{"text": "(*\nConcrete Semantics with Isabelle/HOL\n3. Case Study: IMP Expressions\n*)\n\ntheory \"imp_stack_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 \"Stack Machine\"\n(*********************************************)\n\ntype_synonym stack = \"val list\"\n\ndatatype instr = LOADI val | LOAD vname | ADD\n\nabbreviation \"hd2 xs == hd(tl xs)\"\nabbreviation \"tl2 xs == 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\nvalue \"exec [LOADI 5, LOAD ''y'', ADD] <''x'' := 42, ''y'' := 43> [50]\" (* [48, 50] *)\n\nlemma exec_append [simp] : \"exec (is1 @ is2) s stk = exec is2 s (exec is1 s stk)\"\n  apply (induction is1 arbitrary: stk)\n   apply auto\n  done\n\n(*********************************************)\nsubsection \"Compilation\"\n(*********************************************)\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  (* \"[LOAD ''x'', LOADI 1, ADD, LOAD ''z'', ADD]\" *)\n\ntheorem exec_comp : \"exec (comp a) s stk = aval a s # stk\"\n  apply (induction a arbitrary: stk)\n    apply auto\n  done\n\nend\n", "meta": {"author": "suharahiromichi", "repo": "isabelle", "sha": "9c4969e67b9cbbf87edfc926d609c446c8d71824", "save_path": "github-repos/isabelle/suharahiromichi-isabelle", "path": "github-repos/isabelle/suharahiromichi-isabelle/isabelle-9c4969e67b9cbbf87edfc926d609c446c8d71824/cs/imp_stack_compiler.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473713594991, "lm_q2_score": 0.8596637577007394, "lm_q1q2_score": 0.7499254192832694}}
{"text": "subsection \\<open>Binomial Coefficient is Diophantine\\<close>\n\ntheory Binomial_Coefficient\n  imports Digit_Function\nbegin\n\nlemma bin_coeff_diophantine:\n  shows \"c = a choose b \\<longleftrightarrow> (\\<exists>u.(u = 2^(Suc a) \\<and> c = nth_digit ((u+1)^a) b u))\"\nproof-\n  have \"(u + 1)^a = (\\<Sum>k\\<le>a. (a choose k) * u ^ k)\" for u\n    using binomial[of u 1 a] by auto\n  moreover have \"a choose k < 2 ^ Suc a\" for k\n    using binomial_le_pow2[of a k] by (simp add: le_less_trans)\n  ultimately have \"nth_digit (((2 ^ Suc a) + 1)^a) b (2 ^ Suc a) = a choose b\" \n    using nth_digit_gen_power_series[of \"\\<lambda>k.(a choose k)\" a a b] by (simp add: atLeast0AtMost)\n  then show ?thesis by auto\nqed\n\ndefinition binomial_coefficient (\"[_ = _ choose _]\" 1000)\n  where \"[A = B choose C] \\<equiv> (TERNARY (\\<lambda>a b c. a = b choose c) A B C)\"\n\nlemma binomial_coefficient_dioph[dioph]:\n  fixes A B C :: polynomial\n  defines \"DR \\<equiv> [C = A choose B]\"\n  shows \"is_dioph_rel DR\"\nproof -\n  define A' B' C' where pushed_def:\n    \"A' \\<equiv> (push_param A 2)\" \"B' \\<equiv> (push_param B 2)\" \"C' \\<equiv> (push_param C 2)\"\n\n  (* Param 0 = u = 2^(a + 1), Param 1 = (u+1)^a *)\n  define DS where \"DS \\<equiv> [\\<exists>2] [Param 0 = Const 2 ^ (A' [+] \\<^bold>1)]\n                              [\\<and>] [Param 1 = (Param 0 [+] \\<^bold>1) ^ A']\n                              [\\<and>] [C' = Digit (Param 1) B' (Param 0)]\"\n\n  have \"eval DS a = eval DR a\" for a\n  proof -\n    have \"eval DS a = (peval C a = nth_digit ((2 ^ Suc (peval A a) + 1)^ peval A a)\n                                                      (peval B a) (2 ^ Suc (peval A a)))\"\n      unfolding DS_def defs pushed_def apply (auto simp add: push_push)\n      apply (rule exI[of _ \"[2 * 2 ^ peval A a, Suc (2 * 2 ^ peval A a) ^ peval A a]\"])\n      apply (auto simp add: push_push push_list_eval)\n      by (metis (mono_tags, lifting) Suc_lessI mult_pos_pos n_not_Suc_n\n                numeral_2_eq_2 one_eq_mult_iff pos2 zero_less_power)\n\n    then show ?thesis\n      unfolding DR_def binomial_coefficient_def defs by (simp add: bin_coeff_diophantine)\n  qed\n\n  moreover have \"is_dioph_rel DS\"\n    unfolding DS_def by (auto simp: dioph)\n\n  ultimately show ?thesis\n    by (auto simp: is_dioph_rel_def)\nqed\n\ndeclare binomial_coefficient_def[defs]\n\n\ntext \\<open>odd function is diophantine\\<close>\n\nlemma odd_dioph_repr:\n  fixes a :: nat\n  shows \"odd a \\<longleftrightarrow> (\\<exists>x::nat. a = 2*x + 1)\"\n  by (meson dvd_triv_left even_plus_one_iff oddE)\n\ndefinition odd_lift (\"ODD _\" [999] 1000)\n  where \"ODD A \\<equiv> (UNARY (odd) A)\"\n\nlemma odd_dioph[dioph]:\n  fixes A\n  defines \"DR \\<equiv> (ODD A)\"\n  shows \"is_dioph_rel DR\"\nproof -\n  define DS where \"DS \\<equiv> [\\<exists>] (push_param A 1) [=] Const 2 [*] Param 0 [+] Const 1\"\n\n  have \"eval DS a = eval DR a\" for a\n    unfolding DS_def DR_def odd_lift_def defs using push_push1 by (simp add: odd_dioph_repr push0)\n\n  moreover have \"is_dioph_rel DS\"\n    unfolding DS_def by (auto simp: dioph)\n\n  ultimately show ?thesis\n    by (auto simp: is_dioph_rel_def)\nqed\n\ndeclare odd_lift_def[defs]\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/DPRM_Theorem/Diophantine/Binomial_Coefficient.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505428129514, "lm_q2_score": 0.8289388146603365, "lm_q1q2_score": 0.7498999486411979}}
{"text": "section \\<open>Signed Modulo Operation\\<close>\n\ntheory Signed_Modulo\n  imports \n    Berlekamp_Zassenhaus.Poly_Mod\n    Sqrt_Babylonian.Sqrt_Babylonian_Auxiliary\nbegin\n\ntext \\<open>The upcoming definition of symmetric modulo \n  is different to the HOL-Library-Signed\\_Division.smod, since\n  here the modulus will be in range $\\{-m/2,...,m/2\\}$, \n  whereas there -1 symmod m = m - 1.\n\n  The advantage of have range $\\{-m/2,...,m/2\\}$ is that small negative\n  numbers are represented by small numbers.\n\n  One limitation is that the symmetric modulo is only working properly,\n  if the modulus is a positive number.\\<close>\n\ndefinition sym_mod :: \"int \\<Rightarrow> int \\<Rightarrow> int\" (infixl \"symmod\" 70) where\n  \"sym_mod x y = poly_mod.inv_M y (x mod y)\"\n\nlemma sym_mod_code[code]: \"sym_mod x y = (let m = x mod y\n   in if m + m \\<le> y then m else m - y)\" \n  unfolding sym_mod_def poly_mod.inv_M_def Let_def ..\n\nlemma sym_mod_zero[simp]: \"n symmod 0 = n\" \"n > 0 \\<Longrightarrow> 0 symmod n = 0\"\n  unfolding sym_mod_def poly_mod.inv_M_def by auto\n\nlemma sym_mod_range:\n  \\<open>x symmod y \\<in> {- ((y - 1) div 2) .. y div 2}\\<close> if \\<open>y > 0\\<close>\nproof -\n  from that have \\<open>x mod y < y\\<close>\n    by (rule pos_mod_bound)\n  then have \\<open>x mod y - y < 0\\<close>\n    by simp\n  moreover from that have \\<open>- ((y - 1) div 2) \\<le> 0\\<close> \\<open>0 \\<le> x mod y\\<close>\n    by simp_all\n  then have \\<open>- ((y - 1) div 2) \\<le> x mod y\\<close>\n    by (rule order_trans)\n  ultimately show ?thesis\n    by (auto simp add: sym_mod_def poly_mod.inv_M_def)\nqed\n\ntext \\<open>The range is optimal in the sense that exactly y elements can be represented.\\<close>\nlemma card_sym_mod_range: \"y > 0 \\<Longrightarrow> card {- ((y - 1) div 2) .. y div 2} = y\" \n  by simp\n\nlemma sym_mod_abs: \"y > 0 \\<Longrightarrow> \\<bar>x symmod y\\<bar> < y\"\n  \"y \\<ge> 1 \\<Longrightarrow> \\<bar>x symmod y\\<bar> \\<le> y div 2\"\n  using sym_mod_range[of y x] by auto\n\nlemma sym_mod_sym_mod[simp]: \"x symmod y symmod y = x symmod (y :: int)\" \n  unfolding sym_mod_def using poly_mod.M_def poly_mod.M_inv_M_id by auto\n\nlemma sym_mod_diff_eq: \"(a symmod c - b symmod c) symmod c = (a - b) symmod c\" \n  unfolding sym_mod_def\n  by (metis mod_diff_cong mod_mod_trivial poly_mod.M_def poly_mod.M_inv_M_id)\n\nlemma sym_mod_sym_mod_cancel: \"c dvd b \\<Longrightarrow> a symmod b symmod c = a symmod c\" \n  using mod_mod_cancel[of c b] unfolding sym_mod_def\n  by (metis poly_mod.M_def poly_mod.M_inv_M_id)\n\nlemma sym_mod_diff_right_eq: \"(a - b symmod c) symmod c = (a - b) symmod c\" \n  using sym_mod_diff_eq by (metis sym_mod_sym_mod)\n\nlemma sym_mod_mult_right_eq: \"a * (b symmod c) symmod c = a * b symmod c\" \n  unfolding sym_mod_def by (metis poly_mod.M_def poly_mod.M_inv_M_id mod_mult_right_eq)\n\nlemma dvd_imp_sym_mod_0 [simp]:\n  \"b symmod a = 0\" if \"a > 0\" \"a dvd b\"\n  unfolding sym_mod_def poly_mod.inv_M_def using that by simp\n\nlemma sym_mod_0_imp_dvd [dest!]:\n  \"b dvd a\" if \"a symmod b = 0\"\n  using that apply (simp add: sym_mod_def poly_mod.inv_M_def not_le split: if_splits)\n  using pos_mod_bound [of b a] apply auto\n  done\n\ndefinition sym_div :: \"int \\<Rightarrow> int \\<Rightarrow> int\" (infixl \"symdiv\" 70) where\n  \"sym_div x y = (let d = x div y; m = x mod y in \n       if m + m \\<le> y then d else d + 1)\"\n\nlemma of_int_mod_integer: \"(of_int (x mod y) :: integer) = (of_int x :: integer) mod (of_int y)\" \n  using integer_of_int_eq_of_int modulo_integer.abs_eq by presburger\n\nlemma sym_div_code[code]: \n  \"sym_div x y = (let yy = integer_of_int y in \n     (case divmod_integer (integer_of_int x) yy\n     of (d, m) \\<Rightarrow> if m + m \\<le> yy then int_of_integer d else (int_of_integer (d + 1))))\"\n  unfolding sym_div_def Let_def divmod_integer_def split\n  apply (rule if_cong, subst of_int_le_iff[symmetric], unfold of_int_add)\n  by (subst (1 2) of_int_mod_integer, auto)\n\nlemma sym_mod_sym_div: assumes y: \"y > 0\" shows \"x symmod y = x - sym_div x y * y\"\nproof -\n  let ?z = \"x - y * (x div y)\" \n  let ?u = \"y * (x div y)\" \n  have \"x = y * (x div y) + x mod y\" using y by simp\n  hence id: \"x mod y = ?z\" by linarith\n  have \"x symmod y = poly_mod.inv_M y ?z\" unfolding sym_mod_def id by auto\n  also have \"\\<dots> = (if ?z + ?z \\<le> y then ?z else ?z - y)\" unfolding poly_mod.inv_M_def ..\n  also have \"\\<dots> = x - (if (x mod y) + (x mod y) \\<le> y then x div y else x div y + 1) * y\" \n    by (simp add: algebra_simps id)\n  also have \"(if (x mod y) + (x mod y) \\<le> y then x div y else x div y + 1) = sym_div x y\" \n    unfolding sym_div_def Let_def ..\n  finally show ?thesis .\nqed\n  \nlemma dvd_sym_div_mult_right [simp]:\n  \"(a symdiv b) * b = a\" if \"b > 0\" \"b dvd a\"\n  using sym_mod_sym_div[of b a] that by simp\n\nlemma dvd_sym_div_mult_left [simp]:\n  \"b * (a symdiv b) = a\" if \"b > 0\" \"b dvd a\"\n  using dvd_sym_div_mult_right[OF that] by (simp add: ac_simps)\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/Modular_arithmetic_LLL_and_HNF_algorithms/Signed_Modulo.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9046505402422645, "lm_q2_score": 0.8289388104343892, "lm_q1q2_score": 0.7498999426872504}}
{"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_times\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\nfun times :: \"Bin => Bin => Bin\" where\n\"times (One) y = y\"\n| \"times (ZeroAnd xs1) y = ZeroAnd (times xs1 y)\"\n| \"times (OneAnd xs12) y = plus (ZeroAnd (times xs12 y)) y\"\n\ntheorem property0 :\n  \"((toNat (times 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/TIP15/TIP15/TIP_bin_times.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505351008906, "lm_q2_score": 0.8289388104343892, "lm_q1q2_score": 0.7498999384253658}}
{"text": "theory Object2\n  imports Main\nbegin\n\nsection \\<open>Datatypes\\<close>\n\ntext \\<open>We begin by defining a datatype as an initial value plus a transition function, which takes a\nverson and argument to a (value', ret-val) tuple. We define a datatype to encapsulate this tuple:\\<close>\n\ndatatype ('v, 'r) write_out = WriteOut 'v 'r\n\nprimrec write_out_value :: \"('v, 'r) write_out \\<Rightarrow> 'v\" where\n\"write_out_value (WriteOut v r) = v\"\n\nprimrec write_out_ret :: \"('v, 'r) write_out \\<Rightarrow> 'r\" where\n\"write_out_ret (WriteOut v r) = r\"\n\ntext \\<open>And a locale which fixes the initial value and transition function w.\\<close>\n\nlocale data_type =\n  fixes init :: \"'v\"\n  and w :: \"'v \\<Rightarrow> 'a \\<Rightarrow> ('v, 'r) write_out\"\nbegin\n\ntext \\<open>Given a sequence of write arguments, we can construct a function which applies those arguments\nin sequence.\\<close>\n\nprimrec apply_args :: \"'v \\<Rightarrow> 'a list \\<Rightarrow> 'v\" where\n\"apply_args v [] = v\" |\n\"apply_args v (a # as) = apply_args (write_out_value (w v a)) as\"\n\ntext \\<open>Some lemmata around apply_args\\<close>\n\nlemma apply_args_Cons: \"apply_args v (a#as) = apply_args (write_out_value (w v a)) as\"\n  by auto\n\ntext \\<open>A database is traceable if, for any version, there exists exactly one sequence of args that\nleads to that version.\\<close>\n\ndefinition is_traceable :: \"bool\" where\n\"is_traceable \\<equiv> \\<forall> args1 args2 . apply_args init args1 = apply_args init args2 \\<longrightarrow> args1 = args2\"\n\nend\n\nlocale traceable_data_type = data_type init w for init w +\n  assumes traceable:\"is_traceable\"\nbegin\n\ntext \\<open>Here, we prove facts about traceable data types.\\<close>\n\nend\n\nsection \\<open>Append-only lists\\<close>\n\ntext \\<open>We begin by showing that list append over lists of naturals can form a data type.\\<close>\n\ndefinition list_append_w :: \"'x list \\<Rightarrow> 'x \\<Rightarrow> ('x list, bool) write_out\" where\n\"list_append_w xs x \\<equiv> WriteOut (xs @ [x]) True\"\n\nvalue \"list_append_w [a, b] c\"\n\ninterpretation list_append: data_type \"[]\" list_append_w .\n\ntext \\<open>We want to show this datatype is traceable. First, we prove that applying a sequence of args\nproduces that list of args itself.\\<close>\n\nvalue \"list_append.apply_args x [a,b]\"\n\nlemma list_append_args_are_value:\"list_append.apply_args [] xs = xs\"\nproof (induct xs)\n  case Nil\n  then show ?case\n    by simp\nnext\n  case (Cons x xs)\n  then show ?case\n    apply (simp add: data_type.apply_args_Cons)\n\nqed\n\ninterpretation list_append_traceable:traceable_data_type \"[]\" \"list_append_w\"\n  using list_append.is_traceable_def traceable_data_type_def\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/Object2.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.904650527388829, "lm_q2_score": 0.8289388040954683, "lm_q1q2_score": 0.7498999262980306}}
{"text": "theory Exercise_2_10\n  imports Main\nbegin\ndatatype tree0 = Tip | Node tree0 tree0\n\nfun nodes :: \"tree0 \\<Rightarrow> nat\" where\n  \"nodes Tip = Suc 0\" |\n  \"nodes (Node l r) = Suc ((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 explode_size: \"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", "meta": {"author": "AlexeyAkhunov", "repo": "isabelle", "sha": "3a46e94f04c64b12f806fe50750a5463786593d9", "save_path": "github-repos/isabelle/AlexeyAkhunov-isabelle", "path": "github-repos/isabelle/AlexeyAkhunov-isabelle/isabelle-3a46e94f04c64b12f806fe50750a5463786593d9/Exercise_2_10.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9334308128813471, "lm_q2_score": 0.8031738034238806, "lm_q1q2_score": 0.7497071762149561}}
{"text": "theory Ex1_5\n  imports Main \nbegin \n\n\n  \nprimrec occurs :: \"'a \\<Rightarrow> 'a list \\<Rightarrow> nat\" where\n  \"occurs _ [] = 0\"|\n  \"occurs val (x # xs) = (if x = val then 1 else 0) + occurs val xs\"\n  \ncorollary helper1 : \"occurs a (xs @ ys) = occurs a xs + occurs a ys\" by (induct xs , simp_all)  \n  \nlemma \"occurs a xs = occurs a (rev xs)\" by (induct xs , simp_all add : helper1)\n    \nlemma \"occurs a xs \\<le> length xs\" by (induct xs, simp_all)\n    \n    \n(*lemma \"occurs a (map f xs) = occurs (f a) xs\" quickcheck *)\n    \nlemma \"a \\<noteq> b \\<Longrightarrow>let f = (\\<lambda>x. if x = a then b else x) in occurs a (map f [a,b]) = occurs (f a) [a,b] \\<Longrightarrow> False\" by simp\n    \nlemma \"occurs a (filter P xs) = occurs (a,True)( zip xs (map P xs))\" by (induct xs ; simp)\n\nlemma \"occurs a (filter P xs) = (if P a then occurs a xs else 0 )\" by (induct xs ; simp)\n    \nprimrec remDups :: \"'a list \\<Rightarrow> 'a list\" where\n  \"remDups [] = []\"|\n  \"remDups (x#xs) = (if occurs x xs > 0 then remDups xs else x # remDups xs)\"\n  \nlemma \"occurs x (remDups xs) = (if occurs x xs \\<ge> 1 then 1 else 0)\" by (induct xs; simp)\n\nprimrec unique :: \"'a list \\<Rightarrow> bool\" where \n  \"unique [] = True\"|\n  \"unique (x#xs) = ((occurs x xs = 0)  \\<and> unique xs)\"\n\nlemma helper2 : \"(occurs x xs = 0) = (occurs x (remDups xs) = 0)\" by (induct xs; auto)\n  \nlemma \"unique (remDups xs)\" \nproof (induct xs)\n  case Nil\n  then show ?case by simp\nnext\n  case (Cons a xs)\n  assume hyp:\"unique (remDups xs)\"\n  show ?case \n  proof (cases \"occurs a xs\")\n    case 0\n    assume a:\"occurs a xs = 0\"\n    have \"unique (remDups (a # xs)) = unique (a # remDups  xs) \" by (simp add : a)\n    also have \"\\<dots> = ((occurs a (remDups xs) = 0) \\<and> unique (remDups xs))\" by simp\n    also have \"\\<dots> = ((occurs a  xs = 0) \\<and> unique (remDups xs))\" by (subst helper2, rule refl)\n    finally show ?thesis using hyp by auto \n  next\n    case (Suc nat)\n    then show ?thesis using hyp by simp \n  qed\nqed\n  \n  \n  \n\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_5.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392909114836, "lm_q2_score": 0.847967764140929, "lm_q1q2_score": 0.7496368209269431}}
{"text": "(*<*)\ntheory Szpilrajn\n  imports Main\nbegin\n  (*>*)\n\n\n\nsection \"Introduction\"\n\n\ntext \\<open>\n  We formalize the Szpilrajn extension theorem~\\cite{Szpilrajn:1930}, also known\nas order-extension principal:\n  Every strict partial order can be extended to strict linear order. \nThis is a formalization of the proof presented in the Wikipedia article~\\cite{wiki}.\n\n\nA strict partial order is a transitive and irreflexive relation:\\<close>\n\n\ndefinition \"strict_partial_order r \\<equiv> trans r \\<and> irrefl r\"\n\nlemma show_strict_partial_order[intro]: \n  assumes \"trans r\" and \"irrefl r\" \n  shows \"strict_partial_order r\"\n  by (simp add: assms strict_partial_order_def)\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\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>A strict linear order has all the properties of a strict partial order, but is also total: \\<close>\n\nlemma strict_linear_order_def: \n  \"strict_linear_order r \\<longleftrightarrow> strict_partial_order r \\<and> total r\"\n  by (simp add: strict_linear_order_on_def strict_partial_order_def)\n\n\nsection \"The Proof\"\n\ntext \\<open>A relation \\<^term>\\<open>r\\<close> is a strict extension of a base relation \\<^term>\\<open>base_r\\<close>\nif \\<^term>\\<open>r\\<close> is a strict partial order and \\<^term>\\<open>r\\<close> includes \\<^term>\\<open>base_r\\<close>:\\<close>\n\ndefinition \"strict_ext base_r r \\<equiv> strict_partial_order r \\<and>  base_r \\<subseteq> r\"\n\ntext \\<open>We start by proving that a strict partial order with two incomparable elements\n\\<^term>\\<open>x\\<close> and \\<^term>\\<open>y\\<close> can be extended to a strict partial order where \\<^term>\\<open>x < y\\<close>. \\<close>\n\nlemma can_extend_partial_order: \n  assumes spo: \"strict_partial_order r\"\n    and no1: \"(x,y) \\<notin> r\"\n    and no2: \"(y,x) \\<notin> r\"\n    and neq: \"x\\<noteq>y\"\n  shows \"strict_ext r ((r \\<union> {(x,y)})\\<^sup>+)\"\n  unfolding strict_ext_def proof (intro conjI show_strict_partial_order)\n  show \"trans ((r \\<union> {(x, y)})\\<^sup>+)\"\n    by simp\n  show \"r \\<subseteq> (r \\<union> {(x, y)})\\<^sup>+\" by auto\n\n  from spo have \"trans r\" and \"irrefl r\" \n    by (auto simp add: strict_partial_order_def)\n\n  show \"irrefl ((r \\<union> {(x, y)})\\<^sup>+)\"\n  proof (clarsimp simp add: acyclic_irrefl[symmetric], intro conjI)\n    show \"acyclic r\"\n      by (simp add: spo strict_partial_order_acyclic)\n    show \"(y, x) \\<notin> r\\<^sup>*\"\n      using \\<open>trans r\\<close> neq no2 rtranclD by fastforce\n  qed  \nqed\n\ntext \\<open>With this, we can start the proof of the Szpilrajn extension theorem.\nFor this we will use a variant of Zorns Lemma, which only considers nonempty chains:\\<close>\n\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 ne: \"r \\<noteq> {}\"\n  shows \"\\<exists>m\\<in>Field r. \\<forall>a\\<in>Field r. (m, a) \\<in> r \\<longrightarrow> a = m\"\nproof -\n  from `r\\<noteq>{}` 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 Szpilrajn:\n  assumes \"strict_partial_order base_r\"\n  shows \"\\<exists>r. strict_linear_order r \\<and> base_r \\<subseteq> r\" \nproof -\n  text \\<open>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>r \\<subseteq> s\\<close>:\\<close>\n\n  define order_of_orders :: \"('a rel) rel\" where order_of_orders_def: \n    \"order_of_orders = {(r,s). r\\<subseteq>s \\<and> strict_ext base_r r \\<and> strict_ext base_r s }\"\n\n  have ord_Field: \"Field order_of_orders = {r. strict_ext base_r r}\"\n    by (auto simp add: Field_def order_of_orders_def)\n\n\n  text \\<open>We now show that this set has a maximum and that any maximum of this set is \n    a strict linear order and as thus is one of the extensions we are looking for.\\<close>\n\n  text \\<open>We begin by showing the existence of a maximal element \\<^term>\\<open>m\\<close> using Zorns Lemma:\\<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\n\n\n    text \\<open>Zorns 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>(\\<subseteq>)\\<close> for the relation:\\<close>\n\n\n\n    show \"Partial_order order_of_orders\"\n      by (auto simp add: order_of_orders_def order_on_defs refl_on_def Field_def trans_def antisym_def)\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      using assms strict_ext_def by (auto simp add: order_of_orders_def)\n    thus \"order_of_orders \\<noteq> {}\" by force\n\n\n    text \\<open>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. \\<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_nonemtpy: \"C \\<noteq> {}\"\n      for C\n    proof (rule bexI[where x=\"\\<Union>C\"])\n\n      text \\<open>Obviously each element in the chain is a strict extension of \\<^term>\\<open>base_r\\<close> by definition\n      and as such it is transitive, irreflexive and extends the base relation.\\<close>\n\n      have r_se: \"strict_ext base_r r\" if \"r \\<in> C\" for r\n        using `r \\<in> C` C_def by (auto simp add: Chains_def order_of_orders_def)\n\n      hence r_trans: \"trans r\" \n        and r_irrefl: \"irrefl r\" \n        and r_extends_base: \"base_r \\<subseteq> r\" \n        if \"r \\<in> C\" for r\n        using that by (auto simp add: strict_ext_def strict_partial_order_def)\n\n      text \\<open>Because a chain is ordered, the union of the chain is also transitive:\\<close>\n\n      have C_ordered: \"r\\<subseteq>s \\<or> s\\<subseteq>r\" if \"r \\<in> C\" and \"s \\<in> C\" for r s\n        using C_def that by (auto simp add: Chains_def order_of_orders_def)\n\n      hence \"trans (\\<Union>C)\"\n        by (simp add: chain_subset_def chain_subset_trans_Union r_trans)\n\n      text \\<open>The other properties also can be transferred from the single relations \n       to the union of the chain.\n       Therefore the union is also a strict extension of \\<^term>\\<open>base_r\\<close>: \\<close>\n\n      moreover have \"irrefl (\\<Union>C)\"\n        using irrefl_def r_irrefl by auto\n\n      moreover have \"base_r \\<subseteq> (\\<Union>C)\" \n        by (simp add: less_eq_Sup r_extends_base that)\n\n      ultimately have \"strict_ext base_r (\\<Union>C)\" \n        by (simp add: show_strict_partial_order strict_ext_def that)\n\n      show \"(\\<Union>C) \\<in> Field order_of_orders\"\n        by (simp add: \\<open>strict_ext base_r (\\<Union> C)\\<close> ord_Field)\n\n      text \\<open>The union is obviously an upper bound for the chain: \\<close>\n      show \"\\<forall>a\\<in>C. (a, \\<Union> C) \\<in> order_of_orders\"\n        by (simp add: Sup_upper \\<open>strict_ext base_r (\\<Union> C)\\<close> order_of_orders_def r_se)\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_se: \"strict_ext base_r max\"\n    using ord_Field by auto\n  hence max_spo: \"strict_partial_order max\"\n    and \"base_r \\<subseteq> max\"\n    using strict_ext_def by auto\n\n\n  text \\<open>We still have to show, that \\<^term>\\<open>max\\<close> is a strict linear order, \n  meaning that it is also a total order: \\<close>\n\n  have \"total max\"\n  proof\n    fix x y :: 'a\n    assume \"x\\<noteq>y\"\n\n\n    show \"(x, y) \\<in> max \\<or> (y, x) \\<in> max\"\n    proof (rule ccontr, auto)\n\n      text \\<open>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$:\\<close>\n\n      assume \"(x, y) \\<notin> max\" and \"(y, x) \\<notin> max\"\n      let ?max' = \"((max \\<union> {(x, y)})\\<^sup>+)\"\n\n      from max_spo `(x, y) \\<notin> max` `(y, x) \\<notin> max` `x\\<noteq>y` \n      have max'_se_max: \"strict_ext max ?max'\" by (rule can_extend_partial_order)\n\n      hence max'_se: \"strict_ext base_r ?max'\"\n        by (meson \\<open>base_r \\<subseteq> max\\<close> strict_ext_def subset_trans)\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'_se by (auto simp add: order_of_orders_def max_se)\n      thus False\n        using FieldI2 \\<open>(x, y) \\<notin> max\\<close> is_max by fastforce\n    qed\n  qed\n\n  with max_spo have \"strict_linear_order max\"\n    by (auto simp add: strict_linear_order_def)\n\n  with \\<open>base_r \\<subseteq> max\\<close>\n  show \"\\<exists>r. strict_linear_order r \\<and> base_r \\<subseteq> r\" by auto\nqed\n\ntext \\<open>As a corollary, we can also show that we can extend any \\<^term>\\<open>acyclic\\<close> relation\nto a strict linear order: \\<close>\n\ncorollary can_extend_acyclic_order_to_strict_linear:\n  assumes \"acyclic base_r\"\n  shows \"\\<exists>r. strict_linear_order r \\<and> base_r \\<subseteq> r\" \nproof -\n  have \"strict_partial_order (base_r\\<^sup>+)\"\n    using acyclic_irrefl assms trans_trancl by blast\n  thus ?thesis\n    by (meson Szpilrajn r_into_trancl' subset_iff)\nqed\n\ntext \\<open>Let us conclude with an example, showing that there exists a strict linear \norder on sets, which includes the subset relation:\\<close>\n\nlemma exists_strict_partial_order_on_sets:\n  shows \"\\<exists>r. strict_linear_order r \\<and> {(x,y). x \\<subset> y} \\<subseteq> r\"\n  using strict_partial_order_subset by (rule Szpilrajn)\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/Szpilrajn/Szpilrajn.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8840392909114836, "lm_q2_score": 0.8479677622198946, "lm_q1q2_score": 0.7496368192286731}}
{"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\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 (op ` 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 f \\<equiv> inj_on f UNIV\"\n\nabbreviation (input) surj :: \"('a \\<Rightarrow> 'b) \\<Rightarrow> bool\"\n  where \"surj f \\<equiv> range f = UNIV\"\n\nabbreviation \"bij f \\<equiv> bij_betw f UNIV UNIV\"\n\nlemma injI: \"(\\<And>x y. f x = f y \\<Longrightarrow> x = y) \\<Longrightarrow> inj f\"\n  unfolding inj_on_def by auto\n\ntheorem range_ex1_eq: \"inj f \\<Longrightarrow> b \\<in> range f \\<longleftrightarrow> (\\<exists>!x. b = f x)\"\n  unfolding inj_on_def by blast\n\nlemma injD: \"inj f \\<Longrightarrow> f x = f y \\<Longrightarrow> x = y\"\n  by (simp add: inj_on_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 (force simp add: inj_on_def)\n\nlemma inj_on_cong: \"(\\<And>a. a \\<in> A \\<Longrightarrow> f a = g a) \\<Longrightarrow> inj_on f A = inj_on g A\"\n  unfolding inj_on_def by auto\n\nlemma inj_on_strict_subset: \"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: \"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 \\<Longrightarrow> f x = f y \\<longleftrightarrow> x = y\"\n  by (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 (\\<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::ab_group_add)\"\n  unfolding bij_betw_def inj_on_def\n  by (force intro: minus_minus [symmetric])\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\" using assms\n    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) = 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 add: 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 add: 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_injI:\n  assumes hyp: \"\\<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>\nproof (rule inj_onI)\n  show \"x = y\" if \"f x = f y\" for x y\n   by (rule linorder_cases) (auto dest: hyp simp: that)\nqed\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 *[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  by (simp add: image_comp [symmetric])\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_def: \"bij f \\<longleftrightarrow> inj f \\<and> surj f\"\n  unfolding bij_betw_def ..\n\nlemma bijI: \"inj f \\<Longrightarrow> surj f \\<Longrightarrow> bij f\"\n  by (simp add: bij_def)\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''\"\n  using assms\nproof (auto simp add: bij_betw_comp_iff)\n  assume *: \"bij_betw (f' \\<circ> f) A A''\"\n  then show \"bij_betw f A A'\"\n    using img\n  proof (auto simp add: bij_betw_def)\n    assume \"inj_on (f' \\<circ> f) A\"\n    then show \"inj_on f A\"\n      using inj_on_imageI2 by blast\n  next\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\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 (auto simp: image_def)\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] show \"\\<exists>b\\<in>B. a = ?g b\" by blast\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 \\<le> 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_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 \\<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_on_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_on_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 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\"\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_on_def by blast\n\nlemma image_set_diff: \"inj f \\<Longrightarrow> f ` (A - B) = f ` A - f ` B\"\n  unfolding inj_on_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\n(*FIXME DELETE*)\nlemma inj_on_image_mem_iff_alt: \"inj_on f B \\<Longrightarrow> A \\<subseteq> B \\<Longrightarrow> f a \\<in> f ` A \\<Longrightarrow> a \\<in> B \\<Longrightarrow> a \\<in> A\"\n  by (blast dest: inj_onD)\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 add: inj_on_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_on_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 (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:\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 auto\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\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 (rule_tac [2] ext)\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 (rule ext) 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 (fastforce 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  unfolding override_on_def by (simp add: fun_eq_iff)\n\nlemma override_on_insert': \"override_on f g (insert x X) = (override_on (f(x:=g x)) g X)\"\n  unfolding override_on_def by (simp add: fun_eq_iff)\n\n\nsubsection \\<open>\\<open>swap\\<close>\\<close>\n\ndefinition swap :: \"'a \\<Rightarrow> 'a \\<Rightarrow> ('a \\<Rightarrow> 'b) \\<Rightarrow> ('a \\<Rightarrow> 'b)\"\n  where \"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]: \"swap a a f = f\"\n  by (simp add: swap_def)\n\nlemma swap_commute: \"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]: \"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]: \"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\"\n  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: \"inj_on f A \\<Longrightarrow> a \\<in> A \\<Longrightarrow> b \\<in> A \\<Longrightarrow> inj_on (swap a b f) A\"\n  by (auto simp add: inj_on_def swap_def)\n\nlemma inj_on_swap_iff [simp]:\n  assumes A: \"a \\<in> A\" \"b \\<in> A\"\n  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  then show \"inj_on f A\" by simp\nnext\n  assume \"inj_on f A\"\n  with A show \"inj_on (swap a b f) A\"\n    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]: \"x \\<in> A \\<Longrightarrow> y \\<in> A \\<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 \\<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  apply (simp add: the_inv_into_def)\n  apply (rule the1I2)\n   apply (blast dest: inj_onD)\n  apply blast\n  done\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  apply (simp add: the_inv_into_def)\n  apply (rule the1I2)\n   apply (blast dest: inj_onD)\n  apply blast\n  done\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  apply (erule subst)\n  apply (erule the_inv_into_f_f)\n  apply assumption\n  done\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\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:\n  assumes \"inj f\"\n  shows \"the_inv f (f x) = x\"\n  using assms UNIV_I by (rule the_inv_into_f_f)\n\n\nsubsection \\<open>Cantor's Paradox\\<close>\n\ntheorem Cantors_paradox: \"\\<nexists>f. f ` A = Pow A\"\nproof\n  assume \"\\<exists>f. f ` A = Pow A\"\n  then obtain f where f: \"f ` A = Pow A\" ..\n  let ?X = \"{a \\<in> A. a \\<notin> f a}\"\n  have \"?X \\<in> Pow A\" by blast\n  then have \"?X \\<in> f ` A\" by (simp only: f)\n  then obtain x where \"x \\<in> A\" and \"f x = ?X\" by blast\n  then show False by blast\nqed\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 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 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 \"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\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": "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/Fun.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677737461007, "lm_q2_score": 0.8840392710530071, "lm_q1q2_score": 0.7496368125789441}}
{"text": "(*  \n    Title:      Determinants2.thy\n    Author:     Jose Divas\u00f3n <jose.divasonm at unirioja.es>\n    Author:     Jes\u00fas 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 $ (Transposition.transpose i j) a)\"\n    unfolding interchange_rows_def Transposition.transpose_def by vector\n  hence \"det(interchange_rows A i j) = det(\\<chi> a. A$(Transposition.transpose i j) a)\" by simp\n  also have \"... = of_int (sign (Transposition.transpose i j)) * det A\" by (rule det_permute_rows[of \"Transposition.transpose i j\" 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 - \n  have \"(interchange_columns A i j) = (\\<chi> a b. A $ a $ (Transposition.transpose i j) b)\"\n    unfolding interchange_columns_def Transposition.transpose_def by vector\nhence \"det(interchange_columns A i j) = det(\\<chi> a b. A $ a $ (Transposition.transpose i j) b)\" by simp\nalso have \"... = of_int (sign (Transposition.transpose i j)) * det A\" by (rule det_permute_columns[of \"Transposition.transpose i j\" 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 (opaque_lifting, 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": "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/Determinants2.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9019206844384594, "lm_q2_score": 0.8311430499496096, "lm_q1q2_score": 0.7496251084768206}}
{"text": "theory GabrielaLimonta\nimports Main \"~~/src/HOL/IMP/Star\"\nbegin\n\nsubsection \"Expressions\"\n\ndatatype val = Iv int | Bv bool\n\ntype_synonym vname = string\ntype_synonym state = \"vname \\<Rightarrow> val\"\n\ndatatype exp =  N int | V vname | Plus exp exp |\n  Bc bool | Not exp | And exp exp | Less exp exp\n\ninductive eval :: \"exp \\<Rightarrow> state \\<Rightarrow> val \\<Rightarrow> bool\" where\n\"eval (N i) s (Iv i)\" |\n\"eval (V x) s (s x)\" |\n\"eval a1 s (Iv i1) \\<Longrightarrow> eval a2 s (Iv i2)\n \\<Longrightarrow> eval (Plus a1 a2) s (Iv(i1+i2))\" |\n\"eval (Bc v) s (Bv v)\" |\n\"eval b s (Bv bv) \\<Longrightarrow> eval (Not b) s (Bv(\\<not> bv))\" |\n\"eval b1 s (Bv bv1) \\<Longrightarrow> eval b2 s (Bv bv2) \\<Longrightarrow> eval (And b1 b2) s (Bv(bv1 & bv2))\" |\n\"eval a1 s (Iv i1) \\<Longrightarrow> eval a2 s (Iv i2) \\<Longrightarrow> eval (Less a1 a2) s (Bv(i1 < i2))\"\n\ninductive_cases [elim!]:\n  \"eval (N i) s v\"\n  \"eval (V x) s v\"\n  \"eval (Plus a1 a2) s v\"\n  \"eval (Bc b) s v\"\n  \"eval (Not b) s v\"\n  \"eval (And b1 b2) s v\"\n  \"eval (Less a1 a2) s v\"\n\nsubsection \"Syntax of Commands\"\n(* a copy of Com.thy - keep in sync! *)\n\ndatatype\n  com = SKIP \n      | Assign vname exp       (\"_ ::= _\" [1000, 61] 61)\n      | Seq    com  com         (\"_;; _\"  [60, 61] 60)\n      | If     exp com com     (\"IF _ THEN _ ELSE _\"  [0, 0, 61] 61)\n      | While  exp com         (\"WHILE _ DO _\"  [0, 61] 61)\n\n\nsubsection \"Small-Step Semantics of Commands\"\n\ninductive\n  small_step :: \"(com \\<times> state) \\<Rightarrow> (com \\<times> state) \\<Rightarrow> bool\" (infix \"\\<rightarrow>\" 55)\nwhere\nAssign:  \"eval a s v \\<Longrightarrow> (x ::= a, s) \\<rightarrow> (SKIP, s(x := v))\" |\n\nSeq1:   \"(SKIP;;c,s) \\<rightarrow> (c,s)\" |\nSeq2:   \"(c1,s) \\<rightarrow> (c1',s') \\<Longrightarrow> (c1;;c2,s) \\<rightarrow> (c1';;c2,s')\" |\n\nIfTrue:  \"eval b s (Bv True) \\<Longrightarrow> (IF b THEN c1 ELSE c2,s) \\<rightarrow> (c1,s)\" |\nIfFalse: \"eval b s (Bv False) \\<Longrightarrow> (IF b THEN c1 ELSE c2,s) \\<rightarrow> (c2,s)\" |\n\nWhile:   \"(WHILE b DO c,s) \\<rightarrow> (IF b THEN c;; WHILE b DO c ELSE SKIP,s)\"\n\nlemmas small_step_induct = small_step.induct[split_format(complete)]\n\nsubsection \"The Type System\"\n\ndatatype ty = Ity | Bty\n\ntype_synonym tyenv = \"vname \\<Rightarrow> ty\"\n\ninductive etyping :: \"tyenv \\<Rightarrow> exp \\<Rightarrow> ty \\<Rightarrow> bool\"\n  (\"(1_/ \\<turnstile>/ (_ :/ _))\" [50,0,50] 50)\nwhere\nIc_ty: \"\\<Gamma> \\<turnstile> N i : Ity\" |\nV_ty: \"\\<Gamma> \\<turnstile> V x : \\<Gamma> x\" |\nPlus_ty: \"\\<Gamma> \\<turnstile> a1 : Ity \\<Longrightarrow> \\<Gamma> \\<turnstile> a2 : Ity \\<Longrightarrow> \\<Gamma> \\<turnstile> Plus a1 a2 : Ity\" |\nB_ty: \"\\<Gamma> \\<turnstile> Bc v : Bty\" |\nNot_ty: \"\\<Gamma> \\<turnstile> b : Bty \\<Longrightarrow> \\<Gamma> \\<turnstile> Not b : Bty\" |\nAnd_ty: \"\\<Gamma> \\<turnstile> b1 : Bty \\<Longrightarrow> \\<Gamma> \\<turnstile> b2 : Bty \\<Longrightarrow> \\<Gamma> \\<turnstile> And b1 b2 : Bty\" |\nLess_ty: \"\\<Gamma> \\<turnstile> a1 : Ity \\<Longrightarrow> \\<Gamma> \\<turnstile> a2 : Ity \\<Longrightarrow> \\<Gamma> \\<turnstile> Less a1 a2 : Bty\"\n\ninductive ctyping :: \"tyenv \\<Rightarrow> com \\<Rightarrow> bool\" (infix \"\\<turnstile>\" 50) where\nSkip_ty: \"\\<Gamma> \\<turnstile> SKIP\" |\nAssign_ty: \"\\<Gamma> \\<turnstile> a : \\<Gamma>(x) \\<Longrightarrow> \\<Gamma> \\<turnstile> x ::= a\" |\nSeq_ty: \"\\<Gamma> \\<turnstile> c1 \\<Longrightarrow> \\<Gamma> \\<turnstile> c2 \\<Longrightarrow> \\<Gamma> \\<turnstile> c1;;c2\" |\nIf_ty: \"\\<Gamma> \\<turnstile> b : Bty \\<Longrightarrow> \\<Gamma> \\<turnstile> c1 \\<Longrightarrow> \\<Gamma> \\<turnstile> c2 \\<Longrightarrow> \\<Gamma> \\<turnstile> IF b THEN c1 ELSE c2\" |\nWhile_ty: \"\\<Gamma> \\<turnstile> b : Bty \\<Longrightarrow> \\<Gamma> \\<turnstile> c \\<Longrightarrow> \\<Gamma> \\<turnstile> WHILE b DO c\"\n\ninductive_cases [elim!]:\n  \"\\<Gamma> \\<turnstile> x ::= a\"  \"\\<Gamma> \\<turnstile> c1;;c2\"\n  \"\\<Gamma> \\<turnstile> IF b THEN c1 ELSE c2\"\n  \"\\<Gamma> \\<turnstile> WHILE b DO c\"\n\nsubsection \"Well-typed Programs Do Not Get Stuck\"\n\nfun type :: \"val \\<Rightarrow> ty\" where\n\"type (Iv i) = Ity\" |\n\"type (Bv r) = Bty\"\n\nlemma type_eq_Ity[simp]: \"type v = Ity \\<longleftrightarrow> (\\<exists>i. v = Iv i)\"\nby (cases v) simp_all\n\nlemma type_eq_Bty[simp]: \"type v = Bty \\<longleftrightarrow> (\\<exists>r. v = Bv r)\"\nby (cases v) simp_all\n\ndefinition styping :: \"tyenv \\<Rightarrow> state \\<Rightarrow> bool\" (infix \"\\<turnstile>\" 50)\nwhere \"\\<Gamma> \\<turnstile> s  \\<longleftrightarrow>  (\\<forall>x. type (s x) = \\<Gamma> x)\"\n\nlemma epreservation:\n  \"\\<Gamma> \\<turnstile> a : \\<tau> \\<Longrightarrow> eval a s v \\<Longrightarrow> \\<Gamma> \\<turnstile> s \\<Longrightarrow> type v = \\<tau>\"\n  apply (induction rule: etyping.induct)\n  apply (auto intro: etyping.intros)\n  by (metis styping_def)\n\nlemma eprogress: \"\\<Gamma> \\<turnstile> a : \\<tau> \\<Longrightarrow> \\<Gamma> \\<turnstile> s \\<Longrightarrow> \\<exists>v. eval a s v\"\n  apply (induction rule: etyping.induct)\n  apply (auto intro: eval.intros)\n  apply (metis (full_types) epreservation eval.intros(3) type_eq_Ity)\n  apply (metis epreservation eval.intros(5) type_eq_Bty)\n  apply (metis epreservation eval.intros(6) type_eq_Bty)\n  by (metis (full_types) epreservation eval.intros(7) type_eq_Ity)\n\ntheorem progress:\n  \"\\<Gamma> \\<turnstile> c \\<Longrightarrow> \\<Gamma> \\<turnstile> s \\<Longrightarrow> c \\<noteq> SKIP \\<Longrightarrow> \\<exists>cs'. (c,s) \\<rightarrow> cs'\"\n  apply (induction rule: ctyping.induct)\n  apply (auto intro: ctyping.intros)\n  apply (metis Assign eprogress)\n  apply (metis Seq1 Seq2)\nsorry\n\ntheorem styping_preservation:\n  \"(c,s) \\<rightarrow> (c',s') \\<Longrightarrow> \\<Gamma> \\<turnstile> c \\<Longrightarrow> \\<Gamma> \\<turnstile> s \\<Longrightarrow> \\<Gamma> \\<turnstile> s'\"\n  apply (induction rule: small_step_induct)\n  apply (auto intro: small_step.intros)\n  sorry\n\ntheorem ctyping_preservation:\n  \"(c,s) \\<rightarrow> (c',s') \\<Longrightarrow> \\<Gamma> \\<turnstile> c \\<Longrightarrow> \\<Gamma> \\<turnstile> c'\"\n  apply (induction rule: small_step_induct)\n  apply (auto intro: small_step.intros)\n  by (auto intro: ctyping.intros)\n\nabbreviation small_steps :: \"com * state \\<Rightarrow> com * state \\<Rightarrow> bool\" (infix \"\\<rightarrow>*\" 55)\nwhere \"x \\<rightarrow>* y == star small_step x y\"\n\ntheorem type_sound:\n  \"(c,s) \\<rightarrow>* (c',s') \\<Longrightarrow> \\<Gamma> \\<turnstile> c \\<Longrightarrow> \\<Gamma> \\<turnstile> s \\<Longrightarrow> c' \\<noteq> SKIP\n   \\<Longrightarrow> \\<exists>cs''. (c',s') \\<rightarrow> cs''\"\noops\n\n\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/Exercise8/GabrielaLimonta.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.901920681802153, "lm_q2_score": 0.8311430520409024, "lm_q1q2_score": 0.7496251081718531}}
{"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\nheader {* Functions *}\n\ntheory Relation_Algebra_Functions\n  imports Relation_Algebra_Vectors Relation_Algebra_Tests\nbegin\n\nsubsection {* Functions *}\n\ntext {* This section collects the most important properties of functions. Most\nof them can be found in the books by Maddux and by Schmidt and Str\\\"ohlein. The\nmain material is on partial and total functions, injections, surjections,\nbijections. *}\n\n(* Perhaps this material should be reorganised so that related theorems are\ngrouped together ... *)\n\ncontext relation_algebra\nbegin\n\ndefinition is_p_fun :: \"'a \\<Rightarrow> bool\"\n  where \"is_p_fun x \\<equiv> x\\<^sup>\\<smile> ; x \\<le> 1'\"\n\ndefinition is_total :: \"'a \\<Rightarrow> bool\"\n  where \"is_total x \\<equiv> 1' \\<le> x ; x\\<^sup>\\<smile>\"\n\ndefinition is_map :: \"'a \\<Rightarrow> bool\"\n  where \"is_map x \\<equiv> is_p_fun x \\<and> is_total x\"\n\ndefinition is_inj :: \"'a \\<Rightarrow> bool\"\n  where \"is_inj x \\<equiv> x ; x\\<^sup>\\<smile> \\<le> 1'\"\n\ndefinition is_sur :: \"'a \\<Rightarrow> bool\"\n  where \"is_sur x \\<equiv> 1' \\<le> x\\<^sup>\\<smile> ; x\"\n\ntext {* We distinguish between partial and total bijections. As usual we call\nthe latter just bijections. *}\n\ndefinition is_p_bij :: \"'a \\<Rightarrow> bool\"\n  where \"is_p_bij x \\<equiv> is_p_fun x \\<and> is_inj x \\<and> is_sur x\"\n\ndefinition is_bij :: \"'a \\<Rightarrow> bool\"\n  where \"is_bij x \\<equiv> is_map x \\<and> is_inj x \\<and> is_sur x\"\n\ntext {* Our first set of lemmas relates the various concepts. *}\n\nlemma inj_p_fun: \"is_inj x \\<longleftrightarrow> is_p_fun (x\\<^sup>\\<smile>)\"\nby (metis conv_invol is_inj_def is_p_fun_def)\n\nlemma p_fun_inj: \"is_p_fun x \\<longleftrightarrow> is_inj (x\\<^sup>\\<smile>)\"\nby (metis conv_invol inj_p_fun)\n\nlemma sur_total: \"is_sur x \\<longleftrightarrow> is_total (x\\<^sup>\\<smile>)\"\nby (metis conv_invol is_sur_def is_total_def)\n\nlemma total_sur: \"is_total x \\<longleftrightarrow> is_sur (x\\<^sup>\\<smile>)\"\nby (metis conv_invol sur_total)\n\nlemma bij_conv: \"is_bij x  \\<longleftrightarrow> is_bij (x\\<^sup>\\<smile>)\"\nby (metis is_bij_def inj_p_fun is_map_def p_fun_inj sur_total total_sur)\n\ntext {* Next we show that tests are partial injections. *}\n\nlemma test_is_inj_fun: \"is_test x \\<Longrightarrow> (is_p_fun x \\<and> is_inj x)\"\nby (metis is_inj_def p_fun_inj test_comp test_eq_conv is_test_def)\n\ntext {* Next we show composition properties. *}\n\nlemma p_fun_comp:\n  assumes \"is_p_fun x\" and \"is_p_fun y\"\n  shows \"is_p_fun (x ; y)\"\nproof (unfold is_p_fun_def)\n  have \"(x ; y)\\<^sup>\\<smile> ; x ; y = y\\<^sup>\\<smile> ; x\\<^sup>\\<smile> ; x ; y\"\n    by (metis conv_contrav mult.assoc)\n  also have \"... \\<le> y\\<^sup>\\<smile> ; y\"\n    by (metis assms(1) is_p_fun_def mult_double_iso mult.right_neutral mult.assoc)\n  finally show \"(x ; y)\\<^sup>\\<smile> ; (x ; y) \\<le> 1'\"\n    by (metis assms(2) order_trans is_p_fun_def mult.assoc)\nqed\n\nlemma p_fun_mult_var: \"x\\<^sup>\\<smile> ; x \\<le> 1' \\<Longrightarrow> (x \\<cdot> y)\\<^sup>\\<smile> ; (x \\<cdot> y) \\<le> 1'\"\nby (metis conv_times inf_le1 mult_isol_var order_trans)\n\nlemma inj_comp:\n  assumes \"is_inj x\" and \"is_inj y\"\n  shows \"is_inj (x ; y)\"\nby (metis assms conv_contrav inj_p_fun p_fun_comp)\n\nlemma inj_mult_var: \"x\\<^sup>\\<smile> ; x \\<le> 1' \\<Longrightarrow> (x \\<cdot> y)\\<^sup>\\<smile> ; (x \\<cdot> y) \\<le> 1'\"\nby (metis p_fun_mult_var)\n\nlemma total_comp:\n  assumes \"is_total x\" and \"is_total y\"\n  shows \"is_total (x ; y)\"\nby (metis assms inf_top_left le_iff_inf mult.assoc mult.right_neutral one_conv ra_2 is_total_def)\n\nlemma total_add_var: \"1' \\<le> x\\<^sup>\\<smile> ; x  \\<Longrightarrow> 1' \\<le> (x + y)\\<^sup>\\<smile> ; (x + y)\"\nby (metis add_ub1 conv_add mult_isol_var order_trans)\n\nlemma sur_comp:\n  assumes \"is_sur x\" and \"is_sur y\"\n  shows \"is_sur (x ; y)\"\nby (metis assms conv_contrav sur_total total_comp)\n\nlemma sur_sum_var: \"1' \\<le> x\\<^sup>\\<smile> ; x \\<Longrightarrow> 1' \\<le> (x + y)\\<^sup>\\<smile> ; (x + y)\"\nby (metis total_add_var)\n\nlemma map_comp:\n  assumes \"is_map x\" and \"is_map y\"\n  shows \"is_map (x ; y)\"\nby (metis assms is_map_def p_fun_comp total_comp)\n\nlemma bij_comp:\n  assumes \"is_bij x\" and \"is_bij y\"\n  shows \"is_bij (x ; y)\"\nby (metis assms is_bij_def inj_comp map_comp sur_comp)\n\ntext {* We now show that (partial) functions, unlike relations, distribute over\nmeets from the left. *}\n\nlemma p_fun_distl: \"is_p_fun x \\<Longrightarrow> x ; (y \\<cdot> z) = x ; y \\<cdot> x ; z\"\nproof -\n  assume \"is_p_fun x\"\n  hence \"x ; (z \\<cdot> ((x\\<^sup>\\<smile> ; x) ; y)) \\<le> x ; (z \\<cdot> y)\"\n    by (metis is_p_fun_def inf_le1 le_infI le_infI2 mult_isol mult_isor mult_onel)\n  hence  \"x ; y \\<cdot> x ; z \\<le> x ; (z \\<cdot> y)\"\n    by (metis inf.commute mult.assoc order_trans modular_1_var)\n  thus \"x ; (y \\<cdot> z) = x ; y \\<cdot> x ; z\"\n    by (metis eq_iff inf.commute le_infI mult_subdistl)\nqed\n\nlemma map_distl: \"is_map x \\<Longrightarrow> x ; (y \\<cdot> z) = x ; y \\<cdot> x ; z\"\nby (metis is_map_def p_fun_distl)\n\ntext {* Next we prove simple properties of functions which arise in equivalent\ndefinitions of those concepts. *}\n\nlemma p_fun_zero: \"is_p_fun x \\<Longrightarrow> x ; y \\<cdot> x ; -y = 0\"\nby (metis annir inf_compl_bot p_fun_distl)\n\nlemma total_one: \"is_total x \\<Longrightarrow> x ; 1 = 1\"\nby (metis conv_invol conv_one inf_top_left le_iff_inf mult.right_neutral one_conv ra_2 is_total_def)\n\nlemma total_1: \"is_total x \\<Longrightarrow> (\\<forall>y. y ; x = 0 \\<longrightarrow> y = 0)\"\nby (metis conv_invol conv_zero inf_bot_left inf_top_left peirce total_one)\n\nlemma surj_one: \"is_sur x \\<Longrightarrow> 1 ; x = 1\"\nby (metis conv_contrav conv_invol conv_one sur_total total_one)\n\nlemma surj_1: \"is_sur x \\<Longrightarrow> (\\<forall>y. x ; y = 0 \\<longrightarrow> y = 0)\"\nby (metis comp_res_aux compl_bot_eq conv_contrav conv_one inf.commute inf_top_right surj_one)\n\nlemma bij_is_maprop:\n  assumes \"is_bij x\" and \"is_map x\"\n  shows \"x\\<^sup>\\<smile> ; x  = 1' \\<and> x ; x\\<^sup>\\<smile> = 1'\"\nby (metis assms is_bij_def eq_iff is_inj_def is_map_def is_p_fun_def is_sur_def is_total_def)\n\ntext{* We now provide alternative definitions for functions. These can be found\nin Schmidt and Str\\\"ohlein's book. *}\n\nlemma p_fun_def_var: \"is_p_fun x \\<longleftrightarrow> x ; -(1') \\<le> -x\"\nby (metis conv_galois_1 double_compl galois_aux inf.commute is_p_fun_def)\n\nlemma total_def_var_1: \"is_total x \\<longleftrightarrow> x ; 1 = 1\"\nby (metis inf_top_right le_iff_inf one_conv total_one is_total_def)\n\nlemma total_def_var_2: \"is_total x \\<longleftrightarrow> -x \\<le> x ; -(1')\"\nby (metis total_def_var_1 distrib_left sup_compl_top mult.right_neutral galois_aux3)\n\nlemma sur_def_var1: \"is_sur x \\<longleftrightarrow> 1 ; x = 1\"\nby (metis conv_contrav conv_one sur_total surj_one total_def_var_1)\n\nlemma sur_def_var2: \"is_sur x \\<longleftrightarrow> -x \\<le> -(1') ; x\"\nby (metis sur_total total_def_var_2 conv_compl conv_contrav conv_e conv_iso)\n\nlemma inj_def_var1: \"is_inj x \\<longleftrightarrow> -(1') ; x \\<le> -x\"\nby (metis conv_galois_2 double_compl galois_aux inf.commute is_inj_def)\n\nlemma is_maprop: \"is_map x \\<longleftrightarrow> x ; -(1') = -x\"\nby (metis eq_iff is_map_def p_fun_def_var total_def_var_2)\n\ntext {* Finally we prove miscellaneous properties of functions. *}\n\nlemma ss_422iii: \"is_p_fun y \\<Longrightarrow> (x \\<cdot> z ; y\\<^sup>\\<smile>) ; y = x ; y \\<cdot> z\"\n(* by (smt antisym comp_assoc inf_commute maddux_17 meet_iso mult_isol mult_oner mult_subdistr_var order_trans is_p_fun_def) *)\nproof (rule antisym)\n  assume \"is_p_fun y\"\n  show \"x ; y \\<cdot> z \\<le> (x \\<cdot> z ; y\\<^sup>\\<smile>) ; y\"\n    by (metis maddux_17)\n  have \"(x \\<cdot> z ; y\\<^sup>\\<smile>) ; y \\<le> x ; y \\<cdot> (z ; (y\\<^sup>\\<smile> ; y))\"\n    by (metis mult_subdistr_var mult.assoc)\n  also have \"\\<dots> \\<le> x ; y \\<cdot> z ; 1'\"\n    by (metis `is_p_fun y` inf_absorb2 inf_le1 le_infI le_infI2 mult_subdistl is_p_fun_def)\n  finally show \"(x \\<cdot> z ; y\\<^sup>\\<smile>) ; y \\<le> x ; y \\<cdot> z\"\n    by (metis mult.right_neutral)\nqed\n\nlemma p_fun_compl: \"is_p_fun x \\<Longrightarrow> x ; -y \\<le> -(x; y)\"\nby (metis annir galois_aux inf.commute inf_compl_bot p_fun_distl)\n\nlemma ss_422v: \"is_p_fun x \\<Longrightarrow> x ; -y = x ; 1 \\<cdot> -(x ; y)\"\nby (metis inf.commute inf_absorb2 inf_top_left maddux_23 p_fun_compl)\n\ntext {* The next property is a Galois connection. *}\n\nlemma ss43iii: \"is_map x \\<longleftrightarrow> (\\<forall>y. x ; -y = -(x ; y))\"\nby (default, metis inf_top_left is_map_def ss_422v total_one, metis is_maprop mult.right_neutral)\n\ntext {* Next we prove a lemma from Schmidt and Str\\\"ohlein's book and some of\nits consequences. We show the proof in detail since the textbook proof uses\nTarski's rule which we omit. *}\n\nlemma ss423: \"is_map x \\<Longrightarrow> y ; x \\<le> z \\<longleftrightarrow> y \\<le> z ; x\\<^sup>\\<smile>\"\nproof\n  assume \"is_map x\" and \"y ; x \\<le> z\"\n  hence \"y \\<le> y ; x ; x\\<^sup>\\<smile>\"\n    by (metis is_map_def mult_1_right mult.assoc mult_isol is_total_def)\n  thus \"y \\<le> z ; x\\<^sup>\\<smile>\"\n    by (metis `y ; x \\<le> z` mult_isor order_trans)\nnext\n  assume \"is_map x\" and \"y \\<le> z ; x\\<^sup>\\<smile>\"\n  hence \"y ; x \\<le> z ; x\\<^sup>\\<smile> ; x\"\n    by (metis mult_isor)\n  also have \"\\<dots> \\<le> z ; 1'\"\n    by (metis `is_map x` is_map_def mult.assoc mult_isol is_p_fun_def)\n  finally show \"y ; x \\<le> z\"\n    by (metis mult_1_right)\nqed\n\nlemma ss424i: \"is_total x \\<longleftrightarrow> (\\<forall>y. -(x ; y) \\<le> x ; -y)\"\nby (metis galois_aux3 distrib_left sup_compl_top total_def_var_1)\n\nlemma ss434ii: \"is_p_fun x \\<longleftrightarrow> (\\<forall>y. x ; -y \\<le> -(x ; y))\"\nby (metis mult.right_neutral p_fun_compl p_fun_def_var)\n\nlemma is_maprop1: \"is_map x \\<Longrightarrow> (y \\<le> x ; z ; x\\<^sup>\\<smile> \\<longleftrightarrow> y ; x \\<le> x ; z)\"\nby (metis ss423)\n\nlemma is_maprop2: \"is_map x \\<Longrightarrow> (y ; x \\<le> x ; z \\<longleftrightarrow> x\\<^sup>\\<smile> ; y; x \\<le> z)\"\nby (default, metis galois_aux2 inf_commute mult.assoc schroeder_1 ss43iii, metis conv_contrav conv_invol conv_iso mult.assoc ss423)\n\nlemma is_maprop3: \"is_map x \\<Longrightarrow> (x\\<^sup>\\<smile> ; y; x \\<le> z \\<longleftrightarrow> x\\<^sup>\\<smile> ; y \\<le> z ; x\\<^sup>\\<smile>)\"\nby (metis ss423)\n\nlemma p_fun_sur_id [simp]:\n  assumes \"is_p_fun x\" and \"is_sur x\"\n  shows \"x\\<^sup>\\<smile> ; x = 1'\"\nby (metis assms eq_iff is_p_fun_def is_sur_def)\n\nlemma total_inj_id [simp]:\n  assumes \"is_total x\" and \"is_inj x\"\n  shows \"x ; x\\<^sup>\\<smile> = 1'\"\nby (metis assms conv_invol inj_p_fun p_fun_sur_id sur_total)\n\nlemma bij_inv_1 [simp]: \"is_bij x \\<Longrightarrow> x ; x\\<^sup>\\<smile> = 1'\"\nby (metis bij_is_maprop is_bij_def)\n\nlemma bij_inv_2 [simp]: \"is_bij x \\<Longrightarrow> x\\<^sup>\\<smile> ; x = 1'\"\nby (metis bij_is_maprop is_bij_def)\n\nlemma bij_inv_comm: \"is_bij x \\<Longrightarrow> x ; x\\<^sup>\\<smile> = x\\<^sup>\\<smile> ; x\"\nby (metis bij_inv_1 bij_inv_2)\n\nlemma is_bijrop: \"is_bij x \\<Longrightarrow> (y = x ; z \\<longleftrightarrow> z = x\\<^sup>\\<smile> ; y)\"\nby (metis bij_inv_1 bij_inv_2 mult.assoc mult.left_neutral)\n\nlemma inj_map_monomorph: \"\\<lbrakk>is_inj x; is_map x\\<rbrakk> \\<Longrightarrow> (\\<forall>y z. y ; x = z ; x \\<longrightarrow> y = z)\"\nby (metis is_map_def mult.assoc mult.right_neutral total_inj_id)\n\nlemma sur_map_epimorph: \"\\<lbrakk>is_sur x; is_map x\\<rbrakk> \\<Longrightarrow> (\\<forall>y z. x ; y = x ; z \\<longrightarrow> y = z)\"\nby (metis eq_iff mult.assoc mult.left_neutral ss423 is_sur_def)\n\nsubsection {* Points and Rectangles *}\n\ntext {* Finally here is a section on points and rectangles. This is only a\nbeginning. *}\n\ndefinition is_point :: \"'a \\<Rightarrow> bool\"\n  where \"is_point x \\<equiv> is_vector x \\<and> is_inj x \\<and> x \\<noteq> 0\"\n\ndefinition is_rectangle :: \"'a \\<Rightarrow> bool\"\n  where \"is_rectangle x \\<equiv> x ; 1 ; x \\<le> x\"\n\nlemma rectangle_eq [simp]: \"is_rectangle x \\<longleftrightarrow> x ; 1 ; x = x\"\nby (metis conv_one dedekind eq_iff inf_top_left mult.assoc one_idem_mult is_rectangle_def)\n\nsubsection {* Antidomain *}\n\ntext{* This section needs to be linked with domain semirings. We essentially\nprove the antidomain semiring axioms. Then we have the abstract properties at\nour disposition. *}\n\ndefinition antidom :: \"'a \\<Rightarrow> 'a\" (\"a\")\n  where \"a x = 1' \\<cdot> (-(x ; 1))\"\n\ndefinition dom :: \"'a \\<Rightarrow> 'a\" (\"d\")\n  where \"d x = a (a x)\"\n\nlemma antidom_test_comp [simp]: \"a x = (x ; 1)\\<^sup>\\<dagger>\"\nby (metis antidom_def test_compl_def)\n\nlemma dom_def_aux: \"d x = 1' \\<cdot> x ; 1\"\nby (metis antidom_test_comp dom_def double_compl inf_top_left mult.left_neutral one_compl ra_1 test_compl_def)\n\nlemma dom_def_aux_var: \"d x = 1' \\<cdot> x ; x\\<^sup>\\<smile>\"\nby (metis dom_def_aux one_conv)\n\nlemma antidom_dom [simp]: \"a (d x) = a x\"\nby (metis antidom_test_comp dom_def_aux inf_top_left mult.left_neutral ra_1)\n\nlemma dom_antidom [simp]: \"d (a x) = a x\"\nby (metis antidom_dom dom_def)\n\nlemma dom_verystrict: \"d x = 0 \\<longleftrightarrow> x = 0\"\nby (metis annil dom_def_aux eq_iff inf_top_left maddux_20 mult.left_neutral ra_1 zero_least)\n\nlemma a_1 [simp]: \"a x ; x = 0\"\nby (metis antidom_test_comp galois_aux2 maddux_20 mult.left_neutral one_compl ra_1 test_compl_def)\n\nlemma a_2: \"a (x ; y) = a (x ; d y)\"\nby (metis antidom_test_comp dom_def_aux inf_top_left mult.assoc mult.left_neutral ra_1)\n\nlemma a_3 [simp]: \"a x + d x = 1'\"\nby (metis antidom_def aux4 dom_def_aux double_compl)\n\nlemma test_domain: \"x = d x \\<longleftrightarrow> x \\<le> 1'\"\napply default\n apply (metis dom_def_aux inf_le1)\napply (metis dom_def_aux inf.commute mult.right_neutral test_1 is_test_def)\ndone\n\ntext {* At this point we have all the necessary ingredients to prove that\nrelation algebras form Boolean domain semirings. However, we omit a formal\nproof since we haven't formalized the latter. *}\n\nlemma dom_one: \"x ; 1 = d x ; 1\"\nby (metis dom_def_aux inf_top_left mult.left_neutral ra_1)\n\nlemma test_dom: \"is_test (d x)\"\nby (metis dom_def_aux inf_le1 is_test_def)\n\nlemma p_fun_dom: \"is_p_fun (d x)\"\nby (metis test_dom test_is_inj_fun)\n\nlemma inj_dom: \"is_inj (d x)\"\nby (metis test_dom test_is_inj_fun)\n\nlemma total_alt_def: \"is_total x \\<longleftrightarrow> (d x) = 1'\"\nby (metis dom_def_aux_var le_iff_inf is_total_def)\n\nend (* relation_algebra *)\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/Relation_Algebra/Relation_Algebra_Functions.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.90192067652954, "lm_q2_score": 0.831143054132195, "lm_q1q2_score": 0.7496251056757374}}
{"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{* Using the introduction rules: *}\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{* A recursive definition of evenness: *}\nfun even :: \"nat \\<Rightarrow> bool\" where\n\"even 0 = True\" |\n\"even (Suc 0) = False\" |\n\"even (Suc(Suc n)) = even n\"\n\ntext{*A simple example of rule induction: *}\nlemma \"ev n \\<Longrightarrow> even n\"\napply(induction rule: ev.induct)\n apply(simp)\napply(simp)\ndone\n\ntext{* An induction on the computation of even: *}\nlemma \"even n \\<Longrightarrow> ev n\"\napply(induction n rule: even.induct)\n  apply (simp add: ev0)\n apply simp\napply(simp add: evSS)\ndone\n\ntext{* No problem with termination because the premises are always smaller\nthan the conclusion: *}\ndeclare ev.intros[simp,intro]\n\ntext{* A shorter proof: *}\nlemma \"even n \\<Longrightarrow> ev n\"\napply(induction n rule: even.induct)\napply(simp_all)\ndone\n\ntext{* The power of arith: *}\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": "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/Inductive_Demo.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206712569267, "lm_q2_score": 0.8311430436757313, "lm_q1q2_score": 0.7496250918625407}}
{"text": "(*  Title:       Countable Ordinals\n\n    Author:      Brian Huffman, 2005\n    Maintainer:  Brian Huffman <brianh at cse.ogi.edu>\n*)\n\nsection \\<open>Inverse Functions\\<close>\n\ntheory OrdinalInverse\nimports OrdinalArith\nbegin\n\nlemma (in normal) oInv_ex: \n  assumes \"F 0 \\<le> a\" shows \"\\<exists>q. F q \\<le> a \\<and> a < F (oSuc q)\"\nproof -\n  have \"a < F z \\<Longrightarrow> (\\<exists>q<z. F q \\<le> a \\<and> a < F (oSuc q))\" for z\n  proof (induction z rule: oLimit_induct)\n    case zero\n    then show ?case\n      using assms by auto\n  next\n    case (suc x)\n    then show ?case\n      by (metis less_oSuc linorder_not_le order_less_trans)\n  next\n    case (lim f)\n    then show ?case\n      by (metis less_oLimitD less_oLimitI oLimit)\n  qed\n  then show ?thesis\n    by (metis increasing oSuc_le_eq_less)\nqed\n\nlemma oInv_uniq:\n  assumes \"mono (F::ordinal \\<Rightarrow> ordinal)\" \"F x \\<le> a\" \"a < F (oSuc x)\" \"F y \\<le> a\" \"a < F (oSuc y)\"\n  shows \"x = y\"\nproof (cases \"x<y\")\n  case True\n  with assms show ?thesis \n    by (meson dual_order.trans leD monoD oSuc_leI)\nnext\n  case False\n  with assms show ?thesis\n    by (meson dual_order.strict_trans2 less_oSucE mono_strict_invE)\nqed\n\ndefinition\n  oInv :: \"(ordinal \\<Rightarrow> ordinal) \\<Rightarrow> ordinal \\<Rightarrow> ordinal\" where\n  \"oInv F a = (if F 0 \\<le> a then (THE x. F x \\<le> a \\<and> a < F (oSuc x)) else 0)\"\n\nlemma (in normal) oInv_bounds: \"F 0 \\<le> a \\<Longrightarrow> F (oInv F a) \\<le> a \\<and> a < F (oSuc (oInv F a))\"\n  by (simp add: oInv_def) (metis (no_types, lifting) theI' mono oInv_ex oInv_uniq)\n\nlemma (in normal) oInv_bound1:\n  \"F 0 \\<le> a \\<Longrightarrow> F (oInv F a) \\<le> a\"\n  by (rule oInv_bounds[THEN conjunct1])\n\nlemma (in normal) oInv_bound2: \"a < F (oSuc (oInv F a))\"\n  by (metis cancel_less linorder_not_le oInv_bounds order.strict_trans ordinal_not_0_less)\n\nlemma (in normal) oInv_equality: \"\\<lbrakk>F x \\<le> a; a < F (oSuc x)\\<rbrakk> \\<Longrightarrow> oInv F a = x\"\n  by (meson mono normal.cancel_le normal_axioms oInv_bound1 oInv_bound2 oInv_uniq ordinal_0_le order_trans)\n\nlemma (in normal) oInv_inverse: \"oInv F (F x) = x\"\n  by (rule oInv_equality, simp_all add: cancel_less)\n\nlemma (in normal) oInv_equality': \"a = F x \\<Longrightarrow> oInv F a = x\"\n  by (simp add: oInv_inverse)\n\nlemma (in normal) oInv_eq_0: \"a \\<le> F 0 \\<Longrightarrow> oInv F a = 0\"\n  by (metis nle_le oInv_def oInv_equality')\n\nlemma (in normal) oInv_less: \"\\<lbrakk>F 0 \\<le> a; a < F z\\<rbrakk> \\<Longrightarrow> oInv F a < z\"\n  using cancel_less oInv_bound1 by fastforce\n\nlemma (in normal) le_oInv: \"F z \\<le> a \\<Longrightarrow> z \\<le> oInv F a\"\n  by (metis cancel_le dual_order.trans le_oSucE linorder_not_less oInv_bound2 order_le_less)\n\nlemma (in normal) less_oInvD: \"x < oInv F a \\<Longrightarrow> F (oSuc x) \\<le> a\"\n  by (metis (no_types) linorder_not_le nle_le oInv_eq_0 oInv_less oSuc_leI ordinal_0_le)\n\nlemma (in normal) oInv_le: \"a < F (oSuc x) \\<Longrightarrow> oInv F a \\<le> x\"\n  by (metis leD less_oInvD nle_le order_le_less)\n\nlemma (in normal) mono_oInv: \"mono (oInv F)\"\nproof\n  fix x y :: ordinal\n  assume \"x \\<le> y\"\n  show \"oInv F x \\<le> oInv F y\"\n  proof (rule linorder_le_cases [of x \"F 0\"])\n    assume \"x \\<le> F 0\" then show ?thesis by (simp add: oInv_eq_0)\n  next\n    assume \"F 0 \\<le> x\" show ?thesis\n      by (rule le_oInv, simp only: \\<open>x \\<le> y\\<close> \\<open>F 0 \\<le> x\\<close> order_trans [OF oInv_bound1])\n  qed\nqed\n\nlemma (in normal) oInv_decreasing: \"F 0 \\<le> x \\<Longrightarrow> oInv F x \\<le> x\"\n  by (meson dual_order.trans increasing oInv_bound1)\n\n\nsubsection \\<open>Division\\<close>\n\ninstantiation ordinal :: modulo\nbegin\n\ndefinition\n  div_ordinal_def:\n   \"x div y = (if 0 < y then oInv ((*) y) x else 0)\"\n\ndefinition\n  mod_ordinal_def: \n   \"x mod y = ((x::ordinal) - y * (x div y))\"\n\ninstance ..\n\nend\n\nlemma ordinal_divI: \"\\<lbrakk>x = y * q + r; r < y\\<rbrakk> \\<Longrightarrow> x div y = (q::ordinal)\"\n  using div_ordinal_def normal.oInv_equality normal_times by auto\n\nlemma ordinal_times_div_le: \"y * (x div y) \\<le> (x::ordinal)\"\n  by (simp add: div_ordinal_def normal.oInv_bound1 normal_times)\n\nlemma ordinal_less_times_div_plus: \"0 < y \\<Longrightarrow> x < y * (x div y) + (y::ordinal)\"\n  by (metis div_ordinal_def normal.oInv_bound2 normal_times ordinal_times_oSuc)\n\nlemma ordinal_modI: \"\\<lbrakk>x = y * q + r; r < y\\<rbrakk> \\<Longrightarrow> x mod y = (r::ordinal)\"\n  by (simp add: mod_ordinal_def ordinal_divI)\n\nlemma ordinal_mod_less: \"0 < y \\<Longrightarrow> x mod y < (y::ordinal)\"\n  by (simp add: mod_ordinal_def ordinal_less_times_div_plus ordinal_times_div_le)\n\nlemma ordinal_div_plus_mod: \"y * (x div y) + (x mod y) = (x::ordinal)\"\n  by (simp add: mod_ordinal_def ordinal_times_div_le)\n\nlemma ordinal_div_less: \"x < y * z \\<Longrightarrow> x div y < (z::ordinal)\"\n  using div_ordinal_def normal.oInv_less normal_times by auto\n\nlemma ordinal_le_div: \"\\<lbrakk>0 < y; y * z \\<le> x\\<rbrakk> \\<Longrightarrow> (z::ordinal) \\<le> x div y\"\n  by (simp add: div_ordinal_def normal.le_oInv normal_times)\n\n\n\nlemma ordinal_div_monoL: \"x \\<le> x' \\<Longrightarrow> x div y \\<le> x' div (y::ordinal)\"\n  by (erule monoD[OF ordinal_mono_div])\n\nlemma ordinal_div_decreasing: \"(x::ordinal) div y \\<le> x\"\n  by (simp add: div_ordinal_def normal.oInv_decreasing normal_times)\n\nlemma ordinal_div_0: \"x div 0 = (0::ordinal)\"\n  by (simp add: div_ordinal_def)\n\nlemma ordinal_mod_0: \"x mod 0 = (x::ordinal)\"\n  by (simp add: mod_ordinal_def)\n\n\nsubsection \\<open>Derived properties of division\\<close>\n\nlemma ordinal_div_1 [simp]: \"x div oSuc 0 = x\"\n  using ordinal_divI by force\n\nlemma ordinal_mod_1 [simp]: \"x mod oSuc 0 = 0\"\n  by (simp add: mod_ordinal_def)\n\nlemma ordinal_div_self [simp]: \"0 < x \\<Longrightarrow> x div x = (1::ordinal)\"\n  by (metis ordinal_divI ordinal_one_def ordinal_plus_0 ordinal_times_1)\n\nlemma ordinal_mod_self [simp]: \"x mod x = (0::ordinal)\"\n  by (metis ordinal_modI ordinal_mod_0 ordinal_neq_0 ordinal_plus_0 ordinal_times_1)\n\nlemma ordinal_div_greater [simp]: \"x < y \\<Longrightarrow> x div y = (0::ordinal)\"\n  by (simp add: ordinal_divI)\n\nlemma ordinal_mod_greater [simp]: \"x < y \\<Longrightarrow> x mod y = (x::ordinal)\"\n  by (simp add: mod_ordinal_def)\n\nlemma ordinal_0_div [simp]: \"0 div x = (0::ordinal)\"\n  by (metis div_ordinal_def ordinal_div_greater)\n\nlemma ordinal_0_mod [simp]: \"0 mod x = (0::ordinal)\"\n  by (simp add: mod_ordinal_def)\n\nlemma ordinal_1_dvd [simp]: \"oSuc 0 dvd x\"\n  by (simp add: dvdI)\n\nlemma ordinal_dvd_mod: \"y dvd x = (x mod y = (0::ordinal))\"\n  by (metis dvd_def ordinal_0_times ordinal_div_plus_mod ordinal_modI ordinal_mod_0 ordinal_neq_0 ordinal_plus_0)\n\nlemma ordinal_dvd_times_div: \"y dvd x \\<Longrightarrow> y * (x div y) = (x::ordinal)\"\n  by (metis ordinal_div_plus_mod ordinal_dvd_mod ordinal_plus_0)\n\nlemma ordinal_dvd_oLimit:\n  assumes \"\\<forall>n. x dvd f n\" shows \"x dvd oLimit f\"\nproof \n  show \"oLimit f = x * oLimit (\\<lambda>n. f n div x)\"\n    using assms by (simp add: ordinal_dvd_times_div)\nqed\n\n\nsubsection \\<open>Logarithms\\<close>\n\ndefinition\n  oLog :: \"ordinal \\<Rightarrow> ordinal \\<Rightarrow> ordinal\" where\n  \"oLog b = (\\<lambda>x. if 1 < b then oInv ((**) b) x else 0)\"\n\nlemma ordinal_oLogI: \n  assumes \"b ** y \\<le> x\" \"x < b ** y * b\" shows \"oLog b x = y\"\nproof (cases \"1 < b\")\n  case True\n  then show ?thesis\n    by (simp add: assms normal.oInv_equality normal_exp oLog_def)\nqed (use assms linorder_neq_iff in fastforce)\n\nlemma ordinal_exp_oLog_le: \"\\<lbrakk>0 < x; oSuc 0 < b\\<rbrakk> \\<Longrightarrow> b ** (oLog b x) \\<le> x\"\n  by (simp add: normal.oInv_bound1 normal_exp oLog_def oSuc_leI)\n\nlemma ordinal_less_exp_oLog: \"oSuc 0 < b \\<Longrightarrow> x < b ** (oLog b x) * b\"\n  by (metis normal.oInv_bound2 normal_exp oLog_def ordinal_exp_oSuc ordinal_one_def)\n\nlemma ordinal_oLog_less: \"\\<lbrakk>0 < x; oSuc 0 < b; x < b ** y\\<rbrakk> \\<Longrightarrow> oLog b x < y\"\n  by (simp add: normal.oInv_less normal_exp oLog_def oSuc_leI)\n\nlemma ordinal_le_oLog:\n  \"\\<lbrakk>oSuc 0 < b; b ** y \\<le> x\\<rbrakk> \\<Longrightarrow> y \\<le> oLog b x\"\n  by (simp add: oLog_def normal.le_oInv[OF normal_exp])\n\nlemma ordinal_oLogI2:\n  assumes \"oSuc 0 < b\" \"x = b ** y * q + r\" \"0 < q\" \"q < b\" \"r < b ** y\"\n  shows \"oLog b x = y\"\nproof (rule ordinal_oLogI)\n  show \"b ** y \\<le> x\"\n    using assms by (metis dual_order.trans ordinal_le_plusR ordinal_le_timesR)\n  show \"x < b ** y * b\"\n    using assms\n    by (metis leD leI order_less_trans ordinal_divI ordinal_exp_not_0 ordinal_le_div)\nqed\n\nlemma ordinal_div_exp_oLog_less: \"oSuc 0 < b \\<Longrightarrow> x div (b ** oLog b x) < b\"\n  by (simp add: ordinal_div_less ordinal_less_exp_oLog)\n\nlemma ordinal_oLog_base_0: \"oLog 0 x = 0\"\n  by (simp add: oLog_def)\n\nlemma ordinal_oLog_base_1: \"oLog (oSuc 0) x = 0\"\n  by (simp add: oLog_def)\n\n\n\nlemma ordinal_oLog_exp: \"oSuc 0 < b \\<Longrightarrow> oLog b (b ** x) = x\"\n  by (simp add: oLog_def normal.oInv_inverse[OF normal_exp])\n\nlemma ordinal_oLog_self: \"oSuc 0 < b \\<Longrightarrow> oLog b b = oSuc 0\"\n  by (metis ordinal_exp_1 ordinal_oLog_exp)\n\nlemma ordinal_mono_oLog: \"mono (oLog b)\"\n  by (simp add: monoD monoI normal.mono_oInv normal_exp oLog_def)\n\nlemma ordinal_oLog_monoR: \"x \\<le> y \\<Longrightarrow> oLog b x \\<le> oLog b y\"\n  by (erule monoD[OF ordinal_mono_oLog])\n\nlemma ordinal_oLog_decreasing: \"oLog b x \\<le> x\"\n  by (metis normal.increasing normal_exp oLog_def ordinal_0_le ordinal_oLog_exp ordinal_oLog_monoR ordinal_one_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/Ordinal/OrdinalInverse.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8757870046160258, "lm_q2_score": 0.855851143290548, "lm_q1q2_score": 0.7495433091796301}}
{"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>\\<langle>tensor_ell2 a b, tensor_ell2 c d\\<rangle> = \\<langle>a,c\\<rangle> * \\<langle>b,d\\<rangle>\\<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. \\<langle>x, assoc_ell2 *\\<^sub>V a\\<rangle>)\\<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. \\<langle>a, y\\<rangle>)\\<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. \\<langle>assoc_ell2' *\\<^sub>V a, y\\<rangle>)\\<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>\\<langle>assoc_ell2' *\\<^sub>V (ket x), ket y\\<rangle> = \\<langle>ket x, assoc_ell2 *\\<^sub>V ket y\\<rangle>\\<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>\\<langle>assoc_ell2' *\\<^sub>V (ket x), y\\<rangle> = \\<langle>ket x, assoc_ell2 *\\<^sub>V y\\<rangle>\\<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>\\<langle>assoc_ell2' *\\<^sub>V x, y\\<rangle> = \\<langle>x, assoc_ell2 *\\<^sub>V y\\<rangle>\\<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. \\<langle>x, swap_ell2 *\\<^sub>V a\\<rangle>)\\<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. \\<langle>a, y\\<rangle>)\\<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. \\<langle>swap_ell2 *\\<^sub>V a, y\\<rangle>)\\<close> for y :: \\<open>('b \\<times> 'a) ell2\\<close>\n    by (simp add: cblinfun.add_right cinner_add_left antilinearI)\n  have \\<open>\\<langle>swap_ell2 *\\<^sub>V (ket x), ket y\\<rangle> = \\<langle>ket x, swap_ell2 *\\<^sub>V ket y\\<rangle>\\<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>\\<langle>swap_ell2 *\\<^sub>V (ket x), y\\<rangle> = \\<langle>ket x, swap_ell2 *\\<^sub>V y\\<rangle>\\<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>\\<langle>swap_ell2 *\\<^sub>V x, y\\<rangle> = \\<langle>x, swap_ell2 *\\<^sub>V y\\<rangle>\\<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": "dominique-unruh", "repo": "registers", "sha": "6e88a095c3dabe8e4c0b869eac65454d0d281340", "save_path": "github-repos/isabelle/dominique-unruh-registers", "path": "github-repos/isabelle/dominique-unruh-registers/registers-6e88a095c3dabe8e4c0b869eac65454d0d281340/Finite_Tensor_Product.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869884059266, "lm_q2_score": 0.8558511451289037, "lm_q1q2_score": 0.7495432969162062}}
{"text": "theory Chapter2_MyList\n  imports Main\nbegin\n\n(* Contains original definition of nat and list *)\n\ndatatype bool = True | False\n\nfun conj :: \"bool \\<Rightarrow> bool \\<Rightarrow> bool\" where\n  \"conj True True = True\"\n| \"conj _ _ = False\"\n\ndatatype nat = O | Suc nat\n\nfun add :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\" where\n  \"add nat.O n = n\"\n| \"add (Suc m) n = Suc (add m n)\"\n\nlemma add_02 [simp]: \"add m nat.O = m\"\n  apply (induction m)\n  apply (auto)\n  done\n\n(* List *)\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\"\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\n(* Exercise 2.2 *)\ntheorem add_assoc [simp]: \"add n (add m l) = add (add n m) l\"\n  apply (induction n)\n  apply (auto)\n  done\n\nlemma add_comm' [simp]: \"add n (Suc m) = Suc (add n m)\"\n  apply (induction n)\n   apply (auto)\n  done\n\ntheorem add_comm [simp]: \"add n m = add m n\"\n  apply (induction m)\n   apply (auto)\n  done\n\nfun double :: \"nat \\<Rightarrow> nat\" where\n  \"double nat.O = nat.O\"\n| \"double (Suc n) = Suc (Suc (double n))\"\n\ntheorem double_add_twice[simp]: \"double n = add n n\"\n  apply (induction n)\n   apply (auto)\n  done\n\n\n(* Exercise 2.9 *)\nfun itadd :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\" where\n  \"itadd nat.O m = m\"\n| \"itadd (Suc n) m = itadd n (Suc m)\"\n\ntheorem itadd_add : \"itadd n m = add n m\"\n  apply (induction n arbitrary:m)\n   apply (auto)\n  done\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/Chapter2_MyList.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894661025424, "lm_q2_score": 0.8376199673867852, "lm_q1q2_score": 0.7494935234148505}}
{"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_10\n  imports \"../../Test_Base\"\nbegin\n\ndatatype 'a list = nil2 | cons2 \"'a\" \"'a list\"\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\ntheorem property0 :\n  \"((rev (rev y)) = y)\"\n  apply(induct y)(*\"(induct rule: rev.induct)\" is equally good.*)\n   apply fastforce\n  apply(subst rev.simps)\n  (*common sub-term generalization*)\n  apply(subgoal_tac \"\\<And>rev_y. rev (rev_y) = y \\<longrightarrow> rev (x (rev_y) (cons2 x1 nil2)) = cons2 x1 y\")\n   apply fastforce\n  apply(thin_tac \"rev (rev y) = y\")\n  apply(rule meta_allI)\n  back\n  back\n  back\n  apply(induct_tac rev_y)\n   apply auto\n  done\n\ntheorem property0' :\n  \"((rev (rev y)) = y)\"\n  apply(induct rule:rev.induct) (*\"(induct y)\" is equally good*)\n  apply fastforce\n  apply(subst rev.simps)\n  (*common sub-term generalization*)\n  apply(subgoal_tac \"\\<And>rev_y. rev (rev_y) = xs \\<longrightarrow> rev (x (rev_y) (cons2 z nil2)) = cons2 z xs\")\n   apply fastforce\n  apply(thin_tac \"rev (rev xs) = xs\")\n  apply(rule meta_allI)\n  back\n  back\n  back\n  apply(induct_tac rev_y)\n   apply auto\n  done\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/Prod/Prod/TIP_prop_10.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127529517043, "lm_q2_score": 0.8774767954920548, "lm_q1q2_score": 0.7492886260898601}}
{"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 \\<open>P \\<and> Q \\<longrightarrow> Q \\<and> P\\<close>\n  by (tactic \"IntPr.fast_tac \\<^context> 1\")\n\nlemma \\<open>P \\<or> Q \\<longrightarrow> Q \\<or> P\\<close>\n  by fast\n\n\ntext \\<open>associative laws of \\<open>\\<and>\\<close> and \\<open>\\<or>\\<close>\\<close>\nlemma \\<open>(P \\<and> Q) \\<and> R \\<longrightarrow> P \\<and> (Q \\<and> R)\\<close>\n  by fast\n\nlemma \\<open>(P \\<or> Q) \\<or> R \\<longrightarrow>  P \\<or> (Q \\<or> R)\\<close>\n  by fast\n\n\ntext \\<open>distributive laws of \\<open>\\<and>\\<close> and \\<open>\\<or>\\<close>\\<close>\nlemma \\<open>(P \\<and> Q) \\<or> R \\<longrightarrow> (P \\<or> R) \\<and> (Q \\<or> R)\\<close>\n  by fast\n\nlemma \\<open>(P \\<or> R) \\<and> (Q \\<or> R) \\<longrightarrow> (P \\<and> Q) \\<or> R\\<close>\n  by fast\n\nlemma \\<open>(P \\<or> Q) \\<and> R \\<longrightarrow> (P \\<and> R) \\<or> (Q \\<and> R)\\<close>\n  by fast\n\nlemma \\<open>(P \\<and> R) \\<or> (Q \\<and> R) \\<longrightarrow> (P \\<or> Q) \\<and> R\\<close>\n  by fast\n\n\ntext \\<open>Laws involving implication\\<close>\n\nlemma \\<open>(P \\<longrightarrow> R) \\<and> (Q \\<longrightarrow> R) \\<longleftrightarrow> (P \\<or> Q \\<longrightarrow> R)\\<close>\n  by fast\n\nlemma \\<open>(P \\<and> Q \\<longrightarrow> R) \\<longleftrightarrow> (P \\<longrightarrow> (Q \\<longrightarrow> R))\\<close>\n  by fast\n\nlemma \\<open>((P \\<longrightarrow> R) \\<longrightarrow> R) \\<longrightarrow> ((Q \\<longrightarrow> R) \\<longrightarrow> R) \\<longrightarrow> (P \\<and> Q \\<longrightarrow> R) \\<longrightarrow> R\\<close>\n  by fast\n\nlemma \\<open>\\<not> (P \\<longrightarrow> R) \\<longrightarrow> \\<not> (Q \\<longrightarrow> R) \\<longrightarrow> \\<not> (P \\<and> Q \\<longrightarrow> R)\\<close>\n  by fast\n\nlemma \\<open>(P \\<longrightarrow> Q \\<and> R) \\<longleftrightarrow> (P \\<longrightarrow> Q) \\<and> (P \\<longrightarrow> R)\\<close>\n  by fast\n\n\ntext \\<open>Propositions-as-types\\<close>\n\n\\<comment> \\<open>The combinator K\\<close>\nlemma \\<open>P \\<longrightarrow> (Q \\<longrightarrow> P)\\<close>\n  by fast\n\n\\<comment> \\<open>The combinator S\\<close>\nlemma \\<open>(P \\<longrightarrow> Q \\<longrightarrow> R) \\<longrightarrow> (P \\<longrightarrow> Q) \\<longrightarrow> (P \\<longrightarrow> R)\\<close>\n  by fast\n\n\n\\<comment> \\<open>Converse is classical\\<close>\nlemma \\<open>(P \\<longrightarrow> Q) \\<or> (P \\<longrightarrow> R) \\<longrightarrow> (P \\<longrightarrow> Q \\<or> R)\\<close>\n  by fast\n\nlemma \\<open>(P \\<longrightarrow> Q) \\<longrightarrow> (\\<not> Q \\<longrightarrow> \\<not> P)\\<close>\n  by fast\n\n\ntext \\<open>Schwichtenberg's examples (via T. Nipkow)\\<close>\n\nlemma stab_imp: \\<open>(((Q \\<longrightarrow> R) \\<longrightarrow> R) \\<longrightarrow> Q) \\<longrightarrow> (((P \\<longrightarrow> Q) \\<longrightarrow> R) \\<longrightarrow> R) \\<longrightarrow> P \\<longrightarrow> Q\\<close>\n  by fast\n\nlemma stab_to_peirce:\n  \\<open>(((P \\<longrightarrow> R) \\<longrightarrow> R) \\<longrightarrow> P) \\<longrightarrow> (((Q \\<longrightarrow> R) \\<longrightarrow> R) \\<longrightarrow> Q)\n    \\<longrightarrow> ((P \\<longrightarrow> Q) \\<longrightarrow> P) \\<longrightarrow> P\\<close>\n  by fast\n\nlemma peirce_imp1:\n  \\<open>(((Q \\<longrightarrow> R) \\<longrightarrow> Q) \\<longrightarrow> Q)\n    \\<longrightarrow> (((P \\<longrightarrow> Q) \\<longrightarrow> R) \\<longrightarrow> P \\<longrightarrow> Q) \\<longrightarrow> P \\<longrightarrow> Q\\<close>\n  by fast\n\nlemma peirce_imp2: \\<open>(((P \\<longrightarrow> R) \\<longrightarrow> P) \\<longrightarrow> P) \\<longrightarrow> ((P \\<longrightarrow> Q \\<longrightarrow> R) \\<longrightarrow> P) \\<longrightarrow> P\\<close>\n  by fast\n\nlemma mints: \\<open>((((P \\<longrightarrow> Q) \\<longrightarrow> P) \\<longrightarrow> P) \\<longrightarrow> Q) \\<longrightarrow> Q\\<close>\n  by fast\n\nlemma mints_solovev: \\<open>(P \\<longrightarrow> (Q \\<longrightarrow> R) \\<longrightarrow> Q) \\<longrightarrow> ((P \\<longrightarrow> Q) \\<longrightarrow> R) \\<longrightarrow> R\\<close>\n  by fast\n\nlemma tatsuta:\n  \\<open>(((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\\<close>\n  by fast\n\nlemma tatsuta1:\n  \\<open>(((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\\<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/Propositional_Cla.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8774767810736693, "lm_q2_score": 0.8539127510928476, "lm_q1q2_score": 0.7492886121467133}}
{"text": "theory Type\n  imports \"../00Utils/Variable\"\nbegin\n\ndatatype ty = \n  TyVar var\n  | Base \n  | Arrow ty ty\n\nprimrec tvars :: \"ty \\<Rightarrow> var set\" where\n  \"tvars (TyVar y) = {y}\"\n| \"tvars Base = {}\"\n| \"tvars (Arrow t\\<^sub>1 t\\<^sub>2) = tvars t\\<^sub>1 \\<union> tvars t\\<^sub>2\"\n\nfun tsubst :: \"var \\<Rightarrow> ty \\<Rightarrow> ty \\<Rightarrow> ty\" where\n  \"tsubst x t' (TyVar y) = (if x = y then t' else TyVar y)\"\n| \"tsubst x t' Base = Base\"\n| \"tsubst x t' (Arrow t\\<^sub>1 t\\<^sub>2) = Arrow (tsubst x t' t\\<^sub>1) (tsubst x t' t\\<^sub>2)\"\n\n\n\nlemma [simp]: \"tsubst x (TyVar x) t = t\"\n  by (induction t) simp_all\n\nlemma [simp]: \"y \\<notin> tvars t \\<Longrightarrow> tsubst y t' (tsubst x (TyVar y) t) = tsubst x t' t\"\n  by (induction t) simp_all\n\nlemma tsubst_arrow [consumes 1, case_names TyVar Arrow]: \"Arrow t\\<^sub>1 t\\<^sub>2 = tsubst y t' tt \\<Longrightarrow> \n  (t' = Arrow t\\<^sub>1 t\\<^sub>2 \\<Longrightarrow> tt = TyVar y \\<Longrightarrow> P) \\<Longrightarrow> \n    (\\<And>tt\\<^sub>1 tt\\<^sub>2. t\\<^sub>1 = tsubst y t' tt\\<^sub>1 \\<Longrightarrow> t\\<^sub>2 = tsubst y t' tt\\<^sub>2 \\<Longrightarrow> tt = Arrow tt\\<^sub>1 tt\\<^sub>2 \\<Longrightarrow> P) \\<Longrightarrow> P\"\n  by (induction tt) (simp_all split: if_splits)\n\nend", "meta": {"author": "xtreme-james-cooper", "repo": "Lambda-RAM-Compiler", "sha": "24125435949fa71dfc5faafdb236d28a098beefc", "save_path": "github-repos/isabelle/xtreme-james-cooper-Lambda-RAM-Compiler", "path": "github-repos/isabelle/xtreme-james-cooper-Lambda-RAM-Compiler/Lambda-RAM-Compiler-24125435949fa71dfc5faafdb236d28a098beefc/02Typed/Type.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213664574068, "lm_q2_score": 0.8333245891029457, "lm_q1q2_score": 0.7492599432567976}}
{"text": "section \\<open>Start\\<close>\n\ntheory Isabelle_Intro\n  imports Main\nbegin\n\nsection \\<open>Predefined Inductive Type\\<close>\n\nfun sum_up_to :: \"nat \\<Rightarrow> nat\" where\n  \"sum_up_to 0 = 0\" |\n  \"sum_up_to (Suc n) = sum_up_to n + Suc n\"\n\nlemma gauss: \"sum_up_to n = n * (n + 1) div 2\"\nproof (induction n)\n  case 0\n  show ?case by simp\nnext\n  case Suc\n  then show ?case by simp\nqed\n\nsection \\<open>Custom Inductive Type\\<close>\n\ndatatype 'a tree =\n  Leaf |\n  Branch 'a \"('a tree)\" \"('a tree)\"\n\nfun mirror :: \"'a tree \\<Rightarrow> 'a tree\" where\n  mirror_leaf: \"mirror Leaf = Leaf\" |\n  mirror_branch: \"mirror (Branch x t\\<^sub>1 t\\<^sub>2) = Branch x (mirror t\\<^sub>2) (mirror t\\<^sub>1)\"\n\nlemma double_mirror: \"mirror (mirror t) = t\"\nproof (induction t)\n  case Leaf\n  show ?case by simp\nnext\n  case (Branch x t\\<^sub>1 t\\<^sub>2)\n  have \"mirror (mirror (Branch x t\\<^sub>1 t\\<^sub>2)) = mirror (Branch x (mirror t\\<^sub>2) (mirror t\\<^sub>1))\"\n    by (rule arg_cong [OF mirror_branch])\n  also have \"\\<dots> = Branch x (mirror (mirror t\\<^sub>1)) (mirror (mirror t\\<^sub>2))\"\n    by (rule mirror_branch)\n  also have \"\\<dots> = Branch x t\\<^sub>1 t\\<^sub>2\"\n    by (simp add: Branch.IH)\n  finally show ?case .\nqed\n\nsection \\<open>Computation Induction\\<close>\n\nfun intersperse :: \"'a \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where\n  \"intersperse _ [] = []\" |\n  \"intersperse _ [x] = [x]\" |\n  \"intersperse y (x # xs) = x # y # intersperse y xs\"\n\nvalue \"intersperse (0 :: nat) [1]\"\nvalue \"intersperse (0 :: nat) [1, 2]\"\nvalue \"intersperse (0 :: nat) [1, 2, 3]\"\n\nlemma \"intersperse (0 :: nat) [1, 2, 3] = [1, 0, 2, 0, 3]\" by simp\n\nlemma intersperse_map: \"map f (intersperse y xs) = intersperse (f y) (map f xs)\"\nproof (induction xs rule: intersperse.induct)\n  case 1\n  show ?case by simp\nnext\n  case 2\n  show ?case by simp\nnext\n  case 3\n  then show ?case by simp\nqed\n\nlemma \"map f (intersperse y xs) = intersperse (f y) (map f xs)\" \\<comment> \\<open>now proved more explicitly\\<close>\nproof (induction xs rule: intersperse.induct)\n  fix y\n  show \"map f (intersperse y []) = intersperse (f y) (map f [])\"\n    by simp\nnext\n  fix y and x\n  show \"map f (intersperse y [x]) = intersperse (f y) (map f [x])\"\n    by simp\nnext\n  fix y and x\\<^sub>1 and x\\<^sub>2 and xs\n  assume \"map f (intersperse y (x\\<^sub>2 # xs)) = intersperse (f y) (map f (x\\<^sub>2 # xs))\"\n  then show \"map f (intersperse y (x\\<^sub>1 # x\\<^sub>2 # xs)) = intersperse (f y) (map f (x\\<^sub>1 # x\\<^sub>2 # xs))\"\n    by simp\nqed\n\nsection \\<open>Inductive Predicate\\<close>\n\ninductive closure :: \"('a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> ('a \\<Rightarrow> 'a \\<Rightarrow> bool)\" for r where\n  refl: \"closure r x x\" |\n  step: \"\\<lbrakk> r x y; closure r y z \\<rbrakk> \\<Longrightarrow> closure r x z\"\n\ninductive closure' :: \"('a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> ('a \\<Rightarrow> 'a \\<Rightarrow> bool)\" for r where\n  refl': \"closure' r x x\" |\n  step': \"\\<lbrakk> closure' r x y; r y z \\<rbrakk> \\<Longrightarrow> closure' r x z\"\n\nlemma closure_implies_closure': \"closure r x y \\<Longrightarrow> closure' r x y\"\nproof (induction rule: closure.induct)\n  case refl\n  show ?case by (fact refl')\nnext\n  case (step x y z)\n  from `closure' r y z` and `r x y` show \"closure' r x z\"\n  proof (induction rule: closure'.induct)\n    case refl'\n    then show ?case by (blast intro: closure'.intros)\n  next\n    case step'\n    then show ?case by (blast intro: closure'.step')\n  qed\nqed\n\nsection \\<open>End\\<close>\n\nend\n", "meta": {"author": "jeltsch", "repo": "isabelle-intro", "sha": "36d5e11f5f3f33be41b23858cff716d077cb6e71", "save_path": "github-repos/isabelle/jeltsch-isabelle-intro", "path": "github-repos/isabelle/jeltsch-isabelle-intro/isabelle-intro-36d5e11f5f3f33be41b23858cff716d077cb6e71/Isabelle_Intro.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8856314798554445, "lm_q2_score": 0.845942439250491, "lm_q1q2_score": 0.7491932543459368}}
{"text": "section \\<open>Simplicial complexes\\<close>\n\ntext \\<open>\n  In this section we develop the basic theory of abstract simplicial complexes as a collection of\n  finite sets, where the power set of each member set is contained in the collection. Note that in\n  this development we allow the empty simplex, since allowing it or not seemed of no logical\n  consequence, but of some small practical consequence. \n\\<close>\n\ntheory Simplicial\nimports Prelim\n\nbegin\n\nsubsection \\<open>Geometric notions\\<close>\n\ntext \\<open>\n  The geometric notions attached to a simplicial complex of main interest to us are those of facets\n  (subsets of codimension one), adjacency (sharing a facet in common), and chains of adjacent\n  simplices.\n\\<close>\n\nsubsubsection \\<open>Facets\\<close>\n\ndefinition facetrel :: \"'a set \\<Rightarrow> 'a set \\<Rightarrow> bool\" (infix \"\\<lhd>\" 60)\n  where \"y \\<lhd> x \\<equiv> \\<exists>v. v \\<notin> y \\<and> x = insert v y\"\n\nlemma facetrelI: \"v \\<notin> y \\<Longrightarrow> x = insert v y \\<Longrightarrow> y \\<lhd> x\"\n  using facetrel_def by fast\n\nlemma facetrelI_card: \"y \\<subseteq> x \\<Longrightarrow> card (x-y) = 1 \\<Longrightarrow> y \\<lhd> x\"\n  using card1[of \"x-y\"] by (blast intro: facetrelI)\n\nlemma facetrel_complement_vertex: \"y\\<lhd>x \\<Longrightarrow> x = insert v y \\<Longrightarrow> v\\<notin>y\"\n  using facetrel_def[of y x] by fastforce\n\nlemma facetrel_diff_vertex: \"v\\<in>x \\<Longrightarrow> x-{v} \\<lhd> x\"\n  by (auto intro: facetrelI)\n\nlemma facetrel_conv_insert: \"y \\<lhd> x \\<Longrightarrow> v \\<in> x - y \\<Longrightarrow> x = insert v y\"\n  unfolding facetrel_def by fast\n\nlemma facetrel_psubset: \"y \\<lhd> x \\<Longrightarrow> y \\<subset> x\"\n  unfolding facetrel_def by fast\n\nlemma facetrel_subset: \"y \\<lhd> x \\<Longrightarrow> y \\<subseteq> x\"\n  using facetrel_psubset by fast\n\nlemma facetrel_card: \"y \\<lhd> x \\<Longrightarrow> card (x-y) = 1\"\n  using insert_Diff_if[of _ y y] unfolding facetrel_def by fastforce\n\nlemma finite_facetrel_card: \"finite x \\<Longrightarrow> y\\<lhd>x \\<Longrightarrow> card x = Suc (card y)\"\n  using facetrel_def[of y x] card_insert_disjoint[of x] by auto\n\nlemma facetrelI_cardSuc: \"z\\<subseteq>x \\<Longrightarrow> card x = Suc (card z) \\<Longrightarrow> z\\<lhd>x\"\n  using card_ge_0_finite finite_subset[of z] card_Diff_subset[of z x]\n  by    (force intro: facetrelI_card)\n\nlemma facet2_subset: \"\\<lbrakk> z\\<lhd>x; z\\<lhd>y; x\\<inter>y - z \\<noteq> {} \\<rbrakk> \\<Longrightarrow> x \\<subseteq> y\"\n  unfolding facetrel_def by force\n\nlemma inj_on_pullback_facet:\n  assumes \"inj_on f x\" \"z \\<lhd> f`x\"\n  obtains y where \"y \\<lhd> x\" \"f`y = z\"\nproof\n  from assms(2) obtain v where v: \"v\\<notin>z\" \"f`x = insert v z\"\n    using facetrel_def[of z] by auto\n  define u and y where \"u \\<equiv> the_inv_into x f v\" and y: \"y \\<equiv> {v\\<in>x. f v \\<in> z}\"\n  moreover with assms(2) v have \"x = insert u y\"\n    using the_inv_into_f_eq[OF assms(1)] the_inv_into_into[OF assms(1)]\n    by    auto\n  ultimately show \"y \\<lhd> x\"\n    using v f_the_inv_into_f[OF assms(1)] by (force intro: facetrelI)\n  from y assms(2) show \"f`y = z\" using facetrel_subset by fast\nqed\n\n\nsubsubsection \\<open>Adjacency\\<close>\n\ndefinition adjacent :: \"'a set \\<Rightarrow> 'a set \\<Rightarrow> bool\" (infix \"\\<sim>\" 70)\n  where \"x \\<sim> y \\<equiv> \\<exists>z. z\\<lhd>x \\<and> z\\<lhd>y\"\n\nlemma adjacentI: \"z\\<lhd>x \\<Longrightarrow> z\\<lhd>y \\<Longrightarrow> x \\<sim> y\"\n  using adjacent_def by fast\n\nlemma empty_not_adjacent: \"\\<not> {} \\<sim> x\"\n  unfolding facetrel_def adjacent_def by fast\n\nlemma adjacent_sym: \"x \\<sim> y \\<Longrightarrow> y \\<sim> x\"\n  unfolding adjacent_def by fast\n\nlemma adjacent_refl:\n  assumes \"x \\<noteq> {}\"\n  shows   \"x \\<sim> x\"\nproof-\n  from assms obtain v where v: \"v\\<in>x\" by fast\n  thus \"x \\<sim> x\" using facetrelI[of v \"x-{v}\"] unfolding adjacent_def by fast\nqed\n\nlemma common_facet: \"\\<lbrakk> z\\<lhd>x; z\\<lhd>y; x \\<noteq> y \\<rbrakk> \\<Longrightarrow> z = x \\<inter> y\"\n  using facetrel_subset facet2_subset by fast\n\nlemma adjacent_int_facet1: \"x \\<sim> y \\<Longrightarrow> x \\<noteq> y \\<Longrightarrow> (x \\<inter> y) \\<lhd> x\"\n  using common_facet unfolding adjacent_def by fast\n\nlemma adjacent_int_facet2: \"x \\<sim> y \\<Longrightarrow> x \\<noteq> y \\<Longrightarrow> (x \\<inter> y) \\<lhd> y\"\n  using adjacent_sym adjacent_int_facet1 by (fastforce simp add: Int_commute)\n\nlemma adjacent_conv_insert: \"x \\<sim> y \\<Longrightarrow> v \\<in> x - y \\<Longrightarrow> x = insert v (x\\<inter>y)\"\n  using adjacent_int_facet1 facetrel_conv_insert by fast\n\nlemma adjacent_int_decomp:\n  \"x \\<sim> y \\<Longrightarrow> x \\<noteq> y \\<Longrightarrow> \\<exists>v. v \\<notin> y \\<and> x = insert v (x\\<inter>y)\"\n  using adjacent_int_facet1 unfolding facetrel_def by fast\n\nlemma adj_antivertex:\n  assumes \"x\\<sim>y\" \"x\\<noteq>y\"\n  shows   \"\\<exists>!v. v\\<in>x-y\"\nproof (rule ex_ex1I)\n  from assms obtain w where w: \"w\\<notin>y\" \"x = insert w (x\\<inter>y)\"\n    using adjacent_int_decomp by fast\n  thus \"\\<exists>v. v\\<in>x-y\" by auto\n  from w have \"\\<And>v. v\\<in>x-y \\<Longrightarrow> v=w\" by fast\n  thus \"\\<And>v v'. v\\<in>x-y \\<Longrightarrow> v'\\<in>x-y \\<Longrightarrow> v=v'\" by auto\nqed\n\nlemma adjacent_card: \"x \\<sim> y \\<Longrightarrow> card x = card y\"\n  unfolding adjacent_def facetrel_def by (cases \"finite x\" \"x=y\" rule: two_cases) auto\n\nlemma adjacent_to_adjacent_int_subset:\n  assumes \"C \\<sim> D\" \"f`C \\<sim> f`D\" \"f`C \\<noteq> f`D\"\n  shows   \"f`C \\<inter> f`D \\<subseteq> f`(C\\<inter>D)\"\nproof\n  from assms(1,3) obtain v where v: \"v \\<notin> D\" \"C = insert v (C\\<inter>D)\"\n    using adjacent_int_decomp by fast\n  from assms(2,3) obtain w where w: \"w \\<notin> f`D\" \"f`C = insert w (f`C\\<inter>f`D)\"\n    using adjacent_int_decomp[of \"f`C\" \"f`D\"] by fast\n  from w have w': \"w \\<in> f`C - f`D\" by fast\n  with v assms(1,2) have fv_w: \"f v = w\" using adjacent_conv_insert by fast\n  fix b assume \"b \\<in> f`C \\<inter> f`D\"\n  from this obtain a1 a2\n    where a1: \"a1 \\<in> C\" \"b = f a1\"\n    and   a2: \"a2 \\<in> D\" \"b = f a2\"\n    by    fast\n  from v a1 a2(2) have \"a1 \\<notin> D \\<Longrightarrow> f a2 = w\" using fv_w by auto\n  with a2(1) w' have \"a1 \\<in> D\" by fast\n  with a1 show \"b \\<in> f`(C\\<inter>D)\" by fast\nqed\n\nlemma adjacent_to_adjacent_int:\n  \"\\<lbrakk> C \\<sim> D; f`C \\<sim> f`D; f`C \\<noteq> f`D \\<rbrakk> \\<Longrightarrow> f`(C\\<inter>D) = f`C \\<inter> f`D\"\n  using adjacent_to_adjacent_int_subset by fast\n\nsubsubsection \\<open>Chains of adjacent sets\\<close>\n\nabbreviation \"adjacentchain  \\<equiv> binrelchain adjacent\"\nabbreviation \"padjacentchain \\<equiv> proper_binrelchain adjacent\"\n\nlemmas adjacentchain_Cons_reduce   = binrelchain_Cons_reduce   [of adjacent]\nlemmas adjacentchain_obtain_proper = binrelchain_obtain_proper [of _ _ adjacent]\n\nlemma adjacentchain_card: \"adjacentchain (x#xs@[y]) \\<Longrightarrow> card x = card y\"\n  using adjacent_card by (induct xs arbitrary: x) auto\n\n\nsubsection \\<open>Locale and basic facts\\<close>\n\nlocale SimplicialComplex =\n  fixes   X :: \"'a set set\"\n  assumes finite_simplices: \"\\<forall>x\\<in>X. finite x\"\n  and     faces           : \"x\\<in>X \\<Longrightarrow> y\\<subseteq>x \\<Longrightarrow> y\\<in>X\"\n\ncontext SimplicialComplex\nbegin\n\nabbreviation \"Subcomplex Y \\<equiv> Y \\<subseteq> X \\<and> SimplicialComplex Y\"\n\ndefinition \"maxsimp x \\<equiv> x\\<in>X \\<and> (\\<forall>z\\<in>X. x\\<subseteq>z \\<longrightarrow> z=x)\"\n\ndefinition adjacentset :: \"'a set \\<Rightarrow> 'a set set\"\n  where \"adjacentset x = {y\\<in>X. x\\<sim>y}\"\n\n\n\nlemma singleton_simplex: \"v\\<in>\\<Union>X \\<Longrightarrow> {v} \\<in> X\"\n  using faces by auto\n\nlemma maxsimpI: \"x \\<in> X \\<Longrightarrow> (\\<And>z. z\\<in>X \\<Longrightarrow> x\\<subseteq>z \\<Longrightarrow> z=x) \\<Longrightarrow> maxsimp x\"\n  using maxsimp_def by auto\n\nlemma maxsimpD_simplex: \"maxsimp x \\<Longrightarrow> x\\<in>X\"\n  using maxsimp_def by fast\n\nlemma maxsimpD_maximal: \"maxsimp x \\<Longrightarrow> z\\<in>X \\<Longrightarrow> x\\<subseteq>z \\<Longrightarrow> z=x\"\n  using maxsimp_def by auto\n\nlemmas finite_maxsimp = finite_simplex[OF maxsimpD_simplex]\n\nlemma maxsimp_nempty: \"X \\<noteq> {{}} \\<Longrightarrow> maxsimp x \\<Longrightarrow> x \\<noteq> {}\"\n  unfolding maxsimp_def by fast \n\nlemma maxsimp_vertices: \"maxsimp x \\<Longrightarrow> x\\<subseteq>\\<Union>X\"\n  using maxsimpD_simplex by fast\n\nlemma adjacentsetD_adj: \"y \\<in> adjacentset x \\<Longrightarrow> x\\<sim>y\"\n  using adjacentset_def by fast\n\nlemma max_in_subcomplex:\n  \"\\<lbrakk> Subcomplex Y; y \\<in> Y; maxsimp y \\<rbrakk> \\<Longrightarrow> SimplicialComplex.maxsimp Y y\"\n  using maxsimpD_maximal by (fast intro: SimplicialComplex.maxsimpI)\n\nlemma face_im:\n  assumes \"w \\<in> X\" \"y \\<subseteq> f`w\"\n  defines \"u \\<equiv> {a\\<in>w. f a \\<in> y}\"\n  shows \"y \\<in> f\\<turnstile>X\"\n  using assms faces[of w u] image_eqI[of y \"(`) f\" u X]\n  by    fast\n\nlemma im_faces: \"x \\<in> f \\<turnstile> X \\<Longrightarrow> y \\<subseteq> x \\<Longrightarrow> y \\<in> f \\<turnstile> X\"\n  using faces face_im[of _ y] by (cases \"y={}\") auto\n\nlemma map_is_simplicial_morph: \"SimplicialComplex (f\\<turnstile>X)\"\nproof\n  show \"\\<forall>x\\<in>f\\<turnstile>X. finite x\" using finite_simplices by fast\n  show \"\\<And>x y. x \\<in>f\\<turnstile>X \\<Longrightarrow> y\\<subseteq>x \\<Longrightarrow> y\\<in>f\\<turnstile>X\" using im_faces by fast\nqed\n\nlemma vertex_set_int:\n  assumes \"SimplicialComplex Y\"\n  shows   \"\\<Union>(X\\<inter>Y) = \\<Union>X \\<inter> \\<Union>Y\"\nproof\n  have \"\\<And>v. v \\<in> \\<Union>X \\<inter> \\<Union>Y \\<Longrightarrow> v\\<in> \\<Union>(X\\<inter>Y)\"\n    using faces SimplicialComplex.faces[OF assms] by auto\n  thus \"\\<Union>(X\\<inter>Y) \\<supseteq> \\<Union>X \\<inter> \\<Union>Y\" by fast\nqed auto\n\nend (* context SimplicialComplex *)\n\nsubsection \\<open>Chains of maximal simplices\\<close>\n\ntext \\<open>\n  Chains of maximal simplices (with respect to adjacency) will allow us to walk through chamber\n  complexes. But there is much we can say about them in simplicial complexes. We will call a chain\n  of maximal simplices proper (using the prefix \\<open>p\\<close> as a naming convention to denote proper)\n  if no maximal simplex appears more than once in the chain. (Some sources elect to call improper\n  chains prechains, and reserve the name chain to describe a proper chain. And usually a slightly\n  weaker notion of proper is used, requiring only that no maximal simplex appear twice in succession. But\n  it essentially makes no difference, and we found it easier to use @{const distinct} rather than\n  @{term \"binrelchain not_equal\"}.)\n\\<close>\n\ncontext SimplicialComplex\nbegin\n\ndefinition \"maxsimpchain xs  \\<equiv> (\\<forall>x\\<in>set xs. maxsimp x) \\<and> adjacentchain xs\"\ndefinition \"pmaxsimpchain xs \\<equiv> (\\<forall>x\\<in>set xs. maxsimp x) \\<and> padjacentchain xs\"\n\nfunction min_maxsimpchain :: \"'a set list \\<Rightarrow> bool\"\n  where\n    \"min_maxsimpchain [] = True\"\n  | \"min_maxsimpchain [x] = maxsimp x\"\n  | \"min_maxsimpchain (x#xs@[y]) =\n      (x\\<noteq>y \\<and> is_arg_min length (\\<lambda>zs. maxsimpchain (x#zs@[y])) xs)\"\n  by (auto, rule list_cases_Cons_snoc)\n  termination by (relation \"measure length\") auto\n\nlemma maxsimpchain_snocI:\n  \"\\<lbrakk> maxsimpchain (xs@[x]); maxsimp y; x\\<sim>y \\<rbrakk> \\<Longrightarrow> maxsimpchain (xs@[x,y])\"\n  using maxsimpchain_def binrelchain_snoc maxsimpchain_def by auto\n\nlemma maxsimpchainD_maxsimp:\n  \"maxsimpchain xs \\<Longrightarrow> x \\<in> set xs \\<Longrightarrow> maxsimp x\"\n  using maxsimpchain_def by fast\n\nlemma maxsimpchainD_adj: \"maxsimpchain xs \\<Longrightarrow> adjacentchain xs\"\n  using maxsimpchain_def by fast\n\nlemma maxsimpchain_CConsI:\n  \"\\<lbrakk> maxsimp w; maxsimpchain (x#xs); w\\<sim>x \\<rbrakk> \\<Longrightarrow> maxsimpchain (w#x#xs)\"\n  using maxsimpchain_def by auto\n\nlemma maxsimpchain_Cons_reduce:\n  \"maxsimpchain (x#xs) \\<Longrightarrow> maxsimpchain xs\"\n  using     adjacentchain_Cons_reduce maxsimpchain_def by fastforce\n\nlemma maxsimpchain_append_reduce1:\n  \"maxsimpchain (xs@ys) \\<Longrightarrow> maxsimpchain xs\"\n  using binrelchain_append_reduce1 maxsimpchain_def by auto\n\nlemma maxsimpchain_append_reduce2:\n  \"maxsimpchain (xs@ys) \\<Longrightarrow> maxsimpchain ys\"\n  using binrelchain_append_reduce2 maxsimpchain_def by auto\n\nlemma maxsimpchain_remdup_adj:\n  \"maxsimpchain (xs@[x,x]@ys) \\<Longrightarrow> maxsimpchain (xs@[x]@ys)\"\n  using maxsimpchain_def binrelchain_remdup_adj by auto\n\nlemma maxsimpchain_rev: \"maxsimpchain xs \\<Longrightarrow> maxsimpchain (rev xs)\"\n  using     maxsimpchainD_maxsimp adjacent_sym\n            binrelchain_sym_rev[of adjacent]\n  unfolding maxsimpchain_def\n  by        fastforce\n\nlemma maxsimpchain_overlap_join:\n  \"maxsimpchain (xs@[w]) \\<Longrightarrow> maxsimpchain (w#ys) \\<Longrightarrow>\n    maxsimpchain (xs@w#ys)\"\n  using binrelchain_overlap_join maxsimpchain_def by auto\n\nlemma pmaxsimpchain: \"pmaxsimpchain xs \\<Longrightarrow> maxsimpchain xs\"\n  using maxsimpchain_def pmaxsimpchain_def by fast\n\nlemma pmaxsimpchainI_maxsimpchain:\n  \"maxsimpchain xs \\<Longrightarrow> distinct xs \\<Longrightarrow> pmaxsimpchain xs\"\n  using maxsimpchain_def pmaxsimpchain_def by fast\n\nlemma pmaxsimpchain_CConsI:\n  \"\\<lbrakk> maxsimp w; pmaxsimpchain (x#xs); w\\<sim>x; w \\<notin> set (x#xs) \\<rbrakk> \\<Longrightarrow>\n    pmaxsimpchain (w#x#xs)\"\n  using pmaxsimpchain_def by auto\n\nlemmas pmaxsimpchainD_maxsimp =\n  maxsimpchainD_maxsimp[OF pmaxsimpchain]\nlemmas pmaxsimpchainD_adj =\n  maxsimpchainD_adj [OF pmaxsimpchain]\n\nlemma pmaxsimpchainD_distinct: \"pmaxsimpchain xs \\<Longrightarrow> distinct xs\"\n  using pmaxsimpchain_def by fast\n\nlemma pmaxsimpchain_Cons_reduce:\n  \"pmaxsimpchain (x#xs) \\<Longrightarrow> pmaxsimpchain xs\"\n  using maxsimpchain_Cons_reduce pmaxsimpchain pmaxsimpchainD_distinct\n  by    (fastforce intro: pmaxsimpchainI_maxsimpchain)\n\nlemma pmaxsimpchain_append_reduce1:\n  \"pmaxsimpchain (xs@ys) \\<Longrightarrow> pmaxsimpchain xs\"\n  using maxsimpchain_append_reduce1 pmaxsimpchain pmaxsimpchainD_distinct\n  by    (fastforce intro: pmaxsimpchainI_maxsimpchain)\n\nlemma maxsimpchain_obtain_pmaxsimpchain:\n  assumes \"x\\<noteq>y\" \"maxsimpchain (x#xs@[y])\"\n  shows   \"\\<exists>ys. set ys \\<subseteq> set xs \\<and> length ys \\<le> length xs \\<and>\n            pmaxsimpchain (x#ys@[y])\"\nproof-\n  obtain ys\n    where ys: \"set ys \\<subseteq> set xs\" \"length ys \\<le> length xs\" \"padjacentchain (x#ys@[y])\"\n    using maxsimpchainD_adj[OF assms(2)]\n          adjacentchain_obtain_proper[OF assms(1)]\n    by    auto\n  from ys(1) assms(2) have \"\\<forall>a\\<in>set (x#ys@[y]). maxsimp a\"\n    using maxsimpchainD_maxsimp by auto\n  with ys show ?thesis unfolding pmaxsimpchain_def by auto\nqed\n\nlemma min_maxsimpchainD_maxsimpchain:\n  assumes \"min_maxsimpchain xs\"\n  shows   \"maxsimpchain xs\"\nproof (cases xs rule: list_cases_Cons_snoc)\n  case Nil thus ?thesis using maxsimpchain_def by simp\nnext\n  case Single with assms show ?thesis using maxsimpchain_def by simp\nnext\n  case Cons_snoc with assms show ?thesis using is_arg_minD1 by fastforce\nqed\n\nlemma min_maxsimpchainD_min_betw:\n  \"min_maxsimpchain (x#xs@[y]) \\<Longrightarrow> maxsimpchain (x#ys@[y]) \\<Longrightarrow>\n    length ys \\<ge> length xs\"\n  using is_arg_minD2 by fastforce\n\nlemma min_maxsimpchainI_betw:\n  assumes \"x\\<noteq>y\" \"maxsimpchain (x#xs@[y])\"\n          \"\\<And>ys. maxsimpchain (x#ys@[y]) \\<Longrightarrow> length xs \\<le> length ys\"\n  shows   \"min_maxsimpchain (x#xs@[y])\"\n  using   assms by (simp add: is_arg_min_linorderI)\n\nlemma min_maxsimpchainI_betw_compare:\n  assumes \"x\\<noteq>y\" \"maxsimpchain (x#xs@[y])\"\n          \"min_maxsimpchain (x#ys@[y])\" \"length xs = length ys\"\n  shows   \"min_maxsimpchain (x#xs@[y])\"\n  using   assms min_maxsimpchainD_min_betw min_maxsimpchainI_betw\n  by      auto\n\nlemma min_maxsimpchain_pmaxsimpchain:\n  assumes \"min_maxsimpchain xs\"\n  shows   \"pmaxsimpchain xs\"\nproof (\n  rule pmaxsimpchainI_maxsimpchain, rule min_maxsimpchainD_maxsimpchain,\n  rule assms, cases xs rule: list_cases_Cons_snoc\n)\n  case (Cons_snoc x ys y)\n  have \"\\<not> distinct (x#ys@[y]) \\<Longrightarrow> False\"\n  proof (cases \"x\\<in>set ys\" \"y\\<in>set ys\" rule: two_cases)\n    case both\n    from both(1) obtain as bs where \"ys = as@x#bs\"\n      using in_set_conv_decomp[of x ys] by fast\n    with assms Cons_snoc show False\n      using min_maxsimpchainD_maxsimpchain[OF assms]\n            maxsimpchain_append_reduce2[of \"x#as\"]\n            min_maxsimpchainD_min_betw[of x ys y]\n      by    fastforce\n  next\n    case one\n    from one(1) obtain as bs where \"ys = as@x#bs\"\n      using in_set_conv_decomp[of x ys] by fast\n    with assms Cons_snoc show False\n      using min_maxsimpchainD_maxsimpchain[OF assms]\n            maxsimpchain_append_reduce2[of \"x#as\"]\n            min_maxsimpchainD_min_betw[of x ys y]\n      by    fastforce\n  next\n    case other\n    from other(2) obtain as bs where \"ys = as@y#bs\"\n      using in_set_conv_decomp[of y ys] by fast\n    with assms Cons_snoc show False\n      using min_maxsimpchainD_maxsimpchain[OF assms]\n            maxsimpchain_append_reduce1[of \"x#as@[y]\"]\n            min_maxsimpchainD_min_betw[of x ys y]\n      by    fastforce\n  next\n    case neither\n    moreover assume \"\\<not> distinct (x # ys @ [y])\"\n    ultimately obtain as a bs cs where \"ys = as@[a]@bs@[a]@cs\"\n      using assms Cons_snoc not_distinct_decomp[of ys] by auto\n    with assms Cons_snoc show False\n      using min_maxsimpchainD_maxsimpchain[OF assms]\n            maxsimpchain_append_reduce1[of \"x#as@[a]\"]\n            maxsimpchain_append_reduce2[of \"x#as@[a]@bs\" \"a#cs@[y]\"]\n            maxsimpchain_overlap_join[of \"x#as\" a \"cs@[y]\"]\n            min_maxsimpchainD_min_betw[of x ys y \"as@a#cs\"]\n      by    auto\n  qed\n  with Cons_snoc show \"distinct xs\" by fast\nqed auto\n\nlemma min_maxsimpchain_rev:\n  assumes \"min_maxsimpchain xs\"\n  shows   \"min_maxsimpchain (rev xs)\"\nproof (cases xs rule: list_cases_Cons_snoc)\n  case Single with assms show ?thesis\n    using min_maxsimpchainD_maxsimpchain maxsimpchainD_maxsimp by simp\nnext\n  case (Cons_snoc x ys y)\n  moreover have \"min_maxsimpchain (y # rev ys @ [x])\"\n  proof (rule min_maxsimpchainI_betw)\n    from Cons_snoc assms show \"y\\<noteq>x\"\n      using min_maxsimpchain_pmaxsimpchain pmaxsimpchainD_distinct by auto\n    from Cons_snoc show \"maxsimpchain (y # rev ys @ [x])\"\n      using min_maxsimpchainD_maxsimpchain[OF assms] maxsimpchain_rev\n      by    fastforce\n    from Cons_snoc assms\n      show  \"\\<And>zs. maxsimpchain (y#zs@[x]) \\<Longrightarrow> length (rev ys) \\<le> length zs\"\n      using maxsimpchain_rev min_maxsimpchainD_min_betw[of x ys y]\n      by    fastforce\n  qed\n  ultimately show ?thesis by simp\nqed simp\n\nlemma min_maxsimpchain_adj:\n  \"\\<lbrakk> maxsimp x; maxsimp y; x\\<sim>y; x\\<noteq>y \\<rbrakk> \\<Longrightarrow> min_maxsimpchain [x,y]\"\n  using maxsimpchain_def min_maxsimpchainI_betw[of x y \"[]\"] by simp\n\nlemma min_maxsimpchain_betw_CCons_reduce:\n  assumes \"min_maxsimpchain (w#x#ys@[z])\"\n  shows   \"min_maxsimpchain (x#ys@[z])\"\nproof (rule min_maxsimpchainI_betw)\n  from assms show \"x\\<noteq>z\"\n    using min_maxsimpchain_pmaxsimpchain pmaxsimpchainD_distinct\n    by    fastforce\n  show \"maxsimpchain (x#ys@[z])\" \n    using min_maxsimpchainD_maxsimpchain[OF assms]\n          maxsimpchain_Cons_reduce\n    by    fast\nnext\n fix zs assume \"maxsimpchain (x#zs@[z])\"\n  hence \"maxsimpchain (w#x#zs@[z])\"\n    using min_maxsimpchainD_maxsimpchain[OF assms] maxsimpchain_def\n    by    fastforce\n  with assms show \"length ys \\<le> length zs\"\n    using min_maxsimpchainD_min_betw[of w \"x#ys\" z \"x#zs\"] by simp\nqed\n\nlemma min_maxsimpchain_betw_uniform_length:\n  assumes \"min_maxsimpchain (x#xs@[y])\" \"min_maxsimpchain (x#ys@[y])\"\n  shows   \"length xs = length ys\"\n  using   min_maxsimpchainD_min_betw[OF assms(1)]\n          min_maxsimpchainD_min_betw[OF assms(2)]\n          min_maxsimpchainD_maxsimpchain[OF assms(1)]\n          min_maxsimpchainD_maxsimpchain[OF assms(2)]\n  by      fastforce\n\nlemma not_min_maxsimpchainI_betw:\n  \"\\<lbrakk> maxsimpchain (x#ys@[y]); length ys < length xs \\<rbrakk> \\<Longrightarrow>\n    \\<not> min_maxsimpchain (x#xs@[y])\"\n  using min_maxsimpchainD_min_betw not_less by blast\n\nlemma maxsimpchain_in_subcomplex:\n  \"\\<lbrakk> Subcomplex Y; set ys \\<subseteq> Y; maxsimpchain ys \\<rbrakk> \\<Longrightarrow>\n    SimplicialComplex.maxsimpchain Y ys\"\n  using maxsimpchain_def max_in_subcomplex\n        SimplicialComplex.maxsimpchain_def\n  by    force\n\nend (* context SimplicialComplex *)\n\nsubsection \\<open>Isomorphisms of simplicial complexes\\<close>\n\ntext \\<open>\n  Here we develop the concept of isomorphism of simplicial complexes. Note that we have not\n  bothered to first develop the concept of morphism of simplicial complexes, since every function\n  on the vertex set of a simplicial complex can be considered a morphism of complexes (see lemma\n  \\<open>map_is_simplicial_morph\\<close> above).\n\\<close>\n\nlocale SimplicialComplexIsomorphism = SimplicialComplex X\n  for X :: \"'a set set\"\n+ fixes f :: \"'a \\<Rightarrow> 'b\"\n  assumes inj: \"inj_on f (\\<Union>X)\"\nbegin\n\nlemmas morph = map_is_simplicial_morph[of f]\n\n\n\nlemma maxsimp_im_max: \"maxsimp x \\<Longrightarrow> w \\<in> X \\<Longrightarrow> f`x \\<subseteq> f`w \\<Longrightarrow> f`w = f`x\"\n  using maxsimpD_simplex inj_onD[OF inj] maxsimpD_maximal[of x w] by blast\n\nlemma maxsimp_map:\n  \"maxsimp x \\<Longrightarrow> SimplicialComplex.maxsimp (f\\<turnstile>X) (f`x)\"\n  using maxsimpD_simplex maxsimp_im_max morph\n        SimplicialComplex.maxsimpI[of \"f\\<turnstile>X\" \"f`x\"]\n  by    fastforce\n\nlemma iso_adj_int_im:\n  assumes \"maxsimp x\" \"maxsimp y\" \"x\\<sim>y\" \"x\\<noteq>y\"\n  shows \"(f`x \\<inter> f`y) \\<lhd> f`x\"\nproof (rule facetrelI_card)\n  from assms(1,2) have  1: \"f ` x \\<subseteq> f ` y \\<Longrightarrow> f ` y = f ` x\"\n    using maxsimp_map SimplicialComplex.maxsimpD_simplex[OF morph]\n          SimplicialComplex.maxsimpD_maximal[OF morph]\n    by    simp\n  thus \"f`x \\<inter> f`y \\<subseteq> f`x\" by fast\n\n  from assms(1) have \"card (f`x - f`x \\<inter> f`y) \\<le> card (f`x - f`(x\\<inter>y))\"\n    using finite_maxsimp card_mono[of \"f`x - f`(x\\<inter>y)\" \"f`x - f`x \\<inter> f`y\"] by fast\n  moreover from assms(1,3,4) have \"card (f`x - f`(x\\<inter>y)) = 1\"\n    using maxsimpD_simplex faces[of x] maxsimpD_simplex\n          iso_codim_map adjacent_int_facet1[of x y] facetrel_card\n    by    fastforce\n  ultimately have \"card (f`x - f`x \\<inter> f`y) \\<le> 1\" by simp\n  moreover from assms(1,2,4) have \"card (f`x - f`x \\<inter> f`y) \\<noteq> 0\"\n    using 1 maxsimpD_simplex finite_maxsimp\n          inj_onD[OF induced_pow_fun_inj_on, OF inj, of x y]\n    by    auto\n  ultimately show \"card (f`x - f`x \\<inter> f`y) = 1\" by simp\nqed\n\nlemma iso_adj_map:\n  assumes \"maxsimp x\" \"maxsimp y\" \"x\\<sim>y\" \"x\\<noteq>y\"\n  shows   \"f`x \\<sim> f`y\"\n  using assms(3,4) iso_adj_int_im[OF assms] adjacent_sym\n        iso_adj_int_im[OF assms(2) assms(1)]\n  by    (auto simp add: Int_commute intro: adjacentI)\n\nlemma pmaxsimpchain_map:\n  \"pmaxsimpchain xs \\<Longrightarrow> SimplicialComplex.pmaxsimpchain (f\\<turnstile>X) (f\\<Turnstile>xs)\"\nproof (induct xs rule: list_induct_CCons)\n  case Nil show ?case\n    using map_is_simplicial_morph SimplicialComplex.pmaxsimpchain_def\n    by    fastforce\nnext\n  case (Single x) thus ?case\n    using map_is_simplicial_morph pmaxsimpchainD_maxsimp maxsimp_map\n          SimplicialComplex.pmaxsimpchain_def\n    by    fastforce\nnext\n  case (CCons x y xs)\n  have \"SimplicialComplex.pmaxsimpchain (f \\<turnstile> X) ( f`x # f`y # f\\<Turnstile>xs)\"\n  proof (\n    rule SimplicialComplex.pmaxsimpchain_CConsI,\n    rule map_is_simplicial_morph\n  )\n    from CCons(2) show \"SimplicialComplex.maxsimp (f\\<turnstile>X) (f`x)\"\n      using pmaxsimpchainD_maxsimp maxsimp_map by simp\n    from CCons show \"SimplicialComplex.pmaxsimpchain (f\\<turnstile>X) (f`y # f\\<Turnstile>xs)\"\n      using pmaxsimpchain_Cons_reduce by simp\n    from CCons(2) show \"f`x \\<sim> f`y\"\n      using pmaxsimpchain_def iso_adj_map by simp\n    from inj CCons(2) have \"distinct (f\\<Turnstile>(x#y#xs))\"\n      using     maxsimpD_simplex inj_on_distinct_setlistmapim\n      unfolding pmaxsimpchain_def\n      by        blast\n    thus \"f`x \\<notin> set (f`y # f\\<Turnstile>xs)\" by simp\n  qed\n  thus ?case by simp\nqed\n\nend (* context SimplicialComplexIsomorphism *)\n\nsubsection \\<open>The complex associated to a poset\\<close>\n\ntext \\<open>\n  A simplicial complex is naturally a poset under the subset relation. The following develops the\n  reverse direction: constructing a simplicial complex from a suitable poset.\n\\<close>\n\ncontext ordering\nbegin\n\ndefinition PosetComplex :: \"'a set \\<Rightarrow> 'a set set\"\n  where \"PosetComplex P \\<equiv> (\\<Union>x\\<in>P. { {y. pseudominimal_in (P.\\<^bold>\\<le>x) y} })\"\n\nlemma poset_is_SimplicialComplex:\n  assumes \"\\<forall>x\\<in>P. simplex_like (P.\\<^bold>\\<le>x)\"\n  shows   \"SimplicialComplex (PosetComplex P)\"\nproof (rule SimplicialComplex.intro, rule ballI)\n  fix a assume \"a \\<in> PosetComplex P\"\n  from this obtain x where \"x\\<in>P\" \"a = {y. pseudominimal_in (P.\\<^bold>\\<le>x) y}\"\n    unfolding PosetComplex_def by fast\n  with assms show \"finite a\"\n    using pseudominimal_inD1 simplex_likeD_finite finite_subset[of a \"P.\\<^bold>\\<le>x\"] by fast\nnext\n  fix a b assume ab: \"a \\<in> PosetComplex P\" \"b\\<subseteq>a\"\n  from ab(1) obtain x where x: \"x\\<in>P\" \"a = {y. pseudominimal_in (P.\\<^bold>\\<le>x) y}\"\n    unfolding PosetComplex_def by fast\n  from assms x(1) obtain f and A::\"nat set\"\n    where fA: \"OrderingSetIso less_eq less (\\<subseteq>) (\\<subset>) (P.\\<^bold>\\<le>x) f\"\n              \"f`(P.\\<^bold>\\<le>x) = Pow A\"\n    using simplex_likeD_iso[of \"P.\\<^bold>\\<le>x\"]\n    by    auto\n  define x' where x': \"x' \\<equiv> the_inv_into (P.\\<^bold>\\<le>x) f (\\<Union>(f`b))\"\n  from fA x(2) ab(2) x' have x'_P: \"x'\\<in>P\"\n    using collect_pseudominimals_below_in_poset[of P x f] by simp\n  moreover from x fA ab(2) x' have \"b = {y. pseudominimal_in (P.\\<^bold>\\<le>x') y}\"\n    using collect_pseudominimals_below_in_eq[of x P f] by simp\n  ultimately show \"b \\<in> PosetComplex P\" unfolding PosetComplex_def by fast\nqed\n\ndefinition poset_simplex_map :: \"'a set \\<Rightarrow> 'a \\<Rightarrow> 'a set\"\n  where \"poset_simplex_map P x = {y. pseudominimal_in (P.\\<^bold>\\<le>x) y}\"\n\nlemma poset_to_PosetComplex_OrderingSetMap:\n  assumes \"\\<And>x. x\\<in>P \\<Longrightarrow> simplex_like (P.\\<^bold>\\<le>x)\"\n  shows   \"OrderingSetMap (\\<^bold>\\<le>) (\\<^bold><) (\\<subseteq>) (\\<subset>) P (poset_simplex_map P)\"\nproof\n  from assms\n    show  \"\\<And>a b. \\<lbrakk> a\\<in>P; b\\<in>P; a\\<^bold>\\<le>b \\<rbrakk> \\<Longrightarrow>\n            poset_simplex_map P a \\<subseteq> poset_simplex_map P b\"\n    using     simplex_like_has_bottom pseudominimal_in_below_in\n    unfolding poset_simplex_map_def\n    by        fast\nqed\n\nend (* context ordering *)\n\ntext \\<open>\n  When a poset affords a simplicial complex, there is a natural morphism of posets from the\n  source poset into the poset of sets in the complex, as above. However, some further assumptions\n  are necessary to ensure that this morphism is an isomorphism. These conditions are collected in\n  the following locale.\n\\<close>\n\nlocale ComplexLikePoset = ordering less_eq less\n  for less_eq  :: \"'a\\<Rightarrow>'a\\<Rightarrow>bool\" (infix \"\\<^bold>\\<le>\"  50)\n  and less     :: \"'a\\<Rightarrow>'a\\<Rightarrow>bool\" (infix \"\\<^bold><\"  50)\n+ fixes   P :: \"'a set\"\n  assumes below_in_P_simplex_like: \"x\\<in>P \\<Longrightarrow> simplex_like (P.\\<^bold>\\<le>x)\"\n  and     P_has_bottom           : \"has_bottom P\"\n  and     P_has_glbs             : \"x\\<in>P \\<Longrightarrow> y\\<in>P \\<Longrightarrow> \\<exists>b. glbound_in_of P x y b\"\nbegin\n\nabbreviation \"smap \\<equiv> poset_simplex_map P\"\n\nlemma smap_onto_PosetComplex: \"smap ` P = PosetComplex P\"\n  using poset_simplex_map_def PosetComplex_def by auto\n\nlemma ordsetmap_smap: \"\\<lbrakk> a\\<in>P; b\\<in>P; a\\<^bold>\\<le>b \\<rbrakk> \\<Longrightarrow> smap a \\<subseteq> smap b\"\n  using OrderingSetMap.ordsetmap[\n          OF poset_to_PosetComplex_OrderingSetMap, OF below_in_P_simplex_like\n        ]\n        poset_simplex_map_def\n  by    simp\n\nlemma inj_on_smap: \"inj_on smap P\"\nproof (rule inj_onI)\n  fix x y assume xy: \"x\\<in>P\" \"y\\<in>P\" \"smap x = smap y\"\n  show \"x = y\"\n  proof (cases \"smap x = {}\")\n    case True with xy show ?thesis\n      using poset_simplex_map_def below_in_P_simplex_like P_has_bottom\n            simplex_like_no_pseudominimal_in_below_in_imp_singleton[of x P]\n            simplex_like_no_pseudominimal_in_below_in_imp_singleton[of y P]\n            below_in_singleton_is_bottom[of P x] below_in_singleton_is_bottom[of P y]\n      by    auto\n  next\n    case False\n    from this obtain z where \"z \\<in> smap x\" by fast\n    with xy(3) have z1: \"z \\<in> P.\\<^bold>\\<le>x\" \"z \\<in> P.\\<^bold>\\<le>y\"\n      using pseudominimal_inD1 poset_simplex_map_def by auto\n    hence \"lbound_of x y z\" by (auto intro: lbound_ofI)\n    with z1(1) obtain b where b: \"glbound_in_of P x y b\"\n      using xy(1,2) P_has_glbs by fast\n    moreover have \"b \\<in> P.\\<^bold>\\<le>x\" \"b \\<in> P.\\<^bold>\\<le>y\"\n      using glbound_in_ofD_in[OF b] glbound_in_of_less_eq1[OF b]\n            glbound_in_of_less_eq2[OF b]\n      by    auto\n    ultimately show ?thesis\n      using     xy below_in_P_simplex_like \n                pseudominimal_in_below_in_less_eq_glbound[of P x _ y b]\n                simplex_like_below_in_above_pseudominimal_is_top[of x P]\n                simplex_like_below_in_above_pseudominimal_is_top[of y P]\n      unfolding poset_simplex_map_def\n      by        force\n  qed\nqed\n\nlemma OrderingSetIso_smap:\n  \"OrderingSetIso (\\<^bold>\\<le>) (\\<^bold><) (\\<subseteq>) (\\<subset>) P smap\"\nproof (rule OrderingSetMap.isoI)\n  show \"OrderingSetMap (\\<^bold>\\<le>) (\\<^bold><) (\\<subseteq>) (\\<subset>) P smap\"\n    using poset_simplex_map_def below_in_P_simplex_like\n          poset_to_PosetComplex_OrderingSetMap\n    by    simp\nnext\n  fix x y assume xy: \"x\\<in>P\" \"y\\<in>P\" \"smap x \\<subseteq> smap y\"\n  from xy(2) have \"simplex_like (P.\\<^bold>\\<le>y)\" using below_in_P_simplex_like by fast\n  from this obtain g and A::\"nat set\"\n    where \"OrderingSetIso (\\<^bold>\\<le>) (\\<^bold><) (\\<subseteq>) (\\<subset>) (P.\\<^bold>\\<le>y) g\"\n          \"g`(P.\\<^bold>\\<le>y) = Pow A\"\n    using simplex_likeD_iso[of \"P.\\<^bold>\\<le>y\"]\n    by    auto\n  with xy show \"x\\<^bold>\\<le>y\"\n    using poset_simplex_map_def collect_pseudominimals_below_in_eq[of y P g]\n          collect_pseudominimals_below_in_poset[of P y g]\n          inj_onD[OF inj_on_smap, of \"the_inv_into (P.\\<^bold>\\<le>y) g (\\<Union>(g ` smap x))\" x]\n          collect_pseudominimals_below_in_less_eq_top[of P y g A \"smap x\"]\n    by    simp\nqed (rule inj_on_smap)\n\nlemmas rev_ordsetmap_smap =\n  OrderingSetIso.rev_ordsetmap[OF OrderingSetIso_smap]\n\nend (* context ComplexLikePoset *)\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/Buildings/Simplicial.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8459424373085146, "lm_q2_score": 0.8856314738181875, "lm_q1q2_score": 0.7491932475188895}}
{"text": "theory Chapter3\n  imports Main\nbegin\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 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\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) v = (if n=0 then v else Plus (N n) v)\" |\n\"plus v (N n) = (if n=0 then v else Plus v (N n))\" |\n\"plus v1 v2 = Plus v1 v2\"\n\nlemma aval_plus [simp]: \"aval (plus a1 a2) s = aval a1 s + aval a2 s\"\n  apply (induction a1 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 a1 a2\"\n\nlemma \"aval (asimp a) s = aval a s\"\n  apply (induction a)\n    apply auto\n  done\n\nfun has_ints :: \"aexp \\<Rightarrow> bool\" where\n\"has_ints (N n) = True\" |\n\"has_ints (V x) = False\" |\n\"has_ints (Plus a b) = disj (has_ints a) (has_ints b)\"\n\nfun minimally_int_free :: \"aexp \\<Rightarrow> bool\" where\n\"minimally_int_free (N n) = (if n=0 then True else False)\" |\n\"minimally_int_free (V x) = True\" |\n\"minimally_int_free (Plus a b) = conj (~ (has_ints a)) (~ (has_ints b))\"\n\nfun has_vars :: \"aexp \\<Rightarrow> bool\" where\n\"has_vars (N n) = False\" |\n\"has_vars (V x) = True\" |\n\"has_vars (Plus a b) = disj (has_vars a) (has_vars b)\"\n\nfun optimal :: \"aexp \\<Rightarrow> bool\" where\n\"optimal (Plus (N n1) (N n2)) = False\" |\n\"optimal (N n) = True\" |\n\"optimal (V x) = True\" |\n\"optimal (Plus a1 a2) = conj (optimal a1) (optimal a2)\"\n\ntheorem asimp_const_optimal: \"optimal (asimp_const a)\"\n  apply (induction a)\n    apply (auto split: aexp.split)\n  done\n\nfun var_count :: \"aexp \\<Rightarrow> nat\" where\n\"var_count (N n) = 0\" |\n\"var_count (V v) = 1\" |\n\"var_count (Plus a b) = (var_count a) + (var_count b)\"\n\nfun int_count :: \"aexp \\<Rightarrow> nat\" where\n\"int_count (N n) = 1\" |\n\"int_count (V v) = 0\" |\n\"int_count (Plus a b) = (int_count a) + (int_count b)\"\n\nfun val_count :: \"aexp \\<Rightarrow> nat\" where\n\"val_count (N n) = 1\" |\n\"val_count (V v) = 1\" |\n\"val_count (Plus a b) = (val_count a) + (val_count b)\"\n\nlemma val_count_is_int_plus_var_count: \"val_count a = (int_count a) + (var_count a)\"\n  apply (induction a)\n    apply auto\n  done\n\nlemma val_count_gt_zero [simp]: \"val_count a > 0\"\n  apply (induction a)\n    apply auto\n  done\n\nlemma val_count_addend_lt_sum [simp]: \"val_count (Plus a b) > val_count a\"\n  apply (induction a)\n    apply auto\n  done\n\nfunction (sequential) full_asimp_step :: \"aexp \\<Rightarrow> aexp \\<Rightarrow> int \\<Rightarrow> aexp\" where\n\"full_asimp_step (N n1) (N n2) n3 = N (n1 + n2 + n3)\" |\n\"full_asimp_step (N n1) (V v) n2 = Plus (V v) (N (n1 + n2))\" |\n\"full_asimp_step (N n1) (Plus a b) n2 = full_asimp_step a b (n1 + n2)\" |\n\"full_asimp_step (V v) (N n1) n2 = Plus (V v) (N (n1 + n2))\" |\n\"full_asimp_step (V v1) (V v2) n = Plus (V v1) (Plus (V v2) (N n))\" |\n\"full_asimp_step (V v) (Plus a b) n = Plus (V v) (full_asimp_step a b n)\" |\n\"full_asimp_step (Plus a b) (N n1) n2 = full_asimp_step a b (n1 + n2)\" |\n\"full_asimp_step (Plus a b) (V v) n = Plus (V v) (full_asimp_step a b n)\" |\n\"full_asimp_step (Plus a b) (Plus c d) n = full_asimp_step a (Plus b (Plus c d)) n\"\nby pat_completeness auto\ntermination full_asimp_step\n  apply (relation \"measures [\\<lambda>(a,b,n). (val_count (Plus a b)), \\<lambda>(a,b,n). (var_count (Plus a b)), \\<lambda>(a,b,n). (val_count a)]\")\n  apply auto\n  done\n\nlemma aval_full_asimp_step [simp]: \"aval (full_asimp_step a b n) s = (aval a s) + (aval b s) + n\"\n  apply (induction a b n arbitrary: s rule: full_asimp_step.induct)\n          apply auto\n  done\n\nlemma int_count_full_asimp_step [simp]: \"int_count (full_asimp_step a b n) < 2\"\n  apply (induction a b n rule: full_asimp_step.induct)\n          apply auto\n  done\n\nlemma optimal_full_asimp_step [simp]: \"optimal (full_asimp_step a b n)\"\n  apply (induction a b n rule: full_asimp_step.induct)\n  apply auto\n  done\n\nfun full_asimp :: \"aexp \\<Rightarrow> aexp\" where\n\"full_asimp a = full_asimp_step a (N 0) 0\"\n\ntheorem full_asimp_example: \"full_asimp (Plus (N 1) (Plus (V x) (N 2))) = Plus (V x) (N 3)\"\n  apply auto\n  done\n\ntheorem aval_full_asimp: \"aval (full_asimp a) s = aval a s\"\n  apply (induction a arbitrary: s)\n    apply auto\n  done\n\nlemma int_count_full_asimp: \"int_count (full_asimp a) < 2\"\n  apply (induction a)\n    apply auto\n  done\n\nlemma optimal_full_asimp: \"optimal (full_asimp a)\"\n  apply (induction a rule: full_asimp.induct)\n  apply auto\n  done\n\nfun subst :: \"vname \\<Rightarrow> aexp \\<Rightarrow> aexp \\<Rightarrow> aexp\" where\n\"subst v a (N n) = N n\" |\n\"subst v1 a (V v2) = (if v1=v2 then a else (V v2))\" |\n\"subst v a (Plus b c) = Plus (subst v a b) (subst v a c)\"\n\ntheorem substitution_\n\ntheorem substitution_distributivity: \"aval a1 s = aval a2 s \\<Longrightarrow> aval (subst x a1 e) s = aval (subst x a2 e) s\"\n  apply auto\n  done\n\ndatatype mexp = N int | V vname | Plus mexp mexp | Times mexp mexp\n\nfun mval :: \"mexp \\<Rightarrow> state \\<Rightarrow> val\" where\n\"mval (N n) s = n\" |\n\"mval (V v) s = s v\" |\n\"mval (Plus a b) s = (mval a s) + (mval b s)\" |\n\"mval (Times a b) s = (mval a s) * (mval b s)\"\n\nfun mplus :: \"mexp \\<Rightarrow> mexp \\<Rightarrow> mexp\" where\n\"mplus (N n1) (N n2) = N (n1 + n2)\" |\n\"mplus (N n) a = (if n=0 then a else (Plus (N n) a))\" |\n\"mplus a (N n) = (if n=0 then a else (Plus a (N n)))\" |\n\"mplus a b = Plus a b\"\n\nfun mtimes :: \"mexp \\<Rightarrow> mexp \\<Rightarrow> mexp\" where\n\"mtimes (N n1) (N n2) = N (n1 * n2)\" |\n\"mtimes (N n) a = (if n=1 then a else if n=0 then (N 0) else (Times (N n) a))\" |\n\"mtimes a (N n) = (if n=1 then a else if n=0 then (N 0) else (Times a (N n)))\" |\n\"mtimes a b = Times a b\"\n\nfun msimp :: \"mexp \\<Rightarrow> mexp\" where\n\"msimp (N n) = N n\" |\n\"msimp (V v) = V v\" |\n\"msimp (Plus a b) = mplus (msimp a) (msimp b)\" |\n\"msimp (Times a b) = mtimes (msimp a) (msimp b)\"\n\nlemma mval_mplus [simp]: \"mval (mplus a b) s = (mval a s) + (mval b s)\"\n  apply (induction a rule: mplus.induct)\n     apply auto\n  done\n\nlemma mval_mtimes [simp]: \"mval (mtimes a b) s = (mval a s) * (mval b s)\"\n  apply (induction a rule: mtimes.induct)\n  apply auto\n  done\n\ntheorem mval_msimp: \"mval (msimp a) s = mval a s\"\n  apply (induction a)\n     apply auto\n  done\n\nfun moptimal :: \"mexp \\<Rightarrow> bool\" where\n\"moptimal (Plus (N n1) (N n2)) = False\" |\n\"moptimal (Times (N n1) (N n2)) = False\" |\n\"moptimal (Plus a b) = conj (moptimal a) (moptimal b)\" |\n\"moptimal (Times a b) = conj (moptimal a) (moptimal b)\" |\n\"moptimal a = True\"\n\nlemma moptimal_mplus [simp]: \"(conj (moptimal a) (moptimal b)) \\<Longrightarrow> moptimal (mplus a b)\"\n  apply (induction a b rule: mplus.induct)\n  apply auto\n  done\n\nlemma moptimal_mtimes [simp]: \"(conj (moptimal a) (moptimal b)) \\<Longrightarrow> moptimal (mtimes a b)\"\n  apply (induction a b rule: mtimes.induct)\n  apply auto\n  done\n\ntheorem moptimal_msimp: \"moptimal (msimp a)\"\n  apply (induction a)\n  apply auto\n  done\n\ndatatype cexp = N int |\n  V vname |\n  Plus cexp cexp |\n  Times cexp cexp |\n  Minus cexp cexp |\n  Divide cexp cexp |\n  Incr vname |\n  Decr vname\n\nfun cval :: \"cexp \\<Rightarrow> state \\<Rightarrow> (val \\<times> state) option\" where\n\"cval (N n) s = Some (n, s)\" |\n\"cval (V v) s = Some (s v, s)\" |\n\"cval (Incr v) s = Some (s v, s (v:=(s v)+1))\" |\n\"cval (Decr v) s = Some (s v, s (v:=(s v)-1))\" |\n\"cval (Plus a b) s = Some (\n  (fst (the (cval a s))) + (fst (the (cval b (snd (the (cval a s)))))),\n  snd (the (cval b (snd (the (cval a s)))))\n)\" |\n\"cval (Minus a b) s = Some (\n  (fst (the (cval a s))) - (fst (the (cval b (snd (the (cval a s)))))),\n  snd (the (cval b (snd (the (cval a s)))))\n)\" |\n\"cval (Times a b) s = Some (\n  (fst (the (cval a s))) * (fst (the (cval b (snd (the (cval a s)))))),\n  snd (the (cval b (snd (the (cval a s)))))\n)\" |\n\"cval (Divide a b) s = (\n  if b=(N 0)\n  then None\n  else Some (\n    (fst (the (cval a s))) div (fst (the (cval b (snd (the (cval a s)))))),\n    snd (the (cval b (snd (the (cval a s)))))\n  )\n)\"\n\nfun cval_last :: \"cexp list \\<Rightarrow> state \\<Rightarrow> (val \\<times> state)\" where\n\"cval_last Nil s = (0,s)\" |\n\"cval_last (Cons a Nil) s = the (cval a s)\" |\n\"cval_last (Cons a l) s = cval_last l (snd (the (cval a s)))\"\n\nlemma incr_is_add_one [simp]: \"\nfst (cval_last [(Incr v), (V v)] s)\n= fst (the (cval (Plus (V v) (N 1)) s))\n\"\n  apply auto\n  done\n\nlemma decr_is_minus_one [simp]: \"\nfst (cval_last [(Decr v), (V v)] s)\n= fst (the (cval (Minus (V v) (N 1)) s))\n\"\n  apply auto\n  done\n\nlemma incr_decr_is_noop [simp]: \"snd (cval_last [(Incr v), (Decr v)] s) = s\"\n  apply auto\n  done\n\nlemma decr_incr_is_noop [simp]: \"snd (cval_last [(Decr v), (Incr v)] s) = s\"\n  apply auto\n  done\n\nlemma subeval_order_behavior_l [simp]: \"the (cval (Plus (Incr v) (V v)) s) = (fst (the (cval (Plus (Plus (V v) (V v)) (N 1)) s)), snd (the (cval (Incr v) s)))\"\n  apply auto\n  done\n\nlemma subeval_order_behavior_r [simp]: \"the (cval (Plus (V v) (Incr v)) s) = (fst (the (cval (Plus (V v) (V v)) s)), snd (the (cval (Incr v) s)))\"\n  apply auto\n  done\n\nlemma plus_minus_is_zero [simp]: \"cval (Minus (Plus (V a) (V b)) (V b)) s = cval (V a) s\"\n  apply auto\n  done\n\nlemma times_divide_is_one [simp]: \"(fst (the (cval (V b) s)) \\<noteq> 0) \\<Longrightarrow> (cval (Divide (Times (V a) (V b)) (V b)) s = cval (V a) s)\"\n  apply auto\n  done\n\nlemma times_and_plus_related [simp]: \"cval (Times (V a) (N 2)) s = cval (Plus (V a) (V a)) s\"\n  apply auto\n  done\n\ndatatype lexp = N int |\n  V vname |\n  Plus lexp lexp |\n  Let vname lexp lexp\n\nfun lval :: \"lexp \\<Rightarrow> state \\<Rightarrow> val\" where\n\"lval (N n) s = n\" |\n\"lval (V v) s = s v\" |\n\"lval (Plus a b) s = (lval a s) + (lval b s)\" |\n\"lval (Let v t e) s = lval e (s (v:=(lval t s)))\"\n\nlemma let_identity: \"lval (Let x a (V x)) s = lval a s\"\n  apply auto\n  done\n\nfun inline :: \"lexp \\<Rightarrow> aexp\" where\n\"inline (lexp.N n) = aexp.N n\" |\n\"inline (lexp.V v) = aexp.V v\" |\n\"inline (lexp.Plus a b) = aexp.Plus (inline a) (inline b)\" |\n\"inline (lexp.Let v t e) = subst v (inline t) (inline e)\"\n\ntheorem lval_inline [simp]: \"aval (inline a) s = lval a s\"\n  apply (induction a arbitrary: s rule: inline.induct)\n  apply auto\n  done\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 b) s = b\" |\n\"bval (Not b) s = (~ (bval b s))\" |\n\"bval (And a b) s = conj (bval a s) (bval b s)\" |\n\"bval (Less a b) s = ((aval a s) < (aval b 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\n(* book says and, but that's a keyword *)\nfun andd :: \"bexp \\<Rightarrow> bexp \\<Rightarrow> bexp\" where\n\"andd (Bc True) b = b\" |\n\"andd b (Bc True) = b\" |\n\"andd (Bc False) b = Bc False\" |\n\"andd b (Bc False) = Bc False\" |\n\"andd a b = And a b\"\n\n(* it is necessary to specify aexp.N since I created lexp.N as well *)\nfun less :: \"aexp \\<Rightarrow> aexp \\<Rightarrow> bexp\" where\n\"less (aexp.N a) (aexp.N b) = Bc (a < b)\" |\n\"less a b = Less a b\"\n\nfun bsimp :: \"bexp \\<Rightarrow> bexp\" where\n\"bsimp (Bc b) = Bc b\" |\n\"bsimp (Not b) = not (bsimp b)\" |\n\"bsimp (And a b) = andd (bsimp a) (bsimp b)\" |\n\"bsimp (Less a b) = less (asimp a) (asimp b)\"\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 (Less b a)\"\n\ntheorem bval_eq [simp]: \"bval (Eq a b) s = ((aval a s) = (aval b s))\"\n  apply auto\n  done\n\ntheorem bval_le [simp]: \"bval (Le a b) s = ((aval a s) \\<le> (aval b s))\"\n  apply auto\n  done\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) s = b\" |\n\"ifval (If g a b) s = (\n  if (ifval g s)\n  then (ifval a s)\n  else (ifval b s)\n)\" |\n\"ifval (Less2 a b) s = ((aval a s) < (aval b 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 a b) = Less2 a b\"\n\nfun if2bexp :: \"ifexp \\<Rightarrow> bexp\" where\n\"if2bexp (Bc2 b) = (Bc b)\" |\n\"if2bexp (If g a b) =\nAnd\n  (Not (And\n    (if2bexp g)\n    (Not (if2bexp a))\n  ))\n  (Not (And\n    (Not (if2bexp g))\n    (Not (if2bexp b))\n   ))\n\" |\n\"if2bexp (Less2 a b) = Less a b\"\n\ntheorem b2ifexp_if2exp_noop [simp]: \"ifval (b2ifexp (if2bexp a)) s = ifval a s\"\n  apply (induction a arbitrary: s)\n  apply auto\n  done\n\ntheorem if2bexp_b2ifexp_noop [simp]: \"bval (if2bexp (b2ifexp a)) s = bval a s\"\n  apply (induction a arbitrary: s)\n  apply auto\n  done\n\ndatatype pbexp =\n  VAR vname |\n  NOT pbexp |\n  AND pbexp pbexp |\n  OR pbexp pbexp\n\ntype_synonym pbstate = \"vname \\<Rightarrow> bool\"\n\nfun pbval :: \"pbexp \\<Rightarrow> pbstate \\<Rightarrow> bool\" where\n\"pbval (VAR v) bs = bs v\" |\n\"pbval (NOT b) bs = (~ (pbval b bs))\" |\n\"pbval (AND a b) bs = conj (pbval a bs) (pbval b bs)\" |\n\"pbval (OR a b) bs = disj (pbval a bs) (pbval b bs)\"\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 b) = False\" |\n\"is_nnf (AND a b) = conj (is_nnf a) (is_nnf b)\" |\n\"is_nnf (OR a b) = conj (is_nnf a) (is_nnf b)\"\n\nfun nnf :: \"pbexp \\<Rightarrow> pbexp\" where\n\"nnf (VAR v) = VAR v\" |\n\"nnf (NOT (VAR v)) = NOT (VAR v)\" |\n\"nnf (NOT (NOT b)) = nnf b\" |\n\"nnf (NOT (AND a b)) = OR (nnf (NOT a)) (nnf (NOT b))\" |\n\"nnf (NOT (OR a b)) = AND (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\ntheorem nnf_preserves_pbval [simp]: \"pbval (nnf b) bs = pbval b bs\"\n  apply (induction b rule: nnf.induct)\n  apply auto\n  done\n\ntheorem nnf_is_nnf [simp]: \"is_nnf (nnf a)\"\n  apply (induction a rule: nnf.induct)\n  apply auto\n  done\n\nfun is_dnf_conj :: \"pbexp \\<Rightarrow> bool\" where\n\"is_dnf_conj (VAR v) = True\" |\n\"is_dnf_conj (NOT (VAR v)) = True\" |\n\"is_dnf_conj (NOT b) = False\" |\n\"is_dnf_conj (AND a b) = conj (is_dnf_conj a) (is_dnf_conj b)\" |\n\"is_dnf_conj (OR a b) = False\"\n\nfun is_dnf :: \"pbexp \\<Rightarrow> bool\" where\n\"is_dnf (VAR v) = True\" |\n\"is_dnf (NOT (VAR v)) = True\" |\n\"is_dnf (NOT b) = False\" |\n\"is_dnf (AND a b) = conj (is_dnf_conj a) (is_dnf_conj b)\" |\n\"is_dnf (OR a b) = conj (is_dnf a) (is_dnf b)\"\n\nlemma is_dnf_not_implies_is_dnf_conj_not [simp]: \"is_dnf (NOT b) \\<Longrightarrow> is_dnf_conj (NOT b)\"\n  apply (induction b)\n  apply auto\n  done\n\nlemma is_nnf_not_implies_is_dnf_not [simp]: \"is_nnf (NOT b) \\<Longrightarrow> is_dnf (NOT b)\"\n  apply (induction b)\n  apply auto\n  done\n\nfun dist_conj_over_dnfs :: \"pbexp \\<Rightarrow> pbexp \\<Rightarrow> pbexp\" where\n\"dist_conj_over_dnfs (OR a b) c = OR (dist_conj_over_dnfs a c) (dist_conj_over_dnfs b c)\" |\n\"dist_conj_over_dnfs a (OR b c) = OR (dist_conj_over_dnfs a b) (dist_conj_over_dnfs a c)\" |\n\"dist_conj_over_dnfs a b = AND a b\"\n\nlemma dist_conj_over_dnfs_preserves_val [simp]: \"pbval (dist_conj_over_dnfs a b) bs = pbval (AND a b) bs\"\n  apply (induction a b rule: dist_conj_over_dnfs.induct)\n  apply auto\n  done\n\nlemma dist_conj_over_dnfs_preserves_dnf [simp]: \"(conj (is_dnf a) (is_dnf b)) \\<Longrightarrow> is_dnf (dist_conj_over_dnfs a b)\"\n  apply (induction a b rule: dist_conj_over_dnfs.induct)\n  apply auto\n  done\n\nfun dnf_of_nnf :: \"pbexp \\<Rightarrow> pbexp\" where\n\"dnf_of_nnf (VAR v) = VAR v\" |\n\"dnf_of_nnf (NOT b) = NOT b\" |\n\"dnf_of_nnf (AND a b) = dist_conj_over_dnfs (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\ntheorem dnf_of_nnf_preserves_val [simp]: \"pbval (dnf_of_nnf b) bs = pbval b bs\"\n  apply (induction b)\n  apply auto\n  done\n\ntheorem dnf_of_nnf_turns_nnf_into_dnf [simp]: \"is_nnf b \\<Longrightarrow> is_dnf (dnf_of_nnf b)\"\n  apply (induction b rule: dnf_of_nnf.induct)\n  apply auto\n  done\n\nlemma full_dnf_preserves_val [simp]: \"pbval (dnf_of_nnf (nnf b)) bs = pbval b bs\"\n  apply auto\n  done\n\ndatatype instr =\n  LOADI val |\n  LOAD vname |\n  ADD\n\ntype_synonym stack = \"val list\"\n\nabbreviation hd2 :: \"'a list \\<Rightarrow> 'a\" where\n\"hd2 xs \\<equiv> hd (tl xs)\"\n\nabbreviation tl2 :: \"'a list \\<Rightarrow> 'a list\" 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 v) s stk = Some (s (v) # stk)\" |\n\"exec1 ADD _ (Cons a (Cons b stk)) = Some ((a + b) # stk)\" |\n\"exec1 ADD _ stk = None\"\n\nfun exec :: \"instr list \\<Rightarrow> state \\<Rightarrow> stack option \\<Rightarrow> stack option\" where\n\"exec [] _ (Some stk) = Some stk\" |\n\"exec is s None = None\" |\n\"exec (i#is) s (Some stk) = exec is s (exec1 i s stk)\"\n\nfun comp :: \"aexp \\<Rightarrow> instr list\" where\n\"comp (aexp.N n) = [(LOADI n)]\" |\n\"comp (aexp.V v) = [(LOAD v)]\" |\n\"comp (aexp.Plus a b) = (comp a) @ (comp b) @ [(ADD)]\"\n\ntheorem seq_instr_exec_equiv_recurs_stack_eval [simp]: \"exec (a @ b) s some_stk = exec b s (exec a s some_stk)\"\n  apply (induction a s some_stk arbitrary: b rule: exec.induct)\n   apply auto\n  done\n\ntheorem compiled_execution_matches_evaluation [simp]: \"exec (comp a) s (Some stk) = Some (aval a s#stk)\"\n  apply (induction a arbitrary: stk)\n  apply auto\n  done\n\ntype_synonym reg = nat\n\ndatatype rinstr =\n  RLOADI int reg |\n  RLOAD vname reg |\n  RADD reg reg\n\ntype_synonym rstate = \"reg \\<Rightarrow> int\"\n\n(* The book says exec1 :: \"instr \\<Rightarrow> state \\<Rightarrow> (reg \\<Rightarrow> int) \\<Rightarrow> reg \\<Rightarrow> int\",\n   but exec isn't going to know which register has been set without a deeper spec,\n   which would defeat the purpose of having a separate exec1 in the first place. *)\nfun rexec1 :: \"rinstr \\<Rightarrow> state \\<Rightarrow> rstate \\<Rightarrow> rstate\" where\n\"rexec1 (RLOADI i r) _ rs = (rs (r:=i))\" |\n\"rexec1 (RLOAD v r) s rs = (rs (r:=s v))\" |\n\"rexec1 (RADD r r2) _ rs = (rs (r:=(rs r) + (rs r2)))\"\n\nlemma rexec1_radd_behavior [simp]: \"(conj (a = rs r1) (b = rs r2)) \\<Longrightarrow> ((rexec1 (RADD r1 r2) s rs) r1 = a + b)\"\n  apply auto\n  done\n\nfun rexec :: \"rinstr list \\<Rightarrow> state \\<Rightarrow> rstate \\<Rightarrow> rstate\" where\n\"rexec [] _ rs = rs\" |\n\"rexec (i#is) s rs = rexec is s (rexec1 i s rs)\"\n\nfun rcomp :: \"aexp \\<Rightarrow> reg \\<Rightarrow> rinstr list\" where\n\"rcomp (aexp.N n) r = [(RLOADI n r)]\" |\n\"rcomp (aexp.V v) r = [(RLOAD v r)]\" |\n\"rcomp (aexp.Plus a b) r = (rcomp a r) @ (rcomp b (r+1)) @ [(RADD r (r+1))]\"\n\nlemma rexec_seq_instr_equals_seq_rexec [simp]: \"(rexec (a @ b) s rs) rr = (rexec b s (rexec a s rs)) rr\"\n  apply (induction a s rs arbitrary: b rr rule: rexec.induct)\n  apply auto\n  done\n\nlemma smaller_registers_untouched [simp]: \"(rl < r) \\<Longrightarrow> ((rexec (rcomp a r) s rs) rl = rs rl)\"\n  apply (induction a r arbitrary: s rs rl rule: rcomp.induct)\n  apply auto\n  done\n\nlemma rcomp_preserves_incr_regs [simp]: \"(rexec (a @ (rcomp b r)) s rs) r = (rexec (rcomp b r) s rs) r\"\n  apply (induction b r arbitrary: a s rs rule: rcomp.induct)\n  apply auto\n  done\n\ntheorem rexec_rcomp_equals_aval [simp]: \"rexec (rcomp a r) s rs r = aval a s\"\n  apply (induction a r arbitrary: s rs rule: rcomp.induct)\n  apply auto\n  done\n\ndatatype instr0 =\n  LDI0 val |\n  LD0 vname |\n  MV0 reg |\n  ADD0 reg\n\nfun exec01 :: \"instr0 \\<Rightarrow> state \\<Rightarrow> rstate \\<Rightarrow> rstate\" where\n\"exec01 (LDI0 i) _ rs = rs (0:=i)\" |\n\"exec01 (LD0 v) s rs = rs (0:=s v)\" |\n\"exec01 (MV0 r) _ rs = rs (r:=rs 0)\" |\n\"exec01 (ADD0 r) _ rs = rs (0:=(rs 0) + (rs r))\"\n\nlemma exec01_mov0_behavior [simp]: \"(exec01 (MV0 r) s rs) r = rs 0\"\n  apply auto\n  done\n\n(* \"is\" is a keyword in some circumstances.\n   While using it as a variable name as described in the book\n   is sometimes not a problem, at other times it can be a problem.\n   As such, it seems prudent to always avoid using \"is\" as a variable name. *)\nfun exec0 :: \"instr0 list \\<Rightarrow> state \\<Rightarrow> rstate \\<Rightarrow> rstate\" where\n\"exec0 [] _ rs = rs\" |\n\"exec0 (i#ins) s rs = exec0 ins s (exec01 i s rs)\"\n\nfun comp0_below :: \"aexp \\<Rightarrow> reg \\<Rightarrow> instr0 list\" where\n\"comp0_below (aexp.N n) r = [(LDI0 n)]\" |\n\"comp0_below (aexp.V v) r = [(LD0 v)]\" |\n\"comp0_below (aexp.Plus a b) r = (comp0_below a (r+2)) @ [(MV0 (r+1))] @ (comp0_below b (r+2)) @ [(ADD0 (r+1))]\"\n\nlemma exec0_seq_instr_equals_seq_exec0 [simp]: \"exec0 (a @ b) s rs = exec0 b s (exec0 a s rs)\"\n  apply (induction a s rs arbitrary: b rule: exec0.induct)\n  apply auto\n  done\n\nlemma comp0_below_skips_regs [simp]: \"(conj (rl \\<noteq> 0) (rl < r)) \\<Longrightarrow> ((exec0 (comp0_below a r) s rs) rl = rs rl)\"\n  apply (induction a r arbitrary: rl rs s rule: comp0_below.induct)\n  apply auto\n  done\n\nlemma append_mv0_behavior [simp]: \"(exec0 (ins @ [(MV0 r)]) s rs) r = (exec0 ins s rs) 0\"\n  apply auto\n  done\n\nlemma exec0_comp0_below_equals_aval [simp]: \"(exec0 (comp0_below a r) s rs) 0 = aval a s\"\n  apply (induction a r arbitrary: s rs rule: comp0_below.induct)\n  apply auto\n  done\n\nfun comp0 :: \"aexp \\<Rightarrow> instr0 list\" where\n\"comp0 a = comp0_below a 0\"\n\ntheorem exec0_comp0_equals_aval [simp]: \"(exec0 (comp0 a) s rs) 0 = aval a s\"\n  apply auto\n  done\n\nend\n", "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/ch3/Chapter3.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797051879431, "lm_q2_score": 0.822189123986562, "lm_q1q2_score": 0.7491620436028087}}
{"text": "theory Submission\n  imports Defs\nbegin\n\nfun double :: \"'a list \\<Rightarrow> 'a list\"  where\n  \"double [] = []\" |\n  \"double (x#xs) = x#x#(double xs)\"\n\nvalue \"double [1,2,(3::nat)] = [1,1,2,2,3,3]\"\n\ntheorem double_len: \"length (double xs) = 2 * length xs\"\n  by (induction xs) simp+\n\nlemma double_snoc:\"double (snoc xs x) = snoc ( snoc (double xs) x) x\"\n  by (induction xs) auto\n\ntheorem reverse_double: \"reverse (double xs) = double (reverse xs)\"\n  by (induction xs) (simp add: double_snoc)+\n\nlemma double_add_tl:\"(double xs) @ [a, a] = double (xs @ [a])\"\n  by (induction xs) simp+\n\ntheorem rev_double: \"rev (double xs) = double (rev xs)\"\n  by (induction xs) (simp add: double_add_tl)+\n\nend", "meta": {"author": "VTrelat", "repo": "P4F", "sha": "389c6e9087c354320335d1da28b76962b45754b6", "save_path": "github-repos/isabelle/VTrelat-P4F", "path": "github-repos/isabelle/VTrelat-P4F/P4F-389c6e9087c354320335d1da28b76962b45754b6/ListDouble/Submission.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9059898254600902, "lm_q2_score": 0.8267117876664789, "lm_q1q2_score": 0.7489924682137524}}
{"text": "(*  File:       Evaluation_Function.thy\n    Copyright   2021  Karlsruhe Institute of Technology (KIT)\n*)\n\\<^marker>\\<open>creator \"Stephan Bohr, Karlsruhe Institute of Technology (KIT)\"\\<close>\n\\<^marker>\\<open>contributor \"Michael Kirsten, Karlsruhe Institute of Technology (KIT)\"\\<close>\n\nsection \\<open>Evaluation Function\\<close>\n\ntheory Evaluation_Function\n  imports \"Social_Choice_Types/Profile\"\nbegin\n\ntext \\<open>\n  This is the evaluation function. From a set of currently eligible\n  alternatives, the evaluation function computes a numerical value that is then\n  to be used for further (s)election, e.g., by the elimination module.\n\\<close>\n\nsubsection \\<open>Definition\\<close>\n\ntype_synonym 'a Evaluation_Function = \"'a  \\<Rightarrow> 'a set \\<Rightarrow> 'a Profile \\<Rightarrow> nat\"\n\nsubsection \\<open>Property\\<close>\n\ntext \\<open>\n  An Evaluation function is Condorcet-rating iff the following holds:\n  If a Condorcet Winner w exists, w and only w has the highest value.\n\\<close>\n\ndefinition condorcet_rating :: \"'a Evaluation_Function \\<Rightarrow> bool\" where\n  \"condorcet_rating f \\<equiv>\n    \\<forall> A p w . condorcet_winner A p w \\<longrightarrow>\n      (\\<forall> l \\<in> A . l \\<noteq> w \\<longrightarrow> f l A p < f w A p)\"\n\nsubsection \\<open>Theorems\\<close>\n\ntext \\<open>\n  If e is Condorcet-rating, the following holds:\n  If a Condorcet Winner w exists, w has the maximum evaluation value.\n\\<close>\n\ntheorem cond_winner_imp_max_eval_val:\n  assumes\n    rating: \"condorcet_rating e\" and\n    f_prof: \"finite_profile A p\" and\n    winner: \"condorcet_winner A p w\"\n  shows \"e w A p = Max {e a A p | a. a \\<in> A}\"\nproof -\n  let ?set = \"{e a A p | a. a \\<in> A}\" and\n      ?eMax = \"Max {e a A p | a. a \\<in> A}\" and\n      ?eW = \"e w A p\"\n  from f_prof\n  have 0: \"finite ?set\"\n    by simp\n  have 1: \"?set \\<noteq> {}\"\n    using condorcet_winner.simps winner\n    by fastforce\n  have 2: \"?eW \\<in> ?set\"\n    using CollectI condorcet_winner.simps winner\n    by (metis (mono_tags, lifting))\n  have 3: \"\\<forall> e \\<in> ?set . e \\<le> ?eW\"\n  proof (safe)\n    fix a :: \"'a\"\n    assume aInA: \"a \\<in> A\"\n    have \"\\<forall>n na. (n::nat) \\<noteq> na \\<or> n \\<le> na\"\n      by simp\n    with aInA show \"e a A p \\<le> e w A p\"\n      using less_imp_le rating winner\n      unfolding condorcet_rating_def\n      by (metis (no_types))\n  qed\n  from 2 3 have 4:\n    \"?eW \\<in> ?set \\<and> (\\<forall>a \\<in> ?set. a \\<le> ?eW)\"\n    by blast\n  from 0 1 4 Max_eq_iff\n  show ?thesis\n    by (metis (no_types, lifting))\nqed\n\ntext \\<open>\n  If e is Condorcet-rating, the following holds:\n  If a Condorcet Winner w exists, a non-Condorcet\n  winner has a value lower than the maximum\n  evaluation value.\n\\<close>\n\ntheorem non_cond_winner_not_max_eval:\n  assumes\n    rating: \"condorcet_rating e\" and\n    f_prof: \"finite_profile A p\" and\n    winner: \"condorcet_winner A p w\" and\n    linA: \"l \\<in> A\" and\n    loser: \"w \\<noteq> l\"\n  shows \"e l A p < Max {e a A p | a. a \\<in> A}\"\nproof -\n  have \"e l A p < e w A p\"\n    using linA loser rating winner\n    unfolding condorcet_rating_def\n    by metis\n  also have \"e w A p = Max {e a A p |a. a \\<in> A}\"\n    using cond_winner_imp_max_eval_val f_prof rating winner\n    by fastforce\n  finally show ?thesis\n    by simp\nqed\n\nend\n", "meta": {"author": "VeriVote", "repo": "verifiedVotingRuleConstruction", "sha": "17bf689350c733dc7b419f4924d099a0e65de036", "save_path": "github-repos/isabelle/VeriVote-verifiedVotingRuleConstruction", "path": "github-repos/isabelle/VeriVote-verifiedVotingRuleConstruction/verifiedVotingRuleConstruction-17bf689350c733dc7b419f4924d099a0e65de036/theories/Compositional_Structures/Basic_Modules/Component_Types/Evaluation_Function.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898102301019, "lm_q2_score": 0.8267117876664789, "lm_q1q2_score": 0.7489924556229416}}
{"text": "(*  Title:      SetIntervalStep.thy\n    Date:       Oct 2006\n    Author:     David Trachtenherz\n*)\n\nsection \\<open>Stepping through sets of natural numbers\\<close>\n\ntheory SetIntervalStep\nimports SetIntervalCut\nbegin\n\nsubsection \\<open>Function \\<open>inext\\<close> and \\<open>iprev\\<close> for stepping through natural sets\\<close>\n\ndefinition inext :: \"nat \\<Rightarrow> nat set \\<Rightarrow> nat\"\nwhere\n  \"inext n I \\<equiv> (\n    if (n \\<in> I \\<and> (I \\<down>> n \\<noteq> {}))\n    then iMin (I \\<down>> n)\n    else n)\"\n\ndefinition iprev :: \"nat \\<Rightarrow> nat set \\<Rightarrow> nat\"\nwhere\n  \"iprev n I \\<equiv> (\n    if (n \\<in> I \\<and> (I \\<down>< n \\<noteq> {}))\n    then Max (I \\<down>< n)\n    else n)\"\n\ntext \\<open>\\<open>inext\\<close> and \\<open>iprev\\<close> can be viewed as generalisations of \\<open>Suc\\<close> and \\<open>prev\\<close>\\<close>\n\nlemma inext_UNIV: \"inext n UNIV = Suc n\"\napply (simp add: inext_def cut_greater_def, safe)\napply (rule iMin_equality)\napply fastforce+\ndone\nlemma iprev_UNIV: \"iprev n UNIV = n - Suc 0\"\napply (simp add: iprev_def cut_less_def, safe)\napply (rule Max_equality)\napply fastforce+\ndone\n\nlemma inext_empty: \"inext n {} = n\"\nunfolding inext_def by simp\nlemma iprev_empty: \"iprev n {} = n\"\nunfolding iprev_def by simp\n\nlemma not_in_inext_fix: \"n \\<notin> I \\<Longrightarrow> inext n I = n\"\nunfolding inext_def by simp\nlemma not_in_iprev_fix: \"n \\<notin> I \\<Longrightarrow> iprev n I = n\"\nunfolding iprev_def by simp\n\n\nlemma inext_all_le_fix: \"\\<forall>x\\<in>I. x \\<le> n \\<Longrightarrow> inext n I = n\"\nunfolding inext_def by force\nlemma iprev_all_ge_fix: \"\\<forall>x\\<in>I. n \\<le> x \\<Longrightarrow> iprev n I = n\"\nunfolding iprev_def by force\n\nlemma inext_Max: \"finite I \\<Longrightarrow> inext (Max I) I = Max I\"\nunfolding inext_def cut_greater_def by (fastforce dest: Max_ge)\nlemma iprev_iMin: \"iprev (iMin I) I = iMin I\"\nunfolding iprev_def cut_less_def by fastforce\n\nlemma inext_ge_Max: \"\\<lbrakk> finite I; Max I \\<le> n \\<rbrakk> \\<Longrightarrow> inext n I = n\"\nunfolding inext_def cut_greater_def by (fastforce dest: Max_ge)\n\n\n\nlemma inext_singleton: \"inext n {a} = n\"\nunfolding inext_def by fastforce\n\nlemma iprev_singleton: \"iprev n {a} = n\"\nunfolding iprev_def by fastforce\n\nlemma inext_closed: \"n \\<in> I \\<Longrightarrow> inext n I \\<in> I\"\napply (clarsimp simp: inext_def)\napply (rule subsetD[OF cut_greater_subset])\napply (rule iMinI_ex2, assumption)\ndone\n\nlemma iprev_closed: \"n \\<in> I \\<Longrightarrow> iprev n I \\<in> I\"\napply (clarsimp simp: iprev_def)\napply (rule subsetD[of \"I \\<down>< n\"], fastforce)\nby (rule Max_in[OF nat_cut_less_finite])\n\nlemma inext_in_imp_in: \"inext n I \\<in> I \\<Longrightarrow> n \\<in> I\"\nby (case_tac \"n \\<in> I\", simp_all add: not_in_inext_fix)\n\nlemma inext_in_iff: \"(inext n I \\<in> I) = (n \\<in> I)\"\napply (rule iffI)\napply (rule inext_in_imp_in, assumption)\napply (rule inext_closed, assumption)\ndone\n\nlemma subset_inext_closed: \"\\<lbrakk> n \\<in> B; A \\<subseteq> B \\<rbrakk> \\<Longrightarrow> inext n A \\<in> B\"\napply (case_tac \"n \\<in> A\")\n apply (fastforce simp: inext_closed)\napply (simp add: not_in_inext_fix)\ndone\nlemma subset_inext_in_imp_in: \"\\<lbrakk> inext n A \\<in> B; A \\<subseteq> B \\<rbrakk> \\<Longrightarrow> n \\<in> B\"\napply (case_tac \"n \\<in> A\")\n apply fastforce\napply (simp add: not_in_inext_fix)\ndone\nlemma subset_inext_in_iff: \"A \\<subseteq> B \\<Longrightarrow> (inext n A \\<in> B) = (n \\<in> B)\"\napply (rule iffI)\napply (rule subset_inext_in_imp_in, assumption+)\napply (rule subset_inext_closed, assumption+)\ndone\n\nlemma iprev_in_imp_in: \"iprev n I \\<in> I \\<Longrightarrow> n \\<in> I\"\napply (case_tac \"n \\<in> I\")\napply (simp_all add: not_in_iprev_fix)\ndone\n\nlemma iprev_in_iff: \"(iprev n I \\<in> I) = (n \\<in> I)\"\napply (rule iffI)\napply (rule iprev_in_imp_in, assumption)\napply (rule iprev_closed, assumption)\ndone\n\nlemma subset_iprev_closed: \"\\<lbrakk> n \\<in> B; A \\<subseteq> B \\<rbrakk> \\<Longrightarrow> iprev n A \\<in> B\"\napply (case_tac \"n \\<in> A\")\n apply (fastforce simp: iprev_closed)\napply (simp add: not_in_iprev_fix)\ndone\n\nlemma subset_iprev_in_imp_in: \"\\<lbrakk> iprev n A \\<in> B; A \\<subseteq> B \\<rbrakk> \\<Longrightarrow> n \\<in> B\"\napply (case_tac \"n \\<in> A\")\n apply fastforce\napply (simp add: not_in_iprev_fix)\ndone\n\nlemma subset_iprev_in_iff: \"A \\<subseteq> B \\<Longrightarrow> (iprev n A \\<in> B) = (n \\<in> B)\"\napply (rule iffI)\napply (rule subset_iprev_in_imp_in, assumption+)\napply (rule subset_iprev_closed, assumption+)\ndone\n\nlemma inext_mono: \"n \\<le> inext n I\"\nby (simp add: inext_def i_cut_defs iMin_ge_iff)\n\ncorollary inext_neq_imp_less: \"n \\<noteq> inext n I \\<Longrightarrow> n < inext n I\"\nby (insert inext_mono[of n I], simp)\n\nlemma inext_mono2: \"\\<lbrakk> n \\<in> I; \\<exists>x\\<in>I. n < x \\<rbrakk> \\<Longrightarrow> n < inext n I\"\nby (fastforce simp add: inext_def i_cut_defs iMin_gr_iff)\n\nlemma inext_mono2_infin: \"\\<lbrakk> n \\<in> I; infinite I \\<rbrakk> \\<Longrightarrow> n < inext n I\"\napply (simp add: inext_def i_cut_defs iMin_gr_iff)\napply (fastforce simp: infinite_nat_iff_unbounded)\ndone\n\nlemma inext_mono2_fin: \"\\<lbrakk> n \\<in> I; finite I; n \\<noteq> Max I \\<rbrakk> \\<Longrightarrow> n < inext n I\"\napply (simp add: inext_def i_cut_defs iMin_gr_iff)\napply (blast intro: Max_ge Max_in)\ndone\n\nlemma inext_mono2_infin_fin: \"\n  \\<lbrakk> n \\<in> I; n \\<noteq> Max I \\<or> infinite I \\<rbrakk> \\<Longrightarrow> n < inext n I\"\nby (blast intro: inext_mono2_infin inext_mono2_fin)\n\nlemma inext_neq_iMin: \"\\<exists>x\\<in>I. n < x \\<Longrightarrow> inext n I \\<noteq> iMin I\"\napply (case_tac \"n \\<in> I\")\n prefer 2\n apply (simp add: not_in_inext_fix)\n apply (blast dest: iMinI)\napply (rule not_sym, rule less_imp_neq)\nby (rule le_less_trans[OF iMin_le[of n], OF _ inext_mono2])\n\nlemma inext_neq_iMin_infin: \"infinite I \\<Longrightarrow> inext n I \\<noteq> iMin I\"\napply (rule inext_neq_iMin)\napply (blast dest: infinite_nat_iff_unbounded[THEN iffD1])\ndone\n\nlemma Max_le_iMin_imp_singleton: \"\\<lbrakk> finite I; I \\<noteq> {}; Max I \\<le> iMin I \\<rbrakk> \\<Longrightarrow> I = {iMin I}\"\nby (simp add: iMin_Min_conv Max_le_Min_imp_singleton)\n\nlemma inext_neq_iMin_not_singleton: \"\n  \\<lbrakk> I \\<noteq> {}; \\<not>(\\<exists>a. I = {a}) \\<rbrakk> \\<Longrightarrow> inext n I \\<noteq> iMin I\"\napply (case_tac \"finite I\")\n prefer 2\n apply (simp add: inext_neq_iMin_infin)\napply (case_tac \"n \\<in> I\")\n prefer 2\n apply (simp add: not_in_inext_fix)\n apply (blast intro: iMinI_ex2)\nby (metis Max_le_iMin_imp_singleton iMin_le_Max inext_Max inext_mono2_infin_fin not_less_iMin)\ncorollary inext_neq_iMin_not_card_1: \"\n  \\<lbrakk> I \\<noteq> {}; card I \\<noteq> Suc 0 \\<rbrakk> \\<Longrightarrow> inext n I \\<noteq> iMin I\"\nby (simp add: inext_neq_iMin_not_singleton card_1_singleton_conv)\n\nlemma inext_neq_imp_Max: \"n \\<noteq> inext n I \\<Longrightarrow> n < Max I \\<or> infinite I\"\nby (rule ccontr, clarsimp simp: inext_ge_Max)\n\nlemma inext_less_conv: \"(n \\<in> I \\<and> (n < Max I \\<or> infinite I)) = (n < inext n I)\"\napply (rule iffI)\n apply (blast intro: inext_mono2_infin_fin)\napply (rule conjI)\n apply (rule ccontr)\n apply (simp add: not_in_inext_fix)\napply (blast dest: inext_neq_imp_Max less_imp_neq)\ndone\n\nlemma inext_min_step: \"\\<lbrakk> n < k; k < inext n I \\<rbrakk> \\<Longrightarrow> k \\<notin> I\"\napply (case_tac \"n \\<in> I\")\n prefer 2\n apply (simp add: inext_def)\napply (rule contrapos_pn[of \"k < inext n I\" \"k \\<in> I\"], simp)\napply (simp add: inext_def i_cut_defs)\napply (case_tac \"\\<exists>x. x \\<in> I \\<and> n < x\")\n apply simp\n apply (blast dest: not_less_iMin)\napply blast\ndone\n\ncorollary inext_min_step2: \"\\<not>(\\<exists>k\\<in>I. n < k \\<and> k < inext n I)\"\nby (clarsimp simp add: inext_min_step)\n\nlemma min_step_inext[rule_format]: \"\n  \\<lbrakk> x < y; x \\<in> I; y \\<in> I; \\<And>k. \\<lbrakk> x < k; k < y \\<rbrakk> \\<Longrightarrow> k \\<notin> I \\<rbrakk> \\<Longrightarrow>\n  inext x I = y\"\napply (rule ccontr)\napply (simp add: nat_neq_iff, safe)\napply (blast dest: inext_closed inext_mono2)\napply (simp add: inext_min_step)\ndone\n\ncorollary min_step_inext2[rule_format]: \"\n  \\<lbrakk> x < y; x \\<in> I; y \\<in> I; \\<not>(\\<exists>k \\<in> I. x < k \\<and> k < y) \\<rbrakk> \\<Longrightarrow>\n  inext x I = y\"\nby (blast intro: min_step_inext)\nlemma between_empty_imp_inext_eq: \"\n  \\<lbrakk> n \\<in> A; n < inext n A; n \\<in> B; inext n A \\<in> B; B \\<down>> n \\<down>< (inext n A) = {} \\<rbrakk> \\<Longrightarrow>\n  inext n B = inext n A\"\nby (blast intro: min_step_inext2)\n\n\n\n\nlemma inext_le_mono: \"\\<lbrakk> a \\<le> b; a \\<in> I; b \\<in> I \\<rbrakk> \\<Longrightarrow> inext a I \\<le> inext b I\"\napply (drule order_le_less[THEN iffD1], erule disjE)\n prefer 2\n apply simp\napply (rule order_trans[of _ b])\n apply (rule ccontr, simp add: linorder_not_le)\n apply (blast dest: inext_min_step)\nby (rule inext_mono)\n\nlemma inext_less_mono: \"\n  \\<lbrakk> a < b; a \\<in> I; b \\<in> I; \\<exists>x\\<in>I. b < x \\<rbrakk> \\<Longrightarrow> inext a I < inext b I\"\napply (rule le_less_trans[of _ b])\n apply (rule ccontr, simp add: linorder_not_le)\n apply (blast dest: inext_min_step)\nby (rule inext_mono2)\n\nlemma inext_less_mono_fin: \"\n  \\<lbrakk> a < b; a \\<in> I; b \\<in> I; finite I; b \\<noteq> Max I \\<rbrakk> \\<Longrightarrow> inext a I < inext b I\"\nby (blast intro: inext_less_mono Max_in)\n\nlemma inext_less_mono_infin: \"\n  \\<lbrakk> a < b; a \\<in> I; b \\<in> I; infinite I \\<rbrakk> \\<Longrightarrow> inext a I < inext b I\"\napply (rule inext_less_mono, assumption+)\napply (blast dest: infinite_imp_asc_chain)\ndone\n\nlemma inext_less_mono_infin_fin: \"\n  \\<lbrakk> a < b; a \\<in> I; b \\<in> I; b \\<noteq> Max I \\<or> infinite I \\<rbrakk> \\<Longrightarrow> inext a I < inext b I\"\nby (blast intro: inext_less_mono_infin inext_less_mono_fin)\n\n\nlemma inext_le_mono_rev: \"\n  \\<lbrakk> inext a I \\<le> inext b I; a \\<in> I; b \\<in> I; \\<exists>x\\<in>I. inext a I < x \\<rbrakk> \\<Longrightarrow> a \\<le> b\"\napply (rule ccontr, simp add: linorder_not_le)\napply (frule inext_less_mono, assumption+)\n apply (blast intro: le_less_trans inext_mono)\napply simp\ndone\n\nlemma inext_le_mono_fin_rev: \"\n  \\<lbrakk> inext a I \\<le> inext b I; a \\<in> I; b \\<in> I; finite I; inext a I \\<noteq> Max I\\<rbrakk> \\<Longrightarrow> a \\<le> b\"\nby (metis inext_in_iff inext_le_mono_rev inext_mono2_infin_fin)\n\nlemma inext_le_mono_infin_rev: \"\n  \\<lbrakk> inext a I \\<le> inext b I; a \\<in> I; b \\<in> I; infinite I \\<rbrakk> \\<Longrightarrow> a \\<le> b\"\nby (metis inext_in_iff inext_le_mono_rev inext_mono2_infin_fin)\n\nlemma inext_le_mono_infin_fin_rev: \"\n  \\<lbrakk> inext a I \\<le> inext b I; a \\<in> I; b \\<in> I; inext a I \\<noteq> Max I \\<or> infinite I \\<rbrakk> \\<Longrightarrow> a \\<le> b\"\nby (blast intro: inext_le_mono_infin_rev inext_le_mono_fin_rev)\n\nlemma inext_less_mono_rev: \"\n  \\<lbrakk> inext a I < inext b I; a \\<in> I; b \\<in> I \\<rbrakk> \\<Longrightarrow> a < b\"\nby (metis inext_le_mono not_le)\n\nlemma less_imp_inext_le: \"\\<lbrakk> a < b; a \\<in> I; b \\<in> I \\<rbrakk> \\<Longrightarrow> inext a I \\<le> b\"\nby (metis inext_min_step not_le)\n\nlemma iprev_mono: \"iprev n I \\<le> n\"\nunfolding iprev_def i_cut_defs by simp\ncorollary iprev_neq_imp_greater: \"n \\<noteq> iprev n I \\<Longrightarrow> iprev n I < n\"\nby (insert iprev_mono[of n I], simp)\n\nlemma iprev_mono2: \"\\<lbrakk> n \\<in> I; \\<exists>x\\<in>I. x < n\\<rbrakk> \\<Longrightarrow> iprev n I < n\"\napply (unfold iprev_def i_cut_defs, clarsimp)\napply (blast intro: finite_nat_iff_bounded)+\ndone\n\nlemma iprev_mono2_if_neq_iMin: \"\\<lbrakk> n \\<in> I; iMin I \\<noteq> n\\<rbrakk> \\<Longrightarrow> iprev n I < n\"\nby (blast intro: iMinI iprev_mono2)\n\nlemma iprev_neq_Max: \"\\<lbrakk> finite I; \\<exists>x\\<in>I. x < n \\<rbrakk>  \\<Longrightarrow> iprev n I \\<noteq> Max I\"\napply (case_tac \"n \\<in> I\")\n prefer 2\n apply (simp add: not_in_iprev_fix)\n apply (blast dest: Max_in)\napply (rule less_imp_neq)\nby (rule less_le_trans[OF iprev_mono2 Max_ge])\n\nlemma iprev_neq_Max_not_singleton: \"\n  \\<lbrakk> finite I; I \\<noteq> {}; \\<not>(\\<exists>a. I = {a}) \\<rbrakk> \\<Longrightarrow> iprev n I \\<noteq> Max I\"\napply (case_tac \"n \\<in> I\")\n prefer 2\n apply (simp add: not_in_iprev_fix)\n apply (blast intro: Max_in)\napply (case_tac \"n = iMin I\")\n apply (metis Max_le_Min_conv_singleton iMin_Min_conv iMin_le_Max iprev_iMin)\napply (metis iprev_mono2_if_neq_iMin not_greater_Max)\ndone\ncorollary iprev_neq_Max_not_card_1: \"\n  \\<lbrakk> finite I; I \\<noteq> {}; card I \\<noteq> Suc 0 \\<rbrakk> \\<Longrightarrow> iprev n I \\<noteq> Max I\"\napply (rule iprev_neq_Max_not_singleton, assumption+)\napply (simp add: card_1_singleton_conv)\ndone\n\nlemma iprev_neq_imp_iMin: \"iprev n I \\<noteq> n \\<Longrightarrow> iMin I < n\"\nby (rule ccontr, clarsimp simp: iprev_le_iMin)\n\nlemma iprev_greater_conv: \"(n \\<in> I \\<and> iMin I < n) = (iprev n I < n)\"\napply (rule iffI)\n apply (blast intro: iprev_mono2_if_neq_iMin)\napply (rule conjI)\n apply (rule ccontr)\n apply (simp add: not_in_iprev_fix)\napply (blast dest: iprev_neq_imp_iMin less_imp_neq)\ndone\n\nlemma inext_fix_iff: \"(n \\<notin> I \\<or> (finite I \\<and> Max I = n)) = (inext n I = n)\"\napply (case_tac \"n \\<notin> I\", simp add: not_in_inext_fix)\nby (metis inext_Max inext_min_step2 inext_mono2_infin_fin)\n\nlemma iprev_fix_iff: \"(n \\<notin> I \\<or> iMin I = n) = (iprev n I = n)\"\napply (case_tac \"n \\<notin> I\", simp add: not_in_iprev_fix)\nby (metis iprev_iMin iprev_mono2_if_neq_iMin less_not_refl3)\n\nlemma iprev_min_step: \"\\<lbrakk> iprev n I < k; k < n \\<rbrakk> \\<Longrightarrow> k \\<notin> I\"\napply (case_tac \"n \\<in> I\")\n prefer 2\n apply (simp add: iprev_def)\napply (rule contrapos_pn[of \"iprev n I < k\" \"k \\<in> I\"], simp)\napply (unfold iprev_def i_cut_defs, simp)\napply (split if_split_asm)\napply (cut_tac Max_ge[of \"{x \\<in> I. x < n}\" k])\napply fastforce+\ndone\n\ncorollary iprev_min_step2: \"\\<not>(\\<exists>x\\<in>I. iprev n I < x \\<and> x < n)\"\nby (clarsimp simp add: iprev_min_step)\n\nlemma min_step_iprev: \"\n  \\<lbrakk> x < y; x \\<in> I; y \\<in> I; \\<And>k. \\<lbrakk> x < k; k < y \\<rbrakk> \\<Longrightarrow> k \\<notin> I \\<rbrakk> \\<Longrightarrow>\n  iprev y I = x\"\napply (rule ccontr)\napply (simp add: nat_neq_iff, elim disjE)\n apply (simp add: iprev_min_step)\napply (blast dest: iprev_closed iprev_mono2 iprev_min_step)\ndone\n\ncorollary min_step_iprev2[rule_format]: \"\n  \\<lbrakk> x < y; x \\<in> I; y \\<in> I; \\<not>(\\<exists>k \\<in> I. x < k \\<and> k < y) \\<rbrakk> \\<Longrightarrow>\n  iprev y I = x\"\nby (blast intro: min_step_iprev)\n\nlemma between_empty_imp_iprev_eq: \"\n  \\<lbrakk> n \\<in> A; iprev n A < n; n \\<in> B; iprev n A \\<in> B; B \\<down>> (iprev n A) \\<down>< n = {} \\<rbrakk> \\<Longrightarrow>\n  iprev n B = iprev n A\"\nby (blast intro: min_step_iprev2)\n\n\n\nlemma iprev_le_mono: \"\\<lbrakk> a \\<le> b; a \\<in> I; b \\<in> I \\<rbrakk> \\<Longrightarrow> iprev a I \\<le> iprev b I\"\napply (drule order_le_less[THEN iffD1], erule disjE)\n prefer 2\n apply simp\napply (rule order_trans[OF iprev_mono])\n apply (rule ccontr, simp add: linorder_not_le)\nby (blast dest: iprev_min_step)\n\nlemma iprev_less_mono: \"\n  \\<lbrakk> a < b; a \\<in> I; b \\<in> I; \\<exists>x\\<in>I. x < a \\<rbrakk> \\<Longrightarrow> iprev a I < iprev b I\"\napply (rule less_le_trans[of _ a])\n apply (blast intro: iprev_mono2)\napply (rule ccontr, simp add: linorder_not_le)\nby (blast dest: iprev_min_step)\n\nlemma iprev_less_mono_if_neq_iMin: \"\n  \\<lbrakk> a < b; a \\<in> I; b \\<in> I; iMin I \\<noteq> a \\<rbrakk> \\<Longrightarrow> iprev a I < iprev b I\"\nby (metis iprev_in_iff iprev_less_mono iprev_mono2_if_neq_iMin)\n\nlemma iprev_le_mono_rev: \"\n  \\<lbrakk> iprev a I \\<le> iprev b I; a \\<in> I; b \\<in> I; iMin I \\<noteq> iprev b I \\<rbrakk> \\<Longrightarrow> a \\<le> b\"\napply (rule ccontr, simp add: linorder_not_le)\nby (metis iprev_fix_iff iprev_less_mono_if_neq_iMin less_le_not_le)\n\nlemma iprev_less_mono_rev: \"\n  \\<lbrakk> iprev a I < iprev b I; a \\<in> I; b \\<in> I \\<rbrakk> \\<Longrightarrow> a < b\"\napply (rule ccontr, simp add: linorder_not_less)\nby (metis iprev_le_mono less_le_not_le)\n\n\n\nlemma set_restriction_inext_eq: \"\n  \\<lbrakk> set_restriction interval_fun; n \\<in> interval_fun I; inext n I \\<in> interval_fun I \\<rbrakk> \\<Longrightarrow>\n  inext n (interval_fun I) = inext n I\"\napply (subgoal_tac \"n \\<in> I\")\n prefer 2\n apply (blast intro: set_restriction_in_imp)\napply (case_tac \"inext n I = n\")\n apply simp\n apply (frule inext_fix_iff[THEN iffD2], clarsimp)\n apply (frule set_restriction_finite, assumption)\n apply (subgoal_tac \"Max (interval_fun I) = Max I\")\n  prefer 2\n  apply (blast intro: Max_equality Max_ge set_restriction_in_imp)\n apply (blast intro: inext_fix_iff[THEN iffD1])\napply (drule le_neq_implies_less[OF inext_mono, OF not_sym])\napply (rule between_empty_imp_inext_eq, assumption+)\napply (simp add: not_ex_in_conv[symmetric] i_cut_mem_iff)\nby (metis inext_min_step2 set_restriction_in_imp)\n\nlemma set_restriction_inext_singleton_eq: \"\n  \\<lbrakk> set_restriction interval_fun; n \\<in> interval_fun I; inext n I \\<in> interval_fun I \\<rbrakk> \\<Longrightarrow>\n  {inext n (interval_fun I)} = interval_fun {inext n I}\"\napply (case_tac \"n \\<notin> I\")\n apply (blast dest: set_restriction_not_in_imp)\napply (frule set_restrictionD, erule exE, rename_tac P)\napply (simp add: singleton_iff set_eq_iff)\nby (metis set_restriction_inext_eq)\n\n\n\n\n\nlemma iprev_inext_infin: \"infinite I \\<Longrightarrow> iprev (inext n I) I = n\"\napply (case_tac \"n \\<notin> I\")\n apply (simp add: inext_def iprev_def)\napply simp\nby (metis inext_in_iff inext_min_step2 inext_mono2_infin_fin min_step_iprev2)\n\nlemma iprev_inext_fin: \"\n  \\<lbrakk> finite I; n \\<noteq> Max I \\<rbrakk> \\<Longrightarrow> iprev (inext n I) I = n\"\napply (case_tac \"n \\<notin> I\")\n apply (simp add: inext_def iprev_def)\napply simp\nby (metis inext_in_iff inext_min_step2 inext_mono2_infin_fin min_step_iprev2)\n\nlemma iprev_inext: \"\n  n \\<noteq> Max I \\<or> infinite I \\<Longrightarrow> iprev (inext n I) I = n\"\nby (blast intro: iprev_inext_infin iprev_inext_fin)\n\nlemma inext_eq_infin: \"\n  \\<lbrakk> inext a I = inext b I; infinite I \\<rbrakk> \\<Longrightarrow> a = b\"\napply (drule arg_cong[where f=\"\\<lambda>x. iprev x I\"])\napply (simp add: iprev_inext_infin)\ndone\n\nlemma inext_eq_fin: \"\n  \\<lbrakk> inext a I = inext b I; finite I; a \\<noteq> Max I; b \\<noteq> Max I \\<rbrakk> \\<Longrightarrow> a = b\"\napply (drule arg_cong[where f=\"\\<lambda>x. iprev x I\"])\napply (simp add: iprev_inext_fin)\ndone\n\nlemma inext_eq_infin_fin: \"\n  \\<lbrakk> inext a I = inext b I; a \\<noteq> Max I \\<and> b \\<noteq> Max I \\<or> infinite I \\<rbrakk> \\<Longrightarrow> a = b\"\nby (blast intro: inext_eq_fin inext_eq_infin)+\n\nlemma inext_eq: \"\n  \\<lbrakk> inext a I = inext b I; \\<exists>x\\<in>I. a < x; \\<exists>x\\<in>I. b < x \\<rbrakk> \\<Longrightarrow> a = b\"\nby (metis iprev_inext not_le wellorder_Max_lemma)\n\nlemma iprev_eq_if_neq_iMin: \"\n  \\<lbrakk> iprev a I = iprev b I; iMin I \\<noteq> a; iMin I \\<noteq> b \\<rbrakk> \\<Longrightarrow> a = b\"\napply (drule arg_cong[where f=\"\\<lambda>x. inext x I\"])\napply (simp add: inext_iprev)\ndone\n\nlemma iprev_eq: \"\n  \\<lbrakk> iprev a I = iprev b I; \\<exists>x\\<in>I. x < a; \\<exists>x\\<in>I. x < b \\<rbrakk> \\<Longrightarrow> a = b\"\nby (metis iprev_eq_if_neq_iMin not_less_iMin)\n\nlemma greater_imp_iprev_ge: \"\\<lbrakk> b < a; a \\<in> I; b \\<in> I \\<rbrakk> \\<Longrightarrow> b \\<le> iprev a I\"\napply (rule ccontr, simp add: linorder_not_le)\napply (blast dest: iprev_min_step)\ndone\n\n\nlemma inext_cut_less_conv: \"inext n I < t \\<Longrightarrow> inext n (I \\<down>< t) = inext n I\"\napply (frule le_less_trans[OF inext_mono])\napply (case_tac \"n \\<in> I\")\n apply (simp add: inext_def)\n apply (simp add: i_cut_commute_disj[of \"(\\<down><)\" \"(\\<down>>)\"] cut_less_mem_iff)\n apply (case_tac \"I \\<down>> n \\<noteq> {}\")\n  apply simp\n  apply (metis cut_less_Min_eq cut_less_Min_not_empty)\n apply (simp add: i_cut_empty)\napply (simp add: not_in_inext_fix cut_less_not_in_imp)\ndone\n\n\n\nlemma inext_cut_greater_conv: \"t < n \\<Longrightarrow> inext n (I \\<down>> t) = inext n I\"\napply (case_tac \"n \\<in> I\")\n apply (frule cut_greater_mem_iff[THEN iffD2, OF conjI], simp)\n apply (simp add: inext_def i_cut_commute_disj[of \"(\\<down>>)\" \"(\\<down>>)\"] cut_cut_greater max_def)\napply (simp add: not_in_inext_fix cut_greater_not_in_imp)\ndone\n\nlemma inext_cut_ge_conv: \"t \\<le> n \\<Longrightarrow> inext n (I \\<down>\\<ge> t) = inext n I\"\napply (case_tac \"t = 0\")\n apply (simp add: cut_ge_0_all)\napply (simp add: nat_cut_greater_ge_conv[symmetric] inext_cut_greater_conv)\ndone\n\nlemmas inext_cut_conv =\n  inext_cut_less_conv inext_cut_le_conv\n  inext_cut_greater_conv inext_cut_ge_conv\n\n\n\nlemma iprev_cut_greater_conv: \"t < iprev n I \\<Longrightarrow> iprev n (I \\<down>> t) = iprev n I\"\napply (frule less_le_trans[OF _ iprev_mono])\napply (case_tac \"n \\<in> I\")\n apply (simp add: iprev_def)\n apply (simp add: i_cut_commute_disj[of \"(\\<down>>)\" \"(\\<down><)\"] cut_greater_mem_iff)\n apply (case_tac \"I \\<down>< n \\<noteq> {}\")\n  apply simp\n  apply (metis cut_greater_Max_eq cut_greater_Max_not_empty nat_cut_less_finite)\n apply (simp add: i_cut_empty)\napply (simp add: not_in_iprev_fix cut_greater_not_in_imp)\ndone\n\nlemma iprev_cut_ge_conv: \"t \\<le> iprev n I \\<Longrightarrow> iprev n (I \\<down>\\<ge> t) = iprev n I\"\napply (case_tac \"t = 0\")\n apply (simp add: cut_ge_0_all)\napply (simp add: nat_cut_greater_ge_conv[symmetric] iprev_cut_greater_conv)\ndone\n\nlemma iprev_cut_less_conv: \"n < t \\<Longrightarrow> iprev n (I \\<down>< t) = iprev n I\"\napply (case_tac \"n \\<in> I\")\n apply (frule cut_less_mem_iff[THEN iffD2, OF conjI], simp)\n apply (simp add: iprev_def i_cut_commute_disj[of \"(\\<down><)\" \"(\\<down><)\"] cut_cut_less min_def)\napply (simp add: not_in_iprev_fix cut_less_not_in_imp)\ndone\n\nlemma iprev_cut_le_conv: \"n \\<le> t \\<Longrightarrow> iprev n (I \\<down>\\<le> t) = iprev n I\"\nby (simp add: nat_cut_le_less_conv iprev_cut_less_conv)\n\nlemmas iprev_cut_conv =\n  iprev_cut_less_conv iprev_cut_le_conv\n  iprev_cut_greater_conv iprev_cut_ge_conv\n\nlemma inext_cut_less_fix: \"t \\<le> inext n I \\<Longrightarrow> inext n (I \\<down>< t) = n\"\napply (case_tac \"n \\<in> I\")\n prefer 2\n apply (frule contra_subsetD[OF cut_less_subset[of _ t]])\n apply (simp add: not_in_inext_fix)\napply (case_tac \"t \\<le> n\")\n apply (metis cut_less_mem_iff not_in_inext_fix not_le)\napply (rule_tac t=n and s=\"Max (I \\<down>< t)\" in subst)\n apply (rule Max_equality[OF _ nat_cut_less_finite])\n  apply (simp add: cut_less_mem_iff)\n apply (rule ccontr)\n apply (clarsimp simp: cut_less_mem_iff linorder_not_le)\n apply (simp add: inext_min_step)\napply (blast intro: inext_Max nat_cut_less_finite)\ndone\n\nlemma inext_cut_le_fix: \"t < inext n I \\<Longrightarrow> inext n (I \\<down>\\<le> t) = n\"\nby (simp add: nat_cut_le_less_conv inext_cut_less_fix)\n\nlemma iprev_cut_greater_fix: \"iprev n I \\<le> t \\<Longrightarrow> iprev n (I \\<down>> t) = n\"\napply (case_tac \"n \\<in> I\")\n prefer 2\n apply (frule contra_subsetD[OF cut_greater_subset[of _ t]])\n apply (simp add: not_in_iprev_fix)\napply (case_tac \"n \\<le> t\")\n apply (metis cut_greater_mem_iff not_in_iprev_fix not_le)\napply (rule_tac t=n and s=\"iMin (I \\<down>> t)\" in subst)\n apply (rule iMin_equality)\n  apply (simp add: cut_greater_mem_iff)\n apply (metis cut_greater_mem_iff iprev_min_step2 not_le_imp_less order_le_less_trans)\napply (rule iprev_iMin)\ndone\n\nlemma iprev_cut_ge_fix: \"iprev n I < t \\<Longrightarrow> iprev n (I \\<down>\\<ge> t) = n\"\napply (case_tac \"t = 0\")\n apply (simp add: cut_ge_0_all)\napply (simp add: nat_cut_greater_ge_conv[symmetric] iprev_cut_greater_fix)\ndone\n\ndefinition\n  CommuteWithIntervalCut4 :: \"(('a::linorder) set \\<Rightarrow> 'a set) \\<Rightarrow> bool\"\nwhere\n  \"CommuteWithIntervalCut4 fun \\<equiv>\n  \\<forall>t fun2 I.\n  (fun2 = (\\<lambda>I. I \\<down>< t) \\<or> fun2 = (\\<lambda>I. I \\<down>\\<le> t) \\<or> fun2 = (\\<lambda>I. I \\<down>> t) \\<or> fun2 = (\\<lambda>I. I \\<down>\\<ge> t) ) \\<longrightarrow>\n  fun (fun2 I) = fun2 (fun I)\"\ndefinition CommuteWithIntervalCut2 :: \"(('a::linorder) set \\<Rightarrow> 'a set) \\<Rightarrow> bool\"\nwhere\n  \"CommuteWithIntervalCut2 fun \\<equiv>\n  \\<forall>t fun2 I.\n  (fun2 = (\\<lambda>I. I \\<down>< t) \\<or> fun2 = (\\<lambda>I. I \\<down>> t)) \\<longrightarrow>\n  fun (fun2 I) = fun2 (fun I)\"\n\nlemma CommuteWithIntervalCut4_imp_2: \"CommuteWithIntervalCut4 fun \\<Longrightarrow> CommuteWithIntervalCut2 fun\"\nunfolding CommuteWithIntervalCut2_def CommuteWithIntervalCut4_def by blast\n\nlemma nat_CommuteWithIntervalCut2_4_eq: \"\n  CommuteWithIntervalCut4 (fun::nat set \\<Rightarrow> nat set) = CommuteWithIntervalCut2 fun\"\napply (unfold CommuteWithIntervalCut2_def CommuteWithIntervalCut4_def)\napply (rule iffI)\n apply blast\napply clarify\napply (case_tac \"fun2 = (\\<lambda>I. I \\<down>< t)\", simp)\napply (case_tac \"fun2 = (\\<lambda>I. I \\<down>> t)\", simp)\napply simp\napply (erule disjE)\n apply (simp add: nat_cut_le_less_conv)\napply (case_tac \"t = 0\")\n apply (simp add: cut_ge_0_all)\napply (simp add: nat_cut_greater_ge_conv[symmetric])\ndone\n\nlemma\n  cut_less_CommuteWithIntervalCut4:    \"CommuteWithIntervalCut4 (\\<lambda>I. I \\<down>< t)\" and\n  cut_le_CommuteWithIntervalCut4:      \"CommuteWithIntervalCut4 (\\<lambda>I. I \\<down>\\<le> t)\" and\n  cut_greater_CommuteWithIntervalCut4: \"CommuteWithIntervalCut4 (\\<lambda>I. I \\<down>> t)\" and\n  cut_ge_CommuteWithIntervalCut4:      \"CommuteWithIntervalCut4 (\\<lambda>I. I \\<down>\\<ge> t)\"\nunfolding CommuteWithIntervalCut4_def by (simp_all add: i_cut_commute_disj)\n\nlemmas i_cut_CommuteWithIntervalCut4 =\n  cut_less_CommuteWithIntervalCut4 cut_le_CommuteWithIntervalCut4\n  cut_greater_CommuteWithIntervalCut4 cut_ge_CommuteWithIntervalCut4\n\nlemma inext_image: \"\n  \\<lbrakk> n \\<in> I; strict_mono_on f I \\<rbrakk> \\<Longrightarrow> inext (f n) (f ` I) = f (inext n I)\"\napply (case_tac \"\\<exists>x\\<in>I. n < x\")\n apply (frule inext_mono2, assumption)\n apply (frule cut_greater_not_empty_iff[THEN iffD2])\n apply (simp add: inext_def image_iff)\n apply (subgoal_tac \"\\<exists>x\\<in>I. f n = f x\")\n  prefer 2\n  apply blast\n apply (simp add: cut_greater_image)\n apply (blast intro: strict_mono_on_subset iMin_mono_on2 strict_mono_on_imp_mono_on)\napply (drule strict_mono_on_imp_mono_on)\napply (simp add: inext_all_le_fix linorder_not_less mono_on_def)\ndone\n\nlemma iprev_image: \"\n  \\<lbrakk> n \\<in> I; strict_mono_on f I \\<rbrakk> \\<Longrightarrow> iprev (f n) (f ` I) = f (iprev n I)\"\napply (case_tac \"\\<exists>x\\<in>I. x < n\")\n apply (frule iprev_mono2, assumption)\n apply (frule cut_less_not_empty_iff[THEN iffD2])\n apply (simp add: iprev_def image_iff)\n apply (subgoal_tac \"\\<exists>x\\<in>I. f n = f x\")\n  prefer 2\n  apply blast\n apply (simp add: cut_less_image)\n apply (blast intro: strict_mono_on_subset Max_mono_on2 strict_mono_on_imp_mono_on nat_cut_less_finite)\napply (drule strict_mono_on_imp_mono_on)\napply (simp add: iprev_all_ge_fix linorder_not_less mono_on_def)\ndone\n\nlemma inext_image2: \"\n  strict_mono f \\<Longrightarrow> inext (f n) (f ` I) = f (inext n I)\"\napply (case_tac \"n \\<in> I\")\n apply (blast intro: strict_mono_imp_strict_mono_on inext_image)\napply (simp add: not_in_inext_fix inj_image_mem_iff strict_mono_imp_inj)\ndone\n\nlemma iprev_image2: \"\n  strict_mono f \\<Longrightarrow> iprev (f n) (f ` I) = f (iprev n I)\"\napply (case_tac \"n \\<in> I\")\n apply (blast intro: strict_mono_imp_strict_mono_on iprev_image)\napply (simp add: not_in_iprev_fix inj_image_mem_iff strict_mono_imp_inj)\ndone\n\n\nlemma inext_imirror_iprev_conv: \"\n  \\<lbrakk> finite I; n \\<le> iMin I + Max I \\<rbrakk> \\<Longrightarrow>\n  inext (mirror_elem n I) (imirror I) = mirror_elem (iprev n I) I\"\napply (case_tac \"n \\<in> I\")\n prefer 2\n apply (simp add: not_in_iprev_fix not_in_inext_fix imirror_mem_conv)\napply (frule in_imp_not_empty[of _ I])\napply (frule in_imp_mirror_elem_in[of _ n], assumption)\napply (simp add: inext_def iprev_def)\napply (case_tac \"n = iMin I\")\n apply (simp add: cut_less_Min_empty mirror_elem_Min)\n apply (subst imirror_Max[symmetric], assumption)\n apply (simp add: cut_greater_Max_empty imirror_finite)\napply (frule iMin_le[of n I])\napply (intro conjI impI)\n  apply (simp add: imirror_cut_greater')\n  apply (simp add: imirror_bounds_iMin nat_cut_less_finite cut_less_Min_eq)\n  apply (simp add: mirror_elem_def nat_mirror_def)\n apply (simp add: imirror_cut_greater')\n apply (simp add: imirror_bounds_def)\napply (simp add: cut_less_Min_not_empty)\ndone\n\ncorollary inext_imirror_iprev_conv': \"\n  \\<lbrakk> finite I; n \\<in> I \\<rbrakk> \\<Longrightarrow>\n  inext (mirror_elem n I) (imirror I) = mirror_elem (iprev n I) I\"\nby (simp add: inext_imirror_iprev_conv trans_le_add2)\n\nlemma iprev_imirror_inext_conv: \"\n  \\<lbrakk> finite I; n \\<le> iMin I + Max I \\<rbrakk> \\<Longrightarrow>\n  iprev (mirror_elem n I) (imirror I) = mirror_elem (inext n I) I\"\napply (case_tac \"n \\<in> I\")\n prefer 2\n apply (simp add: not_in_iprev_fix not_in_inext_fix imirror_mem_conv)\napply (frule in_imp_not_empty[of _ I])\napply (frule in_imp_mirror_elem_in[of _ n], assumption)\napply (simp add: inext_def iprev_def)\napply (case_tac \"n = Max I\")\n apply (simp add: cut_greater_Max_empty mirror_elem_Max)\n apply (subst imirror_iMin[symmetric], assumption)\n apply (simp add: cut_less_Min_empty imirror_finite)\napply (frule Max_ge[of I n], assumption)\napply (drule le_neq_trans, assumption)\napply (intro conjI impI)\n  apply (simp add: imirror_cut_less)\n  apply (simp add: imirror_bounds_Max cut_greater_finite cut_greater_Max_eq del: Max_le_iff)\n  apply (simp add: mirror_elem_def nat_mirror_def)\n apply (simp add: imirror_cut_less)\n apply (simp add: imirror_bounds_def)\napply (simp add: cut_greater_Max_not_empty)\ndone\n\ncorollary iprev_imirror_inext_conv': \"\n  \\<lbrakk> finite I; n \\<in> I \\<rbrakk> \\<Longrightarrow>\n  iprev (mirror_elem n I) (imirror I) = mirror_elem (inext n I) I\"\nby (simp add: iprev_imirror_inext_conv trans_le_add2)\n\nlemma inext_insert_ge_Max: \"\n  \\<lbrakk> finite I; I \\<noteq> {}; Max I \\<le> a \\<rbrakk> \\<Longrightarrow> inext (Max I) (insert a I) = a\"\napply (case_tac \"a = Max I\")\n apply (simp add: insert_absorb inext_Max)\napply (drule le_neq_trans, simp)\napply (rule min_step_inext2)\napply (simp, simp, simp)\napply (simp_all, blast?) (* blast is optional for the case, that the last goal could be solved by the simplifier in a future version, making the blast command superfluous. *)\ndone\n\nlemma iprev_insert_le_iMin: \"\n  \\<lbrakk> finite I; I \\<noteq> {}; a \\<le> iMin I \\<rbrakk> \\<Longrightarrow> iprev (iMin I) (insert a I) = a\"\napply (case_tac \"a = iMin I\")\n apply (simp add: iMinI_ex2 insert_absorb iprev_iMin)\napply (drule le_neq_trans, simp)\napply (rule min_step_iprev2)\napply (simp_all add: iMin_Min_conv, blast?)\ndone\n\nlemma cut_less_le_iprev_conv: \"\n  \\<lbrakk> t \\<in> I; t \\<noteq> iMin I \\<rbrakk> \\<Longrightarrow> I \\<down>< t = I \\<down>\\<le> (iprev t I)\"\napply (unfold iprev_def)\napply (rule set_eqI, safe)\n apply (simp add: i_cut_defs)\napply simp\napply (split if_split_asm)\n apply (simp add: Max_ge_iff nat_cut_less_finite)\n apply (blast intro: le_less_trans)\napply (frule iMin_neq_imp_greater, assumption)\napply (blast intro: iMin_in)\ndone\n\nlemma neq_Max_imp_inext_neq_iMin: \"\n  \\<lbrakk> t \\<in> I; t \\<noteq> Max I \\<or> infinite I \\<rbrakk> \\<Longrightarrow> inext t I \\<noteq> iMin I\"\napply (case_tac \"finite I\")\n apply (metis inext_mono2_infin_fin not_less_iMin)\napply (blast dest: inext_neq_iMin_infin)\ndone\n\ncorollary neq_Max_imp_inext_gr_iMin: \"\n  \\<lbrakk> t \\<in> I; t \\<noteq> Max I \\<or> infinite I\\<rbrakk> \\<Longrightarrow> iMin I < inext t I\"\napply (frule neq_Max_imp_inext_neq_iMin[THEN not_sym], assumption)\napply (drule neq_le_trans)\n apply (blast dest: inext_closed)\napply simp\ndone\n\nlemma cut_le_less_inext_conv: \"\n  \\<lbrakk> t \\<in> I; t \\<noteq> Max I \\<or> infinite I\\<rbrakk> \\<Longrightarrow> I \\<down>\\<le> t = I \\<down>< (inext t I)\"\napply (cut_tac cut_less_le_iprev_conv[of \"inext t I\" I])\napply (cut_tac iprev_inext[of t I], simp)\napply assumption\napply (rule inext_closed, assumption)\napply (rule neq_Max_imp_inext_neq_iMin, assumption+)\ndone\n\nlemma cut_ge_greater_iprev_conv: \"\n  \\<lbrakk> t \\<in> I; t \\<noteq> iMin I \\<rbrakk> \\<Longrightarrow> I \\<down>\\<ge> t = I \\<down>> (iprev t I)\"\napply (frule iMin_neq_imp_greater, simp+)\napply (unfold iprev_def)\napply (rule set_eqI, safe)\n apply (simp add: i_cut_defs linorder_not_less)\n apply (drule iMinI, fastforce)\napply (split if_split_asm)\n apply (rule ccontr)\n apply (simp add: nat_cut_less_finite linorder_not_le)\n apply blast\napply simp\ndone\n\nlemma cut_greater_ge_inext_conv: \"\n  \\<lbrakk> t \\<in> I; t \\<noteq> Max I \\<or> infinite I \\<rbrakk> \\<Longrightarrow> I \\<down>> t = I \\<down>\\<ge> (inext t I)\"\napply (cut_tac cut_ge_greater_iprev_conv[of \"inext t I\" I])\napply (cut_tac iprev_inext[of t I], simp)\napply blast\napply (rule inext_closed, assumption)\napply (rule neq_Max_imp_inext_neq_iMin, assumption+)\ndone\n\nlemma inext_append: \"\n  \\<lbrakk> finite A; A \\<noteq> {}; B \\<noteq> {}; Max A < iMin B \\<rbrakk> \\<Longrightarrow>\n  inext n (A \\<union> B) = (if n \\<in> B then inext n B else (if n = Max A then iMin B else inext n A))\"\napply (case_tac \"n \\<in> A \\<union> B\")\n prefer 2\n apply (simp add: not_in_inext_fix)\n apply (blast dest: Max_in)\napply (frule Max_less_iMin_imp_disjoint, assumption)\napply (drule Un_iff[THEN iffD1], elim disjE)\n apply (drule disjoint_iff_in_not_in1[THEN iffD1])\n apply simp\n apply (intro conjI impI)\n  apply (simp add: inext_def cut_greater_Un cut_greater_Max_empty cut_greater_Min_all)\n apply (frule Max_neq_imp_less[of A], simp+)\n apply (simp add: inext_def cut_greater_Un cut_greater_Min_all)\n apply (subgoal_tac \"A \\<down>> n \\<noteq> {}\")\n  prefer 2\n  apply (simp add: cut_greater_not_empty_iff)\n  apply (blast intro: Max_in)\n apply (simp add: iMin_Un)\n apply (drule iMin_in[THEN cut_greater_in_imp])\n apply (rule min_eqL)\n apply (rule less_imp_le)\n apply blast\napply (drule disjoint_iff_in_not_in2[THEN iffD1])\napply simp\napply (subgoal_tac \"A \\<down>> n = {}\")\n prefer 2\n apply (simp add: cut_greater_empty_iff)\n apply fastforce\napply (simp add: inext_def cut_greater_Un)\ndone\ncorollary inext_append_eq1: \"\n  \\<lbrakk> finite A; A \\<noteq> {}; B \\<noteq> {}; Max A < iMin B; n \\<in> A; n \\<noteq> Max A \\<rbrakk> \\<Longrightarrow>\n  inext n (A \\<union> B) = inext n A\"\napply (frule Max_less_iMin_imp_disjoint, assumption)\napply (drule disjoint_iff_in_not_in1[THEN iffD1])\napply (simp add: inext_append Max_less_iMin_imp_disjoint)\ndone\ncorollary inext_append_eq2: \"\n  \\<lbrakk> finite A; A \\<noteq> {}; B \\<noteq> {}; Max A < iMin B; n \\<in> B \\<rbrakk> \\<Longrightarrow>\n  inext n (A \\<union> B) = inext n B\"\nby (simp add: inext_append)\ncorollary inext_append_eq3: \"\n  \\<lbrakk> finite A; A \\<noteq> {}; B \\<noteq> {}; Max A < iMin B \\<rbrakk> \\<Longrightarrow>\n  inext (Max A) (A \\<union> B) = iMin B\"\nby (simp add: inext_append not_less_iMin)\n\nlemma iprev_append: \"\\<lbrakk> finite A; A \\<noteq> {}; B \\<noteq> {}; Max A < iMin B \\<rbrakk> \\<Longrightarrow>\n  iprev n (A \\<union> B) = (if n \\<in> A then iprev n A else (if n = iMin B then Max A else iprev n B))\"\napply (case_tac \"n \\<in> A \\<union> B\")\n prefer 2\n apply (simp add: not_in_iprev_fix)\n apply (blast intro: iMin_in)\napply (frule Max_less_iMin_imp_disjoint, assumption)\napply (drule Un_iff[THEN iffD1], elim disjE)\n apply (drule disjoint_iff_in_not_in1[THEN iffD1])\n apply simp\n apply (subgoal_tac \"B \\<down>< n = {}\")\n  prefer 2\n  apply (simp add: cut_less_empty_iff)\n  apply fastforce\n apply (simp add: iprev_def cut_less_Un)\napply (drule disjoint_iff_in_not_in2[THEN iffD1])\napply simp\napply (intro conjI impI)\n apply (simp add: iprev_def cut_less_Un cut_less_Min_empty cut_less_Max_all)\napply (frule iMin_neq_imp_greater[of _ B], simp+)\napply (simp add: iprev_def cut_less_Un)\napply (subgoal_tac \"A \\<down>< n = A\")\n prefer 2\n apply (simp add: cut_less_all_iff)\n apply fastforce\napply (subgoal_tac \"B \\<down>< n \\<noteq> {}\")\n prefer 2\n apply (simp add: cut_less_not_empty_iff)\n apply (blast intro: iMin_in)\napply (simp add: Max_Un nat_cut_less_finite)\napply (rule max_eqR)\napply (rule less_imp_le)\napply (drule Max_in[OF nat_cut_less_finite, THEN cut_less_in_imp])\napply (blast intro: iMin_le Max_in order_less_le_trans)\ndone\n\ncorollary iprev_append_eq1: \"\n  \\<lbrakk> finite A; A \\<noteq> {}; B \\<noteq> {}; Max A < iMin B; n \\<in> A \\<rbrakk> \\<Longrightarrow>\n  iprev n (A \\<union> B) = iprev n A\"\nby (simp add: iprev_append)\n\ncorollary iprev_append_eq2: \"\n  \\<lbrakk> finite A; A \\<noteq> {}; B \\<noteq> {}; Max A < iMin B; n \\<in> B; n \\<noteq> iMin B \\<rbrakk> \\<Longrightarrow>\n  iprev n (A \\<union> B) = iprev n B\"\napply (frule Max_less_iMin_imp_disjoint, assumption)\napply (drule disjoint_iff_in_not_in2[THEN iffD1])\napply (simp add: iprev_append)\ndone\n\ncorollary iprev_append_eq3: \"\n  \\<lbrakk> finite A; A \\<noteq> {}; B \\<noteq> {}; Max A < iMin B \\<rbrakk> \\<Longrightarrow>\n  iprev (iMin B) (A \\<union> B) = Max A\"\nby (simp add: iprev_append not_greater_Max[of _ \"iMin B\"])\n\n\n\n\nlemma inext_predicate_change_exists_aux: \"\\<And>a.\n  \\<lbrakk> c = card (I \\<down>\\<ge> a \\<down>< b); a < b; a \\<in> I; b \\<in> I; \\<not> P a; P b \\<rbrakk> \\<Longrightarrow>\n  \\<exists>n \\<in> (I \\<down>\\<ge> a \\<down>< b). \\<not> P n \\<and> P (inext n I)\"\napply (subgoal_tac \"0 < c\")\n prefer 2\n apply clarify\n apply (rule_tac x=a in not_empty_card_gr0_conv[OF nat_cut_less_finite, THEN iffD1, OF in_imp_not_empty, rule_format])\n apply (simp add: i_cut_mem_iff)\napply (induct c)\n apply simp\napply (subgoal_tac \"a < inext a I\")\n prefer 2\n apply (blast intro: inext_mono2)\napply (drule_tac x=\"inext a I\" in meta_spec)\napply (frule less_imp_inext_le[of _ b I], assumption+)\napply (case_tac \"inext a I < b\")\n prefer 2\n apply simp\n apply (subgoal_tac \"I \\<down>\\<ge> a \\<down>< b = {a}\")\n  prefer 2\n  apply (simp add: set_eq_iff i_cut_mem_iff, clarify)\n  apply (rule iffI)\n   prefer 2\n   apply simp\n  apply clarify\n  apply (case_tac \"a < x\")\n   apply (simp add: inext_min_step)\n  apply simp+\napply (subgoal_tac \"I \\<down>\\<ge> inext a I = I \\<down>> a\")\n prefer 2\n apply (rule cut_greater_ge_inext_conv[symmetric], assumption)\n apply (case_tac \"finite I\")\n  apply (simp, rule less_imp_neq)\n  apply (simp add: Max_gr_iff in_imp_not_empty)\n  apply (blast intro: inext_closed)\n apply simp\napply (simp add: inext_closed)\napply (subgoal_tac \"a \\<notin> (I \\<down>> a \\<down>< b)\")\n prefer 2\n apply blast\napply (subgoal_tac \"(I \\<down>\\<ge> a \\<down>< b) = insert a (I \\<down>> a \\<down>< b)\")\n prefer 2\n apply (simp add:\n   i_cut_commute_disj[of \"(\\<down>\\<ge>)\" \"(\\<down><)\"] i_cut_commute_disj[of \"(\\<down>>)\" \"(\\<down><)\"])\n apply (simp add: cut_ge_greater_conv_if i_cut_mem_iff)\napply (simp add: card_insert_disjoint[OF nat_cut_less_finite])\napply (case_tac \"P (inext a I)\")\n apply blast\napply (case_tac \"card (I \\<down>> a \\<down>< b) = 0\")\n apply (drule card_0_eq[OF nat_cut_less_finite, THEN iffD1])\n apply (simp add: cut_less_empty_iff)\n apply (drule_tac x=\"inext a I\" in bspec)\n  apply (blast intro: inext_closed)\n apply simp\napply simp\ndone\n\nlemma inext_predicate_change_exists: \"\n  \\<lbrakk> a \\<le> b; a \\<in> I; b \\<in> I; \\<not> P a; P b \\<rbrakk> \\<Longrightarrow>\n  \\<exists>n\\<in>I. a \\<le> n \\<and> n < b \\<and> \\<not> P n \\<and> P (inext n I)\"\napply (drule order_le_less[THEN iffD1], erule disjE)\n prefer 2\n apply blast\napply (drule inext_predicate_change_exists_aux[OF refl], assumption+)\napply blast\ndone\n\nlemma iprev_predicate_change_exists: \"\n  \\<lbrakk> a \\<le> b; a \\<in> I; b \\<in> I; \\<not> P b; P a \\<rbrakk> \\<Longrightarrow>\n  \\<exists>n\\<in>I. a < n \\<and> n \\<le> b \\<and> \\<not> P n \\<and> P (iprev n I)\"\napply (frule inext_predicate_change_exists[of a b I \"\\<lambda>x. \\<not> P x\"], simp+)\napply clarify\napply (rule_tac x=\"inext n I\" in bexI)\n prefer 2\n apply (blast intro: inext_closed)\napply (subgoal_tac \"n < inext n I\")\n prefer 2\n apply (blast intro: inext_mono2)\napply (frule_tac x=a and z=\"inext n I\" in le_less_trans, assumption)\napply (frule less_imp_inext_le, assumption+)\napply (cut_tac n=n and I=I in iprev_inext)\n apply (case_tac \"finite I\")\n  apply simp\n  apply (rule less_imp_neq)\n  apply (blast intro: inext_closed Max_ge order_less_le_trans)\napply simp+\ndone\n\ncorollary nat_Suc_predicate_change_exists: \"\n  \\<lbrakk> a \\<le> b; \\<not> P a; P b \\<rbrakk> \\<Longrightarrow> \\<exists>n\\<ge>a. n < b \\<and> \\<not> P n \\<and> P (Suc n)\"\napply (drule inext_predicate_change_exists[OF _ UNIV_I UNIV_I], assumption+)\napply (simp add: inext_UNIV)\ndone\n\ncorollary nat_pred_predicate_change_exists: \"\n  \\<lbrakk> a \\<le> b; \\<not> P b; P a \\<rbrakk> \\<Longrightarrow> \\<exists>n\\<le>b. a < n \\<and> \\<not> P n \\<and> P (n - Suc 0)\"\napply (drule iprev_predicate_change_exists[OF _ UNIV_I UNIV_I], assumption+)\napply (fastforce simp add: iprev_UNIV)\ndone\n\n\n\nlemma inext_predicate_change_exists2_all: \"\n  \\<lbrakk> (a::nat) \\<le> b; a \\<in> I; b \\<in> I; \\<not> P a; \\<forall>k \\<in> I \\<down>\\<ge> b. P k \\<rbrakk> \\<Longrightarrow>\n  \\<exists>n\\<in>I. a \\<le> n \\<and> n < b \\<and> \\<not> P n \\<and> (\\<forall>k \\<in> I \\<down>> n. P k)\"\napply (drule order_le_less[THEN iffD1], erule disjE)\n prefer 2\n apply blast\napply (frule inext_predicate_change_exists[OF less_imp_le,\n  of a b I \"\\<lambda>n. if (n = a) then P n else (\\<forall>k\\<in>I\\<down>\\<ge>n. P k)\"])\n apply simp+\napply clarify\napply (rule_tac x=n in bexI)\n prefer 2\n apply assumption\napply (case_tac \"a < n\")\n prefer 2\n apply simp\n apply (split if_split_asm)\n  apply (subgoal_tac \"I \\<down>> n = {}\", simp+)\n apply (drule not_sym)\n apply (rule ssubst[OF cut_greater_ge_inext_conv])\n  apply assumption\n  apply (case_tac \"finite I\")\n   prefer 2\n   apply simp\n  apply simp\n  apply (rule less_imp_neq)\n  apply (drule inext_neq_imp_less)\n  apply (rule less_le_trans[OF _ Max_ge])\n  apply assumption+\napply (subgoal_tac \"a < inext n I\")\n prefer 2\n apply (blast intro: inext_mono order_less_le_trans)\napply (subgoal_tac \"I \\<down>\\<ge> inext n I = I \\<down>> n\")\n prefer 2\n apply (rule cut_greater_ge_inext_conv[symmetric], assumption)\n apply (case_tac \"finite I\")\n  apply simp\n  apply (rule less_imp_neq)\n  apply (blast intro: inext_closed Max_ge order_less_le_trans)\n apply simp\napply simp\napply (simp add: cut_greater_ge_conv_if)\napply blast\ndone\n\ncorollary inext_predicate_change_exists2: \"\n  \\<lbrakk> (a::nat) \\<le> b; a \\<in> I; b \\<in> I; \\<not> P a; P b \\<rbrakk> \\<Longrightarrow>\n  \\<exists>n\\<in>I. a \\<le> n \\<and> n < b \\<and> \\<not> P n \\<and> (\\<forall>k\\<in>I. n < k \\<and> k \\<le> b \\<longrightarrow> P k)\"\napply (frule inext_predicate_change_exists2_all[of a b \"I \\<down>\\<le> b\"])\n apply (simp add: i_cut_mem_iff)+\n apply fastforce\napply blast\ndone\n\ncorollary nat_Suc_predicate_change_exists2_all: \"\n  \\<lbrakk> (a::nat) \\<le> b; \\<not> P a; \\<forall>k\\<ge>b. P k \\<rbrakk> \\<Longrightarrow>\n  \\<exists>n\\<ge>a. n < b \\<and> \\<not> P n \\<and> (\\<forall>k>n. P k)\"\napply (drule inext_predicate_change_exists2_all[rule_format, OF _ UNIV_I UNIV_I])\napply (simp add: i_cut_mem_iff Ball_def)+\ndone\n\ncorollary nat_Suc_predicate_change_exists2: \"\n  \\<lbrakk> (a::nat) \\<le> b; \\<not> P a; P b \\<rbrakk> \\<Longrightarrow>\n  \\<exists>n\\<ge>a. n < b \\<and> \\<not> P n \\<and> (\\<forall>k\\<le>b. n < k \\<longrightarrow> P k)\"\napply (drule inext_predicate_change_exists2[of a b UNIV])\napply simp+\napply blast\ndone\n\nlemma iprev_predicate_change_exists2_all: \"\n  \\<lbrakk> (a::nat) \\<le> b; a \\<in> I; b \\<in> I; \\<not> P b; \\<forall>k\\<in>I\\<down>\\<le>a. P k \\<rbrakk> \\<Longrightarrow>\n  \\<exists>n\\<in>I. a < n \\<and> n \\<le> b \\<and> \\<not> P n \\<and> (\\<forall>k\\<in>I\\<down><n. P k)\"\napply (drule order_le_less[THEN iffD1], erule disjE)\n prefer 2\n apply blast\napply (frule iprev_predicate_change_exists[OF less_imp_le,\n  of a b I \"\\<lambda>n. if (n = b) then P n else (\\<forall>k\\<in>I\\<down>\\<le>n. P k)\"])\n apply simp+\napply clarify\napply (rule_tac x=n in bexI)\n prefer 2\n apply assumption\napply (case_tac \"a < n\")\n prefer 2\n apply simp\napply simp\napply (subgoal_tac \"iMin I < n\")\n prefer 2\n apply (blast intro: order_le_less_trans)\napply (split if_split_asm)\n apply clarsimp\n apply (split if_split_asm)\n  apply simp\n apply (simp add: cut_less_le_iprev_conv[symmetric])\n apply blast\napply (split if_split_asm)\n apply simp\napply (simp add: cut_less_le_iprev_conv[symmetric])\napply (clarsimp, rename_tac x)\napply (case_tac \"x < n\")\n apply blast\napply simp\ndone\n\n\ncorollary iprev_predicate_change_exists2: \"\n  \\<lbrakk> (a::nat) \\<le> b; a \\<in> I; b \\<in> I; \\<not> P b; P a \\<rbrakk> \\<Longrightarrow>\n  \\<exists>n\\<in>I. a < n \\<and> n \\<le> b \\<and> \\<not> P n \\<and> (\\<forall>k\\<in>I. a \\<le> k \\<and> k < n \\<longrightarrow> P k)\"\napply (frule iprev_predicate_change_exists2_all[of a b \"I \\<down>\\<ge> a\"])\n apply (simp add: i_cut_mem_iff)+\n apply fastforce\napply blast\ndone\n\ncorollary nat_pred_predicate_change_exists2_all: \"\n  \\<lbrakk> (a::nat) \\<le> b; \\<not> P b; \\<forall>k\\<le>a. P k \\<rbrakk> \\<Longrightarrow>\n  \\<exists>n>a. n \\<le> b \\<and> \\<not> P n \\<and> (\\<forall>k<n. P k)\"\napply (drule iprev_predicate_change_exists2_all[rule_format, OF _ UNIV_I UNIV_I])\napply (simp add: i_cut_mem_iff Ball_def)+\ndone\n\ncorollary nat_pred_predicate_change_exists2: \"\n  \\<lbrakk> (a::nat) \\<le> b; \\<not> P b; P a \\<rbrakk> \\<Longrightarrow>\n  \\<exists>n>a. n \\<le> b \\<and> \\<not> P n \\<and> (\\<forall>k\\<ge>a. k < n \\<longrightarrow> P k)\"\napply (drule iprev_predicate_change_exists2[of a b UNIV])\napply simp+\napply blast\ndone\n\n\nsubsection \\<open>\\<open>inext_nth\\<close> and \\<open>iprev_nth\\<close> -- nth element of a natural set\\<close>\n\nprimrec inext_nth :: \"nat set \\<Rightarrow> nat \\<Rightarrow> nat\"   (\"(_ \\<rightarrow> _)\" [100, 100] 60)\nwhere\n  \"I \\<rightarrow> 0 = iMin I\"\n| \"I \\<rightarrow> Suc n = inext (inext_nth I n) I\"\n\nlemma inext_nth_closed: \"I \\<noteq> {} \\<Longrightarrow> I \\<rightarrow> n \\<in> I\"\napply (induct n)\n apply (simp add: iMinI_ex2)\napply (simp add: inext_closed)\ndone\n\nlemma inext_nth_image: \"\n  \\<lbrakk> I \\<noteq> {}; strict_mono_on f I \\<rbrakk> \\<Longrightarrow> (f ` I) \\<rightarrow> n = f (I \\<rightarrow> n)\"\napply (induct n)\n apply (simp add: iMin_mono_on2 strict_mono_on_imp_mono_on)\napply (simp add: inext_image inext_nth_closed)\ndone\n\nlemma inext_nth_Suc_mono: \"I \\<rightarrow> n \\<le> I \\<rightarrow> Suc n\"\nby (simp add: inext_mono)\n\nlemma inext_nth_mono: \"a \\<le> b \\<Longrightarrow> I \\<rightarrow> a \\<le> I \\<rightarrow> b\"\napply (induct b)\n apply simp\napply (drule le_Suc_eq[THEN iffD1], erule disjE)\napply (rule_tac y=\"I \\<rightarrow> b\" in order_trans)\n apply simp\n apply (rule inext_nth_Suc_mono)\napply simp\ndone\n\nlemma inext_nth_Suc_mono2: \"\\<exists>x\\<in>I. I \\<rightarrow> n < x \\<Longrightarrow> I \\<rightarrow> n < I \\<rightarrow> Suc n\"\napply simp\napply (rule inext_mono2)\napply (blast intro: inext_nth_closed inext_mono2)+\ndone\n\nlemma inext_nth_mono2: \"\\<exists>x\\<in>I. I \\<rightarrow> a < x \\<Longrightarrow> (I \\<rightarrow> a < I \\<rightarrow> b) = (a < b)\"\napply (subgoal_tac \"I \\<noteq> {}\")\n prefer 2\n apply blast\napply (rule iffI)\n apply (rule ccontr)\n apply (simp add: linorder_not_less)\n apply (drule inext_nth_mono[of _ _ I])\n apply simp\napply clarify\napply (induct b)\n apply blast\napply (drule less_Suc_eq[THEN iffD1], erule disjE)\n apply (blast intro: order_less_le_trans inext_nth_Suc_mono)\napply (blast intro: inext_nth_Suc_mono2)\ndone\n\nlemma inext_nth_mono2_infin: \"\n  infinite I \\<Longrightarrow> (I \\<rightarrow> a < I \\<rightarrow> b) = (a < b)\"\napply (drule infinite_nat_iff_unbounded[THEN iffD1])\napply (rule inext_nth_mono2)\napply blast\ndone\n\nlemma inext_nth_Max_fix: \"\n  \\<lbrakk> finite I; I \\<noteq> {}; I \\<rightarrow> a = Max I; a \\<le> b \\<rbrakk> \\<Longrightarrow> I \\<rightarrow> b = Max I\"\napply (induct b)\n apply simp\napply (drule le_Suc_eq[THEN iffD1], erule disjE)\n apply (simp add: inext_Max)\napply blast\ndone\n\n\nlemma inext_nth_cut_less_conv: \"\n  \\<And>I. I \\<rightarrow> n < t \\<Longrightarrow> (I \\<down>< t) \\<rightarrow> n = I \\<rightarrow> n\"\napply (case_tac \"I = {}\")\n apply (simp add: cut_less_empty)\napply (induct n)\n apply (simp add: cut_less_Min_eq cut_less_Min_not_empty)\napply simp\napply (frule order_le_less_trans[OF inext_mono])\napply (simp add: inext_cut_less_conv)\ndone\n\nlemma remove_Min_inext_nth_Suc_conv: \"\\<And>I.\n  Suc 0 < card I \\<or> infinite I \\<Longrightarrow>\n  (I - {iMin I}) \\<rightarrow> n = I \\<rightarrow> Suc n\"\n(*apply (frule card_gt_0_iff[THEN iffD1, OF gr_implies_gr0], clarify)*)\napply (subgoal_tac \"I \\<noteq> {}\")\n prefer 2\n apply (blast dest: card_gr0_imp_not_empty[OF gr_implies_gr0])\napply (subgoal_tac \"I - {iMin I} \\<noteq> {}\")\n prefer 2\n apply (rule ccontr, simp)\n apply (erule disjE)\n  apply (drule card_mono[OF singleton_finite])\n  apply simp\n apply (simp add: subset_singleton_conv)\n apply (blast dest: infinite_imp_nonempty infinite_imp_not_singleton)\napply (induct n)\n apply (simp add: cut_greater_Min_eq_Diff[symmetric] inext_def iMinI_ex2)\napply simp\napply (rule_tac n=\"(inext (I \\<rightarrow> n) I)\" in ssubst[OF inext_def[THEN meta_eq_to_obj_eq], rule_format])\napply (rule_tac n=\"(inext (I \\<rightarrow> n) I)\" in ssubst[OF inext_def[THEN meta_eq_to_obj_eq], rule_format])\napply (simp add: inext_closed inext_nth_closed)\napply (subgoal_tac \"inext (I \\<rightarrow> n) I \\<noteq> iMin I\")\n prefer 2\n apply (erule disjE)\n apply (simp add: inext_neq_iMin_not_card_1 inext_neq_iMin_infin)+\napply (subgoal_tac \"iMin I < (I \\<rightarrow> Suc n)\")\n prefer 2\n apply (drule_tac n=\"Suc n\" in iMin_le[OF inext_nth_closed, rule_format])\n apply simp\napply (simp add: cut_greater_Diff cut_greater_singleton)\ndone\n\ncorollary remove_Min_inext_nth_Suc_conv_finite: \"Suc 0 < card I \\<Longrightarrow> (I - {iMin I}) \\<rightarrow> n = I \\<rightarrow> Suc n\"\nby (simp add: remove_Min_inext_nth_Suc_conv)\ncorollary remove_Min_inext_nth_Suc_conv_infinite: \"infinite I \\<Longrightarrow> (I - {iMin I}) \\<rightarrow> n = I \\<rightarrow> Suc n\"\nby (simp add: remove_Min_inext_nth_Suc_conv)\n\n\nlemma remove_Max_eq: \"\\<lbrakk> finite I; I \\<noteq> {}; n \\<noteq> Max I \\<rbrakk> \\<Longrightarrow> Max (I - {n}) = Max I\"\nby (rule Max_equality, simp+)\nlemma remove_iMin_eq: \"\\<lbrakk> I \\<noteq> {}; n \\<noteq> iMin I \\<rbrakk> \\<Longrightarrow> iMin (I - {n}) = iMin I\"\nby (rule iMin_equality, simp_all add: iMinI_ex2 iMin_le)\nlemma remove_Min_eq: \"\\<lbrakk> finite I; I \\<noteq> {}; n \\<noteq> Min I \\<rbrakk> \\<Longrightarrow> Min (I - {n}) = Min I\"\nby (rule Min_eqI, simp+)\nlemma Max_le_iMin_conv_singleton: \"\\<lbrakk> finite I; I \\<noteq> {} \\<rbrakk> \\<Longrightarrow> (Max I \\<le> iMin I) = (\\<exists>x. I = {x})\"\nby (simp add: iMin_Min_conv Max_le_Min_conv_singleton del: Max_le_iff Min_ge_iff)\n\n\nlemma inext_nth_card_less_Max: \"\n  \\<And>I. Suc n < card I \\<Longrightarrow> I \\<rightarrow> n < Max I\"\napply (frule card_gr0_imp_not_empty[OF less_trans[OF zero_less_Suc]])\napply (frule card_gr0_imp_finite[OF less_trans[OF zero_less_Suc]])\napply (induct n)\n apply (rule ccontr)\n apply (simp add: linorder_not_less iMin_Min_conv del: Max_le_iff Min_ge_iff)\n apply (drule Max_le_Min_conv_singleton[THEN iffD1], assumption+)\n apply clarsimp\napply (drule_tac x=\"I - {iMin I}\" in meta_spec)\napply (simp add: remove_Min_inext_nth_Suc_conv)\napply (subgoal_tac \"\\<not> I \\<subseteq> {iMin I}\")\n prefer 2\n apply (rule ccontr, simp)\n apply (drule card_mono[OF singleton_finite])\n apply simp\napply (simp add: card_Diff_singleton iMin_in Suc_less_pred_conv)\napply (subgoal_tac \"Max I \\<noteq> iMin I\")\n prefer 2\n apply (rule ccontr, simp)\n apply (frule Max_le_iMin_conv_singleton[THEN iffD1], clarsimp+)\napply (simp add: remove_Max_eq Max_le_iMin_conv_singleton)\ndone\n\nlemma inext_nth_card_less_Max': \"\n  n < card I - Suc 0 \\<Longrightarrow> I \\<rightarrow> n < Max I\"\nby (simp add: inext_nth_card_less_Max)\n\n\nlemma inext_nth_card_Max_aux: \"\n  \\<And>I. card I = Suc n \\<Longrightarrow> I \\<rightarrow> n = Max I\"\napply (frule card_gr0_imp_not_empty[OF less_le_trans[OF zero_less_Suc, OF eq_imp_le[OF sym]]])\napply (frule card_gr0_imp_finite[OF less_le_trans[OF zero_less_Suc, OF eq_imp_le[OF sym]]])\napply (induct n)\n apply (clarsimp simp: card_1_singleton_conv)\napply simp\napply (cut_tac I=I and t=\"Max I\" in nat_cut_less_finite)\napply (subgoal_tac \"card (I \\<down>< Max I) = Suc n\")\n prefer 2\n apply (simp add: cut_less_le_conv cut_le_Max_all)\napply (frule_tac n=n in card_gr0_imp_not_empty[OF less_le_trans[OF zero_less_Suc, OF eq_imp_le[OF sym]], rule_format])\napply (subgoal_tac \"Max (I \\<down>< Max I) < iMin {Max I}\")\n prefer 2\n apply (simp, blast)\napply (subgoal_tac \"inext_nth I n < Max I\")\n prefer 2\n apply (simp add: inext_nth_card_less_Max)\napply (frule inext_nth_cut_less_conv[symmetric])\napply simp\napply (rule min_step_inext)\n apply simp\n apply (rule subsetD, rule cut_less_subset, rule Max_in, assumption+)\n apply simp\napply (frule_tac A=\"I \\<down>< Max I\" and k=k in not_greater_Max, assumption)\napply (simp add: cut_less_mem_iff)\ndone\n\nlemma inext_nth_card_Max_aux': \"\n  \\<And>I. \\<lbrakk> finite I; I \\<noteq> {} \\<rbrakk> \\<Longrightarrow> I \\<rightarrow> (card I - Suc 0) = Max I\"\nby (simp add: inext_nth_card_Max_aux not_empty_card_gr0_conv)\n\nlemma inext_nth_card_Max: \"\n  \\<lbrakk> finite I; I \\<noteq> {}; card I \\<le> Suc n \\<rbrakk> \\<Longrightarrow> I \\<rightarrow> n = Max I\"\napply (rule inext_nth_Max_fix[of _ \"card I - Suc 0\"], assumption+)\napply (simp add: inext_nth_card_Max_aux')\napply simp\ndone\n\nlemma inext_nth_card_Max': \"\n  \\<lbrakk> finite I; I \\<noteq> {}; card I - Suc 0 \\<le> n \\<rbrakk> \\<Longrightarrow> I \\<rightarrow> n = Max I\"\nby (simp add: inext_nth_card_Max)\n\nlemma inext_nth_singleton: \"{a} \\<rightarrow> n = a\"\nby (simp add: inext_nth_Max_fix[OF singleton_finite singleton_not_empty _ le0])\n\nlemma inext_nth_eq_Min_conv: \"\n  I \\<noteq> {} \\<Longrightarrow> (I \\<rightarrow> n = iMin I) = (n = 0 \\<or> (\\<exists>a. I = {a}))\"\napply (rule iffI)\n apply (case_tac n, simp)\n apply (rename_tac n')\n apply (rule ccontr)\n apply (drule_tac n=\"I \\<rightarrow> n'\" in  inext_neq_iMin_not_singleton, simp)\n apply simp\napply (erule disjE, simp)\napply (clarsimp simp: inext_nth_singleton)\ndone\n\nlemma inext_nth_gr_Min_conv: \"\n  I \\<noteq> {} \\<Longrightarrow> (iMin I < I \\<rightarrow> n) = (0 < n \\<and> \\<not>(\\<exists>a. I = {a}))\"\napply (rule subst[of \"iMin I \\<noteq> I \\<rightarrow> n\" \"iMin I < I \\<rightarrow> n\"])\n apply (frule iMin_le[OF inext_nth_closed[of _ n]])\n apply (simp add: linorder_neq_iff)\napply (subst neq_commute[of \"iMin I\"])\napply (simp add: inext_nth_eq_Min_conv)\ndone\n\nlemma inext_nth_gr_Min_conv_infinite: \"\n  infinite I \\<Longrightarrow> (iMin I < I \\<rightarrow> n) = (0 < n)\"\nby (simp add: inext_nth_gr_Min_conv infinite_imp_nonempty infinite_imp_not_singleton)\n\n\nlemma inext_nth_cut_ge_inext_nth: \"\\<And>I b.\n  I \\<noteq> {} \\<Longrightarrow> I \\<down>\\<ge> (I \\<rightarrow> a) \\<rightarrow> b = I \\<rightarrow> (a + b)\"\napply (induct a)\n apply (simp add: cut_ge_Min_all)\napply (case_tac \"card I = Suc 0\")\n apply (drule card_1_imp_singleton, clarify)\n apply (simp add: inext_nth_singleton inext_singleton cut_ge_Min_all)\napply (subgoal_tac \"Suc 0 < card I \\<or> infinite I\")\n prefer 2\n apply (rule ccontr, clarsimp simp: linorder_not_less not_empty_card_gr0_conv)\napply (case_tac \"I - {iMin I} = {}\")\n apply (rule_tac t=I and s=\"{iMin I}\" in subst, blast)\n apply (simp (no_asm) add: inext_nth_singleton inext_singleton cut_ge_Min_all)\napply (simp add: subset_singleton_conv)\napply (drule_tac x=\"I - {iMin I}\" in meta_spec)\napply (drule_tac x=b in meta_spec)\napply (drule meta_mp, blast)\napply (simp add: remove_Min_inext_nth_Suc_conv)\napply (simp add: cut_ge_Diff cut_ge_singleton)\napply (subgoal_tac \"iMin I < inext (I \\<rightarrow> a) I\", simp)\napply (rule le_neq_trans[OF _ not_sym])\n apply (simp add: iMin_le inext_closed inext_nth_closed)\napply (erule disjE)\napply (simp add: inext_neq_iMin_not_card_1 inext_neq_iMin_infin)+\ndone\n\nlemma inext_nth_append_eq1: \"\n  \\<lbrakk> finite A; A \\<noteq> {}; Max A < iMin B; A \\<rightarrow> n \\<noteq> Max A \\<rbrakk> \\<Longrightarrow>\n  (A \\<union> B) \\<rightarrow> n = A \\<rightarrow> n\"\napply (case_tac \"B = {}\", simp)\napply (induct n)\n apply (simp add: iMin_Un del: Max_less_iff)\n apply (rule min_eq)\n apply (blast intro: order_less_imp_le order_le_less_trans iMin_le_Max)\napply (frule_tac n=\"Suc n\" in Max_ge[OF _ inext_nth_closed, rule_format], assumption)\napply (drule order_le_neq_trans, simp+)\napply (drule order_le_less_trans[OF inext_mono])\napply (simp add: inext_append_eq1 inext_nth_closed)\ndone\n\nlemma inext_nth_card_append_eq1: \"\n  \\<And>A B.\\<lbrakk> Max A < iMin B; n < card A \\<rbrakk> \\<Longrightarrow>\n  (A \\<union> B) \\<rightarrow> n = A \\<rightarrow> n\"\napply (case_tac \"B = {}\", simp)\napply (frule card_gr0_imp_finite[OF le_less_trans[OF le0]])\napply (frule card_gr0_imp_not_empty[OF le_less_trans[OF le0]])\napply (drule Suc_leI[of n], drule order_le_less[THEN iffD1], erule disjE)\n apply (rule inext_nth_append_eq1, assumption+)\n apply (simp add: inext_nth_card_less_Max less_imp_neq)\napply (simp add: inext_nth_card_Max[OF _ _ eq_imp_le[OF sym]] del: Max_less_iff)\napply (induct n)\n apply (frule card_1_imp_singleton[OF sym], erule exE)\n apply (simp add: iMin_insert)\napply simp\napply (subgoal_tac \"inext_nth A n < Max A\")\n prefer 2\n apply (rule inext_nth_card_less_Max, simp)\napply (simp add: inext_nth_append_eq1)\napply (rule min_step_inext)\napply (simp add: inext_nth_closed)+\napply (rule conjI)\n apply (subgoal_tac \"k < A \\<rightarrow> Suc n\")\n  prefer 2\n  apply (subgoal_tac \"A \\<rightarrow> Suc n = Max A\")\n   prefer 2\n   apply (rule inext_nth_card_Max)\n   apply simp+\n apply (rule_tac n=\"A \\<rightarrow> n\" and k=k in inext_min_step, simp+)\napply (rule not_less_iMin)\napply (rule_tac y=\"Max A\" in order_less_trans)\napply simp+\ndone\n\n\n\nlemma inext_nth_card_append_eq2: \"\n  \\<lbrakk> finite A; A \\<noteq> {}; B \\<noteq> {}; Max A < iMin B; card A \\<le> n \\<rbrakk> \\<Longrightarrow>\n  (A \\<union> B) \\<rightarrow> n = B \\<rightarrow> (n - card A)\"\napply (rule_tac t=\"(A \\<union> B) \\<rightarrow> n\" and s=\"(A \\<union> B) \\<rightarrow> (card A + (n - card A))\" in subst, simp)\napply (subst inext_nth_cut_ge_inext_nth[symmetric], simp)\napply (subst inext_nth_card_append_eq3, assumption+)\napply (simp add: cut_ge_Un cut_ge_Max_empty cut_ge_Min_all del: Max_less_iff)\ndone\n\nlemma inext_nth_card_append: \"\n  \\<lbrakk> finite A; A \\<noteq> {}; B \\<noteq> {}; Max A < iMin B \\<rbrakk> \\<Longrightarrow>\n  (A \\<union> B) \\<rightarrow> n = (if n < card A then A \\<rightarrow> n else B \\<rightarrow> (n - card A))\"\nby (simp add: inext_nth_card_append_eq1 inext_nth_card_append_eq2)\n\nlemma inext_nth_insert_Suc: \"\n  \\<lbrakk> I \\<noteq> {}; a < iMin I \\<rbrakk> \\<Longrightarrow> (insert a I) \\<rightarrow> Suc n = I \\<rightarrow> n\"\napply (frule not_less_iMin)\napply (rule_tac t=\"I \\<rightarrow> n\" and s=\"(insert a I - {iMin (insert a I)}) \\<rightarrow> n\" in subst)\n apply (simp add: iMin_insert min_eqL)\napply (subst remove_Min_inext_nth_Suc_conv)\napply (case_tac \"finite I\")\napply (simp add: not_empty_card_gr0_conv)+\ndone\n\nlemma inext_nth_cut_less_eq: \"\n  n < card (I \\<down>< t) \\<Longrightarrow> (I \\<down>< t) \\<rightarrow> n = I \\<rightarrow> n\"\napply (rule_tac t=\"I \\<rightarrow> n\" and s=\"(I \\<down>< t \\<union> I \\<down>\\<ge> t) \\<rightarrow> n\" in subst)\n apply (simp add: cut_less_cut_ge_ident)\napply (case_tac \"I \\<down>\\<ge> t = {}\", simp)\napply (rule sym, rule inext_nth_card_append_eq1)\n apply (drule card_gt_0_iff[THEN iffD1, OF gr_implies_gr0], clarify)\n apply (simp add: Ball_def i_cut_mem_iff iMin_gr_iff)\napply simp\ndone\n\nlemma less_card_cut_less_imp_inext_nth_less: \"\n  n < card (I \\<down>< t) \\<Longrightarrow> I \\<rightarrow> n < t\"\napply (case_tac \"I \\<down>< t = {}\", simp)\napply (rule subst[OF inext_nth_cut_less_eq], assumption)\napply (rule cut_less_bound[OF inext_nth_closed], assumption)\ndone\n\nlemma inext_nth_less_less_card_conv: \"\n  I \\<down>\\<ge> t \\<noteq> {} \\<Longrightarrow> (I \\<rightarrow> n < t) = (n < card (I \\<down>< t))\"\napply (case_tac \"I = {}\", blast)\napply (case_tac \"I \\<down>< t = {}\")\n apply (simp add: linorder_not_less)\n apply (simp add: cut_less_empty_iff inext_nth_closed)\napply (rule iffI)\n apply (rule ccontr, simp add: linorder_not_less)\n apply (subgoal_tac \"Max (I \\<down>< t) < iMin (I \\<down>\\<ge> t)\")\n  prefer 2\n  apply (simp add: nat_cut_less_finite iMin_gr_iff Ball_def i_cut_mem_iff)\n apply (drule ssubst[OF cut_less_cut_ge_ident[OF order_refl], of \"\\<lambda>x. x \\<rightarrow> n < t\" _ t])\n apply (drule inext_nth_card_append_eq2[OF nat_cut_less_finite, of I t \"I \\<down>\\<ge> t\" n], assumption+)\n apply (simp add: inext_nth_card_append_eq2 nat_cut_less_finite)\n apply (subgoal_tac \"\\<And>x. I \\<down>\\<ge> t \\<rightarrow> x \\<ge> t\")\n  prefer 2\n  apply (rule cut_ge_bound[OF inext_nth_closed], assumption)\n apply (simp add: linorder_not_le[symmetric])\napply (rule subst[OF inext_nth_cut_less_eq], assumption)\napply (rule cut_less_bound[OF inext_nth_closed], assumption)\ndone\n\n\nlemma cut_less_inext_nth_card_eq1: \"\n  n < card I \\<or> infinite I \\<Longrightarrow> card (I \\<down>< (I \\<rightarrow> n)) = n\"\napply (case_tac \"I = {}\", simp)\napply (induct n)\n apply (simp add: card_eq_0_iff nat_cut_less_finite cut_less_Min_empty)\napply (subgoal_tac \"n < card I \\<or> infinite I\")\n prefer 2\n apply fastforce\napply simp\napply (subgoal_tac \"I \\<rightarrow> n \\<noteq> Max I \\<or> infinite I\")\n prefer 2\n apply (blast dest: inext_nth_card_less_Max less_imp_neq)\napply (rule subst[OF cut_le_less_inext_conv[OF inext_nth_closed]], assumption+)\napply (simp add: cut_le_less_conv_if inext_nth_closed cut_less_mem_iff card_insert_if nat_cut_less_finite)\ndone\n\nlemma cut_less_inext_nth_card_eq2: \"\n  \\<lbrakk> finite I; card I \\<le> Suc n \\<rbrakk> \\<Longrightarrow> card (I \\<down>< (I \\<rightarrow> n)) = card I - Suc 0\"\napply (case_tac \"I = {}\", simp add: cut_less_empty)\napply (simp add: inext_nth_card_Max cut_less_Max_eq_Diff)\ndone\n\nlemma cut_less_inext_nth_card_if: \"\n  card (I \\<down>< (I \\<rightarrow> n)) = (\n  if (n < card I \\<or> infinite I) then n else card I - Suc 0)\"\nby (simp add: cut_less_inext_nth_card_eq1 cut_less_inext_nth_card_eq2)\n\nlemma cut_le_inext_nth_card_eq1: \"\n  n < card I \\<or> infinite I \\<Longrightarrow> card (I \\<down>\\<le> (I \\<rightarrow> n)) = Suc n\"\napply (case_tac \"I = {}\", simp)\napply (simp add: cut_le_less_conv_if inext_nth_closed card_insert_if nat_cut_less_finite cut_less_mem_iff cut_less_inext_nth_card_eq1)\ndone\n\nlemma cut_le_inext_nth_card_eq2: \"\n  \\<lbrakk> finite I; card I \\<le> Suc n \\<rbrakk> \\<Longrightarrow> card (I \\<down>\\<le> (I \\<rightarrow> n)) = card I\"\napply (case_tac \"I = {}\", simp add: cut_le_empty)\napply (simp add: inext_nth_card_Max cut_le_Max_all)\ndone\n\nlemma cut_le_inext_nth_card_if: \"\n  card (I \\<down>\\<le> (I \\<rightarrow> n)) = (\n  if (n < card I \\<or> infinite I) then Suc n else card I)\"\nby (simp add: cut_le_inext_nth_card_eq1 cut_le_inext_nth_card_eq2)\n\n\nprimrec iprev_nth :: \"nat set \\<Rightarrow> nat \\<Rightarrow> nat\"  (\"(_ \\<leftarrow> _)\" [100, 100] 60)\nwhere\n  \"I \\<leftarrow> 0 = Max I\"\n| \"I \\<leftarrow> Suc n = iprev (iprev_nth I n) I\"\n\nlemma iprev_nth_closed: \"\\<lbrakk> finite I; I \\<noteq> {} \\<rbrakk> \\<Longrightarrow> I \\<leftarrow> n \\<in> I\"\napply (induct n)\n apply simp\napply (simp add: iprev_closed)\ndone\n\nlemma iprev_nth_image: \"\n  \\<lbrakk> finite I; I \\<noteq> {}; strict_mono_on f I \\<rbrakk> \\<Longrightarrow> (f ` I) \\<leftarrow> n = f (I \\<leftarrow> n)\"\napply (induct n)\n apply (simp add: Max_mono_on2 strict_mono_on_imp_mono_on)\napply (simp add: iprev_image iprev_nth_closed)\ndone\n\nlemma iprev_nth_Suc_mono: \"I \\<leftarrow> (Suc n) \\<le> I \\<leftarrow> n\"\nby (simp add: iprev_mono)\n\nlemma iprev_nth_mono: \"a \\<le> b \\<Longrightarrow> I \\<leftarrow> b \\<le> I \\<leftarrow> a\"\napply (induct b)\n apply simp\napply (drule le_Suc_eq[THEN iffD1], erule disjE)\n apply (rule_tac y=\"iprev_nth I b\" in order_trans)\n apply (rule iprev_nth_Suc_mono)\n apply simp\napply simp\ndone\n\nlemma iprev_nth_Suc_mono2:\n  \"\\<lbrakk> finite I; \\<exists>x\\<in>I. x < I \\<leftarrow> n \\<rbrakk> \\<Longrightarrow> I \\<leftarrow> (Suc n) < I \\<leftarrow> n\"\napply simp\napply (rule iprev_mono2)\napply (blast intro: iprev_nth_closed)+\ndone\n\nlemma iprev_nth_mono2: \"\n  \\<lbrakk> finite I; \\<exists>x\\<in>I. x < I \\<leftarrow> a \\<rbrakk> \\<Longrightarrow> (I \\<leftarrow> b < I \\<leftarrow> a) = (a < b)\"\napply (subgoal_tac \"I \\<noteq> {}\")\n prefer 2\n apply blast\napply (rule iffI)\n apply (rule ccontr)\n apply (simp add: linorder_not_less)\n apply (drule iprev_nth_mono[of _ _ I])\n apply simp\napply clarify\napply (induct b)\n apply blast\napply (drule less_Suc_eq[THEN iffD1], erule disjE)\n apply (blast intro: order_le_less_trans iprev_nth_Suc_mono)\napply (blast intro: iprev_nth_Suc_mono2)\ndone\n\nlemma iprev_nth_iMin_fix: \"\n  \\<lbrakk> I \\<noteq> {}; I \\<leftarrow> a = iMin I; a \\<le> b \\<rbrakk> \\<Longrightarrow> I \\<leftarrow> b = iMin I\"\napply (induct b)\n apply simp\napply (drule le_Suc_eq[THEN iffD1], erule disjE)\n apply (simp add: iprev_iMin)\napply blast\ndone\n\nlemma iprev_nth_singleton: \"{a} \\<leftarrow> n= a\"\nby (simp add: iprev_nth_iMin_fix[OF singleton_not_empty _ le0])\n\n\nsubsection \\<open>Induction over arbitrary natural sets using the functions \\<open>inext\\<close> and \\<open>iprev\\<close>\\<close>\n\nlemma inext_nth_surj_aux1:\"\n  {x \\<in> I. \\<not>(\\<exists>n. I \\<rightarrow> n = x)} = {}\"\n  (is \"?S = {}\"\n   is \"{ x \\<in> I. ?P x} = {}\")\napply (case_tac \"I = {}\", blast)\nproof (rule ccontr)\n  assume as_S_not_empty: \"?S \\<noteq> {}\"\n\n  obtain S where s_S: \"S = ?S\" by blast\n  hence S_not_empty: \"S \\<noteq> {}\"\n    using as_S_not_empty by blast\n\n  have s_not_ex: \"\\<And>x. \\<lbrakk> x \\<in> I; ?P x \\<rbrakk> \\<Longrightarrow> x \\<in> S\"\n    using s_S by blast\n\n  have s_subset:\"S \\<subseteq> I\"\n    using s_S by blast\n  have i_not_empty: \"I \\<noteq> {}\"\n    using as_S_not_empty by blast\n\n  have s_iMin_S: \"iMin S \\<in> S\"\n    using S_not_empty by (simp add: iMinI_ex2)\n  hence s_iMin_i: \"iMin S \\<in> I\"\n    using s_subset by blast\n\n  show False\n  proof cases\n    assume as:\"iMin I < iMin S\"\n\n    obtain prev where s_prev: \"prev = iprev (iMin S) I\" by blast\n    have s_prev_in: \"prev \\<in> I\"\n      apply (simp add: s_prev)\n      apply (rule iprev_closed)\n      apply (rule s_iMin_i)\n      done\n\n    have s_prev_next_min: \"inext prev I = iMin S\"\n      apply (simp add: s_prev)\n      apply (rule inext_iprev)\n      apply (insert as, simp)\n      done\n\n    have s_prev_min_1: \"prev < iMin S\"\n      apply (simp only: s_prev)\n      apply (rule iprev_mono2[of \"iMin S\" ])\n      apply (rule s_iMin_i)\n      apply (rule_tac x=\"iMin I\" in bexI)\n      apply (rule as)\n      apply (simp add: iMinI_ex2 i_not_empty)\n      done\n    hence prev_not_in_s: \"prev \\<notin> S\"\n      by (simp add: not_less_iMin)\n    have \"\\<exists>n. I \\<rightarrow> n = prev\"\n      by (insert prev_not_in_s s_not_ex[of prev] s_prev_in, blast)\n    then obtain nPrev where s_nPrev: \"I \\<rightarrow> nPrev = prev\" by blast\n    hence \"I \\<rightarrow> (Suc nPrev) = inext prev I\" by simp\n    hence \"I \\<rightarrow> (Suc nPrev) = iMin S\"\n      using s_prev_next_min by simp\n    hence \"\\<exists>n. I \\<rightarrow> n = iMin S\" by blast\n    hence \"iMin S \\<notin> S\"\n      using s_iMin_i s_S by blast\n    thus False\n      using s_iMin_S by blast\n  next\n    assume as:\"\\<not>(iMin I < iMin S)\"\n\n    have \"iMin S = iMin I\"\n      apply (insert s_subset S_not_empty as)\n      apply (frule_tac A=S and B=I in iMin_subset)\n      by simp_all\n    hence \"\\<exists>n. I \\<rightarrow> n \\<in> S\"\n      apply (rule_tac x=0 in exI)\n      apply (insert s_iMin_S)\n      apply simp\n      done\n    thus False\n      using s_S by blast\n  qed\nqed\n\nlemma inext_nth_surj_on:\"surj_on (\\<lambda>n. I \\<rightarrow> n) UNIV I\"\napply (simp add: surj_on_conv)\nby (insert inext_nth_surj_aux1[of I], blast)\n\ncorollary in_imp_ex_inext_nth: \"x \\<in> I \\<Longrightarrow> \\<exists>n. x = I \\<rightarrow> n\"\napply (rule surj_onD[where A=UNIV, simplified])\napply (rule inext_nth_surj_on)\napply assumption\ndone\n\nlemma inext_induct: \"\n  \\<lbrakk> P (iMin I); \\<And>n. \\<lbrakk> n \\<in> I; P n \\<rbrakk> \\<Longrightarrow> P (inext n I); n \\<in> I \\<rbrakk> \\<Longrightarrow> P n\"\napply (rule_tac f=\"\\<lambda>n. I \\<rightarrow> n\" and I=I in image_nat_induct)\napply (simp add: inext_nth_closed[OF in_imp_not_empty] inext_nth_surj_on)+\ndone\n\nlemma iprev_nth_surj_aux1:\"\n  finite I \\<Longrightarrow> { x \\<in> I. \\<not>(\\<exists>n. I \\<leftarrow> n = x)} = {}\"\napply (case_tac \"I = {}\", blast)\nproof (rule ccontr)\n  assume as_finite_i: \"finite I\"\n  let ?S = \"{x \\<in> I. \\<not> (\\<exists>n. I \\<leftarrow> n = x)}\"\n  assume as_S_not_empty: \"?S \\<noteq> {}\"\n\n  obtain S where s_S: \"S = ?S\" by blast\n  hence S_not_empty: \"S \\<noteq> {}\"\n    using as_S_not_empty by blast\n\n  have s_not_ex: \"\\<And>x. \\<lbrakk> x \\<in> I; \\<not>(\\<exists>n. I \\<leftarrow> n = x) \\<rbrakk> \\<Longrightarrow> x \\<in> S\"\n    using s_S by blast\n\n  have s_subset:\"S \\<subseteq> I\"\n    using s_S by blast\n  have i_not_empty: \"I \\<noteq> {}\"\n    using as_S_not_empty by blast\n\n  from as_finite_i\n  have S_finite: \"finite S\"\n    using s_subset by (blast intro: finite_subset)\n\n  have s_Max_S: \"Max S \\<in> S\"\n    using S_not_empty S_finite by simp\n  hence s_Max_i: \"Max S \\<in> I\"\n    using s_subset by blast\n\n  show False\n  proof cases\n    assume as:\"Max S < Max I\"\n\n    obtain next' where s_next: \"next' = inext (Max S) I\" by blast\n    have s_next_in: \"next' \\<in> I\"\n      by (simp add: s_next inext_closed s_Max_i)\n\n    have s_next_prev_max: \"iprev next' I = Max S\"\n      apply (simp add: s_next)\n      apply (rule iprev_inext)\n      apply (insert as, simp)\n      done\n\n    have s_next_max_1: \"Max S < next'\"\n      apply (simp add: s_next)\n      apply (rule inext_mono2[of \"Max S\" I])\n      apply (rule s_Max_i)\n      apply (rule_tac x=\"Max I\" in bexI)\n      apply (rule as)\n      apply (simp add: as_finite_i i_not_empty)\n      done\n    hence next_not_in_s: \"next' \\<notin> S\"\n      using S_finite S_not_empty\n      apply clarify\n      apply (drule Max_ge[of _ next'])\n      apply simp_all\n      done\n    have \"\\<exists>n. I \\<leftarrow> n = next'\"\n      by (insert next_not_in_s s_not_ex[of next'] s_next_in, blast)\n    then obtain nNext where s_nNext: \"I \\<leftarrow> nNext = next'\" by blast\n    hence \"I \\<leftarrow> (Suc nNext) = iprev next' I\" by simp\n    hence \"I \\<leftarrow> (Suc nNext) = Max S\"\n      using s_next_prev_max by simp\n    hence \"\\<exists>n. I \\<leftarrow> n = Max S\" by blast\n    hence \"Max S \\<notin> S\"\n      using s_Max_i s_S by blast\n    thus False\n      using s_Max_S by blast+\n  next\n    assume as:\"\\<not>(Max S < Max I)\"\n\n    have \"Max S = Max I\"\n      apply (insert s_subset S_not_empty as_finite_i as)\n      apply (drule Max_subset[of _ I])\n      by simp_all\n    hence \"\\<exists>n. I \\<leftarrow> n \\<in> S\"\n      apply (rule_tac x=0 in exI)\n      apply (insert s_Max_S)\n      apply simp\n      done\n    thus False\n      using s_S by blast\n  qed\nqed\n\nlemma iprev_nth_surj_on: \"finite I \\<Longrightarrow> surj_on (\\<lambda>n. I \\<leftarrow> n) UNIV I\"\napply (simp add: surj_on_def)\nby (insert iprev_nth_surj_aux1[of I], blast)\n\ncorollary in_imp_ex_iprev_nth: \"\n  \\<lbrakk> finite I;  x \\<in> I \\<rbrakk> \\<Longrightarrow> \\<exists>n. x = I \\<leftarrow> n\"\napply (rule surj_onD[of _ UNIV I, simplified])\napply (rule iprev_nth_surj_on)\napply assumption+\ndone\n\nlemma iprev_induct: \"\n  \\<lbrakk> P (Max I); \\<And>n. \\<lbrakk> n \\<in> I; P n \\<rbrakk> \\<Longrightarrow> P (iprev n I); finite I; n \\<in> I \\<rbrakk> \\<Longrightarrow> P n\"\napply (rule_tac f=\"\\<lambda>n. I \\<leftarrow> n\" and I=I in image_nat_induct)\napply (simp add: iprev_nth_closed[OF _ in_imp_not_empty] iprev_nth_surj_on)+\ndone\n\n\nsubsection \\<open>Natural intervals with \\<open>inext\\<close> and \\<open>iprev\\<close>\\<close>\n\nlemma inext_atLeast: \"n \\<le> t \\<Longrightarrow> inext t {n..} = Suc t\"\napply (unfold inext_def)\napply (subgoal_tac \"Suc t \\<in> {n..} \\<down>> t\")\n prefer 2\n apply (simp add: cut_greater_mem_iff)\napply (simp add: in_imp_not_empty)\napply (rule iMin_equality, assumption)\napply (simp add: cut_greater_mem_iff)\ndone\n\nlemma iprev_atLeast': \"n \\<le> t \\<Longrightarrow> iprev (Suc t) {n..} = t\"\napply (rule subst[OF inext_atLeast], assumption)\napply (rule iprev_inext_infin[OF infinite_atLeast])\ndone\n\nlemma iprev_atLeast: \"n < t  \\<Longrightarrow> iprev t {n..} = t - Suc 0\"\nby (insert iprev_atLeast'[of n \"t - Suc 0\"], simp)\n\nlemma inext_atMost: \"t < n \\<Longrightarrow> inext t {..n} = Suc t\"\napply (unfold inext_def)\napply (subgoal_tac \"Suc t \\<in> {..n} \\<down>> t\")\n prefer 2\n apply (simp add: cut_greater_mem_iff)\napply (simp add: in_imp_not_empty)\napply (rule iMin_equality, assumption)\napply (simp add: cut_greater_mem_iff)\ndone\n\nlemma iprev_atMost: \"t \\<le> n \\<Longrightarrow> iprev t {..n} = t - Suc 0\"\napply (case_tac t)\n apply simp\n apply (rule subst[OF iMin_atMost[of n]])\n apply (rule iprev_iMin)\napply simp\napply (drule Suc_le_lessD)\napply (rule subst[OF inext_atMost], assumption)\napply (simp add: Max_atMost iprev_inext_fin)\ndone\n\nlemma inext_lessThan: \"Suc t < n \\<Longrightarrow> inext t {..<n} = Suc t\"\napply (rule subst[OF Suc_pred, of n], simp)\napply (subst lessThan_Suc_atMost)\napply (simp add: inext_atMost)\ndone\nlemma iprev_lessThan: \"t < n \\<Longrightarrow> iprev t {..<n} = t - Suc 0\"\napply (case_tac n, simp)\napply (simp add: lessThan_Suc_atMost iprev_atMost)\ndone\n\nlemma inext_atLeastAtMost: \"\\<lbrakk> m \\<le> t; t < n \\<rbrakk> \\<Longrightarrow> inext t {m..n} = Suc t\"\nby (simp add: atLeastAtMost_def cut_le_Int_conv[symmetric] inext_atLeast inext_cut_le_conv)\nlemma iprev_atLeastAtMost: \"\\<lbrakk> m < t; t \\<le> n \\<rbrakk> \\<Longrightarrow> iprev t {m..n} = t - Suc 0\"\nby (simp add: atLeastAtMost_def cut_le_Int_conv[symmetric] iprev_atLeast iprev_cut_le_conv)\nlemma iprev_atLeastAtMost': \"\\<lbrakk> m \\<le> t; t < n \\<rbrakk> \\<Longrightarrow> iprev (Suc t) {m..n} = t\"\nby (simp add: iprev_atLeastAtMost[of _ \"Suc t\"])\n\nlemma inext_nth_atLeast : \"{n..} \\<rightarrow> a = n + a\"\napply (induct a, simp add: iMin_atLeast)\napply (simp add: inext_atLeast)\ndone\n\n\nlemma inext_nth_lessThan : \"a < n \\<Longrightarrow> {..<n} \\<rightarrow> a = a\"\napply (case_tac n, simp)\napply (simp add: lessThan_Suc_atMost inext_nth_atMost)\ndone\nlemma iprev_nth_lessThan: \"a < n \\<Longrightarrow> {..<n} \\<leftarrow> a = n - Suc a\"\napply (case_tac n, simp)\napply (simp add: lessThan_Suc_atMost iprev_nth_atMost)\ndone\n\nlemma inext_nth_UNIV: \"UNIV \\<rightarrow> a = a\"\nby (simp add: inext_nth_atLeast del: atLeast_0 add: atLeast_0[symmetric])\n\n\nsubsection \\<open>Further result for \\<open>inext_nth\\<close> and \\<open>iprev_nth\\<close>\\<close>\n\nlemma inext_iprev_nth_Suc: \"\n  iMin I \\<noteq> I \\<leftarrow> n \\<Longrightarrow> inext (I \\<leftarrow> Suc n) I = I \\<leftarrow> n\"\nby (simp add: inext_iprev)\n\nlemma inext_iprev_nth_pred: \"\n  \\<lbrakk> finite I; iMin I \\<noteq> I \\<leftarrow> (n - Suc 0) \\<rbrakk> \\<Longrightarrow>\n  inext (I \\<leftarrow> n) I = I \\<leftarrow> (n - Suc 0)\"\napply (case_tac n)\n apply (simp add: inext_Max)\napply (simp add: inext_iprev)\ndone\n\nlemma iprev_inext_nth_Suc: \"\n  I \\<rightarrow> n \\<noteq> Max I \\<or> infinite I \\<Longrightarrow> iprev (I \\<rightarrow> Suc n) I = I \\<rightarrow> n\"\nby (simp add: iprev_inext)\nlemma iprev_inext_nth_pred: \"\n  I \\<rightarrow> (n - Suc 0) \\<noteq> Max I \\<or> infinite I \\<Longrightarrow>\n  iprev (I \\<rightarrow> n) I = I \\<rightarrow> (n - Suc 0)\"\napply (case_tac n)\n apply (simp add: iprev_iMin)\napply (simp add: iprev_inext)\ndone\n\nlemma inext_nth_imirror_iprev_nth_conv: \"\n  \\<lbrakk> finite I; I \\<noteq> {} \\<rbrakk> \\<Longrightarrow>\n  (imirror I) \\<rightarrow> n = mirror_elem (I \\<leftarrow> n) I\"\napply (induct n)\n apply (simp add: imirror_iMin mirror_elem_Max)\napply (simp add: inext_imirror_iprev_conv' iprev_nth_closed)\ndone\n\ncorollary inext_nth_imirror_iprev_nth_conv2: \"\n  \\<lbrakk> finite I; I \\<noteq> {} \\<rbrakk> \\<Longrightarrow>\n  mirror_elem ((imirror I) \\<leftarrow> n) I = I \\<rightarrow> n\"\napply (frule inext_nth_imirror_iprev_nth_conv[OF imirror_finite imirror_not_empty, of _ n], assumption)\napply (simp add: imirror_imirror_ident mirror_elem_imirror)\ndone\n\n\nlemma iprev_nth_imirror_inext_nth_conv: \"\n  \\<lbrakk> finite I; I \\<noteq> {} \\<rbrakk> \\<Longrightarrow>\n  (imirror I) \\<leftarrow> n = mirror_elem (I \\<rightarrow> n) I\"\napply (induct n)\n apply (simp add: imirror_Max mirror_elem_Min)\napply (simp add: iprev_imirror_inext_conv' inext_nth_closed)\ndone\n\ncorollary iprev_nth_imirror_inext_nth_conv2: \"\n  \\<lbrakk> finite I; I \\<noteq> {} \\<rbrakk> \\<Longrightarrow>\n  mirror_elem ((imirror I) \\<rightarrow> n) I = (I \\<leftarrow> n)\"\napply (frule iprev_nth_imirror_inext_nth_conv[OF imirror_finite imirror_not_empty, of _ n], assumption)\napply (simp add: imirror_imirror_ident mirror_elem_imirror)\ndone\n\nlemma iprev_nth_card_greater_iMin: \"Suc n < card I \\<Longrightarrow> iMin I < I \\<leftarrow> n\"\napply (subgoal_tac \"I \\<noteq> {}\" \"finite I\")\n prefer 2\n apply (rule card_gr0_imp_finite, simp)\n prefer 2\n apply (rule card_gr0_imp_not_empty, simp)\napply (subst iprev_nth_imirror_inext_nth_conv2[symmetric], assumption+)\napply (subst mirror_elem_Max[symmetric], assumption+)\napply (subst mirror_elem_imirror[symmetric], assumption)\napply (subst mirror_elem_imirror[symmetric], assumption)\napply (frule imirror_finite, frule imirror_not_empty)\napply (rule mirror_elem_less_conv[THEN iffD2])\n apply assumption\n apply (rule inext_nth_closed, assumption)\n apply (rule subst[OF imirror_Max], assumption)\n apply (rule Max_in, assumption+)\napply (rule subst[OF imirror_Max], assumption)\napply (simp add: inext_nth_card_less_Max imirror_card)\ndone\n\nlemma iprev_nth_card_iMin: \"\n  \\<lbrakk> finite I; I \\<noteq> {}; card I \\<le> Suc n \\<rbrakk> \\<Longrightarrow> I \\<leftarrow> n = iMin I\"\napply (subst iprev_nth_imirror_inext_nth_conv2[symmetric], assumption+)\napply (subst mirror_elem_Max[symmetric], assumption+)\napply (subst mirror_elem_imirror[symmetric], assumption)\napply (subst mirror_elem_imirror[symmetric], assumption)\napply (rule subst[OF imirror_Max], assumption)\napply (frule imirror_finite, frule imirror_not_empty)\napply (simp add: mirror_elem_eq_conv' inext_nth_closed inext_nth_card_Max imirror_card)\ndone\n\nlemma iprev_nth_card_iMin': \"\n  \\<lbrakk> finite I; I \\<noteq> {}; card I - Suc 0 \\<le> n \\<rbrakk> \\<Longrightarrow> I \\<leftarrow> n = iMin I\"\nby (simp add: iprev_nth_card_iMin)\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/CommonSet/SetIntervalStep.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8791467738423873, "lm_q2_score": 0.8519528019683105, "lm_q1q2_score": 0.7489915573164224}}
{"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.*)\n  theory TIP_prop_09\n  imports \"../../Test_Base\"\nbegin\n\ndatatype 'a list = nil2 | cons2 \"'a\" \"'a list\"\n\ndatatype Nat = Z | S \"Nat\"\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\nlemma drop_nil: \"drop n nil2 = nil2\"\n  by(case_tac n, auto)\n\nlemma drop_succ: \"drop (S n) (drop m l) = drop n (drop (S m) l)\" \n  apply(induction l)\n   apply(simp add: drop_nil, simp)\n  apply(induction m, auto)\n  apply(case_tac l, simp add: drop_nil, auto)\n  done\n\nlemma drop_comm: \"((drop x (drop y z)) = (drop y (drop x z)))\"\n  apply(induct z rule: drop.induct, auto)\n  apply(case_tac y, auto)\n  apply(simp add: drop_succ)\n  done\n\ntheorem property0 :\n  \"((drop w (drop x (drop y z))) = (drop y (drop x (drop w z))))\"\n  apply(induct z rule: drop.induct, auto)\n    apply(rule drop_comm)\n   apply(case_tac y, simp_all add: drop_nil drop_succ)\n  done\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_09.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513731336204, "lm_q2_score": 0.8354835432479661, "lm_q1q2_score": 0.7488032728665321}}
{"text": "(* Title: thys/UF.thy\n   Author: Jian Xu, Xingyuan Zhang, and Christian Urban\n   Modifications: Sebastiaan Joosten\n*)\n\nchapter \\<open>Construction of a Universal Function\\<close>\n\ntheory UF\n  imports Rec_Def HOL.GCD Abacus\nbegin\n\ntext \\<open>\n  This theory file constructs the Universal Function \\<open>rec_F\\<close>, which is the UTM defined\n  in terms of recursive functions. This \\<open>rec_F\\<close> is essentially an \n  interpreter of Turing Machines. Once the correctness of \\<open>rec_F\\<close> is established,\n  UTM can easil be obtained by compling \\<open>rec_F\\<close> into the corresponding Turing Machine.\n\\<close>\n\nsection \\<open>Universal Function\\<close>\n\nsubsection \\<open>The construction of component functions\\<close>\n\ntext \\<open>\n  The recursive function used to do arithmetic addition.\n\\<close>\ndefinition rec_add :: \"recf\"\n  where\n    \"rec_add \\<equiv>  Pr 1 (id 1 0) (Cn 3 s [id 3 2])\"\n\ntext \\<open>\n  The recursive function used to do arithmetic multiplication.\n\\<close>\ndefinition rec_mult :: \"recf\"\n  where\n    \"rec_mult = Pr 1 z (Cn 3 rec_add [id 3 0, id 3 2])\"\n\ntext \\<open>\n  The recursive function used to do arithmetic precede.\n\\<close>\ndefinition rec_pred :: \"recf\"\n  where\n    \"rec_pred = Cn 1 (Pr 1 z (id 3 1)) [id 1 0, id 1 0]\"\n\ntext \\<open>\n  The recursive function used to do arithmetic subtraction.\n\\<close>\ndefinition rec_minus :: \"recf\" \n  where\n    \"rec_minus = Pr 1 (id 1 0) (Cn 3 rec_pred [id 3 2])\"\n\ntext \\<open>\n  \\<open>constn n\\<close> is the recursive function which computes \n  nature number \\<open>n\\<close>.\n\\<close>\nfun constn :: \"nat \\<Rightarrow> recf\"\n  where\n    \"constn 0 = z\"  |\n    \"constn (Suc n) = Cn 1 s [constn n]\"\n\n\ntext \\<open>\n  Sign function, which returns 1 when the input argument is greater than \\<open>0\\<close>.\n\\<close>\ndefinition rec_sg :: \"recf\"\n  where\n    \"rec_sg = Cn 1 rec_minus [constn 1, \n                  Cn 1 rec_minus [constn 1, id 1 0]]\"\n\ntext \\<open>\n  \\<open>rec_less\\<close> compares its two arguments, returns \\<open>1\\<close> if\n  the first is less than the second; otherwise returns \\<open>0\\<close>.\n\\<close>\ndefinition rec_less :: \"recf\"\n  where\n    \"rec_less = Cn 2 rec_sg [Cn 2 rec_minus [id 2 1, id 2 0]]\"\n\ntext \\<open>\n  \\<open>rec_not\\<close> inverse its argument: returns \\<open>1\\<close> when the\n  argument is \\<open>0\\<close>; returns \\<open>0\\<close> otherwise.\n\\<close>\ndefinition rec_not :: \"recf\"\n  where\n    \"rec_not = Cn 1 rec_minus [constn 1, id 1 0]\"\n\ntext \\<open>\n  \\<open>rec_eq\\<close> compares its two arguments: returns \\<open>1\\<close>\n  if they are equal; return \\<open>0\\<close> otherwise.\n\\<close>\ndefinition rec_eq :: \"recf\"\n  where\n    \"rec_eq = Cn 2 rec_minus [Cn 2 (constn 1) [id 2 0], \n             Cn 2 rec_add [Cn 2 rec_minus [id 2 0, id 2 1], \n               Cn 2 rec_minus [id 2 1, id 2 0]]]\"\n\ntext \\<open>\n  \\<open>rec_conj\\<close> computes the conjunction of its two arguments, \n  returns \\<open>1\\<close> if both of them are non-zero; returns \\<open>0\\<close>\n  otherwise.\n\\<close>\ndefinition rec_conj :: \"recf\"\n  where\n    \"rec_conj = Cn 2 rec_sg [Cn 2 rec_mult [id 2 0, id 2 1]] \"\n\ntext \\<open>\n  \\<open>rec_disj\\<close> computes the disjunction of its two arguments, \n  returns \\<open>0\\<close> if both of them are zero; returns \\<open>0\\<close>\n  otherwise.\n\\<close>\ndefinition rec_disj :: \"recf\"\n  where\n    \"rec_disj = Cn 2 rec_sg [Cn 2 rec_add [id 2 0, id 2 1]]\"\n\n\ntext \\<open>\n  Computes the arity of recursive function.\n\\<close>\n\nfun arity :: \"recf \\<Rightarrow> nat\"\n  where\n    \"arity z = 1\" \n  | \"arity s = 1\"\n  | \"arity (id m n) = m\"\n  | \"arity (Cn n f gs) = n\"\n  | \"arity (Pr n f g) = Suc n\"\n  | \"arity (Mn n f) = n\"\n\ntext \\<open>\n  \\<open>get_fstn_args n (Suc k)\\<close> returns\n  \\<open>[id n 0, id n 1, id n 2, \\<dots>, id n k]\\<close>, \n  the effect of which is to take out the first \\<open>Suc k\\<close> \n  arguments out of the \\<open>n\\<close> input arguments.\n\\<close>\n\nfun get_fstn_args :: \"nat \\<Rightarrow>  nat \\<Rightarrow> recf list\"\n  where\n    \"get_fstn_args n 0 = []\"\n  | \"get_fstn_args n (Suc y) = get_fstn_args n y @ [id n y]\"\n\ntext \\<open>\n  \\<open>rec_sigma f\\<close> returns the recursive functions which \n  sums up the results of \\<open>f\\<close>:\n  \\[\n  (rec\\_sigma f)(x, y) = f(x, 0) + f(x, 1) + \\cdots + f(x, y)\n  \\]\n\\<close>\nfun rec_sigma :: \"recf \\<Rightarrow> recf\"\n  where\n    \"rec_sigma rf = \n       (let vl = arity rf in \n          Pr (vl - 1) (Cn (vl - 1) rf (get_fstn_args (vl - 1) (vl - 1) @ \n                    [Cn (vl - 1) (constn 0) [id (vl - 1) 0]])) \n             (Cn (Suc vl) rec_add [id (Suc vl) vl, \n                    Cn (Suc vl) rf (get_fstn_args (Suc vl) (vl - 1) \n                        @ [Cn (Suc vl) s [id (Suc vl) (vl - 1)]])]))\"\n\ntext \\<open>\n  \\<open>rec_exec\\<close> is the interpreter function for\n  reursive functions. The function is defined such that \n  it always returns meaningful results for primitive recursive \n  functions.\n\\<close>\n\ndeclare rec_exec.simps[simp del] constn.simps[simp del]\n\ntext \\<open>\n  Correctness of \\<open>rec_add\\<close>.\n\\<close>\nlemma add_lemma: \"\\<And> x y. rec_exec rec_add [x, y] =  x + y\"\n  by(induct_tac y, auto simp: rec_add_def rec_exec.simps)\n\ntext \\<open>\n  Correctness of \\<open>rec_mult\\<close>.\n\\<close>\nlemma mult_lemma: \"\\<And> x y. rec_exec rec_mult [x, y] = x * y\"\n  by(induct_tac y, auto simp: rec_mult_def rec_exec.simps add_lemma)\n\ntext \\<open>\n  Correctness of \\<open>rec_pred\\<close>.\n\\<close>\nlemma pred_lemma: \"\\<And> x. rec_exec rec_pred [x] =  x - 1\"\n  by(induct_tac x, auto simp: rec_pred_def rec_exec.simps)\n\ntext \\<open>\n  Correctness of \\<open>rec_minus\\<close>.\n\\<close>\nlemma minus_lemma: \"\\<And> x y. rec_exec rec_minus [x, y] = x - y\"\n  by(induct_tac y, auto simp: rec_exec.simps rec_minus_def pred_lemma)\n\ntext \\<open>\n  Correctness of \\<open>rec_sg\\<close>.\n\\<close>\nlemma sg_lemma: \"\\<And> x. rec_exec rec_sg [x] = (if x = 0 then 0 else 1)\"\n  by(auto simp: rec_sg_def minus_lemma rec_exec.simps constn.simps)\n\ntext \\<open>\n  Correctness of \\<open>constn\\<close>.\n\\<close>\nlemma constn_lemma: \"rec_exec (constn n) [x] = n\"\n  by(induct n, auto simp: rec_exec.simps constn.simps)\n\ntext \\<open>\n  Correctness of \\<open>rec_less\\<close>.\n\\<close>\nlemma less_lemma: \"\\<And> x y. rec_exec rec_less [x, y] = \n  (if x < y then 1 else 0)\"\n  by(induct_tac y, auto simp: rec_exec.simps \n      rec_less_def minus_lemma sg_lemma)\n\ntext \\<open>\n  Correctness of \\<open>rec_not\\<close>.\n\\<close>\n\n\ntext \\<open>\n  Correctness of \\<open>rec_eq\\<close>.\n\\<close>\nlemma eq_lemma: \"\\<And> x y. rec_exec rec_eq [x, y] = (if x = y then 1 else 0)\"\n  by(induct_tac y, auto simp: rec_exec.simps rec_eq_def constn_lemma add_lemma minus_lemma)\n\ntext \\<open>\n  Correctness of \\<open>rec_conj\\<close>.\n\\<close>\nlemma conj_lemma: \"\\<And> x y. rec_exec rec_conj [x, y] = (if x = 0 \\<or> y = 0 then 0 \n                                                       else 1)\"\n  by(induct_tac y, auto simp: rec_exec.simps sg_lemma rec_conj_def mult_lemma)\n\ntext \\<open>\n  Correctness of \\<open>rec_disj\\<close>.\n\\<close>\nlemma disj_lemma: \"\\<And> x y. rec_exec rec_disj [x, y] = (if x = 0 \\<and> y = 0 then 0\n                                                     else 1)\"\n  by(induct_tac y, auto simp: rec_disj_def sg_lemma add_lemma rec_exec.simps)\n\n\ntext \\<open>\n  \\<open>primrec recf n\\<close> is true iff \n  \\<open>recf\\<close> is a primitive recursive function \n  with arity \\<open>n\\<close>.\n\\<close>\ninductive primerec :: \"recf \\<Rightarrow> nat \\<Rightarrow> bool\"\n  where\n    prime_z[intro]:  \"primerec z (Suc 0)\" |\n    prime_s[intro]:  \"primerec s (Suc 0)\" |\n    prime_id[intro!]: \"\\<lbrakk>n < m\\<rbrakk> \\<Longrightarrow> primerec (id m n) m\" |\n    prime_cn[intro!]: \"\\<lbrakk>primerec f k; length gs = k; \n  \\<forall> i < length gs. primerec (gs ! i) m; m = n\\<rbrakk> \n  \\<Longrightarrow> primerec (Cn n f gs) m\" |\n    prime_pr[intro!]: \"\\<lbrakk>primerec f n; \n  primerec g (Suc (Suc n)); m = Suc n\\<rbrakk> \n  \\<Longrightarrow> primerec (Pr n f g) m\" \n\ninductive_cases prime_cn_reverse'[elim]: \"primerec (Cn n f gs) n\" \ninductive_cases prime_mn_reverse: \"primerec (Mn n f) m\" \ninductive_cases prime_z_reverse[elim]: \"primerec z n\"\ninductive_cases prime_s_reverse[elim]: \"primerec s n\"\ninductive_cases prime_id_reverse[elim]: \"primerec (id m n) k\"\ninductive_cases prime_cn_reverse[elim]: \"primerec (Cn n f gs) m\"\ninductive_cases prime_pr_reverse[elim]: \"primerec (Pr n f g) m\"\n\ndeclare mult_lemma[simp] add_lemma[simp] pred_lemma[simp] \n  minus_lemma[simp] sg_lemma[simp] constn_lemma[simp] \n  less_lemma[simp] not_lemma[simp] eq_lemma[simp]\n  conj_lemma[simp] disj_lemma[simp]\n\ntext \\<open>\n  \\<open>Sigma\\<close> is the logical specification of \n  the recursive function \\<open>rec_sigma\\<close>.\n\\<close>\nfunction Sigma :: \"(nat list \\<Rightarrow> nat) \\<Rightarrow> nat list \\<Rightarrow> nat\"\n  where\n    \"Sigma g xs = (if last xs = 0 then g xs\n                 else (Sigma g (butlast xs @ [last xs - 1]) +\n                       g xs)) \"\n  by pat_completeness auto\ntermination\nproof\n  show \"wf (measure (\\<lambda> (f, xs). last xs))\" by auto\nnext\n  fix g xs\n  assume \"last (xs::nat list) \\<noteq> 0\"\n  thus \"((g, butlast xs @ [last xs - 1]), g, xs)  \n                   \\<in> measure (\\<lambda>(f, xs). last xs)\"\n    by auto\nqed\n\ndeclare rec_exec.simps[simp del] get_fstn_args.simps[simp del]\n  arity.simps[simp del] Sigma.simps[simp del]\n  rec_sigma.simps[simp del]\n\nlemma rec_pr_Suc_simp_rewrite: \n  \"rec_exec (Pr n f g) (xs @ [Suc x]) =\n                       rec_exec g (xs @ [x] @ \n                        [rec_exec (Pr n f g) (xs @ [x])])\"\n  by(simp add: rec_exec.simps)\n\nlemma Sigma_0_simp_rewrite:\n  \"Sigma f (xs @ [0]) = f (xs @ [0])\"\n  by(simp add: Sigma.simps)\n\nlemma Sigma_Suc_simp_rewrite: \n  \"Sigma f (xs @ [Suc x]) = Sigma f (xs @ [x]) + f (xs @ [Suc x])\"\n  by(simp add: Sigma.simps)\n\nlemma append_access_1[simp]: \"(xs @ ys) ! (Suc (length xs)) = ys ! 1\"\n  by(simp add: nth_append)\n\nlemma get_fstn_args_take: \"\\<lbrakk>length xs = m; n \\<le> m\\<rbrakk> \\<Longrightarrow> \n  map (\\<lambda> f. rec_exec f xs) (get_fstn_args m n)= take n xs\"\nproof(induct n)\n  case 0 thus \"?case\"\n    by(simp add: get_fstn_args.simps)\nnext\n  case (Suc n) thus \"?case\"\n    by(simp add: get_fstn_args.simps rec_exec.simps \n        take_Suc_conv_app_nth)\nqed\n\nlemma arity_primerec[simp]: \"primerec f n \\<Longrightarrow> arity f = n\"\n  apply(cases f)\n       apply(auto simp: arity.simps )\n  apply(erule_tac prime_mn_reverse)\n  done\n\n\n\ntext \\<open>\n  The correctness of \\<open>rec_sigma\\<close> with respect to its specification.\n\\<close>\n\n\ntext \\<open>\n  \\<open>rec_accum f (x1, x2, \\<dots>, xn, k) = \n           f(x1, x2, \\<dots>, xn, 0) * \n           f(x1, x2, \\<dots>, xn, 1) *\n               \\<dots> \n           f(x1, x2, \\<dots>, xn, k)\\<close>\n\\<close>\nfun rec_accum :: \"recf \\<Rightarrow> recf\"\n  where\n    \"rec_accum rf = \n       (let vl = arity rf in \n          Pr (vl - 1) (Cn (vl - 1) rf (get_fstn_args (vl - 1) (vl - 1) @ \n                     [Cn (vl - 1) (constn 0) [id (vl - 1) 0]])) \n             (Cn (Suc vl) rec_mult [id (Suc vl) (vl), \n                    Cn (Suc vl) rf (get_fstn_args (Suc vl) (vl - 1) \n                      @ [Cn (Suc vl) s [id (Suc vl) (vl - 1)]])]))\"\n\ntext \\<open>\n  \\<open>Accum\\<close> is the formal specification of \\<open>rec_accum\\<close>.\n\\<close>\nfunction Accum :: \"(nat list \\<Rightarrow> nat) \\<Rightarrow> nat list \\<Rightarrow> nat\"\n  where\n    \"Accum f xs = (if last xs = 0 then f xs \n                     else (Accum f (butlast xs @ [last xs - 1]) *\n                       f xs))\"\n  by pat_completeness auto\ntermination\nproof\n  show \"wf (measure (\\<lambda> (f, xs). last xs))\"\n    by auto\nnext\n  fix f xs\n  assume \"last xs \\<noteq> (0::nat)\"\n  thus \"((f, butlast xs @ [last xs - 1]), f, xs) \\<in> \n            measure (\\<lambda>(f, xs). last xs)\"\n    by auto\nqed\n\nlemma rec_accum_Suc_simp_rewrite: \n  \"primerec f (Suc (length xs))\n    \\<Longrightarrow> rec_exec (rec_accum f) (xs @ [Suc x]) = \n    rec_exec (rec_accum f) (xs @ [x]) * rec_exec f (xs @ [Suc x])\"\n  apply(induct x)\n   apply(auto simp: rec_sigma.simps Let_def rec_pr_Suc_simp_rewrite\n      rec_exec.simps get_fstn_args_take)\n  done  \n\ntext \\<open>\n  The correctness of \\<open>rec_accum\\<close> with respect to its specification.\n\\<close>\nlemma accum_lemma :\n  \"primerec rg (Suc (length xs))\n     \\<Longrightarrow> rec_exec (rec_accum rg) (xs @ [x]) = Accum (rec_exec rg) (xs @ [x])\"\n  apply(induct x)\n   apply(auto simp: rec_exec.simps rec_sigma.simps Let_def \n      get_fstn_args_take)\n  done\n\ndeclare rec_accum.simps [simp del]\n\ntext \\<open>\n  \\<open>rec_all t f (x1, x2, \\<dots>, xn)\\<close> \n  computes the charactrization function of the following FOL formula:\n  \\<open>(\\<forall> x \\<le> t(x1, x2, \\<dots>, xn). (f(x1, x2, \\<dots>, xn, x) > 0))\\<close>\n\\<close>\nfun rec_all :: \"recf \\<Rightarrow> recf \\<Rightarrow> recf\"\n  where\n    \"rec_all rt rf = \n    (let vl = arity rf in\n       Cn (vl - 1) rec_sg [Cn (vl - 1) (rec_accum rf) \n                 (get_fstn_args (vl - 1) (vl - 1) @ [rt])])\"\n\nlemma rec_accum_ex:\n  assumes \"primerec rf (Suc (length xs))\"\n  shows \"(rec_exec (rec_accum rf) (xs @ [x]) = 0) = \n         (\\<exists> t \\<le> x. rec_exec rf (xs @ [t]) = 0)\"\nproof(induct x)\n  case (Suc x)\n  with assms show ?case \n    apply(auto simp add: rec_exec.simps rec_accum.simps get_fstn_args_take)\n     apply(rename_tac t ta)\n     apply(rule_tac x = ta in exI, simp)\n    apply(case_tac \"t = Suc x\", simp_all)\n    apply(rule_tac x = t in exI, simp) done\nqed (insert assms,auto simp add: rec_exec.simps rec_accum.simps get_fstn_args_take)\n\n\ntext \\<open>\n  The correctness of \\<open>rec_all\\<close>.\n\\<close>\nlemma all_lemma: \n  \"\\<lbrakk>primerec rf (Suc (length xs));\n    primerec rt (length xs)\\<rbrakk>\n  \\<Longrightarrow> rec_exec (rec_all rt rf) xs = (if (\\<forall> x \\<le> (rec_exec rt xs). 0 < rec_exec rf (xs @ [x])) then 1\n                                                                                              else 0)\"\n  apply(auto simp: rec_all.simps)\n   apply(simp add: rec_exec.simps map_append get_fstn_args_take split: if_splits)\n   apply(drule_tac x = \"rec_exec rt xs\" in rec_accum_ex)\n   apply(cases \"rec_exec (rec_accum rf) (xs @ [rec_exec rt xs]) = 0\", simp_all)\n   apply force\n  apply(simp add: rec_exec.simps map_append get_fstn_args_take)\n  apply(drule_tac x = \"rec_exec rt xs\" in rec_accum_ex)\n  apply(cases \"rec_exec (rec_accum rf) (xs @ [rec_exec rt xs]) = 0\")\n   apply force+\n  done\n\ntext \\<open>\n  \\<open>rec_ex t f (x1, x2, \\<dots>, xn)\\<close> \n  computes the charactrization function of the following FOL formula:\n  \\<open>(\\<exists> x \\<le> t(x1, x2, \\<dots>, xn). (f(x1, x2, \\<dots>, xn, x) > 0))\\<close>\n\\<close>\nfun rec_ex :: \"recf \\<Rightarrow> recf \\<Rightarrow> recf\"\n  where\n    \"rec_ex rt rf = \n       (let vl = arity rf in \n         Cn (vl - 1) rec_sg [Cn (vl - 1) (rec_sigma rf) \n                  (get_fstn_args (vl - 1) (vl - 1) @ [rt])])\"\n\nlemma rec_sigma_ex: \n  assumes \"primerec rf (Suc (length xs))\"\n  shows \"(rec_exec (rec_sigma rf) (xs @ [x]) = 0) = \n                          (\\<forall> t \\<le> x. rec_exec rf (xs @ [t]) = 0)\"\nproof(induct x)\n  case (Suc x)\n  from Suc assms show ?case\n    by(auto simp add: rec_exec.simps rec_sigma.simps \n        get_fstn_args_take elim:le_SucE)\nqed (insert assms,auto simp: get_fstn_args_take rec_exec.simps rec_sigma.simps)\n\ntext \\<open>\n  The correctness of \\<open>ex_lemma\\<close>.\n\\<close>\nlemma ex_lemma:\"\n  \\<lbrakk>primerec rf (Suc (length xs));\n   primerec rt (length xs)\\<rbrakk>\n\\<Longrightarrow> (rec_exec (rec_ex rt rf) xs =\n    (if (\\<exists> x \\<le> (rec_exec rt xs). 0 <rec_exec rf (xs @ [x])) then 1\n     else 0))\"\n  apply(auto simp: rec_exec.simps get_fstn_args_take split: if_splits)\n   apply(drule_tac x = \"rec_exec rt xs\" in rec_sigma_ex, simp)\n  apply(drule_tac x = \"rec_exec rt xs\" in rec_sigma_ex, simp)\n  done\n\ntext \\<open>\n  Definition of \\<open>Min[R]\\<close> on page 77 of Boolos's book.\n\\<close>\n\nfun Minr :: \"(nat list \\<Rightarrow> bool) \\<Rightarrow> nat list \\<Rightarrow> nat \\<Rightarrow> nat\"\n  where \"Minr Rr xs w = (let setx = {y | y. (y \\<le> w) \\<and> Rr (xs @ [y])} in \n                        if (setx = {}) then (Suc w)\n                                       else (Min setx))\"\n\ndeclare Minr.simps[simp del] rec_all.simps[simp del]\n\ntext \\<open>\n  The following is a set of auxilliary lemmas about \\<open>Minr\\<close>.\n\\<close>\nlemma Minr_range: \"Minr Rr xs w \\<le> w \\<or> Minr Rr xs w = Suc w\"\n  apply(auto simp: Minr.simps)\n  apply(subgoal_tac \"Min {x. x \\<le> w \\<and> Rr (xs @ [x])} \\<le> x\")\n   apply(erule_tac order_trans, simp)\n  apply(rule_tac Min_le, auto)\n  done\n\nlemma expand_conj_in_set: \"{x. x \\<le> Suc w \\<and> Rr (xs @ [x])}\n    = (if Rr (xs @ [Suc w]) then insert (Suc w) \n                              {x. x \\<le> w \\<and> Rr (xs @ [x])}\n      else {x. x \\<le> w \\<and> Rr (xs @ [x])})\"\n  by (auto elim:le_SucE)\n\nlemma Minr_strip_Suc[simp]: \"Minr Rr xs w \\<le> w \\<Longrightarrow> Minr Rr xs (Suc w) = Minr Rr xs w\"\n  by(cases \"\\<forall>x\\<le>w. \\<not> Rr (xs @ [x])\",auto simp add: Minr.simps expand_conj_in_set)\n\nlemma x_empty_set[simp]: \"\\<forall>x\\<le>w. \\<not> Rr (xs @ [x]) \\<Longrightarrow>  \n                           {x. x \\<le> w \\<and> Rr (xs @ [x])} = {} \"\n  by auto\n\nlemma Minr_is_Suc[simp]: \"\\<lbrakk>Minr Rr xs w = Suc w; Rr (xs @ [Suc w])\\<rbrakk> \\<Longrightarrow> \n                                       Minr Rr xs (Suc w) = Suc w\"\n  apply(simp add: Minr.simps expand_conj_in_set)\n  apply(cases \"\\<forall>x\\<le>w. \\<not> Rr (xs @ [x])\", auto)\n  done\n\nlemma Minr_is_Suc_Suc[simp]: \"\\<lbrakk>Minr Rr xs w = Suc w; \\<not> Rr (xs @ [Suc w])\\<rbrakk> \\<Longrightarrow> \n                                   Minr Rr xs (Suc w) = Suc (Suc w)\"\n  apply(simp add: Minr.simps expand_conj_in_set)\n  apply(cases \"\\<forall>x\\<le>w. \\<not> Rr (xs @ [x])\", auto)\n  apply(subgoal_tac \"Min {x. x \\<le> w \\<and> Rr (xs @ [x])} \\<in> \n                                {x. x \\<le> w \\<and> Rr (xs @ [x])}\", simp)\n  apply(rule_tac Min_in, auto)\n  done\n\nlemma Minr_Suc_simp: \n  \"Minr Rr xs (Suc w) = \n      (if Minr Rr xs w \\<le> w then Minr Rr xs w\n       else if (Rr (xs @ [Suc w])) then (Suc w)\n       else Suc (Suc w))\"\n  by(insert Minr_range[of Rr xs w], auto)\n\ntext \\<open>\n  \\<open>rec_Minr\\<close> is the recursive function \n  used to implement \\<open>Minr\\<close>:\n  if \\<open>Rr\\<close> is implemented by a recursive function \\<open>recf\\<close>,\n  then \\<open>rec_Minr recf\\<close> is the recursive function used to \n  implement \\<open>Minr Rr\\<close>\n\\<close>\nfun rec_Minr :: \"recf \\<Rightarrow> recf\"\n  where\n    \"rec_Minr rf = \n     (let vl = arity rf\n      in let rq = rec_all (id vl (vl - 1)) (Cn (Suc vl) \n              rec_not [Cn (Suc vl) rf \n                    (get_fstn_args (Suc vl) (vl - 1) @\n                                        [id (Suc vl) (vl)])]) \n      in  rec_sigma rq)\"\n\nlemma length_getpren_params[simp]: \"length (get_fstn_args m n) = n\"\n  by(induct n, auto simp: get_fstn_args.simps)\n\nlemma length_app:\n  \"(length (get_fstn_args (arity rf - Suc 0)\n                           (arity rf - Suc 0)\n   @ [Cn (arity rf - Suc 0) (constn 0)\n           [recf.id (arity rf - Suc 0) 0]]))\n    = (Suc (arity rf - Suc 0))\"\n  apply(simp)\n  done\n\nlemma primerec_accum: \"primerec (rec_accum rf) n \\<Longrightarrow> primerec rf n\"\n  apply(auto simp: rec_accum.simps Let_def)\n  apply(erule_tac prime_pr_reverse, simp)\n  apply(erule_tac prime_cn_reverse, simp only: length_app)\n  done\n\nlemma primerec_all: \"primerec (rec_all rt rf) n \\<Longrightarrow>\n                       primerec rt n \\<and> primerec rf (Suc n)\"\n  apply(simp add: rec_all.simps Let_def)\n  apply(erule_tac prime_cn_reverse, simp)\n  apply(erule_tac prime_cn_reverse, simp)\n  apply(erule_tac x = n in allE, simp add: nth_append primerec_accum)\n  done\n\ndeclare numeral_3_eq_3[simp]\n\nlemma primerec_rec_pred_1[intro]: \"primerec rec_pred (Suc 0)\"\n  apply(simp add: rec_pred_def)\n  apply(rule_tac prime_cn, auto dest:less_2_cases[unfolded numeral One_nat_def])\n  done\n\nlemma primerec_rec_minus_2[intro]: \"primerec rec_minus (Suc (Suc 0))\"\n  apply(auto simp: rec_minus_def)\n  done\n\nlemma primerec_constn_1[intro]: \"primerec (constn n) (Suc 0)\"\n  apply(induct n)\n   apply(auto simp: constn.simps)\n  done\n\nlemma primerec_rec_sg_1[intro]: \"primerec rec_sg (Suc 0)\" \n  apply(simp add: rec_sg_def)\n  apply(rule_tac k = \"Suc (Suc 0)\" in prime_cn)\n     apply(auto)\n  apply(auto dest!:less_2_cases[unfolded numeral One_nat_def])\n    apply( auto)\n  done\n\nlemma primerec_getpren[elim]: \"\\<lbrakk>i < n; n \\<le> m\\<rbrakk> \\<Longrightarrow> primerec (get_fstn_args m n ! i) m\"\n  apply(induct n, auto simp: get_fstn_args.simps)\n  apply(cases \"i = n\", auto simp: nth_append intro: prime_id)\n  done\n\nlemma primerec_rec_add_2[intro]: \"primerec rec_add (Suc (Suc 0))\"\n  apply(simp add: rec_add_def)\n  apply(rule_tac prime_pr, auto)\n  done\n\nlemma primerec_rec_mult_2[intro]:\"primerec rec_mult (Suc (Suc 0))\"\n  apply(simp add: rec_mult_def )\n  apply(rule_tac prime_pr, auto)\n  using less_2_cases numeral_2_eq_2 by fastforce\n\nlemma primerec_ge_2_elim[elim]: \"\\<lbrakk>primerec rf n; n \\<ge> Suc (Suc 0)\\<rbrakk>   \\<Longrightarrow> \n                        primerec (rec_accum rf) n\"\n  apply(auto simp: rec_accum.simps)\n   apply(simp add: nth_append, auto dest!:less_2_cases[unfolded numeral One_nat_def])\n    apply force\n   apply force\n  apply(auto simp: nth_append)\n  done\n\nlemma primerec_all_iff: \n  \"\\<lbrakk>primerec rt n; primerec rf (Suc n); n > 0\\<rbrakk> \\<Longrightarrow> \n                                 primerec (rec_all rt rf) n\"\n  apply(simp add: rec_all.simps, auto)\n    apply(auto, simp add: nth_append, auto)\n  done\n\nlemma primerec_rec_not_1[intro]: \"primerec rec_not (Suc 0)\"\n  apply(simp add: rec_not_def)\n  apply(rule prime_cn, auto dest!:less_2_cases[unfolded numeral One_nat_def])\n  done\n\nlemma Min_false1[simp]: \"\\<lbrakk>\\<not> Min {uu. uu \\<le> w \\<and> 0 < rec_exec rf (xs @ [uu])} \\<le> w;\n       x \\<le> w; 0 < rec_exec rf (xs @ [x])\\<rbrakk>\n      \\<Longrightarrow>  False\"\n  apply(subgoal_tac \"finite {uu. uu \\<le> w \\<and> 0 < rec_exec rf (xs @ [uu])}\")\n   apply(subgoal_tac \"{uu. uu \\<le> w \\<and> 0 < rec_exec rf (xs @ [uu])} \\<noteq> {}\")\n    apply(simp add: Min_le_iff, simp)\n   apply(rule_tac x = x in exI, simp)\n  apply(simp)\n  done\n\nlemma sigma_minr_lemma: \n  assumes prrf:  \"primerec rf (Suc (length xs))\"\n  shows \"UF.Sigma (rec_exec (rec_all (recf.id (Suc (length xs)) (length xs))\n     (Cn (Suc (Suc (length xs))) rec_not\n      [Cn (Suc (Suc (length xs))) rf (get_fstn_args (Suc (Suc (length xs))) \n       (length xs) @ [recf.id (Suc (Suc (length xs))) (Suc (length xs))])])))\n      (xs @ [w]) =\n       Minr (\\<lambda>args. 0 < rec_exec rf args) xs w\"\nproof(induct w)\n  let ?rt = \"(recf.id (Suc (length xs)) ((length xs)))\"\n  let ?rf = \"(Cn (Suc (Suc (length xs))) \n    rec_not [Cn (Suc (Suc (length xs))) rf \n    (get_fstn_args (Suc (Suc (length xs))) (length xs) @ \n                [recf.id (Suc (Suc (length xs))) \n    (Suc ((length xs)))])])\"\n  let ?rq = \"(rec_all ?rt ?rf)\"\n  have prrf: \"primerec ?rf (Suc (length (xs @ [0]))) \\<and>\n        primerec ?rt (length (xs @ [0]))\"\n    apply(auto simp: prrf nth_append)+\n    done\n  show \"Sigma (rec_exec (rec_all ?rt ?rf)) (xs @ [0])\n       = Minr (\\<lambda>args. 0 < rec_exec rf args) xs 0\"\n    apply(simp add: Sigma.simps)\n    apply(simp only: prrf all_lemma,  \n        auto simp: rec_exec.simps get_fstn_args_take Minr.simps)\n    apply(rule_tac Min_eqI, auto)\n    done\nnext\n  fix w\n  let ?rt = \"(recf.id (Suc (length xs)) ((length xs)))\"\n  let ?rf = \"(Cn (Suc (Suc (length xs))) \n    rec_not [Cn (Suc (Suc (length xs))) rf \n    (get_fstn_args (Suc (Suc (length xs))) (length xs) @ \n                [recf.id (Suc (Suc (length xs))) \n    (Suc ((length xs)))])])\"\n  let ?rq = \"(rec_all ?rt ?rf)\"\n  assume ind:\n    \"Sigma (rec_exec (rec_all ?rt ?rf)) (xs @ [w]) = Minr (\\<lambda>args. 0 < rec_exec rf args) xs w\"\n  have prrf: \"primerec ?rf (Suc (length (xs @ [Suc w]))) \\<and>\n        primerec ?rt (length (xs @ [Suc w]))\"\n    apply(auto simp: prrf nth_append)+\n    done\n  show \"UF.Sigma (rec_exec (rec_all ?rt ?rf))\n         (xs @ [Suc w]) =\n        Minr (\\<lambda>args. 0 < rec_exec rf args) xs (Suc w)\"\n    apply(auto simp: Sigma_Suc_simp_rewrite ind Minr_Suc_simp)\n       apply(simp_all only: prrf all_lemma)\n       apply(auto simp: rec_exec.simps get_fstn_args_take Let_def Minr.simps split: if_splits)\n       apply(drule_tac Min_false1, simp, simp, simp)\n      apply (metis le_SucE neq0_conv)\n     apply(drule_tac Min_false1, simp, simp, simp)\n    apply(drule_tac Min_false1, simp, simp, simp)\n    done\nqed\n\ntext \\<open>\n  The correctness of \\<open>rec_Minr\\<close>.\n\\<close>\nlemma Minr_lemma: \"\n  \\<lbrakk>primerec rf (Suc (length xs))\\<rbrakk> \n     \\<Longrightarrow> rec_exec (rec_Minr rf) (xs @ [w]) = \n            Minr (\\<lambda> args. (0 < rec_exec rf args)) xs w\"\nproof -\n  let ?rt = \"(recf.id (Suc (length xs)) ((length xs)))\"\n  let ?rf = \"(Cn (Suc (Suc (length xs))) \n    rec_not [Cn (Suc (Suc (length xs))) rf \n    (get_fstn_args (Suc (Suc (length xs))) (length xs) @ \n                [recf.id (Suc (Suc (length xs))) \n    (Suc ((length xs)))])])\"\n  let ?rq = \"(rec_all ?rt ?rf)\"\n  assume h: \"primerec rf (Suc (length xs))\"\n  have h1: \"primerec ?rq (Suc (length xs))\"\n    apply(rule_tac primerec_all_iff)\n      apply(auto simp: h nth_append)+\n    done\n  moreover have \"arity rf = Suc (length xs)\"\n    using h by auto\n  ultimately show \"rec_exec (rec_Minr rf) (xs @ [w]) = \n    Minr (\\<lambda> args. (0 < rec_exec rf args)) xs w\"\n    apply(simp add: arity.simps Let_def sigma_lemma all_lemma)\n    apply(rule_tac  sigma_minr_lemma)\n    apply(simp add: h)\n    done\nqed\n\ntext \\<open>\n  \\<open>rec_le\\<close> is the comparasion function \n  which compares its two arguments, testing whether the \n  first is less or equal to the second.\n\\<close>\ndefinition rec_le :: \"recf\"\n  where\n    \"rec_le = Cn (Suc (Suc 0)) rec_disj [rec_less, rec_eq]\"\n\ntext \\<open>\n  The correctness of \\<open>rec_le\\<close>.\n\\<close>\nlemma le_lemma: \n  \"\\<And>x y. rec_exec rec_le [x, y] = (if (x \\<le> y) then 1 else 0)\"\n  by(auto simp: rec_le_def rec_exec.simps)\n\ntext \\<open>\n  Definition of \\<open>Max[Rr]\\<close> on page 77 of Boolos's book.\n\\<close>\n\nfun Maxr :: \"(nat list \\<Rightarrow> bool) \\<Rightarrow> nat list \\<Rightarrow> nat \\<Rightarrow> nat\"\n  where\n    \"Maxr Rr xs w = (let setx = {y. y \\<le> w \\<and> Rr (xs @[y])} in \n                  if setx = {} then 0\n                  else Max setx)\"\n\ntext \\<open>\n  \\<open>rec_maxr\\<close> is the recursive function \n  used to implementation \\<open>Maxr\\<close>.\n\\<close>\nfun rec_maxr :: \"recf \\<Rightarrow> recf\"\n  where\n    \"rec_maxr rr = (let vl = arity rr in \n                  let rt = id (Suc vl) (vl - 1) in\n                  let rf1 = Cn (Suc (Suc vl)) rec_le \n                    [id (Suc (Suc vl)) \n                     ((Suc vl)), id (Suc (Suc vl)) (vl)] in\n                  let rf2 = Cn (Suc (Suc vl)) rec_not \n                      [Cn (Suc (Suc vl)) \n                           rr (get_fstn_args (Suc (Suc vl)) \n                            (vl - 1) @ \n                             [id (Suc (Suc vl)) ((Suc vl))])] in\n                  let rf = Cn (Suc (Suc vl)) rec_disj [rf1, rf2] in\n                  let Qf = Cn (Suc vl) rec_not [rec_all rt rf]\n                  in Cn vl (rec_sigma Qf) (get_fstn_args vl vl @\n                                                         [id vl (vl - 1)]))\"\n\ndeclare rec_maxr.simps[simp del] Maxr.simps[simp del] \ndeclare le_lemma[simp]\n\ndeclare numeral_2_eq_2[simp]\n\nlemma primerec_rec_disj_2[intro]: \"primerec rec_disj (Suc (Suc 0))\"\n  apply(simp add: rec_disj_def, auto)\n    apply(auto dest!:less_2_cases[unfolded numeral One_nat_def])\n  done\n\nlemma primerec_rec_less_2[intro]: \"primerec rec_less (Suc (Suc 0))\"\n  apply(simp add: rec_less_def, auto)\n    apply(auto dest!:less_2_cases[unfolded numeral One_nat_def])\n  done\n\nlemma primerec_rec_eq_2[intro]: \"primerec rec_eq (Suc (Suc 0))\"\n  apply(simp add: rec_eq_def)\n  apply(rule_tac prime_cn, auto dest!:less_2_cases[unfolded numeral One_nat_def])\n       apply force+\n  done\n\nlemma primerec_rec_le_2[intro]: \"primerec rec_le (Suc (Suc 0))\"\n  apply(simp add: rec_le_def)\n  apply(rule_tac prime_cn, auto dest!:less_2_cases[unfolded numeral One_nat_def])\n  done\n\nlemma Sigma_0: \"\\<forall> i \\<le> n. (f (xs @ [i]) = 0) \\<Longrightarrow> \n                              Sigma f (xs @ [n]) = 0\"\n  apply(induct n, simp add: Sigma.simps)\n  apply(simp add: Sigma_Suc_simp_rewrite)\n  done\n\nlemma Sigma_Suc[elim]: \"\\<forall>k<Suc w. f (xs @ [k]) = Suc 0\n        \\<Longrightarrow> Sigma f (xs @ [w]) = Suc w\"\n  apply(induct w)\n   apply(simp add: Sigma.simps, simp)\n  apply(simp add: Sigma.simps)\n  done\n\nlemma Sigma_max_point: \"\\<lbrakk>\\<forall> k < ma. f (xs @ [k]) = 1;\n        \\<forall> k \\<ge> ma. f (xs @ [k]) = 0; ma \\<le> w\\<rbrakk>\n    \\<Longrightarrow> Sigma f (xs @ [w]) = ma\"\n  apply(induct w, auto)\n   apply(rule_tac Sigma_0, simp)\n  apply(simp add: Sigma_Suc_simp_rewrite)\n  using Sigma_Suc by fastforce\n\nlemma Sigma_Max_lemma: \n  assumes prrf: \"primerec rf (Suc (length xs))\"\n  shows \"UF.Sigma (rec_exec (Cn (Suc (Suc (length xs))) rec_not\n  [rec_all (recf.id (Suc (Suc (length xs))) (length xs))\n  (Cn (Suc (Suc (Suc (length xs)))) rec_disj\n  [Cn (Suc (Suc (Suc (length xs)))) rec_le\n  [recf.id (Suc (Suc (Suc (length xs)))) (Suc (Suc (length xs))), \n  recf.id (Suc (Suc (Suc (length xs)))) (Suc (length xs))],\n  Cn (Suc (Suc (Suc (length xs)))) rec_not\n  [Cn (Suc (Suc (Suc (length xs)))) rf\n  (get_fstn_args (Suc (Suc (Suc (length xs)))) (length xs) @ \n  [recf.id (Suc (Suc (Suc (length xs)))) (Suc (Suc (length xs)))])]])]))\n  ((xs @ [w]) @ [w]) =\n       Maxr (\\<lambda>args. 0 < rec_exec rf args) xs w\"\nproof -\n  let ?rt = \"(recf.id (Suc (Suc (length xs))) ((length xs)))\"\n  let ?rf1 = \"Cn (Suc (Suc (Suc (length xs))))\n    rec_le [recf.id (Suc (Suc (Suc (length xs)))) \n    ((Suc (Suc (length xs)))), recf.id \n    (Suc (Suc (Suc (length xs)))) ((Suc (length xs)))]\"\n  let ?rf2 = \"Cn (Suc (Suc (Suc (length xs)))) rf \n               (get_fstn_args (Suc (Suc (Suc (length xs))))\n    (length xs) @ \n    [recf.id (Suc (Suc (Suc (length xs))))    \n    ((Suc (Suc (length xs))))])\"\n  let ?rf3 = \"Cn (Suc (Suc (Suc (length xs)))) rec_not [?rf2]\"\n  let ?rf = \"Cn (Suc (Suc (Suc (length xs)))) rec_disj [?rf1, ?rf3]\"\n  let ?rq = \"rec_all ?rt ?rf\"\n  let ?notrq = \"Cn (Suc (Suc (length xs))) rec_not [?rq]\"\n  show \"?thesis\"\n  proof(auto simp: Maxr.simps)\n    assume h: \"\\<forall>x\\<le>w. rec_exec rf (xs @ [x]) = 0\"\n    have \"primerec ?rf (Suc (length (xs @ [w, i]))) \\<and> \n          primerec ?rt (length (xs @ [w, i]))\"\n      using prrf\n      apply(auto dest!:less_2_cases[unfolded numeral One_nat_def])\n            apply force+\n      apply(case_tac ia, auto simp: h nth_append primerec_getpren)\n      done\n    hence \"Sigma (rec_exec ?notrq) ((xs@[w])@[w]) = 0\"\n      apply(rule_tac Sigma_0)\n      apply(auto simp: rec_exec.simps all_lemma\n          get_fstn_args_take nth_append h)\n      done\n    thus \"UF.Sigma (rec_exec ?notrq)\n      (xs @ [w, w]) = 0\"\n      by simp\n  next\n    fix x\n    assume h: \"x \\<le> w\" \"0 < rec_exec rf (xs @ [x])\"\n    hence \"\\<exists> ma. Max {y. y \\<le> w \\<and> 0 < rec_exec rf (xs @ [y])} = ma\"\n      by auto\n    from this obtain ma where k1: \n      \"Max {y. y \\<le> w \\<and> 0 < rec_exec rf (xs @ [y])} = ma\" ..\n    hence k2: \"ma \\<le> w \\<and> 0 < rec_exec rf (xs @ [ma])\"\n      using h\n      apply(subgoal_tac\n          \"Max {y. y \\<le> w \\<and> 0 < rec_exec rf (xs @ [y])} \\<in>  {y. y \\<le> w \\<and> 0 < rec_exec rf (xs @ [y])}\")\n       apply(erule_tac CollectE, simp)\n      apply(rule_tac Max_in, auto)\n      done\n    hence k3: \"\\<forall> k < ma. (rec_exec ?notrq (xs @ [w, k]) = 1)\"\n      apply(auto simp: nth_append)\n      apply(subgoal_tac \"primerec ?rf (Suc (length (xs @ [w, k]))) \\<and> \n        primerec ?rt (length (xs @ [w, k]))\")\n       apply(auto simp: rec_exec.simps all_lemma get_fstn_args_take nth_append\n          dest!:less_2_cases[unfolded numeral One_nat_def])\n      using prrf\n            apply force+\n      done    \n    have k4: \"\\<forall> k \\<ge> ma. (rec_exec ?notrq (xs @ [w, k]) = 0)\"\n      apply(auto)\n      apply(subgoal_tac \"primerec ?rf (Suc (length (xs @ [w, k]))) \\<and> \n        primerec ?rt (length (xs @ [w, k]))\")\n       apply(auto simp: rec_exec.simps all_lemma get_fstn_args_take nth_append)\n       apply(subgoal_tac \"x \\<le> Max {y. y \\<le> w \\<and> 0 < rec_exec rf (xs @ [y])}\",\n          simp add: k1)\n       apply(rule_tac Max_ge, auto dest!:less_2_cases[unfolded numeral One_nat_def])\n      using prrf apply force+\n      apply(auto simp: h nth_append)\n      done \n    from k3 k4 k1 have \"Sigma (rec_exec ?notrq) ((xs @ [w]) @ [w]) = ma\"\n      apply(rule_tac Sigma_max_point, simp, simp, simp add: k2)\n      done\n    from k1 and this show \"Sigma (rec_exec ?notrq) (xs @ [w, w]) =\n      Max {y. y \\<le> w \\<and> 0 < rec_exec rf (xs @ [y])}\"\n      by simp\n  qed  \nqed\n\ntext \\<open>\n  The correctness of \\<open>rec_maxr\\<close>.\n\\<close>\nlemma Maxr_lemma:\n  assumes h: \"primerec rf (Suc (length xs))\"\n  shows   \"rec_exec (rec_maxr rf) (xs @ [w]) = \n            Maxr (\\<lambda> args. 0 < rec_exec rf args) xs w\"\nproof -\n  from h have \"arity rf = Suc (length xs)\"\n    by auto\n  thus \"?thesis\"\n  proof(simp add: rec_exec.simps rec_maxr.simps nth_append get_fstn_args_take)\n    let ?rt = \"(recf.id (Suc (Suc (length xs))) ((length xs)))\"\n    let ?rf1 = \"Cn (Suc (Suc (Suc (length xs))))\n                     rec_le [recf.id (Suc (Suc (Suc (length xs)))) \n              ((Suc (Suc (length xs)))), recf.id \n             (Suc (Suc (Suc (length xs)))) ((Suc (length xs)))]\"\n    let ?rf2 = \"Cn (Suc (Suc (Suc (length xs)))) rf \n               (get_fstn_args (Suc (Suc (Suc (length xs))))\n                (length xs) @ \n                  [recf.id (Suc (Suc (Suc (length xs))))    \n                           ((Suc (Suc (length xs))))])\"\n    let ?rf3 = \"Cn (Suc (Suc (Suc (length xs)))) rec_not [?rf2]\"\n    let ?rf = \"Cn (Suc (Suc (Suc (length xs)))) rec_disj [?rf1, ?rf3]\"\n    let ?rq = \"rec_all ?rt ?rf\"\n    let ?notrq = \"Cn (Suc (Suc (length xs))) rec_not [?rq]\"\n    have prt: \"primerec ?rt (Suc (Suc (length xs)))\"\n      by(auto intro: prime_id)\n    have prrf: \"primerec ?rf (Suc (Suc (Suc (length xs))))\"\n      apply(auto dest!:less_2_cases[unfolded numeral One_nat_def])\n            apply force+\n        apply(auto intro: prime_id)\n       apply(simp add: h)\n      apply(auto simp add: nth_append)\n      done\n    from prt and prrf have prrq: \"primerec ?rq \n                                       (Suc (Suc (length xs)))\"\n      by(erule_tac primerec_all_iff, auto)\n    hence prnotrp: \"primerec ?notrq (Suc (length ((xs @ [w]))))\"\n      by(rule_tac prime_cn, auto)\n    have g1: \"rec_exec (rec_sigma ?notrq) ((xs @ [w]) @ [w]) \n      = Maxr (\\<lambda>args. 0 < rec_exec rf args) xs w\"\n      using prnotrp\n      using sigma_lemma\n      apply(simp only: sigma_lemma)\n      apply(rule_tac Sigma_Max_lemma)\n      apply(simp add: h)\n      done\n    thus \"rec_exec (rec_sigma ?notrq)\n     (xs @ [w, w]) =\n    Maxr (\\<lambda>args. 0 < rec_exec rf args) xs w\"\n      apply(simp)\n      done\n  qed\nqed\n\ntext \\<open>\n  \\<open>quo\\<close> is the formal specification of division.\n\\<close>\nfun quo :: \"nat list \\<Rightarrow> nat\"\n  where\n    \"quo [x, y] = (let Rr = \n                         (\\<lambda> zs. ((zs ! (Suc 0) * zs ! (Suc (Suc 0))\n                                 \\<le> zs ! 0) \\<and> zs ! Suc 0 \\<noteq> (0::nat)))\n                 in Maxr Rr [x, y] x)\"\n\ndeclare quo.simps[simp del]\n\ntext \\<open>\n  The following lemmas shows more directly the menaing of \\<open>quo\\<close>:\n\\<close>\nlemma quo_is_div: \"y > 0 \\<Longrightarrow> quo [x, y] = x div y\"\nproof -\n  {\n    fix xa ya\n    assume h: \"y * ya \\<le> x\"  \"y > 0\"\n    hence \"(y * ya) div y \\<le> x div y\"\n      by(insert div_le_mono[of \"y * ya\" x y], simp)\n    from this and h have \"ya \\<le> x div y\" by simp}\n  thus ?thesis by(simp add: quo.simps Maxr.simps, auto,\n        rule_tac Max_eqI, simp, auto)\nqed\n\nlemma quo_zero[intro]: \"quo [x, 0] = 0\"\n  by(simp add: quo.simps Maxr.simps)\n\nlemma quo_div: \"quo [x, y] = x div y\"  \n  by(cases \"y=0\", auto elim!:quo_is_div)\n\ntext \\<open>\n  \\<open>rec_noteq\\<close> is the recursive function testing whether its\n  two arguments are not equal.\n\\<close>\ndefinition rec_noteq:: \"recf\"\n  where\n    \"rec_noteq = Cn (Suc (Suc 0)) rec_not [Cn (Suc (Suc 0)) \n              rec_eq [id (Suc (Suc 0)) (0), id (Suc (Suc 0)) \n                                        ((Suc 0))]]\"\n\ntext \\<open>\n  The correctness of \\<open>rec_noteq\\<close>.\n\\<close>\nlemma noteq_lemma: \n  \"\\<And> x y. rec_exec rec_noteq [x, y] = \n               (if x \\<noteq> y then 1 else 0)\"\n  by(simp add: rec_exec.simps rec_noteq_def)\n\ndeclare noteq_lemma[simp]\n\ntext \\<open>\n  \\<open>rec_quo\\<close> is the recursive function used to implement \\<open>quo\\<close>\n\\<close>\ndefinition rec_quo :: \"recf\"\n  where\n    \"rec_quo = (let rR = Cn (Suc (Suc (Suc 0))) rec_conj\n              [Cn (Suc (Suc (Suc 0))) rec_le \n               [Cn (Suc (Suc (Suc 0))) rec_mult \n                  [id (Suc (Suc (Suc 0))) (Suc 0), \n                     id (Suc (Suc (Suc 0))) ((Suc (Suc 0)))],\n                id (Suc (Suc (Suc 0))) (0)], \n                Cn (Suc (Suc (Suc 0))) rec_noteq \n                         [id (Suc (Suc (Suc 0))) (Suc (0)),\n                Cn (Suc (Suc (Suc 0))) (constn 0) \n                              [id (Suc (Suc (Suc 0))) (0)]]] \n              in Cn (Suc (Suc 0)) (rec_maxr rR)) [id (Suc (Suc 0)) \n                           (0),id (Suc (Suc 0)) (Suc (0)), \n                                   id (Suc (Suc 0)) (0)]\"\n\nlemma primerec_rec_conj_2[intro]: \"primerec rec_conj (Suc (Suc 0))\"\n  apply(simp add: rec_conj_def)\n  apply(rule_tac prime_cn, auto dest!:less_2_cases[unfolded numeral One_nat_def])\n  done\n\nlemma primerec_rec_noteq_2[intro]: \"primerec rec_noteq (Suc (Suc 0))\"\n  apply(simp add: rec_noteq_def)\n  apply(rule_tac prime_cn, auto dest!:less_2_cases[unfolded numeral One_nat_def])\n  done\n\n\nlemma quo_lemma1: \"rec_exec rec_quo [x, y] = quo [x, y]\"\nproof(simp add: rec_exec.simps rec_quo_def)\n  let ?rR = \"(Cn (Suc (Suc (Suc 0))) rec_conj\n               [Cn (Suc (Suc (Suc 0))) rec_le\n                   [Cn (Suc (Suc (Suc 0))) rec_mult \n               [recf.id (Suc (Suc (Suc 0))) (Suc (0)), \n                recf.id (Suc (Suc (Suc 0))) (Suc (Suc (0)))],\n                 recf.id (Suc (Suc (Suc 0))) (0)],  \n          Cn (Suc (Suc (Suc 0))) rec_noteq \n                              [recf.id (Suc (Suc (Suc 0))) \n             (Suc (0)), Cn (Suc (Suc (Suc 0))) (constn 0) \n                      [recf.id (Suc (Suc (Suc 0))) (0)]]])\"\n  have \"rec_exec (rec_maxr ?rR) ([x, y]@ [ x]) = Maxr (\\<lambda> args. 0 < rec_exec ?rR args) [x, y] x\"\n  proof(rule_tac Maxr_lemma, simp)\n    show \"primerec ?rR (Suc (Suc (Suc 0)))\"\n      apply(auto dest!:less_2_cases[unfolded numeral One_nat_def]) \n             apply force+\n      done\n  qed\n  hence g1: \"rec_exec (rec_maxr ?rR) ([x, y,  x]) =\n             Maxr (\\<lambda> args. if rec_exec ?rR args = 0 then False\n                           else True) [x, y] x\" \n    by simp\n  have g2: \"Maxr (\\<lambda> args. if rec_exec ?rR args = 0 then False\n                           else True) [x, y] x = quo [x, y]\"\n    apply(simp add: rec_exec.simps)\n    apply(simp add: Maxr.simps quo.simps, auto)\n    done\n  from g1 and g2 show \n    \"rec_exec (rec_maxr ?rR) ([x, y,  x]) = quo [x, y]\"\n    by simp\nqed\n\ntext \\<open>\n  The correctness of \\<open>quo\\<close>.\n\\<close>\nlemma quo_lemma2: \"rec_exec rec_quo [x, y] = x div y\"\n  using quo_lemma1[of x y] quo_div[of x y]\n  by simp\n\ntext \\<open>\n  \\<open>rec_mod\\<close> is the recursive function used to implement \n  the reminder function.\n\\<close>\ndefinition rec_mod :: \"recf\"\n  where\n    \"rec_mod = Cn (Suc (Suc 0)) rec_minus [id (Suc (Suc 0)) (0), \n               Cn (Suc (Suc 0)) rec_mult [rec_quo, id (Suc (Suc 0))\n                                                     (Suc (0))]]\"\n\ntext \\<open>\n  The correctness of \\<open>rec_mod\\<close>:\n\\<close>\nlemma mod_lemma: \"\\<And> x y. rec_exec rec_mod [x, y] = (x mod y)\"\n  by(simp add: rec_exec.simps rec_mod_def quo_lemma2 minus_div_mult_eq_mod)\n\ntext\\<open>lemmas for embranch function\\<close>\ntype_synonym ftype = \"nat list \\<Rightarrow> nat\"\ntype_synonym rtype = \"nat list \\<Rightarrow> bool\"\n\ntext \\<open>\n  The specifation of the mutli-way branching statement on\n  page 79 of Boolos's book.\n\\<close>\nfun Embranch :: \"(ftype * rtype) list \\<Rightarrow> nat list \\<Rightarrow> nat\"\n  where\n    \"Embranch [] xs = 0\" |\n    \"Embranch (gc # gcs) xs = (\n                   let (g, c) = gc in \n                   if c xs then g xs else Embranch gcs xs)\"\n\nfun rec_embranch' :: \"(recf * recf) list \\<Rightarrow> nat \\<Rightarrow> recf\"\n  where\n    \"rec_embranch' [] vl = Cn vl z [id vl (vl - 1)]\" |\n    \"rec_embranch' ((rg, rc) # rgcs) vl = Cn vl rec_add\n                   [Cn vl rec_mult [rg, rc], rec_embranch' rgcs vl]\"\n\ntext \\<open>\n  \\<open>rec_embrach\\<close> is the recursive function used to implement\n  \\<open>Embranch\\<close>.\n\\<close>\nfun rec_embranch :: \"(recf * recf) list \\<Rightarrow> recf\"\n  where\n    \"rec_embranch ((rg, rc) # rgcs) = \n         (let vl = arity rg in \n          rec_embranch' ((rg, rc) # rgcs) vl)\"\n\ndeclare Embranch.simps[simp del] rec_embranch.simps[simp del]\n\nlemma embranch_all0: \n  \"\\<lbrakk>\\<forall> j < length rcs. rec_exec (rcs ! j) xs = 0;\n    length rgs = length rcs;  \n  rcs \\<noteq> []; \n  list_all (\\<lambda> rf. primerec rf (length xs)) (rgs @ rcs)\\<rbrakk>  \\<Longrightarrow> \n  rec_exec (rec_embranch (zip rgs rcs)) xs = 0\"\nproof(induct rcs arbitrary: rgs)\n  case (Cons a rcs)\n  then show ?case proof(cases rgs, simp)  fix a rcs rgs aa list\n    assume ind: \n      \"\\<And>rgs. \\<lbrakk>\\<forall>j<length rcs. rec_exec (rcs ! j) xs = 0; \n             length rgs = length rcs; rcs \\<noteq> []; \n            list_all (\\<lambda>rf. primerec rf (length xs)) (rgs @ rcs)\\<rbrakk> \\<Longrightarrow> \n                      rec_exec (rec_embranch (zip rgs rcs)) xs = 0\"\n      and h:  \"\\<forall>j<length (a # rcs). rec_exec ((a # rcs) ! j) xs = 0\"\n      \"length rgs = length (a # rcs)\" \n      \"a # rcs \\<noteq> []\" \n      \"list_all (\\<lambda>rf. primerec rf (length xs)) (rgs @ a # rcs)\"\n      \"rgs = aa # list\"\n    have g: \"rcs \\<noteq> [] \\<Longrightarrow> rec_exec (rec_embranch (zip list rcs)) xs = 0\"\n      using h by(rule_tac ind, auto)\n    show \"rec_exec (rec_embranch (zip rgs (a # rcs))) xs = 0\"\n    proof(cases \"rcs = []\", simp)\n      show \"rec_exec (rec_embranch (zip rgs [a])) xs = 0\"\n        using h by (auto simp add: rec_embranch.simps rec_exec.simps)\n    next\n      assume \"rcs \\<noteq> []\"\n      hence \"rec_exec (rec_embranch (zip list rcs)) xs = 0\"\n        using g by simp\n      thus \"rec_exec (rec_embranch (zip rgs (a # rcs))) xs = 0\"\n        using h\n        by(cases rcs;cases list, auto simp add: rec_embranch.simps rec_exec.simps)\n    qed\n  qed\nqed simp\n\n\nlemma embranch_exec_0: \"\\<lbrakk>rec_exec aa xs = 0; zip rgs list \\<noteq> []; \n       list_all (\\<lambda> rf. primerec rf (length xs)) ([a, aa] @ rgs @ list)\\<rbrakk>\n       \\<Longrightarrow> rec_exec (rec_embranch ((a, aa) # zip rgs list)) xs\n         = rec_exec (rec_embranch (zip rgs list)) xs\"\n  apply(auto simp add: rec_exec.simps rec_embranch.simps)\n  apply(cases \"zip rgs list\", force)\n  apply(cases \"hd (zip rgs list)\", simp add: rec_embranch.simps rec_exec.simps)\n  apply(subgoal_tac \"arity a = length xs\")\n   apply(cases rgs;cases list;force)\n  by force\n\nlemma zip_null_iff: \"\\<lbrakk>length xs = k; length ys = k; zip xs ys = []\\<rbrakk> \\<Longrightarrow> xs = [] \\<and> ys = []\"\n  apply(cases xs, simp, simp)\n  apply(cases ys, simp, simp)\n  done\n\nlemma zip_null_gr: \"\\<lbrakk>length xs = k; length ys = k; zip xs ys \\<noteq> []\\<rbrakk> \\<Longrightarrow> 0 < k\"\n  apply(cases xs, simp, simp)\n  done\n\nlemma Embranch_0:  \n  \"\\<lbrakk>length rgs = k; length rcs = k; k > 0; \n  \\<forall> j < k. rec_exec (rcs ! j) xs = 0\\<rbrakk> \\<Longrightarrow>\n  Embranch (zip (map rec_exec rgs) (map (\\<lambda>r args. 0 < rec_exec r args) rcs)) xs = 0\"\nproof(induct rgs arbitrary: rcs k)\n  case (Cons a rgs rcs k)\n  then show ?case\n    apply(cases rcs, simp, cases \"rgs = []\")\n     apply(simp add: Embranch.simps)\n     apply(erule_tac x = 0 in allE)\n     apply (auto simp add: Embranch.simps intro!: Cons(1)).\nqed simp\n\ntext \\<open>\n  The correctness of \\<open>rec_embranch\\<close>.\n\\<close>\nlemma embranch_lemma:\n  assumes branch_num:\n    \"length rgs = n\" \"length rcs = n\" \"n > 0\"\n    and partition: \n    \"(\\<exists> i < n. (rec_exec (rcs ! i) xs = 1 \\<and> (\\<forall> j < n. j \\<noteq> i \\<longrightarrow> \n                                      rec_exec (rcs ! j) xs = 0)))\"\n    and prime_all: \"list_all (\\<lambda> rf. primerec rf (length xs)) (rgs @ rcs)\"\n  shows \"rec_exec (rec_embranch (zip rgs rcs)) xs =\n                  Embranch (zip (map rec_exec rgs) \n                     (map (\\<lambda> r args. 0 < rec_exec r args) rcs)) xs\"\n  using branch_num partition prime_all\nproof(induct rgs arbitrary: rcs n, simp)\n  fix a rgs rcs n\n  assume ind: \n    \"\\<And>rcs n. \\<lbrakk>length rgs = n; length rcs = n; 0 < n;\n    \\<exists>i<n. rec_exec (rcs ! i) xs = 1 \\<and> (\\<forall>j<n. j \\<noteq> i \\<longrightarrow> rec_exec (rcs ! j) xs = 0);\n    list_all (\\<lambda>rf. primerec rf (length xs)) (rgs @ rcs)\\<rbrakk>\n    \\<Longrightarrow> rec_exec (rec_embranch (zip rgs rcs)) xs =\n    Embranch (zip (map rec_exec rgs) (map (\\<lambda>r args. 0 < rec_exec r args) rcs)) xs\"\n    and h: \"length (a # rgs) = n\" \"length (rcs::recf list) = n\" \"0 < n\"\n    \" \\<exists>i<n. rec_exec (rcs ! i) xs = 1 \\<and> \n         (\\<forall>j<n. j \\<noteq> i \\<longrightarrow> rec_exec (rcs ! j) xs = 0)\" \n    \"list_all (\\<lambda>rf. primerec rf (length xs)) ((a # rgs) @ rcs)\"\n  from h show \"rec_exec (rec_embranch (zip (a # rgs) rcs)) xs =\n    Embranch (zip (map rec_exec (a # rgs)) (map (\\<lambda>r args. \n                0 < rec_exec r args) rcs)) xs\"\n    apply(cases rcs, simp, simp)\n    apply(cases \"rec_exec (hd rcs) xs = 0\")\n     apply(case_tac [!] \"zip rgs (tl rcs) = []\", simp)\n       apply(subgoal_tac \"rgs = [] \\<and> (tl rcs) = []\", simp add: Embranch.simps rec_exec.simps rec_embranch.simps)\n       apply(rule_tac  zip_null_iff, simp, simp, simp)\n  proof -\n    fix aa list\n    assume \"rcs = aa # list\"\n    assume g:\n      \"Suc (length rgs) = n\" \"Suc (length list) = n\" \n      \"\\<exists>i<n. rec_exec ((aa # list) ! i) xs = Suc 0 \\<and> \n          (\\<forall>j<n. j \\<noteq> i \\<longrightarrow> rec_exec ((aa # list) ! j) xs = 0)\"\n      \"primerec a (length xs) \\<and> \n      list_all (\\<lambda>rf. primerec rf (length xs)) rgs \\<and>\n      primerec aa (length xs) \\<and> \n      list_all (\\<lambda>rf. primerec rf (length xs)) list\"\n      \"rec_exec (hd rcs) xs = 0\" \"rcs = aa # list\" \"zip rgs (tl rcs) \\<noteq> []\"\n    hence \"rec_exec aa xs = 0\" \"zip rgs list \\<noteq> []\" by auto\n    note g = g(1,2,3,4,6) this\n    have \"rec_exec (rec_embranch ((a, aa) # zip rgs list)) xs\n        = rec_exec (rec_embranch (zip rgs list)) xs\"\n      apply(rule embranch_exec_0, simp_all add: g)\n      done\n    from g and this show \"rec_exec (rec_embranch ((a, aa) # zip rgs list)) xs =\n         Embranch ((rec_exec a, \\<lambda>args. 0 < rec_exec aa args) # \n           zip (map rec_exec rgs) (map (\\<lambda>r args. 0 < rec_exec r args) list)) xs\"\n      apply(simp add: Embranch.simps)\n      apply(rule_tac n = \"n - Suc 0\" in ind)\n          apply(cases n;force)\n         apply(cases n;force)\n        apply(cases n;force simp add: zip_null_gr)\n       apply(auto)\n      apply(rename_tac i)\n      apply(case_tac i, force, simp)\n      apply(rule_tac x = \"i - 1\" in exI, simp)\n      by auto\n  next\n    fix aa list\n    assume g: \"Suc (length rgs) = n\" \"Suc (length list) = n\"\n      \"\\<exists>i<n. rec_exec ((aa # list) ! i) xs = Suc 0 \\<and> \n      (\\<forall>j<n. j \\<noteq> i \\<longrightarrow> rec_exec ((aa # list) ! j) xs = 0)\"\n      \"primerec a (length xs) \\<and> list_all (\\<lambda>rf. primerec rf (length xs)) rgs \\<and>\n      primerec aa (length xs) \\<and> list_all (\\<lambda>rf. primerec rf (length xs)) list\"\n      \"rcs = aa # list\" \"rec_exec (hd rcs) xs \\<noteq> 0\" \"zip rgs (tl rcs) = []\"\n    thus \"rec_exec (rec_embranch ((a, aa) # zip rgs list)) xs = \n        Embranch ((rec_exec a, \\<lambda>args. 0 < rec_exec aa args) # \n       zip (map rec_exec rgs) (map (\\<lambda>r args. 0 < rec_exec r args) list)) xs\"\n      apply(subgoal_tac \"rgs = [] \\<and> list = []\", simp)\n       prefer 2\n       apply(rule_tac zip_null_iff, simp, simp, simp)\n      apply(simp add: rec_exec.simps rec_embranch.simps Embranch.simps, auto)\n      done\n  next\n    fix aa list\n    assume g: \"Suc (length rgs) = n\" \"Suc (length list) = n\"\n      \"\\<exists>i<n. rec_exec ((aa # list) ! i) xs = Suc 0 \\<and>  \n           (\\<forall>j<n. j \\<noteq> i \\<longrightarrow> rec_exec ((aa # list) ! j) xs = 0)\"\n      \"primerec a (length xs) \\<and> list_all (\\<lambda>rf. primerec rf (length xs)) rgs\n      \\<and> primerec aa (length xs) \\<and> list_all (\\<lambda>rf. primerec rf (length xs)) list\"\n      \"rcs = aa # list\" \"rec_exec (hd rcs) xs \\<noteq> 0\" \"zip rgs (tl rcs) \\<noteq> []\"\n    have \"rec_exec aa xs =  Suc 0\"\n      using g\n      apply(cases \"rec_exec aa xs\", simp, auto)\n      done      \n    moreover have \"rec_exec (rec_embranch' (zip rgs list) (length xs)) xs = 0\"\n    proof -\n      have \"rec_embranch' (zip rgs list) (length xs) = rec_embranch (zip rgs list)\"\n        using g\n        apply(cases \"zip rgs list\", force)\n        apply(cases \"hd (zip rgs list)\")\n        apply(simp add: rec_embranch.simps)\n        apply(cases rgs, simp, simp, cases list, simp, auto)\n        done\n      moreover have \"rec_exec (rec_embranch (zip rgs list)) xs = 0\"\n      proof(rule embranch_all0)\n        show \" \\<forall>j<length list. rec_exec (list ! j) xs = 0\"\n          using g\n          apply(auto)\n          apply(rename_tac i j)\n          apply(case_tac i, simp)\n           apply(erule_tac x = \"Suc j\" in allE, simp)\n          apply(simp)\n          apply(erule_tac x = 0 in allE, simp)\n          done\n      next\n        show \"length rgs = length list\"\n          using g by(cases n;force)\n      next\n        show \"list \\<noteq> []\"\n          using g by(cases list; force)\n      next\n        show \"list_all (\\<lambda>rf. primerec rf (length xs)) (rgs @ list)\"\n          using g by auto\n      qed\n      ultimately show \"rec_exec (rec_embranch' (zip rgs list) (length xs)) xs = 0\"\n        by simp\n    qed\n    moreover have \n      \"Embranch (zip (map rec_exec rgs) \n          (map (\\<lambda>r args. 0 < rec_exec r args) list)) xs = 0\"\n      using g\n      apply(rule_tac k = \"length rgs\" in Embranch_0)\n         apply(simp, cases n, simp, simp)\n       apply(cases rgs, simp, simp)\n      apply(auto)\n      apply(rename_tac i j)\n      apply(case_tac i, simp)\n       apply(erule_tac x = \"Suc j\" in allE, simp)\n      apply(simp)\n      apply(rule_tac x = 0 in allE, auto)\n      done\n    moreover have \"arity a = length xs\"\n      using g\n      apply(auto)\n      done\n    ultimately show \"rec_exec (rec_embranch ((a, aa) # zip rgs list)) xs = \n      Embranch ((rec_exec a, \\<lambda>args. 0 < rec_exec aa args) #\n           zip (map rec_exec rgs) (map (\\<lambda>r args. 0 < rec_exec r args) list)) xs\"\n      apply(simp add: rec_exec.simps rec_embranch.simps Embranch.simps)\n      done\n  qed\nqed\n\ntext\\<open>\n  \\<open>prime n\\<close> means \\<open>n\\<close> is a prime number.\n\\<close>\nfun Prime :: \"nat \\<Rightarrow> bool\"\n  where\n    \"Prime x = (1 < x \\<and> (\\<forall> u < x. (\\<forall> v < x. u * v \\<noteq> x)))\"\n\ndeclare Prime.simps [simp del]\n\nlemma primerec_all1: \n  \"primerec (rec_all rt rf) n \\<Longrightarrow> primerec rt n\"\n  by (simp add: primerec_all)\n\nlemma primerec_all2: \"primerec (rec_all rt rf) n \\<Longrightarrow> \n  primerec rf (Suc n)\"\n  by(insert primerec_all[of rt rf n], simp)\n\ntext \\<open>\n  \\<open>rec_prime\\<close> is the recursive function used to implement\n  \\<open>Prime\\<close>.\n\\<close>\ndefinition rec_prime :: \"recf\"\n  where\n    \"rec_prime = Cn (Suc 0) rec_conj \n  [Cn (Suc 0) rec_less [constn 1, id (Suc 0) (0)],\n        rec_all (Cn 1 rec_minus [id 1 0, constn 1]) \n       (rec_all (Cn 2 rec_minus [id 2 0, Cn 2 (constn 1) \n  [id 2 0]]) (Cn 3 rec_noteq \n       [Cn 3 rec_mult [id 3 1, id 3 2], id 3 0]))]\"\n\ndeclare numeral_2_eq_2[simp del] numeral_3_eq_3[simp del]\n\nlemma exec_tmp: \n  \"rec_exec (rec_all (Cn 2 rec_minus [recf.id 2 0, Cn 2 (constn (Suc 0)) [recf.id 2 0]]) \n  (Cn 3 rec_noteq [Cn 3 rec_mult [recf.id 3 (Suc 0), recf.id 3 2], recf.id 3 0]))  [x, k] = \n  ((if (\\<forall>w\\<le>rec_exec (Cn 2 rec_minus [recf.id 2 0, Cn 2 (constn (Suc 0)) [recf.id 2 0]]) ([x, k]). \n  0 < rec_exec (Cn 3 rec_noteq [Cn 3 rec_mult [recf.id 3 (Suc 0), recf.id 3 2], recf.id 3 0])\n  ([x, k] @ [w])) then 1 else 0))\"\n  apply(rule_tac all_lemma)\n   apply(auto simp:numeral)\n   apply (metis (no_types, lifting) Suc_mono length_Cons less_2_cases list.size(3) nth_Cons_0\n      nth_Cons_Suc numeral_2_eq_2 prime_cn prime_id primerec_rec_mult_2 zero_less_Suc)\n  by (metis (no_types, lifting) One_nat_def length_Cons less_2_cases nth_Cons_0 nth_Cons_Suc \n      prime_cn_reverse primerec_rec_eq_2 rec_eq_def zero_less_Suc)\n\ntext \\<open>\n  The correctness of \\<open>Prime\\<close>.\n\\<close>\nlemma prime_lemma: \"rec_exec rec_prime [x] = (if Prime x then 1 else 0)\"\nproof(simp add: rec_exec.simps rec_prime_def)\n  let ?rt1 = \"(Cn 2 rec_minus [recf.id 2 0, \n    Cn 2 (constn (Suc 0)) [recf.id 2 0]])\"\n  let ?rf1 = \"(Cn 3 rec_noteq [Cn 3 rec_mult \n    [recf.id 3 (Suc 0), recf.id 3 2], recf.id 3 (0)])\"\n  let ?rt2 = \"(Cn (Suc 0) rec_minus \n    [recf.id (Suc 0) 0, constn (Suc 0)])\"\n  let ?rf2 = \"rec_all ?rt1 ?rf1\"\n  have h1: \"rec_exec (rec_all ?rt2 ?rf2) ([x]) = \n        (if (\\<forall>k\\<le>rec_exec ?rt2 ([x]). 0 < rec_exec ?rf2 ([x] @ [k])) then 1 else 0)\"\n  proof(rule_tac all_lemma, simp_all)\n    show \"primerec ?rf2 (Suc (Suc 0))\"\n      apply(rule_tac primerec_all_iff)\n        apply(auto simp: numeral)\n       apply (metis (no_types, lifting) One_nat_def length_Cons less_2_cases nth_Cons_0 nth_Cons_Suc\n          prime_cn_reverse primerec_rec_eq_2 rec_eq_def zero_less_Suc)\n      by (metis (no_types, lifting) Suc_mono length_Cons less_2_cases list.size(3) nth_Cons_0 \n          nth_Cons_Suc numeral_2_eq_2 prime_cn prime_id primerec_rec_mult_2 zero_less_Suc)\n  next\n    show \"primerec (Cn (Suc 0) rec_minus\n             [recf.id (Suc 0) 0, constn (Suc 0)]) (Suc 0)\"\n      using less_2_cases numeral by fastforce\n  qed\n  from h1 show \n    \"(Suc 0 < x \\<longrightarrow>  (rec_exec (rec_all ?rt2 ?rf2) [x] = 0 \\<longrightarrow> \n    \\<not> Prime x) \\<and>\n     (0 < rec_exec (rec_all ?rt2 ?rf2) [x] \\<longrightarrow> Prime x)) \\<and>\n    (\\<not> Suc 0 < x \\<longrightarrow> \\<not> Prime x \\<and> (rec_exec (rec_all ?rt2 ?rf2) [x] = 0\n    \\<longrightarrow> \\<not> Prime x))\"\n    apply(auto simp:rec_exec.simps)\n       apply(simp add: exec_tmp rec_exec.simps)\n  proof -\n    assume *:\"\\<forall>k\\<le>x - Suc 0. (0::nat) < (if \\<forall>w\\<le>x - Suc 0. \n           0 < (if k * w \\<noteq> x then 1 else (0 :: nat)) then 1 else 0)\" \"Suc 0 < x\"\n    thus \"Prime x\"\n      apply(simp add: rec_exec.simps split: if_splits)\n      apply(simp add: Prime.simps, auto)\n      apply(rename_tac u v)\n      apply(erule_tac x = u in allE, auto)\n       apply(case_tac u, simp)\n       apply(case_tac \"u - 1\", simp, simp)\n      apply(case_tac v, simp)\n      apply(case_tac \"v - 1\", simp, simp)\n      done\n  next\n    assume \"\\<not> Suc 0 < x\" \"Prime x\"\n    thus \"False\"\n      apply(simp add: Prime.simps)\n      done\n  next\n    fix k\n    assume \"rec_exec (rec_all ?rt1 ?rf1)\n      [x, k] = 0\" \"k \\<le> x - Suc 0\" \"Prime x\"\n    thus \"False\"\n      apply(simp add: exec_tmp rec_exec.simps Prime.simps split: if_splits)\n      done\n  next\n    fix k\n    assume \"rec_exec (rec_all ?rt1 ?rf1)\n      [x, k] = 0\" \"k \\<le> x - Suc 0\" \"Prime x\"\n    thus \"False\"\n      apply(simp add: exec_tmp rec_exec.simps Prime.simps split: if_splits)\n      done\n  qed\nqed\n\ndefinition rec_dummyfac :: \"recf\"\n  where\n    \"rec_dummyfac = Pr 1 (constn 1) \n  (Cn 3 rec_mult [id 3 2, Cn 3 s [id 3 1]])\"\n\ntext \\<open>\n  The recursive function used to implment factorization.\n\\<close>\ndefinition rec_fac :: \"recf\"\n  where\n    \"rec_fac = Cn 1 rec_dummyfac [id 1 0, id 1 0]\"\n\ntext \\<open>\n  Formal specification of factorization.\n\\<close>\nfun fac :: \"nat \\<Rightarrow> nat\"  (\"_!\" [100] 99)\n  where\n    \"fac 0 = 1\" |\n    \"fac (Suc x) = (Suc x) * fac x\"\n\n\n\ntext \\<open>\n  The correctness of \\<open>rec_fac\\<close>.\n\\<close>\nlemma fac_lemma: \"rec_exec rec_fac [x] =  x!\"\n  apply(simp add: rec_fac_def rec_exec.simps fac_dummy)\n  done\n\ndeclare fac.simps[simp del]\n\ntext \\<open>\n  \\<open>Np x\\<close> returns the first prime number after \\<open>x\\<close>.\n\\<close>\nfun Np ::\"nat \\<Rightarrow> nat\"\n  where\n    \"Np x = Min {y. y \\<le> Suc (x!) \\<and> x < y \\<and> Prime y}\"\n\ndeclare Np.simps[simp del] rec_Minr.simps[simp del]\n\ntext \\<open>\n  \\<open>rec_np\\<close> is the recursive function used to implement\n  \\<open>Np\\<close>.\n\\<close>\ndefinition rec_np :: \"recf\"\n  where\n    \"rec_np = (let Rr = Cn 2 rec_conj [Cn 2 rec_less [id 2 0, id 2 1], \n  Cn 2 rec_prime [id 2 1]]\n             in Cn 1 (rec_Minr Rr) [id 1 0, Cn 1 s [rec_fac]])\"\n\nlemma n_le_fact[simp]: \"n < Suc (n!)\"\nproof(induct n)\n  case (Suc n)\n  then show ?case  apply(simp add: fac.simps)\n    apply(cases n, auto simp: fac.simps)\n    done\nqed simp\n\nlemma divsor_ex: \n  \"\\<lbrakk>\\<not> Prime x; x > Suc 0\\<rbrakk> \\<Longrightarrow> (\\<exists> u > Suc 0. (\\<exists> v > Suc 0. u * v = x))\"\n  by(auto simp: Prime.simps)\n\nlemma divsor_prime_ex: \"\\<lbrakk>\\<not> Prime x; x > Suc 0\\<rbrakk> \\<Longrightarrow> \n  \\<exists> p. Prime p \\<and> p dvd x\"\n  apply(induct x rule: wf_induct[where r = \"measure (\\<lambda> y. y)\"], simp)\n  apply(drule_tac divsor_ex, simp, auto)\n  apply(rename_tac u v)\n  apply(erule_tac x = u in allE, simp)\n  apply(case_tac \"Prime u\", simp)\n   apply(rule_tac x = u in exI, simp, auto)\n  done\n\nlemma fact_pos[intro]: \"0 < n!\"\n  apply(induct n)\n   apply(auto simp: fac.simps)\n  done\n\nlemma fac_Suc: \"Suc n! =  (Suc n) * (n!)\" by(simp add: fac.simps)\n\nlemma fac_dvd: \"\\<lbrakk>0 < q; q \\<le> n\\<rbrakk> \\<Longrightarrow> q dvd n!\"\nproof(induct n)\n  case (Suc n)\n  then show ?case \n    apply(cases \"q \\<le> n\", simp add: fac_Suc)\n    apply(subgoal_tac \"q = Suc n\", simp only: fac_Suc)\n     apply(rule_tac dvd_mult2, simp, simp)\n    done\nqed simp\n\nlemma fac_dvd2: \"\\<lbrakk>Suc 0 < q; q dvd n!; q \\<le> n\\<rbrakk> \\<Longrightarrow> \\<not> q dvd Suc (n!)\"\nproof(auto simp: dvd_def)\n  fix k ka\n  assume h1: \"Suc 0 < q\" \"q \\<le> n\"\n    and h2: \"Suc (q * k) = q * ka\"\n  have \"k < ka\"\n  proof - \n    have \"q * k < q * ka\" \n      using h2 by arith\n    thus \"k < ka\"\n      using h1\n      by(auto)\n  qed\n  hence \"\\<exists>d. d > 0 \\<and>  ka = d + k\"  \n    by(rule_tac x = \"ka - k\" in exI, simp)\n  from this obtain d where \"d > 0 \\<and> ka = d + k\" ..\n  from h2 and this and h1 show \"False\"\n    by(simp add: add_mult_distrib2)\nqed\n\nlemma prime_ex: \"\\<exists> p. n < p \\<and> p \\<le> Suc (n!) \\<and> Prime p\"\nproof(cases \"Prime (n! + 1)\")\n  case True thus \"?thesis\" \n    by(rule_tac x = \"Suc (n!)\" in exI, simp)\nnext\n  assume h: \"\\<not> Prime (n! + 1)\"  \n  hence \"\\<exists> p. Prime p \\<and> p dvd (n! + 1)\"\n    by(erule_tac divsor_prime_ex, auto)\n  from this obtain q where k: \"Prime q \\<and> q dvd (n! + 1)\" ..\n  thus \"?thesis\"\n  proof(cases \"q > n\")\n    case True thus \"?thesis\"\n      using k by(auto intro:dvd_imp_le)\n  next\n    case False thus \"?thesis\"\n    proof -\n      assume g: \"\\<not> n < q\"\n      have j: \"q > Suc 0\"\n        using k by(cases q, auto simp: Prime.simps)\n      hence \"q dvd n!\"\n        using g \n        apply(rule_tac fac_dvd, auto)\n        done\n      hence \"\\<not> q dvd Suc (n!)\"\n        using g j\n        by(rule_tac fac_dvd2, auto)\n      thus \"?thesis\"\n        using k by simp\n    qed\n  qed\nqed\n\nlemma Suc_Suc_induct[elim!]: \"\\<lbrakk>i < Suc (Suc 0); \n  primerec (ys ! 0) n; primerec (ys ! 1) n\\<rbrakk> \\<Longrightarrow> primerec (ys ! i) n\"\n  by(cases i, auto)\n\nlemma primerec_rec_prime_1[intro]: \"primerec rec_prime (Suc 0)\"\n  apply(auto simp: rec_prime_def, auto)\n  apply(rule_tac primerec_all_iff, auto, auto)\n  apply(rule_tac primerec_all_iff, auto, auto simp:  \n      numeral_2_eq_2 numeral_3_eq_3)\n  done\n\ntext \\<open>\n  The correctness of \\<open>rec_np\\<close>.\n\\<close>\n\n\ntext \\<open>\n  \\<open>rec_power\\<close> is the recursive function used to implement\n  power function.\n\\<close>\ndefinition rec_power :: \"recf\"\n  where\n    \"rec_power = Pr 1 (constn 1) (Cn 3 rec_mult [id 3 0, id 3 2])\"\n\ntext \\<open>\n  The correctness of \\<open>rec_power\\<close>.\n\\<close>\nlemma power_lemma: \"rec_exec rec_power [x, y] = x^y\"\n  by(induct y, auto simp: rec_exec.simps rec_power_def)\n\ntext\\<open>\n  \\<open>Pi k\\<close> returns the \\<open>k\\<close>-th prime number.\n\\<close>\nfun Pi :: \"nat \\<Rightarrow> nat\"\n  where\n    \"Pi 0 = 2\" |\n    \"Pi (Suc x) = Np (Pi x)\"\n\ndefinition rec_dummy_pi :: \"recf\"\n  where\n    \"rec_dummy_pi = Pr 1 (constn 2) (Cn 3 rec_np [id 3 2])\"\n\ntext \\<open>\n  \\<open>rec_pi\\<close> is the recursive function used to implement\n  \\<open>Pi\\<close>.\n\\<close>\ndefinition rec_pi :: \"recf\"\n  where\n    \"rec_pi = Cn 1 rec_dummy_pi [id 1 0, id 1 0]\"\n\nlemma pi_dummy_lemma: \"rec_exec rec_dummy_pi [x, y] = Pi y\"\n  apply(induct y)\n  by(auto simp: rec_exec.simps rec_dummy_pi_def Pi.simps np_lemma)\n\ntext \\<open>\n  The correctness of \\<open>rec_pi\\<close>.\n\\<close>\nlemma pi_lemma: \"rec_exec rec_pi [x] = Pi x\"\n  apply(simp add: rec_pi_def rec_exec.simps pi_dummy_lemma)\n  done\n\nfun loR :: \"nat list \\<Rightarrow> bool\"\n  where\n    \"loR [x, y, u] = (x mod (y^u) = 0)\"\n\ndeclare loR.simps[simp del]\n\ntext \\<open>\n  \\<open>Lo\\<close> specifies the \\<open>lo\\<close> function given on page 79 of \n  Boolos's book. It is one of the two notions of integeral logarithmetic\n  operation on that page. The other is \\<open>lg\\<close>.\n\\<close>\nfun lo :: \" nat \\<Rightarrow> nat \\<Rightarrow> nat\"\n  where \n    \"lo x y  = (if x > 1 \\<and> y > 1 \\<and> {u. loR [x, y, u]} \\<noteq> {} then Max {u. loR [x, y, u]}\n                                                         else 0)\"\n\ndeclare lo.simps[simp del]\n\nlemma primerec_sigma[intro!]:  \n  \"\\<lbrakk>n > Suc 0; primerec rf n\\<rbrakk> \\<Longrightarrow> \n  primerec (rec_sigma rf) n\"\n  apply(simp add: rec_sigma.simps)\n  apply(auto, auto simp: nth_append)\n  done\n\nlemma primerec_rec_maxr[intro!]:  \"\\<lbrakk>primerec rf n; n > 0\\<rbrakk> \\<Longrightarrow> primerec (rec_maxr rf) n\"\n  apply(simp add: rec_maxr.simps)\n  apply(rule_tac prime_cn, auto)\n   apply(rule_tac primerec_all_iff, auto, auto simp: nth_append)\n  done\n\nlemma Suc_Suc_Suc_induct[elim!]: \n  \"\\<lbrakk>i < Suc (Suc (Suc (0::nat))); primerec (ys ! 0) n;\n  primerec (ys ! 1) n;  \n  primerec (ys ! 2) n\\<rbrakk> \\<Longrightarrow> primerec (ys ! i) n\"\n  apply(cases i, auto)\n  apply(cases \"i-1\", simp, simp add: numeral_2_eq_2)\n  done\n\nlemma primerec_2[intro]:\n  \"primerec rec_quo (Suc (Suc 0))\" \"primerec rec_mod (Suc (Suc 0))\"\n  \"primerec rec_power (Suc (Suc 0))\"\n  by(force simp: prime_cn prime_id rec_mod_def rec_quo_def rec_power_def prime_pr numeral)+\n\ntext \\<open>\n  \\<open>rec_lo\\<close> is the recursive function used to implement \\<open>Lo\\<close>.\n\\<close>\ndefinition rec_lo :: \"recf\"\n  where\n    \"rec_lo = (let rR = Cn 3 rec_eq [Cn 3 rec_mod [id 3 0, \n               Cn 3 rec_power [id 3 1, id 3 2]], \n                     Cn 3 (constn 0) [id 3 1]] in\n             let rb =  Cn 2 (rec_maxr rR) [id 2 0, id 2 1, id 2 0] in \n             let rcond = Cn 2 rec_conj [Cn 2 rec_less [Cn 2 (constn 1)\n                                             [id 2 0], id 2 0], \n                                        Cn 2 rec_less [Cn 2 (constn 1)\n                                                [id 2 0], id 2 1]] in \n             let rcond2 = Cn 2 rec_minus \n                              [Cn 2 (constn 1) [id 2 0], rcond] \n             in Cn 2 rec_add [Cn 2 rec_mult [rb, rcond], \n                  Cn 2 rec_mult [Cn 2 (constn 0) [id 2 0], rcond2]])\"\n\nlemma rec_lo_Maxr_lor:\n  \"\\<lbrakk>Suc 0 < x; Suc 0 < y\\<rbrakk> \\<Longrightarrow>  \n        rec_exec rec_lo [x, y] = Maxr loR [x, y] x\"\nproof(auto simp: rec_exec.simps rec_lo_def Let_def \n    numeral_2_eq_2 numeral_3_eq_3)\n  let ?rR = \"(Cn (Suc (Suc (Suc 0))) rec_eq\n     [Cn (Suc (Suc (Suc 0))) rec_mod [recf.id (Suc (Suc (Suc 0))) 0,\n     Cn (Suc (Suc (Suc 0))) rec_power [recf.id (Suc (Suc (Suc 0)))\n     (Suc 0), recf.id (Suc (Suc (Suc 0))) (Suc (Suc 0))]],\n     Cn (Suc (Suc (Suc 0))) (constn 0) [recf.id (Suc (Suc (Suc 0))) (Suc 0)]])\"\n  have h: \"rec_exec (rec_maxr ?rR) ([x, y] @ [x]) =\n    Maxr (\\<lambda> args. 0 < rec_exec ?rR args) [x, y] x\"\n    by(rule_tac Maxr_lemma, auto simp: rec_exec.simps\n        mod_lemma power_lemma, auto simp: numeral_2_eq_2 numeral_3_eq_3)\n  have \"Maxr loR [x, y] x =  Maxr (\\<lambda> args. 0 < rec_exec ?rR args) [x, y] x\"\n    apply(simp add: rec_exec.simps mod_lemma power_lemma)\n    apply(simp add: Maxr.simps loR.simps)\n    done\n  from h and this show \"rec_exec (rec_maxr ?rR) [x, y, x] = \n    Maxr loR [x, y] x\"\n    apply(simp)\n    done\nqed\n\nlemma x_less_exp: \"\\<lbrakk>y > Suc 0\\<rbrakk> \\<Longrightarrow> x < y^x\"\nproof(induct x)\n  case (Suc x)\n  then show ?case  \n    apply(cases x, simp, auto)\n    apply(rule_tac y = \"y* y^(x-1)\" in le_less_trans, auto)\n    done\nqed simp\n\n\nlemma uplimit_loR:\n  assumes \"Suc 0 < x\" \"Suc 0 < y\" \"loR [x, y, xa]\"\n  shows \"xa \\<le> x\"\nproof -\n  have \"Suc 0 < x \\<Longrightarrow> Suc 0 < y \\<Longrightarrow> y ^ xa dvd x \\<Longrightarrow> xa \\<le> x\" \n    by (meson Suc_lessD le_less_trans nat_dvd_not_less nat_le_linear x_less_exp)\n  thus ?thesis using assms by(auto simp: loR.simps)\nqed\n\nlemma loR_set_strengthen[simp]: \"\\<lbrakk>xa \\<le> x; loR [x, y, xa]; Suc 0 < x; Suc 0 < y\\<rbrakk> \\<Longrightarrow>\n  {u. loR [x, y, u]} = {ya. ya \\<le> x \\<and> loR [x, y, ya]}\"\n  apply(rule_tac Collect_cong, auto)\n  apply(erule_tac uplimit_loR, simp, simp)\n  done\n\nlemma Maxr_lo: \"\\<lbrakk>Suc 0 < x; Suc 0 < y\\<rbrakk> \\<Longrightarrow>\n  Maxr loR [x, y] x = lo x y\" \n  apply(simp add: Maxr.simps lo.simps, auto simp: uplimit_loR)\n  by (meson uplimit_loR)+\n\nlemma lo_lemma': \"\\<lbrakk>Suc 0 < x; Suc 0 < y\\<rbrakk> \\<Longrightarrow> \n  rec_exec rec_lo [x, y] = lo x y\"\n  by(simp add: Maxr_lo  rec_lo_Maxr_lor)\n\nlemma lo_lemma'': \"\\<lbrakk>\\<not> Suc 0 < x\\<rbrakk> \\<Longrightarrow> rec_exec rec_lo [x, y] = lo x y\"\n  apply(cases x, auto simp: rec_exec.simps rec_lo_def \n      Let_def lo.simps)\n  done\n\nlemma lo_lemma''': \"\\<lbrakk>\\<not> Suc 0 < y\\<rbrakk> \\<Longrightarrow> rec_exec rec_lo [x, y] = lo x y\"\n  apply(cases y, auto simp: rec_exec.simps rec_lo_def \n      Let_def lo.simps)\n  done\n\ntext \\<open>\n  The correctness of \\<open>rec_lo\\<close>:\n\\<close>\nlemma lo_lemma: \"rec_exec rec_lo [x, y] = lo x y\" \n  apply(cases \"Suc 0 < x \\<and> Suc 0 < y\")\n   apply(auto simp: lo_lemma' lo_lemma'' lo_lemma''')\n  done\n\nfun lgR :: \"nat list \\<Rightarrow> bool\"\n  where\n    \"lgR [x, y, u] = (y^u \\<le> x)\"\n\ntext \\<open>\n  \\<open>lg\\<close> specifies the \\<open>lg\\<close> function given on page 79 of \n  Boolos's book. It is one of the two notions of integeral logarithmetic\n  operation on that page. The other is \\<open>lo\\<close>.\n\\<close>\nfun lg :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\"\n  where\n    \"lg x y = (if x > 1 \\<and> y > 1 \\<and> {u. lgR [x, y, u]} \\<noteq> {} then \n                 Max {u. lgR [x, y, u]}\n              else 0)\"\n\ndeclare lg.simps[simp del] lgR.simps[simp del]\n\ntext \\<open>\n  \\<open>rec_lg\\<close> is the recursive function used to implement \\<open>lg\\<close>.\n\\<close>\ndefinition rec_lg :: \"recf\"\n  where\n    \"rec_lg = (let rec_lgR = Cn 3 rec_le\n  [Cn 3 rec_power [id 3 1, id 3 2], id 3 0] in\n  let conR1 = Cn 2 rec_conj [Cn 2 rec_less \n                     [Cn 2 (constn 1) [id 2 0], id 2 0], \n                            Cn 2 rec_less [Cn 2 (constn 1) \n                                 [id 2 0], id 2 1]] in \n  let conR2 = Cn 2 rec_not [conR1] in \n        Cn 2 rec_add [Cn 2 rec_mult \n              [conR1, Cn 2 (rec_maxr rec_lgR)\n                       [id 2 0, id 2 1, id 2 0]], \n                       Cn 2 rec_mult [conR2, Cn 2 (constn 0) \n                                [id 2 0]]])\"\n\nlemma lg_maxr: \"\\<lbrakk>Suc 0 < x; Suc 0 < y\\<rbrakk> \\<Longrightarrow> \n                      rec_exec rec_lg [x, y] = Maxr lgR [x, y] x\"\nproof(simp add: rec_exec.simps rec_lg_def Let_def)\n  assume h: \"Suc 0 < x\" \"Suc 0 < y\"\n  let ?rR = \"(Cn 3 rec_le [Cn 3 rec_power\n               [recf.id 3 (Suc 0), recf.id 3 2], recf.id 3 0])\"\n  have \"rec_exec (rec_maxr ?rR) ([x, y] @ [x])\n              = Maxr ((\\<lambda> args. 0 < rec_exec ?rR args)) [x, y] x\" \n  proof(rule Maxr_lemma)\n    show \"primerec (Cn 3 rec_le [Cn 3 rec_power \n              [recf.id 3 (Suc 0), recf.id 3 2], recf.id 3 0]) (Suc (length [x, y]))\"\n      apply(auto simp: numeral_3_eq_3)+\n      done\n  qed\n  moreover have \"Maxr lgR [x, y] x = Maxr ((\\<lambda> args. 0 < rec_exec ?rR args)) [x, y] x\"\n    apply(simp add: rec_exec.simps power_lemma)\n    apply(simp add: Maxr.simps lgR.simps)\n    done \n  ultimately show \"rec_exec (rec_maxr ?rR) [x, y, x] = Maxr lgR [x, y] x\"\n    by simp\nqed\n\nlemma lgR_ok: \"\\<lbrakk>Suc 0 < y; lgR [x, y, xa]\\<rbrakk> \\<Longrightarrow> xa \\<le> x\"\n  apply(auto simp add: lgR.simps)\n  apply(subgoal_tac \"y^xa > xa\", simp)\n  apply(erule x_less_exp)\n  done\n\nlemma lgR_set_strengthen[simp]: \"\\<lbrakk>Suc 0 < x; Suc 0 < y; lgR [x, y, xa]\\<rbrakk> \\<Longrightarrow>\n           {u. lgR [x, y, u]} =  {ya. ya \\<le> x \\<and> lgR [x, y, ya]}\"\n  apply(rule_tac Collect_cong, auto simp:lgR_ok)\n  done\n\nlemma maxr_lg: \"\\<lbrakk>Suc 0 < x; Suc 0 < y\\<rbrakk> \\<Longrightarrow> Maxr lgR [x, y] x = lg x y\"\n  apply(auto simp add: lg.simps Maxr.simps)\n  using lgR_ok by blast\n\nlemma lg_lemma': \"\\<lbrakk>Suc 0 < x; Suc 0 < y\\<rbrakk> \\<Longrightarrow> rec_exec rec_lg [x, y] = lg x y\"\n  apply(simp add: maxr_lg lg_maxr)\n  done\n\nlemma lg_lemma'': \"\\<not> Suc 0 < x \\<Longrightarrow> rec_exec rec_lg [x, y] = lg x y\"\n  apply(simp add: rec_exec.simps rec_lg_def Let_def lg.simps)\n  done\n\nlemma lg_lemma''': \"\\<not> Suc 0 < y \\<Longrightarrow> rec_exec rec_lg [x, y] = lg x y\"\n  apply(simp add: rec_exec.simps rec_lg_def Let_def lg.simps)\n  done\n\ntext \\<open>\n  The correctness of \\<open>rec_lg\\<close>.\n\\<close>\nlemma lg_lemma: \"rec_exec rec_lg [x, y] = lg x y\"\n  apply(cases \"Suc 0 < x \\<and> Suc 0 < y\", auto simp: \n      lg_lemma' lg_lemma'' lg_lemma''')\n  done\n\ntext \\<open>\n  \\<open>Entry sr i\\<close> returns the \\<open>i\\<close>-th entry of a list of natural \n  numbers encoded by number \\<open>sr\\<close> using Godel's coding.\n\\<close>\nfun Entry :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\"\n  where\n    \"Entry sr i = lo sr (Pi (Suc i))\"\n\ntext \\<open>\n  \\<open>rec_entry\\<close> is the recursive function used to implement\n  \\<open>Entry\\<close>.\n\\<close>\ndefinition rec_entry:: \"recf\"\n  where\n    \"rec_entry = Cn 2 rec_lo [id 2 0, Cn 2 rec_pi [Cn 2 s [id 2 1]]]\"\n\ndeclare Pi.simps[simp del]\n\ntext \\<open>\n  The correctness of \\<open>rec_entry\\<close>.\n\\<close>\nlemma entry_lemma: \"rec_exec rec_entry [str, i] = Entry str i\"\n  by(simp add: rec_entry_def  rec_exec.simps lo_lemma pi_lemma)\n\n\nsubsection \\<open>The construction of F\\<close>\n\ntext \\<open>\n  Using the auxilliary functions obtained in last section, \n  we are going to contruct the function \\<open>F\\<close>, \n  which is an interpreter of Turing Machines.\n\\<close>\n\nfun listsum2 :: \"nat list \\<Rightarrow> nat \\<Rightarrow> nat\"\n  where\n    \"listsum2 xs 0 = 0\"\n  | \"listsum2 xs (Suc n) = listsum2 xs n + xs ! n\"\n\nfun rec_listsum2 :: \"nat \\<Rightarrow> nat \\<Rightarrow> recf\"\n  where\n    \"rec_listsum2 vl 0 = Cn vl z [id vl 0]\"\n  | \"rec_listsum2 vl (Suc n) = Cn vl rec_add [rec_listsum2 vl n, id vl n]\"\n\ndeclare listsum2.simps[simp del] rec_listsum2.simps[simp del]\n\nlemma listsum2_lemma: \"\\<lbrakk>length xs = vl; n \\<le> vl\\<rbrakk> \\<Longrightarrow> \n      rec_exec (rec_listsum2 vl n) xs = listsum2 xs n\"\n  apply(induct n, simp_all)\n   apply(simp_all add: rec_exec.simps rec_listsum2.simps listsum2.simps)\n  done\n\nfun strt' :: \"nat list \\<Rightarrow> nat \\<Rightarrow> nat\"\n  where\n    \"strt' xs 0 = 0\"\n  | \"strt' xs (Suc n) = (let dbound = listsum2 xs n + n in \n                       strt' xs n + (2^(xs ! n + dbound) - 2^dbound))\"\n\nfun rec_strt' :: \"nat \\<Rightarrow> nat \\<Rightarrow> recf\"\n  where\n    \"rec_strt' vl 0 = Cn vl z [id vl 0]\"\n  | \"rec_strt' vl (Suc n) = (let rec_dbound =\n  Cn vl rec_add [rec_listsum2 vl n, Cn vl (constn n) [id vl 0]]\n  in Cn vl rec_add [rec_strt' vl n, Cn vl rec_minus \n  [Cn vl rec_power [Cn vl (constn 2) [id vl 0], Cn vl rec_add\n  [id vl (n), rec_dbound]], \n  Cn vl rec_power [Cn vl (constn 2) [id vl 0], rec_dbound]]])\"\n\ndeclare strt'.simps[simp del] rec_strt'.simps[simp del]\n\nlemma strt'_lemma: \"\\<lbrakk>length xs = vl; n \\<le> vl\\<rbrakk> \\<Longrightarrow> \n  rec_exec (rec_strt' vl n) xs = strt' xs n\"\n  apply(induct n)\n   apply(simp_all add: rec_exec.simps rec_strt'.simps strt'.simps\n      Let_def power_lemma listsum2_lemma)\n  done\n\ntext \\<open>\n  \\<open>strt\\<close> corresponds to the \\<open>strt\\<close> function on page 90 of B book, but \n  this definition generalises the original one to deal with multiple input arguments.\n\\<close>\nfun strt :: \"nat list \\<Rightarrow> nat\"\n  where\n    \"strt xs = (let ys = map Suc xs in \n              strt' ys (length ys))\"\n\nfun rec_map :: \"recf \\<Rightarrow> nat \\<Rightarrow> recf list\"\n  where\n    \"rec_map rf vl = map (\\<lambda> i. Cn vl rf [id vl i]) [0..<vl]\"\n\ntext \\<open>\n  \\<open>rec_strt\\<close> is the recursive function used to implement \\<open>strt\\<close>.\n\\<close>\nfun rec_strt :: \"nat \\<Rightarrow> recf\"\n  where\n    \"rec_strt vl = Cn vl (rec_strt' vl vl) (rec_map s vl)\"\n\nlemma map_s_lemma: \"length xs = vl \\<Longrightarrow> \n  map ((\\<lambda>a. rec_exec a xs) \\<circ> (\\<lambda>i. Cn vl s [recf.id vl i]))\n  [0..<vl]\n        = map Suc xs\"\n  apply(induct vl arbitrary: xs, simp, auto simp: rec_exec.simps)\n  apply(rename_tac vl xs)\n  apply(subgoal_tac \"\\<exists> ys y. xs = ys @ [y]\", auto)\nproof -\n  fix ys y\n  assume ind: \"\\<And>xs. length xs = length (ys::nat list) \\<Longrightarrow>\n      map ((\\<lambda>a. rec_exec a xs) \\<circ> (\\<lambda>i. Cn (length ys) s \n        [recf.id (length ys) (i)])) [0..<length ys] = map Suc xs\"\n  show\n    \"map ((\\<lambda>a. rec_exec a (ys @ [y])) \\<circ> (\\<lambda>i. Cn (Suc (length ys)) s \n  [recf.id (Suc (length ys)) (i)])) [0..<length ys] = map Suc ys\"\n  proof -\n    have \"map ((\\<lambda>a. rec_exec a ys) \\<circ> (\\<lambda>i. Cn (length ys) s\n        [recf.id (length ys) (i)])) [0..<length ys] = map Suc ys\"\n      apply(rule_tac ind, simp)\n      done\n    moreover have\n      \"map ((\\<lambda>a. rec_exec a (ys @ [y])) \\<circ> (\\<lambda>i. Cn (Suc (length ys)) s\n           [recf.id (Suc (length ys)) (i)])) [0..<length ys]\n         = map ((\\<lambda>a. rec_exec a ys) \\<circ> (\\<lambda>i. Cn (length ys) s \n                 [recf.id (length ys) (i)])) [0..<length ys]\"\n      apply(rule_tac map_ext, auto simp: rec_exec.simps nth_append)\n      done\n    ultimately show \"?thesis\"\n      by simp\n  qed\nnext\n  fix vl xs\n  assume \"length xs = Suc vl\"\n  thus \"\\<exists>ys y. xs = ys @ [y]\"\n    apply(rule_tac x = \"butlast xs\" in exI, rule_tac x = \"last xs\" in exI)\n    apply(subgoal_tac \"xs \\<noteq> []\", auto)\n    done\nqed\n\ntext \\<open>\n  The correctness of \\<open>rec_strt\\<close>.\n\\<close>\nlemma strt_lemma: \"length xs = vl \\<Longrightarrow> \n  rec_exec (rec_strt vl) xs = strt xs\"\n  apply(simp add: strt.simps rec_exec.simps strt'_lemma)\n  apply(subgoal_tac \"(map ((\\<lambda>a. rec_exec a xs) \\<circ> (\\<lambda>i. Cn vl s [recf.id vl (i)])) [0..<vl])\n                  = map Suc xs\", auto)\n  apply(rule map_s_lemma, simp)\n  done\n\ntext \\<open>\n  The \\<open>scan\\<close> function on page 90 of B book.\n\\<close>\nfun scan :: \"nat \\<Rightarrow> nat\"\n  where\n    \"scan r = r mod 2\"\n\ntext \\<open>\n  \\<open>rec_scan\\<close> is the implemention of \\<open>scan\\<close>.\n\\<close>\ndefinition rec_scan :: \"recf\"\n  where \"rec_scan = Cn 1 rec_mod [id 1 0, constn 2]\"\n\ntext \\<open>\n  The correctness of \\<open>scan\\<close>.\n\\<close>\nlemma scan_lemma: \"rec_exec rec_scan [r] = r mod 2\"\n  by(simp add: rec_exec.simps rec_scan_def mod_lemma)\n\nfun newleft0 :: \"nat list \\<Rightarrow> nat\"\n  where\n    \"newleft0 [p, r] = p\"\n\ndefinition rec_newleft0 :: \"recf\"\n  where\n    \"rec_newleft0 = id 2 0\"\n\nfun newrgt0 :: \"nat list \\<Rightarrow> nat\"\n  where\n    \"newrgt0 [p, r] = r - scan r\"\n\ndefinition rec_newrgt0 :: \"recf\"\n  where\n    \"rec_newrgt0 = Cn 2 rec_minus [id 2 1, Cn 2 rec_scan [id 2 1]]\"\n\n(*newleft1, newrgt1: left rgt number after execute on step*)\nfun newleft1 :: \"nat list \\<Rightarrow> nat\"\n  where\n    \"newleft1 [p, r] = p\"\n\ndefinition rec_newleft1 :: \"recf\"\n  where\n    \"rec_newleft1 = id 2 0\"\n\nfun newrgt1 :: \"nat list \\<Rightarrow> nat\"\n  where\n    \"newrgt1 [p, r] = r + 1 - scan r\"\n\ndefinition rec_newrgt1 :: \"recf\"\n  where\n    \"rec_newrgt1 = \n  Cn 2 rec_minus [Cn 2 rec_add [id 2 1, Cn 2 (constn 1) [id 2 0]], \n                  Cn 2 rec_scan [id 2 1]]\"\n\nfun newleft2 :: \"nat list \\<Rightarrow> nat\"\n  where\n    \"newleft2 [p, r] = p div 2\"\n\ndefinition rec_newleft2 :: \"recf\" \n  where\n    \"rec_newleft2 = Cn 2 rec_quo [id 2 0, Cn 2 (constn 2) [id 2 0]]\"\n\nfun newrgt2 :: \"nat list \\<Rightarrow> nat\"\n  where\n    \"newrgt2 [p, r] = 2 * r + p mod 2\"\n\ndefinition rec_newrgt2 :: \"recf\"\n  where\n    \"rec_newrgt2 =\n    Cn 2 rec_add [Cn 2 rec_mult [Cn 2 (constn 2) [id 2 0], id 2 1],                     \n                 Cn 2 rec_mod [id 2 0, Cn 2 (constn 2) [id 2 0]]]\"\n\nfun newleft3 :: \"nat list \\<Rightarrow> nat\"\n  where\n    \"newleft3 [p, r] = 2 * p + r mod 2\"\n\ndefinition rec_newleft3 :: \"recf\"\n  where\n    \"rec_newleft3 = \n  Cn 2 rec_add [Cn 2 rec_mult [Cn 2 (constn 2) [id 2 0], id 2 0], \n                Cn 2 rec_mod [id 2 1, Cn 2 (constn 2) [id 2 0]]]\"\n\nfun newrgt3 :: \"nat list \\<Rightarrow> nat\"\n  where\n    \"newrgt3 [p, r] = r div 2\"\n\ndefinition rec_newrgt3 :: \"recf\"\n  where\n    \"rec_newrgt3 = Cn 2 rec_quo [id 2 1, Cn 2 (constn 2) [id 2 0]]\"\n\ntext \\<open>\n  The \\<open>new_left\\<close> function on page 91 of B book.\n\\<close>\nfun newleft :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> nat\"\n  where\n    \"newleft p r a = (if a = 0 \\<or> a = 1 then newleft0 [p, r] \n                    else if a = 2 then newleft2 [p, r]\n                    else if a = 3 then newleft3 [p, r]\n                    else p)\"\n\ntext \\<open>\n  \\<open>rec_newleft\\<close> is the recursive function used to \n  implement \\<open>newleft\\<close>.\n\\<close>\ndefinition rec_newleft :: \"recf\" \n  where\n    \"rec_newleft =\n  (let g0 = \n      Cn 3 rec_newleft0 [id 3 0, id 3 1] in \n  let g1 = Cn 3 rec_newleft2 [id 3 0, id 3 1] in \n  let g2 = Cn 3 rec_newleft3 [id 3 0, id 3 1] in \n  let g3 = id 3 0 in\n  let r0 = Cn 3 rec_disj\n          [Cn 3 rec_eq [id 3 2, Cn 3 (constn 0) [id 3 0]],\n           Cn 3 rec_eq [id 3 2, Cn 3 (constn 1) [id 3 0]]] in \n  let r1 = Cn 3 rec_eq [id 3 2, Cn 3 (constn 2) [id 3 0]] in \n  let r2 = Cn 3 rec_eq [id 3 2, Cn 3 (constn 3) [id 3 0]] in\n  let r3 = Cn 3 rec_less [Cn 3 (constn 3) [id 3 0], id 3 2] in \n  let gs = [g0, g1, g2, g3] in \n  let rs = [r0, r1, r2, r3] in \n  rec_embranch (zip gs rs))\"\n\ndeclare newleft.simps[simp del]\n\n\nlemma Suc_Suc_Suc_Suc_induct: \n  \"\\<lbrakk>i < Suc (Suc (Suc (Suc 0))); i = 0 \\<Longrightarrow>  P i;\n    i = 1 \\<Longrightarrow> P i; i =2 \\<Longrightarrow> P i; \n    i =3 \\<Longrightarrow> P i\\<rbrakk> \\<Longrightarrow> P i\"\n  apply(cases i, force)\n  apply(cases \"i - 1\", force)\n  apply(cases \"i - 1 - 1\", force)\n  by(cases \"i - 1 - 1 - 1\", auto simp:numeral)\n\ndeclare quo_lemma2[simp] mod_lemma[simp]\n\ntext \\<open>\n  The correctness of \\<open>rec_newleft\\<close>.\n\\<close>\nlemma newleft_lemma: \n  \"rec_exec rec_newleft [p, r, a] = newleft p r a\"\nproof(simp only: rec_newleft_def Let_def)\n  let ?rgs = \"[Cn 3 rec_newleft0 [recf.id 3 0, recf.id 3 1], Cn 3 rec_newleft2 \n       [recf.id 3 0, recf.id 3 1], Cn 3 rec_newleft3 [recf.id 3 0, recf.id 3 1], recf.id 3 0]\"\n  let ?rrs = \n    \"[Cn 3 rec_disj [Cn 3 rec_eq [recf.id 3 2, Cn 3 (constn 0) \n     [recf.id 3 0]], Cn 3 rec_eq [recf.id 3 2, Cn 3 (constn 1) [recf.id 3 0]]], \n     Cn 3 rec_eq [recf.id 3 2, Cn 3 (constn 2) [recf.id 3 0]],\n     Cn 3 rec_eq [recf.id 3 2, Cn 3 (constn 3) [recf.id 3 0]],\n     Cn 3 rec_less [Cn 3 (constn 3) [recf.id 3 0], recf.id 3 2]]\"\n  have k1: \"rec_exec (rec_embranch (zip ?rgs ?rrs)) [p, r, a]\n                         = Embranch (zip (map rec_exec ?rgs) (map (\\<lambda>r args. 0 < rec_exec r args) ?rrs)) [p, r, a]\"\n    apply(rule_tac embranch_lemma )\n        apply(auto simp: numeral_3_eq_3 numeral_2_eq_2 rec_newleft0_def \n        rec_newleft1_def rec_newleft2_def rec_newleft3_def)+\n    apply(cases \"a = 0 \\<or> a = 1\", rule_tac x = 0 in exI)\n     prefer 2\n     apply(cases \"a = 2\", rule_tac x = \"Suc 0\" in exI)\n      prefer 2\n      apply(cases \"a = 3\", rule_tac x = \"2\" in exI)\n       prefer 2\n       apply(cases \"a > 3\", rule_tac x = \"3\" in exI, auto)\n             apply(auto simp: rec_exec.simps)\n        apply(erule_tac [!] Suc_Suc_Suc_Suc_induct, auto simp: rec_exec.simps)\n    done\n  have k2: \"Embranch (zip (map rec_exec ?rgs) (map (\\<lambda>r args. 0 < rec_exec r args) ?rrs)) [p, r, a] = newleft p r a\"\n    apply(simp add: Embranch.simps)\n    apply(simp add: rec_exec.simps)\n    apply(auto simp: newleft.simps rec_newleft0_def rec_exec.simps\n        rec_newleft1_def rec_newleft2_def rec_newleft3_def)\n    done\n  from k1 and k2 show \n    \"rec_exec (rec_embranch (zip ?rgs ?rrs)) [p, r, a] = newleft p r a\"\n    by simp\nqed\n\ntext \\<open>\n  The \\<open>newrght\\<close> function is one similar to \\<open>newleft\\<close>, but used to \n  compute the right number.\n\\<close>\nfun newrght :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> nat\"\n  where\n    \"newrght p r a  = (if a = 0 then newrgt0 [p, r]\n                    else if a = 1 then newrgt1 [p, r]\n                    else if a = 2 then newrgt2 [p, r]\n                    else if a = 3 then newrgt3 [p, r]\n                    else r)\"\n\ntext \\<open>\n  \\<open>rec_newrght\\<close> is the recursive function used to implement \n  \\<open>newrgth\\<close>.\n\\<close>\ndefinition rec_newrght :: \"recf\" \n  where\n    \"rec_newrght =\n  (let g0 = Cn 3 rec_newrgt0 [id 3 0, id 3 1] in \n  let g1 = Cn 3 rec_newrgt1 [id 3 0, id 3 1] in \n  let g2 = Cn 3 rec_newrgt2 [id 3 0, id 3 1] in \n  let g3 = Cn 3 rec_newrgt3 [id 3 0, id 3 1] in\n  let g4 = id 3 1 in \n  let r0 = Cn 3 rec_eq [id 3 2, Cn 3 (constn 0) [id 3 0]] in \n  let r1 = Cn 3 rec_eq [id 3 2, Cn 3 (constn 1) [id 3 0]] in \n  let r2 = Cn 3 rec_eq [id 3 2, Cn 3 (constn 2) [id 3 0]] in\n  let r3 = Cn 3 rec_eq [id 3 2, Cn 3 (constn 3) [id 3 0]] in\n  let r4 = Cn 3 rec_less [Cn 3 (constn 3) [id 3 0], id 3 2] in \n  let gs = [g0, g1, g2, g3, g4] in \n  let rs = [r0, r1, r2, r3, r4] in \n  rec_embranch (zip gs rs))\"\ndeclare newrght.simps[simp del]\n\nlemma numeral_4_eq_4: \"4 = Suc 3\"\n  by auto\n\nlemma Suc_5_induct: \n  \"\\<lbrakk>i < Suc (Suc (Suc (Suc (Suc 0)))); i = 0 \\<Longrightarrow> P 0;\n  i = 1 \\<Longrightarrow> P 1; i = 2 \\<Longrightarrow> P 2; i = 3 \\<Longrightarrow> P 3; i = 4 \\<Longrightarrow> P 4\\<rbrakk> \\<Longrightarrow> P i\"\n  apply(cases i, force)\n  apply(cases \"i-1\", force)\n  apply(cases \"i-1-1\")\n  using less_2_cases numeral by auto\n\n\nlemma primerec_rec_scan_1[intro]: \"primerec rec_scan (Suc 0)\"\n  apply(auto simp: rec_scan_def, auto)\n  done\n\ntext \\<open>\n  The correctness of \\<open>rec_newrght\\<close>.\n\\<close>\n\n\n  have k1: \"rec_exec (rec_embranch (zip ?rgs ?rrs)) [p, r, a]\n    = Embranch (zip (map rec_exec ?rgs) (map (\\<lambda>r args. 0 < rec_exec r args) ?rrs)) [p, r, a]\"\n    apply(rule_tac embranch_lemma)\n        apply(auto simp: numeral_3_eq_3 numeral_2_eq_2 rec_newrgt0_def \n        rec_newrgt1_def rec_newrgt2_def rec_newrgt3_def)+\n    apply(cases \"a = 0\", rule_tac x = 0 in exI)\n     prefer 2\n     apply(cases \"a = 1\", rule_tac x = \"Suc 0\" in exI)\n      prefer 2\n      apply(cases \"a = 2\", rule_tac x = \"2\" in exI)\n       prefer 2\n       apply(cases \"a = 3\", rule_tac x = \"3\" in exI)\n        prefer 2\n        apply(cases \"a > 3\", rule_tac x = \"4\" in exI, auto simp: rec_exec.simps)\n        apply(erule_tac [!] Suc_5_induct, auto simp: rec_exec.simps)\n    done\n  have k2: \"Embranch (zip (map rec_exec ?rgs)\n    (map (\\<lambda>r args. 0 < rec_exec r args) ?rrs)) [p, r, a] = newrght p r a\"\n    apply(auto simp:Embranch.simps rec_exec.simps)\n        apply(auto simp: newrght.simps rec_newrgt3_def rec_newrgt2_def\n        rec_newrgt1_def rec_newrgt0_def rec_exec.simps\n        scan_lemma)\n    done\n  from k1 and k2 show \n    \"rec_exec (rec_embranch (zip ?rgs ?rrs)) [p, r, a] =      \n                                    newrght p r a\" by simp\nqed\n\ndeclare Entry.simps[simp del]\n\ntext \\<open>\n  The \\<open>actn\\<close> function given on page 92 of B book, which is used to \n  fetch Turing Machine intructions. \n  In \\<open>actn m q r\\<close>, \\<open>m\\<close> is the Godel coding of a Turing Machine,\n  \\<open>q\\<close> is the current state of Turing Machine, \\<open>r\\<close> is the\n  right number of Turing Machine tape.\n\\<close>\nfun actn :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> nat\"\n  where\n    \"actn m q r = (if q \\<noteq> 0 then Entry m (4*(q - 1) + 2 * scan r)\n                 else 4)\"\n\ntext \\<open>\n  \\<open>rec_actn\\<close> is the recursive function used to implement \\<open>actn\\<close>\n\\<close>\ndefinition rec_actn :: \"recf\"\n  where\n    \"rec_actn = \n  Cn 3 rec_add [Cn 3 rec_mult \n        [Cn 3 rec_entry [id 3 0, Cn 3 rec_add [Cn 3 rec_mult \n                                 [Cn 3 (constn 4) [id 3 0], \n                Cn 3 rec_minus [id 3 1, Cn 3 (constn 1) [id 3 0]]], \n                   Cn 3 rec_mult [Cn 3 (constn 2) [id 3 0],\n                      Cn 3 rec_scan [id 3 2]]]], \n            Cn 3 rec_noteq [id 3 1, Cn 3 (constn 0) [id 3 0]]], \n                             Cn 3 rec_mult [Cn 3 (constn 4) [id 3 0], \n             Cn 3 rec_eq [id 3 1, Cn 3 (constn 0) [id 3 0]]]] \"\n\ntext \\<open>\n  The correctness of \\<open>actn\\<close>.\n\\<close>\nlemma actn_lemma: \"rec_exec rec_actn [m, q, r] = actn m q r\"\n  by(auto simp: rec_actn_def rec_exec.simps entry_lemma scan_lemma)\n\nfun newstat :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> nat\"\n  where\n    \"newstat m q r = (if q \\<noteq> 0 then Entry m (4*(q - 1) + 2*scan r + 1)\n                    else 0)\"\n\ndefinition rec_newstat :: \"recf\"\n  where\n    \"rec_newstat = Cn 3 rec_add \n    [Cn 3 rec_mult [Cn 3 rec_entry [id 3 0, \n           Cn 3 rec_add [Cn 3 rec_mult [Cn 3 (constn 4) [id 3 0], \n           Cn 3 rec_minus [id 3 1, Cn 3 (constn 1) [id 3 0]]], \n           Cn 3 rec_add [Cn 3 rec_mult [Cn 3 (constn 2) [id 3 0],\n           Cn 3 rec_scan [id 3 2]], Cn 3 (constn 1) [id 3 0]]]], \n           Cn 3 rec_noteq [id 3 1, Cn 3 (constn 0) [id 3 0]]], \n           Cn 3 rec_mult [Cn 3 (constn 0) [id 3 0], \n           Cn 3 rec_eq [id 3 1, Cn 3 (constn 0) [id 3 0]]]] \"\n\nlemma newstat_lemma: \"rec_exec rec_newstat [m, q, r] = newstat m q r\"\n  by(auto simp:  rec_exec.simps entry_lemma scan_lemma rec_newstat_def)\n\ndeclare newstat.simps[simp del] actn.simps[simp del]\n\ntext\\<open>code the configuration\\<close>\n\nfun trpl :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> nat\"\n  where\n    \"trpl p q r = (Pi 0)^p * (Pi 1)^q * (Pi 2)^r\"\n\ndefinition rec_trpl :: \"recf\"\n  where\n    \"rec_trpl = Cn 3 rec_mult [Cn 3 rec_mult \n       [Cn 3 rec_power [Cn 3 (constn (Pi 0)) [id 3 0], id 3 0], \n        Cn 3 rec_power [Cn 3 (constn (Pi 1)) [id 3 0], id 3 1]],\n        Cn 3 rec_power [Cn 3 (constn (Pi 2)) [id 3 0], id 3 2]]\"\ndeclare trpl.simps[simp del]\nlemma trpl_lemma: \"rec_exec rec_trpl [p, q, r] = trpl p q r\"\n  by(auto simp: rec_trpl_def rec_exec.simps power_lemma trpl.simps)\n\ntext\\<open>left, stat, rght: decode func\\<close>\nfun left :: \"nat \\<Rightarrow> nat\"\n  where\n    \"left c = lo c (Pi 0)\"\n\nfun stat :: \"nat \\<Rightarrow> nat\"\n  where\n    \"stat c = lo c (Pi 1)\"\n\nfun rght :: \"nat \\<Rightarrow> nat\"\n  where\n    \"rght c = lo c (Pi 2)\"\n\nfun inpt :: \"nat \\<Rightarrow> nat list \\<Rightarrow> nat\"\n  where\n    \"inpt m xs = trpl 0 1 (strt xs)\"\n\nfun newconf :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\"\n  where\n    \"newconf m c = trpl (newleft (left c) (rght c) \n                        (actn m (stat c) (rght c)))\n                        (newstat m (stat c) (rght c)) \n                        (newrght (left c) (rght c) \n                              (actn m (stat c) (rght c)))\"\n\ndeclare left.simps[simp del] stat.simps[simp del] rght.simps[simp del]\n  inpt.simps[simp del] newconf.simps[simp del]\n\ndefinition rec_left :: \"recf\"\n  where\n    \"rec_left = Cn 1 rec_lo [id 1 0, constn (Pi 0)]\"\n\ndefinition rec_right :: \"recf\"\n  where\n    \"rec_right = Cn 1 rec_lo [id 1 0, constn (Pi 2)]\"\n\ndefinition rec_stat :: \"recf\"\n  where\n    \"rec_stat = Cn 1 rec_lo [id 1 0, constn (Pi 1)]\"\n\ndefinition rec_inpt :: \"nat \\<Rightarrow> recf\"\n  where\n    \"rec_inpt vl = Cn vl rec_trpl \n                  [Cn vl (constn 0) [id vl 0], \n                   Cn vl (constn 1) [id vl 0], \n                   Cn vl (rec_strt (vl - 1)) \n                        (map (\\<lambda> i. id vl (i)) [1..<vl])]\"\n\nlemma left_lemma: \"rec_exec rec_left [c] = left c\"\n  by(simp add: rec_exec.simps rec_left_def left.simps lo_lemma)\n\nlemma right_lemma: \"rec_exec rec_right [c] = rght c\"\n  by(simp add: rec_exec.simps rec_right_def rght.simps lo_lemma)\n\nlemma stat_lemma: \"rec_exec rec_stat [c] = stat c\"\n  by(simp add: rec_exec.simps rec_stat_def stat.simps lo_lemma)\n\ndeclare rec_strt.simps[simp del] strt.simps[simp del]\n\nlemma map_cons_eq: \n  \"(map ((\\<lambda>a. rec_exec a (m # xs)) \\<circ> \n    (\\<lambda>i. recf.id (Suc (length xs)) (i))) \n          [Suc 0..<Suc (length xs)])\n        = map (\\<lambda> i. xs ! (i - 1)) [Suc 0..<Suc (length xs)]\"\n  apply(rule map_ext, auto)\n   apply(auto simp: rec_exec.simps nth_append nth_Cons split: nat.split)\n  done\n\nlemma list_map_eq: \n  \"vl = length (xs::nat list) \\<Longrightarrow> map (\\<lambda> i. xs ! (i - 1))\n                                          [Suc 0..<Suc vl] = xs\"\nproof(induct vl arbitrary: xs)\n  case (Suc vl)\n  then show ?case \n    apply(subgoal_tac \"\\<exists> ys y. xs = ys @ [y]\", auto)\n  proof -\n    fix ys y\n    assume ind: \n      \"\\<And>xs. length (ys::nat list) = length (xs::nat list) \\<Longrightarrow>\n            map (\\<lambda>i. xs ! (i - Suc 0)) [Suc 0..<length xs] @\n                                [xs ! (length xs - Suc 0)] = xs\"\n      and h: \"Suc 0 \\<le> length (ys::nat list)\"\n    have \"map (\\<lambda>i. ys ! (i - Suc 0)) [Suc 0..<length ys] @ \n                                   [ys ! (length ys - Suc 0)] = ys\"\n      apply(rule_tac ind, simp)\n      done\n    moreover have \n      \"map (\\<lambda>i. (ys @ [y]) ! (i - Suc 0)) [Suc 0..<length ys]\n      = map (\\<lambda>i. ys ! (i - Suc 0)) [Suc 0..<length ys]\"\n      apply(rule map_ext)\n      using h\n      apply(auto simp: nth_append)\n      done\n    ultimately show \"map (\\<lambda>i. (ys @ [y]) ! (i - Suc 0)) \n        [Suc 0..<length ys] @ [(ys @ [y]) ! (length ys - Suc 0)] = ys\"\n      apply(simp del: map_eq_conv add: nth_append, auto)\n      using h\n      apply(simp)\n      done\n  next\n    fix vl xs\n    assume \"Suc vl = length (xs::nat list)\"\n    thus \"\\<exists>ys y. xs = ys @ [y]\"\n      apply(rule_tac x = \"butlast xs\" in exI, \n          rule_tac x = \"last xs\" in exI)\n      apply(cases \"xs \\<noteq> []\", auto)\n      done\n  qed\nqed simp\n\nlemma nonempty_listE: \n  \"Suc 0 \\<le> length xs \\<Longrightarrow> \n     (map ((\\<lambda>a. rec_exec a (m # xs)) \\<circ> \n         (\\<lambda>i. recf.id (Suc (length xs)) (i))) \n             [Suc 0..<length xs] @ [(m # xs) ! length xs]) = xs\"\n  using map_cons_eq[of m xs]\n  apply(simp del: map_eq_conv add: rec_exec.simps)\n  using list_map_eq[of \"length xs\" xs]\n  apply(simp)\n  done\n\nlemma inpt_lemma:\n  \"\\<lbrakk>Suc (length xs) = vl\\<rbrakk> \\<Longrightarrow> \n            rec_exec (rec_inpt vl) (m # xs) = inpt m xs\"\n  apply(auto simp: rec_exec.simps rec_inpt_def \n      trpl_lemma inpt.simps strt_lemma)\n   apply(subgoal_tac\n      \"(map ((\\<lambda>a. rec_exec a (m # xs)) \\<circ> \n          (\\<lambda>i. recf.id (Suc (length xs)) (i))) \n            [Suc 0..<length xs] @ [(m # xs) ! length xs]) = xs\", simp)\n   apply(auto elim:nonempty_listE, cases xs, auto)\n  done\n\ndefinition rec_newconf:: \"recf\"\n  where\n    \"rec_newconf = \n    Cn 2 rec_trpl \n        [Cn 2 rec_newleft [Cn 2 rec_left [id 2 1], \n                           Cn 2 rec_right [id 2 1], \n                           Cn 2 rec_actn [id 2 0, \n                                          Cn 2 rec_stat [id 2 1], \n                           Cn 2 rec_right [id 2 1]]],\n          Cn 2 rec_newstat [id 2 0, \n                            Cn 2 rec_stat [id 2 1], \n                            Cn 2 rec_right [id 2 1]],\n           Cn 2 rec_newrght [Cn 2 rec_left [id 2 1], \n                             Cn 2 rec_right [id 2 1], \n                             Cn 2 rec_actn [id 2 0, \n                                   Cn 2 rec_stat [id 2 1], \n                             Cn 2 rec_right [id 2 1]]]]\"\n\nlemma newconf_lemma: \"rec_exec rec_newconf [m ,c] = newconf m c\"\n  by(auto simp: rec_newconf_def rec_exec.simps \n      trpl_lemma newleft_lemma left_lemma\n      right_lemma stat_lemma newrght_lemma actn_lemma \n      newstat_lemma newconf.simps)\n\ndeclare newconf_lemma[simp]\n\ntext \\<open>\n  \\<open>conf m r k\\<close> computes the TM configuration after \\<open>k\\<close> steps of execution\n  of TM coded as \\<open>m\\<close> starting from the initial configuration where the left number equals \\<open>0\\<close>, \n  right number equals \\<open>r\\<close>. \n\\<close>\nfun conf :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> nat\"\n  where\n    \"conf m r 0 = trpl 0 (Suc 0) r\"\n  | \"conf m r (Suc t) = newconf m (conf m r t)\"\n\ndeclare conf.simps[simp del]\n\ntext \\<open>\n  \\<open>conf\\<close> is implemented by the following recursive function \\<open>rec_conf\\<close>.\n\\<close>\ndefinition rec_conf :: \"recf\"\n  where\n    \"rec_conf = Pr 2 (Cn 2 rec_trpl [Cn 2 (constn 0) [id 2 0], Cn 2 (constn (Suc 0)) [id 2 0], id 2 1])\n                  (Cn 4 rec_newconf [id 4 0, id 4 3])\"\n\nlemma conf_step: \n  \"rec_exec rec_conf [m, r, Suc t] =\n         rec_exec rec_newconf [m, rec_exec rec_conf [m, r, t]]\"\nproof -\n  have \"rec_exec rec_conf ([m, r] @ [Suc t]) = \n          rec_exec rec_newconf [m, rec_exec rec_conf [m, r, t]]\"\n    by(simp only: rec_conf_def rec_pr_Suc_simp_rewrite,\n        simp add: rec_exec.simps)\n  thus \"rec_exec rec_conf [m, r, Suc t] =\n                rec_exec rec_newconf [m, rec_exec rec_conf [m, r, t]]\"\n    by simp\nqed\n\ntext \\<open>\n  The correctness of \\<open>rec_conf\\<close>.\n\\<close>\nlemma conf_lemma: \n  \"rec_exec rec_conf [m, r, t] = conf m r t\"\n  by (induct t)\n    (auto simp add: rec_conf_def rec_exec.simps conf.simps inpt_lemma trpl_lemma)\n\ntext \\<open>\n  \\<open>NSTD c\\<close> returns true if the configureation coded by \\<open>c\\<close> is no a stardard\n  final configuration.\n\\<close>\nfun NSTD :: \"nat \\<Rightarrow> bool\"\n  where\n    \"NSTD c = (stat c \\<noteq> 0 \\<or> left c \\<noteq> 0 \\<or> \n             rght c \\<noteq> 2^(lg (rght c + 1) 2) - 1 \\<or> rght c = 0)\"\n\ntext \\<open>\n  \\<open>rec_NSTD\\<close> is the recursive function implementing \\<open>NSTD\\<close>.\n\\<close>\ndefinition rec_NSTD :: \"recf\"\n  where\n    \"rec_NSTD =\n     Cn 1 rec_disj [\n          Cn 1 rec_disj [\n             Cn 1 rec_disj \n                [Cn 1 rec_noteq [rec_stat, constn 0], \n                 Cn 1 rec_noteq [rec_left, constn 0]] , \n              Cn 1 rec_noteq [rec_right,  \n                              Cn 1 rec_minus [Cn 1 rec_power \n                                 [constn 2, Cn 1 rec_lg \n                                    [Cn 1 rec_add        \n                                     [rec_right, constn 1], \n                                            constn 2]], constn 1]]],\n               Cn 1 rec_eq [rec_right, constn 0]]\"\n\nlemma NSTD_lemma1: \"rec_exec rec_NSTD [c] = Suc 0 \\<or>\n                   rec_exec rec_NSTD [c] = 0\"\n  by(simp add: rec_exec.simps rec_NSTD_def)\n\ndeclare NSTD.simps[simp del]\nlemma NSTD_lemma2': \"(rec_exec rec_NSTD [c] = Suc 0) \\<Longrightarrow> NSTD c\"\n  apply(simp add: rec_exec.simps rec_NSTD_def stat_lemma left_lemma \n      lg_lemma right_lemma power_lemma NSTD.simps)\n  apply(auto)\n  apply(cases \"0 < left c\", simp, simp)\n  done\n\nlemma NSTD_lemma2'': \n  \"NSTD c \\<Longrightarrow> (rec_exec rec_NSTD [c] = Suc 0)\"\n  apply(simp add: rec_exec.simps rec_NSTD_def stat_lemma \n      left_lemma lg_lemma right_lemma power_lemma NSTD.simps)\n  apply(auto split: if_splits)\n  done\n\ntext \\<open>\n  The correctness of \\<open>NSTD\\<close>.\n\\<close>\nlemma NSTD_lemma2: \"(rec_exec rec_NSTD [c] = Suc 0) = NSTD c\"\n  using NSTD_lemma1\n  apply(auto intro: NSTD_lemma2' NSTD_lemma2'')\n  done\n\nfun nstd :: \"nat \\<Rightarrow> nat\"\n  where\n    \"nstd c = (if NSTD c then 1 else 0)\"\n\nlemma nstd_lemma: \"rec_exec rec_NSTD [c] = nstd c\"\n  using NSTD_lemma1\n  apply(simp add: NSTD_lemma2, auto)\n  done\n\ntext\\<open>\n  \\<open>nonstep m r t\\<close> means afer \\<open>t\\<close> steps of execution, the TM coded by \\<open>m\\<close>\n  is not at a stardard final configuration.\n\\<close>\nfun nonstop :: \"nat \\<Rightarrow> nat  \\<Rightarrow> nat \\<Rightarrow> nat\"\n  where\n    \"nonstop m r t = nstd (conf m r t)\"\n\ntext \\<open>\n  \\<open>rec_nonstop\\<close> is the recursive function implementing \\<open>nonstop\\<close>.\n\\<close>\ndefinition rec_nonstop :: \"recf\"\n  where\n    \"rec_nonstop = Cn 3 rec_NSTD [rec_conf]\"\n\ntext \\<open>\n  The correctness of \\<open>rec_nonstop\\<close>.\n\\<close>\nlemma nonstop_lemma: \n  \"rec_exec rec_nonstop [m, r, t] = nonstop m r t\"\n  apply(simp add: rec_exec.simps rec_nonstop_def nstd_lemma conf_lemma)\n  done\n\ntext\\<open>\n  \\<open>rec_halt\\<close> is the recursive function calculating the steps a TM needs to execute before\n  to reach a stardard final configuration. This recursive function is the only one\n  using \\<open>Mn\\<close> combinator. So it is the only non-primitive recursive function \n  needs to be used in the construction of the universal function \\<open>F\\<close>.\n\\<close>\n\ndefinition rec_halt :: \"recf\"\n  where\n    \"rec_halt = Mn (Suc (Suc 0)) (rec_nonstop)\"\n\ndeclare nonstop.simps[simp del]\n\ntext \\<open>\n  The lemma relates the interpreter of primitive functions with\n  the calculation relation of general recursive functions. \n\\<close>\n\ndeclare numeral_2_eq_2[simp] numeral_3_eq_3[simp]\n\nlemma primerec_rec_right_1[intro]: \"primerec rec_right (Suc 0)\"\n  by(auto simp: rec_right_def rec_lo_def Let_def;force)\n\nlemma primerec_rec_pi_helper:\n  \"\\<forall>i<Suc (Suc 0). primerec ([recf.id (Suc 0) 0, recf.id (Suc 0) 0] ! i) (Suc 0)\"\n  by fastforce\n\nlemmas primerec_rec_pi_helpers =\n  primerec_rec_pi_helper primerec_constn_1 primerec_rec_sg_1 primerec_rec_not_1 primerec_rec_conj_2\n\nlemma primrec_dummyfac:\n  \"\\<forall>i<Suc (Suc 0).\n       primerec\n        ([recf.id (Suc 0) 0,\n          Cn (Suc 0) s\n           [Cn (Suc 0) rec_dummyfac\n             [recf.id (Suc 0) 0, recf.id (Suc 0) 0]]] !\n         i)\n        (Suc 0)\"\n  by(auto simp: rec_dummyfac_def;force)\n\nlemma primerec_rec_pi_1[intro]:  \"primerec rec_pi (Suc 0)\"\n  apply(simp add: rec_pi_def rec_dummy_pi_def \n      rec_np_def rec_fac_def rec_prime_def\n      rec_Minr.simps Let_def get_fstn_args.simps\n      arity.simps\n      rec_all.simps rec_sigma.simps rec_accum.simps)\n  apply(tactic \\<open>resolve_tac @{context} [@{thm prime_cn},  @{thm prime_pr}] 1\\<close>\n      ;(simp add:primerec_rec_pi_helpers primrec_dummyfac)?)+\n  by fastforce+\n\nlemma primerec_recs[intro]:\n  \"primerec rec_trpl (Suc (Suc (Suc 0)))\"\n  \"primerec rec_newleft0 (Suc (Suc 0))\"\n  \"primerec rec_newleft1 (Suc (Suc 0))\"\n  \"primerec rec_newleft2 (Suc (Suc 0))\"\n  \"primerec rec_newleft3 (Suc (Suc 0))\"\n  \"primerec rec_newleft (Suc (Suc (Suc 0)))\"\n  \"primerec rec_left (Suc 0)\"\n  \"primerec rec_actn (Suc (Suc (Suc 0)))\"\n  \"primerec rec_stat (Suc 0)\"\n  \"primerec rec_newstat (Suc (Suc (Suc 0)))\"\n           apply(simp_all add: rec_newleft_def rec_embranch.simps rec_left_def rec_lo_def rec_entry_def\n      rec_actn_def Let_def arity.simps rec_newleft0_def rec_stat_def rec_newstat_def\n      rec_newleft1_def rec_newleft2_def rec_newleft3_def rec_trpl_def)\n           apply(tactic \\<open>resolve_tac @{context} [@{thm prime_cn}, \n    @{thm prime_id}, @{thm prime_pr}] 1\\<close>;force)+\n  done\n\nlemma primerec_rec_newrght[intro]: \"primerec rec_newrght (Suc (Suc (Suc 0)))\"\n  apply(simp add: rec_newrght_def rec_embranch.simps\n      Let_def arity.simps rec_newrgt0_def \n      rec_newrgt1_def rec_newrgt2_def rec_newrgt3_def)\n  apply(tactic \\<open>resolve_tac @{context} [@{thm prime_cn}, \n    @{thm prime_id}, @{thm prime_pr}] 1\\<close>;force)+\n  done\n\nlemma primerec_rec_newconf[intro]: \"primerec rec_newconf (Suc (Suc 0))\"\n  apply(simp add: rec_newconf_def)\n  by(tactic \\<open>resolve_tac @{context} [@{thm prime_cn}, \n    @{thm prime_id}, @{thm prime_pr}] 1\\<close>;force)\n\nlemma primerec_rec_conf[intro]: \"primerec rec_conf (Suc (Suc (Suc 0)))\"\n  apply(simp add: rec_conf_def)\n  by(tactic \\<open>resolve_tac @{context} [@{thm prime_cn}, \n    @{thm prime_id}, @{thm prime_pr}] 1\\<close>;force simp: numeral)\n\nlemma primerec_recs2[intro]:\n  \"primerec rec_lg (Suc (Suc 0))\"\n  \"primerec rec_nonstop (Suc (Suc (Suc 0)))\"\n   apply(simp_all add: rec_lg_def rec_nonstop_def rec_NSTD_def rec_stat_def\n      rec_lo_def Let_def rec_left_def rec_right_def rec_newconf_def\n      rec_newstat_def)\n  by(tactic \\<open>resolve_tac @{context} [@{thm prime_cn}, \n    @{thm prime_id}, @{thm prime_pr}] 1\\<close>;fastforce)+\n\nlemma primerec_terminate: \n  \"\\<lbrakk>primerec f x; length xs = x\\<rbrakk> \\<Longrightarrow> terminate f xs\"\nproof(induct arbitrary: xs rule: primerec.induct)\n  fix xs\n  assume \"length (xs::nat list) = Suc 0\"  thus \"terminate z xs\"\n    by(cases xs, auto intro: termi_z)\nnext\n  fix xs\n  assume \"length (xs::nat list) = Suc 0\" thus \"terminate s xs\"\n    by(cases xs, auto intro: termi_s)\nnext\n  fix n m xs\n  assume \"n < m\" \"length (xs::nat list) = m\"  thus \"terminate (id m n) xs\"\n    by(erule_tac termi_id, simp)\nnext\n  fix f k gs m n xs\n  assume ind: \"\\<forall>i<length gs. primerec (gs ! i) m \\<and> (\\<forall>x. length x = m \\<longrightarrow> terminate (gs ! i) x)\"\n    and ind2: \"\\<And> xs. length xs = k \\<Longrightarrow> terminate f xs\"\n    and h: \"primerec f k\"  \"length gs = k\" \"m = n\" \"length (xs::nat list) = m\"\n  have \"terminate f (map (\\<lambda>g. rec_exec g xs) gs)\"\n    using ind2[of \"(map (\\<lambda>g. rec_exec g xs) gs)\"] h\n    by simp\n  moreover have \"\\<forall>g\\<in>set gs. terminate g xs\"\n    using ind h\n    by(auto simp: set_conv_nth)\n  ultimately show \"terminate (Cn n f gs) xs\"\n    using h\n    by(rule_tac termi_cn, auto)\nnext\n  fix f n g m xs\n  assume ind1: \"\\<And>xs. length xs = n \\<Longrightarrow> terminate f xs\"\n    and ind2: \"\\<And>xs. length xs = Suc (Suc n) \\<Longrightarrow> terminate g xs\"\n    and h: \"primerec f n\" \" primerec g (Suc (Suc n))\" \" m = Suc n\" \"length (xs::nat list) = m\"\n  have \"\\<forall>y<last xs. terminate g (butlast xs @ [y, rec_exec (Pr n f g) (butlast xs @ [y])])\"\n    using h ind2 by(auto)\n  moreover have \"terminate f (butlast xs)\"\n    using ind1[of \"butlast xs\"] h\n    by simp\n  moreover have \"length (butlast xs) = n\"\n    using h by simp\n  ultimately have \"terminate (Pr n f g) (butlast xs @ [last xs])\"\n    by(rule_tac termi_pr, simp_all)\n  thus \"terminate (Pr n f g) xs\"\n    using h\n    by(cases \"xs = []\", auto)\nqed\n\ntext \\<open>\n  The following lemma gives the correctness of \\<open>rec_halt\\<close>.\n  It says: if \\<open>rec_halt\\<close> calculates that the TM coded by \\<open>m\\<close>\n  will reach a standard final configuration after \\<open>t\\<close> steps of execution, then it is indeed so.\n\\<close>\n\ntext \\<open>F: universal machine\\<close>\n\ntext \\<open>\n  \\<open>valu r\\<close> extracts computing result out of the right number \\<open>r\\<close>.\n\\<close>\nfun valu :: \"nat \\<Rightarrow> nat\"\n  where\n    \"valu r = (lg (r + 1) 2) - 1\"\n\ntext \\<open>\n  \\<open>rec_valu\\<close> is the recursive function implementing \\<open>valu\\<close>.\n\\<close>\ndefinition rec_valu :: \"recf\"\n  where\n    \"rec_valu = Cn 1 rec_minus [Cn 1 rec_lg [s, constn 2], constn 1]\"\n\ntext \\<open>\n  The correctness of \\<open>rec_valu\\<close>.\n\\<close>\nlemma value_lemma: \"rec_exec rec_valu [r] = valu r\"\n  by(simp add: rec_exec.simps rec_valu_def lg_lemma)\n\nlemma primerec_rec_valu_1[intro]: \"primerec rec_valu (Suc 0)\"\n  unfolding rec_valu_def\n  apply(rule prime_cn[of _ \"Suc (Suc 0)\"])\n  by auto auto\n\ndeclare valu.simps[simp del]\n\ntext \\<open>\n  The definition of the universal function \\<open>rec_F\\<close>.\n\\<close>\ndefinition rec_F :: \"recf\"\n  where\n    \"rec_F = Cn (Suc (Suc 0)) rec_valu [Cn (Suc (Suc 0)) rec_right [Cn (Suc (Suc 0))\n rec_conf ([id (Suc (Suc 0)) 0, id (Suc (Suc 0)) (Suc 0), rec_halt])]]\"\n\nlemma terminate_halt_lemma: \n  \"\\<lbrakk>rec_exec rec_nonstop ([m, r] @ [t]) = 0; \n     \\<forall>i<t. 0 < rec_exec rec_nonstop ([m, r] @ [i])\\<rbrakk> \\<Longrightarrow> terminate rec_halt [m, r]\"\n  apply(simp add: rec_halt_def)\n  apply(rule termi_mn, auto)\n  by(rule primerec_terminate; auto)+\n\n\ntext \\<open>\n  The correctness of \\<open>rec_F\\<close>, halt case.\n\\<close>\n\nlemma F_lemma: \"rec_exec rec_halt [m, r] = t \\<Longrightarrow> rec_exec rec_F [m, r] = (valu (rght (conf m r t)))\"\n  by(simp add: rec_F_def rec_exec.simps value_lemma right_lemma conf_lemma halt_lemma)\n\nlemma terminate_F_lemma: \"terminate rec_halt [m, r] \\<Longrightarrow> terminate rec_F [m, r]\"\n  apply(simp add: rec_F_def)\n  apply(rule termi_cn, auto)\n   apply(rule primerec_terminate, auto)\n  apply(rule termi_cn, auto)\n   apply(rule primerec_terminate, auto)\n  apply(rule termi_cn, auto)\n    apply(rule primerec_terminate, auto)\n   apply(rule termi_id;force)\n  apply(rule termi_id;force)\n  done\n\ntext \\<open>\n  The correctness of \\<open>rec_F\\<close>, nonhalt case.\n\\<close>\n\nsubsection \\<open>Coding function of TMs\\<close>\n\ntext \\<open>\n  The purpose of this section is to get the coding function of Turing Machine, which is \n  going to be named \\<open>code\\<close>.\n\\<close>\n\nfun bl2nat :: \"cell list \\<Rightarrow> nat \\<Rightarrow> nat\"\n  where\n    \"bl2nat [] n = 0\"\n  | \"bl2nat (Bk#bl) n = bl2nat bl (Suc n)\"\n  | \"bl2nat (Oc#bl) n = 2^n + bl2nat bl (Suc n)\"\n\nfun bl2wc :: \"cell list \\<Rightarrow> nat\"\n  where\n    \"bl2wc xs = bl2nat xs 0\"\n\nfun trpl_code :: \"config \\<Rightarrow> nat\"\n  where\n    \"trpl_code (st, l, r) = trpl (bl2wc l) st (bl2wc r)\"\n\ndeclare bl2nat.simps[simp del] bl2wc.simps[simp del]\n  trpl_code.simps[simp del]\n\nfun action_map :: \"action \\<Rightarrow> nat\"\n  where\n    \"action_map W0 = 0\"\n  | \"action_map W1 = 1\"\n  | \"action_map L = 2\"\n  | \"action_map R = 3\"\n  | \"action_map Nop = 4\"\n\nfun action_map_iff :: \"nat \\<Rightarrow> action\"\n  where\n    \"action_map_iff (0::nat) = W0\"\n  | \"action_map_iff (Suc 0) = W1\"\n  | \"action_map_iff (Suc (Suc 0)) = L\"\n  | \"action_map_iff (Suc (Suc (Suc 0))) = R\"\n  | \"action_map_iff n = Nop\"\n\nfun block_map :: \"cell \\<Rightarrow> nat\"\n  where\n    \"block_map Bk = 0\"\n  | \"block_map Oc = 1\"\n\nfun godel_code' :: \"nat list \\<Rightarrow> nat \\<Rightarrow> nat\"\n  where\n    \"godel_code' [] n = 1\"\n  | \"godel_code' (x#xs) n = (Pi n)^x * godel_code' xs (Suc n) \"\n\nfun godel_code :: \"nat list \\<Rightarrow> nat\"\n  where\n    \"godel_code xs = (let lh = length xs in \n                   2^lh * (godel_code' xs (Suc 0)))\"\n\nfun modify_tprog :: \"instr list \\<Rightarrow> nat list\"\n  where\n    \"modify_tprog [] =  []\"\n  | \"modify_tprog ((ac, ns)#nl) = action_map ac # ns # modify_tprog nl\"\n\ntext \\<open>\n  \\<open>code tp\\<close> gives the Godel coding of TM program \\<open>tp\\<close>.\n\\<close>\nfun code :: \"instr list \\<Rightarrow> nat\"\n  where \n    \"code tp = (let nl = modify_tprog tp in \n              godel_code nl)\"\n\nsubsection \\<open>Relating interperter functions to the execution of TMs\\<close>\n\nlemma bl2wc_0[simp]: \"bl2wc [] = 0\" by(simp add: bl2wc.simps bl2nat.simps)\n\nlemma fetch_action_map_4[simp]: \"\\<lbrakk>fetch tp 0 b = (nact, ns)\\<rbrakk> \\<Longrightarrow> action_map nact = 4\"\n  apply(simp add: fetch.simps)\n  done\n\nlemma Pi_gr_1[simp]: \"Pi n > Suc 0\"\nproof(induct n, auto simp: Pi.simps Np.simps)\n  fix n\n  let ?setx = \"{y. y \\<le> Suc (Pi n!) \\<and> Pi n < y \\<and> Prime y}\"\n  have \"finite ?setx\" by auto\n  moreover have \"?setx \\<noteq> {}\"\n    using prime_ex[of \"Pi n\"]\n    apply(auto)\n    done\n  ultimately show \"Suc 0 < Min ?setx\"\n    apply(simp add: Min_gr_iff)\n    apply(auto simp: Prime.simps)\n    done\nqed\n\nlemma Pi_not_0[simp]: \"Pi n > 0\"\n  using Pi_gr_1[of n]\n  by arith\n\ndeclare godel_code.simps[simp del]\n\nlemma godel_code'_nonzero[simp]: \"0 < godel_code' nl n\"\n  apply(induct nl arbitrary: n)\n   apply(auto simp: godel_code'.simps)\n  done\n\nlemma godel_code_great: \"godel_code nl > 0\"\n  apply(simp add: godel_code.simps)\n  done\n\nlemma godel_code_eq_1: \"(godel_code nl = 1) = (nl = [])\"\n  apply(auto simp: godel_code.simps)\n  done\n\nlemma godel_code_1_iff[elim]: \n  \"\\<lbrakk>i < length nl; \\<not> Suc 0 < godel_code nl\\<rbrakk> \\<Longrightarrow> nl ! i = 0\"\n  using godel_code_great[of nl] godel_code_eq_1[of nl]\n  apply(simp)\n  done\n\nlemma prime_coprime: \"\\<lbrakk>Prime x; Prime y; x\\<noteq>y\\<rbrakk> \\<Longrightarrow> coprime x y\"\nproof (simp only: Prime.simps coprime_def, auto simp: dvd_def,\n    rule_tac classical, simp)\n  fix d k ka\n  assume case_ka: \"\\<forall>u<d * ka. \\<forall>v<d * ka. u * v \\<noteq> d * ka\" \n    and case_k: \"\\<forall>u<d * k. \\<forall>v<d * k. u * v \\<noteq> d * k\"\n    and h: \"(0::nat) < d\" \"d \\<noteq> Suc 0\" \"Suc 0 < d * ka\" \n    \"ka \\<noteq> k\" \"Suc 0 < d * k\"\n  from h have \"k > Suc 0 \\<or> ka >Suc 0\"\n    by (cases ka;cases k;force+)\n  from this show \"False\"\n  proof(erule_tac disjE)\n    assume  \"(Suc 0::nat) < k\"\n    hence \"k < d*k \\<and> d < d*k\"\n      using h\n      by(auto)\n    thus \"?thesis\"\n      using case_k\n      apply(erule_tac x = d in allE)\n      apply(simp)\n      apply(erule_tac x = k in allE)\n      apply(simp)\n      done\n  next\n    assume \"(Suc 0::nat) < ka\"\n    hence \"ka < d * ka \\<and> d < d*ka\"\n      using h by auto\n    thus \"?thesis\"\n      using case_ka\n      apply(erule_tac x = d in allE)\n      apply(simp)\n      apply(erule_tac x = ka in allE)\n      apply(simp)\n      done\n  qed\nqed\n\nlemma Pi_inc: \"Pi (Suc i) > Pi i\"\nproof(simp add: Pi.simps Np.simps)\n  let ?setx = \"{y. y \\<le> Suc (Pi i!) \\<and> Pi i < y \\<and> Prime y}\"\n  have \"finite ?setx\" by simp\n  moreover have \"?setx \\<noteq> {}\"\n    using prime_ex[of \"Pi i\"]\n    apply(auto)\n    done\n  ultimately show \"Pi i < Min ?setx\"\n    apply(simp)\n    done\nqed    \n\nlemma Pi_inc_gr: \"i < j \\<Longrightarrow> Pi i < Pi j\"\nproof(induct j, simp)\n  fix j\n  assume ind: \"i < j \\<Longrightarrow> Pi i < Pi j\"\n    and h: \"i < Suc j\"\n  from h show \"Pi i < Pi (Suc j)\"\n  proof(cases \"i < j\")\n    case True thus \"?thesis\"\n    proof -\n      assume \"i < j\"\n      hence \"Pi i < Pi j\" by(erule_tac ind)\n      moreover have \"Pi j < Pi (Suc j)\"\n        apply(simp add: Pi_inc)\n        done\n      ultimately show \"?thesis\"\n        by simp\n    qed\n  next\n    assume \"i < Suc j\" \"\\<not> i < j\"\n    hence \"i = j\"\n      by arith\n    thus \"Pi i < Pi (Suc j)\"\n      apply(simp add: Pi_inc)\n      done\n  qed\nqed      \n\nlemma Pi_notEq: \"i \\<noteq> j \\<Longrightarrow> Pi i \\<noteq> Pi j\"\n  apply(cases \"i < j\")\n  using Pi_inc_gr[of i j]\n   apply(simp)\n  using Pi_inc_gr[of j i]\n  apply(simp)\n  done\n\nlemma prime_2[intro]: \"Prime (Suc (Suc 0))\"\n  apply(auto simp: Prime.simps)\n  using less_2_cases by fastforce\n\nlemma Prime_Pi[intro]: \"Prime (Pi n)\"\nproof(induct n, auto simp: Pi.simps Np.simps)\n  fix n\n  let ?setx = \"{y. y \\<le> Suc (Pi n!) \\<and> Pi n < y \\<and> Prime y}\"\n  show \"Prime (Min ?setx)\"\n  proof -\n    have \"finite ?setx\" by simp\n    moreover have \"?setx \\<noteq> {}\" \n      using prime_ex[of \"Pi n\"]\n      apply(simp)\n      done\n    ultimately show \"?thesis\"\n      apply(drule_tac Min_in, simp, simp)\n      done\n  qed\nqed\n\nlemma Pi_coprime: \"i \\<noteq> j \\<Longrightarrow> coprime (Pi i) (Pi j)\"\n  using Prime_Pi[of i]\n  using Prime_Pi[of j]\n  apply(rule_tac prime_coprime, simp_all add: Pi_notEq)\n  done\n\nlemma Pi_power_coprime: \"i \\<noteq> j \\<Longrightarrow> coprime ((Pi i)^m) ((Pi j)^n)\"\n  unfolding coprime_power_right_iff coprime_power_left_iff using Pi_coprime by auto\n\nlemma coprime_dvd_mult_nat2: \"\\<lbrakk>coprime (k::nat) n; k dvd n * m\\<rbrakk> \\<Longrightarrow> k dvd m\"\n  unfolding coprime_dvd_mult_right_iff.\n\ndeclare godel_code'.simps[simp del]\n\nlemma godel_code'_butlast_last_id' :\n  \"godel_code' (ys @ [y]) (Suc j) = godel_code' ys (Suc j) * \n                                Pi (Suc (length ys + j)) ^ y\"\nproof(induct ys arbitrary: j, simp_all add: godel_code'.simps)\nqed  \n\nlemma godel_code'_butlast_last_id: \n  \"xs \\<noteq> [] \\<Longrightarrow> godel_code' xs (Suc j) = \n  godel_code' (butlast xs) (Suc j) * Pi (length xs + j)^(last xs)\"\n  apply(subgoal_tac \"\\<exists> ys y. xs = ys @ [y]\")\n   apply(erule_tac exE, erule_tac exE, simp add: \n      godel_code'_butlast_last_id')\n  apply(rule_tac x = \"butlast xs\" in exI)\n  apply(rule_tac x = \"last xs\" in exI, auto)\n  done\n\nlemma godel_code'_not0: \"godel_code' xs n \\<noteq> 0\"\n  apply(induct xs, auto simp: godel_code'.simps)\n  done\n\nlemma godel_code_append_cons: \n  \"length xs = i \\<Longrightarrow> godel_code' (xs@y#ys) (Suc 0)\n    = godel_code' xs (Suc 0) * Pi (Suc i)^y * godel_code' ys (i + 2)\"\nproof(induct \"length xs\" arbitrary: i y ys xs, simp add: godel_code'.simps,simp)\n  fix x xs i y ys\n  assume ind: \n    \"\\<And>xs i y ys. \\<lbrakk>x = i; length xs = i\\<rbrakk> \\<Longrightarrow> \n       godel_code' (xs @ y # ys) (Suc 0) \n     = godel_code' xs (Suc 0) * Pi (Suc i) ^ y * \n                             godel_code' ys (Suc (Suc i))\"\n    and h: \"Suc x = i\" \n    \"length (xs::nat list) = i\"\n  have \n    \"godel_code' (butlast xs @ last xs # ((y::nat)#ys)) (Suc 0) = \n        godel_code' (butlast xs) (Suc 0) * Pi (Suc (i - 1))^(last xs) \n              * godel_code' (y#ys) (Suc (Suc (i - 1)))\"\n    apply(rule_tac ind)\n    using h\n    by(auto)\n  moreover have \n    \"godel_code' xs (Suc 0)= godel_code' (butlast xs) (Suc 0) *\n                                                  Pi (i)^(last xs)\"\n    using godel_code'_butlast_last_id[of xs] h\n    apply(cases \"xs = []\", simp, simp)\n    done \n  moreover have \"butlast xs @ last xs # y # ys = xs @ y # ys\"\n    using h\n    apply(cases xs, auto)\n    done\n  ultimately show \n    \"godel_code' (xs @ y # ys) (Suc 0) =\n               godel_code' xs (Suc 0) * Pi (Suc i) ^ y *\n                    godel_code' ys (Suc (Suc i))\"\n    using h\n    apply(simp add: godel_code'_not0 Pi_not_0)\n    apply(simp add: godel_code'.simps)\n    done\nqed\n\nlemma Pi_coprime_pre: \n  \"length ps \\<le> i \\<Longrightarrow> coprime (Pi (Suc i)) (godel_code' ps (Suc 0))\"\nproof(induct \"length ps\" arbitrary: ps)\n  fix x ps\n  assume ind: \n    \"\\<And>ps. \\<lbrakk>x = length ps; length ps \\<le> i\\<rbrakk> \\<Longrightarrow>\n                  coprime (Pi (Suc i)) (godel_code' ps (Suc 0))\"\n    and h: \"Suc x = length ps\"\n    \"length (ps::nat list) \\<le> i\"\n  have g: \"coprime (Pi (Suc i)) (godel_code' (butlast ps) (Suc 0))\"\n    apply(rule_tac ind)\n    using h by auto\n  have k: \"godel_code' ps (Suc 0) = \n         godel_code' (butlast ps) (Suc 0) * Pi (length ps)^(last ps)\"\n    using godel_code'_butlast_last_id[of ps 0] h \n    by(cases ps, simp, simp)\n  from g have \"coprime (Pi (Suc i)) (Pi (length ps) ^ last ps)\"\n    unfolding coprime_power_right_iff using Pi_coprime h(2) by auto\n  with g have \n    \"coprime (Pi (Suc i)) (godel_code' (butlast ps) (Suc 0) *\n                                        Pi (length ps)^(last ps)) \"\n    unfolding coprime_mult_right_iff coprime_power_right_iff by auto\n\n  from this and k show \"coprime (Pi (Suc i)) (godel_code' ps (Suc 0))\"\n    by simp\nqed (auto simp add: godel_code'.simps)\n\nlemma Pi_coprime_suf: \"i < j \\<Longrightarrow> coprime (Pi i) (godel_code' ps j)\"\nproof(induct \"length ps\" arbitrary: ps)\n  fix x ps\n  assume ind: \n    \"\\<And>ps. \\<lbrakk>x = length ps; i < j\\<rbrakk> \\<Longrightarrow> \n                    coprime (Pi i) (godel_code' ps j)\"\n    and h: \"Suc x = length (ps::nat list)\" \"i < j\"\n  have g: \"coprime (Pi i) (godel_code' (butlast ps) j)\"\n    apply(rule ind) using h by auto\n  have k: \"(godel_code' ps j) = godel_code' (butlast ps) j *\n                                 Pi (length ps + j - 1)^last ps\"\n    using h godel_code'_butlast_last_id[of ps \"j - 1\"]\n    apply(cases \"ps = []\", simp, simp)\n    done\n  from g have\n    \"coprime (Pi i) (godel_code' (butlast ps) j * \n                          Pi (length ps + j - 1)^last ps)\"\n    using Pi_power_coprime[of i \"length ps + j - 1\" 1 \"last ps\"] h\n    by(auto)\n  from k and this show \"coprime (Pi i) (godel_code' ps j)\"\n    by auto\nqed (simp add: godel_code'.simps)\n\nlemma godel_finite: \n  \"finite {u. Pi (Suc i) ^ u dvd godel_code' nl (Suc 0)}\"\nproof(rule bounded_nat_set_is_finite[of _ \"godel_code' nl (Suc 0)\",rule_format],goal_cases)\n  case (1 ia)\n  then show ?case proof(cases \"ia < godel_code' nl (Suc 0)\")\n    case False\n    hence g1: \"Pi (Suc i) ^ ia dvd godel_code' nl (Suc 0)\"\n      and g2: \"\\<not> ia < godel_code' nl (Suc 0)\"\n      and \"Pi (Suc i)^ia \\<le> godel_code' nl (Suc 0)\"\n      using godel_code'_not0[of nl \"Suc 0\"] using 1 by (auto elim:dvd_imp_le)\n    moreover have \"ia < Pi (Suc i)^ia\"\n      by(rule x_less_exp[OF Pi_gr_1])\n    ultimately show ?thesis\n      using g2 by(auto)\n  qed auto\nqed\n\nlemma godel_code_in: \n  \"i < length nl \\<Longrightarrow>  nl ! i  \\<in> {u. Pi (Suc i) ^ u dvd\n                                     godel_code' nl (Suc 0)}\"\nproof -\n  assume h: \"i<length nl\"\n  hence \"godel_code' (take i nl@(nl!i)#drop (Suc i) nl) (Suc 0)\n           = godel_code' (take i nl) (Suc 0) *  Pi (Suc i)^(nl!i) *\n                               godel_code' (drop (Suc i) nl) (i + 2)\"\n    by(rule_tac godel_code_append_cons, simp)\n  moreover from h have \"take i nl @ (nl ! i) # drop (Suc i) nl = nl\"\n    using upd_conv_take_nth_drop[of i nl \"nl ! i\"]\n    by simp\n  ultimately  show \n    \"nl ! i \\<in> {u. Pi (Suc i) ^ u dvd godel_code' nl (Suc 0)}\"\n    by(simp)\nqed\n\nlemma godel_code'_get_nth:\n  \"i < length nl \\<Longrightarrow> Max {u. Pi (Suc i) ^ u dvd \n                          godel_code' nl (Suc 0)} = nl ! i\"\nproof(rule_tac Max_eqI)\n  let ?gc = \"godel_code' nl (Suc 0)\"\n  assume h: \"i < length nl\" thus \"finite {u. Pi (Suc i) ^ u dvd ?gc}\"\n    by (simp add: godel_finite)  \nnext\n  fix y\n  let ?suf =\"godel_code' (drop (Suc i) nl) (i + 2)\"\n  let ?pref = \"godel_code' (take i nl) (Suc 0)\"\n  assume h: \"i < length nl\" \n    \"y \\<in> {u. Pi (Suc i) ^ u dvd godel_code' nl (Suc 0)}\"\n  moreover hence\n    \"godel_code' (take i nl@(nl!i)#drop (Suc i) nl) (Suc 0)\n    = ?pref * Pi (Suc i)^(nl!i) * ?suf\"\n    by(rule_tac godel_code_append_cons, simp)\n  moreover from h have \"take i nl @ (nl!i) # drop (Suc i) nl = nl\"\n    using upd_conv_take_nth_drop[of i nl \"nl!i\"]\n    by simp\n  ultimately show \"y\\<le>nl!i\"\n  proof(simp)\n    let ?suf' = \"godel_code' (drop (Suc i) nl) (Suc (Suc i))\"\n    assume mult_dvd: \n      \"Pi (Suc i) ^ y dvd ?pref *  Pi (Suc i) ^ nl ! i * ?suf'\"\n    hence \"Pi (Suc i) ^ y dvd ?pref * Pi (Suc i) ^ nl ! i\"\n    proof -\n      have \"coprime (Pi (Suc i)^y) ?suf'\" by (simp add: Pi_coprime_suf)\n      thus ?thesis using coprime_dvd_mult_left_iff mult_dvd by blast\n    qed\n    hence \"Pi (Suc i) ^ y dvd Pi (Suc i) ^ nl ! i\"\n    proof(rule_tac coprime_dvd_mult_nat2)\n      have \"coprime (Pi (Suc i)^y) (?pref^Suc 0)\" using Pi_coprime_pre by simp\n      thus \"coprime (Pi (Suc i) ^ y) ?pref\" by simp\n    qed\n    hence \"Pi (Suc i) ^ y \\<le>  Pi (Suc i) ^ nl ! i \"\n      apply(rule_tac dvd_imp_le, auto)\n      done\n    thus \"y \\<le> nl ! i\"\n      apply(rule_tac power_le_imp_le_exp, auto)\n      done\n  qed\nnext\n  assume h: \"i<length nl\"\n\n  thus \"nl ! i \\<in> {u. Pi (Suc i) ^ u dvd godel_code' nl (Suc 0)}\"\n    by(rule_tac godel_code_in, simp)\nqed\n\nlemma godel_code'_set[simp]: \n  \"{u. Pi (Suc i) ^ u dvd (Suc (Suc 0)) ^ length nl * \n                                     godel_code' nl (Suc 0)} = \n    {u. Pi (Suc i) ^ u dvd  godel_code' nl (Suc 0)}\"\n  apply(rule_tac Collect_cong, auto)\n  apply(rule_tac n = \" (Suc (Suc 0)) ^ length nl\" in \n      coprime_dvd_mult_nat2)\nproof -\n  have \"Pi 0 = (2::nat)\" by(simp add: Pi.simps)\n  show \"coprime (Pi (Suc i) ^ u) ((Suc (Suc 0)) ^ length nl)\" for u\n    using Pi_coprime Pi.simps(1) by force\nqed\n\nlemma godel_code_get_nth: \n  \"i < length nl \\<Longrightarrow> \n           Max {u. Pi (Suc i) ^ u dvd godel_code nl} = nl ! i\"\n  by(simp add: godel_code.simps godel_code'_get_nth)\n\nlemma mod_dvd_simp: \"(x mod y = (0::nat)) = (y dvd x)\"\n  by(simp add: dvd_def, auto)\n\nlemma dvd_power_le: \"\\<lbrakk>a > Suc 0; a ^ y dvd a ^ l\\<rbrakk> \\<Longrightarrow> y \\<le> l\"\n  apply(cases \"y \\<le> l\", simp, simp)\n  apply(subgoal_tac \"\\<exists> d. y = l + d\", auto simp: power_add)\n  apply(rule_tac x = \"y - l\" in exI, simp)\n  done\n\n\nlemma Pi_nonzeroE[elim]: \"Pi n = 0 \\<Longrightarrow> RR\"\n  using Pi_not_0[of n] by simp\n\nlemma Pi_not_oneE[elim]: \"Pi n = Suc 0 \\<Longrightarrow> RR\"\n  using Pi_gr_1[of n] by simp\n\nlemma finite_power_dvd:\n  \"\\<lbrakk>(a::nat) > Suc 0; y \\<noteq> 0\\<rbrakk> \\<Longrightarrow> finite {u. a^u dvd y}\"\n  apply(auto simp: dvd_def simp:gr0_conv_Suc intro!:bounded_nat_set_is_finite[of _ y])\n  by (metis le_less_trans mod_less mod_mult_self1_is_0 not_le Suc_lessD less_trans_Suc\n      mult.right_neutral n_less_n_mult_m x_less_exp\n      zero_less_Suc zero_less_mult_pos)\n\nlemma conf_decode1: \"\\<lbrakk>m \\<noteq> n; m \\<noteq> k; k \\<noteq> n\\<rbrakk> \\<Longrightarrow> \n  Max {u. Pi m ^ u dvd Pi m ^ l * Pi n ^ st * Pi k ^ r} = l\"\nproof -\n  let ?setx = \"{u. Pi m ^ u dvd Pi m ^ l * Pi n ^ st * Pi k ^ r}\"\n  assume g: \"m \\<noteq> n\" \"m \\<noteq> k\" \"k \\<noteq> n\"\n  show \"Max ?setx = l\"\n  proof(rule_tac Max_eqI)\n    show \"finite ?setx\"\n      apply(rule_tac finite_power_dvd, auto)\n      done\n  next\n    fix y\n    assume h: \"y \\<in> ?setx\"\n    have \"Pi m ^ y dvd Pi m ^ l\"\n    proof -\n      have \"Pi m ^ y dvd Pi m ^ l * Pi n ^ st\"\n        using h g Pi_power_coprime\n        by (simp add: coprime_dvd_mult_left_iff)\n      thus \"Pi m^y dvd Pi m^l\" using g Pi_power_coprime coprime_dvd_mult_left_iff by blast\n    qed\n    thus \"y \\<le> (l::nat)\"\n      apply(rule_tac a = \"Pi m\" in power_le_imp_le_exp)\n       apply(simp_all)\n      apply(rule_tac dvd_power_le, auto)\n      done\n  next\n    show \"l \\<in> ?setx\" by simp\n  qed\nqed\n\nlemma left_trpl_fst[simp]: \"left (trpl l st r) = l\"\n  apply(simp add: left.simps trpl.simps lo.simps loR.simps mod_dvd_simp)\n  apply(auto simp: conf_decode1)\n   apply(cases \"Pi 0 ^ l * Pi (Suc 0) ^ st * Pi (Suc (Suc 0)) ^ r\")\n    apply(auto)\n  apply(erule_tac x = l in allE, auto)\n  done   \n\nlemma stat_trpl_snd[simp]: \"stat (trpl l st r) = st\"\n  apply(simp add: stat.simps trpl.simps lo.simps \n      loR.simps mod_dvd_simp, auto)\n    apply(subgoal_tac \"Pi 0 ^ l * Pi (Suc 0) ^ st * Pi (Suc (Suc 0)) ^ r\n               = Pi (Suc 0)^st * Pi 0 ^ l *  Pi (Suc (Suc 0)) ^ r\")\n     apply(simp (no_asm_simp) add: conf_decode1, simp)\n   apply(cases \"Pi 0 ^ l * Pi (Suc 0) ^ st * \n                                  Pi (Suc (Suc 0)) ^ r\", auto)\n  apply(erule_tac x = st in allE, auto)\n  done\n\nlemma rght_trpl_trd[simp]: \"rght (trpl l st r) = r\"\n  apply(simp add: rght.simps trpl.simps lo.simps \n      loR.simps mod_dvd_simp, auto)\n    apply(subgoal_tac \"Pi 0 ^ l * Pi (Suc 0) ^ st * Pi (Suc (Suc 0)) ^ r\n               = Pi (Suc (Suc 0))^r * Pi 0 ^ l *  Pi (Suc 0) ^ st\")\n     apply(simp (no_asm_simp) add: conf_decode1, simp)\n   apply(cases \"Pi 0 ^ l * Pi (Suc 0) ^ st * Pi (Suc (Suc 0)) ^ r\",\n      auto)\n  apply(erule_tac x = r in allE, auto)\n  done\n\nlemma max_lor:\n  \"i < length nl \\<Longrightarrow> Max {u. loR [godel_code nl, Pi (Suc i), u]} \n                   = nl ! i\"\n  apply(simp add: loR.simps godel_code_get_nth mod_dvd_simp)\n  done\n\nlemma godel_decode: \n  \"i < length nl \\<Longrightarrow> Entry (godel_code nl) i = nl ! i\"\n  apply(auto simp: Entry.simps lo.simps max_lor)\n  apply(erule_tac x = \"nl!i\" in allE)\n  using max_lor[of i nl] godel_finite[of i nl]\n  apply(simp)\n  apply(drule_tac Max_in, auto simp: loR.simps \n      godel_code.simps mod_dvd_simp)\n  using godel_code_in[of i nl]\n  apply(simp)\n  done\n\nlemma Four_Suc: \"4 = Suc (Suc (Suc (Suc 0)))\"\n  by auto\n\ndeclare numeral_2_eq_2[simp del]\n\nlemma modify_tprog_fetch_even: \n  \"\\<lbrakk>st \\<le> length tp div 2; st > 0\\<rbrakk> \\<Longrightarrow>\n  modify_tprog tp ! (4 * (st - Suc 0) ) = \n  action_map (fst (tp ! (2 * (st - Suc 0))))\"\nproof(induct st arbitrary: tp, simp)\n  fix tp st\n  assume ind: \n    \"\\<And>tp. \\<lbrakk>st \\<le> length tp div 2; 0 < st\\<rbrakk> \\<Longrightarrow> \n     modify_tprog tp ! (4 * (st - Suc 0)) =\n               action_map (fst ((tp::instr list) ! (2 * (st - Suc 0))))\"\n    and h: \"Suc st \\<le> length (tp::instr list) div 2\" \"0 < Suc st\"\n  thus \"modify_tprog tp ! (4 * (Suc st - Suc 0)) = \n          action_map (fst (tp ! (2 * (Suc st - Suc 0))))\"\n  proof(cases \"st = 0\")\n    case True thus \"?thesis\"\n      using h by(cases tp, auto)\n  next\n    case False\n    assume g: \"st \\<noteq> 0\"\n    hence \"\\<exists> aa ab ba bb tp'. tp = (aa, ab) # (ba, bb) # tp'\"\n      using h by(cases tp; cases \"tl tp\", auto)\n    from this obtain aa ab ba bb tp' where g1: \n      \"tp = (aa, ab) # (ba, bb) # tp'\" by blast\n    hence g2: \n      \"modify_tprog tp' ! (4 * (st - Suc 0)) = \n      action_map (fst ((tp'::instr list) ! (2 * (st - Suc 0))))\"\n      using h g by (auto intro:ind)\n    thus \"?thesis\"\n      using g1 g\n      by(cases st, auto simp add: Four_Suc)\n  qed\nqed\n\nlemma modify_tprog_fetch_odd: \n  \"\\<lbrakk>st \\<le> length tp div 2; st > 0\\<rbrakk> \\<Longrightarrow> \n       modify_tprog tp ! (Suc (Suc (4 * (st - Suc 0)))) = \n       action_map (fst (tp ! (Suc (2 * (st - Suc 0)))))\"\nproof(induct st arbitrary: tp, simp)\n  fix tp st\n  assume ind: \n    \"\\<And>tp. \\<lbrakk>st \\<le> length tp div 2; 0 < st\\<rbrakk> \\<Longrightarrow>  \n       modify_tprog tp ! Suc (Suc (4 * (st - Suc 0))) = \n          action_map (fst (tp ! Suc (2 * (st - Suc 0))))\"\n    and h: \"Suc st \\<le> length (tp::instr list) div 2\" \"0 < Suc st\"\n  thus \"modify_tprog tp ! Suc (Suc (4 * (Suc st - Suc 0))) \n     = action_map (fst (tp ! Suc (2 * (Suc st - Suc 0))))\"\n  proof(cases \"st = 0\")\n    case True thus \"?thesis\"\n      using h\n      apply(cases tp, force)\n      by(cases \"tl tp\", auto)\n  next\n    case False\n    assume g: \"st \\<noteq> 0\"\n    hence \"\\<exists> aa ab ba bb tp'. tp = (aa, ab) # (ba, bb) # tp'\"\n      using h\n      apply(cases tp, simp, cases \"tl tp\", simp, simp)\n      done\n    from this obtain aa ab ba bb tp' where g1: \n      \"tp = (aa, ab) # (ba, bb) # tp'\" by blast\n    hence g2: \"modify_tprog tp' ! Suc (Suc (4 * (st  - Suc 0))) = \n          action_map (fst (tp' ! Suc (2 * (st - Suc 0))))\"\n      apply(rule_tac ind)\n      using h g by auto\n    thus \"?thesis\"\n      using g1 g\n      apply(cases st, simp, simp add: Four_Suc)\n      done\n  qed\nqed    \n\nlemma modify_tprog_fetch_action:\n  \"\\<lbrakk>st \\<le> length tp div 2; st > 0; b = 1 \\<or> b = 0\\<rbrakk> \\<Longrightarrow> \n      modify_tprog tp ! (4 * (st - Suc 0) + 2* b) =\n      action_map (fst (tp ! ((2 * (st - Suc 0)) + b)))\"\n  apply(erule_tac disjE, auto elim: modify_tprog_fetch_odd\n      modify_tprog_fetch_even)\n  done \n\nlemma length_modify: \"length (modify_tprog tp) = 2 * length tp\"\n  apply(induct tp, auto)\n  done\n\ndeclare fetch.simps[simp del]\n\nlemma fetch_action_eq: \n  \"\\<lbrakk>block_map b = scan r; fetch tp st b = (nact, ns);\n   st \\<le> length tp div 2\\<rbrakk> \\<Longrightarrow> actn (code tp) st r = action_map nact\"\nproof(simp add: actn.simps, auto)\n  let ?i = \"4 * (st - Suc 0) + 2 * (r mod 2)\"\n  assume h: \"block_map b = r mod 2\" \"fetch tp st b = (nact, ns)\" \n    \"st \\<le> length tp div 2\" \"0 < st\"\n  have \"?i < length (modify_tprog tp)\"\n  proof -\n    have \"length (modify_tprog tp) = 2 * length tp\"\n      by(simp add: length_modify)\n    thus \"?thesis\"\n      using h\n      by(auto)\n  qed\n  hence \n    \"Entry (godel_code (modify_tprog tp))?i = \n                                   (modify_tprog tp) ! ?i\"\n    by(erule_tac godel_decode)\n  moreover have \n    \"modify_tprog tp ! ?i = \n            action_map (fst (tp ! (2 * (st - Suc 0) + r mod 2)))\"\n    apply(rule_tac  modify_tprog_fetch_action)\n    using h\n    by(auto)    \n  moreover have \"(fst (tp ! (2 * (st - Suc 0) + r mod 2))) = nact\"\n    using h\n    apply(cases st, simp_all add: fetch.simps nth_of.simps)\n    apply(cases b, auto simp: block_map.simps nth_of.simps fetch.simps \n        split: if_splits)\n    apply(cases \"r mod 2\", simp, simp)\n    done\n  ultimately show \n    \"Entry (godel_code (modify_tprog tp))\n                      (4 * (st - Suc 0) + 2 * (r mod 2))\n           = action_map nact\" \n    by simp\nqed\n\nlemma fetch_zero_zero[simp]: \"fetch tp 0 b = (nact, ns) \\<Longrightarrow> ns = 0\"\n  by(simp add: fetch.simps)\n\nlemma modify_tprog_fetch_state:\n  \"\\<lbrakk>st \\<le> length tp div 2; st > 0; b = 1 \\<or> b = 0\\<rbrakk> \\<Longrightarrow> \n     modify_tprog tp ! Suc (4 * (st - Suc 0) + 2 * b) =\n  (snd (tp ! (2 * (st - Suc 0) + b)))\"\nproof(induct st arbitrary: tp, simp)\n  fix st tp\n  assume ind: \n    \"\\<And>tp. \\<lbrakk>st \\<le> length tp div 2; 0 < st; b = 1 \\<or> b = 0\\<rbrakk> \\<Longrightarrow> \n    modify_tprog tp ! Suc (4 * (st - Suc 0) + 2 * b) =\n                             snd (tp ! (2 * (st - Suc 0) + b))\"\n    and h:\n    \"Suc st \\<le> length (tp::instr list) div 2\" \n    \"0 < Suc st\" \n    \"b = 1 \\<or> b = 0\"\n  show \"modify_tprog tp ! Suc (4 * (Suc st - Suc 0) + 2 * b) =\n                             snd (tp ! (2 * (Suc st - Suc 0) + b))\"\n  proof(cases \"st = 0\")\n    case True\n    thus \"?thesis\"\n      using h\n      apply(cases tp, force)\n      apply(cases \"tl tp\", auto)\n      done\n  next\n    case False\n    assume g: \"st \\<noteq> 0\"\n    hence \"\\<exists> aa ab ba bb tp'. tp = (aa, ab) # (ba, bb) # tp'\"\n      using h\n      by(cases tp, force, cases \"tl tp\", auto)\n    from this obtain aa ab ba bb tp' where g1:\n      \"tp = (aa, ab) # (ba, bb) # tp'\" by blast\n    hence g2: \n      \"modify_tprog tp' ! Suc (4 * (st - Suc 0) + 2 * b) =\n                              snd (tp' ! (2 * (st - Suc 0) + b))\"\n      apply(intro ind)\n      using h g by auto\n    thus \"?thesis\"\n      using g1 g\n      by(cases st;force)\n  qed\nqed\n\nlemma fetch_state_eq:\n  \"\\<lbrakk>block_map b = scan r; \n  fetch tp st b = (nact, ns);\n  st \\<le> length tp div 2\\<rbrakk> \\<Longrightarrow> newstat (code tp) st r = ns\"\nproof(simp add: newstat.simps, auto)\n  let ?i = \"Suc (4 * (st - Suc 0) + 2 * (r mod 2))\"\n  assume h: \"block_map b = r mod 2\" \"fetch tp st b =\n             (nact, ns)\" \"st \\<le> length tp div 2\" \"0 < st\"\n  have \"?i < length (modify_tprog tp)\"\n  proof -\n    have \"length (modify_tprog tp) = 2 * length tp\"\n      by(simp add: length_modify)\n    thus \"?thesis\"\n      using h\n      by(auto)\n  qed\n  hence \"Entry (godel_code (modify_tprog tp)) (?i) = \n                                  (modify_tprog tp) ! ?i\"\n    by(erule_tac godel_decode)\n  moreover have \n    \"modify_tprog tp ! ?i =  \n               (snd (tp ! (2 * (st - Suc 0) + r mod 2)))\"\n    apply(rule_tac  modify_tprog_fetch_state)\n    using h\n    by(auto)\n  moreover have \"(snd (tp ! (2 * (st - Suc 0) + r mod 2))) = ns\"\n    using h\n    apply(cases st, simp)\n    apply(cases b, auto simp: fetch.simps split: if_splits)\n    apply(cases \"(2 * (st - r mod 2) + r mod 2) = \n                       (2 * (st - 1) + r mod 2)\";auto)\n    by (metis diff_Suc_Suc diff_zero prod.sel(2))\n  ultimately show \"Entry (godel_code (modify_tprog tp)) (?i)\n           = ns\" \n    by simp\nqed\n\n\nlemma tpl_eqI[intro!]: \n  \"\\<lbrakk>a = a'; b = b'; c = c'\\<rbrakk> \\<Longrightarrow> trpl a b c = trpl a' b' c'\"\n  by simp\n\nlemma bl2nat_double: \"bl2nat xs (Suc n) = 2 * bl2nat xs n\"\nproof(induct xs arbitrary: n)\n  case Nil thus \"?case\"\n    by(simp add: bl2nat.simps)\nnext\n  case (Cons x xs) thus \"?case\"\n  proof -\n    assume ind: \"\\<And>n. bl2nat xs (Suc n) = 2 * bl2nat xs n \"\n    show \"bl2nat (x # xs) (Suc n) = 2 * bl2nat (x # xs) n\"\n    proof(cases x)\n      case Bk thus \"?thesis\"\n        apply(simp add: bl2nat.simps)\n        using ind[of \"Suc n\"] by simp\n    next\n      case Oc thus \"?thesis\"\n        apply(simp add: bl2nat.simps)\n        using ind[of \"Suc n\"] by simp\n    qed\n  qed\nqed\n\n\nlemma bl2wc_simps[simp]:\n  \"bl2wc (Oc # tl c) = Suc (bl2wc c) - bl2wc c mod 2 \"\n  \"bl2wc (Bk # c) = 2*bl2wc (c)\"\n  \"2 * bl2wc (tl c) = bl2wc c - bl2wc c mod 2 \"\n  \"bl2wc [Oc] = Suc 0\"\n  \"c \\<noteq> [] \\<Longrightarrow> bl2wc (tl c) = bl2wc c div 2\"\n  \"c \\<noteq> [] \\<Longrightarrow> bl2wc [hd c] = bl2wc c mod 2\"\n  \"c \\<noteq> [] \\<Longrightarrow> bl2wc (hd c # d) = 2 * bl2wc d + bl2wc c mod 2\"\n  \"2 * (bl2wc c div 2) = bl2wc c - bl2wc c mod 2\"\n  \"bl2wc (Oc # list) mod 2 = Suc 0\" \n  by(cases c;cases \"hd c\";force simp: bl2wc.simps bl2nat.simps bl2nat_double)+\n\ndeclare code.simps[simp del]\ndeclare nth_of.simps[simp del]\n\ntext \\<open>\n  The lemma relates the one step execution of TMs with the interpreter function \\<open>rec_newconf\\<close>.\n\\<close>\nlemma rec_t_eq_step: \n  \"(\\<lambda> (s, l, r). s \\<le> length tp div 2) c \\<Longrightarrow>\n  trpl_code (step0 c tp) = \n  rec_exec rec_newconf [code tp, trpl_code c]\"\nproof(cases c)\n  case (fields s l r) assume \"case c of (s, l, r) \\<Rightarrow> s \\<le> length tp div 2\"\n  with fields have \"s \\<le> length tp div 2\" by auto\n  thus ?thesis unfolding fields \n  proof(cases \"fetch tp s (read r)\",\n      simp add: newconf.simps trpl_code.simps step.simps)\n    fix a b ca aa ba\n    assume h: \"(a::nat) \\<le> length tp div 2\" \n      \"fetch tp a (read ca) = (aa, ba)\"\n    moreover hence \"actn (code tp) a (bl2wc ca) = action_map aa\"\n      apply(rule_tac b = \"read ca\" \n          in fetch_action_eq, auto)\n      apply(cases \"hd ca\";cases ca;force)\n      done\n    moreover from h have \"(newstat (code tp) a (bl2wc ca)) = ba\"\n      apply(rule_tac b = \"read ca\" \n          in fetch_state_eq, auto split: list.splits)\n      apply(cases \"hd ca\";cases ca;force)\n      done\n    ultimately show \n      \"trpl_code (ba, update aa (b, ca)) =\n          trpl (newleft (bl2wc b) (bl2wc ca) (actn (code tp) a (bl2wc ca))) \n    (newstat (code tp) a (bl2wc ca)) (newrght (bl2wc b) (bl2wc ca) (actn (code tp) a (bl2wc ca)))\"\n      apply(cases aa)\n          apply(auto simp: trpl_code.simps \n          newleft.simps newrght.simps split: action.splits)\n      done\n  qed\nqed\n\nlemma bl2nat_simps[simp]: \"bl2nat (Oc # Oc\\<up>x) 0 = (2 * 2 ^ x - Suc 0)\"\n  \"bl2nat (Bk\\<up>x) n = 0\"\n  by(induct x;force simp: bl2nat.simps bl2nat_double exp_ind)+\n\nlemma bl2nat_exp_zero[simp]: \"bl2nat (Oc\\<up>y) 0 = 2^y - Suc 0\"\nproof(induct y)\n  case (Suc y)\n  then show ?case by(cases \"(2::nat)^y\", auto)\nqed (auto simp: bl2nat.simps bl2nat_double)\n\nlemma bl2nat_cons_bk: \"bl2nat (ks @ [Bk]) 0 = bl2nat ks 0\"\nproof(induct ks)\n  case (Cons a ks)\n  then show ?case by (cases a, auto simp: bl2nat.simps bl2nat_double)\nqed (auto simp: bl2nat.simps)\n\nlemma bl2nat_cons_oc:\n  \"bl2nat (ks @ [Oc]) 0 =  bl2nat ks 0 + 2 ^ length ks\"\nproof(induct ks)\n  case (Cons a ks)\n  then show ?case \n    by(cases a, auto simp: bl2nat.simps bl2nat_double)\nqed (auto simp: bl2nat.simps)\n\nlemma bl2nat_append: \n  \"bl2nat (xs @ ys) 0 = bl2nat xs 0 + bl2nat ys (length xs) \"\nproof(induct \"length xs\" arbitrary: xs ys, simp add: bl2nat.simps)\n  fix x xs ys\n  assume ind: \n    \"\\<And>xs ys. x = length xs \\<Longrightarrow> \n             bl2nat (xs @ ys) 0 = bl2nat xs 0 + bl2nat ys (length xs)\"\n    and h: \"Suc x = length (xs::cell list)\"\n  have \"\\<exists> ks k. xs = ks @ [k]\" \n    apply(rule_tac x = \"butlast xs\" in exI,\n        rule_tac x = \"last xs\" in exI)\n    using h\n    apply(cases xs, auto)\n    done\n  from this obtain ks k where \"xs = ks @ [k]\" by blast\n  moreover hence \n    \"bl2nat (ks @ (k # ys)) 0 = bl2nat ks 0 +\n                               bl2nat (k # ys) (length ks)\"\n    apply(rule_tac ind) using h by simp\n  ultimately show \"bl2nat (xs @ ys) 0 = \n                  bl2nat xs 0 + bl2nat ys (length xs)\"\n    apply(cases k, simp_all add: bl2nat.simps)\n     apply(simp_all only: bl2nat_cons_bk bl2nat_cons_oc)\n    done\nqed\n\nlemma trpl_code_simp[simp]:\n  \"trpl_code (steps0 (Suc 0, Bk\\<up>l, <lm>) tp 0) = \n    rec_exec rec_conf [code tp, bl2wc (<lm>), 0]\"\n  apply(simp add: steps.simps rec_exec.simps conf_lemma  conf.simps \n      inpt.simps trpl_code.simps bl2wc.simps)\n  done\n\ntext \\<open>\n  The following lemma relates the multi-step interpreter function \\<open>rec_conf\\<close>\n  with the multi-step execution of TMs.\n\\<close>\nlemma state_in_range_step\n  : \"\\<lbrakk>a \\<le> length A div 2; step0 (a, b, c) A = (st, l, r); tm_wf (A,0)\\<rbrakk>\n  \\<Longrightarrow> st \\<le> length A div 2\"\n  apply(simp add: step.simps fetch.simps tm_wf.simps \n      split: if_splits list.splits)\n   apply(case_tac [!] a, auto simp: list_all_length \n      fetch.simps nth_of.simps)\n   apply(erule_tac x = \"A ! (2*nat) \" in ballE, auto)\n  apply(cases \"hd c\", auto simp: fetch.simps nth_of.simps)\n   apply(erule_tac x = \"A !(2 * nat)\" in ballE, auto)\n  apply(erule_tac x = \"A !Suc (2 * nat)\" in ballE, auto)\n  done\n\nlemma state_in_range: \"\\<lbrakk>steps0 (Suc 0, tp) A stp = (st, l, r); tm_wf (A, 0)\\<rbrakk>\n  \\<Longrightarrow> st \\<le> length A div 2\"\nproof(induct stp arbitrary: st l r)\n  case (Suc stp st l r)\n  from Suc.prems show ?case\n  proof(simp add: step_red, cases \"(steps0 (Suc 0, tp) A stp)\", simp)\n    fix a b c \n    assume h3: \"step0 (a, b, c) A = (st, l, r)\"\n      and h4: \"steps0 (Suc 0, tp) A stp = (a, b, c)\"\n    have \"a \\<le> length A div 2\" using Suc.prems h4 by (auto intro: Suc.hyps)\n    thus \"?thesis\" using h3 Suc.prems by (auto elim: state_in_range_step)\n  qed\nqed(auto simp: tm_wf.simps steps.simps)\n\nlemma rec_t_eq_steps:\n  \"tm_wf (tp,0) \\<Longrightarrow>\n  trpl_code (steps0 (Suc 0, Bk\\<up>l, <lm>) tp stp) = \n  rec_exec rec_conf [code tp, bl2wc (<lm>), stp]\"\nproof(induct stp)\n  case 0 thus \"?case\" by(simp)\nnext\n  case (Suc n) thus \"?case\"\n  proof -\n    assume ind: \n      \"tm_wf (tp,0) \\<Longrightarrow> trpl_code (steps0 (Suc 0, Bk\\<up> l, <lm>) tp n) \n      = rec_exec rec_conf [code tp, bl2wc (<lm>), n]\"\n      and h: \"tm_wf (tp, 0)\"\n    show \n      \"trpl_code (steps0 (Suc 0, Bk\\<up> l, <lm>) tp (Suc n)) =\n      rec_exec rec_conf [code tp, bl2wc (<lm>), Suc n]\"\n    proof(cases \"steps0 (Suc 0, Bk\\<up> l, <lm>) tp  n\", \n        simp only: step_red conf_lemma conf.simps)\n      fix a b c\n      assume g: \"steps0 (Suc 0, Bk\\<up> l, <lm>) tp n = (a, b, c) \"\n      hence \"conf (code tp) (bl2wc (<lm>)) n= trpl_code (a, b, c)\"\n        using ind h\n        apply(simp add: conf_lemma)\n        done\n      moreover hence \n        \"trpl_code (step0 (a, b, c) tp) = \n        rec_exec rec_newconf [code tp, trpl_code (a, b, c)]\"\n        apply(rule_tac rec_t_eq_step)\n        using h g\n        apply(simp add: state_in_range)\n        done\n      ultimately show \n        \"trpl_code (step0 (a, b, c) tp) =\n            newconf (code tp) (conf (code tp) (bl2wc (<lm>)) n)\"\n        by(simp)\n    qed\n  qed\nqed\n\nlemma bl2wc_Bk_0[simp]: \"bl2wc (Bk\\<up> m) = 0\"\n  apply(induct m)\n   apply(simp, simp)\n  done\n\n\n\nlemma lg_power: \"x > Suc 0 \\<Longrightarrow> lg (x ^ rs) x = rs\"\nproof(simp add: lg.simps, auto)\n  fix xa\n  assume h: \"Suc 0 < x\"\n  show \"Max {ya. ya \\<le> x ^ rs \\<and> lgR [x ^ rs, x, ya]} = rs\"\n    apply(rule_tac Max_eqI, simp_all add: lgR.simps)\n     apply(simp add: h)\n    using x_less_exp[of x rs] h\n    apply(simp)\n    done\nnext\n  assume \"\\<not> Suc 0 < x ^ rs\" \"Suc 0 < x\" \n  thus \"rs = 0\"\n    apply(cases \"x ^ rs\", simp, simp)\n    done\nnext\n  assume \"Suc 0 < x\" \"\\<forall>xa. \\<not> lgR [x ^ rs, x, xa]\"\n  thus \"rs = 0\"\n    apply(simp only:lgR.simps)\n    apply(erule_tac x = rs in allE, simp)\n    done\nqed    \n\ntext \\<open>\n  The following lemma relates execution of TMs with \n  the multi-step interpreter function \\<open>rec_nonstop\\<close>. Note,\n  \\<open>rec_nonstop\\<close> is constructed using \\<open>rec_conf\\<close>.\n\\<close>\n\ndeclare tm_wf.simps[simp del]\n\nlemma nonstop_t_eq: \n  \"\\<lbrakk>steps0 (Suc 0, Bk\\<up>l, <lm>) tp stp = (0, Bk\\<up> m, Oc\\<up> rs @ Bk\\<up> n); \n   tm_wf (tp, 0); \n  rs > 0\\<rbrakk> \n  \\<Longrightarrow> rec_exec rec_nonstop [code tp, bl2wc (<lm>), stp] = 0\"\nproof(simp add: nonstop_lemma nonstop.simps )\n  assume h: \"steps0 (Suc 0, Bk\\<up>l, <lm>) tp stp = (0, Bk\\<up> m, Oc\\<up> rs @ Bk\\<up> n)\"\n    and tc_t: \"tm_wf (tp, 0)\" \"rs > 0\"\n  have g: \"rec_exec rec_conf [code tp,  bl2wc (<lm>), stp] =\n                                        trpl_code (0, Bk\\<up> m, Oc\\<up> rs@Bk\\<up> n)\"\n    using rec_t_eq_steps[of tp l lm stp] tc_t h\n    by(simp)\n  thus \"\\<not> NSTD (conf (code tp) (bl2wc (<lm>)) stp)\" \n  proof(auto simp: NSTD.simps)\n    show \"stat (conf (code tp) (bl2wc (<lm>)) stp) = 0\"\n      using g\n      by(auto simp: conf_lemma trpl_code.simps)\n  next\n    show \"left (conf (code tp) (bl2wc (<lm>)) stp) = 0\"\n      using g\n      by(simp add: conf_lemma trpl_code.simps)\n  next\n    show \"rght (conf (code tp) (bl2wc (<lm>)) stp) = \n           2 ^ lg (Suc (rght (conf (code tp) (bl2wc (<lm>)) stp))) 2 - Suc 0\"\n      using g h\n    proof(simp add: conf_lemma trpl_code.simps)\n      have \"2 ^ lg (Suc (bl2wc (Oc\\<up> rs))) 2 = Suc (bl2wc (Oc\\<up> rs))\"\n        apply(simp add: bl2wc.simps lg_power)\n        done\n      thus \"bl2wc (Oc\\<up> rs) = 2 ^ lg (Suc (bl2wc (Oc\\<up> rs))) 2 - Suc 0\"\n        apply(simp)\n        done\n    qed\n  next\n    show \"0 < rght (conf (code tp) (bl2wc (<lm>)) stp)\"\n      using g h tc_t\n      apply(simp add: conf_lemma trpl_code.simps bl2wc.simps\n          bl2nat.simps)\n      apply(cases rs, simp, simp add: bl2nat.simps)\n      done\n  qed\nqed\n\nlemma actn_0_is_4[simp]: \"actn m 0 r = 4\"\n  by(simp add: actn.simps)\n\nlemma newstat_0_0[simp]: \"newstat m 0 r = 0\"\n  by(simp add: newstat.simps)\n\ndeclare step_red[simp del]\n\nlemma halt_least_step: \n  \"\\<lbrakk>steps0 (Suc 0, Bk\\<up>l, <lm>) tp stp = \n       (0, Bk\\<up> m, Oc\\<up>rs @ Bk\\<up>n); \n    tm_wf (tp, 0); \n    0<rs\\<rbrakk> \\<Longrightarrow>\n    \\<exists> stp. (nonstop (code tp) (bl2wc (<lm>)) stp = 0 \\<and>\n       (\\<forall> stp'. nonstop (code tp) (bl2wc (<lm>)) stp' = 0 \\<longrightarrow> stp \\<le> stp'))\"\nproof(induct stp)\n  case 0\n  then show ?case by (simp add: steps.simps(1))\nnext\n  case (Suc stp)\n  hence ind: \n    \"steps0 (Suc 0, Bk\\<up> l, <lm>) tp stp = (0, Bk\\<up> m, Oc\\<up> rs @ Bk\\<up> n) \\<Longrightarrow> \n    \\<exists>stp. nonstop (code tp) (bl2wc (<lm>)) stp = 0 \\<and> \n          (\\<forall>stp'. nonstop (code tp) (bl2wc (<lm>)) stp' = 0 \\<longrightarrow> stp \\<le> stp')\"\n    and h: \n    \"steps0 (Suc 0, Bk\\<up> l, <lm>) tp (Suc stp) = (0, Bk\\<up> m, Oc\\<up> rs @ Bk\\<up> n)\"\n    \"tm_wf (tp, 0::nat)\" \n    \"0 < rs\" by simp+\n  {\n    fix a b c nat\n    assume \"steps0 (Suc 0, Bk\\<up> l, <lm>) tp stp = (a, b, c)\"\n      \"a = Suc nat\"\n    hence \"\\<exists>stp. nonstop (code tp) (bl2wc (<lm>)) stp = 0 \\<and> \n      (\\<forall>stp'. nonstop (code tp) (bl2wc (<lm>)) stp' = 0 \\<longrightarrow> stp \\<le> stp')\"\n      using h\n      apply(rule_tac x = \"Suc stp\" in exI, auto)\n       apply(drule_tac  nonstop_t_eq, simp_all add: nonstop_lemma)\n    proof -\n      fix stp'\n      assume g:\"steps0 (Suc 0, Bk\\<up> l, <lm>) tp stp = (Suc nat, b, c)\" \n        \"nonstop (code tp) (bl2wc (<lm>)) stp' = 0\"\n      thus  \"Suc stp \\<le> stp'\"\n      proof(cases \"Suc stp \\<le> stp'\", simp, simp)\n        assume \"\\<not> Suc stp \\<le> stp'\"\n        hence \"stp' \\<le> stp\" by simp\n        hence \"\\<not> is_final (steps0 (Suc 0, Bk\\<up> l, <lm>) tp stp')\"\n          using g\n          apply(cases \"steps0 (Suc 0, Bk\\<up> l, <lm>) tp stp'\",auto, simp)\n          apply(subgoal_tac \"\\<exists> n. stp = stp' + n\", auto)\n           apply(cases \"fst (steps0 (Suc 0, Bk \\<up> l, <lm>) tp stp')\", simp_all add: steps.simps)\n          apply(rule_tac x = \"stp - stp'\"  in exI, simp)\n          done         \n        hence \"nonstop (code tp) (bl2wc (<lm>)) stp' = 1\"\n        proof(cases \"steps0 (Suc 0, Bk\\<up> l, <lm>) tp stp'\",\n            simp add: nonstop.simps)\n          fix a b c\n          assume k: \n            \"0 < a\" \"steps0 (Suc 0, Bk\\<up> l, <lm>) tp stp' = (a, b, c)\"\n          thus \" NSTD (conf (code tp) (bl2wc (<lm>)) stp')\"\n            using rec_t_eq_steps[of tp l lm stp'] h\n          proof(simp add: conf_lemma) \n            assume \"trpl_code (a, b, c) = conf (code tp) (bl2wc (<lm>)) stp'\"\n            moreover have \"NSTD (trpl_code (a, b, c))\"\n              using k\n              apply(auto simp: trpl_code.simps NSTD.simps)\n              done\n            ultimately show \"NSTD (conf (code tp) (bl2wc (<lm>)) stp')\" by simp\n          qed\n        qed\n        thus \"False\" using g by simp\n      qed qed\n    }\n    note [intro] = this\n    from h show \n      \"\\<exists>stp. nonstop (code tp) (bl2wc (<lm>)) stp = 0 \n    \\<and> (\\<forall>stp'. nonstop (code tp) (bl2wc (<lm>)) stp' = 0 \\<longrightarrow> stp \\<le> stp')\"\n      by(simp add: step_red, \n          cases \"steps0 (Suc 0, Bk\\<up> l, <lm>) tp stp\", simp, \n          cases \"fst (steps0 (Suc 0, Bk\\<up> l, <lm>) tp stp)\",\n          auto simp add: nonstop_t_eq intro:ind dest:nonstop_t_eq)\n  qed    \n\nlemma conf_trpl_ex: \"\\<exists> p q r. conf m (bl2wc (<lm>)) stp = trpl p q r\"\n  apply(induct stp, auto simp: conf.simps inpt.simps trpl.simps \n      newconf.simps)\n  apply(rule_tac x = 0 in exI, rule_tac x = 1 in exI, \n      rule_tac x = \"bl2wc (<lm>)\" in exI)\n  apply(simp)\n  done\n\nlemma nonstop_rgt_ex: \n  \"nonstop m (bl2wc (<lm>)) stpa = 0 \\<Longrightarrow> \\<exists> r. conf m (bl2wc (<lm>)) stpa = trpl 0 0 r\"\n  apply(auto simp: nonstop.simps NSTD.simps split: if_splits)\n  using conf_trpl_ex[of m lm stpa]\n  apply(auto)\n  done\n\nlemma max_divisors: \"x > Suc 0 \\<Longrightarrow> Max {u. x ^ u dvd x ^ r} = r\"\nproof(rule_tac Max_eqI)\n  assume \"x > Suc 0\"\n  thus \"finite {u. x ^ u dvd x ^ r}\"\n    apply(rule_tac finite_power_dvd, auto)\n    done\nnext\n  fix y \n  assume \"Suc 0 < x\" \"y \\<in> {u. x ^ u dvd x ^ r}\"\n  thus \"y \\<le> r\"\n    apply(cases \"y\\<le> r\", simp)\n    apply(subgoal_tac \"\\<exists> d. y = r + d\")\n     apply(auto simp: power_add)\n    apply(rule_tac x = \"y - r\" in exI, simp)\n    done\nnext\n  show \"r \\<in> {u. x ^ u dvd x ^ r}\" by simp\nqed  \n\nlemma lo_power:\n  assumes \"x > Suc 0\" shows \"lo (x ^ r) x = r\"\nproof -\n  have \"\\<not> Suc 0 < x ^ r \\<Longrightarrow> r = 0\" using assms\n    by (metis Suc_lessD Suc_lessI nat_power_eq_Suc_0_iff zero_less_power)\n  moreover have \"\\<forall>xa. \\<not> x ^ xa dvd x ^ r \\<Longrightarrow> r = 0\"\n    using dvd_refl assms by(cases \"x^r\";blast)\n  ultimately show ?thesis using assms\n    by(auto simp: lo.simps loR.simps mod_dvd_simp elim:max_divisors)\nqed\n\nlemma lo_rgt: \"lo (trpl 0 0 r) (Pi 2) = r\"\n  apply(simp add: trpl.simps lo_power)\n  done\n\nlemma conf_keep: \n  \"conf m lm stp = trpl 0 0 r  \\<Longrightarrow>\n  conf m lm (stp + n) = trpl 0 0 r\"\n  apply(induct n)\n   apply(auto simp: conf.simps  newconf.simps newleft.simps \n      newrght.simps rght.simps lo_rgt)\n  done\n\nlemma halt_state_keep_steps_add:\n  \"\\<lbrakk>nonstop m (bl2wc (<lm>)) stpa = 0\\<rbrakk> \\<Longrightarrow> \n  conf m (bl2wc (<lm>)) stpa = conf m (bl2wc (<lm>)) (stpa + n)\"\n  apply(drule_tac nonstop_rgt_ex, auto simp: conf_keep)\n  done\n\nlemma halt_state_keep: \n  \"\\<lbrakk>nonstop m (bl2wc (<lm>)) stpa = 0; nonstop m (bl2wc (<lm>)) stpb = 0\\<rbrakk> \\<Longrightarrow>\n  conf m (bl2wc (<lm>)) stpa = conf m (bl2wc (<lm>)) stpb\"\n  apply(cases \"stpa > stpb\")\n  using halt_state_keep_steps_add[of m lm stpb \"stpa - stpb\"] \n   apply simp\n  using halt_state_keep_steps_add[of m lm stpa \"stpb - stpa\"]\n  apply(simp)\n  done\n\ntext \\<open>\n  The correntess of \\<open>rec_F\\<close> which relates the interpreter function \\<open>rec_F\\<close> with the\n  execution of of TMs.\n\\<close>\n\nlemma terminate_halt: \n  \"\\<lbrakk>steps0 (Suc 0, Bk\\<up>l, <lm>) tp stp = (0, Bk\\<up>m, Oc\\<up>rs@Bk\\<up>n); \n    tm_wf (tp,0); 0<rs\\<rbrakk> \\<Longrightarrow> terminate rec_halt [code tp, (bl2wc (<lm>))]\"\n  by(frule_tac halt_least_step;force simp:nonstop_lemma intro:terminate_halt_lemma)\n\nlemma terminate_F: \n  \"\\<lbrakk>steps0 (Suc 0, Bk\\<up>l, <lm>) tp stp = (0, Bk\\<up>m, Oc\\<up>rs@Bk\\<up>n); \n    tm_wf (tp,0); 0<rs\\<rbrakk> \\<Longrightarrow> terminate rec_F [code tp, (bl2wc (<lm>))]\"\n  apply(drule_tac terminate_halt, simp_all)\n  apply(erule_tac terminate_F_lemma)\n  done\n\nlemma F_correct: \n  \"\\<lbrakk>steps0 (Suc 0, Bk\\<up>l, <lm>) tp stp = (0, Bk\\<up>m, Oc\\<up>rs@Bk\\<up>n); \n    tm_wf (tp,0); 0<rs\\<rbrakk>\n   \\<Longrightarrow> rec_exec rec_F [code tp, (bl2wc (<lm>))] = (rs - Suc 0)\"\n  apply(frule_tac halt_least_step, auto)\n  apply(frule_tac  nonstop_t_eq, auto simp: nonstop_lemma)\n  using rec_t_eq_steps[of tp l lm stp]\n  apply(simp add: conf_lemma)\nproof -\n  fix stpa\n  assume h: \n    \"nonstop (code tp) (bl2wc (<lm>)) stpa = 0\" \n    \"\\<forall>stp'. nonstop (code tp) (bl2wc (<lm>)) stp' = 0 \\<longrightarrow> stpa \\<le> stp'\" \n    \"nonstop (code tp) (bl2wc (<lm>)) stp = 0\" \n    \"trpl_code (0, Bk\\<up> m, Oc\\<up> rs @ Bk\\<up> n) = conf (code tp) (bl2wc (<lm>)) stp\"\n    \"steps0 (Suc 0, Bk\\<up> l, <lm>) tp stp = (0, Bk\\<up> m, Oc\\<up> rs @ Bk\\<up> n)\"\n  hence g1: \"conf (code tp) (bl2wc (<lm>)) stpa = trpl_code (0, Bk\\<up> m, Oc\\<up> rs @ Bk\\<up>n)\"\n    using halt_state_keep[of \"code tp\" lm stpa stp]\n    by(simp)\n  moreover have g2:\n    \"rec_exec rec_halt [code tp, (bl2wc (<lm>))] = stpa\"\n    using h\n    by(auto simp: rec_exec.simps rec_halt_def nonstop_lemma intro!: Least_equality)\n  show  \n    \"rec_exec rec_F [code tp, (bl2wc (<lm>))] = (rs - Suc 0)\"\n  proof -\n    have \n      \"valu (rght (conf (code tp) (bl2wc (<lm>)) stpa)) = rs - Suc 0\" \n      using g1 \n      apply(simp add: valu.simps trpl_code.simps \n          bl2wc.simps  bl2nat_append lg_power)\n      done\n    thus \"?thesis\" \n      by(simp add: rec_exec.simps F_lemma g2)\n  qed\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/Universal_Turing_Machine/UF.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8962513648201266, "lm_q2_score": 0.8354835432479661, "lm_q1q2_score": 0.7488032659207449}}
{"text": "(*  \n    Title:      Gauss_Jordan_IArrays.thy\n    Author:     Jose Divas\u00f3n <jose.divasonm at unirioja.es>\n    Author:     Jes\u00fas Aransay <jesus-maria.aransay at unirioja.es>\n*)\n\nsection\\<open>Gauss Jordan algorithm over nested IArrays\\<close>\n\ntheory Gauss_Jordan_IArrays\nimports\n  Matrix_To_IArray\n  Gauss_Jordan\nbegin\n\nsubsection\\<open>Definitions and functions to compute the Gauss-Jordan algorithm over matrices represented as nested iarrays\\<close>\n\ndefinition \"least_non_zero_position_of_vector_from_index A i = the (List.find (\\<lambda>x. A !! x \\<noteq> 0) [i..<IArray.length A])\"\ndefinition \"least_non_zero_position_of_vector A = least_non_zero_position_of_vector_from_index A 0\"\n\ndefinition vector_all_zero_from_index :: \"(nat \\<times> 'a::{zero} iarray) => bool\"\n  where \"vector_all_zero_from_index A' = (let i=fst A'; A=(snd A') in IArray.all (\\<lambda>x. A!!x = 0) (IArray [i..<(IArray.length A)]))\"\n\ndefinition Gauss_Jordan_in_ij_iarrays :: \"'a::{field} iarray iarray => nat => nat => 'a iarray iarray \"\n  where \"Gauss_Jordan_in_ij_iarrays A i j = (let n = least_non_zero_position_of_vector_from_index (column_iarray j A) i;\n  interchange_A = interchange_rows_iarray A i n; \n  A' = mult_row_iarray interchange_A i (1/interchange_A!!i!!j) \n  in IArray.of_fun (\\<lambda>s. if s = i then A' !! s else row_add_iarray A' s i (- interchange_A !! s !! j) !! s) (nrows_iarray A))\"\n\ndefinition Gauss_Jordan_column_k_iarrays :: \"(nat \\<times> 'a::{field} iarray iarray) => nat => (nat \\<times> 'a iarray iarray)\"\n  where \"Gauss_Jordan_column_k_iarrays A' k=(let A=(snd A'); i=(fst A') in \n  if ((vector_all_zero_from_index (i, (column_iarray k A)))) \\<or> i = (nrows_iarray A) then (i,A) else (Suc i, (Gauss_Jordan_in_ij_iarrays A i k)))\"\n\ndefinition Gauss_Jordan_upt_k_iarrays :: \"'a::{field} iarray iarray => nat => 'a::{field} iarray iarray\"\n  where \"Gauss_Jordan_upt_k_iarrays A k = snd (foldl Gauss_Jordan_column_k_iarrays (0,A) [0..<Suc k])\"\n\ndefinition Gauss_Jordan_iarrays :: \"'a::{field} iarray iarray => 'a::{field} iarray iarray\"\n  where \"Gauss_Jordan_iarrays A = Gauss_Jordan_upt_k_iarrays A (ncols_iarray A - 1)\"\n\n\nsubsection\\<open>Proving the equivalence between Gauss-Jordan algorithm over nested iarrays and over nested vecs (abstract matrices).\\<close>\n\nlemma vector_all_zero_from_index_eq:\nfixes A::\"'a::{zero}^'n::{mod_type}\"\nshows \"(\\<forall>m\\<ge>i. A $ m = 0) = (vector_all_zero_from_index (to_nat i, vec_to_iarray A))\"\nproof (auto simp add: vector_all_zero_from_index_def Let_def Option.is_none_def find_None_iff)\n  fix x\n  assume zero: \"\\<forall>m\\<ge>i. A $ m = 0\"\n    and x_length: \"x<length (IArray.list_of (vec_to_iarray A))\" and i_le_x: \"to_nat i \\<le> x\"\n  have x_le_card: \"x < CARD('n)\"  using x_length unfolding vec_to_iarray_def by auto\n  have i_le_from_nat_x: \"i \\<le> from_nat x\"  using from_nat_mono'[OF i_le_x x_le_card] unfolding from_nat_to_nat_id .\n  hence Axk: \"A $ (from_nat x) = 0\" using zero by simp\n  have \"vec_to_iarray A !! x = vec_to_iarray A !! to_nat (from_nat x::'n)\" unfolding to_nat_from_nat_id[OF x_le_card] ..\n  also have \"... = A $ (from_nat x)\" unfolding vec_to_iarray_nth' ..\n  also have \"... = 0\" unfolding Axk ..\n  finally show\" IArray.list_of (vec_to_iarray A) ! x = 0\"\n    unfolding IArray.sub_def .\nnext\n  fix m::'n\n  assume zero_assm: \"\\<forall>x\\<in>{mod_type_class.to_nat i..<length (IArray.list_of (vec_to_iarray A))}. IArray.list_of (vec_to_iarray A) ! x = 0\"\n   and i_le_m: \"i \\<le> m\"\n  have zero: \"\\<forall>x<length (IArray.list_of (vec_to_iarray A)). mod_type_class.to_nat i \\<le> x \\<longrightarrow> IArray.list_of (vec_to_iarray A) ! x = 0\"\n    using zero_assm by auto\n  have to_nat_i_le_m:\"to_nat i \\<le> to_nat m\" using to_nat_mono'[OF i_le_m] .\n  have m_le_length: \"to_nat m < IArray.length (vec_to_iarray A)\" unfolding vec_to_iarray_def using to_nat_less_card by auto\n  have \"A $ m = vec_to_iarray A !! (to_nat m)\" unfolding vec_to_iarray_nth' ..\n  also have \"... = 0\" using zero to_nat_i_le_m m_le_length unfolding nrows_iarray_def by (metis IArray.sub_def IArray.length_def)\n  finally show \"A $ m = 0\" .\nqed\n\nlemma matrix_vector_all_zero_from_index:\n  fixes A::\"'a::{zero}^'columns::{mod_type}^'rows::{mod_type}\"\n  shows \"(\\<forall>m\\<ge>i. A $ m $ k = 0) = (vector_all_zero_from_index (to_nat i, vec_to_iarray (column k A)))\"\n  unfolding vector_all_zero_from_index_eq[symmetric] column_def by simp\n\n\nlemma vec_to_iarray_least_non_zero_position_of_vector_from_index:\nfixes A::\"'a::{zero}^'n::{mod_type}\"\nassumes not_all_zero: \"\\<not> (vector_all_zero_from_index (to_nat i,  vec_to_iarray A))\"\nshows \"least_non_zero_position_of_vector_from_index (vec_to_iarray A) (to_nat i) = to_nat (LEAST n. A $ n \\<noteq> 0 \\<and> i \\<le> n)\"\nproof -\n  have \"\\<exists>a. List.find (\\<lambda>x. vec_to_iarray A !! x \\<noteq> 0) [to_nat i..<IArray.length (vec_to_iarray A)] = Some a\"\n    proof (rule ccontr, simp, unfold IArray.sub_def[symmetric] IArray.length_def[symmetric])\n      assume \"List.find (\\<lambda>x. (vec_to_iarray A) !! x \\<noteq> 0) [to_nat i..<IArray.length (vec_to_iarray A)] = None\"\n      hence \"\\<not> (\\<exists>x. x \\<in> set [mod_type_class.to_nat i..<IArray.length (vec_to_iarray A)] \\<and> vec_to_iarray A !! x \\<noteq> 0)\" \n        unfolding find_None_iff .\n      thus False using not_all_zero unfolding vector_all_zero_from_index_eq[symmetric]\n      by (simp del: IArray.length_def IArray.sub_def, unfold length_vec_to_iarray, metis to_nat_less_card to_nat_mono' vec_to_iarray_nth')\n     qed\n  from this obtain a where a: \"List.find (\\<lambda>x. vec_to_iarray A !! x \\<noteq> 0) [to_nat i..<IArray.length (vec_to_iarray A)] = Some a\"\n    by blast\n  from this obtain ia where \n    ia_less_length: \"ia<length [to_nat i..<IArray.length (vec_to_iarray A)]\" and\n    not_eq_zero: \"vec_to_iarray A !! ([to_nat i..<IArray.length (vec_to_iarray A)] ! ia) \\<noteq> 0\" and\n    a_eq: \"a = [to_nat i..<IArray.length (vec_to_iarray A)] ! ia\"\n    and least: \"(\\<forall>ja<ia. \\<not> vec_to_iarray A !! ([to_nat i..<IArray.length (vec_to_iarray A)] ! ja) \\<noteq> 0)\" \n    unfolding find_Some_iff by blast  \n  have not_eq_zero': \"vec_to_iarray A !! a \\<noteq> 0\" using not_eq_zero unfolding a_eq .\n  have i_less_a: \"to_nat i \\<le> a\" using  ia_less_length length_upt nth_upt a_eq by auto\n  have a_less_card: \"a<CARD('n)\" using a_eq ia_less_length unfolding vec_to_iarray_def by auto\n  have \"(LEAST n. A $ n \\<noteq> 0 \\<and> i \\<le> n) = from_nat a\"\n  proof (rule Least_equality, rule conjI)\n    show \"A $ from_nat a \\<noteq> 0\"  unfolding vec_to_iarray_nth'[symmetric] using not_eq_zero' unfolding to_nat_from_nat_id[OF a_less_card] .\n    show \"i \\<le> from_nat a\" using a_less_card from_nat_mono' from_nat_to_nat_id i_less_a by fastforce\n    fix x assume \"A $ x  \\<noteq> 0 \\<and> i \\<le> x\" hence Axj: \"A $ x \\<noteq> 0\" and i_le_x: \"i \\<le> x\" by fast+   \n    show \"from_nat a \\<le> x\"\n    proof (rule ccontr)\n      assume \"\\<not> from_nat a \\<le> x\" hence x_less_from_nat_a: \"x < from_nat a\" by simp\n      define ja where \"ja = (to_nat x) - (to_nat i)\"\n      have to_nat_x_less_card: \"to_nat x < CARD ('n)\" using bij_to_nat[where ?'a='n] unfolding bij_betw_def by fastforce\n      hence ja_less_length: \"ja < IArray.length (vec_to_iarray A)\" unfolding ja_def vec_to_iarray_def by auto\n      have \"[to_nat i..<IArray.length (vec_to_iarray A)] ! ja = to_nat i + ja\" \n      by (rule nth_upt, unfold vec_to_iarray_def,auto, metis add_diff_inverse diff_add_zero ja_def not_less_iff_gr_or_eq to_nat_less_card)\n      also have i_plus_ja: \"... = to_nat x\" unfolding ja_def by (simp add: i_le_x to_nat_mono')\n      finally have list_rw: \"[to_nat i..<IArray.length (vec_to_iarray A)] ! ja = to_nat x\" .\n      moreover have \"ja<ia\"\n      proof -\n        have \"a = to_nat i + ia\" unfolding a_eq \n          by (rule nth_upt, metis ia_less_length length_upt less_diff_conv add.commute)\n        thus ?thesis by (metis i_plus_ja add_less_cancel_right add.commute to_nat_le x_less_from_nat_a)\n      qed\n      ultimately have \"vec_to_iarray A !! (to_nat x) = 0\" using least by auto\n      hence \"A $ x = 0\" unfolding vec_to_iarray_nth' .  \n      thus False using Axj by contradiction\n    qed\n  qed\n  hence \"a = to_nat (LEAST n. A $ n \\<noteq> 0 \\<and> i \\<le> n)\" using to_nat_from_nat_id[OF a_less_card] by simp\n  thus ?thesis unfolding least_non_zero_position_of_vector_from_index_def unfolding a by simp\nqed\n\n\ncorollary vec_to_iarray_least_non_zero_position_of_vector_from_index':\nfixes A::\"'a::{zero}^'cols::{mod_type}^'rows::{mod_type}\"\nassumes not_all_zero: \"\\<not> (vector_all_zero_from_index (to_nat i, vec_to_iarray (column j A)))\"\nshows \"least_non_zero_position_of_vector_from_index (vec_to_iarray (column j A)) (to_nat i) = to_nat (LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n)\"\nunfolding vec_to_iarray_least_non_zero_position_of_vector_from_index[OF not_all_zero]\nunfolding column_def by fastforce\n\ncorollary vec_to_iarray_least_non_zero_position_of_vector_from_index'':\nfixes A::\"'a::{zero}^'cols::{mod_type}^'rows::{mod_type}\"\nassumes not_all_zero: \"\\<not> (vector_all_zero_from_index (to_nat j, vec_to_iarray (row i A)))\"\nshows \"least_non_zero_position_of_vector_from_index (vec_to_iarray (row i A)) (to_nat j) = to_nat (LEAST n. A $ i $ n \\<noteq> 0 \\<and> j \\<le> n)\"\nunfolding vec_to_iarray_least_non_zero_position_of_vector_from_index[OF not_all_zero]\nunfolding row_def by fastforce\n\n\nlemma matrix_to_iarray_Gauss_Jordan_in_ij[code_unfold]:\n  fixes A::\"'a::{field}^'columns::{mod_type}^'rows::{mod_type}\"\n  assumes not_all_zero: \"\\<not> (vector_all_zero_from_index (to_nat i, vec_to_iarray (column j A)))\"\n  shows \"matrix_to_iarray (Gauss_Jordan_in_ij A i j) = Gauss_Jordan_in_ij_iarrays (matrix_to_iarray A) (to_nat i) (to_nat j)\"\nproof (unfold Gauss_Jordan_in_ij_def Gauss_Jordan_in_ij_iarrays_def Let_def, rule matrix_to_iarray_eq_of_fun, auto simp del: IArray.sub_def IArray.length_def)\n  show \"vec_to_iarray (mult_row (interchange_rows A i (LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n)) i (1 / A $ (LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n) $ j) $ i) =\n    mult_row_iarray\n     (interchange_rows_iarray (matrix_to_iarray A) (to_nat i)\n       (least_non_zero_position_of_vector_from_index (column_iarray (to_nat j) (matrix_to_iarray A)) (to_nat i)))\n     (to_nat i) (1 / interchange_rows_iarray (matrix_to_iarray A) (to_nat i)\n           (least_non_zero_position_of_vector_from_index (column_iarray (to_nat j) (matrix_to_iarray A)) (to_nat i)) !! to_nat i !! to_nat j) !! to_nat i\" \n    unfolding vec_to_iarray_column[symmetric]\n    unfolding vec_to_iarray_least_non_zero_position_of_vector_from_index'[OF not_all_zero]\n    unfolding matrix_to_iarray_interchange_rows[symmetric]\n    unfolding matrix_to_iarray_mult_row[symmetric] \n    unfolding matrix_to_iarray_nth\n    unfolding interchange_rows_i\n    unfolding vec_matrix ..\nnext\n  fix ia\n  show \"vec_to_iarray\n          (row_add (mult_row (interchange_rows A i (LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n)) i (1 / A $ (LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n) $ j)) ia i\n            (- interchange_rows A i (LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n) $ ia $ j) $ ia) =\n         row_add_iarray\n          (mult_row_iarray\n            (interchange_rows_iarray (matrix_to_iarray A) (to_nat i)\n              (least_non_zero_position_of_vector_from_index (column_iarray (to_nat j) (matrix_to_iarray A)) (to_nat i)))\n            (to_nat i)\n            (1 / interchange_rows_iarray (matrix_to_iarray A) (to_nat i)\n                  (least_non_zero_position_of_vector_from_index (column_iarray (to_nat j) (matrix_to_iarray A)) (to_nat i)) !!\n                 to_nat i !! to_nat j))\n          (to_nat ia) (to_nat i)\n          (- interchange_rows_iarray (matrix_to_iarray A) (to_nat i)\n              (least_non_zero_position_of_vector_from_index (column_iarray (to_nat j) (matrix_to_iarray A)) (to_nat i)) !!\n             to_nat ia !! to_nat j) !! to_nat ia\"\n    unfolding vec_to_iarray_column[symmetric]\n    unfolding vec_to_iarray_least_non_zero_position_of_vector_from_index'[OF not_all_zero]\n    unfolding matrix_to_iarray_interchange_rows[symmetric]\n    unfolding matrix_to_iarray_mult_row[symmetric]\n    unfolding matrix_to_iarray_nth\n    unfolding interchange_rows_i\n    unfolding matrix_to_iarray_row_add[symmetric]\n    unfolding vec_matrix ..\nnext\n  show \"nrows_iarray (matrix_to_iarray A) =\n    IArray.length (matrix_to_iarray\n    (\\<chi> s. if s = i then 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) $ s\n    else row_add (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)) s i\n    (- interchange_rows A i (LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n) $ s $ j) $ s))\" \n    unfolding length_eq_card_rows nrows_eq_card_rows ..\nqed\n\n\n\nlemma matrix_to_iarray_Gauss_Jordan_column_k_1:\n  fixes A::\"'a::{field}^'columns::{mod_type}^'rows::{mod_type}\"\n  assumes k: \"k<ncols A\"\n  and i: \"i\\<le>nrows A\"\n  shows \"(fst (Gauss_Jordan_column_k (i, A) k)) = fst (Gauss_Jordan_column_k_iarrays (i, matrix_to_iarray A) k)\"\nproof (cases \"i<nrows A\")\n  case True\n  show ?thesis\n    unfolding Gauss_Jordan_column_k_def Let_def Gauss_Jordan_column_k_iarrays_def fst_conv snd_conv\n    unfolding vec_to_iarray_column[of \"from_nat k\" A, unfolded to_nat_from_nat_id[OF k[unfolded ncols_def]], symmetric]\n    using matrix_vector_all_zero_from_index[symmetric, of \"from_nat i::'rows\" \"from_nat k::'columns\"]\n    unfolding to_nat_from_nat_id[OF True[unfolded nrows_def]] to_nat_from_nat_id[OF k[unfolded ncols_def]]\n    using matrix_to_iarray_Gauss_Jordan_in_ij    \n    unfolding matrix_to_iarray_nrows snd_conv by auto\nnext\n  case False\n  have \"vector_all_zero_from_index (nrows A, column_iarray k (matrix_to_iarray A))\" unfolding vector_all_zero_from_index_def unfolding Let_def  snd_conv fst_conv\n  unfolding nrows_def column_iarray_def\n  unfolding length_eq_card_rows by (simp add: is_none_code(1))\n  thus ?thesis\n    using i False\n    unfolding Gauss_Jordan_column_k_iarrays_def Gauss_Jordan_column_k_def Let_def by auto\nqed\n\nlemma matrix_to_iarray_Gauss_Jordan_column_k_2:\n  fixes A::\"'a::{field}^'columns::{mod_type}^'rows::{mod_type}\"\n  assumes k: \"k<ncols A\"\n  and i: \"i\\<le>nrows A\"\n  shows \"matrix_to_iarray (snd (Gauss_Jordan_column_k (i, A) k)) = snd (Gauss_Jordan_column_k_iarrays (i, matrix_to_iarray A) k)\"\nproof (cases \"i<nrows A\")\n  case True show ?thesis\n    unfolding Gauss_Jordan_column_k_def Let_def Gauss_Jordan_column_k_iarrays_def fst_conv snd_conv\n    unfolding vec_to_iarray_column[of \"from_nat k\" A, unfolded to_nat_from_nat_id[OF k[unfolded ncols_def]], symmetric]\n    unfolding matrix_vector_all_zero_from_index[symmetric, of \"from_nat i::'rows\" \"from_nat k::'columns\", symmetric]\n    using matrix_to_iarray_Gauss_Jordan_in_ij[of \"from_nat i::'rows\" \"from_nat k::'columns\"]    \n    unfolding to_nat_from_nat_id[OF True[unfolded nrows_def]] to_nat_from_nat_id[OF k[unfolded ncols_def]]\n    unfolding matrix_to_iarray_nrows by auto\nnext\n  case False show ?thesis\n    using assms False unfolding Gauss_Jordan_column_k_def Let_def Gauss_Jordan_column_k_iarrays_def\n    by (auto simp add: matrix_to_iarray_nrows)  \nqed\n\n\ntext\\<open>Due to the assumptions presented in @{thm \"matrix_to_iarray_Gauss_Jordan_column_k_2\"}, the following lemma must have three shows.\nThe proof style is similar to @{thm \"rref_and_index_Gauss_Jordan_upt_k\"}.\\<close>\n\nlemma foldl_Gauss_Jordan_column_k_eq:\n  fixes A::\"'a::{field}^'columns::{mod_type}^'rows::{mod_type}\"\n  assumes k: \"k<ncols A\"\n  shows matrix_to_iarray_Gauss_Jordan_upt_k[code_unfold]: \"matrix_to_iarray (Gauss_Jordan_upt_k A k) = Gauss_Jordan_upt_k_iarrays (matrix_to_iarray A) k\"\n  and fst_foldl_Gauss_Jordan_column_k_eq: \"fst (foldl Gauss_Jordan_column_k_iarrays (0, matrix_to_iarray A) [0..<Suc k]) = fst (foldl Gauss_Jordan_column_k (0, A) [0..<Suc k])\"\n  and fst_foldl_Gauss_Jordan_column_k_less: \"fst (foldl Gauss_Jordan_column_k (0, A) [0..<Suc k]) \\<le> nrows A\"\n  using assms\nproof (induct k)\n  show \"matrix_to_iarray (Gauss_Jordan_upt_k A 0) = Gauss_Jordan_upt_k_iarrays (matrix_to_iarray A) 0\"\n    unfolding Gauss_Jordan_upt_k_def Gauss_Jordan_upt_k_iarrays_def  by (auto, metis k le0 less_nat_zero_code matrix_to_iarray_Gauss_Jordan_column_k_2 neq0_conv) \n  show \"fst (foldl Gauss_Jordan_column_k_iarrays (0, matrix_to_iarray A) [0..<Suc 0]) = fst (foldl Gauss_Jordan_column_k (0, A) [0..<Suc 0])\"\n    unfolding Gauss_Jordan_upt_k_def Gauss_Jordan_upt_k_iarrays_def by (auto, metis gr_implies_not0 k le0 matrix_to_iarray_Gauss_Jordan_column_k_1 neq0_conv) \n  show \"fst (foldl Gauss_Jordan_column_k (0, A) [0..<Suc 0]) \\<le> nrows A\" unfolding Gauss_Jordan_upt_k_def by (simp add: Gauss_Jordan_column_k_def Let_def size1 nrows_def)\nnext\n  fix k\n  assume \"(k < ncols A \\<Longrightarrow> matrix_to_iarray (Gauss_Jordan_upt_k A k) = Gauss_Jordan_upt_k_iarrays (matrix_to_iarray A) k)\" and\n    \"(k < ncols A \\<Longrightarrow> fst (foldl Gauss_Jordan_column_k_iarrays (0, matrix_to_iarray A) [0..<Suc k]) = fst (foldl Gauss_Jordan_column_k (0, A) [0..<Suc k]))\"\n    and \"(k < ncols A \\<Longrightarrow> fst (foldl Gauss_Jordan_column_k (0, A) [0..<Suc k]) \\<le> nrows A)\"\n    and Suc_k_less_card: \"Suc k < ncols A\"\n  hence hyp1: \"matrix_to_iarray (Gauss_Jordan_upt_k A k) = Gauss_Jordan_upt_k_iarrays (matrix_to_iarray A) k\"\n    and hyp2: \"fst (foldl Gauss_Jordan_column_k_iarrays (0, matrix_to_iarray A) [0..<Suc k]) = fst (foldl Gauss_Jordan_column_k (0, A) [0..<Suc k])\"\n    and hyp3: \"fst (foldl Gauss_Jordan_column_k (0, A) [0..<Suc k]) \\<le> nrows A\"\n    by auto\n  hence hyp1_unfolded: \"matrix_to_iarray (snd (foldl Gauss_Jordan_column_k (0, A) [0..<Suc k])) = snd (foldl Gauss_Jordan_column_k_iarrays (0, matrix_to_iarray A) [0..<Suc k])\" \n    using hyp1 unfolding Gauss_Jordan_upt_k_def Gauss_Jordan_upt_k_iarrays_def by simp\n  have upt_rw: \"[0..<Suc (Suc k)] = [0..<Suc k] @ [(Suc k)]\" by auto\n  have fold_rw: \"(foldl Gauss_Jordan_column_k_iarrays (0, matrix_to_iarray A) [0..<Suc k]) \n    = (fst (foldl Gauss_Jordan_column_k_iarrays (0, matrix_to_iarray A) [0..<Suc k]), snd (foldl Gauss_Jordan_column_k_iarrays (0, matrix_to_iarray A) [0..<Suc k]))\"\n    by simp\n  have fold_rw': \"(foldl Gauss_Jordan_column_k (0, A) [0..<(Suc k)]) \n    = (fst (foldl Gauss_Jordan_column_k (0, A) [0..<(Suc k)]), snd (foldl Gauss_Jordan_column_k (0, A) [0..<(Suc k)]))\" by simp\n  show \"fst (foldl Gauss_Jordan_column_k_iarrays (0, matrix_to_iarray A) [0..<Suc (Suc k)]) = fst (foldl Gauss_Jordan_column_k (0, A) [0..<Suc (Suc k)])\"\n    unfolding upt_rw foldl_append unfolding List.foldl.simps apply (subst fold_rw) apply (subst fold_rw') unfolding hyp2 unfolding hyp1_unfolded[symmetric]\n  proof (rule matrix_to_iarray_Gauss_Jordan_column_k_1[symmetric, of \"Suc k\" \"(snd (foldl Gauss_Jordan_column_k (0, A) [0..<Suc k]))\"])\n    show \"Suc k < ncols (snd (foldl Gauss_Jordan_column_k (0, A) [0..<Suc k]))\"  using Suc_k_less_card unfolding ncols_def .\n    show \" fst (foldl Gauss_Jordan_column_k (0, A) [0..<Suc k]) \\<le> nrows (snd (foldl Gauss_Jordan_column_k (0, A) [0..<Suc k]))\" using hyp3 unfolding nrows_def .\n  qed\n  show \"matrix_to_iarray (Gauss_Jordan_upt_k A (Suc k)) = Gauss_Jordan_upt_k_iarrays (matrix_to_iarray A) (Suc k)\"\n    unfolding Gauss_Jordan_upt_k_def Gauss_Jordan_upt_k_iarrays_def  upt_rw foldl_append  List.foldl.simps\n    apply (subst fold_rw) apply (subst fold_rw') unfolding hyp2 hyp1_unfolded[symmetric]\n  proof (rule matrix_to_iarray_Gauss_Jordan_column_k_2, unfold ncols_def nrows_def)\n    show \"Suc k < CARD('columns)\" using Suc_k_less_card unfolding ncols_def .\n    show \"fst (foldl Gauss_Jordan_column_k (0, A) [0..<Suc k]) \\<le> CARD('rows)\" using hyp3 unfolding nrows_def .\n  qed\n  show \"fst (foldl Gauss_Jordan_column_k (0, A) [0..<Suc (Suc k)]) \\<le> nrows A\"\n    using [[unfold_abs_def = false]]\n    unfolding upt_rw foldl_append unfolding List.foldl.simps apply (subst fold_rw')\n    unfolding Gauss_Jordan_column_k_def Let_def\n    using hyp3 le_antisym not_less_eq_eq unfolding nrows_def by fastforce\nqed\n\n\n\nlemma matrix_to_iarray_Gauss_Jordan[code_unfold]:\n  fixes A::\"'a::{field}^'columns::{mod_type}^'rows::{mod_type}\"\n  shows \"matrix_to_iarray (Gauss_Jordan A) = Gauss_Jordan_iarrays (matrix_to_iarray A)\"\n  unfolding Gauss_Jordan_iarrays_def ncols_iarray_def unfolding length_eq_card_columns\n  by (auto simp add: Gauss_Jordan_def matrix_to_iarray_Gauss_Jordan_upt_k ncols_def)\n\n\n\nsubsection\\<open>Implementation over IArrays of the computation of the @{term \"rank\"} of a matrix\\<close>\n\ndefinition rank_iarray :: \"'a::{field} iarray iarray => nat\"\n  where \"rank_iarray A = (let A' = (Gauss_Jordan_iarrays A); nrows = (IArray.length A') in card {i. i<nrows \\<and> \\<not> is_zero_iarray (A' !! i)})\"\n\nsubsubsection\\<open>Proving the equivalence between @{term \"rank\"} and @{term \"rank_iarray\"}.\\<close>\n\ntext\\<open>First of all, some code equations are removed to allow the execution of Gauss-Jordan algorithm using iarrays\\<close>\nlemmas card'_code(2)[code del]\nlemmas rank_Gauss_Jordan_code[code del]\n\n\nlemma rank_eq_card_iarrays:\n  fixes A::\"'a::{field}^'columns::{mod_type}^'rows::{mod_type}\"\n  shows \"rank A = card {vec_to_iarray (row i (Gauss_Jordan A)) |i. \\<not> is_zero_iarray (vec_to_iarray (row i (Gauss_Jordan A)))}\"\nproof (unfold rank_Gauss_Jordan_eq Let_def, rule bij_betw_same_card[of \"vec_to_iarray\"], auto simp add: bij_betw_def)\n  show \"inj_on vec_to_iarray {row i (Gauss_Jordan A) |i. row i (Gauss_Jordan A) \\<noteq> 0}\" using inj_vec_to_iarray unfolding inj_on_def by blast\n  fix i assume r: \"row i (Gauss_Jordan A) \\<noteq> 0\"\n  show \"\\<exists>ia. vec_to_iarray (row i (Gauss_Jordan A)) = vec_to_iarray (row ia (Gauss_Jordan A)) \\<and> \\<not> is_zero_iarray (vec_to_iarray (row ia (Gauss_Jordan A)))\"\n  proof (rule exI[of _ i], simp)\n    show \"\\<not> is_zero_iarray (vec_to_iarray (row i (Gauss_Jordan A)))\" using r unfolding is_zero_iarray_eq_iff .\n  qed\nnext\n  fix i\n  assume not_zero_iarray: \"\\<not> is_zero_iarray (vec_to_iarray (row i (Gauss_Jordan A)))\"\n  show \"vec_to_iarray (row i (Gauss_Jordan A)) \\<in> vec_to_iarray ` {row i (Gauss_Jordan A) |i. row i (Gauss_Jordan A) \\<noteq> 0}\"\n    by (rule imageI, auto simp add: not_zero_iarray  is_zero_iarray_eq_iff)\nqed\n\n\nlemma rank_eq_card_iarrays':\n  fixes A::\"'a::{field}^'columns::{mod_type}^'rows::{mod_type}\"\n  shows \"rank A = (let A' = (Gauss_Jordan_iarrays (matrix_to_iarray A)) in card {row_iarray (to_nat i) A' |i::'rows. \\<not> is_zero_iarray (A' !! (to_nat i))})\"\n  unfolding Let_def unfolding rank_eq_card_iarrays vec_to_iarray_row'  matrix_to_iarray_Gauss_Jordan row_iarray_def ..\n\nlemma rank_eq_card_iarrays_code:\n  fixes A::\"'a::{field}^'columns::{mod_type}^'rows::{mod_type}\"\n  shows \"rank A = (let A' = (Gauss_Jordan_iarrays (matrix_to_iarray A)) in card {i::'rows. \\<not> is_zero_iarray (A' !! (to_nat i))})\" \nproof (unfold rank_eq_card_iarrays' Let_def, rule bij_betw_same_card[symmetric, of \"\\<lambda>i. row_iarray (to_nat i) (Gauss_Jordan_iarrays (matrix_to_iarray A))\"],\n    unfold bij_betw_def inj_on_def, auto, unfold IArray.sub_def[symmetric]) \n  fix x y::'rows\n  assume x: \"\\<not> is_zero_iarray (Gauss_Jordan_iarrays (matrix_to_iarray A) !! to_nat x)\"\n    and y: \"\\<not> is_zero_iarray (Gauss_Jordan_iarrays (matrix_to_iarray A) !! to_nat y)\"\n    and eq: \"row_iarray (to_nat x) (Gauss_Jordan_iarrays (matrix_to_iarray A)) = row_iarray (to_nat y) (Gauss_Jordan_iarrays (matrix_to_iarray A))\"\n  have eq': \"(Gauss_Jordan A) $ x = (Gauss_Jordan A) $ y\" by (metis eq matrix_to_iarray_Gauss_Jordan row_iarray_def vec_matrix vec_to_iarray_morph)\n  hence not_zero_x: \"\\<not> is_zero_row x (Gauss_Jordan A)\" and not_zero_y: \"\\<not> is_zero_row y (Gauss_Jordan A)\"\n    by (metis  is_zero_iarray_eq_iff is_zero_row_def' matrix_to_iarray_Gauss_Jordan vec_eq_iff vec_matrix x zero_index)+\n  hence x_in: \"row x (Gauss_Jordan A) \\<in> {row i (Gauss_Jordan A) |i::'rows. row i (Gauss_Jordan A) \\<noteq> 0}\"\n    and y_in: \"row y (Gauss_Jordan A) \\<in> {row i (Gauss_Jordan A) |i::'rows. row i (Gauss_Jordan A) \\<noteq> 0}\"\n    by (metis (lifting, mono_tags) is_zero_iarray_eq_iff matrix_to_iarray_Gauss_Jordan mem_Collect_eq vec_to_iarray_row' x y)+\n  show \"x = y\" using inj_index_independent_rows[OF _ x_in eq'] rref_Gauss_Jordan by fast\nqed\n\nsubsubsection\\<open>Code equations for computing the rank over nested iarrays and the dimensions of the elementary subspaces\\<close>\n\nlemma rank_iarrays_code[code]:\n  \"rank_iarray A = length (filter (\\<lambda>x. \\<not> is_zero_iarray x) (IArray.list_of (Gauss_Jordan_iarrays A)))\"\nproof -\n  obtain xs where A_eq_xs: \"(Gauss_Jordan_iarrays A) = IArray xs\" by (metis iarray.exhaust)\n  have \"rank_iarray A = card {i. i<(IArray.length (Gauss_Jordan_iarrays A)) \\<and> \\<not> is_zero_iarray ((Gauss_Jordan_iarrays A) !! i)}\" unfolding rank_iarray_def Let_def ..\n  also have \"... = length (filter (\\<lambda>x. \\<not> is_zero_iarray x) (IArray.list_of (Gauss_Jordan_iarrays A)))\"\n    unfolding A_eq_xs using length_filter_conv_card[symmetric] by force\n  finally show ?thesis .\nqed\n\nlemma matrix_to_iarray_rank[code_unfold]:\n  shows \"rank A = rank_iarray (matrix_to_iarray A)\"\n  unfolding rank_eq_card_iarrays_code rank_iarray_def Let_def\n  apply (rule bij_betw_same_card[of \"to_nat\"])\n  unfolding bij_betw_def\n  apply auto\n  unfolding IArray.length_def[symmetric] IArray.sub_def[symmetric] apply (metis inj_onI to_nat_eq)\n  unfolding  matrix_to_iarray_Gauss_Jordan[symmetric] length_eq_card_rows\n  using bij_to_nat[where ?'a='c] unfolding bij_betw_def by auto\n\nlemma dim_null_space_iarray[code_unfold]:\n  fixes A::\"'a::{field}^'columns::{mod_type}^'rows::{mod_type}\"\n  shows \"vec.dim (null_space A) = ncols_iarray (matrix_to_iarray A) - rank_iarray (matrix_to_iarray A)\"\n  unfolding dim_null_space ncols_eq_card_columns matrix_to_iarray_rank dimension_vector by simp\n\nlemma dim_col_space_iarray[code_unfold]:\n  fixes A::\"'a::{field}^'columns::{mod_type}^'rows::{mod_type}\"\n  shows \"vec.dim (col_space A) = rank_iarray (matrix_to_iarray A)\"\n  unfolding rank_eq_dim_col_space[of A, symmetric]  matrix_to_iarray_rank ..\n\nlemma dim_row_space_iarray[code_unfold]:\n  fixes A::\"'a::{field}^'columns::{mod_type}^'rows::{mod_type}\"\n  shows \"vec.dim (row_space A) = rank_iarray (matrix_to_iarray A)\" \n  unfolding row_rank_def[symmetric] rank_def[symmetric] matrix_to_iarray_rank ..\n\nlemma dim_left_null_space_space_iarray[code_unfold]:\n  fixes A::\"'a::{field}^'columns::{mod_type}^'rows::{mod_type}\"\n  shows \"vec.dim (left_null_space A) = nrows_iarray (matrix_to_iarray A) - rank_iarray (matrix_to_iarray A)\"\n  unfolding dim_left_null_space nrows_eq_card_rows matrix_to_iarray_rank dimension_vector 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/Gauss_Jordan_IArrays.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8962513620489619, "lm_q2_score": 0.8354835371034369, "lm_q1q2_score": 0.7488032580984397}}
{"text": "subsection \"Algebraic Classes\"\n\ntheory Derive_Algebra_Laws\n  imports Main \"../Derive\" Derive_Datatypes\nbegin\n\ndatatype simple_int = A int | B int int | C \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 (\"\\<one>\")\n  assumes neutl : \"\\<one> \\<otimes> x = x\"   \n  \nclass group = monoidl +\n  fixes inverse :: \"'a \\<Rightarrow> 'a\"\n  assumes invl: \"(inverse x) \\<otimes> x = \\<one>\" \n\ndefinition semigroup_law :: \"('a \\<Rightarrow> 'a \\<Rightarrow> 'a) \\<Rightarrow> bool\" where\n\"semigroup_law MULT = (\\<forall> x y z. MULT (MULT x y) z = MULT x (MULT y z))\"\ndefinition monoidl_law :: \"'a \\<Rightarrow> ('a \\<Rightarrow> 'a \\<Rightarrow> 'a) \\<Rightarrow> bool\" where\n\"monoidl_law NEUTRAL MULT = ((\\<forall> x. MULT NEUTRAL x = x) \\<and> semigroup_law MULT)\"\ndefinition group_law :: \"('a \\<Rightarrow> 'a) \\<Rightarrow> 'a \\<Rightarrow> ('a \\<Rightarrow> 'a \\<Rightarrow> 'a) \\<Rightarrow> bool\" where\n\"group_law INVERSE NEUTRAL MULT = ((\\<forall> x. MULT (INVERSE x) x = NEUTRAL) \\<and> monoidl_law NEUTRAL MULT)\"\n\nlemma transfer_semigroup:\n  assumes \"Derive.iso f g\"\n  shows \"semigroup_law MULT \\<Longrightarrow> semigroup_law (\\<lambda>x y. g (MULT (f x) (f y)))\"\n  unfolding semigroup_law_def\n  using assms unfolding Derive.iso_def by simp\n\nlemma transfer_monoidl:\n  assumes \"Derive.iso f g\"\n  shows \"monoidl_law NEUTRAL MULT \\<Longrightarrow> monoidl_law (g NEUTRAL) (\\<lambda>x y. g (MULT (f x) (f y)))\"\n  unfolding monoidl_law_def semigroup_law_def \n  using assms unfolding Derive.iso_def by simp\n\nlemma transfer_group:\n  assumes \"Derive.iso f g\"\n  shows \"group_law INVERSE NEUTRAL MULT \\<Longrightarrow> group_law (\\<lambda> x. g (INVERSE (f x))) (g NEUTRAL) (\\<lambda>x y. g (MULT (f x) (f y)))\"\n  unfolding group_law_def monoidl_law_def semigroup_law_def\n  using assms unfolding Derive.iso_def by simp\n\nlemma semigroup_law_semigroup: \"semigroup_law mult\"\n  unfolding semigroup_law_def\n  using semigroup_class.axioms unfolding class.semigroup_def .\n\nlemma monoidl_law_monoidl: \"monoidl_law neutral mult\"\n  unfolding monoidl_law_def\n  using monoidl_class.axioms semigroup_law_semigroup \n  unfolding class.monoidl_axioms_def by simp\n\nlemma group_law_group: \"group_law inverse neutral mult\"\n  unfolding group_law_def\n  using group_class.axioms monoidl_law_monoidl \n  unfolding class.group_axioms_def by simp\n\nderive_generic_setup semigroup\n  unfolding semigroup_class_law_def\n  Derive.iso_def\n  by simp\n\nderive_generic_setup monoidl\n  unfolding monoidl_class_law_def semigroup_class_law_def Derive.iso_def \n  by simp\n\nderive_generic_setup group\n  unfolding group_class_law_def monoidl_class_law_def semigroup_class_law_def Derive.iso_def \n  by simp\n\n(* Manual instances for int, unit, prod, and sum *)    \ninstantiation int and unit:: semigroup\nbegin  \n  definition mult_int_def : \"mult (x::int) y = x + y\"\n  definition mult_unit_def: \"mult (x::unit) y = x\"\ninstance proof\n  fix x y z :: int\n  show \"x \\<otimes> y \\<otimes> z = x \\<otimes> (y \\<otimes> z)\"\n    unfolding mult_int_def by simp\nnext\n  fix x y z :: unit\n  show \"x \\<otimes> y \\<otimes> z = x \\<otimes> (y \\<otimes> z)\"\n    unfolding mult_unit_def by simp\nqed\nend \ninstantiation int and unit:: monoidl\nbegin  \n  definition neutral_int_def : \"neutral = (0::int)\"\n  definition neutral_unit_def: \"neutral = ()\"\ninstance proof\n  fix x :: int\n  show \"\\<one> \\<otimes> x = x\" unfolding neutral_int_def mult_int_def by simp\nnext\n  fix x :: unit\n  show \"\\<one> \\<otimes> x = x\" unfolding neutral_unit_def mult_unit_def by simp\nqed\nend   \n  \ninstantiation int and unit:: group\nbegin  \n  definition inverse_int_def : \"inverse (i::int) = \\<one> - i\"\n  definition inverse_unit_def: \"inverse u = ()\"\ninstance proof\n  fix x :: int\n  show \"inverse x \\<otimes> x = \\<one>\" unfolding inverse_int_def mult_int_def by simp\nnext\n  fix x :: unit\n  show \"inverse x \\<otimes> x = \\<one>\" unfolding inverse_unit_def mult_unit_def by simp\nqed\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> Inr b)\n                                             | Inr a \\<Rightarrow> (case y of Inl b \\<Rightarrow> Inr a | Inr b \\<Rightarrow> Inr (a \\<otimes> b)))\"\ninstance proof\n  fix x y z :: \"('a::semigroup) \\<times> ('b::semigroup)\"\n  show \"x \\<otimes> y \\<otimes> z = x \\<otimes> (y \\<otimes> z)\" unfolding mult_prod_def by (simp add: assoc)\nnext\n  fix x y z :: \"('a::semigroup) + ('b::semigroup)\"\n  show \"x \\<otimes> y \\<otimes> z = x \\<otimes> (y \\<otimes> z)\" unfolding mult_sum_def\n    by (simp add: assoc sum.case_eq_if) \nqed\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\"\ninstance proof\n  fix x :: \"('a::monoidl) \\<times> ('b::monoidl)\"\n  show \"\\<one> \\<otimes> x = x\" unfolding neutral_prod_def mult_prod_def by (simp add: neutl)\nnext\n  fix x :: \"('a::monoidl) + ('b::monoidl)\"\n  show \"\\<one> \\<otimes> x = x\" unfolding neutral_sum_def mult_sum_def\n    by (simp add: neutl sum.case_eq_if sum.exhaust_sel) \nqed\nend \n  \ninstantiation prod :: (group, group) group\nbegin\n  definition inverse_prod_def: \"inverse p = (inverse (fst p), inverse (snd p))\"\ninstance proof\n  fix x :: \"('a::group) \\<times> ('b::group)\"\n  show \"inverse x \\<otimes> x = \\<one>\" unfolding inverse_prod_def mult_prod_def neutral_prod_def\n    by (simp add: invl)\nqed\nend\n\n\nderive_generic semigroup simple_int .\nderive_generic monoidl simple_int .\n\nderive_generic semigroup either .\nderive_generic monoidl either .\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\nlemma \"(L 3) \\<otimes> ((L 4)::(int,int) either) = L 7\" by eval\nlemma \"(R (2::int)) \\<otimes> (L (3::int)) = R 2\" by eval\n\nderive_generic semigroup list\nproof goal_cases\n  case (1 x y z)\n  then show ?case\n  proof (induction x arbitrary: y z)\n    case (In x')\n    then show ?case\n      apply(cases x')\n      apply (cases y; cases z; hypsubst_thin)\n       apply (simp add: Derive_Algebra_Laws.mult_mulistF.simps sum.case_eq_if mult_unit_def)\n      apply(cases y; cases z; hypsubst_thin)\n      unfolding sum_set_defs prod_set_defs\n      apply (simp add: Derive_Algebra_Laws.mult_mulistF.simps mult_unit_def)\n      by (simp add: sum.case_eq_if assoc)\n  qed\nqed    \n\nderive_generic semigroup tree\nproof goal_cases\n  case (1 x y z)\n  then show ?case\n  proof (induction x arbitrary: y z)\n    case (In x')\n    then show ?case\n      apply(cases x')\n      apply (cases y; cases z; hypsubst_thin)\n       apply (simp add: Derive_Algebra_Laws.mult_mutreeF.simps sum.case_eq_if mult_unit_def)\n      apply(cases y; cases z; hypsubst_thin)\n      unfolding sum_set_defs prod_set_defs\n      apply (simp add: Derive_Algebra_Laws.mult_mutreeF.simps mult_unit_def)\n      by (simp add: semigroup_class.assoc sum.case_eq_if) \n  qed\nqed\n\nderive_generic monoidl list\nproof goal_cases\n  case (1 x)\n  then show ?case\n  proof (induction x)\n    case (In x')\n    then show ?case\n      apply(cases x')\n      by (auto simp add: Derive_Algebra_Laws.neutral_mulistF_def sum.case_eq_if neutral_unit_def)\n  qed\nqed\n\nderive_generic monoidl tree\nproof goal_cases\n  case (1 x)\n  then show ?case\n  proof (induction x)\n    case (In x')\n    then show ?case\n      apply(cases x')\n      by (auto simp add: Derive_Algebra_Laws.neutral_mutreeF_def sum.case_eq_if neutral_unit_def)\n  qed\nqed\n\nlemma \"[1,2,3,4::int] \\<otimes> [1,2,3] = [2,4,6,4]\" by eval\nlemma \"(Node (3::int) Leaf Leaf) \\<otimes> (Node (1::int) Leaf Leaf) = (Node 4 Leaf Leaf)\" by eval\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_Laws.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513675912912, "lm_q2_score": 0.8354835309589074, "lm_q1q2_score": 0.7488032572219216}}
{"text": "section \\<open> Bouncing Ball \\<close>\n\ntheory Bouncing_Ball\n  imports \"UTP-dL.utp_hyprog\"\nbegin\n\ntext \\<open> The goal of this theory is to show that a bouncing ball, in normal circumstances, rebounds\n  no higher than its initial height. \\<close>\n\nutp_lit_vars\n\ntext \\<open> The state space has two continuous variables, and so we use a two-place vector to model it. \\<close>\n\ntype_synonym state = \"real vec[2]\"\n\ntext \\<open> Each continuous variable is modelled as a projection from the state space. \\<close>\n\nabbreviation h :: \"real \\<Longrightarrow> state\" where \"h \\<equiv> mat_lens 0 0\"\nabbreviation v :: \"real \\<Longrightarrow> state\" where \"v \\<equiv> mat_lens 0 1\"\n\ntext \\<open> The following locale creates a context for the hybrid system, which fixes a number of\n  constants and provides assumptions. \\<close>\n\nlocale Ball =\n  fixes g :: real \\<comment> \\<open> Gravitational constant \\<close>\n  and H :: real \\<comment> \\<open> The initial or maximum height of the ball \\<close>\n  and c :: real \\<comment> \\<open> The damping coefficient applied upon rebound \\<close>\n  assumes g_pos: \"g > 0\" \\<comment> \\<open> The gravitational contant should be strictly positive (e.g. 9.81) \\<close>\n  and c_pos: \"c > 0\" \\<comment> \\<open> The damping coefficient is greater than 0... \\<close>\n  and c_le_one: \"c \\<le> 1\" \\<comment> \\<open> ... and no greater than 1, otherwise it increases its bounce. \\<close>\n  and H_pos: \"H \\<ge> 0\"\nbegin\n\ntext \\<open> The dynamics encodes the simple first order system of ODEs. It specifies the derivative\n  for each continuous variable, and a evolution domain $h \\ge 0$. \\<close>\n\nabbreviation Dynamics :: \"(state, unit) hyrel\" where\n\"Dynamics \\<equiv> ode [h \\<mapsto>\\<^sub>s v, v \\<mapsto>\\<^sub>s -g] U(&\\<^bold>c:h \\<ge> 0)\"\n\ntext \\<open> The ``controller'' implements a rebound when $h = 0$. \\<close>\n\ndefinition Control :: \"(state, unit) hyrel\" where\n\"Control \\<equiv> if (&\\<^bold>c:h = 0) then \\<^bold>c:v := -c * &\\<^bold>c:v fi\"\n\ntext \\<open> The entire system iterative executes the dynamics follows by the controller. \\<close>\n\nabbreviation \"BBall \\<equiv> (Dynamics ;; Control)\\<^sup>\\<star>\"\n\ntext \\<open> Here is the invariant we wish to prove: it is sufficient to show that always $h \\le H$. \\<close>\n\nabbreviation \"Inv \\<equiv> U(&\\<^bold>c:h \\<ge> 0 \\<and> &\\<^bold>c:v\\<^sup>2 \\<le> 2*g*(H - &\\<^bold>c:h))\"\n\ntext \\<open> We first prove that it is an invariant of the dynamics using Hoare logic. \\<close>\n\nlemma l1 [hoare_safe]: \"\\<^bold>{Inv\\<^bold>}Dynamics\\<^bold>{Inv\\<^bold>}\"\n  apply (rule dCut_split) \\<comment> \\<open> Differential cut rule \\<close>\n   apply (rule dWeakening) \\<comment> \\<open> Differential weakening (invariant first conjunct) \\<close>\n  apply (simp)\n  apply (dInduct, rel_auto) \\<comment> \\<open> Differential induction (invariant second conjunct) \\<close>\n  done\n\ntext \\<open> Next, we prove its also an invariant of the controller. This requires a call to sledgehammer. \\<close>\n\nlemma l2 [hoare_safe]: \"\\<^bold>{Inv\\<^bold>}Control\\<^bold>{Inv\\<^bold>}\"\n  unfolding Control_def\n  apply (hoare_auto)\n  by (smt c_le_one c_pos mult_left_le_one_le power2_eq_square power_mult_distrib zero_le_square)\n\ntext \\<open> As a consequence, it is an invariant of the whole system. \\<close>\n\nlemma l3: \"\\<^bold>{Inv\\<^bold>}BBall\\<^bold>{Inv\\<^bold>}\"\n  by (hoare_auto)\n\ntext \\<open> We can now show the safety property we desire using the consequence rule and sledgehammer. \\<close>\n\nlemma safety_property_1:\n  \"\\<^bold>{0 \\<le> &\\<^bold>c:h \\<and> &\\<^bold>c:v\\<^sup>2 \\<le> 2*g*(H - &\\<^bold>c:h)\\<^bold>}BBall\\<^bold>{0 \\<le> &\\<^bold>c:h \\<and> &\\<^bold>c:h \\<le> H\\<^bold>}\"\n  apply (rule hoare_r_conseq[OF l3]) \\<comment> \\<open> Consequence rule \\<close>\n  apply (simp)\n  apply (rel_simp)\n  apply (smt g_pos power2_less_0 zero_le_mult_iff)\n  done\n\ntext \\<open> A more specific version -- the ball starts stationary and at height $h$. \\<close>\n\nlemma safety_property_2:\n  \"\\<^bold>{&\\<^bold>c:h = H \\<and> &\\<^bold>c:v = 0\\<^bold>}BBall\\<^bold>{0 \\<le> &\\<^bold>c:h \\<and> &\\<^bold>c:h \\<le> H\\<^bold>}\"\n  apply (rule hoare_r_conseq[OF safety_property_1])\n  apply (rel_simp)\n  using H_pos apply blast\n  apply (rel_simp)\n  done\n\nend\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/theories/hyprog/examples/Bouncing_Ball.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9032942014971871, "lm_q2_score": 0.828938806208442, "lm_q1q2_score": 0.7487756170440861}}
{"text": "theory Chapter20_2_Typechecking\nimports Chapter20_1_Language\nbegin\n\nprimrec is_type :: \"kind env => type => bool\"\nwhere \"is_type del (Tyvar v) = (lookup del v ~= None)\"\n    | \"is_type del Nat = True\"\n    | \"is_type del (Arrow e1 e2) = (is_type del e1 & is_type del e2)\"\n    | \"is_type del (All e) = is_type (extend del Star) e\"\n    | \"is_type del Unit = True\"\n    | \"is_type del (Prod e1 e2) = (is_type del e1 & is_type del e2)\"\n    | \"is_type del Void = True\"\n    | \"is_type del (Sum e1 e2) = (is_type del e1 & is_type del e2)\"\n\ninductive typecheck :: \"kind env => type env => expr => type => bool\"\nwhere tc_var [simp]: \"lookup gam x = Some t ==> typecheck del gam (Var x) t\"\n    | tc_zero [simp]: \"typecheck del gam Zero Nat\"\n    | tc_suc [simp]: \"typecheck del gam e Nat ==> typecheck del gam (Suc e) Nat\"\n    | tc_rec [simp]: \"typecheck del gam et Nat ==> typecheck del gam e0 t ==> \n                typecheck del (extend gam t) es t ==> typecheck del gam (Iter et e0 es) t\"\n    | tc_lam [simp]: \"is_type del t1 ==> typecheck del (extend gam t1) e t2 ==> \n                typecheck del gam (Lam t1 e) (Arrow t1 t2)\"\n    | tc_appl [simp]: \"typecheck del gam e1 (Arrow t2 t) ==> typecheck del gam e2 t2 ==> \n                typecheck del gam (Appl e1 e2) t\"\n    | tc_tylam [simp]: \"typecheck (extend del Star) (env_map (type_insert first) gam) e t ==> \n                typecheck del gam (TyLam e) (All t)\"\n    | tc_tyappl [simp]: \"is_type del t' ==> typecheck del gam e (All t) ==> \n                typecheck del gam (TyAppl t' e) (type_subst t' first t)\"\n    | tc_triv [simp]: \"typecheck del gam Triv Unit\"\n    | tc_pair [simp]: \"typecheck del gam e1 t1 ==> typecheck del gam e2 t2 ==> \n                typecheck del gam (Pair e1 e2) (Prod t1 t2)\"\n    | tc_projl [simp]: \"typecheck del gam e (Prod t1 t2) ==> typecheck del gam (ProjL e) t1\"\n    | tc_projr [simp]: \"typecheck del gam e (Prod t1 t2) ==> typecheck del gam (ProjR e) t2\"\n    | tc_abort [simp]: \"is_type del t ==> typecheck del gam e Void ==> \n                typecheck del gam (Abort t e) t\"\n    | tc_case [simp]: \"typecheck del gam et (Sum t1 t2) ==> typecheck del (extend gam t1) el t ==> \n                typecheck del (extend gam t2) er t ==> typecheck del gam (Case et el er) t\"\n    | tc_inl [simp]: \"is_type del t1 ==> is_type del t2 ==> typecheck del gam e t1 ==> \n                typecheck del gam (InL t1 t2 e) (Sum t1 t2)\"\n    | tc_inr [simp]: \"is_type del t1 ==> is_type del t2 ==> typecheck del gam e t2 ==> \n                typecheck del gam (InR t1 t2 e) (Sum t1 t2)\"\n\ninductive_cases [elim!]: \"typecheck del gam (Var x) t\"\ninductive_cases [elim!]: \"typecheck del gam Zero t\"\ninductive_cases [elim!]: \"typecheck del gam (Suc e) t\"\ninductive_cases [elim!]: \"typecheck del gam (Iter et e0 es) t\"\ninductive_cases [elim!]: \"typecheck del gam (Lam t1 e) t\"\ninductive_cases [elim!]: \"typecheck del gam (Appl e1 e2) t\"\ninductive_cases [elim!]: \"typecheck del gam (TyLam e) t\"\ninductive_cases [elim!]: \"typecheck del gam (TyAppl e1 e2) t\"\ninductive_cases [elim!]: \"typecheck del gam Triv t\"\ninductive_cases [elim!]: \"typecheck del gam (Pair e1 e2) t\"\ninductive_cases [elim!]: \"typecheck del gam (ProjL e) t\"\ninductive_cases [elim!]: \"typecheck del gam (ProjR e) t\"\ninductive_cases [elim!]: \"typecheck del gam (Abort t1 e) t\"\ninductive_cases [elim!]: \"typecheck del gam (Case et el er) t\"\ninductive_cases [elim!]: \"typecheck del gam (InL t1 t2 e) t\"\ninductive_cases [elim!]: \"typecheck del gam (InR t1 t2 e) t\"\n\n\n\nlemma [simp]: \"n in del ==> is_type del t ==> is_type (extend_at n del Star) (type_insert n t)\"\nby (induction t arbitrary: n del, simp_all)\n\nlemma [simp]: \"n in del ==> is_type del t' ==> is_type (extend_at n del Star) t ==> \n                  is_type del (type_subst t' n t)\"\nby (induction t arbitrary: n del t', auto) \n\nlemma [simp]: \"typecheck del gam e t ==> n in del ==> \n          typecheck (extend_at n del Star) (env_map (type_insert n) gam) \n                    (expr_insert_type n e) (type_insert n t)\" \nproof (induction del gam e t arbitrary: n rule: typecheck.induct)\ncase tc_var\n  thus ?case by simp\nnext case tc_zero\n  thus ?case by simp\nnext case tc_suc\n  thus ?case by simp\nnext case tc_rec\n  thus ?case by simp\nnext case tc_lam\n  thus ?case by simp\nnext case tc_appl\n  thus ?case by (metis expr_insert_type.simps(6) type_insert.simps(3) typecheck.tc_appl)\nnext case tc_tylam\n  thus ?case by simp\nnext case (tc_tyappl del t' gam e t)\n  hence \"is_type (extend_at n del Star) (type_insert n t')\" by simp\n  moreover from tc_tyappl have \"typecheck (extend_at n del Star) (env_map (type_insert n) gam) \n                                          (expr_insert_type n e) (All (type_insert (next n) t))\" \n    by simp\n  ultimately have \"typecheck (extend_at n del Star) (env_map (type_insert n) gam) \n                             (TyAppl (type_insert n t') (expr_insert_type n e)) \n                             (type_subst (type_insert n t') first (type_insert (next n) t))\" \n    by (metis (full_types) typecheck.tc_tyappl)\n  thus ?case by simp\nnext case tc_triv\n  thus ?case by simp\nnext case tc_pair\n  thus ?case by simp\nnext case tc_projl\n  thus ?case by (metis expr_insert_type.simps(11) type_insert.simps(6) typecheck.tc_projl)\nnext case tc_projr\n  thus ?case by (metis expr_insert_type.simps(12) type_insert.simps(6) typecheck.tc_projr)\nnext case tc_abort\n  thus ?case by simp\nnext case (tc_case del gam et t1 t2 el t er)\n  from tc_case have X: \"typecheck (extend_at n del Star) (env_map (type_insert n) gam) \n              (expr_insert_type n et) (Sum (type_insert n t1) (type_insert n t2))\" by simp\n  from tc_case have Y: \"typecheck (extend_at n del Star) (extend (env_map (type_insert n) gam) \n              (type_insert n t1)) (expr_insert_type n el) (type_insert n t)\" by simp \n  from tc_case have \"typecheck (extend_at n del Star) (extend (env_map (type_insert n) gam) \n              (type_insert n t2)) (expr_insert_type n er) (type_insert n t)\" by simp\n  with X Y show ?case by simp\nnext case tc_inl\n  thus ?case by simp\nnext case tc_inr\n  thus ?case by simp\nqed\n\nlemma [simp]: \"typecheck del (extend_at n gam t') e t ==> n in gam ==> typecheck del gam e' t' ==> \n                   typecheck del gam (subst e' n e) t\"\nproof (induction del \"extend_at n gam t'\" e t arbitrary: n gam t' e' rule: typecheck.induct)\ncase tc_var\n  thus ?case by fastforce\nnext case tc_zero\n  thus ?case by simp\nnext case tc_suc\n  thus ?case by simp\nnext case tc_rec\n  thus ?case by simp\nnext case tc_lam\n  thus ?case by simp\nnext case tc_appl\n  thus ?case by fastforce\nnext case (tc_tylam del e t)\n  moreover hence \"n in env_map (type_insert first) gam\" by force\n  moreover from tc_tylam have \"env_map (type_insert first) (extend_at n gam t') = \n                  extend_at n (env_map (type_insert first) gam) (type_insert first t')\" by simp\n  moreover from tc_tylam have \"typecheck (extend del Star) (env_map (type_insert first) gam) \n                                         (expr_insert_type first e') (type_insert first t')\" by simp\n  ultimately have \"typecheck (extend del Star) (env_map (type_insert first) gam) \n                             (subst (expr_insert_type first e') n e) t\" by blast\n  thus ?case by simp\nnext case tc_tyappl\n  thus ?case by simp\nnext case tc_triv\n  thus ?case by simp\nnext case tc_pair\n  thus ?case by simp\nnext case tc_projl\n  thus ?case by fastforce\nnext case tc_projr\n  thus ?case by fastforce\nnext case tc_abort\n  thus ?case by simp\nnext case tc_case\n  thus ?case by fastforce\nnext case tc_inl\n  thus ?case by simp\nnext case tc_inr\n  thus ?case by simp\nqed\n\nlemma [simp]: \"typecheck (extend_at n del Star) gam e t ==> n in del ==> is_type del t' ==> \n        typecheck del (env_map (type_subst t' n) gam) (expr_subst_type t' n e) (type_subst t' n t)\" \nproof (induction \"extend_at n del Star\" gam e t arbitrary: del t' n rule: typecheck.induct)\ncase tc_var\n  thus ?case by simp\nnext case tc_zero\n  thus ?case by simp\nnext case tc_suc\n  thus ?case by simp\nnext case tc_rec\n  thus ?case by simp\nnext case tc_lam\n  thus ?case by simp\nnext case tc_appl\n  thus ?case by fastforce\nnext case tc_tylam\n  thus ?case by simp\nnext case (tc_tyappl t'' gam e t)\nnext case (tc_tyappl t'' gam e t)\n  from tc_tyappl have X: \"is_type del (type_subst t' n t'')\" by simp\n  from tc_tyappl have \"typecheck del (env_map (type_subst t' n) gam) (expr_subst_type t' n e) \n                                 (All (type_subst (type_insert first t') (next n) t))\" by simp\n  with X have \n    \"typecheck del (env_map (type_subst t' n) gam) \n          (TyAppl (type_subst t' n t'') (expr_subst_type t' n e)) \n          (type_subst (type_subst t' n t'') first (type_subst (type_insert first t') (next n) t))\" \n      by (metis typecheck.tc_tyappl)\n  thus ?case by simp\nnext case tc_triv\n  thus ?case by simp\nnext case tc_pair\n  thus ?case by simp\nnext case tc_projl\n  thus ?case by (metis expr_subst_type.simps(11) type_subst.simps(6) typecheck.tc_projl)\nnext case tc_projr\n  thus ?case by (metis expr_subst_type.simps(12) type_subst.simps(6) typecheck.tc_projr)\nnext case tc_abort\n  thus ?case by simp\nnext case tc_case\n  thus ?case by fastforce\nnext case tc_inl\n  thus ?case by simp\nnext case tc_inr\n  thus ?case by simp\nqed\n\nlemma [simp]: \"typecheck del gam (TyAppl t' e) t ==> \n                  EX tt. typecheck del gam e (All tt) & t = type_subst t' first tt\"\nby (induction del gam \"TyAppl t' e\" t arbitrary: e rule: typecheck.induct, blast)\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/Chapter20_2_Typechecking.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.918480252950991, "lm_q2_score": 0.8152324938410784, "lm_q1q2_score": 0.748774947157021}}
{"text": "theory Shortest_Path\n  imports\n    Weighted_Graph\nbegin\n\nsection \\<open>Shortest walk cost\\<close>\n\ndefinition shortest_walk_cost :: \"'a graph \\<Rightarrow> 'a cost_fun \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> ereal\" where\n  \"shortest_walk_cost G f u v \\<equiv> INF p\\<in>{p. walk G u p v}. ereal (walk_cost f p)\"\n\ndefinition is_shortest_walk :: \"'a graph \\<Rightarrow> 'a cost_fun \\<Rightarrow> 'a \\<Rightarrow> 'a list \\<Rightarrow> 'a \\<Rightarrow> bool\" where\n  \"is_shortest_walk G f u p v \\<equiv> walk G u p v \\<and> walk_cost f p = shortest_walk_cost G f u v\"\n\nlemma is_shortest_walkI:\n  assumes \"walk G u p v\"\n  assumes \"walk_cost f p = shortest_walk_cost G f u v\"\n  shows \"is_shortest_walk G f u p v\"\n  using assms\n  by (simp add: is_shortest_walk_def)\n\nsubsection \\<open>Basic Lemmas\\<close>\n\nlemma (in graph) shortest_walk_cost_symmetric_aux:\n  shows\n    \"(\\<lambda>p. ereal (walk_cost f p)) ` {p. walk G u p v} \\<subseteq>\n      (\\<lambda>p. ereal (walk_cost f p)) ` {p. walk G v p u}\"\n    (is \"?A \\<subseteq> ?B\")\nproof\n  fix x\n  assume \"x \\<in> ?A\"\n  then obtain p where\n    \"p \\<in> {p. walk G u p v}\"\n    \"x = walk_cost f p\"\n    by blast\n  hence\n    \"(rev p) \\<in> {p. walk G v p u}\"\n    \"x = walk_cost f (rev p)\"\n    by (simp add: walk_rev)+\n  thus \"x \\<in> ?B\"\n    by blast\nqed\n\nlemma (in graph) shortest_walk_cost_symmetric:\n  shows \"shortest_walk_cost G f u v = shortest_walk_cost G f v u\"\nproof -\n  have\n    \"(\\<lambda>p. ereal (walk_cost f p)) ` {p. walk G u p v} =\n      (\\<lambda>p. ereal (walk_cost f p)) ` {p. walk G v p u}\"\n    (is \"?A = ?B\")\n  proof\n    show \"?A \\<subseteq> ?B\"\n      using shortest_walk_cost_symmetric_aux[where ?u = u and ?v = v]\n      by simp\n  next\n    show \"?B \\<subseteq> ?A\"\n      using shortest_walk_cost_symmetric_aux[where ?u = v and ?v = u]\n      by simp\n  qed\n  thus ?thesis\n    by (simp add: shortest_walk_cost_def)\nqed\n\nlemma shortest_walk_cost_non_negative_if_cost_non_negative:\n  assumes \"\\<And>e. e \\<in> edges G \\<Longrightarrow> 0 \\<le> f e\"\n  shows \"0 \\<le> shortest_walk_cost G f u v\"\nproof -\n  { fix p\n    assume \"p \\<in> {p. walk G u p v}\"\n    hence \"0 \\<le> walk_cost f p\"\n      using assms\n      by (blast intro: walk_cost_non_negative_if_cost_non_negative) }\n  thus ?thesis\n    by (auto simp add: shortest_walk_cost_def intro: INF_greatest)\nqed\n\nlemma shortest_walk_cost_le_walk_cost:\n  assumes \"walk G u p v\"\n  shows \"shortest_walk_cost G f u v \\<le> walk_cost f p\"\n  using assms\n  by (auto simp add: shortest_walk_cost_def intro: INF_lower)\n\nlemma (in graph) shortest_walk_cost_edge_le_cost:\n  assumes \"{u, v} \\<in> edges G\"\n  shows \"shortest_walk_cost G f u v \\<le> f {u, v}\"\nproof -\n  have \"walk G u [u, v] v\"\n    using assms\n    by (rule edge_is_walk)\n  hence \"shortest_walk_cost G f u v \\<le> walk_cost f [u, v]\"\n    by (rule shortest_walk_cost_le_walk_cost)\n  also have \"... = f {u, v}\"\n    by (simp add: walk_cost_def)\n  finally show ?thesis\n    .\nqed\n\nlemma shortest_walk_cost_reachable_conv:\n  shows \"shortest_walk_cost G f u v \\<noteq> \\<infinity> = reachable G u v\"\nproof\n  assume shortest_walk_cost_finite: \"shortest_walk_cost G f u v \\<noteq> \\<infinity>\"\n  show \"reachable G u v\"\n  proof (rule ccontr)\n    assume \"\\<not> reachable G u v\"\n    hence \"{p. walk G u p v} = {}\"\n      by (simp add: reachable_def)\n    thus \"False\"\n      using shortest_walk_cost_finite\n      by (simp add: shortest_walk_cost_def top_ereal_def)\n  qed\nnext\n  assume \"reachable G u v\"\n  then obtain p where\n    \"walk G u p v\"\n    by (auto simp add: reachable_def)\n  hence \"shortest_walk_cost G f u v \\<le> walk_cost f p\"\n    by (rule shortest_walk_cost_le_walk_cost)\n  also have \"... < \\<infinity>\"\n    by (simp add: walk_cost_def)\n  finally show \"shortest_walk_cost G f u v \\<noteq> \\<infinity>\"\n    by simp\nqed\n\nlemma singleton_is_shortest_walk:\n  assumes f_non_negative: \"\\<And>e. e \\<in> edges G \\<Longrightarrow> 0 \\<le> f e\"\n  assumes v_in_vertices: \"v \\<in> vertices G\"\n  shows \"is_shortest_walk G f v [v] v\"\nproof (intro antisym is_shortest_walkI)\n  show v_walk: \"walk G v [v] v\"\n    using v_in_vertices\n    by (rule singleton_is_walk)\n  have \"walk_cost f [v] = 0\"\n    by (simp add: walk_cost_def)\n  also have \"... \\<le> shortest_walk_cost G f v v\"\n    unfolding zero_ereal_def[symmetric]\n    using f_non_negative\n    by (rule shortest_walk_cost_non_negative_if_cost_non_negative)\n  finally show \"walk_cost f [v] \\<le> shortest_walk_cost G f v v\"\n    .\n  show \"shortest_walk_cost G f v v \\<le> walk_cost f [v]\"\n    using v_walk\n    by (rule shortest_walk_cost_le_walk_cost)\nqed\n\nsubsection \\<open>Shortest path cost\\<close>\n\n(* This subsection is largely based on the formalization of directed graphs (Graph_Theory). *)\n\nlemma (in graph) shortest_walk_cost_ge_shortest_walk_to_path_cost:\n  assumes \"\\<And>e. e \\<in> edges G \\<Longrightarrow> 0 \\<le> f e\"\n  shows\n    \"(INF p\\<in>{p. walk G u p v}. ereal (walk_cost f (walk_to_path p))) \\<le>\n      shortest_walk_cost G f u v\"\nproof -\n  { fix p\n    assume \"p \\<in> {p. walk G u p v}\"\n    hence \"walk_cost f (walk_to_path p) \\<le> walk_cost f p\"\n      using assms\n      by (intro walk_cost_ge_walk_to_path_cost) simp+ }\n  thus ?thesis\n    by (fastforce simp add: shortest_walk_cost_def intro: INF_mono)\nqed\n\nlemma (in graph) shortest_walk_cost_eq_shortest_path_cost:\n  assumes \"\\<And>e. e \\<in> edges G \\<Longrightarrow> 0 \\<le> f e\"\n  shows \"shortest_walk_cost G f u v = (INF p\\<in>{p. path G u p v}. ereal (walk_cost f p))\"\nproof (rule antisym)\n  define walks where \"walks = {p. walk G u p v}\"\n  define paths where \"paths = {p. path G u p v}\"\n\n  have \"paths \\<subseteq> walks\"\n    by (auto simp add: walks_def paths_def path_def)\n  thus \"shortest_walk_cost G f u v \\<le> (INF p\\<in>{p. path G u p v}. ereal (walk_cost f p))\"\n    unfolding shortest_walk_cost_def walks_def[symmetric] paths_def[symmetric]\n    by (rule INF_superset_mono) simp  \n\n  have \"walk_to_path ` walks \\<subseteq> paths\"\n    unfolding walks_def paths_def\n    by (blast intro: walk_to_path_is_path)\n  hence\n    \"(INF p\\<in>paths. ereal (walk_cost f p)) \\<le>\n      (INF p\\<in>walk_to_path ` walks. ereal (walk_cost f p))\"\n    by (rule INF_superset_mono) simp\n  also have \"... = (INF p\\<in>walks. ereal (walk_cost f (walk_to_path p)))\"\n    unfolding image_image\n    by simp\n  also have \"... \\<le> (INF p\\<in>walks. ereal (walk_cost f p))\" \n    unfolding walks_def shortest_walk_cost_def[symmetric]\n    using assms\n    by (rule shortest_walk_cost_ge_shortest_walk_to_path_cost)\n  finally show \"(INF p\\<in>{p. path G u p v}. ereal (walk_cost f p)) \\<le> shortest_walk_cost G f u v\"\n    by (simp add: walks_def paths_def shortest_walk_cost_def)\nqed\n\nlemma (in finite_graph) shortest_walk_cost_path:\n  assumes reachable: \"reachable G u v\"\n  assumes f_non_negative: \"\\<And>e. e \\<in> edges G \\<Longrightarrow> 0 \\<le> f e\"\n  shows \"\\<exists>p. path G u p v \\<and> walk_cost f p = shortest_walk_cost G f u v\"\nproof -\n  have paths_non_empty: \"{p. path G u p v} \\<noteq> {}\"\n    (is \"?A \\<noteq> {}\")\n    using reachable\n    by (auto simp add: reachable_def intro: walk_to_path_is_path)\n\n  have \"shortest_walk_cost G f u v = (INF p\\<in>?A. ereal (walk_cost f p))\"\n    using f_non_negative\n    by (rule shortest_walk_cost_eq_shortest_path_cost)\n  also have \"... \\<in> (\\<lambda>p. ereal (walk_cost f p)) ` ?A\"\n    using paths_finite paths_non_empty\n    by (rule INF_in_image)\n  finally show ?thesis\n    by (auto simp add: image_def)\nqed\n\nsubsection \\<open>Triangle inequality\\<close>\n\nlemma (in finite_graph) shortest_walk_cost_triangle_inequality_case_real:\n  assumes f_non_negative: \"\\<And>e. e \\<in> edges G \\<Longrightarrow> 0 \\<le> f e\"\n  assumes\n    assm: \"shortest_walk_cost G f u v + shortest_walk_cost G f v w <\n      shortest_walk_cost G f u w\"\n    (is \"?b + ?c < ?a\")\n  assumes real: \"shortest_walk_cost G f u w = ereal r\"\n  shows \"False\"\nproof -\n  have\n    \"?b \\<noteq> \\<infinity>\"\n    \"?c \\<noteq> \\<infinity>\"\n    using assm real\n    by auto\n  hence\n    \"reachable G u v\"\n    \"reachable G v w\"\n    by (simp add: shortest_walk_cost_reachable_conv)+\n  hence\n    \"\\<exists>p. path G u p v \\<and> walk_cost f p = ?b\"\n    \"\\<exists>p. path G v p w \\<and> walk_cost f p = ?c\"\n    using f_non_negative\n    by (auto intro: shortest_walk_cost_path)\n  then obtain p q where\n    p_walk: \"walk G u p v\" and\n    p_walk_cost: \"walk_cost f p = ?b\" and\n    q_walk: \"walk G v q w\" and\n    q_walk_cost: \"walk_cost f q = ?c\"\n    by (auto simp add: path_def)\n\n  have \"walk G u (p @ tl q) w\"\n    using p_walk q_walk\n    by (rule walk_append_is_walk)\n  hence \"?a \\<le> walk_cost f (p @ tl q)\"\n    by (rule shortest_walk_cost_le_walk_cost)\n  also have \"... = walk_cost f p + walk_cost f q\"\n    using p_walk q_walk\n    by (auto simp add: walk_def intro: walk_cost_append_2)\n  finally have \"?a \\<le> ?b + ?c\"\n    by (simp add: plus_ereal.simps(1)[symmetric] p_walk_cost q_walk_cost)\n  thus ?thesis\n    using assm\n    by simp\nqed\n\nlemma (in finite_graph) shortest_walk_cost_triangle_inequality_case_PInf:\n  assumes \"\\<And>e. e \\<in> edges G \\<Longrightarrow> 0 \\<le> f e\"\n  assumes assm: \"shortest_walk_cost G f u v + shortest_walk_cost G f v w < shortest_walk_cost G f u w\"\n    (is \"?b + ?c < ?a\")\n  assumes PInf: \"shortest_walk_cost G f u w = \\<infinity>\"\n  shows \"False\"\nproof -\n  have\n    \"?b \\<noteq> \\<infinity>\"\n    \"?c \\<noteq> \\<infinity>\"\n    using assm PInf\n    by simp+\n  hence\n    \"reachable G u v\"\n    \"reachable G v w\"\n    by (simp add: shortest_walk_cost_reachable_conv)+\n  hence \"reachable G u w\"\n    by (rule reachable_trans)\n  hence \"shortest_walk_cost G f u w \\<noteq> \\<infinity>\"\n    by (simp add: shortest_walk_cost_reachable_conv)\n  thus ?thesis\n    using PInf\n    by simp\nqed\n\nlemma (in finite_graph) shortest_walk_cost_triangle_inequality:\n  assumes \"\\<And>e. e \\<in> edges G \\<Longrightarrow> 0 \\<le> f e\"\n  shows \"shortest_walk_cost G f u w \\<le> shortest_walk_cost G f u v + shortest_walk_cost G f v w\"\n    (is \"?a \\<le> ?b + ?c\")\nproof (rule ccontr)\n  assume \"\\<not> ?a \\<le> ?b + ?c\"\n  hence assm: \"?b + ?c < ?a\"\n    by simp\n  show \"False\"\n  proof (cases ?a)\n    case (real r)\n    with assms assm\n    show ?thesis\n      by (rule shortest_walk_cost_triangle_inequality_case_real)\n  next\n    case PInf\n    with assms assm\n    show ?thesis\n      by (rule shortest_walk_cost_triangle_inequality_case_PInf)\n  next\n    case MInf\n    thus ?thesis\n      using assm\n      by simp\n  qed\nqed\n\nsubsection \\<open>Decomposing shortest walks\\<close>\n\nlemma (in finite_graph) shortest_walk_cost_walk_vertex_decomp:\n  assumes f_non_negative: \"\\<And>e. e \\<in> edges G \\<Longrightarrow> 0 \\<le> f e\"\n  assumes p_shortest_walk: \"is_shortest_walk G f 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  shows \"shortest_walk_cost G f u w = shortest_walk_cost G f u v + shortest_walk_cost G f v w\"\n    (is \"?a = ?b + ?c\")\nproof (rule antisym)\n  show \"?a \\<le> ?b + ?c\"\n    using f_non_negative\n    by (rule shortest_walk_cost_triangle_inequality)\nnext\n  have\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    using p_shortest_walk v_in_p qr_def\n    by (auto simp add: is_shortest_walk_def elim: walk_vertex_decompE_2)\n\n  have \"?b + ?c \\<le> walk_cost f q + walk_cost f r\"\n    unfolding plus_ereal.simps(1)[symmetric]\n    using q_walk r_walk\n    by (intro shortest_walk_cost_le_walk_cost add_mono)\n  also have \"... = walk_cost f (q @ tl r)\"\n    using q_walk r_walk\n    by (auto simp add: walk_def intro: walk_cost_append_2[symmetric])\n  finally show \"?b + ?c \\<le> ?a\"\n    using p_shortest_walk\n    by (simp add: p_decomp is_shortest_walk_def)\nqed\n\nsubsection \\<open>Shortest walks in subgraphs/supergraphs\\<close>\n\nlemma (in subgraph) shortest_walk_cost_subgraph_ge_shortest_walk_cost_supergraph:\n  shows \"shortest_walk_cost G f u v \\<le> shortest_walk_cost H f u v\"\nproof -\n  have \"{p. walk H u p v} \\<subseteq> {p. walk G u p v}\"\n    by (blast intro: walk_subgraph_is_walk_supergraph)\n  hence\n    \"(\\<lambda>p. ereal (walk_cost f p)) ` {p. walk H u p v} \\<subseteq>\n      (\\<lambda>p. ereal (walk_cost f p)) ` {p. walk G u p v}\"\n    (is \"?A \\<subseteq> ?B\")\n    by blast\n  hence \"Inf ?B \\<le> Inf ?A\"\n    by (rule Inf_superset_mono)\n  thus ?thesis\n    by (simp add: shortest_walk_cost_def)\nqed\n\nlemmas (in induced_subgraph) shortest_walk_cost_subgraph_ge_shortest_walk_cost_supergraph =\n  shortest_walk_cost_subgraph_ge_shortest_walk_cost_supergraph\n\nlemma (in induced_subgraph) shortest_walk_supergraph_is_shortest_walk_subgraph:\n  assumes p_shortest_walk: \"is_shortest_walk G f u p v\"\n  assumes \"set p \\<subseteq> V\"\n  shows \"is_shortest_walk H f u p v\"\nproof (intro antisym is_shortest_walkI)\n  show p_walk: \"walk H u p v\"\n    using assms\n    by (auto simp add: is_shortest_walk_def intro: walk_supergraph_is_walk_subgraph)\n  show \"walk_cost f p \\<le> shortest_walk_cost H f u v\"\n    using p_shortest_walk shortest_walk_cost_subgraph_ge_shortest_walk_cost_supergraph\n    by (simp add: is_shortest_walk_def)\n  show \"shortest_walk_cost H f u v \\<le> walk_cost f p\"\n    using p_walk\n    by (rule shortest_walk_cost_le_walk_cost)\nqed\n\nsubsection \\<open>Convenience Lemmas\\<close>\n\nlemma (in graph) shortest_walk_cost_infinite_if_not_in_vertices:\n  assumes \"v \\<notin> vertices G\"\n  shows \"shortest_walk_cost G f u v = \\<infinity>\"\nproof (rule ccontr)\n  assume \"shortest_walk_cost G f u v \\<noteq> \\<infinity>\"\n  hence \"reachable G u v\"\n    by (simp add: shortest_walk_cost_reachable_conv)\n  then obtain p where\n    \"walk G u p v\"\n    by (auto simp add: reachable_def)\n  hence \"v \\<in> vertices G\"\n    by (rule walk_last_in_vertices)\n  thus \"False\"\n    using assms\n    by simp\nqed\n\nlemma (in finite_graph) shortest_walk_cost_walk:\n  assumes p_walk: \"walk G u p v\"\n  assumes f_non_negative: \"\\<And>e. e \\<in> edges G \\<Longrightarrow> 0 \\<le> f e\"\n  shows \"\\<exists>q. is_shortest_walk G f u q v \\<and> walk_cost f q \\<le> walk_cost f p\"\nproof -\n  have \"reachable G u v\"\n    using p_walk\n    by (auto simp add: reachable_def)\n  hence \"\\<exists>q. path G u q v \\<and> walk_cost f q = shortest_walk_cost G f u v\"\n    using f_non_negative\n    by (rule shortest_walk_cost_path)\n  then obtain q where\n    q_walk: \"walk G u q v\" and\n    q_walk_cost: \"walk_cost f q = shortest_walk_cost G f u v\"\n    by (auto simp add: path_def)\n\n  have \"walk_cost f q \\<le> walk_cost f p\"\n    unfolding ereal_less_eq(3)[symmetric] q_walk_cost\n    using p_walk\n    by (rule shortest_walk_cost_le_walk_cost)\n  moreover have \"is_shortest_walk G f u q v\"\n    using q_walk q_walk_cost\n    by (rule is_shortest_walkI)\n  ultimately show ?thesis\n    by blast\nqed\n\ndefinition shortest_walk :: \"'a graph \\<Rightarrow> 'a cost_fun \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> 'a list\" where\n  \"shortest_walk G f u v \\<equiv> SOME p. is_shortest_walk G f u p v\"\n\nlemma (in finite_graph) shortest_walk_is_shortest_walk:\n  assumes \"reachable G u v\"\n  assumes \"\\<And>e. e \\<in> edges G \\<Longrightarrow> 0 \\<le> f e\"\n  shows \"is_shortest_walk G f u (shortest_walk G f u v) v\"\nproof -\n  have \"\\<exists>p. path G u p v \\<and> walk_cost f p = shortest_walk_cost G f u v\"\n    using assms\n    by (rule shortest_walk_cost_path)\n  hence \"\\<exists>p. walk G u p v \\<and> walk_cost f p = shortest_walk_cost G f u v\"\n    by (auto simp add: path_def)\n  hence \"\\<exists>p. is_shortest_walk G f u p v\"\n    by (auto simp add: is_shortest_walk_def)\n  thus ?thesis\n    unfolding shortest_walk_def\n    ..\nqed\n\nsection \\<open>Shortest walk length\\<close>\n\n(*\nTODO: Is there a way to define shortest_walk_length as\n\ndefinition shortest_walk_length :: \"'a graph \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> enat\" where\n  \"shortest_walk_length G u v \\<equiv> INF p\\<in>{p. walk G u p v}. enat (walk_length p)\"\n\nand prove\n\n  \"ereal_of_enat (shortest_walk_length G u v) = shortest_walk_cost G (\\<lambda>_. 1) u v\"\n\nIf not, would it be better to change the type of shortest_walk_cost to enat?\n*)\n\nabbreviation shortest_walk_length :: \"'a graph \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> ereal\" where\n  \"shortest_walk_length G \\<equiv> shortest_walk_cost G (\\<lambda>_. 1)\"\n\nlemma walk_length_eq_walk_cost:\n  shows \"walk_length p = walk_cost (\\<lambda>_. 1) 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 add: walk_cost_def)\nnext\n  case (3 v v' vs)\n  define f :: \"'a set \\<Rightarrow> real\" where\n    \"f = (\\<lambda>_. 1)\"\n  have \"walk_length (v # v' # vs) = 1 + walk_length (v' # vs)\"\n    by simp\n  also have \"... = 1 + walk_cost f (v' # vs)\"\n    by (simp add: \"3.IH\" f_def)\n  also have \"... = f {v, v'} + walk_edges_cost f (walk_edges (v' # vs))\"\n    by (simp add: f_def walk_cost_def)\n  also have \"... = walk_cost f (v # v' # vs)\"\n    by (simp add: walk_cost_def)\n  finally show ?case\n    by (simp add: f_def)\nqed\n\nlemma (in finite_graph) shortest_walk_length_eq_1:\n  shows\n    \"0 < shortest_walk_length G u v \\<and> shortest_walk_length G u v \\<le> 1 \\<longleftrightarrow>\n      shortest_walk_length G u v = 1\"\nproof\n  assume assm: \"0 < shortest_walk_length G u v \\<and> shortest_walk_length G u v \\<le> 1\"\n  define f :: \"'a set \\<Rightarrow> real\" where\n    \"f = (\\<lambda>_. 1)\"\n  have f_non_negative: \"\\<And>e. e \\<in> edges G \\<Longrightarrow> 0 \\<le> f e\"\n    by (simp add: f_def)\n\n  have \"shortest_walk_length G u v \\<noteq> \\<infinity>\"\n    using assm\n    by auto\n  hence \"reachable G u v\"\n    by (simp add: shortest_walk_cost_reachable_conv)\n  hence \"\\<exists>p. path G u p v \\<and> walk_cost f p = shortest_walk_cost G f u v\"\n    using f_non_negative\n    by (rule shortest_walk_cost_path)\n  then obtain p where\n    p_walk_cost: \"walk_cost f p = shortest_walk_length G u v\"\n    by (auto simp add: f_def)\n  hence\n    \"0 < walk_cost f p\"\n    \"walk_cost f p \\<le> 1\"\n    using assm\n    by (simp add: ereal_less(2)[symmetric] ereal_less_eq(3)[symmetric] one_ereal_def)+\n  hence\n    \"0 < walk_length p\"\n    \"walk_length p \\<le> 1\"\n    by (simp add: f_def walk_length_eq_walk_cost[symmetric])+\n  hence \"walk_length p = 1\"\n    by linarith\n  hence \"walk_cost f p = 1\"\n    by (simp add: walk_length_eq_walk_cost[symmetric] f_def)\n  thus \"shortest_walk_length G u v = 1\"\n    by (simp add: p_walk_cost[symmetric])\nqed simp\n\nlemma (in finite_graph) shortest_walk_length_eq_1_implies_edge:\n  assumes \"shortest_walk_length G u v = 1\"\n  shows \"{u, v} \\<in> edges G\"\nproof -\n  define f :: \"'a set \\<Rightarrow> real\" where\n    \"f = (\\<lambda>_. 1)\"\n  have f_non_negative: \"\\<And>e. e \\<in> edges G \\<Longrightarrow> 0 \\<le> f e\"\n    by (simp add: f_def)\n\n  have \"shortest_walk_length G u v \\<noteq> \\<infinity>\"\n    using assms\n    by simp\n  hence \"reachable G u v\"\n    by (simp add: shortest_walk_cost_reachable_conv)\n  hence \"\\<exists>p. path G u p v \\<and> walk_cost f p = shortest_walk_cost G f u v\"\n    using f_non_negative\n    by (rule shortest_walk_cost_path)\n  then obtain p where\n    p_walk: \"walk G u p v\" and\n    \"walk_cost f p = 1\"\n    using assms\n    by (auto simp add: path_def f_def)\n  hence \"walk_length p = 1\"\n    by (simp add: f_def walk_length_eq_walk_cost[symmetric])\n  hence \"length p = Suc 1\"\n    using p_walk\n    by (simp add: walk_def walk_length)\n  hence \"p = [u, v]\"\n    using p_walk\n    by (intro list_length_2) (simp add: walk_def)+\n  thus ?thesis\n    using p_walk\n    by (simp add: edge_iff_walk)\nqed\n\nlemma (in finite_graph) shortest_walk_length_le_1_if_edge:\n  assumes \"{u, v} \\<in> edges G\"\n  shows \"shortest_walk_length G u v \\<le> 1\"\nproof -\n  have \"walk G u [u, v] v\"\n    using assms\n    by (rule edge_is_walk)\n  hence \"shortest_walk_length G u v \\<le> walk_cost (\\<lambda>_. 1) [u, v]\"\n    by (rule shortest_walk_cost_le_walk_cost)\n  also have \"... = 1\"\n    by (simp add: walk_cost_def)\n  finally show ?thesis\n    .\nqed\n\nlemma (in finite_graph) shortest_walk_length_ge_1_if_edge:\n  assumes \"{u, v} \\<in> edges G\"\n  shows \"1 \\<le> shortest_walk_length G u v\"\nproof (rule ccontr)\n  assume assm: \"\\<not> 1 \\<le> shortest_walk_length G u v\"\n  define f :: \"'a set \\<Rightarrow> real\" where\n    \"f = (\\<lambda>_. 1)\"\n  have f_non_negative: \"\\<And>e. e \\<in> edges G \\<Longrightarrow> 0 \\<le> f e\"\n    by (simp add: f_def)\n\n  have \"walk G u [u, v] v\"\n    using assms\n    by (rule edge_is_walk)\n  hence \"reachable G u v\"\n    by (auto simp add: reachable_def)\n  hence \"\\<exists>p. path G u p v \\<and> walk_cost f p = shortest_walk_cost G f u v\"\n    using f_non_negative\n    by (rule shortest_walk_cost_path)\n  then obtain p where\n    p_walk: \"walk G u p v\" and\n    \"walk_cost f p = shortest_walk_length G u v\"\n    by (auto simp add: path_def f_def)\n  hence \"walk_cost f p < 1\"\n    using assm\n    by (simp add: ereal_less(3)[symmetric])\n  hence \"walk_length p = 0\"\n    unfolding f_def walk_length_eq_walk_cost[symmetric]\n    by linarith\n  hence \"length p = 1\"\n    using p_walk\n    by (simp add: walk_def walk_length)\n  hence \"p = [u] \\<and> u = v\"\n    using p_walk\n    by (intro list_length_1) (simp add: walk_def)+\n  thus \"False\"\n    using assms graph\n    by auto\nqed\n\nlemma (in finite_graph) shortest_walk_length_eq_1_if_edge:\n  assumes \"{u, v} \\<in> edges G\"\n  shows \"shortest_walk_length G u v = 1\"\nproof (rule antisym)\n  show \"shortest_walk_length G u v \\<le> 1\"\n    using assms\n    by (rule shortest_walk_length_le_1_if_edge)\nnext\n  show \"1 \\<le> shortest_walk_length G u v\"\n    using assms\n    by (rule shortest_walk_length_ge_1_if_edge)\nqed\n\nlemma (in finite_graph) shortest_walk_length_eq_1_iff_edge:\n  shows \"shortest_walk_length G u v = 1 \\<longleftrightarrow> {u, v} \\<in> edges G\"\nproof\n  show \"shortest_walk_length G u v = 1 \\<Longrightarrow> {u, v} \\<in> edges G\"\n    using shortest_walk_length_eq_1_implies_edge\n    .\nnext\n  show \"{u, v} \\<in> edges G \\<Longrightarrow> shortest_walk_length G u v = 1\"\n    using shortest_walk_length_eq_1_if_edge\n    .\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/Shortest_Path.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9184802373309982, "lm_q2_score": 0.8152324960856175, "lm_q1q2_score": 0.74877493648466}}
{"text": "theory indices\nimports Main\nbegin\n\n(*Projection function from a list to which picks out the value at given index*)\ndefinition project_at_index :: \" nat \\<Rightarrow> 'a list  \\<Rightarrow> 'a\" (\"\\<pi>\\<^bsub>=_\\<^esub>\") where \n\"project_at_index k as \\<equiv> as ! k\"\n\nlemma project_at_index_simp[simp]:\n\"project_at_index k as \\<equiv> as ! k\"\n  by (simp add: project_at_index_def)\n\n(****************Canonical Map from finite sets of natural numbers to lists ***********************)\n\nfun remove_smallest :: \"nat set \\<Rightarrow> nat \\<Rightarrow> nat set\" where \n\"remove_smallest A 0 = A\"|\n\"remove_smallest A (Suc n) = (remove_smallest A n) - {(LEAST s. s \\<in> (remove_smallest A n))}\"\n\nlemma remove_smallest_subset[simp]: \n\"remove_smallest A (Suc n) \\<subseteq> (remove_smallest A n)\"\n  by auto\n\nlemma remove_smallest_subset'[simp]: \n\"remove_smallest A (Suc n) \\<subseteq> A\"\n  by (metis less_imp_le lift_Suc_antimono_le remove_smallest.simps(1) \n      remove_smallest_subset zero_less_Suc)\n\nlemma remove_smallest_card_infinite[simp]:\n\"\\<And>A. infinite A \\<Longrightarrow> infinite (remove_smallest A n)\"\n  apply(induction n)\n  apply simp\n  by simp\n\nlemma remove_smallest_shrink[simp]:\n  assumes \"finite (A:: nat set) \\<and> card A \\<ge>1\"\n  shows \"(LEAST s. s \\<in> A) \\<in> A\"\n  by (metis Inf_nat_def1 LeastI assms card_empty le_numeral_extra(2))\n\nlemma remove_smallest_card_finite[simp]:\n  assumes \"finite A \"\n  shows \"card (remove_smallest A 1) = (card A) - 1\"\nproof(cases \"card A \\<ge>1\")\n  case True\n  then show ?thesis \n    by (simp add: assms)\nnext\n  case False\n  then show ?thesis \n    by (metis One_nat_def Suc_leI assms card_0_eq diff_le_self gr_zeroI \n        le_zero_eq remove_smallest.simps(1) remove_smallest_subset subset_empty)\nqed\n\nlemma remove_smallest_card_finite'[simp]:\n\"\\<And>A. finite A  \\<Longrightarrow> card (remove_smallest A n) = (card A) - n\"\n  apply(induction n)\n   apply simp\nproof-\n  fix n A\n  assume IH: \"\\<And>A. (finite A  \\<Longrightarrow> card (remove_smallest A n) = card A - n)\"\n  show \"finite A  \\<Longrightarrow> card (remove_smallest A (Suc n)) = card A - Suc n\"\n  proof-\n    assume A: \"finite A\"\n    then have A0: \"finite (remove_smallest A n) \\<and> card (remove_smallest A n) = card A - n\"\n      using IH  Suc_leD \n      by (metis finite_subset remove_smallest.elims remove_smallest_subset')\n    then have A1: \" card (remove_smallest (remove_smallest A n) 1) = card (remove_smallest A n) - 1\"\n      using remove_smallest_card_finite[of \"(remove_smallest A n)\"] by auto \n    have \"remove_smallest A (Suc n) = (remove_smallest (remove_smallest A n) 1)\"\n    proof-\n      have 0: \"remove_smallest A (Suc n) = (remove_smallest A n) - {(LEAST s. s \\<in> (remove_smallest A n))}\"\n        by simp \n      have \"(remove_smallest (remove_smallest A n) 1) =  (remove_smallest A n) - {(LEAST s. s \\<in> (remove_smallest A n))}\"\n        by simp \n      then show ?thesis using 0 by auto \n    qed\n    then show ?thesis \n      using A0 A1 \n      by presburger\n  qed\nqed\n\nlemma remove_smallest_subset'': \n\"k \\<le> n \\<Longrightarrow> remove_smallest A n \\<subseteq> remove_smallest A k\"\n  apply(induction n)\n  apply blast\n  using lift_Suc_antimono_le remove_smallest_subset \n  by blast\n\ndefinition enumerate_by_order :: \"nat set \\<Rightarrow> nat \\<Rightarrow> nat\" (\"enum\") where\n\"enumerate_by_order A n =  (LEAST s. s \\<in> (remove_smallest A n))\"\n\nlemma enumerate_in_A_0: \n  assumes \"A \\<noteq> {}\"\n  shows \"enum A 0 \\<in> A \\<and> (\\<forall>a. a \\<in> A \\<longrightarrow> a \\<ge> (enum A 0))\"\n unfolding enumerate_by_order_def  \n  by (metis (full_types) Inf_nat_def1 LeastI Least_le assms remove_smallest.simps(1))\n\nlemma enumerate_step: \n  assumes \"\\<not> finite A \\<or> (finite A \\<and> (card A > (Suc  n)))\"\n  assumes \"A' = A - {(enum A 0)}\"\n  shows \"\\<not> finite A' \\<or> (finite A' \\<and> (card A' > n))\"\n  using assms enumerate_in_A_0[of A]\n  by force\n\nlemma enumerate_in_set[simp]: \n\"\\<And>(A::nat set). \\<not> finite A \\<or> (finite A \\<and> (card A > n)) \\<Longrightarrow> (enum A n) \\<in> A\"\nproof(induction n)\n  case 0\n  show ?case \n    by (metis \"0.prems\" card_empty enumerate_in_A_0 finite.intros(1) less_numeral_extra(3))\nnext\n  case (Suc n)\n  then show ?case \n    using enumerate_step[of \"(remove_smallest A n)\"] \n    by (metis card_empty enumerate_by_order_def enumerate_in_A_0 finite.emptyI not_gr0\n        remove_smallest_card_finite' remove_smallest_card_infinite remove_smallest_subset'\n        subsetCE wellorder_Least_lemma(1) zero_less_diff)\nqed\n\nlemma enum_remove_enum: \n\"enum A n = enum (remove_smallest A n) 0\" \nproof-\n  have \" enum (remove_smallest A n) 0 = (LEAST s. s \\<in> (remove_smallest A n))\"\n    using enumerate_by_order_def[of \"(remove_smallest A n)\" 0]  \n    by simp \n  then show ?thesis \n    using enumerate_by_order_def[of A n] by simp \nqed\n\n\nlemma remove_smallest_enum: \n\"remove_smallest A (Suc n) = A - (enum A ` {0..n})\"\n  apply(induction n)\n  apply (simp add: enumerate_by_order_def)\nproof-\n  fix n\n  assume IH: \"remove_smallest A (Suc n) = A - enum A ` {0..n}\"\n  show \"remove_smallest A (Suc (Suc n)) = A - enum A ` {0..Suc n}\"\n    using IH atLeast0_atMost_Suc enumerate_by_order_def\n    by auto\nqed\n\nlemma remove_smallest_prop:\n\"(remove_smallest A (Suc k)) = (remove_smallest (A - {enum A 0}) k)\"\n  apply(induction k)\n  apply (simp add: enumerate_by_order_def)\n  by auto \n\n\nlemma enumerate_order_step: \n\"enum A (Suc k) = enum (A - {enum A 0}) k\"\nproof-\n  have 0:\"enum A (Suc k) = enum (remove_smallest A (Suc k)) 0\"\n    using enum_remove_enum \n    by blast\n  have 1: \" enum (A - {enum A 0}) k = enum (remove_smallest (A - {enum A 0}) k) 0\"\n    using enum_remove_enum by blast\n  show ?thesis \n    using 0 1  remove_smallest_prop \n    by auto\nqed\n\n\nlemma enumerate_order[simp]:\n\"\\<And>A. \\<not> finite A \\<or> (finite A \\<and> (card A > Suc k)) \\<Longrightarrow> enum A k < enum A (Suc k)\"\n  apply(induction k)\n   apply (metis Diff_iff empty_iff enum_remove_enum enumerate_by_order_def \n      enumerate_in_A_0 enumerate_in_set enumerate_step le_neq_trans remove_smallest.simps(1) \n      remove_smallest.simps(2) singletonI)\n    using enumerate_order_step enumerate_step \n    by auto\n\n\nlemma enumerate_order'[simp]: \n  assumes \" \\<not> finite A \\<or> (finite A \\<and> (card A > n))\"\n  assumes \"n > k\"\n  shows \"enum A n > enum A k\"\nproof-\n  have \"\\<And>m A. \\<not> finite A \\<or> (finite A \\<and> (card A > k + (Suc m))) \\<Longrightarrow> enum A  (k + (Suc m)) > enum A k\"\n  proof-\n    fix m\n    show  \"\\<And>A. \\<not> finite A \\<or> (finite A \\<and> (card A > k + (Suc m))) \\<Longrightarrow> enum A  (k + (Suc m)) > enum A k\"\n      apply(induction m)\n       apply (simp)\n      by (metis add_Suc_right enumerate_order less_Suc_eq  less_trans)\n  qed\n  then show ?thesis using assms \n    by (metis gr0_implies_Suc less_imp_add_positive)\nqed\n\nlemma enumerate_by_order_eq:\n  shows \"enum A (Suc n)= (LEAST a. a \\<in>  (A - (enum A ` {0..n})))\"\nproof-\n  have \"enum A (Suc n)=  (LEAST s. s \\<in> remove_smallest A (Suc n))\"\n    unfolding  enumerate_by_order_def by auto \n  then show ?thesis using remove_smallest_enum[of A n]\n    by metis  \nqed\n\n(*Given an input nat n, returns  the index list [0,...,n-1]*)\ndefinition index_list :: \"nat \\<Rightarrow> nat list\" where\n\"index_list n = map nat [0..(int n) -1]\"\n\ndefinition index_set :: \"nat \\<Rightarrow> nat set\" where\n\"index_set n = set (index_list n)\"\n\nlemma index_list_length[simp]:\n\"length (index_list n) = n\"\n  unfolding index_list_def \n  by simp\n\nlemma index_set_memI[simp]:\n  assumes \"(i::nat) < n\"\n  shows \"i \\<in> index_set n\"\nproof-\n  have \"i = index_list n ! i\"\n    by (simp add: assms index_list_def)\n  then show ?thesis \n    by (metis assms index_list_length index_set_def nth_mem)\nqed\n\n\nlemma index_set_notmemI[simp]:\n  assumes \"(i::nat) \\<ge> n\"\n  shows \"i \\<notin> index_set n\"\n  using assms index_list_def index_set_def \n  by auto\n\nlemma index_set_induct:\n\"index_set (Suc n) = (index_set n) \\<union> {n}\"\n  apply(induction n)\nproof\n  show \"index_set (Suc 0) \\<subseteq> index_set 0 \\<union> {0}\"\n  by (metis One_nat_def Suc_inject Suc_le_D Suc_le_mono atMost_0 \n      index_set_notmemI inf_sup_aci(5) insert_subset le0 le_SucE le_supI1 lessThan_Suc_atMost \n      lessThan_Suc_eq_insert_0 not_less_eq_eq order_refl subsetI)\n  show \"index_set 0 \\<union> {0} \\<subseteq> index_set (Suc 0)\"\n    using index_set_memI index_set_notmemI by blast\n  fix n\n  assume IH: \"index_set (Suc n) = index_set n \\<union> {n}\"\n  show \"index_set (Suc (Suc n)) = index_set (Suc n) \\<union> {Suc n}\"\n  proof\n    show \"index_set (Suc (Suc n)) \\<subseteq> index_set (Suc n) \\<union> {Suc n}\"\n      using IH \n      by (metis UnCI index_set_memI index_set_notmemI insertCI less_Suc_eq linorder_not_le subsetI)\n    show \"index_set (Suc n) \\<union> {Suc n} \\<subseteq> index_set (Suc (Suc n))\"\n      by (meson empty_subsetI index_set_memI index_set_notmemI insert_subset le_supI \n          less_Suc_eq linorder_not_le subsetI)\n  qed\nqed\n\n(*Function from sets of nat to lists of nat*)\n\nlemma index_list_hd[simp]:\n\"hd (index_list (Suc n)) = 0\"\nunfolding index_list_def \n  using upto.simps\n  by auto\n\nlemma index_list_index:\n  assumes \"k < n\"\n  shows \"index_list n ! k = k\"\n  using assms \n  unfolding index_list_def \n  by simp\n\n\ndefinition set_to_list :: \"nat set \\<Rightarrow> nat list\" where\n\"set_to_list A = map (enum A) (index_list (card A))\"\n\nlemma set_to_list_hd:\n  assumes \"finite A\"\n  assumes \"card A > 0\"\n  shows \"hd (set_to_list A) = enum A 0\"\n  using assms unfolding set_to_list_def \n  by (metis Suc_pred card_0_eq card_gt_0_iff index_list_hd index_list_length \n      list.map_sel(1) list.size(3))\n\nlemma set_to_list_ind[simp]:\n  assumes \"finite A\"\n  assumes \"card A > n\"\n  shows \"(set_to_list A) ! n = (enum A n)\"\n  unfolding set_to_list_def \n  by (simp add: assms(2) index_list_index)\n\nlemma set_to_list_remove_smallest:\n  assumes \"finite A\"\n  assumes \"card A \\<ge> Suc (Suc n)\"\n  shows \"(set_to_list A) ! (Suc n) = set_to_list (remove_smallest A 1) ! n\"\n  by (metis One_nat_def assms(1) assms(2) enum_remove_enum enumerate_step finite_subset lessI\n      less_le_trans remove_smallest.simps(1) remove_smallest_prop remove_smallest_subset \n      set_to_list_ind)\n\nlemma tl_id:\n  assumes \"length as = Suc n\"\n  assumes \"length bs = n\"\n  assumes \"\\<And>k. k < n \\<Longrightarrow> as ! (Suc k) = bs ! k\"\n  shows \"tl as = bs\"\n  using assms \n  by (metis (mono_tags, lifting) Nitpick.size_list_simp(2) \n      Suc_inject nat.simps(3) nth_equalityI nth_tl)\n\nlemma set_to_list_tail:\n  assumes \"finite A\"\n  assumes \"card A > 0\"\n  shows \"tl (set_to_list A) = set_to_list (remove_smallest A 1)\"\nproof-\n  obtain n where n_def: \"Suc n = card A\"\n    by (metis Suc_pred' assms(2))\n  show ?thesis using tl_id[of \"(set_to_list A)\" n \"set_to_list (remove_smallest A 1)\"]\n    by (metis Suc_lessI Suc_less_eq add_diff_cancel_left' assms(1) index_list_length le_less \n        length_map n_def plus_1_eq_Suc remove_smallest_card_finite set_to_list_def \n        set_to_list_remove_smallest)\nqed\n\nlemma set_to_list_size:\n  assumes \"finite A\"\n  shows \"length (set_to_list A) = card A\"\n  using set_to_list_def by auto\n\nlemma set_to_list_to_set: \n  shows \"finite A \\<Longrightarrow> set (set_to_list A) = A\"\nproof-\n  have 0:\"\\<And>n A. finite A \\<Longrightarrow> n = card A \\<Longrightarrow> set (set_to_list A) = A\"\n  proof-\n    fix n\n    show \"\\<And> A. finite A \\<Longrightarrow> n = card A \\<Longrightarrow> set (set_to_list A) = A\"\n      apply(induction n)\n      using set_to_list_size apply force\n    proof-\n      fix n\n      fix A:: \"nat set\"\n      assume IH: \"(\\<And>A. finite A \\<Longrightarrow> n = card A \\<Longrightarrow> set (set_to_list A) = A)\"\n      assume A0: \"finite A\"\n      assume A1: \"Suc n = card A\"\n      show \"set (set_to_list A) = A\"\n      proof\n        show \"set (set_to_list A) \\<subseteq> A\"\n          using set_to_list_ind[of A n]\n          by (metis A0 enumerate_in_set in_set_conv_nth set_to_list_ind set_to_list_size subsetI)\n        show \"A \\<subseteq> set (set_to_list A)\"\n        proof\n          have \"set (set_to_list A) = insert (hd (set_to_list A)) (set (tl (set_to_list A)))\"\n            by (metis A1 card_0_eq card_gt_0_iff list.exhaust_sel list.set(2) list.size(3) set_to_list_size zero_less_Suc)\n          then have A2: \"set (set_to_list A) = insert (hd (set_to_list A)) (set (set_to_list (remove_smallest A 1)))\"\n            using A0 A1 set_to_list_tail by auto\n          fix x\n          assume A3: \"x \\<in> A\"\n          show \" x \\<in> set (set_to_list A) \"\n          proof(cases \"x = enum A 0\")\n            case True\n            then show ?thesis \n              using A0 A1 in_set_conv_nth set_to_list_size \n              by fastforce\n          next\n            case False\n            then have \"x \\<in> (remove_smallest A 1)\"\n              by (metis A3 DiffI One_nat_def atLeastAtMost_singleton empty_iff image_empty image_insert insertE remove_smallest_enum)\n            then have \"x \\<in> (set (set_to_list (remove_smallest A 1)))\"\n              by (metis A0 A1 IH One_nat_def add_diff_cancel_left' finite_subset plus_1_eq_Suc remove_smallest.simps(1) remove_smallest_card_finite remove_smallest_subset)\n            then show ?thesis \n              using A2 by blast\n          qed\n        qed\n      qed\n    qed\n  qed\n  assume \"finite A\"\n  then show \"set (set_to_list A) = A\"\n    using 0[of A \"card A\"]\n    by auto \nqed\n\nlemma set_to_list_inc[simp]:\n  assumes \"finite S\"\n  assumes \"card S = n\"\n  assumes \"j < n\"\n  assumes \"i < j\"\n  shows \"set_to_list S ! i < set_to_list S ! j\"\n  using assms(1) assms(2) assms(3) assms(4) \n  by auto\n\ndefinition rank :: \"nat set \\<Rightarrow> nat \\<Rightarrow> nat\" where\n\"rank A s = (THE j. j < card A \\<and> s = enum A j)\"\n\nlemma rank_enum:\n  assumes \"finite A\"\n  assumes \"card A = n\"\n  shows \"j < n \\<Longrightarrow> rank A (enum A j) = j\"\nproof-\n  assume A: \"j < n\"\n  have \"\\<And>k. k < n \\<Longrightarrow> (enum A j) = (enum A k) \\<Longrightarrow> k = j\"\n    by (metis \\<open>j < n\\<close> assms(1) assms(2) enumerate_order' less_irrefl less_linear less_not_refl2)\n  then show \"rank A (enum A j) = j\"\n    using A  the_equality[of \"(\\<lambda>k. k < card A \\<and> enum A j = enum A k)\" j] \n    unfolding rank_def\n    using assms(2) \n    by blast\nqed\n\nlemma enum_rank:\n  assumes \"finite A\"\n  assumes \"card A = n\"\n  assumes \"t \\<in> A\"\n  shows \"enum A (rank A t) = t\"\n  by (metis assms(1) assms(3) in_set_conv_nth rank_enum set_to_list_ind set_to_list_size set_to_list_to_set)\n\nlemma rank_bound[simp]:\n  assumes \"finite A\"\n  assumes \"card A = n\"\n  assumes \"a \\<in> A\"\n  shows  \"rank A a < n\"\n  by (metis assms(1) assms(2) assms(3) in_set_conv_nth rank_enum set_to_list_ind \n      set_to_list_size set_to_list_to_set)\n\nlemma set_to_list_induct:\n  assumes \"finite S\"\n  assumes \"\\<And>x. x \\<in>S \\<Longrightarrow> s > x\"\n  shows \"j < card S \\<Longrightarrow> enum S j = enum (insert s S) j\"\nproof(induction j)\n  case 0\n  then show ?case \n    by (metis assms(2) card_gt_0_iff empty_not_insert enumerate_in_A_0 insert_iff le_neq_implies_less linorder_not_le)\nnext\n  case (Suc j)\n  fix j\n  assume IH: \"(j < card S \\<Longrightarrow> enum S j = enum (insert s S) j)\"\n  assume A: \"Suc j < card S\"\n  show \" enum S (Suc j) = enum (insert s S) (Suc j)\"\n  proof-\n    have A0: \"enum S j = enum (insert s S) j\"\n      using IH A Suc_lessD\n      by blast\n    have A1: \"enum (insert s S) (Suc j) > enum S j\"\n      by (metis A Suc_lessD Suc_mono \\<open>enum S j = enum (insert s S) j\\<close> assms(1) \n          card_insert_disjoint enumerate_order insert_absorb)\n    have A2: \"enum (insert s S) (Suc j) \\<in> S\"\n      by (metis A Suc_lessD Suc_mono assms(1) assms(2) card_insert_disjoint \n          enumerate_in_set enumerate_order insertE less_asym')\n    obtain k where k_def: \"k = rank S  (enum (insert s S) (Suc j))\"\n      by simp\n    have k_j:\"k > j\"\n      using k_def A1 \n      by (metis A A2 Suc_lessD assms(1) enumerate_order' in_set_conv_nth not_less_iff_gr_or_eq \n        rank_enum set_to_list_ind set_to_list_size set_to_list_to_set)\n    have k_bound:\"k < card S\"\n      using A2 assms(1) k_def rank_bound by blast\n    have enum_k: \"enum S k = (enum (insert s S) (Suc j))\"\n      by (metis A2 assms(1) in_set_conv_nth k_def rank_enum set_to_list_ind \n            set_to_list_size set_to_list_to_set)\n    have \"k = Suc j\"\n    proof(rule ccontr)\n      assume B: \"k \\<noteq>Suc j\"\n      then have B0: \"k > Suc j\"\n        using Suc_lessI k_j \n        by blast\n      then have \"enum S k > enum S (Suc j)\"\n        by (simp add: k_bound)\n      then have \"enum (insert s S) (Suc j) > enum S (Suc j)\"\n        by (simp add: enum_k)\n      obtain t where t_def: \"t = enum S (Suc j)\"\n        by simp\n      obtain i where i_def: \"i = rank (insert s S) t\"\n        by simp\n      have \"i > j\"\n      proof(rule ccontr)\n        assume \"\\<not> j < i\"\n        then have \"enum (insert s S) i \\<le> enum (insert s S) j\"\n          by (metis A assms(1) card_insert_disjoint enumerate_order' insert_absorb \n              less_SucI less_or_eq_imp_le not_less_iff_gr_or_eq)\n        then have \"enum (insert s S) i \\<le> enum S j\"\n          using A0 by auto \n        then have \"t \\<le> enum S j\"\n          using enum_rank i_def \n          by (simp add: A assms(1) t_def)\n        then show False \n          using A enumerate_order leD t_def by blast\n      qed\n      then show False \n        by (metis A Suc_lessI \\<open>enum S (Suc j) < enum S k\\<close> assms(1) enum_k enum_rank \n            enumerate_in_set enumerate_order' finite.insertI i_def insert_iff less_asym'\n            rank_bound t_def)\n    qed\n    then show ?thesis \n      using enum_k by blast\n  qed\nqed\n     \nlemma set_to_list_induct':\n  assumes \"finite S\"\n  assumes \"\\<And>x. x \\<in> S \\<Longrightarrow>  s > x\"\n  shows \"set_to_list (insert s S) = (set_to_list S) @ [s]\"\nproof-     \n  obtain n where n_def[simp]: \"card S = n\"\n    by simp \n  have 0: \"take n (set_to_list (insert s S)) = take n (set_to_list S)\"\n  proof-\n    have \"\\<And>j. j < n \\<Longrightarrow> (set_to_list (insert s S))!j = (set_to_list S)!j\"\n      by (metis assms(1) assms(2) card_insert_disjoint finite.insertI insert_absorb \n          less_SucI n_def set_to_list_ind set_to_list_induct)      \n    then show ?thesis \n      by (metis (no_types, lifting) assms(1) card_insert_le finite.insertI length_take\n          lessI less_Suc_eq_le min.absorb2 n_def nth_equalityI nth_take set_to_list_size)\n  qed\n  have 1: \"set_to_list (insert s S)  = (take n (set_to_list (insert s S)))@[set_to_list (insert s S)!n]\"\n  by (metis Suc_leI assms(1) assms(2) card_insert_disjoint finite.insertI hd_drop_conv_nth \n      infinite_growing insert_absorb insert_not_empty lessI n_def set_to_list_size take_all\n      take_hd_drop)\n  have 2: \"s = set_to_list (insert s S)!n\"\n  by (smt \"0\" \"1\" assms(1) butlast_snoc card_insert_if finite.insertI in_set_conv_nth insertI1 \n      length_append_singleton lessI less_Suc_eq_le n_def nat_less_le nth_butlast set_to_list_size\n      set_to_list_to_set take_all)\n  then show ?thesis \n    using \"0\" \"1\" assms(1) set_to_list_size by auto\nqed\n\nlemma set_to_list_one:\n\"set_to_list {0} = [0]\"\n  by (metis card_empty card_insert_disjoint enumerate_in_set finite.insertI hd_Cons_tl \n      insert_absorb insert_not_empty lessI list.size(3) set_to_list_hd \n      set_to_list_size singletonD tl_id)\n\nlemma set_to_list_empty[simp]:\n\"set_to_list {} = []\"\n  using set_to_list_size by force\n\nlemma index_set_zero[simp]:\n\"index_set 0 = {}\"\n  using index_set_notmemI by blast\n\nlemma index_set_one[simp]: \n\"index_set 1 = {0}\"\n  using index_set_induct by auto\n\nlemma index_set_to_list_induct:\n\"set_to_list (index_set (Suc n)) = (set_to_list (index_set n))@[n]\"\n  apply(induction n)\n  using index_set_one set_to_list_one apply auto[1]\nproof-\n  fix n\n  assume IH: \"set_to_list (index_set (Suc n)) = set_to_list (index_set n) @ [n]\"\n  show \"set_to_list (index_set (Suc (Suc n))) = set_to_list (index_set (Suc n)) @ [Suc n]\"\n  proof-\n    have \"index_set (Suc (Suc n)) = (index_set (Suc n)) \\<union> {Suc n}\"\n      by (simp add: index_set_induct)\n    then show ?thesis\n      using set_to_list_induct' \n      by (metis IH Nil_is_append_conv Un_insert_right card_infinite index_list_length\n          index_set_notmemI length_0_conv length_map linorder_not_le not_Cons_self2 \n          set_to_list_def sup_bot.right_neutral)\n  qed\nqed\n    \nlemma index_set_to_list:\n  shows \"set_to_list (index_set n) = index_list n\"\n  apply(induction n)\n  using index_list_length apply fastforce\nproof-\n  fix n\n  assume IH: \"set_to_list (index_set n) = index_list n \"\n  show \"set_to_list (index_set (Suc n)) = index_list (Suc n)\"\n  proof-\n    have 0: \"set_to_list (index_set (Suc n)) = (index_list n) @ [n]\"\n      using IH index_set_to_list_induct[of n]\n      by auto\n    have 1: \"index_list (Suc n) = (index_list n) @ [n]\"\n    proof-\n      have 10: \"\\<And>j. j < Suc n \\<Longrightarrow>  index_list (Suc n) ! j= ((index_list n) @ [n]) ! j\"\n      proof-\n        fix j\n        assume A: \"j < Suc n\"\n        show \"index_list (Suc n) ! j= ((index_list n) @ [n]) ! j\"\n          apply(cases \"j < n\")\n           apply (simp add: index_list_index nth_append)\n          by (metis A index_list_index index_list_length less_SucE nth_append_length)\n      qed\n      have 11: \"length (index_list (Suc n)) = Suc n\"\n        by simp\n      have 12: \"length ((index_list n) @ [n]) = Suc n\"\n        by simp\n      then show ?thesis\n        by (metis \"10\" \"11\" nth_equalityI)\n    qed\n    then show ?thesis \n      by (simp add: \"0\")\n  qed\nqed\n    \n(*Insert a in list as at index n*)\nabbreviation initial_segment :: \"nat \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where\n\"initial_segment n as \\<equiv> take n as\"\n\nabbreviation final_segment :: \"nat \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where\n\"final_segment n as \\<equiv> drop n as\"\n\nlemma final_intitial_seg:\n\"as = (initial_segment n as) @ (final_segment n as)\"\n  by simp \n\ndefinition insert_at_ind :: \" 'a list \\<Rightarrow>'a \\<Rightarrow> nat \\<Rightarrow> 'a list\" where\n\"insert_at_ind as a n= (initial_segment n as) @ (a#(final_segment n as))\"\n\nlemma insert_at_ind_length:\n  assumes \"n \\<le> length as\"\n  shows \"length (insert_at_ind as a n) = length as + 1\"\n  by (simp add: insert_at_ind_def)\n\nlemma insert_at_ind_eq[simp]:\n  assumes \"n \\<le> length as\"\n  shows \"(insert_at_ind as a n)!n = a\"\n  unfolding insert_at_ind_def\n  using assms \n  by (metis length_take min.absorb2 nth_append_length)\n\nlemma insert_at_ind_eq'[simp]:\n  assumes \"n \\<le> length as\"\n  assumes \"k < n\"\n  shows \"(insert_at_ind as a n)!k = as ! k\"\n  using assms \n  unfolding insert_at_ind_def\n  by (simp add: nth_append)\n\nlemma insert_at_ind_eq''[simp]:\n  assumes \"n < length as\"\n  assumes \"k \\<le> n\"\n  shows \"(insert_at_ind as a k)!(Suc n) = as ! n\"\n  using assms \n  unfolding insert_at_ind_def\nproof(cases \"k < n\")\n  case T: True\n  have \"(insert_at_ind as a k)!n = (final_segment k as)! (n - (Suc k))\"\n    by (smt T Suc_diff_Suc assms(1) assms(2) diff_is_0_eq' insert_at_ind_def \n        length_take less_imp_le_nat less_numeral_extra(3) less_trans min.absorb2\n        nth_Cons_Suc nth_append zero_less_diff)\n  then show \"(initial_segment k as @ a # final_segment k as) ! Suc n = as ! n\"\n    using assms unfolding project_at_index_def \n    by (smt T Cons_nth_drop_Suc Suc_diff_Suc add_diff_cancel_left' diff_Suc_Suc id_take_nth_drop \n        length_take less_Suc_eq less_imp_le_nat less_trans min.absorb2 nth_Cons_pos nth_append \n        order_less_irrefl plus_1_eq_Suc zero_less_diff)\nnext\n  case False\n  then show \"(initial_segment k as @ a # final_segment k as) ! Suc n = as ! n\"\n    by (smt Cons_nth_drop_Suc Groups.add_ac(2) One_nat_def Suc_lessD add_diff_cancel_left'\n        assms(1) assms(2) le_neq_implies_less length_take less_imp_le_nat min.absorb2 nth_Cons_0\n        nth_Cons_Suc nth_append plus_1_eq_Suc)\nqed\n\n\n(*Given a set of indices, projects the input list to the sublist of elements  with those indices*)\nfun proj_at_index_list :: \"nat list \\<Rightarrow> 'a list \\<Rightarrow> 'a list\"  where \n\"proj_at_index_list [] as = []\"|\n\"proj_at_index_list (x#xs) as = (as!x)#(proj_at_index_list xs as)\"\n\ndefinition proj_at_indices where\n\"proj_at_indices S as = proj_at_index_list (set_to_list S) as\"\n\ntext\\<open>Correctness of proj_at_indices\\<close>\n\ndefinition indices_of :: \"'a list \\<Rightarrow> nat set\" where\n\"indices_of as = index_set (length as)\"\n\nlemma proj_at_index_listE:\n  assumes \"set L \\<subseteq> indices_of as\"\n  shows \"\\<And>i. i < length L \\<Longrightarrow> proj_at_index_list L as ! i = as ! (L ! i)\"\n  apply(induction L)\n   apply simp\nproof-\n  fix a L\n  fix i\n  assume IH: \" (\\<And>i. i < length L \\<Longrightarrow> proj_at_index_list L as ! i = as ! (L ! i))\"\n  assume \"i < length (a # L)\"\n  show \"proj_at_index_list (a # L) as ! i = as ! ((a # L) ! i)\"\n  proof(cases \"i = 0\")\n    case True\n    then show ?thesis \n      by simp \n  next\n    case False\n    then obtain k where k_def: \"i = Suc k\"\n      by (meson lessI less_Suc_eq_0_disj)\n    have 0: \"proj_at_index_list (a # L) as = (as! a)# (proj_at_index_list L as)\"\n      by simp\n    then have 1: \"proj_at_index_list (a # L) as ! i =  (proj_at_index_list L as) ! k\"\n      by (simp add: k_def)\n    then have 2: \"proj_at_index_list (a # L) as ! i =  as ! (L ! k)\"\n      using IH \\<open>i < length (a # L)\\<close> k_def by auto\n    then show ?thesis \n      by (simp add: k_def)\n  qed\nqed\n\nlemma proj_at_indicesE: \n  assumes \"S \\<subseteq> indices_of as\"\n  assumes \"i < card S\"\n  shows \" proj_at_indices S as ! i = as ! (enum S i)\"\nproof-\n  have 0: \"(enum S i) = (set_to_list S)!i\"\n    by (metis assms(2) card_infinite not_less0 set_to_list_ind)    \n  have 1: \"proj_at_index_list (set_to_list S) as ! i = as ! ((set_to_list S) ! i)\"  \n    using proj_at_index_listE \n    by (metis assms(1) assms(2) card_infinite not_less_zero set_to_list_size set_to_list_to_set)   \n  then show ?thesis \n    by (simp add: \"0\" proj_at_indices_def)\nqed\n\nlemma proj_at_index_list_length[simp]:\n  assumes \"set L \\<subseteq> indices_of as\"\n  shows \"length (proj_at_index_list L as) = length L\"\n  apply(induction L)\n  apply simp\n    by simp\n\nlemma proj_at_indices_length:\n  assumes \"S \\<subseteq> indices_of as\"\n  shows \"length (proj_at_indices S as) = card S\"\n  using assms \n  unfolding proj_at_indices_def\n  by (metis card_infinite empty_subsetI length_0_conv length_map list.set(1)\n      proj_at_index_list_length set_to_list_def set_to_list_empty set_to_list_size \n      set_to_list_to_set)\n\n(*Projects a list to the sublist of values not at the given index*)\ndefinition proj_away_from_index :: \"nat \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" (\"\\<pi>\\<^bsub>\\<noteq>_\\<^esub>\")where\n\"proj_away_from_index n as = (initial_segment n as)@(final_segment (Suc n) as)\"\n\ntext\\<open>proj_away_from_index is an inverse to insert_at_ind\\<close>\n\nlemma insert_at_ind_project_away[simp]:\n  assumes \"k < length as\"\n  assumes \"bs = (insert_at_ind as a k)\"\n  shows \"\\<pi>\\<^bsub>\\<noteq> k\\<^esub> bs = as\"\n  by (smt Cons_nth_drop_Suc One_nat_def add.right_neutral add_Suc_right append_eq_conv_conj\n      assms(1) assms(2)  insert_at_ind_def insert_at_ind_length length_take less_Suc_eq \n      less_imp_le_nat less_trans list.inject min.absorb2 proj_away_from_index_def)\n\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_ind 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_ind 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) assms(2) insert_at_ind_length)\nqed\n\nlemma project_fibred_cell[simp]:\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_ind 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 fastforce\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. initial_segment n as @ (a::'a) # final_segment n as \\<notin> A \\<or> as \\<in> \\<pi>\\<^bsub>\\<noteq>n\\<^esub> ` A \\<or> \\<not> n < length as\"\n        by (metis (no_types) imageI insert_at_ind_def insert_at_ind_project_away)\n      have \"\\<forall>n. \\<exists>as a. initial_segment n x @ t # final_segment n x = insert_at_ind as a n \\<and> as \\<in> C \\<and> P as a\"\n        by (metis (full_types) A insert_at_ind_def t_def)\n      then have \"\\<forall>n. initial_segment n x @ t # final_segment n x \\<in> {insert_at_ind 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_ind 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\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/indices.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9184802440252811, "lm_q2_score": 0.815232489352, "lm_q1q2_score": 0.7487749357573623}}
{"text": "   \ntheory Re1\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\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\nsection {* Regular Expressions *}\n\ndatatype rexp =\n  NULL\n| EMPTY\n| CHAR char\n| SEQ rexp rexp\n| ALT rexp rexp\n\nfun SEQS :: \"rexp \\<Rightarrow> rexp list \\<Rightarrow> rexp\"\nwhere\n  \"SEQS r [] = r\"\n| \"SEQS r (r'#rs) = SEQ r (SEQS r' rs)\"\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\nfun zeroable where\n  \"zeroable NULL = True\"\n| \"zeroable EMPTY = False\"\n| \"zeroable (CHAR c) = False\"\n| \"zeroable (ALT r1 r2) = (zeroable r1 \\<and> zeroable r2)\"\n| \"zeroable (SEQ r1 r2) = (zeroable r1 \\<or> zeroable r2)\"\n\nlemma L_ALT_cases:\n  \"L (ALT r1 r2) \\<noteq> {} \\<Longrightarrow> (L r1 \\<noteq> {}) \\<or> (L r1 = {} \\<and> L r2 \\<noteq> {})\"\nby(auto)\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\nlemma nullable_correctness:\n  shows \"nullable r  \\<longleftrightarrow> [] \\<in> (L r)\"\napply (induct r) \napply(auto simp add: Sequ_def) \ndone\n\nsection {* Values *}\n\ndatatype val = \n  Void\n| Char char\n| Seq val val\n| Right val\n| Left val\n\n\nfun Seqs :: \"val \\<Rightarrow> val list \\<Rightarrow> val\"\nwhere\n  \"Seqs v [] = v\"\n| \"Seqs v (v'#vs) = Seqs (Seq v v') vs\"\n\nsection {* The string behind a value *}\n\nfun 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\nfun flats :: \"val \\<Rightarrow> string list\"\nwhere\n  \"flats(Void) = [[]]\"\n| \"flats(Char c) = [[c]]\"\n| \"flats(Left v) = flats(v)\"\n| \"flats(Right v) = flats(v)\"\n| \"flats(Seq v1 v2) = (flats v1) @ (flats v2)\"\n\nvalue \"flats(Seq(Char c)(Char b))\"\n\nsection {* Relation between values and regular expressions *}\n\n\ninductive Prfs :: \"string \\<Rightarrow> val \\<Rightarrow> rexp \\<Rightarrow> bool\" (\"\\<Turnstile>_ _ : _\" [100, 100, 100] 100)\nwhere\n \"\\<lbrakk>\\<Turnstile>s1 v1 : r1; \\<Turnstile>s2 v2 : r2\\<rbrakk> \\<Longrightarrow> \\<Turnstile>(s1 @ s2) (Seq v1 v2) : SEQ r1 r2\"\n| \"\\<Turnstile>s v1 : r1 \\<Longrightarrow> \\<Turnstile>s (Left v1) : ALT r1 r2\"\n| \"\\<Turnstile>s v2 : r2 \\<Longrightarrow> \\<Turnstile>s (Right v2) : ALT r1 r2\"\n| \"\\<Turnstile>[] Void : EMPTY\"\n| \"\\<Turnstile>[c] (Char c) : CHAR c\"\n\nlemma Prfs_flat:\n  \"\\<Turnstile>s v : r \\<Longrightarrow> flat v = s\"\napply(induct s v r rule: Prfs.induct)\napply(auto)\ndone\n\ninductive Prfn :: \"nat \\<Rightarrow> val \\<Rightarrow> rexp \\<Rightarrow> bool\" (\"\\<TTurnstile>_ _ : _\" [100, 100, 100] 100)\nwhere\n \"\\<lbrakk>\\<TTurnstile>n1 v1 : r1; \\<TTurnstile>n2 v2 : r2\\<rbrakk> \\<Longrightarrow> \\<TTurnstile>(n1 + n2) (Seq v1 v2) : SEQ r1 r2\"\n| \"\\<TTurnstile>n v1 : r1 \\<Longrightarrow> \\<TTurnstile>n (Left v1) : ALT r1 r2\"\n| \"\\<TTurnstile>n v2 : r2 \\<Longrightarrow> \\<TTurnstile>n (Right v2) : ALT r1 r2\"\n| \"\\<TTurnstile>0 Void : EMPTY\"\n| \"\\<TTurnstile>1 (Char c) : CHAR c\"\n\nlemma Prfn_flat:\n  \"\\<TTurnstile>n v : r \\<Longrightarrow> length (flat v) = n\"\napply(induct rule: Prfn.induct)\napply(auto)\ndone\n\ninductive 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\nlemma Prf_Prfn:\n  shows \"\\<turnstile> v : r \\<Longrightarrow> \\<TTurnstile>(length (flat v)) v : r\"\napply(induct v r rule: Prf.induct)\napply(auto intro: Prfn.intros)\nby (metis One_nat_def Prfn.intros(5))\n\nlemma Prfn_Prf:\n  shows \"\\<TTurnstile>n v : r \\<Longrightarrow> \\<turnstile> v : r\"\napply(induct n v r rule: Prfn.induct)\napply(auto intro: Prf.intros)\ndone\n\nlemma Prf_Prfs:\n  shows \"\\<turnstile> v : r \\<Longrightarrow> \\<Turnstile>(flat v) v : r\"\napply(induct v r rule: Prf.induct)\napply(auto intro: Prfs.intros)\ndone\n\nlemma Prfs_Prf:\n  shows \"\\<Turnstile>s v : r \\<Longrightarrow> \\<turnstile> v : r\"\napply(induct s v r rule: Prfs.induct)\napply(auto intro: Prf.intros)\ndone\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\n\nfun 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\nlemma mkeps_nullable:\n  assumes \"nullable(r)\" shows \"\\<turnstile> mkeps r : r\"\nusing assms\napply(induct rule: nullable.induct)\napply(auto intro: Prf.intros)\ndone\n\nlemma mkeps_nullable_n:\n  assumes \"nullable(r)\" shows \"\\<TTurnstile>0 (mkeps r) : r\"\nusing assms\napply(induct rule: nullable.induct)\napply(auto intro: Prfn.intros)\napply(drule Prfn.intros(1))\napply(assumption)\napply(simp)\ndone\n\nlemma mkeps_nullable_s:\n  assumes \"nullable(r)\" shows \"\\<Turnstile>[] (mkeps r) : r\"\nusing assms\napply(induct rule: nullable.induct)\napply(auto intro: Prfs.intros)\napply(drule Prfs.intros(1))\napply(assumption)\napply(simp)\ndone\n\nlemma mkeps_flat:\n  assumes \"nullable(r)\" shows \"flat (mkeps r) = []\"\nusing assms\napply(induct rule: nullable.induct)\napply(auto)\ndone\n\ntext {*\n  The value mkeps returns is always the correct POSIX\n  value.\n*}\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 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)\ndone\n\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\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 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\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 rest :: \"val \\<Rightarrow> string \\<Rightarrow> string\" where\n  \"rest v s \\<equiv> drop (length (flat v)) s\"\n\nlemma rest_Suffixes:\n  \"rest v s \\<in> Suffixes s\"\nunfolding rest_def\nby (metis Suffixes_in append_take_drop_id)\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)}\"\nunfolding Values_def\napply(auto)\n(*NULL*)\napply(erule Prf.cases)\napply(simp_all)[5]\n(*EMPTY*)\napply(erule Prf.cases)\napply(simp_all)[5]\napply(rule Prf.intros)\napply (metis append_Nil prefix_def)\n(*CHAR*)\napply(erule Prf.cases)\napply(simp_all)[5]\napply(rule Prf.intros)\napply(erule Prf.cases)\napply(simp_all)[5]\n(*ALT*)\napply(erule Prf.cases)\napply(simp_all)[5]\napply (metis Prf.intros(2))\napply (metis Prf.intros(3))\n(*SEQ*)\napply(erule Prf.cases)\napply(simp_all)[5]\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)\ndone\n\nlemma Values_finite:\n  \"finite (Values r s)\"\napply(induct r arbitrary: s)\napply(simp_all add: Values_recs)\nthm finite_surj\napply(rule_tac f=\"\\<lambda>(x, y). Seq x y\" and \n               A=\"{(v1, v2) | v1 v2. v1 \\<in> Values r1 s \\<and> v2 \\<in> Values r2 (rest v1 s)}\" in finite_surj)\nprefer 2\napply(auto)[1]\napply(rule_tac B=\"\\<Union>sp \\<in> Suffixes s. {(v1, v2). v1 \\<in> Values r1 s \\<and> v2 \\<in> Values r2 sp}\" in finite_subset)\napply(auto)[1]\napply (metis rest_Suffixes)\napply(rule finite_UN_I)\napply(rule finite_Suffixes)\napply(simp)\ndone\n\nsection {* Greedy Ordering according to Frisch/Cardelli *}\n\ninductive GrOrd :: \"val \\<Rightarrow> val \\<Rightarrow> bool\" (\"_ \\<prec> _\")\nwhere \n  \"v1 \\<prec> v1' \\<Longrightarrow> (Seq v1 v2) \\<prec> (Seq v1' v2')\"\n| \"v2 \\<prec> v2' \\<Longrightarrow> (Seq v1 v2) \\<prec> (Seq v1 v2')\"\n| \"v1 \\<prec> v2 \\<Longrightarrow> (Left v1) \\<prec> (Left v2)\"\n| \"v1 \\<prec> v2 \\<Longrightarrow> (Right v1) \\<prec> (Right v2)\"\n| \"(Right v1) \\<prec> (Left v2)\"\n| \"(Char c) \\<prec> (Char c)\"\n| \"(Void) \\<prec> (Void)\"\n\nlemma Gr_refl:\n  assumes \"\\<turnstile> v : r\"\n  shows \"v \\<prec> v\"\nusing assms\napply(induct)\napply(auto intro: GrOrd.intros)\ndone\n\nlemma Gr_total:\n  assumes \"\\<turnstile> v1 : r\" \"\\<turnstile> v2 : r\"\n  shows \"v1 \\<prec> v2 \\<or> v2 \\<prec> v1\"\nusing assms\napply(induct v1 r arbitrary: v2 rule: Prf.induct)\napply(rotate_tac 4)\napply(erule Prf.cases)\napply(simp_all)[5]\napply(clarify)\napply (metis GrOrd.intros(1) GrOrd.intros(2))\napply(rotate_tac 2)\napply(erule Prf.cases)\napply(simp_all)\napply(clarify)\napply (metis GrOrd.intros(3))\napply(clarify)\napply (metis GrOrd.intros(5))\napply(rotate_tac 2)\napply(erule Prf.cases)\napply(simp_all)\napply(clarify)\napply (metis GrOrd.intros(5))\napply(clarify)\napply (metis GrOrd.intros(4))\napply(erule Prf.cases)\napply(simp_all)\napply (metis GrOrd.intros(7))\napply(erule Prf.cases)\napply(simp_all)\napply (metis GrOrd.intros(6))\ndone\n\nlemma Gr_trans: \n  assumes \"v1 \\<prec> v2\" \"v2 \\<prec> v3\" \"\\<turnstile> v1 : r\" \"\\<turnstile> v2 : r\" \"\\<turnstile> v3 : r\"\n  shows \"v1 \\<prec> v3\"\nusing assms\napply(induct r arbitrary: v1 v2 v3)\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]\ndefer\n(* ALT case *)\napply(erule Prf.cases)\napply(simp_all (no_asm_use))[5]\napply(erule Prf.cases)\napply(simp_all (no_asm_use))[5]\napply(erule Prf.cases)\napply(simp_all (no_asm_use))[5]\napply(clarify)\napply(erule GrOrd.cases)\napply(simp_all (no_asm_use))[7]\napply(erule GrOrd.cases)\napply(simp_all (no_asm_use))[7]\napply (metis GrOrd.intros(3))\napply(clarify)\napply(erule GrOrd.cases)\napply(simp_all (no_asm_use))[7]\napply(erule GrOrd.cases)\napply(simp_all (no_asm_use))[7]\napply(erule Prf.cases)\napply(simp_all (no_asm_use))[5]\napply(clarify)\napply(erule GrOrd.cases)\napply(simp_all (no_asm_use))[7]\napply(clarify)\napply(erule GrOrd.cases)\napply(simp_all (no_asm_use))[7]\napply(erule Prf.cases)\napply(simp_all (no_asm_use))[5]\napply(erule Prf.cases)\napply(simp_all (no_asm_use))[5]\napply(clarify)\napply(erule GrOrd.cases)\napply(simp_all (no_asm_use))[7]\napply(erule GrOrd.cases)\napply(simp_all (no_asm_use))[7]\napply (metis GrOrd.intros(5))\napply(clarify)\napply(erule GrOrd.cases)\napply(simp_all (no_asm_use))[7]\napply(erule GrOrd.cases)\napply(simp_all (no_asm_use))[7]\napply(erule Prf.cases)\napply(simp_all (no_asm_use))[5]\napply(clarify)\napply(erule GrOrd.cases)\napply(simp_all (no_asm_use))[7]\napply(erule GrOrd.cases)\napply(simp_all (no_asm_use))[7]\napply (metis GrOrd.intros(5))\napply(clarify)\napply(erule GrOrd.cases)\napply(simp_all (no_asm_use))[7]\napply(erule GrOrd.cases)\napply(simp_all (no_asm_use))[7]\napply (metis GrOrd.intros(4))\n(* seq case *)\napply(erule Prf.cases)\napply(simp_all (no_asm_use))[5]\napply(erule Prf.cases)\napply(simp_all (no_asm_use))[5]\napply(erule Prf.cases)\napply(simp_all (no_asm_use))[5]\napply(clarify)\napply(erule GrOrd.cases)\napply(simp_all (no_asm_use))[7]\napply(erule GrOrd.cases)\napply(simp_all (no_asm_use))[7]\napply(clarify)\napply (metis GrOrd.intros(1))\napply (metis GrOrd.intros(1))\napply(erule GrOrd.cases)\napply(simp_all (no_asm_use))[7]\napply (metis GrOrd.intros(1))\nby (metis GrOrd.intros(1) Gr_refl)\n\ndefinition\n  GrMaxM :: \"val set => val\" where\n  \"GrMaxM S == SOME v.  v \\<in> S \\<and> (\\<forall>v' \\<in> S. v' \\<prec> v)\"\n\ndefinition\n  \"GrMax r s \\<equiv> GrMaxM {v. \\<turnstile> v : r \\<and> flat v = s}\"\n\ninductive ValOrd3 :: \"val \\<Rightarrow> val \\<Rightarrow> bool\" (\"_ 3\\<succ> _\" [100, 100] 100)\nwhere\n  \"v2 3\\<succ> v2' \\<Longrightarrow> (Seq v1 v2) 3\\<succ> (Seq v1 v2')\" \n| \"v1 3\\<succ> v1' \\<Longrightarrow> (Seq v1 v2) 3\\<succ> (Seq v1' v2')\" \n| \"length (flat v1) \\<ge> length (flat v2) \\<Longrightarrow> (Left v1) 3\\<succ> (Right v2)\"\n| \"length (flat v2) > length (flat v1) \\<Longrightarrow> (Right v2) 3\\<succ> (Left v1)\"\n| \"v2 3\\<succ> v2' \\<Longrightarrow> (Right v2) 3\\<succ> (Right v2')\"\n| \"v1 3\\<succ> v1' \\<Longrightarrow> (Left v1) 3\\<succ> (Left v1')\"\n| \"Void 3\\<succ> Void\"\n| \"(Char c) 3\\<succ> (Char c)\"\n\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\ninductive ValOrdStr :: \"string \\<Rightarrow> val \\<Rightarrow> val \\<Rightarrow> bool\" (\"_ \\<turnstile> _ \\<succ>_\" [100, 100, 100] 100)\nwhere\n  \"\\<lbrakk>s \\<turnstile> v1 \\<succ> v1'; rest v1 s \\<turnstile> v2 \\<succ> v2'\\<rbrakk> \\<Longrightarrow> s \\<turnstile> (Seq v1 v2) \\<succ> (Seq v1' v2')\" \n| \"\\<lbrakk>flat v2 \\<sqsubseteq> flat v1; flat v1 \\<sqsubseteq> s\\<rbrakk> \\<Longrightarrow> s \\<turnstile> (Left v1) \\<succ> (Right v2)\"\n| \"\\<lbrakk>flat v1 \\<sqsubset> flat v2; flat v2 \\<sqsubseteq> s\\<rbrakk> \\<Longrightarrow> s \\<turnstile> (Right v2) \\<succ> (Left v1)\"\n| \"s \\<turnstile> v2 \\<succ> v2' \\<Longrightarrow> s \\<turnstile> (Right v2) \\<succ> (Right v2')\"\n| \"s \\<turnstile> v1 \\<succ> v1' \\<Longrightarrow> s \\<turnstile> (Left v1) \\<succ> (Left v1')\"\n| \"s \\<turnstile> Void \\<succ> Void\"\n| \"(c#s) \\<turnstile> (Char c) \\<succ> (Char c)\"\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\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 \n  \"flat Void = []\"\n  \"flat (Seq Void Void) = []\"\napply(simp_all)\ndone\n\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 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(*\ninductive ValOrd3 :: \"val \\<Rightarrow> rexp \\<Rightarrow> val \\<Rightarrow> bool\" (\"_ 3\\<succ>_ _\" [100, 100, 100] 100)\nwhere\n  \"\\<lbrakk>v2 3\\<succ>r2 v2'; \\<turnstile> v1 : r1\\<rbrakk> \\<Longrightarrow> (Seq v1 v2) 3\\<succ>(SEQ r1 r2) (Seq v1 v2')\" \n| \"\\<lbrakk>v1 3\\<succ>r1 v1'; v1 \\<noteq> v1'; flat v2 = flat v2'; \\<turnstile> v2 : r2; \\<turnstile> v2' : r2\\<rbrakk> \n      \\<Longrightarrow> (Seq v1 v2) 3\\<succ>(SEQ r1 r2) (Seq v1' v2')\" \n| \"length (flat v1) \\<ge> length (flat v2) \\<Longrightarrow> (Left v1) 3\\<succ>(ALT r1 r2) (Right v2)\"\n| \"length (flat v2) > length (flat v1) \\<Longrightarrow> (Right v2) 3\\<succ>(ALT r1 r2) (Left v1)\"\n| \"v2 3\\<succ>r2 v2' \\<Longrightarrow> (Right v2) 3\\<succ>(ALT r1 r2) (Right v2')\"\n| \"v1 3\\<succ>r1 v1' \\<Longrightarrow> (Left v1) 3\\<succ>(ALT r1 r2) (Left v1')\"\n| \"Void 3\\<succ>EMPTY Void\"\n| \"(Char c) 3\\<succ>(CHAR c) (Char c)\"\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\ndefinition POSIXs :: \"val \\<Rightarrow> rexp \\<Rightarrow> string \\<Rightarrow> bool\" \nwhere\n  \"POSIXs v r s \\<equiv> (\\<Turnstile>s v : r \\<and> (\\<forall>v'. (\\<Turnstile>s v' : r \\<longrightarrow> v 2\\<succ> v')))\"\n\ndefinition POSIXn :: \"val \\<Rightarrow> rexp \\<Rightarrow> nat \\<Rightarrow> bool\" \nwhere\n  \"POSIXn v r n \\<equiv> (\\<TTurnstile>n v : r \\<and> (\\<forall>v'. (\\<TTurnstile>n v' : r \\<longrightarrow> v 2\\<succ> v')))\"\n\nlemma \"POSIXn v r (length (flat v)) \\<Longrightarrow> POSIX2 v r\"\nunfolding POSIXn_def POSIX2_def\napply(auto)\napply (metis Prfn_Prf)\nby (metis Prf_Prfn)\n\nlemma Prfs_POSIX:\n  \"POSIXs v r s \\<Longrightarrow> \\<Turnstile>s v: r \\<and> flat v = s\"\napply(simp add: POSIXs_def)\nby (metis Prfs_flat)\n\n\nlemma \"POSIXs v r (flat v) =  POSIX2 v r\"\nunfolding POSIXs_def POSIX2_def\napply(auto)\napply (metis Prfs_Prf)\napply (metis Prf_Prfs)\napply (metis Prf_Prfs)\nby (metis Prfs_Prf Prfs_flat)\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 POSIXn_SEQ1:\n  assumes \"POSIXn (Seq v1 v2) (SEQ r1 r2) (n1 + n2)\" \"\\<TTurnstile>n1 v1 : r1\" \"\\<TTurnstile>n2 v2 : r2\"\n  shows \"POSIXn v1 r1 n1\"\nusing assms\nunfolding POSIXn_def\napply(auto)\napply(drule_tac x=\"Seq v' v2\" in spec)\napply(erule impE)\napply(rule Prfn.intros)\napply(simp)\napply(simp)\napply(erule ValOrd2.cases)\napply(simp_all)\napply(clarify)\nby (metis Ord1 Prfn_Prf ValOrd_refl)\n\nlemma POSIXs_SEQ1:\n  assumes \"POSIXs (Seq v1 v2) (SEQ r1 r2) (s1 @ s2)\" \"\\<Turnstile>s1 v1 : r1\" \"\\<Turnstile>s2 v2 : r2\"\n  shows \"POSIXs v1 r1 s1\"\nusing assms\nunfolding POSIXs_def\napply(auto)\napply(drule_tac x=\"Seq v' v2\" in spec)\napply(erule impE)\napply(rule Prfs.intros)\napply(simp)\napply(simp)\napply(erule ValOrd2.cases)\napply(simp_all)\napply(clarify)\nby (metis Ord1 Prfs_Prf 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 POSIXn_SEQ2:\n  assumes \"POSIXn (Seq v1 v2) (SEQ r1 r2) (n1 + n2)\" \"\\<TTurnstile>n1 v1 : r1\" \"\\<TTurnstile>n2 v2 : r2\" \n  shows \"POSIXn v2 r2 n2\"\nusing assms\nunfolding POSIXn_def\napply(auto)\napply(drule_tac x=\"Seq v1 v'\" in spec)\napply(erule impE)\napply(rule Prfn.intros)\napply(simp)\napply(simp)\napply(erule ValOrd2.cases)\napply(simp_all)\ndone\n\nlemma POSIXs_SEQ2:\n  assumes \"POSIXs (Seq v1 v2) (SEQ r1 r2) (s1 @ s2)\" \"\\<Turnstile>s1 v1 : r1\" \"\\<Turnstile>s2 v2 : r2\" \n  shows \"POSIXs v2 r2 s2\"\nusing assms\nunfolding POSIXs_def\napply(auto)\napply(drule_tac x=\"Seq v1 v'\" in spec)\napply(erule impE)\napply(rule Prfs.intros)\napply(simp)\napply(simp)\napply(erule ValOrd2.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 POSIXn_ALT2:\n  assumes \"POSIXn (Left v1) (ALT r1 r2) n\"\n  shows \"POSIXn v1 r1 n\"\nusing assms\nunfolding POSIXn_def\napply(auto)\napply(erule Prfn.cases)\napply(simp_all)[5]\napply(drule_tac x=\"Left v'\" in spec)\napply(drule mp)\napply(rule Prfn.intros)\napply(auto)\napply(erule ValOrd2.cases)\napply(simp_all)\ndone\n\nlemma POSIXs_ALT2:\n  assumes \"POSIXs (Left v1) (ALT r1 r2) s\"\n  shows \"POSIXs v1 r1 s\"\nusing assms\nunfolding POSIXs_def\napply(auto)\napply(erule Prfs.cases)\napply(simp_all)[5]\napply(drule_tac x=\"Left v'\" in spec)\napply(drule mp)\napply(rule Prfs.intros)\napply(auto)\napply(erule ValOrd2.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 POSIXn_ALT1a:\n  assumes \"POSIXn (Right v2) (ALT r1 r2) n\"\n  shows \"POSIXn v2 r2 n\"\nusing assms\nunfolding POSIXn_def\napply(auto)\napply(erule Prfn.cases)\napply(simp_all)[5]\napply(drule_tac x=\"Right v'\" in spec)\napply(drule mp)\napply(rule Prfn.intros)\napply(auto)\napply(erule ValOrd2.cases)\napply(simp_all)\ndone\n\nlemma POSIXs_ALT1a:\n  assumes \"POSIXs (Right v2) (ALT r1 r2) s\"\n  shows \"POSIXs v2 r2 s\"\nusing assms\nunfolding POSIXs_def\napply(auto)\napply(erule Prfs.cases)\napply(simp_all)[5]\napply(drule_tac x=\"Right v'\" in spec)\napply(drule mp)\napply(rule Prfs.intros)\napply(auto)\napply(erule ValOrd2.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 POSIXn_ALT1b:\n  assumes \"POSIXn (Right v2) (ALT r1 r2) n\"\n  shows \"(\\<forall>v'. (\\<TTurnstile>n v' : r2 \\<longrightarrow> v2 2\\<succ> v'))\"\nusing assms\napply(drule_tac POSIXn_ALT1a)\nunfolding POSIXn_def\napply(auto)\ndone\n\nlemma POSIXs_ALT1b:\n  assumes \"POSIXs (Right v2) (ALT r1 r2) s\"\n  shows \"(\\<forall>v'. (\\<Turnstile>s v' : r2 \\<longrightarrow> v2 2\\<succ> v'))\"\nusing assms\napply(drule_tac POSIXs_ALT1a)\nunfolding POSIXs_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 POSIXn_ALT_I1:\n  assumes \"POSIXn v1 r1 n\" \n  shows \"POSIXn (Left v1) (ALT r1 r2) n\"\nusing assms\nunfolding POSIXn_def\napply(auto)\napply (metis Prfn.intros(2))\napply(rotate_tac 2)\napply(erule Prfn.cases)\napply(simp_all)[5]\napply(auto)\napply(rule ValOrd2.intros)\napply(auto)\napply(rule ValOrd2.intros)\nby (metis Prfn_flat order_refl)\n\nlemma POSIXs_ALT_I1:\n  assumes \"POSIXs v1 r1 s\" \n  shows \"POSIXs (Left v1) (ALT r1 r2) s\"\nusing assms\nunfolding POSIXs_def\napply(auto)\napply (metis Prfs.intros(2))\napply(rotate_tac 2)\napply(erule Prfs.cases)\napply(simp_all)[5]\napply(auto)\napply(rule ValOrd2.intros)\napply(auto)\napply(rule ValOrd2.intros)\nby (metis Prfs_flat order_refl)\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 POSIXs_ALT_I2:\n  assumes \"POSIXs v2 r2 s\" \"\\<forall>s' v'. \\<Turnstile>s' v' : r1 \\<longrightarrow> length s > length s'\"\n  shows \"POSIXs (Right v2) (ALT r1 r2) s\"\nusing assms\nunfolding POSIXs_def\napply(auto)\napply (metis Prfs.intros)\napply(rotate_tac 3)\napply(erule Prfs.cases)\napply(simp_all)[5]\napply(auto)\napply(rule ValOrd2.intros)\napply metis\ndone\n\nlemma \n  \"\\<lbrakk>POSIX (mkeps r2) r2; nullable r2; \\<not> nullable r1\\<rbrakk>\n   \\<Longrightarrow> POSIX (Right (mkeps r2)) (ALT r1 r2)\" \napply(auto simp add: POSIX_def)\napply(rule Prf.intros(3))\napply(auto)\napply(rotate_tac 3)\napply(erule Prf.cases)\napply(simp_all)[5]\napply(simp add: mkeps_flat)\napply(auto)[1]\napply (metis Prf_flat_L nullable_correctness)\napply(rule ValOrd.intros)\napply(auto)\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\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\nfun \n ders :: \"string \\<Rightarrow> rexp \\<Rightarrow> rexp\"\nwhere\n  \"ders [] r = r\"\n| \"ders (c # s) r = ders s (der c r)\"\n\nfun\n red :: \"char \\<Rightarrow> rexp \\<Rightarrow> rexp\"\nwhere\n  \"red c (NULL) = NULL\"\n| \"red c (EMPTY) = CHAR c\"\n| \"red c (CHAR c') = SEQ (CHAR c) (CHAR c')\"\n| \"red c (ALT r1 r2) = ALT (red c r1) (red c r2)\"\n| \"red c (SEQ r1 r2) = \n     (if nullable r1\n      then ALT (SEQ (red c r1) r2) (red c r2)\n      else SEQ (red c r1) r2)\"\n\nlemma L_der:\n  shows \"L (der c r) = {s. c#s \\<in> L r}\"\napply(induct r)\napply(simp_all)\napply(simp add: Sequ_def)\napply(auto)[1]\napply (metis append_Cons)\napply (metis append_Nil nullable_correctness)\napply (metis append_eq_Cons_conv)\napply (metis append_Cons)\napply (metis Cons_eq_append_conv nullable_correctness)\napply(auto)\ndone\n\nlemma L_red:\n  shows \"L (red c r) = {c#s | s. s \\<in> L r}\"\napply(induct r)\napply(simp_all)\napply(simp add: Sequ_def)\napply(simp add: Sequ_def)\napply(auto)[1]\napply (metis append_Nil nullable_correctness)\napply (metis append_Cons)\napply (metis append_Cons)\napply(auto)\ndone\n\nlemma L_red_der:\n  \"L(red c (der c r)) = {c#s | s. c#s \\<in> L r}\"\napply(simp add: L_red)\napply(simp add: L_der)\ndone\n\nlemma L_der_red:\n  \"L(der c (red c r)) = L r\"\napply(simp add: L_der)\napply(simp add: L_red)\ndone\n\nsection {* Injection function *}\n\nfun injval :: \"rexp \\<Rightarrow> char \\<Rightarrow> val \\<Rightarrow> val\"\nwhere\n  \"injval (EMPTY) c Void = Char c\"\n| \"injval (CHAR d) c Void = Char d\"\n| \"injval (CHAR d) c (Char c') = Seq (Char d) (Char c')\"\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 (Char c') = Seq (Char c) (Char c')\"\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\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\ntext {*\n  Injection value is related to r\n*}\n\nlemma v3:\n  assumes \"\\<turnstile> v : der c r\" 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)[5]\napply(simp)\napply(erule Prf.cases)\napply(simp_all)[5]\napply(case_tac \"c = c'\")\napply(simp)\napply(erule Prf.cases)\napply(simp_all)[5]\napply (metis Prf.intros(5))\napply(simp)\napply(erule Prf.cases)\napply(simp_all)[5]\napply(simp)\napply(erule Prf.cases)\napply(simp_all)[5]\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)[5]\napply(auto)[1]\napply(erule Prf.cases)\napply(simp_all)[5]\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)[5]\napply(auto)[1]\napply(rule Prf.intros)\napply(auto)[2]\ndone\n\nlemma v3_red:\n  assumes \"\\<turnstile> v : r\" shows \"\\<turnstile> (injval (red c r) c v) : (red c r)\"\nusing assms\napply(induct c r arbitrary: v rule: red.induct)\napply(simp)\napply(erule Prf.cases)\napply(simp_all)[5]\napply(simp)\napply(erule Prf.cases)\napply(simp_all)[5]\napply (metis Prf.intros(5))\napply(erule Prf.cases)\napply(simp_all)[5]\napply (metis Prf.intros(1) Prf.intros(5))\napply(erule Prf.cases)\napply(simp_all)[5]\napply (metis Prf.intros(2))\napply (metis Prf.intros(3))\napply(erule Prf.cases)\napply(simp_all)[5]\napply(auto)\nprefer 2\napply (metis Prf.intros(1))\noops\n\nlemma v3s:\n  assumes \"\\<Turnstile>s v : der c r\" shows \"\\<Turnstile>(c#s) (injval r c v) : r\"\nusing assms\napply(induct arbitrary: s v rule: der.induct)\napply(simp)\napply(erule Prfs.cases)\napply(simp_all)[5]\napply(simp)\napply(erule Prfs.cases)\napply(simp_all)[5]\napply(case_tac \"c = c'\")\napply(simp)\napply(erule Prfs.cases)\napply(simp_all)[5]\napply (metis Prfs.intros(5))\napply(simp)\napply(erule Prfs.cases)\napply(simp_all)[5]\napply(simp)\napply(erule Prfs.cases)\napply(simp_all)[5]\napply (metis Prfs.intros(2))\napply (metis Prfs.intros(3))\napply(simp)\napply(case_tac \"nullable r1\")\napply(simp)\napply(erule Prfs.cases)\napply(simp_all)[5]\napply(auto)[1]\napply(erule Prfs.cases)\napply(simp_all)[5]\napply(auto)[1]\napply (metis Prfs.intros(1) append_Cons)\napply(auto)[1]\napply (metis Prfs.intros(1) append_Nil mkeps_nullable_s)\napply(simp)\napply(erule Prfs.cases)\napply(simp_all)[5]\napply(auto)[1]\nby (metis Prfs.intros(1) append_Cons)\n\nlemma v3n:\n  assumes \"\\<TTurnstile>n v : der c r\" shows \"\\<TTurnstile>(Suc n) (injval r c v) : r\"\nusing assms\napply(induct arbitrary: n v rule: der.induct)\napply(simp)\napply(erule Prfn.cases)\napply(simp_all)[5]\napply(simp)\napply(erule Prfn.cases)\napply(simp_all)[5]\napply(case_tac \"c = c'\")\napply(simp)\napply(erule Prfn.cases)\napply(simp_all)[5]\napply (metis One_nat_def Prfn.intros(5))\napply(simp)\napply(erule Prfn.cases)\napply(simp_all)[5]\napply(simp)\napply(erule Prfn.cases)\napply(simp_all)[5]\napply (metis Prfn.intros(2))\napply (metis Prfn.intros(3))\napply(simp)\napply(case_tac \"nullable r1\")\napply(simp)\napply(erule Prfn.cases)\napply(simp_all)[5]\napply(auto)[1]\napply(erule Prfn.cases)\napply(simp_all)[5]\napply(auto)[1]\napply (metis Prfn.intros(1) add.commute add_Suc_right)\napply(auto)[1]\napply (metis Prfn.intros(1) mkeps_nullable_n plus_nat.add_0)\napply(simp)\napply(erule Prfn.cases)\napply(simp_all)[5]\napply(auto)[1]\nby (metis Prfn.intros(1) add_Suc)\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: Prf.induct)\nprefer 4\napply(simp)\nprefer 4\napply(simp)\napply (metis Prf.intros(4))\nprefer 2\napply(simp)\napply (metis Prf.intros(2))\nprefer 2\napply(simp)\napply (metis Prf.intros(3))\napply(auto)\napply(rule Prf.intros)\napply(simp)\napply (metis Prf_flat_L nullable_correctness)\napply(rule Prf.intros)\napply(rule Prf.intros)\napply (metis Cons_eq_append_conv)\napply(simp)\napply(rule Prf.intros)\napply (metis Cons_eq_append_conv)\napply(simp)\ndone\n\nlemma v3s_proj:\n  assumes \"\\<Turnstile>(c#s) v : r\"\n  shows \"\\<Turnstile>s (projval r c v) : der c r\"\nusing assms\napply(induct s\\<equiv>\"c#s\" v r arbitrary: s rule: Prfs.induct)\nprefer 4\napply(simp)\napply (metis Prfs.intros(4))\nprefer 2\napply(simp)\napply (metis Prfs.intros(2))\nprefer 2\napply(simp)\napply (metis Prfs.intros(3))\napply(auto)\napply(rule Prfs.intros)\napply (metis Prfs_flat append_Nil)\nprefer 2\napply(rule Prfs.intros)\napply(subst (asm) append_eq_Cons_conv)\napply(auto)[1]\napply (metis Prfs_flat)\napply(rule Prfs.intros)\napply metis\napply(simp)\napply(subst (asm) append_eq_Cons_conv)\napply(auto)[1]\napply (metis Prf_flat_L Prfs_Prf nullable_correctness)\napply (metis Prfs_flat list.distinct(1))\napply(subst (asm) append_eq_Cons_conv)\napply(auto)[1]\napply (metis Prfs_flat)\nby (metis Prfs.intros(1))\n\ntext {*\n  The string behind the injection value is an added c\n*}\n\nlemma v4s:\n  assumes \"\\<Turnstile>s v : der c r\" shows \"flat (injval r c v) = c # (flat v)\"\nusing assms\napply(induct arbitrary: s v rule: der.induct)\napply(simp)\napply(erule Prfs.cases)\napply(simp_all)[5]\napply(simp)\napply(erule Prfs.cases)\napply(simp_all)[5]\napply(simp)\napply(case_tac \"c = c'\")\napply(simp)\napply(auto)[1]\napply(erule Prfs.cases)\napply(simp_all)[5]\napply(simp)\napply(erule Prfs.cases)\napply(simp_all)[5]\napply(simp)\napply(erule Prfs.cases)\napply(simp_all)[5]\napply(simp)\napply(case_tac \"nullable r1\")\napply(simp)\napply(erule Prfs.cases)\napply(simp_all (no_asm_use))[5]\napply(auto)[1]\napply(erule Prfs.cases)\napply(simp_all)[5]\napply(clarify)\napply(simp only: injval.simps flat.simps)\napply(auto)[1]\napply (metis mkeps_flat)\napply(simp)\napply(erule Prfs.cases)\napply(simp_all)[5]\ndone\n\nlemma v4:\n  assumes \"\\<turnstile> v : der c r\" 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)[5]\napply(simp)\napply(erule Prf.cases)\napply(simp_all)[5]\napply(simp)\napply(case_tac \"c = c'\")\napply(simp)\napply(auto)[1]\napply(erule Prf.cases)\napply(simp_all)[5]\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 \"nullable r1\")\napply(simp)\napply(erule Prf.cases)\napply(simp_all (no_asm_use))[5]\napply(auto)[1]\napply(erule Prf.cases)\napply(simp_all)[5]\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)[5]\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: Prf.induct)\nprefer 4\napply(simp)\nprefer 4\napply(simp)\nprefer 2\napply(simp)\nprefer 2\napply(simp)\napply(auto)\nby (metis Cons_eq_append_conv)\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\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 = x\")\napply(simp)\napply(simp add: Values_recs)\napply(simp)\napply(simp add: Values_recs)\napply(simp add: prefix_def)\napply(case_tac \"nullable x1\")\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 \n  assumes \"MValue v1 r1 s\"\n  shows \"MValue (Seq v1 v2) (SEQ r1 r2) s\n\n\nlemma MValue_SEQE:\n  assumes \"MValue v (SEQ r1 r2) s\"\n  shows \"(\\<exists>v1 v2. MValue v1 r1 s \\<and> MValue v2 r2 (rest v1 s) \\<and> v = Seq v1 v2)\"\nusing assms\napply(simp add: MValue_def)\napply(simp add: Values_recs)\napply(erule conjE)\napply(erule exE)+\napply(erule conjE)+\napply(simp)\napply(auto)\napply(drule_tac x=\"Seq x v2\" in spec)\napply(drule mp)\napply(rule_tac x=\"x\" in exI)\napply(rule_tac x=\"v2\" in exI)\napply(simp)\noops\n\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 MValue_injval:\n  assumes \"MValue v (der c r) s\"\n  shows \"MValue (injval r c v) r (c#s)\"\nusing assms\napply(induct c r arbitrary: v s rule: der.induct)\napply(simp add: MValue_def)\napply(simp add: Values_recs)\napply(simp add: MValue_def)\napply(simp add: Values_recs)\napply(case_tac \"c = c'\")\napply(simp)\napply(simp add: MValue_def)\napply(simp add: Values_recs)\napply(simp add: prefix_def)\napply(rule ValOrd2.intros)\napply(simp)\napply(simp add: MValue_def)\napply(simp add: Values_recs)\napply(simp)\napply(drule MValue_ALTE)\napply(erule disjE)\napply(auto)[1]\napply(rule MValue_ALTI1)\napply(simp)\napply(subst v4)\napply(simp add: MValue_def Values_def)\napply(rule ballI)\napply(simp)\napply(case_tac \"flat vr = []\")\napply(simp)\napply(drule_tac x=\"projval r2 c vr\" in bspec)\napply(rule Values_projval)\napply(simp)\napply(simp add: Values_def prefix_def)\napply(auto)[1]\napply(simp add: append_eq_Cons_conv)\napply(auto)[1]\napply(simp add: Values_def prefix_def)\napply(auto)[1]\napply(simp add: append_eq_Cons_conv)\napply(auto)[1]\napply(subst (asm) v4_proj2)\napply(assumption)\napply(assumption)\napply(simp)\napply(auto)[1]\napply(rule MValue_ALTI2)\napply(simp)\napply(subst v4)\napply(simp add: MValue_def Values_def)\napply(rule ballI)\napply(simp)\napply(case_tac \"flat vl = []\")\napply(simp)\napply(drule_tac x=\"projval r1 c vl\" in bspec)\napply(rule Values_projval)\napply(simp)\napply(simp add: Values_def prefix_def)\napply(auto)[1]\napply(simp add: append_eq_Cons_conv)\napply(auto)[1]\napply(simp add: Values_def prefix_def)\napply(auto)[1]\napply(simp add: append_eq_Cons_conv)\napply(auto)[1]\napply(subst (asm) v4_proj2)\napply(simp add: MValue_def Values_def)\napply(assumption)\napply(assumption)\napply(case_tac \"nullable r1\")\ndefer\napply(simp)\napply(frule MValue_SEQE)\napply(auto)[1]\n\n\napply(simp add: MValue_def)\napply(simp add: Values_recs)\n\nlemma nullable_red:\n  \"\\<not>nullable (red c r)\"\napply(induct r)\napply(auto)\ndone\n\nlemma twq:\n  assumes \"\\<turnstile> v : r\" \n  shows \"\\<turnstile> injval r c v : red c r\"\nusing assms\napply(induct)\napply(auto)\noops\n\nlemma injval_inj_red: \"inj_on (injval (red c r) c) {v. \\<turnstile> v : r}\"\nusing injval_inj\napply(auto simp add: inj_on_def)\napply(drule_tac x=\"red c r\" in meta_spec)\napply(drule_tac x=\"c\" in meta_spec)\napply(drule_tac x=\"x\" in spec)\napply(drule mp)\noops\n\nlemma \n  assumes \"POSIXs v (der c r) s\" \n  shows \"POSIXs (injval r c v) r (c # s)\"\nusing assms\napply(induct c r arbitrary: v s rule: der.induct)\napply(auto simp add: POSIXs_def)[1]\napply(erule Prfs.cases)\napply(simp_all)[5]\napply(erule Prfs.cases)\napply(simp_all)[5]\napply(auto simp add: POSIXs_def)[1]\napply(erule Prfs.cases)\napply(simp_all)[5]\napply(erule Prfs.cases)\napply(simp_all)[5]\napply(case_tac \"c = c'\")\napply(auto simp add: POSIXs_def)[1]\napply(erule Prfs.cases)\napply(simp_all)[5]\napply (metis Prfs.intros(5))\napply(erule Prfs.cases)\napply(simp_all)[5]\napply(erule Prfs.cases)\napply(simp_all)[5]\napply (metis ValOrd2.intros(8))\napply(auto simp add: POSIXs_def)[1]\napply(erule Prfs.cases)\napply(simp_all)[5]\napply(erule Prfs.cases)\napply(simp_all)[5]\napply(frule Prfs_POSIX)\napply(drule conjunct1)\napply(erule Prfs.cases)\napply(simp_all)[5]\napply(rule POSIXs_ALT_I1)\napply (metis POSIXs_ALT2)\napply(rule POSIXs_ALT_I2)\napply (metis POSIXs_ALT1a)\napply(frule POSIXs_ALT1b)\napply(auto)\napply(frule POSIXs_ALT1a)\n(* HERE *)\noops\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\nsection {* TESTTEST *}\n\ninductive ValOrdA :: \"val \\<Rightarrow> rexp \\<Rightarrow> val \\<Rightarrow> bool\" (\"_ A\\<succ>_ _\" [100, 100, 100] 100)\nwhere\n  \"v2 A\\<succ>r2 v2' \\<Longrightarrow> (Seq v1 v2) A\\<succ>(SEQ r1 r2) (Seq v1 v2')\" \n| \"v1 A\\<succ>r1 v1' \\<Longrightarrow> (Seq v1 v2) A\\<succ>(SEQ r1 r2) (Seq v1' v2')\" \n| \"length (flat v1) \\<ge> length (flat v2) \\<Longrightarrow> (Left v1) A\\<succ>(ALT r1 r2) (Right v2)\"\n| \"length (flat v2) > length (flat v1) \\<Longrightarrow> (Right v2) A\\<succ>(ALT r1 r2) (Left v1)\"\n| \"v2 A\\<succ>r2 v2' \\<Longrightarrow> (Right v2) A\\<succ>(ALT r1 r2) (Right v2')\"\n| \"v1 A\\<succ>r1 v1' \\<Longrightarrow> (Left v1) A\\<succ>(ALT r1 r2) (Left v1')\"\n| \"Void A\\<succ>EMPTY Void\"\n| \"(Char c) A\\<succ>(CHAR c) (Char c)\"\n\ninductive ValOrd4 :: \"val \\<Rightarrow> rexp \\<Rightarrow> val \\<Rightarrow> bool\" (\"_ 4\\<succ> _ _\" [100, 100] 100)\nwhere\n  (*\"v1 4\\<succ>(der c r) v1' \\<Longrightarrow> (injval r c v1) 4\\<succ>r (injval r c v1')\" \n| \"\\<lbrakk>v1 4\\<succ>r v2; v2 4\\<succ>r v3\\<rbrakk> \\<Longrightarrow> v1 4\\<succ>r v3\" \n|*) \n  \"\\<lbrakk>v1 4\\<succ>r1 v1'; flat v2 = flat v2'; \\<turnstile> v2 : r2; \\<turnstile> v2' : r2\\<rbrakk> \\<Longrightarrow> (Seq v1 v2) 4\\<succ>(SEQ r1 r2)  (Seq v1' v2')\"\n| \"\\<lbrakk>v2 4\\<succ>r2 v2'; \\<turnstile> v1 : r1\\<rbrakk> \\<Longrightarrow> (Seq v1 v2) 4\\<succ>(SEQ r1 r2)  (Seq v1 v2')\"\n| \"\\<lbrakk>flat v1 = flat v2; \\<turnstile> v1 : r1; \\<turnstile> v2 : r2\\<rbrakk> \\<Longrightarrow> (Left v1) 4\\<succ>(ALT r1 r2) (Right v2)\"\n| \"v2 4\\<succ>r2 v2' \\<Longrightarrow> (Right v2) 4\\<succ>(ALT r1 r2) (Right v2')\"\n| \"v1 4\\<succ>r1 v1' \\<Longrightarrow> (Left v1) 4\\<succ>(ALT r1 r2) (Left v1')\"\n| \"Void 4\\<succ>(EMPTY) Void\"\n| \"(Char c) 4\\<succ>(CHAR c) (Char c)\"\n\nlemma ValOrd4_Prf:\n  assumes \"v1 4\\<succ>r v2\"\n  shows \"\\<turnstile> v1 : r \\<and> \\<turnstile> v2 : r\"\nusing assms\napply(induct v1 r v2)\napply(auto intro: Prf.intros)\ndone\n\nlemma ValOrd4_flat:\n  assumes \"v1 4\\<succ>r v2\"\n  shows \"flat v1 = flat v2\"\nusing assms\napply(induct v1 r v2)\napply(simp_all)\ndone\n\nlemma ValOrd4_refl:\n  assumes \"\\<turnstile> v : r\"\n  shows \"v 4\\<succ>r v\"\nusing assms\napply(induct v r)\napply(auto intro: ValOrd4.intros)\ndone\n\nlemma \n  assumes \"v1 4\\<succ>r v2\" \"v2 4\\<succ>r v3\" \n  shows \"v1 A\\<succ>r v3\"\nusing assms\napply(induct v1 r v2 arbitrary: v3)\napply(rotate_tac 5)\napply(erule ValOrd4.cases)\napply(simp_all)\napply(clarify)\napply (metis ValOrdA.intros(2))\napply(clarify)\napply (metis ValOrd4_refl ValOrdA.intros(2))\napply(rotate_tac 3)\napply(erule ValOrd4.cases)\napply(simp_all)\napply(clarify)\n\napply (metis ValOrdA.intros(2))\napply (metis ValOrdA.intros(1))\napply (metis ValOrdA.intros(3) order_refl)\napply (auto intro: ValOrdA.intros)\ndone\n\nlemma \n  assumes \"v1 4\\<succ>r v2\"\n  shows \"v1 A\\<succ>r v2\"\nusing assms\napply(induct v1 r v2 arbitrary:)\napply (metis ValOrdA.intros(2))\napply (metis ValOrdA.intros(1))\napply (metis ValOrdA.intros(3) order_refl)\napply (auto intro: ValOrdA.intros)\ndone\n\nlemma \n  assumes \"v1 \\<succ>r v2\" \"\\<turnstile> v1 : r\" \"\\<turnstile> v2 : r\" \"flat v1 = flat v2\"\n  shows \"v1 4\\<succ>r v2\"\nusing assms\napply(induct v1 r v2 arbitrary:)\napply(erule Prf.cases)\napply(simp_all (no_asm_use))[5]\napply(erule Prf.cases)\napply(simp_all (no_asm_use))[5]\napply(clarify)\napply (metis ValOrd4.intros(4) ValOrd4_flat ValOrd4_refl)\napply(simp)\napply(erule Prf.cases)\napply(simp_all (no_asm_use))[5]\napply(erule Prf.cases)\napply(simp_all (no_asm_use))[5]\napply(clarify)\n\nlemma \n  assumes \"v1 \\<succ>r v2\" \"\\<turnstile> v1 : r\" \"\\<turnstile> v2 : r\" \"flat v1 = flat v2\"\n  shows \"v1 4\\<succ>r v2\"\nusing assms\napply(induct v1 r v2 arbitrary:)\napply(erule Prf.cases)\napply(simp_all (no_asm_use))[5]\napply(erule Prf.cases)\napply(simp_all (no_asm_use))[5]\napply(clarify)\napply (metis ValOrd4.intros(4) ValOrd4_flat ValOrd4_refl)\napply(simp)\napply(erule Prf.cases)\napply(simp_all (no_asm_use))[5]\napply(erule Prf.cases)\napply(simp_all (no_asm_use))[5]\napply(clarify)\n\n\napply(simp)\napply(erule Prf.cases)\n\n\n\n\nlemma rr2: \"hd (flats v) \\<noteq> [] \\<Longrightarrow> flats v \\<noteq> []\"\napply(induct v)\napply(auto)\ndone\n\nlemma rr3: \"flats v = [] \\<Longrightarrow> flat v = []\"\napply(induct v)\napply(auto)\ndone\n\nlemma POSIXs_der:\n  assumes \"POSIXs v (der c r) s\" \"\\<Turnstile>s v : der c r\"\n  shows \"POSIXs (injval r c v) r (c#s)\"\nusing assms\nunfolding POSIXs_def\napply(auto)\nthm v3s \napply (erule v3s)\napply(drule_tac x=\"projval r c v'\" in spec)\napply(drule mp)\nthm v3s_proj\napply(rule v3s_proj)\napply(simp)\nthm v3s_proj\napply(drule v3s_proj)\noops\n\nterm Values\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)\n\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)\napply(drule_tac x=\"s\" in meta_spec)\napply(simp)\napply(drule_tac meta_mp)\napply(simp add: rest_def mkeps_flat)\napply(drule_tac meta_mp)\napply(simp add: rest_def mkeps_flat)\napply(simp)\napply(simp add: rest_def mkeps_flat)\napply(subst (asm) (5) v4)\napply(simp)\napply(subst (asm) (5) v4)\napply(simp)\napply(subst (asm) (5) v4)\napply(simp)\napply(simp)\napply(clarify)\napply(simp add: prefix_Cons)\napply(subgoal_tac \"((flat v1c) @ (flat v2b)) \\<sqsubseteq> (flat v2)\")\nprefer 2\napply(simp add: prefix_def)\napply(auto)[1]\n(* HEREHERE *)\n\n\nlemma Prf_inj_test:\n  assumes \"v1 \\<succ>r v2\" \n          \"v1 \\<in> Values r s\"\n          \"v2 \\<in> Values r s\"\n          \"injval r c v1 \\<in> Values (red c r) (c#s)\"\n          \"injval r c v2 \\<in> Values (red c r) (c#s)\"\n  shows \"(injval r c v1) \\<succ>(red c r)  (injval r c v2)\"\nusing assms\napply(induct v1 r v2 arbitrary: s rule: ValOrd.induct)\napply(simp add: Values_recs)\napply (metis ValOrd.intros(1))\napply(simp add: Values_recs)\napply(rule ValOrd.intros(2))\napply(metis)\ndefer\napply(simp add: Values_recs)\napply(rule ValOrd.intros)\napply(subst v4)\napply(simp add: Values_def)\napply(subst v4)\napply(simp add: Values_def)\nusing injval_inj_red\napply(simp add: Values_def inj_on_def)\napply(rule notI)\napply(drule_tac x=\"r1\" in meta_spec)\napply(drule_tac x=\"c\" in meta_spec)\napply(drule_tac x=\"injval r1 c v1\" in spec)\napply(simp)\n\napply(drule_tac x=\"c\" in meta_spec)\n\napply metis\napply (metis ValOrd.intros(1))\n\n\n\ndone\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)\napply(drule_tac x=\"s\" in meta_spec)\napply(simp)\napply(drule_tac meta_mp)\napply(simp add: rest_def mkeps_flat)\napply(drule_tac meta_mp)\napply(simp add: rest_def mkeps_flat)\napply(simp)\napply(simp add: rest_def mkeps_flat)\napply(subst (asm) (5) v4)\napply(simp)\napply(subst (asm) (5) v4)\napply(simp)\napply(subst (asm) (5) v4)\napply(simp)\napply(simp)\napply(clarify)\napply(simp add: prefix_Cons)\napply(subgoal_tac \"((flat v1c) @ (flat v2b)) \\<sqsubseteq> (flat v2)\")\nprefer 2\napply(simp add: prefix_def)\napply(auto)[1]\n(* HEREHERE *)\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)\napply(drule_tac x=\"s\" in meta_spec)\napply(simp)\napply(drule_tac meta_mp)\napply(simp add: rest_def mkeps_flat)\napply(drule_tac meta_mp)\napply(simp add: rest_def mkeps_flat)\napply(simp)\napply(simp add: rest_def mkeps_flat)\napply(subst (asm) (5) v4)\napply(simp)\napply(subst (asm) (5) v4)\napply(simp)\napply(subst (asm) (5) v4)\napply(simp)\napply(simp)\napply(clarify)\napply(simp add: prefix_Cons)\napply(subgoal_tac \"((flat v1c) @ (flat v2b)) \\<sqsubseteq> (flat v2)\")\nprefer 2\napply(simp add: prefix_def)\napply(auto)[1]\n(* HEREHERE *)\n\napply(subst (asm) (7) v4)\napply(simp)\n\n\n(* HEREHERE *)\n\napply(simp add: Values_def)\napply(simp add: Values_recs)\napply(simp add: Values_recs)\ndone\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)\nthm  Prf_inj_test\napply(drule_tac r=\"r\" in Prf_inj_test)\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]\n \n\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\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)\n\napply metis\napply(simp)\napply(simp)\napply(erule disjE)\napply(simp)\n\napply(drule_tac x=\"v2\" in spec)\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]\napply(erule Prf.cases)\napply(simp_all)[5]\napply (metis ValOrd.intros(7))\napply (metis Prf.intros(4))\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(erule Prf.cases)\napply(simp_all)[5]\napply (metis ValOrd.intros(8))\napply (metis Prf.intros(5))\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]\napply(simp add: POSIX_def)\napply(auto)[1]\napply(rule ccontr)\napply(simp)\napply(drule_tac x=\"Seq v va\" in spec)\napply(drule mp)\ndefer\napply (metis Prf.intros(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]\napply (metis ValOrd.intros(7))\napply(erule_tac [!] exE)\nprefer 3\napply(frule POSIX_SEQ1)\napply(erule Prf.cases)\napply(simp_all)[5]\napply(erule Prf.cases)\napply(simp_all)[5]\napply(case_tac \"flat v1 = []\")\napply(subgoal_tac \"nullable r1\")\napply(simp)\nprefer 2\napply(rule_tac v=\"v1\" in Prf_flat_empty)\napply(erule Prf.cases)\napply(simp_all)[5]\napply(simp)\napply(frule POSIX_SEQ2)\napply(erule Prf.cases)\napply(simp_all)[5]\napply(erule Prf.cases)\napply(simp_all)[5]\napply(simp)\napply(drule meta_mp)\napply(erule Prf.cases)\napply(simp_all)[5]\napply(rule ccontr)\napply(subgoal_tac \"\\<turnstile> val.Right (projval r2 c v2) : (ALT (SEQ (der c r1) r2) (der c r2))\")\napply(rotate_tac 11)\napply(frule POSIX_ex)\napply(erule exE)\napply(drule POSIX_ALT_cases2)\napply(erule Prf.cases)\napply(simp_all)[5]\napply(drule v3_proj)\napply(simp)\napply(simp)\napply(drule POSIX_ex)\napply(erule exE)\napply(frule POSIX_ALT_cases2)\napply(simp)\napply(simp)\napply(erule \nprefer 2\napply(case_tac \"nullable r1\")\nprefer 2\napply(simp)\napply(rotate_tac 1)\napply(drule meta_mp)\napply(rule POSIX_SEQ1)\napply(assumption)\napply(erule Prf.cases)\napply(simp_all)[5]\napply(erule Prf.cases)\napply(simp_all)[5]\napply(rotate_tac 7)\napply(drule meta_mp)\napply(erule Prf.cases)\napply(simp_all)[5]\napply(rotate_tac 7)\napply(drule meta_mp)\napply (metis Cons_eq_append_conv)\n\n\napply(erule Prf.cases)\napply(simp_all)[5]\napply(simp add: POSIX_def)\napply(simp)\napply(simp)\napply(simp_all)[5]\napply(simp add: POSIX_def)\n\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]\napply (metis ValOrd.intros(7))\n\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]\napply (metis ValOrd.intros(7))\napply(erule_tac [!] exE)\nprefer 3\napply(frule POSIX_SEQ1)\napply(erule Prf.cases)\napply(simp_all)[5]\napply(erule Prf.cases)\napply(simp_all)[5]\napply(case_tac \"flat v1 = []\")\napply(subgoal_tac \"nullable r1\")\napply(simp)\nprefer 2\napply(rule_tac v=\"v1\" in Prf_flat_empty)\napply(erule Prf.cases)\napply(simp_all)[5]\n\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]\napply (metis ValOrd.intros(7))\napply(erule_tac [!] exE)\nprefer 3\napply(frule POSIX_SEQ1)\napply(erule Prf.cases)\napply(simp_all)[5]\napply(erule Prf.cases)\napply(simp_all)[5]\napply(case_tac \"flat v1 = []\")\napply(subgoal_tac \"nullable r1\")\napply(simp)\nprefer 2\napply(rule_tac v=\"v1\" in Prf_flat_empty)\napply(erule Prf.cases)\napply(simp_all)[5]\napply(simp)\napply(rule ccontr)\napply(drule v3_proj)\napply(simp)\napply(simp)\napply(drule POSIX_ex)\napply(erule exE)\napply(frule POSIX_ALT_cases2)\napply(simp)\napply(simp)\napply(erule \nprefer 2\napply(case_tac \"nullable r1\")\nprefer 2\napply(simp)\napply(rotate_tac 1)\napply(drule meta_mp)\napply(rule POSIX_SEQ1)\napply(assumption)\napply(erule Prf.cases)\napply(simp_all)[5]\napply(erule Prf.cases)\napply(simp_all)[5]\napply(rotate_tac 7)\napply(drule meta_mp)\napply(erule Prf.cases)\napply(simp_all)[5]\napply(rotate_tac 7)\napply(drule meta_mp)\napply (metis Cons_eq_append_conv)\n\n\napply(erule Prf.cases)\napply(simp_all)[5]\napply(simp add: POSIX_def)\napply(simp)\napply(simp)\napply(simp_all)[5]\napply(simp add: POSIX_def)\n\ndone\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]\napply (metis ValOrd.intros(7))\napply(rotate_tac 4)\napply(erule Prf.cases)\napply(simp_all)[5]\napply(simp)\nprefer 2\napply(simp)\napply(frule POSIX_ALT1a)\napply(drule meta_mp)\napply(simp)\napply(drule meta_mp)\napply(erule Prf.cases)\napply(simp_all)[5]\napply(rule POSIX_ALT_I2)\napply(assumption)\napply(auto)[1]\n\nthm v4_proj2\nprefer 2\napply(subst (asm) (13) POSIX_def)\n\napply(drule_tac x=\"projval v2\" in spec)\napply(auto)[1]\napply(drule mp)\napply(rule conjI)\napply(simp)\napply(simp)\n\napply(erule Prf.cases)\napply(simp_all)[5]\napply(erule Prf.cases)\napply(simp_all)[5]\nprefer 2\napply(clarify)\napply(subst (asm) (2) POSIX_def)\n\napply (metis ValOrd.intros(5))\napply(clarify)\napply(simp)\napply(rotate_tac 3)\napply(drule_tac c=\"c\" in t2)\napply(subst (asm) v4_proj)\napply(simp)\napply(simp)\nthm contrapos_np contrapos_nn\napply(erule contrapos_np)\napply(rule ValOrd.intros)\napply(subst  v4_proj2)\napply(simp)\napply(simp)\napply(subgoal_tac \"\\<not>(length (flat v1) < length (flat (projval r2a c v2a)))\")\nprefer 2\napply(erule contrapos_nn)\napply (metis nat_less_le v4_proj2)\napply(simp)\n\napply(blast)\nthm contrapos_nn\n\napply(simp add: POSIX_def)\napply(auto)[1]\napply(erule Prf.cases)\napply(simp_all)[5]\napply(erule Prf.cases)\napply(simp_all)[5]\napply(clarify)\napply(rule ValOrd.intros)\napply(drule meta_mp)\napply(auto)[1]\napply (metis POSIX_ALT2 POSIX_def flat.simps(3))\napply metis\napply(clarify)\napply(rule ValOrd.intros)\napply(simp)\napply(simp add: POSIX_def)\napply(auto)[1]\napply(erule Prf.cases)\napply(simp_all)[5]\napply(erule Prf.cases)\napply(simp_all)[5]\napply(clarify)\napply(rule ValOrd.intros)\napply(simp)\n\napply(drule meta_mp)\napply(auto)[1]\napply (metis POSIX_ALT2 POSIX_def flat.simps(3))\napply metis\napply(clarify)\napply(rule ValOrd.intros)\napply(simp)\n\n\ndone\n(* EMPTY case *)\napply(simp add: POSIX_def)\napply(auto)[1]\napply(rotate_tac 3)\napply(erule Prf.cases)\napply(simp_all)[5]\napply(drule_tac c=\"c\" in t2)\napply(subst (asm) v4_proj)\napply(auto)[2]\n\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 *)\n\n\nunfolding POSIX_def\napply(auto)\nthm v4\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)\napply(simp)\napply(rule ValOrd.intros(2))\napply(erule Prf.cases)\napply(simp_all)[5]\napply(erule Prf.cases)\napply(simp_all)[5]\napply(clarify)\ndefer\napply(simp)\napply(erule ValOrd.cases)\napply(simp_all del: injval.simps)[8]\napply(simp)\napply(clarify)\napply(simp)\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(rule ValOrd.intros(2))\n\n\n\n\ndone\n\n\ntxt {*\ndone\n(* nullable case - unfinished *)\napply(simp)\napply(erule ValOrd.cases)\napply(simp_all del: injval.simps)[8]\napply(simp)\napply(clarify)\napply(simp)\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(simp)\napply(rule ValOrd.intros(2))\noops\n*}\noops\n\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\nlemma \"L r \\<noteq> {} \\<Longrightarrow> \\<exists>v. POSIX3 v r\"\napply(induct r)\napply(simp)\napply(simp add: POSIX3_def)\napply(rule_tac x=\"Void\" in exI)\napply(auto)[1]\napply (metis Prf.intros(4))\napply (metis POSIX3_def flat.simps(1) mkeps.simps(1) mkeps_POSIX3 nullable.simps(2) order_refl)\napply(simp add: POSIX3_def)\napply(rule_tac x=\"Char char\" in exI)\napply(auto)[1]\napply (metis Prf.intros(5))\napply(erule Prf.cases)\napply(simp_all)[5]\napply (metis ValOrd.intros(8))\napply(simp add: Sequ_def)\napply(auto)[1]\napply(drule meta_mp)\napply(auto)[2]\napply(drule meta_mp)\napply(auto)[2]\napply(rule_tac x=\"Seq v va\" in exI)\napply(simp (no_asm) add: POSIX3_def)\napply(auto)[1]\napply (metis POSIX3_def Prf.intros(1))\napply(erule Prf.cases)\napply(simp_all)[5]\napply(clarify)\napply(case_tac \"v  \\<succ>r1a v1\")\napply(rule ValOrd.intros(2))\napply(simp)\napply(case_tac \"v = v1\")\napply(rule ValOrd.intros(1))\napply(simp)\napply(simp)\napply (metis ValOrd_refl)\napply(simp add: POSIX3_def)\noops\n\nlemma \"\\<exists>v. POSIX v r\"\napply(induct r)\napply(rule exI)\napply(simp add: POSIX_def)\napply (metis (full_types) Prf_flat_L der.simps(1) der.simps(2) der.simps(3) flat.simps(1) nullable.simps(1) nullable_correctness proj_inj_id projval.simps(1) v3 v4)\napply(rule_tac x = \"Void\" in exI)\napply(simp add: POSIX_def)\napply (metis POSIX_def flat.simps(1) mkeps.simps(1) mkeps_POSIX nullable.simps(2))\napply(rule_tac x = \"Char char\" in exI)\napply(simp add: POSIX_def)\napply(auto) [1]\napply(erule Prf.cases)\napply(simp_all) [5]\napply (metis ValOrd.intros(8))\ndefer\napply(auto)\napply (metis POSIX_ALT_I1)\n(* maybe it is too early to instantiate this existential quantifier *)\n(* potentially this is the wrong POSIX value *)\napply(case_tac \"r1 = NULL\")\napply(simp add: POSIX_def)\napply(auto)[1]\napply (metis L.simps(1) L.simps(4) Prf_flat_L mkeps_flat nullable.simps(1) nullable.simps(2) nullable_correctness seq_null(2))\napply(case_tac \"r1 = EMPTY\")\napply(rule_tac x = \"Seq Void va\" in exI )\napply(simp (no_asm) add: POSIX_def)\napply(auto)\napply(erule Prf.cases)\napply(simp_all)\napply(auto)[1]\napply(erule Prf.cases)\napply(simp_all)\napply(rule ValOrd.intros(2))\napply(rule ValOrd.intros)\napply(case_tac \"\\<exists>c. r1 = CHAR c\")\napply(auto)\napply(rule_tac x = \"Seq (Char c) va\" in exI )\napply(simp (no_asm) add: POSIX_def)\napply(auto)\napply(erule Prf.cases)\napply(simp_all)\napply(auto)[1]\napply(erule Prf.cases)\napply(simp_all)\napply(auto)[1]\napply(rule ValOrd.intros(2))\napply(rule ValOrd.intros)\napply(case_tac \"\\<exists>r1a r1b. r1 = ALT r1a r1b\")\napply(auto)\noops (* not sure if this can be proved by induction *)\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]\napply(erule Prf.cases)\napply(simp_all)[5]\napply(rule ValOrd.intros)\napply(auto)[1]\napply(erule Prf.cases)\napply(simp_all)[5]\n(* base cases done *)\n(* ALT case *)\napply(erule Prf.cases)\napply(simp_all)[5]\nusing POSIX_ALT POSIX_ALT_I1 apply blast\napply(clarify)\napply(simp)\napply(rule POSIX_ALT_I2)\napply(drule POSIX_ALT1a)\napply metis\napply(auto)[1]\napply(subst v4)\napply(assumption)\napply(simp)\napply(drule POSIX_ALT1a)\napply(rotate_tac 1)\napply(drule_tac x=\"v2\" in meta_spec)\napply(simp)\n\napply(rotate_tac 4)\napply(erule Prf.cases)\napply(simp_all)[5]\napply(rule ValOrd.intros)\napply(simp)\napply(subst (asm) v4)\napply(assumption)\napply(clarify)\nthm POSIX_ALT1a POSIX_ALT1b POSIX_ALT_I2\napply(subst (asm) v4)\napply(auto simp add: POSIX_def)[1]\napply(subgoal_tac \"POSIX v2 (der c r2)\")\nprefer 2\napply(auto simp add: POSIX_def)[1]\napply (metis POSIX_ALT1a POSIX_def flat.simps(4))\napply(frule POSIX_ALT1a)\napply(drule POSIX_ALT1b)\napply(rule POSIX_ALT_I2)\napply(rotate_tac 1)\napply(drule_tac x=\"v2\" in meta_spec)\napply(simp)\napply(subgoal_tac \"\\<turnstile> Right (injval r2 c v2) : (ALT r1 r2)\")\nprefer 2\napply (metis Prf.intros(3) v3)\napply auto[1]\napply(subst v4)\napply(auto)[2]\napply(subst (asm) (4) POSIX_def)\napply(subst (asm) v4)\napply(drule_tac x=\"v2\" in meta_spec)\napply(simp)\n\napply(auto)[2]\n\nthm POSIX_ALT_I2\napply(rule POSIX_ALT_I2)\n\napply(rule ccontr)\napply(auto simp add: POSIX_def)[1]\n\napply(rule allI)\napply(rule impI)\napply(erule conjE)\nthm POSIX_ALT_I2\napply(frule POSIX_ALT1a)\napply(drule POSIX_ALT1b)\napply(rule POSIX_ALT_I2)\napply auto[1]\napply(subst v4)\napply(auto)[2]\napply(rotate_tac 1)\napply(drule_tac x=\"v2\" in meta_spec)\napply(simp)\napply(subst (asm) (4) POSIX_def)\napply(subst (asm) v4)\napply(auto)[2]\n(* stuck in the ALT case *)\n", "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/Re1.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8872045937171067, "lm_q2_score": 0.8438950947024555, "lm_q1q2_score": 0.7487076046353514}}
{"text": "(*  Title:      HOL/Hahn_Banach/Function_Norm.thy\n    Author:     Gertrud Bauer, TU Munich\n*)\n\nsection \\<open>The norm of a function\\<close>\n\ntheory Function_Norm\nimports Normed_Space Function_Order\nbegin\n\nsubsection \\<open>Continuous linear forms\\<close>\n\ntext \\<open>\n  A linear form \\<open>f\\<close> on a normed vector space \\<open>(V, \\<parallel>\\<cdot>\\<parallel>)\\<close> is \\<^emph>\\<open>continuous\\<close>, iff\n  it is bounded, i.e.\n  \\begin{center}\n  \\<open>\\<exists>c \\<in> R. \\<forall>x \\<in> V. \\<bar>f x\\<bar> \\<le> c \\<cdot> \\<parallel>x\\<parallel>\\<close>\n  \\end{center}\n  In our application no other functions than linear forms are considered, so\n  we can define continuous linear forms as bounded linear forms:\n\\<close>\n\nlocale continuous = linearform +\n  fixes norm :: \"_ \\<Rightarrow> real\"    (\"\\<parallel>_\\<parallel>\")\n  assumes bounded: \"\\<exists>c. \\<forall>x \\<in> V. \\<bar>f x\\<bar> \\<le> c * \\<parallel>x\\<parallel>\"\n\ndeclare continuous.intro [intro?] continuous_axioms.intro [intro?]\n\nlemma continuousI [intro]:\n  fixes norm :: \"_ \\<Rightarrow> real\"  (\"\\<parallel>_\\<parallel>\")\n  assumes \"linearform V f\"\n  assumes r: \"\\<And>x. x \\<in> V \\<Longrightarrow> \\<bar>f x\\<bar> \\<le> c * \\<parallel>x\\<parallel>\"\n  shows \"continuous V f norm\"\nproof\n  show \"linearform V f\" by fact\n  from r have \"\\<exists>c. \\<forall>x\\<in>V. \\<bar>f x\\<bar> \\<le> c * \\<parallel>x\\<parallel>\" by blast\n  then show \"continuous_axioms V f norm\" ..\nqed\n\n\nsubsection \\<open>The norm of a linear form\\<close>\n\ntext \\<open>\n  The least real number \\<open>c\\<close> for which holds\n  \\begin{center}\n  \\<open>\\<forall>x \\<in> V. \\<bar>f x\\<bar> \\<le> c \\<cdot> \\<parallel>x\\<parallel>\\<close>\n  \\end{center}\n  is called the \\<^emph>\\<open>norm\\<close> of \\<open>f\\<close>.\n\n  For non-trivial vector spaces \\<open>V \\<noteq> {0}\\<close> the norm can be defined as\n  \\begin{center}\n  \\<open>\\<parallel>f\\<parallel> = \\<sup>x \\<noteq> 0. \\<bar>f x\\<bar> / \\<parallel>x\\<parallel>\\<close>\n  \\end{center}\n\n  For the case \\<open>V = {0}\\<close> the supremum would be taken from an empty set. Since\n  \\<open>\\<real>\\<close> is unbounded, there would be no supremum. To avoid this situation it\n  must be guaranteed that there is an element in this set. This element must\n  be \\<open>{} \\<ge> 0\\<close> so that \\<open>fn_norm\\<close> has the norm properties. Furthermore it does\n  not have to change the norm in all other cases, so it must be \\<open>0\\<close>, as all\n  other elements are \\<open>{} \\<ge> 0\\<close>.\n\n  Thus we define the set \\<open>B\\<close> where the supremum is taken from as follows:\n  \\begin{center}\n  \\<open>{0} \\<union> {\\<bar>f x\\<bar> / \\<parallel>x\\<parallel>. x \\<noteq> 0 \\<and> x \\<in> F}\\<close>\n  \\end{center}\n\n  \\<open>fn_norm\\<close> is equal to the supremum of \\<open>B\\<close>, if the supremum exists (otherwise\n  it is undefined).\n\\<close>\n\nlocale fn_norm =\n  fixes norm :: \"_ \\<Rightarrow> real\"    (\"\\<parallel>_\\<parallel>\")\n  fixes B defines \"B V f \\<equiv> {0} \\<union> {\\<bar>f x\\<bar> / \\<parallel>x\\<parallel> | x. x \\<noteq> 0 \\<and> x \\<in> V}\"\n  fixes fn_norm (\"\\<parallel>_\\<parallel>\\<hyphen>_\" [0, 1000] 999)\n  defines \"\\<parallel>f\\<parallel>\\<hyphen>V \\<equiv> \\<Squnion>(B V f)\"\n\nlocale normed_vectorspace_with_fn_norm = normed_vectorspace + fn_norm\n\nlemma (in fn_norm) B_not_empty [intro]: \"0 \\<in> B V f\"\n  by (simp add: B_def)\n\ntext \\<open>\n  The following lemma states that every continuous linear form on a normed\n  space \\<open>(V, \\<parallel>\\<cdot>\\<parallel>)\\<close> has a function norm.\n\\<close>\n\nlemma (in normed_vectorspace_with_fn_norm) fn_norm_works:\n  assumes \"continuous V f norm\"\n  shows \"lub (B V f) (\\<parallel>f\\<parallel>\\<hyphen>V)\"\nproof -\n  interpret continuous V f norm by fact\n  txt \\<open>The existence of the supremum is shown using the\n    completeness of the reals. Completeness means, that every\n    non-empty bounded set of reals has a supremum.\\<close>\n  have \"\\<exists>a. lub (B V f) a\"\n  proof (rule real_complete)\n    txt \\<open>First we have to show that \\<open>B\\<close> is non-empty:\\<close>\n    have \"0 \\<in> B V f\" ..\n    then show \"\\<exists>x. x \\<in> B V f\" ..\n\n    txt \\<open>Then we have to show that \\<open>B\\<close> is bounded:\\<close>\n    show \"\\<exists>c. \\<forall>y \\<in> B V f. y \\<le> c\"\n    proof -\n      txt \\<open>We know that \\<open>f\\<close> is bounded by some value \\<open>c\\<close>.\\<close>\n      from bounded obtain c where c: \"\\<forall>x \\<in> V. \\<bar>f x\\<bar> \\<le> c * \\<parallel>x\\<parallel>\" ..\n\n      txt \\<open>To prove the thesis, we have to show that there is some \\<open>b\\<close>, such\n        that \\<open>y \\<le> b\\<close> for all \\<open>y \\<in> B\\<close>. Due to the definition of \\<open>B\\<close> there are\n        two cases.\\<close>\n\n      define b where \"b = max c 0\"\n      have \"\\<forall>y \\<in> B V f. y \\<le> b\"\n      proof\n        fix y assume y: \"y \\<in> B V f\"\n        show \"y \\<le> b\"\n        proof cases\n          assume \"y = 0\"\n          then show ?thesis unfolding b_def by arith\n        next\n          txt \\<open>The second case is \\<open>y = \\<bar>f x\\<bar> / \\<parallel>x\\<parallel>\\<close> for some\n            \\<open>x \\<in> V\\<close> with \\<open>x \\<noteq> 0\\<close>.\\<close>\n          assume \"y \\<noteq> 0\"\n          with y obtain x where y_rep: \"y = \\<bar>f x\\<bar> * inverse \\<parallel>x\\<parallel>\"\n              and x: \"x \\<in> V\" and neq: \"x \\<noteq> 0\"\n            by (auto simp add: B_def divide_inverse)\n          from x neq have gt: \"0 < \\<parallel>x\\<parallel>\" ..\n\n          txt \\<open>The thesis follows by a short calculation using the\n            fact that \\<open>f\\<close> is bounded.\\<close>\n\n          note y_rep\n          also have \"\\<bar>f x\\<bar> * inverse \\<parallel>x\\<parallel> \\<le> (c * \\<parallel>x\\<parallel>) * inverse \\<parallel>x\\<parallel>\"\n          proof (rule mult_right_mono)\n            from c x show \"\\<bar>f x\\<bar> \\<le> c * \\<parallel>x\\<parallel>\" ..\n            from gt have \"0 < inverse \\<parallel>x\\<parallel>\" \n              by (rule positive_imp_inverse_positive)\n            then show \"0 \\<le> inverse \\<parallel>x\\<parallel>\" by (rule order_less_imp_le)\n          qed\n          also have \"\\<dots> = c * (\\<parallel>x\\<parallel> * inverse \\<parallel>x\\<parallel>)\"\n            by (rule Groups.mult.assoc)\n          also\n          from gt have \"\\<parallel>x\\<parallel> \\<noteq> 0\" by simp\n          then have \"\\<parallel>x\\<parallel> * inverse \\<parallel>x\\<parallel> = 1\" by simp \n          also have \"c * 1 \\<le> b\" by (simp add: b_def)\n          finally show \"y \\<le> b\" .\n        qed\n      qed\n      then show ?thesis ..\n    qed\n  qed\n  then show ?thesis unfolding fn_norm_def by (rule the_lubI_ex)\nqed\n\nlemma (in normed_vectorspace_with_fn_norm) fn_norm_ub [iff?]:\n  assumes \"continuous V f norm\"\n  assumes b: \"b \\<in> B V f\"\n  shows \"b \\<le> \\<parallel>f\\<parallel>\\<hyphen>V\"\nproof -\n  interpret continuous V f norm by fact\n  have \"lub (B V f) (\\<parallel>f\\<parallel>\\<hyphen>V)\"\n    using \\<open>continuous V f norm\\<close> by (rule fn_norm_works)\n  from this and b show ?thesis ..\nqed\n\nlemma (in normed_vectorspace_with_fn_norm) fn_norm_leastB:\n  assumes \"continuous V f norm\"\n  assumes b: \"\\<And>b. b \\<in> B V f \\<Longrightarrow> b \\<le> y\"\n  shows \"\\<parallel>f\\<parallel>\\<hyphen>V \\<le> y\"\nproof -\n  interpret continuous V f norm by fact\n  have \"lub (B V f) (\\<parallel>f\\<parallel>\\<hyphen>V)\"\n    using \\<open>continuous V f norm\\<close> by (rule fn_norm_works)\n  from this and b show ?thesis ..\nqed\n\ntext \\<open>The norm of a continuous function is always \\<open>\\<ge> 0\\<close>.\\<close>\n\nlemma (in normed_vectorspace_with_fn_norm) fn_norm_ge_zero [iff]:\n  assumes \"continuous V f norm\"\n  shows \"0 \\<le> \\<parallel>f\\<parallel>\\<hyphen>V\"\nproof -\n  interpret continuous V f norm by fact\n  txt \\<open>The function norm is defined as the supremum of \\<open>B\\<close>.\n    So it is \\<open>\\<ge> 0\\<close> if all elements in \\<open>B\\<close> are \\<open>\\<ge>\n    0\\<close>, provided the supremum exists and \\<open>B\\<close> is not empty.\\<close>\n  have \"lub (B V f) (\\<parallel>f\\<parallel>\\<hyphen>V)\"\n    using \\<open>continuous V f norm\\<close> by (rule fn_norm_works)\n  moreover have \"0 \\<in> B V f\" ..\n  ultimately show ?thesis ..\nqed\n\ntext \\<open>\n  \\<^medskip>\n  The fundamental property of function norms is:\n  \\begin{center}\n  \\<open>\\<bar>f x\\<bar> \\<le> \\<parallel>f\\<parallel> \\<cdot> \\<parallel>x\\<parallel>\\<close>\n  \\end{center}\n\\<close>\n\nlemma (in normed_vectorspace_with_fn_norm) fn_norm_le_cong:\n  assumes \"continuous V f norm\" \"linearform V f\"\n  assumes x: \"x \\<in> V\"\n  shows \"\\<bar>f x\\<bar> \\<le> \\<parallel>f\\<parallel>\\<hyphen>V * \\<parallel>x\\<parallel>\"\nproof -\n  interpret continuous V f norm by fact\n  interpret linearform V f by fact\n  show ?thesis\n  proof cases\n    assume \"x = 0\"\n    then have \"\\<bar>f x\\<bar> = \\<bar>f 0\\<bar>\" by simp\n    also have \"f 0 = 0\" by rule unfold_locales\n    also have \"\\<bar>\\<dots>\\<bar> = 0\" by simp\n    also have a: \"0 \\<le> \\<parallel>f\\<parallel>\\<hyphen>V\"\n      using \\<open>continuous V f norm\\<close> by (rule fn_norm_ge_zero)\n    from x have \"0 \\<le> norm x\" ..\n    with a have \"0 \\<le> \\<parallel>f\\<parallel>\\<hyphen>V * \\<parallel>x\\<parallel>\" by (simp add: zero_le_mult_iff)\n    finally show \"\\<bar>f x\\<bar> \\<le> \\<parallel>f\\<parallel>\\<hyphen>V * \\<parallel>x\\<parallel>\" .\n  next\n    assume \"x \\<noteq> 0\"\n    with x have neq: \"\\<parallel>x\\<parallel> \\<noteq> 0\" by simp\n    then have \"\\<bar>f x\\<bar> = (\\<bar>f x\\<bar> * inverse \\<parallel>x\\<parallel>) * \\<parallel>x\\<parallel>\" by simp\n    also have \"\\<dots> \\<le>  \\<parallel>f\\<parallel>\\<hyphen>V * \\<parallel>x\\<parallel>\"\n    proof (rule mult_right_mono)\n      from x show \"0 \\<le> \\<parallel>x\\<parallel>\" ..\n      from x and neq have \"\\<bar>f x\\<bar> * inverse \\<parallel>x\\<parallel> \\<in> B V f\"\n        by (auto simp add: B_def divide_inverse)\n      with \\<open>continuous V f norm\\<close> show \"\\<bar>f x\\<bar> * inverse \\<parallel>x\\<parallel> \\<le> \\<parallel>f\\<parallel>\\<hyphen>V\"\n        by (rule fn_norm_ub)\n    qed\n    finally show ?thesis .\n  qed\nqed\n\ntext \\<open>\n  \\<^medskip>\n  The function norm is the least positive real number for which the\n  following inequality holds:\n  \\begin{center}\n    \\<open>\\<bar>f x\\<bar> \\<le> c \\<cdot> \\<parallel>x\\<parallel>\\<close>\n  \\end{center}\n\\<close>\n\nlemma (in normed_vectorspace_with_fn_norm) fn_norm_least [intro?]:\n  assumes \"continuous V f norm\"\n  assumes ineq: \"\\<And>x. x \\<in> V \\<Longrightarrow> \\<bar>f x\\<bar> \\<le> c * \\<parallel>x\\<parallel>\" and ge: \"0 \\<le> c\"\n  shows \"\\<parallel>f\\<parallel>\\<hyphen>V \\<le> c\"\nproof -\n  interpret continuous V f norm by fact\n  show ?thesis\n  proof (rule fn_norm_leastB [folded B_def fn_norm_def])\n    fix b assume b: \"b \\<in> B V f\"\n    show \"b \\<le> c\"\n    proof cases\n      assume \"b = 0\"\n      with ge show ?thesis by simp\n    next\n      assume \"b \\<noteq> 0\"\n      with b obtain x where b_rep: \"b = \\<bar>f x\\<bar> * inverse \\<parallel>x\\<parallel>\"\n        and x_neq: \"x \\<noteq> 0\" and x: \"x \\<in> V\"\n        by (auto simp add: B_def divide_inverse)\n      note b_rep\n      also have \"\\<bar>f x\\<bar> * inverse \\<parallel>x\\<parallel> \\<le> (c * \\<parallel>x\\<parallel>) * inverse \\<parallel>x\\<parallel>\"\n      proof (rule mult_right_mono)\n        have \"0 < \\<parallel>x\\<parallel>\" using x x_neq ..\n        then show \"0 \\<le> inverse \\<parallel>x\\<parallel>\" by simp\n        from x show \"\\<bar>f x\\<bar> \\<le> c * \\<parallel>x\\<parallel>\" by (rule ineq)\n      qed\n      also have \"\\<dots> = c\"\n      proof -\n        from x_neq and x have \"\\<parallel>x\\<parallel> \\<noteq> 0\" by simp\n        then show ?thesis by simp\n      qed\n      finally show ?thesis .\n    qed\n  qed (insert \\<open>continuous V f norm\\<close>, simp_all add: continuous_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/Hahn_Banach/Function_Norm.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8807970873650401, "lm_q2_score": 0.8499711775577736, "lm_q1q2_score": 0.7486521375371203}}
{"text": "(*  Title:       Countable Ordinals\n\n    Author:      Brian Huffman, 2005\n    Maintainer:  Brian Huffman <brianh at cse.ogi.edu>\n*)\n\nsection \\<open>Ordinal Arithmetic\\<close>\n\ntheory OrdinalArith\nimports OrdinalRec\nbegin\n\nsubsection \\<open>Addition\\<close>\n\ninstantiation ordinal :: plus\nbegin\n\ndefinition\n  \"(+) = (\\<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 \\<open>Subtraction\\<close>\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 \\<open>Multiplication\\<close>\n\ninstantiation ordinal :: times\nbegin\n\ndefinition\n  times_ordinal_def: \"(*) = (\\<lambda>x. ordinal_rec 0 (\\<lambda>p w. w + x))\"\n\ninstance ..\n\nend\n\nlemma continuous_times: \"continuous ((*) x)\"\nby (simp add: times_ordinal_def continuous_ordinal_rec)\n\nlemma normal_times: \"0 < x \\<Longrightarrow> normal ((*) 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 \\<open>Exponentiation\\<close>\n\ndefinition\n  exp_ordinal :: \"[ordinal, ordinal] \\<Rightarrow> ordinal\" (infixr \"**\" 75) where\n  \"(**) = (\\<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 ((**) 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 ((**) 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": "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/OrdinalArith.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.880797071719777, "lm_q2_score": 0.8499711718571775, "lm_q1q2_score": 0.7486521192180292}}
{"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_02\n  imports \"../../Test_Base\"\nbegin\n\ndatatype 'a list = nil2 | cons2 \"'a\" \"'a list\"\n\ndatatype Nat = Z | S \"Nat\"\n\nfun y :: \"'a list => 'a list => 'a list\" where\n  \"y (nil2) y2 = y2\"\n| \"y (cons2 z2 xs) y2 = cons2 z2 (y xs y2)\"\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 y22) = x x2 y22\"\n\nfun count :: \"Nat => Nat list => Nat\" where\n  \"count z (nil2) = Z\"\n| \"count z (cons2 z2 ys) =\n     (if x z z2 then S (count z ys) else count z ys)\"\n\nfun t2 :: \"Nat => Nat => Nat\" where\n  \"t2 (Z) y2 = y2\"\n| \"t2 (S z2) y2 = S (t2 z2 y2)\"\n\ntheorem property0 :\n  \"t2 (count n xs) (count n ys) = count n (y xs ys)\"\n  find_proof DInd\n  apply (induct n xs arbitrary: ys rule: TIP_prop_02.count.induct)\n  apply auto\n  done\n\ntheorem property0_5:\n  \"t2 (count n xs) (count n ys) = count n (y xs ys)\"\n  apply(induct xs arbitrary:n ys)\n   apply(subst y.simps(1))\n   apply(subst count.simps(1))\n   apply(subst t2.simps(1))\n   apply(rule HOL.refl)\n  apply auto\n  done\n\ntheorem property0' :\n  \"((t2 (count n xs) (count n ys)) = (count n (y xs ys)))\"\n  (*why not \"induct ys\"?*)\n  apply(induct ys)\n   apply(subst count.simps(1))\n    (* Neither of the innermost recursively defined constant \"count\" in \"(count n xs)\" and \n   \"y\" in \"(y xs nil2)\" has a simp rule applicable to these.*)\n   apply(induct xs)\n    apply auto[1]\n   apply auto[1]\n  oops\n\n(*alternative proof*)\ntheorem property0'' :\n  \"((t2 (count n xs) (count n ys)) = (count n (y xs ys)))\"\n  apply (induct (*n*) xs arbitrary: n ys rule: count.induct)\n    (*Why \"count.induct\" not \"y.induct\"?\n     *Because \"(induct rule: y.induct)\" leads to a non-theorem.\n     *Because \"y\" is under another \"recursive\" function (\"count\")?\n     *No. \"y.induct\" can be useful as well. See property0'''' for more detail.*)\n    (*\"xs\" in \"induct xs\" here is removable.*)\n    (*Why \"induct xs\" (why induction on xs)?\n     *Because two innermost recursive constants (\"count\" in \"count n xs\" and \"y\" in \"y xs ys\")\n     *is recursively defined on \"xs\". *)\n    (*Why \"arbitrary: ys\", \"arbitrary: n\", \"arbitrary: ys n\", or \"arbitrary: n ys\"?\n     *Because of \"n\" and \"ys\" in \"count n ys\".\n     *This \"count\" is also the innermost recursive constant, but we induct on \"xs\".*)\n   apply auto\n  done\n\ntheorem property0''' :\n  \"((t2 (count n xs) (count n ys)) = (count n (y xs ys)))\"\n  apply(induct rule:y.induct)\n  nitpick\n  oops\n\ntheorem property0'''' :\n  \"((t2 (count n xs) (count n ys)) = (count n (y xs ys)))\"\n  apply(induct xs ys arbitrary: n rule:y.induct)\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_02.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240825770432, "lm_q2_score": 0.8652240808393984, "lm_q1q2_score": 0.7486127115678339}}
{"text": "theory AlgebraicStructure\nimports Main \"HOL-Library.Monad_Syntax\" \"HOL-Library.State_Monad\" HOL.Real \"~~/src/HOL/ex/Sqrt\"\nbegin\n\nsection \\<open>monoid\\<close>\n\nclass monoid =\n  fixes mult :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a\" (infixl \"\\<otimes>\" 70) \n  fixes neutral :: 'a (\"\\<one>\")\n  assumes assoc : \"(x \\<otimes> y) \\<otimes> z = x \\<otimes> (y \\<otimes> z)\"\n     and  neutr : \"x \\<otimes> \\<one> = x\"\n     and  neutl : \"\\<one> \\<otimes> x = x\"\nbegin\n\nlemma \"(w \\<otimes> x) \\<otimes> (y \\<otimes> z) = w \\<otimes> x \\<otimes> y \\<otimes> z\"\n  using assoc by auto\n\nend\n\ninstantiation int :: monoid\nbegin\ndefinition mult_int_def : \"x \\<otimes> y = (x :: int) + y\"\ndefinition neutral_int_def : \"\\<one> = (0::int)\"\n\ninstance \n  apply standard using neutral_int_def mult_int_def by auto\nend\n\nvalue \"(1::int) \\<otimes> 2\"\n\ninstantiation nat :: monoid\nbegin\ndefinition mult_nat_def : \"x \\<otimes> y = (x :: nat) + y\"\ndefinition neutral_nat_def : \"\\<one> = (0::nat)\"\n\ninstance \n  apply standard using neutral_nat_def mult_nat_def by auto\nend\n\nvalue \"(1::nat) \\<otimes> 2\"\n\ninstantiation bool :: monoid\nbegin\ndefinition mult_bool_def : \"x \\<otimes> y = ((x::bool) \\<and> y)\"\ndefinition neutral_bool_def : \"\\<one> = True\"\n\ninstance \n  apply standard using mult_bool_def neutral_bool_def by auto\nend\n\nvalue \"True \\<otimes> True\"\nvalue \"True \\<otimes> False\"\nvalue \"False \\<otimes> False\"\n\ninstantiation list :: (type) monoid  \nbegin\ndefinition mult_list_def : \"(x :: 'a list) \\<otimes> y = x @ y\"\ndefinition neutral_list_def : \"\\<one> = []\"\n\ninstance \n  apply standard using neutral_list_def mult_list_def by auto\n\nend\n\nvalue \"[1::nat,2,3] \\<otimes> [4,5,6]\"\nvalue \"''abcde'' \\<otimes> ''fghij''\"\n\ninstantiation set :: (type) monoid\nbegin\ndefinition mult_set_def : \"(x :: 'a set) \\<otimes> y = x \\<union> y\"\ndefinition neutral_set_def : \"\\<one> = {}\"\n\ninstance \n  apply standard using mult_set_def neutral_set_def by auto\nend\n\nvalue \"{1::int,2,3} \\<otimes> {3,4,5,6}\"\n\ninterpretation setintersect : monoid \"(\\<inter>)\" UNIV\n  unfolding class.monoid_def by auto\n\n\ninstantiation prod :: (monoid, monoid) monoid\nbegin\ndefinition mult_prod_def : \"x \\<otimes> y = (fst x \\<otimes> fst y, snd x \\<otimes> snd y)\"\ndefinition neutral_prod_def : \"\\<one> = (\\<one>,\\<one>)\"\n\ninstance \n  apply standard using mult_prod_def neutral_prod_def neutr neutl\n  apply (simp add: assoc)\n  apply (simp add: mult_prod_def neutr neutral_prod_def)\n  by (simp add: mult_prod_def neutl neutral_prod_def) \n\nend\n\nvalue \"(''aaaa'',{1::int,2,3}) \\<otimes> (''cccc'',{4,5,6})\"\n\nvalue \"(''aaa'',''bbb'',''ccc'') \\<otimes> (''ddd'',''eee'',''fff'') \\<otimes> (''ggg'',''hhh'',''iii'')\"\n\nvalue \"(''aa'',{1::int},1::nat) \\<otimes> (''cc'',{2},2) \\<otimes> (''ee'',{3},3)\"\n\nvalue \"(''aaa'', 20::int, False,{1::int}) \\<otimes> (''ddd'', 30::int, False,{2})\"\n\nvalue \"foldl (\\<otimes>) \\<one> [''aa'',''bb'',''cc'']\"\n\nvalue \"foldl (\\<otimes>) \\<one> [1::int,2,3,4,5]\"\n\nvalue \"foldl (\\<otimes>) \\<one> [(''aa'',{1::int},1::nat),(''bb'',{2},2),(''cc'',{3},3),(''dd'',{4},4)]\"\n\nvalue \"foldl (\\<otimes>) \\<one> [(1::int,''bb''),(2,''dd''),(3,''ff'')]\"\n\n(* count the elements and their sum in a list *)\nvalue \"foldl (\\<otimes>) \\<one> (map (\\<lambda>x. (1::int,x)) [1::int,2,3,4,5])\"\n\n(* count the elements and their sum in a list *)\nvalue \"foldl (\\<otimes>) \\<one> (map (\\<lambda>x. (1::int,x)) [''aa'',''bb'',''cc'',''dd''])\"\n\n\ninterpretation fun_monoid: monoid comp id\n  unfolding class.monoid_def by auto\n\n\nsection \\<open>monad\\<close>\n\nsubsection \\<open>motivation example\\<close>\n\ndefinition eval :: int\nwhere \"eval \\<equiv> let x = 1;\n                  y = x + 5;\n                  z = x + y;\n                  z = z * 2\n               in z div 2\"\n\n(*\ndefinition bind_option :: \"'a option \\<Rightarrow> ('a \\<Rightarrow> 'b option) \\<Rightarrow> 'b option\"\n  where \"bind_option a f \\<equiv> (case a of Some x \\<Rightarrow> f x | None \\<Rightarrow> None)\"\n\nadhoc_overloading Monad_Syntax.bind bind_option\n*)\n\nsubsection \\<open>option monad\\<close>\n\nthm Option.bind.simps\n\ndefinition returno :: \"'a \\<Rightarrow> 'a option\" where\n\"returno a = Some a\"\n\ndefinition add :: \"int option \\<Rightarrow> int option \\<Rightarrow> int option\"\n  where \"add x y \\<equiv> do {\n                     mx \\<leftarrow> x; \n                     my \\<leftarrow> y; \n                     returno (mx + my)\n                   }\"\nthm add_def\nvalue \"add (Some 2) None\"\n\nvalue \"add (Some 3) (Some 5)\"\n\ndefinition adds :: \"int option \\<Rightarrow> int option\"\nwhere \"adds x \\<equiv> do {\n                  a \\<leftarrow> x;\n                  b \\<leftarrow> add (Some a) (Some 1);\n                  c \\<leftarrow> add (Some b) (Some 2);\n                  d \\<leftarrow> add (Some c) (Some 3);\n                  returno d\n                }\"\n\nthm adds_def\nvalue \"adds (Some 2)\"\n\ndefinition safe_div :: \"int option \\<Rightarrow> int option \\<Rightarrow> int option\"\n  where \"safe_div x y \\<equiv> \n    do {\n      mx \\<leftarrow> x; \n      my \\<leftarrow> y; \n      if my \\<noteq> 0 then returno (mx div my) else None\n    }\"\nthm safe_div_def\n\nvalue \"safe_div (Some 5) (Some 0)\"\nvalue \"safe_div (Some 6) (Some 2)\"\nvalue \"safe_div (Some 5) None\"\nvalue \"safe_div None (Some 5)\"\n\ndefinition comps :: \"int option \\<Rightarrow> int option\"\n  where \"comps x \\<equiv> \n    do {\n       a \\<leftarrow> add x (Some (-3)); \n       b \\<leftarrow> safe_div (Some 6) (Some a);\n       c \\<leftarrow> add (Some b) (Some (-6));\n       d \\<leftarrow> safe_div (Some 15) (Some c);\n       returno d\n     }\"\n\nvalue \"comps (Some 3)\"\nvalue \"comps (Some 4)\"\nvalue \"comps (Some 5)\"\n\nsubsection \\<open>list monad\\<close>\n\ncontext begin\n\ndefinition returnl :: \"'a \\<Rightarrow> 'a list\"\nwhere \"returnl a \\<equiv> [a]\"\n\ndefinition \"sqr_even l \\<equiv> \n  do {\n    x \\<leftarrow> l;\n    if x mod 2 = 0 then \n      returnl (x * x) \n    else returnl x\n  }\"\n\nthm sqr_even_def\nvalue \"sqr_even [1..10]\"\n\ndefinition \"list_double l \\<equiv> \n  do {\n    x \\<leftarrow> l;\n    [x,2*x]\n  }\"\n\nthm list_double_def\nvalue \"list_double [1..5]\"\n\n\ndefinition \"prod1 xs ys \\<equiv> \n  do {\n    x \\<leftarrow> xs; \n    y \\<leftarrow> ys; \n    returnl (x, y)\n  }\"\n\nthm prod1_def\nvalue \"prod1 [a,b,c] [e,f,g]\"\n\ndefinition \"prod2 xs ys \\<equiv> concat (map (\\<lambda>x. concat (map (\\<lambda>y. [(x,y)]) ys)) xs)\"\n\nlemma \"prod1 xs ys = prod2 xs ys\"\n  unfolding prod1_def List.bind_def prod2_def returnl_def by simp\n\ndefinition list2 :: \"string list \\<Rightarrow> (nat \\<times> string) list\"\n  where \"list2 ss \\<equiv> do {\n                      x \\<leftarrow> ss;\n                      let y = x@''#'';\n                      let z = y@''@'';\n                      returnl (length x,z@z)\n                    }\"\nthm list2_def\nvalue \"list2 [''aaa'',''bb'',''cccc'']\"\nthm List.bind_def\n\n(*\ndouble vlen(double * v) {\n  double d = 0.0;\n  int n;\n  for (n = 0; n < 3; ++n)\n    d += v[n] * v[n];\n  return sqrt(d);\n}\n*)\ndefinition vlen :: \"real list \\<Rightarrow> real\"\n  where \"vlen l \\<equiv> foldl plus 0.0 ((l \\<bind> (\\<lambda>x. [x * x]))\\<bind> (\\<lambda>x. [x + 1]))\"\ndefinition vlen2 :: \"real list \\<Rightarrow> real\"\n  where \"vlen2 l \\<equiv> foldl plus 0.0 (do {\n                                     x \\<leftarrow> l;\n                                     let y = x * x;\n                                     returnl (y + 1)\n                                    })\"\n\nthm vlen_def\nthm vlen2_def\nvalue \"vlen [1,2,3,5]\"\nvalue \"vlen2 [1,2,3,5]\"\n\ndefinition list3 :: \"real list \\<Rightarrow> real list\"\n  where \"list3 l \\<equiv> ((l \\<bind> (\\<lambda>x. [x * x]))\\<bind> (\\<lambda>x. [x + 100]))\\<bind> (\\<lambda>x. [x + 1000])\"\n\ndefinition list32 :: \"real list \\<Rightarrow> real list\"\n  where \"list32 l \\<equiv> do {\n                      x \\<leftarrow> l;\n                      let y = x * x;\n                      let z = y + 100;\n                      returnl (z + 1000)\n                    }\"\n\nthm list3_def\nthm list32_def\nvalue \"list3 [1,2,3,5]\"\nvalue \"list32 [1,2,3,5]\"\n\nend\n\nsubsection \\<open>set monad\\<close>\n\ndefinition returns :: \"'a \\<Rightarrow> 'a set\"\nwhere \"returns a = {a}\"\n\ndefinition set1 :: \"int set \\<Rightarrow> (int \\<times> string) set\"\n  where \"set1 s \\<equiv> do {\n                     x \\<leftarrow> s;\n                     if x mod 2 = 0 then \n                       returns (3 * x, ''aaa'') \n                     else returns (0,'''')\n                  }\"\n\nvalue \"set1 {0..10}\"\n\ndefinition set2 :: \"int set \\<Rightarrow> (int \\<times> string) set\"\n  where \"set2 s \\<equiv> (s \\<bind> (\\<lambda>x. if x mod 2 = 0 then {(3 * x, ''aaa'')} else {(0,'''')})) \\<bind> (\\<lambda>(x,y). {(x+1,y@''__'')})\"\n\ndefinition set22 :: \"int set \\<Rightarrow> (int \\<times> string) set\"\n  where \"set22 s \\<equiv> do {\n                     x \\<leftarrow> s;\n                     if x mod 2 = 0 then do {\n                       let (x,y) = (3 * x, ''aaa'');\n                       returns (x+1,y@''__'')\n                     } else do {\n                       let (x,y) = (0,'''');\n                       returns (x+1,y@''__'')\n                     }\n                   }\"\nthm set2_def\nthm set22_def\nvalue \"set2 {0..10}\"\nvalue \"set22 {0..10}\"\n\ndefinition set3 :: \"int set \\<Rightarrow> (int \\<times> string) set\"\n  where \"set3 s \\<equiv> (s \\<bind> (\\<lambda>x. {(x*2,''*2'')})) \\<bind> (\\<lambda>(x,y). {(x+1,y@''__'')})\"\n\ndefinition set32 :: \"int set \\<Rightarrow> (int \\<times> string) set\"\n  where \"set32 s \\<equiv> do {\n                     x \\<leftarrow> s;\n                     (x,y) \\<leftarrow> {(x*2,''*2'')};\n                     returns (x+1,y@''__'')\n                   }\"\n\nvalue \"set3 {0..10}\"\nvalue \"set32 {0..10}\"\n\n\nsubsection \\<open>state monad\\<close>\n\nlemma \"Pair a = (\\<lambda>s. (a,s))\" by auto\n\ntype_synonym 'v stack = \"'v list\"\n\ndefinition pop :: \"('v stack,'v option) state\"\nwhere \"pop \\<equiv> State (\\<lambda>s. case s of [] \\<Rightarrow> (None, []) |\n                                  (x#xs) \\<Rightarrow> (Some x,xs))\"\n\ndefinition push :: \"'v \\<Rightarrow> ('v stack,'v option) state\"\nwhere \"push v \\<equiv> State (\\<lambda>s. case s of [] \\<Rightarrow> (None, [v]) |\n                                     (x#xs) \\<Rightarrow> (None,v#x#xs))\"\n\nprimrec pushn :: \"'v list \\<Rightarrow> ('v stack, 'v option) state\"\nwhere \"pushn [] = State_Monad.return None\" |\n      \"pushn (x#xs) = do {\n                        push x; \n                        pushn xs\n                      }\"\n\nprimrec popn :: \"nat \\<Rightarrow> ('v stack,('v option) list) state\"\nwhere \"popn 0 = State_Monad.return []\" |\n      \"popn (Suc n) = do {\n                        a \\<leftarrow> pop; \n                        as \\<leftarrow> popn n; \n                        State_Monad.return (a#as)\n                      }\"\n\nvalue \"run_state (pushn [1::int,2,3,4,5]) []\"\n\nvalue \"run_state (pushn [1::int,2,3,4,5]) [0,0,0]\"\n\nvalue \"run_state (popn 5) [0::int,1,2,3,4,5,6]\"\n\nvalue \"run_state (do {\n                    pushn [1::int,2,3,4,5];\n                    popn 4\n                  }) []\"\n\nthm foldl.simps\n\ndefinition stackops :: \"(int stack,int option) state\"\nwhere \"stackops \\<equiv>\n  do {\n    State_Monad.return (0::int);\n    push (1::int);\n    push 2;\n    push 3;\n    push 4;\n    State_Monad.return None\n  }\"\nthm stackops_def\nvalue \"run_state stackops []\"\n\n\ndefinition swap :: \"'a list \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> 'a list\"\nwhere \"swap l i j \\<equiv> (let temp = l!i in (l[i := l!j])[j := temp])\"\n\nvalue \"swap [0::nat,1,2,3,4] 0 4\"\n\n\nfun insert :: \"('a::linorder) list \\<Rightarrow> nat \\<Rightarrow> (('a::linorder) list,('a::linorder) list) state\"\nwhere \"insert l i = \n  (if i \\<noteq> 0 \\<and> l!i < l!(i-1) then do {\n    let l1 = swap l (i-1) i;\n    insert l1 (i - 1)\n  } else do {\n    State_Monad.return l \n  })\"\n\nvalue \"run_state (insert [3::int,2,8,4,3] 1) []\"\n\nfunction isort :: \"('a::linorder) list \\<Rightarrow> nat \\<Rightarrow> (('a::linorder) list,('a::linorder) list) state\"\nwhere \"isort l i = \n  (if i < length l then do {\n    l' \\<leftarrow> insert l i;\n    isort l' (i + 1)\n  } else do {    \n    State_Monad.return l\n  })\"\nby auto\ntermination \napply (relation \"measure (\\<lambda>(l,i). length l - i)\")\napply auto\n sorry\n\nthm isort.simps\n\nvalue \"(run_state (isort ([1::int,0,2,8,4,3,6,2]) 1) [])\"\n\nsubsection \\<open>I/O monad\\<close>\n\ntype_synonym Name = \"string\"\ntype_synonym IOStreams = \"Name \\<Rightarrow> string\"\ntype_synonym IOState = \"(IOStreams,string) state\"\n\ndefinition \"nl \\<equiv> CHR 0x0A\"\n\ndefinition newIO :: \"Name \\<Rightarrow> IOState\"\nwhere \"newIO x \\<equiv> State (\\<lambda>s. (''OK'', s(x := ([]::string))))\"\n\ndefinition putChar :: \"Name \\<Rightarrow> char \\<Rightarrow> IOState\"\nwhere \"putChar x c \\<equiv> State (\\<lambda>s. ([c],s(x := s x @ [c])))\"\n\ndefinition putStr :: \"Name \\<Rightarrow> string \\<Rightarrow> IOState\"\nwhere \"putStr x c \\<equiv> State (\\<lambda>s. (c, s(x := s x @ c)))\"\n\ndefinition putStrLn :: \"Name \\<Rightarrow> string \\<Rightarrow> IOState\"\nwhere \"putStrLn x c \\<equiv> putStr x (c@[nl])\"\n\ndefinition getChar :: \"Name \\<Rightarrow> IOState\"\nwhere \"getChar x \\<equiv> State (\n          \\<lambda>s. case s x of [] \\<Rightarrow> ([],s) |\n                         (y#xs) \\<Rightarrow> ([y],s(x := xs)))\"\n\nprimrec getline :: \"string \\<Rightarrow> (string \\<times> string)\"\nwhere \"getline [] = ([],[])\" |\n      \"getline (x#xs) = (let (a,b) = getline xs in \n                           if x = nl then ([],xs) \n                           else (x#a,b))\"\n\ndefinition getLine :: \"Name \\<Rightarrow> IOState\"\nwhere \"getLine x = State (\n        \\<lambda>s. let str = s x; \n                (a,b) = getline str in \n              (a, s(x := b)))\"\n\ndefinition init :: \"IOStreams\"\nwhere \"init = (\\<lambda>x. [])\"\n\ndefinition printIO :: \"Name \\<Rightarrow> IOState \\<Rightarrow> (string \\<times> string)\"\nwhere \"printIO x sm \\<equiv> (fst (run_state sm init), (snd (run_state sm init)) x)\"\n\nvalue \"printIO ''io1''\n        (do {\n            newIO ''io1'';\n            putStrLn ''io1'' (''aaa'');\n            putStrLn ''io1'' (''bbb'');\n            putStrLn ''io1'' (''ccc'');\n            putChar ''io1'' (CHR ''d'');\n            x \\<leftarrow> getChar ''io1'';\n            State_Monad.return x\n          })\"\n\nvalue \"printIO ''io2''\n        (do {\n            newIO ''io1'';\n            putStrLn ''io1'' (''aaa'');\n            putStrLn ''io1'' (''bbb'');\n            putStrLn ''io1'' (''ccc'');\n            putChar ''io1'' (CHR ''d'');\n            x \\<leftarrow> getChar ''io1'';\n            newIO ''io2'';\n            putStrLn ''io2'' (x);\n            putStrLn ''io2'' (''fff'');\n            putStrLn ''io2'' (''ggg'');\n            getLine ''io2'';\n            getLine ''io2'';\n            y \\<leftarrow> getLine ''io2'';\n            State_Monad.return y\n          })\"\n\nvalue \"printIO ''io2''\n        (do {\n            newIO ''io1'';\n            putStrLn ''io1'' (''aaa'');\n            putStrLn ''io1'' (''bbb'');\n            putStrLn ''io1'' (''ccc'');\n            putChar ''io1'' (CHR ''d'');\n            getChar ''io1'';\n            newIO ''io2'';\n            putStrLn ''io2'' (''eee'');\n            putStrLn ''io2'' (''fff'');\n            putStrLn ''io2'' (''ggg'');\n            x \\<leftarrow> getLine ''io2'';\n            State_Monad.return x\n          })\"\n\n\nsection \\<open>functor\\<close>\n\ntypedecl ('a, 'b, 'c, 'd) F\nconsts map_F :: \"('a \\<Rightarrow> 'a') \\<Rightarrow> ('b' \\<Rightarrow> 'b) \\<Rightarrow> ('c \\<Rightarrow> 'c') \\<Rightarrow> ('a, 'b, 'c, 'd) F \\<Rightarrow> ('a', 'b', 'c', 'd') F\"\nfunctor map_F sorry\n\ntypedecl 'a T\nconsts map_t :: \"('a \\<Rightarrow> 'a') \\<Rightarrow> 'a T \\<Rightarrow> 'a' T\"\nfunctor map_t sorry\n\nprimrec maplist2 :: \"('a \\<Rightarrow> 'b) \\<Rightarrow> 'a list \\<Rightarrow> 'b list\"\n  where \"maplist2 f [] = []\" |\n        \"maplist2 f (x # xs) = f x # maplist2 f xs\"\n\nfunctor maplist2\nproof \n  fix f g x\n  show \"(maplist2 f \\<circ> maplist2 g) x = maplist2 (f \\<circ> g) x\"\n    apply(induct x)\n      using maplist2.simps by auto\nnext\n  {\n    fix x\n    have \"(maplist2 id) x = id x\"\n      apply(induct x)\n        using maplist2.simps by auto\n  }\n  then show \"maplist2 id = id\" by blast\nqed\n\nthm AlgebraicStructure.list.comp\nthm list.comp\n\n(*\nfunctor map (* map function on list is a functor *)\n by auto\n(* Duplicate fact declaration \"AlgebraicStructure.list.comp\" vs. \"AlgebraicStructure.list.comp\" *)\n*)\n\nprimrec mapsome :: \"('a \\<Rightarrow> 'b) \\<Rightarrow> 'a option \\<Rightarrow> 'b option\"\n  where \"mapsome f None = None\" |\n        \"mapsome f (Some a) = Some (f a)\"\n\nfunctor mapsome\nproof\n  fix f g x\n  show \"(mapsome f \\<circ> mapsome g) x = mapsome (f \\<circ> g) x\"\n    apply(induct x)\n      using mapsome.simps by auto\nnext\n  show \"mapsome id = id\"\n    using mapsome.simps\n    by (metis eq_id_iff not_None_eq) \nqed\n\ndatatype 'a tree = Leaf 'a | Node \"'a tree\" \"'a tree\"\n\nprimrec maptree :: \"('a \\<Rightarrow> 'b) \\<Rightarrow> 'a tree \\<Rightarrow> 'b tree\"\n  where \"maptree f (Leaf a) = Leaf (f a)\" |\n        \"maptree f (Node l r) = Node (maptree f l) (maptree f r)\"\n\nlemma lmmt1: \"(maptree f \\<circ> maptree g) x = (maptree (f \\<circ> g)) x\"\n  apply(induct x)\n  using maplist2.simps by auto\n\nlemma lmmt2: \"(maptree id) x = id x\"\n  apply(induct x)\n  using maptree.simps by auto\n\nfunctor maptree\nproof \n  fix f::\"'b \\<Rightarrow> 'c\" \n  fix g::\"'a \\<Rightarrow> 'b\" \n  fix x::\"'a tree\"\n  show \"(maptree f \\<circ> maptree g) x = maptree (f \\<circ> g) x\"\n    using lmmt1 by simp\nnext\n  show \"maptree id = id\" \n    using lmmt2 by blast\nqed\n\n(*\nlocale Functor =\n  fixes fmap :: \"('a \\<Rightarrow> 'b) \\<Rightarrow> 'a T \\<Rightarrow> 'b T\"\n  assumes \"fmap f \\<circ> fmap g = fmap (f \\<circ> g)\"\n*)\n\n\nend", "meta": {"author": "LVPGroup", "repo": "fpp", "sha": "7e18377ea2c553bf6e57412727a4f06832d93577", "save_path": "github-repos/isabelle/LVPGroup-fpp", "path": "github-repos/isabelle/LVPGroup-fpp/fpp-7e18377ea2c553bf6e57412727a4f06832d93577/2_functionalprog/AlgebraicStructure.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357735451834, "lm_q2_score": 0.8633916029436189, "lm_q1q2_score": 0.7485914063306365}}
{"text": "(*  Author:     Makarius\n\nExample theory involving Unicode characters (UTF-8 encoding) -- both\nformal and informal ones.\n*)\n\nsection \\<open>A Hebrew theory\\<close>\n\ntheory Hebrew\nimports Main\nbegin\n\ntext \\<open>The Hebrew Alef-Bet (\u05d0-\u05d1).\\<close>\n\ndatatype alef_bet =\n    Alef    (\"\u05d0\")\n  | Bet     (\"\u05d1\")\n  | Gimel   (\"\u05d2\")\n  | Dalet   (\"\u05d3\")\n  | He      (\"\u05d4\")\n  | Vav     (\"\u05d5\")\n  | Zayin   (\"\u05d6\")\n  | Het     (\"\u05d7\")\n  | Tet     (\"\u05d8\")\n  | Yod     (\"\u05d9\")\n  | Kaf     (\"\u05db\")\n  | Lamed   (\"\u05dc\")\n  | Mem     (\"\u05de\")\n  | Nun     (\"\u05e0\")\n  | Samekh  (\"\u05e1\")\n  | Ayin    (\"\u05e2\")\n  | Pe      (\"\u05e4\")\n  | Tsadi   (\"\u05e6\")\n  | Qof     (\"\u05e7\")\n  | Resh    (\"\u05e8\")\n  | Shin    (\"\u05e9\")\n  | Tav     (\"\u05ea\")\n\nthm alef_bet.induct\n\n\ntext \\<open>Interpreting Hebrew letters as numbers.\\<close>\n\nprimrec mispar :: \"alef_bet => nat\"\nwhere\n  \"mispar \u05d0 = 1\"\n| \"mispar \u05d1 = 2\"\n| \"mispar \u05d2 = 3\"\n| \"mispar \u05d3 = 4\"\n| \"mispar \u05d4 = 5\"\n| \"mispar \u05d5 = 6\"\n| \"mispar \u05d6 = 7\"\n| \"mispar \u05d7 = 8\"\n| \"mispar \u05d8 = 9\"\n| \"mispar \u05d9 = 10\"\n| \"mispar \u05db = 20\"\n| \"mispar \u05dc = 30\"\n| \"mispar \u05de = 40\"\n| \"mispar \u05e0 = 50\"\n| \"mispar \u05e1 = 60\"\n| \"mispar \u05e2 = 70\"\n| \"mispar \u05e4 = 80\"\n| \"mispar \u05e6 = 90\"\n| \"mispar \u05e7 = 100\"\n| \"mispar \u05e8 = 200\"\n| \"mispar \u05e9 = 300\"\n| \"mispar \u05ea = 400\"\n\nthm mispar.simps\n\nlemma \"mispar \u05e7 + mispar \u05dc + mispar \u05d4 = 135\"\n  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/ex/Hebrew.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357598021707, "lm_q2_score": 0.8633916099737806, "lm_q1q2_score": 0.7485914005604364}}
{"text": "(*  Title:      HOL/Algebra/Multiplicative_Group_Revised.thy\n    Author:     Paulo Em\u00edlio de Vilhena\n*)\n\ntheory Multiplicative_Group_Revised\n  imports Cycles Generated_Groups Polynomials\n\nbegin\n\nsection \\<open>Multiplicative Group\\<close>\n\nsubsection \\<open>Definitions\\<close>\n\ndefinition l_mult :: \"_ \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> 'a\" (\"l'_mult\\<index>\")\n  where \"l_mult\\<^bsub>G\\<^esub> a = (\\<lambda>b. if b \\<in> carrier G then a \\<otimes>\\<^bsub>G\\<^esub> b else b)\"\n\ndefinition ord :: \"_ \\<Rightarrow> 'a \\<Rightarrow> nat\"\n  where \"ord G a = least_power (l_mult\\<^bsub>G\\<^esub> a) \\<one>\\<^bsub>G\\<^esub>\"\n\n\nsubsection \\<open>Basic Properties\\<close>\n\nlemma (in monoid) l_mult_one:\n  shows \"a \\<in> carrier G \\<Longrightarrow> (l_mult a) \\<one> = a\" and \"(l_mult \\<one>) a = a\"\n  unfolding l_mult_def by auto \n\nlemma (in monoid) l_mult_mult:\n  assumes \"a \\<in> carrier G\" and \"b \\<in> carrier G\" shows \"(l_mult a) \\<circ> (l_mult b) = (l_mult (a \\<otimes> b))\"\n  using assms unfolding l_mult_def by (auto simp add: m_assoc)\n\nlemma (in group) l_mult_inv:\n  assumes \"a \\<in> carrier G\" shows \"((l_mult a) \\<circ> (l_mult (inv a))) b = b\"\n  using assms l_mult_one(2) l_mult_mult[OF _ inv_closed] by simp\n\nlemma (in monoid) exp_of_l_mult:\n  assumes \"a \\<in> carrier G\" shows \"(l_mult a) ^^ n = (l_mult (a [^]\\<^bsub>G\\<^esub> n))\"\n  using assms\nproof (induct n)\n  case 0 thus ?case\n    unfolding l_mult_def by auto\nnext\n  case (Suc n)\n  hence \"(l_mult a) ^^ Suc n = (l_mult a) \\<circ> (l_mult (a [^]\\<^bsub>G\\<^esub> n))\"\n    by (simp add: funpow_swap1)\n  thus ?case\n    using l_mult_mult[of a \"a [^]\\<^bsub>G\\<^esub> n\"] Suc(2) nat_pow_Suc2 by auto \nqed\n\nlemma (in group) l_mult_permutes:\n  assumes \"a \\<in> carrier G\" shows \"(l_mult a) permutes (carrier G)\"\nproof (rule bij_imp_permutes)\n  show \"l_mult a b = b\" if \"b \\<notin> carrier G\" for b\n    using that unfolding l_mult_def by simp\nnext\n  show \"bij_betw (l_mult a) (carrier G) (carrier G)\"\n  proof (rule bij_betw_byWitness[where ?f' = \"l_mult (inv a)\"])\n    show \"\\<forall>b \\<in> carrier G. l_mult (inv a) (l_mult a b) = b\"\n      using l_mult_inv[OF inv_closed[OF assms]] unfolding inv_inv[OF assms] by simp\n    show \"\\<forall>b \\<in> carrier G. l_mult a (l_mult (inv a) b) = b\"\n      using l_mult_inv[OF assms] by simp \n    show \"l_mult a ` carrier G \\<subseteq> carrier G\" and \"l_mult (inv a) ` carrier G \\<subseteq> carrier G\"\n      using assms inv_closed[OF assms] unfolding l_mult_def by auto\n  qed\nqed\n\nlemma (in group) l_mult_permutation:\n  assumes \"finite (carrier G)\" and \"a \\<in> carrier G\" shows \"permutation (l_mult a)\"\n  using assms(1) l_mult_permutes[OF assms(2)] unfolding permutation_permutes by auto\n\nlemma (in group) ord_pow:\n  assumes \"finite (carrier G)\" and \"a \\<in> carrier G\"\n  shows \"a [^] (ord G a) = \\<one>\" and \"(ord G a) > 0\"\n  using least_power_of_permutation[OF l_mult_permutation[OF assms], of \\<one>] l_mult_one(1) assms(2)\n  unfolding ord_def exp_of_l_mult[OF assms(2)] by auto\n\nlemma (in group) ord_gt_one:\n  assumes \"finite (carrier G)\" and \"a \\<in> carrier G - { \\<one> }\" shows \"(ord G a) > 1\"\nproof -\n  have \"a = \\<one>\" if \"ord G a = 1\"\n    using ord_pow[OF assms(1), of a] assms(2) unfolding that by simp\n  hence \"ord G a \\<noteq> 1\"\n    using assms(2) by blast\n  thus ?thesis\n    using ord_pow[of a] assms by simp\nqed\n\nlemma (in group) ord_minimal:\n  assumes \"a \\<in> carrier G\" and \"a [^] n = \\<one>\" shows \"(ord G a) dvd n\"\n  using assms(1) l_mult_one exp_of_l_mult[of a n] unfolding ord_def assms(2)\n  by (simp add: least_power_minimal)\n\nlemma (in group) ord_dvd:\n  assumes \"finite (carrier G)\" and \"a \\<in> carrier G\" shows \"(ord G a) dvd n \\<longleftrightarrow> a [^] n = \\<one>\"\n  using assms(2) l_mult_one(1) exp_of_l_mult\n  unfolding ord_def least_power_dvd[OF l_mult_permutation[OF assms(1-2)]] by simp\n\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/Multiplicative_Group_Revised.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357598021707, "lm_q2_score": 0.8633916082162403, "lm_q1q2_score": 0.748591399036586}}
{"text": "(*\nBoolean Expression Checkers Based on Binary Decision Trees\nAuthor: Tobias Nipkow\n*)\n\ntheory Boolean_Expression_Checkers\nimports Main\nbegin\n\nsection{* Tautology (etc) Checking via Binary Decision Trees *}\n\nsubsection {* Boolean Expressions *}\n\ntext{* This is the interface to the tautology checker. If you have your own\ntype of boolean expressions you need to translate into this type first. *}\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\n\nsubsection{* Binary Decision Trees *}\n\ndatatype 'a ifex = Trueif | Falseif | IF 'a \"'a ifex\" \"'a ifex\"\n\nfun val_ifex :: \"'a ifex \\<Rightarrow> ('a \\<Rightarrow> bool) \\<Rightarrow> bool\" where\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\n\nsubsection{* A Simple Minded Translation *}\n\ntext {* Simple minded normalisation, can create branches with repeated vars: *}\n\nprimrec normif0 :: \"'a ifex \\<Rightarrow> 'a ifex \\<Rightarrow> 'a ifex \\<Rightarrow> 'a ifex\" where\n\"normif0 Trueif t1 t2 = t1\" |\n\"normif0 Falseif t1 t2 = t2\" |\n\"normif0 (IF x t1 t2) t3 t4 = IF x (normif0 t1 t3 t4) (normif0 t2 t3 t4)\"\n\ntext {* The corresponding translation from boolean expressions to if-expressions: *}\n\nprimrec ifex0 :: \"'a bool_expr \\<Rightarrow> 'a ifex\" where\n\"ifex0 (Const_bool_expr b) = (if b then Trueif else Falseif)\" |\n\"ifex0 (Atom_bool_expr x)   = IF x Trueif Falseif\" |\n\"ifex0 (Neg_bool_expr b)   = normif0 (ifex0 b) Falseif Trueif\" |\n\"ifex0 (And_bool_expr b1 b2) = normif0 (ifex0 b1) (ifex0 b2) Falseif\" |\n\"ifex0 (Or_bool_expr b1 b2) = normif0 (ifex0 b1) Trueif (ifex0 b2)\" |\n\"ifex0 (Imp_bool_expr b1 b2) = normif0 (ifex0 b1) (ifex0 b2) Trueif\" |\n\"ifex0 (Iff_bool_expr b1 b2) = (let t1 = ifex0 b1; t2 = ifex0 b2 in\n   normif0 t1 t2 (normif0 t2 Falseif Trueif))\"\n\nlemma val_normif0:\n  \"val_ifex (normif0 t t1 t2) s = val_ifex (if val_ifex t s then t1 else t2) s\"\nby(induct t arbitrary: t1 t2) auto\n\ntheorem val_ifex0: \"val_ifex (ifex0 b) = val_bool_expr b\"\nby(induct_tac b)(auto simp: val_normif0 Let_def)\n\n\nsubsection{* Translation to Reduced Binary Decision Trees *}\n\ntext {* An improved translation. *}\n\nsubsubsection{* Environment *}\n\ntext{* Environments are substitutions of values for variables: *}\n\ntype_synonym 'a env_bool = \"('a * bool) list\"\n\ndefinition agree :: \"('a \\<Rightarrow> bool) \\<Rightarrow> 'a env_bool \\<Rightarrow> bool\" where\n\"agree s env = (\\<forall>x b. map_of env x = Some b \\<longrightarrow> s x = b)\"\n\nlemma agree_Nil: \"agree s []\"\nby(simp add: agree_def)\n\nlemma agree_Cons: \"distinct(map fst env) \\<Longrightarrow> x \\<notin> set(map fst env)\n  \\<Longrightarrow> agree s ((x,b) # env) = ((if b then s x else \\<not> s x) \\<and> agree s env)\"\nby(auto simp: agree_def image_iff)\n\nlemma agreeDT:\n  \"\\<lbrakk> agree s env; distinct (map fst env) \\<rbrakk> \\<Longrightarrow> (x,True) \\<in> set env \\<Longrightarrow> s x\"\nby(simp add: agree_def)\n\nlemma agreeDF:\n  \"\\<lbrakk> agree s env; distinct (map fst env) \\<rbrakk> \\<Longrightarrow> (x,False) \\<in> set env \\<Longrightarrow> \\<not> s x\"\nby(simp add: agree_def)\n\nsubsubsection{* Translation and Normalisation *}\n\ntext {* A normalisation avoiding duplicate variables and collapsing\n  @{term \"If x t t\"} to @{text t}. *}\n\ndefinition mkIF :: \"'a \\<Rightarrow> 'a ifex \\<Rightarrow> 'a ifex \\<Rightarrow> 'a ifex\" where\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\" where\n\"reduce env (IF x t1 t2) = (case map_of env x of\n     None \\<Rightarrow> mkIF x (reduce ((x,True)#env) t1) (reduce ((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\" where\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 map_of env x of\n     None \\<Rightarrow> mkIF x (normif ((x,True)#env) t1 t3 t4) (normif ((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\nprimrec 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 [] (ifex_of b) Falseif Trueif\" |\n\"ifex_of (And_bool_expr b1 b2) = normif [] (ifex_of b1) (ifex_of b2) Falseif\" |\n\"ifex_of (Or_bool_expr b1 b2) = normif [] (ifex_of b1) Trueif (ifex_of b2)\" |\n\"ifex_of (Imp_bool_expr b1 b2) = normif [] (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 [] t1 t2 (normif [] t2 Falseif Trueif))\"\n\nsubsubsection{* Functional Correctness Proof *}\n\nlemma val_mkIF: \"val_ifex (mkIF x t1 t2) s = val_ifex (IF x t1 t2) s\"\nby(auto simp: mkIF_def Let_def)\n\ntheorem val_reduce: \"agree s env \\<Longrightarrow> distinct(map fst env) \\<Longrightarrow>\n  val_ifex (reduce env t) s = val_ifex t s\"\napply(induct t arbitrary: s env)\napply(auto simp: map_of_eq_None_iff val_mkIF agree_Cons Let_def\n  dest: agreeDT agreeDF split: option.splits)\ndone\n\nlemma val_normif: \"agree s env \\<Longrightarrow> distinct(map fst env) \\<Longrightarrow>\n  val_ifex (normif env t t1 t2) s =\n  val_ifex (if val_ifex t s then t1 else t2) s\"\napply(induct t arbitrary: t1 t2 s env)\napply(auto simp: val_reduce val_mkIF agree_Cons map_of_eq_None_iff\n  dest: agreeDT agreeDF split: option.splits)\ndone\n\ntheorem val_ifex: \"val_ifex (ifex_of b) s = val_bool_expr b s\"\nby(induct_tac b)(auto simp: val_normif agree_Nil Let_def)\n\nsubsubsection{* A Tautology Checker for Arbitrary If-Expressions *}\n\ntext{* Not really needed because @{const ifex_of} produces reduced\nexpressions which can be checked very easily. *}\n\nfun taut_test_rec :: \"'a ifex \\<Rightarrow> 'a env_bool \\<Rightarrow> bool\" where\n\"taut_test_rec Trueif env = True\" |\n\"taut_test_rec Falseif env = False\" |\n\"taut_test_rec (IF x t1 t2) env = (case map_of env x of\n  Some b \\<Rightarrow> taut_test_rec (if b then t1 else t2) env |\n  None \\<Rightarrow> taut_test_rec t1 ((x,True)#env) \\<and> taut_test_rec t2 ((x,False)#env))\"\n\nlemma taut_test_rec: \"distinct(map fst env)\n  \\<Longrightarrow> taut_test_rec t env = (\\<forall>s. agree s env \\<longrightarrow> val_ifex t s)\"\nproof(induct t arbitrary: env)\n  case Trueif thus ?case by simp\nnext\n  case Falseif\n  have \"agree (\\<lambda>x. the(map_of env x)) env\" by(auto simp: agree_def)\n  thus ?case by(auto)\nnext\n  case (IF x t1 t2) show ?case\n  proof (cases \"map_of env x\")\n    case None thus ?thesis using IF\n      by (simp) (auto simp: map_of_eq_None_iff image_iff agree_Cons)\n  next\n    case Some thus ?thesis using IF\n      by (simp add: agree_def)\n  qed\nqed\n\ndefinition taut_test_ifex :: \"'a ifex \\<Rightarrow> bool\" where\n\"taut_test_ifex t = taut_test_rec t []\"\n\ncorollary taut_test_ifex: \"taut_test_ifex t = (\\<forall>s. val_ifex t s)\"\nusing taut_test_rec[of \"[]\" t]\nby (auto simp: val_ifex taut_test_ifex_def agree_Nil)\n\nsubsubsection{* Reduced If-Expressions *}\n\ntext{* Proof that the result of @{const ifex_of} is reduced.\nAn expression reduced iff no variable appears twice on any branch and\nthere is no subexpression @{term\"IF x t t\"}. *}\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: \"X \\<subseteq> Y \\<Longrightarrow> reduced t Y \\<Longrightarrow> reduced t X\"\napply(induction t arbitrary: X Y)\nby auto (metis insert_mono)+\n\nlemma reduced_mkIF: \"x \\<notin> X \\<Longrightarrow>\n  reduced t1 (insert x X) \\<Longrightarrow> reduced t2 (insert x X) \\<Longrightarrow> reduced (mkIF x t1 t2) X\"\nby(auto simp: mkIF_def intro:reduced_antimono)\n\nlemma reduced_reduce:\n  \"distinct(map fst env) \\<Longrightarrow> reduced (reduce env t) (fst ` set env)\"\nproof(induction t arbitrary: env)\n  case (IF x t1 t2)\n  thus ?case using IF.IH(1)[of \"(x, True) # env\"] IF.IH(2)[of \"(x, False) # env\"]\n    by(auto simp: map_of_eq_None_iff image_iff reduced_mkIF split: option.split)\nqed auto\n\nlemma reduced_normif:\n  \"distinct(map fst env) \\<Longrightarrow> reduced (normif env t t1 t2) (fst ` set env)\"\nproof(induction t arbitrary: t1 t2 env)\n  case (IF x s1 s2)\n  thus ?case using IF.IH(1)[of \"(x, True) # env\"] IF.IH(2)[of \"(x, False) # env\"]\n    by(auto simp: reduced_mkIF map_of_eq_None_iff split: option.split)\nqed (auto simp: reduced_reduce)\n\ntheorem reduced_ifex: \"reduced (ifex_of b) {}\"\nby(induct b)(auto simp: reduced_normif[of \"[]\", simplified] Let_def)\n\ntext{* Proof that reduced if-expressions are @{const Trueif}, @{const Falseif}\nor can evaluate to both @{const True} and @{const False}. *}\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\"\nby(induction t arbitrary: X) auto\n\nlemma reduced_IF_depends: \"\\<lbrakk> reduced t X; t \\<noteq> Trueif; t \\<noteq> Falseif \\<rbrakk>\n  \\<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 Trueif[simp]\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 Falseif[simp]\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\n\nsubsection{* Tautology Checking *}\n\ndefinition taut_test :: \"'a bool_expr \\<Rightarrow> bool\" where\n\"taut_test b = (ifex_of b = Trueif)\"\n\ncorollary taut_test: \"taut_test b = (\\<forall>s. val_bool_expr b s)\"\nunfolding taut_test_def using reduced_IF_depends[OF reduced_ifex, of b]\nby (metis val_ifex val_ifex.simps)\n\n\nsubsection{* Satisfiability Checking *}\n\ndefinition sat_test :: \"'a bool_expr \\<Rightarrow> bool\" where\n\"sat_test b = (ifex_of b \\<noteq> Falseif)\"\n\ncorollary sat_test: \"sat_test b = (\\<exists>s. val_bool_expr b s)\"\nunfolding sat_test_def using reduced_IF_depends[OF reduced_ifex, of b]\nby (metis val_ifex val_ifex.simps(1) val_ifex.simps(2))\n\n\nsubsection{* Equivalence Checking *}\n\ndefinition equiv_test :: \"'a bool_expr \\<Rightarrow> 'a bool_expr \\<Rightarrow> bool\" where\n\"equiv_test b1 b2 = taut_test (Iff_bool_expr b1 b2)\"\n\ncorollary equiv_test: \"equiv_test b1 b2 = (\\<forall>s. val_bool_expr b1 s = val_bool_expr b2 s)\"\nby(auto simp:equiv_test_def taut_test)\n\n\ntext{* Hide everything except the boolean expressions and the checkers. *}\n\nhide_type (open) ifex env_bool\nhide_const (open)  Trueif Falseif IF val_ifex normif0 ifex0 agree mkIF\n  reduce normif ifex_of reduced taut_test_rec taut_test_ifex\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/Boolean_Expression_Checkers/Boolean_Expression_Checkers.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.863391599428538, "lm_q2_score": 0.8670357649558006, "lm_q1q2_score": 0.7485913958669347}}
{"text": "theory examples\n  imports labellings (* extensions*)\nbegin\n\nnitpick_params[assms=true, user_axioms=true, show_all, expect=genuine, format=2] (*default settings*)\n\n(************************************************************************)\n(************************************************************************)\n(* EXAMPLES *)\n(************************************************************************)\n(************************************************************************)\n\n(* Example set-up from [BG2011], Figure 4 *)\nlocale ExFig4 begin\ndatatype Arg = A | B | C | D\n  fun att :: \\<open>Arg Rel\\<close> where\n    \"att A B = True\" |\n    \"att B C = True\" |\n    \"att C D = True\" |\n    \"att D C = True\" |\n    \"att _ _ = False\"\n\n(* admissible labellings *)\nlemma \\<open>admissible att Lab\\<close> nitpick[satisfy] oops\n(* ask nitpick for all admissible labellings *) \nlemma \\<open>findFor2 att admissible Labs\\<close> nitpick[satisfy, eval = \"card Labs\"] oops\n(* this gives us: {(\\<lambda>x. _)(A := In, B := Out, C := In, D := Out), (\\<lambda>x. _)(A := In, B := Out, C := Out, D := In), (\\<lambda>x. _)\n       (A := In, B := Out, C := Undec, D := Undec), (\\<lambda>x. _)(A := In, B := Undec, C := Out, D := In), (\\<lambda>x. _)\n       (A := In, B := Undec, C := Undec, D := Undec), (\\<lambda>x. _)(A := Undec, B := Undec, C := Out, D := In), (\\<lambda>x. _)\n       (A := Undec, B := Undec, C := Undec, D := Undec)} *)\n(* checked: these are exactly the 7 labellings given in [BG2011] *) \n(* we can even ask nitpick to give us that number explicitly using eval *)\n\n(* complete labellings *)\nlemma \\<open>complete att Lab\\<close> nitpick[satisfy] oops\nlemma \\<open>findFor2 att complete Labs\\<close> nitpick[satisfy, eval = \"card Labs\"] oops\n(* checked: these are exactly the 3 labellings given in [BG2011] *) \n\n(* grounded labellings *)\nlemma \\<open>grounded att Lab\\<close> nitpick[satisfy] oops\nlemma \\<open>findFor2 att grounded Labs\\<close> nitpick[satisfy,box=false, eval = \"card Labs\"] oops\n(* checked: these is exactly the one labelling given in [BG2011] *)   \n(* comment: we have to disable boxing for nitpick to find the model *)\n\n(* preferred labellings *)\nlemma \\<open>preferred att Lab\\<close> nitpick[satisfy] oops\nlemma \\<open>findFor2 att preferred Labs\\<close> nitpick[satisfy,box=false, eval = \"card Labs\"] oops\n(* checked: these are exactly the two labellings given in [BG2011] *)   \n(* comment: we have to disable boxing for nitpick to find the model *)\n\n(* stable labellings *)\nlemma \\<open>stable att Lab\\<close> nitpick[satisfy] oops\nlemma \\<open>findFor2 att stable Labs\\<close> nitpick[satisfy,box=false, eval = \"card Labs\"] oops\n(* checked: these are exactly the two labellings given in [BG2011] *)   \n(* comment: we have to disable boxing for nitpick to find the model *)\n\n(* semi-stable labellings *)\nlemma \\<open>semistable att Lab\\<close> nitpick[satisfy] oops\nlemma \\<open>findFor2 att semistable Labs\\<close> nitpick[satisfy,box=false, eval = \"card Labs\"] oops\n(* checked: these are exactly the two labellings given in [BG2011] *)   \n(* comment: we have to disable boxing for nitpick to find the model *)\n\n\n(* ideal labellings: Check this out in detail, the results are weird. But I did not spend time on\nideal labellings sofar. *)\nlemma \\<open>ideal att Lab\\<close> oops\nlemma \\<open>findFor2 att ideal Labs\\<close> oops\n(*expected: same as grounded *)\nend \n\n\n(* Example set-up from [BG2011], Figure 5 *)\nlocale ExFig5 begin\ndatatype Arg = A | B | C | D\n  fun att :: \\<open>Arg Rel\\<close> where\n    \"att A B = True\" |\n    \"att B A = True\" |\n    \"att A C = True\" |\n    \"att B C = True\" |\n    \"att C D = True\" |\n    \"att _ _ = False\"\n\n(* admissible labellings *)\nlemma \\<open>admissible att Lab\\<close> nitpick[satisfy] oops\n(* ask nitpick for all  z admissible labellings *) \nlemma \\<open>findFor2 att admissible Labs\\<close> nitpick[satisfy, eval = \"card Labs\"] oops\n(* this gives us: Labs =\n      {(\\<lambda>x. _)(A := In, B := Out, C := Out, D := In), (\\<lambda>x. _)(A := In, B := Out, C := Out, D := Undec), (\\<lambda>x. _)\n       (A := In, B := Out, C := Undec, D := Undec), (\\<lambda>x. _)(A := Out, B := In, C := Out, D := In), (\\<lambda>x. _)\n       (A := Out, B := In, C := Out, D := Undec), (\\<lambda>x. _)(A := Out, B := In, C := Undec, D := Undec), (\\<lambda>x. _)\n       (A := Undec, B := Undec, C := Undec, D := Undec)} *)\n(* these are 7 labellings, as mentioned in [BG2011]; I havent checked them all. *) \n\n(* complete labellings *)\nlemma \\<open>complete att Lab\\<close> nitpick[satisfy] oops\nlemma \\<open>findFor2 att complete Labs\\<close> nitpick[satisfy, eval = \"card Labs\"] oops\n(* checked: these are exactly the 3 labellings given in [BG2011] *) \n\n(* grounded labellings *)\nlemma \\<open>grounded2 att Lab\\<close> nitpick[satisfy] oops\nlemma \\<open>findFor2 att grounded Labs\\<close> nitpick[satisfy, box=false, eval = \"card Labs\"] oops\n(* (comment: using the the definition above requires disabling boxing for nitpick to find a model)*)\nlemma \\<open>findFor2 att grounded2 Labs\\<close> nitpick[satisfy, eval = \"card Labs\"] oops\n(* checked: these is exactly the one labelling given in [BG2011] *)   \n\n(* preferred labellings *)\nlemma \\<open>preferred att Lab\\<close> nitpick[satisfy] oops\nlemma \\<open>findFor2 att preferred Labs\\<close> nitpick[satisfy, box=false, eval = \"card Labs\"] oops\n(* checked: these are exactly the two labellings given in [BG2011] *)   \n(* (comment: we have to disable boxing for nitpick to find the model) *)\n\n(* stable labellings *)\nlemma \\<open>stable att Lab\\<close> nitpick[satisfy] oops\nlemma \\<open>findFor2 att stable Labs\\<close> nitpick[satisfy,box=false, eval = \"card Labs\"] oops\n(* checked: these are exactly the two labellings given in [BG2011] *)   \n(* comment: we have to disable boxing for nitpick to find the model *)\n\n(* semi-stable labellings *)\nlemma \\<open>semistable att Lab\\<close> nitpick[satisfy] oops\nlemma \\<open>findFor2 att semistable Labs\\<close> nitpick[satisfy,box=false, eval = \"card Labs\"] oops\n(* checked: these are exactly the two labellings given in [BG2011] *)   \n(* comment: we have to disable boxing for nitpick to find the model *)\nend\n\n(* Example set-up from [BG2011], Figure 6 *)\nlocale ExFig6 begin\ndatatype Arg = A | B | C  \n  fun att :: \\<open>Arg Rel\\<close> where\n    \"att A B = True\" |\n    \"att B C = True\" |\n    \"att C A = True\" |\n    \"att _ _ = False\"\n\n(* admissible labellings *)\nlemma \\<open>admissible att Lab\\<close> nitpick[satisfy] oops\n(* ask nitpick for all admissible labellings *) \nlemma \\<open>findFor2 att admissible Labs\\<close> nitpick[satisfy, eval = \"card Labs\"] oops\n(* this gives us: Labs = {(\\<lambda>x. _)(A := Undec, B := Undec, C := Undec)} *)\n(* this is the one trivial labelling, as mentioned in [BG2011]. *) \n\n(* complete labellings *)\nlemma \\<open>complete att Lab\\<close> nitpick[satisfy] oops\nlemma \\<open>findFor2 att complete Labs\\<close> nitpick[satisfy, eval = \"card Labs\"] oops\n(* checked: this is the one trivial labelling, as mentioned in [BG2011].*) \n\n(* grounded labellings *)\nlemma \\<open>grounded att Lab\\<close> nitpick[satisfy] oops\nlemma \\<open>findFor2 att grounded2 Labs\\<close> nitpick[satisfy, eval = \"card Labs\"] oops\n(* checked: this is the one trivial labelling, as mentioned in [BG2011].*) \n\n(* preferred labellings *)\nlemma \\<open>preferred att Lab\\<close> nitpick[satisfy] oops\nlemma \\<open>findFor2 att preferred Labs\\<close> nitpick[satisfy,box=false, eval = \"card Labs\"] oops\n(* checked: this is the one trivial labelling, as mentioned in [BG2011].*) \n(* comment: we have to disable boxing for nitpick to find the model *)\n\n(* stable labellings *)\nlemma \\<open>findFor2 att stable Labs\\<close> nitpick[satisfy,box=false, eval = \"card Labs\"] oops\n(* checked: these are no stable labellings, see [BG2011] *)   \n(* comment: we have to disable boxing for nitpick to find the model *)\n\n(* semi-stable labellings *)\nlemma \\<open>semistable att Lab\\<close> nitpick[satisfy] oops\nlemma \\<open>findFor2 att semistable Labs\\<close> nitpick[satisfy,box=false, eval = \"card Labs\"] oops\n(* checked: this is the one trivial labelling, as mentioned in [BG2011].*) \n(* comment: we have to disable boxing for nitpick to find the model *)\nend\n\n\n(******************************)\n(* further tests with locales *)\n\n(* Lab is an admissible labelling *)\nlocale ExFig4Admissible = ExFig4 +\n  fixes Lab :: \\<open>Arg Labelling\\<close>\n  assumes \\<open>admissible att Lab\\<close>\nbegin\n\n(* Confirms what [BG2011] says: A can only be labelled legally In or Undec *)\n(* lemma \\<open>Lab(A) = In \\<or> Lab(A) = Undec\\<close> unfolding Defs *)\nlemma \\<open>in Lab A \\<or> undec Lab A\\<close> unfolding Defs\n  using ExFig4Admissible_axioms ExFig4Admissible_def ExFig4.att.simps(14) Label.exhaust admissible_def legallyOut_def by (metis outset_def)\n  (* by (metis ExFig4Admissible_axioms ExFig4Admissible_def ExFig4.att.simps(14) Label.exhaust admissible_def legallyOut_def) *)\n\n(* Confirms what [BG2011] says: If A is labelled Undec, then B has to be labelled Undec as well *)\n(* lemma \\<open>Lab(A) = Undec \\<Longrightarrow> Lab(B) = Undec\\<close> unfolding Defs *)\nlemma \\<open>undec Lab A \\<Longrightarrow> undec Lab B\\<close> unfolding Defs \n  using ExFig4Admissible_axioms ExFig4Admissible_def ExFig4.Arg.distinct(7) ExFig4.Arg.distinct(9) ExFig4.att.elims(2) ExFig4.att.simps(1) Label.distinct(3) Label.distinct(5) Label.exhaust admissible_def legallyIn_def legallyOut_def\n  by (smt (z3) inset_def outset_def)\n  (* by (metis (full_types) ExFig4Admissible_axioms ExFig4Admissible_def ExFig4.Arg.distinct(7) ExFig4.Arg.distinct(9) ExFig4.att.elims(2) ExFig4.att.simps(1) Label.distinct(3) Label.distinct(5) Label.exhaust admissible_def legallyIn_def legallyOut_def) *)\nend\n\n\n(* Small test: Test-setup as locale merging of admissible labelling with Figure locale. *)\nlocale AdmissibleLab =\n  fixes Lab :: \\<open>'a Labelling\\<close>\n  assumes \\<open>admissible att Lab\\<close>\n(* saves a bit of writing work, but makes the tools slower, it seems (see below) *)\nlocale ExFig4Admissible2 = ExFig4 + AdmissibleLab Lab\n  for Lab :: \\<open>ExFig4.Arg Labelling\\<close> \nbegin\n\n(* A can only be labelled legally In or Undec *)\n(* lemma \\<open>Lab(A) = In \\<or> Lab(A) = Undec\\<close> unfolding Defs  *)\nlemma \\<open>in Lab A \\<or> undec Lab A\\<close> unfolding Defs\n  using AdmissibleLab_axioms AdmissibleLab_def ExFig4.att.simps(14) Label.exhaust admissible_def legallyOut_def\n  by (metis outset_def)\n  (* by (metis AdmissibleLab_axioms AdmissibleLab_def ExFig4.att.simps(14) Label.exhaust admissible_def legallyOut_def) *)\n\n\n\n\n\n(* If A is labelled Undec, then B has to be labelled Undec as well *)\n(* lemma \\<open>Lab(A) = Undec \\<Longrightarrow> Lab(B) = Undec\\<close> unfolding Defs  *)\nlemma \\<open>undec Lab A \\<Longrightarrow> undec Lab B\\<close> unfolding Defs\n  using AdmissibleLab_axioms AdmissibleLab_def ExFig4.Arg.distinct(7) ExFig4.Arg.distinct(9) ExFig4.att.elims(2) ExFig4.att.simps(1) Label.distinct(3) Label.distinct(5) Label.exhaust admissible_def legallyIn_def legallyOut_def\n  by (smt (z3) inset_def outset_def)\n  (* by (metis (full_types) AdmissibleLab_axioms AdmissibleLab_def ExFig4.Arg.distinct(7) ExFig4.Arg.distinct(9) ExFig4.att.elims(2) ExFig4.att.simps(1) Label.distinct(3) Label.distinct(5) Label.exhaust admissible_def legallyIn_def legallyOut_def) *)\n\n(* ask nitpick for all admissible labellings: MUCH slower, so I commented it out. Works though *) \nlemma \\<open>findFor2 att admissible Labs\\<close> (* nitpick[satisfy]*) oops\n(* this gives us: {(\\<lambda>x. _)(A := In, B := Out, C := In, D := Out), (\\<lambda>x. _)(A := In, B := Out, C := Out, D := In), (\\<lambda>x. _)\n       (A := In, B := Out, C := Undec, D := Undec), (\\<lambda>x. _)(A := In, B := Undec, C := Out, D := In), (\\<lambda>x. _)\n       (A := In, B := Undec, C := Undec, D := Undec), (\\<lambda>x. _)(A := Undec, B := Undec, C := Out, D := In), (\\<lambda>x. _)\n       (A := Undec, B := Undec, C := Undec, D := Undec)} *)\n(* these are exactly the labellings given in [BG2011] *) \nend\n(* I will not be using sublocales for now, seems of little use *)\n\n(******************************)\n(* further tests with locales END *)\n(******************************)\n\n\n(*example set-ups copied from David Fuenmayor's extension-based version *)\n(*Example 1/3/8\nA mock argument between two persons I and A, whose countries are at\nwar, about who is responsible for blocking negotiation in their region.\nI: My government cannot negotiate with your government because your\ngovernment doesn't even recognize my government.\nA: Your government doesn't recognize my government either.\nI: But your government is a terrorist government.\n\nThe exchange between I and A can be\nrepresented by an argumentation framework (AR, attacks) as follows: AR =\n{i\\<^sub>1, i\\<^sub>2, a} and attacks = {(i\\<^sub>1, a), (a, i\\<^sub>1), (i\\<^sub>2, a)} with i\\<^sub>1, and i\\<^sub>2, denoting the first and\nthe second argument of I, respectively, and a denoting the argument of A.\nIt is not difficult to see that AF has exactly one preferred extension E = {i1, i2}*)\nlocale War_Example begin\n  datatype \\<alpha> = i\\<^sub>1 | i\\<^sub>2 | a\n  fun attacks ::\"\\<alpha>\\<Rightarrow>\\<alpha>\\<Rightarrow>bool\" where\n    \"attacks i\\<^sub>1 a = True\" |\n    \"attacks i\\<^sub>2 a = True\" |\n    \"attacks a i\\<^sub>1 = True\" |\n    \"attacks _ _ = False\"\n  \n  (*Uses nitpick to find a preferred extension to the argument graph defined above*)\n  lemma \"preferred(attacks) Lab\" nitpick[satisfy] oops\n  (* Read-off labeling: Lab(i1) = Lab(i2) = In, Lab(a) = Out *)\n\n  (*We can in fact get from nitpick all extensions in one shot*)\n  lemma \"findFor2 attacks preferred Labs\" nitpick[satisfy,timeout=70,box=false] oops\nend\n\n(*Example 9 (Nixon diamond). The well-known Nixon diamond example can be\nrepresented as an argumentation framework AF = (AR, attacks) with AR =\n{A, B}, and attacks = {(A, B), (B, A)} where A represents the argument \"Nixon\nis anti-pacifist since he is a republican\", and B represents the argument \"Nixon is\na pacifist since he is a quaker\". This argumentation framework has two preferred\nextensions, one in which Nixon is a pacifist and one in which Nixon is a quaker.*)\nlocale Nixon_Example begin\ndatatype \\<alpha> = A | B\nfun attacks ::\"\\<alpha>\\<Rightarrow>\\<alpha>\\<Rightarrow>bool\" where\n  \"attacks A B = True\" |\n  \"attacks B A = True\" |\n  \"attacks _ _ = False\"\n\n(* gives the expected results *)\nlemma \"preferred(attacks) Lab\" nitpick[satisfy,timeout=90] oops\nlemma \"findFor2 attacks preferred Labs\" nitpick[satisfy] oops\nend\n\nabbreviation \"isTotal R \\<equiv> \\<forall>x y. x \\<noteq> y \\<longrightarrow> R x y \\<or> R y x\"\nabbreviation \"isAsymm R \\<equiv> \\<forall>x y. R x y \\<longrightarrow> \\<not>R y x\"\nabbreviation \"isTrans R \\<equiv> \\<forall>x y z. R x y \\<and> R y z \\<longrightarrow> R x z\"\n\n(*Section 3.2\nExample: Stable Marriage Problem (infinitistic version)*)\nlocale SMP = \n  fixes prefM::\"'m\\<Rightarrow>'w\\<Rightarrow>'w\\<Rightarrow>bool\"\n    and prefW::\"'w\\<Rightarrow>'m\\<Rightarrow>'m\\<Rightarrow>bool\"\nassumes same_card:  \"\\<exists>g::'m\\<Rightarrow>'w. bij g\"\n    and prefM_total: \"\\<forall>m. isTotal (prefM m)\" \n    and prefM_asym: \"\\<forall>m. isAsymm (prefM m)\"\n    and prefM_trans: \"\\<forall>m. isTrans (prefM m)\"\n    and prefW_total: \"\\<forall>w. isTotal (prefW w)\" \n    and prefW_asym: \"\\<forall>w. isAsymm (prefW w)\"\n    and prefW_trans: \"\\<forall>w. isTrans (prefW w)\"\nbegin\n\nabbreviation attacksM::\"('m\\<times>'w)\\<Rightarrow>('m\\<times>'w)\\<Rightarrow>bool\" (infix \"\\<rightarrow>\\<^sub>m\" 50)\n  where \"x \\<rightarrow>\\<^sub>m y \\<equiv> (fst x = fst y) \\<and> prefM (fst x) (snd x) (snd y)\"\n\nabbreviation attacksW::\"('m\\<times>'w)\\<Rightarrow>('m\\<times>'w)\\<Rightarrow>bool\" (infix \"\\<rightarrow>\\<^sub>w\" 50)\n  where \"x \\<rightarrow>\\<^sub>w y \\<equiv> (snd x = snd y) \\<and> prefW (snd x) (fst x) (fst y)\"\n  \nabbreviation attacks::\"('m\\<times>'w)\\<Rightarrow>('m\\<times>'w)\\<Rightarrow>bool\" (infix \"\\<rightarrow>\" 50) where \"x \\<rightarrow> y \\<equiv> x \\<rightarrow>\\<^sub>m y \\<or> x \\<rightarrow>\\<^sub>w y\"\n\nlemma \"admissible(attacks) Lab\" nitpick[satisfy,show_all] oops\nlemma \"findFor2 attacks preferred Labs\"\n  nitpick[satisfy,box=true] oops\n\nlemma \"complete(attacks) Lab\" nitpick[satisfy] oops \nlemma \"stable(attacks) Lab\" nitpick[satisfy,card 'm=3, card 'w=3] oops (*finds one - TODO: verify*)\nlemma \"findFor2 attacks stable Labs\"\n  nitpick[satisfy,box=true] oops\nlemma \"grounded(attacks) Lab\"  oops  (* no result *)\nlemma \"preferred(attacks) Lab\"  oops (* no result *)\nlemma \"findFor2 attacks preferred Labs\" (* this works, on the contrary; why is that? *)\n  nitpick[satisfy,box=true] oops\nlemma \"findFor2 attacks preferred Labs\" (* this works, on the contrary; why is that? *)\n  nitpick[satisfy,card 'w = 2, card 'm = 2,box=false] oops\n(* result: Labs =\n      {(\\<lambda>x. _)\n       ((m\\<^sub>1, w\\<^sub>1) := Out, (m\\<^sub>1, w\\<^sub>2) := In, (m\\<^sub>2, w\\<^sub>1) := In,\n        (m\\<^sub>2, w\\<^sub>2) := Out)} *)\n\nlemma \"findFor2 attacks stable Labs\" (* this works, on the contrary; why is that? *)\n  nitpick[satisfy,card 'w = 2, card 'm = 2,box=true] oops\n(* result: Labs =\n      {(\\<lambda>x. _)\n       ((m\\<^sub>1, w\\<^sub>1) := In, (m\\<^sub>1, w\\<^sub>2) := Out, (m\\<^sub>2, w\\<^sub>1) := Out,\n        (m\\<^sub>2, w\\<^sub>2) := In)} *)\n\n\nend\n\n(*Example SMP (finitistic variant for n=3)*)\ndatatype w = w1 | w2 | w3\ndatatype m = m1 | m2 | m3\ntype_synonym c = \"m\\<times>w\" (*couples*)\nlocale SMP_finite =\n fixes prefM::\"m\\<Rightarrow>w\\<Rightarrow>w\\<Rightarrow>bool\"\n and prefW::\"w\\<Rightarrow>m\\<Rightarrow>m\\<Rightarrow>bool\"\nassumes  prefM_total: \"\\<forall>m. isTotal (prefM m)\" \n                 and prefM_asym: \"\\<forall>m. isAsymm (prefM m)\"\n                 and prefM_trans: \"\\<forall>m. isTrans (prefM m)\"\n                 and prefW_total: \"\\<forall>w. isTotal (prefW w)\" \n                 and prefW_asym: \"\\<forall>w. isAsymm (prefW w)\"\n                 and prefW_trans: \"\\<forall>w. isTrans (prefW w)\"\nbegin\n\nabbreviation attacksM::\"c\\<Rightarrow>c\\<Rightarrow>bool\" (infix \"\\<rightarrow>\\<^sub>m\" 50)\n  where \"x \\<rightarrow>\\<^sub>m y \\<equiv> (fst x = fst y) \\<and> prefM (fst x) (snd x) (snd y)\"\n\nabbreviation attacksW::\"c\\<Rightarrow>c\\<Rightarrow>bool\" (infix \"\\<rightarrow>\\<^sub>w\" 50)\n  where \"x \\<rightarrow>\\<^sub>w y \\<equiv> (snd x = snd y) \\<and> prefW (snd x) (fst x) (fst y)\"\n\nabbreviation attacks::\"c\\<Rightarrow>c\\<Rightarrow>bool\" (infix \"\\<rightarrow>\" 50) where \"x \\<rightarrow> y \\<equiv> x \\<rightarrow>\\<^sub>m y \\<or> x \\<rightarrow>\\<^sub>w y\"\n\n\nlemma \"admissible(attacks) Lab\" nitpick[satisfy] oops\n(* gives us:  Lab =\n      (\\<lambda>x. _)\n      ((m\\<^sub>1, w\\<^sub>1) := In, (m\\<^sub>1, w\\<^sub>2) := Undec, (m\\<^sub>1, w\\<^sub>3) := Undec,\n       (m\\<^sub>2, w\\<^sub>1) := Out, (m\\<^sub>2, w\\<^sub>2) := Undec, (m\\<^sub>2, w\\<^sub>3) := In,\n       (m\\<^sub>3, w\\<^sub>1) := Undec, (m\\<^sub>3, w\\<^sub>2) := In, (m\\<^sub>3, w\\<^sub>3) := Undec *)\nlemma \"preferred(attacks) Lab\" (*nitpick[satisfy,timeout=60]*) oops\nlemma \"complete(attacks) Lab\" nitpick[satisfy] oops\nlemma \"findFor2 attacks stable Labs\" oops \n(* doesnt work, scaling is a problem*)\n\nend\n\n\nend\n\n", "meta": {"author": "aureleeNet", "repo": "formalizations", "sha": "43bbc805abb03098cd1e581f1bfe4af83286fe2a", "save_path": "github-repos/isabelle/aureleeNet-formalizations", "path": "github-repos/isabelle/aureleeNet-formalizations/formalizations-43bbc805abb03098cd1e581f1bfe4af83286fe2a/AF-old/examples.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8633916064586998, "lm_q2_score": 0.8670357512127873, "lm_q1q2_score": 0.748591390096734}}
{"text": "theory P21 imports Main begin\n\ndatatype tree = Tp | Nd tree tree\n\nfun tips :: \"tree \\<Rightarrow> nat\" where \n\"tips Tp = 1\" |\n\"tips (Nd l r) = tips l + tips r\"\n\nfun height :: \"tree \\<Rightarrow> nat\" where\n\"height Tp = 0\" |\n\"height (Nd l r) = 1 + max (height l) (height r)\"\n\nprimrec cbt :: \"nat \\<Rightarrow> tree\" where\n\"cbt 0 = Tp\" |\n\"cbt (Suc n) = Nd (cbt n) (cbt n)\"\n\nfun iscbt :: \"(tree \\<Rightarrow> 'a) \\<Rightarrow> tree \\<Rightarrow> bool\" where\n\"iscbt f Tp = True\" |\n\"iscbt f (Nd l r) = (f l = f r \\<and> iscbt f l \\<and> iscbt f r)\"\n\n\n\ntheorem \"iscbt height t = iscbt tips t\"\n  apply (induct t)\n   apply auto\n  done\n\nlemma [simp]: \"tips t = size t + 1\"\n  apply (induct t)\n  apply auto\n  done\n\ntheorem \"(iscbt tips t = iscbt size t)\"\n  apply (induct t)\n   apply auto\n  done\n\ntheorem \"iscbt height (cbt n)\"\n  apply (induct n)\n   apply auto\n  done\n\ntheorem \"iscbt height t \\<Longrightarrow> t = cbt (height t)\"\n  apply (induct t)\n   apply auto\n  done\n\ntheorem \"iscbt (\\<lambda>t. False) \\<noteq> (iscbt size)\"\n  apply (rule notI)\n  apply (metis add_cancel_right_left iscbt.simps(1) iscbt.simps(2) nat.distinct(1) \n        tree.size(3) tree.size(4))\n  done\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/P21.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037262250327, "lm_q2_score": 0.8080672066194946, "lm_q1q2_score": 0.7485156645318912}}
{"text": "theory Simp_Demo\nimports Main\nbegin\n\nsection{* How to simplify *}\n\ntext{* No assumption: *}\nlemma \"ys @ [] = []\"\napply(simp)\noops (* abandon proof *)\n\ntext{* Simplification in assumption: *}\nlemma \"\\<lbrakk> xs @ zs = ys @ xs; [] @ xs = [] @ [] \\<rbrakk> \\<Longrightarrow> ys = zs\"\napply(simp)\ndone\n\ntext{* Using additional rules: *}\nlemma \"(a+b)*(a-b) = a*a - b*(b::int)\"\napply(simp add: algebra_simps)\ndone\n\ntext{* Giving a lemma the simp-attribute: *}\ndeclare ring_distribs [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{* Automatic: *}\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{* By hand (for case): *}\nlemma \"1 \\<le> (case ns of [] \\<Rightarrow> 1 | n#_ \\<Rightarrow> Suc n)\"\napply(simp split: list.split)\ndone\n\nsubsection {* Arithmetic *}\n\ntext{* A bit of linear arithmetic (no multiplication) is automatic: *}\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{* Method ``auto'' can be modified almost like ``simp'': instead of\n``add'' use ``simp add'': *}\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/Simp_Demo.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.870597271765821, "lm_q2_score": 0.8596637559030338, "lm_q1q2_score": 0.74842092052514}}
{"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\nimports Main\nbegin\n\ntext \\<open>The Mutilated Checker Board Problem, formalized inductively.\n  See @{cite \"paulson-mutilated-board\"} for the original tactic script version.\\<close>\n\nsubsection \\<open>Tilings\\<close>\n\ninductive_set tiling :: \"'a set set \\<Rightarrow> 'a set set\"\n  for A :: \"'a set set\"\nwhere\n  empty: \"{} \\<in> tiling A\"\n| Un: \"a \\<in> A \\<Longrightarrow> t \\<in> tiling A \\<Longrightarrow> a \\<subseteq> - t \\<Longrightarrow> a \\<union> t \\<in> tiling A\"\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\"\nwhere\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:\n    \"\\<And>b. b < 2 \\<Longrightarrow> card (?e (a \\<union> t) b) = Suc (card (?e t b))\"\n  proof -\n    fix b :: nat\n    assume \"b < 2\"\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 b\" .\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\n    \"mutilated_board m n =\n      below (2 * (m + 1)) \\<times> below (2 * (n + 1))\n        - {(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": "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/Mutilated_Checkerboard.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8723473713594992, "lm_q2_score": 0.8577681068080748, "lm_q1q2_score": 0.7482717532100382}}
{"text": "subsection \"Properties about values\"\n\ntheory ValueProps\n  imports Values\nbegin\n\ninductive_cases fun_le_inv[elim]: \"t1 \\<lesssim> t2\" and\n  vfun_le_inv[elim!]: \"VFun t1 \\<sqsubseteq> VFun t2\" and\n  le_fun_nat_inv[elim!]: \"VFun t2 \\<sqsubseteq> VNat x1\" and\n  le_fun_cons_inv[elim!]: \"(v1, v2) # t1 \\<lesssim> t2\" and\n  le_any_nat_inv[elim!]: \"v \\<sqsubseteq> VNat n\" and\n  le_nat_any_inv[elim!]: \"VNat n \\<sqsubseteq> v\" and\n  le_fun_any_inv[elim!]: \"VFun t \\<sqsubseteq> v\" and\n  le_any_fun_inv[elim!]: \"v \\<sqsubseteq> VFun t\"\n\nlemma fun_le_cons: \"(a # t1) \\<lesssim> t2 \\<Longrightarrow> t1 \\<lesssim> t2\" \n  by (case_tac a) auto\n\nfunction val_size :: \"val \\<Rightarrow> nat\" and fun_size :: \"func \\<Rightarrow> nat\" where\n  \"val_size (VNat n) = 0\" |\n  \"val_size (VFun t) = 1 + fun_size t\" |\n  \"fun_size [] = 0\" |\n  \"fun_size ((v1,v2)#t) = 1 + val_size v1 + val_size v2 + fun_size t\" \n  by pat_completeness auto\ntermination val_size by size_change\n\nlemma val_size_mem: \"(a, b) \\<in> set t \\<Longrightarrow> val_size a + val_size b < fun_size t\"\n  by (induction t) auto\nlemma val_size_mem_l: \"(a, b) \\<in> set t \\<Longrightarrow> val_size a < fun_size t\"\n  by (induction t) auto\nlemma val_size_mem_r: \"(a, b) \\<in> set t \\<Longrightarrow> val_size b < fun_size t\"\n  by (induction t) auto\n        \nlemma val_fun_le_refl: \"\\<forall> v t. n = val_size v + fun_size t \\<longrightarrow> v \\<sqsubseteq> v \\<and> t \\<lesssim> t\"\nproof (induction n rule: nat_less_induct)\n  case (1 n)\n  show ?case apply clarify apply (rule conjI)\n  proof -\n    fix v::val and t::func assume n: \"n = val_size v + fun_size t\"     \n    show \"v \\<sqsubseteq> v\"\n    proof (cases v)\n      case (VNat x1)\n      then show ?thesis by auto\n    next\n      case (VFun t')\n      let ?m = \"val_size (VNat 0) + fun_size t'\"\n      from 1 n VFun have \"t' \\<lesssim> t'\" \n        apply (erule_tac x=\"?m\" in allE) apply (erule impE)\n         apply force apply (erule_tac x=\"VNat 0\" in allE) apply (erule_tac x=\"t'\" in allE)\n        apply simp done\n      from this VFun show ?thesis by force\n    qed \n  next\n    fix v::val and t::func assume n: \"n = val_size v + fun_size t\"\n    show \"t \\<lesssim> t\"\n      apply (rule fun_le) apply clarify\n    proof -\n      fix v1 v2 assume v12: \"(v1,v2) \\<in> set t\"\n      from 1 v12 have v11: \"v1 \\<sqsubseteq> v1\"\n        apply (erule_tac x=\"val_size v1 + fun_size []\" in allE)\n        apply (erule impE) using n apply simp apply (frule val_size_mem) apply force\n        apply (erule_tac x=v1 in allE) apply (erule_tac x=\"[]\" in allE) apply force done\n      from 1 v12 have v22: \"v2 \\<sqsubseteq> v2\" \n        apply (erule_tac x=\"val_size v2 + fun_size []\" in allE)\n        apply (erule impE) using n apply simp apply (frule val_size_mem) apply force\n        apply (erule_tac x=v2 in allE) apply (erule_tac x=\"[]\" in allE) apply force done\n      from v12 v11 v22\n      show \"\\<exists> v3 v4. (v3,v4) \\<in> set t \\<and> v1 \\<sqsubseteq> v3 \\<and> v3 \\<sqsubseteq> v1 \\<and> v2 \\<sqsubseteq> v4 \\<and> v4 \\<sqsubseteq> v2\" by blast \n      qed\n  qed\nqed\n\nproposition val_le_refl[simp]: fixes v::val shows \"v \\<sqsubseteq> v\" using val_fun_le_refl by auto\n    \nlemma fun_le_refl[simp]: fixes t::func shows \"t \\<lesssim> t\" using val_fun_le_refl by auto\n    \ndefinition val_eq :: \"val \\<Rightarrow> val \\<Rightarrow> bool\" (infix \"\\<sim>\" 52) where\n  \"val_eq v1 v2 \\<equiv> (v1 \\<sqsubseteq> v2 \\<and> v2 \\<sqsubseteq> v1)\"\n  \ndefinition fun_eq :: \"func \\<Rightarrow> func \\<Rightarrow> bool\" (infix \"\\<sim>\" 52) where\n  \"fun_eq t1 t2 \\<equiv> (t1 \\<lesssim> t2 \\<and> t2 \\<lesssim> t1)\" \n\nlemma vfun_eq[intro!]: \"t \\<sim> t' \\<Longrightarrow> VFun t \\<sim> VFun t'\"\n  apply (simp add: val_eq_def fun_eq_def) \n  apply (rule conjI) apply (erule conjE) apply (rule vfun_le) apply assumption\n  apply (erule conjE) apply (rule vfun_le) apply assumption\n  done\n \nlemma val_eq_refl[simp]: fixes v::val shows \"v \\<sim> v\"\n  by (simp add: val_eq_def) \n\nlemma val_eq_symm: fixes v1::val and v2::val shows \"v1 \\<sim> v2 \\<Longrightarrow> v2 \\<sim> v1\"\n  unfolding val_eq_def by blast \n    \nlemma val_le_fun_le_trans: \n   \"\\<forall> v2 t2. n = val_size v2 + fun_size t2 \\<longrightarrow> \n    (\\<forall> v1 v3. v1 \\<sqsubseteq> v2 \\<longrightarrow> v2 \\<sqsubseteq> v3 \\<longrightarrow> v1 \\<sqsubseteq> v3) \n    \\<and> (\\<forall> t1 t3. t1 \\<lesssim> t2 \\<longrightarrow> t2 \\<lesssim> t3 \\<longrightarrow> t1 \\<lesssim> t3)\"\nproof (induction n rule: nat_less_induct)\n  case (1 n)\n  show ?case apply clarify\n  proof\n    fix v2 t2 assume n: \"n = val_size v2 + fun_size t2\"\n    show \"\\<forall>v1 v3. v1 \\<sqsubseteq> v2 \\<longrightarrow> v2 \\<sqsubseteq> v3 \\<longrightarrow> v1 \\<sqsubseteq> v3\" apply clarify\n    proof -\n      fix v1 v3 assume v12: \"v1 \\<sqsubseteq> v2\" and v23: \"v2 \\<sqsubseteq> v3\"\n      show \"v1 \\<sqsubseteq> v3\"\n      proof (cases v2)\n        case (VNat n)\n        from VNat v12 have v1: \"v1 = VNat n\" by auto \n        from VNat v23 have v3: \"v3 = VNat n\" by auto \n        from v1 v3 show ?thesis by auto \n      next\n        case (VFun t2')\n        from v12 VFun obtain t1 where t12: \"t1 \\<lesssim> t2'\" and v1: \"v1 = VFun t1\" by auto\n        from v23 VFun obtain t3 where t23: \"t2' \\<lesssim> t3\" and v3: \"v3 = VFun t3\" by auto \n        let ?m = \"val_size (VNat 0) + fun_size t2'\"\n        from 1 n VFun have IH: \"\\<forall>t1 t3. t1 \\<lesssim> t2' \\<longrightarrow> t2' \\<lesssim> t3 \\<longrightarrow> t1 \\<lesssim> t3\"\n          apply simp apply (erule_tac x=\"?m\" in allE) apply (erule impE) apply force\n          apply (erule_tac x=\"VNat 0\" in allE)apply (erule_tac x=\"t2'\" in allE) \n          apply auto done \n        from t12 t23 IH have \"t1 \\<lesssim> t3\" by auto \n        from this v1 v3 show ?thesis apply auto done\n      qed\n    qed\n  next\n    fix v5 t2 assume n: \"n = val_size v5 + fun_size t2\"\n    show \"\\<forall>t1 t3. t1 \\<lesssim> t2 \\<longrightarrow> t2 \\<lesssim> t3 \\<longrightarrow> t1 \\<lesssim> t3\" apply clarify\n    proof -\n      fix t1 t3 v1 v2 assume t12: \"t1 \\<lesssim> t2\" and t23: \"t2 \\<lesssim> t3\" and v12: \"(v1,v2) \\<in> set t1\"\n      from v12 t12 obtain v1' v2' where v12p: \"(v1',v2') \\<in> set t2\" and \n          v1_v1p: \"v1 \\<sqsubseteq> v1'\" and v11p: \"v1' \\<sqsubseteq> v1\" and v22p: \"v2 \\<sqsubseteq> v2'\" and v2p_v2: \"v2' \\<sqsubseteq> v2\" by blast \n      from v12p t23 obtain v1'' v2'' where v12pp: \"(v1'',v2'') \\<in> set t3\" and\n         v1p_v1pp: \"v1' \\<sqsubseteq> v1''\" and v11pp: \"v1'' \\<sqsubseteq> v1'\" and \n         v22pp: \"v2' \\<sqsubseteq> v2''\" and v2pp_v2p: \"v2'' \\<sqsubseteq> v2'\" by blast\n          \n      from v12p have sv1p: \"val_size v1' < fun_size t2\" using val_size_mem_l by blast \n      from v12 1 v11p v11pp n sv1p have v1pp_v1: \"v1'' \\<sqsubseteq> v1\" \n        apply (erule_tac x=\"val_size v1' + fun_size []\" in allE)\n        apply (erule impE) apply force apply (erule_tac x=v1' in allE)\n        apply (erule_tac x=\"[]\" in allE) apply (erule impE) apply force\n        apply (erule conjE) apply blast done\n      \n      from v12p have sv2p: \"val_size v2' < fun_size t2\" using val_size_mem_r by blast \n      from v12 1 v22p v22pp n sv2p have v2_v2pp: \"v2 \\<sqsubseteq> v2''\" \n        apply (erule_tac x=\"val_size v2' + fun_size []\" in allE)\n        apply (erule impE) apply force apply (erule_tac x=v2' in allE)\n        apply (erule_tac x=\"[]\" in allE) apply (erule impE) apply force\n        apply (erule conjE) apply blast done\n\n      from v12 1 v1_v1p v1p_v1pp n sv1p have v1_v1pp: \"v1 \\<sqsubseteq> v1''\" \n        apply (erule_tac x=\"val_size v1' + fun_size []\" in allE)\n        apply (erule impE) apply force apply (erule_tac x=v1' in allE)\n        apply (erule_tac x=\"[]\" in allE) apply (erule impE) apply force\n        apply (erule conjE) apply blast done\n      \n      from v12 1 v2pp_v2p v2p_v2 n sv2p have v2pp_v2: \"v2'' \\<sqsubseteq> v2\" \n        apply (erule_tac x=\"val_size v2' + fun_size []\" in allE)\n        apply (erule impE) apply force apply (erule_tac x=v2' in allE)\n        apply (erule_tac x=\"[]\" in allE) apply (erule impE) apply force\n        apply (erule conjE) apply blast done\n        \n      from v12pp v1pp_v1 v2_v2pp v1_v1pp v2pp_v2\n      show \" \\<exists>v3 v4. (v3, v4) \\<in> set t3 \\<and> v1 \\<sqsubseteq> v3 \\<and> v3 \\<sqsubseteq> v1 \\<and> v2 \\<sqsubseteq> v4 \\<and> v4 \\<sqsubseteq> v2\" by blast\n    qed\n  qed\nqed\n\nproposition val_le_trans: fixes v2::val shows \"\\<lbrakk> v1 \\<sqsubseteq> v2; v2 \\<sqsubseteq> v3 \\<rbrakk> \\<Longrightarrow> v1 \\<sqsubseteq> v3\"\n  using val_le_fun_le_trans by blast\n\nlemma fun_le_trans: \"\\<lbrakk> t1 \\<lesssim> t2; t2 \\<lesssim> t3 \\<rbrakk> \\<Longrightarrow> t1 \\<lesssim> t3\"\n  using val_le_fun_le_trans by blast\n    \nlemma val_eq_trans: fixes v1::val and v2::val and v3::val \n  assumes v12: \"v1 \\<sim> v2\" and v23: \"v2 \\<sim> v3\" shows \"v1 \\<sim> v3\"\n  using v12 v23 apply (simp only: val_eq_def) using val_le_trans apply blast done\n    \nlemma fun_eq_refl[simp]: fixes t::func shows \"t \\<sim> t\"\n  by (simp add: fun_eq_def) \n\nlemma fun_eq_trans: fixes t1::func and t2::func and t3::func\n  assumes t12: \"t1 \\<sim> t2\" and t23: \"t2 \\<sim> t3\" shows \"t1 \\<sim> t3\"\n  using t12 t23 unfolding fun_eq_def apply clarify apply (rule conjI)\n   apply (rule fun_le_trans) apply assumption apply assumption\n  apply (rule fun_le_trans) apply assumption apply assumption\n  done\n    \nlemma append_fun_le:\n   \"\\<lbrakk> t1' \\<lesssim> t1; t2' \\<lesssim> t2 \\<rbrakk> \\<Longrightarrow> t1' @ t2' \\<lesssim> t1 @ t2\"\n  apply (rule fun_le) apply clarify apply simp apply (erule fun_le_inv)+ apply blast done\n\nlemma append_fun_equiv:\n   \"\\<lbrakk> t1' \\<sim> t1; t2' \\<sim> t2 \\<rbrakk> \\<Longrightarrow> t1' @ t2' \\<sim> t1 @ t2\"\n  apply (simp add: val_eq_def fun_eq_def) using append_fun_le apply blast done\n\nlemma append_leq_symm: \"t2 @ t1 \\<lesssim> t1 @ t2\"\n  apply (rule fun_le) apply force done\n    \nlemma append_eq_symm: \"t2 @ t1 \\<sim> t1 @ t2\"\n  unfolding fun_eq_def val_eq_def apply (rule conjI)\n  apply (rule append_leq_symm) apply (rule append_leq_symm) done\n\nlemma le_nat_any[simp]: \"VNat n \\<sqsubseteq> v \\<Longrightarrow> v = VNat n\"\n  by (cases v) auto \n\n\n\nlemma le_nat_nat[simp]: \"VNat n \\<sqsubseteq> VNat n' \\<Longrightarrow> n = n'\"\n  by auto \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/Decl_Sem_Fun_PL/ValueProps.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473614033684, "lm_q2_score": 0.8577680995361899, "lm_q1q2_score": 0.7482717383263772}}
{"text": "(*  Title:    HOL/Analysis/Harmonic_Numbers.thy\n    Author:   Manuel Eberl, TU M\u00fcnchen\n*)\n\nsection \\<open>Harmonic Numbers\\<close>\n\ntheory Harmonic_Numbers\nimports\n  Complex_Transcendental\n  Summation_Tests\nbegin\n\ntext \\<open>\n  The definition of the Harmonic Numbers and the Euler-Mascheroni constant.\n  Also provides a reasonably accurate approximation of \\<^term>\\<open>ln 2 :: real\\<close>\n  and the Euler-Mascheroni constant.\n\\<close>\n\nsubsection \\<open>The Harmonic numbers\\<close>\n\ndefinition\\<^marker>\\<open>tag important\\<close> 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 sum_nonneg) simp_all\n\nlemma harm_pos: \"n > 0 \\<Longrightarrow> harm n > (0 :: 'a :: {real_normed_field,linordered_field})\"\n  unfolding harm_def by (intro sum_pos) simp_all\n\nlemma harm_mono: \"m \\<le> n \\<Longrightarrow> harm m \\<le> (harm n :: 'a :: {real_normed_field,linordered_field})\"\nby(simp add: harm_def sum_mono2)\n\nlemma of_real_harm: \"of_real (harm n) = harm n\"\n  unfolding harm_def by simp\n\nlemma abs_harm [simp]: \"(abs (harm n) :: real) = harm n\"\n  using harm_nonneg[of n] by (rule abs_of_nonneg)\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 0 = 0\"\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_all add: harm_def)\n\ntheorem 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 sum.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\nlemma harm_pos_iff [simp]: \"harm n > (0 :: 'a :: {real_normed_field,linordered_field}) \\<longleftrightarrow> n > 0\"\n  by (rule iffI, cases n, simp add: harm_expand, simp, rule harm_pos)\n\nlemma ln_diff_le_inverse:\n  assumes \"x \\<ge> (1::real)\"\n  shows   \"ln (x + 1) - ln x < 1 / x\"\nproof -\n  from assms have \"\\<exists>z>x. z < x + 1 \\<and> ln (x + 1) - ln x = (x + 1 - x) * inverse z\"\n    by (intro MVT2) (auto intro!: derivative_eq_intros simp: field_simps)\n  then obtain z where z: \"z > x\" \"z < x + 1\" \"ln (x + 1) - ln x = inverse z\" by auto\n  have \"ln (x + 1) - ln x = inverse z\" by fact\n  also from z(1,2) assms have \"\\<dots> < 1 / x\" by (simp add: field_simps)\n  finally show ?thesis .\nqed\n\nlemma ln_le_harm: \"ln (real n + 1) \\<le> (harm n :: real)\"\nproof (induction n)\n  fix n assume IH: \"ln (real n + 1) \\<le> harm n\"\n  have \"ln (real (Suc n) + 1) = ln (real n + 1) + (ln (real n + 2) - ln (real n + 1))\" by simp\n  also have \"(ln (real n + 2) - ln (real n + 1)) \\<le> 1 / real (Suc n)\"\n    using ln_diff_le_inverse[of \"real n + 1\"] by (simp add: add_ac)\n  also note IH\n  also have \"harm n + 1 / real (Suc n) = harm (Suc n)\" by (simp add: harm_Suc field_simps)\n  finally show \"ln (real (Suc n) + 1) \\<le> harm (Suc n)\" by - simp\nqed (simp_all add: harm_def)\n\nlemma harm_at_top: \"filterlim (harm :: nat \\<Rightarrow> real) at_top sequentially\"\nproof (rule filterlim_at_top_mono)\n  show \"eventually (\\<lambda>n. harm n \\<ge> ln (real (Suc n))) at_top\"\n    using ln_le_harm by (intro always_eventually allI) (simp_all add: add_ac)\n  show \"filterlim (\\<lambda>n. ln (real (Suc n))) at_top sequentially\"\n    by (intro filterlim_compose[OF ln_at_top] filterlim_compose[OF filterlim_real_sequentially]\n              filterlim_Suc)\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\nlemma harm_ge_ln: \"harm n \\<ge> ln (real n + 1)\"\nproof -\n  have \"ln (n + 1) = (\\<Sum>j<n. ln (real (Suc j + 1)) - ln (real (j + 1)))\"\n    by (subst sum_lessThan_telescope) auto\n  also have \"\\<dots> \\<le> (\\<Sum>j<n. 1 / (Suc j))\"\n  proof (intro sum_mono, clarify)\n    fix j assume j: \"j < n\"\n    have \"\\<exists>\\<xi>. \\<xi> > real j + 1 \\<and> \\<xi> < real j + 2 \\<and>\n            ln (real j + 2) - ln (real j + 1) = (real j + 2 - (real j + 1)) * (1 / \\<xi>)\"\n      by (intro MVT2) (auto intro!: derivative_eq_intros)\n    then obtain \\<xi> :: real\n      where \\<xi>: \"\\<xi> \\<in> {real j + 1..real j + 2}\" \"ln (real j + 2) - ln (real j + 1) = 1 / \\<xi>\"\n      by auto\n    note \\<xi>(2)\n    also have \"1 / \\<xi> \\<le> 1 / (Suc j)\"\n      using \\<xi>(1) by (auto simp: field_simps)\n    finally show \"ln (real (Suc j + 1)) - ln (real (j + 1)) \\<le> 1 / (Suc j)\"\n      by (simp add: add_ac)\n  qed\n  also have \"\\<dots> = harm n\"\n    by (simp add: harm_altdef field_simps)\n  finally show ?thesis by (simp add: add_ac)\nqed\n\nlemma decseq_harm_diff_ln: \"decseq (\\<lambda>n. harm (Suc n) - ln (Suc n))\"\nproof (rule decseq_SucI)\n  fix m :: nat\n  define n where \"n = Suc m\"\n  have \"n > 0\" by (simp add: n_def)\n  have \"convex_on {0<..} (\\<lambda>x :: real. -ln x)\"\n    by (rule convex_on_realI[where f' = \"\\<lambda>x. -1/x\"])\n       (auto intro!: derivative_eq_intros simp: field_simps)\n  hence \"(-1 / (n + 1)) * (real n - real (n + 1)) \\<le> (- ln (real n)) - (-ln (real (n + 1)))\"\n    using \\<open>n > 0\\<close> by (intro convex_on_imp_above_tangent[where A = \"{0<..}\"])\n                     (auto intro!: derivative_eq_intros simp: interior_open)\n  thus \"harm (Suc n) - ln (Suc n) \\<le> harm n - ln n\"\n    by (auto simp: harm_Suc field_simps)\nqed\n\nlemma euler_mascheroni_sequence_nonneg:\n  assumes \"n > 0\"\n  shows   \"harm n - ln (real n) \\<ge> (0 :: real)\"\nproof -\n  have \"ln (real n) \\<le> ln (real n + 1)\"\n    using assms by simp\n  also have \"\\<dots> \\<le> harm n\"\n    by (rule harm_ge_ln)\n  finally show ?thesis by simp\nqed\n\nlemma euler_mascheroni_convergent: \"convergent (\\<lambda>n. harm n - ln n)\"\nproof -\n  have \"harm (Suc n) - ln (real (Suc n)) \\<ge> 0\" for n :: nat\n    using euler_mascheroni_sequence_nonneg[of \"Suc n\"] by simp\n  hence \"convergent (\\<lambda>n. harm (Suc n) - ln (Suc n))\"\n    by (intro Bseq_monoseq_convergent decseq_bounded[of _ 0] decseq_harm_diff_ln decseq_imp_monoseq)\n       auto\n  thus ?thesis\n    by (subst (asm) convergent_Suc_iff)\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  using decseqD[OF decseq_harm_diff_ln, of \"m - 1\" \"n - 1\"] by simp\n  \nlemma\\<^marker>\\<open>tag important\\<close> euler_mascheroni_LIMSEQ:\n  \"(\\<lambda>n. harm n - ln (of_nat n) :: real) \\<longlonglongrightarrow> 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))) \\<longlonglongrightarrow>\n      (euler_mascheroni :: 'a :: {real_normed_algebra_1, topological_space})\"\nproof -\n  have \"(\\<lambda>n. of_real (harm n - ln (of_nat n))) \\<longlonglongrightarrow> (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_real:\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 euler_mascheroni_sum:\n  \"(\\<lambda>n. inverse (of_nat (n+1)) + of_real (ln (of_nat (n+1))) - of_real (ln (of_nat (n+2))))\n       sums (euler_mascheroni :: 'a :: {banach, real_normed_field})\"\nproof -\n  have \"(\\<lambda>n. of_real (inverse (of_nat (n+1)) + ln (of_nat (n+1)) - ln (of_nat (n+2))))\n       sums (of_real euler_mascheroni :: 'a :: {banach, real_normed_field})\"\n    by (subst sums_of_real_iff) (rule euler_mascheroni_sum_real)\n  thus ?thesis by simp\nqed\n\ntheorem 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: sum.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 sum.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 sum.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 sum.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 sum.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                     \\<longlonglongrightarrow> 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: strict_mono_def)\n  hence \"(\\<lambda>n. ?em (2*n) - ?em n + ln (2::real)) \\<longlonglongrightarrow> ln 2\" by simp\n  ultimately have \"(\\<lambda>n. (\\<Sum>k<2*n. (-1)^k / real_of_nat (Suc k))) \\<longlonglongrightarrow> ln 2\"\n    by (blast intro: 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)) \\<longlonglongrightarrow> (\\<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 \"(*) (2::nat)\"]]\n    have \"(\\<lambda>n. \\<Sum>k<2*n. (-1)^k / real_of_nat (Suc k)) \\<longlonglongrightarrow> (\\<Sum>k. (-1)^k / real_of_nat (Suc k))\"\n    by (simp add: strict_mono_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))) \\<longlonglongrightarrow> 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\n\nsubsection\\<^marker>\\<open>tag unimportant\\<close> \\<open>Bounds on the Euler-Mascheroni constant\\<close>\n(* TODO: perhaps move this section away to remove unnecessary dependency on integration *)\n\n(* TODO: Move? *)\nlemma ln_inverse_approx_le:\n  assumes \"(x::real) > 0\" \"a > 0\"\n  shows   \"ln (x + a) - ln x \\<le> a * (inverse x + inverse (x + a))/2\" (is \"_ \\<le> ?A\")\nproof -\n  define f' where \"f' = (inverse (x + a) - inverse x)/a\"\n  let ?f = \"\\<lambda>t. (t - x) * f' + inverse x\"\n  let ?F = \"\\<lambda>t. (t - x)^2 * f' / 2 + t * inverse x\"\n\n  have deriv: \"\\<exists>D. ((\\<lambda>x. ?F x - ln x) has_field_derivative D) (at \\<xi>) \\<and> D \\<ge> 0\"\n    if \"\\<xi> \\<ge> x\" \"\\<xi> \\<le> x + a\" for \\<xi>\n  proof -\n    from that assms have t: \"0 \\<le> (\\<xi> - x) / a\" \"(\\<xi> - x) / a \\<le> 1\" by simp_all\n    have \"inverse \\<xi> = inverse ((1 - (\\<xi> - x) / a) *\\<^sub>R x + ((\\<xi> - x) / a) *\\<^sub>R (x + a))\" (is \"_ = ?A\")\n      using assms by (simp add: field_simps)\n    also from assms have \"convex_on {x..x+a} inverse\" by (intro convex_on_inverse) auto\n    from convex_onD_Icc[OF this _ t] assms\n      have \"?A \\<le> (1 - (\\<xi> - x) / a) * inverse x + (\\<xi> - x) / a * inverse (x + a)\" by simp\n    also have \"\\<dots> = (\\<xi> - x) * f' + inverse x\" using assms\n      by (simp add: f'_def divide_simps) (simp add: field_simps)\n    finally have \"?f \\<xi> - 1 / \\<xi> \\<ge> 0\" by (simp add: field_simps)\n    moreover have \"((\\<lambda>x. ?F x - ln x) has_field_derivative ?f \\<xi> - 1 / \\<xi>) (at \\<xi>)\"\n      using that assms by (auto intro!: derivative_eq_intros simp: field_simps)\n    ultimately show ?thesis by blast\n  qed\n  have \"?F x - ln x \\<le> ?F (x + a) - ln (x + a)\"\n    by (rule DERIV_nonneg_imp_nondecreasing[of x \"x + a\", OF _ deriv]) (use assms in auto)\n  thus ?thesis\n    using assms by (simp add: f'_def divide_simps) (simp add: algebra_simps power2_eq_square)?\nqed\n\nlemma ln_inverse_approx_ge:\n  assumes \"(x::real) > 0\" \"x < y\"\n  shows   \"ln y - ln x \\<ge> 2 * (y - x) / (x + y)\" (is \"_ \\<ge> ?A\")\nproof -\n  define m where \"m = (x+y)/2\"\n  define f' where \"f' = -inverse (m^2)\"\n  from assms have m: \"m > 0\" by (simp add: m_def)\n  let ?F = \"\\<lambda>t. (t - m)^2 * f' / 2 + t / m\"\n  let ?f = \"\\<lambda>t. (t - m) * f' + inverse m\"\n  \n  have deriv: \"\\<exists>D. ((\\<lambda>x. ln x - ?F x) has_field_derivative D) (at \\<xi>) \\<and> D \\<ge> 0\"\n    if \"\\<xi> \\<ge> x\" \"\\<xi> \\<le> y\" for \\<xi>\n  proof -\n    from that assms have \"inverse \\<xi> - inverse m \\<ge> f' * (\\<xi> - m)\"\n      by (intro convex_on_imp_above_tangent[of \"{0<..}\"] convex_on_inverse)\n         (auto simp: m_def interior_open f'_def power2_eq_square intro!: derivative_eq_intros)\n    hence \"1 / \\<xi> - ?f \\<xi> \\<ge> 0\" by (simp add: field_simps f'_def)\n    moreover have \"((\\<lambda>x. ln x - ?F x) has_field_derivative 1 / \\<xi> - ?f \\<xi>) (at \\<xi>)\"\n      using that assms m by (auto intro!: derivative_eq_intros simp: field_simps)\n    ultimately show ?thesis by blast\n  qed\n  have \"ln x - ?F x \\<le> ln y - ?F y\"\n    by (rule DERIV_nonneg_imp_nondecreasing[of x y, OF _ deriv]) (use assms in auto)\n  hence \"ln y - ln x \\<ge> ?F y - ?F x\"\n    by (simp add: algebra_simps)\n  also have \"?F y - ?F x = ?A\"\n    using assms by (simp add: f'_def m_def divide_simps) (simp add: algebra_simps power2_eq_square)\n  finally show ?thesis .\nqed\n\nlemma euler_mascheroni_lower:\n          \"euler_mascheroni \\<ge> harm (Suc n) - ln (real_of_nat (n + 2)) + 1/real_of_nat (2 * (n + 2))\"\n    and euler_mascheroni_upper:\n          \"euler_mascheroni \\<le> harm (Suc n) - ln (real_of_nat (n + 2)) + 1/real_of_nat (2 * (n + 1))\"\nproof -\n  define D :: \"_ \\<Rightarrow> real\"\n    where \"D n = inverse (of_nat (n+1)) + ln (of_nat (n+1)) - ln (of_nat (n+2))\" for n\n  let ?g = \"\\<lambda>n. ln (of_nat (n+2)) - ln (of_nat (n+1)) - inverse (of_nat (n+1)) :: real\"\n  define inv where [abs_def]: \"inv n = inverse (real_of_nat n)\" for n\n  fix n :: nat\n  note summable = sums_summable[OF euler_mascheroni_sum_real, folded D_def]\n  have sums: \"(\\<lambda>k. (inv (Suc (k + (n+1))) - inv (Suc (Suc k + (n+1))))/2) sums ((inv (Suc (0 + (n+1))) - 0)/2)\"\n    unfolding inv_def\n    by (intro sums_divide telescope_sums' LIMSEQ_ignore_initial_segment LIMSEQ_inverse_real_of_nat)\n  have sums': \"(\\<lambda>k. (inv (Suc (k + n)) - inv (Suc (Suc k + n)))/2) sums ((inv (Suc (0 + n)) - 0)/2)\"\n    unfolding inv_def\n    by (intro sums_divide telescope_sums' LIMSEQ_ignore_initial_segment LIMSEQ_inverse_real_of_nat)\n  from euler_mascheroni_sum_real have \"euler_mascheroni = (\\<Sum>k. D k)\"\n    by (simp add: sums_iff D_def)\n  also have \"\\<dots> = (\\<Sum>k. D (k + Suc n)) + (\\<Sum>k\\<le>n. D k)\"\n    by (subst suminf_split_initial_segment[OF summable, of \"Suc n\"],\n        subst lessThan_Suc_atMost) simp\n  finally have sum: \"(\\<Sum>k\\<le>n. D k) - euler_mascheroni = -(\\<Sum>k. D (k + Suc n))\" by simp\n\n  note sum\n  also have \"\\<dots> \\<le> -(\\<Sum>k. (inv (k + Suc n + 1) - inv (k + Suc n + 2)) / 2)\"\n  proof (intro le_imp_neg_le suminf_le allI summable_ignore_initial_segment[OF summable])\n    fix k' :: nat\n    define k where \"k = k' + Suc n\"\n    hence k: \"k > 0\" by (simp add: k_def)\n    have \"real_of_nat (k+1) > 0\" by (simp add: k_def)\n    with ln_inverse_approx_le[OF this zero_less_one]\n      have \"ln (of_nat k + 2) - ln (of_nat k + 1) \\<le> (inv (k+1) + inv (k+2))/2\"\n      by (simp add: inv_def add_ac)\n    hence \"(inv (k+1) - inv (k+2))/2 \\<le> inv (k+1) + ln (of_nat (k+1)) - ln (of_nat (k+2))\"\n      by (simp add: field_simps)\n    also have \"\\<dots> = D k\" unfolding D_def inv_def ..\n    finally show \"D (k' + Suc n) \\<ge> (inv (k' + Suc n + 1) - inv (k' + Suc n + 2)) / 2\"\n      by (simp add: k_def)\n    from sums_summable[OF sums]\n      show \"summable (\\<lambda>k. (inv (k + Suc n + 1) - inv (k + Suc n + 2))/2)\" by simp\n  qed\n  also from sums have \"\\<dots> = -inv (n+2) / 2\" by (simp add: sums_iff)\n  finally have \"euler_mascheroni \\<ge> (\\<Sum>k\\<le>n. D k) + 1 / (of_nat (2 * (n+2)))\"\n    by (simp add: inv_def field_simps)\n  also have \"(\\<Sum>k\\<le>n. D k) = harm (Suc n) - (\\<Sum>k\\<le>n. ln (real_of_nat (Suc k+1)) - ln (of_nat (k+1)))\"\n    unfolding harm_altdef D_def by (subst lessThan_Suc_atMost) (simp add:  sum.distrib sum_subtractf)\n  also have \"(\\<Sum>k\\<le>n. ln (real_of_nat (Suc k+1)) - ln (of_nat (k+1))) = ln (of_nat (n+2))\"\n    by (subst atLeast0AtMost [symmetric], subst sum_Suc_diff) simp_all\n  finally show \"euler_mascheroni \\<ge> harm (Suc n) - ln (real_of_nat (n + 2)) + 1/real_of_nat (2 * (n + 2))\"\n    by simp\n\n  note sum\n  also have \"-(\\<Sum>k. D (k + Suc n)) \\<ge> -(\\<Sum>k. (inv (Suc (k + n)) - inv (Suc (Suc k + n)))/2)\"\n  proof (intro le_imp_neg_le suminf_le allI summable_ignore_initial_segment[OF summable])\n    fix k' :: nat\n    define k where \"k = k' + Suc n\"\n    hence k: \"k > 0\" by (simp add: k_def)\n    have \"real_of_nat (k+1) > 0\" by (simp add: k_def)\n    from ln_inverse_approx_ge[of \"of_nat k + 1\" \"of_nat k + 2\"]\n      have \"2 / (2 * real_of_nat k + 3) \\<le> ln (of_nat (k+2)) - ln (real_of_nat (k+1))\"\n      by (simp add: add_ac)\n    hence \"D k \\<le> 1 / real_of_nat (k+1) - 2 / (2 * real_of_nat k + 3)\"\n      by (simp add: D_def inverse_eq_divide inv_def)\n    also have \"\\<dots> = inv ((k+1)*(2*k+3))\" unfolding inv_def by (simp add: field_simps)\n    also have \"\\<dots> \\<le> inv (2*k*(k+1))\" unfolding inv_def using k\n      by (intro le_imp_inverse_le)\n         (simp add: algebra_simps, simp del: of_nat_add)\n    also have \"\\<dots> = (inv k - inv (k+1))/2\" unfolding inv_def using k\n      by (simp add: divide_simps del: of_nat_mult) (simp add: algebra_simps)\n    finally show \"D k \\<le> (inv (Suc (k' + n)) - inv (Suc (Suc k' + n)))/2\" unfolding k_def by simp\n  next\n    from sums_summable[OF sums']\n      show \"summable (\\<lambda>k. (inv (Suc (k + n)) - inv (Suc (Suc k + n)))/2)\" by simp\n  qed\n  also from sums' have \"(\\<Sum>k. (inv (Suc (k + n)) - inv (Suc (Suc k + n)))/2) = inv (n+1)/2\"\n    by (simp add: sums_iff)\n  finally have \"euler_mascheroni \\<le> (\\<Sum>k\\<le>n. D k) + 1 / of_nat (2 * (n+1))\"\n    by (simp add: inv_def field_simps)\n  also have \"(\\<Sum>k\\<le>n. D k) = harm (Suc n) - (\\<Sum>k\\<le>n. ln (real_of_nat (Suc k+1)) - ln (of_nat (k+1)))\"\n    unfolding harm_altdef D_def by (subst lessThan_Suc_atMost) (simp add:  sum.distrib sum_subtractf)\n  also have \"(\\<Sum>k\\<le>n. ln (real_of_nat (Suc k+1)) - ln (of_nat (k+1))) = ln (of_nat (n+2))\"\n    by (subst atLeast0AtMost [symmetric], subst sum_Suc_diff) simp_all\n  finally show \"euler_mascheroni \\<le> harm (Suc n) - ln (real_of_nat (n + 2)) + 1/real_of_nat (2 * (n + 1))\"\n    by simp\nqed\n\nlemma euler_mascheroni_pos: \"euler_mascheroni > (0::real)\"\n  using euler_mascheroni_lower[of 0] ln_2_less_1 by (simp add: harm_def)\n\ncontext\nbegin\n\nprivate lemma ln_approx_aux:\n  fixes n :: nat and x :: real\n  defines \"y \\<equiv> (x-1)/(x+1)\"\n  assumes x: \"x > 0\" \"x \\<noteq> 1\"\n  shows \"inverse (2*y^(2*n+1)) * (ln x - (\\<Sum>k<n. 2*y^(2*k+1) / of_nat (2*k+1))) \\<in>\n            {0..(1 / (1 - y^2) / of_nat (2*n+1))}\"\nproof -\n  from x have norm_y: \"norm y < 1\" unfolding y_def by simp\n  from power_strict_mono[OF this, of 2] have norm_y': \"norm y^2 < 1\" by simp\n\n  let ?f = \"\\<lambda>k. 2 * y ^ (2*k+1) / of_nat (2*k+1)\"\n  note sums = ln_series_quadratic[OF x(1)]\n  define c where \"c = inverse (2*y^(2*n+1))\"\n  let ?d = \"c * (ln x - (\\<Sum>k<n. ?f k))\"\n  have \"\\<And>k. y\\<^sup>2^k / of_nat (2*(k+n)+1) \\<le> y\\<^sup>2 ^ k / of_nat (2*n+1)\"\n    by (intro divide_left_mono mult_right_mono mult_pos_pos zero_le_power[of \"y^2\"]) simp_all\n  moreover {\n    have \"(\\<lambda>k. ?f (k + n)) sums (ln x - (\\<Sum>k<n. ?f k))\"\n      using sums_split_initial_segment[OF sums] by (simp add: y_def)\n    hence \"(\\<lambda>k. c * ?f (k + n)) sums ?d\" by (rule sums_mult)\n    also have \"(\\<lambda>k. c * (2*y^(2*(k+n)+1) / of_nat (2*(k+n)+1))) =\n                   (\\<lambda>k. (c * (2*y^(2*n+1))) * ((y^2)^k / of_nat (2*(k+n)+1)))\"\n      by (simp only: ring_distribs power_add power_mult) (simp add: mult_ac)\n    also from x have \"c * (2*y^(2*n+1)) = 1\" by (simp add: c_def y_def)\n    finally have \"(\\<lambda>k. (y^2)^k / of_nat (2*(k+n)+1)) sums ?d\" by simp\n  } note sums' = this\n  moreover from norm_y' have \"(\\<lambda>k. (y^2)^k / of_nat (2*n+1)) sums (1 / (1 - y^2) / of_nat (2*n+1))\"\n    by (intro sums_divide geometric_sums) (simp_all add: norm_power)\n  ultimately have \"?d \\<le> (1 / (1 - y^2) / of_nat (2*n+1))\" by (rule sums_le)\n  moreover have \"c * (ln x - (\\<Sum>k<n. 2 * y ^ (2 * k + 1) / real_of_nat (2 * k + 1))) \\<ge> 0\"\n    by (intro sums_le[OF _ sums_zero sums']) simp_all\n  ultimately show ?thesis unfolding c_def by simp\nqed\n\nlemma\n  fixes n :: nat and x :: real\n  defines \"y \\<equiv> (x-1)/(x+1)\"\n  defines \"approx \\<equiv> (\\<Sum>k<n. 2*y^(2*k+1) / of_nat (2*k+1))\"\n  defines \"d \\<equiv> y^(2*n+1) / (1 - y^2) / of_nat (2*n+1)\"\n  assumes x: \"x > 1\"\n  shows   ln_approx_bounds: \"ln x \\<in> {approx..approx + 2*d}\"\n  and     ln_approx_abs:    \"abs (ln x - (approx + d)) \\<le> d\"\nproof -\n  define c where \"c = 2*y^(2*n+1)\"\n  from x have c_pos: \"c > 0\" unfolding c_def y_def\n    by (intro mult_pos_pos zero_less_power) simp_all\n  have A: \"inverse c * (ln x - (\\<Sum>k<n. 2*y^(2*k+1) / of_nat (2*k+1))) \\<in>\n              {0.. (1 / (1 - y^2) / of_nat (2*n+1))}\" using assms unfolding y_def c_def\n    by (intro ln_approx_aux) simp_all\n  hence \"inverse c * (ln x - (\\<Sum>k<n. 2*y^(2*k+1)/of_nat (2*k+1))) \\<le> (1 / (1-y^2) / of_nat (2*n+1))\"\n    by simp\n  hence \"(ln x - (\\<Sum>k<n. 2*y^(2*k+1) / of_nat (2*k+1))) / c \\<le> (1 / (1 - y^2) / of_nat (2*n+1))\"\n    by (auto simp add: field_split_simps)\n  with c_pos have \"ln x \\<le> c / (1 - y^2) / of_nat (2*n+1) + approx\"\n    by (subst (asm) pos_divide_le_eq) (simp_all add: mult_ac approx_def)\n  moreover {\n    from A c_pos have \"0 \\<le> c * (inverse c * (ln x - (\\<Sum>k<n. 2*y^(2*k+1) / of_nat (2*k+1))))\"\n      by (intro mult_nonneg_nonneg[of c]) simp_all\n    also have \"\\<dots> = (c * inverse c) * (ln x - (\\<Sum>k<n. 2*y^(2*k+1) / of_nat (2*k+1)))\"\n      by (simp add: mult_ac)\n    also from c_pos have \"c * inverse c = 1\" by simp\n    finally have \"ln x \\<ge> approx\" by (simp add: approx_def)\n  }\n  ultimately show \"ln x \\<in> {approx..approx + 2*d}\" by (simp add: c_def d_def)\n  thus \"abs (ln x - (approx + d)) \\<le> d\" by auto\nqed\n\nend\n\nlemma euler_mascheroni_bounds:\n  fixes n :: nat assumes \"n \\<ge> 1\" defines \"t \\<equiv> harm n - ln (of_nat (Suc n)) :: real\"\n  shows \"euler_mascheroni \\<in> {t + inverse (of_nat (2*(n+1)))..t + inverse (of_nat (2*n))}\"\n  using assms euler_mascheroni_upper[of \"n-1\"] euler_mascheroni_lower[of \"n-1\"]\n  unfolding t_def by (cases n) (simp_all add: harm_Suc t_def inverse_eq_divide)\n\nlemma euler_mascheroni_bounds':\n  fixes n :: nat assumes \"n \\<ge> 1\" \"ln (real_of_nat (Suc n)) \\<in> {l<..<u}\"\n  shows \"euler_mascheroni \\<in>\n           {harm n - u + inverse (of_nat (2*(n+1)))<..<harm n - l + inverse (of_nat (2*n))}\"\n  using euler_mascheroni_bounds[OF assms(1)] assms(2) by auto\n\n\ntext \\<open>\n  Approximation of \\<^term>\\<open>ln 2\\<close>. The lower bound is accurate to about 0.03; the upper\n  bound is accurate to about 0.0015.\n\\<close>\nlemma ln2_ge_two_thirds: \"2/3 \\<le> ln (2::real)\"\n  and ln2_le_25_over_36: \"ln (2::real) \\<le> 25/36\"\n  using ln_approx_bounds[of 2 1, simplified, simplified eval_nat_numeral, simplified] by simp_all\n\n\ntext \\<open>\n  Approximation of the Euler-Mascheroni constant. The lower bound is accurate to about 0.0015;\n  the upper bound is accurate to about 0.015.\n\\<close>\nlemma euler_mascheroni_gt_19_over_33: \"(euler_mascheroni :: real) > 19/33\" (is ?th1)\n  and euler_mascheroni_less_13_over_22: \"(euler_mascheroni :: real) < 13/22\" (is ?th2)\nproof -\n  have \"ln (real (Suc 7)) = 3 * ln 2\" by (simp add: ln_powr [symmetric])\n  also from ln_approx_bounds[of 2 3] have \"\\<dots> \\<in> {3*307/443<..<3*4615/6658}\"\n    by (simp add: eval_nat_numeral)\n  finally have \"ln (real (Suc 7)) \\<in> \\<dots>\" .\n  from euler_mascheroni_bounds'[OF _ this] have \"?th1 \\<and> ?th2\" by (simp_all add: harm_expand)\n  thus ?th1 ?th2 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/Analysis/Harmonic_Numbers.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8824278788223264, "lm_q2_score": 0.8479677583778258, "lm_q1q2_score": 0.7482703903350678}}
{"text": "section \\<open>Program Statements as Predicate Transformers\\<close>\n\ntheory Statements\nimports Preliminaries\nbegin\n\ntext \\<open>\n  Program statements are modeled as predicate transformers, functions from predicates to predicates.\n  If $\\mathit{State}$ is the type of program states, then a program $S$ is a a function from \n  $\\mathit{State}\\ \\mathit{set}$ to\n  $\\mathit{State}\\ \\mathit{set}$. If $q \\in \\mathit{State}\\ \\mathit{set}$, then the elements of \n  $S\\ q$ are the initial states from which\n  $S$ is guarantied to terminate in a state from $q$.\n\n  However, most of the time we will work with an arbitrary compleate lattice, or an arbitrary boolean algebra\n  instead of the complete boolean algebra of predicate transformers. \n\n  We will introduce in this section assert, assume, demonic choice, angelic choice, demonic update, and \n  angelic update statements. We will prove also that these statements are monotonic.\n\\<close>\n\nlemma mono_top[simp]: \"mono top\"\n  by (simp add: mono_def top_fun_def)\n\nlemma mono_choice[simp]: \"mono S \\<Longrightarrow> mono T \\<Longrightarrow> mono (S \\<sqinter> T)\"\n  apply (simp add: mono_def inf_fun_def)\n  apply safe\n  apply (rule_tac y = \"S x\" in order_trans)\n  apply simp_all\n  apply (rule_tac y = \"T x\" in order_trans)\n  by simp_all\n\nsubsection \"Assert statement\"\n\ntext \\<open>\nThe assert statement of a predicate $p$ when executed from a state $s$ fails\nif $s\\not\\in p$ and behaves as skip otherwise.\n\\<close>\n\ndefinition\n  assert::\"'a::semilattice_inf \\<Rightarrow> 'a \\<Rightarrow> 'a\" (\"{. _ .}\" [0] 1000) where\n  \"{.p.} q \\<equiv>  p \\<sqinter> q\"\n\nlemma mono_assert [simp]: \"mono {.p.}\"\n  apply (simp add: assert_def mono_def, safe)\n  apply (rule_tac y = \"x\" in order_trans)\n  by simp_all\n\nsubsection \"Assume statement\"\n\ntext \\<open>\nThe assume statement of a predicate $p$ when executed from a state $s$ is not enabled\nif $s\\not\\in p$ and behaves as skip otherwise.\n\\<close>\n\ndefinition\n  \"assume\" :: \"'a::boolean_algebra \\<Rightarrow> 'a \\<Rightarrow> 'a\" (\"[. _ .]\" [0] 1000) where\n  \"[. p .] q \\<equiv>  -p \\<squnion> q\"\n\n\nlemma mono_assume [simp]: \"mono (assume P)\"\n  apply (simp add: assume_def mono_def)\n  apply safe\n  apply (rule_tac y = \"y\" in order_trans)\n  by simp_all\n\nsubsection \"Demonic update statement\"\n\ntext \\<open>\nThe demonic update statement of a relation $Q: \\mathit{State} \\to \\mathit{Sate} \\to bool$,\nwhen executed in a state $s$ computes nondeterministically a new state $s'$ such \n$Q\\ s \\ s'$ is true. In order for this statement to be correct all\npossible choices of $s'$ should be correct. If there is no state $s'$\nsuch that $Q\\ s \\ s'$, then the demonic update of $Q$ is not enabled\nin $s$.\n\\<close>\n\ndefinition\n  demonic :: \"('a \\<Rightarrow> 'b::ord) \\<Rightarrow> 'b::ord \\<Rightarrow> 'a set\" (\"[: _ :]\" [0] 1000) where\n  \"[:Q:] p = {s . Q s \\<le> p}\"\n\nlemma mono_demonic [simp]: \"mono [:Q:]\"\n  apply (simp add: mono_def demonic_def)\n  by auto\n\ntheorem demonic_bottom:\n  \"[:R:] (\\<bottom>::('a::order_bot)) = {s . (R s) = \\<bottom>}\"\n  apply (unfold demonic_def, safe, simp_all)\n  apply (rule antisym)\n  by auto\n\ntheorem demonic_bottom_top [simp]:\n  \"[:(\\<bottom>::_::order_bot):]  = \\<top>\"\n  by (simp add: fun_eq_iff inf_fun_def sup_fun_def demonic_def top_fun_def bot_fun_def)\n\ntheorem demonic_sup_inf:\n  \"[:Q \\<squnion> Q':] = [:Q:] \\<sqinter> [:Q':]\"\n  by (simp add: fun_eq_iff sup_fun_def inf_fun_def demonic_def, blast)\n\nsubsection \"Angelic update statement\"\n\ntext \\<open>\nThe angelic update statement of a relation $Q: \\mathit{State} \\to \\mathit{State} \\to \\mathit{bool}$ is similar\nto the demonic version, except that it is enough that at least for one choice $s'$, $Q \\ s \\ s'$\nis correct. If there is no state $s'$\nsuch that $Q\\ s \\ s'$, then the angelic update of $Q$ fails in $s$.\n\\<close>\n\ndefinition\n  angelic :: \"('a \\<Rightarrow> 'b::{semilattice_inf,order_bot}) \\<Rightarrow> 'b \\<Rightarrow> 'a set\" \n               (\"{: _ :}\" [0] 1000) where\n  \"{:Q:} p = {s . (Q s) \\<sqinter> p \\<noteq> \\<bottom>}\"\n\nsyntax \"_update\" :: \"patterns => patterns => logic => logic\" (\"_ \\<leadsto> _ . _\" 0)\ntranslations\n  \"_update (_patterns x xs) (_patterns y ys) t\" == \"CONST id (_abs\n           (_pattern x xs) (_Coll (_pattern y ys) t))\"\n  \"_update x y t\" == \"CONST id (_abs x (_Coll y t))\"\n\nterm \"{: y, z \\<leadsto> x, z' . P x y z z' :}\"\n\ntheorem angelic_bottom [simp]:\n  \"angelic R \\<bottom>  = {}\"\n  by (simp add: angelic_def inf_bot_bot)\n\ntheorem angelic_disjunctive [simp]:\n  \"{:(R::('a \\<Rightarrow> 'b::complete_distrib_lattice)):} \\<in> Apply.Disjunctive\"\n  by (simp add: Apply.Disjunctive_def angelic_def inf_Sup, blast)\n\n\nsubsection \"The guard of a statement\"\n\ntext \\<open>\nThe guard of a statement $S$ is the set of iniatial states from which $S$\nis enabled or fails.\n\\<close>\n\ndefinition\n  \"((grd S)::'a::boolean_algebra) = - (S bot)\"\n\nlemma grd_choice[simp]: \"grd (S \\<sqinter> T) = (grd S) \\<squnion> (grd T)\"\n  by (simp add: grd_def inf_fun_def)\n\nlemma grd_demonic: \"grd [:Q:] = {s . \\<exists> s' . s' \\<in> (Q s) }\" \n  apply (simp add: grd_def demonic_def)\n  by blast\n\nlemma grd_demonic_2[simp]: \"(s \\<notin> grd [:Q:]) = (\\<forall> s' . s' \\<notin>  (Q s))\" \n  by (simp add: grd_demonic)\n\ntheorem grd_angelic:\n  \"grd {:R:} = UNIV\"\n  by (simp add: grd_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/DataRefinementIBP/Statements.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8824278726384089, "lm_q2_score": 0.8479677564567913, "lm_q1q2_score": 0.7482703833961308}}
{"text": "(*\n    $Id: sol.thy,v 1.2 2004/11/23 15:14:35 webertj Exp $\n*)\n\nheader {* Predicate Logic *}\n\n(*<*) theory sol imports Main begin (*>*)\n\ntext {*\nWe are again talking about proofs in the calculus of Natural Deduction.  In\naddition to the rules given in the exercise ``Propositional Logic'', you may\nnow also use\n\n  @{text \"exI:\"}~@{thm exI[no_vars]}\\\\\n  @{text \"exE:\"}~@{thm exE[no_vars]}\\\\\n  @{text \"allI:\"}~@{thm allI[no_vars]}\\\\\n  @{text \"allE:\"}~@{thm allE[no_vars]}\\\\\n\nGive a proof of the following propositions or an argument why the formula is\nnot valid:\n*}\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\ndone\n\nlemma \"(\\<forall>x. P x \\<longrightarrow> Q) = ((\\<exists>x. P x) \\<longrightarrow> Q)\"\n  apply (rule iffI)\n\n  apply (rule impI)\n  apply (erule exE)\n  apply (erule allE)\n  apply (erule impE)\n  apply assumption+\n\n  apply (rule allI)\n  apply (rule impI)\n  apply (erule impE)\n  apply (rule exI)\n  apply assumption+\ndone\n\nlemma \"((\\<forall> x. P x) \\<and> (\\<forall> x. Q x)) = (\\<forall> x. (P x \\<and> Q x))\"\n  apply (rule iffI)\n\n  apply (erule conjE)\n  apply (rule allI)\n  apply (erule allE)+\n  apply (rule conjI)\n  apply assumption+\n\n  apply (rule conjI)\n  apply (rule allI)\n  apply (erule allE)\n  apply (erule conjE)\n  apply assumption\n  apply (rule allI)\n  apply (erule allE)\n  apply (erule conjE)\n  apply assumption\ndone\n\nlemma \"((\\<forall> x. P x) \\<or> (\\<forall> x. Q x)) = (\\<forall> x. (P x \\<or> Q x))\"\n  refute\noops\n\ntext {*\nA possible counterexample is: @{text \"P = even\"}, @{text \"Q = odd\"},\ninterpreted over the natural numbers.\n*}\n\nlemma \"((\\<exists> x. P x) \\<or> (\\<exists> x. Q x)) = (\\<exists> x. (P x \\<or> Q x))\"\n  apply (rule iffI)\n\n  apply (erule disjE)\n  apply (erule exE)\n  apply (rule exI)\n  apply (rule disjI1)\n  apply assumption\n\n  apply (erule exE)\n  apply (rule exI)\n  apply (rule disjI2)\n  apply assumption\n\n  apply (erule exE)\n  apply (erule disjE)\n  apply (rule disjI1)\n  apply (rule exI)\n  apply assumption\n\n  apply (rule disjI2)\n  apply (rule exI)\n  apply assumption\ndone\n\nlemma \"(\\<forall>x. \\<exists>y. P x y) \\<longrightarrow> (\\<exists>y. \\<forall>x. P x y)\"\n  refute\noops\n\ntext {*\nFor a possible counterexample, let @{text \"P x y\"} be the statement ``@{text y}\nis successor of @{text x}'', interpreted over the natural numbers.\n*}\n\nlemma \"(\\<not> (\\<forall> x. P x)) = (\\<exists> x. \\<not> P x)\"\n  apply (rule iffI)\n\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\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/logic/predicate/sol.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278602705731, "lm_q2_score": 0.8479677602988602, "lm_q1q2_score": 0.7482703762989534}}
{"text": "theory Ex033 \n  imports Main \nbegin \n  \n  \n  \nlemma \"((A \\<and> (B \\<longrightarrow> C )) \\<longrightarrow> A) \\<longleftrightarrow> ((A  \\<and> (B \\<longrightarrow> \\<not>C)) \\<longrightarrow> A) \"\nproof -\n  {\n    assume \"(A \\<and> (B \\<longrightarrow> C )) \\<longrightarrow> A\" \n    {\n      assume \"A  \\<and> (B \\<longrightarrow> \\<not>C)\"\n      hence A by (rule conjE)\n    }\n    hence \"(A \\<and> (B \\<longrightarrow> \\<not>C)) \\<longrightarrow> A\" by (rule impI)\n  }\n  moreover\n  {\n    assume \"(A  \\<and> (B \\<longrightarrow> \\<not>C)) \\<longrightarrow> A\"\n    {\n      assume \"A \\<and> (B \\<longrightarrow> C )\"\n      hence  A by (rule conjE)\n    }\n    hence \"(A \\<and> (B \\<longrightarrow> C )) \\<longrightarrow> A\" by (rule impI)\n  }\n  ultimately show ?thesis by (rule iffI)\nqed\n  \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/Ex033.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9314625012602593, "lm_q2_score": 0.8031737963569014, "lm_q1q2_score": 0.7481262733012976}}
{"text": "theory Part_5 imports Main\n\nbegin\n\n(* 2.10 *)\n\ndatatype tree0 = Tip | Node \"tree0\" \"tree0\"\n\nfun nodes :: \"tree0 \\<Rightarrow> nat\" where\n\"nodes Tip = 1\" |\n\"nodes (Node left right) = 1 + nodes left + nodes right\"\n\nfun explode :: \"nat \\<Rightarrow> tree0 \\<Rightarrow> tree0\" where\n\"explode 0 t = t\" |\n\"explode (Suc m) t = explode m (Node t t)\"\n\ntheorem explode_size : \"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\n(* 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 n = n\" |\n\"eval (Const m) n = m\" |\n\"eval (Add m n) p = eval m p + eval n p\" |\n\"eval (Mult m n) p = eval m p * eval n p\"\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\nfun list_sum :: \"int list \\<Rightarrow> int list \\<Rightarrow> int list\" where\n\"list_sum [] xs = xs\" |\n\"list_sum xs [] = xs\" |\n\"list_sum (x#xs) (y#ys) = (x + y) # list_sum xs ys\"\n\nfun scalar_mult :: \"int \\<Rightarrow> int list \\<Rightarrow> int list\" where\n\"scalar_mult n [] = []\" |\n\"scalar_mult n (x#xs) = n*x # scalar_mult n xs\"\n\nfun list_mult :: \"int list \\<Rightarrow> int list \\<Rightarrow> int list\" where\n\"list_mult [] xs = xs\" |\n\"list_mult (x#xs) ys = list_sum (scalar_mult x ys) (0 # list_mult xs ys)\"\n\nfun coeffs :: \"exp \\<Rightarrow> int list\" where\n\"coeffs Var = [0, 1]\" |\n\"coeffs (Const n) = [n]\" |\n\"coeffs (Add a b) = list_sum (coeffs a) (coeffs b)\" |\n\"coeffs (Mult a b) = list_mult (coeffs a) (coeffs b)\"\n\nlemma \"evalp (coeffs e) x = eval e x\"\n  nitpick\n  oops", "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-2/Part_5.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070109242131, "lm_q2_score": 0.8221891261650247, "lm_q1q2_score": 0.7481156502032084}}
{"text": "(*  Title:      HOL/Datatype_Examples/Lambda_Term.thy\n    Author:     Dmitriy Traytel, TU Muenchen\n    Author:     Andrei Popescu, TU Muenchen\n    Copyright   2012\n\nLambda-terms.\n*)\n\nsection {* Lambda-Terms *}\n\ntheory Lambda_Term\nimports \"~~/src/HOL/Library/FSet\"\nbegin\n\nsection {* Datatype definition *}\n\ndatatype 'a trm =\n  Var 'a |\n  App \"'a trm\" \"'a trm\" |\n  Lam 'a \"'a trm\" |\n  Lt \"('a \\<times> 'a trm) fset\" \"'a trm\"\n\n\nsubsection {* Example: The set of all variables varsOf and free variables fvarsOf of a term *}\n\nprimrec varsOf :: \"'a trm \\<Rightarrow> 'a set\" where\n  \"varsOf (Var a) = {a}\"\n| \"varsOf (App f x) = varsOf f \\<union> varsOf x\"\n| \"varsOf (Lam x b) = {x} \\<union> varsOf b\"\n| \"varsOf (Lt F t) = varsOf t \\<union> (\\<Union> { {x} \\<union> X | x X. (x,X) |\\<in>| fimage (map_prod id varsOf) F})\"\n\nprimrec fvarsOf :: \"'a trm \\<Rightarrow> 'a set\" where\n  \"fvarsOf (Var x) = {x}\"\n| \"fvarsOf (App t1 t2) = fvarsOf t1 \\<union> fvarsOf t2\"\n| \"fvarsOf (Lam x t) = fvarsOf t - {x}\"\n| \"fvarsOf (Lt xts t) = fvarsOf t - {x | x X. (x,X) |\\<in>| fimage (map_prod id varsOf) xts} \\<union>\n    (\\<Union> {X | x X. (x,X) |\\<in>| fimage (map_prod id varsOf) xts})\"\n\nlemma diff_Un_incl_triv: \"\\<lbrakk>A \\<subseteq> D; C \\<subseteq> E\\<rbrakk> \\<Longrightarrow> A - B \\<union> C \\<subseteq> D \\<union> E\" by blast\n\nlemma in_fimage_map_prod_fset_iff[simp]:\n  \"(x, y) |\\<in>| fimage (map_prod f g) xts \\<longleftrightarrow> (\\<exists> t1 t2. (t1, t2) |\\<in>| xts \\<and> x = f t1 \\<and> y = g t2)\"\n  by force\n\nlemma fvarsOf_varsOf: \"fvarsOf t \\<subseteq> varsOf t\"\nproof induct\n  case (Lt xts t) thus ?case unfolding fvarsOf.simps varsOf.simps by (elim diff_Un_incl_triv) auto\nqed 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/Datatype_Examples/Lambda_Term.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772417253256, "lm_q2_score": 0.8558511469672595, "lm_q1q2_score": 0.7480800098685985}}
{"text": "theory Padic_Field_Polynomials\n  imports Padic_Fields\n\nbegin \n\n(**************************************************************************************************)\n(**************************************************************************************************)\nsection\\<open>$p$-adic Univariate Polynomials and Hensel's Lemma\\<close>\n(**************************************************************************************************)\n(**************************************************************************************************)\ntype_synonym padic_field_poly = \"nat \\<Rightarrow> padic_number\"\n\ntype_synonym padic_field_fun = \"padic_number \\<Rightarrow> padic_number\"\n\n(**************************************************************************************************)\n(**************************************************************************************************)\nsubsection\\<open>Gauss Norms of Polynomials\\<close>\n(**************************************************************************************************)\n(**************************************************************************************************)\n\ntext \\<open>\n  The Gauss norm of a polynomial is defined to be the minimum valuation of a coefficient of that \n  polynomial. This induces a valuation on the ring of polynomials, and in particular it satisfies \n  the ultrametric inequality. In addition, the Gauss norm of a polynomial $f(x)$ gives a lower \n  bound for the value $\\text{val } (f(a))$ in terms of $\\text{val }(a)$, for a point \n  $a \\in \\mathbb{Q}_p$. We introduce Gauss norms here as a useful tool for stating and proving \n  Hensel's Lemma for the field $\\mathbb{Q}_p$. We are abusing terminology slightly in calling \n  this the Gauss norm, rather than the Gauss valuation, but this is just to conform with our \n  decision to work exclusively with the $p$-adic valuation and not discuss the equivalent \n  real-valued $p$-adic norm. For a detailed treatment of Gauss norms one can see, for example\n  \\cite{engler2005valued}.\n\\<close>\ncontext padic_fields\nbegin\n\nno_notation Zp.to_fun (infixl\\<open>\\<bullet>\\<close> 70)\n\nabbreviation(input) Q\\<^sub>p_x where\n\"Q\\<^sub>p_x \\<equiv> UP Q\\<^sub>p\"\n\ndefinition gauss_norm where\n\"gauss_norm g = Min (val ` g ` {..degree g}) \"\n\nlemma gauss_normE:  \n  assumes \"g \\<in> carrier Q\\<^sub>p_x\"\n  shows \"gauss_norm g \\<le> val (g k)\" \n  apply(cases \"k \\<le> degree g\")\n  unfolding gauss_norm_def \n  using assms apply auto[1]  \nproof-\n  assume \"\\<not> k \\<le> degree g\"\n  then have \"g k = \\<zero>\\<^bsub>Q\\<^sub>p\\<^esub> \"\n    by (simp add: UPQ.deg_leE assms)    \n  then show \"Min (val ` g ` {..deg Q\\<^sub>p g}) \\<le> val (g k)\"\n    by (simp add: local.val_zero)    \nqed\n\nlemma gauss_norm_geqI:\n  assumes \"g \\<in> carrier (UP Q\\<^sub>p)\"\n  assumes \"\\<And>n. val (g n) \\<ge> \\<alpha>\"\n  shows \"gauss_norm g \\<ge> \\<alpha>\"\n  unfolding gauss_norm_def using assms \n  by simp\n\nlemma gauss_norm_eqI:\n  assumes \"g \\<in> carrier (UP Q\\<^sub>p)\"\n  assumes \"\\<And>n. val (g n) \\<ge> \\<alpha>\"\n  assumes \"val (g i) = \\<alpha>\"\n  shows \"gauss_norm g = \\<alpha>\"\nproof- \n  have 0: \"gauss_norm g \\<le> \\<alpha>\"\n    using assms gauss_normE gauss_norm_def by fastforce\n  have 1: \"gauss_norm g \\<ge> \\<alpha>\"\n    using assms gauss_norm_geqI by auto \n  show ?thesis using 0 1 by auto \nqed\n\nlemma nonzero_poly_nonzero_coeff:\n  assumes \"g \\<in> carrier Q\\<^sub>p_x\"\n  assumes \"g \\<noteq> \\<zero>\\<^bsub>Q\\<^sub>p_x\\<^esub>\"\n  shows \"\\<exists>k. k \\<le>degree g \\<and> g k \\<noteq>\\<zero>\\<^bsub>Q\\<^sub>p\\<^esub>\"\nproof(rule ccontr)\n  assume \"\\<not> (\\<exists>k\\<le>degree g. g k \\<noteq> \\<zero>\\<^bsub>Q\\<^sub>p\\<^esub>)\"\n  then have 0: \"\\<And>k. g k = \\<zero>\\<^bsub>Q\\<^sub>p\\<^esub>\"\n    by (meson UPQ.deg_leE assms(1) not_le_imp_less)\n  then show False \n    using assms  UPQ.cfs_zero by blast\nqed \n\nlemma gauss_norm_prop:\n  assumes \"g \\<in> carrier Q\\<^sub>p_x\"\n  assumes \"g \\<noteq> \\<zero>\\<^bsub>Q\\<^sub>p_x\\<^esub>\"\n  shows \"gauss_norm g \\<noteq> \\<infinity>\"\nproof- \n  obtain k where k_def: \"k \\<le>degree g \\<and> g k \\<noteq>\\<zero>\\<^bsub>Q\\<^sub>p\\<^esub>\"\n    using assms nonzero_poly_nonzero_coeff \n    by blast\n  then have 0: \"gauss_norm g \\<le> val (g k)\"\n    using assms(1) gauss_normE by blast\n  have \"g k \\<in> carrier Q\\<^sub>p\"\n    using UPQ.cfs_closed assms(1) by blast    \n  hence \"val (g k) < \\<infinity>\"\n    using k_def assms  \n    by (metis eint_ord_code(3) eint_ord_simps(4) val_ineq)\n  then show ?thesis \n    using 0 not_le by fastforce   \nqed\n\nlemma gauss_norm_coeff_norm:\n  \"\\<exists>n \\<le> degree g. (gauss_norm g) = val (g n)\"\nproof-\n  have \"finite (val ` g ` {..deg Q\\<^sub>p g})\"\n    by blast\n  hence \"\\<exists>x \\<in> (val ` g ` {..deg Q\\<^sub>p g}). gauss_norm g = x\"\n  unfolding gauss_norm_def\n  by auto \n  thus ?thesis unfolding gauss_norm_def \n    by blast \nqed\n\nlemma gauss_norm_smult_cfs:\n  assumes \"g \\<in> carrier Q\\<^sub>p_x\"\n  assumes \"a \\<in> carrier Q\\<^sub>p\"\n  assumes \"gauss_norm g = val (g k)\"\n  shows \"gauss_norm (a \\<odot>\\<^bsub>Q\\<^sub>p_x\\<^esub> g) = val a + val (g k)\"\nproof-\n  obtain l where l_def: \"gauss_norm (a \\<odot>\\<^bsub>Q\\<^sub>p_x\\<^esub> g) =  val ((a \\<odot>\\<^bsub>Q\\<^sub>p_x\\<^esub> g) l)\"\n    using gauss_norm_coeff_norm \n    by blast\n  then have \"gauss_norm (a \\<odot>\\<^bsub>Q\\<^sub>p_x\\<^esub> g) =  val (a \\<otimes>\\<^bsub>Q\\<^sub>p\\<^esub> (g l))\"\n    using assms \n    by simp   \n  then have \"gauss_norm (a \\<odot>\\<^bsub>Q\\<^sub>p_x\\<^esub> g) =  val a + val (g l)\"\n    by (simp add: UPQ.cfs_closed assms(1) assms(2) val_mult)            \n  then have 0: \"gauss_norm (a \\<odot>\\<^bsub>Q\\<^sub>p_x\\<^esub> g) \\<le> val a +val (g k)\"\n    using assms  gauss_normE[of g l]\n    by (metis UPQ.UP_smult_closed UPQ.cfs_closed UPQ.cfs_smult gauss_normE val_mult)          \n  have \"val a + val (g k) = val ((a \\<odot>\\<^bsub>Q\\<^sub>p_x\\<^esub> g) k)\"\n    by (simp add: UPQ.cfs_closed assms(1) assms(2) val_mult)       \n  then have \"gauss_norm (a \\<odot>\\<^bsub>Q\\<^sub>p_x\\<^esub> g) \\<ge> val a + val (g k)\"\n    by (metis \\<open>gauss_norm (a \\<odot>\\<^bsub>UP Q\\<^sub>p\\<^esub> g) = val a + val (g l)\\<close> add_left_mono assms(1) assms(3) gauss_normE)   \n  then show ?thesis \n    using 0  by auto     \nqed\n\nlemma gauss_norm_smult:\n  assumes \"g \\<in> carrier Q\\<^sub>p_x\"\n  assumes \"a \\<in> carrier Q\\<^sub>p\"\n  shows \"gauss_norm (a \\<odot>\\<^bsub>Q\\<^sub>p_x\\<^esub> g) = val a + gauss_norm g\"\n  using gauss_norm_smult_cfs[of g a] gauss_norm_coeff_norm[of g] assms \n  by metis\n\nlemma gauss_norm_ultrametric:\n  assumes \"g \\<in> carrier Q\\<^sub>p_x\"\n  assumes \"h \\<in> carrier Q\\<^sub>p_x\"\n  shows \"gauss_norm (g \\<oplus>\\<^bsub>Q\\<^sub>p_x\\<^esub> h) \\<ge> min (gauss_norm g) (gauss_norm h)\"\nproof-\n  obtain k where \"gauss_norm (g \\<oplus>\\<^bsub>Q\\<^sub>p_x\\<^esub> h) = val ((g \\<oplus>\\<^bsub>Q\\<^sub>p_x\\<^esub> h) k)\"\n    using gauss_norm_coeff_norm \n    by blast\n  then have 0: \"gauss_norm (g \\<oplus>\\<^bsub>Q\\<^sub>p_x\\<^esub> h) = val (g k \\<oplus>\\<^bsub>Q\\<^sub>p\\<^esub> h k)\"\n    by (simp add: assms(1) assms(2))      \n  have \"min (val (g k)) (val (h k))\\<ge> min (gauss_norm g) (gauss_norm h)\"\n    using gauss_normE[of g k] gauss_normE[of h k]  assms(1) assms(2) min.mono \n    by blast    \n  then show ?thesis \n    using 0 val_ultrametric[of \"g k\" \"h k\"] assms(1) assms(2) dual_order.trans \n    by (metis (no_types, lifting) UPQ.cfs_closed)         \nqed\n\nlemma gauss_norm_a_inv: \n  assumes \"f \\<in> carrier (UP Q\\<^sub>p)\"\n  shows \"gauss_norm (\\<ominus>\\<^bsub>UP Q\\<^sub>p\\<^esub>f) = gauss_norm f\"\nproof- \n  have 0: \"\\<And>n. ((\\<ominus>\\<^bsub>UP Q\\<^sub>p\\<^esub>f) n) = \\<ominus> (f n)\"\n    using assms by simp\n  have 1: \"\\<And>n. val ((\\<ominus>\\<^bsub>UP Q\\<^sub>p\\<^esub>f) n) = val (f n)\"\n    using 0 assms UPQ.UP_car_memE(1) val_minus by presburger\n  obtain i where i_def: \"gauss_norm f = val (f i)\"\n    using assms gauss_norm_coeff_norm by blast\n  have 2: \"\\<And>k. val ((\\<ominus>\\<^bsub>UP Q\\<^sub>p\\<^esub>f) k) \\<ge> val (f i)\"\n    unfolding 1 \n    using i_def assms gauss_normE by fastforce\n  show ?thesis \n    apply(rule gauss_norm_eqI[of _ _ i])\n      apply (simp add: assms; fail)\n    unfolding 1 using assms gauss_normE apply blast\n    unfolding i_def by blast \nqed\n\nlemma gauss_norm_ultrametric':\n  assumes \"f \\<in> carrier (UP Q\\<^sub>p)\"\n  assumes \"g \\<in> carrier (UP Q\\<^sub>p)\"\n  shows \"gauss_norm (f \\<ominus>\\<^bsub>UP Q\\<^sub>p\\<^esub> g) \\<ge> min (gauss_norm f) (gauss_norm g)\"\n  unfolding a_minus_def \n  using assms gauss_norm_a_inv[of g] gauss_norm_ultrametric \n  by (metis UPQ.UP_a_inv_closed)\n\nlemma gauss_norm_finsum:\n  assumes \"f \\<in> A \\<rightarrow> carrier Q\\<^sub>p_x\"\n  assumes \"finite A\"\n  assumes \"A \\<noteq> {}\"\n  shows \" gauss_norm (\\<Oplus>\\<^bsub>Q\\<^sub>p_x\\<^esub>i\\<in>A. f i) \\<ge> Min (gauss_norm ` (f`A))\"  \nproof-\n  obtain k where k_def: \"val ((\\<Oplus>\\<^bsub>Q\\<^sub>p_x\\<^esub>i\\<in>A. f i) k) = gauss_norm (\\<Oplus>\\<^bsub>Q\\<^sub>p_x\\<^esub>i\\<in>A. f i)\"\n    by (metis gauss_norm_coeff_norm)\n  then have 0: \"val (\\<Oplus>\\<^bsub>Q\\<^sub>p\\<^esub>i\\<in>A. f i k) \\<ge> Min (val ` (\\<lambda> i. f i k) ` A)\"\n    using finsum_val_ultrametric[of \"\\<lambda> i. f i k\" A] assms \n    by (simp add: \\<open>\\<lbrakk>(\\<lambda>i. f i k) \\<in> A \\<rightarrow> carrier Q\\<^sub>p; finite A; A \\<noteq> {}\\<rbrakk> \\<Longrightarrow> Min (val ` (\\<lambda>i. f i k) ` A) \\<le> val (\\<Oplus>i\\<in>A. f i k)\\<close> Pi_iff UPQ.cfs_closed)      \n  have \"(\\<And>a. a \\<in> A \\<Longrightarrow> (val \\<circ> (\\<lambda>i. f i k)) a \\<ge> gauss_norm (f a))\"\n    using gauss_normE assms\n    by (metis (no_types, lifting) Pi_split_insert_domain Set.set_insert comp_apply)  \n  then have \"Min (val ` (\\<lambda> i. f i k) ` A) \\<ge> Min ((\\<lambda> i. gauss_norm (f  i)) ` A)\" \n    using Min_mono'[of A] \n    by (simp add: assms(2) image_comp)\n  then have 1: \"Min (val ` (\\<lambda> i. f i k) ` A) \\<ge> Min (gauss_norm ` f ` A)\"\n    by (metis image_image)\n  have \"f \\<in> A \\<rightarrow> carrier (UP Q\\<^sub>p) \\<longrightarrow> ((\\<Oplus>\\<^bsub>Q\\<^sub>p_x\\<^esub>i\\<in>A. f i) \\<in> carrier Q\\<^sub>p_x \\<and> ((\\<Oplus>\\<^bsub>Q\\<^sub>p_x\\<^esub>i\\<in>A. f i) k) = (\\<Oplus>\\<^bsub>Q\\<^sub>p\\<^esub>i\\<in>A. f i k)) \"\n    apply(rule finite.induct[of A])\n      apply (simp add: assms(2); fail)\n     apply (metis (no_types, lifting) Pi_I Qp.add.finprod_one_eqI UPQ.P.finsum_closed UPQ.P.finsum_empty UPQ.cfs_zero empty_iff)        \n  proof-\n    fix a A assume A: \"finite A\" \"f \\<in> A \\<rightarrow> carrier (UP Q\\<^sub>p) \\<longrightarrow> ( finsum (UP Q\\<^sub>p) f A \\<in> carrier (UP Q\\<^sub>p) \\<and> finsum (UP Q\\<^sub>p) f A k = (\\<Oplus>i\\<in>A. f i k)) \"\n    show \" f \\<in> insert a A \\<rightarrow> carrier (UP Q\\<^sub>p) \\<longrightarrow>  finsum (UP Q\\<^sub>p) f (insert a A) \\<in> carrier (UP Q\\<^sub>p) \\<and> finsum (UP Q\\<^sub>p) f (insert a A) k = (\\<Oplus>i\\<in>insert a A. f i k)\"\n      apply(cases \"a \\<in> A\")\n      using A \n      apply (simp add: insert_absorb; fail)\n    proof assume B: \"a \\<notin> A\" \" f \\<in> insert a A \\<rightarrow> carrier (UP Q\\<^sub>p)\"\n      then have f_a: \"f a \\<in> carrier (UP Q\\<^sub>p)\"\n        by blast \n      have f_A: \"f \\<in> A \\<rightarrow> carrier (UP Q\\<^sub>p)\"\n        using B by blast \n      have \"finsum (UP Q\\<^sub>p) f (insert a A) = f a \\<oplus>\\<^bsub>UP Q\\<^sub>p\\<^esub>finsum (UP Q\\<^sub>p) f A\"\n        using assms A B f_a f_A  finsum_insert by simp       \n      then have 0: \"finsum (UP Q\\<^sub>p) f (insert a A) k = f a k \\<oplus>\\<^bsub>Q\\<^sub>p\\<^esub> (finsum (UP Q\\<^sub>p) f A) k\"\n        using f_a f_A A B \n        by simp\n      have \" ( \\<lambda> a. f a k) \\<in> A \\<rightarrow> carrier Q\\<^sub>p\"\n      proof fix a assume \"a \\<in> A\"\n        then have \"f a \\<in> carrier (UP Q\\<^sub>p)\"\n          using f_A by blast \n        then show \"f a k \\<in> carrier Q\\<^sub>p\"\n          using A cfs_closed by blast \n      qed \n      then have 0: \"finsum (UP Q\\<^sub>p) f (insert a A) k = (\\<Oplus>i\\<in>insert a A. f i k)\"\n        using A B Qp.finsum_insert[of A a \"\\<lambda> a. f a k\"] \n        by (simp add: UPQ.cfs_closed)        \n      thus \" finsum (UP Q\\<^sub>p) f (insert a A) \\<in> carrier (UP Q\\<^sub>p) \\<and> finsum (UP Q\\<^sub>p) f (insert a A) k = (\\<Oplus>i\\<in>insert a A. f i k)\"\n        using B(2) UPQ.P.finsum_closed by blast\n    qed        \n  qed   \n  then have \"(\\<Oplus>\\<^bsub>Q\\<^sub>p_x\\<^esub>i\\<in>A. f i) \\<in> carrier Q\\<^sub>p_x \\<and> ((\\<Oplus>\\<^bsub>Q\\<^sub>p_x\\<^esub>i\\<in>A. f i) k) = (\\<Oplus>\\<^bsub>Q\\<^sub>p\\<^esub>i\\<in>A. f i k)\"\n    using assms by blast \n  hence 3: \"gauss_norm (\\<Oplus>\\<^bsub>Q\\<^sub>p_x\\<^esub>i\\<in>A. f i) \\<ge> Min (val ` (\\<lambda> i. f i k) ` A)\"\n    using 0  k_def by auto \n  thus ?thesis \n    using 1 le_trans by auto \nqed\n\nlemma gauss_norm_monom:\n  assumes \"a \\<in> carrier Q\\<^sub>p\"\n  shows \"gauss_norm (monom Q\\<^sub>p_x a n) = val a\"\nproof-\n  have \"val ((monom Q\\<^sub>p_x a n) n) \\<ge> gauss_norm (monom Q\\<^sub>p_x a n)\"\n    using assms gauss_normE[of \"monom Q\\<^sub>p_x a n\" n] UPQ.monom_closed \n    by blast   \n  then show ?thesis \n    using gauss_norm_coeff_norm[of \"monom Q\\<^sub>p_x a n\"] assms val_ineq UPQ.cfs_monom by fastforce     \nqed\n\nlemma val_val_ring_prod:\n  assumes \"a \\<in> \\<O>\\<^sub>p\"\n  assumes \"b \\<in> carrier Q\\<^sub>p\"\n  shows \"val (a \\<otimes>\\<^bsub>Q\\<^sub>p\\<^esub> b) \\<ge> val b\"\nproof-\n  have 0: \"val (a \\<otimes>\\<^bsub>Q\\<^sub>p\\<^esub> b) = val a + val b\"\n    using assms val_ring_memE[of a] val_mult \n    by blast\n  have 1: \" val a \\<ge> 0\"\n    using assms \n    by (simp add: val_ring_memE)\n  then show ?thesis \n    using assms 0 \n    by simp   \nqed\n\nlemma val_val_ring_prod':\n  assumes \"a \\<in> \\<O>\\<^sub>p\"\n  assumes \"b \\<in> carrier Q\\<^sub>p\"\n  shows \"val (b \\<otimes>\\<^bsub>Q\\<^sub>p\\<^esub> a) \\<ge> val b\"\n  using val_val_ring_prod[of a b]\n  by (simp add: Qp.m_comm val_ring_memE assms(1) assms(2)) \n\nlemma val_ring_nat_pow_closed:\n  assumes \"a \\<in> \\<O>\\<^sub>p\"\n  shows \"(a[^](n::nat)) \\<in> \\<O>\\<^sub>p\"\n  apply(induction n)\n  apply auto[1]\n  using Qp.inv_one Z\\<^sub>p_mem apply blast\n  by (metis Qp.nat_pow_Suc Qp.nat_pow_closed val_ring_memE assms image_eqI inc_of_prod to_Zp_closed to_Zp_inc to_Zp_mult)\n  \nlemma val_ringI:\n  assumes \"a \\<in> carrier Q\\<^sub>p\"\n  assumes \"val a \\<ge>0\"\n  shows \" a \\<in> \\<O>\\<^sub>p\"\n  apply(rule val_ring_val_criterion)\n  using assms by auto \n\nnotation UPQ.to_fun (infixl\\<open>\\<bullet>\\<close> 70)\n\nlemma val_gauss_norm_eval:\n  assumes \"g \\<in> carrier Q\\<^sub>p_x\"\n  assumes \"a \\<in> \\<O>\\<^sub>p\"\n  shows \"val (g \\<bullet> a) \\<ge> gauss_norm g\"\nproof-\n  have 0: \"g\\<bullet>a = (\\<Oplus>\\<^bsub>Q\\<^sub>p\\<^esub>i\\<in>{..degree g}. (g i)\\<otimes>\\<^bsub>Q\\<^sub>p\\<^esub> (a[^]i))\"\n    using val_ring_memE assms to_fun_formula[of g a] by auto \n    \n  have 1: \"(\\<lambda>i. g i \\<otimes>\\<^bsub>Q\\<^sub>p\\<^esub> (a[^]i)) \\<in> {..degree g} \\<rightarrow> carrier Q\\<^sub>p\"\n     using assms \n    by (meson Pi_I val_ring_memE cfs_closed monom_term_car)    \n  then have 2: \"val (g\\<bullet>a) \\<ge> Min (val ` (\\<lambda> i. ((g i)\\<otimes>\\<^bsub>Q\\<^sub>p\\<^esub> (a[^]i))) ` {..degree g})\"\n    using 0 finsum_val_ultrametric[of \"\\<lambda> i. ((g i)\\<otimes>\\<^bsub>Q\\<^sub>p\\<^esub> (a[^]i))\" \"{..degree g}\" ]  \n    by (metis finite_atMost not_empty_eq_Iic_eq_empty)\n  have 3: \"\\<And> i. val ((g i)\\<otimes>\\<^bsub>Q\\<^sub>p\\<^esub> (a[^]i)) = val (g i) + val (a[^]i)\"\n    using assms val_mult \n    by (simp add: val_ring_memE UPQ.cfs_closed)    \n  have 4: \"\\<And> i. val ((g i)\\<otimes>\\<^bsub>Q\\<^sub>p\\<^esub> (a[^]i)) \\<ge> val (g i)\"    \n  proof-\n    fix i \n    show \"val ((g i)\\<otimes>\\<^bsub>Q\\<^sub>p\\<^esub> (a[^]i)) \\<ge> val (g i)\"\n      using val_val_ring_prod'[of \"a[^]i\" \"g i\" ] \n        assms(1) assms(2) val_ring_nat_pow_closed cfs_closed \n      by simp      \n  qed\n  have \"Min (val ` (\\<lambda>i. g i \\<otimes>\\<^bsub>Q\\<^sub>p\\<^esub> (a[^]i)) ` {..degree g}) \\<ge> Min ((\\<lambda>i. val (g i)) ` {..degree g})\"\n    using Min_mono'[of \"{..degree g}\" \"\\<lambda>i. val (g i)\" \"\\<lambda>i. val (g i \\<otimes>\\<^bsub>Q\\<^sub>p\\<^esub> (a[^]i))\" ] 4 2 \n    by (metis finite_atMost image_image)\n  then have \"Min (val ` (\\<lambda>i. g i \\<otimes>\\<^bsub>Q\\<^sub>p\\<^esub> (a[^]i)) ` {..degree g}) \\<ge> Min (val ` g ` {..degree g})\"\n    by (metis  image_image)\n  then have  \"val (g\\<bullet>a) \\<ge> Min (val ` g ` {..degree g})\"\n    using 2 \n    by (meson atMost_iff atMost_subset_iff in_mono)    \n  then show ?thesis \n    by (simp add: \\<open>val (g\\<bullet>a) \\<ge> Min (val ` g ` {..degree g})\\<close> gauss_norm_def)\nqed\n\nlemma positive_gauss_norm_eval:\n  assumes \"g \\<in> carrier Q\\<^sub>p_x\"\n  assumes \"gauss_norm g \\<ge> 0\"\n  assumes \"a \\<in> \\<O>\\<^sub>p\"\n  shows \"(g\\<bullet>a) \\<in> \\<O>\\<^sub>p\"\n  apply(rule val_ring_val_criterion[of \"g\\<bullet>a\"])\n  using assms val_ring_memE \n  using UPQ.to_fun_closed apply blast\n  using assms val_gauss_norm_eval[of g a] by auto \n  \nlemma positive_gauss_norm_valuation_ring_coeffs:\n  assumes \"g \\<in> carrier Q\\<^sub>p_x\"\n  assumes \"gauss_norm g \\<ge> 0\"\n  shows \"g n \\<in> \\<O>\\<^sub>p\"\n  apply(rule val_ringI)\n  using cfs_closed assms(1) apply blast\n  using gauss_normE[of g n] assms by auto  \n\nlemma val_ring_cfs_imp_nonneg_gauss_norm:\n  assumes \"g \\<in> carrier (UP Q\\<^sub>p)\"\n  assumes \"\\<And>n. g n \\<in> \\<O>\\<^sub>p\"\n  shows \"gauss_norm g \\<ge> 0\"\n  by(rule gauss_norm_geqI, rule assms, rule val_ring_memE, rule assms)\n\nlemma val_of_add_pow:\n  assumes \"a \\<in> carrier Q\\<^sub>p\"\n  shows \"val ([(n::nat)]\\<cdot>a) \\<ge> val a\"\nproof-\n  have 0: \"[(n::nat)]\\<cdot>a = ([n]\\<cdot>\\<one>)\\<otimes>a\"\n    using assms Qp.add_pow_ldistr Qp.cring_simprules(12) Qp.one_closed by presburger\n  have 1: \"val ([(n::nat)]\\<cdot>a) = val ([n]\\<cdot>\\<one>) + val a\"\n    unfolding 0 by(rule val_mult, simp, rule assms)\n  show ?thesis unfolding 1 using assms \n    by (simp add: val_of_nat_inc)\nqed\n\nlemma gauss_norm_pderiv:\n  assumes \"g \\<in> carrier (UP Q\\<^sub>p)\"\n  shows \"gauss_norm g \\<le> gauss_norm (pderiv g)\"\n  apply(rule gauss_norm_geqI)\n  using UPQ.pderiv_closed assms apply blast\n  using gauss_normE pderiv_cfs val_of_add_pow \n  by (smt UPQ.cfs_closed assms dual_order.trans)\n\n(**************************************************************************************************)\n(**************************************************************************************************)\nsubsection\\<open>Mapping Polynomials with Value Ring Coefficients to Polynomials over $\\mathbb{Z}_p$\\<close>\n(**************************************************************************************************)\n(**************************************************************************************************)\n\ndefinition to_Zp_poly where\n\"to_Zp_poly g = (\\<lambda>n. to_Zp (g n))\"\n\nlemma to_Zp_poly_closed:\n  assumes \"g \\<in> carrier Q\\<^sub>p_x\"\n  assumes \"gauss_norm g \\<ge> 0\"\n  shows \"to_Zp_poly g \\<in> carrier (UP Z\\<^sub>p)\"\nproof-\n  have  \"to_Zp_poly g \\<in> up Z\\<^sub>p\"\n    apply(rule mem_upI)\n   unfolding to_Zp_poly_def \n   using cfs_closed[of g ] assms(1) to_Zp_closed[of ]  apply blast  \n  proof-\n    have \"\\<exists>n. bound \\<zero>\\<^bsub>Q\\<^sub>p\\<^esub> n g\"\n     using UPQ.deg_leE assms(1) by auto\n    then obtain n where n_def: \" bound \\<zero>\\<^bsub>Q\\<^sub>p\\<^esub> n g\"\n      by blast \n    then have \" bound \\<zero>\\<^bsub>Z\\<^sub>p\\<^esub> n (\\<lambda>n. to_Zp (g n))\"\n      unfolding bound_def \n      by (simp add: to_Zp_zero)\n    then show \"\\<exists>n. bound \\<zero>\\<^bsub>Z\\<^sub>p\\<^esub> n (\\<lambda>n. to_Zp (g n))\"\n      by blast\n  qed\n  then show ?thesis using UP_def[of Z\\<^sub>p]\n    by simp\nqed\n\ndefinition poly_inc where\n\"poly_inc g = (\\<lambda>n::nat. \\<iota> (g n))\"\n\nlemma poly_inc_closed:\n  assumes \"g \\<in> carrier (UP Z\\<^sub>p)\"\n  shows \"poly_inc g \\<in> carrier Q\\<^sub>p_x\"\nproof-\n  have \"poly_inc g \\<in> up Q\\<^sub>p\"\n  proof(rule mem_upI)\n    show \"\\<And>n. poly_inc g n \\<in> carrier Q\\<^sub>p\"\n    proof- fix n\n      have \"g n \\<in> carrier Z\\<^sub>p\"\n        using assms UP_def \n        by (simp add: UP_def mem_upD)\n      then show \"poly_inc g n \\<in> carrier Q\\<^sub>p\"\n        using assms poly_inc_def[of g] inc_def[of \"g n\" ] inc_closed \n        by force                   \n    qed\n    show \"\\<exists>n. bound \\<zero>\\<^bsub>Q\\<^sub>p\\<^esub> n (poly_inc g)\"\n    proof-\n      obtain n where n_def: \" bound \\<zero>\\<^bsub>Z\\<^sub>p\\<^esub> n g\"\n        using assms  bound_def[of \"\\<zero>\\<^bsub>Z\\<^sub>p\\<^esub>\" _ g]Zp.cring_axioms UP_cring.deg_leE[of Z\\<^sub>p g]\n        unfolding UP_cring_def \n        by metis \n      then have \" bound \\<zero>\\<^bsub>Q\\<^sub>p\\<^esub> n (poly_inc g)\"\n        unfolding poly_inc_def bound_def \n        by (metis Qp.nat_inc_zero Zp.nat_inc_zero inc_of_nat)\n      then show ?thesis by blast\n    qed\n  qed\n  then show ?thesis \n    by (simp add: \\<open>poly_inc g \\<in> up Q\\<^sub>p\\<close> UP_def)\nqed\n\nlemma poly_inc_inverse_right:\n  assumes \"g \\<in> carrier (UP Z\\<^sub>p)\"\n  shows \"to_Zp_poly (poly_inc g) = g\"\nproof-\n  have 0: \"\\<And>n. g n \\<in> carrier Z\\<^sub>p\"\n    by (simp add: Zp.cfs_closed assms)    \n  show ?thesis \n    unfolding to_Zp_poly_def poly_inc_def\n  proof\n    fix n\n    show \"to_Zp (\\<iota> (g n)) = g n\"\n      using 0 inc_to_Zp \n      by auto\n  qed\nqed\n\nlemma poly_inc_inverse_left:\n  assumes \"g \\<in> carrier Q\\<^sub>p_x\"\n  assumes \"gauss_norm g \\<ge>0\"\n  shows \"poly_inc (to_Zp_poly g) = g\"\nproof\n  fix x\n  show \"poly_inc (to_Zp_poly g) x = g x\"\n    using assms unfolding poly_inc_def to_Zp_poly_def \n    by (simp add: positive_gauss_norm_valuation_ring_coeffs to_Zp_inc)    \nqed\n\nlemma poly_inc_plus: \n  assumes \"f \\<in> carrier (UP Z\\<^sub>p)\"\n  assumes \"g \\<in> carrier (UP Z\\<^sub>p)\"\n  shows \"poly_inc (f \\<oplus>\\<^bsub>UP Z\\<^sub>p\\<^esub> g) = poly_inc f \\<oplus>\\<^bsub>UP Q\\<^sub>p\\<^esub> poly_inc g\"\nproof\n  fix n \n  have 0: \"poly_inc (f \\<oplus>\\<^bsub>UP Z\\<^sub>p\\<^esub> g) n = \\<iota> (f n \\<oplus>\\<^bsub>Z\\<^sub>p\\<^esub> g n)\"\n    unfolding poly_inc_def using assms by auto\n  have 1: \"(poly_inc f \\<oplus>\\<^bsub>UP Q\\<^sub>p\\<^esub> poly_inc g) n = poly_inc f n \\<oplus> poly_inc g n\"\n    by(rule cfs_add, rule poly_inc_closed, rule assms, rule poly_inc_closed, rule assms)\n  show \"poly_inc (f \\<oplus>\\<^bsub>UP Z\\<^sub>p\\<^esub> g) n = (poly_inc f \\<oplus>\\<^bsub>UP Q\\<^sub>p\\<^esub> poly_inc g) n\"\n    unfolding 0 1 unfolding poly_inc_def \n    apply(rule inc_of_sum)\n    using assms apply (simp add: Zp.cfs_closed; fail)\n        using assms by (simp add: Zp.cfs_closed)\nqed\n\nlemma poly_inc_monom:\n  assumes \"a \\<in> carrier Z\\<^sub>p\"\n  shows \"poly_inc (monom (UP Z\\<^sub>p) a m) = monom (UP Q\\<^sub>p) (\\<iota> a) m\"\nproof fix n \n  show \"poly_inc (monom (UP Z\\<^sub>p) a m) n = monom (UP Q\\<^sub>p) (\\<iota> a) m n\"\n    apply(cases \"m = n\")\n    using assms cfs_monom[of \"\\<iota> a\"] Zp.cfs_monom[of a] unfolding poly_inc_def \n     apply (simp add: inc_closed; fail)\n    using assms cfs_monom[of \"\\<iota> a\"] Zp.cfs_monom[of a] unfolding poly_inc_def \n    by (metis Qp.nat_mult_zero Zp_nat_inc_zero inc_closed inc_of_nat)\nqed\n\nlemma poly_inc_times: \n  assumes \"f \\<in> carrier (UP Z\\<^sub>p)\"\n  assumes \"g \\<in> carrier (UP Z\\<^sub>p)\"\n  shows \"poly_inc (f \\<otimes>\\<^bsub>UP Z\\<^sub>p\\<^esub> g) = poly_inc f \\<otimes>\\<^bsub>UP Q\\<^sub>p\\<^esub> poly_inc g\"\n  apply(rule UP_ring.poly_induct3[of Z\\<^sub>p])\n  apply (simp add: Zp.is_UP_ring; fail)\n  using assms apply blast\nproof- \n  fix p q \n  assume A: \"q \\<in> carrier (UP Z\\<^sub>p)\"  \"p \\<in> carrier (UP Z\\<^sub>p)\"\n            \"poly_inc (f \\<otimes>\\<^bsub>UP Z\\<^sub>p\\<^esub> p) = poly_inc f \\<otimes>\\<^bsub>UP Q\\<^sub>p\\<^esub> poly_inc p\"\n            \"poly_inc (f \\<otimes>\\<^bsub>UP Z\\<^sub>p\\<^esub> q) = poly_inc f \\<otimes>\\<^bsub>UP Q\\<^sub>p\\<^esub> poly_inc q\"\n  have 0: \"(f \\<otimes>\\<^bsub>UP Z\\<^sub>p\\<^esub> (p \\<oplus>\\<^bsub>UP Z\\<^sub>p\\<^esub> q)) = (f \\<otimes>\\<^bsub>UP Z\\<^sub>p\\<^esub> p) \\<oplus>\\<^bsub>UP Z\\<^sub>p\\<^esub> (f \\<otimes>\\<^bsub>UP Z\\<^sub>p\\<^esub> q)\"\n    using assms(1) A \n    by (simp add: Zp.P.r_distr)\n  have 1: \"poly_inc (p \\<oplus>\\<^bsub>UP Z\\<^sub>p\\<^esub> q) = poly_inc p \\<oplus>\\<^bsub>UP Q\\<^sub>p\\<^esub> poly_inc q\"\n    by(rule poly_inc_plus, rule A, rule A)\n  show \"poly_inc (f \\<otimes>\\<^bsub>UP Z\\<^sub>p\\<^esub> (p \\<oplus>\\<^bsub>UP Z\\<^sub>p\\<^esub> q)) = poly_inc f \\<otimes>\\<^bsub>UP Q\\<^sub>p\\<^esub> poly_inc (p \\<oplus>\\<^bsub>UP Z\\<^sub>p\\<^esub> q)\"\n    unfolding 0 1 using A poly_inc_closed poly_inc_plus \n    by (simp add: UPQ.P.r_distr assms(1))\nnext\n  fix a fix n::nat\n  assume A: \"a \\<in> carrier Z\\<^sub>p\"\n  show \"poly_inc (f \\<otimes>\\<^bsub>UP Z\\<^sub>p\\<^esub> monom (UP Z\\<^sub>p) a n) =\n           poly_inc f \\<otimes>\\<^bsub>UP Q\\<^sub>p\\<^esub> poly_inc (monom (UP Z\\<^sub>p) a n)\"\n  proof\n    fix m \n    show \"poly_inc (f \\<otimes>\\<^bsub>UP Z\\<^sub>p\\<^esub> monom (UP Z\\<^sub>p) a n) m =\n         (poly_inc f \\<otimes>\\<^bsub>UP Q\\<^sub>p\\<^esub> poly_inc (monom (UP Z\\<^sub>p) a n)) m\"\n    proof(cases \"m < n\")\n      case True\n      have T0: \"(f \\<otimes>\\<^bsub>UP Z\\<^sub>p\\<^esub> monom (UP Z\\<^sub>p) a n) m = \\<zero>\\<^bsub>Z\\<^sub>p\\<^esub>\"\n        using True Zp.cfs_monom_mult[of f a m n] A assms \n        by blast\n      have T1: \"poly_inc (monom (UP Z\\<^sub>p) a n) =  (monom (UP Q\\<^sub>p) (\\<iota> a) n)\"\n        by(rule poly_inc_monom , rule A)\n      show ?thesis\n        unfolding T0 T1 using True \n        by (metis A Q\\<^sub>p_def T0 UPQ.cfs_monom_mult Zp_def assms(1) inc_closed padic_fields.to_Zp_zero padic_fields_axioms poly_inc_closed poly_inc_def to_Zp_inc zero_in_val_ring)\n    next\n      case False\n      then have F0: \"m \\<ge> n\"\n        using False by simp \n      have F1: \"(f \\<otimes>\\<^bsub>UP Z\\<^sub>p\\<^esub> monom (UP Z\\<^sub>p) a n) m = a \\<otimes>\\<^bsub>Z\\<^sub>p\\<^esub> f (m - n)\"\n        using Zp.cfs_monom_mult_l' F0 A assms by simp \n      have F2: \"poly_inc (monom (UP Z\\<^sub>p) a n)  = monom (UP Q\\<^sub>p) (\\<iota> a) n \"\n        by(rule poly_inc_monom, rule A)\n      have F3: \"(poly_inc f \\<otimes>\\<^bsub>UP Q\\<^sub>p\\<^esub> poly_inc (monom (UP Z\\<^sub>p) a n)) m \n                = (\\<iota> a) \\<otimes> (poly_inc f (m -n))\"\n        using UPQ.cfs_monom_mult_l' F0 A assms poly_inc_closed \n        by (simp add: F2 inc_closed)\n      show ?thesis \n        unfolding F3 unfolding poly_inc_def F1 \n        apply(rule inc_of_prod, rule A)\n        using assms Zp.cfs_closed by blast\n    qed\n  qed\nqed\n      \nlemma poly_inc_one:\n\"poly_inc (\\<one>\\<^bsub>UP Z\\<^sub>p\\<^esub>) = \\<one>\\<^bsub>UP Q\\<^sub>p\\<^esub>\"\napply(rule ext)\n  unfolding poly_inc_def \n  using inc_of_one inc_of_zero  \n  by simp\n\nlemma poly_inc_zero:\n\"poly_inc (\\<zero>\\<^bsub>UP Z\\<^sub>p\\<^esub>) = \\<zero>\\<^bsub>UP Q\\<^sub>p\\<^esub>\"\napply(rule ext)\n  unfolding poly_inc_def \n  using inc_of_one inc_of_zero  \n  by simp\n\nlemma poly_inc_hom: \n\"poly_inc \\<in> ring_hom (UP Z\\<^sub>p) (UP Q\\<^sub>p)\"\n  apply(rule ring_hom_memI)\n     apply(rule poly_inc_closed, blast)\n    apply(rule poly_inc_times, blast, blast)\n   apply(rule poly_inc_plus, blast, blast)\n  by(rule poly_inc_one)\n\nlemma poly_inc_as_poly_lift_hom:\n  assumes \"f \\<in> carrier (UP Z\\<^sub>p)\"\n  shows \"poly_inc f = poly_lift_hom Z\\<^sub>p Q\\<^sub>p \\<iota> f\"\n  apply(rule ext)\n  unfolding poly_inc_def \n  using Zp.poly_lift_hom_cf[of Q\\<^sub>p \\<iota> f] assms UPQ.R_cring local.inc_is_hom\n  by blast\n\nlemma poly_inc_eval:\n  assumes \"g \\<in> carrier (UP Z\\<^sub>p)\"\n  assumes \"a \\<in> carrier Z\\<^sub>p\"\n  shows \"to_function Q\\<^sub>p (poly_inc g) (\\<iota> a) = \\<iota> (to_function Z\\<^sub>p g a)\"\nproof- \n  have 0: \"poly_inc g = poly_lift_hom Z\\<^sub>p Q\\<^sub>p \\<iota> g\"\n    using assms poly_inc_as_poly_lift_hom[of g] by blast \n  have 1: \"to_function Q\\<^sub>p (poly_lift_hom Z\\<^sub>p Q\\<^sub>p \\<iota> g) (\\<iota> a) = \\<iota> (to_function Z\\<^sub>p g a)\"\n    using Zp.poly_lift_hom_eval[of Q\\<^sub>p \\<iota> g a] assms inc_is_hom\n    unfolding to_fun_def Zp.to_fun_def \n    using UPQ.R_cring by blast\n  show ?thesis unfolding 0 1 \n    by blast \nqed\n\nlemma val_ring_poly_eval:\n  assumes \"f \\<in> carrier (UP Q\\<^sub>p)\"\n  assumes \"\\<And> i. f i \\<in> \\<O>\\<^sub>p\"\n  shows \"\\<And>x. x \\<in> \\<O>\\<^sub>p \\<Longrightarrow> f \\<bullet> x \\<in> \\<O>\\<^sub>p\"\n  apply(rule positive_gauss_norm_eval, rule assms)\n  apply(rule val_ring_cfs_imp_nonneg_gauss_norm)\n  using assms by auto \n\nlemma Zp_res_of_pow:\n  assumes \"a \\<in> carrier Z\\<^sub>p\"\n  assumes \"b \\<in> carrier Z\\<^sub>p\"\n  assumes \"a n = b n\"\n  shows \"(a[^]\\<^bsub>Z\\<^sub>p\\<^esub>(k::nat)) n = (b[^]\\<^bsub>Z\\<^sub>p\\<^esub>(k::nat)) n\"\n  apply(induction k)\n  using assms Group.nat_pow_0 to_Zp_one apply metis \n  using Zp.geometric_series_id[of a b] Zp_residue_mult_zero(1) assms(1) assms(2) assms(3)\n    pow_closed res_diff_zero_fact'' res_diff_zero_fact(1) by metis \n\nlemma to_Zp_nat_pow:\n  assumes \"a \\<in> \\<O>\\<^sub>p\"\n  shows \"to_Zp (a[^](n::nat)) = (to_Zp a)[^]\\<^bsub>Z\\<^sub>p\\<^esub>(n::nat)\"\n  apply(induction n)\n  using assms Group.nat_pow_0 to_Zp_one apply metis\n  using assms to_Zp_mult[of a] Qp.m_comm Qp.nat_pow_Suc val_ring_memE pow_suc to_Zp_closed val_ring_nat_pow_closed \n  by metis \n\nlemma  to_Zp_res_of_pow:\n  assumes \"a \\<in> \\<O>\\<^sub>p\"\n  assumes \"b \\<in> \\<O>\\<^sub>p\"\n  assumes \"to_Zp a n = to_Zp b n\"\n  shows \"to_Zp (a[^](k::nat)) n = to_Zp (b[^](k::nat)) n\"\n  using assms val_ring_memE Zp_res_of_pow to_Zp_closed to_Zp_nat_pow by presburger\n\nlemma poly_eval_cong:\n  assumes \"g \\<in> carrier (UP Q\\<^sub>p)\"\n  assumes \"\\<And>i. g i \\<in> \\<O>\\<^sub>p\"\n  assumes \"a \\<in> \\<O>\\<^sub>p\"\n  assumes \"b \\<in> \\<O>\\<^sub>p\"\n  assumes \"to_Zp a k = to_Zp b k\"\n  shows \"to_Zp (g \\<bullet> a) k = to_Zp (g \\<bullet> b) k\"\nproof-\n  have \"(\\<forall>i. g i \\<in> \\<O>\\<^sub>p) \\<longrightarrow> to_Zp (g \\<bullet> a) k = to_Zp (g \\<bullet> b) k\"\n  proof(rule UPQ.poly_induct[of g])\n    show \" g \\<in> carrier (UP Q\\<^sub>p)\"\n      using assms by blast\n    show \"\\<And>p. p \\<in> carrier (UP Q\\<^sub>p) \\<Longrightarrow> deg Q\\<^sub>p p = 0 \\<Longrightarrow> (\\<forall>i. p i \\<in> \\<O>\\<^sub>p) \\<longrightarrow> to_Zp (p \\<bullet> a) k = to_Zp (p \\<bullet> b) k\"\n    proof fix p assume A: \"p \\<in> carrier (UP Q\\<^sub>p)\" \"deg Q\\<^sub>p p = 0\" \"\\<forall>i. p i \\<in> \\<O>\\<^sub>p\"\n      obtain c where c_def: \"c \\<in> carrier Q\\<^sub>p \\<and> p = up_ring.monom (UP Q\\<^sub>p) c 0\"\n        using A \n        by (metis UPQ.zcf_degree_zero UPQ.cfs_closed UPQ.trms_of_deg_leq_0 UPQ.trms_of_deg_leq_degree_f)\n      have p_eq: \"p = up_ring.monom (UP Q\\<^sub>p) c 0\"\n        using c_def by blast \n      have p_cfs: \"p 0 = c\"\n        unfolding p_eq using c_def UP_ring.cfs_monom[of Q\\<^sub>p c 0 0] UPQ.P_is_UP_ring by presburger\n      have c_closed: \"c \\<in> \\<O>\\<^sub>p\"\n        using p_cfs A(3) by blast\n      have 0: \"(p \\<bullet> a) = c\"\n        unfolding p_eq using c_def assms by (meson UPQ.to_fun_const val_ring_memE(2))\n      have 1: \"(p \\<bullet> b) = c\"\n        unfolding p_eq using c_def assms UPQ.to_fun_const val_ring_memE(2) by presburger\n      show \" to_Zp (p \\<bullet> a) k = to_Zp (p \\<bullet> b) k\"\n        unfolding 0 1 by blast \n    qed\n    show \"\\<And>p. (\\<And>q. q \\<in> carrier (UP Q\\<^sub>p) \\<Longrightarrow> deg Q\\<^sub>p q < deg Q\\<^sub>p p \\<Longrightarrow> (\\<forall>i. q i \\<in> \\<O>\\<^sub>p) \\<longrightarrow> to_Zp (q \\<bullet> a) k = to_Zp (q \\<bullet> b) k) \\<Longrightarrow>\n         p \\<in> carrier (UP Q\\<^sub>p) \\<Longrightarrow> 0 < deg Q\\<^sub>p p \\<Longrightarrow> (\\<forall>i. p i \\<in> \\<O>\\<^sub>p) \\<longrightarrow> to_Zp (p \\<bullet> a) k = to_Zp (p \\<bullet> b) k\"\n    proof \n      fix p assume A: \"(\\<And>q. q \\<in> carrier (UP Q\\<^sub>p) \\<Longrightarrow> deg Q\\<^sub>p q < deg Q\\<^sub>p p \\<Longrightarrow> (\\<forall>i. q i \\<in> \\<O>\\<^sub>p) \\<longrightarrow> to_Zp (q \\<bullet> a) k = to_Zp (q \\<bullet> b) k)\"\n                      \"p \\<in> carrier (UP Q\\<^sub>p)\" \"0 < deg Q\\<^sub>p p \" \" \\<forall>i. p i \\<in> \\<O>\\<^sub>p\"\n      obtain q where q_def: \"q \\<in> carrier (UP Q\\<^sub>p) \\<and> deg Q\\<^sub>p q < deg Q\\<^sub>p p \\<and> p = UPQ.ltrm p \\<oplus>\\<^bsub>UP Q\\<^sub>p\\<^esub>q\"\n        by (metis A(2) A(3) UPQ.ltrm_closed UPQ.ltrm_decomp UPQ.UP_a_comm)\n      have 0: \"\\<And>i.  p i = q i \\<oplus> UPQ.ltrm p i\"\n        using q_def A \n        by (metis Qp.a_ac(2) UPQ.ltrm_closed UPQ.UP_car_memE(1) UPQ.cfs_add)\n      have 1: \"\\<forall>i. q i \\<in> \\<O>\\<^sub>p\"\n      proof fix i \n        show \"q i \\<in> \\<O>\\<^sub>p\"\n          apply(cases \"i < deg Q\\<^sub>p p\")\n          using 0[of i] A(4) A(2) q_def \n          using UPQ.ltrm_closed UPQ.P.a_ac(2) UPQ.trunc_cfs UPQ.trunc_closed UPQ.trunc_simps(1) \n           apply (metis Qp.r_zero UPQ.ltrm_cfs UPQ.cfs_closed UPQ.deg_leE)\n          using q_def \n          by (metis (no_types, opaque_lifting) A(2) A(4) UPQ.P.add.m_closed UPQ.coeff_of_sum_diff_degree0 UPQ.deg_leE UPQ.equal_deg_sum UPQ.equal_deg_sum' \\<open>\\<And>thesis. (\\<And>q. q \\<in> carrier (UP Q\\<^sub>p) \\<and> deg Q\\<^sub>p q < deg Q\\<^sub>p p \\<and> p = up_ring.monom (UP Q\\<^sub>p) (p (deg Q\\<^sub>p p)) (deg Q\\<^sub>p p) \\<oplus>\\<^bsub>UP Q\\<^sub>p\\<^esub> q \\<Longrightarrow> thesis) \\<Longrightarrow> thesis\\<close> lessI linorder_neqE_nat)\n      qed\n      have 2: \"UPQ.lcf p \\<in> \\<O>\\<^sub>p\"\n        using A(4) by blast \n      have 3: \"UPQ.ltrm p \\<bullet> a = UPQ.lcf p \\<otimes> a[^] deg Q\\<^sub>p p\"\n        apply(rule UP_cring.to_fun_monom) unfolding UP_cring_def \n        using Qp.cring apply blast\n        using A UPQ.lcf_closed apply blast\n        using assms val_ring_memE(2) by blast\n      have 4: \"UPQ.ltrm p \\<bullet> b = UPQ.lcf p \\<otimes> b[^] deg Q\\<^sub>p p\"\n        apply(rule UP_cring.to_fun_monom) unfolding UP_cring_def \n        using Qp.cring apply blast\n        using A UPQ.lcf_closed apply blast\n        using assms val_ring_memE(2) by blast\n      have p_eq: \"p = q \\<oplus>\\<^bsub>UP Q\\<^sub>p\\<^esub> UPQ.ltrm p\"\n        using q_def by (metis A(2) UPQ.ltrm_closed UPQ.UP_a_comm)\n      have 5: \"p \\<bullet> a = q \\<bullet> a \\<oplus>  UPQ.lcf p \\<otimes> a[^] deg Q\\<^sub>p p\"\n        using assms val_ring_memE(2) p_eq q_def UPQ.to_fun_plus[of q \"UPQ.ltrm p\" a] \n        by (metis \"3\" A(2) UPQ.ltrm_closed UPQ.to_fun_plus)\n      have 6: \"p \\<bullet> b = q \\<bullet> b \\<oplus>  UPQ.lcf p \\<otimes> b[^] deg Q\\<^sub>p p\"\n        using assms val_ring_memE(2) p_eq q_def UPQ.to_fun_plus[of q \"UPQ.ltrm p\" a] \n        by (metis \"4\" A(2) UPQ.ltrm_closed UPQ.to_fun_plus)\n      have 7: \"UPQ.lcf p \\<otimes> b[^] deg Q\\<^sub>p p \\<in> \\<O>\\<^sub>p\"\n        apply(rule val_ring_times_closed)\n        using \"2\" apply linarith\n        by(rule val_ring_nat_pow_closed, rule assms)\n      have 8: \"UPQ.lcf p \\<otimes> a[^] deg Q\\<^sub>p p \\<in> \\<O>\\<^sub>p\"\n        apply(rule val_ring_times_closed)\n        using \"2\" apply linarith\n        by(rule val_ring_nat_pow_closed, rule assms)\n      have 9: \"q \\<bullet> a \\<in> \\<O>\\<^sub>p\"\n        using q_def 1 assms(3) val_ring_poly_eval by blast\n      have 10: \"q \\<bullet> b \\<in> \\<O>\\<^sub>p\"\n        using q_def 1 assms(4) val_ring_poly_eval by blast \n      have 11: \"to_Zp (p \\<bullet> a) = to_Zp (q \\<bullet> a) \\<oplus>\\<^bsub>Z\\<^sub>p\\<^esub> to_Zp (UPQ.ltrm p \\<bullet> a)\"\n        using 5 8 9 to_Zp_add 3 by presburger\n      have 12: \"to_Zp (p \\<bullet> b) = to_Zp (q \\<bullet> b) \\<oplus>\\<^bsub>Z\\<^sub>p\\<^esub> to_Zp (UPQ.ltrm p \\<bullet> b)\"\n        using 6 10 7 to_Zp_add 4  by presburger\n      have 13: \"to_Zp (p \\<bullet> a) k = to_Zp (q \\<bullet> a) k \\<oplus>\\<^bsub>Zp_res_ring k\\<^esub> to_Zp (UPQ.ltrm p \\<bullet> a) k\"\n        unfolding 11 using residue_of_sum by blast\n      have 14: \"to_Zp (p \\<bullet> b) k = to_Zp (q \\<bullet> b) k \\<oplus>\\<^bsub>Zp_res_ring k\\<^esub> to_Zp (UPQ.ltrm p \\<bullet> b) k\"\n        unfolding 12 using residue_of_sum by blast\n      have 15: \"to_Zp (UPQ.ltrm p \\<bullet> a) k = to_Zp (UPQ.ltrm p \\<bullet> b) k\"\n      proof(cases \"k = 0\")\n        case True\n        have T0: \"to_Zp (UPQ.ltrm p \\<bullet> a) \\<in> carrier Z\\<^sub>p\"\n          unfolding 3 using 8  to_Zp_closed val_ring_memE(2) by blast\n        have T1: \"to_Zp (UPQ.ltrm p \\<bullet> b) \\<in> carrier Z\\<^sub>p\"\n          unfolding 4 using 7 to_Zp_closed val_ring_memE(2) by blast\n        show ?thesis unfolding True using T0 T1 padic_integers.p_res_ring_0 \n          by (metis p_res_ring_0' residues_closed)       \n      next\n        case False\n        have k_pos: \"k > 0\"\n          using False by presburger \n        have 150: \"to_Zp (p (deg Q\\<^sub>p p) \\<otimes> a [^] deg Q\\<^sub>p p) = to_Zp (p (deg Q\\<^sub>p p)) \\<otimes>\\<^bsub>Z\\<^sub>p\\<^esub> to_Zp( a [^] deg Q\\<^sub>p p)\"\n         apply(rule to_Zp_mult) \n          using \"2\" apply blast\n         by(rule val_ring_nat_pow_closed, rule assms)\n        have 151: \"to_Zp (p (deg Q\\<^sub>p p) \\<otimes> b [^] deg Q\\<^sub>p p) = to_Zp (p (deg Q\\<^sub>p p)) \\<otimes>\\<^bsub>Z\\<^sub>p\\<^esub> to_Zp( b [^] deg Q\\<^sub>p p)\"\n         apply(rule to_Zp_mult) \n          using \"2\" apply blast\n         by(rule val_ring_nat_pow_closed, rule assms)\n       have 152: \"to_Zp (p (deg Q\\<^sub>p p) \\<otimes> a [^] deg Q\\<^sub>p p) k = to_Zp (p (deg Q\\<^sub>p p)) k \\<otimes>\\<^bsub>Zp_res_ring k\\<^esub> to_Zp( a [^] deg Q\\<^sub>p p) k\"\n         unfolding 150 using residue_of_prod by blast\n       have 153: \"to_Zp (p (deg Q\\<^sub>p p) \\<otimes> b [^] deg Q\\<^sub>p p) k = to_Zp (p (deg Q\\<^sub>p p)) k \\<otimes>\\<^bsub>Zp_res_ring k\\<^esub> to_Zp( b [^] deg Q\\<^sub>p p) k\"\n         unfolding 151 using residue_of_prod by blast\n       have 154: \"to_Zp( a [^] deg Q\\<^sub>p p) k = to_Zp a k [^]\\<^bsub>Zp_res_ring k\\<^esub> deg Q\\<^sub>p p\"\n       proof- \n       have 01: \"\\<And>m::nat. to_Zp (a[^]m) k = to_Zp a k [^]\\<^bsub>Zp_res_ring k\\<^esub> m\"\n       proof-\n         fix m::nat show \"to_Zp (a [^] m) k = to_Zp a k [^]\\<^bsub>Zp_res_ring k\\<^esub> m\"\n       proof-\n         have 00: \"to_Zp (a[^]m) = to_Zp a [^]\\<^bsub>Z\\<^sub>p\\<^esub> m\"\n         using assms to_Zp_nat_pow[of a \"m\"] by blast\n       have 01: \"to_Zp a \\<in> carrier Z\\<^sub>p\"\n         using assms to_Zp_closed val_ring_memE(2) by blast \n       have 02: \"to_Zp a k \\<in> carrier (Zp_res_ring k)\"\n         using 01 residues_closed by blast\n       have 03: \"cring (Zp_res_ring k)\"\n         using k_pos padic_integers.R_cring padic_integers_axioms by blast\n       have 01: \"(to_Zp a [^]\\<^bsub>Z\\<^sub>p\\<^esub> m) k = (to_Zp a) k [^]\\<^bsub>Zp_res_ring k\\<^esub> m\"\n         apply(induction m)\n         using 01 02 apply (metis Group.nat_pow_0 k_pos residue_of_one(1))\n         using residue_of_prod[of \"to_Zp a [^]\\<^bsub>Z\\<^sub>p\\<^esub> m\" \"to_Zp a\" k] 01 02 03 \n       proof -\n         fix ma :: nat\n         assume \"(to_Zp a [^]\\<^bsub>Z\\<^sub>p\\<^esub> ma) k = to_Zp a k [^]\\<^bsub>Zp_res_ring k\\<^esub> ma\"\n         then show \"(to_Zp a [^]\\<^bsub>Z\\<^sub>p\\<^esub> Suc ma) k = to_Zp a k [^]\\<^bsub>Zp_res_ring k\\<^esub> Suc ma\"\n           by (metis (no_types) Group.nat_pow_Suc residue_of_prod)\n       qed\n       show ?thesis unfolding 00 01 by blast \n       qed\n       qed\n       thus ?thesis by blast       \n       qed\n       have 155: \"to_Zp( b [^] deg Q\\<^sub>p p) k = to_Zp b k [^]\\<^bsub>Zp_res_ring k\\<^esub> deg Q\\<^sub>p p\"\n         using assms by (metis \"154\" to_Zp_res_of_pow)\n       show ?thesis\n         unfolding 3 4 152 153 154 155 assms by blast \n     qed\n     show \"to_Zp (p \\<bullet> a) k = to_Zp (p \\<bullet> b) k\"\n       unfolding 13 14 15 using A 1 q_def by presburger\n   qed\n  qed\n  thus ?thesis using assms by blast \nqed\n\nlemma to_Zp_poly_eval:\n  assumes \"g \\<in> carrier Q\\<^sub>p_x\"\n  assumes \"gauss_norm g \\<ge> 0\"\n  assumes \"a \\<in> \\<O>\\<^sub>p\"\n  shows \"to_Zp (to_function Q\\<^sub>p g a) = to_function Z\\<^sub>p (to_Zp_poly g) (to_Zp a)\"\nproof- \n  obtain h where h_def: \"h = to_Zp_poly g\"\n    by blast \n  obtain b where b_def: \"b = to_Zp a\"\n    by blast \n  have h_poly_inc: \"poly_inc h = g\"\n    unfolding h_def using assms \n    by (simp add: poly_inc_inverse_left)\n  have b_inc: \"\\<iota> b = a\"\n    unfolding b_def using assms \n    by (simp add: to_Zp_inc)\n  have h_closed: \"h \\<in> carrier (UP Z\\<^sub>p)\"\n    unfolding h_def using assms \n    by (simp add: to_Zp_poly_closed)\n  have b_closed: \"b \\<in> carrier Z\\<^sub>p\"\n    unfolding b_def using assms \n    by (simp add: to_Zp_closed val_ring_memE)\n  have 0: \"to_function Q\\<^sub>p (poly_inc h) (\\<iota> b) = \\<iota> (to_function Z\\<^sub>p h b)\"\n    apply(rule poly_inc_eval)\n    using h_def assms apply (simp add: to_Zp_poly_closed; fail)\n    unfolding b_def using assms \n    by (simp add: to_Zp_closed val_ring_memE)\n  have 1: \"to_Zp (to_function Q\\<^sub>p (poly_inc h) (\\<iota> b)) = to_function Z\\<^sub>p h b\"\n    unfolding 0 \n    using h_closed b_closed Zp.to_fun_closed Zp.to_fun_def inc_to_Zp by auto\n  show ?thesis \n    using 1 unfolding h_poly_inc b_inc \n    unfolding h_def b_def by blast \nqed\n\nlemma poly_eval_equal_val:\n  assumes \"g \\<in> carrier (UP Q\\<^sub>p)\"\n  assumes \"\\<And>x. g x \\<in> \\<O>\\<^sub>p\"\n  assumes \"a \\<in> \\<O>\\<^sub>p\"\n  assumes \"b \\<in> \\<O>\\<^sub>p\"\n  assumes \"val (g \\<bullet> a) < eint n\"\n  assumes \"to_Zp a n = to_Zp b n\"\n  shows \"val (g \\<bullet> b) = val (g \\<bullet> a)\"\nproof-\n  have \"(\\<forall>x. g x \\<in> \\<O>\\<^sub>p) \\<longrightarrow> to_Zp (g \\<bullet> b) n = to_Zp (g \\<bullet> a) n\"\n  proof(rule poly_induct[of g])\n    show \"g \\<in> carrier (UP Q\\<^sub>p)\"\n      by (simp add: assms(1))\n    show \"\\<And>p. p \\<in> carrier (UP Q\\<^sub>p) \\<Longrightarrow> deg Q\\<^sub>p p = 0 \\<Longrightarrow> (\\<forall>x. p x \\<in> \\<O>\\<^sub>p) \\<longrightarrow> to_Zp (p \\<bullet> b) n = to_Zp (p \\<bullet> a) n\"\n    proof fix p assume A: \"p \\<in> carrier (UP Q\\<^sub>p)\" \" deg Q\\<^sub>p p = 0 \" \"\\<forall>x. p x \\<in> \\<O>\\<^sub>p \"\n      show \"to_Zp (p \\<bullet> b) n = to_Zp (p \\<bullet> a) n\"\n        using A  by (metis val_ring_memE UPQ.to_fun_ctrm UPQ.trms_of_deg_leq_0 UPQ.trms_of_deg_leq_degree_f assms(3) assms(4))\n    qed\n    show \"\\<And>p. (\\<And>q. q \\<in> carrier (UP Q\\<^sub>p) \\<Longrightarrow> deg Q\\<^sub>p q < deg Q\\<^sub>p p \\<Longrightarrow> (\\<forall>x. q x \\<in> \\<O>\\<^sub>p) \\<longrightarrow> to_Zp (q \\<bullet> b) n = to_Zp (q \\<bullet> a) n) \\<Longrightarrow>\n         p \\<in> carrier (UP Q\\<^sub>p) \\<Longrightarrow> 0 < deg Q\\<^sub>p p \\<Longrightarrow> (\\<forall>x. p x \\<in> \\<O>\\<^sub>p) \\<longrightarrow> to_Zp (p \\<bullet> b) n = to_Zp (p \\<bullet> a) n\"\n    proof fix p assume IH: \"(\\<And>q. q \\<in> carrier (UP Q\\<^sub>p) \\<Longrightarrow> deg Q\\<^sub>p q < deg Q\\<^sub>p p \\<Longrightarrow> (\\<forall>x. q x \\<in> \\<O>\\<^sub>p) \\<longrightarrow> to_Zp (q \\<bullet> b) n = to_Zp (q \\<bullet> a) n)\"\n      assume A: \"p \\<in> carrier (UP Q\\<^sub>p)\" \"0 < deg Q\\<^sub>p p\" \"\\<forall>x. p x \\<in> \\<O>\\<^sub>p\"\n      show \"to_Zp (p \\<bullet> b) n = to_Zp (p \\<bullet> a) n\"\n      proof-\n        obtain q where q_def: \"q \\<in> carrier (UP Q\\<^sub>p) \\<and> deg Q\\<^sub>p q < deg Q\\<^sub>p p \\<and>\n                      p = q \\<oplus>\\<^bsub>UP Q\\<^sub>p\\<^esub> ltrm p\"\n          using A  by (meson UPQ.ltrm_decomp)\n        have p_eq: \"p = q \\<oplus>\\<^bsub>UP Q\\<^sub>p\\<^esub> ltrm p\"\n          using q_def by blast \n        have \"\\<forall>x. q x \\<in> \\<O>\\<^sub>p\" proof fix x\n          have px: \"p x = (q \\<oplus>\\<^bsub>UP Q\\<^sub>p\\<^esub> ltrm p) x\"\n            using p_eq by simp \n          show \"q x \\<in> \\<O>\\<^sub>p\"\n          proof(cases \"x \\<le> deg Q\\<^sub>p q\")\n            case True\n            then have \"p x = q x\"           \n              unfolding px using q_def A \n              by (smt UPQ.ltrm_closed UPQ.P.add.right_cancel UPQ.coeff_of_sum_diff_degree0 UPQ.deg_ltrm UPQ.trunc_cfs UPQ.trunc_closed UPQ.trunc_simps(1) less_eq_Suc_le nat_neq_iff not_less_eq_eq)\n            then show ?thesis using A \n              by blast\n          next\n            case False\n            then show ?thesis \n              using q_def UPQ.deg_eqI eq_imp_le nat_le_linear zero_in_val_ring\n              by (metis (no_types, lifting) UPQ.coeff_simp UPQ.deg_belowI)\n          qed\n        qed\n        then have 0: \" to_Zp (q \\<bullet> b) n = to_Zp (q \\<bullet> a) n\"\n          using IH q_def by blast\n        have 1: \"to_Zp (ltrm p \\<bullet> b) n = to_Zp (ltrm p \\<bullet> a) n\"\n        proof-\n          have 10: \"(ltrm p \\<bullet> b) = (p (deg Q\\<^sub>p p)) \\<otimes> b[^] (deg Q\\<^sub>p p)\"\n            using assms A  by (meson val_ring_memE UPQ.to_fun_monom)\n          have 11: \"(ltrm p \\<bullet> a) = (p (deg Q\\<^sub>p p)) \\<otimes> a[^] (deg Q\\<^sub>p p)\"\n            using assms A by (meson val_ring_memE UPQ.to_fun_monom)\n          have 12: \"to_Zp (b[^] (deg Q\\<^sub>p p)) n = to_Zp (a[^] (deg Q\\<^sub>p p)) n\"\n            using to_Zp_res_of_pow assms by metis\n          have 13: \"p (deg Q\\<^sub>p p) \\<in> \\<O>\\<^sub>p\"\n            using A(3) by blast\n          have 14: \"b[^] (deg Q\\<^sub>p p) \\<in> \\<O>\\<^sub>p\"\n            using assms(4) val_ring_nat_pow_closed by blast\n          have 15: \"a[^] (deg Q\\<^sub>p p) \\<in> \\<O>\\<^sub>p\"\n            using assms(3) val_ring_nat_pow_closed by blast\n          have 16: \"(ltrm p \\<bullet> b) \\<in> \\<O>\\<^sub>p\"\n            by (simp add: \"10\" \"13\" \"14\" val_ring_times_closed)\n          have 17: \"to_Zp (ltrm p \\<bullet> b) n = to_Zp (p (deg Q\\<^sub>p p)) n \\<otimes>\\<^bsub>Zp_res_ring n\\<^esub> to_Zp (b[^] (deg Q\\<^sub>p p)) n\"\n            using 10 13 14 15 16 assms residue_of_prod to_Zp_mult by presburger \n          have 18: \"(ltrm p \\<bullet> a) \\<in> \\<O>\\<^sub>p\"\n            by (simp add: \"11\" \"15\" A(3) val_ring_times_closed)\n          have 19: \"to_Zp (ltrm p \\<bullet> a) n = to_Zp (p (deg Q\\<^sub>p p)) n \\<otimes>\\<^bsub>Zp_res_ring n\\<^esub> to_Zp (a[^] (deg Q\\<^sub>p p)) n\"\n            using 10 13 14 15 16 17 18 assms residue_of_prod to_Zp_mult 11  by presburger\n          show ?thesis using 12 17 19 by presburger\n        qed\n        have 2: \"p (deg Q\\<^sub>p p) \\<in> \\<O>\\<^sub>p\"\n          using A(3) by blast\n        have 3: \"(ltrm p \\<bullet> b) \\<in> \\<O>\\<^sub>p\"\n          using 2 assms  \n          by (metis A(1) Q\\<^sub>p_def val_ring_memE val_ring_memE UPQ.ltrm_closed Zp_def \\<iota>_def \n              gauss_norm_monom padic_fields.positive_gauss_norm_eval padic_fields_axioms)\n        have 4: \"(ltrm p \\<bullet> a) \\<in> \\<O>\\<^sub>p\"\n          using 2 assms \n          by (metis A(1) Q\\<^sub>p_def val_ring_memE val_ring_memE UPQ.ltrm_closed Zp_def \\<iota>_def\n              gauss_norm_monom padic_fields.positive_gauss_norm_eval padic_fields_axioms)\n        have 5: \"(q \\<bullet> b) \\<in> \\<O>\\<^sub>p\"\n          using  \\<open>\\<forall>x. q x \\<in> \\<O>\\<^sub>p\\<close> assms(4) q_def     \n          by (metis gauss_norm_coeff_norm positive_gauss_norm_eval val_ring_memE(1))\n        have 6: \"(q \\<bullet> a) \\<in> \\<O>\\<^sub>p\"\n          using  \\<open>\\<forall>x. q x \\<in> \\<O>\\<^sub>p\\<close> assms(3) q_def     \n          by (metis gauss_norm_coeff_norm positive_gauss_norm_eval val_ring_memE(1))\n        have 7: \"to_Zp (p \\<bullet> b) = to_Zp (ltrm p \\<bullet> b)  \\<oplus>\\<^bsub>Z\\<^sub>p\\<^esub> to_Zp (q \\<bullet> b)\"\n          using 5 3 q_def by (metis (no_types, lifting) A(1) val_ring_memE UPQ.ltrm_closed UPQ.to_fun_plus add_comm assms(4) to_Zp_add)\n        have 8: \"to_Zp (p \\<bullet> a) = to_Zp (ltrm p \\<bullet> a)  \\<oplus>\\<^bsub>Z\\<^sub>p\\<^esub> to_Zp (q \\<bullet> a)\"\n          using 4 6 q_def by (metis (no_types, lifting) A(1) val_ring_memE UPQ.ltrm_closed UPQ.to_fun_plus add_comm assms(3) to_Zp_add)\n        have 9: \"to_Zp (p \\<bullet> b) \\<in> carrier Z\\<^sub>p\"\n          using A assms by (meson val_ring_memE UPQ.to_fun_closed to_Zp_closed)\n        have 10: \"to_Zp (p \\<bullet> a) \\<in> carrier Z\\<^sub>p\"\n          using A assms val_ring_memE UPQ.to_fun_closed to_Zp_closed by presburger\n        have 11: \"to_Zp (p \\<bullet> b) n = to_Zp (ltrm p \\<bullet> b) n  \\<oplus>\\<^bsub>Zp_res_ring n\\<^esub> to_Zp (q \\<bullet> b) n\"\n          using 7 9 5 3 residue_of_sum by presburger\n        have 12: \"to_Zp (p \\<bullet> a) n = to_Zp (ltrm p \\<bullet> a) n \\<oplus>\\<^bsub>Zp_res_ring n\\<^esub> to_Zp (q \\<bullet> a) n\"\n          using 8 6 4 residue_of_sum by presburger\n        show ?thesis using 0 11 12 q_def assms \n          using \"1\" by presburger\n      qed\n    qed\n  qed\n  have \"(\\<forall>x. g x \\<in> \\<O>\\<^sub>p) \"\n    using assms by blast\n  hence 0: \"to_Zp (g \\<bullet> b) n = to_Zp (g \\<bullet> a) n\"\n    using \\<open>(\\<forall>x. g x \\<in> \\<O>\\<^sub>p) \\<longrightarrow> to_Zp (g \\<bullet> b) n = to_Zp (g \\<bullet> a) n\\<close> by blast\n  have 1: \"g \\<bullet> a \\<in> \\<O>\\<^sub>p\"\n    using  assms(1) assms(2) assms(3) \n    by (metis gauss_norm_coeff_norm positive_gauss_norm_eval val_ring_memE(1))\n  have 2: \"g \\<bullet> b \\<in> \\<O>\\<^sub>p\"\n    using  assms(1) assms(2) assms(4) \n    by (metis gauss_norm_coeff_norm positive_gauss_norm_eval val_ring_memE(1))\n  have 3: \"val (g \\<bullet> b) < eint n\"\n  proof-\n    have P0: \"to_Zp (g \\<bullet> a) \\<in> carrier Z\\<^sub>p\"\n      using 1 val_ring_memE to_Zp_closed by blast\n    have P1: \"to_Zp (g \\<bullet> b) \\<in> carrier Z\\<^sub>p\"\n      using 2 val_ring_memE to_Zp_closed by blast\n    have P2: \"val_Zp (to_Zp (g \\<bullet> a)) < n\"\n      using 1 assms to_Zp_val by presburger\n    have P3: \"to_Zp (g \\<bullet> a) \\<noteq> \\<zero>\\<^bsub>Z\\<^sub>p\\<^esub>\"\n      using P2 P0 unfolding val_Zp_def     by (metis P2 infinity_ilessE val_Zp_def)\n    have P4: \"(to_Zp (g \\<bullet> a)) n \\<noteq> 0\"\n      using 1 P2 P3 above_ord_nonzero[of \"to_Zp (g \\<bullet> a)\" n]  \n      by (metis P0 eint.inject less_eintE val_ord_Zp)\n    then have \"to_Zp (g \\<bullet> b) n \\<noteq> 0\"\n      using 0 by linarith\n    then have \"val_Zp (to_Zp (g \\<bullet> b)) < n\"\n      using P1 P0 \n      by (smt below_val_Zp_zero eint_ile eint_ord_simps(1) eint_ord_simps(2) nonzero_imp_ex_nonzero_res residue_of_zero(2) zero_below_val_Zp)  \n    then show ?thesis using 2 \n      by (metis to_Zp_val)\n  qed\n  thus ?thesis using 0 1 2 assms val_ring_equal_res_imp_equal_val[of \"g \\<bullet> b\" \"g \\<bullet> a\" n] by blast\nqed\n\nlemma to_Zp_poly_monom:\n  assumes \"a \\<in> \\<O>\\<^sub>p\"\n  shows \"to_Zp_poly (monom (UP Q\\<^sub>p) a n) = monom (UP Z\\<^sub>p) (to_Zp a) n\"\n  unfolding to_Zp_poly_def \n  apply(rule ext)\n  using assms cfs_monom[of a n] Zp.cfs_monom[of \"to_Zp a\" n] \n  by (simp add: to_Zp_closed to_Zp_zero val_ring_memE(2))\n\nlemma to_Zp_poly_add:\n  assumes \"f \\<in> carrier (UP Q\\<^sub>p)\"\n  assumes \"gauss_norm f \\<ge> 0\"\n  assumes \"g \\<in> carrier (UP Q\\<^sub>p)\"\n  assumes \"gauss_norm g \\<ge> 0\"\n  shows \"to_Zp_poly (f \\<oplus>\\<^bsub>UP Q\\<^sub>p\\<^esub> g) = to_Zp_poly f \\<oplus>\\<^bsub>UP Z\\<^sub>p\\<^esub> to_Zp_poly g\"\nproof- \n  obtain F where F_def: \"F = to_Zp_poly f\"\n    by blast \n  obtain G where G_def: \"G = to_Zp_poly g\"\n    by blast \n  have F_closed: \"F \\<in> carrier (UP Z\\<^sub>p)\"\n    unfolding F_def using assms \n    by (simp add: to_Zp_poly_closed)\n  have G_closed: \"G \\<in> carrier (UP Z\\<^sub>p)\"\n    unfolding G_def using assms \n    by (simp add: to_Zp_poly_closed)\n  have F_inc: \"poly_inc F = f\"\n    using assms unfolding F_def \n    using poly_inc_inverse_left by blast\n  have G_inc: \"poly_inc G = g\"\n    using assms unfolding G_def \n    by (simp add: poly_inc_inverse_left)\n  have 0: \"poly_inc (F \\<oplus>\\<^bsub>UP Z\\<^sub>p\\<^esub> G) = poly_inc F \\<oplus>\\<^bsub>UP Q\\<^sub>p\\<^esub> poly_inc G\"\n    using F_closed G_closed \n    by (simp add: poly_inc_plus)\n  have 1: \"to_Zp_poly (poly_inc (F \\<oplus>\\<^bsub>UP Z\\<^sub>p\\<^esub> G)) = F \\<oplus>\\<^bsub>UP Z\\<^sub>p\\<^esub> G\"\n    using G_closed F_closed \n    by (simp add: poly_inc_inverse_right)\n  show ?thesis \n    using  1 unfolding F_inc G_inc 0 unfolding F_def G_def \n    by blast \nqed\n\nlemma to_Zp_poly_zero:\n\"to_Zp_poly (\\<zero>\\<^bsub>UP Q\\<^sub>p\\<^esub>) = \\<zero>\\<^bsub>UP Z\\<^sub>p\\<^esub>\"\n  unfolding to_Zp_poly_def \n  apply(rule ext)\n  by (simp add: to_Zp_zero)\n\nlemma to_Zp_poly_one:\n\"to_Zp_poly (\\<one>\\<^bsub>UP Q\\<^sub>p\\<^esub>) = \\<one>\\<^bsub>UP Z\\<^sub>p\\<^esub>\"\n  unfolding to_Zp_poly_def \n  apply(rule ext)\n  by (metis Zp.UP_one_closed poly_inc_inverse_right poly_inc_one to_Zp_poly_def) \n\nlemma val_ring_add_pow:\n  assumes \"a \\<in> carrier Q\\<^sub>p\"\n  assumes \"val a \\<ge> 0\"\n  shows \"val ([(n::nat)]\\<cdot>a) \\<ge> 0\"\nproof-\n  have 0: \"[(n::nat)]\\<cdot>a = ([n]\\<cdot>\\<one>)\\<otimes>a\"\n    using assms Qp.add_pow_ldistr Qp.cring_simprules(12) Qp.one_closed by presburger\n  show ?thesis unfolding 0 using assms \n    by (meson Qp.nat_inc_closed val_ring_memE val_of_nat_inc val_ringI val_ring_times_closed)\nqed\n\nlemma to_Zp_poly_pderiv:\n  assumes \"g \\<in> carrier (UP Q\\<^sub>p)\"\n  assumes \"gauss_norm g \\<ge> 0\"\n  shows \"to_Zp_poly (pderiv g) = Zp.pderiv (to_Zp_poly g)\"\nproof- \n  have 0: \"gauss_norm g \\<ge> 0 \\<longrightarrow> to_Zp_poly (pderiv g) = Zp.pderiv (to_Zp_poly g)\"\n  proof(rule poly_induct, rule assms, rule)\n    fix p \n    assume A: \" p \\<in> carrier (UP Q\\<^sub>p)\"\n         \"deg Q\\<^sub>p p = 0\"\n         \"0 \\<le> gauss_norm p\"\n    obtain a where a_def: \"a \\<in> \\<O>\\<^sub>p \\<and> p = monom (UP Q\\<^sub>p) a 0\"\n      using A \n      by (metis UPQ.ltrm_deg_0 positive_gauss_norm_valuation_ring_coeffs)\n    have p_eq: \"p = monom (UP Q\\<^sub>p) a 0\"\n      using a_def by blast \n    have 0: \"to_Zp_poly p = monom (UP Z\\<^sub>p) (to_Zp a) 0\"\n      unfolding p_eq\n      apply(rule to_Zp_poly_monom)\n      using a_def by blast \n    have 1: \"UPQ.pderiv (monom (UP Q\\<^sub>p) a 0) = \\<zero>\\<^bsub>UP Q\\<^sub>p\\<^esub>\"\n      using A(1) A(2) UPQ.pderiv_deg_0 p_eq by blast\n    have 2: \"Zp.pderiv (monom (UP Z\\<^sub>p) (to_Zp a) 0) = \\<zero>\\<^bsub>UP Z\\<^sub>p\\<^esub>\"\n      apply(rule Zp.pderiv_deg_0) \n       apply(rule Zp.monom_closed, rule to_Zp_closed)\n      using a_def \n       apply (simp add: val_ring_memE(2); fail)\n      apply(cases \"to_Zp a = \\<zero>\\<^bsub>Z\\<^sub>p\\<^esub>\")\n      apply (simp; fail)\n      apply(rule Zp.deg_monom, blast) \n      using a_def \n      by (simp add: to_Zp_closed val_ring_memE(2))\n    show \"to_Zp_poly (UPQ.pderiv p) = Zp.pderiv (to_Zp_poly p)\"\n      unfolding 0 unfolding p_eq \n      unfolding 1 2 to_Zp_poly_zero by blast \n  next \n    fix p \n    assume A: \"\\<And>q. q \\<in> carrier (UP Q\\<^sub>p) \\<Longrightarrow>\n              deg Q\\<^sub>p q < deg Q\\<^sub>p p \\<Longrightarrow>\n              0 \\<le> gauss_norm q \\<longrightarrow>\n              to_Zp_poly (UPQ.pderiv q) = Zp.pderiv (to_Zp_poly q)\"\n              \"p \\<in> carrier (UP Q\\<^sub>p)\"\n              \" 0 < deg Q\\<^sub>p p\"\n    show \"0 \\<le> gauss_norm p \\<longrightarrow> to_Zp_poly (UPQ.pderiv p) = Zp.pderiv (to_Zp_poly p)\"\n    proof \n      assume B: \"0 \\<le> gauss_norm p\"\n      obtain q where q_def: \"q = trunc p\"\n        by blast \n      have p_eq: \"p = q \\<oplus>\\<^bsub>UP Q\\<^sub>p\\<^esub> ltrm p\"\n        by (simp add: A(2) UPQ.trunc_simps(1) q_def)\n      have q_gauss_norm:    \"gauss_norm q \\<ge> 0\"\n        unfolding q_def \n        apply(rule gauss_norm_geqI)\n        using A apply (simp add: UPQ.trunc_closed; fail)\n        using trunc_cfs[of p] A gauss_normE \n      proof -\n        fix n :: nat\n        have f1: \"\\<zero> = q (deg Q\\<^sub>p p)\"\n          by (simp add: UPQ.deg_leE UPQ.trunc_closed UPQ.trunc_degree \\<open>0 < deg Q\\<^sub>p p\\<close> \\<open>p \\<in> carrier (UP Q\\<^sub>p)\\<close> q_def)\n        have \"\\<forall>n. 0 \\<le> val (p n)\"\n          by (meson B \\<open>p \\<in> carrier (UP Q\\<^sub>p)\\<close> eint_ord_trans gauss_normE)\n        then show \"0 \\<le> val (Cring_Poly.truncate Q\\<^sub>p p n)\"\n          using f1 by (metis (no_types) Qp.nat_mult_zero UPQ.ltrm_closed UPQ.coeff_of_sum_diff_degree0 UPQ.deg_ltrm UPQ.trunc_closed \\<open>\\<And>n. \\<lbrakk>p \\<in> carrier (UP Q\\<^sub>p); n < deg Q\\<^sub>p p\\<rbrakk> \\<Longrightarrow> Cring_Poly.truncate Q\\<^sub>p p n = p n\\<close> \\<open>p \\<in> carrier (UP Q\\<^sub>p)\\<close> nat_neq_iff p_eq q_def val_of_nat_inc)\n      qed\n      have 0: \"to_Zp_poly (UPQ.pderiv q) = Zp.pderiv (to_Zp_poly q)\"\n        using A q_def q_gauss_norm \n        by (simp add: UPQ.trunc_closed UPQ.trunc_degree)\n      have 1: \"UPQ.pderiv (monom (UP Q\\<^sub>p) (p (deg Q\\<^sub>p p)) (deg Q\\<^sub>p p)) =\n               monom (UP Q\\<^sub>p) ([deg Q\\<^sub>p p] \\<cdot> p (deg Q\\<^sub>p p)) (deg Q\\<^sub>p p - 1)\"\n        apply(rule pderiv_monom)\n        using A by (simp add: UPQ.UP_car_memE(1))\n      have 2: \"Zp.pderiv (monom (UP Z\\<^sub>p) (to_Zp (p (deg Q\\<^sub>p p))) (deg Q\\<^sub>p p)) =\n    monom (UP Z\\<^sub>p) ([deg Q\\<^sub>p p] \\<cdot>\\<^bsub>Z\\<^sub>p\\<^esub> to_Zp ( p (deg Q\\<^sub>p p))) (deg Q\\<^sub>p p - 1)\"\n        using A  Zp.pderiv_monom[of \"to_Zp ( p (deg Q\\<^sub>p p))\" \"deg Q\\<^sub>p p\"]  \n        by (simp add: UPQ.lcf_closed to_Zp_closed)\n      have 3: \"to_Zp_poly (UPQ.pderiv (monom (UP Q\\<^sub>p) (p (deg Q\\<^sub>p p)) (deg Q\\<^sub>p p))) = monom (UP Z\\<^sub>p) (to_Zp ([deg Q\\<^sub>p p] \\<cdot> p (deg Q\\<^sub>p p))) (deg Q\\<^sub>p p - 1)\"\n        unfolding 1 apply(rule to_Zp_poly_monom)\n        apply(rule val_ring_memI)\n         apply (simp add: A(2) UPQ.UP_car_memE(1); fail)\n        apply(rule val_ring_add_pow)\n        using A \n        apply (simp add: UPQ.lcf_closed; fail)\n        using B A \n        by (simp add: positive_gauss_norm_valuation_ring_coeffs val_ring_memE(1))\n      have 4: \"to_Zp_poly (ltrm p) = monom (UP Z\\<^sub>p) (to_Zp (p (deg Q\\<^sub>p p))) (deg Q\\<^sub>p p)\"\n        apply(rule to_Zp_poly_monom) using A \n        by (simp add: B positive_gauss_norm_valuation_ring_coeffs)\n      have 5: \"to_Zp_poly (UPQ.pderiv (ltrm p)) = Zp.pderiv (to_Zp_poly (ltrm p))\"\n        unfolding 3 4 2 \n        by (simp add: A(2) B positive_gauss_norm_valuation_ring_coeffs to_Zp_nat_add_pow)\n      have 6: \"pderiv p = pderiv q \\<oplus>\\<^bsub>UP Q\\<^sub>p\\<^esub> pderiv (ltrm p)\"\n        using p_eq \n        by (metis A(2) UPQ.ltrm_closed UPQ.pderiv_add UPQ.trunc_closed p_eq q_def)\n      have 7: \"to_Zp_poly p = to_Zp_poly q \\<oplus>\\<^bsub>UP Z\\<^sub>p\\<^esub> to_Zp_poly (ltrm p)\"\n        using p_eq \n        by (metis (no_types, lifting) A(2) B UPQ.ltrm_closed UPQ.cfs_closed UPQ.trunc_closed gauss_norm_monom positive_gauss_norm_valuation_ring_coeffs q_def q_gauss_norm to_Zp_poly_add val_ring_memE(1))\n      have 8: \"to_Zp_poly  (pderiv p) =\n                to_Zp_poly (UPQ.pderiv q) \\<oplus>\\<^bsub>UP Z\\<^sub>p\\<^esub>\n                 to_Zp_poly (UPQ.pderiv (monom (UP Q\\<^sub>p) (p (deg Q\\<^sub>p p)) (deg Q\\<^sub>p p)))\"\n        unfolding 6 apply(rule to_Zp_poly_add)\n           apply (simp add: A(2) UPQ.pderiv_closed UPQ.trunc_closed q_def; fail)\n          apply (metis A(2) UPQ.cfs_closed UPQ.pderiv_cfs UPQ.trunc_closed gauss_norm_coeff_norm positive_gauss_norm_valuation_ring_coeffs q_def q_gauss_norm val_ring_add_pow val_ring_memE(1))\n         apply (simp add: A(2) UPQ.UP_car_memE(1) UPQ.pderiv_closed; fail)\n        apply(rule eint_ord_trans[of _ \"gauss_norm (monom (UP Q\\<^sub>p) (p (deg Q\\<^sub>p p)) (deg Q\\<^sub>p p))\"])\n        apply (simp add: A(2) B UPQ.cfs_closed gauss_norm_monom positive_gauss_norm_valuation_ring_coeffs val_ring_memE(1); fail)\n        apply(rule gauss_norm_pderiv)\n        using A(2) UPQ.ltrm_closed by blast\n      have 9: \"Zp.pderiv  (to_Zp_poly p) =  Zp.pderiv (to_Zp_poly q) \\<oplus>\\<^bsub>UP Z\\<^sub>p\\<^esub>\n         Zp.pderiv (to_Zp_poly (monom (UP Q\\<^sub>p) (p (deg Q\\<^sub>p p)) (deg Q\\<^sub>p p)))\"\n          unfolding 7 apply(rule Zp.pderiv_add)\n           apply(rule to_Zp_poly_closed)\n            apply (simp add: A(2) UPQ.trunc_closed q_def; fail)\n           apply (simp add: q_gauss_norm; fail)\n           apply(rule to_Zp_poly_closed)\n           apply (simp add: A(2) UPQ.UP_car_memE(1); fail)\n          by (simp add: A(2) B UPQ.cfs_closed gauss_norm_monom positive_gauss_norm_valuation_ring_coeffs val_ring_memE(1))\n      show \"to_Zp_poly (UPQ.pderiv p) = Zp.pderiv (to_Zp_poly p)\"\n          unfolding 9 8 5 0 by blast \n    qed\n  qed\n  thus ?thesis using assms by blast \nqed\n\nlemma val_p_int_pow:\n\"val (\\<pp>[^]k) = eint (k)\"\n  by (simp add: ord_p_pow_int p_intpow_closed(2))\n\ndefinition int_gauss_norm where\n\"int_gauss_norm g = (SOME n::int. eint n = gauss_norm g)\"\n\nlemma int_gauss_norm_eq: \n  assumes \"g \\<in> carrier (UP Q\\<^sub>p)\"\n  assumes \"g \\<noteq> \\<zero>\\<^bsub>UP Q\\<^sub>p\\<^esub>\"\n  shows \"eint (int_gauss_norm g) = gauss_norm g\"\nproof- \n  have 0: \"gauss_norm g < \\<infinity>\"\n    using assms by (simp add: gauss_norm_prop)\n  then show ?thesis unfolding int_gauss_norm_def \n    using assms \n    by fastforce\nqed\n\nlemma int_gauss_norm_smult:\n  assumes \"g \\<in> carrier (UP Q\\<^sub>p)\"\n  assumes \"g \\<noteq> \\<zero>\\<^bsub>UP Q\\<^sub>p\\<^esub>\"\n  assumes \"a \\<in> nonzero Q\\<^sub>p\"\n  shows \"int_gauss_norm (a \\<odot>\\<^bsub>UP Q\\<^sub>p\\<^esub> g) = ord a + int_gauss_norm g\"\n  using gauss_norm_smult[of g a] int_gauss_norm_eq val_ord assms \n  by (metis (no_types, opaque_lifting) Qp.nonzero_closed UPQ.UP_smult_closed UPQ.cfs_zero\n      eint.distinct(2) eint.inject gauss_norm_coeff_norm local.val_zero plus_eint_simps(1))\n\ndefinition normalize_poly where\n\"normalize_poly g = (if g = \\<zero>\\<^bsub>UP Q\\<^sub>p\\<^esub> then g else (\\<pp>[^](- int_gauss_norm g)) \\<odot>\\<^bsub>Q\\<^sub>p_x\\<^esub> g)\"\n\nlemma normalize_poly_zero: \n\"normalize_poly \\<zero>\\<^bsub>UP Q\\<^sub>p\\<^esub> = \\<zero>\\<^bsub>UP Q\\<^sub>p\\<^esub>\"\n  unfolding normalize_poly_def by simp \n\nlemma normalize_poly_nonzero_eq:\n  assumes \"g \\<noteq> \\<zero>\\<^bsub>UP Q\\<^sub>p\\<^esub>\"\n  assumes \"g \\<in> carrier (UP Q\\<^sub>p)\"\n  shows \"normalize_poly g = (\\<pp>[^](- int_gauss_norm g)) \\<odot>\\<^bsub>UP Q\\<^sub>p\\<^esub> g\"\n  using assms unfolding normalize_poly_def by simp \n\nlemma int_gauss_norm_normalize_poly:\n  assumes \"g \\<noteq> \\<zero>\\<^bsub>UP Q\\<^sub>p\\<^esub>\"\n  assumes \"g \\<in> carrier (UP Q\\<^sub>p)\"\n  shows \"int_gauss_norm (normalize_poly g) = 0\"\n  using normalize_poly_nonzero_eq int_gauss_norm_smult assms \n  by (simp add: ord_p_pow_int p_intpow_closed(2))\n\nlemma normalize_poly_closed: \n  assumes \"g \\<in> carrier (UP Q\\<^sub>p)\"\n  shows \"normalize_poly g \\<in> carrier (UP Q\\<^sub>p)\"\n  using assms unfolding normalize_poly_def \n  by (simp add: p_intpow_closed(1))\n\nlemma normalize_poly_nonzero:\n  assumes \"g \\<noteq> \\<zero>\\<^bsub>UP Q\\<^sub>p\\<^esub>\"\n  assumes \"g \\<in> carrier (UP Q\\<^sub>p)\"\n  shows \"normalize_poly g \\<noteq> \\<zero>\\<^bsub>UP Q\\<^sub>p\\<^esub>\"\n  using assms normalize_poly_nonzero_eq \n  by (metis (no_types, lifting) UPQ.UP_smult_one UPQ.module_axioms UPQ.smult_r_null module.smult_assoc1 p_intpow_closed(1) p_intpow_inv')\n\nlemma gauss_norm_normalize_poly:\n  assumes \"g \\<noteq> \\<zero>\\<^bsub>UP Q\\<^sub>p\\<^esub>\"\n  assumes \"g \\<in> carrier (UP Q\\<^sub>p)\"\n  shows \"gauss_norm (normalize_poly g) = 0\"\nproof- \n  have 0: \"eint (int_gauss_norm (normalize_poly g)) = gauss_norm (normalize_poly g)\"\n    by(rule int_gauss_norm_eq, rule normalize_poly_closed, rule assms, \n          rule normalize_poly_nonzero, rule assms, rule assms)\n  show ?thesis \n    using 0 int_gauss_norm_normalize_poly assms \n    by (simp add: zero_eint_def)\nqed\n\nlemma taylor_term_eval_eq:\n  assumes \"f \\<in> carrier (UP Q\\<^sub>p)\"\n  assumes \"x \\<in> carrier Q\\<^sub>p\"\n  assumes \"t \\<in> carrier Q\\<^sub>p\"\n  assumes \"\\<And>j. i \\<noteq> j \\<Longrightarrow> val (UPQ.taylor_term x f i \\<bullet> t) < val (UPQ.taylor_term x f j \\<bullet> t) \"\n  shows \"val (f \\<bullet> t) = val (UPQ.taylor_term x f i \\<bullet> t)\"\nproof-\n  have 0: \"f = finsum (UP Q\\<^sub>p) (UPQ.taylor_term x f) {..deg Q\\<^sub>p f}\"\n    by(rule UPQ.taylor_term_sum[of f \"deg Q\\<^sub>p f\" x], rule assms, blast, rule assms)\n  show ?thesis \n  proof(cases \"i \\<in> {..deg Q\\<^sub>p f}\")\n    case True\n    have T0: \"finsum (UP Q\\<^sub>p) (UPQ.taylor_term x f) {..deg Q\\<^sub>p f} = UPQ.taylor_term x f i \\<oplus>\\<^bsub>UP Q\\<^sub>p\\<^esub> finsum (UP Q\\<^sub>p) (UPQ.taylor_term x f) ({..deg Q\\<^sub>p f} - {i})\"\n      apply(rule UPQ.P.finsum_remove[of \"{..deg Q\\<^sub>p f}\" \"UPQ.taylor_term x f\" i])\n      by(rule UPQ.taylor_term_closed, rule assms, rule assms, blast, rule True)\n    have T1: \"f = UPQ.taylor_term x f i \\<oplus>\\<^bsub>UP Q\\<^sub>p\\<^esub> finsum (UP Q\\<^sub>p) (UPQ.taylor_term x f) ({..deg Q\\<^sub>p f} - {i})\"\n      using 0 T0 by metis\n    have T2: \"finsum (UP Q\\<^sub>p) (UPQ.taylor_term x f) ({..deg Q\\<^sub>p f} - {i}) \\<in> carrier (UP Q\\<^sub>p)\"\n      apply(rule UPQ.P.finsum_closed)\n      using UPQ.taylor_term_closed assms(1) assms(2) by blast\n    have T3: \"UPQ.taylor_term x f i \\<in> carrier (UP Q\\<^sub>p)\"\n      by(rule UPQ.taylor_term_closed, rule assms, rule assms )\n    obtain g where g_def: \"g = f\" \n      by blast \n    have T4: \"g = UPQ.taylor_term x f i \\<oplus>\\<^bsub>UP Q\\<^sub>p\\<^esub> finsum (UP Q\\<^sub>p) (UPQ.taylor_term x f) ({..deg Q\\<^sub>p f} - {i})\"\n      unfolding g_def by(rule T1)\n    have g_closed: \"g \\<in> carrier (UP Q\\<^sub>p)\"\n      unfolding g_def by(rule assms)\n    have T5: \"g \\<bullet> t = UPQ.taylor_term x f i \\<bullet> t \\<oplus> ( finsum (UP Q\\<^sub>p) (UPQ.taylor_term x f) ({..deg Q\\<^sub>p f} - {i})) \\<bullet> t\"\n      unfolding T4 by(rule UPQ.to_fun_plus, rule T2, rule T3, rule assms)\n    have T6: \"( finsum (UP Q\\<^sub>p) (UPQ.taylor_term x f) ({..deg Q\\<^sub>p f} - {i})) \\<bullet> t = \n                ( finsum Q\\<^sub>p (\\<lambda>i. UPQ.taylor_term x f i \\<bullet> t) ({..deg Q\\<^sub>p f} - {i}))\"\n      apply(rule UPQ.to_fun_finsum, blast)\n      using assms UPQ.taylor_term_closed apply blast\n      using assms by blast \n    have T7: \"\\<And>j. j \\<in> {..deg Q\\<^sub>p f} - {i} \\<Longrightarrow> val (UPQ.taylor_term x f j \\<bullet> t) > val (UPQ.taylor_term x f i \\<bullet> t)\"\n      using assms  by (metis Diff_iff singletonI)\n    have T8: \"val (( finsum (UP Q\\<^sub>p) (UPQ.taylor_term x f) ({..deg Q\\<^sub>p f} - {i})) \\<bullet> t) > val (UPQ.taylor_term x f i \\<bullet> t)\"\n      unfolding T6\n      apply(rule finsum_val_ultrametric'')\n      using UPQ.taylor_term_closed assms \n      apply (metis (no_types, lifting) Pi_I UPQ.to_fun_closed)\n        apply blast\n      using assms T7 apply blast\n      using assms(4)[of \"Suc i\"] using eint_ord_simps(4)\n        assms(4) eint_ord_code(6)  g_def gr_implies_not_zero less_one by smt \n    have T9: \"val (g \\<bullet> t) =  val (UPQ.taylor_term x f i \\<bullet> t)\"\n      unfolding T5 using T8 T2 T3 \n      by (metis (no_types, lifting) Qp.add.m_comm UPQ.to_fun_closed assms(3) val_ultrametric_noteq)\n    show ?thesis using T9 unfolding g_def by blast \n  next\n    case False\n    have \"i > deg Q\\<^sub>p f\"\n      using False by simp\n    hence \"i > deg Q\\<^sub>p (UPQ.taylor x f)\"\n      using assms UPQ.taylor_deg by presburger\n    hence F0: \"UPQ.taylor x f i = \\<zero>\"\n      using assms UPQ.taylor_closed UPQ.deg_leE by blast\n    have F1: \"(UPQ.taylor_term x f i \\<bullet> t) = \\<zero>\"\n      using UPQ.to_fun_taylor_term[of f t x i]\n      unfolding F0\n      using assms Qp.cring_simprules(2) Qp.cring_simprules(4) Qp.integral_iff Qp.nat_pow_closed by presburger\n    show ?thesis \n      using assms(4)[of \"Suc i\"] unfolding F1 \n      by (metis eint_ord_code(6) local.val_zero n_not_Suc_n)\n  qed\nqed\n\n\n(**************************************************************************************************)\n(**************************************************************************************************)\nsubsection\\<open>Hensel's Lemma for \\<open>p\\<close>-adic fields\\<close>\n(**************************************************************************************************)\n(**************************************************************************************************)\nlemma Zp_hensels_lemma:\n  assumes \"f \\<in> carrier Zp_x\"\n  assumes \"a \\<in> carrier Z\\<^sub>p\"\n  assumes \"val_Zp (Zp.to_fun f a) > eint 2 * val_Zp (Zp.to_fun (Zp.pderiv f) a)\"\n  obtains \\<alpha> where\n       \"Zp.to_fun f \\<alpha> = \\<zero>\\<^bsub>Z\\<^sub>p\\<^esub>\" and \"\\<alpha> \\<in> carrier Z\\<^sub>p\" \n       \"val_Zp (a \\<ominus>\\<^bsub>Z\\<^sub>p\\<^esub> \\<alpha>) > val_Zp (Zp.to_fun (Zp.pderiv f) a)\"\n       \"val_Zp (a \\<ominus>\\<^bsub>Z\\<^sub>p\\<^esub> \\<alpha>) = val_Zp (divide (Zp.to_fun f a) (Zp.to_fun (Zp.pderiv f) a))\"\n       \"val_Zp (Zp.to_fun (Zp.pderiv f) \\<alpha>) = val_Zp (Zp.to_fun (Zp.pderiv f) a)\"\nproof(cases \"Zp.to_fun f a \\<noteq> \\<zero>\\<^bsub>Z\\<^sub>p \\<^esub>\")\n  case True\n  have \"hensel p f a\"\n    using assms True\n    by (simp add: Zp_def hensel.intro hensel_axioms.intro padic_integers_axioms)\n  then show ?thesis \n    using hensel.full_hensels_lemma[of p f a] that \n    unfolding Zp_def    \n    by blast       \nnext\n  case False\n  have F0: \"Zp.to_fun (Zp.pderiv f) a \\<noteq> \\<zero>\\<^bsub>Z\\<^sub>p\\<^esub>\"\n    using assms val_Zp_def by auto\n  have F1: \"val_Zp (a \\<ominus>\\<^bsub>Z\\<^sub>p\\<^esub> a) = \\<infinity>\"\n    using assms unfolding val_Zp_def \n    using Zp.r_right_minus_eq by presburger\n  have F2: \"Zp.to_fun f a = \\<zero>\\<^bsub>Z\\<^sub>p\\<^esub>\"\n    using False by auto \n  have F3: \"(local.divide \\<zero>\\<^bsub>Z\\<^sub>p\\<^esub> (Zp.to_fun (Zp.pderiv f) a)) = \\<zero>\\<^bsub>Z\\<^sub>p\\<^esub>\"\n    using divide_def by auto\n  have \"Zp.to_fun f a = \\<zero>\\<^bsub>Z\\<^sub>p\\<^esub>\" and \"a \\<in> carrier Z\\<^sub>p\"\n    \"val_Zp (a \\<ominus>\\<^bsub>Z\\<^sub>p\\<^esub> a) > val_Zp (Zp.to_fun (Zp.pderiv f) a)\"\n       \"val_Zp (a \\<ominus>\\<^bsub>Z\\<^sub>p\\<^esub> a) = val_Zp (divide (Zp.to_fun f a) (Zp.to_fun (Zp.pderiv f) a))\"\n       \"val_Zp (Zp.to_fun (Zp.pderiv f) a) = val_Zp (Zp.to_fun (Zp.pderiv f) a)\"\n    using assms F0 unfolding F1 F2 F3  unfolding val_Zp_def \n    by auto \n  then show ?thesis \n    using that by blast\nqed\n\ntheorem hensels_lemma:\n  assumes \"f \\<in> carrier (UP Q\\<^sub>p)\"\n  assumes \"a \\<in> \\<O>\\<^sub>p\"\n  assumes \"gauss_norm f \\<ge> 0\"\n  assumes \"val (f\\<bullet>a) > 2*val ((pderiv f)\\<bullet>a)\"\n  shows \"\\<exists>!\\<alpha> \\<in> \\<O>\\<^sub>p. f\\<bullet>\\<alpha> = \\<zero> \\<and> val (a \\<ominus> \\<alpha>) > val ((pderiv f)\\<bullet>a)\"\n        \"\\<exists>!\\<alpha> \\<in> \\<O>\\<^sub>p. f\\<bullet>\\<alpha> = \\<zero> \\<and> val (a \\<ominus> \\<alpha>) > val ((pderiv f)\\<bullet>a) \\<and> val(a \\<ominus> \\<alpha>) = val (f\\<bullet>a) - val ((pderiv f)\\<bullet>a)\"\nproof- \n  have a_closed: \"a \\<in> carrier Q\\<^sub>p\"\n    using assms val_ring_memE by auto \n  have f_nonzero: \"f \\<noteq> \\<zero>\\<^bsub>UP Q\\<^sub>p\\<^esub>\"\n  proof(rule ccontr)\n    assume N: \"\\<not> f \\<noteq> \\<zero>\\<^bsub>UP Q\\<^sub>p\\<^esub>\"\n    then have 0: \"pderiv f = \\<zero>\\<^bsub>UP Q\\<^sub>p\\<^esub>\"\n      using UPQ.deg_zero UPQ.pderiv_deg_0 by blast\n    have 1: \"f = \\<zero>\\<^bsub>UP Q\\<^sub>p\\<^esub>\"\n      using N by auto \n    have 2: \"eint 2 * val (UPQ.pderiv \\<zero>\\<^bsub>UP Q\\<^sub>p\\<^esub> \\<bullet> a) = \\<infinity>\"\n      by (simp add: UPQ.to_fun_zero local.a_closed local.val_zero)\n    show False using assms a_closed\n      unfolding 2 1 \n      using eint_ord_simps(6) by blast\n  qed\n  obtain h where h_def: \"h = to_Zp_poly f\"\n    by blast \n  have h_closed: \"h \\<in> carrier (UP Z\\<^sub>p)\"\n    unfolding h_def using assms\n    by (simp add: to_Zp_poly_closed)\n  have h_deriv: \"Zp.pderiv h = to_Zp_poly (pderiv f)\"\n    unfolding h_def \n    using to_Zp_poly_pderiv[of f] assms by auto \n  have 0: \"to_Zp (f\\<bullet>a) = to_function Z\\<^sub>p h (to_Zp a)\"\n    unfolding h_def \n    using assms a_closed \n    by (simp add: UPQ.to_fun_def to_Zp_poly_eval)\n  have 1: \"to_Zp ((pderiv f)\\<bullet>a) = to_function Z\\<^sub>p (Zp.pderiv h) (to_Zp a)\"\n    unfolding h_deriv \n    using assms a_closed  UPQ.pderiv_closed UPQ.to_fun_def eint_ord_trans gauss_norm_pderiv to_Zp_poly_eval \n    by presburger\n  have 2: \"val (f\\<bullet>a) = val_Zp (to_function Z\\<^sub>p h (to_Zp a))\"\n  proof- \n    have 20: \"f\\<bullet>a \\<in> \\<O>\\<^sub>p\"\n      using assms positive_gauss_norm_eval by blast\n    have 21: \"val (f\\<bullet>a) = val_Zp (to_Zp (f\\<bullet>a))\"\n      using 20 by (simp add: to_Zp_val)\n    show ?thesis unfolding 21 0 by blast \n  qed\n  have 3: \"val ((pderiv f)\\<bullet>a) = val_Zp ( to_function Z\\<^sub>p (Zp.pderiv h) (to_Zp a))\"\n  proof- \n    have 30: \"(pderiv f)\\<bullet>a \\<in> \\<O>\\<^sub>p\"\n      using positive_gauss_norm_eval assms gauss_norm_pderiv \n      by (meson UPQ.pderiv_closed eint_ord_trans)\n    have 31: \"val ((pderiv f)\\<bullet>a) = val_Zp (to_Zp ((pderiv f)\\<bullet>a))\"\n      using 30 by (simp add: to_Zp_val)\n    show ?thesis unfolding 31 1 by blast \n  qed\n  have 4: \"\\<exists>!\\<alpha>. \\<alpha> \\<in> carrier Z\\<^sub>p \\<and>\n        Zp.to_fun (to_Zp_poly f) \\<alpha> = \\<zero>\\<^bsub>Z\\<^sub>p\\<^esub> \\<and>\n        val_Zp (Zp.to_fun (Zp.pderiv (to_Zp_poly f)) (to_Zp a))\n        < val_Zp (to_Zp a \\<ominus>\\<^bsub>Z\\<^sub>p\\<^esub> \\<alpha>)\"\n    apply(rule hensels_lemma')\n    using h_closed h_def apply blast\n    using assms local.a_closed to_Zp_closed apply blast\n    using assms unfolding 2 3 h_def Zp.to_fun_def by blast  \n  obtain \\<alpha> where \\<alpha>_def: \"\\<alpha> \\<in> carrier Z\\<^sub>p \\<and>\n        Zp.to_fun (to_Zp_poly f) \\<alpha> = \\<zero>\\<^bsub>Z\\<^sub>p\\<^esub> \\<and>\n        val_Zp (Zp.to_fun (Zp.pderiv (to_Zp_poly f)) (to_Zp a))\n        < val_Zp (to_Zp a \\<ominus>\\<^bsub>Z\\<^sub>p\\<^esub> \\<alpha>) \n        \\<and> (\\<forall>x.  x \\<in> carrier Z\\<^sub>p \\<and>\n        Zp.to_fun (to_Zp_poly f) x = \\<zero>\\<^bsub>Z\\<^sub>p\\<^esub> \\<and>\n        val_Zp (Zp.to_fun (Zp.pderiv (to_Zp_poly f)) (to_Zp a))\n        < val_Zp (to_Zp a \\<ominus>\\<^bsub>Z\\<^sub>p\\<^esub> x) \\<longrightarrow> x = \\<alpha>)\"\n    using 4 by blast \n  obtain \\<beta> where \\<beta>_def: \"\\<beta> = \\<iota> \\<alpha>\"\n    by blast \n  have \\<beta>_closed: \"\\<beta> \\<in> \\<O>\\<^sub>p\"\n    using \\<alpha>_def unfolding \\<beta>_def by simp\n  have 5: \"(Zp.to_fun (to_Zp_poly f) \\<alpha>) = to_Zp (f\\<bullet>\\<beta>)\"\n    using \\<beta>_closed to_Zp_poly_eval[of f \\<beta>] assms \n    unfolding \\<beta>_def UPQ.to_fun_def \n    by (simp add: Zp.to_fun_def \\<alpha>_def inc_to_Zp)\n  have 6: \"to_Zp (f\\<bullet>\\<beta>) = \\<zero>\\<^bsub>Z\\<^sub>p\\<^esub>\"\n    using 5 \\<alpha>_def by auto \n  have \\<beta>_closed: \"\\<beta> \\<in> \\<O>\\<^sub>p\"\n    unfolding \\<beta>_def using \\<alpha>_def  by simp\n  have 7: \"(f\\<bullet>\\<beta>) = \\<zero>\"\n    using 6 assms unfolding \\<beta>_def \n    by (metis \\<beta>_closed \\<beta>_def inc_of_zero positive_gauss_norm_eval to_Zp_inc)\n  have 8: \"\\<alpha> = to_Zp \\<beta>\"\n    unfolding \\<beta>_def using \\<alpha>_def \n    by (simp add: inc_to_Zp)\n  have 9: \"to_Zp a \\<ominus>\\<^bsub>Z\\<^sub>p\\<^esub> \\<alpha> = to_Zp (a \\<ominus> \\<beta>)\"\n    unfolding 8 using assms(2) \\<beta>_closed \n    by (simp add: to_Zp_minus)\n  have 10: \"val (a \\<ominus> \\<beta>) = val_Zp (to_Zp a \\<ominus>\\<^bsub>Z\\<^sub>p\\<^esub> \\<alpha>)\"\n    unfolding 9 using \\<beta>_closed assms(2) \n    to_Zp_val val_ring_minus_closed by presburger\n  have 11: \"val (a \\<ominus> \\<beta>) > val ((pderiv f)\\<bullet>a)\"\n    using \\<alpha>_def unfolding 9 10 3 h_def \n    by (simp add: Zp.to_fun_def)\n  have 12: \"\\<beta> \\<in> \\<O>\\<^sub>p \\<and> f \\<bullet> \\<beta> = \\<zero> \\<and> val (UPQ.pderiv f \\<bullet> a) < val (a \\<ominus> \\<beta>)\"\n    using \"11\" \"7\" \\<beta>_closed by linarith\n  have 13: \"\\<forall>x. x\\<in> \\<O>\\<^sub>p \\<and> f \\<bullet> x = \\<zero> \\<and> val (UPQ.pderiv f \\<bullet> a) < val (a \\<ominus> x) \n            \\<longrightarrow> x = \\<beta>\"\n  proof(rule, rule)\n    fix x assume A: \"x \\<in> \\<O>\\<^sub>p \\<and>  f \\<bullet> x = \\<zero> \\<and> val (UPQ.pderiv f \\<bullet> a) < val (a \\<ominus> x)\"\n    obtain y where y_def: \"y = to_Zp x\"\n      by blast \n    have y_closed: \"y \\<in> carrier Z\\<^sub>p\"\n      unfolding y_def using A \n      by (simp add: to_Zp_closed val_ring_memE(2))\n    have eval: \"Zp.to_fun (to_Zp_poly f) y = \\<zero>\\<^bsub>Z\\<^sub>p\\<^esub>\"\n      unfolding y_def using A assms \n      by (metis UPQ.to_fun_def Zp.to_fun_def to_Zp_poly_eval to_Zp_zero)\n    have 0: \"to_Zp a \\<ominus>\\<^bsub>Z\\<^sub>p\\<^esub> y = to_Zp (a \\<ominus> x)\"\n      unfolding y_def using A assms \n      by (simp add: to_Zp_minus)\n    have q: \" val_Zp (Zp.to_fun (Zp.pderiv (to_Zp_poly f)) (to_Zp a)) = val (UPQ.pderiv f \\<bullet> a)\"\n      by (simp add: \"3\" Zp.to_fun_def h_def)\n    have 1: \"y \\<in> carrier Z\\<^sub>p \\<and>\n        Zp.to_fun (to_Zp_poly f) y = \\<zero>\\<^bsub>Z\\<^sub>p\\<^esub> \\<and>\n        val_Zp (Zp.to_fun (Zp.pderiv (to_Zp_poly f)) (to_Zp a))\n        < val_Zp (to_Zp a \\<ominus>\\<^bsub>Z\\<^sub>p\\<^esub> y)\"\n      unfolding 0 eval Zp.to_fun_def h_def \n      apply(intro conjI y_closed)\n      using eval Zp.to_fun_def apply (simp; fail)\n      using A unfolding 0 eval Zp.to_fun_def h_def 3 \n      using assms(2) to_Zp_val val_ring_minus_closed by presburger\n    have 2: \"y = \\<alpha>\"\n      using 1 \\<alpha>_def by blast\n    show \"x = \\<beta>\"\n      using y_def unfolding 2 8 using A \\<beta>_closed \n      by (metis to_Zp_inc)\n  qed\n  show first: \"\\<exists>!\\<alpha>. \\<alpha> \\<in> \\<O>\\<^sub>p \\<and> f \\<bullet> \\<alpha> = \\<zero> \\<and> val (UPQ.pderiv f \\<bullet> a) < val (a \\<ominus> \\<alpha>)\"\n    using 12 13 by metis\n  obtain b where b_def: \"b = to_Zp a\"\n    by blast \n  have b_closed: \"b \\<in> carrier Z\\<^sub>p\"\n    unfolding b_def \n    by (simp add: local.a_closed to_Zp_closed)\n  obtain \\<gamma> where \\<gamma>_def:\n    \"Zp.to_fun h \\<gamma> = \\<zero>\\<^bsub>Z\\<^sub>p\\<^esub>\" \"\\<gamma> \\<in> carrier Z\\<^sub>p\" \n       \"val_Zp (b \\<ominus>\\<^bsub>Z\\<^sub>p\\<^esub> \\<gamma>) > val_Zp (Zp.to_fun (Zp.pderiv h) b)\"\n       \"val_Zp (b \\<ominus>\\<^bsub>Z\\<^sub>p\\<^esub> \\<gamma>) = val_Zp (divide (Zp.to_fun h b) (Zp.to_fun (Zp.pderiv h) b))\"\n       \"val_Zp (Zp.to_fun (Zp.pderiv h) \\<gamma>) = val_Zp (Zp.to_fun (Zp.pderiv h) b)\"\n    using h_closed  b_closed  Zp_hensels_lemma[of h b] assms unfolding 2 3 h_def Zp.to_fun_def\n    unfolding b_def by auto \n  obtain \\<eta> where \\<eta>_def: \"\\<eta> = \\<iota> \\<gamma>\"\n    by blast \n  have \\<eta>_closed: \"\\<eta> \\<in> \\<O>\\<^sub>p\"\n    using \\<gamma>_def unfolding \\<eta>_def by simp\n  have 5: \"(Zp.to_fun (to_Zp_poly f) \\<gamma>) = to_Zp (f\\<bullet>\\<eta>)\"\n    using \\<eta>_closed to_Zp_poly_eval[of f \\<eta>] assms \n    unfolding \\<eta>_def UPQ.to_fun_def \n    by (simp add: Zp.to_fun_def \\<gamma>_def inc_to_Zp)\n  have 6: \"to_Zp (f\\<bullet>\\<eta>) = \\<zero>\\<^bsub>Z\\<^sub>p\\<^esub>\"\n    using 5 \\<gamma>_def h_def by auto \n  have \\<eta>_closed: \"\\<eta> \\<in> \\<O>\\<^sub>p\"\n    unfolding \\<eta>_def using \\<gamma>_def  by simp\n  have 7: \"(f\\<bullet>\\<eta>) = \\<zero>\"\n    using 6 assms unfolding \\<eta>_def \n    by (metis \\<eta>_closed \\<eta>_def inc_of_zero positive_gauss_norm_eval to_Zp_inc)\n  have 8: \"\\<gamma> = to_Zp \\<eta>\"\n    unfolding \\<eta>_def using \\<gamma>_def \n    by (simp add: inc_to_Zp)\n  have 9: \"to_Zp a \\<ominus>\\<^bsub>Z\\<^sub>p\\<^esub> \\<gamma> = to_Zp (a \\<ominus> \\<eta>)\"\n    unfolding 8 using assms(2) \\<eta>_closed \n    by (simp add: to_Zp_minus)\n  have 10: \"val (a \\<ominus> \\<eta>) = val_Zp (to_Zp a \\<ominus>\\<^bsub>Z\\<^sub>p\\<^esub> \\<gamma>)\"\n    unfolding 9 using \\<eta>_closed assms(2) \n    to_Zp_val val_ring_minus_closed by presburger\n  have p1: \"gauss_norm (UPQ.pderiv f) \\<ge> 0\"\n    using assms \n    by (meson gauss_norm_pderiv order.trans)\n  have p: \"val (f\\<bullet>a) > val ((pderiv f)\\<bullet>a)\"\n  proof- \n    have p0: \"\\<And> x (y::eint). y \\<ge> 0 \\<Longrightarrow>  x >2*y \\<Longrightarrow> x > y\"\n    proof- \n      fix x y::eint\n      have \"(y \\<ge> 0 \\<and> x >2*y) \\<longrightarrow> x > y\"\n        apply(induction x, induction y)\n          apply auto \n        apply (simp add: zero_eint_def)\n        apply(induction y) by auto \n      thus \"0 \\<le> y \\<Longrightarrow> eint 2 * y < x \\<Longrightarrow> y < x\"\n        by auto \n    qed\n    show ?thesis \n      apply(rule p0)\n      using assms p1 UPQ.pderiv_closed positive_gauss_norm_eval val_ring_memE(1) \n      by auto \n  qed\n  have 11: \"val (a \\<ominus> \\<eta>) =  val (f\\<bullet>a) - val (pderiv f\\<bullet>a)\"\n  proof- \n    have 00: \"val_Zp (divide (Zp.to_fun h b) (Zp.to_fun (Zp.pderiv h) b)) =  \n          val_Zp (Zp.to_fun h b) - val_Zp (Zp.to_fun (Zp.pderiv h) b)\"\n      apply(rule val_of_divide)\n        apply (simp add: Zp.to_fun_closed b_closed h_closed)\n      apply(unfold nonzero_def mem_Collect_eq, intro conjI )\n      using Zp.pderiv_closed Zp.to_fun_closed b_closed h_closed apply presburger\n      using \\<gamma>_def(3)  val_Zp_def apply force\n      using p unfolding 2 3 h_def Zp.to_fun_def unfolding b_def by auto \n    have 01: \"val_Zp (Zp.to_fun h b) = val (f\\<bullet>a)\"\n      using h_def b_def by (simp add: \"2\" Zp.to_fun_def)\n    have 02: \"val_Zp (Zp.to_fun (Zp.pderiv h) b) = val (pderiv f\\<bullet>a)\"\n      using \"3\" Zp.to_fun_def b_def by presburger\n    thus ?thesis using 10 \\<gamma>_def unfolding  01 02 00 \n      by (metis b_def)\n  qed\n  have 12: \"val (UPQ.pderiv f \\<bullet> a) < val (a \\<ominus> \\<eta>)\"\n  proof- \n    have p0: \"\\<And> x (y::eint). y \\<ge> 0 \\<Longrightarrow>  x >2*y \\<Longrightarrow> x - y > y\"\n    proof- \n      fix x y::eint\n      have \"(y \\<ge> 0 \\<and> x >2*y) \\<longrightarrow> x - y > y\"\n        apply(induction x, induction y)\n          apply auto \n        apply (simp add: zero_eint_def)\n        apply(induction y) by auto \n      thus \"0 \\<le> y \\<Longrightarrow> eint 2 * y < x \\<Longrightarrow> x - y > y\"\n        by auto \n    qed\n    show ?thesis \n      unfolding 11 apply(intro p0) using assms p1 \n      apply (meson UPQ.pderiv_closed dual_order.trans val_gauss_norm_eval)\n      by(rule assms)\n  qed\n  have 13: \"\\<eta> \\<in> \\<O>\\<^sub>p \\<and> f \\<bullet> \\<eta> = \\<zero> \\<and> val (UPQ.pderiv f \\<bullet> a) < val (a \\<ominus> \\<eta>) \\<and>\n                 val (a \\<ominus> \\<eta>) =  val (f\\<bullet>a) - val (pderiv f\\<bullet>a)\"\n    using \"11\" \"7\" \\<eta>_closed 12 by auto \n  have 14: \"\\<eta> = \\<beta>\"\n    using 13 \\<eta>_def \\<beta>_def \n    by (metis \"5\" \"6\" \\<alpha>_def \\<gamma>_def(2) \\<gamma>_def(3) b_def h_def)\n  have \"\\<And> \\<alpha>. \\<alpha> \\<in> \\<O>\\<^sub>p \\<and> f \\<bullet> \\<alpha> = \\<zero> \\<and> val (UPQ.pderiv f \\<bullet> a) < val (a \\<ominus> \\<alpha>) \\<and> \n            val (a \\<ominus> \\<alpha>) = val (f \\<bullet> a) - val (UPQ.pderiv f \\<bullet> a) \\<Longrightarrow> \\<alpha> = \\<eta>\"\n    unfolding 14 using 13 \\<beta>_def \n    by (metis \"14\" first)\n  thus \" \\<exists>!\\<alpha>. \\<alpha> \\<in> \\<O>\\<^sub>p \\<and>  f \\<bullet> \\<alpha> = \\<zero> \\<and> val (UPQ.pderiv f \\<bullet> a) < val (a \\<ominus> \\<alpha>) \\<and> \n                  val (a \\<ominus> \\<alpha>) = val (f \\<bullet> a) - val (UPQ.pderiv f \\<bullet> a)\"\n    using \\<eta>_def by (metis \"13\")\nqed\n\nlemma nth_root_poly_root_fixed:\n  assumes \"(n::nat) > 1\"\n  assumes \"a \\<in> \\<O>\\<^sub>p\"\n  assumes \"val (\\<one> \\<ominus>\\<^bsub>Q\\<^sub>p\\<^esub> a) > 2* val ([n]\\<cdot>\\<one>)\"\n  shows \"(\\<exists>! b \\<in> \\<O>\\<^sub>p. (b[^]n) = a \\<and>  val (b \\<ominus> \\<one>) > val ([n]\\<cdot>\\<one>))\"\nproof- \n  obtain f where f_def: \"f = up_ring.monom (UP Q\\<^sub>p) \\<one> n \\<ominus>\\<^bsub>UP Q\\<^sub>p\\<^esub> up_ring.monom (UP Q\\<^sub>p) a 0\"\n    by blast \n  have f_closed: \"f \\<in> carrier (UP Q\\<^sub>p)\"\n    unfolding f_def apply(rule UPQ.P.ring_simprules)\n     apply (simp; fail)   using assms \n    by (simp add: val_ring_memE(2))\n  have 0: \"UPQ.pderiv (up_ring.monom (UP Q\\<^sub>p) a 0) = \\<zero>\\<^bsub>UP Q\\<^sub>p\\<^esub>\"\n    using assms \n    by (simp add: val_ring_memE(2))\n  have 1: \"UPQ.pderiv (up_ring.monom (UP Q\\<^sub>p) (\\<one>) n) = (up_ring.monom (UP Q\\<^sub>p) ([n]\\<cdot>\\<one>) (n-1)) \"\n    using UPQ.pderiv_monom by blast\n  have 2: \"up_ring.monom (UP Q\\<^sub>p) \\<one> n \\<in> carrier (UP Q\\<^sub>p)\"\n    by simp\n  have 3: \"up_ring.monom (UP Q\\<^sub>p) a 0 \\<in> carrier (UP Q\\<^sub>p)\"\n    using assms val_ring_memE by simp \n  have 4: \"UPQ.pderiv f  = up_ring.monom (UP Q\\<^sub>p) ([n] \\<cdot> \\<one>) (n - 1)  \\<ominus>\\<^bsub>UP Q\\<^sub>p\\<^esub> \\<zero>\\<^bsub>UP Q\\<^sub>p\\<^esub>\"\n    using 2 3 assms val_ring_memE UPQ.pderiv_minus[of \"up_ring.monom (UP Q\\<^sub>p) \\<one> n\" \"up_ring.monom (UP Q\\<^sub>p) a 0\"]\n    unfolding f_def 0 1 by blast\n  have 5: \"UPQ.pderiv f = (up_ring.monom (UP Q\\<^sub>p) ([n]\\<cdot>\\<one>) (n-1))\"\n    unfolding 4 a_minus_def by simp\n  have a_closed: \"a \\<in> carrier Q\\<^sub>p\"\n    using assms val_ring_memE by blast \n  have 6: \"UPQ.pderiv f \\<bullet> \\<one> = [n]\\<cdot>\\<one> \\<otimes> \\<one>[^](n-1)\"\n    unfolding 5 using a_closed \n    by (simp add: UPQ.to_fun_monom)\n  have 7: \"val (\\<one> \\<ominus>\\<^bsub>Q\\<^sub>p\\<^esub> a) > val \\<one>\"\n  proof- \n    have \"eint 2 * val ([n] \\<cdot> \\<one>) \\<ge> 0\"\n      by (meson eint_ord_trans eint_pos_int_times_ge val_of_nat_inc zero_less_numeral) \n    thus ?thesis\n      using assms unfolding val_one  \n      by (simp add: Q\\<^sub>p_def)\n  qed\n  hence 8: \"val a = val \\<one>\"\n    using a_closed \n    by (metis Qp.cring_simprules(6) ultrametric_equal_eq')\n  have 9:\"val (a [^] (n - 1)) = 0\"\n    by (simp add: \"8\" local.a_closed val_zero_imp_val_pow_zero) \n  have 10: \"val ([n]\\<cdot>\\<one> \\<otimes> \\<one>[^](n-1)) = val ([n]\\<cdot>\\<one>)\"\n    unfolding val_one 9 by simp\n  have 11: \"0 \\<le> gauss_norm f\"\n  proof- \n    have p0: \"gauss_norm (up_ring.monom (UP Q\\<^sub>p) \\<one> n) \\<ge> 0\"\n      using gauss_norm_monom by simp\n    have p1: \"gauss_norm (up_ring.monom (UP Q\\<^sub>p) a 0) \\<ge> 0\"\n      using gauss_norm_monom assms val_ring_memE by simp\n    have p2: \"min (gauss_norm (up_ring.monom (UP Q\\<^sub>p) \\<one> n)) (gauss_norm (up_ring.monom (UP Q\\<^sub>p) a 0)) \\<ge> 0\"\n      using p0 p1 by simp \n    have p3: \"0 \\<le> gauss_norm\n      (up_ring.monom (UP Q\\<^sub>p) \\<one> n \\<ominus>\\<^bsub>UP Q\\<^sub>p\\<^esub> up_ring.monom (UP Q\\<^sub>p) a 0)\"\n      using gauss_norm_ultrametric'[of \"up_ring.monom (UP Q\\<^sub>p) \\<one> n\" \"up_ring.monom (UP Q\\<^sub>p) a 0\"]\n            p2  \"2\" \"3\" eint_ord_trans  by blast\n    show ?thesis using p3 unfolding f_def by simp \n  qed\n  have 12: \"\\<And>\\<alpha>. \\<alpha> \\<in> \\<O>\\<^sub>p \\<Longrightarrow> f \\<bullet> \\<alpha> = \\<alpha>[^]n \\<ominus> a\"\n    unfolding f_def using a_closed \n    by (simp add: UPQ.to_fun_const UPQ.to_fun_diff UPQ.to_fun_monic_monom val_ring_memE(2))\n  have 13: \"\\<exists>!\\<alpha>. \\<alpha> \\<in> \\<O>\\<^sub>p \\<and> f \\<bullet> \\<alpha> = \\<zero> \\<and> val (UPQ.pderiv f \\<bullet> \\<one>) < val (\\<one> \\<ominus> \\<alpha>)\"\n    apply(rule hensels_lemma, rule f_closed, rule one_in_val_ring, rule 11) \n    unfolding 6 10  \n    using a_closed assms 12[of \\<one>] assms(3) \n    by (simp add: one_in_val_ring)\n  have 14: \"\\<And>\\<alpha>. \\<alpha> \\<in> \\<O>\\<^sub>p \\<Longrightarrow> \\<alpha>[^]n = a \\<longleftrightarrow> f \\<bullet> \\<alpha> = \\<zero>\"\n    unfolding f_def using a_closed 12 f_def val_ring_memE(2) by auto\n  have 15: \"val (UPQ.pderiv f \\<bullet> \\<one>) = val ([n]\\<cdot>\\<one>)\"\n    unfolding 6 10 by auto \n  have 16: \"\\<And>\\<alpha>. \\<alpha> \\<in> \\<O>\\<^sub>p \\<Longrightarrow> val (\\<one> \\<ominus> \\<alpha>) = val (\\<alpha> \\<ominus> \\<one>)\"\n  proof- \n    have 17: \"\\<And>\\<alpha>. \\<alpha> \\<in> \\<O>\\<^sub>p \\<Longrightarrow> (\\<one> \\<ominus> \\<alpha>) = \\<ominus> (\\<alpha> \\<ominus> \\<one>)\"\n      using val_ring_memE \n      by (meson Qp.minus_a_inv Qp.one_closed)\n    show \"\\<And>\\<alpha>. \\<alpha> \\<in> \\<O>\\<^sub>p \\<Longrightarrow> val (\\<one> \\<ominus> \\<alpha>) = val (\\<alpha> \\<ominus> \\<one>)\"\n      unfolding 17 \n      using Qp.minus_closed Qp.one_closed val_minus val_ring_memE(2) by presburger\n  qed\n  show ?thesis using 13 unfolding 15 using 14 16 Qp.one_closed val_ring_memE(2) by metis   \nqed\n\nlemma mod_zeroE: \n  assumes \"(a::int) mod k  = 0\"\n  shows \"\\<exists>l. a = l*k\"\n  using assms \n  using Groups.mult_ac(2) by blast\n\nlemma to_Zp_poly_closed':\n  assumes \"g \\<in> carrier (UP Q\\<^sub>p)\"\n  assumes \"\\<And>i. g i \\<in> \\<O>\\<^sub>p\"\n  shows \"to_Zp_poly g \\<in> carrier (UP Z\\<^sub>p)\"\nproof(rule to_Zp_poly_closed)\n  show \"g \\<in> carrier (UP Q\\<^sub>p)\"\n    using assms(1) by blast \n  show \"0 \\<le> gauss_norm g\"\n  proof-\n    have \"\\<And>i. val (g i) \\<ge> 0\"\n      using assms val_ring_memE by blast \n    thus ?thesis unfolding gauss_norm_def \n      by (metis  gauss_norm_coeff_norm gauss_norm_def)\n  qed\nqed\n\nlemma to_Zp_poly_eval_to_Zp:\n  assumes \"g \\<in> carrier (UP Q\\<^sub>p)\"\n  assumes \"\\<And>i. g i \\<in> \\<O>\\<^sub>p\"\n  assumes \"a \\<in> \\<O>\\<^sub>p\"\n  shows \"to_function Z\\<^sub>p (to_Zp_poly g) (to_Zp a) = to_Zp (g \\<bullet> a)\"\nproof- \n  have \"(\\<forall>i. g i \\<in> \\<O>\\<^sub>p) \\<longrightarrow> to_function Z\\<^sub>p (to_Zp_poly g) (to_Zp a) = to_Zp (g \\<bullet> a)\"\n    apply(rule UPQ.poly_induct[of g]) using assms apply blast\n  proof \n    fix p assume A: \"p \\<in> carrier (UP Q\\<^sub>p)\" \"deg Q\\<^sub>p p = 0\" \"\\<forall>i. p i \\<in> \\<O>\\<^sub>p\"\n    obtain c where c_def: \"c \\<in> carrier Q\\<^sub>p \\<and> p = up_ring.monom (UP Q\\<^sub>p) c  0\"\n      using A  by (metis UPQ.ltrm_deg_0 val_ring_memE(2))\n    have 0: \"to_Zp_poly (up_ring.monom (UP Q\\<^sub>p) c  0) = up_ring.monom (UP Z\\<^sub>p) (to_Zp c) 0\"\n      unfolding to_Zp_poly_def proof fix n show \" to_Zp (up_ring.monom (UP Q\\<^sub>p) c 0 n) = up_ring.monom (UP Z\\<^sub>p) (to_Zp c) 0 n\"\n        using UP_ring.cfs_monom[of Z\\<^sub>p \"to_Zp c\" 0 n] UP_ring.cfs_monom[of Q\\<^sub>p c 0 n] to_Zp_closed[of c ]\n        unfolding UP_ring_def \n        apply(cases \"0 = n\")\n        using UPQ.cfs_monom Zp.cfs_monom c_def apply presburger\n         using UPQ.cfs_monom Zp.cfs_monom c_def \n         using to_Zp_zero by presburger\n    qed    \n    have p_eq: \"p = up_ring.monom (UP Q\\<^sub>p) c  0\"\n      using c_def by blast \n    have 1: \"(up_ring.monom (UP Q\\<^sub>p) c 0 \\<bullet> a) = c\"\n      using UPQ.to_fun_to_poly[of c a]  c_def assms val_ring_memE \n      unfolding to_polynomial_def  by blast \n    show \"to_function Z\\<^sub>p (to_Zp_poly p) (to_Zp a) = to_Zp (p \\<bullet> a)\"\n      using c_def assms(3) val_ring_memE(2)[of a]\n      UP_cring.to_fun_to_poly[of Z\\<^sub>p \"to_Zp c\" \"to_Zp a\"]\n      unfolding p_eq 0 1 Zp.to_fun_def to_polynomial_def  \n      using Zp.UP_cring_axioms to_Zp_closed by blast\n  next  \n    show \"\\<And>p. (\\<And>q. q \\<in> carrier (UP Q\\<^sub>p) \\<Longrightarrow>\n              deg Q\\<^sub>p q < deg Q\\<^sub>p p \\<Longrightarrow> (\\<forall>i. q i \\<in> \\<O>\\<^sub>p) \\<longrightarrow> to_function Z\\<^sub>p (to_Zp_poly q) (to_Zp a) = to_Zp (q \\<bullet> a)) \\<Longrightarrow>\n         p \\<in> carrier (UP Q\\<^sub>p) \\<Longrightarrow> 0 < deg Q\\<^sub>p p \\<Longrightarrow> (\\<forall>i. p i \\<in> \\<O>\\<^sub>p) \\<longrightarrow> to_function Z\\<^sub>p (to_Zp_poly p) (to_Zp a) = to_Zp (p \\<bullet> a)\"\n    proof  fix p \n      assume A: \"(\\<And>q. q \\<in> carrier (UP Q\\<^sub>p) \\<Longrightarrow>\n              deg Q\\<^sub>p q < deg Q\\<^sub>p p \\<Longrightarrow> (\\<forall>i. q i \\<in> \\<O>\\<^sub>p) \\<longrightarrow> to_function Z\\<^sub>p (to_Zp_poly q) (to_Zp a) = to_Zp (q \\<bullet> a))\"\n            \"p \\<in> carrier (UP Q\\<^sub>p)\" \"0 < deg Q\\<^sub>p p\" \"\\<forall>i. p i \\<in> \\<O>\\<^sub>p\"\n      show \"to_function Z\\<^sub>p (to_Zp_poly p) (to_Zp a) = to_Zp (p \\<bullet> a)\"\n      proof- \n        obtain q where q_def: \"q = truncate Q\\<^sub>p  p\"\n          by blast \n        have  q_closed: \"q \\<in> carrier (UP Q\\<^sub>p)\"\n          unfolding q_def by(rule UPQ.trunc_closed, rule A)\n        obtain c where c_def: \"c = UPQ.lcf p\"\n          by blast \n        obtain n where n_def: \"n = deg Q\\<^sub>p p\"\n          by blast \n        have 0: \"p = q \\<oplus>\\<^bsub>UP Q\\<^sub>p\\<^esub> up_ring.monom (UP Q\\<^sub>p) c n\"\n          unfolding c_def n_def q_def \n          using A(2) UPQ.trunc_simps(1) by blast\n        have 1: \"up_ring.monom (UP Q\\<^sub>p) c n \\<in> carrier  (UP Q\\<^sub>p)\"\n          using A(2) UPQ.ltrm_closed c_def n_def by blast\n        have 2: \"p \\<bullet> a  = q  \\<bullet> a \\<oplus> (c \\<otimes> a[^]n)\"\n          unfolding 0 using assms val_ring_memE  \n          by (metis \"1\" A(4) UPQ.to_fun_monom UPQ.to_fun_plus c_def q_closed)\n        have 3: \"\\<And>i. i < n \\<Longrightarrow> q i = p i\"\n          unfolding n_def q_def \n          using A(2) UPQ.trunc_cfs by blast\n        have 4: \"deg Q\\<^sub>p q < n\"\n          unfolding n_def q_def using A\n          using UPQ.trunc_degree by presburger\n        have 5: \"\\<And>i. i \\<ge> n \\<Longrightarrow> i >  deg Q\\<^sub>p q\"\n          using A[of ] less_le_trans[of \"deg Q\\<^sub>p q\" \"deg Q\\<^sub>p p\"] unfolding q_def n_def  \n          using \"4\" n_def q_def by blast\n        have 6: \"\\<And>i. i \\<ge> n \\<Longrightarrow> q i = \\<zero>\"\n          using q_closed 5 UPQ.deg_leE by blast\n        have 7: \"(\\<forall>i. q i \\<in> \\<O>\\<^sub>p) \\<longrightarrow> to_function Z\\<^sub>p (to_Zp_poly q) (to_Zp a) = to_Zp (q \\<bullet> a)\"\n          apply(rule   A) unfolding q_def \n          using q_closed q_def apply blast\n          using \"4\" n_def q_def by blast\n        have 8: \"(\\<forall>i. q i \\<in> \\<O>\\<^sub>p)\"\n        proof fix i show \"q i \\<in> \\<O>\\<^sub>p\" apply(cases \"i < n\") \n            using 3 A(4) apply blast using 6[of i] \n            by (metis less_or_eq_imp_le linorder_neqE_nat zero_in_val_ring)\n        qed\n        have 9: \"to_function Z\\<^sub>p (to_Zp_poly q) (to_Zp a) = to_Zp (q \\<bullet> a)\"\n          using 7 8 by blast \n        have 10: \"to_Zp_poly p = to_Zp_poly q \\<oplus>\\<^bsub>UP Z\\<^sub>p\\<^esub> to_Zp_poly (up_ring.monom (UP Q\\<^sub>p) c n)\"\n        proof fix x  \n          have 100: \"to_Zp_poly (up_ring.monom (UP Q\\<^sub>p) c n) = (up_ring.monom (UP Z\\<^sub>p) (to_Zp c) n)\"\n            using to_Zp_poly_monom[of c] A(4) c_def by blast\n          have 101: \"deg Z\\<^sub>p (to_Zp_poly q) \\<le> n-1\"\n              apply(rule  UP_cring.deg_leqI)\n              unfolding UP_cring_def using Zp.R_cring apply auto[1]\n              using to_Zp_poly_closed' 8 q_closed apply blast\n              unfolding to_Zp_poly_def using 4 6 \n              by (simp add: to_Zp_zero) \n          have 102: \"(to_Zp_poly q) \\<in> carrier (UP Z\\<^sub>p)\"\n            apply(rule to_Zp_poly_closed', rule q_closed) using 8 by blast \n          have 103: \"deg Z\\<^sub>p (to_Zp_poly q) < n\"\n            using 101 4 by linarith\n            have T0: \"(to_Zp_poly q \\<oplus>\\<^bsub>UP Z\\<^sub>p\\<^esub> to_Zp_poly (up_ring.monom (UP Q\\<^sub>p) c n)) x = \n                    (to_Zp_poly q x) \\<oplus>\\<^bsub>Z\\<^sub>p\\<^esub> (to_Zp_poly (up_ring.monom (UP Q\\<^sub>p) c n) x)\"\n              apply(rule  UP_ring.cfs_add)\n              unfolding UP_ring_def apply (simp add: Zp.is_ring)\n               apply(rule 102) unfolding 100 apply(rule UP_ring.monom_closed)\n              unfolding UP_ring_def apply (simp add: Zp.is_ring)\n              apply(rule  to_Zp_closed ) unfolding c_def \n              using A(2) UPQ.UP_car_memE(1) by blast\n            have c_closed: \"c \\<in> \\<O>\\<^sub>p\"\n              unfolding c_def  using A(4) by blast\n            have to_Zp_c_closed: \"to_Zp c \\<in> carrier Z\\<^sub>p\"\n              using c_closed to_Zp_closed val_ring_memE(2) by blast\n          show \"to_Zp_poly p x = (to_Zp_poly q \\<oplus>\\<^bsub>UP Z\\<^sub>p\\<^esub> to_Zp_poly (up_ring.monom (UP Q\\<^sub>p) c n)) x\"\n          proof(cases \"x < n\")\n            case True\n            have T1: \"(to_Zp_poly (up_ring.monom (UP Q\\<^sub>p) c n) x) = \\<zero>\\<^bsub>Z\\<^sub>p\\<^esub>\"\n              using True UP_ring.cfs_monom[of Z\\<^sub>p] unfolding UP_ring_def \n              by (metis \"100\" A(2) UPQ.cfs_closed UPQ.deg_leE Zp.is_ring c_def n_def to_Zp_closed to_Zp_zero)\n            have T2: \"to_Zp (p x) = to_Zp (q x)\" using 3[of x] True by smt \n            have T3: \"to_Zp (p x) \\<in> carrier Z\\<^sub>p\"\n              apply(rule to_Zp_closed) using A(2) UPQ.UP_car_memE(1) by blast\n            show ?thesis using T3 \n              unfolding T0  unfolding T1 unfolding  to_Zp_poly_def  T2  \n              using Zp.cring_simprules(8) add_comm by presburger\n          next\n            case False\n            have F: \"q x = \\<zero> \"\n              using False  \n              by (metis \"6\" less_or_eq_imp_le linorder_neqE_nat)\n            have F': \"(to_Zp_poly q) x = \\<zero>\\<^bsub>Z\\<^sub>p\\<^esub>\"\n             unfolding to_Zp_poly_def F using to_Zp_zero by blast\n            show \"to_Zp_poly p x = (to_Zp_poly q \\<oplus>\\<^bsub>UP Z\\<^sub>p\\<^esub> to_Zp_poly (up_ring.monom (UP Q\\<^sub>p) c n)) x\"\n            proof(cases \"x = n\")\n              case True\n              have T1: \"to_Zp (p x) \\<in> carrier Z\\<^sub>p\"\n                apply(rule to_Zp_closed)\n                using A(2) UPQ.UP_car_memE(1) by blast\n              have T2: \"(to_Zp_poly (up_ring.monom (UP Q\\<^sub>p) c n) x) = to_Zp c\"\n                unfolding 100 using UP_ring.cfs_monom[of Z\\<^sub>p \"to_Zp c\" n n] unfolding UP_ring_def True\n                using Zp.is_ring to_Zp_c_closed by presburger\n              show ?thesis using to_Zp_c_closed unfolding T0 F' T2 unfolding to_Zp_poly_def True c_def n_def\n                using Zp.cring_simprules(8) by presburger\n            next\n              case FF: False\n              have F0: \"p x = \\<zero>\"\n                using FF False unfolding n_def \n                using A(2) UPQ.UP_car_memE(2) linorder_neqE_nat by blast\n              have F1: \"q x = \\<zero>\"\n                using FF False F by linarith\n              have F2: \"(up_ring.monom (UP Q\\<^sub>p) c n) x = \\<zero>\"\n                using FF False A(2) UPQ.cfs_closed UPQ.cfs_monom c_def by presburger\n              show ?thesis unfolding T0 unfolding to_Zp_poly_def F0 F1 F2\n                using Zp.r_zero Zp.zero_closed to_Zp_zero by presburger\n            qed\n          qed\n        qed\n        have 11: \"deg Z\\<^sub>p (to_Zp_poly q) \\<le> n-1\"\n          apply(rule  UP_cring.deg_leqI)\n          unfolding UP_cring_def using Zp.R_cring apply auto[1]\n          using to_Zp_poly_closed' 8 q_closed apply blast\n          unfolding to_Zp_poly_def using 4 6 \n          by (smt diff_commute diff_diff_cancel less_one less_or_eq_imp_le linorder_neqE_nat to_Zp_zero zero_less_diff)\n        have 12: \"(to_Zp_poly q) \\<in> carrier (UP Z\\<^sub>p)\"\n          apply(rule to_Zp_poly_closed', rule q_closed) using 8 by blast \n        have 13: \"deg Z\\<^sub>p (to_Zp_poly q) < n\"\n          using 11 4 by linarith\n        have 14: \"to_Zp_poly (up_ring.monom (UP Q\\<^sub>p) c n) = (up_ring.monom (UP Z\\<^sub>p) (to_Zp c) n)\"\n          using to_Zp_poly_monom[of c] A(4) c_def by blast\n        have 15: \"Zp.to_fun (to_Zp_poly q \\<oplus>\\<^bsub>UP Z\\<^sub>p\\<^esub> to_Zp_poly (up_ring.monom (UP Q\\<^sub>p) c n)) (to_Zp a)= \n            Zp.to_fun (to_Zp_poly q) (to_Zp a) \\<oplus>\\<^bsub>Z\\<^sub>p\\<^esub> Zp.to_fun (to_Zp_poly (up_ring.monom (UP Q\\<^sub>p) c n)) (to_Zp a)\"\n          apply(rule Zp.to_fun_plus)\n          unfolding 14  apply(rule UP_ring.monom_closed) \n          unfolding UP_ring_def using Zp.is_ring apply auto[1]\n          apply(rule to_Zp_closed) unfolding c_def \n          using A(2) UPQ.cfs_closed apply blast\n          using 12 apply blast \n          apply(rule to_Zp_closed) using assms val_ring_memE by blast \n        have 16: \"to_Zp (q \\<bullet> a \\<oplus> c \\<otimes> a [^] n) = to_Zp (q \\<bullet> a)  \\<oplus>\\<^bsub>Z\\<^sub>p\\<^esub> to_Zp (c \\<otimes> a [^] n)\"\n          apply(rule to_Zp_add)\n           apply(rule val_ring_poly_eval, rule q_closed) \n            using \"8\" apply blast\n             apply(rule assms)\n            apply(rule val_ring_times_closed)\n            unfolding c_def using A(4) apply blast\n          by(rule val_ring_nat_pow_closed, rule assms)\n        have  17: \" to_function Z\\<^sub>p (up_ring.monom (UP Z\\<^sub>p) (to_Zp c) n) (to_Zp a) =  to_Zp (c \\<otimes> a [^] n)\"\n          proof-\n            have 170: \"to_Zp (c \\<otimes> a [^] n) = to_Zp c \\<otimes>\\<^bsub>Z\\<^sub>p\\<^esub> to_Zp (a [^] n)\"\n              apply(rule  to_Zp_mult[of c \"a[^]n\"])\n              unfolding c_def using A(4) apply blast\n              by(rule val_ring_nat_pow_closed, rule assms)\n            have 171: \"to_Zp (a [^] n) = (to_Zp a [^]\\<^bsub>Z\\<^sub>p\\<^esub>n)\"\n              by(rule to_Zp_nat_pow, rule assms)\n            have 172: \"to_Zp c \\<in> carrier Z\\<^sub>p \"\n              apply(rule to_Zp_closed) unfolding c_def \n              using A(2) UPQ.UP_car_memE(1) by blast\n            have 173: \"to_Zp a \\<in> carrier Z\\<^sub>p \"\n              apply(rule to_Zp_closed) using assms val_ring_memE by blast  \n            show ?thesis\n              using 172 173 Zp.to_fun_monom[of \"to_Zp c\" \"to_Zp a\" n] unfolding Zp.to_fun_def 170 171\n              by blast \n        qed\n        show ?thesis\n          using 15 unfolding Zp.to_fun_def 10 2 16 9 unfolding 14 17\n          by blast \n      qed\n    qed\n  qed\n  thus ?thesis using assms by blast \nqed\n\nlemma inc_nat_pow:\n  assumes \"a \\<in> carrier Z\\<^sub>p\"\n  shows \"\\<iota> ([(n::nat)] \\<cdot>\\<^bsub>Z\\<^sub>p\\<^esub>a) = [n]\\<cdot>(\\<iota> a)\"\n  apply(induction n)\n  apply (metis Q\\<^sub>p_def Qp.int_inc_zero Qp.nat_mult_zero Zp.add.nat_pow_0 Zp_int_inc_zero' \\<iota>_def frac_inc_of_int)\n  unfolding Qp.add.nat_pow_Suc Zp.add.nat_pow_Suc \n  using Zp_nat_mult_closed assms inc_of_sum by presburger\n  \nlemma poly_inc_pderiv:\n  assumes \"g \\<in> carrier (UP Z\\<^sub>p)\"\n  shows \"poly_inc (Zp.pderiv g) = UPQ.pderiv (poly_inc g)\"\nproof fix x\n  have 0: \"UPQ.pderiv (poly_inc g) x = [Suc x] \\<cdot> poly_inc g (Suc x)\"\n    apply(rule UPQ.pderiv_cfs[of \"poly_inc g\" x])\n    by(rule poly_inc_closed, rule assms)\n  have 1: \"Zp.pderiv g x = [Suc x] \\<cdot>\\<^bsub>Z\\<^sub>p\\<^esub> g (Suc x)\"\n    by(rule Zp.pderiv_cfs[of g x], rule assms)\n  show \"poly_inc (Zp.pderiv g) x = UPQ.pderiv (poly_inc g) x\"\n    unfolding 0  unfolding poly_inc_def 1 apply(rule  inc_nat_pow)\n    using Zp.UP_car_memE(1) assms by blast\nqed\n\n\n\nend\nend\n", "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/Padic_Field/Padic_Field_Polynomials.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8740772286044095, "lm_q2_score": 0.855851143290548, "lm_q1q2_score": 0.7480799954253176}}
{"text": "theory Linorder_Insts imports Main\nbegin\n\n(* Instances of Linorder (built-in typeclass for linear orderings with a trichotomy law)\n * for several types, intended for use with Oalist *)\n\ninstantiation prod :: (linorder, linorder) linorder\nbegin\n\ndefinition prod_lo_leq :\n\"p1 \\<le> p2 =\n  (fst p1 < fst p2 \\<or> \n  (fst p1 = fst p2 \\<and> snd p1 \\<le> snd p2))\"\n\ndefinition prod_lo_lt :\n\"p1 < p2 =\n  (fst p1 < fst p2 \\<or>\n  (fst p1 = fst p2 \\<and> snd p1 < snd p2))\"\n\ninstance proof\n  fix x y :: \"('a * 'b)\"\n  show \"(x < y) = (x \\<le> y \\<and> \\<not> y \\<le> x)\"\n    by(cases x; cases y; auto simp add:prod_lo_leq prod_lo_lt)\nnext\n  fix x :: \"('a * 'b)\"\n  show \"x \\<le> x\"\n    by(cases x; auto simp add:prod_lo_leq)\nnext\n  fix x y z :: \"('a * 'b)\"\n  show \"x \\<le> y \\<Longrightarrow> y \\<le> z \\<Longrightarrow> x \\<le> z\"\n    by(cases x; cases y; cases z; auto simp add:prod_lo_leq)\nnext\n  fix x y :: \"('a * 'b)\"\n  show \"x \\<le> y \\<Longrightarrow> y \\<le> x \\<Longrightarrow> x = y\"\n    by(cases x; cases y; auto simp add:prod_lo_leq prod_lo_lt)\nnext\n  fix x y :: \"('a * 'b)\"\n  show \"x \\<le> y \\<or> y \\<le> x\"\n    by(cases x; cases y; auto simp add:prod_lo_leq prod_lo_lt)\nqed\nend\n\nfun list_lo_leq' ::\n  \"('a :: linorder) list \\<Rightarrow> ('a :: linorder) list \\<Rightarrow> bool\" where\n\"list_lo_leq' [] _ = True\"\n| \"list_lo_leq' (h#t) [] = False\"\n| \"list_lo_leq' (h1#t1) (h2#t2) =\n   (h1 < h2 \\<or>\n   (h1 = h2 \\<and> list_lo_leq' t1 t2))\"\n\nfun list_lo_lt' ::\n  \"('a :: linorder) list \\<Rightarrow> ('a :: linorder) list \\<Rightarrow> bool\" where\n\"list_lo_lt' [] [] = False\"\n| \"list_lo_lt' [] (h#t) = True\"\n| \"list_lo_lt' (h#t) [] = False\"\n| \"list_lo_lt' (h1#t1) (h2#t2) =\n   (h1 < h2 \\<or>\n   (h1 = h2 \\<and> list_lo_lt' t1 t2))\"\n\n\nlemma list_lo_lt'_imp_leq' :\n\"list_lo_lt' l1 l2 \\<Longrightarrow> list_lo_leq' l1 l2\"\nproof(induction l1 arbitrary: l2)\n  case Nil\n  then show ?case by auto\nnext\n  case (Cons a l1)\n  then show ?case \n    by(cases l2; auto)\nqed\n\nlemma list_lo_lt'_nosym :\n  \"list_lo_lt' l1 l2 \\<Longrightarrow> list_lo_lt' l2 l1 \\<Longrightarrow> False\"\nproof(induction l1 arbitrary: l2)\n  case Nil\n  then show ?case by(cases l2; auto)\nnext\n  case (Cons a l1)\n  then show ?case by(cases l2; auto)\nqed\n\nlemma list_lo_lt'_irref :\n  \"list_lo_lt' l l \\<Longrightarrow> False\"\nproof(induction l)\n  case Nil\n  then show ?case by auto\nnext\n  case (Cons a l)\n  then show ?case by auto\nqed\n\nlemma list_lo_leq'_lt'_or_eq :\n  \"list_lo_leq' l1 l2 \\<Longrightarrow>\n   list_lo_lt' l1 l2 \\<or> l1 = l2\"\nproof(induction l1 arbitrary: l2)\n  case Nil\n  then show ?case by(cases l2; auto)\nnext\n  case (Cons a l1)\n  then show ?case\n    by(cases l2; auto)\nqed\n\ninstantiation list :: (linorder) linorder\nbegin\n\ndefinition list_lo_leq :\n\"l1 \\<le> l2 = list_lo_leq' l1 l2\"\n\ndefinition list_lo_lt :\n\"l1 < l2 = list_lo_lt' l1 l2\"\n\ninstance proof\n  fix x y :: \"'a list\"\n\n  have L2R_1 : \"x < y \\<Longrightarrow> x \\<le> y\" \n    unfolding list_lo_leq list_lo_lt using list_lo_lt'_imp_leq' by auto\n\n  have L2R_2 : \"x < y \\<Longrightarrow> \\<not> y \\<le> x\"\n    unfolding list_lo_leq list_lo_lt\n  proof\n    assume HC1 : \"list_lo_lt' x y\"\n    assume HC2 : \"list_lo_leq' y x\"\n\n    consider (1) \"list_lo_lt' y x\" | (2) \"x = y\"\n      using list_lo_leq'_lt'_or_eq[OF HC2]  by auto\n    then show False\n    proof cases\n      case 1\n      then show ?thesis using list_lo_lt'_nosym[OF HC1 1] by auto\n    next\n      case 2\n      then show ?thesis using HC1 list_lo_lt'_irref[of x] by auto\n    qed\n  qed\n\n  show \"(x < y) = (x \\<le> y \\<and> \\<not> y \\<le> x)\" using L2R_1 L2R_2 list_lo_leq'_lt'_or_eq[of x y]\n    unfolding list_lo_leq list_lo_lt\n    by(blast)\nnext\n  fix x :: \"'a list\"\n  show \"x \\<le> x\"\n  proof(induction x)\n    case Nil\n    then show ?case by(auto simp add:list_lo_leq)\n  next\n    case (Cons a x)\n    then show ?case by(auto simp add:list_lo_leq)\n  qed\nnext\n  fix x y z :: \"'a list\"\n  show \"x \\<le> y \\<Longrightarrow> y \\<le> z \\<Longrightarrow> x \\<le> z\"\n  proof(induction x arbitrary: y z)\n    case Nil\n    then show ?case by(auto simp add:list_lo_leq)\n  next\n    case (Cons a x)\n    then show ?case \n      by(cases y; cases z; auto simp add:list_lo_leq)\n  qed\nnext\n  fix x y :: \"'a list\"\n  show \"x \\<le> y \\<Longrightarrow> y \\<le> x \\<Longrightarrow> x = y\"\n  proof(induction x arbitrary: y)\n    case Nil\n    then show ?case by(cases y; auto simp add: list_lo_leq)\n  next\n    case (Cons a x)\n    then show ?case by(cases y; auto simp add: list_lo_leq)\n  qed\nnext\n  fix x y :: \"'a list\"\n  show \"x \\<le> y \\<or> y \\<le> x\"\n  proof(induction x arbitrary: y)\n    case Nil\n    then show ?case by(cases y; auto simp add: list_lo_leq)\n  next\n    case (Cons a x)\n    then show ?case by(cases y; auto simp add: list_lo_leq)\n  qed\nqed\nend\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/Linorder_Insts.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392909114836, "lm_q2_score": 0.84594244507642, "lm_q1q2_score": 0.747846359297285}}
{"text": "theory Unification\n  imports Main\nbegin\n\nsection \\<open> Assignment 1 \\<close>\n\ndatatype ('f, 'v) \"term\" = Var 'v | Fun 'f \"('f, 'v) term list\"\n\ntext \\<open> (a) \\<close>\n\nfun fv :: \"(('f, 'v) term \\<Rightarrow> 'v set)\" where\n  \"fv (Var x) = { x }\" |\n  \"fv (Fun f lst) = \\<Union>(set (map fv lst))\"\n\ntext \\<open> (b) \\<close>\n\ntype_synonym ('f, 'v) subst = \"'v \\<Rightarrow> ('f, 'v) term\"\n\nfun sapply :: \"('f, 'v) subst \\<Rightarrow> ('f, 'v) term \\<Rightarrow> ('f, 'v) term\" \n  (infixr \"\\<cdot>\" 67) where\n    \"sapply \\<sigma> (Var x) = \\<sigma> x\" |\n    \"sapply \\<sigma> (Fun f ts) = Fun f (map (sapply \\<sigma>) ts)\"\n\ndefinition scomp :: \"('f, 'v) subst \\<Rightarrow> ('f, 'v) subst \\<Rightarrow> ('f, 'v) subst\"\n  (infixr \"\\<circ>s\" 75) where\n    \"(scomp \\<sigma> \\<tau>) x = sapply \\<sigma> (\\<tau> x)\"\n\ntext \\<open> (c) \\<close>\n\nlemma fv_sapply: \"fv (\\<sigma> \\<cdot> t) = (\\<Union> x \\<in> fv t. fv (\\<sigma> x))\"\n  apply(induction t rule: fv.induct)\n  by(simp_all)\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(simp_all)\n  by(blast)\n\nlemma scomp_sapply: \"(\\<sigma> \\<circ>s \\<tau>)x = \\<sigma> \\<cdot> (\\<tau> x)\"\n  by(simp add: scomp_def)\n  \nlemma sapply_scomp_distrib: \"(\\<sigma> \\<circ>s \\<tau>) \\<cdot> t = \\<sigma> \\<cdot> (\\<tau> \\<cdot> t)\"\n  apply(induction t)\n  by(simp_all add: scomp_def)\n  \nlemma scomp_assoc: \"(\\<sigma> \\<circ>s \\<tau>) \\<circ>s \\<rho> = \\<sigma> \\<circ>s (\\<tau> \\<circ>s \\<rho>)\"\n  by(simp add: fun_eq_iff scomp_def sapply_scomp_distrib)\n  \nlemma sapply_Var[simp]: \"Var \\<cdot> t = t\"\n  apply(induction t)\n  by(simp_all add: map_idI)\n  \nlemma scomp_Var[simp]: \"\\<sigma> \\<circ>s Var = \\<sigma>\"\n  by(simp add: fun_eq_iff scomp_def)\n\nlemma Var_scomp[simp]: \"Var \\<circ>s \\<sigma> = \\<sigma>\"\n  by(simp add: fun_eq_iff scomp_def)\n  \n\ntext \\<open> (d) \\<close>\n\ndefinition sdom :: \"('f, 'v) subst \\<Rightarrow> 'v set\" where\n  \"sdom \\<sigma> = { x . (\\<sigma> x) \\<noteq> (Var x)}\"\n\ndefinition svran :: \"('f, 'v) subst \\<Rightarrow> 'v set\" where\n  \"svran \\<sigma> = \\<Union>(fv ` (\\<sigma> ` sdom \\<sigma>))\"\n\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)\n  \nlemma sdom_single_non_trivial[simp]:\n  \"t \\<noteq> Var x \\<Longrightarrow> sdom (Var( x := t )) = {x}\"\n  by(simp add: fun_upd_def sdom_def)\n    \nlemma svran_single_non_trivial[simp]:\n  \"t \\<noteq> Var x \\<Longrightarrow> svran (Var( x := t )) = fv t\"\n  by(simp add: fun_upd_def svran_def sdom_def)\n\nlemma svapply_svdom_svran:\n  \"x \\<in> fv (\\<sigma> \\<cdot> t) \\<Longrightarrow> x \\<in> (fv t - sdom \\<sigma>) \\<union> svran \\<sigma>\"\n  apply(induction t)\n   apply(simp_all add: svran_def sdom_def)\n   apply(metis fv.simps(1) singletonD)\n  by(blast)\n\nlemma sdom_scomp: \"sdom (\\<sigma> \\<circ>s \\<tau>) \\<subseteq> sdom \\<sigma> \\<union> sdom \\<tau>\"\n  apply(simp add: sdom_def scomp_def)\n  by(auto)\n  \n\nlemma svran_scomp: \"svran (\\<sigma> \\<circ>s \\<tau>) \\<subseteq> svran \\<sigma> \\<union> svran \\<tau>\"\n  apply(simp add: svran_def scomp_def fv_sapply sdom_def)\n  by(force)\n  \n\nsection \\<open> Assignment 2 \\<close>\n  \ntext \\<open> (a) \\<close>\n\ntype_synonym ('f, 'v) equation = \"('f, 'v) term \\<times> ('f, 'v) term\"\ntype_synonym ('f, 'v) equations = \"('f, 'v) equation list\"\n\ndefinition fv_eq :: \"('f, 'v) equation \\<Rightarrow> 'v set\" where\n  \"fv_eq eq = (fv (fst eq)) \\<union> (fv (snd eq))\"\n\nfun fv_eqs :: \"('f, 'v) equations \\<Rightarrow> 'v set\" where\n  \"fv_eqs [] = {}\"\n| \"fv_eqs (eq#s) = (fv_eq eq) \\<union> (fv_eqs s)\"\n\nlemma fv_eqs_U: \"fv_eqs eqs = \\<Union>(fv_eq ` set eqs)\"\n  apply(induction eqs)\n  by simp_all\n\ndefinition sapply_eq :: \"('f, 'v) subst \\<Rightarrow> ('f, 'v) equation \\<Rightarrow> ('f, 'v) equation\" \n  (infixr \"\\<cdot>e\" 67) where\n    \"sapply_eq \\<sigma> eq = (sapply \\<sigma> (fst eq), sapply \\<sigma> (snd eq))\"\n\nfun sapply_eqs :: \"('f, 'v) subst \\<Rightarrow> ('f, 'v) equations \\<Rightarrow> ('f, 'v) equations\" \n  (infixr \"\\<cdot>s\" 67) where\n    \"sapply_eqs \\<sigma> [] = []\"\n|   \"sapply_eqs \\<sigma> (eq#s) = (sapply_eq \\<sigma> eq) # (sapply_eqs \\<sigma> s)\"\n\nlemma sapply_eqs_map: \"sapply_eqs \\<sigma> eqs = map (sapply_eq \\<sigma>) eqs\"\n  apply(induction eqs)\n  by(simp_all)\n\nlemma fv_sapply_eq: \"fv_eq (\\<sigma> \\<cdot>e e) = (\\<Union> x \\<in> fv_eq e. fv (\\<sigma> x))\"\n  by(simp add: fv_eq_def sapply_eq_def fv_sapply)\n  \nlemma fv_sapply_eqs: \"fv_eqs (\\<sigma> \\<cdot>s s) = (\\<Union> x \\<in> fv_eqs s. fv (\\<sigma> x))\"\n  apply(induction rule: sapply_eqs.induct)\n   apply(simp)\n  by(simp add: fv_sapply_eq)\n  \nlemma sapply_scomp_distrib_eq: \"(\\<sigma> \\<circ>s \\<tau>) \\<cdot>e eq = \\<sigma> \\<cdot>e (\\<tau> \\<cdot>e eq)\"\n  by(simp add: sapply_eq_def sapply_scomp_distrib)\n  \nlemma sapply_scomp_distrib_eqs: \"(\\<sigma> \\<circ>s \\<tau>) \\<cdot>s eqs = \\<sigma> \\<cdot>s (\\<tau> \\<cdot>s eqs)\"\n  apply(induction eqs)\n   apply(simp)\n  by(simp add: sapply_scomp_distrib_eq)\n  \ntext \\<open> (b) \\<close>\n\ndefinition unifies_eq :: \"('f, 'v) subst \\<Rightarrow> ('f, 'v) equation \\<Rightarrow> bool\" where\n  \"(unifies_eq \\<sigma> eq) \\<longleftrightarrow> (\\<sigma> \\<cdot> (fst eq) = \\<sigma> \\<cdot> (snd eq))\"\n\nfun unifies :: \"('f, 'v) subst \\<Rightarrow> ('f, 'v) equations \\<Rightarrow> bool\" where\n  \"(unifies \\<sigma> []) = True\"\n| \"(unifies \\<sigma> (eq#s)) = ((unifies_eq \\<sigma> eq) \\<and> unifies \\<sigma> s)\"\n\nlemma unifies_forall: \"unifies \\<sigma> lst = (\\<forall>eq \\<in> set lst . unifies_eq \\<sigma> eq)\"\n  apply(induction lst)\n  by(simp_all)\n\ndefinition is_mgu :: \"('f, 'v) subst \\<Rightarrow> ('f, 'v) equations \\<Rightarrow> bool\" where\n  \"(is_mgu \\<sigma> eqs) = ((unifies \\<sigma> eqs) \\<and> (\\<forall> \\<tau>. (unifies \\<tau> eqs) \\<longrightarrow> (\\<exists> \\<rho> . \\<tau> = \\<rho> \\<circ>s \\<sigma>)))\"\n\ntext \\<open> (c) \\<close>\n\nlemma unifies_sapply_eq: \"unifies_eq \\<sigma> (\\<tau> \\<cdot>e eq) \\<longleftrightarrow> unifies_eq (\\<sigma> \\<circ>s \\<tau>) eq\"\n  by(simp add: sapply_eq_def unifies_eq_def sapply_scomp_distrib)\n  \nlemma unifies_sapply: \"unifies \\<sigma> (\\<tau> \\<cdot>s eqs) \\<longleftrightarrow> unifies (\\<sigma> \\<circ>s \\<tau>) eqs\"\n  apply(induction eqs)\n  by(simp_all add: unifies_sapply_eq)\n  \nsection \\<open> Assignment 3 \\<close>\n\ntext \\<open> (a) \\<close>\n\n(*Termination definitions and lemmas*)\nfun tsize :: \"('f, 'v) term \\<Rightarrow> nat\" where\n  \"tsize (Var x) = 0\"\n| \"tsize (Fun f l) = 1 + (fold (+) (map tsize l) 0)\"\n\nfun eqs_size_fst :: \"('f, 'v) equations \\<Rightarrow> nat\" where\n  \"eqs_size_fst [] = 0\"\n| \"eqs_size_fst ((t, _)#qs) = tsize t + eqs_size_fst qs\"\n\n(* equivalent to zip, but allows induction *)\nfun term_zip :: \"('f, 'v) term list \\<Rightarrow> ('f, 'v) term list \\<Rightarrow> (('f, 'v) term \\<times> ('f, 'v) term) list\" where\n  \"term_zip [] t1 = []\"\n| \"term_zip t0 [] = []\"\n| \"term_zip (h0#t0) (h1#t1) = (h0, h1) # (term_zip t0 t1)\"\n\nlemma term_swap_X1 [simp]: \n  \"card (fv_eq (Var x, Fun v va) \\<union> fv_eqs s) = card (fv_eq (Fun v va, Var x) \\<union> fv_eqs s)\"\n  by(simp add: fv_eq_def)\n\nlemma fv_term_zip: \n \"length l0 = length l1 \\<Longrightarrow> (\\<Union>x\\<in>set (term_zip l0 l1). fv (fst x) \\<union> fv (snd x)) = (\\<Union> (fv ` set l0) \\<union> \\<Union> (fv ` set l1))\"\n  apply(induction l0 l1 rule: term_zip.induct)\n    apply(simp_all)\n  by blast\n \nlemma term_fun_X1 [simp]:\n  \"length l0 = length l1 \\<Longrightarrow> card (fv_eqs (term_zip l0 l1 @ s)) = card (fv_eq (Fun f0 l0, Fun f0 l1) \\<union> fv_eqs s)\"\n  apply(induction l0 l1 rule: term_zip.induct)\n  by(simp_all add: fv_eq_def fv_eqs_U fv_term_zip Un_assoc Un_left_commute)\n\nlemma term_fun_X2 [simp]:\n  \"length l0 = length l1 \\<Longrightarrow> eqs_size_fst (term_zip l0 l1 @ s) < Suc (fold (+) (map tsize l0) 0 + eqs_size_fst s)\"\n  apply(induction l0 l1 rule: term_zip.induct)\n  by (simp_all add: fold_plus_sum_list_rev)\n\nlemma term_simp_X1 [simp]:\n  \"t = Var x \\<Longrightarrow> card (fv_eqs s) \\<le> card (fv_eq (Var x, Var x) \\<union> fv_eqs s)\"\n  by(simp add: fv_eq_def card_insert_le)\n\nlemma set_elems_card: \n  assumes \"\\<forall> v \\<in> setA . v \\<in> setB\" and \"x \\<in> setB\" and \"x \\<notin> setA\" and \"finite setB\"\n  shows \"card setA < card setB\"\nproof-\n  from assms have \n    \"setA \\<subset> setB\" \n    by blast\n  from this assms(4) show ?thesis by (simp add: psubset_card_mono)  \nqed\n\nlemma fv_finite: \"finite (fv t)\"\n  apply(induction t)\n  by(simp_all)\n\nlemma term_unify_X1 [simp]:\n  assumes \"x \\<notin> fv t\"\n  shows \"card (fv_eqs (Var(x := t) \\<cdot>s s)) < card (fv_eq (Var x, t) \\<union> fv_eqs s)\"\nproof-\n  have\n    \"finite (fv_eq (Var x, t) \\<union> fv_eqs s)\"\n    by(simp add: fv_eqs_U fv_eq_def fv_finite)\n  moreover from assms have\n    \"x \\<notin> fv_eqs (Var(x := t) \\<cdot>s s)\"\n    by(simp add: fv_sapply_eqs)\n  moreover have\n    \"x \\<in> fv_eq (Var x, t) \\<union> fv_eqs s\"\n    by(simp add: fv_eq_def)\n  moreover have\n    \"\\<forall> v \\<in> fv_eqs (Var(x := t) \\<cdot>s s) . v \\<in> (fv_eq (Var x, t) \\<union> fv_eqs s)\"\n    by(simp add: fv_sapply_eqs fv_eq_def)\n  ultimately show ?thesis by (simp add: set_elems_card)\nqed\n\n(*Unification algorithm*)\nfun scomp_opt :: \"('f, 'v) subst option \\<Rightarrow> ('f, 'v) subst \\<Rightarrow> ('f, 'v) subst option\"\n  where\n    \"(scomp_opt None \\<tau>) = None\"\n  | \"(scomp_opt (Some \\<sigma>) \\<tau>) = Some (\\<sigma> \\<circ>s \\<tau>)\" \n\nfunction (sequential) unify :: \"('f, 'v) equations \\<Rightarrow> ('f, 'v) subst option\" where\n  Base: \"unify [] = Some Var\"\n| UnSi: \"unify ((Var x, t)#s) = (if x \\<notin> (fv t) then \n        scomp_opt (unify (Var(x := t) \\<cdot>s s)) (Var(x := t))\n      else \n        if t = (Var x) then \n          unify s \n        else \n          None)\"\n| Swap: \"unify ((t, Var x)#s) = unify ((Var x, t)#s)\"\n| Fun:  \"unify ((Fun f0 l0, Fun f1 l1)#s) = (\n  if (f0 = f1) \\<and> (length l0 = length l1) then \n    unify ((term_zip l0 l1) @ s) \n  else None)\"\n            apply pat_completeness\n            by(simp_all)\ntermination\n  apply(relation \"measures[\n    (\\<lambda> eqs . card (fv_eqs eqs)),\n    (\\<lambda> eqs . eqs_size_fst eqs),\n    (\\<lambda> eqs . size eqs)\n  ]\")\n  by(simp_all add: le_imp_less_or_eq)\n\ntext \\<open> (b) \\<close>\n\nlemma fun_unifies: \"\\<lbrakk>length l0 = length l1; f0 = f1 \\<rbrakk> \\<Longrightarrow> unifies \\<sigma> (term_zip l0 l1 @ s) = unifies \\<sigma> ((Fun f0 l0, Fun f1 l1)#s)\"\n  apply(induction rule: term_zip.induct)\n  by(simp_all add: unifies_eq_def)\n\nlemma unifies_app: \"unifies \\<sigma> (l0 @ l1) \\<Longrightarrow> unifies \\<sigma> l0 \\<and> unifies \\<sigma> l1\"\n  by(simp add: unifies_forall)\n\nlemma scomp_opt_fst: \"scomp_opt (unify eqs) \\<tau> = Some \\<rho> \\<Longrightarrow> \\<exists> \\<sigma> . unify eqs = Some \\<sigma>\"\n  by(metis scomp_opt.elims)\n\nlemma subst_redundancy: \"x \\<notin> fv t \\<Longrightarrow> \\<sigma> \\<circ>s Var(x := t) \\<circ>s Var(x := t) = \\<sigma> \\<circ>s Var(x := t)\"\n  by(simp only: fun_eq_iff; metis scomp_def fun_upd_apply sapply_cong scomp_Var scomp_assoc)\n\nlemma unify_soundness_i: \"unify eqs = Some \\<sigma> \\<Longrightarrow> unifies \\<sigma> eqs\"\n  proof(induction arbitrary: \\<sigma> rule: unify.induct)\n    case 1\n    then show ?case by simp\n  next\n    case (2 x t s)\n    then show ?case proof-\n      show ?case proof(cases \"x \\<notin> fv t\")\n        case True\n        then show ?thesis proof-\n          from True 2(3) have opt:\n            \"scomp_opt (unify (Var(x := t) \\<cdot>s s)) (Var(x := t)) = Some \\<sigma>\"\n            by simp\n          then obtain \\<sigma>p where sigp_unify:\n            \"unify (Var(x := t) \\<cdot>s s) = Some \\<sigma>p\"\n            by fastforce\n          from this opt have sig:\n            \"\\<sigma> = \\<sigma>p \\<circ>s Var(x := t)\" by simp\n          moreover from sigp_unify True 2(1) have \n            \"unifies \\<sigma>p (Var(x := t) \\<cdot>s s)\" \n            by simp\n          ultimately have\n            \"unifies \\<sigma> s\"\n            by(simp add: unifies_sapply subst_redundancy scomp_assoc)\n          moreover from sig True have\n            \"unifies_eq \\<sigma> (Var x, t)\"\n            by (simp add: unifies_eq_def; metis fun_upd_apply sapply_cong scomp_Var scomp_sapply)\n         ultimately show ?thesis by simp\n        qed\n      next\n        case False\n        then show ?thesis proof-\n          from False 2(3) have\n            \"t = Var x\"\n            by fastforce\n          moreover from this 2(3) have\n            \"unify s = Some \\<sigma>\"\n            by simp\n          ultimately show ?thesis using 2(2) by(simp add: unifies_eq_def)\n        qed\n      qed\n    qed\n  next\n    case (3 v va x s)\n    then show ?case by (simp add: unifies_eq_def)\n  next\n    case (4 f0 l0 f1 l1 s)\n    then show ?case proof-\n      from 4(2) have\n        \"(f0 = f1 \\<and> length l0 = length l1) \\<and> (unify (term_zip l0 l1 @ s) = Some \\<sigma>)\"\n        by (simp; metis option.distinct(1))\n      moreover from this 4(1) have\n        \"unifies \\<sigma> (term_zip l0 l1 @ s)\" by simp\n      ultimately show ?thesis using 4(1) by(simp only: fun_unifies)\n    qed\n  qed\n\nlemma unify_soundness_ii: \"unify eqs = Some \\<sigma> \\<Longrightarrow> \n  ((\\<forall> \\<tau>. (unifies \\<tau> eqs) \\<longrightarrow> (\\<exists> \\<rho> . \\<tau> = \\<rho> \\<circ>s \\<sigma>)))\"\nproof(induction eqs arbitrary: \\<sigma> rule: unify.induct)\n  case 1\n  then show ?case by simp\nnext\n    case (2 x t s)\n    then show ?case proof-\n      show ?case proof(cases \"x \\<notin> fv t\")\n        case True\n        then show ?thesis proof-\n          from True 2(3) have\n            \"scomp_opt (unify (Var(x := t) \\<cdot>s s)) (Var(x := t)) = Some \\<sigma>\"\n            by simp\n          moreover from this obtain \\<sigma>p where sigp_unify:\n            \"unify (Var(x := t) \\<cdot>s s) = Some \\<sigma>p\"\n            by fastforce\n          ultimately have sig:\n            \"\\<sigma> = \\<sigma>p \\<circ>s Var(x := t)\" by simp\n          from sigp_unify True 2(1) have IS:\n            \"\\<forall>\\<tau>. unifies \\<tau> (Var(x := t) \\<cdot>s s) \\<longrightarrow> (\\<exists>\\<rho>. \\<tau> = \\<rho> \\<circ>s \\<sigma>p)\"\n            by simp\n          show ?thesis proof(rule allI)\n            fix \\<tau>\n            show \"unifies \\<tau> ((Var x, t) # s) \\<longrightarrow> (\\<exists>\\<rho>. \\<tau> = \\<rho> \\<circ>s \\<sigma>)\"\n            proof(rule impI)\n              assume asm: \"unifies \\<tau> ((Var x, t) # s)\"\n              show \"(\\<exists>\\<rho>. \\<tau> = \\<rho> \\<circ>s \\<sigma>)\" proof-\n                from asm have\n                  \"\\<tau> x = \\<tau> \\<cdot> t\" and \"unifies \\<tau> s\"\n                  by(simp_all add: unifies_eq_def)\n                moreover from this True have t_def:\n                  \"\\<tau> \\<circ>s Var(x := t) = \\<tau>\"\n                  by(simp add: fun_eq_iff scomp_sapply)\n                ultimately have\n                  \"unifies \\<tau> (Var(x := t) \\<cdot>s s)\"\n                  by(simp add: unifies_sapply)\n                from this IS obtain \\<rho> where\n                  \"\\<tau> = \\<rho> \\<circ>s \\<sigma>p\"\n                  by blast\n                hence\n                  \"\\<tau> \\<circ>s Var(x := t) = \\<rho> \\<circ>s \\<sigma>p \\<circ>s Var(x := t)\"\n                  by (simp add: scomp_assoc)\n                from this t_def sig have\n                  \"\\<tau> = \\<rho> \\<circ>s \\<sigma>\"\n                  by auto\n                then show ?thesis\n                  by auto\n              qed\n            qed\n          qed\n        qed\n      next\n        case False\n        then show ?thesis proof-\n          from False 2(3) have\n            \"t = Var x\"\n            by fastforce\n          moreover from this 2(3) have\n            \"unify s = Some \\<sigma>\"\n            by simp\n          ultimately show ?thesis using 2(2) by(simp add: unifies_eq_def)\n        qed\n      qed\n    qed\nnext\n  case (3 v va x s)\n  then show ?case by (simp add: unifies_eq_def) \nnext\n  case (4 f0 l0 f1 l1 s)\n  then show ?case proof-\n      fix \\<tau> \n      from 4(2) have\n        \"(f0 = f1 \\<and> length l0 = length l1) \\<and> (unify (term_zip l0 l1 @ s) = Some \\<sigma>)\"\n        by(simp; metis option.distinct(1))\n      moreover from this 4(1) have\n        \"\\<forall>\\<tau>. unifies \\<tau> (term_zip l0 l1 @ s) \\<longrightarrow> (\\<exists>\\<rho>. \\<tau> = \\<rho> \\<circ>s \\<sigma>)\" \n        by simp\n      ultimately show ?thesis \n        by (metis fun_unifies)\n    qed\n  qed\n\ntheorem unify_soundness: \"unify eqs = Some \\<sigma> \\<Longrightarrow> is_mgu \\<sigma> eqs\"\n  by(simp add: is_mgu_def unify_soundness_i unify_soundness_ii)\n\ntext \\<open> (c) \\<close>\n\n(* in_term presents an alternative way to prove the lemma sapply_size *) \n\n(*(* denotes whether the first term is contained in the second term*)\nfun in_term :: \"('f, 'v) term \\<Rightarrow> ('f, 'v) term \\<Rightarrow> bool\" \n  (infixr \"tin\" 67) where\n  \"in_term t (Var x) = (t = Var x)\"\n| \"in_term t (Fun f l) = ((t = Fun f l) \\<or> (\\<exists> t0 \\<in> set l . in_term t t0))\"\n\nlemma in_term_size: \"\\<lbrakk> t tin t0 \\<rbrakk> \\<Longrightarrow> tsize t \\<le> tsize t0\"\nproof(induction t0 rule: in_term.induct)\n  case (1 t x)\n  then show ?case by simp\nnext\n  case IS: (2 t f l)\n  then show ?case proof-\n    from IS(2) have \"(t = Fun f l) \\<or> (\\<exists> t0 \\<in> set l . in_term t t0)\" by simp\n    then consider \"(t = Fun f l)\" | \"(\\<exists> t0 \\<in> set l . in_term t t0)\" by blast\n    then show ?case proof(cases)\n      case 1\n      then show ?thesis using IS by simp\n    next\n      case 2\n      then show ?thesis proof-\n        from 2 obtain t0 where t0l: \"t0 \\<in> set l\" and tt0: \"t tin t0\"\n          by auto\n        from this IS(1) have \n          \"tsize t \\<le> tsize t0\"\n          by blast\n        moreover from t0l have \n          \"tsize t0 < tsize (Fun f l)\"\n          by(simp only: in_args_size)\n        ultimately show ?thesis by simp\n      qed\n    qed\n  qed\nqed\n\nlemma fv_in_term: \"x \\<in> fv t \\<Longrightarrow> (Var x) tin t\"\n  by(induction t rule: term.induct; simp; auto)\n\nlemma in_itself: \"t tin t\"\n  apply(induction t)\n  by simp_all\n\nlemma in_term_sapply: \"t tin t0 \\<Longrightarrow> (\\<sigma> \\<cdot> t) tin (\\<sigma> \\<cdot> t0)\"\n  apply(induction t0 rule: term.induct)\n   apply(simp add: in_itself)\n  by(simp add: in_itself; auto)  \n*)\n\nlemma fold_eq_sum_list: \"(fold (+) (l :: nat list) 0) = (sum_list l)\"\n  apply(induction l)\n  by (simp_all add: fold_plus_sum_list_rev)\n\nlemma in_args_size: \n  assumes \"t0 \\<in> set l\"\n  shows \"tsize t0 < tsize (Fun f l)\"\nproof-\n  from assms(1) have\n    \"tsize t0 \\<in> set (map tsize l)\"\n    by simp\n  moreover from this have\n    \"tsize t0 \\<le> sum_list (map tsize l)\"\n    by(simp only: member_le_sum_list)\n  moreover from this have\n    \"tsize t0 \\<le> (fold (+) (map tsize l) 0)\"\n    by(simp add: fold_eq_sum_list)\n  ultimately show ?thesis by simp\nqed\n\nlemma sapply_size: \"\\<lbrakk> x \\<in> fv t; t \\<noteq> Var x \\<rbrakk> \\<Longrightarrow> tsize (\\<sigma> \\<cdot> t) > tsize (\\<sigma> x)\"\nproof(induction t)\n  case (Var x)\n  then show ?case by simp \nnext\n  case (Fun x1a x2)\n  then show ?case proof-\n    from Fun(2) obtain x2a where\n      x2a_in: \"x2a \\<in> set x2\" and x2a_fv: \"x \\<in> fv x2a\"\n      by auto\n    show ?thesis proof(cases \"x2a = Var x\")\n      case True\n      then show ?thesis proof-\n        from True x2a_in have\n          \"\\<sigma> x \\<in> set (map ((\\<cdot>) \\<sigma>) x2)\"\n          by force\n        from this in_args_size show ?thesis\n          by fastforce\n      qed\n    next\n      case False\n      then show ?thesis proof-\n        from Fun(1) x2a_in x2a_fv False have\n          \"tsize (\\<sigma> x) < tsize (\\<sigma> \\<cdot> x2a)\"\n          by simp\n        then show ?thesis\n          by (metis (no_types, lifting) image_eqI in_args_size \n              list.set_map order.strict_trans sapply.simps(2) x2a_in)\n      qed\n    qed\n  qed\nqed\n(* Alternate proof using in_term *)\n(*\nproof-\n  from assms(1) have\n    \"Var x tin t\"\n    by(simp only: fv_in_term)\n  hence\n    \"(\\<sigma> \\<cdot> Var x) tin \\<sigma> \\<cdot> t\"\n    using in_term_sapply by fastforce\n  hence sigx:\n    \"\\<sigma> x tin \\<sigma> \\<cdot> t\"\n    by simp\n  from assms obtain f l where t_def:\n    \"\\<sigma> \\<cdot> t = Fun f l\"\n    by (metis fv_in_term in_term.elims(2) sapply.simps(2))\n  from this assms sigx obtain t0 where\n    \"t0 \\<in> set l\" and sigx_t0: \"\\<sigma> x tin t0\"\n    by (smt (z3) \\<open>Var x tin t\\<close> image_eqI in_term.elims(2) in_term_sapply list.set_map sapply.simps(1) sapply.simps(2) term.inject(2))\n  from this t_def have\n    \"tsize (t0) < tsize (\\<sigma> \\<cdot> t)\"\n    by(simp only: in_args_size)\n  moreover from sigx_t0 have\n    \"tsize (\\<sigma> x) \\<le> tsize t0\"\n    by(simp only: in_term_size)\n  ultimately show ?thesis by simp\nqed\n*)\n\nlemma case_occurs:\n  assumes \"x \\<in> fv t\" and \"unifies \\<sigma> ((Var x, t) # s)\"\n  shows \"t = Var x\"\nproof(rule ccontr)\n  assume cont: \"t \\<noteq> Var x\"\n  from cont assms(1) have\n    \"tsize (\\<sigma> \\<cdot> t) > tsize (\\<sigma> x)\"\n    by (simp add: sapply_size)\n  moreover from assms(2) have\n    \"tsize (\\<sigma> \\<cdot> t) = tsize (\\<sigma> x)\"\n    by(simp add: unifies_eq_def)\n  ultimately show False by simp\nqed\n\nlemma unifies_wf: \"unifies_eq \\<sigma> (Fun f0 l0, Fun f1 l1) \\<Longrightarrow> f0 = f1 \\<and> length l0 = length l1\"\n  by (simp add: unifies_eq_def; metis length_map)\n\nlemma lemma2: \"(\\<exists> \\<sigma> . unifies \\<sigma> eqs) \\<Longrightarrow> \\<not> Option.is_none (unify eqs)\"\nproof(induction rule: unify.induct)\n  case 1\n  then show ?case by simp\nnext\n    case (2 x t s)\n    then show ?case proof-\n      show ?case proof(cases \"x \\<notin> fv t\")\n        case True\n        then show ?thesis proof-\n          from 2(3) obtain \\<sigma> where si:\n            \"unifies \\<sigma> ((Var x, t) # s)\"\n            by(rule exE)\n          hence\n            \"\\<sigma> x = \\<sigma> \\<cdot> t\" and sig_s: \"unifies \\<sigma> s\"\n            by(simp_all add: unifies_eq_def)\n          from this True have\n            \"\\<sigma> \\<circ>s Var(x := t) = \\<sigma>\"\n            by (simp add: scomp_def ext)\n          from this sig_s have\n            \"unifies \\<sigma> (Var(x := t) \\<cdot>s s)\"\n            by (simp add: unifies_sapply)\n          from this True 2(1) have\n            \"\\<not> Option.is_none (unify (Var(x := t) \\<cdot>s s))\"\n            by auto\n          hence\n            \"\\<not> Option.is_none (scomp_opt (unify (Var(x := t) \\<cdot>s s)) (Var(x := t)))\"\n            using Option.is_none_def by fastforce\n          then show ?thesis using True\n            by simp\n        qed\n      next\n        case False\n        then show ?thesis proof-\n          from 2(3) obtain \\<sigma> where si:\n            \"unifies \\<sigma> ((Var x, t) # s)\"\n            by(rule exE)\n          hence\n            \"\\<exists> \\<sigma> . unifies \\<sigma> s\"\n            by(simp; blast)\n          moreover from si False have\n            \"t = Var x\"\n            by(simp add: case_occurs)\n          ultimately show ?thesis using 2(2) False by simp\n        qed\n      qed\n    qed\nnext\n  case (3 v va x s)\n  then show ?case proof-\n    from 3(2) obtain \\<sigma> where \"unifies \\<sigma> ((Fun v va, Var x) # s)\"\n      by(rule exE)\n    hence \n      \"unifies \\<sigma> ((Var x, Fun v va) # s)\"\n      by(simp add: unifies_eq_def)\n    hence\n      \"\\<exists>\\<sigma>. unifies \\<sigma> ((Var x, Fun v va) # s)\"\n      by blast\n    hence\n      \"\\<not> Option.is_none (unify ((Var x, Fun v va) # s))\"\n      using 3(1) by simp\n    then show ?thesis by simp\n  qed\nnext\n  case (4 f0 l0 f1 l1 s)\n  then show ?case proof-\n    from 4(2) obtain \\<sigma> where \"unifies \\<sigma> ((Fun f0 l0, Fun f1 l1) # s)\"\n      by(rule exE)\n    hence\n      \"unifies_eq \\<sigma> (Fun f0 l0, Fun f1 l1)\"\n      by(simp)\n    hence reqs:\n      \"f0 = f1 \\<and> length l0 = length l1\"\n      by(simp add: unifies_wf)\n    from 4(2) obtain \\<sigma> where \"unifies \\<sigma> ((Fun f0 l0, Fun f1 l1) # s)\"\n      by(rule exE)\n    hence\n      \"unifies \\<sigma> (term_zip l0 l1 @ s)\"\n      using reqs by(simp only: fun_unifies)\n    hence \n      \"\\<exists> \\<sigma> . unifies \\<sigma> (term_zip l0 l1 @ s)\"\n      by blast\n    from this reqs 4(1) have  \n      \"\\<not> Option.is_none (unify (term_zip l0 l1 @ s))\"\n      by simp\n    moreover have\n      \"unify (term_zip l0 l1 @ s) = unify ((Fun f0 l0, Fun f1 l1) # s)\"\n      using reqs by simp\n    ultimately show ?thesis by(simp)\n  qed\nqed\n        \ntheorem unify_completeness: \"(\\<exists> \\<sigma> . unifies \\<sigma> eqs \\<longrightarrow> unify eqs = Some \\<sigma>)\"\n  by (metis is_none_simps(1) lemma2 option.exhaust_sel) \n\ntext \\<open> (d) \\<close>\n\nlemma fv_swap:\n  \"fv_eq (t0, t1) = fv_eq (t1, t0)\"\n  by(simp add: fv_eq_def; blast)\n\nlemma fv_fun:\n  \"length l0 = length l1 \\<Longrightarrow> fv_eqs ((Fun f0 l0, Fun f1 l1) # s) = fv_eqs ((term_zip l0 l1) @ s)\"\nproof(induction rule: term_zip.induct)\n  case (1 t1)\n  then show ?case by (simp add: fv_eq_def)\nnext\n  case (2 v va)\n  then show ?case by simp\nnext\n  case (3 h0 t0 h1 t1)\n  then show ?case proof-\n    from 3(2) have lens:\n      \"length t0 = length t1\"\n      by simp\n    have\n      \"fv_eqs ((Fun f0 (h0 # t0), Fun f1 (h1 # t1)) # s) = fv h0 \\<union> fv h1 \\<union> fv_eqs ((Fun f0 t0, Fun f1 t1) # s)\"\n      by(simp add: fv_eq_def; auto)\n    moreover have\n      \"... = fv h0 \\<union> fv h1 \\<union> fv_eqs (term_zip t0 t1 @ s)\"\n      using 3(1) lens by simp\n    moreover have\n      \"... = fv_eqs (term_zip (h0 # t0) (h1 # t1) @ s)\"\n      by(simp add: fv_eq_def)\n    ultimately show ?thesis by simp\n  qed\nqed\n\n\nlemma lemma1: \"fv (\\<sigma> \\<cdot> t) \\<subseteq> (fv t - sdom \\<sigma>) \\<union> svran \\<sigma>\"\n  apply(induction t)\n   apply(meson subsetI svapply_svdom_svran)\n  by auto\n\nlemma lemma1_eq: \"fv_eq (\\<sigma> \\<cdot>e eq) \\<subseteq> (fv_eq eq - sdom \\<sigma>) \\<union> svran \\<sigma>\"\n  apply(induction eq)\n  apply(simp add: fv_eq_def sapply_eq_def)\n  by (smt (verit) Diff_subset_conv Un_Diff inf_sup_aci(5) le_supI1 lemma1)\n\nlemma lemma1_eqs: \"fv_eqs (\\<sigma> \\<cdot>s eqs) \\<subseteq> (fv_eqs eqs - sdom \\<sigma>) \\<union> svran \\<sigma>\"\nproof(induction eqs rule: fv_eqs.induct)\n  case 1\n  then show ?case by simp\nnext\n  case (2 eq s)\n  then show ?case proof-\n    have \n      \"fv_eqs (\\<sigma> \\<cdot>s (eq # s)) = fv_eq (\\<sigma> \\<cdot>e eq) \\<union> fv_eqs (\\<sigma> \\<cdot>s s)\"\n      by simp\n    moreover have\n      \"fv_eq (\\<sigma> \\<cdot>e eq) \\<subseteq> (fv_eq eq - sdom \\<sigma>) \\<union> svran \\<sigma>\"\n      by (simp only: lemma1_eq)\n    ultimately show ?thesis\n      using 2 by auto\n  qed\nqed\n\n(* Useful subcase of lemma1_eqs *)\nlemma lemma1_eqs_single: \"x \\<notin> fv t \\<Longrightarrow> fv_eqs (Var(x := t) \\<cdot>s s) \\<subseteq> fv t \\<union> fv_eqs s\"\nusing lemma1_eqs by(smt (verit, del_insts) Diff_iff Diff_insert_absorb Un_Diff Un_commute fv.simps(1) \n                                  insert_Diff1 sdom_single_non_trivial singletonI subset_eq svran_single_non_trivial)\n\nlemma unify_svran_fv: \"unify eqs = Some \\<sigma> \\<Longrightarrow> svran \\<sigma> \\<subseteq> fv_eqs eqs\"\nproof(induction arbitrary: \\<sigma> rule: unify.induct)\n  case 1\n  then show ?case by simp\nnext\n    case (2 x t s)\n    then show ?case proof-\n      show ?case proof(cases \"x \\<notin> fv t\")\n      case True\n      then show ?thesis proof-\n        from True 2(3) have opt:\n          \"scomp_opt (unify (Var(x := t) \\<cdot>s s)) (Var(x := t)) = Some \\<sigma>\"\n          by simp\n        then obtain \\<sigma>p where sigp_unify:\n          \"unify (Var(x := t) \\<cdot>s s) = Some \\<sigma>p\"\n          by fastforce\n        from this opt have sig:\n          \"\\<sigma> = \\<sigma>p \\<circ>s Var(x := t)\" by simp\n        from sigp_unify True 2(1) have IS:\n          \"svran \\<sigma>p \\<subseteq> fv_eqs (Var(x := t) \\<cdot>s s)\"\n          by simp\n        from this sig have\n          \"svran \\<sigma> \\<subseteq> fv t \\<union> fv_eqs (Var(x := t) \\<cdot>s s)\"\n          by (smt (verit) Un_assoc Un_commute fun_upd_triv le_supI2 scomp_Var sup.orderE svran_scomp svran_single_non_trivial)\n        moreover have\n          \"fv_eqs ((Var x, t) # s) = { x } \\<union> fv t \\<union> fv_eqs s\"\n          by (simp add: fv_eq_def)\n        moreover from True lemma1_eqs_single have\n          \"fv_eqs (Var(x := t) \\<cdot>s s) \\<subseteq> fv t \\<union> fv_eqs s\"\n          by metis\n        ultimately show ?thesis\n          by blast\n      qed\n    next\n      case False\n      then show ?thesis proof-\n        from False 2(3) have\n          \" t = Var x\"\n          by fastforce\n        moreover from 2(3) have\n          \"unify s = Some \\<sigma>\"\n          by (simp add: calculation)\n        ultimately show ?thesis using 2(2) False by auto \n      qed\n    qed\n  qed\nnext\n  case (3 v va x s)\n  then show ?case by(simp add: fv_swap)\nnext\n  case (4 f0 l0 f1 l1 s)\n  then show ?case proof-\n    from 4(2) have\n      \"f0 = f1 \\<and> length l0 = length l1\"\n      by (metis Fun option.discI)\n    moreover from 4(2) have\n      \"unify (term_zip l0 l1 @ s) = Some \\<sigma>\"\n      by (simp add: calculation)\n    ultimately show ?thesis using 4(1) by(simp only: fv_fun)\n  qed\nqed\n\nlemma unify_fv_sapply: \"unify eqs = Some \\<sigma> \\<Longrightarrow> fv_eqs (\\<sigma> \\<cdot>s eqs) \\<subseteq> fv_eqs eqs\"\nproof(induction eqs arbitrary: \\<sigma> rule: unify.induct)\n  case 1\n  then show ?case by simp\nnext\n    case (2 x t s)\n    show ?case proof-\n      show ?case proof(cases \"x \\<notin> fv t\")\n      case True\n      then show ?thesis proof-\n        from True 2(3) have opt:\n          \"scomp_opt (unify (Var(x := t) \\<cdot>s s)) (Var(x := t)) = Some \\<sigma>\"\n          by simp\n        then obtain \\<sigma>p where sigp_unify:\n          \"unify (Var(x := t) \\<cdot>s s) = Some \\<sigma>p\"\n          by fastforce\n        from this opt have sig:\n          \"\\<sigma> = \\<sigma>p \\<circ>s Var(x := t)\" by simp\n        from sigp_unify True 2(1) have IS:\n          \"fv_eqs (\\<sigma>p \\<cdot>s Var(x := t) \\<cdot>s s) \\<subseteq> fv_eqs (Var(x := t) \\<cdot>s s)\"\n          by simp\n        from this sig have\n          \"fv_eqs (\\<sigma> \\<cdot>s s) \\<subseteq> fv_eqs (Var(x := t) \\<cdot>s s)\"\n          by(simp only: sapply_scomp_distrib_eqs)\n        moreover from this True have\n          \"svran \\<sigma> \\<subseteq> fv t \\<union> fv_eqs s\"\n          by (smt (verit, ccfv_threshold) Un_absorb2 fun_upd_triv inf_sup_ord(3) lemma1_eqs_single order_trans\n              scomp_Var sig sigp_unify sup.mono svran_scomp svran_single_non_trivial unify_svran_fv)\n        ultimately show ?thesis using 2\n          by (meson Diff_subset dual_order.trans le_supI lemma1_eqs unify_svran_fv)\n      qed\n    next\n      case False\n      then show ?thesis proof-\n        from False 2(3) have t:\n          \" t = Var x\"\n          by fastforce\n        moreover from 2(3) have unify_s:\n          \"unify s = Some \\<sigma>\"\n          by (simp add: calculation)\n        ultimately have\n          \"fv_eqs (\\<sigma> \\<cdot>s s) \\<subseteq> fv_eqs s\"\n          using 2(2) by simp\n        moreover have \n          \"fv_eqs (\\<sigma> \\<cdot>s ((Var x, t) # s)) = fv (\\<sigma> x) \\<union> fv_eqs (\\<sigma> \\<cdot>s s)\"\n          by (simp add: fv_eq_def sapply_eq_def t)\n        moreover from t have \n          \"fv_eqs ((Var x, t) # s) = { x } \\<union> fv_eqs s\"\n          by(simp add: fv_eq_def)\n        moreover have\n          \"fv (\\<sigma> x) \\<subseteq> { x } \\<union> fv_eqs s\"\n        proof-\n          from lemma1 have\n            \"fv (\\<sigma> x) \\<subseteq> { x } - sdom \\<sigma> \\<union> svran \\<sigma>\"\n            by (metis fv.simps(1) sapply.simps(1))\n          moreover from unify_s unify_svran_fv have\n            \"svran \\<sigma> \\<subseteq> fv_eqs s\"\n            by blast\n          ultimately show ?thesis by blast\n        qed\n        ultimately show ?thesis\n          by blast\n      qed\n    qed\n  qed\nnext\n  case (3 v va x s)\n  then show ?case by(simp add: fv_sapply_eqs sapply_eq_def fv_swap)\nnext\n  case (4 f0 l0 f1 l1 s)\n  then show ?case proof-\n    from 4(2) have\n      \"f0 = f1 \\<and> length l0 = length l1\"\n      by (simp; metis option.distinct(1))\n    moreover from 4(2) have\n      \"unify (term_zip l0 l1 @ s) = Some \\<sigma>\"\n      by (simp add: calculation)\n    ultimately have \n      \"fv_eqs (\\<sigma> \\<cdot>s (term_zip l0 l1 @ s)) \\<subseteq> fv_eqs (term_zip l0 l1 @ s)\" \n      using 4(1) by simp\n    from this 4 show ?thesis by(simp only: fv_sapply_eqs fv_fun; metis Fun fv_fun option.simps(3))\n  qed\nqed\n\nlemma unify_sdom_fv: \"unify eqs = Some \\<sigma> \\<Longrightarrow> sdom \\<sigma> \\<subseteq> fv_eqs eqs\"\nproof(induction eqs arbitrary: \\<sigma> rule: unify.induct)\n  case 1\n  then show ?case by simp\nnext\n    case (2 x t s)\n    show ?case proof-\n      show ?case proof(cases \"x \\<notin> fv t\")\n      case True\n      then show ?thesis proof-\n        from True 2(3) have opt:\n          \"scomp_opt (unify (Var(x := t) \\<cdot>s s)) (Var(x := t)) = Some \\<sigma>\"\n          by simp\n        then obtain \\<sigma>p where sigp_unify:\n          \"unify (Var(x := t) \\<cdot>s s) = Some \\<sigma>p\"\n          by fastforce\n        from this opt have sig:\n          \"\\<sigma> = \\<sigma>p \\<circ>s Var(x := t)\" by simp\n        from this have\n          \"sdom \\<sigma> \\<subseteq> sdom \\<sigma>p \\<union> { x }\"\n          by (metis Un_commute fun_upd_idem_iff insert_is_Un scomp_Var sdom_scomp sdom_single_non_trivial subset_insertI)\n        moreover from 2(1) True sigp_unify have IS:\n          \"sdom \\<sigma>p \\<subseteq> fv_eqs (Var(x := t) \\<cdot>s s)\"\n          by simp\n        moreover from True have\n          \"fv_eqs (Var(x := t) \\<cdot>s s) \\<union> { x } \\<subseteq> fv t \\<union> fv_eqs s \\<union> { x }\"\n          by (simp add: lemma1_eqs_single subset_insertI2)\n        moreover have\n          \"fv t \\<union> fv_eqs s \\<union> { x } = fv_eqs ((Var x, t) # s)\"\n          by (simp add: fv_eq_def)\n        ultimately show ?thesis\n          by auto\n      qed\n    next                           \n      case False\n      then show ?thesis proof-\n        from False 2(3) have t:\n          \" t = Var x\"\n          by fastforce\n        moreover from 2(3) have\n          \"unify s = Some \\<sigma>\"\n          by (simp add: calculation)\n        ultimately show ?thesis using 2(2) False by auto \n      qed\n    qed\n  qed\nnext\n  case (3 v va x s)\n  then show ?case by(simp add: fv_swap)\nnext\n  case (4 f0 l0 f1 l1 s)\n  then show ?case proof-\n    from 4(2) have\n      \"f0 = f1 \\<and> length l0 = length l1\"\n      by (metis Fun option.discI)\n    moreover from 4(2) have\n      \"unify (term_zip l0 l1 @ s) = Some \\<sigma>\"\n      by (simp add: calculation)\n    ultimately show ?thesis using 4(1) by(simp only: fv_fun)\n  qed\nqed\n\nlemma unify_sdom_svran: \"unify eqs = Some \\<sigma> \\<Longrightarrow> sdom \\<sigma> \\<inter> svran \\<sigma> = {}\"\nproof(induction arbitrary: \\<sigma> rule: unify.induct)\n  case 1\n  then show ?case by simp\nnext\n    case (2 x t s)\n    then show ?case proof-\n      show ?case proof(cases \"x \\<notin> fv t\")\n      case True\n      then show ?thesis proof-\n        from True 2(3) have opt:\n          \"scomp_opt (unify (Var(x := t) \\<cdot>s s)) (Var(x := t)) = Some \\<sigma>\"\n          by simp\n        then obtain \\<sigma>p where sigp_unify:\n          \"unify (Var(x := t) \\<cdot>s s) = Some \\<sigma>p\"\n          by fastforce\n        from this opt have sig:\n          \"\\<sigma> = \\<sigma>p \\<circ>s Var(x := t)\" by simp\n        from 2(1) True sigp_unify have IS:\n          \"sdom \\<sigma>p \\<inter> svran \\<sigma>p = {}\"\n          by simp\n        from sig True sigp_unify have\n          \"svran \\<sigma>p \\<subseteq> fv_eqs (Var(x := t) \\<cdot>s s)\"\n          using unify_svran_fv by blast\n        from this True have x_svran_sigp: \n          \"x \\<notin> svran \\<sigma>p\"\n          by (metis (no_types, lifting) Diff_iff Diff_insert_absorb Un_Diff fv.simps(1) lemma1_eqs \n              sdom_single_non_trivial singletonI subsetD svran_single_non_trivial)\n        have \n          \"\\<not> (\\<exists> z . z \\<in> sdom \\<sigma> \\<and> z \\<in> svran \\<sigma>)\"\n        proof(rule notI)\n          assume \"\\<exists>z. z \\<in> sdom \\<sigma> \\<and> z \\<in> svran \\<sigma>\"\n          then obtain z where z_sdom:\n            \"z \\<in> sdom \\<sigma>\" and z_svran: \"z \\<in> svran \\<sigma>\"\n            by blast\n          from True z_sdom sig have\n            \"z \\<in> sdom \\<sigma>p \\<union> { x }\"\n            by (metis fv.simps(1) insertI1 insert_absorb insert_subset sdom_scomp sdom_single_non_trivial)\n          moreover from True z_svran sig have\n            \"z \\<in> svran \\<sigma>p \\<union> fv t\"\n            by (metis fv.simps(1) insertI1 insert_absorb insert_subset svran_scomp svran_single_non_trivial)\n          ultimately have z_sdom_sigp:\n            \"z \\<in> sdom \\<sigma>p\"\n            using x_svran_sigp True by blast\n          from svran_def z_svran obtain y where \n            y_sdom_sig: \"y \\<in> sdom \\<sigma>\" and z_fv_sig_y: \"z \\<in> fv (\\<sigma> y)\"\n            by fast\n          then show False proof(cases \"x = y\")\n            case True\n            then show ?thesis proof-\n              from True sig have \n                \"\\<sigma> y = \\<sigma>p \\<cdot> t\"\n                by (simp add: scomp_sapply)\n              from this z_fv_sig_y have\n                \"z \\<in> fv (\\<sigma>p \\<cdot> t)\"\n                by simp\n              from this lemma1 have\n                \"z \\<in> (fv t) - sdom \\<sigma>p \\<union> svran \\<sigma>p\"\n                by fast\n              from this z_sdom_sigp have\n                \"z \\<in> svran \\<sigma>p\"\n                by simp\n              from this IS z_sdom_sigp show ?thesis\n                by auto\n            qed\n          next\n            case False\n            then show ?thesis proof-\n              from False sig have\n                \"\\<sigma> y = \\<sigma>p y\"\n                by (simp add: scomp_sapply)\n              from this z_fv_sig_y z_sdom_sigp have\n                \"z \\<in> svran \\<sigma>p\"\n                by (metis Diff_iff Un_commute Un_iff sapply.simps(1) svapply_svdom_svran)\n              from this IS z_sdom_sigp show ?thesis\n                by auto\n            qed\n          qed\n        qed\n        then show ?thesis\n          by auto\n        qed\n    next\n      case False\n      then show ?thesis proof-\n        from False 2(3) have t:\n          \" t = Var x\"\n          by fastforce\n        moreover from 2(3) have\n          \"unify s = Some \\<sigma>\"\n          by (simp add: calculation)\n        ultimately show ?thesis using 2(2) False by simp \n      qed\n    qed\n  qed\nnext\n  case (3 v va x s)\n  then show ?case by simp\nnext\n  case (4 f0 l0 f1 l1 s)\n  then show ?case proof-\n    from 4(2) have\n      \"f0 = f1 \\<and> length l0 = length l1\"\n      by (metis Fun option.discI)\n    moreover from 4(2) have\n      \"unify (term_zip l0 l1 @ s) = Some \\<sigma>\"\n      by (simp add: calculation)\n    ultimately show ?thesis using 4(1) by simp\n  qed\nqed\n\nsection \\<open> Assignment 4 \\<close>\n\ntext \\<open> (a) \\<close>\n\nfun wf_term :: \"('f \\<Rightarrow> nat) \\<Rightarrow> ('f, 'v) term \\<Rightarrow> bool\" where\n  \"wf_term arity (Var _) = True\"\n| \"wf_term arity (Fun f lst) = (((length lst) = (arity f)) \\<and> (\\<forall> t \\<in> set lst. (wf_term arity t)))\"\n\ndefinition wf_subst :: \"('f \\<Rightarrow> nat) \\<Rightarrow> ('f, 'v) subst \\<Rightarrow> bool\" where\n  \"wf_subst arity \\<sigma> = (\\<forall> x. wf_term arity (\\<sigma> x))\"\n\nfun wf_eq :: \"('f \\<Rightarrow> nat) \\<Rightarrow> ('f, 'v) equation \\<Rightarrow> bool\" where\n  \"wf_eq arity (t0, t1) = ((wf_term arity t0) \\<and> (wf_term arity t1))\"\n\nlemma wf_eq_terms_wf: \"wf_eq arity eq \\<longleftrightarrow> wf_term arity (fst eq) \\<and> wf_term arity (snd eq)\"\n  by (metis surjective_pairing wf_eq.simps)\n\ndefinition wf_eqs :: \"('f \\<Rightarrow> nat) \\<Rightarrow> ('f, 'v) equations \\<Rightarrow> bool\" where\n  \"wf_eqs arity eqs = (\\<forall> eq \\<in> (set eqs). wf_eq arity eq)\"\n\ntext \\<open> (b) \\<close>\n\nlemma wf_term_sapply:\n  \"\\<lbrakk> wf_term arity t; wf_subst arity \\<sigma> \\<rbrakk> \\<Longrightarrow> wf_term arity (\\<sigma> \\<cdot> t)\"\n  apply(induction t)\n  by(simp_all add: wf_subst_def)\n\nlemma wf_subst_scomp:\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 scomp_def wf_term_sapply)\n\nlemma wf_zip: \"\\<lbrakk>length l0 = length l1; \n    \\<forall>t\\<in>set l0. wf_term arity t; \n    \\<forall>t\\<in>set l1. wf_term arity t;\n    wf_eqs arity s\\<rbrakk> \\<Longrightarrow> wf_eqs arity ((term_zip l0 l1)@s)\"\n  apply(induction rule: term_zip.induct)\n  by(simp_all add: wf_eqs_def)\n\nlemma wf_single_subst: \"\\<lbrakk> x \\<notin> fv t; wf_term arity t\\<rbrakk> \\<Longrightarrow> wf_subst arity (Var(x := t))\"\n  by(simp add: wf_subst_def)\n\nlemma wf_Var: \"wf_subst arity Var\"\n  by(simp add: wf_subst_def)\n\nlemma wf_eq_sapply:\n  \"\\<lbrakk> wf_subst arity \\<sigma>; wf_term arity t;  wf_eq arity eq \\<rbrakk> \\<Longrightarrow> wf_eq arity (\\<sigma> \\<cdot>e eq)\"\n  by(simp add: sapply_eq_def wf_eq_terms_wf wf_term_sapply)\n  \nlemma wf_eqs_sapply: \"\\<lbrakk> wf_subst arity \\<sigma>; wf_term arity t;  wf_eqs arity s \\<rbrakk> \\<Longrightarrow> wf_eqs arity (\\<sigma> \\<cdot>s s)\"\n  apply(induction s)\n   apply(simp)\n  by(simp add: wf_eqs_def wf_eq_sapply)\n\nlemma wf_subst_unify:\n  \"\\<lbrakk> unify eqs = Some \\<sigma>; wf_eqs arity eqs \\<rbrakk> \\<Longrightarrow> wf_subst arity \\<sigma>\"\nproof(induction arbitrary: \\<sigma> rule: unify.induct)\n  case 1\n  then show ?case by(simp add: wf_subst_def)\nnext\n  case (2 x t s)\n    from 2(4)have s_wf:\n      \"wf_eqs arity s\"\n      by (simp add: wf_eqs_def)\n    show ?case proof(cases \"x \\<notin> fv t\")\n      case True\n      then show ?thesis proof-\n          from 2(4) have t_wf:\n            \"wf_term arity t\"\n            by(simp add: wf_eqs_def)\n          from this True s_wf have up_wf:\n            \"wf_eqs arity (Var(x := t) \\<cdot>s s)\"\n            by(simp add: wf_single_subst wf_eqs_sapply)\n          from True 2(3) have opt:\n            \"scomp_opt (unify (Var(x := t) \\<cdot>s s)) (Var(x := t)) = Some \\<sigma>\"\n            by simp\n          then obtain \\<sigma>p where sigp_unify:\n            \"unify (Var(x := t) \\<cdot>s s) = Some \\<sigma>p\"\n            by fastforce\n          from this opt have sig:\n            \"\\<sigma> = \\<sigma>p \\<circ>s Var(x := t)\" by simp\n          moreover from 2(1) True sigp_unify up_wf have\n            \"wf_subst arity \\<sigma>p\"\n            by simp\n          ultimately show ?thesis using True\n            by(simp add: t_wf wf_single_subst  wf_subst_scomp)\n        qed\n    next\n      case False\n      then show ?thesis proof-\n        from False 2(3) have\n          \"t = Var x\"\n          by fastforce\n        moreover from 2(3) have\n          \"unify s = Some \\<sigma>\"\n          by (simp add: calculation)\n        ultimately show ?thesis using 2(2) s_wf by simp\n      qed\n    qed\nnext\n  case (3 v va x s)\n  then show ?case by(simp add: wf_eqs_def wf_subst_def)\nnext\n  case (4 f0 l0 f1 l1 s)\n  then show ?case proof -\n    from 4(2) have s0:\n      \"f0 = f1 \\<and> length l0 = length l1\"\n      by (simp; metis option.distinct(1))\n    from 4(2) have s1:\n      \"unify (term_zip l0 l1 @ s) = Some \\<sigma>\"\n      by (simp; metis option.distinct(1))\n    from 4(3) have s2:\n      \"(\\<forall> t \\<in> set l0 . wf_term arity t) \\<and> (\\<forall> t \\<in> set l1 . wf_term arity t)\" \n      by(simp add: wf_eqs_def)\n    from 4(3) have s3:\n      \"wf_eqs arity s\" \n      by(simp add: wf_eqs_def)\n    from s0 s2 s3 have s4:\n      \"wf_eqs arity ((term_zip l0 l1)@s)\"\n      by(simp add: wf_zip)\n    from 4(1) s0 s1 s4 show ?thesis by simp \n  qed\nqed\n\nend\n  ", "meta": {"author": "leonardolima", "repo": "tipl", "sha": "6e662bda05032461e8516ae77a96b9bb1cec93a7", "save_path": "github-repos/isabelle/leonardolima-tipl", "path": "github-repos/isabelle/leonardolima-tipl/tipl-6e662bda05032461e8516ae77a96b9bb1cec93a7/Unification.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127641048444, "lm_q2_score": 0.8757869948899665, "lm_q1q2_score": 0.7478456935735666}}
{"text": "section \\<open>Specification\\<close>\n\ntheory Goodstein_Lambda2\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  apply (induct m) by auto\n\nlemma evalO_mulO [simp]:\n  \"evalO b (mulO n m) = evalO b n * evalO b m\"\n  apply (induct m) by auto\n\nlemma evalO_n [simp]:\n  \"evalO b ((S ^^ n) Z) = n\"\n  apply (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  apply (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  apply (induct n) by auto\n\nlemma addO_assoc [simp]:\n  \"addO n (addO m p) = addO (addO n m) p\"\n  apply (induct p) by auto\n\nlemma mul0_distrib [simp]:\n  \"mulO n (addO p q) = addO (mulO n p) (mulO n q)\"\n  apply (induct q) by auto\n\nlemma mulO_assoc [simp]:\n  \"mulO n (mulO m p) = mulO (mulO n m) p\"\n  apply (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    apply (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    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  apply (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  apply (induct i) by auto\n\nlemma C2O_app:\n  \"C2O (C (xs @ ys)) = addO (C2O (C ys)) (C2O (C xs))\"\n  apply (induct xs arbitrary: ys) by auto\n\nsubsection \\<open>Evaluation\\<close>\n\nlemma evalC_def':\n  \"evalC b n = evalO b (C2O n)\"\n  apply (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  apply (induct ns) by auto\n\nlemma evalC_replicate [simp]:\n  \"evalC b (C (replicate c n)) = c * evalC b (C [n])\"\n  apply (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  apply (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    apply (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    apply (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  apply (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    apply (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  apply (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  apply (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  apply (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  apply (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\"\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    apply (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  apply (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  apply (induct ns) by auto\n\nlemma sum_list_replicate:\n  \"sum_list (replicate n x) = n * x\"\n  apply (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\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 apply (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  proof (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  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  apply (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    apply (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    apply (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  apply (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  apply (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  apply (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 apply (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  apply (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  apply (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>\nML\\<open>\n(*\nfun func x = fn z => func x z;\nIsabelle_Utils.timeout_apply (seconds 3.0) (func) 3 2\n*)\n\\<close>\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  apply (induct n)\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    apply (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    apply (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    apply (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_Lambda2.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8757869981319862, "lm_q2_score": 0.8539127510928476, "lm_q1q2_score": 0.7478456849462309}}
{"text": "(* Title: Program Store\n   Author: Peixin You\n*)\n\nsection \\<open>Program Store\\<close>\n\ntheory Store\n  imports KA\n\nbegin\n\nsubsection \\<open>Function update\\<close>\n\ntext \\<open> Isabelle provides such a function, but its type doesn't suit our needs well enough.\\<close>\n\ndefinition fup :: \"'a \\<Rightarrow> 'b \\<Rightarrow> ('a \\<Rightarrow> 'b) \\<Rightarrow> ('a \\<Rightarrow> 'b)\" (\"\\<Delta>\") where\n  \"\\<Delta> x a f = (\\<lambda>y. if x = y then a else f y)\"\n\nlemma fun_update_simp1 [simp]: \"\\<Delta> x a f x = a\"\n  by (simp add: fup_def)\n\nlemma fun_update_simp2 [simp]: \"x \\<noteq> y \\<Longrightarrow> \\<Delta> x a f y = f y\"\n  by (simp add: fup_def)\n\nlemma fun_update_absorb [simp]: \"\\<Delta> x a (\\<Delta> x b f) = \\<Delta> x a f\"\n  unfolding fup_def by force\n\nlemma fun_update_absorb2 [simp]: \"\\<Delta> x a \\<circ> \\<Delta> x b = \\<Delta> x a\"\n  unfolding fup_def by force\n\nlemma fun_update_comm: \"x \\<noteq> y \\<Longrightarrow> \\<Delta> x a (\\<Delta> y b f) = \\<Delta> y b (\\<Delta> x a f)\"\n  unfolding fup_def by force\n\nlemma fun_update_comm2: \"x \\<noteq> y \\<Longrightarrow> \\<Delta> x a \\<circ> \\<Delta> y b = \\<Delta> y b \\<circ> \\<Delta> x a\"\n  unfolding fup_def by force\n\nlemma fun_update_triv [simp]: \"\\<Delta> x (f x) f = f\"\n  unfolding fup_def by force\n\nabbreviation set :: \"'a \\<Rightarrow> (('a \\<Rightarrow> 'b) \\<Rightarrow> 'b) \\<Rightarrow> ('a \\<Rightarrow> 'b) \\<Rightarrow> ('a \\<Rightarrow> 'b)\" where\n  \"set x e s \\<equiv> \\<Delta> x (e s) s\"\n\n\nsubsection \\<open>Program Store and Semantics of Assignments\\<close>\n\ntype_synonym 'a store = \"string \\<Rightarrow> 'a\"\n\ndefinition rel_assign :: \"'a \\<Rightarrow> (('a \\<Rightarrow> 'b) \\<Rightarrow> 'b) \\<Rightarrow> ('a \\<Rightarrow> 'b) rel\" (\"_ :=\\<^sub>r _\" [70, 65] 61) where \n  \"v :=\\<^sub>r e = {(s, set v e s) |s. True}\"\n\nlemma rel_assign_iff: \"((s,s') \\<in> v :=\\<^sub>r e) = (s' = set v e s)\"\n  by (simp add: rel_assign_def)\n\ndefinition sta_assign :: \"'a \\<Rightarrow> (('a \\<Rightarrow> 'b) \\<Rightarrow> 'b) \\<Rightarrow> ('a \\<Rightarrow> 'b) sta\" (\"_ :=\\<^sub>s _\" [70, 65] 61) where\n  \"v :=\\<^sub>s e = \\<eta> \\<circ> set v e\"\n\nlemma sta_assign_eq: \"(v :=\\<^sub>s e) s = {set v e s}\"\n  by (simp add: sta_assign_def)\n\nlemma sta_assign_iff: \"(s' \\<in> (v :=\\<^sub>s e) s) = (s' = set v e s)\"\n  by (simp add: sta_assign_def)\n\nend\n\n\n\n", "meta": {"author": "hyleIndex", "repo": "Kleene-Algebras-From-Foundations-to-Program-Verification", "sha": "9ec491714e5925c7a6e42738ad6af17be8e70e9f", "save_path": "github-repos/isabelle/hyleIndex-Kleene-Algebras-From-Foundations-to-Program-Verification", "path": "github-repos/isabelle/hyleIndex-Kleene-Algebras-From-Foundations-to-Program-Verification/Kleene-Algebras-From-Foundations-to-Program-Verification-9ec491714e5925c7a6e42738ad6af17be8e70e9f/Store.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9019206712569267, "lm_q2_score": 0.8289388040954684, "lm_q1q2_score": 0.7476370426206989}}
{"text": "theory Exercise6\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 = Nil\"\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 Nil = 0\"\n  | \"listsum (Cons x xs) = x + (listsum xs)\"\n\nlemma shallow_treesum [simp]: \"treesum (Node Tip a Tip) = a\"\n  apply (induction a)\n  apply (auto)\ndone\n\nlemma zero_treesum [simp]: \"treesum (Node l 0 r) = (treesum l) + (treesum r)\"\n  apply (induction l)\n  apply (auto)\ndone\n\nlemma suc_treesum [simp]: \"treesum (Node l (Suc a) r) = Suc (treesum (Node l a r))\"\n  apply (induction a)\n  apply (auto)\ndone\n\nlemma listsum_app_distributivity [simp]: \"listsum (xs @ ys) = (listsum xs) + (listsum ys)\"\n  apply (induction xs)\n  apply (auto)\ndone\n\ntheorem treesum_is_contents_sum [simp]: \"treesum t = listsum (contents t)\"\n  apply (induction t rule: treesum.induct)\n  apply (auto)\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/Exercise6.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206712569267, "lm_q2_score": 0.8289388040954683, "lm_q1q2_score": 0.7476370426206987}}
{"text": "theory Poincare_Between\n  imports Poincare_Distance\nbegin\n\n(* ------------------------------------------------------------------ *)\nsection\\<open>H-betweenness in the Poincar\\'e model\\<close>\n(* ------------------------------------------------------------------ *)\n\nsubsection \\<open>H-betwenness expressed by a cross-ratio\\<close>\n\ntext\\<open>The point $v$ is h-between $u$ and $w$ if the cross-ratio between the pairs $u$ and $w$ and $v$\nand inverse of $v$ is real and negative.\\<close>\ndefinition poincare_between :: \"complex_homo \\<Rightarrow> complex_homo \\<Rightarrow> complex_homo \\<Rightarrow> bool\" where\n  \"poincare_between u v w \\<longleftrightarrow>\n         u = v \\<or> v = w \\<or>\n         (let cr = cross_ratio u v w (inversion v)\n           in is_real (to_complex cr) \\<and> Re (to_complex cr) < 0)\"\n\nsubsubsection \\<open>H-betwenness is preserved by h-isometries\\<close>\n\ntext \\<open>Since they preserve cross-ratio and inversion, h-isometries (unit disc preserving M\u00f6bius\ntransformations and conjugation) preserve h-betweeness.\\<close>\n\nlemma unit_disc_fix_moebius_preserve_poincare_between [simp]:\n  assumes \"unit_disc_fix M\" and \"u \\<in> unit_disc\" and \"v \\<in> unit_disc\" and \"w \\<in> unit_disc\"\n  shows \"poincare_between (moebius_pt M u) (moebius_pt M v) (moebius_pt M w) \\<longleftrightarrow>\n         poincare_between u v w\"\nproof (cases \"u = v \\<or> v = w\")\n  case True\n  thus ?thesis\n    using assms\n    unfolding poincare_between_def\n    by auto\nnext\n  case False\n  moreover\n  hence \"moebius_pt M u \\<noteq> moebius_pt M v \\<and> moebius_pt M v \\<noteq> moebius_pt M w\"\n    by auto\n  moreover\n  have \"v \\<noteq> inversion v\" \"w \\<noteq> inversion v\"\n    using inversion_noteq_unit_disc[of v w]\n    using inversion_noteq_unit_disc[of v v]\n    using \\<open>v \\<in> unit_disc\\<close> \\<open>w \\<in> unit_disc\\<close>\n    by auto\n  ultimately\n  show ?thesis\n    using assms\n    using unit_circle_fix_moebius_pt_inversion[of M v, symmetric]\n    unfolding poincare_between_def\n    by (simp del: unit_circle_fix_moebius_pt_inversion)\nqed\n\nlemma conjugate_preserve_poincare_between [simp]:\n  assumes \"u \\<in> unit_disc\" and \"v \\<in> unit_disc\" and \"w \\<in> unit_disc\"\n  shows \"poincare_between (conjugate u) (conjugate v) (conjugate w) \\<longleftrightarrow>\n         poincare_between u v w\"\nproof (cases \"u = v \\<or> v = w\")\n  case True\n  thus ?thesis\n    using assms\n    unfolding poincare_between_def\n    by auto\nnext\n  case False\n  moreover\n  hence \"conjugate u \\<noteq> conjugate v \\<and> conjugate v \\<noteq> conjugate w\"\n    using conjugate_inj by blast\n  moreover\n  have \"v \\<noteq> inversion v\" \"w \\<noteq> inversion v\"\n    using inversion_noteq_unit_disc[of v w]\n    using inversion_noteq_unit_disc[of v v]\n    using \\<open>v \\<in> unit_disc\\<close> \\<open>w \\<in> unit_disc\\<close>\n    by auto\n  ultimately\n  show ?thesis\n    using assms\n    using conjugate_cross_ratio[of v w \"inversion v\" u]\n    unfolding poincare_between_def\n    by (metis conjugate_id_iff conjugate_involution inversion_def inversion_sym o_apply)\nqed\n\n\nsubsubsection \\<open>Some elementary properties of h-betwenness\\<close>\n\nlemma poincare_between_nonstrict [simp]:\n  shows \"poincare_between u u v\" and \"poincare_between u v v\"\n  by (simp_all add: poincare_between_def)                       \n\nlemma poincare_between_sandwich:\n  assumes \"u \\<in> unit_disc\" and \"v \\<in> unit_disc\"\n  assumes \"poincare_between u v u\"\n  shows \"u = v\"\nproof (rule ccontr)\n  assume \"\\<not> ?thesis\"\n  thus False\n    using assms\n    using inversion_noteq_unit_disc[of v u]\n    using cross_ratio_1[of v u \"inversion v\"]\n    unfolding poincare_between_def Let_def\n    by auto\nqed\n\nlemma poincare_between_rev:\n  assumes \"u \\<in> unit_disc\" and \"v \\<in> unit_disc\" and \"w \\<in> unit_disc\"\n  shows \"poincare_between u v w \\<longleftrightarrow> poincare_between w v u\"       \n  using assms \n  using inversion_noteq_unit_disc[of v w]\n  using inversion_noteq_unit_disc[of v u]\n  using cross_ratio_commute_13[of u v w \"inversion v\"]\n  using cross_ratio_not_inf[of w \"inversion v\" v u]\n  using cross_ratio_not_zero[of w v u \"inversion v\"]\n  using inf_or_of_complex[of \"cross_ratio w v u (inversion v)\"]\n  unfolding poincare_between_def\n  by (auto simp add: Let_def Im_complex_div_eq_0 Re_divide divide_less_0_iff)\n\nsubsubsection \\<open>H-betwenness and h-collinearity\\<close>\n\ntext\\<open>Three points can be in an h-between relation only when they are h-collinear.\\<close>\nlemma poincare_between_poincare_collinear [simp]:       \n  assumes in_disc: \"u \\<in> unit_disc\"  \"v \\<in> unit_disc\"  \"w \\<in> unit_disc\"\n  assumes betw: \"poincare_between u v w\"\n  shows \"poincare_collinear {u, v, w}\"\nproof (cases \"u = v \\<or> v = w\")\n  case True\n  thus ?thesis\n    using assms\n    by auto\nnext\n  case False\n  hence distinct: \"distinct [u, v, w, inversion v]\"\n    using in_disc inversion_noteq_unit_disc[of v v] inversion_noteq_unit_disc[of v u] inversion_noteq_unit_disc[of v w]\n    using betw poincare_between_sandwich[of w v]\n    by (auto simp add: poincare_between_def Let_def)\n\n  then obtain H where *: \"{u, v, w, inversion v} \\<subseteq> circline_set H\"\n    using assms\n    unfolding poincare_between_def\n    using four_points_on_circline_iff_cross_ratio_real[of u v w \"inversion v\"]\n    by auto\n  hence \"H = poincare_line u v\"\n    using assms distinct\n    using unique_circline_set[of u v \"inversion v\"]\n    using poincare_line[of u v] poincare_line_inversion[of u v]\n    unfolding circline_set_def\n    by auto\n  thus ?thesis\n    using * assms False\n    unfolding poincare_collinear_def\n    by (rule_tac x=\"poincare_line u v\" in exI) simp\nqed\n\nlemma poincare_between_poincare_line_uvz:\n  assumes \"u \\<noteq> v\" and \"u \\<in> unit_disc\" and \"v \\<in> unit_disc\" and\n          \"z \\<in> unit_disc\" and \"poincare_between u v z\"\n  shows \"z \\<in> circline_set (poincare_line u v)\"\n  using assms\n  using poincare_between_poincare_collinear[of u v z]\n  using unique_poincare_line[OF assms(1-3)]\n  unfolding poincare_collinear_def\n  by auto\n\nlemma poincare_between_poincare_line_uzv:\n  assumes \"u \\<noteq> v\" and \"u \\<in> unit_disc\" and \"v \\<in> unit_disc\" and\n          \"z \\<in> unit_disc\" \"poincare_between u z v\"\n  shows \"z \\<in> circline_set (poincare_line u v)\"\n  using assms\n  using poincare_between_poincare_collinear[of u z v]\n  using unique_poincare_line[OF assms(1-3)]\n  unfolding poincare_collinear_def\n  by auto\n\nsubsubsection \\<open>H-betweeness on Euclidean segments\\<close> \n\ntext\\<open>If the three points lie on an h-line that is a Euclidean line (e.g., if it contains zero),\nh-betweenness can be characterized much simpler than in the definition.\\<close>\n\nlemma poincare_between_x_axis_u0v:\n  assumes \"is_real u'\" and \"u' \\<noteq> 0\" and \"v' \\<noteq> 0\"\n  shows \"poincare_between (of_complex u') 0\\<^sub>h (of_complex v') \\<longleftrightarrow> is_real v' \\<and> Re u' * Re v' < 0\"\nproof-\n  have \"Re u' \\<noteq> 0\"\n    using \\<open>is_real u'\\<close> \\<open>u' \\<noteq> 0\\<close>\n    using complex_eq_if_Re_eq\n    by auto\n  have nz: \"of_complex u' \\<noteq> 0\\<^sub>h\" \"of_complex v' \\<noteq> 0\\<^sub>h\"\n    by (simp_all add: \\<open>u' \\<noteq> 0\\<close> \\<open>v' \\<noteq> 0\\<close>)\n  hence \"0\\<^sub>h \\<noteq> of_complex v'\"\n    by metis\n\n  let ?cr = \"cross_ratio (of_complex u') 0\\<^sub>h (of_complex v') \\<infinity>\\<^sub>h\"\n  have \"is_real (to_complex ?cr) \\<and> Re (to_complex ?cr) < 0 \\<longleftrightarrow> is_real v' \\<and> Re u' * Re v' < 0\"\n    using cross_ratio_0inf[of v' u'] \\<open>v' \\<noteq> 0\\<close> \\<open>u' \\<noteq> 0\\<close> \\<open>is_real u'\\<close>\n    by (metis Re_complex_div_lt_0 Re_mult_real complex_cnj_divide divide_cancel_left eq_cnj_iff_real to_complex_of_complex)\n  thus ?thesis\n    unfolding poincare_between_def inversion_zero\n    using \\<open>of_complex u' \\<noteq> 0\\<^sub>h\\<close> \\<open>0\\<^sub>h \\<noteq> of_complex v'\\<close>\n    by simp\nqed\n\nlemma poincare_between_u0v:\n  assumes \"u \\<in> unit_disc\" and \"v \\<in> unit_disc\" and \"u \\<noteq> 0\\<^sub>h\" and \"v \\<noteq> 0\\<^sub>h\"\n  shows \"poincare_between u 0\\<^sub>h v \\<longleftrightarrow> (\\<exists> k < 0. to_complex u = cor k * to_complex v)\" (is \"?P u v\")\nproof (cases \"u = v\")\n  case True\n  thus ?thesis\n    using assms\n    using inf_or_of_complex[of v]\n    using poincare_between_sandwich[of u \"0\\<^sub>h\"]      \n    by auto\nnext                                                 \n  case False\n  have \"\\<forall> u. u \\<in> unit_disc \\<and> u \\<noteq> 0\\<^sub>h \\<longrightarrow> ?P u v\" (is \"?P' v\")\n  proof (rule wlog_rotation_to_positive_x_axis)\n    fix \\<phi> v\n    let ?M = \"moebius_pt (moebius_rotation \\<phi>)\"\n    assume 1: \"v \\<in> unit_disc\" \"v \\<noteq> 0\\<^sub>h\"\n    assume 2: \"?P' (?M v)\"\n    show \"?P' v\"\n    proof (rule allI, rule impI, (erule conjE)+)\n      fix u\n      assume 3: \"u \\<in> unit_disc\" \"u \\<noteq> 0\\<^sub>h\"  \n      have \"poincare_between (?M u) 0\\<^sub>h (?M v) \\<longleftrightarrow> poincare_between u 0\\<^sub>h v\"\n        using \\<open>u \\<in> unit_disc\\<close> \\<open>v \\<in> unit_disc\\<close>\n        using unit_disc_fix_moebius_preserve_poincare_between unit_disc_fix_rotation zero_in_unit_disc \n        by fastforce\n      thus \"?P u v\"\n        using 1 2[rule_format, of \"?M u\"] 3\n        using inf_or_of_complex[of u] inf_or_of_complex[of v]\n        by auto\n    qed\n  next\n    fix x\n    assume 1: \"is_real x\" \"0 < Re x\" \"Re x < 1\"\n    hence \"x \\<noteq> 0\"\n      by auto\n    show \"?P' (of_complex x)\"    \n    proof (rule allI, rule impI, (erule conjE)+)\n      fix u\n      assume 2: \"u \\<in> unit_disc\" \"u \\<noteq> 0\\<^sub>h\"\n      then obtain u' where \"u = of_complex u'\"\n        using inf_or_of_complex[of u]\n        by auto\n      show \"?P u (of_complex x)\"\n        using 1 2 \\<open>x \\<noteq> 0\\<close> \\<open>u = of_complex u'\\<close>\n        using poincare_between_rev[of u \"0\\<^sub>h\" \"of_complex x\"]\n        using poincare_between_x_axis_u0v[of x u'] \\<open>is_real x\\<close>\n        apply (auto simp add: cmod_eq_Re)\n        apply (rule_tac x=\"Re u' / Re x\" in exI, simp add: divide_neg_pos algebra_split_simps)\n        using mult_neg_pos mult_pos_neg\n        by blast\n    qed\n  qed fact+\n  thus ?thesis\n    using assms\n    by auto\nqed\n\nlemma poincare_between_u0v_polar_form:\n  assumes \"x \\<in> unit_disc\" and \"y \\<in> unit_disc\" and \"x \\<noteq> 0\\<^sub>h\" and \"y \\<noteq> 0\\<^sub>h\" and \n          \"to_complex x = cor rx * cis \\<phi>\" \"to_complex y = cor ry * cis \\<phi>\"\n  shows \"poincare_between x 0\\<^sub>h y \\<longleftrightarrow> rx * ry < 0\" (is \"?P x y rx ry\")\nproof-\n  from assms have \"rx \\<noteq> 0\" \"ry \\<noteq> 0\"\n    using inf_or_of_complex[of x] inf_or_of_complex[of y]\n    by auto\n\n  have \"(\\<exists>k<0. cor rx = cor k * cor ry ) = (rx * ry < 0)\"\n  proof\n    assume \"\\<exists>k<0. cor rx = cor k * cor ry\"\n    then obtain k where \"k < 0\" \"cor rx = cor k * cor ry\"\n      by auto\n    hence \"rx = k * ry\"\n      using of_real_eq_iff\n      by fastforce\n    thus \"rx * ry < 0\" \n      using \\<open>k < 0\\<close> \\<open>rx \\<noteq> 0\\<close> \\<open>ry \\<noteq> 0\\<close>\n      by (smt divisors_zero mult_nonneg_nonpos mult_nonpos_nonpos zero_less_mult_pos2)\n  next\n    assume \"rx * ry < 0\"\n    hence \"rx = (rx/ry)*ry\" \"rx / ry < 0\"\n      using \\<open>rx \\<noteq> 0\\<close> \\<open>ry \\<noteq> 0\\<close>\n      by (auto simp add: divide_less_0_iff algebra_split_simps)\n    thus \"\\<exists>k<0. cor rx = cor k * cor ry\"\n      using \\<open>rx \\<noteq> 0\\<close> \\<open>ry \\<noteq> 0\\<close>\n      by (rule_tac x=\"rx / ry\" in exI, simp)\n  qed\n  thus ?thesis\n    using assms                                 \n    using poincare_between_u0v[OF assms(1-4)]\n    by auto\nqed\n\nlemma poincare_between_x_axis_0uv:\n  fixes x y :: real\n  assumes \"-1 < x\" and \"x < 1\" and \"x \\<noteq> 0\"\n  assumes \"-1 < y\" and \"y < 1\" and \"y \\<noteq> 0\"\n  shows \"poincare_between 0\\<^sub>h (of_complex x) (of_complex y) \\<longleftrightarrow>\n        (x < 0 \\<and> y < 0 \\<and> y \\<le> x) \\<or> (x > 0 \\<and> y > 0 \\<and> x \\<le> y)\" (is \"?lhs \\<longleftrightarrow> ?rhs\")\nproof (cases \"x = y\")\n  case True\n  thus ?thesis\n    using assms\n    unfolding poincare_between_def\n    by auto\nnext\n  case False\n  let ?x = \"of_complex x\" and ?y = \"of_complex y\"\n\n  have \"?x \\<in> unit_disc\" \"?y \\<in> unit_disc\"\n    using assms\n    by auto\n\n  have distinct: \"distinct [0\\<^sub>h, ?x, ?y, inversion ?x]\"\n    using \\<open>x \\<noteq> 0\\<close> \\<open>y \\<noteq> 0\\<close> \\<open>x \\<noteq> y\\<close> \\<open>?x \\<in> unit_disc\\<close> \\<open>?y \\<in> unit_disc\\<close>\n    using inversion_noteq_unit_disc[of ?x ?y]\n    using inversion_noteq_unit_disc[of ?x ?x]\n    using inversion_noteq_unit_disc[of ?x \"0\\<^sub>h\"]\n    using of_complex_inj[of x y]\n    by (metis distinct_length_2_or_more distinct_singleton of_complex_zero_iff of_real_eq_0_iff of_real_eq_iff zero_in_unit_disc)\n\n  let ?cr = \"cross_ratio 0\\<^sub>h ?x ?y (inversion ?x)\"\n  have \"Re (to_complex ?cr) = x\\<^sup>2 * (x*y - 1) / (x * (y - x))\"\n    using \\<open>x \\<noteq> 0\\<close> \\<open>x \\<noteq> y\\<close>\n    unfolding inversion_def\n    by simp (transfer, transfer, auto simp add: vec_cnj_def power2_eq_square field_simps split: if_split_asm)\n  moreover\n  { \n    fix a b :: real\n    assume \"b \\<noteq> 0\"\n    hence \"a < 0 \\<longleftrightarrow> b\\<^sup>2 * a < (0::real)\"\n      by (metis mult.commute mult_eq_0_iff mult_neg_pos mult_pos_pos not_less_iff_gr_or_eq not_real_square_gt_zero power2_eq_square)\n  }\n  hence \"x\\<^sup>2 * (x*y - 1) < 0\"\n    using assms\n    by (smt minus_mult_minus mult_le_cancel_left1)\n  moreover\n  have \"x * (y - x) > 0 \\<longleftrightarrow> ?rhs\"\n    using \\<open>x \\<noteq> 0\\<close> \\<open>y \\<noteq> 0\\<close> \\<open>x \\<noteq> y\\<close>\n    by (smt mult_le_0_iff)\n  ultimately\n  have *: \"Re (to_complex ?cr) < 0 \\<longleftrightarrow> ?rhs\"\n    by (simp add: divide_less_0_iff)\n\n  show ?thesis\n  proof\n    assume ?lhs\n    have \"is_real (to_complex ?cr)\" \"Re (to_complex ?cr) < 0\"\n      using \\<open>?lhs\\<close> distinct\n      unfolding poincare_between_def Let_def\n      by auto\n    thus ?rhs\n      using *\n      by simp\n  next\n    assume ?rhs\n    hence \"Re (to_complex ?cr) < 0\"\n      using *\n      by simp\n    moreover\n    have \"{0\\<^sub>h, of_complex (cor x), of_complex (cor y), inversion (of_complex (cor x))} \\<subseteq> circline_set x_axis\"\n      using \\<open>x \\<noteq> 0\\<close> is_real_inversion[of \"cor x\"]\n      using inf_or_of_complex[of \"inversion ?x\"]\n      by (auto simp del: inversion_of_complex)\n    hence \"is_real (to_complex ?cr)\"\n      using four_points_on_circline_iff_cross_ratio_real[OF distinct]\n      by auto\n    ultimately\n    show ?lhs\n      using distinct\n      unfolding poincare_between_def Let_def\n      by auto\n  qed\nqed\n\nlemma poincare_between_0uv:\n  assumes \"u \\<in> unit_disc\" and \"v \\<in> unit_disc\" and \"u \\<noteq> 0\\<^sub>h\" and \"v \\<noteq> 0\\<^sub>h\"\n  shows \"poincare_between 0\\<^sub>h u v \\<longleftrightarrow>\n         (let u' = to_complex u; v' = to_complex v in arg u' = arg v' \\<and> cmod u' \\<le> cmod v')\" (is \"?P u v\")\nproof (cases \"u = v\")\n  case True\n  thus ?thesis\n    by simp\nnext\n  case False\n  have \"\\<forall> v. v \\<in> unit_disc \\<and> v \\<noteq> 0\\<^sub>h \\<and> v \\<noteq> u \\<longrightarrow> (poincare_between 0\\<^sub>h u v \\<longleftrightarrow> (let u' = to_complex u; v' = to_complex v in arg u' = arg v' \\<and> cmod u' \\<le> cmod v'))\" (is \"?P' u\")\n  proof (rule wlog_rotation_to_positive_x_axis)\n    show \"u \\<in> unit_disc\" \"u \\<noteq> 0\\<^sub>h\"\n      by fact+\n  next\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 \\<noteq> 0\\<^sub>h\" \"of_complex x \\<in> circline_set x_axis\"\n      unfolding circline_set_x_axis\n      by (auto simp add: cmod_eq_Re)\n    show \"?P' (of_complex x)\"\n    proof safe\n      fix v\n      assume \"v \\<in> unit_disc\" \"v \\<noteq> 0\\<^sub>h\" \"v \\<noteq> of_complex x\" \"poincare_between 0\\<^sub>h (of_complex x) v\"\n      hence \"v \\<in> circline_set x_axis\"\n        using poincare_between_poincare_line_uvz[of \"0\\<^sub>h\" \"of_complex x\" v]\n        using poincare_line_0_real_is_x_axis[of \"of_complex x\"]\n        using \\<open>of_complex x \\<noteq> 0\\<^sub>h\\<close> \\<open>v \\<noteq> 0\\<^sub>h\\<close> \\<open>v \\<noteq> of_complex x\\<close> \\<open>of_complex x \\<in> unit_disc\\<close> \\<open>of_complex x \\<in> circline_set x_axis\\<close>\n        by auto\n      obtain v' where \"v = of_complex v'\"\n        using \\<open>v \\<in> unit_disc\\<close>\n        using inf_or_of_complex[of v]\n        by auto\n      hence **: \"v = of_complex v'\" \"-1 < Re v'\" \"Re v' < 1\" \"Re v' \\<noteq> 0\" \"is_real v'\"\n        using \\<open>v \\<in> unit_disc\\<close> \\<open>v \\<noteq> 0\\<^sub>h\\<close> \\<open>v \\<in> circline_set x_axis\\<close> of_complex_inj[of v']\n        unfolding circline_set_x_axis\n        by (auto simp add: cmod_eq_Re real_imag_0)\n      show \"let u' = to_complex (of_complex x); v' = to_complex v in arg u' = arg v' \\<and> cmod u' \\<le> cmod v'\"\n        using poincare_between_x_axis_0uv[of \"Re x\" \"Re v'\"] * **\n        using \\<open>poincare_between 0\\<^sub>h (of_complex x) v\\<close>\n        using arg_complex_of_real_positive[of \"Re x\"] arg_complex_of_real_negative[of \"Re x\"]\n        using arg_complex_of_real_positive[of \"Re v'\"] arg_complex_of_real_negative[of \"Re v'\"]\n        by (auto simp add: cmod_eq_Re)\n    next\n      fix v\n      assume \"v \\<in> unit_disc\" \"v \\<noteq> 0\\<^sub>h\" \"v \\<noteq> of_complex x\"\n      then obtain v' where **: \"v = of_complex v'\" \"v' \\<noteq> 0\" \"v' \\<noteq> x\"\n        using inf_or_of_complex[of v]\n        by auto blast\n      assume \"let u' = to_complex (of_complex x); v' = to_complex v in arg u' = arg v' \\<and> cmod u' \\<le> cmod v'\"\n      hence ***: \"Re x < 0 \\<and> Re v' < 0 \\<and> Re v' \\<le> Re x \\<or> 0 < Re x \\<and> 0 < Re v' \\<and> Re x \\<le> Re v'\" \"is_real v'\"\n        using arg_pi_iff[of x] arg_pi_iff[of v']\n        using arg_0_iff[of x] arg_0_iff[of v']\n        using * **\n        by (smt cmod_Re_le_iff to_complex_of_complex)+\n      have \"-1 < Re v'\" \"Re v' < 1\" \"Re v' \\<noteq> 0\" \"is_real v'\"\n        using \\<open>v \\<in> unit_disc\\<close> ** \\<open>is_real v'\\<close>\n        by (auto simp add: cmod_eq_Re complex_eq_if_Re_eq)\n      thus \"poincare_between 0\\<^sub>h (of_complex x) v\"\n        using poincare_between_x_axis_0uv[of \"Re x\" \"Re v'\"] * ** ***\n        by simp\n    qed\n  next\n    fix \\<phi> u\n    assume \"u \\<in> unit_disc\" \"u \\<noteq> 0\\<^sub>h\"\n    let ?M = \"moebius_rotation \\<phi>\"\n    assume *: \"?P' (moebius_pt ?M u)\"\n    show \"?P' u\"\n    proof (rule allI, rule impI, (erule conjE)+)\n      fix v\n      assume \"v \\<in> unit_disc\" \"v \\<noteq> 0\\<^sub>h\" \"v \\<noteq> u\"\n      have \"moebius_pt ?M v \\<noteq> moebius_pt ?M u\"\n        using \\<open>v \\<noteq> u\\<close>\n        by auto\n      obtain u' v' where \"v = of_complex v'\" \"u = of_complex u'\" \"v' \\<noteq> 0\" \"u' \\<noteq> 0\"\n        using inf_or_of_complex[of u] inf_or_of_complex[of v]\n        using \\<open>v \\<in> unit_disc\\<close> \\<open>u \\<in> unit_disc\\<close> \\<open>v \\<noteq> 0\\<^sub>h\\<close> \\<open>u \\<noteq> 0\\<^sub>h\\<close>\n        by auto\n      thus \"?P u v\"\n        using *[rule_format, of \"moebius_pt ?M v\"]\n        using \\<open>moebius_pt ?M v \\<noteq> moebius_pt ?M u\\<close>\n        using unit_disc_fix_moebius_preserve_poincare_between[of ?M \"0\\<^sub>h\" u v]\n        using \\<open>v \\<in> unit_disc\\<close> \\<open>u \\<in> unit_disc\\<close> \\<open>v \\<noteq> 0\\<^sub>h\\<close> \\<open>u \\<noteq> 0\\<^sub>h\\<close>\n        using arg_mult_eq[of \"cis \\<phi>\" u' v']\n        by simp (auto simp add: arg_mult)\n    qed\n  qed\n  thus ?thesis\n    using assms False\n    by auto\nqed\n\nlemma poincare_between_y_axis_0uv:\n  fixes x y :: real\n  assumes \"-1 < x\" and \"x < 1\" and \"x \\<noteq> 0\"\n  assumes \"-1 < y\" and \"y < 1\" and \"y \\<noteq> 0\"\n  shows \"poincare_between 0\\<^sub>h (of_complex (\\<i> * x)) (of_complex (\\<i> * y)) \\<longleftrightarrow>\n        (x < 0 \\<and> y < 0 \\<and> y \\<le> x) \\<or> (x > 0 \\<and> y > 0 \\<and> x \\<le> y)\" (is \"?lhs \\<longleftrightarrow> ?rhs\")\n  using assms\n  using poincare_between_0uv[of \"of_complex (\\<i> * x)\" \"of_complex (\\<i> * y)\"]\n  using arg_pi2_iff[of \"\\<i> * cor x\"] arg_pi2_iff[of \"\\<i> * cor y\"]\n  using arg_minus_pi2_iff[of \"\\<i> * cor x\"] arg_minus_pi2_iff[of \"\\<i> * cor y\"]\n  apply simp\n  apply (cases \"x > 0\")\n  apply (cases \"y > 0\", simp, simp)\n  apply (cases \"y > 0\")\n  apply simp\n  using pi_gt_zero apply linarith\n  apply simp\n  done\n\nlemma poincare_between_x_axis_uvw:\n  fixes x y z :: real\n  assumes \"-1 < x\" and \"x < 1\" \n  assumes \"-1 < y\" and \"y < 1\" and \"y \\<noteq> x\"\n  assumes \"-1 < z\" and \"z < 1\" and \"z \\<noteq> x\"\n  shows \"poincare_between (of_complex x) (of_complex y) (of_complex z) \\<longleftrightarrow>\n        (y < x \\<and> z < x \\<and> z \\<le> y) \\<or> (y > x \\<and> z > x \\<and> y \\<le> z)\"  (is \"?lhs \\<longleftrightarrow> ?rhs\")\nproof (cases \"x = 0 \\<or> y = 0 \\<or> z = 0\")\n  case True\n  thus ?thesis\n  proof (cases \"x = 0\")\n    case True\n    thus ?thesis\n      using poincare_between_x_axis_0uv assms\n      by simp\n  next\n    case False\n    show ?thesis\n    proof (cases \"z = 0\")\n      case True\n      thus ?thesis\n        using poincare_between_x_axis_0uv assms poincare_between_rev\n        by (smt norm_of_real of_complex_zero of_real_0 poincare_between_nonstrict(2) unit_disc_iff_cmod_lt_1)\n    next\n      case False\n      have \"y = 0\"\n        using `x \\<noteq> 0` `z \\<noteq> 0` `x = 0 \\<or> y = 0 \\<or> z = 0`\n        by simp\n\n      have \"poincare_between (of_complex x) 0\\<^sub>h (of_complex z) = (is_real z \\<and> x * z < 0)\"\n        using `x \\<noteq> 0` `z \\<noteq> 0` poincare_between_x_axis_u0v \n        by auto\n      moreover\n      have \"x * z < 0 \\<longleftrightarrow> ?rhs\"\n        using True \\<open>x \\<noteq> 0\\<close> \\<open>z \\<noteq> 0\\<close>\n        by (smt zero_le_mult_iff)\n      ultimately\n      show ?thesis\n        using `y = 0`\n        by auto\n    qed\n  qed\nnext\n  case False\n  thus ?thesis\n  proof (cases \"z = y\")\n    case True\n    thus ?thesis\n      using assms\n      unfolding poincare_between_def\n      by auto\n  next\n    case False\n    let ?x = \"of_complex x\" and ?y = \"of_complex y\" and ?z = \"of_complex z\"\n  \n    have \"?x \\<in> unit_disc\" \"?y \\<in> unit_disc\" \"?z \\<in> unit_disc\"\n      using assms\n      by auto\n  \n    have distinct: \"distinct [?x, ?y, ?z, inversion ?y]\"\n      using \\<open>y \\<noteq> x\\<close> \\<open>z \\<noteq> x\\<close> False \\<open>?x \\<in> unit_disc\\<close> \\<open>?y \\<in> unit_disc\\<close> \\<open>?z \\<in> unit_disc\\<close>\n      using inversion_noteq_unit_disc[of ?y ?y]\n      using inversion_noteq_unit_disc[of ?y ?x]\n      using inversion_noteq_unit_disc[of ?y ?z]\n      using of_complex_inj[of x y]  of_complex_inj[of y z]  of_complex_inj[of x z]\n      by auto\n\n    have \"cor y * cor x \\<noteq> 1\"\n      using assms\n      by (smt minus_mult_minus mult_less_cancel_left2 mult_less_cancel_right2 of_real_1 of_real_eq_iff of_real_mult)\n  \n    let ?cr = \"cross_ratio ?x ?y ?z (inversion ?y)\"\n    have \"Re (to_complex ?cr) = (x - y) * (z*y - 1)/ ((x*y - 1)*(z - y))\"\n    proof-\n      have \" \\<And>y x z. \\<lbrakk>y \\<noteq> x; z \\<noteq> x; z \\<noteq> y; cor y * cor x \\<noteq> 1; x \\<noteq> 0; y \\<noteq> 0; z \\<noteq> 0\\<rbrakk> \\<Longrightarrow> \n           (y * y + y * (y * (x * z)) - (y * x + y * (y * (y * z)))) /\n           (y * y + y * (y * (x * z)) - (y * z + y * (y * (y * x)))) =\n           (y + y * (x * z) - (x + y * (y * z))) / (y + y * (x * z) - (z + y * (y * x)))\"\n        by (metis (no_types, hide_lams) ab_group_add_class.ab_diff_conv_add_uminus distrib_left mult_divide_mult_cancel_left_if mult_minus_right)\n      thus ?thesis\n        using \\<open>y \\<noteq> x\\<close> \\<open>z \\<noteq> x\\<close> False \\<open>\\<not> (x = 0 \\<or> y = 0 \\<or> z = 0)\\<close>\n        using \\<open>cor y * cor x \\<noteq> 1\\<close>\n        unfolding inversion_def\n        by (transfer, transfer, auto simp add: vec_cnj_def power2_eq_square field_simps split: if_split_asm)\n    qed\n      \n    moreover\n    have \"(x*y - 1) < 0\"\n      using assms\n      by (smt minus_mult_minus mult_less_cancel_right2 zero_less_mult_iff)\n    moreover\n    have \"(z*y - 1) < 0\"\n      using assms\n      by (smt minus_mult_minus mult_less_cancel_right2 zero_less_mult_iff)\n    moreover\n    have \"(x - y) / (z - y) < 0 \\<longleftrightarrow> ?rhs\"\n      using \\<open>y \\<noteq> x\\<close> \\<open>z \\<noteq> x\\<close> False \\<open>\\<not> (x = 0 \\<or> y = 0 \\<or> z = 0)\\<close>\n      by (smt divide_less_cancel divide_nonneg_nonpos divide_nonneg_pos divide_nonpos_nonneg divide_nonpos_nonpos)\n    ultimately\n    have *: \"Re (to_complex ?cr) < 0 \\<longleftrightarrow> ?rhs\"\n      by (smt algebra_split_simps(24) minus_divide_left zero_less_divide_iff zero_less_mult_iff)\n    show ?thesis\n    proof\n      assume ?lhs\n      have \"is_real (to_complex ?cr)\" \"Re (to_complex ?cr) < 0\"\n        using \\<open>?lhs\\<close> distinct\n        unfolding poincare_between_def Let_def\n        by auto\n      thus ?rhs\n        using *\n        by simp\n    next\n      assume ?rhs\n      hence \"Re (to_complex ?cr) < 0\"\n        using *\n        by simp\n      moreover\n      have \"{of_complex (cor x), of_complex (cor y), of_complex (cor z), inversion (of_complex (cor y))} \\<subseteq> circline_set x_axis\"\n        using \\<open>\\<not> (x = 0 \\<or> y = 0 \\<or> z = 0)\\<close> is_real_inversion[of \"cor y\"]\n        using inf_or_of_complex[of \"inversion ?y\"]\n        by (auto simp del: inversion_of_complex)\n      hence \"is_real (to_complex ?cr)\"\n        using four_points_on_circline_iff_cross_ratio_real[OF distinct]\n        by auto\n      ultimately\n      show ?lhs\n        using distinct\n        unfolding poincare_between_def Let_def\n        by auto\n    qed\n  qed\nqed\n\nsubsubsection \\<open>H-betweenness and h-collinearity\\<close>\n\ntext\\<open>For three h-collinear points at least one of the three possible h-betweeness relations must\nhold.\\<close>\nlemma poincare_collinear3_between:\n  assumes \"u \\<in> unit_disc\" and \"v \\<in> unit_disc\" and \"w \\<in> unit_disc\"\n  assumes \"poincare_collinear {u, v, w}\"\n  shows \"poincare_between u v w \\<or> poincare_between u w v \\<or> poincare_between v u w\" (is \"?P' u v w\")\nproof (cases \"u=v\")\n  case True\n  thus ?thesis\n    using assms\n    by auto\nnext\n  case False\n  have \"\\<forall> w. w \\<in> unit_disc \\<and> poincare_collinear {u, v, w} \\<longrightarrow> ?P' u v w\" (is \"?P u v\")\n  proof (rule wlog_positive_x_axis[where P=\"?P\"])\n    fix x\n    assume x: \"is_real x\" \"0 < Re x\" \"Re x < 1\"\n    hence \"x \\<noteq> 0\"\n      using complex.expand[of x 0]\n      by auto\n    hence *: \"poincare_line 0\\<^sub>h (of_complex x) = x_axis\"\n      using x poincare_line_0_real_is_x_axis[of \"of_complex x\"]\n      unfolding circline_set_x_axis\n      by auto\n    have \"of_complex x \\<in> unit_disc\"\n      using x\n      by (auto simp add: cmod_eq_Re)\n    have \"of_complex x \\<noteq> 0\\<^sub>h\"\n      using \\<open>x \\<noteq> 0\\<close>\n      by auto\n    show \"?P 0\\<^sub>h (of_complex x)\"\n    proof safe\n      fix w\n      assume \"w \\<in> unit_disc\"\n      assume \"poincare_collinear {0\\<^sub>h, of_complex x, w}\"\n      hence \"w \\<in> circline_set x_axis\"\n        using * unique_poincare_line[of \"0\\<^sub>h\" \"of_complex x\"] \\<open>of_complex x \\<in> unit_disc\\<close> \\<open>x \\<noteq> 0\\<close> \\<open>of_complex x \\<noteq> 0\\<^sub>h\\<close>\n        unfolding poincare_collinear_def\n        by auto\n      then obtain w' where w': \"w = of_complex w'\" \"is_real w'\"\n        using \\<open>w \\<in> unit_disc\\<close>\n        using inf_or_of_complex[of w]\n        unfolding circline_set_x_axis\n        by auto\n      hence \"-1 < Re w'\" \"Re w' < 1\"\n        using \\<open>w \\<in> unit_disc\\<close>\n        by (auto simp add: cmod_eq_Re)\n      assume 1: \"\\<not> poincare_between (of_complex x) 0\\<^sub>h w\"\n      hence \"w \\<noteq> 0\\<^sub>h\" \"w' \\<noteq> 0\"\n        using w'\n        unfolding poincare_between_def\n        by auto\n      hence \"Re w' \\<noteq> 0\"\n        using w' complex.expand[of w' 0]\n        by auto\n\n      have \"Re w' \\<ge> 0\"\n        using 1 poincare_between_x_axis_u0v[of x w'] \\<open>Re x > 0\\<close> \\<open>is_real x\\<close> \\<open>x \\<noteq> 0\\<close> \\<open>w' \\<noteq> 0\\<close> w'\n        using mult_pos_neg\n        by force\n\n      moreover\n\n      assume \"\\<not> poincare_between 0\\<^sub>h (of_complex x) w\"\n      hence \"Re w' < Re x\"\n        using poincare_between_x_axis_0uv[of \"Re x\" \"Re w'\"]\n        using w' x \\<open>-1 < Re w'\\<close> \\<open>Re w' < 1\\<close> \\<open>Re w' \\<noteq> 0\\<close>\n        by auto\n\n      ultimately\n      show \"poincare_between 0\\<^sub>h w (of_complex x)\"\n        using poincare_between_x_axis_0uv[of \"Re w'\" \"Re x\"]\n        using w' x \\<open>-1 < Re w'\\<close> \\<open>Re w' < 1\\<close> \\<open>Re w' \\<noteq> 0\\<close>\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    assume 1: \"unit_disc_fix M\" \"u \\<in> unit_disc\" \"v \\<in> unit_disc\" \"u \\<noteq> v\"\n    let ?Mu = \"moebius_pt M u\" and ?Mv = \"moebius_pt M v\"\n    assume 2: \"?P ?Mu ?Mv\"\n    show \"?P u v\"\n    proof safe\n      fix w\n      assume \"w \\<in> unit_disc\" \"poincare_collinear {u, v, w}\" \"\\<not> poincare_between u v w\" \"\\<not> poincare_between v u w\"\n      thus \"poincare_between u w v\"\n        using 1 2[rule_format, of \"moebius_pt M w\"]\n        by simp\n    qed\n  qed\n  thus ?thesis\n    using assms\n    by simp\nqed\n\nlemma poincare_collinear3_iff:\n  assumes \"u \\<in> unit_disc\" \"v \\<in> unit_disc\"  \"w \\<in> unit_disc\"\n  shows \"poincare_collinear {u, v, w} \\<longleftrightarrow> poincare_between u v w \\<or> poincare_between v u w \\<or> poincare_between v w u\"\n  using assms \n  by (metis poincare_collinear3_between insert_commute poincare_between_poincare_collinear poincare_between_rev)\n\nsubsection \\<open>Some properties of betweenness\\<close>\n\nlemma poincare_between_transitivity:\n  assumes \"a \\<in> unit_disc\" and \"x \\<in> unit_disc\" and \"b \\<in> unit_disc\" and \"y \\<in> unit_disc\" and\n          \"poincare_between a x b\" and \"poincare_between a b y\"\n  shows \"poincare_between x b y\"\nproof(cases \"a = b\")\n  case True\n  thus ?thesis\n    using assms\n    using poincare_between_sandwich by blast\nnext\n  case False\n  have \"\\<forall> x. \\<forall> y. poincare_between a x b \\<and> poincare_between a b y \\<and> x \\<in> unit_disc\n                  \\<and> y \\<in> unit_disc \\<longrightarrow> poincare_between x b y\" (is \"?P a b\")\n  proof (rule wlog_positive_x_axis[where P=\"?P\"])\n    show \"a \\<in> unit_disc\"\n      using assms by simp\n  next\n    show \"b \\<in> unit_disc\"\n      using assms by simp\n  next\n    show \"a \\<noteq> b\"\n      using False by simp\n  next\n    fix M u v\n    assume *: \"unit_disc_fix M\" \"u \\<in> unit_disc\" \"v \\<in> unit_disc\" \"u \\<noteq> v\" \n              \"\\<forall>x y. poincare_between (moebius_pt M u) x (moebius_pt M v) \\<and> \n                  poincare_between (moebius_pt M u) (moebius_pt M v) y \\<and>\n                  x \\<in> unit_disc \\<and> y \\<in> unit_disc \\<longrightarrow>\n                  poincare_between x (moebius_pt M v) y\"\n    show \"\\<forall>x y. poincare_between u x v \\<and> poincare_between u v y \\<and> x \\<in> unit_disc \\<and> y \\<in> unit_disc \n                \\<longrightarrow> poincare_between x v y\"\n    proof safe\n      fix x y\n      assume \"poincare_between u x v\" \"poincare_between u v y\" \" x \\<in> unit_disc\" \"y \\<in> unit_disc\"\n\n      have \"poincare_between (moebius_pt M u) (moebius_pt M x) (moebius_pt M v)\" \n        using \\<open>poincare_between u x v\\<close> \\<open>unit_disc_fix M\\<close> \\<open>x \\<in> unit_disc\\<close> \\<open>u \\<in> unit_disc\\<close> \\<open>v \\<in> unit_disc\\<close>\n        by simp\n      moreover\n      have \"poincare_between (moebius_pt M u) (moebius_pt M v) (moebius_pt M y)\"\n        using \\<open>poincare_between u v y\\<close> \\<open>unit_disc_fix M\\<close> \\<open>y \\<in> unit_disc\\<close> \\<open>u \\<in> unit_disc\\<close> \\<open>v \\<in> unit_disc\\<close>\n        by simp\n      moreover\n      have \"(moebius_pt M x) \\<in> unit_disc\"\n        using \\<open>unit_disc_fix M\\<close> \\<open>x \\<in> unit_disc\\<close> by simp\n      moreover\n      have \"(moebius_pt M y) \\<in> unit_disc\"\n        using \\<open>unit_disc_fix M\\<close> \\<open>y \\<in> unit_disc\\<close> by simp\n      ultimately\n      have \"poincare_between (moebius_pt M x) (moebius_pt M v) (moebius_pt M y)\"\n        using * by blast\n      thus \"poincare_between x v y\"\n        using \\<open>y \\<in> unit_disc\\<close> * \\<open>x \\<in> unit_disc\\<close> by simp\n    qed\n  next\n    fix x\n    assume xx: \"is_real x\" \"0 < Re x\" \"Re x < 1\"\n    hence \"of_complex x \\<in> unit_disc\"\n      using cmod_eq_Re by auto\n    hence \"of_complex x \\<noteq> \\<infinity>\\<^sub>h\"\n      by simp\n    have \" of_complex x \\<noteq> 0\\<^sub>h\"\n      using xx by auto\n    have \"of_complex x \\<in> circline_set x_axis\"\n      using xx by simp\n    show \"\\<forall>m n. poincare_between 0\\<^sub>h m (of_complex x) \\<and> poincare_between 0\\<^sub>h (of_complex x) n \\<and>\n            m \\<in> unit_disc \\<and> n \\<in> unit_disc \\<longrightarrow> poincare_between m (of_complex x) n\"\n    proof safe\n      fix m n\n      assume **: \"poincare_between 0\\<^sub>h m (of_complex x)\" \"poincare_between 0\\<^sub>h (of_complex x) n\"\n                 \"m \\<in> unit_disc\" \" n \\<in> unit_disc\"\n      show \"poincare_between m (of_complex x) n\"\n      proof(cases \"m = 0\\<^sub>h\")\n        case True\n        thus ?thesis\n          using ** by auto\n      next\n        case False\n        hence \"m \\<in> circline_set x_axis\"\n          using poincare_between_poincare_line_uzv[of \"0\\<^sub>h\" \"of_complex x\" m]\n          using poincare_line_0_real_is_x_axis[of \"of_complex x\"] \n          using \\<open>of_complex x \\<in> unit_disc\\<close> \\<open>of_complex x \\<noteq> \\<infinity>\\<^sub>h\\<close> \\<open>of_complex x \\<noteq> 0\\<^sub>h\\<close>\n          using \\<open>of_complex x \\<in> circline_set x_axis\\<close> \\<open>m \\<in> unit_disc\\<close> **(1)\n          by simp\n        then obtain m' where \"m = of_complex m'\" \"is_real m'\"\n          using inf_or_of_complex[of m] \\<open>m \\<in> unit_disc\\<close>\n          unfolding circline_set_x_axis\n          by auto\n        hence \"Re m' \\<le> Re x\"\n          using \\<open>poincare_between 0\\<^sub>h m (of_complex x)\\<close> xx \\<open>of_complex x \\<noteq> 0\\<^sub>h\\<close>\n          using False ** \\<open>of_complex x \\<in> unit_disc\\<close>\n          using cmod_Re_le_iff poincare_between_0uv by auto\n \n        have \"n \\<noteq> 0\\<^sub>h\"\n          using **(2, 4) \\<open>of_complex x \\<noteq> 0\\<^sub>h\\<close> \\<open>of_complex x \\<in> unit_disc\\<close>\n          using poincare_between_sandwich by fastforce\n        have \"n \\<in> circline_set x_axis\"\n          using poincare_between_poincare_line_uvz[of \"0\\<^sub>h\" \"of_complex x\" n]\n          using poincare_line_0_real_is_x_axis[of \"of_complex x\"] \n          using \\<open>of_complex x \\<in> unit_disc\\<close> \\<open>of_complex x \\<noteq> \\<infinity>\\<^sub>h\\<close> \\<open>of_complex x \\<noteq> 0\\<^sub>h\\<close>\n          using \\<open>of_complex x \\<in> circline_set x_axis\\<close> \\<open>n \\<in> unit_disc\\<close> **(2)\n          by simp\n        then obtain n' where \"n = of_complex n'\" \"is_real n'\"\n          using inf_or_of_complex[of n] \\<open>n \\<in> unit_disc\\<close>\n          unfolding circline_set_x_axis\n          by auto\n        hence \"Re x \\<le> Re n'\"\n          using \\<open>poincare_between 0\\<^sub>h (of_complex x) n\\<close> xx \\<open>of_complex x \\<noteq> 0\\<^sub>h\\<close>\n          using False ** \\<open>of_complex x \\<in> unit_disc\\<close> \\<open>n \\<noteq> 0\\<^sub>h\\<close>\n          using cmod_Re_le_iff poincare_between_0uv\n          by (metis Re_complex_of_real arg_0_iff rcis_cmod_arg rcis_zero_arg to_complex_of_complex)\n        \n        have \"poincare_between (of_complex m') (of_complex x) (of_complex n')\" \n          using \\<open>Re x \\<le> Re n'\\<close> \\<open>Re m' \\<le> Re x\\<close>\n          using poincare_between_x_axis_uvw[of \"Re m'\" \"Re x\" \"Re n'\"]\n          using \\<open>is_real n'\\<close> \\<open>is_real m'\\<close> \\<open>n \\<in> unit_disc\\<close> \\<open>n = of_complex n'\\<close>\n          using xx \\<open>m = of_complex m'\\<close> \\<open>m \\<in> unit_disc\\<close>\n          by (smt complex_of_real_Re norm_of_real poincare_between_def unit_disc_iff_cmod_lt_1)\n\n        thus ?thesis\n          using \\<open>n = of_complex n'\\<close> \\<open>m = of_complex m'\\<close>\n          by auto\n      qed\n    qed\n  qed \n  thus ?thesis\n    using assms\n    by blast\nqed\n\n(* ------------------------------------------------------------------ *)\nsubsection\\<open>Poincare between - sum distances\\<close>\n(* ------------------------------------------------------------------ *)\n\ntext\\<open>Another possible definition of the h-betweenness relation is given in terms of h-distances\nbetween pairs of points. We prove it as a characterization equivalent to our cross-ratio based\ndefinition.\\<close>\n\nlemma poincare_between_sum_distances_x_axis_u0v:\n  assumes \"of_complex u' \\<in> unit_disc\" \"of_complex v' \\<in> unit_disc\"\n  assumes \"is_real u'\" \"u' \\<noteq> 0\" \"v' \\<noteq> 0\"\n  shows  \"poincare_distance (of_complex u') 0\\<^sub>h + poincare_distance 0\\<^sub>h (of_complex v') = poincare_distance (of_complex u') (of_complex v') \\<longleftrightarrow>\n          is_real v' \\<and> Re u' * Re v' < 0\" (is \"?P u' v' \\<longleftrightarrow> ?Q u' v'\")\nproof-\n  have \"Re u' \\<noteq> 0\"\n    using \\<open>is_real u'\\<close> \\<open>u' \\<noteq> 0\\<close>\n    using complex_eq_if_Re_eq\n    by simp\n\n  let ?u = \"cmod u'\" and ?v = \"cmod v'\" and ?uv = \"cmod (u' - v')\"\n  have disc: \"?u\\<^sup>2 < 1\" \"?v\\<^sup>2 < 1\"\n    using unit_disc_cmod_square_lt_1[OF assms(1)]\n    using unit_disc_cmod_square_lt_1[OF assms(2)]\n    by auto\n  have \"poincare_distance (of_complex u') 0\\<^sub>h + poincare_distance 0\\<^sub>h (of_complex v') =\n              arcosh (((1 + ?u\\<^sup>2) * (1 + ?v\\<^sup>2) + 4 * ?u * ?v) / ((1 - ?u\\<^sup>2) * (1 - ?v\\<^sup>2)))\" (is \"_ = arcosh ?r1\")\n          using poincare_distance_formula_zero_sum[OF assms(1-2)]\n          by (simp add: Let_def)\n  moreover\n  have \"poincare_distance (of_complex u') (of_complex v') =\n              arcosh (((1 - ?u\\<^sup>2) * (1 - ?v\\<^sup>2) + 2 * ?uv\\<^sup>2) / ((1 - ?u\\<^sup>2) * (1 - ?v\\<^sup>2)))\" (is \"_ = arcosh ?r2\")\n    using disc\n    using poincare_distance_formula[OF assms(1-2)]\n    by (subst add_divide_distrib) simp\n  moreover\n  have \"arcosh ?r1 = arcosh ?r2 \\<longleftrightarrow> ?Q u' v'\"\n  proof\n    assume \"arcosh ?r1 = arcosh ?r2\"\n    hence \"?r1 = ?r2\"\n    proof (subst (asm) arcosh_eq_iff)\n      show \"?r1 \\<ge> 1\"\n      proof-\n        have \"(1 - ?u\\<^sup>2) * (1 - ?v\\<^sup>2) \\<le> (1 + ?u\\<^sup>2) * (1 + ?v\\<^sup>2) + 4 * ?u * ?v\"\n          by (simp add: field_simps)\n        thus ?thesis\n          using disc\n          by simp\n      qed\n    next\n      show \"?r2 \\<ge> 1\"\n        using disc\n        by simp\n    qed\n    hence \"(1 + ?u\\<^sup>2) * (1 + ?v\\<^sup>2) + 4 * ?u * ?v = (1 - ?u\\<^sup>2) * (1 - ?v\\<^sup>2) + 2 * ?uv\\<^sup>2\"\n      using disc\n      by auto              \n    hence \"(cmod (u' - v'))\\<^sup>2 = (cmod u' + cmod v')\\<^sup>2\"\n      by (simp add: field_simps power2_eq_square)\n    hence *: \"Re u' * Re v' + \\<bar>Re u'\\<bar> * sqrt ((Im v')\\<^sup>2 + (Re v')\\<^sup>2) = 0\"\n      using \\<open>is_real u'\\<close>\n      unfolding cmod_power2 cmod_def\n      by (simp add: field_simps) (simp add: power2_eq_square field_simps)\n    hence \"sqrt ((Im v')\\<^sup>2 + (Re v')\\<^sup>2) = \\<bar>Re v'\\<bar>\"\n      using \\<open>Re u' \\<noteq> 0\\<close> \\<open>v' \\<noteq> 0\\<close>\n      by (smt complex_neq_0 mult.commute mult_cancel_right mult_minus_left real_sqrt_gt_0_iff)\n    hence \"Im v' = 0\"\n      by (smt Im_eq_0 norm_complex_def)\n    moreover\n    hence \"Re u' * Re v' = - \\<bar>Re u'\\<bar> * \\<bar>Re v'\\<bar>\"\n      using *\n      by simp\n    hence \"Re u' * Re v' < 0\"\n      using \\<open>Re u' \\<noteq> 0\\<close> \\<open>v' \\<noteq> 0\\<close>\n      by (simp add: \\<open>is_real v'\\<close> complex_eq_if_Re_eq)\n    ultimately\n    show \"?Q u' v'\"\n      by simp\n  next\n    assume \"?Q u' v'\"\n    hence \"is_real v'\" \"Re u' * Re v' < 0\"\n      by auto\n    have \"?r1 = ?r2\"\n    proof (cases \"Re u' > 0\")\n      case True\n      hence \"Re v' < 0\"\n        using \\<open>Re u' * Re v' < 0\\<close>\n        by (smt zero_le_mult_iff)\n      show ?thesis\n        using disc \\<open>is_real u'\\<close> \\<open>is_real v'\\<close>\n        using \\<open>Re u' > 0\\<close> \\<open>Re v' < 0\\<close>\n        unfolding cmod_power2 cmod_def\n        by simp (simp add: power2_eq_square field_simps)\n    next\n      case False\n      hence \"Re u' < 0\"\n        using \\<open>Re u' \\<noteq> 0\\<close>\n        by simp\n      hence \"Re v' > 0\"\n        using \\<open>Re u' * Re v' < 0\\<close>\n        by (smt zero_le_mult_iff)\n      show ?thesis\n        using disc \\<open>is_real u'\\<close> \\<open>is_real v'\\<close>\n        using \\<open>Re u' < 0\\<close> \\<open>Re v' > 0\\<close>\n        unfolding cmod_power2 cmod_def\n        by simp (simp add: power2_eq_square field_simps)\n    qed\n    thus \"arcosh ?r1 = arcosh ?r2\"\n      by metis\n  qed\n  ultimately\n  show ?thesis\n    by simp\nqed\n\ntext\\<open>\n  Different proof of the previous theorem relying on the cross-ratio definition, and not the distance formula.\n  We suppose that this could be also used to prove the triangle inequality.\n\\<close>\nlemma poincare_between_sum_distances_x_axis_u0v_different_proof:\n  assumes \"of_complex u' \\<in> unit_disc\" \"of_complex v' \\<in> unit_disc\"\n  assumes \"is_real u'\" \"u' \\<noteq> 0\" \"v' \\<noteq> 0\" (* additional condition *) \"is_real v'\"\n  shows  \"poincare_distance (of_complex u') 0\\<^sub>h + poincare_distance 0\\<^sub>h (of_complex v') = poincare_distance (of_complex u') (of_complex v') \\<longleftrightarrow>\n          Re u' * Re v' < 0\" (is \"?P u' v' \\<longleftrightarrow> ?Q u' v'\")\nproof-\n  have \"-1 < Re u'\" \"Re u' < 1\" \"Re u' \\<noteq> 0\"\n    using assms\n    by (auto simp add: cmod_eq_Re complex_eq_if_Re_eq)\n  have \"-1 < Re v'\" \"Re v' < 1\" \"Re v' \\<noteq> 0\"\n    using assms\n    by (auto simp add: cmod_eq_Re complex_eq_if_Re_eq)\n\n  have \"\\<bar>ln (Re ((1 - u') / (1 + u')))\\<bar> + \\<bar>ln (Re ((1 - v') / (1 + v')))\\<bar> =\n        \\<bar>ln (Re ((1 + u') * (1 - v') / ((1 - u') * (1 + v'))))\\<bar> \\<longleftrightarrow> Re u' * Re v' < 0\" (is \"\\<bar>ln ?a1\\<bar>  + \\<bar>ln ?a2\\<bar> = \\<bar>ln ?a3\\<bar> \\<longleftrightarrow> _\")\n  proof-\n    have 1: \"0 < ?a1\" \"ln ?a1 > 0 \\<longleftrightarrow> Re u' < 0\"\n      using \\<open>Re u' < 1\\<close> \\<open>Re u' > -1\\<close> \\<open>is_real u'\\<close>\n      using complex_is_Real_iff\n      by auto\n    have 2: \"0 < ?a2\" \"ln ?a2 > 0 \\<longleftrightarrow> Re v' < 0\"\n      using \\<open>Re v' < 1\\<close> \\<open>Re v' > -1\\<close> \\<open>is_real v'\\<close>\n      using complex_is_Real_iff\n      by auto\n    have 3: \"0 < ?a3\" \"ln ?a3 > 0 \\<longleftrightarrow> Re v' < Re u'\"\n      using \\<open>Re u' < 1\\<close> \\<open>Re u' > -1\\<close> \\<open>is_real u'\\<close>\n      using \\<open>Re v' < 1\\<close> \\<open>Re v' > -1\\<close> \\<open>is_real v'\\<close>\n      using complex_is_Real_iff\n       by auto (simp add: field_simps)+\n    show ?thesis\n    proof\n      assume *: \"Re u' * Re v' < 0\"\n      show \"\\<bar>ln ?a1\\<bar> + \\<bar>ln ?a2\\<bar> = \\<bar>ln ?a3\\<bar>\"\n      proof (cases \"Re u' > 0\")\n        case True\n        hence \"Re v' < 0\"\n          using *\n          by (smt mult_nonneg_nonneg)\n        show ?thesis\n          using 1 2 3 \\<open>Re u' > 0\\<close> \\<open>Re v' < 0\\<close>\n          using \\<open>Re u' < 1\\<close> \\<open>Re u' > -1\\<close> \\<open>is_real u'\\<close>\n          using \\<open>Re v' < 1\\<close> \\<open>Re v' > -1\\<close> \\<open>is_real v'\\<close>\n          using complex_is_Real_iff\n          using ln_div ln_mult\n          by simp\n      next\n        case False\n        hence \"Re v' > 0\" \"Re u' < 0\"\n          using *\n          by (smt zero_le_mult_iff)+\n        show ?thesis\n          using 1 2 3 \\<open>Re u' < 0\\<close> \\<open>Re v' > 0\\<close>\n          using \\<open>Re u' < 1\\<close> \\<open>Re u' > -1\\<close> \\<open>is_real u'\\<close>\n          using \\<open>Re v' < 1\\<close> \\<open>Re v' > -1\\<close> \\<open>is_real v'\\<close>\n          using complex_is_Real_iff\n          using ln_div ln_mult\n          by simp\n      qed\n    next\n      assume *: \"\\<bar>ln ?a1\\<bar> + \\<bar>ln ?a2\\<bar> = \\<bar>ln ?a3\\<bar>\"\n      {\n        assume \"Re u' > 0\" \"Re v' > 0\"\n        hence False\n          using * 1 2 3\n          using \\<open>Re u' < 1\\<close> \\<open>Re u' > -1\\<close> \\<open>is_real u'\\<close>\n          using \\<open>Re v' < 1\\<close> \\<open>Re v' > -1\\<close> \\<open>is_real v'\\<close>\n          using complex_is_Real_iff\n          using ln_mult ln_div\n          by (cases \"Re v' < Re u'\") auto\n      }\n      moreover\n      {\n        assume \"Re u' < 0\" \"Re v' < 0\"\n        hence False\n          using * 1 2 3\n          using \\<open>Re u' < 1\\<close> \\<open>Re u' > -1\\<close> \\<open>is_real u'\\<close>\n          using \\<open>Re v' < 1\\<close> \\<open>Re v' > -1\\<close> \\<open>is_real v'\\<close>\n          using complex_is_Real_iff\n          using ln_mult ln_div\n          by (cases \"Re v' < Re u'\") auto\n      }\n      ultimately\n      show \"Re u' * Re v' < 0\"\n        using \\<open>Re u' \\<noteq> 0\\<close> \\<open>Re v' \\<noteq> 0\\<close>\n        by (smt divisors_zero mult_le_0_iff)\n    qed\n  qed\n  thus ?thesis\n    using assms\n    apply (subst poincare_distance_sym, simp, simp)\n    apply (subst poincare_distance_zero_x_axis, simp, simp add: circline_set_x_axis)\n    apply (subst poincare_distance_zero_x_axis, simp, simp add: circline_set_x_axis)\n    apply (subst poincare_distance_x_axis_x_axis, simp, simp, simp add: circline_set_x_axis, simp add: circline_set_x_axis)\n    apply simp\n    done\nqed\n\nlemma poincare_between_sum_distances:\n  assumes \"u \\<in> unit_disc\" and \"v \\<in> unit_disc\" and \"w \\<in> unit_disc\"\n  shows \"poincare_between u v w \\<longleftrightarrow> \n         poincare_distance u v + poincare_distance v w = poincare_distance u w\" (is \"?P' u v w\")\nproof (cases \"u = v\")\n  case True\n  thus ?thesis\n    using assms\n    by simp\nnext\n  case False\n  have \"\\<forall> w. w \\<in> unit_disc \\<longrightarrow> (poincare_between u v w \\<longleftrightarrow> poincare_distance u v + poincare_distance v w = poincare_distance u w)\" (is \"?P u v\")\n  proof (rule wlog_positive_x_axis)\n    fix x\n    assume \"is_real x\" \"0 < Re x\" \"Re x < 1\"\n    have \"of_complex x \\<in> circline_set x_axis\"\n      using \\<open>is_real x\\<close>\n      by (auto simp add: circline_set_x_axis)\n\n    have \"of_complex x \\<in> unit_disc\"\n      using \\<open>is_real x\\<close> \\<open>0 < Re x\\<close> \\<open>Re x < 1\\<close>\n      by (simp add: cmod_eq_Re)\n\n    have \"x \\<noteq> 0\"\n      using \\<open>is_real x\\<close> \\<open>Re x > 0\\<close>\n      by auto\n\n    show \"?P (of_complex x) 0\\<^sub>h\"\n    proof (rule allI, rule impI)\n      fix w\n      assume \"w \\<in> unit_disc\"\n      then obtain w' where \"w = of_complex w'\"\n        using inf_or_of_complex[of w]\n        by auto\n\n      show \"?P' (of_complex x) 0\\<^sub>h w\"\n      proof (cases \"w = 0\\<^sub>h\")\n        case True\n        thus ?thesis\n          by simp\n      next\n        case False\n        hence \"w' \\<noteq> 0\"\n          using \\<open>w = of_complex w'\\<close>\n          by auto\n\n        show ?thesis\n          using \\<open>is_real x\\<close> \\<open>x \\<noteq> 0\\<close> \\<open>w = of_complex w'\\<close> \\<open>w' \\<noteq> 0\\<close>\n          using \\<open>of_complex x \\<in> unit_disc\\<close> \\<open>w \\<in> unit_disc\\<close>\n          apply simp\n          apply (subst poincare_between_x_axis_u0v, simp_all)\n          apply (subst poincare_between_sum_distances_x_axis_u0v, simp_all)\n          done\n      qed\n    qed\n  next\n    show \"v \\<in> unit_disc\" \"u \\<in> unit_disc\"\n      using assms\n      by auto\n  next\n    show \"v \\<noteq> u\"\n      using \\<open>u \\<noteq> v\\<close>\n      by simp\n  next\n    fix M u v\n    assume *: \"unit_disc_fix M\" \"u \\<in> unit_disc\" \"v \\<in> unit_disc\" \"u \\<noteq> v\" and\n          **: \"?P (moebius_pt M v) (moebius_pt M u)\"\n    show \"?P v u\"\n    proof (rule allI, rule impI)\n      fix w\n      assume \"w \\<in> unit_disc\"\n      hence \"moebius_pt M w \\<in> unit_disc\"\n        using \\<open>unit_disc_fix M\\<close>\n        by auto\n      thus \"?P' v u w\"\n        using \\<open>u \\<in> unit_disc\\<close> \\<open>v \\<in> unit_disc\\<close> \\<open>w \\<in> unit_disc\\<close> \\<open>unit_disc_fix M\\<close>\n        using **[rule_format, of \"moebius_pt M w\"]\n        by auto\n    qed\n  qed\n  thus ?thesis\n    using assms\n    by simp\nqed\n\nsubsection \\<open>Some more properties of h-betweenness.\\<close>\n\ntext \\<open>Some lemmas proved earlier are proved almost directly using the sum of distances characterization.\\<close>\n\nlemma unit_disc_fix_moebius_preserve_poincare_between':\n  assumes \"unit_disc_fix M\" and \"u \\<in> unit_disc\" and \"v \\<in> unit_disc\" and \"w \\<in> unit_disc\"\n  shows \"poincare_between (moebius_pt M u) (moebius_pt M v) (moebius_pt M w) \\<longleftrightarrow>\n         poincare_between u v w\"\n  using assms\n  using poincare_between_sum_distances\n  by simp\n\nlemma conjugate_preserve_poincare_between':\n  assumes \"u \\<in> unit_disc\" \"v \\<in> unit_disc\" \"w \\<in> unit_disc\"\n  shows \"poincare_between (conjugate u) (conjugate v) (conjugate w) \\<longleftrightarrow> poincare_between u v w\"\n  using assms\n  using poincare_between_sum_distances\n  by simp\n\ntext \\<open>There is a unique point on a ray on the given distance from the given starting point\\<close>\nlemma unique_poincare_distance_on_ray:\n  assumes \"d \\<ge> 0\" \"u \\<noteq> v\" \"u \\<in> unit_disc\" \"v \\<in> unit_disc\"\n  assumes \"y \\<in> unit_disc\" \"poincare_distance u y = d\" \"poincare_between u v y\"\n  assumes \"z \\<in> unit_disc\" \"poincare_distance u z = d\" \"poincare_between u v z\"\n  shows \"y = z\"\nproof-\n  have \"\\<forall> d y z. d \\<ge> 0 \\<and>\n        y \\<in> unit_disc \\<and> poincare_distance u y = d \\<and> poincare_between u v y \\<and>\n        z \\<in> unit_disc \\<and> poincare_distance u z = d \\<and> poincare_between u v z \\<longrightarrow> y = z\" (is \"?P u v\")\n  proof (rule wlog_positive_x_axis[where P=\"?P\"])\n    fix x\n    assume x: \"is_real x\" \"0 < Re x\" \"Re x < 1\"\n    hence \"x \\<noteq> 0\"\n      using complex.expand[of x 0]\n      by auto\n    hence *: \"poincare_line 0\\<^sub>h (of_complex x) = x_axis\"\n      using x poincare_line_0_real_is_x_axis[of \"of_complex x\"]\n      unfolding circline_set_x_axis\n      by auto\n    have \"of_complex x \\<in> unit_disc\"\n      using x\n      by (auto simp add: cmod_eq_Re)\n    have \"arg x = 0\"\n      using x\n      using arg_0_iff by blast\n    show \"?P 0\\<^sub>h (of_complex x)\"\n    proof safe\n      fix y z\n      assume \"y \\<in> unit_disc\" \"z \\<in> unit_disc\"\n      then obtain y' z' where yz: \"y = of_complex y'\" \"z = of_complex z'\"\n        using inf_or_of_complex[of y] inf_or_of_complex[of z]\n        by auto\n      assume betw: \"poincare_between 0\\<^sub>h (of_complex x) y\"  \"poincare_between 0\\<^sub>h (of_complex x) z\"\n      hence \"y \\<noteq> 0\\<^sub>h\" \"z \\<noteq> 0\\<^sub>h\"\n        using \\<open>x \\<noteq> 0\\<close> \\<open>of_complex x \\<in> unit_disc\\<close> \\<open>y \\<in> unit_disc\\<close>\n        using poincare_between_sandwich[of \"0\\<^sub>h\" \"of_complex x\"]\n        using of_complex_zero_iff[of x]\n        by force+\n\n      hence \"arg y' = 0\" \"cmod y' \\<ge> cmod x\" \"arg z' = 0\" \"cmod z' \\<ge> cmod x\"\n        using poincare_between_0uv[of \"of_complex x\" y] poincare_between_0uv[of \"of_complex x\" z]\n        using \\<open>of_complex x \\<in> unit_disc\\<close> \\<open>x \\<noteq> 0\\<close> \\<open>arg x = 0\\<close> \\<open>y \\<in> unit_disc\\<close> \\<open>z \\<in> unit_disc\\<close> betw yz\n        by (simp_all add: Let_def)\n      hence *: \"is_real y'\" \"is_real z'\" \"Re y' > 0\" \"Re z' > 0\"\n        using arg_0_iff[of y'] arg_0_iff[of z'] x \\<open>y \\<noteq> 0\\<^sub>h\\<close> \\<open>z \\<noteq> 0\\<^sub>h\\<close> yz\n        by auto\n      assume \"poincare_distance 0\\<^sub>h z = poincare_distance 0\\<^sub>h y\" \"0 \\<le> poincare_distance 0\\<^sub>h y\"\n      thus \"y = z\"\n        using * yz \\<open>y \\<in> unit_disc\\<close> \\<open>z \\<in> unit_disc\\<close>\n        using unique_x_axis_poincare_distance_positive[of \"poincare_distance 0\\<^sub>h y\"]\n        by (auto simp add: cmod_eq_Re unit_disc_to_complex_inj)\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    assume *: \"unit_disc_fix M\" \"u \\<in> unit_disc\" \"v \\<in> unit_disc\" \"u \\<noteq> v\"\n    assume **: \"?P (moebius_pt M u) (moebius_pt M v)\"\n    show \"?P u v\"\n    proof safe\n      fix d y z\n      assume ***: \"0 \\<le> poincare_distance u y\"\n             \"y \\<in> unit_disc\" \"poincare_between u v y\"\n             \"z \\<in> unit_disc\" \"poincare_between u v z\"\n             \"poincare_distance u z = poincare_distance u y\"\n      let ?Mu = \"moebius_pt M u\" and ?Mv = \"moebius_pt M v\" and ?My = \"moebius_pt M y\" and ?Mz = \"moebius_pt M z\"\n      have \"?Mu \\<in> unit_disc\" \"?Mv \\<in> unit_disc\" \"?My \\<in> unit_disc\" \"?Mz \\<in> unit_disc\"\n        using \\<open>u \\<in> unit_disc\\<close> \\<open>v \\<in> unit_disc\\<close> \\<open>y \\<in> unit_disc\\<close> \\<open>z \\<in> unit_disc\\<close>\n        using \\<open>unit_disc_fix M\\<close>\n        by auto\n      hence \"?My = ?Mz\"\n        using * ***\n        using **[rule_format, of \"poincare_distance ?Mu ?My\" ?My ?Mz]\n        by simp\n      thus \"y = z\"\n        using bij_moebius_pt[of M]\n        unfolding bij_def inj_on_def\n        by blast\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_Between.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8902942377652497, "lm_q2_score": 0.8397339716830606, "lm_q1q2_score": 0.7476103162451563}}
{"text": "(*\n  File:    Pnorm.thy \n  Author:  Jose Manuel Rodriguez Caballero, University of Tartu\n  Author:  Manuel Eberl, TU M\u00fcnchen\n*)\nsection \\<open>p-adic valuation and p-adic norm\\<close>\ntheory Pnorm\n\nimports \n  \"HOL-Number_Theory.Number_Theory\"\n\nbegin\n\ntext \\<open>\n  Following ~\\cite{koblitz2012p}, we define the p-adic valuation @{text pval}, the p-adic norm \n  @{text pnorm} in a computational way. We prove their basic properties.\n\\<close>\n\nsubsection \\<open>Unsorted\\<close>\n\nlemma quotient_of_int' [simp]: \"quotient_of (of_int a) = (a, 1)\"\n  using Rat.of_int_def quotient_of_int by auto\n\nlemma snd_quotient_of_nonzero [simp]: \"snd (quotient_of x) \\<noteq> 0\"\n  using quotient_of_denom_pos[of x \"fst (quotient_of x)\" \"snd (quotient_of x)\"] by simp\n\nlemma fst_quotient_of_eq_0_iff [simp]: \"fst (quotient_of x) = 0 \\<longleftrightarrow> x = 0\"\n  by (metis divide_eq_0_iff fst_conv of_int_0 prod.collapse quotient_of_div quotient_of_int')\n\nlemma multiplicity_int_int [simp]: \"multiplicity (int a) (int b) = multiplicity a b\"\n  by (simp add: multiplicity_def flip: of_nat_power)\n\nlemma multiplicity_add_absorb_left:\n  assumes \"multiplicity p x < multiplicity p y\" \"x \\<noteq> 0\"\n  shows   \"multiplicity p (x + y) = multiplicity p x\"\nproof (cases \"y = 0 \\<or> is_unit p\")\n  case False\n  show ?thesis\n  proof (rule multiplicity_eqI)\n    from assms show \"p ^ multiplicity p x dvd x + y\"\n      by (intro dvd_add) (auto intro!: multiplicity_dvd')\n    show \"\\<not>p ^ Suc (multiplicity p x) dvd x + y\" using assms False\n      by (subst dvd_add_left_iff; subst power_dvd_iff_le_multiplicity) auto\n  qed\nqed (use assms in \\<open>auto simp: multiplicity_unit_left\\<close>)\n\nlemma multiplicity_add_absorb_right:\n  assumes \"multiplicity p x > multiplicity p y\" \"y \\<noteq> 0\"\n  shows   \"multiplicity p (x + y) = multiplicity p y\"\n  using multiplicity_add_absorb_left[of p y x] assms by (simp add: add.commute)\n\nlemma multiplicity_add_ge:\n  assumes \"x + y \\<noteq> 0\"\n  shows   \"multiplicity p (x + y) \\<ge> min (multiplicity p x) (multiplicity p y)\"\nproof (cases \"is_unit p \\<or> x = 0 \\<or> y = 0\")\n  case False\n  thus ?thesis using assms\n    by (intro multiplicity_geI dvd_add) (auto intro!: multiplicity_dvd')\nqed (auto simp: multiplicity_unit_left)\n\nlemma multiplicity_minus_right [simp]:\n  \"multiplicity a (-b :: 'a :: {factorial_semiring,comm_ring_1}) = multiplicity a b\"\n  by (simp add: multiplicity_def)\n\nlemma multiplicity_minus_left [simp]:\n  \"multiplicity (-a :: 'a :: {factorial_semiring,comm_ring_1}) b = multiplicity a b\"\n  using multiplicity_times_unit_left[of \"-1\" a b] by simp\n\n\ndefinition intpow :: \"'a :: {inverse, power} \\<Rightarrow> int \\<Rightarrow> 'a\" where \n  \"intpow x n = (if n \\<ge> 0 then x ^ nat n else inverse x ^ (nat (-n)))\"\n\n(* The option to the user to use the same notation as powr *)\nnotation intpow  (infixr \"powi\" 80)\n\nlemma intpow_int [simp]: \" x powi (int n) = x ^ n\"\n  by (simp add: intpow_def)\n\nlemma intpow_minus [simp]: \"intpow (x :: 'a :: field) (-int n) = inverse (intpow x n)\"\n  by (auto simp: intpow_def power_inverse)\n\nlemma intpow_eq_0_iff [simp]: \"intpow (x :: 'a :: field) n = 0 \\<longleftrightarrow> x = 0 \\<and> n \\<noteq> 0\"\n  by (auto simp: intpow_def)\n\n\nsubsection \\<open>Definitions\\<close>\n\ntext\\<open>\n  The following function is a version of the p-adic valuation as defined in ~\\cite{koblitz2012p}, \n  with the exception that for us the valuation of zero will be zero rather than infinity as in done\n  in traditional mathematics. This definition is computational.\n\\<close>\ndefinition pval :: \\<open>nat \\<Rightarrow> rat \\<Rightarrow> int\\<close> where\n  \\<open>pval p x = int (multiplicity p (fst (quotient_of x))) - \n              int (multiplicity p (snd (quotient_of x)))\\<close>\n\ntext\\<open>\n  The following function is the p-adic norm as defined in ~\\cite{koblitz2012p}.  This definition is\n  computational.\n\\<close>\ndefinition pnorm :: \\<open>nat \\<Rightarrow> rat \\<Rightarrow> real\\<close> where\n  \\<open>pnorm p x = (if x = 0 then 0 else p powr -of_int (pval p x))\\<close>\n\nsubsection \\<open>Trivial simplifications\\<close>\n\nlemma pval_eq_imp_norm_eq: \\<open>pval p x = pval p y \\<Longrightarrow> x \\<noteq> 0 \\<Longrightarrow> y \\<noteq> 0 \\<Longrightarrow> pnorm p x = pnorm p y\\<close>\n  by (simp add: pnorm_def)\n\nlemma pval_0 [simp]: \"pval p 0 = 0\"\n  and pval_1 [simp]: \"pval p 1 = 0\"\n  by (simp_all add: pval_def)\n\nlemma pnorm_0 [simp]: \"pnorm p 0 = 0\"\n  and pnorm_1 [simp]: \"prime p \\<Longrightarrow> pnorm p 1 = 1\"\n  by (simp_all add: pnorm_def prime_gt_0_nat)\n\nlemma pnorm_nonneg: \"pnorm p x \\<ge> 0\"\n  by (simp add: pnorm_def)\n\nlemma pnorm_pos: \"x \\<noteq> 0 \\<Longrightarrow> prime p \\<Longrightarrow> pnorm p x > 0\"\n  by (auto simp: pnorm_def)\n\nlemma pnorm_eq_0_iff [simp]: \"pnorm p x = 0 \\<longleftrightarrow> p = 0 \\<or> x = 0\"\n  by (auto simp: pnorm_def)\n\nlemma pnorm_le_iff:\n  assumes \"prime p\" \"x \\<noteq> 0\" \"y \\<noteq> 0\"\n  shows   \"pnorm p x \\<le> pnorm p y \\<longleftrightarrow> pval p x \\<ge> pval p y\"\n  using assms prime_gt_1_nat[of p] by (simp add: pnorm_def)\n\nlemma pnorm_less_iff:\n  assumes \"prime p\" \"x \\<noteq> 0\" \"y \\<noteq> 0\"\n  shows   \"pnorm p x < pnorm p y \\<longleftrightarrow> pval p x > pval p y\"\n  using assms prime_gt_1_nat[of p] by (simp add: pnorm_def)\n\nlemma pnorm_eq_iff:\n  assumes \"prime p\" \"x \\<noteq> 0\" \"y \\<noteq> 0\"\n  shows   \"pnorm p x = pnorm p y \\<longleftrightarrow> pval p x = pval p y\"\n  using assms prime_gt_1_nat[of p] by (simp add: pnorm_def powr_inj)\n\nlemma pnorm_eq_imp_pval_eq:\n  assumes \"pnorm p x = pnorm p y\" \"prime p\"\n  shows   \"pval p x = pval p y\"\n  using assms prime_gt_1_nat[of p]\n  by (cases \"x = 0 \\<or> y = 0\") (auto simp: pnorm_def powr_inj split: if_splits)\n\n(*\n  Comment by Manuel:\n  his lemma allows to determine a fraction's p-adic valuation even if it is not on\n  lowest terms\n*)\nlemma pval_quotient:\n  assumes \"prime p\" and [simp]: \"a \\<noteq> 0\" \"b \\<noteq> 0\"\n  shows   \"pval p (of_int a / of_int b) = int (multiplicity p a) - int (multiplicity p b)\"\nproof -\n  define d where \"d = sgn b * gcd a b\"\n  define a' b' where \"a' = a div d\" and \"b' = b div d\"\n  have a'b': \"a = a' * d\" \"b = b' * d\"\n    by (simp_all add: d_def a'_def b'_def)\n  from assms have [simp]: \"a' \\<noteq> 0\" \"b' \\<noteq> 0\" \"d \\<noteq> 0\"\n    by (simp_all add: a'b')\n\n  have \"pval p (of_int a / of_int b) = int (multiplicity p a') - int (multiplicity p b')\"\n    by (auto simp: pval_def rat_divide_code case_prod_unfold Let_def\n                   Rat.normalize_def d_def a'_def b'_def sgn_if)\n  also have \"\\<dots> = int (multiplicity p a' + multiplicity p d) -\n                  int (multiplicity p b' + multiplicity p d)\" by simp\n  also have \"\\<dots> = int (multiplicity p a) - int (multiplicity p b)\"\n    unfolding a'b' using \\<open>prime p\\<close>\n    by (subst (1 2) prime_elem_multiplicity_mult_distrib) auto\n  finally show ?thesis .\nqed\n\nlemma pval_of_int [simp]: \"pval p (of_int n) = multiplicity p n\"\n  by (simp add: pval_def)\n\nlemma pval_of_nat [simp]: \"pval p (of_nat n) = multiplicity p n\"\n  using pval_of_int[of p \"int n\"] by (simp del: pval_of_int)\n\nlemma pval_numeral [simp]: \"pval p (numeral n) = multiplicity p (numeral n)\"\n  using pval_of_nat[of p \"numeral n\"] by (simp del: pval_of_nat)\n\nlemma pval_mult [simp]:\n  assumes \"prime p\" and [simp]: \"x \\<noteq> 0\" \"y \\<noteq> 0\"\n  shows \"pval p (x * y) = pval p x + pval p y\"\nproof -\n  define a b where \"a = fst (quotient_of x)\" and \"b = snd (quotient_of x)\"\n  define c d where \"c = fst (quotient_of y)\" and \"d = snd (quotient_of y)\"\n  have xy: \"x = of_int a / of_int b\" \"y = of_int c / of_int d\"\n    by (rule quotient_of_div; simp add: a_def b_def c_def d_def)+\n  have [simp]: \"a \\<noteq> 0\" \"c \\<noteq> 0\" using xy by auto\n  have [simp]: \"b \\<noteq> 0\" \"d \\<noteq> 0\" by (auto simp: b_def d_def)\n\n  have \"x * y = of_int (a * c) / of_int (b * d)\"\n    by (simp add: xy)\n  also have \"pval p \\<dots> = int (multiplicity p (a * c)) - int (multiplicity p (b * d))\"\n    using \\<open>prime p\\<close> by (subst pval_quotient) auto\n  also have \"\\<dots> = pval p x + pval p y\"\n    using \\<open>prime p\\<close> by (simp add: xy pval_quotient prime_elem_multiplicity_mult_distrib)\n  finally show ?thesis .\nqed\n\nlemma pnorm_mult [simp]: \"prime p \\<Longrightarrow> pnorm p (x * y) = pnorm p x * pnorm p y\"\n  by (simp add: pnorm_def powr_diff powr_minus field_simps)\n\nlemma pval_inverse [simp]: \"pval p (inverse x) = -pval p x\"\nproof (cases \"x = 0\")\n  case [simp]: False\n  define a b where \"a = fst (quotient_of x)\" and \"b = snd (quotient_of x)\"\n  have x: \"x = of_int a / of_int b\"\n    by (rule quotient_of_div; simp add: a_def b_def)\n  have [simp]: \"a \\<noteq> 0\" using x by auto\n  have [simp]: \"b \\<noteq> 0\" by (auto simp: b_def)\n\n  have \"\\<bar>a\\<bar> = sgn a * a\"  by (simp add: abs_if sgn_if)\n  thus ?thesis\n    by (auto simp: pval_def rat_inverse_code case_prod_unfold Let_def \n                   multiplicity_times_unit_right simp flip: a_def b_def)\nqed auto\n\nlemma pnorm_inverse [simp]: \"pnorm p (inverse x) = inverse (pnorm p x)\"\n  by (simp add: pnorm_def powr_minus)\n\nlemma pval_minus [simp]: \"pval p (-x) = pval p x\"\n  by (simp add: pval_def rat_uminus_code case_prod_unfold Let_def)\n\nlemma pnorm_minus [simp]: \"pnorm p (-x) = pnorm p x\"\n  by (simp add: pnorm_def)\n\nlemma pval_power [simp]:\n  assumes \"prime p\"\n  shows   \"pval p (x ^ n) = int n * pval p x\"\nproof (cases \"x = 0\")\n  case False\n  thus ?thesis by (induction n) (auto simp: \\<open>prime p\\<close> algebra_simps)\nqed (auto simp: power_0_left)\n\nlemma pnorm_power [simp]: \"prime p \\<Longrightarrow> pnorm p (x ^ n) = pnorm p x ^ n\"\n  by (auto simp: pnorm_def powr_def simp flip: exp_of_nat_mult)\n\nlemma pval_primepow: \\<open>prime p \\<Longrightarrow> pval p (of_int p ^ l) = l\\<close>\n  by simp\n\nlemma pnorm_primepow: \\<open>prime p \\<Longrightarrow> pnorm p ((of_int p)^l) = 1/p^l\\<close>\n  using prime_gt_1_nat[of p]\n  by (simp add: pval_primepow pnorm_def powr_minus powr_realpow field_simps)\n\nlemma pval_eq_0_imp_pnorm_eq_1: \"prime p \\<Longrightarrow> pval p x = 0 \\<Longrightarrow> x \\<noteq> 0 \\<Longrightarrow> pnorm p x = 1\"\n  by (auto simp: pnorm_def)\n\nlemma pnorm_eq_1_imp_pval_eq_0: \"prime p \\<Longrightarrow> pnorm p x = 1 \\<Longrightarrow> pval p x = 0\"\n  using pnorm_eq_iff[of p x 1] by (cases \"x = 0\") auto\n\nlemma pnorm_eq_1_iff: \"x \\<noteq> 0 \\<Longrightarrow> prime p \\<Longrightarrow> pnorm p x = 1 \\<longleftrightarrow> pval p x = 0\"\n  using pval_eq_0_imp_pnorm_eq_1 pnorm_eq_1_imp_pval_eq_0 by metis\n\nlemma pval_coprime_quotient_cases:\n  fixes a b :: int\n  assumes \"prime p\" \"coprime a b\" and [simp]: \"a \\<noteq> 0\" \"b \\<noteq> 0\"\n  shows   \"\\<not>p dvd b \\<and> pval p (of_int a / of_int b) = int (multiplicity p a) \\<or>\n           \\<not>p dvd a \\<and> pval p (of_int a / of_int b) = -int (multiplicity p b)\"\nproof -\n  have \"\\<not>p dvd a \\<or> \\<not>p dvd b\"\n    using assms by (meson coprime_common_divisor not_prime_unit prime_nat_int_transfer)\n  thus ?thesis using \\<open>prime p\\<close>\n    by (auto simp: pval_quotient not_dvd_imp_multiplicity_0)\nqed\n\nlemma pval_cases:\n  fixes a b :: int\n  assumes \"prime p\" \"x \\<noteq> 0\"\n  shows   \"\\<not>p dvd snd (quotient_of x) \\<and> pval p x = int (multiplicity p (fst (quotient_of x))) \\<or>\n           \\<not>p dvd fst (quotient_of x) \\<and> pval p x = -int (multiplicity p (snd (quotient_of x)))\"\nproof -\n  define a b where \"a = fst (quotient_of x)\" and \"b = snd (quotient_of x)\"\n  have x: \"x = of_int a / of_int b\"\n    by (rule quotient_of_div) (simp add: a_def b_def)\n  have [simp]: \"a \\<noteq> 0\" using assms by (simp add: x)\n  have [simp]: \"b \\<noteq> 0\" by (simp add: b_def)\n  have \"coprime a b\"\n    by (rule quotient_of_coprime) (auto simp: a_def b_def)  \n  thus \"\\<not>p dvd b \\<and> pval p x = int (multiplicity p a) \\<or>\n           \\<not>p dvd a \\<and> pval p x = -int (multiplicity p b)\"\n    using pval_coprime_quotient_cases[of p a b] x[symmetric] assms by simp\nqed\n\n\nsubsection \\<open>Integers\\<close>\n\nlemma pval_nonneg_imp_in_Ints:\n  assumes \"\\<And>p. prime p \\<Longrightarrow> pval p x \\<ge> 0\"\n  shows   \"x \\<in> \\<int>\"\nproof (cases \"x = 0\")\n  case False\n  define a b where \"a = fst (quotient_of x)\" and \"b = snd (quotient_of x)\"\n  have x: \"x = of_int a / of_int b\"\n    by (rule quotient_of_div) (simp add: a_def b_def)\n  have [simp]: \"a \\<noteq> 0\" using False by (simp add: x)\n  have [simp]: \"b \\<noteq> 0\" by (simp add: b_def)\n  have \"coprime a b\"\n    by (rule quotient_of_coprime) (auto simp: a_def b_def)\n\n  hence *: \"multiplicity p b = 0\" if \"prime p\" for p :: nat\n    using assms[of p] pval_coprime_quotient_cases[of p a b] that by (auto simp: x pval_quotient)\n  have \"multiplicity p b = 0\" if \"prime p\" for p :: int\n  proof -\n    have \"multiplicity (int (nat p)) b = 0\"\n      by (rule *) (use that in auto)\n    thus ?thesis using prime_ge_0_int[of p] that by simp\n  qed\n  hence \"prime_factors b = {}\"\n    by (auto simp: prime_factors_multiplicity)\n  hence \"is_unit b\"\n    using \\<open>b \\<noteq> 0\\<close> prime_factorization_empty_iff by blast\n  hence [simp]: \"b = 1\"\n    using quotient_of_denom_pos[of x a b] by (simp add: a_def b_def)\n  thus ?thesis by (simp add: x)\nqed auto\n\nlemma pval_Ints_nonneg: \\<open>x \\<in> \\<int> \\<Longrightarrow> prime p \\<Longrightarrow> pval p x \\<ge> 0\\<close>\n  by (auto elim: Ints_cases)\n\nlemma in_Ints_iff_pval_nonneg: \\<open>x \\<in> \\<int> \\<longleftrightarrow> (\\<forall>p. prime p \\<longrightarrow> pval p x \\<ge> 0)\\<close>\n  using pval_nonneg_imp_in_Ints pval_Ints_nonneg by blast \n\nlemma pnorm_le_1_imp_in_Ints: \\<open>(\\<And>p. prime p \\<Longrightarrow> pnorm p x \\<le> 1) \\<Longrightarrow> x \\<in> \\<int>\\<close>\n  using pnorm_le_iff[of _ x 1] in_Ints_iff_pval_nonneg[of x]\n  by (cases \"x = 0\") auto\n\nlemma in_Ints_imp_pnorm_le_1:\n  \\<open>x \\<in> \\<int> \\<Longrightarrow> prime p \\<Longrightarrow> pnorm p x \\<le> 1\\<close>\n  using pnorm_le_iff[of _ x 1] in_Ints_iff_pval_nonneg[of x]\n  by (cases \"x = 0\") auto\n\nlemma integers_pnorm:\n  \\<open>x \\<in> \\<int> \\<longleftrightarrow> (\\<forall>p. prime p \\<longrightarrow> pnorm p x \\<le> 1)\\<close>\n  using pnorm_le_1_imp_in_Ints in_Ints_imp_pnorm_le_1 by blast\n\n\nsubsection \\<open>Divisibility of the numerator and the denominator\\<close>\n\nlemma pval_nonneg_iff:\n  assumes \"prime p\" \"x \\<noteq> 0\"\n  shows   \"pval p x \\<ge> 0 \\<longleftrightarrow> \\<not>p dvd snd (quotient_of x)\"\n  using pval_cases[of p x] assms by (auto simp: prime_elem_multiplicity_eq_zero_iff)\n\nlemma pval_nonpos_iff:\n  assumes \"prime p\" \"x \\<noteq> 0\"\n  shows   \"pval p x \\<le> 0 \\<longleftrightarrow> \\<not>p dvd fst (quotient_of x)\"\n  using pval_cases[of p x] assms by (auto simp: prime_elem_multiplicity_eq_zero_iff)\n\nlemma pval_neg_iff:\n  assumes \"prime p\" \"x \\<noteq> 0\"\n  shows   \"pval p x < 0 \\<longleftrightarrow> p dvd snd (quotient_of x)\"\n  using pval_cases[of p x] assms by (auto simp: prime_multiplicity_gt_zero_iff)\n\nlemma pval_pos_iff:\n  assumes \"prime p\" \"x \\<noteq> 0\"\n  shows   \"pval p x > 0 \\<longleftrightarrow> p dvd fst (quotient_of x)\"\n  using pval_cases[of p x] assms by (auto simp: prime_multiplicity_gt_zero_iff)\n\nlemma pval_eq_0_iff:\n  assumes \"prime p\" \"x \\<noteq> 0\"\n  shows   \"pval p x = 0 \\<longleftrightarrow> \\<not>p dvd fst (quotient_of x) \\<and> \\<not>p dvd snd (quotient_of x)\"\n  using pval_cases[of p x] assms\n  by (auto simp: not_dvd_imp_multiplicity_0 prime_elem_multiplicity_eq_zero_iff)\n\n\nsubsection \\<open>Existence and uniqueness of decomposition\\<close>\n\n(*\n  Comment by Manuel:\n  It's really not a good idea to work with the real or complex power operation here.\n  What one really needs here is an integer power operation\n*)\n\nlemma pval_intpow [simp]: \"prime p \\<Longrightarrow> pval p (intpow x n) = n * pval p x\"\n  by (auto simp: intpow_def)\n\nlemma pval_decomposition_exists:\n  assumes \"prime p\"\n  shows   \"\\<exists>y. x = intpow (of_nat p) (pval p x) * y \\<and> pval p y = 0\"\nproof (cases \"x = 0\")\n  case [simp]: False\n  define y where \"y = x / intpow (of_nat p) (pval p x)\"\n  from assms have [simp]: \"y \\<noteq> 0\" by (auto simp: y_def)\n  from assms have eq: \"x = intpow (of_nat p) (pval p x) * y\"\n    by (auto simp: y_def)\n  have \"pval p x = pval p (intpow (of_nat p) (pval p x) * y)\"\n    by (subst eq) auto\n  hence \"pval p y = 0\" using assms by simp\n  with eq show ?thesis by blast\nqed auto\n\nlemma pval_decomposition_unique:\n  fixes p :: nat and x y :: rat and l :: int\n  shows \\<open>prime p \\<Longrightarrow> y \\<noteq> 0 \\<Longrightarrow> x = intpow (of_int p) l * y \\<Longrightarrow> pval p y = 0 \\<Longrightarrow> pval p x = l\\<close>\n  by auto\n\n(*\n  Comment by Manuel:\n  This is essentially just a copy of the above. Since pnorm = 1 iff pval = 0, there is really\n  no point in stating this again.\n*)\nlemma pnorm_decomposition:\n  \\<open>prime p \\<Longrightarrow> x \\<noteq> 0 \\<Longrightarrow> \\<exists> y::rat. (x::rat) = (p powr (pval p x)) * y \\<and> pnorm p y = 1\\<close>\n  oops\n\nsubsection \\<open>Unit ball\\<close>\n\n(* \n  Comment by Manuel: This is the generalised version of your unit ball properties.\n  pval (x + y) is greater than or equal to the minimum of the pvals of x and y, with equality\n  holding if x and y have distinct pvals.\n*)\n\nlemma pval_add_ge:\n  assumes \"prime p\"\n  assumes \"x + y \\<noteq> 0\"\n  shows \"pval p (x + y) \\<ge> min (pval p x) (pval p y)\"\nproof (cases \"x = 0 \\<or> y = 0\")\n  case False\n  hence [simp]: \"x \\<noteq> 0\" \"y \\<noteq> 0\" by auto\n  define a b where \"a = fst (quotient_of x)\" and \"b = snd (quotient_of x)\"\n  define c d where \"c = fst (quotient_of y)\" and \"d = snd (quotient_of y)\"\n  have xy: \"x = of_int a / of_int b\" \"y = of_int c / of_int d\"\n    by (rule quotient_of_div; simp add: a_def b_def c_def d_def)+\n  have [simp]: \"a \\<noteq> 0\" \"c \\<noteq> 0\" using xy by auto\n  have [simp]: \"b \\<noteq> 0\" \"d \\<noteq> 0\" by (auto simp: b_def d_def)\n  have eq: \"x + y = of_int (a * d + b * c) / of_int (b * d)\"\n    by (simp add: xy field_simps)\n\n  have nz: \"a * d + b * c \\<noteq> 0\"\n  proof\n    assume *: \"a * d + b * c = 0\"\n    have \"x + y = 0\"\n      unfolding eq * by simp\n    with assms show False by simp\n  qed\n\n  have \"min (pval p x) (pval p y) = \n          int (min (multiplicity (int p) (a * d)) (multiplicity (int p) (b * c))) -\n          int (multiplicity (int p) (b * d))\" using \\<open>prime p\\<close>\n    by (simp add: xy pval_quotient prime_elem_multiplicity_mult_distrib)\n  also have \"\\<dots> \\<le> int (multiplicity (int p) (a * d + b * c)) - int (multiplicity (int p) (b * d))\"\n    using multiplicity_add_ge[of \"a * d\" \"b * c\" p] nz\n    by (intro diff_right_mono) auto\n  also have \"\\<dots> = pval p (x + y)\"\n    using nz assms by (subst eq, subst pval_quotient) auto\n  finally show ?thesis .\nqed auto\n\nlemma pval_diff_ge:\n  assumes \"prime p\"\n  assumes \"x \\<noteq> y\"\n  shows \"pval p (x - y) \\<ge> min (pval p x) (pval p y)\"\n  using pval_add_ge[of p x \"-y\"] assms by auto\n\nlemma pnorm_add_le: \"prime p \\<Longrightarrow> pnorm p (x + y) \\<le> max (pnorm p x) (pnorm p y)\"\n  using pval_add_ge[of p x y] prime_gt_1_nat[of p]\n  by (cases \"x + y = 0\") (auto simp: pnorm_def max_def)\n\nlemma pnorm_diff_le:  \"prime p \\<Longrightarrow> pnorm p (x - y) \\<le> max (pnorm p x) (pnorm p y)\"\n  using pnorm_add_le[of p x \"-y\"] by simp\n\nlemma pnorm_sum_le:\n  fixes p::nat and A::\\<open>nat set\\<close> and x::\\<open>nat \\<Rightarrow> rat\\<close>\n  assumes \"finite A\" \"A \\<noteq> {}\" \\<open>prime p\\<close>\n  shows \"pnorm p (sum x A) \\<le> Max ((\\<lambda> i. pnorm p (x i)) ` A)\"\n  using assms\nproof (induction rule: finite_ne_induct)\n  case (singleton y)\n  thus ?case by auto\nnext\n  case (insert y A)\n  have \"pnorm p (x y + sum x A) \\<le> max (pnorm p (x y)) (pnorm p (sum x A))\"\n    by (rule pnorm_add_le) fact\n  also have \"\\<dots> \\<le> max (pnorm p (x y)) (MAX i\\<in>A. pnorm p (x i))\"\n    by (intro max.mono insert.IH) (auto simp: \\<open>prime p\\<close>)\n  finally show ?case\n    using insert.hyps by simp\nqed\n\nlemma pval_add_absorb_left [simp]:\n  assumes \"prime p\" \"x \\<noteq> 0\" \"pval p x < pval p y\"\n  shows   \"pval p (x + y) = pval p x\"\nproof (cases \"y = 0\")\n  case False\n  with assms have [simp]: \"x \\<noteq> 0\" \"y \\<noteq> 0\" by auto\n  from assms have \"x \\<noteq> -y\" by auto\n  hence \"x + y \\<noteq> 0\" by linarith\n\n  define a b where \"a = fst (quotient_of x)\" and \"b = snd (quotient_of x)\"\n  define c d where \"c = fst (quotient_of y)\" and \"d = snd (quotient_of y)\"\n  have xy: \"x = of_int a / of_int b\" \"y = of_int c / of_int d\"\n    by (rule quotient_of_div; simp add: a_def b_def c_def d_def)+\n  have [simp]: \"a \\<noteq> 0\" \"c \\<noteq> 0\" using xy by auto\n  have [simp]: \"b \\<noteq> 0\" \"d \\<noteq> 0\" by (auto simp: b_def d_def)\n  have eq: \"x + y = of_int (a * d + b * c) / of_int (b * d)\"\n    by (simp add: xy field_simps)\n\n  have nz: \"a * d + b * c \\<noteq> 0\"\n  proof\n    assume *: \"a * d + b * c = 0\"\n    have \"x + y = 0\"\n      unfolding eq * by simp\n    with \\<open>x + y \\<noteq> 0\\<close> show False by simp\n  qed\n\n  have \"pval p (x + y) = int (multiplicity (int p) (a * d + b * c)) - \n          int (multiplicity (int p) (b * d))\"\n    using nz assms by (subst eq, subst pval_quotient) auto\n  also from assms have \"multiplicity (int p) (a * d) < multiplicity (int p) (b * c)\"\n    by (auto simp: pval_quotient xy prime_elem_multiplicity_mult_distrib)\n  hence \"multiplicity (int p) (a * d + b * c) = multiplicity (int p) (a * d)\"\n    by (rule multiplicity_add_absorb_left) auto\n  also have \"\\<dots> - int (multiplicity (int p) (b * d)) = pval p x\"\n    using assms by (simp add: xy pval_quotient prime_elem_multiplicity_mult_distrib)\n  finally show \"pval p (x + y) = pval p x\" .\nqed (use assms in auto)\n\nlemma pval_add_absorb_right [simp]:\n  assumes \"prime p\" \"y \\<noteq> 0\" \"pval p y < pval p x\"\n  shows   \"pval p (x + y) = pval p y\"\n  using pval_add_absorb_left[of p y x] assms by (simp add: add.commute del: pval_add_absorb_left)\n\nlemma pnorm_add_absorb_left [simp]:\n  assumes \"prime p\" \"x \\<noteq> 0\" \"pnorm p x > pnorm p y\"\n  shows   \"pnorm p (x + y) = pnorm p x\"\nproof (cases \"y = 0\")\n  case False\n  with assms have [simp]: \"x \\<noteq> 0\" \"y \\<noteq> 0\" by auto\n  from assms have \"x \\<noteq> -y\" by auto\n  hence [simp]: \"x + y \\<noteq> 0\" by linarith\n  have \"pval p (x + y) = pval p x\"\n    using assms by (intro pval_add_absorb_left) (auto simp: pnorm_less_iff)\n  thus ?thesis by (simp add: pnorm_def)\nqed (use assms in auto)\n\nlemma pnorm_add_absorb_right [simp]:\n  assumes \"prime p\" \"y \\<noteq> 0\" \"pnorm p x < pnorm p y\"\n  shows   \"pnorm p (x + y) = pnorm p y\"\n  using pnorm_add_absorb_left[of p y x] assms by (simp add: add.commute del: pnorm_add_absorb_left)\n\n(* Comment by Manuel: this is now a simple corollary *)\nlemma pnorm_unit_ball:\n  fixes n :: nat\n  assumes \\<open>prime p\\<close> and \\<open>pnorm p x = 1\\<close> and \\<open>pnorm p y < 1\\<close>\n  shows \\<open>pnorm p (x + y) = 1\\<close>\n  using assms by (subst pnorm_add_absorb_left) auto\n\nend", "meta": {"author": "josephcmac", "repo": "Pnorm", "sha": "fd884075ef822665f2e9a8783b800fe868f74e92", "save_path": "github-repos/isabelle/josephcmac-Pnorm", "path": "github-repos/isabelle/josephcmac-Pnorm/Pnorm-fd884075ef822665f2e9a8783b800fe868f74e92/Pnorm.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8397339756938818, "lm_q2_score": 0.8902942188450158, "lm_q1q2_score": 0.747610303928004}}
{"text": "(*  Title:       Square Matrices\n    Author:      Jonathan Juli\u00e1n Huerta y Munive, 2020\n    Maintainer:  Jonathan Juli\u00e1n Huerta y Munive <jonjulian23@gmail.com>\n*)\n\nsection \\<open> Square Matrices \\<close>\n\ntext \\<open> The general solution for affine systems of ODEs involves the exponential function. \nUnfortunately, this operation is only available in Isabelle for the type class ``banach''. \nHence, we define a type of square matrices and prove that it is an instance of this class. \\<close>\n\ntheory SQ_MTX\n  imports MTX_Norms\n\nbegin\n\nsubsection \\<open> Definition \\<close>\n\ntypedef 'm sq_mtx = \"UNIV::(real^'m^'m) set\"\n  morphisms to_vec to_mtx by simp\n\ndeclare to_mtx_inverse [simp]\n    and to_vec_inverse [simp]\n\nsetup_lifting type_definition_sq_mtx\n\nlift_definition sq_mtx_ith :: \"'m sq_mtx \\<Rightarrow> 'm \\<Rightarrow> (real^'m)\" (infixl \"$$\" 90) is \"($)\" .\n\nlift_definition sq_mtx_vec_mult :: \"'m sq_mtx \\<Rightarrow> (real^'m) \\<Rightarrow> (real^'m)\" (infixl \"*\\<^sub>V\" 90) is \"(*v)\" .\n\nlift_definition vec_sq_mtx_prod :: \"(real^'m) \\<Rightarrow> 'm sq_mtx \\<Rightarrow> (real^'m)\" is \"(v*)\" .\n\nlift_definition sq_mtx_diag :: \"(('m::finite) \\<Rightarrow> real) \\<Rightarrow> ('m::finite) sq_mtx\" (binder \"\\<d>\\<i>\\<a>\\<g> \" 10) \n  is diag_mat .\n\nlift_definition sq_mtx_transpose :: \"('m::finite) sq_mtx \\<Rightarrow> 'm sq_mtx\" (\"_\\<^sup>\\<dagger>\") is transpose .\n\nlift_definition sq_mtx_inv :: \"('m::finite) sq_mtx \\<Rightarrow> 'm sq_mtx\" (\"_\\<^sup>-\\<^sup>1\" [90]) is matrix_inv .\n\nlift_definition sq_mtx_row :: \"'m \\<Rightarrow> ('m::finite) sq_mtx \\<Rightarrow> real^'m\" (\"\\<r>\\<o>\\<w>\") is row .\n\nlift_definition sq_mtx_col :: \"'m \\<Rightarrow> ('m::finite) sq_mtx \\<Rightarrow> real^'m\" (\"\\<c>\\<o>\\<l>\")  is column .\n\nlemma to_vec_eq_ith: \"(to_vec A) $ i = A $$ i\"\n  by transfer simp\n\nlemma to_mtx_ith[simp]: \n  \"(to_mtx A) $$ i1 = A $ i1\"\n  \"(to_mtx A) $$ i1 $ i2 = A $ i1 $ i2\"\n  by (transfer, simp)+\n\nlemma to_mtx_vec_lambda_ith[simp]: \"to_mtx (\\<chi> i j. x i j) $$ i1 $ i2 = x i1 i2\"\n  by (simp add: sq_mtx_ith_def)\n\nlemma sq_mtx_eq_iff:\n  shows \"A = B = (\\<forall>i j. A $$ i $ j = B $$ i $ j)\"\n    and \"A = B = (\\<forall>i. A $$ i = B $$ i)\"\n  by (transfer, simp add: vec_eq_iff)+\n\nlemma sq_mtx_diag_simps[simp]:\n  \"i = j \\<Longrightarrow> sq_mtx_diag f $$ i $ j = f i\"\n  \"i \\<noteq> j \\<Longrightarrow> sq_mtx_diag f $$ i $ j = 0\"\n  \"sq_mtx_diag f $$ i = axis i (f i)\"\n  unfolding sq_mtx_diag_def by (simp_all add: axis_def vec_eq_iff)\n\n\n\nlemma sq_mtx_vec_mult_diag_axis: \"(\\<d>\\<i>\\<a>\\<g> i. f i) *\\<^sub>V (axis i k) = axis i (f i * k)\"\n  unfolding sq_mtx_diag_vec_mult axis_def by auto\n\nlemma sq_mtx_vec_mult_eq: \"m *\\<^sub>V x = (\\<chi> i. sum (\\<lambda>j. (m $$ i $ j) * (x $ j)) UNIV)\"\n  by (transfer, simp add: matrix_vector_mult_def)\n\nlemma sq_mtx_transpose_transpose[simp]: \"(A\\<^sup>\\<dagger>)\\<^sup>\\<dagger> = A\"\n  by (transfer, simp)\n\nlemma transpose_mult_vec_canon_row[simp]: \"(A\\<^sup>\\<dagger>) *\\<^sub>V (\\<e> i) = \\<r>\\<o>\\<w> i A\"\n  by transfer (simp add: row_def transpose_def axis_def matrix_vector_mult_def)\n\nlemma row_ith[simp]: \"\\<r>\\<o>\\<w> i A = A $$ i\"\n  by transfer (simp add: row_def)\n\nlemma mtx_vec_mult_canon: \"A *\\<^sub>V (\\<e> i) = \\<c>\\<o>\\<l> i A\" \n  by (transfer, simp add: matrix_vector_mult_basis)\n\n\nsubsection \\<open> Ring of square matrices \\<close>\n\ninstantiation sq_mtx :: (finite) ring \nbegin\n\nlift_definition plus_sq_mtx :: \"'a sq_mtx \\<Rightarrow> 'a sq_mtx \\<Rightarrow> 'a sq_mtx\" is \"(+)\" .\n\nlift_definition zero_sq_mtx :: \"'a sq_mtx\" is \"0\" .\n\nlift_definition uminus_sq_mtx :: \"'a sq_mtx \\<Rightarrow> 'a sq_mtx\" is \"uminus\" .\n\nlift_definition minus_sq_mtx :: \"'a sq_mtx \\<Rightarrow> 'a sq_mtx \\<Rightarrow> 'a sq_mtx\" is \"(-)\" .\n\nlift_definition times_sq_mtx :: \"'a sq_mtx \\<Rightarrow> 'a sq_mtx \\<Rightarrow> 'a sq_mtx\" is \"(**)\" .\n\ndeclare plus_sq_mtx.rep_eq [simp]\n    and minus_sq_mtx.rep_eq [simp]\n\ninstance apply intro_classes\n  by(transfer, simp add: algebra_simps matrix_mul_assoc matrix_add_rdistrib matrix_add_ldistrib)+\n\nend\n\nlemma sq_mtx_zero_ith[simp]: \"0 $$ i = 0\"\n  by (transfer, simp)\n\nlemma sq_mtx_zero_nth[simp]: \"0 $$ i $ j = 0\"\n  by transfer simp\n\nlemma sq_mtx_plus_eq: \"A + B = to_mtx (\\<chi> i j. A$$i$j + B$$i$j)\"\n  by transfer (simp add: vec_eq_iff)\n\nlemma sq_mtx_plus_ith[simp]:\"(A + B) $$ i = A $$ i + B $$ i\"\n  unfolding sq_mtx_plus_eq by (simp add: vec_eq_iff)\n\n\n\nlemma sq_mtx_minus_eq: \"A - B = to_mtx (\\<chi> i j. A$$i$j - B$$i$j)\"\n  by transfer (simp add: vec_eq_iff)\n\nlemma sq_mtx_minus_ith[simp]:\"(A - B) $$ i = A $$ i - B $$ i\"\n  unfolding sq_mtx_minus_eq by (simp add: vec_eq_iff)\n\nlemma sq_mtx_times_eq: \"A * B = to_mtx (\\<chi> i j. sum (\\<lambda>k. A$$i$k * B$$k$j) UNIV)\"\n  by transfer (simp add: matrix_matrix_mult_def)\n\nlemma sq_mtx_plus_diag_diag[simp]: \"sq_mtx_diag f + sq_mtx_diag g = (\\<d>\\<i>\\<a>\\<g> i. f i + g i)\"\n  by (subst sq_mtx_eq_iff) (simp add: axis_def)\n\nlemma sq_mtx_minus_diag_diag[simp]: \"sq_mtx_diag f - sq_mtx_diag g = (\\<d>\\<i>\\<a>\\<g> i. f i - g i)\"\n  by (subst sq_mtx_eq_iff) (simp add: axis_def)\n\nlemma sum_sq_mtx_diag[simp]: \"(\\<Sum>n<m. sq_mtx_diag (g n)) = (\\<d>\\<i>\\<a>\\<g> i. \\<Sum>n<m. (g n i))\" for m::nat\n  by (induct m, simp, subst sq_mtx_eq_iff, simp_all)\n\nlemma sq_mtx_mult_diag_diag[simp]: \"sq_mtx_diag f * sq_mtx_diag g = (\\<d>\\<i>\\<a>\\<g> i. f i * g i)\"\n  by (simp add: matrix_mul_diag_diag sq_mtx_diag.abs_eq times_sq_mtx.abs_eq)\n\nlemma sq_mtx_mult_diagl: \"(\\<d>\\<i>\\<a>\\<g> i. f i) * A = to_mtx (\\<chi> i j. f i * A $$ i $ j)\"\n  by transfer (simp add: matrix_mul_diag_matl)\n\nlemma sq_mtx_mult_diagr: \"A * (\\<d>\\<i>\\<a>\\<g> i. f i) = to_mtx (\\<chi> i j. A $$ i $ j * f j)\"\n  by transfer (simp add: matrix_matrix_mul_diag_matr)\n\nlemma mtx_vec_mult_0l[simp]: \"0 *\\<^sub>V x = 0\"\n  by (simp add: sq_mtx_vec_mult.abs_eq zero_sq_mtx_def)\n\nlemma mtx_vec_mult_0r[simp]: \"A *\\<^sub>V 0 = 0\"\n  by (transfer, simp)\n\nlemma mtx_vec_mult_add_rdistr: \"(A + B) *\\<^sub>V x = A *\\<^sub>V x + B *\\<^sub>V x\"\n  unfolding plus_sq_mtx_def \n  apply(transfer)\n  by (simp add: matrix_vector_mult_add_rdistrib)\n\nlemma mtx_vec_mult_add_rdistl: \"A *\\<^sub>V (x + y) = A *\\<^sub>V x + A *\\<^sub>V y\"\n  unfolding plus_sq_mtx_def \n  apply transfer\n  by (simp add: matrix_vector_right_distrib)\n\nlemma mtx_vec_mult_minus_rdistrib: \"(A - B) *\\<^sub>V x = A *\\<^sub>V x - B *\\<^sub>V x\"\n  unfolding minus_sq_mtx_def by(transfer, simp add: matrix_vector_mult_diff_rdistrib)\n\nlemma mtx_vec_mult_minus_ldistrib: \"A *\\<^sub>V (x - y) =  A *\\<^sub>V x -  A *\\<^sub>V y\"\n  by (metis (no_types, lifting) add_diff_cancel diff_add_cancel \n      matrix_vector_right_distrib sq_mtx_vec_mult.rep_eq)\n\nlemma sq_mtx_times_vec_assoc: \"(A * B) *\\<^sub>V x = A *\\<^sub>V (B *\\<^sub>V x)\"\n  by (transfer, simp add: matrix_vector_mul_assoc)\n\nlemma sq_mtx_vec_mult_sum_cols: \"A *\\<^sub>V x = sum (\\<lambda>i. x $ i *\\<^sub>R \\<c>\\<o>\\<l> i A) UNIV\"\n  by(transfer) (simp add: matrix_mult_sum scalar_mult_eq_scaleR)\n\n\nsubsection \\<open> Real normed vector space of square matrices \\<close>\n\ninstantiation sq_mtx :: (finite) real_normed_vector \nbegin\n\ndefinition norm_sq_mtx :: \"'a sq_mtx \\<Rightarrow> real\" where \"\\<parallel>A\\<parallel> = \\<parallel>to_vec A\\<parallel>\\<^sub>o\\<^sub>p\"\n\nlift_definition scaleR_sq_mtx :: \"real \\<Rightarrow> 'a sq_mtx \\<Rightarrow> 'a sq_mtx\" is scaleR .\n\ndefinition sgn_sq_mtx :: \"'a sq_mtx \\<Rightarrow> 'a sq_mtx\" \n  where \"sgn_sq_mtx A = (inverse (\\<parallel>A\\<parallel>)) *\\<^sub>R A\"\n\ndefinition dist_sq_mtx :: \"'a sq_mtx \\<Rightarrow> 'a sq_mtx \\<Rightarrow> real\" \n  where \"dist_sq_mtx A B = \\<parallel>A - B\\<parallel>\" \n\ndefinition uniformity_sq_mtx :: \"('a sq_mtx \\<times> 'a sq_mtx) filter\" \n  where \"uniformity_sq_mtx = (INF e\\<in>{0<..}. principal {(x, y). dist x y < e})\"\n\ndefinition open_sq_mtx :: \"'a sq_mtx set \\<Rightarrow> bool\" \n  where \"open_sq_mtx U = (\\<forall>x\\<in>U. \\<forall>\\<^sub>F (x', y) in uniformity. x' = x \\<longrightarrow> y \\<in> U)\"\n\ninstance apply intro_classes \n  unfolding sgn_sq_mtx_def open_sq_mtx_def dist_sq_mtx_def uniformity_sq_mtx_def\n            prefer 10 \n            apply(transfer, simp add: norm_sq_mtx_def op_norm_triangle)\n           prefer 9 \n           apply(simp_all add: norm_sq_mtx_def zero_sq_mtx_def op_norm_eq_0)\n  by (transfer, simp add: norm_sq_mtx_def op_norm_scaleR algebra_simps)+\n\nend\n\nlemma sq_mtx_scaleR_eq: \"c *\\<^sub>R A = to_mtx (\\<chi> i j. c *\\<^sub>R A $$ i $ j)\"\n  by transfer (simp add: vec_eq_iff)\n\nlemma scaleR_to_mtx_ith[simp]: \"c *\\<^sub>R (to_mtx A) $$ i1 $ i2 = c * A $ i1 $ i2\"\n  by transfer (simp add: scaleR_vec_def)\n\nlemma sq_mtx_scaleR_ith[simp]: \"(c *\\<^sub>R A) $$ i = (c  *\\<^sub>R (A $$ i))\"\n  by (unfold scaleR_sq_mtx_def, transfer, simp)\n\nlemma scaleR_sq_mtx_diag: \"c *\\<^sub>R sq_mtx_diag f = (\\<d>\\<i>\\<a>\\<g> i. c * f i)\"\n  by (subst sq_mtx_eq_iff, simp add: axis_def)\n\nlemma scaleR_mtx_vec_assoc: \"(c *\\<^sub>R A) *\\<^sub>V x = c *\\<^sub>R (A *\\<^sub>V x)\"\n  unfolding scaleR_sq_mtx_def sq_mtx_vec_mult_def apply simp\n  by (simp add: scaleR_matrix_vector_assoc)\n\nlemma mtx_vec_scaleR_commute: \"A *\\<^sub>V (c *\\<^sub>R x) = c *\\<^sub>R (A *\\<^sub>V x)\"\n  unfolding scaleR_sq_mtx_def sq_mtx_vec_mult_def apply(simp, transfer)\n  by (simp add: vector_scaleR_commute)\n\nlemma mtx_times_scaleR_commute: \"A * (c *\\<^sub>R B) = c *\\<^sub>R (A * B)\" for A::\"('n::finite) sq_mtx\"\n  unfolding sq_mtx_scaleR_eq sq_mtx_times_eq \n  apply(simp add: to_mtx_inject)\n  apply(simp add: vec_eq_iff fun_eq_iff)\n  by (simp add: semiring_normalization_rules(19) vector_space_over_itself.scale_sum_right)\n\nlemma le_mtx_norm: \"m \\<in> {\\<parallel>A *\\<^sub>V x\\<parallel> |x. \\<parallel>x\\<parallel> = 1} \\<Longrightarrow> m \\<le> \\<parallel>A\\<parallel>\"\n  using cSup_upper[of _ \"{\\<parallel>(to_vec A) *v x\\<parallel> | x. \\<parallel>x\\<parallel> = 1}\"]\n  by (simp add: op_norm_set_proptys(2) op_norm_def norm_sq_mtx_def sq_mtx_vec_mult.rep_eq)\n\nlemma norm_vec_mult_le: \"\\<parallel>A *\\<^sub>V x\\<parallel> \\<le> (\\<parallel>A\\<parallel>) * (\\<parallel>x\\<parallel>)\"\n  by (simp add: norm_matrix_le_mult_op_norm norm_sq_mtx_def sq_mtx_vec_mult.rep_eq)\n\nlemma bounded_bilinear_sq_mtx_vec_mult: \"bounded_bilinear (\\<lambda>A s. A *\\<^sub>V s)\"\n  apply (rule bounded_bilinear.intro, simp_all add: mtx_vec_mult_add_rdistr \n      mtx_vec_mult_add_rdistl scaleR_mtx_vec_assoc mtx_vec_scaleR_commute)\n  by (rule_tac x=1 in exI, auto intro!: norm_vec_mult_le)\n\nlemma norm_sq_mtx_def2: \"\\<parallel>A\\<parallel> = Sup {\\<parallel>A *\\<^sub>V x\\<parallel> |x. \\<parallel>x\\<parallel> = 1}\"\n  unfolding norm_sq_mtx_def op_norm_def sq_mtx_vec_mult_def by simp\n\nlemma norm_sq_mtx_def3: \"\\<parallel>A\\<parallel> = (SUP x. (\\<parallel>A *\\<^sub>V x\\<parallel>) / (\\<parallel>x\\<parallel>))\"\n  unfolding norm_sq_mtx_def onorm_def sq_mtx_vec_mult_def by simp\n\nlemma norm_sq_mtx_diag: \"\\<parallel>sq_mtx_diag f\\<parallel> = Max {\\<bar>f i\\<bar> |i. i \\<in> UNIV}\"\n  unfolding norm_sq_mtx_def apply transfer\n  by (rule op_norm_diag_mat_eq)\n\nlemma sq_mtx_norm_le_sum_col: \"\\<parallel>A\\<parallel> \\<le> (\\<Sum>i\\<in>UNIV. \\<parallel>\\<c>\\<o>\\<l> i A\\<parallel>)\"\n  using op_norm_le_sum_column[of \"to_vec A\"] \n  apply(simp add: norm_sq_mtx_def)\n  by(transfer, simp add: op_norm_le_sum_column)\n\nlemma norm_le_transpose: \"\\<parallel>A\\<parallel> \\<le> \\<parallel>A\\<^sup>\\<dagger>\\<parallel>\"\n  unfolding norm_sq_mtx_def by transfer (rule op_norm_le_transpose)\n\nlemma norm_eq_norm_transpose[simp]: \"\\<parallel>A\\<^sup>\\<dagger>\\<parallel> = \\<parallel>A\\<parallel>\"\n  using norm_le_transpose[of A] and norm_le_transpose[of \"A\\<^sup>\\<dagger>\"] by simp\n\nlemma norm_column_le_norm: \"\\<parallel>A $$ i\\<parallel> \\<le> \\<parallel>A\\<parallel>\"\n  using norm_vec_mult_le[of \"A\\<^sup>\\<dagger>\" \"\\<e> i\"] by simp\n\n\nsubsection \\<open> Real normed algebra of square matrices \\<close>\n\ninstantiation sq_mtx :: (finite) real_normed_algebra_1\nbegin\n\nlift_definition one_sq_mtx :: \"'a sq_mtx\" is \"to_mtx (mat 1)\" .\n\nlemma sq_mtx_one_idty: \"1 * A = A\" \"A * 1 = A\" for A :: \"'a sq_mtx\"\n  by(transfer, transfer, unfold mat_def matrix_matrix_mult_def, simp add: vec_eq_iff)+\n\nlemma sq_mtx_norm_1: \"\\<parallel>(1::'a sq_mtx)\\<parallel> = 1\"\n  unfolding one_sq_mtx_def norm_sq_mtx_def \n  apply(simp add: op_norm_def)\n  apply(subst cSup_eq[of _ 1])\n  using ex_norm_eq_1 by auto\n\nlemma sq_mtx_norm_times: \"\\<parallel>A * B\\<parallel> \\<le> (\\<parallel>A\\<parallel>) * (\\<parallel>B\\<parallel>)\" for A :: \"'a sq_mtx\"\n  unfolding norm_sq_mtx_def times_sq_mtx_def by(simp add: op_norm_matrix_matrix_mult_le)\n\ninstance \n  apply intro_classes \n  apply(simp_all add: sq_mtx_one_idty sq_mtx_norm_1 sq_mtx_norm_times)\n  apply(simp_all add: to_mtx_inject vec_eq_iff one_sq_mtx_def zero_sq_mtx_def mat_def)\n  by(transfer, simp add: scalar_matrix_assoc matrix_scalar_ac)+\n\nend\n\nlemma sq_mtx_one_ith_simps[simp]: \"1 $$ i $ i = 1\" \"i \\<noteq> j \\<Longrightarrow> 1 $$ i $ j = 0\"\n  unfolding one_sq_mtx_def mat_def by simp_all\n\nlemma of_nat_eq_sq_mtx_diag[simp]: \"of_nat m = (\\<d>\\<i>\\<a>\\<g> i. m)\"\n  by (induct m) (simp, subst sq_mtx_eq_iff, simp add: axis_def)+\n\nlemma mtx_vec_mult_1[simp]: \"1 *\\<^sub>V s = s\"\n  by (auto simp: sq_mtx_vec_mult_def one_sq_mtx_def \n      mat_def vec_eq_iff matrix_vector_mult_def)\n\nlemma sq_mtx_diag_one[simp]: \"(\\<d>\\<i>\\<a>\\<g> i. 1) = 1\"\n  by (subst sq_mtx_eq_iff, simp add: one_sq_mtx_def mat_def axis_def)\n\nabbreviation \"mtx_invertible A \\<equiv> invertible (to_vec A)\"\n\nlemma mtx_invertible_def: \"mtx_invertible A \\<longleftrightarrow> (\\<exists>A'. A' * A = 1 \\<and> A * A' = 1)\"\n  apply (unfold sq_mtx_inv_def times_sq_mtx_def one_sq_mtx_def invertible_def, clarsimp, safe)\n   apply(rule_tac x=\"to_mtx A'\" in exI, simp)\n  by (rule_tac x=\"to_vec A'\" in exI, simp add: to_mtx_inject)\n\n\n\nlemma mtx_invertibleD[simp]:\n  assumes \"mtx_invertible A\" \n  shows \"A\\<^sup>-\\<^sup>1 * A = 1\" and \"A * A\\<^sup>-\\<^sup>1 = 1\"\n  apply (unfold sq_mtx_inv_def times_sq_mtx_def one_sq_mtx_def)\n  using assms by simp_all\n\nlemma mtx_invertible_inv[simp]: \"mtx_invertible A \\<Longrightarrow> mtx_invertible (A\\<^sup>-\\<^sup>1)\"\n  using mtx_invertibleD mtx_invertibleI by blast\n\nlemma mtx_invertible_one[simp]: \"mtx_invertible 1\"\n  by (simp add: one_sq_mtx.rep_eq)\n\nlemma sq_mtx_inv_unique:\n  assumes \"A * B = 1\" and \"B * A = 1\"\n  shows \"A\\<^sup>-\\<^sup>1 = B\"\n  by (metis (no_types, lifting) assms mtx_invertibleD(2) \n      mtx_invertibleI mult.assoc sq_mtx_one_idty(1))\n\nlemma sq_mtx_inv_idempotent[simp]: \"mtx_invertible A \\<Longrightarrow> A\\<^sup>-\\<^sup>1\\<^sup>-\\<^sup>1 = A\"\n  using mtx_invertibleD sq_mtx_inv_unique by blast\n\nlemma sq_mtx_inv_mult:\n  assumes \"mtx_invertible A\" and \"mtx_invertible B\"\n  shows \"(A * B)\\<^sup>-\\<^sup>1 = B\\<^sup>-\\<^sup>1 * A\\<^sup>-\\<^sup>1\"\n  by (simp add: assms matrix_inv_matrix_mul sq_mtx_inv_def times_sq_mtx_def)\n\nlemma sq_mtx_inv_one[simp]: \"1\\<^sup>-\\<^sup>1 = 1\"\n  by (simp add: sq_mtx_inv_unique)\n\ndefinition similar_sq_mtx :: \"('n::finite) sq_mtx \\<Rightarrow> 'n sq_mtx \\<Rightarrow> bool\" (infixr \"\\<sim>\" 25)\n  where \"(A \\<sim> B) \\<longleftrightarrow> (\\<exists> P. mtx_invertible P \\<and> A = P\\<^sup>-\\<^sup>1 * B * P)\"\n\nlemma similar_sq_mtx_matrix: \"(A \\<sim> B) = similar_matrix (to_vec A) (to_vec B)\"\n  apply(unfold similar_matrix_def similar_sq_mtx_def, safe)\n   apply (metis sq_mtx_inv.rep_eq times_sq_mtx.rep_eq)\n  by (metis UNIV_I sq_mtx_inv.abs_eq times_sq_mtx.abs_eq to_mtx_inverse to_vec_inverse)\n\nlemma similar_sq_mtx_refl[simp]: \"A \\<sim> A\"\n  by (unfold similar_sq_mtx_def, rule_tac x=\"1\" in exI, simp)\n\nlemma similar_sq_mtx_simm: \"A \\<sim> B \\<Longrightarrow> B \\<sim> A\"\n  apply(unfold similar_sq_mtx_def, clarsimp)\n  apply(rule_tac x=\"P\\<^sup>-\\<^sup>1\" in exI, simp add: mult.assoc)\n  by (metis mtx_invertibleD(2) mult.assoc mult.left_neutral)\n\nlemma similar_sq_mtx_trans: \"A \\<sim> B \\<Longrightarrow> B \\<sim> C \\<Longrightarrow> A \\<sim> C\"\n  unfolding similar_sq_mtx_matrix using similar_matrix_trans by blast\n\n\n\nlemma power_similiar_sq_mtx_diag_eq:\n  assumes \"mtx_invertible P\"\n      and \"A = P\\<^sup>-\\<^sup>1 * (sq_mtx_diag f) * P\"\n    shows \"A^n = P\\<^sup>-\\<^sup>1 * (\\<d>\\<i>\\<a>\\<g> i. f i^n) * P\"\nproof(induct n, simp_all add: assms)\n  fix n::nat\n  have \"P\\<^sup>-\\<^sup>1 * sq_mtx_diag f * P * (P\\<^sup>-\\<^sup>1 * (\\<d>\\<i>\\<a>\\<g> i. f i ^ n) * P) = \n  P\\<^sup>-\\<^sup>1 * sq_mtx_diag f * (\\<d>\\<i>\\<a>\\<g> i. f i ^ n) * P\"\n    by (metis (no_types, lifting) assms(1) mtx_invertibleD(2) mult.assoc mult.right_neutral)\n  also have \"... = P\\<^sup>-\\<^sup>1 * (\\<d>\\<i>\\<a>\\<g> i. f i * f i ^ n) * P\"\n    by (simp add: mult.assoc) \n  finally show \"P\\<^sup>-\\<^sup>1 * sq_mtx_diag f * P * (P\\<^sup>-\\<^sup>1 * (\\<d>\\<i>\\<a>\\<g> i. f i ^ n) * P) = \n  P\\<^sup>-\\<^sup>1 * (\\<d>\\<i>\\<a>\\<g> i. f i * f i ^ n) * P\" .\nqed\n\nlemma power_similar_sq_mtx_diag:\n  assumes \"A \\<sim> (sq_mtx_diag f)\"\n  shows \"A^n \\<sim> (\\<d>\\<i>\\<a>\\<g> i. f i^n)\"\n  using assms power_similiar_sq_mtx_diag_eq \n  unfolding similar_sq_mtx_def by blast\n\n\nsubsection \\<open> Banach space of square matrices \\<close>\n\nlemma Cauchy_cols:\n  fixes X :: \"nat \\<Rightarrow> ('a::finite) sq_mtx\" \n  assumes \"Cauchy X\"\n  shows \"Cauchy (\\<lambda>n. \\<c>\\<o>\\<l> i (X n))\" \nproof(unfold Cauchy_def dist_norm, clarsimp)\n  fix \\<epsilon>::real assume \"\\<epsilon> > 0\"\n  then obtain M where M_def:\"\\<forall>m\\<ge>M. \\<forall>n\\<ge>M. \\<parallel>X m - X n\\<parallel> < \\<epsilon>\"\n    using \\<open>Cauchy X\\<close> unfolding Cauchy_def by(simp add: dist_sq_mtx_def) metis\n  {fix m n assume \"m \\<ge> M\" and \"n \\<ge> M\"\n    hence \"\\<epsilon> > \\<parallel>X m - X n\\<parallel>\" \n      using M_def by blast\n    moreover have \"\\<parallel>X m - X n\\<parallel> \\<ge> \\<parallel>(X m - X n) *\\<^sub>V \\<e> i\\<parallel>\"\n      by(rule le_mtx_norm[of _ \"X m - X n\"], force)\n    moreover have \"\\<parallel>(X m - X n) *\\<^sub>V \\<e> i\\<parallel> = \\<parallel>X m *\\<^sub>V \\<e> i - X n *\\<^sub>V \\<e> i\\<parallel>\"\n      by (simp add: mtx_vec_mult_minus_rdistrib)\n    moreover have \"... = \\<parallel>\\<c>\\<o>\\<l> i (X m) - \\<c>\\<o>\\<l> i (X n)\\<parallel>\"\n      by (simp add: mtx_vec_mult_minus_rdistrib mtx_vec_mult_canon)\n    ultimately have \"\\<parallel>\\<c>\\<o>\\<l> i (X m) - \\<c>\\<o>\\<l> i (X n)\\<parallel> < \\<epsilon>\" \n      by linarith}\n  thus \"\\<exists>M. \\<forall>m\\<ge>M. \\<forall>n\\<ge>M. \\<parallel>\\<c>\\<o>\\<l> i (X m) - \\<c>\\<o>\\<l> i (X n)\\<parallel> < \\<epsilon>\" \n    by blast\nqed\n\nlemma col_convergence:\n  assumes \"\\<forall>i. (\\<lambda>n. \\<c>\\<o>\\<l> i (X n)) \\<longlonglongrightarrow> L $ i\" \n  shows \"X \\<longlonglongrightarrow> to_mtx (transpose L)\"\nproof(unfold LIMSEQ_def dist_norm, clarsimp)\n  let ?L = \"to_mtx (transpose L)\"\n  let ?a = \"CARD('a)\" fix \\<epsilon>::real assume \"\\<epsilon> > 0\"\n  hence \"\\<epsilon> / ?a > 0\" by simp\n  hence \"\\<forall>i. \\<exists> N. \\<forall>n\\<ge>N. \\<parallel>\\<c>\\<o>\\<l> i (X n) - L $ i\\<parallel> < \\<epsilon>/?a\"\n    using assms unfolding LIMSEQ_def dist_norm convergent_def by blast\n  then obtain N where \"\\<forall>i. \\<forall>n\\<ge>N. \\<parallel>\\<c>\\<o>\\<l> i (X n) - L $ i\\<parallel> < \\<epsilon>/?a\"\n    using finite_nat_minimal_witness[of \"\\<lambda> i n. \\<parallel>\\<c>\\<o>\\<l> i (X n) - L $ i\\<parallel> < \\<epsilon>/?a\"] by blast\n  also have \"\\<And>i n. (\\<c>\\<o>\\<l> i (X n) - L $ i) = (\\<c>\\<o>\\<l> i (X n - ?L))\"\n    unfolding minus_sq_mtx_def by(transfer, simp add: transpose_def vec_eq_iff column_def)\n  ultimately have N_def:\"\\<forall>i. \\<forall>n\\<ge>N. \\<parallel>\\<c>\\<o>\\<l> i (X n - ?L)\\<parallel> < \\<epsilon>/?a\" \n    by auto\n  have \"\\<forall>n\\<ge>N. \\<parallel>X n - ?L\\<parallel> < \\<epsilon>\"\n  proof(rule allI, rule impI)\n    fix n::nat assume \"N \\<le> n\"\n    hence \"\\<forall> i. \\<parallel>\\<c>\\<o>\\<l> i (X n - ?L)\\<parallel> < \\<epsilon>/?a\"\n      using N_def by blast\n    hence \"(\\<Sum>i\\<in>UNIV. \\<parallel>\\<c>\\<o>\\<l> i (X n - ?L)\\<parallel>) < (\\<Sum>(i::'a)\\<in>UNIV. \\<epsilon>/?a)\"\n      using sum_strict_mono[of _ \"\\<lambda>i. \\<parallel>\\<c>\\<o>\\<l> i (X n - ?L)\\<parallel>\"] by force\n    moreover have \"\\<parallel>X n - ?L\\<parallel> \\<le> (\\<Sum>i\\<in>UNIV. \\<parallel>\\<c>\\<o>\\<l> i (X n - ?L)\\<parallel>)\"\n      using sq_mtx_norm_le_sum_col by blast\n    moreover have \"(\\<Sum>(i::'a)\\<in>UNIV. \\<epsilon>/?a) = \\<epsilon>\" \n      by force\n    ultimately show \"\\<parallel>X n - ?L\\<parallel> < \\<epsilon>\" \n      by linarith\n  qed\n  thus \"\\<exists>no. \\<forall>n\\<ge>no. \\<parallel>X n - ?L\\<parallel> < \\<epsilon>\" \n    by blast\nqed\n\ninstance sq_mtx :: (finite) banach\nproof(standard)\n  fix X :: \"nat \\<Rightarrow> 'a sq_mtx\"\n  assume \"Cauchy X\"\n  hence \"\\<And>i. Cauchy (\\<lambda>n. \\<c>\\<o>\\<l> i (X n))\"\n    using Cauchy_cols by blast\n  hence obs: \"\\<forall>i. \\<exists>! L. (\\<lambda>n. \\<c>\\<o>\\<l> i (X n)) \\<longlonglongrightarrow> L\"\n    using Cauchy_convergent convergent_def LIMSEQ_unique by fastforce\n  define L where \"L = (\\<chi> i. lim (\\<lambda>n. \\<c>\\<o>\\<l> i (X n)))\"\n  hence \"\\<forall>i. (\\<lambda>n. \\<c>\\<o>\\<l> i (X n)) \\<longlonglongrightarrow> L $ i\" \n    using obs theI_unique[of \"\\<lambda>L. (\\<lambda>n. \\<c>\\<o>\\<l> _ (X n)) \\<longlonglongrightarrow> L\" \"L $ _\"] by (simp add: lim_def)\n  thus \"convergent X\"\n    using col_convergence unfolding convergent_def by blast\nqed\n\nlemma exp_similiar_sq_mtx_diag_eq:\n  assumes \"mtx_invertible P\"\n      and \"A = P\\<^sup>-\\<^sup>1 * (\\<d>\\<i>\\<a>\\<g> i. f i) * P\"\n    shows \"exp A = P\\<^sup>-\\<^sup>1 * exp (\\<d>\\<i>\\<a>\\<g> i. f i) * P\"\nproof(unfold exp_def power_similiar_sq_mtx_diag_eq[OF assms])\n  have \"(\\<Sum>n. P\\<^sup>-\\<^sup>1 * (\\<d>\\<i>\\<a>\\<g> i. f i ^ n) * P /\\<^sub>R fact n) = \n  (\\<Sum>n. P\\<^sup>-\\<^sup>1 * ((\\<d>\\<i>\\<a>\\<g> i. f i ^ n) /\\<^sub>R fact n) * P)\"\n    by simp\n  also have \"... = (\\<Sum>n. P\\<^sup>-\\<^sup>1 * ((\\<d>\\<i>\\<a>\\<g> i. f i ^ n) /\\<^sub>R fact n)) * P\"\n    apply(subst suminf_multr[OF bounded_linear.summable[OF bounded_linear_mult_right]])\n    unfolding power_sq_mtx_diag[symmetric] by (simp_all add: summable_exp_generic)\n  also have \"... = P\\<^sup>-\\<^sup>1 * (\\<Sum>n. (\\<d>\\<i>\\<a>\\<g> i. f i ^ n) /\\<^sub>R fact n) * P\"\n    apply(subst suminf_mult[of _ \"P\\<^sup>-\\<^sup>1\"])\n    unfolding power_sq_mtx_diag[symmetric] \n    by (simp_all add: summable_exp_generic)\n  finally show \"(\\<Sum>n. P\\<^sup>-\\<^sup>1 * (\\<d>\\<i>\\<a>\\<g> i. f i ^ n) * P /\\<^sub>R fact n) = \n  P\\<^sup>-\\<^sup>1 * (\\<Sum>n. sq_mtx_diag f ^ n /\\<^sub>R fact n) * P\"\n    unfolding power_sq_mtx_diag by simp\nqed\n\nlemma exp_similiar_sq_mtx_diag:\n  assumes \"A \\<sim> sq_mtx_diag f\"\n  shows \"exp A \\<sim> exp (sq_mtx_diag f)\"\n  using assms exp_similiar_sq_mtx_diag_eq \n  unfolding similar_sq_mtx_def by blast\n\nlemma suminf_sq_mtx_diag:\n  assumes \"\\<forall>i. (\\<lambda>n. f n i) sums (suminf (\\<lambda>n. f n i))\"\n  shows \"(\\<Sum>n. (\\<d>\\<i>\\<a>\\<g> i. f n i)) = (\\<d>\\<i>\\<a>\\<g> i. \\<Sum>n. f n i)\"\nproof(rule suminfI, unfold sums_def LIMSEQ_iff, clarsimp simp: norm_sq_mtx_diag)\n  let ?g = \"\\<lambda>n i. \\<bar>(\\<Sum>n<n. f n i) - (\\<Sum>n. f n i)\\<bar>\"\n  fix r::real assume \"r > 0\"\n  have \"\\<forall>i. \\<exists>no. \\<forall>n\\<ge>no. ?g n i < r\"\n    using assms \\<open>r > 0\\<close> unfolding sums_def LIMSEQ_iff by clarsimp \n  then obtain N where key: \"\\<forall>i. \\<forall>n\\<ge>N. ?g n i < r\"\n    using finite_nat_minimal_witness[of \"\\<lambda>i n. ?g n i < r\"] by blast\n  {fix n::nat\n    assume \"n \\<ge> N\"\n    obtain i where i_def: \"Max {x. \\<exists>i. x = ?g n i} = ?g n i\"\n      using cMax_finite_ex[of \"{x. \\<exists>i. x = ?g n i}\"] by auto\n    hence \"?g n i < r\"\n      using key \\<open>n \\<ge> N\\<close> by blast\n    hence \"Max {x. \\<exists>i. x = ?g n i} < r\"\n      unfolding i_def[symmetric] .}\n  thus \"\\<exists>N. \\<forall>n\\<ge>N. Max {x. \\<exists>i. x = ?g n i} < r\"\n    by blast\nqed\n\nlemma exp_sq_mtx_diag: \"exp (sq_mtx_diag f) = (\\<d>\\<i>\\<a>\\<g> i. exp (f i))\"\n  apply(unfold exp_def, simp add: power_sq_mtx_diag scaleR_sq_mtx_diag)\n  apply(rule suminf_sq_mtx_diag)\n  using exp_converges[of \"f _\"] \n  unfolding sums_def LIMSEQ_iff exp_def by force\n\nlemma exp_scaleR_diagonal1:\n  assumes \"mtx_invertible P\" and \"A = P\\<^sup>-\\<^sup>1 * (\\<d>\\<i>\\<a>\\<g> i. f i) * P\"\n    shows \"exp (t *\\<^sub>R A) = P\\<^sup>-\\<^sup>1 * (\\<d>\\<i>\\<a>\\<g> i. exp (t * f i)) * P\"\nproof-\n  have \"exp (t *\\<^sub>R A) = exp (P\\<^sup>-\\<^sup>1 * (t *\\<^sub>R sq_mtx_diag f) * P)\"\n    using assms by simp\n  also have \"... = P\\<^sup>-\\<^sup>1 * (\\<d>\\<i>\\<a>\\<g> i. exp (t * f i)) * P\"\n    by (metis assms(1) exp_similiar_sq_mtx_diag_eq exp_sq_mtx_diag scaleR_sq_mtx_diag)\n  finally show \"exp (t *\\<^sub>R A) = P\\<^sup>-\\<^sup>1 * (\\<d>\\<i>\\<a>\\<g> i. exp (t * f i)) * P\" .\nqed\n\nlemma exp_scaleR_diagonal2:\n  assumes \"mtx_invertible P\" and \"A = P * (\\<d>\\<i>\\<a>\\<g> i. f i) * P\\<^sup>-\\<^sup>1\"\n    shows \"exp (t *\\<^sub>R A) = P * (\\<d>\\<i>\\<a>\\<g> i. exp (t * f i)) * P\\<^sup>-\\<^sup>1\"\n  apply(subst sq_mtx_inv_idempotent[OF assms(1), symmetric])\n  apply(rule exp_scaleR_diagonal1)\n  by (simp_all add: assms)\n\n\nsubsection \\<open> Examples \\<close>\n\ndefinition \"mtx A = to_mtx (vector (map vector A))\"\n\nlemma vector_nth_eq: \"(vector A) $ i = foldr (\\<lambda>x f n. (f (n + 1))(n := x)) A (\\<lambda>n x. 0) 1 i\"\n  unfolding vector_def by simp\n\nlemma mtx_ith_eq[simp]: \"mtx A $$ i $ j = foldr (\\<lambda>x f n. (f (n + 1))(n := x))\n  (map (\\<lambda>l. vec_lambda (foldr (\\<lambda>x f n. (f (n + 1))(n := x)) l (\\<lambda>n x. 0) 1)) A) (\\<lambda>n x. 0) 1 i $ j\"\n  unfolding mtx_def vector_def by (simp add: vector_nth_eq)\n\nsubsubsection \\<open> 2x2 matrices \\<close>\n\nlemma mtx2_eq_iff: \"(mtx \n  ([a1, b1] # \n   [c1, d1] # []) :: 2 sq_mtx) = mtx \n  ([a2, b2] # \n   [c2, d2] # []) \\<longleftrightarrow> a1 = a2 \\<and> b1 = b2 \\<and> c1 = c2 \\<and> d1 = d2\"\n  apply(simp add: sq_mtx_eq_iff, safe)\n  using exhaust_2 by force+\n\nlemma mtx2_to_mtx: \"mtx \n  ([a, b] # \n   [c, d] # []) = \n  to_mtx (\\<chi> i j::2. if i=1 \\<and> j=1 then a \n  else (if i=1 \\<and> j=2 then b \n  else (if i=2 \\<and> j=1 then c \n  else d)))\"\n  apply(subst sq_mtx_eq_iff)\n  using exhaust_2 by force\n\nabbreviation diag2 :: \"real \\<Rightarrow> real \\<Rightarrow> 2 sq_mtx\" \n  where \"diag2 \\<iota>\\<^sub>1 \\<iota>\\<^sub>2 \\<equiv> mtx \n   ([\\<iota>\\<^sub>1, 0] # \n    [0, \\<iota>\\<^sub>2] # [])\"\n\nlemma diag2_eq: \"diag2 (\\<iota> 1) (\\<iota> 2) = (\\<d>\\<i>\\<a>\\<g> i. \\<iota> i)\"\n  apply(simp add: sq_mtx_eq_iff)\n  using exhaust_2 by (force simp: axis_def)\n\nlemma one_mtx2: \"(1::2 sq_mtx) = diag2 1 1\"\n  apply(subst sq_mtx_eq_iff)\n  using exhaust_2 by force\n\nlemma zero_mtx2: \"(0::2 sq_mtx) = diag2 0 0\"\n  by (simp add: sq_mtx_eq_iff)\n\nlemma scaleR_mtx2: \"k *\\<^sub>R mtx \n  ([a, b] # \n   [c, d] # []) = mtx \n  ([k*a, k*b] # \n   [k*c, k*d] # [])\"\n  by (simp add: sq_mtx_eq_iff)\n\nlemma uminus_mtx2: \"-mtx \n  ([a, b] # \n   [c, d] # []) = (mtx \n  ([-a, -b] # \n   [-c, -d] # [])::2 sq_mtx)\"\n  by (simp add: sq_mtx_uminus_eq sq_mtx_eq_iff)\n\nlemma plus_mtx2: \"mtx \n  ([a1, b1] # \n   [c1, d1] # []) + mtx \n  ([a2, b2] # \n   [c2, d2] # []) = ((mtx \n  ([a1+a2, b1+b2] # \n   [c1+c2, d1+d2] # []))::2 sq_mtx)\"\n  by (simp add: sq_mtx_eq_iff)\n\nlemma minus_mtx2: \"mtx \n  ([a1, b1] # \n   [c1, d1] # []) - mtx \n  ([a2, b2] # \n   [c2, d2] # []) = ((mtx \n  ([a1-a2, b1-b2] # \n   [c1-c2, d1-d2] # []))::2 sq_mtx)\"\n  by (simp add: sq_mtx_eq_iff)\n\nlemma times_mtx2: \"mtx \n  ([a1, b1] # \n   [c1, d1] # []) * mtx \n  ([a2, b2] # \n   [c2, d2] # []) = ((mtx \n  ([a1*a2+b1*c2, a1*b2+b1*d2] # \n   [c1*a2+d1*c2, c1*b2+d1*d2] # []))::2 sq_mtx)\"\n  unfolding sq_mtx_times_eq UNIV_2\n  by (simp add: sq_mtx_eq_iff)\n\nsubsubsection \\<open> 3x3 matrices \\<close>\n\nlemma mtx3_to_mtx: \"mtx \n  ([a\\<^sub>1\\<^sub>1, a\\<^sub>1\\<^sub>2, a\\<^sub>1\\<^sub>3] # \n   [a\\<^sub>2\\<^sub>1, a\\<^sub>2\\<^sub>2, a\\<^sub>2\\<^sub>3] # \n   [a\\<^sub>3\\<^sub>1, a\\<^sub>3\\<^sub>2, a\\<^sub>3\\<^sub>3] # []) = \n  to_mtx (\\<chi> i j::3. if i=1 \\<and> j=1 then a\\<^sub>1\\<^sub>1\n  else (if i=1 \\<and> j=2 then a\\<^sub>1\\<^sub>2 \n  else (if i=1 \\<and> j=3 then a\\<^sub>1\\<^sub>3 \n  else (if i=2 \\<and> j=1 then a\\<^sub>2\\<^sub>1\n  else (if i=2 \\<and> j=2 then a\\<^sub>2\\<^sub>2 \n  else (if i=2 \\<and> j=3 then a\\<^sub>2\\<^sub>3 \n  else (if i=3 \\<and> j=1 then a\\<^sub>3\\<^sub>1 \n  else (if i=3 \\<and> j=2 then a\\<^sub>3\\<^sub>2 \n  else a\\<^sub>3\\<^sub>3))))))))\"\n  apply(simp add: sq_mtx_eq_iff)\n  using exhaust_3 by force\n\nabbreviation diag3 :: \"real \\<Rightarrow> real \\<Rightarrow> real \\<Rightarrow> 3 sq_mtx\" \n  where \"diag3 \\<iota>\\<^sub>1 \\<iota>\\<^sub>2 \\<iota>\\<^sub>3 \\<equiv> mtx \n  ([\\<iota>\\<^sub>1, 0, 0] # \n   [0, \\<iota>\\<^sub>2, 0] # \n   [0, 0, \\<iota>\\<^sub>3] # [])\"\n\nlemma diag3_eq: \"diag3 (\\<iota> 1) (\\<iota> 2) (\\<iota> 3) = (\\<d>\\<i>\\<a>\\<g> i. \\<iota> i)\"\n  apply(simp add: sq_mtx_eq_iff)\n  using exhaust_3 by (force simp: axis_def)\n\nlemma one_mtx3: \"(1::3 sq_mtx) = diag3 1 1 1\"\n  apply(subst sq_mtx_eq_iff)\n  using exhaust_3 by force\n\nlemma zero_mtx3: \"(0::3 sq_mtx) = diag3 0 0 0\"\n  by (simp add: sq_mtx_eq_iff)\n\nlemma scaleR_mtx3: \"k *\\<^sub>R mtx \n  ([a\\<^sub>1\\<^sub>1, a\\<^sub>1\\<^sub>2, a\\<^sub>1\\<^sub>3] # \n   [a\\<^sub>2\\<^sub>1, a\\<^sub>2\\<^sub>2, a\\<^sub>2\\<^sub>3] # \n   [a\\<^sub>3\\<^sub>1, a\\<^sub>3\\<^sub>2, a\\<^sub>3\\<^sub>3] # []) = mtx \n  ([k*a\\<^sub>1\\<^sub>1, k*a\\<^sub>1\\<^sub>2, k*a\\<^sub>1\\<^sub>3] # \n   [k*a\\<^sub>2\\<^sub>1, k*a\\<^sub>2\\<^sub>2, k*a\\<^sub>2\\<^sub>3] # \n   [k*a\\<^sub>3\\<^sub>1, k*a\\<^sub>3\\<^sub>2, k*a\\<^sub>3\\<^sub>3] # [])\"\n  by (simp add: sq_mtx_eq_iff)\n\nlemma plus_mtx3: \"mtx \n  ([a\\<^sub>1\\<^sub>1, a\\<^sub>1\\<^sub>2, a\\<^sub>1\\<^sub>3] # \n   [a\\<^sub>2\\<^sub>1, a\\<^sub>2\\<^sub>2, a\\<^sub>2\\<^sub>3] # \n   [a\\<^sub>3\\<^sub>1, a\\<^sub>3\\<^sub>2, a\\<^sub>3\\<^sub>3] # []) + mtx \n  ([b\\<^sub>1\\<^sub>1, b\\<^sub>1\\<^sub>2, b\\<^sub>1\\<^sub>3] # \n   [b\\<^sub>2\\<^sub>1, b\\<^sub>2\\<^sub>2, b\\<^sub>2\\<^sub>3] # \n   [b\\<^sub>3\\<^sub>1, b\\<^sub>3\\<^sub>2, b\\<^sub>3\\<^sub>3] # []) = (mtx \n  ([a\\<^sub>1\\<^sub>1+b\\<^sub>1\\<^sub>1, a\\<^sub>1\\<^sub>2+b\\<^sub>1\\<^sub>2, a\\<^sub>1\\<^sub>3+b\\<^sub>1\\<^sub>3] # \n   [a\\<^sub>2\\<^sub>1+b\\<^sub>2\\<^sub>1, a\\<^sub>2\\<^sub>2+b\\<^sub>2\\<^sub>2, a\\<^sub>2\\<^sub>3+b\\<^sub>2\\<^sub>3] # \n   [a\\<^sub>3\\<^sub>1+b\\<^sub>3\\<^sub>1, a\\<^sub>3\\<^sub>2+b\\<^sub>3\\<^sub>2, a\\<^sub>3\\<^sub>3+b\\<^sub>3\\<^sub>3] # [])::3 sq_mtx)\"\n  by (subst sq_mtx_eq_iff) simp\n\nlemma minus_mtx3: \"mtx \n  ([a\\<^sub>1\\<^sub>1, a\\<^sub>1\\<^sub>2, a\\<^sub>1\\<^sub>3] # \n   [a\\<^sub>2\\<^sub>1, a\\<^sub>2\\<^sub>2, a\\<^sub>2\\<^sub>3] # \n   [a\\<^sub>3\\<^sub>1, a\\<^sub>3\\<^sub>2, a\\<^sub>3\\<^sub>3] # []) - mtx \n  ([b\\<^sub>1\\<^sub>1, b\\<^sub>1\\<^sub>2, b\\<^sub>1\\<^sub>3] # \n   [b\\<^sub>2\\<^sub>1, b\\<^sub>2\\<^sub>2, b\\<^sub>2\\<^sub>3] # \n   [b\\<^sub>3\\<^sub>1, b\\<^sub>3\\<^sub>2, b\\<^sub>3\\<^sub>3] # []) = (mtx \n  ([a\\<^sub>1\\<^sub>1-b\\<^sub>1\\<^sub>1, a\\<^sub>1\\<^sub>2-b\\<^sub>1\\<^sub>2, a\\<^sub>1\\<^sub>3-b\\<^sub>1\\<^sub>3] # \n   [a\\<^sub>2\\<^sub>1-b\\<^sub>2\\<^sub>1, a\\<^sub>2\\<^sub>2-b\\<^sub>2\\<^sub>2, a\\<^sub>2\\<^sub>3-b\\<^sub>2\\<^sub>3] # \n   [a\\<^sub>3\\<^sub>1-b\\<^sub>3\\<^sub>1, a\\<^sub>3\\<^sub>2-b\\<^sub>3\\<^sub>2, a\\<^sub>3\\<^sub>3-b\\<^sub>3\\<^sub>3] # [])::3 sq_mtx)\"\n  by (simp add: sq_mtx_eq_iff)\n\nlemma times_mtx3: \"mtx \n  ([a\\<^sub>1\\<^sub>1, a\\<^sub>1\\<^sub>2, a\\<^sub>1\\<^sub>3] # \n   [a\\<^sub>2\\<^sub>1, a\\<^sub>2\\<^sub>2, a\\<^sub>2\\<^sub>3] # \n   [a\\<^sub>3\\<^sub>1, a\\<^sub>3\\<^sub>2, a\\<^sub>3\\<^sub>3] # []) * mtx \n  ([b\\<^sub>1\\<^sub>1, b\\<^sub>1\\<^sub>2, b\\<^sub>1\\<^sub>3] # \n   [b\\<^sub>2\\<^sub>1, b\\<^sub>2\\<^sub>2, b\\<^sub>2\\<^sub>3] # \n   [b\\<^sub>3\\<^sub>1, b\\<^sub>3\\<^sub>2, b\\<^sub>3\\<^sub>3] # []) = (mtx \n  ([a\\<^sub>1\\<^sub>1*b\\<^sub>1\\<^sub>1+a\\<^sub>1\\<^sub>2*b\\<^sub>2\\<^sub>1+a\\<^sub>1\\<^sub>3*b\\<^sub>3\\<^sub>1, a\\<^sub>1\\<^sub>1*b\\<^sub>1\\<^sub>2+a\\<^sub>1\\<^sub>2*b\\<^sub>2\\<^sub>2+a\\<^sub>1\\<^sub>3*b\\<^sub>3\\<^sub>2, a\\<^sub>1\\<^sub>1*b\\<^sub>1\\<^sub>3+a\\<^sub>1\\<^sub>2*b\\<^sub>2\\<^sub>3+a\\<^sub>1\\<^sub>3*b\\<^sub>3\\<^sub>3] # \n   [a\\<^sub>2\\<^sub>1*b\\<^sub>1\\<^sub>1+a\\<^sub>2\\<^sub>2*b\\<^sub>2\\<^sub>1+a\\<^sub>2\\<^sub>3*b\\<^sub>3\\<^sub>1, a\\<^sub>2\\<^sub>1*b\\<^sub>1\\<^sub>2+a\\<^sub>2\\<^sub>2*b\\<^sub>2\\<^sub>2+a\\<^sub>2\\<^sub>3*b\\<^sub>3\\<^sub>2, a\\<^sub>2\\<^sub>1*b\\<^sub>1\\<^sub>3+a\\<^sub>2\\<^sub>2*b\\<^sub>2\\<^sub>3+a\\<^sub>2\\<^sub>3*b\\<^sub>3\\<^sub>3] # \n   [a\\<^sub>3\\<^sub>1*b\\<^sub>1\\<^sub>1+a\\<^sub>3\\<^sub>2*b\\<^sub>2\\<^sub>1+a\\<^sub>3\\<^sub>3*b\\<^sub>3\\<^sub>1, a\\<^sub>3\\<^sub>1*b\\<^sub>1\\<^sub>2+a\\<^sub>3\\<^sub>2*b\\<^sub>2\\<^sub>2+a\\<^sub>3\\<^sub>3*b\\<^sub>3\\<^sub>2, a\\<^sub>3\\<^sub>1*b\\<^sub>1\\<^sub>3+a\\<^sub>3\\<^sub>2*b\\<^sub>2\\<^sub>3+a\\<^sub>3\\<^sub>3*b\\<^sub>3\\<^sub>3] # [])::3 sq_mtx)\"\n  unfolding sq_mtx_times_eq\n  unfolding UNIV_3 by (simp add: sq_mtx_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/Matrices_for_ODEs/SQ_MTX.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8902942203004186, "lm_q2_score": 0.8397339676722393, "lm_q1q2_score": 0.7476102980085332}}
{"text": "(*\n    Original Author of Riddle: Tjark Weber\n    Updates and additions by Jacques Fleuriot\n*)\n\ntheory tut4sol 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 ", "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/tut4sol.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528057272543, "lm_q2_score": 0.8774767970940975, "lm_q1q2_score": 0.747568819244881}}
{"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\ntext\\<^marker>\\<open>tag important\\<close> \\<open>%whitespace\\<close>\ndefinition\\<^marker>\\<open>tag important\\<close>\nonorm :: \"('a::real_normed_vector \\<Rightarrow> 'b::real_normed_vector) \\<Rightarrow> real\" where\n\"onorm f = (SUP x. norm (f x) / norm x)\"\n\nproposition 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\nlemma onorm_sum:\n  assumes \"finite S\"\n  assumes \"\\<And>s. s \\<in> S \\<Longrightarrow> bounded_linear (f s)\"\n  shows \"onorm (\\<lambda>x. sum (\\<lambda>s. f s x) S) \\<le> sum (\\<lambda>s. onorm (f s)) S\"\n  using assms\n  by (induction) (auto simp: onorm_zero intro!: onorm_triangle_le bounded_linear_sum)\n\nlemmas onorm_sum_le = onorm_sum[THEN order_trans]\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/Operator_Norm.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774768002981829, "lm_q2_score": 0.8519528000888386, "lm_q1q2_score": 0.7475688170270315}}
{"text": "(* Author: Manuel Eberl *)\n\nsection \\<open>Abstract euclidean algorithm\\<close>\n\ntheory Euclidean_Algorithm\nimports \"~~/src/HOL/GCD\" Factorial_Ring\nbegin\n\ntext \\<open>\n  A Euclidean semiring is a semiring upon which the Euclidean algorithm can be\n  implemented. It must provide:\n  \\begin{itemize}\n  \\item division with remainder\n  \\item a size function such that @{term \"size (a mod b) < size b\"} \n        for any @{term \"b \\<noteq> 0\"}\n  \\end{itemize}\n  The existence of these functions makes it possible to derive gcd and lcm functions \n  for any Euclidean semiring.\n\\<close> \nclass euclidean_semiring = semiring_modulo + normalization_semidom + \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 mod_0 [simp]: \"0 mod a = 0\"\n  using div_mult_mod_eq [of 0 a] by simp\n\nlemma dvd_mod_iff: \n  assumes \"k dvd n\"\n  shows   \"(k dvd m mod n) = (k dvd m)\"\nproof -\n  from assms have \"(k dvd m mod n) \\<longleftrightarrow> (k dvd ((m div n) * n + m mod n))\" \n    by (simp add: dvd_add_right_iff)\n  also have \"(m div n) * n + m mod n = m\"\n    using div_mult_mod_eq [of m n] by simp\n  finally show ?thesis .\nqed\n\nlemma mod_0_imp_dvd: \n  assumes \"a mod b = 0\"\n  shows   \"b dvd a\"\nproof -\n  have \"b dvd ((a div b) * b)\" by simp\n  also have \"(a div b) * b = a\"\n    using div_mult_mod_eq [of a b] by (simp add: assms)\n  finally show ?thesis .\nqed\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\nlemma euclidean_division:\n  fixes a :: 'a and b :: 'a\n  assumes \"b \\<noteq> 0\"\n  obtains s and t where \"a = s * b + t\" \n    and \"euclidean_size t < euclidean_size b\"\nproof -\n  from div_mult_mod_eq [of a b] \n     have \"a = a div b * b + a mod b\" by simp\n  with that and assms show ?thesis by (auto simp add: mod_size_less)\nqed\n\nlemma dvd_euclidean_size_eq_imp_dvd:\n  assumes \"a \\<noteq> 0\" and b_dvd_a: \"b dvd a\" and size_eq: \"euclidean_size a = euclidean_size b\"\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 b_dvd_a have b_dvd_mod: \"b dvd b mod a\" by (simp add: dvd_mod_iff)\n  from b_dvd_mod 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 size_eq by simp\nqed\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 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: \"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\" 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 simp: )\nqed\n\nfunction gcd_eucl :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a\"\nwhere\n  \"gcd_eucl a b = (if b = 0 then normalize a else gcd_eucl 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_eucl.simps [simp del]\n\nlemma gcd_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_eucl.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\ndefinition lcm_eucl :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a\"\nwhere\n  \"lcm_eucl a b = normalize (a * b) div gcd_eucl a b\"\n\ndefinition Lcm_eucl :: \"'a set \\<Rightarrow> 'a\" \\<comment> \\<open>\n  Somewhat complicated definition of Lcm that has the advantage of working\n  for infinite sets as well\\<close>\nwhere\n  \"Lcm_eucl 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\ndefinition Gcd_eucl :: \"'a set \\<Rightarrow> 'a\"\nwhere\n  \"Gcd_eucl A = Lcm_eucl {d. \\<forall>a\\<in>A. d dvd a}\"\n\ndeclare Lcm_eucl_def Gcd_eucl_def [code del]\n\nlemma gcd_eucl_0:\n  \"gcd_eucl a 0 = normalize a\"\n  by (simp add: gcd_eucl.simps [of a 0])\n\nlemma gcd_eucl_0_left:\n  \"gcd_eucl 0 a = normalize a\"\n  by (simp_all add: gcd_eucl_0 gcd_eucl.simps [of 0 a])\n\nlemma gcd_eucl_non_0:\n  \"b \\<noteq> 0 \\<Longrightarrow> gcd_eucl a b = gcd_eucl b (a mod b)\"\n  by (simp add: gcd_eucl.simps [of a b] gcd_eucl.simps [of b 0])\n\nlemma gcd_eucl_dvd1 [iff]: \"gcd_eucl a b dvd a\"\n  and gcd_eucl_dvd2 [iff]: \"gcd_eucl a b dvd b\"\n  by (induct a b rule: gcd_eucl_induct)\n     (simp_all add: gcd_eucl_0 gcd_eucl_non_0 dvd_mod_iff)\n\nlemma normalize_gcd_eucl [simp]:\n  \"normalize (gcd_eucl a b) = gcd_eucl a b\"\n  by (induct a b rule: gcd_eucl_induct) (simp_all add: gcd_eucl_0 gcd_eucl_non_0)\n     \nlemma gcd_eucl_greatest:\n  fixes k a b :: 'a\n  shows \"k dvd a \\<Longrightarrow> k dvd b \\<Longrightarrow> k dvd gcd_eucl a b\"\nproof (induct a b rule: gcd_eucl_induct)\n  case (zero a) from zero(1) show ?case by (rule dvd_trans) (simp add: gcd_eucl_0)\nnext\n  case (mod a b)\n  then show ?case\n    by (simp add: gcd_eucl_non_0 dvd_mod_iff)\nqed\n\nlemma gcd_euclI:\n  fixes gcd :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a\"\n  assumes \"d dvd a\" \"d dvd b\" \"normalize d = d\"\n          \"\\<And>k. k dvd a \\<Longrightarrow> k dvd b \\<Longrightarrow> k dvd d\"\n  shows   \"gcd_eucl a b = d\"\n  by (rule associated_eqI) (simp_all add: gcd_eucl_greatest assms)\n\nlemma eq_gcd_euclI:\n  fixes gcd :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a\"\n  assumes \"\\<And>a b. gcd a b dvd a\" \"\\<And>a b. gcd a b dvd b\" \"\\<And>a b. normalize (gcd a b) = gcd a b\"\n          \"\\<And>a b k. k dvd a \\<Longrightarrow> k dvd b \\<Longrightarrow> k dvd gcd a b\"\n  shows   \"gcd = gcd_eucl\"\n  by (intro ext, rule associated_eqI) (simp_all add: gcd_eucl_greatest assms)\n\nlemma gcd_eucl_zero [simp]:\n  \"gcd_eucl a b = 0 \\<longleftrightarrow> a = 0 \\<and> b = 0\"\n  by (metis dvd_0_left dvd_refl gcd_eucl_dvd1 gcd_eucl_dvd2 gcd_eucl_greatest)+\n\n  \nlemma dvd_Lcm_eucl [simp]: \"a \\<in> A \\<Longrightarrow> a dvd Lcm_eucl A\"\n  and Lcm_eucl_least: \"(\\<And>a. a \\<in> A \\<Longrightarrow> a dvd b) \\<Longrightarrow> Lcm_eucl A dvd b\"\n  and unit_factor_Lcm_eucl [simp]: \n          \"unit_factor (Lcm_eucl A) = (if Lcm_eucl A = 0 then 0 else 1)\"\nproof -\n  have \"(\\<forall>a\\<in>A. a dvd Lcm_eucl A) \\<and> (\\<forall>l'. (\\<forall>a\\<in>A. a dvd l') \\<longrightarrow> Lcm_eucl A dvd l') \\<and>\n    unit_factor (Lcm_eucl A) = (if Lcm_eucl A = 0 then 0 else 1)\" (is ?thesis)\n  proof (cases \"\\<exists>l. l \\<noteq>  0 \\<and> (\\<forall>a\\<in>A. a dvd l)\")\n    case False\n    hence \"Lcm_eucl A = 0\" by (auto simp: Lcm_eucl_def)\n    with False show ?thesis by auto\n  next\n    case True\n    then obtain l\\<^sub>0 where l\\<^sub>0_props: \"l\\<^sub>0 \\<noteq> 0 \\<and> (\\<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\" 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_eucl l l'\" by (auto intro: gcd_eucl_greatest)\n      moreover from \\<open>l \\<noteq> 0\\<close> have \"gcd_eucl l l' \\<noteq> 0\" 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_eucl l l')\"\n        by (intro exI[of _ \"gcd_eucl l l'\"], auto)\n      hence \"euclidean_size (gcd_eucl l l') \\<ge> n\" by (subst n_def) (rule Least_le)\n      moreover have \"euclidean_size (gcd_eucl l l') \\<le> n\"\n      proof -\n        have \"gcd_eucl l l' dvd l\" by simp\n        then obtain a where \"l = gcd_eucl l l' * a\" unfolding dvd_def by blast\n        with \\<open>l \\<noteq> 0\\<close> have \"a \\<noteq> 0\" by auto\n        hence \"euclidean_size (gcd_eucl l l') \\<le> euclidean_size (gcd_eucl l l' * a)\"\n          by (rule size_mult_mono)\n        also have \"gcd_eucl l l' * a = l\" using \\<open>l = gcd_eucl l l' * a\\<close> ..\n        also note \\<open>euclidean_size l = n\\<close>\n        finally show \"euclidean_size (gcd_eucl l l') \\<le> n\" .\n      qed\n      ultimately have *: \"euclidean_size l = euclidean_size (gcd_eucl 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_eucl 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_eucl_dvd2])\n    }\n\n    with \\<open>(\\<forall>a\\<in>A. a dvd l)\\<close> and unit_factor_is_unit[OF \\<open>l \\<noteq> 0\\<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') \\<and>\n        unit_factor (normalize l) = \n        (if normalize l = 0 then 0 else 1)\"\n      by (auto simp: unit_simps)\n    also from True have \"normalize l = Lcm_eucl A\"\n      by (simp add: Lcm_eucl_def Let_def n_def l_def)\n    finally show ?thesis .\n  qed\n  note A = this\n\n  {fix a assume \"a \\<in> A\" then show \"a dvd Lcm_eucl A\" using A by blast}\n  {fix b assume \"\\<And>a. a \\<in> A \\<Longrightarrow> a dvd b\" then show \"Lcm_eucl A dvd b\" using A by blast}\n  from A show \"unit_factor (Lcm_eucl A) = (if Lcm_eucl A = 0 then 0 else 1)\" by blast\nqed\n\nlemma normalize_Lcm_eucl [simp]:\n  \"normalize (Lcm_eucl A) = Lcm_eucl A\"\nproof (cases \"Lcm_eucl A = 0\")\n  case True then show ?thesis by simp\nnext\n  case False\n  have \"unit_factor (Lcm_eucl A) * normalize (Lcm_eucl A) = Lcm_eucl A\"\n    by (fact unit_factor_mult_normalize)\n  with False show ?thesis by simp\nqed\n\nlemma eq_Lcm_euclI:\n  fixes lcm :: \"'a set \\<Rightarrow> 'a\"\n  assumes \"\\<And>A a. a \\<in> A \\<Longrightarrow> a dvd lcm A\" and \"\\<And>A c. (\\<And>a. a \\<in> A \\<Longrightarrow> a dvd c) \\<Longrightarrow> lcm A dvd c\"\n          \"\\<And>A. normalize (lcm A) = lcm A\" shows \"lcm = Lcm_eucl\"\n  by (intro ext, rule associated_eqI) (auto simp: assms intro: Lcm_eucl_least)  \n\nlemma Gcd_eucl_dvd: \"a \\<in> A \\<Longrightarrow> Gcd_eucl A dvd a\"\n  unfolding Gcd_eucl_def by (auto intro: Lcm_eucl_least)\n\nlemma Gcd_eucl_greatest: \"(\\<And>x. x \\<in> A \\<Longrightarrow> d dvd x) \\<Longrightarrow> d dvd Gcd_eucl A\"\n  unfolding Gcd_eucl_def by auto\n\nlemma normalize_Gcd_eucl [simp]: \"normalize (Gcd_eucl A) = Gcd_eucl A\"\n  by (simp add: Gcd_eucl_def)\n\nlemma Lcm_euclI:\n  assumes \"\\<And>x. x \\<in> A \\<Longrightarrow> x dvd d\" \"\\<And>d'. (\\<And>x. x \\<in> A \\<Longrightarrow> x dvd d') \\<Longrightarrow> d dvd d'\" \"normalize d = d\"\n  shows   \"Lcm_eucl A = d\"\nproof -\n  have \"normalize (Lcm_eucl A) = normalize d\"\n    by (intro associatedI) (auto intro: dvd_Lcm_eucl Lcm_eucl_least assms)\n  thus ?thesis by (simp add: assms)\nqed\n\nlemma Gcd_euclI:\n  assumes \"\\<And>x. x \\<in> A \\<Longrightarrow> d dvd x\" \"\\<And>d'. (\\<And>x. x \\<in> A \\<Longrightarrow> d' dvd x) \\<Longrightarrow> d' dvd d\" \"normalize d = d\"\n  shows   \"Gcd_eucl A = d\"\nproof -\n  have \"normalize (Gcd_eucl A) = normalize d\"\n    by (intro associatedI) (auto intro: Gcd_eucl_dvd Gcd_eucl_greatest assms)\n  thus ?thesis by (simp add: assms)\nqed\n  \nlemmas lcm_gcd_eucl_facts = \n  gcd_eucl_dvd1 gcd_eucl_dvd2 gcd_eucl_greatest normalize_gcd_eucl lcm_eucl_def\n  Gcd_eucl_def Gcd_eucl_dvd Gcd_eucl_greatest normalize_Gcd_eucl\n  dvd_Lcm_eucl Lcm_eucl_least normalize_Lcm_eucl\n\nlemma normalized_factors_product:\n  \"{p. p dvd a * b \\<and> normalize p = p} = \n     (\\<lambda>(x,y). x * y) ` ({p. p dvd a \\<and> normalize p = p} \\<times> {p. p dvd b \\<and> normalize p = p})\"\nproof safe\n  fix p assume p: \"p dvd a * b\" \"normalize p = p\"\n  interpret semiring_gcd 1 0 \"op *\" gcd_eucl lcm_eucl \"op div\" \"op +\" \"op -\" normalize unit_factor\n    by standard (rule lcm_gcd_eucl_facts; assumption)+\n  from dvd_productE[OF p(1)] guess x y . note xy = this\n  define x' y' where \"x' = normalize x\" and \"y' = normalize y\"\n  have \"p = x' * y'\"\n    by (subst p(2) [symmetric]) (simp add: xy x'_def y'_def normalize_mult)\n  moreover from xy have \"normalize x' = x'\" \"normalize y' = y'\" \"x' dvd a\" \"y' dvd b\" \n    by (simp_all add: x'_def y'_def)\n  ultimately show \"p \\<in> (\\<lambda>(x, y). x * y) ` \n                     ({p. p dvd a \\<and> normalize p = p} \\<times> {p. p dvd b \\<and> normalize p = p})\"\n    by blast\nqed (auto simp: normalize_mult mult_dvd_mono)\n\n\nsubclass factorial_semiring\nproof (standard, rule factorial_semiring_altI_aux)\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      \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      from x y have \"\\<not>is_unit z\" by (auto simp: mult_unit_dvd_iff)\n      have \"?fctrs x = (\\<lambda>(p,p'). p * p') ` (?fctrs y \\<times> ?fctrs z)\"\n        by (subst x) (rule normalized_factors_product)\n      also 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'). 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      finally show ?thesis .\n    qed\n  qed\nnext\n  interpret semiring_gcd 1 0 \"op *\" gcd_eucl lcm_eucl \"op div\" \"op +\" \"op -\" normalize unit_factor\n    by standard (rule lcm_gcd_eucl_facts; assumption)+\n  fix p assume p: \"irreducible p\"\n  thus \"prime_elem p\" by (rule irreducible_imp_prime_elem_gcd)\nqed\n\nlemma gcd_eucl_eq_gcd_factorial: \"gcd_eucl = gcd_factorial\"\n  by (intro ext gcd_euclI gcd_lcm_factorial)\n\nlemma lcm_eucl_eq_lcm_factorial: \"lcm_eucl = lcm_factorial\"\n  by (intro ext) (simp add: lcm_eucl_def lcm_factorial_gcd_factorial gcd_eucl_eq_gcd_factorial)\n\nlemma Gcd_eucl_eq_Gcd_factorial: \"Gcd_eucl = Gcd_factorial\"\n  by (intro ext Gcd_euclI gcd_lcm_factorial)\n\nlemma Lcm_eucl_eq_Lcm_factorial: \"Lcm_eucl = Lcm_factorial\"\n  by (intro ext Lcm_euclI gcd_lcm_factorial)\n\nlemmas eucl_eq_factorial = \n  gcd_eucl_eq_gcd_factorial lcm_eucl_eq_lcm_factorial \n  Gcd_eucl_eq_Gcd_factorial Lcm_eucl_eq_Lcm_factorial\n  \nend\n\nclass euclidean_ring = euclidean_semiring + idom\nbegin\n\nfunction euclid_ext_aux :: \"'a \\<Rightarrow> _\" where\n  \"euclid_ext_aux r' r s' s t' t = (\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 r (r' mod r) s (s' - q * s) t (t' - q * t))\"\nby auto\ntermination by (relation \"measure (\\<lambda>(_,b,_,_,_,_). euclidean_size b)\") (simp_all add: mod_size_less)\n\ndeclare euclid_ext_aux.simps [simp del]\n\nlemma euclid_ext_aux_correct:\n  assumes \"gcd_eucl r' r = gcd_eucl a b\"\n  assumes \"s' * a + t' * b = r'\"\n  assumes \"s * a + t * b = r\"\n  shows   \"case euclid_ext_aux r' r s' s t' t of (x,y,c) \\<Rightarrow>\n             x * a + y * b = c \\<and> c = gcd_eucl a b\" (is \"?P (euclid_ext_aux r' r s' s t' t)\")\nusing assms\nproof (induction r' r s' s t' t rule: euclid_ext_aux.induct)\n  case (1 r' r s' s t' t)\n  show ?case\n  proof (cases \"r = 0\")\n    case True\n    hence \"euclid_ext_aux r' r s' s t' t = \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_eucl a b\" by (simp add: gcd_eucl_0)\n    qed\n    finally show ?thesis .\n  next\n    case False\n    hence \"euclid_ext_aux r' r s' s t' t = \n             euclid_ext_aux r (r' mod r) s (s' - r' div r * s) t (t' - r' div r * t)\"\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: gcd_eucl_non_0 algebra_simps minus_mod_eq_div_mult [symmetric])\n    finally show ?thesis .\n  qed\nqed\n\ndefinition euclid_ext where\n  \"euclid_ext a b = euclid_ext_aux a b 1 0 0 1\"\n\nlemma euclid_ext_0: \n  \"euclid_ext a 0 = (1 div unit_factor a, 0, normalize a)\"\n  by (simp add: euclid_ext_def euclid_ext_aux.simps)\n\nlemma euclid_ext_left_0: \n  \"euclid_ext 0 a = (0, 1 div unit_factor a, normalize a)\"\n  by (simp add: euclid_ext_def euclid_ext_aux.simps)\n\nlemma euclid_ext_correct':\n  \"case euclid_ext a b of (x,y,c) \\<Rightarrow> x * a + y * b = c \\<and> c = gcd_eucl a b\"\n  unfolding euclid_ext_def by (rule euclid_ext_aux_correct) simp_all\n\nlemma euclid_ext_gcd_eucl:\n  \"(case euclid_ext a b of (x,y,c) \\<Rightarrow> c) = gcd_eucl a b\"\n  using euclid_ext_correct'[of a b] by (simp add: case_prod_unfold)\n\ndefinition euclid_ext' where\n  \"euclid_ext' a b = (case euclid_ext a b of (x, y, _) \\<Rightarrow> (x, y))\"\n\nlemma euclid_ext'_correct':\n  \"case euclid_ext' a b of (x,y) \\<Rightarrow> x * a + y * b = gcd_eucl a b\"\n  using euclid_ext_correct'[of a b] by (simp add: case_prod_unfold euclid_ext'_def)\n\nlemma euclid_ext'_0: \"euclid_ext' a 0 = (1 div unit_factor a, 0)\" \n  by (simp add: euclid_ext'_def euclid_ext_0)\n\nlemma euclid_ext'_left_0: \"euclid_ext' 0 a = (0, 1 div unit_factor a)\" \n  by (simp add: euclid_ext'_def euclid_ext_left_0)\n\nend\n\nclass euclidean_semiring_gcd = euclidean_semiring + gcd + Gcd +\n  assumes gcd_gcd_eucl: \"gcd = gcd_eucl\" and lcm_lcm_eucl: \"lcm = lcm_eucl\"\n  assumes Gcd_Gcd_eucl: \"Gcd = Gcd_eucl\" and Lcm_Lcm_eucl: \"Lcm = Lcm_eucl\"\nbegin\n\nsubclass semiring_gcd\n  by standard (simp_all add: gcd_gcd_eucl gcd_eucl_greatest lcm_lcm_eucl lcm_eucl_def)\n\nsubclass semiring_Gcd\n  by standard (auto simp: Gcd_Gcd_eucl Lcm_Lcm_eucl Gcd_eucl_def intro: Lcm_eucl_least)\n\nsubclass factorial_semiring_gcd\nproof\n  fix a b\n  show \"gcd a b = gcd_factorial a b\"\n    by (rule sym, rule gcdI) (rule gcd_lcm_factorial; assumption)+\n  thus \"lcm a b = lcm_factorial a b\"\n    by (simp add: lcm_factorial_gcd_factorial lcm_gcd)\nnext\n  fix A \n  show \"Gcd A = Gcd_factorial A\"\n    by (rule sym, rule GcdI) (rule gcd_lcm_factorial; assumption)+\n  show \"Lcm A = Lcm_factorial A\"\n    by (rule sym, rule LcmI) (rule gcd_lcm_factorial; assumption)+\nqed\n\nlemma gcd_non_0:\n  \"b \\<noteq> 0 \\<Longrightarrow> gcd a b = gcd b (a mod b)\"\n  unfolding gcd_gcd_eucl by (fact gcd_eucl_non_0)\n\nlemmas gcd_0 = gcd_0_right\nlemmas dvd_gcd_iff = gcd_greatest_iff\nlemmas gcd_greatest_iff = dvd_gcd_iff\n\nlemma gcd_mod1 [simp]:\n  \"gcd (a mod b) b = gcd a b\"\n  by (rule gcdI, metis dvd_mod_iff gcd_dvd1 gcd_dvd2, simp_all add: gcd_greatest dvd_mod_iff)\n\nlemma gcd_mod2 [simp]:\n  \"gcd a (b mod a) = gcd a b\"\n  by (rule gcdI, simp, metis dvd_mod_iff gcd_dvd1 gcd_dvd2, simp_all add: gcd_greatest dvd_mod_iff)\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   have \"gcd a b dvd a\" by (rule gcd_dvd1)\n   then obtain c where A: \"a = gcd a b * c\" unfolding dvd_def by blast\n   with \\<open>a \\<noteq> 0\\<close> show ?thesis by (subst (2) A, intro size_mult_mono) auto\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\nlemma Lcm_eucl_set [code]:\n  \"Lcm_eucl (set xs) = foldl lcm_eucl 1 xs\"\n  by (simp add: Lcm_Lcm_eucl [symmetric] lcm_lcm_eucl Lcm_set)\n\nlemma Gcd_eucl_set [code]:\n  \"Gcd_eucl (set xs) = foldl gcd_eucl 0 xs\"\n  by (simp add: Gcd_Gcd_eucl [symmetric] gcd_gcd_eucl Gcd_set)\n\nend\n\n\ntext \\<open>\n  A Euclidean ring is a Euclidean semiring with additive inverses. It provides a \n  few more lemmas; in particular, Bezout's lemma holds for any Euclidean ring.\n\\<close>\n\nclass euclidean_ring_gcd = euclidean_semiring_gcd + idom\nbegin\n\nsubclass euclidean_ring ..\nsubclass ring_gcd ..\nsubclass factorial_ring_gcd ..\n\nlemma euclid_ext_gcd [simp]:\n  \"(case euclid_ext a b of (_, _ , t) \\<Rightarrow> t) = gcd a b\"\n  using euclid_ext_correct'[of a b] by (simp add: case_prod_unfold Let_def gcd_gcd_eucl)\n\nlemma euclid_ext_gcd' [simp]:\n  \"euclid_ext a b = (r, s, t) \\<Longrightarrow> t = gcd a b\"\n  by (insert euclid_ext_gcd[of a b], drule (1) subst, simp)\n\nlemma euclid_ext_correct:\n  \"case euclid_ext a b of (x,y,c) \\<Rightarrow> x * a + y * b = c \\<and> c = gcd a b\"\n  using euclid_ext_correct'[of a b]\n  by (simp add: gcd_gcd_eucl case_prod_unfold)\n  \nlemma euclid_ext'_correct:\n  \"fst (euclid_ext' a b) * a + snd (euclid_ext' a b) * b = gcd a b\"\n  using euclid_ext_correct'[of a b]\n  by (simp add: gcd_gcd_eucl case_prod_unfold euclid_ext'_def)\n\nlemma bezout: \"\\<exists>s t. s * a + t * b = gcd a b\"\n  using euclid_ext'_correct by blast\n\nend\n\n\nsubsection \\<open>Typical instances\\<close>\n\ninstantiation nat :: euclidean_semiring\nbegin\n\ndefinition [simp]:\n  \"euclidean_size_nat = (id :: nat \\<Rightarrow> nat)\"\n\ninstance by standard simp_all\n\nend\n\n\ninstantiation int :: euclidean_ring\nbegin\n\ndefinition [simp]:\n  \"euclidean_size_int = (nat \\<circ> abs :: int \\<Rightarrow> nat)\"\n\ninstance by standard (auto simp add: abs_mult nat_mult_distrib split: abs_split)\n\nend\n\ninstance nat :: euclidean_semiring_gcd\nproof\n  show [simp]: \"gcd = (gcd_eucl :: nat \\<Rightarrow> _)\" \"Lcm = (Lcm_eucl :: nat set \\<Rightarrow> _)\"\n    by (simp_all add: eq_gcd_euclI eq_Lcm_euclI)\n  show \"lcm = (lcm_eucl :: nat \\<Rightarrow> _)\" \"Gcd = (Gcd_eucl :: nat set \\<Rightarrow> _)\"\n    by (intro ext, simp add: lcm_eucl_def lcm_nat_def Gcd_nat_def Gcd_eucl_def)+\nqed\n\ninstance int :: euclidean_ring_gcd\nproof\n  show [simp]: \"gcd = (gcd_eucl :: int \\<Rightarrow> _)\" \"Lcm = (Lcm_eucl :: int set \\<Rightarrow> _)\"\n    by (simp_all add: eq_gcd_euclI eq_Lcm_euclI)\n  show \"lcm = (lcm_eucl :: int \\<Rightarrow> _)\" \"Gcd = (Gcd_eucl :: int set \\<Rightarrow> _)\"\n    by (intro ext, simp add: lcm_eucl_def lcm_altdef_int \n          semiring_Gcd_class.Gcd_Lcm Gcd_eucl_def abs_mult)+\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/Euclidean_Algorithm.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.877476793890012, "lm_q2_score": 0.8519528038477824, "lm_q1q2_score": 0.7475688148659584}}
{"text": "(* author: R. Thiemann *)\n\nsection \\<open>Sunflowers\\<close>\n\ntext \\<open>Sunflowers are sets of sets, such that whenever an element\n  is contained in at least two of the sets, \n  then it is contained in all of the sets.\\<close>\n\ntheory Sunflower\n  imports Main\n    \"HOL-Library.FuncSet\"\nbegin\n\ndefinition sunflower :: \"'a set set \\<Rightarrow> bool\" where\n  \"sunflower S = (\\<forall> x. (\\<exists> A B. A \\<in> S \\<and> B \\<in> S \\<and> A \\<noteq> B \\<and> \n     x \\<in> A \\<and> x \\<in> B)\n    \\<longrightarrow> (\\<forall> A. A \\<in> S \\<longrightarrow> x \\<in> A))\" \n\nlemma sunflower_subset: \"F \\<subseteq> G \\<Longrightarrow> sunflower G \\<Longrightarrow> sunflower F\" \n  unfolding sunflower_def by blast\n\nlemma pairwise_disjnt_imp_sunflower: \n  \"pairwise disjnt F \\<Longrightarrow> sunflower F\" \n  unfolding sunflower_def \n  by (metis disjnt_insert1 mk_disjoint_insert pairwiseD)\n\nlemma card2_sunflower: assumes \"finite S\" and \"card S \\<le> 2\" \n  shows \"sunflower S\" \nproof -\n  from assms have \"card S = 0 \\<or> card S = Suc 0 \\<or> card S = 2\" by linarith\n  with \\<open>finite S\\<close> obtain A B where \"S = {} \\<or> S = {A} \\<or> S = {A,B}\" \n    using card_2_iff[of S] card_1_singleton_iff[of S] by auto\n  thus ?thesis unfolding sunflower_def by auto\nqed\n\nlemma empty_sunflower: \"sunflower {}\" \n  by (rule card2_sunflower, auto)\n\nlemma singleton_sunflower: \"sunflower {A}\" \n  by (rule card2_sunflower, auto)\n\nlemma doubleton_sunflower: \"sunflower {A,B}\" \n  by (rule card2_sunflower, auto, cases \"A = B\", auto)\n\nlemma sunflower_imp_union_intersect_unique: \n  assumes \"sunflower S\"\n    and \"x \\<in> (\\<Union> S) - (\\<Inter> S)\" \n  shows \"\\<exists>! A. A \\<in> S \\<and> x \\<in> A\"\nproof -\n  from assms obtain A where A: \"A \\<in> S\" \"x \\<in> A\" by auto\n  show ?thesis\n  proof\n    show \"A \\<in> S \\<and> x \\<in> A\" using A by auto\n    fix B \n    assume B: \"B \\<in> S \\<and> x \\<in> B\" \n    show \"B = A\" \n    proof (rule ccontr)\n      assume \"B \\<noteq> A\" \n      with A B have \"\\<exists>A B. A \\<in> S \\<and> B \\<in> S \\<and> A \\<noteq> B \\<and> x \\<in> A \\<and> x \\<in> B\" by auto\n      from \\<open>sunflower S\\<close>[unfolded sunflower_def, rule_format, OF this]\n      have \"x \\<in> \\<Inter> S\" by auto\n      with assms show False by auto\n    qed\n  qed\nqed\n\nlemma union_intersect_unique_imp_sunflower: \n  assumes \"\\<And> x. x \\<in> (\\<Union> S) - (\\<Inter> S) \\<Longrightarrow> \\<exists>\\<^sub>\\<le>\\<^sub>1 A. A \\<in> S \\<and> x \\<in> A\" \n  shows \"sunflower S\"\n  unfolding sunflower_def\nproof (intro allI impI, elim exE conjE, goal_cases)\n  case (1 x C A B)\n  hence x: \"x \\<in> \\<Union> S\" by auto\n  show ?case\n  proof (cases \"x \\<in> \\<Inter> S\")\n    case False\n    with assms[of x] x have \"\\<exists>\\<^sub>\\<le>\\<^sub>1 A. A \\<in> S \\<and> x \\<in> A\" by blast\n    with 1 have False unfolding Uniq_def by blast\n    thus ?thesis ..\n  next\n    case True\n    with 1 show ?thesis by blast\n  qed\nqed\n\nlemma sunflower_iff_union_intersect_unique: \n  \"sunflower S \\<longleftrightarrow> (\\<forall> x \\<in> \\<Union> S - \\<Inter> S. \\<exists>! A. A \\<in> S \\<and> x \\<in> A)\" \n  (is \"?l = ?r\")\nproof \n  assume ?l\n  from sunflower_imp_union_intersect_unique[OF this]\n  show ?r by auto\nnext\n  assume ?r\n  hence *: \"\\<forall>x\\<in>\\<Union> S - \\<Inter> S. \\<exists>\\<^sub>\\<le>\\<^sub>1 A. A \\<in> S \\<and> x \\<in> A\" \n    unfolding ex1_iff_ex_Uniq by auto\n  show ?l\n    by (rule union_intersect_unique_imp_sunflower, insert *, auto)\nqed\n\nlemma sunflower_iff_intersect_Uniq: \n  \"sunflower S \\<longleftrightarrow> (\\<forall> x.  x \\<in> \\<Inter> S \\<or> (\\<exists>\\<^sub>\\<le>\\<^sub>1 A. A \\<in> S \\<and> x \\<in> A))\" \n  (is \"?l = ?r\")\nproof \n  assume ?l\n  from sunflower_imp_union_intersect_unique[OF this]\n  show ?r unfolding ex1_iff_ex_Uniq\n    by (metis (no_types, lifting) DiffI UnionI Uniq_I)\nnext\n  assume ?r\n  show ?l\n    by (rule union_intersect_unique_imp_sunflower, insert \\<open>?r\\<close>, auto)\nqed\n\ntext \\<open>If there exists sunflowers whenever all elements are sets of \n  the same cardinality @{term r}, then there also exists sunflowers \n  whenever all elements are sets with cardinality at most @{term r}.\\<close>\n\nlemma sunflower_card_subset_lift: fixes F :: \"'a set set\" \n  assumes sunflower: \"\\<And> G :: ('a + nat) set set. \n     (\\<forall> A \\<in> G. finite A \\<and> card A = k) \\<Longrightarrow> card G > c \n        \\<Longrightarrow> \\<exists> S. S \\<subseteq> G \\<and> sunflower S \\<and> card S = r\" \n    and kF: \"\\<forall> A \\<in> F. finite A \\<and> card A \\<le> k\"\n    and cardF: \"card F > c\"\n  shows \"\\<exists> S. S \\<subseteq> F \\<and> sunflower S \\<and> card S = r\" \nproof -\n  let ?n = \"Suc c\" \n  from cardF have \"card F \\<ge> ?n\" by auto\n  then obtain FF where sub: \"FF \\<subseteq> F\" and cardF: \"card FF = ?n\" \n    by (rule obtain_subset_with_card_n)\n  let ?N = \"{0 ..< ?n}\" \n  from cardF have \"finite FF\" \n    by (simp add: card_ge_0_finite)\n  from ex_bij_betw_nat_finite[OF this, unfolded cardF]\n  obtain f where f: \"bij_betw f ?N FF\" by auto\n  hence injf: \"inj_on f ?N\" by (rule bij_betw_imp_inj_on)\n  have Ff: \"FF = f ` ?N\"\n    by (metis bij_betw_imp_surj_on f)\n  define g where \"g = (\\<lambda> i. (Inl ` f i) \\<union> (Inr ` {0 ..< (k - card (f i))}))\" \n  have injg: \"inj_on g ?N\" unfolding g_def using f\n  proof (intro inj_onI, goal_cases)\n    case (1 x y)\n    hence \"f x = f y\" by auto\n    with injf 1 show \"x = y\" \n      by (meson inj_onD)\n  qed\n  hence cardgN: \"card (g ` ?N) > c\" \n    by (simp add: card_image)\n  {\n    fix i\n    assume \"i \\<in> ?N\" \n    hence \"f i \\<in> FF\" unfolding Ff by auto\n    with sub have \"f i \\<in> F\" by auto\n    hence \"card (f i) \\<le> k\" \"finite (f i)\" using kF by auto\n    hence \"card (g i) = k \\<and> finite (g i)\" unfolding g_def\n      by (subst card_Un_disjoint, auto, subst (1 2) card_image, auto intro: inj_onI)\n  }\n  hence \"\\<forall> A \\<in> g ` ?N. finite A \\<and> card A = k\" by auto\n  from sunflower[OF this cardgN]\n  obtain S where SgN: \"S \\<subseteq> g ` ?N\" and sf: \"sunflower S\" and card: \"card S = r\" by auto\n  from SgN obtain N where NN: \"N \\<subseteq> ?N\" and SgN: \"S = g ` N\"\n    by (meson subset_image_iff)\n  from injg NN have inj_g: \"inj_on g N\"\n    by (rule inj_on_subset)\n  from injf NN have inj_f: \"inj_on f N\"\n    by (rule inj_on_subset)\n  from card_image[OF inj_g] SgN card\n  have cardN: \"card N = r\" by auto\n  let ?S = \"f ` N\" \n  show ?thesis\n  proof (intro exI[of _ ?S] conjI)\n    from NN show \"?S \\<subseteq> F\" using Ff sub by auto\n    from card_image[OF inj_f] cardN show \"card ?S = r\" by auto\n    show \"sunflower ?S\" unfolding sunflower_def\n    proof (intro allI impI, elim exE conjE, goal_cases)\n      case (1 x C A B)\n      from \\<open>A \\<in> f ` N\\<close> obtain i where i: \"i \\<in> N\" and A: \"A = f i\" by auto\n      from \\<open>B \\<in> f ` N\\<close> obtain j where j: \"j \\<in> N\" and B: \"B = f j\" by auto\n      from \\<open>C \\<in> f ` N\\<close> obtain k where k: \"k \\<in> N\" and C: \"C = f k\" by auto\n      hence gk: \"g k \\<in> g ` N\" by auto\n      from \\<open>A \\<noteq> B\\<close> A B have ij: \"i \\<noteq> j\" by auto\n      from inj_g ij i j have gij: \"g i \\<noteq> g j\" by (metis inj_on_contraD)\n      from \\<open>x \\<in> A\\<close> have memi: \"Inl x \\<in> g i\" unfolding A g_def by auto\n      from \\<open>x \\<in> B\\<close> have memj: \"Inl x \\<in> g j\" unfolding B g_def by auto\n      have \"\\<exists>A B. A \\<in> g ` N \\<and> B \\<in> g ` N \\<and> A \\<noteq> B \\<and> Inl x \\<in> A \\<and> Inl x \\<in> B\" \n        using memi memj gij i j by auto\n      from sf[unfolded sunflower_def SgN, rule_format, OF this gk] have \"Inl x \\<in> g k\" .\n      thus \"x \\<in> C\" unfolding C g_def by auto\n    qed\n  qed\nqed\n\ntext \\<open>We provide another sunflower lifting lemma that ensures \n  non-empty cores. Here, all elements must be taken \n  from a finite set, and the bound is multiplied the cardinality.\\<close>\n\nlemma sunflower_card_core_lift: \n  assumes finE: \"finite (E :: 'a set)\" \n    and sunflower: \"\\<And> G :: 'a set set. \n     (\\<forall> A \\<in> G. finite A \\<and> card A \\<le> k) \\<Longrightarrow> card G > c \n        \\<Longrightarrow> \\<exists> S. S \\<subseteq> G \\<and> sunflower S \\<and> card S = r\" \n    and F: \"\\<forall> A \\<in> F. A \\<subseteq> E \\<and> s \\<le> card A \\<and> card A \\<le> k\" \n    and cardF: \"card F > (card E choose s) * c\"\n    and s: \"s \\<noteq> 0\"\n    and r: \"r \\<noteq> 0\" \n  shows \"\\<exists> S. S \\<subseteq> F \\<and> sunflower S \\<and> card S = r \\<and> card (\\<Inter> S) \\<ge> s\"\nproof -\n  let ?g = \"\\<lambda> (A :: 'a set) x. card x = s \\<and> x \\<subseteq> A\" \n  let ?E = \"{X. X \\<subseteq> E \\<and> card X = s}\"\n  from cardF have finF: \"finite F\"\n    by (metis card.infinite le_0_eq less_le)\n  from cardF have FnE: \"F \\<noteq> {}\" by force\n  {\n    from FnE obtain B where B: \"B \\<in> F\" by auto\n    with F[rule_format, OF B] obtain A where \"A \\<subseteq> E\" \"card A = s\"\n      by (meson obtain_subset_with_card_n order_trans)\n    hence \"?E \\<noteq> {}\" using B by auto\n  } note EnE = this\n  define f where \"f = (\\<lambda> A. SOME x. ?g A x)\" \n  from finE have finiteE: \"finite ?E\" by simp\n  \n  have \"f \\<in> F \\<rightarrow> ?E\"\n  proof\n    fix B\n    assume B: \"B \\<in> F\" \n    with F[rule_format, OF B] have \"\\<exists> x. ?g B x\" by (meson obtain_subset_with_card_n)\n    from someI_ex[OF this] B F show \"f B \\<in> ?E\" unfolding f_def by auto\n  qed\n  from pigeonhole_card[OF this finF finiteE EnE]\n  obtain a where a: \"a \\<in> ?E\" \n    and le: \"card F \\<le> card (f -` {a} \\<inter> F) * card ?E\" by auto\n  have precond: \"\\<forall>A\\<in>f -` {a} \\<inter> F. finite A \\<and> card A \\<le> k\" \n    using F finite_subset[OF _ finE] by auto\n  have \"c * (card E choose s) = (card E choose s) * c\" by simp\n  also have \"\\<dots> < card F\" by fact\n  also have \"\\<dots> \\<le> (card (f -` {a} \\<inter> F)) * card ?E\" by fact\n  also have \"card ?E = card E choose s\" by (rule n_subsets[OF finE])\n  finally have \"c < card (f -` {a} \\<inter> F)\" by auto\n  from sunflower[OF precond this]\n  obtain S where *: \"S \\<subseteq> f -` {a} \\<inter> F\" \"sunflower S\" \"card S = r\"\n    by auto\n  from finite_subset[OF _ finF, of S] \n  have finS: \"finite S\" using * by auto\n  from * r have SnE: \"S \\<noteq> {}\" by auto\n  have finIS: \"finite (\\<Inter> S)\" \n  proof (rule finite_Inter)\n    from SnE obtain A where A: \"A \\<in> S\" by auto\n    with F s have \"finite A\"\n      using * precond by blast\n    thus \"\\<exists>A\\<in>S. finite A\" using A by auto\n  qed\n  show ?thesis\n  proof (intro exI[of _ S] conjI *)\n    show \"S \\<subseteq> F\" using * by auto\n    {\n      fix A\n      assume \"A \\<in> S\" \n      with *(1) have \"A \\<in> f -` {a}\" and A: \"A \\<in> F\" using * by auto\n      from this have **: \"f A = a\" \"A \\<in> F\" by auto\n      from F[rule_format, OF A] have \"\\<exists>x. card x = s \\<and> x \\<subseteq> A\" \n        by (meson obtain_subset_with_card_n order_trans)\n      from someI_ex[of \"?g A\", OF this] **\n      have \"a \\<subseteq> A\" unfolding f_def by auto\n    }\n    hence \"a \\<subseteq> \\<Inter> S\" by auto\n    from card_mono[OF finIS this] \n    have \"card a \\<le> card (\\<Inter> S)\" .\n    with a show \"s \\<le> card (\\<Inter> S)\" by auto\n  qed\nqed\n\nlemma sunflower_nonempty_core_lift: \n  assumes finE: \"finite (E :: 'a set)\" \n    and sunflower: \"\\<And> G :: 'a set set. \n     (\\<forall> A \\<in> G. finite A \\<and> card A \\<le> k) \\<Longrightarrow> card G > c \n        \\<Longrightarrow> \\<exists> S. S \\<subseteq> G \\<and> sunflower S \\<and> card S = r\" \n    and F: \"\\<forall> A \\<in> F. A \\<subseteq> E \\<and> card A \\<le> k\" \n    and empty: \"{} \\<notin> F\" \n    and cardF: \"card F > card E * c\"\n  shows \"\\<exists> S. S \\<subseteq> F \\<and> sunflower S \\<and> card S = r \\<and> (\\<Inter> S) \\<noteq> {}\"\nproof (cases \"r = 0\")\n  case False\n  from F empty have F': \"\\<forall>A\\<in>F. A \\<subseteq> E \\<and> 1 \\<le> card A \\<and> card A \\<le> k \" using finE\n    by (metis One_nat_def Suc_leI card_gt_0_iff finite_subset)\n  from cardF have cardF': \"(card E choose 1) * c < card F\" by auto\n  from sunflower_card_core_lift[OF finE sunflower, of k c F 1, OF _ _ F' cardF' _ False]\n  obtain S where \"S \\<subseteq> F\" and main: \"sunflower S\" \"card S = r\" \"1 \\<le> card (\\<Inter> S)\" by auto\n  thus ?thesis by (intro exI[of _ S], auto)\nnext\n  case True\n  thus ?thesis by (intro exI[of _ \"{}\"], auto simp: empty_sunflower)\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/Sunflowers/Sunflower.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527944504228, "lm_q2_score": 0.8774767794716264, "lm_q1q2_score": 0.7475687943362095}}
{"text": "theory Exercise5p4\nimports Main\nbegin\n\ninductive ev :: \"nat \\<Rightarrow> bool\" where\n    ev0:  \"ev 0\" \n  | evSS: \"ev n \\<Longrightarrow> ev (Suc (Suc n))\"\n\n\n(* Exercise 5.4 *)  \nlemma \"\\<not> ev (Suc (Suc (Suc 0)))\" (is \"\\<not>?P\")\nproof\n  assume \"?P\" \n  then have \"ev (Suc 0)\" by cases (* This is the same as \"proof cases qed\" because\n                                     there is nothing to prove *)\n  then show False by cases\nqed  \n\n\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/Exercise5p4.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9334308073258009, "lm_q2_score": 0.8006919997179627, "lm_q1q2_score": 0.7473905797160478}}
{"text": "(*  Title:       Roots of real quadratics\n    Author:      Tim Makarios <tjm1983 at gmail.com>, 2012\n    Maintainer:  Tim Makarios <tjm1983 at gmail.com>\n*)\n\n(* After Isabelle 2012, this may be moved to ~~/src/HOL/Library *)\n\nheader \"Roots of real quadratics\"\n\ntheory Quadratic_Discriminant\nimports Complex_Main\nbegin\n\ndefinition discrim :: \"[real,real,real] \\<Rightarrow> real\" where\n  \"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 `a \\<noteq> 0`\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  thus \"a * x\\<^sup>2 + b * x + c = 0 \\<longleftrightarrow> (2 * a * x + b)\\<^sup>2 = discrim a b c\"\n    unfolding discrim_def\n    by (simp add: 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\" by simp\n  with `discrim a b c < 0` have \"(2 * a * x + b)\\<^sup>2 \\<noteq> discrim a b c\" by arith\n  with complete_square and `a \\<noteq> 0` show \"a * x\\<^sup>2 + b * x + c \\<noteq> 0\" 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  hence \"sqrt (x\\<^sup>2) = sqrt y\" by simp\n  hence \"sqrt y = \\<bar>x\\<bar>\" by simp\n  thus \"x = sqrt y \\<or> x = - sqrt y\" by auto\nnext\n  assume \"x = sqrt y \\<or> x = - sqrt y\"\n  hence \"x\\<^sup>2 = (sqrt y)\\<^sup>2 \\<or> x\\<^sup>2 = (- sqrt y)\\<^sup>2\" by auto\n  with `y \\<ge> 0` show \"x\\<^sup>2 = y\" 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  assume \"x * y = z\"\n  with `x \\<noteq> 0` show \"y = z / x\" by (simp add: field_simps)\nnext\n  assume \"y = z / x\"\n  with `x \\<noteq> 0` show \"x * y = z\" 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 `a \\<noteq> 0` 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  using discriminant_nonneg and assms\n  by simp\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 `a \\<noteq> 0` have \"\\<not>(discrim a b c < 0)\" by auto\n  hence \"discrim a b c \\<ge> 0\" by simp\n  with discriminant_nonneg and `a * x\\<^sup>2 + b * x + c = 0` and `a \\<noteq> 0`\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 `discrim a b c \\<ge> 0`\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  hence \"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 `a \\<noteq> 0` show \"a * x\\<^sup>2 + b * x + c = 0\" 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  using discriminant_nonneg and assms\n  by auto\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 `discrim a b c > 0` have \"sqrt (discrim a b c) \\<noteq> 0\" by simp\n  hence \"sqrt (discrim a b c) \\<noteq> - sqrt (discrim a b c)\" by arith\n  with `a \\<noteq> 0` have \"?x \\<noteq> ?y\" by simp\n  moreover\n  from discriminant_nonneg [of a b c ?x]\n    and discriminant_nonneg [of a b c ?y]\n    and assms\n  have \"a * ?x\\<^sup>2 + b * ?x + c = 0\" and \"a * ?y\\<^sup>2 + b * ?y + c = 0\" by simp_all\n  ultimately\n  show \"\\<exists> x y. x \\<noteq> y \\<and> a * x\\<^sup>2 + b * x + c = 0 \\<and> a * y\\<^sup>2 + b * y + c = 0\" by blast\nqed\n\nlemma discriminant_pos_distinct:\n  fixes a b c x :: real\n  assumes \"a \\<noteq> 0\" 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 `a \\<noteq> 0` and `discrim a b c > 0`\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\n    assume \"x = w\"\n    with `w \\<noteq> z` have \"x \\<noteq> z\" by simp\n    with `a * z\\<^sup>2 + b * z + c = 0`\n    show \"\\<exists> y. x \\<noteq> y \\<and> a * y\\<^sup>2 + b * y + c = 0\" by auto\n  next\n    assume \"x \\<noteq> w\"\n    with `a * w\\<^sup>2 + b * w + c = 0`\n    show \"\\<exists> y. x \\<noteq> y \\<and> a * y\\<^sup>2 + b * y + c = 0\" by auto\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/Tarskis_Geometry/Quadratic_Discriminant.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213772699435, "lm_q2_score": 0.8311430478583168, "lm_q1q2_score": 0.7472984818987084}}
{"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 Binomial\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 Suc [symmetric])\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(* TODO Move *)\nlemma list_ext:\n  assumes \"length xs = length ys\"\n  assumes \"\\<And>i. i < length xs \\<Longrightarrow> xs ! i = ys ! i\"\n  shows \"xs = ys\"\n  using assms\nproof (induction rule: list_induct2)\n  case Nil\n  then show ?case by simp\nnext\n  case (Cons x xs y ys)\n  from Cons.prems[of 0] have \"x = y\"\n    by simp\n  moreover from Cons.prems[of \"Suc i\" for i] have \"xs = ys\"\n    by (intro Cons.IH) simp\n  ultimately show ?case by simp\nqed\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 = map (\\<lambda>(x,y). f x y) (zip (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 map_Suc_upt [symmetric] 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 list_ext, 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": "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/Stirling.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467643431002, "lm_q2_score": 0.8499711832583695, "lm_q1q2_score": 0.7472494155464718}}
{"text": "theory SetUtils\n  imports Main\nbegin\n\n\\<comment> \\<open>TODO use Inf instead of Min where necessary.\\<close>\n\n\\<comment> \\<open>TODO can be replaced by @{term \"card_Un_disjoint (\\<lbrakk>finite A; finite B; A \\<inter> B = {}\\<rbrakk> \n  \\<Longrightarrow> card (A \\<union> B) = card A + card B)\"} ?\\<close>\nlemma card_union': \"(finite s) \\<and> (finite t) \\<and> (disjnt s t) \\<Longrightarrow> (card (s \\<union> t) = card s + card t)\"\n  by (simp add: card_Un_disjoint disjnt_def)\n\nlemma CARD_INJ_IMAGE_2: \n  fixes f s\n  assumes \"finite s\" \"(\\<forall>x y. ((x \\<in> s) \\<and> (y \\<in> s)) \\<longrightarrow> ((f x = f y) \\<longleftrightarrow> (x = y)))\"\n  shows \"(card (f ` s) = card s)\"\nproof -\n  {\n    fix x y\n    assume \"x \\<in> s\" \"y \\<in> s\" \n    then have \"f x = f y \\<longrightarrow> x = y\"\n      using assms(2)\n      by blast\n  }\n  then have \"inj_on f s\"\n    by (simp add: inj_onI)\n  then show ?thesis\n    using assms(1) inj_on_iff_eq_card\n    by blast\nqed\n\nlemma scc_main_lemma_x: \"\\<And>s t x. (x \\<in> s) \\<and> \\<not>(x \\<in> t) \\<Longrightarrow> \\<not>(s = t)\"\n  by blast\n\nlemma neq_funs_neq_images:\n  fixes s \n  assumes \"\\<forall>x. x \\<in> s \\<longrightarrow> (\\<forall>y. y \\<in> s \\<longrightarrow> f1 x \\<noteq> f2 y)\" \"\\<exists>x. x \\<in> s\" \n  shows \"f1 ` s \\<noteq> f2 ` s\"\n  using assms \n  by blast \n\nsubsection \"Sets of Numbers\"\n\n\\<comment> \\<open>TODO \n  Is '<=' natural number lte or overloaded? \n  If it's overloaded for reals, this might be wrong (e.g. the real set s = [0; 1] is not finite even \nthough @{term \"\\<forall> x \\<in> s. x \\<le> 1\"} holds).\\<close>\nlemma mems_le_finite_i: \n  fixes s :: \"nat set\" and k :: nat\n  shows \"(\\<forall> x. x \\<in> s \\<longrightarrow> x \\<le> k) \\<Longrightarrow> finite s\"\nproof -\n  assume P: \"(\\<forall> x. x \\<in> s \\<longrightarrow> x \\<le> k)\"\n  let ?f = \"id :: nat \\<Rightarrow> nat\"\n  let ?S = \"{i. i \\<le> k}\"\n  have \"s \\<subseteq> ?S\" using P by blast\n  moreover have \"?f ` ?S = ?S\" by auto\n  moreover have \"finite ?S\" using nat_seg_image_imp_finite by auto\n  moreover have \"finite s\" using calculation finite_subset by auto\n  ultimately show ?thesis by auto\nqed\nlemma mems_le_finite: \n  fixes s :: \"nat set\" and k :: nat\n  shows \"\\<And>(s :: nat set) k. (\\<forall> x. x \\<in> s \\<longrightarrow> x \\<le> k) \\<Longrightarrow> finite s\"  \n  using mems_le_finite_i by auto\n\n\\<comment> \\<open>NOTE translated `s` to `nat set` (more generality wasn't required.).\\<close> \nlemma mem_le_imp_MIN_le: \n  fixes s :: \"nat set\" and k :: nat \n  assumes \"\\<exists>x. (x \\<in> s) \\<and> (x \\<le> k)\" \n  shows \"(Inf s \\<le> k)\" \nproof -\n  from assms obtain x where 1: \"x \\<in> s\" \"x \\<le> k\"\n    by blast\n  {\n    assume C: \"Inf s > k\"\n    then have \"Inf s > x\" using 1(2)\n      by fastforce\n    then have False \n      using 1(1) cInf_lower leD\n      by fast\n  }\n  then show ?thesis\n    by fastforce\nqed\n\n\\<comment> \\<open>NOTE \n  nat --> bool is the type of a HOL4 set and was translated to 'nat set'.\\<close>\n\\<comment> \\<open>NOTE \n  We cannot use 'Min' instead of 'Inf' because there is no indication that '{n. s n}' will be\nfinite. Without that @{term \"Min {n. s n} \\<in> {n. s n}\"} is not necessarily true.\\<close>\nlemma mem_lt_imp_MIN_lt: \n  fixes s :: \"nat set\" and k :: nat\n  assumes \"(\\<exists>x. x \\<in> s \\<and> x < k)\"\n  shows \"(Inf s) < k\" \nproof -\n  obtain x where 1: \"x \\<in> s\" \"x < k\"\n    using assms\n    by blast\n  then have 2: \"s \\<noteq> {}\" \n    by blast\n  then have \"Inf s \\<in> s\" \n    using Inf_nat_def LeastI\n    by force\n  moreover have \"\\<forall>x\\<in>s. Inf s \\<le> x\"\n    by (simp add: cInf_lower)\n  ultimately show \"(Inf s) < k\"\n    using assms leD \n    by force\nqed\n\n\\<comment> \\<open>NOTE type for 'k' had to be fixed (type unordered error; also not true for e.g. real sets).\\<close>\nlemma bound_child_parent_neq_mems_state_set_neq_len: \n  fixes s and k :: nat\n  assumes \"(\\<forall>x. x \\<in> s \\<longrightarrow> x < k)\"\n  shows \"finite s\"\n  using assms bounded_nat_set_is_finite \n  by blast \n\nlemma bound_main_lemma_2: \"\\<And>(s :: nat set) k. (s \\<noteq> {}) \\<and> (\\<forall>x. x \\<in> s \\<longrightarrow> x \\<le> k) \\<Longrightarrow> Sup s \\<le> k\"\nproof -\n  fix s :: \"nat set\" and k\n  {\n    assume P1: \"s \\<noteq> {}\"\n    assume P2: \"(\\<forall>x. x \\<in> s \\<longrightarrow> x \\<le> k)\"\n    have \"finite s\" using P2 mems_le_finite by auto\n    moreover have \"Max s \\<in> s\" using P1 calculation Max_in by auto\n    moreover have \"Max s \\<le> k\" using P2 calculation by auto \n  }\n  then show \"(s \\<noteq> {}) \\<and> (\\<forall>x. x \\<in> s \\<longrightarrow> x \\<le> k) \\<Longrightarrow> Sup s \\<le> k\"\n    by (simp add: Sup_nat_def)\nqed\n\n\\<comment> \\<open>NOTE type of 'k' fixed to nat to be able to use 'bound\\_child\\_parent\\_neq\\_mems\\_state\\_set\\_neq\\_len'.\\<close>\nlemma bound_child_parent_not_eq_last_diff_paths: \"\\<And>s (k :: nat).\n  (s \\<noteq> {}) \n  \\<Longrightarrow> (\\<forall>x. x \\<in> s \\<longrightarrow> x < k) \n  \\<Longrightarrow> Sup s < k\n\"\n  by (simp add: Sup_nat_def bound_child_parent_neq_mems_state_set_neq_len)\n\nlemma FINITE_ALL_DISTINCT_LISTS_i:\n  fixes P\n  assumes \"finite P\"\n  shows \"\n    {p. distinct p \\<and> set p \\<subseteq> P} \n    = {[]} \\<union> (\\<Union> ((\\<lambda>e. {e # p0 | p0. distinct p0 \\<and> set p0 \\<subseteq> (P - {e})}) ` P))\"\nproof -\n  let ?A=\"{p. distinct p \\<and> set p \\<subseteq> P }\"\n  let ?B=\"{[]} \\<union> (\\<Union> ((\\<lambda>e. {e # p0 | p0. distinct p0 \\<and> set p0 \\<subseteq> (P - {e})}) ` P))\"\n  {\n    {\n      fix a\n      assume P: \"a \\<in> ?A\"\n      then have \"a \\<in> ?B\" \n      proof (cases a)\n        text \\<open> The empty list is distinct and its corresponding set is the empty set which is a \n            trivial subset of `?B`. The `Nil` case can therefore be derived by automation. \\<close>\n        case (Cons h list)\n        {\n          let ?b'=\"h\"\n          {\n            from P have \"set a \\<subseteq> P\"\n              by simp\n            then have \"set list \\<subseteq> (P - {h})\"\n              using P dual_order.trans local.Cons \n              by auto\n          }\n          moreover from P Cons \n          have \"distinct list\"\n            by force\n          ultimately have \"a \\<in> ((\\<lambda>e. {e # p0 | p0. distinct p0 \\<and> set p0 \\<subseteq> (P - {e})}) ?b')\"\n            using Cons\n            by blast\n          moreover {\n            from P Cons have \"?b' \\<in> set a\"\n              by simp\n            moreover from P have \"set a \\<subseteq> P\"\n              by simp\n            ultimately have \"?b' \\<in> P\" \n              by auto\n          }\n          ultimately have \n            \"\\<exists>b' \\<in> P. a \\<in> ((\\<lambda>e. {e # p0 | p0. distinct p0 \\<and> set p0 \\<subseteq> (P - {e})}) b')\"\n            by meson \n        }\n        then obtain b' where\n          \"b' \\<in> P\" \"a \\<in> ((\\<lambda>e. {e # p0 | p0. distinct p0 \\<and> set p0 \\<subseteq> (P - {e})}) b')\"\n          by blast\n        then show ?thesis \n          by blast\n      qed blast\n    }\n    then have \"?A \\<subseteq> ?B\"\n      by auto\n  }\n  moreover {\n    {\n      fix b\n      assume P: \"b \\<in> ?B\"\n      have \"b \\<in> ?A\" \n        text \\<open> The empty list is in `?B` by construction. The `Nil` case can therefore be derived  \n          straightforwardly.\\<close>\n      proof (cases b)\n        case (Cons a list)\n        from P Cons obtain b' where a: \n          \"b' \\<in> P\" \"b \\<in> {b' # p0 | p0. distinct p0 \\<and> set p0 \\<subseteq> (P - {b'})}\"\n          by fast\n        then obtain p0 where b: \"b = b' # p0\" \"distinct p0\" \"set p0 \\<subseteq> (P - {b'})\"\n          by blast\n        then have \"distinct (b' # p0)\"\n          by (simp add: subset_Diff_insert)\n        moreover have \"set (b' # p0) \\<subseteq> P\"\n          using a(1) b(3)\n          by auto\n        ultimately show ?thesis \n          using b(1)\n          by fast\n      qed simp\n    }\n    then have \"?B \\<subseteq> ?A\"\n      by blast\n  }\n  ultimately show ?thesis\n    using set_eq_subset \n    by blast\nqed\n\nlemma FINITE_ALL_DISTINCT_LISTS:\n  fixes P\n  assumes \"finite P\"\n  shows \"finite {p. distinct p \\<and> set p \\<subseteq> P}\"\n  using assms \nproof (induction \"card P\" arbitrary: P)\n  case 0\n  then have \"P = {}\"\n    by force\n  then show ?case \n    using 0\n    by simp\nnext\n  case (Suc x)\n  {\n    text \\<open> Proof the finiteness of the union by proving both sets of the union are finite. The \n      singleton set `{[]}` is trivially finite. \\<close>\n    {\n      {\n        fix e\n        assume P: \"e \\<in> P\" \n        have \"\n          {e # p0 | p0. distinct p0 \\<and> set p0 \\<subseteq> P - {e}} \n          = (\\<lambda>p. e # p) ` { p. distinct p \\<and> set p \\<subseteq> P - {e}}\" \n          by blast\n        moreover {\n          let ?P'=\"P - {e}\"\n          from Suc.prems \n          have \"finite ?P'\"\n            by blast\n          text \\<open> The finiteness can now be shown using the induction hypothesis. However `e` might\n            already be contained in `?P`, so we have to split cases first. \\<close>\n          have \"finite ((\\<lambda>p. e # p) ` {p. distinct p \\<and> set p \\<subseteq> ?P'})\" \n          proof (cases \"e \\<in> P\")\n            case True\n            then have \"x = card ?P'\" using Suc.prems Suc(2) \n              by fastforce\n            moreover from Suc.prems \n            have \"finite ?P'\" \n              by blast\n            ultimately show ?thesis \n              using Suc(1) \n              by blast\n          next\n            case False\n            then have \"?P' = P\" \n              by simp\n            then have \"finite {p. distinct p \\<and> set p \\<subseteq> ?P'}\"\n              using False P by linarith \n            then show ?thesis\n              using finite_imageI\n              by blast\n          qed\n        }\n        ultimately have \"finite {e # p0 | p0. distinct p0 \\<and> set p0 \\<subseteq> (P - {e})}\"\n          by argo\n      }\n      then have \"finite (\\<Union> ((\\<lambda>e. {e # p0 | p0. distinct p0 \\<and> set p0 \\<subseteq> (P - {e})}) ` P))\"\n        using Suc.prems\n        by blast\n    }\n    then have \n      \"finite ({[]} \\<union> (\\<Union> ((\\<lambda>e. {e # p0 | p0. distinct p0 \\<and> set p0 \\<subseteq> (P - {e})}) ` P)))\" \n      using finite_Un\n      by blast    \n  }\n  then show ?case \n    using FINITE_ALL_DISTINCT_LISTS_i[OF Suc.prems]\n    by force\nqed\n\nlemma subset_inter_diff_empty: \n  assumes \"s \\<subseteq> t\" \n  shows \"(s \\<inter> (u - t) = {})\" \n  using assms\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/Factored_Transition_System_Bounding/SetUtils.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467643431002, "lm_q2_score": 0.8499711775577736, "lm_q1q2_score": 0.7472494105348114}}
{"text": "theory Chapter05_06\nimports Chapter04\nbegin\n\nprimrec is_val :: \"expr => bool\"\nwhere \"is_val (Var v) = False\"\n    | \"is_val (Num x) = True\"\n    | \"is_val (Str s) = True\"\n    | \"is_val (Plus e1 e2) = False\"\n    | \"is_val (Times e1 e2) = False\"\n    | \"is_val (Cat e1 e2) = False\"\n    | \"is_val (Len e) = False\"\n    | \"is_val (Let e1 e2) = False\"\n\ninductive eval :: \"expr => expr => bool\"\nwhere eval_plus_1 [simp]: \"eval (Plus (Num n1) (Num n2)) (Num (n1 + n2))\"\n    | eval_plus_2 [simp]: \"eval e1 e1' ==> eval (Plus e1 e2) (Plus e1' e2)\"\n    | eval_plus_3 [simp]: \"is_val e1 ==> eval e2 e2' ==> eval (Plus e1 e2) (Plus e1 e2')\"\n    | eval_times_1 [simp]: \"eval (Times (Num n1) (Num n2)) (Num (n1 * n2))\"\n    | eval_times_2 [simp]: \"eval e1 e1' ==> eval (Times e1 e2) (Times e1' e2)\"\n    | eval_times_3 [simp]: \"is_val e1 ==> eval e2 e2' ==> eval (Times e1 e2) (Times e1 e2')\"\n    | eval_cat_1 [simp]: \"eval (Cat (Str n1) (Str n2)) (Str (n1 @ n2))\"\n    | eval_cat_2 [simp]: \"eval e1 e1' ==> eval (Cat e1 e2) (Cat e1' e2)\"\n    | eval_cat_3 [simp]: \"is_val e1 ==> eval e2 e2' ==> eval (Cat e1 e2) (Cat e1 e2')\"\n    | eval_len_1 [simp]: \"eval (Len (Str n1)) (Num (int (length n1)))\"\n    | eval_len_2 [simp]: \"eval e1 e1' ==> eval (Len e1) (Len e1')\"\n    | eval_let_1 [simp]: \"is_val e1 ==> eval (Let e1 e2) (subst e1 first e2)\"\n    | eval_let_2 [simp]: \"eval e1 e1' ==> eval (Let e1 e2) (Let e1' e2)\"\n\nlemma canonical_num: \"is_val e ==> typecheck gam e NumType ==> EX n. e = Num n\"\nby (induction e, auto)\n\nlemma canonical_str: \"is_val e ==> typecheck gam e StrType ==> EX n. e = Str n\"\nby (induction e, auto)\n\ntheorem preservation: \"eval e e' ==> typecheck gam e t ==> typecheck gam e' t\"\nby (induction e e' arbitrary: t rule: eval.induct, fastforce+)\n\ntheorem progress: \"typecheck gam e t ==> gam = empty_env ==> is_val e | (EX e'. eval e e')\"\nproof (induction gam e t rule: typecheck.induct)\ncase tc_var\n  thus ?case by simp\nnext case tc_str\n  thus ?case by simp\nnext case tc_num\n  thus ?case by simp\nnext case (tc_plus gam e1 e2)\n  thus ?case by (metis eval_plus_1 eval_plus_2 eval_plus_3 canonical_num)\nnext case (tc_times gam e1 e2)\n  thus ?case by (metis eval_times_1 eval_times_2 eval_times_3 canonical_num)\nnext case (tc_cat gam e1 e2)\n  thus ?case by (metis eval_cat_1 eval_cat_2 eval_cat_3 canonical_str)\nnext case (tc_len gam e)\n  thus ?case by (metis eval_len_1 eval_len_2 canonical_str)\nnext case (tc_let gam e1 t1 e2 t2)\n  thus ?case by (metis eval_let_1 eval_let_2)\nqed\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/Chapter05_06.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218348550491, "lm_q2_score": 0.8104789018037399, "lm_q1q2_score": 0.7471981962622091}}
{"text": "(*  Title:      FOL/ex/Miniscope.thy\n    Author:     Lawrence C Paulson, Cambridge University Computer Laboratory\n    Copyright   1994  University of Cambridge\n\nClassical First-Order Logic.\nConversion to nnf/miniscope format: pushing quantifiers in.\nDemonstration of formula rewriting by proof.\n*)\n\ntheory Miniscope\nimports FOL\nbegin\n\n\nlemmas ccontr = FalseE [THEN classical]\n\nsubsection {* Negation Normal Form *}\n\nsubsubsection {* de Morgan laws *}\n\nlemma demorgans:\n  \"~(P&Q) <-> ~P | ~Q\"\n  \"~(P|Q) <-> ~P & ~Q\"\n  \"~~P <-> P\"\n  \"!!P. ~(ALL x. P(x)) <-> (EX x. ~P(x))\"\n  \"!!P. ~(EX x. P(x)) <-> (ALL x. ~P(x))\"\n  by blast+\n\n(*** Removal of --> and <-> (positive and negative occurrences) ***)\n(*Last one is important for computing a compact CNF*)\nlemma nnf_simps:\n  \"(P-->Q) <-> (~P | Q)\"\n  \"~(P-->Q) <-> (P & ~Q)\"\n  \"(P<->Q) <-> (~P | Q) & (~Q | P)\"\n  \"~(P<->Q) <-> (P | Q) & (~P | ~Q)\"\n  by blast+\n\n\n(* BEWARE: rewrite rules for <-> can confuse the simplifier!! *)\n\nsubsubsection {* Pushing in the existential quantifiers *}\n\nlemma ex_simps:\n  \"(EX x. P) <-> P\"\n  \"!!P Q. (EX x. P(x) & Q) <-> (EX x. P(x)) & Q\"\n  \"!!P Q. (EX x. P & Q(x)) <-> P & (EX x. Q(x))\"\n  \"!!P Q. (EX x. P(x) | Q(x)) <-> (EX x. P(x)) | (EX x. Q(x))\"\n  \"!!P Q. (EX x. P(x) | Q) <-> (EX x. P(x)) | Q\"\n  \"!!P Q. (EX x. P | Q(x)) <-> P | (EX x. Q(x))\"\n  by blast+\n\n\nsubsubsection {* Pushing in the universal quantifiers *}\n\nlemma all_simps:\n  \"(ALL x. P) <-> P\"\n  \"!!P Q. (ALL x. P(x) & Q(x)) <-> (ALL x. P(x)) & (ALL x. Q(x))\"\n  \"!!P Q. (ALL x. P(x) & Q) <-> (ALL x. P(x)) & Q\"\n  \"!!P Q. (ALL x. P & Q(x)) <-> P & (ALL x. Q(x))\"\n  \"!!P Q. (ALL x. P(x) | Q) <-> (ALL x. P(x)) | Q\"\n  \"!!P Q. (ALL x. P | Q(x)) <-> P | (ALL x. Q(x))\"\n  by blast+\n\nlemmas mini_simps = demorgans nnf_simps ex_simps all_simps\n\nML {*\nval mini_ss = simpset_of (@{context} addsimps @{thms mini_simps});\nfun mini_tac ctxt = resolve_tac @{thms ccontr} THEN' asm_full_simp_tac (put_simpset mini_ss ctxt);\n*}\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/Miniscope.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916134888614, "lm_q2_score": 0.8652240964782011, "lm_q1q2_score": 0.7470272286877563}}
{"text": "(*  Title:       Examples of hybrid systems verifications\n    Author:      Jonathan Juli\u00e1n Huerta y Munive, 2019\n    Maintainer:  Jonathan Juli\u00e1n Huerta y Munive <jjhuertaymunive1@sheffield.ac.uk>\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[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 assigntment that\nflips the velocity, thus it is a completely elastic collision with the ground. We use @{text \"s$1\"}\nto ball's height and @{text \"s$2\"} for its velocity. We prove that the ball remains above ground\nand 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 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, hide_lams) 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, hide_lams) 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>=(f g) & (\\<lambda> s. s$1 \\<ge> 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  by (rule fbox_loopI) (auto simp: bb_real_arith local_flow.fbox_g_ode[OF local_flow_ball])\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_ivl[OF local_flow_temp _ UNIV_I]\n\nlemma thermostat:\n  assumes \"a > 0\" and \"0 \\<le> t\" 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) on {0..t} UNIV @ 0)\n    ELSE (x\\<acute>=(f a L) & (\\<lambda>s. s$2 \\<le> - (ln ((L-Tmax)/(L-s$3)))/a) on {0..t} UNIV @ 0)) )\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,2)] le_fun_def)\n  using temp_dyn_up_real_arith[OF assms(1) _ _ assms(4), of Tmin]\n    and temp_dyn_down_real_arith[OF assms(1,3), of _ Tmax] by auto\n\nno_notation temp_vec_field (\"f\")\n        and temp_flow (\"\\<phi>\")\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/Hybrid_Systems_VCs/HS_VC_Examples.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8633916205190225, "lm_q2_score": 0.865224084314688, "lm_q1q2_score": 0.7470272242685458}}
{"text": "theory Coloring\n  imports Main Permutation\nbegin\n\nlemma MaxAtLeastLessThan [simp]:\n  fixes k :: nat\n  assumes \"k > 0\"\n  shows \"Max {0..<k} = k - 1\"\nproof (subst Max_eq_iff)\n  show \"finite {0..<k}\" \n    using finite_atLeastLessThan\n    by auto\nnext\n  show \"{0..<k} \\<noteq> {}\" using assms by simp\nnext\n  show \"k - 1 \\<in> {0..<k} \\<and> (\\<forall>a\\<in>{0..<k}. a \\<le> k - 1)\"\n    using assms\n    by auto\nqed\n\n\ntext\\<open>colors are represented by natural numbers\\<close>\ntype_synonym color = nat\n\ntypedef coloring = \"{cs :: color list. (\\<exists> k. set cs = {0..<k})}\"\n    morphisms color_list coloring\nby (rule_tac x=\"[0]\" in exI, auto)\n\nsetup_lifting type_definition_coloring\n\nlift_definition length :: \"coloring \\<Rightarrow> nat\" is List.length\ndone\n\nlift_definition max_color :: \"coloring \\<Rightarrow> color\" is \"\\<lambda> cs. Max (set cs)\"\ndone\n\ndefinition num_colors :: \"coloring \\<Rightarrow> nat\" where\n  \"num_colors \\<pi> = (if color_list \\<pi> = [] then 0 else max_color \\<pi> + 1)\"\n\ndefinition colors :: \"coloring \\<Rightarrow> color list\" where\n    \"colors \\<pi> = [0..<num_colors \\<pi>]\"\n\nlemma distinct_colors:\n  shows \"distinct (colors \\<pi>)\"\n  by (simp add: colors_def) \n\nlemma ex_color:\n  assumes \"c < num_colors \\<pi>\"\n  shows \"c \\<in> set (colors \\<pi>)\"\nusing assms\nunfolding colors_def num_colors_def\nby auto\n\nlift_definition color_fun :: \"coloring => (nat => color)\" is \"\\<lambda> cs v. cs ! v\"\ndone\n\nlemma color_fun_in_colors:\n  assumes \"v < length \\<pi>\"\n  shows \"color_fun \\<pi> v \\<in> set (colors \\<pi>)\"\n  using assms\n  unfolding colors_def num_colors_def\n  by transfer (smt (verit, ccfv_SIG) MaxAtLeastLessThan One_nat_def Suc_pred add.commute empty_iff list.set(1) not_gr_zero nth_mem plus_1_eq_Suc set_upt upt_0)\n\nlemma ex_color_color_fun:\n  assumes \"c \\<in> set (colors \\<pi>)\"\n  shows \"\\<exists> v < length \\<pi>. color_fun \\<pi> v = c\"\n  using assms\n  unfolding colors_def num_colors_def\n  by transfer (metis (mono_tags, opaque_lifting) MaxAtLeastLessThan Suc_eq_plus1 Suc_pred' add_lessD1 atLeastLessThan_iff atLeastLessThan_upt comm_monoid_add_class.add_0 in_set_conv_nth length_greater_0_conv not_less0) \n\nlemma all_colors:\n  shows \"set (colors \\<pi>) = set (map (color_fun \\<pi>) [0..<length \\<pi>])\"\n  unfolding colors_def num_colors_def\n  by transfer (smt (verit, del_insts) MaxAtLeastLessThan Suc_eq_plus1_left Suc_pred' add.commute atLeastLessThan_iff atLeastLessThan_upt gr_zeroI length_greater_0_conv length_pos_if_in_set map_nth nth_mem)\n\nlemma all_colors_list:\n  shows \"colors \\<pi> = remdups (sort (map (color_fun \\<pi>) [0..<length \\<pi>]))\"\n  by (metis all_colors colors_def remdups_upt set_sort sort_upt sorted_list_of_set_sort_remdups sorted_remdups sorted_sort sorted_sort_id)\n\nlemma color_fun_all_colors [simp]: \n  shows \"\\<exists>k. color_fun \\<pi> ` {0..<length \\<pi>} = {0..<k}\"\n  by transfer  (metis list.set_map map_nth set_upt)\n\n\nlemma coloring_eqI:\n  assumes \"length \\<pi> = length \\<pi>'\" \"\\<forall> v < length \\<pi>. color_fun \\<pi> v = color_fun \\<pi>' v\"\n  shows \"\\<pi> = \\<pi>'\"\nproof-\n  have \"color_list \\<pi> = color_list \\<pi>'\"\n    by (metis assms(1) assms(2) color_fun.rep_eq length.rep_eq nth_equalityI) \n  then show ?thesis\n    by (simp add: color_list_inject) \nqed\n\ndefinition color_fun_to_coloring :: \"nat \\<Rightarrow> (nat \\<Rightarrow> color) \\<Rightarrow> coloring\" where\n  \"color_fun_to_coloring n \\<pi> = coloring (map \\<pi> [0..<n])\"\n\n\nlemma color_fun_to_coloring [simp]:\n  assumes \"\\<exists>k. \\<pi> ` {0..<n} = {0..<k}\" \"v < n\" \n  shows \"color_fun (color_fun_to_coloring n \\<pi>) v = \\<pi> v\"\n  using assms\n  unfolding color_fun_to_coloring_def\n  by (subst color_fun.abs_eq) (simp_all add: eq_onp_def)\n\nlemma color_fun_to_coloring_length [simp]:\n  assumes \"\\<exists> k. \\<pi> ` {0..<n} = {0..<k}\"\n  shows \"length (color_fun_to_coloring n \\<pi>) = n\"\n  using assms\n  unfolding color_fun_to_coloring_def\n  by transfer (simp add: coloring_inverse length.rep_eq)\n\nlemma color_fun_to_coloring_eq_conv: \n  assumes \"\\<forall> v < n. \\<pi>1 v = \\<pi>2 v\" \n  shows \"color_fun_to_coloring n \\<pi>1 = color_fun_to_coloring n \\<pi>2\"\n  unfolding color_fun_to_coloring_def\n  by (smt (verit, best) assms ex_nat_less_eq linorder_not_less map_eq_conv set_upt)\n\ntext\\<open>------------------------------------------------------\\<close>\nsubsection\\<open>Cells\\<close>\ntext\\<open>------------------------------------------------------\\<close>\n\ntext \\<open>Cell of a coloring is the set of all vertices colored by the given color\\<close>\ndefinition cell :: \"coloring \\<Rightarrow> color \\<Rightarrow> nat set\" where\n  \"cell \\<pi> c = {v. v < length \\<pi> \\<and> color_fun \\<pi> v = c}\"\n\ntext \\<open>The list of all cells of a given coloring\\<close>\ndefinition cells :: \"coloring \\<Rightarrow> (nat set) list\" where\n  \"cells \\<pi> = map (\\<lambda> c. cell \\<pi> c) (colors \\<pi>)\" \n\nlemma cell_finite [simp]:\n  shows \"finite (cell \\<pi> c)\"\n  unfolding cell_def\n  by auto\n\nlemma length_cells [simp]:\n  shows \"List.length (cells \\<pi>) = num_colors \\<pi>\"\n  by (simp add: cells_def colors_def num_colors_def) \n\nlemma nth_cells [simp]:\n  assumes \"c < num_colors \\<pi>\"\n  shows \"cells \\<pi> ! c = cell \\<pi> c\"\n  using assms\n  unfolding colors_def num_colors_def cells_def\n  by auto\n\nlemma cells_disjunct:\n  assumes \"i < num_colors \\<pi>\" \"j < num_colors \\<pi>\" \"i \\<noteq> j\"\n  shows \"cells \\<pi> ! i \\<inter> cells \\<pi> ! j = {}\"\n  using assms\n  by (auto simp add: cell_def)\n\nlemma cells_non_empty:\n  assumes \"c \\<in> set (cells \\<pi>)\"\n  shows \"c \\<noteq> {}\"\n  using assms ex_color_color_fun\n  unfolding cells_def cell_def\n  by auto\n\nlemma cell_non_empty:\n  assumes \"c < num_colors \\<pi>\"\n  shows \"cell \\<pi> c \\<noteq> {}\"\n  by (metis assms cells_non_empty length_cells nth_cells nth_mem) \n\ndefinition cells_ok where\n  \"cells_ok n cs \\<longleftrightarrow> \n    (\\<forall> i j. i < List.length cs \\<and> j < List.length cs \\<and> i \\<noteq> j  \\<longrightarrow> cs ! i \\<inter> cs ! j = {}) \\<and>\n    (\\<forall> c \\<in> set cs. c \\<noteq> {}) \\<and> \n    (\\<Union> (set cs) = {0..<n})\"\n\nlemma cells_ok:\n  shows \"cells_ok (length \\<pi>) (cells \\<pi>)\"\n  unfolding cells_ok_def\nproof safe\n  fix i j x\n  assume \"i < List.length (cells \\<pi>)\" \"j < List.length (cells \\<pi>)\" \"i \\<noteq> j\"\n         \"x \\<in> (cells \\<pi>) ! i\" \"x \\<in> (cells \\<pi>) ! j\"\n  then show \"x \\<in> {}\"\n    using cells_disjunct\n    by auto\nnext\n  assume \"{} \\<in> set (cells \\<pi>)\"\n  then show False\n    using cells_non_empty by blast\nnext\n  fix v Cell\n  assume \"v \\<in> Cell\" \"Cell \\<in> set (cells \\<pi>)\"\n  then show \"v \\<in> {0..<length \\<pi>}\"\n     unfolding cells_def all_colors cell_def\n     by auto\nnext\n  fix v\n  assume \"v \\<in> {0..<length \\<pi>}\"\n  then have \"v \\<in> cell \\<pi> (color_fun \\<pi> v)\"\n    unfolding cell_def\n    by simp\n  then show \"v \\<in> \\<Union> (set (cells \\<pi>))\"\n    using `v \\<in> {0..<length \\<pi>}`\n    by (simp add: cells_def cell_def color_fun_in_colors)\nqed\n\nlemma cells_ok_finite [simp]:\n  fixes n :: nat\n  assumes \"cells_ok n cs\" \"x \\<in> set cs\"\n  shows \"finite x\"\n  using assms\n  unfolding cells_ok_def\n  by (metis List.finite_set Union_upper finite_subset set_upt)\n\nlemma distinct_cells:\n  shows \"distinct (cells \\<pi>)\"\n  using cells_ok[of \\<pi>]\n  unfolding cells_ok_def\n  by (metis distinct_conv_nth in_set_conv_nth le_iff_inf order.refl)\n\ntext\\<open>------------------------------------------------------\\<close>\nsubsection \\<open>Cells to coloring\\<close>\ntext\\<open>------------------------------------------------------\\<close>\n\ntext\\<open>determine coloring fun or the coloring given by its cells\\<close>\n\ntext\\<open>function given by a set of ordered pairs\\<close>\ndefinition tabulate :: \"('a \\<times> 'b) set \\<Rightarrow> 'a \\<Rightarrow> 'b\" where\n  \"tabulate A x = (THE y. (x, y) \\<in> A)\"\n\nlemma tabulate:\n  assumes \"\\<exists>! y. (x, y) \\<in> A\" \"(x, y) \\<in> A\"\n  shows \"tabulate A x = y\"\n  using assms\n  by (metis tabulate_def the_equality)\n\nlemma tabulate_codomain:\n  assumes \"\\<exists>! y. (x, y) \\<in> A\"\n  shows \"(x, tabulate A x) \\<in> A\"\n  using assms\n  by (metis tabulate)\n\nlemma tabulate_value:\n  assumes \"y = tabulate A x\" \"\\<exists>! y. (x, y) \\<in> A\"\n  shows \"(x, y) \\<in> A\"\n  using assms\n  by (metis tabulate)\n\nabbreviation cells_to_color_fun_pairs :: \"nat set list \\<Rightarrow> (nat \\<times> color) set\" where\n  \"cells_to_color_fun_pairs cs \\<equiv> \n    (\\<Union> (set (map2 (\\<lambda>cl c. (\\<lambda>v. (v, c)) ` cl) cs [0..<List.length cs])))\"\n\ndefinition cells_to_color_fun :: \"nat set list \\<Rightarrow> nat \\<Rightarrow> color\" where\n  \"cells_to_color_fun cs = tabulate (cells_to_color_fun_pairs cs)\"\n\nlemma ex1_cells_to_color_fun_pairs:\n  assumes \"cells_ok n cs\"\n  shows \"\\<forall> v < n. \\<exists>! c. (v, c) \\<in> cells_to_color_fun_pairs cs\"\nproof (rule allI, rule impI)\n  fix v\n  assume \"v < n\"\n  then obtain c where \"c < List.length cs\" \"v \\<in> cs ! c\"\n    using assms\n    unfolding cells_ok_def\n    by (metis Union_iff atLeastLessThan_iff in_set_conv_nth zero_le)\n  then have *: \"(cs ! c, c) \\<in> set (zip cs [0..<List.length cs])\"\n               \"(v, c) \\<in> (\\<lambda>v. (v, c)) ` (cs ! c)\"\n     by (auto simp add: set_zip)\n\n  let ?A = \"cells_to_color_fun_pairs cs\"\n  show \"\\<exists>! c. (v, c) \\<in> ?A\"\n  proof\n    show \"(v, c) \\<in> ?A\"\n      using *\n      by auto\n  next\n    fix c'\n    assume \"(v, c') \\<in> ?A\"\n    then have \"c' < List.length cs\" \"v \\<in> cs ! c'\"\n      by (auto simp add: set_zip)\n    then show \"c' = c\"\n      using * `c < List.length cs` assms\n      unfolding cells_ok_def\n      by auto\n  qed\nqed\n\nlemma cells_to_color_fun: \n  assumes \"cells_ok n cs\" \"c < List.length cs\" \"v \\<in> cs ! c\"\n  shows \"cells_to_color_fun cs v = c\"\n  unfolding cells_to_color_fun_def\nproof (rule tabulate)\n  let ?A = \"cells_to_color_fun_pairs cs\"\n\n  have \"(cs ! c, c) \\<in> set (zip cs [0..<List.length cs])\"\n    by (metis add_cancel_right_left assms(2) in_set_zip length_map map_nth nth_upt prod.sel(1) prod.sel(2))     \n  then show \"(v, c) \\<in> ?A\"\n    using `v \\<in> cs ! c`\n    by auto\n\n  have \"v < n\"\n    using `cells_ok n cs` `c < List.length cs` `v \\<in> cs ! c`\n    unfolding cells_ok_def\n    by auto\n  then show \"\\<exists>!c. (v, c) \\<in> ?A\"\n    using ex1_cells_to_color_fun_pairs[OF assms(1), rule_format, of v]\n    by simp\nqed\n\nlemma cells_to_color_fun': \n  assumes \"cells_ok n cs\" \n          \"c < List.length cs\" \"v < n\" \"cells_to_color_fun cs v = c\"\n  shows \"v \\<in> cs ! c\"\nproof-\n  have \"(v, c) \\<in> cells_to_color_fun_pairs cs\"\n    using assms\n    using tabulate_value[of c \"cells_to_color_fun_pairs cs\" v]  ex1_cells_to_color_fun_pairs\n    unfolding cells_to_color_fun_def\n    by presburger\n  then show ?thesis\n    by (auto simp add: set_zip)\nqed\n  \nlemma cells_to_color_fun_image:\n  assumes \"cells_ok n cs\"\n  shows \"cells_to_color_fun cs ` {0..<n} = {0..<List.length cs}\"\nproof safe\n  fix v\n  assume \"v \\<in> {0..<n}\"\n  then obtain c where \"c < List.length cs\" \"cells_to_color_fun cs v = c\"\n    using assms cells_to_color_fun\n    unfolding cells_ok_def\n    by (smt (verit, ccfv_SIG) Union_iff in_set_conv_nth) \n  then show \"cells_to_color_fun cs v \\<in> {0..<List.length cs}\"\n    by simp\nnext\n  fix c\n  assume \"c \\<in> {0..<List.length cs}\"\n  then obtain v where \"v \\<in> {0..<n}\" \"v \\<in> cs ! c\"\n    using assms\n    unfolding cells_ok_def\n    by (metis Union_iff atLeastLessThan_iff equals0I nth_mem)\n  then show \"c \\<in> cells_to_color_fun cs ` {0..<n}\"\n    using \\<open>c \\<in> {0..<List.length cs}\\<close> assms cells_to_color_fun by fastforce\nqed\n\ndefinition cells_to_coloring where\n  \"cells_to_coloring n cs = color_fun_to_coloring n (cells_to_color_fun cs)\"\n\nlemma color_list_cells_to_coloring [simp]:\n  assumes \"cells_ok n cs\"\n  shows \"color_list (cells_to_coloring n cs) = map (cells_to_color_fun cs) [0..<n]\"\n  unfolding cells_to_coloring_def color_fun_to_coloring_def\nproof (rule coloring_inverse)\n  show \"map (cells_to_color_fun cs) [0..<n] \\<in> {cs. \\<exists>k. set cs = {0..<k}}\"\n    using assms cells_to_color_fun_image by auto  \nqed\n\nlemma length_cells_to_coloring [simp]:\n  assumes \"cells_ok n cs\"\n  shows \"length (cells_to_coloring n cs) = n\"\n  using assms\n  by (simp add: length.rep_eq)\n\nlemma max_color_cells_to_coloring [simp]:\n  assumes \"cells_ok n cs\" \"cs \\<noteq> []\"\n  shows \"max_color (cells_to_coloring n cs) = List.length cs - 1\"\n  by (simp add: assms(1) assms(2) cells_to_color_fun_image max_color.rep_eq)\n\n\nlemma colors_cells_to_coloring [simp]:\n  assumes \"cells_ok n cs\"\n  shows \"colors (cells_to_coloring n cs) = [0..<List.length cs]\"\n  using assms\n  unfolding colors_def num_colors_def\n  by (smt (verit, ccfv_threshold) MaxAtLeastLessThan One_nat_def Suc_pred add.commute cells_to_color_fun_image color_list_cells_to_coloring last_in_set length_pos_if_in_set list.set_map list.size(3) max_color.rep_eq plus_1_eq_Suc set_upt upt_0)\n\n\nlemma num_colors_cells_to_coloring [simp]:\n  assumes \"cells_ok n cs\"\n  shows \"num_colors (cells_to_coloring n cs) = List.length cs\"\n  by (metis assms colors_cells_to_coloring colors_def length_upt minus_nat.diff_0)\n\nlemma cell_cells_to_coloring:\n  assumes \"cells_ok n cs\" \"c < List.length cs\"\n  shows \"cell (cells_to_coloring n cs) c = cs ! c\"\nproof safe\n  fix v\n  let ?cl = \"cells_to_coloring n cs\"\n  assume \"v \\<in> cell ?cl c\"\n  then have \"v < length ?cl\" \"color_fun ?cl v = c\"\n    unfolding cell_def\n    by auto\n  then show \"v \\<in> cs ! c\"\n    using assms(1) cells_to_color_fun'[OF assms, of v]\n    by (simp add:color_fun.rep_eq) \nnext\n  fix v\n  assume \"v \\<in> cs ! c\"\n  then have \"v \\<in> \\<Union> (set cs)\"\n    using assms(2) nth_mem\n    by auto\n  then have \"v < n\"\n    using assms\n    unfolding cells_ok_def\n    by simp\n  then show \"v \\<in> cell (cells_to_coloring n cs) c\"\n    using assms\n    unfolding cell_def\n    using \\<open>v \\<in> cs ! c\\<close> cells_to_color_fun color_fun.rep_eq by force \nqed\n\nlemma cells_cells_to_coloring:\n  assumes \"cells_ok n cs\"\n  shows \"cells (cells_to_coloring n cs) = cs\"\n  using assms\n  unfolding cells_def\n  by (metis cell_cells_to_coloring cells_def colors_cells_to_coloring length_cells length_map map_nth nth_cells nth_equalityI)\n  \n  \ntext\\<open>------------------------------------------------------\\<close>\nsubsection\\<open>Finer colorings\\<close>\ntext\\<open>------------------------------------------------------\\<close>\n\ntext \\<open>Check if the color \\<pi>' refines the coloring \\<pi> - each cells of \\<pi>' is a subset of a cell of \\<pi>\\<close>\ndefinition finer :: \"coloring \\<Rightarrow> coloring \\<Rightarrow> bool\" (infixl \"\\<preceq>\" 100) where\n  \"finer \\<pi>' \\<pi> \\<longleftrightarrow> length \\<pi>' = length \\<pi> \\<and> \n  (\\<forall> v1 < length \\<pi>. \\<forall> v2 < length \\<pi>. \n      color_fun \\<pi> v1 < color_fun \\<pi> v2 \\<longrightarrow> color_fun \\<pi>' v1 < color_fun \\<pi>' v2)\"\n\ndefinition finer_strict :: \"coloring \\<Rightarrow> coloring \\<Rightarrow> bool\"  (infixl \"\\<prec>\" 100) where\n  \"finer_strict \\<pi> \\<pi>' \\<longleftrightarrow> \\<pi> \\<preceq> \\<pi>' \\<and> \\<pi> \\<noteq> \\<pi>'\" \n\nlemma finer_length:\n  assumes \"finer \\<pi>' \\<pi>\"\n  shows \"length \\<pi>' = length \\<pi>\"\n  using assms\n  by (simp add: finer_def)\n\nlemma finer_refl:\n  shows \"finer \\<pi> \\<pi>\"\n  unfolding finer_def\n  by auto\n\nlemma finer_trans:\n  assumes \"finer \\<pi>1 \\<pi>2\" \"finer \\<pi>2 \\<pi>3\"\n  shows \"finer \\<pi>1 \\<pi>3\"\n  using assms\n  using finer_def \n  by auto\n\n\nlemma finer_same_color:\n  assumes \"\\<pi>' \\<preceq> \\<pi>\" \"v1 < length \\<pi>\" \"v2 < length \\<pi>\" \"color_fun \\<pi>' v1 = color_fun \\<pi>' v2\" \n  shows \"color_fun \\<pi> v1 = color_fun \\<pi> v2\"\n  using assms\n  unfolding finer_def\n  by (metis less_imp_not_eq less_linear)\n  \n  \nlemma finer_cell_subset:\n  assumes \"finer \\<pi>' \\<pi>\"\n  shows \"\\<forall> C' \\<in> set (cells \\<pi>'). \\<exists> C \\<in> set (cells \\<pi>). C' \\<subseteq> C\"\nproof safe\n  fix C'\n  assume \"C' \\<in> set (cells \\<pi>')\"\n  then obtain c' where \"c' < num_colors \\<pi>'\" \"C' = cell \\<pi>' c'\"\n    by (metis index_of_in_set length_cells nth_cells)\n  then obtain v where \"v \\<in> cell \\<pi>' c'\"\n    using cell_non_empty by auto\n  then have \"v < length \\<pi>'\" \"color_fun \\<pi>' v = c'\"\n    unfolding cell_def\n    by auto\n  have \"length \\<pi>' = length \\<pi>\"\n    using assms finer_length \n    by simp\n  let ?C = \"cell \\<pi> (color_fun \\<pi> v)\"\n  have \"color_fun \\<pi> v \\<in> set (colors \\<pi>)\"\n    using `v < length \\<pi>'` `length \\<pi>' = length \\<pi>`\n    using color_fun_in_colors\n    by simp\n  then have \"?C \\<in> set (cells \\<pi>)\"\n    unfolding cells_def\n    by simp\n  moreover\n  have \"C' \\<subseteq> ?C\"\n  proof\n    fix v'\n    assume \"v' \\<in> C'\"\n    then have \"v' < length \\<pi>'\" \"color_fun \\<pi>' v' = color_fun \\<pi>' v\"\n      using \\<open>C' \\<in> set (cells \\<pi>')\\<close>  \\<open>C' = cell \\<pi>' c'\\<close> \\<open>v \\<in> cell \\<pi>' c'\\<close> \\<open>v' \\<in> C'\\<close> \n      by (auto simp add: cell_def)\n    then have \"color_fun \\<pi> v' = color_fun \\<pi> v\"\n      using \\<open>v < length \\<pi>'\\<close> \\<open>finer \\<pi>' \\<pi>\\<close> finer_same_color \n      by (metis finer_def) \n    then show \"v' \\<in> ?C\"\n      using \\<open>v' < length \\<pi>'\\<close> \\<open>length \\<pi>' = length \\<pi>\\<close>\n      unfolding cell_def\n      by simp\n  qed\n  ultimately\n  show \"\\<exists> C \\<in> set (cells \\<pi>). C' \\<subseteq> C\"\n    by blast\nqed\n\nlemma finer_cell_subset1:\n  assumes \"finer \\<pi>' \\<pi>\"\n  shows \"\\<forall> C' \\<in> set (cells \\<pi>'). \\<exists>! C \\<in> set (cells \\<pi>). C' \\<subseteq> C\"\nproof\n  fix C'\n  assume \"C' \\<in> set (cells \\<pi>')\"\n  {\n    fix C1 C2\n    assume \"C1 \\<in> set (cells \\<pi>)\" \"C2 \\<in> set (cells \\<pi>)\" \"C' \\<subseteq> C1\" \"C' \\<subseteq> C2\"\n    then have \"C1 = C2\"\n      by (smt (verit, best) Int_empty_right Int_left_commute \\<open>C' \\<in> set (cells \\<pi>')\\<close> cell_non_empty cells_disjunct index_of_in_set inf.absorb_iff2 le_iff_inf length_cells nth_cells)\n  }\n  then show \"\\<exists>! C \\<in> set (cells \\<pi>). C' \\<subseteq> C\"\n    using finer_cell_subset[OF assms]\n    by (meson \\<open>C' \\<in> set (cells \\<pi>')\\<close>)\nqed\n\nlemma finer_cell_subset':\n  assumes \"finer \\<pi>' \\<pi>\"\n  shows \"\\<forall> C \\<in> set (cells \\<pi>). \\<exists> Cs \\<subseteq> set (cells \\<pi>'). Cs \\<noteq> {} \\<and> C = \\<Union> Cs\"\nproof safe\n  fix C\n  assume \"C \\<in> set (cells \\<pi>)\"\n  then obtain c where \"c < num_colors \\<pi>\" \"C = cell \\<pi> c\"\n    by (metis index_of_in_set length_cells nth_cells)\n  let ?Cs = \"(\\<lambda> v. cell \\<pi>' (color_fun \\<pi>' v)) ` C\"\n  have \"?Cs \\<subseteq> set (cells \\<pi>')\"\n  proof safe\n    fix v\n    assume \"v \\<in> C\"\n    then show \"cell \\<pi>' (color_fun \\<pi>' v) \\<in> set (cells \\<pi>')\"\n      unfolding cells_def\n      using \\<open>C = cell \\<pi> c\\<close> assms cell_def color_fun_in_colors finer_length by auto\n  qed\n  moreover\n  have \"?Cs \\<noteq> {}\"\n    using \\<open>C \\<in> set (cells \\<pi>)\\<close> cells_non_empty by blast\n  moreover\n  have \"C = \\<Union> ?Cs\"\n  proof safe\n    fix v\n    assume \"v \\<in> C\" \n    have \"v \\<in> cell \\<pi>' (color_fun \\<pi>' v)\"\n      using finer_length[OF assms] `v \\<in> C` `C = cell \\<pi> c`\n      unfolding cell_def\n      by auto\n    then show \"v \\<in> \\<Union> ?Cs\"\n      using `v \\<in> C`\n      by auto\n  next\n    fix v v'\n    assume \"v \\<in> C\" \"v' \\<in> cell \\<pi>' (color_fun \\<pi>' v)\"\n    then show \"v' \\<in> C\"\n      using finer_same_color[OF assms, of v v'] `C = cell \\<pi> c` `c < num_colors \\<pi>` finer_length[OF assms]\n      unfolding cell_def\n      by auto\n  qed\n  ultimately\n  show \"\\<exists> Cs \\<subseteq> set (cells \\<pi>'). Cs \\<noteq> {} \\<and> C = \\<Union> Cs\"\n    by blast\nqed\n\nlemma cell_subset_finer:\n  assumes \"length \\<pi>' = length \\<pi>\"\n          \"\\<forall> C' \\<in> set (cells \\<pi>'). \\<exists> C \\<in> set (cells \\<pi>). C' \\<subseteq> C\"\n          \"\\<forall> p1 p2 c1 c2. c1 < num_colors \\<pi>' \\<and> p1 < num_colors \\<pi> \\<and>\n                          c2 < num_colors \\<pi>' \\<and> p2 < num_colors \\<pi> \\<and>\n                          cell \\<pi>' c1 \\<subseteq> cell \\<pi> p1 \\<and>\n                          cell \\<pi>' c2 \\<subseteq> cell \\<pi> p2 \\<and> c1 \\<le> c2 \\<longrightarrow> p1 \\<le> p2\"\n  shows \"finer \\<pi>' \\<pi>\"\nunfolding finer_def\nproof safe\n  show \"length \\<pi>' = length \\<pi>\"\n    by fact\nnext\n  fix v1 v2\n  assume \"v1 < length \\<pi>\" \"v2 < length \\<pi>\" \"color_fun \\<pi> v1 < color_fun \\<pi> v2\"\n  show \"color_fun \\<pi>' v1 < color_fun \\<pi>' v2\"\n  proof-\n    let ?p1 = \"color_fun \\<pi> v1\" \n    let ?p2 = \"color_fun \\<pi> v2\"\n    let ?c1 = \"color_fun \\<pi>' v1\"\n    let ?c2 = \"color_fun \\<pi>' v2\" \n    let ?C1' = \"cell \\<pi>' ?c1\"\n    let ?C2' = \"cell \\<pi>' ?c2\"\n    have \"?C1' \\<in> set (cells \\<pi>')\"\n      by (simp add: \\<open>v1 < length \\<pi>\\<close> assms(1) cells_def color_fun_in_colors)\n    then obtain C1 where \"?C1' \\<subseteq> C1\" \"C1 \\<in> set (cells \\<pi>)\"\n      using assms(2) by fastforce     \n    have \"?C2' \\<in> set (cells \\<pi>')\"\n      by (simp add: \\<open>v2 < length \\<pi>\\<close> assms(1) cells_def color_fun_in_colors)\n    then obtain C2 where \"?C2' \\<subseteq> C2\" \"C2 \\<in> set (cells \\<pi>)\"\n      using assms(2) by fastforce\n    have \"v1 \\<in> C1\"\n      using \\<open>cell \\<pi>' (color_fun \\<pi>' v1) \\<subseteq> C1\\<close> \\<open>v1 < length \\<pi>\\<close> assms(1) cell_def\n       by auto\n    then have \"C1 = cell \\<pi> ?p1\"\n      using `C1 \\<in> set (cells \\<pi>)`\n      unfolding cells_def cell_def\n      by auto\n    moreover \n    have \"v2 \\<in> C2\"\n      using \\<open>cell \\<pi>' (color_fun \\<pi>' v2) \\<subseteq> C2\\<close> \\<open>v2 < length \\<pi>\\<close> assms(1) cell_def\n       by auto    \n    then have \"C2 = cell \\<pi> ?p2\"\n      using `C2 \\<in> set (cells \\<pi>)`\n      unfolding cells_def cell_def\n      by auto\n    moreover \n    have \"?c1 < num_colors \\<pi>'\"\n      using \\<open>v1 < length \\<pi>\\<close> assms(1) \n      by (metis atLeast0LessThan atLeastLessThan_upt color_fun_in_colors colors_def lessThan_iff)\n    moreover \n    have \"?c2 < num_colors \\<pi>'\"\n      using \\<open>v2 < length \\<pi>\\<close> assms(1) \n      by (metis atLeast0LessThan atLeastLessThan_upt color_fun_in_colors colors_def lessThan_iff)   \n    moreover \n    have \"?p1 < num_colors \\<pi>\" \"?p2 < num_colors \\<pi>\"\n      using \\<open>v1 < length \\<pi>\\<close> \\<open>v2 < Coloring.length \\<pi>\\<close> color_fun_in_colors colors_def\n      by auto\n    ultimately show \"?c1 < ?c2\"\n      using `?C1' \\<subseteq> C1` `?C2' \\<subseteq> C2` \n      using `color_fun \\<pi> v1 < color_fun \\<pi> v2`\n      using assms(3)\n      by (meson leD linorder_le_less_linear)\n  qed\nqed\n\nlemma finer_color_fun_non_decreasing:\n  assumes \"\\<pi>' \\<preceq> \\<pi>\" \"v < length \\<pi>\"\n  shows \"color_fun \\<pi>' v \\<ge> color_fun \\<pi> v\"\n  using assms\nproof (induction \"color_fun \\<pi> v\" arbitrary: v rule: nat_less_induct)\n  case 1\n  show ?case\n  proof (cases \"color_fun \\<pi> v = 0\")\n    case True\n    then show ?thesis\n      by simp\n  next\n    case False\n    then have \"color_fun \\<pi> v - 1 \\<in> set (colors \\<pi>)\"\n      using \"1.prems\"(2) color_fun_in_colors colors_def less_imp_diff_less by auto\n    then obtain v' where \"v' < length \\<pi>\" \"color_fun \\<pi> v' = color_fun \\<pi> v - 1\"\n      using ex_color_color_fun[of \"color_fun \\<pi> v - 1\" \\<pi>] False\n      by blast\n    then have \"color_fun \\<pi>' v' \\<ge> color_fun \\<pi> v'\"\n      using 1 False\n      by (metis bot_nat_0.not_eq_extremum diff_less zero_less_one)\n    moreover\n    have \"color_fun \\<pi>' v' < color_fun \\<pi>' v\"\n      using `color_fun \\<pi> v' = color_fun \\<pi> v - 1` False\n      using assms `v < length \\<pi>` `v' < length \\<pi>` \n      unfolding finer_def\n      by simp\n    ultimately show ?thesis\n      using `color_fun \\<pi> v' = color_fun \\<pi> v - 1` False\n      by linarith\n  qed\nqed\n\nlemma finer_singleton:\n  assumes \"{v} \\<in> set (cells \\<pi>1)\" \"v < length \\<pi>1\" \"finer \\<pi>2 \\<pi>1\"\n  shows \"{v} \\<in> set (cells \\<pi>2)\"\nproof-\n  have \"length \\<pi>1 = length \\<pi>2\"\n    using `finer \\<pi>2 \\<pi>1`\n    unfolding finer_def\n    by simp\n\n  obtain c where c: \"c \\<in> set (colors \\<pi>1)\" \"color_fun \\<pi>1 v = c\" \"cell \\<pi>1 c = {v}\"\n    using assms\n    by (smt (verit) cell_def color_fun_in_colors in_set_conv_nth length_cells mem_Collect_eq nth_cells singletonI)\n  let ?c = \"color_fun \\<pi>2 v\"\n  have \"cell \\<pi>2 ?c = {v}\"\n  proof-\n    have \"\\<forall> v' < length \\<pi>1. v' \\<noteq> v \\<longrightarrow> color_fun \\<pi>2 v' \\<noteq> ?c\"\n    proof safe\n      fix v'\n      assume \"v' < length \\<pi>1\" \"color_fun \\<pi>2 v' = color_fun \\<pi>2 v\" \"v' \\<noteq> v\"\n      then have \"color_fun \\<pi>1 v' = color_fun \\<pi>1 v\"\n        using assms(2-3) finer_same_color by blast\n      then have \"v' \\<in> cell \\<pi>1 c\"\n        by (simp add: \\<open>v' < length \\<pi>1\\<close> c(2) cell_def)\n      then show False\n        using assms c \\<open>v' \\<noteq> v\\<close>\n        by blast\n    qed\n    then show ?thesis\n      using c(3) `length \\<pi>1 = length \\<pi>2`\n      unfolding cell_def\n      by auto\n  qed\n  then show ?thesis\n    using `v < length \\<pi>1` `length \\<pi>1 = length \\<pi>2` color_fun_in_colors \n    unfolding cells_def\n    by auto\nqed\n\nlemma cells_inj:\n  assumes \"length \\<pi> = length \\<pi>'\" \"cells \\<pi> = cells \\<pi>'\"\n  shows \"\\<pi> = \\<pi>'\"\nproof (rule coloring_eqI)\n  show \"length \\<pi> = length \\<pi>'\"\n    by fact\nnext\n  show \"\\<forall>v<Coloring.length \\<pi>. color_fun \\<pi> v = color_fun \\<pi>' v\"\n  proof safe\n    fix v\n    assume \"v < length \\<pi>\"\n    have \"cell \\<pi> (color_fun \\<pi> v) = cell \\<pi>' (color_fun \\<pi> v)\"\n      using assms\n      unfolding cells_def\n      by (metis \\<open>v < Coloring.length \\<pi>\\<close> assms(2) color_fun_in_colors colors_def length_cells map_eq_conv)\n    then show \"color_fun \\<pi> v = color_fun \\<pi>' v\"\n      using assms(1) cells_ok[of \\<pi>']\n      by (metis (mono_tags, lifting) \\<open>v < Coloring.length \\<pi>\\<close> cell_def mem_Collect_eq)\n  qed\nqed\n\nlemma finer_cells_order:\n  assumes \"\\<pi>' \\<preceq> \\<pi>\" \"c < num_colors \\<pi>\" \"c' < num_colors \\<pi>'\" \"cell \\<pi>' c' = cell \\<pi> c\"\n  shows \"c \\<le> c'\"\nproof-\n obtain v where \"v < length \\<pi>\" \"color_fun \\<pi> v = c\"\n   using \\<open>c < num_colors \\<pi>\\<close> ex_color ex_color_color_fun by blast\n  then have \"color_fun \\<pi>' v = c'\"\n    using \\<open>cell \\<pi>' c' = cell \\<pi> c\\<close>\n    unfolding cell_def\n    by auto\n  show ?thesis\n    using finer_color_fun_non_decreasing[OF assms(1)]\n    using \\<open>color_fun \\<pi> v = c\\<close> \\<open>color_fun \\<pi>' v = c'\\<close> \\<open>v < Coloring.length \\<pi>\\<close>\n    by blast\nqed\n\nlemma finer_cell_set_eq:\n  assumes \"\\<pi>' \\<preceq> \\<pi>\" \"set (cells \\<pi>) = set (cells \\<pi>')\"\n  shows \"cells \\<pi> = cells \\<pi>'\"\nproof-\n  have \"num_colors \\<pi> = num_colors \\<pi>'\"\n    by (metis assms(2) distinct_card distinct_cells length_cells)\n  show ?thesis\n  proof (rule ccontr)\n    assume \"\\<not> ?thesis\"\n    then obtain c where \"c < num_colors \\<pi>\" \"cell \\<pi> c \\<noteq> cell \\<pi>' c\"\n      by (metis \\<open>num_colors \\<pi> = num_colors \\<pi>'\\<close> length_cells nth_cells nth_equalityI)\n    then obtain c' where \"c' < num_colors \\<pi>\" \"cell \\<pi> c = cell \\<pi>' c'\"\n      by (metis \\<open>num_colors \\<pi> = num_colors \\<pi>'\\<close> assms(2) in_set_conv_nth length_cells nth_cells)\n    have \"c < c'\"\n      by (metis \\<open>c < num_colors \\<pi>\\<close> \\<open>c' < num_colors \\<pi>\\<close> \\<open>cell \\<pi> c = cell \\<pi>' c'\\<close> \\<open>cell \\<pi> c \\<noteq> cell \\<pi>' c\\<close> \\<open>num_colors \\<pi> = num_colors \\<pi>'\\<close> assms(1) finer_cells_order order_le_neq_trans)\n\n    have *: \"\\<forall> cc. c < cc \\<and> cc < num_colors \\<pi> \\<longrightarrow> (\\<exists> cc'. c' < cc' \\<and> cc' < num_colors \\<pi>' \\<and> cell \\<pi> cc = cell \\<pi>' cc')\"\n    proof safe\n      fix cc\n      assume \"c < cc\" \"cc < num_colors \\<pi>\"\n      then obtain cc' where \"cc' < num_colors \\<pi>'\" \"cell \\<pi> cc = cell \\<pi>' cc'\"\n        by (metis assms(2) in_set_conv_nth length_cells nth_cells)\n      obtain v where \"v < length \\<pi>\" \"color_fun \\<pi> v = c\" \"color_fun \\<pi>' v = c'\" \n        by (metis (mono_tags, lifting) \\<open>c' < num_colors \\<pi>\\<close> \\<open>cell \\<pi> c = cell \\<pi>' c'\\<close> \\<open>num_colors \\<pi> = num_colors \\<pi>'\\<close> atLeast0LessThan cell_def colors_def ex_color_color_fun lessThan_iff mem_Collect_eq set_upt)\n      obtain v' where \"v' < length \\<pi>\" \"color_fun \\<pi> v' = cc\" \"color_fun \\<pi>' v' = cc'\"\n        by (smt (verit, ccfv_threshold) \\<open>cc' < num_colors \\<pi>'\\<close> \\<open>cell \\<pi> cc = cell \\<pi>' cc'\\<close> atLeast0LessThan cell_def colors_def ex_color_color_fun lessThan_iff mem_Collect_eq set_upt)\n      have \"c' < cc'\"\n        using \\<open>\\<pi>' \\<preceq> \\<pi>\\<close> \\<open>c < cc\\<close>\n        unfolding finer_def\n        using \\<open>color_fun \\<pi> v = c\\<close> \\<open>color_fun \\<pi> v' = cc\\<close> \\<open>color_fun \\<pi>' v = c'\\<close> \\<open>color_fun \\<pi>' v' = cc'\\<close> \\<open>v < Coloring.length \\<pi>\\<close> \\<open>v' < Coloring.length \\<pi>\\<close>\n        by blast\n      then show \"\\<exists>cc'>c'. cc' < num_colors \\<pi>' \\<and> cell \\<pi> cc = cell \\<pi>' cc'\"\n        using \\<open>cc' < num_colors \\<pi>'\\<close> \\<open>cell \\<pi> cc = cell \\<pi>' cc'\\<close> by blast\n    qed\n\n    let ?f = \"\\<lambda> cc. SOME cc'. c' < cc' \\<and> cc' < num_colors \\<pi>' \\<and> cell \\<pi> cc = cell \\<pi>' cc'\"\n\n    have **: \"\\<forall> cc. c < cc \\<and> cc < num_colors \\<pi> \\<longrightarrow> c' < ?f cc \\<and> ?f cc < num_colors \\<pi>' \\<and> cell \\<pi> cc = cell \\<pi>' (?f cc)\"\n      using *\n      by (smt tfl_some)\n\n    have \"card {c+1..<num_colors \\<pi>} \\<le> card {c'+1..<num_colors \\<pi>'}\"\n    proof (rule card_inj_on_le)\n      show \"inj_on ?f {c + 1..<num_colors \\<pi>}\"\n        unfolding inj_on_def\n      proof safe\n        fix x y\n        assume \"x \\<in> {c + 1..<num_colors \\<pi>}\" \"y \\<in> {c + 1..<num_colors \\<pi>}\" \"?f x = ?f y\"\n        then have \"c < x\" \"x < num_colors \\<pi>\" \"c < y\" \"y < num_colors \\<pi>\"\n          by auto\n        then have \"cell \\<pi> x = cell \\<pi>' (?f x)\" \"cell \\<pi> y = cell \\<pi>' (?f y)\"\n          using **\n          by blast+\n        then have \"cell \\<pi> x = cell \\<pi> y\"\n          using `?f x = ?f y`\n          by simp\n        then show \"x = y\"\n          by (metis \\<open>x < num_colors \\<pi>\\<close> \\<open>y < num_colors \\<pi>\\<close> distinct_cells length_cells nth_cells nth_eq_iff_index_eq)\n      qed\n    next\n      show \"?f ` {c + 1..<num_colors \\<pi>} \\<subseteq> {c' + 1..<num_colors \\<pi>'}\"\n      proof safe\n        fix cc\n        assume \"cc \\<in> {c + 1..<num_colors \\<pi>}\"\n        then have \"cc > c\" \"cc < num_colors \\<pi>\"\n          by auto\n        then show \"?f cc \\<in> {c' + 1..<num_colors \\<pi>'}\"\n          using **\n          by fastforce\n      qed\n    next\n      show \"finite {c' + 1..<num_colors \\<pi>'}\"\n        by simp\n    qed\n    then show False\n      using `c < c'` `c < num_colors \\<pi>` `c' < num_colors \\<pi>` `num_colors \\<pi> = num_colors \\<pi>'`\n      using card_atLeastLessThan[of \"c+1\" \"num_colors \\<pi>\"]\n      using card_atLeastLessThan[of \"c'+1\" \"num_colors \\<pi>'\"]\n      by auto\n  qed\nqed\n\nlemma num_colors_finer_strict:\n  assumes \"\\<pi>' \\<prec> \\<pi>\"\n  shows \"num_colors \\<pi>' > num_colors \\<pi>\"\nproof-\n  have \"cells \\<pi> \\<noteq> cells \\<pi>'\"\n    using assms cells_inj[of \\<pi> \\<pi>']\n    using finer_length finer_strict_def\n    by fastforce\n  let ?f = \"\\<lambda> C. SOME C'. C' \\<in> set (cells \\<pi>') \\<and> C' \\<subseteq> C\"\n\n  have *: \"\\<forall> C \\<in> set (cells \\<pi>). ?f C \\<in> set (cells \\<pi>') \\<and> ?f C \\<subseteq> C\"\n  proof\n    fix C\n    assume \"C \\<in> set (cells \\<pi>)\"\n    then obtain Cs where \"C = \\<Union> Cs\" \"Cs\\<subseteq>set (cells \\<pi>')\" \"Cs \\<noteq> {}\"\n      using finer_cell_subset'[of \\<pi>' \\<pi>] assms\n      unfolding finer_strict_def\n      by meson\n    then have \"\\<exists> C' \\<in> set (cells \\<pi>'). C' \\<subseteq> C\"\n      by auto\n    then show \"?f C \\<in> set (cells \\<pi>') \\<and> ?f C \\<subseteq> C\"\n      by (metis (no_types, lifting) verit_sko_ex')\n  qed\n\n  have \"inj_on ?f (set (cells \\<pi>))\"\n    unfolding inj_on_def\n  proof (rule ballI, rule ballI, rule impI)\n    fix C1 C2\n    assume **: \"C1 \\<in> set (cells \\<pi>)\" \"C2 \\<in> set (cells \\<pi>)\"\n               \"?f C1 = ?f C2\"\n    let ?C' = \"(SOME C'. C' \\<in> set (cells \\<pi>') \\<and> C' \\<subseteq> C1)\"\n    have \"?C' \\<in> set (cells \\<pi>')\" \"?C' \\<subseteq> C1\" \"?C' \\<subseteq> C2\"\n      using * **\n      by auto\n    then show \"C1 = C2\"\n      using cells_ok[of \\<pi>] cells_ok[of \\<pi>']\n      unfolding cells_ok_def\n      by (metis (no_types, lifting) \"**\"(1) \"**\"(2) Int_subset_iff index_of_in_set subset_empty)\n  qed\n\n  have \"?f ` set (cells \\<pi>) \\<subset> set (cells \\<pi>')\"\n  proof\n    show \"?f ` set (cells \\<pi>) \\<subseteq> set (cells \\<pi>')\"\n    proof safe\n      fix C\n      assume \"C \\<in> set (cells \\<pi>)\"\n      then obtain Cs where \"C = \\<Union> Cs\" \"Cs\\<subseteq>set (cells \\<pi>')\" \"Cs \\<noteq> {}\"\n        using finer_cell_subset'[of \\<pi>' \\<pi>] assms\n        unfolding finer_strict_def\n        by meson\n      then have \"\\<exists> C' \\<in> set (cells \\<pi>'). C' \\<subseteq> C\"\n        by auto\n      then show \"?f C \\<in> set (cells \\<pi>')\"\n        by (smt (verit, ccfv_SIG) tfl_some)\n    qed\n  next\n    show \"?f ` set (cells \\<pi>) \\<noteq> set (cells \\<pi>')\"\n    proof (rule ccontr)\n      assume contr: \"\\<not> ?thesis\"\n      then have \"card (set (cells \\<pi>)) = card (set (cells \\<pi>'))\"\n        using \\<open>inj_on ?f (set (cells \\<pi>))\\<close> card_image\n        by fastforce\n\n      have ex1: \"\\<forall> C \\<in> set (cells \\<pi>). \\<exists>! C' \\<in> set (cells \\<pi>'). C' \\<subseteq> C\"\n      proof (rule, rule)\n        fix C\n        assume \"C \\<in> set (cells \\<pi>)\"\n        then show \"?f C \\<in> set (cells \\<pi>') \\<and> ?f C \\<subseteq> C\"\n          using \"*\" by blast\n      next\n        fix C C'\n        assume \"C \\<in> set (cells \\<pi>)\" \"C' \\<in> set (cells \\<pi>') \\<and> C' \\<subseteq> C\"\n        let ?g = \"\\<lambda> C'. THE C. C \\<in> set (cells \\<pi>) \\<and> C \\<supseteq> C'\"\n        have gex1: \"\\<forall> C' \\<in> set (cells \\<pi>'). \\<exists>! C \\<in> set (cells \\<pi>). C \\<supseteq> C'\"\n          by (meson assms finer_cell_subset1 finer_strict_def)\n        have \"inj_on ?g (set (cells \\<pi>'))\"\n        proof-\n          have \"?g ` (set (cells \\<pi>')) = set (cells \\<pi>)\"\n          proof safe\n            fix C' \n            assume \"C' \\<in> set (cells \\<pi>')\"\n            then show \"?g C' \\<in> set (cells \\<pi>)\"\n              using gex1 the_eq_trivial\n              by (smt (verit, ccfv_threshold) the_equality)\n          next\n            fix C\n            assume \"C \\<in> set (cells \\<pi>)\"\n            then have \"?g (?f C) = C\"\n              by (smt (verit, ccfv_threshold) \"*\" gex1 someI_ex the_equality)\n            then show \"C \\<in> ?g ` set (cells \\<pi>')\"\n              using \\<open>C \\<in> set (cells \\<pi>)\\<close> contr by blast\n          qed\n            \n          then show ?thesis\n            using `card (set (cells \\<pi>)) = card (set (cells \\<pi>'))`\n            by (simp add: eq_card_imp_inj_on)\n        qed\n        moreover\n        have \"?g C' = ?g (?f C)\"\n        proof-\n          have \"?g (?f C) = C\"\n            by (smt (verit, del_insts) \\<open>C \\<in> set (cells \\<pi>)\\<close> \\<open>C' \\<in> set (cells \\<pi>') \\<and> C' \\<subseteq> C\\<close> gex1 someI_ex the_equality)\n          moreover\n          have \"?g C' = C\"\n            by (simp add: \\<open>C \\<in> set (cells \\<pi>)\\<close> \\<open>C' \\<in> set (cells \\<pi>') \\<and> C' \\<subseteq> C\\<close> gex1 the1_equality)\n          ultimately\n          show ?thesis\n            by simp\n        qed\n        ultimately show \"C' = ?f C\"\n          using `C \\<in> set (cells \\<pi>)` * `C' \\<in> set (cells \\<pi>') \\<and> C' \\<subseteq> C`\n          unfolding inj_on_def\n          by blast\n        qed\n      have \"\\<forall> C \\<in> set (cells \\<pi>). ?f C = C\"\n      proof\n        fix C\n        assume \"C \\<in> set (cells \\<pi>)\"\n        then obtain Cs where \"Cs \\<subseteq> set (cells \\<pi>')\" \"\\<Union>Cs = C\"\n          by (metis assms finer_cell_subset' finer_strict_def)\n        then have \"\\<forall> C' \\<in> Cs. C' \\<in> set (cells \\<pi>') \\<and> C' \\<subseteq> C\"\n          by auto\n        then have \"\\<exists>! C'. C' \\<in> Cs\"\n          using `C \\<in> set (cells \\<pi>)` ex1\n          by (metis Sup_bot_conv(1) \\<open>\\<Union> Cs = C\\<close> cells_non_empty)\n        then have \"Cs = {C}\"\n          by (metis \\<open>\\<Union> Cs = C\\<close> cSup_singleton empty_iff is_singletonI' is_singleton_the_elem)\n        then have \"C \\<in> set (cells \\<pi>')\"\n          using \\<open>Cs \\<subseteq> set (cells \\<pi>')\\<close>\n          by auto\n        moreover\n        have \"?f C \\<in> set (cells \\<pi>')\"  \"?f C \\<subseteq> C\"\n          using * \\<open>C \\<in> set (cells \\<pi>)\\<close>\n          by auto\n        ultimately\n        show \"?f C = C\"\n          using ex1\n          using \\<open>C \\<in> set (cells \\<pi>)\\<close>\n          by blast\n      qed\n      then have \"set (cells \\<pi>) = set (cells \\<pi>')\"\n        using contr by force\n      then show False\n        using `cells \\<pi> \\<noteq> cells \\<pi>'`\n        using assms finer_cell_set_eq finer_strict_def by blast\n    qed\n  qed\n  then have \"card (?f ` set (cells \\<pi>)) < card (set (cells \\<pi>'))\"\n    by (meson List.finite_set psubset_card_mono)\n  moreover \n  have \"card (?f ` set (cells \\<pi>)) = card (set (cells \\<pi>))\"\n  proof (rule card_image)\n    show \"inj_on ?f (set (cells \\<pi>))\"\n      by fact\n  qed\n  ultimately\n  have \"card (set (cells \\<pi>)) < card (set (cells \\<pi>'))\"\n    by simp\n  then have \"List.length (cells \\<pi>') > List.length (cells \\<pi>)\"\n    using distinct_card[of \"cells \\<pi>\"] distinct_card[of \"cells \\<pi>'\"]\n    by (simp add: distinct_cells)\n  then show ?thesis\n    by auto             \nqed\n\ntext \\<open>A coloring is discrete if each vertex is colored by a different color {0..<n}\\<close>\ndefinition discrete :: \"coloring \\<Rightarrow> bool\" where\n  \"discrete \\<pi> \\<longleftrightarrow> set (colors \\<pi>) = {0..<length \\<pi>}\"\n\nlemma discrete_coloring_is_permutation [simp]:\n  assumes \"discrete \\<pi>\"\n  shows \"is_perm_fun (length \\<pi>) (color_fun \\<pi>)\"\n  using assms finite_surj_inj[of \"{0..<length \\<pi>}\" \"color_fun \\<pi>\"] all_colors\n  unfolding discrete_def is_perm_fun_def\n  unfolding bij_betw_def\n  by auto\n\nlemma discrete_singleton:\n  assumes \"discrete \\<pi>\" \"v < length \\<pi>\"\n  shows \"cell \\<pi> (color_fun \\<pi> v) = {v}\"\nproof-\n  have f: \"inj_on (color_fun \\<pi>) {0..<length \\<pi>}\" \"color_fun \\<pi> ` {0..<length \\<pi>} = {0..<length \\<pi>}\"\n    using \\<open>discrete \\<pi>\\<close>\n    by (meson bij_betw_def discrete_coloring_is_permutation is_perm_fun_def)+\n  then show ?thesis\n    using \\<open>v < length \\<pi>\\<close>\n    unfolding cell_def inj_on_def\n    by auto\nqed\n\n    \n    \nlemma discrete_cells_card1:\n  assumes \"discrete \\<pi>\" \"C \\<in> set (cells \\<pi>)\"\n  shows \"card C = 1\"\nproof-\n  obtain c where \"c \\<in> set (colors \\<pi>)\" \"C = cell \\<pi> c\"\n    by (metis assms(2) ex_color index_of_in_set length_cells nth_cells)\n  then obtain v where \"C = {v}\"\n    by (metis assms(1) discrete_singleton ex_color_color_fun)\n  thus ?thesis\n    by simp\nqed\n\nlemma non_discrete_cells_card_gt1:\n  assumes \"\\<not> discrete \\<pi>\"\n  shows \"\\<exists> c \\<in> set (colors \\<pi>). card (cell \\<pi> c) > 1\"\nproof (rule ccontr)\n  assume \"\\<not> ?thesis\"\n  moreover\n  have \"\\<forall> c \\<in> set (colors \\<pi>). card (cell \\<pi> c) \\<ge> 1\"\n    by (metis atLeast0LessThan atLeastLessThan_upt card_0_eq cell_finite cell_non_empty colors_def lessThan_iff less_one linorder_le_less_linear)\n  ultimately\n  have *: \"\\<forall> c \\<in> set (colors \\<pi>). card (cell \\<pi> c) = 1\"\n    by force\n  have \"card ({0..<length \\<pi>}) = card (set (colors \\<pi>))\"\n  proof (rule bij_betw_same_card)\n    show \"bij_betw (color_fun \\<pi>) {0..<length \\<pi>} (set (colors \\<pi>))\"\n      unfolding bij_betw_def \n    proof \n      show \"inj_on (color_fun \\<pi>) {0..<Coloring.length \\<pi>}\"\n        unfolding inj_on_def\n      proof safe\n        fix v1 v2\n        assume \"v1 \\<in> {0..<length \\<pi>}\" \"v2 \\<in> {0..<length \\<pi>}\" \"color_fun \\<pi> v1 = color_fun \\<pi> v2\"\n        then have \"v1 \\<in> cell \\<pi> (color_fun \\<pi> v1)\" \"v2 \\<in> cell \\<pi> (color_fun \\<pi> v1)\"\n          unfolding cell_def\n          by auto\n        moreover have \"card (cell \\<pi> (color_fun \\<pi> v1)) = 1\"\n          using * \\<open>v1 \\<in> {0..<length \\<pi>}\\<close> color_fun_in_colors\n          by force\n        ultimately show \"v1 = v2\"\n          using card_le_Suc0_iff_eq[of \"cell \\<pi> (color_fun \\<pi> v1)\"]\n          by auto\n      qed\n    next\n      show \"color_fun \\<pi> ` {0..<Coloring.length \\<pi>} = set (colors \\<pi>)\"\n      proof safe\n        fix v\n        assume \"v \\<in> {0..<length \\<pi>}\"\n        then show \"color_fun \\<pi> v \\<in> set (colors \\<pi>)\"\n          using color_fun_in_colors\n          by force\n      next\n        fix c\n        assume \"c \\<in> set (colors \\<pi>)\"\n        then obtain v where \"v \\<in> cell \\<pi> c\"\n          using *\n          by fastforce\n        then show \"c \\<in> color_fun \\<pi> ` {0..<Coloring.length \\<pi>}\"\n          unfolding cell_def\n          by auto\n      qed\n    qed\n  qed\n  then have \"length \\<pi> = num_colors \\<pi>\"\n    by (simp add: colors_def)\n  then have \"discrete \\<pi>\"\n    unfolding discrete_def colors_def\n    by auto\n  then show False\n    using assms\n    by auto\n  qed\n\ndefinition discrete_coloring_perm :: \"coloring \\<Rightarrow> perm\" where\n  \"discrete_coloring_perm \\<alpha> = make_perm (length \\<alpha>) (color_fun \\<alpha>)\"\n\nlemma perm_dom_discrete_coloring_perm [simp]:\n  assumes \"discrete \\<alpha>\"\n  shows \"perm_dom (discrete_coloring_perm \\<alpha>) = length \\<alpha>\"\n  using assms\n  unfolding discrete_coloring_perm_def\n  by simp\n\nlemma perm_fun_discrete_coloring_perm [simp]:\n  assumes \"discrete \\<alpha>\" \"v < length \\<alpha>\"\n  shows \"perm_fun (discrete_coloring_perm \\<alpha>) v = color_fun \\<alpha> v\"\n  using assms\n  unfolding discrete_coloring_perm_def\n  by simp\n\n\ntext\\<open>------------------------------------------------------\\<close>\nsubsection\\<open>Permute coloring\\<close>\ntext\\<open>------------------------------------------------------\\<close>\n\ntext\\<open>The effect of vertices perm on colors\\<close>\n\ndefinition perm_coloring :: \"perm \\<Rightarrow> coloring \\<Rightarrow> coloring\" where\n  \"perm_coloring p \\<pi> = coloring (perm_reorder p (color_list \\<pi>))\"\n\nlemma length_perm_coloring [simp]:\n  assumes \"perm_dom p = length \\<pi>\"\n  shows \"length (perm_coloring p \\<pi>) = length \\<pi>\"\n  using assms\n  by (smt (verit) color_list eq_onp_same_args length.abs_eq length.rep_eq length_perm_reorder mem_Collect_eq perm_coloring_def set_perm_reorder)\n\nlemma color_fun_perm_coloring:\n  assumes \"perm_dom p = length \\<pi>\"\n  shows \"color_fun (perm_coloring p \\<pi>) = (!) (perm_reorder p (color_list \\<pi>))\"\n  using assms\n  by (smt (verit) color_fun.abs_eq color_list eq_onp_same_args length.rep_eq list.set_map map_nth mem_Collect_eq perm_coloring_def perm_dom_perm_inv perm_list_set perm_reorder set_upt)\n  \nlemma color_fun_perm_coloring_app:\n  assumes \"perm_dom p  = length \\<pi>\" \n  assumes \"v < length \\<pi>\" \n  shows \"color_fun (perm_coloring p \\<pi>) v = ((color_fun \\<pi>) \\<circ> (perm_fun (perm_inv p))) v\"\n  using assms color_fun.rep_eq color_fun_perm_coloring length.rep_eq\n  by auto\n\nlemma perm_coloring_perm_fun [simp]:\n  assumes \"perm_dom p = length \\<pi>\" \"v < length \\<pi>\"\n  shows \"color_fun (perm_coloring p \\<pi>) (perm_fun p v) = color_fun \\<pi> v\"\n  by (metis assms(1) assms(2) color_fun_perm_coloring_app comp_apply perm_dom_perm_inv perm_fun_perm_inv2 perm_fun_perm_inv_range perm_inv_inv)  \n\nlemma max_color_perm_coloring [simp]:\n  assumes \"perm_dom p = length \\<pi>\"\n  shows \"max_color (perm_coloring p \\<pi>) = max_color \\<pi>\"\n  using assms\n  by (metis color_fun.rep_eq color_fun_perm_coloring length.rep_eq length_perm_coloring length_perm_reorder list.set_map map_nth max_color.rep_eq perm_dom_perm_inv perm_list_set perm_reorder set_upt)\n\nlemma num_colors_perm_coloring [simp]:\n  assumes \"perm_dom p = length \\<pi>\"\n  shows \"num_colors (perm_coloring p \\<pi>) = num_colors \\<pi>\"\n  using assms\n  unfolding num_colors_def\n  using length.rep_eq length_perm_coloring \n  by fastforce\n\nlemma colors_perm_coloring [simp]:\n  assumes \"perm_dom p = length \\<pi>\"\n  shows \"colors (perm_coloring p \\<pi>) = colors \\<pi>\"\n  using assms num_colors_def num_colors_perm_coloring\n  unfolding colors_def\n  by simp\n\nlemma perm_coloring_perm_id [simp]:\n  shows \"perm_coloring (perm_id (length \\<pi>)) \\<pi> = \\<pi>\"\n  by (simp add: color_list_inverse length.rep_eq perm_coloring_def) \n\nlemma perm_coloring_perm_comp:\n  assumes \"perm_dom p1 = length \\<pi>\" \"perm_dom p2 = length \\<pi>\"\n  shows \"perm_coloring (perm_comp p1 p2) \\<pi>  = \n         perm_coloring p1 (perm_coloring p2 \\<pi>)\"\n  using assms\n  unfolding perm_coloring_def\n  by (smt (verit, del_insts) color_list coloring_inverse length.rep_eq mem_Collect_eq perm_reorder_comp set_perm_reorder)\n\nlemma perm_coloring_perm_inv_comp1 [simp]:\n  assumes \"perm_dom p = length \\<pi>\"\n  shows \"perm_coloring (perm_inv p) (perm_coloring p \\<pi>) = \\<pi>\"\n  using assms\n  by (metis perm_coloring_perm_comp perm_coloring_perm_id perm_comp_perm_inv1 perm_dom_perm_inv)\n\nlemma perm_coloring_perm_inv_comp2 [simp]:\n  assumes \"perm_dom p = length \\<pi>\"\n  shows \"perm_coloring p (perm_coloring (perm_inv p) \\<pi>) = \\<pi>\"\n  using assms\n  by (metis perm_coloring_perm_inv_comp1 perm_dom_perm_inv perm_inv_inv)\n\nlemma perm_coloring_inj:\n  assumes \"length \\<pi> = perm_dom p\" \"length \\<pi>' = perm_dom p\" \n          \"perm_coloring p \\<pi> = perm_coloring p \\<pi>'\"\n  shows \"\\<pi> = \\<pi>'\"\n  using assms\n  by (metis perm_coloring_perm_inv_comp1) \n\nlemma cell_perm_coloring [simp]: \n  assumes \"perm_dom p = length \\<pi>\"\n  shows \"cell (perm_coloring p \\<pi>) c = perm_fun_set p (cell \\<pi> c)\" (is \"?lhs = ?rhs\")\nproof safe\n  fix x\n  assume \"x \\<in> ?lhs\"\n  then show \"x \\<in> ?rhs\"\n    using assms color_fun_perm_coloring_app\n    unfolding cell_def\n    by (smt (verit) comp_apply image_iff length_perm_coloring mem_Collect_eq perm_fun_perm_inv1 perm_fun_perm_inv_range perm_fun_set_def)\nnext\n  fix x\n  assume \"x \\<in> ?rhs\"\n  then show \"x \\<in> ?lhs\"\n    by (smt (verit, ccfv_SIG) assms cell_def image_iff length_perm_coloring mem_Collect_eq perm_coloring_perm_fun perm_comp_perm_inv2 perm_dom_perm_inv perm_fun_perm_inv_range perm_fun_set_def perm_inv_solve)\nqed\n\nlemma cells_perm_coloring [simp]:\n  assumes \"perm_dom p = length \\<pi>\"\n  shows \"cells (perm_coloring p \\<pi>) = map (perm_fun_set p) (cells \\<pi>)\"\n  using assms colors_perm_coloring\n  unfolding cells_def\n  by simp\n\nlemma discrete_perm_coloring [simp]:\n  assumes \"perm_dom p = length \\<pi>\"\n  shows \"discrete (perm_coloring p \\<pi>) \\<longleftrightarrow> discrete \\<pi>\"\n  using assms\n  unfolding discrete_def\n  by auto\n\nlemma perm_coloring_finer:\n  assumes \"\\<pi> \\<preceq> \\<pi>0\" \"perm_coloring \\<sigma> \\<pi> = \\<pi>\" \"perm_dom \\<sigma> = length \\<pi>\" \"perm_dom \\<sigma> = length \\<pi>0\"\n  shows \"perm_coloring \\<sigma> \\<pi>0 = \\<pi>0\"\nproof (rule coloring_eqI)\n  show \"\\<forall>v<length (perm_coloring \\<sigma> \\<pi>0). Coloring.color_fun (perm_coloring \\<sigma> \\<pi>0) v = Coloring.color_fun \\<pi>0 v\"\n  proof safe\n    fix v\n    assume \"v < length (perm_coloring \\<sigma> \\<pi>0)\"\n    then have \"Coloring.color_fun \\<pi> (perm_fun \\<sigma> v) = Coloring.color_fun \\<pi> v\"\n      using assms\n      by (metis length_perm_coloring perm_coloring_perm_fun)\n    then show \"Coloring.color_fun (perm_coloring \\<sigma> \\<pi>0) v = Coloring.color_fun \\<pi>0 v\"\n      using assms \\<open>v < Coloring.length (perm_coloring \\<sigma> \\<pi>0)\\<close>\n      by (smt (verit) color_fun_perm_coloring_app comp_def finer_same_color length_perm_coloring perm_fun_perm_inv_range)\n  qed\nnext\n  show \"Coloring.length (perm_coloring \\<sigma> \\<pi>0) = Coloring.length \\<pi>0\"\n    using assms\n    using length_perm_coloring\n    by blast\nqed\n\nlemma color_fun_to_coloring_perm [simp]:\n  assumes \"perm_dom p = n\" \"\\<exists> k. \\<pi> ` {0..<n} = {0..<k}\"\n  shows \"color_fun_to_coloring n (\\<pi> \\<circ> perm_fun (perm_inv p)) = \n         perm_coloring p (color_fun_to_coloring n \\<pi>)\" (is \"?lhs = ?rhs\")\nproof (rule coloring_eqI)\n  have *: \"\\<exists> k. (\\<pi> \\<circ> perm_fun (perm_inv p)) ` {0..<n} = {0..<k}\"\n    using assms\n    by (metis image_comp list.set_map perm_dom_perm_inv perm_fun_list_def perm_inv_perm_list perm_list_set set_upt) \n    \n  then show \"length ?lhs = length ?rhs\"\n    using assms\n    by simp\n    \n  show \"\\<forall> v < length ?lhs. color_fun ?lhs v = color_fun ?rhs v\"\n    using assms *\n    by (simp add: color_fun_perm_coloring_app perm_fun_perm_inv_range) \nqed\n\nlemma color_fun_to_coloring_perm':\n  assumes \"perm_dom p = n\" \"\\<exists> k. \\<pi> ` {0..<n} = {0..<k}\"\n          \"\\<forall> w < n. \\<pi>' (perm_fun p w) = \\<pi> w\"\n  shows \"color_fun_to_coloring n \\<pi>' = \n         perm_coloring p (color_fun_to_coloring n \\<pi>)\" (is \"?lhs = ?rhs\")\nproof (rule coloring_eqI)\n  obtain k where k: \"\\<pi> ` {0..<n} = {0..<k}\"\n    using assms\n    by auto\n  moreover\n  have \"\\<forall> w < n. \\<pi>' w = \\<pi> (perm_fun (perm_inv p) w)\"\n    using assms\n    by (metis perm_fun_perm_inv1 perm_fun_perm_inv_range) \n  moreover\n  have \"\\<forall> w < n. perm_fun (perm_inv p) w < n\"\n    using assms(1)\n    by (simp add: perm_fun_perm_inv_range)\n  ultimately\n  have \"\\<forall> w < n. \\<pi>' w < k\"\n    by auto\n  moreover\n  have \"\\<forall> c < k. \\<exists> w < n. \\<pi>' w = c\"\n  proof safe\n    fix c\n    assume \"c < k\"\n    then obtain w where \"w < n\" \"\\<pi> w = c\"\n      using k\n      by (metis (mono_tags, opaque_lifting) atLeastLessThan_iff image_iff le0) \n    then have \"\\<pi>' (perm_fun p w) = c\"\n      using assms(3) by blast\n    then show \"\\<exists>w<n. \\<pi>' w = c\"\n      using `w < n` assms(1)\n      by (metis perm_dom_perm_inv perm_fun_perm_inv_range perm_inv_inv)\n  qed\n  ultimately have *: \"\\<pi>' ` {0..<n} = {0..<k}\"\n    by auto\n  then have *: \"\\<exists> k. \\<pi>' ` {0..<n} = {0..<k}\"\n    by auto\n\n  show \"length ?lhs = length ?rhs\"\n    using assms *\n    by auto\n\n  show \"\\<forall> v < length ?lhs. color_fun ?lhs v = color_fun ?rhs v\"\n    using assms * \\<open>\\<forall>w<n. \\<pi>' w = \\<pi> (perm_fun (perm_inv p) w)\\<close> \n    by (simp add: color_fun_perm_coloring_app perm_fun_perm_inv_range)\nqed\n\nlemma tabulate_eq:\n  assumes \"(x1, y) \\<in> f1\" \"(x2, y) \\<in> f2\" \"\\<exists>! y. (x1, y) \\<in> f1\" \"\\<exists>! y. (x2, y) \\<in> f2\"\n  shows \"tabulate f1 x1 = tabulate f2 x2\"\n  using assms\n  by (metis tabulate_value) \n\nlemma cells_to_color_fun_perm_perm [simp]:\n  assumes \"cells_ok n cs\" \"perm_dom p = n\" \"w < n\"\n  shows \"cells_to_color_fun (map (perm_fun_set p) cs) (perm_fun p w) = cells_to_color_fun cs w\"\n  unfolding cells_to_color_fun_def\nproof (rule tabulate_eq)\n  let ?c = \"THE c. (w, c) \\<in> cells_to_color_fun_pairs cs\"\n  show \"(w, ?c) \\<in> cells_to_color_fun_pairs cs\"\n    using ex1_cells_to_color_fun_pairs[OF assms(1)] assms(3)\n    by (smt (verit, ccfv_threshold) the_equality)\n  show \"\\<exists>!y. (w, y) \\<in> cells_to_color_fun_pairs cs\"\n    using ex1_cells_to_color_fun_pairs[OF assms(1)] assms(3)\n    by simp\n\n  have \"cells_ok n (map (perm_fun_set p) cs)\" (is \"cells_ok n ?cs\")\n    unfolding cells_ok_def\n  proof safe\n    fix c\n    assume \"{} \\<in> set ?cs\"\n    then show False\n      using assms\n      by (metis cells_cells_to_coloring cells_non_empty cells_perm_coloring length_cells_to_coloring)\n  next\n    fix v C\n    assume \"v \\<in> C\" \"C \\<in> set ?cs\"\n    then obtain C' where \"v \\<in> perm_fun_set p C'\" \"C' \\<in> set cs\"\n      by auto\n    then obtain v' where \"v = perm_fun p v'\" \"v' \\<in> \\<Union> (set cs)\"\n      by (auto simp add: perm_fun_set_def)\n    then show \"v \\<in> {0..<n}\"\n      using assms\n      unfolding cells_ok_def\n      by (metis atLeastLessThan_iff in_set_conv_nth perm_dom.rep_eq perm_list_nth perm_list_set) \n  next\n    fix v\n    assume \"v \\<in> {0..<n}\"\n    then have \"perm_fun (perm_inv p) v \\<in> {0..<n}\"\n      using assms(2)\n      by (simp add: atLeast0LessThan perm_fun_perm_inv_range)\n    then obtain i where \"i < List.length cs\" \"perm_fun (perm_inv p) v \\<in> cs ! i\"\n      using `cells_ok n cs`\n      unfolding cells_ok_def\n      by (metis Union_iff index_of_in_set) \n    then show \"v \\<in> \\<Union> (set ?cs)\"\n      using assms(2)\n      by (smt (verit, ccfv_SIG) UnionI \\<open>v \\<in> {0..<n}\\<close> image_eqI in_set_conv_nth length_map nth_map nth_mem perm_comp_perm_inv2 perm_dom.rep_eq perm_dom_perm_inv perm_fun_perm_inv1 perm_fun_set_def perm_inv_solve perm_list_nth perm_list_set) \n  next\n    fix i j x\n    assume *: \"i < List.length ?cs\" \"j < List.length ?cs\" \"i \\<noteq> j\"\n              \"x \\<in> map (perm_fun_set p) cs ! i\" \"x \\<in> map (perm_fun_set p) cs ! j\"\n    then have \"\\<forall> x \\<in> cs ! i. x < n\" \"\\<forall> x \\<in> cs ! j. x < n\"\n      using `cells_ok n cs`\n      unfolding cells_ok_def\n      by auto\n    then have \"perm_fun (perm_inv p) x \\<in> cs ! i\" \"perm_fun (perm_inv p) x \\<in> cs ! j\"\n      using assms(1) perm_fun_inj[OF assms(2)] *\n      unfolding perm_fun_set_def \n      by (smt (verit) assms(2) image_iff length_map nth_map perm_dom_perm_inv perm_fun_perm_inv1 perm_inv_inv)+\n    then show \"x \\<in> {}\"\n      using assms *\n      unfolding cells_ok_def\n      by auto\n  qed\n\n  have \"perm_fun p w < n\"\n    using assms(2) assms(3)\n    by (metis perm_comp_perm_inv2 perm_dom_perm_inv perm_fun_perm_inv_range perm_inv_solve)\n  show \"\\<exists>!y. (perm_fun p w, y) \\<in> cells_to_color_fun_pairs (map (perm_fun_set p) cs)\"\n    using \\<open>cells_ok n (map (perm_fun_set p) cs)\\<close> \\<open>perm_fun p w < n\\<close> ex1_cells_to_color_fun_pairs \n    by presburger \n\n\n  show \"(perm_fun p w, ?c) \\<in> cells_to_color_fun_pairs (map (perm_fun_set p) cs)\"\n  proof-\n    have \"?c < List.length cs\"\n      using `(w, ?c) \\<in> cells_to_color_fun_pairs cs`\n      by (auto simp add: set_zip)\n    then have \"w \\<in> cs ! ?c\"\n      using assms(1) assms(3) \\<open>(w, THE c. (w, c) \\<in> cells_to_color_fun_pairs cs) \\<in> cells_to_color_fun_pairs cs\\<close> \\<open>\\<exists>!y. (w, y) \\<in> cells_to_color_fun_pairs cs\\<close> \n      by (metis cells_to_color_fun' cells_to_color_fun_def tabulate_value)\n    then have \"perm_fun p w \\<in> (map (perm_fun_set p) cs) ! ?c\"\n      using `?c < List.length cs`\n      unfolding perm_fun_set_def\n      by simp\n    then show ?thesis\n      using `?c < List.length cs`\n      using \\<open>\\<exists>!y. (perm_fun p w, y) \\<in> cells_to_color_fun_pairs (map (perm_fun_set p) cs)\\<close> \\<open>cells_ok n (map (perm_fun_set p) cs)\\<close> \n      by (metis cells_to_color_fun cells_to_color_fun_def length_map tabulate_value) \n  qed\nqed\n\nlemma cells_to_coloring_perm: \n  assumes \"cells_ok n cs\" \"perm_dom p = n\"\n  shows \"cells_to_coloring n (map (perm_fun_set p) cs) = \n         perm_coloring p (cells_to_coloring n cs)\"\n  using assms\n  unfolding cells_to_coloring_def\n  by (subst color_fun_to_coloring_perm') (auto simp add: cells_to_color_fun_image)\n\nlemma finer_perm_coloring [simp]:\n  assumes \"\\<pi> \\<preceq> \\<pi>'\" \"length \\<pi> = length \\<pi>'\" \"length \\<pi> = perm_dom p\"\n  shows \"perm_coloring p \\<pi> \\<preceq> perm_coloring p \\<pi>'\"\n  using assms\n  using color_fun.rep_eq color_fun_perm_coloring finer_def length.rep_eq length_perm_coloring perm_fun_perm_inv_range\n  by fastforce\n\nlemma finer_strict_perm_coloring: \n  assumes \"length \\<pi> = length \\<pi>'\" \"length \\<pi> = perm_dom p\"\n          \"\\<pi> \\<prec> \\<pi>'\" \n  shows \"perm_coloring p \\<pi> \\<prec> perm_coloring p \\<pi>'\"\nproof-\n  have \"perm_coloring p \\<pi> \\<noteq> perm_coloring p \\<pi>'\"\n    using assms\n    by (metis finer_strict_def perm_coloring_inj)\n  then show ?thesis\n    using assms\n    unfolding finer_strict_def\n    by auto\nqed\n\nlemma finer_strict_perm_coloring': \n  assumes  \"length \\<pi> = length \\<pi>'\" \"length \\<pi> = perm_dom p\"\n           \"perm_coloring p \\<pi> \\<prec> perm_coloring p \\<pi>'\"\n  shows \"\\<pi> \\<prec> \\<pi>'\"\n  using assms finer_strict_perm_coloring[of \"perm_coloring p \\<pi>\" \"perm_coloring p \\<pi>'\" \"perm_inv p\"]\n  by auto\n\n\nsubsection\\<open>Permute coloring based on its discrete refinement\\<close>\ndefinition \\<C> :: \"coloring \\<Rightarrow> coloring \\<Rightarrow> coloring\" where\n  \"\\<C> \\<pi> \\<alpha> \\<equiv> perm_coloring (discrete_coloring_perm \\<alpha>) \\<pi>\" \n\nlemma length_\\<C>:\n  assumes \"length \\<alpha> = length \\<pi>\" \"discrete \\<alpha>\"\n  shows \"length (\\<C> \\<pi> \\<alpha>) = length \\<pi>\"\n  using assms length_perm_coloring perm_dom_discrete_coloring_perm\n  unfolding \\<C>_def\n  by force\n\nlemma color_fun_\\<C>:\n  assumes \"length \\<alpha> = length \\<pi>\" \"discrete \\<alpha>\" \"v < length \\<pi>\"\n  shows \"color_fun (\\<C> \\<pi> \\<alpha>) v = (color_fun \\<pi> \\<circ> inv_n (length \\<alpha>) (color_fun \\<alpha>)) v\"\nproof-\n  have \"color_fun (\\<C> \\<pi> \\<alpha>) v = (color_fun \\<pi> \\<circ> perm_fun (perm_inv (make_perm (length \\<alpha>) (color_fun \\<alpha>)))) v\"\n    using assms\n    using color_fun_perm_coloring_app[of \"make_perm (length \\<alpha>) (color_fun \\<alpha>)\" \\<pi> v]\n    unfolding \\<C>_def discrete_coloring_perm_def\n    by (metis discrete_coloring_is_permutation perm_dom_make_perm)\n  then show ?thesis\n    by (smt (verit, best) assms(1) assms(2) assms(3) comp_apply discrete_coloring_is_permutation finer_length inv_n_def inv_perm_fun_def inv_perm_fun_perm_fun make_perm_inv_perm_fun perm_fun_make_perm)\nqed\n    \nlemma color_fun_\\<C>':\n  assumes \"length \\<alpha> = length \\<pi>\" \"discrete \\<alpha>\" \"v < length \\<pi>\"\n  shows \"color_fun (\\<C> \\<pi> \\<alpha>) (color_fun \\<alpha> v) = color_fun \\<pi> v\"\n  using assms\n  by (metis \\<C>_def discrete_coloring_is_permutation discrete_coloring_perm_def perm_coloring_perm_fun perm_dom_make_perm perm_fun_discrete_coloring_perm)\n\nlift_definition id_coloring :: \"nat => coloring\" is \"\\<lambda> n. [0..<n]\"\n  by auto\n\nlemma length_id_coloring [simp]:\n  shows \"length (id_coloring n) = n\"\n  by transfer auto\n\nlemma color_fun_id_coloring_app [simp]:\n  assumes \"v < n\"\n  shows \"color_fun (id_coloring n) v = v\"\n  using assms\n  by transfer auto\n\nlemma \\<C>_id_finer:\n  assumes \"finer \\<alpha> \\<pi>\" \"discrete \\<alpha>\"\n  shows \"finer (id_coloring (length \\<alpha>)) (\\<C> \\<pi> \\<alpha>)\"\n  unfolding finer_def\nproof safe\n  show \"length (id_coloring (length \\<alpha>)) = length (\\<C> \\<pi> \\<alpha>)\"\n    by (simp add: \\<C>_def assms(1) assms(2) discrete_coloring_perm_def finer_length)  \nnext\n  fix v w\n  assume lt: \"v < length (\\<C> \\<pi> \\<alpha>)\" \"w < length (\\<C> \\<pi> \\<alpha>)\"\n  assume \"color_fun (\\<C> \\<pi> \\<alpha>) v < color_fun (\\<C> \\<pi> \\<alpha>) w\"\n  then have \"v < w\"\n    by (smt (verit, ccfv_threshold) \\<C>_def assms(1) assms(2) color_fun_perm_coloring_app comp_apply discrete_coloring_is_permutation discrete_coloring_perm_def finer_def length_\\<C> lt(1) lt(2) perm_dom_make_perm perm_fun_perm_inv_range perm_inv_make_perm1)\n  then show \"color_fun (id_coloring (length \\<alpha>)) v < color_fun (id_coloring (length \\<alpha>)) w\"\n    using assms(1) assms(2) finer_def length_\\<C> lt(2) by auto\nqed\n\nlemma \\<C>_mono:\n  assumes \"finer \\<alpha> \\<pi>\" \"discrete \\<alpha>\" \n  assumes \"v < length \\<pi>\" \"w < length \\<pi>\" \"v \\<le> w\"\n  shows \"color_fun (\\<C> \\<pi> \\<alpha>) v \\<le> color_fun (\\<C> \\<pi> \\<alpha>) w\"\n  using assms\n  by (smt (verit, ccfv_SIG) \\<C>_def color_fun_perm_coloring_app comp_apply discrete_coloring_is_permutation discrete_coloring_perm_def finer_def le_antisym linorder_cases order.order_iff_strict perm_dom_make_perm perm_fun_perm_inv_range perm_inv_make_perm1)\n\nlemma \\<C>_colors [simp]:\n  assumes \"length \\<pi> = length \\<alpha>\" \"discrete \\<alpha>\"\n  shows \"colors (\\<C> \\<pi> \\<alpha>) = colors \\<pi>\"\n  using assms\n  unfolding \\<C>_def\n  by simp\n\nlemma \\<C>_0:\n  assumes \"finer \\<alpha> \\<pi>\" \"discrete \\<alpha>\" \"length \\<pi> > 0\"\n  shows \"color_fun (\\<C> \\<pi> \\<alpha>) 0 = 0\"\n  using assms\nproof-\n  let ?c = \"color_fun (\\<C> \\<pi> \\<alpha>)\"\n  have \"0 \\<in> set (colors \\<pi>)\"\n    using `length \\<pi> > 0`\n    by (metis color_fun_in_colors colors_def empty_iff ex_color gr_zeroI list.set(1) upt_eq_Nil_conv) \n  then have \"0 \\<in> set (colors (\\<C> \\<pi> \\<alpha>))\"\n    using assms\n    by (simp add: finer_def)\n  then obtain v where \"v < length (\\<C> \\<pi> \\<alpha>)\" \"?c v = 0\"\n    using ex_color_color_fun by blast \n  then show ?thesis\n    using \\<C>_mono[OF assms(1-2)]\n    by (metis (full_types) assms(1) assms(2) finer_length leI le_zero_eq length_\\<C> less_nat_zero_code)\nqed\n\nlemma \\<C>_consecutive_colors:\n  assumes \"finer \\<alpha> \\<pi>\" \"discrete \\<alpha>\"\n  assumes \"v + 1 < length \\<pi>\" \n  shows \"color_fun (\\<C> \\<pi> \\<alpha>) (v + 1) = (color_fun (\\<C> \\<pi> \\<alpha>) v) \\<or> \n         color_fun (\\<C> \\<pi> \\<alpha>) (v + 1) = (color_fun (\\<C> \\<pi> \\<alpha>) v) + 1\"\nproof-\n  let ?\\<alpha> = \"discrete_coloring_perm \\<alpha>\"\n  let ?c = \"color_fun (perm_coloring ?\\<alpha> \\<pi>)\"\n  have \"?c (v + 1) \\<ge> ?c v\"\n    using \\<C>_mono[OF assms(1-2)] assms(3)\n    unfolding \\<C>_def\n    by auto\n  moreover\n  have \"?c (v + 1) \\<le> ?c v + 1\"\n  proof (rule ccontr)\n    assume \"\\<not> ?thesis\"\n    then have \"?c (v + 1) > ?c v + 1\"\n      by simp\n\n    have \"\\<exists> w. w < length \\<pi> \\<and> ?c w = ?c v + 1\"\n    proof-\n      have \"?c (v + 1) \\<in> set (colors \\<pi>)\"\n        using \\<open>v + 1 < length \\<pi>\\<close>\n        by (metis assms(1) assms(2) color_fun_in_colors colors_perm_coloring finer_length length_perm_coloring perm_dom_discrete_coloring_perm)\n      then have \"?c v + 1 \\<in> set (colors \\<pi>)\"\n        using \\<open>?c v + 1 < ?c (v + 1)\\<close>\n        by (simp add: colors_def)\n      then show ?thesis\n        by (smt (verit, del_insts) assms(1) assms(2) colors_perm_coloring ex_color_color_fun finer_length length_perm_coloring perm_dom_discrete_coloring_perm)\n    qed\n    then obtain w where \"w < length \\<pi>\" \"?c w = ?c v + 1\"\n      by auto\n    have \"?c v < ?c w\" \"?c w < ?c (v + 1)\"\n      using \\<open>?c w = ?c v + 1\\<close>\n      using \\<open>?c v + 1 < ?c (v + 1)\\<close> \n      by auto\n    then have \"v < w \\<and> w < v + 1\"\n      by (metis \\<C>_def \\<C>_mono \\<open>w < length \\<pi>\\<close> add.commute assms(1) assms(2) assms(3) linorder_not_less trans_le_add2)\n    then show False\n      by auto\n  qed\n  ultimately\n  show ?thesis\n    using \\<C>_def by fastforce\nqed\n\nlemma \\<C>_cell:\n  assumes \"finer \\<alpha> \\<pi>\" \"discrete \\<alpha>\"\n  shows \"cell (\\<C> \\<pi> \\<alpha>) c = color_fun \\<alpha> ` cell \\<pi> c\"\nproof-\n  have \"is_perm_fun (length \\<alpha>) (color_fun \\<alpha>)\"\n    by (simp add: assms(2))\n\n  let ?c = \"color_fun (\\<C> \\<pi> \\<alpha>)\"\n  have \"cell (\\<C> \\<pi> \\<alpha>) c = {v. v < length (\\<C> \\<pi> \\<alpha>) \\<and> ?c v = c}\"\n    unfolding cell_def\n    by simp\n  also have \"... = {v. v < length \\<alpha> \\<and> ?c v = c}\"\n    using assms(1) assms(2) finer_length length_\\<C> by presburger\n  also have \"... = {color_fun \\<alpha> t | t. color_fun \\<alpha> t < length \\<alpha> \\<and> ?c (color_fun \\<alpha> t) = c}\"\n    using `is_perm_fun (length \\<alpha>) (color_fun \\<alpha>)`\n    by (metis perm_inv_make_perm1)\n  also have \"... = {color_fun \\<alpha> t | t. t < length \\<alpha> \\<and> ?c (color_fun \\<alpha> t) = c}\"\n    using `is_perm_fun (length \\<alpha>) (color_fun \\<alpha>)`\n    unfolding is_perm_fun_def bij_betw_def\n    by (metis (no_types, lifting) \\<open>is_perm_fun (length \\<alpha>) (color_fun \\<alpha>)\\<close> assms(2) atLeastLessThan_iff bot_nat_0.extremum discrete_coloring_perm_def image_eqI perm_dom_discrete_coloring_perm perm_fun_perm_inv_range perm_inv_make_perm1)\n  also have \"... = {color_fun \\<alpha> t | t. t < length \\<alpha> \\<and> color_fun \\<pi> t = c}\"\n    by (metis assms(1) assms(2) color_fun_\\<C>' finer_length)\n  also have \"... = color_fun \\<alpha> ` (cell \\<pi> c)\"\n    unfolding cell_def\n    using assms(1) finer_length by auto \n  finally\n  show ?thesis\n    .\nqed\n\nlemma \\<C>_card_cell:\n  assumes \"finer \\<alpha> \\<pi>\" \"discrete \\<alpha>\"\n  shows \"card (cell (\\<C> \\<pi> \\<alpha>) c) = card (cell \\<pi> c)\"\nproof (rule bij_betw_same_card[symmetric])\n  show \"bij_betw (color_fun \\<alpha>) (cell \\<pi> c) (cell (\\<C> \\<pi> \\<alpha>) c)\"\n    by (smt (verit) \\<C>_cell assms(1) assms(2) bij_betwI' cell_def discrete_coloring_is_permutation discrete_coloring_perm_def finer_length image_iff mem_Collect_eq perm_dom_discrete_coloring_perm perm_dom_perm_inv perm_fun_perm_inv1 perm_fun_perm_inv_range perm_inv_make_perm1)\nqed\n\nlemma \\<C>_\\<alpha>_independent':\n  assumes \"finer \\<alpha> \\<pi>\" \"discrete \\<alpha>\" \n  assumes \"finer \\<beta> \\<pi>\" \"discrete \\<beta>\" \n  assumes \"\\<forall> w \\<le> v. color_fun (\\<C> \\<pi> \\<alpha>) w = color_fun (\\<C> \\<pi> \\<beta>) w\" \"v + 1 < length \\<pi>\"\n  assumes \"color_fun (\\<C> \\<pi> \\<alpha>) (v + 1) = color_fun (\\<C> \\<pi> \\<alpha>) v + 1\"\n  shows \"color_fun (\\<C> \\<pi> \\<beta>) (v + 1) = color_fun (\\<C> \\<pi> \\<beta>) v + 1\"\nproof (rule ccontr)\n  let ?\\<alpha> = \"color_fun (\\<C> \\<pi> \\<alpha>)\"\n  let ?\\<beta> = \"color_fun (\\<C> \\<pi> \\<beta>)\"\n\n  assume \"\\<not> ?thesis\"\n  then have \"?\\<beta> (v + 1) = ?\\<beta> v\"\n    using \\<C>_consecutive_colors assms\n    by blast\n\n  let ?cell = \"\\<lambda> n C c. {v. v < n \\<and> color_fun C v = c}\"\n\n  have \"card (cell (\\<C> \\<pi> \\<beta>) (?\\<alpha> v)) > card (?cell (v + 1) (\\<C> \\<pi> \\<beta>) (?\\<alpha> v))\"\n  proof-\n    have \"?cell (v + 1) (\\<C> \\<pi> \\<beta>) (?\\<alpha> v) \\<union> {v + 1} \\<subseteq> cell (\\<C> \\<pi> \\<beta>) (?\\<alpha> v)\"\n      using \\<open>?\\<beta> (v + 1) = ?\\<beta> v\\<close>\n      using assms(3-6)\n      using finer_length length_\\<C>\n      unfolding cell_def\n      by auto \n      \n    moreover\n    have \"finite (cell (\\<C> \\<pi> \\<beta>) (?\\<alpha> v))\"\n      unfolding cell_def\n      by auto\n    ultimately\n    have \"card (?cell (v + 1) (\\<C> \\<pi> \\<beta>) (?\\<alpha> v) \\<union> {v + 1}) \\<le> card (cell (\\<C> \\<pi> \\<beta>) (?\\<alpha> v))\"\n      by (meson card_mono)\n    thus ?thesis\n      unfolding cell_def\n      by auto\n  qed\n\n  moreover\n\n  have \"\\<forall> y. v < y \\<and> y < length \\<pi> \\<longrightarrow> ?\\<alpha> v < ?\\<alpha> y\"\n    using assms\n    by (metis \\<C>_mono discrete)\n\n  then have \"card (cell (\\<C> \\<pi> \\<alpha>) (?\\<alpha> v)) = card (?cell (v + 1) (\\<C> \\<pi> \\<alpha>) (?\\<alpha> v))\"\n    unfolding cell_def\n    by (metis (no_types, lifting) assms(1) assms(2) assms(6) finer_length leD leI length_\\<C> less_add_one less_or_eq_imp_le order_less_le_trans)\n\n  moreover\n\n  have \"card (cell (\\<C> \\<pi> \\<alpha>) (?\\<alpha> v)) = card (cell (\\<C> \\<pi> \\<beta>) (?\\<alpha> v))\"\n    using assms\n    by (simp add: \\<C>_card_cell)\n\n  moreover\n\n  have \"?cell (v + 1) (\\<C> \\<pi> \\<alpha>) (?\\<alpha> v) = ?cell (v + 1) (\\<C> \\<pi> \\<beta>) (?\\<alpha> v)\"\n    using \\<open>\\<forall> w \\<le> v. color_fun (\\<C> \\<pi> \\<alpha>) w = color_fun  (\\<C> \\<pi> \\<beta>) w\\<close>\n    unfolding cell_def\n    by auto\n  then have \"card (?cell (v + 1) (\\<C> \\<pi> \\<alpha>) (?\\<alpha> v)) = card (?cell (v + 1) (\\<C> \\<pi> \\<beta>) (?\\<alpha> v))\"\n    by simp\n\n  ultimately\n\n  show False\n    by simp\nqed\n\nlemma \\<C>_\\<alpha>_independent:\n  assumes \"finer \\<alpha> \\<pi>\" \"discrete \\<alpha>\" \n  assumes \"finer \\<beta> \\<pi>\" \"discrete \\<beta>\" \n  assumes \"v < length \\<pi>\"\n  shows \"color_fun (\\<C> \\<pi> \\<alpha>) v = color_fun (\\<C> \\<pi> \\<beta>) v\"\n  using \\<open>v < length \\<pi>\\<close>\nproof (induction v rule: less_induct)\n  case (less v')\n  show ?case\n  proof (cases \"v' = 0\")\n    case True\n    then have \"Min {c. c < length \\<pi>} = 0\"\n      by (metis \\<open>v' < length \\<pi>\\<close> empty_Collect_eq eq_Min_iff finite_Collect_less_nat mem_Collect_eq zero_le)\n    then show ?thesis\n      using assms \\<C>_0 True\n      by simp\n  next\n    case False\n    then obtain v where \"v' = v + 1\"\n      by (metis add.commute add.left_neutral canonically_ordered_monoid_add_class.lessE less_one linorder_neqE_nat)\n    have ih: \"\\<forall> w \\<le> v. color_fun (\\<C> \\<pi> \\<alpha>) w = color_fun (\\<C> \\<pi> \\<beta>) w\"\n      using less.IH\n      using \\<open>v' = v + 1\\<close> less.prems by force\n    show ?thesis\n    proof (cases \"color_fun (\\<C> \\<pi> \\<alpha>) (v + 1) = color_fun (\\<C> \\<pi> \\<alpha>) v + 1\")\n      case True\n      then have \"color_fun (\\<C> \\<pi> \\<beta>) (v + 1) = color_fun (\\<C> \\<pi> \\<beta>) v + 1\"\n        using \\<C>_\\<alpha>_independent'[OF assms(1-4) ih]\n        using \\<open>v' = v + 1\\<close> less.prems by blast\n      thus ?thesis\n        using True \\<open>v' = v + 1\\<close>\n        using less.IH less.prems by auto\n    next\n      case False\n      then have \"color_fun (\\<C> \\<pi> \\<alpha>) (v + 1) = color_fun (\\<C> \\<pi> \\<alpha>) v\"\n        using \\<C>_consecutive_colors \\<open>v' = v + 1\\<close> assms(1) assms(2) assms(3) less.prems\n         by blast\n      have \"color_fun (\\<C> \\<pi> \\<beta>) (v + 1) = color_fun (\\<C> \\<pi> \\<beta>) v\"\n      proof (rule ccontr)\n        assume \"\\<not> ?thesis\"\n        then have \"color_fun (\\<C> \\<pi> \\<beta>) (v + 1) = color_fun (\\<C> \\<pi> \\<beta>) v + 1\"\n          using \\<C>_consecutive_colors \\<open>v' = v + 1\\<close> assms(1) assms(3) assms(4) less.prems\n           by blast\n        then have \"color_fun (\\<C> \\<pi> \\<alpha>) (v + 1) = color_fun (\\<C> \\<pi> \\<alpha>) v + 1\"\n          using \\<C>_\\<alpha>_independent'[OF assms(3-4) assms(1-2)] ih\n          using \\<open>v' = v + 1\\<close> less.prems \n          by presburger\n        then show False\n          using `color_fun (\\<C> \\<pi> \\<alpha>) (v + 1) = color_fun (\\<C> \\<pi> \\<alpha>) v`\n          by auto\n      qed\n      then show ?thesis\n        using \\<open>color_fun (\\<C> \\<pi> \\<alpha>) (v + 1) = color_fun (\\<C> \\<pi> \\<alpha>) v\\<close> \\<open>v' = v + 1\\<close> ih\n         by auto\n    qed\n  qed\nqed\n\n\nsubsection \\<open> Individualize \\<close>\n\ndefinition individualize_fun :: \"nat \\<Rightarrow> (nat \\<Rightarrow> color) \\<Rightarrow> nat \\<Rightarrow> (nat \\<Rightarrow> color)\" where \n  \"individualize_fun n \\<pi> v = \n    (if (\\<forall> w < n. w \\<noteq> v \\<longrightarrow> \\<pi> w \\<noteq> \\<pi> v) \n     then \\<pi> \n     else (\\<lambda> w. (if \\<pi> w < \\<pi> v \\<or> w = v then \\<pi> w else \\<pi> w + 1)))\"\n\ndefinition individualize :: \"coloring \\<Rightarrow> nat \\<Rightarrow> coloring\" where \n  \"individualize \\<pi> v = color_fun_to_coloring (length \\<pi>) (individualize_fun (length \\<pi>) (color_fun \\<pi>) v)\"\n\nlemma individualize_fun_all_colors [simp]:\n  assumes \"\\<exists> k. \\<pi> ` {0..<n} = {0..<k}\" \"v < n\"\n  shows \"\\<exists> k. individualize_fun n \\<pi> v ` {0..<n} = {0..<k}\"\n  using assms\nproof-\n  obtain k where k: \"\\<pi> ` {0..<n} = {0..<k}\"\n    using assms\n    by auto\n  show ?thesis\n  proof (cases \"\\<forall> w < n. w \\<noteq> v \\<longrightarrow> \\<pi> w \\<noteq> \\<pi> v\")\n    case True\n    then show ?thesis\n      using k\n      by (rule_tac x=\"k\" in exI) (simp add: individualize_fun_def)\n  next\n    case False\n    show ?thesis\n    proof (cases \"\\<forall> w < n. \\<pi> w < \\<pi> v \\<or> w = v\")\n      case True\n      then show ?thesis\n        using k\n        unfolding individualize_fun_def\n        by auto\n    next\n      case False\n      show ?thesis\n      proof (rule_tac x=\"k+1\" in exI, safe)\n        fix x\n        assume x: \"x \\<in> {0..<n}\"\n        show \"individualize_fun n \\<pi> v x \\<in> {0..<k + 1}\"\n        proof-\n          have \"individualize_fun n \\<pi> v x \\<le> \\<pi> x + 1\"\n            unfolding individualize_fun_def\n            by auto\n          moreover\n          have \"\\<pi> x + 1 < k + 1\"\n            using x k\n            by auto\n          ultimately\n          show ?thesis\n            by simp\n        qed\n      next\n        fix c\n        assume \"c \\<in> {0..<k+1}\"\n        have \"\\<pi> v < k\"\n          using `v < n` k\n          by auto\n        show \"c \\<in> individualize_fun n \\<pi> v ` {0..<n}\"\n        proof (cases \"c < \\<pi> v\")\n          case True\n          then show ?thesis\n            using `\\<not> (\\<forall>w<n. \\<pi> w < \\<pi> v \\<or> w = v)` \\<open>\\<pi> v < k\\<close> k\n            by (auto simp add: individualize_fun_def)\n        next\n          case False\n          show ?thesis\n          proof (cases \"c = \\<pi> v\")\n            case True\n            then have \"individualize_fun n \\<pi> v v = c\"\n              using `\\<not> (\\<forall>w<n. \\<pi> w < \\<pi> v \\<or> w = v)`\n              by (simp add: individualize_fun_def)\n            then show ?thesis\n               using `v < n`\n               by auto\n          next\n            case False\n            then have \"c > 0\" \"c > \\<pi> v\"\n              using `\\<not> (c < \\<pi> v)`\n              by auto\n            then have \"c - 1 \\<in> {0..<k}\"\n              using `c \\<in> {0..<k+1}`\n              by auto\n            then obtain w where \"w < n\" \"\\<pi> w = c - 1\" \"w \\<noteq> v\"\n              using k `\\<not> (\\<forall>w<n. w \\<noteq> v \\<longrightarrow> \\<pi> w \\<noteq> \\<pi> v)` `c > \\<pi> v` `c > 0`\n              by (smt (verit) add_0 diff_zero imageE in_set_conv_nth length_upt nth_upt set_upt)\n            then have \"individualize_fun n \\<pi> v w = c\"\n              using `\\<not> (\\<forall>w<n. w \\<noteq> v \\<longrightarrow> \\<pi> w \\<noteq> \\<pi> v)` `c > 0` \\<open>\\<pi> v < c\\<close>\n               by (auto simp add: individualize_fun_def)\n            then show ?thesis\n              using `w < n`\n              by auto\n            qed\n          qed\n        qed\n      qed\n    qed\n  qed\n\nlemma individualize_fun_finer [simp]:\n  assumes \"v < n\" \"v1 < n\" \"v2 < n\" \n          \"\\<pi> v1 < \\<pi> v2\" \n  shows   \"individualize_fun n \\<pi> v v1 < individualize_fun n \\<pi> v v2\"\n  using assms\n  unfolding individualize_fun_def\n  by auto\n\nlemma individualize_finer [simp]:\n  assumes \"v < length \\<pi>\"\n  shows \"finer (individualize \\<pi> v) \\<pi>\"\n  using assms\n  unfolding finer_def individualize_def\n  by auto\n\nlemma individualize_length [simp]:\n  assumes \"v < length \\<pi>\"\n  shows \"length (individualize \\<pi> v) = length \\<pi>\"\n  using assms\n  using finer_length individualize_finer\n  by blast\n\nlemma individualize_fun_retains_color [simp]:\n  assumes \"v < n\" \n  shows \"individualize_fun n \\<pi> v v = \\<pi> v\"\n  using assms\n  by (simp add: individualize_fun_def)\n\nlemma individualize_retains_color:\n  assumes \"v < length \\<pi>\" \n  shows \"color_fun \\<pi> v \\<in> set (colors (individualize \\<pi> v))\"\n  using assms\n  unfolding individualize_def all_colors\n  by force\n\nlemma individualize_fun_cell_v [simp]:\n  assumes \"v < n\"\n  shows \"{w. w < n \\<and> individualize_fun n \\<pi> v w = \\<pi> v} = {v}\"\n  using assms\n  by (auto simp add: individualize_fun_def)\n\nlemma individualize_fun_cell_v':\n  assumes \"v < n\" \"w < n\" \"individualize_fun n \\<pi> v w = \\<pi> v\"\n  shows \"w = v\"\nproof-\n  have \"w \\<in> {w. w < n \\<and> individualize_fun n \\<pi> v w = \\<pi> v}\"\n    using assms\n    by blast\n  then show ?thesis\n    using `v < n`\n    by simp\nqed\n\nlemma individualize_cell_v [simp]:\n  assumes \"v < length \\<pi>\"\n  shows \"cell (individualize \\<pi> v) (color_fun \\<pi> v) = {v}\"\n  using \\<open>v < length \\<pi>\\<close>  \n  unfolding cell_def individualize_def\n  by (auto simp add: individualize_fun_cell_v')\n\nlemma individualize_singleton:\n  assumes \"v < length \\<pi>\"\n  shows \"{v} \\<in> set (cells (individualize \\<pi> v))\"\n  using assms individualize_retains_color\n  unfolding cells_def\n  by force\n\nlemma individualize_singleton_preserve:\n  assumes \"{v'} \\<in> set (cells \\<pi>)\" \"v' < length \\<pi>\" \"v < length \\<pi>\"\n  shows \"{v'} \\<in> set (cells (individualize \\<pi> v))\"\n  using assms finer_singleton individualize_finer\n  by blast\n\nlemma individualize_fun_perm [simp]:\n  assumes \"perm_dom p = length \\<pi>\" \"v < length \\<pi>\" \"w < length \\<pi>\"\n  shows \"individualize_fun (length (perm_coloring p \\<pi>)) (color_fun (perm_coloring p \\<pi>)) (perm_fun p v) (perm_fun p w) =\n         individualize_fun (length \\<pi>) (color_fun \\<pi>) v w\"\n  using assms\n  unfolding individualize_fun_def\n  by (smt (verit, ccfv_SIG) color_fun_perm_coloring_app comp_apply length_perm_coloring perm_dom_perm_inv perm_fun_perm_inv1 perm_fun_perm_inv_range) \n\nlemma individualize_perm [simp]:\n  assumes \"perm_dom p = length \\<pi>\" \"v < length \\<pi>\"\n  shows \"individualize (perm_coloring p \\<pi>) (perm_fun p v) =\n         perm_coloring p (individualize \\<pi> v)\"\n  using assms individualize_fun_perm color_fun_to_coloring_perm' color_fun_all_colors individualize_fun_all_colors\n  unfolding individualize_def\n  by auto\n\nend", "meta": {"author": "milanbankovic", "repo": "isocert", "sha": "0b160702bc0196739915541478fdfc9bb67a35db", "save_path": "github-repos/isabelle/milanbankovic-isocert", "path": "github-repos/isabelle/milanbankovic-isocert/isocert-0b160702bc0196739915541478fdfc9bb67a35db/thy/Coloring.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8918110425624792, "lm_q2_score": 0.8376199714402813, "lm_q1q2_score": 0.7469987400013114}}
{"text": "(*\n  File:         PAC_Specification.thy\n  Author:       Mathias Fleury, Daniela Kaufmann, JKU\n  Maintainer:   Mathias Fleury, JKU\n*)\ntheory PAC_Specification\n  imports PAC_More_Poly\nbegin\n\n\nsection \\<open>Specification of the PAC checker\\<close>\n\nsubsection \\<open>Ideals\\<close>\n\ntype_synonym int_poly = \\<open>int mpoly\\<close>\ndefinition polynomial_bool :: \\<open>int_poly set\\<close> where\n  \\<open>polynomial_bool = (\\<lambda>c. Var c ^ 2 - Var c) ` UNIV\\<close>\n\ndefinition pac_ideal where\n  \\<open>pac_ideal A \\<equiv> ideal (A \\<union> polynomial_bool)\\<close>\n\nlemma X2_X_in_pac_ideal:\n  \\<open>Var c ^ 2 - Var c \\<in> pac_ideal A\\<close>\n  unfolding polynomial_bool_def pac_ideal_def\n  by (auto intro: ideal.span_base)\n\nlemma pac_idealI1[intro]:\n  \\<open>p \\<in> A \\<Longrightarrow> p \\<in> pac_ideal A\\<close>\n  unfolding pac_ideal_def\n  by (auto intro: ideal.span_base)\n\nlemma pac_idealI2[intro]:\n  \\<open>p \\<in> ideal A \\<Longrightarrow> p \\<in> pac_ideal A\\<close>\n  using ideal.span_subspace_induct pac_ideal_def by blast\n\nlemma pac_idealI3[intro]:\n  \\<open>p \\<in> ideal A \\<Longrightarrow> p*q \\<in> pac_ideal A\\<close>\n  by (metis ideal.span_scale mult.commute pac_idealI2)\n\n\n\nlemma diff_in_polynomial_bool_pac_idealI:\n   assumes a1: \"p \\<in> pac_ideal A\"\n   assumes a2: \"p - p' \\<in> More_Modules.ideal polynomial_bool\"\n   shows \\<open>p' \\<in> pac_ideal A\\<close>\n proof -\n   have \"insert p polynomial_bool \\<subseteq> pac_ideal A\"\n     using a1 unfolding pac_ideal_def by (meson ideal.span_superset insert_subset le_sup_iff)\n   then show ?thesis\n     using a2 unfolding pac_ideal_def by (metis (no_types) ideal.eq_span_insert_eq ideal.span_subset_spanI ideal.span_superset insert_subset subsetD)\nqed\n\nlemma diff_in_polynomial_bool_pac_idealI2:\n   assumes a1: \"p \\<in> A\"\n   assumes a2: \"p - p' \\<in> More_Modules.ideal polynomial_bool\"\n   shows \\<open>p' \\<in> pac_ideal A\\<close>\n   using diff_in_polynomial_bool_pac_idealI[OF _ assms(2), of A] assms(1)\n   by (auto simp: ideal.span_base)\n\nlemma pac_ideal_alt_def:\n  \\<open>pac_ideal A = ideal (A \\<union> ideal polynomial_bool)\\<close>\n  unfolding pac_ideal_def\n  by (meson ideal.span_eq ideal.span_mono ideal.span_superset le_sup_iff subset_trans sup_ge2)\n\ntext \\<open>\n\n  The equality on ideals is restricted to polynomials whose variable\n  appear in the set of ideals. The function restrict sets:\n\n\\<close>\ndefinition restricted_ideal_to where\n  \\<open>restricted_ideal_to B A = {p \\<in> A. vars p  \\<subseteq> B}\\<close>\n\nabbreviation restricted_ideal_to\\<^sub>I where\n  \\<open>restricted_ideal_to\\<^sub>I B A \\<equiv> restricted_ideal_to B (pac_ideal (set_mset A))\\<close>\n\nabbreviation restricted_ideal_to\\<^sub>V where\n  \\<open>restricted_ideal_to\\<^sub>V B \\<equiv> restricted_ideal_to (\\<Union>(vars ` set_mset B))\\<close>\n\nabbreviation restricted_ideal_to\\<^sub>V\\<^sub>I where\n  \\<open>restricted_ideal_to\\<^sub>V\\<^sub>I B A \\<equiv> restricted_ideal_to (\\<Union>(vars ` set_mset B)) (pac_ideal (set_mset A))\\<close>\n\n\nlemma restricted_idealI:\n  \\<open>p \\<in> pac_ideal (set_mset A) \\<Longrightarrow> vars p \\<subseteq> C \\<Longrightarrow> p \\<in> restricted_ideal_to\\<^sub>I C A\\<close>\n  unfolding restricted_ideal_to_def\n  by auto\n\nlemma pac_ideal_insert_already_in:\n  \\<open>pq \\<in> pac_ideal (set_mset A) \\<Longrightarrow> pac_ideal (insert pq (set_mset A)) = pac_ideal (set_mset A)\\<close>\n  by (auto simp: pac_ideal_alt_def ideal.span_insert_idI)\n\nlemma pac_ideal_add:\n  \\<open>p \\<in># A \\<Longrightarrow> q \\<in># A \\<Longrightarrow> p + q \\<in> pac_ideal (set_mset A)\\<close>\n  by (simp add: ideal.span_add ideal.span_base pac_ideal_def)\nlemma pac_ideal_mult:\n  \\<open>p \\<in># A \\<Longrightarrow> p * q \\<in> pac_ideal (set_mset A)\\<close>\n  by (simp add: ideal.span_base pac_idealI3)\n\nlemma pac_ideal_mono:\n  \\<open>A \\<subseteq> B \\<Longrightarrow> pac_ideal A \\<subseteq> pac_ideal B\\<close>\n  using ideal.span_mono[of \\<open>A \\<union> _\\<close> \\<open>B \\<union> _\\<close>]\n  by (auto simp: pac_ideal_def intro: ideal.span_mono)\n\n\nsubsection \\<open>PAC Format\\<close>\n\ntext \\<open>The PAC format contains three kind of steps:\n  \\<^item> \\<^verbatim>\\<open>add\\<close> that adds up two polynomials that are known.\n  \\<^item> \\<^verbatim>\\<open>mult\\<close> that multiply a known polynomial with another one.\n  \\<^item> \\<^verbatim>\\<open>del\\<close> that removes a polynomial that cannot be reused anymore.\n\nTo model the simplification that happens, we add the \\<^term>\\<open>p - p' \\<in> polynomial_bool\\<close>\nstating that \\<^term>\\<open>p\\<close> and  \\<^term>\\<open>p'\\<close> are equivalent.\n\\<close>\n\ntype_synonym pac_st = \\<open>(nat set \\<times> int_poly multiset)\\<close>\n\ninductive PAC_Format :: \\<open>pac_st \\<Rightarrow> pac_st \\<Rightarrow> bool\\<close> where\nadd:\n  \\<open>PAC_Format (\\<V>, A) (\\<V>, add_mset p' A)\\<close>\nif\n   \\<open>p \\<in># A\\<close> \\<open>q \\<in># A\\<close>\n   \\<open>p+q - p' \\<in> ideal polynomial_bool\\<close>\n   \\<open>vars p' \\<subseteq> \\<V>\\<close> |\nmult:\n  \\<open>PAC_Format (\\<V>, A) (\\<V>, add_mset p' A)\\<close>\nif\n   \\<open>p \\<in># A\\<close>\n   \\<open>p*q - p' \\<in> ideal polynomial_bool\\<close>\n   \\<open>vars p' \\<subseteq> \\<V>\\<close>\n   \\<open>vars q \\<subseteq> \\<V>\\<close> |\ndel:\n   \\<open>p \\<in># A \\<Longrightarrow> PAC_Format (\\<V>, A) (\\<V>, A - {#p#})\\<close> |\nextend_pos:\n  \\<open>PAC_Format (\\<V>, A) (\\<V> \\<union> {x' \\<in> vars (-Var x + p'). x' \\<notin> \\<V>}, add_mset (-Var x + p') A)\\<close>\n  if\n    \\<open>(p')\\<^sup>2 - p' \\<in> ideal polynomial_bool\\<close>\n    \\<open>vars p' \\<subseteq> \\<V>\\<close>\n    \\<open>x \\<notin> \\<V>\\<close>\n\ntext  \\<open>\n  In the PAC format above, we have a technical condition on the\n  normalisation: \\<^term>\\<open>vars p' \\<subseteq> vars (p + q)\\<close> is here to ensure that\n  we don't normalise \\<^term>\\<open>0 :: int mpoly\\<close> to  \\<^term>\\<open>Var x^2 - Var x :: int mpoly\\<close>\n  for a new variable \\<^term>\\<open>x :: nat\\<close>. This is completely obvious for the normalisation\n  process we have in mind when we write the specification, but we must add it\n  explicitly because we are too general.\n\\<close>\n\nlemmas  PAC_Format_induct_split =\n   PAC_Format.induct[split_format(complete), of V A V' A' for V A V' A']\n\nlemma PAC_Format_induct[consumes 1, case_names add mult del ext]:\n  assumes\n    \\<open>PAC_Format (\\<V>, A) (\\<V>', A')\\<close> and\n    cases:\n      \\<open>\\<And>p q p'  A \\<V>. p \\<in># A \\<Longrightarrow> q \\<in># A \\<Longrightarrow> p+q - p' \\<in> ideal polynomial_bool \\<Longrightarrow> vars p' \\<subseteq> \\<V> \\<Longrightarrow> P \\<V> A \\<V> (add_mset p' A)\\<close>\n      \\<open>\\<And>p q p' A \\<V>. p \\<in># A \\<Longrightarrow> p*q - p' \\<in> ideal polynomial_bool \\<Longrightarrow> vars p' \\<subseteq> \\<V> \\<Longrightarrow> vars q \\<subseteq> \\<V> \\<Longrightarrow>\n        P \\<V> A \\<V> (add_mset p' A)\\<close>\n      \\<open>\\<And>p A \\<V>. p \\<in># A \\<Longrightarrow> P \\<V> A \\<V> (A - {#p#})\\<close>\n      \\<open>\\<And>p' x r.\n        (p')^2 - (p') \\<in> ideal polynomial_bool \\<Longrightarrow> vars p' \\<subseteq> \\<V> \\<Longrightarrow>\n        x \\<notin> \\<V> \\<Longrightarrow> P \\<V> A (\\<V> \\<union> {x' \\<in> vars (p' - Var x). x' \\<notin> \\<V>}) (add_mset (p' -Var x) A)\\<close>\n  shows\n     \\<open>P \\<V> A \\<V>' A'\\<close>\n  using assms(1) apply -\n  by (induct V\\<equiv>\\<V> A\\<equiv>A \\<V>' A' rule: PAC_Format_induct_split)\n   (auto intro: assms(1) cases)\n\n\ntext \\<open>\n\nThe theorem below (based on the proof ideal by Manuel Kauers) is the\ncorrectness theorem of extensions. Remark that the assumption \\<^term>\\<open>vars\nq \\<subseteq> \\<V>\\<close> is only used to show that \\<^term>\\<open>x' \\<notin> vars q\\<close>.\n\n\\<close>\nlemma extensions_are_safe:\n  assumes \\<open>x' \\<in> vars p\\<close> and\n    x': \\<open>x' \\<notin> \\<V>\\<close> and\n    \\<open>\\<Union> (vars ` set_mset A) \\<subseteq> \\<V>\\<close> and\n    p_x_coeff: \\<open>coeff p (monomial (Suc 0) x') = 1\\<close> and\n    vars_q: \\<open>vars q \\<subseteq> \\<V>\\<close> and\n    q: \\<open>q \\<in> More_Modules.ideal (insert p (set_mset A \\<union> polynomial_bool))\\<close> and\n    leading: \\<open>x' \\<notin> vars (p - Var x')\\<close> and\n    diff: \\<open>(Var x' - p)\\<^sup>2 - (Var x' - p) \\<in> More_Modules.ideal polynomial_bool\\<close>\n  shows\n    \\<open>q \\<in> More_Modules.ideal (set_mset A \\<union> polynomial_bool)\\<close>\nproof -\n  define p' where \\<open>p' \\<equiv> p - Var x'\\<close>\n  let ?v = \\<open>Var x' :: int mpoly\\<close>\n  have p_p': \\<open>p = ?v + p'\\<close>\n    by (auto simp: p'_def)\n  define q' where \\<open>q' \\<equiv> Var x' - p\\<close>\n  have q_q': \\<open>p = ?v - q'\\<close>\n    by (auto simp: q'_def)\n  have diff: \\<open>q'^2 - q' \\<in> More_Modules.ideal polynomial_bool\\<close>\n    using diff unfolding q_q' by auto\n\n  have [simp]: \\<open>vars ((Var c)\\<^sup>2 - Var c :: int mpoly) = {c}\\<close> for c\n    apply (auto simp: vars_def Var_def Var\\<^sub>0_def mpoly.MPoly_inverse keys_def lookup_minus_fun\n      lookup_times_monomial_right single.rep_eq split: if_splits)\n    apply (auto simp: vars_def Var_def Var\\<^sub>0_def mpoly.MPoly_inverse keys_def lookup_minus_fun\n      lookup_times_monomial_right single.rep_eq when_def ac_simps adds_def lookup_plus_fun\n      power2_eq_square times_mpoly.rep_eq minus_mpoly.rep_eq split: if_splits)\n    apply (rule_tac x = \\<open>(2 :: nat \\<Rightarrow>\\<^sub>0 nat) * monomial (Suc 0) c\\<close> in exI)\n    apply (auto dest: monomial_0D simp: plus_eq_zero_2 lookup_plus_fun mult_2)\n    by (meson Suc_neq_Zero monomial_0D plus_eq_zero_2)\n\n\n  have eq: \\<open>More_Modules.ideal (insert p (set_mset A \\<union> polynomial_bool)) =\n      More_Modules.ideal (insert p (set_mset A \\<union> (\\<lambda>c. Var c ^ 2 - Var c) ` {c. c \\<noteq> x'}))\\<close>\n      (is \\<open>?A = ?B\\<close> is \\<open>_ = More_Modules.ideal ?trimmed\\<close>)\n  proof -\n     let ?C = \\<open>insert p (set_mset A \\<union> (\\<lambda>c. Var c ^ 2 - Var c) ` {c. c \\<noteq> x'})\\<close>\n     let ?D = \\<open>(\\<lambda>c. Var c ^ 2 - Var c) ` {c. c \\<noteq> x'}\\<close>\n     have diff: \\<open>q'^2 - q' \\<in> More_Modules.ideal ?D\\<close> (is \\<open>?q \\<in> _\\<close>)\n     proof -\n       obtain r t where\n         q: \\<open>?q = (\\<Sum>a\\<in>t. r a * a)\\<close> and\n         fin_t: \\<open>finite t\\<close> and\n         t: \\<open>t \\<subseteq> polynomial_bool\\<close>\n         using diff unfolding ideal.span_explicit\n         by auto\n       show ?thesis\n       proof (cases \\<open>?v^2-?v \\<notin> t\\<close>)\n         case True\n         then show \\<open>?thesis\\<close>\n           using q fin_t t unfolding ideal.span_explicit\n           by (auto intro!: exI[of _ \\<open>t - {?v^2 -?v}\\<close>] exI[of _ r]\n             simp: polynomial_bool_def sum_diff1)\n        next\n          case False\n          define t' where \\<open>t' = t - {?v^2 - ?v}\\<close>\n          have t_t': \\<open>t = insert (?v^2 - ?v) t'\\<close> and\n            notin: \\<open>?v^2 - ?v \\<notin> t'\\<close> and\n            \\<open>t' \\<subseteq> (\\<lambda>c. Var c ^ 2 - Var c) ` {c. c \\<noteq> x'}\\<close>\n            using False t unfolding t'_def polynomial_bool_def by auto\n          have mon: \\<open>monom (monomial (Suc 0) x') 1 = Var x'\\<close>\n            by (auto simp: coeff_def minus_mpoly.rep_eq Var_def Var\\<^sub>0_def monom_def\n              times_mpoly.rep_eq lookup_minus lookup_times_monomial_right mpoly.MPoly_inverse)\n          then have \\<open>\\<forall>a. \\<exists>g h. r a = ?v * g + h \\<and> x' \\<notin> vars h\\<close>\n            using polynomial_split_on_var[of \\<open>r _\\<close> x']\n            by metis\n          then obtain g h where\n            r: \\<open>r a = ?v * g a + h a\\<close> and\n            x'_h: \\<open>x' \\<notin> vars (h a)\\<close> for a\n            using polynomial_split_on_var[of \\<open>r a\\<close> x']\n            by metis\n          have  \\<open>?q = ((\\<Sum>a\\<in>t'. g a * a) + r (?v^2-?v) * (?v - 1)) * ?v + (\\<Sum>a\\<in>t'. h a * a)\\<close>\n            using fin_t notin unfolding t_t' q r\n            by (auto simp: field_simps comm_monoid_add_class.sum.distrib\n              power2_eq_square ideal.scale_left_commute sum_distrib_left)\n          moreover have \\<open>x' \\<notin> vars ?q\\<close>\n            by (metis (no_types, opaque_lifting) Groups.add_ac(2) Un_iff add_diff_cancel_left'\n              diff_minus_eq_add in_mono leading q'_def semiring_normalization_rules(29)\n              vars_in_right_only vars_mult)\n          moreover {\n            have \\<open>x' \\<notin> (\\<Union>m\\<in>t' - {?v^2-?v}. vars (h m * m))\\<close>\n              using fin_t x'_h vars_mult[of \\<open>h _\\<close>] \\<open>t \\<subseteq> polynomial_bool\\<close>\n              by (auto simp: polynomial_bool_def t_t' elim!: vars_unE)\n            then have \\<open>x' \\<notin> vars (\\<Sum>a\\<in>t'. h a * a)\\<close>\n              using vars_setsum[of \\<open>t'\\<close> \\<open>\\<lambda>a. h a * a\\<close>] fin_t x'_h t notin\n              by (auto simp: t_t')\n          }\n          ultimately have \\<open>?q = (\\<Sum>a\\<in>t'. h a * a)\\<close>\n            unfolding mon[symmetric]\n            by (rule polynomial_decomp_alien_var(2)[unfolded])\n          then show ?thesis\n            using t fin_t \\<open>t' \\<subseteq> (\\<lambda>c. Var c ^ 2 - Var c) ` {c. c \\<noteq> x'}\\<close>\n            unfolding ideal.span_explicit t_t'\n            by auto\n       qed\n    qed\n    have eq1: \\<open>More_Modules.ideal (insert p (set_mset A \\<union> polynomial_bool)) =\n      More_Modules.ideal (insert (?v^2 - ?v) ?C)\\<close>\n      (is \\<open>More_Modules.ideal _ = More_Modules.ideal (insert _ ?C)\\<close>)\n      by (rule arg_cong[of _ _ More_Modules.ideal])\n       (auto simp: polynomial_bool_def)\n    moreover have \\<open>?v^2 - ?v \\<in> More_Modules.ideal ?C\\<close>\n    proof -\n      have \\<open>?v - q' \\<in> More_Modules.ideal ?C\\<close>\n        by (auto simp: q_q' ideal.span_base)\n      from ideal.span_scale[OF this, of \\<open>?v + q' - 1\\<close>] have \\<open>(?v - q') * (?v + q' - 1) \\<in> More_Modules.ideal ?C\\<close>\n        by (auto simp: field_simps)\n      moreover have \\<open>q'^2 - q' \\<in> More_Modules.ideal ?C\\<close>\n        using diff by (smt (verit) Un_insert_right ideal.span_mono insert_subset subsetD sup_ge2)\n      ultimately have \\<open>(?v - q') * (?v + q' - 1) + (q'^2 - q') \\<in> More_Modules.ideal ?C\\<close>\n        by (rule ideal.span_add)\n      moreover have \\<open>?v^2 - ?v = (?v - q') * (?v + q' - 1) + (q'^2 - q')\\<close>\n        by (auto simp: p'_def q_q' field_simps power2_eq_square)\n      ultimately show ?thesis by simp\n    qed\n    ultimately show ?thesis\n      using ideal.span_insert_idI by blast\n  qed\n\n  have \\<open>n < m \\<Longrightarrow> n > 0 \\<Longrightarrow> \\<exists>q. ?v^n = ?v + q * (?v^2 - ?v)\\<close> for n m :: nat\n  proof (induction m arbitrary: n)\n    case 0\n    then show ?case by auto\n  next\n    case (Suc m n) note IH = this(1-)\n    consider\n      \\<open>n < m\\<close> |\n      \\<open>m = n\\<close> \\<open>n > 1\\<close> |\n      \\<open>n = 1\\<close>\n      using IH\n      by (cases \\<open>n < m\\<close>; cases n) auto\n    then show ?case\n    proof cases\n      case 1\n      then show ?thesis using IH by auto\n    next\n      case 2\n      have eq: \\<open>?v^(n) = ((?v :: int mpoly) ^ (n-2)) * (?v^2-?v) + ?v^(n-1)\\<close>\n        using 2 by (auto simp: field_simps power_eq_if\n          ideal.scale_right_diff_distrib)\n      obtain q where\n        q: \\<open>?v^(n-1) = ?v + q * (?v^2 - ?v)\\<close>\n        using IH(1)[of \\<open>n-1\\<close>] 2\n        by auto\n      show ?thesis\n        using q unfolding eq\n        by (auto intro!: exI[of _ \\<open>Var x' ^ (n - 2) + q\\<close>] simp: distrib_right)\n    next\n      case 3\n      then show \\<open>?thesis\\<close>\n        by auto\n    qed\n  qed\n\n  obtain r t where\n    q: \\<open>q = (\\<Sum>a\\<in>t. r a * a)\\<close> and\n    fin_t: \\<open>finite t\\<close> and\n    t: \\<open>t \\<subseteq> ?trimmed\\<close>\n    using q unfolding eq unfolding ideal.span_explicit\n    by auto\n\n\n  define t' where \\<open>t' \\<equiv> t - {p}\\<close>\n  have t': \\<open>t = (if p \\<in> t then insert p t' else t')\\<close> and\n    t''[simp]: \\<open>p \\<notin> t'\\<close>\n    unfolding t'_def by auto\n  show ?thesis\n  proof (cases \\<open>r p = 0 \\<or> p \\<notin> t\\<close>)\n    case True\n    have\n      q: \\<open>q = (\\<Sum>a\\<in>t'. r a * a)\\<close> and\n     fin_t: \\<open>finite t'\\<close> and\n      t: \\<open>t' \\<subseteq> set_mset A \\<union> polynomial_bool\\<close>\n      using q fin_t t True t''\n      apply (subst (asm) t')\n      apply (auto intro: sum.cong simp: sum.insert_remove t'_def)\n      using q fin_t t True t''\n      apply (auto intro: sum.cong simp: sum.insert_remove t'_def polynomial_bool_def)\n      done\n    then show ?thesis\n      by (auto simp: ideal.span_explicit)\n  next\n    case False\n    then have \\<open>r p \\<noteq> 0\\<close> and \\<open>p \\<in> t\\<close>\n      by auto\n    then have t: \\<open>t = insert p t'\\<close>\n      by (auto simp: t'_def)\n\n   have \\<open>x' \\<notin> vars (- p')\\<close>\n     using leading p'_def vars_in_right_only by fastforce\n   have mon: \\<open>monom (monomial (Suc 0) x') 1 = Var x'\\<close>\n     by (auto simp:coeff_def minus_mpoly.rep_eq Var_def Var\\<^sub>0_def monom_def\n       times_mpoly.rep_eq lookup_minus lookup_times_monomial_right mpoly.MPoly_inverse)\n   then have \\<open>\\<forall>a. \\<exists>g h. r a = (?v + p') * g + h \\<and> x' \\<notin> vars h\\<close>\n     using polynomial_split_on_var2[of x' \\<open>-p'\\<close> \\<open>r _\\<close>]  \\<open>x' \\<notin> vars (- p')\\<close>\n     by (metis diff_minus_eq_add)\n   then obtain g h where\n     r: \\<open>r a = p * g a + h a\\<close> and\n     x'_h: \\<open>x' \\<notin> vars (h a)\\<close> for a\n     using polynomial_split_on_var2[of x' p' \\<open>r a\\<close>] unfolding p_p'[symmetric]\n     by metis\n\n\n  have ISABLLE_come_on: \\<open>a * (p * g a) = p * (a * g a)\\<close> for a\n    by auto\n  have q1: \\<open>q = p * (\\<Sum>a\\<in>t'. g a * a) + (\\<Sum>a\\<in>t'. h a * a) + p * r p\\<close>\n    (is \\<open>_ = _ + ?NOx' + _\\<close>)\n    using fin_t t'' unfolding q t ISABLLE_come_on r\n    apply (subst semiring_class.distrib_right)+\n    apply (auto simp: comm_monoid_add_class.sum.distrib semigroup_mult_class.mult.assoc\n      ISABLLE_come_on simp flip: semiring_0_class.sum_distrib_right\n         semiring_0_class.sum_distrib_left)\n    by (auto simp: field_simps)\n  also have \\<open>... = ((\\<Sum>a\\<in>t'. g a * a) + r p) * p + (\\<Sum>a\\<in>t'. h a * a)\\<close>\n    by (auto simp: field_simps)\n  finally have q_decomp: \\<open>q = ((\\<Sum>a\\<in>t'. g a * a) + r p) * p + (\\<Sum>a\\<in>t'. h a * a)\\<close>\n    (is \\<open>q = ?X * p + ?NOx'\\<close>).\n\n\n   have [iff]: \\<open>monomial (Suc 0) c = 0 - monomial (Suc 0) c = False\\<close> for c\n     by (metis One_nat_def diff_is_0_eq' le_eq_less_or_eq less_Suc_eq_le monomial_0_iff single_diff zero_neq_one)\n  have \\<open>x \\<in> t' \\<Longrightarrow> x' \\<in> vars x \\<Longrightarrow> False\\<close> for x\n    using  \\<open>t \\<subseteq> ?trimmed\\<close> t assms(2,3)\n    apply (auto simp: polynomial_bool_def dest!: multi_member_split)\n    apply (frule set_rev_mp)\n    apply assumption\n    apply (auto dest!: multi_member_split)\n    done\n   then have \\<open>x' \\<notin> (\\<Union>m\\<in>t'. vars (h m * m))\\<close>\n     using fin_t x'_h vars_mult[of \\<open>h _\\<close>]\n     by (auto simp: t elim!: vars_unE)\n   then have \\<open>x' \\<notin> vars ?NOx'\\<close>\n     using vars_setsum[of \\<open>t'\\<close> \\<open>\\<lambda>a. h a * a\\<close>] fin_t x'_h\n     by (auto simp: t)\n\n  moreover {\n    have \\<open>x' \\<notin> vars p'\\<close>\n      using assms(7)\n      unfolding p'_def\n      by auto\n    then have \\<open>x' \\<notin> vars (h p * p')\\<close>\n      using vars_mult[of \\<open>h p\\<close> p'] x'_h\n      by auto\n  }\n  ultimately have\n    \\<open>x' \\<notin> vars q\\<close>\n    \\<open>x' \\<notin> vars ?NOx'\\<close>\n    \\<open>x' \\<notin> vars p'\\<close>\n    using x' vars_q vars_add[of \\<open>h p * p'\\<close> \\<open>\\<Sum>a\\<in>t'. h a * a\\<close>] x'_h\n      leading p'_def\n    by auto\n  then have \\<open>?X = 0\\<close> and q_decomp: \\<open>q = ?NOx'\\<close>\n    unfolding mon[symmetric] p_p'\n    using polynomial_decomp_alien_var2[OF q_decomp[unfolded p_p' mon[symmetric]]]\n    by auto\n\n  then have \\<open>r p = (\\<Sum>a\\<in>t'. (- g a) * a)\\<close>\n    (is \\<open>_ = ?CL\\<close>)\n    unfolding add.assoc add_eq_0_iff equation_minus_iff\n    by (auto simp: sum_negf ac_simps)\n\n\n  then have q2: \\<open>q = (\\<Sum>a\\<in>t'. a * (r a - p * g a))\\<close>\n    using fin_t unfolding q\n    apply (auto simp: t r q\n         comm_monoid_add_class.sum.distrib[symmetric]\n         sum_distrib_left\n         sum_distrib_right\n         left_diff_distrib\n        intro!: sum.cong)\n    apply (auto simp: field_simps)\n    done\n  then show \\<open>?thesis\\<close>\n    using t fin_t \\<open>t \\<subseteq> ?trimmed\\<close> unfolding ideal.span_explicit\n    by (auto intro!: exI[of _ t'] exI[of _ \\<open>\\<lambda>a. r a - p * g a\\<close>]\n      simp: field_simps polynomial_bool_def)\n  qed\nqed\n\nlemma extensions_are_safe_uminus:\n  assumes \\<open>x' \\<in> vars p\\<close> and\n    x': \\<open>x' \\<notin> \\<V>\\<close> and\n    \\<open>\\<Union> (vars ` set_mset A) \\<subseteq> \\<V>\\<close> and\n    p_x_coeff: \\<open>coeff p (monomial (Suc 0) x') = -1\\<close> and\n    vars_q: \\<open>vars q \\<subseteq> \\<V>\\<close> and\n    q: \\<open>q \\<in> More_Modules.ideal (insert p (set_mset A \\<union> polynomial_bool))\\<close> and\n    leading: \\<open>x' \\<notin> vars (p + Var x')\\<close> and\n    diff: \\<open>(Var x' + p)^2 - (Var x' + p) \\<in> More_Modules.ideal polynomial_bool\\<close>\n  shows\n    \\<open>q \\<in> More_Modules.ideal (set_mset A \\<union> polynomial_bool)\\<close>\nproof -\n  have \\<open>q \\<in> More_Modules.ideal (insert (- p) (set_mset A \\<union> polynomial_bool))\\<close>\n    by (metis ideal.span_breakdown_eq minus_mult_minus q)\n\n  then show ?thesis\n    using extensions_are_safe[of x' \\<open>-p\\<close> \\<V> A q] assms\n    using vars_in_right_only by force\nqed\n\ntext \\<open>This is the correctness theorem of a PAC step: no polynomials are\nadded to the ideal.\\<close>\n\nlemma vars_subst_in_left_only:\n  \\<open>x \\<notin> vars p \\<Longrightarrow> x \\<in> vars (p - Var x)\\<close> for p :: \\<open>int mpoly\\<close>\n  by (metis One_nat_def Var.abs_eq Var\\<^sub>0_def group_eq_aux monom.abs_eq mult_numeral_1 polynomial_decomp_alien_var(1) zero_neq_numeral)\n\nlemma vars_subst_in_left_only_diff_iff:\n  fixes p :: \\<open>int mpoly\\<close>\n  assumes \\<open>x \\<notin> vars p\\<close>\n  shows \\<open>vars (p - Var x) = insert x (vars p)\\<close>\nproof -\n  have \\<open>\\<And>xa. x \\<notin> vars p \\<Longrightarrow> xa \\<in> vars (p - Var x) \\<Longrightarrow> xa \\<notin> vars p \\<Longrightarrow> xa = x\\<close>\n    by (metis (no_types, opaque_lifting) diff_0_right diff_minus_eq_add empty_iff in_vars_addE insert_iff\n      keys_single minus_diff_eq monom_one mult.right_neutral one_neq_zero single_zero\n      vars_monom_keys vars_mult_Var vars_uminus)\n  moreover have \\<open>\\<And>xa. x \\<notin> vars p \\<Longrightarrow> xa \\<in> vars p \\<Longrightarrow> xa \\<in> vars (p - Var x)\\<close>\n    by (metis add.inverse_inverse diff_minus_eq_add empty_iff insert_iff keys_single minus_diff_eq\n      monom_one mult.right_neutral one_neq_zero single_zero vars_in_right_only vars_monom_keys\n      vars_mult_Var vars_uminus)\n  ultimately show ?thesis\n    using assms\n    by (auto simp: vars_subst_in_left_only)\nqed\n\nlemma vars_subst_in_left_only_iff:\n  \\<open>x \\<notin> vars p \\<Longrightarrow> vars (p + Var x) = insert x (vars p)\\<close> for p :: \\<open>int mpoly\\<close>\n  using vars_subst_in_left_only_diff_iff[of x \\<open>-p\\<close>]\n  by (metis diff_0 diff_diff_add vars_uminus)\n\nlemma coeff_add_right_notin:\n  \\<open>x \\<notin> vars p \\<Longrightarrow> MPoly_Type.coeff (Var x - p) (monomial (Suc 0) x) = 1\\<close>\n  apply (auto simp flip: coeff_minus simp: not_in_vars_coeff0)\n  by (simp add: MPoly_Type.coeff_def Var.rep_eq Var\\<^sub>0_def)\n\nlemma coeff_add_left_notin:\n  \\<open>x \\<notin> vars p \\<Longrightarrow> MPoly_Type.coeff (p - Var x) (monomial (Suc 0) x) = -1\\<close> for p :: \\<open>int mpoly\\<close>\n  apply (auto simp flip: coeff_minus simp: not_in_vars_coeff0)\n  by (simp add: MPoly_Type.coeff_def Var.rep_eq Var\\<^sub>0_def)\n\nlemma ideal_insert_polynomial_bool_swap: \\<open>r - s \\<in> ideal polynomial_bool \\<Longrightarrow>\n  More_Modules.ideal (insert r  (A \\<union> polynomial_bool)) = More_Modules.ideal (insert s (A \\<union> polynomial_bool))\\<close>\n  apply auto\n  using ideal.eq_span_insert_eq ideal.span_mono sup_ge2 apply blast+\n  done\n\nlemma PAC_Format_subset_ideal:\n  \\<open>PAC_Format (\\<V>, A) (\\<V>', B) \\<Longrightarrow> \\<Union>(vars ` set_mset A) \\<subseteq> \\<V> \\<Longrightarrow>\n     restricted_ideal_to\\<^sub>I \\<V> B \\<subseteq> restricted_ideal_to\\<^sub>I \\<V> A \\<and> \\<V> \\<subseteq> \\<V>' \\<and> \\<Union>(vars ` set_mset B) \\<subseteq> \\<V>'\\<close>\n  unfolding restricted_ideal_to_def\n  apply (induction rule:PAC_Format_induct)\n  subgoal for p q pq A \\<V>\n    using vars_add\n    by (force simp: ideal.span_add_eq ideal.span_base pac_ideal_insert_already_in[OF diff_in_polynomial_bool_pac_idealI[of \\<open>p + q\\<close> \\<open>_\\<close> pq]]\n        pac_ideal_add\n      intro!: diff_in_polynomial_bool_pac_idealI[of \\<open>p + q\\<close> \\<open>_\\<close> pq])\n  subgoal for p q pq\n    using vars_mult[of p q]\n    by (force simp: ideal.span_add_eq ideal.span_base pac_ideal_mult\n      pac_ideal_insert_already_in[OF diff_in_polynomial_bool_pac_idealI[of \\<open>p*q\\<close> \\<open>_\\<close> pq]])\n  subgoal for p A\n    using pac_ideal_mono[of \\<open>set_mset (A - {#p#})\\<close> \\<open>set_mset A\\<close>]\n    by (auto dest: in_diffD)\n  subgoal for p x' r'\n    apply (subgoal_tac \\<open>x' \\<notin> vars p\\<close>)\n    using extensions_are_safe_uminus[of x' \\<open>-Var x' + p\\<close> \\<V> A] unfolding pac_ideal_def\n    apply (auto simp: vars_subst_in_left_only coeff_add_left_notin)\n    done\n  done\n\n\ntext \\<open>\n  In general, if deletions are disallowed, then the stronger \\<^term>\\<open>B = pac_ideal A\\<close> holds.\n\\<close>\nlemma restricted_ideal_to_restricted_ideal_to\\<^sub>ID:\n  \\<open>restricted_ideal_to \\<V> (set_mset A) \\<subseteq> restricted_ideal_to\\<^sub>I \\<V> A\\<close>\n   by (auto simp add: Collect_disj_eq pac_idealI1 restricted_ideal_to_def)\n\n\nlemma rtranclp_PAC_Format_subset_ideal:\n  \\<open>rtranclp PAC_Format (\\<V>, A) (\\<V>', B) \\<Longrightarrow> \\<Union>(vars ` set_mset A) \\<subseteq> \\<V> \\<Longrightarrow>\n     restricted_ideal_to\\<^sub>I \\<V> B \\<subseteq> restricted_ideal_to\\<^sub>I \\<V> A \\<and> \\<V> \\<subseteq> \\<V>' \\<and> \\<Union>(vars ` set_mset B) \\<subseteq> \\<V>'\\<close>\n  apply (induction rule:rtranclp_induct[of PAC_Format \\<open>(_, _)\\<close> \\<open>(_, _)\\<close>, split_format(complete)])\n  subgoal\n    by (simp add: restricted_ideal_to_restricted_ideal_to\\<^sub>ID)\n  subgoal\n    by (drule PAC_Format_subset_ideal)\n      (auto simp: restricted_ideal_to_def Collect_mono_iff)\n  done\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/PAC_Checker/PAC_Specification.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8918110425624792, "lm_q2_score": 0.8376199653600371, "lm_q1q2_score": 0.7469987345788824}}
{"text": "theory Ex5_3\n  imports Main\nbegin \n\n\ndatatype ('a , 'v) trie = Trie \"'v option\" \"('a \\<times> ('a  , 'v) trie) list\"\n\n\nprimrec \"value\" :: \"('a , 'v) trie \\<Rightarrow> 'v option\" where \n\"value (Trie ov al) = ov\"\n\nprimrec alist ::  \"('a , 'v)trie \\<Rightarrow> ('a \\<times> ('a , 'v)trie) list\" where\n\"alist (Trie v ls) = ls\"\n\nprimrec assoc :: \"('key \\<times> 'val)list \\<Rightarrow> 'key \\<Rightarrow> 'val option\" where\n\"assoc [] x = None\"|\n\"assoc (x#xs) key = (if key=  fst x then Some (snd x) else assoc xs key)\"\n\nprimrec lookup :: \"('a , 'v)trie \\<Rightarrow> 'a list \\<Rightarrow> 'v option\" where \n\"lookup t [] = value t\"|\n\"lookup t (x#xs) = (case assoc (alist t) x of\n  None \\<Rightarrow> None | \n  Some newT \\<Rightarrow> lookup newT xs)\"\n\nprimrec update :: \"('a , 'v) trie \\<Rightarrow> 'a list \\<Rightarrow> 'v \\<Rightarrow> ('a , 'v)trie\" where\n\"update t [] val =  Trie (Some val) (alist t)\"|\n\"update t (x#xs) val = (case assoc (alist t) x of\n  None \\<Rightarrow> Trie (value t) ((x , update (Trie None []) xs val) # alist t)|\n  Some v \\<Rightarrow> Trie  (value t) ((x , update v xs val) # alist t))\"\n\nlemma empty_tree_lookup : \"lookup (Trie None []) ls = None\" by (induction ls ; simp)\n\ntheorem \"\\<forall> t v bs. lookup (update t as v) bs = (if as = bs then Some v else lookup t bs)\" \nproof (induction as)\n  case Nil\n  then show ?case \n  proof - \n    {\n      fix t::\"('a , 'v)trie\"\n      fix v bs\n      have \"lookup (update t [] v) bs = (if [] = bs then Some v else lookup t bs)\" \n      proof (cases \"bs\")\n        case Nil\n        then show ?thesis by simp\n      next\n        case (Cons a list)\n        then show ?thesis by simp\n      qed\n    }\n    thus ?thesis by blast\n  qed\nnext\n  case (Cons a as)\n  assume hyp:\"\\<forall>(t::('a,'v)trie) v bs. lookup (update t as v) bs = (if as = bs then Some v else lookup t bs)\"\n  then show \" \\<forall>(t::('a,'v)trie) v bs. lookup (update t (a # as) v) bs = (if a # as = bs then Some v else lookup t bs)\"\n  proof -\n    {\n      fix t::\"('a , 'v)trie\"\n      fix bs v\n     \n      have \"lookup (update t (a # as) v) bs = (if a # as = bs then Some v else lookup t bs) \" \n      proof (cases \"bs\")\n        case Nil\n        then show ?thesis by (cases \"assoc (alist t) a\" ; simp)\n      next\n        case (Cons aa list)\n        assume c1:\"bs = aa # list\"\n        then show ?thesis \n        proof (cases \"assoc (alist t) a\")\n          case None\n          then show ?thesis \n          proof (cases \"a = aa\")\n            case True\n            from hyp have tmp:\"lookup (update (Trie None []) as v) list = (if as = list then Some v else lookup (Trie None []) list) \" by simp\n\n            have \"lookup (update t (a # as) v) bs = lookup  (Trie (value t) ((a , update (Trie None []) as v) # alist t)) bs\" using None by simp\n            also have \"\\<dots> = lookup (update (Trie None []) as v) list\" using c1 True None by simp\n            also have \"\\<dots> = (if as = list then Some v else lookup (Trie None []) list)\" using tmp by simp\n            also have \"\\<dots> = (if a # as = bs then Some v else lookup (Trie None []) list)\" using True c1 by simp\n            also have \"\\<dots> = (if a # as = bs then Some v else lookup t bs)\" using empty_tree_lookup c1 True None by auto\n            finally show ?thesis by assumption\n          next\n            case False\n            let ?tmp=\"update (Trie None []) as v\"\n            \n            have \"lookup (update t (a # as) v) bs = lookup (Trie (value t) ((a , ?tmp )  # alist t)) bs\" using None by simp\n            also have \"\\<dots> = lookup t bs\" using False c1 by simp\n            finally show ?thesis using c1 False by simp\n          qed\n        next\n          case (Some aaa)\n          then show ?thesis using c1 hyp by (cases \"a = aa\" ; simp)\n        qed\n      qed\n    }\n    then show \" \\<forall>(t::('a,'v)trie) v bs. lookup (update t (a # as) v) bs = (if a # as = bs then Some v else lookup t bs)\"  by simp\n  qed\nqed\n\nprimrec modify :: \"('a , 'v)trie \\<Rightarrow> 'a list \\<Rightarrow> 'v option \\<Rightarrow> ('a , 'v)trie\" where \n\"modify t [] v = Trie v (alist t)\"|\n\"modify t (x#xs) v = (let tr  = (case assoc (alist t) x of\n  None \\<Rightarrow>  (x ,modify (Trie None []) xs v)   |\n  Some t2 \\<Rightarrow>  (x , modify t2 xs v)  ) \n  in Trie (value t) (tr # alist t))\"\n\ntheorem \"\\<forall> t v bs. lookup (modify t as v) bs = (if as = bs then v else lookup t bs)\" \nproof (induction as)\ncase Nil\n  then show ?case  using alist.simps  modify.simps(1) list.exhaust  lookup.simps  value.simps by metis\nnext\n  case (Cons a as)\n  assume hyp:\"\\<forall>(t::('a,'v)trie) (v::'v option) (bs::'a list). lookup (modify t as v) bs = (if as = bs then v else lookup t bs)\"\n  {\n    fix t::\"('a , 'v) trie\"\n    fix v bs\n    have \"lookup (modify t (a # as) v) bs = (if a # as = bs then v else lookup t bs)\" \n    proof (cases bs)\n      case Nil\n      then show ?thesis by simp\n    next\n      case (Cons aa list)\n      show ?thesis \n      proof (cases \"assoc (alist t) a\")\n        case None\n        from hyp have tmp:\"lookup (modify (Trie None []) (as::'a list) v) (list :: 'a list) = (if as = list then v else lookup (Trie None []) list)\" by simp\n        then show ?thesis using Cons hyp None \n        proof (cases \"a = aa\")\n          case True\n          have \"lookup (modify t (a # as) v) bs = lookup  (modify (Trie None []) as v) list\" using None Cons True  by simp\n          also have \"\\<dots> = (if as = list then v else lookup (Trie None []) list)\" using tmp by simp\n          also have \"\\<dots> = (if a#as = bs then v else lookup t bs)\" using Cons True None empty_tree_lookup by auto\n          finally show ?thesis by assumption\n        next\n          case False\n          then show ?thesis using Cons hyp None by simp\n        qed\n      next\n        case (Some aaa)\n        then show ?thesis using hyp Cons by (cases \"a = aa\" ; simp)\n      qed\n    qed\n  }\n  then show \"\\<forall>(t::('a,'v)trie) (v::'v option) bs. lookup (modify t (a # as) v) bs = (if a # as = bs then v else lookup t bs)\" by simp\nqed\n\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/5. Advanced/Ex5_3.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898102301019, "lm_q2_score": 0.8244619285331332, "lm_q1q2_score": 0.7469541061736772}}
{"text": "(*<*)\ntheory tmpl06\n  imports Main\nbegin\n(*>*)\n\n\ntext {* \\ExerciseSheet{6}{18.~5.~2018} *}\n\ntext \\<open>\\Exercise{Complexity of Naive Reverse}\n  Show that the naive reverse function needs quadratically many\n  \\<open>Cons\\<close> operations in the length of the input list.\n  (Note that \\<open>[x]\\<close> is syntax sugar for \\<open>Cons x []\\<close>!)\n\\<close>\n\nthm append.simps\n\nfun reverse where\n  \"reverse [] = []\"\n| \"reverse (x#xs) = reverse xs @ [x]\"\n\n(** Define cost functions and prove that they are equal to quadratic function *)\n\ntext \\<open>\n  \\Exercise{Simple Paths}\n  Recall the definition of paths from last exercise sheet:\n\\<close>\nfun path :: \"('a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> 'a \\<Rightarrow> 'a list \\<Rightarrow> 'a \\<Rightarrow> bool\"\n  where\n  \"path G u [] v \\<longleftrightarrow> u=v\"\n| \"path G u (x#xs) v \\<longleftrightarrow> G u x \\<and> path G x xs v\"\n\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  by (induction p1 arbitrary: u) auto\n\n\ntext \\<open>\n  A simple path is a path without loops, or, in other words, a path\n  where no node occurs twice. (Note that the first node of the path is\n  not included, such that there may be a simple path from \\<open>u\\<close> to \\<open>u\\<close>.)\n\n  Show that for every path, there is a corresponding simple path.\n\n  Hint: Induction on the length of the path\n\\<close>\nthm measure_induct_rule[where f=length, case_names shorter]\n\nthm not_distinct_decomp\n\nlemma exists_simple_path:\n  assumes \"path G u p v\"\n  shows \"\\<exists>p'. path G u p' v \\<and> distinct p'\"\n  oops\n\n\ntext \\<open>\\NumHomework{Stability of Insertion Sort}{May 25}\n  Have a look at Isabelle's standard implementation of sorting: @{const sort_key}.\n  (Use Ctrl-Click to jump to the definition in @{file \"~~/src/HOL/List.thy\"})\n  Show that this function is a stable sorting algorithm, i.e., the order of elements\n  with the same key is not changed during sorting!\n\\<close>\n\nlemma \"[x\\<leftarrow>sort_key k xs. k x = a] = [x\\<leftarrow>xs. k x = a]\"\n  oops\n\nterm \"[x\\<leftarrow>xs. P x]\"\ntext \\<open>\n  Note: @{term [source] \\<open>[x\\<leftarrow>xs. P x] \\<close>} is syntax sugar for @{term [source] \\<open>filter P xs\\<close>},\n  where the filter function returns only the elements of list \\<open>xs\\<close> for which \\<open>P xs = True\\<close>.\n\n  Hint: You do not necessarily need Isar, and the auxiliary lemmas\n    you need are already in Isabelle's library. @{command find_theorems} is your friend!\n\\<close>\n\n\ntext \\<open>\\NumHomework{Quickselect}{May 25}\n\nFrom \\<^url>\\<open>https://en.wikipedia.org/wiki/Quickselect\\<close>:\n\nQuickselect is a selection algorithm to find the kth smallest element in an unordered list.\nIt is related to the quicksort sorting algorithm.\nLike quicksort, it was developed by Tony Hoare, and thus is also known as Hoare's selection\nalgorithm. Like quicksort, it is efficient in practice and has good average-case performance,\nbut has poor worst-case performance. Quickselect and its variants are the selection algorithms\nmost often used in efficient real-world implementations.\n\nQuickselect uses the same overall approach as quicksort, choosing one element as a pivot and\npartitioning the data in two based on the pivot, accordingly as less than or greater than the\npivot. However, instead of recursing into both sides, as in quicksort, quickselect only\nrecurses into one side --- the side with the element it is searching for.\n\n\nYour task is to prove correct the quickselect algorithm, which can be\n  implemented in Isabelle as follows:\n\\<close>\n\nfun quickselect :: \"'a::linorder list \\<Rightarrow> nat \\<Rightarrow> 'a\" where\n  \"quickselect (x#xs) k = (let\n    xs1 = [y\\<leftarrow>xs. y<x];\n    xs2 = [y\\<leftarrow>xs. \\<not>(y<x)]\n  in\n    if k<length xs1 then quickselect xs1 k\n    else if k=length xs1 then x\n    else quickselect xs2 (k-length xs1-1)\n  )\"\n| \"quickselect [] _ = undefined\"\n\n\ntext \\<open>Your first task is to prove the crucial idea of quicksort, i.e., that\n  partitioning wrt.\\ a pivot element $p$ is correct.\n\\<close>\n\nlemma partition_correct: \"sort xs = sort [x\\<leftarrow>xs. x<p] @ sort [x\\<leftarrow>xs. \\<not>(x<p)]\"\n  oops\n\ntext \\<open>\n  Hint: Induction, and auxiliary lemmas to transform a term of the\n    form @{term \\<open>insort x (xs@ys)\\<close>} when you know that \\<open>x\\<close> is greater than\n    all elements in \\<open>xs\\<close> / less than or equal all elements in \\<open>ys\\<close>.\n\\<close>\n\n\n\ntext \\<open>Next, show that quickselect is correct\\<close>\nlemma \"k<length xs \\<Longrightarrow> quickselect xs k = sort xs ! k\"\n  text \\<open>Proceed by computation induction, and a case distinction according to the\n    cases in the body of the quickselect function\\<close>\nproof (induction xs k rule: quickselect.induct)\n  case (1 x xs k)\n\n  text \\<open>Note: To make the induction hypothesis more readable,\n    you can collapse the first two premises of the form \\<open>?x=\\<dots>\\<close>\n    by reflexivity:\\<close>\n  note IH = \"1.IH\"[OF refl refl]\n\n  text \\<open>Insert your proof here!\\<close>\n\n  show ?case sorry\nnext\n  case 2 then show ?case by simp\nqed\n\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/06/tmpl06.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8479677699040321, "lm_q2_score": 0.8807970873650401, "lm_q1q2_score": 0.7468875419109}}
{"text": "theory Sorting\nimports Main\n        Naturals\n        Listing\nbegin\n\nfun sorted :: \"nat List \\<Rightarrow> bool\" where\n  \"sorted Nil                   = True\"\n| \"sorted (Cons _ Nil)          = True\"\n| \"sorted (Cons r (Cons t ts))  = ( r \\<le> t \\<and> sorted (Cons t ts))\"\n\nfun insert :: \"nat \\<Rightarrow> nat List \\<Rightarrow> nat List\" where\n  \"insert r Nil         = Cons r Nil\"\n| \"insert r (Cons t ts) = (if r \\<le> t then Cons r (Cons t ts) else (Cons t (insert r ts)))\"\n\n\nfun isort :: \"nat List \\<Rightarrow> nat List\" where\n  \"isort Nil = Nil\"\n| \"isort (Cons t ts) = insert t (isort ts)\"\n\nfun qsort :: \"nat list \\<Rightarrow> nat list\" where\n  \"qsort [] = []\"\n| \"qsort (t # ts) = (qsort [r <- ts. r \\<le> t]) @ [t] @ (qsort [r <- ts. \\<not> (r \\<le> t)])\"\n\n\nfun sorted2 :: \"nat list \\<Rightarrow> bool\" where\n  \"sorted2 []                   = True\"\n| \"sorted2 [x]         = True\"\n| \"sorted2 (r # (t # ts))  = (r \\<le> t \\<and> sorted2 (t # ts))\"\n\nfun merge :: \"nat list \\<Rightarrow> nat list \\<Rightarrow> nat list\" where\n  \"merge rs [] = rs\"\n| \"merge [] ts = ts\"\n| \"merge (r#rs) (t#ts) = (if r \\<le> t then r # merge rs (t#ts)\n                                       else t # merge (r#rs) ts)\"\n\nfun msort :: \"nat list => nat list\" where\n  \"msort [] = []\"\n| \"msort [t] = [t]\"\n| \"msort ts = merge (msort (List.take (length ts div 2) ts)) (* size instead? *)\n                    (msort (List.drop (length ts div 2) ts))\"\n\n(* lemma sortCons: \"r \\<le> t \\<and> sorted2 (t # ts) \\<Longrightarrow> sorted2 (r # (t # ts))\" by simp *)\nlemma insSortInvar : \"sorted ts \\<Longrightarrow> sorted (insert t ts)\"\nby hipster_induct_schemes\n\nlemma mer1[thy_expl]: \"sorted2 ts \\<Longrightarrow> sorted2 (merge [] ts)\"\n(*by(metis sorted2.cases merge.simps)*) (* replace of cases by inductions *)\nby hipster_induct_simp_metis\n\nlemma mer2[thy_expl]: \"sorted2 ts \\<Longrightarrow> sorted2 (merge [t] ts)\" (* sorted2.induct! *)\nby hipster_induct_schemes\n\nlemma mer3[thy_expl]: \"sorted2 ts \\<Longrightarrow> sorted2 (merge ts [t])\" (* sorted2.induct! *)\nby hipster_induct_schemes\n\nlemma mer4[thy_expl]: \"sorted2 (t # ts) \\<and> \\<not> t \\<le> r \\<Longrightarrow> sorted2 (r # (merge (t#ts) []))\" by simp\n\nlemma mer4'[thy_expl]: \"sorted2 (t # ts) \\<and> t \\<le> r \\<Longrightarrow> sorted2 (t # merge ts [r])\"\nby (hipster_induct_schemes merge.simps mer3)\n\nlemma mer5'[thy_expl]: \"sorted2 (t # ts) \\<and> r \\<le> v \\<and> \\<not> t \\<le> r \\<Longrightarrow> sorted2 (r # (merge (t#ts) [v]))\"\n(*apply(induction ts rule: sorted2.induct)\napply(simp_all add: mer4 mer3 mer2 mer1)\napply(metis sorted2.simps merge.simps)*)\nby (hipster_induct_schemes merge.simps mer3)\n\nlemma mer5''[thy_expl]: \"sorted2 (r # rs) \\<and> \\<not> t \\<le> r \\<Longrightarrow> sorted2 (r # (merge [t] rs))\"\nby (hipster_induct_schemes sorted2.simps)\n\nlemma ssu[thy_expl]: \"sorted2 (r # rs) \\<and> t \\<le> r \\<Longrightarrow> sorted2 (t # (merge [] (r#rs)))\" by (metis merge.simps sorted2.simps)\n(*by (hipster_induct_simp_metis)*)\n\nlemma ssu'[thy_expl]: \"sorted2 (r # rs) \\<and> t \\<le> v \\<and> t \\<le> r \\<Longrightarrow> sorted2 (t # (merge [v] (r#rs)))\"\nby (metis mer5'' merge.simps sorted2.simps)\nlemma ssu''[thy_expl]: \" sorted2 [t, v] \\<and> sorted2 (r # rs) \\<and> t \\<le> r \\<Longrightarrow> sorted2 (t # (merge [v] (r#rs)))\"\n(*by (metis sorted2.simps(3) ssu')*)\nby (hipster_induct_schemes sorted2.simps mer5'')\n\nlemma cons1[thy_expl]: \"sorted2 (t # ts) \\<Longrightarrow> sorted2 ts\"\nby hipster_induct_simp_metis\n(*by (metis sorted2.elims(3) sorted2.simps(3))*)\n\nlemma t1 : \"sorted2 ts \\<and> ts \\<noteq> [] \\<and> t \\<le> hd ts \\<Longrightarrow> sorted2 (t # ts)\"\nby hipster_induct_simp_metis\n(*by (metis list.sel sorted2.elims(3))*)\n\nlemma mer6[thy_expl]: \"(sorted2 ts \\<and> ts \\<noteq> [] \\<and> sorted2 (r # rs)) \\<Longrightarrow> (sorted2 ((merge ts (r#rs))))\"\napply(induction ts rule: sorted2.induct)\napply(induction rs rule: sorted2.induct)\napply(simp_all only: thy_expl)\napply(simp add: ssu'')\napply(rule conjI)\napply(rule impI)\napply(simp add: thy_expl)\napply(rule impI)\napply(rule conjI)\napply(simp add: thy_expl)\napply(simp add: thy_expl)\noops\n(*by (hipster_induct_schemes ssu' ssu'' mer5' mer5'' mer3)\nsledgehammer\napply(metis sorted2.simps ssu'' mer3 ssu ssu' mer4 mer2 mer1 t1 mer5' mer5'' mer4')*)\n\n(* simplification can very much screw up the goal state! *)\nlemma mer5[thy_expl]: \"(sorted2 (t # ts) \\<and> sorted2 (r # rs) \\<and> t \\<le> r) \\<Longrightarrow> (sorted2 (t # (merge ts (r#rs))))\"\napply(induction ts rule: sorted2.induct)\napply(simp)\napply(simp add: mer5'')\napply(simp add: mer4' mer5'' mer3 ssu' ssu'' ssu)\napply(rule conjI)\napply(rule impI)\napply simp\napply(rule impI, rule conjI)\napply(simp_all)\napply(drule conjE)\napply(simp_all add: ssu' mer5'' mer4 mer4' mer3 mer2 mer1 ssu'' mer5')\n(*apply (metis (full_types) sorted2.simps merge.simps if_splits list.exhaust list.distinct)*)\n(*apply(simp add: ssu ssu' mer3 mer2 mer1 ssu'' mer5' mer4')*)\n(*apply(metis merge.simps(3) mer5' mer4' mer3 mer4)*)\nsorry\n\nlemma mergeS: \"sorted2 ts \\<and> sorted2 rs \\<Longrightarrow> sorted2 (merge ts rs)\"\napply(induction ts rs rule: merge.induct)\nsledgehammer\napply (metis merge.simps(1))\nsledgehammer\napply (metis merge.simps(2))\nsledgehammer\nsledgehammer min [e] (cons1 mer4 mer5 merge.elims merge.simps(1) merge.simps(3) nat_induct ord.lexordp_eq.simps ord.lexordp_eq_simps(3) qsort.cases sorted2.simps(3))\napply(simp_all add: mer1 mer2)\n(*sledgehammer*)\nby (metis mer4 mer5 merge.simps sorted2.simps)\n(*\napply(cases rs)\napply(simp_all)\nby (hipster_induct_schemes mer1 mer5'' mer5 merge.simps sorted2.simps)*)\n(*apply(induction ts rule: sorted2.induct)\napply(simp add: mer1)\napply(simp add: mer5'')\nby (metis mer4 mer5 merge.simps sorted2.simps)*)\n(* apply(induction ts rule: sorted2.induct)\napply(simp add: mer1)\napply(simp add: mer2)\napply(cases rs)\napply(simp_all)\nby (metis mer4 mer5 merge.simps sorted2.simps)*)\n(*   by (induct xs ys rule: merge.induct) (auto simp add: ball_Un not_le less_le sorted_Cons) *)\n\nlemma smsort: \"sorted2 (msort xs)\"\nby (hipster_induct_schemes mergeS)\n\n(*lemma merComm: \"sorted2 ts \\<and> sorted2 rs \\<Longrightarrow> merge rs ts = merge ts rs\"\napply(induction rs ts rule: merge.induct)\napply(simp_all)\napply(metis sorted2.cases merge.simps(1) merge.simps(2))*)\n\n\n\n(*\nfun merge :: \"Nat list \\<Rightarrow> Nat list \\<Rightarrow> Nat list\" where\n  \"merge [] ts = ts\"\n| \"merge rs [] = rs\"\n| \"merge (r#rs) (t#ts) = (if leq r t then (r # (merge rs (t #\u00a0ts)) )\n                                     else (t # (merge (r # rs) ts) ) )\"\n\nfun msort :: \"Nat list \\<Rightarrow> Nat list\" where\n  \"msort [] = []\"\n| \"msort [t] = [t]\"\n| \"msort ts = merge (msort (take ((length ts) div 2) ts))\n                    (msort (drop ((length ts) div 2) ts))*)\n(* in a let ... *)\n\n\n\n(* qsort *)\n\n\n\nend\n\n\n", "meta": {"author": "moajohansson", "repo": "IsaHipster", "sha": "91f6ea3f1166a9de547722ece6445fe843ad89b4", "save_path": "github-repos/isabelle/moajohansson-IsaHipster", "path": "github-repos/isabelle/moajohansson-IsaHipster/IsaHipster-91f6ea3f1166a9de547722ece6445fe843ad89b4/TestTheories/Sorting.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970811069351, "lm_q2_score": 0.8479677641409289, "lm_q1q2_score": 0.7468875315281042}}
{"text": "header {* Solutions to Chapter 7 of \"Concrete Semantics\" *}\n  \ntheory Chap_seven imports Big_step Small_step begin\n\ndeclare [[names_short]]\n\n(* 7.1 *)\n\nfun assigned :: \"com \\<Rightarrow> vname set\" where\n\"assigned SKIP = {}\" |\n\"assigned (c1;;c2) = assigned c1 \\<union> assigned c2\" |\n\"assigned (x ::= a) = {x}\" |\n\"assigned (IF b THEN c1 ELSE c2) = assigned c1 \\<union> assigned c2\" |\n\"assigned (WHILE b DO c) = assigned c\" \n\nlemma \"\\<lbrakk>(c, s) \\<Rightarrow> t; x \\<notin> assigned c\\<rbrakk> \\<Longrightarrow> s x = t x\"\napply (induction rule: big_step_induct)\napply (auto)\ndone\n\n(* 7.2 *)\n\nfun skip :: \"com \\<Rightarrow> bool\" where\n\"skip SKIP = True\" |\n\"skip (c1;;c2) = (skip c1 \\<and> skip c2)\" |\n\"skip (x::=a) = False\" |\n\"skip (IF b THEN c1 ELSE c2) = (skip c1 \\<and> skip c2)\" |\n\"skip (WHILE b DO c) = False\" \n\nlemma \"skip c \\<Longrightarrow> c \\<sim> SKIP\"\nproof (induction c)\n  case (Seq c1 c2)\n  hence \"c1 \\<sim> SKIP\" and \"c2 \\<sim> SKIP\" by auto\n  hence \"(c1;;c2) \\<sim> (SKIP;;SKIP)\" by blast\n  thus \"(c1;;c2) \\<sim> SKIP\" by blast\nnext\n  case (If b c1 c2)\n  hence \"c1 \\<sim> SKIP\" and \"c2 \\<sim> SKIP\" by auto\n  thus \"IF b THEN c1 ELSE c2 \\<sim> SKIP\" by blast    \nqed auto+\n\n(* 7.3 *)\n\nfun deskip :: \"com \\<Rightarrow> com\" where\n\"deskip (c1;;c2) = (case (deskip c1, deskip c2) of\n (SKIP, SKIP) \\<Rightarrow> SKIP |\n (SKIP, q) \\<Rightarrow> q |\n (p, SKIP) \\<Rightarrow> p |\n (p, q) \\<Rightarrow> (p;;q))\" |\n\"deskip (WHILE b DO c) = WHILE b DO (deskip c)\" |\n\"deskip (IF b THEN c1 ELSE c2) = IF b THEN (deskip c1) ELSE (deskip c2)\" |\n\"deskip c = c\"\n \nlemma \"deskip c \\<sim> c\"\nproof (induction c)\n case (Seq c1 c2)\n hence \"c1;; c2 \\<sim> (deskip c1);; (deskip c2)\" by auto \n moreover have \"(deskip c1);; (deskip c2) \\<sim> deskip (c1;; c2)\" \n  by (auto split: com.split)\n ultimately show ?case by auto\nqed (auto simp add: sim_while_cong)+\n\n(* 7.4 *)\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\"(p, s) \\<leadsto> (N p') \\<Longrightarrow> (Plus (N p') q, s) \\<leadsto> r \\<Longrightarrow> (Plus p q, s) \\<leadsto> r\" |\n\"(q, s) \\<leadsto> (N q') \\<Longrightarrow> (Plus (N i) q, s) \\<leadsto> N (i + q')\"\n\ncode_pred astep .\n\nvalues \"{c' |c'.\n   (Plus (Plus (V ''x'') (V ''z'')) (V ''y''),\n    <''x'' := 1, ''y'' := 7, ''z'' := 15>) \\<leadsto> c'}\"\n\nlemmas astep_induct = astep.induct[split_format(complete)]\n\nlemma \"(a, s) \\<leadsto> a' \\<Longrightarrow> aval a s = aval a' s\"\n by (induction rule: astep_induct, auto)\n\nlemma \"(a, s) \\<leadsto> a' \\<Longrightarrow> aval a s = aval a' s\"\nproof (induction rule: astep_induct)\n fix x s\n show \"aval (V x) s = aval (N (s x)) s\" by simp\nnext \n fix i j s\n show \"aval (Plus (N i) (N j)) s = aval (N (i + j)) s\" by simp\nnext\n fix p s p' q r\n assume a: \"(p, s) \\<leadsto> N p'\"\n assume b: \"aval p s = aval (N p') s\"\n assume c: \"(Plus (N p') q, s) \\<leadsto> r\" \n assume d: \"aval (Plus (N p') q) s = aval r s\"\n show \"aval (Plus p q) s = aval r s\" using a b c d by simp\nnext\n fix q s q' i\n assume a: \"(q, s) \\<leadsto> N q'\"\n assume b: \"aval q s = aval (N q') s\"\n show \"aval (Plus (N i) q) s = aval (N (i + q')) s\" using a b by simp\nqed\n\n(* 7.5 *)\n\nlemma \"IF And b1 b2 THEN c1 ELSE c2 \\<sim> IF b1 THEN IF b2 THEN c1 ELSE c2 ELSE c2\" (is \"?P \\<sim> ?Q\")\nproof -\n  { fix s t\n    assume \"(?P, s) \\<Rightarrow> t\"\n    { assume b: \"(bval b1 s) \\<and> (bval b2 s)\"\n      with `(?P, s) \\<Rightarrow> t` have \"(c1, s) \\<Rightarrow> t\" by auto\n      hence \"(?Q, s) \\<Rightarrow> t\" using b by auto\n    }\n    moreover\n    { assume b: \"\\<not> ((bval b1 s) \\<and> (bval b2 s))\"\n      hence \"\\<not> bval (And b1 b2) s\" by auto\n      with `(?P, s) \\<Rightarrow> t` have \"(c2, s) \\<Rightarrow> t\" by auto\n      hence \"(?Q, s) \\<Rightarrow> t\" using b by auto\n    }\n    ultimately have \"(?Q, s) \\<Rightarrow> t\" by auto\n  }\n  moreover\n  { fix s t\n    assume \"(?Q, s) \\<Rightarrow> t\"\n    { assume b: \"(bval b1 s) \\<and> (bval b2 s)\"\n      with `(?Q, s) \\<Rightarrow> t` have \"(c1, s) \\<Rightarrow> t\" by auto\n      hence \"(?P, s) \\<Rightarrow> t\" using b by auto\n    }\n    moreover\n    { assume b: \"\\<not> ((bval b1 s) \\<and> (bval b2 s))\"\n      with `(?Q, s) \\<Rightarrow> t` have \"(c2, s) \\<Rightarrow> t\" by auto\n      from b have \"\\<not> bval (And b1 b2) s\" by auto\n      hence \"(?P, s) \\<Rightarrow> t\" using `(c2, s) \\<Rightarrow> t` by auto\n    }\n    ultimately have \"(?P, s) \\<Rightarrow> t\" by auto    \n  }\n  ultimately show ?thesis by auto\nqed\n\nlemma \"\\<not> (\\<forall> b1 b2 c. WHILE And b1 b2 DO c \\<sim> WHILE b1 DO WHILE b2 DO c)\" (is \"\\<not> ?P\")\nproof\n  assume \"?P\"\n  then obtain l p t where\n   vars: \n    \"l = Bc True\" \n    \"t = Bc False\"  \n    \"p = SKIP\"\n   and \"bval (And l t) s = False\" \n   and a: \"WHILE And l t DO p \\<sim> WHILE l DO WHILE t DO p\" by auto\n   then have \"(WHILE And l t DO p, s) \\<Rightarrow> s\" by blast  \n   with a have \"(WHILE l DO WHILE t DO p, s) \\<Rightarrow> s\" by auto\n   thus False \n    by (induction \"WHILE l DO WHILE t DO p\" s s rule: big_step_induct, auto simp add: vars)\nqed    \n\nabbreviation Or :: \"bexp \\<Rightarrow> bexp \\<Rightarrow> bexp\" where\n \"Or b1 b2 \\<equiv> Not (And (Not b1) (Not b2))\"\n \nlemma \"WHILE Or b1 b2 DO c \\<sim> WHILE Or b1 b2 DO c;; WHILE b1 DO c\" (is \"?P \\<sim> ?P ;; ?Q\")\nproof -\n  { fix b c' s t have \"(WHILE b DO c', s) \\<Rightarrow> t \\<Longrightarrow> \\<not> bval b t\"\n    by (induction \"WHILE b DO c'\" s t rule: big_step_induct)\n  } note while_false = this\n\n  { fix s t assume a: \"(?P, s) \\<Rightarrow> t\"\n    with while_false have \"\\<not> bval (Or b1 b2) t\" by blast \n    hence \"(?Q, t) \\<Rightarrow> t\" by auto\n    with a have \"(?P ;; ?Q, s) \\<Rightarrow> t\" by auto\n  }\n  moreover\n  { fix s t assume a: \"(?P ;; ?Q, s) \\<Rightarrow> t\"\n    then obtain s' where a1: \"(?P, s) \\<Rightarrow> s'\" and a2: \"(?Q, s') \\<Rightarrow> t\" by auto\n    with while_false have \"\\<not> bval (Or b1 b2) s'\" by blast\n    hence \"(?Q, s') \\<Rightarrow> s'\" by auto\n    with a2 big_step_determ have \"s' = t\" by auto\n    with a1 have \"(?P, s) \\<Rightarrow> t\" by auto\n  }\n  ultimately show ?thesis by blast\nqed\n\n(* 7.6 *)\n\nabbreviation DoWhile :: \"com \\<Rightarrow> bexp \\<Rightarrow> com\" (\"(DO _/ WHILE _)\"  [0, 61] 61) where\n\"DO c WHILE b \\<equiv> (c ;; WHILE b DO c)\" \n\nfun dewhile :: \"com \\<Rightarrow> com\" where\n\"dewhile (WHILE b DO c) = IF b THEN DO (dewhile c) WHILE b ELSE SKIP\" | \n\"dewhile (c1;; c2) = (dewhile c1);; dewhile c2\" |\n\"dewhile (IF b THEN c1 ELSE c2) = (IF b THEN (dewhile c1) ELSE (dewhile c2))\" |\n\"dewhile c = c\"\n\nlemma \"dewhile c \\<sim> c\"\nproof (induction c)\n  case (While b c)\n  hence \"WHILE b DO c \\<sim> WHILE b DO dewhile c\" using sim_while_cong by auto\n  moreover have \n   \"WHILE b DO dewhile c \\<sim> IF b THEN DO (dewhile c) WHILE b ELSE SKIP\" using while_unfold by auto\n  ultimately have \n   \"WHILE b DO c \\<sim> IF b THEN DO (dewhile c) WHILE b ELSE SKIP\" using sim_trans by blast\n  thus ?case by auto\nqed auto+\n\n(* 7.7 *)\n\nlemma \n fixes \n  C :: \"nat \\<Rightarrow> com\" and\n  S :: \"nat \\<Rightarrow> state\"\n assumes \n  \"C 0 = c;; d\" \n  \"\\<forall> n. (C n, S n) \\<rightarrow> (C (Suc n), S (Suc n))\" \n shows \n \"(\\<forall> n. \\<exists> c1 c2. \n   C n = c1;; d \\<and> \n   C (Suc n) = c2;; d \\<and> \n   (c1, S n) \\<rightarrow> (c2, S (Suc n))) \\<or>\n (\\<exists> k. C k = SKIP;; d)\" (is \"?P \\<or> ?Q\")\nproof cases\n  assume \"?Q\"\n  thus ?thesis by auto\nnext \n  assume \"\\<not> ?Q\"\n  { fix n c1 assume cn: \"C n = c1;; d\"\n    hence \"\\<exists> c2. C (Suc n) = c2;; d \\<and> (c1, S n) \\<rightarrow> (c2, S (Suc n))\"\n    proof -\n      from assms have \"(C n, S n) \\<rightarrow> (C (Suc n), S (Suc n))\" by blast      \n      with cn have cc: \"(c1;; d, S n) \\<rightarrow> (C (Suc n), S (Suc n))\" by auto\n      then obtain c2 where \"C (Suc n) = c2;; d\" \n        \"(c1, S n) \\<rightarrow> (c2, S (Suc n))\" using  `\\<not> ?Q` cn by blast\n      then show ?thesis by auto\n    qed\n  } note Cn_induction = this\n\n  { fix n \n    have \"\\<exists>c1 c2. C n = c1;; d \\<and> C (Suc n) = c2;; d \\<and> (c1, S n) \\<rightarrow> (c2, S (Suc n))\" \n    proof (induction n)\n      case 0\n      from assms obtain c1 where c1: \"C 0 = c1;; d\" by auto\n      with Cn_induction obtain c2  where \"C (Suc 0) = c2;; d\" \n        \"(c1, S 0) \\<rightarrow> (c2, S (Suc 0))\" by blast\n      with c1 show ?case by auto\n    next\n      case (Suc n)\n      from this obtain c1 where c1: \"C (Suc n) = c1;; d\" by blast\n      with Cn_induction obtain c2 where \"C (Suc (Suc n)) = c2;; d\" \n        \"(c1, S (Suc n)) \\<rightarrow> (c2, S (Suc (Suc n)))\" by blast\n      with c1 show ?case by auto\n    qed\n  }\n  thus ?thesis by auto\nqed\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_seven.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970873650401, "lm_q2_score": 0.8479677564567913, "lm_q1q2_score": 0.7468875300666096}}
{"text": "section \\<open>Preliminaries\\<close>\ntheory Preliminaries\n  imports \n    Main\n    HOL.Real\n    \"HOL-Library.FuncSet\"\nbegin\n\nlemma fact_approx_add: \"fact (l + n) \\<le> fact l * (real l + real n) ^ n\" \nproof (induct n arbitrary: l)\n  case (Suc n l)\n  have \"fact (l + Suc n) = (real l + Suc n) * fact (l + n)\" by simp\n  also have \"\\<dots> \\<le> (real l + Suc n) * (fact l * (real l + real n) ^ n)\" \n    by (intro mult_left_mono[OF Suc], auto)\n  also have \"\\<dots> = fact l * ((real l + Suc n) * (real l + real n) ^ n)\" by simp\n  also have \"\\<dots> \\<le> fact l * ((real l + Suc n) * (real l + real (Suc n)) ^ n)\" \n    by (rule mult_left_mono, rule mult_left_mono, rule power_mono, auto)\n  finally show ?case by simp\nqed simp\n\nlemma fact_approx_minus: assumes \"k \\<ge> n\"\n  shows \"fact k \\<le> fact (k - n) * (real k ^ n)\"\nproof -\n  define l where \"l = k - n\" \n  from assms have k: \"k = l + n\" unfolding l_def by auto\n  show ?thesis unfolding k using fact_approx_add[of l n] by simp\nqed\n\nlemma fact_approx_upper_add: assumes al: \"a \\<le> Suc l\" shows \"fact l * real a ^ n \\<le> fact (l + n)\" \nproof (induct n)\n  case (Suc n)\n  have \"fact l * real a ^ (Suc n) = (fact l * real a ^ n) * real a\" by simp\n  also have \"\\<dots> \\<le> fact (l + n) * real a\" \n    by (rule mult_right_mono[OF Suc], auto)\n  also have \"\\<dots> \\<le> fact (l + n) * real (Suc (l + n))\" \n    by (intro mult_left_mono, insert al, auto)\n  also have \"\\<dots> = fact (Suc (l + n))\" by simp\n  finally show ?case by simp\nqed simp\n\nlemma fact_approx_upper_minus: assumes \"n \\<le> k\" and \"n + a \\<le> Suc k\" \n  shows \"fact (k - n) * real a ^ n \\<le> fact k\" \nproof -\n  define l where \"l = k - n\" \n  from assms have k: \"k = l + n\" unfolding l_def by auto\n  show ?thesis using assms unfolding k \n    apply simp\n    apply (rule fact_approx_upper_add, insert assms, auto simp: l_def)\n    done\nqed\n\nlemma choose_mono: \"n \\<le> m \\<Longrightarrow> n choose k \\<le> m choose k\" \n  unfolding binomial_def\n  by (rule card_mono, auto)\n\nlemma div_mult_le: \"(a div b) * c \\<le> (a * c) div (b :: nat)\"\n  by (metis div_mult2_eq div_mult_mult2 mult.commute mult_0_right times_div_less_eq_dividend)\n\nlemma div_mult_pow_le: \"(a div b)^n \\<le> a^n div (b :: nat)^n\"  \nproof (cases \"b = 0\")\n  case True\n  thus ?thesis by (cases n, auto)\nnext\n  case b: False  \n  then obtain c d where a: \"a = b * c + d\" and id: \"c = a div b\" \"d = a mod b\" by auto\n  have \"(a div b)^n = c^n\" unfolding id by simp\n  also have \"\\<dots> = (b * c)^n div b^n\" using b\n    by (metis div_power dvd_triv_left nonzero_mult_div_cancel_left)\n  also have \"\\<dots> \\<le> (b * c + d)^n div b^n\" \n    by (rule div_le_mono, rule power_mono, auto)\n  also have \"\\<dots> = a^n div b^n \" unfolding a by simp\n  finally show ?thesis .\nqed\n\nlemma choose_inj_right:\n  assumes id: \"(n choose l) = (k choose l)\" \n    and n0: \"n choose l \\<noteq> 0\" \n    and l0:  \"l \\<noteq> 0\" \n  shows \"n = k\"\nproof (rule ccontr)\n  assume nk: \"n \\<noteq> k\" \n  define m where \"m = min n k\" \n  define M where \"M = max n k\" \n  from nk have mM: \"m < M\" unfolding m_def M_def by auto\n  let ?new = \"insert (M - 1) {0..< l - 1}\" \n  let ?m = \"{K \\<in> Pow {0..<m}. card K = l}\" \n  let ?M = \"{K \\<in> Pow {0..<M}. card K = l}\" \n  from id n0 have lM :\"l \\<le> M\" unfolding m_def M_def by auto\n  from id have id: \"(m choose l) = (M choose l)\" \n    unfolding m_def M_def by auto\n  from this[unfolded binomial_def]\n  have \"card ?M < Suc (card ?m)\" \n    by auto\n  also have \"\\<dots> = card (insert ?new ?m)\" \n    by (rule sym, rule card_insert_disjoint, force, insert mM, auto)\n  also have \"\\<dots> \\<le> card (insert ?new ?M)\" \n    by (rule card_mono, insert mM, auto)\n  also have \"insert ?new ?M = ?M\" \n    by (insert mM lM l0, auto)\n  finally show False by simp\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/Clique_and_Monotone_Circuits/Preliminaries.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970748488296, "lm_q2_score": 0.8479677660619633, "lm_q1q2_score": 0.746887527913474}}
{"text": "section \\<open>Connection of Euler--MacLaurin summation to Landau symbols\\<close>\ntheory Euler_MacLaurin_Landau\nimports \n  Euler_MacLaurin\n  Landau_Symbols.Landau_More\nbegin\n\nsubsection \\<open>$O$-bound for the remainder term\\<close>  \n\ntext \\<open>\n  Landau symbols allow us to state the bounds on the remainder terms \n  from the Euler--MacLaurin formula a bit more nicely.\n\\<close>\n\nlemma\n  fixes f :: \"real \\<Rightarrow> 'a :: {real_normed_field, banach}\"\n    and g g' :: \"real \\<Rightarrow> real\"\n  assumes fin:     \"finite Y\"\n  assumes cont_f:  \"continuous_on {a..} f\"\n  assumes cont_g:  \"continuous_on {a..} g\"\n  assumes cont_g': \"continuous_on {a..} g'\"\n  assumes limit_g: \"(g \\<longlongrightarrow> 0) at_top\"\n  assumes f_bound: \"\\<And>x. x \\<ge> a \\<Longrightarrow> norm (f x) \\<le> g' x\"\n  assumes deriv:   \"\\<And>x. x \\<in> {a..} - Y \\<Longrightarrow> (g has_field_derivative -g' x) (at x)\"\n  shows   EM_remainder_strong_bigo_int: \"(\\<lambda>x::int. norm (EM_remainder n f x)) \\<in> O(g)\"\n    and   EM_remainder_strong_bigo_nat: \"(\\<lambda>x::nat. norm (EM_remainder n f x)) \\<in> O(g)\"\nproof -\n  from bounded_pbernpoly[of n] obtain D where D: \"\\<forall>x. \\<bar>pbernpoly n x\\<bar> \\<le> D\" by auto\n  from norm_EM_remainder_le_strong_int'[OF fin D assms(2-)]\n    have *: \"\\<And>x. x \\<ge> a \\<longrightarrow> norm (EM_remainder n f x) \\<le> D / fact n * g x\" by auto\n  have **: \"eventually (\\<lambda>x::int. norm (EM_remainder n f x) \\<le> abs (D / fact n) * abs (g x)) at_top\"\n    using eventually_ge_at_top[of \"ceiling a\"]\n  proof eventually_elim\n    case (elim x)\n    with *[of x] have \"norm (EM_remainder n f x) \\<le> D / fact n * g x\" by (simp add: ceiling_le_iff)\n    also have \"\\<dots> \\<le> abs (D / fact n * g x)\" by (rule abs_ge_self)\n    also have \"\\<dots> = abs (D / fact n) * abs (g x)\" by (simp add: abs_mult)\n    finally show ?case .\n  qed\n  thus \"(\\<lambda>x::int. norm (EM_remainder n f x)) \\<in> O(g)\"\n    by (intro bigoI[of _ \"abs D / fact n\"]) (auto elim!: eventually_mono)\n  hence \"(\\<lambda>x::nat. norm (EM_remainder n f (int x))) \\<in> O(\\<lambda>x. g (of_int (int x)))\"\n    by (rule landau_o.big.compose) (fact filterlim_int_sequentially)\n  thus \"(\\<lambda>x::nat. norm (EM_remainder n f x)) \\<in> O(g)\" by simp\nqed\n\n\nsubsection \\<open>Asymptotic expansion of the harmonic numbers\\<close>\n\ntext \\<open>\n  We can now show the asymptotic expansion\n  \\[H_n = \\ln n + \\gamma + \\frac{1}{2n} - \\sum_{i=1}^m \\frac{B_{2i}}{2i} n^{-2i} + O(n^{-2m-2})\\]\n\\<close>\n\nlemma harm_remainder_bigo:\n  assumes \"N > 0\"\n  shows   \"harm_remainder N \\<in> O(\\<lambda>n. 1 / real n ^ (2 * N + 1))\"\nproof -\n  from harm_remainder_bound[OF assms] guess C ..\n  thus ?thesis\n    by (intro bigoI[of _ C] eventually_mono[OF eventually_ge_at_top[of 1]]) auto\nqed\n\nlemma harm_expansion_bigo:\n  fixes N :: nat\n  defines \"T \\<equiv> \\<lambda>n. ln n + euler_mascheroni + 1 / (2*n) -\n                     (\\<Sum>i=1..N. bernoulli (2*i) / ((2*i) * n ^ (2*i)))\"\n  defines \"S \\<equiv> (\\<lambda>n. bernoulli (2*(Suc N)) / ((2*Suc N) * real n ^ (2*Suc N)))\"\n  shows \"(\\<lambda>n. harm n - T n) \\<in> O(\\<lambda>n. 1 / real n ^ (2 * N + 2))\"\nproof -\n  have \"(\\<lambda>n. harm n - T n) \\<in> \\<Theta>(\\<lambda>n. -S n - harm_remainder (Suc N) n)\"\n    by (intro bigthetaI_cong eventually_mono[OF eventually_gt_at_top[of \"0::nat\"]]) \n       (auto simp: T_def harm_expansion[of _ \"Suc N\"] S_def)\n  also have \"(\\<lambda>n. -S n - harm_remainder (Suc N) n) \\<in> O(\\<lambda>n. 1 / real n ^ (2 * N + 2))\"\n  proof (intro sum_in_bigo)\n    show \"(\\<lambda>x. - S x) \\<in> O(\\<lambda>n. 1 / real n ^ (2 * N + 2))\" unfolding S_def\n      by (rule landau_o.big.compose[OF _ filterlim_real_sequentially]) simp\n    have \"harm_remainder (Suc N) \\<in> O(\\<lambda>n. 1 / real n ^ (2 * Suc N + 1))\"\n      by (rule harm_remainder_bigo) simp_all\n    also have \"(\\<lambda>n. 1 / real n ^ (2 * Suc N + 1)) \\<in> O(\\<lambda>n. 1 / real n ^ (2 * N + 2))\"\n      by (rule landau_o.big.compose[OF _ filterlim_real_sequentially]) simp\n    finally show \"harm_remainder (Suc N) \\<in> \\<dots>\" .\n  qed\n  finally show ?thesis .\nqed\n\n\n\nlemma harm_expansion_bigo_simple2:\n  \"(\\<lambda>n. harm n - (ln n + euler_mascheroni)) \\<in> O(\\<lambda>n. 1 / n)\"\nproof -\n  have \"(\\<lambda>n. harm n - (ln n + euler_mascheroni + 1 / (2 * n)) + 1 / (2 * n)) \\<in> O(\\<lambda>n. 1 / n)\"\n  proof (rule sum_in_bigo)\n    have \"(\\<lambda>n. harm n - (ln n + euler_mascheroni + 1 / (2 * n))) \\<in> O(\\<lambda>n. 1 / real n ^ 2)\"\n      using harm_expansion_bigo_simple1 by simp\n    also have \"(\\<lambda>n. 1 / real n ^ 2) \\<in> O(\\<lambda>n. 1 / real n)\"\n      by (rule landau_o.big.compose[OF _ filterlim_real_sequentially]) simp_all\n    finally show \"(\\<lambda>n. harm n - (ln n + euler_mascheroni + 1 / (2 * n))) \\<in> O(\\<lambda>n. 1 / n)\" by simp\n  qed simp_all\n  thus ?thesis by (simp add: algebra_simps)\nqed\n\nlemma harm_expansion_bigo_simple':\n  \"harm =o (\\<lambda>n. ln n + euler_mascheroni + 1 / (2 * n)) +o O(\\<lambda>n. 1 / n ^ 2)\"\n  using harm_expansion_bigo_simple1\n  by (subst set_minus_plus [symmetric]) (simp_all add: fun_diff_def)\n\n\nsubsection \\<open>Asymptotic expansion of the sum of inverse squares\\<close>\n\ntext \\<open>\n  Similarly to before, we show\n  \\[\\sum_{i=1}^n \\frac{1}{i^2} = \\frac{\\pi^2}{6} - \\frac{1}{n} + \\frac{1}{2n^2} - \n     \\sum_{i=1}^m B_{2i} n^{-2i-1} + O(n^{-2m-3})\\]  \n\\<close>\n\ncontext\n  fixes R :: \"nat \\<Rightarrow> nat \\<Rightarrow> real\"\n  defines \"R \\<equiv> (\\<lambda>N n. EM_remainder (2*N+1) (\\<lambda>x. -fact (2*N+2) / x ^ (2*N+3)) (int n))\"\nbegin\n\nlemma sum_inverse_squares_remainder_bigo:\n  assumes \"N > 0\"\n  shows   \"R N \\<in> O(\\<lambda>n. 1 / real n ^ (2 * N + 2))\"\nproof -\n  from sum_inverse_squares_remainder_bound[OF assms] guess C ..\n  thus ?thesis\n    by (intro bigoI[of _ C] eventually_mono[OF eventually_ge_at_top[of 1]]) (auto simp: R_def)\nqed\n\nlemma sum_inverse_squares_expansion_bigo:\n  fixes N :: nat\n  defines \"T \\<equiv> \\<lambda>n. pi ^ 2 / 6 - 1 / n + 1 / (2*n ^ 2) -\n                     (\\<Sum>i=1..N. bernoulli (2*i) / (n ^ (2*i+1)))\"\n  defines \"S \\<equiv> (\\<lambda>n. bernoulli (2*(Suc N)) / (real n ^ (2*N+3)))\"\n  shows \"(\\<lambda>n. (\\<Sum>i=1..n. 1 / real i ^ 2) - T n) \\<in> O(\\<lambda>n. 1 / real n ^ (2 * N + 3))\"\nproof -\n  have 3: \"3 = Suc (Suc (Suc 0))\" by simp\n  have \"(\\<lambda>n. (\\<Sum>i=1..n. 1 / real i ^ 2) - T n) \\<in> \\<Theta>(\\<lambda>n. -S n - R (Suc N) n)\" unfolding R_def\n    by (intro bigthetaI_cong eventually_mono[OF eventually_gt_at_top[of \"0::nat\"]])\n       (auto simp: T_def sum_inverse_squares_expansion[of _ \"Suc N\"] S_def 3\n             simp del: One_nat_def)\n  also have \"(\\<lambda>n. -S n - R (Suc N) n) \\<in> O(\\<lambda>n. 1 / real n ^ (2 * N + 3))\"\n  proof (intro sum_in_bigo)\n    show \"(\\<lambda>x. - S x) \\<in> O(\\<lambda>n. 1 / real n ^ (2 * N + 3))\" unfolding S_def\n      by (rule landau_o.big.compose[OF _ filterlim_real_sequentially]) simp\n    have \"R (Suc N) \\<in> O(\\<lambda>n. 1 / real n ^ (2 * Suc N + 2))\"\n      by (rule sum_inverse_squares_remainder_bigo) simp_all\n    also have \"2 * Suc N + 2 = 2 * N + 4\" by simp\n    also have \"(\\<lambda>n. 1 / real n ^ (2 * N + 4)) \\<in> O(\\<lambda>n. 1 / real n ^ (2 * N + 3))\"\n      by (rule landau_o.big.compose[OF _ filterlim_real_sequentially]) simp\n    finally show \"R (Suc N) \\<in> \\<dots>\" .\n  qed\n  finally show ?thesis .\nqed\n\nlemma sum_inverse_squares_expansion_bigo_simple:\n  \"(\\<lambda>n. (\\<Sum>i=1..n. 1 / real i ^ 2) - (pi ^ 2 / 6 - 1 / n + 1 / (2*n^2))) \\<in> O(\\<lambda>n. 1 / n ^ 3)\"\n  using sum_inverse_squares_expansion_bigo[of 0] by (simp add: power2_eq_square)\n\nlemma sum_inverse_squares_expansion_bigo_simple':\n  \"(\\<lambda>n. (\\<Sum>i=1..n. 1 / real i ^ 2)) =o (\\<lambda>n. pi ^ 2 / 6 - 1 / n + 1 / (2*n^2)) +o O(\\<lambda>n. 1 / n^3)\"\n  using sum_inverse_squares_expansion_bigo_simple\n  by (subst set_minus_plus [symmetric]) (simp_all add: fun_diff_def)\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/Euler_MacLaurin/Euler_MacLaurin_Landau.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970748488296, "lm_q2_score": 0.8479677583778258, "lm_q1q2_score": 0.7468875211453081}}
{"text": "\ntheory InsertSort\nimports\n  Complex_Main\n  \"HOL-Library.Multiset\"\nbegin\n\n\ncontext linorder\nbegin\n\nfun insort :: \"'a \\<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 list \\<Rightarrow> 'a list\" where\n\"isort [] = []\" |\n\"isort (x#xs) = insort x (isort xs)\"\n\nvalue \"isort [100,39,2::nat, 3,5,10,300]\"\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 insort_set: \"set (insort x xs) = insert x (set xs)\"\n  apply(induct xs) by auto\n\nlemma sorted_insort: \"sorted (insort a xs) = sorted xs\"\napply(induction xs) apply simp\napply(case_tac \"a \\<le> aa\")\n  apply auto[1]  \n  apply simp\n  apply(rule iffI)\n    apply (simp add: insort_set)\n    apply (simp add: insort_set)\ndone\n\nlemma sorted_isort: \"sorted (isort xs)\"\napply(induction xs)\napply(auto simp: sorted_insort)\ndone\nend\n\nend\n", "meta": {"author": "LVPGroup", "repo": "fpp", "sha": "7e18377ea2c553bf6e57412727a4f06832d93577", "save_path": "github-repos/isabelle/LVPGroup-fpp", "path": "github-repos/isabelle/LVPGroup-fpp/fpp-7e18377ea2c553bf6e57412727a4f06832d93577/4_ds_algo/Sorting/InsertSort.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8807970654616711, "lm_q2_score": 0.8479677583778258, "lm_q1q2_score": 0.7468875131853003}}
{"text": "(*  Title:      HOL/Hahn_Banach/Normed_Space.thy\n    Author:     Gertrud Bauer, TU Munich\n*)\n\nsection \\<open>Normed vector spaces\\<close>\n\ntheory Normed_Space\nimports Subspace\nbegin\n\nsubsection \\<open>Quasinorms\\<close>\n\ntext \\<open>\n  A \\emph{seminorm} @{text \"\\<parallel>\\<cdot>\\<parallel>\"} is a function on a real vector space\n  into the reals that has the following properties: it is positive\n  definite, absolute homogeneous and subadditive.\n\\<close>\n\nlocale seminorm =\n  fixes V :: \"'a\\<Colon>{minus, plus, zero, uminus} set\"\n  fixes norm :: \"'a \\<Rightarrow> real\"    (\"\\<parallel>_\\<parallel>\")\n  assumes ge_zero [iff?]: \"x \\<in> V \\<Longrightarrow> 0 \\<le> \\<parallel>x\\<parallel>\"\n    and abs_homogenous [iff?]: \"x \\<in> V \\<Longrightarrow> \\<parallel>a \\<cdot> x\\<parallel> = \\<bar>a\\<bar> * \\<parallel>x\\<parallel>\"\n    and subadditive [iff?]: \"x \\<in> V \\<Longrightarrow> y \\<in> V \\<Longrightarrow> \\<parallel>x + y\\<parallel> \\<le> \\<parallel>x\\<parallel> + \\<parallel>y\\<parallel>\"\n\ndeclare seminorm.intro [intro?]\n\nlemma (in seminorm) diff_subadditive:\n  assumes \"vectorspace V\"\n  shows \"x \\<in> V \\<Longrightarrow> y \\<in> V \\<Longrightarrow> \\<parallel>x - y\\<parallel> \\<le> \\<parallel>x\\<parallel> + \\<parallel>y\\<parallel>\"\nproof -\n  interpret vectorspace V by fact\n  assume x: \"x \\<in> V\" and y: \"y \\<in> V\"\n  then have \"x - y = x + - 1 \\<cdot> y\"\n    by (simp add: diff_eq2 negate_eq2a)\n  also from x y have \"\\<parallel>\\<dots>\\<parallel> \\<le> \\<parallel>x\\<parallel> + \\<parallel>- 1 \\<cdot> y\\<parallel>\"\n    by (simp add: subadditive)\n  also from y have \"\\<parallel>- 1 \\<cdot> y\\<parallel> = \\<bar>- 1\\<bar> * \\<parallel>y\\<parallel>\"\n    by (rule abs_homogenous)\n  also have \"\\<dots> = \\<parallel>y\\<parallel>\" by simp\n  finally show ?thesis .\nqed\n\nlemma (in seminorm) minus:\n  assumes \"vectorspace V\"\n  shows \"x \\<in> V \\<Longrightarrow> \\<parallel>- x\\<parallel> = \\<parallel>x\\<parallel>\"\nproof -\n  interpret vectorspace V by fact\n  assume x: \"x \\<in> V\"\n  then have \"- x = - 1 \\<cdot> x\" by (simp only: negate_eq1)\n  also from x have \"\\<parallel>\\<dots>\\<parallel> = \\<bar>- 1\\<bar> * \\<parallel>x\\<parallel>\" by (rule abs_homogenous)\n  also have \"\\<dots> = \\<parallel>x\\<parallel>\" by simp\n  finally show ?thesis .\nqed\n\n\nsubsection \\<open>Norms\\<close>\n\ntext \\<open>\n  A \\emph{norm} @{text \"\\<parallel>\\<cdot>\\<parallel>\"} is a seminorm that maps only the\n  @{text 0} vector to @{text 0}.\n\\<close>\n\nlocale norm = seminorm +\n  assumes zero_iff [iff]: \"x \\<in> V \\<Longrightarrow> (\\<parallel>x\\<parallel> = 0) = (x = 0)\"\n\n\nsubsection \\<open>Normed vector spaces\\<close>\n\ntext \\<open>\n  A vector space together with a norm is called a \\emph{normed\n  space}.\n\\<close>\n\nlocale normed_vectorspace = vectorspace + norm\n\ndeclare normed_vectorspace.intro [intro?]\n\nlemma (in normed_vectorspace) gt_zero [intro?]:\n  assumes x: \"x \\<in> V\" and neq: \"x \\<noteq> 0\"\n  shows \"0 < \\<parallel>x\\<parallel>\"\nproof -\n  from x have \"0 \\<le> \\<parallel>x\\<parallel>\" ..\n  also have \"0 \\<noteq> \\<parallel>x\\<parallel>\"\n  proof\n    assume \"0 = \\<parallel>x\\<parallel>\"\n    with x have \"x = 0\" by simp\n    with neq show False by contradiction\n  qed\n  finally show ?thesis .\nqed\n\ntext \\<open>\n  Any subspace of a normed vector space is again a normed vectorspace.\n\\<close>\n\nlemma subspace_normed_vs [intro?]:\n  fixes F E norm\n  assumes \"subspace F E\" \"normed_vectorspace E norm\"\n  shows \"normed_vectorspace F norm\"\nproof -\n  interpret subspace F E by fact\n  interpret normed_vectorspace E norm by fact\n  show ?thesis\n  proof\n    show \"vectorspace F\" by (rule vectorspace) unfold_locales\n  next\n    have \"Normed_Space.norm E norm\" ..\n    with subset show \"Normed_Space.norm F norm\"\n      by (simp add: norm_def seminorm_def norm_axioms_def)\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/Hahn_Banach/Normed_Space.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045907347107, "lm_q2_score": 0.8418256412990657, "lm_q1q2_score": 0.7468715735587229}}
{"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_33\n  imports \"../../Test_Base\"\nbegin\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 min :: \"Nat => Nat => Nat\" where\n  \"min (Z) z = Z\"\n| \"min (S z2) (Z) = Z\"\n| \"min (S z2) (S y1) = S (min z2 y1)\"\n\nfun t2 :: \"Nat => Nat => bool\" where\n  \"t2 (Z) z = True\"\n| \"t2 (S z2) (Z) = False\"\n| \"t2 (S z2) (S x2) = t2 z2 x2\"\n\ntheorem property0 :(* A bit similar to TIP_prop_24.thy *)\n  \"((x (min a b) a) = (t2 a b))\"\n  find_proof DInd\n  apply (induct rule: TIP_prop_33.x.induct)\n     apply auto\n  done \n    (*Why does \"x.induct\" lead to the shortest proof?\n  Because \"x\"'s pattern-matching is complete, meaning that it does not involve any wild-card.*)\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_33.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.896251378675949, "lm_q2_score": 0.8333246015211008, "lm_q1q2_score": 0.7468683229978723}}
{"text": "(*\n  File:   Prime_Harmonic.thy\n  Author: Manuel Eberl <manuel@pruvisto.org>\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": "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/Prime_Harmonic_Series/Prime_Harmonic.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245953120233, "lm_q2_score": 0.8962513765975758, "lm_q1q2_score": 0.7468683157010186}}
{"text": "(*  Title:      HOL/Real_Vector_Spaces.thy\n    Author:     Brian Huffman\n    Author:     Johannes H\u00f6lzl\n*)\n\nsection \\<open>Vector Spaces and Algebras over the Reals\\<close>\n\ntheory Real_Vector_Spaces              \nimports Real Topological_Spaces Vector_Spaces\nbegin                                   \n\nsubsection \\<open>Real vector spaces\\<close>\n\nclass scaleR =\n  fixes scaleR :: \"real \\<Rightarrow> 'a \\<Rightarrow> 'a\" (infixr \"*\\<^sub>R\" 75)\nbegin\n\nabbreviation divideR :: \"'a \\<Rightarrow> real \\<Rightarrow> 'a\"  (infixl \"'/\\<^sub>R\" 70)\n  where \"x /\\<^sub>R r \\<equiv> inverse r *\\<^sub>R x\"\n\nend\n\nclass real_vector = scaleR + ab_group_add +\n  assumes scaleR_add_right: \"a *\\<^sub>R (x + y) = a *\\<^sub>R x + a *\\<^sub>R y\"\n  and scaleR_add_left: \"(a + b) *\\<^sub>R x = a *\\<^sub>R x + b *\\<^sub>R x\"\n  and scaleR_scaleR: \"a *\\<^sub>R b *\\<^sub>R x = (a * b) *\\<^sub>R x\"\n  and scaleR_one: \"1 *\\<^sub>R x = x\"\n\nclass real_algebra = real_vector + ring +\n  assumes mult_scaleR_left [simp]: \"a *\\<^sub>R x * y = a *\\<^sub>R (x * y)\"\n    and mult_scaleR_right [simp]: \"x * a *\\<^sub>R y = a *\\<^sub>R (x * y)\"\n\nclass real_algebra_1 = real_algebra + ring_1\n\nclass real_div_algebra = real_algebra_1 + division_ring\n\nclass real_field = real_div_algebra + field\n\ninstantiation real :: real_field\nbegin\n\ndefinition real_scaleR_def [simp]: \"scaleR a x = a * x\"\n\ninstance\n  by standard (simp_all add: algebra_simps)\n\nend\n\nlocale linear = Vector_Spaces.linear \"scaleR::_\\<Rightarrow>_\\<Rightarrow>'a::real_vector\" \"scaleR::_\\<Rightarrow>_\\<Rightarrow>'b::real_vector\"\nbegin\n\nlemmas scaleR = scale\n\nend\n\nglobal_interpretation real_vector?: vector_space \"scaleR :: real \\<Rightarrow> 'a \\<Rightarrow> 'a :: real_vector\"\n  rewrites \"Vector_Spaces.linear (*\\<^sub>R) (*\\<^sub>R) = linear\"\n    and \"Vector_Spaces.linear (*) (*\\<^sub>R) = linear\"\n  defines dependent_raw_def: dependent = real_vector.dependent\n    and representation_raw_def: representation = real_vector.representation\n    and subspace_raw_def: subspace = real_vector.subspace\n    and span_raw_def: span = real_vector.span\n    and extend_basis_raw_def: extend_basis = real_vector.extend_basis\n    and dim_raw_def: dim = real_vector.dim\nproof unfold_locales\n  show \"Vector_Spaces.linear (*\\<^sub>R) (*\\<^sub>R) = linear\" \"Vector_Spaces.linear (*) (*\\<^sub>R) = linear\"\n    by (force simp: linear_def real_scaleR_def[abs_def])+\nqed (use scaleR_add_right scaleR_add_left scaleR_scaleR scaleR_one in auto)\n\nhide_const (open)\\<comment> \\<open>locale constants\\<close>\n  real_vector.dependent\n  real_vector.independent\n  real_vector.representation\n  real_vector.subspace\n  real_vector.span\n  real_vector.extend_basis\n  real_vector.dim\n\nabbreviation \"independent x \\<equiv> \\<not> dependent x\"\n\nglobal_interpretation real_vector?: vector_space_pair \"scaleR::_\\<Rightarrow>_\\<Rightarrow>'a::real_vector\" \"scaleR::_\\<Rightarrow>_\\<Rightarrow>'b::real_vector\"\n  rewrites  \"Vector_Spaces.linear (*\\<^sub>R) (*\\<^sub>R) = linear\"\n    and \"Vector_Spaces.linear (*) (*\\<^sub>R) = linear\"\n  defines construct_raw_def: construct = real_vector.construct\nproof unfold_locales\n  show \"Vector_Spaces.linear (*) (*\\<^sub>R) = linear\"\n  unfolding linear_def real_scaleR_def by auto\nqed (auto simp: linear_def)\n\nhide_const (open)\\<comment> \\<open>locale constants\\<close>\n  real_vector.construct\n\nlemma linear_compose: \"linear f \\<Longrightarrow> linear g \\<Longrightarrow> linear (g \\<circ> f)\"\n  unfolding linear_def by (rule Vector_Spaces.linear_compose)\n\ntext \\<open>Recover original theorem names\\<close>\n\nlemmas scaleR_left_commute = real_vector.scale_left_commute\nlemmas scaleR_zero_left = real_vector.scale_zero_left\nlemmas scaleR_minus_left = real_vector.scale_minus_left\nlemmas scaleR_diff_left = real_vector.scale_left_diff_distrib\nlemmas scaleR_sum_left = real_vector.scale_sum_left\nlemmas scaleR_zero_right = real_vector.scale_zero_right\nlemmas scaleR_minus_right = real_vector.scale_minus_right\nlemmas scaleR_diff_right = real_vector.scale_right_diff_distrib\nlemmas scaleR_sum_right = real_vector.scale_sum_right\nlemmas scaleR_eq_0_iff = real_vector.scale_eq_0_iff\nlemmas scaleR_left_imp_eq = real_vector.scale_left_imp_eq\nlemmas scaleR_right_imp_eq = real_vector.scale_right_imp_eq\nlemmas scaleR_cancel_left = real_vector.scale_cancel_left\nlemmas scaleR_cancel_right = real_vector.scale_cancel_right\n\nlemma [field_simps]:\n  \"c \\<noteq> 0 \\<Longrightarrow> a = b /\\<^sub>R c \\<longleftrightarrow> c *\\<^sub>R a = b\"\n  \"c \\<noteq> 0 \\<Longrightarrow> b /\\<^sub>R c = a \\<longleftrightarrow> b = c *\\<^sub>R a\"\n  \"c \\<noteq> 0 \\<Longrightarrow> a + b /\\<^sub>R c = (c *\\<^sub>R a + b) /\\<^sub>R c\"\n  \"c \\<noteq> 0 \\<Longrightarrow> a /\\<^sub>R c + b = (a + c *\\<^sub>R b) /\\<^sub>R c\"\n  \"c \\<noteq> 0 \\<Longrightarrow> a - b /\\<^sub>R c = (c *\\<^sub>R a - b) /\\<^sub>R c\"\n  \"c \\<noteq> 0 \\<Longrightarrow> a /\\<^sub>R c - b = (a - c *\\<^sub>R b) /\\<^sub>R c\"\n  \"c \\<noteq> 0 \\<Longrightarrow> - (a /\\<^sub>R c) + b = (- a + c *\\<^sub>R b) /\\<^sub>R c\"\n  \"c \\<noteq> 0 \\<Longrightarrow> - (a /\\<^sub>R c) - b = (- a - c *\\<^sub>R b) /\\<^sub>R c\"\n  for a b :: \"'a :: real_vector\"\n  by (auto simp add: scaleR_add_right scaleR_add_left scaleR_diff_right scaleR_diff_left)\n\n\ntext \\<open>Legacy names\\<close>\n\nlemmas scaleR_left_distrib = scaleR_add_left\nlemmas scaleR_right_distrib = scaleR_add_right\nlemmas scaleR_left_diff_distrib = scaleR_diff_left\nlemmas scaleR_right_diff_distrib = scaleR_diff_right\n\nlemmas linear_injective_0 = linear_inj_iff_eq_0\n  and linear_injective_on_subspace_0 = linear_inj_on_iff_eq_0\n  and linear_cmul = linear_scale\n  and linear_scaleR = linear_scale_self\n  and subspace_mul = subspace_scale\n  and span_linear_image = linear_span_image\n  and span_0 = span_zero\n  and span_mul = span_scale\n  and injective_scaleR = injective_scale\n\nlemma scaleR_minus1_left [simp]: \"scaleR (-1) x = - x\"\n  for x :: \"'a::real_vector\"\n  using scaleR_minus_left [of 1 x] by simp\n\nlemma scaleR_2:\n  fixes x :: \"'a::real_vector\"\n  shows \"scaleR 2 x = x + x\"\n  unfolding one_add_one [symmetric] scaleR_left_distrib by simp\n\nlemma scaleR_half_double [simp]:\n  fixes a :: \"'a::real_vector\"\n  shows \"(1 / 2) *\\<^sub>R (a + a) = a\"\nproof -\n  have \"\\<And>r. r *\\<^sub>R (a + a) = (r * 2) *\\<^sub>R a\"\n    by (metis scaleR_2 scaleR_scaleR)\n  then show ?thesis\n    by simp\nqed\n\nlemma shift_zero_ident [simp]:\n  fixes f :: \"'a \\<Rightarrow> 'b::real_vector\"\n  shows \"(+)0 \\<circ> f = f\"\n  by force\n  \nlemma linear_scale_real:\n  fixes r::real shows \"linear f \\<Longrightarrow> f (r * b) = r * f b\"\n  using linear_scale by fastforce\n\ninterpretation scaleR_left: additive \"(\\<lambda>a. scaleR a x :: 'a::real_vector)\"\n  by standard (rule scaleR_left_distrib)\n\ninterpretation scaleR_right: additive \"(\\<lambda>x. scaleR a x :: 'a::real_vector)\"\n  by standard (rule scaleR_right_distrib)\n\nlemma nonzero_inverse_scaleR_distrib:\n  \"a \\<noteq> 0 \\<Longrightarrow> x \\<noteq> 0 \\<Longrightarrow> inverse (scaleR a x) = scaleR (inverse a) (inverse x)\"\n  for x :: \"'a::real_div_algebra\"\n  by (rule inverse_unique) simp\n\nlemma inverse_scaleR_distrib: \"inverse (scaleR a x) = scaleR (inverse a) (inverse x)\"\n  for x :: \"'a::{real_div_algebra,division_ring}\"\n  by (metis inverse_zero nonzero_inverse_scaleR_distrib scale_eq_0_iff)\n\nlemmas sum_constant_scaleR = real_vector.sum_constant_scale\\<comment> \\<open>legacy name\\<close>\n\nnamed_theorems vector_add_divide_simps \"to simplify sums of scaled vectors\"\n\nlemma [vector_add_divide_simps]:\n  \"v + (b / z) *\\<^sub>R w = (if z = 0 then v else (z *\\<^sub>R v + b *\\<^sub>R w) /\\<^sub>R z)\"\n  \"a *\\<^sub>R v + (b / z) *\\<^sub>R w = (if z = 0 then a *\\<^sub>R v else ((a * z) *\\<^sub>R v + b *\\<^sub>R w) /\\<^sub>R z)\"\n  \"(a / z) *\\<^sub>R v + w = (if z = 0 then w else (a *\\<^sub>R v + z *\\<^sub>R w) /\\<^sub>R z)\"\n  \"(a / z) *\\<^sub>R v + b *\\<^sub>R w = (if z = 0 then b *\\<^sub>R w else (a *\\<^sub>R v + (b * z) *\\<^sub>R w) /\\<^sub>R z)\"\n  \"v - (b / z) *\\<^sub>R w = (if z = 0 then v else (z *\\<^sub>R v - b *\\<^sub>R w) /\\<^sub>R z)\"\n  \"a *\\<^sub>R v - (b / z) *\\<^sub>R w = (if z = 0 then a *\\<^sub>R v else ((a * z) *\\<^sub>R v - b *\\<^sub>R w) /\\<^sub>R z)\"\n  \"(a / z) *\\<^sub>R v - w = (if z = 0 then -w else (a *\\<^sub>R v - z *\\<^sub>R w) /\\<^sub>R z)\"\n  \"(a / z) *\\<^sub>R v - b *\\<^sub>R w = (if z = 0 then -b *\\<^sub>R w else (a *\\<^sub>R v - (b * z) *\\<^sub>R w) /\\<^sub>R z)\"\n  for v :: \"'a :: real_vector\"\n  by (simp_all add: divide_inverse_commute scaleR_add_right scaleR_diff_right)\n\n\nlemma eq_vector_fraction_iff [vector_add_divide_simps]:\n  fixes x :: \"'a :: real_vector\"\n  shows \"(x = (u / v) *\\<^sub>R a) \\<longleftrightarrow> (if v=0 then x = 0 else v *\\<^sub>R x = u *\\<^sub>R a)\"\nby auto (metis (no_types) divide_eq_1_iff divide_inverse_commute scaleR_one scaleR_scaleR)\n\nlemma vector_fraction_eq_iff [vector_add_divide_simps]:\n  fixes x :: \"'a :: real_vector\"\n  shows \"((u / v) *\\<^sub>R a = x) \\<longleftrightarrow> (if v=0 then x = 0 else u *\\<^sub>R a = v *\\<^sub>R x)\"\nby (metis eq_vector_fraction_iff)\n\nlemma real_vector_affinity_eq:\n  fixes x :: \"'a :: real_vector\"\n  assumes m0: \"m \\<noteq> 0\"\n  shows \"m *\\<^sub>R x + c = y \\<longleftrightarrow> x = inverse m *\\<^sub>R y - (inverse m *\\<^sub>R c)\"\n    (is \"?lhs \\<longleftrightarrow> ?rhs\")\nproof\n  assume ?lhs\n  then have \"m *\\<^sub>R x = y - c\" by (simp add: field_simps)\n  then have \"inverse m *\\<^sub>R (m *\\<^sub>R x) = inverse m *\\<^sub>R (y - c)\" by simp\n  then show \"x = inverse m *\\<^sub>R y - (inverse m *\\<^sub>R c)\"\n    using m0\n  by (simp add: scaleR_diff_right)\nnext\n  assume ?rhs\n  with m0 show \"m *\\<^sub>R x + c = y\"\n    by (simp add: scaleR_diff_right)\nqed\n\nlemma real_vector_eq_affinity: \"m \\<noteq> 0 \\<Longrightarrow> y = m *\\<^sub>R x + c \\<longleftrightarrow> inverse m *\\<^sub>R y - (inverse m *\\<^sub>R c) = x\"\n  for x :: \"'a::real_vector\"\n  using real_vector_affinity_eq[where m=m and x=x and y=y and c=c]\n  by metis\n\nlemma scaleR_eq_iff [simp]: \"b + u *\\<^sub>R a = a + u *\\<^sub>R b \\<longleftrightarrow> a = b \\<or> u = 1\"\n  for a :: \"'a::real_vector\"\nproof (cases \"u = 1\")\n  case True\n  then show ?thesis by auto\nnext\n  case False\n  have \"a = b\" if \"b + u *\\<^sub>R a = a + u *\\<^sub>R b\"\n  proof -\n    from that have \"(u - 1) *\\<^sub>R a = (u - 1) *\\<^sub>R b\"\n      by (simp add: algebra_simps)\n    with False show ?thesis\n      by auto\n  qed\n  then show ?thesis by auto\nqed\n\nlemma scaleR_collapse [simp]: \"(1 - u) *\\<^sub>R a + u *\\<^sub>R a = a\"\n  for a :: \"'a::real_vector\"\n  by (simp add: algebra_simps)\n\n\nsubsection \\<open>Embedding of the Reals into any \\<open>real_algebra_1\\<close>: \\<open>of_real\\<close>\\<close>\n\ndefinition of_real :: \"real \\<Rightarrow> 'a::real_algebra_1\"\n  where \"of_real r = scaleR r 1\"\n\nlemma scaleR_conv_of_real: \"scaleR r x = of_real r * x\"\n  by (simp add: of_real_def)\n\nlemma of_real_0 [simp]: \"of_real 0 = 0\"\n  by (simp add: of_real_def)\n\nlemma of_real_1 [simp]: \"of_real 1 = 1\"\n  by (simp add: of_real_def)\n\nlemma of_real_add [simp]: \"of_real (x + y) = of_real x + of_real y\"\n  by (simp add: of_real_def scaleR_left_distrib)\n\nlemma of_real_minus [simp]: \"of_real (- x) = - of_real x\"\n  by (simp add: of_real_def)\n\nlemma of_real_diff [simp]: \"of_real (x - y) = of_real x - of_real y\"\n  by (simp add: of_real_def scaleR_left_diff_distrib)\n\nlemma of_real_mult [simp]: \"of_real (x * y) = of_real x * of_real y\"\n  by (simp add: of_real_def)\n\nlemma of_real_sum[simp]: \"of_real (sum f s) = (\\<Sum>x\\<in>s. of_real (f x))\"\n  by (induct s rule: infinite_finite_induct) auto\n\nlemma of_real_prod[simp]: \"of_real (prod f s) = (\\<Prod>x\\<in>s. of_real (f x))\"\n  by (induct s rule: infinite_finite_induct) auto\n\nlemma nonzero_of_real_inverse:\n  \"x \\<noteq> 0 \\<Longrightarrow> of_real (inverse x) = inverse (of_real x :: 'a::real_div_algebra)\"\n  by (simp add: of_real_def nonzero_inverse_scaleR_distrib)\n\nlemma of_real_inverse [simp]:\n  \"of_real (inverse x) = inverse (of_real x :: 'a::{real_div_algebra,division_ring})\"\n  by (simp add: of_real_def inverse_scaleR_distrib)\n\nlemma nonzero_of_real_divide:\n  \"y \\<noteq> 0 \\<Longrightarrow> of_real (x / y) = (of_real x / of_real y :: 'a::real_field)\"\n  by (simp add: divide_inverse nonzero_of_real_inverse)\n\nlemma of_real_divide [simp]:\n  \"of_real (x / y) = (of_real x / of_real y :: 'a::real_div_algebra)\"\n  by (simp add: divide_inverse)\n\nlemma of_real_power [simp]:\n  \"of_real (x ^ n) = (of_real x :: 'a::{real_algebra_1}) ^ n\"\n  by (induct n) simp_all\n\nlemma of_real_power_int [simp]:\n  \"of_real (power_int x n) = power_int (of_real x :: 'a :: {real_div_algebra,division_ring}) n\"\n  by (auto simp: power_int_def)\n\nlemma of_real_eq_iff [simp]: \"of_real x = of_real y \\<longleftrightarrow> x = y\"\n  by (simp add: of_real_def)\n\nlemma inj_of_real: \"inj of_real\"\n  by (auto intro: injI)\n\nlemmas of_real_eq_0_iff [simp] = of_real_eq_iff [of _ 0, simplified]\nlemmas of_real_eq_1_iff [simp] = of_real_eq_iff [of _ 1, simplified]\n\nlemma minus_of_real_eq_of_real_iff [simp]: \"-of_real x = of_real y \\<longleftrightarrow> -x = y\"\n  using of_real_eq_iff[of \"-x\" y] by (simp only: of_real_minus)\n\nlemma of_real_eq_minus_of_real_iff [simp]: \"of_real x = -of_real y \\<longleftrightarrow> x = -y\"\n  using of_real_eq_iff[of x \"-y\"] by (simp only: of_real_minus)\n\nlemma of_real_eq_id [simp]: \"of_real = (id :: real \\<Rightarrow> real)\"\n  by (rule ext) (simp add: of_real_def)\n\ntext \\<open>Collapse nested embeddings.\\<close>\nlemma of_real_of_nat_eq [simp]: \"of_real (of_nat n) = of_nat n\"\n  by (induct n) auto\n\nlemma of_real_of_int_eq [simp]: \"of_real (of_int z) = of_int z\"\n  by (cases z rule: int_diff_cases) simp\n\nlemma of_real_numeral [simp]: \"of_real (numeral w) = numeral w\"\n  using of_real_of_int_eq [of \"numeral w\"] by simp\n\nlemma of_real_neg_numeral [simp]: \"of_real (- numeral w) = - numeral w\"\n  using of_real_of_int_eq [of \"- numeral w\"] by simp\n\nlemma numeral_power_int_eq_of_real_cancel_iff [simp]:\n  \"power_int (numeral x) n = (of_real y :: 'a :: {real_div_algebra, division_ring}) \\<longleftrightarrow>\n     power_int (numeral x) n = y\"\nproof -\n  have \"power_int (numeral x) n = (of_real (power_int (numeral x) n) :: 'a)\"\n    by simp\n  also have \"\\<dots> = of_real y \\<longleftrightarrow> power_int (numeral x) n = y\"\n    by (subst of_real_eq_iff) auto\n  finally show ?thesis .\nqed\n\nlemma of_real_eq_numeral_power_int_cancel_iff [simp]:\n  \"(of_real y :: 'a :: {real_div_algebra, division_ring}) = power_int (numeral x) n \\<longleftrightarrow>\n     y = power_int (numeral x) n\"\n  by (subst (1 2) eq_commute) simp\n\nlemma of_real_eq_of_real_power_int_cancel_iff [simp]:\n  \"power_int (of_real b :: 'a :: {real_div_algebra, division_ring}) w = of_real x \\<longleftrightarrow>\n     power_int b w = x\"\n  by (metis of_real_power_int of_real_eq_iff)\n\nlemma of_real_in_Ints_iff [simp]: \"of_real x \\<in> \\<int> \\<longleftrightarrow> x \\<in> \\<int>\"\nproof safe\n  fix x assume \"(of_real x :: 'a) \\<in> \\<int>\"\n  then obtain n where \"(of_real x :: 'a) = of_int n\"\n    by (auto simp: Ints_def)\n  also have \"of_int n = of_real (real_of_int n)\"\n    by simp\n  finally have \"x = real_of_int n\"\n    by (subst (asm) of_real_eq_iff)\n  thus \"x \\<in> \\<int>\"\n    by auto\nqed (auto simp: Ints_def)\n\nlemma Ints_of_real [intro]: \"x \\<in> \\<int> \\<Longrightarrow> of_real x \\<in> \\<int>\"\n  by simp\n\n\ntext \\<open>Every real algebra has characteristic zero.\\<close>\ninstance real_algebra_1 < ring_char_0\nproof\n  from inj_of_real inj_of_nat have \"inj (of_real \\<circ> of_nat)\"\n    by (rule inj_compose)\n  then show \"inj (of_nat :: nat \\<Rightarrow> 'a)\"\n    by (simp add: comp_def)\nqed\n\nlemma fraction_scaleR_times [simp]:\n  fixes a :: \"'a::real_algebra_1\"\n  shows \"(numeral u / numeral v) *\\<^sub>R (numeral w * a) = (numeral u * numeral w / numeral v) *\\<^sub>R a\"\nby (metis (no_types, lifting) of_real_numeral scaleR_conv_of_real scaleR_scaleR times_divide_eq_left)\n\nlemma inverse_scaleR_times [simp]:\n  fixes a :: \"'a::real_algebra_1\"\n  shows \"(1 / numeral v) *\\<^sub>R (numeral w * a) = (numeral w / numeral v) *\\<^sub>R a\"\nby (metis divide_inverse_commute inverse_eq_divide of_real_numeral scaleR_conv_of_real scaleR_scaleR)\n\nlemma scaleR_times [simp]:\n  fixes a :: \"'a::real_algebra_1\"\n  shows \"(numeral u) *\\<^sub>R (numeral w * a) = (numeral u * numeral w) *\\<^sub>R a\"\nby (simp add: scaleR_conv_of_real)\n\ninstance real_field < field_char_0 ..\n\n\nsubsection \\<open>The Set of Real Numbers\\<close>\n\ndefinition Reals :: \"'a::real_algebra_1 set\"  (\"\\<real>\")\n  where \"\\<real> = range of_real\"\n\nlemma Reals_of_real [simp]: \"of_real r \\<in> \\<real>\"\n  by (simp add: Reals_def)\n\nlemma Reals_of_int [simp]: \"of_int z \\<in> \\<real>\"\n  by (subst of_real_of_int_eq [symmetric], rule Reals_of_real)\n\nlemma Reals_of_nat [simp]: \"of_nat n \\<in> \\<real>\"\n  by (subst of_real_of_nat_eq [symmetric], rule Reals_of_real)\n\nlemma Reals_numeral [simp]: \"numeral w \\<in> \\<real>\"\n  by (subst of_real_numeral [symmetric], rule Reals_of_real)\n\nlemma Reals_0 [simp]: \"0 \\<in> \\<real>\" and Reals_1 [simp]: \"1 \\<in> \\<real>\"\n  by (simp_all add: Reals_def)\n\nlemma Reals_add [simp]: \"a \\<in> \\<real> \\<Longrightarrow> b \\<in> \\<real> \\<Longrightarrow> a + b \\<in> \\<real>\"\n  by (metis (no_types, opaque_lifting) Reals_def Reals_of_real imageE of_real_add)\n\nlemma Reals_minus [simp]: \"a \\<in> \\<real> \\<Longrightarrow> - a \\<in> \\<real>\"\n  by (auto simp: Reals_def)\n\nlemma Reals_minus_iff [simp]: \"- a \\<in> \\<real> \\<longleftrightarrow> a \\<in> \\<real>\"\n  using Reals_minus by fastforce\n\nlemma Reals_diff [simp]: \"a \\<in> \\<real> \\<Longrightarrow> b \\<in> \\<real> \\<Longrightarrow> a - b \\<in> \\<real>\"\n  by (metis Reals_add Reals_minus_iff add_uminus_conv_diff)\n\nlemma Reals_mult [simp]: \"a \\<in> \\<real> \\<Longrightarrow> b \\<in> \\<real> \\<Longrightarrow> a * b \\<in> \\<real>\"\n  by (metis (no_types, lifting) Reals_def Reals_of_real imageE of_real_mult)\n\nlemma nonzero_Reals_inverse: \"a \\<in> \\<real> \\<Longrightarrow> a \\<noteq> 0 \\<Longrightarrow> inverse a \\<in> \\<real>\"\n  for a :: \"'a::real_div_algebra\"\n  by (metis Reals_def Reals_of_real imageE of_real_inverse)\n\nlemma Reals_inverse: \"a \\<in> \\<real> \\<Longrightarrow> inverse a \\<in> \\<real>\"\n  for a :: \"'a::{real_div_algebra,division_ring}\"\n  using nonzero_Reals_inverse by fastforce\n\nlemma Reals_inverse_iff [simp]: \"inverse x \\<in> \\<real> \\<longleftrightarrow> x \\<in> \\<real>\"\n  for x :: \"'a::{real_div_algebra,division_ring}\"\n  by (metis Reals_inverse inverse_inverse_eq)\n\nlemma nonzero_Reals_divide: \"a \\<in> \\<real> \\<Longrightarrow> b \\<in> \\<real> \\<Longrightarrow> b \\<noteq> 0 \\<Longrightarrow> a / b \\<in> \\<real>\"\n  for a b :: \"'a::real_field\"\n  by (simp add: divide_inverse)\n\nlemma Reals_divide [simp]: \"a \\<in> \\<real> \\<Longrightarrow> b \\<in> \\<real> \\<Longrightarrow> a / b \\<in> \\<real>\"\n  for a b :: \"'a::{real_field,field}\"\n  using nonzero_Reals_divide by fastforce\n\nlemma Reals_power [simp]: \"a \\<in> \\<real> \\<Longrightarrow> a ^ n \\<in> \\<real>\"\n  for a :: \"'a::real_algebra_1\"\n  by (metis Reals_def Reals_of_real imageE of_real_power)\n\nlemma Reals_cases [cases set: Reals]:\n  assumes \"q \\<in> \\<real>\"\n  obtains (of_real) r where \"q = of_real r\"\n  unfolding Reals_def\nproof -\n  from \\<open>q \\<in> \\<real>\\<close> have \"q \\<in> range of_real\" unfolding Reals_def .\n  then obtain r where \"q = of_real r\" ..\n  then show thesis ..\nqed\n\nlemma sum_in_Reals [intro,simp]: \"(\\<And>i. i \\<in> s \\<Longrightarrow> f i \\<in> \\<real>) \\<Longrightarrow> sum f s \\<in> \\<real>\"\nproof (induct s rule: infinite_finite_induct)\n  case infinite\n  then show ?case by (metis Reals_0 sum.infinite)\nqed simp_all\n\nlemma prod_in_Reals [intro,simp]: \"(\\<And>i. i \\<in> s \\<Longrightarrow> f i \\<in> \\<real>) \\<Longrightarrow> prod f s \\<in> \\<real>\"\nproof (induct s rule: infinite_finite_induct)\n  case infinite\n  then show ?case by (metis Reals_1 prod.infinite)\nqed simp_all\n\nlemma Reals_induct [case_names of_real, induct set: Reals]:\n  \"q \\<in> \\<real> \\<Longrightarrow> (\\<And>r. P (of_real r)) \\<Longrightarrow> P q\"\n  by (rule Reals_cases) auto\n\n\nsubsection \\<open>Ordered real vector spaces\\<close>\n\nclass ordered_real_vector = real_vector + ordered_ab_group_add +\n  assumes scaleR_left_mono: \"x \\<le> y \\<Longrightarrow> 0 \\<le> a \\<Longrightarrow> a *\\<^sub>R x \\<le> a *\\<^sub>R y\"\n    and scaleR_right_mono: \"a \\<le> b \\<Longrightarrow> 0 \\<le> x \\<Longrightarrow> a *\\<^sub>R x \\<le> b *\\<^sub>R x\"\nbegin\n\nlemma scaleR_mono:\n  \"a \\<le> b \\<Longrightarrow> x \\<le> y \\<Longrightarrow> 0 \\<le> b \\<Longrightarrow> 0 \\<le> x \\<Longrightarrow> a *\\<^sub>R x \\<le> b *\\<^sub>R y\"\n  by (meson order_trans scaleR_left_mono scaleR_right_mono)\n  \nlemma scaleR_mono':\n  \"a \\<le> b \\<Longrightarrow> c \\<le> d \\<Longrightarrow> 0 \\<le> a \\<Longrightarrow> 0 \\<le> c \\<Longrightarrow> a *\\<^sub>R c \\<le> b *\\<^sub>R d\"\n  by (rule scaleR_mono) (auto intro: order.trans)\n\nlemma pos_le_divideR_eq [field_simps]:\n  \"a \\<le> b /\\<^sub>R c \\<longleftrightarrow> c *\\<^sub>R a \\<le> b\" (is \"?P \\<longleftrightarrow> ?Q\") if \"0 < c\"\nproof\n  assume ?P\n  with scaleR_left_mono that have \"c *\\<^sub>R a \\<le> c *\\<^sub>R (b /\\<^sub>R c)\"\n    by simp\n  with that show ?Q\n    by (simp add: scaleR_one scaleR_scaleR inverse_eq_divide)\nnext\n  assume ?Q\n  with scaleR_left_mono that have \"c *\\<^sub>R a /\\<^sub>R c \\<le> b /\\<^sub>R c\"\n    by simp\n  with that show ?P\n    by (simp add: scaleR_one scaleR_scaleR inverse_eq_divide)\nqed\n\nlemma pos_less_divideR_eq [field_simps]:\n  \"a < b /\\<^sub>R c \\<longleftrightarrow> c *\\<^sub>R a < b\" if \"c > 0\"\n  using that pos_le_divideR_eq [of c a b]\n  by (auto simp add: le_less scaleR_scaleR scaleR_one)\n\nlemma pos_divideR_le_eq [field_simps]:\n  \"b /\\<^sub>R c \\<le> a \\<longleftrightarrow> b \\<le> c *\\<^sub>R a\" if \"c > 0\"\n  using that pos_le_divideR_eq [of \"inverse c\" b a] by simp\n\nlemma pos_divideR_less_eq [field_simps]:\n  \"b /\\<^sub>R c < a \\<longleftrightarrow> b < c *\\<^sub>R a\" if \"c > 0\"\n  using that pos_less_divideR_eq [of \"inverse c\" b a] by simp\n\nlemma pos_le_minus_divideR_eq [field_simps]:\n  \"a \\<le> - (b /\\<^sub>R c) \\<longleftrightarrow> c *\\<^sub>R a \\<le> - b\" if \"c > 0\"\n  using that by (metis add_minus_cancel diff_0 left_minus minus_minus neg_le_iff_le\n    scaleR_add_right uminus_add_conv_diff pos_le_divideR_eq)\n  \nlemma pos_less_minus_divideR_eq [field_simps]:\n  \"a < - (b /\\<^sub>R c) \\<longleftrightarrow> c *\\<^sub>R a < - b\" if \"c > 0\"\n  using that by (metis le_less less_le_not_le pos_divideR_le_eq\n    pos_divideR_less_eq pos_le_minus_divideR_eq)\n\nlemma pos_minus_divideR_le_eq [field_simps]:\n  \"- (b /\\<^sub>R c) \\<le> a \\<longleftrightarrow> - b \\<le> c *\\<^sub>R a\" if \"c > 0\"\n  using that by (metis pos_divideR_le_eq pos_le_minus_divideR_eq that\n    inverse_positive_iff_positive le_imp_neg_le minus_minus)\n\nlemma pos_minus_divideR_less_eq [field_simps]:\n  \"- (b /\\<^sub>R c) < a \\<longleftrightarrow> - b < c *\\<^sub>R a\" if \"c > 0\"\n  using that by (simp add: less_le_not_le pos_le_minus_divideR_eq pos_minus_divideR_le_eq) \n\nlemma scaleR_image_atLeastAtMost: \"c > 0 \\<Longrightarrow> scaleR c ` {x..y} = {c *\\<^sub>R x..c *\\<^sub>R y}\"\n  apply (auto intro!: scaleR_left_mono simp: image_iff Bex_def)\n  using pos_divideR_le_eq [of c] pos_le_divideR_eq [of c]\n  apply (meson local.order_eq_iff) \n  done\n\nend\n\nlemma neg_le_divideR_eq [field_simps]:\n  \"a \\<le> b /\\<^sub>R c \\<longleftrightarrow> b \\<le> c *\\<^sub>R a\" (is \"?P \\<longleftrightarrow> ?Q\") if \"c < 0\"\n    for a b :: \"'a :: ordered_real_vector\"\n  using that pos_le_divideR_eq [of \"- c\" a \"- b\"] by simp\n\nlemma neg_less_divideR_eq [field_simps]:\n  \"a < b /\\<^sub>R c \\<longleftrightarrow> b < c *\\<^sub>R a\" if \"c < 0\"\n    for a b :: \"'a :: ordered_real_vector\"\n  using that neg_le_divideR_eq [of c a b] by (auto simp add: le_less)\n\nlemma neg_divideR_le_eq [field_simps]:\n  \"b /\\<^sub>R c \\<le> a \\<longleftrightarrow> c *\\<^sub>R a \\<le> b\" if \"c < 0\"\n    for a b :: \"'a :: ordered_real_vector\"\n  using that pos_divideR_le_eq [of \"- c\" \"- b\" a] by simp\n\nlemma neg_divideR_less_eq [field_simps]:\n  \"b /\\<^sub>R c < a \\<longleftrightarrow> c *\\<^sub>R a < b\" if \"c < 0\"\n    for a b :: \"'a :: ordered_real_vector\"\n  using that neg_divideR_le_eq [of c b a] by (auto simp add: le_less)\n\nlemma neg_le_minus_divideR_eq [field_simps]:\n  \"a \\<le> - (b /\\<^sub>R c) \\<longleftrightarrow> - b \\<le> c *\\<^sub>R a\" if \"c < 0\"\n    for a b :: \"'a :: ordered_real_vector\"\n  using that pos_le_minus_divideR_eq [of \"- c\" a \"- b\"] by (simp add: minus_le_iff)\n  \nlemma neg_less_minus_divideR_eq [field_simps]:\n  \"a < - (b /\\<^sub>R c) \\<longleftrightarrow> - b < c *\\<^sub>R a\" if \"c < 0\"\n   for a b :: \"'a :: ordered_real_vector\"\nproof -\n  have *: \"- b = c *\\<^sub>R a \\<longleftrightarrow> b = - (c *\\<^sub>R a)\"\n    by (metis add.inverse_inverse)\n  from that neg_le_minus_divideR_eq [of c a b]\n  show ?thesis by (auto simp add: le_less *)\nqed\n\nlemma neg_minus_divideR_le_eq [field_simps]:\n  \"- (b /\\<^sub>R c) \\<le> a \\<longleftrightarrow> c *\\<^sub>R a \\<le> - b\" if \"c < 0\"\n    for a b :: \"'a :: ordered_real_vector\"\n  using that pos_minus_divideR_le_eq [of \"- c\" \"- b\" a] by (simp add: le_minus_iff) \n\nlemma neg_minus_divideR_less_eq [field_simps]:\n  \"- (b /\\<^sub>R c) < a \\<longleftrightarrow> c *\\<^sub>R a < - b\" if \"c < 0\"\n    for a b :: \"'a :: ordered_real_vector\"\n  using that by (simp add: less_le_not_le neg_le_minus_divideR_eq neg_minus_divideR_le_eq)\n\nlemma [field_split_simps]:\n  \"a = b /\\<^sub>R c \\<longleftrightarrow> (if c = 0 then a = 0 else c *\\<^sub>R a = b)\"\n  \"b /\\<^sub>R c = a \\<longleftrightarrow> (if c = 0 then a = 0 else b = c *\\<^sub>R a)\"\n  \"a + b /\\<^sub>R c = (if c = 0 then a else (c *\\<^sub>R a + b) /\\<^sub>R c)\"\n  \"a /\\<^sub>R c + b = (if c = 0 then b else (a + c *\\<^sub>R b) /\\<^sub>R c)\"\n  \"a - b /\\<^sub>R c = (if c = 0 then a else (c *\\<^sub>R a - b) /\\<^sub>R c)\"\n  \"a /\\<^sub>R c - b = (if c = 0 then - b else (a - c *\\<^sub>R b) /\\<^sub>R c)\"\n  \"- (a /\\<^sub>R c) + b = (if c = 0 then b else (- a + c *\\<^sub>R b) /\\<^sub>R c)\"\n  \"- (a /\\<^sub>R c) - b = (if c = 0 then - b else (- a - c *\\<^sub>R b) /\\<^sub>R c)\"\n    for a b :: \"'a :: real_vector\"\n  by (auto simp add: field_simps)\n\nlemma [field_split_simps]:\n  \"0 < c \\<Longrightarrow> a \\<le> b /\\<^sub>R c \\<longleftrightarrow> (if c > 0 then c *\\<^sub>R a \\<le> b else if c < 0 then b \\<le> c *\\<^sub>R a else a \\<le> 0)\"\n  \"0 < c \\<Longrightarrow> a < b /\\<^sub>R c \\<longleftrightarrow> (if c > 0 then c *\\<^sub>R a < b else if c < 0 then b < c *\\<^sub>R a else a < 0)\"\n  \"0 < c \\<Longrightarrow> b /\\<^sub>R c \\<le> a \\<longleftrightarrow> (if c > 0 then b \\<le> c *\\<^sub>R a else if c < 0 then c *\\<^sub>R a \\<le> b else a \\<ge> 0)\"\n  \"0 < c \\<Longrightarrow> b /\\<^sub>R c < a \\<longleftrightarrow> (if c > 0 then b < c *\\<^sub>R a else if c < 0 then c *\\<^sub>R a < b else a > 0)\"\n  \"0 < c \\<Longrightarrow> a \\<le> - (b /\\<^sub>R c) \\<longleftrightarrow> (if c > 0 then c *\\<^sub>R a \\<le> - b else if c < 0 then - b \\<le> c *\\<^sub>R a else a \\<le> 0)\"\n  \"0 < c \\<Longrightarrow> a < - (b /\\<^sub>R c) \\<longleftrightarrow> (if c > 0 then c *\\<^sub>R a < - b else if c < 0 then - b < c *\\<^sub>R a else a < 0)\"\n  \"0 < c \\<Longrightarrow> - (b /\\<^sub>R c) \\<le> a \\<longleftrightarrow> (if c > 0 then - b \\<le> c *\\<^sub>R a else if c < 0 then c *\\<^sub>R a \\<le> - b else a \\<ge> 0)\"\n  \"0 < c \\<Longrightarrow> - (b /\\<^sub>R c) < a \\<longleftrightarrow> (if c > 0 then - b < c *\\<^sub>R a else if c < 0 then c *\\<^sub>R a < - b else a > 0)\"\n  for a b :: \"'a :: ordered_real_vector\"\n  by (clarsimp intro!: field_simps)+\n\nlemma scaleR_nonneg_nonneg: \"0 \\<le> a \\<Longrightarrow> 0 \\<le> x \\<Longrightarrow> 0 \\<le> a *\\<^sub>R x\"\n  for x :: \"'a::ordered_real_vector\"\n  using scaleR_left_mono [of 0 x a] by simp\n\nlemma scaleR_nonneg_nonpos: \"0 \\<le> a \\<Longrightarrow> x \\<le> 0 \\<Longrightarrow> a *\\<^sub>R x \\<le> 0\"\n  for x :: \"'a::ordered_real_vector\"\n  using scaleR_left_mono [of x 0 a] by simp\n\nlemma scaleR_nonpos_nonneg: \"a \\<le> 0 \\<Longrightarrow> 0 \\<le> x \\<Longrightarrow> a *\\<^sub>R x \\<le> 0\"\n  for x :: \"'a::ordered_real_vector\"\n  using scaleR_right_mono [of a 0 x] by simp\n\nlemma split_scaleR_neg_le: \"(0 \\<le> a \\<and> x \\<le> 0) \\<or> (a \\<le> 0 \\<and> 0 \\<le> x) \\<Longrightarrow> a *\\<^sub>R x \\<le> 0\"\n  for x :: \"'a::ordered_real_vector\"\n  by (auto simp: scaleR_nonneg_nonpos scaleR_nonpos_nonneg)\n\nlemma le_add_iff1: \"a *\\<^sub>R e + c \\<le> b *\\<^sub>R e + d \\<longleftrightarrow> (a - b) *\\<^sub>R e + c \\<le> d\"\n  for c d e :: \"'a::ordered_real_vector\"\n  by (simp add: algebra_simps)\n\nlemma le_add_iff2: \"a *\\<^sub>R e + c \\<le> b *\\<^sub>R e + d \\<longleftrightarrow> c \\<le> (b - a) *\\<^sub>R e + d\"\n  for c d e :: \"'a::ordered_real_vector\"\n  by (simp add: algebra_simps)\n\nlemma scaleR_left_mono_neg: \"b \\<le> a \\<Longrightarrow> c \\<le> 0 \\<Longrightarrow> c *\\<^sub>R a \\<le> c *\\<^sub>R b\"\n  for a b :: \"'a::ordered_real_vector\"\n  by (drule scaleR_left_mono [of _ _ \"- c\"], simp_all)\n\nlemma scaleR_right_mono_neg: \"b \\<le> a \\<Longrightarrow> c \\<le> 0 \\<Longrightarrow> a *\\<^sub>R c \\<le> b *\\<^sub>R c\"\n  for c :: \"'a::ordered_real_vector\"\n  by (drule scaleR_right_mono [of _ _ \"- c\"], simp_all)\n\nlemma scaleR_nonpos_nonpos: \"a \\<le> 0 \\<Longrightarrow> b \\<le> 0 \\<Longrightarrow> 0 \\<le> a *\\<^sub>R b\"\n  for b :: \"'a::ordered_real_vector\"\n  using scaleR_right_mono_neg [of a 0 b] by simp\n\nlemma split_scaleR_pos_le: \"(0 \\<le> a \\<and> 0 \\<le> b) \\<or> (a \\<le> 0 \\<and> b \\<le> 0) \\<Longrightarrow> 0 \\<le> a *\\<^sub>R b\"\n  for b :: \"'a::ordered_real_vector\"\n  by (auto simp: scaleR_nonneg_nonneg scaleR_nonpos_nonpos)\n\nlemma zero_le_scaleR_iff:\n  fixes b :: \"'a::ordered_real_vector\"\n  shows \"0 \\<le> a *\\<^sub>R b \\<longleftrightarrow> 0 < a \\<and> 0 \\<le> b \\<or> a < 0 \\<and> b \\<le> 0 \\<or> a = 0\"\n    (is \"?lhs = ?rhs\")\nproof (cases \"a = 0\")\n  case True\n  then show ?thesis by simp\nnext\n  case False\n  show ?thesis\n  proof\n    assume ?lhs\n    from \\<open>a \\<noteq> 0\\<close> consider \"a > 0\" | \"a < 0\" by arith\n    then show ?rhs\n    proof cases\n      case 1\n      with \\<open>?lhs\\<close> have \"inverse a *\\<^sub>R 0 \\<le> inverse a *\\<^sub>R (a *\\<^sub>R b)\"\n        by (intro scaleR_mono) auto\n      with 1 show ?thesis\n        by simp\n    next\n      case 2\n      with \\<open>?lhs\\<close> have \"- inverse a *\\<^sub>R 0 \\<le> - inverse a *\\<^sub>R (a *\\<^sub>R b)\"\n        by (intro scaleR_mono) auto\n      with 2 show ?thesis\n        by simp\n    qed\n  next\n    assume ?rhs\n    then show ?lhs\n      by (auto simp: not_le \\<open>a \\<noteq> 0\\<close> intro!: split_scaleR_pos_le)\n  qed\nqed\n\nlemma scaleR_le_0_iff: \"a *\\<^sub>R b \\<le> 0 \\<longleftrightarrow> 0 < a \\<and> b \\<le> 0 \\<or> a < 0 \\<and> 0 \\<le> b \\<or> a = 0\"\n  for b::\"'a::ordered_real_vector\"\n  by (insert zero_le_scaleR_iff [of \"-a\" b]) force\n\nlemma scaleR_le_cancel_left: \"c *\\<^sub>R a \\<le> c *\\<^sub>R b \\<longleftrightarrow> (0 < c \\<longrightarrow> a \\<le> b) \\<and> (c < 0 \\<longrightarrow> b \\<le> a)\"\n  for b :: \"'a::ordered_real_vector\"\n  by (auto simp: neq_iff scaleR_left_mono scaleR_left_mono_neg\n      dest: scaleR_left_mono[where a=\"inverse c\"] scaleR_left_mono_neg[where c=\"inverse c\"])\n\nlemma scaleR_le_cancel_left_pos: \"0 < c \\<Longrightarrow> c *\\<^sub>R a \\<le> c *\\<^sub>R b \\<longleftrightarrow> a \\<le> b\"\n  for b :: \"'a::ordered_real_vector\"\n  by (auto simp: scaleR_le_cancel_left)\n\nlemma scaleR_le_cancel_left_neg: \"c < 0 \\<Longrightarrow> c *\\<^sub>R a \\<le> c *\\<^sub>R b \\<longleftrightarrow> b \\<le> a\"\n  for b :: \"'a::ordered_real_vector\"\n  by (auto simp: scaleR_le_cancel_left)\n\nlemma scaleR_left_le_one_le: \"0 \\<le> x \\<Longrightarrow> a \\<le> 1 \\<Longrightarrow> a *\\<^sub>R x \\<le> x\"\n  for x :: \"'a::ordered_real_vector\" and a :: real\n  using scaleR_right_mono[of a 1 x] by simp\n\n\nsubsection \\<open>Real normed vector spaces\\<close>\n\nclass dist =\n  fixes dist :: \"'a \\<Rightarrow> 'a \\<Rightarrow> real\"\n\nclass norm =\n  fixes norm :: \"'a \\<Rightarrow> real\"\n\nclass sgn_div_norm = scaleR + norm + sgn +\n  assumes sgn_div_norm: \"sgn x = x /\\<^sub>R norm x\"\n\nclass dist_norm = dist + norm + minus +\n  assumes dist_norm: \"dist x y = norm (x - y)\"\n\nclass uniformity_dist = dist + uniformity +\n  assumes uniformity_dist: \"uniformity = (INF e\\<in>{0 <..}. principal {(x, y). dist x y < e})\"\nbegin\n\nlemma eventually_uniformity_metric:\n  \"eventually P uniformity \\<longleftrightarrow> (\\<exists>e>0. \\<forall>x y. dist x y < e \\<longrightarrow> P (x, y))\"\n  unfolding uniformity_dist\n  by (subst eventually_INF_base)\n     (auto simp: eventually_principal subset_eq intro: bexI[of _ \"min _ _\"])\n\nend\n\nclass real_normed_vector = real_vector + sgn_div_norm + dist_norm + uniformity_dist + open_uniformity +\n  assumes norm_eq_zero [simp]: \"norm x = 0 \\<longleftrightarrow> x = 0\"\n    and norm_triangle_ineq: \"norm (x + y) \\<le> norm x + norm y\"\n    and norm_scaleR [simp]: \"norm (scaleR a x) = \\<bar>a\\<bar> * norm x\"\nbegin\n\nlemma norm_ge_zero [simp]: \"0 \\<le> norm x\"\nproof -\n  have \"0 = norm (x + -1 *\\<^sub>R x)\"\n    using scaleR_add_left[of 1 \"-1\" x] norm_scaleR[of 0 x] by (simp add: scaleR_one)\n  also have \"\\<dots> \\<le> norm x + norm (-1 *\\<^sub>R x)\" by (rule norm_triangle_ineq)\n  finally show ?thesis by simp\nqed\n\nlemma bdd_below_norm_image: \"bdd_below (norm ` A)\"\n  by (meson bdd_belowI2 norm_ge_zero)\n\nend\n\nclass real_normed_algebra = real_algebra + real_normed_vector +\n  assumes norm_mult_ineq: \"norm (x * y) \\<le> norm x * norm y\"\n\nclass real_normed_algebra_1 = real_algebra_1 + real_normed_algebra +\n  assumes norm_one [simp]: \"norm 1 = 1\"\n\nlemma (in real_normed_algebra_1) scaleR_power [simp]: \"(scaleR x y) ^ n = scaleR (x^n) (y^n)\"\n  by (induct n) (simp_all add: scaleR_one scaleR_scaleR mult_ac)\n\nclass real_normed_div_algebra = real_div_algebra + real_normed_vector +\n  assumes norm_mult: \"norm (x * y) = norm x * norm y\"\n\nclass real_normed_field = real_field + real_normed_div_algebra\n\ninstance real_normed_div_algebra < real_normed_algebra_1\nproof\n  show \"norm (x * y) \\<le> norm x * norm y\" for x y :: 'a\n    by (simp add: norm_mult)\nnext\n  have \"norm (1 * 1::'a) = norm (1::'a) * norm (1::'a)\"\n    by (rule norm_mult)\n  then show \"norm (1::'a) = 1\" by simp\nqed\n\ncontext real_normed_vector begin\n\nlemma norm_zero [simp]: \"norm (0::'a) = 0\"\n  by simp\n\nlemma zero_less_norm_iff [simp]: \"norm x > 0 \\<longleftrightarrow> x \\<noteq> 0\"\n  by (simp add: order_less_le)\n\nlemma norm_not_less_zero [simp]: \"\\<not> norm x < 0\"\n  by (simp add: linorder_not_less)\n\nlemma norm_le_zero_iff [simp]: \"norm x \\<le> 0 \\<longleftrightarrow> x = 0\"\n  by (simp add: order_le_less)\n\nlemma norm_minus_cancel [simp]: \"norm (- x) = norm x\"\nproof -\n  have \"- 1 *\\<^sub>R x = - (1 *\\<^sub>R x)\"\n    unfolding add_eq_0_iff2[symmetric] scaleR_add_left[symmetric]\n    using norm_eq_zero\n    by fastforce\n  then have \"norm (- x) = norm (scaleR (- 1) x)\"\n    by (simp only: scaleR_one)\n  also have \"\\<dots> = \\<bar>- 1\\<bar> * norm x\"\n    by (rule norm_scaleR)\n  finally show ?thesis by simp\nqed\n\nlemma norm_minus_commute: \"norm (a - b) = norm (b - a)\"\nproof -\n  have \"norm (- (b - a)) = norm (b - a)\"\n    by (rule norm_minus_cancel)\n  then show ?thesis by simp\nqed\n\nlemma dist_add_cancel [simp]: \"dist (a + b) (a + c) = dist b c\"\n  by (simp add: dist_norm)\n\nlemma dist_add_cancel2 [simp]: \"dist (b + a) (c + a) = dist b c\"\n  by (simp add: dist_norm)\n\nlemma norm_uminus_minus: \"norm (- x - y) = norm (x + y)\"\n  by (subst (2) norm_minus_cancel[symmetric], subst minus_add_distrib) simp\n\nlemma norm_triangle_ineq2: \"norm a - norm b \\<le> norm (a - b)\"\nproof -\n  have \"norm (a - b + b) \\<le> norm (a - b) + norm b\"\n    by (rule norm_triangle_ineq)\n  then show ?thesis by simp\nqed\n\nlemma norm_triangle_ineq3: \"\\<bar>norm a - norm b\\<bar> \\<le> norm (a - b)\"\nproof -\n  have \"norm a - norm b \\<le> norm (a - b)\"\n    by (simp add: norm_triangle_ineq2)\n  moreover have \"norm b - norm a \\<le> norm (a - b)\"\n    by (metis norm_minus_commute norm_triangle_ineq2)\n  ultimately show ?thesis\n    by (simp add: abs_le_iff)\nqed\n\nlemma norm_triangle_ineq4: \"norm (a - b) \\<le> norm a + norm b\"\nproof -\n  have \"norm (a + - b) \\<le> norm a + norm (- b)\"\n    by (rule norm_triangle_ineq)\n  then show ?thesis by simp\nqed\n\nlemma norm_triangle_le_diff: \"norm x + norm y \\<le> e \\<Longrightarrow> norm (x - y) \\<le> e\"\n    by (meson norm_triangle_ineq4 order_trans)\n\nlemma norm_diff_ineq: \"norm a - norm b \\<le> norm (a + b)\"\nproof -\n  have \"norm a - norm (- b) \\<le> norm (a - - b)\"\n    by (rule norm_triangle_ineq2)\n  then show ?thesis by simp\nqed\n\nlemma norm_triangle_sub: \"norm x \\<le> norm y + norm (x - y)\"\n  using norm_triangle_ineq[of \"y\" \"x - y\"] by (simp add: field_simps)\n\nlemma norm_triangle_le: \"norm x + norm y \\<le> e \\<Longrightarrow> norm (x + y) \\<le> e\"\n  by (rule norm_triangle_ineq [THEN order_trans])\n\nlemma norm_triangle_lt: \"norm x + norm y < e \\<Longrightarrow> norm (x + y) < e\"\n  by (rule norm_triangle_ineq [THEN le_less_trans])\n\nlemma norm_add_leD: \"norm (a + b) \\<le> c \\<Longrightarrow> norm b \\<le> norm a + c\"\n  by (metis ab_semigroup_add_class.add.commute add_commute diff_le_eq norm_diff_ineq order_trans)\n\nlemma norm_diff_triangle_ineq: \"norm ((a + b) - (c + d)) \\<le> norm (a - c) + norm (b - d)\"\nproof -\n  have \"norm ((a + b) - (c + d)) = norm ((a - c) + (b - d))\"\n    by (simp add: algebra_simps)\n  also have \"\\<dots> \\<le> norm (a - c) + norm (b - d)\"\n    by (rule norm_triangle_ineq)\n  finally show ?thesis .\nqed\n\nlemma norm_diff_triangle_le: \"norm (x - z) \\<le> e1 + e2\"\n  if \"norm (x - y) \\<le> e1\"  \"norm (y - z) \\<le> e2\"\nproof -\n  have \"norm (x - (y + z - y)) \\<le> norm (x - y) + norm (y - z)\"\n    using norm_diff_triangle_ineq that diff_diff_eq2 by presburger\n  with that show ?thesis by simp\nqed\n\nlemma norm_diff_triangle_less: \"norm (x - z) < e1 + e2\"\n  if \"norm (x - y) < e1\"  \"norm (y - z) < e2\"\nproof -\n  have \"norm (x - z) \\<le> norm (x - y) + norm (y - z)\"\n    by (metis norm_diff_triangle_ineq add_diff_cancel_left' diff_diff_eq2)\n  with that show ?thesis by auto\nqed\n\nlemma norm_triangle_mono:\n  \"norm a \\<le> r \\<Longrightarrow> norm b \\<le> s \\<Longrightarrow> norm (a + b) \\<le> r + s\"\n  by (metis (mono_tags) add_mono_thms_linordered_semiring(1) norm_triangle_ineq order.trans)\n\nlemma norm_sum: \"norm (sum f A) \\<le> (\\<Sum>i\\<in>A. norm (f i))\"\n  for f::\"'b \\<Rightarrow> 'a\"\n  by (induct A rule: infinite_finite_induct) (auto intro: norm_triangle_mono)\n\nlemma sum_norm_le: \"norm (sum f S) \\<le> sum g S\"\n  if \"\\<And>x. x \\<in> S \\<Longrightarrow> norm (f x) \\<le> g x\"\n  for f::\"'b \\<Rightarrow> 'a\"\n  by (rule order_trans [OF norm_sum sum_mono]) (simp add: that)\n\nlemma abs_norm_cancel [simp]: \"\\<bar>norm a\\<bar> = norm a\"\n  by (rule abs_of_nonneg [OF norm_ge_zero])\n\nlemma sum_norm_bound:\n  \"norm (sum f S) \\<le> of_nat (card S)*K\"\n  if \"\\<And>x. x \\<in> S \\<Longrightarrow> norm (f x) \\<le> K\"\n  for f :: \"'b \\<Rightarrow> 'a\"\n  using sum_norm_le[OF that] sum_constant[symmetric]\n  by simp\n\nlemma norm_add_less: \"norm x < r \\<Longrightarrow> norm y < s \\<Longrightarrow> norm (x + y) < r + s\"\n  by (rule order_le_less_trans [OF norm_triangle_ineq add_strict_mono])\n\nend\n\nlemma dist_scaleR [simp]: \"dist (x *\\<^sub>R a) (y *\\<^sub>R a) = \\<bar>x - y\\<bar> * norm a\"\n  for a :: \"'a::real_normed_vector\"\n  by (metis dist_norm norm_scaleR scaleR_left.diff)\n\nlemma norm_mult_less: \"norm x < r \\<Longrightarrow> norm y < s \\<Longrightarrow> norm (x * y) < r * s\"\n  for x y :: \"'a::real_normed_algebra\"\n  by (rule order_le_less_trans [OF norm_mult_ineq]) (simp add: mult_strict_mono')\n\nlemma norm_of_real [simp]: \"norm (of_real r :: 'a::real_normed_algebra_1) = \\<bar>r\\<bar>\"\n  by (simp add: of_real_def)\n\nlemma norm_numeral [simp]: \"norm (numeral w::'a::real_normed_algebra_1) = numeral w\"\n  by (subst of_real_numeral [symmetric], subst norm_of_real, simp)\n\nlemma norm_neg_numeral [simp]: \"norm (- numeral w::'a::real_normed_algebra_1) = numeral w\"\n  by (subst of_real_neg_numeral [symmetric], subst norm_of_real, simp)\n\nlemma norm_of_real_add1 [simp]: \"norm (of_real x + 1 :: 'a :: real_normed_div_algebra) = \\<bar>x + 1\\<bar>\"\n  by (metis norm_of_real of_real_1 of_real_add)\n\nlemma norm_of_real_addn [simp]:\n  \"norm (of_real x + numeral b :: 'a :: real_normed_div_algebra) = \\<bar>x + numeral b\\<bar>\"\n  by (metis norm_of_real of_real_add of_real_numeral)\n\nlemma norm_of_int [simp]: \"norm (of_int z::'a::real_normed_algebra_1) = \\<bar>of_int z\\<bar>\"\n  by (subst of_real_of_int_eq [symmetric], rule norm_of_real)\n\nlemma norm_of_nat [simp]: \"norm (of_nat n::'a::real_normed_algebra_1) = of_nat n\"\n  by (metis abs_of_nat norm_of_real of_real_of_nat_eq)\n\nlemma nonzero_norm_inverse: \"a \\<noteq> 0 \\<Longrightarrow> norm (inverse a) = inverse (norm a)\"\n  for a :: \"'a::real_normed_div_algebra\"\n  by (metis inverse_unique norm_mult norm_one right_inverse)\n\nlemma norm_inverse: \"norm (inverse a) = inverse (norm a)\"\n  for a :: \"'a::{real_normed_div_algebra,division_ring}\"\n  by (metis inverse_zero nonzero_norm_inverse norm_zero)\n\nlemma nonzero_norm_divide: \"b \\<noteq> 0 \\<Longrightarrow> norm (a / b) = norm a / norm b\"\n  for a b :: \"'a::real_normed_field\"\n  by (simp add: divide_inverse norm_mult nonzero_norm_inverse)\n\nlemma norm_divide: \"norm (a / b) = norm a / norm b\"\n  for a b :: \"'a::{real_normed_field,field}\"\n  by (simp add: divide_inverse norm_mult norm_inverse)\n\nlemma dist_divide_right: \"dist (a/c) (b/c) = dist a b / norm c\" for c :: \"'a :: real_normed_field\"\n  by (metis diff_divide_distrib dist_norm norm_divide)\n\nlemma norm_inverse_le_norm:\n  fixes x :: \"'a::real_normed_div_algebra\"\n  shows \"r \\<le> norm x \\<Longrightarrow> 0 < r \\<Longrightarrow> norm (inverse x) \\<le> inverse r\"\n  by (simp add: le_imp_inverse_le norm_inverse)\n\nlemma norm_power_ineq: \"norm (x ^ n) \\<le> norm x ^ n\"\n  for x :: \"'a::real_normed_algebra_1\"\nproof (induct n)\n  case 0\n  show \"norm (x ^ 0) \\<le> norm x ^ 0\" by simp\nnext\n  case (Suc n)\n  have \"norm (x * x ^ n) \\<le> norm x * norm (x ^ n)\"\n    by (rule norm_mult_ineq)\n  also from Suc have \"\\<dots> \\<le> norm x * norm x ^ n\"\n    using norm_ge_zero by (rule mult_left_mono)\n  finally show \"norm (x ^ Suc n) \\<le> norm x ^ Suc n\"\n    by simp\nqed\n\nlemma norm_power: \"norm (x ^ n) = norm x ^ n\"\n  for x :: \"'a::real_normed_div_algebra\"\n  by (induct n) (simp_all add: norm_mult)\n\nlemma norm_power_int: \"norm (power_int x n) = power_int (norm x) n\"\n  for x :: \"'a::real_normed_div_algebra\"\n  by (cases n rule: int_cases4) (auto simp: norm_power power_int_minus norm_inverse)\n\nlemma power_eq_imp_eq_norm:\n  fixes w :: \"'a::real_normed_div_algebra\"\n  assumes eq: \"w ^ n = z ^ n\" and \"n > 0\"\n    shows \"norm w = norm z\"\nproof -\n  have \"norm w ^ n = norm z ^ n\"\n    by (metis (no_types) eq norm_power)\n  then show ?thesis\n    using assms by (force intro: power_eq_imp_eq_base)\nqed\n\nlemma power_eq_1_iff:\n  fixes w :: \"'a::real_normed_div_algebra\"\n  shows \"w ^ n = 1 \\<Longrightarrow> norm w = 1 \\<or> n = 0\"\n  by (metis norm_one power_0_left power_eq_0_iff power_eq_imp_eq_norm power_one)\n\nlemma norm_mult_numeral1 [simp]: \"norm (numeral w * a) = numeral w * norm a\"\n  for a b :: \"'a::{real_normed_field,field}\"\n  by (simp add: norm_mult)\n\nlemma norm_mult_numeral2 [simp]: \"norm (a * numeral w) = norm a * numeral w\"\n  for a b :: \"'a::{real_normed_field,field}\"\n  by (simp add: norm_mult)\n\nlemma norm_divide_numeral [simp]: \"norm (a / numeral w) = norm a / numeral w\"\n  for a b :: \"'a::{real_normed_field,field}\"\n  by (simp add: norm_divide)\n\nlemma norm_of_real_diff [simp]:\n  \"norm (of_real b - of_real a :: 'a::real_normed_algebra_1) \\<le> \\<bar>b - a\\<bar>\"\n  by (metis norm_of_real of_real_diff order_refl)\n\ntext \\<open>Despite a superficial resemblance, \\<open>norm_eq_1\\<close> is not relevant.\\<close>\nlemma square_norm_one:\n  fixes x :: \"'a::real_normed_div_algebra\"\n  assumes \"x\\<^sup>2 = 1\"\n  shows \"norm x = 1\"\n  by (metis assms norm_minus_cancel norm_one power2_eq_1_iff)\n\nlemma norm_less_p1: \"norm x < norm (of_real (norm x) + 1 :: 'a)\"\n  for x :: \"'a::real_normed_algebra_1\"\nproof -\n  have \"norm x < norm (of_real (norm x + 1) :: 'a)\"\n    by (simp add: of_real_def)\n  then show ?thesis\n    by simp\nqed\n\nlemma prod_norm: \"prod (\\<lambda>x. norm (f x)) A = norm (prod f A)\"\n  for f :: \"'a \\<Rightarrow> 'b::{comm_semiring_1,real_normed_div_algebra}\"\n  by (induct A rule: infinite_finite_induct) (auto simp: norm_mult)\n\nlemma norm_prod_le:\n  \"norm (prod f A) \\<le> (\\<Prod>a\\<in>A. norm (f a :: 'a :: {real_normed_algebra_1,comm_monoid_mult}))\"\nproof (induct A rule: infinite_finite_induct)\n  case empty\n  then show ?case by simp\nnext\n  case (insert a A)\n  then have \"norm (prod f (insert a A)) \\<le> norm (f a) * norm (prod f A)\"\n    by (simp add: norm_mult_ineq)\n  also have \"norm (prod f A) \\<le> (\\<Prod>a\\<in>A. norm (f a))\"\n    by (rule insert)\n  finally show ?case\n    by (simp add: insert mult_left_mono)\nnext\n  case infinite\n  then show ?case by simp\nqed\n\nlemma norm_prod_diff:\n  fixes z w :: \"'i \\<Rightarrow> 'a::{real_normed_algebra_1, comm_monoid_mult}\"\n  shows \"(\\<And>i. i \\<in> I \\<Longrightarrow> norm (z i) \\<le> 1) \\<Longrightarrow> (\\<And>i. i \\<in> I \\<Longrightarrow> norm (w i) \\<le> 1) \\<Longrightarrow>\n    norm ((\\<Prod>i\\<in>I. z i) - (\\<Prod>i\\<in>I. w i)) \\<le> (\\<Sum>i\\<in>I. norm (z i - w i))\"\nproof (induction I rule: infinite_finite_induct)\n  case empty\n  then show ?case by simp\nnext\n  case (insert i I)\n  note insert.hyps[simp]\n\n  have \"norm ((\\<Prod>i\\<in>insert i I. z i) - (\\<Prod>i\\<in>insert i I. w i)) =\n    norm ((\\<Prod>i\\<in>I. z i) * (z i - w i) + ((\\<Prod>i\\<in>I. z i) - (\\<Prod>i\\<in>I. w i)) * w i)\"\n    (is \"_ = norm (?t1 + ?t2)\")\n    by (auto simp: field_simps)\n  also have \"\\<dots> \\<le> norm ?t1 + norm ?t2\"\n    by (rule norm_triangle_ineq)\n  also have \"norm ?t1 \\<le> norm (\\<Prod>i\\<in>I. z i) * norm (z i - w i)\"\n    by (rule norm_mult_ineq)\n  also have \"\\<dots> \\<le> (\\<Prod>i\\<in>I. norm (z i)) * norm(z i - w i)\"\n    by (rule mult_right_mono) (auto intro: norm_prod_le)\n  also have \"(\\<Prod>i\\<in>I. norm (z i)) \\<le> (\\<Prod>i\\<in>I. 1)\"\n    by (intro prod_mono) (auto intro!: insert)\n  also have \"norm ?t2 \\<le> norm ((\\<Prod>i\\<in>I. z i) - (\\<Prod>i\\<in>I. w i)) * norm (w i)\"\n    by (rule norm_mult_ineq)\n  also have \"norm (w i) \\<le> 1\"\n    by (auto intro: insert)\n  also have \"norm ((\\<Prod>i\\<in>I. z i) - (\\<Prod>i\\<in>I. w i)) \\<le> (\\<Sum>i\\<in>I. norm (z i - w i))\"\n    using insert by auto\n  finally show ?case\n    by (auto simp: ac_simps mult_right_mono mult_left_mono)\nnext\n  case infinite\n  then show ?case by simp\nqed\n\nlemma norm_power_diff:\n  fixes z w :: \"'a::{real_normed_algebra_1, comm_monoid_mult}\"\n  assumes \"norm z \\<le> 1\" \"norm w \\<le> 1\"\n  shows \"norm (z^m - w^m) \\<le> m * norm (z - w)\"\nproof -\n  have \"norm (z^m - w^m) = norm ((\\<Prod> i < m. z) - (\\<Prod> i < m. w))\"\n    by simp\n  also have \"\\<dots> \\<le> (\\<Sum>i<m. norm (z - w))\"\n    by (intro norm_prod_diff) (auto simp: assms)\n  also have \"\\<dots> = m * norm (z - w)\"\n    by simp\n  finally show ?thesis .\nqed\n\nsubsection \\<open>Metric spaces\\<close>\n\nclass metric_space = uniformity_dist + open_uniformity +\n  assumes dist_eq_0_iff [simp]: \"dist x y = 0 \\<longleftrightarrow> x = y\"\n    and dist_triangle2: \"dist x y \\<le> dist x z + dist y z\"\nbegin\n\nlemma dist_self [simp]: \"dist x x = 0\"\n  by simp\n\nlemma zero_le_dist [simp]: \"0 \\<le> dist x y\"\n  using dist_triangle2 [of x x y] by simp\n\nlemma zero_less_dist_iff: \"0 < dist x y \\<longleftrightarrow> x \\<noteq> y\"\n  by (simp add: less_le)\n\nlemma dist_not_less_zero [simp]: \"\\<not> dist x y < 0\"\n  by (simp add: not_less)\n\nlemma dist_le_zero_iff [simp]: \"dist x y \\<le> 0 \\<longleftrightarrow> x = y\"\n  by (simp add: le_less)\n\nlemma dist_commute: \"dist x y = dist y x\"\nproof (rule order_antisym)\n  show \"dist x y \\<le> dist y x\"\n    using dist_triangle2 [of x y x] by simp\n  show \"dist y x \\<le> dist x y\"\n    using dist_triangle2 [of y x y] by simp\nqed\n\nlemma dist_commute_lessI: \"dist y x < e \\<Longrightarrow> dist x y < e\"\n  by (simp add: dist_commute)\n\nlemma dist_triangle: \"dist x z \\<le> dist x y + dist y z\"\n  using dist_triangle2 [of x z y] by (simp add: dist_commute)\n\nlemma dist_triangle3: \"dist x y \\<le> dist a x + dist a y\"\n  using dist_triangle2 [of x y a] by (simp add: dist_commute)\n\nlemma abs_dist_diff_le: \"\\<bar>dist a b - dist b c\\<bar> \\<le> dist a c\"\n  using dist_triangle3[of b c a] dist_triangle2[of a b c] by simp\n\nlemma dist_pos_lt: \"x \\<noteq> y \\<Longrightarrow> 0 < dist x y\"\n  by (simp add: zero_less_dist_iff)\n\nlemma dist_nz: \"x \\<noteq> y \\<longleftrightarrow> 0 < dist x y\"\n  by (simp add: zero_less_dist_iff)\n\ndeclare dist_nz [symmetric, simp]\n\nlemma dist_triangle_le: \"dist x z + dist y z \\<le> e \\<Longrightarrow> dist x y \\<le> e\"\n  by (rule order_trans [OF dist_triangle2])\n\nlemma dist_triangle_lt: \"dist x z + dist y z < e \\<Longrightarrow> dist x y < e\"\n  by (rule le_less_trans [OF dist_triangle2])\n\nlemma dist_triangle_less_add: \"dist x1 y < e1 \\<Longrightarrow> dist x2 y < e2 \\<Longrightarrow> dist x1 x2 < e1 + e2\"\n  by (rule dist_triangle_lt [where z=y]) simp\n\nlemma dist_triangle_half_l: \"dist x1 y < e / 2 \\<Longrightarrow> dist x2 y < e / 2 \\<Longrightarrow> dist x1 x2 < e\"\n  by (rule dist_triangle_lt [where z=y]) simp\n\nlemma dist_triangle_half_r: \"dist y x1 < e / 2 \\<Longrightarrow> dist y x2 < e / 2 \\<Longrightarrow> dist x1 x2 < e\"\n  by (rule dist_triangle_half_l) (simp_all add: dist_commute)\n\nlemma dist_triangle_third:\n  assumes \"dist x1 x2 < e/3\" \"dist x2 x3 < e/3\" \"dist x3 x4 < e/3\"\n  shows \"dist x1 x4 < e\"\nproof -\n  have \"dist x1 x3 < e/3 + e/3\"\n    by (metis assms(1) assms(2) dist_commute dist_triangle_less_add)\n  then have \"dist x1 x4 < (e/3 + e/3) + e/3\"\n    by (metis assms(3) dist_commute dist_triangle_less_add)\n  then show ?thesis\n    by simp\nqed\n  \nsubclass uniform_space\nproof\n  fix E x\n  assume \"eventually E uniformity\"\n  then obtain e where E: \"0 < e\" \"\\<And>x y. dist x y < e \\<Longrightarrow> E (x, y)\"\n    by (auto simp: eventually_uniformity_metric)\n  then show \"E (x, x)\" \"\\<forall>\\<^sub>F (x, y) in uniformity. E (y, x)\"\n    by (auto simp: eventually_uniformity_metric dist_commute)\n  show \"\\<exists>D. eventually D uniformity \\<and> (\\<forall>x y z. D (x, y) \\<longrightarrow> D (y, z) \\<longrightarrow> E (x, z))\"\n    using E dist_triangle_half_l[where e=e]\n    unfolding eventually_uniformity_metric\n    by (intro exI[of _ \"\\<lambda>(x, y). dist x y < e / 2\"] exI[of _ \"e/2\"] conjI)\n      (auto simp: dist_commute)\nqed\n\nlemma open_dist: \"open S \\<longleftrightarrow> (\\<forall>x\\<in>S. \\<exists>e>0. \\<forall>y. dist y x < e \\<longrightarrow> y \\<in> S)\"\n  by (simp add: dist_commute open_uniformity eventually_uniformity_metric)\n\nlemma open_ball: \"open {y. dist x y < d}\"\n  unfolding open_dist\nproof (intro ballI)\n  fix y\n  assume *: \"y \\<in> {y. dist x y < d}\"\n  then show \"\\<exists>e>0. \\<forall>z. dist z y < e \\<longrightarrow> z \\<in> {y. dist x y < d}\"\n    by (auto intro!: exI[of _ \"d - dist x y\"] simp: field_simps dist_triangle_lt)\nqed\n\nsubclass first_countable_topology\nproof\n  fix x\n  show \"\\<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))\"\n  proof (safe intro!: exI[of _ \"\\<lambda>n. {y. dist x y < inverse (Suc n)}\"])\n    fix S\n    assume \"open S\" \"x \\<in> S\"\n    then obtain e where e: \"0 < e\" and \"{y. dist x y < e} \\<subseteq> S\"\n      by (auto simp: open_dist subset_eq dist_commute)\n    moreover\n    from e obtain i where \"inverse (Suc i) < e\"\n      by (auto dest!: reals_Archimedean)\n    then have \"{y. dist x y < inverse (Suc i)} \\<subseteq> {y. dist x y < e}\"\n      by auto\n    ultimately show \"\\<exists>i. {y. dist x y < inverse (Suc i)} \\<subseteq> S\"\n      by blast\n  qed (auto intro: open_ball)\nqed\n\nend\n\ninstance metric_space \\<subseteq> t2_space\nproof\n  fix x y :: \"'a::metric_space\"\n  assume xy: \"x \\<noteq> y\"\n  let ?U = \"{y'. dist x y' < dist x y / 2}\"\n  let ?V = \"{x'. dist y x' < dist x y / 2}\"\n  have *: \"d x z \\<le> d x y + d y z \\<Longrightarrow> d y z = d z y \\<Longrightarrow> \\<not> (d x y * 2 < d x z \\<and> d z y * 2 < d x z)\"\n    for d :: \"'a \\<Rightarrow> 'a \\<Rightarrow> real\" and x y z :: 'a\n    by arith\n  have \"open ?U \\<and> open ?V \\<and> x \\<in> ?U \\<and> y \\<in> ?V \\<and> ?U \\<inter> ?V = {}\"\n    using dist_pos_lt[OF xy] *[of dist, OF dist_triangle dist_commute]\n    using open_ball[of _ \"dist x y / 2\"] by auto\n  then show \"\\<exists>U V. open U \\<and> open V \\<and> x \\<in> U \\<and> y \\<in> V \\<and> U \\<inter> V = {}\"\n    by blast\nqed\n\ntext \\<open>Every normed vector space is a metric space.\\<close>\ninstance real_normed_vector < metric_space\nproof\n  fix x y z :: 'a\n  show \"dist x y = 0 \\<longleftrightarrow> x = y\"\n    by (simp add: dist_norm)\n  show \"dist x y \\<le> dist x z + dist y z\"\n    using norm_triangle_ineq4 [of \"x - z\" \"y - z\"] by (simp add: dist_norm)\nqed\n\n\nsubsection \\<open>Class instances for real numbers\\<close>\n\ninstantiation real :: real_normed_field\nbegin\n\ndefinition dist_real_def: \"dist x y = \\<bar>x - y\\<bar>\"\n\ndefinition uniformity_real_def [code del]:\n  \"(uniformity :: (real \\<times> real) filter) = (INF e\\<in>{0 <..}. principal {(x, y). dist x y < e})\"\n\ndefinition open_real_def [code del]:\n  \"open (U :: real set) \\<longleftrightarrow> (\\<forall>x\\<in>U. eventually (\\<lambda>(x', y). x' = x \\<longrightarrow> y \\<in> U) uniformity)\"\n\ndefinition real_norm_def [simp]: \"norm r = \\<bar>r\\<bar>\"\n\ninstance\n  by intro_classes (auto simp: abs_mult open_real_def dist_real_def sgn_real_def uniformity_real_def)\n\nend\n\ndeclare uniformity_Abort[where 'a=real, code]\n\nlemma dist_of_real [simp]: \"dist (of_real x :: 'a) (of_real y) = dist x y\"\n  for a :: \"'a::real_normed_div_algebra\"\n  by (metis dist_norm norm_of_real of_real_diff real_norm_def)\n\ndeclare [[code abort: \"open :: real set \\<Rightarrow> bool\"]]\n\ninstance real :: linorder_topology\nproof\n  show \"(open :: real set \\<Rightarrow> bool) = generate_topology (range lessThan \\<union> range greaterThan)\"\n  proof (rule ext, safe)\n    fix S :: \"real set\"\n    assume \"open S\"\n    then obtain f where \"\\<forall>x\\<in>S. 0 < f x \\<and> (\\<forall>y. dist y x < f x \\<longrightarrow> y \\<in> S)\"\n      unfolding open_dist bchoice_iff ..\n    then have *: \"(\\<Union>x\\<in>S. {x - f x <..} \\<inter> {..< x + f x}) = S\" (is \"?S = S\")\n      by (fastforce simp: dist_real_def)\n    moreover have \"generate_topology (range lessThan \\<union> range greaterThan) ?S\"\n      by (force intro: generate_topology.Basis generate_topology_Union generate_topology.Int)\n    ultimately show \"generate_topology (range lessThan \\<union> range greaterThan) S\"\n      by simp\n  next\n    fix S :: \"real set\"\n    assume \"generate_topology (range lessThan \\<union> range greaterThan) S\"\n    moreover have \"\\<And>a::real. open {..<a}\"\n      unfolding open_dist dist_real_def\n    proof clarify\n      fix x a :: real\n      assume \"x < a\"\n      then have \"0 < a - x \\<and> (\\<forall>y. \\<bar>y - x\\<bar> < a - x \\<longrightarrow> y \\<in> {..<a})\" by auto\n      then show \"\\<exists>e>0. \\<forall>y. \\<bar>y - x\\<bar> < e \\<longrightarrow> y \\<in> {..<a}\" ..\n    qed\n    moreover have \"\\<And>a::real. open {a <..}\"\n      unfolding open_dist dist_real_def\n    proof clarify\n      fix x a :: real\n      assume \"a < x\"\n      then have \"0 < x - a \\<and> (\\<forall>y. \\<bar>y - x\\<bar> < x - a \\<longrightarrow> y \\<in> {a<..})\" by auto\n      then show \"\\<exists>e>0. \\<forall>y. \\<bar>y - x\\<bar> < e \\<longrightarrow> y \\<in> {a<..}\" ..\n    qed\n    ultimately show \"open S\"\n      by induct auto\n  qed\nqed\n\ninstance real :: linear_continuum_topology ..\n\nlemmas open_real_greaterThan = open_greaterThan[where 'a=real]\nlemmas open_real_lessThan = open_lessThan[where 'a=real]\nlemmas open_real_greaterThanLessThan = open_greaterThanLessThan[where 'a=real]\nlemmas closed_real_atMost = closed_atMost[where 'a=real]\nlemmas closed_real_atLeast = closed_atLeast[where 'a=real]\nlemmas closed_real_atLeastAtMost = closed_atLeastAtMost[where 'a=real]\n\ninstance real :: ordered_real_vector\n  by standard (auto intro: mult_left_mono mult_right_mono)\n\n\nsubsection \\<open>Extra type constraints\\<close>\n\ntext \\<open>Only allow \\<^term>\\<open>open\\<close> in class \\<open>topological_space\\<close>.\\<close>\nsetup \\<open>Sign.add_const_constraint\n  (\\<^const_name>\\<open>open\\<close>, SOME \\<^typ>\\<open>'a::topological_space set \\<Rightarrow> bool\\<close>)\\<close>\n\ntext \\<open>Only allow \\<^term>\\<open>uniformity\\<close> in class \\<open>uniform_space\\<close>.\\<close>\nsetup \\<open>Sign.add_const_constraint\n  (\\<^const_name>\\<open>uniformity\\<close>, SOME \\<^typ>\\<open>('a::uniformity \\<times> 'a) filter\\<close>)\\<close>\n\ntext \\<open>Only allow \\<^term>\\<open>dist\\<close> in class \\<open>metric_space\\<close>.\\<close>\nsetup \\<open>Sign.add_const_constraint\n  (\\<^const_name>\\<open>dist\\<close>, SOME \\<^typ>\\<open>'a::metric_space \\<Rightarrow> 'a \\<Rightarrow> real\\<close>)\\<close>\n\ntext \\<open>Only allow \\<^term>\\<open>norm\\<close> in class \\<open>real_normed_vector\\<close>.\\<close>\nsetup \\<open>Sign.add_const_constraint\n  (\\<^const_name>\\<open>norm\\<close>, SOME \\<^typ>\\<open>'a::real_normed_vector \\<Rightarrow> real\\<close>)\\<close>\n\n\nsubsection \\<open>Sign function\\<close>\n\nlemma norm_sgn: \"norm (sgn x) = (if x = 0 then 0 else 1)\"\n  for x :: \"'a::real_normed_vector\"\n  by (simp add: sgn_div_norm)\n\nlemma sgn_zero [simp]: \"sgn (0::'a::real_normed_vector) = 0\"\n  by (simp add: sgn_div_norm)\n\nlemma sgn_zero_iff: \"sgn x = 0 \\<longleftrightarrow> x = 0\"\n  for x :: \"'a::real_normed_vector\"\n  by (simp add: sgn_div_norm)\n\nlemma sgn_minus: \"sgn (- x) = - sgn x\"\n  for x :: \"'a::real_normed_vector\"\n  by (simp add: sgn_div_norm)\n\nlemma sgn_scaleR: \"sgn (scaleR r x) = scaleR (sgn r) (sgn x)\"\n  for x :: \"'a::real_normed_vector\"\n  by (simp add: sgn_div_norm ac_simps)\n\nlemma sgn_one [simp]: \"sgn (1::'a::real_normed_algebra_1) = 1\"\n  by (simp add: sgn_div_norm)\n\nlemma sgn_of_real: \"sgn (of_real r :: 'a::real_normed_algebra_1) = of_real (sgn r)\"\n  unfolding of_real_def by (simp only: sgn_scaleR sgn_one)\n\nlemma sgn_mult: \"sgn (x * y) = sgn x * sgn y\"\n  for x y :: \"'a::real_normed_div_algebra\"\n  by (simp add: sgn_div_norm norm_mult)\n\nhide_fact (open) sgn_mult\n\nlemma real_sgn_eq: \"sgn x = x / \\<bar>x\\<bar>\"\n  for x :: real\n  by (simp add: sgn_div_norm divide_inverse)\n\nlemma zero_le_sgn_iff [simp]: \"0 \\<le> sgn x \\<longleftrightarrow> 0 \\<le> x\"\n  for x :: real\n  by (cases \"0::real\" x rule: linorder_cases) simp_all\n\nlemma sgn_le_0_iff [simp]: \"sgn x \\<le> 0 \\<longleftrightarrow> x \\<le> 0\"\n  for x :: real\n  by (cases \"0::real\" x rule: linorder_cases) simp_all\n\nlemma norm_conv_dist: \"norm x = dist x 0\"\n  unfolding dist_norm by simp\n\ndeclare norm_conv_dist [symmetric, simp]\n\nlemma dist_0_norm [simp]: \"dist 0 x = norm x\"\n  for x :: \"'a::real_normed_vector\"\n  by (simp add: dist_norm)\n\nlemma dist_diff [simp]: \"dist a (a - b) = norm b\"  \"dist (a - b) a = norm b\"\n  by (simp_all add: dist_norm)\n\nlemma dist_of_int: \"dist (of_int m) (of_int n :: 'a :: real_normed_algebra_1) = of_int \\<bar>m - n\\<bar>\"\nproof -\n  have \"dist (of_int m) (of_int n :: 'a) = dist (of_int m :: 'a) (of_int m - (of_int (m - n)))\"\n    by simp\n  also have \"\\<dots> = of_int \\<bar>m - n\\<bar>\" by (subst dist_diff, subst norm_of_int) simp\n  finally show ?thesis .\nqed\n\nlemma dist_of_nat:\n  \"dist (of_nat m) (of_nat n :: 'a :: real_normed_algebra_1) = of_int \\<bar>int m - int n\\<bar>\"\n  by (subst (1 2) of_int_of_nat_eq [symmetric]) (rule dist_of_int)\n\n\nsubsection \\<open>Bounded Linear and Bilinear Operators\\<close>\n\nlemma linearI: \"linear f\"\n  if \"\\<And>b1 b2. f (b1 + b2) = f b1 + f b2\"\n    \"\\<And>r b. f (r *\\<^sub>R b) = r *\\<^sub>R f b\"\n  using that\n  by unfold_locales (auto simp: algebra_simps)\n\nlemma linear_iff:\n  \"linear f \\<longleftrightarrow> (\\<forall>x y. f (x + y) = f x + f y) \\<and> (\\<forall>c x. f (c *\\<^sub>R x) = c *\\<^sub>R f x)\"\n  (is \"linear f \\<longleftrightarrow> ?rhs\")\nproof\n  assume \"linear f\"\n  then interpret f: linear f .\n  show \"?rhs\" by (simp add: f.add f.scale)\nnext\n  assume \"?rhs\"\n  then show \"linear f\" by (intro linearI) auto\nqed\n\nlemmas linear_scaleR_left = linear_scale_left\nlemmas linear_imp_scaleR = linear_imp_scale\n\ncorollary real_linearD:\n  fixes f :: \"real \\<Rightarrow> real\"\n  assumes \"linear f\" obtains c where \"f = (*) c\"\n  by (rule linear_imp_scaleR [OF assms]) (force simp: scaleR_conv_of_real)\n\nlemma linear_times_of_real: \"linear (\\<lambda>x. a * of_real x)\"\n  by (auto intro!: linearI simp: distrib_left)\n    (metis mult_scaleR_right scaleR_conv_of_real)\n\nlocale bounded_linear = linear f for f :: \"'a::real_normed_vector \\<Rightarrow> 'b::real_normed_vector\" +\n  assumes bounded: \"\\<exists>K. \\<forall>x. norm (f x) \\<le> norm x * K\"\nbegin\n\nlemma pos_bounded: \"\\<exists>K>0. \\<forall>x. norm (f x) \\<le> norm x * K\"\nproof -\n  obtain K where K: \"\\<And>x. norm (f x) \\<le> norm x * K\"\n    using bounded by blast\n  show ?thesis\n  proof (intro exI impI conjI allI)\n    show \"0 < max 1 K\"\n      by (rule order_less_le_trans [OF zero_less_one max.cobounded1])\n  next\n    fix x\n    have \"norm (f x) \\<le> norm x * K\" using K .\n    also have \"\\<dots> \\<le> norm x * max 1 K\"\n      by (rule mult_left_mono [OF max.cobounded2 norm_ge_zero])\n    finally show \"norm (f x) \\<le> norm x * max 1 K\" .\n  qed\nqed\n\nlemma nonneg_bounded: \"\\<exists>K\\<ge>0. \\<forall>x. norm (f x) \\<le> norm x * K\"\n  using pos_bounded by (auto intro: order_less_imp_le)\n\nlemma linear: \"linear f\"\n  by (fact local.linear_axioms)\n\nend\n\nlemma bounded_linear_intro:\n  assumes \"\\<And>x y. f (x + y) = f x + f y\"\n    and \"\\<And>r x. f (scaleR r x) = scaleR r (f x)\"\n    and \"\\<And>x. norm (f x) \\<le> norm x * K\"\n  shows \"bounded_linear f\"\n  by standard (blast intro: assms)+\n\nlocale bounded_bilinear =\n  fixes prod :: \"'a::real_normed_vector \\<Rightarrow> 'b::real_normed_vector \\<Rightarrow> 'c::real_normed_vector\"\n    (infixl \"**\" 70)\n  assumes add_left: \"prod (a + a') b = prod a b + prod a' b\"\n    and add_right: \"prod a (b + b') = prod a b + prod a b'\"\n    and scaleR_left: \"prod (scaleR r a) b = scaleR r (prod a b)\"\n    and scaleR_right: \"prod a (scaleR r b) = scaleR r (prod a b)\"\n    and bounded: \"\\<exists>K. \\<forall>a b. norm (prod a b) \\<le> norm a * norm b * K\"\nbegin\n\nlemma pos_bounded: \"\\<exists>K>0. \\<forall>a b. norm (a ** b) \\<le> norm a * norm b * K\"\nproof -\n  obtain K where \"\\<And>a b. norm (a ** b) \\<le> norm a * norm b * K\"\n    using bounded by blast\n  then have \"norm (a ** b) \\<le> norm a * norm b * (max 1 K)\" for a b\n    by (rule order.trans) (simp add: mult_left_mono)\n  then show ?thesis\n    by force\nqed\n\nlemma nonneg_bounded: \"\\<exists>K\\<ge>0. \\<forall>a b. norm (a ** b) \\<le> norm a * norm b * K\"\n  using pos_bounded by (auto intro: order_less_imp_le)\n\nlemma additive_right: \"additive (\\<lambda>b. prod a b)\"\n  by (rule additive.intro, rule add_right)\n\nlemma additive_left: \"additive (\\<lambda>a. prod a b)\"\n  by (rule additive.intro, rule add_left)\n\nlemma zero_left: \"prod 0 b = 0\"\n  by (rule additive.zero [OF additive_left])\n\nlemma zero_right: \"prod a 0 = 0\"\n  by (rule additive.zero [OF additive_right])\n\nlemma minus_left: \"prod (- a) b = - prod a b\"\n  by (rule additive.minus [OF additive_left])\n\nlemma minus_right: \"prod a (- b) = - prod a b\"\n  by (rule additive.minus [OF additive_right])\n\nlemma diff_left: \"prod (a - a') b = prod a b - prod a' b\"\n  by (rule additive.diff [OF additive_left])\n\nlemma diff_right: \"prod a (b - b') = prod a b - prod a b'\"\n  by (rule additive.diff [OF additive_right])\n\nlemma sum_left: \"prod (sum g S) x = sum ((\\<lambda>i. prod (g i) x)) S\"\n  by (rule additive.sum [OF additive_left])\n\nlemma sum_right: \"prod x (sum g S) = sum ((\\<lambda>i. (prod x (g i)))) S\"\n  by (rule additive.sum [OF additive_right])\n\n\nlemma bounded_linear_left: \"bounded_linear (\\<lambda>a. a ** b)\"\nproof -\n  obtain K where \"\\<And>a b. norm (a ** b) \\<le> norm a * norm b * K\"\n    using pos_bounded by blast\n  then show ?thesis\n    by (rule_tac K=\"norm b * K\" in bounded_linear_intro) (auto simp: algebra_simps scaleR_left add_left)\nqed\n\nlemma bounded_linear_right: \"bounded_linear (\\<lambda>b. a ** b)\"\nproof -\n  obtain K where \"\\<And>a b. norm (a ** b) \\<le> norm a * norm b * K\"\n    using pos_bounded by blast\n  then show ?thesis\n    by (rule_tac K=\"norm a * K\" in bounded_linear_intro) (auto simp: algebra_simps scaleR_right add_right)\nqed\n\nlemma prod_diff_prod: \"(x ** y - a ** b) = (x - a) ** (y - b) + (x - a) ** b + a ** (y - b)\"\n  by (simp add: diff_left diff_right)\n\nlemma flip: \"bounded_bilinear (\\<lambda>x y. y ** x)\"\nproof\n  show \"\\<exists>K. \\<forall>a b. norm (b ** a) \\<le> norm a * norm b * K\"\n    by (metis bounded mult.commute)\nqed (simp_all add: add_right add_left scaleR_right scaleR_left)\n\nlemma comp1:\n  assumes \"bounded_linear g\"\n  shows \"bounded_bilinear (\\<lambda>x. (**) (g x))\"\nproof unfold_locales\n  interpret g: bounded_linear g by fact\n  show \"\\<And>a a' b. g (a + a') ** b = g a ** b + g a' ** b\"\n    \"\\<And>a b b'. g a ** (b + b') = g a ** b + g a ** b'\"\n    \"\\<And>r a b. g (r *\\<^sub>R a) ** b = r *\\<^sub>R (g a ** b)\"\n    \"\\<And>a r b. g a ** (r *\\<^sub>R b) = r *\\<^sub>R (g a ** b)\"\n    by (auto simp: g.add add_left add_right g.scaleR scaleR_left scaleR_right)\n  from g.nonneg_bounded nonneg_bounded obtain K L\n    where nn: \"0 \\<le> K\" \"0 \\<le> L\"\n      and K: \"\\<And>x. norm (g x) \\<le> norm x * K\"\n      and L: \"\\<And>a b. norm (a ** b) \\<le> norm a * norm b * L\"\n    by auto\n  have \"norm (g a ** b) \\<le> norm a * K * norm b * L\" for a b\n    by (auto intro!:  order_trans[OF K] order_trans[OF L] mult_mono simp: nn)\n  then show \"\\<exists>K. \\<forall>a b. norm (g a ** b) \\<le> norm a * norm b * K\"\n    by (auto intro!: exI[where x=\"K * L\"] simp: ac_simps)\nqed\n\nlemma comp: \"bounded_linear f \\<Longrightarrow> bounded_linear g \\<Longrightarrow> bounded_bilinear (\\<lambda>x y. f x ** g y)\"\n  by (rule bounded_bilinear.flip[OF bounded_bilinear.comp1[OF bounded_bilinear.flip[OF comp1]]])\n\nend\n\nlemma bounded_linear_ident[simp]: \"bounded_linear (\\<lambda>x. x)\"\n  by standard (auto intro!: exI[of _ 1])\n\nlemma bounded_linear_zero[simp]: \"bounded_linear (\\<lambda>x. 0)\"\n  by standard (auto intro!: exI[of _ 1])\n\nlemma bounded_linear_add:\n  assumes \"bounded_linear f\"\n    and \"bounded_linear g\"\n  shows \"bounded_linear (\\<lambda>x. f x + g x)\"\nproof -\n  interpret f: bounded_linear f by fact\n  interpret g: bounded_linear g by fact\n  show ?thesis\n  proof\n    from f.bounded obtain Kf where Kf: \"norm (f x) \\<le> norm x * Kf\" for x\n      by blast\n    from g.bounded obtain Kg where Kg: \"norm (g x) \\<le> norm x * Kg\" for x\n      by blast\n    show \"\\<exists>K. \\<forall>x. norm (f x + g x) \\<le> norm x * K\"\n      using add_mono[OF Kf Kg]\n      by (intro exI[of _ \"Kf + Kg\"]) (auto simp: field_simps intro: norm_triangle_ineq order_trans)\n  qed (simp_all add: f.add g.add f.scaleR g.scaleR scaleR_right_distrib)\nqed\n\nlemma bounded_linear_minus:\n  assumes \"bounded_linear f\"\n  shows \"bounded_linear (\\<lambda>x. - f x)\"\nproof -\n  interpret f: bounded_linear f by fact\n  show ?thesis\n    by unfold_locales (simp_all add: f.add f.scaleR f.bounded)\nqed\n\nlemma bounded_linear_sub: \"bounded_linear f \\<Longrightarrow> bounded_linear g \\<Longrightarrow> bounded_linear (\\<lambda>x. f x - g x)\"\n  using bounded_linear_add[of f \"\\<lambda>x. - g x\"] bounded_linear_minus[of g]\n  by (auto simp: algebra_simps)\n\nlemma bounded_linear_sum:\n  fixes f :: \"'i \\<Rightarrow> 'a::real_normed_vector \\<Rightarrow> 'b::real_normed_vector\"\n  shows \"(\\<And>i. i \\<in> I \\<Longrightarrow> bounded_linear (f i)) \\<Longrightarrow> bounded_linear (\\<lambda>x. \\<Sum>i\\<in>I. f i x)\"\n  by (induct I rule: infinite_finite_induct) (auto intro!: bounded_linear_add)\n\nlemma bounded_linear_compose:\n  assumes \"bounded_linear f\"\n    and \"bounded_linear g\"\n  shows \"bounded_linear (\\<lambda>x. f (g x))\"\nproof -\n  interpret f: bounded_linear f by fact\n  interpret g: bounded_linear g by fact\n  show ?thesis\n  proof unfold_locales\n    show \"f (g (x + y)) = f (g x) + f (g y)\" for x y\n      by (simp only: f.add g.add)\n    show \"f (g (scaleR r x)) = scaleR r (f (g x))\" for r x\n      by (simp only: f.scaleR g.scaleR)\n    from f.pos_bounded obtain Kf where f: \"\\<And>x. norm (f x) \\<le> norm x * Kf\" and Kf: \"0 < Kf\"\n      by blast\n    from g.pos_bounded obtain Kg where g: \"\\<And>x. norm (g x) \\<le> norm x * Kg\"\n      by blast\n    show \"\\<exists>K. \\<forall>x. norm (f (g x)) \\<le> norm x * K\"\n    proof (intro exI allI)\n      fix x\n      have \"norm (f (g x)) \\<le> norm (g x) * Kf\"\n        using f .\n      also have \"\\<dots> \\<le> (norm x * Kg) * Kf\"\n        using g Kf [THEN order_less_imp_le] by (rule mult_right_mono)\n      also have \"(norm x * Kg) * Kf = norm x * (Kg * Kf)\"\n        by (rule mult.assoc)\n      finally show \"norm (f (g x)) \\<le> norm x * (Kg * Kf)\" .\n    qed\n  qed\nqed\n\nlemma bounded_bilinear_mult: \"bounded_bilinear ((*) :: 'a \\<Rightarrow> 'a \\<Rightarrow> 'a::real_normed_algebra)\"\nproof (rule bounded_bilinear.intro)\n  show \"\\<exists>K. \\<forall>a b::'a. norm (a * b) \\<le> norm a * norm b * K\"\n    by (rule_tac x=1 in exI) (simp add: norm_mult_ineq)\nqed (auto simp: algebra_simps)\n\nlemma bounded_linear_mult_left: \"bounded_linear (\\<lambda>x::'a::real_normed_algebra. x * y)\"\n  using bounded_bilinear_mult\n  by (rule bounded_bilinear.bounded_linear_left)\n\nlemma bounded_linear_mult_right: \"bounded_linear (\\<lambda>y::'a::real_normed_algebra. x * y)\"\n  using bounded_bilinear_mult\n  by (rule bounded_bilinear.bounded_linear_right)\n\nlemmas bounded_linear_mult_const =\n  bounded_linear_mult_left [THEN bounded_linear_compose]\n\nlemmas bounded_linear_const_mult =\n  bounded_linear_mult_right [THEN bounded_linear_compose]\n\nlemma bounded_linear_divide: \"bounded_linear (\\<lambda>x. x / y)\"\n  for y :: \"'a::real_normed_field\"\n  unfolding divide_inverse by (rule bounded_linear_mult_left)\n\nlemma bounded_bilinear_scaleR: \"bounded_bilinear scaleR\"\nproof (rule bounded_bilinear.intro)\n  show \"\\<exists>K. \\<forall>a b. norm (a *\\<^sub>R b) \\<le> norm a * norm b * K\"\n    using less_eq_real_def by auto\nqed (auto simp: algebra_simps)\n\nlemma bounded_linear_scaleR_left: \"bounded_linear (\\<lambda>r. scaleR r x)\"\n  using bounded_bilinear_scaleR\n  by (rule bounded_bilinear.bounded_linear_left)\n\nlemma bounded_linear_scaleR_right: \"bounded_linear (\\<lambda>x. scaleR r x)\"\n  using bounded_bilinear_scaleR\n  by (rule bounded_bilinear.bounded_linear_right)\n\nlemmas bounded_linear_scaleR_const =\n  bounded_linear_scaleR_left[THEN bounded_linear_compose]\n\nlemmas bounded_linear_const_scaleR =\n  bounded_linear_scaleR_right[THEN bounded_linear_compose]\n\nlemma bounded_linear_of_real: \"bounded_linear (\\<lambda>r. of_real r)\"\n  unfolding of_real_def by (rule bounded_linear_scaleR_left)\n\nlemma real_bounded_linear: \"bounded_linear f \\<longleftrightarrow> (\\<exists>c::real. f = (\\<lambda>x. x * c))\"\n  for f :: \"real \\<Rightarrow> real\"\nproof -\n  {\n    fix x\n    assume \"bounded_linear f\"\n    then interpret bounded_linear f .\n    from scaleR[of x 1] have \"f x = x * f 1\"\n      by simp\n  }\n  then show ?thesis\n    by (auto intro: exI[of _ \"f 1\"] bounded_linear_mult_left)\nqed\n\ninstance real_normed_algebra_1 \\<subseteq> perfect_space\nproof\n  fix x::'a\n  have \"\\<And>e. 0 < e \\<Longrightarrow> \\<exists>y. norm (y - x) < e \\<and> y \\<noteq> x\"\n    by (rule_tac x = \"x + of_real (e/2)\" in exI) auto\n  then show \"\\<not> open {x}\" \n    by (clarsimp simp: open_dist dist_norm)\nqed\n\n\nsubsection \\<open>Filters and Limits on Metric Space\\<close>\n\nlemma (in metric_space) nhds_metric: \"nhds x = (INF e\\<in>{0 <..}. principal {y. dist y x < e})\"\n  unfolding nhds_def\nproof (safe intro!: INF_eq)\n  fix S\n  assume \"open S\" \"x \\<in> S\"\n  then obtain e where \"{y. dist y x < e} \\<subseteq> S\" \"0 < e\"\n    by (auto simp: open_dist subset_eq)\n  then show \"\\<exists>e\\<in>{0<..}. principal {y. dist y x < e} \\<le> principal S\"\n    by auto\nqed (auto intro!: exI[of _ \"{y. dist x y < e}\" for e] open_ball simp: dist_commute)\n\n(* Contributed by Dominique Unruh *)\nlemma tendsto_iff_uniformity:\n    \\<comment> \\<open>More general analogus of \\<open>tendsto_iff\\<close> below. Applies to all uniform spaces, not just metric ones.\\<close>\n  fixes l :: \\<open>'b :: uniform_space\\<close>\n  shows \\<open>(f \\<longlongrightarrow> l) F \\<longleftrightarrow> (\\<forall>E. eventually E uniformity \\<longrightarrow> (\\<forall>\\<^sub>F x in F. E (f x, l)))\\<close>\nproof (intro iffI allI impI)\n  fix E :: \\<open>('b \\<times> 'b) \\<Rightarrow> bool\\<close>\n  assume \\<open>(f \\<longlongrightarrow> l) F\\<close> and \\<open>eventually E uniformity\\<close>\n  from \\<open>eventually E uniformity\\<close>\n  have \\<open>eventually (\\<lambda>(x, y). E (y, x)) uniformity\\<close>\n    by (simp add: uniformity_sym)\n  then have \\<open>\\<forall>\\<^sub>F (y, x) in uniformity. y = l \\<longrightarrow> E (x, y)\\<close>\n    using eventually_mono by fastforce\n  with \\<open>(f \\<longlongrightarrow> l) F\\<close> have \\<open>eventually (\\<lambda>x. E (x ,l)) (filtermap f F)\\<close>\n    by (simp add: filterlim_def le_filter_def eventually_nhds_uniformity)\n  then show \\<open>\\<forall>\\<^sub>F x in F. E (f x, l)\\<close>\n    by (simp add: eventually_filtermap)\nnext\n  assume assm: \\<open>\\<forall>E. eventually E uniformity \\<longrightarrow> (\\<forall>\\<^sub>F x in F. E (f x, l))\\<close>\n  have \\<open>eventually P (filtermap f F)\\<close> if \\<open>\\<forall>\\<^sub>F (x, y) in uniformity. x = l \\<longrightarrow> P y\\<close> for P\n  proof -\n    from that have \\<open>\\<forall>\\<^sub>F (y, x) in uniformity. x = l \\<longrightarrow> P y\\<close> \n      using uniformity_sym[where E=\\<open>\\<lambda>(x,y). x=l \\<longrightarrow> P y\\<close>] by auto\n    with assm have \\<open>\\<forall>\\<^sub>F x in F. P (f x)\\<close>\n      by auto\n    then show ?thesis\n      by (auto simp: eventually_filtermap)\n  qed\n  then show \\<open>(f \\<longlongrightarrow> l) F\\<close>\n    by (simp add: filterlim_def le_filter_def eventually_nhds_uniformity)\nqed\n\nlemma (in metric_space) tendsto_iff: \"(f \\<longlongrightarrow> l) F \\<longleftrightarrow> (\\<forall>e>0. eventually (\\<lambda>x. dist (f x) l < e) F)\"\n  unfolding nhds_metric filterlim_INF filterlim_principal by auto\n\nlemma tendsto_dist_iff:\n  \"((f \\<longlongrightarrow> l) F) \\<longleftrightarrow> (((\\<lambda>x. dist (f x) l) \\<longlongrightarrow> 0) F)\"\n  unfolding tendsto_iff by simp\n\nlemma (in metric_space) tendstoI [intro?]:\n  \"(\\<And>e. 0 < e \\<Longrightarrow> eventually (\\<lambda>x. dist (f x) l < e) F) \\<Longrightarrow> (f \\<longlongrightarrow> l) F\"\n  by (auto simp: tendsto_iff)\n\nlemma (in metric_space) tendstoD: \"(f \\<longlongrightarrow> l) F \\<Longrightarrow> 0 < e \\<Longrightarrow> eventually (\\<lambda>x. dist (f x) l < e) F\"\n  by (auto simp: tendsto_iff)\n\nlemma (in metric_space) eventually_nhds_metric:\n  \"eventually P (nhds a) \\<longleftrightarrow> (\\<exists>d>0. \\<forall>x. dist x a < d \\<longrightarrow> P x)\"\n  unfolding nhds_metric\n  by (subst eventually_INF_base)\n     (auto simp: eventually_principal Bex_def subset_eq intro: exI[of _ \"min a b\" for a b])\n\nlemma eventually_at: \"eventually P (at a within S) \\<longleftrightarrow> (\\<exists>d>0. \\<forall>x\\<in>S. x \\<noteq> a \\<and> dist x a < d \\<longrightarrow> P x)\"\n  for a :: \"'a :: metric_space\"\n  by (auto simp: eventually_at_filter eventually_nhds_metric)\n\nlemma frequently_at: \"frequently P (at a within S) \\<longleftrightarrow> (\\<forall>d>0. \\<exists>x\\<in>S. x \\<noteq> a \\<and> dist x a < d \\<and> P x)\"\n  for a :: \"'a :: metric_space\"\n  unfolding frequently_def eventually_at by auto\n\nlemma eventually_at_le: \"eventually P (at a within S) \\<longleftrightarrow> (\\<exists>d>0. \\<forall>x\\<in>S. x \\<noteq> a \\<and> dist x a \\<le> d \\<longrightarrow> P x)\"\n  for a :: \"'a::metric_space\"\n  unfolding eventually_at_filter eventually_nhds_metric\n  apply safe\n  apply (rule_tac x=\"d / 2\" in exI, auto)\n  done\n\nlemma eventually_at_left_real: \"a > (b :: real) \\<Longrightarrow> eventually (\\<lambda>x. x \\<in> {b<..<a}) (at_left a)\"\n  by (subst eventually_at, rule exI[of _ \"a - b\"]) (force simp: dist_real_def)\n\nlemma eventually_at_right_real: \"a < (b :: real) \\<Longrightarrow> eventually (\\<lambda>x. x \\<in> {a<..<b}) (at_right a)\"\n  by (subst eventually_at, rule exI[of _ \"b - a\"]) (force simp: dist_real_def)\n\nlemma metric_tendsto_imp_tendsto:\n  fixes a :: \"'a :: metric_space\"\n    and b :: \"'b :: metric_space\"\n  assumes f: \"(f \\<longlongrightarrow> a) F\"\n    and le: \"eventually (\\<lambda>x. dist (g x) b \\<le> dist (f x) a) F\"\n  shows \"(g \\<longlongrightarrow> b) F\"\nproof (rule tendstoI)\n  fix e :: real\n  assume \"0 < e\"\n  with f have \"eventually (\\<lambda>x. dist (f x) a < e) F\" by (rule tendstoD)\n  with le show \"eventually (\\<lambda>x. dist (g x) b < e) F\"\n    using le_less_trans by (rule eventually_elim2)\nqed\n\nlemma filterlim_real_sequentially: \"LIM x sequentially. real x :> at_top\"\nproof (clarsimp simp: filterlim_at_top)\n  fix Z\n  show \"\\<forall>\\<^sub>F x in sequentially. Z \\<le> real x\"\n    by (meson eventually_sequentiallyI nat_ceiling_le_eq)\nqed\n\nlemma filterlim_nat_sequentially: \"filterlim nat sequentially at_top\"\nproof -\n  have \"\\<forall>\\<^sub>F x in at_top. Z \\<le> nat x\" for Z\n    by (auto intro!: eventually_at_top_linorderI[where c=\"int Z\"])\n  then show ?thesis\n    unfolding filterlim_at_top ..\nqed\n\nlemma filterlim_floor_sequentially: \"filterlim floor at_top at_top\"\nproof -\n  have \"\\<forall>\\<^sub>F x in at_top. Z \\<le> \\<lfloor>x\\<rfloor>\" for Z\n    by (auto simp: le_floor_iff intro!: eventually_at_top_linorderI[where c=\"of_int Z\"])\n  then show ?thesis\n    unfolding filterlim_at_top ..\nqed\n\nlemma filterlim_sequentially_iff_filterlim_real:\n  \"filterlim f sequentially F \\<longleftrightarrow> filterlim (\\<lambda>x. real (f x)) at_top F\" (is \"?lhs = ?rhs\")\nproof\n  assume ?lhs then show ?rhs\n    using filterlim_compose filterlim_real_sequentially by blast\nnext\n  assume R: ?rhs\n  show ?lhs\n  proof -\n    have \"filterlim (\\<lambda>x. nat (floor (real (f x)))) sequentially F\"\n      by (intro filterlim_compose[OF filterlim_nat_sequentially]\n          filterlim_compose[OF filterlim_floor_sequentially] R)\n    then show ?thesis by simp\n  qed\nqed\n\n\nsubsubsection \\<open>Limits of Sequences\\<close>\n\nlemma lim_sequentially: \"X \\<longlonglongrightarrow> L \\<longleftrightarrow> (\\<forall>r>0. \\<exists>no. \\<forall>n\\<ge>no. dist (X n) L < r)\"\n  for L :: \"'a::metric_space\"\n  unfolding tendsto_iff eventually_sequentially ..\n\nlemmas LIMSEQ_def = lim_sequentially  (*legacy binding*)\n\nlemma LIMSEQ_iff_nz: \"X \\<longlonglongrightarrow> L \\<longleftrightarrow> (\\<forall>r>0. \\<exists>no>0. \\<forall>n\\<ge>no. dist (X n) L < r)\"\n  for L :: \"'a::metric_space\"\n  unfolding lim_sequentially by (metis Suc_leD zero_less_Suc)\n\nlemma metric_LIMSEQ_I: \"(\\<And>r. 0 < r \\<Longrightarrow> \\<exists>no. \\<forall>n\\<ge>no. dist (X n) L < r) \\<Longrightarrow> X \\<longlonglongrightarrow> L\"\n  for L :: \"'a::metric_space\"\n  by (simp add: lim_sequentially)\n\nlemma metric_LIMSEQ_D: \"X \\<longlonglongrightarrow> L \\<Longrightarrow> 0 < r \\<Longrightarrow> \\<exists>no. \\<forall>n\\<ge>no. dist (X n) L < r\"\n  for L :: \"'a::metric_space\"\n  by (simp add: lim_sequentially)\n\nlemma LIMSEQ_norm_0:\n  assumes  \"\\<And>n::nat. norm (f n) < 1 / real (Suc n)\"\n  shows \"f \\<longlonglongrightarrow> 0\"\nproof (rule metric_LIMSEQ_I)\n  fix \\<epsilon> :: \"real\"\n  assume \"\\<epsilon> > 0\"\n  then obtain N::nat where \"\\<epsilon> > inverse N\" \"N > 0\"\n    by (metis neq0_conv real_arch_inverse)\n  then have \"norm (f n) < \\<epsilon>\" if \"n \\<ge> N\" for n\n  proof -\n    have \"1 / (Suc n) \\<le> 1 / N\"\n      using \\<open>0 < N\\<close> inverse_of_nat_le le_SucI that by blast\n    also have \"\\<dots> < \\<epsilon>\"\n      by (metis (no_types) \\<open>inverse (real N) < \\<epsilon>\\<close> inverse_eq_divide)\n    finally show ?thesis\n      by (meson assms less_eq_real_def not_le order_trans)\n  qed\n  then show \"\\<exists>no. \\<forall>n\\<ge>no. dist (f n) 0 < \\<epsilon>\"\n    by auto\nqed\n\n\nsubsubsection \\<open>Limits of Functions\\<close>\n\nlemma LIM_def: \"f \\<midarrow>a\\<rightarrow> L \\<longleftrightarrow> (\\<forall>r > 0. \\<exists>s > 0. \\<forall>x. x \\<noteq> a \\<and> dist x a < s \\<longrightarrow> dist (f x) L < r)\"\n  for a :: \"'a::metric_space\" and L :: \"'b::metric_space\"\n  unfolding tendsto_iff eventually_at by simp\n\nlemma metric_LIM_I:\n  \"(\\<And>r. 0 < r \\<Longrightarrow> \\<exists>s>0. \\<forall>x. x \\<noteq> a \\<and> dist x a < s \\<longrightarrow> dist (f x) L < r) \\<Longrightarrow> f \\<midarrow>a\\<rightarrow> L\"\n  for a :: \"'a::metric_space\" and L :: \"'b::metric_space\"\n  by (simp add: LIM_def)\n\nlemma metric_LIM_D: \"f \\<midarrow>a\\<rightarrow> L \\<Longrightarrow> 0 < r \\<Longrightarrow> \\<exists>s>0. \\<forall>x. x \\<noteq> a \\<and> dist x a < s \\<longrightarrow> dist (f x) L < r\"\n  for a :: \"'a::metric_space\" and L :: \"'b::metric_space\"\n  by (simp add: LIM_def)\n\nlemma metric_LIM_imp_LIM:\n  fixes l :: \"'a::metric_space\"\n    and m :: \"'b::metric_space\"\n  assumes f: \"f \\<midarrow>a\\<rightarrow> l\"\n    and le: \"\\<And>x. x \\<noteq> a \\<Longrightarrow> dist (g x) m \\<le> dist (f x) l\"\n  shows \"g \\<midarrow>a\\<rightarrow> m\"\n  by (rule metric_tendsto_imp_tendsto [OF f]) (auto simp: eventually_at_topological le)\n\nlemma metric_LIM_equal2:\n  fixes a :: \"'a::metric_space\"\n  assumes \"g \\<midarrow>a\\<rightarrow> l\" \"0 < R\"\n    and \"\\<And>x. x \\<noteq> a \\<Longrightarrow> dist x a < R \\<Longrightarrow> f x = g x\"\n  shows \"f \\<midarrow>a\\<rightarrow> l\"\nproof -\n  have \"\\<And>S. \\<lbrakk>open S; l \\<in> S; \\<forall>\\<^sub>F x in at a. g x \\<in> S\\<rbrakk> \\<Longrightarrow> \\<forall>\\<^sub>F x in at a. f x \\<in> S\"\n    apply (simp add: eventually_at)\n    by (metis assms(2) assms(3) dual_order.strict_trans linorder_neqE_linordered_idom)\n  then show ?thesis\n    using assms by (simp add: tendsto_def)\nqed\n\nlemma metric_LIM_compose2:\n  fixes a :: \"'a::metric_space\"\n  assumes f: \"f \\<midarrow>a\\<rightarrow> b\"\n    and g: \"g \\<midarrow>b\\<rightarrow> c\"\n    and inj: \"\\<exists>d>0. \\<forall>x. x \\<noteq> a \\<and> dist x a < d \\<longrightarrow> f x \\<noteq> b\"\n  shows \"(\\<lambda>x. g (f x)) \\<midarrow>a\\<rightarrow> c\"\n  using inj by (intro tendsto_compose_eventually[OF g f]) (auto simp: eventually_at)\n\nlemma metric_isCont_LIM_compose2:\n  fixes f :: \"'a :: metric_space \\<Rightarrow> _\"\n  assumes f [unfolded isCont_def]: \"isCont f a\"\n    and g: \"g \\<midarrow>f a\\<rightarrow> l\"\n    and inj: \"\\<exists>d>0. \\<forall>x. x \\<noteq> a \\<and> dist x a < d \\<longrightarrow> f x \\<noteq> f a\"\n  shows \"(\\<lambda>x. g (f x)) \\<midarrow>a\\<rightarrow> l\"\n  by (rule metric_LIM_compose2 [OF f g inj])\n\n\nsubsection \\<open>Complete metric spaces\\<close>\n\nsubsection \\<open>Cauchy sequences\\<close>\n\nlemma (in metric_space) Cauchy_def: \"Cauchy X = (\\<forall>e>0. \\<exists>M. \\<forall>m\\<ge>M. \\<forall>n\\<ge>M. dist (X m) (X n) < e)\"\nproof -\n  have *: \"eventually P (INF M. principal {(X m, X n) | n m. m \\<ge> M \\<and> n \\<ge> M}) \\<longleftrightarrow>\n    (\\<exists>M. \\<forall>m\\<ge>M. \\<forall>n\\<ge>M. P (X m, X n))\" for P\n    apply (subst eventually_INF_base)\n    subgoal by simp\n    subgoal for a b\n      by (intro bexI[of _ \"max a b\"]) (auto simp: eventually_principal subset_eq)\n    subgoal by (auto simp: eventually_principal, blast)\n    done\n  have \"Cauchy X \\<longleftrightarrow> (INF M. principal {(X m, X n) | n m. m \\<ge> M \\<and> n \\<ge> M}) \\<le> uniformity\"\n    unfolding Cauchy_uniform_iff le_filter_def * ..\n  also have \"\\<dots> = (\\<forall>e>0. \\<exists>M. \\<forall>m\\<ge>M. \\<forall>n\\<ge>M. dist (X m) (X n) < e)\"\n    unfolding uniformity_dist le_INF_iff by (auto simp: * le_principal)\n  finally show ?thesis .\nqed\n\nlemma (in metric_space) Cauchy_altdef: \"Cauchy f \\<longleftrightarrow> (\\<forall>e>0. \\<exists>M. \\<forall>m\\<ge>M. \\<forall>n>m. dist (f m) (f n) < e)\"\n  (is \"?lhs \\<longleftrightarrow> ?rhs\")\nproof\n  assume ?rhs\n  show ?lhs\n    unfolding Cauchy_def\n  proof (intro allI impI)\n    fix e :: real assume e: \"e > 0\"\n    with \\<open>?rhs\\<close> obtain M where M: \"m \\<ge> M \\<Longrightarrow> n > m \\<Longrightarrow> dist (f m) (f n) < e\" for m n\n      by blast\n    have \"dist (f m) (f n) < e\" if \"m \\<ge> M\" \"n \\<ge> M\" for m n\n      using M[of m n] M[of n m] e that by (cases m n rule: linorder_cases) (auto simp: dist_commute)\n    then show \"\\<exists>M. \\<forall>m\\<ge>M. \\<forall>n\\<ge>M. dist (f m) (f n) < e\"\n      by blast\n  qed\nnext\n  assume ?lhs\n  show ?rhs\n  proof (intro allI impI)\n    fix e :: real\n    assume e: \"e > 0\"\n    with \\<open>Cauchy f\\<close> obtain M where \"\\<And>m n. m \\<ge> M \\<Longrightarrow> n \\<ge> M \\<Longrightarrow> dist (f m) (f n) < e\"\n      unfolding Cauchy_def by blast\n    then show \"\\<exists>M. \\<forall>m\\<ge>M. \\<forall>n>m. dist (f m) (f n) < e\"\n      by (intro exI[of _ M]) force\n  qed\nqed\n\nlemma (in metric_space) Cauchy_altdef2: \"Cauchy s \\<longleftrightarrow> (\\<forall>e>0. \\<exists>N::nat. \\<forall>n\\<ge>N. dist(s n)(s N) < e)\" (is \"?lhs = ?rhs\")\nproof \n  assume \"Cauchy s\"\n  then show ?rhs by (force simp: Cauchy_def)\nnext\n    assume ?rhs\n    {\n      fix e::real\n      assume \"e>0\"\n      with \\<open>?rhs\\<close> obtain N where N: \"\\<forall>n\\<ge>N. dist (s n) (s N) < e/2\"\n        by (erule_tac x=\"e/2\" in allE) auto\n      {\n        fix n m\n        assume nm: \"N \\<le> m \\<and> N \\<le> n\"\n        then have \"dist (s m) (s n) < e\" using N\n          using dist_triangle_half_l[of \"s m\" \"s N\" \"e\" \"s n\"]\n          by blast\n      }\n      then have \"\\<exists>N. \\<forall>m n. N \\<le> m \\<and> N \\<le> n \\<longrightarrow> dist (s m) (s n) < e\"\n        by blast\n    }\n    then have ?lhs\n      unfolding Cauchy_def by blast\n  then show ?lhs\n    by blast\nqed\n\nlemma (in metric_space) metric_CauchyI:\n  \"(\\<And>e. 0 < e \\<Longrightarrow> \\<exists>M. \\<forall>m\\<ge>M. \\<forall>n\\<ge>M. dist (X m) (X n) < e) \\<Longrightarrow> Cauchy X\"\n  by (simp add: Cauchy_def)\n\nlemma (in metric_space) CauchyI':\n  \"(\\<And>e. 0 < e \\<Longrightarrow> \\<exists>M. \\<forall>m\\<ge>M. \\<forall>n>m. dist (X m) (X n) < e) \\<Longrightarrow> Cauchy X\"\n  unfolding Cauchy_altdef by blast\n\nlemma (in metric_space) metric_CauchyD:\n  \"Cauchy X \\<Longrightarrow> 0 < e \\<Longrightarrow> \\<exists>M. \\<forall>m\\<ge>M. \\<forall>n\\<ge>M. dist (X m) (X n) < e\"\n  by (simp add: Cauchy_def)\n\nlemma (in metric_space) metric_Cauchy_iff2:\n  \"Cauchy X = (\\<forall>j. (\\<exists>M. \\<forall>m \\<ge> M. \\<forall>n \\<ge> M. dist (X m) (X n) < inverse(real (Suc j))))\"\n  apply (auto simp add: Cauchy_def)\n  by (metis less_trans of_nat_Suc reals_Archimedean)\n\nlemma Cauchy_iff2: \"Cauchy X \\<longleftrightarrow> (\\<forall>j. (\\<exists>M. \\<forall>m \\<ge> M. \\<forall>n \\<ge> M. \\<bar>X m - X n\\<bar> < inverse (real (Suc j))))\"\n  by (simp only: metric_Cauchy_iff2 dist_real_def)\n\nlemma lim_1_over_n [tendsto_intros]: \"((\\<lambda>n. 1 / of_nat n) \\<longlongrightarrow> (0::'a::real_normed_field)) sequentially\"\nproof (subst lim_sequentially, intro allI impI exI)\n  fix e::real and n\n  assume e: \"e > 0\" \n  have \"inverse e < of_nat (nat \\<lceil>inverse e + 1\\<rceil>)\" by linarith\n  also assume \"n \\<ge> nat \\<lceil>inverse e + 1\\<rceil>\"\n  finally show \"dist (1 / of_nat n :: 'a) 0 < e\"\n    using e by (simp add: field_split_simps norm_divide)\nqed\n\nlemma (in metric_space) complete_def:\n  shows \"complete S = (\\<forall>f. (\\<forall>n. f n \\<in> S) \\<and> Cauchy f \\<longrightarrow> (\\<exists>l\\<in>S. f \\<longlonglongrightarrow> l))\"\n  unfolding complete_uniform\nproof safe\n  fix f :: \"nat \\<Rightarrow> 'a\"\n  assume f: \"\\<forall>n. f n \\<in> S\" \"Cauchy f\"\n    and *: \"\\<forall>F\\<le>principal S. F \\<noteq> bot \\<longrightarrow> cauchy_filter F \\<longrightarrow> (\\<exists>x\\<in>S. F \\<le> nhds x)\"\n  then show \"\\<exists>l\\<in>S. f \\<longlonglongrightarrow> l\"\n    unfolding filterlim_def using f\n    by (intro *[rule_format])\n       (auto simp: filtermap_sequentually_ne_bot le_principal eventually_filtermap Cauchy_uniform)\nnext\n  fix F :: \"'a filter\"\n  assume \"F \\<le> principal S\" \"F \\<noteq> bot\" \"cauchy_filter F\"\n  assume seq: \"\\<forall>f. (\\<forall>n. f n \\<in> S) \\<and> Cauchy f \\<longrightarrow> (\\<exists>l\\<in>S. f \\<longlonglongrightarrow> l)\"\n\n  from \\<open>F \\<le> principal S\\<close> \\<open>cauchy_filter F\\<close>\n  have FF_le: \"F \\<times>\\<^sub>F F \\<le> uniformity_on S\"\n    by (simp add: cauchy_filter_def principal_prod_principal[symmetric] prod_filter_mono)\n\n  let ?P = \"\\<lambda>P e. eventually P F \\<and> (\\<forall>x. P x \\<longrightarrow> x \\<in> S) \\<and> (\\<forall>x y. P x \\<longrightarrow> P y \\<longrightarrow> dist x y < e)\"\n  have P: \"\\<exists>P. ?P P \\<epsilon>\" if \"0 < \\<epsilon>\" for \\<epsilon> :: real\n  proof -\n    from that have \"eventually (\\<lambda>(x, y). x \\<in> S \\<and> y \\<in> S \\<and> dist x y < \\<epsilon>) (uniformity_on S)\"\n      by (auto simp: eventually_inf_principal eventually_uniformity_metric)\n    from filter_leD[OF FF_le this] show ?thesis\n      by (auto simp: eventually_prod_same)\n  qed\n\n  have \"\\<exists>P. \\<forall>n. ?P (P n) (1 / Suc n) \\<and> P (Suc n) \\<le> P n\"\n  proof (rule dependent_nat_choice)\n    show \"\\<exists>P. ?P P (1 / Suc 0)\"\n      using P[of 1] by auto\n  next\n    fix P n assume \"?P P (1/Suc n)\"\n    moreover obtain Q where \"?P Q (1 / Suc (Suc n))\"\n      using P[of \"1/Suc (Suc n)\"] by auto\n    ultimately show \"\\<exists>Q. ?P Q (1 / Suc (Suc n)) \\<and> Q \\<le> P\"\n      by (intro exI[of _ \"\\<lambda>x. P x \\<and> Q x\"]) (auto simp: eventually_conj_iff)\n  qed\n  then obtain P where P: \"eventually (P n) F\" \"P n x \\<Longrightarrow> x \\<in> S\"\n    \"P n x \\<Longrightarrow> P n y \\<Longrightarrow> dist x y < 1 / Suc n\" \"P (Suc n) \\<le> P n\"\n    for n x y\n    by metis\n  have \"antimono P\"\n    using P(4) by (rule decseq_SucI)\n\n  obtain X where X: \"P n (X n)\" for n\n    using P(1)[THEN eventually_happens'[OF \\<open>F \\<noteq> bot\\<close>]] by metis\n  have \"Cauchy X\"\n    unfolding metric_Cauchy_iff2 inverse_eq_divide\n  proof (intro exI allI impI)\n    fix j m n :: nat\n    assume \"j \\<le> m\" \"j \\<le> n\"\n    with \\<open>antimono P\\<close> X have \"P j (X m)\" \"P j (X n)\"\n      by (auto simp: antimono_def)\n    then show \"dist (X m) (X n) < 1 / Suc j\"\n      by (rule P)\n  qed\n  moreover have \"\\<forall>n. X n \\<in> S\"\n    using P(2) X by auto\n  ultimately obtain x where \"X \\<longlonglongrightarrow> x\" \"x \\<in> S\"\n    using seq by blast\n\n  show \"\\<exists>x\\<in>S. F \\<le> nhds x\"\n  proof (rule bexI)\n    have \"eventually (\\<lambda>y. dist y x < e) F\" if \"0 < e\" for e :: real\n    proof -\n      from that have \"(\\<lambda>n. 1 / Suc n :: real) \\<longlonglongrightarrow> 0 \\<and> 0 < e / 2\"\n        by (subst filterlim_sequentially_Suc) (auto intro!: lim_1_over_n)\n      then have \"\\<forall>\\<^sub>F n in sequentially. dist (X n) x < e / 2 \\<and> 1 / Suc n < e / 2\"\n        using \\<open>X \\<longlonglongrightarrow> x\\<close>\n        unfolding tendsto_iff order_tendsto_iff[where 'a=real] eventually_conj_iff\n        by blast\n      then obtain n where \"dist x (X n) < e / 2\" \"1 / Suc n < e / 2\"\n        by (auto simp: eventually_sequentially dist_commute)\n      show ?thesis\n        using \\<open>eventually (P n) F\\<close>\n      proof eventually_elim\n        case (elim y)\n        then have \"dist y (X n) < 1 / Suc n\"\n          by (intro X P)\n        also have \"\\<dots> < e / 2\" by fact\n        finally show \"dist y x < e\"\n          by (rule dist_triangle_half_l) fact\n      qed\n    qed\n    then show \"F \\<le> nhds x\"\n      unfolding nhds_metric le_INF_iff le_principal by auto\n  qed fact\nqed\n\ntext\\<open>apparently unused\\<close>\nlemma (in metric_space) totally_bounded_metric:\n  \"totally_bounded S \\<longleftrightarrow> (\\<forall>e>0. \\<exists>k. finite k \\<and> S \\<subseteq> (\\<Union>x\\<in>k. {y. dist x y < e}))\"\n  unfolding totally_bounded_def eventually_uniformity_metric imp_ex\n  apply (subst all_comm)\n  apply (intro arg_cong[where f=All] ext, safe)\n  subgoal for e\n    apply (erule allE[of _ \"\\<lambda>(x, y). dist x y < e\"])\n    apply auto\n    done\n  subgoal for e P k\n    apply (intro exI[of _ k])\n    apply (force simp: subset_eq)\n    done\n  done\n\n\nsetup \\<open>Sign.add_const_constraint (\\<^const_name>\\<open>dist\\<close>, SOME \\<^typ>\\<open>'a::dist \\<Rightarrow> 'a \\<Rightarrow> real\\<close>)\\<close>\n\n(* Contributed by Dominique Unruh *)\nlemma cauchy_filter_metric:\n  fixes F :: \"'a::{uniformity_dist,uniform_space} filter\"\n  shows \"cauchy_filter F \\<longleftrightarrow> (\\<forall>e. e>0 \\<longrightarrow> (\\<exists>P. eventually P F \\<and> (\\<forall>x y. P x \\<and> P y \\<longrightarrow> dist x y < e)))\"\nproof (unfold cauchy_filter_def le_filter_def, auto)\n  assume assm: \\<open>\\<forall>e>0. \\<exists>P. eventually P F \\<and> (\\<forall>x y. P x \\<and> P y \\<longrightarrow> dist x y < e)\\<close>\n  then show \\<open>eventually P uniformity \\<Longrightarrow> eventually P (F \\<times>\\<^sub>F F)\\<close> for P\n    apply (auto simp: eventually_uniformity_metric)\n    using eventually_prod_same by blast\nnext\n  fix e :: real\n  assume \\<open>e > 0\\<close>\n  assume asm: \\<open>\\<forall>P. eventually P uniformity \\<longrightarrow> eventually P (F \\<times>\\<^sub>F F)\\<close>\n\n  define P where \\<open>P \\<equiv> \\<lambda>(x,y :: 'a). dist x y < e\\<close>\n  with asm \\<open>e > 0\\<close> have \\<open>eventually P (F \\<times>\\<^sub>F F)\\<close>\n    by (metis case_prod_conv eventually_uniformity_metric)\n  then\n  show \\<open>\\<exists>P. eventually P F \\<and> (\\<forall>x y. P x \\<and> P y \\<longrightarrow> dist x y < e)\\<close>\n    by (auto simp add: eventually_prod_same P_def)\nqed\n\n(* Contributed by Dominique Unruh *)\nlemma cauchy_filter_metric_filtermap:\n  fixes f :: \"'a \\<Rightarrow> 'b::{uniformity_dist,uniform_space}\"\n  shows \"cauchy_filter (filtermap f F) \\<longleftrightarrow> (\\<forall>e. e>0 \\<longrightarrow> (\\<exists>P. eventually P F \\<and> (\\<forall>x y. P x \\<and> P y \\<longrightarrow> dist (f x) (f y) < e)))\"\nproof (subst cauchy_filter_metric, intro iffI allI impI)\n  assume \\<open>\\<forall>e>0. \\<exists>P. eventually P (filtermap f F) \\<and> (\\<forall>x y. P x \\<and> P y \\<longrightarrow> dist x y < e)\\<close>\n  then show \\<open>e>0 \\<Longrightarrow> \\<exists>P. eventually P F \\<and> (\\<forall>x y. P x \\<and> P y \\<longrightarrow> dist (f x) (f y) < e)\\<close> for e\n    unfolding eventually_filtermap by blast\nnext\n  assume asm: \\<open>\\<forall>e>0. \\<exists>P. eventually P F \\<and> (\\<forall>x y. P x \\<and> P y \\<longrightarrow> dist (f x) (f y) < e)\\<close>\n  fix e::real assume \\<open>e > 0\\<close>\n  then obtain P where \\<open>eventually P F\\<close> and PPe: \\<open>P x \\<and> P y \\<longrightarrow> dist (f x) (f y) < e\\<close> for x y\n    using asm by blast\n\n  show \\<open>\\<exists>P. eventually P (filtermap f F) \\<and> (\\<forall>x y. P x \\<and> P y \\<longrightarrow> dist x y < e)\\<close>\n    apply (rule exI[of _ \\<open>\\<lambda>x. \\<exists>y. P y \\<and> x = f y\\<close>])\n    using PPe \\<open>eventually P F\\<close> apply (auto simp: eventually_filtermap)\n    by (smt (verit, ccfv_SIG) eventually_elim2)\nqed\n\nsetup \\<open>Sign.add_const_constraint (\\<^const_name>\\<open>dist\\<close>, SOME \\<^typ>\\<open>'a::metric_space \\<Rightarrow> 'a \\<Rightarrow> real\\<close>)\\<close>\n\nsubsubsection \\<open>Cauchy Sequences are Convergent\\<close>\n\n(* TODO: update to uniform_space *)\nclass complete_space = metric_space +\n  assumes Cauchy_convergent: \"Cauchy X \\<Longrightarrow> convergent X\"\n\nlemma Cauchy_convergent_iff: \"Cauchy X \\<longleftrightarrow> convergent X\"\n  for X :: \"nat \\<Rightarrow> 'a::complete_space\"\n  by (blast intro: Cauchy_convergent convergent_Cauchy)\n\ntext \\<open>To prove that a Cauchy sequence converges, it suffices to show that a subsequence converges.\\<close>\n\nlemma Cauchy_converges_subseq:\n  fixes u::\"nat \\<Rightarrow> 'a::metric_space\"\n  assumes \"Cauchy u\"\n    \"strict_mono r\"\n    \"(u \\<circ> r) \\<longlonglongrightarrow> l\"\n  shows \"u \\<longlonglongrightarrow> l\"\nproof -\n  have *: \"eventually (\\<lambda>n. dist (u n) l < e) sequentially\" if \"e > 0\" for e\n  proof -\n    have \"e/2 > 0\" using that by auto\n    then obtain N1 where N1: \"\\<And>m n. m \\<ge> N1 \\<Longrightarrow> n \\<ge> N1 \\<Longrightarrow> dist (u m) (u n) < e/2\"\n      using \\<open>Cauchy u\\<close> unfolding Cauchy_def by blast\n    obtain N2 where N2: \"\\<And>n. n \\<ge> N2 \\<Longrightarrow> dist ((u \\<circ> r) n) l < e / 2\"\n      using order_tendstoD(2)[OF iffD1[OF tendsto_dist_iff \\<open>(u \\<circ> r) \\<longlonglongrightarrow> l\\<close>] \\<open>e/2 > 0\\<close>]\n      unfolding eventually_sequentially by auto\n    have \"dist (u n) l < e\" if \"n \\<ge> max N1 N2\" for n\n    proof -\n      have \"dist (u n) l \\<le> dist (u n) ((u \\<circ> r) n) + dist ((u \\<circ> r) n) l\"\n        by (rule dist_triangle)\n      also have \"\\<dots> < e/2 + e/2\"\n      proof (intro add_strict_mono)\n        show \"dist (u n) ((u \\<circ> r) n) < e / 2\"\n          using N1[of n \"r n\"] N2[of n] that unfolding comp_def\n          by (meson assms(2) le_trans max.bounded_iff strict_mono_imp_increasing)\n        show \"dist ((u \\<circ> r) n) l < e / 2\"\n          using N2 that by auto\n      qed\n      finally show ?thesis by simp\n    qed \n    then show ?thesis unfolding eventually_sequentially by blast\n  qed\n  have \"(\\<lambda>n. dist (u n) l) \\<longlonglongrightarrow> 0\"\n    by (simp add: less_le_trans * order_tendstoI)\n  then show ?thesis using tendsto_dist_iff by auto\nqed\n\nsubsection \\<open>The set of real numbers is a complete metric space\\<close>\n\ntext \\<open>\n  Proof that Cauchy sequences converge based on the one from\n  \\<^url>\\<open>http://pirate.shu.edu/~wachsmut/ira/numseq/proofs/cauconv.html\\<close>\n\\<close>\n\ntext \\<open>\n  If sequence \\<^term>\\<open>X\\<close> is Cauchy, then its limit is the lub of\n  \\<^term>\\<open>{r::real. \\<exists>N. \\<forall>n\\<ge>N. r < X n}\\<close>\n\\<close>\nlemma increasing_LIMSEQ:\n  fixes f :: \"nat \\<Rightarrow> real\"\n  assumes inc: \"\\<And>n. f n \\<le> f (Suc n)\"\n    and bdd: \"\\<And>n. f n \\<le> l\"\n    and en: \"\\<And>e. 0 < e \\<Longrightarrow> \\<exists>n. l \\<le> f n + e\"\n  shows \"f \\<longlonglongrightarrow> l\"\nproof (rule increasing_tendsto)\n  fix x\n  assume \"x < l\"\n  with dense[of 0 \"l - x\"] obtain e where \"0 < e\" \"e < l - x\"\n    by auto\n  from en[OF \\<open>0 < e\\<close>] obtain n where \"l - e \\<le> f n\"\n    by (auto simp: field_simps)\n  with \\<open>e < l - x\\<close> \\<open>0 < e\\<close> have \"x < f n\"\n    by simp\n  with incseq_SucI[of f, OF inc] show \"eventually (\\<lambda>n. x < f n) sequentially\"\n    by (auto simp: eventually_sequentially incseq_def intro: less_le_trans)\nqed (use bdd in auto)\n\nlemma real_Cauchy_convergent:\n  fixes X :: \"nat \\<Rightarrow> real\"\n  assumes X: \"Cauchy X\"\n  shows \"convergent X\"\nproof -\n  define S :: \"real set\" where \"S = {x. \\<exists>N. \\<forall>n\\<ge>N. x < X n}\"\n  then have mem_S: \"\\<And>N x. \\<forall>n\\<ge>N. x < X n \\<Longrightarrow> x \\<in> S\"\n    by auto\n\n  have bound_isUb: \"y \\<le> x\" if N: \"\\<forall>n\\<ge>N. X n < x\" and \"y \\<in> S\" for N and x y :: real\n  proof -\n    from that have \"\\<exists>M. \\<forall>n\\<ge>M. y < X n\"\n      by (simp add: S_def)\n    then obtain M where \"\\<forall>n\\<ge>M. y < X n\" ..\n    then have \"y < X (max M N)\" by simp\n    also have \"\\<dots> < x\" using N by simp\n    finally show ?thesis by (rule order_less_imp_le)\n  qed\n\n  obtain N where \"\\<forall>m\\<ge>N. \\<forall>n\\<ge>N. dist (X m) (X n) < 1\"\n    using X[THEN metric_CauchyD, OF zero_less_one] by auto\n  then have N: \"\\<forall>n\\<ge>N. dist (X n) (X N) < 1\" by simp\n  have [simp]: \"S \\<noteq> {}\"\n  proof (intro exI ex_in_conv[THEN iffD1])\n    from N have \"\\<forall>n\\<ge>N. X N - 1 < X n\"\n      by (simp add: abs_diff_less_iff dist_real_def)\n    then show \"X N - 1 \\<in> S\" by (rule mem_S)\n  qed\n  have [simp]: \"bdd_above S\"\n  proof\n    from N have \"\\<forall>n\\<ge>N. X n < X N + 1\"\n      by (simp add: abs_diff_less_iff dist_real_def)\n    then show \"\\<And>s. s \\<in> S \\<Longrightarrow>  s \\<le> X N + 1\"\n      by (rule bound_isUb)\n  qed\n  have \"X \\<longlonglongrightarrow> Sup S\"\n  proof (rule metric_LIMSEQ_I)\n    fix r :: real\n    assume \"0 < r\"\n    then have r: \"0 < r/2\" by simp\n    obtain N where \"\\<forall>n\\<ge>N. \\<forall>m\\<ge>N. dist (X n) (X m) < r/2\"\n      using metric_CauchyD [OF X r] by auto\n    then have \"\\<forall>n\\<ge>N. dist (X n) (X N) < r/2\" by simp\n    then have N: \"\\<forall>n\\<ge>N. X N - r/2 < X n \\<and> X n < X N + r/2\"\n      by (simp only: dist_real_def abs_diff_less_iff)\n\n    from N have \"\\<forall>n\\<ge>N. X N - r/2 < X n\" by blast\n    then have \"X N - r/2 \\<in> S\" by (rule mem_S)\n    then have 1: \"X N - r/2 \\<le> Sup S\" by (simp add: cSup_upper)\n\n    from N have \"\\<forall>n\\<ge>N. X n < X N + r/2\" by blast\n    from bound_isUb[OF this]\n    have 2: \"Sup S \\<le> X N + r/2\"\n      by (intro cSup_least) simp_all\n\n    show \"\\<exists>N. \\<forall>n\\<ge>N. dist (X n) (Sup S) < r\"\n    proof (intro exI allI impI)\n      fix n\n      assume n: \"N \\<le> n\"\n      from N n have \"X n < X N + r/2\" and \"X N - r/2 < X n\"\n        by simp_all\n      then show \"dist (X n) (Sup S) < r\" using 1 2\n        by (simp add: abs_diff_less_iff dist_real_def)\n    qed\n  qed\n  then show ?thesis by (auto simp: convergent_def)\nqed\n\ninstance real :: complete_space\n  by intro_classes (rule real_Cauchy_convergent)\n\nclass banach = real_normed_vector + complete_space\n\ninstance real :: banach ..\n\nlemma tendsto_at_topI_sequentially:\n  fixes f :: \"real \\<Rightarrow> 'b::first_countable_topology\"\n  assumes *: \"\\<And>X. filterlim X at_top sequentially \\<Longrightarrow> (\\<lambda>n. f (X n)) \\<longlonglongrightarrow> y\"\n  shows \"(f \\<longlongrightarrow> y) at_top\"\nproof -\n  obtain A where A: \"decseq A\" \"open (A n)\" \"y \\<in> A n\" \"nhds y = (INF n. principal (A n))\" for n\n    by (rule nhds_countable[of y]) (rule that)\n\n  have \"\\<forall>m. \\<exists>k. \\<forall>x\\<ge>k. f x \\<in> A m\"\n  proof (rule ccontr)\n    assume \"\\<not> (\\<forall>m. \\<exists>k. \\<forall>x\\<ge>k. f x \\<in> A m)\"\n    then obtain m where \"\\<And>k. \\<exists>x\\<ge>k. f x \\<notin> A m\"\n      by auto\n    then have \"\\<exists>X. \\<forall>n. (f (X n) \\<notin> A m) \\<and> max n (X n) + 1 \\<le> X (Suc n)\"\n      by (intro dependent_nat_choice) (auto simp del: max.bounded_iff)\n    then obtain X where X: \"\\<And>n. f (X n) \\<notin> A m\" \"\\<And>n. max n (X n) + 1 \\<le> X (Suc n)\"\n      by auto\n    have \"1 \\<le> n \\<Longrightarrow> real n \\<le> X n\" for n\n      using X[of \"n - 1\"] by auto\n    then have \"filterlim X at_top sequentially\"\n      by (force intro!: filterlim_at_top_mono[OF filterlim_real_sequentially]\n          simp: eventually_sequentially)\n    from topological_tendstoD[OF *[OF this] A(2, 3), of m] X(1) show False\n      by auto\n  qed\n  then obtain k where \"k m \\<le> x \\<Longrightarrow> f x \\<in> A m\" for m x\n    by metis\n  then show ?thesis\n    unfolding at_top_def A by (intro filterlim_base[where i=k]) auto\nqed\n\nlemma tendsto_at_topI_sequentially_real:\n  fixes f :: \"real \\<Rightarrow> real\"\n  assumes mono: \"mono f\"\n    and limseq: \"(\\<lambda>n. f (real n)) \\<longlonglongrightarrow> y\"\n  shows \"(f \\<longlongrightarrow> y) at_top\"\nproof (rule tendstoI)\n  fix e :: real\n  assume \"0 < e\"\n  with limseq obtain N :: nat where N: \"N \\<le> n \\<Longrightarrow> \\<bar>f (real n) - y\\<bar> < e\" for n\n    by (auto simp: lim_sequentially dist_real_def)\n  have le: \"f x \\<le> y\" for x :: real\n  proof -\n    obtain n where \"x \\<le> real_of_nat n\"\n      using real_arch_simple[of x] ..\n    note monoD[OF mono this]\n    also have \"f (real_of_nat n) \\<le> y\"\n      by (rule LIMSEQ_le_const[OF limseq]) (auto intro!: exI[of _ n] monoD[OF mono])\n    finally show ?thesis .\n  qed\n  have \"eventually (\\<lambda>x. real N \\<le> x) at_top\"\n    by (rule eventually_ge_at_top)\n  then show \"eventually (\\<lambda>x. dist (f x) y < e) at_top\"\n  proof eventually_elim\n    case (elim x)\n    with N[of N] le have \"y - f (real N) < e\" by auto\n    moreover note monoD[OF mono elim]\n    ultimately show \"dist (f x) y < e\"\n      using le[of x] by (auto simp: dist_real_def field_simps)\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/Real_Vector_Spaces.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8962513731336204, "lm_q2_score": 0.8333245953120233, "lm_q1q2_score": 0.7468683128144193}}
{"text": "(*\n    Authors:    Jose Divas\u00f3n\n                Sebastiaan Joosten\n                Ren\u00e9 Thiemann\n                Akihisa Yamada\n    License:    BSD\n*)\n\nsection \\<open>Factor bound\\<close>\n\ntext \\<open>This theory extends the work about factor bounds which was carried out \n  in the Berlekamp-Zassenhaus development.\\<close> \n\ntheory Factor_Bound_2\nimports Berlekamp_Zassenhaus.Factor_Bound\n   LLL_Basis_Reduction.Norms\nbegin\n\nlemma norm_1_bound_mignotte: \"norm1 f \\<le> 2^(degree f) * mahler_measure f\"\nproof (cases \"f = 0\")\n  case f0: False\n  have cf: \"coeffs f = map (\\<lambda> i. coeff f i) [0 ..< Suc( degree f)]\" unfolding coeffs_def \n    using f0 by auto\n  have \"real_of_int (sum_list (map abs (coeffs f))) \n    = (\\<Sum>i\\<le>degree f. real_of_int \\<bar>poly.coeff f i\\<bar>)\"\n    unfolding cf of_int_hom.hom_sum_list unfolding sum_list_sum_nth \n    by (rule sum.cong, force, auto simp: o_def nth_append)\n  also have \"\\<dots> \\<le> (\\<Sum>i\\<le>degree f. real (degree f choose i) * mahler_measure f)\"\n    by (rule sum_mono, rule Mignotte_bound)\n  also have \"\\<dots> = real (sum (\\<lambda> i. (degree f choose i)) {..degree f}) * mahler_measure f\" \n    unfolding sum_distrib_right[symmetric] by auto\n  also have \"\\<dots> = 2^(degree f) * mahler_measure f\" unfolding choose_row_sum by auto\n  finally show ?thesis unfolding norm1_def .\nqed (auto simp: mahler_measure_ge_0 norm1_def)\n\nlemma mahler_measure_l2norm: \"mahler_measure f \\<le> sqrt (of_int \\<parallel>f\\<parallel>\\<^sup>2)\" \n  using Landau_inequality_mahler_measure[of f] unfolding sq_norm_poly_def\n  by (auto simp: power2_eq_square)\n\nlemma sq_norm_factor_bound: \n  fixes f h :: \"int poly\"\n  assumes dvd: \"h dvd f\" and f0: \"f \\<noteq> 0\" \n  shows \"\\<parallel>h\\<parallel>\\<^sup>2 \\<le> 2 ^ (2 * degree h) * \\<parallel>f\\<parallel>\\<^sup>2\" \nproof - \n  let ?r = real_of_int\n  have h21: \"?r \\<parallel>h\\<parallel>\\<^sup>2 \\<le> (?r (norm1 h))^2\" using norm2_le_norm1_int[of h]\n    by (metis of_int_le_iff of_int_power)\n  also have \"\\<dots> \\<le> (2^(degree h) * mahler_measure h)^2\" \n    using power_mono[OF norm_1_bound_mignotte[of h], of 2] \n    by (auto simp: norm1_ge_0)\n  also have \"\\<dots> = 2^(2 * degree h) * (mahler_measure h)^2\"\n    by (simp add: power_even_eq power_mult_distrib)\n  also have \"\\<dots> \\<le> 2^(2 * degree h) * (mahler_measure f)^2\" \n    by (rule mult_left_mono[OF power_mono], auto simp: mahler_measure_ge_0\n    mahler_measure_dvd[OF f0 dvd])\n  also have \"\\<dots> \\<le> 2^(2 * degree h) * ?r (\\<parallel>f\\<parallel>\\<^sup>2)\"\n  proof (rule mult_left_mono)\n    have \"?r (\\<parallel>f\\<parallel>\\<^sup>2) \\<ge> 0\" by auto\n    from real_sqrt_pow2[OF this]\n    show \"(mahler_measure f)\\<^sup>2 \\<le> ?r (\\<parallel>f\\<parallel>\\<^sup>2)\" \n      using power_mono[OF mahler_measure_l2norm[of f], of 2]\n      by (auto simp: mahler_measure_ge_0)\n  qed auto\n  also have \"\\<dots> = ?r (2^(2*degree h) * \\<parallel>f\\<parallel>\\<^sup>2)\" \n    by (simp add: ac_simps)\n  finally show \"\\<parallel>h\\<parallel>\\<^sup>2 \\<le> 2 ^ (2 * degree h) * \\<parallel>f\\<parallel>\\<^sup>2\" unfolding of_int_le_iff .\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_Factorization/Factor_Bound_2.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8962513620489618, "lm_q2_score": 0.8333246035907933, "lm_q1q2_score": 0.7468683109971597}}
{"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\"\ndefinition \"bf_minus a b = bf_ite b bf_False a\"\nlemma bf_minus_alt: \"bf_minus a b = bf_and a (bf_not b)\" unfolding bf_and_def bf_not_def bf_minus_def unfolding bf_ite_def unfolding fun_eq_iff by simp\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": "jcaesar", "repo": "bdd", "sha": "c61d3cb0a33e13a7da1b92b179ddbe470ce4e8c4", "save_path": "github-repos/isabelle/jcaesar-bdd", "path": "github-repos/isabelle/jcaesar-bdd/bdd-c61d3cb0a33e13a7da1b92b179ddbe470ce4e8c4/thy/Bool_Func.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9161096112990285, "lm_q2_score": 0.8152324826183822, "lm_q1q2_score": 0.7468423127698681}}
{"text": "(*  Title:      HOL/ex/ThreeDivides.thy\n    Author:     Benjamin Porter, 2005\n*)\n\nsection {* Three Divides Theorem *}\n\ntheory ThreeDivides\nimports Main \"~~/src/HOL/Library/LaTeXsugar\"\nbegin\n\nsubsection {* Abstract *}\n\ntext {*\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@{text \"\\<box>\"}\n*}\n\n\nsubsection {* Formal proof *}\n\nsubsubsection {* Miscellaneous summation lemmas *}\n\ntext {* If $a$ divides @{text \"A x\"} for all x then $a$ divides any\nsum over terms of the form @{text \"(A x)*(P x)\"} for arbitrary $P$. *}\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 {* Generalised Three Divides *}\n\ntext {* 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. *}\n\ntext {* 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. *}\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 {* Now we prove that 3 always divides numbers of the form $10^x - 1$. *}\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 {* Expanding on the previous lemma and lemma @{text \"div_sum\"}. *}\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 {* Using lemmas @{text \"digit_diff_split\"} and \n@{text \"three_divs_1\"} we now prove the following lemma. \n*}\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 {* \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*}\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 setsum_mono) simp\n  txt {* This lets us form the term\n         @{term \"(\\<Sum>x<nd. D x * 10^x) - (\\<Sum>x<nd. D x)\"} *}\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 {* Three Divides Natural *}\n\ntext {* 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 @{text\n\"three_div_general\"} to prove our final theorem. *}\n\n\ntext {* \\medskip Definitions of length and digit sum. *}\n\ntext {* 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 @{text \"nlen\"} returns the number of digits in a natural\nnumber n. *}\n\nfun nlen :: \"nat \\<Rightarrow> nat\"\nwhere\n  \"nlen 0 = 0\"\n| \"nlen x = 1 + nlen (x div 10)\"\n\ntext {* The function @{text \"sumdig\"} returns the sum of all digits in\nsome number n. *}\n\ndefinition\n  sumdig :: \"nat \\<Rightarrow> nat\" where\n  \"sumdig n = (\\<Sum>x < nlen n. n div 10^x mod 10)\"\n\ntext {* Some properties of these functions follow. *}\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 {* 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. *}\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 `Suc nd = nlen m`\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 setsum_right_distrib) (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: setsum_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] setsum_head_upt_Suc cdef)\n    also note `Suc nd = nlen m`\n    finally\n    show \"m = (\\<Sum>x<nlen m. m div 10^x mod 10 * 10^x)\" .\n  qed\nqed\n\n\ntext {* \\medskip Final theorem. *}\n\ntext {* We now combine the general theorem @{text \"three_div_general\"}\nand existence result of @{text \"exp_exists\"} to prove our final\ntheorem. *}\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": "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/ThreeDivides.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473680407889, "lm_q2_score": 0.855851143290548, "lm_q1q2_score": 0.7465994922842096}}
{"text": "theory P15 imports Main begin\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\n   apply (rule impI)\n   apply (erule exE)\n   apply (erule allE)\n   apply (erule impE)\n  apply assumption+\n\n  apply (rule allI)\n  apply (rule impI)\n  apply (erule impE)\n  apply (rule exI)\n   apply assumption+\n  done\n\nlemma \"((\\<forall> x. P x) \\<and> (\\<forall> x. Q x)) = (\\<forall> x. (P x \\<and> Q x))\"\n  apply (rule iffI)\n\n   apply (erule conjE)\n   apply (rule allI)\n   apply (rule conjI)\n    apply (erule allE)\n    apply assumption\n   apply (erule allE)+\n   apply assumption\n\n  apply (rule conjI)\n   apply (rule allI)\n   apply (erule allE)\n   apply (erule conjE)\n   apply assumption\n   apply (rule allI)\n   apply (erule allE)\n   apply (erule conjE)\n   apply assumption\n  done\n\nlemma \"((\\<forall> x. P x) \\<or> (\\<forall> x. Q x)) = (\\<forall> x. (P x \\<or> Q x))\"\n  nitpick\n  oops\n\nlemma \"((\\<exists> x. P x) \\<or> (\\<exists> x. Q x)) = (\\<exists> x. (P x \\<or> Q x))\"\n  apply (rule iffI)\n\n   apply (erule disjE)\n    apply (erule exE)\n    apply (rule exI)\n    apply (rule disjI1)\n    apply assumption\n   apply (erule exE)\n   apply (rule exI)\n   apply (rule disjI2)\n   apply assumption\n\n  apply (erule exE)\n  apply (erule disjE)\n   apply (rule disjI1)\n   apply (rule exI)\n   apply assumption\n\n  apply (rule disjI2)\n   apply (rule exI)\n  apply assumption\n  done\n\nlemma \"(\\<forall> x. \\<exists> y. P x y) \\<longrightarrow> (\\<exists> y. \\<forall> x. P x y)\"\n  nitpick\n  oops\n\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 notE)\n  apply (erule allE)\n  apply assumption\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/P15.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404018582426, "lm_q2_score": 0.8031738057795403, "lm_q1q2_score": 0.74650218480575}}
{"text": "theory Inductiv\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 (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)\n   apply(simp_all)\n  done\n\nlemma \"evn n \\<Longrightarrow> ev n\"\n  apply(induction n rule: evn.induct)\n    apply(simp_all add: ev0 evSS)\n  done\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  by (simp add: star.step)\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/Inductiv.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404018582426, "lm_q2_score": 0.8031738057795402, "lm_q1q2_score": 0.7465021848057499}}
{"text": "(*  Title:       The Cauchy-Schwarz Inequality\n    Author:      Benjamin Porter <Benjamin.Porter at gmail.com>, 2006\n    Maintainer:  Benjamin Porter <Benjamin.Porter at gmail.com>\n*)\n\nheader {* The Cauchy-Schwarz Inequality *}\n\ntheory CauchySchwarz\nimports Complex_Main\nbegin\n\n(*<*)\n\n(* Some basic results that don't need to be in the final doc ..*)\n\n\nlemmas real_sq = power2_eq_square [where 'a = real, symmetric]\n\nlemmas real_sq_exp = power_mult_distrib [where 'a = real and ?n = 2]\n\nlemma double_sum_equiv:\n  fixes f::\"nat \\<Rightarrow> real\"\n  shows\n  \"(\\<Sum>k\\<in>{1..n}. (\\<Sum>j\\<in>{1..n}. f k * g j)) =\n   (\\<Sum>k\\<in>{1..n}. (\\<Sum>j\\<in>{1..n}. f j * g k))\"\n  by (rule setsum.commute)\n\n(*>*)\n\n\n\nsection {* Abstract *}\n\ntext {* The following document presents a formalised proof of the\nCauchy-Schwarz Inequality for the specific case of $R^n$. The system\nused is Isabelle/Isar. \n\n{\\em Theorem:} Take $V$ to be some vector space possessing a norm and\ninner product, then for all $a,b \\in V$ the following inequality\nholds: @{text \"\\<bar>a\\<cdot>b\\<bar> \\<le> \\<parallel>a\\<parallel>*\\<parallel>b\\<parallel>\"}. Specifically, in the Real case, the\nnorm is the Euclidean length and the inner product is the standard dot\nproduct. *}\n\n\nsection {* Formal Proof *}\n\nsubsection {* Vector, Dot and Norm definitions. *}\n\ntext {* This section presents definitions for a real vector type, a\ndot product function and a norm function. *}\n\nsubsubsection {* Vector *}\n\ntext {* We now define a vector type to be a tuple of (function,\nlength). Where the function is of type @{typ \"nat\\<Rightarrow>real\"}. We also\ndefine some accessor functions and appropriate notation. *}\n\ntype_synonym vector = \"(nat\\<Rightarrow>real) * nat\";\n\ndefinition\n  ith :: \"vector \\<Rightarrow> nat \\<Rightarrow> real\" (\"((_)\\<^bsub>_\\<^esub>)\" [80,100] 100) where\n  \"ith v i = fst v i\"\n\ndefinition\n  vlen :: \"vector \\<Rightarrow> nat\" where\n  \"vlen v = snd v\"\n\ntext {* Now to access the second element of some vector $v$ the syntax\nis $v_2$. *}\n\nsubsubsection {* Dot and Norm *}\n\ntext {* We now define the dot product and norm operations. *}\n\ndefinition\n  dot :: \"vector \\<Rightarrow> vector \\<Rightarrow> real\" (infixr \"\\<cdot>\" 60) where\n  \"dot a b = (\\<Sum>j\\<in>{1..(vlen a)}. a\\<^bsub>j\\<^esub>*b\\<^bsub>j\\<^esub>)\"\n\ndefinition\n  norm :: \"vector \\<Rightarrow> real\"                  (\"\\<parallel>_\\<parallel>\" 100) where\n  \"norm v = sqrt (\\<Sum>j\\<in>{1..(vlen v)}. v\\<^bsub>j\\<^esub>^2)\"\n\nnotation (HTML output)\n  \"norm\"  (\"||_||\" 100)\n\ntext {* Another definition of the norm is @{term \"\\<parallel>v\\<parallel> = sqrt\n(v\\<cdot>v)\"}. We show that our definition leads to this one. *}\n\nlemma norm_dot:\n \"\\<parallel>v\\<parallel> = sqrt (v\\<cdot>v)\"\nproof -\n  have \"sqrt (v\\<cdot>v) = sqrt (\\<Sum>j\\<in>{1..(vlen v)}. v\\<^bsub>j\\<^esub>*v\\<^bsub>j\\<^esub>)\" unfolding dot_def by simp\n  also with real_sq have \"\\<dots> = sqrt (\\<Sum>j\\<in>{1..(vlen v)}. v\\<^bsub>j\\<^esub>^2)\" by simp\n  also have \"\\<dots> = \\<parallel>v\\<parallel>\" unfolding norm_def by simp\n  finally show ?thesis ..\nqed\n\ntext {* A further important property is that the norm is never negative. *}\n\nlemma norm_pos:\n  \"\\<parallel>v\\<parallel> \\<ge> 0\"\nproof -\n  have \"\\<forall>j. v\\<^bsub>j\\<^esub>^2 \\<ge> 0\" unfolding ith_def by auto\n  hence \"\\<forall>j\\<in>{1..(vlen v)}. v\\<^bsub>j\\<^esub>^2 \\<ge> 0\" by simp\n  with setsum_nonneg have \"(\\<Sum>j\\<in>{1..(vlen v)}. v\\<^bsub>j\\<^esub>^2) \\<ge> 0\" .\n  with real_sqrt_ge_zero have \"sqrt (\\<Sum>j\\<in>{1..(vlen v)}. v\\<^bsub>j\\<^esub>^2) \\<ge> 0\" .\n  thus ?thesis unfolding norm_def .\nqed\n\ntext {* We now prove an intermediary lemma regarding double summation. *}\n\nlemma double_sum_aux:\n  fixes f::\"nat \\<Rightarrow> real\"\n  shows\n  \"(\\<Sum>k\\<in>{1..n}. (\\<Sum>j\\<in>{1..n}. f k * g j)) =\n   (\\<Sum>k\\<in>{1..n}. (\\<Sum>j\\<in>{1..n}. (f k * g j + f j * g k) / 2))\"\nproof -\n  have\n    \"2 * (\\<Sum>k\\<in>{1..n}. (\\<Sum>j\\<in>{1..n}. f k * g j)) =\n    (\\<Sum>k\\<in>{1..n}. (\\<Sum>j\\<in>{1..n}. f k * g j)) +\n    (\\<Sum>k\\<in>{1..n}. (\\<Sum>j\\<in>{1..n}. f k * g j))\"\n    by simp\n  also have\n    \"\\<dots> =\n    (\\<Sum>k\\<in>{1..n}. (\\<Sum>j\\<in>{1..n}. f k * g j)) +\n    (\\<Sum>k\\<in>{1..n}. (\\<Sum>j\\<in>{1..n}. f j * g k))\"\n    by (simp only: double_sum_equiv)\n  also have\n    \"\\<dots> =\n    (\\<Sum>k\\<in>{1..n}. (\\<Sum>j\\<in>{1..n}. f k * g j + f j * g k))\"\n    by (auto simp add: setsum.distrib)\n  finally have\n    \"2 * (\\<Sum>k\\<in>{1..n}. (\\<Sum>j\\<in>{1..n}. f k * g j)) =\n    (\\<Sum>k\\<in>{1..n}. (\\<Sum>j\\<in>{1..n}. f k * g j + f j * g k))\" .\n  hence\n    \"(\\<Sum>k\\<in>{1..n}. (\\<Sum>j\\<in>{1..n}. f k * g j)) =\n     (\\<Sum>k\\<in>{1..n}. (\\<Sum>j\\<in>{1..n}. (f k * g j + f j * g k)))*(1/2)\"\n    by auto\n  also have\n    \"\\<dots> =\n     (\\<Sum>k\\<in>{1..n}. (\\<Sum>j\\<in>{1..n}. (f k * g j + f j * g k)*(1/2)))\"\n    by (simp add: setsum_right_distrib mult.commute)\n  finally show ?thesis by (auto simp add: inverse_eq_divide)\nqed\n\ntext {* The final theorem can now be proven. It is a simple forward\nproof that uses properties of double summation and the preceding\nlemma.  *}\n\ntheorem CauchySchwarzReal:\n  fixes x::vector\n  assumes \"vlen x = vlen y\"\n  shows \"\\<bar>x\\<cdot>y\\<bar> \\<le> \\<parallel>x\\<parallel>*\\<parallel>y\\<parallel>\"\nproof -\n  have \"\\<bar>x\\<cdot>y\\<bar>^2 \\<le> (\\<parallel>x\\<parallel>*\\<parallel>y\\<parallel>)^2\"\n  proof -\n    txt {* We can rewrite the goal in the following form ...*}\n    have \"(\\<parallel>x\\<parallel>*\\<parallel>y\\<parallel>)^2 - \\<bar>x\\<cdot>y\\<bar>^2 \\<ge> 0\"\n    proof -\n      obtain n where nx: \"n = vlen x\" by simp\n      with `vlen x = vlen y` have ny: \"n = vlen y\" by simp\n      {\n        txt {* Some preliminary simplification rules. *}\n        have \"\\<forall>j\\<in>{1..n}. x\\<^bsub>j\\<^esub>^2 \\<ge> 0\" by simp\n        hence \"(\\<Sum>j\\<in>{1..n}. x\\<^bsub>j\\<^esub>^2) \\<ge> 0\" by (rule setsum_nonneg)\n        hence xp: \"(sqrt (\\<Sum>j\\<in>{1..n}. x\\<^bsub>j\\<^esub>^2))^2 = (\\<Sum>j\\<in>{1..n}. x\\<^bsub>j\\<^esub>^2)\"\n          by (rule real_sqrt_pow2)\n\n        have \"\\<forall>j\\<in>{1..n}. y\\<^bsub>j\\<^esub>^2 \\<ge> 0\" by simp\n        hence \"(\\<Sum>j\\<in>{1..n}. y\\<^bsub>j\\<^esub>^2) \\<ge> 0\" by (rule setsum_nonneg)\n        hence yp: \"(sqrt (\\<Sum>j\\<in>{1..n}. y\\<^bsub>j\\<^esub>^2))^2 = (\\<Sum>j\\<in>{1..n}. y\\<^bsub>j\\<^esub>^2)\"\n          by (rule real_sqrt_pow2)\n\n        txt {* The main result of this section is that @{text\n        \"(\\<parallel>x\\<parallel>*\\<parallel>y\\<parallel>)^2\"} can be written as a double sum. *}\n        have\n          \"(\\<parallel>x\\<parallel>*\\<parallel>y\\<parallel>)^2 = \\<parallel>x\\<parallel>^2 * \\<parallel>y\\<parallel>^2\"\n          by (simp add: real_sq_exp)\n        also from nx ny have\n          \"\\<dots> = (sqrt (\\<Sum>j\\<in>{1..n}. x\\<^bsub>j\\<^esub>^2))^2 * (sqrt (\\<Sum>j\\<in>{1..n}. y\\<^bsub>j\\<^esub>^2))^2\"\n          unfolding norm_def by auto\n        also from xp yp have\n          \"\\<dots> = (\\<Sum>j\\<in>{1..n}. x\\<^bsub>j\\<^esub>^2)*(\\<Sum>j\\<in>{1..n}. y\\<^bsub>j\\<^esub>^2)\"\n          by simp\n        also from setsum_product have\n          \"\\<dots> = (\\<Sum>k\\<in>{1..n}. (\\<Sum>j\\<in>{1..n}. (x\\<^bsub>k\\<^esub>^2)*(y\\<^bsub>j\\<^esub>^2)))\" .\n        finally have\n          \"(\\<parallel>x\\<parallel>*\\<parallel>y\\<parallel>)^2 = (\\<Sum>k\\<in>{1..n}. (\\<Sum>j\\<in>{1..n}. (x\\<^bsub>k\\<^esub>^2)*(y\\<^bsub>j\\<^esub>^2)))\" .\n      }\n      moreover\n      {\n        txt {* We also show that @{text \"\\<bar>x\\<cdot>y\\<bar>^2\"} can be expressed as a double sum.*}\n        have\n          \"\\<bar>x\\<cdot>y\\<bar>^2 = (x\\<cdot>y)^2\"\n          by simp\n        also from nx have\n          \"\\<dots> = (\\<Sum>j\\<in>{1..n}. x\\<^bsub>j\\<^esub>*y\\<^bsub>j\\<^esub>)^2\"\n          unfolding dot_def by simp\n        also from real_sq have\n          \"\\<dots> = (\\<Sum>j\\<in>{1..n}. x\\<^bsub>j\\<^esub>*y\\<^bsub>j\\<^esub>)*(\\<Sum>j\\<in>{1..n}. x\\<^bsub>j\\<^esub>*y\\<^bsub>j\\<^esub>)\"\n          by simp\n        also from setsum_product have\n          \"\\<dots> = (\\<Sum>k\\<in>{1..n}. (\\<Sum>j\\<in>{1..n}. (x\\<^bsub>k\\<^esub>*y\\<^bsub>k\\<^esub>)*(x\\<^bsub>j\\<^esub>*y\\<^bsub>j\\<^esub>)))\" .\n        finally have\n          \"\\<bar>x\\<cdot>y\\<bar>^2 = (\\<Sum>k\\<in>{1..n}. (\\<Sum>j\\<in>{1..n}. (x\\<^bsub>k\\<^esub>*y\\<^bsub>k\\<^esub>)*(x\\<^bsub>j\\<^esub>*y\\<^bsub>j\\<^esub>)))\" .\n      }\n      txt {* We now manipulate the double sum expressions to get the\n      required inequality. *}\n      ultimately have\n        \"(\\<parallel>x\\<parallel>*\\<parallel>y\\<parallel>)^2 - \\<bar>x\\<cdot>y\\<bar>^2 =\n         (\\<Sum>k\\<in>{1..n}. (\\<Sum>j\\<in>{1..n}. (x\\<^bsub>k\\<^esub>^2)*(y\\<^bsub>j\\<^esub>^2))) -\n         (\\<Sum>k\\<in>{1..n}. (\\<Sum>j\\<in>{1..n}. (x\\<^bsub>k\\<^esub>*y\\<^bsub>k\\<^esub>)*(x\\<^bsub>j\\<^esub>*y\\<^bsub>j\\<^esub>)))\"\n        by simp\n      also have\n        \"\\<dots> =\n         (\\<Sum>k\\<in>{1..n}. (\\<Sum>j\\<in>{1..n}. ((x\\<^bsub>k\\<^esub>^2*y\\<^bsub>j\\<^esub>^2) + (x\\<^bsub>j\\<^esub>^2*y\\<^bsub>k\\<^esub>^2))/2)) -\n         (\\<Sum>k\\<in>{1..n}. (\\<Sum>j\\<in>{1..n}. (x\\<^bsub>k\\<^esub>*y\\<^bsub>k\\<^esub>)*(x\\<^bsub>j\\<^esub>*y\\<^bsub>j\\<^esub>)))\"\n        by (simp only: double_sum_aux)\n      also have\n        \"\\<dots> =\n         (\\<Sum>k\\<in>{1..n}.  (\\<Sum>j\\<in>{1..n}. ((x\\<^bsub>k\\<^esub>^2*y\\<^bsub>j\\<^esub>^2) + (x\\<^bsub>j\\<^esub>^2*y\\<^bsub>k\\<^esub>^2))/2 - (x\\<^bsub>k\\<^esub>*y\\<^bsub>k\\<^esub>)*(x\\<^bsub>j\\<^esub>*y\\<^bsub>j\\<^esub>)))\"\n        by (auto simp add: setsum_subtractf)\n      also have\n        \"\\<dots> =\n         (\\<Sum>k\\<in>{1..n}.  (\\<Sum>j\\<in>{1..n}. (inverse 2)*2*\n         (((x\\<^bsub>k\\<^esub>^2*y\\<^bsub>j\\<^esub>^2) + (x\\<^bsub>j\\<^esub>^2*y\\<^bsub>k\\<^esub>^2))*(1/2) - (x\\<^bsub>k\\<^esub>*y\\<^bsub>k\\<^esub>)*(x\\<^bsub>j\\<^esub>*y\\<^bsub>j\\<^esub>))))\"\n        by auto\n      also have\n        \"\\<dots> =\n         (\\<Sum>k\\<in>{1..n}.  (\\<Sum>j\\<in>{1..n}. (inverse 2)*(2*\n        (((x\\<^bsub>k\\<^esub>^2*y\\<^bsub>j\\<^esub>^2) + (x\\<^bsub>j\\<^esub>^2*y\\<^bsub>k\\<^esub>^2))*(1/2) - (x\\<^bsub>k\\<^esub>*y\\<^bsub>k\\<^esub>)*(x\\<^bsub>j\\<^esub>*y\\<^bsub>j\\<^esub>)))))\"\n        by (simp only: mult.assoc)\n      also have\n        \"\\<dots> =\n         (\\<Sum>k\\<in>{1..n}.  (\\<Sum>j\\<in>{1..n}. (inverse 2)*\n        ((((x\\<^bsub>k\\<^esub>^2*y\\<^bsub>j\\<^esub>^2) + (x\\<^bsub>j\\<^esub>^2*y\\<^bsub>k\\<^esub>^2))*2*(inverse 2) - 2*(x\\<^bsub>k\\<^esub>*y\\<^bsub>k\\<^esub>)*(x\\<^bsub>j\\<^esub>*y\\<^bsub>j\\<^esub>)))))\"\n        by (auto simp add: distrib_right mult.assoc ac_simps)\n      also have\n        \"\\<dots> =\n        (\\<Sum>k\\<in>{1..n}.  (\\<Sum>j\\<in>{1..n}. (inverse 2)*\n        ((((x\\<^bsub>k\\<^esub>^2*y\\<^bsub>j\\<^esub>^2) + (x\\<^bsub>j\\<^esub>^2*y\\<^bsub>k\\<^esub>^2)) - 2*(x\\<^bsub>k\\<^esub>*y\\<^bsub>k\\<^esub>)*(x\\<^bsub>j\\<^esub>*y\\<^bsub>j\\<^esub>)))))\"\n        by (simp only: mult.assoc, simp)\n      also have\n        \"\\<dots> =\n         (inverse 2)*(\\<Sum>k\\<in>{1..n}. (\\<Sum>j\\<in>{1..n}.\n         (((x\\<^bsub>k\\<^esub>^2*y\\<^bsub>j\\<^esub>^2) + (x\\<^bsub>j\\<^esub>^2*y\\<^bsub>k\\<^esub>^2)) - 2*(x\\<^bsub>k\\<^esub>*y\\<^bsub>k\\<^esub>)*(x\\<^bsub>j\\<^esub>*y\\<^bsub>j\\<^esub>))))\"\n        by (simp only: setsum_right_distrib)\n      also have\n        \"\\<dots> =\n         (inverse 2)*(\\<Sum>k\\<in>{1..n}. (\\<Sum>j\\<in>{1..n}. (x\\<^bsub>k\\<^esub>*y\\<^bsub>j\\<^esub> - x\\<^bsub>j\\<^esub>*y\\<^bsub>k\\<^esub>)^2))\"\n        by (simp only: power2_diff real_sq_exp, auto simp add: ac_simps)\n      also have \"\\<dots> \\<ge> 0\"\n      proof -\n        {\n          fix k::nat\n          have \"\\<forall>j\\<in>{1..n}. (x\\<^bsub>k\\<^esub>*y\\<^bsub>j\\<^esub> - x\\<^bsub>j\\<^esub>*y\\<^bsub>k\\<^esub>)^2 \\<ge> 0\" by simp\n          hence \"(\\<Sum>j\\<in>{1..n}. (x\\<^bsub>k\\<^esub>*y\\<^bsub>j\\<^esub> - x\\<^bsub>j\\<^esub>*y\\<^bsub>k\\<^esub>)^2) \\<ge> 0\" by (rule setsum_nonneg)\n        }\n        hence \"\\<forall>k\\<in>{1..n}. (\\<Sum>j\\<in>{1..n}. (x\\<^bsub>k\\<^esub>*y\\<^bsub>j\\<^esub> - x\\<^bsub>j\\<^esub>*y\\<^bsub>k\\<^esub>)^2) \\<ge> 0\" by simp\n        hence \"(\\<Sum>k\\<in>{1..n}. (\\<Sum>j\\<in>{1..n}. (x\\<^bsub>k\\<^esub>*y\\<^bsub>j\\<^esub> - x\\<^bsub>j\\<^esub>*y\\<^bsub>k\\<^esub>)^2)) \\<ge> 0\"\n          by (rule setsum_nonneg)\n        thus ?thesis by simp\n      qed\n      finally show \"(\\<parallel>x\\<parallel>*\\<parallel>y\\<parallel>)^2 - \\<bar>x\\<cdot>y\\<bar>^2 \\<ge> 0\" .\n    qed\n    thus ?thesis by simp\n  qed\n  moreover have \"0 \\<le> \\<parallel>x\\<parallel>*\\<parallel>y\\<parallel>\"\n    by (auto simp add: norm_pos)\n  ultimately show ?thesis by (rule power2_le_imp_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/Cauchy/CauchySchwarz.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297941266013, "lm_q2_score": 0.828938806208442, "lm_q1q2_score": 0.7464840924984388}}
{"text": "(* Title:      Kleene Algebra\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\nheader {* Omega Algebras *}\n\ntheory Omega_Algebra\nimports Kleene_Algebra\nbegin\n\ntext {*\n\\emph{Omega algebras}~\\cite{cohen00omega} extend Kleene algebras by an\n$\\omega$-operation that axiomatizes infinite iteration (just like the\nKleene star axiomatizes finite iteration).\n*}\n\n\nsubsection {* Left Omega Algebras *}\n\ntext {*\nIn this section we consider \\emph{left omega algebras}, i.e., omega\nalgebras based on left Kleene algebras. Surprisingly, we are still\nlooking for statements mentioning~$\\omega$ that are true in omega\nalgebras, but do not already hold in left omega algebras.\n*}\n\nclass left_omega_algebra = left_kleene_algebra_zero + omega_op +\n  assumes omega_unfold: \"x\\<^sup>\\<omega> \\<le> x \\<cdot> x\\<^sup>\\<omega>\"\n  and omega_coinduct: \"y \\<le> z + x \\<cdot> y \\<longrightarrow> y \\<le> x\\<^sup>\\<omega> + x\\<^sup>\\<star> \\<cdot> z\"\nbegin\n\ntext {* First we prove some variants of the coinduction axiom. *}\n\nlemma omega_coinduct_var1: \"y \\<le> 1 + x \\<cdot> y \\<longrightarrow> y \\<le> x\\<^sup>\\<omega> + x\\<^sup>\\<star>\"\n  by (metis mult_oner omega_coinduct)\n\nlemma  omega_coinduct_var2: \"y \\<le> x \\<cdot> y \\<longrightarrow> y \\<le> x\\<^sup>\\<omega>\"\n  by (metis add.commute add_zero_l annir omega_coinduct)\n\nlemma omega_coinduct_eq: \"y = z + x \\<cdot> y \\<longrightarrow> y \\<le> x\\<^sup>\\<omega> + x\\<^sup>\\<star> \\<cdot> z\"\n  by (metis eq_refl omega_coinduct)\n\nlemma omega_coinduct_eq_var1: \"y = 1 + x \\<cdot> y \\<longrightarrow> y \\<le> x\\<^sup>\\<omega> + x\\<^sup>\\<star>\"\n  by (metis eq_refl omega_coinduct_var1)\n\nlemma  omega_coinduct_eq_var2: \"y = x \\<cdot> y \\<longrightarrow> y \\<le> x\\<^sup>\\<omega>\"\n  by (metis eq_refl omega_coinduct_var2)\n\nlemma \"y = x \\<cdot> y + z \\<longrightarrow> y = x\\<^sup>\\<star> \\<cdot> z + x\\<^sup>\\<omega>\"\n  nitpick [expect=genuine] -- \"2-element counterexample\"\noops\n\nlemma \"y = 1 + x \\<cdot> y \\<longrightarrow> y = x\\<^sup>\\<omega> + x\\<^sup>\\<star>\"\n  nitpick [expect=genuine] -- \"3-element counterexample\"\noops\n\nlemma \"y = x \\<cdot> y \\<longrightarrow> y = x\\<^sup>\\<omega>\"\n  nitpick [expect=genuine] -- \"2-element counterexample\"\noops\n\ntext {* Next we strengthen the unfold law to an equation. *}\n\nlemma omega_unfold_eq [simp]: \"x \\<cdot> x\\<^sup>\\<omega> = x\\<^sup>\\<omega>\"\nproof (rule antisym)\n  have \"x \\<cdot> x\\<^sup>\\<omega> \\<le> x \\<cdot> x \\<cdot> x\\<^sup>\\<omega>\"\n    by (metis mult.assoc mult_isol omega_unfold)\n  thus \"x \\<cdot> x\\<^sup>\\<omega> \\<le> x\\<^sup>\\<omega>\"\n    by (metis mult.assoc omega_coinduct_var2)\n  show  \"x\\<^sup>\\<omega> \\<le> x \\<cdot> x\\<^sup>\\<omega>\"\n    by (fact omega_unfold)\nqed\n\nlemma omega_unfold_var: \"z + x \\<cdot> x\\<^sup>\\<omega> \\<le> x\\<^sup>\\<omega> + x\\<^sup>\\<star> \\<cdot> z\"\n  by (metis add_lub add_ub1 omega_coinduct omega_unfold_eq)\n\nlemma \"z + x \\<cdot> x\\<^sup>\\<omega> = x\\<^sup>\\<omega> + x\\<^sup>\\<star> \\<cdot> z\"\n  nitpick [expect=genuine] -- \"4-element counterexample\"\noops\n\ntext {* We now prove subdistributivity and isotonicity of omega. *}\n\nlemma omega_subdist: \"x\\<^sup>\\<omega> \\<le> (x + y)\\<^sup>\\<omega>\"\nproof -\n  have \"x\\<^sup>\\<omega> \\<le> (x + y) \\<cdot> x\\<^sup>\\<omega>\"\n    by (metis add_ub1 mult_isor omega_unfold_eq)\n  thus ?thesis\n    by (metis omega_coinduct_var2)\nqed\n\nlemma omega_iso: \"x \\<le> y \\<longrightarrow> x\\<^sup>\\<omega> \\<le> y\\<^sup>\\<omega>\"\n  by (metis less_eq_def omega_subdist)\n\nlemma omega_subdist_var: \"x\\<^sup>\\<omega> + y\\<^sup>\\<omega> \\<le> (x + y)\\<^sup>\\<omega>\"\n  by (metis add.commute add_lub omega_subdist)\n\nlemma zero_omega [simp]: \"0\\<^sup>\\<omega> = 0\"\n  by (metis annil omega_unfold_eq)\n\ntext {* The next lemma is another variant of omega unfold *}\n\nlemma star_omega_1 [simp]: \"x\\<^sup>\\<star> \\<cdot> x\\<^sup>\\<omega> = x\\<^sup>\\<omega>\"\nproof (rule antisym)\n  have \"x \\<cdot> x\\<^sup>\\<omega> \\<le> x\\<^sup>\\<omega>\"\n    by (metis eq_refl omega_unfold_eq)\n  thus \"x\\<^sup>\\<star> \\<cdot> x\\<^sup>\\<omega> \\<le> x\\<^sup>\\<omega>\"\n    by (metis star_inductl_var)\n  show \"x\\<^sup>\\<omega> \\<le> x\\<^sup>\\<star> \\<cdot> x\\<^sup>\\<omega>\"\n    by (metis star_ref mult_isor mult_onel)\nqed\n\ntext {* The next lemma says that~@{term \"1\\<^sup>\\<omega>\"} is the maximal element\nof omega algebra. We therefore baptise it~$\\top$. *}\n\nlemma max_element: \"x \\<le> 1\\<^sup>\\<omega>\"\n  by (metis eq_refl mult_onel omega_coinduct_var2)\n\ndefinition top (\"\\<top>\")\n  where \"\\<top> = 1\\<^sup>\\<omega>\"\n\nlemma star_omega_3 [simp]: \"(x\\<^sup>\\<star>)\\<^sup>\\<omega> = \\<top>\"\nproof -\n  have \"1 \\<le> x\\<^sup>\\<star>\"\n    by (fact star_ref)\n  hence \"\\<top> \\<le> (x\\<^sup>\\<star>)\\<^sup>\\<omega>\"\n    by (metis omega_iso top_def)\n  thus ?thesis\n    by (metis eq_iff max_element top_def)\nqed\n\ntext {* The following lemma is strange since it is counterintuitive\nthat one should be able to append something after an infinite\niteration. *}\n\nlemma omega_1: \"x\\<^sup>\\<omega> \\<cdot> y \\<le> x\\<^sup>\\<omega>\"\nproof -\n  have \"x\\<^sup>\\<omega> \\<cdot> y \\<le> x \\<cdot> x\\<^sup>\\<omega> \\<cdot> y\"\n    by (metis eq_refl omega_unfold_eq)\n  thus ?thesis\n    by (metis mult.assoc omega_coinduct_var2)\nqed\n\nlemma \"x\\<^sup>\\<omega> \\<cdot> y = x\\<^sup>\\<omega>\"\n  nitpick [expect=genuine] -- \"2-element counterexample\"\noops\n\nlemma omega_sup_id: \"1 \\<le> y \\<longrightarrow> x\\<^sup>\\<omega> \\<cdot> y = x\\<^sup>\\<omega>\"\n  by (metis eq_iff mult_isol mult_oner omega_1)\n\nlemma omega_top [simp]: \"x\\<^sup>\\<omega> \\<cdot> \\<top> = x\\<^sup>\\<omega>\"\n  by (metis max_element omega_sup_id top_def)\n\nlemma supid_omega: \"1 \\<le> x \\<longrightarrow> x\\<^sup>\\<omega> = \\<top>\"\n  by (metis eq_iff max_element omega_iso top_def)\n\nlemma \"x\\<^sup>\\<omega> = \\<top> \\<longrightarrow> 1 \\<le> x\"\n  nitpick [expect=genuine] -- \"4-element counterexample\"\noops\n\ntext {* Next we prove a simulation law for the omega operation *}\n\nlemma omega_simulation: \"z \\<cdot> x \\<le> y \\<cdot> z \\<longrightarrow> z \\<cdot> x\\<^sup>\\<omega> \\<le> y\\<^sup>\\<omega>\"\nproof\n  assume \"z \\<cdot> x \\<le> y \\<cdot> z\"\n  also have \"z \\<cdot> x\\<^sup>\\<omega> = z \\<cdot> x \\<cdot> x\\<^sup>\\<omega>\"\n    by (metis mult.assoc omega_unfold_eq)\n  moreover have \"... \\<le> y \\<cdot> z \\<cdot> x\\<^sup>\\<omega>\"\n    by (metis mult_isor calculation)\n  thus \"z \\<cdot> x\\<^sup>\\<omega> \\<le> y\\<^sup>\\<omega>\"\n    by (metis calculation mult.assoc omega_coinduct_var2)\nqed\n\nlemma \"z \\<cdot> x \\<le> y \\<cdot> z \\<longrightarrow> z \\<cdot> x\\<^sup>\\<omega> \\<le> y\\<^sup>\\<omega> \\<cdot> z\"\n  nitpick [expect=genuine] -- \"4-element counterexample\"\noops\n\nlemma \"y \\<cdot> z  \\<le> z \\<cdot> x \\<longrightarrow> y\\<^sup>\\<omega> \\<le> z \\<cdot> x\\<^sup>\\<omega>\"\n  nitpick [expect=genuine] -- \"2-element counterexample\"\noops\n\nlemma \"y \\<cdot> z  \\<le> z \\<cdot> x \\<longrightarrow> y\\<^sup>\\<omega> \\<cdot> z \\<le> x\\<^sup>\\<omega>\"\n  nitpick [expect=genuine] -- \"4-element counterexample\"\noops\n\ntext {* Next we prove transitivity of omega elements. *}\n\nlemma omega_trans: \"x\\<^sup>\\<omega> \\<cdot> x\\<^sup>\\<omega> \\<le> x\\<^sup>\\<omega>\"\n  by (fact omega_1)\n\nlemma omega_omega: \"(x\\<^sup>\\<omega>)\\<^sup>\\<omega> \\<le> x\\<^sup>\\<omega>\"\n  by (metis omega_1 omega_unfold_eq)\n\n(*\nlemma \"x\\<^sup>\\<omega> \\<cdot> x\\<^sup>\\<omega> = x\\<^sup>\\<omega>\"\nnitpick -- \"no proof, no counterexample\"\n\nlemma \"(x\\<^sup>\\<omega>)\\<^sup>\\<omega> = x\\<^sup>\\<omega>\"\nnitpick -- \"no proof, no counterexample\"\n*)\n\ntext {* The next lemmas are axioms of Wagner's complete axiomatisation\nfor omega-regular languages~\\cite{Wagner77omega}, but in a slightly\ndifferent setting.  *}\n\nlemma wagner_1 [simp]: \"(x \\<cdot> x\\<^sup>\\<star>)\\<^sup>\\<omega> = x\\<^sup>\\<omega>\"\nproof (rule antisym)\n  have \"(x \\<cdot> x\\<^sup>\\<star>)\\<^sup>\\<omega> = x \\<cdot> x\\<^sup>\\<star> \\<cdot> x \\<cdot> x\\<^sup>\\<star> \\<cdot> (x \\<cdot> x\\<^sup>\\<star>)\\<^sup>\\<omega>\"\n    by (metis mult.assoc omega_unfold_eq)\n  also have \"... = x \\<cdot> x \\<cdot> x\\<^sup>\\<star> \\<cdot> x\\<^sup>\\<star> \\<cdot> (x \\<cdot> x\\<^sup>\\<star>)\\<^sup>\\<omega>\"\n    by (metis mult.assoc star_slide_var)\n  also have \"... = x \\<cdot> x \\<cdot> x\\<^sup>\\<star> \\<cdot> (x \\<cdot> x\\<^sup>\\<star>)\\<^sup>\\<omega>\"\n    by (metis mult.assoc star_trans_eq)\n  also have \"... = x \\<cdot> (x \\<cdot> x\\<^sup>\\<star>)\\<^sup>\\<omega>\"\n    by (metis mult.assoc omega_unfold_eq)\n  thus \"(x \\<cdot> x\\<^sup>\\<star>)\\<^sup>\\<omega> \\<le> x\\<^sup>\\<omega>\"\n    by (metis calculation eq_refl omega_coinduct_var2)\n   show \"x\\<^sup>\\<omega> \\<le> (x \\<cdot> x\\<^sup>\\<star>)\\<^sup>\\<omega>\"\n    by (metis mult_isol mult_oner omega_iso star_ref)\nqed\n\nlemma wagner_2_var: \"x \\<cdot> (y \\<cdot> x)\\<^sup>\\<omega> \\<le> (x \\<cdot> y)\\<^sup>\\<omega>\"\nproof -\n  have \"x \\<cdot> y \\<cdot> x \\<le> x \\<cdot> y \\<cdot> x\"\n    by auto\n  thus \"x \\<cdot> (y \\<cdot> x)\\<^sup>\\<omega> \\<le> (x \\<cdot> y)\\<^sup>\\<omega>\"\n    by (metis mult.assoc omega_simulation)\nqed\n\nlemma wagner_2 [simp]: \"x \\<cdot> (y \\<cdot> x)\\<^sup>\\<omega> = (x \\<cdot> y)\\<^sup>\\<omega>\"\nproof (rule antisym)\n  show \"x \\<cdot> (y \\<cdot> x)\\<^sup>\\<omega> \\<le> (x \\<cdot> y)\\<^sup>\\<omega>\"\n    by (rule wagner_2_var)\n  have \"(x \\<cdot> y)\\<^sup>\\<omega> = x \\<cdot> y \\<cdot> (x \\<cdot> y)\\<^sup>\\<omega>\"\n    by (metis omega_unfold_eq)\n  thus \"(x \\<cdot> y)\\<^sup>\\<omega> \\<le> x \\<cdot> (y \\<cdot> x)\\<^sup>\\<omega>\"\n    by (metis mult.assoc mult_isol wagner_2_var)\nqed\n\ntext {*\nThis identity is called~(A8) in Wagner's paper.\n*}\n\nlemma wagner_3:\nassumes \"x \\<cdot> (x + y)\\<^sup>\\<omega> + z = (x + y)\\<^sup>\\<omega>\"\nshows \"(x + y)\\<^sup>\\<omega> = x\\<^sup>\\<omega> + x\\<^sup>\\<star> \\<cdot> z\"\nproof (rule antisym)\n  show  \"(x + y)\\<^sup>\\<omega> \\<le> x\\<^sup>\\<omega> + x\\<^sup>\\<star> \\<cdot> z\"\n    by (metis add.commute assms omega_coinduct_eq)\n  have \"x\\<^sup>\\<star> \\<cdot> z \\<le> (x + y)\\<^sup>\\<omega>\"\n    by (metis add.commute assms star_inductl_eq)\n  thus \"x\\<^sup>\\<omega> + x\\<^sup>\\<star> \\<cdot> z \\<le> (x + y)\\<^sup>\\<omega>\"\n    by (metis add_lub omega_subdist)\nqed\n\ntext {*\nThis identity is called~(R4) in Wagner's paper.\n*}\n\nlemma wagner_1_var [simp]: \"(x\\<^sup>\\<star> \\<cdot> x)\\<^sup>\\<omega> = x\\<^sup>\\<omega>\"\n  by (metis star_slide_var wagner_1)\n\nlemma star_omega_4 [simp]: \"(x\\<^sup>\\<omega>)\\<^sup>\\<star> = 1 + x\\<^sup>\\<omega>\"\nproof (rule antisym)\n  have \"(x\\<^sup>\\<omega>)\\<^sup>\\<star> = 1 + x\\<^sup>\\<omega> \\<cdot> (x\\<^sup>\\<omega>)\\<^sup>\\<star>\"\n    by simp\n  also have \"... \\<le> 1 + x\\<^sup>\\<omega> \\<cdot> \\<top>\"\n    by (metis add_iso_var eq_refl omega_1 omega_top)\n  thus \"(x\\<^sup>\\<omega>)\\<^sup>\\<star> \\<le> 1 + x\\<^sup>\\<omega>\"\n    by (metis calculation omega_top)\n  show \"1 + x\\<^sup>\\<omega> \\<le> (x\\<^sup>\\<omega>)\\<^sup>\\<star>\"\n    by (metis star2 star_ext)\nqed\n\nlemma star_omega_5 [simp]: \"x\\<^sup>\\<omega> \\<cdot> (x\\<^sup>\\<omega>)\\<^sup>\\<star> = x\\<^sup>\\<omega>\"\nproof (rule antisym)\n  show \"x\\<^sup>\\<omega> \\<cdot> (x\\<^sup>\\<omega>)\\<^sup>\\<star> \\<le> x\\<^sup>\\<omega>\"\n    by (rule omega_1)\n  show \"x\\<^sup>\\<omega> \\<le> x\\<^sup>\\<omega> \\<cdot> (x\\<^sup>\\<omega>)\\<^sup>\\<star>\"\n    by (metis mult_oner star_ref mult_isol)\nqed\n\ntext {* The next law shows how omegas below a sum can be unfolded. *}\n\nlemma omega_sum_unfold: \"x\\<^sup>\\<omega> + x\\<^sup>\\<star> \\<cdot> y \\<cdot> (x + y)\\<^sup>\\<omega> = (x + y)\\<^sup>\\<omega>\"\nproof -\n  have \"(x + y)\\<^sup>\\<omega> = x \\<cdot> (x + y)\\<^sup>\\<omega> + y \\<cdot> (x+y)\\<^sup>\\<omega>\"\n    by (metis distrib_right omega_unfold_eq)\n  thus ?thesis\n    by (metis mult.assoc wagner_3)\nqed\n\ntext {*\nThe next two lemmas apply induction and coinduction to this law.\n*}\n\nlemma omega_sum_unfold_coind: \"(x + y)\\<^sup>\\<omega> \\<le> (x\\<^sup>\\<star> \\<cdot> y)\\<^sup>\\<omega> + (x\\<^sup>\\<star> \\<cdot> y)\\<^sup>\\<star> \\<cdot> x\\<^sup>\\<omega>\"\n  by (metis omega_coinduct_eq omega_sum_unfold)\n\nlemma omega_sum_unfold_ind: \"(x\\<^sup>\\<star> \\<cdot> y)\\<^sup>\\<star> \\<cdot> x\\<^sup>\\<omega> \\<le> (x + y)\\<^sup>\\<omega>\"\n  by (metis omega_sum_unfold star_inductl_eq)\n\nlemma wagner_1_gen: \"(x \\<cdot> y\\<^sup>\\<star>)\\<^sup>\\<omega> \\<le> (x + y)\\<^sup>\\<omega>\"\nproof -\n  have \"(x \\<cdot> y\\<^sup>\\<star>)\\<^sup>\\<omega> \\<le> ((x + y) \\<cdot> (x + y)\\<^sup>\\<star>)\\<^sup>\\<omega>\"\n    by (metis add_ub1 add_ub2 mult_isol_var omega_iso star_iso)\n  thus ?thesis\n    by (metis wagner_1)\nqed\n\nlemma wagner_1_var_gen: \"(x\\<^sup>\\<star> \\<cdot> y)\\<^sup>\\<omega> \\<le> (x + y)\\<^sup>\\<omega>\"\nproof -\n  have \"(x\\<^sup>\\<star> \\<cdot> y)\\<^sup>\\<omega> = x\\<^sup>\\<star> \\<cdot> (y \\<cdot> x\\<^sup>\\<star>)\\<^sup>\\<omega>\"\n    by (metis wagner_2)\n  also have \"... \\<le> x\\<^sup>\\<star> \\<cdot> (x + y)\\<^sup>\\<omega>\"\n    by (metis add.commute mult_isol wagner_1_gen)\n  also have \"... \\<le> (x + y)\\<^sup>\\<star> \\<cdot> (x + y)\\<^sup>\\<omega>\"\n    by (metis add_ub1 mult_isor star_iso)\n  thus ?thesis\n    by (metis calculation order_trans star_omega_1)\nqed\n\ntext {* The next lemma is a variant of the denest law for the star at\nthe level of omega. *}\n\nlemma omega_denest [simp]: \"(x + y)\\<^sup>\\<omega> = (x\\<^sup>\\<star> \\<cdot> y)\\<^sup>\\<omega> + (x\\<^sup>\\<star> \\<cdot> y)\\<^sup>\\<star> \\<cdot> x\\<^sup>\\<omega>\"\nproof (rule antisym)\n  show \"(x + y)\\<^sup>\\<omega> \\<le> (x\\<^sup>\\<star> \\<cdot> y)\\<^sup>\\<omega> + (x\\<^sup>\\<star> \\<cdot> y)\\<^sup>\\<star> \\<cdot> x\\<^sup>\\<omega>\"\n    by (rule omega_sum_unfold_coind)\n  have \"(x\\<^sup>\\<star> \\<cdot> y)\\<^sup>\\<omega> \\<le>  (x + y)\\<^sup>\\<omega>\"\n    by (rule wagner_1_var_gen)\n  hence \"(x\\<^sup>\\<star> \\<cdot> y)\\<^sup>\\<star> \\<cdot> x\\<^sup>\\<omega> \\<le> (x + y)\\<^sup>\\<omega>\"\n    by (metis omega_sum_unfold_ind)\n  thus \"(x\\<^sup>\\<star> \\<cdot> y)\\<^sup>\\<omega> + (x\\<^sup>\\<star> \\<cdot> y)\\<^sup>\\<star> \\<cdot> x\\<^sup>\\<omega> \\<le> (x + y)\\<^sup>\\<omega>\"\n    by (metis add_lub wagner_1_var_gen)\nqed\n\ntext {* The next lemma yields a separation theorem for infinite\niteration in the presence of a quasicommutation property. A\nnondeterministic loop over~@{term x} and~@{term y} can be refined into\nseparate infinite loops over~@{term x} and~@{term y}.  *}\n\nlemma omega_sum_refine:\n  assumes \"y \\<cdot> x \\<le> x \\<cdot> (x + y)\\<^sup>\\<star>\"\n  shows \"(x + y)\\<^sup>\\<omega> = x\\<^sup>\\<omega> + x\\<^sup>\\<star> \\<cdot> y\\<^sup>\\<omega>\"\nproof (rule antisym)\n  have \"y\\<^sup>\\<star> \\<cdot> x \\<le> x \\<cdot> (x + y)\\<^sup>\\<star>\"\n    by (metis assms quasicomm_var)\n  also have \"(x + y)\\<^sup>\\<omega> = y\\<^sup>\\<omega> + y\\<^sup>\\<star> \\<cdot> x \\<cdot> (x + y)\\<^sup>\\<omega>\"\n    by (metis add.commute omega_sum_unfold)\n  moreover have \"... \\<le> x \\<cdot> (x + y)\\<^sup>\\<star> \\<cdot> (x + y)\\<^sup>\\<omega> + y\\<^sup>\\<omega>\"\n    by (metis add_iso add_lub add_ub2 calculation(1) mult_isor)\n  moreover have \"... \\<le> x \\<cdot> (x + y)\\<^sup>\\<omega> + y\\<^sup>\\<omega>\"\n    by (metis mult.assoc order_refl star_omega_1)\n  thus \"(x + y)\\<^sup>\\<omega> \\<le> x\\<^sup>\\<omega> + x\\<^sup>\\<star> \\<cdot> y\\<^sup>\\<omega>\"\n    by (metis add.commute calculation mult.assoc omega_coinduct star_omega_1)\n  have \"x\\<^sup>\\<omega> \\<le> (x + y)\\<^sup>\\<omega>\"\n    by (rule omega_subdist)\n  moreover have \"x\\<^sup>\\<star> \\<cdot> y\\<^sup>\\<omega> \\<le> x\\<^sup>\\<star> \\<cdot> (x + y)\\<^sup>\\<omega>\"\n    by (metis calculation add_ub1 mult_isol)\n  moreover have\"... \\<le> (x + y)\\<^sup>\\<star> \\<cdot> (x + y)\\<^sup>\\<omega>\"\n    by (metis add_ub1 star_iso mult_isor)\n  moreover have \"... = (x + y)\\<^sup>\\<omega>\"\n     by (rule star_omega_1)\n   thus \"x\\<^sup>\\<omega> + x\\<^sup>\\<star> \\<cdot> y\\<^sup>\\<omega> \\<le> (x + y)\\<^sup>\\<omega>\"\n     by (metis add.commute add_lub calculation mult_isol omega_subdist order_trans star_omega_1)\nqed\n\ntext {* The following theorem by Bachmair and\nDershowitz~\\cite{bachmair86commutation} is a corollary. *}\n\nlemma bachmair_dershowitz:\n  assumes \"y \\<cdot> x \\<le> x \\<cdot> (x + y)\\<^sup>\\<star>\"\n  shows \"(x + y)\\<^sup>\\<omega> = 0 \\<longleftrightarrow> x\\<^sup>\\<omega> + y\\<^sup>\\<omega> = 0\"\nproof\n  assume \"(x + y)\\<^sup>\\<omega> = 0\"\n  show \"x\\<^sup>\\<omega> + y\\<^sup>\\<omega> = 0\"\n    by (metis `(x + y)\\<^sup>\\<omega> = (0\\<Colon>'a)` add.commute add_zero_r annir omega_sum_unfold)\nnext\n  assume \"x\\<^sup>\\<omega> + y\\<^sup>\\<omega> = 0\"\n  show \"(x + y)\\<^sup>\\<omega> = 0\"\n    by (metis `x\\<^sup>\\<omega> + y\\<^sup>\\<omega> = (0\\<Colon>'a)` assms no_trivial_inverse omega_sum_refine distrib_left star_omega_1)\nqed\n\ntext {*\nThe next lemmas consider an abstract variant of the empty word\nproperty from language theory and match it with the absence of\ninfinite iteration~\\cite{struth12regeq}.\n*}\n\ndefinition (in dioid_one_zero) ewp\nwhere \"ewp x \\<equiv> \\<not>(\\<forall>y. y \\<le> x \\<cdot> y \\<longrightarrow> y = 0)\"\n\nlemma ewp_super_id1: \"0 \\<noteq> 1 \\<longrightarrow> 1 \\<le> x \\<longrightarrow> ewp x\"\n  by (metis ewp_def mult_oner)\n\nlemma \"0 \\<noteq> 1 \\<longrightarrow> 1 \\<le> x \\<longleftrightarrow> ewp x\"\n  nitpick [expect=genuine] -- \"3-element counterexample\"\noops\n\ntext {* The next facts relate the absence of the empty word property\nwith the absence of infinite iteration. *}\n\nlemma ewp_neg_and_omega: \"\\<not> ewp x \\<longleftrightarrow> x\\<^sup>\\<omega> = 0\"\nproof\n  assume \"\\<not> ewp x\"\n  hence \"\\<forall> y. y \\<le> x \\<cdot> y \\<longrightarrow> y = 0\"\n    by (metis ewp_def)\n  thus \"x\\<^sup>\\<omega> = 0\"\n    by (metis omega_unfold)\nnext\n  assume \"x\\<^sup>\\<omega> = 0\"\n  hence \"\\<forall> y. y \\<le> x \\<cdot> y \\<longrightarrow> y = 0\"\n    by (metis omega_coinduct_var2 zero_unique)\n  thus \"\\<not> ewp x\"\n    by (metis ewp_def)\nqed\n\nlemma ewp_alt1: \"(\\<forall>z. x\\<^sup>\\<omega> \\<le> x\\<^sup>\\<star> \\<cdot> z) \\<longleftrightarrow> (\\<forall>y z. y \\<le> x \\<cdot> y + z \\<longrightarrow> y \\<le> x\\<^sup>\\<star> \\<cdot> z)\"\n  by (metis add_comm less_eq_def omega_coinduct omega_unfold_eq order_prop)\n\nlemma ewp_alt: \"x\\<^sup>\\<omega> = 0 \\<longleftrightarrow> (\\<forall>y z. y \\<le> x \\<cdot> y + z \\<longrightarrow> y \\<le> x\\<^sup>\\<star> \\<cdot> z)\"\n  by (metis annir antisym ewp_alt1 zero_least)\n\ntext {* So we have obtained a condition for Arden's lemma in omega\nalgebra.  *}\n\nlemma omega_super_id1: \"0 \\<noteq> 1 \\<longrightarrow> 1 \\<le> x \\<longrightarrow> x\\<^sup>\\<omega> \\<noteq> 0\"\n  by (metis eq_iff max_element omega_iso zero_least)\n\nlemma omega_super_id2: \"0 \\<noteq> 1 \\<longrightarrow> x\\<^sup>\\<omega> = 0 \\<longrightarrow> \\<not>(1 \\<le> x)\"\n  by (metis omega_super_id1)\n\ntext {* The next lemmas are abstract versions of Arden's lemma from\nlanguage theory.  *}\n\nlemma ardens_lemma_var:\n  assumes \"x\\<^sup>\\<omega> = 0\" and  \"z + x \\<cdot> y = y\"\n  shows \"x\\<^sup>\\<star> \\<cdot> z = y\"\nproof -\n  have \"y \\<le> x\\<^sup>\\<omega> + x\\<^sup>\\<star> \\<cdot> z\"\n    by (metis assms omega_coinduct order_refl)\n  hence \"y \\<le> x\\<^sup>\\<star> \\<cdot> z\"\n    by (metis add_zero_l assms)\n  thus \"x\\<^sup>\\<star> \\<cdot> z = y\"\n    by (metis assms eq_iff star_inductl_eq)\nqed\n\nlemma ardens_lemma: \"\\<not> ewp x \\<longrightarrow> z + x \\<cdot> y = y \\<longrightarrow> x\\<^sup>\\<star> \\<cdot> z = y\"\n  by (metis ardens_lemma_var ewp_neg_and_omega)\n\nlemma ardens_lemma_equiv:\n  assumes \"\\<not> ewp x\"\n  shows \"z + x \\<cdot> y = y \\<longleftrightarrow> x\\<^sup>\\<star> \\<cdot> z = y\"\nproof\n  assume \"z + x \\<cdot> y = y\"\n  thus \"x\\<^sup>\\<star> \\<cdot> z = y\"\n    by (metis ardens_lemma assms)\nnext\n  assume \"x\\<^sup>\\<star> \\<cdot> z = y\"\n  also have \"z + x \\<cdot> y = z + x \\<cdot> x\\<^sup>\\<star> \\<cdot> z\"\n    by (metis calculation mult.assoc)\n  moreover have \"... = (1 + x \\<cdot> x\\<^sup>\\<star>) \\<cdot> z\"\n    by (metis distrib_right mult_onel)\n  moreover have \"... = x\\<^sup>\\<star> \\<cdot> z\"\n    by (metis star_unfoldl_eq)\n  thus \"z + x \\<cdot> y = y\"\n    by (metis calculation)\nqed\n\nlemma ardens_lemma_var_equiv: \"x\\<^sup>\\<omega> = 0 \\<longrightarrow> (z + x \\<cdot> y = y \\<longleftrightarrow> x\\<^sup>\\<star> \\<cdot> z = y)\"\n  by (metis ardens_lemma_equiv ewp_neg_and_omega)\n\nlemma arden_conv1: \"(\\<forall>y z. z + x \\<cdot> y = y \\<longrightarrow> x\\<^sup>\\<star> \\<cdot> z = y) \\<longrightarrow> \\<not> ewp x\"\n  by (metis add_zero_l annir ewp_neg_and_omega omega_unfold_eq)\n\nlemma arden_conv2: \"(\\<forall>y z. z + x \\<cdot> y = y \\<longrightarrow> x\\<^sup>\\<star> \\<cdot> z = y) \\<longrightarrow> x\\<^sup>\\<omega> = 0\"\n  by (metis arden_conv1 ewp_neg_and_omega)\n\nlemma arden_var3: \"(\\<forall>y z. z + x \\<cdot> y = y \\<longrightarrow> x\\<^sup>\\<star> \\<cdot> z = y) \\<longleftrightarrow> x\\<^sup>\\<omega> = 0\"\n  by (metis arden_conv2 ardens_lemma_var)\n\nend\n\n\nsubsection {* Omega Algebras *}\n\nclass omega_algebra = kleene_algebra + left_omega_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/Kleene_Algebra/Omega_Algebra.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8824278757303677, "lm_q2_score": 0.8459424373085146, "lm_q1q2_score": 0.7464831879443223}}
{"text": "(* \nAuthors: \n\n  Anthony Bordg, University of Cambridge, apdb3@cam.ac.uk;\n  Yijun He, University of Cambridge, yh403@cam.ac.uk \n*)\n\ntheory No_Cloning\nimports\n  Quantum\n  Tensor\nbegin\n\nsection \\<open>The Cauchy-Schwarz Inequality\\<close>\n\nlemma inner_prod_expand:\n  assumes \"dim_vec a = dim_vec b\" and \"dim_vec a = dim_vec c\" and \"dim_vec a = dim_vec d\"\n  shows \"\\<langle>a + b|c + d\\<rangle> = \\<langle>a|c\\<rangle> + \\<langle>a|d\\<rangle> + \\<langle>b|c\\<rangle> + \\<langle>b|d\\<rangle>\"\n  apply (simp add: inner_prod_def)\n  using assms sum.cong by (simp add: sum.distrib algebra_simps)\n\nlemma inner_prod_distrib_left:\n  assumes \"dim_vec a = dim_vec b\"\n  shows \"\\<langle>c \\<cdot>\\<^sub>v a|b\\<rangle> = cnj(c) * \\<langle>a|b\\<rangle>\"\n  using assms inner_prod_def by (simp add: algebra_simps mult_hom.hom_sum)\n\nlemma inner_prod_distrib_right:\n  assumes \"dim_vec a = dim_vec b\"\n  shows \"\\<langle>a|c \\<cdot>\\<^sub>v b\\<rangle> = c * \\<langle>a|b\\<rangle>\"\n  using assms by (simp add: algebra_simps mult_hom.hom_sum)\n\nlemma cauchy_schwarz_ineq:\n  assumes \"dim_vec v = dim_vec w\"\n  shows \"(cmod(\\<langle>v|w\\<rangle>))\\<^sup>2 \\<le> Re (\\<langle>v|v\\<rangle> * \\<langle>w|w\\<rangle>)\" \nproof (cases \"\\<langle>v|v\\<rangle> = 0\")\n  case c0:True\n  then have \"\\<And>i. i < dim_vec v \\<Longrightarrow> v $ i = 0\" \n    by(metis index_zero_vec(1) inner_prod_with_itself_nonneg_reals_non0)\n  then have \"(cmod(\\<langle>v|w\\<rangle>))\\<^sup>2 = 0\" by (simp add: assms inner_prod_def)\n  moreover have \"Re (\\<langle>v|v\\<rangle> * \\<langle>w|w\\<rangle>) = 0\" by (simp add: c0)\n  ultimately show ?thesis by simp\nnext\n  case c1:False\n  have \"dim_vec w = dim_vec (- \\<langle>v|w\\<rangle> / \\<langle>v|v\\<rangle> \\<cdot>\\<^sub>v v)\" by (simp add: assms)\n  then have \"\\<langle>w + -\\<langle>v|w\\<rangle>/\\<langle>v|v\\<rangle> \\<cdot>\\<^sub>v v|w + -\\<langle>v|w\\<rangle>/\\<langle>v|v\\<rangle> \\<cdot>\\<^sub>v v\\<rangle> = \\<langle>w|w\\<rangle> + \\<langle>w|-\\<langle>v|w\\<rangle>/\\<langle>v|v\\<rangle> \\<cdot>\\<^sub>v v\\<rangle> + \n\\<langle>-\\<langle>v|w\\<rangle>/\\<langle>v|v\\<rangle> \\<cdot>\\<^sub>v v|w\\<rangle> + \\<langle>-\\<langle>v|w\\<rangle>/\\<langle>v|v\\<rangle> \\<cdot>\\<^sub>v v|-\\<langle>v|w\\<rangle>/\\<langle>v|v\\<rangle> \\<cdot>\\<^sub>v v\\<rangle>\"\n    using inner_prod_expand[of \"w\" \"-\\<langle>v|w\\<rangle>/\\<langle>v|v\\<rangle> \\<cdot>\\<^sub>v v\" \"w\" \"-\\<langle>v|w\\<rangle>/\\<langle>v|v\\<rangle> \\<cdot>\\<^sub>v v\"] by auto\n  moreover have \"\\<langle>w|-\\<langle>v|w\\<rangle>/\\<langle>v|v\\<rangle> \\<cdot>\\<^sub>v v\\<rangle> = -\\<langle>v|w\\<rangle>/\\<langle>v|v\\<rangle> * \\<langle>w|v\\<rangle>\"\n    using assms inner_prod_distrib_right[of \"w\" \"v\" \"-\\<langle>v|w\\<rangle>/\\<langle>v|v\\<rangle>\"] by simp\n  moreover have \"\\<langle>-\\<langle>v|w\\<rangle>/\\<langle>v|v\\<rangle> \\<cdot>\\<^sub>v v|w\\<rangle> = cnj(-\\<langle>v|w\\<rangle>/\\<langle>v|v\\<rangle>) * \\<langle>v|w\\<rangle>\"\n    using assms inner_prod_distrib_left[of \"v\" \"w\" \"-\\<langle>v|w\\<rangle>/\\<langle>v|v\\<rangle>\"] by simp\n  moreover have \"\\<langle>-\\<langle>v|w\\<rangle>/\\<langle>v|v\\<rangle> \\<cdot>\\<^sub>v v|-\\<langle>v|w\\<rangle>/\\<langle>v|v\\<rangle> \\<cdot>\\<^sub>v v\\<rangle> = cnj(-\\<langle>v|w\\<rangle>/\\<langle>v|v\\<rangle>) * (-\\<langle>v|w\\<rangle>/\\<langle>v|v\\<rangle>) * \\<langle>v|v\\<rangle>\"\n    using inner_prod_distrib_left[of \"v\" \"-\\<langle>v|w\\<rangle>/\\<langle>v|v\\<rangle> \\<cdot>\\<^sub>v v\" \"-\\<langle>v|w\\<rangle>/\\<langle>v|v\\<rangle>\"] \ninner_prod_distrib_right[of \"v\" \"v\" \"-\\<langle>v|w\\<rangle>/\\<langle>v|v\\<rangle>\"] by simp\n  ultimately have \"\\<langle>w + -\\<langle>v|w\\<rangle>/\\<langle>v|v\\<rangle> \\<cdot>\\<^sub>v v|w + -\\<langle>v|w\\<rangle>/\\<langle>v|v\\<rangle> \\<cdot>\\<^sub>v v\\<rangle> = \\<langle>w|w\\<rangle> -  cmod(\\<langle>v|w\\<rangle>)^2 / \\<langle>v|v\\<rangle>\"\n    using assms inner_prod_cnj[of \"w\" \"v\"] inner_prod_cnj[of \"v\" \"v\"] complex_norm_square by simp\n  moreover have \"Re(\\<langle>w + -\\<langle>v|w\\<rangle>/\\<langle>v|v\\<rangle> \\<cdot>\\<^sub>v v|w + -\\<langle>v|w\\<rangle>/\\<langle>v|v\\<rangle> \\<cdot>\\<^sub>v v\\<rangle>) \\<ge> 0\"\n    using inner_prod_with_itself_Re by blast\n  ultimately have \"Re(\\<langle>w|w\\<rangle>) \\<ge> cmod(\\<langle>v|w\\<rangle>)^2/Re(\\<langle>v|v\\<rangle>)\"\n    using inner_prod_with_itself_real by simp\n  moreover have c2:\"Re(\\<langle>v|v\\<rangle>) > 0\"\n    using inner_prod_with_itself_Re_non0 inner_prod_with_itself_eq0 c1 by auto\n  ultimately have \"Re(\\<langle>w|w\\<rangle>) * Re(\\<langle>v|v\\<rangle>) \\<ge> cmod(\\<langle>v|w\\<rangle>)^2/Re(\\<langle>v|v\\<rangle>) * Re(\\<langle>v|v\\<rangle>)\"\n    using real_mult_le_cancel_iff1 by blast\n  thus ?thesis\n    using inner_prod_with_itself_Im c2 by (simp add: mult.commute)\nqed\n\nlemma cauchy_schwarz_eq [simp]:\n  assumes \"v = (l \\<cdot>\\<^sub>v w)\"\n  shows \"(cmod(\\<langle>v|w\\<rangle>))\\<^sup>2 = Re (\\<langle>v|v\\<rangle> * \\<langle>w|w\\<rangle>)\"\nproof-\n  have \"cmod(\\<langle>v|w\\<rangle>) = cmod(cnj(l) * \\<langle>w|w\\<rangle>)\"\n    using assms inner_prod_distrib_left[of \"w\" \"w\" \"l\"] by simp\n  then have \"cmod(\\<langle>v|w\\<rangle>)^2 = cmod(l)^2 * \\<langle>w|w\\<rangle> * \\<langle>w|w\\<rangle>\"\n    using complex_norm_square inner_prod_cnj[of \"w\" \"w\"] by simp\n  moreover have \"\\<langle>v|v\\<rangle> = cmod(l)^2 * \\<langle>w|w\\<rangle>\"\n    using assms complex_norm_square inner_prod_distrib_left[of \"w\" \"v\" \"l\"] \ninner_prod_distrib_right[of \"w\" \"w\" \"l\"] by simp\n  ultimately show ?thesis by (metis Re_complex_of_real)\nqed\n\nlemma cauchy_schwarz_col [simp]:\n  assumes \"dim_vec v = dim_vec w\" and \"(cmod(\\<langle>v|w\\<rangle>))\\<^sup>2 = Re (\\<langle>v|v\\<rangle> * \\<langle>w|w\\<rangle>)\"\n  shows \"\\<exists>l. v = (l \\<cdot>\\<^sub>v w) \\<or> w = (l \\<cdot>\\<^sub>v v)\"\nproof (cases \"\\<langle>v|v\\<rangle> = 0\")\n  case c0:True\n  then have \"\\<And>i. i < dim_vec v \\<Longrightarrow> v $ i = 0\" \n    by(metis index_zero_vec(1) inner_prod_with_itself_nonneg_reals_non0)\n  then have \"v = 0 \\<cdot>\\<^sub>v w\" by (auto simp: assms)\n  then show ?thesis by auto\nnext\n  case c1:False\n  have f0:\"dim_vec w = dim_vec (- \\<langle>v|w\\<rangle> / \\<langle>v|v\\<rangle> \\<cdot>\\<^sub>v v)\" by (simp add: assms(1))\n  then have \"\\<langle>w + -\\<langle>v|w\\<rangle>/\\<langle>v|v\\<rangle> \\<cdot>\\<^sub>v v|w + -\\<langle>v|w\\<rangle>/\\<langle>v|v\\<rangle> \\<cdot>\\<^sub>v v\\<rangle> = \\<langle>w|w\\<rangle> + \\<langle>w|-\\<langle>v|w\\<rangle>/\\<langle>v|v\\<rangle> \\<cdot>\\<^sub>v v\\<rangle> + \n\\<langle>-\\<langle>v|w\\<rangle>/\\<langle>v|v\\<rangle> \\<cdot>\\<^sub>v v|w\\<rangle> + \\<langle>-\\<langle>v|w\\<rangle>/\\<langle>v|v\\<rangle> \\<cdot>\\<^sub>v v|-\\<langle>v|w\\<rangle>/\\<langle>v|v\\<rangle> \\<cdot>\\<^sub>v v\\<rangle>\"\n    using inner_prod_expand[of \"w\" \"-\\<langle>v|w\\<rangle>/\\<langle>v|v\\<rangle> \\<cdot>\\<^sub>v v\" \"w\" \"-\\<langle>v|w\\<rangle>/\\<langle>v|v\\<rangle> \\<cdot>\\<^sub>v v\"] by simp\n  moreover have \"\\<langle>w|-\\<langle>v|w\\<rangle>/\\<langle>v|v\\<rangle> \\<cdot>\\<^sub>v v\\<rangle> = -\\<langle>v|w\\<rangle>/\\<langle>v|v\\<rangle> * \\<langle>w|v\\<rangle>\"\n    using assms(1) inner_prod_distrib_right[of \"w\" \"v\" \"-\\<langle>v|w\\<rangle>/\\<langle>v|v\\<rangle>\"] by simp\n  moreover have \"\\<langle>-\\<langle>v|w\\<rangle>/\\<langle>v|v\\<rangle> \\<cdot>\\<^sub>v v|w\\<rangle> = cnj(-\\<langle>v|w\\<rangle>/\\<langle>v|v\\<rangle>) * \\<langle>v|w\\<rangle>\"\n    using assms(1) inner_prod_distrib_left[of \"v\" \"w\" \"-\\<langle>v|w\\<rangle>/\\<langle>v|v\\<rangle>\"] by simp\n  moreover have \"\\<langle>-\\<langle>v|w\\<rangle>/\\<langle>v|v\\<rangle> \\<cdot>\\<^sub>v v|-\\<langle>v|w\\<rangle>/\\<langle>v|v\\<rangle> \\<cdot>\\<^sub>v v\\<rangle> = cnj(-\\<langle>v|w\\<rangle>/\\<langle>v|v\\<rangle>) * (-\\<langle>v|w\\<rangle>/\\<langle>v|v\\<rangle>) * \\<langle>v|v\\<rangle>\"\n    using inner_prod_distrib_left[of \"v\" \"-\\<langle>v|w\\<rangle>/\\<langle>v|v\\<rangle> \\<cdot>\\<^sub>v v\" \"-\\<langle>v|w\\<rangle>/\\<langle>v|v\\<rangle>\"] \ninner_prod_distrib_right[of \"v\" \"v\" \"-\\<langle>v|w\\<rangle>/\\<langle>v|v\\<rangle>\"] by simp\n  ultimately have \"\\<langle>w + -\\<langle>v|w\\<rangle>/\\<langle>v|v\\<rangle> \\<cdot>\\<^sub>v v|w + -\\<langle>v|w\\<rangle>/\\<langle>v|v\\<rangle> \\<cdot>\\<^sub>v v\\<rangle> = \\<langle>w|w\\<rangle> -  cmod(\\<langle>v|w\\<rangle>)^2 / \\<langle>v|v\\<rangle>\"\n    using inner_prod_cnj[of \"w\" \"v\"] inner_prod_cnj[of \"v\" \"v\"] assms(1) complex_norm_square by simp\n  moreover have \"\\<langle>w|w\\<rangle> = cmod(\\<langle>v|w\\<rangle>)^2 / \\<langle>v|v\\<rangle>\"\n    using assms(2) inner_prod_with_itself_real by(metis Reals_mult c1 nonzero_mult_div_cancel_left of_real_Re)\n  ultimately have \"\\<langle>w + -\\<langle>v|w\\<rangle>/\\<langle>v|v\\<rangle> \\<cdot>\\<^sub>v v|w + -\\<langle>v|w\\<rangle>/\\<langle>v|v\\<rangle> \\<cdot>\\<^sub>v v\\<rangle> = 0\" by simp\n  then have \"\\<And>i. i<dim_vec w \\<Longrightarrow> (w + -\\<langle>v|w\\<rangle>/\\<langle>v|v\\<rangle> \\<cdot>\\<^sub>v v) $ i = 0\"\n    by (metis f0 index_add_vec(2) index_zero_vec(1) inner_prod_with_itself_nonneg_reals_non0)\n  then have \"\\<And>i. i<dim_vec w \\<Longrightarrow> w $ i + -\\<langle>v|w\\<rangle>/\\<langle>v|v\\<rangle> * v $ i = 0\"\n    by (metis assms(1) f0 index_add_vec(1) index_smult_vec(1))\n  then have \"\\<And>i. i<dim_vec w \\<Longrightarrow> w $ i = \\<langle>v|w\\<rangle>/\\<langle>v|v\\<rangle> * v $ i\" by simp\n  then have \"w = \\<langle>v|w\\<rangle>/\\<langle>v|v\\<rangle> \\<cdot>\\<^sub>v v\" by (auto simp add: assms(1))\n  thus ?thesis by auto\nqed\n\nsection \\<open>The No-Cloning Theorem\\<close>\n\nlemma eq_from_inner_prod [simp]:\n  assumes \"dim_vec v = dim_vec w\" and \"\\<langle>v|w\\<rangle> = 1\" and \"\\<langle>v|v\\<rangle> = 1\" and \"\\<langle>w|w\\<rangle> = 1\"\n  shows \"v = w\"\nproof-\n  have \"(cmod(\\<langle>v|w\\<rangle>))\\<^sup>2 = Re (\\<langle>v|v\\<rangle> * \\<langle>w|w\\<rangle>)\" by (simp add: assms)\n  then have f0:\"\\<exists>l. v = (l \\<cdot>\\<^sub>v w) \\<or> w = (l \\<cdot>\\<^sub>v v)\" by (simp add: assms(1))\n  then show ?thesis\n  proof (cases \"\\<exists>l. v = (l \\<cdot>\\<^sub>v w)\")\n    case True\n    then have \"\\<exists>l. v = (l \\<cdot>\\<^sub>v w) \\<and> \\<langle>v|w\\<rangle> = cnj(l) * \\<langle>w|w\\<rangle>\"\n      using inner_prod_distrib_left by auto\n    then show ?thesis by (simp add: assms(2,4))\n  next\n    case False\n    then have \"\\<exists>l. w = (l \\<cdot>\\<^sub>v v) \\<and> \\<langle>v|w\\<rangle> = l * \\<langle>v|v\\<rangle>\"\n      using f0 inner_prod_distrib_right by auto\n    then show ?thesis by (simp add: assms(2,3))\n  qed \nqed\n\nlemma hermite_cnj_of_tensor:\n  shows \"(A \\<Otimes> B)\\<^sup>\\<dagger>  = (A\\<^sup>\\<dagger>) \\<Otimes> (B\\<^sup>\\<dagger>)\"\nproof\n  show c0:\"dim_row ((A \\<Otimes> B)\\<^sup>\\<dagger>) = dim_row ((A\\<^sup>\\<dagger>) \\<Otimes> (B\\<^sup>\\<dagger>))\" by simp\n  show c1:\"dim_col ((A \\<Otimes> B)\\<^sup>\\<dagger>) = dim_col ((A\\<^sup>\\<dagger>) \\<Otimes> (B\\<^sup>\\<dagger>))\" by simp\n  show \"\\<And>i j. i < dim_row ((A\\<^sup>\\<dagger>) \\<Otimes> (B\\<^sup>\\<dagger>)) \\<Longrightarrow> j < dim_col ((A\\<^sup>\\<dagger>) \\<Otimes> (B\\<^sup>\\<dagger>)) \\<Longrightarrow> \n((A \\<Otimes> B)\\<^sup>\\<dagger>) $$ (i, j) = ((A\\<^sup>\\<dagger>) \\<Otimes> (B\\<^sup>\\<dagger>)) $$ (i, j)\"\n  proof-\n    fix i j assume a0:\"i < dim_row ((A\\<^sup>\\<dagger>) \\<Otimes> (B\\<^sup>\\<dagger>))\" and a1:\"j < dim_col ((A\\<^sup>\\<dagger>) \\<Otimes> (B\\<^sup>\\<dagger>))\"\n    then have \"(A \\<Otimes> B)\\<^sup>\\<dagger> $$ (i, j) = cnj((A \\<Otimes> B) $$ (j, i))\" by (simp add: dagger_def)\n    also have \"\\<dots> = cnj(A $$ (j div dim_row(B), i div dim_col(B)) * B $$ (j mod dim_row(B), i mod dim_col(B)))\"\n      by (metis (mono_tags, lifting) a0 a1 c1 dim_row_tensor_mat dim_col_of_dagger dim_row_of_dagger \nindex_tensor_mat less_nat_zero_code mult_not_zero neq0_conv)\n    moreover have \"((A\\<^sup>\\<dagger>) \\<Otimes> (B\\<^sup>\\<dagger>)) $$ (i, j) = \n(A\\<^sup>\\<dagger>) $$ (i div dim_col(B), j div dim_row(B)) * (B\\<^sup>\\<dagger>) $$ (i mod dim_col(B), j mod dim_row(B))\"\n      by (smt a0 a1 c1 dim_row_tensor_mat dim_col_of_dagger dim_row_of_dagger index_tensor_mat \nless_nat_zero_code mult_eq_0_iff neq0_conv)\n    moreover have \"(B\\<^sup>\\<dagger>) $$ (i mod dim_col(B), j mod dim_row(B)) = cnj(B $$ (j mod dim_row(B), i mod dim_col(B)))\"\n    proof-\n      have \"i mod dim_col(B) < dim_col(B)\" \n        using a0 gr_implies_not_zero mod_div_trivial by fastforce\n      moreover have \"j mod dim_row(B) < dim_row(B)\"\n        using a1 gr_implies_not_zero mod_div_trivial by fastforce\n      ultimately show ?thesis by (simp add: dagger_def)\n    qed\n    moreover have \"(A\\<^sup>\\<dagger>) $$ (i div dim_col(B), j div dim_row(B)) = cnj(A $$ (j div dim_row(B), i div dim_col(B)))\"\n    proof-\n      have \"i div dim_col(B) < dim_col(A)\"\n        using a0 dagger_def by (simp add: less_mult_imp_div_less)\n      moreover have \"j div dim_row(B) < dim_row(A)\"\n        using a1 dagger_def by (simp add: less_mult_imp_div_less)\n      ultimately show ?thesis by (simp add: dagger_def)\n    qed\n    ultimately show \"((A \\<Otimes> B)\\<^sup>\\<dagger>) $$ (i, j) = ((A\\<^sup>\\<dagger>) \\<Otimes> (B\\<^sup>\\<dagger>)) $$ (i, j)\" by simp\n  qed\nqed\n\nlocale quantum_machine =\n  fixes n:: nat and s:: \"complex Matrix.vec\" and U:: \"complex Matrix.mat\"\n  assumes dim_vec [simp]: \"dim_vec s = 2^n\"\n    and dim_col [simp]: \"dim_col U = 2^n * 2^n\"\n    and square [simp]: \"square_mat U\" and unitary [simp]: \"unitary U\"\n\nlemma inner_prod_of_unit_vec:\n  fixes n i:: nat\n  assumes \"i < n\"\n  shows \"\\<langle>unit_vec n i| unit_vec n i\\<rangle> = 1\"\n  apply (auto simp add: inner_prod_def unit_vec_def) \n  by (simp add: assms sum.cong[of \"{0..<n}\" \"{0..<n}\" \n\"\\<lambda>j. cnj (if j = i then 1 else 0) * (if j = i then 1 else 0)\" \"\\<lambda>j. (if j = i then 1 else 0)\"]) \n\ntheorem (in quantum_machine) no_cloning:\n  assumes [simp]: \"dim_vec v = 2^n\" and [simp]: \"dim_vec w = 2^n\" and \n    cloning1: \"\\<And>s. U * ( |v\\<rangle> \\<Otimes> |s\\<rangle>) = |v\\<rangle> \\<Otimes> |v\\<rangle>\" and\n    cloning2: \"\\<And>s. U * ( |w\\<rangle> \\<Otimes> |s\\<rangle>) = |w\\<rangle> \\<Otimes> |w\\<rangle>\" and \n    \"\\<langle>v|v\\<rangle> = 1\" and \"\\<langle>w|w\\<rangle> = 1\"\n  shows \"v = w \\<or> \\<langle>v|w\\<rangle> = 0\"\nproof-\n  define s:: \"complex Matrix.vec\" where d0:\"s = unit_vec (2^n) 0\"\n  have f0:\"\\<langle>|v\\<rangle>| \\<Otimes> \\<langle>|s\\<rangle>| = (( |v\\<rangle> \\<Otimes> |s\\<rangle>)\\<^sup>\\<dagger>)\" \n    using hermite_cnj_of_tensor[of \"|v\\<rangle>\" \"|s\\<rangle>\"] bra_def dagger_def ket_vec_def by simp\n  moreover have f1:\"( |v\\<rangle> \\<Otimes> |v\\<rangle>)\\<^sup>\\<dagger> * ( |w\\<rangle> \\<Otimes> |w\\<rangle>) = (\\<langle>|v\\<rangle>| \\<Otimes> \\<langle>|s\\<rangle>| ) * ( |w\\<rangle> \\<Otimes> |s\\<rangle>)\"\n  proof-\n    have \"(U * ( |v\\<rangle> \\<Otimes> |s\\<rangle>))\\<^sup>\\<dagger> = (\\<langle>|v\\<rangle>| \\<Otimes> \\<langle>|s\\<rangle>| ) * (U\\<^sup>\\<dagger>)\"\n      using dagger_of_prod[of \"U\" \"|v\\<rangle> \\<Otimes> |s\\<rangle>\"] f0 d0 by (simp add: ket_vec_def)\n    then have \"(U * ( |v\\<rangle> \\<Otimes> |s\\<rangle>))\\<^sup>\\<dagger> * U * ( |w\\<rangle> \\<Otimes> |s\\<rangle>) = (\\<langle>|v\\<rangle>| \\<Otimes> \\<langle>|s\\<rangle>| ) * (U\\<^sup>\\<dagger>) * U * ( |w\\<rangle> \\<Otimes> |s\\<rangle>)\" by simp\n    moreover have \"(U * ( |v\\<rangle> \\<Otimes> |s\\<rangle>))\\<^sup>\\<dagger> * U * ( |w\\<rangle> \\<Otimes> |s\\<rangle>) = (( |v\\<rangle> \\<Otimes> |v\\<rangle>)\\<^sup>\\<dagger>) * ( |w\\<rangle> \\<Otimes> |w\\<rangle>)\"\n      using assms(2-4) d0 unit_vec_def by (smt Matrix.dim_vec assoc_mult_mat carrier_mat_triv dim_row_mat(1) \ndim_row_tensor_mat dim_col_of_dagger index_mult_mat(2) ket_vec_def square square_mat.elims(2))\n    moreover have \"(U\\<^sup>\\<dagger>) * U = 1\\<^sub>m (2^n * 2^n)\"\n      using unitary_def dim_col unitary by simp\n    moreover have \"(\\<langle>|v\\<rangle>| \\<Otimes> \\<langle>|s\\<rangle>| ) * (U\\<^sup>\\<dagger>) * U = (\\<langle>|v\\<rangle>| \\<Otimes> \\<langle>|s\\<rangle>| ) * ((U\\<^sup>\\<dagger>) * U)\"\n      using d0 assms(1) unit_vec_def by (smt Matrix.dim_vec assoc_mult_mat carrier_mat_triv dim_row_mat(1) \ndim_row_tensor_mat f0 dim_col_of_dagger dim_row_of_dagger ket_vec_def local.dim_col)\n    moreover have \"(\\<langle>|v\\<rangle>| \\<Otimes> \\<langle>|s\\<rangle>| ) * 1\\<^sub>m (2^n * 2^n) = (\\<langle>|v\\<rangle>| \\<Otimes> \\<langle>|s\\<rangle>| )\"\n      using f0 ket_vec_def d0 by simp\n    ultimately show ?thesis by simp\n  qed\n  then have f2:\"(\\<langle>|v\\<rangle>| * |w\\<rangle>) \\<Otimes> (\\<langle>|v\\<rangle>| * |w\\<rangle>) = (\\<langle>|v\\<rangle>| * |w\\<rangle>) \\<Otimes> (\\<langle>|s\\<rangle>| * |s\\<rangle>)\"\n  proof-\n    have \"\\<langle>|v\\<rangle>| \\<Otimes> \\<langle>|v\\<rangle>| = (( |v\\<rangle> \\<Otimes> |v\\<rangle>)\\<^sup>\\<dagger>)\"\n      using hermite_cnj_of_tensor[of \"|v\\<rangle>\" \"|v\\<rangle>\"] bra_def dagger_def ket_vec_def by simp\n    then show ?thesis\n      using f1 d0 by (simp add: bra_def mult_distr_tensor ket_vec_def)\n  qed\n  then have \"\\<langle>v|w\\<rangle> * \\<langle>v|w\\<rangle> = \\<langle>v|w\\<rangle> * \\<langle>s|s\\<rangle>\"\n  proof-\n    have \"((\\<langle>|v\\<rangle>| * |w\\<rangle>) \\<Otimes> (\\<langle>|v\\<rangle>| * |w\\<rangle>)) $$ (0,0) = \\<langle>v|w\\<rangle> * \\<langle>v|w\\<rangle>\"\n      using assms inner_prod_with_times_mat[of \"v\" \"w\"] by (simp add: bra_def ket_vec_def)\n    moreover have \"((\\<langle>|v\\<rangle>| * |w\\<rangle>) \\<Otimes> (\\<langle>|s\\<rangle>| * |s\\<rangle>)) $$ (0,0) = \\<langle>v|w\\<rangle> * \\<langle>s|s\\<rangle>\"\n      using inner_prod_with_times_mat[of \"v\" \"w\"] inner_prod_with_times_mat[of \"s\" \"s\"] by(simp add: bra_def ket_vec_def)\n    ultimately show ?thesis using f2 by auto \n  qed\n  then have \"\\<langle>v|w\\<rangle> = 0 \\<or> \\<langle>v|w\\<rangle> = \\<langle>s|s\\<rangle>\" by (simp add: mult_left_cancel)\n  moreover have \"\\<langle>s|s\\<rangle> = 1\" by(simp add: d0 inner_prod_of_unit_vec)\n  ultimately show ?thesis using assms(1,2,5,6) by auto\nqed\n\n\nend", "meta": {"author": "AnthonyBordg", "repo": "Isabelle_marries_Dirac", "sha": "ab313fb4028c99bd5d97f8e30aaf1644e200d57b", "save_path": "github-repos/isabelle/AnthonyBordg-Isabelle_marries_Dirac", "path": "github-repos/isabelle/AnthonyBordg-Isabelle_marries_Dirac/Isabelle_marries_Dirac-ab313fb4028c99bd5d97f8e30aaf1644e200d57b/No_Cloning.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772482857833, "lm_q2_score": 0.8539127529517043, "lm_q1q2_score": 0.7463857093761636}}
{"text": "(*\n  File:    Harmonic_2_adic.thy \n  Author:  Jose Manuel Rodriguez Caballero, University of Tartu\n  Author:  Manuel Eberl, TU M\u00fcnchen\n*)\nsection \\<open>Applications of the p-adic norm to the harmonic numbers\\<close>\ntheory Harmonic_2_adic\n\nimports \n  \"HOL-Analysis.Harmonic_Numbers\"\n  Pnorm\n\nbegin\n\ntext \\<open>\n In 1915, L. Theisinger ~\\cite{theisinger1915bemerkung} proved that, for \\<^term>\\<open>(n::nat) \\<ge> 2\\<close>, the\n harmonic number \\<^term>\\<open>(harm n) :: real\\<close> is not an integer. In 1918,  J. K{\\\"u}rsch{\\'a}k  \n ~\\cite{kurschak1918harmonic} proved that, for \\<^term>\\<open>(n::nat)+2 \\<ge> (m::nat)\\<close>, the difference between \n the two harmonic numbers \\<^term>\\<open>((harm n) - (harm m))::real\\<close> is not an integer. We formalize these \n results as theorems @{text Taeisinger} and @{text Kurschak}, respectively. The proofs will be\n simple consequences the computation of the 2-adic norm of the harmonic numbers \n (lemma @{text harmonic_numbers_2norm}).\n\\<close>\n\nsubsection \\<open>Auxiliary results\\<close>\ntext\\<open>\n  The following function is a variation of \\<^term>\\<open>harm\\<close>, where the codomain is typ>\\<open>rat\\<close>. We need this\n  function because the codomain of \\<^term>\\<open>harm\\<close> cannot be \\<^typ>\\<open>rat\\<close>.\n\\<close>\nfun Harm :: \"nat \\<Rightarrow> rat\" where\n  \"Harm 0 = 0\" |\n  \"Harm (Suc n) = Harm n + inverse (of_nat (Suc n))\"\n\nlemma Harm'[simp]: \"real_of_rat (Harm n) = harm n\"\nproof(induction n)\n  case 0 thus ?case by (simp add: harm_expand(1)) \nnext\n  case (Suc n)\n  have \"real_of_rat (Harm (Suc n)) = real_of_rat (Harm n + inverse (of_nat (Suc n)))\"\n    by simp\n  also have \"\\<dots> = real_of_rat (Harm n) + real_of_rat (inverse (of_nat (Suc n)))\"\n    by (simp add: of_rat_add)\n  also have \"\\<dots> = harm n + real_of_rat (inverse (of_nat (Suc n)))\"\n    by (simp add: Suc.IH)    \n  finally show ?case\n    by (metis harm_Suc of_rat_inverse of_rat_of_nat_eq) \nqed\n\nlemma harm_diff_plus:\n  \"harm (n+t) - harm n = (\\<Sum>k=n+1..n+t. inverse (of_nat k))\"\nproof(induct t)\n  case 0 thus ?case by simp \nnext\n  case (Suc t) show ?case\n  proof -\n    have f1: \"\\<forall>a b c. (a::'a) + b \\<noteq> a + c \\<or> b = c\"\n      by (meson add_left_imp_eq)\n    have f2: \"(\\<Sum>n = 1..n. inverse (of_nat n::'a)) + (harm (n + Suc t) - harm n) \n            = (\\<Sum>n = 1..n + Suc t. inverse (of_nat n))\"\n      by (metis (no_types) add.commute diff_add_cancel harm_def)\n    have \"(\\<Sum>n = 1..n + Suc t. inverse (of_nat n::'a)) \n        = (\\<Sum>n = 1..n. inverse (of_nat n)) + (\\<Sum>n = n + 1..n + Suc t. inverse (of_nat n))\"\n      by (meson le_add2 sum.ub_add_nat)\n    thus ?thesis\n      using f2 f1 by presburger\n  qed \nqed\n\nlemma harm_diff:\n  \"n \\<ge> m \\<Longrightarrow> harm n - harm m = (\\<Sum>k=m+1..n. inverse (of_nat k))\"\n  using harm_diff_plus[where n = m and t = \"n - m\"] by simp\n\nlemma harm_diff':\n  \"n \\<ge> m \\<Longrightarrow> Harm n - Harm m = (\\<Sum>k=m+1..n. inverse (rat_of_nat k))\"\nproof-\n  assume \"n \\<ge> m\"\n  have \"real_of_rat (Harm n - Harm m) = harm n - harm m\"\n    by (simp add: of_rat_diff)\n  also have \"\\<dots> = (\\<Sum>k=m+1..n. inverse (of_nat k))\"\n    using harm_diff \\<open>m \\<le> n\\<close> by blast \n  also have \"\\<dots> = (\\<Sum>k=m+1..n. real_of_rat (inverse (rat_of_nat k)))\"\n    by (simp add: of_rat_inverse)\n  also have \"\\<dots> = real_of_rat (\\<Sum>k=m+1..n. (inverse (rat_of_nat k)))\"\n    by (simp add: of_rat_sum)\n  finally show ?thesis by auto\nqed\n\nlemma Harm_explicit:\n  \"Harm n = (\\<Sum>k=1..n. inverse (rat_of_nat k))\"\n  using harm_diff' by fastforce\n\nlemma Harm_incre: \\<open>m < n \\<Longrightarrow> Harm m < Harm n\\<close>\nproof-\n  assume \\<open>m < n\\<close>\n  have \\<open>finite {m + 1..n}\\<close>\n    by simp\n  moreover have \\<open>{m + 1..n} \\<noteq> {}\\<close>\n    using \\<open>m < n\\<close>\n    by simp\n  moreover have \\<open>k \\<in> {m + 1..n} \\<Longrightarrow> 0 < inverse (rat_of_nat k)\\<close> for k\n  proof-\n    assume \\<open>k \\<in> {m + 1..n}\\<close>\n    hence \\<open>k \\<ge> 1\\<close>\n      by auto\n    thus ?thesis\n      by (simp add: zero_less_Fract_iff) \n  qed\n  ultimately have \\<open>0 < (\\<Sum>k = m + 1..n. inverse (rat_of_nat k))\\<close>\n    using Groups_Big.ordered_comm_monoid_add_class.sum_pos[where I = \"{m+1..n}\" \n        and f = \"\\<lambda> k. inverse (rat_of_nat k)\"] by auto\n  thus ?thesis\n    using harm_diff'[where n = n and m = m] \\<open>n > m\\<close> \n    by simp\nqed\n\nlemma Harm_diff_less_1:\n  \"m < n \\<Longrightarrow> n \\<le> 2*m \\<Longrightarrow> Harm n - Harm m < 1\"\nproof-\n  assume \"m < n\" and \"n \\<le> 2*m\"\n  have \\<open>(\\<Sum>k = m + 1..n. inverse (rat_of_nat k)) < 1\\<close>\n  proof-\n    have \\<open>finite {m + 1..n}\\<close>\n      by simp\n    moreover have \\<open>{m + 1..n} \\<noteq> {}\\<close>\n      using \\<open>m < n\\<close> by simp\n    moreover have \\<open>k \\<in> {m + 1..n} \\<Longrightarrow> inverse (rat_of_nat k) \\<le> inverse (rat_of_nat (m+1))\\<close> for k\n    proof-\n      assume \\<open>k \\<in> {m + 1..n}\\<close>\n      have \\<open>k \\<ge> m+1\\<close>\n        using \\<open>k \\<in> {m + 1..n}\\<close>\n        by auto\n      thus ?thesis\n        by auto\n    qed\n    ultimately have \\<open>(\\<Sum>k = m + 1..n. inverse (rat_of_nat k)) \n                     \\<le> of_nat (card {m + 1..n}) * inverse (rat_of_nat (m+1))\\<close>\n      using Groups_Big.sum_bounded_above[where A = \"{m+1..n}\" and K = \"inverse (rat_of_nat (m+1))\"\n          and f = \"\\<lambda> k. inverse (rat_of_nat k)\"]\n      by auto\n    also  have \\<open>\\<dots> \\<le> of_nat m * inverse (rat_of_nat (m+1))\\<close>\n    proof-\n      have \\<open>card {m+1..n} \\<le> m\\<close>\n      proof-\n        have \\<open>card {m+1..n} = n - m\\<close>\n          by auto\n        thus ?thesis\n          using \\<open>n \\<le> 2*m\\<close> by simp\n      qed\n      moreover have \\<open>card  {m + 1..n} > 0\\<close>\n        using \\<open>{m + 1..n} \\<noteq> {}\\<close> card_gt_0_iff by blast\n      ultimately show ?thesis by simp\n    qed\n    also have \\<open>\\<dots> < 1\\<close>\n    proof -\n      have f1: \"0 < Fract 1 (int (m + 1))\"\n        using zero_less_Fract_iff by auto\n      have \"rat_of_nat (m + 1) * inverse (rat_of_nat (m + 1)) = 1\"\n        by auto\n      thus ?thesis\n        using f1 by (metis (no_types) Fract_of_nat_eq inverse_rat less_add_same_cancel1 less_one \n            linordered_field_class.sign_simps(35) linordered_field_class.sign_simps(44) \n            of_nat_0_less_iff of_nat_add)\n    qed       \n    finally show ?thesis\n      by blast\n  qed\n  thus ?thesis\n    using harm_diff' \\<open>m < n\\<close> by auto\nqed\n\n(* TODO: delete *)\nlemma sum_last:\n  fixes n::nat and a::\\<open>nat \\<Rightarrow> rat\\<close>\n  assumes \\<open>n \\<ge> 2\\<close>\n  shows \\<open>(\\<Sum>k = 1..n - 1. (a k)) + (a n) = (\\<Sum>k = 1..n. (a k))\\<close>\n  using \\<open>n \\<ge> 2\\<close>\n  apply auto\n  by (smt add.commute add_leD2 le_add_diff_inverse numeral_1_eq_Suc_0 numeral_2_eq_2 \n      numeral_One plus_1_eq_Suc sum.nat_ivl_Suc')\n\nlemma harmonic_numbers_2norm:\n  fixes n::nat and r::rat\n  assumes \"n \\<ge> 1\"\n  shows \"pnorm 2 (Harm n) = 2^(nat(\\<lfloor>log 2 n\\<rfloor>))\"\nproof(cases \\<open>n = 1\\<close>)\n  case True\n  have \\<open>prime (2::nat)\\<close>\n    by simp\n  hence \\<open>Harm 1 = 1\\<close>\n    by (simp add: One_rat_def)\n  hence \\<open>pnorm 2 (Harm 1) = pnorm 2 1\\<close>\n    by simp\n  also have \\<open>\\<dots> = 1\\<close>\n    by simp\n  also have \\<open>\\<dots> = 2^(nat(\\<lfloor>log 2 1\\<rfloor>))\\<close>\n  proof-\n    have \\<open>\\<lfloor>log 2 1\\<rfloor> = 0\\<close>\n      by simp      \n    thus ?thesis\n      by auto\n  qed\n  finally show ?thesis\n    using \\<open>n = 1\\<close>\n    by auto\nnext\n  case False\n  hence \\<open>n \\<ge> 2\\<close>\n    using \\<open>n \\<ge> 1\\<close>\n    by auto\n  define l where \\<open>l = nat(\\<lfloor>log 2 n\\<rfloor>)\\<close>\n    (*\n  define H where \\<open>H = (\\<Sum>k = 1..n. (inverse  (of_nat k)))\\<close>\n*)\n  have \\<open>prime (2::nat)\\<close>\n    by simp\n  have \\<open>l \\<ge> 1\\<close>\n  proof-\n    have \\<open>log 2 n \\<ge> 1\\<close>\n      using \\<open>n \\<ge> 2\\<close>\n      by auto\n    hence \\<open>\\<lfloor>log 2 n\\<rfloor> \\<ge> 1\\<close>\n      by simp\n    thus ?thesis \n      using \\<open>l = nat(\\<lfloor>log 2 n\\<rfloor>)\\<close> \\<open>1 \\<le> \\<lfloor>log 2 (real n)\\<rfloor>\\<close> \\<open>l = nat \\<lfloor>log 2 (real n)\\<rfloor>\\<close> nat_mono \n      by presburger            \n  qed\n  hence \\<open>(2::nat)^l \\<ge> 2\\<close>\n  proof -\n    have \"(2::nat) ^ 1 \\<le> 2 ^ l\"\n      by (metis \\<open>1 \\<le> l\\<close> one_le_numeral power_increasing)\n    thus ?thesis\n      by (metis semiring_normalization_rules(33))\n  qed\n  have \\<open>pnorm 2 ((2^l) * Harm n) = 1\\<close>\n  proof-\n    define pre_H where \\<open>pre_H = (\\<Sum>k = 1..(2^l-1). inverse (rat_of_nat k))\\<close>\n    define post_H where \\<open>post_H = (\\<Sum>k = (2^l+1)..n. inverse (rat_of_nat k))\\<close>\n    have \\<open>Harm n = pre_H + (inverse  (of_nat (2^l))) + post_H\\<close>\n    proof-\n      have \\<open>pre_H + (inverse  (of_nat (2^l))) = (\\<Sum>k = 1..(2^l-1). inverse (rat_of_nat k)) \n                  + (inverse  (of_nat (2^l)))\\<close>\n        unfolding pre_H_def\n        by auto\n      also have \\<open>\\<dots> = (\\<Sum>k = 1..2^l. inverse (rat_of_nat k))\\<close>\n        by (metis  \\<open>2 \\<le> 2 ^ l\\<close>  sum_last)\n      finally have \\<open>pre_H + inverse (rat_of_nat (2^l)) = (\\<Sum>k = 1..2 ^ l. inverse (rat_of_nat k))\\<close>\n        by auto \n      moreover have \\<open>(\\<Sum>k = 1..2 ^ l. inverse (rat_of_nat k)) + post_H = Harm n\\<close>\n      proof-\n        have \\<open>(\\<Sum>k = 1..2 ^ l. inverse (rat_of_nat k)) + post_H\n              = (\\<Sum>k = 1..2 ^ l. inverse (rat_of_nat k)) +\n                (\\<Sum>k = 2 ^ l + 1..n. inverse (rat_of_nat k))\\<close>\n          unfolding post_H_def\n          by blast\n        also have \\<open>\\<dots>  = (\\<Sum>k = 1..n. inverse (rat_of_nat k))\\<close>\n        proof-\n          have \\<open>2 ^ l \\<le> n\\<close>\n          proof-\n            have \\<open>2 ^ l =  2 ^ nat \\<lfloor>log 2 (real n)\\<rfloor>\\<close>\n              unfolding l_def\n              by simp\n            also have \\<open>\\<dots> =  2 powi (nat \\<lfloor>log 2 (real n)\\<rfloor>)\\<close>\n              by (metis intpow_int)                           \n            also have \\<open>\\<dots> \\<le>  2 powr (log 2 (real n))\\<close>\n            proof-\n              have \\<open>\\<lfloor>log 2 (real n)\\<rfloor> \\<le> log 2 (real n)\\<close>\n                by simp\n              moreover have \\<open>(2::real) > 1\\<close>\n                by simp\n              ultimately show ?thesis \n                using Transcendental.powr_le_cancel_iff[where x = 2 and a = \"\\<lfloor>log 2 (real n)\\<rfloor>\" \n                    and b = \"log 2 (real n)\"] assms unfolding intpow_def \n                by (simp add: powr_real_of_int)\n            qed\n            also have \\<open>\\<dots> = n\\<close>\n            proof-\n              have \\<open>(2::real) > 1\\<close>\n                by simp                \n              moreover have \\<open>n > 0\\<close>\n                using \\<open>n \\<ge> 2\\<close>\n                by auto\n              ultimately show ?thesis\n                by simp\n            qed\n            finally show ?thesis \n              by simp\n          qed\n          thus ?thesis\n            by (metis le_add2 le_add_diff_inverse sum.ub_add_nat)\n        qed\n        finally have \\<open>(\\<Sum>k = 1..2 ^ l. inverse (rat_of_nat k)) + post_H = \n            (\\<Sum>k = 1..n.  inverse (rat_of_nat k))\\<close>\n          by auto\n        thus ?thesis\n          unfolding pre_H_def\n          using Harm_explicit by auto\n      qed\n      ultimately show ?thesis\n        by linarith\n    qed\n    moreover have \\<open>pnorm 2 ((2^l) * (inverse  (of_nat (2^l)))) = 1\\<close>\n    proof-\n      have \\<open>(2::nat)^l \\<noteq> 0\\<close>\n        by auto\n      hence \\<open>((2::nat)^l) * (inverse  (of_nat ((2::nat)^l))) = 1\\<close>\n      proof -\n        have \"int (2 ^ l) \\<noteq> 0\"\n          using \\<open>2 ^ l \\<noteq> 0\\<close> by linarith\n        hence \"1 = Fract (int (2 ^ l) * 1) (int (2 ^ l) * 1)\"\n          by (metis (no_types) One_rat_def mult_rat_cancel)\n        thus ?thesis\n          by simp\n      qed        \n      hence \\<open>pnorm 2 (((2::rat)^l) * (inverse  (of_nat ((2::nat)^l)))) = pnorm 2 1\\<close>\n        by simp\n      also have \\<open>\\<dots> = 1\\<close>\n        by simp\n      finally show ?thesis \n        by blast\n    qed\n    moreover have \\<open>pnorm 2 ((2^l) * pre_H) < 1\\<close>\n    proof-\n      have \\<open>(2^l) * pre_H = (\\<Sum>k = 1..2 ^ l - 1. (2^l) * inverse (rat_of_nat k) )\\<close>\n        unfolding pre_H_def\n        using Groups_Big.semiring_0_class.sum_distrib_left[where r = \\<open>2^l\\<close> \n            and f = \\<open>(\\<lambda> k. inverse (rat_of_nat k))\\<close> and A = \\<open>{1..(2^l - 1)}\\<close>]\n        by auto\n      hence \\<open>pnorm 2 (2 ^ l * pre_H) =\n              pnorm 2 (\\<Sum>k = 1..2 ^ l - 1. (2 ^ l) * inverse (rat_of_nat k))\\<close>\n        by simp\n      also have \\<open>\\<dots> \\<le>\n              Max ((\\<lambda> k. pnorm 2 ((2 ^ l) * inverse (rat_of_nat k)))`{1..2^l-1})\\<close>\n      proof-\n        have \\<open>pnorm 2 (\\<Sum>k = 1..2 ^ l - 1.  (2 ^ l) * inverse (rat_of_nat k))\n           = pnorm 2 (sum (\\<lambda> k.  (2 ^ l) * inverse (rat_of_nat k)) {1..(2::nat)^l-1})\\<close>\n          by blast\n        also have \\<open>\\<dots> \\<le> Max ((\\<lambda> k. pnorm 2 ((2 ^ l) * inverse (rat_of_nat k) ))`{1..2^l-1})\\<close>\n          using \\<open>prime 2\\<close>  pnorm_sum_le[where p = 2 and A = \\<open>{1..2^l-1}\\<close> \n              and x = \\<open>(\\<lambda> k. (2 ^ l) * inverse (rat_of_nat k))\\<close>]\n          by (metis Nat.le_diff_conv2 \\<open>2 \\<le> 2 ^ l\\<close> add_leD1 atLeastatMost_empty_iff2 \n              finite_atLeastAtMost nat_1_add_1)          \n        finally show ?thesis\n          using \\<open>pnorm 2 (\\<Sum>k = 1..2 ^ l - 1. 2 ^ l * inverse (rat_of_nat k)) \n            \\<le> (MAX k\\<in>{1..2 ^ l - 1}. pnorm 2 (2 ^ l * inverse (rat_of_nat k)))\\<close> by blast          \n      qed\n      also have \\<open>\\<dots> < 1\\<close>\n      proof-\n        have \\<open>finite ((\\<lambda> k. pnorm 2 (2 ^ l) * inverse (rat_of_nat k))`{1..2^l-1})\\<close>\n          by blast          \n        moreover have \\<open>((\\<lambda> k. pnorm 2 ((2 ^ l) * inverse (rat_of_nat k)))`{1..2^l-1}) \\<noteq> {}\\<close>\n        proof-\n          have \\<open>(1::nat) \\<le> (2::nat)^l-1\\<close>\n            using \\<open>(2::nat)^l \\<ge> 2\\<close>\n            by auto\n          hence \\<open>{(1::nat)..(2::nat)^l-1} \\<noteq> {}\\<close>\n            using Set_Interval.order_class.atLeastatMost_empty_iff2[where a = \"1::nat\" \n                and b = \"(2::nat)^l - 1\"]\n            by auto\n          thus ?thesis\n            by blast\n        qed\n        moreover have \\<open>x \\<in> ((\\<lambda> k. pnorm 2 ((2 ^ l) * inverse (rat_of_nat k)))`{1..2^l-1}) \\<Longrightarrow> x < 1\\<close>\n          for x\n        proof-\n          assume \\<open>x \\<in> ((\\<lambda> k. pnorm 2 ((2 ^ l) * inverse (rat_of_nat k)))`{1..2^l-1})\\<close>\n          then obtain k where \\<open>x = pnorm 2 ((2 ^ l) * inverse (rat_of_nat k))\\<close> and \\<open>k \\<in> {1..2^l-1}\\<close>\n            by blast\n          have \\<open>pnorm 2 ((2 ^ l) * inverse (rat_of_nat k)) < 1\\<close>\n          proof-\n            have \\<open>pnorm 2 ((2::rat)^l) = 1/(2::nat)^l\\<close>\n              using  \\<open>prime (2::nat)\\<close> pnorm_primepow[where p = \"(2::nat)\"]\n              by auto\n            moreover have \\<open>pnorm 2 (inverse (rat_of_nat k)) < (2::nat)^l\\<close>\n            proof-\n              have \\<open>2 powi (- pval 2 (inverse (rat_of_nat k))) < (2::nat)^l\\<close>\n              proof-\n                have \\<open>pval 2 (Fract k 1) < l\\<close>\n                proof-\n                  have \\<open>pval 2 (Fract k 1) = multiplicity (2::int) k\\<close>\n                    by (smt Fract_of_nat_eq Suc_1 multiplicity_int_int of_nat_1 of_nat_Suc \n                        pval_of_nat)\n                  also have \\<open>\\<dots> < l\\<close>\n                  proof(rule classical)\n                    assume \\<open>\\<not>(multiplicity 2 (int k) < int l)\\<close>\n                    hence \\<open>multiplicity 2 (int k) \\<ge> int l\\<close>\n                      by simp\n                    hence \\<open>((2::nat)^l) dvd k\\<close>\n                      by (metis (full_types) int_dvd_int_iff multiplicity_dvd' of_nat_numeral\n                          of_nat_power zle_int)\n                    hence \\<open>(2::nat)^l \\<le> k\\<close>\n                      using \\<open>k \\<in> {1..2 ^ l - 1}\\<close> dvd_nat_bounds\n                      by auto\n                    moreover have \\<open>k < (2::nat)^l\\<close>\n                      using  \\<open>k\\<in>{1..(2::nat)^l - 1}\\<close>\n                      by auto                        \n                    ultimately show ?thesis\n                      by linarith \n                  qed\n                  finally show ?thesis\n                    by blast\n                qed\n                hence \\<open>- pval 2 (inverse (rat_of_int k)) < l\\<close>\n                  using \\<open>prime 2\\<close> pval_inverse[where p = \"2\" and x = \\<open>inverse (rat_of_int k)\\<close>] \n                    Fract_of_int_quotient \n                  by auto\n                hence \\<open>2 powr (- pval 2 (inverse (rat_of_int k))) < 2 powr l\\<close>\n                  by auto\n                also have \\<open>\\<dots> = (2::nat)^l\\<close>\n                proof -\n                  have f1: \"\\<not> 2 \\<le> (1::real)\"\n                    by auto\n                  have f2: \"\\<forall>x1. ((1::real) < x1) = (\\<not> x1 \\<le> 1)\"\n                    by force\n                  have \"real (2 ^ l) = 2 ^ l\"\n                    by simp\n                  hence \"real l = log 2 (real (2 ^ l))\"\n                    using f2 f1 by (meson log_of_power_eq)\n                  thus ?thesis\n                    by simp\n                qed\n                finally show ?thesis \n                  unfolding intpow_def\n                  using of_int_of_nat_eq power_inverse powr_real_of_int \n                    \\<open>- pval 2 (inverse (rat_of_int (int k))) < int l\\<close> by auto \n              qed\n              moreover have \\<open>pnorm 2 (inverse (rat_of_nat k)) = 2 powi (- pval 2 (inverse (rat_of_nat k)))\\<close>\n              proof-\n                have \\<open>k \\<noteq> 0\\<close>\n                  using \\<open>k\\<in>{1..2^l - 1}\\<close>\n                  by simp\n                hence \\<open>inverse (rat_of_int k) \\<noteq> 0\\<close>\n                  by auto\n                thus ?thesis\n                  using \\<open>prime 2\\<close> \\<open>k \\<noteq> 0\\<close>\n                  unfolding pnorm_def intpow_def\n                  apply auto\n                  by (simp add: powr_realpow)                                   \n              qed\n              ultimately show ?thesis\n                by auto                \n            qed\n            moreover have \\<open>pnorm 2 ((2::rat)^l) > 0\\<close>\n            proof-\n              have \\<open>(2::rat)^l \\<noteq> 0\\<close>\n                by simp                  \n              moreover have \\<open>pnorm 2 ((2::rat)^l) \\<ge> 0\\<close>\n                by (simp add: pnorm_nonneg)\n              ultimately show ?thesis\n                by (simp add: less_eq_real_def)\n            qed\n            moreover have \\<open>pnorm 2 (inverse (rat_of_nat k)) > 0\\<close>\n            proof-\n              have \\<open>inverse (rat_of_nat k) \\<noteq> 0\\<close>\n                using \\<open>k \\<in> {1..2^l-1}\\<close>\n                by simp\n              moreover have \\<open>pnorm 2 (inverse (rat_of_nat k)) \\<ge> 0\\<close>                  \n                using \\<open>prime (2::nat)\\<close>\n                by (simp add: pnorm_nonneg)                  \n              ultimately show ?thesis\n                using  \\<open>prime (2::nat)\\<close>\n                by (simp add: pnorm_pos)\n            qed\n            ultimately have \\<open>(pnorm 2 ((2::rat)^l))*(pnorm 2 (inverse (rat_of_nat k))) \n                  < (1/(2::nat)^l)*((2::nat)^l)\\<close>\n              by simp\n            also have \\<open>\\<dots> = 1\\<close>\n            proof-\n              have \\<open>(2::nat)^l \\<noteq> 0\\<close>\n                by simp                  \n              thus ?thesis\n                by simp \n            qed\n            finally have \\<open>(pnorm 2 ((2::rat)^l))*(pnorm 2 (inverse (rat_of_nat k))) < 1\\<close>\n              by blast\n            moreover have \\<open>(pnorm 2 ((2::rat)^l))*(pnorm 2 (inverse (rat_of_nat k))) \n                  = pnorm 2 (2 ^ l * inverse (rat_of_nat k))\\<close>\n              using \\<open>prime 2\\<close>\n              by simp\n            ultimately show ?thesis\n              by auto              \n          qed\n          thus ?thesis\n            using \\<open>x = pnorm 2 (2 ^ l * inverse (rat_of_nat k))\\<close> by blast\n\n        qed\n        ultimately show ?thesis \n          using Lattices_Big.linorder_class.Max_less_iff\n            [where A = \"((\\<lambda> k. pnorm 2 (Fract (2 ^ l) (int k)))`{1..2^l-1})\"]\n          by auto\n      qed\n      finally show \\<open>pnorm 2 (2 ^ l * pre_H) < 1\\<close>\n        by blast\n    qed\n    ultimately have \\<open>pnorm 2 ((2^l) * (inverse  (of_nat (2^l))) + (2^l) * pre_H) = 1\\<close>\n      using pnorm_unit_ball[where p = 2 and x = \"(2^l) *  (inverse  (of_nat (2^l)))\" and y = \"(2^l) * pre_H\"]\n      by simp\n    moreover have \\<open>pnorm 2 ((2^l) * post_H) < 1\\<close>\n    proof(cases \\<open>2^l + 1 \\<le> n\\<close>)\n      case True\n      have \\<open>pnorm 2 ((2^l) * post_H) = pnorm 2 (\\<Sum>k = 2 ^ l + 1..n.  (2 ^ l)*(inverse (rat_of_int k)))\\<close>\n      proof-\n        have \\<open>(2^l) * post_H = (\\<Sum>k = 2 ^ l+1..n. (2 ^ l)*(inverse (rat_of_int k)))\\<close>\n          unfolding post_H_def\n          using Groups_Big.semiring_0_class.sum_distrib_left[where r = \\<open>2^l\\<close> \n              and f = \\<open>(\\<lambda> k. inverse (rat_of_int k))\\<close> and A = \\<open>{2 ^ l+1..n}\\<close>]\n          by auto\n        thus ?thesis\n          by simp\n      qed\n      also have \\<open>\\<dots>\n           = pnorm 2 (sum (\\<lambda> k. (2 ^ l)*(inverse (rat_of_int k))) {2 ^ l + 1..n})\\<close>\n        by blast\n      also have \\<open>\\<dots>\n           \\<le> Max ((\\<lambda> k. pnorm 2 ((2 ^ l)*(inverse (rat_of_int k)))) ` {2 ^ l + 1..n})\\<close>\n      proof-\n        have \\<open>finite {2 ^ l + 1..n}\\<close>\n          by simp          \n        moreover have \\<open>{2 ^ l + 1..n} \\<noteq> {}\\<close>\n          using True \n          by auto          \n        ultimately show ?thesis \n          using \\<open>prime 2\\<close>  pnorm_sum_le[where p = 2 and A = \\<open>{2 ^ l + 1..n}\\<close> \n              and x = \\<open>(\\<lambda> k. (2 ^ l)*(inverse (rat_of_int k)))\\<close>]\n          by auto\n      qed\n      finally have \\<open>pnorm 2 ((2^l) * post_H) \\<le> \n          Max ((\\<lambda> k. pnorm 2 ((2 ^ l)*(inverse (rat_of_int k)))) ` {2 ^ l + 1..n})\\<close>\n        using \\<open>pnorm 2 (2 ^ l * post_H) \n            = pnorm 2 (\\<Sum>k = 2 ^ l + 1..n. 2 ^ l * inverse (rat_of_int (int k)))\\<close> \n          \\<open>pnorm 2 (\\<Sum>k = 2 ^ l + 1..n. 2 ^ l * inverse (rat_of_int (int k))) \n          \\<le> (MAX k\\<in>{2 ^ l + 1..n}. pnorm 2 (2 ^ l * inverse (rat_of_int (int k))))\\<close> \n        by linarith        \n      moreover have \\<open>((\\<lambda> k. pnorm 2 ((2 ^ l)*(inverse (rat_of_int k)))) ` {2 ^ l + 1..n}) \\<noteq> {}\\<close>\n        using True \n        by auto        \n      moreover have \\<open>finite ((\\<lambda> k. pnorm 2 ((2 ^ l)*(inverse (rat_of_int k)))) ` {2 ^ l + 1..n})\\<close>\n        by blast        \n      moreover have \\<open>x \\<in> (\\<lambda> k. pnorm 2 ((2 ^ l)*(inverse (rat_of_int k)))) ` {2 ^ l + 1..n} \\<Longrightarrow> x < 1\\<close>\n        for x\n      proof-\n        assume \\<open>x \\<in> (\\<lambda> k. pnorm 2 ((2 ^ l)*(inverse (rat_of_int k)))) ` {2 ^ l + 1..n}\\<close>\n        then obtain t where \\<open>t \\<in> {2 ^ l + 1..n}\\<close> and \\<open>x = pnorm 2 ((2 ^ l)*(inverse (rat_of_nat t)))\\<close>\n          by auto\n        have  \\<open>x = (pnorm 2 (2 ^ l)) * (pnorm 2 (inverse (rat_of_nat t)))\\<close>\n          using \\<open>prime 2\\<close> \\<open>x = pnorm 2 ((2 ^ l)*(inverse  (rat_of_nat t)))\\<close> pnorm_mult by blast         \n        moreover have \\<open>pnorm 2 (2 ^ l) = 1/(2^l)\\<close>\n          using \\<open>prime 2\\<close> pval_primepow[where p = \"2::nat\"]\n          by (metis of_int_numeral of_nat_numeral pnorm_primepow)          \n        moreover have \\<open>pnorm 2 (inverse  (rat_of_nat t)) < 2^l\\<close>\n        proof(rule classical)\n          assume \\<open>\\<not> (pnorm 2 (inverse  (rat_of_nat t)) < 2^l)\\<close>\n          hence \\<open>pnorm 2 (inverse  (rat_of_nat t)) \\<ge> 2^l\\<close>\n            by auto\n          moreover have \\<open>2 powi l = 2^l\\<close>\n            by auto            \n          ultimately have \\<open>pnorm 2 (inverse  (rat_of_nat t)) \\<ge> 2 powi l\\<close>\n            by auto\n          moreover have \\<open>pnorm 2 (inverse  (rat_of_nat t)) \n                          = 2 powi (-pval 2 (inverse  (rat_of_nat t)))\\<close>\n          proof-\n            have \\<open>t \\<noteq> 0\\<close>\n              using \\<open>t \\<in> {2^l + 1 .. n}\\<close>\n              by simp\n            hence \\<open>inverse (rat_of_nat t) \\<noteq> 0\\<close>\n            proof -\n              have \"\\<not> int t \\<le> 0\"\n                by (metis \\<open>t \\<noteq> 0\\<close> of_nat_le_0_iff)\n              hence \"\\<not> inverse  (int t) \\<le> 0\"\n                by (simp add: Fract_le_zero_iff)\n              thus ?thesis\n                by auto\n            qed              \n            thus ?thesis \n              unfolding intpow_def pnorm_def\n              apply auto\n              by (simp add: powr_realpow) \n          qed\n          ultimately have \\<open>-pval 2 (inverse  (rat_of_nat t)) \\<ge> l\\<close>\n            by simp            \n          hence \\<open>-(multiplicity 2 (fst (quotient_of (inverse  (rat_of_nat t)))))\n               + (multiplicity 2 (snd (quotient_of (inverse  (rat_of_nat t)))))\n                     \\<ge> l\\<close>\n            unfolding pval_def \n            by auto\n          have \\<open>quotient_of (inverse (rat_of_nat t)) = (1, t)\\<close>\n          proof-\n            have \\<open>inverse (rat_of_nat t) = Fract 1 t\\<close>\n              by (metis Fract_of_nat_eq inverse_rat)\n            moreover have \\<open>t > 0\\<close>\n              using \\<open>t \\<in> {2^l + 1 .. n}\\<close>\n              by simp\n            moreover have \\<open>coprime 1 t\\<close>\n              by simp\n            ultimately show ?thesis\n              by (simp add: quotient_of_Fract)             \n          qed\n          hence \\<open>fst (quotient_of (inverse  (rat_of_nat t))) = 1\\<close>\n            by simp\n          moreover have \\<open>snd (quotient_of (inverse  (rat_of_nat t))) = t\\<close>\n          proof -\n            have \"Rat.normalize (1, int t) = quotient_of (inverse (rat_of_nat t))\"\n              by (metis (full_types) Fract_of_int_eq inverse_rat of_int_of_nat_eq quotient_of_Fract)\n            hence \"Rat.normalize (1, int t) = (1, snd (quotient_of (inverse (rat_of_nat t))))\"\n              by (metis calculation prod.exhaust_sel)\n            thus ?thesis\n              by (metis (full_types) Fract_of_int_eq inverse_rat normalize_eq of_int_eq_iff)\n          qed            \n          ultimately have \\<open>- int(multiplicity (2::int) 1) + int(multiplicity (2::int) t) \\<ge> l\\<close>\n            using \\<open>-(multiplicity 2 (fst (quotient_of (inverse  (rat_of_nat t)))))\n               + (multiplicity 2 (snd (quotient_of (inverse  (rat_of_nat t)))))\n                     \\<ge> l\\<close>\n            by auto\n          moreover have \\<open>multiplicity (2::int) 1 = 0\\<close>\n            by simp\n          ultimately have \\<open>multiplicity (2::int) t \\<ge> l\\<close>\n            by auto\n          hence \\<open>2^l dvd t\\<close>\n            by (metis int_dvd_int_iff multiplicity_dvd' of_nat_numeral of_nat_power)\n          hence \\<open>\\<exists> k::nat. 2^l * k = t\\<close>\n            by auto\n          then obtain k::nat where \\<open>2^l * k = t\\<close>\n            by blast\n          have \\<open>k \\<ge> 2\\<close>\n          proof(rule classical)\n            assume \\<open>\\<not>(k \\<ge> 2)\\<close>\n            hence \\<open>k < 2\\<close>\n              by simp\n            moreover have \\<open>k \\<noteq> 0\\<close>\n            proof(rule classical)\n              assume \\<open>\\<not>(k \\<noteq> 0)\\<close>\n              hence \\<open>k = 0\\<close>\n                by simp\n              hence \\<open>t = 0\\<close>\n                using \\<open>2^l * k = t\\<close>\n                by auto\n              thus ?thesis\n                using \\<open>t \\<in> {2^l + 1 .. n}\\<close>\n                by auto\n            qed\n            moreover have \\<open>k \\<noteq> 1\\<close>\n            proof(rule classical)\n              assume \\<open>\\<not>(k \\<noteq> 1)\\<close>\n              hence \\<open>k = 1\\<close>\n                by simp\n              hence \\<open>t = 2^l\\<close>\n                using \\<open>2^l * k = t\\<close>\n                by auto\n              thus ?thesis\n                using \\<open>t \\<in> {2^l + 1 .. n}\\<close>\n                by auto\n            qed\n            ultimately show ?thesis\n              by auto\n          qed\n          hence \\<open>2^(Suc l) \\<le> t\\<close>\n            using \\<open>2 ^ l * k = t\\<close> \n            by auto\n          hence \\<open>2^(Suc l) \\<le> n\\<close>\n            using \\<open>t \\<in> {2^l + 1 .. n}\\<close>\n            by auto\n          moreover have \\<open>n < 2^(Suc l)\\<close>\n          proof -\n            have f1: \"\\<forall>n na. (n \\<le> na) = (int n + - 1 * int na \\<le> 0)\"\n              by auto\n            have f2: \"int (Suc (nat \\<lfloor>log 2 (real n)\\<rfloor>)) + - 1 * int (Suc l) \\<le> 0\"\n              by (simp add: l_def)\n            have f3: \"(- 1 * log 2 (real n) + real (Suc l) \\<le> 0) = (0 \\<le> log 2 (real n) + - 1 * real (Suc l))\"\n              by fastforce\n            have f4: \"real (Suc l) + - 1 * log 2 (real n) = - 1 * log 2 (real n) + real (Suc l)\"\n              by auto\n            have f5: \"\\<forall>n na. \\<not> 2 ^ n \\<le> na \\<or> real n + - 1 * log 2 (real na) \\<le> 0\"\n              by (simp add: le_log2_of_power)\n            have f6: \"\\<forall>x0 x1. (- 1 * int x0 + int (2 ^ x1) \\<le> 0) = (0 \\<le> int x0 + - 1 * int (2 ^ x1))\"\n              by auto\n            have f7: \"\\<forall>x0 x1. int (2 ^ x1) + - 1 * int x0 = - 1 * int x0 + int (2 ^ x1)\"\n              by auto\n            have \"\\<not> 0 \\<le> log 2 (real n) + - 1 * real (Suc l)\"\n              using f2 by linarith\n            then have \"\\<not> 0 \\<le> int n + - 1 * int (2 ^ Suc l)\"\n              using f7 f6 f5 f4 f3 f1 by (metis (no_types))\n            then show ?thesis\n              by linarith\n          qed                    \n          ultimately show ?thesis\n            by auto\n        qed\n        moreover have \\<open>pnorm 2 (2 ^ l) \\<ge> 0\\<close>\n          by (simp add: pnorm_nonneg)\n        moreover have \\<open>pnorm 2 (inverse  (rat_of_nat t)) \\<ge> 0\\<close>\n          by (simp add: pnorm_nonneg)\n        ultimately show ?thesis \n          by simp\n      qed\n      ultimately show ?thesis\n        by (smt Max_in)\n    next\n      case False\n      hence \\<open>2 ^ l + 1 > n\\<close>\n        by simp\n      hence \\<open>{2 ^ l + 1..n} = {}\\<close>\n        by simp\n      hence \\<open>post_H = 0\\<close>\n        unfolding post_H_def\n        by simp        \n      hence \\<open>(2^l) * post_H = 0\\<close>\n        by (simp add: \\<open>post_H = 0\\<close>)        \n      thus ?thesis\n        unfolding pnorm_def\n        by auto\n    qed\n    ultimately have \\<open>pnorm 2 (((2^l) *  (inverse  (of_nat (2^l))) \n                                  + (2^l) * pre_H) + ((2^l) * post_H)) = 1\\<close>\n      using pnorm_unit_ball[where p = 2 and x = \"(2^l) *  (inverse  (of_nat (2^l))) + (2^l) * pre_H\" \n          and y = \"(2^l) * post_H\"]\n      by simp\n    moreover have \\<open>2 ^ l * inverse (rat_of_nat (2 ^ l)) + 2 ^ l * pre_H + 2 ^ l * post_H \n          = 2^l * Harm n\\<close>\n      using \\<open>Harm n = pre_H + (inverse  (of_nat (2^l))) + post_H\\<close>\n      by (simp add: semiring_normalization_rules(34))      \n    ultimately show ?thesis\n      by auto      \n  qed\n  hence \\<open>(pnorm 2 (2^l)) * (pnorm 2 (Harm n)) = 1\\<close>\n    using Pnorm.pnorm_mult \\<open>prime 2\\<close>\n    by auto\n  hence \\<open>(1/2^l) * (pnorm 2 (Harm n)) = 1\\<close>\n  proof-\n    have \\<open>prime (2::nat)\\<close>\n      by simp\n    hence \\<open>pnorm 2 (2^l) = 1/2^l\\<close>\n      using pnorm_primepow[where p = 2 and l = \"l\"] \n      by simp\n    thus ?thesis\n      using \\<open>pnorm 2 (2 ^ l) * pnorm 2 (Harm n) = 1\\<close> \n      by auto\n  qed\n  hence \\<open>pnorm 2 (Harm n) = 2^l\\<close>\n    by simp\n  thus ?thesis\n    by (simp add: l_def)\nqed\n\nlemma Harm_mono: \"m \\<noteq> 0 \\<Longrightarrow> 2*m \\<le> n \\<Longrightarrow> pnorm 2 (Harm m) < pnorm 2 (Harm n)\"\nproof-\n  assume \\<open>m \\<noteq> 0\\<close> and \\<open>2*m \\<le> n\\<close>\n  have \\<open>m \\<ge> 1\\<close>\n    using \\<open>m \\<noteq> 0\\<close> by linarith\n  have \\<open>pnorm 2 (Harm m) =  2 ^ nat \\<lfloor>log 2 (real m)\\<rfloor>\\<close>\n    using harmonic_numbers_2norm[where n = \"m\"] \\<open>m \\<noteq> 0\\<close>    \n    by auto\n  moreover have \\<open>pnorm 2 (Harm n) =  2 ^ nat \\<lfloor>log 2 (real n)\\<rfloor>\\<close>\n    using harmonic_numbers_2norm[where n = \"n\"] \\<open>2 * m \\<le> n\\<close> \\<open>m \\<noteq> 0\\<close> by linarith \n  moreover have \\<open>(2::nat) ^ nat \\<lfloor>log 2 (real m)\\<rfloor> < (2::nat) ^ nat \\<lfloor>log 2 (real n)\\<rfloor>\\<close>\n  proof-\n    have \\<open>log 2 (real m) + 1 = log 2 (real m) + log 2 (2::real)\\<close>\n    proof-\n      have \\<open>log 2 (real 2) = 1\\<close>\n        by simp\n      thus ?thesis \n        by simp\n    qed\n    also have \\<open>\\<dots> = log 2 ((real m) * (2::real)) \\<close>\n    proof-\n      have \\<open>(2::real) > 0\\<close>\n        by simp\n      moreover have \\<open>(2::real) \\<noteq> 1\\<close>\n        by simp\n      ultimately show ?thesis\n        using \\<open>m \\<ge> 1\\<close> log_mult[where a = 2 and x = \"real m\" and y = \"2::real\"]         \n        by simp\n    qed\n    also have \\<open>\\<dots> = log 2 (2*real m) \\<close>\n    proof-\n      have \\<open>(real m)*(2::real) = 2*m\\<close>\n        by auto\n      thus ?thesis\n        by (simp add: \\<open>real m * 2 = real (2 * m)\\<close>)             \n    qed\n    also have \\<open>\\<dots> \\<le> log 2 (real n)\\<close>\n      using \\<open>2*m \\<le> n\\<close> \\<open>m \\<noteq> 0\\<close> by auto\n    finally have \\<open>log 2 (real m) + 1 \\<le> log 2 (real n)\\<close>\n      by blast\n    hence \\<open>\\<lfloor>log 2 (real m)\\<rfloor> < \\<lfloor>log 2 (real n)\\<rfloor>\\<close>\n      by linarith\n    moreover have \\<open>\\<lfloor>log 2 (real m)\\<rfloor> \\<ge> 0\\<close>\n    proof-\n      have \\<open>log 2 (real m) \\<ge> 0\\<close>\n        using \\<open>m \\<ge> 1\\<close> by auto\n      thus ?thesis by auto\n    qed\n    ultimately have \\<open>nat \\<lfloor>log 2 (real m)\\<rfloor> < nat \\<lfloor>log 2 (real n)\\<rfloor>\\<close>\n      using nat_less_eq_zless by blast      \n    moreover have \\<open>(2::nat) > 1\\<close>\n      by auto\n    ultimately show ?thesis\n      using power_strict_increasing[where a = \"2::nat\" and n = \"nat \\<lfloor>log 2 (real m)\\<rfloor>\" \n          and N = \"nat \\<lfloor>log 2 (real n)\\<rfloor>\"] by blast\n  qed\n  ultimately show ?thesis \n    by auto\nqed\n\nsubsection \\<open>Main results\\<close>\n\ntext\\<open>The following result is due to L. Taeisinger ~\\cite{theisinger1915bemerkung}.\\<close>\ntheorem Taeisinger:\n  fixes n :: nat\n  assumes \\<open>n \\<ge> 2\\<close>\n  shows \\<open>Harm n \\<notin> \\<int>\\<close>\nproof-\n  have  \\<open>prime (2::nat)\\<close>\n    by simp\n  moreover have \\<open>pnorm 2 (Harm n) > 1\\<close>    \n    using harmonic_numbers_2norm[where n = \"n\"] \\<open>n \\<ge> 2\\<close> \n    by auto\n  ultimately show ?thesis\n    using integers_pnorm[where x = \"Harm n\"] by smt\nqed\n\ntext\\<open>The following result is due to J. K{\\\"u}rsch{\\'a}k  ~\\cite{kurschak1918harmonic}.\\<close>\ntheorem Kurschak:\n  fixes n m :: nat\n  assumes \\<open>m + 2 \\<le> n\\<close>\n  shows \\<open>Harm n - Harm m \\<notin> \\<int>\\<close>\nproof(cases \\<open>2*m \\<le> n\\<close>)\n  case True show ?thesis\n  proof(cases \\<open>m = 0\\<close>)\n    case True thus ?thesis using Taeisinger assms by auto\n  next\n    case False\n    have \\<open>n \\<ge> 2\\<close>\n      using \\<open>m+2 \\<le> n\\<close> by auto\n    have \\<open>prime (2::nat)\\<close>\n      by auto\n    have \\<open>Harm n = (Harm n - Harm m) + (Harm m)\\<close>\n      by simp\n    hence \\<open>pnorm 2 (Harm n) \\<le> max (pnorm 2 (Harm n - Harm m)) (pnorm 2 (Harm m))\\<close>\n      using pnorm_add_le[where p = \"2::nat\" and x = \"Harm n - Harm m\" and y = \"Harm m\"] by simp\n    moreover have \\<open>pnorm 2 (Harm m) < pnorm 2 (Harm n)\\<close>\n      by (simp add: False Harm_mono True)      \n    ultimately have \\<open>pnorm 2 (Harm n) \\<le> pnorm 2 (Harm n - Harm m)\\<close>\n      by linarith\n    moreover have \\<open>1 < pnorm 2 (Harm n)\\<close>\n      using harmonic_numbers_2norm[where n = \"n\"] \\<open>n \\<ge> 2\\<close> by auto\n    ultimately have \\<open>1 < pnorm 2 (Harm n - Harm m)\\<close>\n      by auto\n    thus ?thesis\n      using integers_pnorm[where x = \"Harm n - Harm m\"] \\<open>prime 2\\<close> by smt\n  qed\nnext\n  case False\n  have \\<open>n \\<ge> m\\<close>\n    using add_leE assms by blast\n  have \\<open>Harm n - Harm m < 1\\<close>\n    using False Harm_diff_less_1 assms by auto    \n  moreover have \\<open>0 < Harm n - Harm m\\<close>\n    using Harm_incre \\<open>m+2 \\<le> n\\<close> by simp\n  have f1: \"sgn (Harm n - Harm m) = 1\"\n    by (metis \\<open>0 < Harm n - Harm m\\<close> sgn_pos)\n  have \"0 \\<le> Harm n - Harm m\"\n    by (metis \\<open>0 < Harm n - Harm m\\<close> less_eq_rat_def)\n  thus ?thesis using f1 \\<open>Harm n - Harm m < 1\\<close> frac_eq_0_iff sgn_if zero_neq_one frac_eq by metis\nqed\n\nend\n\n", "meta": {"author": "josephcmac", "repo": "Pnorm", "sha": "fd884075ef822665f2e9a8783b800fe868f74e92", "save_path": "github-repos/isabelle/josephcmac-Pnorm", "path": "github-repos/isabelle/josephcmac-Pnorm/Pnorm-fd884075ef822665f2e9a8783b800fe868f74e92/Harmonic_2_adic.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8539127417985636, "lm_q2_score": 0.8740772400852111, "lm_q1q2_score": 0.746385692624884}}
{"text": "(*  \n  Title:    Random_Permutations.thy\n  Author:   Manuel Eberl, TU M\u00fcnchen\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 \"~~/src/HOL/Probability/Probability\" Set_Permutations\nbegin\n\n(* TODO Move *)\ndeclare bind_pmf_cong [fundef_cong]\n\nadhoc_overloading Monad_Syntax.bind bind_pmf\n\nlemma pmf_bind_pmf_of_set:\n  assumes \"A \\<noteq> {}\" \"finite A\"\n  shows   \"pmf (bind_pmf (pmf_of_set A) f) x = \n             (\\<Sum>xa\\<in>A. pmf (f xa) x) / real_of_nat (card A)\" (is \"?lhs = ?rhs\")\nproof -\n  from assms have \"ereal ?lhs = ereal ?rhs\"\n    by (subst ereal_pmf_bind) (simp_all add: nn_integral_pmf_of_set max_def pmf_nonneg)\n  thus ?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>\nlemma indicator_UN_disjoint:\n  assumes \"finite A\" \"disjoint_family_on f A\"\n  shows   \"indicator (UNION A f) x = (\\<Sum>y\\<in>A. indicator (f y) x)\"\n  using assms by (induction A rule: finite_induct)\n                 (auto simp: disjoint_family_on_def indicator_def split: if_splits)\n\ntext \\<open>\n  The union of an infinite disjoint family of non-empty sets is infinite.\n\\<close>\nlemma infinite_disjoint_family_imp_infinite_UNION:\n  assumes \"\\<not>finite A\" \"\\<And>x. x \\<in> A \\<Longrightarrow> f x \\<noteq> {}\" \"disjoint_family_on f A\"\n  shows   \"\\<not>finite (UNION A f)\"\nproof -\n  def g \\<equiv> \"\\<lambda>x. SOME y. y \\<in> f x\"\n  have g: \"g x \\<in> f x\" if \"x \\<in> A\" for x\n    unfolding g_def by (rule someI_ex, insert assms(2) that) blast\n  have inj_on_g: \"inj_on g A\"\n  proof (rule inj_onI, rule ccontr)\n    fix x y assume A: \"x \\<in> A\" \"y \\<in> A\" \"g x = g y\" \"x \\<noteq> y\"\n    with g[of x] g[of y] have \"g x \\<in> f x\" \"g x \\<in> f y\" by auto\n    with A `x \\<noteq> y` assms show False\n      by (auto simp: disjoint_family_on_def inj_on_def)\n  qed\n  from g have \"g ` A \\<subseteq> UNION A f\" by blast\n  moreover from inj_on_g \\<open>\\<not>finite A\\<close> have \"\\<not>finite (g ` A)\"\n    using finite_imageD by blast\n  ultimately show ?thesis using finite_subset by blast\nqed\n\ntext \\<open>\n  Choosing an element uniformly at random from the union of a disjoint family \n  of finite non-empty sets with the same size is the same as first choosing a set \n  from the family uniformly at random and then choosing an element from the chosen set \n  uniformly at random.  \n\\<close>\nlemma pmf_of_set_UN:\n  assumes \"finite (UNION A f)\" \"A \\<noteq> {}\" \"\\<And>x. x \\<in> A \\<Longrightarrow> f x \\<noteq> {}\"\n          \"\\<And>x. x \\<in> A \\<Longrightarrow> card (f x) = n\" \"disjoint_family_on f A\"\n  shows   \"pmf_of_set (UNION A f) = do {x \\<leftarrow> pmf_of_set A; pmf_of_set (f x)}\"\n            (is \"?lhs = ?rhs\")\nproof (intro pmf_eqI)\n  fix x\n  from assms have [simp]: \"finite A\"\n    using infinite_disjoint_family_imp_infinite_UNION[of A f] by blast\n  from assms have \"ereal (pmf (pmf_of_set (UNION A f)) x) =\n    ereal (indicator (\\<Union>x\\<in>A. f x) x / real (card (\\<Union>x\\<in>A. f x)))\"\n    by (subst pmf_of_set) auto\n  also from assms have \"card (\\<Union>x\\<in>A. f x) = card A * n\"\n    by (subst card_UN_disjoint) (auto simp: disjoint_family_on_def)\n  also from assms \n    have \"indicator (\\<Union>x\\<in>A. f x) x / real \\<dots> = \n              indicator (\\<Union>x\\<in>A. f x) x / (n * real (card A))\"\n      by (simp add: setsum_divide_distrib [symmetric] mult_ac)\n  also from assms have \"indicator (\\<Union>x\\<in>A. f x) x = (\\<Sum>y\\<in>A. indicator (f y) x)\"\n    by (intro indicator_UN_disjoint) simp_all\n  also from assms have \"ereal ((\\<Sum>y\\<in>A. indicator (f y) x) / (real n * real (card A))) =\n                          ereal (pmf ?rhs x)\"\n    by (subst pmf_bind_pmf_of_set) (simp_all add: setsum_divide_distrib)\n  finally show \"pmf ?lhs x = pmf ?rhs x\" by simp\nqed\n\n(* END TODO *)\n\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 \"finite A\" \"A \\<noteq> {}\" \"y \\<in> set_pmf (pmf_of_set A)\"\n  moreover from this have \"card A > 0\" by (simp add: card_gt_0_iff)\n  ultimately 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\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 \"finite A\" \"A \\<noteq> {}\" \"y \\<in> set_pmf (pmf_of_set A)\"\n  moreover from this have \"card A > 0\" by (simp add: card_gt_0_iff)\n  ultimately 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:\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", "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_Permutations.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127529517043, "lm_q2_score": 0.8740772286044095, "lm_q1q2_score": 0.7463856925699875}}
{"text": "(* Title:      HOL/Analysis/Cross3.thy\n   Author:     L C Paulson, University of Cambridge\n\nPorted from HOL Light\n*)\n\nsection\\<open>Vector Cross Products in 3 Dimensions\\<close>\n\ntheory \"Cross3\"\n  imports Determinants Cartesian_Euclidean_Space\nbegin\n\ncontext includes no_Set_Product_syntax \nbegin \\<comment>\\<open>locally disable syntax for set product, to avoid warnings\\<close>\n\ndefinition\\<^marker>\\<open>tag important\\<close> cross3 :: \"[real^3, real^3] \\<Rightarrow> real^3\"  (infixr \"\\<times>\" 80)\n  where \"a \\<times> b \\<equiv>\n    vector [a$2 * b$3 - a$3 * b$2,\n            a$3 * b$1 - a$1 * b$3,\n            a$1 * b$2 - a$2 * b$1]\"\n\nend\n\nbundle cross3_syntax begin\nnotation cross3 (infixr \"\\<times>\" 80)\nno_notation Product_Type.Times (infixr \"\\<times>\" 80)\nend\n\nbundle no_cross3_syntax begin\nno_notation cross3 (infixr \"\\<times>\" 80)\nnotation Product_Type.Times (infixr \"\\<times>\" 80)\nend\n\nunbundle cross3_syntax\n\nsubsection\\<open> Basic lemmas\\<close>\n\nlemmas cross3_simps = cross3_def inner_vec_def sum_3 det_3 vec_eq_iff vector_def algebra_simps\n\nlemma dot_cross_self: \"x \\<bullet> (x \\<times> y) = 0\" \"x \\<bullet> (y \\<times> x) = 0\" \"(x \\<times> y) \\<bullet> y = 0\" \"(y \\<times> x) \\<bullet> y = 0\"\n  by (simp_all add: orthogonal_def cross3_simps)\n\nlemma  orthogonal_cross: \"orthogonal (x \\<times> y) x\" \"orthogonal (x \\<times> y) y\"  \n                        \"orthogonal y (x \\<times> y)\" \"orthogonal (x \\<times> y) x\"\n  by (simp_all add: orthogonal_def dot_cross_self)\n\nlemma  cross_zero_left [simp]: \"0 \\<times> x = 0\" and cross_zero_right [simp]: \"x \\<times> 0 = 0\" for x::\"real^3\"\n  by (simp_all add: cross3_simps)\n\nlemma  cross_skew: \"(x \\<times> y) = -(y \\<times> x)\" for x::\"real^3\"\n  by (simp add: cross3_simps)\n\nlemma  cross_refl [simp]: \"x \\<times> x = 0\" for x::\"real^3\"\n  by (simp add: cross3_simps)\n\nlemma  cross_add_left: \"(x + y) \\<times> z = (x \\<times> z) + (y \\<times> z)\" for x::\"real^3\"\n  by (simp add: cross3_simps)\n\nlemma  cross_add_right: \"x \\<times> (y + z) = (x \\<times> y) + (x \\<times> z)\" for x::\"real^3\"\n  by (simp add: cross3_simps)\n\nlemma  cross_mult_left: \"(c *\\<^sub>R x) \\<times> y = c *\\<^sub>R (x \\<times> y)\" for x::\"real^3\"\n  by (simp add: cross3_simps)\n\nlemma  cross_mult_right: \"x \\<times> (c *\\<^sub>R y) = c *\\<^sub>R (x \\<times> y)\" for x::\"real^3\"\n  by (simp add: cross3_simps)\n\nlemma  cross_minus_left [simp]: \"(-x) \\<times> y = - (x \\<times> y)\" for x::\"real^3\"\n  by (simp add: cross3_simps)\n\nlemma  cross_minus_right [simp]: \"x \\<times> -y = - (x \\<times> y)\" for x::\"real^3\"\n  by (simp add: cross3_simps)\n\nlemma  left_diff_distrib: \"(x - y) \\<times> z = x \\<times> z - y \\<times> z\" for x::\"real^3\"\n  by (simp add: cross3_simps)\n\nlemma  right_diff_distrib: \"x \\<times> (y - z) = x \\<times> y - x \\<times> z\" for x::\"real^3\"\n  by (simp add: cross3_simps)\n\nhide_fact (open) left_diff_distrib right_diff_distrib\n\nproposition Jacobi: \"x \\<times> (y \\<times> z) + y \\<times> (z \\<times> x) + z \\<times> (x \\<times> y) = 0\" for x::\"real^3\"\n  by (simp add: cross3_simps)\n\nproposition Lagrange: \"x \\<times> (y \\<times> z) = (x \\<bullet> z) *\\<^sub>R y - (x \\<bullet> y) *\\<^sub>R z\"\n  by (simp add: cross3_simps) (metis (full_types) exhaust_3)\n\nproposition cross_triple: \"(x \\<times> y) \\<bullet> z = (y \\<times> z) \\<bullet> x\"\n  by (simp add: cross3_def inner_vec_def sum_3 vec_eq_iff algebra_simps)\n\nlemma  cross_components:\n   \"(x \\<times> y)$1 = x$2 * y$3 - y$2 * x$3\" \"(x \\<times> y)$2 = x$3 * y$1 - y$3 * x$1\" \"(x \\<times> y)$3 = x$1 * y$2 - y$1 * x$2\"\n  by (simp_all add: cross3_def inner_vec_def sum_3 vec_eq_iff algebra_simps)\n\nlemma  cross_basis: \"(axis 1 1) \\<times> (axis 2 1) = axis 3 1\" \"(axis 2 1) \\<times> (axis 1 1) = -(axis 3 1)\" \n                   \"(axis 2 1) \\<times> (axis 3 1) = axis 1 1\" \"(axis 3 1) \\<times> (axis 2 1) = -(axis 1 1)\" \n                   \"(axis 3 1) \\<times> (axis 1 1) = axis 2 1\" \"(axis 1 1) \\<times> (axis 3 1) = -(axis 2 1)\"\n  using exhaust_3\n  by (force simp add: axis_def cross3_simps)+\n\nlemma  cross_basis_nonzero:\n  \"u \\<noteq> 0 \\<Longrightarrow> u \\<times> axis 1 1 \\<noteq> 0 \\<or> u \\<times> axis 2 1 \\<noteq> 0 \\<or> u \\<times> axis 3 1 \\<noteq> 0\"\n  by (clarsimp simp add: axis_def cross3_simps) (metis exhaust_3)\n\nlemma  cross_dot_cancel:\n  fixes x::\"real^3\"\n  assumes deq: \"x \\<bullet> y = x \\<bullet> z\" and veq: \"x \\<times> y = x \\<times> z\" and x: \"x \\<noteq> 0\"\n  shows \"y = z\" \nproof -\n  have \"x \\<bullet> x \\<noteq> 0\"\n    by (simp add: x)\n  then have \"y - z = 0\"\n    using veq\n    by (metis (no_types, lifting) Cross3.right_diff_distrib Lagrange deq eq_iff_diff_eq_0 inner_diff_right scale_eq_0_iff)\n  then show ?thesis\n    using eq_iff_diff_eq_0 by blast\nqed\n\nlemma  norm_cross_dot: \"(norm (x \\<times> y))\\<^sup>2 + (x \\<bullet> y)\\<^sup>2 = (norm x * norm y)\\<^sup>2\"\n  unfolding power2_norm_eq_inner power_mult_distrib\n  by (simp add: cross3_simps power2_eq_square)\n\nlemma  dot_cross_det: \"x \\<bullet> (y \\<times> z) = det(vector[x,y,z])\"\n  by (simp add: cross3_simps) \n\nlemma  cross_cross_det: \"(w \\<times> x) \\<times> (y \\<times> z) = det(vector[w,x,z]) *\\<^sub>R y - det(vector[w,x,y]) *\\<^sub>R z\"\n  using exhaust_3 by (force simp add: cross3_simps) \n\nproposition  dot_cross: \"(w \\<times> x) \\<bullet> (y \\<times> z) = (w \\<bullet> y) * (x \\<bullet> z) - (w \\<bullet> z) * (x \\<bullet> y)\"\n  by (force simp add: cross3_simps)\n\nproposition  norm_cross: \"(norm (x \\<times> y))\\<^sup>2 = (norm x)\\<^sup>2 * (norm y)\\<^sup>2 - (x \\<bullet> y)\\<^sup>2\"\n  unfolding power2_norm_eq_inner power_mult_distrib\n  by (simp add: cross3_simps power2_eq_square)\n\nlemma  cross_eq_0: \"x \\<times> y = 0 \\<longleftrightarrow> collinear{0,x,y}\"\nproof -\n  have \"x \\<times> y = 0 \\<longleftrightarrow> norm (x \\<times> y) = 0\"\n    by simp\n  also have \"... \\<longleftrightarrow> (norm x * norm y)\\<^sup>2 = (x \\<bullet> y)\\<^sup>2\"\n    using norm_cross [of x y] by (auto simp: power_mult_distrib)\n  also have \"... \\<longleftrightarrow> \\<bar>x \\<bullet> y\\<bar> = norm x * norm y\"\n    using power2_eq_iff\n    by (metis (mono_tags, opaque_lifting) abs_minus abs_norm_cancel abs_power2 norm_mult power_abs real_norm_def) \n  also have \"... \\<longleftrightarrow> collinear {0, x, y}\"\n    by (rule norm_cauchy_schwarz_equal)\n  finally show ?thesis .\nqed\n\nlemma  cross_eq_self: \"x \\<times> y = x \\<longleftrightarrow> x = 0\" \"x \\<times> y = y \\<longleftrightarrow> y = 0\"\n  apply (metis cross_zero_left dot_cross_self(1) inner_eq_zero_iff)\n  by (metis cross_zero_right dot_cross_self(2) inner_eq_zero_iff)\n\nlemma  norm_and_cross_eq_0:\n   \"x \\<bullet> y = 0 \\<and> x \\<times> y = 0 \\<longleftrightarrow> x = 0 \\<or> y = 0\" (is \"?lhs = ?rhs\")\nproof \n  assume ?lhs\n  then show ?rhs\n    by (metis cross_dot_cancel cross_zero_right inner_zero_right)\nqed auto\n\nlemma  bilinear_cross: \"bilinear(\\<times>)\"\n  apply (auto simp add: bilinear_def linear_def)\n  apply unfold_locales\n  apply (simp add: cross_add_right)\n  apply (simp add: cross_mult_right)\n  apply (simp add: cross_add_left)\n  apply (simp add: cross_mult_left)\n  done\n\nsubsection   \\<open>Preservation by rotation, or other orthogonal transformation up to sign\\<close>\n\nlemma  cross_matrix_mult: \"transpose A *v ((A *v x) \\<times> (A *v y)) = det A *\\<^sub>R (x \\<times> y)\"\n  apply (simp add: vec_eq_iff   )\n  apply (simp add: vector_matrix_mult_def matrix_vector_mult_def forall_3 cross3_simps)\n  done\n\nlemma  cross_orthogonal_matrix:\n  assumes \"orthogonal_matrix A\"\n  shows \"(A *v x) \\<times> (A *v y) = det A *\\<^sub>R (A *v (x \\<times> y))\"\nproof -\n  have \"mat 1 = transpose (A ** transpose A)\"\n    by (metis (no_types) assms orthogonal_matrix_def transpose_mat)\n  then show ?thesis\n    by (metis (no_types) vector_matrix_mul_rid vector_transpose_matrix cross_matrix_mult matrix_vector_mul_assoc matrix_vector_mult_scaleR)\nqed\n\nlemma  cross_rotation_matrix: \"rotation_matrix A \\<Longrightarrow> (A *v x) \\<times> (A *v y) =  A *v (x \\<times> y)\"\n  by (simp add: rotation_matrix_def cross_orthogonal_matrix)\n\nlemma  cross_rotoinversion_matrix: \"rotoinversion_matrix A \\<Longrightarrow> (A *v x) \\<times> (A *v y) = - A *v (x \\<times> y)\"\n  by (simp add: rotoinversion_matrix_def cross_orthogonal_matrix scaleR_matrix_vector_assoc)\n\nlemma  cross_orthogonal_transformation:\n  assumes \"orthogonal_transformation f\"\n  shows   \"(f x) \\<times> (f y) = det(matrix f) *\\<^sub>R f(x \\<times> y)\"\nproof -\n  have orth: \"orthogonal_matrix (matrix f)\"\n    using assms orthogonal_transformation_matrix by blast\n  have \"matrix f *v z = f z\" for z\n    using assms orthogonal_transformation_matrix by force\n  with cross_orthogonal_matrix [OF orth] show ?thesis\n    by simp\nqed\n\nlemma  cross_linear_image:\n   \"\\<lbrakk>linear f; \\<And>x. norm(f x) = norm x; det(matrix f) = 1\\<rbrakk>\n           \\<Longrightarrow> (f x) \\<times> (f y) = f(x \\<times> y)\"\n  by (simp add: cross_orthogonal_transformation orthogonal_transformation)\n\nsubsection \\<open>Continuity\\<close>\n\nlemma  continuous_cross: \"\\<lbrakk>continuous F f; continuous F g\\<rbrakk> \\<Longrightarrow> continuous F (\\<lambda>x. (f x) \\<times> (g x))\"\n  apply (subst continuous_componentwise)\n  apply (clarsimp simp add: cross3_simps)\n  apply (intro continuous_intros; simp)\n  done\n\nlemma  continuous_on_cross:\n  fixes f :: \"'a::t2_space \\<Rightarrow> real^3\"\n  shows \"\\<lbrakk>continuous_on S f; continuous_on S g\\<rbrakk> \\<Longrightarrow> continuous_on S (\\<lambda>x. (f x) \\<times> (g x))\"\n  by (simp add: continuous_on_eq_continuous_within continuous_cross)\n\nunbundle no_cross3_syntax\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/Cross3.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094145755218, "lm_q2_score": 0.8354835330070839, "lm_q1q2_score": 0.7463453057580468}}
{"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: \"\\<forall>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: \"(\\<forall>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 \"(\\<forall>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 \"(\\<forall>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    (\\<forall>j i. (Rep_matrix A j i \\<noteq> 0) \\<longrightarrow> (Rep_matrix B j i = 0)) & (\\<forall>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": "seL4", "repo": "isabelle", "sha": "e1ab32a3bb41728cd19541063283e37919978a4c", "save_path": "github-repos/isabelle/seL4-isabelle", "path": "github-repos/isabelle/seL4-isabelle/isabelle-e1ab32a3bb41728cd19541063283e37919978a4c/src/HOL/Matrix_LP/SparseMatrix.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094003735663, "lm_q2_score": 0.8354835391516133, "lm_q1q2_score": 0.7463452993815127}}
{"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 \"HOL-SPARK.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_remove 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_remove 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_remove)\n  apply (subgoal_tac \"card (js' - {j}) = card js' - 1\")\n  apply (simp add: card.insert_remove 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_remove 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_remove)\n  apply (subgoal_tac \"card (js' - {j}) = card js' - 1\")\n  apply (simp add: card.insert_remove 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 \\<open>liseq/liseq_length\\<close>\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": "seL4", "repo": "isabelle", "sha": "e1ab32a3bb41728cd19541063283e37919978a4c", "save_path": "github-repos/isabelle/seL4-isabelle", "path": "github-repos/isabelle/seL4-isabelle/isabelle-e1ab32a3bb41728cd19541063283e37919978a4c/src/HOL/SPARK/Examples/Liseq/Longest_Increasing_Subsequence.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094032139577, "lm_q2_score": 0.8354835330070839, "lm_q1q2_score": 0.746345296265647}}
{"text": "theory point\nimports Complex_Main (*\"~~/src/HOL/Library/Old_Datatype.thy\"*)\nbegin\n\n(*References\n[1] \"Automation for Geometry in Isabelle/HOL\", Laura Meikle\n[2] Intuition in Formal Proof: A Novel Framework for Combining Mathematical Tools, Laura Meikle*)\n\n(*defintion for Points*)\ntypedef point2d = \"{p::(real*real). True}\" by(auto)(*[1]*)\ndefinition xCoord :: \"point2d \\<Rightarrow> real\" where \"xCoord P \\<equiv> fst(Rep_point2d P)\"(*[1]*)\ndefinition yCoord :: \"point2d \\<Rightarrow> real\" where \"yCoord P \\<equiv> snd(Rep_point2d P)\"(*[1]*)\nlemma xCoord[simp]: \"xCoord (Abs_point2d (a, b)) = a\" by (simp add: xCoord_def Abs_point2d_inverse)\nlemma yCoord[simp]: \"yCoord (Abs_point2d (a, b)) = b\" by (simp add: yCoord_def Abs_point2d_inverse)\nlemma pointSameCoord [simp]: \"Abs_point2d(a, b) = Abs_point2d(a', c) = (a = a' \\<and> b = c)\"\n  by (metis (full_types) Abs_point2d_inject fst_conv mem_Collect_eq snd_conv)\n\n\n(*points equal*)\ndefinition pointsEqual :: \"point2d \\<Rightarrow> point2d \\<Rightarrow> bool\" where\n  \"pointsEqual r p \\<equiv> (xCoord r = xCoord p \\<and> yCoord r = yCoord p)\"\nlemma pointsNotEqual : \"\\<not>pointsEqual r p = (xCoord r \\<noteq> xCoord p \\<or> yCoord r \\<noteq> yCoord p)\"\n  by (simp add: pointsEqual_def)\nlemma pointsNotEqual1: \"(xCoord r \\<noteq> xCoord p \\<or> yCoord r \\<noteq> yCoord p) \\<longleftrightarrow> r \\<noteq> p\"\n  by (metis Rep_point2d_inverse prod.collapse xCoord_def yCoord_def)\nlemma pointsEqualSame : \"pointsEqual p p\" by (simp add: pointsEqual_def)\ntheorem pointsEqual1 [simp] : \"pointsEqual p r = (p = r)\"\n  apply (auto simp add: pointsEqual_def)\nby (metis Rep_point2d_inverse prod.collapse xCoord_def yCoord_def)\n\n\n(*Point a left from point B*)\ndefinition leftFrom :: \"point2d \\<Rightarrow> point2d \\<Rightarrow> bool\" where\n  \"leftFrom a b \\<equiv> (xCoord a < xCoord b)\"\nlemma leftFromSimp: \"xCoord a \\<noteq> xCoord b \\<Longrightarrow> \\<not>leftFrom a b \\<Longrightarrow> leftFrom b a\"\n  by(simp add: leftFrom_def)\nlemma leftFromDest [dest]: \"leftFrom a b \\<Longrightarrow> leftFrom b a \\<Longrightarrow> False\"\n  by (simp add: leftFrom_def)\n\n(*signed area of a triangle; with the convention being that\n- if the points are ordered anti-clockwise, the area is positive\n- if the points are ordered clockwise, the area is negative.*)\ndefinition signedArea :: \"[point2d, point2d, point2d] \\<Rightarrow> real\" where(*[1]*)\n  \"signedArea a b c \\<equiv> (xCoord b - xCoord a)*(yCoord c - yCoord a)\n    - (yCoord b - yCoord a)*(xCoord c - xCoord a)\"\n(*sigendArea-Rotate*)\nlemma signedAreaMin: \"signedArea A B C = -signedArea A C B\"\n  by (simp add: signedArea_def)\nlemma signedAreaRotate [simp]: \"signedArea b c a = signedArea a b c\"(*[1]*)\n  by (simp add: signedArea_def, algebra)\nlemma signedAreaRotate2 [simp]: \"signedArea b a c = signedArea a c b\"(*[1]*)\n  by (simp add: signedArea_def,  algebra)\n(*equal Points*)\nlemma areaDoublePoint [simp]: \"signedArea a a b = 0\"(*[1]*) by (simp add: signedArea_def)\nlemma areaDoublePoint2 [simp]: \"signedArea a b b = 0\"(*[1]*) by (simp add: signedArea_def)\n(*hausner*)\nlemma hausner: \"signedArea P A B + signedArea P B C + signedArea P C A = signedArea A B C\" (*[2]*)\n  by (simp add: mult.commute right_diff_distrib' signedArea_def)\n\n  \n(*3 points are on a line*)\ndefinition collinear :: \"point2d \\<Rightarrow> point2d \\<Rightarrow> point2d \\<Rightarrow> bool\" where(*[1]*)\n  \"collinear a b c \\<equiv>\n    ((xCoord a - xCoord b)*(yCoord b - yCoord c) = (yCoord a- yCoord b)*(xCoord b - xCoord c))\"\nlemma colliniearRight : \"collinear a b c = (signedArea a b c = 0)\"\n  by (simp add: collinear_def signedArea_def, rule iffI, algebra+)\nlemma collRotate [simp]: \"collinear c a b = collinear a b c\"(*[1]*)\n  by (simp add: collinear_def, algebra)\nlemma collSwap [simp]: \"collinear a c b = collinear a b c\"(*[1]*) by(simp add:collinear_def,algebra)\nlemma twoPointsColl [simp]: \"collinear a b b\"(*[1]*) by (simp add: collinear_def)\nlemma twoPointsColl2 [simp]: \"collinear a a b\"(*[1]*) by (simp add: collinear_def)\n\n(*three points a, b and c make a left turn if they make an anti-clockwise cycle:*)\ndefinition leftTurn :: \"[point2d, point2d, point2d] \\<Rightarrow> bool\" where(*[1]*)\n\"leftTurn a b c \\<equiv> 0 < signedArea a b c\"\nlemma leftTurnRotate [simp]: \"leftTurn b c a = leftTurn a b c\"(*[1]*) by (simp add: leftTurn_def)\nlemma leftTurnRotate2 [simp]: \"leftTurn b a c = leftTurn a c b\"(*[1]*) by (simp add: leftTurn_def)\nlemma leftTurnDiffPoints [intro]: \"leftTurn a b c \\<Longrightarrow> a\\<noteq>b \\<and> a\\<noteq>c \\<and> b\\<noteq>c\"(*[1]*)\n  by (auto simp add: leftTurn_def)\n\n(*three points a, b and c make a right turn if they make an clockwise cycle:*)\ndefinition rightTurn :: \"[point2d, point2d, point2d] \\<Rightarrow> bool\" where\n  \"rightTurn a b c \\<equiv> 0 > signedArea a b c\"\nlemma rightTurnEq: \"rightTurn a b c = (signedArea a b c \\<noteq> 0 \\<and> \\<not>leftTurn a b c)\"\n  using leftTurn_def rightTurn_def by auto\nlemma leftRightTurn [simp]: \"leftTurn a b c = rightTurn c b a\"\n  by (simp add: signedArea_def leftTurn_def rightTurn_def less_real_def mult.commute)\nlemma rightTurnRotate [simp]: \"rightTurn b c a = rightTurn a b c\" by (simp add: rightTurn_def)\nlemma rightTurnRotate2 [simp]: \"rightTurn b a c = rightTurn a c b\" by (simp add: rightTurn_def)\n\n(*lemmas for leftTurn and rightTurn*)\nlemma notLeftTurn [simp]: \"(\\<not> leftTurn a c b) = (leftTurn a b c \\<or> collinear a b c)\"(*[1]*)\n  apply (simp add:leftTurn_def del: leftRightTurn, subst colliniearRight)\nby (auto simp add: signedArea_def mult.commute)\nlemma notRightTurn [simp]: \"(\\<not> rightTurn a c b) = (rightTurn a b c \\<or> collinear a b c)\"\n  by (simp add: rightTurn_def, subst colliniearRight,auto simp add: signedArea_def mult.commute)\nlemma notRightTurn1 [simp]: \"(\\<not> rightTurn a b c) = (leftTurn a b c \\<or> collinear a b c)\"\n  by (metis leftRightTurn leftTurnRotate2 notLeftTurn)\nlemma conflictingLeftTurns [dest]: \"leftTurn a b c \\<Longrightarrow> leftTurn a c b \\<Longrightarrow> False\"(*[1]*)\n  by (metis notLeftTurn) \nlemma conflictingLeftTurns3 [dest]: \"leftTurn a b c \\<Longrightarrow> collinear a b c \\<Longrightarrow> False\"(*[1]*)\n  by (metis collSwap notLeftTurn)\nlemma conflictingRigthTurns [dest]: \"rightTurn a b c \\<Longrightarrow> rightTurn a c b \\<Longrightarrow> False\"\n  by (metis notRightTurn) \nlemma conflictingRigthTurns1 [dest]: \"rightTurn a b c \\<Longrightarrow> rightTurn b a c \\<Longrightarrow> False\"\n  by (metis leftRightTurn notLeftTurn)\nlemma conflictingRightTurns3 [dest]: \"rightTurn a b c \\<Longrightarrow> collinear a b c \\<Longrightarrow> False\"\n  by (metis collSwap notRightTurn)\n\n(*signedArea Mult and Div *)\nlemma leftTurnMult:\"leftTurn a b c \\<Longrightarrow> leftTurn d b e \\<Longrightarrow> (signedArea a b c)*(signedArea d b e) > 0\"\n  using leftTurn_def by auto\nlemma leftTurnDiv: \"leftTurn a b c \\<Longrightarrow> leftTurn d b e \\<Longrightarrow> (signedArea a b c)/(signedArea d b e) > 0\"\n  using leftTurn_def by auto\nlemma rightTurnMult: \"rightTurn a b c \\<Longrightarrow> rightTurn d b e \\<Longrightarrow>\n  (signedArea a b c)*(signedArea d b e) > 0\"\n  by (simp add: rightTurn_def zero_less_mult_iff)\nlemma rightTurnDiv: \"rightTurn a b c \\<Longrightarrow> rightTurn d b e \\<Longrightarrow>\n  (signedArea a b c)/(signedArea d b e) > 0\"\n  by (simp add: rightTurn_def zero_less_divide_iff)\n  \nlemma interiority: \"leftTurn t q r \\<Longrightarrow> leftTurn p t r \\<Longrightarrow> leftTurn p q t \\<Longrightarrow> leftTurn p q r\" (*[2]*)\n  by (smt hausner leftRightTurn rightTurn_def)\n\n(*lemmas for collinear und signedArea*)\nlemma notCollThenDiffPoints [intro]: \"\\<not>collinear a b c \\<Longrightarrow> a\\<noteq>b \\<and> a\\<noteq>c \\<and> b\\<noteq>c\"(*[1]*) by (auto)\nlemma notCollThenLfOrRt1 [intro]: \"\\<not>collinear a b c \\<Longrightarrow> leftTurn a b c \\<or> rightTurn a b c\" by (auto)\nlemma areaContra [dest]: \" signedArea a c b < 0 \\<Longrightarrow> signedArea a b c < 0  \\<Longrightarrow> False\"(*[1]*)\n  by (metis colliniearRight leftTurn_def less_trans notLeftTurn) \nlemma areaContra2 [dest]: \"0 < signedArea a c b\\<Longrightarrow> 0 < signedArea a b c \\<Longrightarrow> False\"(*[1]*)\n  by (metis leftTurn_def notLeftTurn) \nlemma collinearTransitiv1 : \"\\<exists> a. collinear a b c \\<and> collinear a b d \\<longrightarrow> collinear a c d\"\n  by (simp add: colliniearRight, rule_tac x=d in exI, simp)\n\n\n(*scalar multiplication*)\ndefinition scalMult :: \"[real, point2d] \\<Rightarrow> point2d\" (infixl \"*s\" 65) where (*[2]*)\n  \"a *s P \\<equiv> (\\<lambda>(p1,p2). Abs_point2d (a*p1,a*p2)) (Rep_point2d P)\"\nlemma scalMultNull[simp]: \"0 *s P = Abs_point2d (0,0)\"\n  by (simp add: scalMult_def)\n(*addition*)\ndefinition pointPlus :: \"[point2d, point2d] \\<Rightarrow> point2d\" (infixl \"+p\" 60) where \n  \"P +p Q \\<equiv> Abs_point2d ((xCoord P) + (xCoord Q), (yCoord P) + (yCoord Q))\"\nlemma pointPlusSym: \"(P +p Q) = (Q +p P)\" by (auto simp add: pointPlus_def)\nlemma pointPlusNull[simp]: \"xCoord Q = 0 \\<Longrightarrow> P +p Q = Abs_point2d (xCoord P, yCoord P + yCoord Q)\"\n  by (simp add: pointPlus_def)\nlemma pointPlusNull1[simp]: \"yCoord Q = 0 \\<Longrightarrow> P +p Q = Abs_point2d (xCoord P + xCoord Q, yCoord P)\"\n  by (simp add: pointPlus_def)\nlemma pointPlusNull2[simp]: \"P = P +p Abs_point2d(0,0)\"\n  by (smt Rep_point2d_inverse pointPlusNull1 prod.collapse xCoord xCoord_def yCoord)\nlemma pointPlusNull3[simp]: \"P = Abs_point2d(0,0) +p P\"\n  by (simp only: pointPlusSym pointPlusNull2)\nlemma cramersRule: \"signedArea P Q R \\<noteq> 0 \\<Longrightarrow> T =\n  ((signedArea T Q R / signedArea P Q R) *s P) +p\n  ((signedArea P T R / signedArea P Q R) *s Q) +p\n  ((signedArea P Q T / signedArea P Q R) *s R)\" (*[2]*)\n  apply (auto)\n  apply (case_tac \"signedArea Q R T = 0\", auto)\nsorry\n(*nur mit cramersRule beweisbar?*)\nlemma transitivity: \"leftTurn t s p \\<Longrightarrow> leftTurn t s q \\<Longrightarrow> leftTurn t s r \\<Longrightarrow> leftTurn t p q (*[2]*)\n  \\<Longrightarrow> leftTurn t q r \\<Longrightarrow> leftTurn t p r\"\nsorry\n\n(*b is between a c?*)\ndefinition isBetween :: \"[point2d, point2d, point2d] \\<Rightarrow> bool\"\n  (\"_ isBetween _ _ \" [60, 60, 60] 60) where(*[1]*)\n  \"b isBetween  a c \\<equiv> collinear a b c \\<and> (\\<exists> d. signedArea a c d \\<noteq> 0) \\<and>\n  (\\<forall> d. signedArea a c d \\<noteq> 0 \\<longrightarrow>\n  (0 < (signedArea a b d / signedArea a c d) \\<and> (signedArea a b d / signedArea a c d) < 1 ))\"\n(*Punkte sind verschieden, wenn*)\nlemma pointsEqualArea: \"a \\<noteq> b = (\\<exists> d. signedArea a b d \\<noteq> 0)\"\n  apply (auto)\n  apply (case_tac \"xCoord a = xCoord b\", rule_tac x=\"Abs_point2d(xCoord b + 1, yCoord b)\" in exI)\n    apply (metis Abs_point2d_inverse Collect_const Rep_point2d_inverse UNIV_I add_diff_cancel_left'\n    eq_iff_diff_eq_0 mult.left_neutral mult_zero_left prod.collapse prod.sel(1) signedAreaRotate\n    signedArea_def xCoord_def yCoord_def)\n  apply (case_tac \"yCoord a = yCoord b\", rule_tac x=\"Abs_point2d(xCoord b, yCoord b + 1)\" in exI)\n    apply (simp add: signedArea_def)\n  apply (case_tac \"xCoord a < xCoord b\", rule_tac x=\"Abs_point2d((xCoord b) + 1, yCoord b)\" in exI)\n    apply (simp add: signedArea_def)\n  apply (rule_tac x=\"Abs_point2d((xCoord b) - 1, yCoord b)\" in exI)\n    apply (simp add: signedArea_def)\ndone\nlemma swapBetween1: \"a isBetween c b \\<Longrightarrow> a isBetween b c\" (*[1]*)\n  apply (simp add: isBetween_def, safe)\n  apply (rule_tac x=d in exI, metis collSwap colliniearRight)\n  apply (erule_tac x=da in allE, safe) using collSwap colliniearRight apply blast\n  apply (simp add: colliniearRight divide_neg_neg le_divide_eq_1 left_diff_distrib' mult.commute\n    signedArea_def)\n  apply (simp add: divide_less_eq_1 divide_neg_neg right_diff_distrib')\n  apply (smt divide_neg_neg divide_pos_pos)\n  apply (erule_tac x=da in allE, safe) using collSwap colliniearRight apply blast\n  apply (simp add: areaContra areaContra2 colliniearRight divide_le_0_iff divide_less_cancel\n    divide_less_eq_1 left_diff_distrib' right_diff_distrib' signedArea_def)\n  apply (simp add: mult.commute zero_less_divide_iff)\nby smt\nlemma swapBetween [simp]: \"a isBetween c b = a isBetween b c\" (*[1]*)\n  by (auto simp add: swapBetween1)\n\nlemma notBetweenSamePoint [dest]: \"a isBetween b b \\<Longrightarrow> False\"(*[1]*)\n  by (simp add: isBetween_def)\nlemma isBetweenImpliesCollinear [intro] : \"a isBetween b c \\<longrightarrow> collinear a b c\"(*[1]*)\n  by (simp add: isBetween_def)\nlemma isBetweenImpliesCollinear2 [intro] : \"b isBetween a c \\<longrightarrow> collinear a b c\"(*[1]*)\n  by (simp add: isBetween_def)\nlemma isBetweenImpliesCollinear3 [intro] : \"c isBetween a b \\<longrightarrow> collinear a b c\"(*[1]*)\n  by (simp add: isBetween_def)\nlemma notBetweenSelf [simp]: \"\\<not> (a isBetween a b)\"(*[1]*)\n  by (rule notI, auto simp add: isBetween_def)\nlemma notBetweenSelf2 [simp]: \"\\<not> (b isBetween a b)\"(*[1]*)\n  by (rule notI, auto simp add: isBetween_def)\n\nlemma isBetweenPointsDistinct [intro]: \"a isBetween b c \\<Longrightarrow> a\\<noteq>b \\<and> a\\<noteq>c \\<and> b\\<noteq>c\"(*[1]*)\n  by (auto simp add: isBetween_def) \nlemma conflictingLeftTurns2 [dest]: \"leftTurn a b c \\<Longrightarrow> a isBetween b c \\<Longrightarrow> False\" (*[1]*)\n  using isBetween_def by auto\nlemma conflictingRightTurns2 [dest]: \"rightTurn a b c \\<Longrightarrow> a isBetween b c \\<Longrightarrow> False\" (*[1]*)\n  using isBetween_def by auto\nlemma isBetweenTransitiv: \"b isBetween a c \\<Longrightarrow> d isBetween a b \\<Longrightarrow> d isBetween a c\"\n  apply (auto simp add: isBetween_def)\n  using colliniearRight apply auto[1]\n  apply (smt zero_less_divide_iff)\nby (smt divide_le_0_iff le_divide_eq_1)\nlemma notBetween3 [dest]: \"\\<lbrakk>B isBetween A C ; C isBetween A B\\<rbrakk> \\<Longrightarrow> False\"(*[1]*)\n  apply (auto simp add: isBetween_def)\n  apply (case_tac \"signedArea d A B \\<noteq> 0\")\n    apply (erule_tac x=d in allE, simp)\n    apply (erule_tac x=d in allE, safe, simp)\nby (smt divide_le_0_iff divide_less_eq_1)\nlemma leftTurnsImplyBetween: \"leftTurn A B C \\<Longrightarrow> leftTurn A C D \\<Longrightarrow> collinear B C D \\<Longrightarrow>\n  C isBetween B D\" (*[2]*)\n  apply (case_tac \"B = D\", blast, case_tac \"C = B\", blast, case_tac \"C = D\", blast)\n  apply (case_tac \"A = B\", blast, case_tac \"A = C\") using leftTurnDiffPoints apply blast\n  apply (case_tac \"A = D\") using leftTurnDiffPoints apply blast\n  apply (simp add: isBetween_def)\n  apply (safe)\n  apply (simp add: pointsEqualArea)\n  apply (subgoal_tac \"signedArea d B C \\<noteq> 0\")\nsorry\n\nlemma notBetween [dest]: \"\\<lbrakk>A isBetween B C; B isBetween A C\\<rbrakk> \\<Longrightarrow> False\" (*[1]*)\n  apply (auto simp add: isBetween_def)\n  apply (case_tac \"signedArea d B A \\<noteq> 0\")\n    apply (erule_tac x=d in allE, simp)\n    apply (erule_tac x=d in allE, safe, simp)\n    apply (simp add: colliniearRight divide_less_eq_1 left_diff_distrib' right_diff_distrib'\n      signedArea_def)\n    apply (smt mult.commute)\n    apply (simp add: divide_less_cancel divide_strict_right_mono_neg isBetween_def leftTurn_def\n      leftTurnsImplyBetween rightTurn_def zero_less_divide_iff)\n    apply (simp add: colliniearRight mult.commute right_diff_distrib' signedArea_def)\n    apply (smt divide_less_eq_1_neg)\nby (smt collSwap colliniearRight zero_less_divide_iff)\nlemma notBetween2 [dest]: \"\\<lbrakk>A isBetween B C ; C isBetween A B\\<rbrakk> \\<Longrightarrow> False\"(*[1]*)\n  apply (auto simp add: isBetween_def)\n  apply (case_tac \"signedArea d B A \\<noteq> 0\")\n    apply (erule_tac x=d in allE, simp)\n    apply (erule_tac x=d in allE, safe, simp)\n    apply (simp add: colliniearRight divide_less_eq_1 left_diff_distrib' right_diff_distrib'\n      signedArea_def)\n    apply (smt mult.commute)\n    apply (simp add: divide_less_cancel divide_strict_right_mono_neg isBetween_def leftTurn_def\n      leftTurnsImplyBetween rightTurn_def zero_less_divide_iff)\n    apply (simp add: colliniearRight mult.commute right_diff_distrib' signedArea_def)\n    apply (smt divide_less_eq_1_neg less_divide_eq_1_pos)\nby (smt collSwap colliniearRight zero_less_divide_iff)\n\nlemma onePointIsBetween[intro]: \"collinear a b c \\<Longrightarrow> a \\<noteq> b \\<Longrightarrow> a \\<noteq> c \\<Longrightarrow> b \\<noteq> c \\<Longrightarrow> (*[2]*)\n  a isBetween b c \\<or> b isBetween a c \\<or> c isBetween a b\"\n  apply (safe)\n  apply (auto simp add: isBetween_def)\n  apply (simp add: pointsEqualArea)+\nsorry\n\n\nlemma collinearTransitiv: \"a \\<noteq> b \\<Longrightarrow> collinear a b c \\<Longrightarrow> collinear a b d \\<Longrightarrow> collinear a c d\"\n  apply (simp add: colliniearRight)\n  apply (cases \"a = c\", simp, cases \"a = d\", simp, cases \"a = b\", simp)\n  apply (cases \"c = d\", simp, cases \"c = b\", simp)\n  apply (cases \"b = d\", metis collSwap colliniearRight)\n  apply (cut_tac a=a and b=b and c=c in onePointIsBetween)\n    apply (auto simp add: colliniearRight)+\n  apply (cut_tac a=a and b=b and c=d in onePointIsBetween)\n    apply (auto simp add: colliniearRight)+\n  apply (rule ccontr, subgoal_tac \"signedArea a c d > 0 \\<or> signedArea a c d < 0\", safe, simp)\n  apply (simp add: signedArea_def)\nsorry\nlemma collinearTransitiv3: \"a \\<noteq> b \\<Longrightarrow> collinear a b c \\<Longrightarrow> collinear a b d \\<Longrightarrow> collinear b c d\"\n  by (smt collRotate collinearTransitiv)\n\nlemma collinearTransitiv2: \"b \\<noteq> c \\<Longrightarrow> collinear a b c \\<Longrightarrow> collinear b c d \\<Longrightarrow> collinear a b d\"\n  using collRotate collinearTransitiv by blast\n\nlemma newLeftTurn: \"\\<lbrakk>A isBetween C D; leftTurn A B C \\<rbrakk> \\<Longrightarrow> leftTurn B C D\" (*[2]*)\n  apply (subgoal_tac \"signedArea B C D \\<noteq> 0\")\n  apply (simp add: isBetween_def, safe)\n  apply (erule_tac x=B in allE, simp)\n  apply (smt divide_nonneg_nonpos leftTurn_def notLeftTurn notRightTurn1)\n  apply (auto simp add: isBetween_def)\n  apply (case_tac \"signedArea d C D \\<noteq> 0\", erule_tac x=d in allE, simp)\n  apply (metis areaDoublePoint collinearTransitiv2 colliniearRight notRightTurn1 signedAreaRotate)\nby blast\n\nlemma newLeftTurn1: \"\\<lbrakk>A isBetween C D; leftTurn A B C \\<rbrakk> \\<Longrightarrow> leftTurn D B A\" (*[1]*)\n  apply (subgoal_tac \"rightTurn C B D\")\n  apply (smt collinearTransitiv2 isBetweenPointsDistinct leftTurnRotate2 newLeftTurn notLeftTurn swapBetween)\n  apply (subgoal_tac \"signedArea C B D \\<noteq> 0\")\n  apply (simp only: isBetween_def, safe)\n  apply (erule_tac x=B in allE, simp)\n  apply (smt colliniearRight divide_nonneg_nonpos notRightTurn rightTurn_def)\n  apply (auto simp add: isBetween_def)\n  apply (case_tac \"signedArea d C D \\<noteq> 0\", erule_tac x=d in allE, simp)\n  apply (metis areaDoublePoint collinearTransitiv2 colliniearRight notRightTurn1 signedAreaRotate)\nby blast\n\n\nlemma leftOrRightTurn: \"c \\<noteq> d \\<Longrightarrow> leftFrom c d \\<Longrightarrow> leftFrom a b \\<Longrightarrow> rightTurn a b c \\<Longrightarrow>\n  rightTurn a b d \\<Longrightarrow> leftFrom a d \\<Longrightarrow> leftFrom c b\\<Longrightarrow> leftTurn c d a \\<or> leftTurn c d b\"\noops\n\n\n(*evtl. noch n\u00fctzlich*)\n\n(*lemma \"a \\<noteq> b \\<Longrightarrow> \\<exists> d c. leftTurn a b c \\<and> leftTurn a b d \\<and> signedArea a b c < signedArea a b d\"\n  apply (case_tac \"xCoord a = xCoord b\")\n    apply (rule_tac x=\"Abs_point2d(xCoord b - 2, yCoord b)\" in exI,\n      rule_tac x=\"Abs_point2d(xCoord b - 1, yCoord b)\" in exI)  \noops*)\n\n(*(*A point between B and C*)\n(*definition midpoint :: \"point2d \\<Rightarrow> point2d \\<Rightarrow> point2d \\<Rightarrow> bool\" where\n\"midpoint a b c = (2 * yCoord a = yCoord b + yCoord c \\<and> 2 * xCoord a = xCoord b + xCoord c)\"*)\ndefinition midpoint :: \"point2d \\<Rightarrow> point2d \\<Rightarrow> point2d \\<Rightarrow> bool\" \n  (\"_ midpoint _ _ \" [60, 60, 60] 60) where\n  \"d midpoint b c \\<equiv> (signedArea d b c = 0 \\<and> (\\<forall> a. signedArea a b c = 2 * signedArea a b d))\"\nlemma midPointCollinear[simp]: \"a midpoint b c \\<Longrightarrow> collinear a b c\"\n  by (simp add: colliniearRight midpoint_def)\nlemma midPointSym : \"a midpoint b c = a midpoint c b\"\n  apply (auto simp add: midpoint_def)\nby (metis collSwap colliniearRight notCollThenDiffPoints, smt hausner)+\nlemma midpointNotSame1[dest]: \"a \\<noteq> b \\<Longrightarrow> a midpoint a b \\<Longrightarrow> False\"\n  by (simp add: midpoint_def pointsEqualArea)\nlemma midpointNotSame[dest]: \"b\\<noteq>c \\<Longrightarrow> a midpoint b c \\<Longrightarrow> b midpoint a c \\<Longrightarrow> False\"\n  apply (auto simp add: midpoint_def)\nby (smt midPointSym midpointNotSame1 midpoint_def signedAreaMin)\n\nlemma \"(a midpoint b c) = (2 * yCoord a = yCoord b + yCoord c \\<and> 2 * xCoord a = xCoord b + xCoord c)\"\n  apply (auto simp add: midpoint_def)\noops\n\nlemma midpointPointExist: \"\\<exists> X. X midpoint a b\"\n  apply (case_tac \"a=b\", smt colliniearRight midpoint_def mult_zero_right notCollThenDiffPoints)\n  apply (auto simp add: midpoint_def)\n  apply (subgoal_tac \"\\<exists> d. signedArea a b d = 0\", simp, erule_tac exE)\n  apply (rule_tac x=\"d\" in exI, auto)\noops*)\n\n\n\nlemma CollPointExist: \"\\<exists> X. collinear A B X\" by (rule_tac x=A in exI, auto)\n\n(*lemma isBeetweenPointExist: \"a \\<noteq> b \\<Longrightarrow> \\<exists> X. X isBetween a b\"\n  apply (cut_tac a=a and b=b in midpointPointExist)\n  apply (auto simp add: isBetween_def)\n  apply (rule_tac x=X in exI)\n  apply (safe)\n  apply (simp add: pointsEqualArea)\n  apply (simp add: pointsEqualArea)\n  (*apply (subgoal_tac \"collinear X a b\")\n    apply (case_tac \"X = d\", simp) using colliniearRight midPointCollinear apply blast\n    apply (case_tac \"X = a\", simp, blast)\n    apply (case_tac \"X = b\", simp)\n    apply (case_tac \"d = a\", simp)\n    apply (case_tac \"d = b\", simp)\n    apply (case_tac \"xCoord a = xCoord b\", subgoal_tac \"xCoord X = xCoord b\")\n      apply (case_tac \"yCoord a < yCoord b\", subgoal_tac \"yCoord a < yCoord X \\<and> yCoord X < yCoord b\")\n      apply (case_tac \"signedArea d a b > 0\")\n      (*selbst hier kein Beweis*)*)\noops*)\n\n(*definition segLength :: \"point2d \\<Rightarrow> point2d \\<Rightarrow> real\" where\n  \"segLength A B \\<equiv> sqrt ((xCoord A - xCoord B)*(xCoord A - xCoord B) +\n  (yCoord A - yCoord B)*(yCoord A - yCoord B))\"\nlemma segLengthSym: \"segLength A B = segLength B A\"\nby (simp add: segLength_def, algebra)\n\ndefinition quadArea :: \"[point2d, point2d, point2d, point2d] \\<Rightarrow> real\" where\n  \"quadArea A B C D \\<equiv> signedArea A B C + signedArea A C D\"\nlemma quadAreaSym: \"quadArea A B C D = quadArea B C D A\"\n  by (auto simp add: quadArea_def signedArea_def, algebra)\nlemma quadAreaSym1: \"quadArea A B C D = quadArea C D A B\"\n  by (metis quadAreaSym)\nlemma quadAreaSym2: \"quadArea A B C D = quadArea D A B C\"\n  by (auto simp add: quadArea_def signedArea_def, algebra)*)\n\nend", "meta": {"author": "vitaB", "repo": "motion-planning", "sha": "163c27420d4615ec6db15ce74f4d324bdf8c1b60", "save_path": "github-repos/isabelle/vitaB-motion-planning", "path": "github-repos/isabelle/vitaB-motion-planning/motion-planning-163c27420d4615ec6db15ce74f4d324bdf8c1b60/point.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896671963207, "lm_q2_score": 0.810478913248044, "lm_q1q2_score": 0.7462806087993021}}
{"text": "(*  Title:  HOL/Rat.thy\n    Author: Markus Wenzel, TU Muenchen\n*)\n\nsection {* Rational numbers *}\n\ntheory Rat\nimports GCD Archimedean_Field\nbegin\n\nsubsection {* Rational numbers as quotient *}\n\nsubsubsection {* Construction of the type of rational numbers *}\n\ndefinition\n  ratrel :: \"(int \\<times> int) \\<Rightarrow> (int \\<times> int) \\<Rightarrow> bool\" where\n  \"ratrel = (\\<lambda>x y. snd x \\<noteq> 0 \\<and> snd y \\<noteq> 0 \\<and> fst x * snd y = fst y * snd x)\"\n\nlemma ratrel_iff [simp]:\n  \"ratrel 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: ratrel_def)\n\nlemma exists_ratrel_refl: \"\\<exists>x. ratrel x x\"\n  by (auto intro!: one_neq_zero)\n\nlemma symp_ratrel: \"symp ratrel\"\n  by (simp add: ratrel_def symp_def)\n\nlemma transp_ratrel: \"transp ratrel\"\nproof (rule transpI, unfold split_paired_all)\n  fix a b a' b' a'' b'' :: int\n  assume A: \"ratrel (a, b) (a', b')\"\n  assume B: \"ratrel (a', b') (a'', b'')\"\n  have \"b' * (a * b'') = b'' * (a * b')\" by simp\n  also from A have \"a * b' = a' * b\" by auto\n  also have \"b'' * (a' * b) = b * (a' * b'')\" by simp\n  also from B have \"a' * b'' = a'' * b'\" by auto\n  also have \"b * (a'' * b') = b' * (a'' * b)\" by simp\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 \"ratrel (a, b) (a'', b'')\" by auto\nqed\n\nlemma part_equivp_ratrel: \"part_equivp ratrel\"\n  by (rule part_equivpI [OF exists_ratrel_refl symp_ratrel transp_ratrel])\n\nquotient_type rat = \"int \\<times> int\" / partial: \"ratrel\"\n  morphisms Rep_Rat Abs_Rat\n  by (rule part_equivp_ratrel)\n\nlemma Domainp_cr_rat [transfer_domain_rule]: \"Domainp pcr_rat = (\\<lambda>x. snd x \\<noteq> 0)\"\nby (simp add: rat.domain_eq)\n\nsubsubsection {* Representation and basic operations *}\n\nlift_definition Fract :: \"int \\<Rightarrow> int \\<Rightarrow> rat\"\n  is \"\\<lambda>a b. if b = 0 then (0, 1) else (a, b)\"\n  by simp\n\nlemma eq_rat:\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\"\n  by (transfer, simp)+\n\nlemma Rat_cases [case_names Fract, cases type: rat]:\n  assumes \"\\<And>a b. q = Fract a b \\<Longrightarrow> b > 0 \\<Longrightarrow> coprime a b \\<Longrightarrow> C\"\n  shows C\nproof -\n  obtain a b :: int where \"q = Fract a b\" and \"b \\<noteq> 0\"\n    by transfer simp\n  let ?a = \"a div gcd a b\"\n  let ?b = \"b div gcd a b\"\n  from `b \\<noteq> 0` have \"?b * gcd a b = b\"\n    by simp\n  with `b \\<noteq> 0` have \"?b \\<noteq> 0\" by fastforce\n  from `q = Fract a b` `b \\<noteq> 0` `?b \\<noteq> 0` have q: \"q = Fract ?a ?b\"\n    by (simp add: eq_rat dvd_div_mult mult.commute [of a])\n  from `b \\<noteq> 0` have coprime: \"coprime ?a ?b\"\n    by (auto intro: div_gcd_coprime_int)\n  show C proof (cases \"b > 0\")\n    case True\n    note assms\n    moreover note q\n    moreover from True have \"?b > 0\" by (simp add: nonneg1_imp_zdiv_pos_iff)\n    moreover note coprime\n    ultimately show C .\n  next\n    case False\n    note assms\n    moreover have \"q = Fract (- ?a) (- ?b)\" unfolding q by transfer simp\n    moreover from False `b \\<noteq> 0` have \"- ?b > 0\" by (simp add: pos_imp_zdiv_neg_iff)\n    moreover from coprime have \"coprime (- ?a) (- ?b)\" by simp\n    ultimately show C .\n  qed\nqed\n\nlemma Rat_induct [case_names Fract, induct type: rat]:\n  assumes \"\\<And>a b. b > 0 \\<Longrightarrow> coprime a b \\<Longrightarrow> P (Fract a b)\"\n  shows \"P q\"\n  using assms by (cases q) simp\n\ninstantiation rat :: field_inverse_zero\nbegin\n\nlift_definition zero_rat :: \"rat\" is \"(0, 1)\"\n  by simp\n\nlift_definition one_rat :: \"rat\" is \"(1, 1)\"\n  by simp\n\nlemma Zero_rat_def: \"0 = Fract 0 1\"\n  by transfer simp\n\nlemma One_rat_def: \"1 = Fract 1 1\"\n  by transfer simp\n\nlift_definition plus_rat :: \"rat \\<Rightarrow> rat \\<Rightarrow> rat\"\n  is \"\\<lambda>x y. (fst x * snd y + fst y * snd x, snd x * snd y)\"\n  by (clarsimp, simp add: distrib_right, simp add: ac_simps)\n\nlemma add_rat [simp]:\n  assumes \"b \\<noteq> 0\" and \"d \\<noteq> 0\"\n  shows \"Fract a b + Fract c d = Fract (a * d + c * b) (b * d)\"\n  using assms by transfer simp\n\nlift_definition uminus_rat :: \"rat \\<Rightarrow> rat\" is \"\\<lambda>x. (- fst x, snd x)\"\n  by simp\n\nlemma minus_rat [simp]: \"- Fract a b = Fract (- a) b\"\n  by transfer simp\n\nlemma minus_rat_cancel [simp]: \"Fract (- a) (- b) = Fract a b\"\n  by (cases \"b = 0\") (simp_all add: eq_rat)\n\ndefinition\n  diff_rat_def: \"q - r = q + - (r::rat)\"\n\nlemma diff_rat [simp]:\n  assumes \"b \\<noteq> 0\" and \"d \\<noteq> 0\"\n  shows \"Fract a b - Fract c d = Fract (a * d - c * b) (b * d)\"\n  using assms by (simp add: diff_rat_def)\n\nlift_definition times_rat :: \"rat \\<Rightarrow> rat \\<Rightarrow> rat\"\n  is \"\\<lambda>x y. (fst x * fst y, snd x * snd y)\"\n  by (simp add: ac_simps)\n\nlemma mult_rat [simp]: \"Fract a b * Fract c d = Fract (a * c) (b * d)\"\n  by transfer simp\n\nlemma mult_rat_cancel:\n  assumes \"c \\<noteq> 0\"\n  shows \"Fract (c * a) (c * b) = Fract a b\"\n  using assms by transfer simp\n\nlift_definition inverse_rat :: \"rat \\<Rightarrow> rat\"\n  is \"\\<lambda>x. if fst x = 0 then (0, 1) else (snd x, fst x)\"\n  by (auto simp add: mult.commute)\n\nlemma inverse_rat [simp]: \"inverse (Fract a b) = Fract b a\"\n  by transfer simp\n\ndefinition\n  divide_rat_def: \"q / r = q * inverse (r::rat)\"\n\nlemma divide_rat [simp]: \"Fract a b / Fract c d = Fract (a * d) (b * c)\"\n  by (simp add: divide_rat_def)\n\ninstance proof\n  fix q r s :: rat\n  show \"(q * r) * s = q * (r * s)\"\n    by transfer simp\n  show \"q * r = r * q\"\n    by transfer simp\n  show \"1 * q = q\"\n    by transfer simp\n  show \"(q + r) + s = q + (r + s)\"\n    by transfer (simp add: algebra_simps)\n  show \"q + r = r + q\"\n    by transfer simp\n  show \"0 + q = q\"\n    by transfer simp\n  show \"- q + q = 0\"\n    by transfer simp\n  show \"q - r = q + - r\"\n    by (fact diff_rat_def)\n  show \"(q + r) * s = q * s + r * s\"\n    by transfer (simp add: algebra_simps)\n  show \"(0::rat) \\<noteq> 1\"\n    by transfer simp\n  { assume \"q \\<noteq> 0\" thus \"inverse q * q = 1\"\n    by transfer simp }\n  show \"q / r = q * inverse r\"\n    by (fact divide_rat_def)\n  show \"inverse 0 = (0::rat)\"\n    by transfer simp\nqed\n\nend\n\nlemma of_nat_rat: \"of_nat k = Fract (of_nat k) 1\"\n  by (induct k) (simp_all add: Zero_rat_def One_rat_def)\n\nlemma of_int_rat: \"of_int k = Fract k 1\"\n  by (cases k rule: int_diff_cases) (simp add: of_nat_rat)\n\nlemma Fract_of_nat_eq: \"Fract (of_nat k) 1 = of_nat k\"\n  by (rule of_nat_rat [symmetric])\n\nlemma Fract_of_int_eq: \"Fract k 1 = of_int k\"\n  by (rule of_int_rat [symmetric])\n\nlemma rat_number_collapse:\n  \"Fract 0 k = 0\"\n  \"Fract 1 1 = 1\"\n  \"Fract (numeral w) 1 = numeral w\"\n  \"Fract (- numeral w) 1 = - numeral w\"\n  \"Fract (- 1) 1 = - 1\"\n  \"Fract k 0 = 0\"\n  using Fract_of_int_eq [of \"numeral w\"]\n  using Fract_of_int_eq [of \"- numeral w\"]\n  by (simp_all add: Zero_rat_def One_rat_def eq_rat)\n\nlemma rat_number_expand:\n  \"0 = Fract 0 1\"\n  \"1 = Fract 1 1\"\n  \"numeral k = Fract (numeral k) 1\"\n  \"- 1 = Fract (- 1) 1\"\n  \"- numeral k = Fract (- numeral k) 1\"\n  by (simp_all add: rat_number_collapse)\n\nlemma Rat_cases_nonzero [case_names Fract 0]:\n  assumes Fract: \"\\<And>a b. q = Fract a b \\<Longrightarrow> b > 0 \\<Longrightarrow> a \\<noteq> 0 \\<Longrightarrow> coprime a b \\<Longrightarrow> C\"\n  assumes 0: \"q = 0 \\<Longrightarrow> C\"\n  shows C\nproof (cases \"q = 0\")\n  case True then show C using 0 by auto\nnext\n  case False\n  then obtain a b where \"q = Fract a b\" and \"b > 0\" and \"coprime a b\" by (cases q) auto\n  with False have \"0 \\<noteq> Fract a b\" by simp\n  with `b > 0` have \"a \\<noteq> 0\" by (simp add: Zero_rat_def eq_rat)\n  with Fract `q = Fract a b` `b > 0` `coprime a b` show C by blast\nqed\n\nsubsubsection {* Function @{text normalize} *}\n\nlemma Fract_coprime: \"Fract (a div gcd a b) (b div gcd a b) = Fract a b\"\nproof (cases \"b = 0\")\n  case True then show ?thesis by (simp add: eq_rat)\nnext\n  case False\n  moreover have \"b div gcd a b * gcd a b = b\"\n    by (rule dvd_div_mult_self) simp\n  ultimately have \"b div gcd a b * gcd a b \\<noteq> 0\" by simp\n  then have \"b div gcd a b \\<noteq> 0\" by fastforce\n  with False show ?thesis by (simp add: eq_rat dvd_div_mult mult.commute [of a])\nqed\n\ndefinition normalize :: \"int \\<times> int \\<Rightarrow> int \\<times> int\" where\n  \"normalize p = (if snd p > 0 then (let a = gcd (fst p) (snd p) in (fst p div a, snd p div a))\n    else if snd p = 0 then (0, 1)\n    else (let a = - gcd (fst p) (snd p) in (fst p div a, snd p div a)))\"\n\nlemma normalize_crossproduct:\n  assumes \"q \\<noteq> 0\" \"s \\<noteq> 0\"\n  assumes \"normalize (p, q) = normalize (r, s)\"\n  shows \"p * s = r * q\"\nproof -\n  have aux: \"p * gcd r s = sgn (q * s) * r * gcd p q \\<Longrightarrow> q * gcd r s = sgn (q * s) * s * gcd p q \\<Longrightarrow> p * s = q * r\"\n  proof -\n    assume \"p * gcd r s = sgn (q * s) * r * gcd p q\" and \"q * gcd r s = sgn (q * s) * s * gcd p q\"\n    then have \"(p * gcd r s) * (sgn (q * s) * s * gcd p q) = (q * gcd r s) * (sgn (q * s) * r * gcd p q)\" by simp\n    with assms show \"p * s = q * r\" by (auto simp add: ac_simps sgn_times sgn_0_0)\n  qed\n  from assms show ?thesis\n    by (auto simp add: normalize_def Let_def dvd_div_div_eq_mult mult.commute sgn_times split: if_splits intro: aux)\nqed\n\nlemma normalize_eq: \"normalize (a, b) = (p, q) \\<Longrightarrow> Fract p q = Fract a b\"\n  by (auto simp add: normalize_def Let_def Fract_coprime dvd_div_neg rat_number_collapse\n    split:split_if_asm)\n\nlemma normalize_denom_pos: \"normalize r = (p, q) \\<Longrightarrow> q > 0\"\n  by (auto simp add: normalize_def Let_def dvd_div_neg pos_imp_zdiv_neg_iff nonneg1_imp_zdiv_pos_iff\n    split:split_if_asm)\n\nlemma normalize_coprime: \"normalize r = (p, q) \\<Longrightarrow> coprime p q\"\n  by (auto simp add: normalize_def Let_def dvd_div_neg div_gcd_coprime_int\n    split:split_if_asm)\n\nlemma normalize_stable [simp]:\n  \"q > 0 \\<Longrightarrow> coprime p q \\<Longrightarrow> normalize (p, q) = (p, q)\"\n  by (simp add: normalize_def)\n\nlemma normalize_denom_zero [simp]:\n  \"normalize (p, 0) = (0, 1)\"\n  by (simp add: normalize_def)\n\nlemma normalize_negative [simp]:\n  \"q < 0 \\<Longrightarrow> normalize (p, q) = normalize (- p, - q)\"\n  by (simp add: normalize_def Let_def dvd_div_neg dvd_neg_div)\n\ntext{*\n  Decompose a fraction into normalized, i.e. coprime numerator and denominator:\n*}\n\ndefinition quotient_of :: \"rat \\<Rightarrow> int \\<times> int\" where\n  \"quotient_of x = (THE pair. x = Fract (fst pair) (snd pair) &\n                   snd pair > 0 & coprime (fst pair) (snd pair))\"\n\nlemma quotient_of_unique:\n  \"\\<exists>!p. r = Fract (fst p) (snd p) \\<and> snd p > 0 \\<and> coprime (fst p) (snd p)\"\nproof (cases r)\n  case (Fract a b)\n  then have \"r = Fract (fst (a, b)) (snd (a, b)) \\<and> snd (a, b) > 0 \\<and> coprime (fst (a, b)) (snd (a, b))\" by auto\n  then show ?thesis proof (rule ex1I)\n    fix p\n    obtain c d :: int where p: \"p = (c, d)\" by (cases p)\n    assume \"r = Fract (fst p) (snd p) \\<and> snd p > 0 \\<and> coprime (fst p) (snd p)\"\n    with p have Fract': \"r = Fract c d\" \"d > 0\" \"coprime c d\" by simp_all\n    have \"c = a \\<and> d = b\"\n    proof (cases \"a = 0\")\n      case True with Fract Fract' show ?thesis by (simp add: eq_rat)\n    next\n      case False\n      with Fract Fract' have *: \"c * b = a * d\" and \"c \\<noteq> 0\" by (auto simp add: eq_rat)\n      then have \"c * b > 0 \\<longleftrightarrow> a * d > 0\" by auto\n      with `b > 0` `d > 0` have \"a > 0 \\<longleftrightarrow> c > 0\" by (simp add: zero_less_mult_iff)\n      with `a \\<noteq> 0` `c \\<noteq> 0` have sgn: \"sgn a = sgn c\" by (auto simp add: not_less)\n      from `coprime a b` `coprime c d` have \"\\<bar>a\\<bar> * \\<bar>d\\<bar> = \\<bar>c\\<bar> * \\<bar>b\\<bar> \\<longleftrightarrow> \\<bar>a\\<bar> = \\<bar>c\\<bar> \\<and> \\<bar>d\\<bar> = \\<bar>b\\<bar>\"\n        by (simp add: coprime_crossproduct_int)\n      with `b > 0` `d > 0` have \"\\<bar>a\\<bar> * d = \\<bar>c\\<bar> * b \\<longleftrightarrow> \\<bar>a\\<bar> = \\<bar>c\\<bar> \\<and> d = b\" by simp\n      then have \"a * sgn a * d = c * sgn c * b \\<longleftrightarrow> a * sgn a = c * sgn c \\<and> d = b\" by (simp add: abs_sgn)\n      with sgn * show ?thesis by (auto simp add: sgn_0_0)\n    qed\n    with p show \"p = (a, b)\" by simp\n  qed\nqed\n\nlemma quotient_of_Fract [code]:\n  \"quotient_of (Fract a b) = normalize (a, b)\"\nproof -\n  have \"Fract a b = Fract (fst (normalize (a, b))) (snd (normalize (a, b)))\" (is ?Fract)\n    by (rule sym) (auto intro: normalize_eq)\n  moreover have \"0 < snd (normalize (a, b))\" (is ?denom_pos)\n    by (cases \"normalize (a, b)\") (rule normalize_denom_pos, simp)\n  moreover have \"coprime (fst (normalize (a, b))) (snd (normalize (a, b)))\" (is ?coprime)\n    by (rule normalize_coprime) simp\n  ultimately have \"?Fract \\<and> ?denom_pos \\<and> ?coprime\" by blast\n  with quotient_of_unique have\n    \"(THE p. Fract a b = Fract (fst p) (snd p) \\<and> 0 < snd p \\<and> coprime (fst p) (snd p)) = normalize (a, b)\"\n    by (rule the1_equality)\n  then show ?thesis by (simp add: quotient_of_def)\nqed\n\nlemma quotient_of_number [simp]:\n  \"quotient_of 0 = (0, 1)\"\n  \"quotient_of 1 = (1, 1)\"\n  \"quotient_of (numeral k) = (numeral k, 1)\"\n  \"quotient_of (- 1) = (- 1, 1)\"\n  \"quotient_of (- numeral k) = (- numeral k, 1)\"\n  by (simp_all add: rat_number_expand quotient_of_Fract)\n\nlemma quotient_of_eq: \"quotient_of (Fract a b) = (p, q) \\<Longrightarrow> Fract p q = Fract a b\"\n  by (simp add: quotient_of_Fract normalize_eq)\n\nlemma quotient_of_denom_pos: \"quotient_of r = (p, q) \\<Longrightarrow> q > 0\"\n  by (cases r) (simp add: quotient_of_Fract normalize_denom_pos)\n\nlemma quotient_of_coprime: \"quotient_of r = (p, q) \\<Longrightarrow> coprime p q\"\n  by (cases r) (simp add: quotient_of_Fract normalize_coprime)\n\nlemma quotient_of_inject:\n  assumes \"quotient_of a = quotient_of b\"\n  shows \"a = b\"\nproof -\n  obtain p q r s where a: \"a = Fract p q\"\n    and b: \"b = Fract r s\"\n    and \"q > 0\" and \"s > 0\" by (cases a, cases b)\n  with assms show ?thesis by (simp add: eq_rat quotient_of_Fract normalize_crossproduct)\nqed\n\nlemma quotient_of_inject_eq:\n  \"quotient_of a = quotient_of b \\<longleftrightarrow> a = b\"\n  by (auto simp add: quotient_of_inject)\n\n\nsubsubsection {* Various *}\n\nlemma Fract_of_int_quotient: \"Fract k l = of_int k / of_int l\"\n  by (simp add: Fract_of_int_eq [symmetric])\n\nlemma Fract_add_one: \"n \\<noteq> 0 ==> Fract (m + n) n = Fract m n + 1\"\n  by (simp add: rat_number_expand)\n\nlemma quotient_of_div:\n  assumes r: \"quotient_of r = (n,d)\"\n  shows \"r = of_int n / of_int d\"\nproof -\n  from theI'[OF quotient_of_unique[of r], unfolded r[unfolded quotient_of_def]]\n  have \"r = Fract n d\" by simp\n  thus ?thesis using Fract_of_int_quotient by simp\nqed\n\nsubsubsection {* The ordered field of rational numbers *}\n\nlift_definition positive :: \"rat \\<Rightarrow> bool\"\n  is \"\\<lambda>x. 0 < fst x * snd x\"\nproof (clarsimp)\n  fix a b c d :: int\n  assume \"b \\<noteq> 0\" and \"d \\<noteq> 0\" and \"a * d = c * b\"\n  hence \"a * d * b * d = c * b * b * d\"\n    by simp\n  hence \"a * b * d\\<^sup>2 = c * d * b\\<^sup>2\"\n    unfolding power2_eq_square by (simp add: ac_simps)\n  hence \"0 < a * b * d\\<^sup>2 \\<longleftrightarrow> 0 < c * d * b\\<^sup>2\"\n    by simp\n  thus \"0 < a * b \\<longleftrightarrow> 0 < c * d\"\n    using `b \\<noteq> 0` and `d \\<noteq> 0`\n    by (simp add: zero_less_mult_iff)\nqed\n\nlemma positive_zero: \"\\<not> positive 0\"\n  by transfer simp\n\nlemma positive_add:\n  \"positive x \\<Longrightarrow> positive y \\<Longrightarrow> positive (x + y)\"\napply transfer\napply (simp add: zero_less_mult_iff)\napply (elim disjE, simp_all add: add_pos_pos add_neg_neg\n  mult_pos_neg mult_neg_pos mult_neg_neg)\ndone\n\nlemma positive_mult:\n  \"positive x \\<Longrightarrow> positive y \\<Longrightarrow> positive (x * y)\"\nby transfer (drule (1) mult_pos_pos, simp add: ac_simps)\n\nlemma positive_minus:\n  \"\\<not> positive x \\<Longrightarrow> x \\<noteq> 0 \\<Longrightarrow> positive (- x)\"\nby transfer (force simp: neq_iff zero_less_mult_iff mult_less_0_iff)\n\ninstantiation rat :: linordered_field_inverse_zero\nbegin\n\ndefinition\n  \"x < y \\<longleftrightarrow> positive (y - x)\"\n\ndefinition\n  \"x \\<le> (y::rat) \\<longleftrightarrow> x < y \\<or> x = y\"\n\ndefinition\n  \"abs (a::rat) = (if a < 0 then - a else a)\"\n\ndefinition\n  \"sgn (a::rat) = (if a = 0 then 0 else if 0 < a then 1 else - 1)\"\n\ninstance proof\n  fix a b c :: rat\n  show \"\\<bar>a\\<bar> = (if a < 0 then - a else a)\"\n    by (rule abs_rat_def)\n  show \"a < b \\<longleftrightarrow> a \\<le> b \\<and> \\<not> b \\<le> a\"\n    unfolding less_eq_rat_def less_rat_def\n    by (auto, drule (1) positive_add, simp_all add: positive_zero)\n  show \"a \\<le> a\"\n    unfolding less_eq_rat_def by simp\n  show \"a \\<le> b \\<Longrightarrow> b \\<le> c \\<Longrightarrow> a \\<le> c\"\n    unfolding less_eq_rat_def less_rat_def\n    by (auto, drule (1) positive_add, simp add: algebra_simps)\n  show \"a \\<le> b \\<Longrightarrow> b \\<le> a \\<Longrightarrow> a = b\"\n    unfolding less_eq_rat_def less_rat_def\n    by (auto, drule (1) positive_add, simp add: positive_zero)\n  show \"a \\<le> b \\<Longrightarrow> c + a \\<le> c + b\"\n    unfolding less_eq_rat_def less_rat_def by auto\n  show \"sgn a = (if a = 0 then 0 else if 0 < a then 1 else - 1)\"\n    by (rule sgn_rat_def)\n  show \"a \\<le> b \\<or> b \\<le> a\"\n    unfolding less_eq_rat_def less_rat_def\n    by (auto dest!: positive_minus)\n  show \"a < b \\<Longrightarrow> 0 < c \\<Longrightarrow> c * a < c * b\"\n    unfolding less_rat_def\n    by (drule (1) positive_mult, simp add: algebra_simps)\nqed\n\nend\n\ninstantiation rat :: distrib_lattice\nbegin\n\ndefinition\n  \"(inf :: rat \\<Rightarrow> rat \\<Rightarrow> rat) = min\"\n\ndefinition\n  \"(sup :: rat \\<Rightarrow> rat \\<Rightarrow> rat) = max\"\n\ninstance proof\nqed (auto simp add: inf_rat_def sup_rat_def max_min_distrib2)\n\nend\n\nlemma positive_rat: \"positive (Fract a b) \\<longleftrightarrow> 0 < a * b\"\n  by transfer simp\n\nlemma less_rat [simp]:\n  assumes \"b \\<noteq> 0\" and \"d \\<noteq> 0\"\n  shows \"Fract a b < Fract c d \\<longleftrightarrow> (a * d) * (b * d) < (c * b) * (b * d)\"\n  using assms unfolding less_rat_def\n  by (simp add: positive_rat algebra_simps)\n\nlemma le_rat [simp]:\n  assumes \"b \\<noteq> 0\" and \"d \\<noteq> 0\"\n  shows \"Fract a b \\<le> Fract c d \\<longleftrightarrow> (a * d) * (b * d) \\<le> (c * b) * (b * d)\"\n  using assms unfolding le_less by (simp add: eq_rat)\n\nlemma abs_rat [simp, code]: \"\\<bar>Fract a b\\<bar> = Fract \\<bar>a\\<bar> \\<bar>b\\<bar>\"\n  by (auto simp add: abs_rat_def zabs_def Zero_rat_def not_less le_less eq_rat zero_less_mult_iff)\n\nlemma sgn_rat [simp, code]: \"sgn (Fract a b) = of_int (sgn a * sgn b)\"\n  unfolding Fract_of_int_eq\n  by (auto simp: zsgn_def sgn_rat_def Zero_rat_def eq_rat)\n    (auto simp: rat_number_collapse not_less le_less zero_less_mult_iff)\n\nlemma Rat_induct_pos [case_names Fract, induct type: rat]:\n  assumes step: \"\\<And>a b. 0 < b \\<Longrightarrow> P (Fract a b)\"\n  shows \"P q\"\nproof (cases q)\n  have step': \"\\<And>a b. b < 0 \\<Longrightarrow> P (Fract a b)\"\n  proof -\n    fix a::int and b::int\n    assume b: \"b < 0\"\n    hence \"0 < -b\" by simp\n    hence \"P (Fract (-a) (-b))\" by (rule step)\n    thus \"P (Fract a b)\" by (simp add: order_less_imp_not_eq [OF b])\n  qed\n  case (Fract a b)\n  thus \"P q\" by (force simp add: linorder_neq_iff step step')\nqed\n\nlemma zero_less_Fract_iff:\n  \"0 < b \\<Longrightarrow> 0 < Fract a b \\<longleftrightarrow> 0 < a\"\n  by (simp add: Zero_rat_def zero_less_mult_iff)\n\nlemma Fract_less_zero_iff:\n  \"0 < b \\<Longrightarrow> Fract a b < 0 \\<longleftrightarrow> a < 0\"\n  by (simp add: Zero_rat_def mult_less_0_iff)\n\nlemma zero_le_Fract_iff:\n  \"0 < b \\<Longrightarrow> 0 \\<le> Fract a b \\<longleftrightarrow> 0 \\<le> a\"\n  by (simp add: Zero_rat_def zero_le_mult_iff)\n\nlemma Fract_le_zero_iff:\n  \"0 < b \\<Longrightarrow> Fract a b \\<le> 0 \\<longleftrightarrow> a \\<le> 0\"\n  by (simp add: Zero_rat_def mult_le_0_iff)\n\nlemma one_less_Fract_iff:\n  \"0 < b \\<Longrightarrow> 1 < Fract a b \\<longleftrightarrow> b < a\"\n  by (simp add: One_rat_def mult_less_cancel_right_disj)\n\nlemma Fract_less_one_iff:\n  \"0 < b \\<Longrightarrow> Fract a b < 1 \\<longleftrightarrow> a < b\"\n  by (simp add: One_rat_def mult_less_cancel_right_disj)\n\nlemma one_le_Fract_iff:\n  \"0 < b \\<Longrightarrow> 1 \\<le> Fract a b \\<longleftrightarrow> b \\<le> a\"\n  by (simp add: One_rat_def mult_le_cancel_right)\n\nlemma Fract_le_one_iff:\n  \"0 < b \\<Longrightarrow> Fract a b \\<le> 1 \\<longleftrightarrow> a \\<le> b\"\n  by (simp add: One_rat_def mult_le_cancel_right)\n\n\nsubsubsection {* Rationals are an Archimedean field *}\n\nlemma rat_floor_lemma:\n  shows \"of_int (a div b) \\<le> Fract a b \\<and> Fract a b < of_int (a div b + 1)\"\nproof -\n  have \"Fract a b = of_int (a div b) + Fract (a mod b) b\"\n    by (cases \"b = 0\", simp, simp add: of_int_rat)\n  moreover have \"0 \\<le> Fract (a mod b) b \\<and> Fract (a mod b) b < 1\"\n    unfolding Fract_of_int_quotient\n    by (rule linorder_cases [of b 0]) (simp_all add: divide_nonpos_neg)\n  ultimately show ?thesis by simp\nqed\n\ninstance rat :: archimedean_field\nproof\n  fix r :: rat\n  show \"\\<exists>z. r \\<le> of_int z\"\n  proof (induct r)\n    case (Fract a b)\n    have \"Fract a b \\<le> of_int (a div b + 1)\"\n      using rat_floor_lemma [of a b] by simp\n    then show \"\\<exists>z. Fract a b \\<le> of_int z\" ..\n  qed\nqed\n\ninstantiation rat :: floor_ceiling\nbegin\n\ndefinition [code del]:\n  \"floor (x::rat) = (THE z. of_int z \\<le> x \\<and> x < of_int (z + 1))\"\n\ninstance proof\n  fix x :: rat\n  show \"of_int (floor x) \\<le> x \\<and> x < of_int (floor x + 1)\"\n    unfolding floor_rat_def using floor_exists1 by (rule theI')\nqed\n\nend\n\nlemma floor_Fract: \"floor (Fract a b) = a div b\"\n  using rat_floor_lemma [of a b]\n  by (simp add: floor_unique)\n\n\nsubsection {* Linear arithmetic setup *}\n\ndeclaration {*\n  K (Lin_Arith.add_inj_thms [@{thm of_nat_le_iff} RS iffD2, @{thm of_nat_eq_iff} RS iffD2]\n    (* not needed because x < (y::nat) can be rewritten as Suc x <= y: of_nat_less_iff RS iffD2 *)\n  #> Lin_Arith.add_inj_thms [@{thm of_int_le_iff} RS iffD2, @{thm of_int_eq_iff} RS iffD2]\n    (* not needed because x < (y::int) can be rewritten as x + 1 <= y: of_int_less_iff RS iffD2 *)\n  #> Lin_Arith.add_simps [@{thm neg_less_iff_less},\n      @{thm True_implies_equals},\n      @{thm distrib_left [where a = \"numeral v\" for v]},\n      @{thm distrib_left [where a = \"- numeral v\" for v]},\n      @{thm divide_1}, @{thm divide_zero_left},\n      @{thm times_divide_eq_right}, @{thm times_divide_eq_left},\n      @{thm minus_divide_left} RS sym, @{thm minus_divide_right} RS sym,\n      @{thm of_int_minus}, @{thm of_int_diff},\n      @{thm of_int_of_nat_eq}]\n  #> Lin_Arith.add_simprocs Numeral_Simprocs.field_divide_cancel_numeral_factor\n  #> Lin_Arith.add_inj_const (@{const_name of_nat}, @{typ \"nat => rat\"})\n  #> Lin_Arith.add_inj_const (@{const_name of_int}, @{typ \"int => rat\"}))\n*}\n\n\nsubsection {* Embedding from Rationals to other Fields *}\n\nclass field_char_0 = field + ring_char_0\n\nsubclass (in linordered_field) field_char_0 ..\n\ncontext field_char_0\nbegin\n\nlift_definition of_rat :: \"rat \\<Rightarrow> 'a\"\n  is \"\\<lambda>x. of_int (fst x) / of_int (snd x)\"\napply (clarsimp simp add: nonzero_divide_eq_eq nonzero_eq_divide_eq)\napply (simp only: of_int_mult [symmetric])\ndone\n\nend\n\nlemma of_rat_rat: \"b \\<noteq> 0 \\<Longrightarrow> of_rat (Fract a b) = of_int a / of_int b\"\n  by transfer simp\n\nlemma of_rat_0 [simp]: \"of_rat 0 = 0\"\n  by transfer simp\n\nlemma of_rat_1 [simp]: \"of_rat 1 = 1\"\n  by transfer simp\n\nlemma of_rat_add: \"of_rat (a + b) = of_rat a + of_rat b\"\n  by transfer (simp add: add_frac_eq)\n\nlemma of_rat_minus: \"of_rat (- a) = - of_rat a\"\n  by transfer simp\n\nlemma of_rat_neg_one [simp]:\n  \"of_rat (- 1) = - 1\"\n  by (simp add: of_rat_minus)\n\nlemma of_rat_diff: \"of_rat (a - b) = of_rat a - of_rat b\"\n  using of_rat_add [of a \"- b\"] by (simp add: of_rat_minus)\n\nlemma of_rat_mult: \"of_rat (a * b) = of_rat a * of_rat b\"\napply transfer\napply (simp add: divide_inverse nonzero_inverse_mult_distrib ac_simps)\ndone\n\nlemma of_rat_setsum: \"of_rat (\\<Sum>a\\<in>A. f a) = (\\<Sum>a\\<in>A. of_rat (f a))\"\n  by (induct rule: infinite_finite_induct) (auto simp: of_rat_add)\n\nlemma of_rat_setprod: \"of_rat (\\<Prod>a\\<in>A. f a) = (\\<Prod>a\\<in>A. of_rat (f a))\"\n  by (induct rule: infinite_finite_induct) (auto simp: of_rat_mult)\n\nlemma nonzero_of_rat_inverse:\n  \"a \\<noteq> 0 \\<Longrightarrow> of_rat (inverse a) = inverse (of_rat a)\"\napply (rule inverse_unique [symmetric])\napply (simp add: of_rat_mult [symmetric])\ndone\n\nlemma of_rat_inverse:\n  \"(of_rat (inverse a)::'a::{field_char_0, field_inverse_zero}) =\n   inverse (of_rat a)\"\nby (cases \"a = 0\", simp_all add: nonzero_of_rat_inverse)\n\nlemma nonzero_of_rat_divide:\n  \"b \\<noteq> 0 \\<Longrightarrow> of_rat (a / b) = of_rat a / of_rat b\"\nby (simp add: divide_inverse of_rat_mult nonzero_of_rat_inverse)\n\nlemma of_rat_divide:\n  \"(of_rat (a / b)::'a::{field_char_0, field_inverse_zero})\n   = of_rat a / of_rat b\"\nby (cases \"b = 0\") (simp_all add: nonzero_of_rat_divide)\n\nlemma of_rat_power:\n  \"(of_rat (a ^ n)::'a::field_char_0) = of_rat a ^ n\"\nby (induct n) (simp_all add: of_rat_mult)\n\nlemma of_rat_eq_iff [simp]: \"(of_rat a = of_rat b) = (a = b)\"\napply transfer\napply (simp add: nonzero_divide_eq_eq nonzero_eq_divide_eq)\napply (simp only: of_int_mult [symmetric] of_int_eq_iff)\ndone\n\nlemma of_rat_eq_0_iff [simp]: \"(of_rat a = 0) = (a = 0)\"\n  using of_rat_eq_iff [of _ 0] by simp\n\nlemma zero_eq_of_rat_iff [simp]: \"(0 = of_rat a) = (0 = a)\"\n  by simp\n\nlemma of_rat_eq_1_iff [simp]: \"(of_rat a = 1) = (a = 1)\"\n  using of_rat_eq_iff [of _ 1] by simp\n\nlemma one_eq_of_rat_iff [simp]: \"(1 = of_rat a) = (1 = a)\"\n  by simp\n\nlemma of_rat_less:\n  \"(of_rat r :: 'a::linordered_field) < of_rat s \\<longleftrightarrow> r < s\"\nproof (induct r, induct s)\n  fix a b c d :: int\n  assume not_zero: \"b > 0\" \"d > 0\"\n  then have \"b * d > 0\" by simp\n  have of_int_divide_less_eq:\n    \"(of_int a :: 'a) / of_int b < of_int c / of_int d\n      \\<longleftrightarrow> (of_int a :: 'a) * of_int d < of_int c * of_int b\"\n    using not_zero by (simp add: pos_less_divide_eq pos_divide_less_eq)\n  show \"(of_rat (Fract a b) :: 'a::linordered_field) < of_rat (Fract c d)\n    \\<longleftrightarrow> Fract a b < Fract c d\"\n    using not_zero `b * d > 0`\n    by (simp add: of_rat_rat of_int_divide_less_eq of_int_mult [symmetric] del: of_int_mult)\nqed\n\nlemma of_rat_less_eq:\n  \"(of_rat r :: 'a::linordered_field) \\<le> of_rat s \\<longleftrightarrow> r \\<le> s\"\n  unfolding le_less by (auto simp add: of_rat_less)\n\nlemma of_rat_le_0_iff [simp]: \"((of_rat r :: 'a::linordered_field) \\<le> 0) = (r \\<le> 0)\"\n  using of_rat_less_eq [of r 0, where 'a='a] by simp\n\nlemma zero_le_of_rat_iff [simp]: \"(0 \\<le> (of_rat r :: 'a::linordered_field)) = (0 \\<le> r)\"\n  using of_rat_less_eq [of 0 r, where 'a='a] by simp\n\nlemma of_rat_le_1_iff [simp]: \"((of_rat r :: 'a::linordered_field) \\<le> 1) = (r \\<le> 1)\"\n  using of_rat_less_eq [of r 1] by simp\n\nlemma one_le_of_rat_iff [simp]: \"(1 \\<le> (of_rat r :: 'a::linordered_field)) = (1 \\<le> r)\"\n  using of_rat_less_eq [of 1 r] by simp\n\nlemma of_rat_less_0_iff [simp]: \"((of_rat r :: 'a::linordered_field) < 0) = (r < 0)\"\n  using of_rat_less [of r 0, where 'a='a] by simp\n\nlemma zero_less_of_rat_iff [simp]: \"(0 < (of_rat r :: 'a::linordered_field)) = (0 < r)\"\n  using of_rat_less [of 0 r, where 'a='a] by simp\n\nlemma of_rat_less_1_iff [simp]: \"((of_rat r :: 'a::linordered_field) < 1) = (r < 1)\"\n  using of_rat_less [of r 1] by simp\n\nlemma one_less_of_rat_iff [simp]: \"(1 < (of_rat r :: 'a::linordered_field)) = (1 < r)\"\n  using of_rat_less [of 1 r] by simp\n\nlemma of_rat_eq_id [simp]: \"of_rat = id\"\nproof\n  fix a\n  show \"of_rat a = id a\"\n  by (induct a)\n     (simp add: of_rat_rat Fract_of_int_eq [symmetric])\nqed\n\ntext{*Collapse nested embeddings*}\nlemma of_rat_of_nat_eq [simp]: \"of_rat (of_nat n) = of_nat n\"\nby (induct n) (simp_all add: of_rat_add)\n\nlemma of_rat_of_int_eq [simp]: \"of_rat (of_int z) = of_int z\"\nby (cases z rule: int_diff_cases) (simp add: of_rat_diff)\n\nlemma of_rat_numeral_eq [simp]:\n  \"of_rat (numeral w) = numeral w\"\nusing of_rat_of_int_eq [of \"numeral w\"] by simp\n\nlemma of_rat_neg_numeral_eq [simp]:\n  \"of_rat (- numeral w) = - numeral w\"\nusing of_rat_of_int_eq [of \"- numeral w\"] by simp\n\nlemmas zero_rat = Zero_rat_def\nlemmas one_rat = One_rat_def\n\nabbreviation\n  rat_of_nat :: \"nat \\<Rightarrow> rat\"\nwhere\n  \"rat_of_nat \\<equiv> of_nat\"\n\nabbreviation\n  rat_of_int :: \"int \\<Rightarrow> rat\"\nwhere\n  \"rat_of_int \\<equiv> of_int\"\n\nsubsection {* The Set of Rational Numbers *}\n\ncontext field_char_0\nbegin\n\ndefinition\n  Rats  :: \"'a set\" where\n  \"Rats = range of_rat\"\n\nnotation (xsymbols)\n  Rats  (\"\\<rat>\")\n\nend\n\nlemma Rats_of_rat [simp]: \"of_rat r \\<in> Rats\"\nby (simp add: Rats_def)\n\nlemma Rats_of_int [simp]: \"of_int z \\<in> Rats\"\nby (subst of_rat_of_int_eq [symmetric], rule Rats_of_rat)\n\nlemma Rats_of_nat [simp]: \"of_nat n \\<in> Rats\"\nby (subst of_rat_of_nat_eq [symmetric], rule Rats_of_rat)\n\nlemma Rats_number_of [simp]: \"numeral w \\<in> Rats\"\nby (subst of_rat_numeral_eq [symmetric], rule Rats_of_rat)\n\nlemma Rats_0 [simp]: \"0 \\<in> Rats\"\napply (unfold Rats_def)\napply (rule range_eqI)\napply (rule of_rat_0 [symmetric])\ndone\n\nlemma Rats_1 [simp]: \"1 \\<in> Rats\"\napply (unfold Rats_def)\napply (rule range_eqI)\napply (rule of_rat_1 [symmetric])\ndone\n\nlemma Rats_add [simp]: \"\\<lbrakk>a \\<in> Rats; b \\<in> Rats\\<rbrakk> \\<Longrightarrow> a + b \\<in> Rats\"\napply (auto simp add: Rats_def)\napply (rule range_eqI)\napply (rule of_rat_add [symmetric])\ndone\n\nlemma Rats_minus [simp]: \"a \\<in> Rats \\<Longrightarrow> - a \\<in> Rats\"\napply (auto simp add: Rats_def)\napply (rule range_eqI)\napply (rule of_rat_minus [symmetric])\ndone\n\nlemma Rats_diff [simp]: \"\\<lbrakk>a \\<in> Rats; b \\<in> Rats\\<rbrakk> \\<Longrightarrow> a - b \\<in> Rats\"\napply (auto simp add: Rats_def)\napply (rule range_eqI)\napply (rule of_rat_diff [symmetric])\ndone\n\nlemma Rats_mult [simp]: \"\\<lbrakk>a \\<in> Rats; b \\<in> Rats\\<rbrakk> \\<Longrightarrow> a * b \\<in> Rats\"\napply (auto simp add: Rats_def)\napply (rule range_eqI)\napply (rule of_rat_mult [symmetric])\ndone\n\nlemma nonzero_Rats_inverse:\n  fixes a :: \"'a::field_char_0\"\n  shows \"\\<lbrakk>a \\<in> Rats; a \\<noteq> 0\\<rbrakk> \\<Longrightarrow> inverse a \\<in> Rats\"\napply (auto simp add: Rats_def)\napply (rule range_eqI)\napply (erule nonzero_of_rat_inverse [symmetric])\ndone\n\nlemma Rats_inverse [simp]:\n  fixes a :: \"'a::{field_char_0, field_inverse_zero}\"\n  shows \"a \\<in> Rats \\<Longrightarrow> inverse a \\<in> Rats\"\napply (auto simp add: Rats_def)\napply (rule range_eqI)\napply (rule of_rat_inverse [symmetric])\ndone\n\nlemma nonzero_Rats_divide:\n  fixes a b :: \"'a::field_char_0\"\n  shows \"\\<lbrakk>a \\<in> Rats; b \\<in> Rats; b \\<noteq> 0\\<rbrakk> \\<Longrightarrow> a / b \\<in> Rats\"\napply (auto simp add: Rats_def)\napply (rule range_eqI)\napply (erule nonzero_of_rat_divide [symmetric])\ndone\n\nlemma Rats_divide [simp]:\n  fixes a b :: \"'a::{field_char_0, field_inverse_zero}\"\n  shows \"\\<lbrakk>a \\<in> Rats; b \\<in> Rats\\<rbrakk> \\<Longrightarrow> a / b \\<in> Rats\"\napply (auto simp add: Rats_def)\napply (rule range_eqI)\napply (rule of_rat_divide [symmetric])\ndone\n\nlemma Rats_power [simp]:\n  fixes a :: \"'a::field_char_0\"\n  shows \"a \\<in> Rats \\<Longrightarrow> a ^ n \\<in> Rats\"\napply (auto simp add: Rats_def)\napply (rule range_eqI)\napply (rule of_rat_power [symmetric])\ndone\n\nlemma Rats_cases [cases set: Rats]:\n  assumes \"q \\<in> \\<rat>\"\n  obtains (of_rat) r where \"q = of_rat r\"\nproof -\n  from `q \\<in> \\<rat>` have \"q \\<in> range of_rat\" unfolding Rats_def .\n  then obtain r where \"q = of_rat r\" ..\n  then show thesis ..\nqed\n\nlemma Rats_induct [case_names of_rat, induct set: Rats]:\n  \"q \\<in> \\<rat> \\<Longrightarrow> (\\<And>r. P (of_rat r)) \\<Longrightarrow> P q\"\n  by (rule Rats_cases) auto\n\nlemma Rats_infinite: \"\\<not> finite \\<rat>\"\n  by (auto dest!: finite_imageD simp: inj_on_def infinite_UNIV_char_0 Rats_def)\n\nsubsection {* Implementation of rational numbers as pairs of integers *}\n\ntext {* Formal constructor *}\n\ndefinition Frct :: \"int \\<times> int \\<Rightarrow> rat\" where\n  [simp]: \"Frct p = Fract (fst p) (snd p)\"\n\nlemma [code abstype]:\n  \"Frct (quotient_of q) = q\"\n  by (cases q) (auto intro: quotient_of_eq)\n\n\ntext {* Numerals *}\n\ndeclare quotient_of_Fract [code abstract]\n\ndefinition of_int :: \"int \\<Rightarrow> rat\"\nwhere\n  [code_abbrev]: \"of_int = Int.of_int\"\nhide_const (open) of_int\n\nlemma quotient_of_int [code abstract]:\n  \"quotient_of (Rat.of_int a) = (a, 1)\"\n  by (simp add: of_int_def of_int_rat quotient_of_Fract)\n\nlemma [code_unfold]:\n  \"numeral k = Rat.of_int (numeral k)\"\n  by (simp add: Rat.of_int_def)\n\nlemma [code_unfold]:\n  \"- numeral k = Rat.of_int (- numeral k)\"\n  by (simp add: Rat.of_int_def)\n\nlemma Frct_code_post [code_post]:\n  \"Frct (0, a) = 0\"\n  \"Frct (a, 0) = 0\"\n  \"Frct (1, 1) = 1\"\n  \"Frct (numeral k, 1) = numeral k\"\n  \"Frct (1, numeral k) = 1 / numeral k\"\n  \"Frct (numeral k, numeral l) = numeral k / numeral l\"\n  \"Frct (- a, b) = - Frct (a, b)\"\n  \"Frct (a, - b) = - Frct (a, b)\"\n  \"- (- Frct q) = Frct q\"\n  by (simp_all add: Fract_of_int_quotient)\n\n\ntext {* Operations *}\n\nlemma rat_zero_code [code abstract]:\n  \"quotient_of 0 = (0, 1)\"\n  by (simp add: Zero_rat_def quotient_of_Fract normalize_def)\n\nlemma rat_one_code [code abstract]:\n  \"quotient_of 1 = (1, 1)\"\n  by (simp add: One_rat_def quotient_of_Fract normalize_def)\n\nlemma rat_plus_code [code abstract]:\n  \"quotient_of (p + q) = (let (a, c) = quotient_of p; (b, d) = quotient_of q\n     in normalize (a * d + b * c, c * d))\"\n  by (cases p, cases q) (simp add: quotient_of_Fract)\n\nlemma rat_uminus_code [code abstract]:\n  \"quotient_of (- p) = (let (a, b) = quotient_of p in (- a, b))\"\n  by (cases p) (simp add: quotient_of_Fract)\n\nlemma rat_minus_code [code abstract]:\n  \"quotient_of (p - q) = (let (a, c) = quotient_of p; (b, d) = quotient_of q\n     in normalize (a * d - b * c, c * d))\"\n  by (cases p, cases q) (simp add: quotient_of_Fract)\n\nlemma rat_times_code [code abstract]:\n  \"quotient_of (p * q) = (let (a, c) = quotient_of p; (b, d) = quotient_of q\n     in normalize (a * b, c * d))\"\n  by (cases p, cases q) (simp add: quotient_of_Fract)\n\nlemma rat_inverse_code [code abstract]:\n  \"quotient_of (inverse p) = (let (a, b) = quotient_of p\n    in if a = 0 then (0, 1) else (sgn a * b, \\<bar>a\\<bar>))\"\nproof (cases p)\n  case (Fract a b) then show ?thesis\n    by (cases \"0::int\" a rule: linorder_cases) (simp_all add: quotient_of_Fract gcd_int.commute)\nqed\n\nlemma rat_divide_code [code abstract]:\n  \"quotient_of (p / q) = (let (a, c) = quotient_of p; (b, d) = quotient_of q\n     in normalize (a * d, c * b))\"\n  by (cases p, cases q) (simp add: quotient_of_Fract)\n\nlemma rat_abs_code [code abstract]:\n  \"quotient_of \\<bar>p\\<bar> = (let (a, b) = quotient_of p in (\\<bar>a\\<bar>, b))\"\n  by (cases p) (simp add: quotient_of_Fract)\n\nlemma rat_sgn_code [code abstract]:\n  \"quotient_of (sgn p) = (sgn (fst (quotient_of p)), 1)\"\nproof (cases p)\n  case (Fract a b) then show ?thesis\n  by (cases \"0::int\" a rule: linorder_cases) (simp_all add: quotient_of_Fract)\nqed\n\nlemma rat_floor_code [code]:\n  \"floor p = (let (a, b) = quotient_of p in a div b)\"\nby (cases p) (simp add: quotient_of_Fract floor_Fract)\n\ninstantiation rat :: equal\nbegin\n\ndefinition [code]:\n  \"HOL.equal a b \\<longleftrightarrow> quotient_of a = quotient_of b\"\n\ninstance proof\nqed (simp add: equal_rat_def quotient_of_inject_eq)\n\nlemma rat_eq_refl [code nbe]:\n  \"HOL.equal (r::rat) r \\<longleftrightarrow> True\"\n  by (rule equal_refl)\n\nend\n\nlemma rat_less_eq_code [code]:\n  \"p \\<le> q \\<longleftrightarrow> (let (a, c) = quotient_of p; (b, d) = quotient_of q in a * d \\<le> c * b)\"\n  by (cases p, cases q) (simp add: quotient_of_Fract mult.commute)\n\nlemma rat_less_code [code]:\n  \"p < q \\<longleftrightarrow> (let (a, c) = quotient_of p; (b, d) = quotient_of q in a * d < c * b)\"\n  by (cases p, cases q) (simp add: quotient_of_Fract mult.commute)\n\n\n\n\ntext {* Quickcheck *}\n\ndefinition (in term_syntax)\n  valterm_fract :: \"int \\<times> (unit \\<Rightarrow> Code_Evaluation.term) \\<Rightarrow> int \\<times> (unit \\<Rightarrow> Code_Evaluation.term) \\<Rightarrow> rat \\<times> (unit \\<Rightarrow> Code_Evaluation.term)\" where\n  [code_unfold]: \"valterm_fract k l = Code_Evaluation.valtermify Fract {\\<cdot>} k {\\<cdot>} l\"\n\nnotation fcomp (infixl \"\\<circ>>\" 60)\nnotation scomp (infixl \"\\<circ>\\<rightarrow>\" 60)\n\ninstantiation rat :: random\nbegin\n\ndefinition\n  \"Quickcheck_Random.random i = Quickcheck_Random.random i \\<circ>\\<rightarrow> (\\<lambda>num. Random.range i \\<circ>\\<rightarrow> (\\<lambda>denom. Pair (\n     let j = int_of_integer (integer_of_natural (denom + 1))\n     in valterm_fract num (j, \\<lambda>u. Code_Evaluation.term_of j))))\"\n\ninstance ..\n\nend\n\nno_notation fcomp (infixl \"\\<circ>>\" 60)\nno_notation scomp (infixl \"\\<circ>\\<rightarrow>\" 60)\n\ninstantiation rat :: exhaustive\nbegin\n\ndefinition\n  \"exhaustive_rat f d = Quickcheck_Exhaustive.exhaustive\n    (\\<lambda>l. Quickcheck_Exhaustive.exhaustive (\\<lambda>k. f (Fract k (int_of_integer (integer_of_natural l) + 1))) d) d\"\n\ninstance ..\n\nend\n\ninstantiation rat :: full_exhaustive\nbegin\n\ndefinition\n  \"full_exhaustive_rat f d = Quickcheck_Exhaustive.full_exhaustive (%(l, _). Quickcheck_Exhaustive.full_exhaustive (%k.\n     f (let j = int_of_integer (integer_of_natural l) + 1\n        in valterm_fract k (j, %_. Code_Evaluation.term_of j))) d) d\"\n\ninstance ..\n\nend\n\ninstantiation rat :: partial_term_of\nbegin\n\ninstance ..\n\nend\n\nlemma [code]:\n  \"partial_term_of (ty :: rat itself) (Quickcheck_Narrowing.Narrowing_variable p tt) == Code_Evaluation.Free (STR ''_'') (Typerep.Typerep (STR ''Rat.rat'') [])\"\n  \"partial_term_of (ty :: rat itself) (Quickcheck_Narrowing.Narrowing_constructor 0 [l, k]) ==\n     Code_Evaluation.App (Code_Evaluation.Const (STR ''Rat.Frct'')\n     (Typerep.Typerep (STR ''fun'') [Typerep.Typerep (STR ''Product_Type.prod'') [Typerep.Typerep (STR ''Int.int'') [], Typerep.Typerep (STR ''Int.int'') []],\n        Typerep.Typerep (STR ''Rat.rat'') []])) (Code_Evaluation.App (Code_Evaluation.App (Code_Evaluation.Const (STR ''Product_Type.Pair'') (Typerep.Typerep (STR ''fun'') [Typerep.Typerep (STR ''Int.int'') [], Typerep.Typerep (STR ''fun'') [Typerep.Typerep (STR ''Int.int'') [], Typerep.Typerep (STR ''Product_Type.prod'') [Typerep.Typerep (STR ''Int.int'') [], Typerep.Typerep (STR ''Int.int'') []]]])) (partial_term_of (TYPE(int)) l)) (partial_term_of (TYPE(int)) k))\"\nby (rule partial_term_of_anything)+\n\ninstantiation rat :: narrowing\nbegin\n\ndefinition\n  \"narrowing = Quickcheck_Narrowing.apply (Quickcheck_Narrowing.apply\n    (Quickcheck_Narrowing.cons (%nom denom. Fract nom denom)) narrowing) narrowing\"\n\ninstance ..\n\nend\n\n\nsubsection {* Setup for Nitpick *}\n\ndeclaration {*\n  Nitpick_HOL.register_frac_type @{type_name rat}\n   [(@{const_name zero_rat_inst.zero_rat}, @{const_name Nitpick.zero_frac}),\n    (@{const_name one_rat_inst.one_rat}, @{const_name Nitpick.one_frac}),\n    (@{const_name plus_rat_inst.plus_rat}, @{const_name Nitpick.plus_frac}),\n    (@{const_name times_rat_inst.times_rat}, @{const_name Nitpick.times_frac}),\n    (@{const_name uminus_rat_inst.uminus_rat}, @{const_name Nitpick.uminus_frac}),\n    (@{const_name inverse_rat_inst.inverse_rat}, @{const_name Nitpick.inverse_frac}),\n    (@{const_name ord_rat_inst.less_rat}, @{const_name Nitpick.less_frac}),\n    (@{const_name ord_rat_inst.less_eq_rat}, @{const_name Nitpick.less_eq_frac}),\n    (@{const_name field_char_0_class.of_rat}, @{const_name Nitpick.of_frac})]\n*}\n\nlemmas [nitpick_unfold] = inverse_rat_inst.inverse_rat\n  one_rat_inst.one_rat ord_rat_inst.less_rat\n  ord_rat_inst.less_eq_rat plus_rat_inst.plus_rat times_rat_inst.times_rat\n  uminus_rat_inst.uminus_rat zero_rat_inst.zero_rat\n\n\nsubsection {* Float syntax *}\n\nsyntax \"_Float\" :: \"float_const \\<Rightarrow> 'a\"    (\"_\")\n\nparse_translation {*\n  let\n    fun mk_frac str =\n      let\n        val {mant = i, exp = n} = Lexicon.read_float str;\n        val exp = Syntax.const @{const_syntax Power.power};\n        val ten = Numeral.mk_number_syntax 10;\n        val exp10 = if n = 1 then ten else exp $ ten $ Numeral.mk_number_syntax n;;\n      in Syntax.const @{const_syntax divide} $ Numeral.mk_number_syntax i $ exp10 end;\n\n    fun float_tr [(c as Const (@{syntax_const \"_constrain\"}, _)) $ t $ u] = c $ float_tr [t] $ u\n      | float_tr [t as Const (str, _)] = mk_frac str\n      | float_tr ts = raise TERM (\"float_tr\", ts);\n  in [(@{syntax_const \"_Float\"}, K float_tr)] end\n*}\n\ntext{* Test: *}\nlemma \"123.456 = -111.111 + 200 + 30 + 4 + 5/10 + 6/100 + (7/1000::rat)\"\n  by simp\n\n\nsubsection {* Hiding implementation details *}\n\nhide_const (open) normalize positive\n\nlifting_update rat.lifting\nlifting_forget rat.lifting\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/Rat.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869884059266, "lm_q2_score": 0.851952809486198, "lm_q1q2_score": 0.7461291852838855}}
{"text": "(*<*)\ntheory Ifexpr imports Main begin\n(*>*)\n\nsubsection\\<open>Case Study: Boolean Expressions\\<close>\n\ntext\\<open>\\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\\<close>\n\nsubsubsection\\<open>Modelling Boolean Expressions\\<close>\n\ntext\\<open>\nWe want to represent boolean expressions built up from variables and\nconstants by negation and conjunction. The following datatype serves exactly\nthat purpose:\n\\<close>\n\ndatatype boolex = Const bool | Var nat | Neg boolex\n                | And boolex boolex\n\ntext\\<open>\\noindent\nThe two constants are represented by \\<^term>\\<open>Const True\\<close> and\n\\<^term>\\<open>Const False\\<close>. Variables are represented by terms of the form\n\\<^term>\\<open>Var n\\<close>, where \\<^term>\\<open>n\\<close> is a natural number (type \\<^typ>\\<open>nat\\<close>).\nFor example, the formula $P@0 \\land \\neg P@1$ is represented by the term\n\\<^term>\\<open>And (Var 0) (Neg(Var 1))\\<close>.\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 \\<open>value\\<close> takes an additional parameter, an\n\\emph{environment} of type \\<^typ>\\<open>nat => bool\\<close>, which maps variables to their\nvalues:\n\\<close>\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\\<open>\\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>\\<open>CIF\\<close>), variables (\\<^term>\\<open>VIF\\<close>) and conditionals\n(\\<^term>\\<open>IF\\<close>):\n\\<close>\n\ndatatype ifex = CIF bool | VIF nat | IF ifex ifex ifex\n\ntext\\<open>\\noindent\nThe evaluation of If-expressions proceeds as for \\<^typ>\\<open>boolex\\<close>:\n\\<close>\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\\<open>\n\\subsubsection{Converting Boolean and If-Expressions}\n\nThe type \\<^typ>\\<open>boolex\\<close> is close to the customary representation of logical\nformulae, whereas \\<^typ>\\<open>ifex\\<close> is designed for efficiency. It is easy to\ntranslate from \\<^typ>\\<open>boolex\\<close> into \\<^typ>\\<open>ifex\\<close>:\n\\<close>\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\\<open>\\noindent\nAt last, we have something we can verify: that \\<^term>\\<open>bool2if\\<close> preserves the\nvalue of its argument:\n\\<close>\n\nlemma \"valif (bool2if b) env = value b env\"\n\ntxt\\<open>\\noindent\nThe proof is canonical:\n\\<close>\n\napply(induct_tac b)\napply(auto)\ndone\n\ntext\\<open>\\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>\\<open>IF\\<close> cannot be another \\<^term>\\<open>IF\\<close> but\nmust be a constant or variable. Such a normal form can be computed by\nrepeatedly replacing a subterm of the form \\<^term>\\<open>IF (IF b x y) z u\\<close> by\n\\<^term>\\<open>IF b (IF x z u) (IF y z u)\\<close>, which has the same value. The following\nprimitive recursive functions perform this task:\n\\<close>\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\\<open>\\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\\<close>\n\ntheorem \"valif (norm b) env = valif b env\"(*<*)oops(*>*)\n\ntext\\<open>\\noindent\nThe proof is canonical, provided we first show the following simplification\nlemma, which also helps to understand what \\<^term>\\<open>normif\\<close> does:\n\\<close>\n\n\n\ntheorem \"valif (norm b) env = valif b env\"\napply(induct_tac b)\nby(auto)\n(*>*)\ntext\\<open>\\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 \\<open>[simp]\\<close> attribute.\n\nBut how can we be sure that \\<^term>\\<open>norm\\<close> really produces a normal form in\nthe above sense? We define a function that tests If-expressions for normality:\n\\<close>\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\\<open>\\noindent\nNow we prove \\<^term>\\<open>normal(norm b)\\<close>. Of course, this requires a lemma about\nnormality of \\<^term>\\<open>normif\\<close>:\n\\<close>\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\\<open>\\medskip\nHow do we come up with the required lemmas? Try to prove the main theorems\nwithout them and study carefully what \\<open>auto\\<close> leaves unproved. This \ncan provide the clue.  The necessity of universal quantification\n(\\<open>\\<forall>t e\\<close>) in the two lemmas is explained in\n\\S\\ref{sec:InductionHeuristics}\n\n\\begin{exercise}\n  We strengthen the definition of a \\<^const>\\<open>normal\\<close> If-expression as follows:\n  the first argument of all \\<^term>\\<open>IF\\<close>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 (\\<open>\\<longrightarrow>\\<close>) rather than\n  equalities (\\<open>=\\<close>).)\n\\end{exercise}\n\\index{boolean expressions example|)}\n\\<close>\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  \"\\<forall>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]: \"\\<forall>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": "seL4", "repo": "isabelle", "sha": "e1ab32a3bb41728cd19541063283e37919978a4c", "save_path": "github-repos/isabelle/seL4-isabelle", "path": "github-repos/isabelle/seL4-isabelle/isabelle-e1ab32a3bb41728cd19541063283e37919978a4c/src/Doc/Tutorial/Ifexpr/Ifexpr.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8757869916479466, "lm_q2_score": 0.8519527963298946, "lm_q1q2_score": 0.7461291765238142}}
{"text": "theory Chapter2Sols\nimports Main Chapter2Defs\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  *)\n(*\nlemma add_assoc[simp]: \"add x (add y z) = add (add x y) z\"\n  apply(induction x)\n   apply(auto)\n  done\n \nlemma suc_add[simp]: \"Suc (add m n) = add m (Suc n)\"\n  apply(induction m)\n   apply(auto)\n  done \n\n\nlemma add_commu[simp]: \"add x y = add y x\"\n  apply(induction x)\n   apply(auto)\n  done\n\n\nfun double:: \"nat \\<Rightarrow> nat\" where\n\"double 0 = 0\" |\n\"double (Suc n) = 2 + double n\"\n\nlemma \"double m = add m m\"\n  apply(induction m)\n   apply(auto)\n  done\n*)\n\n(*  Exercise 2.3  *)\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\ntheorem count_len [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 [] elem = (Cons elem Nil)\" |\n\"snoc (Cons x xs) elem = (Cons x (snoc xs elem))\"\n\nfun reverse:: \"'a list \\<Rightarrow> 'a list\" where\n\"reverse Nil = Nil\" |\n\"reverse (Cons x xs) = snoc (reverse xs) x\"\n\nlemma snoc_rev[simp]: \"reverse (snoc xs a) = a # reverse xs\"\n  apply(induction xs)\n   apply(auto)\n  done\n\nlemma rev_rev[simp]: \"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 n = n + sum_upto (n - 1)\"\n\nlemma \"sum_upto n = (n * (n+1)) div 2\"\n  apply(induction n)\n   apply(auto)\n  done\n\n(*  Exercise 2.6  *)\nfun contents:: \"'a tree \\<Rightarrow> 'a list\" where\n\"contents Tip = []\" |\n\"contents (Node l a r) = (Cons 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   apply(auto)\n  done\n\n(*  Exercise 2.7  *)\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\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 elem [] = [elem]\" |\n\"intersperse elem (x#xs) = [x] @ [elem] @ (intersperse elem xs)\"\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 = 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\nlemma \"nodes(explode n t) = 2^n * (nodes t + 1) - 1\"\n  apply(induction n arbitrary: t)\n   apply(auto)\n  apply(simp add: algebra_simps)\n  done\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 v = v\" |\n\"eval (Const i) v = i\" |\n\"eval (Add e1 e2) v = (eval e1 v) + (eval e2 v)\" |\n\"eval (Mult e1 e2) v = (eval e1 v) * (eval e2 v)\"\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(* not complete *)\nend", "meta": {"author": "mrtkp9993", "repo": "Isabelle-HOL-Examples", "sha": "37a31d2aefce20eb5c49d358c1ea236f5e693458", "save_path": "github-repos/isabelle/mrtkp9993-Isabelle-HOL-Examples", "path": "github-repos/isabelle/mrtkp9993-Isabelle-HOL-Examples/Isabelle-HOL-Examples-37a31d2aefce20eb5c49d358c1ea236f5e693458/Programming and Proving in Isabelle-Hol Exercise Solutions/Chapter2Sols.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951104066293, "lm_q2_score": 0.8840392710530072, "lm_q1q2_score": 0.7460364182490736}}
{"text": "theory ex02\n  imports Main\nbegin\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\nlemma\n  \"fold f [] s = s\"\n  \"fold f (x # xs) s = fold f xs (f x s)\"\n  by auto\n\nfun fold_tree:: \"('b \\<Rightarrow> 'a \\<Rightarrow> 'a) \\<Rightarrow> 'b ltree \\<Rightarrow> 'a \\<Rightarrow> 'a\" where\n  \"fold_tree f (Leaf b) a = f b a\"\n| \"fold_tree f (Node l r) a = fold_tree f r (fold_tree f l a)\"\n\nvalue \"fold_tree\n(\\<lambda>x y. x + y)\n(Node (Leaf (1::nat)) (Node (Leaf 2) (Leaf 4)))\n0\n\"\n\nlemma \"fold_tree f t s = fold f (inorder t) s\"\n  apply(induction t arbitrary: s)\n   apply(auto)\n  done\n\nfun mirror:: \"'a ltree \\<Rightarrow> 'a ltree\" where\n  \"mirror (Leaf a) = Leaf a\"\n| \"mirror (Node l r) = Node (mirror r) (mirror l)\"\n\nlemma \"inorder (mirror t) = rev (inorder t)\"\n  by (induction t) auto\n\nfun shuffles:: \"'a list \\<Rightarrow> 'a list \\<Rightarrow> 'a list list\" where\n  \"shuffles [] ys = [ys]\"\n| \"shuffles xs [] = [xs]\"\n| \"shuffles (x#xs) (y#ys) = \n    map(op # x) (shuffles xs (y#ys)) \n    @ map(op # y) (shuffles (x#xs) ys)\"\n\nlemma \"l\\<in>set (shuffles xs ys) \\<Longrightarrow> length l = length xs + length ys\"\n  apply(induction xs ys arbitrary: l rule: shuffles.induct)\n    apply(auto)\n  done\n\nfun list_sum :: \"nat list \\<Rightarrow> nat\" where\n  \"list_sum [] = 0\"\n| \"list_sum (x#xs) = x + list_sum xs\"\n\ndefinition \"list_sum' xs = fold (op +) xs 0\"\n\nlemma auxi: \"fold (op +) xs a = list_sum xs + a\"\n  apply(induction xs arbitrary: a)\n   apply(auto)\n  done\n\nlemma \"list_sum xs = list_sum' xs\"\n  unfolding list_sum'_def\n  using auxi[where a=0]\n  apply auto\n  done\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/02/ex02.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392756357327, "lm_q2_score": 0.8438950966654774, "lm_q1q2_score": 0.7460364099686952}}
{"text": "(*  File:       Evaluation_Function.thy\n    Copyright   2021  Karlsruhe Institute of Technology (KIT)\n*)\n\\<^marker>\\<open>creator \"Stephan Bohr, Karlsruhe Institute of Technology (KIT)\"\\<close>\n\\<^marker>\\<open>contributor \"Michael Kirsten, Karlsruhe Institute of Technology (KIT)\"\\<close>\n\nsection \\<open>Evaluation Function\\<close>\n\ntheory Evaluation_Function\n  imports \"Social_Choice_Types/Profile\"\nbegin\n\ntext \\<open>\n  This is the evaluation function. From a set of currently eligible\n  alternatives, the evaluation function computes a numerical value that is then\n  to be used for further (s)election, e.g., by the elimination module.\n\\<close>\n\nsubsection \\<open>Definition\\<close>\n\ntype_synonym 'a Evaluation_Function = \"'a  \\<Rightarrow> 'a set \\<Rightarrow> 'a Profile \\<Rightarrow> nat\"\n\nsubsection \\<open>Property\\<close>\n\ntext \\<open>\n  An Evaluation function is Condorcet-rating iff the following holds:\n  If a Condorcet Winner w exists, w and only w has the highest value.\n\\<close>\n\ndefinition condorcet_rating :: \"'a Evaluation_Function \\<Rightarrow> bool\" where\n  \"condorcet_rating f \\<equiv>\n    \\<forall> A p w . condorcet_winner A p w \\<longrightarrow>\n      (\\<forall> l \\<in> A . l \\<noteq> w \\<longrightarrow> f l A p < f w A p)\"\n\n\n\nsubsection \\<open>Theorems\\<close>\n\ntext \\<open>\n  If e is Condorcet-rating, the following holds:\n  If a Condorcet Winner w exists, w has the maximum evaluation value.\n\\<close>\n\ntheorem cond_winner_imp_max_eval_val:\n  assumes\n    rating: \"condorcet_rating e\" and\n    f_prof: \"finite_profile A p\" and\n    winner: \"condorcet_winner A p w\"\n  shows \"e w A p = Max {e a A p | a. a \\<in> A}\"\nproof -\n  let ?set = \"{e a A p | a. a \\<in> A}\" and\n      ?eMax = \"Max {e a A p | a. a \\<in> A}\" and\n      ?eW = \"e w A p\"\n  from f_prof\n  have 0: \"finite ?set\"\n    by simp\n  have 1: \"?set \\<noteq> {}\"\n    using condorcet_winner.simps winner\n    by fastforce\n  have 2: \"?eW \\<in> ?set\"\n    using CollectI condorcet_winner.simps winner\n    by (metis (mono_tags, lifting))\n  have 3: \"\\<forall> e \\<in> ?set . e \\<le> ?eW\"\n  proof (safe)\n    fix a :: \"'a\"\n    assume aInA: \"a \\<in> A\"\n    have \"\\<forall>n na. (n::nat) \\<noteq> na \\<or> n \\<le> na\"\n      by simp\n    with aInA show \"e a A p \\<le> e w A p\"\n      using less_imp_le rating winner\n      unfolding condorcet_rating_def\n      by (metis (no_types))\n  qed\n  from 2 3 have 4:\n    \"?eW \\<in> ?set \\<and> (\\<forall>a \\<in> ?set. a \\<le> ?eW)\"\n    by blast\n  from 0 1 4 Max_eq_iff\n  show ?thesis\n    by (metis (no_types, lifting))\nqed\n\ntext \\<open>\n  If e is Condorcet-rating, the following holds:\n  If a Condorcet Winner w exists, a non-Condorcet\n  winner has a value lower than the maximum\n  evaluation value.\n\\<close>\n\ntheorem non_cond_winner_not_max_eval:\n  assumes\n    rating: \"condorcet_rating e\" and\n    f_prof: \"finite_profile A p\" and\n    winner: \"condorcet_winner A p w\" and\n    linA: \"l \\<in> A\" and\n    loser: \"w \\<noteq> l\"\n  shows \"e l A p < Max {e a A p | a. a \\<in> A}\"\nproof -\n  have \"e l A p < e w A p\"\n    using linA loser rating winner\n    unfolding condorcet_rating_def\n    by metis\n  also have \"e w A p = Max {e a A p |a. a \\<in> A}\"\n    using cond_winner_imp_max_eval_val f_prof rating winner\n    by fastforce\n  finally show ?thesis\n    by simp\nqed\n\nend\n", "meta": {"author": "guillerplazas", "repo": "BachelorThesisRodriguez", "sha": "master", "save_path": "github-repos/isabelle/guillerplazas-BachelorThesisRodriguez", "path": "github-repos/isabelle/guillerplazas-BachelorThesisRodriguez/BachelorThesisRodriguez-main/theories/Compositional_Structures/Basic_Modules/Component_Types/Evaluation_Function.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070133672954, "lm_q2_score": 0.8198933381139645, "lm_q1q2_score": 0.7460266985630195}}
{"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\nheader \"AVL Trees\"\n\ntheory AVL\nimports Main\nbegin\n\ntext {*\n  This is a monolithic formalization of AVL trees.\n*}\n\nsubsection {* AVL tree type definition *}\n\ndatatype (set_of: 'a) tree = ET |  MKT 'a \"'a tree\" \"'a tree\" nat\n\nsubsection {* Invariants and auxiliary functions *}\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 {* AVL interface and implementation *}\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 {* Correctness proof *}\n\nsubsubsection {* Insertion maintains AVL balance *}\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{* Insertion maintains the AVL property: *}\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 `x\\<noteq>n` 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 `x < n` show ?thesis by (auto simp del: mkt_bal_l.simps simp: height_mkt_bal_l2)\n      next\n        case True \n        then have \"height (mkt_bal_l n (AVL.insert x l) r) = height r + 2 \\<or> \n              height (mkt_bal_l n (AVL.insert x l) r) = height r + 3\" \n          using MKT 2 by (intro height_mkt_bal_l) simp_all\n        then show ?thesis \n        proof (rule disjE)\n          case goal1 with 2 `x < n` show ?thesis by (auto simp del: mkt_bal_l.simps)\n        next\n          case goal2 with True 1 MKT(2) `x < n` 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 `\\<not>x < n` show ?thesis by (auto simp del: mkt_bal_r.simps simp: height_mkt_bal_r2)\n      next\n        case True \n        then have \"height (mkt_bal_r n l (AVL.insert x r)) = height l + 2 \\<or> \n              height (mkt_bal_r n l (AVL.insert x r)) = height l + 3\" \n          using MKT 2 by (intro height_mkt_bal_r) simp_all\n        then show ?thesis \n        proof (rule disjE)\n          case goal1 with 2 `\\<not>x < n` show ?thesis by (auto simp del: mkt_bal_r.simps)\n        next\n          case goal2 with True 1 MKT(4) `\\<not>x < n` 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 {* Deletion maintains AVL balance *}\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 `avl x` 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 `avl t` and MKT_MKT have \"avl ?r\" by simp\n  from `avl t` 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 `avl t` 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 `avl ?l'` `avl ?r` 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 `avl t` and MKT_MKT have \"avl ?r\" by simp\n  from `avl t` 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 `avl ?l` by (intro avl_delete_max) auto\n  have t_height: \"height t = 1 + max (height ?l) (height ?r)\" using `avl t` MKT_MKT by simp\n  have \"height t = height ?t' \\<or> height t = height ?t' + 1\" using  `avl t` 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 `avl ?l'` `avl ?r` False])+ arith\n  next\n    case True\n    show ?thesis\n    proof(cases rule: disjE[OF height_mkt_bal_r[OF True `avl ?l'` `avl ?r`, 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{* Deletion maintains the AVL property: *}\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 `x\\<noteq>n` 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 `x < n` show ?thesis by auto\n      next\n        case True \n        then have \"height (mkt_bal_r n (delete x l) r) = height (delete x l) + 2 \\<or>\n              height (mkt_bal_r n (delete x l) r) = height (delete x l) + 3\" \n              using MKT 2 by (intro height_mkt_bal_r) auto\n        then show ?thesis \n        proof(rule disjE)\n          case goal1 with `x < n` MKT 2 show ?thesis by auto\n        next\n          case goal2 with `x < n` 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 `\\<not>x < n` `x \\<noteq> n` show ?thesis by auto\n      next\n        case True \n        then have \"height (mkt_bal_l n l (delete x r)) = height (delete x r) + 2 \\<or>\n              height (mkt_bal_l n l (delete x r)) = height (delete x r) + 3\" \n              using MKT 2 by (intro height_mkt_bal_l) auto\n        then show ?thesis \n        proof(rule disjE)\n          case goal1 with `\\<not>x < n` `x \\<noteq> n` MKT 2 show ?thesis by auto\n        next\n          case goal2 with `\\<not>x < n` `x \\<noteq> n` 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\nsubsubsection {* Correctness of insertion *}\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{* Correctness of @{const insert}: *}\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 {* Correctness of deletion *}\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 assms 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 assms 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{* Correctness of @{const delete}: *}\n\n\n\nsubsubsection {* Correctness of lookup *}\n\ntheorem is_in_correct: \"is_ord t \\<Longrightarrow> is_in k t = (k : set_of t)\"\nby (induct t) auto\n\nsubsubsection {* Insertion maintains order *}\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{* If the order is linear, @{const insert} maintains the order: *}\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 {* Deletion maintains order *}\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 assms have \"\\<forall>h. is_ord(MKT n l ?r' h)\" by (auto simp: set_of_delete_max)\n  moreover from MKT assms 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{* If the order is linear, @{const delete} maintains the order: *}\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)\"] `x\\<noteq>n` show ?thesis by (simp add: avl_delete)\n    qed\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/AVL-Trees/AVL.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070035949656, "lm_q2_score": 0.8198933381139645, "lm_q1q2_score": 0.7460266905507514}}
{"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 G=(V,E) consits of a set of vertices V, also called nodes, \n       and a set of edges 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://afp.sourceforge.net/entries/Dijkstra_Shortest_Path.shtml\n*)\n\nsection {* 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 valid graph, edges only go from nodes to nodes. *}\n  locale valid_graph = \n    fixes G :: \"'v graph\"\n    -- \"Edges only refernce to existing nodes\"\n    assumes E_valid: \"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    lemma E_validD: assumes \"(v,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    lemma E_validD2: \"\\<forall>e \\<in> E. fst e \\<in> V \\<and> snd e \\<in> V\"\n    by (auto simp add: E_validD)\n  end\n\nsubsection {* Basic operations on Graphs *}\n\n \n  text {* The empty graph. *}\n  definition empty 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\n  text {* Deletes an edge from a graph. *}\n  definition delete_edge where \"delete_edge v v' G \\<equiv> \\<lparr>nodes = nodes G, \n    edges = {(e1,e2). (e1, e2) \\<in> edges G \\<and> (e1,e2) \\<noteq> (v,v')} \\<rparr>\"\n  \n  definition delete_edges::\"'v graph \\<Rightarrow> ('v \\<times> 'v) set \\<Rightarrow> 'v graph\" where \n    \"delete_edges G es = \\<lparr>nodes = nodes G, \n    edges = {(e1,e2). (e1, e2) \\<in> edges G \\<and> (e1,e2) \\<notin> es} \\<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\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 v including 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 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: \"valid_graph G \\<Longrightarrow> finite (succ_tran G v)\"\n  proof -\n    assume \"valid_graph G\"\n    from valid_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 v, then v has no successors *}\n  lemma succ_tran_empty: \"\\<lbrakk> valid_graph G; v \\<notin> (fst ` edges G) \\<rbrakk> \\<Longrightarrow> succ_tran G v = {}\"\n  by (metis (lifting) Collect_empty_eq Domain.DomainI converse_tranclE fst_eq_Domain succ_tran_def)\n\n  text{* succ_tran is subset of nodes *}\n  lemma succ_tran_subseteq_nodes: \"\\<lbrakk> valid_graph G \\<rbrakk> \\<Longrightarrow> succ_tran G v \\<subseteq> nodes G\"\n    apply(simp add: succ_tran_def)\n    by (metis (lifting) mem_Collect_eq subsetI trancl.cases valid_graph.E_validD(2))\n\n\n  text {* The number of reachable nodes from 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{*card returns 0 for infinite sets. Here, for a valid graph, if num_reachable is zero,\n        there are actually no nodes reachable.*}\n  lemma num_reachable_zero: \"\\<lbrakk>valid_graph G; num_reachable G v = 0\\<rbrakk> \\<Longrightarrow> succ_tran G v = {}\"\n  apply(unfold num_reachable_def)\n  apply(case_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  by(unfold num_reachable_def, simp)\n  lemma num_reachable_zero_iff: \"\\<lbrakk>valid_graph G\\<rbrakk> \\<Longrightarrow> (num_reachable G v = 0) <-> (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 {*Lemmata*}\n\n  lemma graph_eq_intro: \"(nodes (G::'a graph) = nodes G') \\<Longrightarrow> (edges G = edges G') \\<Longrightarrow> G = G'\"\n  by simp\n\n  -- \"finite\"\n  lemma valid_graph_finite_filterE: \"valid_graph G \\<Longrightarrow> finite {(e1, e2). (e1, e2) \\<in> edges G \\<and> P e1 e2}\"\n  by(simp add: valid_graph.finiteE split_def)\n  lemma valid_graph_finite_filterV: \"valid_graph G \\<Longrightarrow> finite {n. n \\<in> nodes G \\<and> P n}\"\n  by(simp add: valid_graph.finiteV)\n\n  -- \"empty\"\n  lemma empty_valid[simp]: \"valid_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_valid[simp]:\n    \"valid_graph g \\<Longrightarrow> valid_graph (add_node v g)\"\n      unfolding add_node_def\n      unfolding valid_graph_def\n      by (auto)\n\n  lemma delete_node_valid[simp]:\n  \"valid_graph G \\<Longrightarrow> valid_graph (delete_node v G)\"\n  by(auto simp add: delete_node_def valid_graph_def valid_graph_finite_filterE)\n\n  -- \"add edgde\"\n  lemma add_edge_valid[simp]: \"valid_graph G \\<Longrightarrow> valid_graph (add_edge v v' G)\"\n  by(auto simp add: add_edge_def add_node_def valid_graph_def)\n\n  -- \"delete edge\"\n  lemma delete_edge_valid[simp]: \"valid_graph G \\<Longrightarrow> valid_graph (delete_edge v v' G)\"\n  by(auto simp add: delete_edge_def add_node_def valid_graph_def split_def)\n \n  -- \"delte edges\"\n  lemma delete_edges_list_valid[simp]: \"valid_graph G \\<Longrightarrow> valid_graph (delete_edges_list G E)\"\n    by(induction E arbitrary: G, simp, force)\n  lemma delete_edges_valid[simp]: \"valid_graph G \\<Longrightarrow> valid_graph (delete_edges G E)\"\n  by(auto simp add: delete_edges_def add_node_def valid_graph_def split_def)\n  lemma delete_edges_list_set: \"delete_edges_list G E = delete_edges G (set E)\"\n    apply(induction E arbitrary: G)\n     apply(simp_all add: delete_edges_def)\n    apply(clarify)\n    by(simp add: delete_edge_def)\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: \"valid_graph (G::'a graph) \\<Longrightarrow> (a,b) \\<in> edges G \\<Longrightarrow> \n  add_edge a b (delete_edge a b G) = G\"\n   apply(simp add: delete_edge_def add_edge_def valid_graph_def)\n   apply(clarify)\n   apply(rule graph_eq_intro)\n    by (auto)\n\n  lemma add_delete_edges: \"valid_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  apply(simp add: delete_edges_simp2 add_edge_def valid_graph_def)\n  apply(clarify)\n  apply(auto)\n  done\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_valid: \"valid_graph G \\<Longrightarrow> valid_graph (fully_connected G)\"\n    by(simp add: fully_connected_def valid_graph_def)\n\n --\"succ_tran\"\n lemma succ_tran_mono: \n  \"valid_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 valid_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  \"valid_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  \"valid_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_valid: \n    \"valid_graph \\<lparr>nodes=N, edges=E\\<rparr> \\<Longrightarrow> valid_graph \\<lparr>nodes=N, edges=backflows E\\<rparr>\"\n    using [[simproc add: finite_Collect]] by(auto simp add: valid_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\n\n\n\n\nlemmas graph_ops=add_node_def delete_node_def add_edge_def delete_edge_def delete_edges_simp2\n\n\n  --\"valid_graph\"\n  lemma valid_graph_remove_edges: \"valid_graph \\<lparr> nodes = V, edges = E \\<rparr> \\<Longrightarrow> valid_graph \\<lparr> nodes = V, edges=E - X\\<rparr>\"\n    by (metis delete_edges_simp2 delete_edges_valid select_convs(1) select_convs(2))\n\n  lemma valid_graph_remove_edges_union: \n    \"valid_graph \\<lparr> nodes = V, edges = E \\<union> E' \\<rparr> \\<Longrightarrow> valid_graph \\<lparr> nodes = V, edges=E\\<rparr>\"\n    by(auto simp add: valid_graph_def)\n\n  lemma valid_graph_union_edges: \"\\<lbrakk> valid_graph \\<lparr> nodes = V, edges = E \\<rparr>; valid_graph \\<lparr> nodes = V, edges=E'\\<rparr> \\<rbrakk> \\<Longrightarrow>\n     valid_graph \\<lparr> nodes = V, edges=E \\<union> E'\\<rparr>\"\n    by(auto simp add: valid_graph_def)\n\n  lemma valid_graph_add_subset_edges: \"\\<lbrakk> valid_graph \\<lparr> nodes = V, edges = E \\<rparr>; E' \\<subseteq> E \\<rbrakk> \\<Longrightarrow>\n     valid_graph \\<lparr> nodes = V, edges= E \\<union> E'\\<rparr>\"\n    by(auto simp add: valid_graph_def) (metis rev_finite_subset)\n\n\n\n\n\n(*Inspired by \nBenedikt Nordhoff and Peter Lammich\nDijkstra's Shortest Path Algorithm\nhttp://afp.sourceforge.net/entries/Dijkstra_Shortest_Path.shtml*)\n(*more a literal copy of http://afp.sourceforge.net/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 valid_graph) succ_subset: \"succ G v \\<subseteq> V\"\n    unfolding succ_def using E_valid\n    by (force)\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/Network_Security_Policy_Verification/Lib/FiniteGraph.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9073122238669026, "lm_q2_score": 0.822189134878876, "lm_q1q2_score": 0.7459822524061577}}
{"text": "(* Author: Asta Halkj\u00e6r From, DTU Compute *)\n\ntheory System_A imports \"HOL-Library.Countable\" begin\n\nsection \\<open>Syntax\\<close>\n\ndatatype form\n  = Falsity (\\<open>\\<^bold>\\<bottom>\\<close>)\n  | Pro nat\n  | Imp form form (infixr \\<open>\\<^bold>\\<longrightarrow>\\<close> 25)\n  | Dis form form (infixr \\<open>\\<^bold>\\<or>\\<close> 30)\n  | Con form form (infixr \\<open>\\<^bold>\\<and>\\<close> 35)\n\nabbreviation Truth (\\<open>\\<^bold>\\<top>\\<close>) where \\<open>\\<^bold>\\<top> \\<equiv> \\<^bold>\\<bottom> \\<^bold>\\<longrightarrow> \\<^bold>\\<bottom>\\<close>\n\nabbreviation Neg (\\<open>\\<^bold>\\<not> _\\<close> [40] 40) where \\<open>\\<^bold>\\<not> p \\<equiv> p \\<^bold>\\<longrightarrow> \\<^bold>\\<bottom>\\<close>\n\nsection \\<open>Semantics\\<close>\n\nprimrec semantics :: \\<open>(nat \\<Rightarrow> bool) \\<Rightarrow> form \\<Rightarrow> bool\\<close> (\\<open>_ \\<Turnstile> _\\<close> [50, 50] 50) where\n  \\<open>(I \\<Turnstile> \\<^bold>\\<bottom>) = False\\<close>\n| \\<open>(I \\<Turnstile> Pro n) = I n\\<close>\n| \\<open>(I \\<Turnstile> (p \\<^bold>\\<longrightarrow> q)) = ((I \\<Turnstile> p) \\<longrightarrow> (I \\<Turnstile> q))\\<close>\n| \\<open>(I \\<Turnstile> (p \\<^bold>\\<or> q)) = ((I \\<Turnstile> p) \\<or> (I \\<Turnstile> q))\\<close>\n| \\<open>(I \\<Turnstile> (p \\<^bold>\\<and> q)) = ((I \\<Turnstile> p) \\<and> (I \\<Turnstile> q))\\<close>\n\nsection \\<open>Axiomatics\\<close>\n\ninductive Axiomatics :: \\<open>form \\<Rightarrow> bool\\<close> (\\<open>\\<turnstile> _\\<close> [50] 50) where\n  MP: \\<open>\\<turnstile> p \\<Longrightarrow> \\<turnstile> (p \\<^bold>\\<longrightarrow> q) \\<Longrightarrow> \\<turnstile> q\\<close>\n| Imp1: \\<open>\\<turnstile> (p \\<^bold>\\<longrightarrow> q \\<^bold>\\<longrightarrow> p)\\<close>\n| Imp2: \\<open>\\<turnstile> ((p \\<^bold>\\<longrightarrow> q \\<^bold>\\<longrightarrow> r) \\<^bold>\\<longrightarrow> (p \\<^bold>\\<longrightarrow> q) \\<^bold>\\<longrightarrow> p \\<^bold>\\<longrightarrow> r)\\<close>\n| DisE: \\<open>\\<turnstile> ((p \\<^bold>\\<longrightarrow> r) \\<^bold>\\<longrightarrow> (q \\<^bold>\\<longrightarrow> r) \\<^bold>\\<longrightarrow> p \\<^bold>\\<or> q \\<^bold>\\<longrightarrow> r)\\<close>\n| DisI1: \\<open>\\<turnstile> (p \\<^bold>\\<longrightarrow> p \\<^bold>\\<or> q)\\<close>\n| DisI2: \\<open>\\<turnstile> (q \\<^bold>\\<longrightarrow> p \\<^bold>\\<or> q)\\<close>\n| ConE1: \\<open>\\<turnstile> (p \\<^bold>\\<and> q \\<^bold>\\<longrightarrow> p)\\<close>\n| ConE2: \\<open>\\<turnstile> (p \\<^bold>\\<and> q \\<^bold>\\<longrightarrow> q)\\<close>\n| ConI: \\<open>\\<turnstile> (p \\<^bold>\\<longrightarrow> q \\<^bold>\\<longrightarrow> p \\<^bold>\\<and> q)\\<close>\n| Neg: \\<open>\\<turnstile> (((p \\<^bold>\\<longrightarrow> \\<^bold>\\<bottom>) \\<^bold>\\<longrightarrow> \\<^bold>\\<bottom>) \\<^bold>\\<longrightarrow> p)\\<close>\n\nsection \\<open>Soundness\\<close>\n\ntheorem soundness: \\<open>\\<turnstile> p \\<Longrightarrow> I \\<Turnstile> p\\<close>\n  by (induct rule: Axiomatics.induct) simp_all\n\nsection \\<open>Derived Rules\\<close>\n\nlemma Imp3: \\<open>\\<turnstile> (p \\<^bold>\\<longrightarrow> p)\\<close>\n  by (metis Imp1 Imp2 MP)\n\nlemma Imp4: \\<open>\\<turnstile> ((p \\<^bold>\\<longrightarrow> q) \\<^bold>\\<longrightarrow> (q \\<^bold>\\<longrightarrow> r) \\<^bold>\\<longrightarrow> p \\<^bold>\\<longrightarrow> r)\\<close>\n  by (metis Imp1 Imp2 MP)\n\nlemma Imp2': \\<open>\\<turnstile> ((p \\<^bold>\\<longrightarrow> q) \\<^bold>\\<longrightarrow> (p \\<^bold>\\<longrightarrow> q \\<^bold>\\<longrightarrow> r) \\<^bold>\\<longrightarrow> p \\<^bold>\\<longrightarrow> r)\\<close>\n  by (metis Imp1 Imp2 Imp3 Imp4 MP)\n\nlemma Imp2'': \\<open>\\<turnstile> ((p \\<^bold>\\<longrightarrow> q \\<^bold>\\<longrightarrow> r) \\<^bold>\\<longrightarrow> q \\<^bold>\\<longrightarrow> p \\<^bold>\\<longrightarrow> r)\\<close>\n  by (metis Imp1 Imp2' MP)\n\nlemma FalsityE: \\<open>\\<turnstile> (p \\<^bold>\\<longrightarrow> \\<^bold>\\<not> p \\<^bold>\\<longrightarrow> q)\\<close>\nproof -\n  obtain r where \\<open>\\<turnstile> ((r \\<^bold>\\<longrightarrow> p) \\<^bold>\\<longrightarrow> \\<^bold>\\<not> p \\<^bold>\\<longrightarrow> q)\\<close>\n    by (metis Imp1 Imp2 MP Neg)\n  then show ?thesis\n    by (metis Imp1 Imp2 MP)\nqed\n\nlemma ImpE1: \\<open>\\<turnstile> (\\<^bold>\\<not> (p \\<^bold>\\<longrightarrow> q) \\<^bold>\\<longrightarrow> p)\\<close>\n  by (metis FalsityE Imp4 MP Neg)\n\nlemma ImpE2: \\<open>\\<turnstile> (\\<^bold>\\<not> (p \\<^bold>\\<longrightarrow> q) \\<^bold>\\<longrightarrow> \\<^bold>\\<not> q)\\<close>\n  by (metis Imp1 Imp4 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 \\<^bold>\\<longrightarrow> imply ps q)\\<close>\n\nlemma imply_head: \\<open>\\<turnstile> imply (p # ps) p\\<close>\n  by (induct ps) (simp add: Imp3, metis Imp1 Imp2 MP imply.simps(2))\n\nlemma imply_Cons: \\<open>\\<turnstile> imply ps q \\<Longrightarrow> \\<turnstile> imply (p # ps) q\\<close>\n  by (metis Imp1 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 \\<^bold>\\<longrightarrow> imply ps (p \\<^bold>\\<longrightarrow> q) \\<^bold>\\<longrightarrow> imply ps q)\\<close>\nproof (induct ps)\n  case Nil\n  then show ?case\n    by (metis Imp1 Imp2 MP imply.simps(1))\nnext\n  case (Cons r ps)\n  then show ?case\n  proof -\n    have \\<open>\\<turnstile> ((r \\<^bold>\\<longrightarrow> imply ps p) \\<^bold>\\<longrightarrow> r \\<^bold>\\<longrightarrow> imply ps (p \\<^bold>\\<longrightarrow> q) \\<^bold>\\<longrightarrow> imply ps q)\\<close>\n      by (meson Cons.hyps Imp1 Imp2 MP)\n    then have \\<open>\\<turnstile> ((r \\<^bold>\\<longrightarrow> imply ps p) \\<^bold>\\<longrightarrow> (r \\<^bold>\\<longrightarrow> imply ps (p \\<^bold>\\<longrightarrow> q)) \\<^bold>\\<longrightarrow> r \\<^bold>\\<longrightarrow> imply ps q)\\<close>\n      by (meson Imp2' Imp2'' Imp4 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 \\<^bold>\\<longrightarrow> 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 \\<^bold>\\<longrightarrow> 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 \\<^bold>\\<longrightarrow> q)\\<close>\n    using deduct by blast\n  then have \\<open>\\<turnstile> imply ps' (p \\<^bold>\\<longrightarrow> 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 Imp1 Imp2 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 \\<^bold>\\<longrightarrow> q) \\<Longrightarrow> \\<turnstile> (imply ps p \\<^bold>\\<longrightarrow> imply ps q)\\<close>\nproof (induct ps)\n  case (Cons r ps)\n  then show ?case\n    by (metis Axiomatics.simps imply.simps(2))\nqed simp\n\nlemma Neg': \\<open>\\<turnstile> (imply ps (\\<^bold>\\<not> \\<^bold>\\<not> p) \\<^bold>\\<longrightarrow> imply ps p)\\<close>\n  using Neg imply_lift by simp\n\nlemma Boole: \\<open>\\<turnstile> imply ((\\<^bold>\\<not> p) # ps) \\<^bold>\\<bottom> \\<Longrightarrow> \\<turnstile> imply ps p\\<close>\n  using deduct MP Neg' by blast\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\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' \\<^bold>\\<bottom>\\<close>\n\nlemma UN_finite_bound:\n  assumes \\<open>finite A\\<close> \\<open>A \\<subseteq> (\\<Union>n. f n)\\<close>\n  shows \\<open>\\<exists>m :: nat. A \\<subseteq> (\\<Union>n \\<le> m. f n)\\<close>\n  using assms\nproof (induct rule: finite_induct)\n  case (insert x A)\n  then obtain m where \\<open>A \\<subseteq> (\\<Union>n \\<le> m. f n)\\<close>\n    by fast\n  then have \\<open>A \\<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> A \\<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' \\<^bold>\\<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' \\<^bold>\\<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>\\<^bold>\\<bottom> \\<notin> H\\<close> and\n    Pro: \\<open>Pro n \\<in> H \\<Longrightarrow> (\\<^bold>\\<not> Pro n) \\<notin> H\\<close> and\n    ImpP: \\<open>(p \\<^bold>\\<longrightarrow> q) \\<in> H \\<Longrightarrow> (\\<^bold>\\<not> p) \\<in> H \\<or> q \\<in> H\\<close> and\n    ImpN: \\<open>(\\<^bold>\\<not> (p \\<^bold>\\<longrightarrow> q)) \\<in> H \\<Longrightarrow> p \\<in> H \\<and> (\\<^bold>\\<not> q) \\<in> H\\<close> and\n    DisP: \\<open>(p \\<^bold>\\<or> q) \\<in> H \\<Longrightarrow> p \\<in> H \\<or> q \\<in> H\\<close> and\n    DisN: \\<open>(\\<^bold>\\<not> (p \\<^bold>\\<or> q)) \\<in> H \\<Longrightarrow> (\\<^bold>\\<not> p) \\<in> H \\<and> (\\<^bold>\\<not> q) \\<in> H\\<close> and\n    ConP: \\<open>(p \\<^bold>\\<and> q) \\<in> H \\<Longrightarrow> p \\<in> H \\<and> q \\<in> H\\<close> and\n    ConN: \\<open>(\\<^bold>\\<not> (p \\<^bold>\\<and> q)) \\<in> H \\<Longrightarrow> (\\<^bold>\\<not> p) \\<in> H \\<or> (\\<^bold>\\<not> q) \\<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> ((\\<^bold>\\<not> 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') \\<^bold>\\<bottom> \\<and> set S' \\<subseteq> S\\<close>\nproof -\n  obtain S' where S': \\<open>\\<turnstile> imply S' \\<^bold>\\<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'') \\<^bold>\\<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>\\<^bold>\\<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, \\<^bold>\\<not> Pro n] \\<^bold>\\<bottom>\\<close>\n    by (simp add: FalsityE)\n  ultimately show \\<open>(\\<^bold>\\<not> 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 \\<^bold>\\<longrightarrow> q) \\<in> S\\<close>\n  show \\<open>(\\<^bold>\\<not> 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') \\<^bold>\\<bottom>\\<close> \\<open>set Sq' \\<subseteq> S\\<close>\n      using assms inconsistent_head by blast\n\n    assume \\<open>(\\<^bold>\\<not> p) \\<notin> S\\<close>\n    then obtain Sp' where Sp': \\<open>\\<turnstile> imply ((\\<^bold>\\<not> p) # Sp') \\<^bold>\\<bottom>\\<close> \\<open>set Sp' \\<subseteq> S\\<close>\n      using assms inconsistent_head by blast\n\n    obtain S' where S': \\<open>set S' = set Sp' \\<union> set Sq'\\<close>\n      by (meson set_append)\n    then have \\<open>\\<turnstile> imply ((\\<^bold>\\<not> p) # S') \\<^bold>\\<bottom>\\<close> \\<open>\\<turnstile> imply (q # S') \\<^bold>\\<bottom>\\<close>\n    proof -\n      have \\<open>set Sp' \\<subseteq> set S'\\<close>\n        using S' by blast\n      then show \\<open>\\<turnstile> imply ((\\<^bold>\\<not> p) # S') \\<^bold>\\<bottom>\\<close>\n        by (metis Sp'(1) deduct imply_weaken)\n      have \\<open>set Sq' \\<subseteq> set S'\\<close>\n        using S' by blast\n      then show \\<open>\\<turnstile> imply (q # S') \\<^bold>\\<bottom>\\<close>\n        using ** by (metis Sq'(1) deduct imply_weaken)\n    qed\n    then have \\<open>\\<turnstile> imply ((p \\<^bold>\\<longrightarrow> q) # S') \\<^bold>\\<bottom>\\<close>\n      using Boole imply_Cons imply_head imply_mp' cut' by metis\n    moreover have \\<open>set ((p \\<^bold>\\<longrightarrow> q) # S') \\<subseteq> S\\<close> if \\<open>q \\<notin> S\\<close>\n      using that *(1) 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>(\\<^bold>\\<not> (p \\<^bold>\\<longrightarrow> q)) \\<in> S\\<close>\n  show \\<open>p \\<in> S \\<and> (\\<^bold>\\<not> q) \\<in> S\\<close>\n  proof (rule conjI; rule ccontr)\n    assume \\<open>p \\<notin> S\\<close>\n    then obtain S' where S': \\<open>\\<turnstile> imply (p # S') \\<^bold>\\<bottom>\\<close> \\<open>set S' \\<subseteq> S\\<close>\n      using assms inconsistent_head by blast\n    moreover have \\<open>\\<turnstile> imply ((\\<^bold>\\<not> (p \\<^bold>\\<longrightarrow> q)) # S') p\\<close>\n      using add_imply ImpE1 deduct by blast\n    ultimately have \\<open>\\<turnstile> imply ((\\<^bold>\\<not> (p \\<^bold>\\<longrightarrow> q)) # S') \\<^bold>\\<bottom>\\<close>\n      using cut' by blast\n    moreover have \\<open>set ((\\<^bold>\\<not> (p \\<^bold>\\<longrightarrow> q)) # S') \\<subseteq> S\\<close>\n      using *(1) S'(2) by fastforce\n    ultimately show False\n      using assms unfolding consistent_def by blast\n  next\n    assume \\<open>(\\<^bold>\\<not> q) \\<notin> S\\<close>\n    then obtain S' where S': \\<open>\\<turnstile> imply ((\\<^bold>\\<not> q) # S') \\<^bold>\\<bottom>\\<close> \\<open>set S' \\<subseteq> S\\<close>\n      using assms inconsistent_head by blast\n    moreover have \\<open>\\<turnstile> imply ((\\<^bold>\\<not> (p \\<^bold>\\<longrightarrow> q)) # S') (\\<^bold>\\<not> q)\\<close>\n      using add_imply ImpE2 deduct by blast\n    ultimately have \\<open>\\<turnstile> imply ((\\<^bold>\\<not> (p \\<^bold>\\<longrightarrow> q)) # S') \\<^bold>\\<bottom>\\<close>\n      using cut' by blast\n    moreover have \\<open>set ((\\<^bold>\\<not> (p \\<^bold>\\<longrightarrow> q)) # S') \\<subseteq> S\\<close>\n      using *(1) S'(2) by fastforce\n    ultimately show False\n      using assms unfolding consistent_def by blast\n  qed\nnext\n  fix p q\n  assume *: \\<open>(p \\<^bold>\\<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') \\<^bold>\\<bottom>\\<close> \\<open>set Sq' \\<subseteq> S - {q}\\<close>\n      using assms inconsistent_head by blast\n\n    assume \\<open>p \\<notin> S\\<close>\n    then obtain Sp' where Sp': \\<open>\\<turnstile> imply (p # Sp') \\<^bold>\\<bottom>\\<close> \\<open>set Sp' \\<subseteq> S - {p}\\<close>\n      using assms inconsistent_head by blast\n    obtain S' where S': \\<open>set S' = set Sp' \\<union> set Sq'\\<close>\n      by (meson set_append)\n    then have \\<open>\\<turnstile> imply (p # S') \\<^bold>\\<bottom>\\<close> \\<open>\\<turnstile> imply (q # S') \\<^bold>\\<bottom>\\<close>\n    proof -\n      have \\<open>set Sp' \\<subseteq> set S'\\<close>\n        using S' by blast\n      then show \\<open>\\<turnstile> imply (p # S') \\<^bold>\\<bottom>\\<close>\n        by (metis Sp'(1) deduct imply_weaken)\n      have \\<open>set Sq' \\<subseteq> set S'\\<close>\n        using S' by blast\n      then show \\<open>\\<turnstile> imply (q # S') \\<^bold>\\<bottom>\\<close>\n        by (metis Sq'(1) deduct imply_weaken)\n    qed\n    then have \\<open>\\<turnstile> imply ((p \\<^bold>\\<or> q) # S') \\<^bold>\\<bottom>\\<close>\n      by (metis Axiomatics.simps imply.simps(2))\n    moreover have \\<open>set ((p \\<^bold>\\<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>(\\<^bold>\\<not> (p \\<^bold>\\<or> q)) \\<in> S\\<close>\n  show \\<open>(\\<^bold>\\<not> p) \\<in> S \\<and> (\\<^bold>\\<not> q) \\<in> S\\<close>\n  proof (rule conjI; rule ccontr)\n    assume \\<open>(\\<^bold>\\<not> p) \\<notin> S\\<close>\n    then obtain S' where S': \\<open>\\<turnstile> imply ((\\<^bold>\\<not> p) # S') \\<^bold>\\<bottom>\\<close> \\<open>set S' \\<subseteq> S - {\\<^bold>\\<not> p}\\<close>\n      using assms inconsistent_head by blast\n    moreover have \\<open>\\<turnstile> imply ((\\<^bold>\\<not> (p \\<^bold>\\<or> q)) # S') (\\<^bold>\\<not> p)\\<close>\n      using DisI1 Imp4 add_imply deduct MP by blast\n    ultimately have \\<open>\\<turnstile> imply ((\\<^bold>\\<not> (p \\<^bold>\\<or> q)) # S') \\<^bold>\\<bottom>\\<close>\n      using cut' by blast\n    moreover have \\<open>set ((\\<^bold>\\<not> (p \\<^bold>\\<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>(\\<^bold>\\<not> q) \\<notin> S\\<close>\n    then obtain S' where S': \\<open>\\<turnstile> imply ((\\<^bold>\\<not> q) # S') \\<^bold>\\<bottom>\\<close> \\<open>set S' \\<subseteq> S - {\\<^bold>\\<not> q}\\<close>\n      using assms inconsistent_head by blast\n    moreover have \\<open>\\<turnstile> imply ((\\<^bold>\\<not> (p \\<^bold>\\<or> q)) # S') (\\<^bold>\\<not> q)\\<close>\n      using DisI2 Imp4 add_imply deduct MP by blast\n    ultimately have \\<open>\\<turnstile> imply ((\\<^bold>\\<not> (p \\<^bold>\\<or> q)) # S') \\<^bold>\\<bottom>\\<close>\n      using cut' by blast\n    moreover have \\<open>set ((\\<^bold>\\<not> (p \\<^bold>\\<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 q\n  assume *: \\<open>(p \\<^bold>\\<and> q) \\<in> S\\<close>\n  show \\<open>p \\<in> S \\<and> q \\<in> S\\<close>\n  proof (rule conjI; rule ccontr)\n    assume \\<open>p \\<notin> S\\<close>\n    then obtain S' where S': \\<open>\\<turnstile> imply (p # S') \\<^bold>\\<bottom>\\<close> \\<open>set S' \\<subseteq> S - {p}\\<close>\n      using assms inconsistent_head by blast\n    moreover have \\<open>\\<turnstile> imply ((p \\<^bold>\\<and> q) # S') p\\<close>\n      using ConE1 add_imply deduct by blast\n    ultimately have \\<open>\\<turnstile> imply ((p \\<^bold>\\<and> q) # S') \\<^bold>\\<bottom>\\<close>\n      using cut' by blast\n    moreover have \\<open>set ((p \\<^bold>\\<and> 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  next\n    assume \\<open>q \\<notin> S\\<close>\n    then obtain S' where S': \\<open>\\<turnstile> imply (q # S') \\<^bold>\\<bottom>\\<close> \\<open>set S' \\<subseteq> S - {q}\\<close>\n      using assms inconsistent_head by blast\n    moreover have \\<open>\\<turnstile> imply ((p \\<^bold>\\<and> q) # S') q\\<close>\n      using ConE2 add_imply deduct by blast\n    ultimately have \\<open>\\<turnstile> imply ((p \\<^bold>\\<and> q) # S') \\<^bold>\\<bottom>\\<close>\n      using cut' by blast\n    moreover have \\<open>set ((p \\<^bold>\\<and> q) # S') \\<subseteq> S\\<close>\n      using *(1) S'(2) S'(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>(\\<^bold>\\<not> (p \\<^bold>\\<and> q)) \\<in> S\\<close>\n  show \\<open>(\\<^bold>\\<not> p) \\<in> S \\<or> (\\<^bold>\\<not> q) \\<in> S\\<close>\n  proof (rule disjCI, rule ccontr)\n    assume \\<open>(\\<^bold>\\<not> q) \\<notin> S\\<close>\n    then obtain Sq' where Sq': \\<open>\\<turnstile> imply ((\\<^bold>\\<not> q) # Sq') \\<^bold>\\<bottom>\\<close> \\<open>set Sq' \\<subseteq> S - {\\<^bold>\\<not> q}\\<close>\n      using assms inconsistent_head by blast\n\n    assume \\<open>(\\<^bold>\\<not> p) \\<notin> S\\<close>\n    then obtain Sp' where Sp': \\<open>\\<turnstile> imply ((\\<^bold>\\<not> p) # Sp') \\<^bold>\\<bottom>\\<close> \\<open>set Sp' \\<subseteq> S - {\\<^bold>\\<not> p}\\<close>\n      using assms inconsistent_head by blast\n\n    obtain S' where S': \\<open>set S' = set Sp' \\<union> set Sq'\\<close>\n      by (meson set_append)\n    then have \\<open>\\<turnstile> imply ((\\<^bold>\\<not> p) # S') \\<^bold>\\<bottom>\\<close> \\<open>\\<turnstile> imply ((\\<^bold>\\<not> q) # S') \\<^bold>\\<bottom>\\<close>\n    proof -\n      have \\<open>set Sp' \\<subseteq> set S'\\<close>\n        using S' by blast\n      then show \\<open>\\<turnstile> imply ((\\<^bold>\\<not> p) # S') \\<^bold>\\<bottom>\\<close>\n        by (metis Sp'(1) deduct imply_weaken)\n      have \\<open>set Sq' \\<subseteq> set S'\\<close>\n        using S' by blast\n      then show \\<open>\\<turnstile> imply ((\\<^bold>\\<not> q) # S') \\<^bold>\\<bottom>\\<close>\n        by (metis Sq'(1) deduct imply_weaken)\n    qed\n    then have \\<open>\\<turnstile> imply ((\\<^bold>\\<not> (p \\<^bold>\\<and> q)) # S') \\<^bold>\\<bottom>\\<close>\n      by (metis ConI Boole add_imply imply_Cons imply_head imply_mp')\n    moreover have \\<open>set ((\\<^bold>\\<not> (p \\<^bold>\\<and> q)) # S') \\<subseteq> S\\<close>\n      using *(1) S' Sp'(2) Sq'(2) by auto\n    ultimately show False\n      using assms unfolding consistent_def by blast\n  qed\nqed\n\nsection \\<open>Countable Formulas\\<close>\n\ninstance form :: countable by countable_datatype\n\nsection \\<open>Completeness\\<close>\n\nlemma imply_completeness:\n  assumes valid: \\<open>\\<forall>I. 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 ((\\<^bold>\\<not> p) # ps) \\<^bold>\\<bottom>\\<close>\n    using Boole by blast\n\n  let ?S = \\<open>set ((\\<^bold>\\<not> 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> (\\<^bold>\\<not> 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> (\\<^bold>\\<not> 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\nabbreviation \\<open>valid p \\<equiv> \\<forall>I. I \\<Turnstile> p\\<close>\n\ntheorem main: \\<open>valid p \\<longleftrightarrow> \\<turnstile> p\\<close>\n  using completeness soundness by fast\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_A.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122163480667, "lm_q2_score": 0.8221891327004133, "lm_q1q2_score": 0.7459822442477066}}
{"text": "(*  Title:      HOL/Induct/ABexp.thy\n    Author:     Stefan Berghofer, TU Muenchen\n*)\n\nsection \\<open>Arithmetic and boolean expressions\\<close>\n\ntheory ABexp\nimports MainRLT\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 \\<open>\\medskip Evaluation of arithmetic and boolean expressions\\<close>\n\nprimrec evala :: \"('a \\<Rightarrow> nat) \\<Rightarrow> 'a aexp \\<Rightarrow> nat\"\n  and evalb :: \"('a \\<Rightarrow> nat) \\<Rightarrow> 'a bexp \\<Rightarrow> 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 \\<open>\\medskip Substitution on arithmetic and boolean expressions\\<close>\n\nprimrec substa :: \"('a \\<Rightarrow> 'b aexp) \\<Rightarrow> 'a aexp \\<Rightarrow> 'b aexp\"\n  and substb :: \"('a \\<Rightarrow> 'b aexp) \\<Rightarrow> 'a bexp \\<Rightarrow> '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    \\<comment> \\<open>one variable\\<close>\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": "dtraytel", "repo": "HOLRLT", "sha": "e9029da59bb3af0c835604a65308498f9696a364", "save_path": "github-repos/isabelle/dtraytel-HOLRLT", "path": "github-repos/isabelle/dtraytel-HOLRLT/HOLRLT-e9029da59bb3af0c835604a65308498f9696a364/HOLRLT/Induct/ABexp.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9230391643039739, "lm_q2_score": 0.8080672181749422, "lm_q1q2_score": 0.7458776897656356}}
{"text": "theory ex_3_5\n  imports Main\nbegin\ndatatype alpha = a | b\ninductive S::\"alpha list \\<Rightarrow> bool\" where\n\"S []\" |\n\"S w \\<Longrightarrow> S (a # w @ [b])\" |\n\"\\<lbrakk>S x; S y\\<rbrakk> \\<Longrightarrow> S (x @ y)\"\ninductive T::\"alpha list \\<Rightarrow> bool\" where\n\"T []\" |\n\"\\<lbrakk>T x; T y\\<rbrakk> \\<Longrightarrow> T (x @ a # y @ [b])\"\n\ntheorem S_T: \"S w = T w\"\nproof\n  show \"S w \\<Longrightarrow> T w\"\n  proof (induction rule:S.induct)\n    show \"T []\" using T.intros(1) .\n  next\n    fix w assume IH:\"T w\"\n    have \"T []\" using T.intros(1) .\n    with IH T.intros(2) have \"T ([] @ a # w @ [b])\" by blast\n    thus \"T (a # w @ [b])\" by simp\n  next\n    fix x y\n    assume IH:\"T x\" \"T y\"\n    have \"\\<lbrakk>T y; T x\\<rbrakk> \\<Longrightarrow> T (x @ y)\"\n    proof (induction rule:T.induct)\n      case 1\n      with T.intros show ?case by simp\n    next\n      case 2\n      with T.intros(2) show ?case by fastforce\n    qed\n    thus \"T (x @ y)\" using IH by simp\n  qed\nnext\n  show \"T w \\<Longrightarrow> S w\"\n    apply (induction rule: T.induct)\n    by (auto intro:S.intros)\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_3_5.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9230391664210671, "lm_q2_score": 0.8080672066194945, "lm_q1q2_score": 0.7458776808102584}}
{"text": "header{*Perfect Number Theorem*}\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 = \"exponent 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: exponent_ge)\n\n  from m0 have  \"2^?n dvd m\" by (rule power_exponent_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    by (simp add: coprime_exponent)\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 (metis mult.commute dvd_def) \n  hence             \"?np dvd ?A\" \n    by (metis coprime_dvd_mult_nat coprime_minus_one_nat power_eq_0_iff zero_neq_numeral)\n  hence bdef:       \"?np*?B = ?A\" by (simp add: dvd_mult_div_cancel)\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_def)\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_def)\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", "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/Perfect.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391558356, "lm_q2_score": 0.8080672158638528, "lm_q1q2_score": 0.7458776807893942}}
{"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 Main \"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": "seL4", "repo": "isabelle", "sha": "e1ab32a3bb41728cd19541063283e37919978a4c", "save_path": "github-repos/isabelle/seL4-isabelle", "path": "github-repos/isabelle/seL4-isabelle/isabelle-e1ab32a3bb41728cd19541063283e37919978a4c/src/HOL/Number_Theory/Eratosthenes.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9046505376715775, "lm_q2_score": 0.8244619199068831, "lm_q1q2_score": 0.745849919133503}}
{"text": "section \\<open>Missing Lemmas on Vector Spaces\\<close>\n\ntext \\<open>We provide some results on vector spaces which should be merged into other AFP entries.\\<close>\ntheory Missing_VS_Connect\n  imports\n    Jordan_Normal_Form.VS_Connect\n    Missing_Matrix\n    Polynomial_Factorization.Missing_List\nbegin\n\ncontext vec_space\nbegin\nlemma span_diff: assumes A: \"A \\<subseteq> carrier_vec n\"\n  and a: \"a \\<in> span A\" and b: \"b \\<in> span A\"\nshows \"a - b \\<in> span A\"\nproof -\n  from A a have an: \"a \\<in> carrier_vec n\" by auto\n  from A b have bn: \"b \\<in> carrier_vec n\" by auto\n  have \"a + (-1 \\<cdot>\\<^sub>v b) \\<in> span A\"\n    by (rule span_add1[OF A a], insert b A, auto)\n  also have \"a + (-1 \\<cdot>\\<^sub>v b) = a - b\" using an bn by auto\n  finally show ?thesis by auto\nqed\n\n\n\nlemma lincomb_scalar_prod_left: assumes \"W \\<subseteq> carrier_vec n\" \"v \\<in> carrier_vec n\"\n  shows \"lincomb a W \\<bullet> v = (\\<Sum>w\\<in>W. a w * (w \\<bullet> v))\"\n  unfolding lincomb_def\n  by (subst finsum_scalar_prod_sum, insert assms, auto intro!: sum.cong)\n\nlemma lincomb_scalar_prod_right: assumes \"W \\<subseteq> carrier_vec n\" \"v \\<in> carrier_vec n\"\n  shows \"v \\<bullet> lincomb a W = (\\<Sum>w\\<in>W. a w * (v \\<bullet> w))\"\n  unfolding lincomb_def\n  by (subst finsum_scalar_prod_sum', insert assms, auto intro!: sum.cong)\n\nlemma lin_indpt_empty[simp]: \"lin_indpt {}\"\n  using lin_dep_def by auto\n\nlemma span_carrier_lin_indpt_card_n:\n  assumes \"W \\<subseteq> carrier_vec n\" \"card W = n\" \"lin_indpt W\"\n  shows \"span W = carrier_vec n\"\n  using assms basis_def dim_is_n dim_li_is_basis fin_dim_li_fin by simp\n\nlemma ortho_span: assumes W: \"W \\<subseteq> carrier_vec n\"\n  and X: \"X \\<subseteq> carrier_vec n\"\n  and ortho: \"\\<And> w x. w \\<in> W \\<Longrightarrow> x \\<in> X \\<Longrightarrow> w \\<bullet> x = 0\"\n  and w: \"w \\<in> span W\" and x: \"x \\<in> X\"\nshows \"w \\<bullet> x = 0\"\nproof -\n  from w W obtain c V where \"finite V\" and VW: \"V \\<subseteq> W\" and w: \"w = lincomb c V\"\n    by (meson in_spanE)\n  show ?thesis unfolding w\n    by (subst lincomb_scalar_prod_left, insert W VW X x ortho, auto intro!: sum.neutral)\nqed\n\nlemma ortho_span': assumes W: \"W \\<subseteq> carrier_vec n\"\n  and X: \"X \\<subseteq> carrier_vec n\"\n  and ortho: \"\\<And> w x. w \\<in> W \\<Longrightarrow> x \\<in> X \\<Longrightarrow> x \\<bullet> w = 0\"\n  and w: \"w \\<in> span W\" and x: \"x \\<in> X\"\nshows \"x \\<bullet> w = 0\"\nproof -\n  from w W obtain c V where \"finite V\" and VW: \"V \\<subseteq> W\" and w: \"w = lincomb c V\"\n    by (meson in_spanE)\n  show ?thesis unfolding w\n    by (subst lincomb_scalar_prod_right, insert W VW X x ortho, auto intro!: sum.neutral)\nqed\n\nlemma ortho_span_span: assumes W: \"W \\<subseteq> carrier_vec n\"\n  and X: \"X \\<subseteq> carrier_vec n\"\n  and ortho: \"\\<And> w x. w \\<in> W \\<Longrightarrow> x \\<in> X \\<Longrightarrow> w \\<bullet> x = 0\"\n  and w: \"w \\<in> span W\" and x: \"x \\<in> span X\"\nshows \"w \\<bullet> x = 0\"\n  by (rule ortho_span[OF W _ ortho_span'[OF X W _ _] w x], insert W X ortho, auto)\n\nlemma lincomb_in_span[intro]:\n  assumes X: \"X\\<subseteq> carrier_vec n\"\n  shows \"lincomb a X \\<in> span X\"\nproof(cases \"finite X\")\n  case False hence \"lincomb a X = 0\\<^sub>v n\" using X\n    by (simp add: lincomb_def)\n  thus ?thesis using X by force\nqed (insert X, auto)\n\nlemma generating_card_n_basis: assumes X: \"X \\<subseteq> carrier_vec n\"\n  and span: \"carrier_vec n \\<subseteq> span X\"\n  and card: \"card X = n\"\nshows \"basis X\"\nproof -\n  have fin: \"finite X\"\n  proof (cases \"n = 0\")\n    case False\n    with card show \"finite X\" by (meson card_infinite)\n  next\n    case True\n    with X have \"X \\<subseteq> carrier_vec 0\" by auto\n    also have \"\\<dots> = {0\\<^sub>v 0}\" by auto\n    finally have \"X \\<subseteq> {0\\<^sub>v 0}\" .\n    from finite_subset[OF this] show \"finite X\" by auto\n  qed\n  from X have \"span X \\<subseteq> carrier_vec n\" by auto\n  with span have span: \"span X = carrier_vec n\" by auto\n  from dim_is_n card have card: \"card X \\<le> dim\" by auto\n  from dim_gen_is_basis[OF fin X span card] show \"basis X\" .\nqed\n\nlemma lincomb_list_append:\n  assumes Ws: \"set Ws \\<subseteq> carrier_vec n\"\n  shows \"set Vs \\<subseteq> carrier_vec n \\<Longrightarrow> lincomb_list f (Vs @ Ws) =\n    lincomb_list f Vs + lincomb_list (\\<lambda> i. f (i + length Vs)) Ws\"\nproof (induction Vs arbitrary: f)\n  case Nil show ?case by(simp add: lincomb_list_carrier[OF Ws])\nnext\n  case (Cons x Vs)\n  have \"lincomb_list f (x # (Vs @ Ws)) = f 0 \\<cdot>\\<^sub>v x + lincomb_list (f \\<circ> Suc) (Vs @ Ws)\"\n    by (rule lincomb_list_Cons)\n  also have \"lincomb_list (f \\<circ> Suc) (Vs @ Ws) =\n             lincomb_list (f \\<circ> Suc) Vs + lincomb_list (\\<lambda> i. (f \\<circ> Suc) (i + length Vs)) Ws\"\n    using Cons by auto\n  also have \"(\\<lambda> i. (f \\<circ> Suc) (i + length Vs)) = (\\<lambda> i. f (i + length (x # Vs)))\" by simp\n  also have \"f 0 \\<cdot>\\<^sub>v x + ((lincomb_list (f \\<circ> Suc) Vs) + lincomb_list \\<dots> Ws) =\n             (f 0 \\<cdot>\\<^sub>v x + (lincomb_list (f \\<circ> Suc) Vs)) + lincomb_list \\<dots> Ws\"\n    using assoc_add_vec Cons.prems Ws lincomb_list_carrier by auto\n  finally show ?case using lincomb_list_Cons by auto\nqed\n\nlemma lincomb_list_snoc[simp]:\n  shows \"set Vs \\<subseteq> carrier_vec n \\<Longrightarrow> x \\<in> carrier_vec n \\<Longrightarrow>\n          lincomb_list f (Vs @ [x]) = lincomb_list f Vs + f (length Vs) \\<cdot>\\<^sub>v x\"\n  using lincomb_list_append by auto\n\nlemma lincomb_list_smult:\n  \"set Vs \\<subseteq> carrier_vec n \\<Longrightarrow> lincomb_list (\\<lambda> i. a * c i) Vs = a \\<cdot>\\<^sub>v lincomb_list c Vs\"\nproof (induction Vs rule: rev_induct)\n  case (snoc x Vs)\n  have x: \"x \\<in> carrier_vec n\" and Vs: \"set Vs \\<subseteq> carrier_vec n\" using snoc.prems by auto\n  have \"lincomb_list (\\<lambda> i. a * c i) (Vs @ [x]) =\n        lincomb_list (\\<lambda> i. a * c i) Vs + (a * c (length Vs)) \\<cdot>\\<^sub>v x\"\n    using x Vs by auto\n  also have \"lincomb_list (\\<lambda> i. a * c i) Vs = a \\<cdot>\\<^sub>v lincomb_list c Vs\"\n    by(rule snoc.IH[OF Vs])\n  also have \"(a * c (length Vs)) \\<cdot>\\<^sub>v x = a \\<cdot>\\<^sub>v (c (length Vs) \\<cdot>\\<^sub>v x)\"\n    using smult_smult_assoc x by auto\n  also have \"a \\<cdot>\\<^sub>v lincomb_list c Vs + \\<dots> = a \\<cdot>\\<^sub>v (lincomb_list c Vs + c (length Vs) \\<cdot>\\<^sub>v x)\"\n    using smult_add_distrib_vec[of _ n _ a] lincomb_list_carrier[OF Vs] x by simp\n  also have \"lincomb_list c Vs + c (length Vs) \\<cdot>\\<^sub>v x = lincomb_list c (Vs @ [x])\"\n    using Vs x by auto\n  finally show ?case by auto\nqed simp\n\nlemma lincomb_list_index:\n  assumes i: \"i < n\"\n  shows \"set Xs \\<subseteq> carrier_vec n \\<Longrightarrow>\n         lincomb_list c Xs $ i = sum (\\<lambda> j. c j * (Xs ! j) $ i) {0..<length Xs}\"\nproof (induction Xs rule: rev_induct)\n  case (snoc x Xs)\n  hence x: \"x \\<in> carrier_vec n\" and Xs: \"set Xs \\<subseteq> carrier_vec n\" by auto\n  hence \"lincomb_list c (Xs @ [x]) = lincomb_list c Xs + c (length Xs) \\<cdot>\\<^sub>v x\" by auto\n  also have \"\\<dots> $ i = lincomb_list c Xs $ i + (c (length Xs) \\<cdot>\\<^sub>v x) $ i\"\n    using i index_add_vec(1) x by simp\n  also have \"(c (length Xs) \\<cdot>\\<^sub>v x) $ i = c (length Xs) * x $ i\" using i x by simp\n  also have \"x $ i= (Xs @ [x]) ! (length Xs) $ i\" by simp\n  also have \"lincomb_list c Xs $ i = (\\<Sum>j = 0..<length Xs. c j * Xs ! j $ i)\"\n    by (rule snoc.IH[OF Xs])\n  also have \"\\<dots> =  (\\<Sum>j = 0..<length Xs. c j * (Xs @ [x]) ! j $ i)\"\n    by (rule R.finsum_restrict, force, rule restrict_ext, auto simp: append_Cons_nth_left)\n  finally show ?case\n    using sum.atLeast0_lessThan_Suc[of \"\\<lambda> j. c j * (Xs @ [x]) ! j $ i\" \"length Xs\"]\n    by fastforce\nqed (simp add: i)\n\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/Missing_VS_Connect.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8902942319436397, "lm_q2_score": 0.837619961306541, "lm_q1q2_score": 0.7457282201120681}}
{"text": "theory Utility_Functions\nimports\n  Complex_Main\n  \"HOL-Probability.Probability\"\n  Lotteries\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 ac_simps)\n  also have carrier: \"carrier = \\<Union>(set (weak_ranking le))\" by (simp add: weak_ranking_Union)\n  also from carrier 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 \"_ = sum_list ?xs\")\n    using weak_ranking_total_preorder\n    by (subst sum.Union_disjoint)\n       (auto simp: is_weak_ranking_iff disjoint_def sum.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 sum.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: sum_distrib_left 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  define \\<epsilon> where \"\\<epsilon> = Min (insert 1 ?A) / 2\"\n  from finite have \"Min (insert 1 ?A) > 0\"\n    by (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\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/Utility_Functions.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8902942261220292, "lm_q2_score": 0.8376199633332891, "lm_q1q2_score": 0.7457282170401731}}
{"text": "theory Ex026 \n  imports Main \nbegin \n  \n  \nlemma \"(A \\<longrightarrow> (B \\<longrightarrow> C)) \\<longleftrightarrow> (B \\<longrightarrow> (A \\<longrightarrow> C))\" \nproof -\n  {\n    assume a:\"A \\<longrightarrow> (B \\<longrightarrow> C)\"\n    {\n      assume b:B\n      {\n        assume A \n        with a have \"B \\<longrightarrow> C\" by (rule mp)\n        from this and b have C by (rule mp)\n      }\n      hence \"A \\<longrightarrow> C\" by (rule impI)\n    }\n    hence \" B \\<longrightarrow> (A \\<longrightarrow> C)\" by (rule impI)\n  }\n  moreover\n  {\n    assume c:\"B \\<longrightarrow> (A \\<longrightarrow> C)\" \n    {\n      assume d:A \n      {\n        assume B \n        with c have  \"A \\<longrightarrow> C\" by (rule mp)\n        from this and d have C by (rule mp)\n      }\n      hence \"B \\<longrightarrow> C\" by (rule impI)\n    }\n    hence \"A \\<longrightarrow> (B \\<longrightarrow> C)\" by (rule impI)\n  }\n  ultimately show ?thesis by (rule iffI)\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/propLogic/Ex026.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9372107949104865, "lm_q2_score": 0.795658104908603, "lm_q1q2_score": 0.7456993649783631}}
{"text": "theory Chapter18_3_Evaluation\nimports Chapter18_2_Typechecking\nbegin\n\nprimrec is_val :: \"expr => bool\"\nwhere \"is_val (Var v) = False\"\n    | \"is_val (Num n) = True\"\n    | \"is_val Zero = False\"\n    | \"is_val (Succ e) = False\"\n    | \"is_val (IsZ et e0 es) = False\"\n    | \"is_val (Lam e) = True\"\n    | \"is_val (Appl e1 e2) = False\"\n    | \"is_val (Fix e) = False\"\n\ninductive eval :: \"expr => expr => bool\"\nand error :: \"expr => bool\"\nwhere eval_zero [simp]: \"eval Zero (Num 0)\"\n    | eval_suc_1 [simp]: \"eval e e' ==> eval (Succ e) (Succ e')\"\n    | eval_suc_2 [simp]: \"error d ==> error (Succ d)\"\n    | eval_suc_3 [simp]: \"eval (Succ (Num n)) (Num (Suc n))\"\n    | eval_suc_4 [simp]: \"error (Succ (Lam e)) \"\n    | eval_isz_1 [simp]: \"eval et et' ==> eval (IsZ et e0 es) (IsZ et' e0 es)\"\n    | eval_isz_2 [simp]: \"error d ==> error (IsZ d e0 es)\"\n    | eval_isz_3 [simp]: \"eval (IsZ (Num 0) e0 es) e0\"\n    | eval_isz_4 [simp]: \"eval (IsZ (Num (Suc et)) e0 es) (subst (Num et) first es)\"\n    | eval_isz_5 [simp]: \"error (IsZ (Lam et) e0 es)\"\n    | eval_appl_1 [simp]: \"eval e1 e1' ==> eval (Appl e1 e2) (Appl e1' e2)\"\n    | eval_appl_2 [simp]: \"error e1 ==> error (Appl e1 e2)\"\n    | eval_appl_3 [simp]: \"error (Appl (Num e1) e2)\"\n    | eval_appl_4 [simp]: \"eval (Appl (Lam e1) e2) (subst e2 first e1)\"\n    | eval_fix [simp]: \"eval (Fix e) (subst (Fix e) first e)\"\n\ntheorem preservation: \"eval e e' ==> is_ok del e ==> is_ok del e'\" and \"error f ==> True\"\nby (induction e e' and f arbitrary: del rule: eval_error.inducts, fastforce+)\n\ntheorem progress: \"is_ok del e ==> del = empty_env ==> is_val e | (EX e'. eval e e') | error e\"\nproof (induction e arbitrary: del)\ncase Var\n  thus ?case by simp\nnext case Num\n  thus ?case by simp\nnext case Zero\n  thus ?case by (metis eval_zero)\nnext case (Succ e)\n  thus ?case \n  proof (cases \"is_val e\")\n  case True  \n    thus ?thesis by (cases e, simp_all, metis eval_suc_3)\n  next case False\n    with Succ eval_suc_1 show ?thesis by fastforce\n  qed\nnext case (IsZ e1 e2 e3)\n  thus ?case \n  proof (cases \"is_val e1\")\n  case True  \n    thus ?thesis\n    proof (cases e1, simp_all)\n      fix n\n      show \"Ex (eval (IsZ (Num n) e2 e3)) | error (IsZ (Num n) e2 e3)\"\n      by (cases n, metis eval_isz_3, metis eval_isz_4)\n    qed\n  next case False\n    with IsZ eval_isz_1 show ?thesis by fastforce\n  qed\nnext case Lam\n  thus ?case by simp\nnext case (Appl e1 e2)\n  thus ?case \n  proof (cases \"is_val e1\")\n  case True  \n    thus ?thesis by (cases e1, simp_all, metis eval_appl_4)\n  next case False\n    with Appl eval_appl_1 show ?thesis by fastforce\n  qed\nnext case (Fix e)\n  hence \"eval (Fix e) (subst (Fix e) first e)\" by simp\n  thus ?case by fast\nqed\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/Chapter18_3_Evaluation.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894632969136, "lm_q2_score": 0.8333246035907933, "lm_q1q2_score": 0.7456500747991192}}
{"text": "theory Tree\nimports \"$HIPSTER_HOME/IsaHipster\"\n\nbegin\n\ndatatype 'a Tree = \n  Leaf 'a \n  | Node \"'a Tree\"\"'a Tree\"\n\nfun mirror :: \"'a Tree => 'a Tree\"\nwhere\n  \"mirror (Leaf x) = Leaf x\"\n| \"mirror (Node l r) = Node (mirror r) (mirror l)\"\n\nfun tmap :: \"('a => 'b) => 'a Tree => 'b Tree\"\nwhere\n  \"tmap f (Leaf x) = Leaf (f x)\"\n| \"tmap f (Node l r) = Node (tmap f l) (tmap f r)\" \n\n\nML\\<open>Hipster_Explore.explore  @{context} [\"Tree.tmap\", \"Tree.mirror\"];\\<close>\nlemma lemma_a [thy_expl]: \"mirror (tmap x2 y2) = tmap x2 (mirror y2)\"\nby (tactic \\<open>Hipster_Tacs.induct_simp_metis @{context} @{thms Tree.tmap.simps Tree.mirror.simps thy_expl}\\<close>)\n\nlemma lemma_aa [thy_expl]: \"mirror (mirror x2) = x2\"\nby (tactic \\<open>Hipster_Tacs.induct_simp_metis @{context} @{thms Tree.tmap.simps Tree.mirror.simps thy_expl}\\<close>)\n\n\nfun rigthmost :: \"'a Tree \\<Rightarrow> 'a\"\nwhere \n  \"rigthmost (Leaf x) = x\"\n|  \"rigthmost (Node l r) = rigthmost r\"\n\nfun leftmost :: \"'a Tree \\<Rightarrow> 'a\"\nwhere \n  \"leftmost (Leaf x) = x\"\n|  \"leftmost (Node l r) = leftmost l\"\n\nML\\<open>Hipster_Explore.explore  @{context} [\"Tree.mirror\",\"Tree.tmap\", \"Tree.rigthmost\", \"Tree.leftmost\"];\\<close>\nlemma lemma_ab [thy_expl]: \"leftmost (mirror x2) = rigthmost x2\"\nby (tactic \\<open>Hipster_Tacs.induct_simp_metis @{context} @{thms Tree.mirror.simps Tree.tmap.simps Tree.rigthmost.simps Tree.leftmost.simps thy_expl}\\<close>)\n\n\nfun flat_tree :: \"'a Tree => 'a list\"\nwhere\n  \"flat_tree (Leaf x) = Cons x []\"\n| \"flat_tree (Node l r) = (flat_tree l) @ (flat_tree r)\"\n\n\nML\\<open>Hipster_Explore.explore  @{context} [\"Tree.flat_tree\", \"Tree.mirror\", \"Tree.tmap\", \"Tree.leftmost\", \"Tree.rigthmost\",\"List.rev\", \"List.map\", \"List.hd\", \"List.append\"];\\<close>\nlemma lemma_ac [thy_expl]: \"flat_tree (tmap x2 y2) = map x2 (flat_tree y2)\"\nby hipster_induct_simp_metis\n(*by (tactic {* Hipster_Tacs.induct_simp_metis @{context} @{thms Tree.flat_tree.simps Tree.mirror.simps Tree.tmap.simps Tree.leftmost.simps Tree.rigthmost.simps List.rev.simps List.map.simps List.hd.simps List.append.simps thy_expl} *})\n*)\n\nlemma lemma_ad [thy_expl]: \"map x2 (rev xs2) = rev (map x2 xs2)\"\nby hipster_induct_simp_metis\n(*by (tactic {* Hipster_Tacs.induct_simp_metis @{context} @{thms Tree.flat_tree.simps Tree.mirror.simps Tree.tmap.simps Tree.leftmost.simps Tree.rigthmost.simps List.rev.simps List.map.simps List.hd.simps List.append.simps thy_expl} *})\n*)\n\nlemma lemma_ae [thy_expl]: \"flat_tree (mirror x2) = rev (flat_tree x2)\"\nby hipster_induct_simp_metis\n(*by (tactic {* Hipster_Tacs.induct_simp_metis @{context} @{thms Tree.flat_tree.simps Tree.mirror.simps Tree.tmap.simps Tree.leftmost.simps Tree.rigthmost.simps List.rev.simps List.map.simps List.hd.simps List.append.simps thy_expl} *})\n*)\n\nlemma lemma_af [thy_expl]: \"hd (xs2 @ xs2) = hd xs2\"\nby hipster_induct_simp_metis\n(*by (tactic {* Hipster_Tacs.induct_simp_metis @{context} @{thms Tree.flat_tree.simps Tree.mirror.simps Tree.tmap.simps Tree.leftmost.simps Tree.rigthmost.simps List.rev.simps List.map.simps List.hd.simps List.append.simps thy_expl} *})\n*)\nlemma unknown [thy_expl]: \"hd (flat_tree x) = leftmost x\"\noops\n\nlemma flat_tree_non_emp[simp] : \"flat_tree t \\<noteq> []\"\nby(induct t, simp_all)\n\n(* This lemma is discoved by Hipster, but cannot be proved. It is returned with an oops. \n   This is because it needs the above three non-equational lemma, which isn't\n   generated by QuickSpec in this case.\n*)\nlemma unproved_from_hipster : \"hd (flat_tree x) = leftmost x\"\nby(induct x, simp_all)\n\n\n\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/Examples/Tree.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894548800269, "lm_q2_score": 0.8333246035907933, "lm_q1q2_score": 0.7456500677851204}}
{"text": "(* Title: Models of Partial Semigroups\n   Author: Brijesh Dongol, Victor Gomes, Ian J Hayes, Georg Struth\n   Maintainer: Victor Gomes <victor.gomes@cl.cam.ac.uk>\n               Georg Struth <g.struth@sheffield.ac.uk> \n*)\n\nsection \\<open>Models of Partial Semigroups\\<close>\n\ntheory Partial_Semigroup_Models\n  imports Partial_Semigroups\n    \nbegin\n  \ntext \\<open>So far this section collects three models that we need for applications. Other interesting models might be\nadded in the future. These might include binary relations, formal power series and matrices, paths in graphs under fusion, \nprogram traces with alternating state and action symbols under fusion, partial orders under series and parallel products.\\<close>\n  \nsubsection \\<open>Partial Monoids of Segments and Intervals\\<close>\n  \ntext \\<open>Segments of a partial order are sub partial orders between two points. Segments generalise\nintervals in that intervals are segments in linear orders. We formalise segments and intervals as pairs, \nwhere the first coordinate is smaller than the second one. Algebras of segments and intervals are interesting \nin Rota's work on the foundations of combinatorics as well as for interval logics and duration calculi.\\<close>\n    \ntext \\<open>First we define the subtype of ordered pairs of one single type.\\<close>\n\ntypedef 'a dprod = \"{(x::'a, y::'a). True}\" \n  by simp\n\nsetup_lifting type_definition_dprod\n  \ntext \\<open>Such pairs form partial semigroups and partial monoids with respect to fusion.\\<close>\n  \ninstantiation dprod :: (type) partial_semigroup\nbegin \n\nlift_definition D_dprod :: \"'a dprod \\<Rightarrow> 'a dprod \\<Rightarrow> bool\" is \"\\<lambda>x y. (snd x = fst y)\" .\n\nlift_definition times_dprod :: \"'a dprod \\<Rightarrow> 'a dprod \\<Rightarrow> 'a dprod\" is \"\\<lambda>x y. (fst x, snd y)\"\n  by simp\n\ninstance \n  by standard (transfer, force)+\n\nend \n\ninstantiation \"dprod\" :: (type) partial_monoid\nbegin \n\nlift_definition E_dprod :: \"'a dprod set\" is \"{x. fst x = snd x}\" \n  by simp\n\ninstance \n  by standard (transfer,force)+\n\nend \n  \ntext \\<open>Next we define the type of segments.\\<close>\n  \ntypedef (overloaded) 'a segment = \"{x::('a::order \\<times> 'a::order). fst x \\<le> snd x}\"\n  by force\n\nsetup_lifting type_definition_segment\n  \ntext \\<open>Segments form partial monoids as well.\\<close>\n  \ninstantiation segment :: (order) partial_monoid\nbegin\n\nlift_definition E_segment :: \"'a segment set\" is \"{x. fst x = snd x}\"\n  by simp \n\nlift_definition D_segment :: \"'a::order segment \\<Rightarrow> 'a segment \\<Rightarrow> bool\" \n  is \"\\<lambda>x y. (snd x = fst y)\" .\n    \nlift_definition times_segment :: \"'a::order segment \\<Rightarrow> 'a segment \\<Rightarrow> 'a segment\" \n  is \"\\<lambda>x y. if snd x = fst y then (fst x, snd y) else x\"\n  by auto\n\ninstance \n  by standard (transfer, force)+\n \nend\n  \ntext \\<open>Next we define the function segm that maps segments-as-pairs to segments-as-sets.\\<close>\n  \ndefinition segm :: \"'a::order segment \\<Rightarrow> 'a set\" where \n  \"segm x = {y. fst (Rep_segment x) \\<le> y \\<and> y \\<le> snd (Rep_segment x)}\"\n  \n  thm Rep_segment\n\nlemma segm_sub_morph: \"snd (Rep_segment x) = fst (Rep_segment y) \\<Longrightarrow> segm x \\<union> segm y \\<le> segm (x \\<cdot> y)\"\n  apply (simp add: segm_def times_segment.rep_eq, safe)\n  using Rep_segment dual_order.trans apply blast\n  by (metis (mono_tags, lifting) Rep_segment dual_order.trans mem_Collect_eq)\n\ntext \\<open>The function segm is not generally a morphism.\\<close>\n  \nlemma \"snd (Rep_segment x) = fst (Rep_segment y) \\<Longrightarrow> segm x \\<union> segm y = segm (x \\<cdot> y)\" (* nitpick [expect=genuine] *)\noops\n\ntext \\<open>Intervals are segments over orders that satisfy Halpern and Shoham's  linear order property. This \nis still more general than linearity of the poset.\\<close>\n\nclass lip_order = order +\n  assumes lip: \"x \\<le> y \\<Longrightarrow> (\\<forall>v w. (x \\<le> v \\<and> v \\<le> y \\<and> x \\<le> w \\<and> w \\<le> y \\<longrightarrow> v \\<le> w \\<or> w \\<le> v))\"\n    \ntext \\<open>The function segm is now a morphism.\\<close>\n  \nlemma segm_morph: \"snd (Rep_segment x::('a::lip_order \\<times> 'a::lip_order)) = fst (Rep_segment y) \n    \\<Longrightarrow> segm x \\<union> segm y = segm (x \\<cdot> y)\"\n  apply (simp add: segm_def times_segment_def)\n  apply (transfer, clarsimp simp add: Abs_segment_inverse lip, safe)\n  apply force+\n  by (meson lip order_trans)\n    \n    \nsubsection \\<open>Cancellative PAM's of Partial Functions\\<close>\n\ntext \\<open>We show that partial functions under disjoint union form a positive cancellative PAM. \nThis is interesting for modeling the heap in separation logic.\\<close>\n\ntype_synonym 'a pfun = \"'a \\<Rightarrow> 'a option\"\n\ndefinition ortho :: \"'a pfun \\<Rightarrow> 'a pfun \\<Rightarrow> bool\"\n  where \"ortho f g \\<equiv> dom f \\<inter> dom g = {}\"\n\nlemma pfun_comm: \"ortho x y \\<Longrightarrow> x ++ y = y ++ x\"\n  by (force simp: ortho_def intro!: map_add_comm)\n\nlemma pfun_canc: \"ortho z x \\<Longrightarrow> ortho z y \\<Longrightarrow> z ++ x = z ++ y \\<Longrightarrow> x = y\"\n  apply (auto simp: ortho_def map_add_def option.case_eq_if fun_eq_iff)\n  by (metis domIff dom_restrict option.collapse restrict_map_def)\n\ninterpretation pfun: positive_cancellative_pam_one map_add ortho \"{Map.empty}\" Map.empty\n  apply (standard, auto simp: ortho_def pfun_canc)\n  by (simp_all add: inf_commute map_add_comm ortho_def pfun_canc)\n    \nsubsection \\<open>PAM's of Disjoint Unions of Sets\\<close>\n  \ntext \\<open>This simple disjoint union construction underlies important compositions of graphs or partial orders,\nin particular in the context of complete joins and disjoint unions of graphs and of series and parallel products\nof partial orders.\\<close>\n\ninstantiation set :: (type) pas\nbegin  \n\ndefinition D_set :: \"'a set \\<Rightarrow> 'a set \\<Rightarrow> bool\" where \n  \"D_set x y \\<equiv> x \\<inter> y = {}\"\n\ndefinition times_set :: \"'a set \\<Rightarrow> 'a set \\<Rightarrow> 'a set\" where\n  \"times_set x y = x \\<union> y\"\n\ninstance\n  by standard (auto simp: D_set_def times_set_def)\n\nend\n\ninstantiation set :: (type) pam\nbegin \n\ndefinition E_set :: \"'a set set\" where\n  \"E_set = {{}}\"\n\ninstance\n  by standard (auto simp: D_set_def times_set_def E_set_def)\n\nend\n    \nend\n\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/PSemigroupsConvolution/Partial_Semigroup_Models.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8418256472515684, "lm_q2_score": 0.8856314617436728, "lm_q1q2_score": 0.7455472785087199}}
{"text": "(* Title:      Algebras for Aggregation and Minimisation\n   Author:     Walter Guttmann\n   Maintainer: Walter Guttmann <walter.guttmann at canterbury.ac.nz>\n*)\n\nsection \\<open>Algebras for Aggregation and Minimisation\\<close>\n\ntext \\<open>\nThis theory gives algebras with operations for aggregation and minimisation.\nIn the weighted-graph model of matrices over (extended) numbers, the operations have the following meaning.\nThe binary operation $+$ adds the weights of corresponding edges of two graphs.\nAddition does not have to be the standard addition on numbers, but can be any aggregation satisfying certain basic properties as demonstrated by various models of the algebras in another theory.\nThe unary operation \\<open>sum\\<close> adds the weights of all edges of a graph.\nThe result is a single aggregated weight using the same aggregation as $+$ but applied internally to the edges of a single graph.\nThe unary operation \\<open>minarc\\<close> finds an edge with a minimal weight in a graph.\nIt yields the position of such an edge as a regular element of a Stone relation algebra.\n\nWe give axioms for these operations which are sufficient to prove the correctness of Prim's and Kruskal's minimum spanning tree algorithms.\nThe operations have been proposed and axiomatised first in \\<^cite>\\<open>\"Guttmann2016c\"\\<close> with simplified axioms given in \\<^cite>\\<open>\"Guttmann2018a\"\\<close>.\nThe present version adds two axioms to prove total correctness of the spanning tree algorithms as discussed in \\<^cite>\\<open>\"Guttmann2018b\"\\<close>.\n\\<close>\n\ntheory Aggregation_Algebras\n\nimports Stone_Kleene_Relation_Algebras.Kleene_Relation_Algebras\n\nbegin\n\ncontext sup\nbegin\n\nno_notation\n  sup (infixl \"+\" 65)\n\nend\n\ncontext plus\nbegin\n\nnotation\n  plus (infixl \"+\" 65)\n\nend\n\ntext \\<open>\nWe first introduce s-algebras as a class with the operations $+$ and \\<open>sum\\<close>.\nAxiom \\<open>sum_plus_right_isotone\\<close> states that for non-empty graphs, the operation $+$ is $\\leq$-isotone in its second argument on the image of the aggregation operation \\<open>sum\\<close>.\nAxiom \\<open>sum_bot\\<close> expresses that the empty graph contributes no weight.\nAxiom \\<open>sum_plus\\<close> generalises the inclusion-exclusion principle to sets of weights.\nAxiom \\<open>sum_conv\\<close> specifies that reversing edge directions does not change the aggregated weight.\nIn instances of \\<open>s_algebra\\<close>, aggregated weights can be partially ordered.\n\\<close>\n\nclass sum =\n  fixes sum :: \"'a \\<Rightarrow> 'a\"\n\nclass s_algebra = stone_relation_algebra + plus + sum +\n  assumes sum_plus_right_isotone: \"x \\<noteq> bot \\<and> sum x \\<le> sum y \\<longrightarrow> sum z + sum x \\<le> sum z + sum y\"\n  assumes sum_bot: \"sum x + sum bot = sum x\"\n  assumes sum_plus: \"sum x + sum y = sum (x \\<squnion> y) + sum (x \\<sqinter> y)\"\n  assumes sum_conv: \"sum (x\\<^sup>T) = sum x\"\nbegin\n\nlemma sum_disjoint:\n  assumes \"x \\<sqinter> y = bot\"\n    shows \"sum ((x \\<squnion> y) \\<sqinter> z) = sum (x \\<sqinter> z) + sum (y \\<sqinter> z)\"\n  by (subst sum_plus) (metis assms inf.sup_monoid.add_assoc inf.sup_monoid.add_commute inf_bot_left inf_sup_distrib2 sum_bot)\n\nlemma sum_disjoint_3:\n  assumes \"w \\<sqinter> x = bot\"\n      and \"w \\<sqinter> y = bot\"\n      and \"x \\<sqinter> y = bot\"\n    shows \"sum ((w \\<squnion> x \\<squnion> y) \\<sqinter> z) = sum (w \\<sqinter> z) + sum (x \\<sqinter> z) + sum (y \\<sqinter> z)\"\n  by (metis assms inf_sup_distrib2 sup_idem sum_disjoint)\n\nlemma sum_symmetric:\n  assumes \"y = y\\<^sup>T\"\n    shows \"sum (x\\<^sup>T \\<sqinter> y) = sum (x \\<sqinter> y)\"\n  by (metis assms sum_conv conv_dist_inf)\n\nlemma sum_commute:\n  \"sum x + sum y = sum y + sum x\"\n  by (metis inf_commute sum_plus sup_commute)\n\nend\n\ntext \\<open>\nWe next introduce the operation \\<open>minarc\\<close>.\nAxiom \\<open>minarc_below\\<close> expresses that the result of \\<open>minarc\\<close> is contained in the graph ignoring the weights.\nAxiom \\<open>minarc_arc\\<close> states that the result of \\<open>minarc\\<close> is a single unweighted edge if the graph is not empty.\nAxiom \\<open>minarc_min\\<close> specifies that any edge in the graph weighs at least as much as the edge at the position indicated by the result of \\<open>minarc\\<close>, where weights of edges between different nodes are compared by applying the operation \\<open>sum\\<close> to single-edge graphs.\nAxiom \\<open>sum_linear\\<close> requires that aggregated weights are linearly ordered, which is necessary for both Prim's and Kruskal's minimum spanning tree algorithms.\nAxiom \\<open>finite_regular\\<close> ensures that there are only finitely many unweighted graphs, and therefore only finitely many edges and nodes in a graph; again this is necessary for the minimum spanning tree algorithms we consider.\n\\<close>\n\nclass minarc =\n  fixes minarc :: \"'a \\<Rightarrow> 'a\"\n\nclass m_algebra = s_algebra + minarc +\n  assumes minarc_below: \"minarc x \\<le> --x\"\n  assumes minarc_arc: \"x \\<noteq> bot \\<longrightarrow> arc (minarc x)\"\n  assumes minarc_min: \"arc y \\<and> y \\<sqinter> x \\<noteq> bot \\<longrightarrow> sum (minarc x \\<sqinter> x) \\<le> sum (y \\<sqinter> x)\"\n  assumes sum_linear: \"sum x \\<le> sum y \\<or> sum y \\<le> sum x\"\n  assumes finite_regular: \"finite { x . regular x }\"\nbegin\n\ntext \\<open>\nAxioms \\<open>minarc_below\\<close> and \\<open>minarc_arc\\<close> suffice to derive the Tarski rule in Stone relation algebras.\n\\<close>\n\nsubclass stone_relation_algebra_tarski\nproof unfold_locales\n  fix x\n  let ?a = \"minarc x\"\n  assume 1: \"regular x\"\n  assume \"x \\<noteq> bot\"\n  hence \"arc ?a\"\n    by (simp add: minarc_arc)\n  hence \"top = top * ?a * top\"\n    by (simp add: comp_associative)\n  also have \"... \\<le> top * --x * top\"\n    by (simp add: minarc_below mult_isotone)\n  finally show \"top * x * top = top\"\n    using 1 order.antisym by simp\nqed\n\nlemma minarc_bot:\n  \"minarc bot = bot\"\n  by (metis bot_unique minarc_below regular_closed_bot)\n\nlemma minarc_bot_iff:\n  \"minarc x = bot \\<longleftrightarrow> x = bot\"\n  using covector_bot_closed inf_bot_right minarc_arc vector_bot_closed minarc_bot by fastforce\n\nlemma minarc_meet_bot:\n  assumes \"minarc x \\<sqinter> x = bot\"\n    shows \"minarc x = bot\"\nproof -\n  have \"minarc x \\<le> -x\"\n    using assms pseudo_complement by auto\n  thus ?thesis\n    by (metis minarc_below inf_absorb1 inf_import_p inf_p)\nqed\n\n\n\nlemma minarc_meet_bot_iff:\n  \"minarc x \\<sqinter> x = bot \\<longleftrightarrow> x = bot\"\n  using inf_bot_right minarc_bot_iff minarc_meet_bot by blast\n\nlemma minarc_regular:\n  \"regular (minarc x)\"\nproof (cases \"x = bot\")\n  assume \"x = bot\"\n  thus ?thesis\n    by (simp add: minarc_bot)\nnext\n  assume \"x \\<noteq> bot\"\n  thus ?thesis\n    by (simp add: arc_regular minarc_arc)\nqed\n\nlemma minarc_selection:\n  \"selection (minarc x \\<sqinter> y) y\"\n  using inf_assoc minarc_regular selection_closed_id by auto\n\n\n\n(*\nlemma sum_bot: \"sum bot = bot\" nitpick [expect=genuine] oops\nlemma plus_bot: \"x + bot = x\" nitpick [expect=genuine] oops\nlemma \"sum x = bot \\<longrightarrow> x = bot\" nitpick [expect=genuine] oops\n*)\n\nend\n\nclass m_kleene_algebra = m_algebra + stone_kleene_relation_algebra\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/Aggregation_Algebras/Aggregation_Algebras.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8791467675095294, "lm_q2_score": 0.847967764140929, "lm_q1q2_score": 0.7454881187967808}}
{"text": "theory Homework5_2sol\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    by (induction w1 arbitrary: p) (auto simp: path_Nil_conv path_Cons_conv)\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    note PREMS=\"1.prems\"\n    note IH=\"1.IH\"\n    \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 \n    (*<*)\n    proof cases\n      assume \"distinct xs\"\n      thus ?thesis using \"1.prems\" by auto\n    next\n      assume \"\\<not>distinct xs\"\n      then obtain xs1 xs2 xs3 x where XS: \"xs=xs1@[x]@xs2@[x]@xs3\" \n        using not_distinct_decomp by blast\n      with \"1.prems\" obtain p1 p2 where\n        \"path E p xs1 x\" \"E x p1\" \"path E p1 xs2 x\" \"E x p2\" \"path E p2 xs3 q\"\n        by (auto simp: path_Nil_conv path_append_conv path_Cons_conv)\n      hence \"path E p (xs1@[x]@xs3) q\"\n        by (auto simp: path_Nil_conv path_append_conv path_Cons_conv)\n      with \"1.IH\" XS obtain ys where \"distinct ys\" \"path E p ys q\" \n        by force\n      thus ?case by blast\n    qed\n    (*>*)\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_2sol.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391599428538, "lm_q2_score": 0.8633916047011595, "lm_q1q2_score": 0.7454450585161062}}
{"text": "subsection \\<open>More on Graphs\\label{sec:more-graph}\\<close>\ntheory More_Graph\n  imports\n    Berge\n    \"HOL-Library.FuncSet\"\n    \"HOL-Library.LaTeXsugar\"\nbegin\ntext \\<open>\n  Graphs are modelled as sets of undirected edges, where each edge is a doubleton set in a\n  wellformed (finite) graph (\\<^term>\\<open>graph_invar\\<close>), i.e.\\ graphs have type \\<^typ>\\<open>'a set set\\<close>.\n  The main reason for choosing this representation is the existing formalization of Berge's\n  Lemma by Abdulaziz~\\cite{abdulaziz2019}.\n\n  Newly introduced definitions are required to specify wellformed inputs for RANKING, and\n  properties of the output using those wellformed inputs.\n\\<close>\n\nsubsubsection \\<open>More on general concepts, symmetric differences \\& alternating paths\\<close>\n\ntype_synonym 'a graph = \"'a set set\"\n\nlemma edge_commute: \"{u,v} \\<in> G \\<Longrightarrow> {v,u} \\<in> G\"\n  by (simp add: insert_commute)\n\nlemma vs_empty[simp]: \"Vs {} = {}\"\n  by (simp add: Vs_def)\n\nlemma vs_insert: \"Vs (insert e E) = e \\<union> Vs E\"\n  unfolding Vs_def by simp\n\nlemma vs_union: \"Vs (A \\<union> B) = Vs A \\<union> Vs B\"\n  unfolding Vs_def by simp\n\nlemma vs_compr: \"Vs {{u, v} |v. v \\<in> ns} = (if ns = {} then {} else {u} \\<union> ns)\"\n  unfolding Vs_def by auto\n\nlemma graph_abs_empty[simp]: \"graph_abs {}\"\n  by (simp add: graph_abs_def)\n\nlemma graph_abs_insert[simp]: \"graph_abs M \\<Longrightarrow> u \\<noteq> v \\<Longrightarrow> graph_abs (insert {u,v} M)\"\n  by (auto simp: graph_abs_def Vs_def)\n\nlemma graph_abs_union: \"graph_abs G \\<Longrightarrow> graph_abs H \\<Longrightarrow> graph_abs (G \\<union> H)\"\n  by (auto simp: graph_abs_def Vs_def)\n\nlemma graph_abs_compr: \"u \\<notin> ns \\<Longrightarrow> finite ns \\<Longrightarrow> graph_abs {{u, v} |v. v \\<in> ns}\"\n  unfolding graph_abs_def by (auto simp: Vs_def)\n\nlemma graph_abs_subgraph: \"graph_abs G \\<Longrightarrow> G' \\<subseteq> G \\<Longrightarrow> graph_abs G'\"\n  unfolding graph_abs_def by (auto dest: Vs_subset intro: finite_subset)\n\nlemma graph_abs_edgeD: \"graph_abs G \\<Longrightarrow> {u,v} \\<in> G \\<Longrightarrow> u \\<noteq> v\"\n  unfolding graph_abs_def by auto\n\nlemma graph_abs_no_edge_no_vertex:\n  \"graph_abs G \\<Longrightarrow> \\<forall>v. {u,v} \\<notin> G \\<Longrightarrow> u \\<notin> Vs G\"\n  unfolding graph_abs_def Vs_def\n  by (auto simp: insert_commute)\n\nlemma graph_abs_vertex_edgeE:\n  assumes \"graph_abs G\"\n  assumes \"u \\<in> Vs G\"\n  obtains v where \"{u,v} \\<in> G\"\n  using assms\n  by (meson graph_abs_no_edge_no_vertex)\n\nlemma graph_abs_vertex_edgeE':\n  assumes \"graph_abs G\"\n  assumes \"v \\<in> Vs G\"\n  obtains u where \"{u,v} \\<in> G\"\n  using assms\n  by (auto elim: graph_abs_vertex_edgeE dest: edge_commute)\n\nlemma graph_abs_edges_of_distinct_path:\n  \"distinct p \\<Longrightarrow> graph_abs (set (edges_of_path p))\"\n  by (induction p rule: edges_of_path.induct) auto\n\nlemma vs_neq_graphs_neq:\n  \"x \\<in> Vs G \\<Longrightarrow> x \\<notin> Vs H \\<Longrightarrow> G \\<noteq> H\"\n  by blast\n\nlemma path_Cons_hd:\n  \"path G vs \\<Longrightarrow> hd vs = v \\<Longrightarrow> {u,v} \\<in> G \\<Longrightarrow> path G (u#vs)\"\n  by (cases vs) auto\n\nlemma symm_diff_empty[simp]:\n  \"G = G' \\<Longrightarrow> G \\<oplus> G' = {}\"\n  unfolding symmetric_diff_def\n  by simp\n\nlemma sym_diff_sym:\n  \"s \\<oplus> s' = s' \\<oplus> s\"\n  unfolding symmetric_diff_def\n  by blast\n\nlemma alt_path_sym_diff_rev_alt_path:\n  assumes \"M \\<oplus> M' = set (edges_of_path p)\"\n  assumes \"alt_path M p\"\n  shows \"rev_alt_path M' p\"\n  using assms\n  by (auto intro: alt_list_cong simp: symmetric_diff_def)\n\nlemma rev_alt_path_sym_diff_alt_path:\n  assumes \"M \\<oplus> M' = set (edges_of_path p)\"\n  assumes \"rev_alt_path M p\"\n  shows \"alt_path M' p\"\n  using assms\n  by (auto intro: alt_list_cong simp: symmetric_diff_def)\n\nlemma alt_list_distinct:\n  assumes \"alt_list P Q xs\"\n  assumes \"distinct [x <- xs. P x]\"\n  assumes \"distinct [x <- xs. Q x]\"\n  assumes \"\\<forall>x. \\<not>(P x \\<and> Q x)\"\n  shows \"distinct xs\"\n  using assms\n  by (induction xs rule: induct_alt_list012)\n     (auto split: if_splits)\n\nsubsubsection \\<open>More on Matchings\\<close>\nlemma matching_empty[simp]: \"matching {}\"\n  unfolding matching_def by simp\n\nlemma matching_subgraph: \"matching M \\<Longrightarrow> M' \\<subseteq> M \\<Longrightarrow> matching M'\"\n  unfolding matching_def\n  by auto\n\nlemma the_match: \"matching M \\<Longrightarrow> {u,v} \\<in> M \\<Longrightarrow> (THE u. {u,v} \\<in> M) = u\"\n  by (auto intro!: the_equality)\n     (metis doubleton_eq_iff insertI1 matching_unique_match)\n\nlemma the_match': \"matching M \\<Longrightarrow> {u,v} \\<in> M \\<Longrightarrow> (THE v. {u,v} \\<in> M) = v\"\n  by (auto dest: the_match edge_commute)\n\nlemma the_match'': \"matching M \\<Longrightarrow> {u,v} \\<in> M \\<Longrightarrow> (THE u. {v,u} \\<in> M) = u\"\n  by (auto dest: the_match edge_commute)\n\nlemma the_match''': \"matching M \\<Longrightarrow> {u,v} \\<in> M \\<Longrightarrow> (THE v. {v,u} \\<in> M) = v\"\n  by (auto dest: the_match' edge_commute)\n\nlemma the_edge:\n  assumes \"matching M\"\n  assumes \"e \\<in> M\"\n  assumes \"v \\<in> e\"\n  shows \"(THE e. e \\<in> M \\<and> v \\<in> e) = e\"\n  using assms\n  by (auto intro!: the_equality dest: matching_unique_match)\n\nlemma matching_card_vs:\n  assumes \"graph_abs M\"\n  assumes \"matching M\"\n  shows \"2 * card M = card (Vs M)\"\n  using assms\n  by (auto simp: Vs_def card_2_iff card_partition graph_abs.finite_E graph_abs_def matching_def)\n\ntext \\<open>\n  Maximal, maximum cardinality, and perfect matchings all play a role in the analysis of the\n  algorithm. It is relatively straightforward to prove that RANKING produces a maximal\n  matching\\<^footnote>\\<open>This immediately would lead to a competitive ratio of at least $\\frac{1}{2}$.\\<close>.\n  Maximum cardinality matchings go directly into the competitive ratio, as they are the best\n  result an offline algorithm can produce on some input. Perfect matchings are of interest, since\n  we can in fact reduce the analysis of the competitive ratio to inputs where a perfect matching\n  exists~\\cite{birnbaum2008}.\n\\<close>\ndefinition maximal_matching :: \"'a graph \\<Rightarrow> 'a graph \\<Rightarrow> bool\" where\n  \"maximal_matching G M \\<longleftrightarrow> matching M \\<and> (\\<forall>u v. {u,v} \\<in> G \\<longrightarrow> u \\<in> Vs M \\<or> v \\<in> Vs M)\"\n\ndefinition max_card_matching :: \"'a graph \\<Rightarrow> 'a graph \\<Rightarrow> bool\" where\n  \"max_card_matching G M \\<longleftrightarrow> M \\<subseteq> G \\<and> matching M \\<and> (\\<forall>M'. M' \\<subseteq> G \\<and> matching M' \\<longrightarrow> card M' \\<le> card M)\"\n\ndefinition perfect_matching :: \"'a graph \\<Rightarrow> 'a graph \\<Rightarrow> bool\" where\n  \"perfect_matching G M \\<longleftrightarrow> M \\<subseteq> G \\<and> matching M \\<and> Vs G = Vs M\"\n\nlemma maximal_matchingI:\n  assumes \"matching M\"\n  assumes \"\\<And>u v. {u,v} \\<in> G \\<Longrightarrow> u \\<in> Vs M \\<or> v \\<in> Vs M\"\n  shows \"maximal_matching G M\"\n  using assms\n  unfolding maximal_matching_def\n  by auto\n\nlemma maximal_matching_edgeE:\n  assumes \"maximal_matching G M\"\n  assumes \"{u,v} \\<in> G\"\n  obtains e where \"e \\<in> M\" \"u \\<in> e \\<or> v \\<in> e\"\n  using assms\n  unfolding maximal_matching_def\n  by (auto simp: vs_member)\n\nlemma maximal_matchingD:\n  assumes \"maximal_matching G M\"\n  shows \"matching M\"\n  using assms\n  unfolding maximal_matching_def\n  by auto\n\nlemma maximal_matching_edgeD:\n  assumes \"maximal_matching G M\"\n  assumes \"{u,v} \\<in> G\"\n  shows \"u \\<in> Vs M \\<or> v \\<in> Vs M\"\n  using assms\n  by (auto elim: maximal_matching_edgeE)\n\nlemma not_maximal_matchingE:\n  assumes \"matching M\"\n  assumes \"\\<not>maximal_matching G M\"\n  obtains u v where \"{u,v} \\<in> G\" \"u \\<notin> Vs M\" \"v \\<notin> Vs M\"\n  using assms\n  unfolding maximal_matching_def graph_abs_def\n  by auto\n\nlemma max_card_matchingI:\n  assumes \"M \\<subseteq> G\" \"matching M\"\n  assumes \"\\<And>M'. M' \\<subseteq> G \\<Longrightarrow> matching M' \\<Longrightarrow> card M' \\<le> card M\"\n  shows \"max_card_matching G M\"\n  using assms\n  unfolding max_card_matching_def\n  by blast\n\nlemma max_card_matchingD:\n  assumes \"max_card_matching G M\"\n  shows \"M \\<subseteq> G \\<and> matching M \\<and> (\\<forall>M'. M' \\<subseteq> G \\<and> matching M' \\<longrightarrow> card M' \\<le> card M)\"\n  using assms\n  unfolding max_card_matching_def\n  by blast\n\nlemma max_card_matching_ex:\n  assumes \"finite G\"\n  shows \"\\<exists>M. max_card_matching G M\"\nproof (rule ccontr)\n  assume no_max_card: \"\\<nexists>M. max_card_matching G M\"\n\n  obtain M where \"M \\<subseteq> G\" \"matching M\"\n    using matching_empty by blast\n\n  then show False\n  proof (induction \"card G - card M\" arbitrary: M rule: less_induct)\n    case less\n    with no_max_card obtain M' where \"M' \\<subseteq> G\" \"matching M'\" \"card M < card M'\"\n      unfolding max_card_matching_def\n      by auto\n\n    with assms show ?case\n      by (intro less)\n         (auto simp add: card_mono le_diff_iff' less.prems less_le_not_le)\n  qed\nqed\n\nlemma max_card_matchings_same_size:\n  assumes \"max_card_matching G M\"\n  assumes \"max_card_matching G M'\"\n  shows \"card M = card M'\"\n  using assms\n  unfolding max_card_matching_def\n  by (simp add: dual_order.eq_iff)\n\nlemma max_card_matching_cardI:\n  assumes \"max_card_matching G M\"\n  assumes \"card M = card M'\"\n  assumes \"M' \\<subseteq> G\" \"matching M'\"\n  shows \"max_card_matching G M'\"\n  using assms\n  unfolding max_card_matching_def\n  by simp\n\nlemma max_card_matching_non_empty:\n  assumes \"max_card_matching G M\"\n  assumes \"G \\<noteq> {}\"\n  shows \"M \\<noteq> {}\"\nproof (rule ccontr, simp)\n  assume \"M = {}\"\n\n  from assms obtain e where \"e \\<in> G\"\n    by blast\n\n  then have \"matching {e}\" \"{e} \\<subseteq> G\"\n    unfolding matching_def\n    by blast+\n\n  with assms \\<open>M = {}\\<close> show False\n    unfolding max_card_matching_def\n    by auto\nqed\n\nlemma perfect_matchingI:\n  assumes \"M \\<subseteq> G\" \"matching M\" \"Vs G = Vs M\"\n  shows \"perfect_matching G M\"\n  using assms\n  unfolding perfect_matching_def\n  by blast\n\nlemma perfect_matching_max_card_matchingI:\n  assumes \"max_card_matching G M\"\n  assumes \"Vs G = Vs M\"\n  shows \"perfect_matching G M\"\n  using assms\n  unfolding max_card_matching_def\n  by (auto intro: perfect_matchingI)\n\nlemma perfect_matchingD:\n  assumes \"perfect_matching G M\"\n  shows \"M \\<subseteq> G\" \"matching M\" \"Vs G = Vs M\"\n  using assms\n  unfolding perfect_matching_def\n  by blast+\n\nlemma perfect_matching_subgraphD:\n  assumes \"perfect_matching G M\"\n  shows \"\\<And>e. e \\<in> M \\<Longrightarrow> e \\<in> G\"\n  using assms\n  by (auto dest: perfect_matchingD)\n\nlemma perfect_matching_edgeE:\n  assumes \"perfect_matching G M\"\n  assumes \"v \\<in> Vs G\"\n  obtains e where \"e \\<in> M\" \"v \\<in> e\"\n  using assms\n  by (auto dest: perfect_matchingD elim!: vs_member_elim)\n\nlemma perfect_matching_is_max_card_matching: \n  assumes \"graph_abs G\"\n  assumes perfect: \"perfect_matching G M\"\n  shows \"max_card_matching G M\"\nproof (rule ccontr)\n  assume not_max_card: \"\\<not>max_card_matching G M\"\n\n  from perfect have \"M \\<subseteq> G\" \"matching M\" \"Vs G = Vs M\"\n    by (auto dest: perfect_matchingD)\n\n  with not_max_card obtain M' where bigger_matching: \"M' \\<subseteq> G\" \"matching M'\" \"card M < card M'\"\n    unfolding max_card_matching_def perfect_matching_def\n    by auto\n\n  from bigger_matching have *: \"2 * card M < 2 * card M'\"\n    by linarith\n\n  from \\<open>graph_abs G\\<close> \\<open>M \\<subseteq> G\\<close> \\<open>M' \\<subseteq> G\\<close> have \"graph_abs M\" \"graph_abs M'\"\n    by (auto intro: graph_abs_subgraph)\n\n  with * \\<open>matching M\\<close> \\<open>matching M'\\<close> have \"card (Vs M) < card (Vs M')\"\n    by (auto simp: matching_card_vs)\n\n  with \\<open>Vs G = Vs M\\<close>[symmetric] \\<open>M' \\<subseteq> G\\<close> \\<open>graph_abs G\\<close> show False\n    by (auto simp: Vs_def Union_mono card_mono leD dest: graph_abs.graph)\nqed\n\nsubsubsection \\<open>Bipartite Graphs\\<close>\ntext \\<open>\n  We are considering the online \\<^emph>\\<open>bipartite\\<close> matching problem, hence, a definition of\n  bipartiteness.\n\\<close>\ndefinition bipartite :: \"'a graph \\<Rightarrow> 'a set \\<Rightarrow> 'a set \\<Rightarrow> bool\" where\n  \"bipartite G X Y \\<equiv> X \\<inter> Y = {} \\<and> (\\<forall>e \\<in> G. \\<exists>u v. e = {u,v} \\<and> u \\<in> X \\<and> v \\<in> Y)\"\n\nlemma bipartiteI:\n  assumes \"X \\<inter> Y = {}\"\n  assumes \"\\<And>e. e \\<in> G \\<Longrightarrow> \\<exists>u v. e = {u,v} \\<and> u \\<in> X \\<and> v \\<in> Y\"\n  shows \"bipartite G X Y\"\n  using assms\n  unfolding bipartite_def\n  by auto\n\nlemma bipartite_disjointD:\n  assumes \"bipartite G X Y\"\n  shows \"X \\<inter> Y = {}\"\n  using assms\n  unfolding bipartite_def\n  by blast\n\nlemma bipartite_edgeE:\n  assumes \"e \\<in> G\"\n  assumes \"bipartite G X Y\"\n  obtains x y where \"x \\<in> X\" \"y \\<in> Y\" \"e = {x,y}\" \"x \\<noteq> y\"\n  using assms\n  unfolding bipartite_def\n  by fast\n\nlemma bipartite_vertex:\n  assumes \"x \\<in> Vs G\"\n  assumes \"bipartite G U V\"\n  shows \"x \\<in> U \\<Longrightarrow> x \\<notin> V\"\n    and \"x \\<in> V \\<Longrightarrow> x \\<notin> U\"\n    and \"x \\<notin> U \\<Longrightarrow> x \\<in> V\"\n    and \"x \\<notin> V \\<Longrightarrow> x \\<in> U\"\n  using assms\n  unfolding bipartite_def Vs_def\n  by auto\n\nlemma bipartite_edgeD:\n  assumes \"{u,v} \\<in> G\"\n  assumes \"bipartite G X Y\"\n  shows\n    \"u \\<in> X \\<Longrightarrow> v \\<in> Y - X\"\n    \"u \\<in> Y \\<Longrightarrow> v \\<in> X - Y\"\n    \"v \\<in> X \\<Longrightarrow> u \\<in> Y - X\"\n    \"v \\<in> Y \\<Longrightarrow> u \\<in> X - Y\"\n  using assms\n  unfolding bipartite_def\n  by fast+\n\nlemma bipartite_empty[simp]: \"X \\<inter> Y = {} \\<Longrightarrow> bipartite {} X Y\"\n  unfolding bipartite_def by blast\n\nlemma bipartite_empty_part_iff_empty: \"bipartite G {} Y \\<longleftrightarrow> G = {}\"\n  unfolding bipartite_def by blast\n\nlemma bipartite_commute:\n  \"bipartite G X Y \\<Longrightarrow> bipartite G Y X\"\n  unfolding bipartite_def\n  by fast\n\nlemma bipartite_subgraph:\n  \"bipartite G X Y \\<Longrightarrow> G' \\<subseteq> G \\<Longrightarrow> bipartite G' X Y\"\n  unfolding bipartite_def\n  by blast\n\nlemma bipartite_vs_subset: \"bipartite G X Y \\<Longrightarrow> Vs G \\<subseteq> X \\<union> Y\"\n  unfolding bipartite_def Vs_def\n  by auto\n\nlemma finite_parts_bipartite_graph_abs:\n  \"finite X \\<Longrightarrow> finite Y \\<Longrightarrow> bipartite G X Y \\<Longrightarrow> graph_abs G\"\n  unfolding graph_abs_def\n  by (auto dest: bipartite_vs_subset intro: finite_subset elim!: bipartite_edgeE)\n\nlemma finite_bipartite_graph_abs:\n  \"finite G \\<Longrightarrow> bipartite G X Y \\<Longrightarrow> graph_abs G\"\n  unfolding graph_abs_def\n  by (auto elim!: bipartite_edgeE simp: Vs_def)\n\nlemma bipartite_insertI:\n  assumes \"bipartite G X Y\"\n  assumes \"u \\<in> X\" \"v \\<in> Y\"\n  shows \"bipartite (insert {u,v} G) X Y\"\n  using assms\n  unfolding bipartite_def\n  by auto\n\nlemma bipartite_unionI:\n  assumes \"bipartite G X Y\"\n  assumes \"bipartite H X Y\"\n  shows \"bipartite (G \\<union> H) X Y\"\n  using assms\n  unfolding bipartite_def\n  by auto\n\nlemma bipartite_reduced_to_vs:\n  \"bipartite G X Y \\<Longrightarrow> bipartite G (X \\<inter> Vs G) (Y \\<inter> Vs G)\"\n  unfolding bipartite_def\n  by auto (metis edges_are_Vs)\n\nlemma bipartite_edge_In_Ex1:\n  assumes \"bipartite M U V\"\n  assumes \"matching M\"\n  assumes \"e \\<in> M\"\n  shows \"\\<exists>!e'. e' \\<in> M \\<and> V \\<inter> e \\<subseteq> e'\"\nproof\n  from assms show \"e \\<in> M \\<and> V \\<inter> e \\<subseteq> e\"\n    by blast\nnext\n  fix e'\n  assume e': \"e' \\<in> M \\<and> V \\<inter> e \\<subseteq> e'\"\n\n  from assms obtain u v where e: \"e = {u,v}\" \"v \\<in> V\" \"u \\<in> U\"\n    by (auto elim: bipartite_edgeE)\n\n  from assms have \"U \\<inter> V = {}\"\n    by (auto dest: bipartite_disjointD)\n\n  with e' e have \"v \\<in> e'\" by blast\n\n  with assms e' e show \"e' = e\"\n    by (intro matching_unique_match) auto\nqed\n\nlemma the_bipartite_edge_In:\n  assumes \"bipartite M U V\"\n  assumes \"matching M\"\n  assumes \"e \\<in> M\"\n  shows \"(THE e'. e' \\<in> M \\<and> V \\<inter> e \\<subseteq> e') = e\"\n  using assms\n  by (intro the1_equality bipartite_edge_In_Ex1) auto\n\nlemma card_bipartite_matching_In:\n  assumes \"bipartite M U V\"\n  assumes \"matching M\"\n  shows \"card M = card (((\\<inter>) V) ` M)\"\n  using assms\n  by (auto intro!: bij_betw_same_card[of \"(\\<inter>) V\"] intro: bij_betwI[where g = \"\\<lambda>v. (THE e. e \\<in> M \\<and> v \\<subseteq> e)\"]\n      simp: the_bipartite_edge_In)\n\nlemma bipartite_In_singletons:\n  assumes \"bipartite G U V\"\n  assumes \"X \\<in> ((\\<inter>) V) ` G\"\n  shows \"\\<exists>x. X = {x}\"\n  using assms\n  by (auto elim!: bipartite_edgeE dest: bipartite_disjointD)\n\nlemma bipartite_eqI:\n  assumes \"bipartite M U V\"\n  assumes \"e \\<in> M\"\n  assumes \"x \\<in> e\" \"x \\<in> V\" \"y \\<in> e\" \"y \\<in> V\"\n  shows \"x = y\"\n  using assms\nproof -\n  from assms obtain u v where e: \"e = {u,v}\" \"u \\<in> U\" \"v \\<in> V\"\n    by (auto elim: bipartite_edgeE)\n\n  from assms have \"U \\<inter> V = {}\"\n    by (auto dest: bipartite_disjointD)\n\n  with assms e show \"x = y\"\n    by blast\nqed\n\nsubsubsection \\<open>Removing Vertices from Graphs\\<close>\ntext \\<open>\n  As mentioned above we can reduce the analysis of the competitive ratio to inputs where a perfect\n  matching exists. In order to reason about all inputs, we need to remove vertices from the graph\n  which are not in a maximum matching.\n\\<close>\ndefinition remove_vertices_graph :: \"'a graph \\<Rightarrow> 'a set \\<Rightarrow> 'a graph\" (infixl \"\\<setminus>\" 60) where\n  \"G \\<setminus> X \\<equiv> {e \\<in> G. e \\<inter> X = {}}\"\n\nlemma remove_vertices_empty:\n  \"G \\<setminus> {} = G\"\n  unfolding remove_vertices_graph_def by simp\n\nlemma remove_vertices_not_vs:\n  \"v \\<in> X \\<Longrightarrow> v \\<notin> Vs (G \\<setminus> X)\"\n  unfolding Vs_def remove_vertices_graph_def by blast\n\nlemma remove_vertices_not_vs':\n  \"v \\<in> X \\<Longrightarrow> v \\<in> Vs (G \\<setminus> X) \\<Longrightarrow> False\"\n  using remove_vertices_not_vs by force\n\nlemma remove_vertices_subgraph:\n  \"G \\<setminus> X \\<subseteq> G\"\n  unfolding remove_vertices_graph_def\n  by simp\n\nlemma remove_vertices_subgraph':\n  \"e \\<in> G \\<setminus> X \\<Longrightarrow> e \\<in> G\"\n  using remove_vertices_subgraph \n  by fast\n\nlemma remove_vertices_subgraph_Vs:\n  \"v \\<in> Vs (G \\<setminus> X) \\<Longrightarrow> v \\<in> Vs G\" \n  using Vs_subset[OF remove_vertices_subgraph]\n  by fast\n\nlemma in_remove_verticesI:\n  \"e \\<in> G \\<Longrightarrow> e \\<inter> X = {} \\<Longrightarrow> e \\<in> G \\<setminus> X\"\n  unfolding remove_vertices_graph_def\n  by blast\n\nlemma in_remove_vertices_subsetI:\n  \"X' \\<subseteq> X \\<Longrightarrow> e \\<in> G \\<setminus> X' \\<Longrightarrow> e \\<inter> X - X' = {} \\<Longrightarrow> e \\<in> G \\<setminus> X\"\n  unfolding remove_vertices_graph_def\n  by blast\n\nlemma in_remove_vertices_vsI:\n  \"e \\<in> G \\<Longrightarrow> e \\<inter> X = {} \\<Longrightarrow> u \\<in> e \\<Longrightarrow> u \\<in> Vs (G \\<setminus> X)\"\n  by (auto dest: in_remove_verticesI)\n\nlemma remove_vertices_only_vs:\n  \"G \\<setminus> X = G \\<setminus> (X \\<inter> Vs G)\"\n  unfolding remove_vertices_graph_def Vs_def\n  by blast\n\nlemma remove_vertices_mono:\n  \"G' \\<subseteq> G \\<Longrightarrow> e \\<in> G' \\<setminus> X \\<Longrightarrow> e \\<in> G \\<setminus> X\"\n  unfolding remove_vertices_graph_def by blast\n\nlemma remove_vertices_inv_mono:\n  \"X \\<subseteq> X' \\<Longrightarrow> e \\<in> G \\<setminus> X' \\<Longrightarrow> e \\<in> G \\<setminus> X\"\n  unfolding remove_vertices_graph_def by blast\n\nlemma remove_vertices_inv_mono':\n  \"X \\<subseteq> X' \\<Longrightarrow> G \\<setminus> X' \\<subseteq> G \\<setminus> X\"\n  by (auto dest: remove_vertices_inv_mono)\n\nlemma remove_vertices_graph_disjoint: \"X \\<inter> Vs G = {} \\<Longrightarrow> G \\<setminus> X = G\"\n  unfolding Vs_def remove_vertices_graph_def by blast\n\nlemma remove_vertex_not_in_graph: \"x \\<notin> Vs G \\<Longrightarrow> G \\<setminus> {x} = G\"\n  by (auto intro!: remove_vertices_graph_disjoint)\n\nlemma remove_vertex_psubset: \"x \\<in> Vs G \\<Longrightarrow> x \\<in> X \\<Longrightarrow> G \\<setminus> X \\<subset> G\"\n  by (auto intro: remove_vertices_subgraph' dest: remove_vertices_not_vs vs_neq_graphs_neq)\n\nlemma remove_vertex_card_less: \"finite G \\<Longrightarrow> x \\<in> Vs G \\<Longrightarrow> x \\<in> X \\<Longrightarrow> card (G \\<setminus> X) < card G\"\n  by (auto intro: psubset_card_mono intro!: remove_vertex_psubset)\n\nlemma graph_abs_remove_vertices:\n  \"graph_abs G \\<Longrightarrow> graph_abs (G \\<setminus> X)\"\n  by (simp add: graph_abs_subgraph remove_vertices_graph_def)\n\nlemma bipartite_remove_vertices:\n  \"bipartite G U V \\<Longrightarrow> bipartite (G \\<setminus> X) U V\"\n  using remove_vertices_subgraph\n  by (auto intro: bipartite_subgraph)\n\nlemma matching_remove_vertices:\n  \"matching M \\<Longrightarrow> matching (M \\<setminus> X)\"\n  using remove_vertices_subgraph\n  by (auto intro: matching_subgraph)\n\nlemma finite_remove_vertices:\n  \"finite G \\<Longrightarrow> finite (G \\<setminus> X)\"\n  by (auto intro: finite_subset[OF remove_vertices_subgraph])\n\nlemma remove_remove_union: \"G \\<setminus> X \\<setminus> Y = G \\<setminus> X \\<union> Y\"\n  unfolding remove_vertices_graph_def by blast\n\nlemma remove_edge_matching: \"matching M \\<Longrightarrow> {u,v} \\<in> M \\<Longrightarrow> M \\<setminus> {u,v} = M - {{u,v}}\"\n  unfolding remove_vertices_graph_def\n  by auto (metis empty_iff insert_iff matching_unique_match)+\n\nlemma remove_vertex_matching: \"matching M \\<Longrightarrow> {u,v} \\<in> M \\<Longrightarrow> M \\<setminus> {u} = M - {{u,v}}\"\n  unfolding remove_vertices_graph_def\n  by auto (metis empty_iff insert_iff matching_unique_match)+\n\nlemma remove_vertex_matching': \"matching M \\<Longrightarrow> {u,v} \\<in> M \\<Longrightarrow> M \\<setminus> {v} = M - {{u,v}}\"\n  unfolding remove_vertices_graph_def\n  by auto (metis empty_iff insert_iff matching_unique_match)+\n\nlemma remove_edge_matching_vs: \"matching M \\<Longrightarrow> {u,v} \\<in> M \\<Longrightarrow> Vs (M \\<setminus> {u,v}) = Vs M - {u,v}\"\n  by (auto simp add: remove_edge_matching Vs_def) (metis empty_iff insert_iff matching_unique_match)+\n\nlemma remove_vertex_matching_vs: \"matching M \\<Longrightarrow> {u,v} \\<in> M \\<Longrightarrow> Vs (M \\<setminus> {u}) = Vs M - {u,v}\"\n  by (metis remove_edge_matching remove_edge_matching_vs remove_vertex_matching)\n\nlemma remove_vertex_matching_vs': \"matching M \\<Longrightarrow> {u,v} \\<in> M \\<Longrightarrow> Vs (M \\<setminus> {v}) = Vs M - {u,v}\"\n  by (metis remove_edge_matching remove_edge_matching_vs remove_vertex_matching')\n\nlemma remove_vertices_in_diff: \"{u,v} \\<in> G \\<setminus> X \\<Longrightarrow> {u,v} \\<notin> G \\<setminus> X' \\<Longrightarrow> u \\<in> X' - X \\<or> v \\<in> X' - X\"\n  unfolding remove_vertices_graph_def\n  by simp\n\nlemma maximal_matching_remove_edges:\n  assumes \"M \\<subseteq> G\"\n  assumes \"E \\<subseteq> M\"\n  assumes \"X = Vs E\"\n  assumes \"maximal_matching G M\"\n  shows \"maximal_matching (G \\<setminus> X) (M \\<setminus> X)\"\n  unfolding maximal_matching_def\nproof (intro conjI allI impI)\n  show \"matching (M \\<setminus> X)\" using assms\n    by (auto simp: maximal_matching_def intro: matching_remove_vertices)\nnext\n  fix u v\n  assume \"{u,v} \\<in> G \\<setminus> X\"\n\n  then have \"{u,v} \\<in> G\" \"u \\<notin> X\" \"v \\<notin> X\"\n    by (auto dest: remove_vertices_subgraph' remove_vertices_not_vs edges_are_Vs)\n\n  with \\<open>maximal_matching G M\\<close> consider \"u \\<in> Vs M\" | \"v \\<in> Vs M\"\n    by (auto dest: maximal_matching_edgeD)\n\n  then show \"u \\<in> Vs (M \\<setminus> X) \\<or> v \\<in> Vs (M \\<setminus> X)\"\n  proof cases\n    case 1\n    then obtain e where \"e \\<in> M\" \"u \\<in> e\"\n      by (auto simp: vs_member)\n\n    with assms \\<open>u \\<notin> X\\<close> have \"e \\<in> M \\<setminus> X\"\n    proof (intro in_remove_verticesI, goal_cases)\n      case 2\n      then show ?case\n        by (auto simp: vs_member)\n           (metis matching_unique_match maximal_matchingD subsetD)\n    qed blast\n\n    with \\<open>u \\<in> e\\<close> show ?thesis\n      by blast\n  next\n    case 2\n    then obtain e where \"e \\<in> M\" \"v \\<in> e\"\n      by (auto simp: vs_member)\n\n    with assms \\<open>v \\<notin> X\\<close> have \"e \\<in> M \\<setminus> X\"\n    proof (intro in_remove_verticesI, goal_cases)\n      case 2\n      then show ?case\n        by (auto simp: vs_member)\n           (metis matching_unique_match maximal_matchingD subsetD)\n    qed blast\n\n    with \\<open>v \\<in> e\\<close> show ?thesis\n      by blast\n  qed\nqed\n\nlemma max_card_matching_remove_vertices:\n  assumes \"max_card_matching G M\"\n  assumes \"X \\<subseteq> Vs G - Vs M\"\n  shows \"max_card_matching (G \\<setminus> X) M\"\nproof (rule ccontr)\n  assume contr: \"\\<not>max_card_matching (G \\<setminus> X) M\"\n\n  from assms have \"M \\<subseteq> G \\<setminus> X\"\n    by (auto dest: max_card_matchingD intro: in_remove_verticesI)\n\n  with assms contr obtain M' where M': \"M' \\<subseteq> G \\<setminus> X\" \"matching M'\" \"card M' > card M\"\n    by (auto simp: max_card_matching_def)\n\n  then have \"M' \\<subseteq> G\"\n    by (auto intro: remove_vertices_subgraph')\n\n  with M' assms show False\n    by (simp add: leD max_card_matchingD)\nqed\n\ntext \\<open>\n  This function takes two graphs \\<^term>\\<open>G::'a graph\\<close>, \\<^term>\\<open>M::'a graph\\<close> and removes all vertices\n  (and edges incident to them) from \\<^term>\\<open>G::'a graph\\<close> which are not in \\<^term>\\<open>M::'a graph\\<close>.\n  Under the assumptions \\<^term>\\<open>matching M\\<close> and \\<^term>\\<open>(M::'a graph) \\<subseteq> G\\<close>, this returns a graph where\n  \\<^term>\\<open>M::'a graph\\<close> is a perfect matching. We explicitly state the function this way, as it\n  yields an induction scheme that allows to reason about removing single vertices as compared to\n  removing sets of vertices.\n\\<close>\nfunction make_perfect_matching :: \"'a graph \\<Rightarrow> 'a graph \\<Rightarrow> 'a graph\" where\n  \"make_perfect_matching G M = (\n    if (\\<exists>x. x \\<in> Vs G \\<and> x \\<notin> Vs M)\n    then make_perfect_matching (G \\<setminus> {SOME x. x \\<in> Vs G \\<and> x \\<notin> Vs M}) M\n    else G\n  )\n  \" if \"finite G\"\n| \"make_perfect_matching G M = G\" if \"infinite G\"\n  by auto\n\ntermination\n  by (relation \"measure (card \\<circ> fst)\")\n     (auto intro: remove_vertex_card_less dest!: someI_ex)\n\nlemma subgraph_vs_subset_eq:\n  assumes \"M \\<subseteq> G\"\n  assumes \"Vs G \\<subseteq> Vs M\"\n  shows \"Vs G = Vs M\"\n  using assms\n  unfolding Vs_def\n  by auto\n\nlemma subgraph_remove_some_ex:\n  \"\\<exists>x. x \\<in> Vs G \\<and> x \\<notin> Vs M \\<Longrightarrow> M \\<subseteq> G \\<Longrightarrow> M \\<subseteq> G \\<setminus> {SOME x. x \\<in> Vs G \\<and> x \\<notin> Vs M}\"\n    by (auto intro: in_remove_verticesI dest!: someI_ex)\n\nlemma max_card_matching_make_perfect_matching:\n  assumes \"matching M\" \"M \\<subseteq> G\" \"graph_abs G\" \"finite G\"\n  shows \"max_card_matching (make_perfect_matching G M) M\"\n  using assms\nproof (induction G M rule: make_perfect_matching.induct)\n  case (1 G M)\n  show ?case\n  proof (cases \"\\<exists>x. x \\<in> Vs G \\<and> x \\<notin> Vs M\")\n    case True\n    with \\<open>M \\<subseteq> G\\<close> have \"M \\<subseteq> G \\<setminus> {SOME x. x \\<in> Vs G \\<and> x \\<notin> Vs M}\"\n      by (intro subgraph_remove_some_ex)\n\n    from \"1.IH\"[OF True \\<open>matching M\\<close> this graph_abs_remove_vertices[OF \\<open>graph_abs G\\<close>] finite_remove_vertices[OF \\<open>finite G\\<close>]] True \\<open>finite G\\<close>\n    show ?thesis\n      by simp\n  next\n    case False\n    with 1 have \"perfect_matching G M\"\n      by (auto intro!: perfect_matchingI subgraph_vs_subset_eq)\n    \n    with 1 False show ?thesis\n      by (auto dest: perfect_matching_is_max_card_matching)\n  qed\nqed simp\n\nlemma vs_make_perfect_matching:\n  assumes \"M \\<subseteq> G\"\n  assumes \"finite G\"\n  shows \"Vs (make_perfect_matching G M) = Vs M\"\n  using assms\nproof (induction G M rule: make_perfect_matching.induct)\n  case (1 G M)\n  show ?case\n  proof (cases \"\\<exists>x. x \\<in> Vs G \\<and> x \\<notin> Vs M\")\n    case True\n\n    from \\<open>finite G\\<close> True 1 show ?thesis\n      by simp (intro \"1.IH\" finite_remove_vertices subgraph_remove_some_ex)\n  next\n    case False\n    with 1 show ?thesis\n      by (auto dest: Vs_subset)\n  qed\nqed blast\n\nlemma perfect_matching_make_perfect_matching:\n  assumes \"finite G\" \"graph_abs G\"\n  assumes \"matching M\" \"M \\<subseteq> G\"\n  shows \"perfect_matching (make_perfect_matching G M) M\"\n  using assms\n  by (auto simp del: make_perfect_matching.simps\n           intro!: perfect_matching_max_card_matchingI\n                   vs_make_perfect_matching max_card_matching_make_perfect_matching\n           dest: max_card_matchingD)\n\nlemma subgraph_make_perfect_matching:\n  shows \"make_perfect_matching G M \\<subseteq> G\"\n  by (induction G M rule: make_perfect_matching.induct)\n     (auto dest: remove_vertices_subgraph')\n\nlemma perfect_matching_bipartite_card_eq:\n  assumes \"perfect_matching G M\"\n  assumes \"bipartite G U V\"\n  assumes \"Vs G = U \\<union> V\"\n  shows \"card M = card V\"\nproof (intro bij_betw_same_card[where f = \"\\<lambda>e. (THE v. v \\<in> e \\<and> v \\<in> V)\"]\n    bij_betwI[where g = \"\\<lambda>v. (THE e. v \\<in> e \\<and> e \\<in> M)\"] funcsetI)\n  fix e\n  assume \"e \\<in> M\"\n  with assms obtain u v where uv: \"e = {u,v}\" \"u \\<in> U\" \"v \\<in> V\"\n    by (auto dest!: perfect_matching_subgraphD elim: bipartite_edgeE)\n\n  with assms have the_v: \"(THE v. v \\<in> e \\<and> v \\<in> V) = v\"\n    by (auto dest: bipartite_disjointD)\n\n  with \\<open>v \\<in> V\\<close> show \"(THE v. v \\<in> e \\<and> v \\<in> V) \\<in> V\"\n    by blast\n\n  from uv have \"v \\<in> e\"\n    by blast\n\n  with assms \\<open>e \\<in> M\\<close> show \"(THE e'. (THE v. v \\<in> e \\<and> v \\<in> V) \\<in> e' \\<and> e' \\<in> M) = e\"\n    by (simp only: the_v, intro the_equality matching_unique_match)\n       (auto dest: perfect_matchingD)\nnext\n  fix v\n  assume \"v \\<in> V\"\n  with assms have \"v \\<in> Vs M\"\n    by (auto simp: perfect_matchingD)\n\n  then obtain e where e: \"v \\<in> e\" \"e \\<in> M\"\n    by (auto elim: vs_member_elim)\n\n  with assms have the_e: \"(THE e. v \\<in> e \\<and> e \\<in> M) = e\"\n    by (intro the_equality matching_unique_match)\n       (auto dest: perfect_matchingD)\n\n  with e show \"(THE e. v \\<in> e \\<and> e \\<in> M) \\<in> M\"\n    by blast\n\n  from assms e \\<open>v \\<in> V\\<close> obtain u where \"e = {u,v}\" \"u \\<in> U\"\n    by (smt (verit, ccfv_SIG) bipartite_disjointD bipartite_edgeE disjoint_iff_not_equal empty_iff insertE perfect_matching_subgraphD)\n\n  with assms e \\<open>v \\<in> V\\<close> show \"(THE v'. v' \\<in> (THE e. v \\<in> e \\<and> e \\<in> M) \\<and> v' \\<in> V) = v\"\n    by (simp only: the_e, intro the_equality)\n       (auto dest: bipartite_disjointD)\nqed\nend", "meta": {"author": "cmadlener", "repo": "isabelle-ranking", "sha": "707fe59a40385fe8196ff5d34ce55cb60f416548", "save_path": "github-repos/isabelle/cmadlener-isabelle-ranking", "path": "github-repos/isabelle/cmadlener-isabelle-ranking/isabelle-ranking-707fe59a40385fe8196ff5d34ce55cb60f416548/More_Graph.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8615382165412808, "lm_q2_score": 0.8652240895276223, "lm_q1q2_score": 0.7454236190001812}}
{"text": "(*  Author:  Stefan Berghofer et al.\n*)\n\nsubsection \\<open>Signed division: negative results rounded towards zero rather than minus infinity.\\<close>\n\ntheory Signed_Division\n  imports Main\nbegin\n\nclass signed_divide =\n  fixes signed_divide :: \\<open>'a \\<Rightarrow> 'a \\<Rightarrow> 'a\\<close> (infixl \\<open>sdiv\\<close> 70)\n\nclass signed_modulo =\n  fixes signed_modulo :: \\<open>'a \\<Rightarrow> 'a \\<Rightarrow> 'a\\<close> (infixl \\<open>smod\\<close> 70)\n\nclass signed_division = comm_semiring_1_cancel + signed_divide + signed_modulo +\n  assumes sdiv_mult_smod_eq: \\<open>a sdiv b * b + a smod b = a\\<close>\nbegin\n\nlemma mult_sdiv_smod_eq:\n  \\<open>b * (a sdiv b) + a smod b = a\\<close>\n  using sdiv_mult_smod_eq [of a b] by (simp add: ac_simps)\n\nlemma smod_sdiv_mult_eq:\n  \\<open>a smod b + a sdiv b * b = a\\<close>\n  using sdiv_mult_smod_eq [of a b] by (simp add: ac_simps)\n\nlemma smod_mult_sdiv_eq:\n  \\<open>a smod b + b * (a sdiv b) = a\\<close>\n  using sdiv_mult_smod_eq [of a b] by (simp add: ac_simps)\n\nlemma minus_sdiv_mult_eq_smod:\n  \\<open>a - a sdiv b * b = a smod b\\<close>\n  by (rule add_implies_diff [symmetric]) (fact smod_sdiv_mult_eq)\n\nlemma minus_mult_sdiv_eq_smod:\n  \\<open>a - b * (a sdiv b) = a smod b\\<close>\n  by (rule add_implies_diff [symmetric]) (fact smod_mult_sdiv_eq)\n\nlemma minus_smod_eq_sdiv_mult:\n  \\<open>a - a smod b = a sdiv b * b\\<close>\n  by (rule add_implies_diff [symmetric]) (fact sdiv_mult_smod_eq)\n\nlemma minus_smod_eq_mult_sdiv:\n  \\<open>a - a smod b = b * (a sdiv b)\\<close>\n  by (rule add_implies_diff [symmetric]) (fact mult_sdiv_smod_eq)\n\nend\n\ninstantiation int :: signed_division\nbegin\n\ndefinition signed_divide_int :: \\<open>int \\<Rightarrow> int \\<Rightarrow> int\\<close>\n  where \\<open>k sdiv l = sgn k * sgn l * (\\<bar>k\\<bar> div \\<bar>l\\<bar>)\\<close> for k l :: int\n\ndefinition signed_modulo_int :: \\<open>int \\<Rightarrow> int \\<Rightarrow> int\\<close>\n  where \\<open>k smod l = sgn k * (\\<bar>k\\<bar> mod \\<bar>l\\<bar>)\\<close> for k l :: int\n\ninstance by standard\n  (simp add: signed_divide_int_def signed_modulo_int_def div_abs_eq mod_abs_eq algebra_simps)\n\nend\n\nlemma divide_int_eq_signed_divide_int:\n  \\<open>k div l = k sdiv l - 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: div_eq_div_abs [of k l] signed_divide_int_def)\n\nlemma signed_divide_int_eq_divide_int:\n  \\<open>k sdiv l = k div l + 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_eq_signed_divide_int)\n\nlemma modulo_int_eq_signed_modulo_int:\n  \\<open>k mod l = k smod l + l * of_bool (sgn k \\<noteq> sgn l \\<and> \\<not> l dvd k)\\<close>\n  for k l :: int\n  by (simp add: mod_eq_mod_abs [of k l] signed_modulo_int_def)\n\nlemma signed_modulo_int_eq_modulo_int:\n  \\<open>k smod l = k mod l - 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_eq_signed_modulo_int)\n\nlemma sdiv_int_div_0:\n  \"(x :: int) sdiv 0 = 0\"\n  by (clarsimp simp: signed_divide_int_def)\n\nlemma sdiv_int_0_div [simp]:\n  \"0 sdiv (x :: int) = 0\"\n  by (clarsimp simp: signed_divide_int_def)\n\nlemma smod_int_alt_def:\n     \"(a::int) smod b = sgn (a) * (abs a mod abs b)\"\n  by (fact signed_modulo_int_def)\n\nlemma int_sdiv_simps [simp]:\n    \"(a :: int) sdiv 1 = a\"\n    \"(a :: int) sdiv 0 = 0\"\n    \"(a :: int) sdiv -1 = -a\"\n  apply (auto simp: signed_divide_int_def sgn_if)\n  done\n\nlemma smod_int_mod_0 [simp]:\n  \"x smod (0 :: int) = x\"\n  by (clarsimp simp: signed_modulo_int_def abs_mult_sgn ac_simps)\n\nlemma smod_int_0_mod [simp]:\n  \"0 smod (x :: int) = 0\"\n  by (clarsimp simp: smod_int_alt_def)\n\nlemma sgn_sdiv_eq_sgn_mult:\n  \"a sdiv b \\<noteq> 0 \\<Longrightarrow> sgn ((a :: int) sdiv b) = sgn (a * b)\"\n  by (auto simp: signed_divide_int_def sgn_div_eq_sgn_mult sgn_mult)\n\nlemma int_sdiv_same_is_1 [simp]:\n    \"a \\<noteq> 0 \\<Longrightarrow> ((a :: int) sdiv b = a) = (b = 1)\"\n  apply (rule iffI)\n   apply (clarsimp simp: signed_divide_int_def)\n   apply (subgoal_tac \"b > 0\")\n    apply (case_tac \"a > 0\")\n     apply (clarsimp simp: sgn_if)\n  apply (simp_all add: not_less algebra_split_simps sgn_if split: if_splits)\n  using int_div_less_self [of a b] apply linarith\n    apply (metis add.commute add.inverse_inverse group_cancel.rule0 int_div_less_self linorder_neqE_linordered_idom neg_0_le_iff_le not_less verit_comp_simplify1(1) zless_imp_add1_zle)\n   apply (metis div_minus_right neg_imp_zdiv_neg_iff neg_le_0_iff_le not_less order.not_eq_order_implies_strict)\n  apply (metis abs_le_zero_iff abs_of_nonneg neg_imp_zdiv_nonneg_iff order.not_eq_order_implies_strict)\n  done\n\nlemma int_sdiv_negated_is_minus1 [simp]:\n    \"a \\<noteq> 0 \\<Longrightarrow> ((a :: int) sdiv b = - a) = (b = -1)\"\n  apply (clarsimp simp: signed_divide_int_def)\n  apply (rule iffI)\n   apply (subgoal_tac \"b < 0\")\n    apply (case_tac \"a > 0\")\n     apply (clarsimp simp: sgn_if algebra_split_simps not_less)\n     apply (case_tac \"sgn (a * b) = -1\")\n      apply (simp_all add: not_less algebra_split_simps sgn_if split: if_splits)\n     apply (metis add.inverse_inverse int_div_less_self int_one_le_iff_zero_less less_le neg_0_less_iff_less)\n    apply (metis add.inverse_inverse div_minus_right int_div_less_self int_one_le_iff_zero_less less_le neg_0_less_iff_less)\n   apply (metis less_le neg_less_0_iff_less not_less pos_imp_zdiv_neg_iff)\n  apply (metis div_minus_right dual_order.eq_iff neg_imp_zdiv_nonneg_iff neg_less_0_iff_less)\n  done\n\nlemma sdiv_int_range:\n  \\<open>a sdiv b \\<in> {- \\<bar>a\\<bar>..\\<bar>a\\<bar>}\\<close> for a b :: int\n  using zdiv_mono2 [of \\<open>\\<bar>a\\<bar>\\<close> 1 \\<open>\\<bar>b\\<bar>\\<close>]\n  by (cases \\<open>b = 0\\<close>; cases \\<open>sgn b = sgn a\\<close>)\n     (auto simp add: signed_divide_int_def pos_imp_zdiv_nonneg_iff\n     dest!: sgn_not_eq_imp intro: order_trans [of _ 0])\n\nlemma smod_int_range:\n  \\<open>a smod b \\<in> {- \\<bar>b\\<bar> + 1..\\<bar>b\\<bar> - 1}\\<close>\n  if \\<open>b \\<noteq> 0\\<close> for a b :: int\nproof -\n  define m n where \\<open>m = nat \\<bar>a\\<bar>\\<close> \\<open>n = nat \\<bar>b\\<bar>\\<close>\n  then have \\<open>\\<bar>a\\<bar> = int m\\<close> \\<open>\\<bar>b\\<bar> = int n\\<close>\n    by simp_all\n  with that have \\<open>n > 0\\<close>\n    by simp\n  with signed_modulo_int_def [of a b] \\<open>\\<bar>a\\<bar> = int m\\<close> \\<open>\\<bar>b\\<bar> = int n\\<close>\n  show ?thesis\n    by (auto simp add: sgn_if diff_le_eq int_one_le_iff_zero_less simp flip: of_nat_mod of_nat_diff)\nqed\n\nlemma smod_int_compares:\n   \"\\<lbrakk> 0 \\<le> a; 0 < b \\<rbrakk> \\<Longrightarrow> (a :: int) smod b < b\"\n   \"\\<lbrakk> 0 \\<le> a; 0 < b \\<rbrakk> \\<Longrightarrow> 0 \\<le> (a :: int) smod b\"\n   \"\\<lbrakk> a \\<le> 0; 0 < b \\<rbrakk> \\<Longrightarrow> -b < (a :: int) smod b\"\n   \"\\<lbrakk> a \\<le> 0; 0 < b \\<rbrakk> \\<Longrightarrow> (a :: int) smod b \\<le> 0\"\n   \"\\<lbrakk> 0 \\<le> a; b < 0 \\<rbrakk> \\<Longrightarrow> (a :: int) smod b < - b\"\n   \"\\<lbrakk> 0 \\<le> a; b < 0 \\<rbrakk> \\<Longrightarrow> 0 \\<le> (a :: int) smod b\"\n   \"\\<lbrakk> a \\<le> 0; b < 0 \\<rbrakk> \\<Longrightarrow> (a :: int) smod b \\<le> 0\"\n   \"\\<lbrakk> a \\<le> 0; b < 0 \\<rbrakk> \\<Longrightarrow> b \\<le> (a :: int) smod b\"\n  apply (insert smod_int_range [where a=a and b=b])\n  apply (auto simp: add1_zle_eq smod_int_alt_def sgn_if)\n  done\n\nlemma smod_mod_positive:\n    \"\\<lbrakk> 0 \\<le> (a :: int); 0 \\<le> b \\<rbrakk> \\<Longrightarrow> a smod b = a mod b\"\n  by (clarsimp simp: smod_int_alt_def zsgn_def)\n\nlemma minus_sdiv_eq [simp]:\n  \\<open>- k sdiv l = - (k sdiv l)\\<close> for k l :: int\n  by (simp add: signed_divide_int_def)\n\nlemma sdiv_minus_eq [simp]:\n  \\<open>k sdiv - l = - (k sdiv l)\\<close> for k l :: int\n  by (simp add: signed_divide_int_def)\n\nlemma sdiv_int_numeral_numeral [simp]:\n  \\<open>numeral m sdiv numeral n = numeral m div (numeral n :: int)\\<close>\n  by (simp add: signed_divide_int_def)\n\nlemma minus_smod_eq [simp]:\n  \\<open>- k smod l = - (k smod l)\\<close> for k l :: int\n  by (simp add: smod_int_alt_def)\n\nlemma smod_minus_eq [simp]:\n  \\<open>k smod - l = k smod l\\<close> for k l :: int\n  by (simp add: smod_int_alt_def)\n\nlemma smod_int_numeral_numeral [simp]:\n  \\<open>numeral m smod numeral n = numeral m mod (numeral n :: int)\\<close>\n  by (simp add: smod_int_alt_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/Library/Signed_Division.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240860523328, "lm_q2_score": 0.8615382147637196, "lm_q1q2_score": 0.7454236144680977}}
{"text": "(*  Title:      HOL/HOLCF/Cont.thy\n    Author:     Franz Regensburger\n    Author:     Brian Huffman\n*)\n\nsection {* Continuity and monotonicity *}\n\ntheory Cont\nimports Pcpo\nbegin\n\ntext {*\n   Now we change the default class! Form now on all untyped type variables are\n   of default class po\n*}\n\ndefault_sort po\n\nsubsection {* Definitions *}\n\ndefinition\n  monofun :: \"('a \\<Rightarrow> 'b) \\<Rightarrow> bool\"  -- \"monotonicity\"  where\n  \"monofun f = (\\<forall>x y. x \\<sqsubseteq> y \\<longrightarrow> f x \\<sqsubseteq> f y)\"\n\ndefinition\n  cont :: \"('a::cpo \\<Rightarrow> 'b::cpo) \\<Rightarrow> bool\"\nwhere\n  \"cont f = (\\<forall>Y. chain Y \\<longrightarrow> range (\\<lambda>i. f (Y i)) <<| f (\\<Squnion>i. Y i))\"\n\nlemma contI:\n  \"\\<lbrakk>\\<And>Y. chain Y \\<Longrightarrow> range (\\<lambda>i. f (Y i)) <<| f (\\<Squnion>i. Y i)\\<rbrakk> \\<Longrightarrow> cont f\"\nby (simp add: cont_def)\n\nlemma contE:\n  \"\\<lbrakk>cont f; chain Y\\<rbrakk> \\<Longrightarrow> range (\\<lambda>i. f (Y i)) <<| f (\\<Squnion>i. Y i)\"\nby (simp add: cont_def)\n\nlemma monofunI: \n  \"\\<lbrakk>\\<And>x y. x \\<sqsubseteq> y \\<Longrightarrow> f x \\<sqsubseteq> f y\\<rbrakk> \\<Longrightarrow> monofun f\"\nby (simp add: monofun_def)\n\nlemma monofunE: \n  \"\\<lbrakk>monofun f; x \\<sqsubseteq> y\\<rbrakk> \\<Longrightarrow> f x \\<sqsubseteq> f y\"\nby (simp add: monofun_def)\n\n\nsubsection {* Equivalence of alternate definition *}\n\ntext {* monotone functions map chains to chains *}\n\nlemma ch2ch_monofun: \"\\<lbrakk>monofun f; chain Y\\<rbrakk> \\<Longrightarrow> chain (\\<lambda>i. f (Y i))\"\napply (rule chainI)\napply (erule monofunE)\napply (erule chainE)\ndone\n\ntext {* monotone functions map upper bound to upper bounds *}\n\nlemma ub2ub_monofun: \n  \"\\<lbrakk>monofun f; range Y <| u\\<rbrakk> \\<Longrightarrow> range (\\<lambda>i. f (Y i)) <| f u\"\napply (rule ub_rangeI)\napply (erule monofunE)\napply (erule ub_rangeD)\ndone\n\ntext {* a lemma about binary chains *}\n\nlemma binchain_cont:\n  \"\\<lbrakk>cont f; x \\<sqsubseteq> y\\<rbrakk> \\<Longrightarrow> range (\\<lambda>i::nat. f (if i = 0 then x else y)) <<| f y\"\napply (subgoal_tac \"f (\\<Squnion>i::nat. if i = 0 then x else y) = f y\")\napply (erule subst)\napply (erule contE)\napply (erule bin_chain)\napply (rule_tac f=f in arg_cong)\napply (erule is_lub_bin_chain [THEN lub_eqI])\ndone\n\ntext {* continuity implies monotonicity *}\n\nlemma cont2mono: \"cont f \\<Longrightarrow> monofun f\"\napply (rule monofunI)\napply (drule (1) binchain_cont)\napply (drule_tac i=0 in is_lub_rangeD1)\napply simp\ndone\n\nlemmas cont2monofunE = cont2mono [THEN monofunE]\n\nlemmas ch2ch_cont = cont2mono [THEN ch2ch_monofun]\n\ntext {* continuity implies preservation of lubs *}\n\nlemma cont2contlubE:\n  \"\\<lbrakk>cont f; chain Y\\<rbrakk> \\<Longrightarrow> f (\\<Squnion> i. Y i) = (\\<Squnion> i. f (Y i))\"\napply (rule lub_eqI [symmetric])\napply (erule (1) contE)\ndone\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>\n     \\<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\nsubsection {* Collection of continuity rules *}\n\nnamed_theorems cont2cont \"continuity intro rule\"\n\n\nsubsection {* Continuity of basic functions *}\n\ntext {* The identity function is continuous *}\n\nlemma cont_id [simp, cont2cont]: \"cont (\\<lambda>x. x)\"\napply (rule contI)\napply (erule cpo_lubI)\ndone\n\ntext {* constant functions are continuous *}\n\nlemma cont_const [simp, cont2cont]: \"cont (\\<lambda>x. c)\"\n  using is_lub_const by (rule contI)\n\ntext {* application of functions is continuous *}\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\" 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\" 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:\n  \"\\<lbrakk>cont c; cont (\\<lambda>x. f x)\\<rbrakk> \\<Longrightarrow> cont (\\<lambda>x. c (f x))\"\nby (rule cont_apply [OF _ _ cont_const])\n\ntext {* Least upper bounds preserve continuity *}\n\nlemma cont2cont_lub [simp]:\n  assumes chain: \"\\<And>x. chain (\\<lambda>i. F i x)\" and cont: \"\\<And>i. cont (\\<lambda>x. F i x)\"\n  shows \"cont (\\<lambda>x. \\<Squnion>i. F i x)\"\napply (rule contI2)\napply (simp add: monofunI cont2monofunE [OF cont] lub_mono chain)\napply (simp add: cont2contlubE [OF cont])\napply (simp add: diag_lub ch2ch_cont [OF cont] chain)\ndone\n\ntext {* if-then-else is continuous *}\n\nlemma cont_if [simp, cont2cont]:\n  \"\\<lbrakk>cont f; cont g\\<rbrakk> \\<Longrightarrow> cont (\\<lambda>x. if b then f x else g x)\"\nby (induct b) simp_all\n\nsubsection {* Finite chains and flat pcpos *}\n\ntext {* Monotone functions map finite chains to finite chains. *}\n\nlemma monofun_finch2finch:\n  \"\\<lbrakk>monofun f; finite_chain Y\\<rbrakk> \\<Longrightarrow> finite_chain (\\<lambda>n. f (Y n))\"\napply (unfold finite_chain_def)\napply (simp add: ch2ch_monofun)\napply (force simp add: max_in_chain_def)\ndone\n\ntext {* The same holds for continuous functions. *}\n\nlemma cont_finch2finch:\n  \"\\<lbrakk>cont f; finite_chain Y\\<rbrakk> \\<Longrightarrow> finite_chain (\\<lambda>n. f (Y n))\"\nby (rule cont2mono [THEN monofun_finch2finch])\n\ntext {* All monotone functions with chain-finite domain are continuous. *}\n\nlemma chfindom_monofun2cont: \"monofun f \\<Longrightarrow> cont (f::'a::chfin \\<Rightarrow> 'b::cpo)\"\napply (erule contI2)\napply (frule chfin2finch)\napply (clarsimp simp add: finite_chain_def)\napply (subgoal_tac \"max_in_chain i (\\<lambda>i. f (Y i))\")\napply (simp add: maxinch_is_thelub ch2ch_monofun)\napply (force simp add: max_in_chain_def)\ndone\n\ntext {* All strict functions with flat domain are continuous. *}\n\nlemma flatdom_strict2mono: \"f \\<bottom> = \\<bottom> \\<Longrightarrow> monofun (f::'a::flat \\<Rightarrow> 'b::pcpo)\"\napply (rule monofunI)\napply (drule ax_flat)\napply auto\ndone\n\nlemma flatdom_strict2cont: \"f \\<bottom> = \\<bottom> \\<Longrightarrow> cont (f::'a::flat \\<Rightarrow> 'b::pcpo)\"\nby (rule flatdom_strict2mono [THEN chfindom_monofun2cont])\n\ntext {* All functions with discrete domain are continuous. *}\n\nlemma cont_discrete_cpo [simp, cont2cont]: \"cont (f::'a::discrete_cpo \\<Rightarrow> 'b::cpo)\"\napply (rule contI)\napply (drule discrete_chain_const, clarify)\napply (simp add: is_lub_const)\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/HOLCF/Cont.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8615382165412809, "lm_q2_score": 0.8652240825770432, "lm_q1q2_score": 0.7454236130119918}}
{"text": "(*\n    Original Author of Riddle: Tjark Weber\n    Updates and additions by Jacques Fleuriot\n*)\n\ntheory tut4 imports Main begin \n\nsection\\<open>Exercise 1\\<close>\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\nsection\\<open>Exercise 2\\<close>\n\ntext\\<open>A Riddle: Rich Grandfather\\<close> \n\ntext\\<open>\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\"\\<close> \n\n\ntext\\<open>\n\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\\<close>\n\ntext\\<open>Now prove the formula in Isabelle using a sequence of rule applications (i.e.\\\n  only using the methods rule, erule and assumption).\\<close> \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\\<open>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\\<close>\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\\<open>Here is a proof in Isar that resembles the informal reasoning above:\\<close> \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\\<open>An slightly modified proof of the above, with a named assumption right from the beginning:\\<close> \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\nsection\\<open>Exercise 3\\<close>\n\nlocale Geom =\n  fixes on :: \"'point \\<Rightarrow> 'line \\<Rightarrow> bool\"\n  assumes line_on_two_pts: \"a \\<noteq> b  \\<Longrightarrow> (\\<exists>l. on a l \\<and> on b l)\" \n  and line_on_two_pts_unique: \n           \"\\<lbrakk> a \\<noteq> b; on a l; on b l; on a m; on b m \\<rbrakk> \\<Longrightarrow> l = m\"\n  and two_points_on_line: \"\\<exists>a b. a \\<noteq> b \\<and> on a l \\<and> on b l\"\n  and three_points_not_on_line: \"\\<exists>a b c. a \\<noteq> b \\<and> a \\<noteq> c \\<and> b \\<noteq> c \\<and> \n                                    \\<not> (\\<exists>l. on a l \\<and> on b l \\<and> on c l)\"\nbegin\n\ntext\\<open>Not all points lie on the same line.\\<close>\n\n(* One possible structured proof *)\n\nlemma exists_pt_not_on_line: \"\\<exists>x. \\<not> on x l\"\nproof -\n   obtain a b c where l3: \"\\<not> (on a l \\<and> on b l \\<and> on c l)\" using three_points_not_on_line by blast \n   thus ?thesis by blast \n qed\n\ntext\\<open>There exist at least two lines through each point.\\<close>\n\nlemma two_lines_through_each_point: \"\\<exists>l m. on x l \\<and> on x m \\<and> l \\<noteq> m\"\nproof -\n  have \"\\<exists>z. z \\<noteq> x\" \n  proof (rule ccontr)\n    from two_points_on_line obtain a b where ab: \"(a::'point) \\<noteq> b\" by blast\n    assume \"\\<nexists>z. z \\<noteq> x\" then have univ: \"\\<forall>z. z = x\" by blast\n    then have \"a = x\" \"b = x\" by auto\n    then show False using ab by simp\n  qed\n  then obtain z where \"z \\<noteq> x\" by blast\n  then obtain l where xl: \"on x l\" and zl: \"on z l\" using line_on_two_pts by blast \n  obtain w where n_wl: \"\\<not> on w l\" using exists_pt_not_on_line by blast\n  obtain m where wm: \"on x m\" and zm: \"on w m\" using line_on_two_pts xl by force\n  then have \"l \\<noteq> m\" using n_wl by blast  \n  thus ?thesis using wm xl by blast \nqed\n\n(* Alternative proof of the above that uses metis *)\nlemma two_lines_through_each_point2: \"\\<exists>l m. on x l \\<and> on x m \\<and> l \\<noteq> m\"\nproof -\n  obtain z where \"z \\<noteq> x\" using two_points_on_line by metis \n  then obtain l where xl: \"on x l\" and zl: \"on z l\" using line_on_two_pts by blast \n  obtain w where n_wl: \"\\<not> on w l\" using exists_pt_not_on_line by blast\n  obtain m where wm: \"on x m\" and zm: \"on w m\" using line_on_two_pts xl by force\n  then have \"l \\<noteq> m\" using n_wl by blast  \n  thus ?thesis using wm xl by blast \nqed\n\ntext\\<open>Two lines cannot intersect in more than one point.\\<close>\n\nlemma two_lines_unique_intersect_pt: \n   assumes lm: \"l \\<noteq> m\" and \"on x l\" and \"on x m\" and \"on y l\" and \"on y m\" shows \"x = y\"\nproof (rule ccontr)\n   assume \"x \\<noteq> y\" then have \"l = m\" using line_on_two_pts_unique assms by simp\n   thus \"False\" using lm by simp\nqed\n\nend \n", "meta": {"author": "davemalvin", "repo": "Automated-Reasoning", "sha": "0c3b743e94d0efe39e41049826f63310d6bfc5f4", "save_path": "github-repos/isabelle/davemalvin-Automated-Reasoning", "path": "github-repos/isabelle/davemalvin-Automated-Reasoning/Automated-Reasoning-0c3b743e94d0efe39e41049826f63310d6bfc5f4/Tutorial/Tutorial4-Soln.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382200964034, "lm_q2_score": 0.8652240773641087, "lm_q1q2_score": 0.745423611596827}}
{"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\n  imports MainRLT\n  abbrevs PiE = \"Pi\\<^sub>E\"\n    and PIE = \"\\<Pi>\\<^sub>E\"\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 \"\\<rightarrow>\" 60)\n  where \"A \\<rightarrow> B \\<equiv> Pi A (\\<lambda>_. B)\"\n\nsyntax\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>\\<open>Pi\\<close>\\<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 funcset_to_empty_iff: \"A \\<rightarrow> {} = (if A={} then UNIV else {})\"\n  by auto\n\nlemma Pi_eq_empty[simp]: \"(\\<Pi> x \\<in> A. B x) = {} \\<longleftrightarrow> (\\<exists>x\\<in>A. B x = {})\"\nproof -\n  have \"\\<exists>x\\<in>A. B x = {}\" if \"\\<And>f. \\<exists>y. y \\<in> A \\<and> f y \\<notin> B y\"\n    using that [of \"\\<lambda>u. SOME y. y \\<in> B u\"] some_in_eq by blast\n  then show ?thesis\n    by force\nqed\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: \"f i \\<in> A (n i) i\" if \"i \\<in> I\" for i\n    by auto\n  obtain k where k: \"n i \\<le> k\" if \"i \\<in> I\" for i\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 (metis PiE fun_upd_apply)\n  by force\n\n\nsubsection \\<open>Composition With a Restricted Domain: \\<^term>\\<open>compose\\<close>\\<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  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>\\<open>restrict\\<close>\\<close>\n\nlemma restrict_cong: \"I = J \\<Longrightarrow> (\\<And>i. i \\<in> J =simp=> f i = g i) \\<Longrightarrow> restrict f I = restrict g J\"\n  by (auto simp: restrict_def fun_eq_iff simp_implies_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\nlemma sum_restrict' [simp]: \"sum' (\\<lambda>i\\<in>I. g i) I = sum' (\\<lambda>i. g i) I\"\n  by (simp add: sum.G_def conj_commute cong: conj_cong)\n\nlemma prod_restrict' [simp]: \"prod' (\\<lambda>i\\<in>I. g i) I = prod' (\\<lambda>i. g i) I\"\n  by (simp add: prod.G_def conj_commute cong: conj_cong)\n\n\nsubsection \\<open>Bijections Between Sets\\<close>\n\ntext \\<open>The definition of \\<^const>\\<open>bij_betw\\<close> is in \\<open>Fun.thy\\<close>, but most of\nthe theorems belong here, or need at least \\<^term>\\<open>Hilbert_Choice\\<close>.\\<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\"  (\"(3\\<Pi>\\<^sub>E _\\<in>_./ _)\" 10)\ntranslations\n  \"\\<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 \"\\<rightarrow>\\<^sub>E\" 60)\n  where \"A \\<rightarrow>\\<^sub>E B \\<equiv> (\\<Pi>\\<^sub>E i\\<in>A. B)\"\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]: \"Pi\\<^sub>E {} T = {\\<lambda>x. undefined}\"\n  unfolding PiE_def by simp\n\nlemma PiE_UNIV_domain: \"Pi\\<^sub>E 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> Pi\\<^sub>E 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> Pi\\<^sub>E 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> Pi\\<^sub>E S T \\<Longrightarrow> f(x := y) \\<in> Pi\\<^sub>E (insert x S) T\"\n  unfolding PiE_def extensional_def by auto\n\nlemma fun_upd_in_PiE: \"x \\<notin> S \\<Longrightarrow> f \\<in> Pi\\<^sub>E (insert x S) T \\<Longrightarrow> f(x := undefined) \\<in> Pi\\<^sub>E S T\"\n  unfolding PiE_def extensional_def by auto\n\nlemma PiE_insert_eq: \"Pi\\<^sub>E (insert x S) T = (\\<lambda>(y, g). g(x := y)) ` (T x \\<times> Pi\\<^sub>E S T)\"\nproof -\n  {\n    fix f assume \"f \\<in> Pi\\<^sub>E (insert x S) T\" \"x \\<notin> S\"\n    then have \"f \\<in> (\\<lambda>(y, g). g(x := y)) ` (T x \\<times> Pi\\<^sub>E S T)\"\n      by (auto intro!: image_eqI[where x=\"(f x, f(x := undefined))\"] intro: fun_upd_in_PiE PiE_mem)\n  }\n  moreover\n  {\n    fix f assume \"f \\<in> Pi\\<^sub>E (insert x S) T\" \"x \\<in> S\"\n    then have \"f \\<in> (\\<lambda>(y, g). g(x := y)) ` (T x \\<times> Pi\\<^sub>E S T)\"\n      by (auto intro!: image_eqI[where x=\"(f x, f)\"] intro: fun_upd_in_PiE PiE_mem simp: insert_absorb)\n  }\n  ultimately show ?thesis\n    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> Pi\\<^sub>E 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> Pi\\<^sub>E 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> Pi\\<^sub>E A B \\<subseteq> Pi\\<^sub>E A C\"\n  by auto\n\nlemma PiE_iff: \"f \\<in> Pi\\<^sub>E 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 restrict_PiE_iff: \"restrict f I \\<in> Pi\\<^sub>E I X \\<longleftrightarrow> (\\<forall>i \\<in> I. f i \\<in> X i)\"\n  by (simp add: PiE_iff)\n\nlemma ext_funcset_to_sing_iff [simp]: \"A \\<rightarrow>\\<^sub>E {a} = {\\<lambda>x\\<in>A. a}\"\n  by (auto simp: PiE_def Pi_iff extensionalityI)\n\nlemma PiE_restrict[simp]:  \"f \\<in> Pi\\<^sub>E A B \\<Longrightarrow> restrict f A = f\"\n  by (simp add: extensional_restrict PiE_def)\n\nlemma restrict_PiE[simp]: \"restrict f I \\<in> Pi\\<^sub>E 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  by (auto split: if_split_asm)\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\nlemma subset_PiE:\n   \"PiE I S \\<subseteq> PiE I T \\<longleftrightarrow> PiE I S = {} \\<or> (\\<forall>i \\<in> I. S i \\<subseteq> T i)\" (is \"?lhs \\<longleftrightarrow> _ \\<or> ?rhs\")\nproof (cases \"PiE I S = {}\")\n  case False\n  moreover have \"?lhs = ?rhs\"\n  proof\n    assume L: ?lhs\n    have \"\\<And>i. i\\<in>I \\<Longrightarrow> S i \\<noteq> {}\"\n      using False PiE_eq_empty_iff by blast\n    with L show ?rhs\n      by (simp add: PiE_Int PiE_eq_iff inf.absorb_iff2)\n  qed auto\n  ultimately show ?thesis\n    by simp\nqed simp\n\nlemma PiE_eq:\n   \"PiE I S = PiE I T \\<longleftrightarrow> PiE I S = {} \\<and> PiE I T = {} \\<or> (\\<forall>i \\<in> I. S i = T i)\"\n  by (auto simp: PiE_eq_iff PiE_eq_empty_iff)\n\nlemma PiE_UNIV [simp]: \"PiE UNIV (\\<lambda>i. UNIV) = UNIV\"\n  by blast\n\nlemma image_projection_PiE:\n  \"(\\<lambda>f. f i) ` (PiE I S) = (if PiE I S = {} then {} else if i \\<in> I then S i else {undefined})\"\nproof -\n  have \"(\\<lambda>f. f i) ` Pi\\<^sub>E I S = S i\" if \"i \\<in> I\" \"f \\<in> PiE I S\" for f\n    using that apply auto\n    by (rule_tac x=\"(\\<lambda>k. if k=i then x else f k)\" in image_eqI) auto\n  moreover have \"(\\<lambda>f. f i) ` Pi\\<^sub>E I S = {undefined}\" if \"f \\<in> PiE I S\" \"i \\<notin> I\" for f\n    using that by (blast intro: PiE_arb [OF that, symmetric])\n  ultimately show ?thesis\n    by auto\nqed\n\nlemma PiE_singleton:\n  assumes \"f \\<in> extensional A\"\n  shows   \"PiE A (\\<lambda>x. {f x}) = {f}\"\nproof -\n  {\n    fix g assume \"g \\<in> PiE A (\\<lambda>x. {f x})\"\n    hence \"g x = f x\" for x\n      using assms by (cases \"x \\<in> A\") (auto simp: extensional_def)\n    hence \"g = f\" by (simp add: fun_eq_iff)\n  }\n  thus ?thesis using assms by (auto simp: extensional_def)\nqed\n\nlemma PiE_eq_singleton: \"(\\<Pi>\\<^sub>E i\\<in>I. S i) = {\\<lambda>i\\<in>I. f i} \\<longleftrightarrow> (\\<forall>i\\<in>I. S i = {f i})\"\n  by (metis (mono_tags, lifting) PiE_eq PiE_singleton insert_not_empty restrict_apply' restrict_extensional)\n\nlemma PiE_over_singleton_iff: \"(\\<Pi>\\<^sub>E x\\<in>{a}. B x) = (\\<Union>b \\<in> B a. {\\<lambda>x \\<in> {a}. b})\"\n  apply (auto simp: PiE_iff split: if_split_asm)\n  apply (metis (no_types, lifting) extensionalityI restrict_apply' restrict_extensional singletonD)\n  done\n\nlemma all_PiE_elements:\n   \"(\\<forall>z \\<in> PiE I S. \\<forall>i \\<in> I. P i (z i)) \\<longleftrightarrow> PiE I S = {} \\<or> (\\<forall>i \\<in> I. \\<forall>x \\<in> S i. P i x)\" (is \"?lhs = ?rhs\")\nproof (cases \"PiE I S = {}\")\n  case False\n  then obtain f where f: \"\\<And>i. i \\<in> I \\<Longrightarrow> f i \\<in> S i\"\n    by fastforce\n  show ?thesis\n  proof\n    assume L: ?lhs\n    have \"P i x\"\n      if \"i \\<in> I\" \"x \\<in> S i\" for i x\n    proof -\n      have \"(\\<lambda>j \\<in> I. if j=i then x else f j) \\<in> PiE I S\"\n        by (simp add: f that(2))\n      then have \"P i ((\\<lambda>j \\<in> I. if j=i then x else f j) i)\"\n        using L that(1) by blast\n      with that show ?thesis\n        by simp\n    qed\n    then show ?rhs\n      by (simp add: False)\n  qed fastforce\nqed simp\n\nlemma PiE_ext: \"\\<lbrakk>x \\<in> PiE k s; y \\<in> PiE k s; \\<And>i. i \\<in> k \\<Longrightarrow> x i = y i\\<rbrakk> \\<Longrightarrow> x = y\"\n  by (metis ext PiE_E)\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: if_split_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>Misc properties of functions, composition and restriction from HOL Light\\<close>\n\nlemma function_factors_left_gen:\n  \"(\\<forall>x y. P x \\<and> P y \\<and> g x = g y \\<longrightarrow> f x = f y) \\<longleftrightarrow> (\\<exists>h. \\<forall>x. P x \\<longrightarrow> f x = h(g x))\"\n  (is \"?lhs = ?rhs\")\nproof\n  assume L: ?lhs\n  then show ?rhs\n    apply (rule_tac x=\"f \\<circ> inv_into (Collect P) g\" in exI)\n    unfolding o_def\n    by (metis (mono_tags, opaque_lifting) f_inv_into_f imageI inv_into_into mem_Collect_eq)\nqed auto\n\nlemma function_factors_left:\n  \"(\\<forall>x y. (g x = g y) \\<longrightarrow> (f x = f y)) \\<longleftrightarrow> (\\<exists>h. f = h \\<circ> g)\"\n  using function_factors_left_gen [of \"\\<lambda>x. True\" g f] unfolding o_def by blast\n\nlemma function_factors_right_gen:\n  \"(\\<forall>x. P x \\<longrightarrow> (\\<exists>y. g y = f x)) \\<longleftrightarrow> (\\<exists>h. \\<forall>x. P x \\<longrightarrow> f x = g(h x))\"\n  by metis\n\nlemma function_factors_right:\n  \"(\\<forall>x. \\<exists>y. g y = f x) \\<longleftrightarrow> (\\<exists>h. f = g \\<circ> h)\"\n  unfolding o_def by metis\n\nlemma restrict_compose_right:\n   \"restrict (g \\<circ> restrict f S) S = restrict (g \\<circ> f) S\"\n  by auto\n\nlemma restrict_compose_left:\n   \"f ` S \\<subseteq> T \\<Longrightarrow> restrict (restrict g T \\<circ> f) S = restrict (g \\<circ> f) S\"\n  by fastforce\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: if_split_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\nsubsection \\<open>The pigeonhole principle\\<close>\n\ntext \\<open>\n  An alternative formulation of this is that for a function mapping a finite set \\<open>A\\<close> of\n  cardinality \\<open>m\\<close> to a finite set \\<open>B\\<close> of cardinality \\<open>n\\<close>, there exists an element \\<open>y \\<in> B\\<close> that\n  is hit at least $\\lceil \\frac{m}{n}\\rceil$ times. However, since we do not have real numbers\n  or rounding yet, we state it in the following equivalent form:\n\\<close>\nlemma pigeonhole_card:\n  assumes \"f \\<in> A \\<rightarrow> B\" \"finite A\" \"finite B\" \"B \\<noteq> {}\"\n  shows   \"\\<exists>y\\<in>B. card (f -` {y} \\<inter> A) * card B \\<ge> card A\"\nproof -\n  from assms have \"card B > 0\"\n    by auto\n  define M where \"M = Max ((\\<lambda>y. card (f -` {y} \\<inter> A)) ` B)\"\n  have \"A = (\\<Union>y\\<in>B. f -` {y} \\<inter> A)\"\n    using assms by auto\n  also have \"card \\<dots> = (\\<Sum>i\\<in>B. card (f -` {i} \\<inter> A))\"\n    using assms by (subst card_UN_disjoint) auto\n  also have \"\\<dots> \\<le> (\\<Sum>i\\<in>B. M)\"\n    unfolding M_def using assms by (intro sum_mono Max.coboundedI) auto\n  also have \"\\<dots> = card B * M\"\n    by simp\n  finally have \"M * card B \\<ge> card A\"\n    by (simp add: mult_ac)\n  moreover have \"M \\<in> (\\<lambda>y. card (f -` {y} \\<inter> A)) ` B\"\n    unfolding M_def using assms \\<open>B \\<noteq> {}\\<close> by (intro Max_in) auto\n  ultimately show ?thesis\n    by blast\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/FuncSet.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8652240895276223, "lm_q2_score": 0.8615382076534742, "lm_q1q2_score": 0.7454236113102368}}
{"text": "theory E3_1\n  imports Main\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 v r) = (set l) \\<union> {v} \\<union> (set r)\"\n\nfun ord :: \"int tree \\<Rightarrow> bool\" where\n  \"ord Tip = True\" |\n  \"ord (Node Tip v Tip) = True\" |\n  \"ord (Node (Node ll lv lr) v Tip) = ((lv < v) \\<and> (ord (Node ll lv lr)))\" |\n  \"ord (Node Tip v (Node rl rv rr)) = ((v < rv) \\<and> (ord (Node rl rv rr)))\" |\n  \"ord (Node (Node ll lv lr) v (Node rl rv rr)) = ((lv < v) \\<and> (v < rv) \\<and> (ord (Node ll lv lr)) \\<and> (ord (Node rl rv rr)))\"\n\nfun ins :: \"int tree \\<Rightarrow> int \\<Rightarrow> int tree\" where\n  \"ins Tip x = Node Tip x Tip\" |\n  \"ins (Node l v r) x = (if x = v then (Node l v r) else (if v < x then (Node l v (ins r x)) else (Node (ins l x) v r)))\"\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 rule: ord.induct)\n  apply(auto)\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/chapter3/E3_1.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.92522995296862, "lm_q2_score": 0.8056321866478979, "lm_q1q2_score": 0.7453950301622411}}
{"text": "(*\n  File:     PAPP_Impossibility_Base_Case.thy\n  Author:   Manuel Eberl, University of Innsbruck \n*)\nsection \\<open>The Base Case of the Impossibility\\<close>\ntheory PAPP_Impossibility_Base_Case\n  imports Anonymous_PAPP SAT_Replay\nbegin\n\ntext \\<open>\n  In this section, we will prove the base case of our P-APP impossibility result, namely that\n  there exists no anonymous P-APP rule \\<open>f\\<close> for 6 voters, 4 parties, and committee size 3 that\n  satisfies Weak Representation and Cardinality Strategyproofness.\n\n  The proof works by looking at some (comparatively small) set of preference profiles and the\n  set of all 20 possible output committees. Each proposition $f(A) = C$ (where \\<open>A\\<close> is a profile\n  from our set and \\<open>C\\<close> is one of the 20 possible output committees) is considered as a Boolean\n  variable.\n\n  All the conditions arising on these variables based on the fact that \\<open>f\\<close> is a function\n  and the additional properties (Representation, Strategyproofness) are encoded as SAT clauses.\n  This SAT problem is then proven unsatisfiable by an external SAT solver and the resulting\n  proof re-imported into Isabelle/HOL.\n\\<close>\n\nsubsection \\<open>Auxiliary Material\\<close>\n\ntext \\<open>\n  We define the set of committees of the given size \\<open>k\\<close> for a given set of parties \\<open>P\\<close>.\n\\<close>\ndefinition committees :: \"nat \\<Rightarrow> 'a set \\<Rightarrow> 'a multiset set\" where\n  \"committees k P = {W. set_mset W \\<subseteq> P \\<and> size W = k}\"\n\ntext \\<open>\n  We now prove a recurrence for this set so that we can more easily compute the set of all\n  possible committees:\n\\<close>\nlemma committees_0 [simp]: \"committees 0 P = {{#}}\"\n  by (auto simp: committees_def)\n\nlemma committees_Suc:\n  \"committees (Suc n) P = (\\<Union>x\\<in>P. \\<Union>W\\<in>committees n P. {{#x#} + W})\"\nproof safe\n  fix C assume C: \"C \\<in> committees (Suc n) P\"\n  hence \"size C = Suc n\"\n    by (auto simp: committees_def)\n  hence \"C \\<noteq> {#}\"\n    by auto\n  then obtain x where x: \"x \\<in># C\"\n    by auto\n  define C' where \"C' = C - {#x#}\"\n  have \"C = {#x#} + C'\" \"x \\<in> P\" \"C' \\<in> committees n P\"\n    using C x  by (auto simp: committees_def C'_def size_Diff_singleton dest: in_diffD)\n  thus \"C \\<in> (\\<Union>x\\<in>P. \\<Union>W\\<in>committees n P. {{#x#} + W})\"\n    by blast\nqed (auto simp: committees_def)\n\ntext \\<open>\n  The following function takes a list $[a_1, \\ldots, a_n]$ and computes the list of all pairs\n  of the form $(a_i, a_j)$ with $i < j$:\n\\<close>\nfun pairs :: \"'a list \\<Rightarrow> ('a \\<times> 'a) list\" where\n  \"pairs [] = []\"\n| \"pairs (x # xs) = map (\\<lambda>y. (x, y)) xs @ pairs xs\"\n\nlemma distinct_conv_pairs: \"distinct xs \\<longleftrightarrow> list_all (\\<lambda>(x,y). x \\<noteq> y) (pairs xs)\"\n  by (induction xs) (auto simp: list_all_iff)\n\nlemma list_ex_unfold: \"list_ex P (x # y # xs) \\<longleftrightarrow> P x \\<or> list_ex P (y # xs)\" \"list_ex P [x] \\<longleftrightarrow> P x\"\n  by simp_all\n\nlemma list_all_unfold: \"list_all P (x # y # xs) \\<longleftrightarrow> P x \\<and> list_all P (y # xs)\" \"list_all P [x] \\<longleftrightarrow> P x\"\n  by simp_all\n\n\nsubsection \\<open>Setup for the Base Case\\<close>\n\ntext \\<open>\n  We define a locale for an anonymous P-APP rule for 6 voters, 4 parties, and committee size 3\n  that satisfies weak representation and cardinality strategyproofness. Our goal is to prove\n  the theorem \\<^term>\\<open>False\\<close> inside this locale.\n\\<close>\n\nlocale papp_impossibility_base_case =\n  card_stratproof_weak_rep_anon_papp 6 parties 3 r\n  for parties :: \"'a set\" and r +\n  assumes card_parties: \"card parties = 4\"\nbegin\n\ntext \\<open>\n  A slightly more convenient version of Weak Representation:\n\\<close>\nlemma weak_representation':\n  assumes \"is_pref_profile A\" \"A' \\<equiv> A\" \"\\<forall>z\\<in>Z. count A {z} \\<ge> 2\" \"\\<not>Z \\<subseteq> set_mset W\"\n  shows   \"r A' \\<noteq> W\"\n  using weak_representation[OF assms(1)] assms(2-4) by auto\n\ntext \\<open>\n  The following lemma (Lemma~2 in the appendix of the paper) is a strengthening of Weak\n  Representation and Strategyproofness in our concrete setting:\n\n  Let \\<open>A\\<close> be a preference profile containing approval lists \\<open>X\\<close> and\n  let \\<open>Z\\<close> be a set of parties such that each element of \\<open>Z\\<close> is uniquely approved by at least two\n  voters in \\<open>A\\<close>. Due to Weak Representation, at least \\<open>|X \\<inter> Z|\\<close> members of the committee are then\n  approved by \\<open>X\\<close>.\n\n  What the lemma now says is that if there exists another voter with approval list \\<open>Y \\<subseteq> X\\<close> and\n  $Y \\nsubseteq Z$, then there is an additional committee member that is approved by \\<open>X\\<close>.\n\n  This lemma will be used both in our symmetry-breaking argument and as a means to add more\n  clauses to the SAT instance. Since these clauses are logical consequences of Strategyproofness\n  and Weak Representation, they are technically redundant -- but their presence allows us to\n  use consider a smaller set of profiles and still get a contradiction. Without using the lemma,\n  we would need to feed more profiles to the SAT solver to obtain the same information.\n\\<close>\nlemma lemma2:\n  assumes A: \"is_pref_profile A\"\n  assumes \"X \\<in># A\" and \"Y \\<in># A - {#X#}\" and \"Y \\<subseteq> X\" and \"\\<not>Y \\<subseteq> Z\"\n  assumes Z: \"\\<forall>z\\<in>Z. count A {z} \\<ge> 2\"\n  shows   \"size (filter_mset (\\<lambda>x. x \\<in> X) (r A)) > card (X \\<inter> Z)\"\nproof (rule ccontr)\n  text \\<open>\n    For the sake of contradiction, suppose the number of elements approved by \\<open>X\\<close> were\n    no larger than \\<open>|X \\<inter> Z|\\<close>.\n  \\<close>\n  assume \"\\<not>size (filter_mset (\\<lambda>x. x \\<in> X) (r A)) > card (X \\<inter> Z)\"\n  hence le: \"size (filter_mset (\\<lambda>x. x \\<in> X) (r A)) \\<le> card (X \\<inter> Z)\"\n    by linarith\n  interpret anon_papp_profile 6 parties 3 A\n    by fact\n  have \"Z \\<subseteq> parties\"\n    using assms(1,6) by (meson is_committee_def order.trans rule_wf weak_representation')\n  have [simp]: \"finite Z\"\n    by (rule finite_subset[OF _ finite_parties]) fact\n\n  text \\<open>\n    Due to Weak Representation, each member of \\<open>X \\<inter> Z\\<close> must be chosen at least once. But due\n    to the above, it cannot be chosen more than once. So it has to be chosen exactly once.\n  \\<close>\n  have X_approved_A_eq: \"filter_mset (\\<lambda>x. x \\<in> X) (r A) = mset_set (X \\<inter> Z)\"\n  proof -\n    have \"mset_set Z \\<subseteq># r A\"\n      using Z weak_representation[OF A] by (subst mset_set_subset_iff) auto\n    hence \"size (filter_mset (\\<lambda>x. x \\<in> X) (mset_set Z)) \\<le> size (filter_mset (\\<lambda>x. x \\<in> X) (r A))\"\n      by (intro size_mset_mono multiset_filter_mono)\n    also have \"filter_mset (\\<lambda>x. x \\<in> X) (mset_set Z) = mset_set {x\\<in>Z. x \\<in> X}\"\n      by simp\n    also have \"{x\\<in>Z. x \\<in> X} = X \\<inter> Z\"\n      by auto\n    also have \"size (mset_set (X \\<inter> Z)) = card (X \\<inter> Z)\"\n      by simp\n    finally have \"size (filter_mset (\\<lambda>x. x \\<in> X) (r A)) = card (X \\<inter> Z)\"\n      using le by linarith\n    moreover have \"mset_set (X \\<inter> Z) \\<subseteq># filter_mset (\\<lambda>x. x \\<in> X) (r A)\"\n      using Z weak_representation[OF A] by (subst mset_set_subset_iff) auto\n    ultimately show \"filter_mset (\\<lambda>x. x \\<in> X) (r A) = mset_set (X \\<inter> Z)\"\n      by (intro mset_subset_size_ge_imp_eq [symmetric]) auto\n  qed\n\n  have count_eq_1: \"count (r A) x = 1\" if \"x \\<in> X \\<inter> Z\" for x\n    using that X_approved_A_eq\n    by (metis \\<open>finite Z\\<close> count_filter_mset count_mset_set' diff_is_0_eq diff_zero \n              finite_subset inf_le2 not_one_le_zero)\n\n  text \\<open>\n    Let \\<open>x\\<close> be some element of \\<open>Y\\<close> that is not in \\<open>Z\\<close>.\n  \\<close>\n  obtain x where x: \"x \\<in> Y - Z\"\n    using \\<open>\\<not>Y \\<subseteq> Z\\<close> by blast\n  with assms have x': \"x \\<in> X - Z\"\n    by auto\n  have [simp]: \"x \\<in> parties\"\n    using A_subset assms(2) x' by blast\n\n  text \\<open>\n    Let \\<open>A'\\<close> be the preference profile obtained by having voter \\<open>X\\<close> lying and pretending\n    she only approves \\<open>x\\<close>.\n  \\<close>\n  define A' where \"A' = A - {#X#} + {#{x}#}\"\n  have A': \"is_pref_profile A'\"\n    using is_pref_profile_replace[OF A \\<open>X \\<in># A\\<close>, of \"{x}\"] by (auto simp: A'_def)\n\n  text \\<open>\n    We now show that even with this manipulated profile, the committee members approved by \\<open>X\\<close>\n    are exactly the same as before:\n  \\<close>\n  have X_approved_A'_eq: \"filter_mset (\\<lambda>x. x \\<in> X) (r A') = mset_set (X \\<inter> Z)\"\n  proof -\n    text \\<open>\n      Every element of \\<open>Z\\<close> must still be in the result committee due to Weak Representation.\n    \\<close>\n    have \"mset_set Z \\<subseteq># r A'\"\n    proof (subst mset_set_subset_iff) \n      show \"Z \\<subseteq> set_mset (r A')\"\n      proof\n        fix z assume z: \"z \\<in> Z\"\n        from x' z have [simp]: \"x \\<noteq> z\"\n          by auto\n        have [simp]: \"X \\<noteq> {z}\"\n          using x' by auto\n        show \"z \\<in># r A'\"\n          using Z weak_representation[OF A', of z] z x x' by (auto simp: A'_def)\n      qed\n    qed auto\n  \n    text \\<open>\n      Thus the parties in \\<open>X \\<inter> Z\\<close> must be in the committee (and they are approved by \\<open>X\\<close>).\n    \\<close>\n    have \"mset_set (X \\<inter> Z) \\<subseteq># filter_mset (\\<lambda>x. x \\<in> X) (r A')\"\n    proof -\n      have \"filter_mset (\\<lambda>x. x \\<in> X) (mset_set Z) \\<subseteq># filter_mset (\\<lambda>x. x \\<in> X) (r A')\"\n        using \\<open>mset_set Z \\<subseteq># r A'\\<close> by (intro multiset_filter_mono) auto\n      also have \"filter_mset (\\<lambda>x. x \\<in> X) (mset_set Z) = mset_set (X \\<inter> Z)\"\n        by auto\n      finally show \"mset_set (X \\<inter> Z) \\<subseteq># filter_mset (\\<lambda>x. x \\<in> X) (r A')\" .\n    qed\n  \n    text \\<open>\n      Due to Strategyproofness, no additional committee members can be approved by \\<open>X\\<close>,\n      so indeed only \\<open>X \\<inter> Z\\<close> is approved by \\<open>X\\<close>, and they each occur only once.\n    \\<close>\n    moreover have \"\\<not>card_manipulable A X {x}\"\n      using not_manipulable by blast\n    hence \"size (mset_set (X \\<inter> Z)) \\<ge> size (filter_mset (\\<lambda>x. x \\<in> X) (r A'))\" using assms\n      by (simp add: card_manipulable_def A'_def strong_committee_preference_iff not_less\n                    X_approved_A_eq)\n    ultimately show \"filter_mset (\\<lambda>x. x \\<in> X) (r A') = mset_set (X \\<inter> Z)\"\n      by (metis mset_subset_size_ge_imp_eq)\n  qed\n\n  text \\<open>\n    Next, we show that the set of committee members approved by \\<open>Y\\<close> in the committee returned for\n    the manipulated profile is exactly \\<open>Y \\<inter> Z\\<close> (and again, each party only occurs once).\n  \\<close>\n  have Y_approved_A'_eq: \"filter_mset (\\<lambda>x. x \\<in> Y) (r A') = mset_set (Y \\<inter> Z)\"\n  proof -\n    have \"filter_mset (\\<lambda>x. x \\<in> Y) (filter_mset (\\<lambda>x. x \\<in> X) (r A')) =\n           filter_mset (\\<lambda>x. x \\<in> Y) (mset_set (X \\<inter> Z))\"\n      by (simp only: X_approved_A'_eq)\n    also have \"filter_mset (\\<lambda>x. x \\<in> Y) (filter_mset (\\<lambda>x. x \\<in> X) (r A')) =\n               filter_mset (\\<lambda>x. x \\<in> Y \\<and> x \\<in> X) (r A')\"\n      by (simp add: filter_filter_mset conj_commute)\n    also have \"(\\<lambda>x. x \\<in> Y \\<and> x \\<in> X) = (\\<lambda>x. x \\<in> Y)\"\n      using assms by auto\n    also have \"filter_mset (\\<lambda>x. x \\<in> Y) (mset_set (X \\<inter> Z)) = mset_set (Y \\<inter> Z)\"\n      using assms by auto\n    finally show ?thesis .\n  qed\n\n  text \\<open>\n    Next, define the profile \\<open>A''\\<close> obtained from \\<open>A'\\<close> by also having \\<open>Y\\<close> pretend to approve\n    only \\<open>x\\<close>.\n  \\<close>\n  define A'' where \"A'' = A' - {#Y#} + {#{x}#}\"\n  have \"Y \\<in># A'\"\n    using assms by (auto simp: A'_def)\n  hence A'': \"is_pref_profile A''\"\n    using is_pref_profile_replace[OF A', of Y \"{x}\"] by (auto simp: A''_def)\n\n  text \\<open>\n    Again, the elements of \\<open>Z\\<close> must be chosen due to Weak Representation.\n  \\<close>\n  have \"Z \\<subseteq> set_mset (r A'')\"\n  proof\n    fix z assume z: \"z \\<in> Z\"\n    from x' z have [simp]: \"x \\<noteq> z\"\n      by auto\n    have [simp]: \"X \\<noteq> {z}\" \"Y \\<noteq> {z}\"\n      using x x' by auto\n    show \"z \\<in># r A''\"\n      using Z weak_representation[OF A'', of z] z x x' \n      by (auto simp: A''_def A'_def)\n  qed\n\n  text \\<open>\n    But now additionally, \\<open>x\\<close> must be chosen, since both \\<open>X\\<close> and \\<open>Y\\<close> uniquely approve it.\n  \\<close>\n  moreover have \"x \\<in># r A''\"\n    using x x' \\<open>Y \\<in># A - {#X#}\\<close> by (intro weak_representation A'') (auto simp: A''_def A'_def)\n  ultimately have \"insert x (Y \\<inter> Z) \\<subseteq> set_mset (r A'') \\<inter> Y\"\n    using x by blast\n\n  text \\<open>\n    Now we have a contradiction due to Strategyproofness, since \\<open>Y\\<close> can force the additional\n    member \\<open>x\\<close> into the committee by lying.\n  \\<close>\n  hence \"mset_set (insert x (Y \\<inter> Z)) \\<subseteq># filter_mset (\\<lambda>w. w \\<in> Y) (r A'')\"\n    by (subst mset_set_subset_iff) auto\n  hence \"size (mset_set (insert x (Y \\<inter> Z))) \\<le> size (filter_mset (\\<lambda>w. w \\<in> Y) (r A''))\"\n    by (rule size_mset_mono)\n  hence \"size (filter_mset (\\<lambda>x. x \\<in> Y) (r A'')) > size (filter_mset (\\<lambda>x. x \\<in> Y) (r A'))\"\n    using x by (simp add: Y_approved_A'_eq)\n  hence \"card_manipulable A' Y {x}\"\n    using A' x \\<open>Y \\<in># A'\\<close>\n    unfolding card_manipulable_def strong_committee_preference_iff A''_def by auto\n  thus False\n    using not_manipulable by blast\nqed\n\ntext \\<open>\n  The following are merely reformulation of the above lemma for technical reasons.\n\\<close>\nlemma lemma2':\n  assumes \"is_pref_profile A\"\n  assumes \"\\<forall>z\\<in>Z. count A {z} \\<ge> 2\"\n  assumes \"X \\<in># A \\<and> (\\<exists>Y. Y \\<in># A - {#X#} \\<and> Y \\<subseteq> X \\<and> \\<not>Y \\<subseteq> Z)\"\n  shows   \"\\<not>filter_mset (\\<lambda>x. x \\<in> X) (r A) \\<subseteq># mset_set (X \\<inter> Z)\"\nproof\n  assume subset: \"filter_mset (\\<lambda>x. x \\<in> X) (r A) \\<subseteq># mset_set (X \\<inter> Z)\"\n  from assms(3) obtain Y where Y: \"X \\<in># A\" \"Y \\<in># A - {#X#}\" \"Y \\<subseteq> X\" \"\\<not>Y \\<subseteq> Z\"\n    by blast\n  have \"card (X \\<inter> Z) < size {#x \\<in># r A. x \\<in> X#}\"\n    by (rule lemma2[where Y = Y]) (use Y assms(1,2) in auto)\n  with size_mset_mono[OF subset] show False\n    by simp\nqed\n\nlemma lemma2'':\n  assumes \"is_pref_profile A\"\n  assumes \"A' \\<equiv> A\"\n  assumes \"\\<forall>z\\<in>Z. count A {z} \\<ge> 2\"\n  assumes \"X \\<in># A \\<and> (\\<exists>Y\\<in>set_mset (A - {#X#}). Y \\<subseteq> X \\<and> \\<not>Y \\<subseteq> Z)\"\n  assumes \"filter_mset (\\<lambda>x. x \\<in> X) W \\<subseteq># mset_set (X \\<inter> Z)\"\n  shows   \"r A' \\<noteq> W\"\n  using lemma2'[of A Z X] assms by auto\n\n\nsubsection \\<open>Symmetry Breaking\\<close>\n\ntext \\<open>\n  In the following, we formalize the symmetry-breaking argument that shows that we can\n  reorder the four alternatives $C_1$ to $C_4$ in such a way that the preference profile\n  \\[ \\{C_1\\}\\ \\ \\{C_2\\}\\ \\  \\{C_1, C_2\\}\\ \\  \\{C_3\\}\\ \\  \\{C_3\\}\\ \\  \\{C_3, C_4\\} \\]\n  is mapped to one of the committees $[C_1, C_1, C_3]$ or $[C_1, C_2, C_3]$.\n\n  We start with a simple technical lemma that states that if we have a multiset $A$ of size 3\n  consisting of the elements $x$ and $y$ and $x$ occurs at least as often as $y$, then\n  $A = [x, x, y]$.\n\\<close>\n\nlemma papp_multiset_3_aux:\n  assumes \"size A = 3\" \"x \\<in># A\" \"y \\<in># A\" \"set_mset A \\<subseteq> {x, y}\" \"x \\<noteq> y\" \"count A x \\<ge> count A y\"\n  shows   \"A = {#x, x, y#}\"\nproof -\n  have \"count A x > 0\"\n    using assms by force\n  have \"size A = (\\<Sum>z\\<in>set_mset A. count A z)\"\n    by (rule size_multiset_overloaded_eq)\n  also have \"set_mset A = {x, y}\"\n    using assms by auto\n  also have \"(\\<Sum>z\\<in>\\<dots>. count A z) = count A x + count A y\"\n    using assms by auto\n  finally have \"count A x + count A y = 3\"\n    by (simp add: assms(1))\n  moreover from assms have \"count A x > 0\" \"count A y > 0\"\n    by auto\n  ultimately have *: \"count A x = 2 \\<and> count A y = 1\"\n    using \\<open>count A x \\<ge> count A y\\<close> by linarith\n  show ?thesis\n  proof (rule multiset_eqI)\n    fix z show \"count A z = count {#x, x, y#} z\"\n    proof (cases \"z \\<in> {x, y}\")\n      case False\n      with assms have \"z \\<notin> set_mset A\"\n        by auto\n      hence \"count A z = 0\"\n        by (simp add: Multiset.not_in_iff)\n      thus ?thesis\n        using False by auto\n    qed (use * in auto)\n  qed\nqed\n\ntext \\<open>\n  The following is the main symmetry-breaking result. It shows that we can find parties\n  $C_1$ to $C_4$ with the desired property.\n\n  This is a somewhat ad-hoc argument; in the appendix of the paper this is done more\n  systematically in Lemma~3.\n\\<close>\nlemma symmetry_break_aux:\n  obtains C1 C2 C3 C4 where\n    \"parties = {C1, C2, C3, C4}\" \"distinct [C1, C2, C3, C4]\"\n    \"r ({#{C1}, {C2}, {C1, C2}, {C3}, {C4}, {C3, C4}#}) \\<in> {{#C1, C1, C3#}, {#C1, C2, C3#}}\"\nproof -\n  note I = that\n  have \"\\<exists>xs. set xs = parties \\<and> distinct xs\"\n    using finite_distinct_list[of parties] by blast\n  then obtain xs where xs: \"set xs = parties\" \"distinct xs\"\n    by blast\n  from xs have \"length xs = 4\"\n    using card_parties distinct_card[of xs] by auto\n  then obtain C1 C2 C3 C4 where xs_eq: \"xs = [C1, C2, C3, C4]\"\n    by (auto simp: eval_nat_numeral length_Suc_conv)\n  have parties_eq: \"parties = {C1, C2, C3, C4}\"\n    by (subst xs(1) [symmetric], subst xs_eq) auto\n  have [simp]:\n       \"C1 \\<noteq> C2\" \"C1 \\<noteq> C3\" \"C1 \\<noteq> C4\"\n       \"C2 \\<noteq> C1\" \"C2 \\<noteq> C3\" \"C2 \\<noteq> C4\"\n       \"C3 \\<noteq> C1\" \"C3 \\<noteq> C2\" \"C3 \\<noteq> C4\"\n       \"C4 \\<noteq> C1\" \"C4 \\<noteq> C2\" \"C4 \\<noteq> C3\"\n    using \\<open>distinct xs\\<close> unfolding xs_eq by auto\n\n  define A where \"A = {#{C1}, {C2}, {C1, C2}, {C3}, {C4}, {C3, C4}#}\"\n  define m where \"m = Max (count (r A) ` parties)\"\n\n  have A: \"is_pref_profile A\"\n    unfolding A_def is_pref_profile_iff by (simp add: parties_eq)\n  hence \"is_committee (r A)\"\n    by (rule rule_wf)\n  hence rA: \"size (r A) = 3\" \"set_mset (r A) \\<subseteq> parties\"\n    unfolding is_committee_def by auto\n  define X where \"X = set_mset (r A)\"\n  have \"X \\<noteq> {}\" \"X \\<subseteq> parties\"\n    using rA by (auto simp: X_def)\n\n  have \"m > 0\"\n  proof -\n    obtain x where \"x \\<in> X\"\n      using \\<open>X \\<noteq> {}\\<close> by blast\n    with \\<open>X \\<subseteq> parties\\<close> have \"C1 \\<in> X \\<or> C2 \\<in> X \\<or> C3 \\<in> X \\<or> C4 \\<in> X\"\n      unfolding parties_eq by blast\n    thus ?thesis\n      unfolding m_def X_def by (subst Max_gr_iff) (auto simp: parties_eq)\n  qed\n\n  have \"m \\<le> 3\"\n  proof -\n    have \"m \\<le> size (r A)\"\n      unfolding m_def by (subst Max_le_iff) (auto simp: count_le_size)\n    also have \"\\<dots> = 3\"\n      by fact\n    finally show ?thesis .\n  qed\n\n  have \"m \\<in> (count (r A) ` parties)\"\n    unfolding m_def by (intro Max_in) auto\n  then obtain C1' where C1': \"count (r A) C1' = m\" \"C1' \\<in> parties\"\n    by blast\n  have \"C1' \\<in># r A\"\n    using \\<open>m > 0\\<close> C1'(1) by auto\n\n  have \"\\<exists>C2'\\<in>parties-{C1'}. {C1', C2'} \\<in># A\"\n    using C1' unfolding A_def parties_eq\n    by (elim insertE; simp add: insert_Diff_if insert_commute)\n  then obtain C2' where C2': \"C2' \\<in> parties - {C1'}\" \"{C1', C2'} \\<in># A\"\n    by blast\n  have [simp]: \"C1' \\<noteq> C2'\" \"C2' \\<noteq> C1'\"\n    using C2' by auto\n  have disj: \"C1' = C1 \\<and> C2' = C2 \\<or> C1' = C2 \\<and> C2' = C1 \\<or> C1' = C3 \\<and> C2' = C4 \\<or> C1' = C4 \\<and> C2' = C3\"\n    using C1'(2) C2' unfolding A_def parties_eq \n    by (elim insertE; force simp: insert_commute)\n\n  obtain C3' where C3': \"C3' \\<in> parties-{C1', C2'}\"\n    using C1'(2) C2' unfolding parties_eq by (fastforce simp: insert_Diff_if)\n  obtain C4' where C4': \"C4' \\<in> parties-{C1', C2', C3'}\"\n    using C1'(2) C2' C3' unfolding parties_eq by (fastforce simp: insert_Diff_if)\n  have A_eq: \"A = {#{C1'}, {C2'}, {C1', C2'}, {C3'}, {C4'}, {C3', C4'}#}\"\n    using disj C3' C4'\n    by (elim disjE) (auto simp: A_def parties_eq insert_commute)\n  have distinct:\n       \"C1' \\<noteq> C2'\" \"C1' \\<noteq> C3'\" \"C1' \\<noteq> C4'\"\n       \"C2' \\<noteq> C1'\" \"C2' \\<noteq> C3'\" \"C2' \\<noteq> C4'\"\n       \"C3' \\<noteq> C1'\" \"C3' \\<noteq> C2'\" \"C3' \\<noteq> C4'\"\n       \"C4' \\<noteq> C1'\" \"C4' \\<noteq> C2'\" \"C4' \\<noteq> C3'\"\n    using C1' C2' C3' C4' by blast+\n  have parties_eq': \"parties = {C1', C2', C3', C4'}\"\n    using C1'(2) C2'(1) C3' C4' distinct unfolding parties_eq by (elim insertE) auto\n\n  have \"\\<not>{#x \\<in># r A. x \\<in> {C3', C4'}#} \\<subseteq># mset_set ({C3', C4'} \\<inter> {})\"\n    by (rule lemma2'[OF A]) (auto simp: A_eq)\n  hence C34': \"C3' \\<in># r A \\<or> C4' \\<in># r A\"\n    by auto\n  then consider \"C3' \\<in># r A\" \"C4' \\<in># r A\" | \"C3' \\<in># r A\" \"C4' \\<notin># r A\" | \"C3' \\<notin># r A\" \"C4' \\<in># r A\"\n    by blast\n\n  thus ?thesis\n  proof cases\n    assume *: \"C3' \\<in># r A\" \"C4' \\<in># r A\"\n    have \"r A = {#C3', C4', C1'#}\"\n      by (rule sym, rule mset_subset_size_ge_imp_eq)\n         (use * \\<open>C1' \\<in># r A\\<close> distinct in \n            \\<open>auto simp: \\<open>size (r A) = 3\\<close> Multiset.insert_subset_eq_iff in_diff_multiset_absorb2\\<close>)\n    thus ?thesis using distinct\n      by (intro that[of C3' C4' C1' C2'])\n         (auto simp: parties_eq' A_eq add_mset_commute insert_commute)\n\n  next\n\n    assume *: \"C3' \\<in># r A\" \"C4' \\<notin># r A\"\n    show ?thesis\n    proof (cases \"C2' \\<in># r A\")\n      case True\n      have \"r A = {#C1', C2', C3'#}\"\n        by (rule sym, rule mset_subset_size_ge_imp_eq)\n           (use * \\<open>C1' \\<in># r A\\<close> distinct True in \n              \\<open>auto simp: \\<open>size (r A) = 3\\<close> Multiset.insert_subset_eq_iff in_diff_multiset_absorb2\\<close>)\n      thus ?thesis using distinct\n        by (intro that[of C1' C2' C3' C4'])\n           (auto simp: parties_eq' A_eq add_mset_commute insert_commute)\n    next\n      case False\n      have \"r A = {#C1', C1', C3'#}\"\n      proof (rule papp_multiset_3_aux)\n        show \"set_mset (r A) \\<subseteq> {C1', C3'}\"\n          using \\<open>set_mset (r A) \\<subseteq> _\\<close> * False unfolding parties_eq' by auto\n      next\n        have \"count (r A) C3' \\<le> m\"\n          unfolding m_def by (subst Max_ge_iff) (auto simp: parties_eq')\n        also have \"m = count (r A) C1'\"\n          by (simp add: C1')\n        finally show \"count (r A) C3' \\<le> count (r A) C1'\" .\n      qed (use C1' * False \\<open>C1' \\<in># r A\\<close> distinct in \\<open>auto simp: \\<open>size (r A) = 3\\<close>\\<close>)\n      thus ?thesis using distinct\n        by (intro that[of C1' C2' C3' C4'])\n           (auto simp: parties_eq' insert_commute add_mset_commute A_eq)\n    qed\n\n  next\n\n    assume *: \"C3' \\<notin># r A\" \"C4' \\<in># r A\"\n    show ?thesis\n    proof (cases \"C2' \\<in># r A\")\n      case True\n      have \"r A = {#C1', C2', C4'#}\"\n        by (rule sym, rule mset_subset_size_ge_imp_eq)\n           (use * \\<open>C1' \\<in># r A\\<close> distinct True in \n              \\<open>auto simp: \\<open>size (r A) = 3\\<close> Multiset.insert_subset_eq_iff in_diff_multiset_absorb2\\<close>)\n      thus ?thesis using distinct\n        by (intro that[of C1' C2' C4' C3'])\n           (auto simp: parties_eq' A_eq add_mset_commute insert_commute)\n    next\n      case False\n      have \"r A = {#C1', C1', C4'#}\"\n      proof (rule papp_multiset_3_aux)\n        show \"set_mset (r A) \\<subseteq> {C1', C4'}\"\n          using \\<open>set_mset (r A) \\<subseteq> _\\<close> * False unfolding parties_eq' by auto\n      next\n        have \"count (r A) C4' \\<le> m\"\n          unfolding m_def by (subst Max_ge_iff) (auto simp: parties_eq')\n        also have \"m = count (r A) C1'\"\n          by (simp add: C1')\n        finally show \"count (r A) C4' \\<le> count (r A) C1'\" .\n      qed (use C1' * False \\<open>C1' \\<in># r A\\<close> distinct in \\<open>auto simp: \\<open>size (r A) = 3\\<close>\\<close>)\n      thus ?thesis using distinct\n        by (intro that[of C1' C2' C4' C3'])\n           (auto simp: parties_eq' insert_commute add_mset_commute A_eq)\n    qed\n  qed\nqed\n\ntext \\<open>\n  We now use the choice operator to get our hands on such values $C_1$ to $C_4$.\n\\<close>\ndefinition C1234 where\n  \"C1234 = (SOME xs. set xs = parties \\<and> distinct xs \\<and> \n              (case xs of [C1, C2, C3, C4] \\<Rightarrow>\n              r ({#{C1}, {C2}, {C1, C2}, {C3}, {C4}, {C3, C4}#}) \\<in> {{#C1, C1, C3#}, {#C1, C2, C3#}}))\"\n\ndefinition C1 where \"C1 = C1234 ! 0\"\ndefinition C2 where \"C2 = C1234 ! 1\"\ndefinition C3 where \"C3 = C1234 ! 2\"\ndefinition C4 where \"C4 = C1234 ! 3\"\n\nlemma distinct: \"distinct [C1, C2, C3, C4]\"\n  and parties_eq:  \"parties = {C1, C2, C3, C4}\"\n  and symmetry_break:\n        \"r ({#{C1}, {C2}, {C1, C2}, {C3}, {C4}, {C3, C4}#}) \\<in> {{#C1, C1, C3#}, {#C1, C2, C3#}}\"\nproof -\n  have C1234:\n        \"set C1234 = parties \\<and> distinct C1234 \\<and> \n        (case C1234 of [C1', C2', C3', C4'] \\<Rightarrow>\n            r ({#{C1'}, {C2'}, {C1', C2'}, {C3'}, {C4'}, {C3', C4'}#}) \\<in>\n              {{#C1', C1', C3'#}, {#C1', C2', C3'#}})\"\n    unfolding C1234_def\n  proof (rule someI_ex)\n    obtain C1' C2' C3' C4' where *:\n      \"parties = {C1', C2', C3', C4'}\" \"distinct [C1', C2', C3', C4']\"\n      \"r ({#{C1'}, {C2'}, {C1', C2'}, {C3'}, {C4'}, {C3', C4'}#}) \\<in> \n         {{#C1', C1', C3'#}, {#C1', C2', C3'#}}\"\n      using symmetry_break_aux by blast    \n    show \"\\<exists>xs. set xs = parties \\<and> distinct xs \\<and> \n            (case xs of [C1', C2', C3', C4'] \\<Rightarrow>\n              r ({#{C1'}, {C2'}, {C1', C2'}, {C3'}, {C4'}, {C3', C4'}#}) \\<in> \n                {{#C1', C1', C3'#}, {#C1', C2', C3'#}})\"\n      by (intro exI[of _ \"[C1', C2', C3', C4']\"]) (use * in auto)\n  qed\n\n  have \"length C1234 = 4\"\n    using C1234 card_parties distinct_card[of C1234] by simp\n  then obtain C1' C2' C3' C4' where C1234_eq: \"C1234 = [C1', C2', C3', C4']\"\n    by (auto simp: eval_nat_numeral length_Suc_conv)\n  show \"distinct [C1, C2, C3, C4]\" \"parties = {C1, C2, C3, C4}\" \n       \"r ({#{C1}, {C2}, {C1, C2}, {C3}, {C4}, {C3, C4}#}) \\<in> {{#C1, C1, C3#}, {#C1, C2, C3#}}\"\n    using C1234 by (simp_all add: C1234_eq C1_def C2_def C3_def C4_def)\nqed\n\nlemma distinct' [simp]:\n   \"C1 \\<noteq> C2\" \"C1 \\<noteq> C3\" \"C1 \\<noteq> C4\" \"C2 \\<noteq> C1\" \"C2 \\<noteq> C3\" \"C2 \\<noteq> C4\"\n   \"C3 \\<noteq> C1\" \"C3 \\<noteq> C2\" \"C3 \\<noteq> C4\" \"C4 \\<noteq> C1\" \"C4 \\<noteq> C2\" \"C4 \\<noteq> C3\"\n  using distinct by auto\n\nlemma in_parties [simp]: \"C1 \\<in> parties\" \"C2 \\<in> parties\" \"C3 \\<in> parties\" \"C4 \\<in> parties\"\n  by (subst (2) parties_eq; simp; fail)+\n\n\nsubsection \\<open>The Set of Possible Committees\\<close>\n\ntext \\<open>\n  Next, we compute the set of the 20 possible committees.\n\\<close>\n\nabbreviation COM where \"COM \\<equiv> committees 3 parties\"\n\ndefinition COM' where \"COM' =\n  [{#C1, C1, C1#}, {#C1, C1, C2#}, {#C1, C1, C3#}, {#C1, C1, C4#},\n   {#C1, C2, C2#}, {#C1, C2, C3#}, {#C1, C2, C4#}, {#C1, C3, C3#},\n   {#C1, C3, C4#}, {#C1, C4, C4#}, {#C2, C2, C2#}, {#C2, C2, C3#},\n   {#C2, C2, C4#}, {#C2, C3, C3#}, {#C2, C3, C4#}, {#C2, C4, C4#},\n   {#C3, C3, C3#}, {#C3, C3, C4#}, {#C3, C4, C4#},\n   {#C4, C4, C4#}]\"\n\nlemma distinct_COM': \"distinct COM'\"\n  by (simp add: COM'_def add_mset_neq)\n\nlemma COM_eq: \"COM = set COM'\"\n  by (subst parties_eq)\n     (simp_all add: COM'_def numeral_3_eq_3 committees_Suc add_ac insert_commute add_mset_commute)\n\nlemma r_in_COM:\n  assumes \"is_pref_profile A\"\n  shows   \"r A \\<in> COM\"\n  using rule_wf[OF assms] unfolding committees_def is_committee_def by auto\n\nlemma r_in_COM':\n  assumes \"is_pref_profile A\" \"A' \\<equiv> A\"\n  shows   \"list_ex (\\<lambda>W. r A' = W) COM'\"\n  using r_in_COM[OF assms(1)] assms(2) by (auto simp: list_ex_iff COM_eq)\n\nlemma r_right_unique:\n  \"list_all (\\<lambda>(W1,W2). r A \\<noteq> W1 \\<or> r A \\<noteq> W2) (pairs COM')\"\nproof -\n  have \"list_all (\\<lambda>(W1,W2). W1 \\<noteq> W2) (pairs COM')\"\n    using distinct_COM' unfolding distinct_conv_pairs by blast\n  thus ?thesis\n    unfolding list_all_iff by blast\nqed\n\nend\n\n\n\nsubsection \\<open>Generating Clauses and Replaying the SAT Proof\\<close>\n\ntext \\<open>\n  We now employ some custom-written ML code to generate all the SAT clauses arising from the\n  given profiles (read from an external file) as Isabelle/HOL theorems. From these, we then\n  derive \\<^term>\\<open>False\\<close> by replaying an externally found SAT proof (also written from an external\n  file).\n\n  The proof was found with the glucose SAT solver, which outputs proofs in the DRUP format\n  (a subset of the more powerful DRAT format). We then used the \\<^emph>\\<open>DRAT-trim\\<close> tool by\n  Wetzler et al.~\\cite{wetzler_drat_trim} to make the proof smaller. This was done repeatedly\n  until the proof size did not decrease any longer. Then, the proof was converted into the \\<^emph>\\<open>GRAT\\<close>\n  format introduced by Lammich~\\cite{lammich_grat}, which is easier to check (or in our case\n  replay) than the less explicit DRAT (or DRUP) format. \n\\<close>\n\nexternal_file \"sat_data/profiles\"\nexternal_file \"sat_data/papp_impossibility.grat.xz\"\n\ncontext papp_impossibility_base_case\nbegin\n\nML_file \\<open>papp_impossibility.ML\\<close>\n\ntext \\<open>\n  This invocation proves a theorem called \\<^emph>\\<open>contradiction\\<close> whose statement is \\<^term>\\<open>False\\<close>.\n  Note that the DIMACS version of the SAT file that is being generated can be viewed by\n  clicking on ``See theory exports'' in the messages output by the invocation below.\n\n  On a 2021 desktop PC with 12 cores, proving all the clauses takes 8.4\\,s (multithreaded;\n  CPU time 55\\,s). Replaying the proof takes 130\\,s (singlethreaded).\n\\<close>\n\nlocal_setup \\<open>fn lthy =>\n  let\n    val thm =\n      PAPP_Impossibility.derive_false lthy\n        (\\<^master_dir> + \\<^path>\\<open>sat_data/profiles\\<close>)\n        (\\<^master_dir> + \\<^path>\\<open>sat_data/papp_impossibility.grat.xz\\<close>)\n  in\n    Local_Theory.note ((\\<^binding>\\<open>contradiction\\<close>, []), [thm]) lthy |> snd\n  end\n\\<close>\n\nend\n\ntext \\<open>\n  With this, we can now prove the impossibility result:\n\\<close>\nlemma papp_impossibility_base_case:\n  assumes \"card parties = 4\"\n  shows   \"\\<not>card_stratproof_weak_rep_anon_papp 6 parties 3 r\"\nproof\n  assume \"card_stratproof_weak_rep_anon_papp 6 parties 3 r\"\n  then interpret card_stratproof_weak_rep_anon_papp 6 parties 3 r .\n  interpret papp_impossibility_base_case parties r\n    by unfold_locales fact+\n  show False\n    by (rule contradiction)\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/PAPP_Impossibility/PAPP_Impossibility_Base_Case.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.867035763237924, "lm_q2_score": 0.8596637541053281, "lm_q1q2_score": 0.7453592191686922}}
{"text": "(*  Author:  S\u00e9bastien Gou\u00ebzel   sebastien.gouezel@univ-rennes1.fr\n    License: BSD\n*)\n\nsection \\<open>The exponential on extended real numbers.\\<close>\n\ntheory Eexp_Eln\n  imports Library_Complements\nbegin\n\ntext \\<open>To define the distance on the Gromov completion of hyperbolic spaces, we need to use\nthe exponential on extended real numbers. We can not use the symbol \\verb+exp+, as this symbol\nis already used in Banach algebras, so we use \\verb+ennexp+ instead. We prove its basic\nproperties (together with properties of the logarithm) here. We also use it to define the square\nroot on ennreal. Finally, we also define versions from ereal to ereal.\\<close>\n\nfunction ennexp::\"ereal \\<Rightarrow> ennreal\" where\n\"ennexp (ereal r) = ennreal (exp r)\"\n| \"ennexp (\\<infinity>) = \\<infinity>\"\n| \"ennexp (-\\<infinity>) = 0\"\nby (auto intro: ereal_cases)\ntermination by standard (rule wf_empty)\n\nlemma ennexp_0 [simp]:\n  \"ennexp 0 = 1\"\nby (auto simp add: zero_ereal_def one_ennreal_def)\n\nfunction eln::\"ennreal \\<Rightarrow> ereal\" where\n\"eln (ennreal r) = (if r \\<le> 0 then -\\<infinity> else ereal (ln r))\"\n| \"eln (\\<infinity>) = \\<infinity>\"\nby (auto intro: ennreal_cases, metis ennreal_eq_0_iff, simp add: ennreal_neg)\ntermination by standard (rule wf_empty)\n\nlemma eln_simps [simp]:\n  \"eln 0 = -\\<infinity>\"\n  \"eln 1 = 0\"\n  \"eln top = \\<infinity>\"\napply (simp only: eln.simps ennreal_0[symmetric], simp)\napply (simp only: eln.simps ennreal_1[symmetric], simp)\nusing eln.simps(2) by auto\n\nlemma eln_real_pos:\n  assumes \"r > 0\"\n  shows \"eln (ennreal r) = ereal (ln r)\"\nusing eln.simps assms by auto\n\nlemma eln_ennexp [simp]:\n  \"eln (ennexp x) = x\"\napply (cases x) using eln.simps by auto\n\nlemma ennexp_eln [simp]:\n  \"ennexp (eln x) = x\"\napply (cases x) using eln.simps by auto\n\nlemma ennexp_strict_mono:\n  \"strict_mono ennexp\"\nproof -\n  have \"ennexp x < ennexp y\" if \"x < y\" for x y\n    apply (cases x, cases y)\n    using that apply (auto simp add: ennreal_less_iff)\n    by (cases y, auto)\n  then show ?thesis unfolding strict_mono_def by auto\nqed\n\nlemma ennexp_mono:\n  \"mono ennexp\"\nusing ennexp_strict_mono by (simp add: strict_mono_mono)\n\nlemma ennexp_strict_mono2 [mono_intros]:\n  assumes \"x < y\"\n  shows \"ennexp x < ennexp y\"\nusing ennexp_strict_mono assms unfolding strict_mono_def by auto\n\nlemma ennexp_mono2 [mono_intros]:\n  assumes \"x \\<le> y\"\n  shows \"ennexp x \\<le> ennexp y\"\nusing ennexp_mono assms unfolding mono_def by auto\n\nlemma ennexp_le1 [simp]:\n  \"ennexp x \\<le> 1 \\<longleftrightarrow> x \\<le> 0\"\nby (metis ennexp_0 ennexp_mono2 ennexp_strict_mono eq_iff le_cases strict_mono_eq)\n\nlemma ennexp_ge1 [simp]:\n  \"ennexp x \\<ge> 1 \\<longleftrightarrow> x \\<ge> 0\"\nby (metis ennexp_0 ennexp_mono2 ennexp_strict_mono eq_iff le_cases strict_mono_eq)\n\nlemma eln_strict_mono:\n  \"strict_mono eln\"\nby (metis ennexp_eln strict_monoI ennexp_strict_mono strict_mono_less)\n\n\n\nlemma eln_strict_mono2 [mono_intros]:\n  assumes \"x < y\"\n  shows \"eln x < eln y\"\nusing eln_strict_mono assms unfolding strict_mono_def by auto\n\nlemma eln_mono2 [mono_intros]:\n  assumes \"x \\<le> y\"\n  shows \"eln x \\<le> eln y\"\nusing eln_mono assms unfolding mono_def by auto\n\nlemma eln_le0 [simp]:\n  \"eln x \\<le> 0 \\<longleftrightarrow> x \\<le> 1\"\nby (metis ennexp_eln ennexp_le1)\n\nlemma eln_ge0 [simp]:\n  \"eln x \\<ge> 0 \\<longleftrightarrow> x \\<ge> 1\"\nby (metis ennexp_eln ennexp_ge1)\n\nlemma bij_ennexp:\n  \"bij ennexp\"\nby (auto intro!: bij_betw_byWitness[of _ eln])\n\nlemma bij_eln:\n  \"bij eln\"\nby (auto intro!: bij_betw_byWitness[of _ ennexp])\n\nlemma ennexp_continuous:\n  \"continuous_on UNIV ennexp\"\napply (rule continuous_onI_mono)\nusing ennexp_mono unfolding mono_def by (auto simp add: bij_ennexp bij_is_surj)\n\nlemma ennexp_tendsto [tendsto_intros]:\n  assumes \"((\\<lambda>n. u n) \\<longlongrightarrow> l) F\"\n  shows \"((\\<lambda>n. ennexp(u n)) \\<longlongrightarrow> ennexp l) F\"\nusing ennexp_continuous assms by (metis UNIV_I continuous_on tendsto_compose)\n\nlemma eln_continuous:\n  \"continuous_on UNIV eln\"\napply (rule continuous_onI_mono)\nusing eln_mono unfolding mono_def by (auto simp add: bij_eln bij_is_surj)\n\nlemma eln_tendsto [tendsto_intros]:\n  assumes \"((\\<lambda>n. u n) \\<longlongrightarrow> l) F\"\n  shows \"((\\<lambda>n. eln(u n)) \\<longlongrightarrow> eln l) F\"\nusing eln_continuous assms by (metis UNIV_I continuous_on tendsto_compose)\n\nlemma ennexp_special_values [simp]:\n  \"ennexp x = 0 \\<longleftrightarrow> x = -\\<infinity>\"\n  \"ennexp x = 1 \\<longleftrightarrow> x = 0\"\n  \"ennexp x = \\<infinity> \\<longleftrightarrow> x = \\<infinity>\"\n  \"ennexp x = top \\<longleftrightarrow> x = \\<infinity>\"\nby auto (metis eln_ennexp eln_simps)+\n\nlemma eln_special_values [simp]:\n  \"eln x = -\\<infinity> \\<longleftrightarrow> x = 0\"\n  \"eln x = 0 \\<longleftrightarrow> x = 1\"\n  \"eln x = \\<infinity> \\<longleftrightarrow> x = \\<infinity>\"\napply auto\napply (metis ennexp.simps ennexp_eln ennexp_0)+\nby (metis ennexp.simps(2) ennexp_eln infinity_ennreal_def)\n\nlemma ennexp_add_mult:\n  assumes \"\\<not>((a = \\<infinity> \\<and> b = -\\<infinity>) \\<or> (a = -\\<infinity> \\<and> b = \\<infinity>))\"\n  shows \"ennexp(a+b) = ennexp a * ennexp b\"\napply (cases a, cases b)\nusing assms by (auto simp add: ennreal_mult'' exp_add ennreal_top_eq_mult_iff)\n\nlemma eln_mult_add:\n  assumes \"\\<not>((a = \\<infinity> \\<and> b = 0) \\<or> (a = 0 \\<and> b = \\<infinity>))\"\n  shows \"eln(a * b) = eln a + eln b\"\nby (smt assms ennexp.simps(2) ennexp.simps(3) ennexp_add_mult ennexp_eln eln_ennexp)\n\ntext \\<open>We can also define the square root on ennreal using the above exponential.\\<close>\n\ndefinition ennsqrt::\"ennreal \\<Rightarrow> ennreal\"\n  where \"ennsqrt x = ennexp(eln x/2)\"\n\nlemma ennsqrt_square [simp]:\n  \"(ennsqrt x) * (ennsqrt x) = x\"\nproof -\n  have \"y/2 + y/2 = y\" for y::ereal\n    by (cases y, auto)\n  then show ?thesis\n    unfolding ennsqrt_def by (subst ennexp_add_mult[symmetric], auto)\nqed\n\nlemma ennsqrt_simps [simp]:\n  \"ennsqrt 0 = 0\"\n  \"ennsqrt 1 = 1\"\n  \"ennsqrt \\<infinity> = \\<infinity>\"\n  \"ennsqrt top = top\"\nunfolding ennsqrt_def by auto\n\nlemma ennsqrt_mult:\n  \"ennsqrt(a * b) = ennsqrt a * ennsqrt b\"\nproof -\n  have [simp]: \"z/ereal 2 = -\\<infinity> \\<longleftrightarrow> z = -\\<infinity>\" for z\n    by (auto simp add: ereal_divide_eq)\n\n  consider \"a = 0\" | \"b = 0\" | \"a > 0 \\<and> b > 0\"\n    using zero_less_iff_neq_zero by auto\n  then show ?thesis\n    apply (cases, auto)\n    apply (cases a, cases b, auto simp add: ennreal_mult_top ennreal_top_mult)\n    unfolding ennsqrt_def apply (subst ennexp_add_mult[symmetric], auto)\n    apply (subst eln_mult_add, auto)\n    done\nqed\n\nlemma ennsqrt_square2 [simp]:\n  \"ennsqrt (x * x) = x\"\n  unfolding ennsqrt_mult by auto\n\nlemma ennsqrt_eq_iff_square:\n  \"ennsqrt x = y \\<longleftrightarrow> x = y * y\"\nby auto\n\nlemma ennsqrt_bij:\n  \"bij ennsqrt\"\nby (rule bij_betw_byWitness[of _ \"\\<lambda>x. x * x\"], auto)\n\nlemma ennsqrt_strict_mono:\n  \"strict_mono ennsqrt\"\n  unfolding ennsqrt_def\n  apply (rule strict_mono_compose[OF ennexp_strict_mono])\n  apply (rule strict_mono_compose[OF _ eln_strict_mono])\n  by (auto simp add: ereal_less_divide_pos ereal_mult_divide strict_mono_def)\n\nlemma ennsqrt_mono:\n  \"mono ennsqrt\"\nusing ennsqrt_strict_mono by (simp add: strict_mono_mono)\n\nlemma ennsqrt_mono2 [mono_intros]:\n  assumes \"x \\<le> y\"\n  shows \"ennsqrt x \\<le> ennsqrt y\"\nusing ennsqrt_mono assms unfolding mono_def by auto\n\nlemma ennsqrt_continuous:\n  \"continuous_on UNIV ennsqrt\"\napply (rule continuous_onI_mono)\nusing ennsqrt_mono unfolding mono_def by (auto simp add: ennsqrt_bij bij_is_surj)\n\nlemma ennsqrt_tendsto [tendsto_intros]:\n  assumes \"((\\<lambda>n. u n) \\<longlongrightarrow> l) F\"\n  shows \"((\\<lambda>n. ennsqrt(u n)) \\<longlongrightarrow> ennsqrt l) F\"\nusing ennsqrt_continuous assms by (metis UNIV_I continuous_on tendsto_compose)\n\nlemma ennsqrt_ennreal_ennreal_sqrt [simp]:\n  assumes \"t \\<ge> (0::real)\"\n  shows \"ennsqrt (ennreal t) = ennreal (sqrt t)\"\nproof -\n  have \"ennreal t = ennreal (sqrt t) * ennreal(sqrt t)\"\n    apply (subst ennreal_mult[symmetric]) using assms by auto\n  then show ?thesis\n    by auto\nqed\n\nlemma ennreal_sqrt2:\n  \"ennreal (sqrt 2) = ennsqrt 2\"\nusing ennsqrt_ennreal_ennreal_sqrt[of 2] by auto\n\nlemma ennsqrt_4 [simp]:\n  \"ennsqrt 4 = 2\"\nby (metis ennreal_numeral ennsqrt_ennreal_ennreal_sqrt real_sqrt_four zero_le_numeral)\n\nlemma ennsqrt_le [simp]:\n  \"ennsqrt x \\<le> ennsqrt y \\<longleftrightarrow> x \\<le> y\"\nproof\n  assume \"ennsqrt x \\<le> ennsqrt y\"\n  then have \"ennsqrt x * ennsqrt x \\<le> ennsqrt y * ennsqrt y\"\n    by (intro mult_mono, auto)\n  then show \"x \\<le> y\" by auto\nqed (auto intro: mono_intros)\n\ntext \\<open>We can also define the square root on ereal using the square root on ennreal, and $0$\nfor negative numbers.\\<close>\n\ndefinition esqrt::\"ereal \\<Rightarrow> ereal\"\n  where \"esqrt x = enn2ereal(ennsqrt (e2ennreal x))\"\n\nlemma esqrt_square [simp]:\n  assumes \"x \\<ge> 0\"\n  shows \"(esqrt x) * (esqrt x) = x\"\nunfolding esqrt_def times_ennreal.rep_eq[symmetric] ennsqrt_square[of \"e2ennreal x\"]\nusing assms enn2ereal_e2ennreal by auto\n\n\n\nlemma esqrt_nonneg [simp]:\n  \"esqrt x \\<ge> 0\"\nunfolding esqrt_def by auto\n\nlemma esqrt_eq_iff_square [simp]:\n  assumes \"x \\<ge> 0\" \"y \\<ge> 0\"\n  shows \"esqrt x = y \\<longleftrightarrow> x = y * y\"\nusing esqrt_def esqrt_square assms apply auto\nby (metis e2ennreal_enn2ereal ennsqrt_square2 eq_onp_same_args ereal_ennreal_cases leD times_ennreal.abs_eq)\n\nlemma esqrt_simps [simp]:\n  \"esqrt 0 = 0\"\n  \"esqrt 1 = 1\"\n  \"esqrt \\<infinity> = \\<infinity>\"\n  \"esqrt top = top\"\n  \"esqrt (-\\<infinity>) = 0\"\nby (auto simp: top_ereal_def)\n\nlemma esqrt_mult:\n  assumes \"a \\<ge> 0\"\n  shows \"esqrt(a * b) = esqrt a * esqrt b\"\nproof (cases \"b \\<ge> 0\")\n  case True\n  show ?thesis\n    unfolding esqrt_def apply (subst times_ennreal.rep_eq[symmetric])\n    apply (subst ennsqrt_mult[of \"e2ennreal a\" \"e2ennreal b\", symmetric])\n    apply (subst times_ennreal.abs_eq)\n    using assms True by (auto simp add: eq_onp_same_args)\nnext\n  case False\n  then have \"a * b \\<le> 0\" using assms ereal_mult_le_0_iff by auto\n  then have \"esqrt(a * b) = 0\" by auto\n  moreover have \"esqrt b = 0\" using False by auto\n  ultimately show ?thesis by auto\nqed\n\nlemma esqrt_square2 [simp]:\n  \"esqrt(x * x) = abs(x)\"\nproof -\n  have \"esqrt(x * x) = esqrt(abs x * abs x)\"\n    by (metis (no_types, hide_lams) abs_ereal_ge0 ereal_abs_mult ereal_zero_le_0_iff linear)\n  also have \"... = abs x\"\n    by (auto simp add: esqrt_mult)\n  finally show ?thesis by auto\nqed\n\nlemma esqrt_mono:\n  \"mono esqrt\"\nunfolding esqrt_def mono_def by (auto intro: mono_intros)\n\nlemma esqrt_mono2 [mono_intros]:\n  assumes \"x \\<le> y\"\n  shows \"esqrt x \\<le> esqrt y\"\nusing esqrt_mono assms unfolding mono_def by auto\n\nlemma esqrt_continuous:\n  \"continuous_on UNIV esqrt\"\nunfolding esqrt_def apply (rule continuous_on_compose2[of UNIV enn2ereal], intro continuous_on_enn2ereal)\nby (rule continuous_on_compose2[of UNIV ennsqrt], auto intro!: ennsqrt_continuous continuous_on_e2ennreal)\n\nlemma esqrt_tendsto [tendsto_intros]:\n  assumes \"((\\<lambda>n. u n) \\<longlongrightarrow> l) F\"\n  shows \"((\\<lambda>n. esqrt(u n)) \\<longlongrightarrow> esqrt l) F\"\nusing esqrt_continuous assms by (metis UNIV_I continuous_on tendsto_compose)\n\nlemma esqrt_ereal_ereal_sqrt [simp]:\n  assumes \"t \\<ge> (0::real)\"\n  shows \"esqrt (ereal t) = ereal (sqrt t)\"\nproof -\n  have \"ereal t = ereal (sqrt t) * ereal(sqrt t)\"\n    using assms by auto\n  then show ?thesis\n    using assms ereal_less_eq(5) esqrt_mult esqrt_square real_sqrt_ge_zero by presburger\nqed\n\nlemma ereal_sqrt2:\n  \"ereal (sqrt 2) = esqrt 2\"\nusing esqrt_ereal_ereal_sqrt[of 2] by auto\n\nlemma esqrt_4 [simp]:\n  \"esqrt 4 = 2\"\nby auto\n\nlemma esqrt_le [simp]:\n  \"esqrt x \\<le> esqrt y \\<longleftrightarrow> (x \\<le> 0 \\<or> x \\<le> y)\"\napply (auto simp add: esqrt_mono2)\nby (metis eq_iff ereal_zero_times esqrt_mono2 esqrt_square le_cases)\n\ntext \\<open>Finally, we define eexp, as the composition of ennexp and the injection of ennreal in ereal.\\<close>\n\ndefinition eexp::\"ereal \\<Rightarrow> ereal\" where\n  \"eexp x = enn2ereal (ennexp x)\"\n\nlemma eexp_special_values [simp]:\n  \"eexp 0 = 1\"\n  \"eexp (\\<infinity>) = \\<infinity>\"\n  \"eexp(-\\<infinity>) = 0\"\nunfolding eexp_def by (auto simp add: zero_ennreal.rep_eq one_ennreal.rep_eq)\n\nlemma eexp_strict_mono:\n  \"strict_mono eexp\"\nunfolding eexp_def using ennexp_strict_mono unfolding strict_mono_def by (auto intro: mono_intros)\n\nlemma eexp_mono:\n  \"mono eexp\"\nusing eexp_strict_mono by (simp add: strict_mono_mono)\n\nlemma eexp_strict_mono2 [mono_intros]:\n  assumes \"x < y\"\n  shows \"eexp x < eexp y\"\nusing eexp_strict_mono assms unfolding strict_mono_def by auto\n\nlemma eexp_mono2 [mono_intros]:\n  assumes \"x \\<le> y\"\n  shows \"eexp x \\<le> eexp y\"\nusing eexp_mono assms unfolding mono_def by auto\n\nlemma eexp_le_eexp_iff_le:\n  \"eexp x \\<le> eexp y \\<longleftrightarrow> x \\<le> y\"\nusing eexp_strict_mono2 not_le by (auto intro: mono_intros)\n\nlemma eexp_lt_eexp_iff_lt:\n  \"eexp x < eexp y \\<longleftrightarrow> x < y\"\nusing eexp_mono2 not_le by (auto intro: mono_intros)\n\nlemma eexp_special_values_iff [simp]:\n  \"eexp x = 0 \\<longleftrightarrow> x = -\\<infinity>\"\n  \"eexp x = 1 \\<longleftrightarrow> x = 0\"\n  \"eexp x = \\<infinity> \\<longleftrightarrow> x = \\<infinity>\"\n  \"eexp x = top \\<longleftrightarrow> x = \\<infinity>\"\nunfolding eexp_def apply (auto simp add: zero_ennreal.rep_eq one_ennreal.rep_eq top_ereal_def)\napply (metis e2ennreal_enn2ereal ennexp.simps(3) ennexp_strict_mono strict_mono_eq zero_ennreal_def)\nby (metis e2ennreal_enn2ereal eln_ennexp eln_simps(2) one_ennreal_def)\n\nlemma eexp_ineq_iff [simp]:\n  \"eexp x \\<le> 1 \\<longleftrightarrow> x \\<le> 0\"\n  \"eexp x \\<ge> 1 \\<longleftrightarrow> x \\<ge> 0\"\n  \"eexp x > 1 \\<longleftrightarrow> x > 0\"\n  \"eexp x < 1 \\<longleftrightarrow> x < 0\"\n  \"eexp x \\<ge> 0\"\n  \"eexp x > 0 \\<longleftrightarrow> x \\<noteq> - \\<infinity>\"\n  \"eexp x < \\<infinity> \\<longleftrightarrow> x \\<noteq> \\<infinity>\"\napply (metis eexp_le_eexp_iff_le eexp_lt_eexp_iff_lt eexp_special_values)+\napply (simp add: eexp_def)\nusing eexp_strict_mono2 apply (force)\nby simp\n\nlemma eexp_ineq [mono_intros]:\n  \"x \\<le> 0 \\<Longrightarrow> eexp x \\<le> 1\"\n  \"x < 0 \\<Longrightarrow> eexp x < 1\"\n  \"x \\<ge> 0 \\<Longrightarrow> eexp x \\<ge> 1\"\n  \"x > 0 \\<Longrightarrow> eexp x > 1\"\n  \"eexp x \\<ge> 0\"\n  \"x > -\\<infinity> \\<Longrightarrow> eexp x > 0\"\n  \"x < \\<infinity> \\<Longrightarrow> eexp x < \\<infinity>\"\nby auto\n\nlemma eexp_continuous:\n  \"continuous_on UNIV eexp\"\nunfolding eexp_def by (rule continuous_on_compose2[of UNIV enn2ereal], auto simp: continuous_on_enn2ereal ennexp_continuous)\n\n\nlemma eexp_tendsto' [simp]:\n  \"((\\<lambda>n. eexp(u n)) \\<longlongrightarrow> eexp l) F \\<longleftrightarrow> ((\\<lambda>n. u n) \\<longlongrightarrow> l) F\"\nproof\n  assume H: \"((\\<lambda>n. eexp (u n)) \\<longlongrightarrow> eexp l) F\"\n  have \"((\\<lambda>n. eln (e2ennreal (eexp (u n)))) \\<longlongrightarrow> eln (e2ennreal (eexp l))) F\"\n    by (intro tendsto_intros H)\n  then show \"(u \\<longlongrightarrow> l) F\"\n    unfolding eexp_def by auto\nnext\n  assume \"(u \\<longlongrightarrow> l) F\"\n  then show \"((\\<lambda>n. eexp(u n)) \\<longlongrightarrow> eexp l) F\"\n    using eexp_continuous by (metis UNIV_I continuous_on tendsto_compose)\nqed\n\nlemma eexp_tendsto [tendsto_intros]:\n  assumes \"((\\<lambda>n. u n) \\<longlongrightarrow> l) F\"\n  shows \"((\\<lambda>n. eexp(u n)) \\<longlongrightarrow> eexp l) F\"\nusing assms by auto\n\nlemma eexp_add_mult:\n  assumes \"\\<not>((a = \\<infinity> \\<and> b = -\\<infinity>) \\<or> (a = -\\<infinity> \\<and> b = \\<infinity>))\"\n  shows \"eexp(a+b) = eexp a * eexp b\"\nusing ennexp_add_mult[OF assms] unfolding eexp_def by (simp add: times_ennreal.rep_eq)\n\nlemma eexp_ereal [simp]:\n  \"eexp(ereal x) = ereal(exp x)\"\nby (simp add: eexp_def)\n\nend (*of theory Eexp_Eln*)\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/Eexp_Eln.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8596637469145054, "lm_q2_score": 0.8670357701094303, "lm_q1q2_score": 0.7453592188411766}}
{"text": "section \\<open>Counterclockwise\\<close>\ntheory Counterclockwise\nimports \"~~/src/HOL/Analysis/Analysis\"\nbegin\ntext \\<open>\\label{sec:counterclockwise}\\<close>\n\nsubsection \\<open>Auxiliary Lemmas\\<close>\n\nlemma convex3_alt:\n  fixes x y z::\"'a::real_vector\"\n  assumes \"0 \\<le> a\" \"0 \\<le> b\" \"0 \\<le> c\" \"a + b + c = 1\"\n  obtains u v  where \"a *\\<^sub>R x + b *\\<^sub>R y + c *\\<^sub>R z = x + u *\\<^sub>R (y - x) + v *\\<^sub>R (z - x)\"\n    and \"0 \\<le> u\" \"0 \\<le> v\" \"u + v \\<le> 1\"\nproof -\n  from convex_hull_3[of x y z] have \"a *\\<^sub>R x + b *\\<^sub>R y + c *\\<^sub>R z \\<in> convex hull {x, y, z}\"\n    using assms by auto\n  also note convex_hull_3_alt\n  finally obtain u v where \"a *\\<^sub>R x + b *\\<^sub>R y + c *\\<^sub>R z = x + u *\\<^sub>R (y - x) + v *\\<^sub>R (z - x)\"\n    and uv: \"0 \\<le> u\" \"0 \\<le> v\" \"u + v \\<le> 1\"\n    by auto\n  thus ?thesis ..\nqed\n\nlemma (in ordered_ab_group_add) add_nonpos_eq_0_iff:\n  assumes x: \"0 \\<ge> x\" and y: \"0 \\<ge> y\"\n  shows \"x + y = 0 \\<longleftrightarrow> x = 0 \\<and> y = 0\"\nproof -\n  from add_nonneg_eq_0_iff[of \"-x\" \"-y\"] assms\n  have \"- (x + y) = 0 \\<longleftrightarrow> - x = 0 \\<and> - y = 0\"\n    by simp\n  also have \"(- (x + y) = 0) = (x + y = 0)\" unfolding neg_equal_0_iff_equal ..\n  finally show ?thesis by simp\nqed\n\nlemma sum_nonpos_eq_0_iff:\n  fixes f :: \"'a \\<Rightarrow> 'b::ordered_ab_group_add\"\n  shows \"\\<lbrakk>finite A; \\<forall>x\\<in>A. f x \\<le> 0\\<rbrakk> \\<Longrightarrow> sum f A = 0 \\<longleftrightarrow> (\\<forall>x\\<in>A. f x = 0)\"\n  by (induct set: finite) (simp_all add: add_nonpos_eq_0_iff sum_nonpos)\n\nlemma fold_if_in_set:\n  \"fold (\\<lambda>x m. if P x m then x else m) xs x \\<in> set (x#xs)\"\n  by (induct xs arbitrary: x) auto\n\nsubsection \\<open>Sort Elements of a List\\<close>\n\nlocale linorder_list0 = fixes LE::\"'a \\<Rightarrow> 'a \\<Rightarrow> bool\"\nbegin\n\ndefinition \"MIN a b = (if LE a b then a else b)\"\n\nlemma MIN_in[simp]: \"x \\<in> S \\<Longrightarrow> y \\<in> S \\<Longrightarrow> MIN x y \\<in> S\"\n  by (auto simp: MIN_def)\n\nlemma fold_min_eqI1: \"fold MIN ys y \\<notin> set ys \\<Longrightarrow> fold MIN ys y = y\"\n  using fold_if_in_set[of _ ys y]\n  by (auto simp: MIN_def[abs_def])\n\nfunction selsort where\n  \"selsort [] = []\"\n| \"selsort (y#ys) = (let\n      xm = fold MIN ys y;\n      xs' = List.remove1 xm (y#ys)\n    in (xm#selsort xs'))\"\n  by pat_completeness auto\ntermination\n  by (relation \"Wellfounded.measure length\")\n    (auto simp: length_remove1 intro!: fold_min_eqI1 dest!: length_pos_if_in_set)\n\nlemma in_set_selsort_eq: \"x \\<in> set (selsort xs) \\<longleftrightarrow> x \\<in> (set xs)\"\n  by (induct rule: selsort.induct) (auto simp: Let_def intro!: fold_min_eqI1)\n\nlemma set_selsort[simp]: \"set (selsort xs) = set xs\"\n  using in_set_selsort_eq by blast\n\nlemma length_selsort[simp]: \"length (selsort xs) = length xs\"\nproof (induct xs rule: selsort.induct)\n  case (2 x xs)\n  from 2[OF refl refl]\n  show ?case\n    unfolding selsort.simps\n    by (auto simp: Let_def length_remove1\n      simp del: selsort.simps split: if_split_asm\n      intro!: Suc_pred\n      dest!: fold_min_eqI1)\nqed simp\n\nlemma distinct_selsort[simp]: \"distinct (selsort xs) = distinct xs\"\n  by (auto intro!: card_distinct dest!: distinct_card)\n\nlemma selsort_eq_empty_iff[simp]: \"selsort xs = [] \\<longleftrightarrow> xs = []\"\n  by (cases xs) (auto simp: Let_def)\n\n\ninductive sortedP :: \"'a list \\<Rightarrow> bool\" where\n  Nil: \"sortedP []\"\n| Cons: \"\\<forall>y\\<in>set ys. LE x y \\<Longrightarrow> sortedP ys \\<Longrightarrow> sortedP (x # ys)\"\n\ninductive_cases\n  sortedP_Nil: \"sortedP []\" and\n  sortedP_Cons: \"sortedP (x#xs)\"\ninductive_simps\n  sortedP_Nil_iff: \"sortedP Nil\" and\n  sortedP_Cons_iff: \"sortedP (Cons x xs)\"\n\nlemma sortedP_append_iff:\n  \"sortedP (xs @ ys) = (sortedP xs & sortedP ys & (\\<forall>x \\<in> set xs. \\<forall>y \\<in> set ys. LE x y))\"\n  by (induct xs) (auto intro!: Nil Cons elim!: sortedP_Cons)\n\nlemma sortedP_appendI:\n  \"sortedP xs \\<Longrightarrow> sortedP ys \\<Longrightarrow> (\\<And>x y. x \\<in> set xs \\<Longrightarrow> y \\<in> set ys \\<Longrightarrow> LE x y) \\<Longrightarrow> sortedP (xs @ ys)\"\n  by (induct xs) (auto intro!: Nil Cons elim!: sortedP_Cons)\n\nlemma sorted_nth_less: \"sortedP xs \\<Longrightarrow> i < j \\<Longrightarrow> j < length xs \\<Longrightarrow> LE (xs ! i) (xs ! j)\"\n  by (induct xs arbitrary: i j) (auto simp: nth_Cons split: nat.split elim!: sortedP_Cons)\n\nlemma sorted_butlastI[intro, simp]: \"sortedP xs \\<Longrightarrow> sortedP (butlast xs)\"\n  by (induct xs) (auto simp: elim!: sortedP_Cons intro!: sortedP.Cons dest!: in_set_butlastD)\n\nlemma sortedP_right_of_append1:\n  assumes \"sortedP (zs@[z])\"\n  assumes \"y \\<in> set zs\"\n  shows \"LE y z\"\n  using assms\n  by (induct zs arbitrary: y z) (auto elim!: sortedP_Cons)\n\nlemma sortedP_right_of_last:\n  assumes \"sortedP zs\"\n  assumes \"y \\<in> set zs\" \"y \\<noteq> last zs\"\n  shows \"LE y (last zs)\"\n  using assms\n  apply (intro sortedP_right_of_append1[of \"butlast zs\" \"last zs\" y])\n  subgoal by (metis append_is_Nil_conv list.distinct(1) snoc_eq_iff_butlast split_list)\n  subgoal by (metis List.insert_def append_butlast_last_id insert_Nil list.distinct(1) rotate1.simps(2)\n    set_ConsD set_rotate1)\n  done\n\nlemma selsort_singleton_iff: \"selsort xs = [x] \\<longleftrightarrow> xs = [x]\"\n  by (induct xs) (auto simp: Let_def)\n\nlemma hd_last_sorted:\n  assumes \"sortedP xs\" \"length xs > 1\"\n  shows \"LE (hd xs) (last xs)\"\nproof (cases xs)\n  case (Cons y ys)\n  note ys = this\n  thus ?thesis\n    using ys assms\n    by (auto elim!: sortedP_Cons)\nqed (insert assms, simp)\n\nend\n\nlemma (in comm_monoid_add) sum_list_distinct_selsort:\n  assumes \"distinct xs\"\n  shows \"sum_list (linorder_list0.selsort LE xs) = sum_list xs\"\n  using assms\n  apply (simp add: distinct_sum_list_conv_Sum linorder_list0.distinct_selsort)\n  apply (rule sum.cong)\n  subgoal by (simp add: linorder_list0.set_selsort)\n  subgoal by simp\n  done\n\ndeclare linorder_list0.sortedP_Nil_iff[code]\n  linorder_list0.sortedP_Cons_iff[code]\n  linorder_list0.selsort.simps[code]\n  linorder_list0.MIN_def[code]\n\nlocale linorder_list = linorder_list0 LE for LE::\"'a::ab_group_add \\<Rightarrow> _\" +\n  fixes S\n  assumes order_refl: \"a \\<in> S \\<Longrightarrow> LE a a\"\n  assumes trans': \"a \\<in> S \\<Longrightarrow> b \\<in> S \\<Longrightarrow> c \\<in> S \\<Longrightarrow> a \\<noteq> b \\<Longrightarrow> b \\<noteq> c \\<Longrightarrow> a \\<noteq> c \\<Longrightarrow>\n    LE a b \\<Longrightarrow> LE b c \\<Longrightarrow> LE a c\"\n  assumes antisym: \"a \\<in> S \\<Longrightarrow> b \\<in> S \\<Longrightarrow> LE a b \\<Longrightarrow> LE b a \\<Longrightarrow> a = b\"\n  assumes linear': \"a \\<in> S \\<Longrightarrow> b \\<in> S \\<Longrightarrow> a \\<noteq> b \\<Longrightarrow> LE a b \\<or> LE b a\"\nbegin\n\nlemma trans: \"a \\<in> S \\<Longrightarrow> b \\<in> S \\<Longrightarrow> c \\<in> S \\<Longrightarrow> LE a b \\<Longrightarrow> LE b c \\<Longrightarrow> LE a c\"\n  by (cases \"a = b\" \"b = c\" \"a = c\"\n    rule: bool.exhaust[case_product bool.exhaust[case_product bool.exhaust]])\n    (auto simp: order_refl intro: trans')\n\nlemma linear: \"a \\<in> S \\<Longrightarrow> b \\<in> S \\<Longrightarrow> LE a b \\<or> LE b a\"\n  by (cases \"a = b\") (auto simp: linear' order_refl)\n\nlemma MIN_le1: \"w \\<in> S \\<Longrightarrow> y \\<in> S \\<Longrightarrow> LE (MIN w y) y\"\n  and MIN_le2: \"w \\<in> S \\<Longrightarrow> y \\<in> S \\<Longrightarrow> LE (MIN w y) w\"\n  using linear\n  by (auto simp: MIN_def refl)\n\nlemma fold_min:\n  assumes \"set xs \\<subseteq> S\"\n  shows \"list_all (\\<lambda>y. LE (fold MIN (tl xs) (hd xs)) y) xs\"\nproof (cases xs)\n  case (Cons y ys)\n  hence subset: \"set (y#ys) \\<subseteq> S\" using assms\n    by auto\n  show ?thesis\n    unfolding Cons list.sel\n    using subset\n  proof (induct ys arbitrary: y)\n    case (Cons z zs)\n    hence IH: \"\\<And>y. y \\<in> S \\<Longrightarrow> list_all (LE (fold MIN zs y)) (y # zs)\"\n      by simp\n    let ?f = \"fold MIN zs (MIN z y)\"\n    have \"?f \\<in> set ((MIN z y)#zs)\"\n      unfolding MIN_def[abs_def]\n      by (rule fold_if_in_set)\n    also have \"\\<dots> \\<subseteq> S\" using Cons.prems by auto\n    finally have \"?f \\<in> S\" .\n\n    have \"LE ?f (MIN z y)\"\n      using IH[of \"MIN z y\"] Cons.prems\n      by auto\n    moreover have \"LE (MIN z y) y\" \"LE (MIN z y) z\" using Cons.prems\n      by (auto intro!: MIN_le1 MIN_le2)\n    ultimately have \"LE ?f y\" \"LE ?f z\" using Cons.prems \\<open>?f \\<in> S\\<close>\n      by (auto intro!: trans[of ?f \"MIN z y\"])\n    thus ?case\n      using IH[of \"MIN z y\"]\n      using Cons.prems\n      by auto\n  qed (simp add: order_refl)\nqed simp\n\nlemma\n  sortedP_selsort:\n  assumes \"set xs \\<subseteq> S\"\n  shows \"sortedP (selsort xs)\"\n  using assms\nproof (induction xs rule: selsort.induct)\n  case (2 z zs)\n  from this fold_min[of \"z#zs\"]\n  show ?case\n    by (cases \"fold MIN zs z = z\")\n      (fastforce simp: list_all_iff Let_def\n        simp del: remove1.simps\n        intro: Cons intro!: 2(1)[OF refl refl]\n        dest!: set_rev_mp[OF _ set_remove1_subset])+\nqed (auto intro!: Nil)\n\nend\n\n\nsubsection \\<open>Abstract CCW Systems\\<close>\n\nlocale ccw_system0 =\n  fixes ccw::\"'a \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> bool\"\n    and S::\"'a set\"\nbegin\n\nabbreviation \"indelta t p q r \\<equiv> ccw t q r \\<and> ccw p t r \\<and> ccw p q t\"\nabbreviation \"insquare p q r s \\<equiv> ccw p q r \\<and> ccw q r s \\<and> ccw r s p \\<and> ccw s p q\"\n\nend\n\nabbreviation \"distinct3 p q r \\<equiv> \\<not>(p = q \\<or> p = r \\<or> q = r)\"\nabbreviation \"distinct4 p q r s \\<equiv> \\<not>(p = q \\<or> p = r \\<or> p = s \\<or> \\<not> distinct3 q r s)\"\nabbreviation \"distinct5 p q r s t \\<equiv> \\<not>(p = q \\<or> p = r \\<or> p = s \\<or> p = t \\<or> \\<not> distinct4 q r s t)\"\n\nabbreviation \"in3 S p q r \\<equiv> p \\<in> S \\<and> q \\<in> S \\<and> r \\<in> S\"\nabbreviation \"in4 S p q r s \\<equiv> in3 S p q r \\<and> s \\<in> S\"\nabbreviation \"in5 S p q r s t \\<equiv> in4 S p q r s \\<and> t \\<in> S\"\n\nlocale ccw_system12 = ccw_system0 +\n  assumes cyclic: \"ccw p q r \\<Longrightarrow> ccw q r p\"\n  assumes ccw_antisym: \"distinct3 p q r \\<Longrightarrow> in3 S p q r \\<Longrightarrow> ccw p q r \\<Longrightarrow> \\<not> ccw p r q\"\n\nlocale ccw_system123 = ccw_system12 +\n  assumes nondegenerate: \"distinct3 p q r \\<Longrightarrow> in3 S p q r \\<Longrightarrow> ccw p q r \\<or> ccw p r q\"\nbegin\n\nlemma not_ccw_eq: \"distinct3 p q r \\<Longrightarrow> in3 S p q r \\<Longrightarrow> \\<not> ccw p q r \\<longleftrightarrow> ccw p r q\"\n  using ccw_antisym nondegenerate by blast\n\nend\n\nlocale ccw_system4 = ccw_system123 +\n  assumes interior:\n    \"distinct4 p q r t \\<Longrightarrow> in4 S p q r t \\<Longrightarrow> ccw t q r \\<Longrightarrow> ccw p t r \\<Longrightarrow> ccw p q t \\<Longrightarrow> ccw p q r\"\nbegin\n\nlemma interior':\n  \"distinct4 p q r t \\<Longrightarrow> in4 S p q r t \\<Longrightarrow> ccw p q t \\<Longrightarrow> ccw q r t \\<Longrightarrow> ccw r p t \\<Longrightarrow> ccw p q r\"\n  by (metis ccw_antisym cyclic interior nondegenerate)\n\nend\n\nlocale ccw_system1235' = ccw_system123 +\n  assumes dual_transitive:\n    \"distinct5 p q r s t \\<Longrightarrow> in5 S p q r s t \\<Longrightarrow>\n      ccw s t p \\<Longrightarrow> ccw s t q \\<Longrightarrow> ccw s t r \\<Longrightarrow> ccw t p q \\<Longrightarrow> ccw t q r \\<Longrightarrow> ccw t p r\"\n\nlocale ccw_system1235 = ccw_system123 +\n  assumes transitive: \"distinct5 p q r s t \\<Longrightarrow> in5 S p q r s t \\<Longrightarrow>\n    ccw t s p \\<Longrightarrow> ccw t s q \\<Longrightarrow> ccw t s r \\<Longrightarrow> ccw t p q \\<Longrightarrow> ccw t q r \\<Longrightarrow> ccw t p r\"\nbegin\n\nlemmas ccw_axioms = cyclic nondegenerate ccw_antisym transitive\n\nsublocale ccw_system1235'\nproof (unfold_locales, rule ccontr, goal_cases)\n  case prems: (1 p q r s t)\n  hence \"ccw s p q \\<Longrightarrow> ccw s r p\"\n    by (metis ccw_axioms prems)\n  moreover\n  have \"ccw s r p \\<Longrightarrow> ccw s q r\"\n    by (metis ccw_axioms prems)\n  moreover\n  have \"ccw s q r \\<Longrightarrow> ccw s p q\"\n    by (metis ccw_axioms prems)\n  ultimately\n  have \"ccw s p q \\<and> ccw s r p \\<and> ccw s q r \\<or> ccw s q p \\<and> ccw s p r \\<and> ccw s r q\"\n    by (metis ccw_axioms prems)\n  thus False\n    by (metis ccw_axioms prems)\nqed\n\nend\n\nlocale ccw_system = ccw_system1235 + ccw_system4\n\nend\n", "meta": {"author": "rizaldialbert", "repo": "overtaking", "sha": "0e76426d75f791635cd9e23b8e07669b7ce61a81", "save_path": "github-repos/isabelle/rizaldialbert-overtaking", "path": "github-repos/isabelle/rizaldialbert-overtaking/overtaking-0e76426d75f791635cd9e23b8e07669b7ce61a81/Affine_Arithmetic/Counterclockwise.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8670357529306639, "lm_q2_score": 0.8596637577007394, "lm_q1q2_score": 0.7453592134252645}}
{"text": "\n\n(*<*) theory ex2_3 imports Main begin (*>*)\n\ntext {* Let's work with skeletons of binary trees where neither the leaves\n(``tip'') nor the nodes contain any information: *}\n\ndatatype tree = Tp | Nd tree tree\n\ntext {* Define a function @{term tips} that counts the tips of a tree, and a\nfunction @{term height} that computes the height of a tree. *}\nprimrec tips ::\"tree \\<Rightarrow> nat\"\n  where \"tips Tp=1\"\n  |\"tips (Nd x y) = (tips x)+ tips y\" \nprimrec height ::\"tree \\<Rightarrow> nat\"\n  where \"height Tp=0\"\n  |\"height (Nd x y) = 1+  max(height x) (height y)\" \n\ntext {* Complete binary trees of a given height are generated as follows: *}\n\nprimrec cbt :: \"nat \\<Rightarrow> tree\" where\n\"cbt 0       = Tp\" |\n\"cbt (Suc n) = Nd (cbt n) (cbt n)\"\n\ntext {* We will now focus on these complete binary trees.\n\nInstead of generating complete binary trees, we can also \\emph{test} if a\nbinary tree is complete.  Define a function @{term \"iscbt f\"} (where @{term f}\nis a function on trees) that checks for completeness:  @{term Tp} is complete,\nand @{term\"Nd l r\"} is complete iff @{term l} and @{term r} are complete and\n@{prop\"f l = f r\"}. *}\n\nprimrec iscbt  ::\"(tree\\<Rightarrow>nat) \\<Rightarrow>tree \\<Rightarrow> bool\" where\n\"iscbt f Tp = True\"\n|\"iscbt f (Nd x y) = ((f x = f y) \\<and>(iscbt f x)\\<and>(iscbt f y))\" \n\n\n\n\ntheorem one:\"iscbt height t = iscbt tips t\"\n  apply (induct t)\n  apply auto\n  done\nlemma [simp]: \"iscbt tips t --> tips t =1+size t\"\n  apply (induct t)\n  apply auto\n  done \ntheorem two:\"iscbt tips t = iscbt size t\"\n  apply (induct t)\n  apply auto\n  done\n\ntheorem \"iscbt height t = iscbt size t\"\n  apply( simp add:one two)\n  done\n\ntheorem \"iscbt height t = (t = cbt (height t))\"\n  apply (induct t)\n   apply auto\n  done\n\ntext {* We now have 3 functions on trees, namely @{term tips}, @{term height}\nand @{term size}.  The latter is defined automatically -- look it up in the\ntutorial.  Thus we also have 3 kinds of completeness:  complete wrt.\\ @{term\ntips}, complete wrt.\\ @{term height} and complete wrt.\\ @{term size}.  Show\nthat\n\\begin{itemize}\n\\item the 3 notions are the same (e.g.\\ @{prop \"iscbt tips t = iscbt size t\"}),\n      and\n\\item the 3 notions describe exactly the trees generated by @{term cbt}:  the\n      result of @{term cbt} is complete (in the sense of @{term iscbt}, wrt.\\\n      any function on trees), and if a tree is complete in the sense of @{term\n      iscbt}, it is the result of @{term cbt} (applied to a suitable number~--\n      which one?).\n\\end{itemize}\n\nHints:\n\\begin{itemize}\n\\item Work out and prove suitable relationships between @{term tips}, @{term\n      height} und @{term size}.\n\n\\item If you need lemmas dealing only with the basic arithmetic operations\n      (@{text\"+\"}, @{text\"*\"}, @{text\"^\"} etc), you may ``prove'' them with the\n      command @{text sorry}, if neither @{text arith} nor you can find a proof.\n      Not @{text \"apply sorry\"}, just @{text sorry}.\n\n\\item You do not need to show that every notion is equal to every other notion.\n      It suffices to show that $A = C$ und $B = C$ -- $A = B$ is a trivial\n      consequence.  However, the difficulty of the proof will depend on which\n      of the equivalences you prove.\n\n\\item There is @{text\"\\<and>\"} and @{text\"\\<longrightarrow>\"}.\n\\end{itemize} *}\n\n\ntext {* Find a function @{term f} such that @{term \"iscbt f\"} is different from\n@{term \"iscbt size\"}. *}\n\ntheorem \"iscbt height t = iscbt (\\<lambda> x. 0) t \"\n  quickcheck 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/ex2_3.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.867035763237924, "lm_q2_score": 0.8596637469145054, "lm_q1q2_score": 0.7453592129339918}}
{"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> \"greatest fixed point\"\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": "SEL4PROJ", "repo": "jormungand", "sha": "bad97f9817b4034cd705cd295a1f86af880a7631", "save_path": "github-repos/isabelle/SEL4PROJ-jormungand", "path": "github-repos/isabelle/SEL4PROJ-jormungand/jormungand-bad97f9817b4034cd705cd295a1f86af880a7631/case_study/isabelle/src/CCL/Gfp.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213718636752, "lm_q2_score": 0.8289388019824946, "lm_q1q2_score": 0.745316592829532}}
{"text": "(* Title:  Digraph_Component.thy\n   Author: Lars Noschinski, TU M\u00fcnchen\n*)\n\ntheory Digraph_Component\nimports\n  Digraph\n  Arc_Walk\n  Pair_Digraph\nbegin\n\nsection {* Components of (Symmetric) Digraphs *}\n\ndefinition compatible :: \"('a,'b) pre_digraph \\<Rightarrow> ('a,'b) pre_digraph \\<Rightarrow> bool\" where\n  \"compatible G H \\<equiv> tail G = tail H \\<and> head G = head H\"\n\n(* Require @{term \"wf_digraph G\"}? *)\ndefinition subgraph :: \"('a,'b) pre_digraph \\<Rightarrow> ('a,'b) pre_digraph \\<Rightarrow> bool\" where\n  \"subgraph H G \\<equiv> verts H \\<subseteq> verts G \\<and> arcs H \\<subseteq> arcs G \\<and> wf_digraph G \\<and> wf_digraph H \\<and> compatible G H\"\n\ndefinition induced_subgraph :: \"('a,'b) pre_digraph \\<Rightarrow> ('a,'b) pre_digraph \\<Rightarrow> bool\" where\n  \"induced_subgraph H G \\<equiv> subgraph H G \\<and> arcs H = {e \\<in> arcs G. tail G e \\<in> verts H \\<and> head G e \\<in> verts H}\"\n\ndefinition spanning :: \"('a,'b) pre_digraph \\<Rightarrow> ('a,'b) pre_digraph \\<Rightarrow> bool\" where\n  \"spanning H G \\<equiv> subgraph H G \\<and> verts G = verts H\"\n\ndefinition strongly_connected :: \"('a,'b) pre_digraph \\<Rightarrow> bool\" where\n  \"strongly_connected G \\<equiv> verts G \\<noteq> {} \\<and> (\\<forall>u \\<in> verts G. \\<forall>v \\<in> verts G. u \\<rightarrow>\\<^sup>*\\<^bsub>G\\<^esub> v)\"\n\n\ntext {*\n  The following function computes underlying symmetric graph of a digraph\n  and removes parallel arcs.\n*}\n\ndefinition mk_symmetric :: \"('a,'b) pre_digraph \\<Rightarrow> 'a pair_pre_digraph\" where\n  \"mk_symmetric G \\<equiv> \\<lparr> pverts = verts G, parcs = \\<Union>e\\<in>arcs G. {(tail G e, head G e), (head G e, tail G e)}\\<rparr>\"\n\ndefinition connected :: \"('a,'b) pre_digraph \\<Rightarrow> bool\" where\n  \"connected G \\<equiv> strongly_connected (mk_symmetric G)\"\n\ndefinition forest :: \"('a,'b) pre_digraph \\<Rightarrow> bool\" where\n  \"forest G \\<equiv> \\<not>(\\<exists>p. pre_digraph.cycle G p)\"\n\ndefinition tree :: \"('a,'b) pre_digraph \\<Rightarrow> bool\" where\n  \"tree G \\<equiv> connected G \\<and> forest G\"\n\ndefinition spanning_tree :: \"('a,'b) pre_digraph \\<Rightarrow> ('a,'b) pre_digraph \\<Rightarrow> bool\" where\n  \"spanning_tree H G \\<equiv> tree H \\<and> spanning H G\"\n\ndefinition (in pre_digraph) sccs :: \"('a,'b) pre_digraph set\" where\n  \"sccs \\<equiv> {H. induced_subgraph H G \\<and> strongly_connected H \\<and> \\<not>(\\<exists>H'. induced_subgraph H' G\n      \\<and> strongly_connected H' \\<and> verts H \\<subset> verts H')}\"\n\ndefinition union :: \"('a,'b) pre_digraph \\<Rightarrow> ('a,'b) pre_digraph \\<Rightarrow> ('a,'b) pre_digraph\" where\n  \"union G H \\<equiv> \\<lparr> verts = verts G \\<union> verts H, arcs = arcs G \\<union> arcs H, tail = tail G, head = head G\\<rparr>\"\n\ndefinition (in pre_digraph) Union :: \"('a,'b) pre_digraph set \\<Rightarrow> ('a,'b) pre_digraph\" where\n  \"Union gs = \\<lparr> verts = (\\<Union>G \\<in> gs. verts G), arcs = (\\<Union>G \\<in> gs. arcs G),\n    tail = tail G , head = head G  \\<rparr>\"\n\n\n\nsubsection {* Compatible Graphs *}\n\nlemma compatible_tail:\n  assumes \"compatible G H\" shows \"tail G = tail H\"\n  using assms by (simp add: fun_eq_iff compatible_def)\n\nlemma compatible_head:\n  assumes \"compatible G H\" shows \"head G = head H\"\n  using assms by (simp add: fun_eq_iff compatible_def)\n\nlemma compatible_cas:\n  assumes \"compatible G H\" shows \"pre_digraph.cas G = pre_digraph.cas H\"\nproof (unfold fun_eq_iff, intro allI)\n  fix u es v show \"pre_digraph.cas G u es v = pre_digraph.cas H u es v\"\n    using assms\n    by (induct es arbitrary: u)\n       (simp_all add: pre_digraph.cas.simps compatible_head compatible_tail)\nqed\n\nlemma compatible_awalk_verts:\n  assumes \"compatible G H\" shows \"pre_digraph.awalk_verts G = pre_digraph.awalk_verts H\"\nproof (unfold fun_eq_iff, intro allI)\n  fix u es show \"pre_digraph.awalk_verts G u es = pre_digraph.awalk_verts H u es\"\n    using assms\n    by (induct es arbitrary: u)\n       (simp_all add: pre_digraph.awalk_verts.simps compatible_head compatible_tail)\nqed\n\nlemma compatibleI_with_proj[intro]:\n  shows \"compatible (with_proj G) (with_proj H)\"\n  by (auto simp: compatible_def)\n\n\n\nsubsection {* Basic lemmas *}\n\nlemma (in sym_digraph) graph_symmetric:\n  shows \"(u,v) \\<in> arcs_ends G \\<Longrightarrow> (v,u) \\<in> arcs_ends G\"\n  using assms sym_arcs by (auto simp add: symmetric_def sym_def)\n\nlemma strongly_connectedI[intro]:\n  assumes \"verts G \\<noteq> {}\" \"\\<And>u v. u \\<in> verts G \\<Longrightarrow> v \\<in> verts G \\<Longrightarrow> u \\<rightarrow>\\<^sup>*\\<^bsub>G\\<^esub> v\"\n  shows \"strongly_connected G\"\nusing assms by (simp add: strongly_connected_def)\n\nlemma strongly_connectedE[elim]:\n  assumes \"strongly_connected G\"\n  assumes \"(\\<And>u v. u \\<in> verts G \\<and> v \\<in> verts G \\<Longrightarrow> u \\<rightarrow>\\<^sup>*\\<^bsub>G\\<^esub> v) \\<Longrightarrow> P\"\n  shows \"P\"\nusing assms by (auto simp add: strongly_connected_def)\n\nlemma subgraph_imp_subverts:\n  assumes \"subgraph H G\"\n  shows \"verts H \\<subseteq> verts G\"\nusing assms by (simp add: subgraph_def)\n\nlemma induced_imp_subgraph:\n  assumes \"induced_subgraph H G\"\n  shows \"subgraph H G\"\nusing assms by (simp add: induced_subgraph_def)\n\nlemma (in pre_digraph) in_sccs_imp_induced:\n  assumes \"c \\<in> sccs\"\n  shows \"induced_subgraph c G\"\nusing assms by (auto simp: sccs_def)\n\nlemma spanning_tree_imp_tree[dest]:\n  assumes \"spanning_tree H G\"\n  shows \"tree H\"\nusing assms by (simp add: spanning_tree_def)\n\nlemma tree_imp_connected[dest]:\n  assumes \"tree G\"\n  shows \"connected G\"\nusing assms by (simp add: tree_def)\n\nlemma spanning_treeI[intro]:\n  assumes \"spanning H G\"\n  assumes \"tree H\"\n  shows \"spanning_tree H G\"\nusing assms by (simp add: spanning_tree_def)\n\nlemma spanning_treeE[elim]:\n  assumes \"spanning_tree H G\"\n  assumes \"tree H \\<and> spanning H G \\<Longrightarrow> P\"\n  shows \"P\"\nusing assms by (simp add: spanning_tree_def)\n\nlemma spanningE[elim]:\n  assumes \"spanning H G\"\n  assumes \"subgraph H G \\<and> verts G = verts H \\<Longrightarrow> P\"\n  shows \"P\"\nusing assms by (simp add: spanning_def)\n\nlemma (in pre_digraph) in_sccsI[intro]:\n  assumes \"induced_subgraph c G\"\n  assumes \"strongly_connected c\"\n  assumes \"\\<not>(\\<exists>c'. induced_subgraph c' G \\<and> strongly_connected c' \\<and>\n    verts c \\<subset> verts c')\"\n  shows \"c \\<in> sccs\"\nusing assms by (auto simp add: sccs_def)\n\nlemma (in pre_digraph) in_sccsE[elim]:\n  assumes \"c \\<in> sccs\"\n  assumes \"induced_subgraph c G \\<Longrightarrow> strongly_connected c \\<Longrightarrow> \\<not> (\\<exists>d.\n    induced_subgraph d G \\<and> strongly_connected d \\<and> verts c \\<subset> verts d) \\<Longrightarrow> P\"\n  shows \"P\"\nusing assms by (simp add: sccs_def)\n\nlemma subgraphI:\n  assumes \"verts H \\<subseteq> verts G\"\n  assumes \"arcs H \\<subseteq> arcs G\"\n  assumes \"compatible G H\"\n  assumes \"wf_digraph H\"\n  assumes \"wf_digraph G\"\n  shows \"subgraph H G\"\nusing assms by (auto simp add: subgraph_def)\n\nlemma subgraphE[elim]:\n  assumes \"subgraph H G\"\n  obtains \"verts H \\<subseteq> verts G\" \"arcs H \\<subseteq> arcs G\" \"compatible G H\" \"wf_digraph H\" \"wf_digraph G\"\nusing assms by (simp add: subgraph_def)\n\nlemma induced_subgraphI[intro]:\n  assumes \"subgraph H G\"\n  assumes \"arcs H = {e \\<in> arcs G. tail G e \\<in> verts H \\<and> head G e \\<in> verts H}\"\n  shows \"induced_subgraph H G\"\nusing assms unfolding induced_subgraph_def by safe\n\nlemma induced_subgraphE[elim]:\n  assumes \"induced_subgraph H G\"\n  assumes \"\\<lbrakk>subgraph H G; arcs H = {e \\<in> arcs G. tail G e \\<in> verts H \\<and> head G e \\<in> verts H}\\<rbrakk> \\<Longrightarrow> P\"\n  shows \"P\"\nusing assms by (auto simp add: induced_subgraph_def)\n\nlemma pverts_mk_symmetric[simp]: \"pverts (mk_symmetric G) = verts G\"\n  and parcs_mk_symmetric:\n    \"parcs (mk_symmetric G) = (\\<Union>e\\<in>arcs G. {(tail G e, head G e), (head G e, tail G e)})\"\n  by (auto simp: mk_symmetric_def arcs_ends_conv image_UN)\n\nlemma arcs_ends_mono:\n  assumes \"subgraph H G\"\n  shows \"arcs_ends H \\<subseteq> arcs_ends G\"\n  using assms by (auto simp add: subgraph_def arcs_ends_conv compatible_tail compatible_head)\n\nlemma (in wf_digraph) subgraph_refl: \"subgraph G G\"\n  by (auto simp: subgraph_def compatible_def) unfold_locales\n\n\n\n\nsubsection {* The underlying symmetric graph of a digraph *}\n\nlemma (in wf_digraph) wellformed_mk_symmetric[intro]: \"pair_wf_digraph (mk_symmetric G)\"\n  by unfold_locales (auto simp: parcs_mk_symmetric)\n\nlemma (in fin_digraph) pair_fin_digraph_mk_symmetric[intro]: \"pair_fin_digraph (mk_symmetric G)\"\nproof -\n  have \"finite ((\\<lambda>(a,b). (b,a)) ` arcs_ends G)\" (is \"finite ?X\") by (auto simp: arcs_ends_conv)\n  also have \"?X = {(a, b). (b, a) \\<in> arcs_ends G}\" by auto\n  finally have X: \"finite ...\" .\n  then show ?thesis\n    by unfold_locales (auto simp: mk_symmetric_def arcs_ends_conv)\nqed\n\nlemma (in digraph) digraph_mk_symmetric[intro]: \"pair_digraph (mk_symmetric G)\"\nproof -\n  have \"finite ((\\<lambda>(a,b). (b,a)) ` arcs_ends G)\" (is \"finite ?X\") by (auto simp: arcs_ends_conv)\n  also have \"?X = {(a, b). (b, a) \\<in> arcs_ends G}\" by auto\n  finally have \"finite ...\" .\n  then show ?thesis\n    by unfold_locales (auto simp: mk_symmetric_def arc_to_ends_def dest: no_loops)\nqed\n\nlemma (in wf_digraph) reachable_mk_symmetricI:\n  assumes \"u \\<rightarrow>\\<^sup>* v\" shows \"u \\<rightarrow>\\<^sup>*\\<^bsub>mk_symmetric G\\<^esub> v\"\nproof -\n  have \"arcs_ends G \\<subseteq> parcs (mk_symmetric G)\"\n       \"(u, v) \\<in> rtrancl_on (pverts (mk_symmetric G)) (arcs_ends G)\"\n    using assms unfolding reachable_def by (auto simp: parcs_mk_symmetric)\n  then show ?thesis unfolding reachable_def by (auto intro: rtrancl_on_mono)\nqed\n\nlemma (in wf_digraph) adj_mk_symmetric_eq:\n  \"symmetric G \\<Longrightarrow> parcs (mk_symmetric G) = arcs_ends G\"\n  by (auto simp: parcs_mk_symmetric in_arcs_imp_in_arcs_ends arcs_ends_symmetric)\n\nlemma (in wf_digraph) reachable_mk_symmetric_eq:\n  assumes \"symmetric G\" shows \"u \\<rightarrow>\\<^sup>*\\<^bsub>mk_symmetric G\\<^esub> v \\<longleftrightarrow> u \\<rightarrow>\\<^sup>* v\" (is \"?L \\<longleftrightarrow> ?R\")\n  using adj_mk_symmetric_eq[OF assms] unfolding reachable_def by auto\n\nlemma (in wf_digraph) mk_symmetric_awalk_imp_awalk:\n  assumes sym: \"symmetric G\"\n  assumes walk: \"pre_digraph.awalk (mk_symmetric G) u p v\"\n  obtains q where \"awalk u q v\"\nproof -\n  interpret S: pair_wf_digraph \"mk_symmetric G\" ..\n  from walk have \"u \\<rightarrow>\\<^sup>*\\<^bsub>mk_symmetric G\\<^esub> v\"\n    by (simp only: S.reachable_awalk) rule\n  then have \"u \\<rightarrow>\\<^sup>* v\" by (simp only: reachable_mk_symmetric_eq[OF sym])\n  then show ?thesis by (auto simp: reachable_awalk intro: that)\nqed\n\nlemma symmetric_mk_symmetric:\n  \"symmetric (mk_symmetric G)\"\n  by (auto simp: symmetric_def parcs_mk_symmetric intro: symI)\n\n\n\nsubsection {* Subgraphs and Induced Subgraphs *}\n\nlemma subgraph_trans:\n  assumes \"subgraph G H\" \"subgraph H I\" shows \"subgraph G I\"\n  using assms by (auto simp: subgraph_def compatible_def)\n\ntext {*\n  The @{term digraph} and @{term fin_digraph} properties are preserved under\n  the (inverse) subgraph relation\n*}\nlemma (in fin_digraph) fin_digraph_subgraph:\n  assumes \"subgraph H G\" shows \"fin_digraph H\"\nproof (intro_locales)\n  from assms show \"wf_digraph H\" by auto\n\n  have HG: \"arcs H \\<subseteq> arcs G\" \"verts H \\<subseteq> verts G\"\n    using assms by auto\n  then have \"finite (verts H)\" \"finite (arcs H)\"\n    using finite_verts finite_arcs by (blast intro: finite_subset)+\n  then show \"fin_digraph_axioms H\"\n    by unfold_locales\nqed\n\nlemma (in digraph) digraph_subgraph:\n  assumes \"subgraph H G\" shows \"digraph H\"\nproof\n  fix e assume e: \"e \\<in> arcs H\"\n  with assms show \"tail H e \\<in> verts H\" \"head H e \\<in> verts H\"\n    by (auto simp: subgraph_def intro: wf_digraph.wellformed)\n  from e and assms have \"e \\<in> arcs H \\<inter> arcs G\" by auto\n  with assms show \"tail H e \\<noteq> head H e\"\n    using no_loops by (auto simp: subgraph_def compatible_def arc_to_ends_def)\nnext\n  have \"arcs H \\<subseteq> arcs G\" \"verts H \\<subseteq> verts G\" using assms by auto\n  then show \"finite (arcs H)\" \"finite (verts H)\"\n    using finite_verts finite_arcs by (blast intro: finite_subset)+\nnext\n  fix e1 e2 assume \"e1 \\<in> arcs H\" \"e2 \\<in> arcs H\"\n    and eq: \"arc_to_ends H e1 = arc_to_ends H e2\"\n  with assms have \"e1 \\<in> arcs H \\<inter> arcs G\" \"e2 \\<in> arcs H \\<inter> arcs G\"\n    by auto\n  with eq show \"e1 = e2\"\n    using no_multi_arcs assms\n    by (auto simp: subgraph_def compatible_def arc_to_ends_def)\nqed\n\nlemma (in pre_digraph) adj_mono:\n  assumes \"u \\<rightarrow>\\<^bsub>H\\<^esub> v\" \"subgraph H G\"\n  shows \"u \\<rightarrow> v\"\n  using assms by (blast dest: arcs_ends_mono)\n\nlemma (in pre_digraph) reachable_mono:\n  assumes walk: \"u \\<rightarrow>\\<^sup>*\\<^bsub>H\\<^esub> v\" and sub: \"subgraph H G\"\n  shows \"u \\<rightarrow>\\<^sup>* v\"\nproof -\n  have \"verts H \\<subseteq> verts G\" using sub by auto\n  with assms show ?thesis\n    unfolding reachable_def by (metis arcs_ends_mono rtrancl_on_mono)\nqed\n\n\ntext {*\n  Arc walks and paths are preserved under the subgraph relation.\n*}\nlemma (in wf_digraph) subgraph_awalk_imp_awalk:\n  assumes walk: \"pre_digraph.awalk H u p v\"\n  assumes sub: \"subgraph H G\"\n  shows \"awalk u p v\"\n  using assms by (auto simp: pre_digraph.awalk_def compatible_cas)\n\nlemma (in wf_digraph) subgraph_apath_imp_apath:\n  assumes path: \"pre_digraph.apath H u p v\"\n  assumes sub: \"subgraph H G\"\n  shows \"apath u p v\"\n  using assms unfolding pre_digraph.apath_def\n  by (auto intro: subgraph_awalk_imp_awalk simp: compatible_awalk_verts)\n\nlemma subgraph_mk_symmetric:\n  assumes \"subgraph H G\"\n  shows \"subgraph (mk_symmetric H) (mk_symmetric G)\"\nproof (rule subgraphI)\n  let ?wpms = \"\\<lambda>G. mk_symmetric G\"\n  from assms have \"compatible G H\" by auto\n  with assms\n  show \"verts (?wpms H)  \\<subseteq> verts (?wpms G)\"\n    and \"arcs (?wpms H) \\<subseteq> arcs (?wpms G)\"\n    by (auto simp: parcs_mk_symmetric compatible_head compatible_tail)\n  show \"compatible (?wpms G) (?wpms H)\" by rule\n  interpret H: pair_wf_digraph \"mk_symmetric H\"\n    using assms by (auto intro: wf_digraph.wellformed_mk_symmetric)\n  interpret G: pair_wf_digraph \"mk_symmetric G\"\n    using assms by (auto intro: wf_digraph.wellformed_mk_symmetric)\n  show \"wf_digraph (?wpms H)\"\n    by unfold_locales\n  show \"wf_digraph (?wpms G)\" by unfold_locales\nqed\n\nlemma (in fin_digraph) subgraph_in_degree:\n  assumes \"subgraph H G\"\n  shows \"in_degree H v \\<le> in_degree G v\"\nproof -\n  have \"finite (in_arcs G v)\" by auto\n  moreover\n  have \"in_arcs H v \\<subseteq> in_arcs G v\"\n    using assms by (auto simp: subgraph_def in_arcs_def compatible_head compatible_tail)\n  ultimately\n  show ?thesis unfolding in_degree_def by (rule card_mono)\nqed\n\nlemma (in wf_digraph) subgraph_cycle:\n  assumes \"subgraph H G\" \"pre_digraph.cycle H p \" shows \"cycle p\"\nproof -\n  from assms have \"compatible G H\" by auto\n  with assms show ?thesis\n    by (auto simp: pre_digraph.cycle_def compatible_awalk_verts intro: subgraph_awalk_imp_awalk)\nqed\n\n\n\nsubsection {* Induced subgraphs *}\n\nlemma wf_digraphI_induced:\n  assumes \"induced_subgraph H G\"\n  shows \"wf_digraph H\"\nproof -\n  from assms have \"compatible G H\" by auto\n  with assms show ?thesis by unfold_locales (auto simp: compatible_tail compatible_head)\nqed\n\nlemma (in digraph) digraphI_induced:\n  assumes \"induced_subgraph H G\"\n  shows \"digraph H\"\nproof -\n  interpret W: wf_digraph H using assms by (rule wf_digraphI_induced)\n  from assms have \"compatible G H\" by auto\n  from assms have arcs: \"arcs H \\<subseteq> arcs G\" by blast\n  show ?thesis\n  proof\n    from assms have \"verts H \\<subseteq> verts G\" by blast\n    then show \"finite (verts H)\" using finite_verts by (rule finite_subset)\n  next\n    from arcs show \"finite (arcs H)\" using finite_arcs by (rule finite_subset)\n  next\n    fix e assume \"e \\<in> arcs H\"\n    with arcs `compatible G H` show \"tail H e \\<noteq> head H e\"\n      by (auto dest: no_loops simp: compatible_tail[symmetric] compatible_head[symmetric])\n  next\n    fix e1 e2 assume \"e1 \\<in> arcs H\" \"e2 \\<in> arcs H\" and ate: \"arc_to_ends H e1 = arc_to_ends H e2\"\n    with arcs `compatible G H` show \"e1 = e2\" using ate\n      by (auto intro: no_multi_arcs simp: compatible_tail[symmetric] compatible_head[symmetric] arc_to_ends_def)\n  qed\nqed\n\ntext {* Computes the subgraph of @{term G} induced by @{term vs} *}\ndefinition induce_subgraph :: \"('a,'b) pre_digraph \\<Rightarrow> 'a set \\<Rightarrow> ('a,'b) pre_digraph\" (infix \"\\<restriction>\" 67) where\n  \"G \\<restriction> vs = \\<lparr> verts = vs, arcs = {e \\<in> arcs G. tail G e \\<in> vs \\<and> head G e \\<in> vs},\n    tail = tail G, head = head G \\<rparr>\"\n\nlemma induce_subgraph_verts[simp]:\n \"verts (G \\<restriction> vs) = vs\"\nby (auto simp add: induce_subgraph_def)\n\nlemma induce_subgraph_arcs[simp]:\n \"arcs (G \\<restriction> vs) = {e \\<in> arcs G. tail G e \\<in> vs \\<and> head G e \\<in> vs}\"\nby (auto simp add: induce_subgraph_def)\n\nlemma induce_subgraph_tail[simp]:\n  \"tail (G \\<restriction> vs) = tail G\"\nby (auto simp: induce_subgraph_def)\n\nlemma induce_subgraph_head[simp]:\n  \"head (G \\<restriction> vs) = head G\"\nby (auto simp: induce_subgraph_def)\n\nlemma (in wf_digraph) induced_induce[intro]:\n  assumes \"vs \\<subseteq> verts G\"\n  shows \"induced_subgraph (G \\<restriction> vs) G\"\nusing assms\nby (intro subgraphI induced_subgraphI)\n   (auto simp: arc_to_ends_def induce_subgraph_def wf_digraph_def compatible_def)\n\nlemma (in wf_digraph) wellformed_induce_subgraph[intro]:\n  \"wf_digraph (G \\<restriction> vs)\"\n  by unfold_locales auto\n\nlemma induced_graph_imp_symmetric:\n  assumes \"symmetric G\"\n  assumes \"induced_subgraph H G\"\n  shows \"symmetric H\"\nproof (unfold symmetric_conv, safe)\n  from assms have \"compatible G H\" by auto\n\n  fix e1 assume \"e1 \\<in> arcs H\"\n  then obtain e2 where \"tail G e1 = head G e2\"  \"head G e1 = tail G e2\" \"e2 \\<in> arcs G\"\n    using assms by (auto simp add: symmetric_conv)\n  moreover\n  then have \"e2 \\<in> arcs H\"\n    using assms and `e1 \\<in> arcs H` by auto\n  ultimately\n  show \"\\<exists>e2\\<in>arcs H. tail H e1 = head H e2 \\<and> head H e1 = tail H e2\"\n    using assms `e1 \\<in> arcs H` `compatible G H`\n    by (auto simp: compatible_head compatible_tail)\nqed\n\nlemma (in sym_digraph) induced_graph_imp_graph:\n  assumes \"induced_subgraph H G\"\n  shows \"sym_digraph H\"\nproof (rule wf_digraph.sym_digraphI)\n  from assms show \"wf_digraph H\" by (rule wf_digraphI_induced)\nnext\n  show \"symmetric H\"\n    using assms sym_arcs by (auto intro: induced_graph_imp_symmetric)\nqed\n\nlemma (in wf_digraph) induce_reachable_preserves_paths:\n  assumes \"u \\<rightarrow>\\<^sup>*\\<^bsub>G\\<^esub> v\"\n  shows \"u \\<rightarrow>\\<^sup>*\\<^bsub>G \\<restriction> {w. u \\<rightarrow>\\<^sup>*\\<^bsub>G\\<^esub> w}\\<^esub> v\"\n  using assms\nproof induct\n  case base then show ?case by (auto simp: reachable_def)\nnext\n  case (step u w)\n  interpret iG: wf_digraph \"G \\<restriction> {w. u \\<rightarrow>\\<^sup>*\\<^bsub>G\\<^esub> w}\"\n    by (rule wellformed_induce_subgraph)\n  from `u \\<rightarrow> w` have \"u \\<rightarrow>\\<^bsub>G \\<restriction> {wa. u \\<rightarrow>\\<^sup>*\\<^bsub>G\\<^esub> wa}\\<^esub> w\"\n    by (auto simp: arcs_ends_conv reachable_def intro: wellformed rtrancl_on_into_rtrancl_on)\n  then have \"u \\<rightarrow>\\<^sup>*\\<^bsub>G \\<restriction> {wa. u \\<rightarrow>\\<^sup>*\\<^bsub>G\\<^esub> wa}\\<^esub> w\"\n    by (rule iG.reachable_adjI)\n  moreover\n  from step have \"{x. w \\<rightarrow>\\<^sup>* x} \\<subseteq> {x. u \\<rightarrow>\\<^sup>* x}\"\n    by (auto intro: adj_reachable_trans)\n  then have \"subgraph (G \\<restriction> {wa. w \\<rightarrow>\\<^sup>* wa}) (G \\<restriction> {wa. u \\<rightarrow>\\<^sup>* wa})\"\n    by (intro subgraphI) (auto simp: arcs_ends_conv compatible_def)\n  then have \"w \\<rightarrow>\\<^sup>*\\<^bsub>G \\<restriction> {wa. u \\<rightarrow>\\<^sup>* wa}\\<^esub> v\"\n    by (rule iG.reachable_mono[rotated]) fact\n  ultimately show ?case by (rule iG.reachable_trans)\nqed\n\n\n\nsubsection {* Unions of Graphs *}\n\nlemma\n  verts_union[simp]: \"verts (union G H) = verts G \\<union> verts H\" and\n  arcs_union[simp]: \"arcs (union G H) = arcs G \\<union> arcs H\" and\n  tail_union[simp]: \"tail (union G H) = tail G\" and\n  head_union[simp]: \"head (union G H) = head G\"\n  by (auto simp: union_def)\n\nlemma wellformed_union:\n  assumes \"wf_digraph G\" \"wf_digraph H\" \"compatible G H\"\n  shows \"wf_digraph (union G H)\"\n  using assms\n  by unfold_locales\n     (auto simp: union_def compatible_tail compatible_head dest: wf_digraph.wellformed)\n\nlemma subgraph_union_iff:\n  assumes \"wf_digraph H1\" \"wf_digraph H2\" \"compatible H1 H2\"\n  shows \"subgraph (union H1 H2) G \\<longleftrightarrow> subgraph H1 G \\<and> subgraph H2 G\"\n  using assms by (fastforce simp: compatible_def intro!: subgraphI wellformed_union)\n\nlemma subgraph_union[intro]:\n  assumes \"subgraph H1 G\" \"compatible H1 G\"\n  assumes \"subgraph H2 G\" \"compatible H2 G\"\n  shows \"subgraph (union H1 H2) G\"\nproof -\n  from assms have \"wf_digraph (union H1 H2)\"\n    by (auto intro: wellformed_union simp: compatible_def)\n  with assms show ?thesis\n    by (auto simp add: subgraph_def union_def arc_to_ends_def compatible_def)\nqed\n\nlemma union_fin_digraph:\n  assumes \"fin_digraph G\" \"fin_digraph H\" \"compatible G H\"\n  shows \"fin_digraph (union G H)\"\nproof intro_locales\n  interpret G: fin_digraph G by (rule assms)\n  interpret H: fin_digraph H by (rule assms)\n  show \"wf_digraph (union G H)\" using assms\n    by (intro wellformed_union) intro_locales\n  show \"fin_digraph_axioms (union G H)\"\n    using assms by unfold_locales (auto simp: union_def)\nqed\n\nlemma subgraphs_of_union:\n  assumes \"wf_digraph G\" \"wf_digraph G'\" \"compatible G G'\"\n  shows \"subgraph G (union G G')\"\n    and \"subgraph G' (union G G')\"\n  using assms by (auto intro!: subgraphI wellformed_union simp: compatible_def)\n\n\n\nsubsection {* Connected and Strongly Connected Graphs*}\n\nlemma connected_conv:\n  shows \"connected G \\<longleftrightarrow> verts G \\<noteq> {} \\<and> (\\<forall>u \\<in> verts G. \\<forall>v \\<in> verts G. (u,v) \\<in> rtrancl_on (verts G) ((arcs_ends G)\\<^sup>s))\"\nproof -\n  have \"symcl (arcs_ends G) = parcs (mk_symmetric G)\"\n    by (auto simp: parcs_mk_symmetric symcl_def arcs_ends_conv)\n  then show ?thesis by (auto simp: connected_def strongly_connected_def reachable_def)\nqed\n\nlemma (in wf_digraph) strongly_connected_spanning_imp_strongly_connected:\n  assumes \"spanning H G\"\n  assumes \"strongly_connected H\"\n  shows \"strongly_connected G\"\nproof (unfold strongly_connected_def, intro ballI conjI)\n  from assms show \"verts G \\<noteq> {}\" unfolding strongly_connected_def spanning_def by auto\nnext\n  fix u v assume \"u \\<in> verts G\" and \"v \\<in> verts G\"\n  then have \"u \\<rightarrow>\\<^sup>*\\<^bsub>H\\<^esub> v\" \"subgraph H G\"\n    using assms by (auto simp add: strongly_connected_def)\n  then show \"u \\<rightarrow>\\<^sup>* v\" by (rule reachable_mono)\nqed\n\nlemma (in wf_digraph) symmetric_connected_imp_strongly_connected:\n  assumes \"symmetric G\" \"connected G\"\n  shows \"strongly_connected G\"\nproof\n  from `connected G` show \"verts G \\<noteq> {}\" unfolding connected_def strongly_connected_def by auto\nnext\n  from `connected G`\n  have sc_mks: \"strongly_connected (mk_symmetric G)\"\n    unfolding connected_def by simp\n\n  fix u v assume \"u \\<in> verts G\" \"v \\<in> verts G\"\n  with sc_mks have \"u \\<rightarrow>\\<^sup>*\\<^bsub>mk_symmetric G\\<^esub> v\"\n    unfolding strongly_connected_def by auto\n  then show \"u \\<rightarrow>\\<^sup>* v\" using assms by (simp only: reachable_mk_symmetric_eq)\nqed\n\nlemma (in wf_digraph) connected_spanning_imp_connected:\n  assumes \"spanning H G\"\n  assumes \"connected H\"\n  shows \"connected G\"\nproof (unfold connected_def strongly_connected_def, intro conjI ballI)\n  from assms show \"verts (mk_symmetric G )\\<noteq> {}\"\n    unfolding spanning_def connected_def strongly_connected_def by auto\nnext\n  fix u v\n  assume \"u \\<in> verts (mk_symmetric G)\" and \"v \\<in> verts (mk_symmetric G)\"\n  then have \"u \\<in> pverts (mk_symmetric H)\" and \"v \\<in> pverts (mk_symmetric H)\"\n    using `spanning H G` by (auto simp: mk_symmetric_def)\n  with `connected H`\n  have \"u \\<rightarrow>\\<^sup>*\\<^bsub>with_proj (mk_symmetric H)\\<^esub> v\" \"subgraph (mk_symmetric H) (mk_symmetric G)\"\n    using `spanning H G` unfolding connected_def\n    by (auto simp: spanning_def dest: subgraph_mk_symmetric)\n  then show \"u \\<rightarrow>\\<^sup>*\\<^bsub>mk_symmetric G\\<^esub> v\" by (rule pre_digraph.reachable_mono)\nqed\n\nlemma (in wf_digraph) spanning_tree_imp_connected:\n  assumes \"spanning_tree H G\"\n  shows \"connected G\"\nusing assms by (auto intro: connected_spanning_imp_connected)\n\nlemma (in sym_digraph) induce_reachable_is_in_sccs:\n  assumes \"u \\<in> verts G\"\n  shows \"(G \\<restriction> {v. u \\<rightarrow>\\<^sup>* v}) \\<in> sccs\"\nproof -\n  let ?c = \"(G \\<restriction> {v. u \\<rightarrow>\\<^sup>* v})\"\n  have isub_c: \"induced_subgraph ?c G\"\n    by (auto elim: reachable_in_vertsE)\n  then interpret c: wf_digraph ?c by (rule wf_digraphI_induced)\n\n  have sym_c: \"symmetric (G \\<restriction> {v. u \\<rightarrow>\\<^sup>* v})\"\n    using sym_arcs isub_c by (rule induced_graph_imp_symmetric)\n\n  note `induced_subgraph ?c G`\n  moreover\n  have \"strongly_connected ?c\"\n  proof (rule strongly_connectedI)\n    show \"verts ?c \\<noteq> {}\" using assms by auto\n  next\n    fix v w assume l_assms: \"v \\<in> verts ?c\" \"w \\<in> verts ?c\"\n    have \"u \\<rightarrow>\\<^sup>*\\<^bsub>G \\<restriction> {v. u \\<rightarrow>\\<^sup>* v}\\<^esub> v\"\n      using l_assms by (intro induce_reachable_preserves_paths) auto\n    then have \"v \\<rightarrow>\\<^sup>*\\<^bsub>G \\<restriction> {v. u \\<rightarrow>\\<^sup>* v}\\<^esub> u\" by (rule symmetric_reachable[OF sym_c])\n    also have \"u \\<rightarrow>\\<^sup>*\\<^bsub>G \\<restriction> {v. u \\<rightarrow>\\<^sup>* v}\\<^esub> w\"\n      using l_assms by (intro induce_reachable_preserves_paths) auto\n    finally show \"v \\<rightarrow>\\<^sup>*\\<^bsub>G \\<restriction> {v. u \\<rightarrow>\\<^sup>* v}\\<^esub> w\" .\n  qed\n  moreover\n  have \"\\<not>(\\<exists>d. induced_subgraph d G \\<and> strongly_connected d \\<and>\n    verts ?c \\<subset> verts d)\"\n  proof\n    assume \"\\<exists>d. induced_subgraph d G \\<and> strongly_connected d \\<and>\n      verts ?c \\<subset> verts d\"\n    then obtain d where \"induced_subgraph d G\" \"strongly_connected d\"\n      \"verts ?c \\<subset> verts d\" by auto\n    then obtain v where \"v \\<in> verts d\" and \"v \\<notin> verts ?c\"\n      by auto\n\n    have \"u \\<in> verts ?c\" using `u \\<in> verts G` by auto\n    then have \"u \\<in> verts d\" using `verts ?c \\<subset> verts d` by auto \n    then have \"u \\<rightarrow>\\<^sup>*\\<^bsub>d\\<^esub> v\"\n      using `strongly_connected d` `u \\<in> verts d` `v \\<in> verts d` by auto\n    then have \"u \\<rightarrow>\\<^sup>* v\"\n      using `induced_subgraph d G`\n      by (auto intro: pre_digraph.reachable_mono)\n    then have \"v \\<in> verts ?c\" by (auto simp: reachable_awalk)\n    then show False using `v \\<notin> verts ?c` by auto\n  qed\n  ultimately show ?thesis unfolding sccs_def by auto\nqed\n\nlemma induced_eq_verts_imp_eq:\n  assumes \"induced_subgraph G H\"\n  assumes \"induced_subgraph G' H\"\n  assumes \"verts G = verts G'\"\n  shows \"G = G'\"\n  using assms by (auto simp: induced_subgraph_def subgraph_def compatible_def)\n\nlemma (in pre_digraph) in_sccs_subset_imp_eq:\n  assumes \"c \\<in> sccs\"\n  assumes \"d \\<in> sccs\"\n  assumes \"verts c \\<subseteq> verts d\"\n  shows \"c = d\"\nusing assms by (blast intro: induced_eq_verts_imp_eq)\n\nlemma (in wf_digraph) strongly_connected_imp_induce_subgraph_strongly_connected:\n  assumes subg: \"subgraph H G\"\n  assumes sc: \"strongly_connected H\"\n  shows \"strongly_connected (G \\<restriction> (verts H))\"\nproof -\n  let ?is_H = \"G \\<restriction> (verts H)\"\n\n  interpret H: wf_digraph H\n    using subg by (rule subgraphE)\n  interpret GrH: wf_digraph \"?is_H\"\n    by (rule wellformed_induce_subgraph)\n\n  have \"verts H \\<subseteq> verts G\" using assms by auto\n\n  have \"subgraph H (G \\<restriction> verts H)\"\n    using subg by (intro subgraphI) (auto simp: compatible_def)\n  then show ?thesis\n    using induced_induce[OF `verts H \\<subseteq> verts G`]\n      and sc GrH.strongly_connected_spanning_imp_strongly_connected\n    unfolding spanning_def by auto\nqed\n\nlemma (in wf_digraph) connectedI:\n  assumes \"verts G \\<noteq> {}\" \"\\<And>u v. u \\<in> verts G \\<Longrightarrow> v \\<in> verts G \\<Longrightarrow> u \\<rightarrow>\\<^sup>*\\<^bsub>mk_symmetric G\\<^esub> v\"\n  shows \"connected G\"\n  using assms by (auto simp: connected_def)\n\nlemma (in wf_digraph) connected_awalkE:\n  assumes \"connected G\" \"u \\<in> verts G\" \"v \\<in> verts G\"\n  obtains p where \"pre_digraph.awalk (mk_symmetric G) u p v\"\nproof -\n  interpret sG: pair_wf_digraph \"mk_symmetric G\" ..\n  from assms have \"u \\<rightarrow>\\<^sup>*\\<^bsub>mk_symmetric G\\<^esub> v\" by (auto simp: connected_def)\n  then obtain p where \"sG.awalk u p v\" by (auto simp: sG.reachable_awalk)\n  then show ?thesis ..\nqed\n\n\n\nsubsection {* Components *}\n\nlemma (in sym_digraph) exists_scc:\n  assumes \"verts G \\<noteq> {}\" shows \"\\<exists>c. c \\<in> sccs\"\nproof -\n  from assms obtain u where \"u \\<in> verts G\" by auto\n  then show ?thesis by (blast dest: induce_reachable_is_in_sccs)\nqed\n\ntheorem (in sym_digraph) graph_is_union_sccs:\n  shows \"Union sccs = G\"\nproof -\n  have \"(\\<Union>c \\<in> sccs. verts c) = verts G\"\n    by (auto intro: induce_reachable_is_in_sccs)\n  moreover\n  have \"(\\<Union>c \\<in> sccs. arcs c) = arcs G\"\n  proof\n    show \"(\\<Union>c \\<in> sccs. arcs c) \\<subseteq> arcs G\"\n      by safe (metis in_sccsE induced_imp_subgraph subgraphE subsetD)\n    show \"arcs G \\<subseteq> (\\<Union>c \\<in> sccs. arcs c)\"\n    proof (safe)\n      fix e assume \"e \\<in> arcs G\"\n      def a \\<equiv> \"tail G e\" and b \\<equiv> \"head G e\"\n      note a_def[simp] b_def[simp]\n\n      have \"e \\<in> (\\<Union>x \\<in> sccs. arcs x)\"\n      proof cases\n        assume \"\\<exists>x\\<in>sccs. {a,b } \\<subseteq> verts x\"\n        then obtain c where \"c \\<in> sccs\" and \"{a,b} \\<subseteq> verts c\"\n          by auto\n        then have \"e \\<in> {e \\<in> arcs G. tail G e \\<in> verts c\n          \\<and> head G e \\<in> verts c}\" using `e \\<in> arcs G` by auto\n        then have \"e \\<in> arcs c\" using `c \\<in> sccs` by blast\n        then show ?thesis using `c \\<in> sccs` by auto\n      next\n        assume l_assm: \"\\<not>(\\<exists>x\\<in>sccs. {a,b} \\<subseteq> verts x)\"\n\n        have \"a \\<rightarrow>\\<^sup>* b\" using `e \\<in> arcs G` \n          by (metis a_def b_def reachable_adjI in_arcs_imp_in_arcs_ends)\n        then have \"{a,b} \\<subseteq> verts (G \\<restriction> {v. a \\<rightarrow>\\<^sup>* v})\" \"a \\<in> verts G\"\n          by (auto elim: reachable_in_vertsE)\n        moreover\n        have \"(G \\<restriction> {v. a \\<rightarrow>\\<^sup>* v}) \\<in> sccs\"\n          using `a \\<in> verts G` by (auto intro: induce_reachable_is_in_sccs)\n        ultimately\n        have False using l_assm by blast\n        then show ?thesis by simp\n      qed\n      then show \"e \\<in> (\\<Union>c \\<in> sccs. arcs c)\" by auto\n    qed\n  qed\n  ultimately show ?thesis\n    by (auto simp add: Union_def)\nqed\n\nlemma (in sym_digraph) scc_for_vert_ex:\n  assumes \"u \\<in> verts G\"\n  shows \"\\<exists>c. c\\<in>sccs \\<and> u \\<in> verts c\"\nusing assms by (auto intro: induce_reachable_is_in_sccs)\n\nlemma strongly_connected_non_disj:\n  assumes wf: \"wf_digraph G\" \"wf_digraph H\" \"compatible G H\"\n  assumes sc: \"strongly_connected G\" \"strongly_connected H\"\n  assumes not_disj: \"verts G \\<inter> verts H \\<noteq> {}\"\n  shows \"strongly_connected (union G H)\"\nproof\n  from sc show \"verts (union G H) \\<noteq> {}\"\n    unfolding strongly_connected_def by simp\nnext\n  let ?x = \"union G H\"\n  fix u v w assume \"u \\<in> verts ?x\" and \"v \\<in> verts ?x\"\n  obtain w where w_in_both: \"w \\<in> verts G\" \"w \\<in> verts H\"\n    using not_disj by auto\n\n  interpret x: wf_digraph ?x\n    by (rule wellformed_union) fact+\n  have subg: \"subgraph G ?x\" \"subgraph H ?x\"\n    by (rule subgraphs_of_union[OF _ _ ], fact+)+\n  have reach_uw: \"u \\<rightarrow>\\<^sup>*\\<^bsub>?x\\<^esub> w\"\n    using `u \\<in> verts ?x` subg w_in_both sc\n    by (auto intro: pre_digraph.reachable_mono)\n  also have reach_wv: \"w \\<rightarrow>\\<^sup>*\\<^bsub>?x\\<^esub> v\"\n    using `v \\<in> verts ?x` subg w_in_both sc\n    by (auto intro: pre_digraph.reachable_mono)\n  finally (x.reachable_trans) show \"u \\<rightarrow>\\<^sup>*\\<^bsub>?x\\<^esub> v\" .\nqed\n\nlemma (in wf_digraph) scc_disj:\n  assumes scc: \"c \\<in> sccs\" \"d \\<in> sccs\"\n  assumes \"c \\<noteq> d\"\n  shows \"verts c \\<inter> verts d = {}\"\nproof (rule ccontr)\n  assume contr: \"\\<not>?thesis\"\n\n  let ?x = \"union c d\"\n\n  have comp1: \"compatible G c\" \"compatible G d\"\n    using scc by (auto simp: sccs_def)\n  then have comp: \"compatible c d\" by (auto simp: compatible_def)\n\n  have wf: \"wf_digraph c\" \"wf_digraph d\"\n    and sc: \"strongly_connected c\" \"strongly_connected d\"\n    using scc by (auto intro: in_sccs_imp_induced)\n  have \"compatible c d\"\n    using comp by (auto simp: sccs_def compatible_def)\n  from wf comp sc have union_conn: \"strongly_connected ?x\"\n    using contr by (rule strongly_connected_non_disj)\n\n  have sg: \"subgraph ?x G\"\n    using scc comp1 by (intro subgraph_union) (auto simp: compatible_def)\n  then have v_cd: \"verts c \\<subseteq> verts G\"  \"verts d \\<subseteq> verts G\" by (auto elim!: subgraphE)\n  have \"wf_digraph ?x\" by (rule wellformed_union) fact+\n  with v_cd sg union_conn\n  have induce_subgraph_conn: \"strongly_connected (G \\<restriction> verts ?x)\"\n      \"induced_subgraph (G \\<restriction> verts ?x) G\"\n    by - (intro strongly_connected_imp_induce_subgraph_strongly_connected,\n      auto simp: subgraph_union_iff)\n\n  from assms have \"\\<not>verts c \\<subseteq> verts d\" and \"\\<not> verts d \\<subseteq> verts c\"\n    by (metis in_sccs_subset_imp_eq)+\n  then have psub: \"verts c \\<subset> verts ?x\"\n    by (auto simp: union_def)\n  then show False using induce_subgraph_conn\n    by (metis `c \\<in> sccs` in_sccsE induce_subgraph_verts)\nqed\n\nlemma (in sym_digraph) scc_decomp_unique:\n  assumes \"S \\<subseteq> sccs\" \"Union S = G\" shows \"S = sccs\"\nproof (rule ccontr)\n  assume \"S \\<noteq> sccs\"\n  with assms obtain c where \"c \\<in> sccs\" and \"c \\<notin> S\" by auto\n  with assms have \"\\<And>d. d \\<in> S \\<Longrightarrow> verts c \\<inter> verts d = {}\"\n    by (intro scc_disj) auto\n  then have \"verts c \\<inter> verts (Union S) = {}\"\n    by (auto simp: Union_def)\n  with assms have \"verts c \\<inter> verts G = {}\" by auto\n  moreover from `c \\<in> sccs` obtain u where \"u \\<in> verts c \\<inter> verts G\"\n    by (auto simp: sccs_def strongly_connected_def)\n  ultimately show False by blast\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/Graph_Theory/Digraph_Component.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8688267864276108, "lm_q2_score": 0.8577681086260461, "lm_q1q2_score": 0.7452519093176574}}
{"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_49\n  imports \"../../Test_Base\"\nbegin\n\ndatatype 'a list = nil2 | cons2 \"'a\" \"'a list\"\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 butlast :: \"'a list => 'a list\" where\n  \"butlast (nil2) = nil2\"\n| \"butlast (cons2 z (nil2)) = nil2\"\n| \"butlast (cons2 z (cons2 x2 x3)) =\n     cons2 z (butlast (cons2 x2 x3))\"\n\nfun butlastConcat :: \"'a list => 'a list => 'a list\" where\n  \"butlastConcat y (nil2) = butlast y\"\n| \"butlastConcat y (cons2 z2 x2) = x y (butlast (cons2 z2 x2))\"\n\ntheorem property0 :\n  \"((butlast (x xs ys)) = (butlastConcat xs ys))\"\n  (*Why on \"xs\"?\n    Because \"x\" is defined recursively on the first parameter, which is \"xs\" in this case,\n    and \"x\" is the innermost recursive function.\n    and we can apply \"butlast.simps\" to the left-hand side if we can apply \"x.simps\" to \"x xs ys\".\n   *)\n  (*Why \"rule:butlast.induct\"?\n    Because \"butlast\"'s pattern-matching seems to be powerful(?)\n    Because we want to simplify \"x xs ys\" and \"x xs ys\" is a sub-term of \"butlast (x xs ys)\"(?)\n   *)\n  apply(induct xs rule:butlast.induct)\n    apply(cases ys)\n     apply fastforce+\n   apply(cases ys)\n    apply fastforce+\n  apply(cases ys)\n   apply fastforce+\n  done\n\ntheorem property0' :\n  \"((butlast (x xs ys)) = (butlastConcat xs ys))\"\n  apply(induct xs rule:butlast.induct)\n    apply(induct ys)\n     apply fastforce+\n   apply(induct ys)\n    apply fastforce+\n  apply(induct ys)\n   apply fastforce+\n  done\n\ntheorem \"((butlast (x xs ys)) = (butlastConcat xs ys))\"\n  apply(induct ys rule:butlastConcat.induct)\n  nitpick\n  oops\n\ntheorem \"((butlast (x xs ys)) = (butlastConcat xs ys))\"\n  apply(induct xs rule:butlastConcat.induct)\n  nitpick\n  oops\n\ntheorem \"((butlast (x xs ys)) = (butlastConcat xs ys))\"\n(*TODO: find alternative proofs without \"butlast.induct\".*)\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_49.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681013541613, "lm_q2_score": 0.8688267694452331, "lm_q1q2_score": 0.7452518884327072}}
{"text": "(*  Title:      ZF/OrdQuant.thy\n    Authors:    Krzysztof Grabczewski and L C Paulson\n*)\n\nsection {*Special quantifiers*}\n\ntheory OrdQuant imports Ordinal begin\n\nsubsection {*Quantifiers and union operator for ordinals*}\n\ndefinition\n  (* Ordinal Quantifiers *)\n  oall :: \"[i, i => o] => o\"  where\n    \"oall(A, P) == \\<forall>x. x<A \\<longrightarrow> P(x)\"\n\ndefinition\n  oex :: \"[i, i => o] => o\"  where\n    \"oex(A, P)  == \\<exists>x. x<A & P(x)\"\n\ndefinition\n  (* Ordinal Union *)\n  OUnion :: \"[i, i => i] => i\"  where\n    \"OUnion(i,B) == {z: \\<Union>x\\<in>i. B(x). Ord(i)}\"\n\nsyntax\n  \"_oall\"     :: \"[idt, i, o] => o\"        (\"(3ALL _<_./ _)\" 10)\n  \"_oex\"      :: \"[idt, i, o] => o\"        (\"(3EX _<_./ _)\" 10)\n  \"_OUNION\"   :: \"[idt, i, i] => i\"        (\"(3UN _<_./ _)\" 10)\n\ntranslations\n  \"ALL x<a. P\"  == \"CONST oall(a, %x. P)\"\n  \"EX x<a. P\"   == \"CONST oex(a, %x. P)\"\n  \"UN x<a. B\"   == \"CONST OUnion(a, %x. B)\"\n\nsyntax (xsymbols)\n  \"_oall\"     :: \"[idt, i, o] => o\"        (\"(3\\<forall>_<_./ _)\" 10)\n  \"_oex\"      :: \"[idt, i, o] => o\"        (\"(3\\<exists>_<_./ _)\" 10)\n  \"_OUNION\"   :: \"[idt, i, i] => i\"        (\"(3\\<Union>_<_./ _)\" 10)\nsyntax (HTML output)\n  \"_oall\"     :: \"[idt, i, o] => o\"        (\"(3\\<forall>_<_./ _)\" 10)\n  \"_oex\"      :: \"[idt, i, o] => o\"        (\"(3\\<exists>_<_./ _)\" 10)\n  \"_OUNION\"   :: \"[idt, i, i] => i\"        (\"(3\\<Union>_<_./ _)\" 10)\n\n\nsubsubsection {*simplification of the new quantifiers*}\n\n\n(*MOST IMPORTANT that this is added to the simpset BEFORE Ord_atomize\n  is proved.  Ord_atomize would convert this rule to\n    x < 0 ==> P(x) == True, which causes dire effects!*)\n\n\nlemma [simp]: \"~(\\<exists>x<0. P(x))\"\nby (simp add: oex_def)\n\nlemma [simp]: \"(\\<forall>x<succ(i). P(x)) <-> (Ord(i) \\<longrightarrow> P(i) & (\\<forall>x<i. P(x)))\"\napply (simp add: oall_def le_iff)\napply (blast intro: lt_Ord2)\ndone\n\nlemma [simp]: \"(\\<exists>x<succ(i). P(x)) <-> (Ord(i) & (P(i) | (\\<exists>x<i. P(x))))\"\napply (simp add: oex_def le_iff)\napply (blast intro: lt_Ord2)\ndone\n\nsubsubsection {*Union over ordinals*}\n\nlemma Ord_OUN [intro,simp]:\n     \"[| !!x. x<A ==> Ord(B(x)) |] ==> Ord(\\<Union>x<A. B(x))\"\nby (simp add: OUnion_def ltI Ord_UN)\n\nlemma OUN_upper_lt:\n     \"[| a<A;  i < b(a);  Ord(\\<Union>x<A. b(x)) |] ==> i < (\\<Union>x<A. b(x))\"\nby (unfold OUnion_def lt_def, blast )\n\nlemma OUN_upper_le:\n     \"[| a<A;  i\\<le>b(a);  Ord(\\<Union>x<A. b(x)) |] ==> i \\<le> (\\<Union>x<A. b(x))\"\napply (unfold OUnion_def, auto)\napply (rule UN_upper_le )\napply (auto simp add: lt_def)\ndone\n\nlemma Limit_OUN_eq: \"Limit(i) ==> (\\<Union>x<i. x) = i\"\nby (simp add: OUnion_def Limit_Union_eq Limit_is_Ord)\n\n(* No < version of this theorem: consider that @{term\"(\\<Union>i\\<in>nat.i)=nat\"}! *)\nlemma OUN_least:\n     \"(!!x. x<A ==> B(x) \\<subseteq> C) ==> (\\<Union>x<A. B(x)) \\<subseteq> C\"\nby (simp add: OUnion_def UN_least ltI)\n\nlemma OUN_least_le:\n     \"[| Ord(i);  !!x. x<A ==> b(x) \\<le> i |] ==> (\\<Union>x<A. b(x)) \\<le> i\"\nby (simp add: OUnion_def UN_least_le ltI Ord_0_le)\n\nlemma le_implies_OUN_le_OUN:\n     \"[| !!x. x<A ==> c(x) \\<le> d(x) |] ==> (\\<Union>x<A. c(x)) \\<le> (\\<Union>x<A. d(x))\"\nby (blast intro: OUN_least_le OUN_upper_le le_Ord2 Ord_OUN)\n\nlemma OUN_UN_eq:\n     \"(!!x. x \\<in> A ==> Ord(B(x)))\n      ==> (\\<Union>z < (\\<Union>x\\<in>A. B(x)). C(z)) = (\\<Union>x\\<in>A. \\<Union>z < B(x). C(z))\"\nby (simp add: OUnion_def)\n\nlemma OUN_Union_eq:\n     \"(!!x. x \\<in> X ==> Ord(x))\n      ==> (\\<Union>z < \\<Union>(X). C(z)) = (\\<Union>x\\<in>X. \\<Union>z < x. C(z))\"\nby (simp add: OUnion_def)\n\n(*So that rule_format will get rid of this quantifier...*)\nlemma atomize_oall [symmetric, rulify]:\n     \"(!!x. x<A ==> P(x)) == Trueprop (\\<forall>x<A. P(x))\"\nby (simp add: oall_def atomize_all atomize_imp)\n\nsubsubsection {*universal quantifier for ordinals*}\n\nlemma oallI [intro!]:\n    \"[| !!x. x<A ==> P(x) |] ==> \\<forall>x<A. P(x)\"\nby (simp add: oall_def)\n\nlemma ospec: \"[| \\<forall>x<A. P(x);  x<A |] ==> P(x)\"\nby (simp add: oall_def)\n\nlemma oallE:\n    \"[| \\<forall>x<A. P(x);  P(x) ==> Q;  ~x<A ==> Q |] ==> Q\"\nby (simp add: oall_def, blast)\n\nlemma rev_oallE [elim]:\n    \"[| \\<forall>x<A. P(x);  ~x<A ==> Q;  P(x) ==> Q |] ==> Q\"\nby (simp add: oall_def, blast)\n\n\n(*Trival rewrite rule.  @{term\"(\\<forall>x<a.P)<->P\"} holds only if a is not 0!*)\nlemma oall_simp [simp]: \"(\\<forall>x<a. True) <-> True\"\nby blast\n\n(*Congruence rule for rewriting*)\nlemma oall_cong [cong]:\n    \"[| a=a';  !!x. x<a' ==> P(x) <-> P'(x) |]\n     ==> oall(a, %x. P(x)) <-> oall(a', %x. P'(x))\"\nby (simp add: oall_def)\n\n\nsubsubsection {*existential quantifier for ordinals*}\n\nlemma oexI [intro]:\n    \"[| P(x);  x<A |] ==> \\<exists>x<A. P(x)\"\napply (simp add: oex_def, blast)\ndone\n\n(*Not of the general form for such rules... *)\nlemma oexCI:\n   \"[| \\<forall>x<A. ~P(x) ==> P(a);  a<A |] ==> \\<exists>x<A. P(x)\"\napply (simp add: oex_def, blast)\ndone\n\nlemma oexE [elim!]:\n    \"[| \\<exists>x<A. P(x);  !!x. [| x<A; P(x) |] ==> Q |] ==> Q\"\napply (simp add: oex_def, blast)\ndone\n\nlemma oex_cong [cong]:\n    \"[| a=a';  !!x. x<a' ==> P(x) <-> P'(x) |]\n     ==> oex(a, %x. P(x)) <-> oex(a', %x. P'(x))\"\napply (simp add: oex_def cong add: conj_cong)\ndone\n\n\nsubsubsection {*Rules for Ordinal-Indexed Unions*}\n\nlemma OUN_I [intro]: \"[| a<i;  b \\<in> B(a) |] ==> b: (\\<Union>z<i. B(z))\"\nby (unfold OUnion_def lt_def, blast)\n\nlemma OUN_E [elim!]:\n    \"[| b \\<in> (\\<Union>z<i. B(z));  !!a.[| b \\<in> B(a);  a<i |] ==> R |] ==> R\"\napply (unfold OUnion_def lt_def, blast)\ndone\n\nlemma OUN_iff: \"b \\<in> (\\<Union>x<i. B(x)) <-> (\\<exists>x<i. b \\<in> B(x))\"\nby (unfold OUnion_def oex_def lt_def, blast)\n\nlemma OUN_cong [cong]:\n    \"[| i=j;  !!x. x<j ==> C(x)=D(x) |] ==> (\\<Union>x<i. C(x)) = (\\<Union>x<j. D(x))\"\nby (simp add: OUnion_def lt_def OUN_iff)\n\nlemma lt_induct:\n    \"[| i<k;  !!x.[| x<k;  \\<forall>y<x. P(y) |] ==> P(x) |]  ==>  P(i)\"\napply (simp add: lt_def oall_def)\napply (erule conjE)\napply (erule Ord_induct, assumption, blast)\ndone\n\n\nsubsection {*Quantification over a class*}\n\ndefinition\n  \"rall\"     :: \"[i=>o, i=>o] => o\"  where\n    \"rall(M, P) == \\<forall>x. M(x) \\<longrightarrow> P(x)\"\n\ndefinition\n  \"rex\"      :: \"[i=>o, i=>o] => o\"  where\n    \"rex(M, P) == \\<exists>x. M(x) & P(x)\"\n\nsyntax\n  \"_rall\"     :: \"[pttrn, i=>o, o] => o\"        (\"(3ALL _[_]./ _)\" 10)\n  \"_rex\"      :: \"[pttrn, i=>o, o] => o\"        (\"(3EX _[_]./ _)\" 10)\n\nsyntax (xsymbols)\n  \"_rall\"     :: \"[pttrn, i=>o, o] => o\"        (\"(3\\<forall>_[_]./ _)\" 10)\n  \"_rex\"      :: \"[pttrn, i=>o, o] => o\"        (\"(3\\<exists>_[_]./ _)\" 10)\nsyntax (HTML output)\n  \"_rall\"     :: \"[pttrn, i=>o, o] => o\"        (\"(3\\<forall>_[_]./ _)\" 10)\n  \"_rex\"      :: \"[pttrn, i=>o, o] => o\"        (\"(3\\<exists>_[_]./ _)\" 10)\n\ntranslations\n  \"ALL x[M]. P\"  == \"CONST rall(M, %x. P)\"\n  \"EX x[M]. P\"   == \"CONST rex(M, %x. P)\"\n\n\nsubsubsection{*Relativized universal quantifier*}\n\nlemma rallI [intro!]: \"[| !!x. M(x) ==> P(x) |] ==> \\<forall>x[M]. P(x)\"\nby (simp add: rall_def)\n\nlemma rspec: \"[| \\<forall>x[M]. P(x); M(x) |] ==> P(x)\"\nby (simp add: rall_def)\n\n(*Instantiates x first: better for automatic theorem proving?*)\nlemma rev_rallE [elim]:\n    \"[| \\<forall>x[M]. P(x);  ~ M(x) ==> Q;  P(x) ==> Q |] ==> Q\"\nby (simp add: rall_def, blast)\n\nlemma rallE: \"[| \\<forall>x[M]. P(x);  P(x) ==> Q;  ~ M(x) ==> Q |] ==> Q\"\nby blast\n\n(*Trival rewrite rule;   (ALL x[M].P)<->P holds only if A is nonempty!*)\nlemma rall_triv [simp]: \"(ALL x[M]. P) <-> ((EX x. M(x)) --> P)\"\nby (simp add: rall_def)\n\n(*Congruence rule for rewriting*)\nlemma rall_cong [cong]:\n    \"(!!x. M(x) ==> P(x) <-> P'(x)) ==> (\\<forall>x[M]. P(x)) <-> (\\<forall>x[M]. P'(x))\"\nby (simp add: rall_def)\n\n\nsubsubsection{*Relativized existential quantifier*}\n\nlemma rexI [intro]: \"[| P(x); M(x) |] ==> \\<exists>x[M]. P(x)\"\nby (simp add: rex_def, blast)\n\n(*The best argument order when there is only one M(x)*)\nlemma rev_rexI: \"[| M(x);  P(x) |] ==> \\<exists>x[M]. P(x)\"\nby blast\n\n(*Not of the general form for such rules... *)\nlemma rexCI: \"[| \\<forall>x[M]. ~P(x) ==> P(a); M(a) |] ==> \\<exists>x[M]. P(x)\"\nby blast\n\nlemma rexE [elim!]: \"[| \\<exists>x[M]. P(x);  !!x. [| M(x); P(x) |] ==> Q |] ==> Q\"\nby (simp add: rex_def, blast)\n\n(*We do not even have (EX x[M]. True) <-> True unless A is nonempty!!*)\nlemma rex_triv [simp]: \"(EX x[M]. P) <-> ((EX x. M(x)) & P)\"\nby (simp add: rex_def)\n\nlemma rex_cong [cong]:\n    \"(!!x. M(x) ==> P(x) <-> P'(x)) ==> (\\<exists>x[M]. P(x)) <-> (\\<exists>x[M]. P'(x))\"\nby (simp add: rex_def cong: conj_cong)\n\nlemma rall_is_ball [simp]: \"(\\<forall>x[%z. z\\<in>A]. P(x)) <-> (\\<forall>x\\<in>A. P(x))\"\nby blast\n\nlemma rex_is_bex [simp]: \"(\\<exists>x[%z. z\\<in>A]. P(x)) <-> (\\<exists>x\\<in>A. P(x))\"\nby blast\n\nlemma atomize_rall: \"(!!x. M(x) ==> P(x)) == Trueprop (\\<forall>x[M]. P(x))\"\nby (simp add: rall_def atomize_all atomize_imp)\n\ndeclare atomize_rall [symmetric, rulify]\n\nlemma rall_simps1:\n     \"(\\<forall>x[M]. P(x) & Q)   <-> (\\<forall>x[M]. P(x)) & ((\\<forall>x[M]. False) | Q)\"\n     \"(\\<forall>x[M]. P(x) | Q)   <-> ((\\<forall>x[M]. P(x)) | Q)\"\n     \"(\\<forall>x[M]. P(x) \\<longrightarrow> Q) <-> ((\\<exists>x[M]. P(x)) \\<longrightarrow> Q)\"\n     \"(~(\\<forall>x[M]. P(x))) <-> (\\<exists>x[M]. ~P(x))\"\nby blast+\n\nlemma rall_simps2:\n     \"(\\<forall>x[M]. P & Q(x))   <-> ((\\<forall>x[M]. False) | P) & (\\<forall>x[M]. Q(x))\"\n     \"(\\<forall>x[M]. P | Q(x))   <-> (P | (\\<forall>x[M]. Q(x)))\"\n     \"(\\<forall>x[M]. P \\<longrightarrow> Q(x)) <-> (P \\<longrightarrow> (\\<forall>x[M]. Q(x)))\"\nby blast+\n\nlemmas rall_simps [simp] = rall_simps1 rall_simps2\n\nlemma rall_conj_distrib:\n    \"(\\<forall>x[M]. P(x) & Q(x)) <-> ((\\<forall>x[M]. P(x)) & (\\<forall>x[M]. Q(x)))\"\nby blast\n\nlemma rex_simps1:\n     \"(\\<exists>x[M]. P(x) & Q) <-> ((\\<exists>x[M]. P(x)) & Q)\"\n     \"(\\<exists>x[M]. P(x) | Q) <-> (\\<exists>x[M]. P(x)) | ((\\<exists>x[M]. True) & Q)\"\n     \"(\\<exists>x[M]. P(x) \\<longrightarrow> Q) <-> ((\\<forall>x[M]. P(x)) \\<longrightarrow> ((\\<exists>x[M]. True) & Q))\"\n     \"(~(\\<exists>x[M]. P(x))) <-> (\\<forall>x[M]. ~P(x))\"\nby blast+\n\nlemma rex_simps2:\n     \"(\\<exists>x[M]. P & Q(x)) <-> (P & (\\<exists>x[M]. Q(x)))\"\n     \"(\\<exists>x[M]. P | Q(x)) <-> ((\\<exists>x[M]. True) & P) | (\\<exists>x[M]. Q(x))\"\n     \"(\\<exists>x[M]. P \\<longrightarrow> Q(x)) <-> (((\\<forall>x[M]. False) | P) \\<longrightarrow> (\\<exists>x[M]. Q(x)))\"\nby blast+\n\nlemmas rex_simps [simp] = rex_simps1 rex_simps2\n\nlemma rex_disj_distrib:\n    \"(\\<exists>x[M]. P(x) | Q(x)) <-> ((\\<exists>x[M]. P(x)) | (\\<exists>x[M]. Q(x)))\"\nby blast\n\n\nsubsubsection{*One-point rule for bounded quantifiers*}\n\nlemma rex_triv_one_point1 [simp]: \"(\\<exists>x[M]. x=a) <-> ( M(a))\"\nby blast\n\nlemma rex_triv_one_point2 [simp]: \"(\\<exists>x[M]. a=x) <-> ( M(a))\"\nby blast\n\nlemma rex_one_point1 [simp]: \"(\\<exists>x[M]. x=a & P(x)) <-> ( M(a) & P(a))\"\nby blast\n\nlemma rex_one_point2 [simp]: \"(\\<exists>x[M]. a=x & P(x)) <-> ( M(a) & P(a))\"\nby blast\n\nlemma rall_one_point1 [simp]: \"(\\<forall>x[M]. x=a \\<longrightarrow> P(x)) <-> ( M(a) \\<longrightarrow> P(a))\"\nby blast\n\nlemma rall_one_point2 [simp]: \"(\\<forall>x[M]. a=x \\<longrightarrow> P(x)) <-> ( M(a) \\<longrightarrow> P(a))\"\nby blast\n\n\nsubsubsection{*Sets as Classes*}\n\ndefinition\n  setclass :: \"[i,i] => o\"       (\"##_\" [40] 40)  where\n   \"setclass(A) == %x. x \\<in> A\"\n\nlemma setclass_iff [simp]: \"setclass(A,x) <-> x \\<in> A\"\nby (simp add: setclass_def)\n\nlemma rall_setclass_is_ball [simp]: \"(\\<forall>x[##A]. P(x)) <-> (\\<forall>x\\<in>A. P(x))\"\nby auto\n\nlemma rex_setclass_is_bex [simp]: \"(\\<exists>x[##A]. P(x)) <-> (\\<exists>x\\<in>A. P(x))\"\nby auto\n\n\nML\n{*\nval Ord_atomize =\n  atomize ([(@{const_name oall}, @{thms ospec}), (@{const_name rall}, @{thms rspec})] @\n    ZF_conn_pairs, ZF_mem_pairs);\n*}\ndeclaration {* fn _ =>\n  Simplifier.map_ss (Simplifier.set_mksimps (K (map mk_eq o Ord_atomize o gen_all)))\n*}\n\ntext {* Setting up the one-point-rule simproc *}\n\nsimproc_setup defined_rex (\"\\<exists>x[M]. P(x) & Q(x)\") = {*\n  fn _ => Quantifier1.rearrange_bex\n    (fn ctxt =>\n      unfold_tac ctxt @{thms rex_def} THEN\n      Quantifier1.prove_one_point_ex_tac)\n*}\n\nsimproc_setup defined_rall (\"\\<forall>x[M]. P(x) \\<longrightarrow> Q(x)\") = {*\n  fn _ => Quantifier1.rearrange_ball\n    (fn ctxt =>\n      unfold_tac ctxt @{thms rall_def} THEN\n      Quantifier1.prove_one_point_all_tac)\n*}\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/OrdQuant.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970873650403, "lm_q2_score": 0.8459424431344437, "lm_q1q2_score": 0.7451036399912842}}
{"text": "(*  Title:       Square Matrices\n    Author:      Jonathan Juli\u00e1n Huerta y Munive, 2020\n    Maintainer:  Jonathan Juli\u00e1n Huerta y Munive <jjhuertaymunive1@sheffield.ac.uk>\n*)\n\nsection \\<open> Square Matrices \\<close>\n\ntext\\<open> The general solution for affine systems of ODEs involves the exponential function. \nUnfortunately, this operation is only available in Isabelle for the type class ``banach''. \nHence, we define a type of square matrices and prove that it is an instance of this class.\\<close>\n\ntheory SQ_MTX\n  imports MTX_Norms\n\nbegin\n\nsubsection \\<open> Definition \\<close>\n\ntypedef 'm sq_mtx = \"UNIV::(real^'m^'m) set\"\n  morphisms to_vec to_mtx by simp\n\ndeclare to_mtx_inverse [simp]\n    and to_vec_inverse [simp]\n\nsetup_lifting type_definition_sq_mtx\n\nlift_definition sq_mtx_ith :: \"'m sq_mtx \\<Rightarrow> 'm \\<Rightarrow> (real^'m)\" (infixl \"$$\" 90) is \"($)\" .\n\nlift_definition sq_mtx_vec_mult :: \"'m sq_mtx \\<Rightarrow> (real^'m) \\<Rightarrow> (real^'m)\" (infixl \"*\\<^sub>V\" 90) is \"(*v)\" .\n\nlift_definition vec_sq_mtx_prod :: \"(real^'m) \\<Rightarrow> 'm sq_mtx \\<Rightarrow> (real^'m)\" is \"(v*)\" .\n\nlift_definition sq_mtx_diag :: \"(('m::finite) \\<Rightarrow> real) \\<Rightarrow> ('m::finite) sq_mtx\" (binder \"\\<d>\\<i>\\<a>\\<g> \" 10) \n  is diag_mat .\n\nlift_definition sq_mtx_transpose :: \"('m::finite) sq_mtx \\<Rightarrow> 'm sq_mtx\" (\"_\\<^sup>\\<dagger>\") is transpose .\n\nlift_definition sq_mtx_inv :: \"('m::finite) sq_mtx \\<Rightarrow> 'm sq_mtx\" (\"_\\<^sup>-\\<^sup>1\" [90]) is matrix_inv .\n\nlift_definition sq_mtx_row :: \"'m \\<Rightarrow> ('m::finite) sq_mtx \\<Rightarrow> real^'m\" (\"\\<r>\\<o>\\<w>\") is row .\n\nlift_definition sq_mtx_col :: \"'m \\<Rightarrow> ('m::finite) sq_mtx \\<Rightarrow> real^'m\" (\"\\<c>\\<o>\\<l>\")  is column .\n\nlemma to_vec_eq_ith: \"(to_vec A) $ i = A $$ i\"\n  by transfer simp\n\nlemma to_mtx_ith[simp]: \n  \"(to_mtx A) $$ i1 = A $ i1\"\n  \"(to_mtx A) $$ i1 $ i2 = A $ i1 $ i2\"\n  by (transfer, simp)+\n\nlemma to_mtx_vec_lambda_ith[simp]: \"to_mtx (\\<chi> i j. x i j) $$ i1 $ i2 = x i1 i2\"\n  by (simp add: sq_mtx_ith_def)\n\nlemma sq_mtx_eq_iff:\n  shows \"A = B = (\\<forall>i j. A $$ i $ j = B $$ i $ j)\"\n    and \"A = B = (\\<forall>i. A $$ i = B $$ i)\"\n  by (transfer, simp add: vec_eq_iff)+\n\nlemma sq_mtx_diag_simps[simp]:\n  \"i = j \\<Longrightarrow> sq_mtx_diag f $$ i $ j = f i\"\n  \"i \\<noteq> j \\<Longrightarrow> sq_mtx_diag f $$ i $ j = 0\"\n  \"sq_mtx_diag f $$ i = axis i (f i)\"\n  unfolding sq_mtx_diag_def by (simp_all add: axis_def vec_eq_iff)\n\n\n\nlemma sq_mtx_vec_mult_diag_axis: \"(\\<d>\\<i>\\<a>\\<g> i. f i) *\\<^sub>V (axis i k) = axis i (f i * k)\"\n  unfolding sq_mtx_diag_vec_mult axis_def by auto\n\nlemma sq_mtx_vec_mult_eq: \"m *\\<^sub>V x = (\\<chi> i. sum (\\<lambda>j. (m $$ i $ j) * (x $ j)) UNIV)\"\n  by (transfer, simp add: matrix_vector_mult_def)\n\nlemma sq_mtx_transpose_transpose[simp]: \"(A\\<^sup>\\<dagger>)\\<^sup>\\<dagger> = A\"\n  by (transfer, simp)\n\nlemma transpose_mult_vec_canon_row[simp]: \"(A\\<^sup>\\<dagger>) *\\<^sub>V (\\<e> i) = \\<r>\\<o>\\<w> i A\"\n  by transfer (simp add: row_def transpose_def axis_def matrix_vector_mult_def)\n\nlemma row_ith[simp]: \"\\<r>\\<o>\\<w> i A = A $$ i\"\n  by transfer (simp add: row_def)\n\nlemma mtx_vec_mult_canon: \"A *\\<^sub>V (\\<e> i) = \\<c>\\<o>\\<l> i A\" \n  by (transfer, simp add: matrix_vector_mult_basis)\n\n\nsubsection \\<open> Ring of square matrices \\<close>\n\ninstantiation sq_mtx :: (finite) ring \nbegin\n\nlift_definition plus_sq_mtx :: \"'a sq_mtx \\<Rightarrow> 'a sq_mtx \\<Rightarrow> 'a sq_mtx\" is \"(+)\" .\n\nlift_definition zero_sq_mtx :: \"'a sq_mtx\" is \"0\" .\n\nlift_definition uminus_sq_mtx :: \"'a sq_mtx \\<Rightarrow> 'a sq_mtx\" is \"uminus\" .\n\nlift_definition minus_sq_mtx :: \"'a sq_mtx \\<Rightarrow> 'a sq_mtx \\<Rightarrow> 'a sq_mtx\" is \"(-)\" .\n\nlift_definition times_sq_mtx :: \"'a sq_mtx \\<Rightarrow> 'a sq_mtx \\<Rightarrow> 'a sq_mtx\" is \"(**)\" .\n\ndeclare plus_sq_mtx.rep_eq [simp]\n    and minus_sq_mtx.rep_eq [simp]\n\ninstance apply intro_classes\n  by(transfer, simp add: algebra_simps matrix_mul_assoc matrix_add_rdistrib matrix_add_ldistrib)+\n\nend\n\nlemma sq_mtx_zero_ith[simp]: \"0 $$ i = 0\"\n  by (transfer, simp)\n\nlemma sq_mtx_zero_nth[simp]: \"0 $$ i $ j = 0\"\n  by transfer simp\n\nlemma sq_mtx_plus_eq: \"A + B = to_mtx (\\<chi> i j. A$$i$j + B$$i$j)\"\n  by transfer (simp add: vec_eq_iff)\n\nlemma sq_mtx_plus_ith[simp]:\"(A + B) $$ i = A $$ i + B $$ i\"\n  unfolding sq_mtx_plus_eq by (simp add: vec_eq_iff)\n\n\n\nlemma sq_mtx_minus_eq: \"A - B = to_mtx (\\<chi> i j. A$$i$j - B$$i$j)\"\n  by transfer (simp add: vec_eq_iff)\n\nlemma sq_mtx_minus_ith[simp]:\"(A - B) $$ i = A $$ i - B $$ i\"\n  unfolding sq_mtx_minus_eq by (simp add: vec_eq_iff)\n\nlemma sq_mtx_times_eq: \"A * B = to_mtx (\\<chi> i j. sum (\\<lambda>k. A$$i$k * B$$k$j) UNIV)\"\n  by transfer (simp add: matrix_matrix_mult_def)\n\nlemma sq_mtx_plus_diag_diag[simp]: \"sq_mtx_diag f + sq_mtx_diag g = (\\<d>\\<i>\\<a>\\<g> i. f i + g i)\"\n  by (subst sq_mtx_eq_iff) (simp add: axis_def)\n\nlemma sq_mtx_minus_diag_diag[simp]: \"sq_mtx_diag f - sq_mtx_diag g = (\\<d>\\<i>\\<a>\\<g> i. f i - g i)\"\n  by (subst sq_mtx_eq_iff) (simp add: axis_def)\n\nlemma sum_sq_mtx_diag[simp]: \"(\\<Sum>n<m. sq_mtx_diag (g n)) = (\\<d>\\<i>\\<a>\\<g> i. \\<Sum>n<m. (g n i))\" for m::nat\n  by (induct m, simp, subst sq_mtx_eq_iff, simp_all)\n\nlemma sq_mtx_mult_diag_diag[simp]: \"sq_mtx_diag f * sq_mtx_diag g = (\\<d>\\<i>\\<a>\\<g> i. f i * g i)\"\n  by (simp add: matrix_mul_diag_diag sq_mtx_diag.abs_eq times_sq_mtx.abs_eq)\n\nlemma sq_mtx_mult_diagl: \"(\\<d>\\<i>\\<a>\\<g> i. f i) * A = to_mtx (\\<chi> i j. f i * A $$ i $ j)\"\n  by transfer (simp add: matrix_mul_diag_matl)\n\nlemma sq_mtx_mult_diagr: \"A * (\\<d>\\<i>\\<a>\\<g> i. f i) = to_mtx (\\<chi> i j. A $$ i $ j * f j)\"\n  by transfer (simp add: matrix_matrix_mul_diag_matr)\n\nlemma mtx_vec_mult_0l[simp]: \"0 *\\<^sub>V x = 0\"\n  by (simp add: sq_mtx_vec_mult.abs_eq zero_sq_mtx_def)\n\nlemma mtx_vec_mult_0r[simp]: \"A *\\<^sub>V 0 = 0\"\n  by (transfer, simp)\n\nlemma mtx_vec_mult_add_rdistr: \"(A + B) *\\<^sub>V x = A *\\<^sub>V x + B *\\<^sub>V x\"\n  unfolding plus_sq_mtx_def \n  apply(transfer)\n  by (simp add: matrix_vector_mult_add_rdistrib)\n\nlemma mtx_vec_mult_add_rdistl: \"A *\\<^sub>V (x + y) = A *\\<^sub>V x + A *\\<^sub>V y\"\n  unfolding plus_sq_mtx_def \n  apply transfer\n  by (simp add: matrix_vector_right_distrib)\n\nlemma mtx_vec_mult_minus_rdistrib: \"(A - B) *\\<^sub>V x = A *\\<^sub>V x - B *\\<^sub>V x\"\n  unfolding minus_sq_mtx_def by(transfer, simp add: matrix_vector_mult_diff_rdistrib)\n\nlemma mtx_vec_mult_minus_ldistrib: \"A *\\<^sub>V (x - y) =  A *\\<^sub>V x -  A *\\<^sub>V y\"\n  by (metis (no_types, lifting) add_diff_cancel diff_add_cancel \n      matrix_vector_right_distrib sq_mtx_vec_mult.rep_eq)\n\nlemma sq_mtx_times_vec_assoc: \"(A * B) *\\<^sub>V x = A *\\<^sub>V (B *\\<^sub>V x)\"\n  by (transfer, simp add: matrix_vector_mul_assoc)\n\nlemma sq_mtx_vec_mult_sum_cols: \"A *\\<^sub>V x = sum (\\<lambda>i. x $ i *\\<^sub>R \\<c>\\<o>\\<l> i A) UNIV\"\n  by(transfer) (simp add: matrix_mult_sum scalar_mult_eq_scaleR)\n\n\nsubsection \\<open> Real normed vector space of square matrices \\<close>\n\ninstantiation sq_mtx :: (finite) real_normed_vector \nbegin\n\ndefinition norm_sq_mtx :: \"'a sq_mtx \\<Rightarrow> real\" where \"\\<parallel>A\\<parallel> = \\<parallel>to_vec A\\<parallel>\\<^sub>o\\<^sub>p\"\n\nlift_definition scaleR_sq_mtx :: \"real \\<Rightarrow> 'a sq_mtx \\<Rightarrow> 'a sq_mtx\" is scaleR .\n\ndefinition sgn_sq_mtx :: \"'a sq_mtx \\<Rightarrow> 'a sq_mtx\" \n  where \"sgn_sq_mtx A = (inverse (\\<parallel>A\\<parallel>)) *\\<^sub>R A\"\n\ndefinition dist_sq_mtx :: \"'a sq_mtx \\<Rightarrow> 'a sq_mtx \\<Rightarrow> real\" \n  where \"dist_sq_mtx A B = \\<parallel>A - B\\<parallel>\" \n\ndefinition uniformity_sq_mtx :: \"('a sq_mtx \\<times> 'a sq_mtx) filter\" \n  where \"uniformity_sq_mtx = (INF e\\<in>{0<..}. principal {(x, y). dist x y < e})\"\n\ndefinition open_sq_mtx :: \"'a sq_mtx set \\<Rightarrow> bool\" \n  where \"open_sq_mtx U = (\\<forall>x\\<in>U. \\<forall>\\<^sub>F (x', y) in uniformity. x' = x \\<longrightarrow> y \\<in> U)\"\n\ninstance apply intro_classes \n  unfolding sgn_sq_mtx_def open_sq_mtx_def dist_sq_mtx_def uniformity_sq_mtx_def\n            prefer 10 \n            apply(transfer, simp add: norm_sq_mtx_def op_norm_triangle)\n           prefer 9 \n           apply(simp_all add: norm_sq_mtx_def zero_sq_mtx_def op_norm_eq_0)\n  by (transfer, simp add: norm_sq_mtx_def op_norm_scaleR algebra_simps)+\n\nend\n\nlemma sq_mtx_scaleR_eq: \"c *\\<^sub>R A = to_mtx (\\<chi> i j. c *\\<^sub>R A $$ i $ j)\"\n  by transfer (simp add: vec_eq_iff)\n\nlemma scaleR_to_mtx_ith[simp]: \"c *\\<^sub>R (to_mtx A) $$ i1 $ i2 = c * A $ i1 $ i2\"\n  by transfer (simp add: scaleR_vec_def)\n\nlemma sq_mtx_scaleR_ith[simp]: \"(c *\\<^sub>R A) $$ i = (c  *\\<^sub>R (A $$ i))\"\n  by (unfold scaleR_sq_mtx_def, transfer, simp)\n\nlemma scaleR_sq_mtx_diag: \"c *\\<^sub>R sq_mtx_diag f = (\\<d>\\<i>\\<a>\\<g> i. c * f i)\"\n  by (subst sq_mtx_eq_iff, simp add: axis_def)\n\nlemma scaleR_mtx_vec_assoc: \"(c *\\<^sub>R A) *\\<^sub>V x = c *\\<^sub>R (A *\\<^sub>V x)\"\n  unfolding scaleR_sq_mtx_def sq_mtx_vec_mult_def apply simp\n  by (simp add: scaleR_matrix_vector_assoc)\n\nlemma mtx_vec_scaleR_commute: \"A *\\<^sub>V (c *\\<^sub>R x) = c *\\<^sub>R (A *\\<^sub>V x)\"\n  unfolding scaleR_sq_mtx_def sq_mtx_vec_mult_def apply(simp, transfer)\n  by (simp add: vector_scaleR_commute)\n\nlemma mtx_times_scaleR_commute: \"A * (c *\\<^sub>R B) = c *\\<^sub>R (A * B)\" for A::\"('n::finite) sq_mtx\"\n  unfolding sq_mtx_scaleR_eq sq_mtx_times_eq \n  apply(simp add: to_mtx_inject)\n  apply(simp add: vec_eq_iff fun_eq_iff)\n  by (simp add: semiring_normalization_rules(19) vector_space_over_itself.scale_sum_right)\n\nlemma le_mtx_norm: \"m \\<in> {\\<parallel>A *\\<^sub>V x\\<parallel> |x. \\<parallel>x\\<parallel> = 1} \\<Longrightarrow> m \\<le> \\<parallel>A\\<parallel>\"\n  using cSup_upper[of _ \"{\\<parallel>(to_vec A) *v x\\<parallel> | x. \\<parallel>x\\<parallel> = 1}\"]\n  by (simp add: op_norm_set_proptys(2) op_norm_def norm_sq_mtx_def sq_mtx_vec_mult.rep_eq)\n\nlemma norm_vec_mult_le: \"\\<parallel>A *\\<^sub>V x\\<parallel> \\<le> (\\<parallel>A\\<parallel>) * (\\<parallel>x\\<parallel>)\"\n  by (simp add: norm_matrix_le_mult_op_norm norm_sq_mtx_def sq_mtx_vec_mult.rep_eq)\n\nlemma bounded_bilinear_sq_mtx_vec_mult: \"bounded_bilinear (\\<lambda>A s. A *\\<^sub>V s)\"\n  apply (rule bounded_bilinear.intro, simp_all add: mtx_vec_mult_add_rdistr \n      mtx_vec_mult_add_rdistl scaleR_mtx_vec_assoc mtx_vec_scaleR_commute)\n  by (rule_tac x=1 in exI, auto intro!: norm_vec_mult_le)\n\nlemma norm_sq_mtx_def2: \"\\<parallel>A\\<parallel> = Sup {\\<parallel>A *\\<^sub>V x\\<parallel> |x. \\<parallel>x\\<parallel> = 1}\"\n  unfolding norm_sq_mtx_def op_norm_def sq_mtx_vec_mult_def by simp\n\nlemma norm_sq_mtx_def3: \"\\<parallel>A\\<parallel> = (SUP x. (\\<parallel>A *\\<^sub>V x\\<parallel>) / (\\<parallel>x\\<parallel>))\"\n  unfolding norm_sq_mtx_def onorm_def sq_mtx_vec_mult_def by simp\n\nlemma norm_sq_mtx_diag: \"\\<parallel>sq_mtx_diag f\\<parallel> = Max {\\<bar>f i\\<bar> |i. i \\<in> UNIV}\"\n  unfolding norm_sq_mtx_def apply transfer\n  by (rule op_norm_diag_mat_eq)\n\nlemma sq_mtx_norm_le_sum_col: \"\\<parallel>A\\<parallel> \\<le> (\\<Sum>i\\<in>UNIV. \\<parallel>\\<c>\\<o>\\<l> i A\\<parallel>)\"\n  using op_norm_le_sum_column[of \"to_vec A\"] \n  apply(simp add: norm_sq_mtx_def)\n  by(transfer, simp add: op_norm_le_sum_column)\n\nlemma norm_le_transpose: \"\\<parallel>A\\<parallel> \\<le> \\<parallel>A\\<^sup>\\<dagger>\\<parallel>\"\n  unfolding norm_sq_mtx_def by transfer (rule op_norm_le_transpose)\n\nlemma norm_eq_norm_transpose[simp]: \"\\<parallel>A\\<^sup>\\<dagger>\\<parallel> = \\<parallel>A\\<parallel>\"\n  using norm_le_transpose[of A] and norm_le_transpose[of \"A\\<^sup>\\<dagger>\"] by simp\n\nlemma norm_column_le_norm: \"\\<parallel>A $$ i\\<parallel> \\<le> \\<parallel>A\\<parallel>\"\n  using norm_vec_mult_le[of \"A\\<^sup>\\<dagger>\" \"\\<e> i\"] by simp\n\n\nsubsection \\<open> Real normed algebra of square matrices \\<close>\n\ninstantiation sq_mtx :: (finite) real_normed_algebra_1\nbegin\n\nlift_definition one_sq_mtx :: \"'a sq_mtx\" is \"to_mtx (mat 1)\" .\n\nlemma sq_mtx_one_idty: \"1 * A = A\" \"A * 1 = A\" for A :: \"'a sq_mtx\"\n  by(transfer, transfer, unfold mat_def matrix_matrix_mult_def, simp add: vec_eq_iff)+\n\nlemma sq_mtx_norm_1: \"\\<parallel>(1::'a sq_mtx)\\<parallel> = 1\"\n  unfolding one_sq_mtx_def norm_sq_mtx_def \n  apply(simp add: op_norm_def)\n  apply(subst cSup_eq[of _ 1])\n  using ex_norm_eq_1 by auto\n\nlemma sq_mtx_norm_times: \"\\<parallel>A * B\\<parallel> \\<le> (\\<parallel>A\\<parallel>) * (\\<parallel>B\\<parallel>)\" for A :: \"'a sq_mtx\"\n  unfolding norm_sq_mtx_def times_sq_mtx_def by(simp add: op_norm_matrix_matrix_mult_le)\n\ninstance \n  apply intro_classes \n  apply(simp_all add: sq_mtx_one_idty sq_mtx_norm_1 sq_mtx_norm_times)\n  apply(simp_all add: to_mtx_inject vec_eq_iff one_sq_mtx_def zero_sq_mtx_def mat_def)\n  by(transfer, simp add: scalar_matrix_assoc matrix_scalar_ac)+\n\nend\n\nlemma sq_mtx_one_ith_simps[simp]: \"1 $$ i $ i = 1\" \"i \\<noteq> j \\<Longrightarrow> 1 $$ i $ j = 0\"\n  unfolding one_sq_mtx_def mat_def by simp_all\n\nlemma of_nat_eq_sq_mtx_diag[simp]: \"of_nat m = (\\<d>\\<i>\\<a>\\<g> i. m)\"\n  by (induct m) (simp, subst sq_mtx_eq_iff, simp add: axis_def)+\n\nlemma mtx_vec_mult_1[simp]: \"1 *\\<^sub>V s = s\"\n  by (auto simp: sq_mtx_vec_mult_def one_sq_mtx_def \n      mat_def vec_eq_iff matrix_vector_mult_def)\n\nlemma sq_mtx_diag_one[simp]: \"(\\<d>\\<i>\\<a>\\<g> i. 1) = 1\"\n  by (subst sq_mtx_eq_iff, simp add: one_sq_mtx_def mat_def axis_def)\n\nabbreviation \"mtx_invertible A \\<equiv> invertible (to_vec A)\"\n\nlemma mtx_invertible_def: \"mtx_invertible A \\<longleftrightarrow> (\\<exists>A'. A' * A = 1 \\<and> A * A' = 1)\"\n  apply (unfold sq_mtx_inv_def times_sq_mtx_def one_sq_mtx_def invertible_def, clarsimp, safe)\n   apply(rule_tac x=\"to_mtx A'\" in exI, simp)\n  by (rule_tac x=\"to_vec A'\" in exI, simp add: to_mtx_inject)\n\n\n\nlemma mtx_invertibleD[simp]:\n  assumes \"mtx_invertible A\" \n  shows \"A\\<^sup>-\\<^sup>1 * A = 1\" and \"A * A\\<^sup>-\\<^sup>1 = 1\"\n  apply (unfold sq_mtx_inv_def times_sq_mtx_def one_sq_mtx_def)\n  using assms by simp_all\n\nlemma mtx_invertible_inv[simp]: \"mtx_invertible A \\<Longrightarrow> mtx_invertible (A\\<^sup>-\\<^sup>1)\"\n  using mtx_invertibleD mtx_invertibleI by blast\n\nlemma mtx_invertible_one[simp]: \"mtx_invertible 1\"\n  by (simp add: one_sq_mtx.rep_eq)\n\nlemma sq_mtx_inv_unique:\n  assumes \"A * B = 1\" and \"B * A = 1\"\n  shows \"A\\<^sup>-\\<^sup>1 = B\"\n  by (metis (no_types, lifting) assms mtx_invertibleD(2) \n      mtx_invertibleI mult.assoc sq_mtx_one_idty(1))\n\nlemma sq_mtx_inv_idempotent[simp]: \"mtx_invertible A \\<Longrightarrow> A\\<^sup>-\\<^sup>1\\<^sup>-\\<^sup>1 = A\"\n  using mtx_invertibleD sq_mtx_inv_unique by blast\n\nlemma sq_mtx_inv_mult:\n  assumes \"mtx_invertible A\" and \"mtx_invertible B\"\n  shows \"(A * B)\\<^sup>-\\<^sup>1 = B\\<^sup>-\\<^sup>1 * A\\<^sup>-\\<^sup>1\"\n  by (simp add: assms matrix_inv_matrix_mul sq_mtx_inv_def times_sq_mtx_def)\n\nlemma sq_mtx_inv_one[simp]: \"1\\<^sup>-\\<^sup>1 = 1\"\n  by (simp add: sq_mtx_inv_unique)\n\ndefinition similar_sq_mtx :: \"('n::finite) sq_mtx \\<Rightarrow> 'n sq_mtx \\<Rightarrow> bool\" (infixr \"\\<sim>\" 25)\n  where \"(A \\<sim> B) \\<longleftrightarrow> (\\<exists> P. mtx_invertible P \\<and> A = P\\<^sup>-\\<^sup>1 * B * P)\"\n\nlemma similar_sq_mtx_matrix: \"(A \\<sim> B) = similar_matrix (to_vec A) (to_vec B)\"\n  apply(unfold similar_matrix_def similar_sq_mtx_def, safe)\n   apply (metis sq_mtx_inv.rep_eq times_sq_mtx.rep_eq)\n  by (metis UNIV_I sq_mtx_inv.abs_eq times_sq_mtx.abs_eq to_mtx_inverse to_vec_inverse)\n\nlemma similar_sq_mtx_refl[simp]: \"A \\<sim> A\"\n  by (unfold similar_sq_mtx_def, rule_tac x=\"1\" in exI, simp)\n\nlemma similar_sq_mtx_simm: \"A \\<sim> B \\<Longrightarrow> B \\<sim> A\"\n  apply(unfold similar_sq_mtx_def, clarsimp)\n  apply(rule_tac x=\"P\\<^sup>-\\<^sup>1\" in exI, simp add: mult.assoc)\n  by (metis mtx_invertibleD(2) mult.assoc mult.left_neutral)\n\nlemma similar_sq_mtx_trans: \"A \\<sim> B \\<Longrightarrow> B \\<sim> C \\<Longrightarrow> A \\<sim> C\"\n  unfolding similar_sq_mtx_matrix using similar_matrix_trans by blast\n\n\n\nlemma power_similiar_sq_mtx_diag_eq:\n  assumes \"mtx_invertible P\"\n      and \"A = P\\<^sup>-\\<^sup>1 * (sq_mtx_diag f) * P\"\n    shows \"A^n = P\\<^sup>-\\<^sup>1 * (\\<d>\\<i>\\<a>\\<g> i. f i^n) * P\"\nproof(induct n, simp_all add: assms)\n  fix n::nat\n  have \"P\\<^sup>-\\<^sup>1 * sq_mtx_diag f * P * (P\\<^sup>-\\<^sup>1 * (\\<d>\\<i>\\<a>\\<g> i. f i ^ n) * P) = \n  P\\<^sup>-\\<^sup>1 * sq_mtx_diag f * (\\<d>\\<i>\\<a>\\<g> i. f i ^ n) * P\"\n    by (metis (no_types, lifting) assms(1) mtx_invertibleD(2) mult.assoc mult.right_neutral)\n  also have \"... = P\\<^sup>-\\<^sup>1 * (\\<d>\\<i>\\<a>\\<g> i. f i * f i ^ n) * P\"\n    by (simp add: mult.assoc) \n  finally show \"P\\<^sup>-\\<^sup>1 * sq_mtx_diag f * P * (P\\<^sup>-\\<^sup>1 * (\\<d>\\<i>\\<a>\\<g> i. f i ^ n) * P) = \n  P\\<^sup>-\\<^sup>1 * (\\<d>\\<i>\\<a>\\<g> i. f i * f i ^ n) * P\" .\nqed\n\nlemma power_similar_sq_mtx_diag:\n  assumes \"A \\<sim> (sq_mtx_diag f)\"\n  shows \"A^n \\<sim> (\\<d>\\<i>\\<a>\\<g> i. f i^n)\"\n  using assms power_similiar_sq_mtx_diag_eq \n  unfolding similar_sq_mtx_def by blast\n\n\nsubsection \\<open> Banach space of square matrices \\<close>\n\nlemma Cauchy_cols:\n  fixes X :: \"nat \\<Rightarrow> ('a::finite) sq_mtx\" \n  assumes \"Cauchy X\"\n  shows \"Cauchy (\\<lambda>n. \\<c>\\<o>\\<l> i (X n))\" \nproof(unfold Cauchy_def dist_norm, clarsimp)\n  fix \\<epsilon>::real assume \"\\<epsilon> > 0\"\n  then obtain M where M_def:\"\\<forall>m\\<ge>M. \\<forall>n\\<ge>M. \\<parallel>X m - X n\\<parallel> < \\<epsilon>\"\n    using \\<open>Cauchy X\\<close> unfolding Cauchy_def by(simp add: dist_sq_mtx_def) metis\n  {fix m n assume \"m \\<ge> M\" and \"n \\<ge> M\"\n    hence \"\\<epsilon> > \\<parallel>X m - X n\\<parallel>\" \n      using M_def by blast\n    moreover have \"\\<parallel>X m - X n\\<parallel> \\<ge> \\<parallel>(X m - X n) *\\<^sub>V \\<e> i\\<parallel>\"\n      by(rule le_mtx_norm[of _ \"X m - X n\"], force)\n    moreover have \"\\<parallel>(X m - X n) *\\<^sub>V \\<e> i\\<parallel> = \\<parallel>X m *\\<^sub>V \\<e> i - X n *\\<^sub>V \\<e> i\\<parallel>\"\n      by (simp add: mtx_vec_mult_minus_rdistrib)\n    moreover have \"... = \\<parallel>\\<c>\\<o>\\<l> i (X m) - \\<c>\\<o>\\<l> i (X n)\\<parallel>\"\n      by (simp add: mtx_vec_mult_minus_rdistrib mtx_vec_mult_canon)\n    ultimately have \"\\<parallel>\\<c>\\<o>\\<l> i (X m) - \\<c>\\<o>\\<l> i (X n)\\<parallel> < \\<epsilon>\" \n      by linarith}\n  thus \"\\<exists>M. \\<forall>m\\<ge>M. \\<forall>n\\<ge>M. \\<parallel>\\<c>\\<o>\\<l> i (X m) - \\<c>\\<o>\\<l> i (X n)\\<parallel> < \\<epsilon>\" \n    by blast\nqed\n\nlemma col_convergence:\n  assumes \"\\<forall>i. (\\<lambda>n. \\<c>\\<o>\\<l> i (X n)) \\<longlonglongrightarrow> L $ i\" \n  shows \"X \\<longlonglongrightarrow> to_mtx (transpose L)\"\nproof(unfold LIMSEQ_def dist_norm, clarsimp)\n  let ?L = \"to_mtx (transpose L)\"\n  let ?a = \"CARD('a)\" fix \\<epsilon>::real assume \"\\<epsilon> > 0\"\n  hence \"\\<epsilon> / ?a > 0\" by simp\n  hence \"\\<forall>i. \\<exists> N. \\<forall>n\\<ge>N. \\<parallel>\\<c>\\<o>\\<l> i (X n) - L $ i\\<parallel> < \\<epsilon>/?a\"\n    using assms unfolding LIMSEQ_def dist_norm convergent_def by blast\n  then obtain N where \"\\<forall>i. \\<forall>n\\<ge>N. \\<parallel>\\<c>\\<o>\\<l> i (X n) - L $ i\\<parallel> < \\<epsilon>/?a\"\n    using finite_nat_minimal_witness[of \"\\<lambda> i n. \\<parallel>\\<c>\\<o>\\<l> i (X n) - L $ i\\<parallel> < \\<epsilon>/?a\"] by blast\n  also have \"\\<And>i n. (\\<c>\\<o>\\<l> i (X n) - L $ i) = (\\<c>\\<o>\\<l> i (X n - ?L))\"\n    unfolding minus_sq_mtx_def by(transfer, simp add: transpose_def vec_eq_iff column_def)\n  ultimately have N_def:\"\\<forall>i. \\<forall>n\\<ge>N. \\<parallel>\\<c>\\<o>\\<l> i (X n - ?L)\\<parallel> < \\<epsilon>/?a\" \n    by auto\n  have \"\\<forall>n\\<ge>N. \\<parallel>X n - ?L\\<parallel> < \\<epsilon>\"\n  proof(rule allI, rule impI)\n    fix n::nat assume \"N \\<le> n\"\n    hence \"\\<forall> i. \\<parallel>\\<c>\\<o>\\<l> i (X n - ?L)\\<parallel> < \\<epsilon>/?a\"\n      using N_def by blast\n    hence \"(\\<Sum>i\\<in>UNIV. \\<parallel>\\<c>\\<o>\\<l> i (X n - ?L)\\<parallel>) < (\\<Sum>(i::'a)\\<in>UNIV. \\<epsilon>/?a)\"\n      using sum_strict_mono[of _ \"\\<lambda>i. \\<parallel>\\<c>\\<o>\\<l> i (X n - ?L)\\<parallel>\"] by force\n    moreover have \"\\<parallel>X n - ?L\\<parallel> \\<le> (\\<Sum>i\\<in>UNIV. \\<parallel>\\<c>\\<o>\\<l> i (X n - ?L)\\<parallel>)\"\n      using sq_mtx_norm_le_sum_col by blast\n    moreover have \"(\\<Sum>(i::'a)\\<in>UNIV. \\<epsilon>/?a) = \\<epsilon>\" \n      by force\n    ultimately show \"\\<parallel>X n - ?L\\<parallel> < \\<epsilon>\" \n      by linarith\n  qed\n  thus \"\\<exists>no. \\<forall>n\\<ge>no. \\<parallel>X n - ?L\\<parallel> < \\<epsilon>\" \n    by blast\nqed\n\ninstance sq_mtx :: (finite) banach\nproof(standard)\n  fix X :: \"nat \\<Rightarrow> 'a sq_mtx\"\n  assume \"Cauchy X\"\n  hence \"\\<And>i. Cauchy (\\<lambda>n. \\<c>\\<o>\\<l> i (X n))\"\n    using Cauchy_cols by blast\n  hence obs: \"\\<forall>i. \\<exists>! L. (\\<lambda>n. \\<c>\\<o>\\<l> i (X n)) \\<longlonglongrightarrow> L\"\n    using Cauchy_convergent convergent_def LIMSEQ_unique by fastforce\n  define L where \"L = (\\<chi> i. lim (\\<lambda>n. \\<c>\\<o>\\<l> i (X n)))\"\n  hence \"\\<forall>i. (\\<lambda>n. \\<c>\\<o>\\<l> i (X n)) \\<longlonglongrightarrow> L $ i\" \n    using obs theI_unique[of \"\\<lambda>L. (\\<lambda>n. \\<c>\\<o>\\<l> _ (X n)) \\<longlonglongrightarrow> L\" \"L $ _\"] by (simp add: lim_def)\n  thus \"convergent X\"\n    using col_convergence unfolding convergent_def by blast\nqed\n\nlemma exp_similiar_sq_mtx_diag_eq:\n  assumes \"mtx_invertible P\"\n      and \"A = P\\<^sup>-\\<^sup>1 * (\\<d>\\<i>\\<a>\\<g> i. f i) * P\"\n    shows \"exp A = P\\<^sup>-\\<^sup>1 * exp (\\<d>\\<i>\\<a>\\<g> i. f i) * P\"\nproof(unfold exp_def power_similiar_sq_mtx_diag_eq[OF assms])\n  have \"(\\<Sum>n. P\\<^sup>-\\<^sup>1 * (\\<d>\\<i>\\<a>\\<g> i. f i ^ n) * P /\\<^sub>R fact n) = \n  (\\<Sum>n. P\\<^sup>-\\<^sup>1 * ((\\<d>\\<i>\\<a>\\<g> i. f i ^ n) /\\<^sub>R fact n) * P)\"\n    by simp\n  also have \"... = (\\<Sum>n. P\\<^sup>-\\<^sup>1 * ((\\<d>\\<i>\\<a>\\<g> i. f i ^ n) /\\<^sub>R fact n)) * P\"\n    apply(subst suminf_multr[OF bounded_linear.summable[OF bounded_linear_mult_right]])\n    unfolding power_sq_mtx_diag[symmetric] by (simp_all add: summable_exp_generic)\n  also have \"... = P\\<^sup>-\\<^sup>1 * (\\<Sum>n. (\\<d>\\<i>\\<a>\\<g> i. f i ^ n) /\\<^sub>R fact n) * P\"\n    apply(subst suminf_mult[of _ \"P\\<^sup>-\\<^sup>1\"])\n    unfolding power_sq_mtx_diag[symmetric] \n    by (simp_all add: summable_exp_generic)\n  finally show \"(\\<Sum>n. P\\<^sup>-\\<^sup>1 * (\\<d>\\<i>\\<a>\\<g> i. f i ^ n) * P /\\<^sub>R fact n) = \n  P\\<^sup>-\\<^sup>1 * (\\<Sum>n. sq_mtx_diag f ^ n /\\<^sub>R fact n) * P\"\n    unfolding power_sq_mtx_diag by simp\nqed\n\nlemma exp_similiar_sq_mtx_diag:\n  assumes \"A \\<sim> sq_mtx_diag f\"\n  shows \"exp A \\<sim> exp (sq_mtx_diag f)\"\n  using assms exp_similiar_sq_mtx_diag_eq \n  unfolding similar_sq_mtx_def by blast\n\nlemma suminf_sq_mtx_diag:\n  assumes \"\\<forall>i. (\\<lambda>n. f n i) sums (suminf (\\<lambda>n. f n i))\"\n  shows \"(\\<Sum>n. (\\<d>\\<i>\\<a>\\<g> i. f n i)) = (\\<d>\\<i>\\<a>\\<g> i. \\<Sum>n. f n i)\"\nproof(rule suminfI, unfold sums_def LIMSEQ_iff, clarsimp simp: norm_sq_mtx_diag)\n  let ?g = \"\\<lambda>n i. \\<bar>(\\<Sum>n<n. f n i) - (\\<Sum>n. f n i)\\<bar>\"\n  fix r::real assume \"r > 0\"\n  have \"\\<forall>i. \\<exists>no. \\<forall>n\\<ge>no. ?g n i < r\"\n    using assms \\<open>r > 0\\<close> unfolding sums_def LIMSEQ_iff by clarsimp \n  then obtain N where key: \"\\<forall>i. \\<forall>n\\<ge>N. ?g n i < r\"\n    using finite_nat_minimal_witness[of \"\\<lambda>i n. ?g n i < r\"] by blast\n  {fix n::nat\n    assume \"n \\<ge> N\"\n    obtain i where i_def: \"Max {x. \\<exists>i. x = ?g n i} = ?g n i\"\n      using cMax_finite_ex[of \"{x. \\<exists>i. x = ?g n i}\"] by auto\n    hence \"?g n i < r\"\n      using key \\<open>n \\<ge> N\\<close> by blast\n    hence \"Max {x. \\<exists>i. x = ?g n i} < r\"\n      unfolding i_def[symmetric] .}\n  thus \"\\<exists>N. \\<forall>n\\<ge>N. Max {x. \\<exists>i. x = ?g n i} < r\"\n    by blast\nqed\n\nlemma exp_sq_mtx_diag: \"exp (sq_mtx_diag f) = (\\<d>\\<i>\\<a>\\<g> i. exp (f i))\"\n  apply(unfold exp_def, simp add: power_sq_mtx_diag scaleR_sq_mtx_diag)\n  apply(rule suminf_sq_mtx_diag)\n  using exp_converges[of \"f _\"] \n  unfolding sums_def LIMSEQ_iff exp_def by force\n\nlemma exp_scaleR_diagonal1:\n  assumes \"mtx_invertible P\" and \"A = P\\<^sup>-\\<^sup>1 * (\\<d>\\<i>\\<a>\\<g> i. f i) * P\"\n    shows \"exp (t *\\<^sub>R A) = P\\<^sup>-\\<^sup>1 * (\\<d>\\<i>\\<a>\\<g> i. exp (t * f i)) * P\"\nproof-\n  have \"exp (t *\\<^sub>R A) = exp (P\\<^sup>-\\<^sup>1 * (t *\\<^sub>R sq_mtx_diag f) * P)\"\n    using assms by simp\n  also have \"... = P\\<^sup>-\\<^sup>1 * (\\<d>\\<i>\\<a>\\<g> i. exp (t * f i)) * P\"\n    by (metis assms(1) exp_similiar_sq_mtx_diag_eq exp_sq_mtx_diag scaleR_sq_mtx_diag)\n  finally show \"exp (t *\\<^sub>R A) = P\\<^sup>-\\<^sup>1 * (\\<d>\\<i>\\<a>\\<g> i. exp (t * f i)) * P\" .\nqed\n\nlemma exp_scaleR_diagonal2:\n  assumes \"mtx_invertible P\" and \"A = P * (\\<d>\\<i>\\<a>\\<g> i. f i) * P\\<^sup>-\\<^sup>1\"\n    shows \"exp (t *\\<^sub>R A) = P * (\\<d>\\<i>\\<a>\\<g> i. exp (t * f i)) * P\\<^sup>-\\<^sup>1\"\n  apply(subst sq_mtx_inv_idempotent[OF assms(1), symmetric])\n  apply(rule exp_scaleR_diagonal1)\n  by (simp_all add: assms)\n\n\nsubsection \\<open> Examples \\<close>\n\ndefinition \"mtx A = to_mtx (vector (map vector A))\"\n\nlemma vector_nth_eq: \"(vector A) $ i = foldr (\\<lambda>x f n. (f (n + 1))(n := x)) A (\\<lambda>n x. 0) 1 i\"\n  unfolding vector_def by simp\n\nlemma mtx_ith_eq[simp]: \"mtx A $$ i $ j = foldr (\\<lambda>x f n. (f (n + 1))(n := x))\n  (map (\\<lambda>l. vec_lambda (foldr (\\<lambda>x f n. (f (n + 1))(n := x)) l (\\<lambda>n x. 0) 1)) A) (\\<lambda>n x. 0) 1 i $ j\"\n  unfolding mtx_def vector_def by (simp add: vector_nth_eq)\n\nsubsubsection \\<open> 2x2 matrices \\<close>\n\nlemma mtx2_eq_iff: \"(mtx \n  ([a1, b1] # \n   [c1, d1] # []) :: 2 sq_mtx) = mtx \n  ([a2, b2] # \n   [c2, d2] # []) \\<longleftrightarrow> a1 = a2 \\<and> b1 = b2 \\<and> c1 = c2 \\<and> d1 = d2\"\n  apply(simp add: sq_mtx_eq_iff, safe)\n  using exhaust_2 by force+\n\nlemma mtx2_to_mtx: \"mtx \n  ([a, b] # \n   [c, d] # []) = \n  to_mtx (\\<chi> i j::2. if i=1 \\<and> j=1 then a \n  else (if i=1 \\<and> j=2 then b \n  else (if i=2 \\<and> j=1 then c \n  else d)))\"\n  apply(subst sq_mtx_eq_iff)\n  using exhaust_2 by force\n\nabbreviation diag2 :: \"real \\<Rightarrow> real \\<Rightarrow> 2 sq_mtx\" \n  where \"diag2 \\<iota>\\<^sub>1 \\<iota>\\<^sub>2 \\<equiv> mtx \n   ([\\<iota>\\<^sub>1, 0] # \n    [0, \\<iota>\\<^sub>2] # [])\"\n\nlemma diag2_eq: \"diag2 (\\<iota> 1) (\\<iota> 2) = (\\<d>\\<i>\\<a>\\<g> i. \\<iota> i)\"\n  apply(simp add: sq_mtx_eq_iff)\n  using exhaust_2 by (force simp: axis_def)\n\nlemma one_mtx2: \"(1::2 sq_mtx) = diag2 1 1\"\n  apply(subst sq_mtx_eq_iff)\n  using exhaust_2 by force\n\nlemma zero_mtx2: \"(0::2 sq_mtx) = diag2 0 0\"\n  by (simp add: sq_mtx_eq_iff)\n\nlemma scaleR_mtx2: \"k *\\<^sub>R mtx \n  ([a, b] # \n   [c, d] # []) = mtx \n  ([k*a, k*b] # \n   [k*c, k*d] # [])\"\n  by (simp add: sq_mtx_eq_iff)\n\nlemma uminus_mtx2: \"-mtx \n  ([a, b] # \n   [c, d] # []) = (mtx \n  ([-a, -b] # \n   [-c, -d] # [])::2 sq_mtx)\"\n  by (simp add: sq_mtx_uminus_eq sq_mtx_eq_iff)\n\nlemma plus_mtx2: \"mtx \n  ([a1, b1] # \n   [c1, d1] # []) + mtx \n  ([a2, b2] # \n   [c2, d2] # []) = ((mtx \n  ([a1+a2, b1+b2] # \n   [c1+c2, d1+d2] # []))::2 sq_mtx)\"\n  by (simp add: sq_mtx_eq_iff)\n\nlemma minus_mtx2: \"mtx \n  ([a1, b1] # \n   [c1, d1] # []) - mtx \n  ([a2, b2] # \n   [c2, d2] # []) = ((mtx \n  ([a1-a2, b1-b2] # \n   [c1-c2, d1-d2] # []))::2 sq_mtx)\"\n  by (simp add: sq_mtx_eq_iff)\n\nlemma times_mtx2: \"mtx \n  ([a1, b1] # \n   [c1, d1] # []) * mtx \n  ([a2, b2] # \n   [c2, d2] # []) = ((mtx \n  ([a1*a2+b1*c2, a1*b2+b1*d2] # \n   [c1*a2+d1*c2, c1*b2+d1*d2] # []))::2 sq_mtx)\"\n  unfolding sq_mtx_times_eq UNIV_2\n  by (simp add: sq_mtx_eq_iff)\n\nsubsubsection \\<open> 3x3 matrices \\<close>\n\nlemma mtx3_to_mtx: \"mtx \n  ([a\\<^sub>1\\<^sub>1, a\\<^sub>1\\<^sub>2, a\\<^sub>1\\<^sub>3] # \n   [a\\<^sub>2\\<^sub>1, a\\<^sub>2\\<^sub>2, a\\<^sub>2\\<^sub>3] # \n   [a\\<^sub>3\\<^sub>1, a\\<^sub>3\\<^sub>2, a\\<^sub>3\\<^sub>3] # []) = \n  to_mtx (\\<chi> i j::3. if i=1 \\<and> j=1 then a\\<^sub>1\\<^sub>1\n  else (if i=1 \\<and> j=2 then a\\<^sub>1\\<^sub>2 \n  else (if i=1 \\<and> j=3 then a\\<^sub>1\\<^sub>3 \n  else (if i=2 \\<and> j=1 then a\\<^sub>2\\<^sub>1\n  else (if i=2 \\<and> j=2 then a\\<^sub>2\\<^sub>2 \n  else (if i=2 \\<and> j=3 then a\\<^sub>2\\<^sub>3 \n  else (if i=3 \\<and> j=1 then a\\<^sub>3\\<^sub>1 \n  else (if i=3 \\<and> j=2 then a\\<^sub>3\\<^sub>2 \n  else a\\<^sub>3\\<^sub>3))))))))\"\n  apply(simp add: sq_mtx_eq_iff)\n  using exhaust_3 by force\n\nabbreviation diag3 :: \"real \\<Rightarrow> real \\<Rightarrow> real \\<Rightarrow> 3 sq_mtx\" \n  where \"diag3 \\<iota>\\<^sub>1 \\<iota>\\<^sub>2 \\<iota>\\<^sub>3 \\<equiv> mtx \n  ([\\<iota>\\<^sub>1, 0, 0] # \n   [0, \\<iota>\\<^sub>2, 0] # \n   [0, 0, \\<iota>\\<^sub>3] # [])\"\n\nlemma diag3_eq: \"diag3 (\\<iota> 1) (\\<iota> 2) (\\<iota> 3) = (\\<d>\\<i>\\<a>\\<g> i. \\<iota> i)\"\n  apply(simp add: sq_mtx_eq_iff)\n  using exhaust_3 by (force simp: axis_def)\n\nlemma one_mtx3: \"(1::3 sq_mtx) = diag3 1 1 1\"\n  apply(subst sq_mtx_eq_iff)\n  using exhaust_3 by force\n\nlemma zero_mtx3: \"(0::3 sq_mtx) = diag3 0 0 0\"\n  by (simp add: sq_mtx_eq_iff)\n\nlemma scaleR_mtx3: \"k *\\<^sub>R mtx \n  ([a\\<^sub>1\\<^sub>1, a\\<^sub>1\\<^sub>2, a\\<^sub>1\\<^sub>3] # \n   [a\\<^sub>2\\<^sub>1, a\\<^sub>2\\<^sub>2, a\\<^sub>2\\<^sub>3] # \n   [a\\<^sub>3\\<^sub>1, a\\<^sub>3\\<^sub>2, a\\<^sub>3\\<^sub>3] # []) = mtx \n  ([k*a\\<^sub>1\\<^sub>1, k*a\\<^sub>1\\<^sub>2, k*a\\<^sub>1\\<^sub>3] # \n   [k*a\\<^sub>2\\<^sub>1, k*a\\<^sub>2\\<^sub>2, k*a\\<^sub>2\\<^sub>3] # \n   [k*a\\<^sub>3\\<^sub>1, k*a\\<^sub>3\\<^sub>2, k*a\\<^sub>3\\<^sub>3] # [])\"\n  by (simp add: sq_mtx_eq_iff)\n\nlemma plus_mtx3: \"mtx \n  ([a\\<^sub>1\\<^sub>1, a\\<^sub>1\\<^sub>2, a\\<^sub>1\\<^sub>3] # \n   [a\\<^sub>2\\<^sub>1, a\\<^sub>2\\<^sub>2, a\\<^sub>2\\<^sub>3] # \n   [a\\<^sub>3\\<^sub>1, a\\<^sub>3\\<^sub>2, a\\<^sub>3\\<^sub>3] # []) + mtx \n  ([b\\<^sub>1\\<^sub>1, b\\<^sub>1\\<^sub>2, b\\<^sub>1\\<^sub>3] # \n   [b\\<^sub>2\\<^sub>1, b\\<^sub>2\\<^sub>2, b\\<^sub>2\\<^sub>3] # \n   [b\\<^sub>3\\<^sub>1, b\\<^sub>3\\<^sub>2, b\\<^sub>3\\<^sub>3] # []) = (mtx \n  ([a\\<^sub>1\\<^sub>1+b\\<^sub>1\\<^sub>1, a\\<^sub>1\\<^sub>2+b\\<^sub>1\\<^sub>2, a\\<^sub>1\\<^sub>3+b\\<^sub>1\\<^sub>3] # \n   [a\\<^sub>2\\<^sub>1+b\\<^sub>2\\<^sub>1, a\\<^sub>2\\<^sub>2+b\\<^sub>2\\<^sub>2, a\\<^sub>2\\<^sub>3+b\\<^sub>2\\<^sub>3] # \n   [a\\<^sub>3\\<^sub>1+b\\<^sub>3\\<^sub>1, a\\<^sub>3\\<^sub>2+b\\<^sub>3\\<^sub>2, a\\<^sub>3\\<^sub>3+b\\<^sub>3\\<^sub>3] # [])::3 sq_mtx)\"\n  by (subst sq_mtx_eq_iff) simp\n\nlemma minus_mtx3: \"mtx \n  ([a\\<^sub>1\\<^sub>1, a\\<^sub>1\\<^sub>2, a\\<^sub>1\\<^sub>3] # \n   [a\\<^sub>2\\<^sub>1, a\\<^sub>2\\<^sub>2, a\\<^sub>2\\<^sub>3] # \n   [a\\<^sub>3\\<^sub>1, a\\<^sub>3\\<^sub>2, a\\<^sub>3\\<^sub>3] # []) - mtx \n  ([b\\<^sub>1\\<^sub>1, b\\<^sub>1\\<^sub>2, b\\<^sub>1\\<^sub>3] # \n   [b\\<^sub>2\\<^sub>1, b\\<^sub>2\\<^sub>2, b\\<^sub>2\\<^sub>3] # \n   [b\\<^sub>3\\<^sub>1, b\\<^sub>3\\<^sub>2, b\\<^sub>3\\<^sub>3] # []) = (mtx \n  ([a\\<^sub>1\\<^sub>1-b\\<^sub>1\\<^sub>1, a\\<^sub>1\\<^sub>2-b\\<^sub>1\\<^sub>2, a\\<^sub>1\\<^sub>3-b\\<^sub>1\\<^sub>3] # \n   [a\\<^sub>2\\<^sub>1-b\\<^sub>2\\<^sub>1, a\\<^sub>2\\<^sub>2-b\\<^sub>2\\<^sub>2, a\\<^sub>2\\<^sub>3-b\\<^sub>2\\<^sub>3] # \n   [a\\<^sub>3\\<^sub>1-b\\<^sub>3\\<^sub>1, a\\<^sub>3\\<^sub>2-b\\<^sub>3\\<^sub>2, a\\<^sub>3\\<^sub>3-b\\<^sub>3\\<^sub>3] # [])::3 sq_mtx)\"\n  by (simp add: sq_mtx_eq_iff)\n\nlemma times_mtx3: \"mtx \n  ([a\\<^sub>1\\<^sub>1, a\\<^sub>1\\<^sub>2, a\\<^sub>1\\<^sub>3] # \n   [a\\<^sub>2\\<^sub>1, a\\<^sub>2\\<^sub>2, a\\<^sub>2\\<^sub>3] # \n   [a\\<^sub>3\\<^sub>1, a\\<^sub>3\\<^sub>2, a\\<^sub>3\\<^sub>3] # []) * mtx \n  ([b\\<^sub>1\\<^sub>1, b\\<^sub>1\\<^sub>2, b\\<^sub>1\\<^sub>3] # \n   [b\\<^sub>2\\<^sub>1, b\\<^sub>2\\<^sub>2, b\\<^sub>2\\<^sub>3] # \n   [b\\<^sub>3\\<^sub>1, b\\<^sub>3\\<^sub>2, b\\<^sub>3\\<^sub>3] # []) = (mtx \n  ([a\\<^sub>1\\<^sub>1*b\\<^sub>1\\<^sub>1+a\\<^sub>1\\<^sub>2*b\\<^sub>2\\<^sub>1+a\\<^sub>1\\<^sub>3*b\\<^sub>3\\<^sub>1, a\\<^sub>1\\<^sub>1*b\\<^sub>1\\<^sub>2+a\\<^sub>1\\<^sub>2*b\\<^sub>2\\<^sub>2+a\\<^sub>1\\<^sub>3*b\\<^sub>3\\<^sub>2, a\\<^sub>1\\<^sub>1*b\\<^sub>1\\<^sub>3+a\\<^sub>1\\<^sub>2*b\\<^sub>2\\<^sub>3+a\\<^sub>1\\<^sub>3*b\\<^sub>3\\<^sub>3] # \n   [a\\<^sub>2\\<^sub>1*b\\<^sub>1\\<^sub>1+a\\<^sub>2\\<^sub>2*b\\<^sub>2\\<^sub>1+a\\<^sub>2\\<^sub>3*b\\<^sub>3\\<^sub>1, a\\<^sub>2\\<^sub>1*b\\<^sub>1\\<^sub>2+a\\<^sub>2\\<^sub>2*b\\<^sub>2\\<^sub>2+a\\<^sub>2\\<^sub>3*b\\<^sub>3\\<^sub>2, a\\<^sub>2\\<^sub>1*b\\<^sub>1\\<^sub>3+a\\<^sub>2\\<^sub>2*b\\<^sub>2\\<^sub>3+a\\<^sub>2\\<^sub>3*b\\<^sub>3\\<^sub>3] # \n   [a\\<^sub>3\\<^sub>1*b\\<^sub>1\\<^sub>1+a\\<^sub>3\\<^sub>2*b\\<^sub>2\\<^sub>1+a\\<^sub>3\\<^sub>3*b\\<^sub>3\\<^sub>1, a\\<^sub>3\\<^sub>1*b\\<^sub>1\\<^sub>2+a\\<^sub>3\\<^sub>2*b\\<^sub>2\\<^sub>2+a\\<^sub>3\\<^sub>3*b\\<^sub>3\\<^sub>2, a\\<^sub>3\\<^sub>1*b\\<^sub>1\\<^sub>3+a\\<^sub>3\\<^sub>2*b\\<^sub>2\\<^sub>3+a\\<^sub>3\\<^sub>3*b\\<^sub>3\\<^sub>3] # [])::3 sq_mtx)\"\n  unfolding sq_mtx_times_eq\n  unfolding UNIV_3 by (simp add: sq_mtx_eq_iff)\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/Matrices_for_ODEs/SQ_MTX.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8807970904940926, "lm_q2_score": 0.8459424373085146, "lm_q1q2_score": 0.745103637506821}}
{"text": "theory Poly_Monotonicity\nimports \"~~/src/HOL/Library/Poly_Deriv\" \"Lib/Misc_Polynomial\"\nbegin\n\nsection {* Additional monotonicity notions *}\n\nsubsection{* Monotonicity on a set *}\n\ndefinition mono_on where\n  \"mono_on f A  \\<longleftrightarrow> (\\<forall>x y. x \\<in> A \\<longrightarrow> y \\<in> A \\<longrightarrow> x \\<le> y \\<longrightarrow> f x \\<le> f y)\"\n\nlemma mono_onI:\n  assumes \"\\<And>x y. x \\<in> A \\<Longrightarrow> y \\<in> A \\<Longrightarrow> x \\<le> y \\<Longrightarrow> f x \\<le> f y\"\n  shows \"mono_on f A\"\n  using assms unfolding mono_on_def by simp\n\nlemma mono_onD:\n  assumes \"mono_on f A\"\n  shows \"\\<And>x y. x \\<in> A \\<Longrightarrow> y \\<in> A \\<Longrightarrow> x \\<le> y \\<Longrightarrow> f x \\<le> f y\"\n  using assms unfolding mono_on_def by simp\n\nlemma mono_on_subset: \"mono_on f B \\<Longrightarrow> A \\<subseteq> B \\<Longrightarrow> mono_on f A\"\n  by (blast intro: mono_onI dest: mono_onD)\n\nlemma mono_on_UNIV[simp]: \"mono_on f UNIV = mono f\"\n  unfolding mono_on_def mono_def by simp\n\n\nsubsection{* Strict monotonicity on a set *}\n\ndefinition strict_mono_on where\n  \"strict_mono_on f A  \\<longleftrightarrow> (\\<forall>x y. x \\<in> A \\<longrightarrow> y \\<in> A \\<longrightarrow> x < y \\<longrightarrow> f x < f y)\"\n\nlemma strict_mono_onI:\n  assumes \"\\<And>x y. x \\<in> A \\<Longrightarrow> y \\<in> A \\<Longrightarrow> x < y \\<Longrightarrow> f x < f y\"\n  shows \"strict_mono_on f A\"\n  using assms unfolding strict_mono_on_def by simp\n\nlemma strict_mono_onD:\n  assumes \"strict_mono_on f A\"\n  shows \"\\<And>x y. x \\<in> A \\<Longrightarrow> y \\<in> A \\<Longrightarrow> x < y \\<Longrightarrow> f x < f y\"\n  using assms unfolding strict_mono_on_def by simp\n\nlemma strict_mono_on_subset: \"strict_mono_on f B \\<Longrightarrow> A \\<subseteq> B \\<Longrightarrow> strict_mono_on f A\"\n  by (blast intro: strict_mono_onI dest: strict_mono_onD)\n\nlemma strict_mono_on_UNIV[simp]: \"strict_mono_on f UNIV = strict_mono f\"\n  unfolding strict_mono_on_def strict_mono_def by simp\n\nsubsection{* Monotonically decreasing *}\n\ndefinition mono_dec where\n  \"mono_dec f \\<longleftrightarrow> (\\<forall>x y. x \\<le> y \\<longrightarrow> f x \\<ge> f y)\"\n\ndefinition strict_mono_dec where\n  \"strict_mono_dec f \\<longleftrightarrow> (\\<forall>x y. x < y \\<longrightarrow> f x > f y)\"\n\nlemma mono_dec_mono_conv:\n  fixes f :: \"_ \\<Rightarrow> ('a :: ordered_ab_group_add)\"\n  shows \"mono_dec f \\<longleftrightarrow> mono (\\<lambda>x. -f x)\"\n  unfolding mono_def mono_dec_def by simp\n\nlemma strict_mono_dec_strict_mono_conv:\n  fixes f :: \"_ \\<Rightarrow> ('a :: ordered_ab_group_add)\"\n  shows \"strict_mono_dec f \\<longleftrightarrow> strict_mono (\\<lambda>x. -f x)\"\n  unfolding strict_mono_def strict_mono_dec_def by simp\n\n\nsubsection{* Monotonically decreasing on a set *}\n\ndefinition mono_dec_on where\n  \"mono_dec_on f A  \\<longleftrightarrow> (\\<forall>x y. x \\<in> A \\<longrightarrow> y \\<in> A \\<longrightarrow> x \\<le> y \\<longrightarrow> f x \\<ge> f y)\"\n\nlemma mono_dec_onI:\n  assumes \"\\<And>x y. x \\<in> A \\<Longrightarrow> y \\<in> A \\<Longrightarrow> x \\<le> y \\<Longrightarrow> f x \\<ge> f y\"\n  shows \"mono_dec_on f A\"\n  using assms unfolding mono_dec_on_def by simp\n\nlemma mono_dec_onD:\n  assumes \"mono_dec_on f A\"\n  shows \"\\<And>x y. x \\<in> A \\<Longrightarrow> y \\<in> A \\<Longrightarrow> x \\<le> y \\<Longrightarrow> f x \\<ge> f y\"\n  using assms unfolding mono_dec_on_def by simp\n\nlemma mono_dec_on_subset: \"mono_dec_on f B \\<Longrightarrow> A \\<subseteq> B \\<Longrightarrow> mono_dec_on f A\"\n  by (blast intro: mono_dec_onI dest: mono_dec_onD)\n\nlemma mono_dec_on_mono_on_conv:\n  fixes f :: \"_ \\<Rightarrow> ('a :: ordered_ab_group_add)\"\n  shows \"mono_dec_on f A \\<longleftrightarrow> mono_on (\\<lambda>x. -f x) A\"\n  unfolding mono_on_def mono_dec_on_def by simp\n\nlemma mono_dec_on_UNIV[simp]:\n    \"mono_dec_on f UNIV = mono_dec f\"\n  unfolding mono_dec_on_def mono_dec_def by simp\n\nsubsection {* Strictly monotonically decreasing on a set *}\n\ndefinition strict_mono_dec_on where\n  \"strict_mono_dec_on f A  \\<longleftrightarrow> (\\<forall>x y. x \\<in> A \\<longrightarrow> y \\<in> A \\<longrightarrow> x < y \\<longrightarrow> f x > f y)\"\n\nlemma strict_mono_dec_onI:\n  assumes \"\\<And>x y. x \\<in> A \\<Longrightarrow> y \\<in> A \\<Longrightarrow> x < y \\<Longrightarrow> f x > f y\"\n  shows \"strict_mono_dec_on f A\"\n  using assms unfolding strict_mono_dec_on_def by simp\n\nlemma strict_mono_dec_onD:\n  assumes \"strict_mono_dec_on f A\"\n  shows \"\\<And>x y. x \\<in> A \\<Longrightarrow> y \\<in> A \\<Longrightarrow> x < y \\<Longrightarrow> f x > f y\"\n  using assms unfolding strict_mono_dec_on_def by simp\n\nlemma strict_mono_dec_on_subset: \"strict_mono_dec_on f B \\<Longrightarrow> A \\<subseteq> B \\<Longrightarrow> strict_mono_dec_on f A\"\n  by (blast intro: strict_mono_dec_onI dest: strict_mono_dec_onD)\n\nlemma strict_mono_dec_on_strict_mono_on_conv:\n  fixes f :: \"_ \\<Rightarrow> ('a :: ordered_ab_group_add)\"\n  shows \"strict_mono_dec_on f A \\<longleftrightarrow> strict_mono_on (\\<lambda>x. -f x) A\"\n  unfolding strict_mono_on_def strict_mono_dec_on_def by simp\n\nlemma strict_mono_dec_on_UNIV[simp]: \"strict_mono_dec_on f UNIV = strict_mono_dec f\"\n  unfolding strict_mono_dec_on_def strict_mono_dec_def by simp\n\nsection {* Monotonicity of polynomials *}\n\nlemma poly_deriv_ge_0:\n  fixes p :: \"real poly\"\n  defines \"p' \\<equiv> pderiv p\"\n  assumes \"a \\<le> b\" and \"\\<And>x. x \\<in> {a<..<b} \\<Longrightarrow> poly p' x \\<ge> 0\"\n  shows \"poly p a \\<le> poly p b\"\nproof (cases \"a < b\")\n  assume \"a < b\"\n  from poly_MVT[OF this] obtain \\<xi> \n    where \"\\<xi> \\<in> {a<..<b}\" and \"poly p b - poly p a = (b - a) * poly p' \\<xi>\" \n    by (auto simp: p'_def)\n  with assms have \"poly p b - poly p a \\<ge> 0\" by simp\n  thus ?thesis by simp\nqed (insert assms, simp)\n\nlemma poly_deriv_ge_0':\n  fixes p :: \"real poly\"\n  defines \"p' \\<equiv> pderiv p\"\n  assumes \"a < b\" and \"p' \\<noteq> 0\" and \"\\<And>x. x \\<in> {a<..<b} \\<Longrightarrow> poly p' x \\<ge> 0\"\n  shows \"poly p a < poly p b\"\nproof (rule ccontr)\n  assume \"\\<not>(poly p a < poly p b)\"\n  moreover from assms have \"poly p a \\<le> poly p b\" using poly_deriv_ge_0 by simp\n  ultimately have eq: \"poly p a = poly p b\" by simp\n  have interval_const: \"\\<And>x. x \\<in> {a..b} \\<Longrightarrow> poly p x = poly p a\"\n  proof-\n    fix x assume x: \"x \\<in> {a..b}\"\n    with assms(4) have \"poly p x \\<ge> poly p a\" \"poly p x \\<le> poly  p b\"\n      by (intro poly_deriv_ge_0, simp, simp add: p'_def)+\n    with eq show \"poly p x = poly p a\" by auto\n  qed\n\n  have deriv_0: \"\\<And>x. x \\<in> {a<..<b} \\<Longrightarrow> poly p' x = 0\"\n  proof (intro ballI DERIV_local_const)\n    fix x assume x: \"x \\<in> {a<..<b}\"\n    hence px: \"poly p x = poly p a\" by (intro interval_const) simp\n    show \"(poly p has_real_derivative poly p' x) (at x)\" unfolding p'_def by (rule poly_DERIV)\n    let ?m = \"(a + b) / 2\" and ?d = \"(b - a) / 2\"\n    from x and `a < b` show \"?d - abs (x - ?m) > 0\" by (simp add: field_simps abs_real_def)\n    show \"\\<forall>y. \\<bar>x - y\\<bar> < ?d - \\<bar>x - ?m\\<bar> \\<longrightarrow> poly p x = poly p y\"\n    proof (intro allI impI)\n      fix y assume \"\\<bar>x - y\\<bar> < ?d - \\<bar>x - ?m\\<bar>\"\n      hence \"y \\<in> {a<..<b}\" by (simp add: field_simps abs_real_def split: split_if_asm)\n      hence \"poly p y = poly p a\" by (intro interval_const) simp\n      with px show \"poly p x = poly p y\" by simp\n    qed\n  qed\n  from `a < b` have \"\\<not>finite {a<..<b}\" by (rule dense_linorder_class.infinite_Ioo)\n  moreover from deriv_0 have \"{a<..<b} \\<subseteq> {x. poly p' x = 0}\" by blast\n  ultimately have \"\\<not>finite {x. poly p' x = 0}\" using finite_subset by blast\n  hence \"p' = 0\" using poly_roots_finite by blast\n  with `p' \\<noteq> 0` show False by contradiction\nqed\n\nlemma pderiv_ge_0_imp_mono_on:\n  assumes \"connected A\" \"\\<forall>x\\<in>A. poly (pderiv p) x \\<ge> (0::real)\"\n  shows \"mono_on (poly p) A\"\nproof (rule mono_onI)\n  fix x y assume \"x \\<in> A\" \"y \\<in> A\" \"x \\<le> y\"\n  with `connected A` have \"{x<..<y} \\<subseteq> A\" by (intro connected_contains_Ioo)\n  with `x \\<le> y` and assms(2) show \"poly p x \\<le> poly p y\"\n    by (intro poly_deriv_ge_0) auto\nqed\n\nlemma pderiv_ge_0_imp_strict_mono_on:\n  assumes \"connected A\" \"pderiv p \\<noteq> 0\" \"\\<forall>x\\<in>A. poly (pderiv p) x \\<ge> (0::real)\"\n  shows \"strict_mono_on (poly p) A\"\nproof (rule strict_mono_onI)\n  fix x y assume \"x \\<in> A\" \"y \\<in> A\" \"x < y\"\n  with `connected A` have \"{x<..<y} \\<subseteq> A\" by (intro connected_contains_Ioo)\n  with `x < y` and assms(2,3) show \"poly p x < poly p y\"\n    by (intro poly_deriv_ge_0') auto\nqed\n\nlemma pderiv_ge_0_imp_mono:\n    \"(\\<forall>x. poly (pderiv p) x \\<ge> (0::real)) \\<Longrightarrow> mono (poly p) \"\n  by (intro monoI poly_deriv_ge_0) auto\n\nlemma pderiv_ge_0_imp_strict_mono:\n    \"pderiv p \\<noteq> 0 \\<Longrightarrow> (\\<forall>x. poly (pderiv p) x \\<ge> (0::real)) \\<Longrightarrow> strict_mono (poly p) \"\n  by (intro strict_monoI poly_deriv_ge_0') auto\n\nlemma pderiv_le_0_imp_mono_dec_on:\n    \"connected A \\<Longrightarrow> (\\<forall>x\\<in>A. poly (pderiv p) x \\<le> (0::real)) \\<Longrightarrow> mono_dec_on (poly p) A\"\n  apply (subst mono_dec_on_mono_on_conv, subst poly_minus[symmetric])\n  apply (intro pderiv_ge_0_imp_mono_on)\n  apply (simp_all add: pderiv_minus)\n  done\n\nlemma pderiv_ge_0_imp_strict_mono_dec_on:\n    \"connected A \\<Longrightarrow> pderiv p \\<noteq> 0 \\<Longrightarrow> (\\<forall>x\\<in>A. poly (pderiv p) x \\<le> (0::real)) \\<Longrightarrow> strict_mono_dec_on (poly p) A\"\n  apply (subst strict_mono_dec_on_strict_mono_on_conv, subst poly_minus[symmetric])\n  apply (intro pderiv_ge_0_imp_strict_mono_on)\n  apply (simp_all add: pderiv_minus)\n  done\n\nlemma pderiv_le_0_imp_mono_dec:\n    \"(\\<forall>x. poly (pderiv p) x \\<le> (0::real)) \\<Longrightarrow> mono_dec (poly p) \"\n  apply (subst mono_dec_mono_conv, subst poly_minus[symmetric])\n  apply (intro pderiv_ge_0_imp_mono)\n  apply (simp add: pderiv_minus)\n  done\n\nlemma pderiv_ge_0_imp_strict_mono_dec:\n    \"pderiv p \\<noteq> 0 \\<Longrightarrow> (\\<forall>x. poly (pderiv p) x \\<le> (0::real)) \\<Longrightarrow> strict_mono_dec (poly p) \"\n  apply (subst strict_mono_dec_strict_mono_conv, subst poly_minus[symmetric])\n  apply (intro pderiv_ge_0_imp_strict_mono)\n  apply (simp_all add: pderiv_minus)\n  done\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/Poly_Monotonicity.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8807970842359876, "lm_q2_score": 0.8459424314825852, "lm_q1q2_score": 0.7451036270813627}}
{"text": "theory Fun_Semantics\nimports Main\nbegin\n\ndatatype exp = T | F | Zero | Succ exp | IF exp exp exp | EQ exp exp\n\ninductive Eval :: \"exp \\<Rightarrow> exp \\<Rightarrow> bool\" (infix \"\\<Rrightarrow>\" 50) where\n    IF_T:    \"IF T x y \\<Rrightarrow> x\"\n  | IF_F:    \"IF F x y \\<Rrightarrow> y\"\n  | IF_Eval: \"p \\<Rrightarrow> q \\<Longrightarrow> IF p x y \\<Rrightarrow> IF q x y\"\n  | Succ_Eval: \"x \\<Rrightarrow> y \\<Longrightarrow> Succ x \\<Rrightarrow> Succ y\"\n  | EQ_same: \"EQ x x \\<Rrightarrow> T\"\n  | EQ_S0:   \"EQ (Succ x) Zero \\<Rrightarrow> F\"\n  | EQ_0S:   \"EQ Zero (Succ y) \\<Rrightarrow> F\"\n  | EQ_SS:   \"EQ (Succ x) (Succ y) \\<Rrightarrow> EQ x y\"\n  | EQ_Eval1: \"x \\<Rrightarrow> z \\<Longrightarrow> EQ x y \\<Rrightarrow> EQ z y\"\n  | EQ_Eval2: \"y \\<Rrightarrow> z \\<Longrightarrow> EQ x y \\<Rrightarrow> EQ x z\"\n\ninductive_simps T_simp [simp]: \"T \\<Rrightarrow> z\"\ninductive_simps F_simp [simp]: \"F \\<Rrightarrow> z\"\ninductive_simps Zero_simp [simp]: \"Zero \\<Rrightarrow> z\"\ninductive_simps Succ_simp [simp]: \"Succ x \\<Rrightarrow> z\"\ninductive_simps IF_simp [simp]: \"IF p x y \\<Rrightarrow>  z\"\ninductive_simps EQ_simp [simp]: \"EQ x y \\<Rrightarrow> z\"\n\ndatatype tp = bool | num\n\ninductive TP :: \"exp \\<Rightarrow> tp \\<Rightarrow> bool\" where\n  T:    \"TP T bool\"\n| F:    \"TP F bool\"\n| Zero: \"TP Zero num\"\n| IF:   \"\\<lbrakk>TP p bool; TP x t; TP y t\\<rbrakk> \\<Longrightarrow> TP (IF p x y) t\"\n| Succ: \"TP x num \\<Longrightarrow> TP (Succ x) num\"\n| EQ:   \"\\<lbrakk>TP x t; TP y t\\<rbrakk> \\<Longrightarrow> TP (EQ x y) bool\"\n\ninductive_simps TP_IF [simp]: \"TP (IF p x y) t\"\ninductive_simps TP_Succ [simp]: \"TP (Succ x) t\"\ninductive_simps TP_EQ [simp]: \"TP (EQ x y) t\"\n\nproposition type_preservation:\n  assumes \"x \\<Rrightarrow> y\" \"TP x t\" shows \"TP y t\"\n  using assms\n  by (induction x y arbitrary: t rule: Eval.induct) (auto simp: TP.intros)\n\nfun evl :: \"exp \\<Rightarrow> nat\"\n  where\n    \"evl T = 1\"\n  | \"evl F = 0\"\n  | \"evl Zero = 0\"\n  | \"evl (Succ x) = evl x + 1\"\n  | \"evl (IF x y z) = (if evl x = 1 then evl y else evl z)\"\n  | \"evl (EQ x y) = (if evl x = evl y then 1 else 0)\"\n\nlemma\n  assumes \"TP x t\" \"t = bool\" shows \"evl x < 2\"\n  using assms by (induction x t; force)\n\nproposition value_preservation:\n  assumes \"x \\<Rrightarrow> y\" shows \"evl x = evl y\"\n  using assms by (induction x y; force)\n\n\ntext \\<open>This doesn't hold\\<close>\nlemma\n  assumes \"x \\<Rrightarrow> y\" \"x \\<Rrightarrow> z\" shows \"\\<exists>u. y \\<Rrightarrow> u \\<and> z \\<Rrightarrow> u\"\n  nitpick\n  oops\n\ninductive EvalStar :: \"exp \\<Rightarrow> exp \\<Rightarrow> bool\" (infix \"\\<Rrightarrow>*\" 50) where\n    Id: \"x \\<Rrightarrow>* x\"\n  | Step: \"x \\<Rrightarrow> y \\<Longrightarrow> y \\<Rrightarrow>* z \\<Longrightarrow> x \\<Rrightarrow>* z\"\n\nproposition type_preservation_Star:\n  assumes \"x \\<Rrightarrow>* y\" \"TP x t\" shows \"TP y t\"\n  using assms by (induction x y) (auto simp: type_preservation)\n\nlemma Succ_EvalStar:\n  assumes \"x \\<Rrightarrow>* y\" shows \"Succ x \\<Rrightarrow>* Succ y\"\n  using assms by induction (auto intro: Succ_Eval EvalStar.intros)\n\nlemma IF_EvalStar:\n  assumes \"p \\<Rrightarrow>* q\" shows \"IF p x y \\<Rrightarrow>* IF q x y\"\n  using assms by induction (auto intro: IF_Eval EvalStar.intros)\n\nlemma EQ_EvalStar1:\n  assumes \"x \\<Rrightarrow>* z\" shows \"EQ x y \\<Rrightarrow>* EQ z y\"\n  using assms by induction (auto intro: EQ_Eval1 EvalStar.intros)\n\nlemma EQ_EvalStar2:\n  assumes \"y \\<Rrightarrow>* z\" shows \"EQ x y \\<Rrightarrow>* EQ x z \"\n  using assms by induction (auto intro: EQ_Eval2 EvalStar.intros)\n\nproposition diamond:\n  assumes \"x \\<Rrightarrow> y\" \"x \\<Rrightarrow> z\" shows \"\\<exists>u. y \\<Rrightarrow>* u \\<and> z \\<Rrightarrow>* u\"\n  using assms\nproof (induction x y arbitrary: z)\n  case (IF_Eval p q x y)\n  then show ?case\n    by (simp; meson F_simp IF_EvalStar T_simp)\nnext\n  case (EQ_SS x y)\n  then show ?case\n    by (simp; meson Eval.intros EvalStar.intros)\nnext\n  case (EQ_Eval1 x u y)\n  then show ?case\n    by (auto; meson EQ_EvalStar1 Eval.intros EvalStar.intros)+\nnext\n    case (EQ_Eval2 y u x)\n    then show ?case\n    by (auto; meson EQ_EvalStar2 Eval.intros EvalStar.intros)+\nqed (force intro: Succ_EvalStar Eval.intros EvalStar.intros)+\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/Fun_Semantics.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970779778824, "lm_q2_score": 0.8459424373085145, "lm_q1q2_score": 0.7451036269188276}}
{"text": "(*  Title:      HOL/Library/Product_Order.thy\n    Author:     Brian Huffman\n*)\n\nsection \\<open>Pointwise order on product types\\<close>\n\ntheory Product_Order\nimports Product_Plus\nbegin\n\nsubsection \\<open>Pointwise ordering\\<close>\n\ninstantiation prod :: (ord, ord) ord\nbegin\n\ndefinition\n  \"x \\<le> y \\<longleftrightarrow> fst x \\<le> fst y \\<and> snd x \\<le> snd y\"\n\ndefinition\n  \"(x::'a \\<times> 'b) < y \\<longleftrightarrow> x \\<le> y \\<and> \\<not> y \\<le> x\"\n\ninstance ..\n\nend\n\nlemma fst_mono: \"x \\<le> y \\<Longrightarrow> fst x \\<le> fst y\"\n  unfolding less_eq_prod_def by simp\n\nlemma snd_mono: \"x \\<le> y \\<Longrightarrow> snd x \\<le> snd y\"\n  unfolding less_eq_prod_def by simp\n\nlemma Pair_mono: \"x \\<le> x' \\<Longrightarrow> y \\<le> y' \\<Longrightarrow> (x, y) \\<le> (x', y')\"\n  unfolding less_eq_prod_def by simp\n\nlemma Pair_le [simp]: \"(a, b) \\<le> (c, d) \\<longleftrightarrow> a \\<le> c \\<and> b \\<le> d\"\n  unfolding less_eq_prod_def by simp\n\ninstance prod :: (preorder, preorder) preorder\nproof\n  fix x y z :: \"'a \\<times> 'b\"\n  show \"x < y \\<longleftrightarrow> x \\<le> y \\<and> \\<not> y \\<le> x\"\n    by (rule less_prod_def)\n  show \"x \\<le> x\"\n    unfolding less_eq_prod_def\n    by fast\n  assume \"x \\<le> y\" and \"y \\<le> z\" thus \"x \\<le> z\"\n    unfolding less_eq_prod_def\n    by (fast elim: order_trans)\nqed\n\ninstance prod :: (order, order) order\n  by standard auto\n\n\nsubsection \\<open>Binary infimum and supremum\\<close>\n\ninstantiation prod :: (inf, inf) inf\nbegin\n\ndefinition \"inf x y = (inf (fst x) (fst y), inf (snd x) (snd y))\"\n\nlemma inf_Pair_Pair [simp]: \"inf (a, b) (c, d) = (inf a c, inf b d)\"\n  unfolding inf_prod_def by simp\n\nlemma fst_inf [simp]: \"fst (inf x y) = inf (fst x) (fst y)\"\n  unfolding inf_prod_def by simp\n\nlemma snd_inf [simp]: \"snd (inf x y) = inf (snd x) (snd y)\"\n  unfolding inf_prod_def by simp\n\ninstance ..\n\nend\n\ninstance prod :: (semilattice_inf, semilattice_inf) semilattice_inf\n  by standard auto\n\n\ninstantiation prod :: (sup, sup) sup\nbegin\n\ndefinition\n  \"sup x y = (sup (fst x) (fst y), sup (snd x) (snd y))\"\n\nlemma sup_Pair_Pair [simp]: \"sup (a, b) (c, d) = (sup a c, sup b d)\"\n  unfolding sup_prod_def by simp\n\nlemma fst_sup [simp]: \"fst (sup x y) = sup (fst x) (fst y)\"\n  unfolding sup_prod_def by simp\n\nlemma snd_sup [simp]: \"snd (sup x y) = sup (snd x) (snd y)\"\n  unfolding sup_prod_def by simp\n\ninstance ..\n\nend\n\ninstance prod :: (semilattice_sup, semilattice_sup) semilattice_sup\n  by standard auto\n\ninstance prod :: (lattice, lattice) lattice ..\n\ninstance prod :: (distrib_lattice, distrib_lattice) distrib_lattice\n  by standard (auto simp add: sup_inf_distrib1)\n\n\nsubsection \\<open>Top and bottom elements\\<close>\n\ninstantiation prod :: (top, top) top\nbegin\n\ndefinition\n  \"top = (top, top)\"\n\ninstance ..\n\nend\n\nlemma fst_top [simp]: \"fst top = top\"\n  unfolding top_prod_def by simp\n\nlemma snd_top [simp]: \"snd top = top\"\n  unfolding top_prod_def by simp\n\nlemma Pair_top_top: \"(top, top) = top\"\n  unfolding top_prod_def by simp\n\ninstance prod :: (order_top, order_top) order_top\n  by standard (auto simp add: top_prod_def)\n\ninstantiation prod :: (bot, bot) bot\nbegin\n\ndefinition\n  \"bot = (bot, bot)\"\n\ninstance ..\n\nend\n\nlemma fst_bot [simp]: \"fst bot = bot\"\n  unfolding bot_prod_def by simp\n\nlemma snd_bot [simp]: \"snd bot = bot\"\n  unfolding bot_prod_def by simp\n\nlemma Pair_bot_bot: \"(bot, bot) = bot\"\n  unfolding bot_prod_def by simp\n\ninstance prod :: (order_bot, order_bot) order_bot\n  by standard (auto simp add: bot_prod_def)\n\ninstance prod :: (bounded_lattice, bounded_lattice) bounded_lattice ..\n\ninstance prod :: (boolean_algebra, boolean_algebra) boolean_algebra\n  by standard (auto simp add: prod_eqI diff_eq)\n\n\nsubsection \\<open>Complete lattice operations\\<close>\n\ninstantiation prod :: (Inf, Inf) Inf\nbegin\n\ndefinition \"Inf A = (INF x\\<in>A. fst x, INF x\\<in>A. snd x)\"\n\ninstance ..\n\nend\n\ninstantiation prod :: (Sup, Sup) Sup\nbegin\n\ndefinition \"Sup A = (SUP x\\<in>A. fst x, SUP x\\<in>A. snd x)\"\n\ninstance ..\n\nend\n\ninstance prod :: (conditionally_complete_lattice, conditionally_complete_lattice)\n    conditionally_complete_lattice\n  by standard (force simp: less_eq_prod_def Inf_prod_def Sup_prod_def bdd_below_def bdd_above_def\n    intro!: cInf_lower cSup_upper cInf_greatest cSup_least)+\n\ninstance prod :: (complete_lattice, complete_lattice) complete_lattice\n  by standard (simp_all add: less_eq_prod_def Inf_prod_def Sup_prod_def\n    INF_lower SUP_upper le_INF_iff SUP_le_iff bot_prod_def top_prod_def)\n\nlemma fst_Inf: \"fst (Inf A) = (INF x\\<in>A. fst x)\"\n  by (simp add: Inf_prod_def)\n\nlemma fst_INF: \"fst (INF x\\<in>A. f x) = (INF x\\<in>A. fst (f x))\"\n  by (simp add: fst_Inf image_image)\n\nlemma fst_Sup: \"fst (Sup A) = (SUP x\\<in>A. fst x)\"\n  by (simp add: Sup_prod_def)\n\nlemma fst_SUP: \"fst (SUP x\\<in>A. f x) = (SUP x\\<in>A. fst (f x))\"\n  by (simp add: fst_Sup image_image)\n\nlemma snd_Inf: \"snd (Inf A) = (INF x\\<in>A. snd x)\"\n  by (simp add: Inf_prod_def)\n\nlemma snd_INF: \"snd (INF x\\<in>A. f x) = (INF x\\<in>A. snd (f x))\"\n  by (simp add: snd_Inf image_image)\n\nlemma snd_Sup: \"snd (Sup A) = (SUP x\\<in>A. snd x)\"\n  by (simp add: Sup_prod_def)\n\nlemma snd_SUP: \"snd (SUP x\\<in>A. f x) = (SUP x\\<in>A. snd (f x))\"\n  by (simp add: snd_Sup image_image)\n\nlemma INF_Pair: \"(INF x\\<in>A. (f x, g x)) = (INF x\\<in>A. f x, INF x\\<in>A. g x)\"\n  by (simp add: Inf_prod_def image_image)\n\nlemma SUP_Pair: \"(SUP x\\<in>A. (f x, g x)) = (SUP x\\<in>A. f x, SUP x\\<in>A. g x)\"\n  by (simp add: Sup_prod_def image_image)\n\n\ntext \\<open>Alternative formulations for set infima and suprema over the product\nof two complete lattices:\\<close>\n\nlemma INF_prod_alt_def: \\<^marker>\\<open>contributor \\<open>Alessandro Coglio\\<close>\\<close>\n  \"Inf (f ` A) = (Inf ((fst \\<circ> f) ` A), Inf ((snd \\<circ> f) ` A))\"\n  by (simp add: Inf_prod_def image_image)\n\nlemma SUP_prod_alt_def: \\<^marker>\\<open>contributor \\<open>Alessandro Coglio\\<close>\\<close>\n  \"Sup (f ` A) = (Sup ((fst \\<circ> f) ` A), Sup((snd \\<circ> f) ` A))\"\n  by (simp add: Sup_prod_def image_image)\n\n\nsubsection \\<open>Complete distributive lattices\\<close>\n\ninstance prod :: (complete_distrib_lattice, complete_distrib_lattice) complete_distrib_lattice \\<^marker>\\<open>contributor \\<open>Alessandro Coglio\\<close>\\<close>\nproof\n  fix A::\"('a\\<times>'b) set set\"\n  show \"Inf (Sup ` A) \\<le> Sup (Inf ` {f ` A |f. \\<forall>Y\\<in>A. f Y \\<in> Y})\"\n    by (simp add: Inf_prod_def Sup_prod_def INF_SUP_set image_image)\nqed\n\nsubsection \\<open>Bekic's Theorem\\<close>\ntext \\<open>\n  Simultaneous fixed points over pairs can be written in terms of separate fixed points.\n  Transliterated from HOLCF.Fix by Peter Gammie\n\\<close>\n\nlemma lfp_prod:\n  fixes F :: \"'a::complete_lattice \\<times> 'b::complete_lattice \\<Rightarrow> 'a \\<times> 'b\"\n  assumes \"mono F\"\n  shows \"lfp F = (lfp (\\<lambda>x. fst (F (x, lfp (\\<lambda>y. snd (F (x, y)))))),\n                 (lfp (\\<lambda>y. snd (F (lfp (\\<lambda>x. fst (F (x, lfp (\\<lambda>y. snd (F (x, y)))))), y)))))\"\n  (is \"lfp F = (?x, ?y)\")\nproof(rule lfp_eqI[OF assms])\n  have 1: \"fst (F (?x, ?y)) = ?x\"\n    by (rule trans [symmetric, OF lfp_unfold])\n       (blast intro!: monoI monoD[OF assms(1)] fst_mono snd_mono Pair_mono lfp_mono)+\n  have 2: \"snd (F (?x, ?y)) = ?y\"\n    by (rule trans [symmetric, OF lfp_unfold])\n       (blast intro!: monoI monoD[OF assms(1)] fst_mono snd_mono Pair_mono lfp_mono)+\n  from 1 2 show \"F (?x, ?y) = (?x, ?y)\" by (simp add: prod_eq_iff)\nnext\n  fix z assume F_z: \"F z = z\"\n  obtain x y where z: \"z = (x, y)\" by (rule prod.exhaust)\n  from F_z z have F_x: \"fst (F (x, y)) = x\" by simp\n  from F_z z have F_y: \"snd (F (x, y)) = y\" by simp\n  let ?y1 = \"lfp (\\<lambda>y. snd (F (x, y)))\"\n  have \"?y1 \\<le> y\" by (rule lfp_lowerbound, simp add: F_y)\n  hence \"fst (F (x, ?y1)) \\<le> fst (F (x, y))\"\n    by (simp add: assms fst_mono monoD)\n  hence \"fst (F (x, ?y1)) \\<le> x\" using F_x by simp\n  hence 1: \"?x \\<le> x\" by (simp add: lfp_lowerbound)\n  hence \"snd (F (?x, y)) \\<le> snd (F (x, y))\"\n    by (simp add: assms snd_mono monoD)\n  hence \"snd (F (?x, y)) \\<le> y\" using F_y by simp\n  hence 2: \"?y \\<le> y\" by (simp add: lfp_lowerbound)\n  show \"(?x, ?y) \\<le> z\" using z 1 2 by simp\nqed\n\nlemma gfp_prod:\n  fixes F :: \"'a::complete_lattice \\<times> 'b::complete_lattice \\<Rightarrow> 'a \\<times> 'b\"\n  assumes \"mono F\"\n  shows \"gfp F = (gfp (\\<lambda>x. fst (F (x, gfp (\\<lambda>y. snd (F (x, y)))))),\n                 (gfp (\\<lambda>y. snd (F (gfp (\\<lambda>x. fst (F (x, gfp (\\<lambda>y. snd (F (x, y)))))), y)))))\"\n  (is \"gfp F = (?x, ?y)\")\nproof(rule gfp_eqI[OF assms])\n  have 1: \"fst (F (?x, ?y)) = ?x\"\n    by (rule trans [symmetric, OF gfp_unfold])\n       (blast intro!: monoI monoD[OF assms(1)] fst_mono snd_mono Pair_mono gfp_mono)+\n  have 2: \"snd (F (?x, ?y)) = ?y\"\n    by (rule trans [symmetric, OF gfp_unfold])\n       (blast intro!: monoI monoD[OF assms(1)] fst_mono snd_mono Pair_mono gfp_mono)+\n  from 1 2 show \"F (?x, ?y) = (?x, ?y)\" by (simp add: prod_eq_iff)\nnext\n  fix z assume F_z: \"F z = z\"\n  obtain x y where z: \"z = (x, y)\" by (rule prod.exhaust)\n  from F_z z have F_x: \"fst (F (x, y)) = x\" by simp\n  from F_z z have F_y: \"snd (F (x, y)) = y\" by simp\n  let ?y1 = \"gfp (\\<lambda>y. snd (F (x, y)))\"\n  have \"y \\<le> ?y1\" by (rule gfp_upperbound, simp add: F_y)\n  hence \"fst (F (x, y)) \\<le> fst (F (x, ?y1))\"\n    by (simp add: assms fst_mono monoD)\n  hence \"x \\<le> fst (F (x, ?y1))\" using F_x by simp\n  hence 1: \"x \\<le> ?x\" by (simp add: gfp_upperbound)\n  hence \"snd (F (x, y)) \\<le> snd (F (?x, y))\"\n    by (simp add: assms snd_mono monoD)\n  hence \"y \\<le> snd (F (?x, y))\" using F_y by simp\n  hence 2: \"y \\<le> ?y\" by (simp add: gfp_upperbound)\n  show \"z \\<le> (?x, ?y)\" using z 1 2 by simp\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/Library/Product_Order.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970779778824, "lm_q2_score": 0.8459424334245618, "lm_q1q2_score": 0.7451036234978533}}
{"text": "(*  Author: Tobias Nipkow, Alex Krauss, Dmitriy Traytel  *)\n\nheader \"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{* Concatenation of Languages *}\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 I M = UNION I (%i. A @@ M i)\"\nand   \"UNION I M @@ A = UNION I (%i. M i @@ A)\"\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{* Iteration of Languages *}\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(induction n)(auto simp: conc_subset_lists[OF assms])\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 `w : A` 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 `u : star A` obtain m where \"u : A ^^ m\" by (auto simp: star_def)\n  moreover\n  from `v : star A` 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: `P []` step star_if_lang_pow) }\n  with `w : star A` 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 {* Left-Quotients of Languages *}\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 {* Right-Quotients of Languages *}\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 {* Two-Sided-Quotients of Languages *}\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 {* Arden's Lemma *}\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: le_Suc_eq)\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 `[] \\<notin> A` 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 `w : X` 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: le_Suc_eq)\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 `[] \\<notin> A` 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 `w : X` 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 {* Lists of Fixed Length *}\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": "Josh-Tilles", "repo": "AFP", "sha": "f4bf1d502bde2a3469d482b62c531f1c3af3e881", "save_path": "github-repos/isabelle/Josh-Tilles-AFP", "path": "github-repos/isabelle/Josh-Tilles-AFP/AFP-f4bf1d502bde2a3469d482b62c531f1c3af3e881/thys/MSO_Regex_Equivalence/Pi_Regular_Set.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8918110511888302, "lm_q2_score": 0.8354835432479661, "lm_q1q2_score": 0.7450934569549371}}
{"text": "theory MyList\nimports Main\nbegin\n\ndatatype '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\nfun mycount :: \"'a list \\<Rightarrow> nat\" where\n   \"mycount Nil = 0\"\n | \"mycount (Cons x xs) = Suc (mycount xs)\"\n\nfun myremove :: \"'a \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where\n   \"myremove x Nil = Nil\"\n | \"myremove x (Cons y xs) =\n    (if x=y\n      then (myremove x xs)\n      else (Cons y (myremove x xs)))\"\n\nfun mydedup :: \"'a list \\<Rightarrow> 'a list\" where\n   \"mydedup Nil = Nil\"\n | \"mydedup (Cons x xs) = Cons x (myremove x (mydedup xs))\"\n\nfun myiindex :: \"'a \\<Rightarrow> 'a list \\<Rightarrow> nat\" where\n   \"myiindex x Nil = 1\"\n | \"myiindex x (Cons y xs) =\n    (if x=y\n      then 0\n      else (1 + (myiindex x xs)))\"\n\nfun myhas :: \"'a \\<Rightarrow> 'a list \\<Rightarrow> bool\" where\n   \"myhas x Nil = False\"\n | \"myhas x (Cons y xs) =\n    (if x=y\n      then True\n      else (myhas x xs))\"\n\nfun mycindex :: \"'a \\<Rightarrow> 'a list \\<Rightarrow> int\" where\n   \"mycindex x xs =\n    (if (myhas x xs)\n      then int (myiindex x xs)\n      else -1::int)\"\n\nfun myindex :: \"'a \\<Rightarrow> 'a list \\<Rightarrow> int option\" where\n  \"myindex x xs =\n    (if (myhas x xs)\n      then Some (int (myiindex x xs))\n      else None)\"\n\nvalue \"rev (Cons True (Cons False Nil))\"\n\n(* a comment *)\n\nlemma app_Nil2 [simp]: \"app xs Nil = xs\"\n  apply (induction xs)\n  apply (auto)\ndone\n\nlemma app_assoc [simp]: \"app (app xs ys) zs = app xs (app ys zs)\"\n  apply (induction xs)\n  apply (auto)\ndone\n\nlemma rev_app [simp]: \"rev (app xs ys) = app (rev ys) (rev xs)\"\n  apply (induction xs)\n  apply (auto)\ndone\n\ntheorem rev_rev [simp]: \"rev (rev xs) = xs\"\n  apply (induction xs)\n  apply (auto)\ndone\n\ntheorem app_count [simp]: \"mycount (app xs ys) = (mycount xs) + (mycount ys)\"\n  apply (induction xs)\n  apply (auto)\ndone\n\ntheorem rev_count [simp]: \"mycount (rev xs) = mycount xs\"\n  apply (induction xs)\n  apply (auto)\ndone\n\ntheorem remove_idempotence [simp]: \"myremove x (myremove x xs) = myremove x xs\"\n  apply (induction xs)\n  apply (auto)\ndone\n\nlemma remove_count_limit [simp]: \"mycount (myremove x xs) \\<le> mycount xs\"\n  apply (induction xs)\n  apply (auto)\ndone\n\nlemma remove_count_required [simp]: \"mycount (myremove x (Cons x xs)) < mycount (Cons x xs)\"\n  apply (induction xs)\n  apply (auto)\ndone\n\nlemma remove_distributivity [simp]: \"myremove x (myremove y xs) = myremove y (myremove x xs)\"\n  apply (induction xs)\n  apply (auto)\ndone\n\nlemma dedup_remove_distributivity [simp]: \"mydedup (myremove x xs) = myremove x (mydedup xs)\"\n  apply (induction xs)\n  apply (auto)\ndone\n\ntheorem dedup_idempotence [simp]: \"mydedup (mydedup xs) = mydedup xs\"\n  apply (induction xs)\n  apply (auto)\ndone\n\ntheorem dedup_count_limit [simp]: \"mycount (mydedup xs) \\<le> mycount xs\"\n  apply (induction xs)\n  apply (auto)\nby (meson dual_order.trans remove_count_limit)\n\ntheorem dedup_count_nonzero [simp]: \"(mycount xs > 0) = (mycount (mydedup xs) > 0)\"\n  apply (induction xs)\n  apply (auto)\ndone\n\ntheorem iindex_post_remove [simp]: \"myiindex x (myremove x xs) = (mycount (myremove x xs)) + 1\"\n  apply (induction xs)\n  apply (auto)\ndone\n\ntheorem remove_other [simp]: \"x \\<noteq> y \\<longrightarrow> myremove x (Cons y xs) = Cons y (myremove x xs)\"\n  apply (induction xs)\n  apply (auto)\ndone\n\nlemma iindex_remove_limit [simp]: \"x \\<noteq> y \\<longrightarrow> myiindex x (myremove y xs) \\<le> myiindex x xs\"\n  apply (induction xs)\n  apply (auto)\ndone\n\nlemma iindex_dedup_limit [simp]: \"myiindex x (mydedup xs) \\<le> myiindex x xs\"\n  apply (induction xs)\n  apply (auto)\nby (meson dual_order.trans iindex_remove_limit)\n\nlemma remove_other_still_has [simp]: \"x \\<noteq> y \\<longrightarrow> myhas x (myremove y xs) = myhas x xs\"\n  apply (induction xs)\n  apply (auto)\ndone\n\n\ntheorem dedup_no_remove [simp]: \"(myhas x (mydedup xs)) = (myhas x xs)\"\n  apply (induction xs)\n  apply (auto)\ndone\n\ntheorem cindex_dedup_limit [simp]: \"mycindex x (mydedup xs) \\<le> mycindex x xs\"\n  apply (induction xs)\n  apply (auto)\nby (meson dual_order.trans iindex_dedup_limit iindex_remove_limit)\n\n\ntheorem index_dedup_limit [simp]: \"the (myindex x (mydedup xs)) \\<le> the (myindex x xs)\"\n  apply (induction xs)\n  apply (auto)\nby (meson dual_order.trans iindex_dedup_limit iindex_remove_limit)\n\nend\n", "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/MyList.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110454379297, "lm_q2_score": 0.8354835391516133, "lm_q1q2_score": 0.7450934484969817}}
{"text": "\\<^marker>\\<open>creator \"Kevin Kappelmann\"\\<close>\nparagraph \\<open>Symmetric\\<close>\ntheory Binary_Relations_Symmetric\n  imports\n    Functions_Monotone\nbegin\n\nconsts symmetric_on :: \"'a \\<Rightarrow> ('b \\<Rightarrow> 'b \\<Rightarrow> bool) \\<Rightarrow> bool\"\n\noverloading\n  symmetric_on_pred \\<equiv> \"symmetric_on :: ('a \\<Rightarrow> bool) \\<Rightarrow> ('a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> bool\"\nbegin\n  definition \"symmetric_on_pred P R \\<equiv> \\<forall>x y. P x \\<and> P y \\<and> R x y \\<longrightarrow> R y x\"\nend\n\nlemma symmetric_onI [intro]:\n  assumes \"\\<And>x y. P x \\<Longrightarrow> P y \\<Longrightarrow> R x y \\<Longrightarrow> R y x\"\n  shows \"symmetric_on P R\"\n  unfolding symmetric_on_pred_def using assms by blast\n\nlemma symmetric_onD:\n  assumes \"symmetric_on P R\"\n  and \"P x\" \"P y\"\n  and \"R x y\"\n  shows \"R y x\"\n  using assms unfolding symmetric_on_pred_def by blast\n\nlemma symmetric_on_rel_inv_iff_symmetric_on [iff]:\n  \"symmetric_on P R\\<inverse> \\<longleftrightarrow> symmetric_on (P :: 'a \\<Rightarrow> bool) (R :: 'a \\<Rightarrow> _)\"\n  by (blast dest: symmetric_onD)\n\nlemma antimono_symmetric_on [iff]:\n  \"antimono (\\<lambda>(P :: 'a \\<Rightarrow> bool). symmetric_on P (R :: 'a \\<Rightarrow> _))\"\n  by (intro antimonoI) (auto dest: symmetric_onD)\n\nlemma symmetric_on_if_le_pred_if_symmetric_on:\n  fixes P P' :: \"'a \\<Rightarrow> bool\" and R :: \"'a \\<Rightarrow> _\"\n  assumes \"symmetric_on P R\"\n  and \"P' \\<le> P\"\n  shows \"symmetric_on P' R\"\n  using assms by (blast dest: symmetric_onD)\n\ndefinition \"symmetric (R :: 'a \\<Rightarrow> _) \\<equiv> symmetric_on (\\<top> :: 'a \\<Rightarrow> bool) R\"\n\nlemma symmetric_eq_symmetric_on:\n  \"symmetric (R :: 'a \\<Rightarrow> _) = symmetric_on (\\<top> :: 'a \\<Rightarrow> bool) R\"\n  unfolding symmetric_def ..\n\nlemma symmetricI [intro]:\n  assumes \"\\<And>x y. R x y \\<Longrightarrow> R y x\"\n  shows \"symmetric R\"\n  unfolding symmetric_eq_symmetric_on using assms by (intro symmetric_onI)\n\nlemma symmetricD:\n  assumes \"symmetric R\"\n  and \"R x y\"\n  shows \"R y x\"\n  using assms unfolding symmetric_eq_symmetric_on by (auto dest: symmetric_onD)\n\nlemma symmetric_on_if_symmetric:\n  fixes P :: \"'a \\<Rightarrow> bool\" and R :: \"'a \\<Rightarrow> _\"\n  assumes \"symmetric R\"\n  shows \"symmetric_on P R\"\n  using assms by (intro symmetric_onI) (blast dest: symmetricD)\n\nlemma symmetric_rel_inv_iff_symmetric [iff]: \"symmetric R\\<inverse> \\<longleftrightarrow> symmetric R\"\n  by (blast dest: symmetricD)\n\nlemma rel_inv_eq_self_if_symmetric [simp]:\n  assumes \"symmetric R\"\n  shows \"R\\<inverse> = R\"\n  using assms by (blast dest: symmetricD)\n\nlemma rel_iff_rel_if_symmetric:\n  assumes \"symmetric R\"\n  shows \"R x y \\<longleftrightarrow> R y x\"\n  using assms by (blast dest: symmetricD)\n\nlemma symmetric_if_rel_inv_eq_self:\n  assumes \"R\\<inverse> = R\"\n  shows \"symmetric R\"\n  by (intro symmetricI, subst assms[symmetric]) simp\n\nlemma symmetric_iff_rel_inv_eq_self: \"symmetric R \\<longleftrightarrow> R\\<inverse> = R\"\n  using rel_inv_eq_self_if_symmetric symmetric_if_rel_inv_eq_self by blast\n\nlemma symmetric_if_symmetric_on_in_field:\n  assumes \"symmetric_on (in_field R) R\"\n  shows \"symmetric R\"\n  using assms by (intro symmetricI) (blast dest: symmetric_onD)\n\ncorollary symmetric_on_in_field_iff_symmetric [simp]:\n  \"symmetric_on (in_field R) R \\<longleftrightarrow> symmetric R\"\n  using symmetric_if_symmetric_on_in_field symmetric_on_if_symmetric\n  by blast\n\n\nparagraph \\<open>Instantiations\\<close>\n\nlemma symmetric_eq [iff]: \"symmetric (=)\"\n  by (rule symmetricI) (rule sym)\n\nlemma symmetric_top: \"symmetric \\<top>\"\n  by (rule symmetricI) auto\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_Symmetric.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045966995027, "lm_q2_score": 0.8397339656668287, "lm_q1q2_score": 0.7450158343443127}}
{"text": "(* Title:      Iterings\n   Author:     Walter Guttmann\n   Maintainer: Walter Guttmann <walter.guttmann at canterbury.ac.nz>\n*)\n\nsection \\<open>Iterings\\<close>\n\ntext \\<open>\nThis theory introduces algebraic structures with an operation that describes iteration in various relational computation models.\nAn iteration describes the repeated sequential execution of a computation.\nThis is typically modelled by fixpoints, but different computation models use different fixpoints in the refinement order.\nWe therefore look at equational and simulation axioms rather than induction axioms.\nOur development is based on \\cite{Guttmann2012c} and the proposed algebras generalise Kleene algebras.\n\nWe first consider a variant of Conway semirings \\cite{BloomEsik1993a} based on idempotent left semirings.\nConway semirings expand semirings by an iteration operation satisfying Conway's sumstar and productstar axioms \\cite{Conway1971}.\nMany properties of iteration follow already from these equational axioms.\n\nNext we introduce iterings, which use generalised versions of simulation axioms in addition to sumstar and productstar.\nUnlike the induction axioms of the Kleene star, which hold only in partial-correctness models, the simulation axioms are also valid in total and general correctness models.\nThey are still powerful enough to prove the correctness of complex results such as separation theorems of \\cite{Cohen2000} and Back's atomicity refinement theorem \\cite{BackWright1999,Wright2004}.\n\\<close>\n\ntheory Iterings\n\nimports Stone_Relation_Algebras.Semirings\n\nbegin\n\nsubsection \\<open>Conway Semirings\\<close>\n\ntext \\<open>\nIn this section, we consider equational axioms for iteration.\nThe algebraic structures are based on idempotent left semirings, which are expanded by a unary iteration operation.\nWe start with an unfold property, one inequality of the sliding rule and distributivity over joins, which is similar to Conway's sumstar.\n\\<close>\n\nclass circ =\n  fixes circ :: \"'a \\<Rightarrow> 'a\" (\"_\\<^sup>\\<circ>\" [100] 100)\n\nclass left_conway_semiring = idempotent_left_semiring + circ +\n  assumes circ_left_unfold: \"1 \\<squnion> x * x\\<^sup>\\<circ> = x\\<^sup>\\<circ>\"\n  assumes circ_left_slide: \"(x * y)\\<^sup>\\<circ> * x \\<le> x * (y * x)\\<^sup>\\<circ>\"\n  assumes circ_sup_1: \"(x \\<squnion> y)\\<^sup>\\<circ> = x\\<^sup>\\<circ> * (y * x\\<^sup>\\<circ>)\\<^sup>\\<circ>\"\nbegin\n\ntext \\<open>\nWe obtain one inequality of Conway's productstar, as well as of the other unfold rule.\n\\<close>\n\nlemma circ_mult_sub:\n  \"1 \\<squnion> x * (y * x)\\<^sup>\\<circ> * y \\<le> (x * y)\\<^sup>\\<circ>\"\n  by (metis sup_right_isotone circ_left_slide circ_left_unfold mult_assoc mult_right_isotone)\n\nlemma circ_right_unfold_sub:\n  \"1 \\<squnion> x\\<^sup>\\<circ> * x \\<le> x\\<^sup>\\<circ>\"\n  by (metis circ_mult_sub mult_1_left mult_1_right)\n\nlemma circ_zero:\n  \"bot\\<^sup>\\<circ> = 1\"\n  by (metis sup_monoid.add_0_right circ_left_unfold mult_left_zero)\n\nlemma circ_increasing:\n  \"x \\<le> x\\<^sup>\\<circ>\"\n  by (metis le_supI2 circ_left_unfold circ_right_unfold_sub mult_1_left mult_right_sub_dist_sup_left order_trans)\n\nlemma circ_reflexive:\n  \"1 \\<le> x\\<^sup>\\<circ>\"\n  by (metis sup_left_divisibility circ_left_unfold)\n\nlemma circ_mult_increasing:\n  \"x \\<le> x * x\\<^sup>\\<circ>\"\n  by (metis circ_reflexive mult_right_isotone mult_1_right)\n\nlemma circ_mult_increasing_2:\n  \"x \\<le> x\\<^sup>\\<circ> * x\"\n  by (metis circ_reflexive mult_left_isotone mult_1_left)\n\nlemma circ_transitive_equal:\n  \"x\\<^sup>\\<circ> * x\\<^sup>\\<circ> = x\\<^sup>\\<circ>\"\n  by (metis sup_idem circ_sup_1 circ_left_unfold mult_assoc)\n\ntext \\<open>\nWhile iteration is not idempotent, a fixpoint is reached after applying this operation twice.\nIteration is idempotent for the unit.\n\\<close>\n\nlemma circ_circ_circ:\n  \"x\\<^sup>\\<circ>\\<^sup>\\<circ>\\<^sup>\\<circ> = x\\<^sup>\\<circ>\\<^sup>\\<circ>\"\n  by (metis sup_idem circ_sup_1 circ_increasing circ_transitive_equal le_iff_sup)\n\nlemma circ_one:\n  \"1\\<^sup>\\<circ> = 1\\<^sup>\\<circ>\\<^sup>\\<circ>\"\n  by (metis circ_circ_circ circ_zero)\n\nlemma circ_sup_sub:\n  \"(x\\<^sup>\\<circ> * y)\\<^sup>\\<circ> * x\\<^sup>\\<circ> \\<le> (x \\<squnion> y)\\<^sup>\\<circ>\"\n  by (metis circ_sup_1 circ_left_slide)\n\nlemma circ_plus_one:\n  \"x\\<^sup>\\<circ> = 1 \\<squnion> x\\<^sup>\\<circ>\"\n  by (metis le_iff_sup circ_reflexive)\n\ntext \\<open>\nIteration satisfies a characteristic property of reflexive transitive closures.\n\\<close>\n\nlemma circ_rtc_2:\n  \"1 \\<squnion> x \\<squnion> x\\<^sup>\\<circ> * x\\<^sup>\\<circ> = x\\<^sup>\\<circ>\"\n  by (metis sup_assoc circ_increasing circ_plus_one circ_transitive_equal le_iff_sup)\n\nlemma mult_zero_circ:\n  \"(x * bot)\\<^sup>\\<circ> = 1 \\<squnion> x * bot\"\n  by (metis circ_left_unfold mult_assoc mult_left_zero)\n\nlemma mult_zero_sup_circ:\n  \"(x \\<squnion> y * bot)\\<^sup>\\<circ> = x\\<^sup>\\<circ> * (y * bot)\\<^sup>\\<circ>\"\n  by (metis circ_sup_1 mult_assoc mult_left_zero)\n\nlemma circ_plus_sub:\n  \"x\\<^sup>\\<circ> * x \\<le> x * x\\<^sup>\\<circ>\"\n  by (metis circ_left_slide mult_1_left mult_1_right)\n\nlemma circ_loop_fixpoint:\n  \"y * (y\\<^sup>\\<circ> * z) \\<squnion> z = y\\<^sup>\\<circ> * z\"\n  by (metis sup_commute circ_left_unfold mult_assoc mult_1_left mult_right_dist_sup)\n\nlemma left_plus_below_circ:\n  \"x * x\\<^sup>\\<circ> \\<le> x\\<^sup>\\<circ>\"\n  by (metis sup.cobounded2 circ_left_unfold)\n\nlemma right_plus_below_circ:\n  \"x\\<^sup>\\<circ> * x \\<le> x\\<^sup>\\<circ>\"\n  using circ_right_unfold_sub by auto\n\nlemma circ_sup_upper_bound:\n  \"x \\<le> z\\<^sup>\\<circ> \\<Longrightarrow> y \\<le> z\\<^sup>\\<circ> \\<Longrightarrow> x \\<squnion> y \\<le> z\\<^sup>\\<circ>\"\n  by simp\n\nlemma circ_mult_upper_bound:\n  \"x \\<le> z\\<^sup>\\<circ> \\<Longrightarrow> y \\<le> z\\<^sup>\\<circ> \\<Longrightarrow> x * y \\<le> z\\<^sup>\\<circ>\"\n  by (metis mult_isotone circ_transitive_equal)\n\nlemma circ_sub_dist:\n  \"x\\<^sup>\\<circ> \\<le> (x \\<squnion> y)\\<^sup>\\<circ>\"\n  by (metis circ_sup_sub circ_plus_one mult_1_left mult_right_sub_dist_sup_left order_trans)\n\nlemma circ_sub_dist_1:\n  \"x \\<le> (x \\<squnion> y)\\<^sup>\\<circ>\"\n  using circ_increasing le_supE by blast\n\nlemma circ_sub_dist_2:\n  \"x * y \\<le> (x \\<squnion> y)\\<^sup>\\<circ>\"\n  by (metis sup_commute circ_mult_upper_bound circ_sub_dist_1)\n\nlemma circ_sub_dist_3:\n  \"x\\<^sup>\\<circ> * y\\<^sup>\\<circ> \\<le> (x \\<squnion> y)\\<^sup>\\<circ>\"\n  by (metis sup_commute circ_mult_upper_bound circ_sub_dist)\n\nlemma circ_isotone:\n  \"x \\<le> y \\<Longrightarrow> x\\<^sup>\\<circ> \\<le> y\\<^sup>\\<circ>\"\n  by (metis circ_sub_dist le_iff_sup)\n\nlemma circ_sup_2:\n  \"(x \\<squnion> y)\\<^sup>\\<circ> \\<le> (x\\<^sup>\\<circ> * y\\<^sup>\\<circ>)\\<^sup>\\<circ>\"\n  by (metis sup.bounded_iff circ_increasing circ_isotone circ_reflexive mult_isotone mult_1_left mult_1_right)\n\nlemma circ_sup_one_left_unfold:\n  \"1 \\<le> x \\<Longrightarrow> x * x\\<^sup>\\<circ> = x\\<^sup>\\<circ>\"\n  by (metis antisym le_iff_sup mult_1_left mult_right_sub_dist_sup_left left_plus_below_circ)\n\nlemma circ_sup_one_right_unfold:\n  \"1 \\<le> x \\<Longrightarrow> x\\<^sup>\\<circ> * x = x\\<^sup>\\<circ>\"\n  by (metis antisym le_iff_sup mult_left_sub_dist_sup_left mult_1_right right_plus_below_circ)\n\nlemma circ_decompose_4:\n  \"(x\\<^sup>\\<circ> * y\\<^sup>\\<circ>)\\<^sup>\\<circ> = x\\<^sup>\\<circ> * (y\\<^sup>\\<circ> * x\\<^sup>\\<circ>)\\<^sup>\\<circ>\"\n  by (metis sup_assoc sup_commute circ_sup_1 circ_loop_fixpoint circ_plus_one circ_rtc_2 circ_transitive_equal mult_assoc)\n\nlemma circ_decompose_5:\n  \"(x\\<^sup>\\<circ> * y\\<^sup>\\<circ>)\\<^sup>\\<circ> = (y\\<^sup>\\<circ> * x\\<^sup>\\<circ>)\\<^sup>\\<circ>\"\n  by (metis circ_decompose_4 circ_loop_fixpoint antisym mult_right_sub_dist_sup_right mult_assoc)\n\nlemma circ_decompose_6:\n  \"x\\<^sup>\\<circ> * (y * x\\<^sup>\\<circ>)\\<^sup>\\<circ> = y\\<^sup>\\<circ> * (x * y\\<^sup>\\<circ>)\\<^sup>\\<circ>\"\n  by (metis sup_commute circ_sup_1)\n\nlemma circ_decompose_7:\n  \"(x \\<squnion> y)\\<^sup>\\<circ> = x\\<^sup>\\<circ> * y\\<^sup>\\<circ> * (x \\<squnion> y)\\<^sup>\\<circ>\"\n  by (metis circ_sup_1 circ_decompose_6 circ_transitive_equal mult_assoc)\n\nlemma circ_decompose_8:\n  \"(x \\<squnion> y)\\<^sup>\\<circ> = (x \\<squnion> y)\\<^sup>\\<circ> * x\\<^sup>\\<circ> * y\\<^sup>\\<circ>\"\n  by (metis antisym eq_refl mult_assoc mult_isotone mult_1_right circ_mult_upper_bound circ_reflexive circ_sub_dist_3)\n\nlemma circ_decompose_9:\n  \"(x\\<^sup>\\<circ> * y\\<^sup>\\<circ>)\\<^sup>\\<circ> = x\\<^sup>\\<circ> * y\\<^sup>\\<circ> * (x\\<^sup>\\<circ> * y\\<^sup>\\<circ>)\\<^sup>\\<circ>\"\n  by (metis circ_decompose_4 mult_assoc)\n\nlemma circ_decompose_10:\n  \"(x\\<^sup>\\<circ> * y\\<^sup>\\<circ>)\\<^sup>\\<circ> = (x\\<^sup>\\<circ> * y\\<^sup>\\<circ>)\\<^sup>\\<circ> * x\\<^sup>\\<circ> * y\\<^sup>\\<circ>\"\n  by (metis sup_ge2 circ_loop_fixpoint circ_reflexive circ_sup_one_right_unfold mult_assoc order_trans)\n\nlemma circ_back_loop_prefixpoint:\n  \"(z * y\\<^sup>\\<circ>) * y \\<squnion> z \\<le> z * y\\<^sup>\\<circ>\"\n  by (metis sup.bounded_iff circ_left_unfold mult_assoc mult_left_sub_dist_sup_left mult_right_isotone mult_1_right right_plus_below_circ)\n\ntext \\<open>\nWe obtain the fixpoint and prefixpoint properties of iteration, but not least or greatest fixpoint properties.\n\\<close>\n\nlemma circ_loop_is_fixpoint:\n  \"is_fixpoint (\\<lambda>x . y * x \\<squnion> z) (y\\<^sup>\\<circ> * z)\"\n  by (metis circ_loop_fixpoint is_fixpoint_def)\n\nlemma circ_back_loop_is_prefixpoint:\n  \"is_prefixpoint (\\<lambda>x . x * y \\<squnion> z) (z * y\\<^sup>\\<circ>)\"\n  by (metis circ_back_loop_prefixpoint is_prefixpoint_def)\n\nlemma circ_circ_sup:\n  \"(1 \\<squnion> x)\\<^sup>\\<circ> = x\\<^sup>\\<circ>\\<^sup>\\<circ>\"\n  by (metis sup_commute circ_sup_1 circ_decompose_4 circ_zero mult_1_right)\n\nlemma circ_circ_mult_sub:\n  \"x\\<^sup>\\<circ> * 1\\<^sup>\\<circ> \\<le> x\\<^sup>\\<circ>\\<^sup>\\<circ>\"\n  by (metis circ_increasing circ_isotone circ_mult_upper_bound circ_reflexive)\n\nlemma left_plus_circ:\n  \"(x * x\\<^sup>\\<circ>)\\<^sup>\\<circ> = x\\<^sup>\\<circ>\"\n  by (metis circ_left_unfold circ_sup_1 mult_1_right mult_sub_right_one sup.absorb1 mult_assoc)\n\nlemma right_plus_circ:\n  \"(x\\<^sup>\\<circ> * x)\\<^sup>\\<circ> = x\\<^sup>\\<circ>\"\n  by (metis sup_commute circ_isotone circ_loop_fixpoint circ_plus_sub circ_sub_dist eq_iff left_plus_circ)\n\nlemma circ_square:\n  \"(x * x)\\<^sup>\\<circ> \\<le> x\\<^sup>\\<circ>\"\n  by (metis circ_increasing circ_isotone left_plus_circ mult_right_isotone)\n\nlemma circ_mult_sub_sup:\n  \"(x * y)\\<^sup>\\<circ> \\<le> (x \\<squnion> y)\\<^sup>\\<circ>\"\n  by (metis sup_ge1 sup_ge2 circ_isotone circ_square mult_isotone order_trans)\n\nlemma circ_sup_mult_zero:\n  \"x\\<^sup>\\<circ> * y = (x \\<squnion> y * bot)\\<^sup>\\<circ> * y\"\nproof -\n  have \"(x \\<squnion> y * bot)\\<^sup>\\<circ> * y = x\\<^sup>\\<circ> * (1 \\<squnion> y * bot) * y\"\n    by (metis mult_zero_sup_circ mult_zero_circ)\n  also have \"... = x\\<^sup>\\<circ> * (y \\<squnion> y * bot)\"\n    by (metis mult_assoc mult_1_left mult_left_zero mult_right_dist_sup)\n  also have \"... = x\\<^sup>\\<circ> * y\"\n    by (metis sup_commute le_iff_sup zero_right_mult_decreasing)\n  finally show ?thesis\n    by simp\nqed\n\nlemma troeger_1:\n  \"(x \\<squnion> y)\\<^sup>\\<circ> = x\\<^sup>\\<circ> * (1 \\<squnion> y * (x \\<squnion> y)\\<^sup>\\<circ>)\"\n  by (metis circ_sup_1 circ_left_unfold mult_assoc)\n\nlemma troeger_2:\n  \"(x \\<squnion> y)\\<^sup>\\<circ> * z = x\\<^sup>\\<circ> * (y * (x \\<squnion> y)\\<^sup>\\<circ> * z \\<squnion> z)\"\n  by (metis circ_sup_1 circ_loop_fixpoint mult_assoc)\n\nlemma troeger_3:\n  \"(x \\<squnion> y * bot)\\<^sup>\\<circ> = x\\<^sup>\\<circ> * (1 \\<squnion> y * bot)\"\n  by (metis mult_zero_sup_circ mult_zero_circ)\n\nlemma circ_sup_sub_sup_one_1:\n  \"x \\<squnion> y \\<le> x\\<^sup>\\<circ> * (1 \\<squnion> y)\"\n  by (metis circ_increasing circ_left_unfold mult_1_left mult_1_right mult_left_sub_dist_sup mult_right_sub_dist_sup_left order_trans sup_mono)\n\nlemma circ_sup_sub_sup_one_2:\n  \"x\\<^sup>\\<circ> * (x \\<squnion> y) \\<le> x\\<^sup>\\<circ> * (1 \\<squnion> y)\"\n  by (metis circ_sup_sub_sup_one_1 circ_transitive_equal mult_assoc mult_right_isotone)\n\nlemma circ_sup_sub_sup_one:\n  \"x * x\\<^sup>\\<circ> * (x \\<squnion> y) \\<le> x * x\\<^sup>\\<circ> * (1 \\<squnion> y)\"\n  by (metis circ_sup_sub_sup_one_2 mult_assoc mult_right_isotone)\n\nlemma circ_square_2:\n  \"(x * x)\\<^sup>\\<circ> * (x \\<squnion> 1) \\<le> x\\<^sup>\\<circ>\"\n  by (metis sup.bounded_iff circ_increasing circ_mult_upper_bound circ_reflexive circ_square)\n\nlemma circ_extra_circ:\n  \"(y * x\\<^sup>\\<circ>)\\<^sup>\\<circ> = (y * y\\<^sup>\\<circ> * x\\<^sup>\\<circ>)\\<^sup>\\<circ>\"\n  by (metis circ_decompose_6 circ_transitive_equal left_plus_circ mult_assoc)\n\nlemma circ_circ_sub_mult:\n  \"1\\<^sup>\\<circ> * x\\<^sup>\\<circ> \\<le> x\\<^sup>\\<circ>\\<^sup>\\<circ>\"\n  by (metis circ_increasing circ_isotone circ_mult_upper_bound circ_reflexive)\n\nlemma circ_decompose_11:\n  \"(x\\<^sup>\\<circ> * y\\<^sup>\\<circ>)\\<^sup>\\<circ> = (x\\<^sup>\\<circ> * y\\<^sup>\\<circ>)\\<^sup>\\<circ> * x\\<^sup>\\<circ>\"\n  by (metis circ_decompose_10 circ_decompose_4 circ_decompose_5 circ_decompose_9 left_plus_circ)\n\nlemma circ_mult_below_circ_circ:\n  \"(x * y)\\<^sup>\\<circ> \\<le> (x\\<^sup>\\<circ> * y)\\<^sup>\\<circ> * x\\<^sup>\\<circ>\"\n  by (metis circ_increasing circ_isotone circ_reflexive dual_order.trans mult_left_isotone mult_right_isotone mult_1_right)\n\n(*\nlemma circ_right_unfold: \"1 \\<squnion> x\\<^sup>\\<circ> * x = x\\<^sup>\\<circ>\" nitpick [expect=genuine] oops\nlemma circ_mult: \"1 \\<squnion> x * (y * x)\\<^sup>\\<circ> * y = (x * y)\\<^sup>\\<circ>\" nitpick [expect=genuine] oops\nlemma circ_slide: \"(x * y)\\<^sup>\\<circ> * x = x * (y * x)\\<^sup>\\<circ>\" nitpick [expect=genuine] oops\nlemma circ_plus_same: \"x\\<^sup>\\<circ> * x = x * x\\<^sup>\\<circ>\" nitpick [expect=genuine] oops\nlemma \"1\\<^sup>\\<circ> * x\\<^sup>\\<circ> \\<le> x\\<^sup>\\<circ> * 1\\<^sup>\\<circ>\" nitpick [expect=genuine,card=7] oops\nlemma circ_circ_mult_1: \"x\\<^sup>\\<circ> * 1\\<^sup>\\<circ> = x\\<^sup>\\<circ>\\<^sup>\\<circ>\" nitpick [expect=genuine,card=7] oops\nlemma \"x\\<^sup>\\<circ> * 1\\<^sup>\\<circ> \\<le> 1\\<^sup>\\<circ> * x\\<^sup>\\<circ>\" nitpick [expect=genuine,card=7] oops\nlemma circ_circ_mult: \"1\\<^sup>\\<circ> * x\\<^sup>\\<circ> = x\\<^sup>\\<circ>\\<^sup>\\<circ>\" nitpick [expect=genuine,card=7] oops\nlemma circ_sup: \"(x\\<^sup>\\<circ> * y)\\<^sup>\\<circ> * x\\<^sup>\\<circ> = (x \\<squnion> y)\\<^sup>\\<circ>\" nitpick [expect=genuine,card=8] oops\nlemma circ_unfold_sum: \"(x \\<squnion> y)\\<^sup>\\<circ> = x\\<^sup>\\<circ> \\<squnion> x\\<^sup>\\<circ> * y * (x \\<squnion> y)\\<^sup>\\<circ>\" nitpick [expect=genuine,card=7] oops\n\nlemma mult_zero_sup_circ_2: \"(x \\<squnion> y * bot)\\<^sup>\\<circ> = x\\<^sup>\\<circ> \\<squnion> x\\<^sup>\\<circ> * y * bot\" nitpick [expect=genuine,card=7] oops\nlemma sub_mult_one_circ: \"x * 1\\<^sup>\\<circ> \\<le> 1\\<^sup>\\<circ> * x\" nitpick [expect=genuine] oops\nlemma circ_back_loop_fixpoint: \"(z * y\\<^sup>\\<circ>) * y \\<squnion> z = z * y\\<^sup>\\<circ>\" nitpick [expect=genuine] oops\nlemma circ_back_loop_is_fixpoint: \"is_fixpoint (\\<lambda>x . x * y \\<squnion> z) (z * y\\<^sup>\\<circ>)\" nitpick [expect=genuine] oops\nlemma \"x\\<^sup>\\<circ> * y\\<^sup>\\<circ> \\<le> (x\\<^sup>\\<circ> * y)\\<^sup>\\<circ> * x\\<^sup>\\<circ>\" nitpick [expect=genuine,card=7] oops\n*)\n\nend\n\ntext \\<open>\nThe next class considers the interaction of iteration with a greatest element.\n\\<close>\n\nclass bounded_left_conway_semiring = bounded_idempotent_left_semiring + left_conway_semiring\nbegin\n\nlemma circ_top:\n  \"top\\<^sup>\\<circ> = top\"\n  by (simp add: antisym circ_increasing)\n\nlemma circ_right_top:\n  \"x\\<^sup>\\<circ> * top = top\"\n  by (metis sup_right_top circ_loop_fixpoint)\n\nlemma circ_left_top:\n  \"top * x\\<^sup>\\<circ> = top\"\n  by (metis circ_right_top circ_top circ_decompose_11)\n\nlemma mult_top_circ:\n  \"(x * top)\\<^sup>\\<circ> = 1 \\<squnion> x * top\"\n  by (metis circ_left_top circ_left_unfold mult_assoc)\n\nend\n\nclass left_zero_conway_semiring = idempotent_left_zero_semiring + left_conway_semiring\nbegin\n\nlemma mult_zero_sup_circ_2:\n  \"(x \\<squnion> y * bot)\\<^sup>\\<circ> = x\\<^sup>\\<circ> \\<squnion> x\\<^sup>\\<circ> * y * bot\"\n  by (metis mult_assoc mult_left_dist_sup mult_1_right troeger_3)\n\nlemma circ_unfold_sum:\n  \"(x \\<squnion> y)\\<^sup>\\<circ> = x\\<^sup>\\<circ> \\<squnion> x\\<^sup>\\<circ> * y * (x \\<squnion> y)\\<^sup>\\<circ>\"\n  by (metis mult_assoc mult_left_dist_sup mult_1_right troeger_1)\n\nend\n\ntext \\<open>\nThe next class assumes the full sliding equation.\n\\<close>\n\nclass left_conway_semiring_1 = left_conway_semiring +\n  assumes circ_right_slide: \"x * (y * x)\\<^sup>\\<circ> \\<le> (x * y)\\<^sup>\\<circ> * x\"\nbegin\n\nlemma circ_slide_1:\n  \"x * (y * x)\\<^sup>\\<circ> = (x * y)\\<^sup>\\<circ> * x\"\n  by (metis antisym circ_left_slide circ_right_slide)\n\ntext \\<open>\nThis implies the full unfold rules and Conway's productstar.\n\\<close>\n\nlemma circ_right_unfold_1:\n  \"1 \\<squnion> x\\<^sup>\\<circ> * x = x\\<^sup>\\<circ>\"\n  by (metis circ_left_unfold circ_slide_1 mult_1_left mult_1_right)\n\nlemma circ_mult_1:\n  \"(x * y)\\<^sup>\\<circ> = 1 \\<squnion> x * (y * x)\\<^sup>\\<circ> * y\"\n  by (metis circ_left_unfold circ_slide_1 mult_assoc)\n\nlemma circ_sup_9:\n  \"(x \\<squnion> y)\\<^sup>\\<circ> = (x\\<^sup>\\<circ> * y)\\<^sup>\\<circ> * x\\<^sup>\\<circ>\"\n  by (metis circ_sup_1 circ_slide_1)\n\nlemma circ_plus_same:\n  \"x\\<^sup>\\<circ> * x = x * x\\<^sup>\\<circ>\"\n  by (metis circ_slide_1 mult_1_left mult_1_right)\n\nlemma circ_decompose_12:\n  \"x\\<^sup>\\<circ> * y\\<^sup>\\<circ> \\<le> (x\\<^sup>\\<circ> * y)\\<^sup>\\<circ> * x\\<^sup>\\<circ>\"\n  by (metis circ_sup_9 circ_sub_dist_3)\n\nend\n\nclass left_zero_conway_semiring_1 = left_zero_conway_semiring + left_conway_semiring_1\nbegin\n\nlemma circ_back_loop_fixpoint:\n  \"(z * y\\<^sup>\\<circ>) * y \\<squnion> z = z * y\\<^sup>\\<circ>\"\n  by (metis sup_commute circ_left_unfold circ_plus_same mult_assoc mult_left_dist_sup mult_1_right)\n\nlemma circ_back_loop_is_fixpoint:\n  \"is_fixpoint (\\<lambda>x . x * y \\<squnion> z) (z * y\\<^sup>\\<circ>)\"\n  by (metis circ_back_loop_fixpoint is_fixpoint_def)\n\nlemma circ_elimination:\n  \"x * y = bot \\<Longrightarrow> x * y\\<^sup>\\<circ> \\<le> x\"\n  by (metis sup_monoid.add_0_left circ_back_loop_fixpoint circ_plus_same mult_assoc mult_left_zero order_refl)\n\nend\n\nsubsection \\<open>Iterings\\<close>\n\ntext \\<open>\nThis section adds simulation axioms to Conway semirings.\nWe consider several classes with increasingly general simulation axioms.\n\\<close>\n\nclass itering_1 = left_conway_semiring_1 +\n  assumes circ_simulate: \"z * x \\<le> y * z \\<longrightarrow> z * x\\<^sup>\\<circ> \\<le> y\\<^sup>\\<circ> * z\"\nbegin\n\nlemma circ_circ_mult:\n  \"1\\<^sup>\\<circ> * x\\<^sup>\\<circ> = x\\<^sup>\\<circ>\\<^sup>\\<circ>\"\n  by (metis antisym circ_circ_sup circ_reflexive circ_simulate circ_sub_dist_3 circ_sup_one_left_unfold circ_transitive_equal mult_1_left order_refl)\n\nlemma sub_mult_one_circ:\n  \"x * 1\\<^sup>\\<circ> \\<le> 1\\<^sup>\\<circ> * x\"\n  by (metis circ_simulate mult_1_left mult_1_right order_refl)\n\ntext \\<open>\nThe left simulation axioms is enough to prove a basic import property of tests.\n\\<close>\n\nlemma circ_import:\n  assumes \"p \\<le> p * p\"\n      and \"p \\<le> 1\"\n      and \"p * x \\<le> x * p\"\n    shows \"p * x\\<^sup>\\<circ> = p * (p * x)\\<^sup>\\<circ>\"\nproof -\n  have \"p * x \\<le> p * (p * x * p) * p\"\n    by (metis assms coreflexive_transitive eq_iff test_preserves_equation mult_assoc)\n  hence \"p * x\\<^sup>\\<circ> \\<le> p * (p * x)\\<^sup>\\<circ>\"\n    by (metis (no_types) assms circ_simulate circ_slide_1 test_preserves_equation)\n  thus ?thesis\n    by (metis assms(2) circ_isotone mult_left_isotone mult_1_left mult_right_isotone antisym)\nqed\n\nend\n\ntext \\<open>\nIncluding generalisations of both simulation axioms allows us to prove separation rules.\n\\<close>\n\nclass itering_2 = left_conway_semiring_1 +\n  assumes circ_simulate_right: \"z * x \\<le> y * z \\<squnion> w \\<longrightarrow> z * x\\<^sup>\\<circ> \\<le> y\\<^sup>\\<circ> * (z \\<squnion> w * x\\<^sup>\\<circ>)\"\n  assumes circ_simulate_left: \"x * z \\<le> z * y \\<squnion> w \\<longrightarrow> x\\<^sup>\\<circ> * z \\<le> (z \\<squnion> x\\<^sup>\\<circ> * w) * y\\<^sup>\\<circ>\"\nbegin\n\nsubclass itering_1\n  apply unfold_locales\n  by (metis sup_monoid.add_0_right circ_simulate_right mult_left_zero)\n\nlemma circ_simulate_left_1:\n  \"x * z \\<le> z * y \\<Longrightarrow> x\\<^sup>\\<circ> * z \\<le> z * y\\<^sup>\\<circ> \\<squnion> x\\<^sup>\\<circ> * bot\"\n  by (metis sup_monoid.add_0_right circ_simulate_left mult_assoc mult_left_zero mult_right_dist_sup)\n\nlemma circ_separate_1:\n  assumes \"y * x \\<le> x * y\"\n    shows \"(x \\<squnion> y)\\<^sup>\\<circ> = x\\<^sup>\\<circ> * y\\<^sup>\\<circ>\"\nproof -\n  have \"y\\<^sup>\\<circ> * x \\<le> x * y\\<^sup>\\<circ> \\<squnion> y\\<^sup>\\<circ> * bot\"\n    by (metis assms circ_simulate_left_1)\n  hence \"y\\<^sup>\\<circ> * x * y\\<^sup>\\<circ> \\<le> x * y\\<^sup>\\<circ> * y\\<^sup>\\<circ> \\<squnion> y\\<^sup>\\<circ> * bot * y\\<^sup>\\<circ>\"\n    by (metis mult_assoc mult_left_isotone mult_right_dist_sup)\n  also have \"... = x * y\\<^sup>\\<circ> \\<squnion> y\\<^sup>\\<circ> * bot\"\n    by (metis circ_transitive_equal mult_assoc mult_left_zero)\n  finally have \"y\\<^sup>\\<circ> * (x * y\\<^sup>\\<circ>)\\<^sup>\\<circ> \\<le> x\\<^sup>\\<circ> * (y\\<^sup>\\<circ> \\<squnion> y\\<^sup>\\<circ> * bot)\"\n    using circ_simulate_right mult_assoc by fastforce\n  also have \"... = x\\<^sup>\\<circ> * y\\<^sup>\\<circ>\"\n    by (simp add: sup_absorb1 zero_right_mult_decreasing)\n  finally have \"(x \\<squnion> y)\\<^sup>\\<circ> \\<le> x\\<^sup>\\<circ> * y\\<^sup>\\<circ>\"\n    by (simp add: circ_decompose_6 circ_sup_1)\n  thus ?thesis\n    by (simp add: antisym circ_sub_dist_3)\nqed\n\nlemma circ_circ_mult_1:\n  \"x\\<^sup>\\<circ> * 1\\<^sup>\\<circ> = x\\<^sup>\\<circ>\\<^sup>\\<circ>\"\n  by (metis sup_commute circ_circ_sup circ_separate_1 mult_1_left mult_1_right order_refl)\n\nend\n\ntext \\<open>\nWith distributivity, we also get Back's atomicity refinement theorem.\n\\<close>\n\nclass itering_3 = itering_2 + left_zero_conway_semiring_1\nbegin\n\nlemma circ_simulate_1:\n  assumes \"y * x \\<le> x * y\"\n    shows \"y\\<^sup>\\<circ> * x\\<^sup>\\<circ> \\<le> x\\<^sup>\\<circ> * y\\<^sup>\\<circ>\"\nproof -\n  have \"y * x\\<^sup>\\<circ> \\<le> x\\<^sup>\\<circ> * y\"\n    by (metis assms circ_simulate)\n  hence \"y\\<^sup>\\<circ> * x\\<^sup>\\<circ> \\<le> x\\<^sup>\\<circ> * y\\<^sup>\\<circ> \\<squnion> y\\<^sup>\\<circ> * bot\"\n    by (metis circ_simulate_left_1)\n  thus ?thesis\n    by (metis sup_assoc sup_monoid.add_0_right circ_loop_fixpoint mult_assoc mult_left_zero mult_zero_sup_circ_2)\nqed\n\nlemma atomicity_refinement:\n  assumes \"s = s * q\"\n      and \"x = q * x\"\n      and \"q * b = bot\"\n      and \"r * b \\<le> b * r\"\n      and \"r * l \\<le> l * r\"\n      and \"x * l \\<le> l * x\"\n      and \"b * l \\<le> l * b\"\n      and \"q * l \\<le> l * q\"\n      and \"r\\<^sup>\\<circ> * q \\<le> q * r\\<^sup>\\<circ>\"\n      and \"q \\<le> 1\"\n    shows \"s * (x \\<squnion> b \\<squnion> r \\<squnion> l)\\<^sup>\\<circ> * q \\<le> s * (x * b\\<^sup>\\<circ> * q \\<squnion> r \\<squnion> l)\\<^sup>\\<circ>\"\nproof -\n  have \"(x \\<squnion> b \\<squnion> r) * l \\<le> l * (x \\<squnion> b \\<squnion> r)\"\n    using assms(5-7) mult_left_dist_sup mult_right_dist_sup semiring.add_mono by presburger\n  hence \"s * (x \\<squnion> b \\<squnion> r \\<squnion> l)\\<^sup>\\<circ> * q = s * l\\<^sup>\\<circ> * (x \\<squnion> b \\<squnion> r)\\<^sup>\\<circ> * q\"\n    by (metis sup_commute circ_separate_1 mult_assoc)\n  also have \"... = s * l\\<^sup>\\<circ> * b\\<^sup>\\<circ> * r\\<^sup>\\<circ> * q * (x * b\\<^sup>\\<circ> * r\\<^sup>\\<circ> * q)\\<^sup>\\<circ>\"\n  proof -\n    have \"(b \\<squnion> r)\\<^sup>\\<circ> = b\\<^sup>\\<circ> * r\\<^sup>\\<circ>\"\n      by (simp add: assms(4) circ_separate_1)\n    hence \"b\\<^sup>\\<circ> * r\\<^sup>\\<circ> * (q * (x * b\\<^sup>\\<circ> * r\\<^sup>\\<circ>))\\<^sup>\\<circ> = (x \\<squnion> b \\<squnion> r)\\<^sup>\\<circ>\"\n      by (metis (full_types) assms(2) circ_sup_1 sup_assoc sup_commute mult_assoc)\n    thus ?thesis\n      by (metis circ_slide_1 mult_assoc)\n  qed\n  also have \"... \\<le> s * l\\<^sup>\\<circ> * b\\<^sup>\\<circ> * r\\<^sup>\\<circ> * q * (x * b\\<^sup>\\<circ> * q * r\\<^sup>\\<circ>)\\<^sup>\\<circ>\"\n    by (metis assms(9) circ_isotone mult_assoc mult_right_isotone)\n  also have \"... \\<le> s * q * l\\<^sup>\\<circ> * b\\<^sup>\\<circ> * r\\<^sup>\\<circ> * (x * b\\<^sup>\\<circ> * q * r\\<^sup>\\<circ>)\\<^sup>\\<circ>\"\n    by (metis assms(1,10) mult_left_isotone mult_right_isotone mult_1_right)\n  also have \"... \\<le> s * l\\<^sup>\\<circ> * q * b\\<^sup>\\<circ> * r\\<^sup>\\<circ> * (x * b\\<^sup>\\<circ> * q * r\\<^sup>\\<circ>)\\<^sup>\\<circ>\"\n    by (metis assms(1,8) circ_simulate mult_assoc mult_left_isotone mult_right_isotone)\n  also have \"... \\<le> s * l\\<^sup>\\<circ> * r\\<^sup>\\<circ> * (x * b\\<^sup>\\<circ> * q * r\\<^sup>\\<circ>)\\<^sup>\\<circ>\"\n    by (metis assms(3,10) sup_monoid.add_0_left circ_back_loop_fixpoint circ_plus_same mult_assoc mult_left_zero mult_left_isotone mult_right_isotone mult_1_right)\n  also have \"... \\<le> s * (x * b\\<^sup>\\<circ> * q \\<squnion> r \\<squnion> l)\\<^sup>\\<circ>\"\n    by (metis sup_commute circ_sup_1 circ_sub_dist_3 mult_assoc mult_right_isotone)\n  finally show ?thesis\n    .\nqed\n\nend\n\ntext \\<open>\nThe following class contains the most general simulation axioms we consider.\nThey allow us to prove further separation properties.\n\\<close>\n\nclass itering = idempotent_left_zero_semiring + circ +\n  assumes circ_sup: \"(x \\<squnion> y)\\<^sup>\\<circ> = (x\\<^sup>\\<circ> * y)\\<^sup>\\<circ> * x\\<^sup>\\<circ>\"\n  assumes circ_mult: \"(x * y)\\<^sup>\\<circ> = 1 \\<squnion> x * (y * x)\\<^sup>\\<circ> * y\"\n  assumes circ_simulate_right_plus: \"z * x \\<le> y * y\\<^sup>\\<circ> * z \\<squnion> w \\<longrightarrow> z * x\\<^sup>\\<circ> \\<le> y\\<^sup>\\<circ> * (z \\<squnion> w * x\\<^sup>\\<circ>)\"\n  assumes circ_simulate_left_plus: \"x * z \\<le> z * y\\<^sup>\\<circ> \\<squnion> w \\<longrightarrow> x\\<^sup>\\<circ> * z \\<le> (z \\<squnion> x\\<^sup>\\<circ> * w) * y\\<^sup>\\<circ>\"\nbegin\n\nlemma circ_right_unfold:\n  \"1 \\<squnion> x\\<^sup>\\<circ> * x = x\\<^sup>\\<circ>\"\n  by (metis circ_mult mult_1_left mult_1_right)\n\nlemma circ_slide:\n  \"x * (y * x)\\<^sup>\\<circ> = (x * y)\\<^sup>\\<circ> * x\"\nproof -\n  have \"x * (y * x)\\<^sup>\\<circ> = Rf x (y * 1 \\<squnion> y * (x * (y * x)\\<^sup>\\<circ> * y)) * x\"\n    by (metis (no_types) circ_mult mult_1_left mult_1_right mult_left_dist_sup mult_right_dist_sup mult_assoc)\n  thus ?thesis\n    by (metis (no_types) circ_mult mult_1_right mult_left_dist_sup mult_assoc)\nqed\n\nsubclass itering_3\n  apply unfold_locales\n  apply (metis circ_mult mult_1_left mult_1_right)\n  apply (metis circ_slide order_refl)\n  apply (metis circ_sup circ_slide)\n  apply (metis circ_slide order_refl)\n  apply (metis sup_left_isotone circ_right_unfold mult_left_isotone mult_left_sub_dist_sup_left mult_1_right order_trans circ_simulate_right_plus)\n  by (metis sup_commute sup_ge1 sup_right_isotone circ_mult mult_right_isotone mult_1_right order_trans circ_simulate_left_plus)\n\nlemma circ_simulate_right_plus_1:\n  \"z * x \\<le> y * y\\<^sup>\\<circ> * z \\<Longrightarrow> z * x\\<^sup>\\<circ> \\<le> y\\<^sup>\\<circ> * z\"\n  by (metis sup_monoid.add_0_right circ_simulate_right_plus mult_left_zero)\n\nlemma circ_simulate_left_plus_1:\n  \"x * z \\<le> z * y\\<^sup>\\<circ> \\<Longrightarrow> x\\<^sup>\\<circ> * z \\<le> z * y\\<^sup>\\<circ> \\<squnion> x\\<^sup>\\<circ> * bot\"\n  by (metis sup_monoid.add_0_right circ_simulate_left_plus mult_assoc mult_left_zero mult_right_dist_sup)\n\nlemma circ_simulate_2:\n  \"y * x\\<^sup>\\<circ> \\<le> x\\<^sup>\\<circ> * y\\<^sup>\\<circ> \\<longleftrightarrow> y\\<^sup>\\<circ> * x\\<^sup>\\<circ> \\<le> x\\<^sup>\\<circ> * y\\<^sup>\\<circ>\"\n  apply (rule iffI)\n  apply (metis sup_assoc sup_monoid.add_0_right circ_loop_fixpoint circ_simulate_left_plus_1 mult_assoc mult_left_zero mult_zero_sup_circ_2)\n  by (metis circ_increasing mult_left_isotone order_trans)\n\nlemma circ_simulate_absorb:\n  \"y * x \\<le> x \\<Longrightarrow> y\\<^sup>\\<circ> * x \\<le> x \\<squnion> y\\<^sup>\\<circ> * bot\"\n  by (metis circ_simulate_left_plus_1 circ_zero mult_1_right)\n\nlemma circ_simulate_3:\n  \"y * x\\<^sup>\\<circ> \\<le> x\\<^sup>\\<circ> \\<Longrightarrow> y\\<^sup>\\<circ> * x\\<^sup>\\<circ> \\<le> x\\<^sup>\\<circ> * y\\<^sup>\\<circ>\"\n  by (metis sup.bounded_iff circ_reflexive circ_simulate_2 le_iff_sup mult_right_isotone mult_1_right)\n\nlemma circ_separate_mult_1:\n  \"y * x \\<le> x * y \\<Longrightarrow> (x * y)\\<^sup>\\<circ> \\<le> x\\<^sup>\\<circ> * y\\<^sup>\\<circ>\"\n  by (metis circ_mult_sub_sup circ_separate_1)\n\nlemma circ_separate_unfold:\n  \"(y * x\\<^sup>\\<circ>)\\<^sup>\\<circ> = y\\<^sup>\\<circ> \\<squnion> y\\<^sup>\\<circ> * y * x * x\\<^sup>\\<circ> * (y * x\\<^sup>\\<circ>)\\<^sup>\\<circ>\"\n  by (metis circ_back_loop_fixpoint circ_plus_same circ_unfold_sum sup_commute mult_assoc)\n\nlemma separation:\n  assumes \"y * x \\<le> x * y\\<^sup>\\<circ>\"\n    shows \"(x \\<squnion> y)\\<^sup>\\<circ> = x\\<^sup>\\<circ> * y\\<^sup>\\<circ>\"\nproof -\n  have \"y\\<^sup>\\<circ> * x * y\\<^sup>\\<circ> \\<le> x * y\\<^sup>\\<circ> \\<squnion> y\\<^sup>\\<circ> * bot\"\n    by (metis assms circ_simulate_left_plus_1 circ_transitive_equal mult_assoc mult_left_isotone)\n  thus ?thesis\n    by (metis sup_commute circ_sup_1 circ_simulate_right circ_sub_dist_3 le_iff_sup mult_assoc mult_left_zero zero_right_mult_decreasing)\nqed\n\nlemma simulation:\n  \"y * x \\<le> x * y\\<^sup>\\<circ> \\<Longrightarrow> y\\<^sup>\\<circ> * x\\<^sup>\\<circ> \\<le> x\\<^sup>\\<circ> * y\\<^sup>\\<circ>\"\n  by (metis sup_ge2 circ_isotone circ_mult_upper_bound circ_sub_dist separation)\n\nlemma circ_simulate_4:\n  assumes \"y * x \\<le> x * x\\<^sup>\\<circ> * (1 \\<squnion> y)\"\n    shows \"y\\<^sup>\\<circ> * x\\<^sup>\\<circ> \\<le> x\\<^sup>\\<circ> * y\\<^sup>\\<circ>\"\nproof -\n  have \"x \\<squnion> (x * x\\<^sup>\\<circ> * x * x \\<squnion> x * x) = x * x\\<^sup>\\<circ>\"\n    by (metis (no_types) circ_back_loop_fixpoint mult_right_dist_sup sup_commute)\n  hence \"x \\<le> x * x\\<^sup>\\<circ> * 1 \\<squnion> x * x\\<^sup>\\<circ> * y\"\n    by (metis mult_1_right sup_assoc sup_ge1)\n  hence \"(1 \\<squnion> y) * x \\<le> x * x\\<^sup>\\<circ> * (1 \\<squnion> y)\"\n    using assms mult_left_dist_sup mult_right_dist_sup by force\n  hence \"y * x\\<^sup>\\<circ> \\<le> x\\<^sup>\\<circ> * y\\<^sup>\\<circ>\"\n    by (metis circ_sup_upper_bound circ_increasing circ_reflexive circ_simulate_right_plus_1 mult_right_isotone mult_right_sub_dist_sup_right order_trans)\n  thus ?thesis\n    by (metis circ_simulate_2)\nqed\n\nlemma circ_simulate_5:\n  \"y * x \\<le> x * x\\<^sup>\\<circ> * (x \\<squnion> y) \\<Longrightarrow> y\\<^sup>\\<circ> * x\\<^sup>\\<circ> \\<le> x\\<^sup>\\<circ> * y\\<^sup>\\<circ>\"\n  by (metis circ_sup_sub_sup_one circ_simulate_4 order_trans)\n\nlemma circ_simulate_6:\n  \"y * x \\<le> x * (x \\<squnion> y) \\<Longrightarrow> y\\<^sup>\\<circ> * x\\<^sup>\\<circ> \\<le> x\\<^sup>\\<circ> * y\\<^sup>\\<circ>\"\n  by (metis sup_commute circ_back_loop_fixpoint circ_simulate_5 mult_right_sub_dist_sup_left order_trans)\n\nlemma circ_separate_4:\n  assumes \"y * x \\<le> x * x\\<^sup>\\<circ> * (1 \\<squnion> y)\"\n    shows \"(x \\<squnion> y)\\<^sup>\\<circ> = x\\<^sup>\\<circ> * y\\<^sup>\\<circ>\"\nproof -\n  have \"y * x * x\\<^sup>\\<circ> \\<le> x * x\\<^sup>\\<circ> * (1 \\<squnion> y) * x\\<^sup>\\<circ>\"\n    by (simp add: assms mult_left_isotone)\n  also have \"... = x * x\\<^sup>\\<circ> \\<squnion> x * x\\<^sup>\\<circ> * y * x\\<^sup>\\<circ>\"\n    by (simp add: circ_transitive_equal mult_left_dist_sup mult_right_dist_sup mult_assoc)\n  also have \"... \\<le> x * x\\<^sup>\\<circ> \\<squnion> x * x\\<^sup>\\<circ> * x\\<^sup>\\<circ> * y\\<^sup>\\<circ>\"\n    by (metis assms sup_right_isotone circ_simulate_2 circ_simulate_4 mult_assoc mult_right_isotone)\n  finally have \"y * x * x\\<^sup>\\<circ> \\<le> x * x\\<^sup>\\<circ> * y\\<^sup>\\<circ>\"\n    by (metis circ_reflexive circ_transitive_equal le_iff_sup mult_assoc mult_right_isotone mult_1_right)\n  thus ?thesis\n    by (metis circ_sup_1 left_plus_circ mult_assoc separation)\nqed\n\nlemma circ_separate_5:\n  \"y * x \\<le> x * x\\<^sup>\\<circ> * (x \\<squnion> y) \\<Longrightarrow> (x \\<squnion> y)\\<^sup>\\<circ> = x\\<^sup>\\<circ> * y\\<^sup>\\<circ>\"\n  by (metis circ_sup_sub_sup_one circ_separate_4 order_trans)\n\nlemma circ_separate_6:\n  \"y * x \\<le> x * (x \\<squnion> y) \\<Longrightarrow> (x \\<squnion> y)\\<^sup>\\<circ> = x\\<^sup>\\<circ> * y\\<^sup>\\<circ>\"\n  by (metis sup_commute circ_back_loop_fixpoint circ_separate_5 mult_right_sub_dist_sup_left order_trans)\n\nend\n\nclass bounded_itering = bounded_idempotent_left_zero_semiring + itering\nbegin\n\nsubclass bounded_left_conway_semiring ..\n\n(*\nlemma \"1 = x\\<^sup>\\<circ>\" nitpick [expect=genuine] oops\nlemma \"x = x\\<^sup>\\<circ>\" nitpick [expect=genuine] oops\nlemma \"x = x * x\\<^sup>\\<circ>\" nitpick [expect=genuine] oops\nlemma \"x * x\\<^sup>\\<circ> = x\\<^sup>\\<circ>\" nitpick [expect=genuine] oops\nlemma \"x\\<^sup>\\<circ> = x\\<^sup>\\<circ>\\<^sup>\\<circ>\" nitpick [expect=genuine] oops\nlemma \"(x * y)\\<^sup>\\<circ> = (x \\<squnion> y)\\<^sup>\\<circ>\" nitpick [expect=genuine] oops\nlemma \"x\\<^sup>\\<circ> * y\\<^sup>\\<circ> = (x \\<squnion> y)\\<^sup>\\<circ>\" nitpick [expect=genuine,card=6] oops\nlemma \"(x \\<squnion> y)\\<^sup>\\<circ> = (x\\<^sup>\\<circ> * y\\<^sup>\\<circ>)\\<^sup>\\<circ>\" nitpick [expect=genuine] oops\nlemma \"1 = 1\\<^sup>\\<circ>\" nitpick [expect=genuine] oops\n\nlemma \"1 = (x * bot)\\<^sup>\\<circ>\" nitpick [expect=genuine] oops\nlemma \"1 \\<squnion> x * bot = x\\<^sup>\\<circ>\" nitpick [expect=genuine] oops\nlemma \"x\\<^sup>\\<circ> = x\\<^sup>\\<circ> * 1\\<^sup>\\<circ>\" nitpick [expect=genuine] oops\nlemma \"z \\<squnion> y * x = x \\<longrightarrow> y\\<^sup>\\<circ> * z \\<le> x\" nitpick [expect=genuine] oops\nlemma \"y * x = x \\<longrightarrow> y\\<^sup>\\<circ> * x \\<le> x\" nitpick [expect=genuine] oops\nlemma \"z \\<squnion> x * y = x \\<longrightarrow> z * y\\<^sup>\\<circ> \\<le> x\" nitpick [expect=genuine] oops\nlemma \"x * y = x \\<longrightarrow> x * y\\<^sup>\\<circ> \\<le> x\" nitpick [expect=genuine] oops\nlemma \"x = z \\<squnion> y * x \\<longrightarrow> x \\<le> y\\<^sup>\\<circ> * z\" nitpick [expect=genuine] oops\nlemma \"x = y * x \\<longrightarrow> x \\<le> y\\<^sup>\\<circ>\" nitpick [expect=genuine] oops\nlemma \"x * z = z * y \\<longrightarrow> x\\<^sup>\\<circ> * z \\<le> z * y\\<^sup>\\<circ>\" nitpick [expect=genuine] oops\n\nlemma \"x\\<^sup>\\<circ> = (x * x)\\<^sup>\\<circ> * (x \\<squnion> 1)\" oops\nlemma \"y\\<^sup>\\<circ> * x\\<^sup>\\<circ> \\<le> x\\<^sup>\\<circ> * y\\<^sup>\\<circ> \\<longrightarrow> (x \\<squnion> y)\\<^sup>\\<circ> = x\\<^sup>\\<circ> * y\\<^sup>\\<circ>\" oops\nlemma \"y * x \\<le> (1 \\<squnion> x) * y\\<^sup>\\<circ> \\<longrightarrow> (x \\<squnion> y)\\<^sup>\\<circ> = x\\<^sup>\\<circ> * y\\<^sup>\\<circ>\" oops\nlemma \"y * x \\<le> x \\<longrightarrow> y\\<^sup>\\<circ> * x \\<le> 1\\<^sup>\\<circ> * x\" oops\n*)\n\nend\n\ntext \\<open>\nWe finally expand Conway semirings and iterings by an element that corresponds to the endless loop.\n\\<close>\n\nclass L =\n  fixes L :: \"'a\"\n\nclass left_conway_semiring_L = left_conway_semiring + L +\n  assumes one_circ_mult_split: \"1\\<^sup>\\<circ> * x = L \\<squnion> x\"\n  assumes L_split_sup: \"x * (y \\<squnion> L) \\<le> x * y \\<squnion> L\"\nbegin\n\nlemma L_def:\n  \"L = 1\\<^sup>\\<circ> * bot\"\n  by (metis sup_monoid.add_0_right one_circ_mult_split)\n\nlemma one_circ_split:\n  \"1\\<^sup>\\<circ> = L \\<squnion> 1\"\n  by (metis mult_1_right one_circ_mult_split)\n\nlemma one_circ_circ_split:\n  \"1\\<^sup>\\<circ>\\<^sup>\\<circ> = L \\<squnion> 1\"\n  by (metis circ_one one_circ_split)\n\nlemma sub_mult_one_circ:\n  \"x * 1\\<^sup>\\<circ> \\<le> 1\\<^sup>\\<circ> * x\"\n  by (metis L_split_sup sup_commute mult_1_right one_circ_mult_split)\n\nlemma one_circ_mult_split_2:\n  \"1\\<^sup>\\<circ> * x = x * 1\\<^sup>\\<circ> \\<squnion> L\"\nproof -\n  have 1: \"x * 1\\<^sup>\\<circ> \\<le> L \\<squnion> x\"\n    using one_circ_mult_split sub_mult_one_circ by presburger\n  have \"x \\<squnion> x * 1\\<^sup>\\<circ> = x * 1\\<^sup>\\<circ>\"\n    by (meson circ_back_loop_prefixpoint le_iff_sup sup.boundedE)\n  thus ?thesis\n    using 1 by (simp add: le_iff_sup one_circ_mult_split sup_assoc sup_commute)\nqed\n\nlemma sub_mult_one_circ_split:\n  \"x * 1\\<^sup>\\<circ> \\<le> x \\<squnion> L\"\n  by (metis sup_commute one_circ_mult_split sub_mult_one_circ)\n\nlemma sub_mult_one_circ_split_2:\n  \"x * 1\\<^sup>\\<circ> \\<le> x \\<squnion> 1\\<^sup>\\<circ>\"\n  by (metis L_def sup_right_isotone order_trans sub_mult_one_circ_split zero_right_mult_decreasing)\n\nlemma L_split:\n  \"x * L \\<le> x * bot \\<squnion> L\"\n  by (metis L_split_sup sup_monoid.add_0_left)\n\nlemma L_left_zero:\n  \"L * x = L\"\n  by (metis L_def mult_assoc mult_left_zero)\n\nlemma one_circ_L:\n  \"1\\<^sup>\\<circ> * L = L\"\n  by (metis L_def circ_transitive_equal mult_assoc)\n\nlemma mult_L_circ:\n  \"(x * L)\\<^sup>\\<circ> = 1 \\<squnion> x * L\"\n  by (metis L_left_zero circ_left_unfold mult_assoc)\n\nlemma mult_L_circ_mult:\n  \"(x * L)\\<^sup>\\<circ> * y = y \\<squnion> x * L\"\n  by (metis L_left_zero mult_L_circ mult_assoc mult_1_left mult_right_dist_sup)\n\nlemma circ_L:\n  \"L\\<^sup>\\<circ> = L \\<squnion> 1\"\n  by (metis L_left_zero sup_commute circ_left_unfold)\n\nlemma L_below_one_circ:\n  \"L \\<le> 1\\<^sup>\\<circ>\"\n  by (metis L_def zero_right_mult_decreasing)\n\nlemma circ_circ_mult_1:\n  \"x\\<^sup>\\<circ> * 1\\<^sup>\\<circ> = x\\<^sup>\\<circ>\\<^sup>\\<circ>\"\n  by (metis L_left_zero sup_commute circ_sup_1 circ_circ_sup mult_zero_circ one_circ_split)\n\nlemma circ_circ_mult:\n  \"1\\<^sup>\\<circ> * x\\<^sup>\\<circ> = x\\<^sup>\\<circ>\\<^sup>\\<circ>\"\n  by (metis antisym circ_circ_mult_1 circ_circ_sub_mult sub_mult_one_circ)\n\nlemma circ_circ_split:\n  \"x\\<^sup>\\<circ>\\<^sup>\\<circ> = L \\<squnion> x\\<^sup>\\<circ>\"\n  by (metis circ_circ_mult one_circ_mult_split)\n\nlemma circ_sup_6:\n  \"L \\<squnion> (x \\<squnion> y)\\<^sup>\\<circ> = (x\\<^sup>\\<circ> * y\\<^sup>\\<circ>)\\<^sup>\\<circ>\"\n  by (metis sup_assoc sup_commute circ_sup_1 circ_circ_sup circ_circ_split circ_decompose_4)\n\nend\n\nclass itering_L = itering + L +\n  assumes L_def: \"L = 1\\<^sup>\\<circ> * bot\"\nbegin\n\nlemma one_circ_split:\n  \"1\\<^sup>\\<circ> = L \\<squnion> 1\"\n  by (metis L_def sup_commute antisym circ_sup_upper_bound circ_reflexive circ_simulate_absorb mult_1_right order_refl zero_right_mult_decreasing)\n\nlemma one_circ_mult_split:\n  \"1\\<^sup>\\<circ> * x = L \\<squnion> x\"\n  by (metis L_def sup_commute circ_loop_fixpoint mult_assoc mult_left_zero mult_zero_circ one_circ_split)\n\nlemma sub_mult_one_circ_split:\n  \"x * 1\\<^sup>\\<circ> \\<le> x \\<squnion> L\"\n  by (metis sup_commute one_circ_mult_split sub_mult_one_circ)\n\nlemma sub_mult_one_circ_split_2:\n  \"x * 1\\<^sup>\\<circ> \\<le> x \\<squnion> 1\\<^sup>\\<circ>\"\n  by (metis L_def sup_right_isotone order_trans sub_mult_one_circ_split zero_right_mult_decreasing)\n\nlemma L_split:\n  \"x * L \\<le> x * bot \\<squnion> L\"\n  by (metis L_def mult_assoc mult_left_isotone mult_right_dist_sup sub_mult_one_circ_split_2)\n\nsubclass left_conway_semiring_L\n  apply unfold_locales\n  apply (metis L_def sup_commute circ_loop_fixpoint mult_assoc mult_left_zero mult_zero_circ one_circ_split)\n  by (metis sup_commute mult_assoc mult_left_isotone one_circ_mult_split sub_mult_one_circ)\n\nlemma circ_left_induct_mult_L:\n  \"L \\<le> x \\<Longrightarrow> x * y \\<le> x \\<Longrightarrow> x * y\\<^sup>\\<circ> \\<le> x\"\n  by (metis circ_one circ_simulate le_iff_sup one_circ_mult_split)\n\nlemma circ_left_induct_mult_iff_L:\n  \"L \\<le> x \\<Longrightarrow> x * y \\<le> x \\<longleftrightarrow> x * y\\<^sup>\\<circ> \\<le> x\"\n  by (metis sup.bounded_iff circ_back_loop_fixpoint circ_left_induct_mult_L le_iff_sup)\n\nlemma circ_left_induct_L:\n  \"L \\<le> x \\<Longrightarrow> x * y \\<squnion> z \\<le> x \\<Longrightarrow> z * y\\<^sup>\\<circ> \\<le> x\"\n  by (metis sup.bounded_iff circ_left_induct_mult_L le_iff_sup mult_right_dist_sup)\n\nend\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_Kleene_Relation_Algebras/Iterings.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9111797075998823, "lm_q2_score": 0.817574471748733, "lm_q1q2_score": 0.7449572681091388}}
{"text": "section \\<open> SI Prefixes \\<close>\n\ntheory SI_Prefix\n  imports SI_Constants\nbegin\n\nsubsection \\<open> Definitions \\<close>\n\ntext \\<open> Prefixes are simply numbers that can be composed with units using the scalar \n  multiplication operator \\<^const>\\<open>scaleQ\\<close>. \\<close>\n\ndefault_sort ring_char_0\n\ndefinition deca :: \"'a\" where [si_eq]: \"deca = 10^1\"\n\ndefinition hecto :: \"'a\" where [si_eq]: \"hecto = 10^2\"\n\ndefinition kilo :: \"'a\" where [si_eq]: \"kilo = 10^3\"\n\ndefinition mega :: \"'a\" where [si_eq]: \"mega = 10^6\"\n\ndefinition giga :: \"'a\" where [si_eq]: \"giga = 10^9\"\n\ndefinition tera :: \"'a\" where [si_eq]: \"tera = 10^12\"\n\ndefinition peta :: \"'a\" where [si_eq]: \"peta = 10^15\"\n\ndefinition exa :: \"'a\" where [si_eq]: \"exa = 10^18\"\n\ndefinition zetta :: \"'a\" where [si_eq]: \"zetta = 10^21\"\n\ndefinition yotta :: \"'a\" where [si_eq]: \"yotta = 10^24\"\n\ndefault_sort field_char_0\n\ndefinition deci :: \"'a\" where [si_eq]: \"deci = 1/10^1\"\n\ndefinition centi :: \"'a\" where [si_eq]: \"centi = 1/10^2\"\n\ndefinition milli :: \"'a\" where [si_eq]: \"milli = 1/10^3\"\n\ndefinition micro :: \"'a\" where [si_eq]: \"micro = 1/10^6\"\n\ndefinition nano :: \"'a\" where [si_eq]: \"nano = 1/10^9\"\n\ndefinition pico :: \"'a\" where [si_eq]: \"pico = 1/10^12\"\n\ndefinition femto :: \"'a\" where [si_eq]: \"femto = 1/10^15\"\n\ndefinition atto :: \"'a\" where [si_eq]: \"atto = 1/10^18\"\n\ndefinition zepto :: \"'a\" where [si_eq]: \"zepto = 1/10^21\"\n\ndefinition yocto :: \"'a\" where [si_eq]: \"yocto = 1/10^24\"\n\nsubsection \\<open> Examples \\<close>\n\nlemma \"2.3 *\\<^sub>Q (centi *\\<^sub>Q metre)\\<^sup>\\<three> = 2.3 \\<cdot> 1/10^6 *\\<^sub>Q metre\\<^sup>\\<three>\"\n  by (si_simp)\n\nlemma \"1 *\\<^sub>Q (centi *\\<^sub>Q metre)\\<^sup>-\\<^sup>\\<one> = 100 *\\<^sub>Q metre\\<^sup>-\\<^sup>\\<one>\"\n  by (si_simp)\n\nsubsection \\<open> Binary Prefixes \\<close>\n\ntext \\<open> Although not in general applicable to physical quantities, we include these prefixes\n  for completeness. \\<close>\n\ndefault_sort ring_char_0\n\ndefinition kibi :: \"'a\" where [si_eq]: \"kibi = 2^10\"\n\ndefinition mebi :: \"'a\" where [si_eq]: \"mebi = 2^20\"\n\ndefinition gibi :: \"'a\" where [si_eq]: \"gibi = 2^30\"\n\ndefinition tebi :: \"'a\" where [si_eq]: \"tebi = 2^40\"\n\ndefinition pebi :: \"'a\" where [si_eq]: \"pebi = 2^50\"\n\ndefinition exbi :: \"'a\" where [si_eq]: \"exbi = 2^60\"\n\ndefinition zebi :: \"'a\" where [si_eq]: \"zebi = 2^70\"\n\ndefinition yobi :: \"'a\" where [si_eq]: \"yobi = 2^80\"\n\ndefault_sort type\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/SI_Prefix.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9111797003640646, "lm_q2_score": 0.8175744761936437, "lm_q1q2_score": 0.7449572662434313}}
{"text": "section {* \\isaheader{Examples from ITP-2010 slides (adopted to ICF v2)} *}\ntheory itp_2010\nimports \n  \"../../ICF/Collections\" \n  \"../../Lib/Code_Target_ICF\"\nbegin\n\ntext {*\n  Illustrates the various possibilities how to use the ICF in your own \n  algorithms by simple examples. The examples all use the data refinement\n  scheme, and either define a generic algorithm or fix the operations.\n*}\n\n\nsubsection \"List to Set\"\ntext {*\n  In this simple example we do conversion from a list to a set.\n  We define an abstract algorithm.\n  This is then refined by a generic algorithm using a locale and by a generic \n  algorithm fixing its operations as parameters.\n*}\n  subsubsection \"Straightforward version\"\n  -- \"Abstract algorithm\"\n  fun set_a where\n    \"set_a [] s = s\" |\n    \"set_a (a#l) s = set_a l (insert a s)\"\n\n  -- \"Correctness of aa\"\n  lemma set_a_correct: \"set_a l s = set l \\<union> s\"\n    by (induct l arbitrary: s) auto\n\n  -- \"Generic algorithm\"\n\n  setup Locale_Code.open_block -- \"Required to make definitions inside locales\n    executable\"\n  fun (in StdSetDefs) set_i where\n    \"set_i [] s = s\" |\n    \"set_i (a#l) s = set_i l (ins a s)\"\n  setup Locale_Code.close_block\n\n  -- \"Correct implementation of ca\"\n  lemma (in StdSet) set_i_impl: \"invar s \\<Longrightarrow> invar (set_i l s) \\<and> \\<alpha> (set_i l s) = set_a l (\\<alpha> s)\"\n    by (induct l arbitrary: s) (auto simp add: correct)\n\n  -- \"Instantiation\"\n  (* We need to declare a constant to make the code generator work *)\n\n  definition \"hs_seti == hs.set_i\"\n  (*declare hs.set_i.simps[folded hs_seti_def, code]*)\n\n  lemmas hs_set_i_impl = hs.set_i_impl[folded hs_seti_def]\n\nexport_code hs_seti in SML\n\n  -- \"Code generation\"\n  ML {* @{code hs_seti} *} \n  (*value \"hs_seti [1,2,3::nat] hs_empty\"*)\n\n  subsubsection \"Tail-Recursive version\"\n  -- \"Abstract algorithm\"\n  fun set_a2 where\n    \"set_a2 [] = {}\" |\n    \"set_a2 (a#l) = (insert a (set_a2 l))\"\n\n  -- \"Correctness of aa\"\n  lemma set_a2_correct: \"set_a2 l = set l\"\n    by (induct l) auto\n\n  -- \"Generic algorithm\"\n  setup Locale_Code.open_block\n  fun (in StdSetDefs) set_i2 where\n    \"set_i2 [] = empty ()\" |\n    \"set_i2 (a#l) = (ins a (set_i2 l))\"\n  setup Locale_Code.close_block\n\n  -- \"Correct implementation of ca\"\n  lemma (in StdSet) set_i2_impl: \"invar s \\<Longrightarrow> invar (set_i2 l) \\<and> \\<alpha> (set_i2 l) = set_a2 l\"\n    by (induct l) (auto simp add: correct)\n\n  -- \"Instantiation\"\n  definition \"hs_seti2 == hs.set_i2\"\n  (*declare hsr.set_i2.simps[folded hs_seti2_def, code]*)\n\n  lemmas hs_set_i2_impl = hs.set_i2_impl[folded hs_seti2_def]\n\n  -- \"Code generation\"\n  ML {* @{code hs_seti2} *} \n  (*value \"hs_seti [1,2,3::nat] hs_empty\"*)\n\nsubsubsection \"With explicit operation parameters\"\n\n  -- \"Alternative for few operation parameters\"\n  fun set_i' where\n    \"!!ins. set_i' ins [] s = s\" |\n    \"!!ins. set_i' ins (a#l) s = set_i' ins l (ins a s)\"\n\n  lemma (in StdSet) set_i'_impl:\n    \"invar s \\<Longrightarrow> invar (set_i' ins l s) \\<and> \\<alpha> (set_i' ins l s) = set_a l (\\<alpha> s)\"\n    by (induct l arbitrary: s) (auto simp add: correct)\n\n  -- \"Instantiation\"\n  definition \"hs_seti' == set_i' hs.ins\"\n  lemmas hs_set_i'_impl = hs.set_i'_impl[folded hs_seti'_def]\n\n  -- \"Code generation\"\n  ML {* @{code hs_seti'} *} \n  (*value \"hs_seti' [1,2,3::nat] hs_empty\"*)\n\n\nsubsection \"Filter Average\"\ntext {*\n  In this more complex example, we develop a function that filters from a set all\n  numbers that are above the average of the set.\n \n  First, we formulate this as a generic algorithm using a locale.\n  This solution shows how the ICF v2 overcomes some technical problems that\n  ICF v1 had: \n  \\begin{itemize}\n    \\item Iterators are now polymorphic in the type, even inside locales.\n      Hence, there is no special handling of iterators, as it was required\n      in ICF v1.\n    \\item The Locale-Code package handles code generation for the instantiated\n      locale. There is no need for lengthy boilerplate code as it was required\n      in ICF v1.\n  \\end{itemize}\n\n\n  Another possibility is to fix the used \n  implementations beforehand. Changing the implementation is still easy by\n  changing the used operations. In this example, all used operations are \n  introduced by abbbreviations, localizing the required changes to a small part\n  of the theory. This approach is more powerful, as operations are now \n  polymorphic also in the element type. However, it only allows as single \n  instantiation at a time, which is no option for generic algorithms.\n*}\n\n  abbreviation \"average S == \\<Sum>S div card S\"\n\nsubsubsection \"Generic Algorithm\"\n  locale MyContext =\n    StdSet ops for ops :: \"(nat,'s,'more) set_ops_scheme\"\n  begin\n    definition avg_aux :: \"'s \\<Rightarrow> nat\\<times>nat\" \n      where\n      \"avg_aux s == iterate s (\\<lambda>x (c,s). (c+1, s+x)) (0,0)\"\n\n    definition \"avg s == case avg_aux s of (c,s) \\<Rightarrow> s div c\"\n\n    definition \"filter_le_avg s == let a=avg s in\n      iterate s (\\<lambda>x s. if x\\<le>a then ins x s else s) (empty ())\"\n\n    lemma avg_aux_correct: \"invar s \\<Longrightarrow> avg_aux s = (card (\\<alpha> s), \\<Sum>(\\<alpha> s) )\"\n      apply (unfold avg_aux_def)\n      apply (rule_tac \n        I=\"\\<lambda>it (c,sum). c=card (\\<alpha> s - it) \\<and> sum=\\<Sum>(\\<alpha> s - it)\" \n        in iterate_rule_P)\n      apply auto\n      apply (subgoal_tac \"\\<alpha> s - (it - {x}) = insert x (\\<alpha> s - it)\")\n      apply auto\n      apply (subgoal_tac \"\\<alpha> s - (it - {x}) = insert x (\\<alpha> s - it)\")\n      apply auto\n      done\n\n    lemma avg_correct: \"invar s \\<Longrightarrow> avg s = average (\\<alpha> s)\"\n      unfolding avg_def\n      using avg_aux_correct\n      by auto\n\n    lemma filter_le_avg_correct: \n      \"invar s \\<Longrightarrow> \n        invar (filter_le_avg s) \\<and> \n        \\<alpha> (filter_le_avg s) = {x\\<in>\\<alpha> s. x\\<le>average (\\<alpha> s)}\"\n      unfolding filter_le_avg_def Let_def\n      apply (rule_tac\n        I=\"\\<lambda>it r. invar r \\<and> \\<alpha> r = {x\\<in>\\<alpha> s - it. x\\<le>average (\\<alpha> s)}\"\n        in iterate_rule_P)\n      apply (auto simp add: correct avg_correct)\n      done\n  end\n\n  setup Locale_Code.open_block\n  interpretation hs_ctx: MyContext hs_ops by unfold_locales\n  interpretation rs_ctx: MyContext rs_ops by unfold_locales\n  setup Locale_Code.close_block\n\n  definition \"hs_flt_avg_test \\<equiv> hs.to_list \n    o hs_ctx.filter_le_avg \n    o hs.from_list\"\n  definition \"rs_flt_avg_test \\<equiv> rs.to_list \n    o rs_ctx.filter_le_avg \n    o rs.from_list\"\n\n  \n  text \"Code generation\"\n  ML_val {* \n    if @{code hs_flt_avg_test} (map @{code nat_of_integer} [1,2,3,4,6,7])\n    <> @{code rs_flt_avg_test} (map @{code nat_of_integer} [1,2,3,4,6,7])\n    then error \"Oops\"\n    else ()\n    *} \n  \n\nsubsubsection \"Using abbreviations\"\n\n  type_synonym 'a my_set = \"'a hs\"\n  abbreviation \"my_\\<alpha> == hs.\\<alpha>\"\n  abbreviation \"my_invar == hs.invar\"\n  abbreviation \"my_empty == hs.empty\"\n  abbreviation \"my_ins == hs.ins\"\n  abbreviation \"my_iterate == hs.iteratei\"\n  lemmas my_correct = hs.correct\n  lemmas my_iterate_rule_P = hs.iterate_rule_P\n\n  definition avg_aux :: \"nat my_set \\<Rightarrow> nat\\<times>nat\" \n    where\n    \"avg_aux s == my_iterate s (\\<lambda>_. True) (\\<lambda>x (c,s). (c+1, s+x)) (0,0)\"\n\n  definition \"avg s == case avg_aux s of (c,s) \\<Rightarrow> s div c\"\n\n  definition \"filter_le_avg s == let a=avg s in\n    my_iterate s (\\<lambda>_. True) (\\<lambda>x s. if x\\<le>a then my_ins x s else s) (my_empty ())\"\n\n  lemma avg_aux_correct: \"my_invar s \\<Longrightarrow> avg_aux s = (card (my_\\<alpha> s), \\<Sum>(my_\\<alpha> s) )\"\n    apply (unfold avg_aux_def)\n    apply (rule_tac \n      I=\"\\<lambda>it (c,sum). c=card (my_\\<alpha> s - it) \\<and> sum=\\<Sum>(my_\\<alpha> s - it)\" \n      in my_iterate_rule_P)\n    apply auto\n    apply (subgoal_tac \"my_\\<alpha> s - (it - {x}) = insert x (my_\\<alpha> s - it)\")\n    apply auto\n    apply (subgoal_tac \"my_\\<alpha> s - (it - {x}) = insert x (my_\\<alpha> s - it)\")\n    apply auto\n    done\n\n  lemma avg_correct: \"my_invar s \\<Longrightarrow> avg s = average (my_\\<alpha> s)\"\n    unfolding avg_def\n    using avg_aux_correct\n    by auto\n\n  lemma filter_le_avg_correct: \n    \"my_invar s \\<Longrightarrow> \n    my_invar (filter_le_avg s) \\<and> \n    my_\\<alpha> (filter_le_avg s) = {x\\<in>my_\\<alpha> s. x\\<le>average (my_\\<alpha> s)}\"\n    unfolding filter_le_avg_def Let_def\n    apply (rule_tac\n      I=\"\\<lambda>it r. my_invar r \\<and> my_\\<alpha> r = {x\\<in>my_\\<alpha> s - it. x\\<le>average (my_\\<alpha> s)}\"\n      in my_iterate_rule_P)\n    apply (auto simp add: my_correct avg_correct)\n    done\n\n\n  definition \"test_set == my_ins (1::nat) (my_ins 2 (my_ins 3 (my_empty ())))\"\n\n  export_code avg_aux avg filter_le_avg test_set in SML module_name Test\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/Examples/ICF/itp_2010.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430520409023, "lm_q2_score": 0.8962513731336202, "lm_q1q2_score": 0.7449131016621267}}
{"text": "(*  Title:      HOL/Library/Product_Order.thy\n    Author:     Brian Huffman\n*)\n\nsection \\<open>Pointwise order on product types\\<close>\n\ntheory Product_Order\nimports Product_Plus\nbegin\n\nsubsection \\<open>Pointwise ordering\\<close>\n\ninstantiation prod :: (ord, ord) ord\nbegin\n\ndefinition\n  \"x \\<le> y \\<longleftrightarrow> fst x \\<le> fst y \\<and> snd x \\<le> snd y\"\n\ndefinition\n  \"(x::'a \\<times> 'b) < y \\<longleftrightarrow> x \\<le> y \\<and> \\<not> y \\<le> x\"\n\ninstance ..\n\nend\n\nlemma fst_mono: \"x \\<le> y \\<Longrightarrow> fst x \\<le> fst y\"\n  unfolding less_eq_prod_def by simp\n\nlemma snd_mono: \"x \\<le> y \\<Longrightarrow> snd x \\<le> snd y\"\n  unfolding less_eq_prod_def by simp\n\nlemma Pair_mono: \"x \\<le> x' \\<Longrightarrow> y \\<le> y' \\<Longrightarrow> (x, y) \\<le> (x', y')\"\n  unfolding less_eq_prod_def by simp\n\nlemma Pair_le [simp]: \"(a, b) \\<le> (c, d) \\<longleftrightarrow> a \\<le> c \\<and> b \\<le> d\"\n  unfolding less_eq_prod_def by simp\n\nlemma atLeastAtMost_prod_eq: \"{a..b} = {fst a..fst b} \\<times> {snd a..snd b}\"\n  by (auto simp: less_eq_prod_def)\n\ninstance prod :: (preorder, preorder) preorder\nproof\n  fix x y z :: \"'a \\<times> 'b\"\n  show \"x < y \\<longleftrightarrow> x \\<le> y \\<and> \\<not> y \\<le> x\"\n    by (rule less_prod_def)\n  show \"x \\<le> x\"\n    unfolding less_eq_prod_def\n    by fast\n  assume \"x \\<le> y\" and \"y \\<le> z\" thus \"x \\<le> z\"\n    unfolding less_eq_prod_def\n    by (fast elim: order_trans)\nqed\n\ninstance prod :: (order, order) order\n  by standard auto\n\n\nsubsection \\<open>Binary infimum and supremum\\<close>\n\ninstantiation prod :: (inf, inf) inf\nbegin\n\ndefinition \"inf x y = (inf (fst x) (fst y), inf (snd x) (snd y))\"\n\nlemma inf_Pair_Pair [simp]: \"inf (a, b) (c, d) = (inf a c, inf b d)\"\n  unfolding inf_prod_def by simp\n\nlemma fst_inf [simp]: \"fst (inf x y) = inf (fst x) (fst y)\"\n  unfolding inf_prod_def by simp\n\nlemma snd_inf [simp]: \"snd (inf x y) = inf (snd x) (snd y)\"\n  unfolding inf_prod_def by simp\n\ninstance ..\n\nend\n\ninstance prod :: (semilattice_inf, semilattice_inf) semilattice_inf\n  by standard auto\n\n\ninstantiation prod :: (sup, sup) sup\nbegin\n\ndefinition\n  \"sup x y = (sup (fst x) (fst y), sup (snd x) (snd y))\"\n\nlemma sup_Pair_Pair [simp]: \"sup (a, b) (c, d) = (sup a c, sup b d)\"\n  unfolding sup_prod_def by simp\n\nlemma fst_sup [simp]: \"fst (sup x y) = sup (fst x) (fst y)\"\n  unfolding sup_prod_def by simp\n\nlemma snd_sup [simp]: \"snd (sup x y) = sup (snd x) (snd y)\"\n  unfolding sup_prod_def by simp\n\ninstance ..\n\nend\n\ninstance prod :: (semilattice_sup, semilattice_sup) semilattice_sup\n  by standard auto\n\ninstance prod :: (lattice, lattice) lattice ..\n\ninstance prod :: (distrib_lattice, distrib_lattice) distrib_lattice\n  by standard (auto simp add: sup_inf_distrib1)\n\n\nsubsection \\<open>Top and bottom elements\\<close>\n\ninstantiation prod :: (top, top) top\nbegin\n\ndefinition\n  \"top = (top, top)\"\n\ninstance ..\n\nend\n\nlemma fst_top [simp]: \"fst top = top\"\n  unfolding top_prod_def by simp\n\nlemma snd_top [simp]: \"snd top = top\"\n  unfolding top_prod_def by simp\n\nlemma Pair_top_top: \"(top, top) = top\"\n  unfolding top_prod_def by simp\n\ninstance prod :: (order_top, order_top) order_top\n  by standard (auto simp add: top_prod_def)\n\ninstantiation prod :: (bot, bot) bot\nbegin\n\ndefinition\n  \"bot = (bot, bot)\"\n\ninstance ..\n\nend\n\nlemma fst_bot [simp]: \"fst bot = bot\"\n  unfolding bot_prod_def by simp\n\nlemma snd_bot [simp]: \"snd bot = bot\"\n  unfolding bot_prod_def by simp\n\nlemma Pair_bot_bot: \"(bot, bot) = bot\"\n  unfolding bot_prod_def by simp\n\ninstance prod :: (order_bot, order_bot) order_bot\n  by standard (auto simp add: bot_prod_def)\n\ninstance prod :: (bounded_lattice, bounded_lattice) bounded_lattice ..\n\ninstance prod :: (boolean_algebra, boolean_algebra) boolean_algebra\n  by standard (auto simp add: prod_eqI diff_eq)\n\n\nsubsection \\<open>Complete lattice operations\\<close>\n\ninstantiation prod :: (Inf, Inf) Inf\nbegin\n\ndefinition \"Inf A = (INF x\\<in>A. fst x, INF x\\<in>A. snd x)\"\n\ninstance ..\n\nend\n\ninstantiation prod :: (Sup, Sup) Sup\nbegin\n\ndefinition \"Sup A = (SUP x\\<in>A. fst x, SUP x\\<in>A. snd x)\"\n\ninstance ..\n\nend\n\ninstance prod :: (conditionally_complete_lattice, conditionally_complete_lattice)\n    conditionally_complete_lattice\n  by standard (force simp: less_eq_prod_def Inf_prod_def Sup_prod_def bdd_below_def bdd_above_def\n    intro!: cInf_lower cSup_upper cInf_greatest cSup_least)+\n\ninstance prod :: (complete_lattice, complete_lattice) complete_lattice\n  by standard (simp_all add: less_eq_prod_def Inf_prod_def Sup_prod_def\n    INF_lower SUP_upper le_INF_iff SUP_le_iff bot_prod_def top_prod_def)\n\nlemma fst_Inf: \"fst (Inf A) = (INF x\\<in>A. fst x)\"\n  by (simp add: Inf_prod_def)\n\nlemma fst_INF: \"fst (INF x\\<in>A. f x) = (INF x\\<in>A. fst (f x))\"\n  by (simp add: fst_Inf image_image)\n\nlemma fst_Sup: \"fst (Sup A) = (SUP x\\<in>A. fst x)\"\n  by (simp add: Sup_prod_def)\n\nlemma fst_SUP: \"fst (SUP x\\<in>A. f x) = (SUP x\\<in>A. fst (f x))\"\n  by (simp add: fst_Sup image_image)\n\nlemma snd_Inf: \"snd (Inf A) = (INF x\\<in>A. snd x)\"\n  by (simp add: Inf_prod_def)\n\nlemma snd_INF: \"snd (INF x\\<in>A. f x) = (INF x\\<in>A. snd (f x))\"\n  by (simp add: snd_Inf image_image)\n\nlemma snd_Sup: \"snd (Sup A) = (SUP x\\<in>A. snd x)\"\n  by (simp add: Sup_prod_def)\n\nlemma snd_SUP: \"snd (SUP x\\<in>A. f x) = (SUP x\\<in>A. snd (f x))\"\n  by (simp add: snd_Sup image_image)\n\nlemma INF_Pair: \"(INF x\\<in>A. (f x, g x)) = (INF x\\<in>A. f x, INF x\\<in>A. g x)\"\n  by (simp add: Inf_prod_def image_image)\n\nlemma SUP_Pair: \"(SUP x\\<in>A. (f x, g x)) = (SUP x\\<in>A. f x, SUP x\\<in>A. g x)\"\n  by (simp add: Sup_prod_def image_image)\n\n\ntext \\<open>Alternative formulations for set infima and suprema over the product\nof two complete lattices:\\<close>\n\nlemma INF_prod_alt_def: \\<^marker>\\<open>contributor \\<open>Alessandro Coglio\\<close>\\<close>\n  \"Inf (f ` A) = (Inf ((fst \\<circ> f) ` A), Inf ((snd \\<circ> f) ` A))\"\n  by (simp add: Inf_prod_def image_image)\n\nlemma SUP_prod_alt_def: \\<^marker>\\<open>contributor \\<open>Alessandro Coglio\\<close>\\<close>\n  \"Sup (f ` A) = (Sup ((fst \\<circ> f) ` A), Sup((snd \\<circ> f) ` A))\"\n  by (simp add: Sup_prod_def image_image)\n\n\nsubsection \\<open>Complete distributive lattices\\<close>\n\ninstance prod :: (complete_distrib_lattice, complete_distrib_lattice) complete_distrib_lattice \\<^marker>\\<open>contributor \\<open>Alessandro Coglio\\<close>\\<close>\nproof\n  fix A::\"('a\\<times>'b) set set\"\n  show \"Inf (Sup ` A) \\<le> Sup (Inf ` {f ` A |f. \\<forall>Y\\<in>A. f Y \\<in> Y})\"\n    by (simp add: Inf_prod_def Sup_prod_def INF_SUP_set image_image)\nqed\n\nsubsection \\<open>Bekic's Theorem\\<close>\ntext \\<open>\n  Simultaneous fixed points over pairs can be written in terms of separate fixed points.\n  Transliterated from HOLCF.Fix by Peter Gammie\n\\<close>\n\nlemma lfp_prod:\n  fixes F :: \"'a::complete_lattice \\<times> 'b::complete_lattice \\<Rightarrow> 'a \\<times> 'b\"\n  assumes \"mono F\"\n  shows \"lfp F = (lfp (\\<lambda>x. fst (F (x, lfp (\\<lambda>y. snd (F (x, y)))))),\n                 (lfp (\\<lambda>y. snd (F (lfp (\\<lambda>x. fst (F (x, lfp (\\<lambda>y. snd (F (x, y)))))), y)))))\"\n  (is \"lfp F = (?x, ?y)\")\nproof(rule lfp_eqI[OF assms])\n  have 1: \"fst (F (?x, ?y)) = ?x\"\n    by (rule trans [symmetric, OF lfp_unfold])\n       (blast intro!: monoI monoD[OF assms(1)] fst_mono snd_mono Pair_mono lfp_mono)+\n  have 2: \"snd (F (?x, ?y)) = ?y\"\n    by (rule trans [symmetric, OF lfp_unfold])\n       (blast intro!: monoI monoD[OF assms(1)] fst_mono snd_mono Pair_mono lfp_mono)+\n  from 1 2 show \"F (?x, ?y) = (?x, ?y)\" by (simp add: prod_eq_iff)\nnext\n  fix z assume F_z: \"F z = z\"\n  obtain x y where z: \"z = (x, y)\" by (rule prod.exhaust)\n  from F_z z have F_x: \"fst (F (x, y)) = x\" by simp\n  from F_z z have F_y: \"snd (F (x, y)) = y\" by simp\n  let ?y1 = \"lfp (\\<lambda>y. snd (F (x, y)))\"\n  have \"?y1 \\<le> y\" by (rule lfp_lowerbound, simp add: F_y)\n  hence \"fst (F (x, ?y1)) \\<le> fst (F (x, y))\"\n    by (simp add: assms fst_mono monoD)\n  hence \"fst (F (x, ?y1)) \\<le> x\" using F_x by simp\n  hence 1: \"?x \\<le> x\" by (simp add: lfp_lowerbound)\n  hence \"snd (F (?x, y)) \\<le> snd (F (x, y))\"\n    by (simp add: assms snd_mono monoD)\n  hence \"snd (F (?x, y)) \\<le> y\" using F_y by simp\n  hence 2: \"?y \\<le> y\" by (simp add: lfp_lowerbound)\n  show \"(?x, ?y) \\<le> z\" using z 1 2 by simp\nqed\n\nlemma gfp_prod:\n  fixes F :: \"'a::complete_lattice \\<times> 'b::complete_lattice \\<Rightarrow> 'a \\<times> 'b\"\n  assumes \"mono F\"\n  shows \"gfp F = (gfp (\\<lambda>x. fst (F (x, gfp (\\<lambda>y. snd (F (x, y)))))),\n                 (gfp (\\<lambda>y. snd (F (gfp (\\<lambda>x. fst (F (x, gfp (\\<lambda>y. snd (F (x, y)))))), y)))))\"\n  (is \"gfp F = (?x, ?y)\")\nproof(rule gfp_eqI[OF assms])\n  have 1: \"fst (F (?x, ?y)) = ?x\"\n    by (rule trans [symmetric, OF gfp_unfold])\n       (blast intro!: monoI monoD[OF assms(1)] fst_mono snd_mono Pair_mono gfp_mono)+\n  have 2: \"snd (F (?x, ?y)) = ?y\"\n    by (rule trans [symmetric, OF gfp_unfold])\n       (blast intro!: monoI monoD[OF assms(1)] fst_mono snd_mono Pair_mono gfp_mono)+\n  from 1 2 show \"F (?x, ?y) = (?x, ?y)\" by (simp add: prod_eq_iff)\nnext\n  fix z assume F_z: \"F z = z\"\n  obtain x y where z: \"z = (x, y)\" by (rule prod.exhaust)\n  from F_z z have F_x: \"fst (F (x, y)) = x\" by simp\n  from F_z z have F_y: \"snd (F (x, y)) = y\" by simp\n  let ?y1 = \"gfp (\\<lambda>y. snd (F (x, y)))\"\n  have \"y \\<le> ?y1\" by (rule gfp_upperbound, simp add: F_y)\n  hence \"fst (F (x, y)) \\<le> fst (F (x, ?y1))\"\n    by (simp add: assms fst_mono monoD)\n  hence \"x \\<le> fst (F (x, ?y1))\" using F_x by simp\n  hence 1: \"x \\<le> ?x\" by (simp add: gfp_upperbound)\n  hence \"snd (F (x, y)) \\<le> snd (F (?x, y))\"\n    by (simp add: assms snd_mono monoD)\n  hence \"y \\<le> snd (F (?x, y))\" using F_y by simp\n  hence 2: \"y \\<le> ?y\" by (simp add: gfp_upperbound)\n  show \"z \\<le> (?x, ?y)\" using z 1 2 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/Library/Product_Order.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473813156295, "lm_q2_score": 0.8539127566694178, "lm_q1q2_score": 0.744908557152577}}
{"text": "theory Roy_Floyd_Warshall\nimports Main\nbegin\n\nsection \\<open>Transitive closure algorithm\\<close>\n\ntext \\<open>\n  The Roy-Floyd-Warshall algorithm takes a finite relation as input and\n  produces its transitive closure as output. It iterates over all elements of\n  the field of the relation and maintains a cumulative approximation of the\n  result: step \\<open>0\\<close> starts with the original relation, and step \\<open>Suc n\\<close>\n  connects all paths over the intermediate element \\<open>n\\<close>. The final\n  approximation coincides with the full transitive closure.\n\n  This algorithm is often named after ``Floyd'', ``Warshall'', or\n  ``Floyd-Warshall'', but the earliest known description is due to B. Roy\n  @{cite \"Roy:1959\"}.\n\n  \\<^medskip>\n  Subsequently we use a direct mathematical model of the relation, bypassing\n  matrices and arrays that are usually seen in the literature. This is more\n  efficient for sparse relations: only the adjacency for immediate\n  predecessors and successors needs to be maintained, not the square of all\n  possible combinations. Moreover we do not have to worry about mutable data\n  structures in a multi-threaded environment. See also the graph\n  implementation in the Isabelle sources @{file\n  \\<open>$ISABELLE_HOME/src/Pure/General/graph.ML\\<close>} and @{file\n  \\<open>$ISABELLE_HOME/src/Pure/General/graph.scala\\<close>}.\n\\<close>\n\ntype_synonym relation = \"(nat \\<times> nat) set\"\n\nfun steps :: \"relation \\<Rightarrow> nat \\<Rightarrow> relation\"\nwhere\n  \"steps rel 0 = rel\"\n| \"steps rel (Suc n) =\n    steps rel n \\<union> {(x, y). (x, n) \\<in> steps rel n \\<and> (n, y) \\<in> steps rel n}\"\n\n\ntext \\<open>Implementation view on the relation:\\<close>\n\ndefinition preds :: \"relation \\<Rightarrow> nat \\<Rightarrow> nat set\"\n  where \"preds rel y = {x. (x, y) \\<in> rel}\"\n\ndefinition succs :: \"relation \\<Rightarrow> nat \\<Rightarrow> nat set\"\n  where \"succs rel x = {y. (x, y) \\<in> rel}\"\n\nlemma\n  \"steps rel (Suc n) =\n    steps rel n \\<union> {(x, y). x \\<in> preds (steps rel n) n \\<and> y \\<in> succs (steps rel n) n}\"\n  by (simp add: preds_def succs_def)\n\ntext \\<open>\n  The main function requires an upper bound for the iteration, which is left\n  unspecified here (via Hilbert's choice).\n\\<close>\n\ndefinition is_bound :: \"relation \\<Rightarrow> nat \\<Rightarrow> bool\"\n  where \"is_bound rel n \\<longleftrightarrow> (\\<forall>m \\<in> Field rel. m < n)\"\n\ndefinition \"transitive_closure rel = steps rel (SOME n. is_bound rel n)\"\n\n\nsection \\<open>Correctness proof\\<close>\n\nsubsection \\<open>Miscellaneous lemmas\\<close>\n\nlemma finite_bound:\n  assumes \"finite rel\"\n  shows \"\\<exists>n. is_bound rel n\"\n  using assms\nproof induct\n  case empty\n  then show ?case by (simp add: is_bound_def)\nnext\n  case (insert p rel)\n  then obtain n where n: \"\\<forall>m \\<in> Field rel. m < n\"\n    unfolding is_bound_def by blast\n  obtain x y where \"p = (x, y)\" by (cases p)\n  then have \"\\<forall>m \\<in> Field (insert p rel). m < max (Suc x) (max (Suc y) n)\"\n    using n by auto\n  then show ?case\n    unfolding is_bound_def by blast\nqed\n\nlemma steps_Suc: \"(x, y) \\<in> steps rel (Suc n) \\<longleftrightarrow>\n  (x, y) \\<in> steps rel n \\<or> (x, n) \\<in> steps rel n \\<and> (n, y) \\<in> steps rel n\"\n  by auto\n\nlemma steps_cases:\n  assumes \"(x, y) \\<in> steps rel (Suc n)\"\n  obtains (copy) \"(x, y) \\<in> steps rel n\"\n    | (step) \"(x, n) \\<in> steps rel n\" and \"(n, y) \\<in> steps rel n\"\n  using assms by auto\n\nlemma steps_rel: \"(x, y) \\<in> rel \\<Longrightarrow> (x, y) \\<in> steps rel n\"\n  by (induct n) auto\n\n\nsubsection \\<open>Bounded closure\\<close>\n\ntext \\<open>\n  The bounded closure connects all transitive paths over elements below a\n  given bound. For an upper bound of the relation, this coincides with the\n  full transitive closure.\n\\<close>\n\ninductive_set Clos :: \"relation \\<Rightarrow> nat \\<Rightarrow> relation\"\n  for rel :: relation and n :: nat\nwhere\n  base: \"(x, y) \\<in> Clos rel n\" if \"(x, y) \\<in> rel\"\n| step: \"(x, y) \\<in> Clos rel n\" if \"(x, z) \\<in> Clos rel n\" and \"(z, y) \\<in> Clos rel n\" and \"z < n\"\n\ntheorem Clos_closure:\n  assumes \"is_bound rel n\"\n  shows \"(x, y) \\<in> Clos rel n \\<longleftrightarrow> (x, y) \\<in> rel\\<^sup>+\"\nproof\n  show \"(x, y) \\<in> rel\\<^sup>+\" if \"(x, y) \\<in> Clos rel n\"\n    using that by induct simp_all\n  show \"(x, y) \\<in> Clos rel n\" if \"(x, y) \\<in> rel\\<^sup>+\"\n    using that\n  proof (induct rule: trancl_induct)\n    case (base y)\n    then show ?case by (rule Clos.base)\n  next\n    case (step y z)\n    from \\<open>(y, z) \\<in> rel\\<close> have 1: \"(y, z) \\<in> Clos rel n\" by (rule base)\n    from \\<open>(y, z) \\<in> rel\\<close> and \\<open>is_bound rel n\\<close> have 2: \"y < n\"\n      unfolding is_bound_def Field_def by blast\n    from step(3) 1 2 show ?case by (rule Clos.step)\n  qed\nqed\n\nlemma Clos_Suc:\n  assumes \"(x, y) \\<in> Clos rel n\"\n  shows \"(x, y) \\<in> Clos rel (Suc n)\"\n  using assms by induct (auto intro: Clos.intros)\n\ntext \\<open>\n  In each step of the algorithm the approximated relation is exactly the\n  bounded closure.\n\\<close>\n\ntheorem steps_Clos_equiv: \"(x, y) \\<in> steps rel n \\<longleftrightarrow> (x, y) \\<in> Clos rel n\"\nproof (induct n arbitrary: x y)\n  case 0\n  show ?case\n  proof\n    show \"(x, y) \\<in> Clos rel 0\" if \"(x, y) \\<in> steps rel 0\"\n    proof -\n      from that have \"(x, y) \\<in> rel\" by simp\n      then show ?thesis by (rule Clos.base)\n    qed\n    show \"(x, y) \\<in> steps rel 0\" if \"(x, y) \\<in> Clos rel 0\"\n      using that by cases simp_all\n  qed\nnext\n  case (Suc n)\n  show ?case\n  proof\n    show \"(x, y) \\<in> Clos rel (Suc n)\" if \"(x, y) \\<in> steps rel (Suc n)\"\n      using that\n    proof (cases rule: steps_cases)\n      case copy\n      with Suc(1) have \"(x, y) \\<in> Clos rel n\" ..\n      then show ?thesis by (rule Clos_Suc)\n    next\n      case step\n      with Suc have \"(x, n) \\<in> Clos rel n\" and \"(n, y) \\<in> Clos rel n\"\n        by simp_all\n      then have \"(x, n) \\<in> Clos rel (Suc n)\" and \"(n, y) \\<in> Clos rel (Suc n)\"\n        by (simp_all add: Clos_Suc)\n      then show ?thesis by (rule Clos.step) simp\n    qed\n    show \"(x, y) \\<in> steps rel (Suc n)\" if \"(x, y) \\<in> Clos rel (Suc n)\"\n      using that\n    proof induct\n      case (base x y)\n      then show ?case by (simp add: steps_rel)\n    next\n      case (step x z y)\n      with Suc show ?case\n        by (auto simp add: steps_Suc less_Suc_eq intro: Clos.step)\n    qed\n  qed\nqed\n\n\nsubsection \\<open>Main theorem\\<close>\n\ntext \\<open>\n  The main theorem follows immediately from the key observations above. Note\n  that the assumption of finiteness gives a bound for the iteration, although\n  the details are left unspecified. A concrete implementation could choose the\n  the maximum element + 1, or iterate directly over the data structures for\n  the @{term preds} and @{term succs} implementation.\n\\<close>\n\ntheorem transitive_closure_correctness:\n  assumes \"finite rel\"\n  shows \"transitive_closure rel = rel\\<^sup>+\"\nproof -\n  let ?N = \"SOME n. is_bound rel n\"\n  have is_bound: \"is_bound rel ?N\"\n    by (rule someI_ex) (rule finite_bound [OF \\<open>finite rel\\<close>])\n  have \"(x, y) \\<in> steps rel ?N \\<longleftrightarrow> (x, y) \\<in> rel\\<^sup>+\" for x y\n  proof -\n    have \"(x, y) \\<in> steps rel ?N \\<longleftrightarrow> (x, y) \\<in> Clos rel ?N\"\n      by (rule steps_Clos_equiv)\n    also have \"\\<dots> \\<longleftrightarrow> (x, y) \\<in> rel\\<^sup>+\"\n      using is_bound by (rule Clos_closure)\n    finally show ?thesis .\n  qed\n  then show ?thesis unfolding transitive_closure_def by auto\nqed\n\n\nsection \\<open>Alternative formulation\\<close>\n\ntext \\<open>\n  The core of the algorithm may be expressed more declaratively as follows,\n  using an inductive definition to imitate a logic-program. This is equivalent\n  to the function specification @{term steps} from above.\n\\<close>\n\ninductive Steps :: \"relation \\<Rightarrow> nat \\<Rightarrow> nat \\<times> nat \\<Rightarrow> bool\"\n  for rel :: relation\nwhere\n  base: \"Steps rel 0 (x, y)\" if \"(x, y) \\<in> rel\"\n| copy: \"Steps rel (Suc n) (x, y)\" if \"Steps rel n (x, y)\"\n| step: \"Steps rel (Suc n) (x, y)\" if \"Steps rel n (x, n)\" and \"Steps rel n (n, y)\"\n\nlemma steps_equiv: \"(x, y) \\<in> steps rel n \\<longleftrightarrow> Steps rel n (x, y)\"\nproof\n  show \"Steps rel n (x, y)\" if \"(x, y) \\<in> steps rel n\"\n    using that\n  proof (induct n arbitrary: x y)\n    case 0\n    then have \"(x, y) \\<in> rel\" by simp\n    then show ?case by (rule base)\n  next\n    case (Suc n)\n    from Suc(2) show ?case\n    proof (cases rule: steps_cases)\n      case copy\n      with Suc(1) have \"Steps rel n (x, y)\" .\n      then show ?thesis by (rule Steps.copy)\n    next\n      case step\n      with Suc(1) have \"Steps rel n (x, n)\" and \"Steps rel n (n, y)\"\n        by simp_all\n      then show ?thesis by (rule Steps.step)\n    qed\n  qed\n  show \"(x, y) \\<in> steps rel n\" if \"Steps rel n (x, y)\"\n    using that by induct simp_all\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/Roy_Floyd_Warshall/Roy_Floyd_Warshall.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8539127455162773, "lm_q2_score": 0.8723473862936942, "lm_q1q2_score": 0.7449085516739969}}
{"text": "header {* Directed Graphs *}\n(* Author: Peter Lammich *)\ntheory Digraph\n  imports \n  \"CAVA_Base/CAVA_Base\"\n  \"Words\"\nbegin\n\nsubsection \"Directed Graphs\"\ntext {* Directed graphs are modeled as a relation on nodes *}\ntype_synonym 'v digraph = \"('v\\<times>'v) set\"\n\nlocale digraph = fixes E :: \"'v digraph\"\n\nsubsubsection {* Paths *}\ntext {* Path are modeled as list of nodes, the last node of a path is not included\n  into the list. This formalization allows for nice concatenation and splitting\n  of paths. *}\ninductive path :: \"'v digraph \\<Rightarrow> 'v \\<Rightarrow> 'v list \\<Rightarrow> 'v \\<Rightarrow> bool\" for E where\n  path0: \"path E u [] u\"\n| path_prepend: \"\\<lbrakk> (u,v)\\<in>E; path E v l w \\<rbrakk> \\<Longrightarrow> path E u (u#l) w\"\n\nlemma path1: \"(u,v)\\<in>E \\<Longrightarrow> path E u [u] v\"\n  by (auto intro: path.intros)\n\nlemma path_empty_conv[simp]:\n  \"path E u [] v \\<longleftrightarrow> u=v\"\n  by (auto intro: path0 elim: path.cases)\n\ninductive_cases path_uncons: \"path E u (u'#l) w\"\ninductive_simps path_cons_conv: \"path E u (u'#l) w\"\n\nlemma path_no_edges[simp]: \"path {} u p v \\<longleftrightarrow> (u=v \\<and> p=[])\"\n  by (cases p) (auto simp: path_cons_conv)\n\nlemma path_conc: \n  assumes P1: \"path E u la v\" \n  assumes P2: \"path E v lb w\"\n  shows \"path E u (la@lb) w\"\n  using P1 P2 apply induct \n  by (auto intro: path.intros)\n  \nlemma path_append:\n  \"\\<lbrakk> path E u l v; (v,w)\\<in>E \\<rbrakk> \\<Longrightarrow> path E u (l@[v]) w\"\n  using path_conc[OF _ path1] .\n\nlemma path_unconc:\n  assumes \"path E u (la@lb) w\"\n  obtains v where \"path E u la v\" and \"path E v lb w\"\n  using assms \n  thm path.induct\n  apply (induct u \"la@lb\" w arbitrary: la lb rule: path.induct)\n  apply (auto intro: path.intros elim!: list_Cons_eq_append_cases)\n  done\n\nlemma path_conc_conv: \n  \"path E u (la@lb) w \\<longleftrightarrow> (\\<exists>v. path E u la v \\<and> path E v lb w)\"\n  by (auto intro: path_conc elim: path_unconc)\n\nlemma (in -) path_append_conv: \"path E u (p@[v]) w \\<longleftrightarrow> (path E u p v \\<and> (v,w)\\<in>E)\"\n  by (simp add: path_cons_conv path_conc_conv)\n\nlemmas path_simps = path_empty_conv path_cons_conv path_conc_conv\n\n\nlemmas path_trans[trans] = path_prepend path_conc path_append\nlemma path_from_edges: \"\\<lbrakk>(u,v)\\<in>E; (v,w)\\<in>E\\<rbrakk> \\<Longrightarrow> path E u [u] v\" \n  by (auto simp: path_simps)\n\n\nlemma path_edge_cases[case_names no_use split]: \n  assumes \"path (insert (u,v) E) w p x\"\n  obtains \n    \"path E w p x\" \n  | p1 p2 where \"path E w p1 u\" \"path (insert (u,v) E) v p2 x\"\n  using assms\n  apply induction\n  apply simp\n  apply (clarsimp)\n  apply (metis path_simps path_cons_conv)\n  done\n\nlemma path_edge_rev_cases[case_names no_use split]: \n  assumes \"path (insert (u,v) E) w p x\"\n  obtains \n    \"path E w p x\" \n  | p1 p2 where \"path (insert (u,v) E) w p1 u\" \"path E v p2 x\"\n  using assms\n  apply (induction p arbitrary: x rule: rev_induct)\n  apply simp\n  apply (clarsimp simp: path_cons_conv path_conc_conv)\n  apply (metis path_simps path_append_conv)\n  done\n\n\nlemma path_mono: \n  assumes S: \"E\\<subseteq>E'\" \n  assumes P: \"path E u p v\" \n  shows \"path E' u p v\"\n  using P\n  apply induction\n  apply simp\n  using S\n  apply (auto simp: path_cons_conv)\n  done\n\nlemma path_is_rtrancl: \n  assumes \"path E u l v\"\n  shows \"(u,v)\\<in>E\\<^sup>*\"\n  using assms \n  by induct auto\n\nlemma rtrancl_is_path:\n  assumes \"(u,v)\\<in>E\\<^sup>*\"\n  obtains l where \"path E u l v\"\n  using assms \n  by induct (auto intro: path0 path_append)\n\nlemma path_is_trancl: \n  assumes \"path E u l v\"\n  and \"l\\<noteq>[]\"\n  shows \"(u,v)\\<in>E\\<^sup>+\"\n  using assms \n  apply induct\n  apply auto []\n  apply (case_tac l)\n  apply auto\n  done\n\nlemma trancl_is_path:\n  assumes \"(u,v)\\<in>E\\<^sup>+\"\n  obtains l where \"l\\<noteq>[]\" and \"path E u l v\"\n  using assms \n  by induct (auto intro: path0 path_append)\n\nlemma path_nth_conv: \"path E u p v \\<longleftrightarrow> (let p'=p@[v] in\n  u=p'!0 \\<and>\n  (\\<forall>i<length p' - 1. (p'!i,p'!Suc i)\\<in>E))\"\n  apply (induct p arbitrary: v rule: rev_induct)\n  apply (auto simp: path_conc_conv path_cons_conv nth_append)\n  done\n\nlemma path_mapI:\n  assumes \"path E u p v\"\n  shows \"path (pairself f ` E) (f u) (map f p) (f v)\"\n  using assms\n  apply induction\n  apply (simp)\n  apply (force simp: path_cons_conv)\n  done\n\nlemma path_restrict: \n  assumes \"path E u p v\" \n  shows \"path (E \\<inter> set p \\<times> insert v (set (tl p))) u p v\"\n  using assms\nproof induction\n  print_cases\n  case (path_prepend u v p w)\n  from path_prepend.IH have \"path (E \\<inter> set (u#p) \\<times> insert w (set p)) v p w\"\n    apply (rule path_mono[rotated])\n    by (cases p) auto\n  thus ?case using `(u,v)\\<in>E`\n    by (cases p) (auto simp add: path_cons_conv)\nqed auto\n\nlemma path_restrict_closed:\n  assumes CLOSED: \"E``D \\<subseteq> D\"\n  assumes I: \"v\\<in>D\" and P: \"path E v p v'\"\n  shows \"path (E\\<inter>D\\<times>D) v p v'\"\n  using P CLOSED I\n  by induction (auto simp: path_cons_conv)\n\n\nlemma path_set_induct:\n  assumes \"path E u p v\" and \"u\\<in>I\" and \"E``I \\<subseteq> I\"\n  shows \"set p \\<subseteq> I\"\n  using assms\n  by (induction rule: path.induct) auto\n\nlemma path_nodes_reachable: \"path E u p v \\<Longrightarrow> insert v (set p) \\<subseteq> E\\<^sup>*``{u}\"\n  apply (auto simp: in_set_conv_decomp path_cons_conv path_conc_conv)\n  apply (auto dest!: path_is_rtrancl)\n  done\n\nlemma path_nodes_edges: \"path E u p v \\<Longrightarrow> set p \\<subseteq> fst`E\"\n  by (induction rule: path.induct) auto\n\nlemma path_tl_nodes_edges: \n  assumes \"path E u p v\"\n  shows \"set (tl p) \\<subseteq> fst`E \\<inter> snd`E\"\nproof -\n  from path_nodes_edges[OF assms] have \"set (tl p) \\<subseteq> fst`E\"\n    by (cases p) auto\n\n  moreover have \"set (tl p) \\<subseteq> snd`E\"\n    using assms\n    apply (cases)\n    apply simp\n    apply simp\n    apply (erule path_set_induct[where I = \"snd`E\"])\n    apply auto\n    done\n  ultimately show ?thesis\n    by auto\nqed\n\nlemma path_loop_shift: \n  assumes P: \"path E u p u\"\n  assumes S: \"v\\<in>set p\"\n  obtains p' where \"set p' = set p\" \"path E v p' v\"\nproof -\n  from S obtain p1 p2 where [simp]: \"p = p1@v#p2\" by (auto simp: in_set_conv_decomp)\n  from P obtain v' where A: \"path E u p1 v\" \"(v, v') \\<in> E\" \"path E v' p2 u\" \n    by (auto simp: path_simps)\n  hence \"path E v (v#p2@p1) v\" by (auto simp: path_simps)\n  thus ?thesis using that[of \"v#p2@p1\"] by auto\nqed\n\n\n\nsubsubsection {* Infinite Paths *}\ndefinition ipath :: \"'q digraph \\<Rightarrow> 'q word \\<Rightarrow> bool\"\n  -- \"Predicate for an infinite path in a digraph\"\n  where \"ipath E r \\<equiv> \\<forall>i. (r i, r (Suc i))\\<in>E\"\n\n\nlemma ipath_conc_conv: \n  \"ipath E (u \\<frown> v) \\<longleftrightarrow> (\\<exists>a. path E a u (v 0) \\<and> ipath E v)\"\n  apply (auto simp: conc_def ipath_def path_nth_conv nth_append)\n  apply (metis add_Suc_right diff_add_inverse not_add_less1)\n  by (metis Suc_diff_Suc diff_Suc_Suc not_less_eq)\n\nlemma ipath_iter_conv:\n  assumes \"p\\<noteq>[]\"\n  shows \"ipath E (p\\<^sup>\\<omega>) \\<longleftrightarrow> (path E (hd p) p (hd p))\"\nproof (cases p)\n  case Nil thus ?thesis using assms by simp\nnext\n  case (Cons u p') hence PLEN: \"length p > 0\" by simp\n  show ?thesis proof \n    assume \"ipath E (iter (p))\"\n    hence \"\\<forall>i. (iter (p) i, iter (p) (Suc i)) \\<in> E\"\n      unfolding ipath_def by simp\n    hence \"(\\<forall>i<length p. (p!i,(p@[hd p])!Suc i)\\<in>E)\" \n      apply (simp add: assms)\n      apply safe\n      apply (drule_tac x=i in spec)\n      apply simp\n      apply (case_tac \"Suc i = length p\")\n      apply (simp add: Cons)\n      apply (simp add: nth_append)\n      done\n    thus \"path E (hd p) p (hd p)\"\n      by (auto simp: path_nth_conv Cons nth_append nth_Cons')\n  next\n    assume \"path E (hd p) p (hd p)\"\n    thus \"ipath E (iter p)\"\n      apply (auto simp: path_nth_conv ipath_def assms Let_def)\n      apply (drule_tac x=\"i mod length p\" in spec)\n      apply (auto simp: nth_append assms split: split_if_asm)\n      apply (metis less_not_refl mod_Suc)\n      by (metis PLEN diff_self_eq_0 mod_Suc nth_Cons_0 \n        semiring_numeral_div_class.pos_mod_bound)\n  qed\nqed\n\nlemma ipath_to_rtrancl:\n  assumes R: \"ipath E r\"\n  assumes I: \"i1\\<le>i2\"\n  shows \"(r i1,r i2)\\<in>E\\<^sup>*\"\n  using I\nproof (induction i2)\n  case (Suc i2)\n  show ?case proof (cases \"i1=Suc i2\")\n    assume \"i1\\<noteq>Suc i2\"\n    with Suc have \"(r i1,r i2)\\<in>E\\<^sup>*\" by auto\n    also from R have \"(r i2,r (Suc i2))\\<in>E\" unfolding ipath_def by auto\n    finally show ?thesis .\n  qed simp\nqed simp\n    \nlemma ipath_to_trancl:\n  assumes R: \"ipath E r\"\n  assumes I: \"i1<i2\"\n  shows \"(r i1,r i2)\\<in>E\\<^sup>+\"\nproof -\n  from R have \"(r i1,r (Suc i1))\\<in>E\"\n    by (auto simp: ipath_def)\n  also have \"(r (Suc i1),r i2)\\<in>E\\<^sup>*\"\n    using ipath_to_rtrancl[OF R,of \"Suc i1\" i2] I by auto\n  finally (rtrancl_into_trancl2) show ?thesis .\nqed\n\nlemma run_limit_two_connectedI:\n  assumes A: \"ipath E r\" \n  assumes B: \"a \\<in> limit r\" \"b\\<in>limit r\"\n  shows \"(a,b)\\<in>E\\<^sup>+\"\nproof -\n  from B have \"{a,b} \\<subseteq> limit r\" by simp\n  with A show ?thesis\n    by (metis ipath_to_trancl two_in_limit_iff)\nqed\n\n\nlemma ipath_subpath:\n  assumes P: \"ipath E r\"\n  assumes LE: \"l\\<le>u\"\n  shows \"path E (r l) (map r [l..<u]) (r u)\"\n  using LE\nproof (induction \"u-l\" arbitrary: u l)\n  case (Suc n)\n  note IH=Suc.hyps(1)\n  from `Suc n = u-l` `l\\<le>u` obtain u' where [simp]: \"u=Suc u'\" \n    and A: \"n=u'-l\" \"l \\<le> u'\" \n    by (cases u) auto\n    \n  note IH[OF A]\n  also from P have \"(r u',r u)\\<in>E\"\n    by (auto simp: ipath_def)\n  finally show ?case using `l \\<le> u'` by (simp add: upt_Suc_append)\nqed auto  \n\nlemma ipath_restrict_eq: \"ipath (E \\<inter> (E\\<^sup>*``{r 0} \\<times> E\\<^sup>*``{r 0})) r \\<longleftrightarrow> ipath E r\"\n  unfolding ipath_def\n  by (auto simp: relpow_fun_conv rtrancl_power)\nlemma ipath_restrict: \"ipath E r \\<Longrightarrow> ipath (E \\<inter> (E\\<^sup>*``{r 0} \\<times> E\\<^sup>*``{r 0})) r\"\n  by (simp add: ipath_restrict_eq)\n\n\nlemma ipathI[intro?]: \"\\<lbrakk>\\<And>i. (r i, r (Suc i)) \\<in> E\\<rbrakk> \\<Longrightarrow> ipath E r\"\n  unfolding ipath_def by auto\n\nlemma ipathD: \"ipath E r \\<Longrightarrow> (r i, r (Suc i)) \\<in> E\"\n  unfolding ipath_def by auto\n\nlemma ipath_in_Domain: \"ipath E r \\<Longrightarrow> r i \\<in> Domain E\"\n  unfolding ipath_def by auto\n\nlemma ipath_in_Range: \"\\<lbrakk>ipath E r; i\\<noteq>0\\<rbrakk> \\<Longrightarrow> r i \\<in> Range E\"\n  unfolding ipath_def by (cases i) auto\n\nlemma ipath_suffix: \"ipath E r \\<Longrightarrow> ipath E (suffix i r)\"\n  unfolding suffix_def ipath_def by auto\n\n\n\nsubsubsection {* Strongly Connected Components *}\n\ntext {* A strongly connected component is a maximal mutually connected set \n  of nodes *}\ndefinition is_scc :: \"'q digraph \\<Rightarrow> 'q set \\<Rightarrow> bool\"\n  where \"is_scc E U \\<longleftrightarrow> U\\<times>U\\<subseteq>E\\<^sup>* \\<and> (\\<forall>V. V\\<supset>U \\<longrightarrow> \\<not> (V\\<times>V\\<subseteq>E\\<^sup>*))\"\n\nlemma scc_non_empty[simp]: \"\\<not>is_scc E {}\" unfolding is_scc_def by auto\n\nlemma scc_non_empty'[simp]: \"is_scc E U \\<Longrightarrow> U\\<noteq>{}\" unfolding is_scc_def by auto\n\nlemma is_scc_closed: \n  assumes SCC: \"is_scc E U\"\n  assumes MEM: \"x\\<in>U\"\n  assumes P: \"(x,y)\\<in>E\\<^sup>*\" \"(y,x)\\<in>E\\<^sup>*\"\n  shows \"y\\<in>U\"\nproof -\n  from SCC MEM P have \"insert y U \\<times> insert y U \\<subseteq> E\\<^sup>*\"\n    unfolding is_scc_def\n    apply clarsimp\n    apply rule\n    apply clarsimp_all\n    apply (erule disjE1)\n    apply clarsimp\n    apply (metis in_mono mem_Sigma_iff rtrancl_trans)\n    apply auto []\n    apply (erule disjE1)\n    apply clarsimp\n    apply (metis in_mono mem_Sigma_iff rtrancl_trans)\n    apply auto []\n    done\n  with SCC show ?thesis unfolding is_scc_def by blast\nqed\n\nlemma is_scc_connected:\n  assumes SCC: \"is_scc E U\"\n  assumes MEM: \"x\\<in>U\" \"y\\<in>U\"\n  shows \"(x,y)\\<in>E\\<^sup>*\"\n  using assms unfolding is_scc_def by auto\n\ntext {* In the following, we play around with alternative characterizations, and\n  prove them all equivalent .*}\n\ntext {* A common characterization is to define an equivalence relation \n  ,,mutually connected'' on nodes, and characterize the SCCs as its \n  equivalence classes: *}\n\ndefinition mconn :: \"('a\\<times>'a) set \\<Rightarrow> ('a \\<times> 'a) set\"\n  -- \"Mutually connected relation on nodes\"\n  where \"mconn E = E\\<^sup>* \\<inter> (E\\<inverse>)\\<^sup>*\"\n\nlemma mconn_pointwise:\n   \"mconn E = {(u,v). (u,v)\\<in>E\\<^sup>* \\<and> (v,u)\\<in>E\\<^sup>*}\"\n  by (auto simp add: mconn_def rtrancl_converse)\n\ntext {* @{text \"mconn\"} is an equivalence relation: *}\nlemma mconn_refl[simp]: \"Id\\<subseteq>mconn E\"\n  by (auto simp add: mconn_def)\n\nlemma mconn_sym: \"mconn E = (mconn E)\\<inverse>\"\n  by (auto simp add: mconn_pointwise)\n\nlemma mconn_trans: \"mconn E O mconn E = mconn E\"\n  by (auto simp add: mconn_def)\n\nlemma is_scc_mconn_eqclasses: \"is_scc E U \\<longleftrightarrow> U \\<in> UNIV // mconn E\"\n  -- \"The strongly connected components are the equivalence classes of the \n    mutually-connected relation on nodes\"\nproof\n  assume A: \"is_scc E U\"\n  then obtain x where \"x\\<in>U\" unfolding is_scc_def by auto\n  hence \"U = mconn E `` {x}\" using A\n    unfolding mconn_pointwise is_scc_def\n    apply clarsimp\n    apply rule\n    apply auto []\n    apply clarsimp\n    by (metis A is_scc_closed)\n  thus \"U \\<in> UNIV // mconn E\"\n    by (auto simp: quotient_def)\nnext\n  assume \"U \\<in> UNIV // mconn E\"\n  thus \"is_scc E U\"\n    by (auto simp: is_scc_def mconn_pointwise quotient_def)\nqed\n\n(* For presentation in the paper *)\nlemma \"is_scc E U \\<longleftrightarrow> U \\<in> UNIV // (E\\<^sup>* \\<inter> (E\\<inverse>)\\<^sup>*)\"\n  unfolding is_scc_mconn_eqclasses mconn_def by simp\n\ntext {* We can also restrict the notion of \"reachability\" to nodes\n  inside the SCC\n  *}\n\nlemma find_outside_node:\n  assumes \"(u,v)\\<in>E\\<^sup>*\"\n  assumes \"(u,v)\\<notin>(E\\<inter>U\\<times>U)\\<^sup>*\"\n  assumes \"u\\<in>U\" \"v\\<in>U\"\n  shows \"\\<exists>u'. u'\\<notin>U \\<and> (u,u')\\<in>E\\<^sup>* \\<and> (u',v)\\<in>E\\<^sup>*\"\n  using assms\n  apply (induction)\n  apply auto []\n  apply clarsimp\n  by (metis IntI mem_Sigma_iff rtrancl.simps)\n\nlemma is_scc_restrict1:\n  assumes SCC: \"is_scc E U\"\n  shows \"U\\<times>U\\<subseteq>(E\\<inter>U\\<times>U)\\<^sup>*\"\n  using assms\n  unfolding is_scc_def\n  apply clarsimp\n  apply (rule ccontr)\n  apply (drule (2) find_outside_node[rotated])\n  apply auto []\n  by (metis is_scc_closed[OF SCC] mem_Sigma_iff rtrancl_trans subsetD)\n\nlemma is_scc_restrict2:\n  assumes SCC: \"is_scc E U\"\n  assumes \"V\\<supset>U\"\n  shows \"\\<not> (V\\<times>V\\<subseteq>(E\\<inter>V\\<times>V)\\<^sup>*)\"\n  using assms\n  unfolding is_scc_def\n  apply clarsimp\n  using rtrancl_mono[of \"E \\<inter> V \\<times> V\" \"E\"]\n  apply clarsimp\n  apply blast\n  done\n\nlemma is_scc_restrict3: \n  assumes SCC: \"is_scc E U\"\n  shows \"((E\\<^sup>*``((E\\<^sup>*``U) - U)) \\<inter> U = {})\"\n  apply auto\n  by (metis assms is_scc_closed is_scc_connected rtrancl_trans)\n  \nlemma is_scc_alt_restrict_path:\n  \"is_scc E U \\<longleftrightarrow> U\\<noteq>{} \\<and>\n    (U\\<times>U \\<subseteq> (E\\<inter>U\\<times>U)\\<^sup>*) \\<and> ((E\\<^sup>*``((E\\<^sup>*``U) - U)) \\<inter> U = {})\"\n  apply rule\n  apply (intro conjI)\n  apply simp\n  apply (blast dest: is_scc_restrict1)\n  apply (blast dest: is_scc_restrict3)\n  \n  unfolding is_scc_def\n  apply rule\n  apply clarsimp\n  apply (metis (full_types) Int_lower1 in_mono mem_Sigma_iff rtrancl_mono_mp)\n  apply blast\n  done\n\nlemma is_scc_pointwise:\n  \"is_scc E U \\<longleftrightarrow> \n    U\\<noteq>{}\n  \\<and> (\\<forall>u\\<in>U. \\<forall>v\\<in>U. (u,v)\\<in>(E\\<inter>U\\<times>U)\\<^sup>*) \n  \\<and> (\\<forall>u\\<in>U. \\<forall>v. (v\\<notin>U \\<and> (u,v)\\<in>E\\<^sup>*) \\<longrightarrow> (\\<forall>u'\\<in>U. (v,u')\\<notin>E\\<^sup>*))\"\n  -- \"Alternative, pointwise characterization\"\n  unfolding is_scc_alt_restrict_path\n  by blast  \n\n\nsubsection \"Finitely Reachable Graphs\"\ntext {* Finitely reachable graphs are directed graphs with an explicit set \n  of root nodes, such that only finitely many nodes are reachable from\n  the set of root nodes *}\n\nrecord 'v fr_graph_rec = \n  frg_V :: \"'v set\"\n  frg_E :: \"'v digraph\"  \n  frg_V0 :: \"'v set\"\n\nlocale fr_graph = \n  -- \"Directed graph with explicit set of root nodes, and \n      finitely many reachable nodes\"\n  fixes G :: \"('v,'more) fr_graph_rec_scheme\"\n  assumes finite_reachableE_V0[simp, intro!]: \"finite ((frg_E G)\\<^sup>*``frg_V0 G)\"\n  assumes V0_ss: \"frg_V0 G \\<subseteq> (frg_V G)\"\n  assumes E_ss: \"frg_E G \\<subseteq> (frg_V G)\\<times>(frg_V G)\"\nbegin\n  abbreviation \"V \\<equiv> frg_V G\"\n  abbreviation \"E \\<equiv> frg_E G\"\n  abbreviation \"V0 \\<equiv> frg_V0 G\"\n\n  lemma is_fr_graph: \"fr_graph G\" by unfold_locales\n\n  lemma finite_V0[simp, intro!]: \"finite V0\"\n    using finite_reachableE_V0\n    apply (rule finite_subset[rotated])\n    by auto\n\n  definition is_run\n    -- \"Infinite run, i.e., a rooted infinite path\"\n    where \"is_run r \\<equiv> r 0 \\<in> V0 \\<and> ipath E r\"\n  \n  lemma run_reachable: \"is_run r \\<Longrightarrow> r i \\<in> E\\<^sup>*``V0\"\n    unfolding is_run_def\n    using ipath_to_rtrancl[of \"frg_E G\" r 0 i]\n    by auto\n  \n  lemma \n    assumes \"is_run r\"\n    shows run_ipath: \"ipath E r\"\n    and run_V0: \"r 0 \\<in> V0\"\n    using assms unfolding is_run_def by auto\n\n\n  lemma is_run_finite: \"is_run r \\<Longrightarrow> finite (range r)\"\n    apply (rule finite_subset[OF _ finite_reachableE_V0])\n    using run_reachable\n    by auto\n\n  lemma run_V: \"is_run r \\<Longrightarrow> range r \\<subseteq> V\"\n    using run_ipath[THEN ipath_in_Domain] E_ss by auto\n\nend\n\nlocale fin_fr_graph = fr_graph G \n  for G :: \"('v,'more) fr_graph_rec_scheme\"\n+ assumes finite_V[simp, intro!]: \"finite V\"\nbegin\n  lemma is_fin_fr_graph: \"fin_fr_graph G\" by unfold_locales\n\n  lemma finite_E[simp, intro!]: \"finite E\"\n    using finite_subset[OF E_ss] by auto\n\nend\n\n\nabbreviation \"rename_E f E \\<equiv> (\\<lambda>(u,v). (f u, f v))`E\"\n\ndefinition \"fr_rename_ext ecnv f G \\<equiv> \\<lparr> \n    frg_V = f`(frg_V G),\n    frg_E = rename_E f (frg_E G),   \n    frg_V0 = (f`frg_V0 G),\n    \\<dots> = ecnv G\n  \\<rparr>\"\n\nlocale fr_rename_precond\n  = fr_graph G for G :: \"('u,'more) fr_graph_rec_scheme\" +\n  fixes f :: \"'u \\<Rightarrow> 'v\"\n  fixes ecnv :: \"('u, 'more) fr_graph_rec_scheme \\<Rightarrow> 'more'\"\n  assumes INJ: \"inj_on f V\"\nbegin\n  abbreviation \"G' \\<equiv> fr_rename_ext ecnv f G\"\n\n  lemma G'_fields:\n    \"frg_V G' = f`V\"\n    \"frg_V0 G' = f`V0\"\n    \"frg_E G' = rename_E f E\"\n    unfolding fr_rename_ext_def by simp_all\n\n  definition \"fi \\<equiv> the_inv_into V f\"\n\n  lemma \n    fi_f: \"x\\<in>V \\<Longrightarrow> fi (f x) = x\" and\n    f_fi: \"y\\<in>f`V \\<Longrightarrow> f (fi y) = y\" and\n    fi_f_eq: \"\\<lbrakk>f x = y; x\\<in>V\\<rbrakk> \\<Longrightarrow> fi y = x\"\n    unfolding fi_def\n    by (auto \n      simp: the_inv_into_f_f f_the_inv_into_f the_inv_into_f_eq INJ)\n\n  lemma E'_to_E: \"(u,v) \\<in> frg_E G' \\<Longrightarrow> (fi u, fi v)\\<in>E\"\n    using E_ss\n    by (auto simp: fi_f G'_fields)\n\n  lemma V0'_to_V0: \"v\\<in>frg_V0 G' \\<Longrightarrow> fi v \\<in> V0\"\n    using V0_ss\n    by (auto simp: fi_f G'_fields)\n\n\n  lemma rtrancl_E'_sim:\n    assumes \"(f u,v')\\<in>(frg_E G')\\<^sup>*\"\n    assumes \"u\\<in>V\"\n    shows \"\\<exists>v. v' = f v \\<and> v\\<in>V \\<and> (u,v)\\<in>E\\<^sup>*\"\n    using assms\n  proof (induction \"f u\" v' arbitrary: u)\n    case (rtrancl_into_rtrancl v' w' u)\n    then obtain v w where \"v' = f v\" \"w' = f w\" \"(v,w)\\<in>E\"\n      by (auto simp: G'_fields)\n    hence \"v\\<in>V\" \"w\\<in>V\" using E_ss by auto\n    from rtrancl_into_rtrancl obtain vv where \"v' = f vv\" \"vv\\<in>V\" \"(u,vv)\\<in>E\\<^sup>*\"\n      by blast\n    from `v' = f v` `v\\<in>V` `v' = f vv` `vv\\<in>V` have [simp]: \"vv = v\"\n      using INJ by (metis inj_on_contraD)\n\n    note `(u,vv)\\<in>E\\<^sup>*`[simplified]\n    also note `(v,w)\\<in>E`\n    finally show ?case using `w' = f w` `w\\<in>V` by blast\n  qed auto\n    \n  lemma rtrancl_E'_to_E: assumes \"(u,v)\\<in>(frg_E G')\\<^sup>*\" shows \"(fi u, fi v)\\<in>E\\<^sup>*\"\n    using assms apply induction\n    by (fastforce intro: E'_to_E rtrancl_into_rtrancl)+\n\n  lemma G'_invar: \"fr_graph G'\"\n    apply unfold_locales\n  proof -\n    have \"(frg_E G')\\<^sup>* `` frg_V0 G' \\<subseteq> f ` (E\\<^sup>*``V0)\"\n      apply (clarsimp_all simp: G'_fields(2))\n      apply (drule rtrancl_E'_sim)\n      using V0_ss apply auto []\n      apply auto\n      done\n    thus \"finite ((frg_E G')\\<^sup>* `` frg_V0 G')\" \n      by (rule finite_subset) simp\n    \n    show \"frg_V0 G' \\<subseteq> frg_V G'\"\n      using V0_ss by (auto simp: G'_fields) []\n\n    show \"frg_E G' \\<subseteq> frg_V G' \\<times> frg_V G'\"\n      using E_ss by (auto simp: G'_fields) []\n  qed\n\n  sublocale G'!: fr_graph G' using G'_invar .\n\n  lemma V'_to_V: \"v \\<in> G'.V \\<Longrightarrow> fi v \\<in> V\"\n    by (auto simp: fi_f G'_fields)\n\n  lemma ipath_sim1: \"ipath E r \\<Longrightarrow> ipath G'.E (f o r)\"\n    unfolding ipath_def by (auto simp: G'_fields)\n\n  lemma ipath_sim2: \"ipath G'.E r \\<Longrightarrow> ipath E (fi o r)\"\n    unfolding ipath_def \n    apply (clarsimp simp: G'_fields)\n    apply (drule_tac x=i in spec)\n    using E_ss\n    by (auto simp: fi_f)\n\n  lemma run_sim1: \"is_run r \\<Longrightarrow> G'.is_run (f o r)\"\n    unfolding is_run_def G'.is_run_def\n    apply (intro conjI)\n    apply (auto simp: G'_fields) []\n    apply (auto simp: ipath_sim1)\n    done\n\n  lemma run_sim2: \"G'.is_run r \\<Longrightarrow> is_run (fi o r)\"\n    unfolding is_run_def G'.is_run_def\n    by (auto simp: ipath_sim2 V0'_to_V0)\n\nend\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/CAVA_Automata/Digraph.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473746782094, "lm_q2_score": 0.8539127529517043, "lm_q1q2_score": 0.7449085482416617}}
{"text": "theory Section2_1 imports Main begin\n\nsection \"Exercise 2.1\"\n\ntype_alias var = nat\n\n\ndatatype expr =\n  NatLit nat |\n  Var var |\n  Plus expr expr |\n  LAbs \"var list\" expr |\n  LApp expr \"expr list\"\n\n\nfun varSubst :: \"expr \\<Rightarrow> (var \\<times> expr) list \\<Rightarrow> expr\" where\n  varSubstNatLit_iff: \"varSubst (NatLit n) _ = (NatLit n)\" |\n  varSubstVarNil_iff: \"varSubst (Var v') [] = (Var v')\" |\n  varSubstVarCons_iff: \"varSubst (Var v') ((v, e)#vs) = (if v = v' then e else varSubst (Var v') vs)\" |\n  varSubstPlus_iff: \"varSubst (Plus l r) ss = (Plus (varSubst l ss) (varSubst r ss))\" |\n  varSubstLAbs_iff: \"varSubst (LAbs vs b) ss = (LAbs vs (varSubst b ss))\" |\n  varSubstLApp_iff: \"varSubst (LApp f ps) ss = (LApp (varSubst f ss) (map (\\<lambda>p. varSubst p ss) ps))\"\n\n\nlemma pairConsI[intro]: \"\\<lbrakk> \\<forall>i < length xs. zs!i = (xs!i, ys!i) \\<rbrakk> \\<Longrightarrow> (\\<forall>i < length (x#xs). ((x, y)#zs)!i = ((x#xs)!i, (y#ys)!i))\"\n  using less_Suc_eq_0_disj by auto\n\n\ninductive_set B :: \"(expr \\<times> expr) set\" where\n  BNatLitI: \"(NatLit n, NatLit n) \\<in> B\" |\n  BVarI: \"(Var v, Var v) \\<in> B\" |\n  BPlusI: \"\\<lbrakk> (l, l') \\<in> B; (r, r') \\<in> B \\<rbrakk> \\<Longrightarrow> (Plus l r, Plus l' r') \\<in> B\" |\n  BLAbsI: \"\\<lbrakk> (b, b') \\<in> B \\<rbrakk> \\<Longrightarrow> (LAbs vs b, LAbs vs b') \\<in> B\" |\n  BLAppI: \"\\<lbrakk>\n    (f, LAbs vs b) \\<in> B;\n    length vs = length ps;\n    \\<forall>i. i < length vs \\<longrightarrow> ((ss!i) = (vs!i, ps!i));\n    length ss = length vs;\n    e = varSubst b ss\n  \\<rbrakk> \\<Longrightarrow> (LApp f ps, e) \\<in> B\"\n  \n\ntheorem \"((LApp (LAbs [0] (Var 0)) [NatLit 1]), NatLit 1) \\<in> B\"\n  apply(rule BLAppI)\n  apply(rule BLAbsI)\n  apply(rule BVarI)\n  apply(force)\n  apply(intro allI)\n  apply(intro impI)\n  apply(clarsimp)\n  apply(rule nth_Cons_0)\n  apply(simp)\n  apply(subst varSubstVarCons_iff)\n  apply(simp)\n  done\n  \n\ntheorem \"(LApp (LApp (LAbs [0] (Var 0)) [LAbs [0] (Var 0)]) [NatLit 2], NatLit 2) \\<in> B\"\n  apply(rule BLAppI)\n  apply(rule BLAppI)\n  apply(rule BLAbsI)\n  apply(rule BVarI)\n  apply(simp)\n  apply(simp)\n  apply(rule nth_Cons_0)\n  apply(simp)\n  apply(subst varSubstVarCons_iff)\n  apply(simp)\n  apply(simp)\n  apply(simp)\n  apply(rule nth_Cons_0)\n  apply(simp)\n  apply(subst varSubstVarCons_iff)\n  apply(simp)\n  done\n\n\ndefinition LId :: \"expr\" where\n  \"LId \\<equiv> (LAbs [0] (Var 0))\"\n\n\ntheorem \"(LApp LId [e], e) \\<in> B\"\n  apply(unfold LId_def)\n  apply(rule BLAppI)\n  apply(rule BLAbsI)\n  apply(rule BVarI)\n  apply(simp)\n  apply(subgoal_tac \"\\<forall>i<length [0]. [(0, e)] ! i = ([0] ! i, [e] ! i)\")\n  apply(assumption)\n  apply(auto)\n  done\n\n\ndefinition f :: \"expr\" where\n  \"f \\<equiv> LAbs [0, 1, 2] (Plus (Var 0) (Plus (Var 1) (Var 2)))\"\n\n\ndefinition g :: \"expr\" where\n  \"g \\<equiv> LAbs [0] (LAbs [1] (LAbs [2] (Plus (Var 0) (Plus (Var 1) (Var 2)))))\"\n\n\nlemma f_fullBetaConv: \"(LApp f [NatLit 1, NatLit 2, NatLit 3], (Plus (NatLit 1) (Plus (NatLit 2) (NatLit 3)))) \\<in> B\"\n  apply(unfold f_def)\n  apply(rule BLAppI)\n  apply(rule BLAbsI)\n  apply(simp)\n  apply(rule BPlusI)\n  apply(rule BVarI)\n  apply(rule BPlusI)\n  apply(rule BVarI)\n  apply(rule BVarI)\n  apply(simp)\n  apply(rule pairConsI)\n  apply(rule pairConsI)\n  apply(rule pairConsI)\n  apply(simp)\n  apply(simp)\n  apply(simp)\n  done\n\n\nlemma g_fullBetaConv: \"(LApp (LApp (LApp g [NatLit 1]) [NatLit 2]) [NatLit 3], (Plus (NatLit 1) (Plus (NatLit 2) (NatLit 3)))) \\<in> B\"\n  apply(unfold g_def)\n  apply(rule BLAppI)\n  apply(rule BLAppI)\n  apply(rule BLAppI)\n  apply(rule BLAbsI)\n  apply(simp)\n  apply(rule BLAbsI)\n  apply(rule BLAbsI)\n  apply(rule BPlusI)\n  apply(rule BVarI)\n  apply(rule BPlusI)\n  apply(rule BVarI)\n  apply(rule BVarI)\n  apply(simp)\n  apply(rule pairConsI)\n  apply(simp)\n  apply(simp)\n  apply(simp)\n  apply(simp)\n  apply(rule pairConsI)\n  apply(simp)\n  apply(simp)\n  apply(subst varSubstLAbs_iff)\n  apply(rule refl)\n  apply(simp)\n  apply(rule pairConsI)\n  apply(simp)\n  apply(simp)\n  apply(simp)\n  done\n\n\ntheorem \"\\<exists>x. (LApp f [NatLit 1, NatLit 2, NatLit 3], x) \\<in> B \\<and> (LApp (LApp (LApp g [NatLit 1]) [NatLit 2]) [NatLit 3], x) \\<in> B\"\n  apply(rule_tac x=\"Plus (NatLit 1) (Plus (NatLit 2) (NatLit 3))\" in exI)\n  apply(intro conjI)\n  apply(rule f_fullBetaConv)\n  apply(rule g_fullBetaConv)\n  done\n\n\n\nfun vars :: \"expr \\<Rightarrow> var set\" where\n  varsNarLit_iff: \"vars (NatLit _) = {}\" |\n  varsVar_iff: \"vars (Var v) = {v}\" |\n  varsPlus_iff: \"vars (Plus l r) = vars l \\<union> vars r\" |\n  varsLAbs_iff: \"vars (LAbs as b) = vars b \\<union> set as\" |\n  varsLApp_iff: \"vars (LApp fn ps) = vars fn \\<union> (\\<Union> (vars ` set ps))\"\n\n\nfun fv :: \"expr \\<Rightarrow> var set\" where\n  fvNatLit_iff: \"fv (NatLit _) = {}\" |\n  fvVar_iff: \"fv (Var v) = {v}\" |\n  fvPlus_iff: \"fv (Plus l r) = (fv l) \\<union> (fv r)\" |\n  fvLAbs_iff: \"fv (LAbs vs b) = (fv b) - (set vs)\" |\n  fvLApp_iff: \"fv (LApp fn as) = (fv fn) \\<union> (\\<Union> (fv ` set as))\"\n\n\ntheorem \"0 \\<notin> fv (LAbs [0] (Var 0))\"\n  apply(simp)\n  done\n\n\ntheorem \"1 \\<in> fv (LAbs [0] (Var 1))\"\n  apply(simp)\n  done\n\n\ntheorem \"0 \\<in> fv (Plus (Var 0) (LApp (LAbs [0] (Var 0)) [NatLit 0]))\"\n  apply(simp)\n  done\n\n\nfun closed :: \"expr \\<Rightarrow> bool\" where\n  \"closed e = (fv e = {})\"\n\n\nfun binded :: \"var \\<Rightarrow> expr \\<Rightarrow> bool\" where\n  bindedNatLit_iff: \"binded _ (NatLit _) = False\" |\n  bindedVar_iff: \"binded _ (Var _) = False\" |\n  bindedPlus_iff: \"binded v (Plus l r) = (binded v l \\<or> binded v r)\" |\n  bindedLAbs_iff: \"binded v (LAbs as b) = (v \\<in> set as \\<or> binded v b)\" |\n  bindedLApp_iff: \"binded v (LApp fn ps) = (binded v fn \\<or> (\\<exists>p \\<in> set ps. binded v p))\"\n\n\ninductive_set E :: \"expr set\" where\n  ENatLitI: \"NatLit _ \\<in> E\" |\n  EVarI: \"Var _ \\<in> E\" |\n  EPlusI: \"\\<lbrakk> l \\<in> E; r \\<in> E \\<rbrakk> \\<Longrightarrow> Plus l r \\<in> E\" |\n  ELAbsI: \"\\<lbrakk> b \\<in> E; \\<forall>v \\<in> set vs. \\<not>binded v b \\<rbrakk> \\<Longrightarrow> LAbs vs b \\<in> E\" |\n  ELAppI: \"\\<lbrakk> f \\<in> E; \\<forall>p \\<in> set ps. p \\<in> E \\<rbrakk> \\<Longrightarrow> LApp f ps \\<in> E\"\n\n\ninductive_cases ELAbsE: \"LAbs vs b \\<in> E\"\n\n\ntheorem \"\\<lbrakk> e \\<in> E \\<rbrakk> \\<Longrightarrow> fv e \\<subseteq> vars e\"\n  apply(erule E.induct)\n  apply(auto)\n  done\n\n\ntheorem \"LAbs [0] (Var 0) \\<in> E\"\n  apply(rule ELAbsI)\n  apply(rule EVarI)\n  apply(intro ballI)\n  apply(subst bindedVar_iff)\n  apply(rule notI)\n  apply(assumption)\n  done\n\n\nlemma listSingletonI: \"x \\<in> set [x]\"\n  apply(subst set_simps)\n  apply(rule Set.insertI1)\n  done\n\n\ntheorem \"(LAbs [0] (LAbs [0] (Var 0))) \\<notin> E\"\n  apply(rule notI)\n  apply(erule ELAbsE)\n  apply(drule_tac x=0 in bspec)\n  apply(rule listSingletonI)\n  apply(subst (asm) bindedLAbs_iff)\n  apply(erule notE)\n  apply(rule disjI1)\n  apply(rule listSingletonI)\n  done\n\n\nfun betaSet :: \"expr \\<Rightarrow> expr set\" where\n  \"betaSet e = B\\<^sup>+ `` {e}\"\n\n\ntheorem \"NatLit n \\<in> betaSet (NatLit n)\"\n  apply(auto)\n  apply(subst trancl_unfold)\n  apply(rule UnI1)\n  apply(rule BNatLitI)\n  done\n\n\ntheorem \"NatLit 1 \\<in> betaSet (LApp (LAbs [0] (Var 0)) [NatLit 1])\"\n  apply(auto)\n  apply(subst trancl_unfold)\n  apply(rule UnI1)\n  apply(rule BLAppI)\n  apply(rule BLAbsI)\n  apply(rule BVarI)\n  apply(simp)\n  apply(rule pairConsI)\n  apply(simp)\n  apply(simp)\n  apply(simp)\n  done\n\n\n(* \\<beta>\u7c21\u7d04\u304c2\u56de\u5fc5\u8981\u306a\u306e\u306b1\u56de\u306e\u5206\u5c90\u306b\u5165\u3063\u305f\u307f\u305f *)\ntheorem \"NatLit 1 \\<in> betaSet (LApp LId [LApp LId [NatLit 1]])\"\n  apply(auto)\n  apply(subst trancl_unfold)\n  apply(rule UnI1) (* \\<beta>\u7c21\u7d041\u56de\u306e\u5206\u5c90\u306b\u5165\u308b *)\n  apply(rule BLAppI)\n  apply(unfold LId_def)\n  apply(rule BLAbsI)\n  apply(rule BVarI)\n  apply(simp)\n  apply(rule pairConsI)\n  apply(simp)\n  apply(simp)\n  apply(simp)\n  (* goal: False *)\n  oops\n  \n\ntheorem \"NatLit 1 \\<in> betaSet (LApp LId [LApp LId [NatLit 1]])\"\n  apply(auto)\n  apply(subst trancl_unfold)\n  apply(rule UnI2) (* \\<beta>\u7c21\u7d041\u56de\u306e\u30eb\u30fc\u30c8\u3092\u907f\u3051\u308b *)\n  apply(rule relcomp.relcompI)\n  apply(subst trancl_unfold)\n  apply(rule UnI1) (* \\<beta>\u7c21\u7d042\u56de\u306e\u30eb\u30fc\u30c8\u3078\u5165\u308b *)\n  apply(rule BLAppI)\n  apply(unfold LId_def)\n  apply(rule BLAbsI)\n  apply(rule BVarI)\n  apply(simp)\n  apply(rule pairConsI)\n  apply(simp)\n  apply(simp)\n  apply(rule refl)\n  apply(subst varSubstVarCons_iff)\n  apply(simp)\n  apply(rule BLAppI)\n  apply(rule BLAbsI)\n  apply(rule BVarI)\n  apply(simp)\n  apply(rule pairConsI)\n  apply(simp)\n  apply(simp)\n  apply(simp)\n  done\n\n\n(* TODO: \u7df4\u7fd2\u554f\u984c\u306e = \u306e\u610f\u5473\u304c\u602a\u3057\u3044\u304c\u3053\u308c\u4ee5\u4e0a\\<beta>\u5909\u63db\u3067\u304d\u306a\u3044\u7684\u306a\u610f\u5473\u306a\u3089\u3001\u305d\u308c\u305e\u308c\u304c\u305f\u30601\u3064\u306e\u3053\u308c\u4ee5\u4e0a\n   \\<beta>\u5909\u63db\u3067\u304d\u306a\u3044\u5f0f\u3092\u3082\u3064\u7684\u306a\u6761\u4ef6\u3092\u52a0\u3048\u3066\u3042\u3052\u306a\u3044\u3068\u5b58\u5728\u9650\u91cf\u306e\u4e3b\u5f35\u304c\u984c\u610f\u306b\u5bfe\u3057\u3066\u5f31\u3059\u304e\u308b\u6c17\u304c\u3059\u308b *)\ntheorem \"\\<lbrakk> e \\<in> E \\<rbrakk> \\<Longrightarrow> \\<exists>e' \\<in> betaSet e. {e'} = betaSet e'\"\n  oops\nend", "meta": {"author": "Kuniwak", "repo": "semantics-of-programing-yokouchi-exercise", "sha": "c9237aee978c3c78a45f3a49a36ee75164a9ba10", "save_path": "github-repos/isabelle/Kuniwak-semantics-of-programing-yokouchi-exercise", "path": "github-repos/isabelle/Kuniwak-semantics-of-programing-yokouchi-exercise/semantics-of-programing-yokouchi-exercise-c9237aee978c3c78a45f3a49a36ee75164a9ba10/Section2_1.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473614033683, "lm_q2_score": 0.8539127492339909, "lm_q1q2_score": 0.744908533662968}}
{"text": "(*  Title:      Free_Boolean_Algebra.thy\n    Author:     Brian Huffman, Portland State University\n*)\n\nheader {* Free Boolean algebras *}\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 {* Free boolean algebra as a set *}\n\ntext {*\n  We start by defining the free boolean algebra over type @{typ 'a} as\n  an inductive set.  Here @{text \"i :: 'a\"} represents a variable;\n  @{text \"A :: 'a set\"} represents a valuation, assigning a truth\n  value to each variable; and @{text \"S :: 'a set set\"} represents a\n  formula, as the set of valuations that make the formula true.  The\n  set @{text fba} contains representatives of formulas built from\n  finite combinations of variables with negation and conjunction.\n*}\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 {* Free boolean algebra as a type *}\n\ntext {*\n  The next step is to use @{text typedef} to define a type isomorphic\n  to the set @{const fba}.  We also define a constructor @{text var}\n  that corresponds with the similarly-named introduction rule for\n  @{const fba}.\n*}\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 {*\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*}\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 {*\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*}\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 {*\n  \\medskip\n  Here we prove an essential property of a free Boolean algebra:\n  all generators are independent.\n*}\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 {*\n  \\medskip\n  We conclude this section by proving an induction principle for\n  formulas.  It mirrors the definition of the inductive set @{text\n  fba}, with cases for variables, complements, and conjunction.\n*}\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 `P (Abs_formula S)` have \"P (- Abs_formula S)\" by (rule 2)\n    with `S \\<in> fba` show ?case\n      unfolding uminus_formula_def by (simp add: Abs_formula_inverse)\n  next\n    case (inter S T)\n    from `P (Abs_formula S)` and `P (Abs_formula T)`\n    have \"P (Abs_formula S \\<sqinter> Abs_formula T)\" by (rule 3)\n    with `S \\<in> fba` and `T \\<in> fba` show ?case\n      unfolding inf_formula_def by (simp add: Abs_formula_inverse)\n  qed\nqed\n\n\nsubsection {* If-then-else for Boolean algebras *}\n\ntext {*\n  This is a generic if-then-else operator for arbitrary Boolean\n  algebras.\n*}\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 {* Formulas over a set of generators *}\n\ntext {*\n  The set @{text \"formulas S\"} consists of those formulas that only\n  depend on variables in the set @{text S}.  It is analogous to the\n  @{const lists} operator for the list datatype.\n*}\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 {* Injectivity of if-then-else *}\n\ntext {*\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*}\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 `x \\<in> formulas S` by (rule formulasD, force simp add: `i \\<notin> S`)\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 `x' \\<in> formulas S` by (rule formulasD, force simp add: `i \\<notin> S`)\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 `y \\<in> formulas S` by (rule formulasD, force simp add: `i \\<notin> S`)\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 `y' \\<in> formulas S` by (rule formulasD, force simp add: `i \\<notin> S`)\n    finally show \"A \\<in> Rep_formula y \\<longleftrightarrow> A \\<in> Rep_formula y'\" .\n  qed\nqed\n\n\nsubsection {* Specification of homomorphism operator *}\n\ntext {*\n  Our goal is to define a homomorphism operator @{text hom} such that\n  for any function @{text f}, @{text \"hom f\"} is the unique Boolean\n  algebra homomorphism satisfying @{text \"hom f (var i) = f i\"}\n  for all @{text i}.\n\n  Instead of defining @{text hom} directly, we will follow the\n  approach used to define Isabelle's @{text fold} operator for finite\n  sets.  First we define the graph of the @{text hom} function as a\n  relation; later we will define the @{text hom} function itself using\n  definite choice.\n\n  The @{text hom_graph} 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  @{text S}, to ensure that branches of each if-then-else do not use\n  the same variable again.\n*}\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 {*\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*}\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 `k \\<in> insert i S` have k: \"k \\<in> S\" by simp\n    have *: \"insert i S - {k} = insert i (S - {k})\"\n      using `i \\<noteq> k` by (simp add: insert_Diff_if)\n    have **: \"i \\<notin> S - {k}\" using `i \\<notin> S` 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 {*\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 @{text S}, the relation @{term \"hom_graph f S\"} maps each\n  @{text x} to at most one @{text a}.  The proof uses the\n  injectiveness of if-then-else, which we proved earlier.\n*}\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 {*\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 @{text S} with a\n  larger finite set.\n*}\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 `finite T` have \"hom_graph f (S \\<union> T) x a\"\n    by (induct set: finite, simp add: assms, simp add: hom_graph_insert)\n  with `S \\<subseteq> T` 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 {*\n  \\medskip\n  This stronger uniqueness property says that @{term \"hom_graph f\"}\n  maps each @{text x} to at most one @{text a}, even for\n  \\emph{different} values of the set parameter.\n*}\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 {*\n  \\medskip\n  Finally, these last few lemmas establish that the @{term \"hom_graph\n  f\"} relation is total: every @{text x} is mapped to some @{text a}.\n*}\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 {* Homomorphisms into other boolean algebras *}\n\ntext {*\n  Now that we have proved the necessary existence and uniqueness\n  properties of @{const hom_graph}, we can define the function @{text\n  hom} using definite choice.\n*}\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 {*\n  \\medskip\n  The @{const hom} function correctly implements its specification:\n*}\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 {*\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*}\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 {* Map operation on Boolean formulas *}\n\ntext {*\n  We can define a map functional in terms of @{const hom} and @{const\n  var}.  The properties of @{text fmap} follow directly from the\n  lemmas we have already proved about @{const hom}.\n*}\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 {*\n  \\medskip\n  The map functional satisfies the functor laws: it preserves identity\n  and function composition.\n*}\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 {* Hiding lattice syntax *}\n\ntext {*\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 @{text Lattice_Syntax} from\n  the Isabelle library.\n*}\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": "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-Boolean-Algebra/Free_Boolean_Algebra.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9059898127684335, "lm_q2_score": 0.8221891327004132, "lm_q1q2_score": 0.744894978395488}}
{"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.*)\n  theory TIP_prop_53\nimports \"../../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 count :: \"Nat => Nat list => Nat\" where\n\"count y (nil2) = Z\"\n| \"count y (cons2 z2 ys) =\n     (if x y z2 then S (count y ys) else count y ys)\"\n\nfun t2 :: \"Nat => Nat => bool\" where\n\"t2 (Z) z = True\"\n| \"t2 (S z2) (Z) = False\"\n| \"t2 (S z2) (S x2) = t2 z2 x2\"\n\nfun insort :: \"Nat => Nat list => Nat list\" where\n\"insort y (nil2) = cons2 y (nil2)\"\n| \"insort y (cons2 z2 xs) =\n     (if t2 y z2 then cons2 y (cons2 z2 xs) else cons2 z2 (insort y xs))\"\n\nfun sort :: \"Nat list => Nat list\" where\n\"sort (nil2) = nil2\"\n| \"sort (cons2 z xs) = insort z (sort xs)\"\n\ntheorem property0 :\n  \"((count n xs) = (count n (sort 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/Isaplanner/Isaplanner/TIP_prop_53.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765281148513, "lm_q2_score": 0.8152324960856175, "lm_q1q2_score": 0.7448587966299112}}
{"text": "theory hw07\n  imports Main\nbegin\n\nhide_const (open) inv\n\ntype_synonym intervals = \"(nat*nat) list\"\n\nfun inv' :: \"nat \\<Rightarrow> intervals \\<Rightarrow> bool\" where\n  \"inv' n [] \\<longleftrightarrow> True\"|\n  \"inv' n ((a,b)#ivs) \\<longleftrightarrow> n\\<le>a \\<and> a\\<le>b \\<and> inv' (b+2) ivs\"\n\ndefinition inv where \"inv = inv' 0\"\n\n\nfun set_of :: \"intervals \\<Rightarrow> nat set\"\nwhere\n  \"set_of [] = {}\"|\n  \"set_of ((a,b)#ivs) = {a..b} \\<union> set_of ivs\"\n\n\nfun del :: \"nat \\<Rightarrow> intervals \\<Rightarrow> intervals\"\n  where\n   \"del x [] = []\"\n|  \"del x ((a,b)#lis) = (\n    if (x < a) then (a,b)#lis\n    else if (x = a \\<and> x = b) then lis\n    else if (x = a) then ((a+1), b)#lis\n    else if (x < b) then (a,x-1)#(x+1,b)#lis\n    else if (x = b) then (a,b-1)#lis\n    else (a,b)#(del x lis))\"\n\nvalue \"del (12::nat) [(2,5),(7,7),(9,11)]\"\nvalue \"set_of [] - {1::nat}\"\n\nlemma del_pres_inv: \"n\\<le>x \\<Longrightarrow> inv' n itl \\<Longrightarrow> inv' n (del x itl)\"\nproof (induction itl arbitrary:n)\n  case Nil\n  then show ?case by auto\nnext\n  case (Cons a itl)\n  then show ?case\n    apply (cases a)\n    apply (cases itl)\n    apply auto\n    done\nqed\n\nlemma set_of_del:\n  assumes \"n\\<le>x\"\n  assumes \"inv' n itl\"\n  shows \"set_of (del x itl) =  set_of itl - {x}\"\n  using assms\nproof (induction itl arbitrary:n)\ncase Nil\n  then show ?case by auto\nnext\n  case (Cons a itl)\n  then show ?case \n    apply (cases a)\n    apply (cases itl)\n     apply (auto split: if_splits)\n    apply (auto)\n    done\nqed\n\n\nlemma del_correct:\n  assumes \"inv itl\"\n  shows \"inv (del x itl)\" \"set_of (del x itl) =  (set_of itl) - {x}\"\n  using assms del_pres_inv hw07.inv_def apply fastforce\n  using assms hw07.inv_def set_of_del by fastforce\n\n\n\n\n\n\n\n\n\nfun addi :: \"nat \\<Rightarrow> nat \\<Rightarrow> intervals \\<Rightarrow> intervals\"\nwhere\n  \"addi i j [] = [(i,j)]\"|\n  \"addi i j ((a,b)#lis) = (\n    if j + 1 < a then ((i,j)#(a,b)#lis)\n    else if j+1 = a then ((i,b)#lis)\n    else if j \\<le> b then(\n      if i < a then ((i,b)#lis)\n      else ((a,b)#lis))\n    else (\n      if i < a then addi i j lis\n      else if i \\<le> b+1 then addi a j lis\n      else ((a,b)#(addi i j lis)))\n    )\"\n\nvalue \"addi 5 99 [(2,5),(7,7),(9,11)]\"\n\nlemma addi_pres_inv: \"n\\<le>i \\<Longrightarrow> i\\<le>j \\<Longrightarrow> inv' n itl \\<Longrightarrow> inv' n (addi i j itl)\"\nproof (induction i j itl arbitrary:n rule:addi.induct)\n  case (1 i j)\n  then show ?case by auto\nnext\n  case (2 i j a b itl)\n  then show ?case\n    apply(cases itl)\n     apply(auto)\n    done\nqed\n\nlemma set_of_addi:\n  assumes \"n\\<le>i\" \"i\\<le>j\"\n  assumes \"inv' n itl\"\n  shows \"set_of (addi i j itl) = {i..j} \\<union> set_of itl\"\n  using assms\nproof (induction i j itl arbitrary:n rule:addi.induct)\n  case (1 i j)\n  then show ?case by auto\nnext\n  case (2 i j a b lis)\n  then show ?case\n    apply(cases lis)\n     apply(cases a)\n      apply(cases b)\n       apply (auto split:if_splits)\n          apply fastforce\n         apply fastforce\n        apply fastforce\n       apply fastforce\n      apply fastforce\n     apply fastforce\n    apply fastforce\n    done\nqed\n\nlemma addi_correct:\n  assumes \"inv is\" \"i\\<le>j\"\n  shows \"inv (addi i j is)\" \"set_of (addi i j is) = {i..j} \\<union> (set_of is)\"\n  using addi_pres_inv assms hw07.inv_def zero_order(3) apply force\n  by (metis assms hw07.inv_def le0 set_of_addi)\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/07/hw07.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765210631689, "lm_q2_score": 0.8152324871074608, "lm_q1q2_score": 0.7448587826780194}}
{"text": "theory prop_68\nimports Main\n        \"$HIPSTER_HOME/IsaHipster\"\nbegin\n  datatype 'a list = Nil2 | Cons2 \"'a\" \"'a list\"\n  datatype Nat = Z | S \"Nat\"\n  fun len :: \"'a list => Nat\" where\n  \"len (Nil2) = Z\"\n  | \"len (Cons2 y xs) = S (len xs)\"\n  fun 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  fun equal2 :: \"Nat => Nat => bool\" where\n  \"equal2 (Z) (Z) = True\"\n  | \"equal2 (Z) (S z) = False\"\n  | \"equal2 (S x2) (Z) = False\"\n  | \"equal2 (S x2) (S y2) = equal2 x2 y2\"\n  fun delete :: \"Nat => Nat list => Nat list\" where\n  \"delete x (Nil2) = Nil2\"\n  | \"delete x (Cons2 z xs) =\n       (if equal2 x z then delete x xs else Cons2 z (delete x xs))\"\n  (*hipster len le equal2 delete *)\n\nlemma lemma_a [thy_expl]: \"equal2 x4 y4 = equal2 y4 x4\"\nby (hipster_induct_schemes equal2.simps)\n\nlemma lemma_aa [thy_expl]: \"equal2 x2 x2 = True\"\nby (hipster_induct_schemes equal2.simps)\n\nlemma lemma_ab [thy_expl]: \"equal2 x2 (S x2) = False\"\nby (hipster_induct_schemes equal2.simps)\n\n(*hipster le len*)\nlemma lemma_ac [thy_expl]: \"le x2 x2 = True\"\nby (hipster_induct_schemes le.simps len.simps)\n\nlemma lemma_ad [thy_expl]: \"le x2 (S x2) = True\"\nby (hipster_induct_schemes le.simps len.simps)\n\nlemma lemma_ae [thy_expl]: \"le (S x2) x2 = False\"\nby (hipster_induct_schemes le.simps len.simps)\n\nhipster_cond le\n\nlemma lemma_ah [thy_expl]: \"le x2 y2 \\<Longrightarrow> le x2 (S y2) = True\"\nby (hipster_induct_schemes le.simps len.simps)\n\nlemma lemma_ai [thy_expl]: \"le y2 x2 \\<Longrightarrow> le (S x2) y2 = False\"\nby (hipster_induct_schemes le.simps len.simps)\n\nlemma lemma_aj [thy_expl]: \"le y x \\<and> le x y \\<Longrightarrow> x = y\"\nby (hipster_induct_schemes le.simps len.simps Nat.exhaust)\n\nlemma lemma_ak [thy_expl]: \"le z y \\<and> le x z \\<Longrightarrow> le x y = True\"\nby (hipster_induct_schemes le.simps  Nat.exhaust)\n\n(*hipster delete len*)\nlemma lemma_af [thy_expl]: \"delete x10 (delete y10 z10) = delete y10 (delete x10 z10)\"\nby (hipster_induct_schemes delete.simps len.simps)\n\nlemma lemma_ag [thy_expl]: \"delete x6 (delete x6 y6) = delete x6 y6\"\nby (hipster_induct_schemes delete.simps len.simps)\n\n\n  theorem x0 :\n    \"le (len (delete n xs)) (len xs)\"\n    by (hipster_induct_schemes)\n\nend\n\n", "meta": {"author": "moajohansson", "repo": "IsaHipster", "sha": "91f6ea3f1166a9de547722ece6445fe843ad89b4", "save_path": "github-repos/isabelle/moajohansson-IsaHipster", "path": "github-repos/isabelle/moajohansson-IsaHipster/IsaHipster-91f6ea3f1166a9de547722ece6445fe843ad89b4/benchmark/isaplanner/prop_68.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765234137297, "lm_q2_score": 0.8152324803738429, "lm_q1q2_score": 0.7448587784419244}}
{"text": "header \"A Typed Language\"\n(** Score: 5/5\n*)\ntheory GabrielaLimonta\nimports \"~~/src/HOL/IMP/Star\"\nbegin\n\nsubsection \"Expressions\"\n\ndatatype val = Iv int | Bv bool\n\ntype_synonym vname = string\ntype_synonym state = \"vname \\<Rightarrow> val\"\n\ndatatype exp =  N int | V vname | Plus exp exp |\n  Bc bool | Not exp | And exp exp | Less exp exp\n\ninductive eval :: \"exp \\<Rightarrow> state \\<Rightarrow> val \\<Rightarrow> bool\" where\n\"eval (N i) s (Iv i)\" |\n\"eval (V x) s (s x)\" |\n\"eval a1 s (Iv i1) \\<Longrightarrow> eval a2 s (Iv i2)\n \\<Longrightarrow> eval (Plus a1 a2) s (Iv(i1+i2))\" |\n\"eval (Bc v) s (Bv v)\" |\n\"eval b s (Bv bv) \\<Longrightarrow> eval (Not b) s (Bv(\\<not> bv))\" |\n\"eval b1 s (Bv bv1) \\<Longrightarrow> eval b2 s (Bv bv2) \\<Longrightarrow> eval (And b1 b2) s (Bv(bv1 & bv2))\" |\n\"eval a1 s (Iv i1) \\<Longrightarrow> eval a2 s (Iv i2) \\<Longrightarrow> eval (Less a1 a2) s (Bv(i1 < i2))\"\n\ninductive_cases [elim!]:\n  \"eval (N i) s v\"\n  \"eval (V x) s v\"\n  \"eval (Plus a1 a2) s v\"\n  \"eval (Bc b) s v\"\n  \"eval (Not b) s v\"\n  \"eval (And b1 b2) s v\"\n  \"eval (Less a1 a2) s v\"\n\nsubsection \"Syntax of Commands\"\n(* a copy of Com.thy - keep in sync! *)\n\ndatatype\n  com = SKIP \n      | Assign vname exp       (\"_ ::= _\" [1000, 61] 61)\n      | Seq    com  com         (\"_;; _\"  [60, 61] 60)\n      | If     exp com com     (\"IF _ THEN _ ELSE _\"  [0, 0, 61] 61)\n      | While  exp com         (\"WHILE _ DO _\"  [0, 61] 61)\n\n\nsubsection \"Small-Step Semantics of Commands\"\n\ninductive\n  small_step :: \"(com \\<times> state) \\<Rightarrow> (com \\<times> state) \\<Rightarrow> bool\" (infix \"\\<rightarrow>\" 55)\nwhere\nAssign:  \"eval a s v \\<Longrightarrow> (x ::= a, s) \\<rightarrow> (SKIP, s(x := v))\" |\n\nSeq1:   \"(SKIP;;c,s) \\<rightarrow> (c,s)\" |\nSeq2:   \"(c1,s) \\<rightarrow> (c1',s') \\<Longrightarrow> (c1;;c2,s) \\<rightarrow> (c1';;c2,s')\" |\n\nIfTrue:  \"eval b s (Bv True) \\<Longrightarrow> (IF b THEN c1 ELSE c2,s) \\<rightarrow> (c1,s)\" |\nIfFalse: \"eval b s (Bv False) \\<Longrightarrow> (IF b THEN c1 ELSE c2,s) \\<rightarrow> (c2,s)\" |\n\nWhile:   \"(WHILE b DO c,s) \\<rightarrow> (IF b THEN c;; WHILE b DO c ELSE SKIP,s)\"\n\nlemmas small_step_induct = small_step.induct[split_format(complete)]\n\nsubsection \"The Type System\"\n\ndatatype ty = Ity | Bty\n\ntype_synonym tyenv = \"vname \\<Rightarrow> ty\"\n\ninductive etyping :: \"tyenv \\<Rightarrow> exp \\<Rightarrow> ty \\<Rightarrow> bool\"\n  (\"(1_/ \\<turnstile>/ (_ :/ _))\" [50,0,50] 50)\nwhere\nIc_ty: \"\\<Gamma> \\<turnstile> N i : Ity\" |\nV_ty: \"\\<Gamma> \\<turnstile> V x : \\<Gamma> x\" |\nPlus_ty: \"\\<Gamma> \\<turnstile> a1 : Ity \\<Longrightarrow> \\<Gamma> \\<turnstile> a2 : Ity \\<Longrightarrow> \\<Gamma> \\<turnstile> Plus a1 a2 : Ity\" |\nB_ty: \"\\<Gamma> \\<turnstile> Bc v : Bty\" |\nNot_ty: \"\\<Gamma> \\<turnstile> b : Bty \\<Longrightarrow> \\<Gamma> \\<turnstile> Not b : Bty\" |\nAnd_ty: \"\\<Gamma> \\<turnstile> b1 : Bty \\<Longrightarrow> \\<Gamma> \\<turnstile> b2 : Bty \\<Longrightarrow> \\<Gamma> \\<turnstile> And b1 b2 : Bty\" |\nLess_ty: \"\\<Gamma> \\<turnstile> a1 : Ity \\<Longrightarrow> \\<Gamma> \\<turnstile> a2 : Ity \\<Longrightarrow> \\<Gamma> \\<turnstile> Less a1 a2 : Bty\"\n\ninductive ctyping :: \"tyenv \\<Rightarrow> com \\<Rightarrow> bool\" (infix \"\\<turnstile>\" 50) where\nSkip_ty: \"\\<Gamma> \\<turnstile> SKIP\" |\nAssign_ty: \"\\<Gamma> \\<turnstile> a : \\<Gamma>(x) \\<Longrightarrow> \\<Gamma> \\<turnstile> x ::= a\" |\nSeq_ty: \"\\<Gamma> \\<turnstile> c1 \\<Longrightarrow> \\<Gamma> \\<turnstile> c2 \\<Longrightarrow> \\<Gamma> \\<turnstile> c1;;c2\" |\nIf_ty: \"\\<Gamma> \\<turnstile> b : Bty \\<Longrightarrow> \\<Gamma> \\<turnstile> c1 \\<Longrightarrow> \\<Gamma> \\<turnstile> c2 \\<Longrightarrow> \\<Gamma> \\<turnstile> IF b THEN c1 ELSE c2\" |\nWhile_ty: \"\\<Gamma> \\<turnstile> b : Bty \\<Longrightarrow> \\<Gamma> \\<turnstile> c \\<Longrightarrow> \\<Gamma> \\<turnstile> WHILE b DO c\"\n\ninductive_cases [elim!]:\n  \"\\<Gamma> \\<turnstile> x ::= a\"  \"\\<Gamma> \\<turnstile> c1;;c2\"\n  \"\\<Gamma> \\<turnstile> IF b THEN c1 ELSE c2\"\n  \"\\<Gamma> \\<turnstile> WHILE b DO c\"\n\nsubsection \"Well-typed Programs Do Not Get Stuck\"\n\nfun type :: \"val \\<Rightarrow> ty\" where\n\"type (Iv i) = Ity\" |\n\"type (Bv r) = Bty\"\n\nlemma type_eq_Ity[simp]: \"type v = Ity \\<longleftrightarrow> (\\<exists>i. v = Iv i)\"\nby (cases v) simp_all\n\nlemma type_eq_Bty[simp]: \"type v = Bty \\<longleftrightarrow> (\\<exists>r. v = Bv r)\"\nby (cases v) simp_all\n\ndefinition styping :: \"tyenv \\<Rightarrow> state \\<Rightarrow> bool\" (infix \"\\<turnstile>\" 50)\nwhere \"\\<Gamma> \\<turnstile> s  \\<longleftrightarrow>  (\\<forall>x. type (s x) = \\<Gamma> x)\"\n\nlemma epreservation:\n  \"\\<Gamma> \\<turnstile> a : \\<tau> \\<Longrightarrow> eval a s v \\<Longrightarrow> \\<Gamma> \\<turnstile> s \\<Longrightarrow> type v = \\<tau>\"\nproof (induction rule: etyping.induct)\nprint_cases\n  case (Ic_ty \\<Gamma> i)\n    thus ?case by auto\n  next\n  case (V_ty \\<Gamma> x)\n    thus ?case using styping_def by auto\n  next\n  case (Plus_ty \\<Gamma> a1 a2)\n    thus ?case by auto\n  next\n  case (B_ty \\<Gamma> v)\n    thus ?case by auto\n  next\n  case (Not_ty \\<Gamma> b)\n    thus ?case by auto\n  next\n  case (And_ty \\<Gamma> b1 b2)\n    thus ?case by auto\n  next\n  case (Less_ty \\<Gamma> a1 a2)\n    thus ?case by auto\nqed\n\nlemma eprogress: \"\\<Gamma> \\<turnstile> a : \\<tau> \\<Longrightarrow> \\<Gamma> \\<turnstile> s \\<Longrightarrow> \\<exists>v. eval a s v\"\nproof (induction rule: etyping.induct)\nprint_cases\n  case (Ic_ty \\<Gamma>)\n    thus ?case using eval.intros(1) by auto\n  next\n  case (V_ty \\<Gamma>)\n    thus ?case using eval.intros(2) by auto\n  next\n  case (Plus_ty \\<Gamma> a1 a2)\n    from this obtain v1 v2 where \"eval a1 s v1\" and \"eval a2 s v2\" by blast\n    from this and Plus_ty and epreservation have \"type v1 = Ity\" and \"type v2 = Ity\" by auto\n    from this and `eval a1 s v1` and `eval a2 s v2` and Plus_ty \n      obtain i1 i2 where \"v1 = (Iv i1)\" and \"v2 = (Iv i2)\" by auto\n    from this and Plus_ty and `eval a1 s v1` and `eval a2 s v2` and epreservation and eval.intros(3)\n      show ?case by blast\n  next\n  case (B_ty \\<Gamma>)\n    thus ?case using eval.intros(4) by auto\n  next\n  case (Not_ty \\<Gamma> b)\n    from this obtain v where \"eval b s v\" by blast\n    from this and Not_ty and epreservation have \"type v = Bty\" by auto\n    from this and `eval b s v` and Not_ty obtain bv where \"v = (Bv bv)\" by auto\n    from this and Not_ty and `eval b s v` and epreservation and eval.intros(5) show ?case by blast\n  next\n  case (And_ty \\<Gamma> b1 b2)\n    from this obtain v1 v2 where \"eval b1 s v1\" and \"eval b2 s v2\" by blast\n    from this and And_ty and epreservation have \"type v1 = Bty\" and \"type v2 = Bty\" by auto\n    from this and `eval b1 s v1` and `eval b2 s v2` and And_ty\n      obtain bv1 bv2 where \"v1 = (Bv bv1)\" and \"v2 = (Bv bv2)\" by auto\n    from this and And_ty and `eval b1 s v1` and `eval b2 s v2` and epreservation and eval.intros(6)\n      show ?case by blast\n  next\n  case (Less_ty \\<Gamma> a1 a2)\n    from this obtain v1 v2 where \"eval a1 s v1\" and \"eval a2 s v2\" by blast\n    from this and Less_ty and epreservation have \"type v1 = Ity\" and \"type v2 = Ity\" by auto\n    from this and `eval a1 s v1` and `eval a2 s v2` and Less_ty \n      obtain i1 i2 where \"v1 = (Iv i1)\" and \"v2 = (Iv i2)\" by auto\n    from this and Less_ty and `eval a1 s v1` and `eval a2 s v2` and epreservation and eval.intros(7)\n      show ?case by blast\nqed\n\ntheorem progress:\n  \"\\<Gamma> \\<turnstile> c \\<Longrightarrow> \\<Gamma> \\<turnstile> s \\<Longrightarrow> c \\<noteq> SKIP \\<Longrightarrow> \\<exists>cs'. (c,s) \\<rightarrow> cs'\"\nproof (induction rule: ctyping.induct)\nprint_cases\n  case (Skip_ty \\<Gamma>)\n    thus ?case by auto\n  next\n  case (Assign_ty \\<Gamma> a x)\n    from this and eprogress obtain v where \"eval a s v\" by blast\n    from this and Assign show ?case by blast\n  next\n  case (Seq_ty \\<Gamma> c1 c2)\n    thus ?case by (metis PairE Seq1 Seq2)\n  next\n  case (If_ty \\<Gamma> b c1 c2)\n    from this and eprogress obtain v where \"eval b s v\" by blast\n    moreover have \"eval b s (Bv False) \\<Longrightarrow> (IF b THEN c1 ELSE c2, s) \\<rightarrow> (c2, s)\" using IfFalse by auto\n    moreover have \"eval b s (Bv True) \\<Longrightarrow> (IF b THEN c1 ELSE c2, s) \\<rightarrow> (c1, s)\" using IfTrue by auto\n    ultimately show ?case using If_ty and epreservation and type_eq_Bty by metis\n  next\n  case (While_ty \\<Gamma> b c)\n    from this have \"(WHILE b DO c, s) \\<rightarrow> (IF b THEN c;; WHILE b DO c ELSE SKIP, s)\" using While by blast\n    thus ?case by auto\nqed\n\ntheorem styping_preservation:\n  \"(c,s) \\<rightarrow> (c',s') \\<Longrightarrow> \\<Gamma> \\<turnstile> c \\<Longrightarrow> \\<Gamma> \\<turnstile> s \\<Longrightarrow> \\<Gamma> \\<turnstile> s'\"\nproof (induction rule: small_step_induct)\nprint_cases\n  case (Assign a s v x) \n    thus ?case using styping_def and epreservation by auto\n  next\n  case (Seq1 c s)\n    thus ?case by auto\n  next \n  case (Seq2 c1 s c1' s' c2)\n    thus ?case by auto\n  next\n  case (IfTrue b s c1 c2)\n    thus ?case by auto\n  next\n  case (IfFalse b s c1 c2)\n    thus ?case by auto\n  next\n  case (While b c s)\n    thus ?case by auto\nqed\n\ntheorem ctyping_preservation:\n  \"(c,s) \\<rightarrow> (c',s') \\<Longrightarrow> \\<Gamma> \\<turnstile> c \\<Longrightarrow> \\<Gamma> \\<turnstile> c'\"\nproof (induction rule: small_step_induct)\nprint_cases\n  case (Assign a s v)\n    thus ?case using ctyping.Skip_ty by simp\n  next\n  case (Seq1 c)\n    thus ?case by auto\n  next\n  case (Seq2 c1 s c1' s' c2)\n    thus ?case using ctyping.Seq_ty and small_step.Seq2 by blast\n  next\n  case (IfTrue b s c1 c2)\n    thus ?case by auto\n  next\n  case (IfFalse b s c1 c2)\n    thus ?case by auto\n  next\n  case (While b c)\n    thus ?case using ctyping.intros by auto\nqed\n\nabbreviation small_steps :: \"com * state \\<Rightarrow> com * state \\<Rightarrow> bool\" (infix \"\\<rightarrow>*\" 55)\nwhere \"x \\<rightarrow>* y == star small_step x y\"\n\ntheorem type_sound:\n  \"(c,s) \\<rightarrow>* (c',s') \\<Longrightarrow> \\<Gamma> \\<turnstile> c \\<Longrightarrow> \\<Gamma> \\<turnstile> s \\<Longrightarrow> c' \\<noteq> SKIP\n   \\<Longrightarrow> \\<exists>cs''. (c',s') \\<rightarrow> cs''\"\nproof (induction rule: star_induct)\nprint_cases\n  case (refl a b)\n    thus ?case using progress by auto\n  next\n  case (step a1 b1 a' b' a2 b2)\n    thus ?case using ctyping_preservation and styping_preservation by auto\nqed\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/Exercise8/GabrielaLimontaFeedback.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.927363293639213, "lm_q2_score": 0.8031737987125612, "lm_q1q2_score": 0.7448338993387991}}
{"text": "(*  Title:      FOL/ex/Miniscope.thy\n    Author:     Lawrence C Paulson, Cambridge University Computer Laboratory\n    Copyright   1994  University of Cambridge\n\nClassical First-Order Logic.\nConversion to nnf/miniscope format: pushing quantifiers in.\nDemonstration of formula rewriting by proof.\n*)\n\ntheory Miniscope\nimports FOL\nbegin\n\nlemmas ccontr = FalseE [THEN classical]\n\nsubsection \\<open>Negation Normal Form\\<close>\n\nsubsubsection \\<open>de Morgan laws\\<close>\n\nlemma demorgans:\n  \"\\<not> (P \\<and> Q) \\<longleftrightarrow> \\<not> P \\<or> \\<not> Q\"\n  \"\\<not> (P \\<or> Q) \\<longleftrightarrow> \\<not> P \\<and> \\<not> Q\"\n  \"\\<not> \\<not> P \\<longleftrightarrow> P\"\n  \"\\<And>P. \\<not> (\\<forall>x. P(x)) \\<longleftrightarrow> (\\<exists>x. \\<not> P(x))\"\n  \"\\<And>P. \\<not> (\\<exists>x. P(x)) \\<longleftrightarrow> (\\<forall>x. \\<not> P(x))\"\n  by blast+\n\n(*** Removal of --> and <-> (positive and negative occurrences) ***)\n(*Last one is important for computing a compact CNF*)\nlemma nnf_simps:\n  \"(P \\<longrightarrow> Q) \\<longleftrightarrow> (\\<not> P \\<or> Q)\"\n  \"\\<not> (P \\<longrightarrow> Q) \\<longleftrightarrow> (P \\<and> \\<not> Q)\"\n  \"(P \\<longleftrightarrow> Q) \\<longleftrightarrow> (\\<not> P \\<or> Q) \\<and> (\\<not> Q \\<or> P)\"\n  \"\\<not> (P \\<longleftrightarrow> Q) \\<longleftrightarrow> (P \\<or> Q) \\<and> (\\<not> P \\<or> \\<not> Q)\"\n  by blast+\n\n\n(* BEWARE: rewrite rules for <-> can confuse the simplifier!! *)\n\nsubsubsection \\<open>Pushing in the existential quantifiers\\<close>\n\nlemma ex_simps:\n  \"(\\<exists>x. P) \\<longleftrightarrow> P\"\n  \"\\<And>P Q. (\\<exists>x. P(x) \\<and> Q) \\<longleftrightarrow> (\\<exists>x. P(x)) \\<and> Q\"\n  \"\\<And>P Q. (\\<exists>x. P \\<and> Q(x)) \\<longleftrightarrow> P \\<and> (\\<exists>x. Q(x))\"\n  \"\\<And>P Q. (\\<exists>x. P(x) \\<or> Q(x)) \\<longleftrightarrow> (\\<exists>x. P(x)) \\<or> (\\<exists>x. Q(x))\"\n  \"\\<And>P Q. (\\<exists>x. P(x) \\<or> Q) \\<longleftrightarrow> (\\<exists>x. P(x)) \\<or> Q\"\n  \"\\<And>P Q. (\\<exists>x. P \\<or> Q(x)) \\<longleftrightarrow> P \\<or> (\\<exists>x. Q(x))\"\n  by blast+\n\n\nsubsubsection \\<open>Pushing in the universal quantifiers\\<close>\n\nlemma all_simps:\n  \"(\\<forall>x. P) \\<longleftrightarrow> P\"\n  \"\\<And>P Q. (\\<forall>x. P(x) \\<and> Q(x)) \\<longleftrightarrow> (\\<forall>x. P(x)) \\<and> (\\<forall>x. Q(x))\"\n  \"\\<And>P Q. (\\<forall>x. P(x) \\<and> Q) \\<longleftrightarrow> (\\<forall>x. P(x)) \\<and> Q\"\n  \"\\<And>P Q. (\\<forall>x. P \\<and> Q(x)) \\<longleftrightarrow> P \\<and> (\\<forall>x. Q(x))\"\n  \"\\<And>P Q. (\\<forall>x. P(x) \\<or> Q) \\<longleftrightarrow> (\\<forall>x. P(x)) \\<or> Q\"\n  \"\\<And>P Q. (\\<forall>x. P \\<or> Q(x)) \\<longleftrightarrow> P \\<or> (\\<forall>x. Q(x))\"\n  by blast+\n\nlemmas mini_simps = demorgans nnf_simps ex_simps all_simps\n\nML \\<open>\nval mini_ss = simpset_of (@{context} addsimps @{thms mini_simps});\nfun mini_tac ctxt =\n  resolve_tac ctxt @{thms ccontr} THEN' asm_full_simp_tac (put_simpset mini_ss ctxt);\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/FOL/ex/Miniscope.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032941988938413, "lm_q2_score": 0.824461932846258, "lm_q1q2_score": 0.7447316811488286}}
{"text": "(*  Author:     Tobias Nipkow, 2002  *)\n\nsection \"Arrow's Theorem for Utility Functions\"\n\ntheory Arrow_Utility imports Complex_Main\nbegin\n\ntext\\<open>This theory formalizes the first proof due to\nGeanakoplos~\\<^cite>\\<open>\"Geanakoplos05\"\\<close>.  In contrast to the standard model\nof preferences as linear orders, we model preferences as \\emph{utility\nfunctions} mapping each alternative to a real number. The type of\nalternatives and voters is assumed to be finite.\\<close>\n\ntypedecl alt\ntypedecl indi\n\naxiomatization where\n  alt3: \"\\<exists>a b c::alt. distinct[a,b,c]\" and\n  finite_alt: \"finite(UNIV:: alt set)\" and\n\n  finite_indi: \"finite(UNIV:: indi set)\"\n\nlemma third_alt: \"a \\<noteq> b \\<Longrightarrow> \\<exists>c::alt. distinct[a,b,c]\"\nusing alt3 by simp metis\n\nlemma alt2: \"\\<exists>b::alt. b \\<noteq> a\"\nusing alt3 by simp metis\n\ntype_synonym pref = \"alt \\<Rightarrow> real\"\ntype_synonym prof = \"indi \\<Rightarrow> pref\"\n\ndefinition\n top :: \"pref \\<Rightarrow> alt \\<Rightarrow> bool\" (infixr \"<\\<cdot>\" 60) where\n\"p <\\<cdot> b  \\<equiv>  \\<forall>a. a \\<noteq> b \\<longrightarrow> p a < p b\"\n\ndefinition\n bot :: \"alt \\<Rightarrow> pref \\<Rightarrow> bool\" (infixr \"\\<cdot><\" 60) where\n\"b \\<cdot>< p  \\<equiv>  \\<forall>a. a \\<noteq> b \\<longrightarrow> p b < p a\"\n\ndefinition\n extreme :: \"pref \\<Rightarrow> alt \\<Rightarrow> bool\" where\n\"extreme p b  \\<equiv>  b \\<cdot>< p \\<or> p <\\<cdot> b\"\n\nabbreviation\n\"Extreme P b == \\<forall>i. extreme (P i) b\"\n\n\n\nlemma less_if_bot[simp]: \"\\<lbrakk> b \\<cdot>< p; x \\<noteq> b \\<rbrakk> \\<Longrightarrow> p b < p x\"\nby(simp add:bot_def)\n\nlemma [simp]: \"\\<lbrakk> p <\\<cdot> b; x \\<noteq> b \\<rbrakk> \\<Longrightarrow> p x < p b\"\nby(simp add:top_def)\n\nlemma [simp]: assumes top: \"p <\\<cdot> b\" shows \"\\<not> p b < p c\"\nproof (cases)\n  assume \"b = c\" thus ?thesis by simp\nnext\n  assume \"b \\<noteq> c\"\n  with top have \"p c < p b\" by (simp add:eq_sym_conv)\n  thus ?thesis by simp\nqed\n\nlemma not_less_if_bot[simp]:\n  assumes bot: \"b \\<cdot>< p\" shows \"\\<not> p c < p b\"\nproof (cases)\n  assume \"b = c\" thus ?thesis by simp\nnext\n  assume \"b \\<noteq> c\"\n  with bot have \"p b < p c\" by (simp add:eq_sym_conv)\n  thus ?thesis by simp\nqed\n\nlemma top_impl_not_bot[simp]: \"p <\\<cdot> b \\<Longrightarrow> \\<not> b \\<cdot>< p\"\nby(unfold bot_def, simp add:alt2)\n\nlemma [simp]: \"extreme p b \\<Longrightarrow> (\\<not> p <\\<cdot> b) = (b \\<cdot>< p)\"\napply(unfold extreme_def)\napply(fastforce dest:top_impl_not_bot)\ndone\n\nlemma [simp]: \"extreme p b \\<Longrightarrow> (\\<not> b \\<cdot>< p) = (p <\\<cdot> b)\"\napply(unfold extreme_def)\napply(fastforce dest:top_impl_not_bot)\ndone\n\ntext\\<open>Auxiliary construction to hide details of preference model.\\<close>\n\ndefinition\n mktop :: \"pref \\<Rightarrow> alt \\<Rightarrow> pref\" where\n\"mktop p b \\<equiv> p(b := Max(range p) + 1)\"\n\ndefinition\n mkbot :: \"pref \\<Rightarrow> alt \\<Rightarrow> pref\" where\n\"mkbot p b \\<equiv> p(b := Min(range p) - 1)\"\n\ndefinition\n between :: \"pref \\<Rightarrow> alt \\<Rightarrow> alt \\<Rightarrow> alt \\<Rightarrow> pref\" where\n\"between p a b c \\<equiv> p(b := (p a + p c)/2)\"\n\ntext\\<open>To make things simpler:\\<close>\ndeclare between_def[simp]\n\nlemma [simp]: \"a \\<noteq> b \\<Longrightarrow> mktop p b a = p a\"\nby(simp add:mktop_def)\n\nlemma [simp]: \"a \\<noteq> b \\<Longrightarrow> mkbot p b a = p a\"\nby(simp add:mkbot_def)\n\nlemma [simp]: \"a \\<noteq> b \\<Longrightarrow> p a < mktop p b b\"\nby(simp add:mktop_def finite_alt)\n\nlemma [simp]: \"a \\<noteq> b \\<Longrightarrow> mkbot p b b < p a\"\nby(simp add:mkbot_def finite_alt)\n\nlemma [simp]: \"mktop p b <\\<cdot> b\"\nby(simp add:mktop_def top_def finite_alt)\n\nlemma [simp]: \"\\<not> b \\<cdot>< mktop p b\"\nby(simp add:mktop_def bot_def alt2 finite_alt)\n\nlemma [simp]: \"a \\<noteq> b \\<Longrightarrow> \\<not> P p a < mkbot (P p) b b\"\nproof (simp add:mkbot_def finite_alt)\n  have \"\\<not> P p a + 1 < P p a\" by simp\n  thus \"\\<exists>x. \\<not> P p a + 1 < P p x\" ..\nqed\n\ntext\\<open>The proof starts here.\\<close>\n\nlocale arrow =\nfixes F :: \"prof \\<Rightarrow> pref\"\nassumes unanimity: \"(\\<And>i. P i a < P i b) \\<Longrightarrow> F P a < F P b\"\nand IIA:\n\"(\\<And>i. (P i a < P i b) = (P' i a < P' i b)) \\<Longrightarrow>\n (F P a < F P b) = (F P' a < F P' b)\"\nbegin\n\nlemmas IIA' = IIA[THEN iffD1]\n\ndefinition\n dictates :: \"indi \\<Rightarrow> alt \\<Rightarrow> alt \\<Rightarrow> bool\" (\"_ dictates _ < _\") where\n\"(i dictates a < b)  \\<equiv>  \\<forall>P. P i a < P i b \\<longrightarrow> F P a < F P b\"\ndefinition\n dictates2 :: \"indi \\<Rightarrow> alt \\<Rightarrow> alt \\<Rightarrow> bool\" (\"_ dictates _,_\") where\n\"(i dictates a,b)  \\<equiv>  (i dictates a < b) \\<and> (i dictates b < a)\"\ndefinition\n dictatesx:: \"indi \\<Rightarrow> alt \\<Rightarrow> bool\" (\"_ dictates'_except _\") where\n\"(i dictates_except c)  \\<equiv>  \\<forall>a b. c \\<notin> {a,b} \\<longrightarrow> (i dictates a<b)\"\ndefinition\n dictator :: \"indi \\<Rightarrow> bool\" where\n\"dictator i  \\<equiv>  \\<forall>a b. (i dictates a<b)\"\n\ndefinition\n pivotal :: \"indi \\<Rightarrow> alt \\<Rightarrow> bool\" where\n\"pivotal i b \\<equiv>\n \\<exists>P. Extreme P b  \\<and>  b \\<cdot>< P i  \\<and>  b \\<cdot>< F P  \\<and>\n     F (P(i := mktop (P i) b)) <\\<cdot> b\"\n\nlemma all_top[simp]: \"\\<forall>i. P i <\\<cdot> b \\<Longrightarrow> F P <\\<cdot> b\"\nby (unfold top_def) (simp add: unanimity)\n\nlemma not_extreme:\n  assumes nex: \"\\<not> extreme p b\"\n  shows \"\\<exists>a c. distinct[a,b,c] \\<and> \\<not> p a < p b \\<and> \\<not> p b < p c\"\nproof -\n  obtain a c where abc: \"a \\<noteq> b \\<and> \\<not> p a < p b\" \"b \\<noteq> c \\<and> \\<not> p b < p c\"\n    using nex by (unfold extreme_def top_def bot_def) fastforce\n  show ?thesis\n  proof (cases \"a = c\")\n    assume \"a \\<noteq> c\" thus ?thesis using abc by simp blast\n  next\n    assume ac: \"a = c\"\n    obtain d where d: \"distinct[a,b,d]\" using abc third_alt by blast\n    show ?thesis\n    proof (cases \"p b < p d\")\n      case False thus ?thesis using abc d by blast\n    next\n      case True\n      hence db: \"\\<not> p d < p b\" by arith\n      from d have \"distinct[d,b,c]\" by(simp add:ac eq_sym_conv)\n      thus ?thesis using abc db by blast\n    qed\n  qed\nqed\n\nlemma extremal:\n  assumes extremes: \"Extreme P b\" shows \"extreme (F P) b\"\nproof (rule ccontr)\n  assume nec: \"\\<not> extreme (F P) b\"\n  hence \"\\<exists>a c. distinct[a,b,c] \\<and> \\<not> F P a < F P b \\<and> \\<not> F P b < F P c\"\n    by(rule not_extreme)\n  then obtain a c where d: \"distinct[a,b,c]\" and\n    ab: \"\\<not> F P a < F P b\" and bc: \"\\<not> F P b < F P c\" by blast\n  let ?P = \"\\<lambda>i. if P i <\\<cdot> b then between (P i) a c b\n                else (P i)(c := P i a + 1)\"\n  have \"\\<not> F ?P a < F ?P b\"\n    using extremes d by(simp add:IIA[of _ _ _ P] ab)\n  moreover have \"\\<not> F ?P b < F ?P c\"\n    using extremes d by(simp add:IIA[of _ _ _ P] bc eq_sym_conv)\n  moreover have \"F ?P a < F ?P c\" by(rule unanimity)(insert d, simp)\n  ultimately show False by arith\nqed\n\n\nlemma pivotal_ind: assumes fin: \"finite D\"\n  shows \"\\<And>P. \\<lbrakk> D = {i. b \\<cdot>< P i}; Extreme P b; b \\<cdot>< F P \\<rbrakk>\n  \\<Longrightarrow> \\<exists>i. pivotal i b\" (is \"\\<And>P. ?D D P \\<Longrightarrow> ?E P \\<Longrightarrow> ?B P \\<Longrightarrow> _\")\nusing fin\nproof (induct)\n  case (empty P)\n  from empty(1,2) have \"\\<forall>i. P i <\\<cdot> b\" by simp\n  hence \"F P <\\<cdot> b\" by simp\n  hence False using empty by(blast dest:top_impl_not_bot)\n  thus ?case ..\nnext\n  fix D i P\n  assume IH: \"\\<And>P. ?D D P \\<Longrightarrow> ?E P \\<Longrightarrow> ?B P \\<Longrightarrow> \\<exists>i. pivotal i b\"\n    and \"?E P\" and \"?B P\" and insert: \"insert i D = {i. b \\<cdot>< P i}\" and \"i \\<notin> D\"\n  from insert have \"b \\<cdot>< P i\" by blast\n  let ?P = \"P(i := mktop (P i) b)\"\n  show \"\\<exists>i. pivotal i b\"\n  proof (cases \"F ?P <\\<cdot> b\")\n    case True\n    have \"pivotal i b\"\n    proof -\n      from \\<open>?E P\\<close> \\<open>?B P\\<close> \\<open>b \\<cdot>< P i\\<close> True\n      show ?thesis by(unfold pivotal_def, blast)\n    qed\n    thus ?thesis ..\n  next\n    case False\n    have \"D = {i. b \\<cdot>< ?P i}\"\n      by (rule set_eqI) (simp add:\\<open>i \\<notin> D\\<close>, insert insert, blast)\n    moreover have \"Extreme ?P b\"\n      using \\<open>?E P\\<close> by (simp add:extreme_def)\n    moreover have \"b \\<cdot>< F ?P\"\n      using extremal[OF \\<open>Extreme ?P b\\<close>] False by(simp del:fun_upd_apply)\n    ultimately show ?thesis by(rule IH)\n  qed\nqed\n\nlemma pivotal_exists: \"\\<exists>i. pivotal i b\"\nproof -\n  let ?P = \"(\\<lambda>_ a. if a=b then 0 else 1)::prof\"\n  have \"Extreme ?P b\" by(simp add:extreme_def bot_def)\n  moreover have \"b \\<cdot>< F ?P\"\n    by(simp add:bot_def unanimity del: less_if_bot not_less_if_bot)\n  ultimately show \"\\<exists>i. pivotal i b\"\n    by (rule pivotal_ind[OF finite_subset[OF subset_UNIV finite_indi] refl])\nqed\n\n\nlemma pivotal_xdictates: assumes pivo: \"pivotal i b\"\n  shows \"i dictates_except b\"\nproof -\n  have \"\\<And>a c. \\<lbrakk> a \\<noteq> b; b \\<noteq> c \\<rbrakk> \\<Longrightarrow> i dictates a < c\"\n  proof (unfold dictates_def, intro allI impI)\n    fix a c and P::prof\n    assume abc: \"a \\<noteq> b\" \"b \\<noteq> c\" and\n           ac: \"P i a < P i c\"\n    show \"F P a < F P c\"\n    proof -\n      obtain P1 P2 where\n        \"Extreme P1 b\" and \"b \\<cdot>< F P1\" and \"b \\<cdot>< P1 i\" and \"F P2 <\\<cdot> b\" and\n        [simp]: \"P2 = P1(i := mktop (P1 i) b)\"\n        using pivo by (unfold pivotal_def) fast\n      let ?P = \"\\<lambda>j. if j=i then between (P j) a b c\n                    else if P1 j <\\<cdot> b then mktop (P j) b else mkbot (P j) b\"\n      have eq: \"(F P a < F P c) = (F ?P a < F ?P c)\"\n        using abc by - (rule IIA, auto)\n      have \"F ?P a < F ?P b\"\n      proof (rule IIA')\n        fix j show \"(P2 j a < P2 j b) = (?P j a < ?P j b)\"\n          using \\<open>Extreme P1 b\\<close> by(simp add: ac)\n      next\n        show \"F P2 a < F P2 b\"\n          using \\<open>F P2 <\\<cdot> b\\<close> abc by(simp add: eq_sym_conv)\n      qed\n      also have \"\\<dots> < F ?P c\"\n      proof (rule IIA')\n        fix j show \"(P1 j b < P1 j c) = (?P j b < ?P j c)\"\n          using \\<open>Extreme P1 b\\<close> \\<open>b \\<cdot>< P1 i\\<close> by(simp add: ac)\n      next\n        show \"F P1 b < F P1 c\"\n          using \\<open>b \\<cdot>< F P1\\<close> abc by(simp add: eq_sym_conv)\n      qed\n      finally show ?thesis by(simp add:eq)\n    qed\n  qed\n  thus ?thesis  by(unfold dictatesx_def) fast\nqed\n\nlemma pivotal_is_dictator:\n  assumes pivo: \"pivotal i b\" and ab: \"a \\<noteq> b\" and d: \"j dictates a,b\"\n  shows \"i = j\"\nproof (rule ccontr)\n  assume pd: \"i \\<noteq> j\"\n  obtain P1 P2 where \"Extreme P1 b\" and \"b \\<cdot>< F P1\" and \"F P2 <\\<cdot> b\" and\n    P2: \"P2 = P1(i := mktop (P1 i) b)\"\n    using pivo by (unfold pivotal_def) fast\n  have \"~(P1 j a < P1 j b)\" (is \"~ ?ab\")\n  proof\n    assume \"?ab\"\n    hence \"F P1 a < F P1 b\" using d by(simp add: dictates_def dictates2_def)\n    with \\<open>b \\<cdot>< F P1\\<close> show False by simp\n  qed\n  hence \"P1 j b < P1 j a\" using \\<open>Extreme P1 b\\<close>[THEN spec, of j] ab\n    unfolding extreme_def top_def bot_def by metis\n  hence \"P2 j b < P2 j a\" using pd by (simp add:P2)\n  hence \"F P2 b < F P2 a\" using d by(simp add: dictates_def dictates2_def)\n  with \\<open>F P2 <\\<cdot> b\\<close> show False by simp\nqed\n\n\ntheorem dictator: \"\\<exists>i. dictator i\"\nproof-\n  from pivotal_exists[of b] obtain i where pivo: \"pivotal i b\" ..\n  { fix a assume neq: \"a \\<noteq> b\" have \"i dictates a,b\"\n    proof -\n      obtain c where dist: \"distinct[a,b,c]\"\n        using neq third_alt by blast\n      obtain j where \"pivotal j c\" using pivotal_exists by fast\n      hence \"j dictates_except c\" by(rule pivotal_xdictates)\n      hence b: \"j dictates a,b\" \n        using dist by(simp add:dictatesx_def dictates2_def eq_sym_conv)\n      with pivo neq have \"i = j\" by(rule pivotal_is_dictator)\n      thus ?thesis using b by simp\n    qed\n  }\n  with pivotal_xdictates[OF pivo] have \"dictator i\"\n    by(simp add: dictates_def dictatesx_def dictates2_def dictator_def)\n      (metis less_le)\n  thus ?thesis ..\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/ArrowImpossibilityGS/Thys/Arrow_Utility.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.903294209307224, "lm_q2_score": 0.8244619220634457, "lm_q1q2_score": 0.7447316799942144}}
{"text": "section \\<open> Enumeration Extras \\<close>\n\ntheory Enum_extra\n  imports \"HOL-Library.Code_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": "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/Enum_extra.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8824278633625322, "lm_q2_score": 0.8438951104066293, "lm_q1q2_score": 0.7446765591782102}}
{"text": "(*  Author:     Steven Obua, TU Muenchen *)\n\nsection \\<open>Various algebraic structures combined with a lattice\\<close>\n\ntheory Lattice_Algebras\nimports 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 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 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  assume \"a \\<le> c\" \"b \\<le> c\"\n  then show \"- inf (- a) (- b) \\<le> c\"\n    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    unfolding minus_zero ..\n  also have \"\\<dots> = - inf x 0\"\n    unfolding neg_inf_eq_sup ..\n  finally have \"sup (- x) 0 = - inf x 0\" .\n  then show ?thesis\n    unfolding 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 add_eq_inf_sup[symmetric])\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 \"?l = ?r\")\nproof\n  assume ?l\n  then show ?r\n    apply -\n    apply (rule add_le_imp_le_right[of _ \"uminus b\" _])\n    apply (simp add: add.assoc)\n    done\nnext\n  assume ?r\n  then show ?l\n    apply -\n    apply (rule add_le_imp_le_right[of _ \"b\" _])\n    apply simp\n    done\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 p: \"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 p[OF assms] p[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\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\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  (is \"?lhs \\<longleftrightarrow> ?rhs\")\nproof\n  show ?rhs if ?lhs\n  proof -\n    from that have \"a + a + - a = - a\"\n      by simp\n    then have \"a + (a + - a) = - a\"\n      by (simp only: add.assoc)\n    then have a: \"- a = a\"\n      by simp\n    show ?thesis\n      apply (rule antisym)\n      apply (unfold neg_le_iff_le [symmetric, of a])\n      unfolding a\n      apply simp\n      unfolding zero_le_double_add_iff_zero_le_single_add [symmetric, of a]\n      unfolding that\n      unfolding le_less\n      apply simp_all\n      done\n  qed\n  show ?lhs if ?rhs\n    using that by simp\nqed\n\nlemma zero_less_double_add_iff_zero_less_single_add [simp]: \"0 < a + a \\<longleftrightarrow> 0 < a\"\nproof (cases \"a = 0\")\n  case True\n  then show ?thesis by auto\nnext\n  case False\n  then show ?thesis\n    unfolding less_le\n    apply simp\n    apply rule\n    apply clarify\n    apply rule\n    apply assumption\n    apply (rule notI)\n    unfolding double_zero [symmetric, of a]\n    apply blast\n    done\nqed\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] neg_sup_eq_inf [simp] diff_inf_eq_sup [simp] 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 add: add.assoc[symmetric])\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 add: add.assoc[symmetric])\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 add: prts[symmetric])\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  fix k :: int\n  show \"\\<bar>k\\<bar> = sup k (- k)\"\n    by (auto simp add: sup_int_def)\nqed\n\ninstance real :: lattice_ring\nproof\n  fix a :: real\n  show \"\\<bar>a\\<bar> = sup a (- a)\"\n    by (auto simp add: sup_real_def)\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/Lattice_Algebras.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278664544911, "lm_q2_score": 0.8438951045175643, "lm_q1q2_score": 0.7446765565908241}}
{"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.*)\n  theory TIP_prop_45\nimports \"../../Test_Base\"\nbegin\n\ndatatype ('a, 'b) pair = pair2 \"'a\" \"'b\"\n\ndatatype 'a list = nil2 | cons2 \"'a\" \"'a list\"\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\ntheorem property0 :\n  \"((zip (cons2 x xs) (cons2 y ys)) = (cons2 (pair2 x y) (zip xs ys)))\"\n  find_proof DInd\n  apply (induct arbitrary: xs)\n  apply auto\n  done\n\ntheorem property0' :\n  \"((zip (cons2 x xs) (cons2 y ys)) = (cons2 (pair2 x y) (zip xs ys)))\"\n  (*Why \"induct xs\"?\n    Because of \"(zip xs ys)\" on the right-hand side.*)\n  apply (induct xs)\n  apply auto\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/Isaplanner/Isaplanner/TIP_prop_45.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278602705731, "lm_q2_score": 0.8438951084436077, "lm_q1q2_score": 0.7446765548366959}}
{"text": "theory IMP\n  imports Main\nbegin\n\n(* Data type definitions *)\n\n(* Arithmetic expression (i.e. aexp) primitives from 3.1.1 *)\ntype_synonym vname = string\ndatatype aexp =\n  N int\n  | V vname\n  | Plus aexp aexp\n\n(* Variable state primitives from 3.1.2 *)\ntype_synonym val = int\ntype_synonym state = \"vname \\<Rightarrow> val\"\n\n(* Boolean expression (i.e. bexp) primitive from 3.2 *)\ndatatype bexp =\n  Bc bool\n  | Not bexp\n  | And bexp bexp\n  | Less aexp aexp\n\n(* IMP language command (i.e. com) specification from 7.1 *)\ndatatype com =\n  SKIP\n  | Assign vname aexp (\"_ ::= _\")\n  | Seq com com (\"_ ;; _\")\n  | If bexp com com (\"IF _ THEN _ ELSE _\")\n  | While bexp com (\"WHILE _ DO _\")\n\n\n(* Convenient helpers *)\nfun Or :: \"bexp \\<Rightarrow> bexp \\<Rightarrow> bexp\" where\n\"Or a b = (Not (And (Not a) (Not b)))\"\n\nfun Cond :: \"bexp \\<Rightarrow> bexp \\<Rightarrow> bexp\" where\n\"Cond a b = (Or (Not a) b)\"\n\nfun VarEq :: \"vname \\<Rightarrow> aexp \\<Rightarrow> bexp\" where\n\"VarEq x a = (And (Not (Less (V x) a)) (Not (Less a (V x))))\"\n\n(* Semantic definitions *)\n\n(* Arithmetic expression evaluation from 3.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 a1 a2) s = aval a1 s + aval a2 s\"\n\n(* Boolean expression evaluation from 3.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 b1 b2) s = (bval b1 s \\<and> bval b2 s)\" |\n\"bval (Less a1 a2) s = (aval a1 s < aval a2 s)\"\n\n(* Big-step semantics for IMP from 7.2.1 *)\ninductive big_step :: \"com \\<times> state \\<Rightarrow> state \\<Rightarrow> bool\"\n  (infix \"\\<Rightarrow>\" 55) where\nSkip: \"(SKIP,s) \\<Rightarrow> s\" |\nAssign: \"(x ::= a,s) \\<Rightarrow> s(x := aval a s)\" |\nSeq: \"\n  \\<lbrakk> (c1,s1) \\<Rightarrow> s2; (c2,s2) \\<Rightarrow> s3 \\<rbrakk>\n  \\<Longrightarrow> (c1;;c2,s1) \\<Rightarrow> s3\n\" |\nIfTrue: \"\n  \\<lbrakk> bval b s; (c1,s) \\<Rightarrow>t \\<rbrakk>\n  \\<Longrightarrow> (IF b THEN c1 ELSE c2,s) \\<Rightarrow> t\n\" |\nIfFalse: \"\n  \\<lbrakk> \\<not>bval b s; (c2,s) \\<Rightarrow> t \\<rbrakk>\n  \\<Longrightarrow> (IF b THEN c1 ELSE c2,s) \\<Rightarrow> t\n\" |\nWhileFalse: \"\n  \\<not>bval b s\n  \\<Longrightarrow> (WHILE b DO c,s) \\<Rightarrow> s\n\" |\nWhileTrue: \"\n  \\<lbrakk> bval b s1; (c,s1) \\<Rightarrow> s2; (WHILE b DO c,s2) \\<Rightarrow> s3 \\<rbrakk>\n  \\<Longrightarrow> (WHILE b DO c,s1) \\<Rightarrow> s3\n\"\n\n(* Big step tweaks to simplify usage as found in\n   the implementation included in the Isabelle source *)\ndeclare big_step.intros [intro]\nlemmas big_step_induct = big_step.induct[split_format(complete)]\ninductive_cases SkipE[elim!]: \"(SKIP,s) \\<Rightarrow> t\"\ninductive_cases AssignE[elim!]: \"(x ::= c,s) \\<Rightarrow> t\"\ninductive_cases SeqE[elim!]: \"(c1 ;; c2,s) \\<Rightarrow> t\"\ninductive_cases IfE[elim!]: \"(IF b THEN c1 ELSE c2,s) \\<Rightarrow> t\"\ninductive_cases WhileE[elim]: \"(WHILE b DO c,s) \\<Rightarrow> t\"\n\n(* Small-step semantic rules from 7.3 *)\ninductive small_step :: \"com \\<times> state \\<Rightarrow> com \\<times> state \\<Rightarrow> bool\"\n  (infix \"\\<rightarrow>\" 55) where\nAssign: \"(x ::= a,s) \\<rightarrow> (SKIP,s(x := aval a s))\" |\nSeq1: \"(SKIP;;c2,s) \\<rightarrow> (c2,s)\" |\nSeq2: \"(c1,s) \\<rightarrow> (c1',s') \\<Longrightarrow> (c1;;c2,s) \\<rightarrow> (c1';;c2,s')\" |\nIfTrue: \"bval b s \\<Longrightarrow> (IF b THEN c1 ELSE c2,s) \\<rightarrow> (c1,s)\" |\nIfFalse: \"\\<not>bval b s \\<Longrightarrow> (IF b THEN c1 ELSE c2,s) \\<rightarrow> (c2,s)\" |\nWhile: \"(WHILE b DO c,s) \\<rightarrow> (IF b THEN c;;WHILE b DO c ELSE SKIP,s)\"\n\n\n(* Semantic helpers *)\n\n(* Rule inversion equivalence lemmas from 7.2.3 *)\nlemma skip_state_equiv:\n  \"(SKIP,s) \\<Rightarrow> t \\<longleftrightarrow> t = s\" (is \"?LHS \\<longleftrightarrow> ?RHS\")\nproof\n  assume \"?LHS\"\n  thus \"?RHS\" by cases\nnext\n  assume \"?RHS\"\n  thus \"?LHS\" by (simp add: Skip)\nqed\n\nlemma assign_state:\n  \"(x ::= a,s) \\<Rightarrow> t \\<longleftrightarrow> t = s(x := aval a s)\"\n  (is \"?LHS \\<longleftrightarrow> ?RHS\")\nproof\n  assume \"?LHS\"\n  thus \"?RHS\" by cases\nnext\n  assume \"?RHS\"\n  thus \"?LHS\" using big_step.Assign by blast\nqed\n\nlemma inter_seq:\n  \"(c1 ;; c2,s1) \\<Rightarrow> s3\n    \\<longleftrightarrow> (\\<exists>s2. ((c1,s1) \\<Rightarrow> s2 \\<and> (c2,s2) \\<Rightarrow> s3))\"\n  (is \"?LHS \\<longleftrightarrow> ?RHS\")\nproof\n  assume \"?LHS\"\n  thus \"?RHS\"\n  proof cases\n    case Seq thus ?thesis by auto\n  qed\nnext\n  assume \"?RHS\"\n  thus \"?LHS\" using Seq by blast\nqed\n\nlemma while_split:\n  \"(WHILE b DO c,s) \\<Rightarrow> t\n    \\<longleftrightarrow> (\n      \\<not> bval b s \\<and> t = s\n      \\<or> bval b s\n        \\<and> (\\<exists>s'. (c,s) \\<Rightarrow> s'\n            \\<and> (WHILE b DO c,s') \\<Rightarrow> t))\"\n  (is \"?LHS \\<longleftrightarrow> ?RHS\")\nproof\n  assume \"?LHS\"\n  thus \"?RHS\"\n  proof cases\n    case WhileFalse\n    thus ?thesis by auto\n  next\n    case WhileTrue\n    thus ?thesis by auto\n  qed\nnext\n  assume \"?RHS\"\n  thus \"?LHS\"\n    using WhileFalse WhileTrue by blast\nqed\n\n(* Associativity of Seq from 7.2.3 *)\nlemma seq_assoc:\n  \"((c1 ;; c2) ;; c3,s) \\<Rightarrow> s'\n   \\<longleftrightarrow> (c1 ;; (c2 ;; c3),s) \\<Rightarrow> s'\"\n  (is \"?LHS \\<longleftrightarrow> ?RHS\")\nproof\n  assume \"?LHS\"\n  then obtain s1 s2 where\n    \"(c1,s) \\<Rightarrow> s1\" and\n    \"(c2,s1) \\<Rightarrow> s2\" and\n    \"(c3,s2) \\<Rightarrow> s'\"\n    using inter_seq by blast\n  thus \"?RHS\" by (simp add: Seq)\nnext\n  assume \"?RHS\"\n  then obtain s1 s2 where\n    \"(c1,s) \\<Rightarrow> s1\" and\n    \"(c2,s1) \\<Rightarrow> s2\" and\n    \"(c3,s2) \\<Rightarrow> s'\"\n    using inter_seq by blast\n  thus \"?LHS\"\n    using Seq by blast\nqed\n\n(* Big-step equivalence from 7.2.4 *)\nabbreviation equiv_c :: \"com \\<Rightarrow> com \\<Rightarrow> bool\"\n  (infix \"\\<sim>\" 50) where\n\"c \\<sim> c' \\<equiv> (\\<forall>s. \\<forall>t. ((c,s) \\<Rightarrow> t = (c',s) \\<Rightarrow> t))\"\n\n(* While is equivalent to a single unfold of itself *)\nlemma while_is_unfolded_while:\n  \"(WHILE b DO c)\n    \\<sim> (IF b THEN c ;; WHILE b DO c ELSE SKIP)\"\n  (is \"?LHS \\<sim> ?RHS\")\nproof -\n  have \"(?RHS,s) \\<Rightarrow> t\" if assm: \"(?LHS,s) \\<Rightarrow> t\" for s t\n  proof -\n    from assm show ?thesis\n    proof cases\n      case WhileTrue\n      from this `bval b s` `(?LHS,s) \\<Rightarrow> t`\n      obtain s'\n        where \"(c,s) \\<Rightarrow> s'\" and \"(?LHS,s') \\<Rightarrow> t\"\n        by blast\n      hence \"(c ;; ?LHS,s) \\<Rightarrow> t\" by (rule Seq)\n      thus ?thesis using `bval b s` by auto\n    next\n      case WhileFalse\n      thus ?thesis by auto\n    qed\n  qed\n  moreover\n  have \"(?LHS,s) \\<Rightarrow> t\" if assm: \"(?RHS,s) \\<Rightarrow> t\" for s t\n  proof -\n    from assm show ?thesis\n    proof cases\n      case IfTrue\n      from this inter_seq obtain s'\n        where \"(c,s) \\<Rightarrow> s'\" and \"(?LHS,s') \\<Rightarrow> t\"\n        by blast\n      thus ?thesis using IfTrue by blast\n    next\n      case IfFalse\n      hence \"s = t\" using skip_state_equiv by simp\n      thus ?thesis using IfFalse by blast\n    qed\n  qed\n  ultimately\n  show ?thesis by blast\nqed\n\n(* The previous proof is likely clearer,\n   but all that inductive_case stuff allows\n   full auto here *)\nlemma \"(WHILE b DO c) \\<sim> (IF b THEN c ;; WHILE b DO c ELSE SKIP)\"\n  by blast\n\n(* A command in both if clauses is equivalent\n   to the command (from 7.2.4) *)\nlemma if_both_com_is_com:\n  \"(IF b THEN c ELSE c) \\<sim> c\"\n  by blast\n\n(* Equivalent commands yeild equivalent while loops\n   (from 7.2.4) *)\nlemma while_equiv_complex:\n  \"\\<lbrakk> (WHILE b DO c,s) \\<Rightarrow> t ; c \\<sim> c' \\<rbrakk>\n    \\<Longrightarrow> (WHILE b DO c',s) \\<Rightarrow> t\"\n  apply (induction \"WHILE b DO c\" s t arbitrary: b c rule: big_step_induct)\n   apply blast\n  apply blast\n  done\n\ncorollary while_equiv:\n  \"c \\<sim> c' \\<Longrightarrow> ((WHILE b DO c) \\<sim> (WHILE b DO c'))\"\n  by (meson while_equiv_complex)\n\n(* Big-step equivalence is an equivalence relation *)\ntheorem refl_equiv_c: \"c \\<sim> c\" by auto\ntheorem sym_equiv_c: \"c1 \\<sim> c2 \\<Longrightarrow> c2 \\<sim> c1\" by auto\ntheorem trans_equiv_c: \"c1 \\<sim> c2 \\<and> c2 \\<sim> c3 \\<Longrightarrow> c1 \\<sim> c3\"\n  by auto\n\n(* IMP is deterministic from 7.2.5 *)\ntheorem imp_deterministic:\n  \"(c,s) \\<Rightarrow> t \\<Longrightarrow> (c,s) \\<Rightarrow> t' \\<Longrightarrow> t' = t\"\nproof (induction arbitrary: t' rule: big_step.induct)\n  fix b c s s1 t t'\n  assume \"bval b s\"\n    and \"(c,s) \\<Rightarrow> s1\"\n    and \"(WHILE b DO c,s1) \\<Rightarrow> t\"\n  assume IHc: \"\\<And>t'. (c,s) \\<Rightarrow> t' \\<Longrightarrow> t' = s1\"\n  assume IHw: \"\\<And>t'. (WHILE b DO c,s1) \\<Rightarrow> t' \\<Longrightarrow> t' = t\"\n  assume \"(WHILE b DO c,s) \\<Rightarrow> t'\"\n  with `bval b s` obtain s1' where\n    c: \"(c,s) \\<Rightarrow> s1'\" and\n    w: \"(WHILE b DO c,s1') \\<Rightarrow> t'\"\n    by auto\n  from c IHc have \"s1' = s1\" by blast\n  with w IHw show \"t' = t\" by blast\nqed blast+\n\n(* Reflexive transitive closure from 4.5.2 *)\n(* Needed for closure of small-step semantic *)\ninductive star :: \"('a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> bool\"\n  for r where\nrefl: \"star r x x\" |\nstep: \"r x y \\<Longrightarrow> star r y z \\<Longrightarrow> star r x z\"\n\n(* Closure of small-step sequences from 7.3 *)\nabbreviation small_step_closure :: \"com \\<times> state \\<Rightarrow> com \\<times> state \\<Rightarrow> bool\"\n  (infix \"\\<rightarrow>*\" 55) where\n\"x \\<rightarrow>* y \\<equiv> star small_step x y\"\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/ch7/IMP.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278664544911, "lm_q2_score": 0.8438950966654772, "lm_q1q2_score": 0.7446765496619236}}
{"text": "(*\n  File:     Furstenberg_Topology.thy\n  Author:   Manuel Eberl, TU M\u00fcnchen\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{furstenberg}. 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{zulfeqarr}. We follow the exposition by Dirmeier~\\cite{dirmeier}.\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)\n  show \"\\<forall>k. ?I (n + m) k \\<le> ?I n k + ?I m k\"\n    using q_gt_1 by auto\nqed\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 allI 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 \" \\<forall>na. (if na = 0 \\<or> int na dvd n then 0 else 1 / q ^ na)\n         \\<le> (if na \\<in> {0, 1, p', n'} then 0 else (1 / q) ^ na)\"\n      using q_gt_1 assms 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 allI 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": "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/Furstenberg_Topology/Furstenberg_Topology.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8438950907764118, "lm_q2_score": 0.8824278680004706, "lm_q1q2_score": 0.7446765457698926}}
{"text": "section \\<open>Introduction and Definition\\<close>\n\ntheory Definitions\n  imports \"HOL-Probability.Independent_Family\"\nbegin\n\ntext \\<open>Universal hash families are commonly used in randomized algorithms and data structures to\nrandomize the input of algorithms, such that probabilistic methods can be employed without requiring\nany assumptions about the input distribution.\n\nIf we regard a family of hash functions from a domain $D$ to a finite range $R$ as a uniform probability\nspace, then the family is $k$-universal if:\n\\begin{itemize}\n\\item For each $x \\in D$ the evaluation of the functions at $x$ forms a uniformly distributed random variable on $R$.\n\\item The evaluation random variables for $k$ or fewer distinct domain elements form an\nindependent family of random variables.\n\\end{itemize}\n\nThis definition closely follows the definition from Vadhan~\\<^cite>\\<open>\\<open>\\textsection 3.5.5\\<close> in \"vadhan2012\"\\<close>, with the minor\nmodification that independence is required not only for exactly $k$, but also for \\emph{fewer} than $k$ distinct\ndomain elements. The correction is due to the fact that in the corner case where $D$ has fewer than $k$ elements,\nthe second part of their definition becomes void. In the formalization this helps avoid an unnecessary assumption in\nthe theorems.\n\nThe following definition introduces the notion of $k$-wise independent random variables:\\<close>\n\ndefinition (in prob_space) k_wise_indep_vars where\n  \"k_wise_indep_vars k M' X I =\n    (\\<forall>J \\<subseteq> I. card J \\<le> k \\<longrightarrow> finite J \\<longrightarrow> indep_vars M' X J)\"\n\nlemma (in prob_space) k_wise_indep_vars_subset:\n  assumes \"k_wise_indep_vars k M' X I\"\n  assumes \"J \\<subseteq> I\"\n  assumes \"finite J\"\n  assumes \"card J \\<le> k\"\n  shows \"indep_vars M' X J\"\n  using assms\n  by (simp add:k_wise_indep_vars_def)\n\ntext \\<open>Similarly for a finite non-empty set $A$ the predicate @{term \"uniform_on X A\"} indicates that\nthe random variable is uniformly distributed on $A$:\\<close>\n\ndefinition (in prob_space) \"uniform_on X A = (\n  distr M (count_space UNIV) X = uniform_measure (count_space UNIV) A \\<and>\n  A \\<noteq> {} \\<and> finite A \\<and> random_variable (count_space UNIV) X)\"\n\nlemma (in prob_space) uniform_onD:\n  assumes \"uniform_on X A\"\n  shows \"prob {\\<omega> \\<in> space M. X \\<omega> \\<in> B} = card (A \\<inter> B) / card A\"\nproof -\n  have \"prob {\\<omega> \\<in> space M. X \\<omega> \\<in> B} = prob (X -` B \\<inter> space M)\"\n    by (subst Int_commute, simp add:vimage_def Int_def)\n  also have \"... = measure (distr M (count_space UNIV) X) B\"\n    using assms by (subst measure_distr, auto simp:uniform_on_def)\n  also have \"... = measure (uniform_measure (count_space UNIV) A) B\"\n    using assms by (simp add:uniform_on_def)\n  also have \"... = card (A \\<inter> B) / card A\"\n    using assms by (subst measure_uniform_measure, auto simp:uniform_on_def)+\n  finally show ?thesis by simp\nqed\n\ntext \\<open>With the two previous definitions it is possible to define the $k$-universality condition for a family\nof hash functions from $D$ to $R$:\\<close>\n\ndefinition (in prob_space) \"k_universal k X D R = (\n  k_wise_indep_vars k (\\<lambda>_. count_space UNIV) X D \\<and>\n  (\\<forall>i \\<in> D. uniform_on (X i) R))\"\n\ntext \\<open>Note: The definition is slightly more generic then the informal specification from above.\nThis is because usually a family is formed by a single function with a variable seed parameter. Instead of\nchoosing a random function from a probability space, a random seed is chosen from the probability space\nwhich parameterizes the hash function.\n\nThe following section contains some preliminary results about independent families\nof random variables.\nSection~\\ref{sec:carter_wegman} introduces the Carter-Wegman hash family, which is an\nexplicit construction of $k$-universal families for arbitrary $k$ using polynomials over finite fields.\nThe last section contains a proof that the factor ring of the integers modulo a prime ideal is a finite field,\nfollowed by an isomorphic construction of prime fields over an initial segment of the natural numbers.\\<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/Universal_Hash_Families/Definitions.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8438950986284991, "lm_q2_score": 0.8824278587245935, "lm_q1q2_score": 0.744676544870926}}
{"text": "section \\<open>Well-foundedness of Relations Defined as Predicate Functions\\<close>\n\ntheory Well_founded\n  imports Main\nbegin\n\nlocale well_founded =\n  fixes R :: \"'a \\<Rightarrow> 'a \\<Rightarrow> bool\" (infix \"\\<sqsubset>\" 70)\n  assumes\n    wf: \"wfP (\\<sqsubset>)\"\nbegin\n\nlemmas induct = wfP_induct_rule[OF wf]\n\nend\n\nsubsection \\<open>Lexicographic product\\<close>\n\ncontext\n  fixes\n    r1 :: \"'a \\<Rightarrow> 'a \\<Rightarrow> bool\" and\n    r2 :: \"'b \\<Rightarrow> 'b \\<Rightarrow> bool\"\nbegin\n\ndefinition lex_prodp :: \"'a \\<times> 'b \\<Rightarrow> 'a \\<times> 'b \\<Rightarrow> bool\" where\n  \"lex_prodp x y \\<equiv> r1 (fst x) (fst y) \\<or> fst x = fst y \\<and> r2 (snd x) (snd y)\"\n\nlemma lex_prodp_lex_prod:\n  shows \"lex_prodp x y \\<longleftrightarrow> (x, y) \\<in> lex_prod { (x, y). r1 x y } { (x, y). r2 x y }\"\n  by (auto simp: lex_prod_def lex_prodp_def)\n\nlemma lex_prodp_wfP:\n  assumes\n    \"wfP r1\" and\n    \"wfP r2\"\n  shows \"wfP lex_prodp\"\nproof (rule wfPUNIVI)\n  show \"\\<And>P. \\<forall>x. (\\<forall>y. lex_prodp y x \\<longrightarrow> P y) \\<longrightarrow> P x \\<Longrightarrow> (\\<And>x. P x)\"\n  proof -\n    fix P\n    assume \"\\<forall>x. (\\<forall>y. lex_prodp y x \\<longrightarrow> P y) \\<longrightarrow> P x\"\n    hence hyps: \"(\\<And>y1 y2. lex_prodp (y1, y2) (x1, x2) \\<Longrightarrow> P (y1, y2)) \\<Longrightarrow> P (x1, x2)\" for x1 x2\n      by fast\n    show \"(\\<And>x. P x)\"\n      apply (simp only: split_paired_all)\n      apply (atomize (full))\n      apply (rule allI)\n      apply (rule wfP_induct_rule[OF assms(1), of \"\\<lambda>y. \\<forall>b. P (y, b)\"])\n      apply (rule allI)\n      apply (rule wfP_induct_rule[OF assms(2), of \"\\<lambda>b. P (x, b)\" for x])\n      using hyps[unfolded lex_prodp_def, simplified]\n      by blast\n  qed\nqed\n\nend\n\nlemma lex_prodp_well_founded:\n  assumes\n    \"well_founded r1\" and\n    \"well_founded r2\"\n  shows \"well_founded (lex_prodp r1 r2)\"\n  using well_founded.intro lex_prodp_wfP assms[THEN well_founded.wf] by auto\n\nsubsection \\<open>Lexicographic list\\<close>\n\ncontext\n  fixes order :: \"'a \\<Rightarrow> 'a \\<Rightarrow> bool\"\nbegin\n\ninductive lexp :: \"'a list \\<Rightarrow> 'a list \\<Rightarrow> bool\" where\n  lexp_head: \"order x y \\<Longrightarrow> length xs = length ys \\<Longrightarrow> lexp (x # xs) (y # ys)\" |\n  lexp_tail: \"lexp xs ys \\<Longrightarrow> lexp (x # xs) (x # ys)\"\n\nend\n\nlemma lexp_prepend: \"lexp order ys zs \\<Longrightarrow> lexp order (xs @ ys) (xs @ zs)\"\n  by (induction xs) (simp_all add: lexp_tail)\n\nlemma lexp_lex: \"lexp order xs ys \\<longleftrightarrow> (xs, ys) \\<in> lex {(x, y). order x y}\"\nproof\n  assume \"lexp order xs ys\"\n  thus \"(xs, ys) \\<in> lex {(x, y). order x y}\"\n    by (induction xs ys rule: lexp.induct) simp_all\nnext\n  assume \"(xs, ys) \\<in> lex {(x, y). order x y}\"\n  thus \"lexp order xs ys\"\n    by (auto intro!: lexp_prepend intro: lexp_head simp: lex_conv)\nqed\n\nlemma lex_list_wfP: \"wfP order \\<Longrightarrow> wfP (lexp order)\"\n  by (simp add: lexp_lex wf_lex wfP_def)\n\nlemma lex_list_well_founded:\n  assumes \"well_founded order\"\n  shows \"well_founded (lexp order)\"\n  using well_founded.intro assms(1)[THEN well_founded.wf, THEN lex_list_wfP] 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/VeriComp/Well_founded.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772351648677, "lm_q2_score": 0.8519528076067262, "lm_q1q2_score": 0.7446725545638337}}
{"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_ISortSorts\nimports \"../../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 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 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  \"ordered (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_ISortSorts.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418283357702, "lm_q2_score": 0.8056321866478978, "lm_q1q2_score": 0.7445184019349328}}
{"text": "theory BDD\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 e i (Leaf v) = v\" |\n\"eval e i (Branch b1 b2) = \n  (if e i then eval e (Suc i) b2 else eval e (Suc i) b2)\"\n\nprimrec bdd_unop :: \"(bool \\<Rightarrow> bool) \\<Rightarrow> bdd \\<Rightarrow> bdd\" where\n\"bdd_unop f (Leaf v) = Leaf (f v)\" |\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 v) b = bdd_unop (f v) b\" |\n\"bdd_binop f (Branch b1 b2) b = (case b of \n    Leaf v \\<Rightarrow> Branch (bdd_binop f b1 (Leaf v)) (bdd_binop f b2 (Leaf v))\n  | Branch b1' b2' \\<Rightarrow> Branch (bdd_binop f b1 b1') (bdd_binop f b2 b2'))\"\n\ntheorem bdd_unop_correct: \"\\<forall>i. eval e i (bdd_unop f b) = f (eval e i b)\"\n  apply (induction b)\n   apply (auto)\n  done\n\ntheorem bdd_binop_correct: \"\\<forall>i b2. eval e i (bdd_binop f b1 b2) = f (eval e i b1) (eval e i b2)\"\n  apply (induction b1)\n   apply (auto split: bdd.split)\n   apply (auto simp add: bdd_unop_correct)\n  done\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/BDD.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418116217418, "lm_q2_score": 0.8056321866478979, "lm_q1q2_score": 0.7445183884695736}}
{"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_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/TIP15/TIP15/TIP_sort_MSortBU2IsSort.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587993853654, "lm_q2_score": 0.8376199633332891, "lm_q1q2_score": 0.7444421129533079}}
{"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>\\<open>\"Chaieb2011\"\\<close> \\<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>\\<open>\"paulsonDefiningFunctionsEquivalence2006\"\\<close>, 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, opaque_lifting) 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>\\<open>\"Fine\"\\<close> 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>\\<open>\"petercameronNotesCombinatorics2007\"\\<close> \\<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, opaque_lifting) 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>\\<open>\"bayerDPRMTheoremIsabelle2019\"\\<close> 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": "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/Lucas_Theorem/Lucas_Theorem.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8933094003735664, "lm_q2_score": 0.8333245911726382, "lm_q1q2_score": 0.7444166908569768}}
{"text": "(*\n  File:     Algebraic_Integer_Divisibility.thy\n  Author:   Manuel Eberl, TU M\u00fcnchen\n*)\nsection \\<open>Divisibility of algebraic integers\\<close>\ntheory Algebraic_Integer_Divisibility\n  imports \"Algebraic_Numbers.Algebraic_Numbers\"\nbegin\n\ntext \\<open>\n  In this section, we define a notion of divisibility of algebraic integers: \\<open>y\\<close> is divisible\n  by \\<open>x\\<close> if \\<open>y / x\\<close> is an algebraic integer (or if \\<open>x\\<close> and \\<open>y\\<close> are both zero).\n\n  Technically, the definition does not require \\<open>x\\<close> and \\<open>y\\<close> to be algebraic integers themselves,\n  but we will always use it that way (in fact, in our case \\<open>x\\<close> will always be a rational integer).\n\\<close>\n\ndefinition alg_dvd :: \"'a :: field \\<Rightarrow> 'a \\<Rightarrow> bool\" (infix \"alg'_dvd\" 50) where\n  \"x alg_dvd y \\<longleftrightarrow> (x = 0 \\<longrightarrow> y = 0) \\<and> algebraic_int (y / x)\"\n\nlemma alg_dvd_imp_algebraic_int:\n  fixes x y :: \"'a :: field_char_0\"\n  shows \"x alg_dvd y \\<Longrightarrow> algebraic_int x \\<Longrightarrow> algebraic_int y\"\n  using algebraic_int_times[of \"y / x\" x] by (auto simp: alg_dvd_def)\n\nlemma alg_dvd_0_left_iff [simp]: \"0 alg_dvd x \\<longleftrightarrow> x = 0\"\n  by (auto simp: alg_dvd_def)\n\nlemma alg_dvd_0_right [iff]: \"x alg_dvd 0\"\n  by (auto simp: alg_dvd_def)\n\nlemma one_alg_dvd_iff [simp]: \"1 alg_dvd x \\<longleftrightarrow> algebraic_int x\"\n  by (auto simp: alg_dvd_def)\n\nlemma alg_dvd_of_int [intro]:\n  assumes \"x dvd y\"\n  shows   \"of_int x alg_dvd of_int y\"\nproof (cases \"of_int x = (0 :: 'a)\")\n  case False\n  from assms obtain z where z: \"y = x * z\"\n    by (elim dvdE)\n  have \"algebraic_int (of_int z)\"\n    by auto\n  also have \"of_int z = of_int y / (of_int x :: 'a)\"\n    using False by (simp add: z field_simps)\n  finally show ?thesis\n    using False by (simp add: alg_dvd_def)\nqed (use assms in \\<open>auto simp: alg_dvd_def\\<close>)\n\nlemma alg_dvd_of_nat [intro]:\n  assumes \"x dvd y\"\n  shows   \"of_nat x alg_dvd of_nat y\"\n  using alg_dvd_of_int[of \"int x\" \"int y\"] assms by simp\n\nlemma alg_dvd_of_int_iff [simp]:\n  \"(of_int x :: 'a :: field_char_0) alg_dvd of_int y \\<longleftrightarrow> x dvd y\"\nproof\n  assume \"(of_int x :: 'a) alg_dvd of_int y\"\n  hence \"of_int y / (of_int x :: 'a) \\<in> \\<int>\" and nz: \"of_int x = (0::'a) \\<longrightarrow> of_int y = (0::'a)\"\n    by (auto simp: alg_dvd_def dest!: rational_algebraic_int_is_int)\n  then obtain n where \"of_int y / of_int x = (of_int n :: 'a)\"\n    by (elim Ints_cases)\n  hence \"of_int y = (of_int (x * n) :: 'a)\"\n    unfolding of_int_mult using nz by (auto simp: field_simps)\n  hence \"y = x * n\"\n    by (subst (asm) of_int_eq_iff)\n  thus \"x dvd y\"\n    by auto\nqed blast\n\nlemma alg_dvd_of_nat_iff [simp]:\n  \"(of_nat x :: 'a :: field_char_0) alg_dvd of_nat y \\<longleftrightarrow> x dvd y\"\nproof -\n  have \"(of_int (int x) :: 'a) alg_dvd of_int (int y) \\<longleftrightarrow> x dvd y\"\n    by (subst alg_dvd_of_int_iff) auto\n  thus ?thesis unfolding of_int_of_nat_eq .\nqed\n\nlemma alg_dvd_add [intro]:\n  fixes x y z :: \"'a :: field_char_0\"\n  shows \"x alg_dvd y \\<Longrightarrow> x alg_dvd z \\<Longrightarrow> x alg_dvd (y + z)\"\n  unfolding alg_dvd_def by (auto simp: add_divide_distrib)\n\nlemma alg_dvd_uminus_right [intro]: \"x alg_dvd y \\<Longrightarrow> x alg_dvd -y\"\n  by (auto simp: alg_dvd_def)\n\nlemma alg_dvd_uminus_right_iff [simp]: \"x alg_dvd -y \\<longleftrightarrow> x alg_dvd y\"\n  using alg_dvd_uminus_right[of x y] alg_dvd_uminus_right[of x \"-y\"] by auto\n\nlemma alg_dvd_diff [intro]:\n  fixes x y z :: \"'a :: field_char_0\"\n  shows \"x alg_dvd y \\<Longrightarrow> x alg_dvd z \\<Longrightarrow> x alg_dvd (y - z)\"\n  unfolding alg_dvd_def by (auto simp: diff_divide_distrib)\n\nlemma alg_dvd_triv_left [intro]: \"algebraic_int y \\<Longrightarrow> x alg_dvd x * y\"\n  by (auto simp: alg_dvd_def)\n\nlemma alg_dvd_triv_right [intro]: \"algebraic_int x \\<Longrightarrow> y alg_dvd x * y\"\n  by (auto simp: alg_dvd_def)\n\nlemma alg_dvd_triv_left_iff: \"x alg_dvd x * y \\<longleftrightarrow> x = 0 \\<or> algebraic_int y\"\n  by (auto simp: alg_dvd_def)\n\nlemma alg_dvd_triv_right_iff: \"y alg_dvd x * y \\<longleftrightarrow> y = 0 \\<or> algebraic_int x\"\n  by (auto simp: alg_dvd_def)\n\nlemma alg_dvd_triv_left_iff' [simp]: \"x \\<noteq> 0 \\<Longrightarrow> x alg_dvd x * y \\<longleftrightarrow> algebraic_int y\"\n  by (simp add: alg_dvd_triv_left_iff)\n\nlemma alg_dvd_triv_right_iff' [simp]: \"y \\<noteq> 0 \\<Longrightarrow> y alg_dvd x * y \\<longleftrightarrow> algebraic_int x\"\n  by (simp add: alg_dvd_triv_right_iff)\n\nlemma alg_dvd_trans [trans]:\n  fixes x y z :: \"'a :: field_char_0\"\n  shows \"x alg_dvd y \\<Longrightarrow> y alg_dvd z \\<Longrightarrow> x alg_dvd z\"\n  using algebraic_int_times[of \"y / x\" \"z / y\"] by (auto simp: alg_dvd_def)\n\nlemma alg_dvd_mono [simp]: \n  fixes a b c d :: \"'a :: field_char_0\"\n  shows \"a alg_dvd c \\<Longrightarrow> b alg_dvd d \\<Longrightarrow> (a * b) alg_dvd (c * d)\"\n  using algebraic_int_times[of \"c / a\" \"d / b\"] by (auto simp: alg_dvd_def)\n\nlemma alg_dvd_mult [simp]: \n  fixes a b c :: \"'a :: field_char_0\"\n  shows \"a alg_dvd c \\<Longrightarrow> algebraic_int b \\<Longrightarrow> a alg_dvd (b * c)\"\n  using alg_dvd_mono[of a c 1 b] by (auto simp: mult.commute)\n\nlemma alg_dvd_mult2 [simp]:\n  fixes a b c :: \"'a :: field_char_0\"\n  shows \"a alg_dvd b \\<Longrightarrow> algebraic_int c \\<Longrightarrow> a alg_dvd (b * c)\"\n  using alg_dvd_mult[of a b c] by (simp add: mult.commute)\n\ntext \\<open>\n  A crucial theorem: if an integer \\<open>x\\<close> divides a rational number \\<open>y\\<close>, then \\<open>y\\<close> is in fact\n  also an integer, and that integer is a multiple of \\<open>x\\<close>.\n\\<close>\nlemma alg_dvd_int_rat:\n  fixes y :: \"'a :: field_char_0\"\n  assumes \"of_int x alg_dvd y\" and \"y \\<in> \\<rat>\"\n  shows   \"\\<exists>n. y = of_int n \\<and> x dvd n\"\nproof (cases \"x = 0\")\n  case False\n  have \"y / of_int x \\<in> \\<int>\"\n    by (intro rational_algebraic_int_is_int) (use assms in \\<open>auto simp: alg_dvd_def\\<close>)\n  then obtain n where n: \"of_int n = y / (of_int x :: 'a)\"\n    by (elim Ints_cases) auto\n  hence \"y = of_int (n * x)\"\n    using False by (simp add: field_simps)\n  thus ?thesis by (intro exI[of _ \"x * n\"]) auto\nqed (use assms in auto)\n\nlemma prod_alg_dvd_prod:\n  fixes f :: \"'a \\<Rightarrow> 'b :: field_char_0\"\n  assumes \"\\<And>x. x \\<in> A \\<Longrightarrow> f x alg_dvd g x\"\n  shows   \"prod f A alg_dvd prod g A\"\n  using assms by (induction A rule: infinite_finite_induct) auto\n\nlemma alg_dvd_sum:\n  fixes f :: \"'a \\<Rightarrow> 'b :: field_char_0\"\n  assumes \"\\<And>x. x \\<in> A \\<Longrightarrow> y alg_dvd f x\"\n  shows   \"y alg_dvd sum f A\"\n  using assms by (induction A rule: infinite_finite_induct) auto\n\nlemma not_alg_dvd_sum:\n  fixes f :: \"'a \\<Rightarrow> 'b :: field_char_0\"\n  assumes \"\\<And>x. x \\<in> A-{x'} \\<Longrightarrow> y alg_dvd f x\"\n  assumes \"\\<not>y alg_dvd f x'\"\n  assumes \"x' \\<in> A\" \"finite A\"\n  shows   \"\\<not>y alg_dvd sum f A\"\nproof\n  assume *: \"y alg_dvd sum f A\"\n  have \"y alg_dvd sum f A - sum f (A - {x'})\"\n    using \\<open>x' \\<in> A\\<close> by (intro alg_dvd_diff[OF * alg_dvd_sum] assms) auto\n  also have \"\\<dots> = sum f (A - (A - {x'}))\"\n    using assms by (subst sum_diff) auto\n  also have \"A - (A - {x'}) = {x'}\"\n    using assms by auto\n  finally show False using assms by simp\nqed\n\nlemma fact_dvd_pochhammer:\n  assumes \"m \\<le> n + 1\"\n  shows   \"fact m dvd pochhammer (int n - int m + 1) m\"\nproof -\n  have \"(real n gchoose m) * fact m = of_int (pochhammer (int n - int m + 1) m)\"\n    by (simp add: gbinomial_pochhammer' pochhammer_of_int [symmetric])\n  also have \"(real n gchoose m) * fact m = of_int (int (n choose m) * fact m)\"\n    by (simp add: binomial_gbinomial)\n  finally have \"int (n choose m) * fact m = pochhammer (int n - int m + 1) m\"\n    by (subst (asm) of_int_eq_iff)\n  from this [symmetric] show ?thesis by simp\nqed\n\nlemma coeff_higher_pderiv:\n  \"coeff ((pderiv ^^ m) f) n = pochhammer (of_nat (Suc n)) m * coeff f (n + m)\"\n  by (induction m arbitrary: n) (simp_all add: coeff_pderiv pochhammer_rec algebra_simps)\n\nlemma fact_alg_dvd_poly_higher_pderiv:\n  fixes p :: \"'a :: field_char_0 poly\"\n  assumes \"\\<And>i. algebraic_int (poly.coeff p i)\" \"algebraic_int x\" \"m \\<le> k\"\n  shows   \"fact m alg_dvd poly ((pderiv ^^ k) p) x\"\n  unfolding poly_altdef\nproof (intro alg_dvd_sum, goal_cases)\n  case (1 i)\n  have \"(of_int (fact m) :: 'a) alg_dvd (of_int (fact k))\"\n    by (intro alg_dvd_of_int fact_dvd assms)\n  also have \"(of_int (fact k) :: 'a) alg_dvd of_int (pochhammer (int i + 1) k)\"\n    using fact_dvd_pochhammer[of k \"i + k\"]\n    by (intro alg_dvd_of_int fact_dvd_pochhammer) (auto simp: algebra_simps)\n  finally have \"fact m alg_dvd (pochhammer (of_nat i + 1) k :: 'a)\"\n    by (simp flip: pochhammer_of_int)\n  also have \"\\<dots> alg_dvd pochhammer (of_nat i + 1) k * poly.coeff p (i + k)\"\n    by (rule alg_dvd_triv_left) (rule assms)\n  also have \"\\<dots> = poly.coeff ((pderiv ^^ k) p) i\"\n    unfolding coeff_higher_pderiv by (simp add: add_ac flip: pochhammer_of_int)\n  also have \"\\<dots> alg_dvd poly.coeff ((pderiv ^^ k) p) i * x ^ i\"\n    by (intro alg_dvd_triv_left algebraic_int_power assms)\n  finally show ?case .\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/Algebraic_Integer_Divisibility.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8499711718571775, "lm_q2_score": 0.8757869932689566, "lm_q1q2_score": 0.744393696966089}}
{"text": "(* Section 2.5 *)\ntheory BDatatypes\nimports Main\nbegin\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 t\\<^sub>1 x t\\<^sub>2) = Node (mirror t\\<^sub>2) x (mirror t\\<^sub>1)\"\n\nlemma mirror_mirror: \"mirror (mirror t) = t\"\napply (induct_tac t)\napply auto\ndone\n\nprimrec flatten :: \"'a tree \\<Rightarrow> 'a list\" where\n\"flatten Tip = []\" |\n\"flatten (Node t\\<^sub>1 x t\\<^sub>2) = flatten t\\<^sub>1 @ [x] @ flatten t\\<^sub>2\"\n\nlemma \"flatten (mirror t) = rev (flatten t)\"\napply (induct_tac t)\napply auto\ndone\n\nlemma \"(case xs of [] \\<Rightarrow> [] | y # ys \\<Rightarrow> xs) = xs\"\napply (case_tac xs)\napply auto\ndone\n\ndatatype boolex = Const bool | Var nat | Neg boolex | And boolex boolex\n\nprimrec \"value\" :: \"boolex \\<Rightarrow> (nat \\<Rightarrow> bool) \\<Rightarrow> bool\" where\n\"value (Const b) env = b\" |\n\"value (Var n)   env = env n\" |\n\"value (Neg b)   env = (\\<not> value b env)\" |\n\"value (And b c) env = (value b env \\<and> value c env)\"\n\ndatatype ifex = CIF bool | VIF nat | IF ifex ifex ifex\n\nprimrec valif :: \"ifex \\<Rightarrow> (nat \\<Rightarrow> bool) \\<Rightarrow> bool\" where\n\"valif (CIF b)    env = b\" |\n\"valif (VIF n)    env = env n\" |\n\"valif (IF c t f) env = (if valif c env then valif t env else valif f env)\"\n\nprimrec bool2if :: \"boolex \\<Rightarrow> ifex\" where\n\"bool2if (Const b) = CIF b\" |\n\"bool2if (Var n)   = VIF n\" |\n\"bool2if (Neg b)   = IF (bool2if b) (CIF False) (CIF True)\" |\n\"bool2if (And b c) = IF (bool2if b) (bool2if c) (CIF False)\"\n\nlemma \"valif (bool2if b) env = value b env\"\napply (induct_tac b)\napply auto\ndone\n\nprimrec normif :: \"ifex \\<Rightarrow> ifex \\<Rightarrow> ifex \\<Rightarrow> ifex\" where\n\"normif (CIF b) t f      = IF (CIF b) t f\" |\n\"normif (VIF n) t f      = IF (VIF n) t f\" |\n\"normif (IF c c\\<^sub>1 c\\<^sub>2) t f = normif c (normif c\\<^sub>1 t f) (normif c\\<^sub>2 t f)\"\n\nprimrec norm :: \"ifex \\<Rightarrow> ifex\" where\n\"norm (CIF b) = CIF b\" |\n\"norm (VIF n) = VIF n\" |\n\"norm (IF c t f) = normif c (norm t) (norm f)\"\n\n\n\ntheorem \"valif (norm b) env = valif b env\"\napply (induct_tac b)\napply auto\ndone\n\nprimrec normal :: \"ifex \\<Rightarrow> bool\" where\n\"normal (CIF b)    = True\" |\n\"normal (VIF n)    = True\" |\n\"normal (IF c t f) = ((case c of CIF b \\<Rightarrow> True | VIF n \\<Rightarrow> True | IF x y z \\<Rightarrow> False)\n                   \\<and> normal t\n                   \\<and> normal f)\"\n\nlemma [simp]: \"\\<forall>t f. normal (normif c t f) = (normal t \\<and> normal f)\"\napply (induct_tac c)\napply auto\ndone\n\ntheorem \"normal (norm b)\"\napply (induct_tac b)\napply auto\ndone\n\n(* Strengthened s.t. the first argument to IF must be a variable *)\nprimrec normif' :: \"ifex \\<Rightarrow> ifex \\<Rightarrow> ifex \\<Rightarrow> ifex\" where\n\"normif' (CIF b) t f      = (if b then t else f)\" |\n\"normif' (VIF n) t f      = IF (VIF n) t f\" |\n\"normif' (IF c c\\<^sub>1 c\\<^sub>2) t f = normif' c (normif' c\\<^sub>1 t f) (normif' c\\<^sub>2 t f)\"\n\nprimrec norm' :: \"ifex \\<Rightarrow> ifex\" where\n\"norm' (CIF b) = CIF b\" |\n\"norm' (VIF n) = VIF n\" |\n\"norm' (IF c t f) = normif' c (norm' t) (norm' f)\"\n\nlemma [simp]: \"\\<forall>t e. valif (normif' b t e) env = valif (IF b t e) env\"\napply (induct_tac b)\napply auto\ndone\n\ntheorem \"valif (norm' b) env = valif b env\"\napply (induct_tac b)\napply auto\ndone\n\nprimrec normal' :: \"ifex \\<Rightarrow> bool\" where\n\"normal' (CIF b)    = True\" |\n\"normal' (VIF n)    = True\" |\n\"normal' (IF c t f) = ((case c of CIF b \\<Rightarrow> False | VIF n \\<Rightarrow> True | IF x y z \\<Rightarrow> False)\n                    \\<and> normal' t\n                    \\<and> normal' f)\"\n\nlemma [simp]: \"\\<forall>t f. (normal' t \\<and> normal' f) \\<longrightarrow> normal' (normif' c t f)\"\napply (induct_tac c)\napply auto\ndone\n\ntheorem \"normal' (norm' b)\"\napply (induct_tac b)\napply auto\ndone\n\nend\n", "meta": {"author": "spl", "repo": "isabelle-tutorial", "sha": "56ee8d748d6d639ea7238e5fbb9edce4330637f2", "save_path": "github-repos/isabelle/spl-isabelle-tutorial", "path": "github-repos/isabelle/spl-isabelle-tutorial/isabelle-tutorial-56ee8d748d6d639ea7238e5fbb9edce4330637f2/BDatatypes.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869819218865, "lm_q2_score": 0.849971181358171, "lm_q1q2_score": 0.744393695642253}}
{"text": "(*  Title:       Definition of Expectation and Distribution of uniformly distributed bit vectors\n    Author:      Max Haslbeck\n*)\n\nsection \"Probability Theory\"\n\ntheory Prob_Theory\nimports \"HOL-Probability.Probability\"\nbegin\n\nlemma integral_map_pmf[simp]:\n  fixes f::\"real \\<Rightarrow> real\"\n  shows \"(\\<integral>x. f x \\<partial>(map_pmf g M)) = (\\<integral>x. f (g x) \\<partial>M)\"\n   unfolding map_pmf_rep_eq\n using integral_distr[of g \"(measure_pmf M)\" \"(count_space UNIV)\" f] by auto\n\n\nsubsection \"function \\<open>E\\<close>\"\n\ndefinition E :: \"real pmf \\<Rightarrow> real\"  where\n  \"E M = (\\<integral>x. x \\<partial> measure_pmf M)\"\n\ntranslations\n  \"\\<integral> x. f \\<partial>M\" <= \"CONST lebesgue_integral M (\\<lambda>x. f)\"\n\nnotation (latex output) E  (\"E[_]\" [1] 100)\n\nlemma E_const[simp]: \"E (return_pmf a) = a\"\nunfolding E_def\nunfolding return_pmf.rep_eq\nby (simp add: integral_return)\n\nlemma E_null[simp]: \"E (return_pmf 0) = 0\"\nby auto\n\nlemma E_finite_sum: \"finite (set_pmf X) \\<Longrightarrow> E X = (\\<Sum>x\\<in>(set_pmf X). pmf X x * x)\"\n  unfolding E_def by (subst integral_measure_pmf) simp_all\n\nlemma E_of_const: \"E(map_pmf (\\<lambda>x. y) (X::real pmf)) = y\" by auto\n\nlemma E_nonneg:\n  shows \"(\\<forall>x\\<in>set_pmf X. 0\\<le> x) \\<Longrightarrow> 0 \\<le> E X\"\nunfolding E_def\nusing integral_nonneg by (simp add: AE_measure_pmf_iff integral_nonneg_AE)\n\nlemma E_nonneg_fun: fixes f::\"'a\\<Rightarrow>real\"\n  shows \"(\\<forall>x\\<in>set_pmf X. 0\\<le>f x) \\<Longrightarrow> 0 \\<le> E (map_pmf f X)\"\nusing E_nonneg by auto\n\nlemma E_cong:\n  fixes f::\"'a \\<Rightarrow> real\"\n  shows \"finite (set_pmf X) \\<Longrightarrow> (\\<forall>x\\<in> set_pmf X. (f x) = (u x)) \\<Longrightarrow> E (map_pmf f X) = E (map_pmf u X)\"\nunfolding E_def integral_map_pmf apply(rule integral_cong_AE)\napply(simp add: integrable_measure_pmf_finite)+\nby (simp add: AE_measure_pmf_iff)\n\nlemma E_mono3:\n  fixes f::\"'a \\<Rightarrow> real\"\n  shows \" integrable (measure_pmf X) f \\<Longrightarrow>  integrable (measure_pmf X) u \\<Longrightarrow> (\\<forall>x\\<in> set_pmf X. (f x) \\<le> (u x)) \\<Longrightarrow> E (map_pmf f X) \\<le> E (map_pmf u X)\"\nunfolding E_def integral_map_pmf apply(rule integral_mono_AE)\nby (auto simp add: AE_measure_pmf_iff)\n\nlemma E_mono2:\n  fixes f::\"'a \\<Rightarrow> real\"\n  shows \"finite (set_pmf X) \\<Longrightarrow> (\\<forall>x\\<in> set_pmf X. (f x) \\<le> (u x)) \\<Longrightarrow> E (map_pmf f X) \\<le> E (map_pmf u X)\"\nunfolding E_def integral_map_pmf apply(rule integral_mono_AE)\napply(simp add: integrable_measure_pmf_finite)+\nby (simp add: AE_measure_pmf_iff)\n\nlemma E_linear_diff2: \"finite (set_pmf A) \\<Longrightarrow> E (map_pmf f A) - E (map_pmf g A) = E (map_pmf (\\<lambda>x. (f x) - (g x)) A)\"\nunfolding E_def integral_map_pmf apply(rule Bochner_Integration.integral_diff[of \"measure_pmf A\" f g, symmetric])\n by (simp_all add: integrable_measure_pmf_finite)\n\nlemma E_linear_plus2: \"finite (set_pmf A) \\<Longrightarrow> E (map_pmf f A) + E (map_pmf g A) = E (map_pmf (\\<lambda>x. (f x) + (g x)) A)\"\nunfolding E_def integral_map_pmf apply(rule Bochner_Integration.integral_add[of \"measure_pmf A\" f g, symmetric])\n by (simp_all add: integrable_measure_pmf_finite)\n\nlemma E_linear_sum2: \"finite (set_pmf D) \\<Longrightarrow> E(map_pmf (\\<lambda>x. (\\<Sum>i<up. f i x)) D)\n      = (\\<Sum>i<(up::nat). E(map_pmf (f i) D))\"\nunfolding E_def integral_map_pmf apply(rule Bochner_Integration.integral_sum) by (simp add: integrable_measure_pmf_finite)\n\nlemma E_linear_sum_allg: \"finite (set_pmf D) \\<Longrightarrow> E(map_pmf (\\<lambda>x. (\\<Sum>i\\<in> A. f i x)) D)\n      = (\\<Sum>i\\<in> (A::'a set). E(map_pmf (f i) D))\"\nunfolding E_def integral_map_pmf apply(rule Bochner_Integration.integral_sum) by (simp add: integrable_measure_pmf_finite)\n\nlemma E_finite_sum_fun: \"finite (set_pmf X) \\<Longrightarrow>\n    E (map_pmf f X) = (\\<Sum>x\\<in>set_pmf X. pmf X x * f x)\"\nproof -\n  assume finite: \"finite (set_pmf X)\"\n  have \"E (map_pmf f X) = (\\<integral>x. f x \\<partial>measure_pmf X)\"\n      unfolding E_def by auto\n  also have \"\\<dots> = (\\<Sum>x\\<in>set_pmf X. pmf X x * f x)\"\n    by (subst integral_measure_pmf) (auto simp add: finite)\n  finally show ?thesis .\nqed\n\nlemma E_bernoulli: \"0\\<le>p \\<Longrightarrow> p\\<le>1 \\<Longrightarrow>\n        E (map_pmf f (bernoulli_pmf p)) = p*(f True) + (1-p)*(f False)\"\nunfolding E_def by (auto)\n\n\nsubsection \"function \\<open>bv\\<close>\"\n\n  fun bv:: \"nat \\<Rightarrow> bool list pmf\" where\n  \"bv 0 = return_pmf []\"\n| \"bv (Suc n) =  do {\n                    (xs::bool list) \\<leftarrow> bv n;\n                    (x::bool) \\<leftarrow> (bernoulli_pmf 0.5);\n                    return_pmf (x#xs)\n                  }\"\n\nlemma bv_finite: \"finite (bv n)\"\nby (induct  n) auto\n\nlemma len_bv_n: \"\\<forall>xs \\<in> set_pmf (bv n). length xs = n\"\napply(induct n) by auto\n\nlemma bv_set: \"set_pmf (bv n) = {x::bool list. length x = n}\"\nproof (induct n)\n  case (Suc n)\n  then have \"set_pmf (bv (Suc n)) = (\\<Union>x\\<in>{x. length x = n}. {True # x, False # x})\"\n    by(simp add: set_pmf_bernoulli UNIV_bool)\n  also have \"\\<dots> = {x#xs| x xs. length xs = n}\" by auto\n  also have \"\\<dots> = {x. length x = Suc n} \" using Suc_length_conv by fastforce\n  finally show ?case .\nqed (simp)\n\nlemma len_not_in_bv: \"length xs  \\<noteq> n \\<Longrightarrow> xs \\<notin> set_pmf (bv n)\"\nby(auto simp: len_bv_n)\n\nlemma not_n_bv_0: \"length xs \\<noteq> n \\<Longrightarrow> pmf (bv n) xs = 0\"\nby (simp add: len_not_in_bv pmf_eq_0_set_pmf)\n\nlemma bv_comp_bernoulli: \"n < l\n        \\<Longrightarrow> map_pmf (\\<lambda>y. y!n) (bv l) = bernoulli_pmf (5 / 10)\"\nproof (induct n arbitrary: l)\n  case 0\n  then obtain m where \"l = Suc m\" by (metis Suc_pred)\n  then show \"map_pmf (\\<lambda>y. y!0) (bv l) =  bernoulli_pmf (5 / 10)\" by (auto simp: map_pmf_def bind_return_pmf bind_assoc_pmf bind_return_pmf')\nnext\n  case (Suc n)\n  then have \"0 < l\" by auto\n  then obtain m where lsm: \"l = Suc m\" by (metis Suc_pred)\n  with Suc(2) have nltm: \"n < m\" by auto\n\n  from lsm have \"map_pmf (\\<lambda>y. y ! Suc n) (bv l)\n       =  map_pmf (\\<lambda>x. x!n) (bind_pmf (bv m) (\\<lambda>t. (return_pmf t)))\" by (auto simp: map_bind_pmf)\nalso\n  have \"\\<dots> =  map_pmf (\\<lambda>x. x!n) (bv m)\" by (auto simp: bind_return_pmf')\nalso\n  have \"\\<dots> = bernoulli_pmf (5 / 10)\" by (auto simp add: Suc(1)[of m, OF nltm])\nfinally\n  show ?case .\nqed\n\nlemma pmf_2elemlist: \"pmf (bv (Suc 0)) ([x]) = pmf (bv 0) [] * pmf (bernoulli_pmf (5 / 10)) x\"\n  unfolding bv.simps(2)[where n=0] pmf_bind pmf_return\n  apply (subst integral_measure_pmf[where A=\"{[]}\"])\n  apply (auto) by (cases x) auto\n\nlemma pmf_moreelemlist: \"pmf (bv (Suc n)) (x#xs) = pmf (bv n) xs * pmf (bernoulli_pmf (5 / 10)) x\"\n  unfolding bv.simps(2) pmf_bind pmf_return\n  apply (subst integral_measure_pmf[where A=\"{xs}\"])\n  apply auto apply (cases x) apply(auto)\n  apply (meson indicator_simps(2) list.inject singletonD)\n  apply (meson indicator_simps(2) list.inject singletonD)\n  apply (cases x) by(auto)\n\nlemma list_pmf: \"length xs = n \\<Longrightarrow> pmf (bv n) xs = (1 / 2)^n\"\nproof(induct n arbitrary: xs)\n  case 0\n  then have \"xs = []\" by auto\n  then show \"pmf (bv 0) xs = (1 / 2) ^ 0\" by(auto)\nnext\n  case (Suc n xs)\n  then obtain a as where split: \"xs = a#as\" by (metis Suc_length_conv)\n  have \"length as = n\" using Suc(2) split by auto\n  with Suc(1) have 1: \"pmf (bv n) as = (1 / 2) ^ n\" by auto\n\n  from split pmf_moreelemlist[where n=n and x=a and xs=as] have\n    \"pmf (bv (Suc n)) xs = pmf (bv n) as * pmf (bernoulli_pmf (5 / 10)) a\" by auto\n  then have \"pmf (bv (Suc n)) xs = (1 / 2) ^ n * 1 / 2\" using 1 by auto\n  then show \"pmf (bv (Suc n)) xs = (1 / 2) ^ Suc n\" by auto\nqed\n\nlemma bv_0_notlen: \"pmf (bv n) xs = 0 \\<Longrightarrow> length xs \\<noteq> n \"\nby(auto simp: list_pmf)\n\nlemma \"length xs > n \\<Longrightarrow> pmf (bv n) xs = 0\"\nproof (induct n arbitrary: xs)\n  case (Suc n xs)\n  then obtain a as where split: \"xs = a#as\" by (metis Suc_length_conv Suc_lessE)\n  have \"length as > n\" using Suc(2) split by auto\n  with Suc(1) have 1: \"pmf (bv n) as = 0\" by auto\n  from split pmf_moreelemlist[where n=n and x=a and xs=as] have\n    \"pmf (bv (Suc n)) xs = pmf (bv n) as * pmf (bernoulli_pmf (5 / 10)) a\" by auto\n  then have \"pmf (bv (Suc n)) xs = 0 * 1 / 2\" using 1 by auto\n  then show \"pmf (bv (Suc n)) xs = 0\" by auto\nqed simp\n\nlemma map_hd_list_pmf: \"map_pmf hd (bv (Suc n)) = bernoulli_pmf (5 / 10)\"\n  by (simp add: map_pmf_def bind_assoc_pmf bind_return_pmf bind_return_pmf')\n\nlemma map_tl_list_pmf: \"map_pmf tl (bv (Suc n)) = bv n\"\n  by (simp add: map_pmf_def bind_assoc_pmf bind_return_pmf bind_return_pmf' )\n\n\nsubsection \"function \\<open>flip\\<close>\"\n\nfun flip :: \"nat \\<Rightarrow> bool list \\<Rightarrow> bool list\" where\n  \"flip _ [] = []\"\n| \"flip 0 (x#xs) = (\\<not>x)#xs\"\n| \"flip (Suc n) (x#xs) = x#(flip n xs)\"\n\nlemma flip_length[simp]: \"length (flip i xs) = length xs\"\napply(induct xs arbitrary: i) apply(simp) apply(case_tac i) by(simp_all)\n\nlemma flip_out_of_bounds: \"y \\<ge> length X \\<Longrightarrow> flip y X = X\"\napply(induct X arbitrary: y)\nproof -\n  case (Cons X Xs)\n  hence \"y > 0\" by auto\n  with Cons obtain y' where y1: \"y = Suc y'\" and y2: \"y' \\<ge> length Xs\" by (metis Suc_pred' length_Cons not_less_eq_eq)\n  then have \"flip y (X # Xs) = X#(flip y' Xs)\" by auto\n  moreover from Cons y2 have \"flip y' Xs = Xs\" by auto\n  ultimately show ?case by auto\nqed simp\n\nlemma flip_other: \"y < length X \\<Longrightarrow> z < length X \\<Longrightarrow> z \\<noteq> y \\<Longrightarrow> flip z X ! y = X ! y\"\napply(induct y arbitrary: X z)\napply(simp) apply (metis flip.elims neq0_conv nth_Cons_0)\nproof (case_tac z, goal_cases)\n  case (1 y X z)\n  then obtain a as where \"X=a#as\" using length_greater_0_conv by (metis (full_types) flip.elims)\n  with 1(5) show ?case by(simp)\nnext\n  case (2 y X z z')\n  from 2 have 3: \"z' \\<noteq> y\" by auto\n  from 2(2) have \"length X > 0\" by auto\n  then obtain a as where aas: \"X = a#as\" by (metis (full_types) flip.elims length_greater_0_conv)\n  then have a: \"flip (Suc z') X ! Suc y = flip z' as ! y\"\n    and b : \"(X ! Suc y) = (as !  y)\" by auto\n  from 2(2) aas have 1: \"y < length as\" by auto\n  from 2(3,5) aas have f2: \"z' < length as\" by auto\n  note c=2(1)[OF 1 f2 3]\n\n  have \"flip z X ! Suc y = flip (Suc z') X ! Suc y\" using 2 by auto\n  also have \"\\<dots> = flip z' as ! y\" by (rule a)\n  also have \"\\<dots> = as ! y\" by (rule c)\n  also have \"\\<dots> = (X ! Suc y)\" by (rule b[symmetric])\n  finally show \"flip z X ! Suc y = (X ! Suc y)\" .\nqed\n\nlemma flip_itself: \"y < length X \\<Longrightarrow> flip y X ! y = (\\<not> X ! y)\"\napply(induct y arbitrary: X)\napply(simp) apply (metis flip.elims nth_Cons_0 old.nat.distinct(2))\nproof -\n  fix y\n  fix X::\"bool list\"\n  assume iH: \"(\\<And>X. y < length X \\<Longrightarrow> flip y X ! y = (\\<not> X ! y))\"\n  assume len: \"Suc y < length X\"\n  from len have \"y < length X\" by auto\n  from len have \"length X > 0\" by auto\n  then obtain z zs where zzs: \"X = z#zs\" by (metis (full_types) flip.elims length_greater_0_conv)\n  then have a: \"flip (Suc y) X ! Suc y = flip y zs ! y\"\n    and b : \"(\\<not> X ! Suc y) = (\\<not> zs !  y)\" by auto\n  from len zzs have \"y < length zs\" by auto\n  note c=iH[OF this]\n  from a b c show \"flip (Suc y) X ! Suc y = (\\<not> X ! Suc y)\" by auto\nqed\n\nlemma flip_twice: \"flip i (flip i b) = b\"\nproof (cases \"i < length b\")\n  case True\n  then have A: \"i < length (flip i b)\" by simp\n  show ?thesis apply(simp add: list_eq_iff_nth_eq) apply(clarify)\n  proof (goal_cases)\n    case (1 j)\n    then show ?case\n      apply(cases \"i=j\")\n        using flip_itself[OF A] flip_itself[OF True] apply(simp)\n        using flip_other True 1 by auto\n  qed\nqed (simp add: flip_out_of_bounds)\n\nlemma flipidiflip: \"y < length X \\<Longrightarrow> e < length X  \\<Longrightarrow> flip e X ! y = (if e=y then ~ (X ! y) else X ! y)\"\napply(cases \"e=y\")\napply(simp add: flip_itself)\nby(simp add: flip_other)\n\nlemma bernoulli_Not: \"map_pmf Not (bernoulli_pmf (1 / 2)) = (bernoulli_pmf (1 / 2))\"\napply(rule pmf_eqI)\nproof (case_tac i, goal_cases)\n  case (1 i)\n  then have \"pmf (map_pmf Not (bernoulli_pmf (1 / 2))) i =\n    pmf (map_pmf Not (bernoulli_pmf (1 / 2))) (Not False)\" by auto\n  also have \"\\<dots> = pmf (bernoulli_pmf (1 / 2)) False\" apply (rule pmf_map_inj') apply(rule injI) by auto\n  also have \"\\<dots> = pmf (bernoulli_pmf (1 / 2)) i\" by auto\n  finally show ?case .\nnext\n  case (2 i)\n  then have \"pmf (map_pmf Not (bernoulli_pmf (1 / 2))) i =\n    pmf (map_pmf Not (bernoulli_pmf (1 / 2))) (Not True)\" by auto\n  also have \"\\<dots> = pmf (bernoulli_pmf (1 / 2)) True\" apply (rule pmf_map_inj') apply(rule injI) by auto\n  also have \"\\<dots> = pmf (bernoulli_pmf (1 / 2)) i\" by auto\n  finally show ?case .\nqed\n\nlemma inv_flip_bv: \"map_pmf (flip i) (bv n) = (bv n)\"\nproof(induct n arbitrary: i)\n   case (Suc n i)\n   note iH=this\n   have \"bind_pmf (bv n) (\\<lambda>x. bind_pmf (bernoulli_pmf (1 / 2)) (\\<lambda>xa. map_pmf (flip i) (return_pmf (xa # x))))\n    = bind_pmf (bernoulli_pmf (1 / 2)) (\\<lambda>xa .bind_pmf (bv n) (\\<lambda>x. map_pmf (flip i) (return_pmf (xa # x))))\"\n    by(rule bind_commute_pmf)\n   also have \"\\<dots> = bind_pmf (bernoulli_pmf (1 / 2)) (\\<lambda>xa . bind_pmf (bv n) (\\<lambda>x. return_pmf (xa # x)))\"\n   proof (cases i)\n    case 0\n    then have \"bind_pmf (bernoulli_pmf (1 / 2)) (\\<lambda>xa. bind_pmf (bv n) (\\<lambda>x. map_pmf (flip i) (return_pmf (xa # x))))\n        = bind_pmf (bernoulli_pmf (1 / 2)) (\\<lambda>xa. bind_pmf (bv n) (\\<lambda>x. return_pmf ((\\<not> xa) # x)))\" by auto\n    also have \"\\<dots>  = bind_pmf (bv n) (\\<lambda>x. bind_pmf (bernoulli_pmf (1 / 2)) (\\<lambda>xa. return_pmf ((\\<not> xa) # x)))\"\n      by(rule bind_commute_pmf)\n    also have \"\\<dots>\n        = bind_pmf (bv n) (\\<lambda>x. bind_pmf (map_pmf Not (bernoulli_pmf (1 / 2))) (\\<lambda>xa. return_pmf (xa # x)))\"\n              by(auto simp add: bind_map_pmf)\n    also have \"\\<dots> = bind_pmf (bv n) (\\<lambda>x. bind_pmf (bernoulli_pmf (1 / 2)) (\\<lambda>xa. return_pmf (xa # x)))\" by (simp only: bernoulli_Not)\n    also have \"\\<dots> = bind_pmf (bernoulli_pmf (1 / 2)) (\\<lambda>xa. bind_pmf (bv n) (\\<lambda>x. return_pmf (xa # x)))\"\n      by(rule bind_commute_pmf)\n    finally show ?thesis .\n   next\n    case (Suc i')\n    have \"bind_pmf (bernoulli_pmf (1 / 2)) (\\<lambda>xa. bind_pmf (bv n) (\\<lambda>x. map_pmf (flip i) (return_pmf (xa # x))))\n        = bind_pmf (bernoulli_pmf (1 / 2)) (\\<lambda>xa. bind_pmf (bv n) (\\<lambda>x. return_pmf (xa # flip i' x)))\" unfolding Suc by(simp)\n    also have \"\\<dots> = bind_pmf (bernoulli_pmf (1 / 2)) (\\<lambda>xa. bind_pmf (map_pmf (flip i') (bv n)) (\\<lambda>x. return_pmf (xa # x)))\"\n        by(auto simp add: bind_map_pmf)\n    also have \"\\<dots> =  bind_pmf (bernoulli_pmf (1 / 2)) (\\<lambda>xa. bind_pmf (bv n) (\\<lambda>x. return_pmf (xa # x)))\"\n        using iH[of \"i'\"] by simp\n    finally show ?thesis .\n   qed\n   also have \"\\<dots> = bind_pmf (bv n) (\\<lambda>x. bind_pmf (bernoulli_pmf (1 / 2)) (\\<lambda>xa. return_pmf (xa # x)))\"\n    by(rule bind_commute_pmf)\n   finally show ?case by(simp add: map_pmf_def bind_assoc_pmf)\nqed simp\n\n\nsubsection \"Example for pmf\"\n\ndefinition \"twocoins =\n                do {\n                    x \\<leftarrow> (bernoulli_pmf 0.4);\n                    y \\<leftarrow> (bernoulli_pmf 0.5);\n                    return_pmf (x \\<or> y)\n                  }\"\n\nlemma experiment0_7: \"pmf twocoins True = 0.7\"\nunfolding twocoins_def\n  unfolding pmf_bind pmf_return\n  apply (subst integral_measure_pmf[where A=\"{True, False}\"])\n  by auto\n\nsubsection \"Sum Distribution\"\n\ndefinition \"Sum_pmf p Da Db = (bernoulli_pmf p) \\<bind> (%b. if b then map_pmf Inl Da else map_pmf Inr Db )\"\n\nlemma b0: \"bernoulli_pmf 0 = return_pmf False\"\napply(rule pmf_eqI) apply(case_tac i)\n  by(simp_all)\nlemma b1: \"bernoulli_pmf 1 = return_pmf True\"\napply(rule pmf_eqI) apply(case_tac i)\n  by(simp_all)\n\n\nlemma Sum_pmf_0: \"Sum_pmf 0 Da Db = map_pmf Inr Db\"\nunfolding Sum_pmf_def\napply(rule pmf_eqI)\n  by(simp add: b0 bind_return_pmf)\n\nlemma Sum_pmf_1: \"Sum_pmf 1 Da Db = map_pmf Inl Da\"\nunfolding Sum_pmf_def\napply(rule pmf_eqI)\n  by(simp add: b1 bind_return_pmf)\n\n\ndefinition \"Proj1_pmf D = map_pmf (%a. case a of Inl e \\<Rightarrow> e) (cond_pmf D {f. (\\<exists>e. Inl e = f)})\"\n\n\nlemma A: \"(case_sum (\\<lambda>e. e) (\\<lambda>a. undefined)) (Inl e) = e\"\n  by(simp)\n\nlemma B: \"inj (case_sum (\\<lambda>e. e) (\\<lambda>a. undefined))\"\n  oops\n\nlemma none: \"p >0 \\<Longrightarrow> p < 1 \\<Longrightarrow> (set_pmf (bernoulli_pmf p \\<bind>\n          (\\<lambda>b. if b then map_pmf Inl Da else map_pmf Inr Db))\n          \\<inter> {f. (\\<exists>e. Inl e = f)}) \\<noteq> {}\"\n    apply(simp add: UNIV_bool)\n      using set_pmf_not_empty by fast\nlemma none2: \"p >0 \\<Longrightarrow> p < 1 \\<Longrightarrow>  (set_pmf (bernoulli_pmf p \\<bind>\n          (\\<lambda>b. if b then map_pmf Inl Da else map_pmf Inr Db))\n          \\<inter> {f. (\\<exists>e. Inr e = f)}) \\<noteq> {}\"\n    apply(simp add: UNIV_bool)\n      using set_pmf_not_empty by fast\n\nlemma C: \"set_pmf (Proj1_pmf (Sum_pmf 0.5 Da Db)) = set_pmf Da\"\nproof -\n  show ?thesis\n    unfolding Sum_pmf_def Proj1_pmf_def\n    apply(simp add: )\n    using none[of \"0.5\" Da Db] apply(simp add: set_cond_pmf UNIV_bool)\n      by force\nqed\n\nthm integral_measure_pmf\n\nthm pmf_cond pmf_cond[OF none]\n\nlemma proj1_pmf: assumes \"p>0\" \"p<1\" shows \"Proj1_pmf (Sum_pmf p Da Db) =  Da\"\nproof -\n\n  have kl: \"\\<And>e. pmf (map_pmf Inr Db) (Inl e) = 0\"\n    apply(simp only: pmf_eq_0_set_pmf)\n    apply(simp) by blast\n\n  have ll: \"measure_pmf.prob\n           (bernoulli_pmf p \\<bind>\n            (\\<lambda>b. if b then map_pmf Inl Da else map_pmf Inr Db))\n           {f. \\<exists>e. Inl e = f} = p\"\n       using assms\n     apply(simp add: integral_pmf[symmetric] pmf_bind)\n     apply(subst Bochner_Integration.integral_add)\n      using integrable_pmf apply fast\n      using integrable_pmf apply fast\n        by(simp add: integral_pmf)\n\n  have E: \"(cond_pmf\n       (bernoulli_pmf p \\<bind>\n        (\\<lambda>b. if b then map_pmf Inl Da else map_pmf Inr Db))\n       {f. \\<exists>e. Inl e = f}) =\n    map_pmf Inl Da\"\n    apply(rule pmf_eqI)\n      apply(subst pmf_cond)\n      using none[of p Da Db] assms apply (simp)\n       using assms apply(auto)\n          apply(subst pmf_bind)\n          apply(simp add: kl ll )\n          apply(simp only: pmf_eq_0_set_pmf) by auto\n\n  have ID: \"case_sum (\\<lambda>e. e) (\\<lambda>a. undefined) \\<circ> Inl = id\"\n    by fastforce\n  show ?thesis\n    unfolding Sum_pmf_def Proj1_pmf_def\n    apply(simp only: E)\n    apply(simp add: pmf.map_comp ID)\n  done\n\nqed\n\n\ndefinition \"Proj2_pmf D = map_pmf (%a. case a of Inr e \\<Rightarrow> e) (cond_pmf D {f. (\\<exists>e. Inr e = f)})\"\n\nlemma proj2_pmf: assumes \"p>0\" \"p<1\" shows \"Proj2_pmf (Sum_pmf p Da Db) =  Db\"\nproof -\n\n  have kl: \"\\<And>e. pmf (map_pmf Inl Da) (Inr e) = 0\"\n    apply(simp only: pmf_eq_0_set_pmf)\n    apply(simp) by blast\n\n  have ll: \"measure_pmf.prob\n           (bernoulli_pmf p \\<bind>\n            (\\<lambda>b. if b then map_pmf Inl Da else map_pmf Inr Db))\n           {f. \\<exists>e. Inr e = f} = 1-p\"\n       using assms\n     apply(simp add: integral_pmf[symmetric] pmf_bind)\n     apply(subst Bochner_Integration.integral_add)\n      using integrable_pmf apply fast\n      using integrable_pmf apply fast\n        by(simp add: integral_pmf)\n\n  have E: \"(cond_pmf\n       (bernoulli_pmf p \\<bind>\n        (\\<lambda>b. if b then map_pmf Inl Da else map_pmf Inr Db))\n       {f. \\<exists>e. Inr e = f}) =\n    map_pmf Inr Db\"\n    apply(rule pmf_eqI)\n      apply(subst pmf_cond)\n      using none2[of p Da Db] assms apply (simp)\n       using assms apply(auto)\n          apply(subst pmf_bind)\n          apply(simp add: kl ll )\n          apply(simp only: pmf_eq_0_set_pmf) by auto\n\n  have ID: \"case_sum (\\<lambda>e. undefined) (\\<lambda>a. a) \\<circ> Inr = id\"\n    by fastforce\n  show ?thesis\n    unfolding Sum_pmf_def Proj2_pmf_def\n    apply(simp only: E)\n    apply(simp add: pmf.map_comp ID)\n  done\n\nqed\n\n\n\n\ndefinition \"invSum invA invB D x i == invA (Proj1_pmf D) x i \\<and> invB (Proj2_pmf D) x i\"\n\n\n\n\nterm \"(%a. case a of Inl e \\<Rightarrow> Inl (fa e) | Inr e \\<Rightarrow> Inr (fb e))\"\ndefinition \"f_on2 fa fb = (%a. case a of Inl e \\<Rightarrow> map_pmf Inl (fa e) | Inr e \\<Rightarrow> map_pmf Inr (fb e))\"\n\nterm \"bind_pmf\"\n\n\nlemma Sum_bind_pmf: assumes a: \"bind_pmf Da fa = Da'\" and b: \"bind_pmf Db fb = Db'\"\n  shows \"bind_pmf (Sum_pmf p Da Db) (f_on2 fa fb)\n              = Sum_pmf p Da' Db'\"\nproof -\n  { fix x\n  have \"(if x then map_pmf Inl Da else map_pmf Inr Db) \\<bind>\n                 case_sum (\\<lambda>e. map_pmf Inl (fa e))\n                  (\\<lambda>e. map_pmf Inr (fb e))\n            =\n        (if x then map_pmf Inl Da \\<bind> case_sum (\\<lambda>e. map_pmf Inl (fa e))\n                  (\\<lambda>e. map_pmf Inr (fb e))\n              else map_pmf Inr Db \\<bind> case_sum (\\<lambda>e. map_pmf Inl (fa e))\n                  (\\<lambda>e. map_pmf Inr (fb e)))\"\n                  apply(simp) done\n  also\n    have \"\\<dots> = (if x then map_pmf Inl (bind_pmf Da fa) else map_pmf Inr (bind_pmf Db fb))\"\n      by(auto simp add: map_pmf_def bind_assoc_pmf bind_return_pmf)\n  also\n    have \"\\<dots> = (if x then map_pmf Inl Da' else map_pmf Inr Db')\"\n      using a b by simp\n  finally\n    have \"(if x then map_pmf Inl Da else map_pmf Inr Db) \\<bind>\n                 case_sum (\\<lambda>e. map_pmf Inl (fa e))\n                  (\\<lambda>e. map_pmf Inr (fb e)) = (if x then map_pmf Inl Da' else map_pmf Inr Db')\" .\n  } note gr=this\n\n\n\n  show ?thesis\n    unfolding Sum_pmf_def f_on2_def\n    apply(rule pmf_eqI)\n    apply(case_tac i)\n    by(simp_all add: bind_return_pmf bind_assoc_pmf gr)\nqed\n\ndefinition \"sum_map_pmf fa fb = (%a. case a of Inl e \\<Rightarrow> Inl (fa e) | Inr e \\<Rightarrow> Inr (fb e))\"\n\nlemma Sum_map_pmf: assumes a: \"map_pmf fa Da = Da'\" and b: \"map_pmf fb Db = Db'\"\n  shows \"map_pmf (sum_map_pmf fa fb) (Sum_pmf p Da Db)\n              = Sum_pmf p Da' Db'\"\nproof -\n  have \"map_pmf (sum_map_pmf fa fb) (Sum_pmf p Da Db)\n        = bind_pmf (Sum_pmf p Da Db) (f_on2 (\\<lambda>x. return_pmf (fa x)) (\\<lambda>x. return_pmf (fb x)))\"\n        using a b\n  unfolding map_pmf_def sum_map_pmf_def f_on2_def\n    by(auto simp add: bind_return_pmf sum.case_distrib)\nalso\n  have \"\\<dots> = Sum_pmf p Da' Db'\"\n using assms[unfolded map_pmf_def]\n by(rule Sum_bind_pmf )\nfinally\n  show ?thesis .\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/List_Update/Prob_Theory.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976953030553434, "lm_q2_score": 0.8289388125473629, "lm_q1q2_score": 0.7441344785440415}}
{"text": "theory Submission\n  imports Defs\nbegin\n\nlemma S_ge_2:\n  \"S n \\<ge> 2\"\n  by (induction n) auto\n\nlemma prime_factors_nonempty:\n  \"prime_factors n \\<noteq> {}\" if \"n > 1\" for n :: nat\n  by (metis less_trans neq_iff prime_factorization_1 prod_mset_prime_factorization_nat\n        set_mset_eq_empty_iff that zero_less_one)\n\nlemma pf_in_prime_factors[intro]:\n  \"pf n \\<in> prime_factors n\" if \"n > 1\" for n :: nat\n  unfolding pf_def using prime_factors_nonempty[OF \\<open>n > 1\\<close>] by (intro Min_in) auto\n\nlemma pf_S_in_prime_factors[simp, intro]:\n  \"pf (S n) \\<in> prime_factors (S n)\"\n  using S_ge_2[of n] by auto\n\n\ntheorem prime_pf_Suc_S:\n  \"prime(pf(S(n)+1))\"\n  using S_ge_2[of n] by force\n\n\nlemma prime_factors_subs:\n  \"prime_factors m \\<subseteq> prime_factors (m * k)\" if \"0 < m\" \"0 < k\" for m k :: nat\n  using that by (intro dvd_prime_factors) auto\n\nlemma prime_factors_S_Suc:\n  \"prime_factors (S m + 1) \\<subseteq> prime_factors (S (m + 1))\"\n  using prime_factors_subs[of \"S m + 1\" \"S m\"] S_ge_2[of m] by simp\n\nlemma prime_factors_S_le_subs:\n  \"prime_factors (S m + 1) \\<subseteq> prime_factors (S n)\" if \"m < n\"\n  using that\n  apply (induction n)\n  apply simp\n  subgoal for n\n    apply (cases \"m = n\")\n    using prime_factors_S_Suc\n     apply simp\n    apply simp\n    apply (erule subset_trans)\n    using prime_factors_subs[of \"S n\" \"S n + 1\"] S_ge_2[of n]\n    apply simp\n    done\n  done\n\nlemma prime_factors_int_Suc:\n  \"prime_factors n \\<inter> prime_factors (n + 1) = {}\" if \"n > 0\" for n :: nat\n  by (metis add_eq_0_iff_both_eq_0 gcd_add2 inf_bot_right not_gr_zero prime_factorization_1\n      prime_factors_gcd set_mset_empty that zero_neq_one)\n\nlemma prime_factors_S_neq:\n  \"prime_factors (S m + 1) \\<inter> prime_factors (S n + 1) = {}\" if \"m < n\"\n  using prime_factors_int_Suc[of \"S n\"] S_ge_2[of n] prime_factors_S_le_subs[OF \\<open>m < n\\<close>] by auto\n\nlemma pf_S_inj_aux:\n  assumes \"pf(S(n)+1) = pf(S(m)+1)\" \"m < n\"\n  shows False\nproof -\n  have \"pf(S(n)+1) \\<in> prime_factors (S n + 1)\" \"pf(S(m)+1) \\<in> prime_factors (S m + 1)\"\n    using S_ge_2[of n] S_ge_2[of m] by auto\n  with prime_factors_S_neq[OF \\<open>m < n\\<close>] assms(1) show ?thesis\n    by auto\nqed\n\n\ntheorem pf_S_inj:\n  assumes \"pf(S(n)+1) = pf(S(m)+1)\"\n  shows \"n = m\"\n  using pf_S_inj_aux assms by (metis less_linear)\n\ntheorem infinitely_many_primes:\n  \"infinite {p :: nat. prime p}\"\nproof -\n  let ?S = \"(\\<lambda>n. pf(S(n)+1)) ` UNIV\" let ?P = \"{p :: nat. prime p}\"\n  have \"?S \\<subseteq> ?P\"\n    using prime_pf_Suc_S by auto\n  moreover have \"infinite ?S\"\n    by (intro range_inj_infinite inj_onI, rule pf_S_inj)\n  ultimately show ?thesis\n    by (rule infinite_super)\nqed\n\nend\n", "meta": {"author": "maxhaslbeck", "repo": "proofground2020-solutions", "sha": "023ec2643f6aa06e60bec391e20f178c258ea1a3", "save_path": "github-repos/isabelle/maxhaslbeck-proofground2020-solutions", "path": "github-repos/isabelle/maxhaslbeck-proofground2020-solutions/proofground2020-solutions-023ec2643f6aa06e60bec391e20f178c258ea1a3/infinitude_of_primes/Isabelle/wimmers/Submission.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952838963489, "lm_q2_score": 0.82893881677331, "lm_q1q2_score": 0.7441344664560201}}
{"text": "(*\n  File:    Eulerian_Polynomials.thy\n  Author:  Manuel Eberl, TU M\u00fcnchen\n*)\nsection \\<open>Eulerian polynomials\\<close>\ntheory Eulerian_Polynomials\nimports \n  Complex_Main \n  \"HOL-Combinatorics.Stirling\"\n  \"HOL-Computational_Algebra.Computational_Algebra\"\nbegin\n\ntext \\<open>\n  The Eulerian polynomials are a sequence of polynomials that is related to\n  the closed forms of the power series\n  \\[\\sum_{n=0}^\\infty n^k X^n\\]\n  for a fixed $k$.\n\\<close>\nprimrec eulerian_poly :: \"nat \\<Rightarrow> 'a :: idom poly\" where\n  \"eulerian_poly 0 = 1\"\n| \"eulerian_poly (Suc n) = (let p = eulerian_poly n in \n     [:0,1,-1:] * pderiv p + p * [:1, of_nat n:])\"\n\nlemmas eulerian_poly_Suc [simp del] = eulerian_poly.simps(2)\n\nlemma eulerian_poly:\n  \"fps_of_poly (eulerian_poly k :: 'a :: field poly) = \n     Abs_fps (\\<lambda>n. of_nat (n+1) ^ k) * (1 - fps_X) ^ (k + 1)\"\nproof (induction k)\n  case 0\n  have \"Abs_fps (\\<lambda>_. 1 :: 'a) = inverse (1 - fps_X)\"\n    by (rule fps_inverse_unique [symmetric])\n       (simp add: inverse_mult_eq_1 fps_inverse_gp' [symmetric])\n  thus ?case by (simp add: inverse_mult_eq_1)\nnext\n  case (Suc k)\n  define p :: \"'a fps\" where \"p = fps_of_poly (eulerian_poly k)\"\n  define F :: \"'a fps\" where \"F = Abs_fps (\\<lambda>n. of_nat (n+1) ^ k)\"\n\n  have p: \"p = F * (1 - fps_X) ^ (k+1)\" by (simp add: p_def Suc F_def)\n  have p': \"fps_deriv p = fps_deriv F * (1 - fps_X) ^ (k + 1) - F * (1 - fps_X) ^ k * of_nat (k + 1)\"\n    by (simp add: p fps_deriv_power algebra_simps fps_const_neg [symmetric] fps_of_nat \n             del: power_Suc of_nat_Suc fps_const_neg)\n  \n  have \"fps_of_poly (eulerian_poly (Suc k)) = (fps_X * fps_deriv F + F) * (1 - fps_X) ^ (Suc k + 1)\"\n    apply (simp add: Let_def p_def [symmetric] fps_of_poly_simps eulerian_poly_Suc del: power_Suc)\n    apply (simp add: p p' fps_deriv_power fps_const_neg [symmetric] fps_of_nat\n                del: power_Suc of_nat_Suc fps_const_neg)\n    apply (simp add: algebra_simps)\n    done\n  also have \"fps_X * fps_deriv F + F = Abs_fps (\\<lambda>n. of_nat (n + 1) ^ Suc k)\"\n    unfolding F_def by (intro fps_ext) (auto simp: algebra_simps)\n  finally show ?case .\nqed\n\nlemma eulerian_poly':\n  \"Abs_fps (\\<lambda>n. of_nat (n+1) ^ k) = \n     fps_of_poly (eulerian_poly k :: 'a :: field poly) / (1 - fps_X) ^ (k + 1)\"\n  by (subst eulerian_poly) simp\n  \nlemma eulerian_poly'':\n  assumes k: \"k > 0\"\n  shows \"Abs_fps (\\<lambda>n. of_nat n ^ k) = \n           fps_of_poly (pCons 0 (eulerian_poly k :: 'a :: field poly)) / (1 - fps_X) ^ (k + 1)\"\nproof -\n  from assms have \"Abs_fps (\\<lambda>n. of_nat n ^ k :: 'a) = fps_X * Abs_fps (\\<lambda>n. of_nat (n + 1) ^ k)\"\n    by (intro fps_ext) (auto simp: of_nat_diff)\n  also have \"Abs_fps (\\<lambda>n. of_nat (n + 1) ^ k :: 'a) = \n               fps_of_poly (eulerian_poly k) / (1 - fps_X) ^ (k + 1)\" by (rule eulerian_poly')\n  also have \"fps_X * \\<dots> = fps_of_poly (pCons 0 (eulerian_poly k)) / (1 - fps_X) ^ (k + 1)\"\n    by (simp add: fps_of_poly_pCons fps_divide_unit)\n  finally show ?thesis .\nqed\n\ndefinition fps_monom_poly :: \"'a :: field \\<Rightarrow> nat \\<Rightarrow> 'a poly\"\n  where \"fps_monom_poly c k = (if k = 0 then 1 else pcompose (pCons 0 (eulerian_poly k)) [:0,c:])\"\n\nprimrec fps_monom_poly_aux :: \"'a :: field \\<Rightarrow> nat \\<Rightarrow> 'a poly\" where\n  \"fps_monom_poly_aux c 0 = [:c:]\"\n| \"fps_monom_poly_aux c (Suc k) = \n      (let p = fps_monom_poly_aux c k\n       in  [:0,1,-c:] * pderiv p + [:1, of_nat k * c:] * p)\"\n\nlemma fps_monom_poly_aux:\n  \"fps_monom_poly_aux c k = smult c (pcompose (eulerian_poly k) [:0,c:])\"\n  by (induction k) \n     (simp_all add: eulerian_poly_Suc Let_def pderiv_pcompose pcompose_pCons\n                    pcompose_add pcompose_smult pcompose_uminus smult_add_right pderiv_pCons\n                    pderiv_smult algebra_simps one_pCons)\n\nlemma fps_monom_poly_code [code]:\n  \"fps_monom_poly c k = (if k = 0 then 1 else pCons 0 (fps_monom_poly_aux c k))\"\n  by (simp add: fps_monom_poly_def fps_monom_poly_aux pcompose_pCons)\n\nlemma fps_monom_aux: \n  \"Abs_fps (\\<lambda>n. of_nat n ^ k) = fps_of_poly (fps_monom_poly 1 k) / (1 - fps_X) ^ (k+1)\"\nproof (cases \"k = 0\")\n  assume [simp]: \"k = 0\"\n  hence \"Abs_fps (\\<lambda>n. of_nat n ^ k :: 'a) = Abs_fps (\\<lambda>_. 1)\" by simp\n  also have \"\\<dots> = 1 / (1 - fps_X)\" by (subst gp [symmetric]) simp_all\n  finally show ?thesis by (simp add: fps_monom_poly_def)\nqed (insert eulerian_poly''[of k, where ?'a = 'a], simp add: fps_monom_poly_def)\n\nlemma fps_monom:\n  \"Abs_fps (\\<lambda>n. of_nat n ^ k * c ^ n) = \n      fps_of_poly (fps_monom_poly c k) / (1 - fps_const c * fps_X) ^ (k+1)\"\nproof -\n  have \"Abs_fps (\\<lambda>n. of_nat n ^ k * c ^ n) = \n          fps_compose (Abs_fps (\\<lambda>n. of_nat n ^ k)) (fps_const c * fps_X)\"\n    by (subst fps_compose_linear) (simp add: mult_ac)\n  also have \"Abs_fps (\\<lambda>n. of_nat n ^ k) = fps_of_poly (fps_monom_poly 1 k) / (1 - fps_X) ^ (k+1)\"\n    by (rule fps_monom_aux)\n  also have \"fps_compose \\<dots> (fps_const c * fps_X) = \n                 (fps_of_poly (fps_monom_poly 1 k) oo fps_const c * fps_X) /\n                 ((1 - fps_X) ^ (k + 1) oo fps_const c * fps_X)\"\n    by (intro fps_compose_divide_distrib)\n       (simp_all add: fps_compose_power [symmetric] fps_compose_sub_distrib del: power_Suc)\n  also have \"fps_of_poly (fps_monom_poly 1 k) oo (fps_const c * fps_X) = \n                fps_of_poly (fps_monom_poly c k)\"\n    by (simp add: fps_monom_poly_def fps_of_poly_pcompose fps_of_poly_simps\n                  fps_of_poly_pCons mult_ac)\n  also have \"((1 - fps_X) ^ (k + 1) oo fps_const c * fps_X) = (1 - fps_const c * fps_X) ^ (k + 1)\"\n    by (simp add: fps_compose_power [symmetric] fps_compose_sub_distrib del: power_Suc)\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/Linear_Recurrences/Eulerian_Polynomials.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.877476800298183, "lm_q2_score": 0.847967764140929, "lm_q1q2_score": 0.7440720404343867}}
{"text": "(*\n  File:     Min_Int_Poly.thy\n  Author:   Manuel Eberl, TU M\u00fcnchen\n*)\nsection \\<open>The minimal polynomial of an algebraic number\\<close>\ntheory Min_Int_Poly\nimports\n  Algebraic_Numbers_Prelim\nbegin\n\ntext \\<open>\n  Given an algebraic number \\<open>x\\<close> in a field, the minimal polynomial is the unique irreducible\n  integer polynomial with positive leading coefficient that has \\<open>x\\<close> as a root.\n\n  Note that we assume characteristic 0 since the material upon which all of this builds also\n  assumes it.\n\\<close>\n\ndefinition min_int_poly :: \"'a :: field_char_0 \\<Rightarrow> int poly\" where\n  \"min_int_poly x =\n     (if algebraic x then THE p. p represents x \\<and> irreducible p \\<and> lead_coeff p > 0\n      else [:0, 1:])\"\n\nlemma\n  fixes x :: \"'a :: {field_char_0, field_gcd}\"\n  shows min_int_poly_represents [intro]: \"algebraic x \\<Longrightarrow> min_int_poly x represents x\"\n  and   min_int_poly_irreducible [intro]: \"irreducible (min_int_poly x)\"\n  and   lead_coeff_min_int_poly_pos: \"lead_coeff (min_int_poly x) > 0\"\nproof -\n  note * = theI'[OF algebraic_imp_represents_unique, of x]\n  show \"min_int_poly x represents x\" if \"algebraic x\"\n    using *[OF that] by (simp add: that min_int_poly_def)\n  have \"irreducible [:0, 1::int:]\"\n    by (rule irreducible_linear_poly) auto\n  thus \"irreducible (min_int_poly x)\"\n    using * by (auto simp: min_int_poly_def)\n  show \"lead_coeff (min_int_poly x) > 0\"\n    using * by (auto simp: min_int_poly_def)\nqed\n\nlemma \n  fixes x :: \"'a :: {field_char_0, field_gcd}\"\n  shows degree_min_int_poly_pos [intro]: \"degree (min_int_poly x) > 0\"\n    and degree_min_int_poly_nonzero [simp]: \"degree (min_int_poly x) \\<noteq> 0\"\nproof -\n  show \"degree (min_int_poly x) > 0\"\n  proof (cases \"algebraic x\")\n    case True\n    hence \"min_int_poly x represents x\"\n      by auto\n    thus ?thesis by blast\n  qed (auto simp: min_int_poly_def)\n  thus \"degree (min_int_poly x) \\<noteq> 0\"\n    by blast\nqed\n\nlemma min_int_poly_primitive [intro]:\n  fixes x :: \"'a :: {field_char_0, field_gcd}\"\n  shows \"primitive (min_int_poly x)\"\n  by (rule irreducible_imp_primitive) auto\n\nlemma min_int_poly_content [simp]:\n  fixes x :: \"'a :: {field_char_0, field_gcd}\"\n  shows \"content (min_int_poly x) = 1\"\n  using min_int_poly_primitive[of x] by (simp add: primitive_def)\n\nlemma ipoly_min_int_poly [simp]: \n  \"algebraic x \\<Longrightarrow> ipoly (min_int_poly x) (x :: 'a :: {field_gcd, field_char_0}) = 0\"\n  using min_int_poly_represents[of x] by (auto simp: represents_def)\n\nlemma min_int_poly_nonzero [simp]:\n  fixes x :: \"'a :: {field_char_0, field_gcd}\"\n  shows \"min_int_poly x \\<noteq> 0\"\n  using lead_coeff_min_int_poly_pos[of x] by auto\n\nlemma min_int_poly_normalize [simp]:\n  fixes x :: \"'a :: {field_char_0, field_gcd}\"\n  shows \"normalize (min_int_poly x) = min_int_poly x\"\n  unfolding normalize_poly_def using lead_coeff_min_int_poly_pos[of x] by simp\n\nlemma min_int_poly_prime_elem [intro]:\n  fixes x :: \"'a :: {field_char_0, field_gcd}\"\n  shows \"prime_elem (min_int_poly x)\"\n  using min_int_poly_irreducible[of x] by blast\n\nlemma min_int_poly_prime [intro]:\n  fixes x :: \"'a :: {field_char_0, field_gcd}\"\n  shows \"prime (min_int_poly x)\"\n  using min_int_poly_prime_elem[of x]\n  by (simp only: prime_normalize_iff [symmetric] min_int_poly_normalize)\n\nlemma min_int_poly_unique:\n  fixes x :: \"'a :: {field_char_0, field_gcd}\"\n  assumes \"p represents x\" \"irreducible p\" \"lead_coeff p > 0\"\n  shows \"min_int_poly x = p\"\nproof -\n  from assms(1) have x: \"algebraic x\"\n    using algebraic_iff_represents by blast\n  thus ?thesis\n    using the1_equality[OF algebraic_imp_represents_unique[OF x], of p] assms\n    unfolding min_int_poly_def by auto\nqed\n\nlemma min_int_poly_of_int [simp]:\n  \"min_int_poly (of_int n :: 'a :: {field_char_0, field_gcd}) = [:-of_int n, 1:]\"\n  by (intro min_int_poly_unique irreducible_linear_poly) auto\n\nlemma min_int_poly_of_nat [simp]:\n  \"min_int_poly (of_nat n :: 'a :: {field_char_0, field_gcd}) = [:-of_nat n, 1:]\"\n  using min_int_poly_of_int[of \"int n\"] by (simp del: min_int_poly_of_int)\n\nlemma min_int_poly_0 [simp]: \"min_int_poly (0 :: 'a :: {field_char_0, field_gcd}) = [:0, 1:]\"\n  using min_int_poly_of_int[of 0] unfolding of_int_0 by simp\n\nlemma min_int_poly_1 [simp]: \"min_int_poly (1 :: 'a :: {field_char_0, field_gcd}) = [:-1, 1:]\"\n  using min_int_poly_of_int[of 1] unfolding of_int_1 by simp\n\nlemma poly_min_int_poly_0_eq_0_iff [simp]:\n  fixes x :: \"'a :: {field_char_0, field_gcd}\"\n  assumes \"algebraic x\"\n  shows \"poly (min_int_poly x) 0 = 0 \\<longleftrightarrow> x = 0\"\nproof\n  assume *: \"poly (min_int_poly x) 0 = 0\"\n  show \"x = 0\"\n  proof (rule ccontr)\n    assume \"x \\<noteq> 0\"\n    hence \"poly (min_int_poly x) 0 \\<noteq> 0\"\n      using assms by (intro represents_irr_non_0) auto\n    with * show False by contradiction\n  qed\nqed auto\n\nlemma min_int_poly_eqI:\n  fixes x :: \"'a :: {field_char_0, field_gcd}\"\n  assumes \"p represents x\" \"irreducible p\" \"lead_coeff p \\<ge> 0\"\n  shows   \"min_int_poly x = p\"\nproof -\n  from assms have [simp]: \"p \\<noteq> 0\"\n    by auto\n  have \"lead_coeff p \\<noteq> 0\"\n    by auto\n  with assms(3) have \"lead_coeff p > 0\"\n    by linarith\n  moreover have \"algebraic x\"\n    using \\<open>p represents x\\<close> by (meson algebraic_iff_represents)\n  ultimately show ?thesis\n    unfolding min_int_poly_def\n    using the1_equality[OF algebraic_imp_represents_unique[OF \\<open>algebraic x\\<close>], of p] assms by auto\nqed\n\ntext \\<open>Implementation for real and rational numbers\\<close>\n\nlemma min_int_poly_of_rat: \"min_int_poly (of_rat r :: 'a :: {field_char_0, field_gcd}) = poly_rat r\"\n  by (intro min_int_poly_unique, auto)\n\ndefinition min_int_poly_real :: \"real \\<Rightarrow> int poly\" where\n  [simp]: \"min_int_poly_real = min_int_poly\"\n\nlemma min_int_poly_real_code_unfold [code_unfold]: \"min_int_poly = min_int_poly_real\"\n  by simp\n\nlemma min_int_poly_real_basic_impl[code]: \"min_int_poly_real (real_of_rat x) = poly_rat x\" \n  unfolding min_int_poly_real_def by (rule min_int_poly_of_rat)\n\nlemma min_int_poly_rat_code_unfold [code_unfold]: \"min_int_poly = poly_rat\"\n  by (intro ext, insert min_int_poly_of_rat[where ?'a = rat], 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/Algebraic_Numbers/Min_Int_Poly.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8479677660619634, "lm_q2_score": 0.8774767826757123, "lm_q1q2_score": 0.7440720271767627}}
{"text": "theory Funpow\nimports\n  \"HOL-Library.FuncSet\"\n  \"HOL-Library.Permutations\"\nbegin\n\nsection \\<open>Auxiliary Lemmas about @{term \"op ^^\"}\\<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_comp)\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 `m < n` 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    def k' \\<equiv> \"min k l\" and l' \\<equiv> \"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 `f permutes S` 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  def m' \\<equiv> \"min m n\" and n' \\<equiv> \"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  def m' \\<equiv> \"min m n\" and n' \\<equiv> \"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  then have \"\\<not>(funpow_dist1 f x y mod m < funpow_dist1 f x y)\"\n    by (metis False assms(3) funpow_dist_least funpow_dist_prop funpow_dist_step)\n  then show ?thesis\n    by (metis (poly_guards_query) Divides.mod_less_eq_dividend assms(2) le_less mod_less_divisor)\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) `inj f` * 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": "z5146542", "repo": "TOR", "sha": "9a82d491288a6d013e0764f68e602a63e48f92cf", "save_path": "github-repos/isabelle/z5146542-TOR", "path": "github-repos/isabelle/z5146542-TOR/TOR-9a82d491288a6d013e0764f68e602a63e48f92cf/checker-verification/Graph_Theory/Funpow.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8774767810736693, "lm_q2_score": 0.847967764140929, "lm_q1q2_score": 0.7440720241326189}}
{"text": "section \\<open>Tensor products as matrices\\<close>\n\ntheory Finite_Tensor_Product_Matrices\n  imports Finite_Tensor_Product\nbegin\n\ndefinition tensor_pack :: \"nat \\<Rightarrow> nat \\<Rightarrow> (nat \\<times> nat) \\<Rightarrow> nat\"\n  where \"tensor_pack X Y = (\\<lambda>(x, y). x * Y + y)\"\n\ndefinition tensor_unpack :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> (nat \\<times> nat)\"\n  where \"tensor_unpack X Y xy = (xy div Y, xy mod Y)\"\n\nlemma tensor_unpack_inj:\n  assumes \"i < A * B\" and \"j < A * B\"\n  shows \"tensor_unpack A B i = tensor_unpack A B j \\<longleftrightarrow> i = j\"\n  by (metis div_mult_mod_eq prod.sel(1) prod.sel(2) tensor_unpack_def)\n\nlemma tensor_unpack_bound1[simp]: \"i < A * B \\<Longrightarrow> fst (tensor_unpack A B i) < A\"\n  unfolding tensor_unpack_def\n  apply auto\n  using less_mult_imp_div_less by blast\nlemma tensor_unpack_bound2[simp]: \"i < A * B \\<Longrightarrow> snd (tensor_unpack A B i) < B\"\n  unfolding tensor_unpack_def\n  apply auto\n  by (metis mod_less_divisor mult.commute mult_zero_left nat_neq_iff not_less0)\n\nlemma tensor_unpack_fstfst: \\<open>fst (tensor_unpack A B (fst (tensor_unpack (A * B) C i)))\n     = fst (tensor_unpack A (B * C) i)\\<close>\n  unfolding tensor_unpack_def apply auto\n  by (metis div_mult2_eq mult.commute)\nlemma tensor_unpack_sndsnd: \\<open>snd (tensor_unpack B C (snd (tensor_unpack A (B * C) i)))\n     = snd (tensor_unpack (A * B) C i)\\<close>\n  unfolding tensor_unpack_def apply auto\n  by (meson dvd_triv_right mod_mod_cancel)\nlemma tensor_unpack_fstsnd: \\<open>fst (tensor_unpack B C (snd (tensor_unpack A (B * C) i)))\n     = snd (tensor_unpack A B (fst (tensor_unpack (A * B) C i)))\\<close>\n  unfolding tensor_unpack_def apply auto\n  by (cases \\<open>C = 0\\<close>) (simp_all add: mult.commute [of B C] mod_mult2_eq [of i C B])\n\ndefinition \"tensor_state_jnf \\<psi> \\<phi> = (let d1 = dim_vec \\<psi> in let d2 = dim_vec \\<phi> in\n  vec (d1*d2) (\\<lambda>i. let (i1,i2) = tensor_unpack d1 d2 i in (vec_index \\<psi> i1) * (vec_index \\<phi> i2)))\"\n\nlemma tensor_state_jnf_dim[simp]: \\<open>dim_vec (tensor_state_jnf \\<psi> \\<phi>) = dim_vec \\<psi> * dim_vec \\<phi>\\<close>\n  unfolding tensor_state_jnf_def Let_def by simp\n\nlemma enum_prod_nth_tensor_unpack:\n  assumes \\<open>i < CARD('a) * CARD('b)\\<close>\n  shows \"(Enum.enum ! i :: 'a::enum\\<times>'b::enum) = \n        (let (i1,i2) = tensor_unpack CARD('a) CARD('b) i in \n              (Enum.enum ! i1, Enum.enum ! i2))\"\n  using assms \n  by (simp add: enum_prod_def card_UNIV_length_enum product_nth tensor_unpack_def)\n\nlemma vec_of_basis_enum_tensor_state_index:\n  fixes \\<psi> :: \\<open>'a::enum ell2\\<close> and \\<phi> :: \\<open>'b::enum ell2\\<close>\n  assumes [simp]: \\<open>i < CARD('a) * CARD('b)\\<close>\n  shows \\<open>vec_of_basis_enum (\\<psi> \\<otimes>\\<^sub>s \\<phi>) $ i = (let (i1,i2) = tensor_unpack CARD('a) CARD('b) i in\n    vec_of_basis_enum \\<psi> $ i1 * vec_of_basis_enum \\<phi> $ i2)\\<close>\nproof -\n  define i1 i2 where \"i1 = fst (tensor_unpack CARD('a) CARD('b) i)\"\n    and \"i2 = snd (tensor_unpack CARD('a) CARD('b) i)\"\n  have [simp]: \"i1 < CARD('a)\" \"i2 < CARD('b)\"\n    using assms i1_def tensor_unpack_bound1 apply presburger\n    using assms i2_def tensor_unpack_bound2 by presburger\n\n  have \\<open>vec_of_basis_enum (\\<psi> \\<otimes>\\<^sub>s \\<phi>) $ i = Rep_ell2 (\\<psi> \\<otimes>\\<^sub>s \\<phi>) (enum_class.enum ! i)\\<close>\n    by (simp add: vec_of_basis_enum_ell2_component)\n  also have \\<open>\\<dots> = Rep_ell2 \\<psi> (Enum.enum!i1) * Rep_ell2 \\<phi> (Enum.enum!i2)\\<close>\n    apply (transfer fixing: i i1 i2)\n    by (simp add: enum_prod_nth_tensor_unpack case_prod_beta i1_def i2_def)\n  also have \\<open>\\<dots> = vec_of_basis_enum \\<psi> $ i1 * vec_of_basis_enum \\<phi> $ i2\\<close>\n    by (simp add: vec_of_basis_enum_ell2_component)\n  finally show ?thesis\n    by (simp add: case_prod_beta i1_def i2_def)\nqed\n\nlemma vec_of_basis_enum_tensor_state:\n  fixes \\<psi> :: \\<open>'a::enum ell2\\<close> and \\<phi> :: \\<open>'b::enum ell2\\<close>\n  shows \\<open>vec_of_basis_enum (\\<psi> \\<otimes>\\<^sub>s \\<phi>) = tensor_state_jnf (vec_of_basis_enum \\<psi>) (vec_of_basis_enum \\<phi>)\\<close>\n  apply (rule eq_vecI, simp_all)\n  apply (subst vec_of_basis_enum_tensor_state_index, simp_all)\n  by (simp add: tensor_state_jnf_def case_prod_beta Let_def)\n\n\nlemma mat_of_cblinfun_tensor_op_index:\n  fixes a :: \\<open>'a::enum ell2 \\<Rightarrow>\\<^sub>C\\<^sub>L 'b::enum ell2\\<close> and b :: \\<open>'c::enum ell2 \\<Rightarrow>\\<^sub>C\\<^sub>L 'd::enum ell2\\<close>\n  assumes [simp]: \\<open>i < CARD('b) * CARD('d)\\<close>\n  assumes [simp]: \\<open>j < CARD('a) * CARD('c)\\<close>\n  shows \\<open>mat_of_cblinfun (tensor_op a b) $$ (i,j) = \n            (let (i1,i2) = tensor_unpack CARD('b) CARD('d) i in\n             let (j1,j2) = tensor_unpack CARD('a) CARD('c) j in\n                  mat_of_cblinfun a $$ (i1,j1) * mat_of_cblinfun b $$ (i2,j2))\\<close>\nproof -\n  define i1 i2 j1 j2\n    where \"i1 = fst (tensor_unpack CARD('b) CARD('d) i)\"\n      and \"i2 = snd (tensor_unpack CARD('b) CARD('d) i)\"\n      and \"j1 = fst (tensor_unpack CARD('a) CARD('c) j)\"\n      and \"j2 = snd (tensor_unpack CARD('a) CARD('c) j)\"\n  have [simp]: \"i1 < CARD('b)\" \"i2 < CARD('d)\" \"j1 < CARD('a)\" \"j2 < CARD('c)\"\n    using assms i1_def tensor_unpack_bound1 apply presburger\n    using assms i2_def tensor_unpack_bound2 apply blast\n    using assms(2) j1_def tensor_unpack_bound1 apply blast\n    using assms(2) j2_def tensor_unpack_bound2 by presburger\n\n  have \\<open>mat_of_cblinfun (tensor_op a b) $$ (i,j) \n       = Rep_ell2 (tensor_op a b *\\<^sub>V ket (Enum.enum!j)) (Enum.enum ! i)\\<close>\n    by (simp add: mat_of_cblinfun_ell2_component)\n  also have \\<open>\\<dots> = Rep_ell2 ((a *\\<^sub>V ket (Enum.enum!j1)) \\<otimes>\\<^sub>s (b *\\<^sub>V ket (Enum.enum!j2))) (Enum.enum!i)\\<close>\n    by (simp add: tensor_op_ell2 enum_prod_nth_tensor_unpack[where i=j] Let_def case_prod_beta j1_def[symmetric] j2_def[symmetric] flip: tensor_ell2_ket)\n  also have \\<open>\\<dots> = vec_of_basis_enum ((a *\\<^sub>V ket (Enum.enum!j1)) \\<otimes>\\<^sub>s b *\\<^sub>V ket (Enum.enum!j2)) $ i\\<close>\n    by (simp add: vec_of_basis_enum_ell2_component)\n  also have \\<open>\\<dots> = vec_of_basis_enum (a *\\<^sub>V ket (enum_class.enum ! j1)) $ i1 *\n                  vec_of_basis_enum (b *\\<^sub>V ket (enum_class.enum ! j2)) $ i2\\<close>\n    by (simp add: case_prod_beta vec_of_basis_enum_tensor_state_index i1_def[symmetric] i2_def[symmetric])\n  also have \\<open>\\<dots> = Rep_ell2 (a *\\<^sub>V ket (enum_class.enum ! j1)) (enum_class.enum ! i1) *\n                  Rep_ell2 (b *\\<^sub>V ket (enum_class.enum ! j2)) (enum_class.enum ! i2)\\<close>\n    by (simp add: vec_of_basis_enum_ell2_component)\n  also have \\<open>\\<dots> = mat_of_cblinfun a $$ (i1, j1) * mat_of_cblinfun b $$ (i2, j2)\\<close>\n    by (simp add: mat_of_cblinfun_ell2_component)\n  finally show ?thesis\n    by (simp add: i1_def[symmetric] i2_def[symmetric] j1_def[symmetric] j2_def[symmetric] case_prod_beta)\nqed\n\n\ndefinition \"tensor_op_jnf A B = \n  (let r1 = dim_row A in\n   let c1 = dim_col A in\n   let r2 = dim_row B in\n   let c2 = dim_col B in\n   mat (r1 * r2) (c1 * c2)\n   (\\<lambda>(i,j). let (i1,i2) = tensor_unpack r1 r2 i in\n            let (j1,j2) = tensor_unpack c1 c2 j in\n              (A $$ (i1,j1)) * (B $$ (i2,j2))))\"\n\nlemma tensor_op_jnf_dim[simp]: \n  \\<open>dim_row (tensor_op_jnf a b) = dim_row a * dim_row b\\<close>\n  \\<open>dim_col (tensor_op_jnf a b) = dim_col a * dim_col b\\<close>\n  unfolding tensor_op_jnf_def Let_def by simp_all\n\n\nlemma mat_of_cblinfun_tensor_op:\n  fixes a :: \\<open>'a::enum ell2 \\<Rightarrow>\\<^sub>C\\<^sub>L 'b::enum ell2\\<close> and b :: \\<open>'c::enum ell2 \\<Rightarrow>\\<^sub>C\\<^sub>L 'd::enum ell2\\<close>\n  shows \\<open>mat_of_cblinfun (tensor_op a b) = tensor_op_jnf (mat_of_cblinfun a) (mat_of_cblinfun b)\\<close>\n  apply (rule eq_matI, simp_all add: )\n  apply (subst mat_of_cblinfun_tensor_op_index, simp_all)\n  by (simp add: tensor_op_jnf_def case_prod_beta Let_def)\n\n\nlemma mat_of_cblinfun_assoc_ell2'[simp]: \n  \\<open>mat_of_cblinfun (assoc_ell2' :: (('a::enum\\<times>('b::enum\\<times>'c::enum)) ell2 \\<Rightarrow>\\<^sub>C\\<^sub>L _)) = one_mat (CARD('a)*CARD('b)*CARD('c))\\<close>\n  (is \"mat_of_cblinfun ?assoc = _\")\nproof  (rule mat_eq_iff[THEN iffD2], intro conjI allI impI)\n\n  show \\<open>dim_row (mat_of_cblinfun ?assoc) =\n    dim_row (1\\<^sub>m (CARD('a) * CARD('b) * CARD('c)))\\<close>\n    by (simp)\n  show \\<open>dim_col (mat_of_cblinfun ?assoc) =\n    dim_col (1\\<^sub>m (CARD('a) * CARD('b) * CARD('c)))\\<close>\n    by (simp)\n\n  fix i j\n  let ?i = \"Enum.enum ! i :: (('a\\<times>'b)\\<times>'c)\" and ?j = \"Enum.enum ! j :: ('a\\<times>('b\\<times>'c))\"\n\n  assume \\<open>i < dim_row (1\\<^sub>m (CARD('a) * CARD('b) * CARD('c)))\\<close>\n  then have iB[simp]: \\<open>i < CARD('a) * CARD('b) * CARD('c)\\<close> by simp\n  then have iB'[simp]: \\<open>i < CARD('a) * (CARD('b) * CARD('c))\\<close> by linarith\n  assume \\<open>j < dim_col (1\\<^sub>m (CARD('a) * CARD('b) * CARD('c)))\\<close>\n  then have jB[simp]: \\<open>j < CARD('a) * CARD('b) * CARD('c)\\<close> by simp\n  then have jB'[simp]: \\<open>j < CARD('a) * (CARD('b) * CARD('c))\\<close> by linarith\n\n  define i1 i23 i2 i3\n    where \"i1 = fst (tensor_unpack CARD('a) (CARD('b)*CARD('c)) i)\"\n      and \"i23 = snd (tensor_unpack CARD('a) (CARD('b)*CARD('c)) i)\"\n      and \"i2 = fst (tensor_unpack CARD('b) CARD('c) i23)\"\n      and \"i3 = snd (tensor_unpack CARD('b) CARD('c) i23)\"\n  define j12 j1 j2 j3\n    where \"j12 = fst (tensor_unpack (CARD('a)*CARD('b)) CARD('c) j)\"\n      and \"j1 = fst (tensor_unpack CARD('a) CARD('b) j12)\"\n      and \"j2 = snd (tensor_unpack CARD('a) CARD('b) j12)\"\n      and \"j3 = snd (tensor_unpack (CARD('a)*CARD('b)) CARD('c) j)\"\n\n  have [simp]: \"j12 < CARD('a)*CARD('b)\" \"i23 < CARD('b)*CARD('c)\"\n    using j12_def jB tensor_unpack_bound1 apply presburger\n    using i23_def iB' tensor_unpack_bound2 by blast\n\n  have j1': \\<open>fst (tensor_unpack CARD('a) (CARD('b) * CARD('c)) j) = j1\\<close>\n    by (simp add: j1_def j12_def tensor_unpack_fstfst)\n\n  let ?i1 = \"Enum.enum ! i1 :: 'a\" and ?i2 = \"Enum.enum ! i2 :: 'b\" and ?i3 = \"Enum.enum ! i3 :: 'c\"\n  let ?j1 = \"Enum.enum ! j1 :: 'a\" and ?j2 = \"Enum.enum ! j2 :: 'b\" and ?j3 = \"Enum.enum ! j3 :: 'c\"\n\n  have i: \\<open>?i = ((?i1,?i2),?i3)\\<close>\n    by (auto simp add: enum_prod_nth_tensor_unpack case_prod_beta\n          tensor_unpack_fstfst tensor_unpack_fstsnd tensor_unpack_sndsnd i1_def i2_def i23_def i3_def)\n  have j: \\<open>?j = (?j1,(?j2,?j3))\\<close> \n    by (auto simp add: enum_prod_nth_tensor_unpack case_prod_beta\n        tensor_unpack_fstfst tensor_unpack_fstsnd tensor_unpack_sndsnd j1_def j2_def j12_def j3_def)\n  have ijeq: \\<open>(?i1,?i2,?i3) = (?j1,?j2,?j3) \\<longleftrightarrow> i = j\\<close>\n    unfolding i1_def i2_def i3_def j1_def j2_def j3_def apply simp\n    apply (subst enum_inj, simp, simp)\n    apply (subst enum_inj, simp, simp)\n    apply (subst enum_inj, simp, simp)\n    apply (subst tensor_unpack_inj[symmetric, where i=i and j=j and A=\"CARD('a)\" and B=\"CARD('b)*CARD('c)\"], simp, simp)\n    unfolding prod_eq_iff\n    apply (subst tensor_unpack_inj[symmetric, where i=\\<open>snd (tensor_unpack CARD('a) (CARD('b) * CARD('c)) i)\\<close> and A=\"CARD('b)\" and B=\"CARD('c)\"], simp, simp)\n    by (simp add: i1_def[symmetric] j1_def[symmetric] i2_def[symmetric] j2_def[symmetric] i3_def[symmetric] j3_def[symmetric]\n        i23_def[symmetric] j12_def[symmetric] j1'\n        prod_eq_iff tensor_unpack_fstsnd tensor_unpack_sndsnd)\n\n  have \\<open>mat_of_cblinfun ?assoc $$ (i, j) = Rep_ell2 (assoc_ell2' *\\<^sub>V ket ?j) ?i\\<close>\n    by (subst mat_of_cblinfun_ell2_component, auto)\n  also have \\<open>\\<dots> = Rep_ell2 ((ket ?j1 \\<otimes>\\<^sub>s ket ?j2) \\<otimes>\\<^sub>s ket ?j3) ?i\\<close>\n    by (simp add: j assoc_ell2'_tensor flip: tensor_ell2_ket)\n  also have \\<open>\\<dots> = (if (?i1,?i2,?i3) = (?j1,?j2,?j3) then 1 else 0)\\<close>\n    by (auto simp add: ket.rep_eq i)\n  also have \\<open>\\<dots> = (if i=j then 1 else 0)\\<close>\n    using ijeq by simp\n  finally\n  show \\<open>mat_of_cblinfun ?assoc $$ (i, j) =\n           1\\<^sub>m (CARD('a) * CARD('b) * CARD('c)) $$ (i, j)\\<close>\n    by auto\nqed\n\nlemma assoc_ell2'_inv: \"assoc_ell2 o\\<^sub>C\\<^sub>L assoc_ell2' = id_cblinfun\"\n  apply (rule equal_ket, case_tac x, hypsubst)\n  by (simp flip: tensor_ell2_ket add: cblinfun_apply_cblinfun_compose assoc_ell2'_tensor assoc_ell2_tensor)\n\nlemma assoc_ell2_inv: \"assoc_ell2' o\\<^sub>C\\<^sub>L assoc_ell2 = id_cblinfun\"\n  apply (rule equal_ket, case_tac x, hypsubst)\n  by (simp flip: tensor_ell2_ket add: cblinfun_apply_cblinfun_compose assoc_ell2'_tensor assoc_ell2_tensor)\n\nlemma mat_of_cblinfun_assoc_ell2[simp]: \n  \\<open>mat_of_cblinfun (assoc_ell2 :: ((('a::enum\\<times>'b::enum)\\<times>'c::enum) ell2 \\<Rightarrow>\\<^sub>C\\<^sub>L _)) = one_mat (CARD('a)*CARD('b)*CARD('c))\\<close>\n  (is \"mat_of_cblinfun ?assoc = _\")\nproof -\n  let ?assoc' = \"assoc_ell2' :: (('a::enum\\<times>('b::enum\\<times>'c::enum)) ell2 \\<Rightarrow>\\<^sub>C\\<^sub>L _)\"\n  have \"one_mat (CARD('a)*CARD('b)*CARD('c)) = mat_of_cblinfun (?assoc o\\<^sub>C\\<^sub>L ?assoc')\"\n    by (simp add: mult.assoc mat_of_cblinfun_id)\n  also have \\<open>\\<dots> = mat_of_cblinfun ?assoc * mat_of_cblinfun ?assoc'\\<close>\n    using mat_of_cblinfun_compose by blast\n  also have \\<open>\\<dots> = mat_of_cblinfun ?assoc * one_mat (CARD('a)*CARD('b)*CARD('c))\\<close>\n    by simp\n  also have \\<open>\\<dots> = mat_of_cblinfun ?assoc\\<close>\n    apply (rule right_mult_one_mat')\n    by (simp)\n  finally show ?thesis\n    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/Registers/Finite_Tensor_Product_Matrices.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.877476784277755, "lm_q2_score": 0.8479677506936878, "lm_q1q2_score": 0.7440720150499383}}
{"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_TSortCount\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 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 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 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\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  \"((count x (tsort 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_TSortCount.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896715436483, "lm_q2_score": 0.8080672158638527, "lm_q1q2_score": 0.7440599462804672}}
{"text": "theory ZFC_Library\n  imports \"HOL-Library.Countable_Set\" \"HOL-Library.Equipollence\" \"HOL-Cardinals.Cardinals\"\n\nbegin\n\ntext\\<open>Equipollence and Lists.\\<close>\n\nlemma countable_iff_lepoll: \"countable A \\<longleftrightarrow> A \\<lesssim> (UNIV :: nat set)\"\n  by (auto simp: countable_def lepoll_def)\n\nlemma infinite_times_eqpoll_self:\n  assumes \"infinite A\" shows \"A \\<times> A \\<approx> A\"\n  by (simp add: Times_same_infinite_bij_betw assms eqpoll_def)\n\nlemma infinite_finite_times_lepoll_self:\n  assumes \"infinite A\" \"finite B\" shows \"A \\<times> B \\<lesssim> A\"\nproof -\n  have \"B \\<lesssim> A\"\n    by (simp add: assms finite_lepoll_infinite)\n  then have \"A \\<times> B \\<lesssim> A \\<times> A\"\n    by (simp add: subset_imp_lepoll times_lepoll_mono)\n  also have \"\\<dots> \\<approx> A\"\n    by (simp add: \\<open>infinite A\\<close> infinite_times_eqpoll_self)\n  finally show ?thesis .\nqed\n\nlemma lists_n_lepoll_self:\n  assumes \"infinite A\" shows \"{l \\<in> lists A. length l = n} \\<lesssim> A\"\nproof (induction n)\n  case 0\n  have \"{l \\<in> lists A. length l = 0} = {[]}\"\n    by auto\n  then show ?case\n    by (metis Set.set_insert assms ex_in_conv finite.emptyI singleton_lepoll)\nnext\n  case (Suc n)\n  have \"{l \\<in> lists A. length l = Suc n} = (\\<Union>x\\<in>A. \\<Union>l \\<in> {l \\<in> lists A. length l = n}. {x#l})\"\n    by (auto simp: length_Suc_conv)\n  also have \"\\<dots> \\<lesssim> A \\<times> {l \\<in> lists A. length l = n}\"\n    unfolding lepoll_iff\n    by (rule_tac x=\"\\<lambda>(x,l). Cons x l\" in exI) auto\n  also have \"\\<dots> \\<lesssim> A\"\n  proof (cases \"finite {l \\<in> lists A. length l = n}\")\n    case True\n    then show ?thesis\n      using assms infinite_finite_times_lepoll_self by blast\n  next\n    case False\n    have \"A \\<times> {l \\<in> lists A. length l = n} \\<lesssim> A \\<times> A\"\n      by (simp add: Suc.IH subset_imp_lepoll times_lepoll_mono)\n    also have \"\\<dots> \\<approx> A\"\n      by (simp add: assms infinite_times_eqpoll_self)\n    finally show ?thesis .\n  qed\n  finally show ?case .\nqed\n\nlemma infinite_eqpoll_lists:\n    assumes \"infinite A\" shows \"lists A \\<approx> A\"\nproof -\n  have \"lists A \\<lesssim> Sigma UNIV (\\<lambda>n. {l \\<in> lists A. length l = n})\"\n    unfolding lepoll_iff\n    by (rule_tac x=snd in exI) (auto simp: in_listsI snd_image_Sigma)\n  also have \"\\<dots> \\<lesssim> (UNIV::nat set) \\<times> A\"\n    by (rule Sigma_lepoll_mono) (auto simp: lists_n_lepoll_self assms)\n  also have \"\\<dots> \\<lesssim> A \\<times> A\"\n    by (metis assms infinite_le_lepoll order_refl subset_imp_lepoll times_lepoll_mono)\n  also have \"\\<dots> \\<approx> A\"\n    by (simp add: assms infinite_times_eqpoll_self)\n  finally show ?thesis\n    by (simp add: lepoll_antisym lepoll_lists)\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/ZFC_Library.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312213841788, "lm_q2_score": 0.8198933359135361, "lm_q1q2_score": 0.7438992377218391}}
{"text": "(*\n  File: Finite.thy\n  Author: Bohua Zhan\n\n  Finite sets.\n*)\n\ntheory Finite\n  imports Nat\nbegin\n\nsection \\<open>Set of first n natural numbers\\<close>\n\ndefinition nat_less_range :: \"i \\<Rightarrow> i\" where [rewrite]:\n  \"nat_less_range(n) = {x\\<in>.\\<nat>. x <\\<^sub>\\<nat> n}\"\nsetup {* register_wellform_data (\"nat_less_range(n)\", [\"n \\<in> nat\"]) *}\nnotation nat_less_range (\"[_]\")\n\nlemma nat_less_rangeI [typing2]:\n  \"m \\<in>. \\<nat> \\<Longrightarrow> n \\<in>. \\<nat> \\<Longrightarrow> m <\\<^sub>\\<nat> n \\<Longrightarrow> m \\<in> [n]\" by auto2\n\nlemma nat_less_range_iff [rewrite]: \"n \\<in> nat \\<Longrightarrow> m \\<in> [n] \\<longleftrightarrow> m <\\<^sub>\\<nat> n\" by auto2\nsetup {* del_prfstep_thm @{thm nat_less_range_def} *}\n\nlemma nat_less_range_zero [rewrite]: \"[0] = \\<emptyset>\" by auto2\nlemma nat_less_range_empty_iff [rewrite]: \"x \\<in> nat \\<Longrightarrow> [x] = \\<emptyset> \\<longleftrightarrow> x = 0\"\n  @proof @case \"x \\<noteq> 0\" @with @have \"x >\\<^sub>\\<nat> 0\" @end @qed\n\nlemma nat_less_range_notin [resolve]: \"k \\<in> nat \\<Longrightarrow> k \\<notin> [k]\" by auto2\nlemma nat_less_range_Suc [rewrite_back]: \"n \\<in> nat \\<Longrightarrow> [n +\\<^sub>\\<nat> 1] = cons(n,[n])\" by auto2\nlemma nat_less_range_Suc_diff [rewrite]: \"n \\<in>. \\<nat> \\<Longrightarrow> [n +\\<^sub>\\<nat> 1] \\<midarrow> {n} = [n]\" by auto2\n\nlemma equipotent_nat_less_range [forward]:\n  \"m \\<in> nat \\<Longrightarrow> n \\<in> nat \\<Longrightarrow> [m] \\<approx>\\<^sub>S [n] \\<Longrightarrow> m = n\"\n@proof\n  @var_induct \"m \\<in> nat\" arbitrary n @with\n    @subgoal \"m = m' +\\<^sub>\\<nat> 1\"\n      @obtain \"n'\\<in>nat\" where \"n = n' +\\<^sub>\\<nat> 1\"\n      @have \"[m'] = [m' +\\<^sub>\\<nat> 1] \\<midarrow> {m'}\"\n      @have \"[n'] = [n' +\\<^sub>\\<nat> 1] \\<midarrow> {n'}\"\n      @have \"[m'] \\<approx>\\<^sub>S [n']\"\n    @endgoal\n  @end\n@qed\n\nsection \\<open>Cardinality on finite sets\\<close>\n  \ndefinition finite :: \"i \\<Rightarrow> o\" where [rewrite]:\n  \"finite(X) \\<longleftrightarrow> (\\<exists>n\\<in>nat. X \\<approx>\\<^sub>S [n])\"\n\nlemma finiteI [forward]: \"n \\<in> nat \\<Longrightarrow> X \\<approx>\\<^sub>S [n] \\<Longrightarrow> finite(X)\" by auto2\nlemma finiteD [backward]: \"finite(X) \\<Longrightarrow> \\<exists>n\\<in>nat. X \\<approx>\\<^sub>S [n]\" by auto2\nsetup {* del_prfstep_thm @{thm finite_def} *}\n\nlemma finite_empty [forward]: \"finite(\\<emptyset>)\"\n  @proof @have \"\\<emptyset> \\<approx>\\<^sub>S [0]\" @qed\n\nlemma finite_nat_less_range: \"k \\<in> nat \\<Longrightarrow> finite([k])\"\n  @proof @have \"[k] \\<approx>\\<^sub>S [k]\" @qed\nsetup {* add_forward_prfstep_cond @{thm finite_nat_less_range} [with_term \"[?k]\"] *}\n\nlemma finite_cons [forward]: \"finite(X) \\<Longrightarrow> finite(cons(a,X))\"\n@proof\n  @contradiction\n  @obtain \"n\\<in>nat\" where \"X \\<approx>\\<^sub>S [n]\"\n  @have \"cons(a,X) \\<approx>\\<^sub>S [n +\\<^sub>\\<nat> 1]\" @with\n    @have \"[n +\\<^sub>\\<nat> 1] = cons(n,[n])\" @end\n@qed\n\nlemma finite_diff_singleton: \"finite(X) \\<Longrightarrow> finite(X \\<midarrow> {a})\"\n@proof\n  @case \"a \\<notin> X\"\n  @obtain \"n\\<in>nat\" where \"X \\<approx>\\<^sub>S [n]\"\n  @have \"n \\<noteq> 0\"\n  @obtain \"n'\\<in>nat\" where \"n = n' +\\<^sub>\\<nat> 1\"\n  @have \"X \\<midarrow> {a} \\<approx>\\<^sub>S [n']\" @with @have \"[n'] = [n] \\<midarrow> {n'}\" @end\n@qed\nsetup {* add_forward_prfstep_cond @{thm finite_diff_singleton} [with_term \"?X \\<midarrow> {?a}\"] *}\n\ndefinition card :: \"i \\<Rightarrow> i\" where [rewrite]:\n  \"card(X) = (THE n. n \\<in> nat \\<and> X \\<approx>\\<^sub>S [n])\"\n\nlemma card_unique [forward]:\n  \"m \\<in> nat \\<Longrightarrow> n \\<in> nat \\<Longrightarrow> X \\<approx>\\<^sub>S [m] \\<Longrightarrow> X \\<approx>\\<^sub>S [n] \\<Longrightarrow> m = n\"\n@proof @have \"[m] \\<approx>\\<^sub>S [n]\" @qed\n\nlemma card_type [typing]: \"finite(X) \\<Longrightarrow> card(X) \\<in> nat\" by auto2\nlemma card_equipotent [resolve]: \"finite(X) \\<Longrightarrow> X \\<approx>\\<^sub>S [card(X)]\" by auto2\nlemma cardI [rewrite]: \"n \\<in> nat \\<Longrightarrow> X \\<approx>\\<^sub>S [n] \\<Longrightarrow> card(X) = n\" by auto2\nsetup {* del_prfstep_thm @{thm card_def} *}\n\nlemma card_empty [rewrite]: \"card(\\<emptyset>) = 0\"\n@proof @have \"\\<emptyset> \\<approx>\\<^sub>S [0]\" @qed\n\nlemma card_empty' [forward]: \"finite(X) \\<Longrightarrow> card(X) = 0 \\<Longrightarrow> X = \\<emptyset>\"\n@proof @have \"X \\<approx>\\<^sub>S [0]\" @qed\n\nlemma card_nat_less_range [rewrite]: \"k \\<in> nat \\<Longrightarrow> card([k]) = k\"\n@proof @have \"[k] \\<approx>\\<^sub>S [k]\" @qed\n\nlemma card_cons [rewrite]:\n  \"finite(X) \\<Longrightarrow> a \\<notin> X \\<Longrightarrow> n = card(X) \\<Longrightarrow> card(cons(a,X)) = n +\\<^sub>\\<nat> 1\"\n@proof\n  @have \"X \\<approx>\\<^sub>S [n]\" @have \"[n +\\<^sub>\\<nat> 1] = cons(n,[n])\"\n  @have \"cons(a,X) \\<approx>\\<^sub>S cons(n,[n])\"\n@qed\n\nno_notation nat_less_range (\"[_]\")\n\nsection \\<open>Induction on finite sets\\<close>\n\nlemma card_Suc_elim [resolve]:\n  \"finite(F) \\<Longrightarrow> n \\<in>. \\<nat> \\<Longrightarrow> card(F) = n +\\<^sub>\\<nat> 1 \\<Longrightarrow> \\<exists>a F'. F = cons(a,F') \\<and> a \\<notin> F' \\<and> finite(F') \\<and> card(F') = n\"\n@proof @obtain \"a \\<in> F\" @have \"F = cons(a,F\\<midarrow>{a})\" @qed\nsetup {* del_prfstep_thm @{thm finite_diff_singleton} *}\n\nlemma card_1_elim [backward]:\n  \"finite(F) \\<Longrightarrow> card(F) = 1 \\<Longrightarrow> \\<exists>a. F = {a}\"\n@proof\n  @have \"1 = 0 +\\<^sub>\\<nat> 1\"\n  @obtain a F' where \"F = cons(a,F') \\<and> a \\<notin> F' \\<and> finite(F') \\<and> card(F') = 0\"\n@qed\n\nlemma finite_induct [var_induct]:\n  \"finite(F) \\<Longrightarrow> P(\\<emptyset>) \\<Longrightarrow> \\<forall>a X. finite(X) \\<longrightarrow> a \\<notin> X \\<longrightarrow> P(X) \\<longrightarrow> P(cons(a,X)) \\<Longrightarrow> P(F)\"\n@proof\n  @let \"n = card(F)\"\n  @var_induct \"n \\<in> nat\" arbitrary F @with\n    @subgoal \"n = n' +\\<^sub>\\<nat> 1\"\n      @obtain a F' where \"F = cons(a,F')\" \"a \\<notin> F'\" \"finite(F')\" \"card(F') = n'\"\n    @endgoal\n  @end\n@qed\n\nlemma finite_nonempty_induct [var_induct]:\n  \"finite(F) \\<and> F \\<noteq> \\<emptyset> \\<Longrightarrow>\n   \\<forall>a. P({a}) \\<Longrightarrow> \\<forall>a X. finite(X) \\<longrightarrow> X \\<noteq> \\<emptyset> \\<longrightarrow> a \\<notin> X \\<longrightarrow> P(X) \\<longrightarrow> P(cons(a,X)) \\<Longrightarrow> P(F)\"\n@proof\n  @let \"n = card(F)\"\n  @var_induct \"n \\<ge>\\<^sub>\\<nat> 1\" for \"finite(F) \\<longrightarrow> n = card(F) \\<longrightarrow> P(F)\" arbitrary F @with\n    @subgoal \"n = 1\"\n      @obtain a where \"F = {a}\"\n    @endgoal\n    @subgoal \"n = n' +\\<^sub>\\<nat> 1\"\n      @obtain a F' where \"F = cons(a,F')\" \"a \\<notin> F'\" \"finite(F')\" \"card(F') = n'\"\n    @endgoal\n  @end\n@qed\n\nsection \\<open>Applications\\<close>\n\nlemma subset_finite [forward]: \"finite(A) \\<Longrightarrow> B \\<subseteq> A \\<Longrightarrow> finite(B)\"\n@proof\n  @var_induct \"finite(A)\" arbitrary B @with\n    @subgoal \"A = cons(a,A')\"\n      @case \"a \\<notin> B\" @with @have \"B \\<subseteq> A'\" @end\n      @have \"B = cons(a, B \\<inter> A')\" @have \"B \\<inter> A' \\<subseteq> A'\"\n    @endgoal\n  @end\n@qed\n\nlemma finite_minus_gen [forward]: \"finite(A) \\<Longrightarrow> finite(A \\<midarrow> B)\"\n@proof @have \"A \\<midarrow> B \\<subseteq> A\" @qed\n\nlemma image_finite [forward]: \"is_function(f) \\<Longrightarrow> finite(A) \\<Longrightarrow> finite(f `` A)\"\n@proof\n  @var_induct \"finite(A)\" @with\n    @subgoal \"A = cons(x,A')\"\n      @have \"f `` cons(x,A') \\<subseteq> cons(f ` x, f `` A')\"\n    @endgoal\n  @end\n@qed\n\nsection \\<open>Finite sets contain greatest element\\<close>\n  \nlemma has_greatest_singleton [backward]:\n  \"linorder(R) \\<Longrightarrow> a \\<in>. R \\<Longrightarrow> has_greatest(R,{a})\"\n@proof @have \"has_greatest(R,{a}) \\<and> greatest(R,{a}) = a\" @qed\n\nlemma has_greatest_cons [backward1]:\n  \"linorder(R) \\<Longrightarrow> a \\<in>. R \\<Longrightarrow> X \\<subseteq> carrier(R) \\<Longrightarrow> has_greatest(R,X) \\<Longrightarrow> has_greatest(R,cons(a,X))\"\n@proof @have \"has_greatest(R,cons(a,X)) \\<and> greatest(R,cons(a,X)) = max(R,a,greatest(R,X))\" @qed\n\nlemma finite_set_has_greatest [backward]:\n  \"linorder(R) \\<Longrightarrow> finite(X) \\<Longrightarrow> X \\<noteq> \\<emptyset> \\<Longrightarrow> X \\<subseteq> carrier(R) \\<Longrightarrow> has_greatest(R,X)\"\n@proof @var_induct \"finite(X) \\<and> X \\<noteq> \\<emptyset>\" @qed\nsetup {* add_forward_prfstep_cond @{thm finite_set_has_greatest} [with_term \"greatest(?R,?X)\"] *}\n\nsection \\<open>Other consequences of induction\\<close>\n\nlemma ex_least_nat_less [backward1]:\n  \"n \\<in> nat \\<Longrightarrow> \\<not>P(0) \\<Longrightarrow> P(n) \\<Longrightarrow> \\<exists>k<\\<^sub>\\<nat>n. (\\<forall>i\\<le>\\<^sub>\\<nat>k. \\<not>P(i)) \\<and> P(k +\\<^sub>\\<nat> 1)\"\n@proof\n  @contradiction\n  @have (@rule) \"\\<forall>x\\<in>nat. \\<forall>i\\<le>\\<^sub>\\<nat>x. \\<not>P(i)\" @with\n    @var_induct \"x \\<in> nat\" for \"\\<forall>i\\<le>\\<^sub>\\<nat>x. \\<not>P(i)\" @with\n      @subgoal \"x = x' +\\<^sub>\\<nat> 1\" @case \"i = x' +\\<^sub>\\<nat> 1\" @endgoal\n    @end\n  @end\n@qed\n\nlemma ex_nat_split [backward1]:\n  \"n \\<in> nat \\<Longrightarrow> \\<not>P(0) \\<Longrightarrow> P(n) \\<Longrightarrow> \\<exists>k<\\<^sub>\\<nat>n. \\<not>P(k) \\<and> P(k +\\<^sub>\\<nat> 1)\"\n@proof @obtain k where \"k <\\<^sub>\\<nat> n\" \"(\\<forall>i\\<le>\\<^sub>\\<nat>k. \\<not>P(i))\" \"P(k +\\<^sub>\\<nat> 1)\" @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/Finite.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382236515258, "lm_q2_score": 0.8633916099737806, "lm_q1q2_score": 0.7438448739724419}}
{"text": "(*  Title:      HOL/Hull.thy\n    Author:     Amine Chaieb, University of Cambridge\n    Author:     Jose Divas\u00f3n <jose.divasonm at unirioja.es>\n    Author:     Jes\u00fas Aransay <jesus-maria.aransay at unirioja.es>\n    Author:     Johannes H\u00f6lzl, VU Amsterdam\n*)\n\ntheory Hull\n  imports MainRLT\nbegin\n\nsubsection \\<open>A generic notion of the convex, affine, conic hull, or closed \"hull\".\\<close>\n\ndefinition hull :: \"('a set \\<Rightarrow> bool) \\<Rightarrow> 'a set \\<Rightarrow> 'a set\"  (infixl \"hull\" 75)\n  where \"S hull s = \\<Inter>{t. S t \\<and> s \\<subseteq> t}\"\n\nlemma hull_same: \"S s \\<Longrightarrow> S hull s = s\"\n  unfolding hull_def by auto\n\nlemma hull_in: \"(\\<And>T. Ball T S \\<Longrightarrow> S (\\<Inter>T)) \\<Longrightarrow> S (S hull s)\"\n  unfolding hull_def Ball_def by auto\n\nlemma hull_eq: \"(\\<And>T. Ball T S \\<Longrightarrow> S (\\<Inter>T)) \\<Longrightarrow> (S hull s) = s \\<longleftrightarrow> S s\"\n  using hull_same[of S s] hull_in[of S s] by metis\n\nlemma hull_hull [simp]: \"S hull (S hull s) = S hull s\"\n  unfolding hull_def by blast\n\nlemma hull_subset[intro]: \"s \\<subseteq> (S hull s)\"\n  unfolding hull_def by blast\n\nlemma hull_mono: \"s \\<subseteq> t \\<Longrightarrow> (S hull s) \\<subseteq> (S hull t)\"\n  unfolding hull_def by blast\n\nlemma hull_antimono: \"\\<forall>x. S x \\<longrightarrow> T x \\<Longrightarrow> (T hull s) \\<subseteq> (S hull s)\"\n  unfolding hull_def by blast\n\nlemma hull_minimal: \"s \\<subseteq> t \\<Longrightarrow> S t \\<Longrightarrow> (S hull s) \\<subseteq> t\"\n  unfolding hull_def by blast\n\nlemma subset_hull: \"S t \\<Longrightarrow> S hull s \\<subseteq> t \\<longleftrightarrow> s \\<subseteq> t\"\n  unfolding hull_def by blast\n\nlemma hull_UNIV [simp]: \"S hull UNIV = UNIV\"\n  unfolding hull_def by auto\n\nlemma hull_unique: \"s \\<subseteq> t \\<Longrightarrow> S t \\<Longrightarrow> (\\<And>t'. s \\<subseteq> t' \\<Longrightarrow> S t' \\<Longrightarrow> t \\<subseteq> t') \\<Longrightarrow> (S hull s = t)\"\n  unfolding hull_def by auto\n\nlemma hull_induct: \"\\<lbrakk>a \\<in> Q hull S; \\<And>x. x\\<in> S \\<Longrightarrow> P x; Q {x. P x}\\<rbrakk> \\<Longrightarrow> P a\"\n  using hull_minimal[of S \"{x. P x}\" Q]\n  by (auto simp add: subset_eq)\n\nlemma hull_inc: \"x \\<in> S \\<Longrightarrow> x \\<in> P hull S\"\n  by (metis hull_subset subset_eq)\n\nlemma hull_Un_subset: \"(S hull s) \\<union> (S hull t) \\<subseteq> (S hull (s \\<union> t))\"\n  unfolding Un_subset_iff by (metis hull_mono Un_upper1 Un_upper2)\n\nlemma hull_Un:\n  assumes T: \"\\<And>T. Ball T S \\<Longrightarrow> S (\\<Inter>T)\"\n  shows \"S hull (s \\<union> t) = S hull (S hull s \\<union> S hull t)\"\n  apply (rule equalityI)\n  apply (meson hull_mono hull_subset sup.mono)\n  by (metis hull_Un_subset hull_hull hull_mono)\n\nlemma hull_Un_left: \"P hull (S \\<union> T) = P hull (P hull S \\<union> T)\"\n  apply (rule equalityI)\n   apply (simp add: Un_commute hull_mono hull_subset sup.coboundedI2)\n  by (metis Un_subset_iff hull_hull hull_mono hull_subset)\n\nlemma hull_Un_right: \"P hull (S \\<union> T) = P hull (S \\<union> P hull T)\"\n  by (metis hull_Un_left sup.commute)\n\nlemma hull_insert:\n   \"P hull (insert a S) = P hull (insert a (P hull S))\"\n  by (metis hull_Un_right insert_is_Un)\n\nlemma hull_redundant_eq: \"a \\<in> (S hull s) \\<longleftrightarrow> S hull (insert a s) = S hull s\"\n  unfolding hull_def by blast\n\nlemma hull_redundant: \"a \\<in> (S hull s) \\<Longrightarrow> S hull (insert a s) = S hull s\"\n  by (metis hull_redundant_eq)\n\nend", "meta": {"author": "dtraytel", "repo": "HOLRLT", "sha": "e9029da59bb3af0c835604a65308498f9696a364", "save_path": "github-repos/isabelle/dtraytel-HOLRLT", "path": "github-repos/isabelle/dtraytel-HOLRLT/HOLRLT-e9029da59bb3af0c835604a65308498f9696a364/HOLRLT/Hull.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391624034103, "lm_q2_score": 0.8615382076534743, "lm_q1q2_score": 0.7438448722733635}}
{"text": "header {* \\isaheader{Formalization of Bit Vectors} *}\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 {* Some basic properties *}\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 = `xs \\<preceq>\\<^sub>b ys = \n    ((\\<forall>i < length xs. xs ! i \\<longrightarrow> ys ! i) \\<and> length xs = length ys)`\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 `x \\<longrightarrow> y` 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 `\\<forall>i < length xs. xs ! i \\<longrightarrow> ys ! i` \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 `(x#xs) ! 0 \\<longrightarrow> (y#ys) ! 0` `length xs = length ys`\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 `\\<forall>i < length (x#xs). (x#xs) ! i \\<longrightarrow> (y#ys) ! i`\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 `length (x#xs) = length (y#ys)` have \"xs \\<preceq>\\<^sub>b ys\" by simp\n    from `\\<forall>i < length (x#xs). (x#xs) ! i \\<longrightarrow> (y#ys) ! i`\n    have \"x \\<longrightarrow> y\" by(erule_tac x=\"0\" in allE) simp\n    with `xs \\<preceq>\\<^sub>b ys` show \"x#xs \\<preceq>\\<^sub>b y#ys\" by simp\n  qed\nqed simp_all\n\n\nsubsection {* $\\preceq_b$ is an order on bit vectors with minimal and \n  maximal element *}\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 = `\\<And>zs. \\<lbrakk>xs \\<preceq>\\<^sub>b ys; ys \\<preceq>\\<^sub>b zs\\<rbrakk> \\<Longrightarrow> xs \\<preceq>\\<^sub>b zs`\n  from `(x#xs) \\<preceq>\\<^sub>b (y#ys)` have \"xs \\<preceq>\\<^sub>b ys\" and \"x \\<longrightarrow> y\" by simp_all\n  from `(y#ys) \\<preceq>\\<^sub>b zs` obtain z zs' where \"zs = z#zs'\" by(cases zs) auto\n  with `(y#ys) \\<preceq>\\<^sub>b zs` have \"ys \\<preceq>\\<^sub>b zs'\" and \"y \\<longrightarrow> z\" by simp_all\n  from IH[OF `xs \\<preceq>\\<^sub>b ys` `ys \\<preceq>\\<^sub>b zs'`] have \"xs \\<preceq>\\<^sub>b zs'\" .\n  with `x \\<longrightarrow> y` `y \\<longrightarrow> z` `zs = z#zs'` 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": "Josh-Tilles", "repo": "AFP", "sha": "f4bf1d502bde2a3469d482b62c531f1c3af3e881", "save_path": "github-repos/isabelle/Josh-Tilles-AFP", "path": "github-repos/isabelle/Josh-Tilles-AFP/AFP-f4bf1d502bde2a3469d482b62c531f1c3af3e881/thys/Slicing/Dynamic/BitVector.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8615382094310357, "lm_q2_score": 0.8633916205190225, "lm_q1q2_score": 0.7438448707797188}}
{"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> _\" [900] 900)\n\nclass Sup =\n  fixes Sup :: \"'a set \\<Rightarrow> 'a\"  (\"\\<Squnion> _\" [900] 900)\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: order.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: order.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 order.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 order.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!: order.antisym Inf_lower)\n\nlemma Sup_UNIV [simp]: \"\\<Squnion>UNIV = \\<top>\"\n  by (auto intro!: order.antisym Sup_upper)\n\nlemma Inf_eq_Sup: \"\\<Sqinter>A = \\<Squnion>{b. \\<forall>a \\<in> A. b \\<le> a}\"\n  by (auto intro: order.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: order.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 order.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 order.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 order.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!: order.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 order.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!: order.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 order.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 order.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_constant: \"(\\<Sqinter>y\\<in>A. c) = (if A = {} then \\<top> else c)\"\n  by (auto intro: order.antisym INF_lower INF_greatest)\n\nlemma SUP_constant: \"(\\<Squnion>y\\<in>A. c) = (if A = {} then \\<bottom> else c)\"\n  by (auto intro: order.antisym SUP_upper SUP_least)\n\nlemma INF_const [simp]: \"A \\<noteq> {} \\<Longrightarrow> (\\<Sqinter>i\\<in>A. f) = f\"\n  by (simp add: INF_constant)\n\nlemma SUP_const [simp]: \"A \\<noteq> {} \\<Longrightarrow> (\\<Squnion>i\\<in>A. f) = f\"\n  by (simp add: SUP_constant)\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 order.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 order.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 order.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 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 order.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 order.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 order.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 order.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 order.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: order.antisym simp add: min_def fun_eq_iff)\n\nlemma complete_linorder_sup_max: \"sup = max\"\n  by (auto intro: order.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  unfolding disjnt_def\n  by safe (use inj_on_eq_iff in \\<open>fastforce+\\<close>)\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": "seL4", "repo": "isabelle", "sha": "e1ab32a3bb41728cd19541063283e37919978a4c", "save_path": "github-repos/isabelle/seL4-isabelle", "path": "github-repos/isabelle/seL4-isabelle/isabelle-e1ab32a3bb41728cd19541063283e37919978a4c/src/HOL/Complete_Lattices.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382129861582, "lm_q2_score": 0.8633916152464016, "lm_q1q2_score": 0.7438448693066175}}
{"text": "(*\n  File:     Nearest_Neighbors.thy\n  Author:   Martin Rau, TU M\u00fcnchen\n*)\n\nsection \\<open>Nearest Neighbor Search on the \\<open>k\\<close>-d Tree\\<close>\n\ntheory Nearest_Neighbors\nimports\n  KD_Tree\n  \"../../../../SeLFiE\"\nbegin\n\ntext \\<open>\n  Verifying nearest neighbor search on the k-d tree. Given a \\<open>k\\<close>-d tree and a point \\<open>p\\<close>,\n  which might not be in the tree, find the points \\<open>ps\\<close> that are closest to \\<open>p\\<close> using the\n  Euclidean metric.\n\\<close>\n\nsubsection \\<open>Auxiliary Lemmas about \\<open>sorted_wrt\\<close>\\<close>\n\nlemma\n  assumes \"sorted_wrt f xs\"\n  shows sorted_wrt_take: \"sorted_wrt f (take n xs)\"\n  and sorted_wrt_drop: \"sorted_wrt f (drop n xs)\"\nproof -\n  have \"sorted_wrt f (take n xs @ drop n xs)\"\n    using assms by simp\n  thus \"sorted_wrt f (take n xs)\" \"sorted_wrt f (drop n xs)\"\n    using sorted_wrt_append by blast+\nqed\n\ndefinition sorted_wrt_dist :: \"('k::finite) point \\<Rightarrow> 'k point list \\<Rightarrow> bool\" where\n  \"sorted_wrt_dist p \\<equiv> sorted_wrt (\\<lambda>p\\<^sub>0 p\\<^sub>1. dist p\\<^sub>0 p \\<le> dist p\\<^sub>1 p)\"\n\nlemma sorted_wrt_dist_insort_key:\n  \"sorted_wrt_dist p ps \\<Longrightarrow> sorted_wrt_dist p (insort_key (\\<lambda>q. dist q p) q ps)\"\n  \n  assert_SeLFiE_true  generalize_arguments_used_in_recursion [on[\"ps\"], arb[],rule[]]\n  assert_SeLFiE_true  generalize_arguments_used_in_recursion [on[\"ps\"], arb[\"q\"],rule[]](*a little unfortunate, but okay*)\n  assert_SeLFiE_true  generalize_arguments_used_in_recursion [on[\"ps\"], arb[\"p\"],rule[]](*a little unfortunate, but okay*)\n  assert_SeLFiE_false for_all_arbs_there_should_be_a_change [on[\"ps\"], arb[\"p\"],rule[]]      (*very good*)\n  assert_SeLFiE_false for_all_arbs_there_should_be_a_change [on[\"ps\"], arb[\"p\", \"q\"],rule[]] (*very good*)\n  assert_SeLFiE_false for_all_arbs_there_should_be_a_change [on[\"ps\"], arb[\"q\"],rule[]]\n  assert_SeLFiE_true  for_all_arbs_there_should_be_a_change [on[\"ps\"], arb[],rule[]] (*good*)\n  all_induction_heuristic      [on[\"ps\"], arb[],rule[]]\n  all_generalization_heuristic [on[\"ps\"], arb[],rule[]]\n  by (induction ps) (auto simp: sorted_wrt_dist_def set_insort_key)\n\nlemma sorted_wrt_dist_take_drop:\n  assumes \"sorted_wrt_dist p ps\"\n  shows \"\\<forall>p\\<^sub>0 \\<in> set (take n ps). \\<forall>p\\<^sub>1 \\<in> set (drop n ps). dist p\\<^sub>0 p \\<le> dist p\\<^sub>1 p\"\n  using assms sorted_wrt_append[of _ \"take n ps\" \"drop n ps\"] by (simp add: sorted_wrt_dist_def)\n\nlemma sorted_wrt_dist_last_take_mono:\n  assumes \"sorted_wrt_dist p ps\" \"n \\<le> length ps\" \"0 < n\"\n  shows \"dist (last (take n ps)) p \\<le> dist (last ps) p\"\n  using assms unfolding sorted_wrt_dist_def \n  \n  assert_SeLFiE_true  generalize_arguments_used_in_recursion [on[\"ps\"], arb[\"n\"],rule[]]\n  assert_SeLFiE_false  generalize_arguments_used_in_recursion [on[\"ps\"], arb[],rule[]]\n  all_induction_heuristic      [on[\"ps\"], arb[\"n\"],rule[]]\n  all_generalization_heuristic [on[\"ps\"], arb[\"n\"],rule[]]\n  by (induction ps arbitrary: n) (auto simp add: take_Cons')\n\nlemma sorted_wrt_dist_last_insort_key_eq:\n  assumes \"sorted_wrt_dist p ps\" \"insort_key (\\<lambda>q. dist q p) q ps \\<noteq> ps @ [q]\"\n  shows \"last (insort_key (\\<lambda>q. dist q p) q ps) = last ps\"\n  using assms unfolding sorted_wrt_dist_def by (induction ps) (auto)\n\nlemma sorted_wrt_dist_last:\n  assumes \"sorted_wrt_dist p ps\"\n  shows \"\\<forall>q \\<in> set ps. dist q p \\<le> dist (last ps) p\"\nproof (cases \"ps = []\")\n  case True\n  thus ?thesis by simp\nnext\n  case False\n  then obtain ps' p' where [simp]:\"ps = ps' @ [p']\"\n    using rev_exhaust by blast\n  hence \"sorted_wrt_dist p (ps' @ [p'])\"\n    using assms by blast\n  thus ?thesis\n    unfolding sorted_wrt_dist_def using sorted_wrt_append[of _ ps' \"[p']\"] by simp\nqed\n\n\nsubsection \\<open>Neighbors Sorted wrt. Distance\\<close>\n\ndefinition upd_nbors :: \"nat \\<Rightarrow> ('k::finite) point \\<Rightarrow> 'k point \\<Rightarrow> 'k point list \\<Rightarrow> 'k point list\" where\n  \"upd_nbors n p q ps = take n (insort_key (\\<lambda>q. dist q p) q ps)\"\n\nlemma sorted_wrt_dist_nbors:\n  assumes \"sorted_wrt_dist p ps\"\n  shows \"sorted_wrt_dist p (upd_nbors n p q ps)\"\nproof -\n  have \"sorted_wrt_dist p (insort_key (\\<lambda>q. dist q p) q ps)\"\n    using assms sorted_wrt_dist_insort_key by blast\n  thus ?thesis\n    by (simp add: sorted_wrt_dist_def sorted_wrt_take upd_nbors_def)\nqed\n\nlemma sorted_wrt_dist_nbors_diff:\n  assumes \"sorted_wrt_dist p ps\"\n  shows \"\\<forall>r \\<in> set ps \\<union> {q} - set (upd_nbors n p q ps). \\<forall>s \\<in> set (upd_nbors n p q ps). dist s p \\<le> dist r p\"\nproof -\n  let ?ps' = \"insort_key (\\<lambda>q. dist q p) q ps\"\n  have \"set ps \\<union> { q } = set ?ps'\"\n    by (simp add: set_insort_key)\n  moreover have \"set ?ps' = set (take n ?ps') \\<union> set (drop n ?ps')\"\n    using append_take_drop_id set_append by metis\n  ultimately have \"set ps \\<union> { q } - set (take n ?ps') \\<subseteq> set (drop n ?ps')\"\n    by blast\n  moreover have \"sorted_wrt_dist p ?ps'\"\n    using assms sorted_wrt_dist_insort_key by blast\n  ultimately show ?thesis\n    unfolding upd_nbors_def using sorted_wrt_dist_take_drop by blast\nqed\n\nlemma sorted_wrt_dist_last_upd_nbors_mono:\n  assumes \"sorted_wrt_dist p ps\" \"n \\<le> length ps\" \"0 < n\"\n  shows \"dist (last (upd_nbors n p q ps)) p \\<le> dist (last ps) p\"\nproof (cases \"insort_key (\\<lambda>q. dist q p) q ps = ps @ [q]\")\n  case True\n  thus ?thesis\n    unfolding upd_nbors_def using assms sorted_wrt_dist_last_take_mono by auto\nnext\n  case False\n  hence \"last (insort_key (\\<lambda>q. dist q p) q ps) = last ps\"\n    using sorted_wrt_dist_last_insort_key_eq assms by blast\n  moreover have \"dist (last (upd_nbors  n p q ps)) p \\<le> dist (last (insort_key (\\<lambda>q. dist q p) q ps)) p\"\n    unfolding upd_nbors_def using assms sorted_wrt_dist_last_take_mono[of p \"insort_key (\\<lambda>q. dist q p) q ps\"]\n    by (simp add: sorted_wrt_dist_insort_key)\n  ultimately show ?thesis\n    by simp\nqed\n\n\nsubsection \\<open>The Recursive Nearest Neighbor Algorithm\\<close>\n\nfun nearest_nbors :: \"nat \\<Rightarrow> ('k::finite) point list \\<Rightarrow> 'k point \\<Rightarrow> 'k kdt \\<Rightarrow> 'k point list\" where\n  \"nearest_nbors n ps p (Leaf q) = upd_nbors n p q ps\"\n| \"nearest_nbors n ps p (Node k v l r) = (\n    if p$k \\<le> v then\n      let candidates = nearest_nbors n ps p l in\n      if length candidates = n \\<and> dist p (last candidates) \\<le> dist v (p$k) then\n        candidates\n      else\n        nearest_nbors n candidates p r\n    else\n      let candidates = nearest_nbors n ps p r in\n      if length candidates = n \\<and> dist p (last candidates) \\<le> dist v (p$k) then\n        candidates\n      else\n        nearest_nbors n candidates p l\n  )\"\n\n\nsubsection \\<open>Auxiliary Lemmas\\<close>\n\nlemma cutoff_r:\n  assumes \"invar (Node k v l r)\"\n  assumes \"p$k \\<le> v\" \"dist p c \\<le> dist (p$k) v\"\n  shows \"\\<forall>q \\<in> set_kdt r. dist p c \\<le> dist p q\"\nproof standard\n  fix q\n  assume *: \"q \\<in> set_kdt r\"\n  have \"dist p c \\<le> dist (p$k) v\"\n    using assms(3) by blast\n  also have \"... \\<le> dist (p$k) v + dist v (q$k)\"\n    by simp\n  also have \"... = dist (p$k) (q$k)\"\n    using * assms(1,2) dist_real_def by auto\n  also have \"... \\<le> dist p q\"\n    using dist_vec_nth_le by blast\n  finally show \"dist p c \\<le> dist p q\" .\nqed\n\nlemma cutoff_l:\n  assumes \"invar (Node k v l r)\"\n  assumes \"v \\<le> p$k\" \"dist p c \\<le> dist v (p$k)\"\n  shows \"\\<forall>q \\<in> set_kdt l. dist p c \\<le> dist p q\"\nproof standard\n  fix q\n  assume *: \"q \\<in> set_kdt l\"\n  have \"dist p c \\<le> dist v (p$k)\"\n    using assms(3) by blast\n  also have \"... \\<le> dist v (p$k) + dist (q$k) v\"\n    by simp\n  also have \"... = dist (p$k) (q$k)\"\n    using * assms(1,2) dist_real_def by auto\n  also have \"... \\<le> dist p q\"\n    using dist_vec_nth_le by blast\n  finally show \"dist p c \\<le> dist p q\" .\nqed\n\n\nsubsection \\<open>The Main Theorems\\<close>\n\nlemma set_nns:\n  \"set (nearest_nbors n ps p kdt) \\<subseteq> set_kdt kdt \\<union> set ps\"\n  assert_SeLFiE_true  generalize_arguments_used_in_recursion_deep [on[\"kdt\"], arb[\"ps\"], rule[]](*okay*)\n  assert_SeLFiE_true  generalize_arguments_used_in_recursion_deep [on[\"kdt\"], arb[    ], rule[]](*not great, but okay*)\n  assert_SeLFiE_true  generalize_arguments_used_in_recursion [on[\"kdt\"], arb[\"ps\"],rule[]](*very good.It takes 2.385s elapsed time, 13.012s cpu time, 0.196s GC time*)\n  assert_SeLFiE_false generalize_arguments_used_in_recursion [on[\"kdt\"], arb[],rule[]]    (*very good*)\n  assert_SeLFiE_true  generalize_arguments_used_in_recursion [on[\"kdt\"], arb[\"p\", \"ps\"],rule[]](*a little unfortunate*)\n  assert_SeLFiE_true  for_all_arbs_there_should_be_a_change [on[\"kdt\"], arb[\"ps\"],rule[]]\n  assert_SeLFiE_true  for_all_arbs_there_should_be_a_change [on[\"kdt\"], arb[],rule[]]     (*unfortunate because of the universal quantifier over generalized terms*)\n  assert_SeLFiE_false for_all_arbs_there_should_be_a_change [on[\"kdt\"], arb[\"p\"],rule[]]\n  assert_SeLFiE_false for_all_arbs_there_should_be_a_change [on[\"kdt\"], arb[\"p\", \"ps\"],rule[]](*very good*)\n  assert_SeLFiE_false for_all_arbs_there_should_be_a_change [on[\"kdt\"], arb[\"n\"],rule[]]\n  assert_SeLFiE_false for_all_arbs_there_should_be_a_change [on[\"kdt\"], arb[\"n\",\"p\"],rule[]]\n  apply (induction kdt arbitrary: ps)\n  apply (auto simp: Let_def upd_nbors_def set_insort_key)\n  using in_set_takeD set_insort_key by fastforce\n\nlemma length_nns:\n  \"length (nearest_nbors n ps p kdt) = min n (size_kdt kdt + length ps)\"\n  assert_SeLFiE_true  generalize_arguments_used_in_recursion [on[\"kdt\"], arb[\"ps\"],rule[]](*very good. It takes 1.706s elapsed time, 4.520s cpu time, 0.064s GC time*)\n  assert_SeLFiE_false generalize_arguments_used_in_recursion [on[\"kdt\"], arb[],rule[]]    (*very good*)\n  assert_SeLFiE_true  generalize_arguments_used_in_recursion [on[\"kdt\"], arb[\"p\", \"ps\"],rule[]](*a little unfortunate*)(*1.793s elapsed time, 5.413s cpu time, 0.180s GC time*)\n  assert_SeLFiE_true  for_all_arbs_there_should_be_a_change [on[\"kdt\"], arb[\"ps\"],rule[]]\n  assert_SeLFiE_true  for_all_arbs_there_should_be_a_change [on[\"kdt\"], arb[],rule[]]     (*unfortunate because of the universal quantifier over generalized terms*)\n  assert_SeLFiE_false for_all_arbs_there_should_be_a_change [on[\"kdt\"], arb[\"p\"],rule[]]\n  assert_SeLFiE_false for_all_arbs_there_should_be_a_change [on[\"kdt\"], arb[\"p\", \"ps\"],rule[]](*very good*)\n  assert_SeLFiE_false for_all_arbs_there_should_be_a_change [on[\"kdt\"], arb[\"n\"],rule[]]\n  assert_SeLFiE_false for_all_arbs_there_should_be_a_change [on[\"kdt\"], arb[\"n\",\"p\"],rule[]]\n  by (induction kdt arbitrary: ps) (auto simp: Let_def upd_nbors_def)\n\nlemma length_nns_gt_0:\n  \"0 < n \\<Longrightarrow> 0 < length (nearest_nbors n ps p kdt)\"\n  all_induction_heuristic      [on[\"n\"], arb[\"ps\"],rule[]]\n  all_generalization_heuristic [on[\"n\"], arb[\"ps\"],rule[]]\n  all_induction_heuristic      [on[\"kdt\"], arb[\"ps\"],rule[]]\n  all_generalization_heuristic [on[\"kdt\"], arb[\"ps\"],rule[]]\n  all_generalization_heuristic [on[\"kdt\"], arb[\"ps\",\"p\",\"n\"],rule[]]\n  assert_SeLFiE_false for_all_arbs_there_should_be_a_change [on[\"kdt\"], arb[\"p\"],rule[]]\n  by (induction kdt arbitrary: ps) (auto simp: Let_def upd_nbors_def)\n\nlemma length_nns_n:\n  assumes \"(set_kdt kdt \\<union> set ps) - set (nearest_nbors n ps p kdt) \\<noteq> {}\"\n  shows \"length (nearest_nbors n ps p kdt) = n\"\n  using assms \n  all_induction_heuristic      [on[\"kdt\"], arb[\"ps\",\"p\",\"n\"],rule[]]\n  all_generalization_heuristic [on[\"kdt\"], arb[\"ps\",\"p\",\"n\"],rule[]]\n  assert_SeLFiE_false for_all_arbs_there_should_be_a_change [on[\"kdt\"], arb[\"p\"],rule[]](*!*)\nproof (induction kdt arbitrary: ps)\n  case (Node k v l r)\n  let ?nnsl = \"nearest_nbors n ps p l\"\n  let ?nnsr = \"nearest_nbors n ps p r\"\n  consider (A) \"p$k \\<le> v \\<and> length ?nnsl = n \\<and> dist p (last ?nnsl) \\<le> dist v (p$k)\"\n         | (B) \"p$k \\<le> v \\<and> \\<not>(length ?nnsl = n \\<and> dist p (last ?nnsl) \\<le> dist v (p$k))\"\n         | (C) \"v < p$k \\<and> length ?nnsr = n \\<and> dist p (last ?nnsr) \\<le> dist v (p$k)\"\n         | (D) \"v < p$k \\<and> \\<not>(length ?nnsr = n \\<and> dist p (last ?nnsr) \\<le> dist v (p$k))\"\n    by argo\n  thus ?case\n  proof cases\n    case B\n    let ?nns = \"nearest_nbors n ?nnsl p r\"\n    have \"length ?nnsl \\<noteq> n \\<longrightarrow> (set_kdt l \\<union> set ps - set (nearest_nbors n ps p l) = {})\"\n      using Node.IH(1) by blast\n    hence \"length ?nnsl \\<noteq> n \\<longrightarrow> (set_kdt r \\<union> set ?nnsl - set ?nns \\<noteq> {})\"\n      using B Node.prems by auto\n    moreover have \"length ?nnsl = n \\<longrightarrow> ?thesis\"\n      using B by (auto simp: length_nns)\n    ultimately show ?thesis\n      using B Node.IH(2) by force\n  next\n    case D\n    let ?nns = \"nearest_nbors n ?nnsr p l\"\n    have \"length ?nnsr \\<noteq> n \\<longrightarrow> (set_kdt r \\<union> set ps - set (nearest_nbors n ps p r) = {})\"\n      using Node.IH(2) by blast\n    hence \"length ?nnsr \\<noteq> n \\<longrightarrow> (set_kdt l \\<union> set ?nnsr - set ?nns \\<noteq> {})\"\n      using D Node.prems by auto\n    moreover have \"length ?nnsr = n \\<longrightarrow> ?thesis\"\n      using D by (auto simp: length_nns)\n    ultimately show ?thesis\n      using D Node.IH(1) by force\n  qed auto\nqed (auto simp: upd_nbors_def min_def set_insort_key)\n\nlemma sorted_nns:\n  \"sorted_wrt_dist p ps \\<Longrightarrow> sorted_wrt_dist p (nearest_nbors n ps p kdt)\"\n  using sorted_wrt_dist_nbors by (induction kdt arbitrary: ps) (auto simp: Let_def)\n\nlemma distinct_nns:\n  assumes \"invar kdt\" \"distinct ps\" \"set ps \\<inter> set_kdt kdt = {}\"\n  shows \"distinct (nearest_nbors n ps p kdt)\"\n  using assms semantic_induct\nproof (induction kdt arbitrary: ps)\n  case (Node k v l r)\n  let ?nnsl = \"nearest_nbors n ps p l\"\n  let ?nnsr = \"nearest_nbors n ps p r\"\n  have \"set ps \\<inter> set_kdt l = {}\" \"set ps \\<inter> set_kdt r = {}\"\n    using Node.prems(3) by auto\n  hence DCLR: \"distinct ?nnsl\" \"distinct ?nnsr\"\n    using Node invar_l invar_r by blast+\n  have \"set ?nnsl \\<inter> set_kdt r = {}\" \"set ?nnsr \\<inter> set_kdt l = {}\"\n    using Node.prems(1,3) set_nns by fastforce+\n  hence \"distinct (nearest_nbors n ?nnsl p r)\" \"distinct (nearest_nbors n ?nnsr p l)\"\n    using Node.IH(1,2) Node.prems(1,2) DCLR invar_l invar_r by blast+\n  thus ?case\n    using DCLR by (auto simp add: Let_def)\nqed (auto simp: upd_nbors_def distinct_insort)\n\n\n\ntheorem dist_nns:\n  assumes \"invar kdt\" \"sorted_wrt_dist p ps\" \"set ps \\<inter> set_kdt kdt = {}\" \"distinct ps\" \"0 < n\"\n  shows \"\\<forall>q \\<in> set_kdt kdt \\<union> set ps - set (nearest_nbors n ps p kdt). dist (last (nearest_nbors n ps p kdt)) p \\<le> dist q p\"\n  using assms \nproof (induction kdt arbitrary: ps)\n  case (Node k v l r)\n\n  let ?nnsl = \"nearest_nbors n ps p l\"\n  let ?nnsr = \"nearest_nbors n ps p r\"\n\n  have IHL: \"\\<forall>q \\<in> set_kdt l \\<union> set ps - set ?nnsl. dist (last ?nnsl) p \\<le> dist q p\"\n    using Node.IH(1) Node.prems invar_l invar_set by auto\n  have IHR: \"\\<forall>q \\<in> set_kdt r \\<union> set ps - set ?nnsr. dist (last ?nnsr) p \\<le> dist q p\"\n    using Node.IH(2) Node.prems invar_r invar_set by auto\n\n  have SORTED_L: \"sorted_wrt_dist p ?nnsl\"\n    using sorted_nns Node.prems(2) by blast\n  have SORTED_R: \"sorted_wrt_dist p ?nnsr\"\n    using sorted_nns Node.prems(2) by blast\n\n  have DISTINCT_L: \"distinct ?nnsl\"\n    using Node.prems distinct_nns invar_set invar_l by fastforce\n  have DISTINCT_R: \"distinct ?nnsr\"\n    using Node.prems distinct_nns invar_set invar_r\n    by (metis inf_bot_right inf_sup_absorb inf_sup_aci(3) sup.commute)\n\n  consider (A) \"p$k \\<le> v \\<and> length ?nnsl = n \\<and> dist p (last ?nnsl) \\<le> dist v (p$k)\"\n         | (B) \"p$k \\<le> v \\<and> \\<not>(length ?nnsl = n \\<and> dist p (last ?nnsl) \\<le> dist v (p$k))\"\n         | (C) \"v < p$k \\<and> length ?nnsr = n \\<and> dist p (last ?nnsr) \\<le> dist v (p$k)\"\n         | (D) \"v < p$k \\<and> \\<not>(length ?nnsr = n \\<and> dist p (last ?nnsr) \\<le> dist v (p$k))\"\n    by argo\n  thus ?case\n  proof cases\n    case A\n    hence \"\\<forall>q \\<in> set_kdt r. dist (last ?nnsl) p \\<le> dist q p\"\n      using Node.prems(1,2) cutoff_r by (metis dist_commute)\n    thus ?thesis\n      using IHL A by auto\n  next\n    case B\n\n    let ?nns = \"nearest_nbors n ?nnsl p r\"\n\n    have \"set ?nnsl \\<subseteq> set_kdt l \\<union> set ps\" \"set ps \\<inter> set_kdt r = {}\"\n      using set_nns Node.prems(1,3) by (simp add: set_nns disjoint_iff_not_equal)+\n    hence \"set ?nnsl \\<inter> set_kdt r = {}\"\n      using Node.prems(1) by fastforce\n    hence IHLR: \"\\<forall>q \\<in> set_kdt r \\<union> set ?nnsl - set ?nns. dist (last ?nns) p \\<le> dist q p\"\n      using Node.IH(2)[OF _ SORTED_L _ DISTINCT_L Node.prems(5)] Node.prems(1) invar_r by blast\n\n    have \"\\<forall>q \\<in> set ps - set ?nnsl. dist (last ?nns) p \\<le> dist q p\"\n    proof standard\n      fix q\n      assume *: \"q \\<in> set ps - set ?nnsl\"\n\n      hence \"length ?nnsl = n\"\n        using length_nns_n by blast\n      hence LAST: \"dist (last ?nns) p \\<le> dist (last ?nnsl) p\"\n        using last_nns_mono SORTED_L invar_r Node.prems(1,2,5) by (metis order_refl)\n      have \"dist (last ?nnsl) p \\<le> dist q p\"\n        using IHL * by blast\n      thus \"dist (last ?nns) p \\<le> dist q p\"\n        using LAST by argo\n    qed\n    hence R: \"\\<forall>q \\<in> set_kdt r \\<union> set ps - set ?nns. dist (last ?nns) p \\<le> dist q p\"\n      using IHLR by auto\n\n    have \"\\<forall>q \\<in> set_kdt l - set ?nnsl. dist (last ?nns) p \\<le> dist q p\"\n    proof standard\n      fix q\n      assume *: \"q \\<in> set_kdt l - set ?nnsl\"\n\n      hence \"length ?nnsl = n\"\n        using length_nns_n by blast\n      hence LAST: \"dist (last ?nns) p \\<le> dist (last ?nnsl) p\"\n        using last_nns_mono SORTED_L invar_r Node.prems(1,2,5) by (metis order_refl)\n      have \"dist (last ?nnsl) p \\<le> dist q p\"\n        using IHL * by blast\n      thus \"dist (last ?nns) p \\<le> dist q p\"\n        using LAST by argo\n    qed\n    hence L: \"\\<forall>q \\<in> set_kdt l - set ?nns. dist (last ?nns) p \\<le> dist q p\"\n      using IHLR by blast\n\n    show ?thesis\n      using B R L by auto\n  next\n    case C\n    hence \"\\<forall>q \\<in> set_kdt l. dist (last ?nnsr) p \\<le> dist q p\"\n      using Node.prems(1,2) cutoff_l by (metis dist_commute less_imp_le)\n    thus ?thesis\n      using IHR C by auto\n  next\n    case D\n\n    let ?nns = \"nearest_nbors n ?nnsr p l\"\n\n    have \"set ?nnsr \\<subseteq> set_kdt r \\<union> set ps\" \"set ps \\<inter> set_kdt l = {}\"\n      using set_nns Node.prems(1,3) by (simp add: set_nns disjoint_iff_not_equal)+\n    hence \"set ?nnsr \\<inter> set_kdt l = {}\"\n      using Node.prems(1) by fastforce\n    hence IHRL: \"\\<forall>q \\<in> set_kdt l \\<union> set ?nnsr - set ?nns. dist (last ?nns) p \\<le> dist q p\"\n      using Node.IH(1)[OF _ SORTED_R _ DISTINCT_R Node.prems(5)] Node.prems(1) invar_l by blast\n\n    have \"\\<forall>q \\<in> set ps - set ?nnsr. dist (last ?nns) p \\<le> dist q p\"\n    proof standard\n      fix q\n      assume *: \"q \\<in> set ps - set ?nnsr\"\n\n      hence \"length ?nnsr = n\"\n        using length_nns_n by blast\n      hence LAST: \"dist (last ?nns) p \\<le> dist (last ?nnsr) p\"\n        using last_nns_mono SORTED_R invar_l Node.prems(1,2,5) by (metis order_refl)\n      have \"dist (last ?nnsr) p \\<le> dist q p\"\n        using IHR * by blast\n      thus \"dist (last ?nns) p \\<le> dist q p\"\n        using LAST by argo\n    qed\n    hence R: \"\\<forall>q \\<in> set_kdt l \\<union> set ps - set ?nns. dist (last ?nns) p \\<le> dist q p\"\n      using IHRL by auto\n\n    have \"\\<forall>q \\<in> set_kdt r - set ?nnsr. dist (last ?nns) p \\<le> dist q p\"\n    proof standard\n      fix q\n      assume *: \"q \\<in> set_kdt r - set ?nnsr\"\n\n      hence \"length ?nnsr = n\"\n        using length_nns_n by blast\n      hence LAST: \"dist (last ?nns) p \\<le> dist (last ?nnsr) p\"\n        using last_nns_mono SORTED_R invar_l Node.prems(1,2,5) by (metis order_refl)\n      have \"dist (last ?nnsr) p \\<le> dist q p\"\n        using IHR * by blast\n      thus \"dist (last ?nns) p \\<le> dist q p\"\n        using LAST by argo\n    qed\n    hence L: \"\\<forall>q \\<in> set_kdt r - set ?nns. dist (last ?nns) p \\<le> dist q p\"\n      using IHRL by blast\n\n    show ?thesis\n      using D R L by auto\n  qed\nqed (auto simp: sorted_wrt_dist_nbors_diff upd_nbors_def)\n\n\nsubsection \\<open>Nearest Neighbors Definition and Theorems\\<close>\n\ndefinition nearest_neighbors :: \"nat \\<Rightarrow> ('k::finite) point \\<Rightarrow> 'k kdt \\<Rightarrow> 'k point list\" where\n  \"nearest_neighbors n p kdt = nearest_nbors n [] p kdt\"\n\ntheorem length_nearest_neighbors:\n  \"length (nearest_neighbors n p kdt) = min n (size_kdt kdt)\"\n  by (simp add: length_nns nearest_neighbors_def)\n\ntheorem sorted_wrt_dist_nearest_neighbors:\n  \"sorted_wrt_dist p (nearest_neighbors n p kdt)\"\n  using sorted_nns unfolding nearest_neighbors_def sorted_wrt_dist_def by force\n\n\n\ntheorem distinct_nearest_neighbors:\n  assumes \"invar kdt\"\n  shows \"distinct (nearest_neighbors n p kdt)\"\n  using assms by (simp add: distinct_nns nearest_neighbors_def)\n\ntheorem dist_nearest_neighbors:\n  assumes \"invar kdt\" \"nns = nearest_neighbors n p kdt\"\n  shows \"\\<forall>q \\<in> (set_kdt kdt - set nns). \\<forall>r \\<in> set nns. dist r p \\<le> dist q p\"\nproof (cases \"0 < n\")\n  case True\n  have \"\\<forall>q \\<in> set_kdt kdt - set nns. dist (last nns) p \\<le> dist q p\"\n    using nearest_neighbors_def dist_nns[OF assms(1), of p \"[]\", OF _ _ _ True] assms(2)\n    by (simp add: nearest_neighbors_def sorted_wrt_dist_def)\n  hence \"\\<forall>q \\<in> set_kdt kdt - set nns. \\<forall>n \\<in> set nns. dist n p \\<le> dist q p\"\n    using assms(2) sorted_wrt_dist_nearest_neighbors[of p n kdt] sorted_wrt_dist_last[of p nns] by force\n  thus ?thesis\n    using nearest_neighbors_def by blast\nnext\n  case False\n  hence \"length nns = 0\"\n    using assms(2) unfolding nearest_neighbors_def by (auto simp: length_nns)\n  thus ?thesis\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/KD_Tree/Nearest_Neighbors.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8615382200964034, "lm_q2_score": 0.863391599428538, "lm_q1q2_score": 0.7438448618178495}}
{"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_24\n  imports \"../../Test_Base\"\nbegin\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 max :: \"Nat => Nat => Nat\" where\n  \"max (Z) z = z\"\n| \"max (S z2) (Z) = S z2\"\n| \"max (S z2) (S x2) = S (max z2 x2)\"\n\nfun t2 :: \"Nat => Nat => bool\" where\n  \"t2 (Z) z = True\"\n| \"t2 (S z2) (Z) = False\"\n| \"t2 (S z2) (S x2) = t2 z2 x2\"\n\n\ntheorem property0 :(*Probably the best proof.*)\n  \"((x (max a b) a) = (t2 b a))\"\n  apply(induct rule:x.induct)\n     apply fastforce\n    apply clarsimp\n    apply(induct_tac z2)\n     apply fastforce+\n  done\n    (*Why does \"x.induct\" lead to the shortest proof?\n  Because \"x\"'s pattern-matching is complete, meaning that it does not involve any wild-card.*)\n\ntheorem property0' :\n  \"((x (max a b) a) = (t2 b a))\"\n  apply(induct b arbitrary:a)(*This arbitrary is important.*)\n   apply(induct_tac a)\n    apply fastforce+\n   apply(induct_tac xa)\n    apply fastforce+\n  apply(induct_tac a)\n   apply fastforce+\n  done\n\n(*We can finish proving this theorem starting induction on \"a\".*)\ntheorem property0'' :\n  \"((x (max a b) a) = (t2 b a))\"\n  apply(induct a arbitrary:b)(*This arbitrary is important.*)\n   apply clarsimp\n   apply(induct_tac b)\n    apply fastforce+\n  apply(induct_tac b)\n   apply clarsimp\n   apply(induct_tac a)\n    apply fastforce+\n  done\n\ntheorem property0''' :\n  \"((x (max a b) a) = (t2 b a))\"\n  apply(induct rule:t2.induct)\n    apply clarsimp\n    apply(induct_tac z)\n     apply fastforce\n    apply clarsimp\n    apply(induct_tac xa)\n     apply fastforce+\n  done\n\ntheorem property0'''' :\n  \"((x (max a b) a) = (t2 b a))\"\n  apply(induct rule:max.induct)(*This is equivalent to \"(induct rule:t2.induct)\"*)\n    apply clarsimp\n    apply(induct_tac z)\n     apply fastforce\n    apply clarsimp\n    apply(induct_tac xa)\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_24.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916029436189, "lm_q2_score": 0.8615382040983514, "lm_q1q2_score": 0.7438448510336423}}
{"text": "theory Testing\n  imports \"HOL-Analysis.Multivariate_Analysis\"\n\nbegin\n\nlemma interior_ball: \"(x \\<in> interior S) \\<longleftrightarrow> (\\<exists> e. 0 < e & (ball x e) \\<subseteq> S)\"\nproof-\n  { assume \"x \\<in> interior S\"\n    from this obtain T where T_def: \"open T & x \\<in> T & T \\<subseteq> S\" using interior_def by auto\n    hence \"\\<exists> e. 0 < e & (ball x e) \\<subseteq> T\" using open_contains_ball by auto\n    hence \"\\<exists> e. 0 < e & (ball x e) \\<subseteq> S\" using T_def by auto\n  } note imp1 = this\n  { assume \"(\\<exists> e. 0 < e & (ball x e) \\<subseteq> S)\"\n    from this obtain e where e_def: \"0 < e & (ball x e) \\<subseteq> S\" by auto\n    obtain T where T_def: \"T = ball x e\" by auto\n    then have \"open T & x \\<in> T & T \\<subseteq> S\" using open_ball e_def by auto\n    hence \"x \\<in> interior S\" using interior_def by auto\n  } from this show ?thesis using imp1 by auto\nqed\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/Testing.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8902942348544447, "lm_q2_score": 0.8354835289107309, "lm_q1q2_score": 0.7438261691050705}}
{"text": "(*  Author:  S\u00e9bastien Gou\u00ebzel   sebastien.gouezel@univ-nantes.fr\n    License: BSD\n*)\n\nsection \\<open>A theorem by Kohlberg and Neyman\\<close>\n\ntheory Kohlberg_Neyman_Karlsson\n  imports Fekete\nbegin\n\ntext \\<open>In this section, we prove a theorem due to Kohlberg and Neyman: given a semicontraction\n$T$ of a euclidean space, then $T^n(0)/n$ converges when $n \\to \\infty$. The proof we give\nis due to Karlsson. It mainly builds on subadditivity ideas. The geometry of the space\nis essentially not relevant except at the very end of the argument, where strict convexity\ncomes into play.\\<close>\n\ntext \\<open>We recall Fekete's lemma: if a sequence is subadditive (i.e.,\n$u_{n+m}\\leq u_n + u_m$), then $u_n/n$ converges to its infimum. It is proved\nin a different file, but we recall the statement for self-containedness.\\<close>\n\nlemma fekete:\n  fixes u::\"nat \\<Rightarrow> real\"\n  assumes \"\\<And>n m. u (m+n) \\<le> u m + u n\"\n          \"bdd_below {u n/n | n. n>0}\"\n  shows \"(\\<lambda>n. u n/n) \\<longlonglongrightarrow> Inf {u n/n | n. n>0}\"\napply (rule subadditive_converges_bounded) unfolding subadditive_def using assms by auto\n\ntext \\<open>A real sequence tending to infinity has infinitely many high-scores, i.e.,\nthere are infinitely many times where it is larger than all its previous values.\\<close>\n\nlemma high_scores:\n  fixes u::\"nat \\<Rightarrow> real\" and i::nat\n  assumes \"u \\<longlonglongrightarrow> \\<infinity>\"\n  shows \"\\<exists>n \\<ge> i. \\<forall>l \\<le> n. u l \\<le> u n\"\nproof -\n  define M where \"M = Max {u l|l. l < i}\"\n  define n where \"n = Inf {m. u m > M}\"\n  have \"eventually (\\<lambda>m. u m > M) sequentially\"\n    using assms by (simp add: filterlim_at_top_dense tendsto_PInfty_eq_at_top)\n  then have \"{m. u m > M} \\<noteq> {}\" by fastforce\n  then have \"n \\<in> {m. u m > M}\" unfolding n_def using Inf_nat_def1 by metis\n  then have \"u n > M\" by simp\n  have \"n \\<ge> i\"\n  proof (rule ccontr)\n    assume \" \\<not> i \\<le> n\"\n    then have *: \"n < i\" by simp\n    have \"u n \\<le> M\" unfolding M_def apply (rule Max_ge) using * by auto\n    then show False using \\<open>u n > M\\<close> by auto\n  qed\n  moreover have \"u l \\<le> u n\" if \"l \\<le> n\" for l\n  proof (cases \"l = n\")\n    case True\n    then show ?thesis by simp\n  next\n    case False\n    then have \"l < n\" using \\<open>l \\<le> n\\<close> by auto\n    then have \"l \\<notin> {m. u m > M}\"\n      unfolding n_def by (meson bdd_below_def cInf_lower not_le zero_le)\n    then show ?thesis using \\<open>u n > M\\<close> by auto\n  qed\n  ultimately show ?thesis by auto\nqed\n\ntext \\<open>Hahn-Banach in euclidean spaces: given a vector $u$, there exists a unit norm\nvector $v$ such that $\\langle u, v \\rangle = \\|u\\|$ (and we put a minus sign as we will\nuse it in this form). This uses the fact that, in Isabelle/HOL, euclidean spaces\nhave positive dimension by definition.\\<close>\n\nlemma select_unit_norm:\n  fixes u::\"'a::euclidean_space\"\n  shows \"\\<exists>v. norm v = 1 \\<and> v \\<bullet> u = - norm u\"\nproof (cases \"u = 0\")\n  case True\n  then show ?thesis using norm_Basis nonempty_Basis by fastforce\nnext\n  case False\n  show ?thesis\n    apply (rule exI[of _ \"-u/\\<^sub>R norm u\"])\n    using False by (auto simp add: dot_square_norm power2_eq_square)\nqed\n\ntext \\<open>We set up the assumption that we will use until the end of this file,\nin the following locale: we fix a semicontraction $T$ of a euclidean space.\nOur goal will be to show that such a semicontraction has an asymptotic translation vector.\\<close>\n\nlocale Kohlberg_Neyman_Karlsson =\n  fixes T::\"'a::euclidean_space \\<Rightarrow> 'a\"\n  assumes semicontract: \"dist (T x) (T y) \\<le> dist x y\"\nbegin\n\ntext \\<open>The iterates of $T$ are still semicontractions, by induction.\\<close>\n\nlemma semicontract_Tn:\n  \"dist ((T^^n) x) ((T^^n) y) \\<le> dist x y\"\napply (induction n, auto) using semicontract order_trans by blast\n\ntext \\<open>The main quantity we will use is the distance from the origin to its image under $T^n$.\nWe denote it by $u_n$. The main point is that it is subadditive by semicontraction, hence\nit converges to a limit $A$ given by $Inf \\{u_n/n\\}$, thanks to Fekete Lemma.\\<close>\n\ndefinition u::\"nat \\<Rightarrow> real\"\n  where \"u n = dist 0 ((T^^n) 0)\"\n\ndefinition A::real\n  where \"A = Inf {u n/n | n. n>0}\"\n\nlemma Apos: \"A \\<ge> 0\"\nunfolding A_def u_def by (rule cInf_greatest, auto)\n\nlemma Alim:\"(\\<lambda>n. u n/n) \\<longlonglongrightarrow> A\"\nunfolding A_def proof (rule fekete)\n  show \"bdd_below {u n / real n |n. 0 < n}\"\n    unfolding u_def bdd_below_def by (rule exI[of _ 0], auto)\n\n  fix m n\n  have \"u (m+n) = dist 0 ((T^^(m+n)) 0)\"\n    unfolding u_def by simp\n  also have \"... \\<le> dist 0 ((T^^m) 0) + dist ((T^^m) 0) ((T^^(m+n)) 0)\"\n    by (rule dist_triangle)\n  also have \"... = dist 0 ((T^^m) 0) + dist ((T^^m) 0) ((T^^m) ((T^^n) 0))\"\n    by (auto simp add: funpow_add)\n  also have \"... \\<le> dist 0 ((T^^m) 0) + dist 0 ((T^^n) 0)\"\n    using semicontract_Tn[of m] add_mono_thms_linordered_semiring(2) by blast\n  also have \"... = u m + u n\"\n    unfolding u_def by auto\n  finally show \"u (m+n) \\<le> u m + u n\" by auto\nqed\n\ntext \\<open>The main fact to prove the existence of an asymptotic translation vector for $T$\nis the following proposition: there exists a unit norm vector $v$ such that $T^\\ell(0)$ is in\nthe half-space at distance $A \\ell$ of the origin directed by $v$.\n\nThe idea of the proof is to find such a vector $v_i$ that works (with a small error $\\epsilon_i > 0$)\nfor times up to a time $n_i$, and then take a limit by compactness (or weak compactness, but\nsince we are in finite dimension, compactness works fine). Times $n_i$ are chosen to be large\nhigh scores of the sequence $u_n - (A-\\epsilon_i) n$, which tends to infinity since $u_n/n$\ntends to $A$.\\<close>\n\nproposition half_space:\n  \"\\<exists>v. norm v = 1 \\<and> (\\<forall>l. v \\<bullet> (T ^^ l) 0 \\<le> - A * l)\"\nproof -\n  define eps::\"nat \\<Rightarrow> real\" where \"eps = (\\<lambda>i. 1/of_nat (i+1))\"\n  have \"eps i > 0\" for i unfolding eps_def by auto\n  have \"eps \\<longlonglongrightarrow> 0\"\n    unfolding eps_def using LIMSEQ_ignore_initial_segment[OF lim_1_over_n, of 1] by simp\n  have vi: \"\\<exists>vi. norm vi = 1 \\<and> (\\<forall>l \\<le> i. vi \\<bullet> (T ^^ l) 0 \\<le> (- A + eps i) * l)\" for i\n  proof -\n    have L: \"(\\<lambda>n. ereal(u n - (A - eps i) * n)) \\<longlonglongrightarrow> \\<infinity>\"\n    proof (rule Lim_transform_eventually)\n      have \"ereal ((u n/n - A) + eps i) * ereal n = ereal(u n - (A - eps i) * n)\" if \"n \\<ge> 1\" for n\n        using that by (auto simp add: divide_simps algebra_simps)\n      then show \"eventually (\\<lambda>n. ereal ((u n/n - A) + eps i) * ereal n = ereal(u n - (A - eps i) * n)) sequentially\"\n        unfolding eventually_sequentially by auto\n\n      have \"(\\<lambda>n. (ereal ((u n/n - A) + eps i)) * ereal n) \\<longlonglongrightarrow> (0 + eps i) * \\<infinity>\"\n        apply (intro tendsto_intros)\n        using \\<open>eps i > 0\\<close> Alim by (auto simp add: LIM_zero)\n      then show \"(\\<lambda>n. ereal (u n / real n - A + eps i) * ereal (real n)) \\<longlonglongrightarrow> \\<infinity>\" \n        using  \\<open>eps i > 0\\<close> by simp\n    qed\n    obtain n where n: \"n \\<ge> i\" \"\\<And>l. l \\<le> n \\<Longrightarrow> u l - (A - eps i) * l \\<le> u n - (A - eps i) * n\"\n      using high_scores[OF L, of i] by auto\n    obtain vi where vi: \"norm vi = 1\" \"vi \\<bullet> ((T^^n) 0) = - norm ((T^^n) 0)\"\n      using select_unit_norm by auto\n    have \"vi \\<bullet> (T ^^ l) 0 \\<le> (- A + eps i) * l\" if \"l \\<le> i\" for l\n    proof -\n      have *: \"n = l + (n-l)\" using that \\<open>n \\<ge> i\\<close> by auto\n      have **: \"real (n-l) = real n - real l\" using that \\<open>n \\<ge> i\\<close> by auto\n      have \"vi \\<bullet> (T ^^ l) 0 = vi \\<bullet> ((T ^^ l) 0 - (T^^n) 0) + vi \\<bullet> ((T^^n) 0)\"\n        by (simp add: inner_diff_right)\n      also have \"... \\<le> norm vi * norm (((T ^^ l) 0 - (T^^n) 0)) + vi \\<bullet> ((T^^n) 0)\"\n        by (simp add: norm_cauchy_schwarz)\n      also have \"... = dist ((T^^l)(0)) ((T^^n) 0) - norm ((T^^n) 0)\"\n        using vi by (auto simp add: dist_norm)\n      also have \"... = dist ((T^^l)(0)) ((T^^l) ((T^^(n-l)) 0)) - norm ((T^^n) 0)\"\n        by (metis * funpow_add o_apply)\n      also have \"... \\<le> dist 0 ((T^^(n-l)) 0) - norm ((T^^n) 0)\"\n        using semicontract_Tn[of l 0 \"(T^^(n-l)) 0\"] by auto\n      also have \"... = u (n-l) - u n\"\n        unfolding u_def by auto\n      also have \"... \\<le> - (A - eps i) * l\"\n        using n(2)[of \"n-l\"] unfolding ** by (auto simp add: algebra_simps)\n      finally show ?thesis by auto\n    qed\n    then show ?thesis using vi(1) by auto\n  qed\n  have \"\\<exists>V::(nat \\<Rightarrow> 'a). \\<forall>i. norm (V i) = 1 \\<and> (\\<forall>l\\<le>i. V i \\<bullet> (T ^^ l) 0 \\<le> (- A + eps i) * l)\"\n    apply (rule choice) using vi by auto\n  then obtain V::\"nat \\<Rightarrow> 'a\" where V: \"\\<And>i. norm (V i) = 1\" \"\\<And>l i. l \\<le> i \\<Longrightarrow> V i \\<bullet> (T ^^ l) 0 \\<le> (- A + eps i) * l\"\n    by auto\n\n  have \"compact (sphere (0::'a) 1)\" by simp\n  moreover have \"V i \\<in> sphere 0 1\" for i using V(1) by auto\n  ultimately have \"\\<exists>v \\<in> sphere 0 1. \\<exists>r. strict_mono r \\<and> (V o r) \\<longlonglongrightarrow> v\"\n    using compact_eq_seq_compact_metric seq_compact_def by metis\n  then obtain v r where v: \"v \\<in> sphere 0 1\" \"strict_mono r\" \"(V o r) \\<longlonglongrightarrow> v\"\n    by auto\n  have \"v \\<bullet> (T ^^ l) 0 \\<le> - A * l\" for l\n  proof -\n    have *: \"(\\<lambda>i. (-A + eps (r i)) * l - V (r i) \\<bullet> (T ^^ l) 0) \\<longlonglongrightarrow> (-A + 0) * l - v \\<bullet> (T ^^ l) 0\"\n      apply (intro tendsto_intros)\n      using \\<open>(V o r) \\<longlonglongrightarrow> v\\<close> \\<open>eps \\<longlonglongrightarrow> 0\\<close> \\<open>strict_mono r\\<close> LIMSEQ_subseq_LIMSEQ unfolding comp_def by auto\n    have \"eventually (\\<lambda>i. (-A + eps (r i)) * l - V (r i) \\<bullet> (T ^^ l) 0 \\<ge> 0) sequentially\"\n      unfolding eventually_sequentially apply (rule exI[of _ l])\n      using V(2)[of l] seq_suble[OF \\<open>strict_mono r\\<close>] apply auto using le_trans by blast\n    then have \" (-A + 0) * l - v \\<bullet> (T ^^ l) 0 \\<ge> 0\"\n      using LIMSEQ_le_const[OF *, of 0] unfolding eventually_sequentially by auto\n    then show ?thesis by auto\n  qed\n  then show ?thesis using \\<open>v \\<in> sphere 0 1\\<close> by auto\nqed\n\ntext \\<open>We can now show the existence of an asymptotic translation vector for $T$. It is the vector\n$-v$ of the previous proposition: the point $T^\\ell(0)$ is in the half-space\nat distance $A \\ell$ of the origin directed by $v$, and has norm $\\sim A \\ell$, hence it has\nto be essentially $-A v$ by strict convexity of the euclidean norm.\\<close>\n\ntheorem KNK_thm:\n  \"convergent (\\<lambda>n. ((T^^n) 0) /\\<^sub>R n)\"\nproof -\n  obtain v where v: \"norm v = 1\" \"\\<And>l. v \\<bullet> (T ^^ l) 0 \\<le> - A * l\"\n    using half_space by auto\n  have \"(\\<lambda>n. norm(((T^^n) 0) /\\<^sub>R n + A *\\<^sub>R v)^2) \\<longlonglongrightarrow> 0\"\n  proof (rule tendsto_sandwich[of \"\\<lambda>_. 0\" _ _ \"\\<lambda>n. (norm((T^^n) 0) /\\<^sub>R n)^2 - A^2\"])\n    have \"norm(((T^^n) 0) /\\<^sub>R n + A *\\<^sub>R v)^2 \\<le> (norm((T^^n) 0) /\\<^sub>R n)^2 - A^2\" if \"n \\<ge> 1\" for n\n    proof -\n      have \"norm(((T^^n) 0) /\\<^sub>R n + A *\\<^sub>R v)^2 = norm(((T^^n) 0) /\\<^sub>R n)^2 + A * A * (norm v)^2 + 2 * A * inverse n * (v \\<bullet> (T^^n) 0)\"\n        unfolding power2_norm_eq_inner by (auto simp add: inner_commute algebra_simps)\n      also have \"... \\<le> norm(((T^^n) 0) /\\<^sub>R n)^2 + A * A * (norm v)^2 + 2 * A * inverse n * (-A * n)\"\n        using mult_left_mono[OF v(2)[of n] Apos] \\<open>n \\<ge> 1\\<close> by (auto, auto simp add: divide_simps)\n      also have \"... = norm(((T^^n) 0) /\\<^sub>R n)^2 - A * A\"\n        using \\<open>n \\<ge> 1\\<close> v(1) by auto\n      finally show ?thesis by (simp add: power2_eq_square)\n    qed\n    then show \"eventually (\\<lambda>n. norm ((T ^^ n) 0 /\\<^sub>R real n + A *\\<^sub>R v)^2 \\<le> (norm ((T ^^ n) 0) /\\<^sub>R real n)\\<^sup>2 - A^2) sequentially\"\n      unfolding eventually_sequentially by auto\n    have \"(\\<lambda>n. (norm ((T ^^ n) 0) /\\<^sub>R real n)^2) \\<longlonglongrightarrow> A\\<^sup>2\"\n      apply (intro tendsto_intros)\n      using Alim unfolding u_def by (auto simp add: divide_simps)\n    then show \"(\\<lambda>n. (norm ((T ^^ n) 0) /\\<^sub>R real n)\\<^sup>2 - A\\<^sup>2) \\<longlonglongrightarrow> 0\"\n      by (simp add: LIM_zero)\n  qed (auto)\n  then have \"(\\<lambda>n. sqrt((norm(((T^^n) 0) /\\<^sub>R n + A *\\<^sub>R v))^2)) \\<longlonglongrightarrow> sqrt 0\"\n    by (intro tendsto_intros)\n  then have \"(\\<lambda>n. norm((((T^^n) 0) /\\<^sub>R n) - (- A *\\<^sub>R v))) \\<longlonglongrightarrow> 0\"\n    by auto\n  then have \"(\\<lambda>n. ((T^^n) 0) /\\<^sub>R n) \\<longlonglongrightarrow> - A *\\<^sub>R v\"\n    using Lim_null tendsto_norm_zero_iff by blast\n  then show \"convergent (\\<lambda>n. ((T^^n) 0) /\\<^sub>R n)\"\n    unfolding convergent_def by auto\nqed\n\nend\n\nend (*of Kolberg_Neyman_Karlsson.thy*)\n\n\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/Ergodic_Theory/Kohlberg_Neyman_Karlsson.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8652240895276223, "lm_q2_score": 0.8596637523076225, "lm_q1q2_score": 0.743801787390262}}
{"text": "chapter {* R8: Deducci\u00f3n natural proposicional en Isabelle/HOL *}\n \ntheory R8_Deduccion_natural_proposicional\nimports Main \nbegin\n \ntext {*\n  Demostrar o refutar los siguientes lemas usando s\u00f3lo las reglas\n  b\u00e1sicas de deducci\u00f3n natural de la l\u00f3gica proposicional, de los\n  cuantificadores y de la igualdad: \n  \u00b7 conjI:      \\<lbrakk>P; Q\\<rbrakk> \\<Longrightarrow> P \\<and> Q\n  \u00b7 conjunct1:  P \\<and> Q \\<Longrightarrow> P\n  \u00b7 conjunct2:  P \\<and> Q \\<Longrightarrow> Q  \n  \u00b7 notnotD:    \\<not>\\<not> P \\<Longrightarrow> P\n  \u00b7 mp:         \\<lbrakk>P \\<longrightarrow> Q; P\\<rbrakk> \\<Longrightarrow> Q \n  \u00b7 impI:       (P \\<Longrightarrow> Q) \\<Longrightarrow> P \\<longrightarrow> Q\n  \u00b7 disjI1:     P \\<Longrightarrow> P \\<or> Q\n  \u00b7 disjI2:     Q \\<Longrightarrow> P \\<or> Q\n  \u00b7 disjE:      \\<lbrakk>P \\<or> Q; P \\<Longrightarrow> R; Q \\<Longrightarrow> R\\<rbrakk> \\<Longrightarrow> R \n  \u00b7 FalseE:     False \\<Longrightarrow> P\n  \u00b7 notE:       \\<lbrakk>\\<not>P; P\\<rbrakk> \\<Longrightarrow> R\n  \u00b7 notI:       (P \\<Longrightarrow> False) \\<Longrightarrow> \\<not>P\n  \u00b7 iffI:       \\<lbrakk>P \\<Longrightarrow> Q; Q \\<Longrightarrow> P\\<rbrakk> \\<Longrightarrow> P = Q\n  \u00b7 iffD1:      \\<lbrakk>Q = P; Q\\<rbrakk> \\<Longrightarrow> P \n  \u00b7 iffD2:      \\<lbrakk>P = Q; Q\\<rbrakk> \\<Longrightarrow> P\n  \u00b7 ccontr:     (\\<not>P \\<Longrightarrow> False) \\<Longrightarrow> P\n \n  \u00b7 allI:       \\<lbrakk>\\<forall>x. P x; P x \\<Longrightarrow> R\\<rbrakk> \\<Longrightarrow> R\n  \u00b7 allE:       (\\<And>x. P x) \\<Longrightarrow> \\<forall>x. P x\n  \u00b7 exI:        P x \\<Longrightarrow> \\<exists>x. P x\n  \u00b7 exE:        \\<lbrakk>\\<exists>x. P x; \\<And>x. P x \\<Longrightarrow> Q\\<rbrakk> \\<Longrightarrow> Q\n \n  \u00b7 refl:       t = t\n  \u00b7 subst:      \\<lbrakk>s = t; P s\\<rbrakk> \\<Longrightarrow> P t\n  \u00b7 trans:      \\<lbrakk>r = s; s = t\\<rbrakk> \\<Longrightarrow> r = t\n  \u00b7 sym:        s = t \\<Longrightarrow> t = s\n  \u00b7 not_sym:    t \\<noteq> s \\<Longrightarrow> s \\<noteq> t\n  \u00b7 ssubst:     \\<lbrakk>t = s; P s\\<rbrakk> \\<Longrightarrow> P t\n  \u00b7 box_equals: \\<lbrakk>a = b; a = c; b = d\\<rbrakk> \\<Longrightarrow> a: = d\n  \u00b7 arg_cong:   x = y \\<Longrightarrow> f x = f y\n  \u00b7 fun_cong:   f = g \\<Longrightarrow> f x = g x\n  \u00b7 cong:       \\<lbrakk>f = g; x = y\\<rbrakk> \\<Longrightarrow> f x = g y\n*}\n \ntext {*\n  Se usar\u00e1n las reglas notnotI, mt y not_ex que demostramos a continuaci\u00f3n.\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 \ntext {* --------------------------------------------------------------- \n  Ejercicio 1. Demostrar\n     \\<not>q \\<longrightarrow> \\<not>p \\<turnstile> p \\<longrightarrow> q\n  ------------------------------------------------------------------ *}\n \nlemma ejercicio_1:\n  assumes 1: \"\\<not>q \\<longrightarrow> \\<not>p\"\n  shows \"p \\<longrightarrow> q\"\nproof -\n  {assume 2: \"p\"\n   then have 3: \"\\<not>\\<not>p\" by (rule notnotI)\n   have 4: \"\\<not>\\<not>q\" using 1 3 by (rule mt)\n   then have 5: \"q\" by (rule notnotD)} \n  then show \"p \\<longrightarrow> q\" by (rule impI)\nqed\n\nlemma ejercicio_1_2:\n  assumes \"\\<not>q \\<longrightarrow> \\<not>p\"\n          \"p\"\n  shows \"p \\<longrightarrow> q\"\nusing assms\nby auto\n\ntext {* --------------------------------------------------------------- \n  Ejercicio 2. Demostrar\n     \\<not>(\\<not>p \\<and> \\<not>q) \\<turnstile> p \\<or> q\n  ------------------------------------------------------------------ *}\n\nlemma ejercicio_2:\n  assumes 1: \"\\<not>(\\<not>p \\<and> \\<not>q)\"\n  shows \"p \\<or> q\"\nproof -\n  {assume 2: \"(\\<not>p \\<and> \\<not>q)\"\n   have 3: \"p\" using 1 2 by (rule notE)\n   then have 4: \"p \\<or> q\" by (rule disjI1)}\n   then show \"p \\<or> q\" by auto\nqed\n\nlemma ejercicio_2_2:\n  assumes \"\\<not>(\\<not>p \\<and> \\<not>q)\" and\n          \"(\\<not>p \\<and> \\<not>q)\"\n  shows \"p \\<or> q\"\nusing assms\nby auto\n\n\ntext {* --------------------------------------------------------------- \n  Ejercicio 3. Demostrar\n     \\<not>(\\<not>p \\<or> \\<not>q) \\<turnstile> p \\<and> q\n  ------------------------------------------------------------------ *}\n\nlemma ejercicio_3:\n  assumes 1: \"\\<not>(\\<not>p \\<or> \\<not>q)\" and\n          2: \"(\\<not>p \\<or> \\<not>q)\"\n  shows \"p \\<and> q\"\nproof -\n   have 3: \"p\" using 1 2 by (rule notE)\n   have 4: \"q\" using 1 2 by (rule notE)\n   show \"p \\<and> q\" using 3 4 by (rule conjI)\nqed\n\nlemma ejercicio_3_2:\n  assumes \"\\<not>(\\<not>p \\<or> \\<not>q)\" and\n          \"(\\<not>p \\<or> \\<not>q)\"\n  shows \"p \\<and> q\"\nusing assms\nby auto\n\ntext {* --------------------------------------------------------------- \n  Ejercicio 4. Demostrar\n     \\<not>(p \\<and> q) \\<turnstile> \\<not>p \\<or> \\<not>q\n  ------------------------------------------------------------------ *}\n \nlemma ejercicio_4:\n  assumes 1: \"\\<not>(p \\<and> q)\" and\n          2: \"(p \\<and> q)\"\n  shows \"\\<not>p \\<or> \\<not>q\"\nproof -\n   have 3: \"\\<not>p\" using 1 2 by (rule notE)\n   show \"\\<not>p \\<or> \\<not>q\" using 3 by (rule disjI1)\nqed\n\nlemma ejercicio_4_2:\n  assumes \"\\<not>(p \\<and> q)\" and\n          \"(p \\<and> q)\"\n  shows \"\\<not>p \\<or> \\<not>q\"\nusing assms\nby auto\n\ntext {* --------------------------------------------------------------- \n  Ejercicio 5. Demostrar\n     \\<turnstile> (p \\<longrightarrow> q) \\<or> (q \\<longrightarrow> p)\n  ------------------------------------------------------------------ *}\n \nlemma ejercicio_5:\n  assumes 1: \"q\"\n  shows \"(p \\<longrightarrow> q) \\<or> (q \\<longrightarrow> p)\" \nproof -\n  have 2: \"(p \\<longrightarrow>q)\" using 1 by (rule impI)\n  show \"(p \\<longrightarrow> q) \\<or> (q \\<longrightarrow> p)\" using 2 by (rule disjI1) \nqed\n\nlemma ejercicio_5_2:\n  assumes \"q\"\n  shows \"(p \\<longrightarrow> q) \\<or> (q \\<longrightarrow> p)\" \nusing assms\nby auto\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/R8_Deduccion_natural_proposicional.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637577007394, "lm_q2_score": 0.8652240738888188, "lm_q1q2_score": 0.7438017786124043}}
{"text": "(*  Title:      HOL/ex/MergeSort.thy\n    Author:     Tobias Nipkow\n    Copyright   2002 TU Muenchen\n*)\n\nsection\\<open>Merge Sort\\<close>\n\ntheory MergeSort\nimports \"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 mset_merge [simp]:\n  \"mset (merge xs ys) = mset xs + mset 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)\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 mset_msort:\n  \"mset (msort xs) = mset xs\"\n  by (induct xs rule: msort.induct)\n    (simp_all, metis append_take_drop_id mset.simps(2) mset_append)\n\ntheorem msort_sort:\n  \"sort = msort\"\n  by (rule ext, rule properties_for_sort) (fact mset_msort sorted_msort)+\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/MergeSort.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8670357701094303, "lm_q2_score": 0.8577681104440172, "lm_q1q2_score": 0.7437156342141393}}
{"text": "(*  Author:  Florian Haftmann, TU Muenchen\n*)\n\nsubsection \\<open>Rounded division: modulus centered towards zero.\\<close>\n\ntheory Rounded_Division\n  imports Main\nbegin\n\nlemma off_iff_abs_mod_2_eq_one:\n  \\<open>odd l \\<longleftrightarrow> \\<bar>l\\<bar> mod 2 = 1\\<close> for l :: int\n  by (simp flip: odd_iff_mod_2_eq_one)\n\ndefinition rounded_divide :: \\<open>int \\<Rightarrow> int \\<Rightarrow> int\\<close>  (infixl \\<open>rdiv\\<close> 70)\n  where \\<open>k rdiv l = sgn l * ((k + \\<bar>l\\<bar> div 2) div \\<bar>l\\<bar>)\\<close>\n\ndefinition rounded_modulo :: \\<open>int \\<Rightarrow> int \\<Rightarrow> int\\<close>  (infixl \\<open>rmod\\<close> 70)\n  where \\<open>k rmod l = (k + \\<bar>l\\<bar> div 2) mod \\<bar>l\\<bar> - \\<bar>l\\<bar> div 2\\<close>\n\nlemma rdiv_mult_rmod_eq:\n  \\<open>k rdiv l * l + k rmod l = k\\<close>\nproof -\n  have *: \\<open>l * (sgn l * j) = \\<bar>l\\<bar> * j\\<close> for j\n    by (simp add: ac_simps abs_sgn)\n  show ?thesis\n    by (simp add: rounded_divide_def rounded_modulo_def algebra_simps *)\nqed\n\nlemma mult_rdiv_rmod_eq:\n  \\<open>l * (k rdiv l) + k rmod l = k\\<close>\n  using rdiv_mult_rmod_eq [of k l] by (simp add: ac_simps)\n\nlemma rmod_rdiv_mult_eq:\n  \\<open>k rmod l + k rdiv l * l = k\\<close>\n  using rdiv_mult_rmod_eq [of k l] by (simp add: ac_simps)\n\nlemma rmod_mult_rdiv_eq:\n  \\<open>k rmod l + l * (k rdiv l) = k\\<close>\n  using rdiv_mult_rmod_eq [of k l] by (simp add: ac_simps)\n\nlemma minus_rdiv_mult_eq_rmod:\n  \\<open>k - k rdiv l * l = k rmod l\\<close>\n  by (rule add_implies_diff [symmetric]) (fact rmod_rdiv_mult_eq)\n\nlemma minus_mult_rdiv_eq_rmod:\n  \\<open>k - l * (k rdiv l) = k rmod l\\<close>\n  by (rule add_implies_diff [symmetric]) (fact rmod_mult_rdiv_eq)\n\nlemma minus_rmod_eq_rdiv_mult:\n  \\<open>k - k rmod l = k rdiv l * l\\<close>\n  by (rule add_implies_diff [symmetric]) (fact rdiv_mult_rmod_eq)\n\nlemma minus_rmod_eq_mult_rdiv:\n  \\<open>k - k rmod l = l * (k rdiv l)\\<close>\n  by (rule add_implies_diff [symmetric]) (fact mult_rdiv_rmod_eq)\n\nlemma rdiv_0_eq [simp]:\n  \\<open>k rdiv 0 = 0\\<close>\n  by (simp add: rounded_divide_def)\n\nlemma rmod_0_eq [simp]:\n  \\<open>k rmod 0 = k\\<close>\n  by (simp add: rounded_modulo_def)\n\nlemma rdiv_1_eq [simp]:\n  \\<open>k rdiv 1 = k\\<close>\n  by (simp add: rounded_divide_def)\n\nlemma rmod_1_eq [simp]:\n  \\<open>k rmod 1 = 0\\<close>\n  by (simp add: rounded_modulo_def)\n\nlemma zero_rdiv_eq [simp]:\n  \\<open>0 rdiv k = 0\\<close>\n  by (auto simp add: rounded_divide_def not_less zdiv_eq_0_iff)\n\nlemma zero_rmod_eq [simp]:\n  \\<open>0 rmod k = 0\\<close>\n  by (auto simp add: rounded_modulo_def not_less zmod_trivial_iff)\n\nlemma rdiv_minus_eq:\n  \\<open>k rdiv - l = - (k rdiv l)\\<close>\n  by (simp add: rounded_divide_def)\n\nlemma rmod_minus_eq [simp]:\n  \\<open>k rmod - l = k rmod l\\<close>\n  by (simp add: rounded_modulo_def)\n\nlemma rdiv_abs_eq:\n  \\<open>k rdiv \\<bar>l\\<bar> = sgn l * (k rdiv l)\\<close>\n  by (simp add: rounded_divide_def)\n\nlemma rmod_abs_eq [simp]:\n  \\<open>k rmod \\<bar>l\\<bar> = k rmod l\\<close>\n  by (simp add: rounded_modulo_def)\n\nlemma nonzero_mult_rdiv_cancel_right:\n  \\<open>k * l rdiv l = k\\<close> if \\<open>l \\<noteq> 0\\<close>\nproof -\n  have \\<open>sgn l * k * \\<bar>l\\<bar> rdiv l = k\\<close>\n    using that by (simp add: rounded_divide_def)\n  with that show ?thesis\n    by (simp add: ac_simps abs_sgn)\nqed\n\nlemma rdiv_self_eq [simp]:\n  \\<open>k rdiv k = 1\\<close> if \\<open>k \\<noteq> 0\\<close>\n  using that nonzero_mult_rdiv_cancel_right [of k 1] by simp\n\nlemma rmod_self_eq [simp]:\n  \\<open>k rmod k = 0\\<close>\nproof -\n  have \\<open>(sgn k * \\<bar>k\\<bar> + \\<bar>k\\<bar> div 2) mod \\<bar>k\\<bar> = \\<bar>k\\<bar> div 2\\<close>\n    by (auto simp add: zmod_trivial_iff)\n  also have \\<open>sgn k * \\<bar>k\\<bar> = k\\<close>\n    by (simp add: abs_sgn)\n  finally show ?thesis\n    by (simp add: rounded_modulo_def algebra_simps)\nqed\n\nlemma signed_take_bit_eq_rmod:\n  \\<open>signed_take_bit n k = k rmod (2 ^ Suc n)\\<close>\n  by (simp only: rounded_modulo_def power_abs abs_numeral flip: take_bit_eq_mod)\n    (simp add: signed_take_bit_eq_take_bit_shift)\n\nlemma rmod_less_divisor:\n  \\<open>k rmod l < \\<bar>l\\<bar> - \\<bar>l\\<bar> div 2\\<close> if \\<open>l \\<noteq> 0\\<close>\n  using that pos_mod_bound [of \\<open>\\<bar>l\\<bar>\\<close>] by (simp add: rounded_modulo_def)\n\nlemma rmod_less_equal_divisor:\n  \\<open>k rmod l \\<le> \\<bar>l\\<bar> div 2\\<close> if \\<open>l \\<noteq> 0\\<close>\nproof -\n  from that rmod_less_divisor [of l k]\n  have \\<open>k rmod l < \\<bar>l\\<bar> - \\<bar>l\\<bar> div 2\\<close>\n    by simp\n  also have \\<open>\\<bar>l\\<bar> - \\<bar>l\\<bar> div 2 = \\<bar>l\\<bar> div 2 + of_bool (odd l)\\<close>\n    by auto\n  finally show ?thesis\n    by (cases \\<open>even l\\<close>) simp_all\nqed\n\nlemma divisor_less_equal_rmod':\n  \\<open>\\<bar>l\\<bar> div 2 - \\<bar>l\\<bar> \\<le> k rmod l\\<close> if \\<open>l \\<noteq> 0\\<close>\nproof -\n  have \\<open>0 \\<le> (k + \\<bar>l\\<bar> div 2) mod \\<bar>l\\<bar>\\<close>\n    using that pos_mod_sign [of \\<open>\\<bar>l\\<bar>\\<close>] by simp\n  then show ?thesis\n    by (simp_all add: rounded_modulo_def)\nqed\n\nlemma divisor_less_equal_rmod:\n  \\<open>- (\\<bar>l\\<bar> div 2) \\<le> k rmod l\\<close> if \\<open>l \\<noteq> 0\\<close>\n  using that divisor_less_equal_rmod' [of l k]\n  by (simp add: rounded_modulo_def)\n\nlemma abs_rmod_less_equal:\n  \\<open>\\<bar>k rmod l\\<bar> \\<le> \\<bar>l\\<bar> div 2\\<close> if \\<open>l \\<noteq> 0\\<close>\n  using that divisor_less_equal_rmod [of l k]\n  by (simp add: abs_le_iff rmod_less_equal_divisor)\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/Rounded_Division.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681122619883, "lm_q2_score": 0.8670357649558006, "lm_q1q2_score": 0.7437156313697662}}
{"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\" \"k' < k1 \\<Longrightarrow> f k' = g k'\" for k'\n    by (blast elim!: less_funE) \n  assume \"less_fun g f\" then obtain k2 where k2: \"g k2 < f k2\" \"k' < k2 \\<Longrightarrow> g k' = f k'\" for 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 \\<open>less_fun f g\\<close> obtain k1 where k1: \"f k1 < g k1\" \"k' < k1 \\<Longrightarrow> f k' = g k'\" for k'\n    by (blast elim!: less_funE)                          \n  from \\<open>less_fun g h\\<close> obtain k2 where k2: \"g k2 < h k2\" \"k' < k2 \\<Longrightarrow> g k' = h k'\" for 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  { define K where \"K = {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    define q where \"q = 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 \\<open>q \\<in> K\\<close> 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": "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/Fun_Lexorder.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357701094304, "lm_q2_score": 0.8577681031721325, "lm_q1q2_score": 0.7437156279091552}}
{"text": "(*\n  File:     Power_Sum_Puzzle.thy\n  Author:   Manuel Eberl, TU M\u00fcnchen\n*)\nsection \\<open>Power sum puzzles\\<close>\ntheory Power_Sum_Puzzle\nimports\n  Power_Sum_Polynomials\n  \"Polynomial_Factorization.Rational_Root_Test\"\nbegin\n\nsubsection \\<open>General setting and results\\<close>\n\ntext \\<open>\n  We now consider the following situation: Given unknown complex numbers $x_1,\\ldots,x_n$,\n  define $p_k = x_1^k + \\ldots + x_n^k$. Also, define $e_k := e_k(x_1,\\ldots,x_n)$ where\n  $e_k(X_1,\\ldots,X_n)$ is the $k$-th elementary symmetric polynomial.\n\n  What is the relationship between the sequences $e_k$ and $p_k$; in particular,\n  how can we determine one from the other?\n\\<close>\nlocale power_sum_puzzle =\n  fixes x :: \"nat \\<Rightarrow> complex\"\n  fixes n :: nat\nbegin\n\ntext \\<open>\n  We first introduce the notation $p_k := x_1 ^ k + \\ldots + x_n ^ k$:\n\\<close>\ndefinition p where \"p k = (\\<Sum>i<n. x i ^ k)\"\n\nlemma p_0 [simp]: \"p 0 = of_nat n\"\n  by (simp add: p_def)\n\nlemma p_altdef: \"p k = insertion x (powsum_mpoly {..<n} k)\"\n  by (simp add: p_def)\n\ntext \\<open>\n  Similarly, we introduce the notation $e_k = e_k(x_1,\\ldots, x_n)$ where\n  $e_k(X_1,\\ldots,X_n)$ is the $k$-th elementary symmetric polynomial (i.\\,e. the sum of\n  all monomials that can be formed by taking the product of exactly $k$ distinct variables).\n\\<close>\ndefinition e where \"e k = (\\<Sum>Y | Y \\<subseteq> {..<n} \\<and> card Y = k. prod x Y)\"\n\nlemma e_altdef: \"e k = insertion x (sym_mpoly {..<n} k)\"\n  by (simp add: e_def insertion_sym_mpoly)\n\ntext \\<open>\n  It is clear that $e_k$ vanishes for $k > n$.\n\\<close>\nlemma e_eq_0 [simp]: \"k > n \\<Longrightarrow> e k = 0\"\n  by (simp add: e_altdef)\n\nlemma e_0 [simp]: \"e 0 = 1\"\n  by (simp add: e_altdef)\n\n\ntext \\<open>\n  The recurrences we got from the Girard--Newton Theorem earlier now directly give us\n  analogous recurrences for $e_k$ and $p_k$:\n\\<close>\nlemma e_recurrence:\n  assumes k: \"k > 0\"\n  shows   \"e k = -(\\<Sum>i=1..k. (- 1) ^ i * e (k - i) * p i) / of_nat k\"\n  using assms unfolding e_altdef p_altdef\n  by (subst sym_mpoly_recurrence)\n     (auto simp: insertion_sum insertion_add insertion_mult insertion_power insertion_sym_mpoly)\n\nlemma p_recurrence:\n  assumes k: \"k > 0\"\n  shows   \"p k = -of_nat k * (-1) ^ k * e k - (\\<Sum>i=1..<k. (-1) ^ i * e i * p (k - i))\"\n  using assms unfolding e_altdef p_altdef\n  by (subst powsum_mpoly_recurrence)\n     (auto simp: insertion_sum insertion_add insertion_mult insertion_diff \n                 insertion_power insertion_sym_mpoly)\n\nlemma p_recurrence'':\n  assumes k: \"k > n\"\n  shows   \"p k = -(\\<Sum>i=1..n. (-1) ^ i * e i * p (k - i))\"\n  using assms unfolding e_altdef p_altdef\n  by (subst powsum_mpoly_recurrence')\n     (auto simp: insertion_sum insertion_add insertion_mult insertion_diff \n                 insertion_power insertion_sym_mpoly)\n\n\ntext \\<open>\n  It is clear from this recurrence that if $p_1$ to $p_n$ are rational, then so are the $e_k$:\n\\<close>\nlemma e_in_Rats:\n  assumes \"\\<And>k. k \\<in> {1..n} \\<Longrightarrow> p k \\<in> \\<rat>\"\n  shows   \"e k \\<in> \\<rat>\"\nproof (cases \"k \\<le> n\")\n  case True\n  thus ?thesis\n  proof (induction k rule: less_induct)\n    case (less k)\n    show ?case\n    proof (cases \"k = 0\")\n      case False\n      thus ?thesis using assms less\n        by (subst e_recurrence) (auto intro!: Rats_divide)\n    qed auto\n  qed\nqed auto\n\ntext \\<open>\n  Analogously, if $p_1$ to $p_n$ are rational, then so are all the other $p_k$:\n\\<close>\nlemma p_in_Rats:\n  assumes \"\\<And>k. k \\<in> {1..n} \\<Longrightarrow> p k \\<in> \\<rat>\"\n  shows   \"p k \\<in> \\<rat>\"\nproof (induction k rule: less_induct)\n  case (less k)\n  consider \"k = 0\" | \"k \\<in> {1..n}\" | \"k > n\"\n    by force\n  thus ?case\n  proof cases\n    assume \"k > n\"\n    thus ?thesis\n      using less assms by (subst p_recurrence'') (auto intro!: sum_in_Rats Rats_mult e_in_Rats)\n  qed (use assms in auto)\nqed\n\n\ntext \\<open>\n  Next, we define the unique monic polynomial that has $x_1, \\ldots, x_n$ as its roots\n  (respecting multiplicity):\n\\<close>\ndefinition Q :: \"complex poly\" where \"Q = (\\<Prod>i<n. [:-x i, 1:])\"\n\nlemma degree_Q [simp]: \"Polynomial.degree Q = n\"\n  by (simp add: Q_def degree_prod_eq_sum_degree)\n\nlemma lead_coeff_Q [simp]: \"Polynomial.coeff Q n = 1\"\n  using monic_prod[of \"{..<n}\" \"\\<lambda>i. [:-x i, 1:]\"]\n  by (simp add: Q_def degree_prod_eq_sum_degree)\n\ntext \\<open>\n  By Vieta's Theorem, we then have:\n  \\[Q(X) = \\sum_{k=0}^n (-1)^{n-k} e_{n-k} X^k\\]\n  In other words: The above allows us to determine the $x_1, \\ldots, x_n$ explicitly.\n  They are, in fact, precisely the roots of the above polynomial (respecting multiplicity).\n  Since this polynomial depends only on the $e_k$, which are in turn determined by\n  $p_1, \\ldots, p_n$, this means that these are the \\<^emph>\\<open>only\\<close> solutions of this puzzle\n  (up to permutation of the $x_i$).\n\\<close>\nlemma coeff_Q: \"Polynomial.coeff Q k = (if k > n then 0 else (-1) ^ (n - k) * e (n - k))\"\nproof (cases \"k \\<le> n\")\n  case True\n  thus ?thesis\n    using coeff_poly_from_roots[of \"{..<n}\" k x] by (auto simp: Q_def e_def)\nqed (auto simp: Polynomial.coeff_eq_0)\n\nlemma Q_altdef: \"Q = (\\<Sum>k\\<le>n. Polynomial.monom ((-1) ^ (n - k) * e (n - k)) k)\"\n  by (subst poly_as_sum_of_monoms [symmetric]) (simp add: coeff_Q)\n\ntext \\<open>\n  The following theorem again shows that $x_1, \\ldots, x_n$ are precisely the roots\n  of \\<^term>\\<open>Q\\<close>, respecting multiplicity.\n\\<close>\ntheorem mset_x_eq_poly_roots_Q: \"{#x i. i \\<in># mset_set {..<n}#} = poly_roots Q\"\nproof -\n  have \"poly_roots Q = (\\<Sum>i<n. {#x i#})\"\n    by (simp add: Q_def poly_roots_prod)\n  also have \"\\<dots> = {#x i. i \\<in># mset_set {..<n}#}\"\n    by (induction n) (auto simp: lessThan_Suc)\n  finally show ?thesis ..\nqed\n\nend\n\n\nsubsection \\<open>Existence of solutions\\<close>\n\ntext \\<open>\n  So far, we have assumed a solution to the puzzle and then shown the properties that this\n  solution must fulfil. However, we have not yet shown that there \\<^emph>\\<open>is\\<close> a solution.\n  We will do that now.\n\n  Let $n$ be a natural number and $f_k$ some sequence of complex numbers. We will show that \n  there are $x_1, \\ldots, x_n$ so that $x_1 ^ k + \\ldots + x_n ^ k = f_k$ for any $1\\leq k\\leq n$.\n\\<close>\nlocale power_sum_puzzle_existence =\n  fixes f :: \"nat \\<Rightarrow> complex\" and n :: nat\nbegin\n\ntext \\<open>\n  First, we define a sequence of numbers \\<open>e'\\<close> analogously to the sequence \\<open>e\\<close> before,\n  except that we replace all occurrences of the power sum $p_k$ with $f_k$ (recall that in the end\n  we want $p_k = f_k$).\n\\<close>\nfun e' :: \"nat \\<Rightarrow> complex\"\n  where \"e' k = (if k = 0 then 1 else if k > n then 0\n                 else -(\\<Sum>i=1..k. (-1) ^ i * e' (k - i) * f i) / of_nat k)\"\n\nlemmas [simp del] = e'.simps\n\nlemma e'_0 [simp]: \"e' 0 = 1\"\n  by (simp add: e'.simps)\n\nlemma e'_eq_0 [simp]: \"k > n \\<Longrightarrow> e' k = 0\"\n  by (auto simp: e'.simps)\n\ntext \\<open>\n  Just as before, we can show the following recurrence for \\<open>f\\<close> in terms of \\<open>e'\\<close>:\n\\<close>\nlemma f_recurrence:\n  assumes k: \"k > 0\" \"k \\<le> n\"\n  shows   \"f k = -of_nat k * (-1) ^ k * e' k - (\\<Sum>i=1..<k. (- 1) ^ i * e' i * f (k - i))\"\nproof -\n  have \"-of_nat k * e' k = (\\<Sum>i=1..k. (- 1) ^ i * e' (k - i) * f i)\"\n    using assms by (subst e'.simps) (simp add: field_simps)\n  hence \"(-1)^k * (-of_nat k * e' k) = (-1)^k * (\\<Sum>i=1..k. (- 1) ^ i * e' (k - i) * f i)\"\n    by simp\n  also have \"\\<dots> = f k + (-1) ^ k * (\\<Sum>i=1..<k. (- 1) ^ i * e' (k - i) * f i)\"\n    using assms by (subst sum.last_plus) (auto simp: minus_one_power_iff)\n  also have \"(-1) ^ k * (\\<Sum>i=1..<k. (- 1) ^ i * e' (k - i) * f i) =\n             (\\<Sum>i=1..<k. (- 1) ^ (k - i) * e' (k - i) * f i)\"\n    unfolding sum_distrib_left by (intro sum.cong) (auto simp: minus_one_power_iff)\n  also have \"\\<dots> = (\\<Sum>i=1..<k. (- 1) ^ i * e' i * f (k - i))\"\n    by (intro sum.reindex_bij_witness[of _ \"\\<lambda>i. k - i\" \"\\<lambda>i. k - i\"]) auto\n  finally show ?thesis\n    by (simp add: algebra_simps)\nqed\n\ntext \\<open>\n  We now define a polynomial whose roots will be precisely the solution $x_1, \\ldots, x_n$ to our\n  problem.\n\\<close>\nlift_definition Q' :: \"complex poly\" is \"\\<lambda>k. if k > n then 0 else (-1) ^ (n - k) * e' (n - k)\"\n  using eventually_gt_at_top[of n] unfolding cofinite_eq_sequentially\n  by eventually_elim auto\n\nlemma coeff_Q': \"Polynomial.coeff Q' k = (if k > n then 0 else (-1) ^ (n - k) * e' (n - k))\"\n  by transfer auto\n\nlemma lead_coeff_Q': \"Polynomial.coeff Q' n = 1\"\n  by (simp add: coeff_Q')\n\nlemma degree_Q' [simp]: \"Polynomial.degree Q' = n\"\nproof (rule antisym)\n  show \"Polynomial.degree Q' \\<ge> n\"\n    by (rule le_degree) (auto simp: coeff_Q')\n  show \"Polynomial.degree Q' \\<le> n\"\n    by (rule degree_le) (auto simp: coeff_Q')\nqed\n\ntext \\<open>\n  Since the complex numbers are algebraically closed, this polynomial splits into\n  linear factors:\n\\<close>\ndefinition Root :: \"nat \\<Rightarrow> complex\"\n  where \"Root = (SOME Root. Q' = (\\<Prod>i<n. [:-Root i, 1:]))\"\n\n\n\ntext \\<open>\n  We can therefore now use the results from before for these $x_1, \\ldots, x_n$.\n\\<close>\nsublocale power_sum_puzzle Root n .\n\ntext \\<open>\n  Vieta's theorem gives us an expression for the coefficients of \\<open>Q'\\<close> in terms of\n  $e_k(x_1,\\ldots,x_n)$. This shows that our \\<open>e'\\<close> is indeed exactly the same as \\<open>e\\<close>.\n\\<close>\nlemma e'_eq_e: \"e' k = e k\"\nproof (cases \"k \\<le> n\")\n  case True\n  from True have \"e' k = (-1) ^ k * poly.coeff Q' (n - k)\"\n    by (simp add: coeff_Q')\n  also have \"Q' = (\\<Prod>x<n. [:-Root x, 1:])\"\n    using Root by simp\n  also have \"(-1) ^ k * poly.coeff \\<dots> (n - k) = e k\"\n    using True coeff_poly_from_roots[of \"{..<n}\" \"n - k\" Root]\n    by (simp add: insertion_sym_mpoly e_altdef)\n  finally show \"e' k = e k\" .\nqed auto\n\ntext \\<open>\n  It then follows by a simple induction that $p_k = f_k$ for $1\\leq k\\leq n$, as intended:\n\\<close>\nlemma p_eq_f:\n  assumes \"k > 0\" \"k \\<le> n\"\n  shows   \"p k = f k\"\n  using assms\nproof (induction k rule: less_induct)\n  case (less k)\n  thus \"p k = f k\"\n    using p_recurrence[of k] f_recurrence[of k] less by (simp add: e'_eq_e)\nqed\n\nend\n\ntext \\<open>\n  Here is a more condensed form of the above existence theorem:\n\\<close>\ntheorem power_sum_puzzle_has_solution:\n  fixes f :: \"nat \\<Rightarrow> complex\"\n  shows \"\\<exists>Root. \\<forall>k\\<in>{1..n}. (\\<Sum>i<n. Root i ^ k) = f k\"\nproof -\n  interpret power_sum_puzzle_existence f .\n  from p_eq_f have \"\\<forall>k\\<in>{1..n}. (\\<Sum>i<n. Root i ^ k) = f k\"\n    by (auto simp: p_def)\n  thus ?thesis by blast\nqed\n\n\nsubsection \\<open>A specific puzzle\\<close>\n\ntext \\<open>\n  We now look at one particular instance of this puzzle, which was given as an exercise in\n  \\<^emph>\\<open>Abstract Algebra\\<close> by Dummit and Foote (Exercise 23 in Section 14.6)~\\cite{dummit}.\n\n Suppose we know that\n  $x + y + z = 1$, $x^2 + y^2 + z^2 = 2$, and $x^3 + y^3 + z^3 = 3$. Then what is\n  $x^5+y^5+z^5$? What about any arbitrary $x^n+y^n+z^n$?\n\\<close>\nlocale power_sum_puzzle_example =\n  fixes x y z :: complex\n  assumes xyz: \"x   + y   + z   = 1\"\n               \"x^2 + y^2 + z^2 = 2\"\n               \"x^3 + y^3 + z^3 = 3\"\nbegin\n\ntext \\<open>\n  We reuse the results we have shown in the general case before.\n\\<close>\ndefinition f where \"f n = [x,y,z] ! n\"\n\nsublocale power_sum_puzzle f 3 .\n\ntext \\<open>\n  We can simplify \\<^term>\\<open>p\\<close> a bit more now.\n\\<close>\nlemma p_altdef': \"p k = x ^ k + y ^ k + z ^ k\"\n  unfolding p_def f_def by (simp add: eval_nat_numeral)\n\nlemma p_base [simp]: \"p (Suc 0) = 1\" \"p 2 = 2\" \"p 3 = 3\"\n  using xyz by (simp_all add: p_altdef')\n\ntext \\<open>\n  We can easily compute all the non-zero values of \\<^term>\\<open>e\\<close> recursively:\n\\<close>\nlemma e_Suc_0 [simp]: \"e (Suc 0) = 1\"\n  by (subst e_recurrence; simp)\n\nlemma e_2 [simp]: \"e 2 = -1/2\"\n  by (subst e_recurrence; simp add: atLeastAtMost_nat_numeral)\n\nlemma e_3 [simp]: \"e 3 = 1/6\"\n  by (subst e_recurrence; simp add: atLeastAtMost_nat_numeral)\n\ntext \\<open>\n  Plugging in all the values, the recurrence relation for \\<^term>\\<open>p\\<close> now looks like this:\n\\<close>\nlemma p_recurrence''': \"k > 3 \\<Longrightarrow> p k = p (k-3) / 6 + p (k-2) / 2 + p (k-1)\"\n  using p_recurrence''[of k] by (simp add: atLeastAtMost_nat_numeral)\n\ntext \\<open>\n  Also note again that all $p_k$ are rational:\n\\<close>\nlemma p_in_Rats': \"p k \\<in> \\<rat>\"\nproof -\n  have *: \"{1..3} = {1, 2, (3::nat)}\"\n    by auto\n  also have \"\\<forall>k\\<in>\\<dots>. p k \\<in> \\<rat>\"\n    by auto\n  finally show ?thesis\n    using p_in_Rats[of k] by simp\nqed  \n\ntext \\<open>\n  The above recurrence has the characteristic polynomial $X^3 - X^2 - \\frac{1}{2} X - \\frac{1}{6}$\n  (which is exactly our \\<^term>\\<open>Q\\<close>), so we know that can now specify $x$, $y$, and $z$\n  more precisely: They are the roots of that polynomial (in unspecified order).\n\\<close>\n\nlemma xyz_eq: \"{#x, y, z#} = poly_roots [:-1/6, -1/2, -1, 1:]\"\nproof -\n  have \"image_mset f (mset_set {..<3}) = poly_roots Q\"\n    using mset_x_eq_poly_roots_Q .\n  also have \"image_mset f (mset_set {..<3}) = {#x, y, z#}\"\n    by (simp add: numeral_3_eq_3 lessThan_Suc f_def Multiset.union_ac)\n  also have \"Q = [:-1/6, -1/2, -1, 1:]\"\n    by (simp add: Q_altdef atMost_nat_numeral Polynomial.monom_altdef\n                  power3_eq_cube power2_eq_square)\n  finally show ?thesis .\nqed\n\ntext \\<open>\n  Using the rational root test, we can easily show that $x$, $y$, and $z$ are irrational.\n\\<close>\nlemma xyz_irrational: \"set_mset (poly_roots [:-1/6, -1/2, -1, 1::complex:]) \\<inter> \\<rat> = {}\"\nproof -\n  define p :: \"rat poly\" where \"p = [:-1/6, -1/2, -1, 1:]\"\n  have \"rational_root_test p = None\"\n    unfolding p_def by code_simp\n  hence \"\\<not>(\\<exists>x::rat. poly p x = 0)\"\n    by (rule rational_root_test)\n  hence \"\\<not>(\\<exists>x\\<in>\\<rat>. poly (map_poly of_rat p) x = (0 :: complex))\"\n    by (auto simp: Rats_def)\n  also have \"map_poly of_rat p = [:-1/6, -1/2, -1, 1 :: complex:]\"\n    by (simp add: p_def of_rat_minus of_rat_divide)\n  finally show ?thesis\n    by auto\nqed   \n    \n\ntext \\<open>\n  This polynomial is \\<^emph>\\<open>squarefree\\<close>, so these three roots are, in fact, unique (so that there are\n  indeed $3! = 6$ possible permutations).\n\\<close>\nlemma rsquarefree: \"rsquarefree [:-1/6, -1/2, -1, 1 :: complex:]\"\n  by (rule coprime_pderiv_imp_rsquarefree)\n     (auto simp: pderiv_pCons coprime_iff_gcd_eq_1 gcd_poly_code gcd_poly_code_def content_def\n                 primitive_part_def gcd_poly_code_aux_reduce pseudo_mod_def pseudo_divmod_def\n                 Let_def Polynomial.monom_altdef normalize_poly_def)\n\nlemma distinct_xyz: \"distinct [x, y, z]\"\n  by (rule rsquarefree_imp_distinct_roots[OF rsquarefree]) (simp_all add: xyz_eq)\n\n\ntext \\<open>\n  While these roots \\<^emph>\\<open>can\\<close> be written more explicitly in radical form, they are not very pleasant\n  to look at. We therefore only compute a few values of \\<open>p\\<close> just for fun:\n\\<close>\nlemma \"p 4 = 25 / 6\" and \"p 5 = 6\" and \"p 10 = 15539 / 432\"\n  by (simp_all add: p_recurrence''')\n\ntext \\<open>\n  Lastly, let us (informally) examine the asymptotics of this problem.\n\n  Two of the roots have a norm of roughly $\\beta \\approx 0.341$, while the remaining root \n  \\<open>\\<alpha>\\<close> is roughly 1.431. Consequently, $x^n + y^n + z^n$ is asymptotically equivalent to $\\alpha^n$,\n  with the error being bounded by $2\\cdot \\beta^n$ and therefore goes to 0 very quickly.\n\n  For $p(10) = \\frac{15539}{432} \\approx 35.97$, for instance, this approximation is correct\n  up to 6 decimals (a relative error of about 0.0001\\,\\%).\n\\<close>\n\nend\n\n\ntext \\<open>\n  To really emphasise that the above puzzle has a solution and the locale is not `vacuous',\n  here is an interpretation of the locale using the existence theorem from before:\n\\<close>\nnotepad\nbegin\n  define f :: \"nat \\<Rightarrow> complex\" where \"f = (\\<lambda>k. [1,2,3] ! (k - 1))\"\n  obtain Root :: \"nat \\<Rightarrow> complex\" where Root: \"\\<And>k. k \\<in> {1..3} \\<Longrightarrow> (\\<Sum>i<3. Root i ^ k) = f k\"\n    using power_sum_puzzle_has_solution[of 3 f] by metis\n  define x y z where \"x = Root 0\" \"y = Root 1\" \"z = Root 2\"\n  have \"x + y + z = 1\" and \"x^2 + y^2 + z^2 = 2\" and \"x^3 + y^3 + z^3 = 3\"\n    using Root[of 1] Root[of 2] Root[of 3] by (simp_all add: eval_nat_numeral x_y_z_def f_def)\n  then interpret power_sum_puzzle_example x y z\n    by unfold_locales\n  have \"p 5 = 6\"\n    by (simp add: p_recurrence''')\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/Power_Sum_Polynomials/Power_Sum_Puzzle.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.857768094082276, "lm_q2_score": 0.867035763237924, "lm_q1q2_score": 0.7437156141337655}}
{"text": "(*  Title:      HOL/ex/Sqrt.thy\n    Author:     Markus Wenzel, Tobias Nipkow, TU Muenchen\n*)\n\nsection \\<open>Square roots of primes are irrational\\<close>\n\ntheory Sqrt\nimports Complex_Main \"HOL-Computational_Algebra.Primes\"\nbegin\n\ntext \\<open>The square root of any prime number (including 2) is irrational.\\<close>\n\ntheorem sqrt_prime_irrational:\n  assumes \"prime (p::nat)\"\n  shows \"sqrt p \\<notin> \\<rat>\"\nproof\n  from \\<open>prime p\\<close> have p: \"1 < p\" by (simp add: prime_nat_iff)\n  assume \"sqrt p \\<in> \\<rat>\"\n  then obtain m n :: nat where\n      n: \"n \\<noteq> 0\" 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\"\n      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 show ?thesis using of_nat_eq_iff by blast\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_nat)\n    then obtain k where \"m = p * k\" ..\n    with eq have \"p * n\\<^sup>2 = p\\<^sup>2 * k\\<^sup>2\" by (auto simp add: power2_eq_square ac_simps)\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_nat)\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\n\nsubsection \\<open>Variations\\<close>\n\ntext \\<open>\n  Here is an alternative version of the main proof, using mostly\n  linear forward-reasoning.  While this results in less top-down\n  structure, it is probably closer to proofs seen in mathematics.\n\\<close>\n\ntheorem\n  assumes \"prime (p::nat)\"\n  shows \"sqrt p \\<notin> \\<rat>\"\nproof\n  from \\<open>prime p\\<close> have p: \"1 < p\" by (simp add: prime_nat_iff)\n  assume \"sqrt p \\<in> \\<rat>\"\n  then obtain m n :: nat where\n      n: \"n \\<noteq> 0\" 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\"\n    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\" using of_nat_eq_iff by blast\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_nat)\n  then obtain k where \"m = p * k\" ..\n  with eq have \"p * n\\<^sup>2 = p\\<^sup>2 * k\\<^sup>2\" by (auto simp add: power2_eq_square ac_simps)\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_nat)\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>Another old chestnut, which is a consequence of the irrationality of 2.\\<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\n  assume \"sqrt 2 powr sqrt 2 \\<in> \\<rat>\"\n  then have \"?P (sqrt 2) (sqrt 2)\"\n    by (metis sqrt_2_not_rat)\n  then show ?thesis by blast\nnext\n  assume 1: \"sqrt 2 powr sqrt 2 \\<notin> \\<rat>\"\n  have \"(sqrt 2 powr sqrt 2) powr sqrt 2 = 2\"\n    using powr_realpow [of _ 2]\n    by (simp add: powr_powr power2_eq_square [symmetric])\n  then have \"?P (sqrt 2 powr sqrt 2) (sqrt 2)\"\n    by (metis 1 Rats_number_of sqrt_2_not_rat)\n  then show ?thesis by blast\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/Sqrt.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424528443251, "lm_q2_score": 0.8791467627598857, "lm_q1q2_score": 0.7437075688992457}}
{"text": "section \\<open>Classifying Markov Chain States\\<close>\n\ntheory Classifying_Markov_Chain_States\n  imports\n    \"HOL-Computational_Algebra.Group_Closure\"\n    Discrete_Time_Markov_Chain\nbegin\n\nlemma eventually_mult_Gcd:\n  fixes S :: \"nat set\"\n  assumes S: \"\\<And>s t. s \\<in> S \\<Longrightarrow> t \\<in> S \\<Longrightarrow> s + t \\<in> S\"\n  assumes s: \"s \\<in> S\" \"s > 0\"\n  shows \"eventually (\\<lambda>m. m * Gcd S \\<in> S) sequentially\"\nproof -\n  define T where \"T = insert 0 (int ` S)\"\n  with s S have \"int s \\<in> T\" \"0 \\<in> T\" and T: \"r \\<in> T \\<Longrightarrow> t \\<in> T \\<Longrightarrow> r + t \\<in> T\" for r t\n    by (auto simp del: of_nat_add simp add: of_nat_add [symmetric])\n  have \"Gcd T \\<in> group_closure T\"\n    by (rule Gcd_in_group_closure)\n  also have \"group_closure T = {s - t | s t. s \\<in> T \\<and> t \\<in> T}\"\n  proof (auto intro: group_closure.base group_closure.diff)\n    fix x assume \"x \\<in> group_closure T\"\n    then show \"\\<exists>s t. x = s - t \\<and> s \\<in> T \\<and> t \\<in> T\"\n    proof induction\n      case (base x) with \\<open>0 \\<in> T\\<close> show ?case\n        apply (rule_tac x=x in exI)\n        apply (rule_tac x=0 in exI)\n        apply auto\n        done\n    next\n      case (diff x y)\n      then obtain a b c d where\n        \"a \\<in> T\" \"b \\<in> T\" \"x = a - b\"\n        \"c \\<in> T\" \"d \\<in> T\" \"y = c - d\"\n        by auto\n      then show ?case\n        apply (rule_tac x=\"a + d\" in exI)\n        apply (rule_tac x=\"b + c\" in exI)\n        apply (auto intro: T)\n        done\n    qed\n  qed\n  finally obtain s' t' :: int\n    where \"s' \\<in> T\" \"t' \\<in> T\" \"Gcd T = s' - t'\"\n    by blast\n  moreover define s and t where \"s = nat s'\" and \"t = nat t'\"\n  moreover have \"int (Gcd S) = - int t \\<longleftrightarrow> S \\<subseteq> {0} \\<and> t = 0\"\n    by auto (metis Gcd_dvd_nat dvd_0_right dvd_antisym nat_int nat_zminus_int) \n  ultimately have \n    st: \"s = 0 \\<or> s \\<in> S\" \"t = 0 \\<or> t \\<in> S\" and Gcd_S: \"Gcd S = s - t\"\n    using T_def by safe simp_all\n  with s\n  have \"t < s\"\n    by (rule_tac ccontr) auto\n\n  { fix s n have \"0 < n \\<Longrightarrow> s \\<in> S \\<Longrightarrow> n * s \\<in> S\"\n    proof (induct n)\n      case (Suc n) then show ?case\n        by (cases n) (auto intro: S)\n    qed simp }\n  note cmult_S = this\n\n  show ?thesis\n    unfolding eventually_sequentially\n  proof cases\n    assume \"s = 0 \\<or> t = 0\"\n    with st Gcd_S s have *: \"Gcd S \\<in> S\"\n      by (auto simp: int_eq_iff)\n    then show \"\\<exists>N. \\<forall>n\\<ge>N. n * Gcd S \\<in> S\" by (auto intro!: exI[of _ 1] cmult_S)\n  next\n    assume \"\\<not> (s = 0 \\<or> t = 0)\"\n    with st have \"s \\<in> S\" \"t \\<in> S\" \"t \\<noteq> 0\" by auto\n    then have \"Gcd S dvd t\" by auto\n    then obtain a where a: \"t = Gcd S * a\" ..\n    with \\<open>t \\<noteq> 0\\<close> have \"0 < a\" by auto\n\n    show \"\\<exists>N. \\<forall>n\\<ge>N. n * Gcd S \\<in> S\"\n    proof (safe intro!: exI[of _ \"a * a\"])\n      fix n\n      define m where \"m = (n - a * a) div a\"\n      define r where \"r = (n - a * a) mod a\"\n      with \\<open>0 < a\\<close> have \"r < a\" by simp\n      moreover define am where \"am = a + m\"\n      ultimately have \"r < am\" by simp\n      assume \"a * a \\<le> n\" then have n: \"n = a * a + (m * a + r)\"\n        unfolding m_def r_def by simp\n      have \"n * Gcd S = am * t + r * Gcd S\"\n        unfolding n a by (simp add: field_simps am_def)\n      also have \"\\<dots> = r * s + (am - r) * t\"\n        unfolding \\<open>Gcd S = s - t\\<close>\n        using \\<open>t < s\\<close> \\<open>r < am\\<close> by (simp add: field_simps diff_mult_distrib2)\n      also have \"\\<dots> \\<in> S\"\n        using \\<open>s \\<in> S\\<close> \\<open>t \\<in> S\\<close> \\<open>r < am\\<close>\n        by (cases \"r = 0\") (auto intro!: cmult_S S)\n      finally show \"n * Gcd S \\<in> S\" .\n    qed\n  qed\nqed\n\ncontext MC_syntax\nbegin\n\nsubsection \\<open>Expected number of visits\\<close>\n\ndefinition \"G s t = (\\<integral>\\<^sup>+\\<omega>. scount (HLD {t}) (s ## \\<omega>) \\<partial>T s)\"\n\nlemma G_eq: \"G s t = (\\<integral>\\<^sup>+\\<omega>. emeasure (count_space UNIV) {i. (s ## \\<omega>) !! i = t} \\<partial>T s)\"\n  by (simp add: G_def scount_eq_emeasure HLD_iff)\n\ndefinition \"p s t n = \\<P>(\\<omega> in T s. (s ## \\<omega>) !! n = t)\"\n\ndefinition \"gf_G s t z = (\\<Sum>n. p s t n *\\<^sub>R z ^ n)\"\n\ndefinition \"convergence_G s t z \\<longleftrightarrow> summable (\\<lambda>n. p s t n * norm z ^ n)\"\n\nlemma p_nonneg[simp]: \"0 \\<le> p x y n\"\n  by (simp add: p_def)\n\nlemma p_le_1: \"p x y n \\<le> 1\"\n  by (simp add: p_def)\n\nlemma p_x_x_0[simp]: \"p x x 0 = 1\"\n  by (simp add: p_def T.prob_space del: space_T)\n\nlemma p_0: \"p x y 0 = (if x = y then 1 else 0)\"\n  by (simp add: p_def T.prob_space del: space_T)\n\nlemma p_in_reachable: assumes \"(x, y) \\<notin> (SIGMA x:UNIV. K x)\\<^sup>*\" shows \"p x y n = 0\"\n  unfolding p_def\nproof (rule T.prob_eq_0_AE)\n  from AE_T_reachable show \"AE \\<omega> in T x. (x ## \\<omega>) !! n \\<noteq> y\"\n  proof eventually_elim\n    fix \\<omega> assume \"alw (HLD ((SIGMA \\<omega>:UNIV. K \\<omega>)\\<^sup>* `` {x})) \\<omega>\"\n    then have \"alw (HLD (- {y})) \\<omega>\"\n      using assms by (auto intro: alw_mono simp: HLD_iff)\n    then show \"(x ## \\<omega>) !! n \\<noteq> y\"\n      using assms by (cases n) (auto simp: alw_HLD_iff_streams streams_iff_snth)\n  qed\nqed\n\nlemma p_Suc: \"ennreal (p x y (Suc n)) = (\\<integral>\\<^sup>+ w. p w y n \\<partial>K x)\"\n  unfolding p_def T.emeasure_eq_measure[symmetric] by (subst emeasure_Collect_T) simp_all\n\nlemma p_Suc':\n  \"p x y (Suc n) = (\\<integral>x'. p x' y n \\<partial>K x)\"\n  using p_Suc[of x y n]\n  by (subst (asm) nn_integral_eq_integral)\n     (auto simp: p_le_1 intro!: measure_pmf.integrable_const_bound[where B=1])\n\nlemma p_add: \"p x y (n + m) = (\\<integral>\\<^sup>+ w. p x w n * p w y m \\<partial>count_space UNIV)\"\nproof (induction n arbitrary: x)\n  case 0\n  have [simp]: \"\\<And>w. (if x = w then 1 else 0) * p w y m = ennreal (p x y m) * indicator {x} w\"\n    by auto\n  show ?case\n    by (simp add: p_0 one_ennreal_def[symmetric] max_def)\nnext\n  case (Suc n)\n  define X where \"X = (SIGMA x:UNIV. K x)\\<^sup>* `` K x\"\n  then have X: \"countable X\"\n    by (blast intro: countable_Image countable_reachable countable_set_pmf)\n\n  then interpret X: sigma_finite_measure \"count_space X\"\n    by (rule sigma_finite_measure_count_space_countable)\n  interpret XK: pair_sigma_finite \"K x\" \"count_space X\"\n    by unfold_locales\n\n  have \"ennreal (p x y (Suc n + m)) = (\\<integral>\\<^sup>+t. (\\<integral>\\<^sup>+w. p t w n * p w y m \\<partial>count_space UNIV) \\<partial>K x)\"\n    by (simp add: p_Suc Suc)\n  also have \"\\<dots> = (\\<integral>\\<^sup>+t. (\\<integral>\\<^sup>+w. ennreal (p t w n * p w y m) * indicator X w \\<partial>count_space UNIV) \\<partial>K x)\"\n    by (auto intro!: nn_integral_cong_AE simp: AE_measure_pmf_iff AE_count_space Image_iff p_in_reachable X_def             split: split_indicator)\n  also have \"\\<dots> = (\\<integral>\\<^sup>+t. (\\<integral>\\<^sup>+w. p t w n * p w y m \\<partial>count_space X) \\<partial>K x)\"\n    by (subst nn_integral_restrict_space[symmetric]) (simp_all add: restrict_count_space)\n  also have \"\\<dots> = (\\<integral>\\<^sup>+w. (\\<integral>\\<^sup>+t. p t w n * p w y m \\<partial>K x) \\<partial>count_space X)\"\n    apply (rule XK.Fubini'[symmetric])\n    unfolding measurable_split_conv\n    apply (rule measurable_compose_countable'[OF _ measurable_snd X])\n    apply (rule measurable_compose[OF measurable_fst])\n    apply simp\n    done\n  also have \"\\<dots> = (\\<integral>\\<^sup>+w. (\\<integral>\\<^sup>+t. ennreal (p t w n * p w y m) * indicator X w \\<partial>K x) \\<partial>count_space UNIV)\"\n    by (simp add: nn_integral_restrict_space[symmetric] restrict_count_space nn_integral_multc)\n  also have \"\\<dots> = (\\<integral>\\<^sup>+w. (\\<integral>\\<^sup>+t. ennreal (p t w n * p w y m) \\<partial>K x) \\<partial>count_space UNIV)\"\n    by (auto intro!: nn_integral_cong_AE simp: AE_measure_pmf_iff AE_count_space Image_iff p_in_reachable X_def             split: split_indicator)\n  also have \"\\<dots> = (\\<integral>\\<^sup>+w. (\\<integral>\\<^sup>+t. p t w n \\<partial>K x) * p w y m \\<partial>count_space UNIV)\"\n    by (simp add: nn_integral_multc[symmetric] ennreal_mult)\n  finally show ?case\n    by (simp add: ennreal_mult p_Suc)\nqed\n\nlemma prob_reachable_le:\n  assumes [simp]: \"m \\<le> n\"\n  shows \"p x y m * p y w (n - m) \\<le> p x w n\"\nproof -\n  have \"p x y m * p y w (n - m) = (\\<integral>\\<^sup>+y'. ennreal (p x y m * p y w (n - m)) * indicator {y} y' \\<partial>count_space UNIV)\"\n    by simp\n  also have \"\\<dots> \\<le> p x w (m + (n - m))\"\n    by (subst p_add)\n       (auto intro!: nn_integral_mono split: split_indicator simp del: nn_integral_indicator_singleton)\n  finally show ?thesis\n    by simp\nqed\n\nlemma G_eq_suminf: \"G x y = (\\<Sum>i. ennreal (p x y i))\"\nproof -\n  have *: \"\\<And>i \\<omega>. indicator {\\<omega> \\<in> space S. (x ## \\<omega>) !! i = y} \\<omega> = indicator {i. (x ## \\<omega>) !! i = y} i\"\n    by (auto simp: space_stream_space split: split_indicator)\n\n  have \"G x y = (\\<integral>\\<^sup>+ \\<omega>. (\\<Sum>i. indicator {\\<omega>\\<in>space (T x). (x ## \\<omega>) !! i = y} \\<omega>) \\<partial>T x)\"\n    unfolding G_eq by (simp add: nn_integral_count_space_nat[symmetric] *)\n  also have \"\\<dots> = (\\<Sum>i. ennreal (p x y i))\"\n    by (simp add: T.emeasure_eq_measure[symmetric] p_def nn_integral_suminf)\n  finally show ?thesis .\nqed\n\nlemma G_eq_real_suminf:\n  \"convergence_G x y (1::real) \\<Longrightarrow> G x y = ennreal (\\<Sum>i. p x y i)\"\n  unfolding G_eq_suminf\n  by (intro suminf_ennreal ennreal_suminf_neq_top p_nonneg)\n     (auto simp: convergence_G_def p_def)\n\nlemma convergence_norm_G:\n  \"convergence_G x y z \\<Longrightarrow> summable (\\<lambda>n. p x y n * norm z ^ n)\"\n  unfolding convergence_G_def .\n\nlemma convergence_G:\n  \"convergence_G x y (z::'a::{banach, real_normed_div_algebra}) \\<Longrightarrow> summable (\\<lambda>n. p x y n *\\<^sub>R z ^ n)\"\n  unfolding convergence_G_def\n  by (rule summable_norm_cancel) (simp add: abs_mult norm_power)\n\nlemma convergence_G_less_1:\n  fixes z :: \"_ :: {banach, real_normed_field}\"\n  assumes z: \"norm z < 1\" shows \"convergence_G x y z\"\n  unfolding convergence_G_def\nproof (rule summable_comparison_test)\n  have \"\\<And>n. p x y n * norm (z ^ n) \\<le> 1 * norm (z ^ n)\"\n    by (intro mult_right_mono p_le_1) simp_all\n  then show \"\\<exists>N. \\<forall>n\\<ge>N. norm (p x y n * norm z ^ n) \\<le> norm z ^ n\"\n    by (simp add: norm_power)\nqed (simp add: z summable_geometric)\n\nlemma lim_gf_G: \"((\\<lambda>z. ennreal (gf_G x y z)) \\<longlongrightarrow> G x y) (at_left (1::real))\"\n  unfolding gf_G_def G_eq_suminf real_scaleR_def\n  by (intro power_series_tendsto_at_left p_nonneg p_le_1 summable_power_series)\n\nsubsection \\<open>Reachability probability\\<close>\n\ndefinition \"u x y n = \\<P>(\\<omega> in T x. ev_at (HLD {y}) n \\<omega>)\"\n\ndefinition \"U s t = \\<P>(\\<omega> in T s. ev (HLD {t}) \\<omega>)\"\n\ndefinition \"gf_U x y z = (\\<Sum>n. u x y n *\\<^sub>R z ^ Suc n)\"\n\ndefinition \"f x y n = \\<P>(\\<omega> in T x. ev_at (HLD {y}) n (x ## \\<omega>))\"\n\ndefinition \"F s t = \\<P>(\\<omega> in T s. ev (HLD {t}) (s ## \\<omega>))\"\n\ndefinition \"gf_F x y z = (\\<Sum>n. f x y n * z ^ n)\"\n\nlemma f_Suc: \"x \\<noteq> y \\<Longrightarrow> f x y (Suc n) = u x y n\"\n  by (simp add: u_def f_def)\n\nlemma f_Suc_eq: \"f x x (Suc n) = 0\"\n  by (simp add: f_def)\n\n\n\nlemma shows u_nonneg: \"0 \\<le> u x y n\" and u_le_1: \"u x y n \\<le> 1\"\n  by (simp_all add: u_def)\n\nlemma shows f_nonneg: \"0 \\<le> f x y n\" and f_le_1: \"f x y n \\<le> 1\"\n  by (simp_all add: f_def)\n\nlemma U_nonneg[simp]: \"0 \\<le> U x y\"\n  by (simp add: U_def)\n\nlemma U_le_1: \"U s t \\<le> 1\"\n  by (auto simp add: U_def intro!: antisym)\n\nlemma U_cases: \"U s s = 1 \\<or> U s s < 1\"\n  by (auto simp add: U_def intro!: antisym)\n\nlemma u_sums_U: \"u x y sums U x y\"\n  unfolding u_def[abs_def] U_def ev_iff_ev_at by (intro T.prob_sums) (auto intro: ev_at_unique)\n\nlemma gf_U_eq_U: \"gf_U x y 1 = U x y\"\n  using u_sums_U[THEN sums_unique] by (simp add: gf_U_def U_def)\n\nlemma f_sums_F: \"f x y sums F x y\"\n  unfolding f_def[abs_def] F_def ev_iff_ev_at\n  by (intro T.prob_sums) (auto intro: ev_at_unique)\n\nlemma F_nonneg[simp]: \"0 \\<le> F x y\"\n  by (auto simp: F_def)\n\nlemma F_le_1: \"F x y \\<le> 1\"\n  by (simp add: F_def)\n\nlemma gf_F_eq_F: \"gf_F x y 1 = F x y\"\n  using f_sums_F[THEN sums_unique] by (simp add: gf_F_def F_def)\n\nlemma gf_F_le_1:\n  fixes z :: real\n  assumes z: \"0 \\<le> z\" \"z \\<le> 1\"\n  shows \"gf_F x y z \\<le> 1\"\nproof -\n  have \"gf_F x y z \\<le> gf_F x y 1\"\n    using z unfolding gf_F_def\n    by (intro suminf_le[OF _ summable_comparison_test[OF _ sums_summable[OF f_sums_F[of x y]]]] mult_left_mono allI f_nonneg)\n       (simp_all add: power_le_one f_nonneg mult_right_le_one_le f_le_1 sums_summable[OF f_sums_F[of x y]])\n  also have \"\\<dots> \\<le> 1\"\n    by (simp add: gf_F_eq_F F_def)\n  finally show ?thesis .\nqed\n\nlemma u_le_p: \"u x y n \\<le> p x y (Suc n)\"\n  unfolding u_def p_def by (auto intro!: T.finite_measure_mono dest: ev_at_HLD_imp_snth)\n\nlemma f_le_p: \"f x y n \\<le> p x y n\"\n  unfolding f_def p_def by (auto intro!: T.finite_measure_mono dest: ev_at_HLD_imp_snth)\n\n\n\nlemma convergence_norm_F:\n  fixes z :: \"_ :: real_normed_div_algebra\"\n  assumes z: \"convergence_G x y z\"\n  shows \"summable (\\<lambda>n. f x y n * norm z ^ n)\"\n  using convergence_norm_G[OF z]\n  by (rule summable_comparison_test[rotated])\n     (auto simp add: f_nonneg abs_mult intro!: exI[of _ 0] mult_right_mono f_le_p)\n\nlemma gf_G_nonneg:\n  fixes z :: real\n  shows \"0 \\<le> z \\<Longrightarrow> z < 1 \\<Longrightarrow> 0 \\<le> gf_G x y z\"\n  unfolding gf_G_def\n  by (intro suminf_nonneg convergence_G convergence_G_less_1) simp_all\n\nlemma gf_F_nonneg:\n  fixes z :: real\n  shows \"0 \\<le> z \\<Longrightarrow> z < 1 \\<Longrightarrow> 0 \\<le> gf_F x y z\"\n  unfolding gf_F_def\n  using convergence_norm_F[OF convergence_G_less_1, of z x y]\n  by (intro suminf_nonneg) (simp_all add: f_nonneg)\n\nlemma convergence_U:\n  fixes z :: \"_ :: banach\"\n  shows \"convergence_G x y z \\<Longrightarrow> summable (\\<lambda>n. u x y n * z ^ Suc n)\"\n  by (rule summable_norm_cancel)\n     (auto simp add: abs_mult u_nonneg power_abs dest!: convergence_norm_U)\n\nlemma p_eq_sum_p_u: \"p x y (Suc n) = (\\<Sum>i\\<le>n. p y y (n - i) * u x y i)\"\nproof -\n  have \"\\<And>\\<omega>. \\<omega> !! n = y \\<Longrightarrow> (\\<exists>i. i \\<le> n \\<and> ev_at (HLD {y}) i \\<omega>)\"\n  proof (induction n)\n    case (Suc n)\n    then obtain i where \"i \\<le> n\" \"ev_at (HLD {y}) i (stl \\<omega>)\"\n      by auto\n    then show ?case\n      by (auto intro!: exI[of _ \"if HLD {y} \\<omega> then 0 else Suc i\"])\n  qed (simp add: HLD_iff)\n  then have \"p x y (Suc n) = (\\<Sum>i\\<le>n. \\<P>(\\<omega> in T x. ev_at (HLD {y}) i \\<omega> \\<and> \\<omega> !! n = y))\"\n    unfolding p_def by (intro T.prob_sum) (auto intro: ev_at_unique)\n  also have \"\\<dots> = (\\<Sum>i\\<le>n. p y y (n - i) * u x y i)\"\n  proof (intro sum.cong refl)\n    fix i assume i: \"i \\<in> {.. n}\"\n    then have \"\\<And>\\<omega>. (Suc i \\<le> n \\<longrightarrow> \\<omega> !! (n - Suc i) = y) \\<longleftrightarrow> ((y ## \\<omega>) !! (n - i) = y)\"\n      by (auto simp: Stream_snth diff_Suc split: nat.split)\n    from i have \"i \\<le> n\" by auto\n    then have \"\\<P>(\\<omega> in T x. ev_at (HLD {y}) i \\<omega> \\<and> \\<omega> !! n = y) =\n      (\\<integral>\\<omega>'. \\<P>(\\<omega> in T y. (y ## \\<omega>) !! (n - i) = y) *\n        indicator {\\<omega>'\\<in>space (T x). ev_at (HLD {y}) i \\<omega>' } \\<omega>' \\<partial>T x)\"\n      by (subst prob_T_split[where n=\"Suc i\"])\n         (auto simp: ev_at_shift ev_at_HLD_single_imp_snth shift_snth diff_Suc\n               split: split_indicator nat.split intro!: Bochner_Integration.integral_cong arg_cong2[where f=measure]\n               simp del: stake.simps integral_mult_right_zero)\n    then show \"\\<P>(\\<omega> in T x. ev_at (HLD {y}) i \\<omega> \\<and> \\<omega> !! n = y) = p y y (n - i) * u x y i\"\n      by (simp add: p_def u_def)\n  qed\n  finally show ?thesis .\nqed\n\nlemma p_eq_sum_p_f: \"p x y n = (\\<Sum>i\\<le>n. p y y (n - i) * f x y i)\"\n  by (cases n)\n     (simp_all del: sum.atMost_Suc\n               add: f_0 p_0 p_eq_sum_p_u atMost_Suc_eq_insert_0 zero_notin_Suc_image sum.reindex\n                    f_Suc f_Suc_eq)\n\nlemma gf_G_eq_gf_F:\n  assumes z: \"norm z < 1\"\n  shows \"gf_G x y z = gf_F x y z * gf_G y y z\"\nproof -\n  have \"gf_G x y z = (\\<Sum>n. \\<Sum>i\\<le>n. p y y (n - i) * f x y i * z^n)\"\n    by (simp add: gf_G_def p_eq_sum_p_f[of x y] sum_distrib_right)\n  also have \"\\<dots> = (\\<Sum>n. \\<Sum>i\\<le>n. (f x y i * z^i) * (p y y (n - i) * z^(n - i)))\"\n    by (intro arg_cong[where f=suminf] sum.cong ext atLeast0AtMost[symmetric])\n       (simp_all add: power_add[symmetric])\n  also have \"\\<dots> = (\\<Sum>n. f x y n * z^n) * (\\<Sum>n. p y y n * z^n)\"\n    using convergence_norm_F[OF convergence_G_less_1[OF z]] convergence_norm_G[OF convergence_G_less_1[OF z]]\n    by (intro Cauchy_product[symmetric]) (auto simp: f_nonneg abs_mult power_abs)\n  also have \"\\<dots> = gf_F x y z * gf_G y y z\"\n    by (simp add: gf_F_def gf_G_def)\n  finally show ?thesis .\nqed\n\nlemma gf_G_eq_gf_U:\n  fixes z :: \"'z :: {banach, real_normed_field}\"\n  assumes z: \"convergence_G x x z\"\n  shows \"gf_G x x z = 1 / (1 - gf_U x x z)\" \"gf_U x x z \\<noteq> 1\"\nproof -\n  { fix n\n    have \"p x x (Suc n) *\\<^sub>R z^Suc n = (\\<Sum>i\\<le>n. (p x x (n - i) * u x x i) *\\<^sub>R z^Suc n)\"\n      unfolding scaleR_sum_left[symmetric] by (simp add: p_eq_sum_p_u)\n    also have \"\\<dots> = (\\<Sum>i\\<le>n. (u x x i *\\<^sub>R z^Suc i) * (p x x (n - i) *\\<^sub>R z^(n - i)))\"\n      by (intro sum.cong refl) (simp add: field_simps power_diff cong: disj_cong)\n    finally have \"p x x (Suc n) *\\<^sub>R z^(Suc n) = (\\<Sum>i\\<le>n. (u x x i *\\<^sub>R z^Suc i) * (p x x (n - i) *\\<^sub>R z^(n - i)))\"\n      unfolding atLeast0AtMost . }\n  note gfs_Suc_eq = this\n\n  have \"gf_G x x z = 1 + (\\<Sum>n. p x x (Suc n) *\\<^sub>R z^(Suc n))\"\n    unfolding gf_G_def\n    by (subst suminf_split_initial_segment[OF convergence_G[OF z], of 1]) simp\n  also have \"\\<dots> = 1 + (\\<Sum>n. \\<Sum>i\\<le>n. (u x x i *\\<^sub>R z^Suc i) * (p x x (n - i) *\\<^sub>R z^(n - i)))\"\n    unfolding gfs_Suc_eq ..\n  also have \"\\<dots> = 1 + gf_U x x z * gf_G x x z\"\n    unfolding gf_U_def gf_G_def\n    by (subst Cauchy_product)\n       (auto simp: u_nonneg norm_power simp del: power_Suc\n             intro!: z convergence_norm_G convergence_norm_U)\n  finally show \"gf_G x x z = 1 / (1 - gf_U x x z)\" \"gf_U x x z \\<noteq> 1\"\n    apply -\n    apply (cases \"gf_U x x z = 1\")\n    apply (auto simp add: field_simps)\n    done\nqed\n\nlemma gf_U: \"(gf_U x y \\<longlongrightarrow> U x y) (at_left 1)\"\nproof -\n  have \"((\\<lambda>z. ennreal (\\<Sum>n. u x y n * z ^ n)) \\<longlongrightarrow> (\\<Sum>n. ennreal (u x y n))) (at_left 1)\"\n    using u_le_1 u_nonneg by (intro power_series_tendsto_at_left summable_power_series)\n  also have \"(\\<Sum>n. ennreal (u x y n)) = ennreal (suminf (u x y))\"\n    by (intro u_nonneg suminf_ennreal ennreal_suminf_neq_top sums_summable[OF u_sums_U])\n  also have \"suminf (u x y) = U x y\"\n    using u_sums_U by (rule sums_unique[symmetric])\n  finally have \"((\\<lambda>z. \\<Sum>n. u x y n * z ^ n) \\<longlongrightarrow> U x y) (at_left 1)\"\n    by (rule tendsto_ennrealD)\n       (auto simp: u_nonneg u_le_1 intro!: suminf_nonneg summable_power_series eventually_at_left_1)\n  then have \"((\\<lambda>z. z * (\\<Sum>n. u x y n * z ^ n)) \\<longlongrightarrow> 1 * U x y) (at_left 1)\"\n    by (intro tendsto_intros) simp\n  then have \"((\\<lambda>z. \\<Sum>n. u x y n * z ^ Suc n) \\<longlongrightarrow> 1 * U x y) (at_left 1)\"\n    apply (rule filterlim_cong[OF refl refl, THEN iffD1, rotated])\n    apply (rule eventually_at_left_1)\n    apply (subst suminf_mult[symmetric])\n    apply (auto intro!: summable_power_series u_le_1 u_nonneg)\n    apply (simp add: field_simps)\n    done\n  then show ?thesis\n    by (simp add: gf_U_def[abs_def] U_def)\nqed\n\nlemma gf_U_le_1: assumes z: \"0 < z\" \"z < 1\" shows \"gf_U x y z \\<le> (1::real)\"\nproof -\n  note u = u_sums_U[of x y, THEN sums_summable]\n  have \"gf_U x y z \\<le> gf_U x y 1\"\n    using z\n    unfolding gf_U_def real_scaleR_def\n    by (intro suminf_le allI mult_mono power_mono summable_comparison_test_ev[OF _ u] always_eventually)\n       (auto simp: u_nonneg intro!: mult_left_le mult_le_one power_le_one)\n  also have \"\\<dots> \\<le> 1\"\n    unfolding gf_U_eq_U by (rule U_le_1)\n  finally show ?thesis .\nqed\n\nlemma gf_F: \"(gf_F x y \\<longlongrightarrow> F x y) (at_left 1)\"\nproof -\n  have \"((\\<lambda>z. ennreal (\\<Sum>n. f x y n * z ^ n)) \\<longlongrightarrow> (\\<Sum>n. ennreal (f x y n))) (at_left 1)\"\n    using f_le_1 f_nonneg by (intro power_series_tendsto_at_left summable_power_series)\n  also have \"(\\<Sum>n. ennreal (f x y n)) = ennreal (suminf (f x y))\"\n    by (intro f_nonneg suminf_ennreal ennreal_suminf_neq_top sums_summable[OF f_sums_F])\n  also have \"suminf (f x y) = F x y\"\n    using f_sums_F by (rule sums_unique[symmetric])\n  finally have \"((\\<lambda>z. \\<Sum>n. f x y n * z ^ n) \\<longlongrightarrow> F x y) (at_left 1)\"\n    by (rule tendsto_ennrealD)\n       (auto simp: f_nonneg f_le_1 intro!: suminf_nonneg summable_power_series eventually_at_left_1)\n  then show ?thesis\n    by (simp add: gf_F_def[abs_def] F_def)\nqed\n\nlemma U_bounded: \"0 \\<le> U x y\" \"U x y \\<le> 1\"\n  unfolding U_def by simp_all\n\nsubsection \\<open>Recurrent states\\<close>\n\ndefinition recurrent :: \"'s \\<Rightarrow> bool\" where\n  \"recurrent s \\<longleftrightarrow> (AE \\<omega> in T s. ev (HLD {s}) \\<omega>)\"\n\nlemma recurrent_iff_U_eq_1: \"recurrent s \\<longleftrightarrow> U s s = 1\"\n    unfolding recurrent_def U_def by (subst T.prob_Collect_eq_1) simp_all\n\ndefinition \"H s t = \\<P>(\\<omega> in T s. alw (ev (HLD {t})) \\<omega>)\"\n\nlemma H_eq:\n  \"recurrent s \\<longleftrightarrow> H s s = 1\"\n  \"\\<not> recurrent s \\<longleftrightarrow> H s s = 0\"\n  \"H s t = U s t * H t t\"\nproof -\n  define H' where \"H' t n = {\\<omega>\\<in>space S. enat n \\<le> scount (HLD {t::'s}) \\<omega>}\" for t n\n  have [measurable]: \"\\<And>y n. H' y n \\<in> sets S\"\n    by (simp add: H'_def)\n  let ?H' = \"\\<lambda>s t n. measure (T s) (H' t n)\"\n  { fix x y :: 's and \\<omega>\n    have \"Suc 0 \\<le> scount (HLD {y}) \\<omega> \\<longleftrightarrow> ev (HLD {y}) \\<omega>\"\n      using scount_eq_0_iff[of \"HLD {y}\" \\<omega>]\n      by (cases \"scount (HLD {y}) \\<omega>\" rule: enat_coexhaust)\n         (auto simp: not_ev_iff[symmetric] eSuc_enat[symmetric] enat_0 HLD_iff[abs_def]) }\n  then have H'_1: \"\\<And>x y. ?H' x y 1 = U x y\"\n    unfolding H'_def U_def by simp\n\n  { fix n and x y :: 's\n    let ?U = \"(not (HLD {y}) suntil (HLD {y} aand nxt (\\<lambda>\\<omega>. enat n \\<le> scount (HLD {y}) \\<omega>)))\"\n    { fix \\<omega>\n      have \"enat (Suc n) \\<le> scount (HLD {y}) \\<omega> \\<longleftrightarrow> ?U \\<omega>\"\n      proof\n        assume \"enat (Suc n) \\<le> scount (HLD {y}) \\<omega>\"\n        with scount_eq_0_iff[of \"HLD {y}\" \\<omega>] have \"ev (HLD {y}) \\<omega>\" \"enat (Suc n) \\<le> scount (HLD {y}) \\<omega>\"\n          by (auto simp add: not_ev_iff[symmetric] eSuc_enat[symmetric])\n        then show \"?U \\<omega>\"\n          by (induction rule: ev_induct_strong)\n             (auto simp: scount_simps eSuc_enat[symmetric] intro: suntil.intros)\n      next\n        assume \"?U \\<omega>\" then show \"enat (Suc n) \\<le> scount (HLD {y}) \\<omega>\"\n          by induction (auto simp: scount_simps  eSuc_enat[symmetric])\n      qed }\n    then have \"emeasure (T x) (H' y (Suc n)) = emeasure (T x) {\\<omega>\\<in>space (T x). ?U \\<omega>}\"\n      by (simp add: H'_def)\n    also have \"\\<dots> = U x y * ?H' y y n\"\n      by (subst emeasure_suntil_HLD) (simp_all add: T.emeasure_eq_measure U_def H'_def ennreal_mult)\n    finally have \"?H' x y (Suc n) = U x y * ?H' y y n\"\n      by (simp add: T.emeasure_eq_measure) }\n  note H'_Suc = this\n\n  { fix m and x :: 's\n    have \"?H' x x (Suc m) = U x x^Suc m\"\n      using H'_1 H'_Suc by (induct m) auto }\n  note H'_eq = this\n\n  { fix x y\n    have \"?H' x y \\<longlonglongrightarrow> measure (T x) (\\<Inter>i. H' y i)\"\n      apply (rule T.finite_Lim_measure_decseq)\n      apply safe\n      apply simp\n      apply (auto simp add: decseq_Suc_iff subset_eq H'_def eSuc_enat[symmetric]\n                  intro: ile_eSuc order_trans)\n      done\n    also have \"(\\<Inter>i. H' y i) = {\\<omega>\\<in>space (T x). alw (ev (HLD {y})) \\<omega>}\"\n      by (auto simp: H'_def scount_infinite_iff[symmetric]) (metis Suc_ile_eq enat.exhaust neq_iff)\n    finally have \"?H' x y \\<longlonglongrightarrow> H x y\"\n      unfolding H_def . }\n  note H'_lim = this\n\n  from H'_lim[of s s, THEN LIMSEQ_Suc]\n  have \"(\\<lambda>n. U s s ^ Suc n) \\<longlonglongrightarrow> H s s\"\n    by (simp add: H'_eq)\n  then have lim_H: \"(\\<lambda>n. U s s ^ n) \\<longlonglongrightarrow> H s s\"\n    by (rule LIMSEQ_imp_Suc)\n\n  have \"U s s < 1 \\<Longrightarrow> (\\<lambda>n. U s s ^ n) \\<longlonglongrightarrow> 0\"\n    by (rule LIMSEQ_realpow_zero) (simp_all add: U_def)\n  with lim_H have \"U s s < 1 \\<Longrightarrow> H s s = 0\"\n    by (blast intro: LIMSEQ_unique)\n  moreover have \"U s s = 1 \\<Longrightarrow> (\\<lambda>n. U s s ^ n) \\<longlonglongrightarrow> 1\"\n    by simp\n  with lim_H have \"U s s = 1 \\<Longrightarrow> H s s = 1\"\n    by (blast intro: LIMSEQ_unique)\n  moreover note recurrent_iff_U_eq_1 U_cases\n  ultimately show \"recurrent s \\<longleftrightarrow> H s s = 1\" \"\\<not> recurrent s \\<longleftrightarrow> H s s = 0\"\n    by (metis one_neq_zero)+\n\n  from H'_lim[of s t, THEN LIMSEQ_Suc] H'_Suc[of s]\n  have \"(\\<lambda>n. U s t * ?H' t t n) \\<longlonglongrightarrow> H s t\"\n    by simp\n  moreover have \"(\\<lambda>n. U s t * ?H' t t n) \\<longlonglongrightarrow> U s t * H t t\"\n    by (intro tendsto_intros H'_lim)\n  ultimately show \"H s t = U s t * H t t\"\n    by (blast intro: LIMSEQ_unique)\nqed\n\nlemma recurrent_iff_G_infinite: \"recurrent x \\<longleftrightarrow> G x x = \\<infinity>\"\nproof -\n  have \"((\\<lambda>z. ennreal (gf_G x x z)) \\<longlongrightarrow> G x x) (at_left 1)\"\n    by (rule lim_gf_G)\n  then have G: \"((\\<lambda>z. ennreal (1 / (1 - gf_U x x z))) \\<longlongrightarrow> G x x) (at_left (1::real))\"\n    apply (rule filterlim_cong[OF refl refl, THEN iffD1, rotated])\n    apply (rule eventually_at_left_1)\n    apply (subst gf_G_eq_gf_U)\n    apply (rule convergence_G_less_1)\n    apply simp\n    apply simp\n    done\n\n  { fix z :: real assume z: \"0 < z\" \"z < 1\"\n    have 1: \"summable (u x x)\"\n      using u_sums_U by (rule sums_summable)\n    have \"gf_U x x z \\<noteq> 1\"\n      using gf_G_eq_gf_U[OF convergence_G_less_1[of z]] z by simp\n    moreover\n    have \"gf_U x x z \\<le> U x x\"\n      unfolding gf_U_def gf_U_eq_U[symmetric]\n      using z\n      by (intro suminf_le)\n         (auto simp add: 1 convergence_U convergence_G_less_1 u_nonneg simp del: power_Suc\n               intro!: mult_right_le_one_le power_le_one)\n    ultimately have \"gf_U x x z < 1\"\n      using U_bounded[of x x] by simp }\n  note strict = this\n\n  { assume \"U x x = 1\"\n    moreover have \"((\\<lambda>xa. 1 - gf_U x x xa :: real) \\<longlongrightarrow> 1 - U x x) (at_left 1)\"\n      by (intro tendsto_intros gf_U)\n    moreover have \"eventually (\\<lambda>z. gf_U x x z < 1) (at_left (1::real))\"\n      by (auto intro!: eventually_at_left_1 strict simp: \\<open>U x x = 1\\<close> gf_U_eq_U)\n    ultimately have \"((\\<lambda>z. ennreal (1 / (1 - gf_U x x z))) \\<longlongrightarrow> top) (at_left 1)\"\n      unfolding ennreal_tendsto_top_eq_at_top\n      by (intro LIM_at_top_divide[where a=1] tendsto_const zero_less_one)\n         (auto simp: field_simps)\n    with G have \"G x x = top\"\n      by (rule tendsto_unique[rotated]) simp }\n  moreover\n  { assume \"U x x < 1\"\n    then have \"((\\<lambda>xa. ennreal (1 / (1 - gf_U x x xa))) \\<longlongrightarrow> 1 / (1 - U x x)) (at_left 1)\"\n      by (intro tendsto_intros gf_U tendsto_ennrealI) simp\n    from tendsto_unique[OF _ G this] have \"G x x \\<noteq> \\<infinity>\"\n      by simp }\n  ultimately show ?thesis\n    using U_cases recurrent_iff_U_eq_1 by auto\nqed\n\ndefinition communicating :: \"('s \\<times> 's) set\" where\n  \"communicating = acc \\<inter> acc\\<inverse>\"\n\ndefinition essential_class :: \"'s set \\<Rightarrow> bool\" where\n  \"essential_class C \\<longleftrightarrow> C \\<in> UNIV // communicating \\<and> acc `` C \\<subseteq> C\"\n\nlemma accI_U:\n  assumes \"0 < U x y\" shows \"(x, y) \\<in> acc\"\nproof (rule ccontr)\n  assume *: \"(x, y) \\<notin> acc\"\n\n  { fix \\<omega> assume \"ev (HLD {y}) \\<omega>\" \"alw (HLD (acc `` {x})) \\<omega>\" from this * have False\n      by induction (auto simp: HLD_iff) }\n  with AE_T_reachable[of x] have \"U x y = 0\"\n    unfolding U_def by (intro T.prob_eq_0_AE) auto\n  with \\<open>0 < U x y\\<close> show False by auto\nqed\n\nlemma accD_pos:\n  assumes \"(x, y) \\<in> acc\"\n  shows \"\\<exists>n. 0 < p x y n\"\nusing assms proof induction\n  case base with T.prob_space[of x] show ?case\n    by (auto intro!: exI[of _ 0])\nnext\n  have [simp]: \"\\<And>x y. (if x = y then 1 else 0::real) = indicator {y} x\"\n    by simp\n  case (step w y)\n  then obtain n where \"0 < p x w n\" and \"0 < pmf (K w) y\"\n    by (auto simp: set_pmf_iff less_le)\n  then have \"0 < p x w n * pmf (K w) y\"\n    by (intro mult_pos_pos)\n  also have \"\\<dots> \\<le> p x w n * p w y (Suc 0)\"\n    by (simp add: p_Suc' p_0 pmf.rep_eq)\n  also have \"\\<dots> \\<le> p x y (Suc n)\"\n    using prob_reachable_le[of n \"Suc n\" x w y] by simp\n  finally show ?case ..\nqed\n\nlemma accI_pos: \"0 < p x y n \\<Longrightarrow> (x, y) \\<in> acc\"\nproof (induct n arbitrary: x)\n  case (Suc n)\n  then have less: \"0 < (\\<integral>x'. p x' y n \\<partial>K x)\"\n    by (simp add: p_Suc')\n  have \"\\<exists>x'\\<in>K x. 0 < p x' y n\"\n  proof (rule ccontr)\n    assume \"\\<not> ?thesis\"\n    then have \"AE x' in K x. p x' y n = 0\"\n      by (simp add: AE_measure_pmf_iff less_le)\n    then have \"(\\<integral>x'. p x' y n \\<partial>K x) = (\\<integral>x'. 0 \\<partial>K x)\"\n      by (intro integral_cong_AE) simp_all\n    with less show False by simp\n  qed\n  with Suc show ?case\n    by (auto intro: converse_rtrancl_into_rtrancl)\nqed (simp add: p_0 split: if_split_asm)\n\nlemma recurrent_iffI_communicating:\n  assumes \"(x, y) \\<in> communicating\"\n  shows \"recurrent x \\<longleftrightarrow> recurrent y\"\nproof -\n  from assms obtain n m where \"0 < p x y n\" \"0 < p y x m\"\n    by (force simp: communicating_def dest: accD_pos)\n  moreover\n  { fix x y n m assume \"0 < p x y n\" \"0 < p y x m\" \"G y y = \\<infinity>\"\n    then have \"\\<infinity> = ennreal (p x y n * p y x m) * G y y\"\n      by (auto intro: mult_pos_pos simp: ennreal_mult_top)\n    also have \"ennreal (p x y n * p y x m) * G y y = (\\<Sum>i. ennreal (p x y n * p y x m) * p y y i)\"\n      unfolding G_eq_suminf by (rule ennreal_suminf_cmult[symmetric])\n    also have \"\\<dots> \\<le> (\\<Sum>i. ennreal (p x x (n + i + m)))\"\n    proof (intro suminf_le allI)\n      fix i\n      have \"(p x y n * p y y ((n + i) - n)) * p y x ((n + i + m) - (n + i)) \\<le> p x y (n + i) * p y x ((n + i + m) - (n + i))\"\n        by (intro mult_right_mono prob_reachable_le) simp_all\n      also have \"\\<dots> \\<le> p x x (n + i + m)\"\n         by (intro prob_reachable_le) simp_all\n      finally show \"ennreal (p x y n * p y x m) * p y y i \\<le> ennreal (p x x (n + i + m))\"\n        by (simp add: ac_simps ennreal_mult'[symmetric])\n    qed auto\n    also have \"\\<dots> \\<le> (\\<Sum>i. ennreal (p x x (i + (n + m))))\"\n      by (simp add: ac_simps)\n    also have \"\\<dots> \\<le> (\\<Sum>i. ennreal (p x x i))\"\n      by (subst suminf_offset[of \"\\<lambda>i. ennreal (p x x i)\" \"n + m\"]) auto\n    also have \"\\<dots> \\<le> G x x\"\n      unfolding G_eq_suminf by (auto intro!: suminf_le_pos)\n    finally have \"G x x = \\<infinity>\"\n      by (simp add: top_unique) }\n  ultimately show ?thesis\n    using recurrent_iff_G_infinite by blast\nqed\n\nlemma recurrent_acc:\n  assumes \"recurrent x\" \"(x, y) \\<in> acc\"\n  shows \"U y x = 1\" \"H y x = 1\" \"recurrent y\" \"(x, y) \\<in> communicating\"\nproof -\n  { fix w y assume step: \"(x, w) \\<in> acc\" \"y \\<in> K w\" \"U w x = 1\" \"H w x = 1\" \"recurrent w\" \"x \\<noteq> y\"\n    have \"measure (K w) UNIV = U w x\"\n      using step measure_pmf.prob_space[of \"K w\"] by simp\n    also have \"\\<dots> = (\\<integral>v. indicator {x} v + U v x * indicator (- {x}) v \\<partial>K w)\"\n      unfolding U_def\n      by (subst prob_T)\n         (auto intro!: Bochner_Integration.integral_cong arg_cong2[where f=measure] AE_I2\n               simp: ev_Stream T.prob_eq_1 split: split_indicator)\n    also have \"\\<dots> = measure (K w) {x} + (\\<integral>v. U v x * indicator (- {x}) v \\<partial>K w)\"\n      by (subst Bochner_Integration.integral_add)\n         (auto intro!: measure_pmf.integrable_const_bound[where B=1]\n               simp: abs_mult mult_le_one U_bounded(2) measure_pmf.emeasure_eq_measure)\n    finally have \"measure (K w) UNIV - measure (K w) {x} = (\\<integral>v. U v x * indicator (- {x}) v \\<partial>K w)\"\n      by simp\n    also have \"measure (K w) UNIV - measure (K w) {x} = measure (K w) (UNIV - {x})\"\n      by (subst measure_pmf.finite_measure_Diff) auto\n    finally have \"0 = (\\<integral>v. indicator (- {x}) v \\<partial>K w) - (\\<integral>v. U v x * indicator (- {x}) v \\<partial>K w)\"\n      by (simp add: measure_pmf.emeasure_eq_measure Compl_eq_Diff_UNIV)\n    also have \"\\<dots> = (\\<integral>v. (1 - U v x) * indicator (- {x}) v \\<partial>K w)\"\n      by (subst Bochner_Integration.integral_diff[symmetric])\n         (auto intro!: measure_pmf.integrable_const_bound[where B=1] Bochner_Integration.integral_cong\n               simp: abs_mult mult_le_one U_bounded(2) split: split_indicator)\n    also have \"\\<dots> \\<ge> (\\<integral>v. (1 - U y x) * indicator {y} v \\<partial>K w)\" (is \"_ \\<ge> ?rhs\")\n      using \\<open>recurrent x\\<close>\n      by (intro integral_mono measure_pmf.integrable_const_bound[where B=1])\n         (auto simp: abs_mult mult_le_one U_bounded(2) recurrent_iff_U_eq_1 field_simps\n               split: split_indicator)\n    also (xtrans) have \"?rhs = (1 - U y x) * pmf (K w) y\"\n      by (simp add: measure_pmf.emeasure_eq_measure pmf.rep_eq)\n    finally have \"(1 - U y x) * pmf (K w) y = 0\"\n      by (auto intro!: antisym simp: U_bounded(2) mult_le_0_iff)\n    with \\<open>y \\<in> K w\\<close> have \"U y x = 1\"\n      by (simp add: set_pmf_iff)\n    then have \"U y x = 1\" \"H y x = 1\"\n      using H_eq(3)[of y x] H_eq(1)[of x] by (simp_all add: \\<open>recurrent x\\<close>)\n    then have \"(y, x) \\<in> acc\"\n      by (intro accI_U) auto\n    with step have \"(x, y) \\<in> communicating\"\n      by (auto simp add: communicating_def intro: rtrancl_trans)\n    with \\<open>recurrent x\\<close> have \"recurrent y\"\n      by (simp add: recurrent_iffI_communicating)\n    note this \\<open>U y x = 1\\<close> \\<open>H y x = 1\\<close> \\<open>(x, y) \\<in> communicating\\<close> }\n  note enabled = this\n\n  from \\<open>(x, y) \\<in> acc\\<close>\n  show \"U y x = 1\" \"H y x = 1\" \"recurrent y\" \"(x, y) \\<in> communicating\"\n  proof induction\n    case base then show \"U x x = 1\" \"H x x = 1\" \"recurrent x\" \"(x, x) \\<in> communicating\"\n      using \\<open>recurrent x\\<close> H_eq(1)[of x] by (auto simp: recurrent_iff_U_eq_1 communicating_def)\n  next\n    case (step w y)\n    with enabled[of w y] \\<open>recurrent x\\<close> H_eq(1)[of x]\n    have \"U y x = 1 \\<and> H y x = 1 \\<and> recurrent y \\<and> (x, y) \\<in> communicating\"\n      by (cases \"x = y\") (auto simp: recurrent_iff_U_eq_1 communicating_def)\n    then show \"U y x = 1\" \"H y x = 1\" \"recurrent y\" \"(x, y) \\<in> communicating\"\n      by auto\n  qed\nqed\n\nlemma equiv_communicating: \"equiv UNIV communicating\"\n  by (auto simp: equiv_def sym_def communicating_def refl_on_def trans_def)\n\nlemma recurrent_class:\n  assumes \"recurrent x\"\n  shows \"acc `` {x} = communicating `` {x}\"\n  using recurrent_acc(4)[OF \\<open>recurrent x\\<close>] by (auto simp: communicating_def)\n\nlemma irreduccible_recurrent_class:\n  assumes \"recurrent x\" shows \"acc `` {x} \\<in> UNIV // communicating\"\n  unfolding recurrent_class[OF \\<open>recurrent x\\<close>] by (rule quotientI) simp\n\nlemma essential_classI:\n  assumes C: \"C \\<in> UNIV // communicating\"\n  assumes eq: \"\\<And>x y. x \\<in> C \\<Longrightarrow> (x, y) \\<in> acc \\<Longrightarrow> y \\<in> C\"\n  shows \"essential_class C\"\n  by (auto simp: essential_class_def intro: C) (metis eq)\n\nlemma essential_recurrent_class:\n  assumes \"recurrent x\" shows \"essential_class (communicating `` {x})\"\n  unfolding recurrent_class[OF \\<open>recurrent x\\<close>, symmetric]\n  apply (rule essential_classI)\n  apply (rule irreduccible_recurrent_class[OF assms])\n  apply (auto simp: communicating_def)\n  done\n\nlemma essential_classD2:\n  \"essential_class C \\<Longrightarrow> x \\<in> C \\<Longrightarrow> (x, y) \\<in> acc \\<Longrightarrow> y \\<in> C\"\n  unfolding essential_class_def by auto\n\nlemma essential_classD3:\n  \"essential_class C \\<Longrightarrow> x \\<in> C \\<Longrightarrow> y \\<in> C \\<Longrightarrow> (x, y) \\<in> communicating\"\n  unfolding essential_class_def\n  by (auto elim!: quotientE simp: communicating_def)\n\nlemma AE_acc:\n  shows \"AE \\<omega> in T x. \\<forall>m. (x, (x ## \\<omega>) !! m) \\<in> acc\"\n  using AE_T_reachable\n  by eventually_elim (auto simp: alw_HLD_iff_streams streams_iff_snth Stream_snth split: nat.splits)\n\nlemma finite_essential_class_imp_recurrent:\n  assumes C: \"essential_class C\" \"finite C\" and x: \"x \\<in> C\"\n  shows \"recurrent x\"\nproof -\n  have \"AE \\<omega> in T x. \\<exists>y\\<in>C. alw (ev (HLD {y})) \\<omega>\"\n    using AE_T_reachable\n  proof eventually_elim\n    fix \\<omega> assume \"alw (HLD (acc `` {x})) \\<omega>\"\n    then have \"alw (HLD C) \\<omega>\"\n      by (rule alw_mono) (auto simp: HLD_iff intro: assms essential_classD2)\n    then show \"\\<exists>y\\<in>C. alw (ev (HLD {y})) \\<omega>\"\n      by (rule pigeonhole_stream) fact\n  qed\n  then have \"1 = \\<P>(\\<omega> in T x. \\<exists>y\\<in>C. alw (ev (HLD {y})) \\<omega>)\"\n    by (subst (asm) T.prob_Collect_eq_1[symmetric]) (auto simp: \\<open>finite C\\<close>)\n  also have \"\\<dots> = measure (T x) (\\<Union>y\\<in>C. {\\<omega>\\<in>space (T x). alw (ev (HLD {y})) \\<omega>})\"\n    by (intro arg_cong2[where f=measure]) auto\n  also have \"\\<dots> \\<le> (\\<Sum>y\\<in>C. H x y)\"\n    unfolding H_def using \\<open>finite C\\<close> by (rule T.finite_measure_subadditive_finite) auto\n  also have \"\\<dots> = (\\<Sum>y\\<in>C. U x y * H y y)\"\n    by (auto intro!: sum.cong H_eq)\n  finally have \"\\<exists>y\\<in>C. recurrent y\"\n    by (rule_tac ccontr) (simp add: H_eq(2))\n  then guess y ..\n  from essential_classD3[OF C(1) x this(1)] recurrent_acc(3)[OF this(2)]\n  show \"recurrent x\"\n    by (simp add: communicating_def)\nqed\n\nlemma irreducibleD:\n  \"C \\<in> UNIV // communicating \\<Longrightarrow> a \\<in> C \\<Longrightarrow> b \\<in> C \\<Longrightarrow> (a, b) \\<in> communicating\"\n  by (auto elim!: quotientE simp: communicating_def)\n\nlemma irreducibleD2:\n  \"C \\<in> UNIV // communicating \\<Longrightarrow> a \\<in> C \\<Longrightarrow> (a, b) \\<in> communicating \\<Longrightarrow> b \\<in> C\"\n  by (auto elim!: quotientE simp: communicating_def)\n\nlemma essential_class_iff_recurrent:\n  \"finite C \\<Longrightarrow> C \\<in> UNIV // communicating \\<Longrightarrow> essential_class C \\<longleftrightarrow> (\\<forall>x\\<in>C. recurrent x)\"\n  by (metis finite_essential_class_imp_recurrent irreducibleD2 recurrent_acc(4) essential_classI)\n\ndefinition \"U' x y = (\\<integral>\\<^sup>+\\<omega>. eSuc (sfirst (HLD {y}) \\<omega>) \\<partial>T x)\"\n\nlemma U'_neq_zero[simp]: \"U' x y \\<noteq> 0\"\n  unfolding U'_def by (simp add: nn_integral_add)\n\ndefinition \"gf_U' x y z = (\\<Sum>n. u x y n * Suc n * z ^ n)\"\n\ndefinition \"pos_recurrent x \\<longleftrightarrow> recurrent x \\<and> U' x x \\<noteq> \\<infinity>\"\n\n\n\nlemma gf_U'_nonneg[simp]: \"0 < z \\<Longrightarrow> z < 1 \\<Longrightarrow> 0 \\<le> gf_U' x y z\"\n  unfolding gf_U'_def\n  by (intro suminf_nonneg summable_gf_U') (auto simp: u_nonneg)\n\nlemma DERIV_gf_U:\n  fixes z :: real assumes z: \"0 < z\" \"z < 1\"\n  shows \"DERIV (gf_U x y) z :> gf_U' x y z\"\n  unfolding gf_U_def[abs_def]  gf_U'_def real_scaleR_def u_def[symmetric]\n  using z by (intro DERIV_power_series'[where R=1] summable_gf_U') auto\n\nlemma sfirst_finiteI_recurrent:\n  \"recurrent x \\<Longrightarrow> (x, y) \\<in> acc \\<Longrightarrow> AE \\<omega> in T x. sfirst (HLD {y}) \\<omega> < \\<infinity>\"\n  using recurrent_acc(1)[of y x] recurrent_acc[of x y]\n    T.AE_prob_1[of x \"{\\<omega>\\<in>space (T x). ev (HLD {y}) \\<omega>}\"]\n  unfolding sfirst_finite U_def by (simp add: space_stream_space communicating_def)\n\nlemma U'_eq_suminf:\n  assumes x: \"recurrent x\" \"(x, y) \\<in> acc\"\n  shows \"U' x y = (\\<Sum>i. ennreal (u x y i * Suc i))\"\nproof -\n  have \"(\\<integral>\\<^sup>+\\<omega>. eSuc (sfirst (HLD {y}) \\<omega>) \\<partial>T x) =\n      (\\<integral>\\<^sup>+\\<omega>. (\\<Sum>i. ennreal (Suc i) * indicator {\\<omega>\\<in>space (T y). ev_at (HLD {y}) i \\<omega>} \\<omega>) \\<partial>T x)\"\n    using sfirst_finiteI_recurrent[OF x]\n  proof (intro nn_integral_cong_AE, eventually_elim)\n    fix \\<omega> assume \"sfirst (HLD {y}) \\<omega> < \\<infinity>\"\n    then obtain n :: nat where [simp]: \"sfirst (HLD {y}) \\<omega> = n\"\n      by auto\n    show \"eSuc (sfirst (HLD {y}) \\<omega>) = (\\<Sum>i. ennreal (Suc i) * indicator {\\<omega>\\<in>space (T y). ev_at (HLD {y}) i \\<omega>} \\<omega>)\"\n      by (subst suminf_cmult_indicator[where i=n])\n         (auto simp: disjoint_family_on_def ev_at_unique space_stream_space\n                     sfirst_eq_enat_iff[symmetric] ennreal_of_nat_eq_real_of_nat\n               split: split_indicator)\n  qed\n  also have \"\\<dots> = (\\<Sum>i. ennreal (Suc i) * emeasure (T x) {\\<omega>\\<in>space (T x). ev_at (HLD {y}) i \\<omega>})\"\n    by (subst nn_integral_suminf)\n       (auto intro!: arg_cong[where f=suminf] nn_integral_cmult_indicator simp: fun_eq_iff)\n  finally show ?thesis\n    by (simp add: U'_def u_def T.emeasure_eq_measure mult_ac ennreal_mult)\nqed\n\nlemma gf_U'_tendsto_U':\n  assumes x: \"recurrent x\" \"(x, y) \\<in> acc\"\n  shows \"((\\<lambda>z. ennreal (gf_U' x y z)) \\<longlongrightarrow> U' x y) (at_left 1)\"\n  unfolding U'_eq_suminf[OF x] gf_U'_def\n  by (auto intro!: power_series_tendsto_at_left summable_gf_U' mult_nonneg_nonneg u_nonneg simp del: of_nat_Suc)\n\nlemma one_le_integral_t:\n  assumes x: \"recurrent x\" shows \"1 \\<le> U' x x\"\n  by (simp add: nn_integral_add T.emeasure_space_1 U'_def del: space_T)\n\nlemma gf_U'_pos:\n  fixes z :: real\n  assumes z: \"0 < z\" \"z < 1\" and \"U x y \\<noteq> 0\"\n  shows \"0 < gf_U' x y z\"\n  unfolding gf_U'_def\nproof (subst suminf_pos_iff)\n  show \"summable (\\<lambda>n. u x y n * real (Suc n) * z ^ n)\"\n    using z by (intro summable_gf_U') simp\n  show pos: \"\\<forall>n. 0 \\<le> u x y n * real (Suc n) * z ^ n\"\n    using z by (auto intro!: mult_nonneg_nonneg u_nonneg)\n  show \"\\<exists>n. 0 < u x y n * real (Suc n) * z ^ n\"\n  proof (rule ccontr)\n    assume \"\\<not> (\\<exists>n. 0 < u x y n * real (Suc n) * z ^ n)\"\n    with pos have \"\\<forall>n. u x y n * real (Suc n) * z ^ n = 0\"\n      by (intro antisym allI) (simp_all add: not_less)\n    with z have \"u x y = (\\<lambda>n. 0)\"\n      by (intro ext) simp\n    with u_sums_U[of x y, THEN sums_unique] \\<open>U x y \\<noteq> 0\\<close> show False\n      by simp\n  qed\nqed\n\nlemma inverse_gf_U'_tendsto:\n  assumes \"recurrent y\"\n  shows \"((\\<lambda>x. - 1 / - gf_U' y y x) \\<longlongrightarrow> enn2real (1 / U' y y)) (at_left (1::real))\"\nproof cases\n  assume inf: \"U' y y = \\<infinity>\"\n  with gf_U'_tendsto_U'[of y y] \\<open>recurrent y\\<close>\n  have \"LIM z (at_left 1). gf_U' y y z :> at_top\"\n    by (auto simp: ennreal_tendsto_top_eq_at_top U'_def)\n  then have \"LIM z (at_left 1). gf_U' y y z :> at_infinity\"\n    by (rule filterlim_mono) (auto simp: at_top_le_at_infinity)\n  with inf show ?thesis\n    by (auto intro!: tendsto_divide_0)\nnext\n  assume fin: \"U' y y \\<noteq> \\<infinity>\"\n  then obtain r where r: \"U' y y = ennreal r\" and [simp]: \"0 \\<le> r\"\n    by (cases \"U' y y\") (auto simp: U'_def)\n  then have eq: \"enn2real (1 / U' y y) = - 1 / - r\" and \"1 \\<le> r\"\n    using one_le_integral_t[OF \\<open>recurrent y\\<close>]\n    by (auto simp add: ennreal_1[symmetric] divide_ennreal simp del: ennreal_1)\n  have \"((\\<lambda>z. ennreal (gf_U' y y z)) \\<longlongrightarrow> ennreal r) (at_left 1)\"\n    using gf_U'_tendsto_U'[OF \\<open>recurrent y\\<close>, of y] r by simp\n  then have gf_U': \"(gf_U' y y \\<longlongrightarrow> r) (at_left (1::real))\"\n    by (rule tendsto_ennrealD)\n       (insert summable_gf_U', auto intro!: eventually_at_left_1 suminf_nonneg simp: gf_U'_def u_nonneg)\n  show ?thesis\n    using \\<open>1 \\<le> r\\<close> unfolding eq by (intro tendsto_intros gf_U') simp\nqed\n\nlemma gf_G_pos:\n  fixes z :: real\n  assumes z: \"0 < z\" \"z < 1\" and *: \"(x, y) \\<in> acc\"\n  shows \"0 < gf_G x y z\"\n  unfolding gf_G_def\nproof (subst suminf_pos_iff)\n  show \"summable (\\<lambda>n. p x y n *\\<^sub>R z ^ n)\"\n    using z by (intro convergence_G convergence_G_less_1) simp\n  show pos: \"\\<forall>n. 0 \\<le> p x y n *\\<^sub>R z ^ n\"\n    using z by (auto intro!: mult_nonneg_nonneg p_nonneg)\n  show \"\\<exists>n. 0 < p x y n *\\<^sub>R z ^ n\"\n  proof (rule ccontr)\n    assume \"\\<not> (\\<exists>n. 0 < p x y n *\\<^sub>R z ^ n)\"\n    with pos have \"\\<forall>n. p x y n * z ^ n = 0\"\n      by (intro antisym allI) (simp_all add: not_less)\n    with z have \"\\<And>n. p x y n = 0\"\n      by simp\n    with *[THEN accD_pos] show False\n      by simp\n  qed\nqed\n\nlemma pos_recurrentI_communicating:\n  assumes y: \"pos_recurrent y\" and x: \"(y, x) \\<in> communicating\"\n  shows \"pos_recurrent x\"\nproof -\n  from y x have recurrent: \"recurrent y\" \"recurrent x\" and fin: \"U' y y \\<noteq> \\<infinity>\"\n    by (auto simp: pos_recurrent_def recurrent_iffI_communicating nn_integral_add)\n  have pos: \"0 < enn2real (1 / U' y y)\"\n    using one_le_integral_t[OF \\<open>recurrent y\\<close>] fin\n    by (auto simp: U'_def enn2real_positive_iff less_top[symmetric] ennreal_zero_less_divide ennreal_divide_eq_top_iff)\n\n  from fin obtain r where r: \"U' y y = ennreal r\" and [simp]: \"0 \\<le> r\"\n    by (cases \"U' y y\") (auto simp: U'_def)\n\n  from x obtain n m where \"0 < p x y n\" \"0 < p y x m\"\n    by (auto dest!: accD_pos simp: communicating_def)\n\n  let ?L = \"at_left (1::real)\"\n  have le: \"eventually (\\<lambda>z. p x y n * p y x m * z^(n + m) \\<le> (1 - gf_U y y z) / (1 - gf_U x x z)) ?L\"\n  proof (rule eventually_at_left_1)\n    fix z :: real assume z: \"0 < z\" \"z < 1\"\n    then have conv: \"\\<And>x. convergence_G x x z\"\n      by (intro convergence_G_less_1) simp\n    have sums: \"(\\<lambda>i. (p x y n * p y x m * z^(n + m)) * (p y y i * z^i)) sums ((p x y n * p y x m * z^(n + m)) * gf_G y y z)\"\n      unfolding gf_G_def\n      by (intro sums_mult summable_sums) (auto intro!: conv convergence_G[where 'a=real, simplified])\n    have \"(\\<Sum>i. (p x y n * p y x m * z^(n + m)) * (p y y i * z^i)) \\<le> (\\<Sum>i. p x x (i + (n + m)) * z^(i + (n + m)))\"\n    proof (intro allI suminf_le sums_summable[OF sums] summable_ignore_initial_segment convergence_G[where 'a=real, simplified] convergence_G_less_1)\n      show \"norm z < 1\" using z by simp\n      fix i\n      have \"(p x y n * p y y ((n + i) - n)) * p y x ((n + i + m) - (n + i)) \\<le> p x y (n + i) * p y x ((n + i + m) - (n + i))\"\n        by (intro mult_right_mono prob_reachable_le) simp_all\n      also have \"\\<dots> \\<le> p x x (n + i + m)\"\n         by (intro prob_reachable_le) simp_all\n      finally show \"p x y n * p y x m * z ^ (n + m) * (p y y i * z ^ i) \\<le> p x x (i + (n + m)) * z ^ (i + (n + m))\"\n        using z by (auto simp add: ac_simps power_add intro!: mult_left_mono)\n    qed\n    also have \"\\<dots> \\<le> gf_G x x z\"\n      unfolding gf_G_def\n      using z\n      apply (subst (2) suminf_split_initial_segment[where k=\"n + m\"])\n      apply (intro convergence_G conv)\n      apply (simp add: sum_nonneg)\n      done\n    finally have \"(p x y n * p y x m * z^(n + m)) * gf_G y y z \\<le> gf_G x x z\"\n      using sums_unique[OF sums] by simp\n    then have \"(p x y n * p y x m * z^(n + m)) \\<le> gf_G x x z / gf_G y y z\"\n      using z gf_G_pos[of z y y] by (simp add: field_simps)\n    also have \"\\<dots> = (1 - gf_U y y z) / (1 - gf_U x x z)\"\n      unfolding gf_G_eq_gf_U[OF conv] using gf_G_eq_gf_U(2)[OF conv] by (simp add: field_simps )\n    finally show \"p x y n * p y x m * z^(n + m) \\<le> (1 - gf_U y y z) / (1 - gf_U x x z)\" .\n  qed\n\n  have \"U' x x \\<noteq> \\<infinity>\"\n  proof\n    assume \"U' x x = \\<infinity>\"\n    have \"((\\<lambda>z. (1 - gf_U y y z) / (1 - gf_U x x z)) \\<longlongrightarrow> 0) ?L\"\n    proof (rule lhopital_left)\n      show \"((\\<lambda>z. 1 - gf_U y y z) \\<longlongrightarrow> 0) ?L\"\n        using gf_U[of y] recurrent_iff_U_eq_1[of y] \\<open>recurrent y\\<close> by (auto intro!: tendsto_eq_intros)\n      show \"((\\<lambda>z. 1 - gf_U x x z) \\<longlongrightarrow> 0) ?L\"\n        using gf_U[of x] recurrent_iff_U_eq_1[of x] \\<open>recurrent x\\<close> by (auto intro!: tendsto_eq_intros)\n      show \"eventually (\\<lambda>z. 1 - gf_U x x z \\<noteq> 0) ?L\"\n        by (auto intro!: eventually_at_left_1 simp: gf_G_eq_gf_U(2) convergence_G_less_1)\n      show \"eventually (\\<lambda>z. - gf_U' x x z \\<noteq> 0) ?L\"\n        using gf_U'_pos[of _ x x] recurrent_iff_U_eq_1[of x] \\<open>recurrent x\\<close>\n        by (auto intro!: eventually_at_left_1) (metis less_le)\n      show \"eventually (\\<lambda>z. DERIV (\\<lambda>xa. 1 - gf_U x x xa) z :> - gf_U' x x z) ?L\"\n        by (auto intro!: eventually_at_left_1 derivative_eq_intros DERIV_gf_U)\n      show \"eventually (\\<lambda>z. DERIV (\\<lambda>xa. 1 - gf_U y y xa) z :> - gf_U' y y z) ?L\"\n        by (auto intro!: eventually_at_left_1 derivative_eq_intros DERIV_gf_U)\n\n      have \"(gf_U' y y \\<longlongrightarrow> U' y y) ?L\"\n        using \\<open>recurrent y\\<close> by (rule gf_U'_tendsto_U') simp\n      then have *: \"(gf_U' y y \\<longlongrightarrow> r) ?L\"\n        by (auto simp add: r eventually_at_left_1 dest!: tendsto_ennrealD)\n      moreover\n      have \"(gf_U' x x \\<longlongrightarrow> U' x x) ?L\"\n        using \\<open>recurrent x\\<close> by (rule gf_U'_tendsto_U') simp\n      then have \"LIM z ?L. - gf_U' x x z :> at_bot\"\n        by (simp add: ennreal_tendsto_top_eq_at_top \\<open>U' x x = \\<infinity>\\<close> filterlim_uminus_at_top\n                 del: ennreal_of_enat_eSuc)\n      then have \"LIM z ?L. - gf_U' x x z :> at_infinity\"\n        by (rule filterlim_mono) (auto simp: at_bot_le_at_infinity)\n      ultimately show \"((\\<lambda>z. - gf_U' y y z / - gf_U' x x z) \\<longlongrightarrow> 0) ?L\"\n        by (intro tendsto_divide_0[where c=\"- r\"] tendsto_intros)\n    qed\n    moreover\n    have \"((\\<lambda>z. p x y n * p y x m * z^(n + m)) \\<longlongrightarrow> p x y n * p y x m) ?L\"\n      by (auto intro!: tendsto_eq_intros)\n    ultimately have \"p x y n * p y x m \\<le> 0\"\n      using le by (rule tendsto_le[OF trivial_limit_at_left_real])\n    with \\<open>0 < p x y n\\<close> \\<open>0 < p y x m\\<close> show False\n      by (auto simp add: mult_le_0_iff)\n  qed\n  with \\<open>recurrent x\\<close> show ?thesis\n    by (simp add: pos_recurrent_def nn_integral_add)\nqed\n\nlemma pos_recurrent_iffI_communicating:\n  \"(y, x) \\<in> communicating \\<Longrightarrow> pos_recurrent y \\<longleftrightarrow> pos_recurrent x\"\n  using pos_recurrentI_communicating[of x y] pos_recurrentI_communicating[of y x]\n  by (auto simp add: communicating_def)\n\nlemma U_le_F: \"U x y \\<le> F x y\"\n  by (auto simp: U_def F_def intro!: T.finite_measure_mono)\n\nlemma not_empty_irreducible: \"C \\<in> UNIV // communicating \\<Longrightarrow> C \\<noteq> {}\"\n  by (auto simp: quotient_def Image_def communicating_def)\n\nsubsection \\<open>Stationary distribution\\<close>\n\ndefinition stat :: \"'s set \\<Rightarrow> 's measure\" where\n  \"stat C = point_measure UNIV (\\<lambda>x. indicator C x / U' x x)\"\n\nlemma sets_stat[simp]: \"sets (stat C) = sets (count_space UNIV)\"\n  by (simp add: stat_def sets_point_measure)\n\nlemma space_stat[simp]: \"space (stat C) = UNIV\"\n  by (simp add: stat_def space_point_measure)\n\nlemma stat_subprob:\n  assumes C: \"essential_class C\" and \"countable C\" and pos: \"\\<forall>c\\<in>C. pos_recurrent c\"\n  shows \"emeasure (stat C) C \\<le> 1\"\nproof -\n  let ?L = \"at_left (1::real)\"\n  from finite_sequence_to_countable_set[OF \\<open>countable C\\<close>] guess A . note A = this\n  then have \"(\\<lambda>n. emeasure (stat C) (A n)) \\<longlonglongrightarrow> emeasure (stat C) (\\<Union>i. A i)\"\n    by (intro Lim_emeasure_incseq) (auto simp: incseq_Suc_iff)\n  then have \"emeasure (stat C) (\\<Union>i. A i) \\<le> 1\"\n  proof (rule LIMSEQ_le[OF _ tendsto_const], intro exI allI impI)\n    fix n\n    from A(1,3) have A_n: \"finite (A n)\"\n      by auto\n\n    from C have \"C \\<noteq> {}\"\n      by (simp add: essential_class_def not_empty_irreducible)\n    then obtain x where \"x \\<in> C\" by auto\n\n    have \"((\\<lambda>z. (\\<Sum>y\\<in>A n. gf_F x y z * ((1 - z) / (1 - gf_U y y z)))) \\<longlongrightarrow> (\\<Sum>y\\<in>A n. F x y * enn2real (1 / U' y y))) ?L\"\n    proof (intro tendsto_intros gf_F, rule lhopital_left)\n      fix y assume \"y \\<in> A n\"\n      with \\<open>A n \\<subseteq> C\\<close> have \"y \\<in> C\"\n        by auto\n      show \"((-) 1 \\<longlongrightarrow> 0) ?L\"\n        by (intro tendsto_eq_intros) simp_all\n      have \"recurrent y\"\n        using pos[THEN bspec, OF \\<open>y\\<in>C\\<close>] by (simp add: pos_recurrent_def)\n      then have \"U y y = 1\"\n        by (simp add: recurrent_iff_U_eq_1)\n\n      show \"((\\<lambda>x. 1 - gf_U y y x) \\<longlongrightarrow> 0) ?L\"\n        using gf_U[of y y] \\<open>U y y = 1\\<close> by (intro tendsto_eq_intros) auto\n      show \"eventually (\\<lambda>x. 1 - gf_U y y x \\<noteq> 0) ?L\"\n        using gf_G_eq_gf_U(2)[OF convergence_G_less_1, where 'z=real] by (auto intro!: eventually_at_left_1)\n      have \"eventually (\\<lambda>x. 0 < gf_U' y y x) ?L\"\n        by (intro eventually_at_left_1 gf_U'_pos) (simp_all add: \\<open>U y y = 1\\<close>)\n      then show \"eventually (\\<lambda>x. - gf_U' y y x \\<noteq> 0) ?L\"\n        by eventually_elim simp\n      show \"eventually (\\<lambda>x. DERIV (\\<lambda>x. 1 - gf_U y y x) x :> - gf_U' y y x) ?L\"\n        by (auto intro!: eventually_at_left_1 derivative_eq_intros DERIV_gf_U)\n      show \"eventually (\\<lambda>x. DERIV ((-) 1) x :> - 1) ?L\"\n        by (auto intro!: eventually_at_left_1 derivative_eq_intros)\n      show \"((\\<lambda>x. - 1 / - gf_U' y y x) \\<longlongrightarrow> enn2real (1 / U' y y)) ?L\"\n        using \\<open>recurrent y\\<close> by (rule inverse_gf_U'_tendsto)\n    qed\n    also have \"(\\<Sum>y\\<in>A n. F x y * enn2real (1 / U' y y)) = (\\<Sum>y\\<in>A n. enn2real (1 / U' y y))\"\n    proof (intro sum.cong refl)\n      fix y assume \"y \\<in> A n\"\n      with \\<open>A n \\<subseteq> C\\<close> have \"y \\<in> C\" by auto\n      with \\<open>x \\<in> C\\<close> have \"(x, y) \\<in> communicating\"\n        by (rule essential_classD3[OF C])\n      with \\<open>y\\<in>C\\<close> have \"recurrent y\" \"(y, x) \\<in> acc\"\n        using pos[THEN bspec, of y] by (auto simp add: pos_recurrent_def communicating_def)\n      then have \"U x y = 1\"\n        by (rule recurrent_acc)\n      with F_le_1[of x y] U_le_F[of x y] have \"F x y = 1\" by simp\n      then show \"F x y * enn2real (1 / U' y y) = enn2real (1 / U' y y)\"\n        by simp\n    qed\n    finally have le: \"(\\<Sum>y\\<in>A n. enn2real (1 / U' y y)) \\<le> 1\"\n    proof (rule tendsto_le[OF trivial_limit_at_left_real tendsto_const], intro eventually_at_left_1)\n      fix z :: real assume z: \"0 < z\" \"z < 1\"\n      with \\<open>x \\<in> C\\<close> have \"norm z < 1\"\n        by auto\n      then have conv: \"\\<And>x y. convergence_G x y z\"\n        by (simp add: convergence_G_less_1)\n      have \"(\\<Sum>y\\<in>A n. gf_F x y z / (1 - gf_U y y z)) = (\\<Sum>y\\<in>A n. gf_G x y z)\"\n        using \\<open>norm z < 1\\<close>\n        apply (intro sum.cong refl)\n        apply (subst gf_G_eq_gf_F)\n        apply assumption\n        apply (subst gf_G_eq_gf_U(1)[OF conv])\n        apply auto\n        done\n      also have \"\\<dots> = (\\<Sum>y\\<in>A n. \\<Sum>n. p x y n * z^n)\"\n        by (simp add: gf_G_def)\n      also have \"\\<dots>  = (\\<Sum>i. \\<Sum>y\\<in>A n. p x y i *\\<^sub>R z^i)\"\n        by (subst suminf_sum[OF convergence_G[OF conv]]) simp\n      also have \"\\<dots>  \\<le> (\\<Sum>i. z^i)\"\n      proof (intro suminf_le summable_sum convergence_G conv summable_geometric allI)\n        fix l\n        have \"(\\<Sum>y\\<in>A n. p x y l *\\<^sub>R z ^ l) = (\\<Sum>y\\<in>A n. p x y l) * z ^ l\"\n          by (simp add: sum_distrib_right)\n        also have \"\\<dots> \\<le> z ^ l\"\n        proof (intro mult_left_le_one_le)\n          have \"(\\<Sum>y\\<in>A n. p x y l) = \\<P>(\\<omega> in T x. (x ## \\<omega>) !! l \\<in> A n)\"\n            unfolding p_def using \\<open>finite (A n)\\<close>\n            by (subst T.finite_measure_finite_Union[symmetric])\n               (auto simp: disjoint_family_on_def intro!: arg_cong2[where f=measure])\n          then show \"(\\<Sum>y\\<in>A n. p x y l) \\<le> 1\"\n            by simp\n        qed (insert z, auto simp: sum_nonneg)\n        finally show \"(\\<Sum>y\\<in>A n. p x y l *\\<^sub>R z ^ l) \\<le> z ^ l\" .\n      qed fact\n      also have \"\\<dots> = 1 / (1 - z)\"\n        using sums_unique[OF geometric_sums, OF \\<open>norm z < 1\\<close>] ..\n      finally have \"(\\<Sum>y\\<in>A n. gf_F x y z / (1 - gf_U y y z)) \\<le> 1 / (1 - z)\" .\n      then have \"(\\<Sum>y\\<in>A n. gf_F x y z / (1 - gf_U y y z)) * (1 - z) \\<le> 1\"\n        using z by (simp add: field_simps)\n      then have \"(\\<Sum>y\\<in>A n. gf_F x y z / (1 - gf_U y y z) * (1 - z)) \\<le> 1\"\n        by (simp add: sum_distrib_right)\n      then show \"(\\<Sum>y\\<in>A n. gf_F x y z * ((1 - z) / (1 - gf_U y y z))) \\<le> 1\"\n        by simp\n    qed\n\n    from A_n have \"emeasure (stat C) (A n) = (\\<Sum>y\\<in>A n. emeasure (stat C) {y})\"\n      by (intro emeasure_eq_sum_singleton) simp_all\n    also have \"\\<dots> = (\\<Sum>y\\<in>A n. inverse (U' y y))\"\n      unfolding stat_def U'_def using A(1)[of n]\n      apply (intro sum.cong refl)\n      apply (subst emeasure_point_measure_finite2)\n        apply (auto simp: divide_ennreal_def Collect_conv_if)\n      done\n    also have \"\\<dots> = ennreal (\\<Sum>y\\<in>A n. enn2real (1 / U' y y))\"\n      apply (subst sum_ennreal[symmetric], simp)\n    proof (intro sum.cong refl)\n      fix y assume \"y \\<in> A n\"\n      with \\<open>A n \\<subseteq> C\\<close> pos have \"pos_recurrent y\"\n        by auto\n      with one_le_integral_t[of y] obtain r where \"U' y y = ennreal r\" \"1 \\<le> U' y y\" and [simp]: \"0 \\<le> r\"\n        by (cases \"U' y y\") (auto simp: pos_recurrent_def nn_integral_add)\n      then show \"inverse (U' y y) = ennreal (enn2real (1 / U' y y))\"\n        by (simp add: ennreal_1[symmetric] divide_ennreal inverse_ennreal inverse_eq_divide del: ennreal_1)\n    qed\n    also have \"\\<dots> \\<le> 1\"\n      using le by simp\n    finally show \"emeasure (stat C) (A n) \\<le> 1\" .\n  qed\n  with A show ?thesis\n    by simp\nqed\n\nlemma emeasure_stat_not_C:\n  assumes \"y \\<notin> C\"\n  shows \"emeasure (stat C) {y} = 0\"\n  unfolding stat_def using \\<open>y \\<notin> C\\<close>\n  by (subst emeasure_point_measure_finite2) auto\n\ndefinition stationary_distribution :: \"'s pmf \\<Rightarrow> bool\" where\n  \"stationary_distribution N \\<longleftrightarrow> N = bind_pmf N K\"\n\nlemma stationary_distributionI:\n  assumes le: \"\\<And>y. (\\<integral>x. pmf (K x) y \\<partial>measure_pmf N) \\<le> pmf N y\"\n  shows \"stationary_distribution N\"\n  unfolding stationary_distribution_def\nproof (rule pmf_eqI antisym)+\n  fix i\n  show \"pmf (bind_pmf N K) i \\<le> pmf N i\"\n    by (simp add: pmf_bind le)\n\n  define \\<Omega> where \"\\<Omega> = N \\<union> (\\<Union>i\\<in>N. set_pmf (K i))\"\n  then have \\<Omega>: \"countable \\<Omega>\"\n    by (auto intro: countable_set_pmf)\n  then interpret N: sigma_finite_measure \"count_space \\<Omega>\"\n    by (rule sigma_finite_measure_count_space_countable)\n  interpret pN: pair_sigma_finite N \"count_space \\<Omega>\"\n    by unfold_locales\n\n  have measurable_pmf[measurable]: \"(\\<lambda>(x, y). pmf (K x) y) \\<in> borel_measurable (N \\<Otimes>\\<^sub>M count_space \\<Omega>)\"\n    unfolding measurable_split_conv\n    apply (rule measurable_compose_countable'[OF _ measurable_snd])\n    apply (rule measurable_compose[OF measurable_fst])\n    apply (simp_all add: \\<Omega>)\n    done\n\n  { assume *: \"(\\<integral>y. pmf (K y) i \\<partial>N) < pmf N i\"\n    have \"0 \\<le> (\\<integral>y. pmf (K y) i \\<partial>N)\"\n      by (intro integral_nonneg_AE) simp\n    with * have i: \"i \\<in> set_pmf N\" \"i \\<in> \\<Omega>\"\n      by (auto simp: set_pmf_iff \\<Omega>_def not_le[symmetric])\n    from * have \"0 < pmf N i - (\\<integral>y. pmf (K y) i \\<partial>N)\"\n      by (simp add: field_simps)\n    also have \"\\<dots> = (\\<integral>t. (pmf N i - (\\<integral>y. pmf (K y) i \\<partial>N)) * indicator {i} t \\<partial>count_space \\<Omega>)\"\n      by (simp add: i)\n    also have \"\\<dots> \\<le> (\\<integral>t. pmf N t - \\<integral>y. pmf (K y) t \\<partial>N \\<partial>count_space \\<Omega>)\"\n      using le\n      by (intro integral_mono integrable_diff)\n         (auto simp: i pmf_bind[symmetric] integrable_pmf field_simps split: split_indicator)\n    also have \"\\<dots> = (\\<integral>t. pmf N t \\<partial>count_space \\<Omega>) - (\\<integral>t. \\<integral>y. pmf (K y) t \\<partial>N \\<partial>count_space \\<Omega>)\"\n      by (subst Bochner_Integration.integral_diff) (auto intro!: integrable_pmf simp: pmf_bind[symmetric])\n    also have \"(\\<integral>t. \\<integral>y. pmf (K y) t \\<partial>N \\<partial>count_space \\<Omega>) = (\\<integral>y. \\<integral>t. pmf (K y) t \\<partial>count_space \\<Omega> \\<partial>N)\"\n      apply (intro pN.Fubini_integral integrable_iff_bounded[THEN iffD2] conjI)\n      apply (auto simp add: N.nn_integral_fst[symmetric] nn_integral_eq_integral integrable_pmf)\n      unfolding less_top[symmetric] unfolding infinity_ennreal_def[symmetric]\n      apply (intro integrableD)\n      apply (auto intro!: measure_pmf.integrable_const_bound[where B=1]\n                  simp: AE_measure_pmf_iff integral_nonneg_AE integral_pmf)\n      done\n    also have \"(\\<integral>y. \\<integral>t. pmf (K y) t \\<partial>count_space \\<Omega> \\<partial>N) = (\\<integral>y. 1 \\<partial>N)\"\n      by (intro integral_cong_AE)\n         (auto simp: AE_measure_pmf_iff integral_pmf \\<Omega>_def intro!: measure_pmf.prob_eq_1[THEN iffD2])\n    finally have False\n      using measure_pmf.prob_space[of N] by (simp add: integral_pmf field_simps not_le[symmetric]) }\n  then show \"pmf N i \\<le> pmf (bind_pmf N K) i\"\n    by (auto simp: pmf_bind not_le[symmetric])\nqed\n\nlemma stationary_distribution_iterate:\n  assumes N: \"stationary_distribution N\"\n  shows \"ennreal (pmf N y) = (\\<integral>\\<^sup>+x. p x y n \\<partial>N)\"\nproof (induct n arbitrary: y)\n  have [simp]: \"\\<And>x y. ennreal (if x = y then 1 else 0) = indicator {y} x\"\n    by simp\n  case 0 then show ?case\n    by (simp add: p_0 pmf.rep_eq measure_pmf.emeasure_eq_measure)\nnext\n  case (Suc n) with N show ?case\n    apply (simp add: nn_integral_eq_integral[symmetric] p_le_1 p_Suc'\n                     measure_pmf.integrable_const_bound[where B=1])\n    apply (subst nn_integral_bind[symmetric, where B=\"count_space UNIV\"])\n    apply (auto simp: stationary_distribution_def measure_pmf_bind[symmetric]\n                simp del: measurable_pmf_measure1)\n    done\nqed\n\nlemma stationary_distribution_iterate':\n  assumes \"stationary_distribution N\"\n  shows \"measure N {y} = (\\<integral>x. p x y n \\<partial>N)\"\n  using stationary_distribution_iterate[OF assms]\n  by (subst (asm) nn_integral_eq_integral)\n     (auto intro!: measure_pmf.integrable_const_bound[where B=1] simp: p_le_1 pmf.rep_eq)\n\nlemma stationary_distributionD:\n  assumes C: \"essential_class C\" \"countable C\"\n  assumes N: \"stationary_distribution N\" \"N \\<subseteq> C\"\n  shows \"\\<forall>x\\<in>C. pos_recurrent x\" \"measure_pmf N = stat C\"\nproof -\n  have integrable_K: \"\\<And>f x. integrable N (\\<lambda>s. pmf (K s) (f x))\"\n    by (rule measure_pmf.integrable_const_bound[where B=1]) (simp_all add: pmf_le_1)\n\n  have measure_C: \"measure N C = 1\" and ae_C: \"AE x in N. x \\<in> C\"\n    using N C measure_pmf.prob_eq_1[of C] by (auto simp: AE_measure_pmf_iff)\n\n  have integrable_p: \"\\<And>n y. integrable N (\\<lambda>x. p x y n)\"\n    by (rule measure_pmf.integrable_const_bound[where B=1]) (simp_all add: p_le_1)\n\n  { fix e :: real assume \"0 < e\"\n    then have [simp]: \"0 \\<le> e\" by simp\n    have \"\\<exists>A\\<subseteq>C. finite A \\<and> 1 - e < measure N A\"\n    proof (rule ccontr)\n      assume contr: \"\\<not> (\\<exists>A \\<subseteq> C. finite A \\<and> 1 - e < measure N A)\"\n      from finite_sequence_to_countable_set[OF \\<open>countable C\\<close>] guess F . note F = this\n      then have *: \"(\\<lambda>n. measure N (F n)) \\<longlonglongrightarrow> measure N (\\<Union>i. F i)\"\n        by (intro measure_pmf.finite_Lim_measure_incseq) (auto simp: incseq_Suc_iff)\n      with F contr have \"measure N (\\<Union>i. F i) \\<le> 1 - e\"\n        by (intro LIMSEQ_le[OF * tendsto_const]) (auto simp: not_less)\n      with F \\<open>0 < e\\<close> show False\n        by (simp add: measure_C)\n    qed\n    then obtain A where \"A \\<subseteq> C\" \"finite A\" and e: \"1 - e < measure N A\" by auto\n\n    { fix y n assume \"y \\<in> C\"\n      from N(1) have \"measure N {y} = (\\<integral>x. p x y n \\<partial>N)\"\n        by (rule stationary_distribution_iterate')\n      also have \"\\<dots> \\<le> (\\<integral>x. p x y n * indicator A x + indicator (C - A) x \\<partial>N)\"\n        using ae_C \\<open>A \\<subseteq> C\\<close>\n        by (intro integral_mono_AE)\n           (auto elim!: eventually_mono\n                 intro!: integral_add integral_indicator p_le_1 integrable_real_mult_indicator\n                   integrable_add\n                 split: split_indicator simp: integrable_p less_top[symmetric] top_unique)\n      also have \"\\<dots> = (\\<integral>x. p x y n * indicator A x \\<partial>N) + measure N (C - A)\"\n        using ae_C \\<open>A \\<subseteq> C\\<close>\n        apply (subst Bochner_Integration.integral_add)\n        apply (auto elim!: eventually_mono\n                    intro!: integral_add integral_indicator p_le_1 integrable_real_mult_indicator\n                    split: split_indicator simp: integrable_p less_top[symmetric] top_unique)\n        done\n      also have \"\\<dots> \\<le> (\\<integral>x. p x y n * indicator A x \\<partial>N) + e\"\n        using e \\<open>A \\<subseteq> C\\<close>  by (simp add: measure_pmf.finite_measure_Diff measure_C)\n      finally have \"measure N {y} \\<le> (\\<integral>x. p x y n * indicator A x \\<partial>N) + e\" .\n      then have \"emeasure N {y} \\<le> ennreal (\\<integral>x. p x y n * indicator A x \\<partial>N) + e\"\n        by (simp add: measure_pmf.emeasure_eq_measure ennreal_plus[symmetric] del: ennreal_plus)\n      also have \"\\<dots> = (\\<integral>\\<^sup>+x. ennreal (p x y n) * indicator A x \\<partial>N) + e\"\n        by (subst nn_integral_eq_integral[symmetric])\n           (auto intro!: measure_pmf.integrable_const_bound[where B=1]\n                 simp: abs_mult p_le_1 mult_le_one ennreal_indicator ennreal_mult)\n      finally have \"emeasure N {y} \\<le> (\\<integral>\\<^sup>+x. ennreal (p x y n) * indicator A x \\<partial>N) + e\" . }\n    note v_le = this\n\n    { fix y and z :: real assume y: \"y \\<in> C\" and z: \"0 < z\" \"z < 1\"\n      have summable_int_p: \"summable (\\<lambda>n. (\\<integral> x. p x y n * indicator A x \\<partial>N) * (1 - z) * z ^ n)\"\n        using \\<open>y\\<in>C\\<close> z \\<open>A \\<subseteq> C\\<close>\n        by (auto intro!: summable_comparison_test[OF _ summable_mult[OF summable_geometric[of z], of 1]] exI[of _ 0] mult_le_one\n                            measure_pmf.integral_le_const integrable_real_mult_indicator integrable_p AE_I2 p_le_1\n                    simp: abs_mult integral_nonneg_AE)\n\n      from y z have sums_y: \"(\\<lambda>n. measure N {y} * (1 - z) * z ^ n) sums measure N {y}\"\n        using sums_mult[OF geometric_sums[of z], of \"measure N {y} * (1 - z)\"] by simp\n      then have \"emeasure N {y} = ennreal (\\<Sum>n. (measure N {y} * (1 - z)) * z ^ n)\"\n        by (auto simp add: sums_unique[symmetric] measure_pmf.emeasure_eq_measure)\n      also have \"\\<dots> = (\\<Sum>n. emeasure N {y} * (1 - z) * z ^ n)\"\n        using z  summable_mult[OF summable_geometric[of z], of \"measure_pmf.prob N {y} * (1 - z)\"]\n        by (subst suminf_ennreal[symmetric])\n           (auto simp: measure_pmf.emeasure_eq_measure ennreal_mult[symmetric] ennreal_suminf_neq_top)\n      also have \"\\<dots> \\<le> (\\<Sum>n. ((\\<integral>\\<^sup>+x. ennreal (p x y n) * indicator A x \\<partial>N) + e) * (1 - z) * z ^ n)\"\n        using \\<open>y\\<in>C\\<close> z \\<open>A \\<subseteq> C\\<close>\n        by (intro suminf_le mult_right_mono v_le allI)\n           (auto simp: measure_pmf.emeasure_eq_measure)\n      also have \"\\<dots> = (\\<Sum>n. (\\<integral>\\<^sup>+x. ennreal (p x y n) * indicator A x \\<partial>N) * (1 - z) * z ^ n) + e\"\n        using \\<open>0 < e\\<close> z sums_mult[OF geometric_sums[of z], of \"e * (1 - z)\"] \\<open>0<z\\<close> \\<open>z<1\\<close>\n        by (simp add: distrib_right suminf_add[symmetric] ennreal_suminf_cmult[symmetric]\n                      ennreal_mult[symmetric] suminf_ennreal_eq sums_unique[symmetric]\n                 del: ennreal_suminf_cmult)\n      also have \"\\<dots> = (\\<Sum>n. ennreal (1 - z) * ((\\<integral>\\<^sup>+x. ennreal (p x y n) * indicator A x \\<partial>N) * z ^ n)) + e\"\n        by (simp add: ac_simps)\n      also have \"\\<dots> = ennreal (1 - z) * (\\<Sum>n. ((\\<integral>\\<^sup>+x. ennreal (p x y n) * indicator A x \\<partial>N) * z ^ n)) + e\"\n        using z by (subst ennreal_suminf_cmult) simp_all\n      also have \"(\\<Sum>n. ((\\<integral>\\<^sup>+x. ennreal (p x y n) * indicator A x \\<partial>N) * z ^ n)) =\n          (\\<Sum>n. (\\<integral>\\<^sup>+x. ennreal (p x y n * z ^ n) * indicator A x \\<partial>N))\"\n        using z by (simp add: ac_simps nn_integral_cmult[symmetric] ennreal_mult)\n      also have \"\\<dots> = (\\<integral>\\<^sup>+x. ennreal (gf_G x y z) * indicator A x \\<partial>N)\"\n        using z\n        apply (subst nn_integral_suminf[symmetric])\n        apply (auto simp add: gf_G_def simp del: suminf_ennreal\n                    intro!: ennreal_mult_right_cong suminf_ennreal2 nn_integral_cong)\n        apply (intro summable_comparison_test[OF _ summable_mult[OF summable_geometric[of z], of 1]] impI)\n        apply (simp_all add: abs_mult p_le_1 mult_le_one power_le_one split: split_indicator)\n        done\n      also have \"\\<dots> = (\\<integral>\\<^sup>+x. ennreal (gf_F x y z * gf_G y y z) * indicator A x \\<partial>N)\"\n        using z by (intro nn_integral_cong) (simp add: gf_G_eq_gf_F[symmetric])\n      also have \"\\<dots> = ennreal (gf_G y y z) * (\\<integral>\\<^sup>+x. ennreal (gf_F x y z) * indicator A x \\<partial>N)\"\n        using z by (subst nn_integral_cmult[symmetric]) (simp_all add: gf_G_nonneg gf_F_nonneg ac_simps ennreal_mult)\n      also have \"\\<dots> = ennreal (1 / (1 - gf_U y y z)) * (\\<integral>\\<^sup>+x. ennreal (gf_F x y z) * indicator A x \\<partial>N)\"\n        using z \\<open>y \\<in> C\\<close> by (subst gf_G_eq_gf_U) (auto intro!: convergence_G_less_1)\n      finally have \"emeasure N {y} \\<le> ennreal ((1 - z) / (1 - gf_U y y z)) * (\\<integral>\\<^sup>+x. gf_F x y z * indicator A x \\<partial>N) + e\"\n        using z\n        by (subst (asm) mult.assoc[symmetric])\n           (simp add: ennreal_indicator[symmetric] ennreal_mult'[symmetric] gf_F_nonneg)\n      then have \"measure N {y} \\<le> (1 - z) / (1 - gf_U y y z) * (\\<integral>x. gf_F x y z * indicator A x \\<partial>N) + e\"\n        using z\n        by (subst (asm) nn_integral_eq_integral[OF measure_pmf.integrable_const_bound[where B=1]])\n           (auto simp: gf_F_nonneg gf_U_le_1 gf_F_le_1 measure_pmf.emeasure_eq_measure mult_le_one\n                       ennreal_mult''[symmetric] ennreal_plus[symmetric]\n                 simp del: ennreal_plus) }\n    then have \"\\<exists>A \\<subseteq> C. finite A \\<and> (\\<forall>y\\<in>C. \\<forall>z. 0 < z \\<longrightarrow> z < 1 \\<longrightarrow> measure N {y} \\<le> (1 - z) / (1 - gf_U y y z) * (\\<integral>x. gf_F x y z * indicator A x \\<partial>N) + e)\"\n      using \\<open>A \\<subseteq> C\\<close> \\<open>finite A\\<close> by auto }\n  note eps = this\n\n  { fix y A assume \"y \\<in> C\" \"finite A\" \"A \\<subseteq> C\"\n    then have \"((\\<lambda>z. \\<integral>x. gf_F x y z * indicator A x \\<partial>N) \\<longlongrightarrow> \\<integral>x. F x y * indicator A x \\<partial>N) (at_left 1)\"\n      by (subst (1 2) integral_measure_pmf[of A]) (auto intro!: tendsto_intros gf_F simp: indicator_eq_0_iff) }\n  note int_gf_F = this\n\n  have all_recurrent: \"\\<forall>y\\<in>C. recurrent y\"\n  proof (rule ccontr)\n    assume \"\\<not> (\\<forall>y\\<in>C. recurrent y)\"\n    then obtain x where \"x \\<in> C\" \"\\<not> recurrent x\" by auto\n    then have transient: \"\\<And>x. x \\<in> C \\<Longrightarrow> \\<not> recurrent x\"\n      using C by (auto simp: essential_class_def recurrent_iffI_communicating[symmetric] elim!: quotientE)\n\n    { fix y assume \"y \\<in> C\"\n      with transient have \"U y y < 1\"\n        by (metis recurrent_iff_U_eq_1 U_cases)\n      have \"measure N {y} \\<le> 0\"\n      proof (rule dense_ge)\n        fix e :: real assume \"0 < e\"\n        from eps[OF this] \\<open>y \\<in> C\\<close> obtain A where\n          A: \"finite A\" \"A \\<subseteq> C\" and\n          le: \"\\<And>z. 0 < z \\<Longrightarrow> z < 1 \\<Longrightarrow> measure N {y} \\<le> (1 - z) / (1 - gf_U y y z) * (\\<integral>x. gf_F x y z * indicator A x \\<partial>N) + e\"\n          by auto\n        have \"((\\<lambda>z. (1 - z) / (1 - gf_U y y z) * (\\<integral>x. gf_F x y z * indicator A x \\<partial>N) + e) \\<longlongrightarrow>\n          (1 - 1) / (1 - U y y) * (\\<integral>x. F x y * indicator A x \\<partial>N) + e) (at_left (1::real))\"\n          using A \\<open>U y y < 1\\<close> \\<open>y \\<in> C\\<close> by (intro tendsto_intros gf_U int_gf_F) auto\n        then have 1: \"((\\<lambda>z. (1 - z) / (1 - gf_U y y z) * (\\<integral>x. gf_F x y z * indicator A x \\<partial>N) + e) \\<longlongrightarrow> e) (at_left (1::real))\"\n          by simp\n        with le show \"measure N {y} \\<le> e\"\n          by (intro tendsto_le[OF trivial_limit_at_left_real _ tendsto_const])\n             (auto simp: eventually_at_left_1)\n      qed\n      then have \"measure N {y} = 0\"\n        by (intro antisym measure_nonneg) }\n    then have \"emeasure N C = 0\"\n      by (subst emeasure_countable_singleton) (auto simp: measure_pmf.emeasure_eq_measure nn_integral_0_iff_AE ae_C C)\n    then show False\n      using \\<open>measure N C = 1\\<close> by (simp add: measure_pmf.emeasure_eq_measure)\n  qed\n  then have \"\\<And>x. x \\<in> C \\<Longrightarrow> U x x = 1\"\n    by (metis recurrent_iff_U_eq_1)\n\n  { fix y assume \"y \\<in> C\"\n    then have \"U y y = 1\" \"recurrent y\"\n      using \\<open>y \\<in> C \\<Longrightarrow> U y y = 1\\<close> all_recurrent by auto\n    have \"measure N {y} \\<le> enn2real (1 / U' y y)\"\n    proof (rule field_le_epsilon)\n      fix e :: real assume \"0 < e\"\n      from eps[OF \\<open>0 < e\\<close>] \\<open>y \\<in> C\\<close> obtain A where\n        A: \"finite A\" \"A \\<subseteq> C\" and\n        le: \"\\<And>z. 0 < z \\<Longrightarrow> z < 1 \\<Longrightarrow> measure N {y} \\<le> (1 - z) / (1 - gf_U y y z) * (\\<integral>x. gf_F x y z * indicator A x \\<partial>N) + e\"\n        by auto\n      let ?L = \"at_left (1::real)\"\n      have \"((\\<lambda>z. (1 - z) / (1 - gf_U y y z) * (\\<integral>x. gf_F x y z * indicator A x \\<partial>N) + e) \\<longlongrightarrow>\n          enn2real (1 / U' y y) * (\\<integral>x. F x y * indicator A x \\<partial>N) + e) ?L\"\n      proof (intro tendsto_add tendsto_const tendsto_mult int_gf_F,\n             rule lhopital_left[where f'=\"\\<lambda>x. - 1\" and g'=\"\\<lambda>z. - gf_U' y y z\"])\n        show \"((-) 1 \\<longlongrightarrow> 0) ?L\" \"((\\<lambda>x. 1 - gf_U y y x) \\<longlongrightarrow> 0) ?L\"\n          using gf_U[of y y] by (auto intro!: tendsto_eq_intros simp: \\<open>U y y = 1\\<close>)\n        show \"y \\<in> C\" \"finite A\" \"A \\<subseteq> C\" by fact+\n        show \"eventually (\\<lambda>x. 1 - gf_U y y x \\<noteq> 0) ?L\"\n          using gf_G_eq_gf_U(2)[OF convergence_G_less_1, where 'z=real] by (auto intro!: eventually_at_left_1)\n        show \"((\\<lambda>x. - 1 / - gf_U' y y x) \\<longlongrightarrow> enn2real (1 / U' y y)) ?L\"\n          using \\<open>recurrent y\\<close> by (rule inverse_gf_U'_tendsto)\n        have \"eventually (\\<lambda>x. 0 < gf_U' y y x) ?L\"\n          by (intro eventually_at_left_1 gf_U'_pos) (simp_all add: \\<open>U y y = 1\\<close>)\n        then show \"eventually (\\<lambda>x. - gf_U' y y x \\<noteq> 0) ?L\"\n          by eventually_elim simp\n        show \"eventually (\\<lambda>x. DERIV (\\<lambda>x. 1 - gf_U y y x) x :> - gf_U' y y x) ?L\"\n          by (auto intro!: eventually_at_left_1 derivative_eq_intros DERIV_gf_U)\n        show \"eventually (\\<lambda>x. DERIV ((-) 1) x :> - 1) ?L\"\n          by (auto intro!: eventually_at_left_1 derivative_eq_intros)\n      qed\n      then have \"measure N {y} \\<le> enn2real (1 / U' y y) * (\\<integral>x. F x y * indicator A x \\<partial>N) + e\"\n        by (rule tendsto_le[OF trivial_limit_at_left_real _ tendsto_const]) (intro eventually_at_left_1 le)\n      then have \"measure N {y} - e \\<le> enn2real (1 / U' y y) * (\\<integral>x. F x y * indicator A x \\<partial>N)\"\n        by simp\n      also have \"\\<dots> \\<le> enn2real (1 / U' y y)\"\n        using A\n        by (intro mult_left_le measure_pmf.integral_le_const measure_pmf.integrable_const_bound[where B=1])\n           (auto simp: mult_le_one F_le_1 U'_def)\n      finally show \"measure N {y} \\<le> enn2real (1 / U' y y) + e\"\n        by simp\n    qed }\n  note measure_y_le = this\n\n  show pos: \"\\<forall>y\\<in>C. pos_recurrent y\"\n  proof (rule ccontr)\n    assume \"\\<not> (\\<forall>y\\<in>C. pos_recurrent y)\"\n    then obtain x where x: \"x \\<in> C\" \"\\<not> pos_recurrent x\" by auto\n    { fix y assume \"y \\<in> C\"\n      with x have \"\\<not> pos_recurrent y\"\n        using C by (auto simp: essential_class_def pos_recurrent_iffI_communicating[symmetric] elim!: quotientE)\n      with all_recurrent \\<open>y \\<in> C\\<close> have \"enn2real (1 / U' y y) = 0\"\n        by (simp add: pos_recurrent_def nn_integral_add)\n      with measure_y_le[OF \\<open>y \\<in> C\\<close>] have \"measure N {y} = 0\"\n        by (auto intro!: antisym simp: pos_recurrent_def) }\n    then have \"emeasure N C = 0\"\n      by (subst emeasure_countable_singleton) (auto simp: C ae_C measure_pmf.emeasure_eq_measure nn_integral_0_iff_AE)\n    then show False\n      using \\<open>measure N C = 1\\<close> by (simp add: measure_pmf.emeasure_eq_measure)\n  qed\n\n  { fix A :: \"'s set\" assume [simp]: \"countable A\"\n    have \"emeasure N A = (\\<integral>\\<^sup>+x. emeasure N {x} \\<partial>count_space A)\"\n      by (intro emeasure_countable_singleton) auto\n    also have \"\\<dots> \\<le> (\\<integral>\\<^sup>+x. emeasure (stat C) {x} \\<partial>count_space A)\"\n    proof (intro nn_integral_mono)\n      fix y assume \"y \\<in> space (count_space A)\"\n      show \"emeasure N {y} \\<le> emeasure (stat C) {y}\"\n      proof cases\n        assume \"y \\<in> C\"\n        with pos have \"pos_recurrent y\"\n          by auto\n        with one_le_integral_t[of y] obtain r where r: \"U' y y = ennreal r\" \"1 \\<le> U' y y\" and [simp]: \"0 \\<le> r\"\n          by (cases \"U' y y\") (auto simp: pos_recurrent_def nn_integral_add)\n\n        from measure_y_le[OF \\<open>y \\<in> C\\<close>]\n        have \"emeasure N {y} \\<le> ennreal (enn2real (1 / U' y y))\"\n          by (simp add: measure_pmf.emeasure_eq_measure)\n        also have \"\\<dots> = emeasure (stat C) {y}\"\n          unfolding stat_def using \\<open>y \\<in> C\\<close> r\n          by (subst emeasure_point_measure_finite2)\n             (auto simp add: ennreal_1[symmetric] divide_ennreal inverse_ennreal inverse_eq_divide ennreal_mult[symmetric]\n                   simp del: ennreal_1)\n        finally show \"emeasure N {y} \\<le> emeasure (stat C) {y}\"\n          by simp\n      next\n        assume \"y \\<notin> C\"\n        with ae_C have \"emeasure N {y} = 0\"\n          by (subst AE_iff_measurable[symmetric, where P=\"\\<lambda>x. x \\<noteq> y\"]) (auto elim!: eventually_mono)\n        moreover have \"emeasure (stat C) {y} = 0\"\n          using emeasure_stat_not_C[OF \\<open>y \\<notin> C\\<close>] .\n        ultimately show ?thesis by simp\n      qed\n    qed\n    also have \"\\<dots> = emeasure (stat C) A\"\n      by (intro emeasure_countable_singleton[symmetric]) auto\n    finally have \"emeasure N A \\<le> emeasure (stat C) A\" . }\n  note N_le_C = this\n\n  from stat_subprob[OF C(1) \\<open>countable C\\<close> pos] N_le_C[OF \\<open>countable C\\<close>] \\<open>measure N C = 1\\<close>\n  have stat_C_eq_1: \"emeasure (stat C) C = 1\"\n    by (auto simp add: measure_pmf.emeasure_eq_measure one_ennreal_def)\n  moreover have \"emeasure (stat C) (UNIV - C) = 0\"\n    by (subst AE_iff_measurable[symmetric, where P=\"\\<lambda>x. x \\<in> C\"])\n       (auto simp: stat_def AE_point_measure sets_point_measure space_point_measure\n                split: split_indicator cong del: AE_cong)\n  ultimately have \"emeasure (stat C) (space (stat C)) = 1\"\n    using plus_emeasure[of C \"stat C\" \"UNIV - C\"] by (simp add: Un_absorb1)\n  interpret stat: prob_space \"stat C\"\n    by standard fact\n\n  show \"measure_pmf N = stat C\"\n  proof (rule measure_eqI_countable_AE)\n    show \"sets N = UNIV\" \"sets (stat C) = UNIV\"\n      by auto\n    show \"countable C\" \"AE x in N. x \\<in> C\" and ae_stat: \"AE x in stat C. x \\<in> C\"\n      using C ae_C stat_C_eq_1 by (auto intro!: stat.AE_prob_1 simp: stat.emeasure_eq_measure)\n\n    { assume \"\\<exists>x. emeasure N {x} \\<noteq> emeasure (stat C) {x}\"\n      then obtain x where [simp]: \"emeasure N {x} \\<noteq> emeasure (stat C) {x}\" by auto\n      with N_le_C[of \"{x}\"] have x: \"emeasure N {x} < emeasure (stat C) {x}\"\n        by (auto simp: less_le)\n      have \"1 = emeasure N {x} + emeasure N (C - {x})\"\n        using ae_C\n        by (subst plus_emeasure) (auto intro!: measure_pmf.emeasure_eq_1_AE)\n      also have \"\\<dots> < emeasure (stat C) {x} + emeasure (stat C) (C - {x})\"\n        using x N_le_C[of \"C - {x}\"] C ae_C\n        by (simp add: stat.emeasure_eq_measure measure_pmf.emeasure_eq_measure\n                      ennreal_plus[symmetric] ennreal_less_iff\n                 del: ennreal_plus)\n      also have \"\\<dots> = 1\"\n        using ae_stat by (subst plus_emeasure) (auto intro!: stat.emeasure_eq_1_AE)\n      finally have False by simp }\n    then show \"\\<And>x. emeasure N {x} = emeasure (stat C) {x}\" by auto\n  qed\nqed\n\nlemma measure_point_measure_singleton:\n  \"x \\<in> A \\<Longrightarrow> measure (point_measure A X) {x} = enn2real (X x)\"\n  unfolding measure_def by (subst emeasure_point_measure_finite2) auto\n\nlemma stationary_distribution_imp_int_t:\n  assumes C: \"essential_class C\" \"countable C\" \"stationary_distribution N\" \"N \\<subseteq> C\"\n  assumes x: \"x \\<in> C\" shows \"U' x x = 1 / ennreal (pmf N x)\"\nproof -\n  from stationary_distributionD[OF C]\n  have \"measure_pmf N = stat C\" and *: \"\\<forall>x\\<in>C. pos_recurrent x\" by auto\n  show ?thesis\n    unfolding \\<open>measure_pmf N = stat C\\<close> pmf.rep_eq stat_def\n    using *[THEN bspec, OF x] x\n    apply (simp add: measure_point_measure_singleton)\n    apply (cases \"U' x x\")\n    subgoal for r\n      by (cases \"r = 0\")\n         (simp_all add: divide_ennreal_def inverse_ennreal)\n    apply simp\n    done\nqed\n\ndefinition \"period_set x = {i. 0 < i \\<and> 0 < p x x i }\"\ndefinition \"period C = (SOME d. \\<forall>x\\<in>C. d = Gcd (period_set x))\"\n\nlemma Gcd_period_set_invariant:\n  assumes c: \"(x, y) \\<in> communicating\"\n  shows \"Gcd (period_set x) = Gcd (period_set y)\"\nproof -\n  { fix x y n assume c: \"(x, y) \\<in> communicating\" \"x \\<noteq> y\" and n: \"n \\<in> period_set x\"\n    from c obtain l k where \"0 < p x y l\" \"0 < p y x k\"\n      by (auto simp: communicating_def dest!: accD_pos)\n    moreover with \\<open>x \\<noteq> y\\<close> have \"l \\<noteq> 0 \\<and> k \\<noteq> 0\"\n      by (intro notI conjI) (auto simp: p_0)\n    ultimately have pos: \"0 < l\" \"0 < k\" and l: \"0 < p x y l\" and k: \"0 < p y x k\"\n      by auto\n\n    from mult_pos_pos[OF k l] prob_reachable_le[of k \"k + l\" y x y] c\n    have k_l: \"0 < p y y (k + l)\"\n      by simp\n    then have \"Gcd (period_set y) dvd k + l\"\n      using pos by (auto intro!: Gcd_dvd_nat simp: period_set_def)\n    moreover\n    from n have \"0 < p x x n\" \"0 < n\" by (auto simp: period_set_def)\n    from mult_pos_pos[OF k this(1)] prob_reachable_le[of k \"k + n\" y x x] c\n    have \"0 < p y x (k + n)\"\n      by simp\n    from mult_pos_pos[OF this(1) l] prob_reachable_le[of \"k + n\" \"(k + n) + l\" y x y] c\n    have \"0 < p y y (k + n + l)\"\n      by simp\n    then have \"Gcd (period_set y) dvd (k + l) + n\"\n      using pos by (auto intro!: Gcd_dvd_nat simp: period_set_def ac_simps)\n    ultimately have \"Gcd (period_set y) dvd n\"\n      by (metis dvd_add_left_iff add.commute) }\n  note this[of x y] this[of y x] c\n  moreover have \"(y, x) \\<in> communicating\"\n    using c by (simp add: communicating_def)\n  ultimately show ?thesis\n    by (auto intro: dvd_antisym Gcd_greatest Gcd_dvd)\nqed\n\nlemma period_eq:\n  assumes \"C \\<in> UNIV // communicating\" \"x \\<in> C\"\n  shows \"period C = Gcd (period_set x)\"\n  unfolding period_def\n  using assms\n  by (rule_tac someI2[where a=\"Gcd (period_set x)\"])\n     (auto intro!: Gcd_period_set_invariant irreducibleD)\n\ndefinition \"aperiodic C \\<longleftrightarrow> C \\<in> UNIV // communicating \\<and> period C = 1\"\n\ndefinition \"not_ephemeral C \\<longleftrightarrow> C \\<in> UNIV // communicating \\<and> \\<not> (\\<exists>x. C = {x} \\<and> p x x 1 = 0)\"\n\nlemma not_ephemeralD:\n  assumes C: \"not_ephemeral C\" \"x \\<in> C\"\n  shows \"\\<exists>n>0. 0 < p x x n\"\nproof cases\n  assume \"\\<exists>x. C = {x}\"\n  with \\<open>x \\<in> C\\<close> have \"C = {x}\" by auto\n  with C p_nonneg[of x x 1] have \"0 < p x x 1\"\n    by (auto simp: not_ephemeral_def less_le)\n  with \\<open>C = {x}\\<close> show ?thesis by auto\nnext\n  from C have irr: \"C \\<in> UNIV // communicating\"\n    by (auto simp: not_ephemeral_def)\n  assume \"\\<not>(\\<exists>x. C = {x})\"\n  then have \"\\<forall>x. C \\<noteq> {x}\" by auto\n  with \\<open>x \\<in> C\\<close> obtain y where \"y \\<in> C\" \"x \\<noteq> y\"\n    by blast\n  with irreducibleD[OF irr, of x y] C \\<open>x \\<in> C\\<close> have c: \"(x, y) \\<in> communicating\" by auto\n  with accD_pos[of x y] accD_pos[of y x]\n  obtain k l where pos: \"0 < p x y k\" \"0 < p y x l\"\n    by (auto simp: communicating_def)\n  with \\<open>x \\<noteq> y\\<close> have \"l \\<noteq> 0\"\n    by (intro notI) (auto simp: p_0)\n  have \"0 < p x y k * p y x (k + l - k)\"\n    using pos by auto\n  also have \"p x y k * p y x (k + l - k) \\<le> p x x (k + l)\"\n    using prob_reachable_le[of \"k\" \"k + l\" x y x] c by auto\n  finally show ?thesis\n    using \\<open>l \\<noteq> 0\\<close> \\<open>x \\<in> C\\<close> by (auto intro!: exI[of _ \"k + l\"])\nqed\n\nlemma not_ephemeralD_pos_period:\n  assumes C: \"not_ephemeral C\"\n  shows \"0 < period C\"\nproof -\n  from C not_empty_irreducible[of C] obtain x where \"x \\<in> C\"\n    by (auto simp: not_ephemeral_def)\n  from not_ephemeralD[OF C this]\n  obtain n where n: \"0 < p x x n\" \"0 < n\" by auto\n  have C': \"C \\<in> UNIV // communicating\"\n    using C by (auto simp: not_ephemeral_def)\n\n  have \"period C \\<noteq> 0\"\n    unfolding period_eq [OF C' \\<open>x \\<in> C\\<close>]\n    using n by (auto simp: period_set_def)\n  then show ?thesis by auto\nqed\n\n\nlemma period_posD:\n  assumes C: \"C \\<in> UNIV // communicating\" and \"0 < period C\" \"x \\<in> C\"\n  shows \"\\<exists>n>0. 0 < p x x n\"\nproof -\n  from \\<open>0 < period C\\<close> have \"period C \\<noteq> 0\"\n    by auto\n  then show ?thesis\n    unfolding period_eq [OF C \\<open>x \\<in> C\\<close>]\n    unfolding period_set_def by auto\nqed\n\nlemma not_ephemeralD_pos_period':\n  assumes C: \"C \\<in> UNIV // communicating\"\n  shows \"not_ephemeral C \\<longleftrightarrow> 0 < period C\"\nproof (auto dest!: not_ephemeralD_pos_period intro: C)\n  from C not_empty_irreducible[of C] obtain x where \"x \\<in> C\"\n    by (auto simp: not_ephemeral_def)\n\n  assume \"0 < period C\"\n  then show \"not_ephemeral C\"\n    apply (auto simp: not_ephemeral_def C)\noops \\<comment> \\<open>should be easy to finish\\<close>\n\n\nlemma eventually_periodic:\n  assumes C: \"C \\<in> UNIV // communicating\" \"0 < period C\" \"x \\<in> C\"\n  shows \"eventually (\\<lambda>m. 0 < p x x (m * period C)) sequentially\"\nproof -\n  from period_posD[OF assms] obtain n where n: \"0 < p x x n\" \"0 < n\" by auto\n  have C': \"C \\<in> UNIV // communicating\"\n    using C by auto\n\n  have \"period C \\<noteq> 0\"\n    unfolding period_eq [OF C' \\<open>x \\<in> C\\<close>]\n    using n by (auto simp: period_set_def)\n  have \"eventually (\\<lambda>m. m * Gcd (period_set x) \\<in> (period_set x)) sequentially\"\n  proof (rule eventually_mult_Gcd)\n    show \"n > 0\" \"n \\<in> period_set x\"\n      using n by (auto simp add: period_set_def)\n    fix k l  assume \"k \\<in> period_set x\" \"l \\<in> period_set x\"\n    then have \"0 < p x x k * p x x l\" \"0 < l\" \"0 < k\"\n      by (auto simp: period_set_def)\n    moreover have \"p x x k * p x x l \\<le> p x x (k + l)\"\n      using prob_reachable_le[of k \"k + l\" x x x] \\<open>x \\<in> C\\<close>\n      by auto\n    ultimately show \"k + l \\<in> period_set x\"\n      using \\<open>0 < l\\<close> by (auto simp: period_set_def)\n  qed\n  with eventually_ge_at_top[of 1] show \"eventually (\\<lambda>m. 0 < p x x (m * period C)) sequentially\"\n    by eventually_elim \n       (insert \\<open>period C \\<noteq> 0\\<close> period_eq[OF C' \\<open>x \\<in> C\\<close>, symmetric], auto simp: period_set_def)\nqed\n\n\nlemma aperiodic_eventually_recurrent:\n  \"aperiodic C \\<longleftrightarrow> C \\<in> UNIV // communicating \\<and> (\\<forall>x\\<in>C. eventually (\\<lambda>m. 0 < p x x m) sequentially)\"\nproof safe\n  fix x assume \"x \\<in> C\" \"aperiodic C\"\n  with eventually_periodic[of C x]\n  show \"eventually (\\<lambda>m. 0 < p x x m) sequentially\"\n    by (auto simp add: aperiodic_def)\nnext\n  assume \"\\<forall>x\\<in>C. eventually (\\<lambda>m. 0 < p x x m) sequentially\" and C: \"C \\<in> UNIV // communicating\"\n  moreover from not_empty_irreducible[OF C] obtain x where \"x \\<in> C\" by auto\n  ultimately obtain N where \"\\<And>M.  M\\<ge>N \\<Longrightarrow> 0 < p x x M\"\n    by (auto simp: eventually_sequentially)\n  then have \"{N <..} \\<subseteq> period_set x\"\n    by (auto simp: period_set_def)\n  from C show \"aperiodic C\"\n    unfolding period_eq [OF C \\<open>x \\<in> C\\<close>] aperiodic_def\n  proof\n    show \"Gcd (period_set x) = 1\"\n    proof (rule Gcd_eqI)\n      from one_dvd show \"1 dvd q\" for q :: nat .\n      fix m\n      assume \"\\<And>q. q \\<in> period_set x \\<Longrightarrow> m dvd q\"\n      moreover from \\<open>{N <..} \\<subseteq> period_set x\\<close>\n      have \"{Suc N, Suc (Suc N)} \\<subseteq> period_set x\"\n        by auto\n      ultimately have \"m dvd Suc (Suc N)\" and \"m dvd Suc N\"\n        by auto\n      then have \"m dvd Suc (Suc N) - Suc N\"\n        by (rule dvd_diff_nat)\n      then show \"is_unit m\"\n        by simp\n    qed simp\n  qed\nqed (simp add: aperiodic_def)\n\nlemma stationary_distributionD_emeasure:\n  assumes N: \"stationary_distribution N\"\n  shows \"emeasure N A = (\\<integral>\\<^sup>+s. emeasure (K s) A \\<partial>N)\"\nproof -\n  have \"prob_space (measure_pmf N)\"\n    by intro_locales\n  then interpret subprob_space \"measure_pmf N\"\n    by (rule prob_space_imp_subprob_space)\n  show ?thesis\n    unfolding measure_pmf.emeasure_eq_measure\n    apply (subst N[unfolded stationary_distribution_def])\n    apply (simp add: measure_pmf_bind)\n    apply (subst measure_pmf.measure_bind[where N=\"count_space UNIV\"])\n    apply (rule measurable_compose[OF _ measurable_measure_pmf])\n    apply (auto intro!: nn_integral_eq_integral[symmetric] measure_pmf.integrable_const_bound[where B=1])\n    done\nqed\n\nlemma communicatingD1:\n  \"C \\<in> UNIV // communicating \\<Longrightarrow> (a, b) \\<in> communicating \\<Longrightarrow> a \\<in> C \\<Longrightarrow> b \\<in> C\"\n  by (auto elim!: quotientE) (auto simp add: communicating_def)\n\nlemma communicatingD2:\n  \"C \\<in> UNIV // communicating \\<Longrightarrow> (a, b) \\<in> communicating \\<Longrightarrow> b \\<in> C \\<Longrightarrow> a \\<in> C\"\n  by (auto elim!: quotientE) (auto simp add: communicating_def)\n\nlemma acc_iff: \"(x, y) \\<in> acc \\<longleftrightarrow> (\\<exists>n. 0 < p x y n)\"\n  by (blast intro: accD_pos accI_pos)\n\nlemma communicating_iff: \"(x, y) \\<in> communicating \\<longleftrightarrow> (\\<exists>n. 0 < p x y n) \\<and> (\\<exists>n. 0 < p y x n)\"\n  by (auto simp add: acc_iff communicating_def)\n\nend\n\ncontext MC_pair\nbegin\n\nlemma p_eq_p1_p2:\n  \"p (x1, x2) (y1, y2) n = K1.p x1 y1 n * K2.p x2 y2 n\"\n  unfolding p_def K1.p_def K2.p_def\n  by (subst prod_eq_prob_T)\n     (auto intro!: arg_cong2[where f=measure] split: nat.splits simp: Stream_snth)\n\nlemma P_accD:\n  assumes \"((x1, x2), (y1, y2)) \\<in> acc\"shows \"(x1, y1) \\<in> K1.acc\" \"(x2, y2) \\<in> K2.acc\"\n  using assms by (auto simp: acc_iff K1.acc_iff K2.acc_iff p_eq_p1_p2 zero_less_mult_iff not_le[of 0, symmetric]\n                       cong: conj_cong)\n\nlemma aperiodicI_pair:\n  assumes C1: \"K1.aperiodic C1\" and C2: \"K2.aperiodic C2\"\n  shows \"aperiodic (C1 \\<times> C2)\"\n  unfolding aperiodic_eventually_recurrent\nproof safe\n  from C1[unfolded K1.aperiodic_eventually_recurrent] C2[unfolded K2.aperiodic_eventually_recurrent]\n  have C1: \"C1 \\<in> UNIV // K1.communicating\" and C2: \"C2 \\<in> UNIV // K2.communicating\" and\n    ev: \"\\<And>x. x \\<in> C1 \\<Longrightarrow> eventually (\\<lambda>m. 0 < K1.p x x m) sequentially\" \"\\<And>x. x \\<in> C2 \\<Longrightarrow> eventually (\\<lambda>m. 0 < K2.p x x m) sequentially\"\n    by auto\n  { fix x1 x2 assume x: \"x1 \\<in> C1\" \"x2 \\<in> C2\"\n    from ev(1)[OF x(1)] ev(2)[OF x(2)]\n    show \"eventually (\\<lambda>m. 0 < p (x1, x2) (x1, x2) m) sequentially\"\n       by eventually_elim  (simp add: p_eq_p1_p2 x) }\n\n  { fix x1 x2 y1 y2\n    assume acc: \"(x1, y1) \\<in> K1.acc\" \"(x2, y2) \\<in> K2.acc\" \"x1 \\<in> C1\" \"y1 \\<in> C1\" \"x2 \\<in> C2\" \"y2 \\<in> C2\"\n    then obtain k l where \"0 < K1.p x1 y1 l\" \"0 < K2.p x2 y2 k\"\n      by (auto dest!: K1.accD_pos K2.accD_pos)\n    with acc ev(1)[of y1] ev(2)[of y2]\n    have \"eventually (\\<lambda>m. 0 < K1.p x1 y1 l * K1.p y1 y1 m \\<and> 0 < K2.p x2 y2 k * K2.p y2 y2 m) sequentially\"\n      by (auto elim: eventually_elim2)\n    then have \"eventually (\\<lambda>m. 0 < K1.p x1 y1 (m + l) \\<and> 0 < K2.p x2 y2 (m + k)) sequentially\"\n    proof eventually_elim\n      fix m assume \"0 < K1.p x1 y1 l * K1.p y1 y1 m \\<and> 0 < K2.p x2 y2 k * K2.p y2 y2 m\"\n      with acc\n        K1.prob_reachable_le[of l \"l + m\" x1 y1 y1]\n        K2.prob_reachable_le[of k \"k + m\" x2 y2 y2]\n      show \"0 < K1.p x1 y1 (m + l) \\<and> 0 < K2.p x2 y2 (m + k)\"\n        by (auto simp add: ac_simps)\n    qed\n    then have \"eventually (\\<lambda>m. 0 < K1.p x1 y1 m \\<and> 0 < K2.p x2 y2 m) sequentially\"\n      unfolding eventually_conj_iff by (subst (asm) (1 2) eventually_sequentially_seg) (auto elim: eventually_elim2)\n    then obtain N where \"0 < K1.p x1 y1 N\" \"0 < K2.p x2 y2 N\"\n      by (auto simp: eventually_sequentially)\n    with acc have \"0 < p (x1, x2) (y1, y2) N\"\n      by (auto simp add: p_eq_p1_p2)\n    with acc have \"((x1, x2), (y1, y2)) \\<in> acc\"\n      by (auto intro!: accI_pos) }\n  note 1 = this\n\n  { fix x1 x2 y1 y2 assume acc:\"((x1, x2), (y1, y2)) \\<in> acc\"\n    moreover from acc obtain k where \"0 < p (x1, x2) (y1, y2) k\" by (auto dest!: accD_pos)\n    ultimately have \"(x1, y1) \\<in> K1.acc \\<and> (x2, y2) \\<in> K2.acc\"\n      by (subst (asm) p_eq_p1_p2)\n         (auto intro!: K1.accI_pos K2.accI_pos simp: zero_less_mult_iff not_le[of 0, symmetric]) }\n  note 2 = this\n\n  from K1.not_empty_irreducible[OF C1] K2.not_empty_irreducible[OF C2]\n  obtain x1 x2 where xC: \"x1 \\<in> C1\" \"x2 \\<in> C2\" by auto\n  show \"C1 \\<times> C2 \\<in> UNIV // communicating\"\n    apply (simp add: quotient_def Image_def)\n    apply (safe intro!: exI[of _ x1] exI[of _ x2])\n  proof -\n    fix y1 y2 assume yC: \"y1 \\<in> C1\" \"y2 \\<in> C2\"\n    from K1.irreducibleD[OF C1 \\<open>x1 \\<in> C1\\<close> \\<open>y1 \\<in> C1\\<close>] K2.irreducibleD[OF C2 \\<open>x2 \\<in> C2\\<close> \\<open>y2 \\<in> C2\\<close>]\n    show \"((x1, x2), (y1, y2)) \\<in> communicating\"\n      using 1[of x1 y1 x2 y2] 1[of y1 x1 y2 x2] xC yC\n      by (auto simp: communicating_def K1.communicating_def K2.communicating_def)\n  next\n    fix y1 y2 assume \"((x1, x2), (y1, y2)) \\<in> communicating\"\n    with 2[of x1 x2 y1 y2] 2[of y1 y2 x1 x2]\n    have \"(x1, y1) \\<in> K1.communicating\" \"(x2, y2) \\<in> K2.communicating\"\n      by (auto simp: communicating_def K1.communicating_def K2.communicating_def)\n    with xC show \"y1 \\<in> C1\" \"y2 \\<in> C2\"\n      using K1.communicatingD1[OF C1] K2.communicatingD1[OF C2] by auto\n  qed\nqed\n\nlemma stationary_distributionI_pair:\n  assumes N1: \"K1.stationary_distribution N1\"\n  assumes N2: \"K2.stationary_distribution N2\"\n  shows \"stationary_distribution (pair_pmf N1 N2)\"\n  unfolding stationary_distribution_def\n  unfolding Kp_def pair_pmf_def\n  apply (subst N1[unfolded K1.stationary_distribution_def])\n  apply (subst N2[unfolded K2.stationary_distribution_def])\n  apply (simp add: bind_assoc_pmf bind_return_pmf)\n  apply (subst bind_commute_pmf[of N2])\n  apply simp\n  done\n\nend\n\ncontext MC_syntax\nbegin\n\nlemma stationary_distribution_imp_limit:\n  assumes C: \"aperiodic C\" \"essential_class C\" \"countable C\" and N: \"stationary_distribution N\" \"N \\<subseteq> C\"\n  assumes [simp]: \"y \\<in> C\"\n  shows \"(\\<lambda>n. \\<integral>x. \\<bar>p y x n - pmf N x\\<bar> \\<partial>count_space C) \\<longlonglongrightarrow> 0\"\n    (is \"?L \\<longlonglongrightarrow> 0\")\nproof -\n  from \\<open>essential_class C\\<close> have C_comm: \"C \\<in> UNIV // communicating\"\n    by (simp add: essential_class_def)\n\n  define K' where \"K' = (\\<lambda>Some x \\<Rightarrow> map_pmf Some (K x) | None \\<Rightarrow> map_pmf Some N)\"\n\n  interpret K2: MC_syntax K' .\n  interpret KN: MC_pair K K' .\n\n  from stationary_distributionD[OF C(2,3) N]\n  have pos: \"\\<And>x. x \\<in> C \\<Longrightarrow> pos_recurrent x\" and \"measure_pmf N = stat C\" by auto\n\n  have pos: \"\\<And>x. x \\<in> C \\<Longrightarrow> 0 < emeasure N {x}\"\n    using pos unfolding stat_def \\<open>measure_pmf N = stat C\\<close>\n    by (subst emeasure_point_measure_finite2)\n       (auto simp: U'_def pos_recurrent_def nn_integral_add ennreal_zero_less_divide less_top)\n  then have rpos: \"\\<And>x. x \\<in> C \\<Longrightarrow> 0 < pmf N x\"\n    by (simp add: measure_pmf.emeasure_eq_measure pmf.rep_eq)\n\n  have eq: \"\\<And>x y. (if x = y then 1 else 0) = indicator {y} x\" by auto\n\n  have intK: \"\\<And>f x. (\\<integral>x. (f x :: real) \\<partial>K' (Some x)) = (\\<integral>x. f (Some x) \\<partial>K x)\"\n    by (simp add: K'_def integral_distr map_pmf_rep_eq)\n\n  { fix m and x y :: 's\n    have \"K2.p (Some x) (Some y) m = p x y m\"\n      by (induct m arbitrary: x)\n         (auto intro!: integral_cong simp add: K2.p_Suc' p_Suc' intK K2.p_0 p_0) }\n  note K_p_eq = this\n\n  { fix n and x :: 's have \"K2.p (Some x) None n = 0\"\n      by (induct n arbitrary: x) (auto simp: K2.p_Suc' K2.p_0 intK cong: integral_cong) }\n  note K_S_None = this\n\n  from not_empty_irreducible[OF C_comm] obtain c0 where c0: \"c0 \\<in> C\" by auto\n\n  have K2_acc: \"\\<And>x y. (Some x, y) \\<in> K2.acc \\<longleftrightarrow> (\\<exists>z. y = Some z \\<and> (x, z) \\<in> acc)\"\n    apply (auto simp: K2.acc_iff acc_iff K_p_eq)\n    apply (case_tac y)\n    apply (auto simp: K_p_eq K_S_None)\n    done\n\n  have K2_communicating: \"\\<And>c x. c \\<in> C \\<Longrightarrow> (Some c, x) \\<in> K2.communicating \\<longleftrightarrow> (\\<exists>c'\\<in>C. x = Some c')\"\n  proof safe\n    fix x c assume \"c \\<in> C\" \"(Some c, x) \\<in> K2.communicating\"\n    then show \"\\<exists>c'\\<in>C. x = Some c'\"\n      by (cases x)\n         (auto simp: communicating_iff K2.communicating_iff K_p_eq K_S_None intro!: irreducibleD2[OF C_comm \\<open>c\\<in>C\\<close>])\n  next\n    fix c c' x assume \"c \\<in> C\" \"c' \\<in> C\"\n    with irreducibleD[OF C_comm this] show \"(Some c, Some c') \\<in> K2.communicating\"\n      by (auto simp: K2.communicating_iff communicating_iff K_p_eq)\n  qed\n\n  have \"Some ` C \\<in> UNIV // K2.communicating\"\n    by (auto simp add: quotient_def Image_def c0 K2_communicating\n             intro!: exI[of _ \"Some c0\"])\n  then have \"K2.essential_class (Some ` C)\"\n    by (rule K2.essential_classI)\n       (auto simp: K2_acc essential_classD2[OF \\<open>essential_class C\\<close>])\n\n  have \"K2.aperiodic (Some ` C)\"\n    unfolding K2.aperiodic_eventually_recurrent\n  proof safe\n    fix x assume \"x \\<in> C\" then show \"eventually (\\<lambda>m. 0 < K2.p (Some x) (Some x) m) sequentially\"\n      using \\<open>aperiodic C\\<close> unfolding aperiodic_eventually_recurrent\n      by (auto elim!: eventually_mono simp: K_p_eq)\n  qed fact\n  then have aperiodic: \"KN.aperiodic (C \\<times> Some ` C)\"\n    by (rule KN.aperiodicI_pair[OF \\<open>aperiodic C\\<close>])\n\n  have KN_essential: \"KN.essential_class (C \\<times> Some ` C)\"\n  proof (rule KN.essential_classI)\n    show \"C \\<times> Some ` C \\<in> UNIV // KN.communicating\"\n      using aperiodic by (simp add: KN.aperiodic_def)\n  next\n    fix x y assume \"x \\<in> C \\<times> Some ` C\" \"(x, y) \\<in> KN.acc\"\n    with KN.P_accD[of \"fst x\" \"snd x\" \"fst y\" \"snd y\"]\n    show \"y \\<in> C \\<times> Some ` C\"\n      by (cases x y rule: prod.exhaust[case_product prod.exhaust])\n         (auto simp: K2_acc essential_classD2[OF \\<open>essential_class C\\<close>])\n  qed\n\n  { fix n and x y :: 's\n    have \"measure N {y} = \\<P>(\\<omega> in K2.T None. (None ## \\<omega>) !! (Suc n) = Some y)\"\n      unfolding stationary_distribution_iterate'[OF N(1), of y n]\n      apply (subst K2.p_def[symmetric])\n      apply (subst K2.p_Suc')\n      apply (subst K'_def)\n      apply (simp add: map_pmf_rep_eq integral_distr K_p_eq)\n      done\n    then have \"measure N {y} = \\<P>(\\<omega> in K2.T None. \\<omega> !! n = Some y)\"\n      by simp }\n  note measure_y_eq = this\n\n  define D where \"D = {x::'s \\<times> 's option. Some (fst x) = snd x}\"\n\n  have [measurable]:\n    \"\\<And>P::('s \\<times> 's option \\<Rightarrow> bool). P \\<in> measurable (count_space UNIV) (count_space UNIV)\"\n    by simp\n\n  { fix n and x :: 's\n    have \"\\<P>(\\<omega> in KN.T (y, None). \\<exists>i<n. snd (\\<omega> !! n) = Some x \\<and> ev_at (HLD D) i \\<omega>) =\n      (\\<Sum>i<n. \\<P>(\\<omega> in KN.T (y, None). snd (\\<omega> !! n) = Some x \\<and> ev_at (HLD D) i \\<omega>))\"\n      by (subst KN.T.finite_measure_finite_Union[symmetric])\n         (auto simp: disjoint_family_on_def intro!: arg_cong2[where f=measure] dest: ev_at_unique)\n    also have \"\\<dots> = (\\<Sum>i<n. \\<P>(\\<omega> in KN.T (y, None). fst (\\<omega> !! n) = x \\<and> ev_at (HLD D) i \\<omega>))\"\n    proof (intro sum.cong refl)\n      fix i assume i: \"i \\<in> {..< n}\"\n      show \"\\<P>(\\<omega> in KN.T (y, None). snd (\\<omega> !! n) = Some x \\<and> ev_at (HLD D) i \\<omega>) =\n        \\<P>(\\<omega> in KN.T (y, None). fst (\\<omega> !! n) = x \\<and> ev_at (HLD D) i \\<omega>)\"\n        apply (subst (1 2) KN.prob_T_split[where n=\"Suc i\"])\n        apply (simp_all add: ev_at_shift snth_Stream del: stake.simps KN.space_T)\n        unfolding ev_at_shift snth_Stream\n      proof (intro Bochner_Integration.integral_cong refl)\n        fix \\<omega> :: \"('s \\<times> 's option) stream\" let ?s = \"\\<lambda>\\<omega>'. stake (Suc i) \\<omega> @- \\<omega>'\"\n        show \"\\<P>(\\<omega>' in KN.T (\\<omega> !! i). snd (?s \\<omega>' !! n) = Some x \\<and> ev_at (HLD D) i \\<omega>) =\n          \\<P>(\\<omega>' in KN.T (\\<omega> !! i). fst (?s \\<omega>' !! n) = x \\<and> ev_at (HLD D) i \\<omega>)\"\n        proof cases\n          assume \"ev_at (HLD D) i \\<omega>\"\n          from ev_at_imp_snth[OF this]\n          have eq: \"snd (\\<omega> !! i) = Some (fst (\\<omega> !! i))\"\n            by (simp add: D_def HLD_iff)\n\n          have \"\\<P>(\\<omega>' in KN.T (\\<omega> !! i). fst (\\<omega>' !! (n - Suc i)) = x) =\n            \\<P>(\\<omega>' in T (fst (\\<omega> !! i)). \\<omega>' !! (n - Suc i) = x) * \\<P>(\\<omega>' in K2.T (snd (\\<omega> !! i)). True)\"\n            by (subst KN.prod_eq_prob_T) simp_all\n          also have \"\\<dots> = p (fst (\\<omega> !! i)) x (Suc (n - Suc i))\"\n            using K2.T.prob_space by (simp add: p_def)\n          also have \"\\<dots> = K2.p (snd (\\<omega> !! i)) (Some x) (Suc (n - Suc i))\"\n            by (simp add: K_p_eq eq)\n          also have \"\\<dots> = \\<P>(\\<omega>' in T (fst (\\<omega> !! i)). True) * \\<P>(\\<omega>' in K2.T (snd (\\<omega> !! i)). \\<omega>' !! (n - Suc i) = Some x)\"\n            using T.prob_space by (simp add: K2.p_def)\n          also have \"\\<dots> = \\<P>(\\<omega>' in KN.T (\\<omega> !! i). snd (\\<omega>' !! (n - Suc i)) = Some x)\"\n            by (subst KN.prod_eq_prob_T) simp_all\n          finally show ?thesis using \\<open>ev_at (HLD D) i \\<omega>\\<close> i\n            by (simp del: stake.simps)\n        qed simp\n      qed\n    qed\n    also have \"\\<dots> = \\<P>(\\<omega> in KN.T (y, None). (\\<exists>i<n. fst (\\<omega> !! n) = x \\<and> ev_at (HLD D) i \\<omega>))\"\n      by (subst KN.T.finite_measure_finite_Union[symmetric])\n         (auto simp add: disjoint_family_on_def dest: ev_at_unique\n               intro!: arg_cong2[where f=measure])\n    finally have eq: \"\\<P>(\\<omega> in KN.T (y, None). (\\<exists>i<n. snd (\\<omega> !! n) = Some x \\<and> ev_at (HLD D) i \\<omega>)) =\n      \\<P>(\\<omega> in KN.T (y, None). (\\<exists>i<n. fst (\\<omega> !! n) = x \\<and> ev_at (HLD D) i \\<omega>))\" .\n\n    have \"p y x (Suc n) - measure N {x} = \\<P>(\\<omega> in T y. \\<omega> !! n = x) - \\<P>(\\<omega> in K2.T None. \\<omega> !! n = Some x)\"\n      unfolding p_def by (subst measure_y_eq) simp_all\n    also have \"\\<P>(\\<omega> in T y. \\<omega> !! n = x) = \\<P>(\\<omega> in T y. \\<omega> !! n = x) * \\<P>(\\<omega> in K2.T None. True)\"\n      using K2.T.prob_space by simp\n    also have \"\\<dots> = \\<P>(\\<omega> in KN.T (y, None). fst (\\<omega> !! n) = x)\"\n      by (subst KN.prod_eq_prob_T) auto\n    also have \"\\<dots> = \\<P>(\\<omega> in KN.T (y, None). (\\<exists>i<n. fst (\\<omega> !! n) = x \\<and> ev_at (HLD D) i \\<omega>)) +\n      \\<P>(\\<omega> in KN.T (y, None). fst (\\<omega> !! n) = x \\<and> \\<not> (\\<exists>i<n. ev_at (HLD D) i \\<omega>))\"\n      by (subst KN.T.finite_measure_Union[symmetric])\n         (auto intro!: arg_cong2[where f=measure])\n    also have \"\\<P>(\\<omega> in K2.T None. \\<omega> !! n = Some x) = \\<P>(\\<omega> in T y. True) * \\<P>(\\<omega> in K2.T None. \\<omega> !! n = Some x)\"\n      using T.prob_space by simp\n    also have \"\\<dots> = \\<P>(\\<omega> in KN.T (y, None). snd (\\<omega> !! n) = Some x)\"\n      by (subst KN.prod_eq_prob_T) auto\n    also have \"\\<dots> = \\<P>(\\<omega> in KN.T (y, None). (\\<exists>i<n. snd (\\<omega> !! n) = Some x \\<and> ev_at (HLD D) i \\<omega>)) +\n      \\<P>(\\<omega> in KN.T (y, None). snd (\\<omega> !! n) = Some x \\<and> \\<not> (\\<exists>i<n. ev_at (HLD D) i \\<omega>))\"\n      by (subst KN.T.finite_measure_Union[symmetric])\n         (auto intro!: arg_cong2[where f=measure])\n    finally have \"\\<bar> p y x (Suc n) - measure N {x} \\<bar> =\n      \\<bar> \\<P>(\\<omega> in KN.T (y, None). fst (\\<omega> !! n) = x \\<and> \\<not> (\\<exists>i<n. ev_at (HLD D) i \\<omega>)) -\n      \\<P>(\\<omega> in KN.T (y, None). snd (\\<omega> !! n) = Some x \\<and> \\<not> (\\<exists>i<n. ev_at (HLD D) i \\<omega>)) \\<bar>\"\n      unfolding eq by (simp add: field_simps)\n    also have \"\\<dots> \\<le> \\<bar> \\<P>(\\<omega> in KN.T (y, None). fst (\\<omega> !! n) = x \\<and> \\<not> (\\<exists>i<n. ev_at (HLD D) i \\<omega>)) \\<bar> +\n      \\<bar> \\<P>(\\<omega> in KN.T (y, None). snd (\\<omega> !! n) = Some x \\<and> \\<not> (\\<exists>i<n. ev_at (HLD D) i \\<omega>)) \\<bar>\"\n      by (rule abs_triangle_ineq4)\n    also have \"\\<dots> \\<le> \\<P>(\\<omega> in KN.T (y, None). fst (\\<omega> !! n) = x \\<and> \\<not> (\\<exists>i<n. ev_at (HLD D) i \\<omega>)) +\n      \\<P>(\\<omega> in KN.T (y, None). snd (\\<omega> !! n) = Some x \\<and> \\<not> (\\<exists>i<n. ev_at (HLD D) i \\<omega>))\"\n      by simp\n    finally have \"\\<bar> p y x (Suc n) - measure N {x} \\<bar> \\<le> \\<dots>\" . }\n  note mono = this\n\n  { fix n :: nat\n    have \"(\\<integral>\\<^sup>+x. \\<bar> p y x (Suc n) - measure N {x} \\<bar> \\<partial>count_space C) \\<le>\n      (\\<integral>\\<^sup>+x. ennreal (\\<P>(\\<omega> in KN.T (y, None). fst (\\<omega> !! n) = x \\<and> \\<not> (\\<exists>i<n. ev_at (HLD D) i \\<omega>))) +\n      ennreal (\\<P>(\\<omega> in KN.T (y, None). snd (\\<omega> !! n) = Some x \\<and> \\<not> (\\<exists>i<n. ev_at (HLD D) i \\<omega>))) \\<partial>count_space C)\"\n      using mono by (intro nn_integral_mono) (simp add: ennreal_plus[symmetric] del: ennreal_plus)\n    also have \"\\<dots> = (\\<integral>\\<^sup>+x. \\<P>(\\<omega> in KN.T (y, None). fst (\\<omega> !! n) = x \\<and> \\<not> (\\<exists>i<n. ev_at (HLD D) i \\<omega>)) \\<partial>count_space C) +\n      (\\<integral>\\<^sup>+x. \\<P>(\\<omega> in KN.T (y, None). snd (\\<omega> !! n) = Some x \\<and> \\<not> (\\<exists>i<n. ev_at (HLD D) i \\<omega>)) \\<partial>count_space C)\"\n      by (subst nn_integral_add) auto\n    also have \"\\<dots> = emeasure (KN.T (y, None)) (\\<Union>x\\<in>C. {\\<omega>\\<in>space (KN.T (y, None)). fst (\\<omega> !! n) = x \\<and> \\<not> (\\<exists>i<n. ev_at (HLD D) i \\<omega>)}) +\n      emeasure (KN.T (y, None)) (\\<Union>x\\<in>C. {\\<omega>\\<in>space (KN.T (y, None)). snd (\\<omega> !! n) = Some x \\<and> \\<not> (\\<exists>i<n. ev_at (HLD D) i \\<omega>)})\"\n      by (subst (1 2) emeasure_UN_countable)\n         (auto simp add: disjoint_family_on_def KN.T.emeasure_eq_measure C)\n    also have \"\\<dots> \\<le> ennreal (\\<P>(\\<omega> in KN.T (y, None). \\<not> (\\<exists>i<n. ev_at (HLD D) i \\<omega>))) + ennreal (\\<P>(\\<omega> in KN.T (y, None). \\<not> (\\<exists>i<n. ev_at (HLD D) i \\<omega>)))\"\n      unfolding KN.T.emeasure_eq_measure\n      by (intro add_mono) (auto intro!: KN.T.finite_measure_mono)\n    also have \"\\<dots> \\<le> 2 * \\<P>(\\<omega> in KN.T (y, None). \\<not> (\\<exists>i<n. ev_at (HLD D) i \\<omega>))\"\n      by (simp add: ennreal_plus[symmetric] del: ennreal_plus)\n    finally have \"?L (Suc n) \\<le> 2 * \\<P>(\\<omega> in KN.T (y, None). \\<not> (\\<exists>i<n. ev_at (HLD D) i \\<omega>))\"\n      by (auto intro!: integral_real_bounded simp add: pmf.rep_eq) }\n  note le_2 = this\n\n  have c0_D: \"(c0, Some c0) \\<in> D\"\n    by (simp add: D_def c0)\n\n  let ?N' = \"map_pmf Some N\"\n  interpret NP: pair_prob_space N ?N' ..\n\n  have pos_recurrent: \"\\<forall>x\\<in>C \\<times> Some ` C. KN.pos_recurrent x\"\n  proof (rule KN.stationary_distributionD(1)[OF KN_essential _ KN.stationary_distributionI_pair[OF N(1)]])\n    show \"K2.stationary_distribution ?N'\"\n      unfolding K2.stationary_distribution_def\n      by (subst N(1)[unfolded stationary_distribution_def])\n         (auto intro!: bind_pmf_cong simp: K'_def map_pmf_def bind_assoc_pmf bind_return_pmf)\n    show \"countable (C \\<times> Some`C)\"\n      using C by auto\n    show \"set_pmf (pair_pmf N (map_pmf Some N)) \\<subseteq> C \\<times> Some ` C\"\n      using \\<open>N \\<subseteq> C\\<close> by auto\n  qed\n\n  from c0_D have \"\\<P>(\\<omega> in KN.T (y, None). alw (not (HLD D)) \\<omega>) \\<le> \\<P>(\\<omega> in KN.T (y, None). alw (not (HLD {(c0, Some c0)})) \\<omega>)\"\n    apply (auto intro!: KN.T.finite_measure_mono)\n    apply (rule alw_mono, assumption)\n    apply (auto simp: HLD_iff)\n    done\n  also have \"\\<dots> = 0\"\n    apply (rule KN.T.prob_eq_0_AE)\n    apply (simp add: not_ev_iff[symmetric])\n    apply (subst KN.AE_T_iff)\n    apply simp\n  proof\n    fix t assume t: \"t \\<in> KN.Kp (y, None)\"\n    then obtain a b where t_eq: \"t = (a, Some b)\" \"a \\<in> K y\" \"b \\<in> N\"\n      unfolding KN.Kp_def by (auto simp: K'_def)\n    with \\<open>y \\<in> C\\<close> have \"a \\<in> C\"\n      using essential_classD2[OF \\<open>essential_class C\\<close> \\<open>y \\<in> C\\<close>] by auto\n    have \"b \\<in> C\"\n      using \\<open>N \\<subseteq> C\\<close> \\<open>b \\<in> N\\<close> by auto\n\n    from pos_recurrent[THEN bspec, of \"(c0, Some c0)\"]\n    have recurrent_c0: \"KN.recurrent (c0, Some c0)\"\n      by (simp add: KN.pos_recurrent_def c0)\n    have \"C \\<times> Some ` C \\<in> UNIV // KN.communicating\"\n      using aperiodic by (simp add: KN.aperiodic_def)\n    then have \"((c0, Some c0), t) \\<in> KN.communicating\"\n      by (rule KN.irreducibleD) (simp_all add: t_eq c0 \\<open>b \\<in> C\\<close> \\<open>a \\<in> C\\<close>)\n    then have \"((c0, Some c0), t) \\<in> KN.acc\"\n      by (simp add: KN.communicating_def)\n    then have \"KN.U t (c0, Some c0) = 1\"\n      by (rule KN.recurrent_acc(1)[OF recurrent_c0])\n    then show \"AE \\<omega> in KN.T t. ev (HLD {(c0, Some c0)}) (t ## \\<omega>)\"\n      unfolding KN.U_def by (subst (asm) KN.T.prob_Collect_eq_1) (auto simp add: ev_Stream)\n  qed\n  finally have \"\\<P>(\\<omega> in KN.T (y, None). alw (not (HLD D)) \\<omega>) = 0\"\n    by (intro antisym measure_nonneg)\n\n  have \"(\\<lambda>n. \\<P>(\\<omega> in KN.T (y, None). \\<not> (\\<exists>i<n. ev_at (HLD D) i \\<omega>))) \\<longlonglongrightarrow>\n    measure (KN.T (y, None)) (\\<Inter>n. {\\<omega>\\<in>space (KN.T (y, None)). \\<not> (\\<exists>i<n. ev_at (HLD D) i \\<omega>)})\"\n    by (rule KN.T.finite_Lim_measure_decseq) (auto simp: decseq_def)\n  also have \"(\\<Inter>n. {\\<omega>\\<in>space (KN.T (y, None)). \\<not> (\\<exists>i<n. ev_at (HLD D) i \\<omega>)}) =\n    {\\<omega>\\<in>space (KN.T (y, None)). alw (not (HLD D)) \\<omega>}\"\n    by (auto simp: not_ev_iff[symmetric] ev_iff_ev_at)\n  also have \"\\<P>(\\<omega> in KN.T (y, None). alw (not (HLD D)) \\<omega>) = 0\" by fact\n  finally have *: \"(\\<lambda>n. 2 * \\<P>(\\<omega> in KN.T (y, None). \\<not> (\\<exists>i<n. ev_at (HLD D) i \\<omega>))) \\<longlonglongrightarrow> 0\"\n    by (intro tendsto_eq_intros) auto\n\n  show ?thesis\n    apply (rule LIMSEQ_imp_Suc)\n    apply (rule tendsto_sandwich[OF _ _ tendsto_const *])\n    using le_2\n    apply (simp_all add: integral_nonneg_AE)\n    done\nqed\n\nlemma stationary_distribution_imp_p_limit:\n  assumes \"aperiodic C\" \"essential_class C\" and [simp]: \"countable C\"\n  assumes N: \"stationary_distribution N\" \"N \\<subseteq> C\"\n  assumes [simp]: \"x \\<in> C\" \"y \\<in> C\"\n  shows \"p x y \\<longlonglongrightarrow> pmf N y\"\nproof -\n  define D where \"D y n = \\<bar>p x y n - pmf N y\\<bar>\" for y n\n\n  from stationary_distribution_imp_limit[OF assms(1,2,3,4,5,6)]\n  have INT: \"(\\<lambda>n. \\<integral>y. D y n \\<partial>count_space C) \\<longlonglongrightarrow> 0\"\n    unfolding D_def .\n\n  { fix n\n    have \"D y n \\<le> (\\<integral>z. D y n * indicator {y} z \\<partial>count_space C)\"\n      by simp\n    also have \"\\<dots> \\<le> (\\<integral>y. D y n \\<partial>count_space C)\"\n      by (intro integral_mono)\n         (auto split: split_indicator simp: D_def p_def disjoint_family_on_def\n               intro!: Bochner_Integration.integrable_diff integrable_pmf T.integrable_measure)\n    finally have \"D y n \\<le> (\\<integral>y. D y n \\<partial>count_space C)\" . }\n  note * = this\n\n  have D_nonneg: \"\\<And>n. 0 \\<le> D y n\" by (simp add: D_def)\n\n  have \"D y \\<longlonglongrightarrow> 0\"\n    by (rule tendsto_sandwich[OF _ _ tendsto_const INT])\n       (auto simp: eventually_sequentially * D_nonneg)\n  then show ?thesis\n    using Lim_null[where l=\"pmf N y\" and net=sequentially and f=\"p x y\"]\n    by (simp add: D_def [abs_def] tendsto_rabs_zero_iff)\nqed\n\nend\n\nlemma (in MC_syntax) essential_classI2:\n  assumes \"X \\<noteq> {}\"\n  assumes accI: \"\\<And>x y. x \\<in> X \\<Longrightarrow> y \\<in> X \\<Longrightarrow> (x, y) \\<in> acc\"\n  assumes ED: \"\\<And>x y. x \\<in> X \\<Longrightarrow> y \\<in> set_pmf (K x) \\<Longrightarrow> y \\<in> X\"\n  shows \"essential_class X\"\nproof (rule essential_classI)\n  { fix x y assume \"(x, y) \\<in> acc\" \"x \\<in> X\"\n    then show \"y \\<in> X\"\n      by induct (auto dest: ED)}\n  note accD = this\n\n  from \\<open>X \\<noteq> {}\\<close> obtain x where \"x \\<in> X\" by auto\n  from \\<open>x \\<in> X\\<close> show \"X \\<in> UNIV // communicating\"\n    by (auto simp add: quotient_def Image_def communicating_def accI dest: accD intro!: exI[of _ x])\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/Markov_Models/Classifying_Markov_Chain_States.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8791467706759584, "lm_q2_score": 0.84594244507642, "lm_q1q2_score": 0.7437075687666589}}
{"text": "(*\n  File:      HOL/Computational_Algebra/Squarefree.thy\n  Author:    Manuel Eberl <manuel@pruvisto.org>\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": "seL4", "repo": "isabelle", "sha": "e1ab32a3bb41728cd19541063283e37919978a4c", "save_path": "github-repos/isabelle/seL4-isabelle", "path": "github-repos/isabelle/seL4-isabelle/isabelle-e1ab32a3bb41728cd19541063283e37919978a4c/src/HOL/Computational_Algebra/Squarefree.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467675095292, "lm_q2_score": 0.8459424431344437, "lm_q1q2_score": 0.7437075643807599}}
{"text": "(*  Title:      HOL/Topological_Spaces.thy\n    Author:     Brian Huffman\n    Author:     Johannes H\u00f6lzl\n*)\n\nsection \\<open>Topological Spaces\\<close>\n\ntheory Topological_Spaces\n  imports Main\nbegin\n\nnamed_theorems continuous_intros \"structural introduction rules for continuity\"\n\nsubsection \\<open>Topological space\\<close>\n\nclass \"open\" =\n  fixes \"open\" :: \"'a set \\<Rightarrow> bool\"\n\nclass topological_space = \"open\" +\n  assumes open_UNIV [simp, intro]: \"open UNIV\"\n  assumes open_Int [intro]: \"open S \\<Longrightarrow> open T \\<Longrightarrow> open (S \\<inter> T)\"\n  assumes open_Union [intro]: \"\\<forall>S\\<in>K. open S \\<Longrightarrow> open (\\<Union>K)\"\nbegin\n\ndefinition closed :: \"'a set \\<Rightarrow> bool\"\n  where \"closed S \\<longleftrightarrow> open (- S)\"\n\nlemma open_empty [continuous_intros, intro, simp]: \"open {}\"\n  using open_Union [of \"{}\"] by simp\n\nlemma open_Un [continuous_intros, intro]: \"open S \\<Longrightarrow> open T \\<Longrightarrow> open (S \\<union> T)\"\n  using open_Union [of \"{S, T}\"] by simp\n\nlemma open_UN [continuous_intros, intro]: \"\\<forall>x\\<in>A. open (B x) \\<Longrightarrow> open (\\<Union>x\\<in>A. B x)\"\n  using open_Union [of \"B ` A\"] by simp\n\nlemma open_Inter [continuous_intros, intro]: \"finite S \\<Longrightarrow> \\<forall>T\\<in>S. open T \\<Longrightarrow> open (\\<Inter>S)\"\n  by (induct set: finite) auto\n\nlemma open_INT [continuous_intros, intro]: \"finite A \\<Longrightarrow> \\<forall>x\\<in>A. open (B x) \\<Longrightarrow> open (\\<Inter>x\\<in>A. B x)\"\n  using open_Inter [of \"B ` A\"] by simp\n\nlemma openI:\n  assumes \"\\<And>x. x \\<in> S \\<Longrightarrow> \\<exists>T. open T \\<and> x \\<in> T \\<and> T \\<subseteq> S\"\n  shows \"open S\"\nproof -\n  have \"open (\\<Union>{T. open T \\<and> T \\<subseteq> S})\" by auto\n  moreover have \"\\<Union>{T. open T \\<and> T \\<subseteq> S} = S\" by (auto dest!: assms)\n  ultimately show \"open S\" by simp\nqed\n\nlemma closed_empty [continuous_intros, intro, simp]: \"closed {}\"\n  unfolding closed_def by simp\n\nlemma closed_Un [continuous_intros, intro]: \"closed S \\<Longrightarrow> closed T \\<Longrightarrow> closed (S \\<union> T)\"\n  unfolding closed_def by auto\n\nlemma closed_UNIV [continuous_intros, intro, simp]: \"closed UNIV\"\n  unfolding closed_def by simp\n\nlemma closed_Int [continuous_intros, intro]: \"closed S \\<Longrightarrow> closed T \\<Longrightarrow> closed (S \\<inter> T)\"\n  unfolding closed_def by auto\n\nlemma closed_INT [continuous_intros, intro]: \"\\<forall>x\\<in>A. closed (B x) \\<Longrightarrow> closed (\\<Inter>x\\<in>A. B x)\"\n  unfolding closed_def by auto\n\nlemma closed_Inter [continuous_intros, intro]: \"\\<forall>S\\<in>K. closed S \\<Longrightarrow> closed (\\<Inter>K)\"\n  unfolding closed_def uminus_Inf by auto\n\nlemma closed_Union [continuous_intros, intro]: \"finite S \\<Longrightarrow> \\<forall>T\\<in>S. closed T \\<Longrightarrow> closed (\\<Union>S)\"\n  by (induct set: finite) auto\n\nlemma closed_UN [continuous_intros, intro]:\n  \"finite A \\<Longrightarrow> \\<forall>x\\<in>A. closed (B x) \\<Longrightarrow> closed (\\<Union>x\\<in>A. B x)\"\n  using closed_Union [of \"B ` A\"] by simp\n\nlemma open_closed: \"open S \\<longleftrightarrow> closed (- S)\"\n  by (simp add: closed_def)\n\nlemma closed_open: \"closed S \\<longleftrightarrow> open (- S)\"\n  by (rule closed_def)\n\nlemma open_Diff [continuous_intros, intro]: \"open S \\<Longrightarrow> closed T \\<Longrightarrow> open (S - T)\"\n  by (simp add: closed_open Diff_eq open_Int)\n\nlemma closed_Diff [continuous_intros, intro]: \"closed S \\<Longrightarrow> open T \\<Longrightarrow> closed (S - T)\"\n  by (simp add: open_closed Diff_eq closed_Int)\n\nlemma open_Compl [continuous_intros, intro]: \"closed S \\<Longrightarrow> open (- S)\"\n  by (simp add: closed_open)\n\nlemma closed_Compl [continuous_intros, intro]: \"open S \\<Longrightarrow> closed (- S)\"\n  by (simp add: open_closed)\n\nlemma open_Collect_neg: \"closed {x. P x} \\<Longrightarrow> open {x. \\<not> P x}\"\n  unfolding Collect_neg_eq by (rule open_Compl)\n\nlemma open_Collect_conj:\n  assumes \"open {x. P x}\" \"open {x. Q x}\"\n  shows \"open {x. P x \\<and> Q x}\"\n  using open_Int[OF assms] by (simp add: Int_def)\n\nlemma open_Collect_disj:\n  assumes \"open {x. P x}\" \"open {x. Q x}\"\n  shows \"open {x. P x \\<or> Q x}\"\n  using open_Un[OF assms] by (simp add: Un_def)\n\nlemma open_Collect_ex: \"(\\<And>i. open {x. P i x}) \\<Longrightarrow> open {x. \\<exists>i. P i x}\"\n  using open_UN[of UNIV \"\\<lambda>i. {x. P i x}\"] unfolding Collect_ex_eq by simp\n\nlemma open_Collect_imp: \"closed {x. P x} \\<Longrightarrow> open {x. Q x} \\<Longrightarrow> open {x. P x \\<longrightarrow> Q x}\"\n  unfolding imp_conv_disj by (intro open_Collect_disj open_Collect_neg)\n\nlemma open_Collect_const: \"open {x. P}\"\n  by (cases P) auto\n\nlemma closed_Collect_neg: \"open {x. P x} \\<Longrightarrow> closed {x. \\<not> P x}\"\n  unfolding Collect_neg_eq by (rule closed_Compl)\n\nlemma closed_Collect_conj:\n  assumes \"closed {x. P x}\" \"closed {x. Q x}\"\n  shows \"closed {x. P x \\<and> Q x}\"\n  using closed_Int[OF assms] by (simp add: Int_def)\n\nlemma closed_Collect_disj:\n  assumes \"closed {x. P x}\" \"closed {x. Q x}\"\n  shows \"closed {x. P x \\<or> Q x}\"\n  using closed_Un[OF assms] by (simp add: Un_def)\n\nlemma closed_Collect_all: \"(\\<And>i. closed {x. P i x}) \\<Longrightarrow> closed {x. \\<forall>i. P i x}\"\n  using closed_INT[of UNIV \"\\<lambda>i. {x. P i x}\"] by (simp add: Collect_all_eq)\n\nlemma closed_Collect_imp: \"open {x. P x} \\<Longrightarrow> closed {x. Q x} \\<Longrightarrow> closed {x. P x \\<longrightarrow> Q x}\"\n  unfolding imp_conv_disj by (intro closed_Collect_disj closed_Collect_neg)\n\nlemma closed_Collect_const: \"closed {x. P}\"\n  by (cases P) auto\n\nend\n\n\nsubsection \\<open>Hausdorff and other separation properties\\<close>\n\nclass t0_space = topological_space +\n  assumes t0_space: \"x \\<noteq> y \\<Longrightarrow> \\<exists>U. open U \\<and> \\<not> (x \\<in> U \\<longleftrightarrow> y \\<in> U)\"\n\nclass t1_space = topological_space +\n  assumes t1_space: \"x \\<noteq> y \\<Longrightarrow> \\<exists>U. open U \\<and> x \\<in> U \\<and> y \\<notin> U\"\n\ninstance t1_space \\<subseteq> t0_space\n  by standard (fast dest: t1_space)\n\nlemma separation_t1: \"x \\<noteq> y \\<longleftrightarrow> (\\<exists>U. open U \\<and> x \\<in> U \\<and> y \\<notin> U)\"\n  for x y :: \"'a::t1_space\"\n  using t1_space[of x y] by blast\n\nlemma closed_singleton [iff]: \"closed {a}\"\n  for a :: \"'a::t1_space\"\nproof -\n  let ?T = \"\\<Union>{S. open S \\<and> a \\<notin> S}\"\n  have \"open ?T\"\n    by (simp add: open_Union)\n  also have \"?T = - {a}\"\n    by (auto simp add: set_eq_iff separation_t1)\n  finally show \"closed {a}\"\n    by (simp only: closed_def)\nqed\n\nlemma closed_insert [continuous_intros, simp]:\n  fixes a :: \"'a::t1_space\"\n  assumes \"closed S\"\n  shows \"closed (insert a S)\"\nproof -\n  from closed_singleton assms have \"closed ({a} \\<union> S)\"\n    by (rule closed_Un)\n  then show \"closed (insert a S)\"\n    by simp\nqed\n\nlemma finite_imp_closed: \"finite S \\<Longrightarrow> closed S\"\n  for S :: \"'a::t1_space set\"\n  by (induct pred: finite) simp_all\n\n\ntext \\<open>T2 spaces are also known as Hausdorff spaces.\\<close>\n\nclass t2_space = topological_space +\n  assumes hausdorff: \"x \\<noteq> y \\<Longrightarrow> \\<exists>U V. open U \\<and> open V \\<and> x \\<in> U \\<and> y \\<in> V \\<and> U \\<inter> V = {}\"\n\ninstance t2_space \\<subseteq> t1_space\n  by standard (fast dest: hausdorff)\n\nlemma separation_t2: \"x \\<noteq> y \\<longleftrightarrow> (\\<exists>U V. open U \\<and> open V \\<and> x \\<in> U \\<and> y \\<in> V \\<and> U \\<inter> V = {})\"\n  for x y :: \"'a::t2_space\"\n  using hausdorff [of x y] by blast\n\nlemma separation_t0: \"x \\<noteq> y \\<longleftrightarrow> (\\<exists>U. open U \\<and> \\<not> (x \\<in> U \\<longleftrightarrow> y \\<in> U))\"\n  for x y :: \"'a::t0_space\"\n  using t0_space [of x y] by blast\n\n\ntext \\<open>A perfect space is a topological space with no isolated points.\\<close>\n\nclass perfect_space = topological_space +\n  assumes not_open_singleton: \"\\<not> open {x}\"\n\nlemma UNIV_not_singleton: \"UNIV \\<noteq> {x}\"\n  for x :: \"'a::perfect_space\"\n  by (metis open_UNIV not_open_singleton)\n\n\nsubsection \\<open>Generators for toplogies\\<close>\n\ninductive generate_topology :: \"'a set set \\<Rightarrow> 'a set \\<Rightarrow> bool\" for S :: \"'a set set\"\n  where\n    UNIV: \"generate_topology S UNIV\"\n  | Int: \"generate_topology S (a \\<inter> b)\" if \"generate_topology S a\" and \"generate_topology S b\"\n  | UN: \"generate_topology S (\\<Union>K)\" if \"(\\<And>k. k \\<in> K \\<Longrightarrow> generate_topology S k)\"\n  | Basis: \"generate_topology S s\" if \"s \\<in> S\"\n\nhide_fact (open) UNIV Int UN Basis\n\nlemma generate_topology_Union:\n  \"(\\<And>k. k \\<in> I \\<Longrightarrow> generate_topology S (K k)) \\<Longrightarrow> generate_topology S (\\<Union>k\\<in>I. K k)\"\n  using generate_topology.UN [of \"K ` I\"] by auto\n\nlemma topological_space_generate_topology: \"class.topological_space (generate_topology S)\"\n  by standard (auto intro: generate_topology.intros)\n\n\nsubsection \\<open>Order topologies\\<close>\n\nclass order_topology = order + \"open\" +\n  assumes open_generated_order: \"open = generate_topology (range (\\<lambda>a. {..< a}) \\<union> range (\\<lambda>a. {a <..}))\"\nbegin\n\nsubclass topological_space\n  unfolding open_generated_order\n  by (rule topological_space_generate_topology)\n\nlemma open_greaterThan [continuous_intros, simp]: \"open {a <..}\"\n  unfolding open_generated_order by (auto intro: generate_topology.Basis)\n\nlemma open_lessThan [continuous_intros, simp]: \"open {..< a}\"\n  unfolding open_generated_order by (auto intro: generate_topology.Basis)\n\nlemma open_greaterThanLessThan [continuous_intros, simp]: \"open {a <..< b}\"\n   unfolding greaterThanLessThan_eq by (simp add: open_Int)\n\nend\n\nclass linorder_topology = linorder + order_topology\n\nlemma closed_atMost [continuous_intros, simp]: \"closed {..a}\"\n  for a :: \"'a::linorder_topology\"\n  by (simp add: closed_open)\n\nlemma closed_atLeast [continuous_intros, simp]: \"closed {a..}\"\n  for a :: \"'a::linorder_topology\"\n  by (simp add: closed_open)\n\nlemma closed_atLeastAtMost [continuous_intros, simp]: \"closed {a..b}\"\n  for a b :: \"'a::linorder_topology\"\nproof -\n  have \"{a .. b} = {a ..} \\<inter> {.. b}\"\n    by auto\n  then show ?thesis\n    by (simp add: closed_Int)\nqed\n\nlemma (in linorder) less_separate:\n  assumes \"x < y\"\n  shows \"\\<exists>a b. x \\<in> {..< a} \\<and> y \\<in> {b <..} \\<and> {..< a} \\<inter> {b <..} = {}\"\nproof (cases \"\\<exists>z. x < z \\<and> z < y\")\n  case True\n  then obtain z where \"x < z \\<and> z < y\" ..\n  then have \"x \\<in> {..< z} \\<and> y \\<in> {z <..} \\<and> {z <..} \\<inter> {..< z} = {}\"\n    by auto\n  then show ?thesis by blast\nnext\n  case False\n  with \\<open>x < y\\<close> have \"x \\<in> {..< y}\" \"y \\<in> {x <..}\" \"{x <..} \\<inter> {..< y} = {}\"\n    by auto\n  then show ?thesis by blast\nqed\n\ninstance linorder_topology \\<subseteq> t2_space\nproof\n  fix x y :: 'a\n  show \"x \\<noteq> y \\<Longrightarrow> \\<exists>U V. open U \\<and> open V \\<and> x \\<in> U \\<and> y \\<in> V \\<and> U \\<inter> V = {}\"\n    using less_separate [of x y] less_separate [of y x]\n    by (elim neqE; metis open_lessThan open_greaterThan Int_commute)\nqed\n\nlemma (in linorder_topology) open_right:\n  assumes \"open S\" \"x \\<in> S\"\n    and gt_ex: \"x < y\"\n  shows \"\\<exists>b>x. {x ..< b} \\<subseteq> S\"\n  using assms unfolding open_generated_order\nproof induct\n  case UNIV\n  then show ?case by blast\nnext\n  case (Int A B)\n  then obtain a b where \"a > x\" \"{x ..< a} \\<subseteq> A\"  \"b > x\" \"{x ..< b} \\<subseteq> B\"\n    by auto\n  then show ?case\n    by (auto intro!: exI[of _ \"min a b\"])\nnext\n  case UN\n  then show ?case by blast\nnext\n  case Basis\n  then show ?case\n    by (fastforce intro: exI[of _ y] gt_ex)\nqed\n\nlemma (in linorder_topology) open_left:\n  assumes \"open S\" \"x \\<in> S\"\n    and lt_ex: \"y < x\"\n  shows \"\\<exists>b<x. {b <.. x} \\<subseteq> S\"\n  using assms unfolding open_generated_order\nproof induction\n  case UNIV\n  then show ?case by blast\nnext\n  case (Int A B)\n  then obtain a b where \"a < x\" \"{a <.. x} \\<subseteq> A\"  \"b < x\" \"{b <.. x} \\<subseteq> B\"\n    by auto\n  then show ?case\n    by (auto intro!: exI[of _ \"max a b\"])\nnext\n  case UN\n  then show ?case by blast\nnext\n  case Basis\n  then show ?case\n    by (fastforce intro: exI[of _ y] lt_ex)\nqed\n\n\nsubsection \\<open>Setup some topologies\\<close>\n\nsubsubsection \\<open>Boolean is an order topology\\<close>\n\nclass discrete_topology = topological_space +\n  assumes open_discrete: \"\\<And>A. open A\"\n\ninstance discrete_topology < t2_space\nproof\n  fix x y :: 'a\n  assume \"x \\<noteq> y\"\n  then show \"\\<exists>U V. open U \\<and> open V \\<and> x \\<in> U \\<and> y \\<in> V \\<and> U \\<inter> V = {}\"\n    by (intro exI[of _ \"{_}\"]) (auto intro!: open_discrete)\nqed\n\ninstantiation bool :: linorder_topology\nbegin\n\ndefinition open_bool :: \"bool set \\<Rightarrow> bool\"\n  where \"open_bool = generate_topology (range (\\<lambda>a. {..< a}) \\<union> range (\\<lambda>a. {a <..}))\"\n\ninstance\n  by standard (rule open_bool_def)\n\nend\n\ninstance bool :: discrete_topology\nproof\n  fix A :: \"bool set\"\n  have *: \"{False <..} = {True}\" \"{..< True} = {False}\"\n    by auto\n  have \"A = UNIV \\<or> A = {} \\<or> A = {False <..} \\<or> A = {..< True}\"\n    using subset_UNIV[of A] unfolding UNIV_bool * by blast\n  then show \"open A\"\n    by auto\nqed\n\ninstantiation nat :: linorder_topology\nbegin\n\ndefinition open_nat :: \"nat set \\<Rightarrow> bool\"\n  where \"open_nat = generate_topology (range (\\<lambda>a. {..< a}) \\<union> range (\\<lambda>a. {a <..}))\"\n\ninstance\n  by standard (rule open_nat_def)\n\nend\n\ninstance nat :: discrete_topology\nproof\n  fix A :: \"nat set\"\n  have \"open {n}\" for n :: nat\n  proof (cases n)\n    case 0\n    moreover have \"{0} = {..<1::nat}\"\n      by auto\n    ultimately show ?thesis\n       by auto\n  next\n    case (Suc n')\n    then have \"{n} = {..<Suc n} \\<inter> {n' <..}\"\n      by auto\n    with Suc show ?thesis\n      by (auto intro: open_lessThan open_greaterThan)\n  qed\n  then have \"open (\\<Union>a\\<in>A. {a})\"\n    by (intro open_UN) auto\n  then show \"open A\"\n    by simp\nqed\n\ninstantiation int :: linorder_topology\nbegin\n\ndefinition open_int :: \"int set \\<Rightarrow> bool\"\n  where \"open_int = generate_topology (range (\\<lambda>a. {..< a}) \\<union> range (\\<lambda>a. {a <..}))\"\n\ninstance\n  by standard (rule open_int_def)\n\nend\n\ninstance int :: discrete_topology\nproof\n  fix A :: \"int set\"\n  have \"{..<i + 1} \\<inter> {i-1 <..} = {i}\" for i :: int\n    by auto\n  then have \"open {i}\" for i :: int\n    using open_Int[OF open_lessThan[of \"i + 1\"] open_greaterThan[of \"i - 1\"]] by auto\n  then have \"open (\\<Union>a\\<in>A. {a})\"\n    by (intro open_UN) auto\n  then show \"open A\"\n    by simp\nqed\n\n\nsubsubsection \\<open>Topological filters\\<close>\n\ndefinition (in topological_space) nhds :: \"'a \\<Rightarrow> 'a filter\"\n  where \"nhds a = (INF S:{S. open S \\<and> a \\<in> S}. principal S)\"\n\ndefinition (in topological_space) at_within :: \"'a \\<Rightarrow> 'a set \\<Rightarrow> 'a filter\"\n    (\"at (_)/ within (_)\" [1000, 60] 60)\n  where \"at a within s = inf (nhds a) (principal (s - {a}))\"\n\nabbreviation (in topological_space) at :: \"'a \\<Rightarrow> 'a filter\"  (\"at\")\n  where \"at x \\<equiv> at x within (CONST UNIV)\"\n\nabbreviation (in order_topology) at_right :: \"'a \\<Rightarrow> 'a filter\"\n  where \"at_right x \\<equiv> at x within {x <..}\"\n\nabbreviation (in order_topology) at_left :: \"'a \\<Rightarrow> 'a filter\"\n  where \"at_left x \\<equiv> at x within {..< x}\"\n\nlemma (in topological_space) nhds_generated_topology:\n  \"open = generate_topology T \\<Longrightarrow> nhds x = (INF S:{S\\<in>T. x \\<in> S}. principal S)\"\n  unfolding nhds_def\nproof (safe intro!: antisym INF_greatest)\n  fix S\n  assume \"generate_topology T S\" \"x \\<in> S\"\n  then show \"(INF S:{S \\<in> T. x \\<in> S}. principal S) \\<le> principal S\"\n    by induct\n      (auto intro: INF_lower order_trans simp: inf_principal[symmetric] simp del: inf_principal)\nqed (auto intro!: INF_lower intro: generate_topology.intros)\n\nlemma (in topological_space) eventually_nhds:\n  \"eventually P (nhds a) \\<longleftrightarrow> (\\<exists>S. open S \\<and> a \\<in> S \\<and> (\\<forall>x\\<in>S. P x))\"\n  unfolding nhds_def by (subst eventually_INF_base) (auto simp: eventually_principal)\n\nlemma (in topological_space) eventually_nhds_in_open:\n  \"open s \\<Longrightarrow> x \\<in> s \\<Longrightarrow> eventually (\\<lambda>y. y \\<in> s) (nhds x)\"\n  by (subst eventually_nhds) blast\n\nlemma eventually_nhds_x_imp_x: \"eventually P (nhds x) \\<Longrightarrow> P x\"\n  by (subst (asm) eventually_nhds) blast\n\nlemma nhds_neq_bot [simp]: \"nhds a \\<noteq> bot\"\n  by (simp add: trivial_limit_def eventually_nhds)\n\nlemma (in t1_space) t1_space_nhds: \"x \\<noteq> y \\<Longrightarrow> (\\<forall>\\<^sub>F x in nhds x. x \\<noteq> y)\"\n  by (drule t1_space) (auto simp: eventually_nhds)\n\nlemma (in topological_space) nhds_discrete_open: \"open {x} \\<Longrightarrow> nhds x = principal {x}\"\n  by (auto simp: nhds_def intro!: antisym INF_greatest INF_lower2[of \"{x}\"])\n\nlemma (in discrete_topology) nhds_discrete: \"nhds x = principal {x}\"\n  by (simp add: nhds_discrete_open open_discrete)\n\nlemma (in discrete_topology) at_discrete: \"at x within S = bot\"\n  unfolding at_within_def nhds_discrete by simp\n\nlemma at_within_eq: \"at x within s = (INF S:{S. open S \\<and> x \\<in> S}. principal (S \\<inter> s - {x}))\"\n  unfolding nhds_def at_within_def\n  by (subst INF_inf_const2[symmetric]) (auto simp: Diff_Int_distrib)\n\nlemma eventually_at_filter:\n  \"eventually P (at a within s) \\<longleftrightarrow> eventually (\\<lambda>x. x \\<noteq> a \\<longrightarrow> x \\<in> s \\<longrightarrow> P x) (nhds a)\"\n  by (simp add: at_within_def eventually_inf_principal imp_conjL[symmetric] conj_commute)\n\nlemma at_le: \"s \\<subseteq> t \\<Longrightarrow> at x within s \\<le> at x within t\"\n  unfolding at_within_def by (intro inf_mono) auto\n\nlemma eventually_at_topological:\n  \"eventually P (at a within s) \\<longleftrightarrow> (\\<exists>S. open S \\<and> a \\<in> S \\<and> (\\<forall>x\\<in>S. x \\<noteq> a \\<longrightarrow> x \\<in> s \\<longrightarrow> P x))\"\n  by (simp add: eventually_nhds eventually_at_filter)\n\nlemma at_within_open: \"a \\<in> S \\<Longrightarrow> open S \\<Longrightarrow> at a within S = at a\"\n  unfolding filter_eq_iff eventually_at_topological by (metis open_Int Int_iff UNIV_I)\n\nlemma at_within_open_NO_MATCH: \"a \\<in> s \\<Longrightarrow> open s \\<Longrightarrow> NO_MATCH UNIV s \\<Longrightarrow> at a within s = at a\"\n  by (simp only: at_within_open)\n\nlemma at_within_nhd:\n  assumes \"x \\<in> S\" \"open S\" \"T \\<inter> S - {x} = U \\<inter> S - {x}\"\n  shows \"at x within T = at x within U\"\n  unfolding filter_eq_iff eventually_at_filter\nproof (intro allI eventually_subst)\n  have \"eventually (\\<lambda>x. x \\<in> S) (nhds x)\"\n    using \\<open>x \\<in> S\\<close> \\<open>open S\\<close> by (auto simp: eventually_nhds)\n  then show \"\\<forall>\\<^sub>F n in nhds x. (n \\<noteq> x \\<longrightarrow> n \\<in> T \\<longrightarrow> P n) = (n \\<noteq> x \\<longrightarrow> n \\<in> U \\<longrightarrow> P n)\" for P\n    by eventually_elim (insert \\<open>T \\<inter> S - {x} = U \\<inter> S - {x}\\<close>, blast)\nqed\n\nlemma at_within_empty [simp]: \"at a within {} = bot\"\n  unfolding at_within_def by simp\n\nlemma at_within_union: \"at x within (S \\<union> T) = sup (at x within S) (at x within T)\"\n  unfolding filter_eq_iff eventually_sup eventually_at_filter\n  by (auto elim!: eventually_rev_mp)\n\nlemma at_eq_bot_iff: \"at a = bot \\<longleftrightarrow> open {a}\"\n  unfolding trivial_limit_def eventually_at_topological\n  apply safe\n   apply (case_tac \"S = {a}\")\n    apply simp\n   apply fast\n  apply fast\n  done\n\nlemma at_neq_bot [simp]: \"at a \\<noteq> bot\"\n  for a :: \"'a::perfect_space\"\n  by (simp add: at_eq_bot_iff not_open_singleton)\n\nlemma (in order_topology) nhds_order:\n  \"nhds x = inf (INF a:{x <..}. principal {..< a}) (INF a:{..< x}. principal {a <..})\"\nproof -\n  have 1: \"{S \\<in> range lessThan \\<union> range greaterThan. x \\<in> S} =\n      (\\<lambda>a. {..< a}) ` {x <..} \\<union> (\\<lambda>a. {a <..}) ` {..< x}\"\n    by auto\n  show ?thesis\n    by (simp only: nhds_generated_topology[OF open_generated_order] INF_union 1 INF_image comp_def)\nqed\n\nlemma filterlim_at_within_If:\n  assumes \"filterlim f G (at x within (A \\<inter> {x. P x}))\"\n    and \"filterlim g G (at x within (A \\<inter> {x. \\<not>P x}))\"\n  shows \"filterlim (\\<lambda>x. if P x then f x else g x) G (at x within A)\"\nproof (rule filterlim_If)\n  note assms(1)\n  also have \"at x within (A \\<inter> {x. P x}) = inf (nhds x) (principal (A \\<inter> Collect P - {x}))\"\n    by (simp add: at_within_def)\n  also have \"A \\<inter> Collect P - {x} = (A - {x}) \\<inter> Collect P\"\n    by blast\n  also have \"inf (nhds x) (principal \\<dots>) = inf (at x within A) (principal (Collect P))\"\n    by (simp add: at_within_def inf_assoc)\n  finally show \"filterlim f G (inf (at x within A) (principal (Collect P)))\" .\nnext\n  note assms(2)\n  also have \"at x within (A \\<inter> {x. \\<not> P x}) = inf (nhds x) (principal (A \\<inter> {x. \\<not> P x} - {x}))\"\n    by (simp add: at_within_def)\n  also have \"A \\<inter> {x. \\<not> P x} - {x} = (A - {x}) \\<inter> {x. \\<not> P x}\"\n    by blast\n  also have \"inf (nhds x) (principal \\<dots>) = inf (at x within A) (principal {x. \\<not> P x})\"\n    by (simp add: at_within_def inf_assoc)\n  finally show \"filterlim g G (inf (at x within A) (principal {x. \\<not> P x}))\" .\nqed\n\nlemma filterlim_at_If:\n  assumes \"filterlim f G (at x within {x. P x})\"\n    and \"filterlim g G (at x within {x. \\<not>P x})\"\n  shows \"filterlim (\\<lambda>x. if P x then f x else g x) G (at x)\"\n  using assms by (intro filterlim_at_within_If) simp_all\n\nlemma (in linorder_topology) at_within_order:\n  assumes \"UNIV \\<noteq> {x}\"\n  shows \"at x within s =\n    inf (INF a:{x <..}. principal ({..< a} \\<inter> s - {x}))\n        (INF a:{..< x}. principal ({a <..} \\<inter> s - {x}))\"\nproof (cases \"{x <..} = {}\" \"{..< x} = {}\" rule: case_split [case_product case_split])\n  case True_True\n  have \"UNIV = {..< x} \\<union> {x} \\<union> {x <..}\"\n    by auto\n  with assms True_True show ?thesis\n    by auto\nqed (auto simp del: inf_principal simp: at_within_def nhds_order Int_Diff\n      inf_principal[symmetric] INF_inf_const2 inf_sup_aci[where 'a=\"'a filter\"])\n\nlemma (in linorder_topology) at_left_eq:\n  \"y < x \\<Longrightarrow> at_left x = (INF a:{..< x}. principal {a <..< x})\"\n  by (subst at_within_order)\n     (auto simp: greaterThan_Int_greaterThan greaterThanLessThan_eq[symmetric] min.absorb2 INF_constant\n           intro!: INF_lower2 inf_absorb2)\n\nlemma (in linorder_topology) eventually_at_left:\n  \"y < x \\<Longrightarrow> eventually P (at_left x) \\<longleftrightarrow> (\\<exists>b<x. \\<forall>y>b. y < x \\<longrightarrow> P y)\"\n  unfolding at_left_eq\n  by (subst eventually_INF_base) (auto simp: eventually_principal Ball_def)\n\nlemma (in linorder_topology) at_right_eq:\n  \"x < y \\<Longrightarrow> at_right x = (INF a:{x <..}. principal {x <..< a})\"\n  by (subst at_within_order)\n     (auto simp: lessThan_Int_lessThan greaterThanLessThan_eq[symmetric] max.absorb2 INF_constant Int_commute\n           intro!: INF_lower2 inf_absorb1)\n\nlemma (in linorder_topology) eventually_at_right:\n  \"x < y \\<Longrightarrow> eventually P (at_right x) \\<longleftrightarrow> (\\<exists>b>x. \\<forall>y>x. y < b \\<longrightarrow> P y)\"\n  unfolding at_right_eq\n  by (subst eventually_INF_base) (auto simp: eventually_principal Ball_def)\n\nlemma eventually_at_right_less: \"\\<forall>\\<^sub>F y in at_right (x::'a::{linorder_topology, no_top}). x < y\"\n  using gt_ex[of x] eventually_at_right[of x] by auto\n\nlemma trivial_limit_at_right_top: \"at_right (top::_::{order_top,linorder_topology}) = bot\"\n  by (auto simp: filter_eq_iff eventually_at_topological)\n\nlemma trivial_limit_at_left_bot: \"at_left (bot::_::{order_bot,linorder_topology}) = bot\"\n  by (auto simp: filter_eq_iff eventually_at_topological)\n\nlemma trivial_limit_at_left_real [simp]: \"\\<not> trivial_limit (at_left x)\"\n  for x :: \"'a::{no_bot,dense_order,linorder_topology}\"\n  using lt_ex [of x]\n  by safe (auto simp add: trivial_limit_def eventually_at_left dest: dense)\n\nlemma trivial_limit_at_right_real [simp]: \"\\<not> trivial_limit (at_right x)\"\n  for x :: \"'a::{no_top,dense_order,linorder_topology}\"\n  using gt_ex[of x]\n  by safe (auto simp add: trivial_limit_def eventually_at_right dest: dense)\n\nlemma at_eq_sup_left_right: \"at x = sup (at_left x) (at_right x)\"\n  for x :: \"'a::linorder_topology\"\n  by (auto simp: eventually_at_filter filter_eq_iff eventually_sup\n      elim: eventually_elim2 eventually_mono)\n\nlemma eventually_at_split:\n  \"eventually P (at x) \\<longleftrightarrow> eventually P (at_left x) \\<and> eventually P (at_right x)\"\n  for x :: \"'a::linorder_topology\"\n  by (subst at_eq_sup_left_right) (simp add: eventually_sup)\n\nlemma eventually_at_leftI:\n  assumes \"\\<And>x. x \\<in> {a<..<b} \\<Longrightarrow> P x\" \"a < b\"\n  shows   \"eventually P (at_left b)\"\n  using assms unfolding eventually_at_topological by (intro exI[of _ \"{a<..}\"]) auto\n\nlemma eventually_at_rightI:\n  assumes \"\\<And>x. x \\<in> {a<..<b} \\<Longrightarrow> P x\" \"a < b\"\n  shows   \"eventually P (at_right a)\"\n  using assms unfolding eventually_at_topological by (intro exI[of _ \"{..<b}\"]) auto\n\n\nsubsubsection \\<open>Tendsto\\<close>\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\nlemma tendsto_eq_rhs: \"(f \\<longlongrightarrow> x) F \\<Longrightarrow> x = y \\<Longrightarrow> (f \\<longlongrightarrow> y) F\"\n  by simp\n\nnamed_theorems tendsto_intros \"introduction rules for tendsto\"\nsetup \\<open>\n  Global_Theory.add_thms_dynamic (@{binding tendsto_eq_intros},\n    fn context =>\n      Named_Theorems.get (Context.proof_of context) @{named_theorems tendsto_intros}\n      |> map_filter (try (fn thm => @{thm tendsto_eq_rhs} OF [thm])))\n\\<close>\n\nlemma (in topological_space) tendsto_def:\n   \"(f \\<longlongrightarrow> l) F \\<longleftrightarrow> (\\<forall>S. open S \\<longrightarrow> l \\<in> S \\<longrightarrow> eventually (\\<lambda>x. f x \\<in> S) F)\"\n   unfolding nhds_def filterlim_INF filterlim_principal by auto\n\nlemma tendsto_cong: \"(f \\<longlongrightarrow> c) F \\<longleftrightarrow> (g \\<longlongrightarrow> c) F\" if \"eventually (\\<lambda>x. f x = g x) F\"\n  by (rule filterlim_cong [OF refl refl that])\n\nlemma tendsto_mono: \"F \\<le> F' \\<Longrightarrow> (f \\<longlongrightarrow> l) F' \\<Longrightarrow> (f \\<longlongrightarrow> l) F\"\n  unfolding tendsto_def le_filter_def by fast\n\nlemma tendsto_within_subset: \"(f \\<longlongrightarrow> l) (at x within S) \\<Longrightarrow> T \\<subseteq> S \\<Longrightarrow> (f \\<longlongrightarrow> l) (at x within T)\"\n  by (blast intro: tendsto_mono at_le)\n\nlemma filterlim_at:\n  \"(LIM x F. f x :> at b within s) \\<longleftrightarrow> eventually (\\<lambda>x. f x \\<in> s \\<and> f x \\<noteq> b) F \\<and> (f \\<longlongrightarrow> b) F\"\n  by (simp add: at_within_def filterlim_inf filterlim_principal conj_commute)\n\nlemma filterlim_at_withinI:\n  assumes \"filterlim f (nhds c) F\"\n  assumes \"eventually (\\<lambda>x. f x \\<in> A - {c}) F\"\n  shows   \"filterlim f (at c within A) F\"\n  using assms by (simp add: filterlim_at)\n\nlemma filterlim_atI:\n  assumes \"filterlim f (nhds c) F\"\n  assumes \"eventually (\\<lambda>x. f x \\<noteq> c) F\"\n  shows   \"filterlim f (at c) F\"\n  using assms by (intro filterlim_at_withinI) simp_all\n\nlemma (in topological_space) topological_tendstoI:\n  \"(\\<And>S. open S \\<Longrightarrow> l \\<in> S \\<Longrightarrow> eventually (\\<lambda>x. f x \\<in> S) F) \\<Longrightarrow> (f \\<longlongrightarrow> l) F\"\n  by (auto simp: tendsto_def)\n\nlemma (in topological_space) topological_tendstoD:\n  \"(f \\<longlongrightarrow> l) F \\<Longrightarrow> open S \\<Longrightarrow> l \\<in> S \\<Longrightarrow> eventually (\\<lambda>x. f x \\<in> S) F\"\n  by (auto simp: tendsto_def)\n\nlemma (in order_topology) order_tendsto_iff:\n  \"(f \\<longlongrightarrow> x) F \\<longleftrightarrow> (\\<forall>l<x. eventually (\\<lambda>x. l < f x) F) \\<and> (\\<forall>u>x. eventually (\\<lambda>x. f x < u) F)\"\n  by (auto simp: nhds_order filterlim_inf filterlim_INF filterlim_principal)\n\nlemma (in order_topology) order_tendstoI:\n  \"(\\<And>a. a < y \\<Longrightarrow> eventually (\\<lambda>x. a < f x) F) \\<Longrightarrow> (\\<And>a. y < a \\<Longrightarrow> eventually (\\<lambda>x. f x < a) F) \\<Longrightarrow>\n    (f \\<longlongrightarrow> y) F\"\n  by (auto simp: order_tendsto_iff)\n\nlemma (in order_topology) order_tendstoD:\n  assumes \"(f \\<longlongrightarrow> y) F\"\n  shows \"a < y \\<Longrightarrow> eventually (\\<lambda>x. a < f x) F\"\n    and \"y < a \\<Longrightarrow> eventually (\\<lambda>x. f x < a) F\"\n  using assms by (auto simp: order_tendsto_iff)\n\nlemma tendsto_bot [simp]: \"(f \\<longlongrightarrow> a) bot\"\n  by (simp add: tendsto_def)\n\nlemma (in linorder_topology) tendsto_max:\n  assumes X: \"(X \\<longlongrightarrow> x) net\"\n    and Y: \"(Y \\<longlongrightarrow> y) net\"\n  shows \"((\\<lambda>x. max (X x) (Y x)) \\<longlongrightarrow> max x y) net\"\nproof (rule order_tendstoI)\n  fix a\n  assume \"a < max x y\"\n  then show \"eventually (\\<lambda>x. a < max (X x) (Y x)) net\"\n    using order_tendstoD(1)[OF X, of a] order_tendstoD(1)[OF Y, of a]\n    by (auto simp: less_max_iff_disj elim: eventually_mono)\nnext\n  fix a\n  assume \"max x y < a\"\n  then show \"eventually (\\<lambda>x. max (X x) (Y x) < a) net\"\n    using order_tendstoD(2)[OF X, of a] order_tendstoD(2)[OF Y, of a]\n    by (auto simp: eventually_conj_iff)\nqed\n\nlemma (in linorder_topology) tendsto_min:\n  assumes X: \"(X \\<longlongrightarrow> x) net\"\n    and Y: \"(Y \\<longlongrightarrow> y) net\"\n  shows \"((\\<lambda>x. min (X x) (Y x)) \\<longlongrightarrow> min x y) net\"\nproof (rule order_tendstoI)\n  fix a\n  assume \"a < min x y\"\n  then show \"eventually (\\<lambda>x. a < min (X x) (Y x)) net\"\n    using order_tendstoD(1)[OF X, of a] order_tendstoD(1)[OF Y, of a]\n    by (auto simp: eventually_conj_iff)\nnext\n  fix a\n  assume \"min x y < a\"\n  then show \"eventually (\\<lambda>x. min (X x) (Y x) < a) net\"\n    using order_tendstoD(2)[OF X, of a] order_tendstoD(2)[OF Y, of a]\n    by (auto simp: min_less_iff_disj elim: eventually_mono)\nqed\n\nlemma tendsto_ident_at [tendsto_intros, simp, intro]: \"((\\<lambda>x. x) \\<longlongrightarrow> a) (at a within s)\"\n  by (auto simp: tendsto_def eventually_at_topological)\n\nlemma (in topological_space) tendsto_const [tendsto_intros, simp, intro]: \"((\\<lambda>x. k) \\<longlongrightarrow> k) F\"\n  by (simp add: tendsto_def)\n\nlemma (in t2_space) tendsto_unique:\n  assumes \"F \\<noteq> bot\"\n    and \"(f \\<longlongrightarrow> a) F\"\n    and \"(f \\<longlongrightarrow> b) F\"\n  shows \"a = b\"\nproof (rule ccontr)\n  assume \"a \\<noteq> b\"\n  obtain U V where \"open U\" \"open V\" \"a \\<in> U\" \"b \\<in> V\" \"U \\<inter> V = {}\"\n    using hausdorff [OF \\<open>a \\<noteq> b\\<close>] by fast\n  have \"eventually (\\<lambda>x. f x \\<in> U) F\"\n    using \\<open>(f \\<longlongrightarrow> a) F\\<close> \\<open>open U\\<close> \\<open>a \\<in> U\\<close> by (rule topological_tendstoD)\n  moreover\n  have \"eventually (\\<lambda>x. f x \\<in> V) F\"\n    using \\<open>(f \\<longlongrightarrow> b) F\\<close> \\<open>open V\\<close> \\<open>b \\<in> V\\<close> by (rule topological_tendstoD)\n  ultimately\n  have \"eventually (\\<lambda>x. False) F\"\n  proof eventually_elim\n    case (elim x)\n    then have \"f x \\<in> U \\<inter> V\" by simp\n    with \\<open>U \\<inter> V = {}\\<close> show ?case by simp\n  qed\n  with \\<open>\\<not> trivial_limit F\\<close> show \"False\"\n    by (simp add: trivial_limit_def)\nqed\n\nlemma (in t2_space) tendsto_const_iff:\n  fixes a b :: 'a\n  assumes \"\\<not> trivial_limit F\"\n  shows \"((\\<lambda>x. a) \\<longlongrightarrow> b) F \\<longleftrightarrow> a = b\"\n  by (auto intro!: tendsto_unique [OF assms tendsto_const])\n\nlemma increasing_tendsto:\n  fixes f :: \"_ \\<Rightarrow> 'a::order_topology\"\n  assumes bdd: \"eventually (\\<lambda>n. f n \\<le> l) F\"\n    and en: \"\\<And>x. x < l \\<Longrightarrow> eventually (\\<lambda>n. x < f n) F\"\n  shows \"(f \\<longlongrightarrow> l) F\"\n  using assms by (intro order_tendstoI) (auto elim!: eventually_mono)\n\nlemma decreasing_tendsto:\n  fixes f :: \"_ \\<Rightarrow> 'a::order_topology\"\n  assumes bdd: \"eventually (\\<lambda>n. l \\<le> f n) F\"\n    and en: \"\\<And>x. l < x \\<Longrightarrow> eventually (\\<lambda>n. f n < x) F\"\n  shows \"(f \\<longlongrightarrow> l) F\"\n  using assms by (intro order_tendstoI) (auto elim!: eventually_mono)\n\nlemma tendsto_sandwich:\n  fixes f g h :: \"'a \\<Rightarrow> 'b::order_topology\"\n  assumes ev: \"eventually (\\<lambda>n. f n \\<le> g n) net\" \"eventually (\\<lambda>n. g n \\<le> h n) net\"\n  assumes lim: \"(f \\<longlongrightarrow> c) net\" \"(h \\<longlongrightarrow> c) net\"\n  shows \"(g \\<longlongrightarrow> c) net\"\nproof (rule order_tendstoI)\n  fix a\n  show \"a < c \\<Longrightarrow> eventually (\\<lambda>x. a < g x) net\"\n    using order_tendstoD[OF lim(1), of a] ev by (auto elim: eventually_elim2)\nnext\n  fix a\n  show \"c < a \\<Longrightarrow> eventually (\\<lambda>x. g x < a) net\"\n    using order_tendstoD[OF lim(2), of a] ev by (auto elim: eventually_elim2)\nqed\n\nlemma limit_frequently_eq:\n  fixes c d :: \"'a::t1_space\"\n  assumes \"F \\<noteq> bot\"\n    and \"frequently (\\<lambda>x. f x = c) F\"\n    and \"(f \\<longlongrightarrow> d) F\"\n  shows \"d = c\"\nproof (rule ccontr)\n  assume \"d \\<noteq> c\"\n  from t1_space[OF this] obtain U where \"open U\" \"d \\<in> U\" \"c \\<notin> U\"\n    by blast\n  with assms have \"eventually (\\<lambda>x. f x \\<in> U) F\"\n    unfolding tendsto_def by blast\n  then have \"eventually (\\<lambda>x. f x \\<noteq> c) F\"\n    by eventually_elim (insert \\<open>c \\<notin> U\\<close>, blast)\n  with assms(2) show False\n    unfolding frequently_def by contradiction\nqed\n\nlemma tendsto_imp_eventually_ne:\n  fixes c :: \"'a::t1_space\"\n  assumes  \"(f \\<longlongrightarrow> c) F\" \"c \\<noteq> c'\"\n  shows \"eventually (\\<lambda>z. f z \\<noteq> c') F\"\nproof (cases \"F=bot\")\n  case True\n  thus ?thesis by auto\nnext\n  case False\n  show ?thesis\n  proof (rule ccontr)\n    assume \"\\<not> eventually (\\<lambda>z. f z \\<noteq> c') F\"\n    then have \"frequently (\\<lambda>z. f z = c') F\"\n      by (simp add: frequently_def)\n    from limit_frequently_eq[OF False this \\<open>(f \\<longlongrightarrow> c) F\\<close>] and \\<open>c \\<noteq> c'\\<close> show False\n      by contradiction\n  qed\nqed\n\nlemma tendsto_le:\n  fixes f g :: \"'a \\<Rightarrow> 'b::linorder_topology\"\n  assumes F: \"\\<not> trivial_limit F\"\n    and x: \"(f \\<longlongrightarrow> x) F\"\n    and y: \"(g \\<longlongrightarrow> y) F\"\n    and ev: \"eventually (\\<lambda>x. g x \\<le> f x) F\"\n  shows \"y \\<le> x\"\nproof (rule ccontr)\n  assume \"\\<not> y \\<le> x\"\n  with less_separate[of x y] obtain a b where xy: \"x < a\" \"b < y\" \"{..<a} \\<inter> {b<..} = {}\"\n    by (auto simp: not_le)\n  then have \"eventually (\\<lambda>x. f x < a) F\" \"eventually (\\<lambda>x. b < g x) F\"\n    using x y by (auto intro: order_tendstoD)\n  with ev have \"eventually (\\<lambda>x. False) F\"\n    by eventually_elim (insert xy, fastforce)\n  with F show False\n    by (simp add: eventually_False)\nqed\n\nlemma tendsto_lowerbound:\n  fixes f :: \"'a \\<Rightarrow> 'b::linorder_topology\"\n  assumes x: \"(f \\<longlongrightarrow> x) F\"\n      and ev: \"eventually (\\<lambda>i. a \\<le> f i) F\"\n      and F: \"\\<not> trivial_limit F\"\n  shows \"a \\<le> x\"\n  using F x tendsto_const ev by (rule tendsto_le)\n\nlemma tendsto_upperbound:\n  fixes f :: \"'a \\<Rightarrow> 'b::linorder_topology\"\n  assumes x: \"(f \\<longlongrightarrow> x) F\"\n      and ev: \"eventually (\\<lambda>i. a \\<ge> f i) F\"\n      and F: \"\\<not> trivial_limit F\"\n  shows \"a \\<ge> x\"\n  by (rule tendsto_le [OF F tendsto_const x ev])\n\n\nsubsubsection \\<open>Rules about @{const Lim}\\<close>\n\nlemma tendsto_Lim: \"\\<not> trivial_limit net \\<Longrightarrow> (f \\<longlongrightarrow> l) net \\<Longrightarrow> Lim net f = l\"\n  unfolding Lim_def using tendsto_unique [of net f] by auto\n\nlemma Lim_ident_at: \"\\<not> trivial_limit (at x within s) \\<Longrightarrow> Lim (at x within s) (\\<lambda>x. x) = x\"\n  by (rule tendsto_Lim[OF _ tendsto_ident_at]) auto\n\nlemma filterlim_at_bot_at_right:\n  fixes f :: \"'a::linorder_topology \\<Rightarrow> 'b::linorder\"\n  assumes mono: \"\\<And>x y. Q x \\<Longrightarrow> Q y \\<Longrightarrow> x \\<le> y \\<Longrightarrow> f x \\<le> f y\"\n    and bij: \"\\<And>x. P x \\<Longrightarrow> f (g x) = x\" \"\\<And>x. P x \\<Longrightarrow> Q (g x)\"\n    and Q: \"eventually Q (at_right a)\"\n    and bound: \"\\<And>b. Q b \\<Longrightarrow> a < b\"\n    and P: \"eventually P at_bot\"\n  shows \"filterlim f at_bot (at_right a)\"\nproof -\n  from P obtain x where x: \"\\<And>y. y \\<le> x \\<Longrightarrow> P y\"\n    unfolding eventually_at_bot_linorder by auto\n  show ?thesis\n  proof (intro filterlim_at_bot_le[THEN iffD2] allI impI)\n    fix z\n    assume \"z \\<le> x\"\n    with x have \"P z\" by auto\n    have \"eventually (\\<lambda>x. x \\<le> g z) (at_right a)\"\n      using bound[OF bij(2)[OF \\<open>P z\\<close>]]\n      unfolding eventually_at_right[OF bound[OF bij(2)[OF \\<open>P z\\<close>]]]\n      by (auto intro!: exI[of _ \"g z\"])\n    with Q show \"eventually (\\<lambda>x. f x \\<le> z) (at_right a)\"\n      by eventually_elim (metis bij \\<open>P z\\<close> mono)\n  qed\nqed\n\nlemma filterlim_at_top_at_left:\n  fixes f :: \"'a::linorder_topology \\<Rightarrow> 'b::linorder\"\n  assumes mono: \"\\<And>x y. Q x \\<Longrightarrow> Q y \\<Longrightarrow> x \\<le> y \\<Longrightarrow> f x \\<le> f y\"\n    and bij: \"\\<And>x. P x \\<Longrightarrow> f (g x) = x\" \"\\<And>x. P x \\<Longrightarrow> Q (g x)\"\n    and Q: \"eventually Q (at_left a)\"\n    and bound: \"\\<And>b. Q b \\<Longrightarrow> b < a\"\n    and P: \"eventually P at_top\"\n  shows \"filterlim f at_top (at_left a)\"\nproof -\n  from P obtain x where x: \"\\<And>y. x \\<le> y \\<Longrightarrow> P y\"\n    unfolding eventually_at_top_linorder by auto\n  show ?thesis\n  proof (intro filterlim_at_top_ge[THEN iffD2] allI impI)\n    fix z\n    assume \"x \\<le> z\"\n    with x have \"P z\" by auto\n    have \"eventually (\\<lambda>x. g z \\<le> x) (at_left a)\"\n      using bound[OF bij(2)[OF \\<open>P z\\<close>]]\n      unfolding eventually_at_left[OF bound[OF bij(2)[OF \\<open>P z\\<close>]]]\n      by (auto intro!: exI[of _ \"g z\"])\n    with Q show \"eventually (\\<lambda>x. z \\<le> f x) (at_left a)\"\n      by eventually_elim (metis bij \\<open>P z\\<close> mono)\n  qed\nqed\n\nlemma filterlim_split_at:\n  \"filterlim f F (at_left x) \\<Longrightarrow> filterlim f F (at_right x) \\<Longrightarrow>\n    filterlim f F (at x)\"\n  for x :: \"'a::linorder_topology\"\n  by (subst at_eq_sup_left_right) (rule filterlim_sup)\n\nlemma filterlim_at_split:\n  \"filterlim f F (at x) \\<longleftrightarrow> filterlim f F (at_left x) \\<and> filterlim f F (at_right x)\"\n  for x :: \"'a::linorder_topology\"\n  by (subst at_eq_sup_left_right) (simp add: filterlim_def filtermap_sup)\n\nlemma eventually_nhds_top:\n  fixes P :: \"'a :: {order_top,linorder_topology} \\<Rightarrow> bool\"\n    and b :: 'a\n  assumes \"b < top\"\n  shows \"eventually P (nhds top) \\<longleftrightarrow> (\\<exists>b<top. (\\<forall>z. b < z \\<longrightarrow> P z))\"\n  unfolding eventually_nhds\nproof safe\n  fix S :: \"'a set\"\n  assume \"open S\" \"top \\<in> S\"\n  note open_left[OF this \\<open>b < top\\<close>]\n  moreover assume \"\\<forall>s\\<in>S. P s\"\n  ultimately show \"\\<exists>b<top. \\<forall>z>b. P z\"\n    by (auto simp: subset_eq Ball_def)\nnext\n  fix b\n  assume \"b < top\" \"\\<forall>z>b. P z\"\n  then show \"\\<exists>S. open S \\<and> top \\<in> S \\<and> (\\<forall>xa\\<in>S. P xa)\"\n    by (intro exI[of _ \"{b <..}\"]) auto\nqed\n\nlemma tendsto_at_within_iff_tendsto_nhds:\n  \"(g \\<longlongrightarrow> g l) (at l within S) \\<longleftrightarrow> (g \\<longlongrightarrow> g l) (inf (nhds l) (principal S))\"\n  unfolding tendsto_def eventually_at_filter eventually_inf_principal\n  by (intro ext all_cong imp_cong) (auto elim!: eventually_mono)\n\n\nsubsection \\<open>Limits on sequences\\<close>\n\nabbreviation (in topological_space)\n  LIMSEQ :: \"[nat \\<Rightarrow> 'a, 'a] \\<Rightarrow> bool\"  (\"((_)/ \\<longlonglongrightarrow> (_))\" [60, 60] 60)\n  where \"X \\<longlonglongrightarrow> L \\<equiv> (X \\<longlongrightarrow> L) sequentially\"\n\nabbreviation (in t2_space) lim :: \"(nat \\<Rightarrow> 'a) \\<Rightarrow> 'a\"\n  where \"lim X \\<equiv> Lim sequentially X\"\n\ndefinition (in topological_space) convergent :: \"(nat \\<Rightarrow> 'a) \\<Rightarrow> bool\"\n  where \"convergent X = (\\<exists>L. X \\<longlonglongrightarrow> L)\"\n\nlemma lim_def: \"lim X = (THE L. X \\<longlonglongrightarrow> L)\"\n  unfolding Lim_def ..\n\n\nsubsubsection \\<open>Monotone sequences and subsequences\\<close>\n\ntext \\<open>\n  Definition of monotonicity.\n  The use of disjunction here complicates proofs considerably.\n  One alternative is to add a Boolean argument to indicate the direction.\n  Another is to develop the notions of increasing and decreasing first.\n\\<close>\ndefinition monoseq :: \"(nat \\<Rightarrow> 'a::order) \\<Rightarrow> bool\"\n  where \"monoseq X \\<longleftrightarrow> (\\<forall>m. \\<forall>n\\<ge>m. X m \\<le> X n) \\<or> (\\<forall>m. \\<forall>n\\<ge>m. X n \\<le> X m)\"\n\nabbreviation incseq :: \"(nat \\<Rightarrow> 'a::order) \\<Rightarrow> bool\"\n  where \"incseq X \\<equiv> mono X\"\n\nlemma incseq_def: \"incseq X \\<longleftrightarrow> (\\<forall>m. \\<forall>n\\<ge>m. X n \\<ge> X m)\"\n  unfolding mono_def ..\n\nabbreviation decseq :: \"(nat \\<Rightarrow> 'a::order) \\<Rightarrow> bool\"\n  where \"decseq X \\<equiv> antimono X\"\n\nlemma decseq_def: \"decseq X \\<longleftrightarrow> (\\<forall>m. \\<forall>n\\<ge>m. X n \\<le> X m)\"\n  unfolding antimono_def ..\n\ntext \\<open>Definition of subsequence.\\<close>\ndefinition subseq :: \"(nat \\<Rightarrow> nat) \\<Rightarrow> bool\"\n  where \"subseq f \\<longleftrightarrow> (\\<forall>m. \\<forall>n>m. f m < f n)\"\n\nlemma incseq_SucI: \"(\\<And>n. X n \\<le> X (Suc n)) \\<Longrightarrow> incseq X\"\n  using lift_Suc_mono_le[of X] by (auto simp: incseq_def)\n\nlemma incseqD: \"incseq f \\<Longrightarrow> i \\<le> j \\<Longrightarrow> f i \\<le> f j\"\n  by (auto simp: incseq_def)\n\nlemma incseq_SucD: \"incseq A \\<Longrightarrow> A i \\<le> A (Suc i)\"\n  using incseqD[of A i \"Suc i\"] by auto\n\nlemma incseq_Suc_iff: \"incseq f \\<longleftrightarrow> (\\<forall>n. f n \\<le> f (Suc n))\"\n  by (auto intro: incseq_SucI dest: incseq_SucD)\n\nlemma incseq_const[simp, intro]: \"incseq (\\<lambda>x. k)\"\n  unfolding incseq_def by auto\n\nlemma decseq_SucI: \"(\\<And>n. X (Suc n) \\<le> X n) \\<Longrightarrow> decseq X\"\n  using order.lift_Suc_mono_le[OF dual_order, of X] by (auto simp: decseq_def)\n\nlemma decseqD: \"decseq f \\<Longrightarrow> i \\<le> j \\<Longrightarrow> f j \\<le> f i\"\n  by (auto simp: decseq_def)\n\nlemma decseq_SucD: \"decseq A \\<Longrightarrow> A (Suc i) \\<le> A i\"\n  using decseqD[of A i \"Suc i\"] by auto\n\nlemma decseq_Suc_iff: \"decseq f \\<longleftrightarrow> (\\<forall>n. f (Suc n) \\<le> f n)\"\n  by (auto intro: decseq_SucI dest: decseq_SucD)\n\nlemma decseq_const[simp, intro]: \"decseq (\\<lambda>x. k)\"\n  unfolding decseq_def by auto\n\nlemma monoseq_iff: \"monoseq X \\<longleftrightarrow> incseq X \\<or> decseq X\"\n  unfolding monoseq_def incseq_def decseq_def ..\n\nlemma monoseq_Suc: \"monoseq X \\<longleftrightarrow> (\\<forall>n. X n \\<le> X (Suc n)) \\<or> (\\<forall>n. X (Suc n) \\<le> X n)\"\n  unfolding monoseq_iff incseq_Suc_iff decseq_Suc_iff ..\n\nlemma monoI1: \"\\<forall>m. \\<forall>n \\<ge> m. X m \\<le> X n \\<Longrightarrow> monoseq X\"\n  by (simp add: monoseq_def)\n\nlemma monoI2: \"\\<forall>m. \\<forall>n \\<ge> m. X n \\<le> X m \\<Longrightarrow> monoseq X\"\n  by (simp add: monoseq_def)\n\nlemma mono_SucI1: \"\\<forall>n. X n \\<le> X (Suc n) \\<Longrightarrow> monoseq X\"\n  by (simp add: monoseq_Suc)\n\nlemma mono_SucI2: \"\\<forall>n. X (Suc n) \\<le> X n \\<Longrightarrow> monoseq X\"\n  by (simp add: monoseq_Suc)\n\nlemma monoseq_minus:\n  fixes a :: \"nat \\<Rightarrow> 'a::ordered_ab_group_add\"\n  assumes \"monoseq a\"\n  shows \"monoseq (\\<lambda> n. - a n)\"\nproof (cases \"\\<forall>m. \\<forall>n \\<ge> m. a m \\<le> a n\")\n  case True\n  then have \"\\<forall>m. \\<forall>n \\<ge> m. - a n \\<le> - a m\" by auto\n  then show ?thesis by (rule monoI2)\nnext\n  case False\n  then have \"\\<forall>m. \\<forall>n \\<ge> m. - a m \\<le> - a n\"\n    using \\<open>monoseq a\\<close>[unfolded monoseq_def] by auto\n  then show ?thesis by (rule monoI1)\nqed\n\n\ntext \\<open>Subsequence (alternative definition, (e.g. Hoskins)\\<close>\n\nlemma subseq_Suc_iff: \"subseq f \\<longleftrightarrow> (\\<forall>n. f n < f (Suc n))\"\n  apply (simp add: subseq_def)\n  apply (auto dest!: less_imp_Suc_add)\n  apply (induct_tac k)\n   apply (auto intro: less_trans)\n  done\n\nlemma subseq_add: \"subseq (\\<lambda>n. n + k)\"\n  by (auto simp: subseq_Suc_iff)\n\ntext \\<open>For any sequence, there is a monotonic subsequence.\\<close>\nlemma seq_monosub:\n  fixes s :: \"nat \\<Rightarrow> 'a::linorder\"\n  shows \"\\<exists>f. subseq f \\<and> monoseq (\\<lambda>n. (s (f n)))\"\nproof (cases \"\\<forall>n. \\<exists>p>n. \\<forall>m\\<ge>p. s m \\<le> s p\")\n  case True\n  then have \"\\<exists>f. \\<forall>n. (\\<forall>m\\<ge>f n. s m \\<le> s (f n)) \\<and> f n < f (Suc n)\"\n    by (intro dependent_nat_choice) (auto simp: conj_commute)\n  then obtain f where f: \"subseq f\" and mono: \"\\<And>n m. f n \\<le> m \\<Longrightarrow> s m \\<le> s (f n)\"\n    by (auto simp: subseq_Suc_iff)\n  then have \"incseq f\"\n    unfolding subseq_Suc_iff incseq_Suc_iff by (auto intro: less_imp_le)\n  then have \"monoseq (\\<lambda>n. s (f n))\"\n    by (auto simp add: incseq_def intro!: mono monoI2)\n  with f show ?thesis\n    by auto\nnext\n  case False\n  then obtain N where N: \"p > N \\<Longrightarrow> \\<exists>m>p. s p < s m\" for p\n    by (force simp: not_le le_less)\n  have \"\\<exists>f. \\<forall>n. N < f n \\<and> f n < f (Suc n) \\<and> s (f n) \\<le> s (f (Suc n))\"\n  proof (intro dependent_nat_choice)\n    fix x\n    assume \"N < x\" with N[of x]\n    show \"\\<exists>y>N. x < y \\<and> s x \\<le> s y\"\n      by (auto intro: less_trans)\n  qed auto\n  then show ?thesis\n    by (auto simp: monoseq_iff incseq_Suc_iff subseq_Suc_iff)\nqed\n\nlemma seq_suble:\n  assumes sf: \"subseq f\"\n  shows \"n \\<le> f n\"\nproof (induct n)\n  case 0\n  show ?case by simp\nnext\n  case (Suc n)\n  with sf [unfolded subseq_Suc_iff, rule_format, of n] have \"n < f (Suc n)\"\n     by arith\n  then show ?case by arith\nqed\n\nlemma eventually_subseq:\n  \"subseq r \\<Longrightarrow> eventually P sequentially \\<Longrightarrow> eventually (\\<lambda>n. P (r n)) sequentially\"\n  unfolding eventually_sequentially by (metis seq_suble le_trans)\n\nlemma not_eventually_sequentiallyD:\n  assumes \"\\<not> eventually P sequentially\"\n  shows \"\\<exists>r. subseq r \\<and> (\\<forall>n. \\<not> P (r n))\"\nproof -\n  from assms have \"\\<forall>n. \\<exists>m\\<ge>n. \\<not> P m\"\n    unfolding eventually_sequentially by (simp add: not_less)\n  then obtain r where \"\\<And>n. r n \\<ge> n\" \"\\<And>n. \\<not> P (r n)\"\n    by (auto simp: choice_iff)\n  then show ?thesis\n    by (auto intro!: exI[of _ \"\\<lambda>n. r (((Suc \\<circ> r) ^^ Suc n) 0)\"]\n             simp: less_eq_Suc_le subseq_Suc_iff)\nqed\n\nlemma filterlim_subseq: \"subseq f \\<Longrightarrow> filterlim f sequentially sequentially\"\n  unfolding filterlim_iff by (metis eventually_subseq)\n\nlemma subseq_o: \"subseq r \\<Longrightarrow> subseq s \\<Longrightarrow> subseq (r \\<circ> s)\"\n  unfolding subseq_def by simp\n\nlemma subseq_mono: \"subseq r \\<Longrightarrow> m < n \\<Longrightarrow> r m < r n\"\n  by (auto simp: subseq_def)\n\nlemma subseq_imp_inj_on: \"subseq g \\<Longrightarrow> inj_on g A\"\nproof (rule inj_onI)\n  assume g: \"subseq g\"\n  fix x y\n  assume \"g x = g y\"\n  with subseq_mono[OF g, of x y] subseq_mono[OF g, of y x] show \"x = y\"\n    by (cases x y rule: linorder_cases) simp_all\nqed\n\nlemma subseq_strict_mono: \"subseq g \\<Longrightarrow> strict_mono g\"\n  by (intro strict_monoI subseq_mono[of g])\n\nlemma incseq_imp_monoseq:  \"incseq X \\<Longrightarrow> monoseq X\"\n  by (simp add: incseq_def monoseq_def)\n\nlemma decseq_imp_monoseq:  \"decseq X \\<Longrightarrow> monoseq X\"\n  by (simp add: decseq_def monoseq_def)\n\nlemma decseq_eq_incseq: \"decseq X = incseq (\\<lambda>n. - X n)\"\n  for X :: \"nat \\<Rightarrow> 'a::ordered_ab_group_add\"\n  by (simp add: decseq_def incseq_def)\n\nlemma INT_decseq_offset:\n  assumes \"decseq F\"\n  shows \"(\\<Inter>i. F i) = (\\<Inter>i\\<in>{n..}. F i)\"\nproof safe\n  fix x i\n  assume x: \"x \\<in> (\\<Inter>i\\<in>{n..}. F i)\"\n  show \"x \\<in> F i\"\n  proof cases\n    from x have \"x \\<in> F n\" by auto\n    also assume \"i \\<le> n\" with \\<open>decseq F\\<close> have \"F n \\<subseteq> F i\"\n      unfolding decseq_def by simp\n    finally show ?thesis .\n  qed (insert x, simp)\nqed auto\n\nlemma LIMSEQ_const_iff: \"(\\<lambda>n. k) \\<longlonglongrightarrow> l \\<longleftrightarrow> k = l\"\n  for k l :: \"'a::t2_space\"\n  using trivial_limit_sequentially by (rule tendsto_const_iff)\n\nlemma LIMSEQ_SUP: \"incseq X \\<Longrightarrow> X \\<longlonglongrightarrow> (SUP i. X i :: 'a::{complete_linorder,linorder_topology})\"\n  by (intro increasing_tendsto)\n    (auto simp: SUP_upper less_SUP_iff incseq_def eventually_sequentially intro: less_le_trans)\n\nlemma LIMSEQ_INF: \"decseq X \\<Longrightarrow> X \\<longlonglongrightarrow> (INF i. X i :: 'a::{complete_linorder,linorder_topology})\"\n  by (intro decreasing_tendsto)\n    (auto simp: INF_lower INF_less_iff decseq_def eventually_sequentially intro: le_less_trans)\n\nlemma LIMSEQ_ignore_initial_segment: \"f \\<longlonglongrightarrow> a \\<Longrightarrow> (\\<lambda>n. f (n + k)) \\<longlonglongrightarrow> a\"\n  unfolding tendsto_def by (subst eventually_sequentially_seg[where k=k])\n\nlemma LIMSEQ_offset: \"(\\<lambda>n. f (n + k)) \\<longlonglongrightarrow> a \\<Longrightarrow> f \\<longlonglongrightarrow> a\"\n  unfolding tendsto_def\n  by (subst (asm) eventually_sequentially_seg[where k=k])\n\nlemma LIMSEQ_Suc: \"f \\<longlonglongrightarrow> l \\<Longrightarrow> (\\<lambda>n. f (Suc n)) \\<longlonglongrightarrow> l\"\n  by (drule LIMSEQ_ignore_initial_segment [where k=\"Suc 0\"]) simp\n\nlemma LIMSEQ_imp_Suc: \"(\\<lambda>n. f (Suc n)) \\<longlonglongrightarrow> l \\<Longrightarrow> f \\<longlonglongrightarrow> l\"\n  by (rule LIMSEQ_offset [where k=\"Suc 0\"]) simp\n\nlemma LIMSEQ_Suc_iff: \"(\\<lambda>n. f (Suc n)) \\<longlonglongrightarrow> l = f \\<longlonglongrightarrow> l\"\n  by (blast intro: LIMSEQ_imp_Suc LIMSEQ_Suc)\n\nlemma LIMSEQ_unique: \"X \\<longlonglongrightarrow> a \\<Longrightarrow> X \\<longlonglongrightarrow> b \\<Longrightarrow> a = b\"\n  for a b :: \"'a::t2_space\"\n  using trivial_limit_sequentially by (rule tendsto_unique)\n\nlemma LIMSEQ_le_const: \"X \\<longlonglongrightarrow> x \\<Longrightarrow> \\<exists>N. \\<forall>n\\<ge>N. a \\<le> X n \\<Longrightarrow> a \\<le> x\"\n  for a x :: \"'a::linorder_topology\"\n  by (simp add: eventually_at_top_linorder tendsto_lowerbound)\n\nlemma LIMSEQ_le: \"X \\<longlonglongrightarrow> x \\<Longrightarrow> Y \\<longlonglongrightarrow> y \\<Longrightarrow> \\<exists>N. \\<forall>n\\<ge>N. X n \\<le> Y n \\<Longrightarrow> x \\<le> y\"\n  for x y :: \"'a::linorder_topology\"\n  using tendsto_le[of sequentially Y y X x] by (simp add: eventually_sequentially)\n\nlemma LIMSEQ_le_const2: \"X \\<longlonglongrightarrow> x \\<Longrightarrow> \\<exists>N. \\<forall>n\\<ge>N. X n \\<le> a \\<Longrightarrow> x \\<le> a\"\n  for a x :: \"'a::linorder_topology\"\n  by (rule LIMSEQ_le[of X x \"\\<lambda>n. a\"]) auto\n\nlemma convergentD: \"convergent X \\<Longrightarrow> \\<exists>L. X \\<longlonglongrightarrow> L\"\n  by (simp add: convergent_def)\n\nlemma convergentI: \"X \\<longlonglongrightarrow> L \\<Longrightarrow> convergent X\"\n  by (auto simp add: convergent_def)\n\nlemma convergent_LIMSEQ_iff: \"convergent X \\<longleftrightarrow> X \\<longlonglongrightarrow> lim X\"\n  by (auto intro: theI LIMSEQ_unique simp add: convergent_def lim_def)\n\nlemma convergent_const: \"convergent (\\<lambda>n. c)\"\n  by (rule convergentI) (rule tendsto_const)\n\nlemma monoseq_le:\n  \"monoseq a \\<Longrightarrow> a \\<longlonglongrightarrow> x \\<Longrightarrow>\n    (\\<forall>n. a n \\<le> x) \\<and> (\\<forall>m. \\<forall>n\\<ge>m. a m \\<le> a n) \\<or>\n    (\\<forall>n. x \\<le> a n) \\<and> (\\<forall>m. \\<forall>n\\<ge>m. a n \\<le> a m)\"\n  for x :: \"'a::linorder_topology\"\n  by (metis LIMSEQ_le_const LIMSEQ_le_const2 decseq_def incseq_def monoseq_iff)\n\nlemma LIMSEQ_subseq_LIMSEQ: \"X \\<longlonglongrightarrow> L \\<Longrightarrow> subseq f \\<Longrightarrow> (X \\<circ> f) \\<longlonglongrightarrow> L\"\n  unfolding comp_def by (rule filterlim_compose [of X, OF _ filterlim_subseq])\n\nlemma convergent_subseq_convergent: \"convergent X \\<Longrightarrow> subseq f \\<Longrightarrow> convergent (X \\<circ> f)\"\n  by (auto simp: convergent_def intro: LIMSEQ_subseq_LIMSEQ)\n\nlemma limI: \"X \\<longlonglongrightarrow> L \\<Longrightarrow> lim X = L\"\n  by (rule tendsto_Lim) (rule trivial_limit_sequentially)\n\nlemma lim_le: \"convergent f \\<Longrightarrow> (\\<And>n. f n \\<le> x) \\<Longrightarrow> lim f \\<le> x\"\n  for x :: \"'a::linorder_topology\"\n  using LIMSEQ_le_const2[of f \"lim f\" x] by (simp add: convergent_LIMSEQ_iff)\n\nlemma lim_const [simp]: \"lim (\\<lambda>m. a) = a\"\n  by (simp add: limI)\n\n\nsubsubsection \\<open>Increasing and Decreasing Series\\<close>\n\nlemma incseq_le: \"incseq X \\<Longrightarrow> X \\<longlonglongrightarrow> L \\<Longrightarrow> X n \\<le> L\"\n  for L :: \"'a::linorder_topology\"\n  by (metis incseq_def LIMSEQ_le_const)\n\nlemma decseq_le: \"decseq X \\<Longrightarrow> X \\<longlonglongrightarrow> L \\<Longrightarrow> L \\<le> X n\"\n  for L :: \"'a::linorder_topology\"\n  by (metis decseq_def LIMSEQ_le_const2)\n\n\nsubsection \\<open>First countable topologies\\<close>\n\nclass first_countable_topology = topological_space +\n  assumes first_countable_basis:\n    \"\\<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))\"\n\nlemma (in first_countable_topology) countable_basis_at_decseq:\n  obtains A :: \"nat \\<Rightarrow> 'a set\" where\n    \"\\<And>i. open (A i)\" \"\\<And>i. x \\<in> (A i)\"\n    \"\\<And>S. open S \\<Longrightarrow> x \\<in> S \\<Longrightarrow> eventually (\\<lambda>i. A i \\<subseteq> S) sequentially\"\nproof atomize_elim\n  from first_countable_basis[of x] obtain A :: \"nat \\<Rightarrow> 'a set\"\n    where nhds: \"\\<And>i. open (A i)\" \"\\<And>i. x \\<in> A i\"\n      and incl: \"\\<And>S. open S \\<Longrightarrow> x \\<in> S \\<Longrightarrow> \\<exists>i. A i \\<subseteq> S\"\n    by auto\n  define F where \"F n = (\\<Inter>i\\<le>n. A i)\" for n\n  show \"\\<exists>A. (\\<forall>i. open (A i)) \\<and> (\\<forall>i. x \\<in> A i) \\<and>\n    (\\<forall>S. open S \\<longrightarrow> x \\<in> S \\<longrightarrow> eventually (\\<lambda>i. A i \\<subseteq> S) sequentially)\"\n  proof (safe intro!: exI[of _ F])\n    fix i\n    show \"open (F i)\"\n      using nhds(1) by (auto simp: F_def)\n    show \"x \\<in> F i\"\n      using nhds(2) by (auto simp: F_def)\n  next\n    fix S\n    assume \"open S\" \"x \\<in> S\"\n    from incl[OF this] obtain i where \"F i \\<subseteq> S\"\n      unfolding F_def by auto\n    moreover have \"\\<And>j. i \\<le> j \\<Longrightarrow> F j \\<subseteq> F i\"\n      by (simp add: Inf_superset_mono F_def image_mono)\n    ultimately show \"eventually (\\<lambda>i. F i \\<subseteq> S) sequentially\"\n      by (auto simp: eventually_sequentially)\n  qed\nqed\n\nlemma (in first_countable_topology) nhds_countable:\n  obtains X :: \"nat \\<Rightarrow> 'a set\"\n  where \"decseq X\" \"\\<And>n. open (X n)\" \"\\<And>n. x \\<in> X n\" \"nhds x = (INF n. principal (X n))\"\nproof -\n  from first_countable_basis obtain A :: \"nat \\<Rightarrow> 'a set\"\n    where *: \"\\<And>n. x \\<in> A n\" \"\\<And>n. open (A n)\" \"\\<And>S. open S \\<Longrightarrow> x \\<in> S \\<Longrightarrow> \\<exists>i. A i \\<subseteq> S\"\n    by metis\n  show thesis\n  proof\n    show \"decseq (\\<lambda>n. \\<Inter>i\\<le>n. A i)\"\n      by (simp add: antimono_iff_le_Suc atMost_Suc)\n    show \"x \\<in> (\\<Inter>i\\<le>n. A i)\" \"\\<And>n. open (\\<Inter>i\\<le>n. A i)\" for n\n      using * by auto\n    show \"nhds x = (INF n. principal (\\<Inter>i\\<le>n. A i))\"\n      using *\n      unfolding nhds_def\n      apply -\n      apply (rule INF_eq)\n       apply simp_all\n       apply fastforce\n      apply (intro exI [of _ \"\\<Inter>i\\<le>n. A i\" for n] conjI open_INT)\n         apply auto\n      done\n  qed\nqed\n\nlemma (in first_countable_topology) countable_basis:\n  obtains A :: \"nat \\<Rightarrow> 'a set\" where\n    \"\\<And>i. open (A i)\" \"\\<And>i. x \\<in> A i\"\n    \"\\<And>F. (\\<forall>n. F n \\<in> A n) \\<Longrightarrow> F \\<longlonglongrightarrow> x\"\nproof atomize_elim\n  obtain A :: \"nat \\<Rightarrow> 'a set\" where *:\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 (rule countable_basis_at_decseq) blast\n  have \"eventually (\\<lambda>n. F n \\<in> S) sequentially\"\n    if \"\\<forall>n. F n \\<in> A n\" \"open S\" \"x \\<in> S\" for F S\n    using *(3)[of S] that by (auto elim: eventually_mono simp: subset_eq)\n  with * show \"\\<exists>A. (\\<forall>i. open (A i)) \\<and> (\\<forall>i. x \\<in> A i) \\<and> (\\<forall>F. (\\<forall>n. F n \\<in> A n) \\<longrightarrow> F \\<longlonglongrightarrow> x)\"\n    by (intro exI[of _ A]) (auto simp: tendsto_def)\nqed\n\nlemma (in first_countable_topology) sequentially_imp_eventually_nhds_within:\n  assumes \"\\<forall>f. (\\<forall>n. f n \\<in> s) \\<and> f \\<longlonglongrightarrow> a \\<longrightarrow> eventually (\\<lambda>n. P (f n)) sequentially\"\n  shows \"eventually P (inf (nhds a) (principal s))\"\nproof (rule ccontr)\n  obtain A :: \"nat \\<Rightarrow> 'a set\" where *:\n    \"\\<And>i. open (A i)\"\n    \"\\<And>i. a \\<in> A i\"\n    \"\\<And>F. \\<forall>n. F n \\<in> A n \\<Longrightarrow> F \\<longlonglongrightarrow> a\"\n    by (rule countable_basis) blast\n  assume \"\\<not> ?thesis\"\n  with * have \"\\<exists>F. \\<forall>n. F n \\<in> s \\<and> F n \\<in> A n \\<and> \\<not> P (F n)\"\n    unfolding eventually_inf_principal eventually_nhds\n    by (intro choice) fastforce\n  then obtain F where F: \"\\<forall>n. F n \\<in> s\" and \"\\<forall>n. F n \\<in> A n\" and F': \"\\<forall>n. \\<not> P (F n)\"\n    by blast\n  with * have \"F \\<longlonglongrightarrow> a\"\n    by auto\n  then have \"eventually (\\<lambda>n. P (F n)) sequentially\"\n    using assms F by simp\n  then show False\n    by (simp add: F')\nqed\n\nlemma (in first_countable_topology) eventually_nhds_within_iff_sequentially:\n  \"eventually P (inf (nhds a) (principal s)) \\<longleftrightarrow>\n    (\\<forall>f. (\\<forall>n. f n \\<in> s) \\<and> f \\<longlonglongrightarrow> a \\<longrightarrow> eventually (\\<lambda>n. P (f n)) sequentially)\"\nproof (safe intro!: sequentially_imp_eventually_nhds_within)\n  assume \"eventually P (inf (nhds a) (principal s))\"\n  then obtain S where \"open S\" \"a \\<in> S\" \"\\<forall>x\\<in>S. x \\<in> s \\<longrightarrow> P x\"\n    by (auto simp: eventually_inf_principal eventually_nhds)\n  moreover\n  fix f\n  assume \"\\<forall>n. f n \\<in> s\" \"f \\<longlonglongrightarrow> a\"\n  ultimately show \"eventually (\\<lambda>n. P (f n)) sequentially\"\n    by (auto dest!: topological_tendstoD elim: eventually_mono)\nqed\n\nlemma (in first_countable_topology) eventually_nhds_iff_sequentially:\n  \"eventually P (nhds a) \\<longleftrightarrow> (\\<forall>f. f \\<longlonglongrightarrow> a \\<longrightarrow> eventually (\\<lambda>n. P (f n)) sequentially)\"\n  using eventually_nhds_within_iff_sequentially[of P a UNIV] by simp\n\nlemma tendsto_at_iff_sequentially:\n  \"(f \\<longlongrightarrow> a) (at x within s) \\<longleftrightarrow> (\\<forall>X. (\\<forall>i. X i \\<in> s - {x}) \\<longrightarrow> X \\<longlonglongrightarrow> x \\<longrightarrow> ((f \\<circ> X) \\<longlonglongrightarrow> a))\"\n  for f :: \"'a::first_countable_topology \\<Rightarrow> _\"\n  unfolding filterlim_def[of _ \"nhds a\"] le_filter_def eventually_filtermap\n    at_within_def eventually_nhds_within_iff_sequentially comp_def\n  by metis\n\nlemma approx_from_above_dense_linorder:\n  fixes x::\"'a::{dense_linorder, linorder_topology, first_countable_topology}\"\n  assumes \"x < y\"\n  shows \"\\<exists>u. (\\<forall>n. u n > x) \\<and> (u \\<longlonglongrightarrow> x)\"\nproof -\n  obtain A :: \"nat \\<Rightarrow> 'a set\" where A: \"\\<And>i. open (A i)\" \"\\<And>i. x \\<in> A i\"\n                                      \"\\<And>F. (\\<forall>n. F n \\<in> A n) \\<Longrightarrow> F \\<longlonglongrightarrow> x\"\n    by (metis first_countable_topology_class.countable_basis)\n  define u where \"u = (\\<lambda>n. SOME z. z \\<in> A n \\<and> z > x)\"\n  have \"\\<exists>z. z \\<in> U \\<and> x < z\" if \"x \\<in> U\" \"open U\" for U\n    using open_right[OF `open U` `x \\<in> U` `x < y`]\n    by (meson atLeastLessThan_iff dense less_imp_le subset_eq)\n  then have *: \"u n \\<in> A n \\<and> x < u n\" for n\n    using `x \\<in> A n` `open (A n)` unfolding u_def by (metis (no_types, lifting) someI_ex)\n  then have \"u \\<longlonglongrightarrow> x\" using A(3) by simp\n  then show ?thesis using * by auto\nqed\n\nlemma approx_from_below_dense_linorder:\n  fixes x::\"'a::{dense_linorder, linorder_topology, first_countable_topology}\"\n  assumes \"x > y\"\n  shows \"\\<exists>u. (\\<forall>n. u n < x) \\<and> (u \\<longlonglongrightarrow> x)\"\nproof -\n  obtain A :: \"nat \\<Rightarrow> 'a set\" where A: \"\\<And>i. open (A i)\" \"\\<And>i. x \\<in> A i\"\n                                      \"\\<And>F. (\\<forall>n. F n \\<in> A n) \\<Longrightarrow> F \\<longlonglongrightarrow> x\"\n    by (metis first_countable_topology_class.countable_basis)\n  define u where \"u = (\\<lambda>n. SOME z. z \\<in> A n \\<and> z < x)\"\n  have \"\\<exists>z. z \\<in> U \\<and> z < x\" if \"x \\<in> U\" \"open U\" for U\n    using open_left[OF `open U` `x \\<in> U` `x > y`]\n    by (meson dense greaterThanAtMost_iff less_imp_le subset_eq)\n  then have *: \"u n \\<in> A n \\<and> u n < x\" for n\n    using `x \\<in> A n` `open (A n)` unfolding u_def by (metis (no_types, lifting) someI_ex)\n  then have \"u \\<longlonglongrightarrow> x\" using A(3) by simp\n  then show ?thesis using * by auto\nqed\n\n\nsubsection \\<open>Function limit at a point\\<close>\n\nabbreviation LIM :: \"('a::topological_space \\<Rightarrow> 'b::topological_space) \\<Rightarrow> 'a \\<Rightarrow> 'b \\<Rightarrow> bool\"\n    (\"((_)/ \\<midarrow>(_)/\\<rightarrow> (_))\" [60, 0, 60] 60)\n  where \"f \\<midarrow>a\\<rightarrow> L \\<equiv> (f \\<longlongrightarrow> L) (at a)\"\n\nlemma tendsto_within_open: \"a \\<in> S \\<Longrightarrow> open S \\<Longrightarrow> (f \\<longlongrightarrow> l) (at a within S) \\<longleftrightarrow> (f \\<midarrow>a\\<rightarrow> l)\"\n  by (simp add: tendsto_def at_within_open[where S = S])\n\nlemma tendsto_within_open_NO_MATCH:\n  \"a \\<in> S \\<Longrightarrow> NO_MATCH UNIV S \\<Longrightarrow> open S \\<Longrightarrow> (f \\<longlongrightarrow> l)(at a within S) \\<longleftrightarrow> (f \\<longlongrightarrow> l)(at a)\"\n  for f :: \"'a::topological_space \\<Rightarrow> 'b::topological_space\"\n  using tendsto_within_open by blast\n\nlemma LIM_const_not_eq[tendsto_intros]: \"k \\<noteq> L \\<Longrightarrow> \\<not> (\\<lambda>x. k) \\<midarrow>a\\<rightarrow> L\"\n  for a :: \"'a::perfect_space\" and k L :: \"'b::t2_space\"\n  by (simp add: tendsto_const_iff)\n\nlemmas LIM_not_zero = LIM_const_not_eq [where L = 0]\n\nlemma LIM_const_eq: \"(\\<lambda>x. k) \\<midarrow>a\\<rightarrow> L \\<Longrightarrow> k = L\"\n  for a :: \"'a::perfect_space\" and k L :: \"'b::t2_space\"\n  by (simp add: tendsto_const_iff)\n\nlemma LIM_unique: \"f \\<midarrow>a\\<rightarrow> L \\<Longrightarrow> f \\<midarrow>a\\<rightarrow> M \\<Longrightarrow> L = M\"\n  for a :: \"'a::perfect_space\" and L M :: \"'b::t2_space\"\n  using at_neq_bot by (rule tendsto_unique)\n\n\ntext \\<open>Limits are equal for functions equal except at limit point.\\<close>\nlemma LIM_equal: \"\\<forall>x. x \\<noteq> a \\<longrightarrow> f x = g x \\<Longrightarrow> (f \\<midarrow>a\\<rightarrow> l) \\<longleftrightarrow> (g \\<midarrow>a\\<rightarrow> l)\"\n  by (simp add: tendsto_def eventually_at_topological)\n\nlemma LIM_cong: \"a = b \\<Longrightarrow> (\\<And>x. x \\<noteq> b \\<Longrightarrow> f x = g x) \\<Longrightarrow> l = m \\<Longrightarrow> (f \\<midarrow>a\\<rightarrow> l) \\<longleftrightarrow> (g \\<midarrow>b\\<rightarrow> m)\"\n  by (simp add: LIM_equal)\n\nlemma LIM_cong_limit: \"f \\<midarrow>x\\<rightarrow> L \\<Longrightarrow> K = L \\<Longrightarrow> f \\<midarrow>x\\<rightarrow> K\"\n  by simp\n\nlemma tendsto_at_iff_tendsto_nhds: \"g \\<midarrow>l\\<rightarrow> g l \\<longleftrightarrow> (g \\<longlongrightarrow> g l) (nhds l)\"\n  unfolding tendsto_def eventually_at_filter\n  by (intro ext all_cong imp_cong) (auto elim!: eventually_mono)\n\nlemma tendsto_compose: \"g \\<midarrow>l\\<rightarrow> g l \\<Longrightarrow> (f \\<longlongrightarrow> l) F \\<Longrightarrow> ((\\<lambda>x. g (f x)) \\<longlongrightarrow> g l) F\"\n  unfolding tendsto_at_iff_tendsto_nhds by (rule filterlim_compose[of g])\n\nlemma LIM_o: \"g \\<midarrow>l\\<rightarrow> g l \\<Longrightarrow> f \\<midarrow>a\\<rightarrow> l \\<Longrightarrow> (g \\<circ> f) \\<midarrow>a\\<rightarrow> g l\"\n  unfolding o_def by (rule tendsto_compose)\n\nlemma tendsto_compose_eventually:\n  \"g \\<midarrow>l\\<rightarrow> m \\<Longrightarrow> (f \\<longlongrightarrow> l) F \\<Longrightarrow> eventually (\\<lambda>x. f x \\<noteq> l) F \\<Longrightarrow> ((\\<lambda>x. g (f x)) \\<longlongrightarrow> m) F\"\n  by (rule filterlim_compose[of g _ \"at l\"]) (auto simp add: filterlim_at)\n\nlemma LIM_compose_eventually:\n  assumes \"f \\<midarrow>a\\<rightarrow> b\"\n    and \"g \\<midarrow>b\\<rightarrow> c\"\n    and \"eventually (\\<lambda>x. f x \\<noteq> b) (at a)\"\n  shows \"(\\<lambda>x. g (f x)) \\<midarrow>a\\<rightarrow> c\"\n  using assms(2,1,3) by (rule tendsto_compose_eventually)\n\nlemma tendsto_compose_filtermap: \"((g \\<circ> f) \\<longlongrightarrow> T) F \\<longleftrightarrow> (g \\<longlongrightarrow> T) (filtermap f F)\"\n  by (simp add: filterlim_def filtermap_filtermap comp_def)\n\n\nsubsubsection \\<open>Relation of \\<open>LIM\\<close> and \\<open>LIMSEQ\\<close>\\<close>\n\nlemma (in first_countable_topology) sequentially_imp_eventually_within:\n  \"(\\<forall>f. (\\<forall>n. f n \\<in> s \\<and> f n \\<noteq> a) \\<and> f \\<longlonglongrightarrow> a \\<longrightarrow> eventually (\\<lambda>n. P (f n)) sequentially) \\<Longrightarrow>\n    eventually P (at a within s)\"\n  unfolding at_within_def\n  by (intro sequentially_imp_eventually_nhds_within) auto\n\nlemma (in first_countable_topology) sequentially_imp_eventually_at:\n  \"(\\<forall>f. (\\<forall>n. f n \\<noteq> a) \\<and> f \\<longlonglongrightarrow> a \\<longrightarrow> eventually (\\<lambda>n. P (f n)) sequentially) \\<Longrightarrow> eventually P (at a)\"\n  using sequentially_imp_eventually_within [where s=UNIV] by simp\n\nlemma LIMSEQ_SEQ_conv1:\n  fixes f :: \"'a::topological_space \\<Rightarrow> 'b::topological_space\"\n  assumes f: \"f \\<midarrow>a\\<rightarrow> l\"\n  shows \"\\<forall>S. (\\<forall>n. S n \\<noteq> a) \\<and> S \\<longlonglongrightarrow> a \\<longrightarrow> (\\<lambda>n. f (S n)) \\<longlonglongrightarrow> l\"\n  using tendsto_compose_eventually [OF f, where F=sequentially] by simp\n\nlemma LIMSEQ_SEQ_conv2:\n  fixes f :: \"'a::first_countable_topology \\<Rightarrow> 'b::topological_space\"\n  assumes \"\\<forall>S. (\\<forall>n. S n \\<noteq> a) \\<and> S \\<longlonglongrightarrow> a \\<longrightarrow> (\\<lambda>n. f (S n)) \\<longlonglongrightarrow> l\"\n  shows \"f \\<midarrow>a\\<rightarrow> l\"\n  using assms unfolding tendsto_def [where l=l] by (simp add: sequentially_imp_eventually_at)\n\nlemma LIMSEQ_SEQ_conv: \"(\\<forall>S. (\\<forall>n. S n \\<noteq> a) \\<and> S \\<longlonglongrightarrow> a \\<longrightarrow> (\\<lambda>n. X (S n)) \\<longlonglongrightarrow> L) \\<longleftrightarrow> X \\<midarrow>a\\<rightarrow> L\"\n  for a :: \"'a::first_countable_topology\" and L :: \"'b::topological_space\"\n  using LIMSEQ_SEQ_conv2 LIMSEQ_SEQ_conv1 ..\n\nlemma sequentially_imp_eventually_at_left:\n  fixes a :: \"'a::{linorder_topology,first_countable_topology}\"\n  assumes b[simp]: \"b < a\"\n    and *: \"\\<And>f. (\\<And>n. b < f n) \\<Longrightarrow> (\\<And>n. f n < a) \\<Longrightarrow> incseq f \\<Longrightarrow> f \\<longlonglongrightarrow> a \\<Longrightarrow>\n      eventually (\\<lambda>n. P (f n)) sequentially\"\n  shows \"eventually P (at_left a)\"\nproof (safe intro!: sequentially_imp_eventually_within)\n  fix X\n  assume X: \"\\<forall>n. X n \\<in> {..< a} \\<and> X n \\<noteq> a\" \"X \\<longlonglongrightarrow> a\"\n  show \"eventually (\\<lambda>n. P (X n)) sequentially\"\n  proof (rule ccontr)\n    assume neg: \"\\<not> ?thesis\"\n    have \"\\<exists>s. \\<forall>n. (\\<not> P (X (s n)) \\<and> b < X (s n)) \\<and> (X (s n) \\<le> X (s (Suc n)) \\<and> Suc (s n) \\<le> s (Suc n))\"\n      (is \"\\<exists>s. ?P s\")\n    proof (rule dependent_nat_choice)\n      have \"\\<not> eventually (\\<lambda>n. b < X n \\<longrightarrow> P (X n)) sequentially\"\n        by (intro not_eventually_impI neg order_tendstoD(1) [OF X(2) b])\n      then show \"\\<exists>x. \\<not> P (X x) \\<and> b < X x\"\n        by (auto dest!: not_eventuallyD)\n    next\n      fix x n\n      have \"\\<not> eventually (\\<lambda>n. Suc x \\<le> n \\<longrightarrow> b < X n \\<longrightarrow> X x < X n \\<longrightarrow> P (X n)) sequentially\"\n        using X\n        by (intro not_eventually_impI order_tendstoD(1)[OF X(2)] eventually_ge_at_top neg) auto\n      then show \"\\<exists>n. (\\<not> P (X n) \\<and> b < X n) \\<and> (X x \\<le> X n \\<and> Suc x \\<le> n)\"\n        by (auto dest!: not_eventuallyD)\n    qed\n    then obtain s where \"?P s\" ..\n    with X have \"b < X (s n)\"\n      and \"X (s n) < a\"\n      and \"incseq (\\<lambda>n. X (s n))\"\n      and \"(\\<lambda>n. X (s n)) \\<longlonglongrightarrow> a\"\n      and \"\\<not> P (X (s n))\"\n      for n\n      by (auto simp: subseq_Suc_iff Suc_le_eq incseq_Suc_iff\n          intro!: LIMSEQ_subseq_LIMSEQ[OF \\<open>X \\<longlonglongrightarrow> a\\<close>, unfolded comp_def])\n    from *[OF this(1,2,3,4)] this(5) show False\n      by auto\n  qed\nqed\n\nlemma tendsto_at_left_sequentially:\n  fixes a b :: \"'b::{linorder_topology,first_countable_topology}\"\n  assumes \"b < a\"\n  assumes *: \"\\<And>S. (\\<And>n. S n < a) \\<Longrightarrow> (\\<And>n. b < S n) \\<Longrightarrow> incseq S \\<Longrightarrow> S \\<longlonglongrightarrow> a \\<Longrightarrow>\n    (\\<lambda>n. X (S n)) \\<longlonglongrightarrow> L\"\n  shows \"(X \\<longlongrightarrow> L) (at_left a)\"\n  using assms by (simp add: tendsto_def [where l=L] sequentially_imp_eventually_at_left)\n\nlemma sequentially_imp_eventually_at_right:\n  fixes a b :: \"'a::{linorder_topology,first_countable_topology}\"\n  assumes b[simp]: \"a < b\"\n  assumes *: \"\\<And>f. (\\<And>n. a < f n) \\<Longrightarrow> (\\<And>n. f n < b) \\<Longrightarrow> decseq f \\<Longrightarrow> f \\<longlonglongrightarrow> a \\<Longrightarrow>\n    eventually (\\<lambda>n. P (f n)) sequentially\"\n  shows \"eventually P (at_right a)\"\nproof (safe intro!: sequentially_imp_eventually_within)\n  fix X\n  assume X: \"\\<forall>n. X n \\<in> {a <..} \\<and> X n \\<noteq> a\" \"X \\<longlonglongrightarrow> a\"\n  show \"eventually (\\<lambda>n. P (X n)) sequentially\"\n  proof (rule ccontr)\n    assume neg: \"\\<not> ?thesis\"\n    have \"\\<exists>s. \\<forall>n. (\\<not> P (X (s n)) \\<and> X (s n) < b) \\<and> (X (s (Suc n)) \\<le> X (s n) \\<and> Suc (s n) \\<le> s (Suc n))\"\n      (is \"\\<exists>s. ?P s\")\n    proof (rule dependent_nat_choice)\n      have \"\\<not> eventually (\\<lambda>n. X n < b \\<longrightarrow> P (X n)) sequentially\"\n        by (intro not_eventually_impI neg order_tendstoD(2) [OF X(2) b])\n      then show \"\\<exists>x. \\<not> P (X x) \\<and> X x < b\"\n        by (auto dest!: not_eventuallyD)\n    next\n      fix x n\n      have \"\\<not> eventually (\\<lambda>n. Suc x \\<le> n \\<longrightarrow> X n < b \\<longrightarrow> X n < X x \\<longrightarrow> P (X n)) sequentially\"\n        using X\n        by (intro not_eventually_impI order_tendstoD(2)[OF X(2)] eventually_ge_at_top neg) auto\n      then show \"\\<exists>n. (\\<not> P (X n) \\<and> X n < b) \\<and> (X n \\<le> X x \\<and> Suc x \\<le> n)\"\n        by (auto dest!: not_eventuallyD)\n    qed\n    then obtain s where \"?P s\" ..\n    with X have \"a < X (s n)\"\n      and \"X (s n) < b\"\n      and \"decseq (\\<lambda>n. X (s n))\"\n      and \"(\\<lambda>n. X (s n)) \\<longlonglongrightarrow> a\"\n      and \"\\<not> P (X (s n))\"\n      for n\n      by (auto simp: subseq_Suc_iff Suc_le_eq decseq_Suc_iff\n          intro!: LIMSEQ_subseq_LIMSEQ[OF \\<open>X \\<longlonglongrightarrow> a\\<close>, unfolded comp_def])\n    from *[OF this(1,2,3,4)] this(5) show False\n      by auto\n  qed\nqed\n\nlemma tendsto_at_right_sequentially:\n  fixes a :: \"_ :: {linorder_topology, first_countable_topology}\"\n  assumes \"a < b\"\n    and *: \"\\<And>S. (\\<And>n. a < S n) \\<Longrightarrow> (\\<And>n. S n < b) \\<Longrightarrow> decseq S \\<Longrightarrow> S \\<longlonglongrightarrow> a \\<Longrightarrow>\n      (\\<lambda>n. X (S n)) \\<longlonglongrightarrow> L\"\n  shows \"(X \\<longlongrightarrow> L) (at_right a)\"\n  using assms by (simp add: tendsto_def [where l=L] sequentially_imp_eventually_at_right)\n\n\nsubsection \\<open>Continuity\\<close>\n\nsubsubsection \\<open>Continuity on a set\\<close>\n\ndefinition continuous_on :: \"'a set \\<Rightarrow> ('a::topological_space \\<Rightarrow> 'b::topological_space) \\<Rightarrow> bool\"\n  where \"continuous_on s f \\<longleftrightarrow> (\\<forall>x\\<in>s. (f \\<longlongrightarrow> f x) (at x within s))\"\n\nlemma continuous_on_cong [cong]:\n  \"s = t \\<Longrightarrow> (\\<And>x. x \\<in> t \\<Longrightarrow> f x = g x) \\<Longrightarrow> continuous_on s f \\<longleftrightarrow> continuous_on t g\"\n  unfolding continuous_on_def\n  by (intro ball_cong filterlim_cong) (auto simp: eventually_at_filter)\n\nlemma continuous_on_strong_cong:\n  \"s = t \\<Longrightarrow> (\\<And>x. x \\<in> t =simp=> f x = g x) \\<Longrightarrow> continuous_on s f \\<longleftrightarrow> continuous_on t g\"\n  unfolding simp_implies_def by (rule continuous_on_cong)\n\nlemma continuous_on_topological:\n  \"continuous_on s f \\<longleftrightarrow>\n    (\\<forall>x\\<in>s. \\<forall>B. open B \\<longrightarrow> f x \\<in> B \\<longrightarrow> (\\<exists>A. open A \\<and> x \\<in> A \\<and> (\\<forall>y\\<in>s. y \\<in> A \\<longrightarrow> f y \\<in> B)))\"\n  unfolding continuous_on_def tendsto_def eventually_at_topological by metis\n\nlemma continuous_on_open_invariant:\n  \"continuous_on s f \\<longleftrightarrow> (\\<forall>B. open B \\<longrightarrow> (\\<exists>A. open A \\<and> A \\<inter> s = f -` B \\<inter> s))\"\nproof safe\n  fix B :: \"'b set\"\n  assume \"continuous_on s f\" \"open B\"\n  then have \"\\<forall>x\\<in>f -` B \\<inter> s. (\\<exists>A. open A \\<and> x \\<in> A \\<and> s \\<inter> A \\<subseteq> f -` B)\"\n    by (auto simp: continuous_on_topological subset_eq Ball_def imp_conjL)\n  then obtain A where \"\\<forall>x\\<in>f -` B \\<inter> s. open (A x) \\<and> x \\<in> A x \\<and> s \\<inter> A x \\<subseteq> f -` B\"\n    unfolding bchoice_iff ..\n  then show \"\\<exists>A. open A \\<and> A \\<inter> s = f -` B \\<inter> s\"\n    by (intro exI[of _ \"\\<Union>x\\<in>f -` B \\<inter> s. A x\"]) auto\nnext\n  assume B: \"\\<forall>B. open B \\<longrightarrow> (\\<exists>A. open A \\<and> A \\<inter> s = f -` B \\<inter> s)\"\n  show \"continuous_on s f\"\n    unfolding continuous_on_topological\n  proof safe\n    fix x B\n    assume \"x \\<in> s\" \"open B\" \"f x \\<in> B\"\n    with B obtain A where A: \"open A\" \"A \\<inter> s = f -` B \\<inter> s\"\n      by auto\n    with \\<open>x \\<in> s\\<close> \\<open>f x \\<in> B\\<close> show \"\\<exists>A. open A \\<and> x \\<in> A \\<and> (\\<forall>y\\<in>s. y \\<in> A \\<longrightarrow> f y \\<in> B)\"\n      by (intro exI[of _ A]) auto\n  qed\nqed\n\nlemma continuous_on_open_vimage:\n  \"open s \\<Longrightarrow> continuous_on s f \\<longleftrightarrow> (\\<forall>B. open B \\<longrightarrow> open (f -` B \\<inter> s))\"\n  unfolding continuous_on_open_invariant\n  by (metis open_Int Int_absorb Int_commute[of s] Int_assoc[of _ _ s])\n\ncorollary continuous_imp_open_vimage:\n  assumes \"continuous_on s f\" \"open s\" \"open B\" \"f -` B \\<subseteq> s\"\n  shows \"open (f -` B)\"\n  by (metis assms continuous_on_open_vimage le_iff_inf)\n\ncorollary open_vimage[continuous_intros]:\n  assumes \"open s\"\n    and \"continuous_on UNIV f\"\n  shows \"open (f -` s)\"\n  using assms by (simp add: continuous_on_open_vimage [OF open_UNIV])\n\nlemma continuous_on_closed_invariant:\n  \"continuous_on s f \\<longleftrightarrow> (\\<forall>B. closed B \\<longrightarrow> (\\<exists>A. closed A \\<and> A \\<inter> s = f -` B \\<inter> s))\"\nproof -\n  have *: \"(\\<And>A. P A \\<longleftrightarrow> Q (- A)) \\<Longrightarrow> (\\<forall>A. P A) \\<longleftrightarrow> (\\<forall>A. Q A)\"\n    for P Q :: \"'b set \\<Rightarrow> bool\"\n    by (metis double_compl)\n  show ?thesis\n    unfolding continuous_on_open_invariant\n    by (intro *) (auto simp: open_closed[symmetric])\nqed\n\nlemma continuous_on_closed_vimage:\n  \"closed s \\<Longrightarrow> continuous_on s f \\<longleftrightarrow> (\\<forall>B. closed B \\<longrightarrow> closed (f -` B \\<inter> s))\"\n  unfolding continuous_on_closed_invariant\n  by (metis closed_Int Int_absorb Int_commute[of s] Int_assoc[of _ _ s])\n\ncorollary closed_vimage_Int[continuous_intros]:\n  assumes \"closed s\"\n    and \"continuous_on t f\"\n    and t: \"closed t\"\n  shows \"closed (f -` s \\<inter> t)\"\n  using assms by (simp add: continuous_on_closed_vimage [OF t])\n\ncorollary closed_vimage[continuous_intros]:\n  assumes \"closed s\"\n    and \"continuous_on UNIV f\"\n  shows \"closed (f -` s)\"\n  using closed_vimage_Int [OF assms] by simp\n\nlemma continuous_on_empty [simp]: \"continuous_on {} f\"\n  by (simp add: continuous_on_def)\n\nlemma continuous_on_sing [simp]: \"continuous_on {x} f\"\n  by (simp add: continuous_on_def at_within_def)\n\nlemma continuous_on_open_Union:\n  \"(\\<And>s. s \\<in> S \\<Longrightarrow> open s) \\<Longrightarrow> (\\<And>s. s \\<in> S \\<Longrightarrow> continuous_on s f) \\<Longrightarrow> continuous_on (\\<Union>S) f\"\n  unfolding continuous_on_def\n  by safe (metis open_Union at_within_open UnionI)\n\nlemma continuous_on_open_UN:\n  \"(\\<And>s. s \\<in> S \\<Longrightarrow> open (A s)) \\<Longrightarrow> (\\<And>s. s \\<in> S \\<Longrightarrow> continuous_on (A s) f) \\<Longrightarrow>\n    continuous_on (\\<Union>s\\<in>S. A s) f\"\n  by (rule continuous_on_open_Union) auto\n\nlemma continuous_on_open_Un:\n  \"open s \\<Longrightarrow> open t \\<Longrightarrow> continuous_on s f \\<Longrightarrow> continuous_on t f \\<Longrightarrow> continuous_on (s \\<union> t) f\"\n  using continuous_on_open_Union [of \"{s,t}\"] by auto\n\nlemma continuous_on_closed_Un:\n  \"closed s \\<Longrightarrow> closed t \\<Longrightarrow> continuous_on s f \\<Longrightarrow> continuous_on t f \\<Longrightarrow> continuous_on (s \\<union> t) f\"\n  by (auto simp add: continuous_on_closed_vimage closed_Un Int_Un_distrib)\n\nlemma continuous_on_If:\n  assumes closed: \"closed s\" \"closed t\"\n    and cont: \"continuous_on s f\" \"continuous_on t g\"\n    and P: \"\\<And>x. x \\<in> s \\<Longrightarrow> \\<not> P x \\<Longrightarrow> f x = g x\" \"\\<And>x. x \\<in> t \\<Longrightarrow> P x \\<Longrightarrow> f x = g x\"\n  shows \"continuous_on (s \\<union> t) (\\<lambda>x. if P x then f x else g x)\"\n    (is \"continuous_on _ ?h\")\nproof-\n  from P have \"\\<forall>x\\<in>s. f x = ?h x\" \"\\<forall>x\\<in>t. g x = ?h x\"\n    by auto\n  with cont have \"continuous_on s ?h\" \"continuous_on t ?h\"\n    by simp_all\n  with closed show ?thesis\n    by (rule continuous_on_closed_Un)\nqed\n\nlemma continuous_on_id[continuous_intros]: \"continuous_on s (\\<lambda>x. x)\"\n  unfolding continuous_on_def by fast\n\nlemma continuous_on_id'[continuous_intros]: \"continuous_on s id\"\n  unfolding continuous_on_def id_def by fast\n\nlemma continuous_on_const[continuous_intros]: \"continuous_on s (\\<lambda>x. c)\"\n  unfolding continuous_on_def by auto\n\nlemma continuous_on_subset: \"continuous_on s f \\<Longrightarrow> t \\<subseteq> s \\<Longrightarrow> continuous_on t f\"\n  unfolding continuous_on_def by (metis subset_eq tendsto_within_subset)\n\nlemma continuous_on_compose[continuous_intros]:\n  \"continuous_on s f \\<Longrightarrow> continuous_on (f ` s) g \\<Longrightarrow> continuous_on s (g \\<circ> f)\"\n  unfolding continuous_on_topological by simp metis\n\nlemma continuous_on_compose2:\n  \"continuous_on t g \\<Longrightarrow> continuous_on s f \\<Longrightarrow> f ` s \\<subseteq> t \\<Longrightarrow> continuous_on s (\\<lambda>x. g (f x))\"\n  using continuous_on_compose[of s f g] continuous_on_subset by (force simp add: comp_def)\n\nlemma continuous_on_generate_topology:\n  assumes *: \"open = generate_topology X\"\n    and **: \"\\<And>B. B \\<in> X \\<Longrightarrow> \\<exists>C. open C \\<and> C \\<inter> A = f -` B \\<inter> A\"\n  shows \"continuous_on A f\"\n  unfolding continuous_on_open_invariant\nproof safe\n  fix B :: \"'a set\"\n  assume \"open B\"\n  then show \"\\<exists>C. open C \\<and> C \\<inter> A = f -` B \\<inter> A\"\n    unfolding *\n  proof induct\n    case (UN K)\n    then obtain C where \"\\<And>k. k \\<in> K \\<Longrightarrow> open (C k)\" \"\\<And>k. k \\<in> K \\<Longrightarrow> C k \\<inter> A = f -` k \\<inter> A\"\n      by metis\n    then show ?case\n      by (intro exI[of _ \"\\<Union>k\\<in>K. C k\"]) blast\n  qed (auto intro: **)\nqed\n\nlemma continuous_onI_mono:\n  fixes f :: \"'a::linorder_topology \\<Rightarrow> 'b::{dense_order,linorder_topology}\"\n  assumes \"open (f`A)\"\n    and mono: \"\\<And>x y. x \\<in> A \\<Longrightarrow> y \\<in> A \\<Longrightarrow> x \\<le> y \\<Longrightarrow> f x \\<le> f y\"\n  shows \"continuous_on A f\"\nproof (rule continuous_on_generate_topology[OF open_generated_order], safe)\n  have monoD: \"\\<And>x y. x \\<in> A \\<Longrightarrow> y \\<in> A \\<Longrightarrow> f x < f y \\<Longrightarrow> x < y\"\n    by (auto simp: not_le[symmetric] mono)\n  have \"\\<exists>x. x \\<in> A \\<and> f x < b \\<and> a < x\" if a: \"a \\<in> A\" and fa: \"f a < b\" for a b\n  proof -\n    obtain y where \"f a < y\" \"{f a ..< y} \\<subseteq> f`A\"\n      using open_right[OF \\<open>open (f`A)\\<close>, of \"f a\" b] a fa\n      by auto\n    obtain z where z: \"f a < z\" \"z < min b y\"\n      using dense[of \"f a\" \"min b y\"] \\<open>f a < y\\<close> \\<open>f a < b\\<close> by auto\n    then obtain c where \"z = f c\" \"c \\<in> A\"\n      using \\<open>{f a ..< y} \\<subseteq> f`A\\<close>[THEN subsetD, of z] by (auto simp: less_imp_le)\n    with a z show ?thesis\n      by (auto intro!: exI[of _ c] simp: monoD)\n  qed\n  then show \"\\<exists>C. open C \\<and> C \\<inter> A = f -` {..<b} \\<inter> A\" for b\n    by (intro exI[of _ \"(\\<Union>x\\<in>{x\\<in>A. f x < b}. {..< x})\"])\n       (auto intro: le_less_trans[OF mono] less_imp_le)\n\n  have \"\\<exists>x. x \\<in> A \\<and> b < f x \\<and> x < a\" if a: \"a \\<in> A\" and fa: \"b < f a\" for a b\n  proof -\n    note a fa\n    moreover\n    obtain y where \"y < f a\" \"{y <.. f a} \\<subseteq> f`A\"\n      using open_left[OF \\<open>open (f`A)\\<close>, of \"f a\" b]  a fa\n      by auto\n    then obtain z where z: \"max b y < z\" \"z < f a\"\n      using dense[of \"max b y\" \"f a\"] \\<open>y < f a\\<close> \\<open>b < f a\\<close> by auto\n    then obtain c where \"z = f c\" \"c \\<in> A\"\n      using \\<open>{y <.. f a} \\<subseteq> f`A\\<close>[THEN subsetD, of z] by (auto simp: less_imp_le)\n    with a z show ?thesis\n      by (auto intro!: exI[of _ c] simp: monoD)\n  qed\n  then show \"\\<exists>C. open C \\<and> C \\<inter> A = f -` {b <..} \\<inter> A\" for b\n    by (intro exI[of _ \"(\\<Union>x\\<in>{x\\<in>A. b < f x}. {x <..})\"])\n       (auto intro: less_le_trans[OF _ mono] less_imp_le)\nqed\n\n\nsubsubsection \\<open>Continuity at a point\\<close>\n\ndefinition continuous :: \"'a::t2_space filter \\<Rightarrow> ('a \\<Rightarrow> 'b::topological_space) \\<Rightarrow> bool\"\n  where \"continuous F f \\<longleftrightarrow> (f \\<longlongrightarrow> f (Lim F (\\<lambda>x. x))) F\"\n\nlemma continuous_bot[continuous_intros, simp]: \"continuous bot f\"\n  unfolding continuous_def by auto\n\nlemma continuous_trivial_limit: \"trivial_limit net \\<Longrightarrow> continuous net f\"\n  by simp\n\nlemma continuous_within: \"continuous (at x within s) f \\<longleftrightarrow> (f \\<longlongrightarrow> f x) (at x within s)\"\n  by (cases \"trivial_limit (at x within s)\") (auto simp add: Lim_ident_at continuous_def)\n\nlemma continuous_within_topological:\n  \"continuous (at x within s) f \\<longleftrightarrow>\n    (\\<forall>B. open B \\<longrightarrow> f x \\<in> B \\<longrightarrow> (\\<exists>A. open A \\<and> x \\<in> A \\<and> (\\<forall>y\\<in>s. y \\<in> A \\<longrightarrow> f y \\<in> B)))\"\n  unfolding continuous_within tendsto_def eventually_at_topological by metis\n\nlemma continuous_within_compose[continuous_intros]:\n  \"continuous (at x within s) f \\<Longrightarrow> continuous (at (f x) within f ` s) g \\<Longrightarrow>\n    continuous (at x within s) (g \\<circ> f)\"\n  by (simp add: continuous_within_topological) metis\n\nlemma continuous_within_compose2:\n  \"continuous (at x within s) f \\<Longrightarrow> continuous (at (f x) within f ` s) g \\<Longrightarrow>\n    continuous (at x within s) (\\<lambda>x. g (f x))\"\n  using continuous_within_compose[of x s f g] by (simp add: comp_def)\n\nlemma continuous_at: \"continuous (at x) f \\<longleftrightarrow> f \\<midarrow>x\\<rightarrow> f x\"\n  using continuous_within[of x UNIV f] by simp\n\nlemma continuous_ident[continuous_intros, simp]: \"continuous (at x within S) (\\<lambda>x. x)\"\n  unfolding continuous_within by (rule tendsto_ident_at)\n\nlemma continuous_const[continuous_intros, simp]: \"continuous F (\\<lambda>x. c)\"\n  unfolding continuous_def by (rule tendsto_const)\n\nlemma continuous_on_eq_continuous_within:\n  \"continuous_on s f \\<longleftrightarrow> (\\<forall>x\\<in>s. continuous (at x within s) f)\"\n  unfolding continuous_on_def continuous_within ..\n\nabbreviation isCont :: \"('a::t2_space \\<Rightarrow> 'b::topological_space) \\<Rightarrow> 'a \\<Rightarrow> bool\"\n  where \"isCont f a \\<equiv> continuous (at a) f\"\n\nlemma isCont_def: \"isCont f a \\<longleftrightarrow> f \\<midarrow>a\\<rightarrow> f a\"\n  by (rule continuous_at)\n\nlemma isCont_cong:\n  assumes \"eventually (\\<lambda>x. f x = g x) (nhds x)\"\n  shows \"isCont f x \\<longleftrightarrow> isCont g x\"\nproof -\n  from assms have [simp]: \"f x = g x\"\n    by (rule eventually_nhds_x_imp_x)\n  from assms have \"eventually (\\<lambda>x. f x = g x) (at x)\"\n    by (auto simp: eventually_at_filter elim!: eventually_mono)\n  with assms have \"isCont f x \\<longleftrightarrow> isCont g x\" unfolding isCont_def\n    by (intro filterlim_cong) (auto elim!: eventually_mono)\n  with assms show ?thesis by simp\nqed\n\nlemma continuous_at_imp_continuous_at_within: \"isCont f x \\<Longrightarrow> continuous (at x within s) f\"\n  by (auto intro: tendsto_mono at_le simp: continuous_at continuous_within)\n\nlemma continuous_on_eq_continuous_at: \"open s \\<Longrightarrow> continuous_on s f \\<longleftrightarrow> (\\<forall>x\\<in>s. isCont f x)\"\n  by (simp add: continuous_on_def continuous_at at_within_open[of _ s])\n\nlemma continuous_within_open: \"a \\<in> A \\<Longrightarrow> open A \\<Longrightarrow> continuous (at a within A) f \\<longleftrightarrow> isCont f a\"\n  by (simp add: at_within_open_NO_MATCH)\n\nlemma continuous_at_imp_continuous_on: \"\\<forall>x\\<in>s. isCont f x \\<Longrightarrow> continuous_on s f\"\n  by (auto intro: continuous_at_imp_continuous_at_within simp: continuous_on_eq_continuous_within)\n\nlemma isCont_o2: \"isCont f a \\<Longrightarrow> isCont g (f a) \\<Longrightarrow> isCont (\\<lambda>x. g (f x)) a\"\n  unfolding isCont_def by (rule tendsto_compose)\n\nlemma isCont_o[continuous_intros]: \"isCont f a \\<Longrightarrow> isCont g (f a) \\<Longrightarrow> isCont (g \\<circ> f) a\"\n  unfolding o_def by (rule isCont_o2)\n\nlemma isCont_tendsto_compose: \"isCont g l \\<Longrightarrow> (f \\<longlongrightarrow> l) F \\<Longrightarrow> ((\\<lambda>x. g (f x)) \\<longlongrightarrow> g l) F\"\n  unfolding isCont_def by (rule tendsto_compose)\n\nlemma continuous_on_tendsto_compose:\n  assumes f_cont: \"continuous_on s f\"\n    and g: \"(g \\<longlongrightarrow> l) F\"\n    and l: \"l \\<in> s\"\n    and ev: \"\\<forall>\\<^sub>Fx in F. g x \\<in> s\"\n  shows \"((\\<lambda>x. f (g x)) \\<longlongrightarrow> f l) F\"\nproof -\n  from f_cont l have f: \"(f \\<longlongrightarrow> f l) (at l within s)\"\n    by (simp add: continuous_on_def)\n  have i: \"((\\<lambda>x. if g x = l then f l else f (g x)) \\<longlongrightarrow> f l) F\"\n    by (rule filterlim_If)\n       (auto intro!: filterlim_compose[OF f] eventually_conj tendsto_mono[OF _ g]\n             simp: filterlim_at eventually_inf_principal eventually_mono[OF ev])\n  show ?thesis\n    by (rule filterlim_cong[THEN iffD1[OF _ i]]) auto\nqed\n\nlemma continuous_within_compose3:\n  \"isCont g (f x) \\<Longrightarrow> continuous (at x within s) f \\<Longrightarrow> continuous (at x within s) (\\<lambda>x. g (f x))\"\n  using continuous_at_imp_continuous_at_within continuous_within_compose2 by blast\n\nlemma filtermap_nhds_open_map:\n  assumes cont: \"isCont f a\"\n    and open_map: \"\\<And>S. open S \\<Longrightarrow> open (f`S)\"\n  shows \"filtermap f (nhds a) = nhds (f a)\"\n  unfolding filter_eq_iff\nproof safe\n  fix P\n  assume \"eventually P (filtermap f (nhds a))\"\n  then obtain S where \"open S\" \"a \\<in> S\" \"\\<forall>x\\<in>S. P (f x)\"\n    by (auto simp: eventually_filtermap eventually_nhds)\n  then show \"eventually P (nhds (f a))\"\n    unfolding eventually_nhds by (intro exI[of _ \"f`S\"]) (auto intro!: open_map)\nqed (metis filterlim_iff tendsto_at_iff_tendsto_nhds isCont_def eventually_filtermap cont)\n\nlemma continuous_at_split:\n  \"continuous (at x) f \\<longleftrightarrow> continuous (at_left x) f \\<and> continuous (at_right x) f\"\n  for x :: \"'a::linorder_topology\"\n  by (simp add: continuous_within filterlim_at_split)\n\ntext \\<open>\n  The following open/closed Collect lemmas are ported from\n  S\u00e9bastien Gou\u00ebzel's \\<open>Ergodic_Theory\\<close>.\n\\<close>\nlemma open_Collect_neq:\n  fixes f g :: \"'a::topological_space \\<Rightarrow> 'b::t2_space\"\n  assumes f: \"continuous_on UNIV f\" and g: \"continuous_on UNIV g\"\n  shows \"open {x. f x \\<noteq> g x}\"\nproof (rule openI)\n  fix t\n  assume \"t \\<in> {x. f x \\<noteq> g x}\"\n  then obtain U V where *: \"open U\" \"open V\" \"f t \\<in> U\" \"g t \\<in> V\" \"U \\<inter> V = {}\"\n    by (auto simp add: separation_t2)\n  with open_vimage[OF \\<open>open U\\<close> f] open_vimage[OF \\<open>open V\\<close> g]\n  show \"\\<exists>T. open T \\<and> t \\<in> T \\<and> T \\<subseteq> {x. f x \\<noteq> g x}\"\n    by (intro exI[of _ \"f -` U \\<inter> g -` V\"]) auto\nqed\n\nlemma closed_Collect_eq:\n  fixes f g :: \"'a::topological_space \\<Rightarrow> 'b::t2_space\"\n  assumes f: \"continuous_on UNIV f\" and g: \"continuous_on UNIV g\"\n  shows \"closed {x. f x = g x}\"\n  using open_Collect_neq[OF f g] by (simp add: closed_def Collect_neg_eq)\n\nlemma open_Collect_less:\n  fixes f g :: \"'a::topological_space \\<Rightarrow> 'b::linorder_topology\"\n  assumes f: \"continuous_on UNIV f\" and g: \"continuous_on UNIV g\"\n  shows \"open {x. f x < g x}\"\nproof (rule openI)\n  fix t\n  assume t: \"t \\<in> {x. f x < g x}\"\n  show \"\\<exists>T. open T \\<and> t \\<in> T \\<and> T \\<subseteq> {x. f x < g x}\"\n  proof (cases \"\\<exists>z. f t < z \\<and> z < g t\")\n    case True\n    then obtain z where \"f t < z \\<and> z < g t\" by blast\n    then show ?thesis\n      using open_vimage[OF _ f, of \"{..< z}\"] open_vimage[OF _ g, of \"{z <..}\"]\n      by (intro exI[of _ \"f -` {..<z} \\<inter> g -` {z<..}\"]) auto\n  next\n    case False\n    then have *: \"{g t ..} = {f t <..}\" \"{..< g t} = {.. f t}\"\n      using t by (auto intro: leI)\n    show ?thesis\n      using open_vimage[OF _ f, of \"{..< g t}\"] open_vimage[OF _ g, of \"{f t <..}\"] t\n      apply (intro exI[of _ \"f -` {..< g t} \\<inter> g -` {f t<..}\"])\n      apply (simp add: open_Int)\n      apply (auto simp add: *)\n      done\n  qed\nqed\n\nlemma closed_Collect_le:\n  fixes f g :: \"'a :: topological_space \\<Rightarrow> 'b::linorder_topology\"\n  assumes f: \"continuous_on UNIV f\"\n    and g: \"continuous_on UNIV g\"\n  shows \"closed {x. f x \\<le> g x}\"\n  using open_Collect_less [OF g f]\n  by (simp add: closed_def Collect_neg_eq[symmetric] not_le)\n\n\nsubsubsection \\<open>Open-cover compactness\\<close>\n\ncontext topological_space\nbegin\n\ndefinition compact :: \"'a set \\<Rightarrow> bool\"\n  where compact_eq_heine_borel:  (* This name is used for backwards compatibility *)\n    \"compact S \\<longleftrightarrow> (\\<forall>C. (\\<forall>c\\<in>C. open c) \\<and> S \\<subseteq> \\<Union>C \\<longrightarrow> (\\<exists>D\\<subseteq>C. finite D \\<and> S \\<subseteq> \\<Union>D))\"\n\nlemma compactI:\n  assumes \"\\<And>C. \\<forall>t\\<in>C. open t \\<Longrightarrow> s \\<subseteq> \\<Union>C \\<Longrightarrow> \\<exists>C'. C' \\<subseteq> C \\<and> finite C' \\<and> s \\<subseteq> \\<Union>C'\"\n  shows \"compact s\"\n  unfolding compact_eq_heine_borel using assms by metis\n\nlemma compact_empty[simp]: \"compact {}\"\n  by (auto intro!: compactI)\n\nlemma compactE:\n  assumes \"compact s\"\n    and \"\\<forall>t\\<in>C. open t\"\n    and \"s \\<subseteq> \\<Union>C\"\n  obtains C' where \"C' \\<subseteq> C\" and \"finite C'\" and \"s \\<subseteq> \\<Union>C'\"\n  using assms unfolding compact_eq_heine_borel by metis\n\nlemma compactE_image:\n  assumes \"compact s\"\n    and \"\\<forall>t\\<in>C. open (f t)\"\n    and \"s \\<subseteq> (\\<Union>c\\<in>C. f c)\"\n  obtains C' where \"C' \\<subseteq> C\" and \"finite C'\" and \"s \\<subseteq> (\\<Union>c\\<in>C'. f c)\"\n  using assms unfolding ball_simps [symmetric]\n  by (metis (lifting) finite_subset_image compact_eq_heine_borel[of s])\n\nlemma compact_Int_closed [intro]:\n  assumes \"compact s\"\n    and \"closed t\"\n  shows \"compact (s \\<inter> t)\"\nproof (rule compactI)\n  fix C\n  assume C: \"\\<forall>c\\<in>C. open c\"\n  assume cover: \"s \\<inter> t \\<subseteq> \\<Union>C\"\n  from C \\<open>closed t\\<close> have \"\\<forall>c\\<in>C \\<union> {- t}. open c\"\n    by auto\n  moreover from cover have \"s \\<subseteq> \\<Union>(C \\<union> {- t})\"\n    by auto\n  ultimately have \"\\<exists>D\\<subseteq>C \\<union> {- t}. finite D \\<and> s \\<subseteq> \\<Union>D\"\n    using \\<open>compact s\\<close> unfolding compact_eq_heine_borel by auto\n  then obtain D where \"D \\<subseteq> C \\<union> {- t} \\<and> finite D \\<and> s \\<subseteq> \\<Union>D\" ..\n  then show \"\\<exists>D\\<subseteq>C. finite D \\<and> s \\<inter> t \\<subseteq> \\<Union>D\"\n    by (intro exI[of _ \"D - {-t}\"]) auto\nqed\n\nlemma inj_setminus: \"inj_on uminus (A::'a set set)\"\n  by (auto simp: inj_on_def)\n\n\nsubsection \\<open>Finite intersection property\\<close>\n\nlemma compact_fip:\n  \"compact U \\<longleftrightarrow>\n    (\\<forall>A. (\\<forall>a\\<in>A. closed a) \\<longrightarrow> (\\<forall>B \\<subseteq> A. finite B \\<longrightarrow> U \\<inter> \\<Inter>B \\<noteq> {}) \\<longrightarrow> U \\<inter> \\<Inter>A \\<noteq> {})\"\n  (is \"_ \\<longleftrightarrow> ?R\")\nproof (safe intro!: compact_eq_heine_borel[THEN iffD2])\n  fix A\n  assume \"compact U\"\n  assume A: \"\\<forall>a\\<in>A. closed a\" \"U \\<inter> \\<Inter>A = {}\"\n  assume fin: \"\\<forall>B \\<subseteq> A. finite B \\<longrightarrow> U \\<inter> \\<Inter>B \\<noteq> {}\"\n  from A have \"(\\<forall>a\\<in>uminus`A. open a) \\<and> U \\<subseteq> \\<Union>(uminus`A)\"\n    by auto\n  with \\<open>compact U\\<close> obtain B where \"B \\<subseteq> A\" \"finite (uminus`B)\" \"U \\<subseteq> \\<Union>(uminus`B)\"\n    unfolding compact_eq_heine_borel by (metis subset_image_iff)\n  with fin[THEN spec, of B] show False\n    by (auto dest: finite_imageD intro: inj_setminus)\nnext\n  fix A\n  assume ?R\n  assume \"\\<forall>a\\<in>A. open a\" \"U \\<subseteq> \\<Union>A\"\n  then have \"U \\<inter> \\<Inter>(uminus`A) = {}\" \"\\<forall>a\\<in>uminus`A. closed a\"\n    by auto\n  with \\<open>?R\\<close> obtain B where \"B \\<subseteq> A\" \"finite (uminus`B)\" \"U \\<inter> \\<Inter>(uminus`B) = {}\"\n    by (metis subset_image_iff)\n  then show \"\\<exists>T\\<subseteq>A. finite T \\<and> U \\<subseteq> \\<Union>T\"\n    by (auto intro!: exI[of _ B] inj_setminus dest: finite_imageD)\nqed\n\nlemma compact_imp_fip:\n  assumes \"compact S\"\n    and \"\\<And>T. T \\<in> F \\<Longrightarrow> closed T\"\n    and \"\\<And>F'. finite F' \\<Longrightarrow> F' \\<subseteq> F \\<Longrightarrow> S \\<inter> (\\<Inter>F') \\<noteq> {}\"\n  shows \"S \\<inter> (\\<Inter>F) \\<noteq> {}\"\n  using assms unfolding compact_fip by auto\n\nlemma compact_imp_fip_image:\n  assumes \"compact s\"\n    and P: \"\\<And>i. i \\<in> I \\<Longrightarrow> closed (f i)\"\n    and Q: \"\\<And>I'. finite I' \\<Longrightarrow> I' \\<subseteq> I \\<Longrightarrow> (s \\<inter> (\\<Inter>i\\<in>I'. f i) \\<noteq> {})\"\n  shows \"s \\<inter> (\\<Inter>i\\<in>I. f i) \\<noteq> {}\"\nproof -\n  note \\<open>compact s\\<close>\n  moreover from P have \"\\<forall>i \\<in> f ` I. closed i\"\n    by blast\n  moreover have \"\\<forall>A. finite A \\<and> A \\<subseteq> f ` I \\<longrightarrow> (s \\<inter> (\\<Inter>A) \\<noteq> {})\"\n    apply rule\n    apply rule\n    apply (erule conjE)\n  proof -\n    fix A :: \"'a set set\"\n    assume \"finite A\" and \"A \\<subseteq> f ` I\"\n    then obtain B where \"B \\<subseteq> I\" and \"finite B\" and \"A = f ` B\"\n      using finite_subset_image [of A f I] by blast\n    with Q [of B] show \"s \\<inter> \\<Inter>A \\<noteq> {}\"\n      by simp\n  qed\n  ultimately have \"s \\<inter> (\\<Inter>(f ` I)) \\<noteq> {}\"\n    by (metis compact_imp_fip)\n  then show ?thesis by simp\nqed\n\nend\n\nlemma (in t2_space) compact_imp_closed:\n  assumes \"compact s\"\n  shows \"closed s\"\n  unfolding closed_def\nproof (rule openI)\n  fix y\n  assume \"y \\<in> - s\"\n  let ?C = \"\\<Union>x\\<in>s. {u. open u \\<and> x \\<in> u \\<and> eventually (\\<lambda>y. y \\<notin> u) (nhds y)}\"\n  note \\<open>compact s\\<close>\n  moreover have \"\\<forall>u\\<in>?C. open u\" by simp\n  moreover have \"s \\<subseteq> \\<Union>?C\"\n  proof\n    fix x\n    assume \"x \\<in> s\"\n    with \\<open>y \\<in> - s\\<close> have \"x \\<noteq> y\" by clarsimp\n    then have \"\\<exists>u v. open u \\<and> open v \\<and> x \\<in> u \\<and> y \\<in> v \\<and> u \\<inter> v = {}\"\n      by (rule hausdorff)\n    with \\<open>x \\<in> s\\<close> show \"x \\<in> \\<Union>?C\"\n      unfolding eventually_nhds by auto\n  qed\n  ultimately obtain D where \"D \\<subseteq> ?C\" and \"finite D\" and \"s \\<subseteq> \\<Union>D\"\n    by (rule compactE)\n  from \\<open>D \\<subseteq> ?C\\<close> have \"\\<forall>x\\<in>D. eventually (\\<lambda>y. y \\<notin> x) (nhds y)\"\n    by auto\n  with \\<open>finite D\\<close> have \"eventually (\\<lambda>y. y \\<notin> \\<Union>D) (nhds y)\"\n    by (simp add: eventually_ball_finite)\n  with \\<open>s \\<subseteq> \\<Union>D\\<close> have \"eventually (\\<lambda>y. y \\<notin> s) (nhds y)\"\n    by (auto elim!: eventually_mono)\n  then show \"\\<exists>t. open t \\<and> y \\<in> t \\<and> t \\<subseteq> - s\"\n    by (simp add: eventually_nhds subset_eq)\nqed\n\nlemma compact_continuous_image:\n  assumes f: \"continuous_on s f\"\n    and s: \"compact s\"\n  shows \"compact (f ` s)\"\nproof (rule compactI)\n  fix C\n  assume \"\\<forall>c\\<in>C. open c\" and cover: \"f`s \\<subseteq> \\<Union>C\"\n  with f have \"\\<forall>c\\<in>C. \\<exists>A. open A \\<and> A \\<inter> s = f -` c \\<inter> s\"\n    unfolding continuous_on_open_invariant by blast\n  then obtain A where A: \"\\<forall>c\\<in>C. open (A c) \\<and> A c \\<inter> s = f -` c \\<inter> s\"\n    unfolding bchoice_iff ..\n  with cover have \"\\<forall>c\\<in>C. open (A c)\" \"s \\<subseteq> (\\<Union>c\\<in>C. A c)\"\n    by (fastforce simp add: subset_eq set_eq_iff)+\n  from compactE_image[OF s this] obtain D where \"D \\<subseteq> C\" \"finite D\" \"s \\<subseteq> (\\<Union>c\\<in>D. A c)\" .\n  with A show \"\\<exists>D \\<subseteq> C. finite D \\<and> f`s \\<subseteq> \\<Union>D\"\n    by (intro exI[of _ D]) (fastforce simp add: subset_eq set_eq_iff)+\nqed\n\nlemma continuous_on_inv:\n  fixes f :: \"'a::topological_space \\<Rightarrow> 'b::t2_space\"\n  assumes \"continuous_on s f\"\n    and \"compact s\"\n    and \"\\<forall>x\\<in>s. g (f x) = x\"\n  shows \"continuous_on (f ` s) g\"\n  unfolding continuous_on_topological\nproof (clarsimp simp add: assms(3))\n  fix x :: 'a and B :: \"'a set\"\n  assume \"x \\<in> s\" and \"open B\" and \"x \\<in> B\"\n  have 1: \"\\<forall>x\\<in>s. f x \\<in> f ` (s - B) \\<longleftrightarrow> x \\<in> s - B\"\n    using assms(3) by (auto, metis)\n  have \"continuous_on (s - B) f\"\n    using \\<open>continuous_on s f\\<close> Diff_subset\n    by (rule continuous_on_subset)\n  moreover have \"compact (s - B)\"\n    using \\<open>open B\\<close> and \\<open>compact s\\<close>\n    unfolding Diff_eq by (intro compact_Int_closed closed_Compl)\n  ultimately have \"compact (f ` (s - B))\"\n    by (rule compact_continuous_image)\n  then have \"closed (f ` (s - B))\"\n    by (rule compact_imp_closed)\n  then have \"open (- f ` (s - B))\"\n    by (rule open_Compl)\n  moreover have \"f x \\<in> - f ` (s - B)\"\n    using \\<open>x \\<in> s\\<close> and \\<open>x \\<in> B\\<close> by (simp add: 1)\n  moreover have \"\\<forall>y\\<in>s. f y \\<in> - f ` (s - B) \\<longrightarrow> y \\<in> B\"\n    by (simp add: 1)\n  ultimately show \"\\<exists>A. open A \\<and> f x \\<in> A \\<and> (\\<forall>y\\<in>s. f y \\<in> A \\<longrightarrow> y \\<in> B)\"\n    by fast\nqed\n\nlemma continuous_on_inv_into:\n  fixes f :: \"'a::topological_space \\<Rightarrow> 'b::t2_space\"\n  assumes s: \"continuous_on s f\" \"compact s\"\n    and f: \"inj_on f s\"\n  shows \"continuous_on (f ` s) (the_inv_into s f)\"\n  by (rule continuous_on_inv[OF s]) (auto simp: the_inv_into_f_f[OF f])\n\nlemma (in linorder_topology) compact_attains_sup:\n  assumes \"compact S\" \"S \\<noteq> {}\"\n  shows \"\\<exists>s\\<in>S. \\<forall>t\\<in>S. t \\<le> s\"\nproof (rule classical)\n  assume \"\\<not> (\\<exists>s\\<in>S. \\<forall>t\\<in>S. t \\<le> s)\"\n  then obtain t where t: \"\\<forall>s\\<in>S. t s \\<in> S\" and \"\\<forall>s\\<in>S. s < t s\"\n    by (metis not_le)\n  then have \"\\<forall>s\\<in>S. open {..< t s}\" \"S \\<subseteq> (\\<Union>s\\<in>S. {..< t s})\"\n    by auto\n  with \\<open>compact S\\<close> obtain C where \"C \\<subseteq> S\" \"finite C\" and C: \"S \\<subseteq> (\\<Union>s\\<in>C. {..< t s})\"\n    by (erule compactE_image)\n  with \\<open>S \\<noteq> {}\\<close> have Max: \"Max (t`C) \\<in> t`C\" and \"\\<forall>s\\<in>t`C. s \\<le> Max (t`C)\"\n    by (auto intro!: Max_in)\n  with C have \"S \\<subseteq> {..< Max (t`C)}\"\n    by (auto intro: less_le_trans simp: subset_eq)\n  with t Max \\<open>C \\<subseteq> S\\<close> show ?thesis\n    by fastforce\nqed\n\nlemma (in linorder_topology) compact_attains_inf:\n  assumes \"compact S\" \"S \\<noteq> {}\"\n  shows \"\\<exists>s\\<in>S. \\<forall>t\\<in>S. s \\<le> t\"\nproof (rule classical)\n  assume \"\\<not> (\\<exists>s\\<in>S. \\<forall>t\\<in>S. s \\<le> t)\"\n  then obtain t where t: \"\\<forall>s\\<in>S. t s \\<in> S\" and \"\\<forall>s\\<in>S. t s < s\"\n    by (metis not_le)\n  then have \"\\<forall>s\\<in>S. open {t s <..}\" \"S \\<subseteq> (\\<Union>s\\<in>S. {t s <..})\"\n    by auto\n  with \\<open>compact S\\<close> obtain C where \"C \\<subseteq> S\" \"finite C\" and C: \"S \\<subseteq> (\\<Union>s\\<in>C. {t s <..})\"\n    by (erule compactE_image)\n  with \\<open>S \\<noteq> {}\\<close> have Min: \"Min (t`C) \\<in> t`C\" and \"\\<forall>s\\<in>t`C. Min (t`C) \\<le> s\"\n    by (auto intro!: Min_in)\n  with C have \"S \\<subseteq> {Min (t`C) <..}\"\n    by (auto intro: le_less_trans simp: subset_eq)\n  with t Min \\<open>C \\<subseteq> S\\<close> show ?thesis\n    by fastforce\nqed\n\nlemma continuous_attains_sup:\n  fixes f :: \"'a::topological_space \\<Rightarrow> 'b::linorder_topology\"\n  shows \"compact s \\<Longrightarrow> s \\<noteq> {} \\<Longrightarrow> continuous_on s f \\<Longrightarrow> (\\<exists>x\\<in>s. \\<forall>y\\<in>s.  f y \\<le> f x)\"\n  using compact_attains_sup[of \"f ` s\"] compact_continuous_image[of s f] by auto\n\nlemma continuous_attains_inf:\n  fixes f :: \"'a::topological_space \\<Rightarrow> 'b::linorder_topology\"\n  shows \"compact s \\<Longrightarrow> s \\<noteq> {} \\<Longrightarrow> continuous_on s f \\<Longrightarrow> (\\<exists>x\\<in>s. \\<forall>y\\<in>s. f x \\<le> f y)\"\n  using compact_attains_inf[of \"f ` s\"] compact_continuous_image[of s f] by auto\n\n\nsubsection \\<open>Connectedness\\<close>\n\ncontext topological_space\nbegin\n\ndefinition \"connected S \\<longleftrightarrow>\n  \\<not> (\\<exists>A B. open A \\<and> open B \\<and> S \\<subseteq> A \\<union> B \\<and> A \\<inter> B \\<inter> S = {} \\<and> A \\<inter> S \\<noteq> {} \\<and> B \\<inter> S \\<noteq> {})\"\n\nlemma connectedI:\n  \"(\\<And>A B. open A \\<Longrightarrow> open B \\<Longrightarrow> A \\<inter> U \\<noteq> {} \\<Longrightarrow> B \\<inter> U \\<noteq> {} \\<Longrightarrow> A \\<inter> B \\<inter> U = {} \\<Longrightarrow> U \\<subseteq> A \\<union> B \\<Longrightarrow> False)\n  \\<Longrightarrow> connected U\"\n  by (auto simp: connected_def)\n\nlemma connected_empty [simp]: \"connected {}\"\n  by (auto intro!: connectedI)\n\nlemma connected_sing [simp]: \"connected {x}\"\n  by (auto intro!: connectedI)\n\nlemma connectedD:\n  \"connected A \\<Longrightarrow> open U \\<Longrightarrow> open V \\<Longrightarrow> U \\<inter> V \\<inter> A = {} \\<Longrightarrow> A \\<subseteq> U \\<union> V \\<Longrightarrow> U \\<inter> A = {} \\<or> V \\<inter> A = {}\"\n  by (auto simp: connected_def)\n\nend\n\nlemma connected_closed:\n  \"connected s \\<longleftrightarrow>\n    \\<not> (\\<exists>A B. closed A \\<and> closed B \\<and> s \\<subseteq> A \\<union> B \\<and> A \\<inter> B \\<inter> s = {} \\<and> A \\<inter> s \\<noteq> {} \\<and> B \\<inter> s \\<noteq> {})\"\n  apply (simp add: connected_def del: ex_simps, safe)\n   apply (drule_tac x=\"-A\" in spec)\n   apply (drule_tac x=\"-B\" in spec)\n   apply (fastforce simp add: closed_def [symmetric])\n  apply (drule_tac x=\"-A\" in spec)\n  apply (drule_tac x=\"-B\" in spec)\n  apply (fastforce simp add: open_closed [symmetric])\n  done\n\nlemma connected_closedD:\n  \"\\<lbrakk>connected s; A \\<inter> B \\<inter> s = {}; s \\<subseteq> A \\<union> B; closed A; closed B\\<rbrakk> \\<Longrightarrow> A \\<inter> s = {} \\<or> B \\<inter> s = {}\"\n  by (simp add: connected_closed)\n\nlemma connected_Union:\n  assumes cs: \"\\<And>s. s \\<in> S \\<Longrightarrow> connected s\"\n    and ne: \"\\<Inter>S \\<noteq> {}\"\n  shows \"connected(\\<Union>S)\"\nproof (rule connectedI)\n  fix A B\n  assume A: \"open A\" and B: \"open B\" and Alap: \"A \\<inter> \\<Union>S \\<noteq> {}\" and Blap: \"B \\<inter> \\<Union>S \\<noteq> {}\"\n    and disj: \"A \\<inter> B \\<inter> \\<Union>S = {}\" and cover: \"\\<Union>S \\<subseteq> A \\<union> B\"\n  have disjs:\"\\<And>s. s \\<in> S \\<Longrightarrow> A \\<inter> B \\<inter> s = {}\"\n    using disj by auto\n  obtain sa where sa: \"sa \\<in> S\" \"A \\<inter> sa \\<noteq> {}\"\n    using Alap by auto\n  obtain sb where sb: \"sb \\<in> S\" \"B \\<inter> sb \\<noteq> {}\"\n    using Blap by auto\n  obtain x where x: \"\\<And>s. s \\<in> S \\<Longrightarrow> x \\<in> s\"\n    using ne by auto\n  then have \"x \\<in> \\<Union>S\"\n    using \\<open>sa \\<in> S\\<close> by blast\n  then have \"x \\<in> A \\<or> x \\<in> B\"\n    using cover by auto\n  then show False\n    using cs [unfolded connected_def]\n    by (metis A B IntI Sup_upper sa sb disjs x cover empty_iff subset_trans)\nqed\n\nlemma connected_Un: \"connected s \\<Longrightarrow> connected t \\<Longrightarrow> s \\<inter> t \\<noteq> {} \\<Longrightarrow> connected (s \\<union> t)\"\n  using connected_Union [of \"{s,t}\"] by auto\n\nlemma connected_diff_open_from_closed:\n  assumes st: \"s \\<subseteq> t\"\n    and tu: \"t \\<subseteq> u\"\n    and s: \"open s\"\n    and t: \"closed t\"\n    and u: \"connected u\"\n    and ts: \"connected (t - s)\"\n  shows \"connected(u - s)\"\nproof (rule connectedI)\n  fix A B\n  assume AB: \"open A\" \"open B\" \"A \\<inter> (u - s) \\<noteq> {}\" \"B \\<inter> (u - s) \\<noteq> {}\"\n    and disj: \"A \\<inter> B \\<inter> (u - s) = {}\"\n    and cover: \"u - s \\<subseteq> A \\<union> B\"\n  then consider \"A \\<inter> (t - s) = {}\" | \"B \\<inter> (t - s) = {}\"\n    using st ts tu connectedD [of \"t-s\" \"A\" \"B\"] by auto\n  then show False\n  proof cases\n    case 1\n    then have \"(A - t) \\<inter> (B \\<union> s) \\<inter> u = {}\"\n      using disj st by auto\n    moreover have \"u \\<subseteq> (A - t) \\<union> (B \\<union> s)\"\n      using 1 cover by auto\n    ultimately show False\n      using connectedD [of u \"A - t\" \"B \\<union> s\"] AB s t 1 u by auto\n  next\n    case 2\n    then have \"(A \\<union> s) \\<inter> (B - t) \\<inter> u = {}\"\n      using disj st by auto\n    moreover have \"u \\<subseteq> (A \\<union> s) \\<union> (B - t)\"\n      using 2 cover by auto\n    ultimately show False\n      using connectedD [of u \"A \\<union> s\" \"B - t\"] AB s t 2 u by auto\n  qed\nqed\n\nlemma connected_iff_const:\n  fixes S :: \"'a::topological_space set\"\n  shows \"connected S \\<longleftrightarrow> (\\<forall>P::'a \\<Rightarrow> bool. continuous_on S P \\<longrightarrow> (\\<exists>c. \\<forall>s\\<in>S. P s = c))\"\nproof safe\n  fix P :: \"'a \\<Rightarrow> bool\"\n  assume \"connected S\" \"continuous_on S P\"\n  then have \"\\<And>b. \\<exists>A. open A \\<and> A \\<inter> S = P -` {b} \\<inter> S\"\n    unfolding continuous_on_open_invariant by (simp add: open_discrete)\n  from this[of True] this[of False]\n  obtain t f where \"open t\" \"open f\" and *: \"f \\<inter> S = P -` {False} \\<inter> S\" \"t \\<inter> S = P -` {True} \\<inter> S\"\n    by meson\n  then have \"t \\<inter> S = {} \\<or> f \\<inter> S = {}\"\n    by (intro connectedD[OF \\<open>connected S\\<close>])  auto\n  then show \"\\<exists>c. \\<forall>s\\<in>S. P s = c\"\n  proof (rule disjE)\n    assume \"t \\<inter> S = {}\"\n    then show ?thesis\n      unfolding * by (intro exI[of _ False]) auto\n  next\n    assume \"f \\<inter> S = {}\"\n    then show ?thesis\n      unfolding * by (intro exI[of _ True]) auto\n  qed\nnext\n  assume P: \"\\<forall>P::'a \\<Rightarrow> bool. continuous_on S P \\<longrightarrow> (\\<exists>c. \\<forall>s\\<in>S. P s = c)\"\n  show \"connected S\"\n  proof (rule connectedI)\n    fix A B\n    assume *: \"open A\" \"open B\" \"A \\<inter> S \\<noteq> {}\" \"B \\<inter> S \\<noteq> {}\" \"A \\<inter> B \\<inter> S = {}\" \"S \\<subseteq> A \\<union> B\"\n    have \"continuous_on S (\\<lambda>x. x \\<in> A)\"\n      unfolding continuous_on_open_invariant\n    proof safe\n      fix C :: \"bool set\"\n      have \"C = UNIV \\<or> C = {True} \\<or> C = {False} \\<or> C = {}\"\n        using subset_UNIV[of C] unfolding UNIV_bool by auto\n      with * show \"\\<exists>T. open T \\<and> T \\<inter> S = (\\<lambda>x. x \\<in> A) -` C \\<inter> S\"\n        by (intro exI[of _ \"(if True \\<in> C then A else {}) \\<union> (if False \\<in> C then B else {})\"]) auto\n    qed\n    from P[rule_format, OF this] obtain c where \"\\<And>s. s \\<in> S \\<Longrightarrow> (s \\<in> A) = c\"\n      by blast\n    with * show False\n      by (cases c) auto\n  qed\nqed\n\nlemma connectedD_const: \"connected S \\<Longrightarrow> continuous_on S P \\<Longrightarrow> \\<exists>c. \\<forall>s\\<in>S. P s = c\"\n  for P :: \"'a::topological_space \\<Rightarrow> bool\"\n  by (auto simp: connected_iff_const)\n\nlemma connectedI_const:\n  \"(\\<And>P::'a::topological_space \\<Rightarrow> bool. continuous_on S P \\<Longrightarrow> \\<exists>c. \\<forall>s\\<in>S. P s = c) \\<Longrightarrow> connected S\"\n  by (auto simp: connected_iff_const)\n\nlemma connected_local_const:\n  assumes \"connected A\" \"a \\<in> A\" \"b \\<in> A\"\n    and *: \"\\<forall>a\\<in>A. eventually (\\<lambda>b. f a = f b) (at a within A)\"\n  shows \"f a = f b\"\nproof -\n  obtain S where S: \"\\<And>a. a \\<in> A \\<Longrightarrow> a \\<in> S a\" \"\\<And>a. a \\<in> A \\<Longrightarrow> open (S a)\"\n    \"\\<And>a x. a \\<in> A \\<Longrightarrow> x \\<in> S a \\<Longrightarrow> x \\<in> A \\<Longrightarrow> f a = f x\"\n    using * unfolding eventually_at_topological by metis\n  let ?P = \"\\<Union>b\\<in>{b\\<in>A. f a = f b}. S b\" and ?N = \"\\<Union>b\\<in>{b\\<in>A. f a \\<noteq> f b}. S b\"\n  have \"?P \\<inter> A = {} \\<or> ?N \\<inter> A = {}\"\n    using \\<open>connected A\\<close> S \\<open>a\\<in>A\\<close>\n    by (intro connectedD) (auto, metis)\n  then show \"f a = f b\"\n  proof\n    assume \"?N \\<inter> A = {}\"\n    then have \"\\<forall>x\\<in>A. f a = f x\"\n      using S(1) by auto\n    with \\<open>b\\<in>A\\<close> show ?thesis by auto\n  next\n    assume \"?P \\<inter> A = {}\" then show ?thesis\n      using \\<open>a \\<in> A\\<close> S(1)[of a] by auto\n  qed\nqed\n\nlemma (in linorder_topology) connectedD_interval:\n  assumes \"connected U\"\n    and xy: \"x \\<in> U\" \"y \\<in> U\"\n    and \"x \\<le> z\" \"z \\<le> y\"\n  shows \"z \\<in> U\"\nproof -\n  have eq: \"{..<z} \\<union> {z<..} = - {z}\"\n    by auto\n  have \"\\<not> connected U\" if \"z \\<notin> U\" \"x < z\" \"z < y\"\n    using xy that\n    apply (simp only: connected_def simp_thms)\n    apply (rule_tac exI[of _ \"{..< z}\"])\n    apply (rule_tac exI[of _ \"{z <..}\"])\n    apply (auto simp add: eq)\n    done\n  with assms show \"z \\<in> U\"\n    by (metis less_le)\nqed\n\nlemma connected_continuous_image:\n  assumes *: \"continuous_on s f\"\n    and \"connected s\"\n  shows \"connected (f ` s)\"\nproof (rule connectedI_const)\n  fix P :: \"'b \\<Rightarrow> bool\"\n  assume \"continuous_on (f ` s) P\"\n  then have \"continuous_on s (P \\<circ> f)\"\n    by (rule continuous_on_compose[OF *])\n  from connectedD_const[OF \\<open>connected s\\<close> this] show \"\\<exists>c. \\<forall>s\\<in>f ` s. P s = c\"\n    by auto\nqed\n\n\nsection \\<open>Linear Continuum Topologies\\<close>\n\nclass linear_continuum_topology = linorder_topology + linear_continuum\nbegin\n\nlemma Inf_notin_open:\n  assumes A: \"open A\"\n    and bnd: \"\\<forall>a\\<in>A. x < a\"\n  shows \"Inf A \\<notin> A\"\nproof\n  assume \"Inf A \\<in> A\"\n  then obtain b where \"b < Inf A\" \"{b <.. Inf A} \\<subseteq> A\"\n    using open_left[of A \"Inf A\" x] assms by auto\n  with dense[of b \"Inf A\"] obtain c where \"c < Inf A\" \"c \\<in> A\"\n    by (auto simp: subset_eq)\n  then show False\n    using cInf_lower[OF \\<open>c \\<in> A\\<close>] bnd\n    by (metis not_le less_imp_le bdd_belowI)\nqed\n\nlemma Sup_notin_open:\n  assumes A: \"open A\"\n    and bnd: \"\\<forall>a\\<in>A. a < x\"\n  shows \"Sup A \\<notin> A\"\nproof\n  assume \"Sup A \\<in> A\"\n  with assms obtain b where \"Sup A < b\" \"{Sup A ..< b} \\<subseteq> A\"\n    using open_right[of A \"Sup A\" x] by auto\n  with dense[of \"Sup A\" b] obtain c where \"Sup A < c\" \"c \\<in> A\"\n    by (auto simp: subset_eq)\n  then show False\n    using cSup_upper[OF \\<open>c \\<in> A\\<close>] bnd\n    by (metis less_imp_le not_le bdd_aboveI)\nqed\n\nend\n\ninstance linear_continuum_topology \\<subseteq> perfect_space\nproof\n  fix x :: 'a\n  obtain y where \"x < y \\<or> y < x\"\n    using ex_gt_or_lt [of x] ..\n  with Inf_notin_open[of \"{x}\" y] Sup_notin_open[of \"{x}\" y] show \"\\<not> open {x}\"\n    by auto\nqed\n\nlemma connectedI_interval:\n  fixes U :: \"'a :: linear_continuum_topology set\"\n  assumes *: \"\\<And>x y z. x \\<in> U \\<Longrightarrow> y \\<in> U \\<Longrightarrow> x \\<le> z \\<Longrightarrow> z \\<le> y \\<Longrightarrow> z \\<in> U\"\n  shows \"connected U\"\nproof (rule connectedI)\n  {\n    fix A B\n    assume \"open A\" \"open B\" \"A \\<inter> B \\<inter> U = {}\" \"U \\<subseteq> A \\<union> B\"\n    fix x y\n    assume \"x < y\" \"x \\<in> A\" \"y \\<in> B\" \"x \\<in> U\" \"y \\<in> U\"\n\n    let ?z = \"Inf (B \\<inter> {x <..})\"\n\n    have \"x \\<le> ?z\" \"?z \\<le> y\"\n      using \\<open>y \\<in> B\\<close> \\<open>x < y\\<close> by (auto intro: cInf_lower cInf_greatest)\n    with \\<open>x \\<in> U\\<close> \\<open>y \\<in> U\\<close> have \"?z \\<in> U\"\n      by (rule *)\n    moreover have \"?z \\<notin> B \\<inter> {x <..}\"\n      using \\<open>open B\\<close> by (intro Inf_notin_open) auto\n    ultimately have \"?z \\<in> A\"\n      using \\<open>x \\<le> ?z\\<close> \\<open>A \\<inter> B \\<inter> U = {}\\<close> \\<open>x \\<in> A\\<close> \\<open>U \\<subseteq> A \\<union> B\\<close> by auto\n    have \"\\<exists>b\\<in>B. b \\<in> A \\<and> b \\<in> U\" if \"?z < y\"\n    proof -\n      obtain a where \"?z < a\" \"{?z ..< a} \\<subseteq> A\"\n        using open_right[OF \\<open>open A\\<close> \\<open>?z \\<in> A\\<close> \\<open>?z < y\\<close>] by auto\n      moreover obtain b where \"b \\<in> B\" \"x < b\" \"b < min a y\"\n        using cInf_less_iff[of \"B \\<inter> {x <..}\" \"min a y\"] \\<open>?z < a\\<close> \\<open>?z < y\\<close> \\<open>x < y\\<close> \\<open>y \\<in> B\\<close>\n        by auto\n      moreover have \"?z \\<le> b\"\n        using \\<open>b \\<in> B\\<close> \\<open>x < b\\<close>\n        by (intro cInf_lower) auto\n      moreover have \"b \\<in> U\"\n        using \\<open>x \\<le> ?z\\<close> \\<open>?z \\<le> b\\<close> \\<open>b < min a y\\<close>\n        by (intro *[OF \\<open>x \\<in> U\\<close> \\<open>y \\<in> U\\<close>]) (auto simp: less_imp_le)\n      ultimately show ?thesis\n        by (intro bexI[of _ b]) auto\n    qed\n    then have False\n      using \\<open>?z \\<le> y\\<close> \\<open>?z \\<in> A\\<close> \\<open>y \\<in> B\\<close> \\<open>y \\<in> U\\<close> \\<open>A \\<inter> B \\<inter> U = {}\\<close>\n      unfolding le_less by blast\n  }\n  note not_disjoint = this\n\n  fix A B assume AB: \"open A\" \"open B\" \"U \\<subseteq> A \\<union> B\" \"A \\<inter> B \\<inter> U = {}\"\n  moreover assume \"A \\<inter> U \\<noteq> {}\" then obtain x where x: \"x \\<in> U\" \"x \\<in> A\" by auto\n  moreover assume \"B \\<inter> U \\<noteq> {}\" then obtain y where y: \"y \\<in> U\" \"y \\<in> B\" by auto\n  moreover note not_disjoint[of B A y x] not_disjoint[of A B x y]\n  ultimately show False\n    by (cases x y rule: linorder_cases) auto\nqed\n\nlemma connected_iff_interval: \"connected U \\<longleftrightarrow> (\\<forall>x\\<in>U. \\<forall>y\\<in>U. \\<forall>z. x \\<le> z \\<longrightarrow> z \\<le> y \\<longrightarrow> z \\<in> U)\"\n  for U :: \"'a::linear_continuum_topology set\"\n  by (auto intro: connectedI_interval dest: connectedD_interval)\n\nlemma connected_UNIV[simp]: \"connected (UNIV::'a::linear_continuum_topology set)\"\n  by (simp add: connected_iff_interval)\n\nlemma connected_Ioi[simp]: \"connected {a<..}\"\n  for a :: \"'a::linear_continuum_topology\"\n  by (auto simp: connected_iff_interval)\n\nlemma connected_Ici[simp]: \"connected {a..}\"\n  for a :: \"'a::linear_continuum_topology\"\n  by (auto simp: connected_iff_interval)\n\nlemma connected_Iio[simp]: \"connected {..<a}\"\n  for a :: \"'a::linear_continuum_topology\"\n  by (auto simp: connected_iff_interval)\n\nlemma connected_Iic[simp]: \"connected {..a}\"\n  for a :: \"'a::linear_continuum_topology\"\n  by (auto simp: connected_iff_interval)\n\nlemma connected_Ioo[simp]: \"connected {a<..<b}\"\n  for a b :: \"'a::linear_continuum_topology\"\n  unfolding connected_iff_interval by auto\n\nlemma connected_Ioc[simp]: \"connected {a<..b}\"\n  for a b :: \"'a::linear_continuum_topology\"\n  by (auto simp: connected_iff_interval)\n\nlemma connected_Ico[simp]: \"connected {a..<b}\"\n  for a b :: \"'a::linear_continuum_topology\"\n  by (auto simp: connected_iff_interval)\n\nlemma connected_Icc[simp]: \"connected {a..b}\"\n  for a b :: \"'a::linear_continuum_topology\"\n  by (auto simp: connected_iff_interval)\n\nlemma connected_contains_Ioo:\n  fixes A :: \"'a :: linorder_topology set\"\n  assumes \"connected A\" \"a \\<in> A\" \"b \\<in> A\" shows \"{a <..< b} \\<subseteq> A\"\n  using connectedD_interval[OF assms] by (simp add: subset_eq Ball_def less_imp_le)\n\nlemma connected_contains_Icc:\n  fixes A :: \"'a::linorder_topology set\"\n  assumes \"connected A\" \"a \\<in> A\" \"b \\<in> A\"\n  shows \"{a..b} \\<subseteq> A\"\nproof\n  fix x assume \"x \\<in> {a..b}\"\n  then have \"x = a \\<or> x = b \\<or> x \\<in> {a<..<b}\"\n    by auto\n  then show \"x \\<in> A\"\n    using assms connected_contains_Ioo[of A a b] by auto\nqed\n\n\nsubsection \\<open>Intermediate Value Theorem\\<close>\n\nlemma IVT':\n  fixes f :: \"'a::linear_continuum_topology \\<Rightarrow> 'b::linorder_topology\"\n  assumes y: \"f a \\<le> y\" \"y \\<le> f b\" \"a \\<le> b\"\n    and *: \"continuous_on {a .. b} f\"\n  shows \"\\<exists>x. a \\<le> x \\<and> x \\<le> b \\<and> f x = y\"\nproof -\n  have \"connected {a..b}\"\n    unfolding connected_iff_interval by auto\n  from connected_continuous_image[OF * this, THEN connectedD_interval, of \"f a\" \"f b\" y] y\n  show ?thesis\n    by (auto simp add: atLeastAtMost_def atLeast_def atMost_def)\nqed\n\nlemma IVT2':\n  fixes f :: \"'a :: linear_continuum_topology \\<Rightarrow> 'b :: linorder_topology\"\n  assumes y: \"f b \\<le> y\" \"y \\<le> f a\" \"a \\<le> b\"\n    and *: \"continuous_on {a .. b} f\"\n  shows \"\\<exists>x. a \\<le> x \\<and> x \\<le> b \\<and> f x = y\"\nproof -\n  have \"connected {a..b}\"\n    unfolding connected_iff_interval by auto\n  from connected_continuous_image[OF * this, THEN connectedD_interval, of \"f b\" \"f a\" y] y\n  show ?thesis\n    by (auto simp add: atLeastAtMost_def atLeast_def atMost_def)\nqed\n\nlemma IVT:\n  fixes f :: \"'a::linear_continuum_topology \\<Rightarrow> 'b::linorder_topology\"\n  shows \"f a \\<le> y \\<Longrightarrow> y \\<le> f b \\<Longrightarrow> a \\<le> b \\<Longrightarrow> (\\<forall>x. a \\<le> x \\<and> x \\<le> b \\<longrightarrow> isCont f x) \\<Longrightarrow>\n    \\<exists>x. a \\<le> x \\<and> x \\<le> b \\<and> f x = y\"\n  by (rule IVT') (auto intro: continuous_at_imp_continuous_on)\n\nlemma IVT2:\n  fixes f :: \"'a::linear_continuum_topology \\<Rightarrow> 'b::linorder_topology\"\n  shows \"f b \\<le> y \\<Longrightarrow> y \\<le> f a \\<Longrightarrow> a \\<le> b \\<Longrightarrow> (\\<forall>x. a \\<le> x \\<and> x \\<le> b \\<longrightarrow> isCont f x) \\<Longrightarrow>\n    \\<exists>x. a \\<le> x \\<and> x \\<le> b \\<and> f x = y\"\n  by (rule IVT2') (auto intro: continuous_at_imp_continuous_on)\n\nlemma continuous_inj_imp_mono:\n  fixes f :: \"'a::linear_continuum_topology \\<Rightarrow> 'b::linorder_topology\"\n  assumes x: \"a < x\" \"x < b\"\n    and cont: \"continuous_on {a..b} f\"\n    and inj: \"inj_on f {a..b}\"\n  shows \"(f a < f x \\<and> f x < f b) \\<or> (f b < f x \\<and> f x < f a)\"\nproof -\n  note I = inj_on_eq_iff[OF inj]\n  {\n    assume \"f x < f a\" \"f x < f b\"\n    then obtain s t where \"x \\<le> s\" \"s \\<le> b\" \"a \\<le> t\" \"t \\<le> x\" \"f s = f t\" \"f x < f s\"\n      using IVT'[of f x \"min (f a) (f b)\" b] IVT2'[of f x \"min (f a) (f b)\" a] x\n      by (auto simp: continuous_on_subset[OF cont] less_imp_le)\n    with x I have False by auto\n  }\n  moreover\n  {\n    assume \"f a < f x\" \"f b < f x\"\n    then obtain s t where \"x \\<le> s\" \"s \\<le> b\" \"a \\<le> t\" \"t \\<le> x\" \"f s = f t\" \"f s < f x\"\n      using IVT'[of f a \"max (f a) (f b)\" x] IVT2'[of f b \"max (f a) (f b)\" x] x\n      by (auto simp: continuous_on_subset[OF cont] less_imp_le)\n    with x I have False by auto\n  }\n  ultimately show ?thesis\n    using I[of a x] I[of x b] x less_trans[OF x]\n    by (auto simp add: le_less less_imp_neq neq_iff)\nqed\n\nlemma continuous_at_Sup_mono:\n  fixes f :: \"'a::{linorder_topology,conditionally_complete_linorder} \\<Rightarrow>\n    'b::{linorder_topology,conditionally_complete_linorder}\"\n  assumes \"mono f\"\n    and cont: \"continuous (at_left (Sup S)) f\"\n    and S: \"S \\<noteq> {}\" \"bdd_above S\"\n  shows \"f (Sup S) = (SUP s:S. f s)\"\nproof (rule antisym)\n  have f: \"(f \\<longlongrightarrow> f (Sup S)) (at_left (Sup S))\"\n    using cont unfolding continuous_within .\n  show \"f (Sup S) \\<le> (SUP s:S. f s)\"\n  proof cases\n    assume \"Sup S \\<in> S\"\n    then show ?thesis\n      by (rule cSUP_upper) (auto intro: bdd_above_image_mono S \\<open>mono f\\<close>)\n  next\n    assume \"Sup S \\<notin> S\"\n    from \\<open>S \\<noteq> {}\\<close> obtain s where \"s \\<in> S\"\n      by auto\n    with \\<open>Sup S \\<notin> S\\<close> S have \"s < Sup S\"\n      unfolding less_le by (blast intro: cSup_upper)\n    show ?thesis\n    proof (rule ccontr)\n      assume \"\\<not> ?thesis\"\n      with order_tendstoD(1)[OF f, of \"SUP s:S. f s\"] obtain b where \"b < Sup S\"\n        and *: \"\\<And>y. b < y \\<Longrightarrow> y < Sup S \\<Longrightarrow> (SUP s:S. f s) < f y\"\n        by (auto simp: not_le eventually_at_left[OF \\<open>s < Sup S\\<close>])\n      with \\<open>S \\<noteq> {}\\<close> obtain c where \"c \\<in> S\" \"b < c\"\n        using less_cSupD[of S b] by auto\n      with \\<open>Sup S \\<notin> S\\<close> S have \"c < Sup S\"\n        unfolding less_le by (blast intro: cSup_upper)\n      from *[OF \\<open>b < c\\<close> \\<open>c < Sup S\\<close>] cSUP_upper[OF \\<open>c \\<in> S\\<close> bdd_above_image_mono[of f]]\n      show False\n        by (auto simp: assms)\n    qed\n  qed\nqed (intro cSUP_least \\<open>mono f\\<close>[THEN monoD] cSup_upper S)\n\nlemma continuous_at_Sup_antimono:\n  fixes f :: \"'a::{linorder_topology,conditionally_complete_linorder} \\<Rightarrow>\n    'b::{linorder_topology,conditionally_complete_linorder}\"\n  assumes \"antimono f\"\n    and cont: \"continuous (at_left (Sup S)) f\"\n    and S: \"S \\<noteq> {}\" \"bdd_above S\"\n  shows \"f (Sup S) = (INF s:S. f s)\"\nproof (rule antisym)\n  have f: \"(f \\<longlongrightarrow> f (Sup S)) (at_left (Sup S))\"\n    using cont unfolding continuous_within .\n  show \"(INF s:S. f s) \\<le> f (Sup S)\"\n  proof cases\n    assume \"Sup S \\<in> S\"\n    then show ?thesis\n      by (intro cINF_lower) (auto intro: bdd_below_image_antimono S \\<open>antimono f\\<close>)\n  next\n    assume \"Sup S \\<notin> S\"\n    from \\<open>S \\<noteq> {}\\<close> obtain s where \"s \\<in> S\"\n      by auto\n    with \\<open>Sup S \\<notin> S\\<close> S have \"s < Sup S\"\n      unfolding less_le by (blast intro: cSup_upper)\n    show ?thesis\n    proof (rule ccontr)\n      assume \"\\<not> ?thesis\"\n      with order_tendstoD(2)[OF f, of \"INF s:S. f s\"] obtain b where \"b < Sup S\"\n        and *: \"\\<And>y. b < y \\<Longrightarrow> y < Sup S \\<Longrightarrow> f y < (INF s:S. f s)\"\n        by (auto simp: not_le eventually_at_left[OF \\<open>s < Sup S\\<close>])\n      with \\<open>S \\<noteq> {}\\<close> obtain c where \"c \\<in> S\" \"b < c\"\n        using less_cSupD[of S b] by auto\n      with \\<open>Sup S \\<notin> S\\<close> S have \"c < Sup S\"\n        unfolding less_le by (blast intro: cSup_upper)\n      from *[OF \\<open>b < c\\<close> \\<open>c < Sup S\\<close>] cINF_lower[OF bdd_below_image_antimono, of f S c] \\<open>c \\<in> S\\<close>\n      show False\n        by (auto simp: assms)\n    qed\n  qed\nqed (intro cINF_greatest \\<open>antimono f\\<close>[THEN antimonoD] cSup_upper S)\n\nlemma continuous_at_Inf_mono:\n  fixes f :: \"'a::{linorder_topology,conditionally_complete_linorder} \\<Rightarrow>\n    'b::{linorder_topology,conditionally_complete_linorder}\"\n  assumes \"mono f\"\n    and cont: \"continuous (at_right (Inf S)) f\"\n    and S: \"S \\<noteq> {}\" \"bdd_below S\"\n  shows \"f (Inf S) = (INF s:S. f s)\"\nproof (rule antisym)\n  have f: \"(f \\<longlongrightarrow> f (Inf S)) (at_right (Inf S))\"\n    using cont unfolding continuous_within .\n  show \"(INF s:S. f s) \\<le> f (Inf S)\"\n  proof cases\n    assume \"Inf S \\<in> S\"\n    then show ?thesis\n      by (rule cINF_lower[rotated]) (auto intro: bdd_below_image_mono S \\<open>mono f\\<close>)\n  next\n    assume \"Inf S \\<notin> S\"\n    from \\<open>S \\<noteq> {}\\<close> obtain s where \"s \\<in> S\"\n      by auto\n    with \\<open>Inf S \\<notin> S\\<close> S have \"Inf S < s\"\n      unfolding less_le by (blast intro: cInf_lower)\n    show ?thesis\n    proof (rule ccontr)\n      assume \"\\<not> ?thesis\"\n      with order_tendstoD(2)[OF f, of \"INF s:S. f s\"] obtain b where \"Inf S < b\"\n        and *: \"\\<And>y. Inf S < y \\<Longrightarrow> y < b \\<Longrightarrow> f y < (INF s:S. f s)\"\n        by (auto simp: not_le eventually_at_right[OF \\<open>Inf S < s\\<close>])\n      with \\<open>S \\<noteq> {}\\<close> obtain c where \"c \\<in> S\" \"c < b\"\n        using cInf_lessD[of S b] by auto\n      with \\<open>Inf S \\<notin> S\\<close> S have \"Inf S < c\"\n        unfolding less_le by (blast intro: cInf_lower)\n      from *[OF \\<open>Inf S < c\\<close> \\<open>c < b\\<close>] cINF_lower[OF bdd_below_image_mono[of f] \\<open>c \\<in> S\\<close>]\n      show False\n        by (auto simp: assms)\n    qed\n  qed\nqed (intro cINF_greatest \\<open>mono f\\<close>[THEN monoD] cInf_lower \\<open>bdd_below S\\<close> \\<open>S \\<noteq> {}\\<close>)\n\nlemma continuous_at_Inf_antimono:\n  fixes f :: \"'a::{linorder_topology,conditionally_complete_linorder} \\<Rightarrow>\n    'b::{linorder_topology,conditionally_complete_linorder}\"\n  assumes \"antimono f\"\n    and cont: \"continuous (at_right (Inf S)) f\"\n    and S: \"S \\<noteq> {}\" \"bdd_below S\"\n  shows \"f (Inf S) = (SUP s:S. f s)\"\nproof (rule antisym)\n  have f: \"(f \\<longlongrightarrow> f (Inf S)) (at_right (Inf S))\"\n    using cont unfolding continuous_within .\n  show \"f (Inf S) \\<le> (SUP s:S. f s)\"\n  proof cases\n    assume \"Inf S \\<in> S\"\n    then show ?thesis\n      by (rule cSUP_upper) (auto intro: bdd_above_image_antimono S \\<open>antimono f\\<close>)\n  next\n    assume \"Inf S \\<notin> S\"\n    from \\<open>S \\<noteq> {}\\<close> obtain s where \"s \\<in> S\"\n      by auto\n    with \\<open>Inf S \\<notin> S\\<close> S have \"Inf S < s\"\n      unfolding less_le by (blast intro: cInf_lower)\n    show ?thesis\n    proof (rule ccontr)\n      assume \"\\<not> ?thesis\"\n      with order_tendstoD(1)[OF f, of \"SUP s:S. f s\"] obtain b where \"Inf S < b\"\n        and *: \"\\<And>y. Inf S < y \\<Longrightarrow> y < b \\<Longrightarrow> (SUP s:S. f s) < f y\"\n        by (auto simp: not_le eventually_at_right[OF \\<open>Inf S < s\\<close>])\n      with \\<open>S \\<noteq> {}\\<close> obtain c where \"c \\<in> S\" \"c < b\"\n        using cInf_lessD[of S b] by auto\n      with \\<open>Inf S \\<notin> S\\<close> S have \"Inf S < c\"\n        unfolding less_le by (blast intro: cInf_lower)\n      from *[OF \\<open>Inf S < c\\<close> \\<open>c < b\\<close>] cSUP_upper[OF \\<open>c \\<in> S\\<close> bdd_above_image_antimono[of f]]\n      show False\n        by (auto simp: assms)\n    qed\n  qed\nqed (intro cSUP_least \\<open>antimono f\\<close>[THEN antimonoD] cInf_lower S)\n\n\nsubsection \\<open>Uniform spaces\\<close>\n\nclass uniformity =\n  fixes uniformity :: \"('a \\<times> 'a) filter\"\nbegin\n\nabbreviation uniformity_on :: \"'a set \\<Rightarrow> ('a \\<times> 'a) filter\"\n  where \"uniformity_on s \\<equiv> inf uniformity (principal (s\\<times>s))\"\n\nend\n\nlemma uniformity_Abort:\n  \"uniformity =\n    Filter.abstract_filter (\\<lambda>u. Code.abort (STR ''uniformity is not executable'') (\\<lambda>u. uniformity))\"\n  by simp\n\nclass open_uniformity = \"open\" + uniformity +\n  assumes open_uniformity:\n    \"\\<And>U. open U \\<longleftrightarrow> (\\<forall>x\\<in>U. eventually (\\<lambda>(x', y). x' = x \\<longrightarrow> y \\<in> U) uniformity)\"\n\nclass uniform_space = open_uniformity +\n  assumes uniformity_refl: \"eventually E uniformity \\<Longrightarrow> E (x, x)\"\n    and uniformity_sym: \"eventually E uniformity \\<Longrightarrow> eventually (\\<lambda>(x, y). E (y, x)) uniformity\"\n    and uniformity_trans:\n      \"eventually E uniformity \\<Longrightarrow>\n        \\<exists>D. eventually D uniformity \\<and> (\\<forall>x y z. D (x, y) \\<longrightarrow> D (y, z) \\<longrightarrow> E (x, z))\"\nbegin\n\nsubclass topological_space\n  by standard (force elim: eventually_mono eventually_elim2 simp: split_beta' open_uniformity)+\n\nlemma uniformity_bot: \"uniformity \\<noteq> bot\"\n  using uniformity_refl by auto\n\nlemma uniformity_trans':\n  \"eventually E uniformity \\<Longrightarrow>\n    eventually (\\<lambda>((x, y), (y', z)). y = y' \\<longrightarrow> E (x, z)) (uniformity \\<times>\\<^sub>F uniformity)\"\n  by (drule uniformity_trans) (auto simp add: eventually_prod_same)\n\nlemma uniformity_transE:\n  assumes \"eventually E uniformity\"\n  obtains D where \"eventually D uniformity\" \"\\<And>x y z. D (x, y) \\<Longrightarrow> D (y, z) \\<Longrightarrow> E (x, z)\"\n  using uniformity_trans [OF assms] by auto\n\nlemma eventually_nhds_uniformity:\n  \"eventually P (nhds x) \\<longleftrightarrow> eventually (\\<lambda>(x', y). x' = x \\<longrightarrow> P y) uniformity\"\n  (is \"_ \\<longleftrightarrow> ?N P x\")\n  unfolding eventually_nhds\nproof safe\n  assume *: \"?N P x\"\n  have \"?N (?N P) x\" if \"?N P x\" for x\n  proof -\n    from that obtain D where ev: \"eventually D uniformity\"\n      and D: \"D (a, b) \\<Longrightarrow> D (b, c) \\<Longrightarrow> case (a, c) of (x', y) \\<Rightarrow> x' = x \\<longrightarrow> P y\" for a b c\n      by (rule uniformity_transE) simp\n    from ev show ?thesis\n      by eventually_elim (insert ev D, force elim: eventually_mono split: prod.split)\n  qed\n  then have \"open {x. ?N P x}\"\n    by (simp add: open_uniformity)\n  then show \"\\<exists>S. open S \\<and> x \\<in> S \\<and> (\\<forall>x\\<in>S. P x)\"\n    by (intro exI[of _ \"{x. ?N P x}\"]) (auto dest: uniformity_refl simp: *)\nqed (force simp add: open_uniformity elim: eventually_mono)\n\n\nsubsubsection \\<open>Totally bounded sets\\<close>\n\ndefinition totally_bounded :: \"'a set \\<Rightarrow> bool\"\n  where \"totally_bounded S \\<longleftrightarrow>\n    (\\<forall>E. eventually E uniformity \\<longrightarrow> (\\<exists>X. finite X \\<and> (\\<forall>s\\<in>S. \\<exists>x\\<in>X. E (x, s))))\"\n\nlemma totally_bounded_empty[iff]: \"totally_bounded {}\"\n  by (auto simp add: totally_bounded_def)\n\nlemma totally_bounded_subset: \"totally_bounded S \\<Longrightarrow> T \\<subseteq> S \\<Longrightarrow> totally_bounded T\"\n  by (fastforce simp add: totally_bounded_def)\n\nlemma totally_bounded_Union[intro]:\n  assumes M: \"finite M\" \"\\<And>S. S \\<in> M \\<Longrightarrow> totally_bounded S\"\n  shows \"totally_bounded (\\<Union>M)\"\n  unfolding totally_bounded_def\nproof safe\n  fix E\n  assume \"eventually E uniformity\"\n  with M obtain X where \"\\<forall>S\\<in>M. finite (X S) \\<and> (\\<forall>s\\<in>S. \\<exists>x\\<in>X S. E (x, s))\"\n    by (metis totally_bounded_def)\n  with \\<open>finite M\\<close> show \"\\<exists>X. finite X \\<and> (\\<forall>s\\<in>\\<Union>M. \\<exists>x\\<in>X. E (x, s))\"\n    by (intro exI[of _ \"\\<Union>S\\<in>M. X S\"]) force\nqed\n\n\nsubsubsection \\<open>Cauchy filter\\<close>\n\ndefinition cauchy_filter :: \"'a filter \\<Rightarrow> bool\"\n  where \"cauchy_filter F \\<longleftrightarrow> F \\<times>\\<^sub>F F \\<le> uniformity\"\n\ndefinition Cauchy :: \"(nat \\<Rightarrow> 'a) \\<Rightarrow> bool\"\n  where Cauchy_uniform: \"Cauchy X = cauchy_filter (filtermap X sequentially)\"\n\nlemma Cauchy_uniform_iff:\n  \"Cauchy X \\<longleftrightarrow> (\\<forall>P. eventually P uniformity \\<longrightarrow> (\\<exists>N. \\<forall>n\\<ge>N. \\<forall>m\\<ge>N. P (X n, X m)))\"\n  unfolding Cauchy_uniform cauchy_filter_def le_filter_def eventually_prod_same\n    eventually_filtermap eventually_sequentially\nproof safe\n  let ?U = \"\\<lambda>P. eventually P uniformity\"\n  {\n    fix P\n    assume \"?U P\" \"\\<forall>P. ?U P \\<longrightarrow> (\\<exists>Q. (\\<exists>N. \\<forall>n\\<ge>N. Q (X n)) \\<and> (\\<forall>x y. Q x \\<longrightarrow> Q y \\<longrightarrow> P (x, y)))\"\n    then obtain Q N where \"\\<And>n. n \\<ge> N \\<Longrightarrow> Q (X n)\" \"\\<And>x y. Q x \\<Longrightarrow> Q y \\<Longrightarrow> P (x, y)\"\n      by metis\n    then show \"\\<exists>N. \\<forall>n\\<ge>N. \\<forall>m\\<ge>N. P (X n, X m)\"\n      by blast\n  next\n    fix P\n    assume \"?U P\" and P: \"\\<forall>P. ?U P \\<longrightarrow> (\\<exists>N. \\<forall>n\\<ge>N. \\<forall>m\\<ge>N. P (X n, X m))\"\n    then obtain Q where \"?U Q\" and Q: \"\\<And>x y z. Q (x, y) \\<Longrightarrow> Q (y, z) \\<Longrightarrow> P (x, z)\"\n      by (auto elim: uniformity_transE)\n    then have \"?U (\\<lambda>x. Q x \\<and> (\\<lambda>(x, y). Q (y, x)) x)\"\n      unfolding eventually_conj_iff by (simp add: uniformity_sym)\n    from P[rule_format, OF this]\n    obtain N where N: \"\\<And>n m. n \\<ge> N \\<Longrightarrow> m \\<ge> N \\<Longrightarrow> Q (X n, X m) \\<and> Q (X m, X n)\"\n      by auto\n    show \"\\<exists>Q. (\\<exists>N. \\<forall>n\\<ge>N. Q (X n)) \\<and> (\\<forall>x y. Q x \\<longrightarrow> Q y \\<longrightarrow> P (x, y))\"\n    proof (safe intro!: exI[of _ \"\\<lambda>x. \\<forall>n\\<ge>N. Q (x, X n) \\<and> Q (X n, x)\"] exI[of _ N] N)\n      fix x y\n      assume \"\\<forall>n\\<ge>N. Q (x, X n) \\<and> Q (X n, x)\" \"\\<forall>n\\<ge>N. Q (y, X n) \\<and> Q (X n, y)\"\n      then have \"Q (x, X N)\" \"Q (X N, y)\" by auto\n      then show \"P (x, y)\"\n        by (rule Q)\n    qed\n  }\nqed\n\nlemma nhds_imp_cauchy_filter:\n  assumes *: \"F \\<le> nhds x\"\n  shows \"cauchy_filter F\"\nproof -\n  have \"F \\<times>\\<^sub>F F \\<le> nhds x \\<times>\\<^sub>F nhds x\"\n    by (intro prod_filter_mono *)\n  also have \"\\<dots> \\<le> uniformity\"\n    unfolding le_filter_def eventually_nhds_uniformity eventually_prod_same\n  proof safe\n    fix P\n    assume \"eventually P uniformity\"\n    then obtain Ql where ev: \"eventually Ql uniformity\"\n      and \"Ql (x, y) \\<Longrightarrow> Ql (y, z) \\<Longrightarrow> P (x, z)\" for x y z\n      by (rule uniformity_transE) simp\n    with ev[THEN uniformity_sym]\n    show \"\\<exists>Q. eventually (\\<lambda>(x', y). x' = x \\<longrightarrow> Q y) uniformity \\<and>\n        (\\<forall>x y. Q x \\<longrightarrow> Q y \\<longrightarrow> P (x, y))\"\n      by (rule_tac exI[of _ \"\\<lambda>y. Ql (y, x) \\<and> Ql (x, y)\"]) (fastforce elim: eventually_elim2)\n  qed\n  finally show ?thesis\n    by (simp add: cauchy_filter_def)\nqed\n\nlemma LIMSEQ_imp_Cauchy: \"X \\<longlonglongrightarrow> x \\<Longrightarrow> Cauchy X\"\n  unfolding Cauchy_uniform filterlim_def by (intro nhds_imp_cauchy_filter)\n\nlemma Cauchy_subseq_Cauchy:\n  assumes \"Cauchy X\" \"subseq f\"\n  shows \"Cauchy (X \\<circ> f)\"\n  unfolding Cauchy_uniform comp_def filtermap_filtermap[symmetric] cauchy_filter_def\n  by (rule order_trans[OF _ \\<open>Cauchy X\\<close>[unfolded Cauchy_uniform cauchy_filter_def]])\n     (intro prod_filter_mono filtermap_mono filterlim_subseq[OF \\<open>subseq f\\<close>, unfolded filterlim_def])\n\nlemma convergent_Cauchy: \"convergent X \\<Longrightarrow> Cauchy X\"\n  unfolding convergent_def by (erule exE, erule LIMSEQ_imp_Cauchy)\n\ndefinition complete :: \"'a set \\<Rightarrow> bool\"\n  where complete_uniform: \"complete S \\<longleftrightarrow>\n    (\\<forall>F \\<le> principal S. F \\<noteq> bot \\<longrightarrow> cauchy_filter F \\<longrightarrow> (\\<exists>x\\<in>S. F \\<le> nhds x))\"\n\nend\n\n\nsubsubsection \\<open>Uniformly continuous functions\\<close>\n\ndefinition uniformly_continuous_on :: \"'a set \\<Rightarrow> ('a::uniform_space \\<Rightarrow> 'b::uniform_space) \\<Rightarrow> bool\"\n  where uniformly_continuous_on_uniformity: \"uniformly_continuous_on s f \\<longleftrightarrow>\n    (LIM (x, y) (uniformity_on s). (f x, f y) :> uniformity)\"\n\nlemma uniformly_continuous_onD:\n  \"uniformly_continuous_on s f \\<Longrightarrow> eventually E uniformity \\<Longrightarrow>\n    eventually (\\<lambda>(x, y). x \\<in> s \\<longrightarrow> y \\<in> s \\<longrightarrow> E (f x, f y)) uniformity\"\n  by (simp add: uniformly_continuous_on_uniformity filterlim_iff\n      eventually_inf_principal split_beta' mem_Times_iff imp_conjL)\n\nlemma uniformly_continuous_on_const[continuous_intros]: \"uniformly_continuous_on s (\\<lambda>x. c)\"\n  by (auto simp: uniformly_continuous_on_uniformity filterlim_iff uniformity_refl)\n\nlemma uniformly_continuous_on_id[continuous_intros]: \"uniformly_continuous_on s (\\<lambda>x. x)\"\n  by (auto simp: uniformly_continuous_on_uniformity filterlim_def)\n\nlemma uniformly_continuous_on_compose[continuous_intros]:\n  \"uniformly_continuous_on s g \\<Longrightarrow> uniformly_continuous_on (g`s) f \\<Longrightarrow>\n    uniformly_continuous_on s (\\<lambda>x. f (g x))\"\n  using filterlim_compose[of \"\\<lambda>(x, y). (f x, f y)\" uniformity\n      \"uniformity_on (g`s)\"  \"\\<lambda>(x, y). (g x, g y)\" \"uniformity_on s\"]\n  by (simp add: split_beta' uniformly_continuous_on_uniformity\n      filterlim_inf filterlim_principal eventually_inf_principal mem_Times_iff)\n\nlemma uniformly_continuous_imp_continuous:\n  assumes f: \"uniformly_continuous_on s f\"\n  shows \"continuous_on s f\"\n  by (auto simp: filterlim_iff eventually_at_filter eventually_nhds_uniformity continuous_on_def\n           elim: eventually_mono dest!: uniformly_continuous_onD[OF f])\n\n\nsection \\<open>Product Topology\\<close>\n\nsubsection \\<open>Product is a topological space\\<close>\n\ninstantiation prod :: (topological_space, topological_space) topological_space\nbegin\n\ndefinition open_prod_def[code del]:\n  \"open (S :: ('a \\<times> 'b) set) \\<longleftrightarrow>\n    (\\<forall>x\\<in>S. \\<exists>A B. open A \\<and> open B \\<and> x \\<in> A \\<times> B \\<and> A \\<times> B \\<subseteq> S)\"\n\nlemma open_prod_elim:\n  assumes \"open S\" and \"x \\<in> S\"\n  obtains A B where \"open A\" and \"open B\" and \"x \\<in> A \\<times> B\" and \"A \\<times> B \\<subseteq> S\"\n  using assms unfolding open_prod_def by fast\n\nlemma open_prod_intro:\n  assumes \"\\<And>x. x \\<in> S \\<Longrightarrow> \\<exists>A B. open A \\<and> open B \\<and> x \\<in> A \\<times> B \\<and> A \\<times> B \\<subseteq> S\"\n  shows \"open S\"\n  using assms unfolding open_prod_def by fast\n\ninstance\nproof\n  show \"open (UNIV :: ('a \\<times> 'b) set)\"\n    unfolding open_prod_def by auto\nnext\n  fix S T :: \"('a \\<times> 'b) set\"\n  assume \"open S\" \"open T\"\n  show \"open (S \\<inter> T)\"\n  proof (rule open_prod_intro)\n    fix x\n    assume x: \"x \\<in> S \\<inter> T\"\n    from x have \"x \\<in> S\" by simp\n    obtain Sa Sb where A: \"open Sa\" \"open Sb\" \"x \\<in> Sa \\<times> Sb\" \"Sa \\<times> Sb \\<subseteq> S\"\n      using \\<open>open S\\<close> and \\<open>x \\<in> S\\<close> by (rule open_prod_elim)\n    from x have \"x \\<in> T\" by simp\n    obtain Ta Tb where B: \"open Ta\" \"open Tb\" \"x \\<in> Ta \\<times> Tb\" \"Ta \\<times> Tb \\<subseteq> T\"\n      using \\<open>open T\\<close> and \\<open>x \\<in> T\\<close> by (rule open_prod_elim)\n    let ?A = \"Sa \\<inter> Ta\" and ?B = \"Sb \\<inter> Tb\"\n    have \"open ?A \\<and> open ?B \\<and> x \\<in> ?A \\<times> ?B \\<and> ?A \\<times> ?B \\<subseteq> S \\<inter> T\"\n      using A B by (auto simp add: open_Int)\n    then show \"\\<exists>A B. open A \\<and> open B \\<and> x \\<in> A \\<times> B \\<and> A \\<times> B \\<subseteq> S \\<inter> T\"\n      by fast\n  qed\nnext\n  fix K :: \"('a \\<times> 'b) set set\"\n  assume \"\\<forall>S\\<in>K. open S\"\n  then show \"open (\\<Union>K)\"\n    unfolding open_prod_def by fast\nqed\n\nend\n\ndeclare [[code abort: \"open :: ('a::topological_space \\<times> 'b::topological_space) set \\<Rightarrow> bool\"]]\n\nlemma open_Times: \"open S \\<Longrightarrow> open T \\<Longrightarrow> open (S \\<times> T)\"\n  unfolding open_prod_def by auto\n\nlemma fst_vimage_eq_Times: \"fst -` S = S \\<times> UNIV\"\n  by auto\n\nlemma snd_vimage_eq_Times: \"snd -` S = UNIV \\<times> S\"\n  by auto\n\nlemma open_vimage_fst: \"open S \\<Longrightarrow> open (fst -` S)\"\n  by (simp add: fst_vimage_eq_Times open_Times)\n\nlemma open_vimage_snd: \"open S \\<Longrightarrow> open (snd -` S)\"\n  by (simp add: snd_vimage_eq_Times open_Times)\n\nlemma closed_vimage_fst: \"closed S \\<Longrightarrow> closed (fst -` S)\"\n  unfolding closed_open vimage_Compl [symmetric]\n  by (rule open_vimage_fst)\n\nlemma closed_vimage_snd: \"closed S \\<Longrightarrow> closed (snd -` S)\"\n  unfolding closed_open vimage_Compl [symmetric]\n  by (rule open_vimage_snd)\n\nlemma closed_Times: \"closed S \\<Longrightarrow> closed T \\<Longrightarrow> closed (S \\<times> T)\"\nproof -\n  have \"S \\<times> T = (fst -` S) \\<inter> (snd -` T)\"\n    by auto\n  then show \"closed S \\<Longrightarrow> closed T \\<Longrightarrow> closed (S \\<times> T)\"\n    by (simp add: closed_vimage_fst closed_vimage_snd closed_Int)\nqed\n\nlemma subset_fst_imageI: \"A \\<times> B \\<subseteq> S \\<Longrightarrow> y \\<in> B \\<Longrightarrow> A \\<subseteq> fst ` S\"\n  unfolding image_def subset_eq by force\n\nlemma subset_snd_imageI: \"A \\<times> B \\<subseteq> S \\<Longrightarrow> x \\<in> A \\<Longrightarrow> B \\<subseteq> snd ` S\"\n  unfolding image_def subset_eq by force\n\nlemma open_image_fst:\n  assumes \"open S\"\n  shows \"open (fst ` S)\"\nproof (rule openI)\n  fix x\n  assume \"x \\<in> fst ` S\"\n  then obtain y where \"(x, y) \\<in> S\"\n    by auto\n  then obtain A B where \"open A\" \"open B\" \"x \\<in> A\" \"y \\<in> B\" \"A \\<times> B \\<subseteq> S\"\n    using \\<open>open S\\<close> unfolding open_prod_def by auto\n  from \\<open>A \\<times> B \\<subseteq> S\\<close> \\<open>y \\<in> B\\<close> have \"A \\<subseteq> fst ` S\"\n    by (rule subset_fst_imageI)\n  with \\<open>open A\\<close> \\<open>x \\<in> A\\<close> have \"open A \\<and> x \\<in> A \\<and> A \\<subseteq> fst ` S\"\n    by simp\n  then show \"\\<exists>T. open T \\<and> x \\<in> T \\<and> T \\<subseteq> fst ` S\" ..\nqed\n\nlemma open_image_snd:\n  assumes \"open S\"\n  shows \"open (snd ` S)\"\nproof (rule openI)\n  fix y\n  assume \"y \\<in> snd ` S\"\n  then obtain x where \"(x, y) \\<in> S\"\n    by auto\n  then obtain A B where \"open A\" \"open B\" \"x \\<in> A\" \"y \\<in> B\" \"A \\<times> B \\<subseteq> S\"\n    using \\<open>open S\\<close> unfolding open_prod_def by auto\n  from \\<open>A \\<times> B \\<subseteq> S\\<close> \\<open>x \\<in> A\\<close> have \"B \\<subseteq> snd ` S\"\n    by (rule subset_snd_imageI)\n  with \\<open>open B\\<close> \\<open>y \\<in> B\\<close> have \"open B \\<and> y \\<in> B \\<and> B \\<subseteq> snd ` S\"\n    by simp\n  then show \"\\<exists>T. open T \\<and> y \\<in> T \\<and> T \\<subseteq> snd ` S\" ..\nqed\n\nlemma nhds_prod: \"nhds (a, b) = nhds a \\<times>\\<^sub>F nhds b\"\n  unfolding nhds_def\nproof (subst prod_filter_INF, auto intro!: antisym INF_greatest simp: principal_prod_principal)\n  fix S T\n  assume \"open S\" \"a \\<in> S\" \"open T\" \"b \\<in> T\"\n  then show \"(INF x : {S. open S \\<and> (a, b) \\<in> S}. principal x) \\<le> principal (S \\<times> T)\"\n    by (intro INF_lower) (auto intro!: open_Times)\nnext\n  fix S'\n  assume \"open S'\" \"(a, b) \\<in> S'\"\n  then obtain S T where \"open S\" \"a \\<in> S\" \"open T\" \"b \\<in> T\" \"S \\<times> T \\<subseteq> S'\"\n    by (auto elim: open_prod_elim)\n  then show \"(INF x : {S. open S \\<and> a \\<in> S}. INF y : {S. open S \\<and> b \\<in> S}.\n      principal (x \\<times> y)) \\<le> principal S'\"\n    by (auto intro!: INF_lower2)\nqed\n\n\nsubsubsection \\<open>Continuity of operations\\<close>\n\nlemma tendsto_fst [tendsto_intros]:\n  assumes \"(f \\<longlongrightarrow> a) F\"\n  shows \"((\\<lambda>x. fst (f x)) \\<longlongrightarrow> fst a) F\"\nproof (rule topological_tendstoI)\n  fix S\n  assume \"open S\" and \"fst a \\<in> S\"\n  then have \"open (fst -` S)\" and \"a \\<in> fst -` S\"\n    by (simp_all add: open_vimage_fst)\n  with assms have \"eventually (\\<lambda>x. f x \\<in> fst -` S) F\"\n    by (rule topological_tendstoD)\n  then show \"eventually (\\<lambda>x. fst (f x) \\<in> S) F\"\n    by simp\nqed\n\nlemma tendsto_snd [tendsto_intros]:\n  assumes \"(f \\<longlongrightarrow> a) F\"\n  shows \"((\\<lambda>x. snd (f x)) \\<longlongrightarrow> snd a) F\"\nproof (rule topological_tendstoI)\n  fix S\n  assume \"open S\" and \"snd a \\<in> S\"\n  then have \"open (snd -` S)\" and \"a \\<in> snd -` S\"\n    by (simp_all add: open_vimage_snd)\n  with assms have \"eventually (\\<lambda>x. f x \\<in> snd -` S) F\"\n    by (rule topological_tendstoD)\n  then show \"eventually (\\<lambda>x. snd (f x) \\<in> S) F\"\n    by simp\nqed\n\nlemma tendsto_Pair [tendsto_intros]:\n  assumes \"(f \\<longlongrightarrow> a) F\" and \"(g \\<longlongrightarrow> b) F\"\n  shows \"((\\<lambda>x. (f x, g x)) \\<longlongrightarrow> (a, b)) F\"\nproof (rule topological_tendstoI)\n  fix S\n  assume \"open S\" and \"(a, b) \\<in> S\"\n  then obtain A B where \"open A\" \"open B\" \"a \\<in> A\" \"b \\<in> B\" \"A \\<times> B \\<subseteq> S\"\n    unfolding open_prod_def by fast\n  have \"eventually (\\<lambda>x. f x \\<in> A) F\"\n    using \\<open>(f \\<longlongrightarrow> a) F\\<close> \\<open>open A\\<close> \\<open>a \\<in> A\\<close>\n    by (rule topological_tendstoD)\n  moreover\n  have \"eventually (\\<lambda>x. g x \\<in> B) F\"\n    using \\<open>(g \\<longlongrightarrow> b) F\\<close> \\<open>open B\\<close> \\<open>b \\<in> B\\<close>\n    by (rule topological_tendstoD)\n  ultimately\n  show \"eventually (\\<lambda>x. (f x, g x) \\<in> S) F\"\n    by (rule eventually_elim2)\n       (simp add: subsetD [OF \\<open>A \\<times> B \\<subseteq> S\\<close>])\nqed\n\nlemma continuous_fst[continuous_intros]: \"continuous F f \\<Longrightarrow> continuous F (\\<lambda>x. fst (f x))\"\n  unfolding continuous_def by (rule tendsto_fst)\n\nlemma continuous_snd[continuous_intros]: \"continuous F f \\<Longrightarrow> continuous F (\\<lambda>x. snd (f x))\"\n  unfolding continuous_def by (rule tendsto_snd)\n\nlemma continuous_Pair[continuous_intros]:\n  \"continuous F f \\<Longrightarrow> continuous F g \\<Longrightarrow> continuous F (\\<lambda>x. (f x, g x))\"\n  unfolding continuous_def by (rule tendsto_Pair)\n\nlemma continuous_on_fst[continuous_intros]:\n  \"continuous_on s f \\<Longrightarrow> continuous_on s (\\<lambda>x. fst (f x))\"\n  unfolding continuous_on_def by (auto intro: tendsto_fst)\n\nlemma continuous_on_snd[continuous_intros]:\n  \"continuous_on s f \\<Longrightarrow> continuous_on s (\\<lambda>x. snd (f x))\"\n  unfolding continuous_on_def by (auto intro: tendsto_snd)\n\nlemma continuous_on_Pair[continuous_intros]:\n  \"continuous_on s f \\<Longrightarrow> continuous_on s g \\<Longrightarrow> continuous_on s (\\<lambda>x. (f x, g x))\"\n  unfolding continuous_on_def by (auto intro: tendsto_Pair)\n\nlemma continuous_on_swap[continuous_intros]: \"continuous_on A prod.swap\"\n  by (simp add: prod.swap_def continuous_on_fst continuous_on_snd\n      continuous_on_Pair continuous_on_id)\n\nlemma continuous_on_swap_args:\n  assumes \"continuous_on (A\\<times>B) (\\<lambda>(x,y). d x y)\"\n    shows \"continuous_on (B\\<times>A) (\\<lambda>(x,y). d y x)\"\nproof -\n  have \"(\\<lambda>(x,y). d y x) = (\\<lambda>(x,y). d x y) \\<circ> prod.swap\"\n    by force\n  then show ?thesis\n    apply (rule ssubst)\n    apply (rule continuous_on_compose)\n     apply (force intro: continuous_on_subset [OF continuous_on_swap])\n    apply (force intro: continuous_on_subset [OF assms])\n    done\nqed\n\nlemma isCont_fst [simp]: \"isCont f a \\<Longrightarrow> isCont (\\<lambda>x. fst (f x)) a\"\n  by (fact continuous_fst)\n\nlemma isCont_snd [simp]: \"isCont f a \\<Longrightarrow> isCont (\\<lambda>x. snd (f x)) a\"\n  by (fact continuous_snd)\n\nlemma isCont_Pair [simp]: \"\\<lbrakk>isCont f a; isCont g a\\<rbrakk> \\<Longrightarrow> isCont (\\<lambda>x. (f x, g x)) a\"\n  by (fact continuous_Pair)\n\n\nsubsubsection \\<open>Separation axioms\\<close>\n\ninstance prod :: (t0_space, t0_space) t0_space\nproof\n  fix x y :: \"'a \\<times> 'b\"\n  assume \"x \\<noteq> y\"\n  then have \"fst x \\<noteq> fst y \\<or> snd x \\<noteq> snd y\"\n    by (simp add: prod_eq_iff)\n  then show \"\\<exists>U. open U \\<and> (x \\<in> U) \\<noteq> (y \\<in> U)\"\n    by (fast dest: t0_space elim: open_vimage_fst open_vimage_snd)\nqed\n\ninstance prod :: (t1_space, t1_space) t1_space\nproof\n  fix x y :: \"'a \\<times> 'b\"\n  assume \"x \\<noteq> y\"\n  then have \"fst x \\<noteq> fst y \\<or> snd x \\<noteq> snd y\"\n    by (simp add: prod_eq_iff)\n  then show \"\\<exists>U. open U \\<and> x \\<in> U \\<and> y \\<notin> U\"\n    by (fast dest: t1_space elim: open_vimage_fst open_vimage_snd)\nqed\n\ninstance prod :: (t2_space, t2_space) t2_space\nproof\n  fix x y :: \"'a \\<times> 'b\"\n  assume \"x \\<noteq> y\"\n  then have \"fst x \\<noteq> fst y \\<or> snd x \\<noteq> snd y\"\n    by (simp add: prod_eq_iff)\n  then show \"\\<exists>U V. open U \\<and> open V \\<and> x \\<in> U \\<and> y \\<in> V \\<and> U \\<inter> V = {}\"\n    by (fast dest: hausdorff elim: open_vimage_fst open_vimage_snd)\nqed\n\nlemma isCont_swap[continuous_intros]: \"isCont prod.swap a\"\n  using continuous_on_eq_continuous_within continuous_on_swap by blast\n\nlemma open_diagonal_complement:\n  \"open {(x,y) | x y. x \\<noteq> (y::('a::t2_space))}\"\nproof (rule topological_space_class.openI)\n  fix t assume \"t \\<in> {(x, y) | x y. x \\<noteq> (y::'a)}\"\n  then obtain x y where \"t = (x,y)\" \"x \\<noteq> y\" by blast\n  then obtain U V where *: \"open U \\<and> open V \\<and> x \\<in> U \\<and> y \\<in> V \\<and> U \\<inter> V = {}\"\n    by (auto simp add: separation_t2)\n  define T where \"T = U \\<times> V\"\n  have \"open T\" using * open_Times T_def by auto\n  moreover have \"t \\<in> T\" unfolding T_def using `t = (x,y)` * by auto\n  moreover have \"T \\<subseteq> {(x, y) | x y. x \\<noteq> y}\" unfolding T_def using * by auto\n  ultimately show \"\\<exists>T. open T \\<and> t \\<in> T \\<and> T \\<subseteq> {(x, y) | x y. x \\<noteq> y}\" by auto\nqed\n\nlemma closed_diagonal:\n  \"closed {y. \\<exists> x::('a::t2_space). y = (x,x)}\"\nproof -\n  have \"{y. \\<exists> x::'a. y = (x,x)} = UNIV - {(x,y) | x y. x \\<noteq> y}\" by auto\n  then show ?thesis using open_diagonal_complement closed_Diff by auto\nqed\n\nlemma open_superdiagonal:\n  \"open {(x,y) | x y. x > (y::'a::{linorder_topology})}\"\nproof (rule topological_space_class.openI)\n  fix t assume \"t \\<in> {(x, y) | x y. y < (x::'a)}\"\n  then obtain x y where \"t = (x, y)\" \"x > y\" by blast\n  show \"\\<exists>T. open T \\<and> t \\<in> T \\<and> T \\<subseteq> {(x, y) | x y. y < x}\"\n  proof (cases)\n    assume \"\\<exists>z. y < z \\<and> z < x\"\n    then obtain z where z: \"y < z \\<and> z < x\" by blast\n    define T where \"T = {z<..} \\<times> {..<z}\"\n    have \"open T\" unfolding T_def by (simp add: open_Times)\n    moreover have \"t \\<in> T\" using T_def z `t = (x,y)` by auto\n    moreover have \"T \\<subseteq> {(x, y) | x y. y < x}\" unfolding T_def by auto\n    ultimately show ?thesis by auto\n  next\n    assume \"\\<not>(\\<exists>z. y < z \\<and> z < x)\"\n    then have *: \"{x ..} = {y<..}\" \"{..< x} = {..y}\"\n      using `x > y` apply auto using leI by blast\n    define T where \"T = {x ..} \\<times> {.. y}\"\n    then have \"T = {y<..} \\<times> {..< x}\" using * by simp\n    then have \"open T\" unfolding T_def by (simp add: open_Times)\n    moreover have \"t \\<in> T\" using T_def `t = (x,y)` by auto\n    moreover have \"T \\<subseteq> {(x, y) | x y. y < x}\" unfolding T_def using `x > y` by auto\n    ultimately show ?thesis by auto\n  qed\nqed\n\nlemma closed_subdiagonal:\n  \"closed {(x,y) | x y. x \\<le> (y::'a::{linorder_topology})}\"\nproof -\n  have \"{(x,y) | x y. x \\<le> (y::'a)} = UNIV - {(x,y) | x y. x > (y::'a)}\" by auto\n  then show ?thesis using open_superdiagonal closed_Diff by auto\nqed\n\nlemma open_subdiagonal:\n  \"open {(x,y) | x y. x < (y::'a::{linorder_topology})}\"\nproof (rule topological_space_class.openI)\n  fix t assume \"t \\<in> {(x, y) | x y. y > (x::'a)}\"\n  then obtain x y where \"t = (x, y)\" \"x < y\" by blast\n  show \"\\<exists>T. open T \\<and> t \\<in> T \\<and> T \\<subseteq> {(x, y) | x y. y > x}\"\n  proof (cases)\n    assume \"\\<exists>z. y > z \\<and> z > x\"\n    then obtain z where z: \"y > z \\<and> z > x\" by blast\n    define T where \"T = {..<z} \\<times> {z<..}\"\n    have \"open T\" unfolding T_def by (simp add: open_Times)\n    moreover have \"t \\<in> T\" using T_def z `t = (x,y)` by auto\n    moreover have \"T \\<subseteq> {(x, y) |x y. y > x}\" unfolding T_def by auto\n    ultimately show ?thesis by auto\n  next\n    assume \"\\<not>(\\<exists>z. y > z \\<and> z > x)\"\n    then have *: \"{..x} = {..<y}\" \"{x<..} = {y..}\"\n      using `x < y` apply auto using leI by blast\n    define T where \"T = {..x} \\<times> {y..}\"\n    then have \"T = {..<y} \\<times> {x<..}\" using * by simp\n    then have \"open T\" unfolding T_def by (simp add: open_Times)\n    moreover have \"t \\<in> T\" using T_def `t = (x,y)` by auto\n    moreover have \"T \\<subseteq> {(x, y) |x y. y > x}\" unfolding T_def using `x < y` by auto\n    ultimately show ?thesis by auto\n  qed\nqed\n\nlemma closed_superdiagonal:\n  \"closed {(x,y) | x y. x \\<ge> (y::('a::{linorder_topology}))}\"\nproof -\n  have \"{(x,y) | x y. x \\<ge> (y::'a)} = UNIV - {(x,y) | x y. x < y}\" by auto\n  then show ?thesis using open_subdiagonal closed_Diff by auto\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/Topological_Spaces.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.879146761176671, "lm_q2_score": 0.845942439250491, "lm_q1q2_score": 0.7437075556089618}}
{"text": "(* Title: thys/UF.thy\n   Author: Jian Xu, Xingyuan Zhang, and Christian Urban\n   Modifications: Sebastiaan Joosten\n   Modifications: Franz Regensburger (FABR) 08/2022\n     added LaTeX sections and text for explaination\n *)\n\nchapter \\<open>Construction of a Universal Function\\<close>\n\ntheory UF\n  imports Rec_Def HOL.GCD Abacus\nbegin\n\ntext \\<open>\n  This theory file constructs the Universal Function \\<open>rec_F\\<close>, which is the UTM defined\n  in terms of recursive functions. This \\<open>rec_F\\<close> is essentially an \n  interpreter for Turing Machines. Once the correctness of \\<open>rec_F\\<close> is established,\n  UTM can easily be obtained by compiling \\<open>rec_F\\<close> into the corresponding Turing Machine.\n\\<close>\n\nsection \\<open>Building blocks of the Universal Function rec\\_F\\<close>\n\nsubsection \\<open>Some helper functions: Recursive Functions for arithmetic and logic\\<close>\n\ntext \\<open>\n  The recursive function used to do arithmetic addition.\n\\<close>\n\ndefinition rec_add :: \"recf\"\n  where\n    \"rec_add \\<equiv>  Pr 1 (id 1 0) (Cn 3 s [id 3 2])\"\n\ntext \\<open>\n  The recursive function used to do arithmetic multiplication.\n\\<close>\n\ndefinition rec_mult :: \"recf\"\n  where\n    \"rec_mult = Pr 1 z (Cn 3 rec_add [id 3 0, id 3 2])\"\n\ntext \\<open>\n  The recursive function used to do arithmetic precede.\n\\<close>\n\ndefinition rec_pred :: \"recf\"\n  where\n    \"rec_pred = Cn 1 (Pr 1 z (id 3 1)) [id 1 0, id 1 0]\"\n\ntext \\<open>\n  The recursive function used to do arithmetic subtraction.\n\\<close>\n\ndefinition rec_minus :: \"recf\" \n  where\n    \"rec_minus = Pr 1 (id 1 0) (Cn 3 rec_pred [id 3 2])\"\n\ntext \\<open>\n  \\<open>constn n\\<close> is the recursive function which computes \n  natural number \\<open>n\\<close>.\n\\<close>\n\nfun constn :: \"nat \\<Rightarrow> recf\"\n  where\n    \"constn 0 = z\"  |\n    \"constn (Suc n) = Cn 1 s [constn n]\"\n\n\ntext \\<open>\n  Sign function, which returns 1 when the input argument is greater than \\<open>0\\<close>.\n\\<close>\n\ndefinition rec_sg :: \"recf\"\n  where\n    \"rec_sg = Cn 1 rec_minus [constn 1, \n                  Cn 1 rec_minus [constn 1, id 1 0]]\"\n\ntext \\<open>\n  \\<open>rec_less\\<close> compares its two arguments, returns \\<open>1\\<close> if\n  the first is less than the second; otherwise returns \\<open>0\\<close>.\n\\<close>\n\ndefinition rec_less :: \"recf\"\n  where\n    \"rec_less = Cn 2 rec_sg [Cn 2 rec_minus [id 2 1, id 2 0]]\"\n\ntext \\<open>\n  \\<open>rec_not\\<close> inverse its argument: returns \\<open>1\\<close> when the\n  argument is \\<open>0\\<close>; returns \\<open>0\\<close> otherwise.\n\\<close>\n\ndefinition rec_not :: \"recf\"\n  where\n    \"rec_not = Cn 1 rec_minus [constn 1, id 1 0]\"\n\ntext \\<open>\n  \\<open>rec_eq\\<close> compares its two arguments: returns \\<open>1\\<close>\n  if they are equal; return \\<open>0\\<close> otherwise.\n\\<close>\n\ndefinition rec_eq :: \"recf\"\n  where\n    \"rec_eq = Cn 2 rec_minus [Cn 2 (constn 1) [id 2 0], \n             Cn 2 rec_add [Cn 2 rec_minus [id 2 0, id 2 1], \n               Cn 2 rec_minus [id 2 1, id 2 0]]]\"\n\ntext \\<open>\n  \\<open>rec_conj\\<close> computes the conjunction of its two arguments, \n  returns \\<open>1\\<close> if both of them are non-zero; returns \\<open>0\\<close>\n  otherwise.\n\\<close>\n\ndefinition rec_conj :: \"recf\"\n  where\n    \"rec_conj = Cn 2 rec_sg [Cn 2 rec_mult [id 2 0, id 2 1]] \"\n\ntext \\<open>\n  \\<open>rec_disj\\<close> computes the disjunction of its two arguments, \n  returns \\<open>0\\<close> if both of them are zero; returns \\<open>0\\<close>\n  otherwise.\n\\<close>\n\ndefinition rec_disj :: \"recf\"\n  where\n    \"rec_disj = Cn 2 rec_sg [Cn 2 rec_add [id 2 0, id 2 1]]\"\n\n\ntext \\<open>\n  Computes the arity of recursive function.\n\\<close>\n\nfun arity :: \"recf \\<Rightarrow> nat\"\n  where\n    \"arity z = 1\" \n  | \"arity s = 1\"\n  | \"arity (id m n) = m\"\n  | \"arity (Cn n f gs) = n\"\n  | \"arity (Pr n f g) = Suc n\"\n  | \"arity (Mn n f) = n\"\n\ntext \\<open>\n  \\<open>get_fstn_args n (Suc k)\\<close> returns\n  \\<open>[id n 0, id n 1, id n 2, \\<dots>, id n k]\\<close>, \n  the effect of which is to take out the first \\<open>Suc k\\<close> \n  arguments out of the \\<open>n\\<close> input arguments.\n\\<close>\n\nfun get_fstn_args :: \"nat \\<Rightarrow>  nat \\<Rightarrow> recf list\"\n  where\n    \"get_fstn_args n 0 = []\"\n  | \"get_fstn_args n (Suc y) = get_fstn_args n y @ [id n y]\"\n\ntext \\<open>\n  \\<open>rec_sigma f\\<close> returns the recursive functions which \n  sums up the results of \\<open>f\\<close>:\n  \\[\n  (rec\\_sigma f)(x, y) = f(x, 0) + f(x, 1) + \\cdots + f(x, y)\n  \\]\n\\<close>\n\nfun rec_sigma :: \"recf \\<Rightarrow> recf\"\n  where\n    \"rec_sigma rf = \n       (let vl = arity rf in \n          Pr (vl - 1) (Cn (vl - 1) rf (get_fstn_args (vl - 1) (vl - 1) @ \n                    [Cn (vl - 1) (constn 0) [id (vl - 1) 0]])) \n             (Cn (Suc vl) rec_add [id (Suc vl) vl, \n                    Cn (Suc vl) rf (get_fstn_args (Suc vl) (vl - 1) \n                        @ [Cn (Suc vl) s [id (Suc vl) (vl - 1)]])]))\"\n\ntext \\<open>\n  \\<open>rec_exec\\<close> is the interpreter function for\n  Recursive Functions. The function is defined such that \n  it always returns meaningful results for primitive recursive \n  functions.\n\\<close>\n\nsubsubsection \\<open>Correctness of the helper functions\\<close>\n\ndeclare rec_exec.simps[simp del] constn.simps[simp del]\n\ntext \\<open>\n  Correctness of \\<open>rec_add\\<close>.\n\\<close>\nlemma add_lemma: \"\\<And> x y. rec_exec rec_add [x, y] =  x + y\"\n  by(induct_tac y, auto simp: rec_add_def rec_exec.simps)\n\ntext \\<open>\n  Correctness of \\<open>rec_mult\\<close>.\n\\<close>\nlemma mult_lemma: \"\\<And> x y. rec_exec rec_mult [x, y] = x * y\"\n  by(induct_tac y, auto simp: rec_mult_def rec_exec.simps add_lemma)\n\ntext \\<open>\n  Correctness of \\<open>rec_pred\\<close>.\n\\<close>\nlemma pred_lemma: \"\\<And> x. rec_exec rec_pred [x] =  x - 1\"\n  by(induct_tac x, auto simp: rec_pred_def rec_exec.simps)\n\ntext \\<open>\n  Correctness of \\<open>rec_minus\\<close>.\n\\<close>\nlemma minus_lemma: \"\\<And> x y. rec_exec rec_minus [x, y] = x - y\"\n  by(induct_tac y, auto simp: rec_exec.simps rec_minus_def pred_lemma)\n\ntext \\<open>\n  Correctness of \\<open>rec_sg\\<close>.\n\\<close>\nlemma sg_lemma: \"\\<And> x. rec_exec rec_sg [x] = (if x = 0 then 0 else 1)\"\n  by(auto simp: rec_sg_def minus_lemma rec_exec.simps constn.simps)\n\ntext \\<open>\n  Correctness of \\<open>constn\\<close>.\n\\<close>\nlemma constn_lemma: \"rec_exec (constn n) [x] = n\"\n  by(induct n, auto simp: rec_exec.simps constn.simps)\n\ntext \\<open>\n  Correctness of \\<open>rec_less\\<close>.\n\\<close>\nlemma less_lemma: \"\\<And> x y. rec_exec rec_less [x, y] = \n  (if x < y then 1 else 0)\"\n  by(induct_tac y, auto simp: rec_exec.simps \n      rec_less_def minus_lemma sg_lemma)\n\ntext \\<open>\n  Correctness of \\<open>rec_not\\<close>.\n\\<close>\n\n\ntext \\<open>\n  Correctness of \\<open>rec_eq\\<close>.\n\\<close>\nlemma eq_lemma: \"\\<And> x y. rec_exec rec_eq [x, y] = (if x = y then 1 else 0)\"\n  by(induct_tac y, auto simp: rec_exec.simps rec_eq_def constn_lemma add_lemma minus_lemma)\n\ntext \\<open>\n  Correctness of \\<open>rec_conj\\<close>.\n\\<close>\nlemma conj_lemma: \"\\<And> x y. rec_exec rec_conj [x, y] = (if x = 0 \\<or> y = 0 then 0 \n                                                       else 1)\"\n  by(induct_tac y, auto simp: rec_exec.simps sg_lemma rec_conj_def mult_lemma)\n\ntext \\<open>\n  Correctness of \\<open>rec_disj\\<close>.\n\\<close>\nlemma disj_lemma: \"\\<And> x y. rec_exec rec_disj [x, y] = (if x = 0 \\<and> y = 0 then 0\n                                                     else 1)\"\n  by(induct_tac y, auto simp: rec_disj_def sg_lemma add_lemma rec_exec.simps)\n\nsubsection \\<open>The characteristic function primerec for the set of Primitive Recursive Functions\\<close>\n\ntext \\<open>\n  \\<open>primerec recf n\\<close> is true iff \n  \\<open>recf\\<close> is a primitive recursive function \n  with arity \\<open>n\\<close>.\n\\<close>\ninductive primerec :: \"recf \\<Rightarrow> nat \\<Rightarrow> bool\"\n  where\n    prime_z[intro]:  \"primerec z (Suc 0)\" |\n    prime_s[intro]:  \"primerec s (Suc 0)\" |\n    prime_id[intro!]: \"\\<lbrakk>n < m\\<rbrakk> \\<Longrightarrow> primerec (id m n) m\" |\n    prime_cn[intro!]: \"\\<lbrakk>primerec f k; length gs = k; \n  \\<forall> i < length gs. primerec (gs ! i) m; m = n\\<rbrakk> \n  \\<Longrightarrow> primerec (Cn n f gs) m\" |\n    prime_pr[intro!]: \"\\<lbrakk>primerec f n; \n  primerec g (Suc (Suc n)); m = Suc n\\<rbrakk> \n  \\<Longrightarrow> primerec (Pr n f g) m\" \n\ninductive_cases prime_cn_reverse'[elim]: \"primerec (Cn n f gs) n\" \ninductive_cases prime_mn_reverse: \"primerec (Mn n f) m\" \ninductive_cases prime_z_reverse[elim]: \"primerec z n\"\ninductive_cases prime_s_reverse[elim]: \"primerec s n\"\ninductive_cases prime_id_reverse[elim]: \"primerec (id m n) k\"\ninductive_cases prime_cn_reverse[elim]: \"primerec (Cn n f gs) m\"\ninductive_cases prime_pr_reverse[elim]: \"primerec (Pr n f g) m\"\n\nsubsection \\<open>The Recursive Function rec\\_sigma\\<close>\n\ndeclare mult_lemma[simp] add_lemma[simp] pred_lemma[simp] \n  minus_lemma[simp] sg_lemma[simp] constn_lemma[simp] \n  less_lemma[simp] not_lemma[simp] eq_lemma[simp]\n  conj_lemma[simp] disj_lemma[simp]\n\ntext \\<open>\n  \\<open>Sigma\\<close> is the logical specification of \n  the recursive function \\<open>rec_sigma\\<close>.\n\\<close>\nfunction Sigma :: \"(nat list \\<Rightarrow> nat) \\<Rightarrow> nat list \\<Rightarrow> nat\"\n  where\n    \"Sigma g xs = (if last xs = 0 then g xs\n                 else (Sigma g (butlast xs @ [last xs - 1]) +\n                       g xs)) \"\n  by pat_completeness auto\ntermination\nproof\n  show \"wf (measure (\\<lambda> (f, xs). last xs))\" by auto\nnext\n  fix g xs\n  assume \"last (xs::nat list) \\<noteq> 0\"\n  thus \"((g, butlast xs @ [last xs - 1]), g, xs)  \n                   \\<in> measure (\\<lambda>(f, xs). last xs)\"\n    by auto\nqed\n\ndeclare rec_exec.simps[simp del] get_fstn_args.simps[simp del]\n  arity.simps[simp del] Sigma.simps[simp del]\n  rec_sigma.simps[simp del]\n\nlemma rec_pr_Suc_simp_rewrite: \n  \"rec_exec (Pr n f g) (xs @ [Suc x]) =\n                       rec_exec g (xs @ [x] @ \n                        [rec_exec (Pr n f g) (xs @ [x])])\"\n  by(simp add: rec_exec.simps)\n\nlemma Sigma_0_simp_rewrite:\n  \"Sigma f (xs @ [0]) = f (xs @ [0])\"\n  by(simp add: Sigma.simps)\n\nlemma Sigma_Suc_simp_rewrite: \n  \"Sigma f (xs @ [Suc x]) = Sigma f (xs @ [x]) + f (xs @ [Suc x])\"\n  by(simp add: Sigma.simps)\n\nlemma append_access_1[simp]: \"(xs @ ys) ! (Suc (length xs)) = ys ! 1\"\n  by(simp add: nth_append)\n\nlemma get_fstn_args_take: \"\\<lbrakk>length xs = m; n \\<le> m\\<rbrakk> \\<Longrightarrow> \n  map (\\<lambda> f. rec_exec f xs) (get_fstn_args m n)= take n xs\"\nproof(induct n)\n  case 0 thus \"?case\"\n    by(simp add: get_fstn_args.simps)\nnext\n  case (Suc n) thus \"?case\"\n    by(simp add: get_fstn_args.simps rec_exec.simps \n        take_Suc_conv_app_nth)\nqed\n\nlemma arity_primerec[simp]: \"primerec f n \\<Longrightarrow> arity f = n\"\n  apply(cases f)\n       apply(auto simp: arity.simps )\n  apply(erule_tac prime_mn_reverse)\n  done\n\n\n\ntext \\<open>\n  The correctness of \\<open>rec_sigma\\<close> with respect to its specification.\n\\<close>\n\n\nsubsection \\<open>The Recursive Function rec\\_accum\\<close>\n\ntext \\<open>\n  \\<open>rec_accum f (x1, x2, \\<dots>, xn, k) = \n           f(x1, x2, \\<dots>, xn, 0) * \n           f(x1, x2, \\<dots>, xn, 1) *\n               \\<dots> \n           f(x1, x2, \\<dots>, xn, k)\\<close>\n\\<close>\n\nfun rec_accum :: \"recf \\<Rightarrow> recf\"\n  where\n    \"rec_accum rf = \n       (let vl = arity rf in \n          Pr (vl - 1) (Cn (vl - 1) rf (get_fstn_args (vl - 1) (vl - 1) @ \n                     [Cn (vl - 1) (constn 0) [id (vl - 1) 0]])) \n             (Cn (Suc vl) rec_mult [id (Suc vl) (vl), \n                    Cn (Suc vl) rf (get_fstn_args (Suc vl) (vl - 1) \n                      @ [Cn (Suc vl) s [id (Suc vl) (vl - 1)]])]))\"\n\ntext \\<open>\n  \\<open>Accum\\<close> is the formal specification of \\<open>rec_accum\\<close>.\n\\<close>\nfunction Accum :: \"(nat list \\<Rightarrow> nat) \\<Rightarrow> nat list \\<Rightarrow> nat\"\n  where\n    \"Accum f xs = (if last xs = 0 then f xs \n                     else (Accum f (butlast xs @ [last xs - 1]) *\n                       f xs))\"\n  by pat_completeness auto\ntermination\nproof\n  show \"wf (measure (\\<lambda> (f, xs). last xs))\"\n    by auto\nnext\n  fix f xs\n  assume \"last xs \\<noteq> (0::nat)\"\n  thus \"((f, butlast xs @ [last xs - 1]), f, xs) \\<in> \n            measure (\\<lambda>(f, xs). last xs)\"\n    by auto\nqed\n\nlemma rec_accum_Suc_simp_rewrite: \n  \"primerec f (Suc (length xs))\n    \\<Longrightarrow> rec_exec (rec_accum f) (xs @ [Suc x]) = \n    rec_exec (rec_accum f) (xs @ [x]) * rec_exec f (xs @ [Suc x])\"\n  apply(induct x)\n   apply(auto simp: rec_sigma.simps Let_def rec_pr_Suc_simp_rewrite\n      rec_exec.simps get_fstn_args_take)\n  done  \n\ntext \\<open>\n  The correctness of \\<open>rec_accum\\<close> with respect to its specification.\n\\<close>\nlemma accum_lemma :\n  \"primerec rg (Suc (length xs))\n     \\<Longrightarrow> rec_exec (rec_accum rg) (xs @ [x]) = Accum (rec_exec rg) (xs @ [x])\"\n  apply(induct x)\n   apply(auto simp: rec_exec.simps rec_sigma.simps Let_def \n      get_fstn_args_take)\n  done\n\ndeclare rec_accum.simps [simp del]\n\nsubsection \\<open>The Recursive Function rec\\_all\\<close>\n\ntext \\<open>\n  \\<open>rec_all t f (x1, x2, \\<dots>, xn)\\<close> \n  computes the charactrization function of the following FOL formula:\n  \\<open>(\\<forall> x \\<le> t(x1, x2, \\<dots>, xn). (f(x1, x2, \\<dots>, xn, x) > 0))\\<close>\n\\<close>\nfun rec_all :: \"recf \\<Rightarrow> recf \\<Rightarrow> recf\"\n  where\n    \"rec_all rt rf = \n    (let vl = arity rf in\n       Cn (vl - 1) rec_sg [Cn (vl - 1) (rec_accum rf) \n                 (get_fstn_args (vl - 1) (vl - 1) @ [rt])])\"\n\nlemma rec_accum_ex:\n  assumes \"primerec rf (Suc (length xs))\"\n  shows \"(rec_exec (rec_accum rf) (xs @ [x]) = 0) = \n         (\\<exists> t \\<le> x. rec_exec rf (xs @ [t]) = 0)\"\nproof(induct x)\n  case (Suc x)\n  with assms show ?case \n    apply(auto simp add: rec_exec.simps rec_accum.simps get_fstn_args_take)\n     apply(rename_tac t ta)\n     apply(rule_tac x = ta in exI, simp)\n    apply(case_tac \"t = Suc x\", simp_all)\n    apply(rule_tac x = t in exI, simp) done\nqed (insert assms,auto simp add: rec_exec.simps rec_accum.simps get_fstn_args_take)\n\ntext \\<open>\n  The correctness of \\<open>rec_all\\<close>.\n\\<close>\nlemma all_lemma: \n  \"\\<lbrakk>primerec rf (Suc (length xs));\n    primerec rt (length xs)\\<rbrakk>\n  \\<Longrightarrow> rec_exec (rec_all rt rf) xs = (if (\\<forall> x \\<le> (rec_exec rt xs). 0 < rec_exec rf (xs @ [x])) then 1\n                                                                                              else 0)\"\n  apply(auto simp: rec_all.simps)\n   apply(simp add: rec_exec.simps map_append get_fstn_args_take split: if_splits)\n   apply(drule_tac x = \"rec_exec rt xs\" in rec_accum_ex)\n   apply(cases \"rec_exec (rec_accum rf) (xs @ [rec_exec rt xs]) = 0\", simp_all)\n   apply force\n  apply(simp add: rec_exec.simps map_append get_fstn_args_take)\n  apply(drule_tac x = \"rec_exec rt xs\" in rec_accum_ex)\n  apply(cases \"rec_exec (rec_accum rf) (xs @ [rec_exec rt xs]) = 0\")\n   apply force+\n  done\n\nsubsection \\<open>The Recursive Function rec\\_ex\\<close>\n\ntext \\<open>\n  \\<open>rec_ex t f (x1, x2, \\<dots>, xn)\\<close> \n  computes the charactrization function of the following FOL formula:\n  \\<open>(\\<exists> x \\<le> t(x1, x2, \\<dots>, xn). (f(x1, x2, \\<dots>, xn, x) > 0))\\<close>\n\\<close>\nfun rec_ex :: \"recf \\<Rightarrow> recf \\<Rightarrow> recf\"\n  where\n    \"rec_ex rt rf = \n       (let vl = arity rf in \n         Cn (vl - 1) rec_sg [Cn (vl - 1) (rec_sigma rf) \n                  (get_fstn_args (vl - 1) (vl - 1) @ [rt])])\"\n\nlemma rec_sigma_ex: \n  assumes \"primerec rf (Suc (length xs))\"\n  shows \"(rec_exec (rec_sigma rf) (xs @ [x]) = 0) = \n                          (\\<forall> t \\<le> x. rec_exec rf (xs @ [t]) = 0)\"\nproof(induct x)\n  case (Suc x)\n  from Suc assms show ?case\n    by(auto simp add: rec_exec.simps rec_sigma.simps \n        get_fstn_args_take elim:le_SucE)\nqed (insert assms,auto simp: get_fstn_args_take rec_exec.simps rec_sigma.simps)\n\ntext \\<open>\n  The correctness of \\<open>rec_ex\\<close>.\n\\<close>\nlemma ex_lemma:\"\n  \\<lbrakk>primerec rf (Suc (length xs));\n   primerec rt (length xs)\\<rbrakk>\n\\<Longrightarrow> (rec_exec (rec_ex rt rf) xs =\n    (if (\\<exists> x \\<le> (rec_exec rt xs). 0 <rec_exec rf (xs @ [x])) then 1\n     else 0))\"\n  apply(auto simp: rec_exec.simps get_fstn_args_take split: if_splits)\n   apply(drule_tac x = \"rec_exec rt xs\" in rec_sigma_ex, simp)\n  apply(drule_tac x = \"rec_exec rt xs\" in rec_sigma_ex, simp)\n  done\n\nsubsection \\<open>The Recursive Function rec\\_Minr\\<close>\n\ntext \\<open>\n  Definition of \\<open>Min[R]\\<close> on page 77 of Boolos's book~\\<^cite>\\<open>\"Boolos07\"\\<close>.\n\\<close>\n\nfun Minr :: \"(nat list \\<Rightarrow> bool) \\<Rightarrow> nat list \\<Rightarrow> nat \\<Rightarrow> nat\"\n  where \"Minr Rr xs w = (let setx = {y | y. (y \\<le> w) \\<and> Rr (xs @ [y])} in \n                        if (setx = {}) then (Suc w)\n                                       else (Min setx))\"\n\ndeclare Minr.simps[simp del] rec_all.simps[simp del]\n\ntext \\<open>\n  The following is a set of auxiliary lemmas about \\<open>Minr\\<close>.\n\\<close>\nlemma Minr_range: \"Minr Rr xs w \\<le> w \\<or> Minr Rr xs w = Suc w\"\n  apply(auto simp: Minr.simps)\n  apply(subgoal_tac \"Min {x. x \\<le> w \\<and> Rr (xs @ [x])} \\<le> x\")\n   apply(erule_tac order_trans, simp)\n  apply(rule_tac Min_le, auto)\n  done\n\nlemma expand_conj_in_set: \"{x. x \\<le> Suc w \\<and> Rr (xs @ [x])}\n    = (if Rr (xs @ [Suc w]) then insert (Suc w) \n                              {x. x \\<le> w \\<and> Rr (xs @ [x])}\n      else {x. x \\<le> w \\<and> Rr (xs @ [x])})\"\n  by (auto elim:le_SucE)\n\nlemma Minr_strip_Suc[simp]: \"Minr Rr xs w \\<le> w \\<Longrightarrow> Minr Rr xs (Suc w) = Minr Rr xs w\"\n  by(cases \"\\<forall>x\\<le>w. \\<not> Rr (xs @ [x])\",auto simp add: Minr.simps expand_conj_in_set)\n\nlemma x_empty_set[simp]: \"\\<forall>x\\<le>w. \\<not> Rr (xs @ [x]) \\<Longrightarrow>  \n                           {x. x \\<le> w \\<and> Rr (xs @ [x])} = {} \"\n  by auto\n\nlemma Minr_is_Suc[simp]: \"\\<lbrakk>Minr Rr xs w = Suc w; Rr (xs @ [Suc w])\\<rbrakk> \\<Longrightarrow> \n                                       Minr Rr xs (Suc w) = Suc w\"\n  apply(simp add: Minr.simps expand_conj_in_set)\n  apply(cases \"\\<forall>x\\<le>w. \\<not> Rr (xs @ [x])\", auto)\n  done\n\nlemma Minr_is_Suc_Suc[simp]: \"\\<lbrakk>Minr Rr xs w = Suc w; \\<not> Rr (xs @ [Suc w])\\<rbrakk> \\<Longrightarrow> \n                                   Minr Rr xs (Suc w) = Suc (Suc w)\"\n  apply(simp add: Minr.simps expand_conj_in_set)\n  apply(cases \"\\<forall>x\\<le>w. \\<not> Rr (xs @ [x])\", auto)\n  apply(subgoal_tac \"Min {x. x \\<le> w \\<and> Rr (xs @ [x])} \\<in> \n                                {x. x \\<le> w \\<and> Rr (xs @ [x])}\", simp)\n  apply(rule_tac Min_in, auto)\n  done\n\nlemma Minr_Suc_simp: \n  \"Minr Rr xs (Suc w) = \n      (if Minr Rr xs w \\<le> w then Minr Rr xs w\n       else if (Rr (xs @ [Suc w])) then (Suc w)\n       else Suc (Suc w))\"\n  by(insert Minr_range[of Rr xs w], auto)\n\n\ntext \\<open>\n  \\<open>rec_Minr\\<close> is the recursive function \n  used to implement \\<open>Minr\\<close>:\n  if \\<open>Rr\\<close> is implemented by a recursive function \\<open>recf\\<close>,\n  then \\<open>rec_Minr recf\\<close> is the recursive function used to \n  implement \\<open>Minr Rr\\<close>\n\\<close>\n\nfun rec_Minr :: \"recf \\<Rightarrow> recf\"\n  where\n    \"rec_Minr rf = \n     (let vl = arity rf\n      in let rq = rec_all (id vl (vl - 1)) (Cn (Suc vl) \n              rec_not [Cn (Suc vl) rf \n                    (get_fstn_args (Suc vl) (vl - 1) @\n                                        [id (Suc vl) (vl)])]) \n      in  rec_sigma rq)\"\n\nlemma length_getpren_params[simp]: \"length (get_fstn_args m n) = n\"\n  by(induct n, auto simp: get_fstn_args.simps)\n\nlemma length_app:\n  \"(length (get_fstn_args (arity rf - Suc 0)\n                           (arity rf - Suc 0)\n   @ [Cn (arity rf - Suc 0) (constn 0)\n           [recf.id (arity rf - Suc 0) 0]]))\n    = (Suc (arity rf - Suc 0))\"\n  apply(simp)\n  done\n\nlemma primerec_accum: \"primerec (rec_accum rf) n \\<Longrightarrow> primerec rf n\"\n  apply(auto simp: rec_accum.simps Let_def)\n  apply(erule_tac prime_pr_reverse, simp)\n  apply(erule_tac prime_cn_reverse, simp only: length_app)\n  done\n\nlemma primerec_all: \"primerec (rec_all rt rf) n \\<Longrightarrow>\n                       primerec rt n \\<and> primerec rf (Suc n)\"\n  apply(simp add: rec_all.simps Let_def)\n  apply(erule_tac prime_cn_reverse, simp)\n  apply(erule_tac prime_cn_reverse, simp)\n  apply(erule_tac x = n in allE, simp add: nth_append primerec_accum)\n  done\n\ndeclare numeral_3_eq_3[simp]\n\nlemma primerec_rec_pred_1[intro]: \"primerec rec_pred (Suc 0)\"\n  apply(simp add: rec_pred_def)\n  apply(rule_tac prime_cn, auto dest:less_2_cases[unfolded numeral_eqs_upto_12 One_nat_def])\n  done\n\nlemma primerec_rec_minus_2[intro]: \"primerec rec_minus (Suc (Suc 0))\"\n  apply(auto simp: rec_minus_def)\n  done\n\nlemma primerec_constn_1[intro]: \"primerec (constn n) (Suc 0)\"\n  apply(induct n)\n   apply(auto simp: constn.simps)\n  done\n\nlemma primerec_rec_sg_1[intro]: \"primerec rec_sg (Suc 0)\" \n  apply(simp add: rec_sg_def)\n  apply(rule_tac k = \"Suc (Suc 0)\" in prime_cn)\n     apply(auto)\n  apply(auto dest!:less_2_cases[unfolded numeral_eqs_upto_12 One_nat_def])\n    apply( auto)\n  done\n\nlemma primerec_getpren[elim]: \"\\<lbrakk>i < n; n \\<le> m\\<rbrakk> \\<Longrightarrow> primerec (get_fstn_args m n ! i) m\"\n  apply(induct n, auto simp: get_fstn_args.simps)\n  apply(cases \"i = n\", auto simp: nth_append intro: prime_id)\n  done\n\nlemma primerec_rec_add_2[intro]: \"primerec rec_add (Suc (Suc 0))\"\n  apply(simp add: rec_add_def)\n  apply(rule_tac prime_pr, auto)\n  done\n\nlemma primerec_rec_mult_2[intro]:\"primerec rec_mult (Suc (Suc 0))\"\n  apply(simp add: rec_mult_def )\n  apply(rule_tac prime_pr, auto)\n  using less_2_cases numeral_2_eq_2 by fastforce\n\nlemma primerec_ge_2_elim[elim]: \"\\<lbrakk>primerec rf n; n \\<ge> Suc (Suc 0)\\<rbrakk>   \\<Longrightarrow> \n                        primerec (rec_accum rf) n\"\n  apply(auto simp: rec_accum.simps)\n   apply(simp add: nth_append, auto dest!:less_2_cases[unfolded numeral_eqs_upto_12 One_nat_def])\n    apply force\n   apply force\n  apply(auto simp: nth_append)\n  done\n\nlemma primerec_all_iff: \n  \"\\<lbrakk>primerec rt n; primerec rf (Suc n); n > 0\\<rbrakk> \\<Longrightarrow> \n                                 primerec (rec_all rt rf) n\"\n  apply(simp add: rec_all.simps, auto)\n    apply(auto, simp add: nth_append, auto)\n  done\n\nlemma primerec_rec_not_1[intro]: \"primerec rec_not (Suc 0)\"\n  apply(simp add: rec_not_def)\n  apply(rule prime_cn, auto dest!:less_2_cases[unfolded numeral_eqs_upto_12 One_nat_def])\n  done\n\nlemma Min_false1[simp]: \"\\<lbrakk>\\<not> Min {uu. uu \\<le> w \\<and> 0 < rec_exec rf (xs @ [uu])} \\<le> w;\n       x \\<le> w; 0 < rec_exec rf (xs @ [x])\\<rbrakk>\n      \\<Longrightarrow>  False\"\n  apply(subgoal_tac \"finite {uu. uu \\<le> w \\<and> 0 < rec_exec rf (xs @ [uu])}\")\n   apply(subgoal_tac \"{uu. uu \\<le> w \\<and> 0 < rec_exec rf (xs @ [uu])} \\<noteq> {}\")\n    apply(simp add: Min_le_iff, simp)\n   apply(rule_tac x = x in exI, simp)\n  apply(simp)\n  done\n\nlemma sigma_minr_lemma: \n  assumes prrf:  \"primerec rf (Suc (length xs))\"\n  shows \"UF.Sigma (rec_exec (rec_all (recf.id (Suc (length xs)) (length xs))\n     (Cn (Suc (Suc (length xs))) rec_not\n      [Cn (Suc (Suc (length xs))) rf (get_fstn_args (Suc (Suc (length xs))) \n       (length xs) @ [recf.id (Suc (Suc (length xs))) (Suc (length xs))])])))\n      (xs @ [w]) =\n       Minr (\\<lambda>args. 0 < rec_exec rf args) xs w\"\nproof(induct w)\n  let ?rt = \"(recf.id (Suc (length xs)) ((length xs)))\"\n  let ?rf = \"(Cn (Suc (Suc (length xs))) \n    rec_not [Cn (Suc (Suc (length xs))) rf \n    (get_fstn_args (Suc (Suc (length xs))) (length xs) @ \n                [recf.id (Suc (Suc (length xs))) \n    (Suc ((length xs)))])])\"\n  let ?rq = \"(rec_all ?rt ?rf)\"\n  have prrf: \"primerec ?rf (Suc (length (xs @ [0]))) \\<and>\n        primerec ?rt (length (xs @ [0]))\"\n    apply(auto simp: prrf nth_append)+\n    done\n  show \"Sigma (rec_exec (rec_all ?rt ?rf)) (xs @ [0])\n       = Minr (\\<lambda>args. 0 < rec_exec rf args) xs 0\"\n    apply(simp add: Sigma.simps)\n    apply(simp only: prrf all_lemma,  \n        auto simp: rec_exec.simps get_fstn_args_take Minr.simps)\n    apply(rule_tac Min_eqI, auto)\n    done\nnext\n  fix w\n  let ?rt = \"(recf.id (Suc (length xs)) ((length xs)))\"\n  let ?rf = \"(Cn (Suc (Suc (length xs))) \n    rec_not [Cn (Suc (Suc (length xs))) rf \n    (get_fstn_args (Suc (Suc (length xs))) (length xs) @ \n                [recf.id (Suc (Suc (length xs))) \n    (Suc ((length xs)))])])\"\n  let ?rq = \"(rec_all ?rt ?rf)\"\n  assume ind:\n    \"Sigma (rec_exec (rec_all ?rt ?rf)) (xs @ [w]) = Minr (\\<lambda>args. 0 < rec_exec rf args) xs w\"\n  have prrf: \"primerec ?rf (Suc (length (xs @ [Suc w]))) \\<and>\n        primerec ?rt (length (xs @ [Suc w]))\"\n    apply(auto simp: prrf nth_append)+\n    done\n  show \"UF.Sigma (rec_exec (rec_all ?rt ?rf))\n         (xs @ [Suc w]) =\n        Minr (\\<lambda>args. 0 < rec_exec rf args) xs (Suc w)\"\n    apply(auto simp: Sigma_Suc_simp_rewrite ind Minr_Suc_simp)\n       apply(simp_all only: prrf all_lemma)\n       apply(auto simp: rec_exec.simps get_fstn_args_take Let_def Minr.simps split: if_splits)\n       apply(drule_tac Min_false1, simp, simp, simp)\n      apply (metis le_SucE neq0_conv)\n     apply(drule_tac Min_false1, simp, simp, simp)\n    apply(drule_tac Min_false1, simp, simp, simp)\n    done\nqed\n\ntext \\<open>\n  The correctness of \\<open>rec_Minr\\<close>.\n\\<close>\nlemma Minr_lemma: \"\n  \\<lbrakk>primerec rf (Suc (length xs))\\<rbrakk> \n     \\<Longrightarrow> rec_exec (rec_Minr rf) (xs @ [w]) = \n            Minr (\\<lambda> args. (0 < rec_exec rf args)) xs w\"\nproof -\n  let ?rt = \"(recf.id (Suc (length xs)) ((length xs)))\"\n  let ?rf = \"(Cn (Suc (Suc (length xs))) \n    rec_not [Cn (Suc (Suc (length xs))) rf \n    (get_fstn_args (Suc (Suc (length xs))) (length xs) @ \n                [recf.id (Suc (Suc (length xs))) \n    (Suc ((length xs)))])])\"\n  let ?rq = \"(rec_all ?rt ?rf)\"\n  assume h: \"primerec rf (Suc (length xs))\"\n  have h1: \"primerec ?rq (Suc (length xs))\"\n    apply(rule_tac primerec_all_iff)\n      apply(auto simp: h nth_append)+\n    done\n  moreover have \"arity rf = Suc (length xs)\"\n    using h by auto\n  ultimately show \"rec_exec (rec_Minr rf) (xs @ [w]) = \n    Minr (\\<lambda> args. (0 < rec_exec rf args)) xs w\"\n    apply(simp add: arity.simps Let_def sigma_lemma all_lemma)\n    apply(rule_tac  sigma_minr_lemma)\n    apply(simp add: h)\n    done\nqed\n\nsubsection \\<open>The Recursive Function rec\\_le\\<close>\n\ntext \\<open>\n  \\<open>rec_le\\<close> is the comparison function \n  which compares its two arguments, testing whether the \n  first is less or equal to the second.\n\\<close>\ndefinition rec_le :: \"recf\"\n  where\n    \"rec_le = Cn (Suc (Suc 0)) rec_disj [rec_less, rec_eq]\"\n\ntext \\<open>\n  The correctness of \\<open>rec_le\\<close>.\n\\<close>\nlemma le_lemma: \n  \"\\<And>x y. rec_exec rec_le [x, y] = (if (x \\<le> y) then 1 else 0)\"\n  by(auto simp: rec_le_def rec_exec.simps)\n\nsubsection \\<open>The Recursive Function rec\\_maxr\\<close>\n\ntext \\<open>\n  Definition of \\<open>Max[Rr]\\<close> on page 77 of Boolos's book~\\<^cite>\\<open>\"Boolos07\"\\<close>.\n\\<close>\n\nfun Maxr :: \"(nat list \\<Rightarrow> bool) \\<Rightarrow> nat list \\<Rightarrow> nat \\<Rightarrow> nat\"\n  where\n    \"Maxr Rr xs w = (let setx = {y. y \\<le> w \\<and> Rr (xs @[y])} in \n                  if setx = {} then 0\n                  else Max setx)\"\n\ntext \\<open>\n  \\<open>rec_maxr\\<close> is the Recursive Function \n  used to implement \\<open>Maxr\\<close>.\n\n\\<close>\nfun rec_maxr :: \"recf \\<Rightarrow> recf\"\n  where\n    \"rec_maxr rr = (let vl = arity rr in \n                  let rt = id (Suc vl) (vl - 1) in\n                  let rf1 = Cn (Suc (Suc vl)) rec_le \n                    [id (Suc (Suc vl)) \n                     ((Suc vl)), id (Suc (Suc vl)) (vl)] in\n                  let rf2 = Cn (Suc (Suc vl)) rec_not \n                      [Cn (Suc (Suc vl)) \n                           rr (get_fstn_args (Suc (Suc vl)) \n                            (vl - 1) @ \n                             [id (Suc (Suc vl)) ((Suc vl))])] in\n                  let rf = Cn (Suc (Suc vl)) rec_disj [rf1, rf2] in\n                  let Qf = Cn (Suc vl) rec_not [rec_all rt rf]\n                  in Cn vl (rec_sigma Qf) (get_fstn_args vl vl @\n                                                         [id vl (vl - 1)]))\"\n\ndeclare rec_maxr.simps[simp del] Maxr.simps[simp del] \ndeclare le_lemma[simp]\n\ndeclare numeral_2_eq_2[simp]\n\nlemma primerec_rec_disj_2[intro]: \"primerec rec_disj (Suc (Suc 0))\"\n  apply(simp add: rec_disj_def, auto)\n    apply(auto dest!:less_2_cases[unfolded numeral_eqs_upto_12 One_nat_def])\n  done\n\nlemma primerec_rec_less_2[intro]: \"primerec rec_less (Suc (Suc 0))\"\n  apply(simp add: rec_less_def, auto)\n    apply(auto dest!:less_2_cases[unfolded numeral_eqs_upto_12 One_nat_def])\n  done\n\nlemma primerec_rec_eq_2[intro]: \"primerec rec_eq (Suc (Suc 0))\"\n  apply(simp add: rec_eq_def)\n  apply(rule_tac prime_cn, auto dest!:less_2_cases[unfolded numeral_eqs_upto_12 One_nat_def])\n       apply force+\n  done\n\nlemma primerec_rec_le_2[intro]: \"primerec rec_le (Suc (Suc 0))\"\n  apply(simp add: rec_le_def)\n  apply(rule_tac prime_cn, auto dest!:less_2_cases[unfolded numeral_eqs_upto_12 One_nat_def])\n  done\n\nlemma Sigma_0: \"\\<forall> i \\<le> n. (f (xs @ [i]) = 0) \\<Longrightarrow> \n                              Sigma f (xs @ [n]) = 0\"\n  apply(induct n, simp add: Sigma.simps)\n  apply(simp add: Sigma_Suc_simp_rewrite)\n  done\n\nlemma Sigma_Suc[elim]: \"\\<forall>k<Suc w. f (xs @ [k]) = Suc 0\n        \\<Longrightarrow> Sigma f (xs @ [w]) = Suc w\"\n  apply(induct w)\n   apply(simp add: Sigma.simps, simp)\n  apply(simp add: Sigma.simps)\n  done\n\nlemma Sigma_max_point: \"\\<lbrakk>\\<forall> k < ma. f (xs @ [k]) = 1;\n        \\<forall> k \\<ge> ma. f (xs @ [k]) = 0; ma \\<le> w\\<rbrakk>\n    \\<Longrightarrow> Sigma f (xs @ [w]) = ma\"\n  apply(induct w, auto)\n   apply(rule_tac Sigma_0, simp)\n  apply(simp add: Sigma_Suc_simp_rewrite)\n  using Sigma_Suc by fastforce\n\nlemma Sigma_Max_lemma: \n  assumes prrf: \"primerec rf (Suc (length xs))\"\n  shows \"UF.Sigma (rec_exec (Cn (Suc (Suc (length xs))) rec_not\n  [rec_all (recf.id (Suc (Suc (length xs))) (length xs))\n  (Cn (Suc (Suc (Suc (length xs)))) rec_disj\n  [Cn (Suc (Suc (Suc (length xs)))) rec_le\n  [recf.id (Suc (Suc (Suc (length xs)))) (Suc (Suc (length xs))), \n  recf.id (Suc (Suc (Suc (length xs)))) (Suc (length xs))],\n  Cn (Suc (Suc (Suc (length xs)))) rec_not\n  [Cn (Suc (Suc (Suc (length xs)))) rf\n  (get_fstn_args (Suc (Suc (Suc (length xs)))) (length xs) @ \n  [recf.id (Suc (Suc (Suc (length xs)))) (Suc (Suc (length xs)))])]])]))\n  ((xs @ [w]) @ [w]) =\n       Maxr (\\<lambda>args. 0 < rec_exec rf args) xs w\"\nproof -\n  let ?rt = \"(recf.id (Suc (Suc (length xs))) ((length xs)))\"\n  let ?rf1 = \"Cn (Suc (Suc (Suc (length xs))))\n    rec_le [recf.id (Suc (Suc (Suc (length xs)))) \n    ((Suc (Suc (length xs)))), recf.id \n    (Suc (Suc (Suc (length xs)))) ((Suc (length xs)))]\"\n  let ?rf2 = \"Cn (Suc (Suc (Suc (length xs)))) rf \n               (get_fstn_args (Suc (Suc (Suc (length xs))))\n    (length xs) @ \n    [recf.id (Suc (Suc (Suc (length xs))))    \n    ((Suc (Suc (length xs))))])\"\n  let ?rf3 = \"Cn (Suc (Suc (Suc (length xs)))) rec_not [?rf2]\"\n  let ?rf = \"Cn (Suc (Suc (Suc (length xs)))) rec_disj [?rf1, ?rf3]\"\n  let ?rq = \"rec_all ?rt ?rf\"\n  let ?notrq = \"Cn (Suc (Suc (length xs))) rec_not [?rq]\"\n  show \"?thesis\"\n  proof(auto simp: Maxr.simps)\n    assume h: \"\\<forall>x\\<le>w. rec_exec rf (xs @ [x]) = 0\"\n    have \"primerec ?rf (Suc (length (xs @ [w, i]))) \\<and> \n          primerec ?rt (length (xs @ [w, i]))\"\n      using prrf\n      apply(auto dest!:less_2_cases[unfolded numeral_eqs_upto_12 One_nat_def])\n            apply force+\n      apply(case_tac ia, auto simp: h nth_append primerec_getpren)\n      done\n    hence \"Sigma (rec_exec ?notrq) ((xs@[w])@[w]) = 0\"\n      apply(rule_tac Sigma_0)\n      apply(auto simp: rec_exec.simps all_lemma\n          get_fstn_args_take nth_append h)\n      done\n    thus \"UF.Sigma (rec_exec ?notrq)\n      (xs @ [w, w]) = 0\"\n      by simp\n  next\n    fix x\n    assume h: \"x \\<le> w\" \"0 < rec_exec rf (xs @ [x])\"\n    hence \"\\<exists> ma. Max {y. y \\<le> w \\<and> 0 < rec_exec rf (xs @ [y])} = ma\"\n      by auto\n    from this obtain ma where k1: \n      \"Max {y. y \\<le> w \\<and> 0 < rec_exec rf (xs @ [y])} = ma\" ..\n    hence k2: \"ma \\<le> w \\<and> 0 < rec_exec rf (xs @ [ma])\"\n      using h\n      apply(subgoal_tac\n          \"Max {y. y \\<le> w \\<and> 0 < rec_exec rf (xs @ [y])} \\<in>  {y. y \\<le> w \\<and> 0 < rec_exec rf (xs @ [y])}\")\n       apply(erule_tac CollectE, simp)\n      apply(rule_tac Max_in, auto)\n      done\n    hence k3: \"\\<forall> k < ma. (rec_exec ?notrq (xs @ [w, k]) = 1)\"\n      apply(auto simp: nth_append)\n      apply(subgoal_tac \"primerec ?rf (Suc (length (xs @ [w, k]))) \\<and> \n        primerec ?rt (length (xs @ [w, k]))\")\n       apply(auto simp: rec_exec.simps all_lemma get_fstn_args_take nth_append\n          dest!:less_2_cases[unfolded numeral_eqs_upto_12 One_nat_def])\n      using prrf\n            apply force+\n      done    \n    have k4: \"\\<forall> k \\<ge> ma. (rec_exec ?notrq (xs @ [w, k]) = 0)\"\n      apply(auto)\n      apply(subgoal_tac \"primerec ?rf (Suc (length (xs @ [w, k]))) \\<and> \n        primerec ?rt (length (xs @ [w, k]))\")\n       apply(auto simp: rec_exec.simps all_lemma get_fstn_args_take nth_append)\n       apply(subgoal_tac \"x \\<le> Max {y. y \\<le> w \\<and> 0 < rec_exec rf (xs @ [y])}\",\n          simp add: k1)\n       apply(rule_tac Max_ge, auto dest!:less_2_cases[unfolded numeral_eqs_upto_12 One_nat_def])\n      using prrf apply force+\n      apply(auto simp: h nth_append)\n      done \n    from k3 k4 k1 have \"Sigma (rec_exec ?notrq) ((xs @ [w]) @ [w]) = ma\"\n      apply(rule_tac Sigma_max_point, simp, simp, simp add: k2)\n      done\n    from k1 and this show \"Sigma (rec_exec ?notrq) (xs @ [w, w]) =\n      Max {y. y \\<le> w \\<and> 0 < rec_exec rf (xs @ [y])}\"\n      by simp\n  qed  \nqed\n\ntext \\<open>\n  The correctness of \\<open>rec_maxr\\<close>.\n\\<close>\nlemma Maxr_lemma:\n  assumes h: \"primerec rf (Suc (length xs))\"\n  shows   \"rec_exec (rec_maxr rf) (xs @ [w]) = \n            Maxr (\\<lambda> args. 0 < rec_exec rf args) xs w\"\nproof -\n  from h have \"arity rf = Suc (length xs)\"\n    by auto\n  thus \"?thesis\"\n  proof(simp add: rec_exec.simps rec_maxr.simps nth_append get_fstn_args_take)\n    let ?rt = \"(recf.id (Suc (Suc (length xs))) ((length xs)))\"\n    let ?rf1 = \"Cn (Suc (Suc (Suc (length xs))))\n                     rec_le [recf.id (Suc (Suc (Suc (length xs)))) \n              ((Suc (Suc (length xs)))), recf.id \n             (Suc (Suc (Suc (length xs)))) ((Suc (length xs)))]\"\n    let ?rf2 = \"Cn (Suc (Suc (Suc (length xs)))) rf \n               (get_fstn_args (Suc (Suc (Suc (length xs))))\n                (length xs) @ \n                  [recf.id (Suc (Suc (Suc (length xs))))    \n                           ((Suc (Suc (length xs))))])\"\n    let ?rf3 = \"Cn (Suc (Suc (Suc (length xs)))) rec_not [?rf2]\"\n    let ?rf = \"Cn (Suc (Suc (Suc (length xs)))) rec_disj [?rf1, ?rf3]\"\n    let ?rq = \"rec_all ?rt ?rf\"\n    let ?notrq = \"Cn (Suc (Suc (length xs))) rec_not [?rq]\"\n    have prt: \"primerec ?rt (Suc (Suc (length xs)))\"\n      by(auto intro: prime_id)\n    have prrf: \"primerec ?rf (Suc (Suc (Suc (length xs))))\"\n      apply(auto dest!:less_2_cases[unfolded numeral_eqs_upto_12 One_nat_def])\n            apply force+\n        apply(auto intro: prime_id)\n       apply(simp add: h)\n      apply(auto simp add: nth_append)\n      done\n    from prt and prrf have prrq: \"primerec ?rq \n                                       (Suc (Suc (length xs)))\"\n      by(erule_tac primerec_all_iff, auto)\n    hence prnotrp: \"primerec ?notrq (Suc (length ((xs @ [w]))))\"\n      by(rule_tac prime_cn, auto)\n    have g1: \"rec_exec (rec_sigma ?notrq) ((xs @ [w]) @ [w]) \n      = Maxr (\\<lambda>args. 0 < rec_exec rf args) xs w\"\n      using prnotrp\n      using sigma_lemma\n      apply(simp only: sigma_lemma)\n      apply(rule_tac Sigma_Max_lemma)\n      apply(simp add: h)\n      done\n    thus \"rec_exec (rec_sigma ?notrq)\n     (xs @ [w, w]) =\n    Maxr (\\<lambda>args. 0 < rec_exec rf args) xs w\"\n      apply(simp)\n      done\n  qed\nqed\n\n\nsubsection \\<open>The Recursive Function rec\\_noteq\\<close>\n\ntext \\<open>\n  \\<open>rec_noteq\\<close> is the recursive function testing whether its\n  two arguments are not equal.\n\\<close>\ndefinition rec_noteq:: \"recf\"\n  where\n    \"rec_noteq = Cn (Suc (Suc 0)) rec_not [Cn (Suc (Suc 0)) \n              rec_eq [id (Suc (Suc 0)) (0), id (Suc (Suc 0)) \n                                        ((Suc 0))]]\"\ntext \\<open>\n  The correctness of \\<open>rec_noteq\\<close>.\n\\<close>\nlemma noteq_lemma: \n  \"\\<And> x y. rec_exec rec_noteq [x, y] = \n               (if x \\<noteq> y then 1 else 0)\"\n  by(simp add: rec_exec.simps rec_noteq_def)\n\ndeclare noteq_lemma[simp]\n\nsubsection \\<open>The Recursive Function rec\\_quo\\<close>\n\ntext \\<open>\n  \\<open>quo\\<close> is the formal specification of division.\n\\<close>\nfun quo :: \"nat list \\<Rightarrow> nat\"\n  where\n    \"quo [x, y] = (let Rr = \n                         (\\<lambda> zs. ((zs ! (Suc 0) * zs ! (Suc (Suc 0))\n                                 \\<le> zs ! 0) \\<and> zs ! Suc 0 \\<noteq> (0::nat)))\n                 in Maxr Rr [x, y] x)\"\n\ndeclare quo.simps[simp del]\n\ntext \\<open>\n  The following lemmas shows more directly the meaning of \\<open>quo\\<close>:\n\\<close>\nlemma quo_is_div: \"y > 0 \\<Longrightarrow> quo [x, y] = x div y\"\nproof -\n  {\n    fix xa ya\n    assume h: \"y * ya \\<le> x\"  \"y > 0\"\n    hence \"(y * ya) div y \\<le> x div y\"\n      by(insert div_le_mono[of \"y * ya\" x y], simp)\n    from this and h have \"ya \\<le> x div y\" by simp}\n  thus ?thesis by(simp add: quo.simps Maxr.simps, auto,\n        rule_tac Max_eqI, simp, auto)\nqed\n\nlemma quo_zero[intro]: \"quo [x, 0] = 0\"\n  by(simp add: quo.simps Maxr.simps)\n\nlemma quo_div: \"quo [x, y] = x div y\"  \n  by(cases \"y=0\", auto elim!:quo_is_div)\n\ntext \\<open>\n  \\<open>rec_quo\\<close> is the recursive function used to implement \\<open>quo\\<close>\n\\<close>\ndefinition rec_quo :: \"recf\"\n  where\n    \"rec_quo = (let rR = Cn (Suc (Suc (Suc 0))) rec_conj\n              [Cn (Suc (Suc (Suc 0))) rec_le \n               [Cn (Suc (Suc (Suc 0))) rec_mult \n                  [id (Suc (Suc (Suc 0))) (Suc 0), \n                     id (Suc (Suc (Suc 0))) ((Suc (Suc 0)))],\n                id (Suc (Suc (Suc 0))) (0)], \n                Cn (Suc (Suc (Suc 0))) rec_noteq \n                         [id (Suc (Suc (Suc 0))) (Suc (0)),\n                Cn (Suc (Suc (Suc 0))) (constn 0) \n                              [id (Suc (Suc (Suc 0))) (0)]]] \n              in Cn (Suc (Suc 0)) (rec_maxr rR)) [id (Suc (Suc 0)) \n                           (0),id (Suc (Suc 0)) (Suc (0)), \n                                   id (Suc (Suc 0)) (0)]\"\n\nlemma primerec_rec_conj_2[intro]: \"primerec rec_conj (Suc (Suc 0))\"\n  apply(simp add: rec_conj_def)\n  apply(rule_tac prime_cn, auto dest!:less_2_cases[unfolded numeral_eqs_upto_12 One_nat_def])\n  done\n\nlemma primerec_rec_noteq_2[intro]: \"primerec rec_noteq (Suc (Suc 0))\"\n  apply(simp add: rec_noteq_def)\n  apply(rule_tac prime_cn, auto dest!:less_2_cases[unfolded numeral_eqs_upto_12 One_nat_def])\n  done\n\n\nlemma quo_lemma1: \"rec_exec rec_quo [x, y] = quo [x, y]\"\nproof(simp add: rec_exec.simps rec_quo_def)\n  let ?rR = \"(Cn (Suc (Suc (Suc 0))) rec_conj\n               [Cn (Suc (Suc (Suc 0))) rec_le\n                   [Cn (Suc (Suc (Suc 0))) rec_mult \n               [recf.id (Suc (Suc (Suc 0))) (Suc (0)), \n                recf.id (Suc (Suc (Suc 0))) (Suc (Suc (0)))],\n                 recf.id (Suc (Suc (Suc 0))) (0)],  \n          Cn (Suc (Suc (Suc 0))) rec_noteq \n                              [recf.id (Suc (Suc (Suc 0))) \n             (Suc (0)), Cn (Suc (Suc (Suc 0))) (constn 0) \n                      [recf.id (Suc (Suc (Suc 0))) (0)]]])\"\n  have \"rec_exec (rec_maxr ?rR) ([x, y]@ [ x]) = Maxr (\\<lambda> args. 0 < rec_exec ?rR args) [x, y] x\"\n  proof(rule_tac Maxr_lemma, simp)\n    show \"primerec ?rR (Suc (Suc (Suc 0)))\"\n      apply(auto dest!:less_2_cases[unfolded numeral_eqs_upto_12 One_nat_def]) \n             apply force+\n      done\n  qed\n  hence g1: \"rec_exec (rec_maxr ?rR) ([x, y,  x]) =\n             Maxr (\\<lambda> args. if rec_exec ?rR args = 0 then False\n                           else True) [x, y] x\" \n    by simp\n  have g2: \"Maxr (\\<lambda> args. if rec_exec ?rR args = 0 then False\n                           else True) [x, y] x = quo [x, y]\"\n    apply(simp add: rec_exec.simps)\n    apply(simp add: Maxr.simps quo.simps, auto)\n    done\n  from g1 and g2 show \n    \"rec_exec (rec_maxr ?rR) ([x, y,  x]) = quo [x, y]\"\n    by simp\nqed\n\ntext \\<open>\n  The correctness of \\<open>quo\\<close>.\n\\<close>\nlemma quo_lemma2: \"rec_exec rec_quo [x, y] = x div y\"\n  using quo_lemma1[of x y] quo_div[of x y]\n  by simp\n\nsubsection \\<open>The Recursive Function rec\\_mod\\<close>\n\ntext \\<open>\n  \\<open>rec_mod\\<close> is the recursive function used to implement \n  the reminder function.\n\\<close>\ndefinition rec_mod :: \"recf\"\n  where\n    \"rec_mod = Cn (Suc (Suc 0)) rec_minus [id (Suc (Suc 0)) (0), \n               Cn (Suc (Suc 0)) rec_mult [rec_quo, id (Suc (Suc 0))\n                                                     (Suc (0))]]\"\ntext \\<open>\n  The correctness of \\<open>rec_mod\\<close>:\n\\<close>\nlemma mod_lemma: \"\\<And> x y. rec_exec rec_mod [x, y] = (x mod y)\"\n  by(simp add: rec_exec.simps rec_mod_def quo_lemma2 minus_div_mult_eq_mod)\n\nsubsection \\<open>The Recursive Function rec\\_embranch\\<close>\n\ntext\\<open>lemmas for embranch function\\<close>\n\ntype_synonym ftype = \"nat list \\<Rightarrow> nat\"\ntype_synonym rtype = \"nat list \\<Rightarrow> bool\"\n\ntext \\<open>\n  The specifcation of the multi-way branching statement (definition by cases).\n  See page 74 of Boolos's book~\\<^cite>\\<open>\"Boolos07\"\\<close>.\n\\<close>\nfun Embranch :: \"(ftype * rtype) list \\<Rightarrow> nat list \\<Rightarrow> nat\"\n  where\n    \"Embranch [] xs = 0\" |\n    \"Embranch (gc # gcs) xs = (\n                   let (g, c) = gc in \n                   if c xs then g xs else Embranch gcs xs)\"\n\nfun rec_embranch' :: \"(recf * recf) list \\<Rightarrow> nat \\<Rightarrow> recf\"\n  where\n    \"rec_embranch' [] vl = Cn vl z [id vl (vl - 1)]\" |\n    \"rec_embranch' ((rg, rc) # rgcs) vl = Cn vl rec_add\n                   [Cn vl rec_mult [rg, rc], rec_embranch' rgcs vl]\"\n\ntext \\<open>\n  \\<open>rec_embrach\\<close> is the recursive function used to implement\n  \\<open>Embranch\\<close>.\n\\<close>\nfun rec_embranch :: \"(recf * recf) list \\<Rightarrow> recf\"\n  where\n    \"rec_embranch ((rg, rc) # rgcs) = \n         (let vl = arity rg in \n          rec_embranch' ((rg, rc) # rgcs) vl)\"\n\ndeclare Embranch.simps[simp del] rec_embranch.simps[simp del]\n\nlemma embranch_all0: \n  \"\\<lbrakk>\\<forall> j < length rcs. rec_exec (rcs ! j) xs = 0;\n    length rgs = length rcs;  \n  rcs \\<noteq> []; \n  list_all (\\<lambda> rf. primerec rf (length xs)) (rgs @ rcs)\\<rbrakk>  \\<Longrightarrow> \n  rec_exec (rec_embranch (zip rgs rcs)) xs = 0\"\nproof(induct rcs arbitrary: rgs)\n  case (Cons a rcs)\n  then show ?case proof(cases rgs, simp)  fix a rcs rgs aa list\n    assume ind: \n      \"\\<And>rgs. \\<lbrakk>\\<forall>j<length rcs. rec_exec (rcs ! j) xs = 0; \n             length rgs = length rcs; rcs \\<noteq> []; \n            list_all (\\<lambda>rf. primerec rf (length xs)) (rgs @ rcs)\\<rbrakk> \\<Longrightarrow> \n                      rec_exec (rec_embranch (zip rgs rcs)) xs = 0\"\n      and h:  \"\\<forall>j<length (a # rcs). rec_exec ((a # rcs) ! j) xs = 0\"\n      \"length rgs = length (a # rcs)\" \n      \"a # rcs \\<noteq> []\" \n      \"list_all (\\<lambda>rf. primerec rf (length xs)) (rgs @ a # rcs)\"\n      \"rgs = aa # list\"\n    have g: \"rcs \\<noteq> [] \\<Longrightarrow> rec_exec (rec_embranch (zip list rcs)) xs = 0\"\n      using h by(rule_tac ind, auto)\n    show \"rec_exec (rec_embranch (zip rgs (a # rcs))) xs = 0\"\n    proof(cases \"rcs = []\", simp)\n      show \"rec_exec (rec_embranch (zip rgs [a])) xs = 0\"\n        using h by (auto simp add: rec_embranch.simps rec_exec.simps)\n    next\n      assume \"rcs \\<noteq> []\"\n      hence \"rec_exec (rec_embranch (zip list rcs)) xs = 0\"\n        using g by simp\n      thus \"rec_exec (rec_embranch (zip rgs (a # rcs))) xs = 0\"\n        using h\n        by(cases rcs;cases list, auto simp add: rec_embranch.simps rec_exec.simps)\n    qed\n  qed\nqed simp\n\n\nlemma embranch_exec_0: \"\\<lbrakk>rec_exec aa xs = 0; zip rgs list \\<noteq> []; \n       list_all (\\<lambda> rf. primerec rf (length xs)) ([a, aa] @ rgs @ list)\\<rbrakk>\n       \\<Longrightarrow> rec_exec (rec_embranch ((a, aa) # zip rgs list)) xs\n         = rec_exec (rec_embranch (zip rgs list)) xs\"\n  apply(auto simp add: rec_exec.simps rec_embranch.simps)\n  apply(cases \"zip rgs list\", force)\n  apply(cases \"hd (zip rgs list)\", simp add: rec_embranch.simps rec_exec.simps)\n  apply(subgoal_tac \"arity a = length xs\")\n   apply(cases rgs;cases list;force)\n  by force\n\nlemma zip_null_iff: \"\\<lbrakk>length xs = k; length ys = k; zip xs ys = []\\<rbrakk> \\<Longrightarrow> xs = [] \\<and> ys = []\"\n  apply(cases xs, simp, simp)\n  done\n\nlemma zip_null_gr: \"\\<lbrakk>length xs = k; length ys = k; zip xs ys \\<noteq> []\\<rbrakk> \\<Longrightarrow> 0 < k\"\n  apply(cases xs, simp, simp)\n  done\n\nlemma Embranch_0:  \n  \"\\<lbrakk>length rgs = k; length rcs = k; k > 0; \n  \\<forall> j < k. rec_exec (rcs ! j) xs = 0\\<rbrakk> \\<Longrightarrow>\n  Embranch (zip (map rec_exec rgs) (map (\\<lambda>r args. 0 < rec_exec r args) rcs)) xs = 0\"\nproof(induct rgs arbitrary: rcs k)\n  case (Cons a rgs rcs k)\n  then show ?case\n    apply(cases rcs, simp, cases \"rgs = []\")\n     apply(simp add: Embranch.simps)\n     apply(erule_tac x = 0 in allE)\n     apply (auto simp add: Embranch.simps intro!: Cons(1)).\nqed simp\n\ntext \\<open>\n  The correctness of \\<open>rec_embranch\\<close>.\n\\<close>\nlemma embranch_lemma:\n  assumes branch_num:\n    \"length rgs = n\" \"length rcs = n\" \"n > 0\"\n    and partition: \n    \"(\\<exists> i < n. (rec_exec (rcs ! i) xs = 1 \\<and> (\\<forall> j < n. j \\<noteq> i \\<longrightarrow> \n                                      rec_exec (rcs ! j) xs = 0)))\"\n    and prime_all: \"list_all (\\<lambda> rf. primerec rf (length xs)) (rgs @ rcs)\"\n  shows \"rec_exec (rec_embranch (zip rgs rcs)) xs =\n                  Embranch (zip (map rec_exec rgs) \n                     (map (\\<lambda> r args. 0 < rec_exec r args) rcs)) xs\"\n  using branch_num partition prime_all\nproof(induct rgs arbitrary: rcs n, simp)\n  fix a rgs rcs n\n  assume ind: \n    \"\\<And>rcs n. \\<lbrakk>length rgs = n; length rcs = n; 0 < n;\n    \\<exists>i<n. rec_exec (rcs ! i) xs = 1 \\<and> (\\<forall>j<n. j \\<noteq> i \\<longrightarrow> rec_exec (rcs ! j) xs = 0);\n    list_all (\\<lambda>rf. primerec rf (length xs)) (rgs @ rcs)\\<rbrakk>\n    \\<Longrightarrow> rec_exec (rec_embranch (zip rgs rcs)) xs =\n    Embranch (zip (map rec_exec rgs) (map (\\<lambda>r args. 0 < rec_exec r args) rcs)) xs\"\n    and h: \"length (a # rgs) = n\" \"length (rcs::recf list) = n\" \"0 < n\"\n    \" \\<exists>i<n. rec_exec (rcs ! i) xs = 1 \\<and> \n         (\\<forall>j<n. j \\<noteq> i \\<longrightarrow> rec_exec (rcs ! j) xs = 0)\" \n    \"list_all (\\<lambda>rf. primerec rf (length xs)) ((a # rgs) @ rcs)\"\n  from h show \"rec_exec (rec_embranch (zip (a # rgs) rcs)) xs =\n    Embranch (zip (map rec_exec (a # rgs)) (map (\\<lambda>r args. \n                0 < rec_exec r args) rcs)) xs\"\n    apply(cases rcs, simp, simp)\n    apply(cases \"rec_exec (hd rcs) xs = 0\")\n     apply(case_tac [!] \"zip rgs (tl rcs) = []\", simp)\n       apply(subgoal_tac \"rgs = [] \\<and> (tl rcs) = []\", simp add: Embranch.simps rec_exec.simps rec_embranch.simps)\n       apply(rule_tac  zip_null_iff, simp, simp, simp)\n  proof -\n    fix aa list\n    assume \"rcs = aa # list\"\n    assume g:\n      \"Suc (length rgs) = n\" \"Suc (length list) = n\" \n      \"\\<exists>i<n. rec_exec ((aa # list) ! i) xs = Suc 0 \\<and> \n          (\\<forall>j<n. j \\<noteq> i \\<longrightarrow> rec_exec ((aa # list) ! j) xs = 0)\"\n      \"primerec a (length xs) \\<and> \n      list_all (\\<lambda>rf. primerec rf (length xs)) rgs \\<and>\n      primerec aa (length xs) \\<and> \n      list_all (\\<lambda>rf. primerec rf (length xs)) list\"\n      \"rec_exec (hd rcs) xs = 0\" \"rcs = aa # list\" \"zip rgs (tl rcs) \\<noteq> []\"\n    hence \"rec_exec aa xs = 0\" \"zip rgs list \\<noteq> []\" by auto\n    note g = g(1,2,3,4,6,7) this\n    hence \"rec_exec (rec_embranch ((a, aa) # zip rgs list)) xs\n        = rec_exec (rec_embranch (zip rgs list)) xs\"\n      by(simp add: embranch_exec_0)\n    from g and this show \"rec_exec (rec_embranch ((a, aa) # zip rgs list)) xs =\n         Embranch ((rec_exec a, \\<lambda>args. 0 < rec_exec aa args) # \n           zip (map rec_exec rgs) (map (\\<lambda>r args. 0 < rec_exec r args) list)) xs\"\n      apply(simp add: Embranch.simps)\n      apply(rule_tac n = \"n - Suc 0\" in ind)\n          apply(cases n;force)\n         apply(cases n;force)\n        apply(cases n;force simp add: zip_null_gr)\n       apply(auto)\n      apply(rename_tac i)\n      apply(case_tac i, force, simp)\n      apply(rule_tac x = \"i - 1\" in exI, simp)\n      by auto\n  next\n    fix aa list\n    assume g: \"Suc (length rgs) = n\" \"Suc (length list) = n\"\n      \"\\<exists>i<n. rec_exec ((aa # list) ! i) xs = Suc 0 \\<and> \n      (\\<forall>j<n. j \\<noteq> i \\<longrightarrow> rec_exec ((aa # list) ! j) xs = 0)\"\n      \"primerec a (length xs) \\<and> list_all (\\<lambda>rf. primerec rf (length xs)) rgs \\<and>\n      primerec aa (length xs) \\<and> list_all (\\<lambda>rf. primerec rf (length xs)) list\"\n      \"rcs = aa # list\" \"rec_exec (hd rcs) xs \\<noteq> 0\" \"zip rgs (tl rcs) = []\"\n    thus \"rec_exec (rec_embranch ((a, aa) # zip rgs list)) xs = \n        Embranch ((rec_exec a, \\<lambda>args. 0 < rec_exec aa args) # \n       zip (map rec_exec rgs) (map (\\<lambda>r args. 0 < rec_exec r args) list)) xs\"\n      apply(subgoal_tac \"rgs = [] \\<and> list = []\", simp)\n       prefer 2\n       apply(rule_tac zip_null_iff, simp, simp, simp)\n      apply(simp add: rec_exec.simps rec_embranch.simps Embranch.simps, auto)\n      done\n  next\n    fix aa list\n    assume g: \"Suc (length rgs) = n\" \"Suc (length list) = n\"\n      \"\\<exists>i<n. rec_exec ((aa # list) ! i) xs = Suc 0 \\<and>  \n           (\\<forall>j<n. j \\<noteq> i \\<longrightarrow> rec_exec ((aa # list) ! j) xs = 0)\"\n      \"primerec a (length xs) \\<and> list_all (\\<lambda>rf. primerec rf (length xs)) rgs\n      \\<and> primerec aa (length xs) \\<and> list_all (\\<lambda>rf. primerec rf (length xs)) list\"\n      \"rcs = aa # list\" \"rec_exec (hd rcs) xs \\<noteq> 0\" \"zip rgs (tl rcs) \\<noteq> []\"\n    have \"rec_exec aa xs =  Suc 0\"\n      using g\n      apply(cases \"rec_exec aa xs\", simp, auto)\n      done      \n    moreover have \"rec_exec (rec_embranch' (zip rgs list) (length xs)) xs = 0\"\n    proof -\n      have \"rec_embranch' (zip rgs list) (length xs) = rec_embranch (zip rgs list)\"\n        using g\n        apply(cases \"zip rgs list\", force)\n        apply(cases \"hd (zip rgs list)\")\n        apply(simp add: rec_embranch.simps)\n        apply(cases rgs, simp, simp, cases list, simp, auto)\n        done\n      moreover have \"rec_exec (rec_embranch (zip rgs list)) xs = 0\"\n      proof(rule embranch_all0)\n        show \" \\<forall>j<length list. rec_exec (list ! j) xs = 0\"\n          using g\n          apply(auto)\n          apply(rename_tac i j)\n          apply(case_tac i, simp)\n           apply(erule_tac x = \"Suc j\" in allE, simp)\n          apply(simp)\n          apply(erule_tac x = 0 in allE, simp)\n          done\n      next\n        show \"length rgs = length list\"\n          using g by(cases n;force)\n      next\n        show \"list \\<noteq> []\"\n          using g by(cases list; force)\n      next\n        show \"list_all (\\<lambda>rf. primerec rf (length xs)) (rgs @ list)\"\n          using g by auto\n      qed\n      ultimately show \"rec_exec (rec_embranch' (zip rgs list) (length xs)) xs = 0\"\n        by simp\n    qed\n    moreover have \n      \"Embranch (zip (map rec_exec rgs) \n          (map (\\<lambda>r args. 0 < rec_exec r args) list)) xs = 0\"\n      using g\n      apply(rule_tac k = \"length rgs\" in Embranch_0)\n         apply(simp, cases n, simp, simp)\n       apply(cases rgs, simp, simp)\n      apply(auto)\n      apply(rename_tac i j)\n      apply(case_tac i, simp)\n       apply(erule_tac x = \"Suc j\" in allE, simp)\n      apply(simp)\n      apply(rule_tac x = 0 in allE, auto)\n      done\n    moreover have \"arity a = length xs\"\n      using g\n      apply(auto)\n      done\n    ultimately show \"rec_exec (rec_embranch ((a, aa) # zip rgs list)) xs = \n      Embranch ((rec_exec a, \\<lambda>args. 0 < rec_exec aa args) #\n           zip (map rec_exec rgs) (map (\\<lambda>r args. 0 < rec_exec r args) list)) xs\"\n      apply(simp add: rec_exec.simps rec_embranch.simps Embranch.simps)\n      done\n  qed\nqed\n\nsubsection \\<open>The Recursive Function rec\\_prime\\<close>\n\ntext\\<open>\n  \\<open>prime n\\<close> means \\<open>n\\<close> is a prime number.\n\\<close>\nfun Prime :: \"nat \\<Rightarrow> bool\"\n  where\n    \"Prime x = (1 < x \\<and> (\\<forall> u < x. (\\<forall> v < x. u * v \\<noteq> x)))\"\n\ndeclare Prime.simps [simp del]\n\nlemma primerec_all1: \n  \"primerec (rec_all rt rf) n \\<Longrightarrow> primerec rt n\"\n  by (simp add: primerec_all)\n\nlemma primerec_all2: \"primerec (rec_all rt rf) n \\<Longrightarrow> \n  primerec rf (Suc n)\"\n  by(insert primerec_all[of rt rf n], simp)\n\ntext \\<open>\n  \\<open>rec_prime\\<close> is the recursive function used to implement\n  \\<open>Prime\\<close>.\n\\<close>\ndefinition rec_prime :: \"recf\"\n  where\n    \"rec_prime = Cn (Suc 0) rec_conj \n  [Cn (Suc 0) rec_less [constn 1, id (Suc 0) (0)],\n        rec_all (Cn 1 rec_minus [id 1 0, constn 1]) \n       (rec_all (Cn 2 rec_minus [id 2 0, Cn 2 (constn 1) \n  [id 2 0]]) (Cn 3 rec_noteq \n       [Cn 3 rec_mult [id 3 1, id 3 2], id 3 0]))]\"\n\ndeclare numeral_2_eq_2[simp del] numeral_3_eq_3[simp del]\n\nlemma exec_tmp: \n  \"rec_exec (rec_all (Cn 2 rec_minus [recf.id 2 0, Cn 2 (constn (Suc 0)) [recf.id 2 0]]) \n  (Cn 3 rec_noteq [Cn 3 rec_mult [recf.id 3 (Suc 0), recf.id 3 2], recf.id 3 0]))  [x, k] = \n  ((if (\\<forall>w\\<le>rec_exec (Cn 2 rec_minus [recf.id 2 0, Cn 2 (constn (Suc 0)) [recf.id 2 0]]) ([x, k]). \n  0 < rec_exec (Cn 3 rec_noteq [Cn 3 rec_mult [recf.id 3 (Suc 0), recf.id 3 2], recf.id 3 0])\n  ([x, k] @ [w])) then 1 else 0))\"\n  apply(rule_tac all_lemma)\n   apply(auto simp:numeral_eqs_upto_12)\n   apply (metis (no_types, lifting) Suc_mono length_Cons less_2_cases list.size(3) nth_Cons_0\n      nth_Cons_Suc numeral_2_eq_2 prime_cn prime_id primerec_rec_mult_2 zero_less_Suc)\n  by (metis (no_types, lifting) One_nat_def length_Cons less_2_cases nth_Cons_0 nth_Cons_Suc \n      prime_cn_reverse primerec_rec_eq_2 rec_eq_def zero_less_Suc)\n\ntext \\<open>\n  The correctness of \\<open>Prime\\<close>.\n\\<close>\nlemma prime_lemma: \"rec_exec rec_prime [x] = (if Prime x then 1 else 0)\"\nproof(simp add: rec_exec.simps rec_prime_def)\n  let ?rt1 = \"(Cn 2 rec_minus [recf.id 2 0, \n    Cn 2 (constn (Suc 0)) [recf.id 2 0]])\"\n  let ?rf1 = \"(Cn 3 rec_noteq [Cn 3 rec_mult \n    [recf.id 3 (Suc 0), recf.id 3 2], recf.id 3 (0)])\"\n  let ?rt2 = \"(Cn (Suc 0) rec_minus \n    [recf.id (Suc 0) 0, constn (Suc 0)])\"\n  let ?rf2 = \"rec_all ?rt1 ?rf1\"\n  have h1: \"rec_exec (rec_all ?rt2 ?rf2) ([x]) = \n        (if (\\<forall>k\\<le>rec_exec ?rt2 ([x]). 0 < rec_exec ?rf2 ([x] @ [k])) then 1 else 0)\"\n  proof(rule_tac all_lemma, simp_all)\n    show \"primerec ?rf2 (Suc (Suc 0))\"\n      apply(rule_tac primerec_all_iff)\n        apply(auto simp: numeral_eqs_upto_12)\n       apply (metis (no_types, lifting) One_nat_def length_Cons less_2_cases nth_Cons_0 nth_Cons_Suc\n          prime_cn_reverse primerec_rec_eq_2 rec_eq_def zero_less_Suc)\n      by (metis (no_types, lifting) Suc_mono length_Cons less_2_cases list.size(3) nth_Cons_0 \n          nth_Cons_Suc numeral_2_eq_2 prime_cn prime_id primerec_rec_mult_2 zero_less_Suc)\n  next\n    show \"primerec (Cn (Suc 0) rec_minus\n             [recf.id (Suc 0) 0, constn (Suc 0)]) (Suc 0)\"\n      using less_2_cases numeral_eqs_upto_12 by fastforce\n  qed\n  from h1 show \n    \"(Suc 0 < x \\<longrightarrow>  (rec_exec (rec_all ?rt2 ?rf2) [x] = 0 \\<longrightarrow> \n    \\<not> Prime x) \\<and>\n     (0 < rec_exec (rec_all ?rt2 ?rf2) [x] \\<longrightarrow> Prime x)) \\<and>\n    (\\<not> Suc 0 < x \\<longrightarrow> \\<not> Prime x \\<and> (rec_exec (rec_all ?rt2 ?rf2) [x] = 0\n    \\<longrightarrow> \\<not> Prime x))\"\n    apply(auto simp:rec_exec.simps)\n       apply(simp add: exec_tmp rec_exec.simps)\n  proof -\n    assume *:\"\\<forall>k\\<le>x - Suc 0. (0::nat) < (if \\<forall>w\\<le>x - Suc 0. \n           0 < (if k * w \\<noteq> x then 1 else (0 :: nat)) then 1 else 0)\" \"Suc 0 < x\"\n    thus \"Prime x\"\n      apply(simp add: rec_exec.simps split: if_splits)\n      apply(simp add: Prime.simps, auto)\n      apply(rename_tac u v)\n      apply(erule_tac x = u in allE, auto)\n       apply(case_tac u, simp)\n       apply(case_tac \"u - 1\", simp, simp)\n      apply(case_tac v, simp)\n      apply(case_tac \"v - 1\", simp, simp)\n      done\n  next\n    assume \"\\<not> Suc 0 < x\" \"Prime x\"\n    thus \"False\"\n      apply(simp add: Prime.simps)\n      done\n  next\n    fix k\n    assume \"rec_exec (rec_all ?rt1 ?rf1)\n      [x, k] = 0\" \"k \\<le> x - Suc 0\" \"Prime x\"\n    thus \"False\"\n      apply(simp add: exec_tmp rec_exec.simps Prime.simps split: if_splits)\n      done\n  next\n    fix k\n    assume \"rec_exec (rec_all ?rt1 ?rf1)\n      [x, k] = 0\" \"k \\<le> x - Suc 0\" \"Prime x\"\n    thus \"False\"\n      apply(simp add: exec_tmp rec_exec.simps Prime.simps split: if_splits)\n      done\n  qed\nqed\n\nsubsection \\<open>The Recursive Function rec\\_fac for factorization\\<close>\n\ndefinition rec_dummyfac :: \"recf\"\n  where\n    \"rec_dummyfac = Pr 1 (constn 1) \n  (Cn 3 rec_mult [id 3 2, Cn 3 s [id 3 1]])\"\n\ntext \\<open>\n  The recursive function used to implement factorization.\n\\<close>\ndefinition rec_fac :: \"recf\"\n  where\n    \"rec_fac = Cn 1 rec_dummyfac [id 1 0, id 1 0]\"\n\ntext \\<open>\n  Formal specification of factorization.\n\\<close>\nfun fac :: \"nat \\<Rightarrow> nat\"  (\"_!\" [100] 99)\n  where\n    \"fac 0 = 1\" |\n    \"fac (Suc x) = (Suc x) * fac x\"\n\n\n\ntext \\<open>\n  The correctness of \\<open>rec_fac\\<close>.\n\\<close>\n\nlemma fac_lemma: \"rec_exec rec_fac [x] =  x!\"\n  apply(simp add: rec_fac_def rec_exec.simps fac_dummy)\n  done\n\n\ndeclare fac.simps[simp del]\n\nsubsection \\<open>The Recursive Function rec\\_np for finding the next prime\\<close>\n\ntext \\<open>\n  \\<open>Np x\\<close> returns the first prime number after \\<open>x\\<close>.\n\\<close>\nfun Np ::\"nat \\<Rightarrow> nat\"\n  where\n    \"Np x = Min {y. y \\<le> Suc (x!) \\<and> x < y \\<and> Prime y}\"\n\ndeclare Np.simps[simp del] rec_Minr.simps[simp del]\n\ntext \\<open>\n  \\<open>rec_np\\<close> is the recursive function used to implement\n  \\<open>Np\\<close>.\n\\<close>\ndefinition rec_np :: \"recf\"\n  where\n    \"rec_np = (let Rr = Cn 2 rec_conj [Cn 2 rec_less [id 2 0, id 2 1], \n  Cn 2 rec_prime [id 2 1]]\n             in Cn 1 (rec_Minr Rr) [id 1 0, Cn 1 s [rec_fac]])\"\n\nlemma n_le_fact[simp]: \"n < Suc (n!)\"\nproof(induct n)\n  case (Suc n)\n  then show ?case  apply(simp add: fac.simps)\n    apply(cases n, auto simp: fac.simps)\n    done\nqed simp\n\nlemma divsor_ex: \n  \"\\<lbrakk>\\<not> Prime x; x > Suc 0\\<rbrakk> \\<Longrightarrow> (\\<exists> u > Suc 0. (\\<exists> v > Suc 0. u * v = x))\"\n  by(auto simp: Prime.simps)\n\nlemma divsor_prime_ex: \"\\<lbrakk>\\<not> Prime x; x > Suc 0\\<rbrakk> \\<Longrightarrow> \n  \\<exists> p. Prime p \\<and> p dvd x\"\n  apply(induct x rule: wf_induct[where r = \"measure (\\<lambda> y. y)\"], simp)\n  apply(drule_tac divsor_ex, simp, auto)\n  apply(rename_tac u v)\n  apply(erule_tac x = u in allE, simp)\n  apply(case_tac \"Prime u\", simp)\n   apply(rule_tac x = u in exI, simp, auto)\n  done\n\nlemma fact_pos[intro]: \"0 < n!\"\n  apply(induct n)\n   apply(auto simp: fac.simps)\n  done\n\nlemma fac_Suc: \"Suc n! =  (Suc n) * (n!)\" by(simp add: fac.simps)\n\nlemma fac_dvd: \"\\<lbrakk>0 < q; q \\<le> n\\<rbrakk> \\<Longrightarrow> q dvd n!\"\nproof(induct n)\n  case (Suc n)\n  then show ?case \n    apply(cases \"q \\<le> n\", simp add: fac_Suc)\n    apply(subgoal_tac \"q = Suc n\", simp only: fac_Suc)\n     apply(rule_tac dvd_mult2, simp, simp)\n    done\nqed simp\n\nlemma fac_dvd2: \"\\<lbrakk>Suc 0 < q; q dvd n!; q \\<le> n\\<rbrakk> \\<Longrightarrow> \\<not> q dvd Suc (n!)\"\nproof(auto simp: dvd_def)\n  fix k ka\n  assume h1: \"Suc 0 < q\" \"q \\<le> n\"\n    and h2: \"Suc (q * k) = q * ka\"\n  have \"k < ka\"\n  proof - \n    have \"q * k < q * ka\" \n      using h2 by arith\n    thus \"k < ka\"\n      using h1\n      by(auto)\n  qed\n  hence \"\\<exists>d. d > 0 \\<and>  ka = d + k\"  \n    by(rule_tac x = \"ka - k\" in exI, simp)\n  from this obtain d where \"d > 0 \\<and> ka = d + k\" ..\n  from h2 and this and h1 show \"False\"\n    by(simp add: add_mult_distrib2)\nqed\n\nlemma prime_ex: \"\\<exists> p. n < p \\<and> p \\<le> Suc (n!) \\<and> Prime p\"\nproof(cases \"Prime (n! + 1)\")\n  case True thus \"?thesis\" \n    by(rule_tac x = \"Suc (n!)\" in exI, simp)\nnext\n  assume h: \"\\<not> Prime (n! + 1)\"  \n  hence \"\\<exists> p. Prime p \\<and> p dvd (n! + 1)\"\n    by(erule_tac divsor_prime_ex, auto)\n  from this obtain q where k: \"Prime q \\<and> q dvd (n! + 1)\" ..\n  thus \"?thesis\"\n  proof(cases \"q > n\")\n    case True thus \"?thesis\"\n      using k by(auto intro:dvd_imp_le)\n  next\n    case False thus \"?thesis\"\n    proof -\n      assume g: \"\\<not> n < q\"\n      have j: \"q > Suc 0\"\n        using k by(cases q, auto simp: Prime.simps)\n      hence \"q dvd n!\"\n        using g \n        apply(rule_tac fac_dvd, auto)\n        done\n      hence \"\\<not> q dvd Suc (n!)\"\n        using g j\n        by(rule_tac fac_dvd2, auto)\n      thus \"?thesis\"\n        using k by simp\n    qed\n  qed\nqed\n\nlemma Suc_Suc_induct[elim!]: \"\\<lbrakk>i < Suc (Suc 0); \n  primerec (ys ! 0) n; primerec (ys ! 1) n\\<rbrakk> \\<Longrightarrow> primerec (ys ! i) n\"\n  by(cases i, auto)\n\nlemma primerec_rec_prime_1[intro]: \"primerec rec_prime (Suc 0)\"\n  apply(auto simp: rec_prime_def, auto)\n  apply(rule_tac primerec_all_iff, auto, auto)\n  apply(rule_tac primerec_all_iff, auto, auto simp:  \n      numeral_2_eq_2 numeral_3_eq_3)\n  done\n\ntext \\<open>\n  The correctness of \\<open>rec_np\\<close>.\n\\<close>\n\n\nsubsection \\<open>The Recursive Function rec\\_power\\<close>\n\ntext \\<open>\n  \\<open>rec_power\\<close> is the recursive function used to implement\n  power function.\n\\<close>\ndefinition rec_power :: \"recf\"\n  where\n    \"rec_power = Pr 1 (constn 1) (Cn 3 rec_mult [id 3 0, id 3 2])\"\n\ntext \\<open>\n  The correctness of \\<open>rec_power\\<close>.\n\\<close>\nlemma power_lemma: \"rec_exec rec_power [x, y] = x^y\"\n  by(induct y, auto simp: rec_exec.simps rec_power_def)\n\nsubsection \\<open>The Recursive Function rec\\_pi\\<close>\n\ntext\\<open>\n  \\<open>Pi k\\<close> returns the \\<open>k\\<close>-th prime number.\n\\<close>\nfun Pi :: \"nat \\<Rightarrow> nat\"\n  where\n    \"Pi 0 = 2\" |\n    \"Pi (Suc x) = Np (Pi x)\"\n\ndefinition rec_dummy_pi :: \"recf\"\n  where\n    \"rec_dummy_pi = Pr 1 (constn 2) (Cn 3 rec_np [id 3 2])\"\n\ntext \\<open>\n  \\<open>rec_pi\\<close> is the recursive function used to implement\n  \\<open>Pi\\<close>.\n\\<close>\ndefinition rec_pi :: \"recf\"\n  where\n    \"rec_pi = Cn 1 rec_dummy_pi [id 1 0, id 1 0]\"\n\nlemma pi_dummy_lemma: \"rec_exec rec_dummy_pi [x, y] = Pi y\"\n  apply(induct y)\n  by(auto simp: rec_exec.simps rec_dummy_pi_def Pi.simps np_lemma)\n\ntext \\<open>\n  The correctness of \\<open>rec_pi\\<close>.\n\\<close>\nlemma pi_lemma: \"rec_exec rec_pi [x] = Pi x\"\n  apply(simp add: rec_pi_def rec_exec.simps pi_dummy_lemma)\n  done\n\n\nsubsection \\<open>The Recursive Function rec\\_lo\\<close>\n\nfun loR :: \"nat list \\<Rightarrow> bool\"\n  where\n    \"loR [x, y, u] = (x mod (y^u) = 0)\"\n\ndeclare loR.simps[simp del]\n\ntext \\<open>\n  \\<open>Lo\\<close> specifies the \\<open>lo\\<close> function given on page 79 of \n  Boolos's book~\\<^cite>\\<open>\"Boolos07\"\\<close>. It is one of the two notions of integeral logarithmetic\n  operation on that page. The other is \\<open>lg\\<close>.\n\\<close>\nfun lo :: \" nat \\<Rightarrow> nat \\<Rightarrow> nat\"\n  where \n    \"lo x y  = (if x > 1 \\<and> y > 1 \\<and> {u. loR [x, y, u]} \\<noteq> {} then Max {u. loR [x, y, u]}\n                                                         else 0)\"\n\ndeclare lo.simps[simp del]\n\nlemma primerec_sigma[intro!]:  \n  \"\\<lbrakk>n > Suc 0; primerec rf n\\<rbrakk> \\<Longrightarrow> \n  primerec (rec_sigma rf) n\"\n  apply(simp add: rec_sigma.simps)\n  apply(auto, auto simp: nth_append)\n  done\n\nlemma primerec_rec_maxr[intro!]:  \"\\<lbrakk>primerec rf n; n > 0\\<rbrakk> \\<Longrightarrow> primerec (rec_maxr rf) n\"\n  apply(simp add: rec_maxr.simps)\n  apply(rule_tac prime_cn, auto)\n   apply(rule_tac primerec_all_iff, auto, auto simp: nth_append)\n  done\n\nlemma Suc_Suc_Suc_induct[elim!]: \n  \"\\<lbrakk>i < Suc (Suc (Suc (0::nat))); primerec (ys ! 0) n;\n  primerec (ys ! 1) n;  \n  primerec (ys ! 2) n\\<rbrakk> \\<Longrightarrow> primerec (ys ! i) n\"\n  apply(cases i, auto)\n  apply(cases \"i-1\", simp, simp add: numeral_2_eq_2)\n  done\n\nlemma primerec_2[intro]:\n  \"primerec rec_quo (Suc (Suc 0))\" \"primerec rec_mod (Suc (Suc 0))\"\n  \"primerec rec_power (Suc (Suc 0))\"\n  by(force simp: prime_cn prime_id rec_mod_def rec_quo_def rec_power_def prime_pr numeral_eqs_upto_12)+\n\ntext \\<open>\n  \\<open>rec_lo\\<close> is the recursive function used to implement \\<open>Lo\\<close>.\n\\<close>\ndefinition rec_lo :: \"recf\"\n  where\n    \"rec_lo = (let rR = Cn 3 rec_eq [Cn 3 rec_mod [id 3 0, \n               Cn 3 rec_power [id 3 1, id 3 2]], \n                     Cn 3 (constn 0) [id 3 1]] in\n             let rb =  Cn 2 (rec_maxr rR) [id 2 0, id 2 1, id 2 0] in \n             let rcond = Cn 2 rec_conj [Cn 2 rec_less [Cn 2 (constn 1)\n                                             [id 2 0], id 2 0], \n                                        Cn 2 rec_less [Cn 2 (constn 1)\n                                                [id 2 0], id 2 1]] in \n             let rcond2 = Cn 2 rec_minus \n                              [Cn 2 (constn 1) [id 2 0], rcond] \n             in Cn 2 rec_add [Cn 2 rec_mult [rb, rcond], \n                  Cn 2 rec_mult [Cn 2 (constn 0) [id 2 0], rcond2]])\"\n\nlemma rec_lo_Maxr_lor:\n  \"\\<lbrakk>Suc 0 < x; Suc 0 < y\\<rbrakk> \\<Longrightarrow>  \n        rec_exec rec_lo [x, y] = Maxr loR [x, y] x\"\nproof(auto simp: rec_exec.simps rec_lo_def Let_def \n    numeral_2_eq_2 numeral_3_eq_3)\n  let ?rR = \"(Cn (Suc (Suc (Suc 0))) rec_eq\n     [Cn (Suc (Suc (Suc 0))) rec_mod [recf.id (Suc (Suc (Suc 0))) 0,\n     Cn (Suc (Suc (Suc 0))) rec_power [recf.id (Suc (Suc (Suc 0)))\n     (Suc 0), recf.id (Suc (Suc (Suc 0))) (Suc (Suc 0))]],\n     Cn (Suc (Suc (Suc 0))) (constn 0) [recf.id (Suc (Suc (Suc 0))) (Suc 0)]])\"\n  have h: \"rec_exec (rec_maxr ?rR) ([x, y] @ [x]) =\n    Maxr (\\<lambda> args. 0 < rec_exec ?rR args) [x, y] x\"\n    by(rule_tac Maxr_lemma, auto simp: rec_exec.simps\n        mod_lemma power_lemma, auto simp: numeral_2_eq_2 numeral_3_eq_3)\n  have \"Maxr loR [x, y] x =  Maxr (\\<lambda> args. 0 < rec_exec ?rR args) [x, y] x\"\n    apply(simp add: rec_exec.simps mod_lemma power_lemma)\n    apply(simp add: Maxr.simps loR.simps)\n    done\n  from h and this show \"rec_exec (rec_maxr ?rR) [x, y, x] = \n    Maxr loR [x, y] x\"\n    apply(simp)\n    done\nqed\n\nlemma x_less_exp: \"\\<lbrakk>y > Suc 0\\<rbrakk> \\<Longrightarrow> x < y^x\"\nproof(induct x)\n  case (Suc x)\n  then show ?case  \n    apply(cases x, simp, auto)\n    apply(rule_tac y = \"y* y^(x-1)\" in le_less_trans, auto)\n    done\nqed simp\n\n\nlemma uplimit_loR:\n  assumes \"Suc 0 < x\" \"Suc 0 < y\" \"loR [x, y, xa]\"\n  shows \"xa \\<le> x\"\nproof -\n  have \"Suc 0 < x \\<Longrightarrow> Suc 0 < y \\<Longrightarrow> y ^ xa dvd x \\<Longrightarrow> xa \\<le> x\" \n    by (meson Suc_lessD le_less_trans nat_dvd_not_less nat_le_linear x_less_exp)\n  thus ?thesis using assms by(auto simp: loR.simps)\nqed\n\nlemma loR_set_strengthen[simp]: \"\\<lbrakk>xa \\<le> x; loR [x, y, xa]; Suc 0 < x; Suc 0 < y\\<rbrakk> \\<Longrightarrow>\n  {u. loR [x, y, u]} = {ya. ya \\<le> x \\<and> loR [x, y, ya]}\"\n  apply(rule_tac Collect_cong, auto)\n  apply(erule_tac uplimit_loR, simp, simp)\n  done\n\nlemma Maxr_lo: \"\\<lbrakk>Suc 0 < x; Suc 0 < y\\<rbrakk> \\<Longrightarrow>\n  Maxr loR [x, y] x = lo x y\" \n  apply(simp add: Maxr.simps lo.simps, auto simp: uplimit_loR)\n  by (meson uplimit_loR)+\n\nlemma lo_lemma': \"\\<lbrakk>Suc 0 < x; Suc 0 < y\\<rbrakk> \\<Longrightarrow> \n  rec_exec rec_lo [x, y] = lo x y\"\n  by(simp add: Maxr_lo  rec_lo_Maxr_lor)\n\nlemma lo_lemma'': \"\\<lbrakk>\\<not> Suc 0 < x\\<rbrakk> \\<Longrightarrow> rec_exec rec_lo [x, y] = lo x y\"\n  apply(cases x, auto simp: rec_exec.simps rec_lo_def \n      Let_def lo.simps)\n  done\n\nlemma lo_lemma''': \"\\<lbrakk>\\<not> Suc 0 < y\\<rbrakk> \\<Longrightarrow> rec_exec rec_lo [x, y] = lo x y\"\n  apply(cases y, auto simp: rec_exec.simps rec_lo_def \n      Let_def lo.simps)\n  done\n\ntext \\<open>\n  The correctness of \\<open>rec_lo\\<close>:\n\\<close>\nlemma lo_lemma: \"rec_exec rec_lo [x, y] = lo x y\" \n  apply(cases \"Suc 0 < x \\<and> Suc 0 < y\")\n   apply(auto simp: lo_lemma' lo_lemma'' lo_lemma''')\n  done\n\nsubsection \\<open>The Recursive Function rec\\_lg\\<close>\n\nfun lgR :: \"nat list \\<Rightarrow> bool\"\n  where\n    \"lgR [x, y, u] = (y^u \\<le> x)\"\n\ntext \\<open>\n  \\<open>lg\\<close> specifies the \\<open>lg\\<close> function given on page 79 of \n  Boolos's book~\\<^cite>\\<open>\"Boolos07\"\\<close>. It is one of the two notions of integral logarithmetic\n  operation on that page. The other is \\<open>lo\\<close>.\n\\<close>\nfun lg :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\"\n  where\n    \"lg x y = (if x > 1 \\<and> y > 1 \\<and> {u. lgR [x, y, u]} \\<noteq> {} then \n                 Max {u. lgR [x, y, u]}\n              else 0)\"\n\ndeclare lg.simps[simp del] lgR.simps[simp del]\n\ntext \\<open>\n  \\<open>rec_lg\\<close> is the recursive function used to implement \\<open>lg\\<close>.\n\\<close>\ndefinition rec_lg :: \"recf\"\n  where\n    \"rec_lg = (let rec_lgR = Cn 3 rec_le\n  [Cn 3 rec_power [id 3 1, id 3 2], id 3 0] in\n  let conR1 = Cn 2 rec_conj [Cn 2 rec_less \n                     [Cn 2 (constn 1) [id 2 0], id 2 0], \n                            Cn 2 rec_less [Cn 2 (constn 1) \n                                 [id 2 0], id 2 1]] in \n  let conR2 = Cn 2 rec_not [conR1] in \n        Cn 2 rec_add [Cn 2 rec_mult \n              [conR1, Cn 2 (rec_maxr rec_lgR)\n                       [id 2 0, id 2 1, id 2 0]], \n                       Cn 2 rec_mult [conR2, Cn 2 (constn 0) \n                                [id 2 0]]])\"\n\nlemma lg_maxr: \"\\<lbrakk>Suc 0 < x; Suc 0 < y\\<rbrakk> \\<Longrightarrow> \n                      rec_exec rec_lg [x, y] = Maxr lgR [x, y] x\"\nproof(simp add: rec_exec.simps rec_lg_def Let_def)\n  assume h: \"Suc 0 < x\" \"Suc 0 < y\"\n  let ?rR = \"(Cn 3 rec_le [Cn 3 rec_power\n               [recf.id 3 (Suc 0), recf.id 3 2], recf.id 3 0])\"\n  have \"rec_exec (rec_maxr ?rR) ([x, y] @ [x])\n              = Maxr ((\\<lambda> args. 0 < rec_exec ?rR args)) [x, y] x\" \n  proof(rule Maxr_lemma)\n    show \"primerec (Cn 3 rec_le [Cn 3 rec_power \n              [recf.id 3 (Suc 0), recf.id 3 2], recf.id 3 0]) (Suc (length [x, y]))\"\n      apply(auto simp: numeral_3_eq_3)+\n      done\n  qed\n  moreover have \"Maxr lgR [x, y] x = Maxr ((\\<lambda> args. 0 < rec_exec ?rR args)) [x, y] x\"\n    apply(simp add: rec_exec.simps power_lemma)\n    apply(simp add: Maxr.simps lgR.simps)\n    done \n  ultimately show \"rec_exec (rec_maxr ?rR) [x, y, x] = Maxr lgR [x, y] x\"\n    by simp\nqed\n\nlemma lgR_ok: \"\\<lbrakk>Suc 0 < y; lgR [x, y, xa]\\<rbrakk> \\<Longrightarrow> xa \\<le> x\"\n  apply(auto simp add: lgR.simps)\n  apply(subgoal_tac \"y^xa > xa\", simp)\n  apply(erule x_less_exp)\n  done\n\nlemma lgR_set_strengthen[simp]: \"\\<lbrakk>Suc 0 < x; Suc 0 < y; lgR [x, y, xa]\\<rbrakk> \\<Longrightarrow>\n           {u. lgR [x, y, u]} =  {ya. ya \\<le> x \\<and> lgR [x, y, ya]}\"\n  apply(rule_tac Collect_cong, auto simp:lgR_ok)\n  done\n\nlemma maxr_lg: \"\\<lbrakk>Suc 0 < x; Suc 0 < y\\<rbrakk> \\<Longrightarrow> Maxr lgR [x, y] x = lg x y\"\n  apply(auto simp add: lg.simps Maxr.simps)\n  using lgR_ok by blast\n\nlemma lg_lemma': \"\\<lbrakk>Suc 0 < x; Suc 0 < y\\<rbrakk> \\<Longrightarrow> rec_exec rec_lg [x, y] = lg x y\"\n  apply(simp add: maxr_lg lg_maxr)\n  done\n\nlemma lg_lemma'': \"\\<not> Suc 0 < x \\<Longrightarrow> rec_exec rec_lg [x, y] = lg x y\"\n  apply(simp add: rec_exec.simps rec_lg_def Let_def lg.simps)\n  done\n\nlemma lg_lemma''': \"\\<not> Suc 0 < y \\<Longrightarrow> rec_exec rec_lg [x, y] = lg x y\"\n  apply(simp add: rec_exec.simps rec_lg_def Let_def lg.simps)\n  done\n\ntext \\<open>\n  The correctness of \\<open>rec_lg\\<close>.\n\\<close>\nlemma lg_lemma: \"rec_exec rec_lg [x, y] = lg x y\"\n  apply(cases \"Suc 0 < x \\<and> Suc 0 < y\", auto simp: \n      lg_lemma' lg_lemma'' lg_lemma''')\n  done\n\nsubsection \\<open>The Recursive Function rec\\_entry\\<close>\n\ntext \\<open>\n  \\<open>Entry sr i\\<close> returns the \\<open>i\\<close>-th entry of a list of natural \n  numbers encoded by number \\<open>sr\\<close> using Godel's coding.\n  This function is called {\\em ent} on page 80 of Boolos's book~\\<^cite>\\<open>\"Boolos07\"\\<close>.\n\\<close>\nfun Entry :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\"\n  where\n    \"Entry sr i = lo sr (Pi (Suc i))\"\n\ntext \\<open>\n  \\<open>rec_entry\\<close> is the recursive function used to implement\n  \\<open>Entry\\<close>.\n\\<close>\ndefinition rec_entry:: \"recf\"\n  where\n    \"rec_entry = Cn 2 rec_lo [id 2 0, Cn 2 rec_pi [Cn 2 s [id 2 1]]]\"\n\ndeclare Pi.simps[simp del]\n\ntext \\<open>\n  The correctness of \\<open>rec_entry\\<close>.\n\\<close>\nlemma entry_lemma: \"rec_exec rec_entry [str, i] = Entry str i\"\n  by(simp add: rec_entry_def  rec_exec.simps lo_lemma pi_lemma)\n\n\nsection \\<open>Main components of rec\\_F\\<close>\n\ntext \\<open>\n  Using the auxiliary functions obtained in last section, \n  we are going to construct the function \\<open>F\\<close>, \n  which is an interpreter for Turing Machines.\n\\<close>\n\nfun listsum2 :: \"nat list \\<Rightarrow> nat \\<Rightarrow> nat\"\n  where\n    \"listsum2 xs 0 = 0\"\n  | \"listsum2 xs (Suc n) = listsum2 xs n + xs ! n\"\n\nfun rec_listsum2 :: \"nat \\<Rightarrow> nat \\<Rightarrow> recf\"\n  where\n    \"rec_listsum2 vl 0 = Cn vl z [id vl 0]\"\n  | \"rec_listsum2 vl (Suc n) = Cn vl rec_add [rec_listsum2 vl n, id vl n]\"\n\ndeclare listsum2.simps[simp del] rec_listsum2.simps[simp del]\n\nlemma listsum2_lemma: \"\\<lbrakk>length xs = vl; n \\<le> vl\\<rbrakk> \\<Longrightarrow> \n      rec_exec (rec_listsum2 vl n) xs = listsum2 xs n\"\n  apply(induct n, simp_all)\n   apply(simp_all add: rec_exec.simps rec_listsum2.simps listsum2.simps)\n  done\n\nsubsection \\<open>The Recursive Function rec\\_strt\\<close>\n\nfun strt' :: \"nat list \\<Rightarrow> nat \\<Rightarrow> nat\"\n  where\n    \"strt' xs 0 = 0\"\n  | \"strt' xs (Suc n) = (let dbound = listsum2 xs n + n in \n                       strt' xs n + (2^(xs ! n + dbound) - 2^dbound))\"\n\nfun rec_strt' :: \"nat \\<Rightarrow> nat \\<Rightarrow> recf\"\n  where\n    \"rec_strt' vl 0 = Cn vl z [id vl 0]\"\n  | \"rec_strt' vl (Suc n) = (let rec_dbound =\n  Cn vl rec_add [rec_listsum2 vl n, Cn vl (constn n) [id vl 0]]\n  in Cn vl rec_add [rec_strt' vl n, Cn vl rec_minus \n  [Cn vl rec_power [Cn vl (constn 2) [id vl 0], Cn vl rec_add\n  [id vl (n), rec_dbound]], \n  Cn vl rec_power [Cn vl (constn 2) [id vl 0], rec_dbound]]])\"\n\ndeclare strt'.simps[simp del] rec_strt'.simps[simp del]\n\nlemma strt'_lemma: \"\\<lbrakk>length xs = vl; n \\<le> vl\\<rbrakk> \\<Longrightarrow> \n  rec_exec (rec_strt' vl n) xs = strt' xs n\"\n  apply(induct n)\n   apply(simp_all add: rec_exec.simps rec_strt'.simps strt'.simps\n      Let_def power_lemma listsum2_lemma)\n  done\n\ntext \\<open>\n  \\<open>strt\\<close> corresponds to the \\<open>strt\\<close> function on page 90 of B book, but \n  this definition generalises the original one to deal with multiple input arguments.\n\\<close>\nfun strt :: \"nat list \\<Rightarrow> nat\"\n  where\n    \"strt xs = (let ys = map Suc xs in \n              strt' ys (length ys))\"\n\nfun rec_map :: \"recf \\<Rightarrow> nat \\<Rightarrow> recf list\"\n  where\n    \"rec_map rf vl = map (\\<lambda> i. Cn vl rf [id vl i]) [0..<vl]\"\n\ntext \\<open>\n  \\<open>rec_strt\\<close> is the recursive function used to implement \\<open>strt\\<close>.\n\\<close>\nfun rec_strt :: \"nat \\<Rightarrow> recf\"\n  where\n    \"rec_strt vl = Cn vl (rec_strt' vl vl) (rec_map s vl)\"\n\nlemma map_s_lemma: \"length xs = vl \\<Longrightarrow> \n  map ((\\<lambda>a. rec_exec a xs) \\<circ> (\\<lambda>i. Cn vl s [recf.id vl i]))\n  [0..<vl]\n        = map Suc xs\"\n  apply(induct vl arbitrary: xs, simp, auto simp: rec_exec.simps)\n  apply(rename_tac vl xs)\n  apply(subgoal_tac \"\\<exists> ys y. xs = ys @ [y]\", auto)\nproof -\n  fix ys y\n  assume ind: \"\\<And>xs. length xs = length (ys::nat list) \\<Longrightarrow>\n      map ((\\<lambda>a. rec_exec a xs) \\<circ> (\\<lambda>i. Cn (length ys) s \n        [recf.id (length ys) (i)])) [0..<length ys] = map Suc xs\"\n  show\n    \"map ((\\<lambda>a. rec_exec a (ys @ [y])) \\<circ> (\\<lambda>i. Cn (Suc (length ys)) s \n  [recf.id (Suc (length ys)) (i)])) [0..<length ys] = map Suc ys\"\n  proof -\n    have \"map ((\\<lambda>a. rec_exec a ys) \\<circ> (\\<lambda>i. Cn (length ys) s\n        [recf.id (length ys) (i)])) [0..<length ys] = map Suc ys\"\n      apply(rule_tac ind, simp)\n      done\n    moreover have\n      \"map ((\\<lambda>a. rec_exec a (ys @ [y])) \\<circ> (\\<lambda>i. Cn (Suc (length ys)) s\n           [recf.id (Suc (length ys)) (i)])) [0..<length ys]\n         = map ((\\<lambda>a. rec_exec a ys) \\<circ> (\\<lambda>i. Cn (length ys) s \n                 [recf.id (length ys) (i)])) [0..<length ys]\"\n      apply(rule_tac map_ext, auto simp: rec_exec.simps nth_append)\n      done\n    ultimately show \"?thesis\"\n      by simp\n  qed\nnext\n  fix vl xs\n  assume \"length xs = Suc vl\"\n  thus \"\\<exists>ys y. xs = ys @ [y]\"\n    apply(rule_tac x = \"butlast xs\" in exI, rule_tac x = \"last xs\" in exI)\n    apply(subgoal_tac \"xs \\<noteq> []\", auto)\n    done\nqed\n\ntext \\<open>\n  The correctness of \\<open>rec_strt\\<close>.\n\\<close>\nlemma strt_lemma: \"length xs = vl \\<Longrightarrow> \n  rec_exec (rec_strt vl) xs = strt xs\"\n  apply(simp add: strt.simps rec_exec.simps strt'_lemma)\n  apply(subgoal_tac \"(map ((\\<lambda>a. rec_exec a xs) \\<circ> (\\<lambda>i. Cn vl s [recf.id vl (i)])) [0..<vl])\n                  = map Suc xs\", auto)\n  apply(rule map_s_lemma, simp)\n  done\n\nsubsection \\<open>The Recursive Function rec\\_scan\\<close>\n\ntext \\<open>\n  The \\<open>scan\\<close> function on page 90 of B book.\n\\<close>\nfun scan :: \"nat \\<Rightarrow> nat\"\n  where\n    \"scan r = r mod 2\"\n\ntext \\<open>\n  \\<open>rec_scan\\<close> is the implemention of \\<open>scan\\<close>.\n\\<close>\ndefinition rec_scan :: \"recf\"\n  where \"rec_scan = Cn 1 rec_mod [id 1 0, constn 2]\"\n\ntext \\<open>\n  The correctness of \\<open>scan\\<close>.\n\\<close>\nlemma scan_lemma: \"rec_exec rec_scan [r] = r mod 2\"\n  by(simp add: rec_exec.simps rec_scan_def mod_lemma)\n\nsubsection \\<open>The Recursive Function rec\\_newleft\\<close>\n\nfun newleft0 :: \"nat list \\<Rightarrow> nat\"\n  where\n    \"newleft0 [p, r] = p\"\n\ndefinition rec_newleft0 :: \"recf\"\n  where\n    \"rec_newleft0 = id 2 0\"\n\nfun newrgt0 :: \"nat list \\<Rightarrow> nat\"\n  where\n    \"newrgt0 [p, r] = r - scan r\"\n\ndefinition rec_newrgt0 :: \"recf\"\n  where\n    \"rec_newrgt0 = Cn 2 rec_minus [id 2 1, Cn 2 rec_scan [id 2 1]]\"\n\n(*newleft1, newrgt1: left rgt number after execute on step*)\nfun newleft1 :: \"nat list \\<Rightarrow> nat\"\n  where\n    \"newleft1 [p, r] = p\"\n\ndefinition rec_newleft1 :: \"recf\"\n  where\n    \"rec_newleft1 = id 2 0\"\n\nfun newrgt1 :: \"nat list \\<Rightarrow> nat\"\n  where\n    \"newrgt1 [p, r] = r + 1 - scan r\"\n\ndefinition rec_newrgt1 :: \"recf\"\n  where\n    \"rec_newrgt1 = \n  Cn 2 rec_minus [Cn 2 rec_add [id 2 1, Cn 2 (constn 1) [id 2 0]], \n                  Cn 2 rec_scan [id 2 1]]\"\n\nfun newleft2 :: \"nat list \\<Rightarrow> nat\"\n  where\n    \"newleft2 [p, r] = p div 2\"\n\ndefinition rec_newleft2 :: \"recf\" \n  where\n    \"rec_newleft2 = Cn 2 rec_quo [id 2 0, Cn 2 (constn 2) [id 2 0]]\"\n\nfun newrgt2 :: \"nat list \\<Rightarrow> nat\"\n  where\n    \"newrgt2 [p, r] = 2 * r + p mod 2\"\n\ndefinition rec_newrgt2 :: \"recf\"\n  where\n    \"rec_newrgt2 =\n    Cn 2 rec_add [Cn 2 rec_mult [Cn 2 (constn 2) [id 2 0], id 2 1],                     \n                 Cn 2 rec_mod [id 2 0, Cn 2 (constn 2) [id 2 0]]]\"\n\nfun newleft3 :: \"nat list \\<Rightarrow> nat\"\n  where\n    \"newleft3 [p, r] = 2 * p + r mod 2\"\n\ndefinition rec_newleft3 :: \"recf\"\n  where\n    \"rec_newleft3 = \n  Cn 2 rec_add [Cn 2 rec_mult [Cn 2 (constn 2) [id 2 0], id 2 0], \n                Cn 2 rec_mod [id 2 1, Cn 2 (constn 2) [id 2 0]]]\"\n\nfun newrgt3 :: \"nat list \\<Rightarrow> nat\"\n  where\n    \"newrgt3 [p, r] = r div 2\"\n\ndefinition rec_newrgt3 :: \"recf\"\n  where\n    \"rec_newrgt3 = Cn 2 rec_quo [id 2 1, Cn 2 (constn 2) [id 2 0]]\"\n\ntext \\<open>\n  The \\<open>new_left\\<close> function on page 91 of B book.\n\\<close>\nfun newleft :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> nat\"\n  where\n    \"newleft p r a = (if a = 0 \\<or> a = 1 then newleft0 [p, r] \n                    else if a = 2 then newleft2 [p, r]\n                    else if a = 3 then newleft3 [p, r]\n                    else p)\"\n\ntext \\<open>\n  \\<open>rec_newleft\\<close> is the recursive function used to \n  implement \\<open>newleft\\<close>.\n\\<close>\ndefinition rec_newleft :: \"recf\" \n  where\n    \"rec_newleft =\n  (let g0 = \n      Cn 3 rec_newleft0 [id 3 0, id 3 1] in \n  let g1 = Cn 3 rec_newleft2 [id 3 0, id 3 1] in \n  let g2 = Cn 3 rec_newleft3 [id 3 0, id 3 1] in \n  let g3 = id 3 0 in\n  let r0 = Cn 3 rec_disj\n          [Cn 3 rec_eq [id 3 2, Cn 3 (constn 0) [id 3 0]],\n           Cn 3 rec_eq [id 3 2, Cn 3 (constn 1) [id 3 0]]] in \n  let r1 = Cn 3 rec_eq [id 3 2, Cn 3 (constn 2) [id 3 0]] in \n  let r2 = Cn 3 rec_eq [id 3 2, Cn 3 (constn 3) [id 3 0]] in\n  let r3 = Cn 3 rec_less [Cn 3 (constn 3) [id 3 0], id 3 2] in \n  let gs = [g0, g1, g2, g3] in \n  let rs = [r0, r1, r2, r3] in \n  rec_embranch (zip gs rs))\"\n\ndeclare newleft.simps[simp del]\n\n\nlemma Suc_Suc_Suc_Suc_induct: \n  \"\\<lbrakk>i < Suc (Suc (Suc (Suc 0))); i = 0 \\<Longrightarrow>  P i;\n    i = 1 \\<Longrightarrow> P i; i =2 \\<Longrightarrow> P i; \n    i =3 \\<Longrightarrow> P i\\<rbrakk> \\<Longrightarrow> P i\"\n  apply(cases i, force)\n  apply(cases \"i - 1\", force)\n  apply(cases \"i - 1 - 1\", force)\n  by(cases \"i - 1 - 1 - 1\", auto simp:numeral_eqs_upto_12)\n\ndeclare quo_lemma2[simp] mod_lemma[simp]\n\ntext \\<open>\n  The correctness of \\<open>rec_newleft\\<close>.\n\\<close>\nlemma newleft_lemma: \n  \"rec_exec rec_newleft [p, r, a] = newleft p r a\"\nproof(simp only: rec_newleft_def Let_def)\n  let ?rgs = \"[Cn 3 rec_newleft0 [recf.id 3 0, recf.id 3 1], Cn 3 rec_newleft2 \n       [recf.id 3 0, recf.id 3 1], Cn 3 rec_newleft3 [recf.id 3 0, recf.id 3 1], recf.id 3 0]\"\n  let ?rrs = \n    \"[Cn 3 rec_disj [Cn 3 rec_eq [recf.id 3 2, Cn 3 (constn 0) \n     [recf.id 3 0]], Cn 3 rec_eq [recf.id 3 2, Cn 3 (constn 1) [recf.id 3 0]]], \n     Cn 3 rec_eq [recf.id 3 2, Cn 3 (constn 2) [recf.id 3 0]],\n     Cn 3 rec_eq [recf.id 3 2, Cn 3 (constn 3) [recf.id 3 0]],\n     Cn 3 rec_less [Cn 3 (constn 3) [recf.id 3 0], recf.id 3 2]]\"\n  have k1: \"rec_exec (rec_embranch (zip ?rgs ?rrs)) [p, r, a]\n                         = Embranch (zip (map rec_exec ?rgs) (map (\\<lambda>r args. 0 < rec_exec r args) ?rrs)) [p, r, a]\"\n    apply(rule_tac embranch_lemma )\n        apply(auto simp: numeral_3_eq_3 numeral_2_eq_2 rec_newleft0_def \n        rec_newleft1_def rec_newleft2_def rec_newleft3_def)+\n    apply(cases \"a = 0 \\<or> a = 1\", rule_tac x = 0 in exI)\n     prefer 2\n     apply(cases \"a = 2\", rule_tac x = \"Suc 0\" in exI)\n      prefer 2\n      apply(cases \"a = 3\", rule_tac x = \"2\" in exI)\n       prefer 2\n       apply(cases \"a > 3\", rule_tac x = \"3\" in exI, auto)\n             apply(auto simp: rec_exec.simps)\n        apply(erule_tac [!] Suc_Suc_Suc_Suc_induct, auto simp: rec_exec.simps)\n    done\n  have k2: \"Embranch (zip (map rec_exec ?rgs) (map (\\<lambda>r args. 0 < rec_exec r args) ?rrs)) [p, r, a] = newleft p r a\"\n    apply(simp add: Embranch.simps)\n    apply(simp add: rec_exec.simps)\n    apply(auto simp: newleft.simps rec_newleft0_def rec_exec.simps\n        rec_newleft1_def rec_newleft2_def rec_newleft3_def)\n    done\n  from k1 and k2 show \n    \"rec_exec (rec_embranch (zip ?rgs ?rrs)) [p, r, a] = newleft p r a\"\n    by simp\nqed\n\nsubsection \\<open>The Recursive Function rec\\_newrght\\<close>\n\ntext \\<open>\n  The \\<open>newrght\\<close> function is one similar to \\<open>newleft\\<close>, but used to \n  compute the right number.\n\\<close>\nfun newrght :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> nat\"\n  where\n    \"newrght p r a  = (if a = 0 then newrgt0 [p, r]\n                    else if a = 1 then newrgt1 [p, r]\n                    else if a = 2 then newrgt2 [p, r]\n                    else if a = 3 then newrgt3 [p, r]\n                    else r)\"\n\ntext \\<open>\n  \\<open>rec_newrght\\<close> is the recursive function used to implement \n  \\<open>newrgth\\<close>.\n\\<close>\ndefinition rec_newrght :: \"recf\" \n  where\n    \"rec_newrght =\n  (let g0 = Cn 3 rec_newrgt0 [id 3 0, id 3 1] in \n  let g1 = Cn 3 rec_newrgt1 [id 3 0, id 3 1] in \n  let g2 = Cn 3 rec_newrgt2 [id 3 0, id 3 1] in \n  let g3 = Cn 3 rec_newrgt3 [id 3 0, id 3 1] in\n  let g4 = id 3 1 in \n  let r0 = Cn 3 rec_eq [id 3 2, Cn 3 (constn 0) [id 3 0]] in \n  let r1 = Cn 3 rec_eq [id 3 2, Cn 3 (constn 1) [id 3 0]] in \n  let r2 = Cn 3 rec_eq [id 3 2, Cn 3 (constn 2) [id 3 0]] in\n  let r3 = Cn 3 rec_eq [id 3 2, Cn 3 (constn 3) [id 3 0]] in\n  let r4 = Cn 3 rec_less [Cn 3 (constn 3) [id 3 0], id 3 2] in \n  let gs = [g0, g1, g2, g3, g4] in \n  let rs = [r0, r1, r2, r3, r4] in \n  rec_embranch (zip gs rs))\"\ndeclare newrght.simps[simp del]\n\nlemma Suc_5_induct: \n  \"\\<lbrakk>i < Suc (Suc (Suc (Suc (Suc 0)))); i = 0 \\<Longrightarrow> P 0;\n  i = 1 \\<Longrightarrow> P 1; i = 2 \\<Longrightarrow> P 2; i = 3 \\<Longrightarrow> P 3; i = 4 \\<Longrightarrow> P 4\\<rbrakk> \\<Longrightarrow> P i\"\n  apply(cases i, force)\n  apply(cases \"i-1\", force)\n  apply(cases \"i-1-1\")\n  using less_2_cases numeral_eqs_upto_12 by auto\n\n\nlemma primerec_rec_scan_1[intro]: \"primerec rec_scan (Suc 0)\"\n  apply(auto simp: rec_scan_def, auto)\n  done\n\ntext \\<open>\n  The correctness of \\<open>rec_newrght\\<close>.\n\\<close>\n\n\n  have k1: \"rec_exec (rec_embranch (zip ?rgs ?rrs)) [p, r, a]\n    = Embranch (zip (map rec_exec ?rgs) (map (\\<lambda>r args. 0 < rec_exec r args) ?rrs)) [p, r, a]\"\n    apply(rule_tac embranch_lemma)\n        apply(auto simp: numeral_3_eq_3 numeral_2_eq_2 rec_newrgt0_def \n        rec_newrgt1_def rec_newrgt2_def rec_newrgt3_def)+\n    apply(cases \"a = 0\", rule_tac x = 0 in exI)\n     prefer 2\n     apply(cases \"a = 1\", rule_tac x = \"Suc 0\" in exI)\n      prefer 2\n      apply(cases \"a = 2\", rule_tac x = \"2\" in exI)\n       prefer 2\n       apply(cases \"a = 3\", rule_tac x = \"3\" in exI)\n        prefer 2\n        apply(cases \"a > 3\", rule_tac x = \"4\" in exI, auto simp: rec_exec.simps)\n        apply(erule_tac [!] Suc_5_induct, auto simp: rec_exec.simps)\n    done\n  have k2: \"Embranch (zip (map rec_exec ?rgs)\n    (map (\\<lambda>r args. 0 < rec_exec r args) ?rrs)) [p, r, a] = newrght p r a\"\n    apply(auto simp:Embranch.simps rec_exec.simps)\n        apply(auto simp: newrght.simps rec_newrgt3_def rec_newrgt2_def\n        rec_newrgt1_def rec_newrgt0_def rec_exec.simps\n        scan_lemma)\n    done\n  from k1 and k2 show \n    \"rec_exec (rec_embranch (zip ?rgs ?rrs)) [p, r, a] =      \n                                    newrght p r a\" by simp\nqed\n\ndeclare Entry.simps[simp del]\n\nsubsection \\<open>The Recursive Function rec\\_actn\\<close>\n\ntext \\<open>\n  The \\<open>actn\\<close> function given on page 92 of B book, which is used to \n  fetch Turing Machine instructions. \n  In \\<open>actn m q r\\<close>, \\<open>m\\<close> is the G\u00f6del coding of a Turing Machine,\n  \\<open>q\\<close> is the current state of Turing Machine, \\<open>r\\<close> is the\n  right number of Turing Machine tape.\n\\<close>\nfun actn :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> nat\"\n  where\n    \"actn m q r = (if q \\<noteq> 0 then Entry m (4*(q - 1) + 2 * scan r)\n                 else 4)\"\n\ntext \\<open>\n  \\<open>rec_actn\\<close> is the recursive function used to implement \\<open>actn\\<close>\n\\<close>\ndefinition rec_actn :: \"recf\"\n  where\n    \"rec_actn = \n  Cn 3 rec_add [Cn 3 rec_mult \n        [Cn 3 rec_entry [id 3 0, Cn 3 rec_add [Cn 3 rec_mult \n                                 [Cn 3 (constn 4) [id 3 0], \n                Cn 3 rec_minus [id 3 1, Cn 3 (constn 1) [id 3 0]]], \n                   Cn 3 rec_mult [Cn 3 (constn 2) [id 3 0],\n                      Cn 3 rec_scan [id 3 2]]]], \n            Cn 3 rec_noteq [id 3 1, Cn 3 (constn 0) [id 3 0]]], \n                             Cn 3 rec_mult [Cn 3 (constn 4) [id 3 0], \n             Cn 3 rec_eq [id 3 1, Cn 3 (constn 0) [id 3 0]]]] \"\n\ntext \\<open>\n  The correctness of \\<open>actn\\<close>.\n\\<close>\nlemma actn_lemma: \"rec_exec rec_actn [m, q, r] = actn m q r\"\n  by(auto simp: rec_actn_def rec_exec.simps entry_lemma scan_lemma)\n\nsubsection \\<open>The Recursive Function rec\\_newstat\\<close>\n\nfun newstat :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> nat\"\n  where\n    \"newstat m q r = (if q \\<noteq> 0 then Entry m (4*(q - 1) + 2*scan r + 1)\n                    else 0)\"\n\ndefinition rec_newstat :: \"recf\"\n  where\n    \"rec_newstat = Cn 3 rec_add \n    [Cn 3 rec_mult [Cn 3 rec_entry [id 3 0, \n           Cn 3 rec_add [Cn 3 rec_mult [Cn 3 (constn 4) [id 3 0], \n           Cn 3 rec_minus [id 3 1, Cn 3 (constn 1) [id 3 0]]], \n           Cn 3 rec_add [Cn 3 rec_mult [Cn 3 (constn 2) [id 3 0],\n           Cn 3 rec_scan [id 3 2]], Cn 3 (constn 1) [id 3 0]]]], \n           Cn 3 rec_noteq [id 3 1, Cn 3 (constn 0) [id 3 0]]], \n           Cn 3 rec_mult [Cn 3 (constn 0) [id 3 0], \n           Cn 3 rec_eq [id 3 1, Cn 3 (constn 0) [id 3 0]]]] \"\n\nlemma newstat_lemma: \"rec_exec rec_newstat [m, q, r] = newstat m q r\"\n  by(auto simp:  rec_exec.simps entry_lemma scan_lemma rec_newstat_def)\n\ndeclare newstat.simps[simp del] actn.simps[simp del]\n\nsubsection \\<open>The Recursive Function rec\\_trpl\\<close>\n\ntext\\<open>code the configuration\\<close>\n\nfun trpl :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> nat\"\n  where\n    \"trpl p q r = (Pi 0)^p * (Pi 1)^q * (Pi 2)^r\"\n\ndefinition rec_trpl :: \"recf\"\n  where\n    \"rec_trpl = Cn 3 rec_mult [Cn 3 rec_mult \n       [Cn 3 rec_power [Cn 3 (constn (Pi 0)) [id 3 0], id 3 0], \n        Cn 3 rec_power [Cn 3 (constn (Pi 1)) [id 3 0], id 3 1]],\n        Cn 3 rec_power [Cn 3 (constn (Pi 2)) [id 3 0], id 3 2]]\"\ndeclare trpl.simps[simp del]\nlemma trpl_lemma: \"rec_exec rec_trpl [p, q, r] = trpl p q r\"\n  by(auto simp: rec_trpl_def rec_exec.simps power_lemma trpl.simps)\n\nsubsection \\<open>The Recursive Functions rec\\_left, rec\\_right, rec\\_stat, rec\\_inpt\\<close>\n\ntext\\<open>left, stat, rght: decode func\\<close>\nfun left :: \"nat \\<Rightarrow> nat\"\n  where\n    \"left c = lo c (Pi 0)\"\n\nfun stat :: \"nat \\<Rightarrow> nat\"\n  where\n    \"stat c = lo c (Pi 1)\"\n\nfun rght :: \"nat \\<Rightarrow> nat\"\n  where\n    \"rght c = lo c (Pi 2)\"\n\nfun inpt :: \"nat \\<Rightarrow> nat list \\<Rightarrow> nat\"\n  where\n    \"inpt m xs = trpl 0 1 (strt xs)\"\n\nfun newconf :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\"\n  where\n    \"newconf m c = trpl (newleft (left c) (rght c) \n                        (actn m (stat c) (rght c)))\n                        (newstat m (stat c) (rght c)) \n                        (newrght (left c) (rght c) \n                              (actn m (stat c) (rght c)))\"\n\ndeclare left.simps[simp del] stat.simps[simp del] rght.simps[simp del]\n  inpt.simps[simp del] newconf.simps[simp del]\n\ndefinition rec_left :: \"recf\"\n  where\n    \"rec_left = Cn 1 rec_lo [id 1 0, constn (Pi 0)]\"\n\ndefinition rec_right :: \"recf\"\n  where\n    \"rec_right = Cn 1 rec_lo [id 1 0, constn (Pi 2)]\"\n\ndefinition rec_stat :: \"recf\"\n  where\n    \"rec_stat = Cn 1 rec_lo [id 1 0, constn (Pi 1)]\"\n\ndefinition rec_inpt :: \"nat \\<Rightarrow> recf\"\n  where\n    \"rec_inpt vl = Cn vl rec_trpl \n                  [Cn vl (constn 0) [id vl 0], \n                   Cn vl (constn 1) [id vl 0], \n                   Cn vl (rec_strt (vl - 1)) \n                        (map (\\<lambda> i. id vl (i)) [1..<vl])]\"\n\nlemma left_lemma: \"rec_exec rec_left [c] = left c\"\n  by(simp add: rec_exec.simps rec_left_def left.simps lo_lemma)\n\nlemma right_lemma: \"rec_exec rec_right [c] = rght c\"\n  by(simp add: rec_exec.simps rec_right_def rght.simps lo_lemma)\n\nlemma stat_lemma: \"rec_exec rec_stat [c] = stat c\"\n  by(simp add: rec_exec.simps rec_stat_def stat.simps lo_lemma)\n\ndeclare rec_strt.simps[simp del] strt.simps[simp del]\n\nlemma map_cons_eq: \n  \"(map ((\\<lambda>a. rec_exec a (m # xs)) \\<circ> \n    (\\<lambda>i. recf.id (Suc (length xs)) (i))) \n          [Suc 0..<Suc (length xs)])\n        = map (\\<lambda> i. xs ! (i - 1)) [Suc 0..<Suc (length xs)]\"\n  apply(rule map_ext, auto)\n   apply(auto simp: rec_exec.simps nth_append nth_Cons split: nat.split)\n  done\n\nlemma list_map_eq: \n  \"vl = length (xs::nat list) \\<Longrightarrow> map (\\<lambda> i. xs ! (i - 1))\n                                          [Suc 0..<Suc vl] = xs\"\nproof(induct vl arbitrary: xs)\n  case (Suc vl)\n  then show ?case \n    apply(subgoal_tac \"\\<exists> ys y. xs = ys @ [y]\", auto)\n  proof -\n    fix ys y\n    assume ind: \n      \"\\<And>xs. length (ys::nat list) = length (xs::nat list) \\<Longrightarrow>\n            map (\\<lambda>i. xs ! (i - Suc 0)) [Suc 0..<length xs] @\n                                [xs ! (length xs - Suc 0)] = xs\"\n      and h: \"Suc 0 \\<le> length (ys::nat list)\"\n    have \"map (\\<lambda>i. ys ! (i - Suc 0)) [Suc 0..<length ys] @ \n                                   [ys ! (length ys - Suc 0)] = ys\"\n      apply(rule_tac ind, simp)\n      done\n    moreover have \n      \"map (\\<lambda>i. (ys @ [y]) ! (i - Suc 0)) [Suc 0..<length ys]\n      = map (\\<lambda>i. ys ! (i - Suc 0)) [Suc 0..<length ys]\"\n      apply(rule map_ext)\n      using h\n      apply(auto simp: nth_append)\n      done\n    ultimately show \"map (\\<lambda>i. (ys @ [y]) ! (i - Suc 0)) \n        [Suc 0..<length ys] @ [(ys @ [y]) ! (length ys - Suc 0)] = ys\"\n      apply(simp del: map_eq_conv add: nth_append, auto)\n      using h\n      apply(simp)\n      done\n  next\n    fix vl xs\n    assume \"Suc vl = length (xs::nat list)\"\n    thus \"\\<exists>ys y. xs = ys @ [y]\"\n      apply(rule_tac x = \"butlast xs\" in exI, \n          rule_tac x = \"last xs\" in exI)\n      apply(cases \"xs \\<noteq> []\", auto)\n      done\n  qed\nqed simp\n\nlemma nonempty_listE: \n  \"Suc 0 \\<le> length xs \\<Longrightarrow> \n     (map ((\\<lambda>a. rec_exec a (m # xs)) \\<circ> \n         (\\<lambda>i. recf.id (Suc (length xs)) (i))) \n             [Suc 0..<length xs] @ [(m # xs) ! length xs]) = xs\"\n  using map_cons_eq[of m xs]\n  apply(simp del: map_eq_conv add: rec_exec.simps)\n  using list_map_eq[of \"length xs\" xs]\n  apply(simp)\n  done\n\nlemma inpt_lemma:\n  \"\\<lbrakk>Suc (length xs) = vl\\<rbrakk> \\<Longrightarrow> \n            rec_exec (rec_inpt vl) (m # xs) = inpt m xs\"\n  apply(auto simp: rec_exec.simps rec_inpt_def \n      trpl_lemma inpt.simps strt_lemma)\n   apply(subgoal_tac\n      \"(map ((\\<lambda>a. rec_exec a (m # xs)) \\<circ> \n          (\\<lambda>i. recf.id (Suc (length xs)) (i))) \n            [Suc 0..<length xs] @ [(m # xs) ! length xs]) = xs\", simp)\n   apply(auto elim:nonempty_listE, cases xs, auto)\n  done\n\nsubsection \\<open>The Recursive Function rec\\_newconf\\<close>\n\ndefinition rec_newconf:: \"recf\"\n  where\n    \"rec_newconf = \n    Cn 2 rec_trpl \n        [Cn 2 rec_newleft [Cn 2 rec_left [id 2 1], \n                           Cn 2 rec_right [id 2 1], \n                           Cn 2 rec_actn [id 2 0, \n                                          Cn 2 rec_stat [id 2 1], \n                           Cn 2 rec_right [id 2 1]]],\n          Cn 2 rec_newstat [id 2 0, \n                            Cn 2 rec_stat [id 2 1], \n                            Cn 2 rec_right [id 2 1]],\n           Cn 2 rec_newrght [Cn 2 rec_left [id 2 1], \n                             Cn 2 rec_right [id 2 1], \n                             Cn 2 rec_actn [id 2 0, \n                                   Cn 2 rec_stat [id 2 1], \n                             Cn 2 rec_right [id 2 1]]]]\"\n\nlemma newconf_lemma: \"rec_exec rec_newconf [m ,c] = newconf m c\"\n  by(auto simp: rec_newconf_def rec_exec.simps \n      trpl_lemma newleft_lemma left_lemma\n      right_lemma stat_lemma newrght_lemma actn_lemma \n      newstat_lemma newconf.simps)\n\ndeclare newconf_lemma[simp]\n\nsubsection \\<open>The Recursive Function rec\\_conf\\<close>\n\ntext \\<open>\n  \\<open>conf m r k\\<close> computes the TM configuration after \\<open>k\\<close> steps of execution\n  of TM coded as \\<open>m\\<close> starting from the initial configuration where the left number equals \\<open>0\\<close>, \n  right number equals \\<open>r\\<close>. \n\\<close>\nfun conf :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> nat\"\n  where\n    \"conf m r 0 = trpl 0 (Suc 0) r\"\n  | \"conf m r (Suc t) = newconf m (conf m r t)\"\n\ndeclare conf.simps[simp del]\n\ntext \\<open>\n  \\<open>conf\\<close> is implemented by the following recursive function \\<open>rec_conf\\<close>.\n\\<close>\ndefinition rec_conf :: \"recf\"\n  where\n    \"rec_conf = Pr 2 (Cn 2 rec_trpl [Cn 2 (constn 0) [id 2 0], Cn 2 (constn (Suc 0)) [id 2 0], id 2 1])\n                  (Cn 4 rec_newconf [id 4 0, id 4 3])\"\n\nlemma conf_step: \n  \"rec_exec rec_conf [m, r, Suc t] =\n         rec_exec rec_newconf [m, rec_exec rec_conf [m, r, t]]\"\nproof -\n  have \"rec_exec rec_conf ([m, r] @ [Suc t]) = \n          rec_exec rec_newconf [m, rec_exec rec_conf [m, r, t]]\"\n    by(simp only: rec_conf_def rec_pr_Suc_simp_rewrite,\n        simp add: rec_exec.simps)\n  thus \"rec_exec rec_conf [m, r, Suc t] =\n                rec_exec rec_newconf [m, rec_exec rec_conf [m, r, t]]\"\n    by simp\nqed\n\ntext \\<open>\n  The correctness of \\<open>rec_conf\\<close>.\n\\<close>\nlemma conf_lemma: \n  \"rec_exec rec_conf [m, r, t] = conf m r t\"\n  by (induct t)\n    (auto simp add: rec_conf_def rec_exec.simps conf.simps inpt_lemma trpl_lemma)\n\nsubsection \\<open>The Recursive Function rec\\_NSTD\\<close>\n\ntext \\<open>\n  \\<open>NSTD c\\<close> returns true if the configuration coded by \\<open>c\\<close> is no a stardard\n  final configuration.\n\\<close>\nfun NSTD :: \"nat \\<Rightarrow> bool\"\n  where\n    \"NSTD c = (stat c \\<noteq> 0 \\<or> left c \\<noteq> 0 \\<or> \n             rght c \\<noteq> 2^(lg (rght c + 1) 2) - 1 \\<or> rght c = 0)\"\n\ntext \\<open>\n  \\<open>rec_NSTD\\<close> is the recursive function implementing \\<open>NSTD\\<close>.\n\\<close>\ndefinition rec_NSTD :: \"recf\"\n  where\n    \"rec_NSTD =\n     Cn 1 rec_disj [\n          Cn 1 rec_disj [\n             Cn 1 rec_disj \n                [Cn 1 rec_noteq [rec_stat, constn 0], \n                 Cn 1 rec_noteq [rec_left, constn 0]] , \n              Cn 1 rec_noteq [rec_right,  \n                              Cn 1 rec_minus [Cn 1 rec_power \n                                 [constn 2, Cn 1 rec_lg \n                                    [Cn 1 rec_add        \n                                     [rec_right, constn 1], \n                                            constn 2]], constn 1]]],\n               Cn 1 rec_eq [rec_right, constn 0]]\"\n\nlemma NSTD_lemma1: \"rec_exec rec_NSTD [c] = Suc 0 \\<or>\n                   rec_exec rec_NSTD [c] = 0\"\n  by(simp add: rec_exec.simps rec_NSTD_def)\n\ndeclare NSTD.simps[simp del]\nlemma NSTD_lemma2': \"(rec_exec rec_NSTD [c] = Suc 0) \\<Longrightarrow> NSTD c\"\n  apply(simp add: rec_exec.simps rec_NSTD_def stat_lemma left_lemma \n      lg_lemma right_lemma power_lemma NSTD.simps)\n  apply(auto)\n  apply(cases \"0 < left c\", simp, simp)\n  done\n\nlemma NSTD_lemma2'': \n  \"NSTD c \\<Longrightarrow> (rec_exec rec_NSTD [c] = Suc 0)\"\n  apply(simp add: rec_exec.simps rec_NSTD_def stat_lemma \n      left_lemma lg_lemma right_lemma power_lemma NSTD.simps)\n  apply(auto split: if_splits)\n  done\n\ntext \\<open>\n  The correctness of \\<open>NSTD\\<close>.\n\\<close>\nlemma NSTD_lemma2: \"(rec_exec rec_NSTD [c] = Suc 0) = NSTD c\"\n  using NSTD_lemma1\n  apply(auto intro: NSTD_lemma2' NSTD_lemma2'')\n  done\n\nfun nstd :: \"nat \\<Rightarrow> nat\"\n  where\n    \"nstd c = (if NSTD c then 1 else 0)\"\n\nlemma nstd_lemma: \"rec_exec rec_NSTD [c] = nstd c\"\n  using NSTD_lemma1\n  apply(simp add: NSTD_lemma2, auto)\n  done\n\nsubsection \\<open>The Recursive Function rec\\_nonstop\\<close>\n\ntext\\<open>\n  \\<open>nonstop m r t\\<close> means afer \\<open>t\\<close> steps of execution, the TM coded by \\<open>m\\<close>\n  is not at a stardard final configuration.\n\\<close>\nfun nonstop :: \"nat \\<Rightarrow> nat  \\<Rightarrow> nat \\<Rightarrow> nat\"\n  where\n    \"nonstop m r t = nstd (conf m r t)\"\n\ntext \\<open>\n  \\<open>rec_nonstop\\<close> is the recursive function implementing \\<open>nonstop\\<close>.\n\\<close>\ndefinition rec_nonstop :: \"recf\"\n  where\n    \"rec_nonstop = Cn 3 rec_NSTD [rec_conf]\"\n\ntext \\<open>\n  The correctness of \\<open>rec_nonstop\\<close>.\n\\<close>\nlemma nonstop_lemma: \n  \"rec_exec rec_nonstop [m, r, t] = nonstop m r t\"\n  apply(simp add: rec_exec.simps rec_nonstop_def nstd_lemma conf_lemma)\n  done\n\nsubsection \\<open>The Recursive Function rec\\_halt\\<close>\n\ntext\\<open>\n  \\<open>rec_halt\\<close> is the recursive function calculating the steps a TM needs to execute before\n  to reach a standard final configuration. This recursive function is the only one\n  using the \\<open>Mn\\<close> combinator. So it is the only non-primitive recursive function that\n  needs to be used in the construction of the universal function \\<open>F\\<close>.\n\\<close>\n\ndefinition rec_halt :: \"recf\"\n  where\n    \"rec_halt = Mn (Suc (Suc 0)) (rec_nonstop)\"\n\ndeclare nonstop.simps[simp del]\n\ntext \\<open>\n  The lemma relates the interpreter of primitive functions with\n  the calculation relation of general recursive functions. \n\\<close>\n\nsubsection \\<open>Execution of  Primitive Recursive Functions always terminates\\<close>\n\ndeclare numeral_2_eq_2[simp] numeral_3_eq_3[simp]\n\nlemma primerec_rec_right_1[intro]: \"primerec rec_right (Suc 0)\"\n  by(auto simp: rec_right_def rec_lo_def Let_def;force)\n\nlemma primerec_rec_pi_helper:\n  \"\\<forall>i<Suc (Suc 0). primerec ([recf.id (Suc 0) 0, recf.id (Suc 0) 0] ! i) (Suc 0)\"\n  by fastforce\n\nlemmas primerec_rec_pi_helpers =\n  primerec_rec_pi_helper primerec_constn_1 primerec_rec_sg_1 primerec_rec_not_1 primerec_rec_conj_2\n\nlemma primrec_dummyfac:\n  \"\\<forall>i<Suc (Suc 0).\n       primerec\n        ([recf.id (Suc 0) 0,\n          Cn (Suc 0) s\n           [Cn (Suc 0) rec_dummyfac\n             [recf.id (Suc 0) 0, recf.id (Suc 0) 0]]] !\n         i)\n        (Suc 0)\"\n  by(auto simp: rec_dummyfac_def;force)\n\nlemma primerec_rec_pi_1[intro]:  \"primerec rec_pi (Suc 0)\"\n  apply(simp add: rec_pi_def rec_dummy_pi_def \n      rec_np_def rec_fac_def rec_prime_def\n      rec_Minr.simps Let_def get_fstn_args.simps\n      arity.simps\n      rec_all.simps rec_sigma.simps rec_accum.simps)\n  apply(tactic \\<open>resolve_tac @{context} [@{thm prime_cn},  @{thm prime_pr}] 1\\<close>\n      ;(simp add:primerec_rec_pi_helpers primrec_dummyfac)?)+\n  by fastforce+\n\nlemma primerec_recs[intro]:\n  \"primerec rec_trpl (Suc (Suc (Suc 0)))\"\n  \"primerec rec_newleft0 (Suc (Suc 0))\"\n  \"primerec rec_newleft1 (Suc (Suc 0))\"\n  \"primerec rec_newleft2 (Suc (Suc 0))\"\n  \"primerec rec_newleft3 (Suc (Suc 0))\"\n  \"primerec rec_newleft (Suc (Suc (Suc 0)))\"\n  \"primerec rec_left (Suc 0)\"\n  \"primerec rec_actn (Suc (Suc (Suc 0)))\"\n  \"primerec rec_stat (Suc 0)\"\n  \"primerec rec_newstat (Suc (Suc (Suc 0)))\"\n           apply(simp_all add: rec_newleft_def rec_embranch.simps rec_left_def rec_lo_def rec_entry_def\n      rec_actn_def Let_def arity.simps rec_newleft0_def rec_stat_def rec_newstat_def\n      rec_newleft1_def rec_newleft2_def rec_newleft3_def rec_trpl_def)\n           apply(tactic \\<open>resolve_tac @{context} [@{thm prime_cn}, \n    @{thm prime_id}, @{thm prime_pr}] 1\\<close>;force)+\n  done\n\nlemma primerec_rec_newrght[intro]: \"primerec rec_newrght (Suc (Suc (Suc 0)))\"\n  apply(simp add: rec_newrght_def rec_embranch.simps\n      Let_def arity.simps rec_newrgt0_def \n      rec_newrgt1_def rec_newrgt2_def rec_newrgt3_def)\n  apply(tactic \\<open>resolve_tac @{context} [@{thm prime_cn}, \n    @{thm prime_id}, @{thm prime_pr}] 1\\<close>;force)+\n  done\n\nlemma primerec_rec_newconf[intro]: \"primerec rec_newconf (Suc (Suc 0))\"\n  apply(simp add: rec_newconf_def)\n  by(tactic \\<open>resolve_tac @{context} [@{thm prime_cn}, \n    @{thm prime_id}, @{thm prime_pr}] 1\\<close>;force)\n\nlemma primerec_rec_conf[intro]: \"primerec rec_conf (Suc (Suc (Suc 0)))\"\n  apply(simp add: rec_conf_def)\n  by(tactic \\<open>resolve_tac @{context} [@{thm prime_cn}, \n    @{thm prime_id}, @{thm prime_pr}] 1\\<close>;force simp: numeral_eqs_upto_12)\n\nlemma primerec_recs2[intro]:\n  \"primerec rec_lg (Suc (Suc 0))\"\n  \"primerec rec_nonstop (Suc (Suc (Suc 0)))\"\n   apply(simp_all add: rec_lg_def rec_nonstop_def rec_NSTD_def rec_stat_def\n      rec_lo_def Let_def rec_left_def rec_right_def rec_newconf_def\n      rec_newstat_def)\n  by(tactic \\<open>resolve_tac @{context} [@{thm prime_cn}, \n    @{thm prime_id}, @{thm prime_pr}] 1\\<close>;fastforce)+\n\nlemma primerec_terminate: \n  \"\\<lbrakk>primerec f x; length xs = x\\<rbrakk> \\<Longrightarrow> terminate f xs\"\nproof(induct arbitrary: xs rule: primerec.induct)\n  fix xs\n  assume \"length (xs::nat list) = Suc 0\"  thus \"terminate z xs\"\n    by(cases xs, auto intro: termi_z)\nnext\n  fix xs\n  assume \"length (xs::nat list) = Suc 0\" thus \"terminate s xs\"\n    by(cases xs, auto intro: termi_s)\nnext\n  fix n m xs\n  assume \"n < m\" \"length (xs::nat list) = m\"  thus \"terminate (id m n) xs\"\n    by(erule_tac termi_id, simp)\nnext\n  fix f k gs m n xs\n  assume ind: \"\\<forall>i<length gs. primerec (gs ! i) m \\<and> (\\<forall>x. length x = m \\<longrightarrow> terminate (gs ! i) x)\"\n    and ind2: \"\\<And> xs. length xs = k \\<Longrightarrow> terminate f xs\"\n    and h: \"primerec f k\"  \"length gs = k\" \"m = n\" \"length (xs::nat list) = m\"\n  have \"terminate f (map (\\<lambda>g. rec_exec g xs) gs)\"\n    using ind2[of \"(map (\\<lambda>g. rec_exec g xs) gs)\"] h\n    by simp\n  moreover have \"\\<forall>g\\<in>set gs. terminate g xs\"\n    using ind h\n    by(auto simp: set_conv_nth)\n  ultimately show \"terminate (Cn n f gs) xs\"\n    using h\n    by(rule_tac termi_cn, auto)\nnext\n  fix f n g m xs\n  assume ind1: \"\\<And>xs. length xs = n \\<Longrightarrow> terminate f xs\"\n    and ind2: \"\\<And>xs. length xs = Suc (Suc n) \\<Longrightarrow> terminate g xs\"\n    and h: \"primerec f n\" \" primerec g (Suc (Suc n))\" \" m = Suc n\" \"length (xs::nat list) = m\"\n  have \"\\<forall>y<last xs. terminate g (butlast xs @ [y, rec_exec (Pr n f g) (butlast xs @ [y])])\"\n    using h ind2 by(auto)\n  moreover have \"terminate f (butlast xs)\"\n    using ind1[of \"butlast xs\"] h\n    by simp\n  moreover have \"length (butlast xs) = n\"\n    using h by simp\n  ultimately have \"terminate (Pr n f g) (butlast xs @ [last xs])\"\n    by(rule_tac termi_pr, simp_all)\n  thus \"terminate (Pr n f g) xs\"\n    using h\n    by(cases \"xs = []\", auto)\nqed\n\n\nsubsection \\<open>The Recursive Function rec\\_valu\\<close>\n\ntext \\<open>\n  \\<open>valu r\\<close> extracts computing result out of the right number \\<open>r\\<close>.\n\\<close>\nfun valu :: \"nat \\<Rightarrow> nat\"\n  where\n    \"valu r = (lg (r + 1) 2) - 1\"\n\ntext \\<open>\n  \\<open>rec_valu\\<close> is the recursive function implementing \\<open>valu\\<close>.\n\\<close>\ndefinition rec_valu :: \"recf\"\n  where\n    \"rec_valu = Cn 1 rec_minus [Cn 1 rec_lg [s, constn 2], constn 1]\"\n\ntext \\<open>\n  The correctness of \\<open>rec_valu\\<close>.\n\\<close>\nlemma value_lemma: \"rec_exec rec_valu [r] = valu r\"\n  by(simp add: rec_exec.simps rec_valu_def lg_lemma)\n\nlemma primerec_rec_valu_1[intro]: \"primerec rec_valu (Suc 0)\"\n  unfolding rec_valu_def\n  apply(rule prime_cn[of _ \"Suc (Suc 0)\"])\n  by auto auto\n\ndeclare valu.simps[simp del]\n\nsection \\<open>Definition of the Universal Function rec\\_F\\<close>\n\ndefinition rec_F :: \"recf\"\n  where\n    \"rec_F = Cn (Suc (Suc 0)) rec_valu [Cn (Suc (Suc 0)) rec_right [Cn (Suc (Suc 0))\n rec_conf ([id (Suc (Suc 0)) 0, id (Suc (Suc 0)) (Suc 0), rec_halt])]]\"\n\nlemma terminate_halt_lemma: \n  \"\\<lbrakk>rec_exec rec_nonstop ([m, r] @ [t]) = 0; \n     \\<forall>i<t. 0 < rec_exec rec_nonstop ([m, r] @ [i])\\<rbrakk> \\<Longrightarrow> terminate rec_halt [m, r]\"\n  apply(simp add: rec_halt_def)\n  apply(rule termi_mn, auto)\n  by(rule primerec_terminate; auto)+\n\nsection \\<open>Correctness of rec\\_F with respect to rec\\_halt\\<close>\n\ntext \\<open>\n  The following lemma gives the correctness of \\<open>rec_halt\\<close>.\n  It says: if \\<open>rec_halt\\<close> calculates that the TM coded by \\<open>m\\<close>\n  will reach a standard final configuration after \\<open>t\\<close> steps of execution, then it is indeed so.\n\\<close>\n\nlemma F_lemma: \"rec_exec rec_halt [m, r] = t \\<Longrightarrow> rec_exec rec_F [m, r] = (valu (rght (conf m r t)))\"\n  by(simp add: rec_F_def rec_exec.simps value_lemma right_lemma conf_lemma halt_lemma)\n\nlemma terminate_F_lemma: \"terminate rec_halt [m, r] \\<Longrightarrow> terminate rec_F [m, r]\"\n  apply(simp add: rec_F_def)\n  apply(rule termi_cn, auto)\n   apply(rule primerec_terminate, auto)\n  apply(rule termi_cn, auto)\n   apply(rule primerec_terminate, auto)\n  apply(rule termi_cn, auto)\n    apply(rule primerec_terminate, auto)\n   apply(rule termi_id;force)\n  apply(rule termi_id;force)\n  done\n\nsection \\<open>A G\u00f6del-Encoding for TMs: the function code\\<close>\n\ntext \\<open>\n  The purpose of this section is to get the coding function of Turing Machine, which is \n  going to be named \\<open>code\\<close>.\n\\<close>\n\nfun bl2nat :: \"cell list \\<Rightarrow> nat \\<Rightarrow> nat\"\n  where\n    \"bl2nat [] n = 0\"\n  | \"bl2nat (Bk#bl) n = bl2nat bl (Suc n)\"\n  | \"bl2nat (Oc#bl) n = 2^n + bl2nat bl (Suc n)\"\n\nfun bl2wc :: \"cell list \\<Rightarrow> nat\"\n  where\n    \"bl2wc xs = bl2nat xs 0\"\n\nfun trpl_code :: \"config \\<Rightarrow> nat\"\n  where\n    \"trpl_code (st, l, r) = trpl (bl2wc l) st (bl2wc r)\"\n\ndeclare bl2nat.simps[simp del] bl2wc.simps[simp del]\n  trpl_code.simps[simp del]\n\nfun action_map :: \"action \\<Rightarrow> nat\"\n  where\n    \"action_map WB = 0\"\n  | \"action_map WO = 1\"\n  | \"action_map L = 2\"\n  | \"action_map R = 3\"\n  | \"action_map Nop = 4\"\n\nfun action_map_iff :: \"nat \\<Rightarrow> action\"\n  where\n    \"action_map_iff (0::nat) = WB\"\n  | \"action_map_iff (Suc 0) = WO\"\n  | \"action_map_iff (Suc (Suc 0)) = L\"\n  | \"action_map_iff (Suc (Suc (Suc 0))) = R\"\n  | \"action_map_iff n = Nop\"\n\nfun block_map :: \"cell \\<Rightarrow> nat\"\n  where\n    \"block_map Bk = 0\"\n  | \"block_map Oc = 1\"\n\nfun godel_code' :: \"nat list \\<Rightarrow> nat \\<Rightarrow> nat\"\n  where\n    \"godel_code' [] n = 1\"\n  | \"godel_code' (x#xs) n = (Pi n)^x * godel_code' xs (Suc n) \"\n\nfun godel_code :: \"nat list \\<Rightarrow> nat\"\n  where\n    \"godel_code xs = (let lh = length xs in \n                   2^lh * (godel_code' xs (Suc 0)))\"\n\nfun modify_tprog :: \"instr list \\<Rightarrow> nat list\"\n  where\n    \"modify_tprog [] =  []\"\n  | \"modify_tprog ((ac, ns)#nl) = action_map ac # ns # modify_tprog nl\"\n\ntext \\<open>\n  \\<open>code tp\\<close> gives the Godel coding of TM program \\<open>tp\\<close>.\n\\<close>\nfun code :: \"instr list \\<Rightarrow> nat\"\n  where \n    \"code tp = (let nl = modify_tprog tp in \n              godel_code nl)\"\n\nsection \\<open>Relating interpreter functions to the execution of TMs\\<close>\n\nlemma bl2wc_0[simp]: \"bl2wc [] = 0\" by(simp add: bl2wc.simps bl2nat.simps)\n\nlemma fetch_action_map_4[simp]: \"\\<lbrakk>fetch tp 0 b = (nact, ns)\\<rbrakk> \\<Longrightarrow> action_map nact = 4\"\n  apply(simp add: fetch.simps)\n  done\n\nlemma Pi_gr_1[simp]: \"Pi n > Suc 0\"\nproof(induct n, auto simp: Pi.simps Np.simps)\n  fix n\n  let ?setx = \"{y. y \\<le> Suc (Pi n!) \\<and> Pi n < y \\<and> Prime y}\"\n  have \"finite ?setx\" by auto\n  moreover have \"?setx \\<noteq> {}\"\n    using prime_ex[of \"Pi n\"]\n    apply(auto)\n    done\n  ultimately show \"Suc 0 < Min ?setx\"\n    apply(simp add: Min_gr_iff)\n    apply(auto simp: Prime.simps)\n    done\nqed\n\nlemma Pi_not_0[simp]: \"Pi n > 0\"\n  using Pi_gr_1[of n]\n  by arith\n\ndeclare godel_code.simps[simp del]\n\nlemma godel_code'_nonzero[simp]: \"0 < godel_code' nl n\"\n  apply(induct nl arbitrary: n)\n   apply(auto simp: godel_code'.simps)\n  done\n\nlemma godel_code_great: \"godel_code nl > 0\"\n  apply(simp add: godel_code.simps)\n  done\n\nlemma godel_code_eq_1: \"(godel_code nl = 1) = (nl = [])\"\n  apply(auto simp: godel_code.simps)\n  done\n\nlemma godel_code_1_iff[elim]: \n  \"\\<lbrakk>i < length nl; \\<not> Suc 0 < godel_code nl\\<rbrakk> \\<Longrightarrow> nl ! i = 0\"\n  using godel_code_great[of nl] godel_code_eq_1[of nl]\n  apply(simp)\n  done\n\nlemma prime_coprime: \"\\<lbrakk>Prime x; Prime y; x\\<noteq>y\\<rbrakk> \\<Longrightarrow> coprime x y\"\nproof (simp only: Prime.simps coprime_def, auto simp: dvd_def,\n    rule_tac classical, simp)\n  fix d k ka\n  assume case_ka: \"\\<forall>u<d * ka. \\<forall>v<d * ka. u * v \\<noteq> d * ka\" \n    and case_k: \"\\<forall>u<d * k. \\<forall>v<d * k. u * v \\<noteq> d * k\"\n    and h: \"(0::nat) < d\" \"d \\<noteq> Suc 0\" \"Suc 0 < d * ka\" \n    \"ka \\<noteq> k\" \"Suc 0 < d * k\"\n  from h have \"k > Suc 0 \\<or> ka >Suc 0\"\n    by (cases ka;cases k;force+)\n  from this show \"False\"\n  proof(erule_tac disjE)\n    assume  \"(Suc 0::nat) < k\"\n    hence \"k < d*k \\<and> d < d*k\"\n      using h\n      by(auto)\n    thus \"?thesis\"\n      using case_k\n      apply(erule_tac x = d in allE)\n      apply(simp)\n      apply(erule_tac x = k in allE)\n      apply(simp)\n      done\n  next\n    assume \"(Suc 0::nat) < ka\"\n    hence \"ka < d * ka \\<and> d < d*ka\"\n      using h by auto\n    thus \"?thesis\"\n      using case_ka\n      apply(erule_tac x = d in allE)\n      apply(simp)\n      apply(erule_tac x = ka in allE)\n      apply(simp)\n      done\n  qed\nqed\n\nlemma Pi_inc: \"Pi (Suc i) > Pi i\"\nproof(simp add: Pi.simps Np.simps)\n  let ?setx = \"{y. y \\<le> Suc (Pi i!) \\<and> Pi i < y \\<and> Prime y}\"\n  have \"finite ?setx\" by simp\n  moreover have \"?setx \\<noteq> {}\"\n    using prime_ex[of \"Pi i\"]\n    apply(auto)\n    done\n  ultimately show \"Pi i < Min ?setx\"\n    apply(simp)\n    done\nqed    \n\nlemma Pi_inc_gr: \"i < j \\<Longrightarrow> Pi i < Pi j\"\nproof(induct j, simp)\n  fix j\n  assume ind: \"i < j \\<Longrightarrow> Pi i < Pi j\"\n    and h: \"i < Suc j\"\n  from h show \"Pi i < Pi (Suc j)\"\n  proof(cases \"i < j\")\n    case True thus \"?thesis\"\n    proof -\n      assume \"i < j\"\n      hence \"Pi i < Pi j\" by(erule_tac ind)\n      moreover have \"Pi j < Pi (Suc j)\"\n        apply(simp add: Pi_inc)\n        done\n      ultimately show \"?thesis\"\n        by simp\n    qed\n  next\n    assume \"i < Suc j\" \"\\<not> i < j\"\n    hence \"i = j\"\n      by arith\n    thus \"Pi i < Pi (Suc j)\"\n      apply(simp add: Pi_inc)\n      done\n  qed\nqed      \n\nlemma Pi_notEq: \"i \\<noteq> j \\<Longrightarrow> Pi i \\<noteq> Pi j\"\n  apply(cases \"i < j\")\n  using Pi_inc_gr[of i j]\n   apply(simp)\n  using Pi_inc_gr[of j i]\n  apply(simp)\n  done\n\nlemma prime_2[intro]: \"Prime (Suc (Suc 0))\"\n  apply(auto simp: Prime.simps)\n  using less_2_cases by fastforce\n\nlemma Prime_Pi[intro]: \"Prime (Pi n)\"\nproof(induct n, auto simp: Pi.simps Np.simps)\n  fix n\n  let ?setx = \"{y. y \\<le> Suc (Pi n!) \\<and> Pi n < y \\<and> Prime y}\"\n  show \"Prime (Min ?setx)\"\n  proof -\n    have \"finite ?setx\" by simp\n    moreover have \"?setx \\<noteq> {}\" \n      using prime_ex[of \"Pi n\"]\n      apply(simp)\n      done\n    ultimately show \"?thesis\"\n      apply(drule_tac Min_in, simp, simp)\n      done\n  qed\nqed\n\nlemma Pi_coprime: \"i \\<noteq> j \\<Longrightarrow> coprime (Pi i) (Pi j)\"\n  using Prime_Pi[of i]\n  using Prime_Pi[of j]\n  apply(rule_tac prime_coprime, simp_all add: Pi_notEq)\n  done\n\nlemma Pi_power_coprime: \"i \\<noteq> j \\<Longrightarrow> coprime ((Pi i)^m) ((Pi j)^n)\"\n  unfolding coprime_power_right_iff coprime_power_left_iff using Pi_coprime by auto\n\nlemma coprime_dvd_mult_nat2: \"\\<lbrakk>coprime (k::nat) n; k dvd n * m\\<rbrakk> \\<Longrightarrow> k dvd m\"\n  unfolding coprime_dvd_mult_right_iff.\n\ndeclare godel_code'.simps[simp del]\n\nlemma godel_code'_butlast_last_id' :\n  \"godel_code' (ys @ [y]) (Suc j) = godel_code' ys (Suc j) * \n                                Pi (Suc (length ys + j)) ^ y\"\nproof(induct ys arbitrary: j, simp_all add: godel_code'.simps)\nqed  \n\nlemma godel_code'_butlast_last_id: \n  \"xs \\<noteq> [] \\<Longrightarrow> godel_code' xs (Suc j) = \n  godel_code' (butlast xs) (Suc j) * Pi (length xs + j)^(last xs)\"\n  apply(subgoal_tac \"\\<exists> ys y. xs = ys @ [y]\")\n   apply(erule_tac exE, erule_tac exE, simp add: \n      godel_code'_butlast_last_id')\n  apply(rule_tac x = \"butlast xs\" in exI)\n  apply(rule_tac x = \"last xs\" in exI, auto)\n  done\n\nlemma godel_code'_not0: \"godel_code' xs n \\<noteq> 0\"\n  apply(induct xs, auto simp: godel_code'.simps)\n  done\n\nlemma godel_code_append_cons: \n  \"length xs = i \\<Longrightarrow> godel_code' (xs@y#ys) (Suc 0)\n    = godel_code' xs (Suc 0) * Pi (Suc i)^y * godel_code' ys (i + 2)\"\nproof(induct \"length xs\" arbitrary: i y ys xs, simp add: godel_code'.simps,simp)\n  fix x xs i y ys\n  assume ind: \n    \"\\<And>xs i y ys. \\<lbrakk>x = i; length xs = i\\<rbrakk> \\<Longrightarrow> \n       godel_code' (xs @ y # ys) (Suc 0) \n     = godel_code' xs (Suc 0) * Pi (Suc i) ^ y * \n                             godel_code' ys (Suc (Suc i))\"\n    and h: \"Suc x = i\" \n    \"length (xs::nat list) = i\"\n  have \n    \"godel_code' (butlast xs @ last xs # ((y::nat)#ys)) (Suc 0) = \n        godel_code' (butlast xs) (Suc 0) * Pi (Suc (i - 1))^(last xs) \n              * godel_code' (y#ys) (Suc (Suc (i - 1)))\"\n    apply(rule_tac ind)\n    using h\n    by(auto)\n  moreover have \n    \"godel_code' xs (Suc 0)= godel_code' (butlast xs) (Suc 0) *\n                                                  Pi (i)^(last xs)\"\n    using godel_code'_butlast_last_id[of xs] h\n    apply(cases \"xs = []\", simp, simp)\n    done \n  moreover have \"butlast xs @ last xs # y # ys = xs @ y # ys\"\n    using h\n    apply(cases xs, auto)\n    done\n  ultimately show \n    \"godel_code' (xs @ y # ys) (Suc 0) =\n               godel_code' xs (Suc 0) * Pi (Suc i) ^ y *\n                    godel_code' ys (Suc (Suc i))\"\n    using h\n    apply(simp add: godel_code'_not0 Pi_not_0)\n    apply(simp add: godel_code'.simps)\n    done\nqed\n\nlemma Pi_coprime_pre: \n  \"length ps \\<le> i \\<Longrightarrow> coprime (Pi (Suc i)) (godel_code' ps (Suc 0))\"\nproof(induct \"length ps\" arbitrary: ps)\n  fix x ps\n  assume ind: \n    \"\\<And>ps. \\<lbrakk>x = length ps; length ps \\<le> i\\<rbrakk> \\<Longrightarrow>\n                  coprime (Pi (Suc i)) (godel_code' ps (Suc 0))\"\n    and h: \"Suc x = length ps\"\n    \"length (ps::nat list) \\<le> i\"\n  have g: \"coprime (Pi (Suc i)) (godel_code' (butlast ps) (Suc 0))\"\n    apply(rule_tac ind)\n    using h by auto\n  have k: \"godel_code' ps (Suc 0) = \n         godel_code' (butlast ps) (Suc 0) * Pi (length ps)^(last ps)\"\n    using godel_code'_butlast_last_id[of ps 0] h \n    by(cases ps, simp, simp)\n  from g have \"coprime (Pi (Suc i)) (Pi (length ps) ^ last ps)\"\n    unfolding coprime_power_right_iff using Pi_coprime h(2) by auto\n  with g have \n    \"coprime (Pi (Suc i)) (godel_code' (butlast ps) (Suc 0) *\n                                        Pi (length ps)^(last ps)) \"\n    unfolding coprime_mult_right_iff coprime_power_right_iff by auto\n\n  from this and k show \"coprime (Pi (Suc i)) (godel_code' ps (Suc 0))\"\n    by simp\nqed (auto simp add: godel_code'.simps)\n\nlemma Pi_coprime_suf: \"i < j \\<Longrightarrow> coprime (Pi i) (godel_code' ps j)\"\nproof(induct \"length ps\" arbitrary: ps)\n  fix x ps\n  assume ind: \n    \"\\<And>ps. \\<lbrakk>x = length ps; i < j\\<rbrakk> \\<Longrightarrow> \n                    coprime (Pi i) (godel_code' ps j)\"\n    and h: \"Suc x = length (ps::nat list)\" \"i < j\"\n  have g: \"coprime (Pi i) (godel_code' (butlast ps) j)\"\n    apply(rule ind) using h by auto\n  have k: \"(godel_code' ps j) = godel_code' (butlast ps) j *\n                                 Pi (length ps + j - 1)^last ps\"\n    using h godel_code'_butlast_last_id[of ps \"j - 1\"]\n    apply(cases \"ps = []\", simp, simp)\n    done\n  from g have\n    \"coprime (Pi i) (godel_code' (butlast ps) j * \n                          Pi (length ps + j - 1)^last ps)\"\n    using Pi_power_coprime[of i \"length ps + j - 1\" 1 \"last ps\"] h\n    by(auto)\n  from k and this show \"coprime (Pi i) (godel_code' ps j)\"\n    by auto\nqed (simp add: godel_code'.simps)\n\nlemma godel_finite: \n  \"finite {u. Pi (Suc i) ^ u dvd godel_code' nl (Suc 0)}\"\nproof(rule bounded_nat_set_is_finite[of _ \"godel_code' nl (Suc 0)\",rule_format],goal_cases)\n  case (1 ia)\n  then show ?case proof(cases \"ia < godel_code' nl (Suc 0)\")\n    case False\n    hence g1: \"Pi (Suc i) ^ ia dvd godel_code' nl (Suc 0)\"\n      and g2: \"\\<not> ia < godel_code' nl (Suc 0)\"\n      and \"Pi (Suc i)^ia \\<le> godel_code' nl (Suc 0)\"\n      using godel_code'_not0[of nl \"Suc 0\"] using 1 by (auto elim:dvd_imp_le)\n    moreover have \"ia < Pi (Suc i)^ia\"\n      by(rule x_less_exp[OF Pi_gr_1])\n    ultimately show ?thesis\n      using g2 by(auto)\n  qed auto\nqed\n\nlemma godel_code_in: \n  \"i < length nl \\<Longrightarrow>  nl ! i  \\<in> {u. Pi (Suc i) ^ u dvd\n                                     godel_code' nl (Suc 0)}\"\nproof -\n  assume h: \"i<length nl\"\n  hence \"godel_code' (take i nl@(nl!i)#drop (Suc i) nl) (Suc 0)\n           = godel_code' (take i nl) (Suc 0) *  Pi (Suc i)^(nl!i) *\n                               godel_code' (drop (Suc i) nl) (i + 2)\"\n    by(rule_tac godel_code_append_cons, simp)\n  moreover from h have \"take i nl @ (nl ! i) # drop (Suc i) nl = nl\"\n    using upd_conv_take_nth_drop[of i nl \"nl ! i\"]\n    by simp\n  ultimately  show \n    \"nl ! i \\<in> {u. Pi (Suc i) ^ u dvd godel_code' nl (Suc 0)}\"\n    by(simp)\nqed\n\nlemma godel_code'_get_nth:\n  \"i < length nl \\<Longrightarrow> Max {u. Pi (Suc i) ^ u dvd \n                          godel_code' nl (Suc 0)} = nl ! i\"\nproof(rule_tac Max_eqI)\n  let ?gc = \"godel_code' nl (Suc 0)\"\n  assume h: \"i < length nl\" thus \"finite {u. Pi (Suc i) ^ u dvd ?gc}\"\n    by (simp add: godel_finite)  \nnext\n  fix y\n  let ?suf =\"godel_code' (drop (Suc i) nl) (i + 2)\"\n  let ?pref = \"godel_code' (take i nl) (Suc 0)\"\n  assume h: \"i < length nl\" \n    \"y \\<in> {u. Pi (Suc i) ^ u dvd godel_code' nl (Suc 0)}\"\n  moreover hence\n    \"godel_code' (take i nl@(nl!i)#drop (Suc i) nl) (Suc 0)\n    = ?pref * Pi (Suc i)^(nl!i) * ?suf\"\n    by(rule_tac godel_code_append_cons, simp)\n  moreover from h have \"take i nl @ (nl!i) # drop (Suc i) nl = nl\"\n    using upd_conv_take_nth_drop[of i nl \"nl!i\"]\n    by simp\n  ultimately show \"y\\<le>nl!i\"\n  proof(simp)\n    let ?suf' = \"godel_code' (drop (Suc i) nl) (Suc (Suc i))\"\n    assume mult_dvd: \n      \"Pi (Suc i) ^ y dvd ?pref *  Pi (Suc i) ^ nl ! i * ?suf'\"\n    hence \"Pi (Suc i) ^ y dvd ?pref * Pi (Suc i) ^ nl ! i\"\n    proof -\n      have \"coprime (Pi (Suc i)^y) ?suf'\" by (simp add: Pi_coprime_suf)\n      thus ?thesis using coprime_dvd_mult_left_iff mult_dvd by blast\n    qed\n    hence \"Pi (Suc i) ^ y dvd Pi (Suc i) ^ nl ! i\"\n    proof(rule_tac coprime_dvd_mult_nat2)\n      have \"coprime (Pi (Suc i)^y) (?pref^Suc 0)\" using Pi_coprime_pre by simp\n      thus \"coprime (Pi (Suc i) ^ y) ?pref\" by simp\n    qed\n    hence \"Pi (Suc i) ^ y \\<le>  Pi (Suc i) ^ nl ! i \"\n      apply(rule_tac dvd_imp_le, auto)\n      done\n    thus \"y \\<le> nl ! i\"\n      apply(rule_tac power_le_imp_le_exp, auto)\n      done\n  qed\nnext\n  assume h: \"i<length nl\"\n\n  thus \"nl ! i \\<in> {u. Pi (Suc i) ^ u dvd godel_code' nl (Suc 0)}\"\n    by(rule_tac godel_code_in, simp)\nqed\n\nlemma godel_code'_set[simp]: \n  \"{u. Pi (Suc i) ^ u dvd (Suc (Suc 0)) ^ length nl * \n                                     godel_code' nl (Suc 0)} = \n    {u. Pi (Suc i) ^ u dvd  godel_code' nl (Suc 0)}\"\n  apply(rule_tac Collect_cong, auto)\n  apply(rule_tac n = \" (Suc (Suc 0)) ^ length nl\" in \n      coprime_dvd_mult_nat2)\nproof -\n  have \"Pi 0 = (2::nat)\" by(simp add: Pi.simps)\n  show \"coprime (Pi (Suc i) ^ u) ((Suc (Suc 0)) ^ length nl)\" for u\n    using Pi_coprime Pi.simps(1) by force\nqed\n\nlemma godel_code_get_nth: \n  \"i < length nl \\<Longrightarrow> \n           Max {u. Pi (Suc i) ^ u dvd godel_code nl} = nl ! i\"\n  by(simp add: godel_code.simps godel_code'_get_nth)\n\nlemma mod_dvd_simp: \"(x mod y = (0::nat)) = (y dvd x)\"\n  by(simp add: dvd_def, auto)\n\nlemma dvd_power_le: \"\\<lbrakk>a > Suc 0; a ^ y dvd a ^ l\\<rbrakk> \\<Longrightarrow> y \\<le> l\"\n  apply(cases \"y \\<le> l\", simp, simp)\n  apply(subgoal_tac \"\\<exists> d. y = l + d\", auto simp: power_add)\n  apply(rule_tac x = \"y - l\" in exI, simp)\n  done\n\n\nlemma Pi_nonzeroE[elim]: \"Pi n = 0 \\<Longrightarrow> RR\"\n  using Pi_not_0[of n] by simp\n\nlemma Pi_not_oneE[elim]: \"Pi n = Suc 0 \\<Longrightarrow> RR\"\n  using Pi_gr_1[of n] by simp\n\nlemma finite_power_dvd:\n  \"\\<lbrakk>(a::nat) > Suc 0; y \\<noteq> 0\\<rbrakk> \\<Longrightarrow> finite {u. a^u dvd y}\"\n  apply(auto simp: dvd_def simp:gr0_conv_Suc intro!:bounded_nat_set_is_finite[of _ y])\n  by (metis le_less_trans mod_less mod_mult_self1_is_0 not_le Suc_lessD less_trans_Suc\n      mult.right_neutral n_less_n_mult_m x_less_exp\n      zero_less_Suc zero_less_mult_pos)\n\nlemma conf_decode1: \"\\<lbrakk>m \\<noteq> n; m \\<noteq> k; k \\<noteq> n\\<rbrakk> \\<Longrightarrow> \n  Max {u. Pi m ^ u dvd Pi m ^ l * Pi n ^ st * Pi k ^ r} = l\"\nproof -\n  let ?setx = \"{u. Pi m ^ u dvd Pi m ^ l * Pi n ^ st * Pi k ^ r}\"\n  assume g: \"m \\<noteq> n\" \"m \\<noteq> k\" \"k \\<noteq> n\"\n  show \"Max ?setx = l\"\n  proof(rule_tac Max_eqI)\n    show \"finite ?setx\"\n      apply(rule_tac finite_power_dvd, auto)\n      done\n  next\n    fix y\n    assume h: \"y \\<in> ?setx\"\n    have \"Pi m ^ y dvd Pi m ^ l\"\n    proof -\n      have \"Pi m ^ y dvd Pi m ^ l * Pi n ^ st\"\n        using h g Pi_power_coprime\n        by (simp add: coprime_dvd_mult_left_iff)\n      thus \"Pi m^y dvd Pi m^l\" using g Pi_power_coprime coprime_dvd_mult_left_iff by blast\n    qed\n    thus \"y \\<le> (l::nat)\"\n      apply(rule_tac a = \"Pi m\" in power_le_imp_le_exp)\n       apply(simp_all)\n      apply(rule_tac dvd_power_le, auto)\n      done\n  next\n    show \"l \\<in> ?setx\" by simp\n  qed\nqed\n\nlemma left_trpl_fst[simp]: \"left (trpl l st r) = l\"\n  apply(simp add: left.simps trpl.simps lo.simps loR.simps mod_dvd_simp)\n  apply(auto simp: conf_decode1)\n   apply(cases \"Pi 0 ^ l * Pi (Suc 0) ^ st * Pi (Suc (Suc 0)) ^ r\")\n    apply(auto)\n  apply(erule_tac x = l in allE, auto)\n  done   \n\nlemma stat_trpl_snd[simp]: \"stat (trpl l st r) = st\"\n  apply(simp add: stat.simps trpl.simps lo.simps \n      loR.simps mod_dvd_simp, auto)\n    apply(subgoal_tac \"Pi 0 ^ l * Pi (Suc 0) ^ st * Pi (Suc (Suc 0)) ^ r\n               = Pi (Suc 0)^st * Pi 0 ^ l *  Pi (Suc (Suc 0)) ^ r\")\n     apply(simp (no_asm_simp) add: conf_decode1, simp)\n   apply(cases \"Pi 0 ^ l * Pi (Suc 0) ^ st * \n                                  Pi (Suc (Suc 0)) ^ r\", auto)\n  apply(erule_tac x = st in allE, auto)\n  done\n\nlemma rght_trpl_trd[simp]: \"rght (trpl l st r) = r\"\n  apply(simp add: rght.simps trpl.simps lo.simps \n      loR.simps mod_dvd_simp, auto)\n    apply(subgoal_tac \"Pi 0 ^ l * Pi (Suc 0) ^ st * Pi (Suc (Suc 0)) ^ r\n               = Pi (Suc (Suc 0))^r * Pi 0 ^ l *  Pi (Suc 0) ^ st\")\n     apply(simp (no_asm_simp) add: conf_decode1, simp)\n   apply(cases \"Pi 0 ^ l * Pi (Suc 0) ^ st * Pi (Suc (Suc 0)) ^ r\",\n      auto)\n  apply(erule_tac x = r in allE, auto)\n  done\n\nlemma max_lor:\n  \"i < length nl \\<Longrightarrow> Max {u. loR [godel_code nl, Pi (Suc i), u]} \n                   = nl ! i\"\n  apply(simp add: loR.simps godel_code_get_nth mod_dvd_simp)\n  done\n\nlemma godel_decode: \n  \"i < length nl \\<Longrightarrow> Entry (godel_code nl) i = nl ! i\"\n  apply(auto simp: Entry.simps lo.simps max_lor)\n  apply(erule_tac x = \"nl!i\" in allE)\n  using max_lor[of i nl] godel_finite[of i nl]\n  apply(simp)\n  apply(drule_tac Max_in, auto simp: loR.simps \n      godel_code.simps mod_dvd_simp)\n  using godel_code_in[of i nl]\n  apply(simp)\n  done\n\nlemma Four_Suc: \"4 = Suc (Suc (Suc (Suc 0)))\"\n  by auto\n\ndeclare numeral_2_eq_2[simp del]\n\nlemma modify_tprog_fetch_even: \n  \"\\<lbrakk>st \\<le> length tp div 2; st > 0\\<rbrakk> \\<Longrightarrow>\n  modify_tprog tp ! (4 * (st - Suc 0) ) = \n  action_map (fst (tp ! (2 * (st - Suc 0))))\"\nproof(induct st arbitrary: tp, simp)\n  fix tp st\n  assume ind: \n    \"\\<And>tp. \\<lbrakk>st \\<le> length tp div 2; 0 < st\\<rbrakk> \\<Longrightarrow> \n     modify_tprog tp ! (4 * (st - Suc 0)) =\n               action_map (fst ((tp::instr list) ! (2 * (st - Suc 0))))\"\n    and h: \"Suc st \\<le> length (tp::instr list) div 2\" \"0 < Suc st\"\n  thus \"modify_tprog tp ! (4 * (Suc st - Suc 0)) = \n          action_map (fst (tp ! (2 * (Suc st - Suc 0))))\"\n  proof(cases \"st = 0\")\n    case True thus \"?thesis\"\n      using h by(cases tp, auto)\n  next\n    case False\n    assume g: \"st \\<noteq> 0\"\n    hence \"\\<exists> aa ab ba bb tp'. tp = (aa, ab) # (ba, bb) # tp'\"\n      using h by(cases tp; cases \"tl tp\", auto)\n    from this obtain aa ab ba bb tp' where g1: \n      \"tp = (aa, ab) # (ba, bb) # tp'\" by blast\n    hence g2: \n      \"modify_tprog tp' ! (4 * (st - Suc 0)) = \n      action_map (fst ((tp'::instr list) ! (2 * (st - Suc 0))))\"\n      using h g by (auto intro:ind)\n    thus \"?thesis\"\n      using g1 g\n      by(cases st, auto simp add: Four_Suc)\n  qed\nqed\n\nlemma modify_tprog_fetch_odd: \n  \"\\<lbrakk>st \\<le> length tp div 2; st > 0\\<rbrakk> \\<Longrightarrow> \n       modify_tprog tp ! (Suc (Suc (4 * (st - Suc 0)))) = \n       action_map (fst (tp ! (Suc (2 * (st - Suc 0)))))\"\nproof(induct st arbitrary: tp, simp)\n  fix tp st\n  assume ind: \n    \"\\<And>tp. \\<lbrakk>st \\<le> length tp div 2; 0 < st\\<rbrakk> \\<Longrightarrow>  \n       modify_tprog tp ! Suc (Suc (4 * (st - Suc 0))) = \n          action_map (fst (tp ! Suc (2 * (st - Suc 0))))\"\n    and h: \"Suc st \\<le> length (tp::instr list) div 2\" \"0 < Suc st\"\n  thus \"modify_tprog tp ! Suc (Suc (4 * (Suc st - Suc 0))) \n     = action_map (fst (tp ! Suc (2 * (Suc st - Suc 0))))\"\n  proof(cases \"st = 0\")\n    case True thus \"?thesis\"\n      using h\n      apply(cases tp, force)\n      by(cases \"tl tp\", auto)\n  next\n    case False\n    assume g: \"st \\<noteq> 0\"\n    hence \"\\<exists> aa ab ba bb tp'. tp = (aa, ab) # (ba, bb) # tp'\"\n      using h\n      apply(cases tp, simp, cases \"tl tp\", simp, simp)\n      done\n    from this obtain aa ab ba bb tp' where g1: \n      \"tp = (aa, ab) # (ba, bb) # tp'\" by blast\n    hence g2: \"modify_tprog tp' ! Suc (Suc (4 * (st  - Suc 0))) = \n          action_map (fst (tp' ! Suc (2 * (st - Suc 0))))\"\n      apply(rule_tac ind)\n      using h g by auto\n    thus \"?thesis\"\n      using g1 g\n      apply(cases st, simp, simp add: Four_Suc)\n      done\n  qed\nqed    \n\nlemma modify_tprog_fetch_action:\n  \"\\<lbrakk>st \\<le> length tp div 2; st > 0; b = 1 \\<or> b = 0\\<rbrakk> \\<Longrightarrow> \n      modify_tprog tp ! (4 * (st - Suc 0) + 2* b) =\n      action_map (fst (tp ! ((2 * (st - Suc 0)) + b)))\"\n  apply(erule_tac disjE, auto elim: modify_tprog_fetch_odd\n      modify_tprog_fetch_even)\n  done \n\nlemma length_modify: \"length (modify_tprog tp) = 2 * length tp\"\n  apply(induct tp, auto)\n  done\n\ndeclare fetch.simps[simp del]\n\nlemma fetch_action_eq: \n  \"\\<lbrakk>block_map b = scan r; fetch tp st b = (nact, ns);\n   st \\<le> length tp div 2\\<rbrakk> \\<Longrightarrow> actn (code tp) st r = action_map nact\"\nproof(simp add: actn.simps, auto)\n  let ?i = \"4 * (st - Suc 0) + 2 * (r mod 2)\"\n  assume h: \"block_map b = r mod 2\" \"fetch tp st b = (nact, ns)\" \n    \"st \\<le> length tp div 2\" \"0 < st\"\n  have \"?i < length (modify_tprog tp)\"\n  proof -\n    have \"length (modify_tprog tp) = 2 * length tp\"\n      by(simp add: length_modify)\n    thus \"?thesis\"\n      using h\n      by(auto)\n  qed\n  hence \n    \"Entry (godel_code (modify_tprog tp))?i = \n                                   (modify_tprog tp) ! ?i\"\n    by(erule_tac godel_decode)\n  moreover have \n    \"modify_tprog tp ! ?i = \n            action_map (fst (tp ! (2 * (st - Suc 0) + r mod 2)))\"\n    apply(rule_tac  modify_tprog_fetch_action)\n    using h\n    by(auto)    \n  moreover have \"(fst (tp ! (2 * (st - Suc 0) + r mod 2))) = nact\"\n    using h\n    apply(cases st, simp_all add: fetch.simps nth_of.simps)\n    apply(cases b, auto simp: block_map.simps nth_of.simps fetch.simps \n        split: if_splits)\n    apply(cases \"r mod 2\", simp, simp)\n    done\n  ultimately show \n    \"Entry (godel_code (modify_tprog tp))\n                      (4 * (st - Suc 0) + 2 * (r mod 2))\n           = action_map nact\" \n    by simp\nqed\n\nlemma fetch_zero_zero[simp]: \"fetch tp 0 b = (nact, ns) \\<Longrightarrow> ns = 0\"\n  by(simp add: fetch.simps)\n\nlemma modify_tprog_fetch_state:\n  \"\\<lbrakk>st \\<le> length tp div 2; st > 0; b = 1 \\<or> b = 0\\<rbrakk> \\<Longrightarrow> \n     modify_tprog tp ! Suc (4 * (st - Suc 0) + 2 * b) =\n  (snd (tp ! (2 * (st - Suc 0) + b)))\"\nproof(induct st arbitrary: tp, simp)\n  fix st tp\n  assume ind: \n    \"\\<And>tp. \\<lbrakk>st \\<le> length tp div 2; 0 < st; b = 1 \\<or> b = 0\\<rbrakk> \\<Longrightarrow> \n    modify_tprog tp ! Suc (4 * (st - Suc 0) + 2 * b) =\n                             snd (tp ! (2 * (st - Suc 0) + b))\"\n    and h:\n    \"Suc st \\<le> length (tp::instr list) div 2\" \n    \"0 < Suc st\" \n    \"b = 1 \\<or> b = 0\"\n  show \"modify_tprog tp ! Suc (4 * (Suc st - Suc 0) + 2 * b) =\n                             snd (tp ! (2 * (Suc st - Suc 0) + b))\"\n  proof(cases \"st = 0\")\n    case True\n    thus \"?thesis\"\n      using h\n      apply(cases tp, force)\n      apply(cases \"tl tp\", auto)\n      done\n  next\n    case False\n    assume g: \"st \\<noteq> 0\"\n    hence \"\\<exists> aa ab ba bb tp'. tp = (aa, ab) # (ba, bb) # tp'\"\n      using h\n      by(cases tp, force, cases \"tl tp\", auto)\n    from this obtain aa ab ba bb tp' where g1:\n      \"tp = (aa, ab) # (ba, bb) # tp'\" by blast\n    hence g2: \n      \"modify_tprog tp' ! Suc (4 * (st - Suc 0) + 2 * b) =\n                              snd (tp' ! (2 * (st - Suc 0) + b))\"\n      apply(intro ind)\n      using h g by auto\n    thus \"?thesis\"\n      using g1 g\n      by(cases st;force)\n  qed\nqed\n\nlemma fetch_state_eq:\n  \"\\<lbrakk>block_map b = scan r; \n  fetch tp st b = (nact, ns);\n  st \\<le> length tp div 2\\<rbrakk> \\<Longrightarrow> newstat (code tp) st r = ns\"\nproof(simp add: newstat.simps, auto)\n  let ?i = \"Suc (4 * (st - Suc 0) + 2 * (r mod 2))\"\n  assume h: \"block_map b = r mod 2\" \"fetch tp st b =\n             (nact, ns)\" \"st \\<le> length tp div 2\" \"0 < st\"\n  have \"?i < length (modify_tprog tp)\"\n  proof -\n    have \"length (modify_tprog tp) = 2 * length tp\"\n      by(simp add: length_modify)\n    thus \"?thesis\"\n      using h\n      by(auto)\n  qed\n  hence \"Entry (godel_code (modify_tprog tp)) (?i) = \n                                  (modify_tprog tp) ! ?i\"\n    by(erule_tac godel_decode)\n  moreover have \n    \"modify_tprog tp ! ?i =  \n               (snd (tp ! (2 * (st - Suc 0) + r mod 2)))\"\n    apply(rule_tac  modify_tprog_fetch_state)\n    using h\n    by(auto)\n  moreover have \"(snd (tp ! (2 * (st - Suc 0) + r mod 2))) = ns\"\n    using h\n    apply(cases st, simp)\n    apply(cases b, auto simp: fetch.simps split: if_splits)\n    apply(cases \"(2 * (st - r mod 2) + r mod 2) = \n                       (2 * (st - 1) + r mod 2)\";auto)\n    by (metis diff_Suc_Suc diff_zero prod.sel(2))\n  ultimately show \"Entry (godel_code (modify_tprog tp)) (?i)\n           = ns\" \n    by simp\nqed\n\n\nlemma tpl_eqI[intro!]: \n  \"\\<lbrakk>a = a'; b = b'; c = c'\\<rbrakk> \\<Longrightarrow> trpl a b c = trpl a' b' c'\"\n  by simp\n\nlemma bl2nat_double: \"bl2nat xs (Suc n) = 2 * bl2nat xs n\"\nproof(induct xs arbitrary: n)\n  case Nil thus \"?case\"\n    by(simp add: bl2nat.simps)\nnext\n  case (Cons x xs) thus \"?case\"\n  proof -\n    assume ind: \"\\<And>n. bl2nat xs (Suc n) = 2 * bl2nat xs n \"\n    show \"bl2nat (x # xs) (Suc n) = 2 * bl2nat (x # xs) n\"\n    proof(cases x)\n      case Bk thus \"?thesis\"\n        apply(simp add: bl2nat.simps)\n        using ind[of \"Suc n\"] by simp\n    next\n      case Oc thus \"?thesis\"\n        apply(simp add: bl2nat.simps)\n        using ind[of \"Suc n\"] by simp\n    qed\n  qed\nqed\n\n\nlemma bl2wc_simps[simp]:\n  \"bl2wc (Oc # tl c) = Suc (bl2wc c) - bl2wc c mod 2 \"\n  \"bl2wc (Bk # c) = 2*bl2wc (c)\"\n  \"2 * bl2wc (tl c) = bl2wc c - bl2wc c mod 2 \"\n  \"bl2wc [Oc] = Suc 0\"\n  \"c \\<noteq> [] \\<Longrightarrow> bl2wc (tl c) = bl2wc c div 2\"\n  \"c \\<noteq> [] \\<Longrightarrow> bl2wc [hd c] = bl2wc c mod 2\"\n  \"c \\<noteq> [] \\<Longrightarrow> bl2wc (hd c # d) = 2 * bl2wc d + bl2wc c mod 2\"\n  \"2 * (bl2wc c div 2) = bl2wc c - bl2wc c mod 2\"\n  \"bl2wc (Oc # list) mod 2 = Suc 0\" \n  by(cases c;cases \"hd c\";force simp: bl2wc.simps bl2nat.simps bl2nat_double)+\n\ndeclare code.simps[simp del]\ndeclare nth_of.simps[simp del]\n\ntext \\<open>\n  The lemma relates the one step execution of TMs with the interpreter function \\<open>rec_newconf\\<close>.\n\\<close>\nlemma rec_t_eq_step: \n  \"(\\<lambda> (s, l, r). s \\<le> length tp div 2) c \\<Longrightarrow>\n  trpl_code (step0 c tp) = \n  rec_exec rec_newconf [code tp, trpl_code c]\"\nproof(cases c)\n  case (fields s l r) assume \"case c of (s, l, r) \\<Rightarrow> s \\<le> length tp div 2\"\n  with fields have \"s \\<le> length tp div 2\" by auto\n  thus ?thesis unfolding fields \n  proof(cases \"fetch tp s (read r)\",\n      simp add: newconf.simps trpl_code.simps step.simps)\n    fix a b ca aa ba\n    assume h: \"(a::nat) \\<le> length tp div 2\" \n      \"fetch tp a (read ca) = (aa, ba)\"\n    moreover hence \"actn (code tp) a (bl2wc ca) = action_map aa\"\n      apply(rule_tac b = \"read ca\" \n          in fetch_action_eq, auto)\n      apply(cases \"hd ca\";cases ca;force)\n      done\n    moreover from h have \"(newstat (code tp) a (bl2wc ca)) = ba\"\n      apply(rule_tac b = \"read ca\" \n          in fetch_state_eq, auto split: list.splits)\n      apply(cases \"hd ca\";cases ca;force)\n      done\n    ultimately show \n      \"trpl_code (ba, update aa (b, ca)) =\n          trpl (newleft (bl2wc b) (bl2wc ca) (actn (code tp) a (bl2wc ca))) \n    (newstat (code tp) a (bl2wc ca)) (newrght (bl2wc b) (bl2wc ca) (actn (code tp) a (bl2wc ca)))\"\n      apply(cases aa)\n          apply(auto simp: trpl_code.simps \n          newleft.simps newrght.simps split: action.splits)\n      done\n  qed\nqed\n\nlemma bl2nat_simps[simp]: \"bl2nat (Oc # Oc\\<up>x) 0 = (2 * 2 ^ x - Suc 0)\"\n  \"bl2nat (Bk\\<up>x) n = 0\"\n  by(induct x;force simp: bl2nat.simps bl2nat_double exp_ind)+\n\nlemma bl2nat_exp_zero[simp]: \"bl2nat (Oc\\<up>y) 0 = 2^y - Suc 0\"\nproof(induct y)\n  case (Suc y)\n  then show ?case by(cases \"(2::nat)^y\", auto)\nqed (auto simp: bl2nat.simps bl2nat_double)\n\nlemma bl2nat_cons_bk: \"bl2nat (ks @ [Bk]) 0 = bl2nat ks 0\"\nproof(induct ks)\n  case (Cons a ks)\n  then show ?case by (cases a, auto simp: bl2nat.simps bl2nat_double)\nqed (auto simp: bl2nat.simps)\n\nlemma bl2nat_cons_oc:\n  \"bl2nat (ks @ [Oc]) 0 =  bl2nat ks 0 + 2 ^ length ks\"\nproof(induct ks)\n  case (Cons a ks)\n  then show ?case \n    by(cases a, auto simp: bl2nat.simps bl2nat_double)\nqed (auto simp: bl2nat.simps)\n\nlemma bl2nat_append: \n  \"bl2nat (xs @ ys) 0 = bl2nat xs 0 + bl2nat ys (length xs) \"\nproof(induct \"length xs\" arbitrary: xs ys, simp add: bl2nat.simps)\n  fix x xs ys\n  assume ind: \n    \"\\<And>xs ys. x = length xs \\<Longrightarrow> \n             bl2nat (xs @ ys) 0 = bl2nat xs 0 + bl2nat ys (length xs)\"\n    and h: \"Suc x = length (xs::cell list)\"\n  have \"\\<exists> ks k. xs = ks @ [k]\" \n    apply(rule_tac x = \"butlast xs\" in exI,\n        rule_tac x = \"last xs\" in exI)\n    using h\n    apply(cases xs, auto)\n    done\n  from this obtain ks k where \"xs = ks @ [k]\" by blast\n  moreover hence \n    \"bl2nat (ks @ (k # ys)) 0 = bl2nat ks 0 +\n                               bl2nat (k # ys) (length ks)\"\n    apply(rule_tac ind) using h by simp\n  ultimately show \"bl2nat (xs @ ys) 0 = \n                  bl2nat xs 0 + bl2nat ys (length xs)\"\n    apply(cases k, simp_all add: bl2nat.simps)\n     apply(simp_all only: bl2nat_cons_bk bl2nat_cons_oc)\n    done\nqed\n\nlemma trpl_code_simp[simp]:\n  \"trpl_code (steps0 (Suc 0, Bk\\<up>l, <lm>) tp 0) = \n    rec_exec rec_conf [code tp, bl2wc (<lm>), 0]\"\n  apply(simp add: steps.simps rec_exec.simps conf_lemma  conf.simps \n      inpt.simps trpl_code.simps bl2wc.simps)\n  done\n\ntext \\<open>\n  The following lemma relates the multi-step interpreter function \\<open>rec_conf\\<close>\n  with the multi-step execution of TMs.\n\\<close>\nlemma state_in_range_step\n  : \"\\<lbrakk>a \\<le> length A div 2; step0 (a, b, c) A = (st, l, r); composable_tm (A,0)\\<rbrakk>\n  \\<Longrightarrow> st \\<le> length A div 2\"\n  apply(simp add: step.simps fetch.simps composable_tm.simps \n      split: if_splits list.splits)\n   apply(case_tac [!] a, auto simp: list_all_length \n      fetch.simps nth_of.simps)\n   apply(erule_tac x = \"A ! (2*nat) \" in ballE, auto)\n  apply(cases \"hd c\", auto simp: fetch.simps nth_of.simps)\n   apply(erule_tac x = \"A !(2 * nat)\" in ballE, auto)\n  apply(erule_tac x = \"A !Suc (2 * nat)\" in ballE, auto)\n  done\n\nlemma state_in_range: \"\\<lbrakk>steps0 (Suc 0, tp) A stp = (st, l, r); composable_tm (A, 0)\\<rbrakk>\n  \\<Longrightarrow> st \\<le> length A div 2\"\nproof(induct stp arbitrary: st l r)\n  case (Suc stp st l r)\n  from Suc.prems show ?case\n  proof(simp add: step_red, cases \"(steps0 (Suc 0, tp) A stp)\", simp)\n    fix a b c \n    assume h3: \"step0 (a, b, c) A = (st, l, r)\"\n      and h4: \"steps0 (Suc 0, tp) A stp = (a, b, c)\"\n    have \"a \\<le> length A div 2\" using Suc.prems h4 by (auto intro: Suc.hyps)\n    thus \"?thesis\" using h3 Suc.prems by (auto elim: state_in_range_step)\n  qed\nqed(auto simp: composable_tm.simps steps.simps)\n\nlemma rec_t_eq_steps:\n  \"composable_tm (tp,0) \\<Longrightarrow>\n  trpl_code (steps0 (Suc 0, Bk\\<up>l, <lm>) tp stp) = \n  rec_exec rec_conf [code tp, bl2wc (<lm>), stp]\"\nproof(induct stp)\n  case 0 thus \"?case\" by(simp)\nnext\n  case (Suc n) thus \"?case\"\n  proof -\n    assume ind: \n      \"composable_tm (tp,0) \\<Longrightarrow> trpl_code (steps0 (Suc 0, Bk\\<up> l, <lm>) tp n) \n      = rec_exec rec_conf [code tp, bl2wc (<lm>), n]\"\n      and h: \"composable_tm (tp, 0)\"\n    show \n      \"trpl_code (steps0 (Suc 0, Bk\\<up> l, <lm>) tp (Suc n)) =\n      rec_exec rec_conf [code tp, bl2wc (<lm>), Suc n]\"\n    proof(cases \"steps0 (Suc 0, Bk\\<up> l, <lm>) tp  n\", \n        simp only: step_red conf_lemma conf.simps)\n      fix a b c\n      assume g: \"steps0 (Suc 0, Bk\\<up> l, <lm>) tp n = (a, b, c) \"\n      hence \"conf (code tp) (bl2wc (<lm>)) n= trpl_code (a, b, c)\"\n        using ind h\n        apply(simp add: conf_lemma)\n        done\n      moreover hence \n        \"trpl_code (step0 (a, b, c) tp) = \n        rec_exec rec_newconf [code tp, trpl_code (a, b, c)]\"\n        apply(rule_tac rec_t_eq_step)\n        using h g\n        apply(simp add: state_in_range)\n        done\n      ultimately show \n        \"trpl_code (step0 (a, b, c) tp) =\n            newconf (code tp) (conf (code tp) (bl2wc (<lm>)) n)\"\n        by(simp)\n    qed\n  qed\nqed\n\nlemma bl2wc_Bk_0[simp]: \"bl2wc (Bk\\<up> m) = 0\"\n  apply(induct m)\n   apply(simp, simp)\n  done\n\n\n\nlemma lg_power: \"x > Suc 0 \\<Longrightarrow> lg (x ^ rs) x = rs\"\nproof(simp add: lg.simps, auto)\n  fix xa\n  assume h: \"Suc 0 < x\"\n  show \"Max {ya. ya \\<le> x ^ rs \\<and> lgR [x ^ rs, x, ya]} = rs\"\n    apply(rule_tac Max_eqI, simp_all add: lgR.simps)\n     apply(simp add: h)\n    using x_less_exp[of x rs] h\n    apply(simp)\n    done\nnext\n  assume \"\\<not> Suc 0 < x ^ rs\" \"Suc 0 < x\" \n  thus \"rs = 0\"\n    apply(cases \"x ^ rs\", simp, simp)\n    done\nnext\n  assume \"Suc 0 < x\" \"\\<forall>xa. \\<not> lgR [x ^ rs, x, xa]\"\n  thus \"rs = 0\"\n    apply(simp only:lgR.simps)\n    apply(erule_tac x = rs in allE, simp)\n    done\nqed    \n\ntext \\<open>\n  The following lemma relates execution of TMs with \n  the multi-step interpreter function \\<open>rec_nonstop\\<close>. Note,\n  \\<open>rec_nonstop\\<close> is constructed using \\<open>rec_conf\\<close>.\n\\<close>\n\ndeclare composable_tm.simps[simp del]\n\nlemma nonstop_t_eq: \n  \"\\<lbrakk>steps0 (Suc 0, Bk\\<up>l, <lm>) tp stp = (0, Bk\\<up> m, Oc\\<up> rs @ Bk\\<up> n); \n   composable_tm (tp, 0); \n  rs > 0\\<rbrakk> \n  \\<Longrightarrow> rec_exec rec_nonstop [code tp, bl2wc (<lm>), stp] = 0\"\nproof(simp add: nonstop_lemma nonstop.simps )\n  assume h: \"steps0 (Suc 0, Bk\\<up>l, <lm>) tp stp = (0, Bk\\<up> m, Oc\\<up> rs @ Bk\\<up> n)\"\n    and tc_t: \"composable_tm (tp, 0)\" \"rs > 0\"\n  have g: \"rec_exec rec_conf [code tp,  bl2wc (<lm>), stp] =\n                                        trpl_code (0, Bk\\<up> m, Oc\\<up> rs@Bk\\<up> n)\"\n    using rec_t_eq_steps[of tp l lm stp] tc_t h\n    by(simp)\n  thus \"\\<not> NSTD (conf (code tp) (bl2wc (<lm>)) stp)\" \n  proof(auto simp: NSTD.simps)\n    show \"stat (conf (code tp) (bl2wc (<lm>)) stp) = 0\"\n      using g\n      by(auto simp: conf_lemma trpl_code.simps)\n  next\n    show \"left (conf (code tp) (bl2wc (<lm>)) stp) = 0\"\n      using g\n      by(simp add: conf_lemma trpl_code.simps)\n  next\n    show \"rght (conf (code tp) (bl2wc (<lm>)) stp) = \n           2 ^ lg (Suc (rght (conf (code tp) (bl2wc (<lm>)) stp))) 2 - Suc 0\"\n      using g h\n    proof(simp add: conf_lemma trpl_code.simps)\n      have \"2 ^ lg (Suc (bl2wc (Oc\\<up> rs))) 2 = Suc (bl2wc (Oc\\<up> rs))\"\n        apply(simp add: bl2wc.simps lg_power)\n        done\n      thus \"bl2wc (Oc\\<up> rs) = 2 ^ lg (Suc (bl2wc (Oc\\<up> rs))) 2 - Suc 0\"\n        apply(simp)\n        done\n    qed\n  next\n    show \"0 < rght (conf (code tp) (bl2wc (<lm>)) stp)\"\n      using g h tc_t\n      apply(simp add: conf_lemma trpl_code.simps bl2wc.simps\n          bl2nat.simps)\n      apply(cases rs, simp, simp add: bl2nat.simps)\n      done\n  qed\nqed\n\nlemma actn_0_is_4[simp]: \"actn m 0 r = 4\"\n  by(simp add: actn.simps)\n\nlemma newstat_0_0[simp]: \"newstat m 0 r = 0\"\n  by(simp add: newstat.simps)\n\ndeclare step_red[simp del]\n\nlemma halt_least_step: \n  \"\\<lbrakk>steps0 (Suc 0, Bk\\<up>l, <lm>) tp stp = \n       (0, Bk\\<up> m, Oc\\<up>rs @ Bk\\<up>n); \n    composable_tm (tp, 0); \n    0<rs\\<rbrakk> \\<Longrightarrow>\n    \\<exists> stp. (nonstop (code tp) (bl2wc (<lm>)) stp = 0 \\<and>\n       (\\<forall> stp'. nonstop (code tp) (bl2wc (<lm>)) stp' = 0 \\<longrightarrow> stp \\<le> stp'))\"\nproof(induct stp)\n  case 0\n  then show ?case by (simp add: steps.simps(1))\nnext\n  case (Suc stp)\n  hence ind: \n    \"steps0 (Suc 0, Bk\\<up> l, <lm>) tp stp = (0, Bk\\<up> m, Oc\\<up> rs @ Bk\\<up> n) \\<Longrightarrow> \n    \\<exists>stp. nonstop (code tp) (bl2wc (<lm>)) stp = 0 \\<and> \n          (\\<forall>stp'. nonstop (code tp) (bl2wc (<lm>)) stp' = 0 \\<longrightarrow> stp \\<le> stp')\"\n    and h: \n    \"steps0 (Suc 0, Bk\\<up> l, <lm>) tp (Suc stp) = (0, Bk\\<up> m, Oc\\<up> rs @ Bk\\<up> n)\"\n    \"composable_tm (tp, 0::nat)\" \n    \"0 < rs\" by simp+\n  {\n    fix a b c nat\n    assume \"steps0 (Suc 0, Bk\\<up> l, <lm>) tp stp = (a, b, c)\"\n      \"a = Suc nat\"\n    hence \"\\<exists>stp. nonstop (code tp) (bl2wc (<lm>)) stp = 0 \\<and> \n      (\\<forall>stp'. nonstop (code tp) (bl2wc (<lm>)) stp' = 0 \\<longrightarrow> stp \\<le> stp')\"\n      using h\n      apply(rule_tac x = \"Suc stp\" in exI, auto)\n       apply(drule_tac  nonstop_t_eq, simp_all add: nonstop_lemma)\n    proof -\n      fix stp'\n      assume g:\"steps0 (Suc 0, Bk\\<up> l, <lm>) tp stp = (Suc nat, b, c)\" \n        \"nonstop (code tp) (bl2wc (<lm>)) stp' = 0\"\n      thus  \"Suc stp \\<le> stp'\"\n      proof(cases \"Suc stp \\<le> stp'\", simp, simp)\n        assume \"\\<not> Suc stp \\<le> stp'\"\n        hence \"stp' \\<le> stp\" by simp\n        hence \"\\<not> is_final (steps0 (Suc 0, Bk\\<up> l, <lm>) tp stp')\"\n          using g\n          apply(cases \"steps0 (Suc 0, Bk\\<up> l, <lm>) tp stp'\",auto, simp)\n          apply(subgoal_tac \"\\<exists> n. stp = stp' + n\", auto)\n           apply(cases \"fst (steps0 (Suc 0, Bk \\<up> l, <lm>) tp stp')\", simp_all add: steps.simps)\n          apply(rule_tac x = \"stp - stp'\"  in exI, simp)\n          done         \n        hence \"nonstop (code tp) (bl2wc (<lm>)) stp' = 1\"\n        proof(cases \"steps0 (Suc 0, Bk\\<up> l, <lm>) tp stp'\",\n            simp add: nonstop.simps)\n          fix a b c\n          assume k: \n            \"0 < a\" \"steps0 (Suc 0, Bk\\<up> l, <lm>) tp stp' = (a, b, c)\"\n          thus \" NSTD (conf (code tp) (bl2wc (<lm>)) stp')\"\n            using rec_t_eq_steps[of tp l lm stp'] h\n          proof(simp add: conf_lemma) \n            assume \"trpl_code (a, b, c) = conf (code tp) (bl2wc (<lm>)) stp'\"\n            moreover have \"NSTD (trpl_code (a, b, c))\"\n              using k\n              apply(auto simp: trpl_code.simps NSTD.simps)\n              done\n            ultimately show \"NSTD (conf (code tp) (bl2wc (<lm>)) stp')\" by simp\n          qed\n        qed\n        thus \"False\" using g by simp\n      qed qed\n    }\n    note [intro] = this\n    from h show \n      \"\\<exists>stp. nonstop (code tp) (bl2wc (<lm>)) stp = 0 \n    \\<and> (\\<forall>stp'. nonstop (code tp) (bl2wc (<lm>)) stp' = 0 \\<longrightarrow> stp \\<le> stp')\"\n      by(simp add: step_red, \n          cases \"steps0 (Suc 0, Bk\\<up> l, <lm>) tp stp\", simp, \n          cases \"fst (steps0 (Suc 0, Bk\\<up> l, <lm>) tp stp)\",\n          auto simp add: nonstop_t_eq intro:ind dest:nonstop_t_eq)\n  qed    \n\nlemma conf_trpl_ex: \"\\<exists> p q r. conf m (bl2wc (<lm>)) stp = trpl p q r\"\n  apply(induct stp, auto simp: conf.simps inpt.simps trpl.simps \n      newconf.simps)\n  apply(rule_tac x = 0 in exI, rule_tac x = 1 in exI, \n      rule_tac x = \"bl2wc (<lm>)\" in exI)\n  apply(simp)\n  done\n\nlemma nonstop_rgt_ex: \n  \"nonstop m (bl2wc (<lm>)) stpa = 0 \\<Longrightarrow> \\<exists> r. conf m (bl2wc (<lm>)) stpa = trpl 0 0 r\"\n  apply(auto simp: nonstop.simps NSTD.simps split: if_splits)\n  using conf_trpl_ex[of m lm stpa]\n  apply(auto)\n  done\n\nlemma max_divisors: \"x > Suc 0 \\<Longrightarrow> Max {u. x ^ u dvd x ^ r} = r\"\nproof(rule_tac Max_eqI)\n  assume \"x > Suc 0\"\n  thus \"finite {u. x ^ u dvd x ^ r}\"\n    apply(rule_tac finite_power_dvd, auto)\n    done\nnext\n  fix y \n  assume \"Suc 0 < x\" \"y \\<in> {u. x ^ u dvd x ^ r}\"\n  thus \"y \\<le> r\"\n    apply(cases \"y\\<le> r\", simp)\n    apply(subgoal_tac \"\\<exists> d. y = r + d\")\n     apply(auto simp: power_add)\n    apply(rule_tac x = \"y - r\" in exI, simp)\n    done\nnext\n  show \"r \\<in> {u. x ^ u dvd x ^ r}\" by simp\nqed  \n\nlemma lo_power:\n  assumes \"x > Suc 0\" shows \"lo (x ^ r) x = r\"\nproof -\n  have \"\\<not> Suc 0 < x ^ r \\<Longrightarrow> r = 0\" using assms\n    by (metis Suc_lessD Suc_lessI nat_power_eq_Suc_0_iff zero_less_power)\n  moreover have \"\\<forall>xa. \\<not> x ^ xa dvd x ^ r \\<Longrightarrow> r = 0\"\n    using dvd_refl assms by(cases \"x^r\";blast)\n  ultimately show ?thesis using assms\n    by(auto simp: lo.simps loR.simps mod_dvd_simp elim:max_divisors)\nqed\n\nlemma lo_rgt: \"lo (trpl 0 0 r) (Pi 2) = r\"\n  apply(simp add: trpl.simps lo_power)\n  done\n\nlemma conf_keep: \n  \"conf m lm stp = trpl 0 0 r  \\<Longrightarrow>\n  conf m lm (stp + n) = trpl 0 0 r\"\n  apply(induct n)\n   apply(auto simp: conf.simps  newconf.simps newleft.simps \n      newrght.simps rght.simps lo_rgt)\n  done\n\nlemma halt_state_keep_steps_add:\n  \"\\<lbrakk>nonstop m (bl2wc (<lm>)) stpa = 0\\<rbrakk> \\<Longrightarrow> \n  conf m (bl2wc (<lm>)) stpa = conf m (bl2wc (<lm>)) (stpa + n)\"\n  apply(drule_tac nonstop_rgt_ex, auto simp: conf_keep)\n  done\n\nlemma halt_state_keep: \n  \"\\<lbrakk>nonstop m (bl2wc (<lm>)) stpa = 0; nonstop m (bl2wc (<lm>)) stpb = 0\\<rbrakk> \\<Longrightarrow>\n  conf m (bl2wc (<lm>)) stpa = conf m (bl2wc (<lm>)) stpb\"\n  apply(cases \"stpa > stpb\")\n  using halt_state_keep_steps_add[of m lm stpb \"stpa - stpb\"] \n   apply simp\n  using halt_state_keep_steps_add[of m lm stpa \"stpb - stpa\"]\n  apply(simp)\n  done\n\nsection \\<open>Correctness of rec\\_F with respect to execution of TMs compiled as Recursive Functions\\<close>\n\ntext \\<open>\n  The correctness of \\<open>rec_F\\<close>, which relates the interpreter function \\<open>rec_F\\<close> with the\n  execution of TMs.\n\\<close>\n\nlemma terminate_halt: \n  \"\\<lbrakk>steps0 (Suc 0, Bk\\<up>l, <lm>) tp stp = (0, Bk\\<up>m, Oc\\<up>rs@Bk\\<up>n); \n    composable_tm (tp,0); 0<rs\\<rbrakk> \\<Longrightarrow> terminate rec_halt [code tp, (bl2wc (<lm>))]\"\n  by(frule_tac halt_least_step;force simp:nonstop_lemma intro:terminate_halt_lemma)\n\nlemma terminate_F: \n  \"\\<lbrakk>steps0 (Suc 0, Bk\\<up>l, <lm>) tp stp = (0, Bk\\<up>m, Oc\\<up>rs@Bk\\<up>n); \n    composable_tm (tp,0); 0<rs\\<rbrakk> \\<Longrightarrow> terminate rec_F [code tp, (bl2wc (<lm>))]\"\n  apply(drule_tac terminate_halt, simp_all)\n  apply(erule_tac terminate_F_lemma)\n  done\n\nlemma F_correct: \n  \"\\<lbrakk>steps0 (Suc 0, Bk\\<up>l, <lm>) tp stp = (0, Bk\\<up>m, Oc\\<up>rs@Bk\\<up>n); \n    composable_tm (tp,0); 0<rs\\<rbrakk>\n   \\<Longrightarrow> rec_exec rec_F [code tp, (bl2wc (<lm>))] = (rs - Suc 0)\"\n  apply(frule_tac halt_least_step, auto)\n  apply(frule_tac  nonstop_t_eq, auto simp: nonstop_lemma)\n  using rec_t_eq_steps[of tp l lm stp]\n  apply(simp add: conf_lemma)\nproof -\n  fix stpa\n  assume h: \n    \"nonstop (code tp) (bl2wc (<lm>)) stpa = 0\" \n    \"\\<forall>stp'. nonstop (code tp) (bl2wc (<lm>)) stp' = 0 \\<longrightarrow> stpa \\<le> stp'\" \n    \"nonstop (code tp) (bl2wc (<lm>)) stp = 0\" \n    \"trpl_code (0, Bk\\<up> m, Oc\\<up> rs @ Bk\\<up> n) = conf (code tp) (bl2wc (<lm>)) stp\"\n    \"steps0 (Suc 0, Bk\\<up> l, <lm>) tp stp = (0, Bk\\<up> m, Oc\\<up> rs @ Bk\\<up> n)\"\n  hence g1: \"conf (code tp) (bl2wc (<lm>)) stpa = trpl_code (0, Bk\\<up> m, Oc\\<up> rs @ Bk\\<up>n)\"\n    using halt_state_keep[of \"code tp\" lm stpa stp]\n    by(simp)\n  moreover have g2:\n    \"rec_exec rec_halt [code tp, (bl2wc (<lm>))] = stpa\"\n    using h\n    by(auto simp: rec_exec.simps rec_halt_def nonstop_lemma intro!: Least_equality)\n  show  \n    \"rec_exec rec_F [code tp, (bl2wc (<lm>))] = (rs - Suc 0)\"\n  proof -\n    have \n      \"valu (rght (conf (code tp) (bl2wc (<lm>)) stpa)) = rs - Suc 0\" \n      using g1 \n      apply(simp add: valu.simps trpl_code.simps \n          bl2wc.simps  bl2nat_append lg_power)\n      done\n    thus \"?thesis\" \n      by(simp add: rec_exec.simps F_lemma g2)\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/Universal_Turing_Machine/UF.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8947894717137997, "lm_q2_score": 0.8311430478583168, "lm_q1q2_score": 0.7436980487117407}}
{"text": " theory Submission\n  imports Defs\nbegin\n\nlemma modpower5: fixes n :: nat\n  shows \"n mod 10 = (n ^ 5) mod 10\"\nproof -\n  have *: \"m ^ 5 mod 10 = m\" if \"m < 10\" for m :: nat\n  proof -\n    have \"m \\<in> {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}\"\n      using that by auto\n    thus ?thesis by auto\n  qed\n  have \"(n mod 10) ^ 5 mod 10 = n mod 10\"\n    by (intro *) auto\n  thus ?thesis by (subst (asm) power_mod) auto\nqed\n\nend\n", "meta": {"author": "maxhaslbeck", "repo": "ProvingForFun-July2019", "sha": "ea3cf3a41168da50e785621c4ee6612895bdf599", "save_path": "github-repos/isabelle/maxhaslbeck-ProvingForFun-July2019", "path": "github-repos/isabelle/maxhaslbeck-ProvingForFun-July2019/ProvingForFun-July2019-ea3cf3a41168da50e785621c4ee6612895bdf599/mod5/isabelle/haslbema/Submission.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009573133051, "lm_q2_score": 0.8128673155708975, "lm_q1q2_score": 0.7436930851845106}}
{"text": "(*  \n    Title:      Gauss_Jordan.thy\n    Author:     Jose Divas\u00f3n <jose.divasonm at unirioja.es>\n    Author:     Jes\u00fas Aransay <jesus-maria.aransay at unirioja.es>\n*)\n\nheader{*Gauss Jordan algorithm over abstract matrices*}\n\ntheory Gauss_Jordan\nimports\n  Rref\n  Elementary_Operations\n  Rank  \nbegin\n\nsubsection{*The Gauss-Jordan Algorithm*}\n\ntext{* Now, a computable version of the Gauss-Jordan algorithm is presented. The output will be a matrix in reduced row echelon form.\nWe present an algorithm in which the reduction is applied by columns*}\n\ntext{*Using this definition, zeros are made in the column j of a matrix A placing the pivot entry (a nonzero element) in the position (i,j).\nFor that, a suitable row interchange is made to achieve a non-zero entry in position (i,j). Then, this pivot entry is multiplied by its inverse\nto make the pivot entry equals to 1. After that, are other entries of the j-th column are eliminated by subtracting suitable multiples of the\ni-th row from the other rows.*}\n\ndefinition Gauss_Jordan_in_ij :: \"'a::{semiring_1, inverse, one, uminus}^'m^'n::{finite, ord}=> 'n=>'m=>'a^'m^'n::{finite, ord}\"\nwhere \"Gauss_Jordan_in_ij A i j = (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 \n                                vec_lambda(% s. if s=i then A' $ s else (row_add A' s i (-(interchange_A$s$j))) $ s))\"\n\ntext{*The following definition makes the step of Gauss-Jordan in a column. This function receives two input parameters: the column k\nwhere the step of Gauss-Jordan must be applied and a pair (which consists of the row where the pivot should be placed in the column k and the original matrix).*}\n\ndefinition Gauss_Jordan_column_k :: \"(nat \\<times> ('a::{zero,inverse,uminus,semiring_1}^'m::{mod_type}^'n::{mod_type})) \n=> nat => (nat \\<times> ('a^'m::{mod_type}^'n::{mod_type}))\"\nwhere \"Gauss_Jordan_column_k A' k = (let i=fst A'; A=(snd A'); from_nat_i=(from_nat i::'n); from_nat_k=(from_nat k::'m) in \n        if (\\<forall>m\\<ge>(from_nat_i). A $ m $(from_nat_k)=0) \\<or> (i = nrows A) then (i,A) else (i+1, (Gauss_Jordan_in_ij A (from_nat_i) (from_nat_k))))\"\n\ntext{*The following definition applies the Gauss-Jordan step from the first column up to the k one (included).*}\n\ndefinition Gauss_Jordan_upt_k :: \"'a::{inverse,uminus,semiring_1}^'columns::{mod_type}^'rows::{mod_type} => nat \n=> 'a^'columns::{mod_type}^'rows::{mod_type}\"\n where \"Gauss_Jordan_upt_k A k = snd (foldl Gauss_Jordan_column_k (0,A) [0..<Suc k])\"\n\ntext{*Gauss-Jordan is to apply the @{term \"Gauss_Jordan_column_k\"} in all columns.*}\ndefinition Gauss_Jordan :: \"'a::{inverse,uminus,semiring_1}^'columns::{mod_type}^'rows::{mod_type}  \n=> 'a^'columns::{mod_type}^'rows::{mod_type}\"\n where \"Gauss_Jordan A = Gauss_Jordan_upt_k A ((ncols A) - 1)\"\n\n\nsubsection{*Properties about rref and the greatest nonzero row.*}\n\nlemma greatest_plus_one_eq_0:\n  fixes A::\"'a::{field}^'columns::{mod_type}^'rows::{mod_type}\" and k::nat\n  assumes \"Suc (to_nat (GREATEST' n. \\<not> is_zero_row_upt_k n k A)) = nrows A\"\n  shows \"(GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1 = 0\"\nproof -\n  have \"to_nat (GREATEST' R. \\<not> is_zero_row_upt_k R k A) + 1 = card (UNIV\\<Colon>'rows set)\"\n    using assms unfolding nrows_def by fastforce\n  thus \"(GREATEST' n. \\<not> is_zero_row_upt_k n k A) + (1\\<Colon>'rows) = (0\\<Colon>'rows)\"\n    using to_nat_plus_one_less_card by fastforce\nqed\n\nlemma from_nat_to_nat_greatest:\n  fixes A::\"'a::{zero}^'columns::{mod_type}^'rows::{mod_type}\"\n  shows \"from_nat (Suc (to_nat (GREATEST' n. \\<not> is_zero_row_upt_k n k A))) = (GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1\"\n  unfolding Suc_eq_plus1\n  unfolding to_nat_1[where ?'a='rows, symmetric]\n  unfolding add_to_nat_def ..\n\nlemma greatest_less_zero_row:\n  fixes A::\"'a::{one, zero}^'n::{mod_type}^'m::{finite,one,plus,linorder}\"\n  assumes r: \"reduced_row_echelon_form_upt_k A k\"\n  and zero_i: \"is_zero_row_upt_k i k A\"\n  and not_all_zero: \"\\<not> (\\<forall>a. is_zero_row_upt_k a k A)\"\n  shows \"(GREATEST' m. \\<not> is_zero_row_upt_k m k A) < i\"\nproof (rule ccontr)\n  assume not_less_i: \"\\<not> (GREATEST' m. \\<not> is_zero_row_upt_k m k A) < i\"\n  have i_less_greatest: \"i < (GREATEST' m. \\<not> is_zero_row_upt_k m k A)\"\n    by (metis not_less_i dual_linorder.neq_iff Greatest'I not_all_zero zero_i)\n  have \"is_zero_row_upt_k (GREATEST' m. \\<not> is_zero_row_upt_k m k A) k A\"\n    using r zero_i i_less_greatest unfolding reduced_row_echelon_form_upt_k_def by blast\n  thus False using Greatest'I_ex not_all_zero by fast\nqed\n\nlemma rref_suc_if_zero_below_greatest:\n  fixes A::\"'a::{one, zero}^'n::{mod_type}^'m::{finite,one,plus,linorder}\"\n  assumes r: \"reduced_row_echelon_form_upt_k A k\"\n  and not_all_zero: \"\\<not> (\\<forall>a. is_zero_row_upt_k a k A)\" (*This premisse is necessary to assure the existence of the Greatest*)\n  and all_zero_below_greatest: \"\\<forall>a. a>(GREATEST' m. \\<not> is_zero_row_upt_k m k A) \\<longrightarrow> is_zero_row_upt_k a (Suc k) A\"\n  shows \"reduced_row_echelon_form_upt_k A (Suc k)\"\nproof (rule reduced_row_echelon_form_upt_k_intro, auto)\n  fix i j assume zero_i_suc: \"is_zero_row_upt_k i (Suc k) A\" and i_le_j: \"i < j\"\n  have zero_i: \"is_zero_row_upt_k i k A\" using zero_i_suc unfolding is_zero_row_upt_k_def by simp\n  have \"i>(GREATEST' m. \\<not> is_zero_row_upt_k m k A)\" by (rule greatest_less_zero_row[OF r zero_i not_all_zero])\n  hence \"j>(GREATEST' m. \\<not> is_zero_row_upt_k m k A)\" using i_le_j by simp\n  thus \"is_zero_row_upt_k j (Suc k) A\" using all_zero_below_greatest by fast\nnext\n  fix i assume not_zero_i: \"\\<not> is_zero_row_upt_k i (Suc k) A\"\n  show \"A $ i $ (LEAST k. A $ i $ k \\<noteq> 0) = 1\" \n    using  greatest_less_zero_row[OF r _ not_all_zero] not_zero_i r all_zero_below_greatest\n    unfolding reduced_row_echelon_form_upt_k_def \n    by fast\nnext\n  fix i\n  assume i: \"i < i + 1\" and not_zero_i: \"\\<not> is_zero_row_upt_k i (Suc k) A\" and not_zero_suc_i: \"\\<not> is_zero_row_upt_k (i + 1) (Suc k) A\"\n  have not_zero_i_k: \"\\<not> is_zero_row_upt_k i k A\"\n  using all_zero_below_greatest greatest_less_zero_row[OF r _ not_all_zero] not_zero_i by blast\n  have not_zero_suc_i: \"\\<not> is_zero_row_upt_k (i+1) k A\"\n     using all_zero_below_greatest greatest_less_zero_row[OF r _ not_all_zero] not_zero_suc_i by blast\n  have aux:\"(\\<forall>i j. i + 1 = j \\<and> i < j \\<and> \\<not> is_zero_row_upt_k i k A \\<and> \\<not> is_zero_row_upt_k j k A \\<longrightarrow> (LEAST n. A $ i $ n \\<noteq> 0) < (LEAST n. A $ j $ n \\<noteq> 0))\"\n    using r unfolding reduced_row_echelon_form_upt_k_def by fast\n  show \"(LEAST n. A $ i $ n \\<noteq> 0) < (LEAST n. A $ (i + 1) $ n \\<noteq> 0)\" using aux not_zero_i_k not_zero_suc_i i by simp\nnext\n  fix i j assume \"\\<not> is_zero_row_upt_k i (Suc k) A\" and \"i \\<noteq> j\"\n  thus \"A $ j $ (LEAST n. A $ i $ n \\<noteq> 0) = 0\"\n    using all_zero_below_greatest greatest_less_zero_row not_all_zero r rref_upt_condition4 by blast\nqed\n\nlemma rref_suc_if_all_rows_not_zero:\n  fixes A::\"'a::{one, zero}^'n::{mod_type}^'m::{finite,one,plus,linorder}\"\n  assumes r: \"reduced_row_echelon_form_upt_k A k\"\n  and all_not_zero: \"\\<forall>n. \\<not> is_zero_row_upt_k n k A\"\n  shows \"reduced_row_echelon_form_upt_k A (Suc k)\"\nproof (rule rref_suc_if_zero_below_greatest)\n  show \"reduced_row_echelon_form_upt_k A k\" using r .\n  show \"\\<not> (\\<forall>a. is_zero_row_upt_k a k A)\" using all_not_zero by auto\n  show \"\\<forall>a>GREATEST' m. \\<not> is_zero_row_upt_k m k A. is_zero_row_upt_k a (Suc k) A\"\n    using all_not_zero not_greater_Greatest' by blast\nqed\n\n\nlemma greatest_ge_nonzero_row:\n  fixes A::\"'a::{zero}^'n::{mod_type}^'m::{finite,linorder}\"\n  assumes \"\\<not> is_zero_row_upt_k i k A\"\n  shows \"i \\<le> (GREATEST' m. \\<not> is_zero_row_upt_k m k A)\" using Greatest'_ge[of \"(\\<lambda>m. \\<not> is_zero_row_upt_k m k A)\", OF assms] .\n\nlemma greatest_ge_nonzero_row':\n  fixes A::\"'a::{zero, one}^'n::{mod_type}^'m::{finite, linorder, one, plus}\"\n  assumes r: \"reduced_row_echelon_form_upt_k A k\"\n  and i: \"i \\<le> (GREATEST' m. \\<not> is_zero_row_upt_k m k A)\"\n  and not_all_zero: \"\\<not> (\\<forall>a. is_zero_row_upt_k a k A)\"\n  shows \"\\<not> is_zero_row_upt_k i k A\"\n  using greatest_less_zero_row[OF r] i not_all_zero by fastforce\n\ncorollary row_greater_greatest_is_zero:\n  fixes A::\"'a::{zero}^'n::{mod_type}^'m::{finite,linorder}\"\n  assumes \"(GREATEST' m. \\<not> is_zero_row_upt_k m k A) < i\"\n  shows \"is_zero_row_upt_k i k A\" using greatest_ge_nonzero_row assms by fastforce\n\nsubsection{*The proof of its correctness*}\n\ntext{*Properties of @{term \"Gauss_Jordan_in_ij\"}*}\n\nlemma Gauss_Jordan_in_ij_1:\n  fixes A::\"'a::{field}^'m^'n::{finite, ord, wellorder}\"\n  assumes ex: \"\\<exists>n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n\"\n  shows \"(Gauss_Jordan_in_ij A i j) $ i $ j = 1\"\nproof (unfold Gauss_Jordan_in_ij_def Let_def mult_row_def interchange_rows_def, vector, rule divide_self)\n  obtain n where Anj: \"A $ n $ j \\<noteq> 0 \\<and> i \\<le> n\" using ex by blast\n  show \"A $ (LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n) $ j \\<noteq> 0\" using LeastI[of \"\\<lambda>n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n\" n, OF Anj] by simp \nqed\n\nlemma Gauss_Jordan_in_ij_0:\n  fixes A::\"'a::{field}^'m^'n::{finite, ord, wellorder}\"\n  assumes ex: \"\\<exists>n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n\" and a: \"a \\<noteq> i\"\n  shows \"(Gauss_Jordan_in_ij A i j) $ a $ j = 0\"\nproof (unfold Gauss_Jordan_in_ij_def Let_def mult_row_def interchange_rows_def row_add_def, auto simp add: a)\n  obtain n where Anj: \"A $ n $ j \\<noteq> 0 \\<and> i \\<le> n\" using ex by blast\n  have A_least: \"A $ (LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n) $ j \\<noteq> 0\" using LeastI[of \"\\<lambda>n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n\" n, OF Anj] by simp \n  thus \"A $ i $ j = A $ i $ j * A $ (LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n) $ j / A $ (LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n) $ j\" by fastforce\n  assume \"a \\<noteq> (LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n)\"\n  thus \"A $ a $ j = A $ a $ j * A $ (LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n) $ j / A $ (LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n) $ j\" \n    using A_least by fastforce\nqed\n\ncorollary Gauss_Jordan_in_ij_0':\n  fixes A::\"'a::{field}^'m^'n::{finite, ord, wellorder}\"\n  assumes ex: \"\\<exists>n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n\"\n  shows \"\\<forall>a. a \\<noteq> i \\<longrightarrow> (Gauss_Jordan_in_ij A i j) $ a $ j = 0\" using assms Gauss_Jordan_in_ij_0 by blast\n\nlemma Gauss_Jordan_in_ij_preserves_previous_elements:\n  fixes A::\"'a::{field}^'columns::{mod_type}^'rows::{mod_type}\"\n  assumes r: \"reduced_row_echelon_form_upt_k A k\"\n  and not_zero_a: \"\\<not> is_zero_row_upt_k a k A\"\n  and exists_m: \"\\<exists>m. A $ m $ (from_nat k) \\<noteq> 0 \\<and> (GREATEST' m. \\<not> is_zero_row_upt_k m k A) + 1 \\<le> m\"\n  and Greatest_plus_1: \"(GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1 \\<noteq> 0\"\n  and j_le_k: \"to_nat j < k\"\n  shows \"Gauss_Jordan_in_ij A ((GREATEST' m. \\<not> is_zero_row_upt_k m k A) + 1) (from_nat k) $ i $ j = A $ i $ j\"\nproof (unfold Gauss_Jordan_in_ij_def Let_def interchange_rows_def mult_row_def row_add_def, auto)\n  def last_nonzero_row == \"(GREATEST' m. \\<not> is_zero_row_upt_k m k A)\"\n  have \"last_nonzero_row < (last_nonzero_row + 1)\" by (rule  Suc_le'[of last_nonzero_row], auto simp add: last_nonzero_row_def Greatest_plus_1)  \n  hence zero_row: \"is_zero_row_upt_k (last_nonzero_row + 1) k A\"\n    using not_le greatest_ge_nonzero_row last_nonzero_row_def by fastforce\n  hence A_greatest_0: \"A $ (last_nonzero_row + 1) $ j = 0\" unfolding is_zero_row_upt_k_def last_nonzero_row_def using j_le_k by auto\n  thus  \"A $ (last_nonzero_row + 1) $ j / A $ (last_nonzero_row + 1) $ from_nat k = A $ (last_nonzero_row + 1) $ j\"\n    by simp\n  have zero: \"A $ (LEAST n. A $ n $ from_nat k \\<noteq> 0 \\<and> (GREATEST' m. \\<not> is_zero_row_upt_k m k A) + 1 \\<le> n) $ j = 0\"\n  proof -\n    def least_n \\<equiv> \"(LEAST n. A $ n $ from_nat k \\<noteq> 0 \\<and> (GREATEST' m. \\<not> is_zero_row_upt_k m k A) + 1 \\<le> n)\"\n    have \"\\<exists>n. A $ n $ from_nat k \\<noteq> 0 \\<and> (GREATEST' m. \\<not> is_zero_row_upt_k m k A) + 1 \\<le> n\" by (metis exists_m)\n    from this obtain n where n1: \"A $ n $ from_nat k \\<noteq> 0\"  and n2: \"(GREATEST' m. \\<not> is_zero_row_upt_k m k A) + 1 \\<le> n\" by blast\n    have \"(GREATEST' m. \\<not> is_zero_row_upt_k m k A) + 1 \\<le> least_n\"\n      by (metis (lifting, full_types) LeastI_ex least_n_def n1 n2)\n    hence \"is_zero_row_upt_k least_n k A\" using last_nonzero_row_def less_le rref_upt_condition1[OF r] zero_row by metis\n    thus \"A $ least_n $ j = 0\" unfolding is_zero_row_upt_k_def using j_le_k by simp\n  qed\n  show \"A $ ((GREATEST' m. \\<not> is_zero_row_upt_k m k A) + 1) $ j -\n    A $ ((GREATEST' m. \\<not> is_zero_row_upt_k m k A) + 1) $ from_nat k *\n    A $ (LEAST n. A $ n $ from_nat k \\<noteq> 0 \\<and> (GREATEST' m. \\<not> is_zero_row_upt_k m k A) + 1 \\<le> n) $ j /\n    A $ (LEAST n. A $ n $ from_nat k \\<noteq> 0 \\<and> (GREATEST' m. \\<not> is_zero_row_upt_k m k A) + 1 \\<le> n) $ from_nat k =\n    A $ (LEAST n. A $ n $ from_nat k \\<noteq> 0 \\<and> (GREATEST' m. \\<not> is_zero_row_upt_k m k A) + 1 \\<le> n) $ j\"\n    unfolding last_nonzero_row_def[symmetric] unfolding A_greatest_0 unfolding last_nonzero_row_def unfolding zero by fastforce\n  show \"A $ (LEAST n. A $ n $ from_nat k \\<noteq> 0 \\<and> (GREATEST' m. \\<not> is_zero_row_upt_k m k A) + 1 \\<le> n) $ j /\n    A $ (LEAST n. A $ n $ from_nat k \\<noteq> 0 \\<and> (GREATEST' m. \\<not> is_zero_row_upt_k m k A) + 1 \\<le> n) $ from_nat k =\n    A $ ((GREATEST' m. \\<not> is_zero_row_upt_k m k A) + 1) $ j\" unfolding zero using A_greatest_0 unfolding last_nonzero_row_def by simp\n  show \"A $ i $ from_nat k * A $ (LEAST n. A $ n $ from_nat k \\<noteq> 0 \\<and> (GREATEST' m. \\<not> is_zero_row_upt_k m k A) + 1 \\<le> n) $ j /\n    A $ (LEAST n. A $ n $ from_nat k \\<noteq> 0 \\<and> (GREATEST' m. \\<not> is_zero_row_upt_k m k A) + 1 \\<le> n) $ from_nat k =\n    0\" unfolding zero by auto\nqed\n\n\n\nlemma Gauss_Jordan_in_ij_preserves_previous_elements':\n  fixes A::\"'a::{field}^'columns::{mod_type}^'rows::{mod_type}\"\n  assumes all_zero: \"\\<forall>n. is_zero_row_upt_k n k A\"\n  and j_le_k: \"to_nat j < k\"\n  and A_nk_not_zero: \"A $ n $ (from_nat k) \\<noteq> 0\"\n  shows \"Gauss_Jordan_in_ij A 0 (from_nat k) $ i $ j = A $ i $ j\"\nproof (unfold Gauss_Jordan_in_ij_def Let_def mult_row_def interchange_rows_def row_add_def, auto)\n  have A_0_j: \"A $ 0 $ j = 0\"  using all_zero is_zero_row_upt_k_def j_le_k by blast\n  thus \"A $ 0 $ j / A $ 0 $ from_nat k = A $ 0 $ j\" by simp\n  have A_least_j: \"A $ (LEAST n. A $ n $ from_nat k \\<noteq> 0 \\<and> 0 \\<le> n) $ j = 0\" using all_zero is_zero_row_upt_k_def j_le_k by blast\n  show \"A $ 0 $ j -\n    A $ 0 $ from_nat k * A $ (LEAST n. A $ n $ from_nat k \\<noteq> 0 \\<and> 0 \\<le> n) $ j /\n    A $ (LEAST n. A $ n $ from_nat k \\<noteq> 0 \\<and> 0 \\<le> n) $ from_nat k =\n    A $ (LEAST n. A $ n $ from_nat k \\<noteq> 0 \\<and> 0 \\<le> n) $ j\" unfolding A_0_j A_least_j by fastforce\n  show \"A $ (LEAST n. A $ n $ from_nat k \\<noteq> 0 \\<and> 0 \\<le> n) $ j / A $ (LEAST n. A $ n $ from_nat k \\<noteq> 0 \\<and> 0 \\<le> n) $ from_nat k = A $ 0 $ j\"\n    unfolding A_least_j A_0_j by simp\n  show \"A $ i $ from_nat k * A $ (LEAST n. A $ n $ from_nat k \\<noteq> 0 \\<and> 0 \\<le> n) $ j /\n    A $ (LEAST n. A $ n $ from_nat k \\<noteq> 0 \\<and> 0 \\<le> n) $ from_nat k = 0\"\n    unfolding A_least_j by simp\nqed\n\nlemma is_zero_after_Gauss:\n  fixes A::\"'a::{field}^'n::{mod_type}^'m::{mod_type}\"\n  assumes zero_a: \"is_zero_row_upt_k a k A\"\n  and not_zero_m: \"\\<not> is_zero_row_upt_k m k A\"\n  and r: \"reduced_row_echelon_form_upt_k A k\"\n  and greatest_less_ma: \"(GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1 \\<le> ma\"\n  and A_ma_k_not_zero: \"A $ ma $ from_nat k \\<noteq> 0\"\n  shows \"is_zero_row_upt_k a k (Gauss_Jordan_in_ij A ((GREATEST' m. \\<not> is_zero_row_upt_k m k A) + 1) (from_nat k))\"\nproof (subst is_zero_row_upt_k_def, clarify)\n  fix j::'n assume j_less_k: \"to_nat j < k\"\n  have not_zero_g: \"(GREATEST' m. \\<not> is_zero_row_upt_k m k A) + 1 \\<noteq> 0\"\n  proof (rule ccontr, simp)\n    assume \"(GREATEST' m. \\<not> is_zero_row_upt_k m k A) + 1 = 0\"\n    hence \"(GREATEST' m. \\<not> is_zero_row_upt_k m k A) = -1\" using a_eq_minus_1 by blast\n    hence \"a\\<le>(GREATEST' m. \\<not> is_zero_row_upt_k m k A)\" using Greatest_is_minus_1 by auto\n    hence \"\\<not> is_zero_row_upt_k a k A\" using greatest_less_zero_row[OF r] not_zero_m by fastforce\n    thus False using zero_a by contradiction\n  qed\n  have \"Gauss_Jordan_in_ij A ((GREATEST' m. \\<not> is_zero_row_upt_k m k A) + 1) (from_nat k) $ a $ j = A $ a $ j\"\n    by (rule Gauss_Jordan_in_ij_preserves_previous_elements[OF r not_zero_m _ not_zero_g j_less_k], auto intro!: A_ma_k_not_zero greatest_less_ma)\n  also have \"... = 0\" \n    using zero_a j_less_k unfolding is_zero_row_upt_k_def by blast\n  finally show \"Gauss_Jordan_in_ij A ((GREATEST' m. \\<not> is_zero_row_upt_k m k A) + 1) (from_nat k) $ a $ j = 0\" .\nqed\n\n\nlemma all_zero_imp_Gauss_Jordan_column_not_zero_in_row_0:\n  fixes A::\"'a::{field}^'columns::{mod_type}^'rows::{mod_type}\" and k::nat\n  defines ia:\"ia\\<equiv>(if \\<forall>m. is_zero_row_upt_k m k A then 0 else to_nat (GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1)\"\n  defines B:\"B\\<equiv>(snd (Gauss_Jordan_column_k (ia,A) k))\"\n  assumes all_zero: \"\\<forall>n. is_zero_row_upt_k n k A\"\n  and not_zero_i: \"\\<not> is_zero_row_upt_k i (Suc k) B\"\n  and Amk_zero: \"A $ m $ from_nat k \\<noteq> 0\"\n  shows \"i=0\"\nproof (rule ccontr)\n  assume i_not_0: \"i \\<noteq> 0\"\n  have ia2: \"ia = 0\" using ia all_zero by simp\n  have B_eq_Gauss: \"B = Gauss_Jordan_in_ij A 0 (from_nat k)\"\n    unfolding B Gauss_Jordan_column_k_def Let_def fst_conv snd_conv ia2 \n    using all_zero Amk_zero least_mod_type unfolding from_nat_0 nrows_def by auto\n  also have \"...$ i $ (from_nat k) = 0\" proof (rule Gauss_Jordan_in_ij_0)\n    show \"\\<exists>n. A $ n $ from_nat k \\<noteq> 0 \\<and> 0 \\<le> n\" using Amk_zero least_mod_type by blast\n    show \"i \\<noteq> 0\" using i_not_0 .\n  qed\n  finally have \"B $ i $ from_nat k = 0\" .\n  hence \"is_zero_row_upt_k i (Suc k) B\"\n    unfolding B_eq_Gauss\n    using Gauss_Jordan_in_ij_preserves_previous_elements'[OF all_zero _ Amk_zero]\n    by (metis all_zero is_zero_row_upt_k_def less_SucE to_nat_from_nat)\n  thus False using not_zero_i by contradiction\nqed\n\ntext{*Here we start to prove that \n      the output of @{term \"Gauss Jordan A\"} is a matrix in reduced row echelon form.*}\n\nlemma condition_1_part_1:\n  fixes A::\"'a::{field}^'columns::{mod_type}^'rows::{mod_type}\" and k::nat\n  assumes zero_column_k: \"\\<forall>m\\<ge>from_nat 0. A $ m $ from_nat k = 0\"\n  and all_zero: \"\\<forall>m. is_zero_row_upt_k m k A\"\n  shows \"is_zero_row_upt_k j (Suc k) A\"\n  unfolding is_zero_row_upt_k_def apply clarify\nproof -\n  fix ja::'columns assume ja_less_suc_k: \"to_nat ja < Suc k\"\n  show \"A $ j $ ja = 0\"\n  proof (cases \"to_nat ja < k\")\n    case True thus ?thesis using all_zero unfolding is_zero_row_upt_k_def by blast\n  next\n    case False hence ja_eq_k: \"k = to_nat ja \" using ja_less_suc_k by simp\n    show ?thesis using zero_column_k unfolding ja_eq_k from_nat_to_nat_id from_nat_0 using least_mod_type by blast\n  qed\nqed\n\nlemma condition_1_part_2:\n  fixes A::\"'a::{field}^'columns::{mod_type}^'rows::{mod_type}\" and k::nat\n  assumes j_not_zero: \"j \\<noteq> 0\"\n  and all_zero: \"\\<forall>m. is_zero_row_upt_k m k A\" \n  and Amk_not_zero: \"A $ m $ from_nat k \\<noteq> 0\"\n  shows \"is_zero_row_upt_k j (Suc k) (Gauss_Jordan_in_ij A (from_nat 0) (from_nat k))\"\nproof (unfold is_zero_row_upt_k_def, clarify)\n  fix ja::'columns\n  assume ja_less_suc_k: \"to_nat ja < Suc k\"\n  show \"Gauss_Jordan_in_ij A (from_nat 0) (from_nat k) $ j $ ja = 0\"\n  proof (cases \"to_nat ja < k\")\n    case True \n    have \"Gauss_Jordan_in_ij A (from_nat 0) (from_nat k) $ j $ ja = A $ j $ ja\"\n      unfolding from_nat_0 using Gauss_Jordan_in_ij_preserves_previous_elements'[OF all_zero True Amk_not_zero] .\n    also have \"... = 0\" using all_zero True unfolding is_zero_row_upt_k_def by blast\n    finally show ?thesis .\n  next\n    case False hence k_eq_ja: \"k = to_nat ja\"\n      using ja_less_suc_k by simp\n    show \"Gauss_Jordan_in_ij A (from_nat 0) (from_nat k) $ j $ ja = 0\"\n      unfolding k_eq_ja from_nat_to_nat_id\n    proof (rule Gauss_Jordan_in_ij_0)\n      show \"\\<exists>n. A $ n $ ja \\<noteq> 0 \\<and> from_nat 0 \\<le> n\"\n        using least_mod_type Amk_not_zero\n        unfolding k_eq_ja from_nat_to_nat_id from_nat_0 by blast\n      show \"j \\<noteq> from_nat 0\" using j_not_zero unfolding from_nat_0 .\n    qed\n  qed\nqed\n\nlemma condition_1_part_3:\n  fixes A::\"'a::{field}^'columns::{mod_type}^'rows::{mod_type}\" and k::nat\n  defines ia:\"ia\\<equiv>(if \\<forall>m. is_zero_row_upt_k m k A then 0 else to_nat (GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1)\"\n  defines B:\"B \\<equiv>(snd (Gauss_Jordan_column_k (ia,A) k))\"\n  assumes rref: \"reduced_row_echelon_form_upt_k A k\"\n  and i_less_j: \"i<j\"\n  and not_zero_m: \"\\<not> is_zero_row_upt_k m k A\"\n  and zero_below_greatest: \"\\<forall>m\\<ge>(GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1. A $ m $ from_nat k = 0\"\n  and zero_i_suc_k: \"is_zero_row_upt_k i (Suc k) B\"\n  shows \"is_zero_row_upt_k j (Suc k) A\"\nproof (unfold is_zero_row_upt_k_def, auto)\n  fix ja::'columns\n  assume ja_less_suc_k: \"to_nat ja < Suc k\"\n  have ia2: \"ia=to_nat (GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1\" unfolding ia using not_zero_m by presburger\n  have B_eq_A: \"B=A\"\n    unfolding B Gauss_Jordan_column_k_def Let_def fst_conv snd_conv ia2\n    apply simp\n    unfolding from_nat_to_nat_greatest using zero_below_greatest by blast\n  have zero_ikA: \"is_zero_row_upt_k i k A\" using zero_i_suc_k unfolding B_eq_A is_zero_row_upt_k_def by fastforce\n  hence zero_jkA: \"is_zero_row_upt_k j k A\" using rref_upt_condition1[OF rref] i_less_j by blast\n  show \"A $ j $ ja = 0\"\n  proof (cases \"to_nat ja < k\")\n    case True\n    thus ?thesis using zero_jkA unfolding is_zero_row_upt_k_def by blast\n  next\n    case False\n    hence k_eq_ja:\"k = to_nat ja\" using ja_less_suc_k by auto\n    have \"(GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1 \\<le> j\"\n    proof (rule le_Suc, rule Greatest'I2)\n      show \"\\<not> is_zero_row_upt_k m k A\" using not_zero_m .\n      fix x assume not_zero_xkA: \"\\<not> is_zero_row_upt_k x k A\" show \"x < j\"\n        using rref_upt_condition1[OF rref] not_zero_xkA zero_jkA neq_iff by blast\n    qed     \n    thus ?thesis using zero_below_greatest unfolding k_eq_ja from_nat_to_nat_id is_zero_row_upt_k_def by blast\n  qed\nqed\n\nlemma condition_1_part_4:\n  fixes A::\"'a::{field}^'columns::{mod_type}^'rows::{mod_type}\" and k::nat\n  defines ia:\"ia\\<equiv>(if \\<forall>m. is_zero_row_upt_k m k A then 0 else to_nat (GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1)\"\n  defines B:\"B \\<equiv>(snd (Gauss_Jordan_column_k (ia,A) k))\"\n  assumes rref: \"reduced_row_echelon_form_upt_k A k\"\n  and zero_i_suc_k: \"is_zero_row_upt_k i (Suc k) B\" \n  and i_less_j: \"i<j\"\n  and not_zero_m: \"\\<not> is_zero_row_upt_k m k A\"\n  and greatest_eq_card: \"Suc (to_nat (GREATEST' n. \\<not> is_zero_row_upt_k n k A)) = nrows A\"\n  shows \"is_zero_row_upt_k j (Suc k) A\"\nproof -\n  have ia2: \"ia=to_nat (GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1\" unfolding ia using not_zero_m by presburger\n  have B_eq_A: \"B=A\"\n    unfolding B Gauss_Jordan_column_k_def Let_def fst_conv snd_conv ia2\n    unfolding from_nat_to_nat_greatest using greatest_eq_card nrows_def by force\n  have rref_Suc: \"reduced_row_echelon_form_upt_k A (Suc k)\" \n  proof (rule rref_suc_if_zero_below_greatest[OF rref])\n    show \"\\<forall>a>GREATEST' m. \\<not> is_zero_row_upt_k m k A. is_zero_row_upt_k a (Suc k) A\"\n      using greatest_eq_card not_less_eq to_nat_less_card to_nat_mono nrows_def by metis\n    show \"\\<not> (\\<forall>a. is_zero_row_upt_k a k A)\" using not_zero_m by fast\n  qed\n  show ?thesis using zero_i_suc_k unfolding B_eq_A using rref_upt_condition1[OF rref_Suc] i_less_j by fast\nqed\n\n\nlemma condition_1_part_5:\n  fixes A::\"'a::{field}^'columns::{mod_type}^'rows::{mod_type}\" and k::nat\n  defines ia:\"ia\\<equiv>(if \\<forall>m. is_zero_row_upt_k m k A then 0 else to_nat (GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1)\"\n  defines B:\"B \\<equiv>(snd (Gauss_Jordan_column_k (ia,A) k))\"\n  assumes rref: \"reduced_row_echelon_form_upt_k A k\"\n  and zero_i_suc_k: \"is_zero_row_upt_k i (Suc k) B\" \n  and i_less_j: \"i<j\"\n  and not_zero_m: \"\\<not> is_zero_row_upt_k m k A\"\n  and greatest_not_card: \"Suc (to_nat (GREATEST' n. \\<not> is_zero_row_upt_k n k A)) \\<noteq> nrows A\"\n  and greatest_less_ma: \"(GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1 \\<le> ma\"\n  and A_ma_k_not_zero: \"A $ ma $ from_nat k \\<noteq> 0\"\n  shows \"is_zero_row_upt_k j (Suc k) (Gauss_Jordan_in_ij A ((GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1) (from_nat k))\"\nproof (subst (1) is_zero_row_upt_k_def, clarify)\n  fix ja::'columns assume ja_less_suc_k: \"to_nat ja < Suc k\"\n  have ia2: \"ia=to_nat (GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1\" unfolding ia using not_zero_m by presburger\n  have B_eq_Gauss_ij: \"B = Gauss_Jordan_in_ij A ((GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1) (from_nat k)\"\n    unfolding B Gauss_Jordan_column_k_def \n    unfolding ia2 Let_def fst_conv snd_conv\n    using greatest_not_card greatest_less_ma A_ma_k_not_zero\n    by (auto simp add: from_nat_to_nat_greatest nrows_def)\n  have zero_ikA: \"is_zero_row_upt_k i k A\" \n  proof (unfold is_zero_row_upt_k_def, clarify)\n    fix a::'columns\n    assume a_less_k: \"to_nat a < k\"\n    have \"A $ i $ a = Gauss_Jordan_in_ij A ((GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1) (from_nat k) $ i $ a\" \n    proof (rule Gauss_Jordan_in_ij_preserves_previous_elements[symmetric])\n      show \"reduced_row_echelon_form_upt_k A k\" using rref .\n      show \"\\<not> is_zero_row_upt_k m k A\" using not_zero_m .\n      show \"\\<exists>n. A $ n $ from_nat k \\<noteq> 0 \\<and> (GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1 \\<le> n\" using A_ma_k_not_zero greatest_less_ma by blast\n      show \"(GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1 \\<noteq> 0\" using suc_not_zero greatest_not_card unfolding nrows_def by simp\n      show \"to_nat a < k\" using a_less_k .\n    qed\n    also have \"... = 0\" unfolding B_eq_Gauss_ij[symmetric] using zero_i_suc_k a_less_k unfolding is_zero_row_upt_k_def by simp\n    finally show \"A $ i $ a = 0\" .\n  qed\n  hence zero_jkA: \"is_zero_row_upt_k j k A\" using rref_upt_condition1[OF rref] i_less_j by blast\n  show \"Gauss_Jordan_in_ij A ((GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1) (from_nat k) $ j $ ja = 0\"\n  proof (cases \"to_nat ja < k\")\n    case True\n    have \"Gauss_Jordan_in_ij A ((GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1) (from_nat k) $ j $ ja = A $ j $ ja\" \n    proof (rule Gauss_Jordan_in_ij_preserves_previous_elements)\n      show \"reduced_row_echelon_form_upt_k A k\" using rref .\n      show \"\\<not> is_zero_row_upt_k m k A\" using not_zero_m .\n      show \"\\<exists>n. A $ n $ from_nat k \\<noteq> 0 \\<and> (GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1 \\<le> n\" using A_ma_k_not_zero greatest_less_ma by blast\n      show \"(GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1 \\<noteq> 0\" using suc_not_zero greatest_not_card unfolding nrows_def by simp       \n      show \"to_nat ja < k\" using True .\n    qed\n    also have \"... = 0\" using zero_jkA True unfolding is_zero_row_upt_k_def by fast\n    finally show ?thesis .\n  next\n    case False hence k_eq_ja: \"k = to_nat ja\" using ja_less_suc_k by simp\n    show ?thesis \n    proof (unfold k_eq_ja from_nat_to_nat_id, rule Gauss_Jordan_in_ij_0)\n      show \"\\<exists>n. A $ n $ ja \\<noteq> 0 \\<and> (GREATEST' n. \\<not> is_zero_row_upt_k n (to_nat ja) A) + 1 \\<le> n\"\n        using A_ma_k_not_zero greatest_less_ma k_eq_ja to_nat_from_nat by auto\n      show \"j \\<noteq> (GREATEST' n. \\<not> is_zero_row_upt_k n (to_nat ja) A) + 1\" \n      proof (unfold k_eq_ja[symmetric], rule ccontr)\n        assume \"\\<not> j \\<noteq> (GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1\"\n        hence j_eq: \"j = (GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1\" by fast\n        hence \"i < (GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1\" using i_less_j by force\n        hence i_le_greatest: \"i \\<le> (GREATEST' n. \\<not> is_zero_row_upt_k n k A)\" using le_Suc dual_linorder.not_less by auto\n        hence \"\\<not> is_zero_row_upt_k i k A\" using greatest_ge_nonzero_row'[OF rref] not_zero_m by fast\n        thus \"False\" using zero_ikA by contradiction\n      qed\n    qed\n  qed\nqed\n\n\nlemma condition_1:\n  fixes A::\"'a::{field}^'columns::{mod_type}^'rows::{mod_type}\" and k::nat\n  defines ia:\"ia\\<equiv>(if \\<forall>m. is_zero_row_upt_k m k A then 0 else to_nat (GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1)\"\n  defines B:\"B\\<equiv>(snd (Gauss_Jordan_column_k (ia,A) k))\"\n  assumes rref: \"reduced_row_echelon_form_upt_k A k\"\n  and zero_i_suc_k: \"is_zero_row_upt_k i (Suc k) B\" and i_less_j: \"i < j\"\n  shows \"is_zero_row_upt_k j (Suc k) B\"\nproof (unfold B Gauss_Jordan_column_k_def ia Let_def fst_conv snd_conv, auto, unfold from_nat_to_nat_greatest)\n  assume zero_k: \"\\<forall>m\\<ge>from_nat 0. A $ m $ from_nat k = 0\"  and all_zero: \"\\<forall>m. is_zero_row_upt_k m k A\"\n  show \"is_zero_row_upt_k j (Suc k) A\"\n    using condition_1_part_1[OF zero_k all_zero] .\nnext\n  fix m\n  assume all_zero: \"\\<forall>m. is_zero_row_upt_k m k A\" and Amk_not_zero: \"A $ m $ from_nat k \\<noteq> 0\"\n  have j_not_0: \"j \\<noteq> 0\" using i_less_j least_mod_type not_le by blast\n  show \"is_zero_row_upt_k j (Suc k) (Gauss_Jordan_in_ij A (from_nat 0) (from_nat k))\"\n    using condition_1_part_2[OF j_not_0 all_zero Amk_not_zero] .\nnext\n  fix m assume not_zero_mkA: \"\\<not> is_zero_row_upt_k m k A\"\n    and zero_below_greatest: \"\\<forall>m\\<ge>(GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1. A $ m $ from_nat k = 0\"\n  show \"is_zero_row_upt_k j (Suc k) A\" using condition_1_part_3[OF rref i_less_j not_zero_mkA zero_below_greatest] zero_i_suc_k\n    unfolding B ia .\nnext\n  fix m assume not_zero_m: \"\\<not> is_zero_row_upt_k m k A\"\n    and greatest_eq_card: \"Suc (to_nat (GREATEST' n. \\<not> is_zero_row_upt_k n k A)) =  nrows A\"\n  show \"is_zero_row_upt_k j (Suc k) A\"\n    using condition_1_part_4[OF rref _ i_less_j not_zero_m greatest_eq_card] zero_i_suc_k unfolding B ia nrows_def .\nnext\n  fix m ma\n  assume not_zero_m: \"\\<not> is_zero_row_upt_k m k A\"\n    and greatest_not_card: \"Suc (to_nat (GREATEST' n. \\<not> is_zero_row_upt_k n k A)) \\<noteq> nrows A\"\nand greatest_less_ma: \"(GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1 \\<le> ma\"\n    and A_ma_k_not_zero: \"A $ ma $ from_nat k \\<noteq> 0\"\n  show \"is_zero_row_upt_k j (Suc k) (Gauss_Jordan_in_ij A ((GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1) (from_nat k))\"\n    using condition_1_part_5[OF rref _ i_less_j not_zero_m greatest_not_card greatest_less_ma A_ma_k_not_zero]\n    using zero_i_suc_k\n    unfolding B ia .\nqed\n\n\n\nlemma condition_2_part_1:\n  fixes A::\"'a::{field}^'columns::{mod_type}^'rows::{mod_type}\" and k::nat\n  defines ia:\"ia\\<equiv>(if \\<forall>m. is_zero_row_upt_k m k A then 0 else to_nat (GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1)\"\n  defines B:\"B\\<equiv>(snd (Gauss_Jordan_column_k (ia,A) k))\"\n  assumes not_zero_i_suc_k: \"\\<not> is_zero_row_upt_k i (Suc k) B\"\n  and all_zero: \"\\<forall>m. is_zero_row_upt_k m k A\"\n  and all_zero_k: \"\\<forall>m. A $ m $ from_nat k = 0\"\n  shows \"A $ i $ (LEAST k. A $ i $ k \\<noteq> 0) = 1\"\nproof -\n  have ia2: \"ia = 0\" using ia all_zero by simp\n  have B_eq_A: \"B=A\" unfolding B Gauss_Jordan_column_k_def Let_def fst_conv snd_conv ia2 using all_zero_k by fastforce\n  show ?thesis  using all_zero_k condition_1_part_1[OF _ all_zero] not_zero_i_suc_k unfolding B_eq_A by presburger\nqed\n\n\nlemma condition_2_part_2:\n  fixes A::\"'a::{field}^'columns::{mod_type}^'rows::{mod_type}\" and k::nat\n  defines ia:\"ia\\<equiv>(if \\<forall>m. is_zero_row_upt_k m k A then 0 else to_nat (GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1)\"\n  defines B:\"B\\<equiv>(snd (Gauss_Jordan_column_k (ia,A) k))\"\n  assumes not_zero_i_suc_k: \"\\<not> is_zero_row_upt_k i (Suc k) B\"\n  and all_zero: \"\\<forall>m. is_zero_row_upt_k m k A\"\n  and Amk_not_zero: \"A $ m $ from_nat k \\<noteq> 0\"\n  shows \"Gauss_Jordan_in_ij A 0 (from_nat k) $ i $ (LEAST ka. Gauss_Jordan_in_ij A 0 (from_nat k) $ i $ ka \\<noteq> 0) = 1\"\nproof -\n  have ia2: \"ia = 0\" unfolding ia using all_zero by simp\n  have B_eq: \"B = Gauss_Jordan_in_ij A 0 (from_nat k)\" unfolding B Gauss_Jordan_column_k_def unfolding ia2 Let_def fst_conv snd_conv\n    using Amk_not_zero least_mod_type unfolding from_nat_0 nrows_def by auto\n  have i_eq_0: \"i=0\" using Amk_not_zero B_eq all_zero condition_1_part_2 from_nat_0 not_zero_i_suc_k by metis\n  have Least_eq: \"(LEAST ka. Gauss_Jordan_in_ij A 0 (from_nat k) $ i $ ka \\<noteq> 0) = from_nat k\"\n  proof (rule Least_equality)\n    have \"Gauss_Jordan_in_ij A 0 (from_nat k) $ 0 $ from_nat k = 1\" using Gauss_Jordan_in_ij_1 Amk_not_zero least_mod_type by blast\n    thus \"Gauss_Jordan_in_ij A 0 (from_nat k) $ i $ from_nat k \\<noteq> 0\" unfolding i_eq_0 by simp\n    fix y assume not_zero_gauss: \"Gauss_Jordan_in_ij A 0 (from_nat k) $ i $ y \\<noteq> 0\"\n    show \"from_nat k \\<le> y\"\n    proof (rule ccontr)\n      assume \"\\<not> from_nat k \\<le> y\" hence y: \"y < from_nat k\" by force\n      have \"Gauss_Jordan_in_ij A 0 (from_nat k) $ 0 $ y = A $ 0 $ y\"\n        by (rule Gauss_Jordan_in_ij_preserves_previous_elements'[OF all_zero to_nat_le[OF y] Amk_not_zero])\n      also have \"... = 0\" using all_zero to_nat_le[OF y] unfolding is_zero_row_upt_k_def by blast\n      finally show \"False\" using not_zero_gauss unfolding i_eq_0 by contradiction\n    qed\n  qed\n  show ?thesis unfolding Least_eq unfolding i_eq_0 by (rule Gauss_Jordan_in_ij_1, auto intro!: Amk_not_zero least_mod_type)\nqed\n\n\n\n\nlemma condition_2_part_3:\n  fixes A::\"'a::{field}^'columns::{mod_type}^'rows::{mod_type}\" and k::nat\n  defines ia:\"ia\\<equiv>(if \\<forall>m. is_zero_row_upt_k m k A then 0 else to_nat (GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1)\"\n  defines B:\"B\\<equiv>(snd (Gauss_Jordan_column_k (ia,A) k))\"\n  assumes rref: \"reduced_row_echelon_form_upt_k A k\"\n  and not_zero_i_suc_k: \"\\<not> is_zero_row_upt_k i (Suc k) B\"\n  and not_zero_m: \"\\<not> is_zero_row_upt_k m k A\"\n  and zero_below_greatest: \"\\<forall>m\\<ge>(GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1. A $ m $ from_nat k = 0\"\n  shows \"A $ i $ (LEAST k. A $ i $ k \\<noteq> 0) = 1\"\nproof -\n  have ia2: \"ia=to_nat (GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1\" unfolding ia using not_zero_m by presburger\n  have B_eq_A: \"B=A\"\n    unfolding B Gauss_Jordan_column_k_def Let_def fst_conv snd_conv ia2\n    apply simp\n    unfolding from_nat_to_nat_greatest using zero_below_greatest by blast\n  show ?thesis\n  proof (cases \"to_nat (GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1 < CARD('rows)\")\n    case True\n    have \"\\<not> is_zero_row_upt_k i k A\"\n    proof -\n      have \"i<(GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1\"\n      proof (rule ccontr)\n        assume \"\\<not> i < (GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1\"\n        hence i: \"(GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1 \\<le> i\" by simp\n        hence \"(GREATEST' n. \\<not> is_zero_row_upt_k n k A) < i\" using le_Suc' True by simp\n        hence zero_i: \"is_zero_row_upt_k i k A\" using not_greater_Greatest' by blast\n        hence \"is_zero_row_upt_k i (Suc k) A\" \n        proof (unfold is_zero_row_upt_k_def, clarify)\n          fix j::'columns \n          assume \"to_nat j < Suc k\"\n          thus \"A $ i $ j = 0\"\n            using zero_i unfolding is_zero_row_upt_k_def using zero_below_greatest i \n            by (metis from_nat_to_nat_id le_neq_implies_less not_le not_less_eq_eq)\n        qed        \n        thus False using not_zero_i_suc_k unfolding B_eq_A by contradiction\n      qed\n      hence \"i\\<le>(GREATEST' n. \\<not> is_zero_row_upt_k n k A)\" using dual_linorder.not_le le_Suc by metis\n      thus ?thesis using greatest_ge_nonzero_row'[OF rref] not_zero_m by fast\n    qed\n    thus ?thesis using rref_upt_condition2[OF rref] by blast\n  next\n    case False\n    have greatest_plus_one_eq_0: \"(GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1 = 0\"\n      using to_nat_plus_one_less_card False by blast\n    have \"\\<not> is_zero_row_upt_k i k A\"\n    proof (rule not_is_zero_row_upt_suc)\n      show \"\\<not> is_zero_row_upt_k i (Suc k) A\" using not_zero_i_suc_k unfolding B_eq_A .\n      show \"\\<forall>i. A $ i $ from_nat k = 0\"\n        using zero_below_greatest\n        unfolding greatest_plus_one_eq_0 using least_mod_type by blast\n    qed\n    thus ?thesis using rref_upt_condition2[OF rref] by blast\n  qed\nqed\n\nlemma condition_2_part_4:\n  fixes A::\"'a::{field}^'columns::{mod_type}^'rows::{mod_type}\" and k::nat\n  assumes rref: \"reduced_row_echelon_form_upt_k A k\"\n  and not_zero_m: \"\\<not> is_zero_row_upt_k m k A\"\n  and greatest_eq_card: \"Suc (to_nat (GREATEST' n. \\<not> is_zero_row_upt_k n k A)) = nrows A\"\n  shows \"A $ i $ (LEAST k. A $ i $ k \\<noteq> 0) = 1\"\nproof -\n  have \"\\<not> is_zero_row_upt_k i k A\"\n  proof (rule ccontr, simp)\n    assume zero_i: \"is_zero_row_upt_k i k A\"\n    hence zero_minus_1: \"is_zero_row_upt_k (-1) k A\"\n      using rref_upt_condition1[OF rref]\n      using Greatest_is_minus_1 neq_le_trans by metis \n    have \"(GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1 = 0\" using greatest_plus_one_eq_0[OF greatest_eq_card] .\n    hence greatest_eq_minus_1: \"(GREATEST' n. \\<not> is_zero_row_upt_k n k A) = -1\" using a_eq_minus_1 by fast\n    have \"\\<not> is_zero_row_upt_k (GREATEST' n. \\<not> is_zero_row_upt_k n k A) k A\"\n      by (rule greatest_ge_nonzero_row'[OF rref _ ], auto intro!: not_zero_m)\n    thus \"False\" using zero_minus_1 unfolding greatest_eq_minus_1 by contradiction\n  qed\n  thus ?thesis using rref_upt_condition2[OF rref] by blast\nqed\n\n\nlemma condition_2_part_5:\n  fixes A::\"'a::{field}^'columns::{mod_type}^'rows::{mod_type}\" and k::nat\n  defines ia:\"ia\\<equiv>(if \\<forall>m. is_zero_row_upt_k m k A then 0 else to_nat (GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1)\"\n  defines B:\"B\\<equiv>(snd (Gauss_Jordan_column_k (ia,A) k))\"\n  assumes rref: \"reduced_row_echelon_form_upt_k A k\"\n  and not_zero_i_suc_k: \"\\<not> is_zero_row_upt_k i (Suc k) B\"\n  and not_zero_m: \"\\<not> is_zero_row_upt_k m k A\"\n  and greatest_noteq_card: \"Suc (to_nat (GREATEST' n. \\<not> is_zero_row_upt_k n k A)) \\<noteq> nrows A\"\n  and greatest_less_ma: \"(GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1 \\<le> ma\"\n  and A_ma_k_not_zero: \"A $ ma $ from_nat k \\<noteq> 0\"\n  shows \"Gauss_Jordan_in_ij A ((GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1) (from_nat k) $ i $\n  (LEAST ka. Gauss_Jordan_in_ij A ((GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1) (from_nat k) $ i $ ka \\<noteq> 0) = 1\"\nproof -\n  have ia2: \"ia=to_nat (GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1\" unfolding ia using not_zero_m by presburger\n  have B_eq_Gauss: \"B=Gauss_Jordan_in_ij A ((GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1) (from_nat k)\"\n    unfolding B Gauss_Jordan_column_k_def Let_def fst_conv snd_conv ia2\n    apply simp\n    unfolding from_nat_to_nat_greatest using greatest_noteq_card A_ma_k_not_zero greatest_less_ma by blast\n  have greatest_plus_one_not_zero: \"(GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1 \\<noteq> 0\"\n    using suc_not_zero greatest_noteq_card unfolding nrows_def by auto\n  show ?thesis\n  proof (cases \"is_zero_row_upt_k i k A\")\n    case True\n    hence not_zero_iB: \"is_zero_row_upt_k i k B\" unfolding is_zero_row_upt_k_def unfolding B_eq_Gauss\n      using Gauss_Jordan_in_ij_preserves_previous_elements[OF rref not_zero_m _ greatest_plus_one_not_zero]\n      using A_ma_k_not_zero greatest_less_ma by fastforce\n    hence Gauss_Jordan_i_not_0: \"Gauss_Jordan_in_ij A ((GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1) (from_nat k) $ i $ (from_nat k) \\<noteq> 0\"\n      using not_zero_i_suc_k unfolding B_eq_Gauss unfolding is_zero_row_upt_k_def using from_nat_to_nat_id less_Suc_eq by (metis (lifting, no_types))\n    have \"i = ((GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1)\"\n    proof (rule ccontr)\n      assume i_not_greatest: \"i \\<noteq> (GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1\"\n      have \"Gauss_Jordan_in_ij A ((GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1) (from_nat k) $ i $ (from_nat k) = 0\"\n      proof (rule Gauss_Jordan_in_ij_0)\n        show \"\\<exists>n. A $ n $ from_nat k \\<noteq> 0 \\<and> (GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1 \\<le> n\" using A_ma_k_not_zero greatest_less_ma by blast\n        show \"i \\<noteq> (GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1\" using i_not_greatest .\n      qed\n      thus False using Gauss_Jordan_i_not_0 by contradiction\n    qed\n    hence Gauss_Jordan_i_1: \"Gauss_Jordan_in_ij A ((GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1) (from_nat k) $ i $ (from_nat k) = 1\"\n      using Gauss_Jordan_in_ij_1 using A_ma_k_not_zero greatest_less_ma by blast\n    have Least_eq_k: \"(LEAST ka. Gauss_Jordan_in_ij A ((GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1) (from_nat k) $ i $ ka \\<noteq> 0) = from_nat k\"\n    proof (rule Least_equality)\n      show \"Gauss_Jordan_in_ij A ((GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1) (from_nat k) $ i $ from_nat k \\<noteq> 0\" using Gauss_Jordan_i_not_0 .\n      show  \"\\<And>y. Gauss_Jordan_in_ij A ((GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1) (from_nat k) $ i $ y \\<noteq> 0 \\<Longrightarrow> from_nat k \\<le> y\"\n        using B_eq_Gauss is_zero_row_upt_k_def not_less not_zero_iB to_nat_le by fast\n    qed\n    show ?thesis using Gauss_Jordan_i_1 unfolding Least_eq_k .\n  next\n    case False\n    obtain j where Aij_not_0: \"A $ i $ j \\<noteq> 0\" and j_le_k: \"to_nat j < k\" using False unfolding is_zero_row_upt_k_def by auto\n    have least_le_k: \"to_nat (LEAST ka. A $ i $ ka \\<noteq> 0) < k\"\n      by (metis (lifting, mono_tags) Aij_not_0 j_le_k less_trans linorder_cases not_less_Least to_nat_mono)\n    have least_le_j: \"(LEAST ka. Gauss_Jordan_in_ij A ((GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1) (from_nat k) $ i $ ka \\<noteq> 0) \\<le> j\"\n      using Gauss_Jordan_in_ij_preserves_previous_elements[OF rref not_zero_m _ greatest_plus_one_not_zero j_le_k] using A_ma_k_not_zero greatest_less_ma\n      using Aij_not_0 False dual_linorder.not_leE not_less_Least by (metis (mono_tags))\n    have Least_eq: \"(LEAST ka. Gauss_Jordan_in_ij A ((GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1) (from_nat k) $ i $ ka \\<noteq> 0) \n      = (LEAST ka. A $ i $ ka \\<noteq> 0)\"\n    proof (rule Least_equality)\n      show \"Gauss_Jordan_in_ij A ((GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1) (from_nat k) $ i $ (LEAST ka. A $ i $ ka \\<noteq> 0) \\<noteq> 0\" \n        using Gauss_Jordan_in_ij_preserves_previous_elements[OF rref False _ greatest_plus_one_not_zero] least_le_k False rref_upt_condition2[OF rref]\n        using  A_ma_k_not_zero B_eq_Gauss greatest_less_ma zero_neq_one by fastforce\n      fix y assume Gauss_Jordan_y:\"Gauss_Jordan_in_ij A ((GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1) (from_nat k) $ i $ y \\<noteq> 0\"\n      show \"(LEAST ka. A $ i $ ka \\<noteq> 0) \\<le> y\"\n      proof (cases \"to_nat y < k\")\n        case False \n        thus ?thesis\n          using least_le_k less_trans not_leE to_nat_from_nat to_nat_le by metis\n      next\n        case True\n        have \"A $ i $ y \\<noteq> 0\" using Gauss_Jordan_y using Gauss_Jordan_in_ij_preserves_previous_elements[OF rref not_zero_m _ greatest_plus_one_not_zero True]\n          using A_ma_k_not_zero greatest_less_ma by fastforce\n        thus ?thesis using Least_le by fastforce\n      qed\n    qed\n    have \"A $ i $ (LEAST ka. Gauss_Jordan_in_ij A ((GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1) (from_nat k) $ i $ ka \\<noteq> 0) = 1\"\n      using False using rref_upt_condition2[OF rref] unfolding Least_eq by blast   \n    thus ?thesis unfolding Least_eq using Gauss_Jordan_in_ij_preserves_previous_elements[OF rref False _ greatest_plus_one_not_zero]\n      using least_le_k A_ma_k_not_zero greatest_less_ma by fastforce\n  qed\nqed\n\n\nlemma condition_2:\n  fixes A::\"'a::{field}^'columns::{mod_type}^'rows::{mod_type}\" and k::nat\n  defines ia:\"ia\\<equiv>(if \\<forall>m. is_zero_row_upt_k m k A then 0 else to_nat (GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1)\"\n  defines B:\"B\\<equiv>(snd (Gauss_Jordan_column_k (ia,A) k))\"\n  assumes rref: \"reduced_row_echelon_form_upt_k A k\"\n  and not_zero_i_suc_k: \"\\<not> is_zero_row_upt_k i (Suc k) B\"\n  shows \"B $ i $ (LEAST k. B $ i $ k \\<noteq> 0) = 1\"\nproof (unfold B Gauss_Jordan_column_k_def ia Let_def fst_conv snd_conv, auto, unfold from_nat_to_nat_greatest from_nat_0)\n  assume all_zero: \"\\<forall>m. is_zero_row_upt_k m k A\" and all_zero_k: \"\\<forall>m\\<ge>0. A $ m $ from_nat k = 0\"\n  show \"A $ i $ (LEAST k. A $ i $ k \\<noteq> 0) = 1\"\n    using condition_2_part_1[OF _ all_zero] not_zero_i_suc_k all_zero_k least_mod_type unfolding B ia by blast\nnext\n  fix m assume all_zero: \"\\<forall>m. is_zero_row_upt_k m k A\"\n    and Amk_not_zero: \"A $ m $ from_nat k \\<noteq> 0\"\n  show \"Gauss_Jordan_in_ij A 0 (from_nat k) $ i $ (LEAST ka. Gauss_Jordan_in_ij A 0 (from_nat k) $ i $ ka \\<noteq> 0) = 1\"\n    using condition_2_part_2[OF _ all_zero Amk_not_zero] not_zero_i_suc_k unfolding B ia .\nnext\n  fix m\n  assume not_zero_m: \"\\<not> is_zero_row_upt_k m k A\"\n    and zero_below_greatest: \"\\<forall>m\\<ge>(GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1. A $ m $ from_nat k = 0\" \n  show \"A $ i $ (LEAST k. A $ i $ k \\<noteq> 0) = 1\" using condition_2_part_3[OF rref _ not_zero_m zero_below_greatest] not_zero_i_suc_k unfolding B ia .\nnext\n  fix m \n  assume not_zero_m: \"\\<not> is_zero_row_upt_k m k A\"\n    and greatest_eq_card: \"Suc (to_nat (GREATEST' n. \\<not> is_zero_row_upt_k n k A)) = nrows A\"\n  show \"A $ i $ (LEAST k. A $ i $ k \\<noteq> 0) = 1\" using condition_2_part_4[OF rref not_zero_m greatest_eq_card] .\nnext\n  fix m ma\n  assume not_zero_m: \"\\<not> is_zero_row_upt_k m k A\"\n    and greatest_noteq_card: \"Suc (to_nat (GREATEST' n. \\<not> is_zero_row_upt_k n k A)) \\<noteq> nrows A\"\n    and greatest_less_ma: \"(GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1 \\<le> ma\"\n    and A_ma_k_not_zero: \"A $ ma $ from_nat k \\<noteq> 0\"\n  show \"Gauss_Jordan_in_ij A ((GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1) (from_nat k) $ i \n    $ (LEAST ka. Gauss_Jordan_in_ij A ((GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1) (from_nat k) $ i $ ka \\<noteq> 0) = 1\"\n    using condition_2_part_5[OF rref _ not_zero_m greatest_noteq_card greatest_less_ma A_ma_k_not_zero] not_zero_i_suc_k unfolding B ia .\nqed\n\n\nlemma condition_3_part_1:\n  fixes A::\"'a::{field}^'columns::{mod_type}^'rows::{mod_type}\" and k::nat\n  defines ia:\"ia\\<equiv>(if \\<forall>m. is_zero_row_upt_k m k A then 0 else to_nat (GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1)\"\n  defines B:\"B\\<equiv>(snd (Gauss_Jordan_column_k (ia,A) k))\"\n  assumes not_zero_i_suc_k: \"\\<not> is_zero_row_upt_k i (Suc k) B\"\n  and all_zero: \"\\<forall>m. is_zero_row_upt_k m k A\"\n  and all_zero_k: \"\\<forall>m. A $ m $ from_nat k = 0\"\n  shows \"(LEAST n. A $ i $ n \\<noteq> 0) < (LEAST n. A $ (i + 1) $ n \\<noteq> 0)\"\nproof -\n  have ia2: \"ia = 0\" using ia all_zero by simp\n  have B_eq_A: \"B=A\" unfolding B Gauss_Jordan_column_k_def Let_def fst_conv snd_conv ia2 using all_zero_k by fastforce\n  have \"is_zero_row_upt_k i (Suc k) B\"  using all_zero all_zero_k unfolding B_eq_A is_zero_row_upt_k_def by (metis less_SucE to_nat_from_nat)\n  thus ?thesis using not_zero_i_suc_k by contradiction\nqed\n\n\n\nlemma condition_3_part_2:\n  fixes A::\"'a::{field}^'columns::{mod_type}^'rows::{mod_type}\" and k::nat\n  defines ia:\"ia\\<equiv>(if \\<forall>m. is_zero_row_upt_k m k A then 0 else to_nat (GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1)\"\n  defines B:\"B\\<equiv>(snd (Gauss_Jordan_column_k (ia,A) k))\"\n  assumes i_le: \"i < i + 1\"\n  and not_zero_i_suc_k: \"\\<not> is_zero_row_upt_k i (Suc k) B\"\n  and not_zero_suc_i_suc_k: \"\\<not> is_zero_row_upt_k (i + 1) (Suc k) B\"\n  and all_zero: \"\\<forall>m. is_zero_row_upt_k m k A\"\n  and Amk_notzero: \"A $ m $ from_nat k \\<noteq> 0\"\n  shows \"(LEAST n. Gauss_Jordan_in_ij A 0 (from_nat k) $ i $ n \\<noteq> 0) < (LEAST n. Gauss_Jordan_in_ij A 0 (from_nat k) $ (i + 1) $ n \\<noteq> 0)\"\nproof -\n  have ia2: \"ia = 0\" using ia all_zero by simp\n  have B_eq_Gauss: \"B = Gauss_Jordan_in_ij A 0 (from_nat k)\"\n    unfolding B Gauss_Jordan_column_k_def Let_def fst_conv snd_conv ia2 \n    using all_zero Amk_notzero least_mod_type unfolding from_nat_0 by auto\n  have \"i=0\" using all_zero_imp_Gauss_Jordan_column_not_zero_in_row_0[OF all_zero _ Amk_notzero] not_zero_i_suc_k unfolding B ia .\n  moreover have \"i+1=0\" using all_zero_imp_Gauss_Jordan_column_not_zero_in_row_0[OF all_zero _ Amk_notzero] not_zero_suc_i_suc_k unfolding B ia .\n  ultimately show ?thesis using i_le by auto\nqed\n\n\n\nlemma condition_3_part_3:\n  fixes A::\"'a::{field}^'columns::{mod_type}^'rows::{mod_type}\" and k::nat\n  defines ia:\"ia\\<equiv>(if \\<forall>m. is_zero_row_upt_k m k A then 0 else to_nat (GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1)\"\n  defines B:\"B\\<equiv>(snd (Gauss_Jordan_column_k (ia,A) k))\"\n  assumes rref: \"reduced_row_echelon_form_upt_k A k\"\n  and i_le: \"i < i + 1\"\n  and not_zero_i_suc_k: \"\\<not> is_zero_row_upt_k i (Suc k) B\"\n  and not_zero_suc_i_suc_k: \"\\<not> is_zero_row_upt_k (i + 1) (Suc k) B\"\n  and not_zero_m: \"\\<not> is_zero_row_upt_k m k A\"\n  and zero_below_greatest: \"\\<forall>m\\<ge>(GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1. A $ m $ from_nat k = 0\"\n  shows \"(LEAST n. A $ i $ n \\<noteq> 0) < (LEAST n. A $ (i + 1) $ n \\<noteq> 0)\"\nproof -\n  have ia2: \"ia=to_nat (GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1\" unfolding ia using not_zero_m by presburger\n  have B_eq_A: \"B=A\"\n    unfolding B Gauss_Jordan_column_k_def Let_def fst_conv snd_conv ia2\n    apply simp\n    unfolding from_nat_to_nat_greatest using zero_below_greatest by blast\n  have rref_suc: \"reduced_row_echelon_form_upt_k A (Suc k)\"\n  proof (rule rref_suc_if_zero_below_greatest)\n    show \"reduced_row_echelon_form_upt_k A k\" using rref .\n    show \"\\<not> (\\<forall>a. is_zero_row_upt_k a k A)\" using not_zero_m by fast\n    show \"\\<forall>a>GREATEST' m. \\<not> is_zero_row_upt_k m k A. is_zero_row_upt_k a (Suc k) A\"\n    proof (clarify)\n      fix a::'rows assume greatest_less_a:  \"(GREATEST' m. \\<not> is_zero_row_upt_k m k A) < a\"\n      show \"is_zero_row_upt_k a (Suc k) A\"\n      proof (rule is_zero_row_upt_k_suc)\n        show \"is_zero_row_upt_k a k A\" using greatest_less_a row_greater_greatest_is_zero by fast\n        show \"A $ a $ from_nat k = 0\" using  le_Suc[OF greatest_less_a] zero_below_greatest by fast\n      qed    \n    qed\n  qed\n  show ?thesis using rref_upt_condition3[OF rref_suc] i_le not_zero_i_suc_k not_zero_suc_i_suc_k unfolding B_eq_A by blast\nqed\n\n\n\nlemma condition_3_part_4:\n  fixes A::\"'a::{field}^'columns::{mod_type}^'rows::{mod_type}\" and k::nat\n  defines ia:\"ia\\<equiv>(if \\<forall>m. is_zero_row_upt_k m k A then 0 else to_nat (GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1)\"\n  defines B:\"B\\<equiv>(snd (Gauss_Jordan_column_k (ia,A) k))\"\n  assumes rref: \"reduced_row_echelon_form_upt_k A k\" and i_le: \"i < i + 1\"\n  and not_zero_i_suc_k: \"\\<not> is_zero_row_upt_k i (Suc k) B\"\n  and not_zero_suc_i_suc_k: \"\\<not> is_zero_row_upt_k (i + 1) (Suc k) B\"\n  and not_zero_m: \"\\<not> is_zero_row_upt_k m k A\"\n  and greatest_eq_card: \"Suc (to_nat (GREATEST' n. \\<not> is_zero_row_upt_k n k A)) = nrows A\"\n  shows \"(LEAST n. A $ i $ n \\<noteq> 0) < (LEAST n. A $ (i + 1) $ n \\<noteq> 0)\"\nproof -\n  have ia2: \"ia=to_nat (GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1\" unfolding ia using not_zero_m by presburger\n  have B_eq_A: \"B=A\"\n    unfolding B Gauss_Jordan_column_k_def Let_def fst_conv snd_conv ia2\n    unfolding from_nat_to_nat_greatest using greatest_eq_card by simp\n  have greatest_eq_minus_1: \"(GREATEST' n. \\<not> is_zero_row_upt_k n k A) = -1\"\n    using a_eq_minus_1 greatest_eq_card to_nat_plus_one_less_card unfolding nrows_def by fastforce\n  have rref_suc: \"reduced_row_echelon_form_upt_k A (Suc k)\"\n  proof (rule rref_suc_if_all_rows_not_zero)\n    show \"reduced_row_echelon_form_upt_k A k\" using rref .\n    show \"\\<forall>n. \\<not> is_zero_row_upt_k n k A\" using Greatest_is_minus_1 greatest_eq_minus_1 greatest_ge_nonzero_row'[OF rref _] not_zero_m by metis\n  qed\n  show ?thesis using rref_upt_condition3[OF rref_suc] i_le not_zero_i_suc_k not_zero_suc_i_suc_k unfolding B_eq_A by blast\nqed\n\nlemma condition_3_part_5:\n  fixes A::\"'a::{field}^'columns::{mod_type}^'rows::{mod_type}\" and k::nat\n  defines ia:\"ia\\<equiv>(if \\<forall>m. is_zero_row_upt_k m k A then 0 else to_nat (GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1)\"\n  defines B:\"B\\<equiv>(snd (Gauss_Jordan_column_k (ia,A) k))\"\n  assumes rref: \"reduced_row_echelon_form_upt_k A k\"\n  and i_le: \"i < i + 1\"\n  and not_zero_i_suc_k: \"\\<not> is_zero_row_upt_k i (Suc k) B\"\n  and not_zero_suc_i_suc_k: \"\\<not> is_zero_row_upt_k (i + 1) (Suc k) B\"\n  and not_zero_m: \"\\<not> is_zero_row_upt_k m k A\"\n  and greatest_not_card: \"Suc (to_nat (GREATEST' n. \\<not> is_zero_row_upt_k n k A)) \\<noteq> nrows A\"\n  and greatest_less_ma: \"(GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1 \\<le> ma\"\n  and A_ma_k_not_zero: \"A $ ma $ from_nat k \\<noteq> 0\"\n  shows \"(LEAST n. Gauss_Jordan_in_ij A ((GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1) (from_nat k) $ i $ n \\<noteq> 0)\n  < (LEAST n. Gauss_Jordan_in_ij A ((GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1) (from_nat k) $ (i + 1) $ n \\<noteq> 0)\"\nproof -\n  have ia2: \"ia=to_nat (GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1\" unfolding ia using not_zero_m by presburger\n  have B_eq_Gauss: \"B = Gauss_Jordan_in_ij A ((GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1) (from_nat k)\"\n    unfolding B Gauss_Jordan_column_k_def \n    unfolding ia2 Let_def fst_conv snd_conv\n    using greatest_not_card greatest_less_ma A_ma_k_not_zero\n    by (auto simp add: from_nat_to_nat_greatest)\n  have suc_greatest_not_zero: \"(GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1 \\<noteq> 0\"\n    using Suc_eq_plus1 suc_not_zero greatest_not_card unfolding nrows_def by auto\n  show ?thesis\n  proof (cases \"is_zero_row_upt_k (i + 1) k A\")\n    case True\n    have zero_i_plus_one_k_B: \"is_zero_row_upt_k (i+1) k B\" \n      by (unfold B_eq_Gauss, rule is_zero_after_Gauss[OF True not_zero_m rref greatest_less_ma A_ma_k_not_zero])\n    hence Gauss_Jordan_i_not_0: \"Gauss_Jordan_in_ij A ((GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1) (from_nat k) $ (i+1) $ (from_nat k) \\<noteq> 0\"\n      using not_zero_suc_i_suc_k unfolding B_eq_Gauss using is_zero_row_upt_k_suc by blast\n    have i_plus_one_eq: \"i + 1 = ((GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1)\"\n    proof (rule ccontr)\n      assume i_not_greatest: \"i + 1 \\<noteq> (GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1\"\n      have \"Gauss_Jordan_in_ij A ((GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1) (from_nat k) $ (i + 1) $ (from_nat k) = 0\"\n      proof (rule Gauss_Jordan_in_ij_0)\n        show \"\\<exists>n. A $ n $ from_nat k \\<noteq> 0 \\<and> (GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1 \\<le> n\" using greatest_less_ma A_ma_k_not_zero by blast\n        show \"i + 1 \\<noteq> (GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1\" using i_not_greatest .\n      qed\n      thus False using Gauss_Jordan_i_not_0 by contradiction\n    qed\n    hence i_eq_greatest: \"i=(GREATEST' n. \\<not> is_zero_row_upt_k n k A)\" using add_right_cancel by simp\n    have Least_eq_k: \"(LEAST ka. Gauss_Jordan_in_ij A ((GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1) (from_nat k) $ (i+1) $ ka \\<noteq> 0) = from_nat k\"\n    proof (rule Least_equality)\n      show \"Gauss_Jordan_in_ij A ((GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1) (from_nat k) $ (i+1) $ from_nat k \\<noteq> 0\" by (metis Gauss_Jordan_i_not_0)\n      fix y assume \"Gauss_Jordan_in_ij A ((GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1) (from_nat k) $ (i+1) $ y \\<noteq> 0\"\n      thus \"from_nat k \\<le> y\" using zero_i_plus_one_k_B  unfolding i_eq_greatest B_eq_Gauss by (metis is_zero_row_upt_k_def not_less to_nat_le)   \n    qed\n    have not_zero_i_A: \"\\<not> is_zero_row_upt_k i k A\" using greatest_less_zero_row[OF rref] not_zero_m unfolding i_eq_greatest by fast\n    from this obtain j where Aij_not_0: \"A $ i $ j \\<noteq> 0\" and j_le_k: \"to_nat j < k\" unfolding is_zero_row_upt_k_def by blast\n    have least_le_k: \"to_nat (LEAST ka. A $ i $ ka \\<noteq> 0) < k\"\n      by (metis (lifting, mono_tags) Aij_not_0 j_le_k less_trans linorder_cases not_less_Least to_nat_mono)\n    have Least_eq: \" (LEAST n. Gauss_Jordan_in_ij A ((GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1) (from_nat k) $ i $ n \\<noteq> 0) = \n      (LEAST n. A $ i $ n \\<noteq> 0)\"\n    proof (rule Least_equality)\n      show \"Gauss_Jordan_in_ij A ((GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1) (from_nat k) $ i $ (LEAST ka. A $ i $ ka \\<noteq> 0) \\<noteq> 0\" \n        using Gauss_Jordan_in_ij_preserves_previous_elements[OF rref not_zero_i_A _ suc_greatest_not_zero least_le_k] greatest_less_ma A_ma_k_not_zero\n        using rref_upt_condition2[OF rref] not_zero_i_A by fastforce        \n      fix y assume Gauss_Jordan_y:\"Gauss_Jordan_in_ij A ((GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1) (from_nat k) $ i $ y \\<noteq> 0\"\n      show \"(LEAST ka. A $ i $ ka \\<noteq> 0) \\<le> y\"\n      proof (cases \"to_nat y < k\")\n        case False thus ?thesis by (metis dual_linorder.not_le least_le_k less_trans to_nat_mono)\n      next\n        case True\n        have \"A $ i $ y \\<noteq> 0\" using Gauss_Jordan_y using Gauss_Jordan_in_ij_preserves_previous_elements[OF rref not_zero_m _ suc_greatest_not_zero True]\n          using A_ma_k_not_zero greatest_less_ma by fastforce\n        thus ?thesis using Least_le by fastforce\n      qed\n    qed\n    also have \"... < from_nat k\" by (metis is_zero_row_upt_k_def is_zero_row_upt_k_suc le_less_linear le_less_trans least_le_k not_zero_suc_i_suc_k to_nat_mono' zero_i_plus_one_k_B) \n    finally show ?thesis unfolding Least_eq_k .\n  next\n    case False\n    have not_zero_i_A: \"\\<not> is_zero_row_upt_k i k A\" using rref_upt_condition1[OF rref] False i_le by blast \n    from this obtain j where Aij_not_0: \"A $ i $ j \\<noteq> 0\" and j_le_k: \"to_nat j < k\" unfolding is_zero_row_upt_k_def by blast\n    have least_le_k: \"to_nat (LEAST ka. A $ i $ ka \\<noteq> 0) < k\"\n      by (metis (lifting, mono_tags) Aij_not_0 j_le_k less_trans linorder_cases not_less_Least to_nat_mono)\n    have Least_i_eq: \"(LEAST n. Gauss_Jordan_in_ij A ((GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1) (from_nat k) $ i $ n \\<noteq> 0)\n      = (LEAST n. A $ i $ n \\<noteq> 0)\"\n    proof (rule Least_equality)\n      show \"Gauss_Jordan_in_ij A ((GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1) (from_nat k) $ i $ (LEAST ka. A $ i $ ka \\<noteq> 0) \\<noteq> 0\" \n        using Gauss_Jordan_in_ij_preserves_previous_elements[OF rref not_zero_i_A _ suc_greatest_not_zero least_le_k] greatest_less_ma A_ma_k_not_zero\n        using rref_upt_condition2[OF rref] not_zero_i_A by fastforce\n      fix y assume Gauss_Jordan_y:\"Gauss_Jordan_in_ij A ((GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1) (from_nat k) $ i $ y \\<noteq> 0\"\n      show \"(LEAST ka. A $ i $ ka \\<noteq> 0) \\<le> y\"\n      proof (cases \"to_nat y < k\")\n        case False thus ?thesis by (metis dual_linorder.not_le dual_linorder.not_less_iff_gr_or_eq le_less_trans least_le_k to_nat_mono)\n      next\n        case True\n        have \"A $ i $ y \\<noteq> 0\" using Gauss_Jordan_y using Gauss_Jordan_in_ij_preserves_previous_elements[OF rref not_zero_m _ suc_greatest_not_zero True]\n          using A_ma_k_not_zero greatest_less_ma by fastforce\n        thus ?thesis using Least_le by fastforce\n      qed\n    qed\n    from False obtain s where Ais_not_0: \"A $ (i+1) $ s \\<noteq> 0\" and s_le_k: \"to_nat s < k\" unfolding is_zero_row_upt_k_def by blast\n    have least_le_k: \"to_nat (LEAST ka. A $ (i+1) $ ka \\<noteq> 0) < k\" \n      by (metis (lifting, mono_tags) Ais_not_0 s_le_k dual_linorder.neq_iff less_trans not_less_Least to_nat_mono) \n    have Least_i_plus_one_eq: \"(LEAST n. Gauss_Jordan_in_ij A ((GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1) (from_nat k) $ (i+1) $ n \\<noteq> 0)\n      = (LEAST n. A $ (i+1) $ n \\<noteq> 0)\"\n    proof (rule Least_equality)\n      show \"Gauss_Jordan_in_ij A ((GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1) (from_nat k) $ (i+1) $ (LEAST ka. A $ (i+1) $ ka \\<noteq> 0) \\<noteq> 0\" \n        using Gauss_Jordan_in_ij_preserves_previous_elements[OF rref not_zero_i_A _ suc_greatest_not_zero least_le_k] greatest_less_ma A_ma_k_not_zero\n        using rref_upt_condition2[OF rref] False by fastforce\n      fix y assume Gauss_Jordan_y:\"Gauss_Jordan_in_ij A ((GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1) (from_nat k) $ (i+1) $ y \\<noteq> 0\"\n      show \"(LEAST ka. A $ (i+1) $ ka \\<noteq> 0) \\<le> y\"\n      proof (cases \"to_nat y < k\")\n        case False thus ?thesis by (metis (mono_tags) dual_linorder.le_less_linear least_le_k less_trans to_nat_mono)\n      next\n        case True\n        have \"A $ (i+1) $ y \\<noteq> 0\" using Gauss_Jordan_y using Gauss_Jordan_in_ij_preserves_previous_elements[OF rref not_zero_m _ suc_greatest_not_zero True]\n          using A_ma_k_not_zero greatest_less_ma by fastforce\n        thus ?thesis using Least_le by fastforce\n      qed\n    qed\n    show ?thesis unfolding Least_i_plus_one_eq Least_i_eq using rref_upt_condition3[OF rref] i_le False not_zero_i_A by blast\n  qed\nqed\n\nlemma condition_3:\n  fixes A::\"'a::{field}^'columns::{mod_type}^'rows::{mod_type}\" and k::nat\n  defines ia:\"ia\\<equiv>(if \\<forall>m. is_zero_row_upt_k m k A then 0 else to_nat (GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1)\"\n  defines B:\"B\\<equiv>(snd (Gauss_Jordan_column_k (ia,A) k))\"\n  assumes rref: \"reduced_row_echelon_form_upt_k A k\"\n  and i_le: \"i < i + 1\"\n  and not_zero_i_suc_k: \"\\<not> is_zero_row_upt_k i (Suc k) B\"\n  and not_zero_suc_i_suc_k: \"\\<not> is_zero_row_upt_k (i + 1) (Suc k) B\"\n  shows \"(LEAST n. B $ i $ n \\<noteq> 0) < (LEAST n. B $ (i + 1) $ n \\<noteq> 0)\"\nproof (unfold B Gauss_Jordan_column_k_def ia Let_def fst_conv snd_conv, auto, unfold from_nat_to_nat_greatest from_nat_0)\n  assume all_zero: \"\\<forall>m. is_zero_row_upt_k m k A\"\n    and all_zero_k: \"\\<forall>m\\<ge>0. A $ m $ from_nat k = 0\"\n  show \"(LEAST n. A $ i $ n \\<noteq> 0) < (LEAST n. A $ (i + 1) $ n \\<noteq> 0)\"\n    using condition_3_part_1[OF _ all_zero] using all_zero_k least_mod_type not_zero_i_suc_k unfolding B ia by fast\nnext\n  fix m assume all_zero: \"\\<forall>m. is_zero_row_upt_k m k A\"\n    and Amk_notzero: \"A $ m $ from_nat k \\<noteq> 0\"\n  show \"(LEAST n. Gauss_Jordan_in_ij A 0 (from_nat k) $ i $ n \\<noteq> 0) < (LEAST n. Gauss_Jordan_in_ij A 0 (from_nat k) $ (i + 1) $ n \\<noteq> 0)\"\n    using condition_3_part_2[OF i_le _ _ all_zero Amk_notzero] using not_zero_i_suc_k not_zero_suc_i_suc_k unfolding B ia .\nnext\n  fix m\n  assume not_zero_m: \"\\<not> is_zero_row_upt_k m k A\"\n    and zero_below_greatest: \"\\<forall>m\\<ge>(GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1. A $ m $ from_nat k = 0\"\n  show \"(LEAST n. A $ i $ n \\<noteq> 0) < (LEAST n. A $ (i + 1) $ n \\<noteq> 0)\"\n    using condition_3_part_3[OF rref i_le _ _ not_zero_m zero_below_greatest] using not_zero_i_suc_k not_zero_suc_i_suc_k unfolding B ia .\nnext\n  fix m\n  assume not_zero_m: \"\\<not> is_zero_row_upt_k m k A\"\n    and greatest_eq_card: \"Suc (to_nat (GREATEST' n. \\<not> is_zero_row_upt_k n k A)) = nrows A\"\n  show \"(LEAST n. A $ i $ n \\<noteq> 0) < (LEAST n. A $ (i + 1) $ n \\<noteq> 0)\"\n    using condition_3_part_4[OF rref i_le _ _ not_zero_m greatest_eq_card] using not_zero_i_suc_k not_zero_suc_i_suc_k unfolding B ia .\nnext\n  fix m ma\n  assume not_zero_m: \"\\<not> is_zero_row_upt_k m k A\"\n    and greatest_not_card: \"Suc (to_nat (GREATEST' n. \\<not> is_zero_row_upt_k n k A)) \\<noteq> nrows A\"\n    and greatest_less_ma: \"(GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1 \\<le> ma\"\n    and A_ma_k_not_zero: \"A $ ma $ from_nat k \\<noteq> 0\"\n  show \"(LEAST n. Gauss_Jordan_in_ij A ((GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1) (from_nat k) $ i $ n \\<noteq> 0) \n    < (LEAST n. Gauss_Jordan_in_ij A ((GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1) (from_nat k) $ (i + 1) $ n \\<noteq> 0)\"\n    using condition_3_part_5[OF rref i_le _ _ not_zero_m greatest_not_card greatest_less_ma A_ma_k_not_zero]\n    using not_zero_i_suc_k not_zero_suc_i_suc_k unfolding B ia .\nqed\n\n\nlemma condition_4_part_1:\n  fixes A::\"'a::{field}^'columns::{mod_type}^'rows::{mod_type}\" and k::nat\n  defines ia:\"ia\\<equiv>(if \\<forall>m. is_zero_row_upt_k m k A then 0 else to_nat (GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1)\"\n  defines B:\"B\\<equiv>(snd (Gauss_Jordan_column_k (ia,A) k))\"\n  assumes not_zero_i_suc_k:  \"\\<not> is_zero_row_upt_k i (Suc k) B\"\n  and all_zero: \"\\<forall>m. is_zero_row_upt_k m k A\"\n  and all_zero_k: \"\\<forall>m. A $ m $ from_nat k = 0\"\n  shows \"A $ j $ (LEAST n. A $ i $ n \\<noteq> 0) = 0\"\nproof -\n  have ia2: \"ia = 0\" using ia all_zero by simp\n  have B_eq_A: \"B=A\" unfolding B Gauss_Jordan_column_k_def Let_def fst_conv snd_conv ia2 using all_zero_k by fastforce\n  show ?thesis using B_eq_A all_zero all_zero_k is_zero_row_upt_k_suc not_zero_i_suc_k by blast\nqed\n\n\nlemma condition_4_part_2:\n  fixes A::\"'a::{field}^'columns::{mod_type}^'rows::{mod_type}\" and k::nat\n  defines ia:\"ia\\<equiv>(if \\<forall>m. is_zero_row_upt_k m k A then 0 else to_nat (GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1)\"\n  defines B:\"B\\<equiv>(snd (Gauss_Jordan_column_k (ia,A) k))\"\n  assumes not_zero_i_suc_k: \"\\<not> is_zero_row_upt_k i (Suc k) B\"\n  and i_not_j: \"i \\<noteq> j\"\n  and all_zero: \"\\<forall>m. is_zero_row_upt_k m k A\"\n  and Amk_not_zero: \"A $ m $ from_nat k \\<noteq> 0\"\n  shows \"Gauss_Jordan_in_ij A 0 (from_nat k) $ j $ (LEAST n. Gauss_Jordan_in_ij A 0 (from_nat k) $ i $ n \\<noteq> 0) = 0\"\nproof -\n  have i_eq_0: \"i=0\" using all_zero_imp_Gauss_Jordan_column_not_zero_in_row_0[OF all_zero _ Amk_not_zero] not_zero_i_suc_k unfolding B ia .\n  have least_eq_k: \"(LEAST n. Gauss_Jordan_in_ij A 0 (from_nat k) $ i $ n \\<noteq> 0) = from_nat k\"\n  proof (rule Least_equality)\n    show \"Gauss_Jordan_in_ij A 0 (from_nat k) $ i $ from_nat k \\<noteq> 0\" unfolding i_eq_0 using Amk_not_zero Gauss_Jordan_in_ij_1 least_mod_type zero_neq_one by fastforce\n    fix y assume Gauss_Jordan_y_not_0: \"Gauss_Jordan_in_ij A 0 (from_nat k) $ i $ y \\<noteq> 0\"\n    show \"from_nat k \\<le> y\"\n    proof (rule ccontr)\n      assume \"\\<not> from_nat k \\<le> y\"\n      hence \"y < (from_nat k)\" by simp\n      hence to_nat_y_less_k: \"to_nat y < k\" using to_nat_le by auto\n      have \"Gauss_Jordan_in_ij A 0 (from_nat k) $ i $ y = 0\" \n        using Gauss_Jordan_in_ij_preserves_previous_elements'[OF all_zero to_nat_y_less_k Amk_not_zero] all_zero to_nat_y_less_k\n        unfolding is_zero_row_upt_k_def  by fastforce\n      thus False using Gauss_Jordan_y_not_0 by contradiction\n    qed\n  qed\n  show ?thesis unfolding least_eq_k apply (rule Gauss_Jordan_in_ij_0) using i_eq_0 i_not_j Amk_not_zero least_mod_type by blast+\nqed\n\n\nlemma condition_4_part_3:\n  fixes A::\"'a::{field}^'columns::{mod_type}^'rows::{mod_type}\" and k::nat\n  defines ia:\"ia\\<equiv>(if \\<forall>m. is_zero_row_upt_k m k A then 0 else to_nat (GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1)\"\n  defines B:\"B\\<equiv>(snd (Gauss_Jordan_column_k (ia,A) k))\"\n  assumes rref: \"reduced_row_echelon_form_upt_k A k\"\n  and not_zero_i_suc_k:  \"\\<not> is_zero_row_upt_k i (Suc k) B\"\n  and i_not_j: \"i \\<noteq> j\"\n  and not_zero_m: \" \\<not> is_zero_row_upt_k m k A\"\n  and zero_below_greatest: \"\\<forall>m\\<ge>(GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1. A $ m $ from_nat k = 0\" \n  shows \"A $ j $ (LEAST n. A $ i $ n \\<noteq> 0) = 0\"\nproof -\n  have ia2: \"ia=to_nat (GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1\" unfolding ia using not_zero_m by presburger\n  have B_eq_A: \"B=A\"\n    unfolding B Gauss_Jordan_column_k_def Let_def fst_conv snd_conv ia2\n    apply simp\n    unfolding from_nat_to_nat_greatest using zero_below_greatest by blast\n  have rref_suc: \"reduced_row_echelon_form_upt_k A (Suc k)\"\n  proof (rule rref_suc_if_zero_below_greatest[OF rref], auto intro!: not_zero_m)\n    fix a\n    assume greatest_less_a: \"(GREATEST' m. \\<not> is_zero_row_upt_k m k A) < a\"\n    show \"is_zero_row_upt_k a (Suc k) A\"\n    proof (rule is_zero_row_upt_k_suc)  \n      show \"is_zero_row_upt_k a k A\" using row_greater_greatest_is_zero[OF greatest_less_a] .\n      show \"A $ a $ from_nat k = 0\" using zero_below_greatest  le_Suc[OF greatest_less_a] by blast\n    qed\n  qed\n  show ?thesis using rref_upt_condition4[OF rref_suc] not_zero_i_suc_k i_not_j unfolding B_eq_A by blast\nqed   \n\nlemma condition_4_part_4:\n  fixes A::\"'a::{field}^'columns::{mod_type}^'rows::{mod_type}\" and k::nat\n  defines ia:\"ia\\<equiv>(if \\<forall>m. is_zero_row_upt_k m k A then 0 else to_nat (GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1)\"\n  defines B:\"B\\<equiv>(snd (Gauss_Jordan_column_k (ia,A) k))\"\n  assumes rref: \"reduced_row_echelon_form_upt_k A k\"\n  and not_zero_i_suc_k:  \"\\<not> is_zero_row_upt_k i (Suc k) B\"\n  and i_not_j: \"i \\<noteq> j\"\n  and not_zero_m: \"\\<not> is_zero_row_upt_k m k A\"\n  and greatest_eq_card: \"Suc (to_nat (GREATEST' n. \\<not> is_zero_row_upt_k n k A)) = nrows A\"\n  shows \"A $ j $ (LEAST n. A $ i $ n \\<noteq> 0) = 0\"\nproof -\n  have ia2: \"ia=to_nat (GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1\" unfolding ia using not_zero_m by presburger\n  have B_eq_A: \"B=A\"\n    unfolding B Gauss_Jordan_column_k_def Let_def fst_conv snd_conv ia2\n    unfolding from_nat_to_nat_greatest using greatest_eq_card by simp\n  have greatest_eq_minus_1: \"(GREATEST' n. \\<not> is_zero_row_upt_k n k A) = -1\"\n    using a_eq_minus_1 greatest_eq_card to_nat_plus_one_less_card unfolding nrows_def by fastforce\n  have rref_suc: \"reduced_row_echelon_form_upt_k A (Suc k)\"\n  proof (rule rref_suc_if_all_rows_not_zero)\n    show \"reduced_row_echelon_form_upt_k A k\" using rref .\n    show \"\\<forall>n. \\<not> is_zero_row_upt_k n k A\" using Greatest_is_minus_1 greatest_eq_minus_1 greatest_ge_nonzero_row'[OF rref _] not_zero_m by metis\n  qed\n  show ?thesis using rref_upt_condition4[OF rref_suc] using not_zero_i_suc_k i_not_j unfolding B_eq_A i_not_j by blast\nqed\n\nlemma condition_4_part_5:\n  fixes A::\"'a::{field}^'columns::{mod_type}^'rows::{mod_type}\" and k::nat\n  defines ia:\"ia\\<equiv>(if \\<forall>m. is_zero_row_upt_k m k A then 0 else to_nat (GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1)\"\n  defines B:\"B\\<equiv>(snd (Gauss_Jordan_column_k (ia,A) k))\"\n  assumes rref: \"reduced_row_echelon_form_upt_k A k\"\n  and not_zero_i_suc_k:  \"\\<not> is_zero_row_upt_k i (Suc k) B\"\n  and i_not_j: \"i \\<noteq> j\"\n  and not_zero_m: \"\\<not> is_zero_row_upt_k m k A\"\n  and greatest_not_card: \"Suc (to_nat (GREATEST' n. \\<not> is_zero_row_upt_k n k A)) \\<noteq> nrows A\"\n  and greatest_less_ma: \"(GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1 \\<le> ma\"\n  and A_ma_k_not_zero: \"A $ ma $ from_nat k \\<noteq> 0\"\n  shows \"Gauss_Jordan_in_ij A ((GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1) (from_nat k) $ j $ \n  (LEAST n. Gauss_Jordan_in_ij A ((GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1) (from_nat k) $ i $ n \\<noteq> 0) = 0\"\nproof -\n  have ia2: \"ia=to_nat (GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1\" unfolding ia using not_zero_m by presburger\n  have B_eq_Gauss: \"B = Gauss_Jordan_in_ij A ((GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1) (from_nat k)\"\n    unfolding B Gauss_Jordan_column_k_def \n    unfolding ia2 Let_def fst_conv snd_conv\n    using greatest_not_card greatest_less_ma A_ma_k_not_zero\n    by (auto simp add: from_nat_to_nat_greatest)\n  have suc_greatest_not_zero: \"(GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1 \\<noteq> 0\"\n    using Suc_eq_plus1 suc_not_zero greatest_not_card unfolding nrows_def by auto\n  show ?thesis\n  proof (cases \"is_zero_row_upt_k i k A\")\n    case True\n    have zero_i_k_B: \"is_zero_row_upt_k i k B\" unfolding B_eq_Gauss by (rule is_zero_after_Gauss[OF True not_zero_m rref greatest_less_ma A_ma_k_not_zero])\n    hence Gauss_Jordan_i_not_0: \"Gauss_Jordan_in_ij A ((GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1) (from_nat k) $ (i) $ (from_nat k) \\<noteq> 0\"\n      using not_zero_i_suc_k unfolding B_eq_Gauss using is_zero_row_upt_k_suc by blast\n    have i_eq_greatest: \"i = ((GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1)\"\n    proof (rule ccontr)\n      assume i_not_greatest: \"i \\<noteq> (GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1\"\n      have \"Gauss_Jordan_in_ij A ((GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1) (from_nat k) $ i $ (from_nat k) = 0\"\n      proof (rule Gauss_Jordan_in_ij_0)\n        show \"\\<exists>n. A $ n $ from_nat k \\<noteq> 0 \\<and> (GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1 \\<le> n\" using greatest_less_ma A_ma_k_not_zero by blast\n        show \"i \\<noteq> (GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1\" using i_not_greatest .\n      qed\n      thus False using Gauss_Jordan_i_not_0 by contradiction\n    qed    \n    have Gauss_Jordan_i_1: \"Gauss_Jordan_in_ij A ((GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1) (from_nat k) $ i $ (from_nat k) = 1\"\n      unfolding i_eq_greatest using Gauss_Jordan_in_ij_1 greatest_less_ma A_ma_k_not_zero by blast\n    have Least_eq_k: \"(LEAST ka. Gauss_Jordan_in_ij A ((GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1) (from_nat k) $ i $ ka \\<noteq> 0) = from_nat k\"\n    proof (rule Least_equality)\n      show \"Gauss_Jordan_in_ij A ((GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1) (from_nat k) $ i $ from_nat k \\<noteq> 0\" using Gauss_Jordan_i_not_0 .\n      fix y assume \"Gauss_Jordan_in_ij A ((GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1) (from_nat k) $ i $ y \\<noteq> 0\"\n      thus \"from_nat k \\<le> y\" using zero_i_k_B  unfolding i_eq_greatest B_eq_Gauss by (metis is_zero_row_upt_k_def not_less to_nat_le)   \n    qed\n    show ?thesis using A_ma_k_not_zero Gauss_Jordan_in_ij_0' Least_eq_k greatest_less_ma i_eq_greatest i_not_j by force\n  next\n    case False\n    obtain n where Ain_not_0: \"A $ i $ n \\<noteq> 0\" and j_le_k: \"to_nat n < k\" using False unfolding is_zero_row_upt_k_def by auto\n    have least_le_k: \"to_nat (LEAST ka. A $ i $ ka \\<noteq> 0) < k\" \n      by (metis (lifting, mono_tags) Ain_not_0 dual_linorder.neq_iff j_le_k less_trans not_less_Least to_nat_mono)\n    have Least_eq: \"(LEAST ka. Gauss_Jordan_in_ij A ((GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1) (from_nat k) $ i $ ka \\<noteq> 0) \n      = (LEAST ka. A $ i $ ka \\<noteq> 0)\"\n    proof (rule Least_equality)\n      show \"Gauss_Jordan_in_ij A ((GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1) (from_nat k) $ i $ (LEAST ka. A $ i $ ka \\<noteq> 0) \\<noteq> 0\" \n        using Gauss_Jordan_in_ij_preserves_previous_elements[OF rref False _ suc_greatest_not_zero least_le_k] using greatest_less_ma A_ma_k_not_zero \n        using rref_upt_condition2[OF rref] False by fastforce\n      fix y assume Gauss_Jordan_y:\"Gauss_Jordan_in_ij A ((GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1) (from_nat k) $ i $ y \\<noteq> 0\"\n      show \"(LEAST ka. A $ i $ ka \\<noteq> 0) \\<le> y\"\n      proof (cases \"to_nat y < k\")\n        case False show ?thesis by (metis (mono_tags) False least_le_k less_trans not_leE to_nat_from_nat to_nat_le)\n      next\n        case True\n        have \"A $ i $ y \\<noteq> 0\"\n          using Gauss_Jordan_y using Gauss_Jordan_in_ij_preserves_previous_elements[OF rref not_zero_m _ suc_greatest_not_zero True]\n          using A_ma_k_not_zero greatest_less_ma by fastforce\n        thus ?thesis by (rule Least_le)\n      qed\n    qed\n    have Gauss_Jordan_eq_A: \"Gauss_Jordan_in_ij A ((GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1) (from_nat k) $ j $ (LEAST n. A $ i $ n \\<noteq> 0) =\n      A $ j $ (LEAST n. A $ i $ n \\<noteq> 0)\"\n      using Gauss_Jordan_in_ij_preserves_previous_elements[OF rref not_zero_m _ suc_greatest_not_zero least_le_k]\n      using A_ma_k_not_zero greatest_less_ma by fastforce    \n    show ?thesis unfolding Least_eq using rref_upt_condition4[OF rref] \n      using False Gauss_Jordan_eq_A i_not_j by presburger\n  qed\nqed\n\n\nlemma condition_4:\n  fixes A::\"'a::{field}^'columns::{mod_type}^'rows::{mod_type}\" and k::nat\n  defines ia:\"ia\\<equiv>(if \\<forall>m. is_zero_row_upt_k m k A then 0 else to_nat (GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1)\"\n  defines B:\"B\\<equiv>(snd (Gauss_Jordan_column_k (ia,A) k))\"\n  assumes rref: \"reduced_row_echelon_form_upt_k A k\"\n  and not_zero_i_suc_k:  \"\\<not> is_zero_row_upt_k i (Suc k) B\"\n  and i_not_j: \"i \\<noteq> j\"\n  shows \"B $ j $ (LEAST n. B $ i $ n \\<noteq> 0) = 0\"\nproof (unfold B Gauss_Jordan_column_k_def ia Let_def fst_conv snd_conv, auto, unfold from_nat_to_nat_greatest from_nat_0)\n  assume all_zero: \"\\<forall>m. is_zero_row_upt_k m k A\"\n    and all_zero_k: \"\\<forall>m\\<ge>0. A $ m $ from_nat k = 0\"\n  show \"A $ j $ (LEAST n. A $ i $ n \\<noteq> 0) = 0\" using condition_4_part_1[OF _ all_zero] using all_zero_k not_zero_i_suc_k least_mod_type unfolding B ia by blast\nnext\n  fix m\n  assume all_zero: \"\\<forall>m. is_zero_row_upt_k m k A\"\n    and Amk_not_zero: \"A $ m $ from_nat k \\<noteq> 0\"\n  show \"Gauss_Jordan_in_ij A 0 (from_nat k) $ j $ (LEAST n. Gauss_Jordan_in_ij A 0 (from_nat k) $ i $ n \\<noteq> 0) = 0\"\n    using condition_4_part_2[OF _ i_not_j all_zero Amk_not_zero] using  not_zero_i_suc_k unfolding B ia .\nnext\n  fix m assume not_zero_m: \"\\<not> is_zero_row_upt_k m k A\"\n    and zero_below_greatest: \"\\<forall>m\\<ge>(GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1. A $ m $ from_nat k = 0\"\n  show \"A $ j $ (LEAST n. A $ i $ n \\<noteq> 0) = 0\"\n    using condition_4_part_3[OF rref _ i_not_j not_zero_m zero_below_greatest] using not_zero_i_suc_k unfolding B ia .\nnext\n  fix m\n  assume not_zero_m: \"\\<not> is_zero_row_upt_k m k A\"\n    and greatest_eq_card: \"Suc (to_nat (GREATEST' n. \\<not> is_zero_row_upt_k n k A)) = nrows A\"\n  show \"A $ j $ (LEAST n. A $ i $ n \\<noteq> 0) = 0\"\n    using  condition_4_part_4[OF rref _ i_not_j not_zero_m greatest_eq_card] using not_zero_i_suc_k unfolding B ia .\nnext\n  fix m ma\n  assume not_zero_m: \"\\<not> is_zero_row_upt_k m k A\"\n    and greatest_not_card: \"Suc (to_nat (GREATEST' n. \\<not> is_zero_row_upt_k n k A)) \\<noteq> nrows A\"\n    and greatest_less_ma: \"(GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1 \\<le> ma\"\n    and A_ma_k_not_zero: \"A $ ma $ from_nat k \\<noteq> 0\"\n  show \"Gauss_Jordan_in_ij A ((GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1) (from_nat k) $ j $ \n    (LEAST n. Gauss_Jordan_in_ij A ((GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1) (from_nat k) $ i $ n \\<noteq> 0) = 0\"\n    using  condition_4_part_5[OF rref _ i_not_j not_zero_m greatest_not_card greatest_less_ma A_ma_k_not_zero] using not_zero_i_suc_k unfolding B ia .\nqed\n\n\nlemma reduced_row_echelon_form_upt_k_Gauss_Jordan_column_k:\n  fixes A::\"'a::{field}^'columns::{mod_type}^'rows::{mod_type}\" and k::nat\n  defines ia:\"ia\\<equiv>(if \\<forall>m. is_zero_row_upt_k m k A then 0 else to_nat (GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1)\"\n  defines B:\"B\\<equiv>(snd (Gauss_Jordan_column_k (ia,A) k))\"\n  assumes rref: \"reduced_row_echelon_form_upt_k A k\"\n  shows \"reduced_row_echelon_form_upt_k B (Suc k)\"\nproof (rule reduced_row_echelon_form_upt_k_intro, auto)\n  show \"\\<And>i j. is_zero_row_upt_k i (Suc k) B \\<Longrightarrow> i < j \\<Longrightarrow> is_zero_row_upt_k j (Suc k) B\" using condition_1 assms by blast\n  show \"\\<And>i. \\<not> is_zero_row_upt_k i (Suc k) B \\<Longrightarrow> B $ i $ (LEAST k. B $ i $ k \\<noteq> 0) = 1\" using condition_2 assms by blast\n  show \"\\<And>i. i < i + 1 \\<Longrightarrow> \\<not> is_zero_row_upt_k i (Suc k) B \\<Longrightarrow> \\<not> is_zero_row_upt_k (i + 1) (Suc k) B \\<Longrightarrow> (LEAST n. B $ i $ n \\<noteq> 0) < (LEAST n. B $ (i + 1) $ n \\<noteq> 0)\" using condition_3 assms by blast\n  show \"\\<And>i j. \\<not> is_zero_row_upt_k i (Suc k) B \\<Longrightarrow> i \\<noteq> j \\<Longrightarrow> B $ j $ (LEAST n. B $ i $ n \\<noteq> 0) = 0\" using condition_4 assms by blast\nqed\n\n\nlemma foldl_Gauss_condition_1:\n  fixes A::\"'a::{field}^'columns::{mod_type}^'rows::{mod_type}\" and k::nat\n  assumes \"\\<forall>m. is_zero_row_upt_k m k A\"\n  and \"\\<forall>m\\<ge>0. A $ m $ from_nat k = 0\"\n  shows \"is_zero_row_upt_k m (Suc k) A\" \n  by (rule is_zero_row_upt_k_suc, auto simp add: assms least_mod_type)\n\n\nlemma foldl_Gauss_condition_2:\n  fixes A::\"'a::{field}^'columns::{mod_type}^'rows::{mod_type}\" and k::nat\n  assumes k: \"k < ncols A\"\n  and all_zero: \"\\<forall>m. is_zero_row_upt_k m k A\"\n  and Amk_not_zero: \"A $ m $ from_nat k \\<noteq> 0\"\n  shows \"\\<exists>m. \\<not> is_zero_row_upt_k m (Suc k) (Gauss_Jordan_in_ij A 0 (from_nat k))\"\nproof -\n  have to_nat_from_nat_k_suc: \"to_nat (from_nat k::'columns) < (Suc k)\"  using to_nat_from_nat_id[OF k[unfolded ncols_def]] by simp\n  have A0k_eq_1: \"(Gauss_Jordan_in_ij A 0 (from_nat k)) $ 0 $ (from_nat k) = 1\"\n    by (rule Gauss_Jordan_in_ij_1, auto intro!: Amk_not_zero least_mod_type)\n  have \"\\<not> is_zero_row_upt_k 0 (Suc k) (Gauss_Jordan_in_ij A 0 (from_nat k))\"\n    unfolding is_zero_row_upt_k_def\n    using A0k_eq_1 to_nat_from_nat_k_suc by force\n  thus ?thesis by blast\nqed\n\n\nlemma foldl_Gauss_condition_3:\n  fixes A::\"'a::{field}^'columns::{mod_type}^'rows::{mod_type}\" and k::nat\n  assumes k: \"k < ncols A\"\n  and all_zero: \"\\<forall>m. is_zero_row_upt_k m k A\"           \n  and Amk_not_zero: \"A $ m $ from_nat k \\<noteq> 0\"\n  and \"\\<not> is_zero_row_upt_k ma (Suc k) (Gauss_Jordan_in_ij A 0 (from_nat k))\"\n  shows \"to_nat (GREATEST' n. \\<not> is_zero_row_upt_k n (Suc k) (Gauss_Jordan_in_ij A 0 (from_nat k))) = 0\"\nproof (unfold to_nat_eq_0, rule Greatest'_equality)\n  have to_nat_from_nat_k_suc: \"to_nat (from_nat k::'columns) < Suc (k)\"  using to_nat_from_nat_id[OF k[unfolded ncols_def]] by simp\n  have A0k_eq_1: \"(Gauss_Jordan_in_ij A 0 (from_nat k)) $ 0 $ (from_nat k) = 1\"\n    by (rule Gauss_Jordan_in_ij_1, auto intro!: Amk_not_zero least_mod_type)\n  show \"\\<not> is_zero_row_upt_k 0 (Suc k) (Gauss_Jordan_in_ij A 0 (from_nat k))\"\n    unfolding is_zero_row_upt_k_def\n    using A0k_eq_1 to_nat_from_nat_k_suc by force\n  fix y\n  assume not_zero_y: \"\\<not> is_zero_row_upt_k y (Suc k) (Gauss_Jordan_in_ij A 0 (from_nat k))\"\n  have y_eq_0: \"y=0\"\n  proof (rule ccontr)\n    assume y_not_0: \"y \\<noteq> 0\"\n    have \"is_zero_row_upt_k y (Suc k) (Gauss_Jordan_in_ij A 0 (from_nat k))\" unfolding is_zero_row_upt_k_def\n    proof (clarify)\n      fix j::\"'columns\" assume j: \"to_nat j < Suc k\"\n      show \"Gauss_Jordan_in_ij A 0 (from_nat k) $ y $ j = 0\"\n      proof (cases \"to_nat j = k\")\n        case True show ?thesis unfolding to_nat_from_nat[OF True]\n          by (rule Gauss_Jordan_in_ij_0[OF _ y_not_0], unfold to_nat_from_nat[OF True, symmetric], auto intro!:  y_not_0 least_mod_type Amk_not_zero)\n      next\n        case False hence j_less_k: \"to_nat j < k\" by (metis j less_SucE)\n        show ?thesis using Gauss_Jordan_in_ij_preserves_previous_elements'[OF all_zero j_less_k Amk_not_zero]\n          using all_zero j_less_k unfolding is_zero_row_upt_k_def by presburger\n      qed\n    qed\n    thus \"False\" using not_zero_y by contradiction\n  qed\n  thus \"y\\<le>0\" using least_mod_type by simp\nqed\n\n\nlemma foldl_Gauss_condition_5:\n  fixes A::\"'a::{field}^'columns::{mod_type}^'rows::{mod_type}\" and k::nat\n  assumes rref_A: \"reduced_row_echelon_form_upt_k A k\"\n  and not_zero_a:\"\\<not> is_zero_row_upt_k a k A\"\n  and all_zero_below_greatest: \"\\<forall>m\\<ge>(GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1. A $ m $ from_nat k = 0\"\n  shows \"(GREATEST' n. \\<not> is_zero_row_upt_k n k A) = (GREATEST' n. \\<not> is_zero_row_upt_k n (Suc k) A)\"\nproof -\n  have \"\\<And>n. (is_zero_row_upt_k n (Suc k) A) = (is_zero_row_upt_k n k A)\"\n  proof \n    fix n assume \"is_zero_row_upt_k n (Suc k) A\"\n    thus \"is_zero_row_upt_k n k A\" using is_zero_row_upt_k_le by fast\n  next\n    fix n assume zero_n_k: \"is_zero_row_upt_k n k A\"\n    have \"n>(GREATEST' n. \\<not> is_zero_row_upt_k n k A)\" by (rule greatest_less_zero_row[OF rref_A zero_n_k], auto intro!: not_zero_a)\n    hence n_ge_gratest: \"n \\<ge> (GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1\" using le_Suc by blast\n    hence A_nk_zero: \"A $ n $ (from_nat k) = 0\" using all_zero_below_greatest by fast\n    show \"is_zero_row_upt_k n (Suc k) A\" by (rule is_zero_row_upt_k_suc[OF zero_n_k A_nk_zero])\n  qed\n  thus \"(GREATEST' n. \\<not> is_zero_row_upt_k n k A) = (GREATEST' n. \\<not> is_zero_row_upt_k n (Suc k) A)\" by simp\nqed\n\n\nlemma foldl_Gauss_condition_6:\n  fixes A::\"'a::{field}^'columns::{mod_type}^'rows::{mod_type}\" and k::nat\n  assumes not_zero_m: \"\\<not> is_zero_row_upt_k m k A\"\n  and eq_card: \"Suc (to_nat (GREATEST' n. \\<not> is_zero_row_upt_k n k A)) = nrows A\"\n  shows \"nrows A = Suc (to_nat (GREATEST' n. \\<not> is_zero_row_upt_k n (Suc k) A))\"\nproof -\n  have \"(GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1 = 0\" using greatest_plus_one_eq_0[OF eq_card] .\n  hence greatest_k_eq_minus_1: \"(GREATEST' n. \\<not> is_zero_row_upt_k n k A) = -1\" using a_eq_minus_1 by blast\n  have \"(GREATEST' n. \\<not> is_zero_row_upt_k n (Suc k) A) = -1\"\n  proof (rule Greatest'_equality)\n    show \"\\<not> is_zero_row_upt_k (- 1) (Suc k) A\" \n      using Greatest'I_ex greatest_k_eq_minus_1 is_zero_row_upt_k_le not_zero_m by force\n    show \"\\<And>y. \\<not> is_zero_row_upt_k y (Suc k) A \\<Longrightarrow> y \\<le> -1\" using Greatest_is_minus_1 by fast\n  qed\n  thus \"nrows A = Suc (to_nat (GREATEST' n. \\<not> is_zero_row_upt_k n (Suc k) A))\" using eq_card greatest_k_eq_minus_1 by fastforce\nqed\n\n\n\nlemma foldl_Gauss_condition_8:\n  fixes A::\"'a::{field}^'columns::{mod_type}^'rows::{mod_type}\" and k::nat\n  assumes k: \"k < ncols A\"\n  and not_zero_m: \" \\<not> is_zero_row_upt_k m k A\" \n  and A_ma_k: \" A $ ma $ from_nat k \\<noteq> 0\" \n  and ma: \"(GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1 \\<le> ma\"\n  shows \"\\<exists>m. \\<not> is_zero_row_upt_k m (Suc k) (Gauss_Jordan_in_ij A ((GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1) (from_nat k))\"\nproof -\n  def Greatest_plus_one\\<equiv>\"((GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1)\"\n  have to_nat_from_nat_k_suc: \"to_nat (from_nat k::'columns) < (Suc k)\"  using to_nat_from_nat_id[OF k[unfolded ncols_def]] by simp\n  have Gauss_eq_1: \"(Gauss_Jordan_in_ij A Greatest_plus_one (from_nat k)) $ Greatest_plus_one $ (from_nat k) = 1\" \n    by (unfold Greatest_plus_one_def, rule Gauss_Jordan_in_ij_1, auto intro!: A_ma_k ma)\n  show \"\\<exists>m. \\<not> is_zero_row_upt_k m (Suc k) (Gauss_Jordan_in_ij A (Greatest_plus_one) (from_nat k))\"\n    by (rule exI[of _ \"Greatest_plus_one\"], unfold is_zero_row_upt_k_def, auto, rule exI[of _ \"from_nat k\"], simp add: Gauss_eq_1 to_nat_from_nat_k_suc)\nqed\n\nlemma foldl_Gauss_condition_9:\n  fixes A::\"'a::{field}^'columns::{mod_type}^'rows::{mod_type}\" and k::nat\n  assumes k: \"k < ncols A\"\n  and rref_A: \"reduced_row_echelon_form_upt_k A k\"\n  assumes not_zero_m: \"\\<not> is_zero_row_upt_k m k A\"\n  and suc_greatest_not_card: \"Suc (to_nat (GREATEST' n. \\<not> is_zero_row_upt_k n k A)) \\<noteq> nrows A\"\n  and greatest_less_ma: \"(GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1 \\<le> ma\"\n  and A_ma_k: \"A $ ma $ from_nat k \\<noteq> 0\"\n  shows \"Suc (to_nat (GREATEST' n. \\<not> is_zero_row_upt_k n k A)) =\n  to_nat(GREATEST' n. \\<not> is_zero_row_upt_k n (Suc k) (Gauss_Jordan_in_ij A ((GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1) (from_nat k)))\"\nproof -\n  def Greatest_plus_one==\"((GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1)\"\n  have to_nat_from_nat_k_suc: \"to_nat (from_nat k::'columns) < (Suc k)\"  using to_nat_from_nat_id[OF k[unfolded ncols_def]] by simp\n  have greatest_plus_one_not_zero: \"Greatest_plus_one \\<noteq> 0\"\n  proof -\n    have \"to_nat (GREATEST' n. \\<not> is_zero_row_upt_k n k A) < nrows A\" using to_nat_less_card unfolding nrows_def by blast\n    hence \"to_nat (GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1 < nrows A\" using suc_greatest_not_card by linarith\n    show ?thesis unfolding Greatest_plus_one_def by (rule suc_not_zero[OF suc_greatest_not_card[unfolded Suc_eq_plus1 nrows_def]])\n  qed\n  have greatest_eq: \"Greatest_plus_one = (GREATEST' n. \\<not> is_zero_row_upt_k n (Suc k) (Gauss_Jordan_in_ij A Greatest_plus_one (from_nat k)))\"\n  proof (rule Greatest'_equality[symmetric])\n    have \"(Gauss_Jordan_in_ij A Greatest_plus_one (from_nat k)) $ (Greatest_plus_one) $ (from_nat k) = 1\"\n      by (unfold Greatest_plus_one_def, rule Gauss_Jordan_in_ij_1, auto intro!: greatest_less_ma A_ma_k)\n    thus \"\\<not> is_zero_row_upt_k Greatest_plus_one (Suc k) (Gauss_Jordan_in_ij A Greatest_plus_one (from_nat k))\"\n      using to_nat_from_nat_k_suc\n      unfolding is_zero_row_upt_k_def by fastforce    \n    fix y\n    assume not_zero_y: \"\\<not> is_zero_row_upt_k y (Suc k) (Gauss_Jordan_in_ij A Greatest_plus_one (from_nat k))\"\n    show \"y \\<le> Greatest_plus_one\"\n    proof (cases \"y<Greatest_plus_one\")\n      case True thus ?thesis by simp\n    next\n      case False hence y_ge_greatest: \"y\\<ge>Greatest_plus_one\" by simp\n      have \"y=Greatest_plus_one\"\n      proof (rule ccontr)\n        assume y_not_greatest: \"y \\<noteq> Greatest_plus_one\" \n        have \"(GREATEST' n. \\<not> is_zero_row_upt_k n k A) < y\" using greatest_plus_one_not_zero \n          using Suc_le' less_le_trans y_ge_greatest unfolding Greatest_plus_one_def by auto\n        hence zero_row_y_upt_k: \"is_zero_row_upt_k y k A\" using not_greater_Greatest'[of \"\\<lambda>n. \\<not> is_zero_row_upt_k n k A\" y] unfolding Greatest_plus_one_def by fast\n        have \"is_zero_row_upt_k y (Suc k) (Gauss_Jordan_in_ij A Greatest_plus_one (from_nat k))\" unfolding is_zero_row_upt_k_def\n        proof (clarify)\n          fix j::'columns assume j: \"to_nat j < Suc k\"\n          show \"Gauss_Jordan_in_ij A Greatest_plus_one (from_nat k) $ y $ j = 0\"\n          proof (cases \"j=from_nat k\")\n            case True\n            show ?thesis\n            proof (unfold True, rule Gauss_Jordan_in_ij_0[OF _ y_not_greatest], rule exI[of _ ma], rule conjI)\n              show \"A $ ma $ from_nat k \\<noteq> 0\" using A_ma_k .\n              show \"Greatest_plus_one \\<le> ma\" using greatest_less_ma unfolding Greatest_plus_one_def .\n            qed\n          next\n            case False hence j_le_suc_k: \"to_nat j < Suc k\" using j by simp\n            have \"Gauss_Jordan_in_ij A Greatest_plus_one (from_nat k) $ y $ j = A $ y $ j\" unfolding Greatest_plus_one_def\n            proof (rule Gauss_Jordan_in_ij_preserves_previous_elements)\n              show \"reduced_row_echelon_form_upt_k A k\" using rref_A .\n              show \"\\<not> is_zero_row_upt_k m k A\" using not_zero_m .\n              show \"\\<exists>n. A $ n $ from_nat k \\<noteq> 0 \\<and> (GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1 \\<le> n\" using A_ma_k greatest_less_ma by blast\n              show \"(GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1 \\<noteq> 0\" using greatest_plus_one_not_zero unfolding Greatest_plus_one_def .\n              show \"to_nat j < k\" using False from_nat_to_nat_id j_le_suc_k less_antisym by fastforce\n            qed\n            also have \"... = 0\" using zero_row_y_upt_k unfolding is_zero_row_upt_k_def\n              using  False le_imp_less_or_eq from_nat_to_nat_id j_le_suc_k less_Suc_eq_le by fastforce          \n            finally show \"Gauss_Jordan_in_ij A Greatest_plus_one (from_nat k) $ y $ j = 0\" .\n          qed\n        qed\n        thus \"False\" using not_zero_y by contradiction\n      qed\n      thus \"y \\<le> Greatest_plus_one\" using y_ge_greatest by blast\n    qed\n  qed\n  show \"Suc (to_nat (GREATEST' n. \\<not> is_zero_row_upt_k n k A)) =\n    to_nat (GREATEST' n. \\<not> is_zero_row_upt_k n (Suc k) (Gauss_Jordan_in_ij A ((GREATEST' n. \\<not> is_zero_row_upt_k n k A) + 1) (from_nat k)))\"\n    unfolding greatest_eq[unfolded Greatest_plus_one_def, symmetric]\n    unfolding add_to_nat_def\n    unfolding to_nat_1\n    using to_nat_from_nat_id to_nat_plus_one_less_card\n    using greatest_plus_one_not_zero[unfolded Greatest_plus_one_def]\n    by force\nqed\n\n\ntext{*The following lemma is one of most important ones in the verification of the Gauss-Jordan algorithm.\nThe aim is to prove two statements about @{thm \"Gauss_Jordan_upt_k_def\"} (one about the result is on rref and another about the index).\nThe reason of doing that way is because both statements need them mutually to be proved.\nAs the proof is made using induction, two base cases and two induction steps appear.\n*}\nlemma rref_and_index_Gauss_Jordan_upt_k:\n  fixes A::\"'a::{field}^'columns::{mod_type}^'rows::{mod_type}\" and k::nat\n  assumes  \"k < ncols A\"\n  shows rref_Gauss_Jordan_upt_k: \"reduced_row_echelon_form_upt_k (Gauss_Jordan_upt_k A k) (Suc k)\"\n  and snd_Gauss_Jordan_upt_k: \n  \"foldl Gauss_Jordan_column_k (0, A) [0..<Suc k] =\n  (if \\<forall>m. is_zero_row_upt_k m (Suc k) (snd (foldl Gauss_Jordan_column_k (0, A) [0..<Suc k])) then 0\n  else to_nat (GREATEST' n. \\<not> is_zero_row_upt_k n (Suc k) (snd (foldl Gauss_Jordan_column_k (0, A) [0..<Suc k]))) + 1,\n  snd (foldl Gauss_Jordan_column_k (0, A) [0..<Suc k]))\"\n  using assms\nproof (induct k)\n    -- \"Two base cases, one for each show\"\n    -- \"The first one\"\n  show \"reduced_row_echelon_form_upt_k (Gauss_Jordan_upt_k A 0) (Suc 0)\"\n    unfolding Gauss_Jordan_upt_k_def apply auto\n    using reduced_row_echelon_form_upt_k_Gauss_Jordan_column_k[OF rref_upt_0, of A] using is_zero_row_utp_0'[of A] by simp\n      --\"The second base case\"\n  have rw_upt: \"[0..<Suc 0] = [0]\" by simp\n  show \"foldl Gauss_Jordan_column_k (0, A) [0..<Suc 0] =\n    (if \\<forall>m. is_zero_row_upt_k m (Suc 0) (snd (foldl Gauss_Jordan_column_k (0, A) [0..<Suc 0])) then 0\n    else to_nat (GREATEST' n. \\<not> is_zero_row_upt_k n (Suc 0) (snd (foldl Gauss_Jordan_column_k (0, A) [0..<Suc 0]))) + 1,\n    snd (foldl Gauss_Jordan_column_k (0, A) [0..<Suc 0]))\"\n    unfolding rw_upt\n    unfolding foldl.simps\n    unfolding Gauss_Jordan_column_k_def Let_def from_nat_0 fst_conv snd_conv\n    unfolding is_zero_row_upt_k_def\n    apply (auto simp add: least_mod_type to_nat_eq_0)\n    apply (metis Gauss_Jordan_in_ij_1 least_mod_type zero_neq_one)\n    by (metis (lifting, mono_tags) Gauss_Jordan_in_ij_0 Greatest'I_ex least_mod_type)\nnext\n    -- \"Now we begin with the proof of the induction step of the first show. We will make use the induction hypothesis of the second show\"\n  fix k\n  assume \"(k < ncols A \\<Longrightarrow> reduced_row_echelon_form_upt_k (Gauss_Jordan_upt_k A k) (Suc k))\"\n    and \"(k < ncols A \\<Longrightarrow>\n    foldl Gauss_Jordan_column_k (0, A) [0..<Suc k] =\n    (if \\<forall>m. is_zero_row_upt_k m (Suc k) (snd (foldl Gauss_Jordan_column_k (0, A) [0..<Suc k])) then 0\n    else to_nat (GREATEST' n. \\<not> is_zero_row_upt_k n (Suc k) (snd (foldl Gauss_Jordan_column_k (0, A) [0..<Suc k]))) + 1,\n    snd (foldl Gauss_Jordan_column_k (0, A) [0..<Suc k])))\"\n    and k: \"Suc k < ncols A\" \n  hence hyp_rref: \"reduced_row_echelon_form_upt_k (Gauss_Jordan_upt_k A k) (Suc k)\"\n    and hyp_foldl: \"foldl Gauss_Jordan_column_k (0, A) [0..<Suc k] =\n    (if \\<forall>m. is_zero_row_upt_k m (Suc k) (snd (foldl Gauss_Jordan_column_k (0, A) [0..<Suc k])) then 0\n    else to_nat (GREATEST' n. \\<not> is_zero_row_upt_k n (Suc k) (snd (foldl Gauss_Jordan_column_k (0, A) [0..<Suc k]))) + 1,\n    snd (foldl Gauss_Jordan_column_k (0, A) [0..<Suc k]))\"\n    by simp+\n  have rw: \"[0..<Suc (Suc k)]= [0..<(Suc k)] @ [(Suc k)]\" by auto\n  have rw2: \"(foldl Gauss_Jordan_column_k (0, A) [0..<Suc k]) = \n    (if \\<forall>m. is_zero_row_upt_k m (Suc k) (Gauss_Jordan_upt_k A k) then 0 else to_nat (GREATEST' n. \\<not> is_zero_row_upt_k n (Suc k) (Gauss_Jordan_upt_k A k)) + 1,\n    Gauss_Jordan_upt_k A k)\" unfolding Gauss_Jordan_upt_k_def using hyp_foldl by fast\n  show \"reduced_row_echelon_form_upt_k (Gauss_Jordan_upt_k A (Suc k)) (Suc (Suc k))\"\n    unfolding Gauss_Jordan_upt_k_def unfolding rw unfolding foldl_append unfolding foldl.simps unfolding rw2\n    by (rule reduced_row_echelon_form_upt_k_Gauss_Jordan_column_k[OF hyp_rref])\n      -- \"Making use of the same hypotheses of above proof, we begin with the proof of the induction step of the second show.\"\n  have fst_foldl: \"fst (foldl Gauss_Jordan_column_k (0, A) [0..<Suc k]) =\n    fst (if \\<forall>m. is_zero_row_upt_k m (Suc k) (snd (foldl Gauss_Jordan_column_k (0, A) [0..<Suc k])) then 0\n    else to_nat (GREATEST' n. \\<not> is_zero_row_upt_k n (Suc k) (snd (foldl Gauss_Jordan_column_k (0, A) [0..<Suc k]))) + 1,\n    snd (foldl Gauss_Jordan_column_k (0, A) [0..<Suc k]))\" using hyp_foldl by simp\n  show \"foldl Gauss_Jordan_column_k (0, A) [0..<Suc (Suc k)] =\n    (if \\<forall>m. is_zero_row_upt_k m (Suc (Suc k)) (snd (foldl Gauss_Jordan_column_k (0, A) [0..<Suc (Suc k)])) then 0\n    else to_nat (GREATEST' n. \\<not> is_zero_row_upt_k n (Suc (Suc k)) (snd (foldl Gauss_Jordan_column_k (0, A) [0..<Suc (Suc k)]))) + 1,\n    snd (foldl Gauss_Jordan_column_k (0, A) [0..<Suc (Suc k)]))\" \n  proof (rule prod_eqI)\n    show \"snd (foldl Gauss_Jordan_column_k (0, A) [0..<Suc (Suc k)]) =\n      snd (if \\<forall>m. is_zero_row_upt_k m (Suc (Suc k)) (snd (foldl Gauss_Jordan_column_k (0, A) [0..<Suc (Suc k)])) then 0\n      else to_nat (GREATEST' n. \\<not> is_zero_row_upt_k n (Suc (Suc k)) (snd (foldl Gauss_Jordan_column_k (0, A) [0..<Suc (Suc k)]))) + 1,\n      snd (foldl Gauss_Jordan_column_k (0, A) [0..<Suc (Suc k)]))\"\n      unfolding Gauss_Jordan_upt_k_def by force\n    def A'\\<equiv>\"(snd (foldl Gauss_Jordan_column_k (0, A) [0..<Suc k]))\"\n    have ncols_eq: \"ncols A = ncols A'\" unfolding A'_def ncols_def ..\n    have rref_A': \"reduced_row_echelon_form_upt_k A' (Suc k)\"  using hyp_rref unfolding A'_def Gauss_Jordan_upt_k_def .\n    show \"fst (foldl Gauss_Jordan_column_k (0, A) [0..<Suc (Suc k)]) =\n      fst (if \\<forall>m. is_zero_row_upt_k m (Suc (Suc k)) (snd (foldl Gauss_Jordan_column_k (0, A) [0..<Suc (Suc k)])) then 0\n      else to_nat (GREATEST' n. \\<not> is_zero_row_upt_k n (Suc (Suc k)) (snd (foldl Gauss_Jordan_column_k (0, A) [0..<Suc (Suc k)]))) + 1,\n      snd (foldl Gauss_Jordan_column_k (0, A) [0..<Suc (Suc k)]))\"\n      unfolding rw unfolding foldl_append unfolding foldl.simps unfolding Gauss_Jordan_column_k_def Let_def fst_foldl unfolding A'_def[symmetric]\n    proof (auto, unfold from_nat_0 from_nat_to_nat_greatest)\n      fix m assume \"\\<forall>m. is_zero_row_upt_k m (Suc k) A'\" and \"\\<forall>m\\<ge>0. A' $ m $ from_nat (Suc k) = 0\"\n      thus \"is_zero_row_upt_k m (Suc (Suc k)) A'\" using foldl_Gauss_condition_1 by blast\n    next\n      fix m\n      assume \"\\<forall>m. is_zero_row_upt_k m (Suc k) A'\"\n        and \"A' $ m $ from_nat (Suc k) \\<noteq> 0\"\n      thus \"\\<exists>m. \\<not> is_zero_row_upt_k m (Suc (Suc k)) (Gauss_Jordan_in_ij A' 0 (from_nat (Suc k)))\"\n        using foldl_Gauss_condition_2 k ncols_eq by simp\n    next\n      fix m ma\n      assume \"\\<forall>m. is_zero_row_upt_k m (Suc k) A'\"\n        and \"A' $ m $ from_nat (Suc k) \\<noteq> 0\"\n        and \"\\<not> is_zero_row_upt_k ma (Suc (Suc k)) (Gauss_Jordan_in_ij A' 0 (from_nat (Suc k)))\"\n      thus \"to_nat (GREATEST' n. \\<not> is_zero_row_upt_k n (Suc (Suc k)) (Gauss_Jordan_in_ij A' 0 (from_nat (Suc k)))) = 0\"\n        using foldl_Gauss_condition_3  k ncols_eq by simp\n    next\n      fix m assume \"\\<not> is_zero_row_upt_k m (Suc k) A' \"\n      thus \"\\<exists>m. \\<not> is_zero_row_upt_k m (Suc (Suc k)) A'\" and \"\\<exists>m. \\<not> is_zero_row_upt_k m (Suc (Suc k)) A'\" using is_zero_row_upt_k_le by blast+\n    next\n      fix m\n      assume not_zero_m: \"\\<not> is_zero_row_upt_k m (Suc k) A'\"\n        and zero_below_greatest: \"\\<forall>m\\<ge>(GREATEST' n. \\<not> is_zero_row_upt_k n (Suc k) A') + 1. A' $ m $ from_nat (Suc k) = 0\"\n      show \"(GREATEST' n. \\<not> is_zero_row_upt_k n (Suc k) A') = (GREATEST' n. \\<not> is_zero_row_upt_k n (Suc (Suc k)) A')\"\n        by (rule foldl_Gauss_condition_5[OF rref_A' not_zero_m zero_below_greatest])\n    next\n      fix m assume \"\\<not> is_zero_row_upt_k m (Suc k) A'\" and \"Suc (to_nat (GREATEST' n. \\<not> is_zero_row_upt_k n (Suc k) A')) = nrows A'\"\n      thus \"nrows A' = Suc (to_nat (GREATEST' n. \\<not> is_zero_row_upt_k n (Suc (Suc k)) A'))\"\n        using foldl_Gauss_condition_6 by blast\n    next\n      fix m ma\n      assume \"\\<not> is_zero_row_upt_k m (Suc k) A'\"\n        and \"(GREATEST' n. \\<not> is_zero_row_upt_k n (Suc k) A') + 1 \\<le> ma\"\n        and \"A' $ ma $ from_nat (Suc k) \\<noteq> 0\"\n      thus \"\\<exists>m. \\<not> is_zero_row_upt_k m (Suc (Suc k)) (Gauss_Jordan_in_ij A' ((GREATEST' n. \\<not> is_zero_row_upt_k n (Suc k) A') + 1) (from_nat (Suc k)))\"\n        using foldl_Gauss_condition_8 using k ncols_eq by simp\n    next\n      fix m ma mb\n      assume \"\\<not> is_zero_row_upt_k m (Suc k) A'\" and\n        \"Suc (to_nat (GREATEST' n. \\<not> is_zero_row_upt_k n (Suc k) A')) \\<noteq> nrows A'\"\n        and \"(GREATEST' n. \\<not> is_zero_row_upt_k n (Suc k) A') + 1 \\<le> ma\"\n        and \"A' $ ma $ from_nat (Suc k) \\<noteq> 0\"\n        and \"\\<not> is_zero_row_upt_k mb (Suc (Suc k)) (Gauss_Jordan_in_ij A' ((GREATEST' n. \\<not> is_zero_row_upt_k n (Suc k) A') + 1) (from_nat (Suc k)))\"\n      thus \"Suc (to_nat (GREATEST' n. \\<not> is_zero_row_upt_k n (Suc k) A')) =\n        to_nat (GREATEST' n. \\<not> is_zero_row_upt_k n (Suc (Suc k)) (Gauss_Jordan_in_ij A' ((GREATEST' n. \\<not> is_zero_row_upt_k n (Suc k) A') + 1) (from_nat (Suc k))))\"\n        using foldl_Gauss_condition_9[OF k[unfolded ncols_eq] rref_A'] unfolding nrows_def by blast\n    qed\n  qed\nqed\n\n\ncorollary rref_Gauss_Jordan:\n  fixes A::\"'a::{field}^'columns::{mod_type}^'rows::{mod_type}\"\n  shows \"reduced_row_echelon_form (Gauss_Jordan A)\"\nproof -\n  have \"CARD('columns) - 1 < CARD('columns)\" by fastforce\n  thus \"reduced_row_echelon_form (Gauss_Jordan A)\"\n    unfolding reduced_row_echelon_form_def unfolding Gauss_Jordan_def\n    using rref_Gauss_Jordan_upt_k unfolding ncols_def\n    by (metis (mono_tags) diff_Suc_1 lessE)\nqed\n\n\nlemma independent_not_zero_rows_rref:\n  fixes A::\"'a::{field}^'m::{mod_type}^'n::{finite,one,plus,ord}\"\n  assumes rref_A: \"reduced_row_echelon_form A\"\n  shows \"vec.independent {row i A |i. row i A \\<noteq> 0}\"\nproof\n  def R \\<equiv> \"{row i A |i. row i A \\<noteq> 0}\"\n  assume dep: \"vec.dependent R\"\n  from this obtain a where a_in_R: \"a\\<in>R\" and a_in_span: \"a \\<in> vec.span (R - {a})\" unfolding vec.dependent_def by fast\n  from a_in_R obtain i where a_eq_row_i_A: \"a=row i A\" unfolding R_def by blast\n  hence a_eq_Ai: \"a = A $ i\" unfolding row_def unfolding vec_nth_inverse .\n  have row_i_A_not_zero: \"\\<not> is_zero_row i A\" using a_in_R \n  unfolding R_def is_zero_row_def is_zero_row_upt_ncols row_def vec_nth_inverse\n  unfolding vec_lambda_unique zero_vec_def mem_Collect_eq using a_eq_Ai by force\n  def least_n == \"(LEAST n. A $ i $ n \\<noteq> 0)\"\n  have span_rw: \"vec.span (R - {a}) = {y. \\<exists>u. (\\<Sum>v\\<in>(R - {a}). u v *s v) = y}\"\n  proof (rule vec.span_finite)\n    show \"finite (R - {a})\" using finite_rows[of A] unfolding rows_def R_def by simp\n  qed\n  from this obtain f where f: \"(\\<Sum>v\\<in>(R - {a}). f v *s v) = a\" using a_in_span by fast\n  have \"1 = a $ least_n\"  using rref_condition2[OF rref_A] row_i_A_not_zero unfolding least_n_def a_eq_Ai by presburger\n  also have\"... = (\\<Sum>v\\<in>(R - {a}). f v *s v) $ least_n\" using f by auto\n  also have \"... = (\\<Sum>v\\<in>(R - {a}). (f v *s v) $ least_n)\" unfolding setsum_component ..\n  also have \"... = (\\<Sum>v\\<in>(R - {a}). (f v) * (v $ least_n))\" unfolding vector_smult_component ..\n  also have \"... = (\\<Sum>v\\<in>(R - {a}). 0)\"\n  proof (rule setsum.cong)\n    fix x assume x: \"x \\<in> R - {a}\"\n    from this obtain j where x_eq_row_j_A: \"x=row j A\" unfolding R_def by auto\n    hence i_not_j: \"i \\<noteq> j\" using a_eq_row_i_A x by auto\n    have x_least_is_zero: \"x $ least_n = 0\" using rref_condition4[OF rref_A] i_not_j row_i_A_not_zero \n      unfolding x_eq_row_j_A least_n_def row_def vec_nth_inverse by blast\n    show \"f x * x $ least_n = 0\" unfolding x_least_is_zero by auto\n  qed rule\n  also have \"... = 0\" unfolding setsum.neutral_const ..\n  finally show False by simp\nqed\n\n\n\n\n\n\n\ntext{*Here we start to prove that the transformation from the original matrix to its reduced row echelon form has been carried out by means of elementary operations.*}\ntext{*The following function eliminates all entries of the j-th column using the non-zero element situated in the position (i,j).\nIt is introduced to make easier the proof that each Gauss-Jordan step consists in applying suitable elementary operations.*}\n\nprimrec row_add_iterate :: \"'a::{semiring_1, uminus}^'n^'m::{mod_type} => nat => 'm => 'n => 'a^'n^'m::{mod_type}\"\n  where \"row_add_iterate A 0 i j = (if i=0 then A else row_add A 0 i (-A $ 0 $ j))\"\n  | \"row_add_iterate A (Suc n) i j = (if (Suc n = to_nat i) then row_add_iterate A n i j\n     else row_add_iterate (row_add A (from_nat (Suc n)) i (- A $ (from_nat (Suc n)) $ j)) n i j)\"\n\nlemma invertible_row_add_iterate:\n  fixes A::\"'a::{ring_1}^'n^'m::{mod_type}\"\n  assumes n: \"n<nrows A\"\n  shows \"\\<exists>P. invertible P \\<and> row_add_iterate A n i j = P**A\"\n  using n\nproof (induct n arbitrary: A)\n  fix A::\"'a::{ring_1}^'n^'m::{mod_type}\"\n  show \"\\<exists>P. invertible P \\<and> row_add_iterate A 0 i j = P ** A\"\n  proof (cases \"i=0\")\n    case True show ?thesis\n      unfolding row_add_iterate.simps by (metis True invertible_def matrix_mul_lid)\n  next\n    case False\n    show ?thesis by (metis False invertible_row_add row_add_iterate.simps(1) row_add_mat_1) \n  qed\n  fix n and A::\"'a::{ring_1}^'n^'m::{mod_type}\"\n  def A'==\"(row_add A (from_nat (Suc n)) i (- A $ from_nat (Suc n) $ j))\"\n  assume  hyp: \"\\<And>A::'a::{ring_1}^'n^'m::{mod_type}. n < nrows A \\<Longrightarrow> \\<exists>P. invertible P \\<and> row_add_iterate A n i j = P ** A\" and Suc_n: \"Suc n < nrows A\"\n  hence \"\\<exists>P. invertible P \\<and> row_add_iterate A' n i j = P ** A'\" unfolding nrows_def by auto\n  from this obtain P where inv_P: \"invertible P\"  and P: \"row_add_iterate A' n i j = P ** A'\" by auto\n  show \"\\<exists>P. invertible P \\<and> row_add_iterate A (Suc n) i j = P ** A\" \n    unfolding row_add_iterate.simps\n  proof (cases \"Suc n = to_nat i\")\n    case True\n    show \"\\<exists>P. invertible P \\<and>\n      (if Suc n = to_nat i then row_add_iterate A n i j\n      else row_add_iterate (row_add A (from_nat (Suc n)) i (- A $ from_nat (Suc n) $ j)) n i j) =\n      P ** A\"\n      unfolding if_P[OF True] using hyp Suc_n by simp\n  next\n    case False\n    show \"\\<exists>P. invertible P \\<and>\n      (if Suc n = to_nat i then row_add_iterate A n i j\n      else row_add_iterate (row_add A (from_nat (Suc n)) i (- A $ from_nat (Suc n) $ j)) n i j) =\n      P ** A\"\n      unfolding if_not_P[OF False]\n      unfolding P[unfolded A'_def]\n    proof (rule exI[of _ \"P ** (row_add (mat 1) (from_nat (Suc n)) i (- A $ from_nat (Suc n) $ j))\"], rule conjI)\n      show \"invertible (P ** row_add (mat 1) (from_nat (Suc n)) i (- A $ from_nat (Suc n) $ j))\"\n        by (metis False Suc_n inv_P invertible_mult invertible_row_add to_nat_from_nat_id nrows_def)\n      show \"P ** row_add A (from_nat (Suc n)) i (- A $ from_nat (Suc n) $ j) =\n        P ** row_add (mat 1) (from_nat (Suc n)) i (- A $ from_nat (Suc n) $ j) ** A\" \n        using matrix_mul_assoc row_add_mat_1[of \"from_nat (Suc n)\" i \" (- A $ from_nat (Suc n) $ j)\"] \n        by metis\n    qed\n  qed\nqed\n\nlemma row_add_iterate_preserves_greater_than_n:\n  fixes A::\"'a::{ring_1}^'n^'m::{mod_type}\"\n  assumes n: \"n<nrows A\"\n  and a: \"to_nat a > n\"\n  shows \"(row_add_iterate A n i j) $ a $ b = A $ a $ b\"\n  using assms\nproof (induct n arbitrary: A)\n  case 0\n  show ?case unfolding row_add_iterate.simps\n  proof (auto)\n    assume \"i \\<noteq> 0\"\n    hence \"a \\<noteq> 0\" by (metis \"0.prems\"(2) less_numeral_extra(3) to_nat_0)\n    thus \"row_add A 0 i (- A $ 0 $ j) $ a $ b = A $ a $ b\" unfolding row_add_def by auto\n  qed\nnext\n  fix n and A::\"'a::{ring_1}^'n^'m::{mod_type}\" \n  assume hyp: \"(\\<And>A::'a::{ring_1}^'n^'m::{mod_type}. n < nrows A \\<Longrightarrow> n < to_nat a \\<Longrightarrow> row_add_iterate A n i j $ a $ b = A $ a $ b)\"\n    and suc_n_less_card: \"Suc n < nrows A\" and suc_n_kess_a: \"Suc n < to_nat a\" \n  hence row_add_iterate_A: \"row_add_iterate A n i j $ a $ b = A $ a $ b\" by auto\n  show \"row_add_iterate A (Suc n) i j $ a $ b = A $ a $ b\"\n  proof (cases \"Suc n = to_nat i\")\n    case True\n    show \"row_add_iterate A (Suc n) i j $ a $ b = A $ a $ b\" unfolding row_add_iterate.simps if_P[OF True] using row_add_iterate_A .\n  next\n    case False\n    def A' \\<equiv> \"row_add A (from_nat (Suc n)) i (- A $ from_nat (Suc n) $ j)\"\n    have row_add_iterate_A': \"row_add_iterate A' n i j $ a $ b = A' $ a $ b\" using hyp suc_n_less_card suc_n_kess_a unfolding nrows_def by auto\n    have from_nat_not_a: \"from_nat (Suc n) \\<noteq> a\" by (metis less_not_refl suc_n_kess_a suc_n_less_card to_nat_from_nat_id nrows_def)\n    show \"row_add_iterate A (Suc n) i j $ a $ b = A $ a $ b\" unfolding row_add_iterate.simps if_not_P[OF False] row_add_iterate_A'[unfolded A'_def]\n      unfolding row_add_def using from_nat_not_a by simp\n  qed\nqed\n\n\nlemma row_add_iterate_preserves_pivot_row:\n  fixes A::\"'a::{ring_1}^'n^'m::{mod_type}\"\n  assumes n: \"n<nrows A\"\n  and a: \"to_nat i \\<le> n\"\n  shows \"(row_add_iterate A n i j) $ i $ b = A $ i $ b\"\n  using assms\nproof (induct n arbitrary: A)\n  case 0\n  show ?case by (metis \"0.prems\"(2) le_0_eq least_mod_type row_add_iterate.simps(1) to_nat_eq to_nat_mono')\nnext\n  fix n and A::\"'a::{ring_1}^'n^'m::{mod_type}\"\n  assume hyp: \"\\<And>A::'a::{ring_1}^'n^'m::{mod_type}. n < nrows A \\<Longrightarrow> to_nat i \\<le> n \\<Longrightarrow> row_add_iterate A n i j $ i $ b = A $ i $ b\"\n    and Suc_n_less_card: \"Suc n < nrows A\" and i_less_suc: \"to_nat i \\<le> Suc n\"\n  show \"row_add_iterate A (Suc n) i j $ i $ b = A $ i $ b\"\n  proof (cases \"Suc n = to_nat i\")\n    case True\n    show ?thesis unfolding row_add_iterate.simps if_P[OF True] apply (rule row_add_iterate_preserves_greater_than_n) using Suc_n_less_card True lessI by linarith+\n  next\n    case False\n    def A'\\<equiv> \"(row_add A (from_nat (Suc n)) i (- A $ from_nat (Suc n) $ j))\"\n    have row_add_iterate_A': \"row_add_iterate A' n i j $ i $ b = A' $ i $ b\" using hyp Suc_n_less_card i_less_suc False unfolding nrows_def by auto\n    have from_nat_noteq_i: \"from_nat (Suc n) \\<noteq> i\"  using False Suc_n_less_card from_nat_not_eq unfolding nrows_def by blast\n    show ?thesis unfolding row_add_iterate.simps if_not_P[OF False] row_add_iterate_A'[unfolded A'_def]\n      unfolding row_add_def using from_nat_noteq_i by simp\n  qed\nqed\n\nlemma row_add_iterate_eq_row_add:\n  fixes A::\"'a::{ring_1}^'n^'m::{mod_type}\"\n  assumes a_not_i: \"a \\<noteq> i\"\n  and n: \"n<nrows A\"\n  and \"to_nat a \\<le> n\"\n  shows \"(row_add_iterate A n i j) $ a $ b = (row_add A a i (- A $ a $ j)) $ a $ b\" \n  using assms\nproof (induct n arbitrary: A)\n  case 0\n  show ?case unfolding row_add_iterate.simps using \"0.prems\"(3) a_not_i to_nat_eq_0 least_mod_type by force\nnext\n  fix n and A::\"'a::{ring_1}^'n^'m::{mod_type}\"\n  assume hyp: \"(\\<And>A::'a::{ring_1}^'n^'m::{mod_type}. a \\<noteq> i \\<Longrightarrow> n < nrows A  \\<Longrightarrow> to_nat a \\<le> n \n    \\<Longrightarrow> row_add_iterate A n i j $ a $ b = row_add A a i (- A $ a $ j) $ a $ b)\"\n    and a_not_i: \"a \\<noteq> i\"\n    and suc_n_less_card: \"Suc n < nrows A\"\n    and a_le_suc_n: \"to_nat a \\<le> Suc n\"\n  show \"row_add_iterate A (Suc n) i j $ a $ b = row_add A a i (- A $ a $ j) $ a $ b\"\n  proof (cases \"Suc n = to_nat i\")\n    case True\n    show \"row_add_iterate A (Suc n) i j $ a $ b = row_add A a i (- A $ a $ j) $ a $ b\" unfolding row_add_iterate.simps if_P[OF True]\n    apply (rule hyp[OF a_not_i], auto simp add: Suc_lessD suc_n_less_card) by (metis True a_le_suc_n a_not_i le_SucE to_nat_eq)\n  next\n    case False note Suc_n_not_i=False\n    show ?thesis unfolding row_add_iterate.simps if_not_P[OF False]\n    proof (cases \"to_nat a = Suc n\") case True\n      show \"row_add_iterate (row_add A (from_nat (Suc n)) i (- A $ from_nat (Suc n) $ j)) n i j $ a $ b = row_add A a i (- A $ a $ j) $ a $ b\"\n        by (metis Suc_le_lessD True dual_order.order_refl less_imp_le row_add_iterate_preserves_greater_than_n suc_n_less_card to_nat_from_nat nrows_def)\n    next\n      case False\n      def A'\\<equiv>\"(row_add A (from_nat (Suc n)) i (- A $ from_nat (Suc n) $ j))\"\n      have rw: \"row_add_iterate A' n i j $ a $ b = row_add A' a i (- A' $ a $ j) $ a $ b\"\n      proof (rule hyp)\n        show \"a \\<noteq> i\" using a_not_i .\n        show \"n < nrows A'\" using suc_n_less_card unfolding nrows_def by auto\n        show \"to_nat a \\<le> n\" using False a_le_suc_n by simp\n      qed\n      have rw1: \"row_add A (from_nat (Suc n)) i (- A $ from_nat (Suc n) $ j) $ a $ b = A $ a $ b\"\n        unfolding row_add_def using False suc_n_less_card unfolding nrows_def by (auto simp add: to_nat_from_nat_id)\n      have rw2: \"row_add A (from_nat (Suc n)) i (- A $ from_nat (Suc n) $ j) $ a $ j = A $ a $ j\"\n        unfolding row_add_def using False suc_n_less_card unfolding nrows_def by (auto simp add: to_nat_from_nat_id)\n      have rw3: \"row_add A (from_nat (Suc n)) i (- A $ from_nat (Suc n) $ j) $ i $ b = A $ i $ b\"\n        unfolding row_add_def using Suc_n_not_i suc_n_less_card unfolding nrows_def by (auto simp add: to_nat_from_nat_id)\n      show  \"row_add_iterate A' n i j $ a $ b = row_add A a i (- A $ a $ j) $ a $ b\"\n        unfolding rw row_add_def apply simp\n        unfolding A'_def rw1 rw2 rw3 ..\n    qed\n  qed\nqed\n\n\nlemma row_add_iterate_eq_Gauss_Jordan_in_ij:\n  fixes A::\"'a::{field}^'n^'m::{mod_type}\" and i::\"'m\" and j::\"'n\"\n  defines 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)\"\n  shows \"row_add_iterate A' (nrows A - 1) i j = Gauss_Jordan_in_ij A i j\"\nproof (unfold Gauss_Jordan_in_ij_def Let_def, vector, auto)\n  fix ia\n  have interchange_rw: \"A $ (LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n) $ j = interchange_rows A i (LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n) $ i $ j\"\n   using interchange_rows_j[symmetric, of A \"(LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n)\"] by auto\n  show \"row_add_iterate A' (nrows A - Suc 0) i j $ i $ ia = \n    mult_row (interchange_rows A i (LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n)) i (1 / A $ (LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n) $ j) $ i $ ia\"\n    unfolding interchange_rw unfolding A'\n    proof (rule row_add_iterate_preserves_pivot_row, unfold nrows_def)\n    show \"CARD('m) - Suc 0 < CARD('m)\" by simp\n    have \"to_nat i < CARD('m)\" using bij_to_nat[where ?'a='m] unfolding bij_betw_def by auto\n    thus \"to_nat i \\<le> CARD('m) - Suc 0\" by auto\n  qed\nnext\n  fix ia iaa\n  have interchange_rw: \"A $ (LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n) $ j = interchange_rows A i (LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n) $ i $ j\"\n   using interchange_rows_j[symmetric, of A \"(LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n)\"] by auto\n  assume ia_not_i: \"ia \\<noteq> i\"\n  have rw: \"(- interchange_rows A i (LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n) $ ia $ j) \n    = - 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) $ ia $ j\"\n    unfolding interchange_rows_def mult_row_def using ia_not_i by auto  \n  show \"row_add_iterate A' (nrows A - Suc 0) i j $ ia $ iaa =\n             row_add (mult_row (interchange_rows A i (LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n)) i (1 / A $ (LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n) $ j)) ia i\n              (- interchange_rows A i (LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n) $ ia $ j) $\n             ia $\n             iaa\"\n    unfolding interchange_rw A' rw\n  proof (rule row_add_iterate_eq_row_add[of ia i \"(nrows A - Suc 0)\" _ j iaa], unfold nrows_def)\n    show \"ia \\<noteq> i\" using ia_not_i .\n    show \"CARD('m) - Suc 0 < CARD('m)\" by simp\n    have \"to_nat ia < CARD('m)\" using bij_to_nat[where ?'a='m] unfolding bij_betw_def by auto\n    thus \"to_nat ia \\<le> CARD('m) - Suc 0\" by simp\n  qed\nqed\n\n\n\nlemma invertible_Gauss_Jordan_column_k:\n  fixes A::\"'a::{field}^'n::{mod_type}^'m::{mod_type}\" and k::nat\n  shows \"\\<exists>P. invertible P \\<and> (snd (Gauss_Jordan_column_k (i,A) k)) = P**A\"\n  unfolding Gauss_Jordan_column_k_def Let_def\nproof (auto)\n  show \"\\<exists>P. invertible P \\<and> A = P ** A\" and \" \\<exists>P. invertible P \\<and> A = P ** A\" using invertible_mat_1 matrix_mul_lid[of A] by auto\nnext\n  fix m\n  assume i: \"i \\<noteq> nrows A\"\n    and i_le_m: \"from_nat i \\<le> m\" and Amk_not_zero: \"A $ m $ from_nat k \\<noteq> 0\"\n  def A_interchange \\<equiv> \"(interchange_rows A (from_nat i) (LEAST n. A $ n $ from_nat k \\<noteq> 0 \\<and> (from_nat i) \\<le> n))\"\n  def A_mult \\<equiv> \"(mult_row A_interchange (from_nat i) (1 / (A_interchange $ (from_nat i) $ from_nat k)))\"\n  obtain P where inv_P: \"invertible P\" and PA: \"A_interchange = P**A\" \n    unfolding A_interchange_def\n    using interchange_rows_mat_1[of \"from_nat i\" \"(LEAST n. A $ n $ from_nat k \\<noteq> 0 \\<and> from_nat i \\<le> n)\" A]\n    using invertible_interchange_rows[of \"from_nat i\" \"(LEAST n. A $ n $ from_nat k \\<noteq> 0 \\<and> from_nat i \\<le> n)\"]\n    by fastforce\n  def Q \\<equiv> \"(mult_row (mat 1) (from_nat i) (1 / (A_interchange $ (from_nat i) $ from_nat k)))::'a^'m::{mod_type}^'m::{mod_type}\"\n  have Q_A_interchange: \"A_mult = Q**A_interchange\" unfolding A_mult_def A_interchange_def Q_def unfolding mult_row_mat_1 ..\n  have inv_Q: \"invertible Q\"\n  proof (unfold Q_def, rule invertible_mult_row', unfold A_interchange_def, rule LeastI2_ex)\n    show \"\\<exists>a. A $ a $ from_nat k \\<noteq> 0 \\<and> (from_nat i) \\<le> a\" using i_le_m Amk_not_zero by blast\n    show \"\\<And>x. A $ x $ from_nat k \\<noteq> 0 \\<and> (from_nat i) \\<le> x \\<Longrightarrow> 1 / interchange_rows A (from_nat i) x $ (from_nat i) $ from_nat k \\<noteq> 0\"\n      using interchange_rows_i mult_zero_left nonzero_divide_eq_eq zero_neq_one by fastforce\n  qed\n  obtain Pa where inv_Pa: \"invertible Pa\" and Pa: \"row_add_iterate (Q ** (P ** A)) (nrows A - 1) (from_nat i) (from_nat k) = Pa ** (Q ** (P ** A))\"\n    using invertible_row_add_iterate by (metis (full_types) diff_less nrows_def zero_less_card_finite zero_less_one)\n  show \"\\<exists>P. invertible P \\<and> Gauss_Jordan_in_ij A (from_nat i) (from_nat k) = P ** A\"\n  proof (rule exI[of _ \"Pa**Q**P\"], rule conjI)\n    show \"invertible (Pa ** Q ** P)\" using inv_P inv_Pa inv_Q invertible_mult by auto\n    have \"Gauss_Jordan_in_ij A (from_nat i) (from_nat k) = row_add_iterate A_mult (nrows A - 1) (from_nat i) (from_nat k)\"\n      unfolding row_add_iterate_eq_Gauss_Jordan_in_ij[symmetric]  A_mult_def A_interchange_def ..\n    also have \"... = Pa ** (Q ** (P ** A))\" using Pa unfolding PA[symmetric] Q_A_interchange[symmetric] .\n    also have \"... = Pa ** Q ** P ** A\" unfolding matrix_mul_assoc ..\n    finally show \"Gauss_Jordan_in_ij A (from_nat i) (from_nat k) = Pa ** Q ** P ** A\" .\n  qed\nqed\n\n\nlemma invertible_Gauss_Jordan_up_to_k:\n  fixes A::\"'a::{field}^'n::{mod_type}^'m::{mod_type}\"\n  shows \"\\<exists>P. invertible P \\<and> (Gauss_Jordan_upt_k A k) = P**A\"\nproof (induct k)\n  case 0\n  have rw: \"[0..<Suc 0] = [0]\" by fastforce\n  show ?case\n    unfolding Gauss_Jordan_upt_k_def rw foldl.simps\n    using invertible_Gauss_Jordan_column_k .\n  case (Suc k)\n  have rw2: \"[0..<Suc (Suc k)] = [0..< Suc k] @ [(Suc k)]\" by simp\n  obtain P' where inv_P': \"invertible P'\" and Gk_eq_P'A: \"Gauss_Jordan_upt_k A k = P' ** A\" using Suc.hyps by force\n  have g: \"Gauss_Jordan_upt_k A k = snd (foldl Gauss_Jordan_column_k (0, A) [0..<Suc k])\" unfolding Gauss_Jordan_upt_k_def by auto\n  show ?case unfolding Gauss_Jordan_upt_k_def unfolding rw2 foldl_append foldl.simps\n    apply (subst pair_collapse[symmetric, of \"(foldl Gauss_Jordan_column_k (0, A) [0..<Suc k])\", unfolded g[symmetric]]) \n    using invertible_Gauss_Jordan_column_k\n    using Suc.hyps using invertible_mult matrix_mul_assoc by metis\nqed\n\n\nlemma inj_index_independent_rows:\n  fixes A::\"'a::{field}^'m::{mod_type}^'n::{finite,one,plus,ord}\"\n  assumes rref_A: \"reduced_row_echelon_form A\"\n  and x: \"row x A \\<in> {row i A |i. row i A \\<noteq> 0}\"\n  and eq: \"A $ x = A $ y\"\n  shows \"x = y\"\nproof (rule ccontr)\n  assume x_not_y: \"x \\<noteq> y\"  \n  have not_zero_x: \"\\<not> is_zero_row x A\" \n    using x unfolding is_zero_row_def unfolding is_zero_row_upt_k_def unfolding row_def vec_eq_iff \n    ncols_def\n    by auto\n  hence not_zero_y: \"\\<not> is_zero_row y A\" using eq unfolding is_zero_row_def' by simp\n  have Ax: \"A $ x $ (LEAST k. A $ x $ k \\<noteq> 0) = 1\" using not_zero_x rref_condition2[OF rref_A] by simp\n  have Ay: \"A $ x $ (LEAST k. A $ y $ k \\<noteq> 0) = 0\" using not_zero_y x_not_y rref_condition4[OF rref_A] by fast\n  show False using Ax Ay unfolding eq by simp\nqed\n\ntext{*The final results:*}\n\nlemma invertible_Gauss_Jordan:\n  fixes A::\"'a::{field}^'n::{mod_type}^'m::{mod_type}\"\n  shows \"\\<exists>P. invertible P \\<and> (Gauss_Jordan A) = P**A\" unfolding Gauss_Jordan_def using invertible_Gauss_Jordan_up_to_k .\n  \nlemma Gauss_Jordan:\n  fixes A::\"'a::{field}^'n::{mod_type}^'m::{mod_type}\"\n  shows \"\\<exists>P. invertible P \\<and> (Gauss_Jordan A) = P**A \\<and> reduced_row_echelon_form (Gauss_Jordan A)\"\n  by (simp add: invertible_Gauss_Jordan rref_Gauss_Jordan)\n  \ntext{*Some properties about the rank of a matrix, obtained thanks to the Gauss-Jordan algorithm and\n  the reduced row echelon form.*}  \n\nlemma rref_rank:\n  fixes A::\"'a::{field}^'m::{mod_type}^'n::{finite,one,plus,ord}\"\n  assumes rref_A: \"reduced_row_echelon_form A\"\n  shows \"rank A = card {row i A |i. row i A \\<noteq> 0}\"\n  unfolding rank_def row_rank_def\nproof (rule vec.dim_unique[of \"{row i A | i. row i A \\<noteq> 0}\"])\n  show \"{row i A |i. row i A \\<noteq> 0} \\<subseteq> row_space A\"\n  proof (auto, unfold row_space_def rows_def)\n    fix i assume \"row i A \\<noteq> 0\" show \"row i A \\<in> vec.span {row i A |i. i \\<in> UNIV}\" by (rule vec.span_superset, auto)\n  qed\n  show \"row_space A \\<subseteq> vec.span {row i A |i. row i A \\<noteq> 0}\"\n  proof (unfold row_space_def rows_def, cases \"\\<exists>i. row i A = 0\")\n    case True\n    have set_rw: \"{row i A |i. i \\<in> UNIV} = insert 0 {row i A |i. row i A \\<noteq> 0}\" using True by auto\n    have \"vec.span {row i A |i. i \\<in> UNIV} = vec.span {row i A |i. row i A \\<noteq> 0}\" unfolding set_rw using vec.span_insert_0 .\n    thus \"vec.span {row i A |i. i \\<in> UNIV} \\<subseteq> vec.span {row i A |i. row i A \\<noteq> 0}\" by simp\n  next\n    case False show \"vec.span {row i A |i. i \\<in> UNIV} \\<subseteq> vec.span {row i A |i. row i A \\<noteq> 0}\" using False by simp\n  qed\n  show \"vec.independent {row i A |i. row i A \\<noteq> 0}\" by (rule independent_not_zero_rows_rref[OF rref_A])\n  show \"card {row i A |i. row i A \\<noteq> 0} = card {row i A |i. row i A \\<noteq> 0}\" ..\nqed\n\nlemma column_leading_coefficient_component_eq:\n  fixes A::\"'a::{field}^'m::{mod_type}^'n::{finite,one,plus,ord}\"\n  assumes rref_A: \"reduced_row_echelon_form A\"\n  and v: \"v \\<in> {column (LEAST n. A $ i $ n \\<noteq> 0) A |i. row i A \\<noteq> 0}\" \n  and vx: \"v $ x \\<noteq> 0\"\n  and vy: \"v $ y \\<noteq> 0\"\n  shows \"x = y\"\nproof -\nobtain b where b: \"v = column (LEAST n. A $ b $ n \\<noteq> 0) A\" and row_b: \"row b A \\<noteq> 0\" using v by blast\nhave vb_not_zero: \"v $ b \\<noteq> 0\" unfolding b column_def by (auto, metis is_zero_row_eq_row_zero row_b rref_A rref_condition2 zero_neq_one)\nhave b_eq_x: \"b = x\"\n proof (rule ccontr)\n  assume b_not_x: \"b\\<noteq>x\"\n  have \"A $ x $ (LEAST n. A $ b $ n \\<noteq> 0) = 0\" \n    by (rule rref_condition4_explicit[OF rref_A _ b_not_x], simp add: is_zero_row_eq_row_zero row_b)\n  thus False using vx unfolding b column_def by auto\n qed\nmoreover have b_eq_y: \"b = y\"\n proof (rule ccontr)\n  assume b_not_y: \"b\\<noteq>y\"\n  have \"A $ y $ (LEAST n. A $ b $ n \\<noteq> 0) = 0\" \n    by (rule rref_condition4_explicit[OF rref_A _ b_not_y], simp add: is_zero_row_eq_row_zero row_b)\n  thus False using vy unfolding b column_def by auto\n qed\nultimately show ?thesis by simp\nqed\n\n\nlemma column_leading_coefficient_component_1:\n  fixes A::\"'a::{field}^'m::{mod_type}^'n::{finite,one,plus,ord}\"\n  assumes rref_A: \"reduced_row_echelon_form A\"\n  and v: \"v \\<in> {column (LEAST n. A $ i $ n \\<noteq> 0) A |i. row i A \\<noteq> 0}\" \n  and vx: \"v $ x \\<noteq> 0\"\n  shows \"v $ x = 1\"\nproof -\nobtain b where b: \"v = column (LEAST n. A $ b $ n \\<noteq> 0) A\" and row_b: \"row b A \\<noteq> 0\" using v by blast\nhave vb_not_zero: \"v $ b \\<noteq> 0\" unfolding b column_def by (auto, metis is_zero_row_eq_row_zero row_b rref_A rref_condition2 zero_neq_one)\nhave b_eq_x: \"b = x\" \n  by (metis b column_def is_zero_row_eq_row_zero row_b rref_A rref_condition4 transpose_row_code transpose_row_def vx)\nshow?thesis\n using rref_condition2_explicit[OF rref_A, of b] row_b\n unfolding b column_def is_zero_row_def' \n by (metis (mono_tags) `\\<not> is_zero_row b A \\<Longrightarrow> A $ b $ (LEAST k. A $ b $ k \\<noteq> 0) = 1`\n          b_eq_x is_zero_row_eq_row_zero vec_lambda_beta) \nqed\n\n\nlemma column_leading_coefficient_component_0:\n  fixes A::\"'a::{field}^'m::{mod_type}^'n::{finite,one,plus,ord}\"\n  assumes rref_A: \"reduced_row_echelon_form A\"\n  and v: \"v \\<in> {column (LEAST n. A $ i $ n \\<noteq> 0) A |i. row i A \\<noteq> 0}\" \n  and vx: \"v $ x \\<noteq> 0\"\n  and x_not_y: \"x \\<noteq> y\"\n  shows \"v $ y = 0\" using column_leading_coefficient_component_eq[OF rref_A v vx] x_not_y by auto\n\nlemma rref_col_rank:\n  fixes A::\"'a::{field}^'m::{mod_type}^'n::{mod_type}\"\n  assumes rref_A: \"reduced_row_echelon_form A\"\n  shows \"col_rank A = card {column (LEAST n. A $ i $ n \\<noteq> 0) A | i. row i A \\<noteq> 0}\"\nproof (unfold col_rank_def, rule vec.dim_unique[of \"{column (LEAST n. A $ i $ n \\<noteq> 0) A | i. row i A \\<noteq> 0}\"])\n  show \"{column (LEAST n. A $ i $ n \\<noteq> 0) A |i. row i A \\<noteq> 0} \\<subseteq> col_space A\" \n  by (auto simp add: col_space_def, rule vec.span_superset, unfold columns_def, auto)\n  show \"vec.independent {column (LEAST n. A $ i $ n \\<noteq> 0) A |i. row i A \\<noteq> 0}\"\n    proof (rule vec.independent_if_scalars_zero, auto)\n      fix f i\n      let ?x = \"column (LEAST n. A $ i $ n \\<noteq> 0) A\"\n      have setsum0: \"(\\<Sum>x\\<in>{column (LEAST n. A $ i $ n \\<noteq> 0) A |i. row i A \\<noteq> 0} - {?x}. f x * (x $ i)) = 0\"\n        proof (rule setsum.neutral, rule ballI)\n        fix x assume x: \"x \\<in> {column (LEAST n. A $ i $ n \\<noteq> 0) A |i. row i A \\<noteq> 0} - {?x}\"\n        obtain j where x_eq: \"x=column (LEAST n. A $ j $ n \\<noteq> 0) A\" and row_j_not_0: \"row j A \\<noteq> 0\" \n          and j_not_i: \"j\\<noteq>i\" using x by auto\n        have \"x$i=0\" unfolding x_eq column_def \n          by (auto, metis is_zero_row_eq_row_zero j_not_i row_j_not_0 rref_A rref_condition4_explicit)\n        thus \"f x * x $ i = 0\" by simp\n        qed\n      assume eq_0: \"(\\<Sum>x\\<in>{column (LEAST n. A $ i $ n \\<noteq> 0) A |i. row i A \\<noteq> 0}. f x *s x) = 0\"\n        and i: \"row i A \\<noteq> 0\"\n      have xi_1: \"(?x $ i) = 1\" unfolding column_def by (auto, metis i is_zero_row_eq_row_zero rref_A rref_condition2_explicit)\n      have \"0 = (\\<Sum>x\\<in>{column (LEAST n. A $ i $ n \\<noteq> 0) A |i. row i A \\<noteq> 0}. f x *s x) $ i\" \n        using eq_0 by auto\n      also have \"... = (\\<Sum>x\\<in>{column (LEAST n. A $ i $ n \\<noteq> 0) A |i. row i A \\<noteq> 0}. f x * (x $ i))\"\n        unfolding setsum_component vector_smult_component ..\n     also have \"... = f ?x * (?x $ i) \n      + (\\<Sum>x\\<in>{column (LEAST n. A $ i $ n \\<noteq> 0) A |i. row i A \\<noteq> 0} - {?x}. f x * (x $ i))\"\n      by (rule setsum.remove, auto, rule exI[of _ i], simp add: i)\n     also have \"... = f ?x * (?x $ i)\" unfolding setsum0 by simp\n     also have \"... = f (column (LEAST n. A $ i $ n \\<noteq> 0) A)\" unfolding xi_1 by simp\n     finally show \"f (column (LEAST n. A $ i $ n \\<noteq> 0) A) = 0\" by simp\n     qed\n  show \"col_space A \\<subseteq> vec.span {column (LEAST n. A $ i $ n \\<noteq> 0) A |i. row i A \\<noteq> 0}\"\n  unfolding col_space_def \n  proof (rule vec.span_mono[of \"(columns A)\" \n        \"vec.span {column (LEAST n. A $ i $ n \\<noteq> 0) A |i. row i A \\<noteq> 0}\", unfolded vec.span_span], auto)\n  fix x assume x: \"x \\<in> columns A\"\n  have f: \"finite {column (LEAST n. A $ i $ n \\<noteq> 0) A |i. row i A \\<noteq> 0}\" by simp\n  let ?f=\"\\<lambda>v. x $ (THE i. v $ i \\<noteq> 0)\"\n  show \"x \\<in> vec.span {column (LEAST n. A $ i $ n \\<noteq> 0) A |i. row i A \\<noteq> 0}\" unfolding vec.span_finite[OF f]\n  proof (auto, rule exI[of _ ?f], subst (3) vec_eq_iff, clarify)\n    fix i\n    show \"(\\<Sum>v\\<in>{column (LEAST n. A $ i $ n \\<noteq> 0) A |i. row i A \\<noteq> 0}. x $ (THE i. v $ i \\<noteq> 0) *s v) $ i = x $ i\"\n    proof (cases \"\\<exists>v. v \\<in> {column (LEAST n. A $ i $ n \\<noteq> 0) A |i. row i A \\<noteq> 0} \\<and> v $ i \\<noteq> 0\")\n    case False \n    have xi_0: \"x $ i = 0\"\n      proof (rule ccontr)\n      assume xi_not_0: \"x $ i \\<noteq> 0\"\n      hence row_iA_not_zero: \"row i A \\<noteq> 0\" using x unfolding columns_def column_def row_def by (vector, metis vec_lambda_unique)\n      let ?v=\"column (LEAST n. A $ i $ n \\<noteq> 0) A\"\n      have \"?v \\<in> {column (LEAST n. A $ i $ n \\<noteq> 0) A |i. row i A \\<noteq> 0}\" using row_iA_not_zero by auto\n      moreover have \"?v $ i = 1\" unfolding column_def by (auto, metis is_zero_row_eq_row_zero row_iA_not_zero rref_A rref_condition2)\n      ultimately show False using False by auto\n      qed\n    show ?thesis \n      unfolding xi_0\n      proof (unfold setsum_component vector_smult_component, rule setsum.neutral, rule ballI)\n      fix xa assume xa: \"xa \\<in> {column (LEAST n. A $ i $ n \\<noteq> 0) A |i. row i A \\<noteq> 0}\"\n      have \"xa $ i = 0\" using False xa by auto\n      thus \"x $ (THE i. xa $ i \\<noteq> 0) * xa $ i = 0\" by simp\n      qed          \n    next\n    case True\n    obtain v where v: \"v \\<in> {column (LEAST n. A $ i $ n \\<noteq> 0) A |i. row i A \\<noteq> 0}\" and vi: \"v $ i \\<noteq> 0\"\n      using True by blast\n    obtain b where b: \"v = column (LEAST n. A $ b $ n \\<noteq> 0) A\" and row_b: \"row b A \\<noteq> 0\" using v by blast\n    have vb: \"v $ b \\<noteq> 0\" unfolding b column_def by (auto, metis is_zero_row_eq_row_zero row_b rref_A rref_condition2 zero_neq_one)\n    have b_eq_i: \"b = i\" by (rule column_leading_coefficient_component_eq[OF rref_A v vb vi])     \n   have the_vi: \"(THE a. v $ a \\<noteq> 0) = i\"\n      proof (rule the_equality, rule vi)\n      fix a assume va: \"v $ a \\<noteq> 0\" show \"a=i\" by (rule column_leading_coefficient_component_eq[OF rref_A v va vi])\n      qed     \n    have vi_1: \"v $ i = 1\"  by (rule column_leading_coefficient_component_1[OF rref_A v vi])\n    have setsum0: \"(\\<Sum>v\\<in>{column (LEAST n. A $ i $ n \\<noteq> 0) A |i. row i A \\<noteq> 0} - {v}. x $ (THE a. v $ a \\<noteq> 0) * (v $ i)) = 0\"\n      proof (rule setsum.neutral, rule ballI)\n        fix xa assume xa: \"xa \\<in> {column (LEAST n. A $ i $ n \\<noteq> 0) A |i. row i A \\<noteq> 0} - {v}\"\n        obtain y where y: \"xa = column (LEAST n. A $ y $ n \\<noteq> 0) A\" and row_b: \"row y A \\<noteq> 0\" using xa by blast\n        have xa_in_V: \"xa \\<in> {column (LEAST n. A $ i $ n \\<noteq> 0) A |i. row i A \\<noteq> 0}\" using xa by simp\n        have \"xa $ i = 0\"\n          proof (rule column_leading_coefficient_component_0[OF rref_A xa_in_V])            \n           show \"xa $ y \\<noteq> 0\" unfolding y column_def\n            by (auto, metis (lifting, full_types) LeastI2_ex is_zero_row_def' is_zero_row_eq_row_zero row_b)\n            have \"y \\<noteq> b\" by (metis (mono_tags) Diff_iff b mem_Collect_eq singleton_conv2 xa y)\n            thus \"y \\<noteq> i\" unfolding b_eq_i[symmetric] . \n          qed\n        thus \"x $ (THE a. xa $ a \\<noteq> 0) * xa $ i = 0\" by simp      \n      qed\n    have \"(\\<Sum>v\\<in>{column (LEAST n. A $ i $ n \\<noteq> 0) A |i. row i A \\<noteq> 0}. x $ (THE a. v $ a \\<noteq> 0) *s v) $ i =\n    (\\<Sum>v\\<in>{column (LEAST n. A $ i $ n \\<noteq> 0) A |i. row i A \\<noteq> 0}. x $ (THE a. v $ a \\<noteq> 0) * (v $ i))\"\n      unfolding setsum_component vector_smult_component ..\n    also have \"... = x $ (THE a. v $ a \\<noteq> 0) * (v $ i) \n    + (\\<Sum>v\\<in>{column (LEAST n. A $ i $ n \\<noteq> 0) A |i. row i A \\<noteq> 0} - {v}. x $ (THE a. v $ a \\<noteq> 0) * (v $ i))\"\n      by (simp add: setsum.remove[OF _ v])\n    also have \"... = x $ (THE a. v $ a \\<noteq> 0) * (v $ i)\" unfolding setsum0 by simp\n    also have \"... = x $ (THE a. v $ a \\<noteq> 0)\" unfolding vi_1 by simp\n    also have \"... = x $ i\" unfolding the_vi .. \n    finally show \"(\\<Sum>v\\<in>{column (LEAST n. A $ i $ n \\<noteq> 0) A |i. row i A \\<noteq> 0}. x $ (THE a. v $ a \\<noteq> 0) *s v) $ i = x $ i\" .\n  qed\n qed \nqed\nqed (simp)\n\n\nlemma rref_row_rank:\n  fixes A::\"'a::{field}^'m::{mod_type}^'n::{finite,one,plus,ord}\"\n  assumes rref_A: \"reduced_row_echelon_form A\"\n  shows \"row_rank A = card {column (LEAST n. A $ i $ n \\<noteq> 0) A | i. row i A \\<noteq> 0}\"\n  proof - \n  let ?f=\"\\<lambda>x. column ((LEAST n. x $ n \\<noteq> 0)) A\"\n  show ?thesis\n  unfolding rref_rank[OF rref_A, unfolded rank_def]\n  proof (rule bij_betw_same_card[of ?f], unfold bij_betw_def, auto)\n    show \"inj_on (\\<lambda>x. column (LEAST n. x $ n \\<noteq> 0) A) {row i A |i. row i A \\<noteq> 0}\"\n      unfolding inj_on_def\n      proof (auto)\n        fix i ia\n        assume i: \"row i A \\<noteq> 0\" and ia: \"row ia A \\<noteq> 0\"\n         and c_eq: \"column (LEAST n. row i A $ n \\<noteq> 0) A = column (LEAST n. row ia A $ n \\<noteq> 0) A\"\n         show \"row i A = row ia A\"\n        using c_eq unfolding column_def unfolding row_def vec_nth_inverse\n        proof -\n          have \"transpose_row A (LEAST R. A $ ia $ R \\<noteq> 0) = transpose_row A (LEAST R. A $ i $ R \\<noteq> 0)\"\n           by (metis c_eq column_def row_def transpose_row_def vec_nth_inverse)\n          hence f1: \"\\<And>x\\<^sub>1. A $ x\\<^sub>1 $ (LEAST R. A $ ia $ R \\<noteq> 0) = A $ x\\<^sub>1 $ (LEAST R. A $ i $ R \\<noteq> 0)\"\n            by (metis (no_types) transpose_row_def vec_lambda_beta)\n          have f2: \"is_zero_row ia A = False\"\n            using ia is_zero_row_eq_row_zero by auto\n          have f3: \"\\<not> is_zero_row i A\"\n            using i is_zero_row_eq_row_zero by auto\n          have \"A $ ia $ (LEAST R. A $ i $ R \\<noteq> 0) = 1\"\n            using f1 f2 rref_A rref_condition2 by fastforce\n          thus \"A $ i = A $ ia\"\n            using f3 rref_A rref_condition4_explicit by fastforce\n         qed\n        qed\n      next\n    fix i\n    assume i: \"row i A \\<noteq> 0\"\n    show \"\\<exists>ia. column (LEAST n. row i A $ n \\<noteq> 0) A = column (LEAST n. A $ ia $ n \\<noteq> 0) A \\<and> row ia A \\<noteq> 0\"\n      by (rule exI[of _ \"i\"], simp add: row_def vec_lambda_eta)\n         (metis i is_zero_row_def' is_zero_row_eq_row_zero zero_index)\n      next\n      fix i\n      assume i: \"row i A \\<noteq> 0\"\n      show \"column (LEAST n. A $ i $ n \\<noteq> 0) A \\<in> (\\<lambda>x. column (LEAST n. x $ n \\<noteq> 0) A) ` {row i A |i. row i A \\<noteq> 0}\"\n      unfolding column_def row_def image_def\n      by (auto, metis i row_def vec_lambda_eta)\n      qed\nqed\n  \n  \n\nlemma row_rank_eq_col_rank_rref:\nfixes A::\"'a::{field}^'m::{mod_type}^'n::{mod_type}\"\nassumes r: \"reduced_row_echelon_form A\"\nshows \"row_rank A = col_rank A\"\n  unfolding rref_row_rank[OF r] rref_col_rank[OF r] ..\n\nlemma row_rank_eq_col_rank:\n  fixes A::\"'a::{field}^'n::{mod_type}^'m::{mod_type}\"\n  shows \"row_rank A = col_rank A\"\nproof -\nobtain P where inv_P: \"invertible P\" and G_PA: \"(Gauss_Jordan A) = P**A\"\n  and rref_G: \"reduced_row_echelon_form (Gauss_Jordan A)\"\n  using invertible_Gauss_Jordan rref_Gauss_Jordan by blast\nhave \"row_rank A = row_rank (Gauss_Jordan A)\"\n  by (metis row_space_is_preserved invertible_Gauss_Jordan row_rank_def)\nmoreover have \"col_rank A = col_rank (Gauss_Jordan A)\"\n  by (metis invertible_Gauss_Jordan crk_is_preserved)\nmoreover have \"col_rank (Gauss_Jordan A) = row_rank (Gauss_Jordan A)\"\n  using row_rank_eq_col_rank_rref[OF rref_G] by simp\nultimately show ?thesis by simp\nqed\n  \n\ntheorem rank_col_rank:\n  fixes A::\"'a::{field}^'n::{mod_type}^'m::{mod_type}\"\n  shows \"rank A = col_rank A\" unfolding rank_def row_rank_eq_col_rank ..\n\ntheorem rank_eq_dim_image:\n  fixes A::\"'a::{field}^'n::{mod_type}^'m::{mod_type}\"\n  shows \"rank A = vec.dim (range (\\<lambda>x. A *v x))\"\n  unfolding rank_col_rank col_rank_def col_space_eq' ..\n\ntheorem rank_eq_dim_col_space:\n  fixes A::\"'a::{field}^'n::{mod_type}^'m::{mod_type}\"\n  shows \"rank A = vec.dim (col_space A)\" using rank_col_rank unfolding col_rank_def .\n\nlemma rank_transpose: \n  fixes A::\"'a::{field}^'n::{mod_type}^'m::{mod_type}\"\n  shows  \"rank (transpose A) = rank A\"\n  by (metis rank_def rank_eq_dim_col_space row_rank_def row_space_eq_col_space_transpose)\n\nlemma rank_le_nrows:\n  fixes A::\"'a::{field}^'n::{mod_type}^'m::{mod_type}\"\n  shows \"rank A \\<le> nrows A\"\n  unfolding rank_eq_dim_col_space nrows_def\n  by (metis top_greatest vec.dim_subset vec_dim_card) \n\nlemma rank_le_ncols:\n  fixes A::\"'a::{field}^'n::{mod_type}^'m::{mod_type}\"\n  shows \"rank A \\<le> ncols A\"\n  unfolding rank_def row_rank_def ncols_def \n  by (metis top_greatest vec.dim_subset vec_dim_card)\n\nlemma rank_Gauss_Jordan:\n  fixes A::\"'a::{field}^'n::{mod_type}^'m::{mod_type}\"\n  shows \"rank A = rank (Gauss_Jordan A)\"\n  by (metis Gauss_Jordan_def invertible_Gauss_Jordan_up_to_k \n      row_rank_eq_col_rank rank_def crk_is_preserved)\n\ntext{*Other interesting properties:*}\n\nlemma A_0_imp_Gauss_Jordan_0:\n  fixes A::\"'a::{field}^'n::{mod_type}^'m::{mod_type}\"\n  assumes \"A=0\"\n  shows \"Gauss_Jordan A = 0\"\nproof -\nobtain P where PA: \"Gauss_Jordan A = P ** A\" using invertible_Gauss_Jordan by blast\nalso have \"... = 0\" unfolding assms by (metis eq_add_iff matrix_add_ldistrib)\nfinally show \"Gauss_Jordan A = 0\" .\nqed\n\nlemma rank_0: \"rank 0 = 0\"\nunfolding rank_def row_rank_def row_space_def rows_def row_def\nby (simp add: vec.dim_span vec.dim_zero_eq' vec_nth_inverse)\n\n\nlemma rank_greater_zero:\n  assumes \"A \\<noteq> 0\"\n  shows \"rank A > 0\"\nproof (rule ccontr, simp)\nassume \"rank A = 0\"\nhence \"row_space A = {} \\<or> row_space A = {0}\" unfolding rank_def row_rank_def using vec.dim_zero_eq by blast\nhence \"row_space A = {0}\" unfolding row_space_def using vec.span_0 by blast\nhence \"rows A = {} \\<or> rows A = {0}\" unfolding row_space_def using vec.span_0_imp_set_empty_or_0 by blast\nhence \"rows A = {0}\" unfolding rows_def row_def by force\nhence \"A = 0\" unfolding rows_def row_def vec_nth_inverse\n   by (auto, metis (mono_tags) mem_Collect_eq singleton_iff vec_lambda_unique zero_index)\nthus False using assms by contradiction\nqed\n\nlemma Gauss_Jordan_not_0:\nfixes A::\"'a::{field}^'cols::{mod_type}^'rows::{mod_type}\"\nassumes \"A \\<noteq> 0\"\nshows \"Gauss_Jordan A \\<noteq> 0\"\nby (metis assms less_not_refl3 rank_0 rank_Gauss_Jordan rank_greater_zero)\n\nlemma rank_eq_suc_to_nat_greatest:\nassumes A_not_0: \"A \\<noteq> 0\"\nshows \"rank A = to_nat (GREATEST' a. \\<not> is_zero_row a (Gauss_Jordan A)) + 1\"\nproof -\nhave rref: \"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  by auto\nhave not_all_zero: \"\\<not> (\\<forall>a. is_zero_row_upt_k a (ncols (Gauss_Jordan A)) (Gauss_Jordan A))\"\nunfolding is_zero_row_def[symmetric] using Gauss_Jordan_not_0[OF A_not_0] unfolding is_zero_row_def' by (metis vec_eq_iff zero_index)\nhave \"rank A = card {row i (Gauss_Jordan A) |i. row i (Gauss_Jordan A) \\<noteq> 0}\"\nunfolding rank_Gauss_Jordan[of A] unfolding rref_rank[OF rref_Gauss_Jordan] ..\nalso have \"... = card {i. i\\<le>(GREATEST' a. \\<not> is_zero_row a (Gauss_Jordan A))}\"\n  proof (rule bij_betw_same_card[symmetric, of \"\\<lambda>i. row i (Gauss_Jordan A)\"], unfold bij_betw_def, rule conjI)\n    show \"inj_on (\\<lambda>i. row i (Gauss_Jordan A)) {i. i \\<le> (GREATEST' a. \\<not> is_zero_row a (Gauss_Jordan A))}\"\n        proof (unfold inj_on_def, auto, rule ccontr)\n         fix x y\n         assume x: \"x \\<le> (GREATEST' a. \\<not> is_zero_row a (Gauss_Jordan A))\" and y: \"y \\<le> (GREATEST' a. \\<not> is_zero_row a (Gauss_Jordan A))\"\n         and xy_eq_row: \"row x (Gauss_Jordan A) = row y (Gauss_Jordan A)\" and x_not_y: \"x \\<noteq> y\"\n         show False\n          proof (cases \"x<y\")\n            case True\n              have \"(LEAST n. (Gauss_Jordan A) $ x $ n \\<noteq> 0) < (LEAST n. (Gauss_Jordan A) $ y $ n \\<noteq> 0)\"\n                proof (rule rref_condition3_equiv[OF rref_Gauss_Jordan True])\n                  show \"\\<not> is_zero_row x (Gauss_Jordan A)\"\n                  by (unfold is_zero_row_def, \n                    rule greatest_ge_nonzero_row'[OF rref x[unfolded is_zero_row_def] not_all_zero])\n                  show \"\\<not> is_zero_row y (Gauss_Jordan A)\" by (unfold is_zero_row_def, rule greatest_ge_nonzero_row'[OF rref y[unfolded is_zero_row_def] not_all_zero])\n               qed\n              thus ?thesis by (metis less_irrefl row_def vec_nth_inverse xy_eq_row)\n            next\n            case False\n            hence x_ge_y: \"x>y\" using x_not_y by simp\n            have \"(LEAST n. (Gauss_Jordan A) $ y $ n \\<noteq> 0) < (LEAST n. (Gauss_Jordan A) $ x $ n \\<noteq> 0)\"\n              proof (rule rref_condition3_equiv[OF rref_Gauss_Jordan x_ge_y])\n                  show \"\\<not> is_zero_row x (Gauss_Jordan A)\"\n                  by (unfold is_zero_row_def, rule greatest_ge_nonzero_row'[OF rref x[unfolded is_zero_row_def] not_all_zero])\n                  show \"\\<not> is_zero_row y (Gauss_Jordan A)\" by (unfold is_zero_row_def, rule greatest_ge_nonzero_row'[OF rref y[unfolded is_zero_row_def] not_all_zero])\n               qed\n            thus ?thesis by (metis dual_order.less_irrefl row_def vec_nth_inverse xy_eq_row)\n      qed\n      qed\n    show \"(\\<lambda>i. row i (Gauss_Jordan A)) ` {i. i \\<le> (GREATEST' a. \\<not> is_zero_row a (Gauss_Jordan A))} = {row i (Gauss_Jordan A) |i. row i (Gauss_Jordan A) \\<noteq> 0}\"\n    proof (unfold image_def, auto)\n      fix xa\n      assume  xa: \"xa \\<le> (GREATEST' a. \\<not> is_zero_row a (Gauss_Jordan A))\"\n      show \"\\<exists>i. row xa (Gauss_Jordan A) = row i (Gauss_Jordan A) \\<and> row i (Gauss_Jordan A) \\<noteq> 0\"\n          proof (rule exI[of _ xa], simp)\n              have \"\\<not> is_zero_row xa (Gauss_Jordan A)\" \n                by (unfold is_zero_row_def, rule greatest_ge_nonzero_row'[OF rref xa[unfolded is_zero_row_def] not_all_zero])                  \n              thus \"row xa (Gauss_Jordan A) \\<noteq> 0\" unfolding row_def is_zero_row_def' by (metis vec_nth_inverse zero_index)\n              qed\nnext\n  fix i\n  assume  \"row i (Gauss_Jordan A) \\<noteq> 0\"\n  hence \"\\<not> is_zero_row i (Gauss_Jordan A)\" unfolding row_def is_zero_row_def' by (metis vec_eq_iff vec_nth_inverse zero_index)\n  hence \"i \\<le> (GREATEST' a. \\<not> is_zero_row a (Gauss_Jordan A))\" using Greatest'_ge by fast\n  thus \"\\<exists>x\\<le>GREATEST' a. \\<not> is_zero_row a (Gauss_Jordan A). row i (Gauss_Jordan A) = row x (Gauss_Jordan A)\"\n    by blast\nqed\nqed\nalso have \"... = card {i. i \\<le> to_nat (GREATEST' a. \\<not> is_zero_row a (Gauss_Jordan A))}\"\nproof (rule bij_betw_same_card[of \"\\<lambda>i. to_nat i\"], unfold bij_betw_def, rule conjI)\n  show \"inj_on to_nat {i. i \\<le> (GREATEST' a. \\<not> is_zero_row a (Gauss_Jordan A))}\" using bij_to_nat by (metis bij_betw_imp_inj_on subset_inj_on top_greatest)\n  show \"to_nat ` {i. i \\<le> (GREATEST' a. \\<not> is_zero_row a (Gauss_Jordan A))} = {i. i \\<le> to_nat (GREATEST' a. \\<not> is_zero_row a (Gauss_Jordan A))}\"    \n    proof (unfold image_def, auto simp add: to_nat_mono')\n    fix x\n    assume x: \"x \\<le> to_nat (GREATEST' a. \\<not> is_zero_row a (Gauss_Jordan A))\"\n    hence \"from_nat x \\<le> (GREATEST' a. \\<not> is_zero_row a (Gauss_Jordan A))\"\n    by (metis (full_types) leD not_leE to_nat_le)\n    moreover have \"x < CARD('c)\" using x bij_to_nat[where ?'a='b] unfolding bij_betw_def  by (metis less_le_trans not_le to_nat_less_card)\n    ultimately show \"\\<exists>xa\\<le>GREATEST' a. \\<not> is_zero_row a (Gauss_Jordan A). x = to_nat xa\" using to_nat_from_nat_id by fastforce\n    qed\n    qed\n    also have \"... = to_nat (GREATEST' a. \\<not> is_zero_row a (Gauss_Jordan A)) + 1\" unfolding card_Collect_le_nat by simp\n    finally show ?thesis .\nqed\n\n\nlemma rank_less_row_i_imp_i_is_zero:\nassumes rank_less_i: \"to_nat i \\<ge> rank A\"\nshows \"Gauss_Jordan A $ i = 0\"\nproof (cases \"A=0\")\ncase True thus ?thesis by (metis A_0_imp_Gauss_Jordan_0 zero_index)\nnext\ncase False\nhave \"to_nat i \\<ge> to_nat (GREATEST' a. \\<not> is_zero_row a (Gauss_Jordan A)) + 1\" using rank_less_i unfolding rank_eq_suc_to_nat_greatest[OF False] .\nhence \"i>(GREATEST' a. \\<not> is_zero_row a (Gauss_Jordan A))\"\n  by (metis One_nat_def add.commute add_strict_increasing \n    add_strict_increasing2 le0 lessI neq_iff not_le to_nat_mono)\nhence \"is_zero_row i (Gauss_Jordan A)\" using not_greater_Greatest' by auto\nthus ?thesis unfolding is_zero_row_def' vec_eq_iff by auto\nqed\n\nlemma rank_Gauss_Jordan_eq:\n  fixes A::\"'a::{field}^'n::{mod_type}^'m::{mod_type}\"\n  shows \"rank A = (let A'=(Gauss_Jordan A) in card {row i A' |i. row i A' \\<noteq> 0})\"\n  by (metis (mono_tags) rank_Gauss_Jordan rref_Gauss_Jordan rref_rank)\n\nsubsection{*Lemmas for code generation and rank computation*}\n\nlemma [code abstract]: \nshows \"vec_nth (Gauss_Jordan_in_ij A i j) = (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 \n  (% s. if s=i then A' $ s else (row_add A' s i (-(interchange_A$s$j))) $ s))\"\n  unfolding Gauss_Jordan_in_ij_def Let_def by fastforce\n\nlemma rank_Gauss_Jordan_code[code]:\n  fixes A::\"'a::{field}^'n::{mod_type}^'m::{mod_type}\"\n  shows \"rank A = (if A = 0 then 0 else (let A'=(Gauss_Jordan A) in to_nat (GREATEST' a. row a A' \\<noteq> 0) + 1))\"\n  proof (cases \"A = 0\")\n    case True show ?thesis unfolding if_P[OF True] unfolding True  rank_0 ..\n    next\n    case False\n    show ?thesis unfolding if_not_P[OF False]\n    unfolding rank_eq_suc_to_nat_greatest[OF False] Let_def is_zero_row_eq_row_zero ..\nqed\n\nlemma dim_null_space[code_unfold]:\n  fixes A::\"'a::{field}^'cols::{mod_type}^'rows::{mod_type}\"\n  shows \"vec.dim (null_space A) = (vec.dimension TYPE('a) TYPE('cols)) - rank (A)\"\n  apply (rule add_implies_diff) \n  using rank_nullity_theorem_matrices  \n  unfolding rank_eq_dim_col_space[of A]\n  unfolding dimension_vector ncols_def ..\n  \nlemma rank_eq_dim_col_space'[code_unfold]:\n fixes A::\"'a::{field}^'cols::{mod_type}^'rows::{mod_type}\"\n shows \"vec.dim (col_space A) = rank A\" unfolding  rank_eq_dim_col_space ..\n\nlemma dim_left_null_space[code_unfold]:\n  fixes A::\"'a::{field}^'cols::{mod_type}^'rows::{mod_type}\"\n  shows \"vec.dim (left_null_space A) = (vec.dimension TYPE('a) TYPE('rows)) - rank (A)\"\n  unfolding left_null_space_eq_null_space_transpose\n  unfolding dim_null_space unfolding rank_transpose ..\n\nlemmas rank_col_rank[symmetric, code_unfold]\nlemmas rank_def[symmetric, code_unfold]\nlemmas row_rank_def[symmetric, code_unfold]\nlemmas col_rank_def[symmetric, code_unfold]\nlemmas DIM_cart[code_unfold]\nlemmas DIM_real[code_unfold]\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/Gauss_Jordan.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9149009549929797, "lm_q2_score": 0.8128673110375457, "lm_q1q2_score": 0.743693079150826}}
{"text": "(*  Title:      HOL/Algebra/Indexed_Polynomials.thy\n    Author:     Paulo Em\u00edlio de Vilhena\n*)\n\ntheory Indexed_Polynomials\n  imports Weak_Morphisms \"HOL-Library.Multiset\" Polynomial_Divisibility\n    \nbegin\n\nsection \\<open>Indexed Polynomials\\<close>\n\ntext \\<open>In this theory, we build a basic framework to the study of polynomials on letters\n      indexed by a set. The main interest is to then apply these concepts to the construction\n      of the algebraic closure of a field. \\<close>\n\n\nsubsection \\<open>Definitions\\<close>\n\ntext \\<open>We formalize indexed monomials as multisets with its support a subset of the index set.\n      On top of those, we build indexed polynomials which are simply functions mapping a monomial\n      to its coefficient. \\<close>\n\ndefinition (in ring) indexed_const :: \"'a \\<Rightarrow> ('c multiset \\<Rightarrow> 'a)\" \n  where \"indexed_const k = (\\<lambda>m. if m = {#} then k else \\<zero>)\"\n\ndefinition (in ring) indexed_pmult :: \"('c multiset \\<Rightarrow> 'a) \\<Rightarrow> 'c \\<Rightarrow> ('c multiset \\<Rightarrow> 'a)\" (infixl \"\\<Otimes>\" 65)\n  where \"indexed_pmult P i = (\\<lambda>m. if i \\<in># m then P (m - {# i #}) else \\<zero>)\"\n\ndefinition (in ring) indexed_padd :: \"_ \\<Rightarrow> _ \\<Rightarrow> ('c multiset \\<Rightarrow> 'a)\" (infixl \"\\<Oplus>\" 65)\n  where \"indexed_padd P Q = (\\<lambda>m. (P m) \\<oplus> (Q m))\"\n\ndefinition (in ring) indexed_var :: \"'c \\<Rightarrow> ('c multiset \\<Rightarrow> 'a)\" (\"\\<X>\\<index>\")\n  where \"indexed_var i = (indexed_const \\<one>) \\<Otimes> i\"\n\ndefinition (in ring) index_free :: \"('c multiset \\<Rightarrow> 'a) \\<Rightarrow> 'c \\<Rightarrow> bool\"\n  where \"index_free P i \\<longleftrightarrow> (\\<forall>m. i \\<in># m \\<longrightarrow> P m = \\<zero>)\"\n\ndefinition (in ring) carrier_coeff :: \"('c multiset \\<Rightarrow> 'a) \\<Rightarrow> bool\"\n  where \"carrier_coeff P \\<longleftrightarrow> (\\<forall>m. P m \\<in> carrier R)\"\n\ninductive_set (in ring) indexed_pset :: \"'c set \\<Rightarrow> 'a set \\<Rightarrow> ('c multiset \\<Rightarrow> 'a) set\" (\"_ [\\<X>\\<index>]\" 80)\n  for I and K where\n    indexed_const:  \"k \\<in> K \\<Longrightarrow> indexed_const k \\<in> (K[\\<X>\\<^bsub>I\\<^esub>])\"\n  | indexed_padd:  \"\\<lbrakk> P \\<in> (K[\\<X>\\<^bsub>I\\<^esub>]); Q \\<in> (K[\\<X>\\<^bsub>I\\<^esub>]) \\<rbrakk> \\<Longrightarrow> P \\<Oplus> Q \\<in> (K[\\<X>\\<^bsub>I\\<^esub>])\"\n  | indexed_pmult: \"\\<lbrakk> P \\<in> (K[\\<X>\\<^bsub>I\\<^esub>]); i \\<in> I \\<rbrakk> \\<Longrightarrow> P \\<Otimes> i \\<in> (K[\\<X>\\<^bsub>I\\<^esub>])\"\n\nfun (in ring) indexed_eval_aux :: \"('c multiset \\<Rightarrow> 'a) list \\<Rightarrow> 'c \\<Rightarrow> ('c multiset \\<Rightarrow> 'a)\"\n  where \"indexed_eval_aux Ps i = foldr (\\<lambda>P Q. (Q \\<Otimes> i) \\<Oplus> P) Ps (indexed_const \\<zero>)\"\n\nfun (in ring) indexed_eval :: \"('c multiset \\<Rightarrow> 'a) list \\<Rightarrow> 'c \\<Rightarrow> ('c multiset \\<Rightarrow> 'a)\"\n  where \"indexed_eval Ps i = indexed_eval_aux (rev Ps) i\"\n\n\nsubsection \\<open>Basic Properties\\<close>\n\nlemma (in ring) carrier_coeffE:\n  assumes \"carrier_coeff P\" shows \"P m \\<in> carrier R\"\n  using assms unfolding carrier_coeff_def by simp\n\nlemma (in ring) indexed_zero_def: \"indexed_const \\<zero> = (\\<lambda>_. \\<zero>)\"\n  unfolding indexed_const_def by simp\n\nlemma (in ring) indexed_const_index_free: \"index_free (indexed_const k) i\"\n  unfolding index_free_def indexed_const_def by auto\n\nlemma (in domain) indexed_var_not_index_free: \"\\<not> index_free \\<X>\\<^bsub>i\\<^esub> i\"\nproof -\n  have \"\\<X>\\<^bsub>i\\<^esub> {# i #} = \\<one>\"\n    unfolding indexed_var_def indexed_pmult_def indexed_const_def by simp\n  thus ?thesis\n    using one_not_zero unfolding index_free_def by fastforce \nqed\n\nlemma (in ring) indexed_pmult_zero [simp]:\n  shows \"indexed_pmult (indexed_const \\<zero>) i = indexed_const \\<zero>\"\n  unfolding indexed_zero_def indexed_pmult_def by auto\n\nlemma (in ring) indexed_padd_zero:\n  assumes \"carrier_coeff P\" shows \"P \\<Oplus> (indexed_const \\<zero>) = P\" and \"(indexed_const \\<zero>) \\<Oplus> P = P\"\n  using assms unfolding carrier_coeff_def indexed_zero_def indexed_padd_def by auto\n\nlemma (in ring) indexed_padd_const:\n  shows \"(indexed_const k1) \\<Oplus> (indexed_const k2) = indexed_const (k1 \\<oplus> k2)\"\n  unfolding indexed_padd_def indexed_const_def by auto\n\nlemma (in ring) indexed_const_in_carrier:\n  assumes \"K \\<subseteq> carrier R\" and \"k \\<in> K\" shows \"\\<And>m. (indexed_const k) m \\<in> carrier R\"\n  using assms unfolding indexed_const_def by auto\n\nlemma (in ring) indexed_padd_in_carrier:\n  assumes \"carrier_coeff P\" and \"carrier_coeff Q\" shows \"carrier_coeff (indexed_padd P Q)\"\n  using assms unfolding carrier_coeff_def indexed_padd_def by simp\n\nlemma (in ring) indexed_pmult_in_carrier:\n  assumes \"carrier_coeff P\" shows \"carrier_coeff (P \\<Otimes> i)\"\n  using assms unfolding carrier_coeff_def indexed_pmult_def by simp\n\nlemma (in ring) indexed_eval_aux_in_carrier:\n  assumes \"list_all carrier_coeff Ps\" shows \"carrier_coeff (indexed_eval_aux Ps i)\"\n  using assms unfolding carrier_coeff_def\n  by (induct Ps) (auto simp add: indexed_zero_def indexed_padd_def indexed_pmult_def)\n\nlemma (in ring) indexed_eval_in_carrier:\n  assumes \"list_all carrier_coeff Ps\" shows \"carrier_coeff (indexed_eval Ps i)\"\n  using assms indexed_eval_aux_in_carrier[of \"rev Ps\"] by auto\n\nlemma (in ring) indexed_pset_in_carrier:\n  assumes \"K \\<subseteq> carrier R\" and \"P \\<in> (K[\\<X>\\<^bsub>I\\<^esub>])\" shows \"carrier_coeff P\"\n  using assms(2,1) indexed_const_in_carrier unfolding carrier_coeff_def\n  by (induction) (auto simp add: indexed_zero_def indexed_padd_def indexed_pmult_def)\n\n\nsubsection \\<open>Indexed Eval\\<close>\n\nlemma (in ring) exists_indexed_eval_aux_monomial:\n  assumes \"carrier_coeff P\" and \"list_all carrier_coeff Qs\"\n    and \"count n i = k\" and \"P n \\<noteq> \\<zero>\" and \"list_all (\\<lambda>Q. index_free Q i) Qs\"\n  obtains m where \"count m i = length Qs + k\" and \"(indexed_eval_aux (Qs @ [ P ]) i) m \\<noteq> \\<zero>\"\nproof -\n  from assms(2,5) have \"\\<exists>m. count m i = length Qs + k \\<and> (indexed_eval_aux (Qs @ [ P ]) i) m \\<noteq> \\<zero>\"\n  proof (induct Qs)\n    case Nil thus ?case\n      using indexed_padd_zero(2)[OF assms(1)] assms(3-4) by auto\n  next\n    case (Cons Q Qs)\n    then obtain m where m: \"count m i = length Qs + k\" \"(indexed_eval_aux (Qs @ [ P ]) i) m \\<noteq> \\<zero>\"\n      by auto\n    define m' where \"m' = m + {# i #}\"\n    hence \"Q m' = \\<zero>\"\n      using Cons(3) unfolding index_free_def by simp\n    moreover have \"(indexed_eval_aux (Qs @ [ P ]) i) m \\<in> carrier R\"\n      using indexed_eval_aux_in_carrier[of \"Qs @ [ P ]\" i] Cons(2) assms(1) carrier_coeffE by auto\n    hence \"((indexed_eval_aux (Qs @ [ P ]) i) \\<Otimes> i) m' \\<in> carrier R - { \\<zero> }\"\n      using m unfolding indexed_pmult_def m'_def by simp\n    ultimately have \"(indexed_eval_aux (Q # (Qs @ [ P ])) i) m' \\<noteq> \\<zero>\"\n      by (auto simp add: indexed_padd_def)\n    moreover from \\<open>count m i = length Qs + k\\<close> have \"count m' i = length (Q # Qs) + k\"\n      unfolding m'_def by simp\n    ultimately show ?case\n      by auto\n  qed\n  thus thesis\n    using that by blast\nqed\n\nlemma (in ring) indexed_eval_aux_monomial_degree_le:\n  assumes \"list_all carrier_coeff Ps\" and \"list_all (\\<lambda>P. index_free P i) Ps\"\n    and \"(indexed_eval_aux Ps i) m \\<noteq> \\<zero>\" shows \"count m i \\<le> length Ps - 1\"\n  using assms(1-3)\nproof (induct Ps arbitrary: m, simp add: indexed_zero_def)\n  case (Cons P Ps) show ?case\n  proof (cases \"count m i = 0\", simp)\n    assume \"count m i \\<noteq> 0\"\n    hence \"P m = \\<zero>\"\n      using Cons(3) unfolding index_free_def by simp\n    moreover have \"(indexed_eval_aux Ps i) m \\<in> carrier R\"\n      using carrier_coeffE[OF indexed_eval_aux_in_carrier[of Ps i]] Cons(2) by simp \n    ultimately have \"((indexed_eval_aux Ps i) \\<Otimes> i) m \\<noteq> \\<zero>\"\n      using Cons(4) by (auto simp add: indexed_padd_def)\n    with \\<open>count m i \\<noteq> 0\\<close> have \"(indexed_eval_aux Ps i) (m - {# i #}) \\<noteq> \\<zero>\"\n      unfolding indexed_pmult_def by (auto simp del: indexed_eval_aux.simps)\n    hence \"count m i - 1 \\<le> length Ps - 1\"\n      using Cons(1)[of \"m - {# i #}\"] Cons(2-3) by auto\n    moreover from \\<open>(indexed_eval_aux Ps i) (m - {# i #}) \\<noteq> \\<zero>\\<close> have \"length Ps > 0\"\n      by (auto simp add: indexed_zero_def)\n    moreover from \\<open>count m i \\<noteq> 0\\<close> have \"count m i > 0\"\n      by simp\n    ultimately show ?thesis\n      by (simp add: Suc_leI le_diff_iff)\n  qed\nqed\n\nlemma (in ring) indexed_eval_aux_is_inj:\n  assumes \"list_all carrier_coeff Ps\" and \"list_all (\\<lambda>P. index_free P i) Ps\"\n      and \"list_all carrier_coeff Qs\" and \"list_all (\\<lambda>Q. index_free Q i) Qs\"\n    and \"indexed_eval_aux Ps i = indexed_eval_aux Qs i\" and \"length Ps = length Qs\"\n  shows \"Ps = Qs\"\n  using assms\nproof (induct Ps arbitrary: Qs, simp)\n  case (Cons P Ps)\n  from \\<open>length (P # Ps) = length Qs\\<close> obtain Q' Qs' where Qs: \"Qs = Q' # Qs'\" and \"length Ps = length Qs'\"\n    by (metis Suc_length_conv)\n\n  have in_carrier:\n    \"((indexed_eval_aux Ps  i) \\<Otimes> i) m \\<in> carrier R\" \"P  m \\<in> carrier R\"\n    \"((indexed_eval_aux Qs' i) \\<Otimes> i) m \\<in> carrier R\" \"Q' m \\<in> carrier R\" for m\n    using indexed_eval_aux_in_carrier[of Ps  i]\n          indexed_eval_aux_in_carrier[of Qs' i] Cons(2,4) carrier_coeffE\n    unfolding Qs indexed_pmult_def by auto\n\n  have \"(indexed_eval_aux (P # Ps) i) m = (indexed_eval_aux (Q' # Qs') i) m\" for m\n    using Cons(6) unfolding Qs by simp\n  hence eq: \"((indexed_eval_aux Ps i) \\<Otimes> i) m \\<oplus> P m = ((indexed_eval_aux Qs' i) \\<Otimes> i) m \\<oplus> Q' m\" for m\n    by (simp add: indexed_padd_def)\n\n  have \"P m = Q' m\" if \"i \\<in># m\" for m\n    using that Cons(3,5) unfolding index_free_def Qs by auto\n  moreover have \"P m = Q' m\" if \"i \\<notin># m\" for m\n    using in_carrier(2,4) eq[of m] that by (auto simp add: indexed_pmult_def)\n  ultimately have \"P = Q'\"\n    by auto\n\n  hence \"(indexed_eval_aux Ps i) m = (indexed_eval_aux Qs' i) m\" for m\n    using eq[of \"m + {# i #}\"] in_carrier[of \"m + {# i #}\"] unfolding indexed_pmult_def by auto\n  with \\<open>length Ps = length Qs'\\<close> have \"Ps = Qs'\"\n    using Cons(1)[of Qs'] Cons(2-5) unfolding Qs by auto\n  with \\<open>P = Q'\\<close> show ?case\n    unfolding Qs by simp\nqed\n\nlemma (in ring) indexed_eval_aux_is_inj':\n  assumes \"list_all carrier_coeff Ps\" and \"list_all (\\<lambda>P. index_free P i) Ps\"\n      and \"list_all carrier_coeff Qs\" and \"list_all (\\<lambda>Q. index_free Q i) Qs\"\n      and \"carrier_coeff P\" and \"index_free P i\" \"P \\<noteq> indexed_const \\<zero>\"\n      and \"carrier_coeff Q\" and \"index_free Q i\" \"Q \\<noteq> indexed_const \\<zero>\"\n    and \"indexed_eval_aux (Ps @ [ P ]) i = indexed_eval_aux (Qs @ [ Q ]) i\"\n  shows \"Ps = Qs\" and \"P = Q\"\nproof -\n  obtain m n where \"P m \\<noteq> \\<zero>\" and \"Q n \\<noteq> \\<zero>\"\n    using assms(7,10) unfolding indexed_zero_def by blast\n  hence \"count m i = 0\" and \"count n i = 0\"\n    using assms(6,9) unfolding index_free_def by (meson count_inI)+ \n  with \\<open>P m \\<noteq> \\<zero>\\<close> and \\<open>Q n \\<noteq> \\<zero>\\<close> obtain m' n'\n    where m': \"count m' i = length Ps\" \"(indexed_eval_aux (Ps @ [ P ]) i) m' \\<noteq> \\<zero>\"\n      and n': \"count n' i = length Qs\" \"(indexed_eval_aux (Qs @ [ Q ]) i) n' \\<noteq> \\<zero>\"\n    using exists_indexed_eval_aux_monomial[of P Ps m i 0]\n          exists_indexed_eval_aux_monomial[of Q Qs n i 0] assms(1-5,8)\n    by (metis (no_types, lifting) add.right_neutral)\n  have \"(indexed_eval_aux (Qs @ [ Q ]) i) m' \\<noteq> \\<zero>\"\n    using m'(2) assms(11) by simp\n  with \\<open>count m' i = length Ps\\<close> have \"length Ps \\<le> length Qs\"\n    using indexed_eval_aux_monomial_degree_le[of \"Qs @ [ Q ]\" i m'] assms(3-4,8-9) by auto\n  moreover have \"(indexed_eval_aux (Ps @ [ P ]) i) n' \\<noteq> \\<zero>\"\n    using n'(2) assms(11) by simp\n  with \\<open>count n' i = length Qs\\<close> have \"length Qs \\<le> length Ps\"\n    using indexed_eval_aux_monomial_degree_le[of \"Ps @ [ P ]\" i n'] assms(1-2,5-6) by auto\n  ultimately have same_len: \"length (Ps @ [ P ]) = length (Qs @ [ Q ])\"\n    by simp\n  thus \"Ps = Qs\" and \"P = Q\"\n    using indexed_eval_aux_is_inj[of \"Ps @ [ P ]\" i \"Qs @ [ Q ]\"] assms(1-6,8-9,11) by auto\nqed\n\nlemma (in ring) exists_indexed_eval_monomial:\n  assumes \"carrier_coeff P\" and \"list_all carrier_coeff Qs\"\n    and \"P n \\<noteq> \\<zero>\" and \"list_all (\\<lambda>Q. index_free Q i) Qs\"\n  obtains m where \"count m i = length Qs + (count n i)\" and \"(indexed_eval (P # Qs) i) m \\<noteq> \\<zero>\"\n  using exists_indexed_eval_aux_monomial[OF assms(1) _ _ assms(3), of \"rev Qs\"] assms(2,4) by auto\n\ncorollary (in ring) exists_indexed_eval_monomial':\n  assumes \"carrier_coeff P\" and \"list_all carrier_coeff Qs\"\n    and \"P \\<noteq> indexed_const \\<zero>\" and \"list_all (\\<lambda>Q. index_free Q i) Qs\"\n  obtains m where \"count m i \\<ge> length Qs\" and \"(indexed_eval (P # Qs) i) m \\<noteq> \\<zero>\"\nproof -\n  from \\<open>P \\<noteq> indexed_const \\<zero>\\<close> obtain n where \"P n \\<noteq> \\<zero>\"\n    unfolding indexed_const_def by auto\n  then obtain m where \"count m i = length Qs + (count n i)\" and \"(indexed_eval (P # Qs) i) m \\<noteq> \\<zero>\"\n    using exists_indexed_eval_monomial[OF assms(1-2) _ assms(4)] by auto\n  thus thesis\n    using that by force\nqed\n\nlemma (in ring) indexed_eval_monomial_degree_le:\n  assumes \"list_all carrier_coeff Ps\" and \"list_all (\\<lambda>P. index_free P i) Ps\"\n    and \"(indexed_eval Ps i) m \\<noteq> \\<zero>\" shows \"count m i \\<le> length Ps - 1\"\n  using indexed_eval_aux_monomial_degree_le[of \"rev Ps\"] assms by auto\n\nlemma (in ring) indexed_eval_is_inj:\n  assumes \"list_all carrier_coeff Ps\" and \"list_all (\\<lambda>P. index_free P i) Ps\"\n      and \"list_all carrier_coeff Qs\" and \"list_all (\\<lambda>Q. index_free Q i) Qs\"\n      and \"carrier_coeff P\" and \"index_free P i\" \"P \\<noteq> indexed_const \\<zero>\"\n      and \"carrier_coeff Q\" and \"index_free Q i\" \"Q \\<noteq> indexed_const \\<zero>\"\n    and \"indexed_eval (P # Ps) i = indexed_eval (Q # Qs) i\"\n  shows \"Ps = Qs\" and \"P = Q\"\nproof -\n  have rev_cond:\n    \"list_all carrier_coeff (rev Ps)\" \"list_all (\\<lambda>P. index_free P i) (rev Ps)\"\n    \"list_all carrier_coeff (rev Qs)\" \"list_all (\\<lambda>Q. index_free Q i) (rev Qs)\"\n    using assms(1-4) by auto\n  show \"Ps = Qs\" and \"P = Q\"\n    using indexed_eval_aux_is_inj'[OF rev_cond assms(5-10)] assms(11) by auto\nqed\n\nlemma (in ring) indexed_eval_inj_on_carrier:\n  assumes \"\\<And>P. P \\<in> carrier L \\<Longrightarrow> carrier_coeff P\" and \"\\<And>P. P \\<in> carrier L \\<Longrightarrow> index_free P i\" and \"\\<zero>\\<^bsub>L\\<^esub> = indexed_const \\<zero>\"\n  shows \"inj_on (\\<lambda>Ps. indexed_eval Ps i) (carrier (poly_ring L))\"\nproof -\n  { fix Ps\n    assume \"Ps \\<in> carrier (poly_ring L)\" and \"indexed_eval Ps i = indexed_const \\<zero>\"\n    have \"Ps = []\"\n    proof (rule ccontr)\n      assume \"Ps \\<noteq> []\"\n      then obtain P' Ps' where Ps: \"Ps = P' # Ps'\"\n        using list.exhaust by blast\n      with \\<open>Ps \\<in> carrier (poly_ring L)\\<close>\n      have \"P' \\<noteq> indexed_const \\<zero>\" and \"list_all carrier_coeff Ps\" and \"list_all (\\<lambda>P. index_free P i) Ps\"\n        using assms unfolding sym[OF univ_poly_carrier[of L \"carrier L\"]] polynomial_def\n        by (simp add: list.pred_set subset_code(1))+\n      then obtain m where \"(indexed_eval Ps i) m \\<noteq> \\<zero>\"\n        using exists_indexed_eval_monomial'[of P' Ps'] unfolding Ps by auto\n      hence \"indexed_eval Ps i \\<noteq> indexed_const \\<zero>\"\n        unfolding indexed_const_def by auto\n      with \\<open>indexed_eval Ps i = indexed_const \\<zero>\\<close> show False by simp\n    qed } note aux_lemma = this\n\n  show ?thesis\n  proof (rule inj_onI)\n    fix Ps Qs\n    assume \"Ps \\<in> carrier (poly_ring L)\" and \"Qs \\<in> carrier (poly_ring L)\"\n    show \"indexed_eval Ps i = indexed_eval Qs i \\<Longrightarrow> Ps = Qs\"\n    proof (cases)\n      assume \"Qs = []\" and \"indexed_eval Ps i = indexed_eval Qs i\"\n      with \\<open>Ps \\<in> carrier (poly_ring L)\\<close> show \"Ps = Qs\"\n        using aux_lemma by simp\n    next\n      assume \"Qs \\<noteq> []\" and eq: \"indexed_eval Ps i = indexed_eval Qs i\"\n      with \\<open>Qs \\<in> carrier (poly_ring L)\\<close> have \"Ps \\<noteq> []\"\n        using aux_lemma by auto\n      from \\<open>Ps \\<noteq> []\\<close> and \\<open>Qs \\<noteq> []\\<close> obtain P' Ps' Q' Qs' where Ps: \"Ps = P' # Ps'\" and Qs: \"Qs = Q' # Qs'\"\n        using list.exhaust by metis\n\n      from \\<open>Ps \\<in> carrier (poly_ring L)\\<close> and \\<open>Ps = P' # Ps'\\<close>\n      have \"carrier_coeff P'\" and \"index_free P' i\" \"P' \\<noteq> indexed_const \\<zero>\"\n       and \"list_all carrier_coeff Ps'\" and \"list_all (\\<lambda>P. index_free P i) Ps'\"\n        using assms unfolding sym[OF univ_poly_carrier[of L \"carrier L\"]] polynomial_def\n        by (simp add: list.pred_set subset_code(1))+\n      moreover \n      from \\<open>Qs \\<in> carrier (poly_ring L)\\<close> and \\<open>Qs = Q' # Qs'\\<close>\n      have \"carrier_coeff Q'\" and \"index_free Q' i\" \"Q' \\<noteq> indexed_const \\<zero>\"\n       and \"list_all carrier_coeff Qs'\" and \"list_all (\\<lambda>P. index_free P i) Qs'\"\n        using assms unfolding sym[OF univ_poly_carrier[of L \"carrier L\"]] polynomial_def\n        by (simp add: list.pred_set subset_code(1))+\n      ultimately show ?thesis\n        using indexed_eval_is_inj[of Ps' i Qs' P' Q'] eq unfolding Ps Qs by auto\n    qed\n  qed\nqed\n\n\nsubsection \\<open>Link with Weak Morphisms\\<close>\n\ntext \\<open>We study some elements of the contradiction needed in the algebraic closure existence proof. \\<close>\n\ncontext ring\nbegin\n\nlemma (in ring) indexed_padd_index_free:\n  assumes \"index_free P i\" and \"index_free Q i\" shows \"index_free (P \\<Oplus> Q) i\"\n  using assms unfolding indexed_padd_def index_free_def by auto\n\nlemma (in ring) indexed_pmult_index_free:\n  assumes \"index_free P j\" and \"i \\<noteq> j\" shows \"index_free (P \\<Otimes> i) j\"\n  using assms unfolding index_free_def indexed_pmult_def\n  by (metis insert_DiffM insert_noteq_member)\n\nlemma (in ring) indexed_eval_index_free:\n  assumes \"list_all (\\<lambda>P. index_free P j) Ps\" and \"i \\<noteq> j\" shows \"index_free (indexed_eval Ps i) j\"\nproof -\n  { fix Ps assume \"list_all (\\<lambda>P. index_free P j) Ps\" hence \"index_free (indexed_eval_aux Ps i) j\"\n      using indexed_padd_index_free[OF indexed_pmult_index_free[OF _ assms(2)]]\n      by (induct Ps) (auto simp add: indexed_zero_def index_free_def) }\n  thus ?thesis\n    using assms(1) by auto\nqed\n\ncontext\n  fixes L :: \"(('c multiset) \\<Rightarrow> 'a) ring\" and i :: 'c\n  assumes hyps:\n    \\<comment> \\<open>i\\<close>   \"field L\"\n    \\<comment> \\<open>ii\\<close>  \"\\<And>P. P \\<in> carrier L \\<Longrightarrow> carrier_coeff P\"\n    \\<comment> \\<open>iii\\<close> \"\\<And>P. P \\<in> carrier L \\<Longrightarrow> index_free P i\"\n    \\<comment> \\<open>iv\\<close>  \"\\<zero>\\<^bsub>L\\<^esub> = indexed_const \\<zero>\"\nbegin\n\ninterpretation L: field L\n  using \\<open>field L\\<close> .\n\ninterpretation UP: principal_domain \"poly_ring L\"\n  using L.univ_poly_is_principal[OF L.carrier_is_subfield] .\n\n\nabbreviation eval_pmod\n  where \"eval_pmod q \\<equiv> (\\<lambda>p. indexed_eval (L.pmod p q) i)\"\n\nabbreviation image_poly\n  where \"image_poly q \\<equiv> image_ring (eval_pmod q) (poly_ring L)\"\n\n\nlemma indexed_eval_is_weak_ring_morphism:\n  assumes \"q \\<in> carrier (poly_ring L)\" shows \"weak_ring_morphism (eval_pmod q) (PIdl\\<^bsub>poly_ring L\\<^esub> q) (poly_ring L)\"\nproof (rule weak_ring_morphismI)\n  show \"ideal (PIdl\\<^bsub>poly_ring L\\<^esub> q) (poly_ring L)\"\n    using UP.cgenideal_ideal[OF assms] .\nnext\n  fix a b assume in_carrier: \"a \\<in> carrier (poly_ring L)\" \"b \\<in> carrier (poly_ring L)\"\n  note ldiv_closed = in_carrier[THEN L.long_division_closed(2)[OF L.carrier_is_subfield _ assms]]\n\n  have \"(eval_pmod q) a = (eval_pmod q) b \\<longleftrightarrow> L.pmod a q = L.pmod b q\"\n    using inj_onD[OF indexed_eval_inj_on_carrier[OF hyps(2-4)] _ ldiv_closed] by fastforce\n  also have \" ... \\<longleftrightarrow> q pdivides\\<^bsub>L\\<^esub> (a \\<ominus>\\<^bsub>poly_ring L\\<^esub> b)\"\n    unfolding L.same_pmod_iff_pdivides[OF L.carrier_is_subfield in_carrier assms] ..\n  also have \" ... \\<longleftrightarrow> PIdl\\<^bsub>poly_ring L\\<^esub> (a \\<ominus>\\<^bsub>poly_ring L\\<^esub> b) \\<subseteq> PIdl\\<^bsub>poly_ring L\\<^esub> q\"\n    unfolding UP.to_contain_is_to_divide[OF assms UP.minus_closed[OF in_carrier]] pdivides_def ..\n  also have \" ... \\<longleftrightarrow> a \\<ominus>\\<^bsub>poly_ring L\\<^esub> b \\<in> PIdl\\<^bsub>poly_ring L\\<^esub> q\"\n    unfolding UP.cgenideal_eq_genideal[OF assms] UP.cgenideal_eq_genideal[OF UP.minus_closed[OF in_carrier]]\n              UP.Idl_subset_ideal'[OF UP.minus_closed[OF in_carrier] assms] ..\n  finally show \"(eval_pmod q) a = (eval_pmod q) b \\<longleftrightarrow> a \\<ominus>\\<^bsub>poly_ring L\\<^esub> b \\<in> PIdl\\<^bsub>poly_ring L\\<^esub> q\" .\nqed\n\nlemma eval_norm_eq_id:\n  assumes \"q \\<in> carrier (poly_ring L)\" and \"degree q > 0\" and \"a \\<in> carrier L\"\n  shows \"((eval_pmod q) \\<circ> (ring.poly_of_const L)) a = a\"\nproof (cases)\n  assume \"a = \\<zero>\\<^bsub>L\\<^esub>\" thus ?thesis\n    using L.long_division_zero(2)[OF L.carrier_is_subfield assms(1)] hyps(4)\n    unfolding ring.poly_of_const_def[OF L.ring_axioms] by auto\nnext\n  assume \"a \\<noteq> \\<zero>\\<^bsub>L\\<^esub>\" then have in_carrier: \"[ a ] \\<in> carrier (poly_ring L)\"\n    using assms(3) unfolding sym[OF univ_poly_carrier[of L \"carrier L\"]] polynomial_def by simp\n  from \\<open>a \\<noteq> \\<zero>\\<^bsub>L\\<^esub>\\<close> show ?thesis\n    using L.pmod_const(2)[OF L.carrier_is_subfield in_carrier assms(1)] assms(2)\n          indexed_padd_zero(2)[OF hyps(2)[OF assms(3)]]\n    unfolding ring.poly_of_const_def[OF L.ring_axioms] by auto\nqed\n\nlemma image_poly_iso_incl:\n  assumes \"q \\<in> carrier (poly_ring L)\" and \"degree q > 0\" shows \"id \\<in> ring_hom L (image_poly q)\"\nproof -\n  have \"((eval_pmod q) \\<circ> L.poly_of_const) \\<in> ring_hom L (image_poly q)\"\n    using ring_hom_trans[OF L.canonical_embedding_is_hom[OF L.carrier_is_subring]\n          UP.weak_ring_morphism_is_hom[OF indexed_eval_is_weak_ring_morphism[OF assms(1)]]]\n    by simp\n  thus ?thesis\n    using eval_norm_eq_id[OF assms(1-2)] L.ring_hom_restrict[of _ \"image_poly q\" id] by auto\nqed\n\nlemma image_poly_is_field:\n  assumes \"q \\<in> carrier (poly_ring L)\" and \"pirreducible\\<^bsub>L\\<^esub> (carrier L) q\" shows \"field (image_poly q)\"\n  using UP.image_ring_is_field[OF indexed_eval_is_weak_ring_morphism[OF assms(1)]] assms(2)\n  unfolding sym[OF L.rupture_is_field_iff_pirreducible[OF L.carrier_is_subfield assms(1)]] rupture_def\n  by simp\n\nlemma image_poly_index_free:\n  assumes \"q \\<in> carrier (poly_ring L)\" and \"P \\<in> carrier (image_poly q)\" and \"\\<not> index_free P j\" \"i \\<noteq> j\"\n  obtains Q where \"Q \\<in> carrier L\" and \"\\<not> index_free Q j\"\nproof -\n  from \\<open>P \\<in> carrier (image_poly q)\\<close> obtain p where p: \"p \\<in> carrier (poly_ring L)\" and P: \"P = (eval_pmod q) p\"\n    unfolding image_ring_carrier by blast\n  from \\<open>\\<not> index_free P j\\<close> have \"\\<not> list_all (\\<lambda>P. index_free P j) (L.pmod p q)\"\n    using indexed_eval_index_free[OF _ assms(4), of \"L.pmod p q\"] unfolding sym[OF P] by auto\n  then obtain Q where \"Q \\<in> set (L.pmod p q)\" and \"\\<not> index_free Q j\"\n    unfolding list_all_iff by auto\n  thus ?thesis\n    using L.long_division_closed(2)[OF L.carrier_is_subfield p assms(1)] that\n    unfolding sym[OF univ_poly_carrier[of L \"carrier L\"]] polynomial_def\n    by auto\nqed\n\nlemma eval_pmod_var:\n  assumes \"indexed_const \\<in> ring_hom R L\" and \"q \\<in> carrier (poly_ring L)\" and \"degree q > 1\"\n  shows \"(eval_pmod q) X\\<^bsub>L\\<^esub> = \\<X>\\<^bsub>i\\<^esub>\" and \"\\<X>\\<^bsub>i\\<^esub> \\<in> carrier (image_poly q)\"\nproof -\n  have \"X\\<^bsub>L\\<^esub> = [ indexed_const \\<one>, indexed_const \\<zero> ]\" and \"X\\<^bsub>L\\<^esub> \\<in> carrier (poly_ring L)\"\n    using ring_hom_one[OF assms(1)] hyps(4) L.var_closed(1) L.carrier_is_subring unfolding var_def by auto\n  thus \"(eval_pmod q) X\\<^bsub>L\\<^esub> = \\<X>\\<^bsub>i\\<^esub>\"\n    using L.pmod_const(2)[OF L.carrier_is_subfield _ assms(2), of \"X\\<^bsub>L\\<^esub>\"] assms(3)\n    by (auto simp add: indexed_pmult_def indexed_padd_def indexed_const_def indexed_var_def)\n  with \\<open>X\\<^bsub>L\\<^esub> \\<in> carrier (poly_ring L)\\<close> show \"\\<X>\\<^bsub>i\\<^esub> \\<in> carrier (image_poly q)\"\n    using image_iff unfolding image_ring_carrier by fastforce\nqed\n\nlemma image_poly_eval_indexed_var:\n  assumes \"indexed_const \\<in> ring_hom R L\"\n    and \"q \\<in> carrier (poly_ring L)\" and \"degree q > 1\" and \"pirreducible\\<^bsub>L\\<^esub> (carrier L) q\"\n  shows \"(ring.eval (image_poly q)) q \\<X>\\<^bsub>i\\<^esub> = \\<zero>\\<^bsub>image_poly q\\<^esub>\"\nproof -\n  let ?surj = \"L.rupture_surj (carrier L) q\"\n  let ?Rupt = \"Rupt\\<^bsub>L\\<^esub> (carrier L) q\"\n  let ?f = \"eval_pmod q\"\n\n  interpret UP: ring \"poly_ring L\"\n    using L.univ_poly_is_ring[OF L.carrier_is_subring] .\n  from \\<open>pirreducible\\<^bsub>L\\<^esub> (carrier L) q\\<close> interpret Rupt: field ?Rupt\n    using L.rupture_is_field_iff_pirreducible[OF L.carrier_is_subfield assms(2)] by simp\n\n  have weak_morphism: \"weak_ring_morphism ?f (PIdl\\<^bsub>poly_ring L\\<^esub> q) (poly_ring L)\"\n    using indexed_eval_is_weak_ring_morphism[OF assms(2)] .\n  then interpret I: ideal \"PIdl\\<^bsub>poly_ring L\\<^esub> q\" \"poly_ring L\"\n    using weak_ring_morphism.axioms(1) by auto\n  interpret Hom: ring_hom_ring ?Rupt \"image_poly q\" \"\\<lambda>x. the_elem (?f ` x)\"\n    using ring_hom_ring.intro[OF I.quotient_is_ring UP.image_ring_is_ring[OF weak_morphism]]\n          UP.weak_ring_morphism_is_iso[OF weak_morphism]\n    unfolding ring_iso_def symmetric[OF ring_hom_ring_axioms_def] rupture_def\n    by auto\n\n  have \"set q \\<subseteq> carrier L\" and lc: \"q \\<noteq> [] \\<Longrightarrow> lead_coeff q \\<in> carrier L - { \\<zero>\\<^bsub>L\\<^esub> }\"\n    using assms(2) unfolding sym[OF univ_poly_carrier] polynomial_def by auto\n\n  have map_surj: \"set (map (?surj \\<circ> L.poly_of_const) q) \\<subseteq> carrier ?Rupt\"\n  proof -\n    have \"L.poly_of_const a \\<in> carrier (poly_ring L)\" if \"a \\<in> carrier L\" for a\n      using that L.normalize_gives_polynomial[of \"[ a ]\"]\n      unfolding univ_poly_carrier ring.poly_of_const_def[OF L.ring_axioms] by simp\n    hence \"(?surj \\<circ> L.poly_of_const) a \\<in> carrier ?Rupt\" if \"a \\<in> carrier L\" for a\n      using ring_hom_memE(1)[OF L.rupture_surj_hom(1)[OF L.carrier_is_subring assms(2)]] that by simp\n    with \\<open>set q \\<subseteq> carrier L\\<close> show ?thesis\n      by (induct q) (auto)\n  qed\n\n  have \"?surj X\\<^bsub>L\\<^esub> \\<in> carrier ?Rupt\"\n    using ring_hom_memE(1)[OF L.rupture_surj_hom(1)[OF _ assms(2)] L.var_closed(1)] L.carrier_is_subring by simp\n  moreover have \"map (\\<lambda>x. the_elem (?f ` x)) (map (?surj \\<circ> L.poly_of_const) q) = q\"\n  proof -\n    define g where \"g = (?surj \\<circ> L.poly_of_const)\"\n    define f where \"f = (\\<lambda>x. the_elem (?f ` x))\"\n\n    have \"the_elem (?f ` ((?surj \\<circ> L.poly_of_const) a)) = ((eval_pmod q) \\<circ> L.poly_of_const) a\"\n      if \"a \\<in> carrier L\" for a\n      using that L.normalize_gives_polynomial[of \"[ a ]\"] UP.weak_ring_morphism_range[OF weak_morphism]\n      unfolding univ_poly_carrier ring.poly_of_const_def[OF L.ring_axioms] by auto\n    hence \"the_elem (?f ` ((?surj \\<circ> L.poly_of_const) a)) = a\" if \"a \\<in> carrier L\" for a\n      using eval_norm_eq_id[OF assms(2)] that assms(3) by simp\n    hence \"f (g a) = a\" if \"a \\<in> carrier L\" for a\n      using that unfolding f_def g_def by simp\n    with \\<open>set q \\<subseteq> carrier L\\<close> have \"map f (map g q) = q\"\n      by (induct q) (auto)\n    thus ?thesis\n      unfolding f_def g_def by simp\n  qed\n  moreover have \"(\\<lambda>x. the_elem (?f ` x)) (?surj X\\<^bsub>L\\<^esub>) = \\<X>\\<^bsub>i\\<^esub>\"\n    using UP.weak_ring_morphism_range[OF weak_morphism L.var_closed(1)[OF L.carrier_is_subring]]\n    unfolding eval_pmod_var(1)[OF assms(1-3)] by simp\n  ultimately have \"Hom.S.eval q \\<X>\\<^bsub>i\\<^esub> = (\\<lambda>x. the_elem (?f ` x)) (Rupt.eval (map (?surj \\<circ> L.poly_of_const) q) (?surj X\\<^bsub>L\\<^esub>))\"\n    using Hom.eval_hom'[OF _ map_surj] by auto\n  moreover have \"\\<zero>\\<^bsub>?Rupt\\<^esub> = ?surj \\<zero>\\<^bsub>poly_ring L\\<^esub>\"\n    unfolding rupture_def FactRing_def by (simp add: I.a_rcos_const)\n  hence \"the_elem (?f ` \\<zero>\\<^bsub>?Rupt\\<^esub>) = \\<zero>\\<^bsub>image_poly q\\<^esub>\"\n    using UP.weak_ring_morphism_range[OF weak_morphism UP.zero_closed]\n    unfolding image_ring_zero by simp \n  hence \"(\\<lambda>x. the_elem (?f ` x)) (Rupt.eval (map (?surj \\<circ> L.poly_of_const) q) (?surj X\\<^bsub>L\\<^esub>)) = \\<zero>\\<^bsub>image_poly q\\<^esub>\"\n    using L.polynomial_rupture[OF L.carrier_is_subring assms(2)] by simp\n  ultimately show ?thesis\n    by simp\nqed\n\nend (* of fixed L context. *)\n\nend (* of ring context. *)\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/Algebra/Indexed_Polynomials.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.90192067652954, "lm_q2_score": 0.824461932846258, "lm_q1q2_score": 0.7435992642455492}}
{"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\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 \"of_real (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) * of_real (cmod a) = a\"\n  by (metis assms cmod_cis mult.commute)\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 (opaque_lifting, 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 cis_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\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 cis_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": "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_Complex.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511579973931, "lm_q2_score": 0.8688267643505193, "lm_q1q2_score": 0.7435863923685201}}
{"text": "section  \\<open>Undirected Graphs\\<close>\ntheory Undirected_Graph\nimports\n  Main\n  \"HOL-Library.Extended_Nat\" \n  \"HOL-Eisbach.Eisbach\"\nbegin\n\n  (* TODO: Move *)\n  lemma split_sym_rel: \n    fixes G :: \"'a rel\"\n    assumes \"sym G\" \"irrefl G\"\n    obtains E where \"E\\<inter>E\\<inverse> = {}\" \"G = E \\<union> E\\<inverse>\"  \n  proof -\n    obtain R :: \"'a rel\" \n    where WO: \"well_order_on UNIV R\" using Zorn.well_order_on ..\n  \n    let ?E = \"G \\<inter> R\"\n    \n    from \\<open>irrefl G\\<close> have [simp, intro!]: \"(x,x)\\<notin>G\" for x by (auto simp: irrefl_def)\n    \n    have \"?E \\<inter> ?E\\<inverse> = {}\"\n      using WO unfolding well_order_on_def linear_order_on_def partial_order_on_def antisym_def\n      by fastforce \n    moreover  \n    have \"G = ?E \\<union> ?E\\<inverse>\" \n      apply (auto dest: symD[OF \\<open>sym G\\<close>])\n      using WO unfolding well_order_on_def linear_order_on_def total_on_def\n      by force\n    ultimately show ?thesis by (rule that)  \n  qed\n    \n  \n  (* TODO: Move *)\n  lemma map_eq_append_conv: \"map f xs = ys\\<^sub>1@ys\\<^sub>2 \\<longleftrightarrow> (\\<exists>xs\\<^sub>1 xs\\<^sub>2. xs = xs\\<^sub>1@xs\\<^sub>2 \\<and> map f xs\\<^sub>1 = ys\\<^sub>1 \\<and> map f xs\\<^sub>2 = ys\\<^sub>2)\"\n    apply rule\n    subgoal\n      apply (rule exI[where x=\"take (length ys\\<^sub>1) xs\"])\n      apply (rule exI[where x=\"drop (length ys\\<^sub>1) xs\"])\n      apply (drule sym)\n      by (auto simp: append_eq_conv_conj take_map drop_map)\n    subgoal by auto\n    done\n  \n  lemma sym_inv_eq[simp]: \"sym E \\<Longrightarrow> E\\<inverse> = E\" unfolding sym_def by auto \n\n\n  (* TODO: Move *)\n  lemma insert_inv[simp]: \"(insert e E)\\<inverse> = insert (prod.swap e) (E\\<inverse>)\"\n    by (cases e) auto\n    \n  (* TODO: Move *)\n  lemma inter_compl_eq_diff[simp]: \"x \\<inter> - s = x - s\"  \n    by auto\n\n  \n\n      \n  subsection \\<open>Nodes and Edges\\<close>  \n\n  typedef 'v ugraph = \"{ (V::'v set , E). E \\<subseteq> V\\<times>V \\<and> finite V \\<and> sym E \\<and> irrefl E }\"\n    unfolding sym_def irrefl_def by blast\n\n  setup_lifting type_definition_ugraph\n  \n  lift_definition nodes_internal :: \"'v ugraph \\<Rightarrow> 'v set\" is fst .\n  lift_definition edges_internal :: \"'v ugraph \\<Rightarrow> ('v\\<times>'v) set\" is snd .\n  lift_definition graph_internal :: \"'v set \\<Rightarrow> ('v\\<times>'v) set \\<Rightarrow> 'v ugraph\" \n    is \"\\<lambda>V E. if finite V \\<and> finite E then (V\\<union>fst`E\\<union>snd`E, (E\\<union>E\\<inverse>)-Id) else ({},{})\"\n    by (auto simp: sym_def irrefl_def; force)     \n  \n  definition nodes :: \"'v ugraph \\<Rightarrow> 'v set\" where \"nodes = nodes_internal\" \n  definition edges :: \"'v ugraph \\<Rightarrow> ('v\\<times>'v) set\" where \"edges = edges_internal\" \n  definition graph :: \"'v set \\<Rightarrow> ('v\\<times>'v) set \\<Rightarrow> 'v ugraph\" where \"graph = graph_internal\" \n  \n  lemma edges_subset: \"edges g \\<subseteq> nodes g \\<times> nodes g\"\n    unfolding edges_def nodes_def by transfer auto\n  \n  lemma nodes_finite[simp, intro!]: \"finite (nodes g)\"\n    unfolding edges_def nodes_def by transfer auto\n    \n  lemma edges_sym: \"sym (edges g)\"    \n    unfolding edges_def nodes_def by transfer auto\n\n  lemma edges_irrefl: \"irrefl (edges g)\"      \n    unfolding edges_def nodes_def by transfer auto\n\n  lemma nodes_graph: \"\\<lbrakk>finite V; finite E\\<rbrakk> \\<Longrightarrow> nodes (graph V E) = V\\<union>fst`E\\<union>snd`E\"    \n    unfolding edges_def nodes_def graph_def by transfer auto\n    \n  lemma edges_graph: \"\\<lbrakk>finite V; finite E\\<rbrakk> \\<Longrightarrow> edges (graph V E) = (E\\<union>E\\<inverse>)-Id\"    \n    unfolding edges_def nodes_def graph_def by transfer auto\n\n  lemmas graph_accs = nodes_graph edges_graph  \n    \n  lemma nodes_edges_graph_presentation:\n    \"\\<lbrakk>finite V; finite E\\<rbrakk> \\<Longrightarrow> nodes (graph V E) = V \\<union> fst`E \\<union> snd`E \\<and> edges (graph V E) = E\\<union>E\\<inverse> - Id\"\n    by (simp add: graph_accs)\n        \n  lemma graph_eq[simp]: \"graph (nodes g) (edges g) = g\"  \n    unfolding edges_def nodes_def graph_def\n    apply transfer\n    unfolding sym_def irrefl_def\n    apply (clarsimp split: prod.splits)\n    by (fastforce simp: finite_subset)\n\n  lemma edges_finite[simp, intro!]: \"finite (edges g)\"\n    using edges_subset finite_subset by fastforce\n    \n  lemma graph_cases[cases type]: \n    obtains V E where \"g = graph V E\" \"finite V\" \"finite E\" \"E\\<subseteq>V\\<times>V\" \"sym E\" \"irrefl E\"  \n  proof -\n    show ?thesis\n      apply (rule that[of \"nodes g\" \"edges g\"]) \n      using edges_subset edges_sym edges_irrefl[of g]\n      by auto\n  qed     \n  \n  lemma graph_eq_iff: \"g=g' \\<longleftrightarrow> nodes g = nodes g' \\<and> edges g = edges g'\"  \n    unfolding edges_def nodes_def graph_def by transfer auto\n\n    \n    \n  lemma edges_sym': \"(u,v)\\<in>edges g \\<Longrightarrow> (v,u)\\<in>edges g\" using edges_sym by (blast intro: symD)\n  lemma edges_irrefl'[simp,intro!]: \"(u,u)\\<notin>edges g\"\n    by (meson edges_irrefl irrefl_def)\n    \n  lemma edges_irreflI[simp, intro]: \"(u,v)\\<in>edges g \\<Longrightarrow> u\\<noteq>v\" by auto \n    \n  lemma edgesT_diff_sng_inv_eq[simp]: \"(edges T - {(x, y), (y, x)})\\<inverse> = edges T - {(x, y), (y, x)}\"\n    using edges_sym' by fast\n    \n  lemma nodesI[simp,intro]: assumes \"(u,v)\\<in>edges g\" shows \"u\\<in>nodes g\" \"v\\<in>nodes g\"\n    using assms edges_subset by auto\n    \n  lemma split_edges_sym: \"\\<exists>E. E\\<inter>E\\<inverse> = {} \\<and> edges g = E \\<union> E\\<inverse>\"  \n    using split_sym_rel[OF edges_sym edges_irrefl, of g] by metis\n  \n    \n  subsection \\<open>Connectedness Relation\\<close>  \n    \n  lemma rtrancl_edges_sym': \"(u,v)\\<in>(edges g)\\<^sup>* \\<Longrightarrow> (v,u)\\<in>(edges g)\\<^sup>*\"  \n    by (simp add: edges_sym symD sym_rtrancl)\n    \n  lemma trancl_edges_subset: \"(edges g)\\<^sup>+ \\<subseteq> nodes g \\<times> nodes g\"  \n    by (simp add: edges_subset trancl_subset_Sigma)\n        \n  lemma find_crossing_edge:\n    assumes \"(u,v)\\<in>E\\<^sup>*\" \"u\\<in>V\" \"v\\<notin>V\"\n    obtains u' v' where \"(u',v')\\<in>E\\<inter>V\\<times>-V\"\n    using assms apply (induction rule: converse_rtrancl_induct)\n    by auto\n  \n\n    \n  \n  subsection \\<open>Constructing Graphs\\<close>\n\n  (*\n  lift_definition make_graph :: \"'v set \\<Rightarrow> ('v\\<times>'v) set \\<Rightarrow> 'v ugraph\" is \n    \"\\<lambda>V E. if finite V \\<and> finite E then (V\\<union>fst`E\\<union>snd`E, (E\\<union>E\\<inverse>)-Id) else ({},{})\"\n    by (auto simp: sym_def irrefl_def; force)     \n    \n       \n  lift_definition graph_empty :: \"'v ugraph\" is \"({},{})\" by (auto simp: sym_def irrefl_def)\n  lift_definition ins_node :: \"'v \\<Rightarrow> 'v ugraph \\<Rightarrow> 'v ugraph\" is \"\\<lambda>v (V,E). (insert v V,E)\" by auto\n  lift_definition ins_edge :: \"'v\\<times>'v \\<Rightarrow> 'v ugraph \\<Rightarrow> 'v ugraph\" \n    is \"\\<lambda>(u,v) (V,E). if u\\<noteq>v then ({u,v}\\<union>V, {(u,v),(v,u)}\\<union>E) else (insert u V,E)\"\n    by (auto simp: sym_def irrefl_def split: if_splits)\n    \n  lift_definition graph_join :: \"'v ugraph \\<Rightarrow> 'v ugraph \\<Rightarrow> 'v ugraph\" is \"\\<lambda>(V,E) (V',E'). (V\\<union>V', E\\<union>E')\"\n    by (auto simp: sym_def irrefl_def)\n    \n  lift_definition restrict_nodes :: \"'v ugraph \\<Rightarrow> 'v set \\<Rightarrow> 'v ugraph\" is \"\\<lambda>(V,E) V'. (V\\<inter>V', E \\<inter> (V'\\<times>V'))\"  \n    by (auto simp: sym_def irrefl_def)\n  \n  lift_definition restrict_edges :: \"'v ugraph \\<Rightarrow> ('v\\<times>'v) set \\<Rightarrow> 'v ugraph\" is \"\\<lambda>(V,E) E'. (V, E \\<inter> (E'\\<union>E'\\<inverse>))\"\n    by (auto simp: sym_def irrefl_def)\n  *)\n    \n  definition \"graph_empty \\<equiv> graph {} {}\"\n  definition \"ins_node v g \\<equiv> graph (insert v (nodes g)) (edges g)\"\n  definition \"ins_edge e g \\<equiv> graph (nodes g) (insert e (edges g))\"\n  definition \"graph_join g\\<^sub>1 g\\<^sub>2 \\<equiv> graph (nodes g\\<^sub>1 \\<union> nodes g\\<^sub>2) (edges g\\<^sub>1 \\<union> edges g\\<^sub>2)\"\n  definition \"restrict_nodes g V \\<equiv> graph (nodes g \\<inter> V) (edges g \\<inter> V\\<times>V)\"\n  definition \"restrict_edges g E \\<equiv> graph (nodes g) (edges g \\<inter> (E\\<union>E\\<inverse>))\"\n  \n  \n  definition \"nodes_edges_consistent V E \\<equiv> finite V \\<and> irrefl E \\<and> sym E \\<and> E \\<subseteq> V\\<times>V\"\n  \n  \n\n  lemma graph_empty_accs[simp]:\n    \"nodes graph_empty = {}\"\n    \"edges graph_empty = {}\"\n    unfolding graph_empty_def by (auto)  \n    \n  \n\n  lemma edges_ins_edge_ss: \"edges g \\<subseteq> edges (ins_edge e g)\"  \n    by (auto simp: edges_ins_edge)\n    \n    \n  lemma nodes_join[simp]: \"nodes (graph_join g\\<^sub>1 g\\<^sub>2) = nodes g\\<^sub>1 \\<union> nodes g\\<^sub>2\"  \n    and edges_join[simp]: \"edges (graph_join g\\<^sub>1 g\\<^sub>2) = edges g\\<^sub>1 \\<union> edges g\\<^sub>2\"\n    unfolding graph_join_def\n    by (auto simp: graph_accs dest: edges_sym')\n\n  lemma nodes_restrict_nodes[simp]: \"nodes (restrict_nodes g V) = nodes g \\<inter> V\"  \n    and edges_restrict_nodes[simp]: \"edges (restrict_nodes g V) = edges g \\<inter> V\\<times>V\"\n    unfolding restrict_nodes_def\n    by (auto simp: graph_accs dest: edges_sym')\n    \n  lemma nodes_restrict_edges[simp]: \"nodes (restrict_edges g E) = nodes g\"\n    and edges_restrict_edges[simp]: \"edges (restrict_edges g E) = edges g \\<inter> (E\\<union>E\\<inverse>)\"\n    unfolding restrict_edges_def\n    by (auto simp: graph_accs dest: edges_sym')\n\n  lemma unrestricte_edges: \"edges (restrict_edges g E) \\<subseteq> edges g\" by auto\n  lemma unrestrictn_edges: \"edges (restrict_nodes g V) \\<subseteq> edges g\" by auto\n\n  lemma unrestrict_nodes: \"nodes (restrict_edges g E) \\<subseteq> nodes g\" by auto\n  \n  \n  \n  subsection \\<open>Paths\\<close>  \n      \n  fun path where\n    \"path g u [] v \\<longleftrightarrow> u=v\"  \n  | \"path g u (e#ps) w \\<longleftrightarrow> (\\<exists>v. e=(u,v) \\<and> e\\<in>edges g \\<and> path g v ps w)\"  \n\n  lemma path_emptyI[intro!]: \"path g u [] u\" by auto\n      \n  lemma path_append[simp]: \"path g u (p1@p2) w \\<longleftrightarrow> (\\<exists>v. path g u p1 v \\<and> path g v p2 w)\" \n    by (induction p1 arbitrary: u) auto\n\n  lemma path_transs1[trans]:\n    \"path g u p v \\<Longrightarrow> (v,w)\\<in>edges g \\<Longrightarrow> path g u (p@[(v,w)]) w\"  \n    \"(u,v)\\<in>edges g \\<Longrightarrow> path g v p w \\<Longrightarrow> path g u ((u,v)#p) w\"\n    \"path g u p1 v \\<Longrightarrow> path g v p2 w \\<Longrightarrow> path g u (p1@p2) w\"\n    by auto\n    \n  lemma path_graph_empty[simp]: \"path graph_empty u p v \\<longleftrightarrow> v=u \\<and> p=[]\" by (cases p) auto\n\n  abbreviation \"revp p \\<equiv> rev (map prod.swap p)\"\n  lemma revp_alt: \"revp p = rev (map (\\<lambda>(u,v). (v,u)) p)\" by auto\n    \n  lemma path_rev[simp]: \"path g u (revp p) v \\<longleftrightarrow> path g v p u\"  \n    by (induction p arbitrary: v) (auto dest: edges_sym')\n\n  lemma path_rev_sym[sym]: \"path g v p u \\<Longrightarrow> path g u (revp p) v\" by simp \n\n  lemma path_transs2[trans]: \n    \"path g u p v \\<Longrightarrow> (w,v)\\<in>edges g \\<Longrightarrow> path g u (p@[(v,w)]) w\"  \n    \"(v,u)\\<in>edges g \\<Longrightarrow> path g v p w \\<Longrightarrow> path g u ((u,v)#p) w\"\n    \"path g u p1 v \\<Longrightarrow> path g w p2 v \\<Longrightarrow> path g u (p1@revp p2) w\"\n    by (auto dest: edges_sym')\n  \n    \n  lemma path_edges: \"path g u p v \\<Longrightarrow> set p \\<subseteq> edges g\"\n    by (induction p arbitrary: u) auto\n\n  lemma path_graph_cong: \"path g\\<^sub>1 u p v \\<Longrightarrow> \\<lbrakk>set p \\<subseteq> edges g\\<^sub>1 \\<Longrightarrow> set p \\<subseteq> edges g\\<^sub>2\\<rbrakk> \\<Longrightarrow> path g\\<^sub>2 u p v\"\n    apply (frule path_edges; simp)\n    apply (induction p arbitrary: u) \n    apply auto    \n    done\n    \n                  \n  lemma path_endpoints: \n    assumes \"path g u p v\" \"p\\<noteq>[]\" shows \"u\\<in>nodes g\" \"v\\<in>nodes g\"\n    subgoal using assms by (cases p) (auto intro: nodesI)\n    subgoal using assms by (cases p rule: rev_cases) (auto intro: nodesI)\n    done\n\n  lemma path_mono: \"edges g \\<subseteq> edges g' \\<Longrightarrow> path g u p v \\<Longrightarrow> path g' u p v\"  \n    by (meson path_edges path_graph_cong subset_trans)\n\n    \n    \n  lemmas unrestricte_path = path_mono[OF unrestricte_edges]\n  lemmas unrestrictn_path = path_mono[OF unrestrictn_edges]\n\n  lemma unrestrict_path_edges: \"path (restrict_edges g E) u p v \\<Longrightarrow> path g u p v\"  \n    by (induction p arbitrary: u) auto\n    \n  lemma unrestrict_path_nodes: \"path (restrict_nodes g E) u p v \\<Longrightarrow> path g u p v\"  \n    by (induction p arbitrary: u) auto\n    \n        \n    \n  subsubsection \\<open>Paths and Connectedness\\<close>  \n    \n  lemma rtrancl_edges_iff_path: \"(u,v)\\<in>(edges g)\\<^sup>* \\<longleftrightarrow> (\\<exists>p. path g u p v)\"\n    apply rule\n    subgoal\n      apply (induction rule: converse_rtrancl_induct)\n      apply (auto dest: path_transs1)\n      done\n    apply clarify  \n    subgoal for p by (induction p arbitrary: u; force)\n    done  \n    \n  lemma rtrancl_edges_pathE: assumes \"(u,v)\\<in>(edges g)\\<^sup>*\" obtains p where \"path g u p v\"\n    using assms by (auto simp: rtrancl_edges_iff_path)\n\n  lemma path_rtrancl_edgesD: \"path g u p v \\<Longrightarrow> (u,v)\\<in>(edges g)\\<^sup>*\"\n    by (auto simp: rtrancl_edges_iff_path)  \n        \n    \n  subsubsection \\<open>Simple Paths\\<close>  \n    \n  definition \"uedge \\<equiv> \\<lambda>(a,b). {a,b}\"   \n    \n  definition \"simple p \\<equiv> distinct (map uedge p)\"  \n \n\n  lemma in_uedge_conv[simp]: \"x\\<in>uedge (u,v) \\<longleftrightarrow> x=u \\<or> x=v\"\n    by (auto simp: uedge_def)\n  \n  lemma uedge_eq_iff: \"uedge (a,b) = uedge (c,d) \\<longleftrightarrow> a=c \\<and> b=d \\<or> a=d \\<and> b=c\"\n    by (auto simp: uedge_def doubleton_eq_iff)\n    \n  lemma uedge_degen[simp]: \"uedge (a,a) = {a}\"  \n    by (auto simp: uedge_def)\n\n  lemma uedge_in_set_eq: \"uedge (u, v) \\<in> uedge ` S \\<longleftrightarrow> (u,v)\\<in>S \\<or> (v,u)\\<in>S\"  \n    by (auto simp: uedge_def doubleton_eq_iff)\n    \n    \n        \n  lemma simple_empty[simp]: \"simple []\"\n    by (auto simp: simple_def)\n  \n  lemma simple_cons[simp]: \"simple (e#p) \\<longleftrightarrow> uedge e \\<notin> uedge ` set p \\<and> simple p\"\n    by (auto simp: simple_def)\n  \n  \n\n  subsubsection \\<open>Splitting Paths\\<close>  \n  \n  lemma find_crossing_edge_on_path:\n    assumes \"path g u p v\" \"\\<not>P u\" \"P v\"\n    obtains u' v' where \"(u',v')\\<in>set p\" \"\\<not>P u'\" \"P v'\"\n    using assms by (induction p arbitrary: u) auto\n    \n  lemma find_crossing_edges_on_path:  \n    assumes P: \"path g u p v\" and \"P u\" \"P v\"\n    obtains \"\\<forall>(u,v)\\<in>set p. P u \\<and> P v\"\n          | u\\<^sub>1 v\\<^sub>1 v\\<^sub>2 u\\<^sub>2 p\\<^sub>1 p\\<^sub>2 p\\<^sub>3 where \"p=p\\<^sub>1@[(u\\<^sub>1,v\\<^sub>1)]@p\\<^sub>2@[(u\\<^sub>2,v\\<^sub>2)]@p\\<^sub>3\" \"P u\\<^sub>1\" \"\\<not>P v\\<^sub>1\" \"\\<not>P u\\<^sub>2\" \"P v\\<^sub>2\"\n  proof (cases \"\\<forall>(u,v)\\<in>set p. P u \\<and> P v\")\n    case True with that show ?thesis by blast\n  next\n    case False\n    with P \\<open>P u\\<close> have \"\\<exists>(u\\<^sub>1,v\\<^sub>1)\\<in>set p. P u\\<^sub>1 \\<and> \\<not>P v\\<^sub>1\"\n      apply clarsimp apply (induction p arbitrary: u) by auto\n    then obtain u\\<^sub>1 v\\<^sub>1 where \"(u\\<^sub>1,v\\<^sub>1)\\<in>set p\" and PRED1: \"P u\\<^sub>1\" \"\\<not>P v\\<^sub>1\" by blast\n    then obtain p\\<^sub>1 p\\<^sub>2\\<^sub>3 where [simp]: \"p=p\\<^sub>1@[(u\\<^sub>1,v\\<^sub>1)]@p\\<^sub>2\\<^sub>3\" by (auto simp: in_set_conv_decomp)\n    with P have \"path g v\\<^sub>1 p\\<^sub>2\\<^sub>3 v\" by auto\n    from find_crossing_edge_on_path[where P=P, OF this \\<open>\\<not>P v\\<^sub>1\\<close> \\<open>P v\\<close>] obtain u\\<^sub>2 v\\<^sub>2 \n      where \"(u\\<^sub>2,v\\<^sub>2)\\<in>set p\\<^sub>2\\<^sub>3\" \"\\<not>P u\\<^sub>2\" \"P v\\<^sub>2\" .\n    then show thesis using PRED1\n      by (auto simp: in_set_conv_decomp intro: that)\n  qed      \n    \n  lemma find_crossing_edge_rtrancl:\n    assumes \"(u,v)\\<in>(edges g)\\<^sup>*\" \"\\<not>P u\" \"P v\"\n    obtains u' v' where \"(u',v')\\<in>edges g\" \"\\<not>P u'\" \"P v'\"\n    using assms\n    by (metis converse_rtrancl_induct)\n    \n  \n  lemma path_change: \n    assumes \"u\\<in>S\" \"v\\<notin>S\" \"path g u p v\" \"simple p\"\n    obtains x y p1 p2 where \n      \"(x,y) \\<in> set p\" \"x \\<in> S\" \"y \\<notin> S\"\n      \"path (restrict_edges g (-{(x,y),(y,x)})) u p1 x\" \n      \"path (restrict_edges g (-{(x,y),(y,x)})) y p2 v\"\n  proof -\n    from find_crossing_edge_on_path[where P=\"\\<lambda>x. x\\<notin>S\"] assms obtain x y where \n      1: \"(x,y)\\<in>set p\" \"x\\<in>S\" \"y\\<notin>S\" by blast\n    then obtain p1 p2 where [simp]: \"p=p1@[(x,y)]@p2\" by (auto simp: in_set_conv_decomp)\n    \n    let ?g' = \"restrict_edges g (-{(x,y),(y,x)})\"\n    \n    from \\<open>path g u p v\\<close> have P1: \"path g u p1 x\" and P2: \"path g y p2 v\" by auto\n    from \\<open>simple p\\<close> have \"uedge (x,y)\\<notin>set (map uedge p1)\" \"uedge (x,y)\\<notin>set (map uedge p2)\" by auto\n    then have \"path ?g' u p1 x\" \"path ?g' y p2 v\"  \n      using path_graph_cong[OF P1, of ?g'] path_graph_cong[OF P2, of ?g']\n      by (auto simp: uedge_in_set_eq)\n    with 1 show ?thesis by (blast intro: that)\n  qed\n        \n  \n  \n\n\n  subsection \\<open>Cycles\\<close>      \n    \n  definition \"cycle_free g \\<equiv> \\<nexists>p u. p\\<noteq>[] \\<and> simple p \\<and> path g u p u\"\n\n  lemma cycle_free_alt_in_nodes: \n    \"cycle_free g \\<equiv> \\<nexists>p u. p\\<noteq>[] \\<and> u\\<in>nodes g \\<and> simple p \\<and> path g u p u\"\n    by (smt cycle_free_def path_endpoints(2))\n  \n  lemma cycle_freeI:\n    assumes \"\\<And>p u. \\<lbrakk> path g u p u; p\\<noteq>[]; simple p \\<rbrakk> \\<Longrightarrow> False\"\n    shows \"cycle_free g\"\n    using assms unfolding cycle_free_def by auto\n  \n  lemma cycle_freeD:\n    assumes \"cycle_free g\" \"path g u p u\" \"p\\<noteq>[]\" \"simple p\" \n    shows False\n    using assms unfolding cycle_free_def by auto\n\n    \n  lemma cycle_free_antimono: \"edges g \\<subseteq> edges g' \\<Longrightarrow> cycle_free g' \\<Longrightarrow> cycle_free g\"\n    unfolding cycle_free_def\n    by (auto dest: path_mono)\n\n  lemma cycle_free_empty[simp]: \"cycle_free graph_empty\" unfolding cycle_free_def by auto\n    \n  lemma cycle_free_no_edges: \"edges g = {} \\<Longrightarrow> cycle_free g\"\n    by (rule cycle_freeI) (auto simp: neq_Nil_conv)\n    \n  \n\n    with Cons.IH[of u' p''] Cons.prems show ?case by simp \n  qed    \n    \n                \n    \n  subsubsection \\<open>Characterization by Removing Edge\\<close>      \n  \n  \n  \n  lemma cycle_free_alt: \"cycle_free g \\<longleftrightarrow> (\\<forall>e\\<in>edges g. e\\<notin>(edges (restrict_edges g (-{e,prod.swap e})))\\<^sup>*)\"\n    apply (rule)\n    apply (clarsimp simp del: edges_restrict_edges)\n    subgoal premises prems for u v proof -\n      note edges_restrict_edges[simp del]\n      let ?rg = \"(restrict_edges g (- {(u,v), (v,u)}))\"\n      from \\<open>(u, v) \\<in> (edges ?rg)\\<^sup>*\\<close>\n      obtain p where P: \"path ?rg u p v\" and \"simple p\" \n        by (auto simp: rtrancl_edges_iff_path elim: simplify_pathE)\n      from P have \"path g u p v\" by (rule unrestricte_path) \n      also note \\<open>(u, v) \\<in> edges g\\<close> finally have \"path g u (p @ [(v, u)]) u\" .\n      moreover from path_edges[OF P] have \"uedge (u,v) \\<notin> set (map uedge p)\" \n        by (auto simp: uedge_eq_iff edges_restrict_edges)\n      with \\<open>simple p\\<close> have \"simple (p @ [(v, u)])\"\n        by (auto simp: uedge_eq_iff uedge_in_set_eq)\n      ultimately show ?thesis using \\<open>cycle_free g\\<close>  \n        unfolding cycle_free_def by blast\n    qed\n    apply (clarsimp simp: cycle_free_def)\n    subgoal premises prems for p u proof -\n      from \\<open>p\\<noteq>[]\\<close> \\<open>path g u p u\\<close> obtain v p' where \n        [simp]: \"p=(u,v)#p'\" and \"(u,v)\\<in>edges g\" \"path g v p' u\" \n        by (cases p) auto\n      from \\<open>simple p\\<close> have \"simple p'\" \"uedge (u,v) \\<notin> set (map uedge p')\" by auto  \n      hence \"(u,v)\\<notin>set p'\" \"(v,u)\\<notin>set p'\" by (auto simp: uedge_in_set_eq)\n      with \\<open>path g v p' u\\<close> have \"path (restrict_edges g (-{(u,v),(v,u)})) v p' u\" (is \"path ?rg _ _ _\")\n        by (erule_tac path_graph_cong) auto\n        \n      hence \"(u,v)\\<in>(edges ?rg)\\<^sup>*\"\n        by (meson path_rev rtrancl_edges_iff_path)  \n      with prems(1) \\<open>(u,v)\\<in>edges g\\<close> show False by auto\n    qed    \n    done\n    \n  lemma cycle_free_altI:\n    assumes \"\\<And>u v. \\<lbrakk> (u,v)\\<in>edges g; (u,v)\\<in>(edges g - {(u,v),(v,u)})\\<^sup>* \\<rbrakk> \\<Longrightarrow> False\"\n    shows \"cycle_free g\"\n    unfolding cycle_free_alt using assms by (force)\n    \n  lemma cycle_free_altD:  \n    assumes \"cycle_free g\"\n    assumes \"(u,v)\\<in>edges g\" \n    shows \"(u,v)\\<notin>(edges g - {(u,v),(v,u)})\\<^sup>*\"\n    using assms unfolding cycle_free_alt by (auto)\n    \n  \n  \n  lemma remove_redundant_edge:\n    assumes \"(u, v) \\<in> (edges g - {(u, v), (v, u)})\\<^sup>*\"  \n    shows \"(edges g - {(u, v), (v, u)})\\<^sup>* = (edges g)\\<^sup>*\" (is \"?E'\\<^sup>* = _\")\n  proof  \n    show \"?E'\\<^sup>* \\<subseteq> (edges g)\\<^sup>*\"\n      by (simp add: Diff_subset rtrancl_mono)\n  next\n    show \"(edges g)\\<^sup>* \\<subseteq> ?E'\\<^sup>*\"\n    proof clarify\n      fix a b assume \"(a,b)\\<in>(edges g)\\<^sup>*\" then \n      show \"(a,b)\\<in>?E'\\<^sup>*\"\n      proof induction\n        case base\n        then show ?case by simp\n      next\n        case (step b c)\n        then show ?case \n        proof (cases \"(b,c)\\<in>{(u,v),(v,u)}\")\n          case True\n\n          have SYME: \"sym (?E'\\<^sup>*)\"\n            apply (rule sym_rtrancl)\n            using edges_sym[of g] \n            by (auto simp: sym_def)\n          with step.IH assms have \n            IH': \"(b,a) \\<in> ?E'\\<^sup>*\" (*and A': \"(v,u) \\<in> (?E')\\<^sup>*\"*)\n            by (auto intro: symD)\n          \n          from True show ?thesis apply safe\n            subgoal using assms step.IH by simp\n            subgoal using assms IH' apply (rule_tac symD[OF SYME]) by simp\n            done\n          \n        next\n          case False\n          then show ?thesis\n            by (meson DiffI rtrancl.rtrancl_into_rtrancl step.IH step.hyps(2))\n        qed \n          \n      qed\n    qed\n  qed\n    \n    \n    \n    \n    \n  subsection \\<open>Connected Graphs\\<close>  \n    \n    \n  definition connected \n    where \"connected g \\<equiv> nodes g \\<times> nodes g \\<subseteq> (edges g)\\<^sup>*\"  \n\n  lemma connectedI[intro?]: \n    assumes \"\\<And>u v. \\<lbrakk>u\\<in>nodes g; v\\<in>nodes g\\<rbrakk> \\<Longrightarrow> (u,v)\\<in>(edges g)\\<^sup>*\"  \n    shows \"connected g\"\n    using assms unfolding connected_def by auto\n    \n  \n\n  subsection \\<open>Component Containing Node\\<close>\n  definition \"reachable_nodes g r \\<equiv> (edges g)\\<^sup>*``{r}\"\n  definition \"component_of g r \\<equiv> ins_node r (restrict_nodes g (reachable_nodes g r))\"\n  \n  lemma reachable_nodes_refl[simp, intro!]: \"r \\<in> reachable_nodes g r\" by (auto simp: reachable_nodes_def)\n  lemma reachable_nodes_step: \"edges g `` reachable_nodes g r \\<subseteq> reachable_nodes g r\"\n    by (auto simp: reachable_nodes_def)\n\n  lemma reachable_nodes_steps: \"(edges g)\\<^sup>* `` reachable_nodes g r \\<subseteq> reachable_nodes g r\"\n    by (auto simp: reachable_nodes_def)\n\n  lemma reachable_nodes_step':\n    assumes \"u \\<in> reachable_nodes g r\" \"(u, v) \\<in> edges g\" \n    shows \"v\\<in>reachable_nodes g r\" \"(u, v) \\<in> edges (component_of g r)\" \n  proof -\n    show \"v \\<in> reachable_nodes g r\"\n      by (meson ImageI assms(1) assms(2) reachable_nodes_step rev_subsetD)\n    then show \"(u, v) \\<in> edges (component_of g r)\"\n      by (simp add: assms(1) assms(2) component_of_def)\n  qed\n    \n  lemma reachable_nodes_steps':\n    assumes \"u \\<in> reachable_nodes g r\" \"(u, v) \\<in> (edges g)\\<^sup>*\" \n    shows \"v\\<in>reachable_nodes g r\" \"(u, v) \\<in> (edges (component_of g r))\\<^sup>*\" \n  proof -\n    show \"v\\<in>reachable_nodes g r\" using reachable_nodes_steps assms by fast\n    show \"(u, v) \\<in> (edges (component_of g r))\\<^sup>*\"\n      using assms(2,1)\n      apply (induction rule: converse_rtrancl_induct)\n      apply auto \n      by (smt converse_rtrancl_into_rtrancl reachable_nodes_step')\n  qed\n     \n  lemma reachable_not_node: \"r\\<notin>nodes g \\<Longrightarrow> reachable_nodes g r = {r}\"\n    by (force elim: converse_rtranclE simp: reachable_nodes_def intro: nodesI)\n     \n    \n  lemma nodes_of_component[simp]: \"nodes (component_of g r) = reachable_nodes g r\"\n    unfolding component_of_def apply (auto simp: reachable_nodes_def)\n    by (metis nodesI(2) rtranclE)\n  \n  lemma component_connected[simp, intro!]: \"connected (component_of g r)\"\n  proof (rule connectedI; simp)\n    fix u v\n    assume A: \"u \\<in> reachable_nodes g r\" \"v \\<in> reachable_nodes g r\"\n    hence \"(u,r)\\<in>(edges g)\\<^sup>*\" \"(r,v)\\<in>(edges g)\\<^sup>*\" by (auto simp: reachable_nodes_def dest: rtrancl_edges_sym')\n    hence \"(u,v)\\<in>(edges g)\\<^sup>*\" by (rule rtrancl_trans)\n    with A show \"(u, v) \\<in> (edges (component_of g r))\\<^sup>*\" by (rule_tac reachable_nodes_steps'(2))\n  qed  \n  \n  lemma component_edges_subset: \"edges (component_of g r) \\<subseteq> edges g\"  \n    by (auto simp: component_of_def)\n\n  lemma component_path: \"u\\<in>nodes (component_of g r) \\<Longrightarrow> \n    path (component_of g r) u p v \\<longleftrightarrow> path g u p v\"  \n    apply rule\n    subgoal by (erule path_mono[OF component_edges_subset])     \n    subgoal by (induction p arbitrary: u) (auto simp: reachable_nodes_step')\n    done  \n    \n  lemma component_cycle_free: \"cycle_free g \\<Longrightarrow> cycle_free (component_of g r)\"  \n    by (meson component_edges_subset cycle_free_antimono)\n    \n  lemma component_of_connected_graph: \"\\<lbrakk>connected g; r\\<in>nodes g\\<rbrakk> \\<Longrightarrow> component_of g r = g\"  \n    unfolding graph_eq_iff \n    apply auto\n    subgoal by (metis Image_singleton_iff nodesI(2) reachable_nodes_def rtranclE)\n    subgoal by (simp add: connectedD reachable_nodes_def)\n    subgoal by (simp add: component_of_def)\n    subgoal by (simp add: \\<open>\\<And>x. \\<lbrakk>connected g; r \\<in> nodes g; x \\<in> nodes g\\<rbrakk> \\<Longrightarrow> x \\<in> reachable_nodes g r\\<close> nodesI(1) reachable_nodes_step'(2))\n    done\n  \n  lemma component_of_not_node: \"r\\<notin>nodes g \\<Longrightarrow> component_of g r = graph {r} {}\"\n    by (clarsimp simp: graph_eq_iff component_of_def reachable_not_node graph_accs)\n  \n        \n  subsection \\<open>Trees\\<close>\n  \n  definition \"tree g \\<equiv> connected g \\<and> cycle_free g \"    \n\n  lemma tree_empty[simp]: \"tree graph_empty\" by (simp add: tree_def)\n  \n  lemma component_of_tree: \"tree T \\<Longrightarrow> tree (component_of T r)\"\n    unfolding tree_def using component_connected component_cycle_free by auto\n\n\n  subsubsection \\<open>Joining and Splitting Trees on Single Edge\\<close>\n        \n  lemma join_connected:\n    assumes CONN: \"connected g\\<^sub>1\" \"connected g\\<^sub>2\"\n    assumes IN_NODES: \"u\\<in>nodes g\\<^sub>1\" \"v\\<in>nodes g\\<^sub>2\"\n    shows \"connected (ins_edge (u,v) (graph_join g\\<^sub>1 g\\<^sub>2))\" (is \"connected ?g'\") \n    unfolding connected_def\n  proof clarify\n    fix a b\n    assume A: \"a\\<in>nodes ?g'\" \"b\\<in>nodes ?g'\"\n    \n    have ESS: \"(edges g\\<^sub>1)\\<^sup>* \\<subseteq> (edges ?g')\\<^sup>*\" \"(edges g\\<^sub>2)\\<^sup>* \\<subseteq> (edges ?g')\\<^sup>*\"\n      using edges_ins_edge_ss\n      by (force intro!: rtrancl_mono)+\n    \n    have UV: \"(u,v)\\<in>(edges ?g')\\<^sup>*\"\n      by (simp add: edges_ins_edge r_into_rtrancl)\n      \n    show \"(a,b)\\<in>(edges ?g')\\<^sup>*\"\n    proof -\n      {\n        assume \"a\\<in>nodes g\\<^sub>1\" \"b\\<in>nodes g\\<^sub>1\"\n        hence ?thesis using \\<open>connected g\\<^sub>1\\<close> ESS(1) unfolding connected_def by blast\n      } moreover {\n        assume \"a\\<in>nodes g\\<^sub>2\" \"b\\<in>nodes g\\<^sub>2\"\n        hence ?thesis using \\<open>connected g\\<^sub>2\\<close> ESS(2) unfolding connected_def by blast\n      } moreover {\n        assume \"a\\<in>nodes g\\<^sub>1\" \"b\\<in>nodes g\\<^sub>2\"\n        with connectedD[OF CONN(1)] connectedD[OF CONN(2)] ESS\n        have ?thesis by (meson UV IN_NODES contra_subsetD rtrancl_trans)\n      } moreover {\n        assume \"a\\<in>nodes g\\<^sub>2\" \"b\\<in>nodes g\\<^sub>1\"\n        with connectedD[OF CONN(1)] connectedD[OF CONN(2)] ESS\n        have ?thesis\n          by (meson UV IN_NODES contra_subsetD rtrancl_edges_sym' rtrancl_trans)\n      }\n      ultimately show ?thesis using A IN_NODES by auto\n    qed    \n  qed\n    \n    \n  lemma join_cycle_free:  \n    assumes CYCF: \"cycle_free g\\<^sub>1\" \"cycle_free g\\<^sub>2\"\n    assumes DJ: \"nodes g\\<^sub>1 \\<inter> nodes g\\<^sub>2 = {}\"\n    assumes IN_NODES: \"u\\<in>nodes g\\<^sub>1\" \"v\\<in>nodes g\\<^sub>2\"\n    shows \"cycle_free (ins_edge (u,v) (graph_join g\\<^sub>1 g\\<^sub>2))\" (is \"cycle_free ?g'\") \n  proof (rule cycle_freeI)\n    fix p a\n    assume P: \"path ?g' a p a\" \"p\\<noteq>[]\" \"simple p\"\n    from path_endpoints[OF this(1,2)] IN_NODES have A_NODE: \"a\\<in>nodes g\\<^sub>1 \\<union> nodes g\\<^sub>2\" by auto\n    thus False proof \n      assume N1: \"a\\<in>nodes g\\<^sub>1\"\n      have \"set p \\<subseteq> nodes g\\<^sub>1 \\<times> nodes g\\<^sub>1\"\n      proof (cases rule: find_crossing_edges_on_path[where P=\"\\<lambda>x. x\\<in>nodes g\\<^sub>1\", OF P(1) N1 N1])\n        case 1\n        then show ?thesis by auto\n      next\n        case (2 u\\<^sub>1 v\\<^sub>1 v\\<^sub>2 u\\<^sub>2 p\\<^sub>1 p\\<^sub>2 p\\<^sub>3)\n        then show ?thesis using \\<open>simple p\\<close> P\n          apply clarsimp\n          apply (drule path_edges)+\n          apply (cases \"u=v\"; clarsimp simp: edges_ins_edge uedge_in_set_eq)\n          apply (metis DJ IntI IN_NODES empty_iff)\n          by (metis DJ IntI empty_iff nodesI uedge_eq_iff)\n          \n      qed\n      hence \"set p \\<subseteq> edges g\\<^sub>1\" using DJ edges_subset path_edges[OF P(1)] IN_NODES\n        by (auto simp: edges_ins_edge split: if_splits; blast)\n      hence \"path g\\<^sub>1 a p a\" by (meson P(1) path_graph_cong)\n      thus False using cycle_freeD[OF CYCF(1)] P(2,3) by blast\n    next\n      assume N2: \"a\\<in>nodes g\\<^sub>2\"\n      have \"set p \\<subseteq> nodes g\\<^sub>2 \\<times> nodes g\\<^sub>2\"\n      proof (cases rule: find_crossing_edges_on_path[where P=\"\\<lambda>x. x\\<in>nodes g\\<^sub>2\", OF P(1) N2 N2])\n        case 1\n        then show ?thesis by auto\n      next\n        case (2 u\\<^sub>1 v\\<^sub>1 v\\<^sub>2 u\\<^sub>2 p\\<^sub>1 p\\<^sub>2 p\\<^sub>3)\n        then show ?thesis using \\<open>simple p\\<close> P\n          apply clarsimp\n          apply (drule path_edges)+\n          apply (cases \"u=v\"; clarsimp simp: edges_ins_edge uedge_in_set_eq)\n          apply (metis DJ IntI IN_NODES empty_iff)\n          by (metis DJ IntI empty_iff nodesI uedge_eq_iff)\n          \n      qed\n      hence \"set p \\<subseteq> edges g\\<^sub>2\" using DJ edges_subset path_edges[OF P(1)] IN_NODES\n        by (auto simp: edges_ins_edge split: if_splits; blast)\n      hence \"path g\\<^sub>2 a p a\" by (meson P(1) path_graph_cong)\n      thus False using cycle_freeD[OF CYCF(2)] P(2,3) by blast\n    qed\n  qed\n        \n  lemma join_trees:     \n    assumes TREE: \"tree g\\<^sub>1\" \"tree g\\<^sub>2\"\n    assumes DJ: \"nodes g\\<^sub>1 \\<inter> nodes g\\<^sub>2 = {}\"\n    assumes IN_NODES: \"u\\<in>nodes g\\<^sub>1\" \"v\\<in>nodes g\\<^sub>2\"\n    shows \"tree (ins_edge (u,v) (graph_join g\\<^sub>1 g\\<^sub>2))\"\n    using assms join_cycle_free join_connected unfolding tree_def by metis \n    \n    \n  lemma split_tree:\n    assumes \"tree T\" \"(x,y)\\<in>edges T\"\n    defines \"E' \\<equiv> (edges T - {(x,y),(y,x)})\"\n    obtains T1 T2 where \n      \"tree T1\" \"tree T2\" \n      \"nodes T1 \\<inter> nodes T2 = {}\" \"nodes T = nodes T1 \\<union> nodes T2\"\n      \"edges T1 \\<union> edges T2 = E'\"\n      \"nodes T1 = { u. (x,u)\\<in>E'\\<^sup>*}\" \"nodes T2 = { u. (y,u)\\<in>E'\\<^sup>*}\"\n      \"x\\<in>nodes T1\" \"y\\<in>nodes T2\"\n  proof -\n    (* TODO: Use component_of here! *)\n    define N1 where \"N1 = { u. (x,u)\\<in>E'\\<^sup>* }\"\n    define N2 where \"N2 = { u. (y,u)\\<in>E'\\<^sup>* }\"\n  \n    define T1 where \"T1 = restrict_nodes T N1\"\n    define T2 where \"T2 = restrict_nodes T N2\"\n    \n    have SYME: \"sym (E'\\<^sup>*)\"\n      apply (rule sym_rtrancl) \n      using edges_sym[of T] by (auto simp: sym_def E'_def)\n    \n\n    from assms have \"connected T\" \"cycle_free T\" unfolding tree_def by auto\n    from \\<open>cycle_free T\\<close> have \"cycle_free T1\" \"cycle_free T2\"\n      unfolding T1_def T2_def\n      using cycle_free_antimono unrestrictn_edges by blast+\n\n    from \\<open>(x,y) \\<in> edges T\\<close> have XYN: \"x\\<in>nodes T\" \"y\\<in>nodes T\" using edges_subset by auto\n    from XYN have [simp]: \"nodes T1 = N1\" \"nodes T2 = N2\" \n      unfolding T1_def T2_def N1_def N2_def unfolding E'_def apply auto\n      by (metis DiffD1 nodesI(2) rtrancl.simps)+\n    \n    have \"x\\<in>N1\" \"y\\<in>N2\" by (auto simp: N1_def N2_def)   \n    \n    have \"N1 \\<inter> N2 = {}\" \n    proof (safe;simp)\n      fix u\n      assume \"u\\<in>N1\" \"u\\<in>N2\"\n      hence \"(x,u)\\<in>E'\\<^sup>*\" \"(u,y)\\<in>E'\\<^sup>*\" by (auto simp: N1_def N2_def symD[OF SYME])\n      with cycle_free_altD[OF \\<open>cycle_free T\\<close> \\<open>(x,y)\\<in>edges T\\<close>] show False unfolding E'_def\n        by (meson rtrancl_trans)\n    qed\n  \n    \n    have N1C: \"E'``N1 \\<subseteq> N1\"\n      unfolding N1_def\n      apply clarsimp \n      by (simp add: rtrancl.rtrancl_into_rtrancl)\n    \n    have N2C: \"E'``N2 \\<subseteq> N2\"\n      unfolding N2_def\n      apply clarsimp \n      by (simp add: rtrancl.rtrancl_into_rtrancl)\n\n    have XE1: \"(x,u) \\<in> (edges T1)\\<^sup>*\" if \"u\\<in>N1\" for u\n    proof -\n      from that have \"(x,u)\\<in>E'\\<^sup>*\" by (auto simp: N1_def)\n      then show ?thesis using \\<open>x\\<in>N1\\<close> \n        unfolding T1_def\n      proof (induction rule: converse_rtrancl_induct)\n        case (step y z)\n        with N1C have \"z\\<in>N1\" by auto\n        with step.hyps(1) step.prems have \"(y,z)\\<in>Restr (edges T) N1\" unfolding E'_def by auto\n        with step.IH[OF \\<open>z\\<in>N1\\<close>] show ?case \n          by (metis converse_rtrancl_into_rtrancl edges_restrict_nodes)\n      qed auto\n    qed    \n    \n    have XE2: \"(y,u) \\<in> (edges T2)\\<^sup>*\" if \"u\\<in>N2\" for u\n    proof -\n      from that have \"(y,u)\\<in>E'\\<^sup>*\" by (auto simp: N2_def)\n      then show ?thesis using \\<open>y\\<in>N2\\<close> \n        unfolding T2_def\n      proof (induction rule: converse_rtrancl_induct)\n        case (step y z)\n        with N2C have \"z\\<in>N2\" by auto\n        with step.hyps(1) step.prems have \"(y,z)\\<in>Restr (edges T) N2\" unfolding E'_def by auto\n        with step.IH[OF \\<open>z\\<in>N2\\<close>] show ?case \n          by (metis converse_rtrancl_into_rtrancl edges_restrict_nodes)\n      qed auto\n    qed    \n    \n    \n    have \"connected T1\" \n      apply rule\n      apply simp\n      apply (drule XE1)+\n      by (meson rtrancl_edges_sym' rtrancl_trans)      \n    \n    have \"connected T2\" \n      apply rule\n      apply simp\n      apply (drule XE2)+\n      by (meson rtrancl_edges_sym' rtrancl_trans)      \n     \n    have \"u\\<in>N1 \\<union> N2\" if \"u\\<in>nodes T\" for u \n    proof -\n      from connectedD[OF \\<open>connected T\\<close> \\<open>x\\<in>nodes T\\<close> that ]\n      obtain p where P: \"path T x p u\" \"simple p\" \n        by (auto simp: rtrancl_edges_iff_path elim: simplify_pathE)\n      show ?thesis proof cases\n        assume \"(x,y)\\<notin>set p \\<and> (y,x)\\<notin>set p\"\n        with P(1) have \"path (restrict_edges T E') x p u\" \n          unfolding E'_def by (erule_tac path_graph_cong) auto\n        from path_rtrancl_edgesD[OF this]\n        show ?thesis unfolding N1_def E'_def by auto\n      next\n        assume \"\\<not>((x,y)\\<notin>set p \\<and> (y,x)\\<notin>set p)\"\n        with P obtain p' where \"uedge (x,y)\\<notin>set (map uedge p')\" \"path T y p' u \\<or> path T x p' u\"\n          apply (auto simp: in_set_conv_decomp)    \n          by (metis uedge_eq_iff)\n        hence \"path (restrict_edges T E') y p' u \\<or> path (restrict_edges T E') x p' u\"  \n          apply (clarsimp simp: uedge_in_set_eq E'_def)\n          by (smt ComplD DiffI Int_iff UnCI edges_restrict_edges insertE path_graph_cong subset_Compl_singleton subset_iff)\n        then show ?thesis unfolding N1_def N2_def E'_def by (auto dest: path_rtrancl_edgesD)\n      qed\n    qed\n    then have \"nodes T = N1 \\<union> N2\" \n      unfolding N1_def N2_def using XYN\n      apply (auto intro: nodesI simp: E'_def)\n      by (metis DiffD1 nodesI(2) rtrancl.cases)+ \n\n    have \"edges T1 \\<union> edges T2 \\<subseteq> E'\"\n      unfolding T1_def T2_def E'_def using \\<open>N1 \\<inter> N2 = {}\\<close> \\<open>x \\<in> N1\\<close> \\<open>y \\<in> N2\\<close> by auto  \n    also have \"edges T1 \\<union> edges T2 \\<supseteq> E'\"\n    proof -\n      note ED1 = nodesI[where g=T, unfolded \\<open>nodes T = N1\\<union>N2\\<close>]  \n      have \"E' \\<subseteq> edges T\" by (auto simp: E'_def)\n      thus \"edges T1 \\<union> edges T2 \\<supseteq> E'\"\n        unfolding T1_def T2_def\n        using ED1 N1C N2C by (auto; blast)\n    qed \n    finally have \"edges T1 \\<union> edges T2 = E'\" .  \n            \n    show ?thesis\n      apply (rule that[of T1 T2, unfolded tree_def]; (intro conjI)?; fact?)\n      apply simp_all\n      apply fact+\n      done\n  qed\n    \n    \n    \n    \n  subsection \\<open>Spanning Trees\\<close>    \n                                      \n  definition \"is_spanning_tree G T \\<equiv> tree T \\<and> nodes T = nodes G \\<and> edges T \\<subseteq> edges G\"    \n    \n  (* TODO: Move *)\n  lemma connected_singleton[simp]: \"connected (ins_node u graph_empty)\"\n    unfolding connected_def by auto\n    \n  lemma path_singleton[simp]: \"path (ins_node u graph_empty) v p w \\<longleftrightarrow> v=w \\<and> p=[]\"  \n    by (cases p) auto\n  \n  lemma tree_singleton[simp]: \"tree (ins_node u graph_empty)\"\n    by (simp add: cycle_free_no_edges tree_def)\n  \n  (* TODO: Move *)\n  lemma tree_add_edge_in_out:\n    assumes \"tree T\"\n    assumes \"u\\<in>nodes T\" \"v\\<notin>nodes T\"\n    shows \"tree (ins_edge (u,v) T)\"\n  proof -\n    from assms have [simp]: \"u\\<noteq>v\" by auto\n    have \"ins_edge (u,v) T = ins_edge (u,v) (graph_join T (ins_node v graph_empty))\"\n      by (auto simp: graph_eq_iff)\n    also have \"tree \\<dots>\"\n      apply (rule join_trees)\n      using assms\n      by auto\n    finally show ?thesis .\n  qed\n    \n  text \\<open>Remove edges on cycles until the graph is cycle free\\<close>\n  lemma ex_spanning_tree: \n    \"connected g \\<Longrightarrow> \\<exists>t. is_spanning_tree g t\"\n    using edges_finite[of g]\n  proof (induction \"edges g\" arbitrary: g rule: finite_psubset_induct)\n    case psubset\n    show ?case proof (cases \"cycle_free g\")\n      case True with \\<open>connected g\\<close> show ?thesis by (auto simp: is_spanning_tree_def tree_def)\n    next\n      case False \n      then obtain u v where EDGE: \"(u,v)\\<in>edges g\" and RED: \"(u,v)\\<in>(edges g - {(u,v),(v,u)})\\<^sup>*\" \n        using cycle_free_altI by metis\n      from \\<open>connected g\\<close> have \"connected (restrict_edges g (- {(u,v),(v,u)}))\" (is \"connected ?g'\")\n        unfolding connected_def\n        by (auto simp: remove_redundant_edge[OF RED])\n      moreover have \"edges ?g' \\<subset> edges g\" using EDGE by auto\n      ultimately obtain t where \"is_spanning_tree ?g' t\" using psubset.hyps(2)[of ?g'] by blast\n      hence \"is_spanning_tree g t\" by (auto simp: is_spanning_tree_def)\n      thus ?thesis ..\n    qed\n  qed\n    \n  \n  section \\<open>Weighted Undirected Graphs\\<close>\n  \n  definition weight :: \"('v set \\<Rightarrow> nat) \\<Rightarrow> 'v ugraph \\<Rightarrow> nat\" \n    where \"weight w g \\<equiv> (\\<Sum>e\\<in>edges g. w (uedge e)) div 2\"\n\n    \n  lemma weight_alt: \"weight w g = (\\<Sum>e\\<in>uedge`edges g. w e)\"  \n  proof -\n    from split_edges_sym[of g] obtain E where \"edges g = E \\<union> E\\<inverse>\" and \"E\\<inter>E\\<inverse>={}\" by auto\n    hence [simp, intro!]: \"finite E\" by (metis edges_finite finite_Un) \n    hence [simp, intro!]: \"finite (E\\<inverse>)\" by blast\n  \n    have [simp]: \"(\\<Sum>e\\<in>E\\<inverse>. w (uedge e)) = (\\<Sum>e\\<in>E. w (uedge e))\"\n      apply (rule sum.reindex_cong[where l=prod.swap and A=\"E\\<inverse>\" and B=\"E\"])\n      apply (auto simp: uedge_def insert_commute)\n      done\n\n    have [simp]: \"inj_on uedge E\" using \\<open>E\\<inter>E\\<inverse>=_\\<close>\n      by (auto simp: uedge_def inj_on_def doubleton_eq_iff)\n          \n    have \"weight w g = (\\<Sum>e\\<in>E. w (uedge e))\"\n      unfolding weight_def \\<open>edges g = _\\<close> using \\<open>E\\<inter>E\\<inverse>={}\\<close>\n      by (auto simp: sum.union_disjoint)\n    also have \"\\<dots> = (\\<Sum>e\\<in>uedge`E. w e)\" \n      using sum.reindex[of uedge E w]\n      by auto \n    also have \"uedge`E = uedge`(edges g)\"  \n      unfolding \\<open>edges g = _\\<close> uedge_def using \\<open>E\\<inter>E\\<inverse>={}\\<close>\n      by auto\n    finally show ?thesis .\n  qed \n  \n  lemma weight_empty[simp]: \"weight w graph_empty = 0\" unfolding weight_def by auto\n    \n  lemma weight_ins_edge[simp]: \"\\<lbrakk>u\\<noteq>v; (u,v)\\<notin>edges g\\<rbrakk> \\<Longrightarrow> weight w (ins_edge (u,v) g) = w {u,v} + weight w g\"\n    unfolding weight_def\n    apply clarsimp\n    apply (subst sum.insert)\n    by (auto dest: edges_sym' simp: uedge_def insert_commute)\n\n  lemma uedge_img_disj_iff[simp]: \"uedge`edges g\\<^sub>1 \\<inter> uedge`edges g\\<^sub>2 = {} \\<longleftrightarrow> edges g\\<^sub>1 \\<inter> edges g\\<^sub>2 = {}\"\n    by (auto simp: uedge_eq_iff dest: edges_sym')+  \n    \n  lemma weight_join[simp]: \"edges g\\<^sub>1 \\<inter> edges g\\<^sub>2 = {} \\<Longrightarrow> weight w (graph_join g\\<^sub>1 g\\<^sub>2) = weight w g\\<^sub>1 + weight w g\\<^sub>2\"  \n    unfolding weight_alt by (auto simp: sum.union_disjoint image_Un)\n\n  lemma weight_cong: \"edges g\\<^sub>1 = edges g\\<^sub>2 \\<Longrightarrow> weight w g\\<^sub>1 = weight w g\\<^sub>2\"  \n    by (auto simp: weight_def)\n\n  lemma weight_mono: \"edges g \\<subseteq> edges g' \\<Longrightarrow> weight w g \\<le> weight w g'\"\n    unfolding weight_alt apply (rule sum_mono2) by auto\n    \n  lemma weight_ge_edge:\n    assumes \"(x,y)\\<in>edges T\"\n    shows \"weight w T \\<ge> w {x,y}\"\n    using assms unfolding weight_alt\n    by (auto simp: uedge_def intro: member_le_sum)\n    \n    \n            \n  lemma weight_del_edge[simp]: \n    assumes \"(x,y)\\<in>edges T\"  \n    shows \"weight w (restrict_edges T (- {(x, y), (y, x)})) = weight w T - w {x,y}\"\n  proof -\n    define E where \"E = uedge ` edges T - {{x,y}}\"\n    have [simp]: \"(uedge ` (edges T - {(x, y), (y, x)})) = E\"  \n      by (safe; simp add: E_def uedge_def doubleton_eq_iff; blast)\n      \n    from assms have [simp]: \"uedge ` edges T = insert {x,y} E\"\n      unfolding E_def by force\n\n    have [simp]: \"{x,y}\\<notin>E\" unfolding E_def by blast        \n  \n    then show ?thesis\n      unfolding weight_alt\n      apply simp\n      by (metis E_def \\<open>uedge ` edges T = insert {x, y} E\\<close> insertI1 sum_diff1_nat)\n  qed    \n    \n          \n  subsection \\<open>Minimum Spanning Trees\\<close>\n  \n  definition \"is_MST w g t \\<equiv> is_spanning_tree g t \n    \\<and> (\\<forall>t'. is_spanning_tree g t' \\<longrightarrow> weight w t \\<le> weight w t')\"  \n  \n  lemma exists_MST: \"connected g \\<Longrightarrow> \\<exists>t. is_MST w g t\"\n    using ex_has_least_nat[of \"is_spanning_tree g\"] ex_spanning_tree unfolding is_MST_def by blast\n\n   \n  \n  \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/Prim/Undirected_Graph.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267660487573, "lm_q2_score": 0.855851143290548, "lm_q1q2_score": 0.7435863810442584}}
{"text": "theory Poincare_Circles\n  imports Poincare_Distance\nbegin\n(* -------------------------------------------------------------------------- *)\nsection\\<open>H-circles in the Poincar\\'e model\\<close>\n(* -------------------------------------------------------------------------- *)\n\ntext\\<open>Circles consist of points that are at the same distance from the center.\\<close>\ndefinition poincare_circle :: \"complex_homo \\<Rightarrow> real \\<Rightarrow> complex_homo set\" where\n  \"poincare_circle z r = {z'. z' \\<in> unit_disc \\<and> poincare_distance z z' = r}\"\n\ntext\\<open>Each h-circle in the Poincar\\'e model is represented by an Euclidean circle in the model ---\nthe center and radius of that euclidean circle are determined by the following formulas.\\<close>\ndefinition poincare_circle_euclidean :: \"complex_homo \\<Rightarrow> real \\<Rightarrow> euclidean_circle\" where\n  \"poincare_circle_euclidean z r =\n      (let R = (cosh r - 1) / 2;\n           z' = to_complex z;\n           cz = 1 - (cmod z')\\<^sup>2;\n           k = cz * R + 1\n        in (z' / k, cz * sqrt(R * (R + 1)) / k))\"\n\ntext\\<open>That Euclidean circle has a positive radius and is always fully within the disc.\\<close>\nlemma poincare_circle_in_disc:\n  assumes \"r > 0\" and \"z \\<in> unit_disc\" and \"(ze, re) = poincare_circle_euclidean z r\"\n  shows \"cmod ze < 1\" \"re > 0\" \"\\<forall> x \\<in> circle ze re. cmod x < 1\"\nproof-\n  let ?R = \"(cosh r - 1) / 2\"\n  let ?z' = \"to_complex z\"\n  let ?cz = \"1 - (cmod ?z')\\<^sup>2\"\n  let ?k = \"?cz * ?R + 1\"\n  let ?ze = \"?z' / ?k\"\n  let ?re = \"?cz * sqrt(?R * (?R + 1)) / ?k\"\n\n  from \\<open>z \\<in> unit_disc\\<close>\n  obtain z' where z': \"z = of_complex z'\"\n    using inf_or_of_complex[of z]\n    by auto\n\n  hence \"z' = ?z'\"\n    by simp\n\n  obtain cz where cz: \"cz = (1 - (cmod z')\\<^sup>2)\"\n    by auto\n\n  have \"cz > 0\" \"cz \\<le> 1\"\n    using \\<open>z \\<in> unit_disc\\<close> z' cz\n    using unit_disc_cmod_square_lt_1\n    by fastforce+\n\n  obtain R where R: \"R = ?R\"\n    by blast\n\n  have \"R > 0\"\n    using cosh_gt_1[of r] \\<open>r > 0\\<close>\n    by (subst R) simp\n\n  obtain k where k: \"k = cz * R + 1\"\n    by auto\n\n  have \"k > 1\"\n    using k \\<open>R > 0\\<close> \\<open>cz > 0\\<close>\n    by simp\n\n  hence \"cmod k = k\"\n    by simp\n\n  let ?RR = \"cz * sqrt(R * (R + 1)) / k\"\n\n  have \"cmod z' + cz * sqrt(R * (R + 1)) < k\"\n  proof-\n    have \"((R+1)-R)\\<^sup>2 > 0\"\n      by simp\n    hence \"(R+1)\\<^sup>2 - 2*R*(R+1) + R\\<^sup>2 > 0\"\n      unfolding power2_diff\n      by (simp add: field_simps)\n    hence \"(R+1)\\<^sup>2 + 2*R*(R+1) + R\\<^sup>2 - 4*R*(R+1) > 0\"\n      by simp\n    hence \"(2*R+1)\\<^sup>2 / 4 > R*(R+1)\"\n      using power2_sum[of \"R+1\" R]\n      by (simp add: field_simps)\n    hence \"sqrt(R*(R+1)) < (2*R+1) / 2\"\n      using \\<open>R > 0\\<close>\n      by (smt arith_geo_mean_sqrt power_divide real_sqrt_four real_sqrt_pow2 zero_le_mult_iff)\n    hence \"sqrt(R*(R+1)) - R < 1/2\"\n      by (simp add: field_simps)\n    hence \"(1 + (cmod z')) * (sqrt(R*(R+1)) - R) < (1 + (cmod z')) *  (1 / 2)\"\n      by (subst mult_strict_left_mono, simp, smt norm_not_less_zero, simp)\n    also have \"... < 1\"\n      using \\<open>z \\<in> unit_disc\\<close> z'\n      by auto\n    finally have \"(1 - cmod z') * ((1 + cmod z') * (sqrt(R*(R+1)) - R)) < (1 - cmod z') * 1\"\n      using \\<open>z \\<in> unit_disc\\<close> z'\n      by (subst mult_strict_left_mono, simp_all)\n    hence \"cz * (sqrt (R*(R+1)) - R) < 1 - cmod z'\"\n      using square_diff_square_factored[of 1 \"cmod z'\"]\n      by (subst cz, subst (asm) mult.assoc[symmetric], simp add: power2_eq_square field_simps)\n    hence \"cmod z' + cz * sqrt(R*(R+1)) < 1 + R * cz\"\n      by (simp add: field_simps)\n    thus ?thesis\n      using k\n      by (simp add: field_simps)\n  qed\n  hence \"cmod z' / k + cz * sqrt(R * (R + 1)) / k < 1\"\n    using \\<open>k > 1\\<close>\n    unfolding add_divide_distrib[symmetric]\n    by simp\n  hence \"cmod (z' / k) + cz * sqrt(R * (R + 1)) / k < 1\"\n    using \\<open>k > 1\\<close>\n    by simp\n  hence \"cmod ?ze + ?re < 1\"\n    using k cz \\<open>R = ?R\\<close> z'\n    by simp\n\n  moreover\n\n  have \"cz * sqrt(R * (R + 1)) / k > 0\"\n    using \\<open>cz > 0\\<close> \\<open>R > 0\\<close> \\<open>k > 1\\<close>\n    by auto\n  hence \"?re > 0\"\n    using k cz \\<open>R = ?R\\<close> z'\n    by simp\n\n  moreover\n\n  have \"cmod ?ze < 1\"\n    using \\<open>cmod ?ze + ?re < 1\\<close> \\<open>?re > 0\\<close>\n    by simp\n\n  moreover\n\n  have \"ze = ?ze\" \"re = ?re\"\n    using \\<open>(ze, re) = poincare_circle_euclidean z r\\<close>\n    unfolding poincare_circle_euclidean_def Let_def\n    by simp_all\n\n  moreover\n\n  have \"\\<forall> x \\<in> circle ze re. cmod x \\<le> cmod ze + re\"\n    using norm_triangle_ineq2[of _ ze]\n    unfolding circle_def\n    by (smt mem_Collect_eq)\n\n  ultimately\n\n  show \"cmod ze < 1\" \"re > 0\" \"\\<forall> x \\<in> circle ze re. cmod x < 1\"\n    by auto\nqed\n\ntext\\<open>The connection between the points on the h-circle and its corresponding Euclidean circle.\\<close>\nlemma poincare_circle_is_euclidean_circle:\n  assumes \"z \\<in> unit_disc\" and \"r > 0\"\n  shows  \"let (Ze, Re) = poincare_circle_euclidean z r\n           in of_complex ` (circle Ze Re) = poincare_circle z r\"\nproof-\n  {\n    fix x\n    let ?z = \"to_complex z\"\n\n    from assms obtain z' where z': \"z = of_complex z'\" \"cmod z' < 1\"\n      using inf_or_of_complex[of z]\n      by auto\n\n    have *: \"\\<And> x. cmod x < 1 \\<Longrightarrow> 1 - (cmod x)\\<^sup>2 > 0\"\n      by (metis less_iff_diff_less_0 minus_diff_eq mult.left_neutral neg_less_0_iff_less norm_mult_less norm_power power2_eq_square)\n\n    let ?R = \"(cosh r - 1) / 2\"\n    obtain R where R: \"R = ?R\"\n      by blast\n\n    let ?cx = \"1 - (cmod x)\\<^sup>2\" and ?cz = \"1 - (cmod z')\\<^sup>2\"  and ?czx = \"(cmod (z' - x))\\<^sup>2\"\n\n    let ?k = \"1 + R * ?cz\"\n    obtain k where k: \"k = ?k\"\n      by blast\n    have \"R > 0\"\n      using R cosh_gt_1[OF \\<open>r > 0\\<close>]\n      by simp\n\n    hence \"k > 1\"\n      using assms z' k *[of z']\n      by auto\n    hence **: \"cor k \\<noteq> 0\"\n      by (smt of_real_eq_0_iff)\n\n\n    have \"of_complex x \\<in> poincare_circle z r \\<longleftrightarrow> cmod x < 1 \\<and> poincare_distance z (of_complex x) = r\"\n      unfolding poincare_circle_def\n      by auto\n    also have \"... \\<longleftrightarrow> cmod x < 1 \\<and> poincare_distance_formula' ?z x = cosh r\"\n      using poincare_distance_formula[of z \"of_complex x\"] cosh_dist[of z \"of_complex x\"]\n      unfolding poincare_distance_formula_def\n      using assms\n      using arcosh_cosh_real\n      by auto\n    also have \"... \\<longleftrightarrow> cmod x < 1 \\<and> ?czx / (?cz * ?cx) = ?R\"\n      using z'\n      by (simp add: field_simps)\n    also have \"... \\<longleftrightarrow> cmod x < 1 \\<and> ?czx = ?R * ?cx * ?cz\"\n      using assms z' *[of z'] *[of x]\n      using nonzero_divide_eq_eq[of \"(1 - (cmod x)\\<^sup>2) * (1 - (cmod z')\\<^sup>2)\" \"(cmod (z' - x))\\<^sup>2\" ?R]\n      by (auto, simp add: field_simps)\n    also have \"... \\<longleftrightarrow> cmod x < 1 \\<and> (z' - x) * (cnj z' - cnj x) = R * ?cz * (1 - x * cnj x)\" (is \"_ \\<longleftrightarrow> _ \\<and> ?l = ?r\")\n    proof-\n      let ?l = \"(z' - x) * (cnj z' - cnj x)\" and ?r = \"R * (1 - Re (z' * cnj z')) * (1 - x * cnj x)\"\n      have \"is_real ?l\"\n        using eq_cnj_iff_real[of \"?l\"]\n        by simp\n      moreover\n      have \"is_real ?r\"\n        using eq_cnj_iff_real[of \"1 - x * cnj x\"]\n        using Im_complex_of_real[of \"R * (1 - Re (z' * cnj z'))\"]\n        by simp\n      ultimately\n      show ?thesis\n        apply (subst R[symmetric])\n        apply (subst cmod_square)+\n        apply (subst complex_eq_if_Re_eq, simp_all add: field_simps)\n        done\n    qed\n    also have \"... \\<longleftrightarrow> cmod x < 1 \\<and> z' * cnj z' - x * cnj z' - cnj x * z' + x * cnj x = R * ?cz - R * ?cz * x * cnj x\"\n      unfolding right_diff_distrib left_diff_distrib\n      by (simp add: field_simps)\n    also have \"... \\<longleftrightarrow> cmod x < 1 \\<and> k * (x * cnj x) - x * cnj z' - cnj x * z' + z' * cnj z' = R * ?cz\" (is \"_ \\<longleftrightarrow> _ \\<and> ?lhs = ?rhs\")\n      by (subst k) (auto simp add: field_simps)\n    also have \"... \\<longleftrightarrow> cmod x < 1 \\<and> (k * x * cnj x - x * cnj z' - cnj x * z' + z' * cnj z') / k = (R * ?cz) / k\"\n      using **\n      by (auto simp add: Groups.mult_ac(1))\n    also have \"... \\<longleftrightarrow> cmod x < 1 \\<and> x * cnj x - x * cnj z' / k - cnj x * z' / k + z' * cnj z' / k = (R * ?cz) / k\"\n      using **\n      unfolding add_divide_distrib diff_divide_distrib\n      by auto\n    also have \"... \\<longleftrightarrow> cmod x < 1 \\<and> (x - z'/k) * cnj(x - z'/k) = (R * ?cz) / k + (z' / k) * cnj(z' / k) - z' * cnj z' / k\"\n      by (auto simp add: field_simps diff_divide_distrib)\n    also have \"... \\<longleftrightarrow> cmod x < 1 \\<and> (cmod (x - z'/k))\\<^sup>2 = (R * ?cz) / k + (cmod z')\\<^sup>2 / k\\<^sup>2 - (cmod z')\\<^sup>2 / k\"\n      apply (subst complex_mult_cnj_cmod)+\n      apply (subst complex_eq_if_Re_eq)\n      apply (simp_all add: power_divide)\n      done\n    also have \"... \\<longleftrightarrow> cmod x < 1 \\<and> (cmod (x - z'/k))\\<^sup>2 = (R * ?cz * k + (cmod z')\\<^sup>2 - (cmod z')\\<^sup>2 * k) / k\\<^sup>2\"\n      using **\n      unfolding add_divide_distrib diff_divide_distrib\n      by (simp add: power2_eq_square)\n    also have \"... \\<longleftrightarrow> cmod x < 1 \\<and> (cmod (x - z'/k))\\<^sup>2 = ?cz\\<^sup>2 * R * (R + 1) / k\\<^sup>2\" (is \"_ \\<longleftrightarrow> _ \\<and> ?a\\<^sup>2 = ?b\")\n    proof-\n      have *: \"R * (1 - (cmod z')\\<^sup>2) * k + (cmod z')\\<^sup>2 - (cmod z')\\<^sup>2 * k = (1 - (cmod z')\\<^sup>2)\\<^sup>2 * R * (R + 1)\"\n        by (subst k)+ (simp add: field_simps power2_diff)\n      thus ?thesis\n        by (subst *, simp)\n    qed\n    also have \"... \\<longleftrightarrow> cmod x < 1 \\<and> cmod (x - z'/k) = ?cz * sqrt (R * (R + 1)) / k\"\n      using \\<open>R > 0\\<close> *[of z'] ** \\<open>k > 1\\<close> \\<open>z \\<in> unit_disc\\<close> z'\n      using real_sqrt_unique[of ?a ?b, symmetric]\n      by (auto simp add: real_sqrt_divide real_sqrt_mult power_divide power_mult_distrib)\n    finally\n    have \"of_complex x \\<in> poincare_circle z r \\<longleftrightarrow> cmod x < 1 \\<and> x \\<in> circle (z'/k) (?cz * sqrt(R * (R+1)) / k)\"\n      unfolding circle_def z' k R\n      by simp\n    hence \"of_complex x \\<in> poincare_circle z r \\<longleftrightarrow> (let (Ze, Re) = poincare_circle_euclidean z r in cmod x < 1 \\<and> x \\<in> circle Ze Re)\"\n      unfolding poincare_circle_euclidean_def Let_def circle_def\n      using z' R k\n      by (simp add: field_simps)\n    hence \"of_complex x \\<in> poincare_circle z r \\<longleftrightarrow> (let (Ze, Re) = poincare_circle_euclidean z r in x \\<in> circle Ze Re)\"\n      using poincare_circle_in_disc[OF \\<open>r > 0\\<close> \\<open>z \\<in> unit_disc\\<close>]\n      by auto\n  } note * = this\n  show ?thesis\n    unfolding Let_def\n  proof safe\n    fix Ze Re x\n    assume \"poincare_circle_euclidean z r = (Ze, Re)\" \"x \\<in> circle Ze Re\"\n    thus \"of_complex x \\<in> poincare_circle z r\"\n      using *[of x]\n      by simp\n  next\n    fix Ze Re x\n    assume **: \"poincare_circle_euclidean z r = (Ze, Re)\" \"x \\<in> poincare_circle z r\"\n    then obtain x' where x': \"x = of_complex x'\"\n      unfolding poincare_circle_def\n      using inf_or_of_complex[of x]\n      by auto\n    hence \"x' \\<in> circle Ze Re\"\n      using *[of x'] **\n      by simp\n    thus \"x \\<in> of_complex ` circle Ze Re\"\n      using x'\n      by auto\n  qed\nqed\n\nsubsection \\<open>Intersection of circles in special positions\\<close>\n\ntext \\<open>Two h-circles centered at the x-axis intersect at mutually conjugate points\\<close>\nlemma intersect_poincare_circles_x_axis:\n  assumes z: \"is_real z1\" and \"is_real z2\" and \"r1 > 0\" and \"r2 > 0\" and\n             \"-1 < Re z1\" and \"Re z1 < 1\" and \"-1 < Re z2\" and \"Re z2 < 1\" and\n             \"z1 \\<noteq> z2\"\n  assumes x1: \"x1 \\<in> poincare_circle (of_complex z1) r1 \\<inter> poincare_circle (of_complex z2) r2\" and\n          x2: \"x2 \\<in> poincare_circle (of_complex z1) r1 \\<inter> poincare_circle (of_complex z2) r2\" and\n              \"x1 \\<noteq> x2\"\n  shows \"x1 = conjugate x2\"\nproof-\n  have in_disc: \"of_complex z1 \\<in> unit_disc\" \"of_complex z2 \\<in> unit_disc\"\n    using assms\n    by (auto simp add: cmod_eq_Re)\n\n  obtain x1' x2' where x': \"x1 = of_complex x1'\" \"x2 = of_complex x2'\"\n    using x1 x2\n    using inf_or_of_complex[of x1] inf_or_of_complex[of x2]\n    unfolding poincare_circle_def\n    by auto\n\n  obtain Ze1 Re1 where 1: \"(Ze1, Re1) = poincare_circle_euclidean (of_complex z1) r1\"\n    by (metis poincare_circle_euclidean_def)\n  obtain Ze2 Re2 where 2: \"(Ze2, Re2) = poincare_circle_euclidean (of_complex z2) r2\"\n    by (metis poincare_circle_euclidean_def)\n  have circle: \"x1' \\<in> circle Ze1 Re1 \\<inter> circle Ze2 Re2\"  \"x2' \\<in> circle Ze1 Re1 \\<inter> circle Ze2 Re2\"\n    using poincare_circle_is_euclidean_circle[of \"of_complex z1\" r1]\n    using poincare_circle_is_euclidean_circle[of \"of_complex z2\" r2]\n    using assms 1 2 \\<open>of_complex z1 \\<in> unit_disc\\<close> \\<open>of_complex z2 \\<in> unit_disc\\<close> x'\n    by auto (metis image_iff of_complex_inj)+\n\n  have \"is_real Ze1\" \"is_real Ze2\"\n    using 1 2 \\<open>is_real z1\\<close> \\<open>is_real z2\\<close>\n    by (simp_all add: poincare_circle_euclidean_def Let_def)\n\n  have \"Re1 > 0\" \"Re2 > 0\"\n    using 1 2 in_disc \\<open>r1 > 0\\<close> \\<open>r2 > 0\\<close>\n    using poincare_circle_in_disc(2)[of r1 \"of_complex z1\" Ze1 Re1]\n    using poincare_circle_in_disc(2)[of r2 \"of_complex z2\" Ze2 Re2]\n    by auto\n\n  have \"Ze1 \\<noteq> Ze2\"\n  proof (rule ccontr)\n    assume \"\\<not> ?thesis\"\n    hence eq: \"Ze1 = Ze2\" \"Re1 = Re2\"\n      using circle(1)\n      unfolding circle_def\n      by auto\n\n    let ?A = \"Ze1 - Re1\" and ?B = \"Ze1 + Re1\"\n    have \"?A \\<in> circle Ze1 Re1\" \"?B \\<in> circle Ze1 Re1\"\n      using \\<open>Re1 > 0\\<close>\n      unfolding circle_def\n      by simp_all\n    hence \"of_complex ?A \\<in> poincare_circle (of_complex z1) r1\" \"of_complex ?B \\<in> poincare_circle (of_complex z1) r1\"\n          \"of_complex ?A \\<in> poincare_circle (of_complex z2) r2\" \"of_complex ?B \\<in> poincare_circle (of_complex z2) r2\"\n      using eq\n      using poincare_circle_is_euclidean_circle[OF \\<open>of_complex z1 \\<in> unit_disc\\<close> \\<open>r1 > 0\\<close>]\n      using poincare_circle_is_euclidean_circle[OF \\<open>of_complex z2 \\<in> unit_disc\\<close> \\<open>r2 > 0\\<close>]\n      using 1 2\n      by auto blast+\n    hence \"poincare_distance (of_complex z1) (of_complex ?A) = poincare_distance (of_complex z1) (of_complex ?B)\"\n          \"poincare_distance (of_complex z2) (of_complex ?A) = poincare_distance (of_complex z2) (of_complex ?B)\"\n          \"-1 < Re (Ze1 - Re1)\" \"Re (Ze1 - Re1) < 1\" \"-1 < Re (Ze1 + Re1)\" \"Re (Ze1 + Re1) < 1\"\n      using \\<open>is_real Ze1\\<close> \\<open>is_real Ze2\\<close>\n      unfolding poincare_circle_def\n      by (auto simp add: cmod_eq_Re)\n    hence \"z1 = z2\"\n      using unique_midpoint_x_axis[of \"Ze1 - Re1\" \"Ze1 + Re1\"]\n      using \\<open>is_real Ze1\\<close> \\<open>is_real z1\\<close> \\<open>is_real z2\\<close> \\<open>Re1 > 0\\<close> \\<open>-1 < Re z1\\<close> \\<open>Re z1 < 1\\<close> \\<open>-1 < Re z2\\<close> \\<open>Re z2 < 1\\<close>\n      by auto\n    thus False\n      using \\<open>z1 \\<noteq> z2\\<close>\n      by simp\n  qed\n\n  hence *: \"(Re x1')\\<^sup>2 + (Im x1')\\<^sup>2 - 2 * Re x1' * Ze1 + Ze1 * Ze1 - cor (Re1 * Re1) = 0\"\n           \"(Re x1')\\<^sup>2 + (Im x1')\\<^sup>2 - 2 * Re x1' * Ze2 + Ze2 * Ze2 - cor (Re2 * Re2) = 0\"\n           \"(Re x2')\\<^sup>2 + (Im x2')\\<^sup>2 - 2 * Re x2' * Ze1 + Ze1 * Ze1 - cor (Re1 * Re1) = 0\"\n           \"(Re x2')\\<^sup>2 + (Im x2')\\<^sup>2 - 2 * Re x2' * Ze2 + Ze2 * Ze2 - cor (Re2 * Re2) = 0\"\n    using circle_equation[of Re1 Ze1] circle_equation[of Re2 Ze2] circle\n    using eq_cnj_iff_real[of Ze1] \\<open>is_real Ze1\\<close> \\<open>Re1 > 0\\<close>\n    using eq_cnj_iff_real[of Ze2] \\<open>is_real Ze2\\<close> \\<open>Re2 > 0\\<close>\n    using complex_add_cnj[of x1']  complex_add_cnj[of x2']\n    using distrib_left[of Ze1 x1' \"cnj x1'\"] distrib_left[of Ze2 x1' \"cnj x1'\"]\n    using distrib_left[of Ze1 x2' \"cnj x2'\"] distrib_left[of Ze2 x2' \"cnj x2'\"]\n    by (auto simp add: complex_mult_cnj power2_eq_square field_simps)\n\n  hence \"- 2 * Re x1' * Ze1 + Ze1 * Ze1 - cor (Re1 * Re1) = - 2 * Re x1' * Ze2 + Ze2 * Ze2 - cor (Re2 * Re2)\"\n        \"- 2 * Re x2' * Ze1 + Ze1 * Ze1 - cor (Re1 * Re1) = - 2 * Re x2' * Ze2 + Ze2 * Ze2 - cor (Re2 * Re2)\"\n    by (smt add_diff_cancel_right' add_diff_eq eq_iff_diff_eq_0 minus_diff_eq mult_minus_left of_real_minus)+\n  hence \"2 * Re x1' * (Ze2 - Ze1) =  (Ze2 * Ze2 - cor (Re2 * Re2)) - (Ze1 * Ze1 - cor (Re1 * Re1))\"\n        \"2 * Re x2' * (Ze2 - Ze1) =  (Ze2 * Ze2 - cor (Re2 * Re2)) - (Ze1 * Ze1 - cor (Re1 * Re1))\"\n    by simp_all (simp add: field_simps)+\n  hence \"2 * Re x1' * (Ze2 - Ze1) = 2 * Re x2' * (Ze2 - Ze1)\"\n    by simp\n  hence \"Re x1' = Re x2'\"\n    using \\<open>Ze1 \\<noteq> Ze2\\<close>\n    by simp\n  moreover\n  hence \"(Im x1')\\<^sup>2 = (Im x2')\\<^sup>2\"\n    using *(1) *(3)\n    by (simp add: \\<open>is_real Ze1\\<close> complex_eq_if_Re_eq)\n  hence \"Im x1' = Im x2' \\<or> Im x1' = -Im x2'\"\n    using power2_eq_iff\n    by blast\n  ultimately\n  show ?thesis\n    using x' `x1 \\<noteq> x2`\n    using complex.expand\n    by (metis cnj.code complex_surj conjugate_of_complex)\nqed\n\n\ntext \\<open>Two h-circles of the same radius centered at mutually conjugate points intersect at the x-axis\\<close>\nlemma intersect_poincare_circles_conjugate_centers:\n  assumes in_disc: \"z1 \\<in> unit_disc\" \"z2 \\<in> unit_disc\" and \n          \"z1 \\<noteq> z2\" and \"z1 = conjugate z2\" and \"r > 0\" and\n          u: \"u \\<in> poincare_circle z1 r \\<inter> poincare_circle z2 r\"\n  shows \"is_real (to_complex u)\"\nproof-\n  obtain z1e r1e z2e r2e where\n   euclidean: \"(z1e, r1e) = poincare_circle_euclidean z1 r\"\n              \"(z2e, r2e) = poincare_circle_euclidean z2 r\"\n    by (metis poincare_circle_euclidean_def)\n  obtain z1' z2' where z': \"z1 = of_complex z1'\" \"z2 = of_complex z2'\"\n    using inf_or_of_complex[of z1] inf_or_of_complex[of z2] in_disc\n    by auto\n  obtain u' where u': \"u = of_complex u'\"\n    using u inf_or_of_complex[of u]\n    by (auto simp add: poincare_circle_def)\n  have \"z1' = cnj z2'\"\n    using \\<open>z1 = conjugate z2\\<close> z'\n    by (auto simp add: of_complex_inj)\n  moreover\n  let ?cz = \"1 - (cmod z2')\\<^sup>2\"\n  let ?den = \"?cz * (cosh r - 1) / 2 + 1\"\n  have \"?cz > 0\"\n    using in_disc z'\n    by (simp add: cmod_def)\n  hence \"?den \\<ge> 1\"\n    using cosh_gt_1[OF \\<open>r > 0\\<close>]\n    by auto\n  hence \"?den \\<noteq> 0\"\n    by simp\n  hence \"cor ?den \\<noteq> 0\"\n    using of_real_eq_0_iff\n    by blast\n  ultimately\n  have \"r1e = r2e\" \"z1e = cnj z2e\" \"z1e \\<noteq> z2e\"\n    using z' euclidean \\<open>z1 \\<noteq> z2\\<close>\n    unfolding poincare_circle_euclidean_def Let_def\n    by simp_all metis\n\n  hence \"u' \\<in> circle (cnj z2e) r2e \\<inter> circle z2e r2e\" \"z2e \\<noteq> cnj z2e\"\n    using euclidean u u'\n    using poincare_circle_is_euclidean_circle[of z1 r]\n    using poincare_circle_is_euclidean_circle[of z2 r]\n    using in_disc \\<open>r > 0\\<close>\n    by auto (metis image_iff of_complex_inj)+\n  hence \"(cmod (u' - z2e))\\<^sup>2 = (cmod(u' - cnj z2e))\\<^sup>2\"\n    by (simp add: circle_def)\n  hence \"(u' - z2e) * (cnj u' - cnj z2e) = (u' - cnj z2e) * (cnj u' - z2e)\"\n    by (metis complex_cnj_cnj complex_cnj_diff complex_norm_square)\n  hence \"(z2e - cnj z2e) * (u' - cnj u') = 0\"\n    by (simp add: field_simps)\n  thus ?thesis\n    using u' \\<open>z2e \\<noteq> cnj z2e\\<close> eq_cnj_iff_real[of u']\n    by simp\nqed\n\nsubsection \\<open>Congruent triangles\\<close>\n\ntext\\<open>For every pair of triangles such that its three pairs of sides are pairwise equal there is an\nh-isometry (a unit disc preserving M\u00f6bius transform, eventually composed with a conjugation) that\nmaps one triangle onto the other.\\<close>\nlemma unit_disc_fix_f_congruent_triangles:\n  assumes\n    in_disc: \"u \\<in> unit_disc\" \"v \\<in> unit_disc\" \"w \\<in> unit_disc\" and\n    in_disc': \"u' \\<in> unit_disc\" \"v' \\<in> unit_disc\" \"w' \\<in> unit_disc\" and \n    d: \"poincare_distance u v = poincare_distance u' v'\"\n       \"poincare_distance v w = poincare_distance v' w'\"\n       \"poincare_distance u w = poincare_distance u' w'\"\n  shows\n    \"\\<exists> M. unit_disc_fix_f M \\<and> M u = u' \\<and> M v = v' \\<and> M w = w'\"\nproof (cases \"u = v \\<or> u = w \\<or> v = w\")\n  case True\n  thus ?thesis\n    using assms\n    using poincare_distance_eq_0_iff[of u' v']\n    using poincare_distance_eq_0_iff[of v' w']\n    using poincare_distance_eq_0_iff[of u' w']\n    using poincare_distance_eq_ex_moebius[of v w v' w']\n    using poincare_distance_eq_ex_moebius[of u w u' w']\n    using poincare_distance_eq_ex_moebius[of u v u' v']\n    by (metis unit_disc_fix_f_def)\nnext\n  case False\n\n  have \"\\<forall> w u' v' w'. w \\<in> unit_disc \\<and> u' \\<in> unit_disc \\<and> v' \\<in> unit_disc \\<and> w' \\<in> unit_disc \\<and> w \\<noteq> u \\<and> w \\<noteq> v \\<and>\n    poincare_distance u v = poincare_distance u' v' \\<and>\n    poincare_distance v w = poincare_distance v' w' \\<and>\n    poincare_distance u w = poincare_distance u' w' \\<longrightarrow>\n    (\\<exists> M. unit_disc_fix_f M \\<and> M u = u' \\<and> M v = v' \\<and> M w = w')\" (is \"?P u v\")\n  proof (rule wlog_positive_x_axis[where P=\"?P\"])\n    show \"v \\<in> unit_disc\" \"u \\<in> unit_disc\"\n      by fact+\n  next\n    show \"u \\<noteq> v\"\n      using False\n      by simp\n  next\n    fix x\n    assume x: \"is_real x\" \"0 < Re x\" \"Re x < 1\"\n\n    hence \"of_complex x \\<noteq> 0\\<^sub>h\"\n      using of_complex_zero_iff[of x]\n      by (auto simp add: complex.expand)\n\n    show \"?P 0\\<^sub>h (of_complex x)\"\n    proof safe\n      fix w u' v' w'\n      assume in_disc: \"w \\<in> unit_disc\" \"u' \\<in> unit_disc\" \"v' \\<in> unit_disc\" \"w' \\<in> unit_disc\"\n      assume \"poincare_distance 0\\<^sub>h (of_complex x) = poincare_distance u' v'\"\n      then obtain M' where M': \"unit_disc_fix M'\" \"moebius_pt M' u' = 0\\<^sub>h\" \"moebius_pt M' v' = (of_complex x)\"\n        using poincare_distance_eq_ex_moebius[of u' v' \"0\\<^sub>h\" \"of_complex x\"] in_disc x\n        by (auto simp add: cmod_eq_Re)\n\n      let ?w = \"moebius_pt M' w'\"\n      have \"?w \\<in> unit_disc\"\n        using \\<open>unit_disc_fix M'\\<close> \\<open>w' \\<in> unit_disc\\<close>\n        by simp\n\n      assume \"w \\<noteq> 0\\<^sub>h\" \"w \\<noteq> of_complex x\"\n      hence dist_gt_0: \"poincare_distance 0\\<^sub>h w > 0\" \"poincare_distance (of_complex x) w > 0\"\n        using poincare_distance_eq_0_iff[of \"0\\<^sub>h\" w] in_disc poincare_distance_ge0[of \"0\\<^sub>h\" w]\n        using poincare_distance_eq_0_iff[of \"of_complex x\" w] in_disc poincare_distance_ge0[of \"of_complex x\" w]\n        using x\n        by (simp_all add: cmod_eq_Re)\n\n      assume \"poincare_distance (of_complex x) w = poincare_distance v' w'\"\n             \"poincare_distance 0\\<^sub>h w = poincare_distance u' w'\"\n      hence \"poincare_distance 0\\<^sub>h ?w = poincare_distance 0\\<^sub>h w\"\n            \"poincare_distance (of_complex x) ?w = poincare_distance (of_complex x) w\"\n        using M'(1) M'(2)[symmetric] M'(3)[symmetric] in_disc\n        using unit_disc_fix_preserve_poincare_distance[of M' u' w']\n        using unit_disc_fix_preserve_poincare_distance[of M' v' w']\n        by simp_all\n      hence \"?w \\<in> poincare_circle 0\\<^sub>h (poincare_distance 0\\<^sub>h w) \\<inter> poincare_circle (of_complex x) (poincare_distance (of_complex x) w)\"\n            \"w \\<in> poincare_circle 0\\<^sub>h (poincare_distance 0\\<^sub>h w) \\<inter> poincare_circle (of_complex x) (poincare_distance (of_complex x) w)\"\n        using \\<open>?w \\<in> unit_disc\\<close> \\<open>w \\<in> unit_disc\\<close>\n        unfolding poincare_circle_def\n        by simp_all\n      hence \"?w = w \\<or> ?w = conjugate w\"\n        using intersect_poincare_circles_x_axis[of 0 x \"poincare_distance 0\\<^sub>h w\" \"poincare_distance (of_complex x) w\" ?w w] x\n        using \\<open>of_complex x \\<noteq> 0\\<^sub>h\\<close> dist_gt_0\n        using poincare_distance_eq_0_iff\n        by auto\n      thus \"\\<exists>M. unit_disc_fix_f M \\<and> M 0\\<^sub>h = u' \\<and> M (of_complex x) = v' \\<and> M w = w'\"\n      proof\n        assume \"moebius_pt M' w' = w\"\n        thus ?thesis\n          using M'\n          using moebius_pt_invert[of M' u' \"0\\<^sub>h\"]\n          using moebius_pt_invert[of M' v' \"of_complex x\"]\n          using moebius_pt_invert[of M' w' \"w\"]\n          apply (rule_tac x=\"moebius_pt (-M')\" in exI)\n          apply (simp add: unit_disc_fix_f_def)\n          apply (rule_tac x=\"-M'\" in exI, simp)\n          done\n      next\n        let ?M = \"moebius_pt (-M') \\<circ> conjugate\"\n        assume \"moebius_pt M' w' = conjugate w\"\n        hence \"?M w = w'\"\n          using moebius_pt_invert[of  M' w' \"conjugate w\"]\n          by simp\n        moreover\n        have \"?M 0\\<^sub>h = u'\" \"?M (of_complex x) = v'\"\n          using moebius_pt_invert[of M' u' \"0\\<^sub>h\"]\n          using moebius_pt_invert[of M' v' \"of_complex x\"]\n          using M' \\<open>is_real x\\<close> eq_cnj_iff_real[of x]\n          by simp_all\n        moreover\n        have \"unit_disc_fix_f ?M\"\n          using \\<open>unit_disc_fix M'\\<close>\n          unfolding unit_disc_fix_f_def\n          by (rule_tac x=\"-M'\" in exI, simp)\n        ultimately\n        show ?thesis\n          by blast\n      qed\n    qed\n  next\n    fix M u v\n    assume 1: \"unit_disc_fix M\" \"u \\<in> unit_disc\" \"v \\<in> unit_disc\"\n    let ?Mu = \"moebius_pt M u\" and ?Mv = \"moebius_pt M v\"\n    assume 2: \"?P ?Mu ?Mv\"\n    show \"?P u v\"\n    proof safe\n      fix w u' v' w'\n      let ?Mw = \"moebius_pt M w\" and ?Mu' = \"moebius_pt M u'\" and ?Mv' = \"moebius_pt M v'\" and ?Mw' = \"moebius_pt M w'\"\n      assume \"w \\<in> unit_disc\" \"u' \\<in> unit_disc\" \"v' \\<in> unit_disc\" \"w' \\<in> unit_disc\" \"w \\<noteq> u\" \"w \\<noteq> v\"\n             \"poincare_distance u v = poincare_distance u' v'\"\n             \"poincare_distance v w = poincare_distance v' w'\"\n             \"poincare_distance u w = poincare_distance u' w'\"\n      then obtain M' where M': \"unit_disc_fix_f M'\" \"M' ?Mu = ?Mu'\" \"M' ?Mv = ?Mv'\" \"M' ?Mw = ?Mw'\"\n        using 1 2[rule_format, of ?Mw ?Mu' ?Mv' ?Mw']\n        by auto\n\n      let ?M = \"moebius_pt (-M) \\<circ> M' \\<circ> moebius_pt M\"\n      show \"\\<exists>M. unit_disc_fix_f M \\<and> M u = u' \\<and> M v = v' \\<and> M w = w'\"\n      proof (rule_tac x=\"?M\" in exI, safe)\n        show \"unit_disc_fix_f ?M\"\n          using M'(1) \\<open>unit_disc_fix M\\<close>\n          by (subst unit_disc_fix_f_comp, subst unit_disc_fix_f_comp, simp_all)\n      next\n        show \"?M u = u'\" \"?M v = v'\" \"?M w = w'\"\n          using M'\n          by auto\n      qed\n    qed\n  qed\n  thus ?thesis\n    using assms False\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_Circles.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8705972717658209, "lm_q2_score": 0.8539127566694178, "lm_q1q2_score": 0.7434141162824264}}
{"text": "theory BasicAlgebra\nimports Main\nbegin\n\n(* this is just me messing around reminding myself of basic Isabelle syntax *)\n\nlocale group =\n  fixes mult :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a\" (infixl \"\\<cdot>\" 50)\n  and id :: \"'a\"\n  and inv :: \"'a \\<Rightarrow> 'a\" \n  assumes lmultinv [simp] : \"(inv x) \\<cdot> x = id\"\n  and rmultinv [simp] : \"x \\<cdot> (inv x) = id\"\n  and lmultid [simp] : \"id \\<cdot> x = x\"\n  and rmultid [simp] : \"x \\<cdot> id = x\"\n  and assoc : \"(x \\<cdot> (y \\<cdot> z)) = ((x \\<cdot> y) \\<cdot> z)\"\n  \nlemma (in group) unique_id: \n  fixes id' :: \"'a\"\n  assumes \"\\<And> x. id' \\<cdot> x = x\" (* why do we have to quantify the x here? *)\n  and \"\\<And> x. x \\<cdot> id' = x\" \n  shows \"id = id'\"\n  proof -\n  have \"id' \\<cdot> id = id\" using assms by blast\n  moreover have \"id' \\<cdot> id = id'\" by simp\n  ultimately show ?thesis by simp\n  qed\n  \n  \nthm group_def\n\ndatatype Nat = Zero | Succ Nat\n\nfun addy :: \"Nat \\<Rightarrow> Nat \\<Rightarrow> Nat\" (infixl \"\\<oplus>\" 50) where\n\"addy Zero n = n\"|\n\"addy (Succ n) m = Succ (addy n m)\"\n\nfun subby :: \"Nat \\<Rightarrow> Nat \\<Rightarrow> Nat\" where\n\"subby Zero i = Zero\" |\n\"subby i Zero = i\" |\n\"subby (Succ i) (Succ j) = subby i j\"\n\nfun gt :: \"Nat \\<Rightarrow> Nat \\<Rightarrow> bool\" where\n\"gt (Succ i) Zero = True\" |\n\"gt Zero i = False\" |\n\"gt (Succ i) (Succ j) = gt i j\"\n\nfun lt :: \"Nat \\<Rightarrow> Nat \\<Rightarrow> bool\" where\n\"lt i Zero = False\" |\n\"lt Zero (Succ i) = True\" |\n\"lt (Succ i) (Succ j) = lt i j\"\n\ntheorem addy_assoc : \"n \\<oplus> (m \\<oplus> l) = ((n \\<oplus> m) \\<oplus> l)\"\nproof (induction n)\ncase Zero\n show ?case by simp\ncase (Succ n)\n thus ?case by simp\nqed\n\n\n\ndatatype Integer = IZ | IPos Nat | INeg Nat\n\nfun iaddy :: \"Integer \\<Rightarrow> Integer \\<Rightarrow> Integer\" (infixl \"\\<bullet>\" 50) where\n\"iaddy IZ i = i\" |\n\"iaddy i IZ = i\" |\n\"iaddy (IPos i) (IPos j) = IPos (Succ (i \\<oplus> j))\"|\n\"iaddy (INeg i) (INeg j) = INeg (Succ (i \\<oplus> j))\"|\n\"iaddy (IPos i) (INeg j) = (if (gt i j) \n  then (IPos (subby i (Succ j))) else \n    (if (lt i j) then (INeg (subby j (Succ i))) else IZ))\"|\n\"iaddy (INeg i) (IPos j) = (if (gt i j) \n  then (INeg (subby i (Succ j))) else \n    (if (lt i j) then (IPos (subby j (Succ i))) else IZ))\"\n\nlemma iassoc : \"(m \\<bullet> (n \\<bullet> l)) = ((m \\<bullet> n) \\<bullet> l)\"\nproof (induction m)\ncase IZ\n  show ?case by simp\ncase (IPos m)\n  show ?case apply -\n             apply (cases n)\n             apply simp\n             apply (cases l)\n             apply simp\n             apply (simp add: addy_assoc)\n             apply simp (* in progress *)", "meta": {"author": "clarissalittler", "repo": "isabelle-bits", "sha": "c98dfd406957af211f3ba563b2ca7109f6dc26e5", "save_path": "github-repos/isabelle/clarissalittler-isabelle-bits", "path": "github-repos/isabelle/clarissalittler-isabelle-bits/isabelle-bits-c98dfd406957af211f3ba563b2ca7109f6dc26e5/BasicAlgebra.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087985746092, "lm_q2_score": 0.8006920044739461, "lm_q1q2_score": 0.743369501901952}}
{"text": "(* Author: Alexander Bentkamp, Universit\u00e4t des Saarlandes\n*)\nsection \\<open>Missing Lemmas of Finite\\_Set\\<close>\ntheory DL_Missing_Finite_Set\nimports Main\nbegin\n\nlemma card_even[simp]: \"card {a \\<in> Collect even. a < 2 * n} = n\"\nproof (induction n)\n  case 0\n  then show ?case by auto\nnext\n  case (Suc n)\n  have \"{a \\<in> Collect even. a < 2 * Suc n} = insert (2*n) {a \\<in> Collect even. a < 2 * n}\"\n    using le_eq_less_or_eq less_Suc_eq_le subset_antisym by force\n  show ?case\n    unfolding \\<open>{a \\<in> Collect even. a < 2 * Suc n} = insert (2*n) {a \\<in> Collect even. a < 2 * n}\\<close>\n    using Suc card_insert_disjoint[of \"{a \\<in> Collect even. a < 2 * n}\" \"2*n\"]\n    by (simp add: finite_M_bounded_by_nat less_not_refl2)\nqed\n\nlemma card_odd[simp]: \"card {a \\<in> Collect odd. a < 2 * n} = n\"\nproof (induction n)\n  case 0\n  then show ?case by auto\nnext\n  case (Suc n)\n  have \"{a \\<in> Collect odd. a < 2 * Suc n} = insert (2*n+1) {a \\<in> Collect odd. a < 2 * n}\"\n    using le_eq_less_or_eq less_Suc_eq_le subset_antisym by force\n  show ?case\n    unfolding \\<open>{a \\<in> Collect odd. a < 2 * Suc n} = insert (2*n+1) {a \\<in> Collect odd. a < 2 * n}\\<close>\n    using Suc card_insert_disjoint[of \"{a \\<in> Collect even. a < 2 * n}\" \"2*n\"]\n    by (simp add: finite_M_bounded_by_nat less_not_refl2)\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/Deep_Learning/DL_Missing_Finite_Set.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970904940926, "lm_q2_score": 0.8438951025545426, "lm_q1q2_score": 0.743300351012255}}
{"text": "theory CS_Ch5\nimports Main\nbegin\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\nfixes a b :: int\nassumes \"b dvd (a + b)\"\nshows \"b dvd a\"\nproof -\n  { fix k assume k: \"a + b = b * k\"\n    have \"\\<exists>k'. a = b*k'\"\n    proof\n      show \"a = b*(k - 1)\" using k by (simp add: algebra_simps)\n    qed }\n  then show ?thesis using assms by (auto simp add: dvd_def)\nqed\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  hence \"T y x\" using T by auto\n  hence \"A y x\" using TA by simp\n  hence \"x = y\" using assms by simp\n  hence \"T x x\" using assms by (auto)\n  hence \"T x y\" using assms and `x = y` by (auto)\n  thus \"False\" using `\\<not> T x y` by auto\nqed\n\n(* 5.2 *)\n\nlemma not2k_is_2y_plus_1: \"\\<exists>l. a = 2 * l + 1 \\<Longrightarrow> \\<forall>k. (a :: nat) \\<noteq> 2 * k\" by presburger\n\nlemma shows \"(\\<exists>ys zs. xs = ys @ zs \\<and> length ys = length zs) \\<or> (\\<exists>ys zs. xs = ys @ zs \\<and> length ys = length zs + 1)\" (is \"?L \\<or> ?R\")\nproof cases\n  assume k2: \"even (length xs)\"\n  then obtain k where \"length xs = 2 * k\" using evenE by metis\n  let ?x = \"take k xs\"\n  let ?y = \"drop k xs\"\n  have \"(xs = ?x @ ?y \\<and> length ?x = length ?y)\" by (simp add: `length xs = 2 * k`)\n  thus ?thesis by metis\nnext\n  assume nk2: \"odd (length xs)\"\n  then obtain l where \"length xs = 2 * l + 1\" using oddE by metis\n  let ?x = \"take (l+1) xs\"\n  let ?y = \"drop (l+1) xs\"\n  have \"length ?x = length ?y + 1\" using `length xs = 2 * l + 1` by simp\n  moreover have \"xs = ?x @ ?y\" by simp\n  ultimately have \"(xs = ?x @ ?y \\<and> length ?x = length ?y + 1)\" by simp\n  hence th: \"?L \\<or> ?R\" by metis\n  thus ?thesis by metis\nqed\n\ninductive ev :: \"nat \\<Rightarrow> bool\" where\nev0: \"ev 0\" |\nevSS: \"ev n \\<Longrightarrow> ev (Suc (Suc n))\"\n\n(* 5.3 *)\n\nlemma\nassumes a: \"ev (Suc (Suc n))\"\nshows \"ev n\"\nproof -\n  from a show \"ev n\"\n  proof cases\n    case evSS thus \"ev n\" by simp\n  qed\nqed\n\n(* 5.4 *)\n\nlemma\nshows \"\\<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\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\niter0: \"iter r 0 x x\" |\niterstep: \"r x y \\<Longrightarrow> iter r n y z \\<Longrightarrow> iter r (n+1) x z\"\n\nlemma\nshows \"iter r n x y \\<Longrightarrow> star r x y\"\nproof (induction rule: iter.induct)\n  case iter0 show ?case by (rule star.refl)\nnext\n  case iterstep thus ?case by (auto intro: 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\n(* I don't think I like the case shorthand, but it sure does shorten proofs *)\nlemma\nfixes xs :: \"'a list\"\nshows \"x \\<in> elems xs \\<Longrightarrow> \\<exists>ys zs. xs = ys @ x # zs \\<and> x \\<notin> elems ys\"\nproof (induction xs)\n  case Nil\n  (* personally I would have wanted to do a proof-by-contradiction here, but the simplifier\n     seems to be able to handle this sort of case when it's simple enough *)\n  thus ?case by simp\nnext\n  case (Cons a as)\n  show ?case\n  proof cases\n    (* a and as (such that xs = a # as) becomes a \"Skolem variable\". I don't know precisely what this means yet, \n       but it seems to behave normally *)\n    assume \"x = a\"\n    then obtain zs where ac: \"a # as = x # zs\" by simp\n    let ?ys = \"[] :: 'a list\"\n    from ac have \"a # as = ?ys @ x # zs\" by simp\n    have s: \"x \\<notin> elems ?ys\" by simp\n    from ac s show ?case by blast \n    (* seems to be the easiest way to get the existential introduced.\n       unfortunately/fortunately, blast also knows how to solve the goal outright without any\n       of this manual fluffery! I think the point of this exercise is practice with structured\n       proofs, so I'll leave it in.*)\n   next\n    assume \"x \\<noteq> a\"\n    from this `x \\<in> elems (a # as)` have \"x \\<in> elems as\" by simp\n    from this Cons.IH obtain ys zs where \"as = ys @ x # zs \\<and> x \\<notin> elems ys\" by auto\n    (* interestingly, this is a case where auto works but simp doesn't.\n       I need to check the manual to see precisely what these proof methods do.\n    *)\n    from this `x \\<noteq> a` Cons.IH obtain ys' where \"a # as = ys' @ x # zs \\<and> x \\<notin> elems ys'\" by force\n    thus ?case by blast\n  qed\nqed\n  \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_Ch5.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950986284991, "lm_q2_score": 0.8807970779778824, "lm_q1q2_score": 0.743300336991839}}
{"text": "(*\n    $Id: sol.thy,v 1.4 2011/06/28 18:11:38 webertj Exp $\n    Author: Martin Strecker\n*)\n\nheader {* Sets as Lists *}\n\n(*<*) theory sol 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 *}\n\n\nprimrec list_union :: \"['a list, 'a list] \\<Rightarrow> 'a list\" where\n  \"list_union xs []     = xs\"\n| \"list_union xs (y#ys) = (let result = list_union xs ys in if y : set result then result else y#result)\"\n\ntext {* to be defined by you it has to be shown that *}\n\nlemma \"set (list_union xs ys) = set xs \\<union> set ys\"\n  apply (induct \"ys\")\n    apply simp\n  apply (simp add: Let_def)\n  apply auto\ndone\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, *}\n\nlemma [rule_format]: \n  \"distinct xs \\<longrightarrow> distinct ys \\<longrightarrow> (distinct (list_union xs ys))\"\n  apply (induct \"ys\")\n  apply (auto simp add: Let_def)\ndone\n\ntext {* \\emph{Hint:} @{text \"distinct\"} is defined in @{text List.thy}. *}\n\ntext {* We omit the definitions and correctness proofs for set\nintersection and set difference. *}\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> S. P x)\"\n(*<*)oops(*>*)\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\ntext {* Define a (non-trivial) predicate @{text P} such that *}\n\nlemma \"\\<forall> x \\<in> A. P (f x) \\<Longrightarrow>  \\<forall> y \\<in> f ` A. Q y\"\n(*<*)oops(*>*)\n\nlemma \"\\<forall> x \\<in> A. Q (f x) \\<Longrightarrow>  \\<forall> y \\<in> f ` A. Q y\"\n  by auto\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/sets/sol.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8519528057272543, "lm_q2_score": 0.8723473813156294, "lm_q1q2_score": 0.7431987990806734}}
{"text": "(*  Title:      HOL/Hahn_Banach/Subspace.thy\n    Author:     Gertrud Bauer, TU Munich\n*)\n\nsection \\<open>Subspaces\\<close>\n\ntheory Subspace\nimports Vector_Space \"~~/src/HOL/Library/Set_Algebras\"\nbegin\n\nsubsection \\<open>Definition\\<close>\n\ntext \\<open>\n  A non-empty subset \\<open>U\\<close> of a vector space \\<open>V\\<close> is a \\<^emph>\\<open>subspace\\<close> of \\<open>V\\<close>, iff\n  \\<open>U\\<close> is closed under addition and scalar multiplication.\n\\<close>\n\nlocale subspace =\n  fixes U :: \"'a::{minus, plus, zero, uminus} set\" and V\n  assumes non_empty [iff, intro]: \"U \\<noteq> {}\"\n    and subset [iff]: \"U \\<subseteq> V\"\n    and add_closed [iff]: \"x \\<in> U \\<Longrightarrow> y \\<in> U \\<Longrightarrow> x + y \\<in> U\"\n    and mult_closed [iff]: \"x \\<in> U \\<Longrightarrow> a \\<cdot> x \\<in> U\"\n\nnotation (symbols)\n  subspace  (infix \"\\<unlhd>\" 50)\n\ndeclare vectorspace.intro [intro?] subspace.intro [intro?]\n\nlemma subspace_subset [elim]: \"U \\<unlhd> V \\<Longrightarrow> U \\<subseteq> V\"\n  by (rule subspace.subset)\n\nlemma (in subspace) subsetD [iff]: \"x \\<in> U \\<Longrightarrow> x \\<in> V\"\n  using subset by blast\n\nlemma subspaceD [elim]: \"U \\<unlhd> V \\<Longrightarrow> x \\<in> U \\<Longrightarrow> x \\<in> V\"\n  by (rule subspace.subsetD)\n\nlemma rev_subspaceD [elim?]: \"x \\<in> U \\<Longrightarrow> U \\<unlhd> V \\<Longrightarrow> x \\<in> V\"\n  by (rule subspace.subsetD)\n\nlemma (in subspace) diff_closed [iff]:\n  assumes \"vectorspace V\"\n  assumes x: \"x \\<in> U\" and y: \"y \\<in> U\"\n  shows \"x - y \\<in> U\"\nproof -\n  interpret vectorspace V by fact\n  from x y show ?thesis by (simp add: diff_eq1 negate_eq1)\nqed\n\ntext \\<open>\n  \\<^medskip>\n  Similar as for linear spaces, the existence of the zero element in every\n  subspace follows from the non-emptiness of the carrier set and by vector\n  space laws.\n\\<close>\n\nlemma (in subspace) zero [intro]:\n  assumes \"vectorspace V\"\n  shows \"0 \\<in> U\"\nproof -\n  interpret V: vectorspace V by fact\n  have \"U \\<noteq> {}\" by (rule non_empty)\n  then obtain x where x: \"x \\<in> U\" by blast\n  then have \"x \\<in> V\" .. then have \"0 = x - x\" by simp\n  also from \\<open>vectorspace V\\<close> x x have \"\\<dots> \\<in> U\" by (rule diff_closed)\n  finally show ?thesis .\nqed\n\nlemma (in subspace) neg_closed [iff]:\n  assumes \"vectorspace V\"\n  assumes x: \"x \\<in> U\"\n  shows \"- x \\<in> U\"\nproof -\n  interpret vectorspace V by fact\n  from x show ?thesis by (simp add: negate_eq1)\nqed\n\ntext \\<open>\\<^medskip> Further derived laws: every subspace is a vector space.\\<close>\n\nlemma (in subspace) vectorspace [iff]:\n  assumes \"vectorspace V\"\n  shows \"vectorspace U\"\nproof -\n  interpret vectorspace V by fact\n  show ?thesis\n  proof\n    show \"U \\<noteq> {}\" ..\n    fix x y z assume x: \"x \\<in> U\" and y: \"y \\<in> U\" and z: \"z \\<in> U\"\n    fix a b :: real\n    from x y show \"x + y \\<in> U\" by simp\n    from x show \"a \\<cdot> x \\<in> U\" by simp\n    from x y z show \"(x + y) + z = x + (y + z)\" by (simp add: add_ac)\n    from x y show \"x + y = y + x\" by (simp add: add_ac)\n    from x show \"x - x = 0\" by simp\n    from x show \"0 + x = x\" by simp\n    from x y show \"a \\<cdot> (x + y) = a \\<cdot> x + a \\<cdot> y\" by (simp add: distrib)\n    from x show \"(a + b) \\<cdot> x = a \\<cdot> x + b \\<cdot> x\" by (simp add: distrib)\n    from x show \"(a * b) \\<cdot> x = a \\<cdot> b \\<cdot> x\" by (simp add: mult_assoc)\n    from x show \"1 \\<cdot> x = x\" by simp\n    from x show \"- x = - 1 \\<cdot> x\" by (simp add: negate_eq1)\n    from x y show \"x - y = x + - y\" by (simp add: diff_eq1)\n  qed\nqed\n\n\ntext \\<open>The subspace relation is reflexive.\\<close>\n\nlemma (in vectorspace) subspace_refl [intro]: \"V \\<unlhd> V\"\nproof\n  show \"V \\<noteq> {}\" ..\n  show \"V \\<subseteq> V\" ..\nnext\n  fix x y assume x: \"x \\<in> V\" and y: \"y \\<in> V\"\n  fix a :: real\n  from x y show \"x + y \\<in> V\" by simp\n  from x show \"a \\<cdot> x \\<in> V\" by simp\nqed\n\ntext \\<open>The subspace relation is transitive.\\<close>\n\nlemma (in vectorspace) subspace_trans [trans]:\n  \"U \\<unlhd> V \\<Longrightarrow> V \\<unlhd> W \\<Longrightarrow> U \\<unlhd> W\"\nproof\n  assume uv: \"U \\<unlhd> V\" and vw: \"V \\<unlhd> W\"\n  from uv show \"U \\<noteq> {}\" by (rule subspace.non_empty)\n  show \"U \\<subseteq> W\"\n  proof -\n    from uv have \"U \\<subseteq> V\" by (rule subspace.subset)\n    also from vw have \"V \\<subseteq> W\" by (rule subspace.subset)\n    finally show ?thesis .\n  qed\n  fix x y assume x: \"x \\<in> U\" and y: \"y \\<in> U\"\n  from uv and x y show \"x + y \\<in> U\" by (rule subspace.add_closed)\n  from uv and x show \"a \\<cdot> x \\<in> U\" for a by (rule subspace.mult_closed)\nqed\n\n\nsubsection \\<open>Linear closure\\<close>\n\ntext \\<open>\n  The \\<^emph>\\<open>linear closure\\<close> of a vector \\<open>x\\<close> is the set of all scalar multiples of\n  \\<open>x\\<close>.\n\\<close>\n\ndefinition lin :: \"('a::{minus,plus,zero}) \\<Rightarrow> 'a set\"\n  where \"lin x = {a \\<cdot> x | a. True}\"\n\nlemma linI [intro]: \"y = a \\<cdot> x \\<Longrightarrow> y \\<in> lin x\"\n  unfolding lin_def by blast\n\nlemma linI' [iff]: \"a \\<cdot> x \\<in> lin x\"\n  unfolding lin_def by blast\n\nlemma linE [elim]:\n  assumes \"x \\<in> lin v\"\n  obtains a :: real where \"x = a \\<cdot> v\"\n  using assms unfolding lin_def by blast\n\n\ntext \\<open>Every vector is contained in its linear closure.\\<close>\n\nlemma (in vectorspace) x_lin_x [iff]: \"x \\<in> V \\<Longrightarrow> x \\<in> lin x\"\nproof -\n  assume \"x \\<in> V\"\n  then have \"x = 1 \\<cdot> x\" by simp\n  also have \"\\<dots> \\<in> lin x\" ..\n  finally show ?thesis .\nqed\n\nlemma (in vectorspace) \"0_lin_x\" [iff]: \"x \\<in> V \\<Longrightarrow> 0 \\<in> lin x\"\nproof\n  assume \"x \\<in> V\"\n  then show \"0 = 0 \\<cdot> x\" by simp\nqed\n\ntext \\<open>Any linear closure is a subspace.\\<close>\n\nlemma (in vectorspace) lin_subspace [intro]:\n  assumes x: \"x \\<in> V\"\n  shows \"lin x \\<unlhd> V\"\nproof\n  from x show \"lin x \\<noteq> {}\" by auto\nnext\n  show \"lin x \\<subseteq> V\"\n  proof\n    fix x' assume \"x' \\<in> lin x\"\n    then obtain a where \"x' = a \\<cdot> x\" ..\n    with x show \"x' \\<in> V\" by simp\n  qed\nnext\n  fix x' x'' assume x': \"x' \\<in> lin x\" and x'': \"x'' \\<in> lin x\"\n  show \"x' + x'' \\<in> lin x\"\n  proof -\n    from x' obtain a' where \"x' = a' \\<cdot> x\" ..\n    moreover from x'' obtain a'' where \"x'' = a'' \\<cdot> x\" ..\n    ultimately have \"x' + x'' = (a' + a'') \\<cdot> x\"\n      using x by (simp add: distrib)\n    also have \"\\<dots> \\<in> lin x\" ..\n    finally show ?thesis .\n  qed\n  fix a :: real\n  show \"a \\<cdot> x' \\<in> lin x\"\n  proof -\n    from x' obtain a' where \"x' = a' \\<cdot> x\" ..\n    with x have \"a \\<cdot> x' = (a * a') \\<cdot> x\" by (simp add: mult_assoc)\n    also have \"\\<dots> \\<in> lin x\" ..\n    finally show ?thesis .\n  qed\nqed\n\n\ntext \\<open>Any linear closure is a vector space.\\<close>\n\nlemma (in vectorspace) lin_vectorspace [intro]:\n  assumes \"x \\<in> V\"\n  shows \"vectorspace (lin x)\"\nproof -\n  from \\<open>x \\<in> V\\<close> have \"subspace (lin x) V\"\n    by (rule lin_subspace)\n  from this and vectorspace_axioms show ?thesis\n    by (rule subspace.vectorspace)\nqed\n\n\nsubsection \\<open>Sum of two vectorspaces\\<close>\n\ntext \\<open>\n  The \\<^emph>\\<open>sum\\<close> of two vectorspaces \\<open>U\\<close> and \\<open>V\\<close> is the set of all sums of\n  elements from \\<open>U\\<close> and \\<open>V\\<close>.\n\\<close>\n\nlemma sum_def: \"U + V = {u + v | u v. u \\<in> U \\<and> v \\<in> V}\"\n  unfolding set_plus_def by auto\n\nlemma sumE [elim]:\n    \"x \\<in> U + V \\<Longrightarrow> (\\<And>u v. x = u + v \\<Longrightarrow> u \\<in> U \\<Longrightarrow> v \\<in> V \\<Longrightarrow> C) \\<Longrightarrow> C\"\n  unfolding sum_def by blast\n\nlemma sumI [intro]:\n    \"u \\<in> U \\<Longrightarrow> v \\<in> V \\<Longrightarrow> x = u + v \\<Longrightarrow> x \\<in> U + V\"\n  unfolding sum_def by blast\n\nlemma sumI' [intro]:\n    \"u \\<in> U \\<Longrightarrow> v \\<in> V \\<Longrightarrow> u + v \\<in> U + V\"\n  unfolding sum_def by blast\n\ntext \\<open>\\<open>U\\<close> is a subspace of \\<open>U + V\\<close>.\\<close>\n\nlemma subspace_sum1 [iff]:\n  assumes \"vectorspace U\" \"vectorspace V\"\n  shows \"U \\<unlhd> U + V\"\nproof -\n  interpret vectorspace U by fact\n  interpret vectorspace V by fact\n  show ?thesis\n  proof\n    show \"U \\<noteq> {}\" ..\n    show \"U \\<subseteq> U + V\"\n    proof\n      fix x assume x: \"x \\<in> U\"\n      moreover have \"0 \\<in> V\" ..\n      ultimately have \"x + 0 \\<in> U + V\" ..\n      with x show \"x \\<in> U + V\" by simp\n    qed\n    fix x y assume x: \"x \\<in> U\" and \"y \\<in> U\"\n    then show \"x + y \\<in> U\" by simp\n    from x show \"a \\<cdot> x \\<in> U\" for a by simp\n  qed\nqed\n\ntext \\<open>The sum of two subspaces is again a subspace.\\<close>\n\nlemma sum_subspace [intro?]:\n  assumes \"subspace U E\" \"vectorspace E\" \"subspace V E\"\n  shows \"U + V \\<unlhd> E\"\nproof -\n  interpret subspace U E by fact\n  interpret vectorspace E by fact\n  interpret subspace V E by fact\n  show ?thesis\n  proof\n    have \"0 \\<in> U + V\"\n    proof\n      show \"0 \\<in> U\" using \\<open>vectorspace E\\<close> ..\n      show \"0 \\<in> V\" using \\<open>vectorspace E\\<close> ..\n      show \"(0::'a) = 0 + 0\" by simp\n    qed\n    then show \"U + V \\<noteq> {}\" by blast\n    show \"U + V \\<subseteq> E\"\n    proof\n      fix x assume \"x \\<in> U + V\"\n      then obtain u v where \"x = u + v\" and\n        \"u \\<in> U\" and \"v \\<in> V\" ..\n      then show \"x \\<in> E\" by simp\n    qed\n  next\n    fix x y assume x: \"x \\<in> U + V\" and y: \"y \\<in> U + V\"\n    show \"x + y \\<in> U + V\"\n    proof -\n      from x obtain ux vx where \"x = ux + vx\" and \"ux \\<in> U\" and \"vx \\<in> V\" ..\n      moreover\n      from y obtain uy vy where \"y = uy + vy\" and \"uy \\<in> U\" and \"vy \\<in> V\" ..\n      ultimately\n      have \"ux + uy \\<in> U\"\n        and \"vx + vy \\<in> V\"\n        and \"x + y = (ux + uy) + (vx + vy)\"\n        using x y by (simp_all add: add_ac)\n      then show ?thesis ..\n    qed\n    fix a show \"a \\<cdot> x \\<in> U + V\"\n    proof -\n      from x obtain u v where \"x = u + v\" and \"u \\<in> U\" and \"v \\<in> V\" ..\n      then have \"a \\<cdot> u \\<in> U\" and \"a \\<cdot> v \\<in> V\"\n        and \"a \\<cdot> x = (a \\<cdot> u) + (a \\<cdot> v)\" by (simp_all add: distrib)\n      then show ?thesis ..\n    qed\n  qed\nqed\n\ntext \\<open>The sum of two subspaces is a vectorspace.\\<close>\n\nlemma sum_vs [intro?]:\n    \"U \\<unlhd> E \\<Longrightarrow> V \\<unlhd> E \\<Longrightarrow> vectorspace E \\<Longrightarrow> vectorspace (U + V)\"\n  by (rule subspace.vectorspace) (rule sum_subspace)\n\n\nsubsection \\<open>Direct sums\\<close>\n\ntext \\<open>\n  The sum of \\<open>U\\<close> and \\<open>V\\<close> is called \\<^emph>\\<open>direct\\<close>, iff the zero element is the only\n  common element of \\<open>U\\<close> and \\<open>V\\<close>. For every element \\<open>x\\<close> of the direct sum of\n  \\<open>U\\<close> and \\<open>V\\<close> the decomposition in \\<open>x = u + v\\<close> with \\<open>u \\<in> U\\<close> and \\<open>v \\<in> V\\<close> is\n  unique.\n\\<close>\n\nlemma decomp:\n  assumes \"vectorspace E\" \"subspace U E\" \"subspace V E\"\n  assumes direct: \"U \\<inter> V = {0}\"\n    and u1: \"u1 \\<in> U\" and u2: \"u2 \\<in> U\"\n    and v1: \"v1 \\<in> V\" and v2: \"v2 \\<in> V\"\n    and sum: \"u1 + v1 = u2 + v2\"\n  shows \"u1 = u2 \\<and> v1 = v2\"\nproof -\n  interpret vectorspace E by fact\n  interpret subspace U E by fact\n  interpret subspace V E by fact\n  show ?thesis\n  proof\n    have U: \"vectorspace U\"  (* FIXME: use interpret *)\n      using \\<open>subspace U E\\<close> \\<open>vectorspace E\\<close> by (rule subspace.vectorspace)\n    have V: \"vectorspace V\"\n      using \\<open>subspace V E\\<close> \\<open>vectorspace E\\<close> by (rule subspace.vectorspace)\n    from u1 u2 v1 v2 and sum have eq: \"u1 - u2 = v2 - v1\"\n      by (simp add: add_diff_swap)\n    from u1 u2 have u: \"u1 - u2 \\<in> U\"\n      by (rule vectorspace.diff_closed [OF U])\n    with eq have v': \"v2 - v1 \\<in> U\" by (simp only:)\n    from v2 v1 have v: \"v2 - v1 \\<in> V\"\n      by (rule vectorspace.diff_closed [OF V])\n    with eq have u': \" u1 - u2 \\<in> V\" by (simp only:)\n    \n    show \"u1 = u2\"\n    proof (rule add_minus_eq)\n      from u1 show \"u1 \\<in> E\" ..\n      from u2 show \"u2 \\<in> E\" ..\n      from u u' and direct show \"u1 - u2 = 0\" by blast\n    qed\n    show \"v1 = v2\"\n    proof (rule add_minus_eq [symmetric])\n      from v1 show \"v1 \\<in> E\" ..\n      from v2 show \"v2 \\<in> E\" ..\n      from v v' and direct show \"v2 - v1 = 0\" by blast\n    qed\n  qed\nqed\n\ntext \\<open>\n  An application of the previous lemma will be used in the proof of the\n  Hahn-Banach Theorem (see page \\pageref{decomp-H-use}): for any element\n  \\<open>y + a \\<cdot> x\\<^sub>0\\<close> of the direct sum of a vectorspace \\<open>H\\<close> and the linear closure\n  of \\<open>x\\<^sub>0\\<close> the components \\<open>y \\<in> H\\<close> and \\<open>a\\<close> are uniquely determined.\n\\<close>\n\nlemma decomp_H':\n  assumes \"vectorspace E\" \"subspace H E\"\n  assumes y1: \"y1 \\<in> H\" and y2: \"y2 \\<in> H\"\n    and x': \"x' \\<notin> H\"  \"x' \\<in> E\"  \"x' \\<noteq> 0\"\n    and eq: \"y1 + a1 \\<cdot> x' = y2 + a2 \\<cdot> x'\"\n  shows \"y1 = y2 \\<and> a1 = a2\"\nproof -\n  interpret vectorspace E by fact\n  interpret subspace H E by fact\n  show ?thesis\n  proof\n    have c: \"y1 = y2 \\<and> a1 \\<cdot> x' = a2 \\<cdot> x'\"\n    proof (rule decomp)\n      show \"a1 \\<cdot> x' \\<in> lin x'\" ..\n      show \"a2 \\<cdot> x' \\<in> lin x'\" ..\n      show \"H \\<inter> lin x' = {0}\"\n      proof\n        show \"H \\<inter> lin x' \\<subseteq> {0}\"\n        proof\n          fix x assume x: \"x \\<in> H \\<inter> lin x'\"\n          then obtain a where xx': \"x = a \\<cdot> x'\"\n            by blast\n          have \"x = 0\"\n          proof cases\n            assume \"a = 0\"\n            with xx' and x' show ?thesis by simp\n          next\n            assume a: \"a \\<noteq> 0\"\n            from x have \"x \\<in> H\" ..\n            with xx' have \"inverse a \\<cdot> a \\<cdot> x' \\<in> H\" by simp\n            with a and x' have \"x' \\<in> H\" by (simp add: mult_assoc2)\n            with \\<open>x' \\<notin> H\\<close> show ?thesis by contradiction\n          qed\n          then show \"x \\<in> {0}\" ..\n        qed\n        show \"{0} \\<subseteq> H \\<inter> lin x'\"\n        proof -\n          have \"0 \\<in> H\" using \\<open>vectorspace E\\<close> ..\n          moreover have \"0 \\<in> lin x'\" using \\<open>x' \\<in> E\\<close> ..\n          ultimately show ?thesis by blast\n        qed\n      qed\n      show \"lin x' \\<unlhd> E\" using \\<open>x' \\<in> E\\<close> ..\n    qed (rule \\<open>vectorspace E\\<close>, rule \\<open>subspace H E\\<close>, rule y1, rule y2, rule eq)\n    then show \"y1 = y2\" ..\n    from c have \"a1 \\<cdot> x' = a2 \\<cdot> x'\" ..\n    with x' show \"a1 = a2\" by (simp add: mult_right_cancel)\n  qed\nqed\n\ntext \\<open>\n  Since for any element \\<open>y + a \\<cdot> x'\\<close> of the direct sum of a vectorspace \\<open>H\\<close>\n  and the linear closure of \\<open>x'\\<close> the components \\<open>y \\<in> H\\<close> and \\<open>a\\<close> are unique, it\n  follows from \\<open>y \\<in> H\\<close> that \\<open>a = 0\\<close>.\n\\<close>\n\nlemma decomp_H'_H:\n  assumes \"vectorspace E\" \"subspace H E\"\n  assumes t: \"t \\<in> H\"\n    and x': \"x' \\<notin> H\"  \"x' \\<in> E\"  \"x' \\<noteq> 0\"\n  shows \"(SOME (y, a). t = y + a \\<cdot> x' \\<and> y \\<in> H) = (t, 0)\"\nproof -\n  interpret vectorspace E by fact\n  interpret subspace H E by fact\n  show ?thesis\n  proof (rule, simp_all only: split_paired_all split_conv)\n    from t x' show \"t = t + 0 \\<cdot> x' \\<and> t \\<in> H\" by simp\n    fix y and a assume ya: \"t = y + a \\<cdot> x' \\<and> y \\<in> H\"\n    have \"y = t \\<and> a = 0\"\n    proof (rule decomp_H')\n      from ya x' show \"y + a \\<cdot> x' = t + 0 \\<cdot> x'\" by simp\n      from ya show \"y \\<in> H\" ..\n    qed (rule \\<open>vectorspace E\\<close>, rule \\<open>subspace H E\\<close>, rule t, (rule x')+)\n    with t x' show \"(y, a) = (y + a \\<cdot> x', 0)\" by simp\n  qed\nqed\n\ntext \\<open>\n  The components \\<open>y \\<in> H\\<close> and \\<open>a\\<close> in \\<open>y + a \\<cdot> x'\\<close> are unique, so the function\n  \\<open>h'\\<close> defined by \\<open>h' (y + a \\<cdot> x') = h y + a \\<cdot> \\<xi>\\<close> is definite.\n\\<close>\n\nlemma h'_definite:\n  fixes H\n  assumes h'_def:\n    \"\\<And>x. h' x =\n      (let (y, a) = SOME (y, a). (x = y + a \\<cdot> x' \\<and> y \\<in> H)\n       in (h y) + a * xi)\"\n    and x: \"x = y + a \\<cdot> x'\"\n  assumes \"vectorspace E\" \"subspace H E\"\n  assumes y: \"y \\<in> H\"\n    and x': \"x' \\<notin> H\"  \"x' \\<in> E\"  \"x' \\<noteq> 0\"\n  shows \"h' x = h y + a * xi\"\nproof -\n  interpret vectorspace E by fact\n  interpret subspace H E by fact\n  from x y x' have \"x \\<in> H + lin x'\" by auto\n  have \"\\<exists>!(y, a). x = y + a \\<cdot> x' \\<and> y \\<in> H\" (is \"\\<exists>!p. ?P p\")\n  proof (rule ex_ex1I)\n    from x y show \"\\<exists>p. ?P p\" by blast\n    fix p q assume p: \"?P p\" and q: \"?P q\"\n    show \"p = q\"\n    proof -\n      from p have xp: \"x = fst p + snd p \\<cdot> x' \\<and> fst p \\<in> H\"\n        by (cases p) simp\n      from q have xq: \"x = fst q + snd q \\<cdot> x' \\<and> fst q \\<in> H\"\n        by (cases q) simp\n      have \"fst p = fst q \\<and> snd p = snd q\"\n      proof (rule decomp_H')\n        from xp show \"fst p \\<in> H\" ..\n        from xq show \"fst q \\<in> H\" ..\n        from xp and xq show \"fst p + snd p \\<cdot> x' = fst q + snd q \\<cdot> x'\"\n          by simp\n      qed (rule \\<open>vectorspace E\\<close>, rule \\<open>subspace H E\\<close>, (rule x')+)\n      then show ?thesis by (cases p, cases q) simp\n    qed\n  qed\n  then have eq: \"(SOME (y, a). x = y + a \\<cdot> x' \\<and> y \\<in> H) = (y, a)\"\n    by (rule some1_equality) (simp add: x y)\n  with h'_def show \"h' x = h y + a * xi\" by (simp add: Let_def)\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/Hahn_Banach/Subspace.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8333245870332531, "lm_q2_score": 0.891811054783143, "lm_q1q2_score": 0.7431680789388525}}
{"text": "\\<^marker>\\<open>creator Florian Ke\u00dfler\\<close>\n\nsection \"Binary Arithmetic\"\n                                                    \ntheory Binary_Arithmetic \n  imports Main \"../IMP_Minus_Minus_Small_StepT\" \"HOL-Library.Discrete\"\n\nbegin \n\ntext \\<open> In this theory, we introduce functions to access bits out of nats, and Lemmas that relate \n        the bits in the result of addition and subtraction to the bits of the original numbers. \\<close>\n\nfun nth_bit_nat:: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\" where\n\"nth_bit_nat x 0 = x mod 2\" |\n\"nth_bit_nat x (Suc n) = nth_bit_nat (x div 2) n\"\n\nlemma nth_bit_nat_is_right_shift: \"nth_bit_nat x n = (x div 2 ^ n) mod 2\"\n  apply(induction n arbitrary: x)\n  by(auto simp:  div_mult2_eq)\n\ndefinition nth_bit:: \"nat \\<Rightarrow> nat \\<Rightarrow> bit\" where\n\"nth_bit x n = nat_to_bit (nth_bit_nat x n)\" \n\nfun nth_bit_of_num:: \"num \\<Rightarrow> nat \\<Rightarrow> bit\" where\n\"nth_bit_of_num Num.One 0 = One\" |\n\"nth_bit_of_num Num.One (Suc n) = Zero\" | \n\"nth_bit_of_num (Num.Bit0 x) 0 = Zero\" |\n\"nth_bit_of_num (Num.Bit1 x) 0 = One\" |\n\"nth_bit_of_num (Num.Bit0 x) (Suc n) = nth_bit_of_num x n\" |\n\"nth_bit_of_num (Num.Bit1 x) (Suc n) = nth_bit_of_num x n\"\n\nlemma nth_bit_nat_of_zero[simp]: \"nth_bit_nat 0 n = 0\" \n  by (induction n) auto\n\nlemma nth_bit_of_zero[simp]: \"nth_bit 0 n = Zero\" \n  by (induction n) (auto simp: nth_bit_def)\n\nlemma nth_bit_of_one[simp]: \"nth_bit (Suc 0) n = (if n = 0 then One else Zero)\"\n  apply(cases n)\n  by(auto simp: nth_bit_def nat_to_bit_eq_Zero_iff)\n\nlemma one_plus_2n_is_odd[simp]: \"Suc (n + n) mod 2 = 1\" by presburger\n\nlemma nth_bit_of_nat_of_num: \"nth_bit (nat_of_num x) n = nth_bit_of_num x n\" \nproof(induction n arbitrary: x)\n  case 0\n  then show ?case by (cases x) (auto simp: nth_bit_def nat_to_bit_eq_One_iff)\nnext\n  case (Suc n)\n  then show ?case using Suc by (cases x) (auto simp: nth_bit_def)\nqed\n\nlemma nth_bit_is_nth_bit_of_num: \"nth_bit x n = (if x = 0 then Zero\n  else nth_bit_of_num (num_of_nat x) n)\" \nproof (cases \"x = 0\")\n  case False\n  hence \"nth_bit x n = nth_bit (nat_of_num (num_of_nat x)) n\" using num_of_nat_inverse by auto\n  thus ?thesis using False by(simp add: nth_bit_of_nat_of_num)\nqed auto\n\nlemma le_2_to_the_n_then_nth_bit_zero: \"x < 2 ^ n \\<Longrightarrow> nth_bit x n = Zero\" \n  by(auto simp: nth_bit_def nat_to_bit_eq_Zero_iff nth_bit_nat_is_right_shift)\n\nlemma nth_bit_add_out_of_range: \"(a :: nat) < 2 ^ n \\<Longrightarrow> j < n \\<Longrightarrow> nth_bit (2 ^ n + a) j = nth_bit a j\" \nproof-\n  assume \"a < 2 ^ n\" \"j < n\" \n  have \"(2 ^ n + a) div 2 ^ j mod 2 = ((2 ^ n) div 2 ^ j + a div 2 ^ j) mod 2\" \n    using div_plus_div_distrib_dvd_left[OF le_imp_power_dvd[OF less_imp_le_nat[OF \\<open>j < n\\<close>]]]\n    by metis\n  also have \"... = (2 ^ (n - j) + a div 2 ^ j) mod 2\" using \\<open>j < n\\<close> \n    using power_diff[OF _ less_imp_le_nat[OF \\<open>j < n\\<close>], where ?a=2] \n    by (metis nat.simps numeral_2_eq_2)\n  also have  \"... = a div 2 ^ j mod 2\" using \\<open>j < n\\<close> \n    by (metis (no_types, lifting) Suc_leI add.commute add.right_neutral even_iff_mod_2_eq_zero \n        le_imp_power_dvd mod_add_left_eq power_Suc0_right zero_less_diff)\n  finally show ?thesis \n    apply(cases \"nth_bit a j\")\n    by(auto simp: nth_bit_def nat_to_bit_cases nth_bit_nat_is_right_shift)\nqed\n\nfun nth_carry:: \"nat \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> bit\" where\n\"nth_carry 0 a b = (if (nth_bit a 0 = One \\<and> nth_bit b 0 = One) then One else Zero)\" | \n\"nth_carry (Suc n) a b = (if (nth_bit a (Suc n) = One \\<and> nth_bit b (Suc n) = One) \n  \\<or> ((nth_bit a (Suc n) = One \\<or> nth_bit b (Suc n) = One) \\<and> nth_carry n a b = One) \n  then One else Zero)\" \n\nlemma a_mod_n_plus_b_mod_n_geq_a_plus_b_mod_n: \"(a :: nat) mod n + b mod n \\<ge> (a + b) mod n\" \n  by (metis mod_add_eq mod_less_eq_dividend)\n\nlemma a_mod_2_to_the_n_decomposition: \"(a :: nat) mod (2 * 2 ^ n) \n  = a div 2 ^ n mod 2 * 2 ^ n +  a mod 2 ^ n\" \n  by (metis mod_mult2_eq mult.commute)\n\nlemma a_mod_plus_b_mod_div_le_2: \"((a :: nat) mod 2 ^ n + b mod 2 ^ n) div 2 ^ n < 2\" \nproof-\n  have \"a mod 2 ^ n < 2 ^ n\" \"b mod 2 ^ n < 2 ^ n\" by auto\n  hence \"(a mod 2 ^ n + b mod 2 ^ n) < 2 * 2 ^ n\" by linarith\n  thus ?thesis using less_mult_imp_div_less by simp\nqed\n\nlemma a_mod_plus_b_mod: \"((a :: nat) mod (2 * 2 ^ n) + b mod (2 * 2 ^ n)) div (2 * 2 ^ n) mod 2 \n  = (a div 2 ^ n mod 2 + b div 2 ^ n mod 2 + \n      (a mod (2 ^ n) + b mod (2 ^ n)) div (2 ^ n) mod 2) div 2\" \nproof -\n  have \"(a mod (2 * 2 ^ n) + b mod (2 * 2 ^ n)) div (2 * 2 ^ n) mod 2 \n    = (a div 2 ^ n mod 2 * 2 ^ n + b div 2 ^ n mod 2 * 2 ^ n \n      + a mod 2 ^ n + b mod 2 ^ n) div (2 * 2 ^ n) mod 2\"\n    using a_mod_2_to_the_n_decomposition by presburger\n  also have \"... = ((a div 2 ^ n mod 2 * 2 ^ n + b div 2 ^ n mod 2 * 2 ^ n \n      + a mod 2 ^ n + b mod 2 ^ n) div 2 ^ n) div 2 mod 2\"\n    by (metis (mono_tags, lifting) div_mult2_eq mult.commute)\n  also have \"... = ((a div 2 ^ n mod 2 * 2 ^ n) div 2 ^ n  + (b div 2 ^ n mod 2 * 2 ^ n) div 2 ^ n\n      + (a mod 2 ^ n + b mod 2 ^ n) div 2 ^ n) div 2 mod 2\" by (simp add: add.assoc)\n  also have \"... = (a div 2 ^ n mod 2  + b div 2 ^ n mod 2 \n      + (a mod 2 ^ n + b mod 2 ^ n) div 2 ^ n) div 2 mod 2\" by simp\n  also have \"... = (a div 2 ^ n mod 2  + b div 2 ^ n mod 2 \n      + (a mod 2 ^ n + b mod 2 ^ n) div 2 ^ n mod 2) div 2 mod 2\" \n    using a_mod_plus_b_mod_div_le_2 by simp\n  finally show ?thesis by simp\nqed\n\nlemma nth_carry_mod: \"nth_carry n a b = \n  nth_bit ((a mod 2 ^ Suc n) + (b mod 2 ^ Suc n)) (Suc n)\" \nproof(induction n)\n  case 0\n  then show ?case by(auto simp: nth_bit_def nat_to_bit_cases nth_bit_nat_is_right_shift)\nnext\n  case (Suc n)\n  then show ?case \n    apply(cases \"nth_carry n a b\")\n      by(auto simp: nth_bit_def nat_to_bit_cases nth_bit_nat_is_right_shift \n          a_mod_plus_b_mod[where ?n=\"Suc n\", simplified] algebra_simps split: if_splits)\nqed\n\nlemma first_bit_of_add: \"nth_bit (a + b) 0 \n  = (if nth_bit a 0 = One then if nth_bit b 0 = One then Zero else One \n     else if nth_bit b 0 = One then One else Zero)\" \n  apply(auto simp: nth_bit_def nat_to_bit_eq_One_iff nat_to_bit_eq_Zero_iff)\n  by presburger\n\nlemma nth_bit_of_add: \"nth_bit (a + b) (Suc n) = (let u = nth_bit a (Suc n); \n  v = nth_bit b (Suc n); w = nth_carry n a b in \n  (if u = One then \n    if v = One then\n     if w = One then One else Zero\n    else\n     if w = One then Zero else One\n   else\n    if v = One then\n     if w = One then Zero else One\n    else\n     if w = One then One else Zero))\"\n  apply(auto simp: Let_def nth_bit_def nth_bit_nat_is_right_shift nat_to_bit_cases nth_carry_mod)\n  by (metis div_add1_eq even_add even_iff_mod_2_eq_zero not_mod2_eq_Suc_0_eq_0)+\n\nlemma no_overflow_condition: \"a + b < 2 ^ n \\<Longrightarrow> nth_carry (n - 1) a b = Zero\" \n  apply(cases n)\n  by(auto simp: nth_carry_mod nth_bit_def nth_bit_nat_is_right_shift nat_to_bit_cases)\n\nlemma has_bit_one_then_greater_zero: \"nth_bit a j = One \\<Longrightarrow> 0 < a\" \n  apply(auto simp: nth_bit_def nth_bit_nat_is_right_shift nat_to_bit_cases)\n  by (metis One_nat_def div_less dvd_0_right even_mod_2_iff gr_zeroI less_2_cases_iff \n      odd_one zero_less_power)\n\nlemma greater_zero_then_has_bit_one: \"x > 0 \\<Longrightarrow> x < 2 ^ n \\<Longrightarrow> \\<exists>b \\<in> {0..<n}. nth_bit x b = One\" \nproof(rule ccontr)\n  assume \"x > 0\" \"x < 2 ^ n\" \"\\<not> (\\<exists>b\\<in>{0..<n}. nth_bit x b = One)\" \n  hence \"(\\<forall>b. nth_bit x b = Zero) \\<or> (\\<exists>b \\<ge> n. nth_bit x b = One)\" by auto\n  thus False \n  proof(elim disjE)\n    assume \"\\<forall>b. nth_bit x b = Zero\"\n    hence \"nth_bit x (Discrete.log x) = Zero\" by auto\n    moreover have \"x div 2 ^ Discrete.log x = 1\" \n      using Discrete.log_exp2_gt log_exp2_le[OF \\<open>x > 0\\<close>]\n      by (metis Euclidean_Division.div_eq_0_iff One_nat_def leD less_2_cases_iff \n          less_mult_imp_div_less power_not_zero zero_neq_numeral)\n    ultimately show False by(auto simp: nth_bit_def nth_bit_nat_is_right_shift nat_to_bit_cases)\n  next \n    assume \"\\<exists>b \\<ge> n. nth_bit x b = One\"\n    then obtain b where \"b \\<ge> n \\<and> nth_bit x b = One\" by blast\n    thus False using \\<open>x < 2 ^ n\\<close> \n      apply(auto simp: nth_bit_def nth_bit_nat_is_right_shift nat_to_bit_cases)\n      by (metis div_greater_zero_iff gr0I leD le_less_trans less_2_cases_iff less_Suc0 \n          mod_less_eq_dividend nat_power_less_imp_less)\n  qed\nqed   \n\nfun nth_carry_sub:: \"nat \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> bit\" where\n\"nth_carry_sub 0 a b = (if (nth_bit a 0 = Zero \\<and> nth_bit b 0 = One) then One else Zero)\" | \n\"nth_carry_sub (Suc n) a b = \n  (if (nth_bit a (Suc n) = Zero \\<and> ( nth_bit b (Suc n) = One \\<or> nth_carry_sub n a b = One))\n    \\<or> (nth_bit a (Suc n) = One \\<and> (nth_bit b (Suc n)) = One \\<and> nth_carry_sub n a b = One) then One\n  else Zero)\"\n\nlemma a_mod_less_b_mod_iff: \"(a :: nat) mod (2 * 2 ^ n) < b mod (2 * 2 ^ n)\n  \\<longleftrightarrow> ((a div 2 ^ n mod 2 < b div 2 ^ n mod 2) \n        \\<or> (a div 2 ^ n mod 2 = b div 2 ^ n mod 2 \\<and> a mod 2 ^ n < b mod 2 ^ n))\" \n  apply(auto simp: algebra_simps a_mod_2_to_the_n_decomposition)\n    apply (smt add.right_neutral add_self_div_2 le_less_trans le_simps(1) less_Suc0 mod_less_divisor \n      mult_0_right mult_numeral_1_right not_add_less2 not_mod_2_eq_0_eq_1 numeral_2_eq_2 \n      numeral_Bit0_div_2 plus_1_eq_Suc pos2 zero_less_power)\n   apply (metis (no_types, lifting) One_nat_def add.right_neutral add_lessD1 add_less_cancel_right \n      less_Suc0 mult_0_right not_mod_2_eq_0_eq_1)\n  by (smt add.commute add.right_neutral add_self_div_2 mod_less_divisor mult_0_right \n      mult_numeral_1_right not_add_less2 not_mod_2_eq_0_eq_1 numeral_2_eq_2 \n      numeral_Bit0_div_2 plus_1_eq_Suc trans_less_add2 zero_less_power)\n\nlemma nth_carry_sub_mod: \"nth_carry_sub n a b = \n (if (a mod 2 ^ Suc n) < (b mod 2 ^ Suc n) then One else Zero)\" \nproof(induction n)\n  case 0\n  then show ?case by(auto simp: nth_bit_def nat_to_bit_cases nth_bit_nat_is_right_shift)\nnext\n  case (Suc n)\n  then show ?case \n    apply(cases \"nth_carry_sub n a b\")\n    by(auto simp: nth_bit_def nat_to_bit_cases nth_bit_nat_is_right_shift \n        a_mod_less_b_mod_iff[where ?n=\"Suc n\", simplified] algebra_simps split: if_splits)\nqed\n\nlemma first_bit_of_sub_n_no_underflow: \"a \\<ge> b \\<Longrightarrow> nth_bit (a - b) 0 = (if nth_bit a 0 = One then\n  (if nth_bit b 0 = One then Zero else One)\n  else (if nth_bit b 0 = One then One else Zero))\" \n  apply(auto simp: nth_bit_def nat_to_bit_eq_One_iff nat_to_bit_eq_Zero_iff)\n  by presburger+\n\nlemma a_times_n_minus_one_div_n: \"n > 0 \\<Longrightarrow> ((a :: nat) * n - 1) div n = a - 1\" \nproof(induction a)\n  case (Suc a)\n  then show ?case using Suc\n  proof(cases a)\n    case (Suc nat)\n    hence \"((Suc a) * n - 1) div n = (n + (a * n - 1)) div n\" \n      using Suc.prems by auto\n    also have \"... = 1 + (a * n - 1) div n\" using Suc by (simp add: Suc.prems)\n    finally show ?thesis using Suc  using Suc.IH Suc.prems by auto\n  qed auto\nqed auto\n\nlemma a_times_n_minus_n_minus_one_div_n: \"n > 1 \\<Longrightarrow> ((a :: nat) * n - (n - 1)) div n = a - 1\"\nproof(induction a)\n  case (Suc a)\n  then show ?case using Suc\n  proof(cases a)\n    case (Suc nat)\n    hence \"((Suc a) * n - (n - 1)) div n = (n + (a * n - (n - 1))) div n\" \n      using Suc.prems by auto\n    also have \"... = 1 + (a * n - (n - 1)) div n\" using Suc.prems div_geq by auto\n    finally show ?thesis using Suc  using Suc.IH Suc.prems by auto\n  qed auto\nqed auto\n\nlemma a_plus_b_minus_c_mod:\n  assumes \"n > 1\" \n  shows \"((a :: nat) * n + b mod n - c mod n) div n \n    = a - (if b mod n < c mod n then 1 else 0)\" \nproof(cases \"b mod n < c mod n\")\n  case True\n  hence \"(a * n + b mod n - c mod n) div n \\<le> (a * n - 1) div n\" by(auto intro: div_le_mono)\n  hence \"(a * n + b mod n - c mod n) div n \\<le> a - 1\" using \\<open>n > 1\\<close> a_times_n_minus_one_div_n by simp\n  have \"(a * n + b mod n - c mod n) div n \\<ge> (a * n + b mod n - (n - 1)) div n\" \n    apply(rule div_le_mono)\n    apply(rule diff_le_mono2)\n    using  mod_less_divisor[where ?n=n] \\<open>n > 1\\<close> \n    by (metis One_nat_def Suc_pred le_less_trans less_Suc_eq_le zero_le_one)\n  moreover have \"(a * n + b mod n - (n - 1)) div n \\<ge> (a * n - (n - 1)) div n\" \n    using div_le_mono by simp\n  ultimately have \"(a * n + b mod n - c mod n) div n \\<ge> a - 1\" \n    using a_times_n_minus_n_minus_one_div_n[OF \\<open>n > 1\\<close>] by simp\n  show ?thesis using \\<open>(a * n + b mod n - c mod n) div n \\<le> a - 1\\<close>\n    \\<open>(a * n + b mod n - c mod n) div n \\<ge> a - 1\\<close> using True le_antisym by presburger\nnext\n  case False\n  hence \"(a * n + b mod n - c mod n) div n = (a * n + (b mod n - c mod n)) div n\" by simp\n  hence \"(a * n + b mod n - c mod n) div n = a + (b mod n - c mod n) div n\" using \\<open>n > 1\\<close> by auto\n  thus ?thesis using \\<open>\\<not> b mod n < c mod n\\<close>\n    by (metis (mono_tags, lifting) Euclidean_Division.div_eq_0_iff add_cancel_left_right diff_zero \n        less_imp_diff_less mod_less_divisor neq0_conv)\nqed\n\nlemma a_minus_b_shift_right: \"(a - b) div 2 ^ Suc n = (a :: nat) div 2 ^ Suc n - b div 2 ^ Suc n \n  - (if a mod 2 ^ Suc n < b mod 2 ^ Suc n then 1 else 0)\"\nproof -\n  have \"1 < (2 :: nat) ^ Suc n\" \n    using one_less_numeral_iff power_gt1 semiring_norm(76) by blast\n   have *: \"(a - b) div (2 ^ Suc n) = (((a div (2 * 2 ^ n)) * 2 * 2 ^ n + a mod (2 * 2 ^ n))\n        - ((b div (2 * 2 ^ n)) * 2 * 2 ^ n + b mod (2 * 2 ^ n))) div (2 * 2 ^ n)\"\n     by (simp add: div_mult_mod_eq mult.assoc)\n   show ?thesis \n   proof(cases \"(a div (2 * 2 ^ n)) * 2 * 2 ^ n \\<ge> (b div (2 * 2 ^ n)) * 2 * 2 ^ n\")\n     case True\n     hence \"(a - b) div (2 ^ Suc n) \n        = (((a div (2 * 2 ^ n)) - (b div (2 * 2 ^ n))) * (2 * 2 ^ n)\n          + a mod (2 * 2 ^ n) - b mod (2 * 2 ^ n))  div (2 * 2 ^ n)\"\n       using \"*\" by(auto simp: algebra_simps)\n     then show ?thesis \n       using a_plus_b_minus_c_mod[OF \\<open>1 < (2 :: nat) ^ Suc n\\<close>, where \n           ?a=\"(a div (2 * 2 ^ n)) - (b div (2 * 2 ^ n))\" and ?b=a and ?c=b, simplified]\n       by(auto)\n  next\n    case False\n    hence \"a < b\"\n      by (metis div_le_mono le_neq_implies_less mult_le_mono1 nat_le_linear)\n    thus ?thesis using False by auto\n  qed\nqed\n\nlemma a_minus_b_mod2: \"(a :: nat) \\<ge> b \\<Longrightarrow> (a - b) mod 2 = (if a mod 2 = 0 then\n  (if b mod 2 = 0 then 0 else 1)\n else \n  (if b mod 2 = 0 then 1 else 0))\" \n  by presburger\n\nlemma a_le_b_but_a_mod_greater_b_mod_then: \"a \\<ge> b \\<Longrightarrow> a mod n < b mod n\n  \\<Longrightarrow> a div n \\<ge> Suc (b div n)\" \nproof(rule ccontr)\n  assume\"a \\<ge> b\" \"a mod n < b mod n\" \"\\<not> (a div n \\<ge> Suc (b div n))\"\n  hence \"a = a div n * n + a mod n\" by auto\n  hence \"a < a div n * n + b mod n\" using \\<open>a mod n < b mod n\\<close> by linarith\n  moreover have \"a div n * n \\<le> b div n * n\" using \\<open>\\<not> (a div n \\<ge> Suc (b div n))\\<close> by simp\n  ultimately have \"a < b div n * n + b mod n\" by linarith\n  also have \"... = b\" by simp\n  finally show False using \\<open>a \\<ge> b\\<close> by simp\nqed\n\nlemma nth_bit_of_sub_n_no_underflow: \"a \\<ge> b \\<Longrightarrow> \n  nth_bit (a - b) (Suc n) = (let an = nth_bit a (Suc n); bn = nth_bit b (Suc n);\n  c = nth_carry_sub n a b in \n  (if an = One then \n    (if bn = One then \n      (if c = One then One else Zero)\n     else \n      (if c = One then Zero else One))\n  else \n    (if bn = One then \n      (if c = One then Zero else One)\n     else \n      (if c = One then One else Zero))))\" \n  apply(auto simp: Let_def nth_bit_def nth_bit_nat_is_right_shift nat_to_bit_cases \n      a_minus_b_shift_right[simplified] nth_carry_sub_mod a_minus_b_mod2[OF div_le_mono] \n      a_minus_b_mod2[OF a_le_b_but_a_mod_greater_b_mod_then] split: if_splits)\n  by (metis dvd_imp_mod_0 even_Suc)+\n  \n\nlemma nth_bit_of_sub_n_underflow: \"a < b \\<Longrightarrow> \n  nth_bit (a - b) (Suc n) = Zero\" \n  by simp\n\nlemma nth_carry_sub_underflow: \"a < b \\<Longrightarrow> a < 2 ^ n \\<Longrightarrow> b < 2 ^ n \n  \\<Longrightarrow> nth_carry_sub (n - 1) (2^n + a) b = One\" \n  apply(cases n)\n  by(auto simp: nth_carry_sub_mod)\n\nlemma nth_carry_sub_no_underflow: \"a \\<ge> b \\<Longrightarrow> a < 2 ^ n \\<Longrightarrow> b < 2 ^ n \n  \\<Longrightarrow> nth_carry_sub (n - 1) a b = Zero\" \n  by (smt bit_neq_zero_iff le_add_diff_inverse no_overflow_condition nth_bit_of_add \n      nth_bit_of_sub_n_no_underflow)\n\nlemma div2_is_right_shift: \"nth_bit (x div 2) n = nth_bit x (Suc n)\" \n  by(auto simp: nth_bit_def)\n\nfun bit_list_to_nat:: \"bit list \\<Rightarrow> nat\" where\n\"bit_list_to_nat [] = 0\" |\n\"bit_list_to_nat (x # xs) = (case x of Zero \\<Rightarrow> 2 * bit_list_to_nat xs |\n  One \\<Rightarrow> 1 + 2 * bit_list_to_nat xs)\" \n\nlemma bit_list_to_nat_right_shift: \"(bit_list_to_nat l) div 2 ^ n \n  = (bit_list_to_nat (drop n l))\" \nproof(induction l arbitrary: n)\n  case (Cons a l)\n  then show ?case\n     apply(cases n)\n     apply(auto split: bit.splits)\n    by (simp add: div_mult2_eq)\nqed simp\n\nlemma bit_list_to_nat_mod2: \"bit_list_to_nat l mod 2 = (if l = [] then 0 else \n  (if hd l = Zero then 0 else 1))\" \n  apply(cases l)\n  by auto\n\nlemma nth_bit_of_bit_list_to_nat[simp]: \"nth_bit (bit_list_to_nat l) k \n  = (if k < length l then l ! k else Zero)\" \n    apply(cases \"nat_to_bit (2 * bit_list_to_nat l div 2 ^ k mod 2)\")\n  by(auto simp: nth_bit_def nth_bit_nat_is_right_shift nat_to_bit_cases \n        bit_list_to_nat_right_shift bit_list_to_nat_mod2 hd_drop_conv_nth\n        split: bit.splits if_splits)\n\nlemma nth_bit_to_nat_greater_zero_then_has_bit_greater_zero: \n  assumes \"bit_list_to_nat l > 0\"\n  shows \"\\<exists>i < length l. l ! i = One\" \n  using assms \nproof(induction l)\n  case (Cons a l)\n  then show ?case\n  proof(cases a)\n    case Zero\n    hence \"bit_list_to_nat l > 0\" using Cons by simp\n    show ?thesis using Cons.IH[OF \\<open>bit_list_to_nat l > 0\\<close>] by auto\n  qed auto\nqed auto\n\nlemma bit_list_to_nat_geq_two_to_the_k_then: \"bit_list_to_nat l \\<ge> 2 ^ k\n  \\<Longrightarrow> (\\<exists>i. k \\<le> i \\<and> i < length l \\<and> l ! i = One)\" \nproof-\n  assume \"bit_list_to_nat l \\<ge> 2 ^ k\" \n  hence \"(bit_list_to_nat l) div 2 ^ k \\<ge> 1\" by (simp add: Suc_leI div_greater_zero_iff) \n  hence \"bit_list_to_nat (drop k l) \\<ge> 1\" using bit_list_to_nat_right_shift by simp\n  then obtain i where \"i < length (drop k l) \\<and> (drop k l) ! i = One\" \n    using nth_bit_to_nat_greater_zero_then_has_bit_greater_zero by force\n  hence \"k \\<le> (k + i) \\<and> k + i < length l \\<and> l ! (k + i) = One\" by auto\n  thus ?thesis by blast\nqed\n\nlemma not_One_then_has_bit_one_at_higher_position: \"x \\<noteq> Num.One \n  \\<Longrightarrow> (\\<exists>i > 0. nth_bit_of_num x i = One)\" \nproof(induction x)\n  case One\n  then show ?case by auto\nnext\n  case (Bit0 x)\n  then show ?case by (cases x) auto\nnext\n  case (Bit1 x)\n  then show ?case by (cases x) auto\nqed\n\n\nlemma num_unequal_then_has_unequal_bit: \"x \\<noteq> y \n  \\<Longrightarrow> (\\<exists>i. nth_bit_of_num x i \\<noteq> nth_bit_of_num y i)\" \nproof(induction x arbitrary: y)\n  case One\n  hence \"y \\<noteq> Num.One\" by simp\n  then obtain i where \"i > 0 \\<and> nth_bit_of_num y i = One\" \n    using not_One_then_has_bit_one_at_higher_position by auto\n  moreover hence \"nth_bit_of_num Num.One i = Zero\" using gr0_implies_Suc nth_bit_of_num.simps by blast\n  ultimately show ?case by (metis bit.simps)\nnext\n  case (Bit0 x)\n  then show ?case \n  proof(cases y)\n    case One\n    then obtain i where \"i > 0 \\<and> nth_bit_of_num (Num.Bit0 x) i = One\" \n      using not_One_then_has_bit_one_at_higher_position by auto\n    moreover hence \"nth_bit_of_num Num.One i = Zero\" using gr0_implies_Suc nth_bit_of_num.simps by blast\n    ultimately show ?thesis using One by (metis bit.simps)\n  next\n    case (Bit0 x2)\n    hence \"x \\<noteq> x2\" using \\<open>num.Bit0 x \\<noteq> y\\<close> by simp\n    then obtain i where \"nth_bit_of_num x i \\<noteq> nth_bit_of_num x2 i\" using Bit0.IH[OF \\<open>x \\<noteq> x2\\<close>] by blast\n    hence \"nth_bit_of_num (num.Bit0 x) (Suc i) \\<noteq> nth_bit_of_num (num.Bit0 x2) (Suc i)\" by simp\n    then show ?thesis using \\<open>y = num.Bit0 x2\\<close> by blast\n  next\n    case (Bit1 x3)\n    then show ?thesis by (metis bit.simps nth_bit_of_num.simps nth_bit_of_num.simps)\n  qed\nnext\n  case (Bit1 x)\n  then show ?case \n  proof(cases y)\n    case One\n    then obtain i where \"i > 0 \\<and> nth_bit_of_num (Num.Bit1 x) i = One\" \n      using not_One_then_has_bit_one_at_higher_position by auto\n    moreover hence \"nth_bit_of_num Num.One i = Zero\" using gr0_implies_Suc nth_bit_of_num.simps by blast\n    ultimately show ?thesis using One by (metis bit.simps)\n  next\n    case (Bit0 x2)\n    then show ?thesis by (metis bit.simps nth_bit_of_num.simps nth_bit_of_num.simps)\n  next\n    case (Bit1 x3)\n    hence \"x \\<noteq> x3\" using \\<open>num.Bit1 x \\<noteq> y\\<close> by simp\n    then obtain i where \"nth_bit_of_num x i \\<noteq> nth_bit_of_num x3 i\" using Bit1.IH[OF \\<open>x \\<noteq> x3\\<close>] by blast\n    hence \"nth_bit_of_num (num.Bit1 x) (Suc i) \\<noteq> nth_bit_of_num (num.Bit1 x3) (Suc i)\" by simp\n    then show ?thesis using \\<open>y = num.Bit1 x3\\<close> by blast\n  qed\nqed\n\nlemma all_bits_equal_then_equal: \"x < 2 ^ n \\<Longrightarrow> y < 2 ^ n \\<Longrightarrow> (\\<forall>i < n. nth_bit x i = nth_bit y i) \n  \\<Longrightarrow> x = y\"\nproof(rule ccontr)\n  assume \"x < 2 ^ n\" \"y < 2 ^ n\" \"(\\<forall>i < n. nth_bit x i = nth_bit y i)\"\n  hence \"i > n \\<longrightarrow> x div 2 ^ i = 0\" \"i > n \\<longrightarrow> y div 2 ^ i = 0\" for i\n    by (meson div_greater_zero_iff gr0I le_less_trans nat_power_less_imp_less order.asym pos2)+\n  hence all_bits_equal: \"nth_bit x i = nth_bit y i\" for i \n    apply(cases \"i < n\")\n    using \\<open>\\<forall>i < n. nth_bit x i = nth_bit y i\\<close> \n     apply(auto simp add: nth_bit_def nth_bit_nat_is_right_shift)\n    by (metis \\<open>x < 2 ^ n\\<close> \\<open>y < 2 ^ n\\<close> div_less linorder_neqE_nat)\n  assume \"x \\<noteq> y\"\n  have \"x \\<noteq> 0\" apply - apply(rule ccontr) \n    using \\<open>x \\<noteq> y\\<close> all_bits_equal greater_zero_then_has_bit_one[OF _ \\<open>y < 2 ^ n\\<close>] by auto\n  have \"y \\<noteq> 0\" apply - apply(rule ccontr) \n    using \\<open>x \\<noteq> y\\<close> all_bits_equal greater_zero_then_has_bit_one[OF _ \\<open>x < 2 ^ n\\<close>] by auto\n  have \"num_of_nat x \\<noteq> num_of_nat y\" \n  proof (rule ccontr)\n    assume \"\\<not>(num_of_nat x \\<noteq> num_of_nat y)\"\n    hence \"nat_of_num (num_of_nat x) = nat_of_num (num_of_nat y)\" by simp\n    hence \"x = y\" using \\<open>x \\<noteq> 0\\<close> \\<open>y \\<noteq> 0\\<close> num_of_nat_inverse by auto\n    thus False using \\<open>x \\<noteq> y\\<close> by blast\n  qed\n  then obtain i where \"nth_bit_of_num (num_of_nat x) i \\<noteq> nth_bit_of_num (num_of_nat y) i\"\n    using num_unequal_then_has_unequal_bit by auto\n  hence \"nth_bit x i \\<noteq> nth_bit y i\" using \\<open>x \\<noteq> 0\\<close> \\<open>y \\<noteq> 0\\<close>\n    by(auto simp: nth_bit_is_nth_bit_of_num)\n  thus False using all_bits_equal by blast\nqed\n\nlemma bit_list_to_nat_less_2_to_the_length: \"bit_list_to_nat l < 2 ^ length l\"\n  apply(rule ccontr)\n  using bit_list_to_nat_geq_two_to_the_k_then using not_less by blast\n\nlemma bit_list_to_nat_eq_nat_iff: \"bit_list_to_nat l = y \\<longleftrightarrow> (y < 2 ^ length l \\<and>\n  (\\<forall>i < length l. l ! i = nth_bit y i))\"\nproof\n  assume \"bit_list_to_nat l = y\" \n  hence \"y = bit_list_to_nat l\" by simp\n  hence \"y div 2 ^ length l = 0\" by(simp add: \\<open>y = bit_list_to_nat l\\<close> bit_list_to_nat_right_shift)\n  hence \"y < 2 ^ length l\" by (simp add: Euclidean_Division.div_eq_0_iff)\n  thus \"y < 2 ^ length l \\<and> (\\<forall>i < length l. l ! i = nth_bit y i)\"  \n    by(simp add: \\<open>y = bit_list_to_nat l\\<close>)\nnext\n  assume \"y < 2 ^ length l \\<and> (\\<forall>i < length l. l ! i = nth_bit y i)\"\n  thus \"bit_list_to_nat l = y\"\n    apply - apply(rule all_bits_equal_then_equal[where ?n=\"length l\"])\n    using bit_list_to_nat_less_2_to_the_length by auto\nqed\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 mod_2_of_zero_is_zero_intro: \"x = (0 :: nat) \\<Longrightarrow> x mod 2 = 0\" by auto \n\nlemma bit_geq_bit_length_is_Zero: \"i \\<ge> bit_length x \\<Longrightarrow> nth_bit x i = Zero\" \n  apply(auto simp: nth_bit_def nat_to_bit_cases nth_bit_nat_is_right_shift bit_length_def)\n  apply(rule mod_2_of_zero_is_zero_intro)\n  by (metis div_less leI log_exp log_mono monoD not_less_eq_eq)\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/Cook_Levin/IMP-_To_SAS+/IMP-_To_IMP--/Binary_Arithmetic.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8872045937171068, "lm_q2_score": 0.8376199673867852, "lm_q1q2_score": 0.743140282854729}}
{"text": "(*  Title       : Deriv.thy\n    Author      : Jacques D. Fleuriot\n    Copyright   : 1998  University of Cambridge\n    Author      : Brian Huffman\n    Conversion to Isar and new proofs by Lawrence C Paulson, 2004\n    GMVT by Benjamin Porter, 2005\n*)\n\nsection{* Differentiation *}\n\ntheory Deriv\nimports Limits\nbegin\n\nsubsection {* Frechet derivative *}\n\ndefinition\n  has_derivative :: \"('a::real_normed_vector \\<Rightarrow> 'b::real_normed_vector) \\<Rightarrow> ('a \\<Rightarrow> 'b) \\<Rightarrow> 'a filter \\<Rightarrow>  bool\"\n  (infix \"(has'_derivative)\" 50)\nwhere\n  \"(f has_derivative f') F \\<longleftrightarrow>\n    (bounded_linear f' \\<and>\n     ((\\<lambda>y. ((f y - f (Lim F (\\<lambda>x. x))) - f' (y - Lim F (\\<lambda>x. x))) /\\<^sub>R norm (y - Lim F (\\<lambda>x. x))) ---> 0) F)\"\n\ntext {*\n  Usually the filter @{term F} is @{term \"at x within s\"}.  @{term \"(f has_derivative D)\n  (at x within s)\"} means: @{term D} is the derivative of function @{term f} at point @{term x}\n  within the set @{term s}. Where @{term s} is used to express left or right sided derivatives. In\n  most cases @{term s} is either a variable or @{term UNIV}.\n*}\n\nlemma has_derivative_eq_rhs: \"(f has_derivative f') F \\<Longrightarrow> f' = g' \\<Longrightarrow> (f has_derivative g') F\"\n  by simp\n\ndefinition \n  has_field_derivative :: \"('a::real_normed_field \\<Rightarrow> 'a) \\<Rightarrow> 'a \\<Rightarrow> 'a filter \\<Rightarrow> bool\"\n  (infix \"(has'_field'_derivative)\" 50)\nwhere\n  \"(f has_field_derivative D) F \\<longleftrightarrow> (f has_derivative op * D) F\"\n\nlemma DERIV_cong: \"(f has_field_derivative X) F \\<Longrightarrow> X = Y \\<Longrightarrow> (f has_field_derivative Y) F\"\n  by simp\n\ndefinition\n  has_vector_derivative :: \"(real \\<Rightarrow> 'b::real_normed_vector) \\<Rightarrow> 'b \\<Rightarrow> real filter \\<Rightarrow> bool\"\n  (infix \"has'_vector'_derivative\" 50)\nwhere\n  \"(f has_vector_derivative f') net \\<longleftrightarrow> (f has_derivative (\\<lambda>x. x *\\<^sub>R f')) net\"\n\nlemma has_vector_derivative_eq_rhs: \"(f has_vector_derivative X) F \\<Longrightarrow> X = Y \\<Longrightarrow> (f has_vector_derivative Y) F\"\n  by simp\n\nnamed_theorems derivative_intros \"structural introduction rules for derivatives\"\nsetup {*\n  let\n    val eq_thms = @{thms has_derivative_eq_rhs DERIV_cong has_vector_derivative_eq_rhs}\n    fun eq_rule thm = get_first (try (fn eq_thm => eq_thm OF [thm])) eq_thms\n  in\n    Global_Theory.add_thms_dynamic\n      (@{binding derivative_eq_intros},\n        fn context =>\n          Named_Theorems.get (Context.proof_of context) @{named_theorems derivative_intros}\n          |> map_filter eq_rule)\n  end;\n*}\n\ntext {*\n  The following syntax is only used as a legacy syntax.\n*}\nabbreviation (input)\n  FDERIV :: \"('a::real_normed_vector \\<Rightarrow> 'b::real_normed_vector) \\<Rightarrow> 'a \\<Rightarrow>  ('a \\<Rightarrow> 'b) \\<Rightarrow> bool\"\n  (\"(FDERIV (_)/ (_)/ :> (_))\" [1000, 1000, 60] 60)\nwhere\n  \"FDERIV f x :> f' \\<equiv> (f has_derivative f') (at x)\"\n\nlemma has_derivative_bounded_linear: \"(f has_derivative f') F \\<Longrightarrow> bounded_linear f'\"\n  by (simp add: has_derivative_def)\n\nlemma has_derivative_linear: \"(f has_derivative f') F \\<Longrightarrow> linear f'\"\n  using bounded_linear.linear[OF has_derivative_bounded_linear] .\n\nlemma has_derivative_ident[derivative_intros, simp]: \"((\\<lambda>x. x) has_derivative (\\<lambda>x. x)) F\"\n  by (simp add: has_derivative_def)\n\nlemma has_derivative_const[derivative_intros, simp]: \"((\\<lambda>x. c) has_derivative (\\<lambda>x. 0)) F\"\n  by (simp add: has_derivative_def)\n\nlemma (in bounded_linear) bounded_linear: \"bounded_linear f\" ..\n\nlemma (in bounded_linear) has_derivative:\n  \"(g has_derivative g') F \\<Longrightarrow> ((\\<lambda>x. f (g x)) has_derivative (\\<lambda>x. f (g' x))) F\"\n  using assms unfolding has_derivative_def\n  apply safe\n  apply (erule bounded_linear_compose [OF bounded_linear])\n  apply (drule tendsto)\n  apply (simp add: scaleR diff add zero)\n  done\n\nlemmas has_derivative_scaleR_right [derivative_intros] =\n  bounded_linear.has_derivative [OF bounded_linear_scaleR_right]\n\nlemmas has_derivative_scaleR_left [derivative_intros] =\n  bounded_linear.has_derivative [OF bounded_linear_scaleR_left]\n\nlemmas has_derivative_mult_right [derivative_intros] =\n  bounded_linear.has_derivative [OF bounded_linear_mult_right]\n\nlemmas has_derivative_mult_left [derivative_intros] =\n  bounded_linear.has_derivative [OF bounded_linear_mult_left]\n\nlemma has_derivative_add[simp, derivative_intros]:\n  assumes f: \"(f has_derivative f') F\" and g: \"(g has_derivative g') F\"\n  shows \"((\\<lambda>x. f x + g x) has_derivative (\\<lambda>x. f' x + g' x)) F\"\n  unfolding has_derivative_def\nproof safe\n  let ?x = \"Lim F (\\<lambda>x. x)\"\n  let ?D = \"\\<lambda>f f' y. ((f y - f ?x) - f' (y - ?x)) /\\<^sub>R norm (y - ?x)\"\n  have \"((\\<lambda>x. ?D f f' x + ?D g g' x) ---> (0 + 0)) F\"\n    using f g by (intro tendsto_add) (auto simp: has_derivative_def)\n  then show \"(?D (\\<lambda>x. f x + g x) (\\<lambda>x. f' x + g' x) ---> 0) F\"\n    by (simp add: field_simps scaleR_add_right scaleR_diff_right)\nqed (blast intro: bounded_linear_add f g has_derivative_bounded_linear)\n\nlemma has_derivative_setsum[simp, derivative_intros]:\n  assumes f: \"\\<And>i. i \\<in> I \\<Longrightarrow> (f i has_derivative f' i) F\"\n  shows \"((\\<lambda>x. \\<Sum>i\\<in>I. f i x) has_derivative (\\<lambda>x. \\<Sum>i\\<in>I. f' i x)) F\"\nproof cases\n  assume \"finite I\" from this f show ?thesis\n    by induct (simp_all add: f)\nqed simp\n\nlemma has_derivative_minus[simp, derivative_intros]: \"(f has_derivative f') F \\<Longrightarrow> ((\\<lambda>x. - f x) has_derivative (\\<lambda>x. - f' x)) F\"\n  using has_derivative_scaleR_right[of f f' F \"-1\"] by simp\n\nlemma has_derivative_diff[simp, derivative_intros]:\n  \"(f has_derivative f') F \\<Longrightarrow> (g has_derivative g') F \\<Longrightarrow> ((\\<lambda>x. f x - g x) has_derivative (\\<lambda>x. f' x - g' x)) F\"\n  by (simp only: diff_conv_add_uminus has_derivative_add has_derivative_minus)\n\nlemma has_derivative_at_within:\n  \"(f has_derivative f') (at x within s) \\<longleftrightarrow>\n    (bounded_linear f' \\<and> ((\\<lambda>y. ((f y - f x) - f' (y - x)) /\\<^sub>R norm (y - x)) ---> 0) (at x within s))\"\n  by (cases \"at x within s = bot\") (simp_all add: has_derivative_def Lim_ident_at)\n\nlemma has_derivative_iff_norm:\n  \"(f has_derivative f') (at x within s) \\<longleftrightarrow>\n    (bounded_linear f' \\<and> ((\\<lambda>y. norm ((f y - f x) - f' (y - x)) / norm (y - x)) ---> 0) (at x within s))\"\n  using tendsto_norm_zero_iff[of _ \"at x within s\", where 'b=\"'b\", symmetric]\n  by (simp add: has_derivative_at_within divide_inverse ac_simps)\n\nlemma has_derivative_at:\n  \"(f has_derivative D) (at x) \\<longleftrightarrow> (bounded_linear D \\<and> (\\<lambda>h. norm (f (x + h) - f x - D h) / norm h) -- 0 --> 0)\"\n  unfolding has_derivative_iff_norm LIM_offset_zero_iff[of _ _ x] by simp\n\nlemma field_has_derivative_at:\n  fixes x :: \"'a::real_normed_field\"\n  shows \"(f has_derivative op * D) (at x) \\<longleftrightarrow> (\\<lambda>h. (f (x + h) - f x) / h) -- 0 --> D\"\n  apply (unfold has_derivative_at)\n  apply (simp add: bounded_linear_mult_right)\n  apply (simp cong: LIM_cong add: nonzero_norm_divide [symmetric])\n  apply (subst diff_divide_distrib)\n  apply (subst times_divide_eq_left [symmetric])\n  apply (simp cong: LIM_cong)\n  apply (simp add: tendsto_norm_zero_iff LIM_zero_iff)\n  done\n\nlemma has_derivativeI:\n  \"bounded_linear f' \\<Longrightarrow> ((\\<lambda>y. ((f y - f x) - f' (y - x)) /\\<^sub>R norm (y - x)) ---> 0) (at x within s) \\<Longrightarrow>\n  (f has_derivative f') (at x within s)\"\n  by (simp add: has_derivative_at_within)\n\nlemma has_derivativeI_sandwich:\n  assumes e: \"0 < e\" and bounded: \"bounded_linear f'\"\n    and sandwich: \"(\\<And>y. y \\<in> s \\<Longrightarrow> y \\<noteq> x \\<Longrightarrow> dist y x < e \\<Longrightarrow> norm ((f y - f x) - f' (y - x)) / norm (y - x) \\<le> H y)\"\n    and \"(H ---> 0) (at x within s)\"\n  shows \"(f has_derivative f') (at x within s)\"\n  unfolding has_derivative_iff_norm\nproof safe\n  show \"((\\<lambda>y. norm (f y - f x - f' (y - x)) / norm (y - x)) ---> 0) (at x within s)\"\n  proof (rule tendsto_sandwich[where f=\"\\<lambda>x. 0\"])\n    show \"(H ---> 0) (at x within s)\" by fact\n    show \"eventually (\\<lambda>n. norm (f n - f x - f' (n - x)) / norm (n - x) \\<le> H n) (at x within s)\"\n      unfolding eventually_at using e sandwich by auto\n  qed (auto simp: le_divide_eq)\nqed fact\n\nlemma has_derivative_subset: \"(f has_derivative f') (at x within s) \\<Longrightarrow> t \\<subseteq> s \\<Longrightarrow> (f has_derivative f') (at x within t)\"\n  by (auto simp add: has_derivative_iff_norm intro: tendsto_within_subset)\n\nlemmas has_derivative_within_subset = has_derivative_subset \n\n\nsubsection {* Continuity *}\n\nlemma has_derivative_continuous:\n  assumes f: \"(f has_derivative f') (at x within s)\"\n  shows \"continuous (at x within s) f\"\nproof -\n  from f interpret F: bounded_linear f' by (rule has_derivative_bounded_linear)\n  note F.tendsto[tendsto_intros]\n  let ?L = \"\\<lambda>f. (f ---> 0) (at x within s)\"\n  have \"?L (\\<lambda>y. norm ((f y - f x) - f' (y - x)) / norm (y - x))\"\n    using f unfolding has_derivative_iff_norm by blast\n  then have \"?L (\\<lambda>y. norm ((f y - f x) - f' (y - x)) / norm (y - x) * norm (y - x))\" (is ?m)\n    by (rule tendsto_mult_zero) (auto intro!: tendsto_eq_intros)\n  also have \"?m \\<longleftrightarrow> ?L (\\<lambda>y. norm ((f y - f x) - f' (y - x)))\"\n    by (intro filterlim_cong) (simp_all add: eventually_at_filter)\n  finally have \"?L (\\<lambda>y. (f y - f x) - f' (y - x))\"\n    by (rule tendsto_norm_zero_cancel)\n  then have \"?L (\\<lambda>y. ((f y - f x) - f' (y - x)) + f' (y - x))\"\n    by (rule tendsto_eq_intros) (auto intro!: tendsto_eq_intros simp: F.zero)\n  then have \"?L (\\<lambda>y. f y - f x)\"\n    by simp\n  from tendsto_add[OF this tendsto_const, of \"f x\"] show ?thesis\n    by (simp add: continuous_within)\nqed\n\nsubsection {* Composition *}\n\nlemma tendsto_at_iff_tendsto_nhds_within: \"f x = y \\<Longrightarrow> (f ---> y) (at x within s) \\<longleftrightarrow> (f ---> y) (inf (nhds x) (principal s))\"\n  unfolding tendsto_def eventually_inf_principal eventually_at_filter\n  by (intro ext all_cong imp_cong) (auto elim!: eventually_elim1)\n\nlemma has_derivative_in_compose:\n  assumes f: \"(f has_derivative f') (at x within s)\"\n  assumes g: \"(g has_derivative g') (at (f x) within (f`s))\"\n  shows \"((\\<lambda>x. g (f x)) has_derivative (\\<lambda>x. g' (f' x))) (at x within s)\"\nproof -\n  from f interpret F: bounded_linear f' by (rule has_derivative_bounded_linear)\n  from g interpret G: bounded_linear g' by (rule has_derivative_bounded_linear)\n  from F.bounded obtain kF where kF: \"\\<And>x. norm (f' x) \\<le> norm x * kF\" by fast\n  from G.bounded obtain kG where kG: \"\\<And>x. norm (g' x) \\<le> norm x * kG\" by fast\n  note G.tendsto[tendsto_intros]\n\n  let ?L = \"\\<lambda>f. (f ---> 0) (at x within s)\"\n  let ?D = \"\\<lambda>f f' x y. (f y - f x) - f' (y - x)\"\n  let ?N = \"\\<lambda>f f' x y. norm (?D f f' x y) / norm (y - x)\"\n  let ?gf = \"\\<lambda>x. g (f x)\" and ?gf' = \"\\<lambda>x. g' (f' x)\"\n  def Nf \\<equiv> \"?N f f' x\"\n  def Ng \\<equiv> \"\\<lambda>y. ?N g g' (f x) (f y)\"\n\n  show ?thesis\n  proof (rule has_derivativeI_sandwich[of 1])\n    show \"bounded_linear (\\<lambda>x. g' (f' x))\"\n      using f g by (blast intro: bounded_linear_compose has_derivative_bounded_linear)\n  next\n    fix y::'a assume neq: \"y \\<noteq> x\"\n    have \"?N ?gf ?gf' x y = norm (g' (?D f f' x y) + ?D g g' (f x) (f y)) / norm (y - x)\"\n      by (simp add: G.diff G.add field_simps)\n    also have \"\\<dots> \\<le> norm (g' (?D f f' x y)) / norm (y - x) + Ng y * (norm (f y - f x) / norm (y - x))\"\n      by (simp add: add_divide_distrib[symmetric] divide_right_mono norm_triangle_ineq G.zero Ng_def)\n    also have \"\\<dots> \\<le> Nf y * kG + Ng y * (Nf y + kF)\"\n    proof (intro add_mono mult_left_mono)\n      have \"norm (f y - f x) = norm (?D f f' x y + f' (y - x))\"\n        by simp\n      also have \"\\<dots> \\<le> norm (?D f f' x y) + norm (f' (y - x))\"\n        by (rule norm_triangle_ineq)\n      also have \"\\<dots> \\<le> norm (?D f f' x y) + norm (y - x) * kF\"\n        using kF by (intro add_mono) simp\n      finally show \"norm (f y - f x) / norm (y - x) \\<le> Nf y + kF\"\n        by (simp add: neq Nf_def field_simps)\n    qed (insert kG, simp_all add: Ng_def Nf_def neq zero_le_divide_iff field_simps)\n    finally show \"?N ?gf ?gf' x y \\<le> Nf y * kG + Ng y * (Nf y + kF)\" .\n  next\n    have [tendsto_intros]: \"?L Nf\"\n      using f unfolding has_derivative_iff_norm Nf_def ..\n    from f have \"(f ---> f x) (at x within s)\"\n      by (blast intro: has_derivative_continuous continuous_within[THEN iffD1])\n    then have f': \"LIM x at x within s. f x :> inf (nhds (f x)) (principal (f`s))\"\n      unfolding filterlim_def\n      by (simp add: eventually_filtermap eventually_at_filter le_principal)\n\n    have \"((?N g  g' (f x)) ---> 0) (at (f x) within f`s)\"\n      using g unfolding has_derivative_iff_norm ..\n    then have g': \"((?N g  g' (f x)) ---> 0) (inf (nhds (f x)) (principal (f`s)))\"\n      by (rule tendsto_at_iff_tendsto_nhds_within[THEN iffD1, rotated]) simp\n\n    have [tendsto_intros]: \"?L Ng\"\n      unfolding Ng_def by (rule filterlim_compose[OF g' f'])\n    show \"((\\<lambda>y. Nf y * kG + Ng y * (Nf y + kF)) ---> 0) (at x within s)\"\n      by (intro tendsto_eq_intros) auto\n  qed simp\nqed\n\nlemma has_derivative_compose:\n  \"(f has_derivative f') (at x within s) \\<Longrightarrow> (g has_derivative g') (at (f x)) \\<Longrightarrow>\n  ((\\<lambda>x. g (f x)) has_derivative (\\<lambda>x. g' (f' x))) (at x within s)\"\n  by (blast intro: has_derivative_in_compose has_derivative_subset)\n\nlemma (in bounded_bilinear) FDERIV:\n  assumes f: \"(f has_derivative f') (at x within s)\" and g: \"(g has_derivative g') (at x within s)\"\n  shows \"((\\<lambda>x. f x ** g x) has_derivative (\\<lambda>h. f x ** g' h + f' h ** g x)) (at x within s)\"\nproof -\n  from bounded_linear.bounded [OF has_derivative_bounded_linear [OF f]]\n  obtain KF where norm_F: \"\\<And>x. norm (f' x) \\<le> norm x * KF\" by fast\n\n  from pos_bounded obtain K where K: \"0 < K\" and norm_prod:\n    \"\\<And>a b. norm (a ** b) \\<le> norm a * norm b * K\" by fast\n  let ?D = \"\\<lambda>f f' y. f y - f x - f' (y - x)\"\n  let ?N = \"\\<lambda>f f' y. norm (?D f f' y) / norm (y - x)\"\n  def Ng ==\"?N g g'\" and Nf ==\"?N f f'\"\n\n  let ?fun1 = \"\\<lambda>y. norm (f y ** g y - f x ** g x - (f x ** g' (y - x) + f' (y - x) ** g x)) / norm (y - x)\"\n  let ?fun2 = \"\\<lambda>y. norm (f x) * Ng y * K + Nf y * norm (g y) * K + KF * norm (g y - g x) * K\"\n  let ?F = \"at x within s\"\n\n  show ?thesis\n  proof (rule has_derivativeI_sandwich[of 1])\n    show \"bounded_linear (\\<lambda>h. f x ** g' h + f' h ** g x)\"\n      by (intro bounded_linear_add\n        bounded_linear_compose [OF bounded_linear_right] bounded_linear_compose [OF bounded_linear_left]\n        has_derivative_bounded_linear [OF g] has_derivative_bounded_linear [OF f])\n  next\n    from g have \"(g ---> g x) ?F\"\n      by (intro continuous_within[THEN iffD1] has_derivative_continuous)\n    moreover from f g have \"(Nf ---> 0) ?F\" \"(Ng ---> 0) ?F\"\n      by (simp_all add: has_derivative_iff_norm Ng_def Nf_def)\n    ultimately have \"(?fun2 ---> norm (f x) * 0 * K + 0 * norm (g x) * K + KF * norm (0::'b) * K) ?F\"\n      by (intro tendsto_intros) (simp_all add: LIM_zero_iff)\n    then show \"(?fun2 ---> 0) ?F\"\n      by simp\n  next\n    fix y::'d assume \"y \\<noteq> x\"\n    have \"?fun1 y = norm (f x ** ?D g g' y + ?D f f' y ** g y + f' (y - x) ** (g y - g x)) / norm (y - x)\"\n      by (simp add: diff_left diff_right add_left add_right field_simps)\n    also have \"\\<dots> \\<le> (norm (f x) * norm (?D g g' y) * K + norm (?D f f' y) * norm (g y) * K +\n        norm (y - x) * KF * norm (g y - g x) * K) / norm (y - x)\"\n      by (intro divide_right_mono mult_mono'\n                order_trans [OF norm_triangle_ineq add_mono]\n                order_trans [OF norm_prod mult_right_mono]\n                mult_nonneg_nonneg order_refl norm_ge_zero norm_F\n                K [THEN order_less_imp_le])\n    also have \"\\<dots> = ?fun2 y\"\n      by (simp add: add_divide_distrib Ng_def Nf_def)\n    finally show \"?fun1 y \\<le> ?fun2 y\" .\n  qed simp\nqed\n\nlemmas has_derivative_mult[simp, derivative_intros] = bounded_bilinear.FDERIV[OF bounded_bilinear_mult]\nlemmas has_derivative_scaleR[simp, derivative_intros] = bounded_bilinear.FDERIV[OF bounded_bilinear_scaleR]\n\nlemma has_derivative_setprod[simp, derivative_intros]:\n  fixes f :: \"'i \\<Rightarrow> 'a :: real_normed_vector \\<Rightarrow> 'b :: real_normed_field\"\n  assumes f: \"\\<And>i. i \\<in> I \\<Longrightarrow> (f i has_derivative f' i) (at x within s)\"\n  shows \"((\\<lambda>x. \\<Prod>i\\<in>I. f i x) has_derivative (\\<lambda>y. \\<Sum>i\\<in>I. f' i y * (\\<Prod>j\\<in>I - {i}. f j x))) (at x within s)\"\nproof cases\n  assume \"finite I\" from this f show ?thesis\n  proof induct\n    case (insert i I)\n    let ?P = \"\\<lambda>y. f i x * (\\<Sum>i\\<in>I. f' i y * (\\<Prod>j\\<in>I - {i}. f j x)) + (f' i y) * (\\<Prod>i\\<in>I. f i x)\"\n    have \"((\\<lambda>x. f i x * (\\<Prod>i\\<in>I. f i x)) has_derivative ?P) (at x within s)\"\n      using insert by (intro has_derivative_mult) auto\n    also have \"?P = (\\<lambda>y. \\<Sum>i'\\<in>insert i I. f' i' y * (\\<Prod>j\\<in>insert i I - {i'}. f j x))\"\n      using insert(1,2) by (auto simp add: setsum_right_distrib insert_Diff_if intro!: ext setsum.cong)\n    finally show ?case\n      using insert by simp\n  qed simp  \nqed simp\n\nlemma has_derivative_power[simp, derivative_intros]:\n  fixes f :: \"'a :: real_normed_vector \\<Rightarrow> 'b :: real_normed_field\"\n  assumes f: \"(f has_derivative f') (at x within s)\"\n  shows \"((\\<lambda>x. f x^n) has_derivative (\\<lambda>y. of_nat n * f' y * f x^(n - 1))) (at x within s)\"\n  using has_derivative_setprod[OF f, of \"{..< n}\"] by (simp add: setprod_constant ac_simps)\n\nlemma has_derivative_inverse':\n  fixes x :: \"'a::real_normed_div_algebra\"\n  assumes x: \"x \\<noteq> 0\"\n  shows \"(inverse has_derivative (\\<lambda>h. - (inverse x * h * inverse x))) (at x within s)\"\n        (is \"(?inv has_derivative ?f) _\")\nproof (rule has_derivativeI_sandwich)\n  show \"bounded_linear (\\<lambda>h. - (?inv x * h * ?inv x))\"\n    apply (rule bounded_linear_minus)\n    apply (rule bounded_linear_mult_const)\n    apply (rule bounded_linear_const_mult)\n    apply (rule bounded_linear_ident)\n    done\nnext\n  show \"0 < norm x\" using x by simp\nnext\n  show \"((\\<lambda>y. norm (?inv y - ?inv x) * norm (?inv x)) ---> 0) (at x within s)\"\n    apply (rule tendsto_mult_left_zero)\n    apply (rule tendsto_norm_zero)\n    apply (rule LIM_zero)\n    apply (rule tendsto_inverse)\n    apply (rule tendsto_ident_at)\n    apply (rule x)\n    done\nnext\n  fix y::'a assume h: \"y \\<noteq> x\" \"dist y x < norm x\"\n  then have \"y \\<noteq> 0\"\n    by (auto simp: norm_conv_dist dist_commute)\n  have \"norm (?inv y - ?inv x - ?f (y -x)) / norm (y - x) = norm ((?inv y - ?inv x) * (y - x) * ?inv x) / norm (y - x)\"\n    apply (subst inverse_diff_inverse [OF `y \\<noteq> 0` x])\n    apply (subst minus_diff_minus)\n    apply (subst norm_minus_cancel)\n    apply (simp add: left_diff_distrib)\n    done\n  also have \"\\<dots> \\<le> norm (?inv y - ?inv x) * norm (y - x) * norm (?inv x) / norm (y - x)\"\n    apply (rule divide_right_mono [OF _ norm_ge_zero])\n    apply (rule order_trans [OF norm_mult_ineq])\n    apply (rule mult_right_mono [OF _ norm_ge_zero])\n    apply (rule norm_mult_ineq)\n    done\n  also have \"\\<dots> = norm (?inv y - ?inv x) * norm (?inv x)\"\n    by simp\n  finally show \"norm (?inv y - ?inv x - ?f (y -x)) / norm (y - x) \\<le>\n      norm (?inv y - ?inv x) * norm (?inv x)\" .\nqed\n\nlemma has_derivative_inverse[simp, derivative_intros]:\n  fixes f :: \"_ \\<Rightarrow> 'a::real_normed_div_algebra\"\n  assumes x:  \"f x \\<noteq> 0\" and f: \"(f has_derivative f') (at x within s)\"\n  shows \"((\\<lambda>x. inverse (f x)) has_derivative (\\<lambda>h. - (inverse (f x) * f' h * inverse (f x)))) (at x within s)\"\n  using has_derivative_compose[OF f has_derivative_inverse', OF x] .\n\nlemma has_derivative_divide[simp, derivative_intros]:\n  fixes f :: \"_ \\<Rightarrow> 'a::real_normed_div_algebra\"\n  assumes f: \"(f has_derivative f') (at x within s)\" and g: \"(g has_derivative g') (at x within s)\" \n  assumes x: \"g x \\<noteq> 0\"\n  shows \"((\\<lambda>x. f x / g x) has_derivative\n                (\\<lambda>h. - f x * (inverse (g x) * g' h * inverse (g x)) + f' h / g x)) (at x within s)\"\n  using has_derivative_mult[OF f has_derivative_inverse[OF x g]]\n  by (simp add: field_simps)\n\ntext{*Conventional form requires mult-AC laws. Types real and complex only.*}\n\nlemma has_derivative_divide'[derivative_intros]: \n  fixes f :: \"_ \\<Rightarrow> 'a::real_normed_field\"\n  assumes f: \"(f has_derivative f') (at x within s)\" and g: \"(g has_derivative g') (at x within s)\" and x: \"g x \\<noteq> 0\"\n  shows \"((\\<lambda>x. f x / g x) has_derivative (\\<lambda>h. (f' h * g x - f x * g' h) / (g x * g x))) (at x within s)\"\nproof -\n  { fix h\n    have \"f' h / g x - f x * (inverse (g x) * g' h * inverse (g x)) =\n          (f' h * g x - f x * g' h) / (g x * g x)\"\n      by (simp add: field_simps x)\n   }\n  then show ?thesis\n    using has_derivative_divide [OF f g] x\n    by simp\nqed\n\nsubsection {* Uniqueness *}\n\ntext {*\n\nThis can not generally shown for @{const has_derivative}, as we need to approach the point from\nall directions. There is a proof in @{text Multivariate_Analysis} for @{text euclidean_space}.\n\n*}\n\nlemma has_derivative_zero_unique:\n  assumes \"((\\<lambda>x. 0) has_derivative F) (at x)\" shows \"F = (\\<lambda>h. 0)\"\nproof -\n  interpret F: bounded_linear F\n    using assms by (rule has_derivative_bounded_linear)\n  let ?r = \"\\<lambda>h. norm (F h) / norm h\"\n  have *: \"?r -- 0 --> 0\"\n    using assms unfolding has_derivative_at by simp\n  show \"F = (\\<lambda>h. 0)\"\n  proof\n    fix h show \"F h = 0\"\n    proof (rule ccontr)\n      assume **: \"F h \\<noteq> 0\"\n      hence h: \"h \\<noteq> 0\" by (clarsimp simp add: F.zero)\n      with ** have \"0 < ?r h\" by simp\n      from LIM_D [OF * this] obtain s where s: \"0 < s\"\n        and r: \"\\<And>x. x \\<noteq> 0 \\<Longrightarrow> norm x < s \\<Longrightarrow> ?r x < ?r h\" by auto\n      from dense [OF s] obtain t where t: \"0 < t \\<and> t < s\" ..\n      let ?x = \"scaleR (t / norm h) h\"\n      have \"?x \\<noteq> 0\" and \"norm ?x < s\" using t h by simp_all\n      hence \"?r ?x < ?r h\" by (rule r)\n      thus \"False\" using t h by (simp add: F.scaleR)\n    qed\n  qed\nqed\n\nlemma has_derivative_unique:\n  assumes \"(f has_derivative F) (at x)\" and \"(f has_derivative F') (at x)\" shows \"F = F'\"\nproof -\n  have \"((\\<lambda>x. 0) has_derivative (\\<lambda>h. F h - F' h)) (at x)\"\n    using has_derivative_diff [OF assms] by simp\n  hence \"(\\<lambda>h. F h - F' h) = (\\<lambda>h. 0)\"\n    by (rule has_derivative_zero_unique)\n  thus \"F = F'\"\n    unfolding fun_eq_iff right_minus_eq .\nqed\n\nsubsection {* Differentiability predicate *}\n\ndefinition\n  differentiable :: \"('a::real_normed_vector \\<Rightarrow> 'b::real_normed_vector) \\<Rightarrow> 'a filter \\<Rightarrow> bool\"\n  (infix \"differentiable\" 50)\nwhere\n  \"f differentiable F \\<longleftrightarrow> (\\<exists>D. (f has_derivative D) F)\"\n\nlemma differentiable_subset: \"f differentiable (at x within s) \\<Longrightarrow> t \\<subseteq> s \\<Longrightarrow> f differentiable (at x within t)\"\n  unfolding differentiable_def by (blast intro: has_derivative_subset)\n\nlemmas differentiable_within_subset = differentiable_subset\n\nlemma differentiable_ident [simp, derivative_intros]: \"(\\<lambda>x. x) differentiable F\"\n  unfolding differentiable_def by (blast intro: has_derivative_ident)\n\nlemma differentiable_const [simp, derivative_intros]: \"(\\<lambda>z. a) differentiable F\"\n  unfolding differentiable_def by (blast intro: has_derivative_const)\n\nlemma differentiable_in_compose:\n  \"f differentiable (at (g x) within (g`s)) \\<Longrightarrow> g differentiable (at x within s) \\<Longrightarrow> (\\<lambda>x. f (g x)) differentiable (at x within s)\"\n  unfolding differentiable_def by (blast intro: has_derivative_in_compose)\n\nlemma differentiable_compose:\n  \"f differentiable (at (g x)) \\<Longrightarrow> g differentiable (at x within s) \\<Longrightarrow> (\\<lambda>x. f (g x)) differentiable (at x within s)\"\n  by (blast intro: differentiable_in_compose differentiable_subset)\n\nlemma differentiable_sum [simp, derivative_intros]:\n  \"f differentiable F \\<Longrightarrow> g differentiable F \\<Longrightarrow> (\\<lambda>x. f x + g x) differentiable F\"\n  unfolding differentiable_def by (blast intro: has_derivative_add)\n\nlemma differentiable_minus [simp, derivative_intros]:\n  \"f differentiable F \\<Longrightarrow> (\\<lambda>x. - f x) differentiable F\"\n  unfolding differentiable_def by (blast intro: has_derivative_minus)\n\nlemma differentiable_diff [simp, derivative_intros]:\n  \"f differentiable F \\<Longrightarrow> g differentiable F \\<Longrightarrow> (\\<lambda>x. f x - g x) differentiable F\"\n  unfolding differentiable_def by (blast intro: has_derivative_diff)\n\nlemma differentiable_mult [simp, derivative_intros]:\n  fixes f g :: \"'a :: real_normed_vector \\<Rightarrow> 'b :: real_normed_algebra\"\n  shows \"f differentiable (at x within s) \\<Longrightarrow> g differentiable (at x within s) \\<Longrightarrow> (\\<lambda>x. f x * g x) differentiable (at x within s)\"\n  unfolding differentiable_def by (blast intro: has_derivative_mult)\n\nlemma differentiable_inverse [simp, derivative_intros]:\n  fixes f :: \"'a :: real_normed_vector \\<Rightarrow> 'b :: real_normed_field\"\n  shows \"f differentiable (at x within s) \\<Longrightarrow> f x \\<noteq> 0 \\<Longrightarrow> (\\<lambda>x. inverse (f x)) differentiable (at x within s)\"\n  unfolding differentiable_def by (blast intro: has_derivative_inverse)\n\nlemma differentiable_divide [simp, derivative_intros]:\n  fixes f g :: \"'a :: real_normed_vector \\<Rightarrow> 'b :: real_normed_field\"\n  shows \"f differentiable (at x within s) \\<Longrightarrow> g differentiable (at x within s) \\<Longrightarrow> g x \\<noteq> 0 \\<Longrightarrow> (\\<lambda>x. f x / g x) differentiable (at x within s)\"\n  unfolding divide_inverse using assms by simp\n\nlemma differentiable_power [simp, derivative_intros]:\n  fixes f g :: \"'a :: real_normed_vector \\<Rightarrow> 'b :: real_normed_field\"\n  shows \"f differentiable (at x within s) \\<Longrightarrow> (\\<lambda>x. f x ^ n) differentiable (at x within s)\"\n  unfolding differentiable_def by (blast intro: has_derivative_power)\n\nlemma differentiable_scaleR [simp, derivative_intros]:\n  \"f differentiable (at x within s) \\<Longrightarrow> g differentiable (at x within s) \\<Longrightarrow> (\\<lambda>x. f x *\\<^sub>R g x) differentiable (at x within s)\"\n  unfolding differentiable_def by (blast intro: has_derivative_scaleR)\n\nlemma has_derivative_imp_has_field_derivative:\n  \"(f has_derivative D) F \\<Longrightarrow> (\\<And>x. x * D' = D x) \\<Longrightarrow> (f has_field_derivative D') F\"\n  unfolding has_field_derivative_def \n  by (rule has_derivative_eq_rhs[of f D]) (simp_all add: fun_eq_iff mult.commute)\n\nlemma has_field_derivative_imp_has_derivative: \"(f has_field_derivative D) F \\<Longrightarrow> (f has_derivative op * D) F\"\n  by (simp add: has_field_derivative_def)\n\nlemma DERIV_subset: \n  \"(f has_field_derivative f') (at x within s) \\<Longrightarrow> t \\<subseteq> s \n   \\<Longrightarrow> (f has_field_derivative f') (at x within t)\"\n  by (simp add: has_field_derivative_def has_derivative_within_subset)\n\nabbreviation (input)\n  DERIV :: \"('a::real_normed_field \\<Rightarrow> 'a) \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> bool\"\n  (\"(DERIV (_)/ (_)/ :> (_))\" [1000, 1000, 60] 60)\nwhere\n  \"DERIV f x :> D \\<equiv> (f has_field_derivative D) (at x)\"\n\nabbreviation \n  has_real_derivative :: \"(real \\<Rightarrow> real) \\<Rightarrow> real \\<Rightarrow> real filter \\<Rightarrow> bool\"\n  (infix \"(has'_real'_derivative)\" 50)\nwhere\n  \"(f has_real_derivative D) F \\<equiv> (f has_field_derivative D) F\"\n\nlemma real_differentiable_def:\n  \"f differentiable at x within s \\<longleftrightarrow> (\\<exists>D. (f has_real_derivative D) (at x within s))\"\nproof safe\n  assume \"f differentiable at x within s\"\n  then obtain f' where *: \"(f has_derivative f') (at x within s)\"\n    unfolding differentiable_def by auto\n  then obtain c where \"f' = (op * c)\"\n    by (metis real_bounded_linear has_derivative_bounded_linear mult.commute fun_eq_iff)\n  with * show \"\\<exists>D. (f has_real_derivative D) (at x within s)\"\n    unfolding has_field_derivative_def by auto\nqed (auto simp: differentiable_def has_field_derivative_def)\n\nlemma real_differentiableE [elim?]:\n  assumes f: \"f differentiable (at x within s)\" obtains df where \"(f has_real_derivative df) (at x within s)\"\n  using assms by (auto simp: real_differentiable_def)\n\nlemma differentiableD: \"f differentiable (at x within s) \\<Longrightarrow> \\<exists>D. (f has_real_derivative D) (at x within s)\"\n  by (auto elim: real_differentiableE)\n\nlemma differentiableI: \"(f has_real_derivative D) (at x within s) \\<Longrightarrow> f differentiable (at x within s)\"\n  by (force simp add: real_differentiable_def)\n\nlemma DERIV_def: \"DERIV f x :> D \\<longleftrightarrow> (\\<lambda>h. (f (x + h) - f x) / h) -- 0 --> D\"\n  apply (simp add: has_field_derivative_def has_derivative_at bounded_linear_mult_right LIM_zero_iff[symmetric, of _ D])\n  apply (subst (2) tendsto_norm_zero_iff[symmetric])\n  apply (rule filterlim_cong)\n  apply (simp_all add: eventually_at_filter field_simps nonzero_norm_divide)\n  done\n\nlemma mult_commute_abs: \"(\\<lambda>x. x * c) = op * (c::'a::ab_semigroup_mult)\"\n  by (simp add: fun_eq_iff mult.commute)\n\nsubsection {* Derivatives *}\n\nlemma DERIV_D: \"DERIV f x :> D \\<Longrightarrow> (\\<lambda>h. (f (x + h) - f x) / h) -- 0 --> D\"\n  by (simp add: DERIV_def)\n\nlemma DERIV_const [simp, derivative_intros]: \"((\\<lambda>x. k) has_field_derivative 0) F\"\n  by (rule has_derivative_imp_has_field_derivative[OF has_derivative_const]) auto\n\nlemma DERIV_ident [simp, derivative_intros]: \"((\\<lambda>x. x) has_field_derivative 1) F\"\n  by (rule has_derivative_imp_has_field_derivative[OF has_derivative_ident]) auto\n\nlemma field_differentiable_add[derivative_intros]:\n  \"(f has_field_derivative f') F \\<Longrightarrow> (g has_field_derivative g') F \\<Longrightarrow> \n    ((\\<lambda>z. f z + g z) has_field_derivative f' + g') F\"\n  by (rule has_derivative_imp_has_field_derivative[OF has_derivative_add])\n     (auto simp: has_field_derivative_def field_simps mult_commute_abs)\n\ncorollary DERIV_add:\n  \"(f has_field_derivative D) (at x within s) \\<Longrightarrow> (g has_field_derivative E) (at x within s) \\<Longrightarrow>\n  ((\\<lambda>x. f x + g x) has_field_derivative D + E) (at x within s)\"\n  by (rule field_differentiable_add)\n\nlemma field_differentiable_minus[derivative_intros]:\n  \"(f has_field_derivative f') F \\<Longrightarrow> ((\\<lambda>z. - (f z)) has_field_derivative -f') F\"\n  by (rule has_derivative_imp_has_field_derivative[OF has_derivative_minus])\n     (auto simp: has_field_derivative_def field_simps mult_commute_abs)\n\ncorollary DERIV_minus: \"(f has_field_derivative D) (at x within s) \\<Longrightarrow> ((\\<lambda>x. - f x) has_field_derivative -D) (at x within s)\"\n  by (rule field_differentiable_minus)\n\nlemma field_differentiable_diff[derivative_intros]:\n  \"(f has_field_derivative f') F \\<Longrightarrow> (g has_field_derivative g') F \\<Longrightarrow> ((\\<lambda>z. f z - g z) has_field_derivative f' - g') F\"\n  by (simp only: assms diff_conv_add_uminus field_differentiable_add field_differentiable_minus)\n\ncorollary DERIV_diff:\n  \"(f has_field_derivative D) (at x within s) \\<Longrightarrow> (g has_field_derivative E) (at x within s) \\<Longrightarrow>\n  ((\\<lambda>x. f x - g x) has_field_derivative D - E) (at x within s)\"\n  by (rule field_differentiable_diff)\n\nlemma DERIV_continuous: \"(f has_field_derivative D) (at x within s) \\<Longrightarrow> continuous (at x within s) f\"\n  by (drule has_derivative_continuous[OF has_field_derivative_imp_has_derivative]) simp\n\ncorollary DERIV_isCont: \"DERIV f x :> D \\<Longrightarrow> isCont f x\"\n  by (rule DERIV_continuous)\n\nlemma DERIV_continuous_on:\n  \"(\\<And>x. x \\<in> s \\<Longrightarrow> (f has_field_derivative D) (at x)) \\<Longrightarrow> continuous_on s f\"\n  by (metis DERIV_continuous continuous_at_imp_continuous_on)\n\nlemma DERIV_mult':\n  \"(f has_field_derivative D) (at x within s) \\<Longrightarrow> (g has_field_derivative E) (at x within s) \\<Longrightarrow>\n  ((\\<lambda>x. f x * g x) has_field_derivative f x * E + D * g x) (at x within s)\"\n  by (rule has_derivative_imp_has_field_derivative[OF has_derivative_mult])\n     (auto simp: field_simps mult_commute_abs dest: has_field_derivative_imp_has_derivative)\n\nlemma DERIV_mult[derivative_intros]:\n  \"(f has_field_derivative Da) (at x within s) \\<Longrightarrow> (g has_field_derivative Db) (at x within s) \\<Longrightarrow>\n  ((\\<lambda>x. f x * g x) has_field_derivative Da * g x + Db * f x) (at x within s)\"\n  by (rule has_derivative_imp_has_field_derivative[OF has_derivative_mult])\n     (auto simp: field_simps dest: has_field_derivative_imp_has_derivative)\n\ntext {* Derivative of linear multiplication *}\n\nlemma DERIV_cmult:\n  \"(f has_field_derivative D) (at x within s) ==> ((\\<lambda>x. c * f x) has_field_derivative c * D) (at x within s)\"\n  by (drule DERIV_mult' [OF DERIV_const], simp)\n\nlemma DERIV_cmult_right:\n  \"(f has_field_derivative D) (at x within s) ==> ((\\<lambda>x. f x * c) has_field_derivative D * c) (at x within s)\"\n  using DERIV_cmult by (force simp add: ac_simps)\n\nlemma DERIV_cmult_Id [simp]: \"(op * c has_field_derivative c) (at x within s)\"\n  by (cut_tac c = c and x = x in DERIV_ident [THEN DERIV_cmult], simp)\n\nlemma DERIV_cdivide:\n  \"(f has_field_derivative D) (at x within s) \\<Longrightarrow> ((\\<lambda>x. f x / c) has_field_derivative D / c) (at x within s)\"\n  using DERIV_cmult_right[of f D x s \"1 / c\"] by simp\n\nlemma DERIV_unique:\n  \"DERIV f x :> D \\<Longrightarrow> DERIV f x :> E \\<Longrightarrow> D = E\"\n  unfolding DERIV_def by (rule LIM_unique) \n\nlemma DERIV_setsum[derivative_intros]:\n  \"(\\<And> n. n \\<in> S \\<Longrightarrow> ((\\<lambda>x. f x n) has_field_derivative (f' x n)) F) \\<Longrightarrow> \n    ((\\<lambda>x. setsum (f x) S) has_field_derivative setsum (f' x) S) F\"\n  by (rule has_derivative_imp_has_field_derivative[OF has_derivative_setsum])\n     (auto simp: setsum_right_distrib mult_commute_abs dest: has_field_derivative_imp_has_derivative)\n\nlemma DERIV_inverse'[derivative_intros]:\n  \"(f has_field_derivative D) (at x within s) \\<Longrightarrow> f x \\<noteq> 0 \\<Longrightarrow>\n  ((\\<lambda>x. inverse (f x)) has_field_derivative - (inverse (f x) * D * inverse (f x))) (at x within s)\"\n  by (rule has_derivative_imp_has_field_derivative[OF has_derivative_inverse])\n     (auto dest: has_field_derivative_imp_has_derivative)\n\ntext {* Power of @{text \"-1\"} *}\n\nlemma DERIV_inverse:\n  \"x \\<noteq> 0 \\<Longrightarrow> ((\\<lambda>x. inverse(x)) has_field_derivative - (inverse x ^ Suc (Suc 0))) (at x within s)\"\n  by (drule DERIV_inverse' [OF DERIV_ident]) simp\n\ntext {* Derivative of inverse *}\n\nlemma DERIV_inverse_fun:\n  \"(f has_field_derivative d) (at x within s) \\<Longrightarrow> f x \\<noteq> 0 \\<Longrightarrow>\n  ((\\<lambda>x. inverse (f x)) has_field_derivative (- (d * inverse(f x ^ Suc (Suc 0))))) (at x within s)\"\n  by (drule (1) DERIV_inverse') (simp add: ac_simps nonzero_inverse_mult_distrib)\n\ntext {* Derivative of quotient *}\n\nlemma DERIV_divide[derivative_intros]:\n  \"(f has_field_derivative D) (at x within s) \\<Longrightarrow>\n  (g has_field_derivative E) (at x within s) \\<Longrightarrow> g x \\<noteq> 0 \\<Longrightarrow>\n  ((\\<lambda>x. f x / g x) has_field_derivative (D * g x - f x * E) / (g x * g x)) (at x within s)\"\n  by (rule has_derivative_imp_has_field_derivative[OF has_derivative_divide])\n     (auto dest: has_field_derivative_imp_has_derivative simp: field_simps)\n\nlemma DERIV_quotient:\n  \"(f has_field_derivative d) (at x within s) \\<Longrightarrow>\n  (g has_field_derivative e) (at x within s)\\<Longrightarrow> g x \\<noteq> 0 \\<Longrightarrow> \n  ((\\<lambda>y. f y / g y) has_field_derivative (d * g x - (e * f x)) / (g x ^ Suc (Suc 0))) (at x within s)\"\n  by (drule (2) DERIV_divide) (simp add: mult.commute)\n\nlemma DERIV_power_Suc:\n  \"(f has_field_derivative D) (at x within s) \\<Longrightarrow>\n  ((\\<lambda>x. f x ^ Suc n) has_field_derivative (1 + of_nat n) * (D * f x ^ n)) (at x within s)\"\n  by (rule has_derivative_imp_has_field_derivative[OF has_derivative_power])\n     (auto simp: has_field_derivative_def)\n\nlemma DERIV_power[derivative_intros]:\n  \"(f has_field_derivative D) (at x within s) \\<Longrightarrow>\n  ((\\<lambda>x. f x ^ n) has_field_derivative of_nat n * (D * f x ^ (n - Suc 0))) (at x within s)\"\n  by (rule has_derivative_imp_has_field_derivative[OF has_derivative_power])\n     (auto simp: has_field_derivative_def)\n\nlemma DERIV_pow: \"((\\<lambda>x. x ^ n) has_field_derivative real n * (x ^ (n - Suc 0))) (at x within s)\"\n  apply (cut_tac DERIV_power [OF DERIV_ident])\n  apply (simp add: real_of_nat_def)\n  done\n\nlemma DERIV_chain': \"(f has_field_derivative D) (at x within s) \\<Longrightarrow> DERIV g (f x) :> E \\<Longrightarrow> \n  ((\\<lambda>x. g (f x)) has_field_derivative E * D) (at x within s)\"\n  using has_derivative_compose[of f \"op * D\" x s g \"op * E\"]\n  unfolding has_field_derivative_def mult_commute_abs ac_simps .\n\ncorollary DERIV_chain2: \"DERIV f (g x) :> Da \\<Longrightarrow> (g has_field_derivative Db) (at x within s) \\<Longrightarrow>\n  ((\\<lambda>x. f (g x)) has_field_derivative Da * Db) (at x within s)\"\n  by (rule DERIV_chain')\n\ntext {* Standard version *}\n\nlemma DERIV_chain:\n  \"DERIV f (g x) :> Da \\<Longrightarrow> (g has_field_derivative Db) (at x within s) \\<Longrightarrow> \n  (f o g has_field_derivative Da * Db) (at x within s)\"\n  by (drule (1) DERIV_chain', simp add: o_def mult.commute)\n\nlemma DERIV_image_chain: \n  \"(f has_field_derivative Da) (at (g x) within (g ` s)) \\<Longrightarrow> (g has_field_derivative Db) (at x within s) \\<Longrightarrow>\n  (f o g has_field_derivative Da * Db) (at x within s)\"\n  using has_derivative_in_compose [of g \"op * Db\" x s f \"op * Da \"]\n  by (simp add: has_field_derivative_def o_def mult_commute_abs ac_simps)\n\n(*These two are from HOL Light: HAS_COMPLEX_DERIVATIVE_CHAIN*)\nlemma DERIV_chain_s:\n  assumes \"(\\<And>x. x \\<in> s \\<Longrightarrow> DERIV g x :> g'(x))\"\n      and \"DERIV f x :> f'\" \n      and \"f x \\<in> s\"\n    shows \"DERIV (\\<lambda>x. g(f x)) x :> f' * g'(f x)\"\n  by (metis (full_types) DERIV_chain' mult.commute assms)\n\nlemma DERIV_chain3: (*HAS_COMPLEX_DERIVATIVE_CHAIN_UNIV*)\n  assumes \"(\\<And>x. DERIV g x :> g'(x))\"\n      and \"DERIV f x :> f'\" \n    shows \"DERIV (\\<lambda>x. g(f x)) x :> f' * g'(f x)\"\n  by (metis UNIV_I DERIV_chain_s [of UNIV] assms)\n\ndeclare\n  DERIV_power[where 'a=real, unfolded real_of_nat_def[symmetric], derivative_intros]\n\ntext{*Alternative definition for differentiability*}\n\nlemma DERIV_LIM_iff:\n  fixes f :: \"'a::{real_normed_vector,inverse} \\<Rightarrow> 'a\" shows\n     \"((%h. (f(a + h) - f(a)) / h) -- 0 --> D) =\n      ((%x. (f(x)-f(a)) / (x-a)) -- a --> D)\"\napply (rule iffI)\napply (drule_tac k=\"- a\" in LIM_offset)\napply simp\napply (drule_tac k=\"a\" in LIM_offset)\napply (simp add: add.commute)\ndone\n\nlemma DERIV_iff2: \"(DERIV f x :> D) \\<longleftrightarrow> (\\<lambda>z. (f z - f x) / (z - x)) --x --> D\"\n  by (simp add: DERIV_def DERIV_LIM_iff)\n\nlemma DERIV_cong_ev: \"x = y \\<Longrightarrow> eventually (\\<lambda>x. f x = g x) (nhds x) \\<Longrightarrow> u = v \\<Longrightarrow>\n    DERIV f x :> u \\<longleftrightarrow> DERIV g y :> v\"\n  unfolding DERIV_iff2\nproof (rule filterlim_cong)\n  assume *: \"eventually (\\<lambda>x. f x = g x) (nhds x)\"\n  moreover from * have \"f x = g x\" by (auto simp: eventually_nhds)\n  moreover assume \"x = y\" \"u = v\"\n  ultimately show \"eventually (\\<lambda>xa. (f xa - f x) / (xa - x) = (g xa - g y) / (xa - y)) (at x)\"\n    by (auto simp: eventually_at_filter elim: eventually_elim1)\nqed simp_all\n\nlemma DERIV_shift:\n  \"(DERIV f (x + z) :> y) \\<longleftrightarrow> (DERIV (\\<lambda>x. f (x + z)) x :> y)\"\n  by (simp add: DERIV_def field_simps)\n\nlemma DERIV_mirror:\n  \"(DERIV f (- x) :> y) \\<longleftrightarrow> (DERIV (\\<lambda>x. f (- x::real) :: real) x :> - y)\"\n  by (simp add: DERIV_def filterlim_at_split filterlim_at_left_to_right\n                tendsto_minus_cancel_left field_simps conj_commute)\n\ntext {* Caratheodory formulation of derivative at a point *}\n\nlemma CARAT_DERIV: (*FIXME: SUPERSEDED BY THE ONE IN Deriv.thy. But still used by NSA/HDeriv.thy*)\n  \"(DERIV f x :> l) \\<longleftrightarrow> (\\<exists>g. (\\<forall>z. f z - f x = g z * (z - x)) \\<and> isCont g x \\<and> g x = l)\"\n      (is \"?lhs = ?rhs\")\nproof\n  assume der: \"DERIV f x :> l\"\n  show \"\\<exists>g. (\\<forall>z. f z - f x = g z * (z-x)) \\<and> isCont g x \\<and> g x = l\"\n  proof (intro exI conjI)\n    let ?g = \"(%z. if z = x then l else (f z - f x) / (z-x))\"\n    show \"\\<forall>z. f z - f x = ?g z * (z-x)\" by simp\n    show \"isCont ?g x\" using der\n      by (simp add: isCont_iff DERIV_def cong: LIM_equal [rule_format])\n    show \"?g x = l\" by simp\n  qed\nnext\n  assume \"?rhs\"\n  then obtain g where\n    \"(\\<forall>z. f z - f x = g z * (z-x))\" and \"isCont g x\" and \"g x = l\" by blast\n  thus \"(DERIV f x :> l)\"\n     by (auto simp add: isCont_iff DERIV_def cong: LIM_cong)\nqed\n\ntext {*\n Let's do the standard proof, though theorem\n @{text \"LIM_mult2\"} follows from a NS proof\n*}\n\nsubsection {* Local extrema *}\n\ntext{*If @{term \"0 < f'(x)\"} then @{term x} is Locally Strictly Increasing At The Right*}\n\nlemma DERIV_pos_inc_right:\n  fixes f :: \"real => real\"\n  assumes der: \"DERIV f x :> l\"\n      and l:   \"0 < l\"\n  shows \"\\<exists>d > 0. \\<forall>h > 0. h < d --> f(x) < f(x + h)\"\nproof -\n  from l der [THEN DERIV_D, THEN LIM_D [where r = \"l\"]]\n  have \"\\<exists>s > 0. (\\<forall>z. z \\<noteq> 0 \\<and> \\<bar>z\\<bar> < s \\<longrightarrow> \\<bar>(f(x+z) - f x) / z - l\\<bar> < l)\"\n    by simp\n  then obtain s\n        where s:   \"0 < s\"\n          and all: \"!!z. z \\<noteq> 0 \\<and> \\<bar>z\\<bar> < s \\<longrightarrow> \\<bar>(f(x+z) - f x) / z - l\\<bar> < l\"\n    by auto\n  thus ?thesis\n  proof (intro exI conjI strip)\n    show \"0<s\" using s .\n    fix h::real\n    assume \"0 < h\" \"h < s\"\n    with all [of h] show \"f x < f (x+h)\"\n    proof (simp add: abs_if pos_less_divide_eq split add: split_if_asm)\n      assume \"~ (f (x+h) - f x) / h < l\" and h: \"0 < h\"\n      with l\n      have \"0 < (f (x+h) - f x) / h\" by arith\n      thus \"f x < f (x+h)\"\n  by (simp add: pos_less_divide_eq h)\n    qed\n  qed\nqed\n\nlemma DERIV_neg_dec_left:\n  fixes f :: \"real => real\"\n  assumes der: \"DERIV f x :> l\"\n      and l:   \"l < 0\"\n  shows \"\\<exists>d > 0. \\<forall>h > 0. h < d --> f(x) < f(x-h)\"\nproof -\n  from l der [THEN DERIV_D, THEN LIM_D [where r = \"-l\"]]\n  have \"\\<exists>s > 0. (\\<forall>z. z \\<noteq> 0 \\<and> \\<bar>z\\<bar> < s \\<longrightarrow> \\<bar>(f(x+z) - f x) / z - l\\<bar> < -l)\"\n    by simp\n  then obtain s\n        where s:   \"0 < s\"\n          and all: \"!!z. z \\<noteq> 0 \\<and> \\<bar>z\\<bar> < s \\<longrightarrow> \\<bar>(f(x+z) - f x) / z - l\\<bar> < -l\"\n    by auto\n  thus ?thesis\n  proof (intro exI conjI strip)\n    show \"0<s\" using s .\n    fix h::real\n    assume \"0 < h\" \"h < s\"\n    with all [of \"-h\"] show \"f x < f (x-h)\"\n    proof (simp add: abs_if pos_less_divide_eq split add: split_if_asm)\n      assume \" - ((f (x-h) - f x) / h) < l\" and h: \"0 < h\"\n      with l\n      have \"0 < (f (x-h) - f x) / h\" by arith\n      thus \"f x < f (x-h)\"\n  by (simp add: pos_less_divide_eq h)\n    qed\n  qed\nqed\n\nlemma DERIV_pos_inc_left:\n  fixes f :: \"real => real\"\n  shows \"DERIV f x :> l \\<Longrightarrow> 0 < l \\<Longrightarrow> \\<exists>d > 0. \\<forall>h > 0. h < d --> f(x - h) < f(x)\"\n  apply (rule DERIV_neg_dec_left [of \"%x. - f x\" \"-l\" x, simplified])\n  apply (auto simp add: DERIV_minus)\n  done\n\nlemma DERIV_neg_dec_right:\n  fixes f :: \"real => real\"\n  shows \"DERIV f x :> l \\<Longrightarrow> l < 0 \\<Longrightarrow> \\<exists>d > 0. \\<forall>h > 0. h < d --> f(x) > f(x + h)\"\n  apply (rule DERIV_pos_inc_right [of \"%x. - f x\" \"-l\" x, simplified])\n  apply (auto simp add: DERIV_minus)\n  done\n\nlemma DERIV_local_max:\n  fixes f :: \"real => real\"\n  assumes der: \"DERIV f x :> l\"\n      and d:   \"0 < d\"\n      and le:  \"\\<forall>y. \\<bar>x-y\\<bar> < d --> f(y) \\<le> f(x)\"\n  shows \"l = 0\"\nproof (cases rule: linorder_cases [of l 0])\n  case equal thus ?thesis .\nnext\n  case less\n  from DERIV_neg_dec_left [OF der less]\n  obtain d' where d': \"0 < d'\"\n             and lt: \"\\<forall>h > 0. h < d' \\<longrightarrow> f x < f (x-h)\" by blast\n  from real_lbound_gt_zero [OF d d']\n  obtain e where \"0 < e \\<and> e < d \\<and> e < d'\" ..\n  with lt le [THEN spec [where x=\"x-e\"]]\n  show ?thesis by (auto simp add: abs_if)\nnext\n  case greater\n  from DERIV_pos_inc_right [OF der greater]\n  obtain d' where d': \"0 < d'\"\n             and lt: \"\\<forall>h > 0. h < d' \\<longrightarrow> f x < f (x + h)\" by blast\n  from real_lbound_gt_zero [OF d d']\n  obtain e where \"0 < e \\<and> e < d \\<and> e < d'\" ..\n  with lt le [THEN spec [where x=\"x+e\"]]\n  show ?thesis by (auto simp add: abs_if)\nqed\n\n\ntext{*Similar theorem for a local minimum*}\nlemma DERIV_local_min:\n  fixes f :: \"real => real\"\n  shows \"[| DERIV f x :> l; 0 < d; \\<forall>y. \\<bar>x-y\\<bar> < d --> f(x) \\<le> f(y) |] ==> l = 0\"\nby (drule DERIV_minus [THEN DERIV_local_max], auto)\n\n\ntext{*In particular, if a function is locally flat*}\nlemma DERIV_local_const:\n  fixes f :: \"real => real\"\n  shows \"[| DERIV f x :> l; 0 < d; \\<forall>y. \\<bar>x-y\\<bar> < d --> f(x) = f(y) |] ==> l = 0\"\nby (auto dest!: DERIV_local_max)\n\n\nsubsection {* Rolle's Theorem *}\n\ntext{*Lemma about introducing open ball in open interval*}\nlemma lemma_interval_lt:\n     \"[| a < x;  x < b |]\n      ==> \\<exists>d::real. 0 < d & (\\<forall>y. \\<bar>x-y\\<bar> < d --> a < y & y < b)\"\n\napply (simp add: abs_less_iff)\napply (insert linorder_linear [of \"x-a\" \"b-x\"], safe)\napply (rule_tac x = \"x-a\" in exI)\napply (rule_tac [2] x = \"b-x\" in exI, auto)\ndone\n\nlemma lemma_interval: \"[| a < x;  x < b |] ==>\n        \\<exists>d::real. 0 < d &  (\\<forall>y. \\<bar>x-y\\<bar> < d --> a \\<le> y & y \\<le> b)\"\napply (drule lemma_interval_lt, auto)\napply force\ndone\n\ntext{*Rolle's Theorem.\n   If @{term f} is defined and continuous on the closed interval\n   @{text \"[a,b]\"} and differentiable on the open interval @{text \"(a,b)\"},\n   and @{term \"f(a) = f(b)\"},\n   then there exists @{text \"x0 \\<in> (a,b)\"} such that @{term \"f'(x0) = 0\"}*}\ntheorem Rolle:\n  assumes lt: \"a < b\"\n      and eq: \"f(a) = f(b)\"\n      and con: \"\\<forall>x. a \\<le> x & x \\<le> b --> isCont f x\"\n      and dif [rule_format]: \"\\<forall>x. a < x & x < b --> f differentiable (at x)\"\n  shows \"\\<exists>z::real. a < z & z < b & DERIV f z :> 0\"\nproof -\n  have le: \"a \\<le> b\" using lt by simp\n  from isCont_eq_Ub [OF le con]\n  obtain x where x_max: \"\\<forall>z. a \\<le> z \\<and> z \\<le> b \\<longrightarrow> f z \\<le> f x\"\n             and alex: \"a \\<le> x\" and xleb: \"x \\<le> b\"\n    by blast\n  from isCont_eq_Lb [OF le con]\n  obtain x' where x'_min: \"\\<forall>z. a \\<le> z \\<and> z \\<le> b \\<longrightarrow> f x' \\<le> f z\"\n              and alex': \"a \\<le> x'\" and x'leb: \"x' \\<le> b\"\n    by blast\n  show ?thesis\n  proof cases\n    assume axb: \"a < x & x < b\"\n        --{*@{term f} attains its maximum within the interval*}\n    hence ax: \"a<x\" and xb: \"x<b\" by arith + \n    from lemma_interval [OF ax xb]\n    obtain d where d: \"0<d\" and bound: \"\\<forall>y. \\<bar>x-y\\<bar> < d \\<longrightarrow> a \\<le> y \\<and> y \\<le> b\"\n      by blast\n    hence bound': \"\\<forall>y. \\<bar>x-y\\<bar> < d \\<longrightarrow> f y \\<le> f x\" using x_max\n      by blast\n    from differentiableD [OF dif [OF axb]]\n    obtain l where der: \"DERIV f x :> l\" ..\n    have \"l=0\" by (rule DERIV_local_max [OF der d bound'])\n        --{*the derivative at a local maximum is zero*}\n    thus ?thesis using ax xb der by auto\n  next\n    assume notaxb: \"~ (a < x & x < b)\"\n    hence xeqab: \"x=a | x=b\" using alex xleb by arith\n    hence fb_eq_fx: \"f b = f x\" by (auto simp add: eq)\n    show ?thesis\n    proof cases\n      assume ax'b: \"a < x' & x' < b\"\n        --{*@{term f} attains its minimum within the interval*}\n      hence ax': \"a<x'\" and x'b: \"x'<b\" by arith+ \n      from lemma_interval [OF ax' x'b]\n      obtain d where d: \"0<d\" and bound: \"\\<forall>y. \\<bar>x'-y\\<bar> < d \\<longrightarrow> a \\<le> y \\<and> y \\<le> b\"\n  by blast\n      hence bound': \"\\<forall>y. \\<bar>x'-y\\<bar> < d \\<longrightarrow> f x' \\<le> f y\" using x'_min\n  by blast\n      from differentiableD [OF dif [OF ax'b]]\n      obtain l where der: \"DERIV f x' :> l\" ..\n      have \"l=0\" by (rule DERIV_local_min [OF der d bound'])\n        --{*the derivative at a local minimum is zero*}\n      thus ?thesis using ax' x'b der by auto\n    next\n      assume notax'b: \"~ (a < x' & x' < b)\"\n        --{*@{term f} is constant througout the interval*}\n      hence x'eqab: \"x'=a | x'=b\" using alex' x'leb by arith\n      hence fb_eq_fx': \"f b = f x'\" by (auto simp add: eq)\n      from dense [OF lt]\n      obtain r where ar: \"a < r\" and rb: \"r < b\" by blast\n      from lemma_interval [OF ar rb]\n      obtain d where d: \"0<d\" and bound: \"\\<forall>y. \\<bar>r-y\\<bar> < d \\<longrightarrow> a \\<le> y \\<and> y \\<le> b\"\n  by blast\n      have eq_fb: \"\\<forall>z. a \\<le> z --> z \\<le> b --> f z = f b\"\n      proof (clarify)\n        fix z::real\n        assume az: \"a \\<le> z\" and zb: \"z \\<le> b\"\n        show \"f z = f b\"\n        proof (rule order_antisym)\n          show \"f z \\<le> f b\" by (simp add: fb_eq_fx x_max az zb)\n          show \"f b \\<le> f z\" by (simp add: fb_eq_fx' x'_min az zb)\n        qed\n      qed\n      have bound': \"\\<forall>y. \\<bar>r-y\\<bar> < d \\<longrightarrow> f r = f y\"\n      proof (intro strip)\n        fix y::real\n        assume lt: \"\\<bar>r-y\\<bar> < d\"\n        hence \"f y = f b\" by (simp add: eq_fb bound)\n        thus \"f r = f y\" by (simp add: eq_fb ar rb order_less_imp_le)\n      qed\n      from differentiableD [OF dif [OF conjI [OF ar rb]]]\n      obtain l where der: \"DERIV f r :> l\" ..\n      have \"l=0\" by (rule DERIV_local_const [OF der d bound'])\n        --{*the derivative of a constant function is zero*}\n      thus ?thesis using ar rb der by auto\n    qed\n  qed\nqed\n\n\nsubsection{*Mean Value Theorem*}\n\nlemma lemma_MVT:\n     \"f a - (f b - f a)/(b-a) * a = f b - (f b - f a)/(b-a) * (b::real)\"\n  by (cases \"a = b\") (simp_all add: field_simps)\n\ntheorem MVT:\n  assumes lt:  \"a < b\"\n      and con: \"\\<forall>x. a \\<le> x & x \\<le> b --> isCont f x\"\n      and dif [rule_format]: \"\\<forall>x. a < x & x < b --> f differentiable (at x)\"\n  shows \"\\<exists>l z::real. a < z & z < b & DERIV f z :> l &\n                   (f(b) - f(a) = (b-a) * l)\"\nproof -\n  let ?F = \"%x. f x - ((f b - f a) / (b-a)) * x\"\n  have contF: \"\\<forall>x. a \\<le> x \\<and> x \\<le> b \\<longrightarrow> isCont ?F x\"\n    using con by (fast intro: continuous_intros)\n  have difF: \"\\<forall>x. a < x \\<and> x < b \\<longrightarrow> ?F differentiable (at x)\"\n  proof (clarify)\n    fix x::real\n    assume ax: \"a < x\" and xb: \"x < b\"\n    from differentiableD [OF dif [OF conjI [OF ax xb]]]\n    obtain l where der: \"DERIV f x :> l\" ..\n    show \"?F differentiable (at x)\"\n      by (rule differentiableI [where D = \"l - (f b - f a)/(b-a)\"],\n          blast intro: DERIV_diff DERIV_cmult_Id der)\n  qed\n  from Rolle [where f = ?F, OF lt lemma_MVT contF difF]\n  obtain z where az: \"a < z\" and zb: \"z < b\" and der: \"DERIV ?F z :> 0\"\n    by blast\n  have \"DERIV (%x. ((f b - f a)/(b-a)) * x) z :> (f b - f a)/(b-a)\"\n    by (rule DERIV_cmult_Id)\n  hence derF: \"DERIV (\\<lambda>x. ?F x + (f b - f a) / (b - a) * x) z\n                   :> 0 + (f b - f a) / (b - a)\"\n    by (rule DERIV_add [OF der])\n  show ?thesis\n  proof (intro exI conjI)\n    show \"a < z\" using az .\n    show \"z < b\" using zb .\n    show \"f b - f a = (b - a) * ((f b - f a)/(b-a))\" by (simp)\n    show \"DERIV f z :> ((f b - f a)/(b-a))\"  using derF by simp\n  qed\nqed\n\nlemma MVT2:\n     \"[| a < b; \\<forall>x. a \\<le> x & x \\<le> b --> DERIV f x :> f'(x) |]\n      ==> \\<exists>z::real. a < z & z < b & (f b - f a = (b - a) * f'(z))\"\napply (drule MVT)\napply (blast intro: DERIV_isCont)\napply (force dest: order_less_imp_le simp add: real_differentiable_def)\napply (blast dest: DERIV_unique order_less_imp_le)\ndone\n\n\ntext{*A function is constant if its derivative is 0 over an interval.*}\n\nlemma DERIV_isconst_end:\n  fixes f :: \"real => real\"\n  shows \"[| a < b;\n         \\<forall>x. a \\<le> x & x \\<le> b --> isCont f x;\n         \\<forall>x. a < x & x < b --> DERIV f x :> 0 |]\n        ==> f b = f a\"\napply (drule MVT, assumption)\napply (blast intro: differentiableI)\napply (auto dest!: DERIV_unique simp add: diff_eq_eq)\ndone\n\nlemma DERIV_isconst1:\n  fixes f :: \"real => real\"\n  shows \"[| a < b;\n         \\<forall>x. a \\<le> x & x \\<le> b --> isCont f x;\n         \\<forall>x. a < x & x < b --> DERIV f x :> 0 |]\n        ==> \\<forall>x. a \\<le> x & x \\<le> b --> f x = f a\"\napply safe\napply (drule_tac x = a in order_le_imp_less_or_eq, safe)\napply (drule_tac b = x in DERIV_isconst_end, auto)\ndone\n\nlemma DERIV_isconst2:\n  fixes f :: \"real => real\"\n  shows \"[| a < b;\n         \\<forall>x. a \\<le> x & x \\<le> b --> isCont f x;\n         \\<forall>x. a < x & x < b --> DERIV f x :> 0;\n         a \\<le> x; x \\<le> b |]\n        ==> f x = f a\"\napply (blast dest: DERIV_isconst1)\ndone\n\nlemma DERIV_isconst3: fixes a b x y :: real\n  assumes \"a < b\" and \"x \\<in> {a <..< b}\" and \"y \\<in> {a <..< b}\"\n  assumes derivable: \"\\<And>x. x \\<in> {a <..< b} \\<Longrightarrow> DERIV f x :> 0\"\n  shows \"f x = f y\"\nproof (cases \"x = y\")\n  case False\n  let ?a = \"min x y\"\n  let ?b = \"max x y\"\n  \n  have \"\\<forall>z. ?a \\<le> z \\<and> z \\<le> ?b \\<longrightarrow> DERIV f z :> 0\"\n  proof (rule allI, rule impI)\n    fix z :: real assume \"?a \\<le> z \\<and> z \\<le> ?b\"\n    hence \"a < z\" and \"z < b\" using `x \\<in> {a <..< b}` and `y \\<in> {a <..< b}` by auto\n    hence \"z \\<in> {a<..<b}\" by auto\n    thus \"DERIV f z :> 0\" by (rule derivable)\n  qed\n  hence isCont: \"\\<forall>z. ?a \\<le> z \\<and> z \\<le> ?b \\<longrightarrow> isCont f z\"\n    and DERIV: \"\\<forall>z. ?a < z \\<and> z < ?b \\<longrightarrow> DERIV f z :> 0\" using DERIV_isCont by auto\n\n  have \"?a < ?b\" using `x \\<noteq> y` by auto\n  from DERIV_isconst2[OF this isCont DERIV, of x] and DERIV_isconst2[OF this isCont DERIV, of y]\n  show ?thesis by auto\nqed auto\n\nlemma DERIV_isconst_all:\n  fixes f :: \"real => real\"\n  shows \"\\<forall>x. DERIV f x :> 0 ==> f(x) = f(y)\"\napply (rule linorder_cases [of x y])\napply (blast intro: sym DERIV_isCont DERIV_isconst_end)+\ndone\n\nlemma DERIV_const_ratio_const:\n  fixes f :: \"real => real\"\n  shows \"[|a \\<noteq> b; \\<forall>x. DERIV f x :> k |] ==> (f(b) - f(a)) = (b-a) * k\"\napply (rule linorder_cases [of a b], auto)\napply (drule_tac [!] f = f in MVT)\napply (auto dest: DERIV_isCont DERIV_unique simp add: real_differentiable_def)\napply (auto dest: DERIV_unique simp add: ring_distribs)\ndone\n\nlemma DERIV_const_ratio_const2:\n  fixes f :: \"real => real\"\n  shows \"[|a \\<noteq> b; \\<forall>x. DERIV f x :> k |] ==> (f(b) - f(a))/(b-a) = k\"\napply (rule_tac c1 = \"b-a\" in mult_right_cancel [THEN iffD1])\napply (auto dest!: DERIV_const_ratio_const simp add: mult.assoc)\ndone\n\nlemma real_average_minus_first [simp]: \"((a + b) /2 - a) = (b-a)/(2::real)\"\nby (simp)\n\nlemma real_average_minus_second [simp]: \"((b + a)/2 - a) = (b-a)/(2::real)\"\nby (simp)\n\ntext{*Gallileo's \"trick\": average velocity = av. of end velocities*}\n\nlemma DERIV_const_average:\n  fixes v :: \"real => real\"\n  assumes neq: \"a \\<noteq> (b::real)\"\n      and der: \"\\<forall>x. DERIV v x :> k\"\n  shows \"v ((a + b)/2) = (v a + v b)/2\"\nproof (cases rule: linorder_cases [of a b])\n  case equal with neq show ?thesis by simp\nnext\n  case less\n  have \"(v b - v a) / (b - a) = k\"\n    by (rule DERIV_const_ratio_const2 [OF neq der])\n  hence \"(b-a) * ((v b - v a) / (b-a)) = (b-a) * k\" by simp\n  moreover have \"(v ((a + b) / 2) - v a) / ((a + b) / 2 - a) = k\"\n    by (rule DERIV_const_ratio_const2 [OF _ der], simp add: neq)\n  ultimately show ?thesis using neq by force\nnext\n  case greater\n  have \"(v b - v a) / (b - a) = k\"\n    by (rule DERIV_const_ratio_const2 [OF neq der])\n  hence \"(b-a) * ((v b - v a) / (b-a)) = (b-a) * k\" by simp\n  moreover have \" (v ((b + a) / 2) - v a) / ((b + a) / 2 - a) = k\"\n    by (rule DERIV_const_ratio_const2 [OF _ der], simp add: neq)\n  ultimately show ?thesis using neq by (force simp add: add.commute)\nqed\n\n(* A function with positive derivative is increasing. \n   A simple proof using the MVT, by Jeremy Avigad. And variants.\n*)\nlemma DERIV_pos_imp_increasing_open:\n  fixes a::real and b::real and f::\"real => real\"\n  assumes \"a < b\" and \"\\<And>x. a < x \\<Longrightarrow> x < b \\<Longrightarrow> (EX y. DERIV f x :> y & y > 0)\"\n      and con: \"\\<And>x. a \\<le> x \\<Longrightarrow> x \\<le> b \\<Longrightarrow> isCont f x\"\n  shows \"f a < f b\"\nproof (rule ccontr)\n  assume f: \"~ f a < f b\"\n  have \"EX l z. a < z & z < b & DERIV f z :> l\n      & f b - f a = (b - a) * l\"\n    apply (rule MVT)\n      using assms Deriv.differentiableI\n      apply force+\n    done\n  then obtain l z where z: \"a < z\" \"z < b\" \"DERIV f z :> l\"\n      and \"f b - f a = (b - a) * l\"\n    by auto\n  with assms f have \"~(l > 0)\"\n    by (metis linorder_not_le mult_le_0_iff diff_le_0_iff_le)\n  with assms z show False\n    by (metis DERIV_unique)\nqed\n\nlemma DERIV_pos_imp_increasing:\n  fixes a::real and b::real and f::\"real => real\"\n  assumes \"a < b\" and \"\\<forall>x. a \\<le> x & x \\<le> b --> (EX y. DERIV f x :> y & y > 0)\"\n  shows \"f a < f b\"\nby (metis DERIV_pos_imp_increasing_open [of a b f] assms DERIV_continuous less_imp_le)\n\nlemma DERIV_nonneg_imp_nondecreasing:\n  fixes a::real and b::real and f::\"real => real\"\n  assumes \"a \\<le> b\" and\n    \"\\<forall>x. a \\<le> x & x \\<le> b --> (\\<exists>y. DERIV f x :> y & y \\<ge> 0)\"\n  shows \"f a \\<le> f b\"\nproof (rule ccontr, cases \"a = b\")\n  assume \"~ f a \\<le> f b\" and \"a = b\"\n  then show False by auto\nnext\n  assume A: \"~ f a \\<le> f b\"\n  assume B: \"a ~= b\"\n  with assms have \"EX l z. a < z & z < b & DERIV f z :> l\n      & f b - f a = (b - a) * l\"\n    apply -\n    apply (rule MVT)\n      apply auto\n      apply (metis DERIV_isCont)\n     apply (metis differentiableI less_le)\n    done\n  then obtain l z where z: \"a < z\" \"z < b\" \"DERIV f z :> l\"\n      and C: \"f b - f a = (b - a) * l\"\n    by auto\n  with A have \"a < b\" \"f b < f a\" by auto\n  with C have \"\\<not> l \\<ge> 0\" by (auto simp add: not_le algebra_simps)\n    (metis A add_le_cancel_right assms(1) less_eq_real_def mult_right_mono add_left_mono linear order_refl)\n  with assms z show False\n    by (metis DERIV_unique order_less_imp_le)\nqed\n\nlemma DERIV_neg_imp_decreasing_open:\n  fixes a::real and b::real and f::\"real => real\"\n  assumes \"a < b\" and \"\\<And>x. a < x \\<Longrightarrow> x < b \\<Longrightarrow> (EX y. DERIV f x :> y & y < 0)\"\n      and con: \"\\<And>x. a \\<le> x \\<Longrightarrow> x \\<le> b \\<Longrightarrow> isCont f x\"\n  shows \"f a > f b\"\nproof -\n  have \"(%x. -f x) a < (%x. -f x) b\"\n    apply (rule DERIV_pos_imp_increasing_open [of a b \"%x. -f x\"])\n    using assms\n    apply auto\n    apply (metis field_differentiable_minus neg_0_less_iff_less)\n    done\n  thus ?thesis\n    by simp\nqed\n\nlemma DERIV_neg_imp_decreasing:\n  fixes a::real and b::real and f::\"real => real\"\n  assumes \"a < b\" and\n    \"\\<forall>x. a \\<le> x & x \\<le> b --> (\\<exists>y. DERIV f x :> y & y < 0)\"\n  shows \"f a > f b\"\nby (metis DERIV_neg_imp_decreasing_open [of a b f] assms DERIV_continuous less_imp_le)\n\nlemma DERIV_nonpos_imp_nonincreasing:\n  fixes a::real and b::real and f::\"real => real\"\n  assumes \"a \\<le> b\" and\n    \"\\<forall>x. a \\<le> x & x \\<le> b --> (\\<exists>y. DERIV f x :> y & y \\<le> 0)\"\n  shows \"f a \\<ge> f b\"\nproof -\n  have \"(%x. -f x) a \\<le> (%x. -f x) b\"\n    apply (rule DERIV_nonneg_imp_nondecreasing [of a b \"%x. -f x\"])\n    using assms\n    apply auto\n    apply (metis DERIV_minus neg_0_le_iff_le)\n    done\n  thus ?thesis\n    by simp\nqed\n\nlemma DERIV_pos_imp_increasing_at_bot:\n  fixes f :: \"real => real\"\n  assumes \"\\<And>x. x \\<le> b \\<Longrightarrow> (EX y. DERIV f x :> y & y > 0)\"\n      and lim: \"(f ---> flim) at_bot\"\n  shows \"flim < f b\"\nproof -\n  have \"flim \\<le> f (b - 1)\"\n    apply (rule tendsto_ge_const [OF _ lim])\n    apply (auto simp: trivial_limit_at_bot_linorder eventually_at_bot_linorder)\n    apply (rule_tac x=\"b - 2\" in exI)\n    apply (force intro: order.strict_implies_order DERIV_pos_imp_increasing [where f=f] assms)\n    done\n  also have \"... < f b\"\n    by (force intro: DERIV_pos_imp_increasing [where f=f] assms)\n  finally show ?thesis .\nqed\n\nlemma DERIV_neg_imp_decreasing_at_top:\n  fixes f :: \"real => real\"\n  assumes der: \"\\<And>x. x \\<ge> b \\<Longrightarrow> (EX y. DERIV f x :> y & y < 0)\"\n      and lim: \"(f ---> flim) at_top\"\n  shows \"flim < f b\"\n  apply (rule DERIV_pos_imp_increasing_at_bot [where f = \"\\<lambda>i. f (-i)\" and b = \"-b\", simplified])\n  apply (metis DERIV_mirror der le_minus_iff neg_0_less_iff_less)\n  apply (metis filterlim_at_top_mirror lim)\n  done\n\ntext {* Derivative of inverse function *}\n\nlemma DERIV_inverse_function:\n  fixes f g :: \"real \\<Rightarrow> real\"\n  assumes der: \"DERIV f (g x) :> D\"\n  assumes neq: \"D \\<noteq> 0\"\n  assumes a: \"a < x\" and b: \"x < b\"\n  assumes inj: \"\\<forall>y. a < y \\<and> y < b \\<longrightarrow> f (g y) = y\"\n  assumes cont: \"isCont g x\"\n  shows \"DERIV g x :> inverse D\"\nunfolding DERIV_iff2\nproof (rule LIM_equal2)\n  show \"0 < min (x - a) (b - x)\"\n    using a b by arith \nnext\n  fix y\n  assume \"norm (y - x) < min (x - a) (b - x)\"\n  hence \"a < y\" and \"y < b\" \n    by (simp_all add: abs_less_iff)\n  thus \"(g y - g x) / (y - x) =\n        inverse ((f (g y) - x) / (g y - g x))\"\n    by (simp add: inj)\nnext\n  have \"(\\<lambda>z. (f z - f (g x)) / (z - g x)) -- g x --> D\"\n    by (rule der [unfolded DERIV_iff2])\n  hence 1: \"(\\<lambda>z. (f z - x) / (z - g x)) -- g x --> D\"\n    using inj a b by simp\n  have 2: \"\\<exists>d>0. \\<forall>y. y \\<noteq> x \\<and> norm (y - x) < d \\<longrightarrow> g y \\<noteq> g x\"\n  proof (rule exI, safe)\n    show \"0 < min (x - a) (b - x)\"\n      using a b by simp\n  next\n    fix y\n    assume \"norm (y - x) < min (x - a) (b - x)\"\n    hence y: \"a < y\" \"y < b\"\n      by (simp_all add: abs_less_iff)\n    assume \"g y = g x\"\n    hence \"f (g y) = f (g x)\" by simp\n    hence \"y = x\" using inj y a b by simp\n    also assume \"y \\<noteq> x\"\n    finally show False by simp\n  qed\n  have \"(\\<lambda>y. (f (g y) - x) / (g y - g x)) -- x --> D\"\n    using cont 1 2 by (rule isCont_LIM_compose2)\n  thus \"(\\<lambda>y. inverse ((f (g y) - x) / (g y - g x)))\n        -- x --> inverse D\"\n    using neq by (rule tendsto_inverse)\nqed\n\nsubsection {* Generalized Mean Value Theorem *}\n\ntheorem GMVT:\n  fixes a b :: real\n  assumes alb: \"a < b\"\n    and fc: \"\\<forall>x. a \\<le> x \\<and> x \\<le> b \\<longrightarrow> isCont f x\"\n    and fd: \"\\<forall>x. a < x \\<and> x < b \\<longrightarrow> f differentiable (at x)\"\n    and gc: \"\\<forall>x. a \\<le> x \\<and> x \\<le> b \\<longrightarrow> isCont g x\"\n    and gd: \"\\<forall>x. a < x \\<and> x < b \\<longrightarrow> g differentiable (at x)\"\n  shows \"\\<exists>g'c f'c c.\n    DERIV g c :> g'c \\<and> DERIV f c :> f'c \\<and> a < c \\<and> c < b \\<and> ((f b - f a) * g'c) = ((g b - g a) * f'c)\"\nproof -\n  let ?h = \"\\<lambda>x. (f b - f a)*(g x) - (g b - g a)*(f x)\"\n  from assms have \"a < b\" by simp\n  moreover have \"\\<forall>x. a \\<le> x \\<and> x \\<le> b \\<longrightarrow> isCont ?h x\"\n    using fc gc by simp\n  moreover have \"\\<forall>x. a < x \\<and> x < b \\<longrightarrow> ?h differentiable (at x)\"\n    using fd gd by simp\n  ultimately have \"\\<exists>l z. a < z \\<and> z < b \\<and> DERIV ?h z :> l \\<and> ?h b - ?h a = (b - a) * l\" by (rule MVT)\n  then obtain l where ldef: \"\\<exists>z. a < z \\<and> z < b \\<and> DERIV ?h z :> l \\<and> ?h b - ?h a = (b - a) * l\" ..\n  then obtain c where cdef: \"a < c \\<and> c < b \\<and> DERIV ?h c :> l \\<and> ?h b - ?h a = (b - a) * l\" ..\n\n  from cdef have cint: \"a < c \\<and> c < b\" by auto\n  with gd have \"g differentiable (at c)\" by simp\n  hence \"\\<exists>D. DERIV g c :> D\" by (rule differentiableD)\n  then obtain g'c where g'cdef: \"DERIV g c :> g'c\" ..\n\n  from cdef have \"a < c \\<and> c < b\" by auto\n  with fd have \"f differentiable (at c)\" by simp\n  hence \"\\<exists>D. DERIV f c :> D\" by (rule differentiableD)\n  then obtain f'c where f'cdef: \"DERIV f c :> f'c\" ..\n\n  from cdef have \"DERIV ?h c :> l\" by auto\n  moreover have \"DERIV ?h c :>  g'c * (f b - f a) - f'c * (g b - g a)\"\n    using g'cdef f'cdef by (auto intro!: derivative_eq_intros)\n  ultimately have leq: \"l =  g'c * (f b - f a) - f'c * (g b - g a)\" by (rule DERIV_unique)\n\n  {\n    from cdef have \"?h b - ?h a = (b - a) * l\" by auto\n    also from leq have \"\\<dots> = (b - a) * (g'c * (f b - f a) - f'c * (g b - g a))\" by simp\n    finally have \"?h b - ?h a = (b - a) * (g'c * (f b - f a) - f'c * (g b - g a))\" by simp\n  }\n  moreover\n  {\n    have \"?h b - ?h a =\n         ((f b)*(g b) - (f a)*(g b) - (g b)*(f b) + (g a)*(f b)) -\n          ((f b)*(g a) - (f a)*(g a) - (g b)*(f a) + (g a)*(f a))\"\n      by (simp add: algebra_simps)\n    hence \"?h b - ?h a = 0\" by auto\n  }\n  ultimately have \"(b - a) * (g'c * (f b - f a) - f'c * (g b - g a)) = 0\" by auto\n  with alb have \"g'c * (f b - f a) - f'c * (g b - g a) = 0\" by simp\n  hence \"g'c * (f b - f a) = f'c * (g b - g a)\" by simp\n  hence \"(f b - f a) * g'c = (g b - g a) * f'c\" by (simp add: ac_simps)\n\n  with g'cdef f'cdef cint show ?thesis by auto\nqed\n\nlemma GMVT':\n  fixes f g :: \"real \\<Rightarrow> real\"\n  assumes \"a < b\"\n  assumes isCont_f: \"\\<And>z. a \\<le> z \\<Longrightarrow> z \\<le> b \\<Longrightarrow> isCont f z\"\n  assumes isCont_g: \"\\<And>z. a \\<le> z \\<Longrightarrow> z \\<le> b \\<Longrightarrow> isCont g z\"\n  assumes DERIV_g: \"\\<And>z. a < z \\<Longrightarrow> z < b \\<Longrightarrow> DERIV g z :> (g' z)\"\n  assumes DERIV_f: \"\\<And>z. a < z \\<Longrightarrow> z < b \\<Longrightarrow> DERIV f z :> (f' z)\"\n  shows \"\\<exists>c. a < c \\<and> c < b \\<and> (f b - f a) * g' c = (g b - g a) * f' c\"\nproof -\n  have \"\\<exists>g'c f'c c. DERIV g c :> g'c \\<and> DERIV f c :> f'c \\<and>\n    a < c \\<and> c < b \\<and> (f b - f a) * g'c = (g b - g a) * f'c\"\n    using assms by (intro GMVT) (force simp: real_differentiable_def)+\n  then obtain c where \"a < c\" \"c < b\" \"(f b - f a) * g' c = (g b - g a) * f' c\"\n    using DERIV_f DERIV_g by (force dest: DERIV_unique)\n  then show ?thesis\n    by auto\nqed\n\n\nsubsection {* L'Hopitals rule *}\n\nlemma isCont_If_ge:\n  fixes a :: \"'a :: linorder_topology\"\n  shows \"continuous (at_left a) g \\<Longrightarrow> (f ---> g a) (at_right a) \\<Longrightarrow> isCont (\\<lambda>x. if x \\<le> a then g x else f x) a\"\n  unfolding isCont_def continuous_within\n  apply (intro filterlim_split_at)\n  apply (subst filterlim_cong[OF refl refl, where g=g])\n  apply (simp_all add: eventually_at_filter less_le)\n  apply (subst filterlim_cong[OF refl refl, where g=f])\n  apply (simp_all add: eventually_at_filter less_le)\n  done\n\nlemma lhopital_right_0:\n  fixes f0 g0 :: \"real \\<Rightarrow> real\"\n  assumes f_0: \"(f0 ---> 0) (at_right 0)\"\n  assumes g_0: \"(g0 ---> 0) (at_right 0)\"\n  assumes ev:\n    \"eventually (\\<lambda>x. g0 x \\<noteq> 0) (at_right 0)\"\n    \"eventually (\\<lambda>x. g' x \\<noteq> 0) (at_right 0)\"\n    \"eventually (\\<lambda>x. DERIV f0 x :> f' x) (at_right 0)\"\n    \"eventually (\\<lambda>x. DERIV g0 x :> g' x) (at_right 0)\"\n  assumes lim: \"((\\<lambda> x. (f' x / g' x)) ---> x) (at_right 0)\"\n  shows \"((\\<lambda> x. f0 x / g0 x) ---> x) (at_right 0)\"\nproof -\n  def f \\<equiv> \"\\<lambda>x. if x \\<le> 0 then 0 else f0 x\"\n  then have \"f 0 = 0\" by simp\n\n  def g \\<equiv> \"\\<lambda>x. if x \\<le> 0 then 0 else g0 x\"\n  then have \"g 0 = 0\" by simp\n\n  have \"eventually (\\<lambda>x. g0 x \\<noteq> 0 \\<and> g' x \\<noteq> 0 \\<and>\n      DERIV f0 x :> (f' x) \\<and> DERIV g0 x :> (g' x)) (at_right 0)\"\n    using ev by eventually_elim auto\n  then obtain a where [arith]: \"0 < a\"\n    and g0_neq_0: \"\\<And>x. 0 < x \\<Longrightarrow> x < a \\<Longrightarrow> g0 x \\<noteq> 0\"\n    and g'_neq_0: \"\\<And>x. 0 < x \\<Longrightarrow> x < a \\<Longrightarrow> g' x \\<noteq> 0\"\n    and f0: \"\\<And>x. 0 < x \\<Longrightarrow> x < a \\<Longrightarrow> DERIV f0 x :> (f' x)\"\n    and g0: \"\\<And>x. 0 < x \\<Longrightarrow> x < a \\<Longrightarrow> DERIV g0 x :> (g' x)\"\n    unfolding eventually_at by (auto simp: dist_real_def)\n\n  have g_neq_0: \"\\<And>x. 0 < x \\<Longrightarrow> x < a \\<Longrightarrow> g x \\<noteq> 0\"\n    using g0_neq_0 by (simp add: g_def)\n\n  { fix x assume x: \"0 < x\" \"x < a\" then have \"DERIV f x :> (f' x)\"\n      by (intro DERIV_cong_ev[THEN iffD1, OF _ _ _ f0[OF x]])\n         (auto simp: f_def eventually_nhds_metric dist_real_def intro!: exI[of _ x]) }\n  note f = this\n\n  { fix x assume x: \"0 < x\" \"x < a\" then have \"DERIV g x :> (g' x)\"\n      by (intro DERIV_cong_ev[THEN iffD1, OF _ _ _ g0[OF x]])\n         (auto simp: g_def eventually_nhds_metric dist_real_def intro!: exI[of _ x]) }\n  note g = this\n\n  have \"isCont f 0\"\n    unfolding f_def by (intro isCont_If_ge f_0 continuous_const)\n\n  have \"isCont g 0\"\n    unfolding g_def by (intro isCont_If_ge g_0 continuous_const)\n\n  have \"\\<exists>\\<zeta>. \\<forall>x\\<in>{0 <..< a}. 0 < \\<zeta> x \\<and> \\<zeta> x < x \\<and> f x / g x = f' (\\<zeta> x) / g' (\\<zeta> x)\"\n  proof (rule bchoice, rule)\n    fix x assume \"x \\<in> {0 <..< a}\"\n    then have x[arith]: \"0 < x\" \"x < a\" by auto\n    with g'_neq_0 g_neq_0 `g 0 = 0` have g': \"\\<And>x. 0 < x \\<Longrightarrow> x < a  \\<Longrightarrow> 0 \\<noteq> g' x\" \"g 0 \\<noteq> g x\"\n      by auto\n    have \"\\<And>x. 0 \\<le> x \\<Longrightarrow> x < a \\<Longrightarrow> isCont f x\"\n      using `isCont f 0` f by (auto intro: DERIV_isCont simp: le_less)\n    moreover have \"\\<And>x. 0 \\<le> x \\<Longrightarrow> x < a \\<Longrightarrow> isCont g x\"\n      using `isCont g 0` g by (auto intro: DERIV_isCont simp: le_less)\n    ultimately have \"\\<exists>c. 0 < c \\<and> c < x \\<and> (f x - f 0) * g' c = (g x - g 0) * f' c\"\n      using f g `x < a` by (intro GMVT') auto\n    then obtain c where *: \"0 < c\" \"c < x\" \"(f x - f 0) * g' c = (g x - g 0) * f' c\"\n      by blast\n    moreover\n    from * g'(1)[of c] g'(2) have \"(f x - f 0)  / (g x - g 0) = f' c / g' c\"\n      by (simp add: field_simps)\n    ultimately show \"\\<exists>y. 0 < y \\<and> y < x \\<and> f x / g x = f' y / g' y\"\n      using `f 0 = 0` `g 0 = 0` by (auto intro!: exI[of _ c])\n  qed\n  then obtain \\<zeta> where \"\\<forall>x\\<in>{0 <..< a}. 0 < \\<zeta> x \\<and> \\<zeta> x < x \\<and> f x / g x = f' (\\<zeta> x) / g' (\\<zeta> x)\" ..\n  then have \\<zeta>: \"eventually (\\<lambda>x. 0 < \\<zeta> x \\<and> \\<zeta> x < x \\<and> f x / g x = f' (\\<zeta> x) / g' (\\<zeta> x)) (at_right 0)\"\n    unfolding eventually_at by (intro exI[of _ a]) (auto simp: dist_real_def)\n  moreover\n  from \\<zeta> have \"eventually (\\<lambda>x. norm (\\<zeta> x) \\<le> x) (at_right 0)\"\n    by eventually_elim auto\n  then have \"((\\<lambda>x. norm (\\<zeta> x)) ---> 0) (at_right 0)\"\n    by (rule_tac real_tendsto_sandwich[where f=\"\\<lambda>x. 0\" and h=\"\\<lambda>x. x\"]) auto\n  then have \"(\\<zeta> ---> 0) (at_right 0)\"\n    by (rule tendsto_norm_zero_cancel)\n  with \\<zeta> have \"filterlim \\<zeta> (at_right 0) (at_right 0)\"\n    by (auto elim!: eventually_elim1 simp: filterlim_at)\n  from this lim have \"((\\<lambda>t. f' (\\<zeta> t) / g' (\\<zeta> t)) ---> x) (at_right 0)\"\n    by (rule_tac filterlim_compose[of _ _ _ \\<zeta>])\n  ultimately have \"((\\<lambda>t. f t / g t) ---> x) (at_right 0)\" (is ?P)\n    by (rule_tac filterlim_cong[THEN iffD1, OF refl refl])\n       (auto elim: eventually_elim1)\n  also have \"?P \\<longleftrightarrow> ?thesis\"\n    by (rule filterlim_cong) (auto simp: f_def g_def eventually_at_filter)\n  finally show ?thesis .\nqed\n\nlemma lhopital_right:\n  \"((f::real \\<Rightarrow> real) ---> 0) (at_right x) \\<Longrightarrow> (g ---> 0) (at_right x) \\<Longrightarrow>\n    eventually (\\<lambda>x. g x \\<noteq> 0) (at_right x) \\<Longrightarrow>\n    eventually (\\<lambda>x. g' x \\<noteq> 0) (at_right x) \\<Longrightarrow>\n    eventually (\\<lambda>x. DERIV f x :> f' x) (at_right x) \\<Longrightarrow>\n    eventually (\\<lambda>x. DERIV g x :> g' x) (at_right x) \\<Longrightarrow>\n    ((\\<lambda> x. (f' x / g' x)) ---> y) (at_right x) \\<Longrightarrow>\n  ((\\<lambda> x. f x / g x) ---> y) (at_right x)\"\n  unfolding eventually_at_right_to_0[of _ x] filterlim_at_right_to_0[of _ _ x] DERIV_shift\n  by (rule lhopital_right_0)\n\nlemma lhopital_left:\n  \"((f::real \\<Rightarrow> real) ---> 0) (at_left x) \\<Longrightarrow> (g ---> 0) (at_left x) \\<Longrightarrow>\n    eventually (\\<lambda>x. g x \\<noteq> 0) (at_left x) \\<Longrightarrow>\n    eventually (\\<lambda>x. g' x \\<noteq> 0) (at_left x) \\<Longrightarrow>\n    eventually (\\<lambda>x. DERIV f x :> f' x) (at_left x) \\<Longrightarrow>\n    eventually (\\<lambda>x. DERIV g x :> g' x) (at_left x) \\<Longrightarrow>\n    ((\\<lambda> x. (f' x / g' x)) ---> y) (at_left x) \\<Longrightarrow>\n  ((\\<lambda> x. f x / g x) ---> y) (at_left x)\"\n  unfolding eventually_at_left_to_right filterlim_at_left_to_right DERIV_mirror\n  by (rule lhopital_right[where f'=\"\\<lambda>x. - f' (- x)\"]) (auto simp: DERIV_mirror)\n\nlemma lhopital:\n  \"((f::real \\<Rightarrow> real) ---> 0) (at x) \\<Longrightarrow> (g ---> 0) (at x) \\<Longrightarrow>\n    eventually (\\<lambda>x. g x \\<noteq> 0) (at x) \\<Longrightarrow>\n    eventually (\\<lambda>x. g' x \\<noteq> 0) (at x) \\<Longrightarrow>\n    eventually (\\<lambda>x. DERIV f x :> f' x) (at x) \\<Longrightarrow>\n    eventually (\\<lambda>x. DERIV g x :> g' x) (at x) \\<Longrightarrow>\n    ((\\<lambda> x. (f' x / g' x)) ---> y) (at x) \\<Longrightarrow>\n  ((\\<lambda> x. f x / g x) ---> y) (at x)\"\n  unfolding eventually_at_split filterlim_at_split\n  by (auto intro!: lhopital_right[of f x g g' f'] lhopital_left[of f x g g' f'])\n\nlemma lhopital_right_0_at_top:\n  fixes f g :: \"real \\<Rightarrow> real\"\n  assumes g_0: \"LIM x at_right 0. g x :> at_top\"\n  assumes ev:\n    \"eventually (\\<lambda>x. g' x \\<noteq> 0) (at_right 0)\"\n    \"eventually (\\<lambda>x. DERIV f x :> f' x) (at_right 0)\"\n    \"eventually (\\<lambda>x. DERIV g x :> g' x) (at_right 0)\"\n  assumes lim: \"((\\<lambda> x. (f' x / g' x)) ---> x) (at_right 0)\"\n  shows \"((\\<lambda> x. f x / g x) ---> x) (at_right 0)\"\n  unfolding tendsto_iff\nproof safe\n  fix e :: real assume \"0 < e\"\n\n  with lim[unfolded tendsto_iff, rule_format, of \"e / 4\"]\n  have \"eventually (\\<lambda>t. dist (f' t / g' t) x < e / 4) (at_right 0)\" by simp\n  from eventually_conj[OF eventually_conj[OF ev(1) ev(2)] eventually_conj[OF ev(3) this]]\n  obtain a where [arith]: \"0 < a\"\n    and g'_neq_0: \"\\<And>x. 0 < x \\<Longrightarrow> x < a \\<Longrightarrow> g' x \\<noteq> 0\"\n    and f0: \"\\<And>x. 0 < x \\<Longrightarrow> x \\<le> a \\<Longrightarrow> DERIV f x :> (f' x)\"\n    and g0: \"\\<And>x. 0 < x \\<Longrightarrow> x \\<le> a \\<Longrightarrow> DERIV g x :> (g' x)\"\n    and Df: \"\\<And>t. 0 < t \\<Longrightarrow> t < a \\<Longrightarrow> dist (f' t / g' t) x < e / 4\"\n    unfolding eventually_at_le by (auto simp: dist_real_def)\n    \n\n  from Df have\n    \"eventually (\\<lambda>t. t < a) (at_right 0)\" \"eventually (\\<lambda>t::real. 0 < t) (at_right 0)\"\n    unfolding eventually_at by (auto intro!: exI[of _ a] simp: dist_real_def)\n\n  moreover\n  have \"eventually (\\<lambda>t. 0 < g t) (at_right 0)\" \"eventually (\\<lambda>t. g a < g t) (at_right 0)\"\n    using g_0 by (auto elim: eventually_elim1 simp: filterlim_at_top_dense)\n\n  moreover\n  have inv_g: \"((\\<lambda>x. inverse (g x)) ---> 0) (at_right 0)\"\n    using tendsto_inverse_0 filterlim_mono[OF g_0 at_top_le_at_infinity order_refl]\n    by (rule filterlim_compose)\n  then have \"((\\<lambda>x. norm (1 - g a * inverse (g x))) ---> norm (1 - g a * 0)) (at_right 0)\"\n    by (intro tendsto_intros)\n  then have \"((\\<lambda>x. norm (1 - g a / g x)) ---> 1) (at_right 0)\"\n    by (simp add: inverse_eq_divide)\n  from this[unfolded tendsto_iff, rule_format, of 1]\n  have \"eventually (\\<lambda>x. norm (1 - g a / g x) < 2) (at_right 0)\"\n    by (auto elim!: eventually_elim1 simp: dist_real_def)\n\n  moreover\n  from inv_g have \"((\\<lambda>t. norm ((f a - x * g a) * inverse (g t))) ---> norm ((f a - x * g a) * 0)) (at_right 0)\"\n    by (intro tendsto_intros)\n  then have \"((\\<lambda>t. norm (f a - x * g a) / norm (g t)) ---> 0) (at_right 0)\"\n    by (simp add: inverse_eq_divide)\n  from this[unfolded tendsto_iff, rule_format, of \"e / 2\"] `0 < e`\n  have \"eventually (\\<lambda>t. norm (f a - x * g a) / norm (g t) < e / 2) (at_right 0)\"\n    by (auto simp: dist_real_def)\n\n  ultimately show \"eventually (\\<lambda>t. dist (f t / g t) x < e) (at_right 0)\"\n  proof eventually_elim\n    fix t assume t[arith]: \"0 < t\" \"t < a\" \"g a < g t\" \"0 < g t\"\n    assume ineq: \"norm (1 - g a / g t) < 2\" \"norm (f a - x * g a) / norm (g t) < e / 2\"\n\n    have \"\\<exists>y. t < y \\<and> y < a \\<and> (g a - g t) * f' y = (f a - f t) * g' y\"\n      using f0 g0 t(1,2) by (intro GMVT') (force intro!: DERIV_isCont)+\n    then obtain y where [arith]: \"t < y\" \"y < a\"\n      and D_eq0: \"(g a - g t) * f' y = (f a - f t) * g' y\"\n      by blast\n    from D_eq0 have D_eq: \"(f t - f a) / (g t - g a) = f' y / g' y\"\n      using `g a < g t` g'_neq_0[of y] by (auto simp add: field_simps)\n\n    have *: \"f t / g t - x = ((f t - f a) / (g t - g a) - x) * (1 - g a / g t) + (f a - x * g a) / g t\"\n      by (simp add: field_simps)\n    have \"norm (f t / g t - x) \\<le>\n        norm (((f t - f a) / (g t - g a) - x) * (1 - g a / g t)) + norm ((f a - x * g a) / g t)\"\n      unfolding * by (rule norm_triangle_ineq)\n    also have \"\\<dots> = dist (f' y / g' y) x * norm (1 - g a / g t) + norm (f a - x * g a) / norm (g t)\"\n      by (simp add: abs_mult D_eq dist_real_def)\n    also have \"\\<dots> < (e / 4) * 2 + e / 2\"\n      using ineq Df[of y] `0 < e` by (intro add_le_less_mono mult_mono) auto\n    finally show \"dist (f t / g t) x < e\"\n      by (simp add: dist_real_def)\n  qed\nqed\n\nlemma lhopital_right_at_top:\n  \"LIM x at_right x. (g::real \\<Rightarrow> real) x :> at_top \\<Longrightarrow>\n    eventually (\\<lambda>x. g' x \\<noteq> 0) (at_right x) \\<Longrightarrow>\n    eventually (\\<lambda>x. DERIV f x :> f' x) (at_right x) \\<Longrightarrow>\n    eventually (\\<lambda>x. DERIV g x :> g' x) (at_right x) \\<Longrightarrow>\n    ((\\<lambda> x. (f' x / g' x)) ---> y) (at_right x) \\<Longrightarrow>\n    ((\\<lambda> x. f x / g x) ---> y) (at_right x)\"\n  unfolding eventually_at_right_to_0[of _ x] filterlim_at_right_to_0[of _ _ x] DERIV_shift\n  by (rule lhopital_right_0_at_top)\n\nlemma lhopital_left_at_top:\n  \"LIM x at_left x. (g::real \\<Rightarrow> real) x :> at_top \\<Longrightarrow>\n    eventually (\\<lambda>x. g' x \\<noteq> 0) (at_left x) \\<Longrightarrow>\n    eventually (\\<lambda>x. DERIV f x :> f' x) (at_left x) \\<Longrightarrow>\n    eventually (\\<lambda>x. DERIV g x :> g' x) (at_left x) \\<Longrightarrow>\n    ((\\<lambda> x. (f' x / g' x)) ---> y) (at_left x) \\<Longrightarrow>\n    ((\\<lambda> x. f x / g x) ---> y) (at_left x)\"\n  unfolding eventually_at_left_to_right filterlim_at_left_to_right DERIV_mirror\n  by (rule lhopital_right_at_top[where f'=\"\\<lambda>x. - f' (- x)\"]) (auto simp: DERIV_mirror)\n\nlemma lhopital_at_top:\n  \"LIM x at x. (g::real \\<Rightarrow> real) x :> at_top \\<Longrightarrow>\n    eventually (\\<lambda>x. g' x \\<noteq> 0) (at x) \\<Longrightarrow>\n    eventually (\\<lambda>x. DERIV f x :> f' x) (at x) \\<Longrightarrow>\n    eventually (\\<lambda>x. DERIV g x :> g' x) (at x) \\<Longrightarrow>\n    ((\\<lambda> x. (f' x / g' x)) ---> y) (at x) \\<Longrightarrow>\n    ((\\<lambda> x. f x / g x) ---> y) (at x)\"\n  unfolding eventually_at_split filterlim_at_split\n  by (auto intro!: lhopital_right_at_top[of g x g' f f'] lhopital_left_at_top[of g x g' f f'])\n\nlemma lhospital_at_top_at_top:\n  fixes f g :: \"real \\<Rightarrow> real\"\n  assumes g_0: \"LIM x at_top. g x :> at_top\"\n  assumes g': \"eventually (\\<lambda>x. g' x \\<noteq> 0) at_top\"\n  assumes Df: \"eventually (\\<lambda>x. DERIV f x :> f' x) at_top\"\n  assumes Dg: \"eventually (\\<lambda>x. DERIV g x :> g' x) at_top\"\n  assumes lim: \"((\\<lambda> x. (f' x / g' x)) ---> x) at_top\"\n  shows \"((\\<lambda> x. f x / g x) ---> x) at_top\"\n  unfolding filterlim_at_top_to_right\nproof (rule lhopital_right_0_at_top)\n  let ?F = \"\\<lambda>x. f (inverse x)\"\n  let ?G = \"\\<lambda>x. g (inverse x)\"\n  let ?R = \"at_right (0::real)\"\n  let ?D = \"\\<lambda>f' x. f' (inverse x) * - (inverse x ^ Suc (Suc 0))\"\n\n  show \"LIM x ?R. ?G x :> at_top\"\n    using g_0 unfolding filterlim_at_top_to_right .\n\n  show \"eventually (\\<lambda>x. DERIV ?G x  :> ?D g' x) ?R\"\n    unfolding eventually_at_right_to_top\n    using Dg eventually_ge_at_top[where c=\"1::real\"]\n    apply eventually_elim\n    apply (rule DERIV_cong)\n    apply (rule DERIV_chain'[where f=inverse])\n    apply (auto intro!:  DERIV_inverse)\n    done\n\n  show \"eventually (\\<lambda>x. DERIV ?F x  :> ?D f' x) ?R\"\n    unfolding eventually_at_right_to_top\n    using Df eventually_ge_at_top[where c=\"1::real\"]\n    apply eventually_elim\n    apply (rule DERIV_cong)\n    apply (rule DERIV_chain'[where f=inverse])\n    apply (auto intro!:  DERIV_inverse)\n    done\n\n  show \"eventually (\\<lambda>x. ?D g' x \\<noteq> 0) ?R\"\n    unfolding eventually_at_right_to_top\n    using g' eventually_ge_at_top[where c=\"1::real\"]\n    by eventually_elim auto\n    \n  show \"((\\<lambda>x. ?D f' x / ?D g' x) ---> x) ?R\"\n    unfolding filterlim_at_right_to_top\n    apply (intro filterlim_cong[THEN iffD2, OF refl refl _ lim])\n    using eventually_ge_at_top[where c=\"1::real\"]\n    by eventually_elim 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/Deriv.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8740772482857833, "lm_q2_score": 0.8499711699569786, "lm_q1q2_score": 0.7429404613582437}}
{"text": "(*\n  File:     PAPP_Multiset_Extras.thy\n  Author:   Manuel Eberl, University of Innsbruck \n*)\nsection \\<open>Auxiliary Facts About Multisets\\<close>\ntheory PAPP_Multiset_Extras\n  imports \"HOL-Library.Multiset\"\nbegin\n\ntext \\<open>\n  This section contains a number of not particularly interesting small facts about multisets.\n\\<close>\n\nlemma mset_set_subset_iff: \"finite A \\<Longrightarrow> mset_set A \\<subseteq># B \\<longleftrightarrow> A \\<subseteq> set_mset B\"\n  by (metis finite_set_mset finite_set_mset_mset_set mset_set_set_mset_msubset \n            msubset_mset_set_iff set_mset_mono subset_mset.trans)\n\nlemma mset_subset_size_ge_imp_eq:\n  assumes \"A \\<subseteq># B\" \"size A \\<ge> size B\"\n  shows   \"A = B\"\n  using assms\nproof (induction A arbitrary: B)\n  case empty\n  thus ?case by auto\nnext\n  case (add x A B)\n  have [simp]: \"x \\<in># B\"\n    using add.prems  by (simp add: insert_subset_eq_iff)\n  define B' where \"B' = B - {#x#}\"\n  have B_eq: \"B = add_mset x B'\"\n    using add.prems unfolding B'_def by (auto simp: add_mset_remove_trivial_If)\n  have \"A = B'\"\n    using add.prems by (intro add.IH) (auto simp: B_eq)\n  thus ?case\n    by (auto simp: B_eq)\nqed\n\nlemma mset_psubset_iff:\n  \"X \\<subset># Y \\<longleftrightarrow> X \\<subseteq># Y \\<and> (\\<exists>x. count X x < count Y x)\"\n  by (meson less_le_not_le subset_mset.less_le_not_le subseteq_mset_def)\n  \nlemma count_le_size: \"count A x \\<le> size A\"\n  by (induction A) auto\n\nlemma size_filter_eq_conv_count [simp]: \"size (filter_mset (\\<lambda>y. y = x) A) = count A x\"\n  by (induction A) auto\n\nlemma multiset_filter_mono':\n  assumes \"\\<And>x. x \\<in># A \\<Longrightarrow> P x \\<Longrightarrow> Q x\"\n  shows   \"filter_mset P A \\<subseteq># filter_mset Q A\"\n  using assms by (induction A)  (auto simp: subset_mset.absorb_iff1 add_mset_union)\n\nlemma multiset_filter_mono'':\n  assumes \"A \\<subseteq># B\" \"\\<And>x. x \\<in># A \\<Longrightarrow> P x \\<Longrightarrow> Q x\"\n  shows \"filter_mset P A \\<subseteq># filter_mset Q B\"\n  using assms multiset_filter_mono multiset_filter_mono'\n  by (metis subset_mset.order_trans)\n\nlemma filter_mset_disjunction:\n  assumes \"\\<And>x. x \\<in># X \\<Longrightarrow> P x \\<Longrightarrow> Q x \\<Longrightarrow> False\"\n  shows   \"filter_mset (\\<lambda>x. P x \\<or> Q x) X = filter_mset P X + filter_mset Q X\"\n  using assms by (induction X) auto\n  \nlemma size_mset_sum_mset: \"size (sum_mset X) = (\\<Sum>x\\<in>#X. size (x :: 'a multiset))\"\n  by (induction X) auto\n\nlemma count_sum_mset: \"count (sum_mset X) x = (\\<Sum>Y\\<in>#X. count Y x)\"\n  by (induction X) auto\n\nlemma replicate_mset_rec: \"n > 0 \\<Longrightarrow> replicate_mset n x = add_mset x (replicate_mset (n - 1) x)\"\n  by (cases n) auto\n\nlemma add_mset_neq: \"x \\<notin># B \\<Longrightarrow> add_mset x A \\<noteq> B\"\n  by force\n\nlemma filter_replicate_mset:\n  \"filter_mset P (replicate_mset n x) = (if P x then replicate_mset n x else {#})\"\n  by (induction n) auto\n\nlemma filter_diff_mset': \"filter_mset P (X - Y) = filter_mset P X - Y\"\n  by (rule multiset_eqI) auto\n\nlemma in_diff_multiset_absorb2: \"x \\<notin># B \\<Longrightarrow> x \\<in># A - B \\<longleftrightarrow> x \\<in># A\"\n  by (metis count_greater_zero_iff count_inI in_diff_count)\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/PAPP_Impossibility/PAPP_Multiset_Extras.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8740772351648678, "lm_q2_score": 0.8499711794579723, "lm_q1q2_score": 0.7429404585104461}}
{"text": "(*  Title:       Examples of hybrid systems verifications\n    Author:      Jonathan Juli\u00e1n Huerta y Munive, 2020\n    Maintainer:  Jonathan Juli\u00e1n 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\nrecently described verification components.\\<close>\n\ntheory HS_VC_MKA_Examples_rel\n  imports HS_VC_MKA_rel\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\n  else - s$1 * sin t + s$2 * cos t)\"\n\n\\<comment> \\<open>Verified by providing dynamics. \\<close>\n\nlemma pendulum_dyn:\n  \"\\<lceil>\\<lambda>s. r\\<^sup>2 = (s$1)\\<^sup>2 + (s$2)\\<^sup>2\\<rceil> \\<le> wp (EVOL \\<phi> G T) \\<lceil>\\<lambda>s. r\\<^sup>2 = (s$1)\\<^sup>2 + (s$2)\\<^sup>2\\<rceil>\"\n  by simp\n\n\\<comment> \\<open>Verified with differential invariants. \\<close>\n\nlemma pendulum_inv:\n  \"\\<lceil>\\<lambda>s. r\\<^sup>2 = (s$1)\\<^sup>2 + (s$2)\\<^sup>2\\<rceil> \\<le> wp (x\\<acute>= f & G) \\<lceil>\\<lambda>s. r\\<^sup>2 = (s$1)\\<^sup>2 + (s$2)\\<^sup>2\\<rceil>\"\n  by (auto intro!: poly_derivatives diff_invariant_rules)\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:\n  \"\\<lceil>\\<lambda>s. r\\<^sup>2 = (s$1)\\<^sup>2 + (s$2)\\<^sup>2\\<rceil> \\<le> wp (x\\<acute>= f & G) \\<lceil>\\<lambda>s. r\\<^sup>2 = (s$1)\\<^sup>2 + (s$2)\\<^sup>2\\<rceil>\"\n  by (simp add: local_flow.wp_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 bouncing_ball_inv:\n  fixes h::real\n  shows \"g < 0 \\<Longrightarrow> h \\<ge> 0 \\<Longrightarrow> \\<lceil>\\<lambda>s. s$1 = h \\<and> s$2 = 0\\<rceil> \\<le>\n  wp\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  ) \\<lceil>\\<lambda>s. 0 \\<le> s$1 \\<and> s$1 \\<le> h\\<rceil>\"\n  apply(rule wp_loopI, simp_all, force simp: bb_real_arith)\n  by (rule wp_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> * (g * \\<tau> + v) + 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, opaque_lifting) 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, opaque_lifting) 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> * (g * \\<tau> + v) + v * (g * \\<tau> + v)) = 0\"\n    by (simp add: monoid_mult_class.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> * (g * \\<tau> + v) + 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:\n  fixes h::real\n  assumes \"g < 0\" and \"h \\<ge> 0\"\n  shows \"g < 0 \\<Longrightarrow> h \\<ge> 0 \\<Longrightarrow>\n  \\<lceil>\\<lambda>s. s$1 = h \\<and> s$2 = 0\\<rceil> \\<le> wp\n    (LOOP\n      ((EVOL (\\<phi> g) (\\<lambda>s. 0 \\<le> s$1) 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  \\<lceil>\\<lambda>s. 0 \\<le> s$1 \\<and> s$1 \\<le> h\\<rceil>\"\n  by (rule wp_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:\n  fixes h::real\n  assumes \"g < 0\" and \"h \\<ge> 0\"\n  shows \"g < 0 \\<Longrightarrow> h \\<ge> 0 \\<Longrightarrow>\n  \\<lceil>\\<lambda>s. s$1 = h \\<and> s$2 = 0\\<rceil> \\<le> wp\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  \\<lceil>\\<lambda>s. 0 \\<le> s$1 \\<and> s$1 \\<le> h\\<rceil>\"\n  apply(rule wp_loopI, simp_all add: local_flow.wp_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_all 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.wp_g_ode_subset[OF local_flow_temp]\n\nlemma thermostat:\n  assumes \"a > 0\" and \"0 < Tmin\" and \"Tmax < L\"\n  shows \"\\<lceil>\\<lambda>s. Tmin \\<le> s$1 \\<and> s$1 \\<le> Tmax \\<and> s$4 = 0\\<rceil> \\<le> wp\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  \\<lceil>\\<lambda>s. Tmin \\<le> s$1 \\<and> s$1 \\<le> Tmax\\<rceil>\"\n  apply(rule wp_loopI, simp_all add: fbox_temp_dyn[OF assms(1)])\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 \"\\<lceil>\\<lambda>s. I hmin hmax s\\<rceil> \\<le> wp\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  \\<lceil>\\<lambda>s. I hmin hmax s\\<rceil>\"\n  apply(rule wp_loopI, simp_all add: local_flow.wp_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/ModalKleeneAlgebra/HS_VC_MKA_Examples_rel.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8740772253241802, "lm_q2_score": 0.849971181358171, "lm_q1q2_score": 0.7429404518070656}}
{"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_08\n  imports \"../../Test_Base\"\nbegin\n\ndatatype 'a list = nil2 | cons2 \"'a\" \"'a list\"\n\ndatatype Nat = Z | S \"Nat\"\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\nlemma drop_nil: \"drop n nil2 = nil2\"\n  by(case_tac n, auto)\n\n(*\nlemma drop_succ: \"drop (S n) (drop m l) = drop n (drop (S m) l)\"\n  apply(induction l)\n   apply(simp add: drop_nil, simp)\n  apply(induction m, auto)\n  apply(case_tac l, simp add: drop_nil, auto)\n  done\n\ntheorem property0 :\n  \"((drop x (drop y z)) = (drop y (drop x z)))\"\n  apply(induct z rule: drop.induct, auto)\n  apply(case_tac y, auto)\n  apply(simp add: drop_succ)\n  done\n*)\n\nlemma bottom_up_nested_drop_and_S:\n  \"drop (S n) (drop m l) = drop n (drop (S m) l)\"\n  apply(induct l)\n   apply (simp add: drop_nil)\n  apply clarsimp\n  apply(induct m)\n   apply fastforce\n  apply clarsimp\n  apply(case_tac l)(*sledgehammer can solve this as well*)\n   apply(simp add: drop_nil)+\n  done\n\n(* declare [[show_types]] *)\n(* Due to the fixed type variable caused by the \"assumes\" keyword, we cannot use the standard \n * technique for abductive reasoning. *)\n(*\nlemma subgoal_as_a_separate_lemma:\n (*assumes \"TIP_prop_08.drop (S (n::Nat)) (TIP_prop_08.drop (m::Nat) (l::'a TIP_prop_08.list)) = TIP_prop_08.drop n (TIP_prop_08.drop (S m) l)\"*)\n  shows \"drop    z  (drop y           x3 ) = drop y (drop z x3) \\<Longrightarrow>\n         drop (S z) (drop y (cons2 x2 x3)) = drop y (drop z x3)\"\n  apply(simp add: bottom_up_nested_drop_and_S)\n  done\n*)\ntheorem property: \"((drop x (drop y z)) = (drop y (drop x z)))\"\n  apply(induct z rule: drop.induct)\n    apply (simp add: drop_nil)\n   apply (simp add: drop_nil)\n  apply clarsimp\n  by (simp add: bottom_up_nested_drop_and_S)\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/Prod/Prod/TIP_prop_08.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772286044094, "lm_q2_score": 0.8499711699569787, "lm_q1q2_score": 0.7429404446296434}}
{"text": "section\\<open>T1 and Hausdorff spaces\\<close>\n\ntheory T1_Spaces\nimports Product_Topology\nbegin\n\nsection\\<open>T1 spaces with equivalences to many naturally \"nice\" properties. \\<close>\n\ndefinition t1_space where\n \"t1_space X \\<equiv> \\<forall>x \\<in> topspace X. \\<forall>y \\<in> topspace X. x\\<noteq>y \\<longrightarrow> (\\<exists>U. openin X U \\<and> x \\<in> U \\<and> y \\<notin> U)\"\n\nlemma t1_space_expansive:\n   \"\\<lbrakk>topspace Y = topspace X; \\<And>U. openin X U \\<Longrightarrow> openin Y U\\<rbrakk> \\<Longrightarrow> t1_space X \\<Longrightarrow> t1_space Y\"\n  by (metis t1_space_def)\n\nlemma t1_space_alt:\n   \"t1_space X \\<longleftrightarrow> (\\<forall>x \\<in> topspace X. \\<forall>y \\<in> topspace X. x\\<noteq>y \\<longrightarrow> (\\<exists>U. closedin X U \\<and> x \\<in> U \\<and> y \\<notin> U))\"\n by (metis DiffE DiffI closedin_def openin_closedin_eq t1_space_def)\n\nlemma t1_space_empty: \"topspace X = {} \\<Longrightarrow> t1_space X\"\n  by (simp add: t1_space_def)\n\nlemma t1_space_derived_set_of_singleton:\n  \"t1_space X \\<longleftrightarrow> (\\<forall>x \\<in> topspace X. X derived_set_of {x} = {})\"\n  apply (simp add: t1_space_def derived_set_of_def, safe)\n   apply (metis openin_topspace)\n  by force\n\nlemma t1_space_derived_set_of_finite:\n   \"t1_space X \\<longleftrightarrow> (\\<forall>S. finite S \\<longrightarrow> X derived_set_of S = {})\"\nproof (intro iffI allI impI)\n  fix S :: \"'a set\"\n  assume \"finite S\"\n  then have fin: \"finite ((\\<lambda>x. {x}) ` (topspace X \\<inter> S))\"\n    by blast\n  assume \"t1_space X\"\n  then have \"X derived_set_of (\\<Union>x \\<in> topspace X \\<inter> S. {x}) = {}\"\n    unfolding derived_set_of_Union [OF fin]\n    by (auto simp: t1_space_derived_set_of_singleton)\n  then have \"X derived_set_of (topspace X \\<inter> S) = {}\"\n    by simp\n  then show \"X derived_set_of S = {}\"\n    by simp\nqed (auto simp: t1_space_derived_set_of_singleton)\n\nlemma t1_space_closedin_singleton:\n   \"t1_space X \\<longleftrightarrow> (\\<forall>x \\<in> topspace X. closedin X {x})\"\n  apply (rule iffI)\n  apply (simp add: closedin_contains_derived_set t1_space_derived_set_of_singleton)\n  using t1_space_alt by auto\n\nlemma closedin_t1_singleton:\n   \"\\<lbrakk>t1_space X; a \\<in> topspace X\\<rbrakk> \\<Longrightarrow> closedin X {a}\"\n  by (simp add: t1_space_closedin_singleton)\n\nlemma t1_space_closedin_finite:\n   \"t1_space X \\<longleftrightarrow> (\\<forall>S. finite S \\<and> S \\<subseteq> topspace X \\<longrightarrow> closedin X S)\"\n  apply (rule iffI)\n  apply (simp add: closedin_contains_derived_set t1_space_derived_set_of_finite)\n  by (simp add: t1_space_closedin_singleton)\n\nlemma closure_of_singleton:\n   \"t1_space X \\<Longrightarrow> X closure_of {a} = (if a \\<in> topspace X then {a} else {})\"\n  by (simp add: closure_of_eq t1_space_closedin_singleton closure_of_eq_empty_gen)\n\nlemma separated_in_singleton:\n  assumes \"t1_space X\"\n  shows \"separatedin X {a} S \\<longleftrightarrow> a \\<in> topspace X \\<and> S \\<subseteq> topspace X \\<and> (a \\<notin> X closure_of S)\"\n        \"separatedin X S {a} \\<longleftrightarrow> a \\<in> topspace X \\<and> S \\<subseteq> topspace X \\<and> (a \\<notin> X closure_of S)\"\n  unfolding separatedin_def\n  using assms closure_of closure_of_singleton by fastforce+\n\nlemma t1_space_openin_delete:\n   \"t1_space X \\<longleftrightarrow> (\\<forall>U x. openin X U \\<and> x \\<in> U \\<longrightarrow> openin X (U - {x}))\"\n  apply (rule iffI)\n  apply (meson closedin_t1_singleton in_mono openin_diff openin_subset)\n  by (simp add: closedin_def t1_space_closedin_singleton)\n\nlemma t1_space_openin_delete_alt:\n   \"t1_space X \\<longleftrightarrow> (\\<forall>U x. openin X U \\<longrightarrow> openin X (U - {x}))\"\n  by (metis Diff_empty Diff_insert0 t1_space_openin_delete)\n\n\nlemma t1_space_singleton_Inter_open:\n      \"t1_space X \\<longleftrightarrow> (\\<forall>x \\<in> topspace X. \\<Inter>{U. openin X U \\<and> x \\<in> U} = {x})\"  (is \"?P=?Q\")\n  and t1_space_Inter_open_supersets:\n     \"t1_space X \\<longleftrightarrow> (\\<forall>S. S \\<subseteq> topspace X \\<longrightarrow> \\<Inter>{U. openin X U \\<and> S \\<subseteq> U} = S)\" (is \"?P=?R\")\nproof -\n  have \"?R \\<Longrightarrow> ?Q\"\n    apply clarify\n    apply (drule_tac x=\"{x}\" in spec, simp)\n    done\n  moreover have \"?Q \\<Longrightarrow> ?P\"\n    apply (clarsimp simp add: t1_space_def)\n    apply (drule_tac x=x in bspec)\n     apply (simp_all add: set_eq_iff)\n    by (metis (no_types, lifting))\n  moreover have \"?P \\<Longrightarrow> ?R\"\n  proof (clarsimp simp add: t1_space_closedin_singleton, rule subset_antisym)\n    fix S\n    assume S: \"\\<forall>x\\<in>topspace X. closedin X {x}\" \"S \\<subseteq> topspace X\"\n    then show \"\\<Inter> {U. openin X U \\<and> S \\<subseteq> U} \\<subseteq> S\"\n      apply clarsimp\n      by (metis Diff_insert_absorb Set.set_insert closedin_def openin_topspace subset_insert)\n  qed force\n  ultimately show \"?P=?Q\" \"?P=?R\"\n    by auto\nqed\n\nlemma t1_space_derived_set_of_infinite_openin:\n   \"t1_space X \\<longleftrightarrow>\n        (\\<forall>S. X derived_set_of S =\n             {x \\<in> topspace X. \\<forall>U. x \\<in> U \\<and> openin X U \\<longrightarrow> infinite(S \\<inter> U)})\"\n         (is \"_ = ?rhs\")\nproof\n  assume \"t1_space X\"\n  show ?rhs\n  proof safe\n    fix S x U\n    assume \"x \\<in> X derived_set_of S\" \"x \\<in> U\" \"openin X U\" \"finite (S \\<inter> U)\"\n    with \\<open>t1_space X\\<close> show \"False\"\n      apply (simp add: t1_space_derived_set_of_finite)\n      by (metis IntI empty_iff empty_subsetI inf_commute openin_Int_derived_set_of_subset subset_antisym)\n  next\n    fix S x\n    have eq: \"(\\<exists>y. (y \\<noteq> x) \\<and> y \\<in> S \\<and> y \\<in> T) \\<longleftrightarrow> ~((S \\<inter> T) \\<subseteq> {x})\" for x S T\n      by blast\n    assume \"x \\<in> topspace X\" \"\\<forall>U. x \\<in> U \\<and> openin X U \\<longrightarrow> infinite (S \\<inter> U)\"\n    then show \"x \\<in> X derived_set_of S\"\n      apply (clarsimp simp add: derived_set_of_def eq)\n      by (meson finite.emptyI finite.insertI finite_subset)\n  qed (auto simp: in_derived_set_of)\nqed (auto simp: t1_space_derived_set_of_singleton)\n\nlemma finite_t1_space_imp_discrete_topology:\n   \"\\<lbrakk>topspace X = U; finite U; t1_space X\\<rbrakk> \\<Longrightarrow> X = discrete_topology U\"\n  by (metis discrete_topology_unique_derived_set t1_space_derived_set_of_finite)\n\nlemma t1_space_subtopology: \"t1_space X \\<Longrightarrow> t1_space(subtopology X U)\"\n  by (simp add: derived_set_of_subtopology t1_space_derived_set_of_finite)\n\nlemma closedin_derived_set_of_gen:\n   \"t1_space X \\<Longrightarrow> closedin X (X derived_set_of S)\"\n  apply (clarsimp simp add: in_derived_set_of closedin_contains_derived_set derived_set_of_subset_topspace)\n  by (metis DiffD2 insert_Diff insert_iff t1_space_openin_delete)\n\nlemma derived_set_of_derived_set_subset_gen:\n   \"t1_space X \\<Longrightarrow> X derived_set_of (X derived_set_of S) \\<subseteq> X derived_set_of S\"\n  by (meson closedin_contains_derived_set closedin_derived_set_of_gen)\n\nlemma subtopology_eq_discrete_topology_gen_finite:\n   \"\\<lbrakk>t1_space X; finite S\\<rbrakk> \\<Longrightarrow> subtopology X S = discrete_topology(topspace X \\<inter> S)\"\n  by (simp add: subtopology_eq_discrete_topology_gen t1_space_derived_set_of_finite)\n\nlemma subtopology_eq_discrete_topology_finite:\n   \"\\<lbrakk>t1_space X; S \\<subseteq> topspace X; finite S\\<rbrakk>\n        \\<Longrightarrow> subtopology X S = discrete_topology S\"\n  by (simp add: subtopology_eq_discrete_topology_eq t1_space_derived_set_of_finite)\n\nlemma t1_space_closed_map_image:\n   \"\\<lbrakk>closed_map X Y f; f ` (topspace X) = topspace Y; t1_space X\\<rbrakk> \\<Longrightarrow> t1_space Y\"\n  by (metis closed_map_def finite_subset_image t1_space_closedin_finite)\n\nlemma homeomorphic_t1_space: \"X homeomorphic_space Y \\<Longrightarrow> (t1_space X \\<longleftrightarrow> t1_space Y)\"\n  apply (clarsimp simp add: homeomorphic_space_def)\n  by (meson homeomorphic_eq_everything_map homeomorphic_maps_map t1_space_closed_map_image)\n\nproposition t1_space_product_topology:\n   \"t1_space (product_topology X I)\n\\<longleftrightarrow> topspace(product_topology X I) = {} \\<or> (\\<forall>i \\<in> I. t1_space (X i))\"\nproof (cases \"topspace(product_topology X I) = {}\")\n  case True\n  then show ?thesis\n    using True t1_space_empty by blast\nnext\n  case False\n  then obtain f where f: \"f \\<in> (\\<Pi>\\<^sub>E i\\<in>I. topspace(X i))\"\n    by fastforce\n  have \"t1_space (product_topology X I) \\<longleftrightarrow> (\\<forall>i\\<in>I. t1_space (X i))\"\n  proof (intro iffI ballI)\n    show \"t1_space (X i)\" if \"t1_space (product_topology X I)\" and \"i \\<in> I\" for i\n    proof -\n      have clo: \"\\<And>h. h \\<in> (\\<Pi>\\<^sub>E i\\<in>I. topspace (X i)) \\<Longrightarrow> closedin (product_topology X I) {h}\"\n        using that by (simp add: t1_space_closedin_singleton)\n      show ?thesis\n        unfolding t1_space_closedin_singleton\n      proof clarify\n        show \"closedin (X i) {xi}\" if \"xi \\<in> topspace (X i)\" for xi\n          using clo [of \"\\<lambda>j \\<in> I. if i=j then xi else f j\"] f that \\<open>i \\<in> I\\<close>\n          by (fastforce simp add: closedin_product_topology_singleton)\n      qed\n    qed\n  next\n  next\n    show \"t1_space (product_topology X I)\" if \"\\<forall>i\\<in>I. t1_space (X i)\"\n      using that\n      by (simp add: t1_space_closedin_singleton Ball_def PiE_iff closedin_product_topology_singleton)\n  qed\n  then show ?thesis\n    using False by blast\nqed\n\nlemma t1_space_prod_topology:\n   \"t1_space(prod_topology X Y) \\<longleftrightarrow> topspace(prod_topology X Y) = {} \\<or> t1_space X \\<and> t1_space Y\"\nproof (cases \"topspace (prod_topology X Y) = {}\")\n  case True then show ?thesis\n  by (auto simp: t1_space_empty)\nnext\n  case False\n  have eq: \"{(x,y)} = {x} \\<times> {y}\" for x y\n    by simp\n  have \"t1_space (prod_topology X Y) \\<longleftrightarrow> (t1_space X \\<and> t1_space Y)\"\n    using False\n    by (force simp: t1_space_closedin_singleton closedin_prod_Times_iff eq simp del: insert_Times_insert)\n  with False show ?thesis\n    by simp\nqed\n\nsubsection\\<open>Hausdorff Spaces\\<close>\n\ndefinition Hausdorff_space\n  where\n \"Hausdorff_space X \\<equiv>\n        \\<forall>x y. x \\<in> topspace X \\<and> y \\<in> topspace X \\<and> (x \\<noteq> y)\n              \\<longrightarrow> (\\<exists>U V. openin X U \\<and> openin X V \\<and> x \\<in> U \\<and> y \\<in> V \\<and> disjnt U V)\"\n\nlemma Hausdorff_space_expansive:\n   \"\\<lbrakk>Hausdorff_space X; topspace X = topspace Y; \\<And>U. openin X U \\<Longrightarrow> openin Y U\\<rbrakk> \\<Longrightarrow> Hausdorff_space Y\"\n  by (metis Hausdorff_space_def)\n\nlemma Hausdorff_space_topspace_empty:\n   \"topspace X = {} \\<Longrightarrow> Hausdorff_space X\"\n  by (simp add: Hausdorff_space_def)\n\nlemma Hausdorff_imp_t1_space:\n   \"Hausdorff_space X \\<Longrightarrow> t1_space X\"\n  by (metis Hausdorff_space_def disjnt_iff t1_space_def)\n\nlemma closedin_derived_set_of:\n   \"Hausdorff_space X \\<Longrightarrow> closedin X (X derived_set_of S)\"\n  by (simp add: Hausdorff_imp_t1_space closedin_derived_set_of_gen)\n\nlemma t1_or_Hausdorff_space:\n   \"t1_space X \\<or> Hausdorff_space X \\<longleftrightarrow> t1_space X\"\n  using Hausdorff_imp_t1_space by blast\n\nlemma Hausdorff_space_sing_Inter_opens:\n   \"\\<lbrakk>Hausdorff_space X; a \\<in> topspace X\\<rbrakk> \\<Longrightarrow> \\<Inter>{u. openin X u \\<and> a \\<in> u} = {a}\"\n  using Hausdorff_imp_t1_space t1_space_singleton_Inter_open by force\n\nlemma Hausdorff_space_subtopology:\n  assumes \"Hausdorff_space X\" shows \"Hausdorff_space(subtopology X S)\"\nproof -\n  have *: \"disjnt U V \\<Longrightarrow> disjnt (S \\<inter> U) (S \\<inter> V)\" for U V\n    by (simp add: disjnt_iff)\n  from assms show ?thesis\n    apply (simp add: Hausdorff_space_def openin_subtopology_alt)\n    apply (fast intro: * elim!: all_forward)\n    done\nqed\n\nlemma Hausdorff_space_compact_separation:\n  assumes X: \"Hausdorff_space X\" and S: \"compactin X S\" and T: \"compactin X T\" and \"disjnt S T\"\n  obtains U V where \"openin X U\" \"openin X V\" \"S \\<subseteq> U\" \"T \\<subseteq> V\" \"disjnt U V\"\nproof (cases \"S = {}\")\n  case True\n  then show thesis\n    by (metis \\<open>compactin X T\\<close> compactin_subset_topspace disjnt_empty1 empty_subsetI openin_empty openin_topspace that)\nnext\n  case False\n  have \"\\<forall>x \\<in> S. \\<exists>U V. openin X U \\<and> openin X V \\<and> x \\<in> U \\<and> T \\<subseteq> V \\<and> disjnt U V\"\n  proof\n    fix a\n    assume \"a \\<in> S\"\n    then have \"a \\<notin> T\"\n      by (meson assms(4) disjnt_iff)\n    have a: \"a \\<in> topspace X\"\n      using S \\<open>a \\<in> S\\<close> compactin_subset_topspace by blast\n    show \"\\<exists>U V. openin X U \\<and> openin X V \\<and> a \\<in> U \\<and> T \\<subseteq> V \\<and> disjnt U V\"\n    proof (cases \"T = {}\")\n      case True\n      then show ?thesis\n        using a disjnt_empty2 openin_empty by blast\n    next\n      case False\n      have \"\\<forall>x \\<in> topspace X - {a}. \\<exists>U V. openin X U \\<and> openin X V \\<and> x \\<in> U \\<and> a \\<in> V \\<and> disjnt U V\"\n        using X a by (simp add: Hausdorff_space_def)\n      then obtain U V where UV: \"\\<forall>x \\<in> topspace X - {a}. openin X (U x) \\<and> openin X (V x) \\<and> x \\<in> U x \\<and> a \\<in> V x \\<and> disjnt (U x) (V x)\"\n        by metis\n      with \\<open>a \\<notin> T\\<close> compactin_subset_topspace [OF T]\n      have Topen: \"\\<forall>W \\<in> U ` T. openin X W\" and Tsub: \"T \\<subseteq> \\<Union> (U ` T)\"\n        by auto\n      then obtain \\<F> where \\<F>: \"finite \\<F>\" \"\\<F> \\<subseteq> U ` T\" and \"T \\<subseteq> \\<Union>\\<F>\"\n        using T unfolding compactin_def by meson\n      then obtain F where F: \"finite F\" \"F \\<subseteq> T\" \"\\<F> = U ` F\" and SUF: \"T \\<subseteq> \\<Union>(U ` F)\" and \"a \\<notin> F\"\n        using finite_subset_image [OF \\<F>] \\<open>a \\<notin> T\\<close> by (metis subsetD)\n      have U: \"\\<And>x. \\<lbrakk>x \\<in> topspace X; x \\<noteq> a\\<rbrakk> \\<Longrightarrow> openin X (U x)\"\n        and V: \"\\<And>x. \\<lbrakk>x \\<in> topspace X; x \\<noteq> a\\<rbrakk> \\<Longrightarrow> openin X (V x)\"\n        and disj: \"\\<And>x. \\<lbrakk>x \\<in> topspace X; x \\<noteq> a\\<rbrakk> \\<Longrightarrow> disjnt (U x) (V x)\"\n        using UV by blast+\n      show ?thesis\n      proof (intro exI conjI)\n        have \"F \\<noteq> {}\"\n          using False SUF by blast\n        with \\<open>a \\<notin> F\\<close> show \"openin X (\\<Inter>(V ` F))\"\n          using F compactin_subset_topspace [OF T] by (force intro: V)\n        show \"openin X (\\<Union>(U ` F))\"\n          using F Topen Tsub by (force intro: U)\n        show \"disjnt (\\<Inter>(V ` F)) (\\<Union>(U ` F))\"\n          using disj\n          apply (auto simp: disjnt_def)\n          using \\<open>F \\<subseteq> T\\<close> \\<open>a \\<notin> F\\<close> compactin_subset_topspace [OF T] by blast\n        show \"a \\<in> (\\<Inter>(V ` F))\"\n          using \\<open>F \\<subseteq> T\\<close> T UV \\<open>a \\<notin> T\\<close> compactin_subset_topspace by blast\n      qed (auto simp: SUF)\n    qed\n  qed\n  then obtain U V where UV: \"\\<forall>x \\<in> S. openin X (U x) \\<and> openin X (V x) \\<and> x \\<in> U x \\<and> T \\<subseteq> V x \\<and> disjnt (U x) (V x)\"\n    by metis\n  then have \"S \\<subseteq> \\<Union> (U ` S)\"\n    by auto\n  moreover have \"\\<forall>W \\<in> U ` S. openin X W\"\n    using UV by blast\n  ultimately obtain I where I: \"S \\<subseteq> \\<Union> (U ` I)\" \"I \\<subseteq> S\" \"finite I\"\n    by (metis S compactin_def finite_subset_image)\n  show thesis\n  proof\n    show \"openin X (\\<Union>(U ` I))\"\n      using \\<open>I \\<subseteq> S\\<close> UV by blast\n    show \"openin X (\\<Inter> (V ` I))\"\n      using False UV \\<open>I \\<subseteq> S\\<close> \\<open>S \\<subseteq> \\<Union> (U ` I)\\<close> \\<open>finite I\\<close> by blast\n    show \"disjnt (\\<Union>(U ` I)) (\\<Inter> (V ` I))\"\n      by simp (meson UV \\<open>I \\<subseteq> S\\<close> disjnt_subset2 in_mono le_INF_iff order_refl)\n  qed (use UV I in auto)\nqed\n\n\nlemma Hausdorff_space_compact_sets:\n  \"Hausdorff_space X \\<longleftrightarrow>\n    (\\<forall>S T. compactin X S \\<and> compactin X T \\<and> disjnt S T\n           \\<longrightarrow> (\\<exists>U V. openin X U \\<and> openin X V \\<and> S \\<subseteq> U \\<and> T \\<subseteq> V \\<and> disjnt U V))\"\n  (is \"?lhs = ?rhs\")\nproof\n  assume ?lhs\n  then show ?rhs\n    by (meson Hausdorff_space_compact_separation)\nnext\n  assume R [rule_format]: ?rhs\n  show ?lhs\n  proof (clarsimp simp add: Hausdorff_space_def)\n    fix x y\n    assume \"x \\<in> topspace X\" \"y \\<in> topspace X\" \"x \\<noteq> y\"\n    then show \"\\<exists>U. openin X U \\<and> (\\<exists>V. openin X V \\<and> x \\<in> U \\<and> y \\<in> V \\<and> disjnt U V)\"\n      using R [of \"{x}\" \"{y}\"] by auto\n  qed\nqed\n\nlemma compactin_imp_closedin:\n  assumes X: \"Hausdorff_space X\" and S: \"compactin X S\" shows \"closedin X S\"\nproof -\n  have \"S \\<subseteq> topspace X\"\n    by (simp add: assms compactin_subset_topspace)\n  moreover\n  have \"\\<exists>T. openin X T \\<and> x \\<in> T \\<and> T \\<subseteq> topspace X - S\" if \"x \\<in> topspace X\" \"x \\<notin> S\" for x\n    using Hausdorff_space_compact_separation [OF X _ S, of \"{x}\"] that\n    apply (simp add: disjnt_def)\n    by (metis Diff_mono Diff_triv openin_subset)\n  ultimately show ?thesis\n    using closedin_def openin_subopen by force\nqed\n\nlemma closedin_Hausdorff_singleton:\n   \"\\<lbrakk>Hausdorff_space X; x \\<in> topspace X\\<rbrakk> \\<Longrightarrow> closedin X {x}\"\n  by (simp add: Hausdorff_imp_t1_space closedin_t1_singleton)\n\nlemma closedin_Hausdorff_sing_eq:\n   \"Hausdorff_space X \\<Longrightarrow> closedin X {x} \\<longleftrightarrow> x \\<in> topspace X\"\n  by (meson closedin_Hausdorff_singleton closedin_subset insert_subset)\n\nlemma Hausdorff_space_discrete_topology [simp]:\n   \"Hausdorff_space (discrete_topology U)\"\n  unfolding Hausdorff_space_def\n  apply safe\n  by (metis discrete_topology_unique_alt disjnt_empty2 disjnt_insert2 insert_iff mk_disjoint_insert topspace_discrete_topology)\n\nlemma compactin_Int:\n   \"\\<lbrakk>Hausdorff_space X; compactin X S; compactin X T\\<rbrakk> \\<Longrightarrow> compactin X (S \\<inter> T)\"\n  by (simp add: closed_Int_compactin compactin_imp_closedin)\n\nlemma finite_topspace_imp_discrete_topology:\n   \"\\<lbrakk>topspace X = U; finite U; Hausdorff_space X\\<rbrakk> \\<Longrightarrow> X = discrete_topology U\"\n  using Hausdorff_imp_t1_space finite_t1_space_imp_discrete_topology by blast\n\nlemma derived_set_of_finite:\n   \"\\<lbrakk>Hausdorff_space X; finite S\\<rbrakk> \\<Longrightarrow> X derived_set_of S = {}\"\n  using Hausdorff_imp_t1_space t1_space_derived_set_of_finite by auto\n\nlemma derived_set_of_singleton:\n   \"Hausdorff_space X \\<Longrightarrow> X derived_set_of {x} = {}\"\n  by (simp add: derived_set_of_finite)\n\nlemma closedin_Hausdorff_finite:\n   \"\\<lbrakk>Hausdorff_space X; S \\<subseteq> topspace X; finite S\\<rbrakk> \\<Longrightarrow> closedin X S\"\n  by (simp add: compactin_imp_closedin finite_imp_compactin_eq)\n\nlemma open_in_Hausdorff_delete:\n   \"\\<lbrakk>Hausdorff_space X; openin X S\\<rbrakk> \\<Longrightarrow> openin X (S - {x})\"\n  using Hausdorff_imp_t1_space t1_space_openin_delete_alt by auto\n\nlemma closedin_Hausdorff_finite_eq:\n   \"\\<lbrakk>Hausdorff_space X; finite S\\<rbrakk> \\<Longrightarrow> closedin X S \\<longleftrightarrow> S \\<subseteq> topspace X\"\n  by (meson closedin_Hausdorff_finite closedin_def)\n\nlemma derived_set_of_infinite_openin:\n   \"Hausdorff_space X\n        \\<Longrightarrow> X derived_set_of S =\n            {x \\<in> topspace X. \\<forall>U. x \\<in> U \\<and> openin X U \\<longrightarrow> infinite(S \\<inter> U)}\"\n  using Hausdorff_imp_t1_space t1_space_derived_set_of_infinite_openin by fastforce\n\nlemma Hausdorff_space_discrete_compactin:\n   \"Hausdorff_space X\n        \\<Longrightarrow> S \\<inter> X derived_set_of S = {} \\<and> compactin X S \\<longleftrightarrow> S \\<subseteq> topspace X \\<and> finite S\"\n  using derived_set_of_finite discrete_compactin_eq_finite by fastforce\n\nlemma Hausdorff_space_finite_topspace:\n   \"Hausdorff_space X \\<Longrightarrow> X derived_set_of (topspace X) = {} \\<and> compact_space X \\<longleftrightarrow> finite(topspace X)\"\n  using derived_set_of_finite discrete_compact_space_eq_finite by auto\n\nlemma derived_set_of_derived_set_subset:\n   \"Hausdorff_space X \\<Longrightarrow> X derived_set_of (X derived_set_of S) \\<subseteq> X derived_set_of S\"\n  by (simp add: Hausdorff_imp_t1_space derived_set_of_derived_set_subset_gen)\n\n\nlemma Hausdorff_space_injective_preimage:\n  assumes \"Hausdorff_space Y\" and cmf: \"continuous_map X Y f\" and \"inj_on f (topspace X)\"\n  shows \"Hausdorff_space X\"\n  unfolding Hausdorff_space_def\nproof clarify\n  fix x y\n  assume x: \"x \\<in> topspace X\" and y: \"y \\<in> topspace X\" and \"x \\<noteq> y\"\n  then obtain U V where \"openin Y U\" \"openin Y V\" \"f x \\<in> U\" \"f y \\<in> V\" \"disjnt U V\"\n    using assms unfolding Hausdorff_space_def continuous_map_def by (meson inj_onD)\n  show \"\\<exists>U V. openin X U \\<and> openin X V \\<and> x \\<in> U \\<and> y \\<in> V \\<and> disjnt U V\"\n  proof (intro exI conjI)\n    show \"openin X {x \\<in> topspace X. f x \\<in> U}\"\n      using \\<open>openin Y U\\<close> cmf continuous_map by fastforce\n    show \"openin X {x \\<in> topspace X. f x \\<in> V}\"\n      using \\<open>openin Y V\\<close> cmf openin_continuous_map_preimage by blast\n    show \"disjnt {x \\<in> topspace X. f x \\<in> U} {x \\<in> topspace X. f x \\<in> V}\"\n      using \\<open>disjnt U V\\<close> by (auto simp add: disjnt_def)\n  qed (use x \\<open>f x \\<in> U\\<close> y \\<open>f y \\<in> V\\<close> in auto)\nqed\n\nlemma homeomorphic_Hausdorff_space:\n   \"X homeomorphic_space Y \\<Longrightarrow> Hausdorff_space X \\<longleftrightarrow> Hausdorff_space Y\"\n  unfolding homeomorphic_space_def homeomorphic_maps_map\n  by (auto simp: homeomorphic_eq_everything_map Hausdorff_space_injective_preimage)\n\nlemma Hausdorff_space_retraction_map_image:\n   \"\\<lbrakk>retraction_map X Y r; Hausdorff_space X\\<rbrakk> \\<Longrightarrow> Hausdorff_space Y\"\n  unfolding retraction_map_def\n  using Hausdorff_space_subtopology homeomorphic_Hausdorff_space retraction_maps_section_image2 by blast\n\nlemma compact_Hausdorff_space_optimal:\n  assumes eq: \"topspace Y = topspace X\" and XY: \"\\<And>U. openin X U \\<Longrightarrow> openin Y U\"\n      and \"Hausdorff_space X\" \"compact_space Y\"\n    shows \"Y = X\"\nproof -\n  have \"\\<And>U. closedin X U \\<Longrightarrow> closedin Y U\"\n    using XY using topology_finer_closedin [OF eq]\n    by metis\n  have \"openin Y S = openin X S\" for S\n    by (metis XY assms(3) assms(4) closedin_compact_space compactin_contractive compactin_imp_closedin eq openin_closedin_eq)\n  then show ?thesis\n    by (simp add: topology_eq)\nqed\n\nlemma continuous_map_imp_closed_graph:\n  assumes f: \"continuous_map X Y f\" and Y: \"Hausdorff_space Y\"\n  shows \"closedin (prod_topology X Y) ((\\<lambda>x. (x,f x)) ` topspace X)\"\n  unfolding closedin_def\nproof\n  show \"(\\<lambda>x. (x, f x)) ` topspace X \\<subseteq> topspace (prod_topology X Y)\"\n    using continuous_map_def f by fastforce\n  show \"openin (prod_topology X Y) (topspace (prod_topology X Y) - (\\<lambda>x. (x, f x)) ` topspace X)\"\n    unfolding openin_prod_topology_alt\n  proof (intro allI impI)\n    show \"\\<exists>U V. openin X U \\<and> openin Y V \\<and> x \\<in> U \\<and> y \\<in> V \\<and> U \\<times> V \\<subseteq> topspace (prod_topology X Y) - (\\<lambda>x. (x, f x)) ` topspace X\"\n      if \"(x,y) \\<in> topspace (prod_topology X Y) - (\\<lambda>x. (x, f x)) ` topspace X\"\n      for x y\n    proof -\n      have \"x \\<in> topspace X\" \"y \\<in> topspace Y\" \"y \\<noteq> f x\"\n        using that by auto\n      moreover have \"f x \\<in> topspace Y\"\n        by (meson \\<open>x \\<in> topspace X\\<close> continuous_map_def f)\n      ultimately obtain U V where UV: \"openin Y U\" \"openin Y V\" \"f x \\<in> U\" \"y \\<in> V\" \"disjnt U V\"\n        using Y Hausdorff_space_def by metis\n      show ?thesis\n      proof (intro exI conjI)\n        show \"openin X {x \\<in> topspace X. f x \\<in> U}\"\n          using \\<open>openin Y U\\<close> f openin_continuous_map_preimage by blast\n        show \"{x \\<in> topspace X. f x \\<in> U} \\<times> V \\<subseteq> topspace (prod_topology X Y) - (\\<lambda>x. (x, f x)) ` topspace X\"\n          using UV by (auto simp: disjnt_iff dest: openin_subset)\n      qed (use UV \\<open>x \\<in> topspace X\\<close> in auto)\n    qed\n  qed\nqed\n\nlemma continuous_imp_closed_map:\n   \"\\<lbrakk>continuous_map X Y f; compact_space X; Hausdorff_space Y\\<rbrakk> \\<Longrightarrow> closed_map X Y f\"\n  by (meson closed_map_def closedin_compact_space compactin_imp_closedin image_compactin)\n\nlemma continuous_imp_quotient_map:\n   \"\\<lbrakk>continuous_map X Y f; compact_space X; Hausdorff_space Y; f ` (topspace X) = topspace Y\\<rbrakk>\n        \\<Longrightarrow> quotient_map X Y f\"\n  by (simp add: continuous_imp_closed_map continuous_closed_imp_quotient_map)\n\nlemma continuous_imp_homeomorphic_map:\n   \"\\<lbrakk>continuous_map X Y f; compact_space X; Hausdorff_space Y; \n     f ` (topspace X) = topspace Y; inj_on f (topspace X)\\<rbrakk>\n        \\<Longrightarrow> homeomorphic_map X Y f\"\n  by (simp add: continuous_imp_closed_map bijective_closed_imp_homeomorphic_map)\n\nlemma continuous_imp_embedding_map:\n   \"\\<lbrakk>continuous_map X Y f; compact_space X; Hausdorff_space Y; inj_on f (topspace X)\\<rbrakk>\n        \\<Longrightarrow> embedding_map X Y f\"\n  by (simp add: continuous_imp_closed_map injective_closed_imp_embedding_map)\n\nlemma continuous_inverse_map:\n  assumes \"compact_space X\" \"Hausdorff_space Y\"\n    and cmf: \"continuous_map X Y f\" and gf: \"\\<And>x. x \\<in> topspace X \\<Longrightarrow> g(f x) = x\"\n    and Sf:  \"S \\<subseteq> f ` (topspace X)\"\n  shows \"continuous_map (subtopology Y S) X g\"\nproof (rule continuous_map_from_subtopology_mono [OF _ \\<open>S \\<subseteq> f ` (topspace X)\\<close>])\n  show \"continuous_map (subtopology Y (f ` (topspace X))) X g\"\n    unfolding continuous_map_closedin\n  proof (intro conjI ballI allI impI)\n    fix x\n    assume \"x \\<in> topspace (subtopology Y (f ` topspace X))\"\n    then show \"g x \\<in> topspace X\"\n      by (auto simp: gf)\n  next\n    fix C\n    assume C: \"closedin X C\"\n    show \"closedin (subtopology Y (f ` topspace X))\n           {x \\<in> topspace (subtopology Y (f ` topspace X)). g x \\<in> C}\"\n    proof (rule compactin_imp_closedin)\n      show \"Hausdorff_space (subtopology Y (f ` topspace X))\"\n        using Hausdorff_space_subtopology [OF \\<open>Hausdorff_space Y\\<close>] by blast\n      have \"compactin Y (f ` C)\"\n        using C cmf image_compactin closedin_compact_space [OF \\<open>compact_space X\\<close>] by blast\n      moreover have \"{x \\<in> topspace Y. x \\<in> f ` topspace X \\<and> g x \\<in> C} = f ` C\"\n        using closedin_subset [OF C] cmf by (auto simp: gf continuous_map_def)\n      ultimately have \"compactin Y {x \\<in> topspace Y. x \\<in> f ` topspace X \\<and> g x \\<in> C}\"\n        by simp\n      then show \"compactin (subtopology Y (f ` topspace X))\n              {x \\<in> topspace (subtopology Y (f ` topspace X)). g x \\<in> C}\"\n        by (auto simp add: compactin_subtopology)\n    qed\n  qed\nqed\n\nlemma closed_map_paired_continuous_map_right:\n   \"\\<lbrakk>continuous_map X Y f; Hausdorff_space Y\\<rbrakk> \\<Longrightarrow> closed_map X (prod_topology X Y) (\\<lambda>x. (x,f x))\"\n  by (simp add: continuous_map_imp_closed_graph embedding_map_graph embedding_imp_closed_map)\n\nlemma closed_map_paired_continuous_map_left:\n  assumes f: \"continuous_map X Y f\" and Y: \"Hausdorff_space Y\"\n  shows \"closed_map X (prod_topology Y X) (\\<lambda>x. (f x,x))\"\nproof -\n  have eq: \"(\\<lambda>x. (f x,x)) = (\\<lambda>(a,b). (b,a)) \\<circ> (\\<lambda>x. (x,f x))\"\n    by auto\n  show ?thesis\n    unfolding eq\n  proof (rule closed_map_compose)\n    show \"closed_map X (prod_topology X Y) (\\<lambda>x. (x, f x))\"\n      using Y closed_map_paired_continuous_map_right f by blast\n    show \"closed_map (prod_topology X Y) (prod_topology Y X) (\\<lambda>(a, b). (b, a))\"\n      by (metis homeomorphic_map_swap homeomorphic_imp_closed_map)\n  qed\nqed\n\nlemma proper_map_paired_continuous_map_right:\n   \"\\<lbrakk>continuous_map X Y f; Hausdorff_space Y\\<rbrakk>\n        \\<Longrightarrow> proper_map X (prod_topology X Y) (\\<lambda>x. (x,f x))\"\n  using closed_injective_imp_proper_map closed_map_paired_continuous_map_right\n  by (metis (mono_tags, lifting) Pair_inject inj_onI)\n\nlemma proper_map_paired_continuous_map_left:\n   \"\\<lbrakk>continuous_map X Y f; Hausdorff_space Y\\<rbrakk>\n        \\<Longrightarrow> proper_map X (prod_topology Y X) (\\<lambda>x. (f x,x))\"\n  using closed_injective_imp_proper_map closed_map_paired_continuous_map_left\n  by (metis (mono_tags, lifting) Pair_inject inj_onI)\n\nlemma Hausdorff_space_prod_topology:\n  \"Hausdorff_space(prod_topology X Y) \\<longleftrightarrow> topspace(prod_topology X Y) = {} \\<or> Hausdorff_space X \\<and> Hausdorff_space Y\"\n  (is \"?lhs = ?rhs\")\nproof\n  assume ?lhs\n  then show ?rhs\n    by (rule topological_property_of_prod_component) (auto simp: Hausdorff_space_subtopology homeomorphic_Hausdorff_space)\nnext\n  assume R: ?rhs\n  show ?lhs\n  proof (cases \"(topspace X \\<times> topspace Y) = {}\")\n    case False\n    with R have ne: \"topspace X \\<noteq> {}\" \"topspace Y \\<noteq> {}\" and X: \"Hausdorff_space X\" and Y: \"Hausdorff_space Y\"\n      by auto\n    show ?thesis\n      unfolding Hausdorff_space_def\n    proof clarify\n      fix x y x' y'\n      assume xy: \"(x, y) \\<in> topspace (prod_topology X Y)\"\n        and xy': \"(x',y') \\<in> topspace (prod_topology X Y)\"\n        and *: \"\\<nexists>U V. openin (prod_topology X Y) U \\<and> openin (prod_topology X Y) V\n               \\<and> (x, y) \\<in> U \\<and> (x', y') \\<in> V \\<and> disjnt U V\"\n      have False if \"x \\<noteq> x' \\<or> y \\<noteq> y'\"\n        using that\n      proof\n        assume \"x \\<noteq> x'\"\n        then obtain U V where \"openin X U\" \"openin X V\" \"x \\<in> U\" \"x' \\<in> V\" \"disjnt U V\"\n          by (metis Hausdorff_space_def X mem_Sigma_iff topspace_prod_topology xy xy')\n        let ?U = \"U \\<times> topspace Y\"\n        let ?V = \"V \\<times> topspace Y\"\n        have \"openin (prod_topology X Y) ?U\" \"openin (prod_topology X Y) ?V\"\n          by (simp_all add: openin_prod_Times_iff \\<open>openin X U\\<close> \\<open>openin X V\\<close>)\n        moreover have \"disjnt ?U ?V\"\n          by (simp add: \\<open>disjnt U V\\<close>)\n        ultimately show False\n          using * \\<open>x \\<in> U\\<close> \\<open>x' \\<in> V\\<close> xy xy' by (metis SigmaD2 SigmaI topspace_prod_topology)\n      next\n        assume \"y \\<noteq> y'\"\n        then obtain U V where \"openin Y U\" \"openin Y V\" \"y \\<in> U\" \"y' \\<in> V\" \"disjnt U V\"\n          by (metis Hausdorff_space_def Y mem_Sigma_iff topspace_prod_topology xy xy')\n        let ?U = \"topspace X \\<times> U\"\n        let ?V = \"topspace X \\<times> V\"\n        have \"openin (prod_topology X Y) ?U\" \"openin (prod_topology X Y) ?V\"\n          by (simp_all add: openin_prod_Times_iff \\<open>openin Y U\\<close> \\<open>openin Y V\\<close>)\n        moreover have \"disjnt ?U ?V\"\n          by (simp add: \\<open>disjnt U V\\<close>)\n        ultimately show False\n          using \"*\" \\<open>y \\<in> U\\<close> \\<open>y' \\<in> V\\<close> xy xy' by (metis SigmaD1 SigmaI topspace_prod_topology)\n      qed\n      then show \"x = x' \\<and> y = y'\"\n        by blast\n    qed\n  qed (simp add: Hausdorff_space_topspace_empty)\nqed\n\n\nlemma Hausdorff_space_product_topology:\n   \"Hausdorff_space (product_topology X I) \\<longleftrightarrow> (\\<Pi>\\<^sub>E i\\<in>I. topspace(X i)) = {} \\<or> (\\<forall>i \\<in> I. Hausdorff_space (X i))\"\n  (is \"?lhs = ?rhs\")\nproof\n  assume ?lhs\n  then show ?rhs\n    apply (rule topological_property_of_product_component)\n     apply (blast dest: Hausdorff_space_subtopology homeomorphic_Hausdorff_space)+\n    done\nnext\n  assume R: ?rhs\n  show ?lhs\n  proof (cases \"(\\<Pi>\\<^sub>E i\\<in>I. topspace(X i)) = {}\")\n    case True\n    then show ?thesis\n      by (simp add: Hausdorff_space_topspace_empty)\n  next\n    case False\n    have \"\\<exists>U V. openin (product_topology X I) U \\<and> openin (product_topology X I) V \\<and> f \\<in> U \\<and> g \\<in> V \\<and> disjnt U V\"\n      if f: \"f \\<in> (\\<Pi>\\<^sub>E i\\<in>I. topspace (X i))\" and g: \"g \\<in> (\\<Pi>\\<^sub>E i\\<in>I. topspace (X i))\" and \"f \\<noteq> g\"\n      for f g :: \"'a \\<Rightarrow> 'b\"\n    proof -\n      obtain m where \"f m \\<noteq> g m\"\n        using \\<open>f \\<noteq> g\\<close> by blast\n      then have \"m \\<in> I\"\n        using f g by fastforce\n      then have \"Hausdorff_space (X m)\" \n        using False that R by blast\n      then obtain U V where U: \"openin (X m) U\" and V: \"openin (X m) V\" and \"f m \\<in> U\" \"g m \\<in> V\" \"disjnt U V\"\n        by (metis Hausdorff_space_def PiE_mem \\<open>f m \\<noteq> g m\\<close> \\<open>m \\<in> I\\<close> f g)\n      show ?thesis\n      proof (intro exI conjI)\n        let ?U = \"(\\<Pi>\\<^sub>E i\\<in>I. topspace(X i)) \\<inter> {x. x m \\<in> U}\"\n        let ?V = \"(\\<Pi>\\<^sub>E i\\<in>I. topspace(X i)) \\<inter> {x. x m \\<in> V}\"\n        show \"openin (product_topology X I) ?U\" \"openin (product_topology X I) ?V\"\n          using \\<open>m \\<in> I\\<close> U V\n          by (force simp add: openin_product_topology intro: arbitrary_union_of_inc relative_to_inc finite_intersection_of_inc)+\n        show \"f \\<in> ?U\"\n          using \\<open>f m \\<in> U\\<close> f by blast\n        show \"g \\<in> ?V\"\n          using \\<open>g m \\<in> V\\<close> g by blast\n        show \"disjnt ?U ?V\"\n          using \\<open>disjnt U V\\<close> by (auto simp: PiE_def Pi_def disjnt_def)\n        qed\n    qed\n    then show ?thesis\n      by (simp add: Hausdorff_space_def)   \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/Analysis/T1_Spaces.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513675912912, "lm_q2_score": 0.8289388104343892, "lm_q1q2_score": 0.7429375425013194}}
{"text": "(* ---------------------------------------------------------------------------- *)\nsubsection \\<open>Angle between two vectors\\<close>\n(* ---------------------------------------------------------------------------- *)\n\ntext \\<open>In this section we introduce different measures of angle between two vectors (represented by complex numbers).\\<close>\n\ntheory Angles\nimports More_Transcendental Canonical_Angle More_Complex\nbegin\n\n(* ---------------------------------------------------------------------------- *)\nsubsubsection \\<open>Oriented angle\\<close>\n(* ---------------------------------------------------------------------------- *)\n\ntext \\<open>Oriented angle between two vectors (it is always in the interval $(-\\pi, \\pi]$).\\<close>\ndefinition ang_vec (\"\\<angle>\") where\n  [simp]: \"\\<angle> z1 z2 \\<equiv> \\<downharpoonright>arg z2 - arg z1\\<downharpoonleft>\"\n\nlemma ang_vec_bounded:\n  shows \"-pi < \\<angle> z1 z2 \\<and> \\<angle> z1 z2 \\<le> pi\"\n  by (simp add: canon_ang(1) canon_ang(2))\n\nlemma ang_vec_sym:\n  assumes \"\\<angle> z1 z2 \\<noteq> pi\"\n  shows \"\\<angle> z1 z2 = - \\<angle> z2 z1\"\n  using assms\n  unfolding ang_vec_def\n  using canon_ang_uminus[of \"arg z2 - arg z1\"]\n  by simp\n\nlemma ang_vec_sym_pi:\n  assumes \"\\<angle> z1 z2 = pi\"\n  shows \"\\<angle> z1 z2 = \\<angle> z2 z1\"\n  using assms\n  unfolding ang_vec_def\n  using canon_ang_uminus_pi[of \"arg z2 - arg z1\"]\n  by simp\n\nlemma ang_vec_plus_pi1:\n  assumes \"\\<angle> z1 z2 > 0\"\n  shows \"\\<downharpoonright>\\<angle> z1 z2 + pi\\<downharpoonleft> = \\<angle> z1 z2 - pi\"\nproof (rule canon_ang_eqI)\n  show \"\\<exists> x::int. \\<angle> z1 z2 - pi - (\\<angle> z1 z2 + pi) = 2 * real_of_int x * pi\"\n    by (rule_tac x=\"-1\" in exI) auto\nnext\n  show \"- pi < \\<angle> z1 z2 - pi \\<and> \\<angle> z1 z2 - pi \\<le> pi\"\n    using assms\n    unfolding ang_vec_def\n    using canon_ang(1)[of \"arg z2 - arg z1\"] canon_ang(2)[of \"arg z2 - arg z1\"]\n    by auto\nqed\n\nlemma ang_vec_plus_pi2:\n  assumes \"\\<angle> z1 z2 \\<le> 0\"\n  shows \"\\<downharpoonright>\\<angle> z1 z2 + pi\\<downharpoonleft> = \\<angle> z1 z2 + pi\"\nproof (rule canon_ang_id)\n  show \"- pi < \\<angle> z1 z2 + pi \\<and> \\<angle> z1 z2 + pi \\<le> pi\"\n    using assms\n    unfolding ang_vec_def\n    using canon_ang(1)[of \"arg z2 - arg z1\"] canon_ang(2)[of \"arg z2 - arg z1\"]\n    by auto\nqed\n\nlemma ang_vec_opposite1:\n  assumes \"z1 \\<noteq> 0\"\n  shows \"\\<angle> (-z1) z2 = \\<downharpoonright>\\<angle> z1 z2 - pi\\<downharpoonleft>\"\nproof-\n  have \"\\<angle> (-z1) z2 = \\<downharpoonright>arg z2 - (arg z1 + pi)\\<downharpoonleft>\"\n    unfolding ang_vec_def\n    using arg_uminus[OF assms] \n    using canon_ang_arg[of z2, symmetric]\n    using canon_ang_diff[of \"arg z2\" \"arg z1 + pi\", symmetric]\n    by simp\n  moreover\n  have \"\\<downharpoonright>\\<angle> z1 z2 - pi\\<downharpoonleft> = \\<downharpoonright>arg z2 - arg z1 - pi\\<downharpoonleft>\"\n    using canon_ang_id[of pi, symmetric]\n    using canon_ang_diff[of \"arg z2 - arg z1\" \"pi\", symmetric]\n    by simp_all\n  ultimately\n  show ?thesis\n    by (simp add: field_simps)\nqed\n\nlemma ang_vec_opposite2:\n  assumes \"z2 \\<noteq> 0\"\n  shows \"\\<angle> z1 (-z2) = \\<downharpoonright>\\<angle> z1 z2 + pi\\<downharpoonleft>\"\n  unfolding ang_vec_def\n  using arg_mult[of \"-1\" \"z2\"] assms\n  using arg_complex_of_real_negative[of \"-1\"]\n  using canon_ang_diff[of \"arg (-1) + arg z2\" \"arg z1\", symmetric]\n  using canon_ang_sum[of \"arg z2 - arg z1\" \"pi\", symmetric]\n  using canon_ang_id[of pi] canon_ang_arg[of z1]\n  by (auto simp: algebra_simps)\n  \n\nlemma ang_vec_opposite_opposite:\n  assumes \"z1 \\<noteq> 0\" and \"z2 \\<noteq> 0\"\n  shows \"\\<angle> (-z1) (-z2) = \\<angle> z1 z2\"\nproof-\n  have \"\\<angle> (-z1) (-z2) = \\<downharpoonright>\\<downharpoonright>\\<angle> z1 z2 + pi\\<downharpoonleft> - \\<downharpoonright>pi\\<downharpoonleft>\\<downharpoonleft>\"\n    using ang_vec_opposite1[OF assms(1)]\n    using ang_vec_opposite2[OF assms(2)]\n    using canon_ang_id[of pi, symmetric]\n    by simp_all\n  also have \"... = \\<downharpoonright>\\<angle> z1 z2\\<downharpoonleft>\"\n    by (subst canon_ang_diff[symmetric], simp)\n  finally\n  show ?thesis\n    by (metis ang_vec_def canon_ang(1) canon_ang(2) canon_ang_id)\nqed\n\nlemma ang_vec_opposite_opposite':\n  assumes \"z1 \\<noteq> z\" and \"z2 \\<noteq> z\"\n  shows \"\\<angle> (z - z1) (z - z2) = \\<angle> (z1 - z) (z2 - z)\"\nusing ang_vec_opposite_opposite[of \"z - z1\" \"z - z2\"] assms\nby (simp add: field_simps del: ang_vec_def)\n\ntext \\<open>Cosine, scalar product and the law of cosines\\<close>\n\nlemma cos_cmod_scalprod:\n  shows \"cmod z1 * cmod z2 * (cos (\\<angle> z1 z2)) = Re (scalprod z1 z2)\"\nproof (cases \"z1 = 0 \\<or> z2 = 0\")\n  case True\n  thus ?thesis\n    by auto\nnext\n  case False\n  thus ?thesis\n    by (simp add: cos_diff cos_arg sin_arg field_simps)\nqed\n\nlemma cos0_scalprod0:\n  assumes \"z1 \\<noteq> 0\" and \"z2 \\<noteq> 0\"\n  shows \"cos (\\<angle> z1 z2) = 0 \\<longleftrightarrow> scalprod z1 z2 = 0\"\n  using assms\n  using cnj_mix_real[of z1 z2]\n  using cos_cmod_scalprod[of z1 z2]\n  by (auto simp add: complex_eq_if_Re_eq)\n\nlemma ortho_scalprod0:\n  assumes \"z1 \\<noteq> 0\" and \"z2 \\<noteq> 0\"\n  shows \"\\<angle> z1 z2 = pi/2 \\<or> \\<angle> z1 z2 = -pi/2 \\<longleftrightarrow> scalprod z1 z2 = 0\"\n  using cos0_scalprod0[OF assms]\n  using ang_vec_bounded[of z1 z2]\n  using cos_0_iff_canon[of \"\\<angle> z1 z2\"]\n  by (metis cos_minus cos_pi_half divide_minus_left)\n\nlemma law_of_cosines:\n  shows \"(cdist B C)\\<^sup>2 = (cdist A C)\\<^sup>2 + (cdist A B)\\<^sup>2 - 2*(cdist A C)*(cdist A B)*(cos (\\<angle> (C-A) (B-A)))\"\nproof-\n  let ?a = \"C-B\" and ?b = \"C-A\" and ?c = \"B-A\"\n  have \"?a = ?b - ?c\"\n    by simp\n  hence \"(cmod ?a)\\<^sup>2 = (cmod (?b - ?c))\\<^sup>2\"\n    by metis\n  also have \"... = Re (scalprod (?b-?c) (?b-?c))\"\n    by (simp add: cmod_square)\n  also have \"... = (cmod ?b)\\<^sup>2 + (cmod ?c)\\<^sup>2 - 2*Re (scalprod ?b ?c)\"\n    by (simp add: cmod_square field_simps)\n  finally\n  show ?thesis\n    using cos_cmod_scalprod[of ?b ?c]\n    by simp\nqed\n\n(* ---------------------------------------------------------------------------- *)\nsubsubsection \\<open>Unoriented angle\\<close>\n(* ---------------------------------------------------------------------------- *)\n\ntext \\<open>Convex unoriented angle between two vectors (it is always in the interval $[0, pi]$).\\<close>\ndefinition ang_vec_c (\"\\<angle>c\") where\n  [simp]:\"\\<angle>c z1 z2 \\<equiv> abs (\\<angle> z1 z2)\"\n\nlemma ang_vec_c_sym:\n  shows \"\\<angle>c z1 z2 = \\<angle>c z2 z1\"\n  unfolding ang_vec_c_def\n  using ang_vec_sym_pi[of z1 z2] ang_vec_sym[of z1 z2]\n  by (cases \"\\<angle> z1 z2 = pi\") auto\n\nlemma ang_vec_c_bounded: \"0 \\<le> \\<angle>c z1 z2 \\<and> \\<angle>c z1 z2 \\<le> pi\"\n  using canon_ang(1)[of \"arg z2 - arg z1\"] canon_ang(2)[of \"arg z2 - arg z1\"]\n  by auto\n\ntext \\<open>Cosine and scalar product\\<close>\n\nlemma cos_c_: \"cos (\\<angle>c z1 z2) = cos (\\<angle> z1 z2)\"\n  unfolding ang_vec_c_def\n  by (smt cos_minus)\n\nlemma ortho_c_scalprod0:\n  assumes \"z1 \\<noteq> 0\" and \"z2 \\<noteq> 0\"\n  shows \"\\<angle>c z1 z2 = pi/2 \\<longleftrightarrow> scalprod z1 z2 = 0\"\nproof-\n  have \"\\<angle> z1 z2 = pi / 2 \\<or> \\<angle> z1 z2 = - pi / 2 \\<longleftrightarrow> \\<angle>c z1 z2 = pi/2\"\n    unfolding ang_vec_c_def\n    using arctan \n    by force\n  thus ?thesis\n    using ortho_scalprod0[OF assms]\n    by simp\nqed\n\n(* ---------------------------------------------------------------------------- *)\nsubsubsection \\<open>Acute angle\\<close>\n(* ---------------------------------------------------------------------------- *)\n\ntext \\<open>Acute or right angle (non-obtuse) between two vectors (it is always in the interval $[0, \\frac{\\pi}{2}$]).\nWe will use this to measure angle between two circles, since it can always be acute (or right).\\<close>\n\ndefinition acute_ang where\n  [simp]: \"acute_ang \\<alpha> = (if \\<alpha> > pi / 2 then pi - \\<alpha> else \\<alpha>)\"\n\ndefinition ang_vec_a (\"\\<angle>a\") where\n  [simp]: \"\\<angle>a z1 z2 \\<equiv> acute_ang (\\<angle>c z1 z2)\"\n\nlemma ang_vec_a_sym:\n  \"\\<angle>a z1 z2 = \\<angle>a z2 z1\"\n  unfolding ang_vec_a_def\n  using ang_vec_c_sym\n  by auto\n\nlemma ang_vec_a_opposite2:\n  \"\\<angle>a z1 z2 = \\<angle>a z1 (-z2)\"\nproof(cases \"z2  = 0\")\n  case True\n  thus ?thesis\n    by (metis minus_zero)\nnext\n  case False\n  thus ?thesis\n  proof(cases \"\\<angle> z1 z2 < -pi / 2\")\n    case True\n    hence \"\\<angle> z1 z2 < 0\"\n      using pi_not_less_zero\n      by linarith\n    have \"\\<angle>a z1 z2 = pi + \\<angle> z1 z2\"\n      using True \\<open>\\<angle> z1 z2 < 0\\<close>\n      unfolding ang_vec_a_def ang_vec_c_def ang_vec_a_def abs_real_def\n      by auto\n    moreover\n    have \"\\<angle>a z1 (-z2) = pi + \\<angle> z1 z2\"\n      unfolding ang_vec_a_def ang_vec_c_def abs_real_def\n      using canon_ang(1)[of \"arg z2 - arg z1\"] canon_ang(2)[of \"arg z2 - arg z1\"]\n      using ang_vec_plus_pi2[of z1 z2] True \\<open>\\<angle> z1 z2 < 0\\<close> \\<open>z2 \\<noteq> 0\\<close>\n      using ang_vec_opposite2[of z2 z1]\n      by auto\n    ultimately\n    show ?thesis\n      by auto\n  next\n    case False\n    show ?thesis\n    proof (cases \"\\<angle> z1 z2 \\<le> 0\")\n      case True\n      have \"\\<angle>a z1 z2 = - \\<angle> z1 z2\"\n        using \\<open>\\<not> \\<angle> z1 z2 < - pi / 2\\<close> True\n        unfolding ang_vec_a_def ang_vec_c_def ang_vec_a_def abs_real_def\n        by auto\n      moreover\n      have \"\\<angle>a z1 (-z2) = - \\<angle> z1 z2\"\n        using \\<open>\\<not> \\<angle> z1 z2 < - pi / 2\\<close> True\n        unfolding ang_vec_a_def ang_vec_c_def abs_real_def\n        using ang_vec_plus_pi2[of z1 z2]\n        using canon_ang(1)[of \"arg z2 - arg z1\"] canon_ang(2)[of \"arg z2 - arg z1\"]\n        using \\<open>z2 \\<noteq> 0\\<close> ang_vec_opposite2[of z2 z1]\n        by auto\n      ultimately\n      show ?thesis\n        by simp\n    next\n      case False\n      show ?thesis\n      proof (cases \"\\<angle> z1 z2 < pi / 2\")\n        case True\n        have \"\\<angle>a z1 z2 = \\<angle> z1 z2\"\n          using \\<open>\\<not> \\<angle> z1 z2 \\<le> 0\\<close> True\n          unfolding ang_vec_a_def ang_vec_c_def ang_vec_a_def abs_real_def\n          by auto\n        moreover\n        have \"\\<angle>a z1 (-z2) = \\<angle> z1 z2\"\n          using \\<open>\\<not> \\<angle> z1 z2 \\<le> 0\\<close> True\n          unfolding ang_vec_a_def ang_vec_c_def abs_real_def\n          using ang_vec_plus_pi1[of z1 z2]\n          using canon_ang(1)[of \"arg z2 - arg z1\"] canon_ang(2)[of \"arg z2 - arg z1\"]\n          using \\<open>z2 \\<noteq> 0\\<close> ang_vec_opposite2[of z2 z1]\n          by auto\n        ultimately\n        show ?thesis\n          by simp\n      next\n        case False\n        have \"\\<angle> z1 z2 > 0\"\n          using False\n          by (metis less_linear less_trans pi_half_gt_zero)\n        have \"\\<angle>a z1 z2 = pi - \\<angle> z1 z2\"\n          using False \\<open>\\<angle> z1 z2 > 0\\<close>\n          unfolding ang_vec_a_def ang_vec_c_def ang_vec_a_def abs_real_def\n          by auto\n        moreover\n        have \"\\<angle>a z1 (-z2) = pi - \\<angle> z1 z2\"\n          unfolding ang_vec_a_def ang_vec_c_def abs_real_def\n          using False \\<open>\\<angle> z1 z2 > 0\\<close>\n          using ang_vec_plus_pi1[of z1 z2]\n          using canon_ang(1)[of \"arg z2 - arg z1\"] canon_ang(2)[of \"arg z2 - arg z1\"]\n          using \\<open>z2 \\<noteq> 0\\<close> ang_vec_opposite2[of z2 z1]\n          by auto\n        ultimately\n        show ?thesis\n          by auto\n      qed\n    qed\n  qed\nqed\n\nlemma ang_vec_a_opposite1:\n  shows \"\\<angle>a z1 z2 = \\<angle>a (-z1) z2\"\n  using ang_vec_a_sym[of \"-z1\" z2] ang_vec_a_opposite2[of z2 z1] ang_vec_a_sym[of z2 z1]\n  by auto\n\nlemma ang_vec_a_scale1:\n  assumes \"k \\<noteq> 0\"\n  shows \"\\<angle>a (cor k * z1) z2 = \\<angle>a z1 z2\"\nproof (cases \"k > 0\")\n  case True\n  thus ?thesis\n    unfolding ang_vec_a_def ang_vec_c_def ang_vec_def\n    using arg_mult_real_positive[of k z1]\n    by auto\nnext\n  case False\n  hence \"k < 0\"\n    using assms\n    by auto\n  thus ?thesis\n    using arg_mult_real_negative[of k z1]\n    using ang_vec_a_opposite1[of z1 z2]\n    unfolding ang_vec_a_def ang_vec_c_def ang_vec_def\n    by simp\nqed\n\nlemma ang_vec_a_scale2:\n  assumes \"k \\<noteq> 0\"\n  shows \"\\<angle>a z1 (cor k * z2) = \\<angle>a z1 z2\"\n  using ang_vec_a_sym[of z1 \"complex_of_real k * z2\"]\n  using ang_vec_a_scale1[OF assms, of z2 z1]\n  using ang_vec_a_sym[of z1 z2]\n  by auto\n\nlemma ang_vec_a_scale:\n  assumes \"k1 \\<noteq> 0\" and \"k2 \\<noteq> 0\"\n  shows \"\\<angle>a (cor k1 * z1) (cor k2 * z2) = \\<angle>a z1 z2\"\n  using ang_vec_a_scale1[OF assms(1)] ang_vec_a_scale2[OF assms(2)]\n  by auto\n\nlemma ang_a_cnj_cnj:\n  shows \"\\<angle>a z1 z2 = \\<angle>a (cnj z1) (cnj z2)\"\nunfolding ang_vec_a_def ang_vec_c_def ang_vec_def\nproof(cases \"arg z1 \\<noteq> pi \\<and> arg z2 \\<noteq> pi\")\n  case True\n  thus \"acute_ang \\<bar>\\<downharpoonright>arg z2 - arg z1\\<downharpoonleft>\\<bar> = acute_ang \\<bar>\\<downharpoonright>arg (cnj z2) - arg (cnj z1)\\<downharpoonleft>\\<bar>\"\n    using arg_cnj_not_pi[of z1] arg_cnj_not_pi[of z2]\n    apply (auto simp del:acute_ang_def)\n    proof(cases \"\\<downharpoonright>arg z2 - arg z1\\<downharpoonleft> = pi\")\n      case True\n      thus \"acute_ang \\<bar>\\<downharpoonright>arg z2 - arg z1\\<downharpoonleft>\\<bar> = acute_ang \\<bar>\\<downharpoonright>arg z1 - arg z2\\<downharpoonleft>\\<bar>\"\n        using  canon_ang_uminus_pi[of \"arg z2 - arg z1\"]\n        by (auto simp add:field_simps)\n    next\n      case False\n      thus \"acute_ang \\<bar>\\<downharpoonright>arg z2 - arg z1\\<downharpoonleft>\\<bar> = acute_ang \\<bar>\\<downharpoonright>arg z1 - arg z2\\<downharpoonleft>\\<bar>\"\n        using  canon_ang_uminus[of \"arg z2 - arg z1\"]\n        by (auto simp add:field_simps)\n    qed\n  next\n    case False\n    thus \"acute_ang \\<bar>\\<downharpoonright>arg z2 - arg z1\\<downharpoonleft>\\<bar> = acute_ang \\<bar>\\<downharpoonright>arg (cnj z2) - arg (cnj z1)\\<downharpoonleft>\\<bar>\"\n    proof(cases \"arg z1 = pi\")\n      case False\n      hence \"arg z2 = pi\"\n        using \\<open> \\<not> (arg z1 \\<noteq> pi \\<and> arg z2 \\<noteq> pi)\\<close>\n        by auto\n      thus ?thesis\n        using False\n        using arg_cnj_not_pi[of z1] arg_cnj_pi[of z2]\n        apply (auto simp del:acute_ang_def)\n      proof(cases \"arg z1 > 0\")\n          case True\n          hence \"-arg z1 \\<le> 0\"\n            by auto\n          thus \"acute_ang \\<bar>\\<downharpoonright>pi - arg z1\\<downharpoonleft>\\<bar> = acute_ang \\<bar>\\<downharpoonright>pi + arg z1\\<downharpoonleft>\\<bar>\"\n            using True canon_ang_plus_pi1[of \"arg z1\"]\n            using arg_bounded[of z1] canon_ang_plus_pi2[of \"-arg z1\"]\n            by (auto simp add:field_simps)\n        next\n          case False\n          hence \"-arg z1 \\<ge> 0\"\n             by simp\n          thus \"acute_ang \\<bar>\\<downharpoonright>pi - arg z1\\<downharpoonleft>\\<bar> = acute_ang \\<bar>\\<downharpoonright>pi + arg z1\\<downharpoonleft>\\<bar>\"\n          proof(cases \"arg z1 = 0\")\n            case True\n            thus ?thesis\n              by (auto simp del:acute_ang_def)\n          next\n            case False\n            hence \"-arg z1 > 0\"\n              using \\<open>-arg z1 \\<ge> 0\\<close>\n              by auto\n            thus ?thesis\n            using False canon_ang_plus_pi1[of \"-arg z1\"]\n            using arg_bounded[of z1] canon_ang_plus_pi2[of \"arg z1\"]\n            by (auto simp add:field_simps)\n        qed\n      qed\n    next\n      case True\n      thus ?thesis\n        using arg_cnj_pi[of z1]\n        apply (auto simp del:acute_ang_def)\n      proof(cases \"arg z2 = pi\")\n        case True\n        thus \"acute_ang \\<bar>\\<downharpoonright>arg z2 - pi\\<downharpoonleft>\\<bar> = acute_ang \\<bar>\\<downharpoonright>arg (cnj z2) - pi\\<downharpoonleft>\\<bar>\"\n          using arg_cnj_pi[of z2]\n          by auto\n      next\n        case False\n        thus \"acute_ang \\<bar>\\<downharpoonright>arg z2 - pi\\<downharpoonleft>\\<bar> = acute_ang \\<bar>\\<downharpoonright>arg (cnj z2) - pi\\<downharpoonleft>\\<bar>\"\n          using arg_cnj_not_pi[of z2]\n          apply (auto simp del:acute_ang_def)\n        proof(cases \"arg z2 > 0\")\n          case True\n          hence \"-arg z2 \\<le> 0\"\n            by auto\n          thus \"acute_ang \\<bar>\\<downharpoonright>arg z2 - pi\\<downharpoonleft>\\<bar> = acute_ang \\<bar>\\<downharpoonright>- arg z2 - pi\\<downharpoonleft>\\<bar>\"\n            using True canon_ang_minus_pi1[of \"arg z2\"]\n            using arg_bounded[of z2] canon_ang_minus_pi2[of \"-arg z2\"]\n            by (auto simp add: field_simps)\n        next\n          case False\n          hence \"-arg z2 \\<ge> 0\"\n             by simp\n          thus \"acute_ang \\<bar>\\<downharpoonright>arg z2 - pi\\<downharpoonleft>\\<bar> = acute_ang \\<bar>\\<downharpoonright>- arg z2 - pi\\<downharpoonleft>\\<bar>\"\n          proof(cases \"arg z2 = 0\")\n            case True\n            thus ?thesis\n              by (auto simp del:acute_ang_def)\n          next\n            case False\n            hence \"-arg z2 > 0\"\n              using \\<open>-arg z2 \\<ge> 0\\<close>\n              by auto\n            thus ?thesis\n            using False canon_ang_minus_pi1[of \"-arg z2\"]\n            using arg_bounded[of z2] canon_ang_minus_pi2[of \"arg z2\"]\n            by (auto simp add:field_simps)\n        qed\n      qed\n    qed\n  qed\nqed\n\ntext \\<open>Cosine and scalar product\\<close>\n\nlemma ortho_a_scalprod0:\n  assumes \"z1 \\<noteq> 0\" and \"z2 \\<noteq> 0\"\n  shows \"\\<angle>a z1 z2 = pi/2 \\<longleftrightarrow> scalprod z1 z2 = 0\"\n  unfolding ang_vec_a_def\n  using assms ortho_c_scalprod0[of z1 z2]\n  by auto\n\ndeclare ang_vec_c_def[simp del]\n\nlemma cos_a_c: \"cos (\\<angle>a z1 z2) = abs (cos (\\<angle>c z1 z2))\"\nproof-\n  have \"0 \\<le> \\<angle>c z1 z2\" \"\\<angle>c z1 z2 \\<le> pi\"\n    using ang_vec_c_bounded[of z1 z2]\n    by auto\n  show ?thesis\n  proof (cases \"\\<angle>c z1 z2 = pi/2\")\n    case True\n    thus ?thesis\n      unfolding ang_vec_a_def acute_ang_def\n      by (smt cos_pi_half pi_def pi_half)\n  next\n    case False\n    show ?thesis\n    proof (cases \"\\<angle>c z1 z2 < pi / 2\")\n      case True\n      thus ?thesis\n        using `0 \\<le> \\<angle>c z1 z2`\n        using cos_gt_zero_pi[of \"\\<angle>c z1 z2\"]\n        unfolding ang_vec_a_def\n        by simp\n    next\n      case False\n      hence \"\\<angle>c z1 z2 > pi/2\"\n        using `\\<angle>c z1 z2 \\<noteq> pi/2`\n        by simp\n      hence \"cos (\\<angle>c z1 z2) < 0\"\n        using `\\<angle>c z1 z2 \\<le> pi`\n        using cos_lt_zero_on_pi2_pi[of \"\\<angle>c z1 z2\"] \n        by simp\n      thus ?thesis\n        using `\\<angle>c z1 z2 > pi/2`\n        unfolding ang_vec_a_def\n        by simp\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/Complex_Geometry/Angles.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9086178919837706, "lm_q2_score": 0.817574478416099, "lm_q1q2_score": 0.7428627991181667}}
{"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    \\<comment>\\<open>symmetric closure: removes the orientation of a relation\\<close>\n\ndefinition neighbors :: \"[vertex, (vertex*vertex)set]=>vertex set\" where\n  \"neighbors i r == ((r \\<union> r^-1)``{i}) - {i}\"\n    \\<comment>\\<open>Neighbors of a vertex i\\<close>\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    \\<comment>\\<open>reachable and above vertices: the original notation was R* and A*\\<close>\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    \\<comment>\\<open>The original definition\\<close>\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    \\<comment>\\<open>Our alternative definition\\<close>\n  \"derive i r q == A i r = {} & (q = reverse i r)\"\n\naxiomatization where\n  finite_vertex_univ:  \"finite (UNIV :: vertex set)\"\n    \\<comment>\\<open>we assume that the universe of vertices is finite\\<close>\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\\<open>All vertex sets are finite\\<close>\ndeclare finite_subset [OF subset_UNIV finite_vertex_univ, iff]\n\ntext\\<open>and relatons over vertex are finite too\\<close>\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": "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/UNITY/Comp/PriorityAux.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9086178944582997, "lm_q2_score": 0.8175744695262777, "lm_q1q2_score": 0.7428627930638276}}
{"text": "theory Suduku\nimports Main\nbegin\n\ntype_notation bool  (\"\\<bool>\") \ntype_notation nat (\"\\<nat>\")\n\n(*\nMAX_GRID_VAL: nat1 = 9;\nMAX_SUB_GRID: nat1 = 3;\nGRID_SIZE   : nat1 = MAX_GRID_VAL * MAX_GRID_VAL;\n*)\nabbreviation  MAX_GRID_VAL :: \\<nat> where \"MAX_GRID_VAL \\<equiv> 9\"\nabbreviation  MAX_SUB_GRID :: \\<nat> where \"MAX_SUB_GRID \\<equiv> 3\"\nabbreviation  GRID_SIZE :: \\<nat> \n  where \"GRID_SIZE \\<equiv> MAX_GRID_VAL * MAX_GRID_VAL\"\n\n(*\nGRID_VALS    : set of nat1 = {1,...,MAX_GRID_VAL};\nALL_CELLS   : set of Cell = { mk_Cell(r, c) | r, c in set GRID_VALS };\n*)\nabbreviation  GRID_VALS :: \"nat set\" \n  where \"GRID_VALS \\<equiv> {1..MAX_GRID_VAL}\"\n\nvalue \"GRID_VALS\"\n\n(*\nCell :: r:nat1 \n\t\t\t  c:nat1\ninv mk_Cell(r,c) == r <= MAX_GRID_VAL \n \t\t\t\t\t\t\t  and c <= MAX_GRID_VAL;\n*)\nrecord Cell =\n  r :: \\<nat>\n  c :: \\<nat>\n\nvalue \"\\<lparr>r = 0, c = 10\\<rparr>\"\n\ndefinition \n   inv_Cell :: \"Cell \\<Rightarrow> \\<bool>\"\nwhere\n  \"inv_Cell cell \\<equiv> (r cell) \\<ge> 1 \\<and> (c cell) \\<ge> 1 \\<and>\n                   (r cell) \\<le> MAX_GRID_VAL \\<and>\n                   (c cell) \\<le> MAX_GRID_VAL\"  (* cell.r *)\n\n(* ALL_CELLS = { mk_Cell(v1, v2) | v1, v2 in set GRID_VALS & True *)\ndefinition  ALL_CELLS :: \"Cell set\" \n  where \"ALL_CELLS \\<equiv> { \\<lparr> r = v1, c = v2 \\<rparr> | \n                        v1 v2 . v1 \\<in> GRID_VALS \\<and> \n                                v2 \\<in> GRID_VALS \\<and>  \n                                inv_Cell \\<lparr> r = v1, c = v2 \\<rparr>}\"\n\ndeclare [[show_types]]\nlemma \"ALL_CELLS = A\"\nunfolding ALL_CELLS_def\napply simp\noops\n\n(*\n{{mk_Cell(1, 1), mk_Cell(1, 2), mk_Cell(1, 3), \n  mk_Cell(2, 1), mk_Cell(2, 2), mk_Cell(2, 3), \n  mk_Cell(3, 1), mk_Cell(3, 2), mk_Cell(3, 3)}, \n\n {mk_Cell(1, 4), mk_Cell(1, 5), mk_Cell(1, 6), \n  mk_Cell(2, 4), mk_Cell(2, 5), mk_Cell(2, 6), \n  mk_Cell(3, 4), mk_Cell(3, 5), mk_Cell(3, 6)}, \n\n {mk_Cell(1, 7), mk_Cell(1, 8), mk_Cell(1, 9), \n  mk_Cell(2, 7), mk_Cell(2, 8), mk_Cell(2, 9), \n  mk_Cell(3, 7), mk_Cell(3, 8), mk_Cell(3, 9)}, \n \n {mk_Cell(4, 1), mk_Cell(4, 2), mk_Cell(4, 3), \n  mk_Cell(5, 1), mk_Cell(5, 2), mk_Cell(5, 3), \n  mk_Cell(6, 1), mk_Cell(6, 2), mk_Cell(6, 3)}, \n\n {mk_Cell(4, 4), mk_Cell(4, 5), mk_Cell(4, 6), mk_Cell(5, 4), mk_Cell(5, 5), mk_Cell(5, 6), mk_Cell(6, 4), mk_Cell(6, 5), mk_Cell(6, 6)}, {mk_Cell(4, 7), mk_Cell(4, 8), mk_Cell(4, 9), mk_Cell(5, 7), mk_Cell(5, 8), mk_Cell(5, 9), mk_Cell(6, 7), mk_Cell(6, 8), mk_Cell(6, 9)}, {mk_Cell(7, 1), mk_Cell(7, 2), mk_Cell(7, 3), mk_Cell(8, 1), mk_Cell(8, 2), mk_Cell(8, 3), mk_Cell(9, 1), mk_Cell(9, 2), mk_Cell(9, 3)}, {mk_Cell(7, 4), mk_Cell(7, 5), mk_Cell(7, 6), mk_Cell(8, 4), mk_Cell(8, 5), mk_Cell(8, 6), mk_Cell(9, 4), mk_Cell(9, 5), mk_Cell(9, 6)}, {mk_Cell(7, 7), mk_Cell(7, 8), mk_Cell(7, 9), mk_Cell(8, 7), mk_Cell(8, 8), mk_Cell(8, 9), mk_Cell(9, 7), mk_Cell(9, 8), mk_Cell(9, 9)}}\n\n*)\n\n(*\nPuzzle0 = map Cell to nat1;\n*)\n\ntype_synonym Puzzle0 = \"Cell \\<rightharpoonup> \\<nat>\"\n\ndefinition\n   nat1 :: \"\\<nat> \\<Rightarrow> \\<bool>\"\nwhere\n  \"nat1 n \\<equiv> n \\<ge> 1\"\n\ndefinition \n    inv_Puzzle0 :: \"Puzzle0 \\<Rightarrow> bool\"\nwhere\n   \"inv_Puzzle0 p == (\\<forall> x \\<in> dom p . inv_Cell x) \\<and>\n                     (\\<forall> y \\<in> ran p . nat1 y)\"\n \n\ndefinition\n    inv_Cells :: \"Cell set \\<Rightarrow> \\<bool>\"\nwhere\n    \"inv_Cells cs \\<equiv> \\<forall> c \\<in> cs . inv_Cell c\"\n\ndefinition \n    inv_Puzzle0_2 :: \"(Cell \\<rightharpoonup> \\<nat>) \\<Rightarrow> \\<bool>\"\nwhere\n    \"inv_Puzzle0_2 p \\<equiv> inv_Cells (dom p) \\<and> \n                        (\\<forall> x \\<in> dom p . nat1 (the (p x)))\"\n\ndefinition\n    inv_Puzzle :: \"Puzzle0 \\<Rightarrow> bool\"\nwhere   \n    \"inv_Puzzle p == inv_Puzzle0 p \\<and> ran p \\<subseteq> GRID_VALS\"\n\ndefinition \n  get3x3 :: \"Cell \\<Rightarrow> Cell\"\nwhere\n  \"get3x3 cell \\<equiv> \\<lparr>r =((((r cell)- 1) div MAX_SUB_GRID) * MAX_SUB_GRID)+1,\n                  c =((((c cell)- 1) div MAX_SUB_GRID) * MAX_SUB_GRID)+1\\<rparr>\"\n\ndefinition \n  post_get3x3 :: \"Cell \\<Rightarrow> Cell \\<Rightarrow> bool\"\nwhere\n  \"post_get3x3 cell result \\<equiv> (r result) \\<in> {1,4,7} \\<and> (c result) \\<in> {1,4,7}\"\n\n(*\n(forall mk_Cell(r, c):Cell & \n    post_get3x3(mk_Cell(r, c), \n        mk_Cell(((((r - 1) div MAX_SUB_GRID) * MAX_SUB_GRID) + 1), \n                ((((c - 1) div MAX_SUB_GRID) * MAX_SUB_GRID) + 1))))\n*)\n\ndeclare [[show_types]]\ndefinition\n   PO_get3x3_satisfiability :: \"bool\"\nwhere\n  \"PO_get3x3_satisfiability == \\<forall> cell . inv_Cell cell \\<longrightarrow> \n                                          (let row = (r cell); col = (c cell) in \n                                              post_get3x3 cell \n                                                         \\<lparr>r =((((r cell)- 1) div MAX_SUB_GRID) * MAX_SUB_GRID)+1,\n                                                          c =((((c cell)- 1) div MAX_SUB_GRID) * MAX_SUB_GRID)+1\\<rparr>)\"\n\nlemma PO_get3x3_satisfiability\nunfolding PO_get3x3_satisfiability_def post_get3x3_def\napply auto\nnitpick\noops\n\ndefinition\n   in3x3 :: \"Cell \\<Rightarrow> Cell \\<Rightarrow> \\<bool>\"\nwhere\n   \"in3x3 cell origin \\<equiv> inv_Cell cell \\<and> inv_Cell origin \\<and> \n                        (r cell) \\<ge> (r origin) \\<and> \n                        (r cell) \\<le> (r origin) + (MAX_SUB_GRID - 1) \\<and>\n                        (c cell) \\<ge> (c origin) \\<and> \n                        (c cell) \\<le> (r origin) + (MAX_SUB_GRID - 1)\"\n\n(*\n-- set of 'first' cells per sub-grid (e.g. mk_Cell(1,1), mk_Cell(1,7), mk_Cell(4,7))\nSUB_GRID_ORIGINS : set of Cell\t \t\t  = { get3x3(c) | c in set ALL_CELLS };\nSUB_GRID_CELLS   : set of set of Cell = { { c | c in set ALL_CELLS & in3x3(c, get3x3(origin)) } | origin in set SUB_GRID_ORIGINS };\n*)\n\ndefinition\n   SG_ORIGINS :: \"Cell set\"\nwhere\n  \"SG_ORIGINS \\<equiv> { get3x3 c | c . c \\<in> ALL_CELLS }\"\n\ndefinition\n   SG_ORIGINS2 :: \"Cell set\"\nwhere\n  \"SG_ORIGINS2 \\<equiv> { cell | cell . cell \\<in> ALL_CELLS \\<and> \n                   (r cell) \\<in> {1,4,7} \\<and> (c cell) \\<in> {1,4,7}}\"\n\ndefinition\n   SG_CELLS :: \"Cell set set\"\nwhere\n  \"SG_CELLS \\<equiv> { { c | c . c \\<in> ALL_CELLS \\<and> \n                  in3x3 c (get3x3 origin)} | \n                    origin . origin \\<in> SG_ORIGINS }\"\n\nvalue \"get3x3 \\<lparr> r = 1, c =1 \\<rparr>\"\nvalue \"get3x3 \\<lparr> r = 5, c =1 \\<rparr>\"\nvalue \"get3x3 \\<lparr> r = 9, c =1 \\<rparr>\"\nvalue \"in3x3 \\<lparr> r = 2, c = 2 \\<rparr> (get3x3 \\<lparr> r = 2, c = 1\\<rparr>)\"\nvalue \"in3x3 \\<lparr> r = 2, c = 2 \\<rparr> (get3x3 \\<lparr> r = 5, c = 1\\<rparr>)\"\n\n\ndefinition\n    isInj :: \"Puzzle0 \\<Rightarrow> \\<bool>\"\nwhere\n  \"isInj p \\<equiv> inv_Puzzle0 p \\<and>  \n              (\\<forall> x1 \\<in> dom p . \\<forall> x2 \\<in> dom p . \n                  \\<forall> y . p x1 = y \\<and> p x2 = y \\<longrightarrow> x1 = x2)\"\n\ndefinition\n  dom_restr :: \"'a set \\<Rightarrow> ('a \\<rightharpoonup> 'b) \\<Rightarrow> ('a \\<rightharpoonup> 'b)\"  (infixr \"\\<triangleleft>\" 110)\nwhere\n  [intro!]: \"s \\<triangleleft> m \\<equiv> m |` s\" \n  (* same as VDM  s <: m *)\n\ndefinition\n    sgValid :: \"Puzzle0 \\<Rightarrow> \\<bool>\"\nwhere\n  \"sgValid p \\<equiv> inv_Puzzle0 p \\<and> \n                (\\<forall> sg \\<in> SG_CELLS . isInj (sg \\<triangleleft> p))\"\n\ndefinition\n   inv_Puzzle_2 :: \"Puzzle0 \\<Rightarrow> \\<bool>\"\nwhere\n  \"inv_Puzzle_2 p \\<equiv> inv_Puzzle0 p \\<and> finite(dom p) \\<and> \n                    card(dom p) \\<le> GRID_SIZE \\<and> \n                    ran p \\<subseteq> GRID_VALS \\<and> sgValid p\"\n\n\nend\n", "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/experiments/isa/Suduku/Suduku.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797124237604, "lm_q2_score": 0.8152324915965392, "lm_q1q2_score": 0.7428233072514403}}
{"text": "theory QSort\nimports Main\nbegin\n\n(* first, define some rules about what it means to be sorted. *)\n\nfun sorted :: \"'a::ord list \\<Rightarrow> bool\" where\n   \"sorted [] = True\"\n | \"sorted [x] = True\"\n | \"sorted (x#y#zs) = ((x \\<le> y) \\<and> sorted (y#zs))\"\n\n \nlemma sorted_lt:\n  assumes \"sorted (x#y#zs)\"\n  shows \"x \\<le> y\" using assms by auto\n\nlemma sorted_behead:\n  assumes \"sorted (y#zs)\"\n  shows \"sorted zs\" using assms by (induction zs; auto)\n\nlemma sorted_cons:\n  fixes x y zs \n  assumes \"x\\<le>y\" and \"sorted (y#zs)\"\n  shows \"sorted (x#y#zs)\" using assms by auto\n \nlemma lt_trans:\n  fixes x y z\n  assumes \"(x \\<le> y)\" and \"(y \\<le> z)\" \n  shows \"(x \\<le> z)\"\n  sorry\n\nlemma sorted_nip:\n  fixes x y zs z zz\n  assumes a0:\"sorted (x#y#zs)\" and a1:\"zs=(z#zz)\"\n  shows \"sorted (x#zs)\" using assms\nproof -\n  have \"sorted zs\"\n    proof -\n      from a0 have \"sorted (y#zs)\" by (rule sorted_behead)\n      thus ?thesis by (rule sorted_behead)\n    qed\n\n  also have \"x\\<le>z\"\n    proof -\n      have \"x\\<le>y\" and \"y\\<le>z\" using a0 a1 by auto\n      thus ?thesis by (rule lt_trans)\n    qed\n    \n  thus ?thesis using assms by (auto)\nqed\n\n\nlemma sorted_head_shrink:\n  fixes x y zs z zz\n  assumes \"x \\<le> y\" and \"sorted (y#zs)\" and zz:\"zs=(z#zz)\"\n  shows \"sorted (x#zs)\"\nproof -\n  have \"sorted (x#y#zs)\" using assms by auto\n  from this and zz show ?thesis by (rule sorted_nip)\nqed\n\n\n\n(* rules about the minimum item in a list (and particularly a sorted list) *)\n\nlemma minxy [simp]:\n  assumes \"x \\<le> y\" shows \"(min x y) = x\"\n  using assms by (simp only: min_def; auto)\n \nfun listmin :: \"'a::ord list \\<Rightarrow> 'a\" where\n   \"listmin [] = undefined\"\n | \"listmin [x] = x\"\n | \"listmin (x#xs) = min x (listmin xs)\"\n\n\n\nlemma assumes \"sorted (x#y#zs)\" shows \"listmin (x#y#zs) = x\" using assms\nby (induction zs arbitrary: x y rule: listmin.induct; auto)\n\nlemma assumes \"sorted (x#xs)\" shows \"listmin (x#xs) = x\" using assms\nby (induction xs arbitrary: x rule: listmin.induct; auto)\n\n(* same for max item *)\n\nlemma gt_vs_le:\n  fixes x y\n  assumes \"x > y\"\n  shows \"\\<not>(x \\<le> y)\"\n  sorry (* I have no idea yet why this isn't proved automatically :/ *)\n\nlemma maxxy [simp]:\n  fixes x y assumes \"x > y\"\n  shows \"(max x y) = x\"\n  using assms\nproof -\n  have  \"(max x y)= (if x \\<le> y then y else x)\" by (rule max_def)\n  hence \"(max x y)= (if False then y else x)\" using assms by (simp only: gt_vs_le)\n  then show ?thesis by auto\nqed\n\nfun listmax :: \"'a::ord list \\<Rightarrow> 'a\" where\n   \"listmax [] = undefined\"\n | \"listmax [x] = x\"\n | \"listmax (x#xs) = max x (listmax xs)\"\n\nlemma [simp]: \"listmax [x,y] = max x y\" by auto\n\nlemma sorted_concat:\n  assumes \"sorted (y0#ys)\"\n      and \"sorted xs\"\n      and \"listmax(x) < y0\"\n    shows \"sorted (xs @ ys)\"\n    sorry (* TODO *)\n\n\n(* and now, the (functional-style) quicksort: *)\n\nfun qsort :: \"'a::ord list \\<Rightarrow> 'a list\" where \n   \"qsort [] = []\"\n | \"qsort (x#ys) = (qsort [y \\<leftarrow> ys. y<x]) @ (x # qsort [y \\<leftarrow> ys. y \\<ge> x])\"\n\nvalue \"qsort [ 5, 9, 2, 3, 4 ] :: int list\"\n\n\n\nlemma \"sorted (qsort [])\" by auto\nlemma \"sorted (qsort [x])\" by auto\n\ntheorem \"sorted (qsort (x#ys))\"\nsorry\n\n(* proof (induct ys rule: qsort.induct)\n  show \"sorted (qsort [x])\" by auto\nnext\n  let ?lt = \"[y \\<leftarrow> ys. y < x]\"\n  let ?ge = \"[y \\<leftarrow> ys. y \\<ge> x]\"\n  have  q0: \"qsort (x#ys) = (qsort ?lt) @ (x # qsort ?ge)\" by auto\n  sorry\nqed *)\n\n\n\nend\n", "meta": {"author": "tangentstorm", "repo": "tangentlabs", "sha": "49d7a335221e1ae67e8de0203a3f056bc4ab1d00", "save_path": "github-repos/isabelle/tangentstorm-tangentlabs", "path": "github-repos/isabelle/tangentstorm-tangentlabs/tangentlabs-49d7a335221e1ae67e8de0203a3f056bc4ab1d00/isar/QSort.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898229217591, "lm_q2_score": 0.8198933337131076, "lm_q1q2_score": 0.7428150162254691}}
{"text": "subsection\\<open>Chaum-Pedersen \\<open>\\<Sigma>\\<close>-protocol\\<close>\n\ntext\\<open>The Chaum-Pedersen \\<open>\\<Sigma>\\<close>-protocol \\cite{DBLP:conf/crypto/ChaumP92} considers a relation of equality of discrete logs.\\<close>\n\ntheory Chaum_Pedersen_Sigma_Commit imports\n  Commitment_Schemes\n  Sigma_Protocols\n  Cyclic_Group_Ext\n  Discrete_Log\n  Number_Theory_Aux\n  Uniform_Sampling \nbegin \n\nlocale chaum_ped_\\<Sigma>_base = \n  fixes \\<G> :: \"'grp cyclic_group\" (structure)\n    and x :: nat\n  assumes  prime_order: \"prime (order \\<G>)\"\nbegin\n\ndefinition \"g' = \\<^bold>g [^] x\"\n\nlemma or_gt_1: \"order \\<G> > 1\" \n  using prime_order \n  using prime_gt_1_nat by blast\n\nlemma or_gt_0 [simp]:\"order \\<G> > 0\" \n  using or_gt_1 by simp\n\ntype_synonym witness = \"nat\"\ntype_synonym rand = nat \ntype_synonym 'grp' msg = \"'grp' \\<times> 'grp'\"\ntype_synonym response = nat\ntype_synonym challenge = nat\ntype_synonym 'grp' pub_in = \"'grp' \\<times> 'grp'\"\n\ndefinition \"G = do {\n    w \\<leftarrow> sample_uniform (order \\<G>);\n    return_spmf ((\\<^bold>g [^] w, g' [^] w), w)}\"\n\nlemma lossless_G: \"lossless_spmf G\"\n  by(simp add: G_def)\n\ndefinition \"challenge_space = {..< order \\<G>}\" \n\ndefinition init :: \"'grp pub_in \\<Rightarrow> witness \\<Rightarrow> (rand \\<times> 'grp msg) spmf\"\n  where \"init h w = do {\n    let (h, h') = h;  \n    r \\<leftarrow> sample_uniform (order \\<G>);\n    return_spmf (r, \\<^bold>g [^] r, g' [^] r)}\"\n\nlemma lossless_init: \"lossless_spmf (init h w)\" \n  by(simp add:  init_def)\n\ndefinition \"response r w e = return_spmf ((w*e + r) mod (order \\<G>))\"\n\nlemma lossless_response: \"lossless_spmf (response r w  e)\"\n  by(simp add: response_def)\n\ndefinition check :: \"'grp pub_in \\<Rightarrow> 'grp msg \\<Rightarrow> challenge \\<Rightarrow> response \\<Rightarrow> bool\"\n  where \"check h a e z =  (fst a \\<otimes> (fst h [^] e) = \\<^bold>g [^] z \\<and> snd a \\<otimes> (snd h [^] e) = g' [^] z \\<and> fst a \\<in> carrier \\<G> \\<and> snd a \\<in> carrier \\<G>)\"\n\ndefinition R :: \"('grp pub_in \\<times> witness) set\"\n  where \"R = {(h, w). (fst h = \\<^bold>g [^] w \\<and> snd h = g' [^] w)}\"\n\ndefinition S2 :: \"'grp pub_in \\<Rightarrow> challenge \\<Rightarrow> ('grp msg, response) sim_out spmf\"\n  where \"S2 H c = do {\n  let (h, h') = H;\n  z \\<leftarrow> (sample_uniform (order \\<G>));\n  let a = \\<^bold>g [^] z \\<otimes> inv (h [^] c); \n  let a' =  g' [^] z \\<otimes> inv (h' [^] c);\n  return_spmf ((a,a'), z)}\"\n\ndefinition ss_adversary :: \"'grp pub_in \\<Rightarrow> ('grp msg, challenge, response) conv_tuple \\<Rightarrow> ('grp msg, challenge, response) conv_tuple \\<Rightarrow> nat spmf\"\n  where \"ss_adversary x' c1 c2 = do {\n    let ((a,a'), e, z) = c1;\n    let ((b,b'), e', z') = c2;\n    return_spmf (if (e mod order \\<G> > e' mod order \\<G>) then (nat ((int z - int z') * (fst (bezw ((e mod order \\<G> - e' mod order \\<G>) mod order \\<G>) (order \\<G>))) mod order \\<G>)) else \n(nat ((int z' - int z) * (fst (bezw ((e' mod order \\<G> - e mod order \\<G>) mod order \\<G>) (order \\<G>))) mod order \\<G>)))}\"\n\ndefinition \"valid_pub = carrier \\<G> \\<times> carrier \\<G>\"\n\nend \n\nlocale chaum_ped_\\<Sigma> = chaum_ped_\\<Sigma>_base + cyclic_group \\<G>\nbegin\n\nlemma g'_in_carrier [simp]: \"g' \\<in> carrier \\<G>\"\n  by(simp add: g'_def) \n\nsublocale chaum_ped_sigma: \\<Sigma>_protocols_base init response check R S2 ss_adversary challenge_space valid_pub \n  by unfold_locales (auto simp add: R_def valid_pub_def)\n\nlemma completeness: \n  shows \"chaum_ped_sigma.completeness\"\nproof-\n  have \"g' [^] y \\<otimes> (g' [^] w') [^] e = g' [^] ((w' * e + y) mod order \\<G>)\" for y e w'\n    by (simp add: Groups.add_ac(2) pow_carrier_mod nat_pow_pow nat_pow_mult)\n  moreover have \"\\<^bold>g [^] y \\<otimes> (\\<^bold>g [^] w') [^] e = \\<^bold>g [^] ((w' * e + y) mod order \\<G>)\" for y e w'\n    by (metis add.commute nat_pow_pow nat_pow_mult pow_generator_mod generator_closed mod_mult_right_eq)  \n  ultimately show ?thesis\n    unfolding chaum_ped_sigma.completeness_def chaum_ped_sigma.completeness_game_def\n    by(auto simp add: R_def challenge_space_def init_def check_def response_def split_def bind_spmf_const)\nqed\n\nlemma hvzk_xr'_rewrite:\n  assumes r: \"r < order \\<G>\"\n  shows \"((w*c + r) mod (order \\<G>) mod (order \\<G>) + (order \\<G>) * w*c - w*c) mod (order \\<G>) = r\"\n(is \"?lhs = ?rhs\")\nproof-\n  have \"?lhs = (w*c + r  + (order \\<G>) * w*c- w*c) mod (order \\<G>)\" \n    by (metis Nat.add_diff_assoc Num.of_nat_simps(1) One_nat_def add_less_same_cancel2 less_imp_le_nat \n        mod_add_left_eq mult.assoc mult_0_right n_less_m_mult_n nat_neq_iff not_add_less2 of_nat_0_le_iff prime_gt_1_nat prime_order) \n  thus ?thesis using r \n    by (metis ab_semigroup_add_class.add_ac(1) ab_semigroup_mult_class.mult_ac(1) diff_add_inverse mod_if mod_mult_self2)\nqed\n\nlemma hvzk_h_sub_rewrite:\n  assumes \"h = \\<^bold>g [^] w\"  \n    and z: \"z < order \\<G>\" \n  shows \"\\<^bold>g [^] ((z + (order \\<G>)* w * c - w*c)) = \\<^bold>g [^] z \\<otimes> inv (h [^] c)\" \n    (is \"?lhs = ?rhs\")\nproof(cases \"w = 0\")\n  case True\n  then show ?thesis using assms by simp\nnext\n  case w_gt_0: False\n  then show ?thesis \n  proof-\n    have \"(z + order \\<G> * w * c - w * c) = (z + (order \\<G> * w * c- w * c))\"\n      using z by (simp add: less_imp_le_nat mult_le_mono) \n    then have lhs: \"?lhs = \\<^bold>g [^] z \\<otimes> \\<^bold>g [^] ((order \\<G>) * w *c - w*c)\" \n      by(simp add: nat_pow_mult)\n    have \" \\<^bold>g [^] ((order \\<G>) * w *c - w*c) =  inv (h [^] c)\"  \n    proof(cases \"c = 0\")\n      case True\n      then show ?thesis using lhs by simp\n    next\n      case False\n      hence *: \"((order \\<G>)*w *c - w*c) > 0\" using assms w_gt_0 \n        using gr0I mult_less_cancel2 n_less_m_mult_n numeral_nat(7) prime_gt_1_nat prime_order zero_less_diff by presburger\n      then have \" \\<^bold>g [^] ((order \\<G>)*w*c - w*c) =  \\<^bold>g [^] int ((order \\<G>)*w*c - w*c)\"\n        by (simp add: int_pow_int) \n      also have \"... = \\<^bold>g [^] int ((order \\<G>)*w*c) \\<otimes> inv (\\<^bold>g [^] (w*c))\" \n        using int_pow_diff[of \"\\<^bold>g\" \"order \\<G> * w * c\" \"w * c\"] * generator_closed int_ops(6) int_pow_neg int_pow_neg_int by presburger\n\n      also have \"... = \\<^bold>g [^] ((order \\<G>)*w*c) \\<otimes> inv (\\<^bold>g [^] (w*c))\"\n        by (metis int_pow_int) \n      also have \"... = \\<^bold>g [^] ((order \\<G>)*w*c) \\<otimes> inv ((\\<^bold>g [^] w) [^] c)\"\n        by(simp add: nat_pow_pow)\n      also have \"... = \\<^bold>g [^] ((order \\<G>)*w*c) \\<otimes> inv (h [^] c)\"\n        using assms by simp\n      also have \"... = \\<one> \\<otimes> inv (h [^] c)\"\n        using generator_pow_order\n        by (metis generator_closed mult_is_0 nat_pow_0 nat_pow_pow)\n      ultimately show ?thesis\n        by (simp add: assms(1)) \n    qed\n    then show ?thesis using lhs by simp\n  qed\nqed\n\nlemma hvzk_h_sub2_rewrite:\n  assumes  \"h' = g' [^] w\" \n    and z: \"z < order \\<G>\" \n  shows \"g' [^] ((z + (order \\<G>)*w*c - w*c))  = g' [^] z \\<otimes> inv (h' [^] c)\" \n    (is \"?lhs = ?rhs\")\nproof(cases \"w = 0\")\n  case True\n  then show ?thesis \n    using assms by (simp add: g'_def)\nnext\n  case w_gt_0: False\n  then show ?thesis \n  proof-\n    have \"g' = \\<^bold>g [^] x\" using g'_def by simp\n    have g'_carrier: \"g' \\<in> carrier \\<G>\" using g'_def by simp\n    have 1: \"g' [^] ((order \\<G>)*w*c- w*c) = inv (h' [^] c)\"\n    proof(cases \"c = 0\")\n      case True\n      then show ?thesis by simp\n    next\n      case False\n      hence *: \"((order \\<G>)*w*c - w*c) > 0\" \n        using assms mult_strict_mono w_gt_0 prime_gt_1_nat prime_order by auto \n      then have \" g' [^] ((order \\<G>)*w*c - w*c) =  g' [^] int ((order \\<G>)*w*c - w*c)\"\n        by (simp add: int_pow_int) \n      also have \"... = g' [^] int ((order \\<G>)*w*c) \\<otimes> inv (g' [^] (w*c))\" \n        using int_pow_diff[of \"g'\" \"order \\<G> * w* c\" \"w * c\"] g'_carrier \n        by (metis * chaum_ped_\\<Sigma>_axioms chaum_ped_\\<Sigma>_def cyclic_group_def group.int_pow_neg_int int_ops(6) int_pow_neg less_not_refl2 of_nat_eq_0_iff)\n      also have \"... = g' [^] ((order \\<G>)*w*c) \\<otimes> inv (g' [^] (w*c))\" \n        by (metis int_pow_int) \n      also have \"... = g' [^] ((order \\<G>)*w*c) \\<otimes> inv (h' [^] c)\"\n        by(simp add: nat_pow_pow assms)\n      also have \"... = \\<one> \\<otimes> inv (h' [^] c)\" \n        by (metis g'_carrier nat_pow_one nat_pow_pow pow_order_eq_1)\n      ultimately show ?thesis\n        by (simp add: assms(1)) \n    qed\n    have \"(z + order \\<G> * w * c - w * c) = (z + (order \\<G> * w * c - w * c))\"\n      using z by (simp add: less_imp_le_nat mult_le_mono) \n    then have lhs: \"?lhs = g' [^] z \\<otimes> g' [^] ((order \\<G>)*w*c - w*c)\" \n      by(auto simp add: nat_pow_mult)\n    then show ?thesis using 1 by simp\n  qed\nqed\n\nlemma hv_zk2:\n  assumes \"(H, w) \\<in> R\" \n  shows \"chaum_ped_sigma.R H w c = chaum_ped_sigma.S H c\"\n  including monad_normalisation\nproof-\n  have H: \"H = (\\<^bold>g [^] (w::nat), g' [^] w)\" \n    using assms R_def  by(simp add: prod.expand)\n  have g'_carrier: \"g' \\<in> carrier \\<G>\" using g'_def by simp\n  have \"chaum_ped_sigma.R H w c  = do {\n    let (h, h') = H;\n    r \\<leftarrow> sample_uniform (order \\<G>);\n    let z = (w*c + r) mod (order \\<G>);\n    let a = \\<^bold>g [^] ((z + (order \\<G>) * w*c - w*c) mod (order \\<G>)); \n    let a' = g' [^] ((z + (order \\<G>) * w*c - w*c) mod (order \\<G>));\n    return_spmf ((a,a'),c, z)}\"\n    apply(simp add: chaum_ped_sigma.R_def Let_def response_def split_def init_def)\n    using assms hvzk_xr'_rewrite \n    by(simp cong: bind_spmf_cong_simp)\n  also have \"... = do {\n    let (h, h') = H;\n    z \\<leftarrow> map_spmf (\\<lambda> r. (w*c + r) mod (order \\<G>)) (sample_uniform (order \\<G>));\n    let a = \\<^bold>g [^] ((z + (order \\<G>) * w*c - w*c) mod (order \\<G>)); \n    let a' = g' [^] ((z + (order \\<G>) * w*c - w*c) mod (order \\<G>));\n    return_spmf ((a,a'),c, z)}\"\n    by(simp add: bind_map_spmf Let_def o_def)\n  also have \"... = do {\n    let (h, h') = H;\n    z \\<leftarrow> (sample_uniform (order \\<G>));\n    let a = \\<^bold>g [^] ((z + (order \\<G>) * w*c - w*c) mod (order \\<G>)); \n    let a' = g' [^] ((z + (order \\<G>) * w*c - w*c) mod (order \\<G>));\n    return_spmf ((a,a'),c, z)}\"\n    by(simp add: samp_uni_plus_one_time_pad)\n  also have \"... = do {\n    let (h, h') = H;\n    z \\<leftarrow> (sample_uniform (order \\<G>));\n    let a = \\<^bold>g [^] z \\<otimes> inv (h [^] c); \n    let a' = g' [^] ((z + (order \\<G>) * w*c - w*c) mod (order \\<G>));\n    return_spmf ((a,a'),c, z)}\"\n    using hvzk_h_sub_rewrite assms\n    apply(simp add: Let_def H)\n    apply(intro bind_spmf_cong[OF refl]; clarsimp?)\n    by (simp add: pow_generator_mod)\n  also have \"... = do {\n    let (h, h') = H;\n    z \\<leftarrow> (sample_uniform (order \\<G>));\n    let a = \\<^bold>g [^] z \\<otimes> inv (h [^] c); \n    let a' = g' [^] ((z + (order \\<G>)*w*c - w*c));\n    return_spmf ((a,a'),c, z)}\"\n     using g'_carrier pow_carrier_mod[of \"g'\"] by simp\n   also have \"... = do {\n    let (h, h') = H;\n    z \\<leftarrow> (sample_uniform (order \\<G>));\n    let a = \\<^bold>g [^] z \\<otimes> inv (h [^] c); \n    let a' =  g' [^] z \\<otimes> inv (h' [^] c);\n    return_spmf ((a,a'),c, z)}\"\n     using hvzk_h_sub2_rewrite assms H\n     by(simp cong: bind_spmf_cong_simp)\n   ultimately show ?thesis \n     unfolding chaum_ped_sigma.S_def chaum_ped_sigma.R_def\n     by(simp add: init_def S2_def split_def Let_def \\<Sigma>_protocols_base.S_def bind_map_spmf map_spmf_conv_bind_spmf)\nqed\n\nlemma HVZK: \n  shows \"chaum_ped_sigma.HVZK\"\n    unfolding chaum_ped_sigma.HVZK_def \n    by(auto simp add: hv_zk2 R_def valid_pub_def   S2_def check_def cyclic_group_assoc)\n\nlemma ss_rewrite1:\n  assumes \"fst h \\<in> carrier \\<G>\"\n    and \"a \\<in> carrier \\<G>\" \n    and e: \"e < order \\<G>\" \n    and \"a \\<otimes> fst h [^] e = \\<^bold>g [^] z\"  \n    and e': \"e' < e\"\n    and \"a \\<otimes> fst h [^] e' = \\<^bold>g [^] z'\"\n  shows \"fst h = \\<^bold>g [^] ((int z - int z') * inverse (e - e') (order \\<G>) mod int (order \\<G>))\"\nproof-\n  have gcd: \"gcd (e - e') (order \\<G>) = 1\" \n    using e e' prime_field prime_order by simp\n  have \"a = \\<^bold>g [^] z \\<otimes> inv (fst h [^] e)\" \n    using assms\n    by (simp add: assms inv_solve_right)\n  moreover have \"a = \\<^bold>g [^] z' \\<otimes> inv (fst h [^] e')\" \n    using assms\n    by (simp add: assms inv_solve_right)\n  ultimately have \"\\<^bold>g [^] z \\<otimes> fst h [^] e' = \\<^bold>g [^] z' \\<otimes> fst h [^] e\"\n    by (metis (no_types, lifting) assms cyclic_group_assoc cyclic_group_commute nat_pow_closed)\n  moreover obtain t :: nat where t: \"fst h = \\<^bold>g [^] t\"\n    using assms generatorE by blast\n  ultimately have \"\\<^bold>g [^] (z + t * e') = \\<^bold>g [^] (z' + t * e)\" \n    using nat_pow_pow \n    by (simp add: nat_pow_mult)\n  hence \"[z + t * e' = z' + t * e] (mod order \\<G>)\"\n    using group_eq_pow_eq_mod or_gt_0 by blast\n  hence \"[int z + int t * int e' = int z' + int t * int e] (mod order \\<G>)\"\n    using cong_int_iff by force\n  hence \"[int z - int z' = int t * int e - int t * int e'] (mod order \\<G>)\"\n    by (smt cong_diff_iff_cong_0)\n  hence \"[int z - int z' = int t * (int e - int e')] (mod order \\<G>)\"\n    by (simp add: right_diff_distrib)\n  hence \"[int z - int z' = int t * (e - e')] (mod order \\<G>)\" \n    using assms by (simp add: of_nat_diff)\n  hence \"[(int z - int z') * fst (bezw (e - e') (order \\<G>))  = int t * (e - e') * fst (bezw (e - e') (order \\<G>))] (mod order \\<G>)\"\n    using cong_scalar_right by blast\n  hence \"[(int z - int z') * fst (bezw (e - e') (order \\<G>))  = int t * ((e - e') * fst (bezw (e - e') (order \\<G>)))] (mod order \\<G>)\" \n    by (simp add: more_arith_simps(11))\n  hence \"[(int z - int z') * fst (bezw (e - e') (order \\<G>))  = int t * 1] (mod order \\<G>)\" \n    by (metis (no_types, hide_lams) cong_scalar_left cong_trans inverse gcd)\n  hence \"[(int z - int z') * fst (bezw (e - e') (order \\<G>)) mod order \\<G>  = t] (mod order \\<G>)\" \n    by simp\n  hence \"[nat ((int z - int z') * fst (bezw (e - e') (order \\<G>)) mod order \\<G>)  = t] (mod order \\<G>)\" \n    by (metis cong_def int_ops(9) mod_mod_trivial nat_int)\n  hence \"\\<^bold>g [^] (nat ((int z - int z') * fst (bezw (e - e') (order \\<G>)) mod order \\<G>))  = \\<^bold>g [^] t\" \n    using order_gt_0 order_gt_0_iff_finite pow_generator_eq_iff_cong by blast\n  thus ?thesis using t by simp\nqed\n\nlemma ss_rewrite2:\n  assumes \"fst h \\<in> carrier \\<G>\"\n    and \"snd h \\<in> carrier \\<G>\" \n    and \"a \\<in> carrier \\<G>\" \n    and \"b \\<in> carrier \\<G>\"\n    and \"e < order \\<G>\" \n    and \"a \\<otimes> fst h [^] e = \\<^bold>g [^] z\" \n    and \"b \\<otimes> snd h [^] e = g' [^] z\"\n    and \"e' < e\" \n    and \"a \\<otimes> fst h [^] e' = \\<^bold>g [^] z'\"\n    and \"b \\<otimes> snd h [^] e' = g' [^] z'\"\n  shows \"snd h = g' [^] ((int z - int z') * inverse (e - e') (order \\<G>) mod int (order \\<G>))\"\nproof-\n  have gcd: \"gcd (e - e') (order \\<G>) = 1\" \n    using prime_field assms prime_order by simp\n  have \"b = g' [^] z \\<otimes> inv (snd h [^] e)\"\n    by (simp add: assms inv_solve_right)\n  moreover have \"b = g' [^] z' \\<otimes> inv (snd h [^] e')\"\n    by (metis assms(2) assms(4) assms(10) g'_def generator_closed group.inv_solve_right' group_l_invI l_inv_ex nat_pow_closed)\n  ultimately have \"g' [^] z \\<otimes> snd h [^] e' = g' [^] z' \\<otimes> snd h [^] e\" \n    by (metis (no_types, lifting) assms cyclic_group_assoc cyclic_group_commute nat_pow_closed)\n  moreover obtain t :: nat where t: \"snd h = \\<^bold>g [^] t\"\n    using assms(2) generatorE by blast\n  ultimately have \"\\<^bold>g [^] (x * z + t * e') = \\<^bold>g [^] (x * z' + t * e)\"\n    using g'_def nat_pow_pow\n    by (simp add: nat_pow_mult) \n  hence \"[x * z + t * e' = x * z' + t * e] (mod order \\<G>)\"\n    using group_eq_pow_eq_mod order_gt_0 by blast\n  hence \"[int x * int z + int t * int e' = int x * int z' + int t * int e] (mod order \\<G>)\"\n    by (metis Groups.add_ac(2) Groups.mult_ac(2) cong_int_iff int_ops(7) int_plus)\n  hence \"[int x * int z - int x * int z' = int t * int e - int t * int e'] (mod order \\<G>)\"\n    by (smt cong_diff_iff_cong_0)\n  hence \"[int x * (int z - int z') = int t * (int e - int e')] (mod order \\<G>)\"\n    by (simp add: int_distrib(4))\n  hence \"[int x * (int z - int z') = int t * (e - e')] (mod order \\<G>)\"\n    using assms by (simp add: of_nat_diff)\n  hence \"[(int x * (int z - int z')) * fst (bezw (e - e') (order \\<G>)) = int t * (e - e') * fst (bezw (e - e') (order \\<G>))] (mod order \\<G>)\"\n    using cong_scalar_right by blast\n  hence \"[(int x * (int z - int z')) * fst (bezw (e - e') (order \\<G>)) = int t * ((e - e') * fst (bezw (e - e') (order \\<G>)))] (mod order \\<G>)\"\n    by (simp add: more_arith_simps(11))\n  hence *: \"[(int x * (int z - int z')) * fst (bezw (e - e') (order \\<G>)) = int t * 1] (mod order \\<G>)\"\n    by (metis (no_types, hide_lams) cong_scalar_left cong_trans gcd inverse)\n  hence \"[nat ((int x * (int z - int z')) * fst (bezw (e - e') (order \\<G>)) mod order \\<G>) = t] (mod order \\<G>)\"\n    by (metis cong_def cong_mod_right more_arith_simps(6) nat_int zmod_int)\n  hence \"\\<^bold>g [^] (nat ((int x * (int z - int z')) * fst (bezw (e - e') (order \\<G>)) mod order \\<G>)) = \\<^bold>g [^] t\"\n    using order_gt_0 order_gt_0_iff_finite pow_generator_eq_iff_cong by blast\n  thus ?thesis using t \n    by (metis (mono_tags, hide_lams) * cong_def g'_def generator_closed int_pow_int int_pow_pow mod_mult_right_eq more_arith_simps(11) more_arith_simps(6) pow_generator_mod_int)\nqed\n\nlemma ss_rewrite_snd_h:\n  assumes e_e'_mod: \"e' mod order \\<G> < e mod order \\<G>\"\n    and h_mem: \"snd h \\<in> carrier \\<G>\"\n    and a_mem: \"snd a \\<in> carrier \\<G>\"\n    and a1: \"snd a \\<otimes> snd h [^] e = g' [^] z\" \n    and a2: \"snd a \\<otimes> snd h [^] e' = g' [^] z'\" \n  shows \"snd h = g' [^] ((int z - int z') * fst (bezw ((e mod order \\<G> - e' mod order \\<G>) mod order \\<G>) (order \\<G>)) mod int (order \\<G>))\"\nproof-\n  have gcd: \"gcd ((e mod order \\<G> - e' mod order \\<G>) mod order \\<G>) (order \\<G>) = 1\"\n    using prime_field \n    by (simp add: assms less_imp_diff_less linorder_not_le prime_order)\n  have \"snd a = g' [^] z \\<otimes> inv (snd h [^] e)\"\n    using a1 \n    by (metis (no_types, lifting) Group.group.axioms(1) h_mem a_mem group.inv_closed group_l_invI l_inv_ex monoid.m_assoc nat_pow_closed r_inv r_one)\n  moreover have \"snd a = g' [^] z' \\<otimes> inv (snd h [^] e')\"\n    by (metis a2 h_mem a_mem g'_def generator_closed group.inv_solve_right' group_l_invI l_inv_ex nat_pow_closed)\n  ultimately have \"g' [^] z \\<otimes> snd h [^] e' = g' [^] z' \\<otimes> snd h [^] e\" \n    by (metis (no_types, lifting) a2 h_mem a_mem a1 cyclic_group_assoc cyclic_group_commute nat_pow_closed)\n  moreover obtain t :: nat where t: \"snd h = \\<^bold>g [^] t\"\n    using assms(2) generatorE by blast\n  ultimately have \"\\<^bold>g [^] (x * z + t * e') = \\<^bold>g [^] (x * z' + t * e)\"\n    using g'_def nat_pow_pow\n    by (simp add: nat_pow_mult) \n  hence \"[x * z + t * e' = x * z' + t * e] (mod order \\<G>)\"\n    using group_eq_pow_eq_mod order_gt_0 by blast\n  hence \"[int x * int z + int t * int e' = int x * int z' + int t * int e] (mod order \\<G>)\"\n    by (metis Groups.add_ac(2) Groups.mult_ac(2) cong_int_iff int_ops(7) int_plus)\n  hence \"[int x * int z - int x * int z' = int t * int e - int t * int e'] (mod order \\<G>)\"\n    by (smt cong_diff_iff_cong_0)\n  hence \"[int x * (int z - int z') = int t * (int e - int e')] (mod order \\<G>)\"\n    by (simp add: int_distrib(4))\n  hence \"[int x * (int z - int z') = int t * (int e mod order \\<G> - int e' mod order \\<G>) mod order \\<G>] (mod order \\<G>)\"\n    by (metis (no_types, lifting) cong_def mod_diff_eq mod_mod_trivial mod_mult_right_eq)\n  hence *: \"[int x * (int z - int z') = int t * (e mod order \\<G> - e' mod order \\<G>) mod order \\<G>] (mod order \\<G>)\"\n    by (simp add: assms(1) int_ops(9) less_imp_le_nat of_nat_diff)\n  hence \"[int x * (int z - int z') * fst (bezw ((e mod order \\<G> - e' mod order \\<G>) mod order \\<G>) (order \\<G>)) \n               = int t * ((e mod order \\<G> - e' mod order \\<G>) mod order \\<G> \n                  * fst (bezw ((e mod order \\<G> - e' mod order \\<G>) mod order \\<G>) (order \\<G>)))] (mod order \\<G>)\"\n    by (metis (no_types, lifting) cong_mod_right cong_scalar_right less_imp_diff_less mod_if more_arith_simps(11) or_gt_0 unique_euclidean_semiring_numeral_class.pos_mod_bound)\n  hence \"[int x * (int z - int z') * fst (bezw ((e mod order \\<G> - e' mod order \\<G>) mod order \\<G>) (order \\<G>)) \n               = int t * 1] (mod order \\<G>)\"\n    by (meson Number_Theory_Aux.inverse * gcd cong_scalar_left cong_trans)\n  hence \"\\<^bold>g [^] (int x * (int z - int z') * fst (bezw ((e mod order \\<G> - e' mod order \\<G>) mod order \\<G>) (order \\<G>))) = \\<^bold>g [^] t\"\n    by (metis cong_def int_pow_int more_arith_simps(6) pow_generator_mod_int)\n  thus ?thesis using t \n    by (metis (mono_tags, hide_lams) g'_def generator_closed int_pow_int int_pow_pow mod_mult_right_eq more_arith_simps(11) pow_generator_mod_int)\nqed\n\nlemma special_soundness:\n  shows \"chaum_ped_sigma.special_soundness\"\n  unfolding chaum_ped_sigma.special_soundness_def \n  apply(auto simp add: challenge_space_def check_def ss_adversary_def R_def valid_pub_def)\n  using ss_rewrite2 ss_rewrite1 by auto\n\ntheorem \\<Sigma>_protocol:  \"chaum_ped_sigma.\\<Sigma>_protocol\"\n  by(simp add: chaum_ped_sigma.\\<Sigma>_protocol_def completeness HVZK special_soundness)\n\nsublocale chaum_ped_\\<Sigma>_commit: \\<Sigma>_protocols_to_commitments init response check R S2 ss_adversary challenge_space valid_pub G\n  apply unfold_locales\n      apply(auto simp add: \\<Sigma>_protocol lossless_init lossless_response lossless_G)\n  by(simp add: R_def G_def)\n\nsublocale dis_log: dis_log \\<G> \n  unfolding dis_log_def by simp\n\nsublocale dis_log_alt: dis_log_alt \\<G> x \n  unfolding dis_log_alt_def by simp\n\nlemma reduction_to_dis_log: \n  shows \"chaum_ped_\\<Sigma>_commit.rel_advantage \\<A> = dis_log.advantage (dis_log_alt.adversary3 \\<A>)\"\nproof-\n  have \"chaum_ped_\\<Sigma>_commit.rel_game \\<A> = TRY do {\n    w \\<leftarrow> sample_uniform (order \\<G>);\n    let (h,w) = ((\\<^bold>g [^] w, g' [^] w), w);\n    w' \\<leftarrow> \\<A> h;\n    return_spmf ((fst h = \\<^bold>g [^] w' \\<and> snd h = g' [^] w'))} ELSE return_spmf False\"\n    unfolding chaum_ped_\\<Sigma>_commit.rel_game_def \n    by(simp add:  G_def R_def)\n  also have \"... = TRY do {    \n    w \\<leftarrow> sample_uniform (order \\<G>);\n    let (h,w) = ((\\<^bold>g [^] w, g' [^] w), w);\n    w' \\<leftarrow> \\<A> h;\n    return_spmf ([w = w'] (mod (order \\<G>)) \\<and> [x*w = x*w'] (mod order \\<G>))} ELSE return_spmf False\"\n    apply(intro try_spmf_cong bind_spmf_cong[OF refl]; simp add: dis_log_alt.dis_log3_def dis_log_alt.g'_def g'_def)\n    by (simp add: finite_carrier nat_pow_pow pow_generator_eq_iff_cong)\n  also have \"... = dis_log_alt.dis_log3 \\<A>\"\n    apply(auto simp add:  dis_log_alt.dis_log3_def dis_log_alt.g'_def g'_def)\n    by(intro try_spmf_cong  bind_spmf_cong[OF refl]; clarsimp?; auto simp add: cong_scalar_left)\n  ultimately have \"chaum_ped_\\<Sigma>_commit.rel_advantage \\<A> = dis_log_alt.advantage3 \\<A>\"\n    by(simp add: chaum_ped_\\<Sigma>_commit.rel_advantage_def dis_log_alt.advantage3_def)\n  thus ?thesis\n    by (simp add: dis_log_alt_reductions.dis_log_adv3 cyclic_group_axioms dis_log_alt.dis_log_alt_axioms dis_log_alt_reductions.intro)\nqed\n\nlemma commitment_correct: \"chaum_ped_\\<Sigma>_commit.abstract_com.correct\"\n  by(simp add: chaum_ped_\\<Sigma>_commit.commit_correct)\n\nlemma  \"chaum_ped_\\<Sigma>_commit.abstract_com.perfect_hiding_ind_cpa \\<A>\"\n  using chaum_ped_\\<Sigma>_commit.perfect_hiding by blast\n\n\n\nend\n\nlocale chaum_ped_asymp = \n  fixes \\<G> :: \"nat \\<Rightarrow> 'grp cyclic_group\"\n    and x :: nat\n  assumes cp_\\<Sigma>: \"\\<And>\\<eta>. chaum_ped_\\<Sigma> (\\<G> \\<eta>)\"\nbegin\n\nsublocale chaum_ped_\\<Sigma> \"\\<G> \\<eta>\" for \\<eta> \n  by(simp add: cp_\\<Sigma>)\n\ntext\\<open>The \\<open>\\<Sigma>\\<close>-protocol statement comes easily in the asympotic setting.\\<close>\n\ntheorem sigma_protocol:\n  shows \"chaum_ped_sigma.\\<Sigma>_protocol n\"\n  by(simp add: \\<Sigma>_protocol)\n\ntext\\<open>We now show the statements of security for the commitment scheme in the asymptotic setting, the main difference is that\nwe are able to show the binding advantage is negligible in the security parameter.\\<close>\n\nlemma asymp_correct: \"chaum_ped_\\<Sigma>_commit.abstract_com.correct n\" \n  using  chaum_ped_\\<Sigma>_commit.commit_correct by simp\n\nlemma asymp_perfect_hiding: \"chaum_ped_\\<Sigma>_commit.abstract_com.perfect_hiding_ind_cpa n (\\<A> n)\"\n  using chaum_ped_\\<Sigma>_commit.perfect_hiding by blast\n\n\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/Sigma_Commit_Crypto/Chaum_Pedersen_Sigma_Commit.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.905989815306765, "lm_q2_score": 0.819893340314393, "lm_q1q2_score": 0.7428150159626835}}
{"text": "(* ------------------------------------------------------------------ *)\nsection \\<open>H-lines in the Poincar\\'e model\\<close>\n(* ------------------------------------------------------------------ *)\n\ntheory Poincare_Lines\n  imports Complex_Geometry.Unit_Circle_Preserving_Moebius Complex_Geometry.Circlines_Angle\nbegin\n\n\n(* ------------------------------------------------------------------ *)\nsubsection \\<open>Definition and basic properties of h-lines\\<close>\n(* ------------------------------------------------------------------ *)\n\ntext \\<open>H-lines in the Poincar\\'e model are either line segments passing trough the origin or\nsegments (within the unit disc) of circles that are perpendicular to the unit circle. Algebraically\nthese are circlines that are represented by Hermitean matrices of\nthe form\n$$H = \\left(\n \\begin{array}{cc}\n A & B\\\\\n \\overline{B} & A\n \\end{array}\n\\right),$$\nfor $A \\in \\mathbb{R}$, and $B \\in \\mathbb{C}$, and $|B|^2 > A^2$,\nwhere the circline equation is the usual one: $z^*Hz = 0$, for homogenous coordinates $z$.\\<close>\n\ndefinition is_poincare_line_cmat :: \"complex_mat \\<Rightarrow> bool\" where\n  [simp]: \"is_poincare_line_cmat H \\<longleftrightarrow>\n             (let (A, B, C, D) = H\n               in hermitean (A, B, C, D) \\<and> A = D \\<and> (cmod B)\\<^sup>2 > (cmod A)\\<^sup>2)\"\n\nlift_definition is_poincare_line_clmat :: \"circline_mat \\<Rightarrow> bool\" is is_poincare_line_cmat\n  done\n\ntext \\<open>We introduce the predicate that checks if a given complex matrix is a matrix of a h-line in\nthe Poincar\\'e model, and then by means of the lifting package lift it to the type of non-zero\nHermitean matrices, and then to circlines (that are equivalence classes of such matrices).\\<close>\n\nlift_definition is_poincare_line :: \"circline \\<Rightarrow> bool\" is is_poincare_line_clmat\nproof (transfer, transfer)\n  fix H1 H2 :: complex_mat\n  assume hh: \"hermitean H1 \\<and> H1 \\<noteq> mat_zero\" \"hermitean H2 \\<and> H2 \\<noteq> mat_zero\"\n  assume \"circline_eq_cmat H1 H2\"\n  thus \"is_poincare_line_cmat H1 \\<longleftrightarrow> is_poincare_line_cmat H2\"\n    using hh\n    by (cases H1, cases H2) (auto simp add: power_mult_distrib)\nqed\n\nlemma is_poincare_line_mk_circline:\n  assumes \"(A, B, C, D) \\<in> hermitean_nonzero\"\n  shows \"is_poincare_line (mk_circline A B C D) \\<longleftrightarrow> (cmod B)\\<^sup>2 > (cmod A)\\<^sup>2 \\<and> A = D\"\n  using assms\n  by (transfer, transfer, auto simp add: Let_def)\n\n\ntext\\<open>Abstract characterisation of @{term is_poincare_line} predicate: H-lines in the Poincar\\'e\nmodel are real circlines (circlines with the negative determinant) perpendicular to the unit\ncircle.\\<close>\n\nlemma is_poincare_line_iff:\n  shows \"is_poincare_line H \\<longleftrightarrow> circline_type H = -1 \\<and> perpendicular H unit_circle\"\n  unfolding perpendicular_def\nproof (simp, transfer, transfer)\n  fix H\n  assume hh: \"hermitean H \\<and> H \\<noteq> mat_zero\"\n  obtain A B C D where *: \"H = (A, B, C, D)\"\n    by (cases H, auto)\n  have **: \"is_real A\" \"is_real D\" \"C = cnj B\"\n    using hh * hermitean_elems\n    by auto\n  hence \"(Re A = Re D \\<and> cmod A * cmod A < cmod B * cmod B) =\n         (Re A * Re D < Re B * Re B + Im B * Im B \\<and> (Re D = Re A \\<or> Re A * Re D = Re B * Re B + Im B * Im B))\"\n    using *\n    by (smt cmod_power2 power2_eq_square zero_power2)+\n  thus \"is_poincare_line_cmat H \\<longleftrightarrow>\n         circline_type_cmat H = - 1 \\<and> cos_angle_cmat (of_circline_cmat H) unit_circle_cmat = 0\"\n    using * **\n    by (auto simp add: sgn_1_neg complex_eq_if_Re_eq cmod_square power2_eq_square simp del: pos_oriented_cmat_def)\nqed\n\ntext\\<open>The @{term x_axis} is an h-line.\\<close>\nlemma is_poincare_line_x_axis [simp]:\n  shows \"is_poincare_line x_axis\"\n  by (transfer, transfer) (auto simp add: hermitean_def mat_adj_def mat_cnj_def)\n\ntext\\<open>The @{term unit_circle} is not an h-line.\\<close>\nlemma not_is_poincare_line_unit_circle [simp]:\n  shows \"\\<not> is_poincare_line unit_circle\"\n  by (transfer, transfer, simp)\n\n(* ------------------------------------------------------------------ *)\nsubsubsection \\<open>Collinear points\\<close>\n(* ------------------------------------------------------------------ *)\n\ntext\\<open>Points are collinear if they all belong to an h-line. \\<close>\ndefinition poincare_collinear :: \"complex_homo set \\<Rightarrow> bool\" where\n  \"poincare_collinear S \\<longleftrightarrow> (\\<exists> p. is_poincare_line p \\<and> S \\<subseteq> circline_set p)\"\n\n(* ------------------------------------------------------------------ *)\nsubsubsection \\<open>H-lines and inversion\\<close>\n(* ------------------------------------------------------------------ *)\n\ntext\\<open>Every h-line in the Poincar\\'e model contains the inverse (wrt.~the unit circle) of each of its\npoints (note that at most one of them belongs to the unit disc).\\<close>\nlemma is_poincare_line_inverse_point:\n  assumes \"is_poincare_line H\" \"u \\<in> circline_set H\"\n  shows \"inversion u \\<in> circline_set H\"\n  using assms\n  unfolding is_poincare_line_iff circline_set_def perpendicular_def inversion_def\n  apply simp\nproof (transfer, transfer)\n  fix u H\n  assume hh: \"hermitean H \\<and> H \\<noteq> mat_zero\" \"u \\<noteq> vec_zero\" and\n         aa: \"circline_type_cmat H = - 1 \\<and> cos_angle_cmat (of_circline_cmat H) unit_circle_cmat = 0\" \"on_circline_cmat_cvec H u\"\n  obtain A B C D u1 u2 where *: \"H = (A, B, C, D)\" \"u = (u1, u2)\"\n    by (cases H, cases u, auto)\n  have \"is_real A\" \"is_real D\" \"C = cnj B\"\n    using * hh hermitean_elems\n    by auto\n  moreover\n  have \"A = D\"\n    using aa(1) * \\<open>is_real A\\<close> \\<open>is_real D\\<close>\n    by (auto simp del: pos_oriented_cmat_def simp add: complex.expand split: if_split_asm)\n  thus \"on_circline_cmat_cvec H (conjugate_cvec (reciprocal_cvec u))\"\n    using aa(2) *\n    by (simp add: vec_cnj_def field_simps)\nqed\n\ntext\\<open>Every h-line in the Poincar\\'e model and is invariant under unit circle inversion.\\<close>\n\nlemma circline_inversion_poincare_line:\n  assumes \"is_poincare_line H\"\n  shows \"circline_inversion H = H\"\nproof-\n  obtain u v w where *: \"u \\<noteq> v\" \"v \\<noteq> w\" \"u \\<noteq> w\" \"{u, v, w} \\<subseteq> circline_set H\"\n    using assms is_poincare_line_iff[of H]\n    using circline_type_neg_card_gt3[of H]\n    by auto\n  hence \"{inversion u, inversion v, inversion w} \\<subseteq> circline_set (circline_inversion H)\"\n        \"{inversion u, inversion v, inversion w} \\<subseteq> circline_set H\"\n    using is_poincare_line_inverse_point[OF assms]\n    by auto\n  thus ?thesis\n    using * unique_circline_set[of \"inversion u\" \"inversion v\" \"inversion w\"]\n    by (metis insert_subset inversion_involution)\nqed\n\n(* ------------------------------------------------------------------ *)\nsubsubsection \\<open>Classification of h-lines into Euclidean segments and circles\\<close>\n(* ------------------------------------------------------------------ *)\n\ntext\\<open>If an h-line contains zero, than it also contains infinity (the inverse point of zero) and is by\ndefinition an Euclidean line.\\<close>\nlemma is_poincare_line_trough_zero_trough_infty [simp]:\n  assumes \"is_poincare_line l\" and \"0\\<^sub>h \\<in> circline_set l\"\n  shows \"\\<infinity>\\<^sub>h \\<in> circline_set l\"\n  using is_poincare_line_inverse_point[OF assms]\n  by simp\n\nlemma is_poincare_line_trough_zero_is_line:\n  assumes \"is_poincare_line l\" and \"0\\<^sub>h \\<in> circline_set l\"\n  shows \"is_line l\"\n  using assms\n  using inf_in_circline_set is_poincare_line_trough_zero_trough_infty\n  by blast\n\ntext\\<open>If an h-line does not contain zero, than it also does not contain infinity (the inverse point of\nzero) and is by definition an Euclidean circle.\\<close>\nlemma is_poincare_line_not_trough_zero_not_trough_infty [simp]:\n  assumes \"is_poincare_line l\"\n  assumes \"0\\<^sub>h \\<notin> circline_set l\"\n  shows \"\\<infinity>\\<^sub>h \\<notin> circline_set l\"\n  using assms\n  using is_poincare_line_inverse_point[OF assms(1), of \"\\<infinity>\\<^sub>h\"]\n  by auto\n\nlemma is_poincare_line_not_trough_zero_is_circle:\n  assumes \"is_poincare_line l\" \"0\\<^sub>h \\<notin> circline_set l\"\n  shows \"is_circle l\"\n  using assms\n  using inf_in_circline_set is_poincare_line_not_trough_zero_not_trough_infty\n  by auto\n\n(* ------------------------------------------------------------------ *)\nsubsubsection\\<open>Points on h-line\\<close>\n(* ------------------------------------------------------------------ *)\n\ntext\\<open>Each h-line in the Poincar\\'e model contains at least two different points within the unit\ndisc.\\<close>\n\ntext\\<open>First we prove an auxiliary lemma.\\<close>\nlemma ex_is_poincare_line_points':\n  assumes i12: \"i1 \\<in> circline_set H \\<inter> unit_circle_set\"\n               \"i2 \\<in> circline_set H \\<inter> unit_circle_set\"\n               \"i1 \\<noteq> i2\"\n  assumes a: \"a \\<in> circline_set H\" \"a \\<notin> unit_circle_set\"\n  shows \"\\<exists> b. b \\<noteq> i1 \\<and> b \\<noteq> i2 \\<and> b \\<noteq> a \\<and> b \\<noteq> inversion a \\<and> b \\<in> circline_set H\"\nproof-\n  have \"inversion a \\<notin> unit_circle_set\"\n    using \\<open>a \\<notin> unit_circle_set\\<close> \n    unfolding unit_circle_set_def circline_set_def\n    by (metis inversion_id_iff_on_unit_circle inversion_involution mem_Collect_eq)\n\n  have \"a \\<noteq> inversion a\"\n    using \\<open>a \\<notin> unit_circle_set\\<close> inversion_id_iff_on_unit_circle[of a]\n    unfolding unit_circle_set_def circline_set_def\n    by auto\n\n  have \"a \\<noteq> i1\" \"a \\<noteq> i2\" \"inversion a \\<noteq> i1\" \"inversion a \\<noteq> i2\"\n    using assms \\<open>inversion a \\<notin> unit_circle_set\\<close>\n    by auto\n\n  then obtain b where cr2: \"cross_ratio b i1 a i2 = of_complex 2\"\n    using \\<open>i1 \\<noteq> i2\\<close>\n    using ex_cross_ratio[of i1 a i2]\n    by blast\n\n  have distinct_b: \"b \\<noteq> i1\" \"b \\<noteq> i2\" \"b \\<noteq> a\"\n    using \\<open>i1 \\<noteq> i2\\<close> \\<open>a \\<noteq> i1\\<close> \\<open>a \\<noteq> i2\\<close>\n    using ex1_cross_ratio[of i1 a i2]\n    using cross_ratio_0[of i1 a i2] cross_ratio_1[of i1 a i2] cross_ratio_inf[of i1 i2 a]\n    using cr2\n    by auto\n\n  hence \"b \\<in> circline_set H\" \n    using assms four_points_on_circline_iff_cross_ratio_real[of b i1 a i2] cr2\n    using unique_circline_set[of i1 i2 a]\n    by auto\n\n  moreover\n\n  have \"b \\<noteq> inversion a\"\n  proof (rule ccontr)\n    assume *: \"\\<not> ?thesis\"\n    have \"inversion i1 = i1\" \"inversion i2 = i2\"\n      using i12\n      unfolding unit_circle_set_def\n      by auto\n    hence \"cross_ratio (inversion a) i1 a i2 = cross_ratio a i1 (inversion a) i2\"\n      using * cross_ratio_inversion[of i1 a i2 b] \\<open>a \\<noteq> i1\\<close> \\<open>a \\<noteq> i2\\<close> \\<open>i1 \\<noteq> i2\\<close> \\<open>b \\<noteq> i1\\<close>\n      using four_points_on_circline_iff_cross_ratio_real[of b i1 a i2]\n      using i12 distinct_b conjugate_id_iff[of \"cross_ratio b i1 a i2\"]\n      using i12 a \\<open>b \\<in> circline_set H\\<close>            \n      by auto\n    hence \"cross_ratio (inversion a) i1 a i2 \\<noteq> of_complex 2\"\n      using cross_ratio_commute_13[of \"inversion a\" i1 a i2]\n      using reciprocal_id_iff\n      using of_complex_inj\n      by force\n    thus False\n      using * cr2\n      by simp\n  qed\n\n  ultimately\n  show ?thesis\n    using assms \\<open>b \\<noteq> i1\\<close> \\<open>b \\<noteq> i2\\<close> \\<open>b \\<noteq> a\\<close>\n    by auto\nqed\n\ntext\\<open>Now we can prove the statement.\\<close>\nlemma ex_is_poincare_line_points:\n  assumes \"is_poincare_line H\"\n  shows \"\\<exists> u v. u \\<in> unit_disc \\<and> v \\<in> unit_disc \\<and> u \\<noteq> v \\<and> {u, v} \\<subseteq> circline_set H\"\nproof-\n  obtain u v w where *: \"u \\<noteq> v\" \"v \\<noteq> w\" \"u \\<noteq> w\" \"{u, v, w} \\<subseteq> circline_set H\"\n    using assms is_poincare_line_iff[of H]\n    using circline_type_neg_card_gt3[of H]\n    by auto\n\n  have \"\\<not> {u, v, w} \\<subseteq> unit_circle_set\"\n    using unique_circline_set[of u v w] *\n    by (metis assms insert_subset not_is_poincare_line_unit_circle unit_circle_set_def)\n\n  hence \"H \\<noteq> unit_circle\"\n    unfolding unit_circle_set_def\n    using *\n    by auto\n\n  show ?thesis\n  proof (cases \"(u \\<in> unit_disc \\<and> v \\<in> unit_disc) \\<or>\n                (u \\<in> unit_disc \\<and> w \\<in> unit_disc) \\<or>\n                (v \\<in> unit_disc \\<and> w \\<in> unit_disc)\")\n    case True\n    thus ?thesis\n      using *\n      by auto\n  next\n    case False\n\n    have \"\\<exists> a b. a \\<noteq> b \\<and> a \\<noteq> inversion b \\<and> a \\<in> circline_set H \\<and> b \\<in> circline_set H \\<and> a \\<notin> unit_circle_set \\<and> b \\<notin> unit_circle_set\"\n    proof (cases \"(u \\<in> unit_circle_set \\<and> v \\<in> unit_circle_set) \\<or>\n                  (u \\<in> unit_circle_set \\<and> w \\<in> unit_circle_set) \\<or>\n                  (v \\<in> unit_circle_set \\<and> w \\<in> unit_circle_set)\")\n      case True\n      then obtain i1 i2 a where *:\n        \"i1 \\<in> unit_circle_set \\<inter> circline_set H\" \"i2 \\<in> unit_circle_set \\<inter> circline_set H\" \n        \"a \\<in> circline_set H\" \"a \\<notin> unit_circle_set\"\n        \"i1 \\<noteq> i2\" \"i1 \\<noteq> a\" \"i2 \\<noteq> a\"\n        using * \\<open>\\<not> {u, v, w} \\<subseteq> unit_circle_set\\<close>\n        by auto\n      then obtain b where \"b \\<in> circline_set H\" \"b \\<noteq> i1\" \"b \\<noteq> i2\" \"b \\<noteq> a\" \"b \\<noteq> inversion a\"\n        using ex_is_poincare_line_points'[of i1 H i2 a]\n        by blast\n\n      hence \"b \\<notin> unit_circle_set\"\n        using * \\<open>H \\<noteq> unit_circle\\<close> unique_circline_set[of i1 i2 b]\n        unfolding unit_circle_set_def\n        by auto\n        \n      thus ?thesis\n        using * \\<open>b \\<in> circline_set H\\<close> \\<open>b \\<noteq> a\\<close> \\<open>b \\<noteq> inversion a\\<close>\n        by auto\n    next\n      case False  \n      then obtain f g h where\n        *: \"f \\<noteq> g\" \"f \\<in> circline_set H\" \"f \\<notin> unit_circle_set\"  \n                    \"g \\<in> circline_set H\" \"g \\<notin> unit_circle_set\"\n                    \"h \\<in> circline_set H\" \"h \\<noteq> f\" \"h \\<noteq> g\"\n        using *\n        by auto\n      show ?thesis\n      proof (cases \"f = inversion g\")   \n        case False\n        thus ?thesis\n          using *\n          by auto\n      next\n        case True\n        show ?thesis\n        proof (cases \"h \\<in> unit_circle_set\")\n          case False\n          thus ?thesis\n            using * \\<open>f = inversion g\\<close>\n            by auto\n        next\n          case True\n          obtain m where cr2: \"cross_ratio m h f g = of_complex 2\"\n            using ex_cross_ratio[of h f g] * \\<open>f \\<noteq> g\\<close> \\<open>h \\<noteq> f\\<close> \\<open>h \\<noteq> g\\<close>\n            by auto\n          hence \"m \\<noteq> h\" \"m \\<noteq> f\" \"m \\<noteq> g\"\n            using \\<open>h \\<noteq> f\\<close> \\<open>h \\<noteq> g\\<close> \\<open>f \\<noteq> g\\<close>\n            using ex1_cross_ratio[of h f g]\n            using cross_ratio_0[of h f g] cross_ratio_1[of h f g] cross_ratio_inf[of h g f]\n            using cr2\n            by auto\n          hence \"m \\<in> circline_set H\" \n            using four_points_on_circline_iff_cross_ratio_real[of m h f g] cr2\n            using \\<open>h \\<noteq> f\\<close> \\<open>h \\<noteq> g\\<close> \\<open>f \\<noteq> g\\<close> *\n            using unique_circline_set[of h f g]\n            by auto\n\n          show ?thesis\n          proof (cases \"m \\<in> unit_circle_set\")\n            case False\n            thus ?thesis\n              using \\<open>m \\<noteq> f\\<close> \\<open>m \\<noteq> g\\<close> \\<open>f = inversion g\\<close> * \\<open>m \\<in> circline_set H\\<close>\n              by auto\n          next\n            case True\n            then obtain n where \"n \\<noteq> h\" \"n \\<noteq> m\" \"n \\<noteq> f\" \"n \\<noteq> inversion f\" \"n \\<in> circline_set H\"\n              using ex_is_poincare_line_points'[of h H m f] * \\<open>m \\<in> circline_set H\\<close> \\<open>h \\<in> unit_circle_set\\<close> \\<open>m \\<noteq> h\\<close>\n              by auto\n            hence \"n \\<notin> unit_circle_set\"\n              using * \\<open>H \\<noteq> unit_circle\\<close> unique_circline_set[of m n h] \n              using \\<open>m \\<noteq> h\\<close> \\<open>m \\<in> unit_circle_set\\<close> \\<open>h \\<in> unit_circle_set\\<close> \\<open>m \\<in> circline_set H\\<close>\n              unfolding unit_circle_set_def\n              by auto\n        \n            thus ?thesis\n              using * \\<open>n \\<in> circline_set H\\<close> \\<open>n \\<noteq> f\\<close> \\<open>n \\<noteq> inversion f\\<close>\n              by auto\n          qed\n        qed\n      qed\n    qed\n    then obtain a b where ab: \"a \\<noteq> b\" \"a \\<noteq> inversion b\" \"a \\<in> circline_set H\" \"b \\<in> circline_set H\" \"a \\<notin> unit_circle_set\" \"b \\<notin> unit_circle_set\"\n      by blast\n    have \"\\<forall> x. x \\<in> circline_set H \\<and> x \\<notin> unit_circle_set \\<longrightarrow> (\\<exists> x'. x' \\<in> circline_set H \\<inter> unit_disc \\<and> (x' = x \\<or> x' = inversion x))\"\n    proof safe\n      fix x\n      assume x: \"x \\<in> circline_set H\" \"x \\<notin> unit_circle_set\" \n      show \"\\<exists> x'. x' \\<in> circline_set H \\<inter> unit_disc \\<and> (x' = x \\<or> x' = inversion x)\"\n      proof (cases \"x \\<in> unit_disc\")\n        case True\n        thus ?thesis\n          using x\n          by auto\n      next\n        case False\n        hence \"x \\<in> unit_disc_compl\"\n          using x  in_on_out_univ[of \"ounit_circle\"]\n          unfolding unit_circle_set_def unit_disc_def unit_disc_compl_def\n          by auto\n        hence \"inversion x \\<in> unit_disc\"\n          using inversion_unit_disc_compl\n          by blast\n        thus ?thesis\n          using is_poincare_line_inverse_point[OF assms, of x] x\n          by auto\n      qed\n    qed\n    then obtain a' b' where \n      *: \"a' \\<in> circline_set H\" \"a' \\<in> unit_disc\" \"b' \\<in> circline_set H\" \"b' \\<in> unit_disc\" and\n      **: \"a' = a \\<or> a' = inversion a\" \"b' = b \\<or> b' = inversion b\" \n      using ab\n      by blast\n    have \"a' \\<noteq> b'\"\n      using \\<open>a \\<noteq> b\\<close> \\<open>a \\<noteq> inversion b\\<close> ** *\n      by (metis inversion_involution)\n    thus ?thesis\n      using *\n      by auto\n  qed\nqed\n\n(* ------------------------------------------------------------------ *)\nsubsubsection \\<open>H-line uniqueness\\<close>\n(* ------------------------------------------------------------------ *)\n\ntext\\<open>There is no more than one h-line that contains two different h-points (in the disc).\\<close>\nlemma unique_is_poincare_line:\n  assumes in_disc: \"u \\<in> unit_disc\" \"v \\<in> unit_disc\" \"u \\<noteq> v\"\n  assumes pl: \"is_poincare_line l1\" \"is_poincare_line l2\"\n  assumes on_l: \"{u, v} \\<subseteq> circline_set l1 \\<inter> circline_set l2\"\n  shows \"l1 = l2\"\nproof-\n  have \"u \\<noteq> inversion u\" \"v \\<noteq> inversion u\"\n    using in_disc\n    using inversion_noteq_unit_disc[of u v]\n    using inversion_noteq_unit_disc[of u u]\n    by auto\n  thus ?thesis\n    using on_l\n    using unique_circline_set[of u \"inversion u\" \"v\"] \\<open>u \\<noteq> v\\<close>\n    using is_poincare_line_inverse_point[of l1 u]\n    using is_poincare_line_inverse_point[of l2 u]\n    using pl\n    by auto                                                                            \nqed\n\ntext\\<open>For the rest of our formalization it is often useful to consider points on h-lines that are not\nwithin the unit disc. Many lemmas in the rest of this section will have such generalizations.\\<close>\n\ntext\\<open>There is no more than one h-line that contains two different and not mutually inverse points\n(not necessary in the unit disc).\\<close>\nlemma unique_is_poincare_line_general:\n  assumes different: \"u \\<noteq> v\" \"u \\<noteq> inversion v\"\n  assumes pl: \"is_poincare_line l1\" \"is_poincare_line l2\"\n  assumes on_l: \"{u, v} \\<subseteq> circline_set l1 \\<inter> circline_set l2\"\n  shows  \"l1 = l2\"\nproof (cases \"u \\<noteq> inversion u\")\n  case True\n  thus ?thesis\n    using unique_circline_set[of u \"inversion u\" \"v\"]\n    using assms\n    using is_poincare_line_inverse_point by force\nnext\n  case False\n  show ?thesis\n  proof (cases \"v \\<noteq> inversion v\")\n    case True\n    thus ?thesis\n      using unique_circline_set[of u \"inversion v\" \"v\"]\n      using assms\n      using is_poincare_line_inverse_point by force\n  next\n    case False\n\n    have \"on_circline unit_circle u\" \"on_circline unit_circle v\"\n      using `\\<not> u \\<noteq> inversion u` `\\<not> v \\<noteq> inversion v`\n      using inversion_id_iff_on_unit_circle\n      by fastforce+\n    thus ?thesis\n      using pl on_l `u \\<noteq> v`\n      unfolding circline_set_def\n      apply simp\n    proof (transfer, transfer, safe)\n      fix u1 u2 v1 v2 A1 B1 C1 D1 A2 B2 C2 D2 :: complex\n      let ?u = \"(u1, u2)\" and ?v = \"(v1, v2)\" and  ?H1 = \"(A1, B1, C1, D1)\" and ?H2 = \"(A2, B2, C2, D2)\"\n      assume *: \"?u \\<noteq> vec_zero\" \"?v \\<noteq> vec_zero\"\n        \"on_circline_cmat_cvec unit_circle_cmat ?u\" \"on_circline_cmat_cvec unit_circle_cmat ?v\" \n        \"is_poincare_line_cmat ?H1\" \"is_poincare_line_cmat ?H2\"\n        \"hermitean ?H1\" \"?H1 \\<noteq> mat_zero\" \"hermitean ?H2\" \"?H2 \\<noteq> mat_zero\"\n        \"on_circline_cmat_cvec ?H1 ?u\" \"on_circline_cmat_cvec ?H1 ?v\"\n        \"on_circline_cmat_cvec ?H2 ?u\" \"on_circline_cmat_cvec ?H2 ?v\"\n        \"\\<not> (u1, u2) \\<approx>\\<^sub>v (v1, v2)\"\n      have **: \"A1 = D1\" \"A2 = D2\" \"C1 = cnj B1\" \"C2 = cnj B2\" \"is_real A1\" \"is_real A2\"\n        using `is_poincare_line_cmat ?H1` `is_poincare_line_cmat ?H2`\n        using `hermitean ?H1` `?H1 \\<noteq> mat_zero` `hermitean ?H2` `?H2 \\<noteq> mat_zero`\n        using hermitean_elems\n        by auto\n\n      have uv: \"u1 \\<noteq> 0\" \"u2 \\<noteq> 0\" \"v1 \\<noteq> 0\" \"v2 \\<noteq> 0\"\n        using *(1-4)\n        by (auto simp add: vec_cnj_def)\n\n      have u: \"cor ((Re (u1/u2))\\<^sup>2) + cor ((Im (u1/u2))\\<^sup>2) = 1\"\n        using `on_circline_cmat_cvec unit_circle_cmat ?u` uv\n        apply (subst cor_add[symmetric])\n        apply (subst complex_mult_cnj[symmetric])\n        apply (simp add: vec_cnj_def mult.commute)\n        done\n\n      have v: \"cor ((Re (v1/v2))\\<^sup>2) + cor ((Im (v1/v2))\\<^sup>2) = 1\"\n        using `on_circline_cmat_cvec unit_circle_cmat ?v` uv\n        apply (subst cor_add[symmetric])\n        apply (subst complex_mult_cnj[symmetric])\n        apply (simp add: vec_cnj_def mult.commute)\n        done\n\n      have \n        \"A1 * (cor ((Re (u1/u2))\\<^sup>2) + cor ((Im (u1/u2))\\<^sup>2) + 1) + cor (Re B1) * cor(2 * Re (u1/u2)) + cor (Im B1) * cor(2 * Im (u1/u2)) = 0\"\n        \"A2 * (cor ((Re (u1/u2))\\<^sup>2) + cor ((Im (u1/u2))\\<^sup>2) + 1) + cor (Re B2) * cor(2 * Re (u1/u2)) + cor (Im B2) * cor(2 * Im (u1/u2)) = 0\"\n        \"A1 * (cor ((Re (v1/v2))\\<^sup>2) + cor ((Im (v1/v2))\\<^sup>2) + 1) + cor (Re B1) * cor(2 * Re (v1/v2)) + cor (Im B1) * cor(2 * Im (v1/v2)) = 0\"\n        \"A2 * (cor ((Re (v1/v2))\\<^sup>2) + cor ((Im (v1/v2))\\<^sup>2) + 1) + cor (Re B2) * cor(2 * Re (v1/v2)) + cor (Im B2) * cor(2 * Im (v1/v2)) = 0\"\n        using circline_equation_quadratic_equation[of A1 \"u1/u2\" B1 D1 \"Re (u1/u2)\" \"Im (u1 / u2)\" \"Re B1\" \"Im B1\"]\n        using circline_equation_quadratic_equation[of A2 \"u1/u2\" B2 D2 \"Re (u1/u2)\" \"Im (u1 / u2)\" \"Re B2\" \"Im B2\"]\n        using circline_equation_quadratic_equation[of A1 \"v1/v2\" B1 D1 \"Re (v1/v2)\" \"Im (v1 / v2)\" \"Re B1\" \"Im B1\"]\n        using circline_equation_quadratic_equation[of A2 \"v1/v2\" B2 D2 \"Re (v1/v2)\" \"Im (v1 / v2)\" \"Re B2\" \"Im B2\"]\n        using `on_circline_cmat_cvec ?H1 ?u` `on_circline_cmat_cvec ?H2 ?u` \n        using `on_circline_cmat_cvec ?H1 ?v` `on_circline_cmat_cvec ?H2 ?v` \n        using ** uv\n        by (simp_all add: vec_cnj_def field_simps)\n\n      hence\n        \"A1 + cor (Re B1) * cor(Re (u1/u2)) + cor (Im B1) * cor(Im (u1/u2)) = 0\"\n        \"A1 + cor (Re B1) * cor(Re (v1/v2)) + cor (Im B1) * cor(Im (v1/v2)) = 0\"\n        \"A2 + cor (Re B2) * cor(Re (u1/u2)) + cor (Im B2) * cor(Im (u1/u2)) = 0\"\n        \"A2 + cor (Re B2) * cor(Re (v1/v2)) + cor (Im B2) * cor(Im (v1/v2)) = 0\"\n        using u v\n        by simp_all algebra+\n\n      hence \n        \"cor (Re A1 + Re B1 * Re (u1/u2) + Im B1 * Im (u1/u2)) = 0\"\n        \"cor (Re A2 + Re B2 * Re (u1/u2) + Im B2 * Im (u1/u2)) = 0\"\n        \"cor (Re A1 + Re B1 * Re (v1/v2) + Im B1 * Im (v1/v2)) = 0\"\n        \"cor (Re A2 + Re B2 * Re (v1/v2) + Im B2 * Im (v1/v2)) = 0\"\n        using `is_real A1` `is_real A2`\n        by simp_all\n\n      hence \n        \"Re A1 + Re B1 * Re (u1/u2) + Im B1 * Im (u1/u2) = 0\"\n        \"Re A1 + Re B1 * Re (v1/v2) + Im B1 * Im (v1/v2) = 0\"\n        \"Re A2 + Re B2 * Re (u1/u2) + Im B2 * Im (u1/u2) = 0\"\n        \"Re A2 + Re B2 * Re (v1/v2) + Im B2 * Im (v1/v2) = 0\"\n        using of_real_eq_0_iff \n        by blast+\n\n      moreover\n\n      have \"Re(u1/u2) \\<noteq> Re(v1/v2) \\<or> Im(u1/u2) \\<noteq> Im(v1/v2)\"\n      proof (rule ccontr)\n        assume \"\\<not> ?thesis\"\n        hence \"u1/u2 = v1/v2\"\n          using complex_eqI by blast\n        thus False\n          using uv `\\<not> (u1, u2) \\<approx>\\<^sub>v (v1, v2)`\n          using \"*\"(1) \"*\"(2) complex_cvec_eq_mix[OF *(1) *(2)]\n          by (auto simp add: field_simps)\n      qed\n\n      moreover\n\n      have \"Re A1 \\<noteq> 0 \\<or> Re B1 \\<noteq> 0 \\<or> Im B1 \\<noteq> 0\"\n        using `?H1 \\<noteq> mat_zero` **\n        by (metis complex_cnj_zero complex_of_real_Re mat_zero_def of_real_0)\n\n      ultimately\n\n      obtain k where\n        k: \"Re A2 = k * Re A1\" \"Re B2 = k * Re B1\" \"Im B2 = k * Im B1\"\n        using linear_system_homogenous_3_2[of \"\\<lambda>x y z. 1 * x + Re (u1 / u2) * y + Im (u1 / u2) * z\" 1 \"Re (u1/u2)\" \"Im (u1/u2)\" \n                                              \"\\<lambda>x y z. 1 * x + Re (v1 / v2) * y + Im (v1 / v2) * z\" 1 \"Re (v1/v2)\" \"Im (v1/v2)\"\n                                              \"Re A2\" \"Re B2\" \"Im B2\" \"Re A1\" \"Re B1\" \"Im B1\"]\n        by (auto simp add: field_simps)\n\n      have \"Re A2 \\<noteq> 0 \\<or> Re B2 \\<noteq> 0 \\<or> Im B2 \\<noteq> 0\"\n        using `?H2 \\<noteq> mat_zero` **\n        by (metis complex_cnj_zero complex_of_real_Re mat_zero_def of_real_0)\n      hence \"k \\<noteq> 0\"\n        using k\n        by auto\n\n      show \"circline_eq_cmat ?H1 ?H2\"\n        using ** k `k \\<noteq> 0`\n        by (auto simp add: vec_cnj_def) (rule_tac x=\"k\" in exI, auto simp add: complex.expand)\n    qed\n  qed\nqed\n\ntext \\<open>The only h-line that goes trough zero and a non-zero point on the x-axis is the x-axis.\\<close>\nlemma is_poincare_line_0_real_is_x_axis:\n  assumes \"is_poincare_line l\" \"0\\<^sub>h \\<in> circline_set l\"\n    \"x \\<in> circline_set l \\<inter> circline_set x_axis\" \"x \\<noteq> 0\\<^sub>h\" \"x \\<noteq> \\<infinity>\\<^sub>h\"\n  shows \"l = x_axis\"\n  using assms\n  using is_poincare_line_trough_zero_trough_infty[OF assms(1-2)]\n  using unique_circline_set[of x \"0\\<^sub>h\" \"\\<infinity>\\<^sub>h\"]\n  by auto\n\ntext \\<open>The only h-line that goes trough zero and a non-zero point on the y-axis is the y-axis.\\<close>\nlemma is_poincare_line_0_imag_is_y_axis:\n  assumes \"is_poincare_line l\" \"0\\<^sub>h \\<in> circline_set l\"\n    \"y \\<in> circline_set l \\<inter> circline_set y_axis\" \"y \\<noteq> 0\\<^sub>h\" \"y \\<noteq> \\<infinity>\\<^sub>h\"\n  shows \"l = y_axis\"\n  using assms\n  using is_poincare_line_trough_zero_trough_infty[OF assms(1-2)]\n  using unique_circline_set[of y \"0\\<^sub>h\" \"\\<infinity>\\<^sub>h\"]\n  by auto\n\n(* ------------------------------------------------------------------ *)\nsubsubsection\\<open>H-isometries preserve h-lines\\<close>\n(* ------------------------------------------------------------------ *)\n\ntext\\<open>\\emph{H-isometries} are defined as homographies (actions of M\u00f6bius transformations) and\nantihomographies (compositions of actions of M\u00f6bius transformations with conjugation) that fix the\nunit disc (map it onto itself). They also map h-lines onto h-lines\\<close>\n\ntext\\<open>We prove a bit more general lemma that states that all M\u00f6bius transformations that fix the\nunit circle (not necessary the unit disc) map h-lines onto h-lines\\<close>\nlemma unit_circle_fix_preserve_is_poincare_line [simp]:\n  assumes \"unit_circle_fix M\" \"is_poincare_line H\"\n  shows \"is_poincare_line (moebius_circline M H)\"\n  using assms\n  unfolding is_poincare_line_iff\nproof (safe)\n  let ?H' = \"moebius_ocircline M (of_circline H)\"\n  let ?U' = \"moebius_ocircline M ounit_circle\"\n  assume ++: \"unit_circle_fix M\" \"perpendicular H unit_circle\"\n  have ounit: \"ounit_circle = moebius_ocircline M ounit_circle \\<or>\n               ounit_circle = moebius_ocircline M (opposite_ocircline ounit_circle)\"\n    using ++(1) unit_circle_fix_iff[of M]\n    by (simp add: inj_of_ocircline moebius_circline_ocircline)\n\n  show \"perpendicular (moebius_circline M H) unit_circle\"\n  proof (cases \"pos_oriented ?H'\")\n    case True\n    hence *: \"of_circline (of_ocircline ?H') = ?H'\"\n      using of_circline_of_ocircline_pos_oriented\n      by blast\n    from ounit show ?thesis\n    proof\n      assume **: \"ounit_circle = moebius_ocircline M ounit_circle\"\n      show ?thesis\n        using ++ \n        unfolding perpendicular_def\n        by (simp, subst moebius_circline_ocircline, subst *, subst **) simp\n    next\n      assume **: \"ounit_circle = moebius_ocircline M (opposite_ocircline ounit_circle)\"\n      show ?thesis\n        using ++\n        unfolding perpendicular_def\n        by (simp, subst moebius_circline_ocircline, subst *, subst **) simp\n    qed\n  next\n    case False\n    hence *: \"of_circline (of_ocircline ?H') = opposite_ocircline ?H'\"\n      by (metis of_circline_of_ocircline pos_oriented_of_circline)\n    from ounit show ?thesis\n    proof\n      assume **: \"ounit_circle = moebius_ocircline M ounit_circle\"\n      show ?thesis\n        using ++\n        unfolding perpendicular_def\n        by (simp, subst moebius_circline_ocircline, subst *, subst **) simp\n    next\n      assume **: \"ounit_circle = moebius_ocircline M (opposite_ocircline ounit_circle)\"\n      show ?thesis\n        using ++\n        unfolding perpendicular_def\n        by (simp, subst moebius_circline_ocircline, subst *, subst **) simp\n    qed\n  qed\nqed simp\n\nlemma unit_circle_fix_preserve_is_poincare_line_iff [simp]:\n  assumes \"unit_circle_fix M\"\n  shows \"is_poincare_line (moebius_circline M H) \\<longleftrightarrow> is_poincare_line H\"\n  using assms\n  using unit_circle_fix_preserve_is_poincare_line[of M H]\n  using unit_circle_fix_preserve_is_poincare_line[of \"moebius_inv M\" \"moebius_circline M H\"]\n  by (auto simp del: unit_circle_fix_preserve_is_poincare_line)\n\ntext\\<open>Since h-lines are preserved by transformations that fix the unit circle, so is collinearity.\\<close>\nlemma unit_disc_fix_preserve_poincare_collinear [simp]:\n  assumes \"unit_circle_fix M\" \"poincare_collinear A\"\n  shows \"poincare_collinear (moebius_pt M ` A)\"\n  using assms\n  unfolding poincare_collinear_def                                                    \n  by (auto, rule_tac x=\"moebius_circline M p\" in exI, auto)\n\nlemma unit_disc_fix_preserve_poincare_collinear_iff [simp]:\n  assumes \"unit_circle_fix M\"\n  shows \"poincare_collinear (moebius_pt M ` A) \\<longleftrightarrow> poincare_collinear A\"\n  using assms\n  using unit_disc_fix_preserve_poincare_collinear[of M A]\n  using unit_disc_fix_preserve_poincare_collinear[of \"moebius_inv M\" \"moebius_pt M ` A\"]\n  by (auto simp del: unit_disc_fix_preserve_poincare_collinear)\n\nlemma unit_disc_fix_preserve_poincare_collinear3 [simp]:\n  assumes \"unit_disc_fix M\"\n  shows \"poincare_collinear {moebius_pt M u, moebius_pt M v, moebius_pt M w} \\<longleftrightarrow>\n         poincare_collinear {u, v, w}\"\n  using assms unit_disc_fix_preserve_poincare_collinear_iff[of M \"{u, v, w}\"]\n  by simp\n\ntext\\<open>Conjugation is also an h-isometry and it preserves h-lines.\\<close>\nlemma is_poincare_line_conjugate_circline [simp]:\n  assumes \"is_poincare_line H\"\n  shows \"is_poincare_line (conjugate_circline H)\"\n  using assms\n  by (transfer, transfer, auto simp add: mat_cnj_def hermitean_def mat_adj_def)\n\nlemma is_poincare_line_conjugate_circline_iff [simp]:\n  shows \"is_poincare_line (conjugate_circline H) \\<longleftrightarrow> is_poincare_line H\"\n  using is_poincare_line_conjugate_circline[of \"conjugate_circline H\"]\n  by auto\n\ntext\\<open>Since h-lines are preserved by conjugation, so is collinearity.\\<close>\nlemma conjugate_preserve_poincare_collinear [simp]:\n  assumes \"poincare_collinear A\"\n  shows \"poincare_collinear (conjugate ` A)\"\n  using assms\n  unfolding poincare_collinear_def\n  by auto (rule_tac x=\"conjugate_circline p\" in exI, auto)\n\nlemma conjugate_conjugate [simp]: \"conjugate ` conjugate ` A = A\"\n  by (auto simp add: image_iff)\n\n\n\n(* ------------------------------------------------------------------ *)\nsubsubsection\\<open>Mapping h-lines to x-axis\\<close>\n(* ------------------------------------------------------------------ *)\n\ntext\\<open>Each h-line in the Poincar\\'e model can be mapped onto the x-axis (by a unit-disc preserving\nM\u00f6bius transformation).\\<close>\nlemma ex_unit_disc_fix_is_poincare_line_to_x_axis:\n  assumes \"is_poincare_line l\"\n  shows  \"\\<exists> M. unit_disc_fix M \\<and> moebius_circline M l = x_axis\"\nproof-\n  from assms obtain u v where \"u \\<noteq> v\" \"u \\<in> unit_disc\" \"v \\<in> unit_disc\" and \"{u, v} \\<subseteq> circline_set l\"\n    using ex_is_poincare_line_points\n    by blast\n  then obtain M where *: \"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]\n    by auto\n  moreover\n  hence \"{0\\<^sub>h, moebius_pt M v} \\<subseteq> circline_set x_axis\"\n    unfolding positive_x_axis_def\n    by auto\n  moreover\n  have \"moebius_pt M v \\<noteq> 0\\<^sub>h\"\n    using \\<open>u \\<noteq> v\\<close> *\n    by (metis moebius_pt_neq_I)\n  moreover\n  have \"moebius_pt M v \\<noteq> \\<infinity>\\<^sub>h\"\n    using \\<open>unit_disc_fix M\\<close> \\<open>v \\<in> unit_disc\\<close>\n    using unit_disc_fix_discI\n    by fastforce\n  ultimately\n  show ?thesis\n    using \\<open>is_poincare_line l\\<close> \\<open>{u, v} \\<subseteq> circline_set l\\<close> \\<open>unit_disc_fix M\\<close>\n    using is_poincare_line_0_real_is_x_axis[of \"moebius_circline M l\" \"moebius_pt M v\"]\n    by (rule_tac x=\"M\" in exI, force) \nqed\n\ntext \\<open>When proving facts about h-lines, without loss of generality it can be assumed that h-line is\nthe x-axis (if the property being proved is invariant under M\u00f6bius transformations that fix the\nunit disc).\\<close>\n\nlemma wlog_line_x_axis:\n  assumes is_line: \"is_poincare_line H\"\n  assumes x_axis: \"P x_axis\"\n  assumes preserves: \"\\<And> M. \\<lbrakk>unit_disc_fix M; P (moebius_circline M H)\\<rbrakk> \\<Longrightarrow> P H\"\n  shows \"P H\"\n  using assms\n  using ex_unit_disc_fix_is_poincare_line_to_x_axis[of H]\n  by auto\n\n(* ------------------------------------------------------------------ *)\nsubsection\\<open>Construction of the h-line between the two given points\\<close>\n(* ------------------------------------------------------------------ *)\n\ntext\\<open>Next we show how to construct the (unique) h-line between the two given points in the Poincar\\'e model\\<close>\n\ntext\\<open>\nGeometrically, h-line can be constructed by finding the inverse point of one of the two points and \nby constructing the circle (or line) trough it and the two given points.\n\nAlgebraically, for two given points $u$ and $v$ in $\\mathbb{C}$, the h-line matrix coefficients can\nbe $A = i\\cdot(u\\overline{v}-v\\overline{u})$ and $B = i\\cdot(v(|u|^2+1) - u(|v|^2+1))$.\n\nWe need to extend this to homogenous coordinates. There are several degenerate cases.\n\n - If $\\{z, w\\} = \\{0_h, \\infty_h\\}$ then there is no unique h-line (any line trough zero is an h-line).\n\n - If z and w are mutually inverse, then the construction fails (both geometric and algebraic).\n\n - If z and w are different points on the unit circle, then the standard construction fails (only geometric).\n\n - None of this problematic cases occur when z and w are inside the unit disc.\n\nWe express the construction algebraically, and construct the Hermitean circline matrix for the two\npoints given in homogenous coordinates. It works correctly in all cases except when the two points\nare the same or are mutually inverse.\n\\<close>\n\n\ndefinition mk_poincare_line_cmat :: \"real \\<Rightarrow> complex \\<Rightarrow> complex_mat\" where\n  [simp]: \"mk_poincare_line_cmat A B = (cor A, B, cnj B, cor A)\"\n\nlemma mk_poincare_line_cmat_zero_iff:\n  \"mk_poincare_line_cmat A B = mat_zero \\<longleftrightarrow> A = 0 \\<and> B = 0\"\n  by auto\n\nlemma mk_poincare_line_cmat_hermitean\n  [simp]:  \"hermitean (mk_poincare_line_cmat A B)\"\n  by simp\n\nlemma mk_poincare_line_cmat_scale:\n  \"cor k *\\<^sub>s\\<^sub>m mk_poincare_line_cmat A B = mk_poincare_line_cmat (k * A) (k * B)\"\n  by simp\n\ndefinition poincare_line_cvec_cmat :: \"complex_vec \\<Rightarrow> complex_vec \\<Rightarrow> complex_mat\" where\n  [simp]: \"poincare_line_cvec_cmat z w =\n            (let (z1, z2) = z;\n                 (w1, w2) = w;\n                 nom = w1*cnj w2*(z1*cnj z1 + z2*cnj z2) - z1*cnj z2*(w1*cnj w1 + w2*cnj w2);\n                 den = z1*cnj z2*cnj w1*w2 - w1*cnj w2*cnj z1*z2\n              in if den \\<noteq> 0 then\n                    mk_poincare_line_cmat (Re(\\<i>*den)) (\\<i>*nom)\n                 else if z1*cnj z2 \\<noteq> 0 then\n                    mk_poincare_line_cmat 0 (\\<i>*z1*cnj z2)\n                 else if w1*cnj w2 \\<noteq> 0 then\n                    mk_poincare_line_cmat 0 (\\<i>*w1*cnj w2)\n                 else\n                    mk_poincare_line_cmat 0 \\<i>)\"\n\nlemma poincare_line_cvec_cmat_AeqD:\n  assumes \"poincare_line_cvec_cmat z w = (A, B, C, D)\"\n  shows \"A = D\"\n  using assms\n  by (cases z, cases w) (auto split: if_split_asm)\n\nlemma poincare_line_cvec_cmat_hermitean [simp]: \n  shows \"hermitean (poincare_line_cvec_cmat z w)\"\n  by (cases z, cases w) (auto split: if_split_asm simp del: mk_poincare_line_cmat_def)\n\nlemma poincare_line_cvec_cmat_nonzero [simp]:\n  assumes \"z \\<noteq> vec_zero\" \"w \\<noteq> vec_zero\"\n  shows  \"poincare_line_cvec_cmat z w \\<noteq> mat_zero\"\nproof-\n\n  obtain z1 z2 w1 w2 where *: \"z = (z1, z2)\" \"w = (w1, w2)\"\n    by (cases z, cases w, auto)\n\n  let ?den = \"z1*cnj z2*cnj w1*w2 - w1*cnj w2*cnj z1*z2\"\n  show ?thesis\n  proof (cases \"?den \\<noteq> 0\")\n    case True\n    have \"is_real (\\<i> * ?den)\"\n      using eq_cnj_iff_real[of \"\\<i> *?den\"]\n      by (simp add: field_simps)\n    hence \"Re (\\<i> * ?den) \\<noteq> 0\"\n      using \\<open>?den \\<noteq> 0\\<close>\n      by (metis complex_i_not_zero complex_surj mult_eq_0_iff zero_complex.code)\n    thus ?thesis\n      using * \\<open>?den \\<noteq> 0\\<close>\n      by (simp del: mk_poincare_line_cmat_def mat_zero_def add: mk_poincare_line_cmat_zero_iff)\n  next\n    case False\n    thus ?thesis\n      using *\n      by (simp del: mk_poincare_line_cmat_def mat_zero_def add: mk_poincare_line_cmat_zero_iff)\n  qed\nqed\n\nlift_definition poincare_line_hcoords_clmat :: \"complex_homo_coords \\<Rightarrow> complex_homo_coords \\<Rightarrow> circline_mat\" is poincare_line_cvec_cmat\n  using poincare_line_cvec_cmat_hermitean poincare_line_cvec_cmat_nonzero\n  by simp\n\nlift_definition poincare_line :: \"complex_homo \\<Rightarrow> complex_homo \\<Rightarrow> circline\" is poincare_line_hcoords_clmat\nproof transfer\n  fix za zb wa wb\n  assume \"za \\<noteq> vec_zero\" \"zb \\<noteq> vec_zero\" \"wa \\<noteq> vec_zero\" \"wb \\<noteq> vec_zero\"\n  assume \"za \\<approx>\\<^sub>v zb\" \"wa \\<approx>\\<^sub>v wb\"\n  obtain za1 za2 zb1 zb2 wa1 wa2 wb1 wb2 where\n  *: \"(za1, za2) = za\" \"(zb1, zb2) = zb\"\n     \"(wa1, wa2) = wa\" \"(wb1, wb2) = wb\"\n    by (cases za, cases zb, cases wa, cases wb, auto)\n  obtain kz kw where\n    **: \"kz \\<noteq> 0\" \"kw \\<noteq> 0\" \"zb1 = kz * za1\" \"zb2 = kz * za2\" \"wb1 = kw * wa1\" \"wb2 = kw * wa2\"\n    using \\<open>za \\<approx>\\<^sub>v zb\\<close> \\<open>wa \\<approx>\\<^sub>v wb\\<close> *[symmetric]\n    by auto\n\n  let ?nom = \"\\<lambda> z1 z2 w1 w2. w1*cnj w2*(z1*cnj z1 + z2*cnj z2) - z1*cnj z2*(w1*cnj w1 + w2*cnj w2)\"\n  let ?den = \"\\<lambda> z1 z2 w1 w2. z1*cnj z2*cnj w1*w2 - w1*cnj w2*cnj z1*z2\"\n\n  show \"circline_eq_cmat (poincare_line_cvec_cmat za wa)\n                         (poincare_line_cvec_cmat zb wb)\"\n  proof-\n    have \"\\<exists>k. k \\<noteq> 0 \\<and>\n            poincare_line_cvec_cmat (zb1, zb2) (wb1, wb2) = cor k *\\<^sub>s\\<^sub>m poincare_line_cvec_cmat (za1, za2) (wa1, wa2)\"\n    proof (cases \"?den za1 za2 wa1 wa2 \\<noteq> 0\")\n      case True\n      hence \"?den zb1 zb2 wb1 wb2 \\<noteq> 0\"\n        using **\n        by (simp add: field_simps)\n\n      let ?k = \"kz * cnj kz * kw * cnj kw\"\n\n      have \"?k \\<noteq> 0\"\n        using **\n        by simp\n\n      have \"is_real ?k\"\n        using eq_cnj_iff_real[of ?k]\n        by auto\n\n      have \"cor (Re ?k) = ?k\"\n        using \\<open>is_real ?k\\<close>\n        using complex_of_real_Re\n        by blast\n\n      have \"Re ?k \\<noteq> 0\"\n        using \\<open>?k \\<noteq> 0\\<close> \\<open>cor (Re ?k) = ?k\\<close>\n        by (metis of_real_0)\n\n      have arg1: \"Re (\\<i> * ?den zb1 zb2 wb1 wb2) = Re ?k * Re (\\<i> * ?den za1 za2 wa1 wa2)\"\n        apply (subst **)+\n        apply (subst Re_mult_real[symmetric, OF \\<open>is_real ?k\\<close>])\n        apply (rule arg_cong[where f=Re])\n        apply (simp add: field_simps)\n        done\n      have arg2: \"\\<i> * ?nom zb1 zb2 wb1 wb2 = ?k * \\<i> * ?nom za1 za2 wa1 wa2\"\n        using **\n        by (simp add: field_simps)\n      have \"mk_poincare_line_cmat (Re (\\<i>*?den zb1 zb2 wb1 wb2)) (\\<i>*?nom zb1 zb2 wb1 wb2) =\n            cor (Re ?k) *\\<^sub>s\\<^sub>m mk_poincare_line_cmat (Re (\\<i>*?den za1 za2 wa1 wa2)) (\\<i>*?nom za1 za2 wa1 wa2)\"\n        using \\<open>cor (Re ?k) = ?k\\<close> \\<open>is_real ?k\\<close>\n        apply (subst mk_poincare_line_cmat_scale)\n        apply (subst arg1, subst arg2)\n        apply (subst \\<open>cor (Re ?k) = ?k\\<close>)+\n        apply simp\n        done\n       thus ?thesis\n        using \\<open>?den za1 za2 wa1 wa2 \\<noteq> 0\\<close> \\<open>?den zb1 zb2 wb1 wb2 \\<noteq> 0\\<close>\n        using \\<open>Re ?k \\<noteq> 0\\<close> \\<open>cor (Re ?k) = ?k\\<close>\n        by (rule_tac x=\"Re ?k\" in exI, simp)\n    next\n      case False\n      hence \"?den zb1 zb2 wb1 wb2 = 0\"\n        using **\n        by (simp add: field_simps)\n      show ?thesis\n      proof (cases \"za1*cnj za2 \\<noteq> 0\")\n        case True\n        hence \"zb1*cnj zb2 \\<noteq> 0\"\n          using **\n          by (simp add: field_simps)\n\n        let ?k = \"kz * cnj kz\"\n\n        have \"?k \\<noteq> 0\" \"is_real ?k\"\n          using **\n          using eq_cnj_iff_real[of ?k]\n          by auto\n        thus ?thesis\n          using \\<open>za1 * cnj za2 \\<noteq> 0\\<close> \\<open>zb1 * cnj zb2 \\<noteq> 0\\<close>\n          using \\<open>\\<not> (?den za1 za2 wa1 wa2 \\<noteq> 0)\\<close> \\<open>?den zb1 zb2 wb1 wb2 = 0\\<close> **\n          by (rule_tac x=\"Re (kz * cnj kz)\" in exI, auto simp add: complex.expand)\n      next\n        case False\n        hence \"zb1 * cnj zb2 = 0\"\n          using **\n          by (simp add: field_simps)\n        show ?thesis\n        proof (cases \"wa1 * cnj wa2 \\<noteq> 0\")\n          case True\n          hence \"wb1*cnj wb2 \\<noteq> 0\"\n            using **\n            by (simp add: field_simps)\n\n          let ?k = \"kw * cnj kw\"\n\n          have \"?k \\<noteq> 0\" \"is_real ?k\"\n            using **\n            using eq_cnj_iff_real[of ?k]\n            by auto\n\n          thus ?thesis\n            using \\<open>\\<not> (za1 * cnj za2 \\<noteq> 0)\\<close> \n            using \\<open>wa1 * cnj wa2 \\<noteq> 0\\<close> \\<open>wb1 * cnj wb2 \\<noteq> 0\\<close>\n            using \\<open>\\<not> (?den za1 za2 wa1 wa2 \\<noteq> 0)\\<close> \\<open>?den zb1 zb2 wb1 wb2 = 0\\<close> **\n            by (rule_tac x=\"Re (kw * cnj kw)\" in exI) \n               (auto simp add: complex.expand)\n        next\n          case False\n          hence \"wb1 * cnj wb2 = 0\"\n            using **\n            by (simp add: field_simps)\n          thus ?thesis\n            using \\<open>\\<not> (za1 * cnj za2 \\<noteq> 0)\\<close> \\<open>zb1 * cnj zb2 = 0\\<close>\n            using \\<open>\\<not> (wa1 * cnj wa2 \\<noteq> 0)\\<close> \\<open>wb1 * cnj wb2 = 0\\<close>\n            using \\<open>\\<not> (?den za1 za2 wa1 wa2 \\<noteq> 0)\\<close> \\<open>?den zb1 zb2 wb1 wb2 = 0\\<close> **\n            by simp\n        qed\n      qed\n    qed\n    thus ?thesis\n      using *[symmetric]\n      by simp\n  qed\nqed\n\nsubsubsection \\<open>Correctness of the construction\\<close>\n\ntext\\<open>For finite points, our definition matches the classic algebraic definition for points in\n$\\mathbb{C}$ (given in ordinary, not homogenous coordinates).\\<close>\nlemma poincare_line_non_homogenous:\n  assumes \"u \\<noteq> \\<infinity>\\<^sub>h\" \"v \\<noteq> \\<infinity>\\<^sub>h\" \"u \\<noteq> v\" \"u \\<noteq> inversion v\"\n  shows \"let u' = to_complex u;  v' = to_complex v;\n             A = \\<i> * (u' * cnj v' - v' * cnj u');\n             B = \\<i> * (v' * ((cmod u')\\<^sup>2 + 1) - u' * ((cmod v')\\<^sup>2 + 1))\n          in poincare_line u v = mk_circline A B (cnj B) A\"\n  using assms\n  unfolding unit_disc_def disc_def inversion_def\n  apply (simp add: Let_def)\nproof (transfer, transfer, safe)\n  fix u1 u2 v1 v2\n  assume uv: \"(u1, u2) \\<noteq> vec_zero\" \"(v1, v2) \\<noteq> vec_zero\" \n             \"\\<not> (u1, u2) \\<approx>\\<^sub>v \\<infinity>\\<^sub>v\" \"\\<not> (v1, v2) \\<approx>\\<^sub>v \\<infinity>\\<^sub>v\"            \n             \"\\<not> (u1, u2) \\<approx>\\<^sub>v (v1, v2)\" \"\\<not> (u1, u2) \\<approx>\\<^sub>v conjugate_cvec (reciprocal_cvec (v1, v2))\"\n  let ?u = \"to_complex_cvec (u1, u2)\" and ?v = \"to_complex_cvec (v1, v2)\"\n  let ?A = \"\\<i> * (?u * cnj ?v - ?v * cnj ?u)\"\n  let ?B = \"\\<i> * (?v * ((cor (cmod ?u))\\<^sup>2 + 1) - ?u * ((cor (cmod ?v))\\<^sup>2 + 1))\"\n  let ?C = \"- (\\<i> * (cnj ?v * ((cor (cmod ?u))\\<^sup>2 + 1) - cnj ?u * ((cor (cmod ?v))\\<^sup>2 + 1)))\"\n  let ?D = ?A\n  let ?H = \"(?A, ?B, ?C, ?D)\"\n\n\n  let ?den = \"u1 * cnj u2 * cnj v1 * v2 - v1 * cnj v2 * cnj u1 * u2\"\n\n  have \"u2 \\<noteq> 0\" \"v2 \\<noteq> 0\"\n    using uv                                                    \n    using inf_cvec_z2_zero_iff \n    by blast+\n\n  have \"\\<not> (u1, u2) \\<approx>\\<^sub>v (cnj v2, cnj v1)\"\n    using uv(6)\n    by (simp add: vec_cnj_def)\n  moreover\n  have \"(cnj v2, cnj v1) \\<noteq> vec_zero\"\n    using uv(2)\n    by auto\n  ultimately\n  have *: \"u1 * cnj v1 \\<noteq> u2 * cnj v2\" \"u1 * v2 \\<noteq> u2 * v1\" \n    using uv(5) uv(1) uv(2) `u2 \\<noteq> 0` `v2 \\<noteq> 0`\n    using complex_cvec_eq_mix \n    by blast+\n\n  show \"circline_eq_cmat (poincare_line_cvec_cmat (u1, u2) (v1, v2))\n                         (mk_circline_cmat ?A ?B ?C ?D)\"\n  proof (cases \"?den \\<noteq> 0\")\n    case True\n\n    let ?nom = \"v1 * cnj v2 * (u1 * cnj u1 + u2 * cnj u2) - u1 * cnj u2 * (v1 * cnj v1 + v2 * cnj v2)\"\n    let ?H' = \"mk_poincare_line_cmat (Re (\\<i> * ?den)) (\\<i> * ?nom)\"\n\n    have \"circline_eq_cmat ?H ?H'\"\n    proof-\n      let ?k = \"(u2 * cnj v2) * (v2 * cnj u2)\"\n      have \"is_real ?k\"\n        using eq_cnj_iff_real \n        by fastforce\n      hence \"cor (Re ?k) = ?k\"\n        using complex_of_real_Re \n        by blast\n\n      have \"Re (\\<i> * ?den) = Re ?k * ?A\"\n      proof-\n        have \"?A = cnj ?A\"\n          by (simp add: field_simps)\n        hence \"is_real ?A\"\n          using eq_cnj_iff_real \n          by fastforce\n        moreover\n        have \"\\<i> * ?den =  cnj (\\<i> * ?den)\"\n          by (simp add: field_simps)\n        hence \"is_real (\\<i> * ?den)\"\n          using eq_cnj_iff_real \n          by fastforce\n        hence \"cor (Re (\\<i> * ?den)) = \\<i> * ?den\"\n          using complex_of_real_Re\n          by blast\n        ultimately\n        show ?thesis\n          using `cor (Re ?k) = ?k`\n          by (simp add: field_simps)\n      qed\n      \n      moreover\n      have \"\\<i> * ?nom = Re ?k  * ?B\"\n        using `cor (Re ?k) = ?k` `u2 \\<noteq>  0` `v2 \\<noteq> 0` complex_mult_cnj_cmod[symmetric]\n        by (auto simp add: field_simps)\n      \n      moreover\n      have \"?k \\<noteq> 0\"\n        using `u2 \\<noteq> 0` `v2 \\<noteq> 0`\n        by simp\n      hence \"Re ?k \\<noteq> 0\"\n        using `is_real ?k`\n        by (metis \\<open>cor (Re ?k) = ?k\\<close> of_real_0)\n\n      ultimately\n      show ?thesis\n        by simp (rule_tac x=\"Re ?k\" in exI, simp add: mult.commute)\n    qed\n\n    moreover\n\n    have \"poincare_line_cvec_cmat (u1, u2) (v1, v2) = ?H'\"\n      using `?den \\<noteq> 0`\n      unfolding poincare_line_cvec_cmat_def\n      by (simp add: Let_def)\n\n    moreover\n\n    hence \"hermitean ?H' \\<and> ?H' \\<noteq> mat_zero\"\n      by (metis mk_poincare_line_cmat_hermitean poincare_line_cvec_cmat_nonzero uv(1) uv(2))\n\n    hence \"hermitean ?H \\<and> ?H \\<noteq> mat_zero\"\n      using `circline_eq_cmat ?H ?H'`\n      using circline_eq_cmat_hermitean_nonzero[of ?H' ?H] symp_circline_eq_cmat\n      unfolding symp_def\n      by metis\n\n    hence \"mk_circline_cmat ?A ?B ?C ?D = ?H\"\n      by simp\n\n    ultimately\n\n    have \"circline_eq_cmat (mk_circline_cmat ?A ?B ?C ?D)\n                           (poincare_line_cvec_cmat (u1, u2) (v1, v2))\"\n      by simp\n    thus ?thesis\n      using symp_circline_eq_cmat\n      unfolding symp_def\n      by blast\n  next\n    case False\n\n    let ?d = \"v1 * (u1 * cnj u1 / (u2 * cnj u2) + 1) / v2 - u1 * (v1 * cnj v1 / (v2 * cnj v2) + 1) / u2\"\n    let ?cd = \"cnj v1 * (u1 * cnj u1 / (u2 * cnj u2) + 1) / cnj v2 - cnj u1 * (v1 * cnj v1 / (v2 * cnj v2) + 1) / cnj u2\"\n\n    have \"cnj ?d = ?cd\"\n      by (simp add: mult.commute)\n\n    let ?d1 = \"(v1 / v2) * (cnj u1 / cnj u2) - 1\"\n    let ?d2 = \"u1 / u2 - v1 / v2\"\n\n    have **: \"?d = ?d1 * ?d2\"\n      using `\\<not> ?den \\<noteq> 0` `u2 \\<noteq> 0` `v2 \\<noteq> 0` \n      by(simp add: field_simps)\n\n    hence \"?d \\<noteq> 0\"\n      using `\\<not> ?den \\<noteq> 0` `u2 \\<noteq> 0` `v2 \\<noteq> 0` *\n      by auto (simp add: field_simps)+\n\n    have \"is_real ?d1\"\n    proof-\n      have \"cnj ?d1 = ?d1\"\n        using `\\<not> ?den \\<noteq> 0` `u2 \\<noteq> 0` `v2 \\<noteq> 0` *\n        by (simp add: field_simps)\n      thus ?thesis\n        using eq_cnj_iff_real\n        by blast\n    qed\n\n    show ?thesis\n    proof (cases \"u1 * cnj u2 \\<noteq> 0\")\n      case True\n      let ?nom = \"u1 * cnj u2\"\n      let ?H' = \"mk_poincare_line_cmat 0 (\\<i> * ?nom)\"\n\n      have \"circline_eq_cmat ?H ?H'\"\n      proof-\n\n        let ?k = \"(u1 * cnj u2) / ?d\"\n\n        have \"is_real ?k\"\n        proof-\n          have \"is_real ((u1 * cnj u2) / ?d2)\"\n          proof-\n            let ?rhs = \"(u2 * cnj u2) / (1 - (v1*u2)/(u1*v2))\"\n\n            have 1: \"(u1 * cnj u2) / ?d2 = ?rhs\"\n              using `\\<not> ?den \\<noteq> 0` `u2 \\<noteq> 0` `v2 \\<noteq> 0` * `u1 * cnj u2 \\<noteq> 0`\n              by (simp add: field_simps)\n            moreover\n            have \"cnj ?rhs = ?rhs\"\n            proof-\n              have \"cnj (1 - v1 * u2 / (u1 * v2)) = 1 - v1 * u2 / (u1 * v2)\"\n                using `\\<not> ?den \\<noteq> 0` `u2 \\<noteq> 0` `v2 \\<noteq> 0` * `u1 * cnj u2 \\<noteq> 0`\n                by (simp add: field_simps)\n              moreover\n              have \"cnj (u2 * cnj u2) = u2 * cnj u2\"\n                by simp\n              ultimately\n              show ?thesis\n                by simp\n            qed\n\n            ultimately \n\n            show ?thesis\n              using eq_cnj_iff_real\n              by fastforce\n          qed\n\n          thus ?thesis\n            using ** `is_real ?d1`\n            by (metis complex_cnj_divide divide_divide_eq_left' eq_cnj_iff_real)\n        qed\n\n        have \"?k \\<noteq> 0\"\n          using `?d \\<noteq> 0` `u1 * cnj u2 \\<noteq> 0`\n          by simp\n\n        have \"cnj ?k = ?k\"\n          using `is_real ?k`\n          using eq_cnj_iff_real by blast\n\n        have \"Re ?k \\<noteq> 0\"\n          using `?k \\<noteq> 0` `is_real ?k` \n          by (metis complex.expand zero_complex.simps(1) zero_complex.simps(2))\n\n        have \"u1 * cnj u2 = ?k * ?d\"\n          using `?d \\<noteq> 0`\n          by simp\n\n        moreover\n\n        hence \"cnj u1 * u2 = cnj ?k * cnj ?d\"\n          by (metis complex_cnj_cnj complex_cnj_mult)\n        hence \"cnj u1 * u2 = ?k * ?cd\"\n          using `cnj ?k = ?k` `cnj ?d = ?cd`\n          by metis\n\n        ultimately\n\n        show ?thesis\n          using `~ ?den \\<noteq> 0` `u1 * cnj u2 \\<noteq> 0` `u2 \\<noteq> 0` `v2 \\<noteq> 0` `Re ?k \\<noteq> 0` `is_real ?k` `?d \\<noteq> 0`\n          using complex_mult_cnj_cmod[symmetric, of u1]\n          using complex_mult_cnj_cmod[symmetric, of v1]\n          using complex_mult_cnj_cmod[symmetric, of u2]\n          using complex_mult_cnj_cmod[symmetric, of v2]\n          apply (auto simp add: power_divide)\n          apply (rule_tac x=\"Re ?k\" in exI)\n          apply simp\n          apply (simp add: field_simps)\n          done\n      qed\n\n      moreover\n\n      have \"poincare_line_cvec_cmat (u1, u2) (v1, v2) = ?H'\"\n        using `\\<not> ?den \\<noteq> 0` `u1 * cnj u2 \\<noteq> 0`\n        unfolding poincare_line_cvec_cmat_def\n        by (simp add: Let_def)\n\n      moreover\n\n      hence \"hermitean ?H' \\<and> ?H' \\<noteq> mat_zero\"\n        by (metis mk_poincare_line_cmat_hermitean poincare_line_cvec_cmat_nonzero uv(1) uv(2))\n\n      hence \"hermitean ?H \\<and> ?H \\<noteq> mat_zero\"\n        using `circline_eq_cmat ?H ?H'`\n        using circline_eq_cmat_hermitean_nonzero[of ?H' ?H] symp_circline_eq_cmat\n        unfolding symp_def\n        by metis\n\n      hence \"mk_circline_cmat ?A ?B ?C ?D = ?H\"\n        by simp\n\n      ultimately\n\n      have \"circline_eq_cmat (mk_circline_cmat ?A ?B ?C ?D)\n                             (poincare_line_cvec_cmat (u1, u2) (v1, v2))\"\n        by simp\n      thus ?thesis\n        using symp_circline_eq_cmat\n        unfolding symp_def\n        by blast\n    next\n      case  False\n      show ?thesis\n      proof (cases \"v1 * cnj v2 \\<noteq> 0\")\n        case True\n        let ?nom = \"v1 * cnj v2\"\n        let ?H' = \"mk_poincare_line_cmat 0 (\\<i> * ?nom)\"\n\n        have \"circline_eq_cmat ?H ?H'\"\n        proof-\n          let ?k = \"(v1 * cnj v2) / ?d\"\n\n          have \"is_real ?k\"\n          proof-\n          have \"is_real ((v1 * cnj v2) / ?d2)\"\n          proof-\n            let ?rhs = \"(v2 * cnj v2) / ((u1*v2)/(u2*v1) - 1)\"\n\n            have 1: \"(v1 * cnj v2) / ?d2 = ?rhs\"\n              using `\\<not> ?den \\<noteq> 0` `u2 \\<noteq> 0` `v2 \\<noteq> 0` * `v1 * cnj v2 \\<noteq> 0`\n              by (simp add: field_simps)\n            moreover\n            have \"cnj ?rhs = ?rhs\"\n            proof-\n              have \"cnj (u1 * v2 / (u2 * v1) - 1) = u1 * v2 / (u2 * v1) - 1\"\n                using `\\<not> ?den \\<noteq> 0` `u2 \\<noteq> 0` `v2 \\<noteq> 0` * `v1 * cnj v2 \\<noteq> 0`\n                by (simp add: field_simps)\n              moreover                            \n              have \"cnj (v2 * cnj v2) = v2 * cnj v2\"\n                by simp\n              ultimately\n              show ?thesis\n                by simp\n            qed\n\n            ultimately \n\n            show ?thesis\n              using eq_cnj_iff_real\n              by fastforce\n          qed\n\n          thus ?thesis\n            using ** `is_real ?d1`\n            by (metis complex_cnj_divide divide_divide_eq_left' eq_cnj_iff_real)\n        qed\n\n        have \"?k \\<noteq> 0\"\n          using `?d \\<noteq> 0` `v1 * cnj v2 \\<noteq> 0`\n          by simp\n\n        have \"cnj ?k = ?k\"\n          using `is_real ?k`\n          using eq_cnj_iff_real by blast\n\n        have \"Re ?k \\<noteq> 0\"\n          using `?k \\<noteq> 0` `is_real ?k` \n          by (metis complex.expand zero_complex.simps(1) zero_complex.simps(2))\n\n        have \"v1 * cnj v2 = ?k * ?d\"\n          using `?d \\<noteq> 0`\n          by simp\n\n        moreover\n\n        hence \"cnj v1 * v2 = cnj ?k * cnj ?d\"\n          by (metis complex_cnj_cnj complex_cnj_mult)\n        hence \"cnj v1 * v2 = ?k * ?cd\"\n          using `cnj ?k = ?k` `cnj ?d = ?cd`\n          by metis\n\n        ultimately\n\n        show ?thesis\n          using `~ ?den \\<noteq> 0` `v1 * cnj v2 \\<noteq> 0` `u2 \\<noteq> 0` `v2 \\<noteq> 0` `Re ?k \\<noteq> 0` `is_real ?k` `?d \\<noteq> 0`\n          using complex_mult_cnj_cmod[symmetric, of u1]\n          using complex_mult_cnj_cmod[symmetric, of v1]\n          using complex_mult_cnj_cmod[symmetric, of u2]\n          using complex_mult_cnj_cmod[symmetric, of v2]\n          apply (auto simp add: power_divide)\n          apply (rule_tac x=\"Re ?k\" in exI)\n          apply simp\n          apply (simp add: field_simps)\n          done\n        qed\n\n        moreover\n\n        have \"poincare_line_cvec_cmat (u1, u2) (v1, v2) = ?H'\"\n          using `\\<not> ?den \\<noteq> 0` `\\<not> u1 * cnj u2 \\<noteq> 0` `v1 * cnj v2 \\<noteq> 0`\n          unfolding poincare_line_cvec_cmat_def\n          by (simp add: Let_def)\n\n        moreover\n\n        hence \"hermitean ?H' \\<and> ?H' \\<noteq> mat_zero\"\n          by (metis mk_poincare_line_cmat_hermitean poincare_line_cvec_cmat_nonzero uv(1) uv(2))\n\n        hence \"hermitean ?H \\<and> ?H \\<noteq> mat_zero\"\n          using `circline_eq_cmat ?H ?H'`\n          using circline_eq_cmat_hermitean_nonzero[of ?H' ?H] symp_circline_eq_cmat\n          unfolding symp_def\n          by metis\n\n        hence \"mk_circline_cmat ?A ?B ?C ?D = ?H\"\n          by simp\n\n        ultimately\n\n        have \"circline_eq_cmat (mk_circline_cmat ?A ?B ?C ?D)\n                               (poincare_line_cvec_cmat (u1, u2) (v1, v2))\"\n          by simp\n        thus ?thesis\n          using symp_circline_eq_cmat\n          unfolding symp_def\n          by blast\n      next\n        case False\n        hence False\n          using `\\<not> ?den \\<noteq> 0` `\\<not> u1 * cnj u2 \\<noteq> 0` uv\n          by (simp add: \\<open>u2 \\<noteq> 0\\<close> \\<open>v2 \\<noteq> 0\\<close>)\n        thus ?thesis\n          by simp\n      qed\n    qed\n  qed                    \nqed\n\ntext\\<open>Our construction (in homogenous coordinates) always yields an h-line that contain two starting\npoints (this also holds for all degenerate cases except when points are the same).\\<close>\nlemma poincare_line [simp]:\n  assumes \"z \\<noteq> w\"\n  shows \"on_circline (poincare_line z w) z\"\n        \"on_circline (poincare_line z w) w\"\nproof-\n  have \"on_circline (poincare_line z w) z \\<and> on_circline (poincare_line z w) w\"\n    using assms\n  proof (transfer, transfer)\n    fix z w\n    assume vz: \"z \\<noteq> vec_zero\" \"w \\<noteq> vec_zero\"\n    obtain z1 z2 w1 w2 where\n    zw: \"(z1, z2) = z\" \"(w1, w2) = w\"\n      by (cases z, cases w, auto)\n\n    let ?den = \"z1*cnj z2*cnj w1*w2 - w1*cnj w2*cnj z1*z2\"\n    have *: \"cor (Re (\\<i> * ?den)) = \\<i> * ?den\"\n    proof-\n      have \"cnj ?den = -?den\"\n        by auto\n      hence \"is_imag ?den\"\n        using eq_minus_cnj_iff_imag[of ?den]\n        by simp\n      thus ?thesis\n        using complex_of_real_Re[of \"\\<i> * ?den\"]\n        by simp\n    qed\n    show \"on_circline_cmat_cvec (poincare_line_cvec_cmat z w) z \\<and>\n          on_circline_cmat_cvec (poincare_line_cvec_cmat z w) w\"\n      unfolding poincare_line_cvec_cmat_def mk_poincare_line_cmat_def\n      apply (subst zw[symmetric])+\n      unfolding Let_def prod.case\n      apply (subst *)+\n      by (auto simp add: vec_cnj_def field_simps)\n  qed\n  thus \"on_circline (poincare_line z w) z\" \"on_circline (poincare_line z w) w\"\n    by auto\nqed\n\nlemma poincare_line_circline_set [simp]:\n  assumes \"z \\<noteq> w\"\n  shows \"z \\<in> circline_set (poincare_line z w)\"\n        \"w \\<in> circline_set (poincare_line z w)\"\n  using assms\n  by (auto simp add: circline_set_def)\n\ntext\\<open>When the points are different, the constructed line matrix always has a negative determinant\\<close>\nlemma poincare_line_type:\n  assumes \"z \\<noteq> w\"\n  shows \"circline_type (poincare_line z w) = -1\"\nproof-\n  have \"\\<exists> a b. a \\<noteq> b \\<and> {a, b} \\<subseteq> circline_set (poincare_line z w)\"\n    using poincare_line[of z w] assms\n    unfolding circline_set_def\n    by (rule_tac x=z in exI, rule_tac x=w in exI, simp)\n  thus ?thesis\n    using circline_type[of \"poincare_line z w\"]\n    using circline_type_pos_card_eq0[of \"poincare_line z w\"]\n    using circline_type_zero_card_eq1[of \"poincare_line z w\"]\n    by auto\nqed\n\ntext\\<open>The constructed line is an h-line in the Poincar\\'e model (in all cases when the two points are\ndifferent)\\<close>\nlemma is_poincare_line_poincare_line [simp]:\n  assumes \"z \\<noteq> w\"\n  shows \"is_poincare_line (poincare_line z w)\"\n  using poincare_line_type[of z w, OF assms]\nproof (transfer, transfer)\n  fix z w\n  assume vz: \"z \\<noteq> vec_zero\" \"w \\<noteq> vec_zero\"\n  obtain A B C D where *: \"poincare_line_cvec_cmat z w = (A, B, C, D)\"\n    by (cases \"poincare_line_cvec_cmat z w\") auto\n  assume \"circline_type_cmat (poincare_line_cvec_cmat z w) = - 1\"\n  thus \"is_poincare_line_cmat (poincare_line_cvec_cmat z w)\"\n    using vz *\n    using poincare_line_cvec_cmat_hermitean[of z w]\n    using poincare_line_cvec_cmat_nonzero[of z w]\n    using poincare_line_cvec_cmat_AeqD[of z w A B C D]\n    using hermitean_elems[of A B C D]\n    using cmod_power2[of D] cmod_power2[of C]\n    unfolding is_poincare_line_cmat_def\n    by (simp del: poincare_line_cvec_cmat_def add: sgn_1_neg power2_eq_square)\nqed\n\ntext \\<open>When the points are different, the constructed h-line between two points also contains their inverses\\<close>\nlemma poincare_line_inversion:\n  assumes \"z \\<noteq> w\"\n  shows \"on_circline (poincare_line z w) (inversion z)\"\n        \"on_circline (poincare_line z w) (inversion w)\"\n  using assms\n  using is_poincare_line_poincare_line[OF \\<open>z \\<noteq> w\\<close>]\n  using is_poincare_line_inverse_point\n  unfolding circline_set_def\n  by auto\n\ntext \\<open>When the points are different, the onstructed h-line between two points contains the inverse of its every point\\<close>\nlemma poincare_line_inversion_full:\n  assumes \"u \\<noteq> v\"\n  assumes \"on_circline (poincare_line u v) x\"\n  shows \"on_circline (poincare_line u v) (inversion x)\"\n  using is_poincare_line_inverse_point[of \"poincare_line u v\" x]\n  using is_poincare_line_poincare_line[OF `u \\<noteq> v`] assms\n  unfolding circline_set_def\n  by simp\n\nsubsubsection \\<open>Existence of h-lines\\<close>\n\ntext\\<open>There is an h-line trough every point in the Poincar\\'e model\\<close>\nlemma ex_poincare_line_one_point:\n  shows \"\\<exists> l. is_poincare_line l \\<and> z \\<in> circline_set l\"\nproof (cases \"z = 0\\<^sub>h\")\n  case True\n  thus ?thesis\n    by (rule_tac x=\"x_axis\" in exI) simp\nnext\n  case False\n  thus ?thesis\n    by (rule_tac x=\"poincare_line 0\\<^sub>h z\" in exI) auto\nqed\n\nlemma poincare_collinear_singleton [simp]:\n  assumes \"u \\<in> unit_disc\"\n  shows \"poincare_collinear {u}\"\n  using assms\n  using ex_poincare_line_one_point[of u]\n  by (auto simp add: poincare_collinear_def)\n\ntext\\<open>There is an h-line trough every two points in the Poincar\\'e model\\<close>\nlemma ex_poincare_line_two_points:\n  assumes \"z \\<noteq> w\"\n  shows \"\\<exists> l. is_poincare_line l \\<and> z \\<in> circline_set l \\<and> w \\<in> circline_set l\"\n  using assms\n  by (rule_tac x=\"poincare_line z w\" in exI, simp)\n\nlemma poincare_collinear_doubleton [simp]:\n  assumes \"u \\<in> unit_disc\" \"v \\<in> unit_disc\"\n  shows \"poincare_collinear {u, v}\"\n  using assms\n  using ex_poincare_line_one_point[of u]\n  using ex_poincare_line_two_points[of u v]\n  by (cases \"u = v\") (simp_all add: poincare_collinear_def)\n\n\nsubsubsection \\<open>Uniqueness of h-lines\\<close>\n\ntext \\<open>The only h-line between two points is the one obtained by the line-construction.\\<close> \ntext \\<open>First we show this only for two different points inside the disc.\\<close>\nlemma unique_poincare_line:\n  assumes in_disc: \"u \\<noteq> v\" \"u \\<in> unit_disc\" \"v \\<in> unit_disc\"\n  assumes on_l: \"u \\<in> circline_set l\" \"v \\<in> circline_set l\" \"is_poincare_line l\"\n  shows \"l = poincare_line u v\"\n  using assms\n  using unique_is_poincare_line[of u v l \"poincare_line u v\"]\n  unfolding circline_set_def\n  by auto\n\ntext\\<open>The assumption that the points are inside the disc can be relaxed.\\<close>\nlemma unique_poincare_line_general:\n  assumes in_disc: \"u \\<noteq> v\" \"u \\<noteq> inversion v\"\n  assumes on_l: \"u \\<in> circline_set l\" \"v \\<in> circline_set l\" \"is_poincare_line l\"\n  shows \"l = poincare_line u v\"\n  using assms\n  using unique_is_poincare_line_general[of u v l \"poincare_line u v\"]\n  unfolding circline_set_def\n  by auto\n\ntext\\<open>The explicit line construction enables us to prove that there exists a unique h-line through any\ngiven two h-points (uniqueness part was already shown earlier).\\<close>\ntext \\<open>First we show this only for two different points inside the disc.\\<close>\nlemma ex1_poincare_line:\n  assumes \"u \\<noteq> v\" \"u \\<in> unit_disc\" \"v \\<in> unit_disc\"\n  shows \"\\<exists>! l. is_poincare_line l \\<and> u \\<in> circline_set l \\<and> v \\<in> circline_set l\"\nproof (rule ex1I)\n  let ?l = \"poincare_line u v\"\n  show \"is_poincare_line ?l \\<and> u \\<in> circline_set ?l \\<and> v \\<in> circline_set ?l\"\n    using assms\n    unfolding circline_set_def\n    by auto\nnext\n  fix l\n  assume \"is_poincare_line l \\<and> u \\<in> circline_set l \\<and> v \\<in> circline_set l\"\n  thus \"l = poincare_line u v\"\n    using unique_poincare_line assms\n    by auto\nqed\n\ntext \\<open>The assumption that the points are in the disc can be relaxed.\\<close>\nlemma ex1_poincare_line_general:\n  assumes \"u \\<noteq> v\" \"u \\<noteq> inversion v\"\n  shows \"\\<exists>! l. is_poincare_line l \\<and> u \\<in> circline_set l \\<and> v \\<in> circline_set l\"\nproof (rule ex1I)\n  let ?l = \"poincare_line u v\"\n  show \"is_poincare_line ?l \\<and> u \\<in> circline_set ?l \\<and> v \\<in> circline_set ?l\"\n    using assms\n    unfolding circline_set_def\n    by auto\nnext\n  fix l\n  assume \"is_poincare_line l \\<and> u \\<in> circline_set l \\<and> v \\<in> circline_set l\"\n  thus \"l = poincare_line u v\"\n    using unique_poincare_line_general assms\n    by auto\nqed\n\nsubsubsection \\<open>Some consequences of line uniqueness\\<close>\n\ntext\\<open>H-line $uv$ is the same as the h-line $vu$.\\<close>\nlemma poincare_line_sym:\n  assumes \"u \\<in> unit_disc\" \"v \\<in> unit_disc\" \"u \\<noteq> v\"\n  shows \"poincare_line u v = poincare_line v u\"\n  using assms\n  using unique_poincare_line[of u v \"poincare_line v u\"]\n  by simp\n\nlemma poincare_line_sym_general:\n  assumes \"u \\<noteq> v\" \"u \\<noteq> inversion v\"\n  shows \"poincare_line u v = poincare_line v u\"\n  using assms\n  using unique_poincare_line_general[of u v \"poincare_line v u\"]\n  by simp\n\ntext\\<open>Each h-line is the h-line constructed out of its two arbitrary different points.\\<close>\nlemma ex_poincare_line_points:\n  assumes \"is_poincare_line H\"\n  shows \"\\<exists> u v. u \\<in> unit_disc \\<and> v \\<in> unit_disc \\<and> u \\<noteq> v \\<and> H = poincare_line u v\"\n  using assms\n  using ex_is_poincare_line_points\n  using unique_poincare_line[where l=H]\n  by fastforce\n\ntext\\<open>If an h-line contains two different points on x-axis/y-axis then it is the x-axis/y-axis.\\<close>\nlemma poincare_line_0_real_is_x_axis:\n  assumes \"x \\<in> circline_set x_axis\" \"x \\<noteq> 0\\<^sub>h\" \"x \\<noteq> \\<infinity>\\<^sub>h\"\n  shows \"poincare_line 0\\<^sub>h x = x_axis\"\n  using assms\n  using is_poincare_line_0_real_is_x_axis[of \"poincare_line 0\\<^sub>h x\" x]\n  by auto\n\nlemma poincare_line_0_imag_is_y_axis:\n  assumes \"y \\<in> circline_set y_axis\" \"y \\<noteq> 0\\<^sub>h\" \"y \\<noteq> \\<infinity>\\<^sub>h\"\n  shows \"poincare_line 0\\<^sub>h y = y_axis\"\n  using assms\n  using is_poincare_line_0_imag_is_y_axis[of \"poincare_line 0\\<^sub>h y\" y]\n  by auto\n\nlemma poincare_line_x_axis:\n  assumes \"x \\<in> unit_disc\" \"y \\<in> unit_disc\" \"x \\<in> circline_set x_axis\" \"y \\<in> circline_set x_axis\" \"x \\<noteq> y\"\n  shows \"poincare_line x y = x_axis\"\n  using assms\n  using unique_poincare_line\n  by auto\n\nlemma poincare_line_minus_one_one [simp]: \n  shows \"poincare_line (of_complex (-1)) (of_complex 1) = x_axis\"\nproof-\n  have \"0\\<^sub>h \\<in> circline_set (poincare_line (of_complex (-1)) (of_complex 1))\"\n    unfolding circline_set_def\n    by simp (transfer, transfer,  simp add: vec_cnj_def)\n  hence \"poincare_line 0\\<^sub>h (of_complex 1) = poincare_line (of_complex (-1)) (of_complex 1)\"\n    by (metis is_poincare_line_poincare_line is_poincare_line_trough_zero_trough_infty not_zero_on_unit_circle of_complex_inj of_complex_one one_neq_neg_one one_on_unit_circle poincare_line_0_real_is_x_axis poincare_line_circline_set(2) reciprocal_involution reciprocal_one reciprocal_zero unique_circline_01inf')\n  thus ?thesis\n    using poincare_line_0_real_is_x_axis[of \"of_complex 1\"]\n    by auto\nqed\n\nsubsubsection \\<open>Transformations of constructed lines\\<close>\n\ntext\\<open>Unit dics preserving M\u00f6bius transformations preserve the h-line construction\\<close>\nlemma unit_disc_fix_preserve_poincare_line [simp]:\n  assumes \"unit_disc_fix M\" \"u \\<in> unit_disc\" \"v \\<in> unit_disc\" \"u \\<noteq> v\"\n  shows \"poincare_line (moebius_pt M u) (moebius_pt M v) = moebius_circline M (poincare_line u v)\"\nproof (rule unique_poincare_line[symmetric])\n  show \"moebius_pt M u \\<noteq> moebius_pt M v\"\n    using \\<open>u \\<noteq> v\\<close> \n    by auto\nnext\n  show \"moebius_pt M u \\<in> circline_set (moebius_circline M (poincare_line u v))\"\n       \"moebius_pt M v \\<in> circline_set (moebius_circline M (poincare_line u v))\"\n    unfolding circline_set_def\n    using moebius_circline[of M \"poincare_line u v\"] \\<open>u \\<noteq> v\\<close>\n    by auto\nnext\n  from assms(1) have \"unit_circle_fix M\"\n    by simp\n  thus \"is_poincare_line (moebius_circline M (poincare_line u v))\"\n    using unit_circle_fix_preserve_is_poincare_line assms\n    by auto\nnext\n  show \"moebius_pt M u \\<in> unit_disc\" \"moebius_pt M v \\<in> unit_disc\"\n    using assms(2-3) unit_disc_fix_iff[OF assms(1)]\n    by auto\nqed\n\ntext\\<open>Conjugate preserve the h-line construction\\<close>\nlemma conjugate_preserve_poincare_line [simp]:\n  assumes \"u \\<in> unit_disc\" \"v \\<in> unit_disc\" \"u \\<noteq> v\"\n  shows \"poincare_line (conjugate u) (conjugate v) = conjugate_circline (poincare_line u v)\"\nproof-\n  have \"conjugate u \\<noteq> conjugate v\"\n    using \\<open>u \\<noteq> v\\<close>\n    by (auto simp add: conjugate_inj)\n  moreover\n  have \"conjugate u \\<in> unit_disc\" \"conjugate v \\<in> unit_disc\"\n    using assms\n    by auto\n  moreover\n  have \"conjugate u \\<in> circline_set (conjugate_circline (poincare_line u v))\"\n       \"conjugate v \\<in> circline_set (conjugate_circline (poincare_line u v))\"\n    using \\<open>u \\<noteq> v\\<close>\n    by simp_all\n  moreover\n  have \"is_poincare_line (conjugate_circline (poincare_line u v))\"\n    using is_poincare_line_poincare_line[OF \\<open>u \\<noteq> v\\<close>]\n    by simp\n  ultimately\n  show ?thesis\n    using unique_poincare_line[of \"conjugate u\" \"conjugate v\" \"conjugate_circline (poincare_line u v)\"]\n    by simp\nqed\n\nsubsubsection \\<open>Collinear points and h-lines\\<close>\n\nlemma poincare_collinear3_poincare_line_general:\n  assumes \"poincare_collinear {a, a1, a2}\" \"a1 \\<noteq> a2\" \"a1 \\<noteq> inversion a2\"\n  shows \"a \\<in> circline_set (poincare_line a1 a2)\"\n  using assms\n  using poincare_collinear_def unique_poincare_line_general\n  by auto\n\nlemma poincare_line_poincare_collinear3_general:\n  assumes \"a \\<in> circline_set (poincare_line a1 a2)\" \"a1 \\<noteq> a2\"\n  shows \"poincare_collinear {a, a1, a2}\"\n  using assms\n  unfolding poincare_collinear_def\n  by (rule_tac x=\"poincare_line a1 a2\" in exI, simp)\n  \n\nlemma poincare_collinear3_poincare_lines_equal_general:\n  assumes \"poincare_collinear {a, a1, a2}\" \"a \\<noteq> a1\" \"a \\<noteq> a2\" \"a \\<noteq> inversion a1\" \"a \\<noteq> inversion a2\"\n  shows \"poincare_line a a1 = poincare_line a a2\"\n  using assms\n  using unique_poincare_line_general[of a a2 \"poincare_line a a1\"]\n  by (simp add: insert_commute poincare_collinear3_poincare_line_general)\n\nsubsubsection \\<open>Points collinear with @{term \"0\\<^sub>h\"}\\<close>\n\nlemma poincare_collinear_zero_iff:\n  assumes \"of_complex y' \\<in> unit_disc\" and \"of_complex z' \\<in> unit_disc\" and\n          \"y' \\<noteq> z'\" and \"y' \\<noteq> 0\" and \"z' \\<noteq> 0\"\n  shows \"poincare_collinear {0\\<^sub>h, of_complex y', of_complex z'} \\<longleftrightarrow>\n         y'*cnj z' = cnj y'*z'\" (is \"?lhs \\<longleftrightarrow> ?rhs\")\nproof-\n  have \"of_complex y' \\<noteq> of_complex z'\"\n    using assms\n    using of_complex_inj\n    by blast\n  show ?thesis\n  proof\n    assume ?lhs\n    hence \"0\\<^sub>h \\<in> circline_set (poincare_line (of_complex y') (of_complex z'))\"\n      using unique_poincare_line[of \"of_complex y'\" \"of_complex z'\"]\n      using assms \\<open>of_complex y' \\<noteq> of_complex z'\\<close>\n      unfolding poincare_collinear_def\n      by auto\n    moreover\n    let ?mix = \"y' * cnj z' - cnj y' * z'\"\n    have \"is_real (\\<i> * ?mix)\"\n      using eq_cnj_iff_real[of ?mix]\n      by auto\n    hence \"y' * cnj z' = cnj y' * z' \\<longleftrightarrow> Re (\\<i> * ?mix) = 0\"\n      using complex.expand[of \"\\<i> * ?mix\" 0]\n      by (metis complex_i_not_zero eq_iff_diff_eq_0 mult_eq_0_iff zero_complex.simps(1) zero_complex.simps(2))\n    ultimately\n    show ?rhs\n      using \\<open>y' \\<noteq> z'\\<close> \\<open>y' \\<noteq> 0\\<close> \\<open>z' \\<noteq> 0\\<close>\n      unfolding circline_set_def\n      by simp (transfer, transfer, auto simp add: vec_cnj_def split: if_split_asm, metis Re_complex_of_real Re_mult_real Im_complex_of_real)\n  next\n    assume ?rhs\n    thus ?lhs\n      using assms \\<open>of_complex y' \\<noteq> of_complex z'\\<close>\n      unfolding poincare_collinear_def\n      unfolding circline_set_def\n      apply (rule_tac x=\"poincare_line (of_complex y') (of_complex z')\" in exI)\n      apply auto\n      apply (transfer, transfer, simp add: vec_cnj_def)\n      done\n  qed\nqed\n\nlemma poincare_collinear_zero_polar_form:\n  assumes \"poincare_collinear {0\\<^sub>h, of_complex x, of_complex y}\" and\n          \"x \\<noteq> 0\" and \"y \\<noteq> 0\" and \"of_complex x \\<in> unit_disc\" and \"of_complex y \\<in> unit_disc\"\n  shows \"\\<exists> \\<phi> rx ry. x = cor rx * cis \\<phi> \\<and> y = cor ry * cis \\<phi> \\<and> rx \\<noteq> 0 \\<and> ry \\<noteq> 0\"\nproof-\n  from \\<open>x \\<noteq> 0\\<close> \\<open>y \\<noteq> 0\\<close> obtain \\<phi> \\<phi>' rx ry where\n    polar: \"x = cor rx * cis \\<phi>\" \"y = cor ry * cis \\<phi>'\" and  \"\\<phi> = arg x\" \"\\<phi>' = arg y\"\n    by (metis cmod_cis)\n  hence \"rx \\<noteq> 0\" \"ry \\<noteq> 0\"\n    using \\<open>x \\<noteq> 0\\<close> \\<open>y \\<noteq> 0\\<close>\n    by auto\n  have \"of_complex y \\<in> circline_set (poincare_line 0\\<^sub>h (of_complex x))\"\n    using assms\n    using unique_poincare_line[of \"0\\<^sub>h\" \"of_complex x\"]\n    unfolding poincare_collinear_def\n    unfolding circline_set_def\n    using of_complex_zero_iff\n    by fastforce\n  hence \"cnj x * y = x * cnj y\"\n    using \\<open>x \\<noteq> 0\\<close> \\<open>y \\<noteq> 0\\<close>\n    unfolding circline_set_def\n    by simp (transfer, transfer, simp add: vec_cnj_def field_simps)\n  hence \"cis(\\<phi>' - \\<phi>) = cis(\\<phi> - \\<phi>')\"\n    using polar \\<open>rx \\<noteq> 0\\<close> \\<open>ry \\<noteq> 0\\<close>\n    by (simp add: cis_mult)\n  hence \"sin (\\<phi>' - \\<phi>) = 0\"\n    using cis_diff_cis_opposite[of \"\\<phi>' - \\<phi>\"]\n    by simp\n  then obtain k :: int where \"\\<phi>' - \\<phi> = k * pi\"\n    using sin_zero_iff_int2[of \"\\<phi>' - \\<phi>\"]\n    by auto\n  hence *: \"\\<phi>' = \\<phi> + k * pi\"\n    by simp\n  show ?thesis\n  proof (cases \"even k\")\n    case True\n    then obtain k' where \"k = 2*k'\"\n      using evenE by blast\n    hence \"cis \\<phi> = cis \\<phi>'\"\n      using * cos_periodic_int sin_periodic_int\n      by (simp add: cis.ctr field_simps)\n    thus ?thesis\n      using polar \\<open>rx \\<noteq> 0\\<close> \\<open>ry \\<noteq> 0\\<close>\n      by (rule_tac x=\\<phi> in exI, rule_tac x=rx in exI, rule_tac x=ry in exI) simp\n  next\n    case False\n    then obtain k' where \"k = 2*k' + 1\"\n      using oddE by blast\n    hence \"cis \\<phi> = - cis \\<phi>'\"\n      using * cos_periodic_int sin_periodic_int\n      by (simp add: cis.ctr complex_minus field_simps)\n    thus ?thesis\n      using polar \\<open>rx \\<noteq> 0\\<close> \\<open>ry \\<noteq> 0\\<close>\n      by (rule_tac x=\\<phi> in exI, rule_tac x=rx in exI, rule_tac x=\"-ry\" 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/Poincare_Disc/Poincare_Lines.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9059898153067649, "lm_q2_score": 0.8198933359135361, "lm_q1q2_score": 0.7428150119755519}}
{"text": "(*\nTitle:KoenigsbergBridge.thy\nAuthor:Wenda Li\n*)\n\ntheory KoenigsbergBridge imports MoreGraph Map Enum\nbegin\n\nsection{*Definition of Eulerian trails and circuits*}\n\ndefinition (in valid_unMultigraph) is_Eulerian_trail:: \"'v\\<Rightarrow>('v,'w) path\\<Rightarrow>'v\\<Rightarrow> bool\" where\n  \"is_Eulerian_trail v ps v'\\<equiv> is_trail v ps v' \\<and> edges (rem_unPath ps G) = {}\"\n\ndefinition (in valid_unMultigraph) is_Eulerian_circuit:: \"'v \\<Rightarrow> ('v,'w) path \\<Rightarrow> 'v \\<Rightarrow> bool\" where\n  \"is_Eulerian_circuit v ps v'\\<equiv> (v=v') \\<and> (is_Eulerian_trail v ps v')\"\n\nsection{*Necessary conditions for Eulerian trails and circuits*}\n\nlemma (in valid_unMultigraph) euclerian_rev:\n  \"is_Eulerian_trail v' (rev_path ps) v=is_Eulerian_trail v ps v' \"\nproof -\n  have \"is_trail v' (rev_path ps) v=is_trail v ps v'\" \n    by (metis is_trail_rev)\n  moreover have \"edges (rem_unPath (rev_path ps) G)=edges (rem_unPath ps G)\"\n    by (metis rem_unPath_graph)\n  ultimately show ?thesis unfolding is_Eulerian_trail_def by auto\nqed\n\n(*Necessary conditions for Eulerian circuits*)\ntheorem (in valid_unMultigraph) euclerian_cycle_ex: \n  assumes \"is_Eulerian_circuit v ps v'\" \"finite V\" \"finite E\"\n  shows \"\\<forall>v\\<in>V. even (degree v G)\"\nproof -\n  obtain v ps v' where cycle:\"is_Eulerian_circuit v ps v'\" using assms by auto\n  hence \"edges (rem_unPath ps G) = {}\" \n    unfolding is_Eulerian_circuit_def is_Eulerian_trail_def \n    by simp\n  moreover have \"nodes (rem_unPath ps G)=nodes G\" by auto \n  ultimately have \"rem_unPath ps G = G \\<lparr>edges:={}\\<rparr>\" by auto\n  hence \"num_of_odd_nodes (rem_unPath ps G) = 0\" by (metis assms(2) odd_nodes_no_edge)\n  moreover have \"v=v'\" \n    by (metis `is_Eulerian_circuit v ps v'` is_Eulerian_circuit_def)\n  hence \"num_of_odd_nodes (rem_unPath ps G)=num_of_odd_nodes G\" \n    by (metis assms(2) assms(3) cycle is_Eulerian_circuit_def \n        is_Eulerian_trail_def rem_UnPath_cycle)\n  ultimately have \"num_of_odd_nodes G=0\" by auto\n  moreover have \"finite(odd_nodes_set G)\" \n    using `finite V` unfolding odd_nodes_set_def by auto\n  ultimately have \"odd_nodes_set G = {}\" unfolding num_of_odd_nodes_def by auto\n  thus ?thesis unfolding odd_nodes_set_def by auto\nqed\n\n(*Necessary conditions for Eulerian trails*)\ntheorem (in valid_unMultigraph) euclerian_path_ex: \n  assumes \"is_Eulerian_trail v ps v'\" \"finite V\" \"finite E\"\n  shows \"(\\<forall>v\\<in>V. even (degree v G)) \\<or> (num_of_odd_nodes G =2)\"\nproof -\n  obtain v ps v' where path:\"is_Eulerian_trail v ps v'\" using assms by auto\n  hence \"edges (rem_unPath ps G) = {}\" \n    unfolding  is_Eulerian_trail_def \n    by simp\n  moreover have \"nodes (rem_unPath ps G)=nodes G\" by auto \n  ultimately have \"rem_unPath ps G = G \\<lparr>edges:={}\\<rparr>\" by auto\n  hence odd_nodes: \"num_of_odd_nodes (rem_unPath ps G) = 0\" \n    by (metis assms(2) odd_nodes_no_edge)    \n  have \"v\\<noteq>v' \\<Longrightarrow> ?thesis\" \n    proof (cases \"even(degree v' G)\")\n      case True\n      assume \"v\\<noteq>v'\"\n      have \"is_trail v ps v'\" by (metis is_Eulerian_trail_def path)\n      hence \"num_of_odd_nodes (rem_unPath ps G) = num_of_odd_nodes G \n          + (if even (degree v G) then 2 else 0)\" \n        using rem_UnPath_even True `finite V` `finite E` `v\\<noteq>v'` by auto\n      hence \"num_of_odd_nodes G + (if even (degree v G) then 2 else 0)=0\"\n        using odd_nodes by auto\n      hence \"num_of_odd_nodes G = 0\" by auto\n      moreover have \"finite(odd_nodes_set G)\" \n        using `finite V` unfolding odd_nodes_set_def by auto\n      ultimately have \"odd_nodes_set G = {}\" unfolding num_of_odd_nodes_def by auto\n      thus ?thesis unfolding odd_nodes_set_def by auto\n    next  \n      case False\n      assume \"v\\<noteq>v'\"\n      have \"is_trail v ps v'\" by (metis is_Eulerian_trail_def path)\n      hence \"num_of_odd_nodes (rem_unPath ps G) = num_of_odd_nodes G \n          + (if odd (degree v G) then -2 else 0)\" \n        using rem_UnPath_odd False `finite V` `finite E` `v\\<noteq>v'` by auto\n      hence odd_nodes_if: \"num_of_odd_nodes G + (if odd (degree v G) then -2 else 0)=0\"\n        using odd_nodes by auto\n      have \"odd (degree v G) \\<Longrightarrow> ?thesis\" \n        proof -\n          assume \"odd (degree v G)\"\n          hence \"num_of_odd_nodes G = 2\" using odd_nodes_if by auto\n          thus ?thesis by simp\n        qed\n      moreover have \"even(degree v G) \\<Longrightarrow> ?thesis\" \n        proof -\n          assume \"even (degree v G)\"\n          hence \"num_of_odd_nodes G = 0\" using odd_nodes_if by auto\n          moreover have \"finite(odd_nodes_set G)\" \n            using `finite V` unfolding odd_nodes_set_def by auto\n          ultimately have \"odd_nodes_set G = {}\" unfolding num_of_odd_nodes_def by auto\n          thus ?thesis unfolding odd_nodes_set_def by auto\n        qed\n      ultimately show ?thesis by auto\n    qed\n  moreover have \"v=v'\\<Longrightarrow> ?thesis\" \n    by (metis assms(2) assms(3) euclerian_cycle_ex is_Eulerian_circuit_def path)\n  ultimately show ?thesis by auto \nqed\n\nsection{*Specific case of the Konigsberg Bridge Problem*}\n\n(*to denote the four landmasses*)\ndatatype kon_node = a | b | c | d\n\n(*to denote the seven bridges*)\ndatatype kon_bridge = ab1 | ab2 | ac1 | ac2 | ad1 | bd1 | cd1 \n\ndefinition kon_graph :: \"(kon_node,kon_bridge) graph\" where\n  \"kon_graph\\<equiv>\\<lparr>nodes={a,b,c,d}, \n              edges={(a,ab1,b), (b,ab1,a),\n                     (a,ab2,b), (b,ab2,a),\n                     (a,ac1,c), (c,ac1,a),\n                     (a,ac2,c), (c,ac2,a),\n                     (a,ad1,d), (d,ad1,a),\n                     (b,bd1,d), (d,bd1,b),\n                     (c,cd1,d), (d,cd1,c)} \\<rparr>\"\n\ninstantiation kon_node :: enum\nbegin\ndefinition [simp]:  \"enum_class.enum =[a,b,c,d]\"\ndefinition  [simp]: \"enum_class.enum_all P \\<longleftrightarrow> P a \\<and> P b \\<and> P c \\<and> P d\"\ndefinition   [simp]:\"enum_class.enum_ex P \\<longleftrightarrow> P a \\<or> P b \\<or> P c \\<or> P d\"\ninstance proof qed (auto,(case_tac x,auto)+)\nend\n\ninstantiation kon_bridge :: enum\nbegin\ndefinition [simp]:\"enum_class.enum =[ab1,ab2,ac1,ac2,ad1,cd1,bd1]\"\ndefinition  [simp]:\"enum_class.enum_all P \\<longleftrightarrow> P ab1 \\<and> P ab2 \\<and> P ac1 \\<and> P ac2 \\<and> P ad1  \\<and> P bd1  \n    \\<and> P cd1\"\ndefinition   [simp]:\"enum_class.enum_ex P \\<longleftrightarrow>  P ab1 \\<or> P ab2 \\<or> P ac1 \\<or> P ac2 \\<or> P ad1  \\<or> P bd1  \n    \\<or> P cd1\"\ninstance proof qed (auto,(case_tac x,auto)+)\nend\n\ninterpretation   kon_graph: valid_unMultigraph kon_graph \nproof (unfold_locales) \n  show \"fst ` edges kon_graph \\<subseteq> nodes kon_graph\" by eval\nnext\n  show \"snd ` snd ` edges kon_graph \\<subseteq> nodes kon_graph\"  by eval\nnext\n  have \" \\<forall>v w u'. ((v, w, u') \\<in> edges kon_graph) = ((u', w, v) \\<in> edges kon_graph)\" \n    by eval\n  thus \"\\<And>v w u'. ((v, w, u') \\<in> edges kon_graph) = ((u', w, v) \\<in> edges kon_graph)\" by simp\nnext\n  have \"\\<forall>v w. (v, w, v) \\<notin> edges kon_graph\"  by eval\n  thus \"\\<And>v w. (v, w, v) \\<notin> edges kon_graph\" by simp\nqed\n\n(*The specific case of the Konigsberg Bridge Problem does not have a solution*)\ntheorem \"\\<not>kon_graph.is_Eulerian_trail v1 p v2\" \nproof \n  assume \"kon_graph.is_Eulerian_trail  v1 p v2\"\n  moreover have \"finite (nodes kon_graph)\" by (metis finite_code) \n  moreover have \"finite (edges kon_graph)\" by (metis finite_code) \n  ultimately have contra: \n    \"(\\<forall>v\\<in>nodes kon_graph. even (degree v kon_graph)) \\<or>(num_of_odd_nodes kon_graph =2)\"\n    by (metis kon_graph.euclerian_path_ex)\n  have \"odd(degree a kon_graph)\" by eval \n  moreover have \"odd(degree b kon_graph)\" by eval\n  moreover have \"odd(degree c kon_graph)\" by eval\n  moreover have \"odd(degree d kon_graph)\" by eval\n  ultimately have \"\\<not>(num_of_odd_nodes kon_graph =2)\" by eval\n  moreover have \"\\<not>(\\<forall>v\\<in>nodes kon_graph. even (degree v kon_graph))\" by eval\n  ultimately show False using contra by auto\nqed\n\nsection{*Sufficient conditions for Eulerian trails and circuits*}\n\nlemma (in valid_unMultigraph) eulerian_cons:\n  assumes \n    \"valid_unMultigraph.is_Eulerian_trail (del_unEdge v0 w v1 G) v1 ps v2\"\n    \"(v0,w,v1)\\<in> E\"  \n  shows \"is_Eulerian_trail v0 ((v0,w,v1)#ps) v2\" \nproof -\n  have valid:\"valid_unMultigraph (del_unEdge v0 w v1 G)\" \n    using  valid_unMultigraph_axioms by auto \n  hence distinct:\"valid_unMultigraph.is_trail (del_unEdge v0 w v1 G) v1 ps v2\" \n    using assms unfolding valid_unMultigraph.is_Eulerian_trail_def[OF valid] \n    by auto\n  hence \"set ps \\<subseteq> edges (del_unEdge v0 w v1 G)\" \n    using valid_unMultigraph.path_in_edges[OF valid] by auto\n  moreover have \"(v0,w,v1)\\<notin>edges (del_unEdge v0 w v1 G)\" \n    unfolding del_unEdge_def by auto\n  moreover have \"(v1,w,v0)\\<notin>edges (del_unEdge v0 w v1 G)\" \n    unfolding del_unEdge_def by auto\n  ultimately have \"(v0,w,v1)\\<notin>set ps\" \"(v1,w,v0)\\<notin>set ps\"  by auto\n  moreover have \"is_trail v1 ps v2\" \n    using distinct_path_intro[OF distinct] . \n  ultimately have \"is_trail v0 ((v0,w,v1)#ps) v2\" \n    using `(v0,w,v1)\\<in> E` by auto\n  moreover have \"edges (rem_unPath ps (del_unEdge v0 w v1 G)) ={}\"\n    using assms unfolding valid_unMultigraph.is_Eulerian_trail_def[OF valid]\n    by auto\n  hence \"edges (rem_unPath ((v0,w,v1)#ps) G)={}\" \n    by (metis rem_unPath.simps(2))\n  ultimately show ?thesis unfolding is_Eulerian_trail_def by auto\nqed\n\nlemma (in valid_unMultigraph) eulerian_cons':\n  assumes \n    \"valid_unMultigraph.is_Eulerian_trail (del_unEdge v2 w v3 G) v1 ps v2\"\n    \"(v2,w,v3)\\<in> E\"  \n  shows \"is_Eulerian_trail v1 (ps@[(v2,w,v3)]) v3\" \nproof -\n  have valid:\"valid_unMultigraph (del_unEdge v3 w v2 G)\" \n    using valid_unMultigraph_axioms del_unEdge_valid by auto\n  have \"del_unEdge v2 w v3 G=del_unEdge v3 w v2 G\" \n    by (metis delete_edge_sym)\n  hence \"valid_unMultigraph.is_Eulerian_trail (del_unEdge v3 w v2 G) v2 \n        (rev_path ps) v1\" using assms valid_unMultigraph.euclerian_rev[OF valid] \n    by auto\n  hence \"is_Eulerian_trail v3 ((v3,w,v2)#(rev_path ps)) v1\" \n    using eulerian_cons by (metis assms(2) corres)\n  hence \"is_Eulerian_trail v1 (rev_path((v3,w,v2)#(rev_path ps))) v3\" \n    using euclerian_rev by auto\n  moreover have \"rev_path((v3,w,v2)#(rev_path ps)) = rev_path(rev_path ps)@[(v2,w,v3)]\" \n    unfolding rev_path_def by auto\n  hence \"rev_path((v3,w,v2)#(rev_path ps))=ps@[(v2,w,v3)]\" by auto\n  ultimately show ?thesis by auto\nqed\n\nlemma eulerian_split:\n  assumes \"nodes G1 \\<inter> nodes G2 = {}\" \"edges G1 \\<inter> edges G2={}\" \n    \"valid_unMultigraph G1\" \"valid_unMultigraph G2\"  \n    \"valid_unMultigraph.is_Eulerian_trail  G1 v1 ps1 v1'\"\n    \"valid_unMultigraph.is_Eulerian_trail  G2 v2 ps2 v2'\"\n  shows \"valid_unMultigraph.is_Eulerian_trail \\<lparr>nodes=nodes G1 \\<union> nodes G2,\n          edges=edges G1 \\<union> edges G2 \\<union> {(v1',w,v2),(v2,w,v1')}\\<rparr> v1 (ps1@(v1',w,v2)#ps2) v2'\"\nproof -\n  have \"valid_graph G1\" using `valid_unMultigraph G1` valid_unMultigraph_def by auto\n  have \"valid_graph G2\" using `valid_unMultigraph G2` valid_unMultigraph_def by auto\n  obtain G where G:\"G=\\<lparr>nodes=nodes G1 \\<union> nodes G2, edges=edges G1 \\<union> edges G2 \n      \\<union> {(v1',w,v2),(v2,w,v1')}\\<rparr>\" \n    by metis\n  have \"v1'\\<in>nodes G1\" \n    by (metis (full_types) `valid_graph G1` assms(3) assms(5) valid_graph.is_path_memb \n        valid_unMultigraph.is_trail_intro valid_unMultigraph.is_Eulerian_trail_def)\n  moreover have \"v2\\<in>nodes G2\" \n    by (metis (full_types) `valid_graph G2` assms(4) assms(6) valid_graph.is_path_memb \n        valid_unMultigraph.is_trail_intro valid_unMultigraph.is_Eulerian_trail_def)\n  ultimately have \"valid_unMultigraph \\<lparr>nodes=nodes G1 \\<union> nodes G2, edges=edges G1 \\<union> edges G2 \\<union> \n                   {(v1',w,v2),(v2,w,v1')}\\<rparr>\"\n    using\n      valid_unMultigraph.corres[OF `valid_unMultigraph G1`]\n      valid_unMultigraph.no_id[OF `valid_unMultigraph G1`]\n      valid_unMultigraph.corres[OF `valid_unMultigraph G2`]\n      valid_unMultigraph.no_id[OF `valid_unMultigraph G2`]\n      valid_graph.E_validD[OF `valid_graph G1`]\n      valid_graph.E_validD[OF `valid_graph G2`]\n      `nodes G1 \\<inter> nodes G2 = {}`\n    proof (unfold_locales,auto)\n      fix aa ab ba \n      assume  \"(aa, ab, ba) \\<in> edges G1\"\n      thus \"ba \\<in> nodes G1\" by (metis `\\<And>v' v e. (v, e, v') \\<in> edges G1 \\<Longrightarrow> v' \\<in> nodes G1`)\n    next\n      fix aa ab ba \n      assume \"ba \\<notin> nodes G2\"  \"(aa, ab, ba) \\<in> edges G2\"\n      thus \"ba \\<in> nodes G1\" by (metis `valid_graph G2` valid_graph.E_validD(2))\n    qed\n  hence valid: \"valid_unMultigraph G\" using G by auto\n  hence valid':\"valid_graph G\" using valid_unMultigraph_def by auto\n  moreover have \"valid_unMultigraph.is_trail G v1 (ps1@((v1',w,v2)#ps2)) v2'\"\n    proof -\n      have ps1_G:\"valid_unMultigraph.is_trail G v1 ps1 v1'\"\n        proof -\n          have \"valid_unMultigraph.is_trail G1 v1 ps1 v1'\" using assms \n            by (metis valid_unMultigraph.is_Eulerian_trail_def)\n          moreover have \"edges G1 \\<subseteq> edges G\" by (metis G UnI1 Un_assoc select_convs(2) subrelI)\n          moreover have \"nodes G1 \\<subseteq> nodes G\" by (metis G inf_sup_absorb le_iff_inf select_convs(1))\n          ultimately show ?thesis \n            using distinct_path_subset[of G1 G,OF `valid_unMultigraph G1` valid] by auto\n        qed\n      have ps2_G:\"valid_unMultigraph.is_trail G v2 ps2 v2'\"\n        proof -\n          have \"valid_unMultigraph.is_trail G2 v2 ps2 v2'\" using assms \n            by (metis valid_unMultigraph.is_Eulerian_trail_def)\n          moreover have \"edges G2 \\<subseteq> edges G\" by (metis G inf_sup_ord(3) le_supE select_convs(2))\n          moreover have \"nodes G2 \\<subseteq> nodes G\" by (metis G inf_sup_ord(4) select_convs(1))\n          ultimately show ?thesis \n            using distinct_path_subset[of G2 G,OF `valid_unMultigraph G2` valid] by auto\n        qed\n      have \"valid_graph.is_path G v1 (ps1@((v1',w,v2)#ps2)) v2'\" \n        proof -\n          have \"valid_graph.is_path  G v1 ps1 v1'\" \n            by (metis ps1_G valid valid_unMultigraph.is_trail_intro)\n          moreover have \"valid_graph.is_path G v2 ps2 v2'\" \n            by (metis ps2_G valid valid_unMultigraph.is_trail_intro)\n          moreover have \"(v1',w,v2) \\<in> edges G\" \n            using G by auto\n          ultimately show ?thesis \n            using valid_graph.is_path_split'[OF valid',of v1 ps1 v1' w v2 ps2 v2'] by auto\n        qed\n      moreover have \"distinct (ps1@((v1',w,v2)#ps2))\" \n        proof -\n          have \"distinct ps1\" by (metis ps1_G valid valid_unMultigraph.is_trail_path)\n          moreover have \"distinct ps2\" \n            by (metis ps2_G valid valid_unMultigraph.is_trail_path)\n          moreover have \"set ps1 \\<inter> set ps2 = {}\" \n            proof -\n              have \"set ps1 \\<subseteq>edges G1\" \n                by (metis assms(3) assms(5) valid_unMultigraph.is_Eulerian_trail_def \n                    valid_unMultigraph.path_in_edges)\n              moreover have \"set ps2 \\<subseteq> edges G2\" \n                by (metis assms(4) assms(6) valid_unMultigraph.is_Eulerian_trail_def \n                    valid_unMultigraph.path_in_edges)\n              ultimately show ?thesis using `edges G1 \\<inter> edges G2={}` by auto\n            qed\n          moreover have \"(v1',w,v2)\\<notin>edges G1\" \n            using `v2 \\<in> nodes G2` `valid_graph G1`\n            by (metis Int_iff  all_not_in_conv assms(1) valid_graph.E_validD(2))\n          hence \"(v1',w,v2)\\<notin>set ps1\" \n            by (metis (full_types) assms(3) assms(5) subsetD valid_unMultigraph.path_in_edges\n                valid_unMultigraph.is_Eulerian_trail_def )\n          moreover have \"(v1',w,v2)\\<notin>edges G2\" \n            using `v1' \\<in> nodes G1` `valid_graph G2`\n            by (metis  assms(1) disjoint_iff_not_equal valid_graph.E_validD(1))\n          hence  \"(v1',w,v2)\\<notin>set ps2\" \n            by (metis (full_types)  assms(4) assms(6) in_mono valid_unMultigraph.path_in_edges              \n                valid_unMultigraph.is_Eulerian_trail_def )\n          ultimately show ?thesis using distinct_append by auto\n        qed\n      moreover have \"set (ps1@((v1',w,v2)#ps2)) \\<inter> set (rev_path (ps1@((v1',w,v2)#ps2))) = {}\" \n        proof -\n          have \"set ps1 \\<inter> set (rev_path ps1) = {}\" \n            by (metis ps1_G valid valid_unMultigraph.is_trail_path)\n          moreover have \"set (rev_path ps2) \\<subseteq> edges G2\" \n            by (metis assms(4) assms(6) valid_unMultigraph.is_trail_rev \n                valid_unMultigraph.is_Eulerian_trail_def valid_unMultigraph.path_in_edges)\n          hence \"set ps1 \\<inter> set (rev_path ps2) = {}\" \n            using assms  \n              valid_unMultigraph.path_in_edges[OF `valid_unMultigraph G1`, of v1 ps1 v1']\n              valid_unMultigraph.path_in_edges[OF `valid_unMultigraph G2`, of v2 ps2 v2'] \n            unfolding valid_unMultigraph.is_Eulerian_trail_def[OF `valid_unMultigraph G1`] \n              valid_unMultigraph.is_Eulerian_trail_def[OF `valid_unMultigraph G2`]\n            by auto\n          moreover have \"set ps2 \\<inter> set (rev_path ps2) = {}\" \n            by (metis ps2_G valid valid_unMultigraph.is_trail_path)\n          moreover have \"set (rev_path ps1) \\<subseteq>edges G1\" \n            by (metis assms(3) assms(5) valid_unMultigraph.is_Eulerian_trail_def\n                valid_unMultigraph.path_in_edges valid_unMultigraph.euclerian_rev) \n          hence \"set ps2 \\<inter> set (rev_path ps1) = {}\" \n            by (metis calculation(2) distinct_append distinct_rev_path ps1_G ps2_G rev_path_append \n              rev_path_double valid valid_unMultigraph.is_trail_path) \n          moreover have \"(v2,w,v1')\\<notin>set (ps1@((v1',w,v2)#ps2))\" \n            proof -\n              have \"(v2,w,v1')\\<notin>edges G1\" \n                using `v2 \\<in> nodes G2` `valid_graph G1`\n                by (metis Int_iff  all_not_in_conv assms(1) valid_graph.E_validD(1))\n              hence \"(v2,w,v1')\\<notin>set ps1\" \n                by (metis assms(3) assms(5) split_list valid_unMultigraph.is_trail_split' \n                    valid_unMultigraph.is_Eulerian_trail_def) \n              moreover have \"(v2,w,v1')\\<notin>edges G2\" \n                using `v1' \\<in> nodes G1` `valid_graph G2`\n                by (metis IntI assms(1) empty_iff valid_graph.E_validD(2))\n              hence \"(v2,w,v1')\\<notin>set ps2\" \n                by (metis (full_types) assms(4) assms(6) in_mono  valid_unMultigraph.path_in_edges \n                    valid_unMultigraph.is_Eulerian_trail_def)\n              moreover have \"(v2,w,v1')\\<noteq>(v1',w,v2)\" \n                using `v1' \\<in> nodes G1` `v2 \\<in> nodes G2`\n                by (metis IntI Pair_inject  assms(1) assms(5) bex_empty)\n              ultimately show ?thesis by auto\n            qed\n          ultimately show ?thesis using rev_path_append by auto\n        qed\n      ultimately show ?thesis using valid_unMultigraph.is_trail_path[OF valid] \n        by auto \n    qed\n  moreover have \"edges (rem_unPath (ps1@((v1',w,v2)#ps2)) G)= {}\" \n    proof -\n      have \"edges (rem_unPath (ps1@((v1',w,v2)#ps2)) G)=edges G - \n           (set (ps1@((v1',w,v2)#ps2)) \\<union> set (rev_path (ps1@((v1',w,v2)#ps2))))\" \n        by (metis rem_unPath_edges)\n      also have \"...=edges G - (set ps1 \\<union> set ps2 \\<union> set (rev_path ps1) \\<union> set (rev_path ps2) \n                 \\<union> {(v1',w,v2),(v2,w,v1')})\" using rev_path_append by auto\n      finally have \"edges (rem_unPath (ps1@((v1',w,v2)#ps2)) G) = edges G - (set ps1 \\<union> \n                    set ps2 \\<union> set (rev_path ps1) \\<union> set (rev_path ps2) \\<union> {(v1',w,v2),(v2,w,v1')})\" .\n      moreover have \"edges (rem_unPath ps1 G1)={}\" \n        by (metis assms(3) assms(5) valid_unMultigraph.is_Eulerian_trail_def)\n      hence \"edges G1 - (set ps1 \\<union> set (rev_path ps1))={}\" \n        by (metis rem_unPath_edges)\n      moreover have \"edges (rem_unPath ps2 G2)={}\" \n        by (metis assms(4) assms(6) valid_unMultigraph.is_Eulerian_trail_def)\n      hence \"edges G2 - (set ps2 \\<union> set (rev_path ps2))={}\" \n        by (metis rem_unPath_edges)\n      ultimately show ?thesis using G by auto\n    qed\n  ultimately show ?thesis by (metis G valid valid_unMultigraph.is_Eulerian_trail_def)\nqed\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/Koenigsberg_Friendship/KoenigsbergBridge.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898127684335, "lm_q2_score": 0.819893335913536, "lm_q1q2_score": 0.7428150098943908}}
{"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\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\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": "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/BExp.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032941988938413, "lm_q2_score": 0.8221891327004133, "lm_q1q2_score": 0.742678673961842}}
{"text": "chapter \"Arithmetic and Boolean Expressions\"\n\ntheory Chapter3_ex3_04_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    N int \n  | V vname\n  | Plus aexp aexp\n  | Times aexp aexp\ntext_raw{*}%endsnip*}\n\ntext_raw{*\\snip{AExpavaldef}{1}{2}{% *}\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\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\ntext {* \\noindent\n  We can now write a series of updates to the function @{text \"\\<lambda>x. 0\"} compactly:\n*}\nlemma \"<a := Suc 0, b := 2> = (<> (a := Suc 0)) (b := 2)\"\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}{% *}\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\"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)\"\n\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}{% *}\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_raw{*}%endsnip*}\n\ntext_raw{*\\snip{AExpplusdef}{0}{2}{% *}\n\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 = 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\\<^sub>1     a\\<^sub>2     = Times a\\<^sub>1 a\\<^sub>2\"\n\ntext_raw{*}%endsnip*}\n\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\nlemma aval_times : \"aval (times a\\<^sub>1 a\\<^sub>2) s = aval a\\<^sub>1 s * aval a\\<^sub>2 s\"\napply(induction a\\<^sub>1 a\\<^sub>2 rule: times.induct)\napply(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)\" |\n\"asimp (Times a\\<^sub>1 a\\<^sub>2) = times (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 add: aval_times)\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_ex3_04_AExp.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9032942014971872, "lm_q2_score": 0.8221891239865619, "lm_q1q2_score": 0.7426786682311133}}
{"text": "theory CStruct\nimports Main Sequences\nbegin\n\nsection {* A formalization of command ctructures (C-Structs)*}\n\ntext {* C-Structs were introduced by Leslie Lamport in \\cite{Lamport05GeneralizeConsensus} \n  for the definition of Generalized Consensus *}\n\nsubsection {* The pre-CStruct locale fixes constants and makes some definitions that \n  are used in the C-Struct locale to state the properties of C-Structs.*}\n\nlocale pre_CStruct = Sequences +\n  fixes \\<delta>::\"'a \\<Rightarrow> 'c \\<Rightarrow> 'a\" (infix \"\\<bullet>\" 65)\n  and bot::'a (\"\\<bottom>\")\nbegin\n\nfun exec::\"'a \\<Rightarrow> 'c list \\<Rightarrow> 'a\" (infix \"\\<star>\" 65) where\n  \"exec s Nil = s\"\n| \"exec s (rs#r) = (exec s rs) \\<bullet> r\"\n\ndefinition less_eq (infix \"\\<preceq>\" 50) where\n  \"less_eq s s' \\<equiv> \\<exists> rs . s' = (s\\<star>rs)\"\n\ndefinition less (infix \"\\<prec>\" 50) where\n  \"less s s' \\<equiv> less_eq s s' \\<and> s \\<noteq> s'\"\n\ndefinition is_lb where\n  \"is_lb s s1 s2 \\<equiv> s \\<preceq> s2 \\<and> s \\<preceq> s1\"\n\ndefinition is_ub where\n  \"is_ub s s1 s2 \\<equiv> s2 \\<preceq> s \\<and> s1 \\<preceq> s\"\n\ndefinition is_glb where\n  \"is_glb s s1 s2 \\<equiv> is_lb s s1 s2 \\<and> (\\<forall> s' . is_lb s' s1 s2 \\<longrightarrow> s' \\<preceq> s)\"\n  \ndefinition is_lub where\n  \"is_lub s s1 s2 \\<equiv> is_ub s s1 s2 \\<and> (\\<forall> s' . is_ub s' s1 s2 \\<longrightarrow> s \\<preceq> s')\"\n\ndefinition contains where\n  \"contains s r \\<equiv> \\<exists> rs . r \\<in> set rs \\<and> s = (\\<bottom> \\<star> rs)\"\n\ndefinition inf  (infix \"\\<sqinter>\" 65) where\n  \"inf s1 s2 \\<equiv> THE s . is_glb s s1 s2\"\n\ndefinition sup  (infix \"\\<squnion>\" 65) where\n  \"sup s1 s2 \\<equiv> THE s . is_lub s s1 s2\"\n\ndefinition compat2 where\n  -- {* Two c-structs are compatible when they have a common upper-bound. *}\n  \"compat2 s1 s2 \\<equiv> \\<exists> s3 . s1 \\<preceq> s3 \\<and> s2 \\<preceq> s3\"\n\ndefinition compat where\n  \"compat S \\<equiv> \\<forall> s1 \\<in> S . \\<forall> s2 \\<in> S .compat2 s1 s2\"\n\nsubsection {* Lemmas in the pre-CStruct locale *}\n\nlemma exec_cons: \n  \"s \\<star> (rs # r)= (s \\<star> rs) \\<bullet> r\" by simp\n\nlemma exec_append: \n  \"(s \\<star> rs) \\<star> rs'  = s \\<star> (rs@rs')\"\nby (induct rs') (simp, metis append_Cons exec_cons)\n\nlemma trans:\n  assumes \"s1 \\<preceq> s2\" and \"s2 \\<preceq> s3\"\n  shows \"s1 \\<preceq> s3\" using assms\n    by (auto simp add:less_eq_def, metis exec_append)\n\nlemma contains_star:\n  fixes s r rs\n  assumes \"contains s r\"\n  shows \"contains (s \\<star> rs) r\"\nproof (induct rs)\n  case Nil thus ?case using assms by auto\nnext\n  case (Cons r' rs)\n  with this obtain rs' where 1:\"s \\<star> rs = \\<bottom> \\<star> rs'\" and 2:\"r \\<in> set rs'\" \n    by (auto simp add:contains_def)\n  have 3:\"s \\<star> (rs#r') = \\<bottom>\\<star>(rs'#r')\" using 1 by fastforce\n  show \"contains (s \\<star> (rs#r')) r\" using 2 3 \n    by (auto simp add:contains_def) (metis exec_cons set_rev_mp set_subset_Cons)\nqed\n\nlemma preceq_star: \"s \\<star> (rs#r) \\<preceq> s' \\<Longrightarrow> (s \\<star> rs)  \\<preceq> s'\"\nby (metis pre_CStruct.exec.simps(1) pre_CStruct.exec.simps(2) pre_CStruct.less_eq_def trans)\n\nlemma compat_sym:\"compat2 s1 s2 \\<longleftrightarrow> compat2 s2 s1\"\nby (metis compat2_def)\n\nlemma less_bullet:\"s \\<preceq> s \\<bullet> c\"\nby (metis pre_CStruct.exec.simps(1) pre_CStruct.exec_cons pre_CStruct.less_eq_def) \n\nend\n\nsubsection {* The CStruct locale *}\n\ntext {* Properties of CStructs *}\n\nlocale CStruct = pre_CStruct +\n  assumes antisym:\"\\<And> s1 s2 . s1 \\<preceq> s2 \\<and> s2 \\<preceq> s1 \\<Longrightarrow> s1 = s2\"\n    -- {* antisym implies that @{term \"op \\<preceq>\"} is a partial order*}\n  and glb_exists:\"\\<And> s1 s2 . \\<exists> s . is_glb s s1 s2\"\n  and glb_construct:\"\\<And> cs1 cs2 . is_glb s (\\<bottom> \\<star> cs1) (\\<bottom> \\<star> cs2) \n    \\<Longrightarrow> \\<exists> cs . set cs \\<subseteq> set cs1 \\<union> set cs2 \\<and> s = \\<bottom> \\<star> cs\"\n  and bot:\"\\<And> s . \\<bottom> \\<preceq> s\"\n  and lub_exists:\"compat2 s1 s2 \\<Longrightarrow> \\<exists> s . is_lub s s1 s2\"\n  and lub_compat:\"compat {s1,s2,s3} \\<Longrightarrow> compat {(s1 \\<squnion> s2), s3}\"\n\nbegin\n\nlemma inf_glb:\"is_glb (s1 \\<sqinter> s2) s1 s2\"\nproof -\n  { fix s s'\n    assume \"is_glb s s1 s2\" and \"is_glb s' s1 s2\"\n    hence \"s = s'\" using antisym by (auto simp add:is_glb_def is_lb_def) }\n    from this and glb_exists show ?thesis\n      by (auto simp add:inf_def, metis (lifting) theI')\nqed\n\nlemma sup_lub:\n  assumes \"compat2 s1 s2\"\n  shows \"is_lub (s1 \\<squnion> s2) s1 s2\"\nproof -\n  { fix s s'\n    assume \"is_lub s s1 s2\" and \"is_lub s' s1 s2\"\n    hence \"s = s'\" using antisym by (auto simp add:is_lub_def is_ub_def) }\n    from this and lub_exists show ?thesis \n      by (auto simp add:sup_def) (metis (lifting) assms theI)\nqed\n\n\n\nsublocale ordering less_eq less\n  -- {* CStructs form a partial order *}\nproof\n  fix s\n  show \"s \\<preceq> s\"\n  by (metis exec.simps(1) less_eq_def)\nnext\n  fix s s'\n  show \"s \\<prec> s' = (s \\<preceq> s' \\<and> s \\<noteq> s')\" \n  by (auto simp add:less_def)\nnext\n  fix s s'\n  assume \"s \\<preceq> s'\" and \"s' \\<preceq> s\"\n  thus \"s = s'\"\n  using antisym by auto\nnext\n  fix s1 s2 s3\n  assume \"s1 \\<preceq> s2\" and \"s2 \\<preceq> s3\"\n  thus \"s1 \\<preceq> s3\"\n  using trans by blast\nqed\n\nsublocale semilattice_set inf\nproof\n  fix s\n  show \"s \\<sqinter> s = s\" \n    using inf_glb\n    by (metis antisym is_glb_def is_lb_def refl) \nnext\n  fix s1 s2\n  show \"s1 \\<sqinter> s2 = (s2 \\<sqinter> s1)\"\n    using inf_glb \n    by (smt antisym is_glb_def pre_CStruct.is_lb_def)\nnext\n  fix s1 s2 s3\n  show \"(s1 \\<sqinter> s2) \\<sqinter> s3 = (s1 \\<sqinter> (s2 \\<sqinter> s3))\"\n    using inf_glb \n    by(auto simp add:is_glb_def is_lb_def, smt antisym trans)\nqed\n\nsublocale semilattice_order_set inf less_eq less\nproof \n  fix s s'\n  show \"s \\<preceq> s' = (s = s \\<sqinter> s')\"\n  by (metis antisym idem inf_glb pre_CStruct.is_glb_def pre_CStruct.is_lb_def)\nnext\n  fix s s'\n  show \"s \\<prec> s' = (s = s \\<sqinter> s' \\<and> s \\<noteq> s')\"\n  by (metis inf_glb local.antisym local.refl pre_CStruct.is_glb_def pre_CStruct.is_lb_def pre_CStruct.less_def)\nqed\n\nnotation F (\"\\<Sqinter> _\" [99])\n  -- {* The GLB of a set of c-structs. *}\n\nlemma GLB_constuct:\n  -- {* A direct consequence of glb_constuct*}\nfixes ss rset \nassumes \"finite ss\"  and \"ss \\<noteq> {}\"\nand \"\\<And> s . s \\<in> ss \\<Longrightarrow> \\<exists> rs . s = \\<bottom> \\<star> rs \\<and> set rs \\<subseteq> rset\"\nshows \"\\<exists> rs . \\<Sqinter> ss = \\<bottom> \\<star> rs \\<and> set rs \\<subseteq> rset\"\nusing assms\nproof (induct ss rule:finite_ne_induct)\n  case (singleton s)\n  obtain rs where \"s = \\<bottom> \\<star> rs \\<and> set rs \\<subseteq> rset\"\n    using singleton.prems by auto \n  moreover have \"\\<Sqinter> {s} = s\" using singleton by auto\n  ultimately show \"\\<exists> rs . \\<Sqinter> {s} = \\<bottom> \\<star> rs \\<and> set rs \\<subseteq> rset\" by blast\nnext\n  case (insert s ss)\n  have 1:\"\\<And> s' . s' \\<in> ss \\<Longrightarrow> \\<exists> rs . s' = \\<bottom> \\<star> rs \\<and> set rs \\<subseteq> rset\"\n    using insert(5) by force\n  obtain rs where 2:\"\\<Sqinter> ss = \\<bottom> \\<star> rs\" and 3:\"set rs \\<subseteq> rset\" \n    using insert(4) 1 by blast\n  obtain rs' where 4:\"s = \\<bottom> \\<star> rs'\"and 5:\"set rs' \\<subseteq> rset\"\n    using insert(5) by blast\n  have 6:\"\\<Sqinter> (insert s ss) = s \\<sqinter> (\\<Sqinter> ss)\"\n    by (metis insert.hyps(1-3) insert_not_elem) \n  obtain rs'' where 7:\"\\<Sqinter> (insert s ss) = \\<bottom> \\<star> rs''\" \n    and 8:\"set rs'' \\<subseteq> set rs' \\<union> set rs\"\n    using 2 4 6 glb_construct by (metis inf_glb) \n  have 9:\"set rs'' \\<subseteq> rset\" using 3 5 8 by blast\n  show \"\\<exists> rs . \\<Sqinter> (insert s ss) = \\<bottom> \\<star> rs \\<and> set rs \\<subseteq> rset\"\n    using 7 9 by blast\nqed\n\nlemma GLB_constuct_obtains:\nfixes ss rset \nassumes \"finite ss\"  and \"ss \\<noteq> {}\"\nand \"\\<And> s . s \\<in> ss \\<Longrightarrow> \\<exists> rs . s = \\<bottom> \\<star> rs \\<and> set rs \\<subseteq> rset\"\nobtains rs where \"\\<Sqinter> ss = \\<bottom> \\<star> rs\" and \"set rs \\<subseteq> rset\"\nproof -\n  from assms and GLB_constuct\n  have \"\\<exists> rs . \\<Sqinter> ss = \\<bottom> \\<star> rs \\<and> set rs \\<subseteq> rset\" by simp\n  with that show thesis by metis \nqed\n\nlemma glb_insert:\"S \\<noteq> {} \\<Longrightarrow> \\<Sqinter> (insert x S) \\<preceq> \\<Sqinter> S\"\nby (metis antimono finite_insert infinite order_iff_strict subset_insertI)\n\nlemma glb_anti:\"\\<lbrakk>finite S; S \\<noteq> {}; finite S'; S' \\<noteq> {}; S \\<subseteq> S'\\<rbrakk> \\<Longrightarrow> \\<Sqinter>S' \\<preceq> \\<Sqinter>S\"\n  proof (induct S arbitrary:S' rule:finite_ne_induct)\n    case (singleton s) thus ?case by (simp add: coboundedI)\n    next\n    case (insert s ss) thus ?case by (meson antimono insert_not_empty)\nqed\n\nlemma glb_singleton:\"\\<lbrakk>finite S; S \\<noteq> {}; s \\<in> S\\<rbrakk> \\<Longrightarrow> \\<Sqinter>S \\<preceq> s\"\nby (simp add: coboundedI)\n\nend\n\nend", "meta": {"author": "nano-o", "repo": "dist-systems-verif", "sha": "9826370dd5f1c6df6543e64481bfafc3e164674e", "save_path": "github-repos/isabelle/nano-o-dist-systems-verif", "path": "github-repos/isabelle/nano-o-dist-systems-verif/dist-systems-verif-9826370dd5f1c6df6543e64481bfafc3e164674e/Isabelle2/CStruct.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677622198946, "lm_q2_score": 0.8757869819218865, "lm_q1q2_score": 0.7426391272416174}}
{"text": "theory Thm7AVL\nimports\n  \"Thm7\"\n  \"HOL-Data_Structures.AVL_Set\"\nbegin\n\nsection \"Strongly Joinable AVL Trees\"\n\nsubsection \"Join for AVL Trees\"\n\nfun joinR where\n\"joinR L a R = (case L of Node l (k,_) r \\<Rightarrow> \n if ht r \\<le> ht R + 1 \n then balR l k (node r a R)\n else balR l k (joinR r a R))\"\n\ndeclare joinR.simps[simp del]\n\nfun joinL where\n\"joinL L a R = (case R of Node l (k,_) r \\<Rightarrow> \n if ht l \\<le> ht L + 1 \n then balL (node L a l) k r\n else balL (joinL L a l) k r)\"\n\ndeclare joinL.simps[simp del]\n\nfun join where \n\"join l a r = \n(if      ht l > ht r + 1 then joinR l a r\n else if ht r > ht l + 1 then joinL l a r\n else    node l a r)\"\n\n\nsubsection \"Proof of Correctness\"\nsubsubsection \"Set Preservation\"\n\nlemma balR_set:\"set_tree (balR l a r) = set_tree \n  l \\<union> {a} \\<union> set_tree r\"\n  by (auto simp: balR_def node_def split!: if_splits tree.splits)\n\nlemma joinR_set:\"ht l > ht r + 1 \\<Longrightarrow> set_tree (joinR l a r) = set_tree \n  l \\<union> {a} \\<union> set_tree r\"\nproof(induction l a r rule: joinR.induct)\n  case (1 L a R)\n  then show ?case \n    by (auto simp: joinR.simps[of L a R] balR_set node_def split!: if_splits tree.splits)\nqed\n\nlemma balL_set:\"set_tree (balL l a r) = set_tree \n  l \\<union> {a} \\<union> set_tree r\"\n  by (auto simp: balL_def node_def split!: if_splits tree.splits)\n\nlemma joinL_set:\"ht r > ht l + 1 \\<Longrightarrow> set_tree (joinL l a r) = set_tree \n  l \\<union> {a} \\<union> set_tree r\"\nproof(induction l a r rule: joinL.induct)\n  case (1 L a R)\n  then show ?case \n    by (auto simp: joinL.simps[of L a R]  balL_set node_def split!: if_splits tree.splits)\nqed\n\ncorollary set_join:\"set_tree (join l a r) = set_tree l \\<union> {a} \\<union> set_tree r\"\n  by(auto simp: node_def joinR_set joinL_set split!: if_splits)\n\nsubsubsection \"BST Preservation\"\n\nlemma balR_bst:\"\\<lbrakk>bst l; bst r; \\<forall>x\\<in>set_tree l. x < a; \\<forall>y\\<in>set_tree r. a < y\\<rbrakk>\n  \\<Longrightarrow> bst (balR l a r)\"\n  by (auto simp: balR_def node_def split!: if_splits tree.splits)\n\nlemma joinR_bst:\"\\<lbrakk>ht l > ht r + 1; bst l; bst r; \\<forall>x\\<in>set_tree l. x < a; \\<forall>y\\<in>set_tree r. a < y\\<rbrakk>\n  \\<Longrightarrow> bst (joinR l a r)\"\nproof(induction l a r arbitrary: b rule: joinR.induct)\n  case (1 L a R)\n  then show ?case\n    by (auto simp: joinR.simps[of L a R] node_def balR_bst joinR_set ball_Un \n      intro!: balR_bst split!: if_splits tree.splits) \nqed\n\nlemma balL_bst:\"\\<lbrakk>bst l; bst r; \\<forall>x\\<in>set_tree l. x < a; \\<forall>y\\<in>set_tree r. a < y\\<rbrakk>\n  \\<Longrightarrow> bst (balL l a r)\"\n  by (auto simp: balL_def node_def split!: if_splits tree.splits)\n\nlemma joinL_bst:\"\\<lbrakk>ht r > ht l + 1; bst l; bst r; \\<forall>x\\<in>set_tree l. x < a; \\<forall>y\\<in>set_tree r. a < y\\<rbrakk>\n\\<Longrightarrow> bst (joinL l a r)\"\nproof(induction l a r arbitrary: b rule: joinL.induct)\n  case (1 L a R)\n  then show ?case\n    by (auto simp: joinL.simps[of L a R] node_def balL_bst joinL_set ball_Un \n      intro!: balL_bst split!: if_splits tree.splits) \nqed\n\ncorollary bst_join:\"bst (Node l (a, b) r) \\<Longrightarrow> bst (join l a r)\"\n  by(auto simp: node_def joinR_bst joinL_bst split!: if_splits)\n\nsubsubsection \"Preservation of AVL Predicate\"\ntext\\<open>Automatic proofs are relatively expensive in this section, expect a few minutes\nruntime on low-powered machines.\\<close>\n\nlemma avl_joinR_height:\"\\<lbrakk>avl l; avl r; height l > height r + 1\\<rbrakk> \n\\<Longrightarrow> avl (joinR l a r) \\<and> height (joinR l a r) \\<in> {height l, height l + 1}\"\nproof(induction l a r rule: joinR.induct)\n  case (1 L a R)\n  then show ?case \n    by(auto simp: joinR.simps[of L a R] balR_def node_def max_absorb2 split!: if_splits tree.splits)\n    \\<comment> \\<open>6 subgoals\\<close>\n    fastforce+\nqed\n\nlemma avl_joinL_height:\"\\<lbrakk>avl l; avl r; height r > height l + 1\\<rbrakk> \n\\<Longrightarrow> avl (joinL l a r) \\<and> height (joinL l a r) \\<in> {height r, height r + 1}\"\nproof(induction l a r rule: joinL.induct)\n  case (1 L a R)\n  then show ?case \n    by(auto simp: joinL.simps[of L a R] balL_def node_def max_absorb2 split!: if_splits tree.splits)\n    \\<comment> \\<open>20 subgoals\\<close>\n    fastforce+\nqed\n\ncorollary inv_join:\"\\<lbrakk>avl l; avl r\\<rbrakk> \\<Longrightarrow> avl (join l a r)\"\n  by(auto simp: node_def avl_joinR_height avl_joinL_height split: if_splits)\n\ntext \\<open>To finish the proof of functional correctness, instantiate the \\<open>Set2_Join\\<close> locale.\\<close>\n\ninterpretation tree_ht: Set2_Join\nwhere join = join and inv = avl\nproof (standard, goal_cases)\n  case 1 show ?case by (rule set_join)\nnext\n  case 2 thus ?case by (rule bst_join)\nnext\n  case 3 show ?case by simp\nnext\n  case 4 thus ?case by (rule inv_join)\nnext\n  case 5 thus ?case by simp\nqed\n\nsubsection \"Proof of Strongly Joinable Properties\"\n\n\nsubsubsection \"Monoticity Rule\"\n\ncorollary join_height: \nassumes \"avl l \\<and> avl r\"\nshows \"height (join l a r) \\<in> {max (height l) (height r), max (height l) (height r) + 1}\"\nproof-\n  consider \n    (Right) R  where \"R = joinR l a r\" and \"ht l > ht r + 1\" and \n                     \"join l a r = R\"\n  | (Left)  L  where \"L = joinL l a r\" and \"ht r > ht l + 1\" and \n                     \"join l a r = L\"\n  | (Node)  EQ where \"EQ = node l a r\" and \"ht r \\<le> ht l + 1\" and \n                     \"ht l \\<le> ht r + 1\" and \"join l a r = EQ\"\n    by(auto split!: if_splits)linarith\n  then show ?thesis\n  proof cases\n    case Right\n    from this assms show ?thesis \n      by (metis avl_joinR_height ht_height linorder_not_less max_def trans_le_add1)\n  next\n    case Left\n    from this assms show ?thesis \n      by (metis add_lessD1 ht_height avl_joinL_height max.absorb4)\n  next\n  next\n    case Node\n    then show ?thesis \n      by simp\n  qed\nqed\n\ncorollary rule_mono: \"\\<lbrakk>avl l; avl r\\<rbrakk> \\<Longrightarrow> max (height l) (height r) \\<le> height (join l a r)\"\n  using join_height \n  by (metis insertE le_add_same_cancel1 zero_le_one nle_le singletonD)\n\nsubsubsection \"Submodularity Rule\"\n\ncorollary rule_sub_dec: \nassumes \"height l' \\<le> height l \\<and> height r' \\<le> height r\"\nassumes \"avl l' \\<and> avl r' \\<and> avl (Node l (a,b) r)\"\nshows \"height (join l' a r') \\<le> height (Node l (a,b) r)\"\nproof-\n  from assms have \"max (height l') (height r') \\<le> max (height l) (height r)\"\n    by linarith\n  moreover from assms have \"height (join l' a r') \\<le> max (height l') (height r') + 1\"\n    using join_height by (metis order_eq_iff insertE singletonD trans_le_add1)\n  moreover have \"height (Node l (a,b) r) = max (height l) (height r) + 1\"\n    by simp\n  ultimately show ?thesis \n    by linarith\nqed\n\n\n(* TODO maybe shorten this *)\nlemma rule_sub_inc: \nassumes \"height l \\<le> height l' \\<and> height r \\<le> height r'\"\nassumes \"height r' - height r \\<le> x \\<and> height l' - height l \\<le> x\"\nassumes \"avl l' \\<and> avl r' \\<and> avl (Node l (a,b) r)\"\nshows \"height (Node l (a,b) r) \\<le> height (join l' a r') \\<and>\n  height (join l' a r') - height (Node l (a,b) r) \\<le> x\"\nproof-\n    have joinmax:\"height (join l' a r') \\<le> max (height l') (height r') + 1\"\n      using assms join_height by (metis order_eq_iff insertE singletonD trans_le_add1)\n    show ?thesis \n    proof(cases \"height l \\<ge> height r\")\n      case True\n      then have \"height (Node l (a,b) r) = height l + 1\"\n        using assms by simp\n      moreover then have \"max (height l') (height r') \\<le> height l + x\"\n        using True assms by auto\n      moreover then have \"height (join l' a r') \\<le> height l + x + 1\"\n        using assms joinmax by linarith \n      moreover have \"height (join l' a r') \\<noteq> height l\"\n        proof(rule ccontr)\n          assume *:\"\\<not> height (join l' a r') \\<noteq> height l\"\n          moreover then have heq:\"height l = height l'\"\n            by (metis assms(1) assms(3) le_antisym max.bounded_iff rule_mono)\n          ultimately have \"height r' \\<le> height l'\"\n            by (metis assms(3) max.commute max_def rule_mono)\n          moreover then have \"join l' a r' = node l' a r'\"\n            using heq assms by auto\n          ultimately have \"height (join l' a r') = height l + 1 \"\n            using heq by simp\n          then show False \n            using * by linarith\n          qed\n      moreover have \"height l \\<le> height (join l' a r')\"\n        by (meson assms(1) assms(3) le_max_iff_disj order_trans rule_mono)\n      ultimately show ?thesis \n        by linarith\n    next\n      case False\n      then have \"height (Node l (a,b) r) = height r + 1\"\n        using assms by simp\n      moreover then have \"max (height l') (height r') \\<le> height r + x\"\n        using False assms by auto\n      moreover then have \"height (join l' a r') \\<le> height r + x + 1\"\n        using assms joinmax by linarith \n      moreover have \"height (join l' a r') \\<noteq> height r\"\n        proof(rule ccontr)\n          assume *:\"\\<not> height (join l' a r') \\<noteq> height r\"\n          moreover then have heq:\"height r = height r'\"\n            by (metis assms(1) assms(3) le_antisym max.bounded_iff rule_mono)\n          ultimately have \"height l' \\<le> height r'\"\n            by (metis assms(3) max_def rule_mono)\n          moreover then have \"join l' a r' = node l' a r'\"\n            using heq assms by auto\n          ultimately have \"height (join l' a r') = height r + 1 \"\n            using heq by simp\n          then show False \n            using * by linarith\n          qed\n      moreover have \"height r \\<le> height (join l' a r')\"\n        by (meson assms(1) assms(3) le_max_iff_disj order_trans rule_mono)\n      ultimately show ?thesis \n        by linarith\n    qed\nqed\n\nsubsubsection \"Balancing Rule\" \n\nlemma rule_bal: \"avl t \\<Longrightarrow> bal t height 1 2\"\n  by(induction t) auto\n\nsubsubsection \"Cost Rule\"\n\nfun T_joinR :: \"'a tree_ht \\<Rightarrow> 'a \\<Rightarrow> 'a tree_ht \\<Rightarrow> nat\" where\n\"T_joinR L a R = (case L of Node l (k,_) r \\<Rightarrow> \n if ht r \\<le> ht R + 1 \n then 1 \n else 1 + T_joinR r a R)\"\n\ndeclare T_joinR.simps[simp del]\n\nfun T_joinL :: \"'a tree_ht \\<Rightarrow> 'a \\<Rightarrow> 'a tree_ht \\<Rightarrow> nat\" where\n\"T_joinL L a R = (case R of Node l (k,_) r \\<Rightarrow> \n if ht l \\<le> ht L + 1 \n then 1 \n else 1 + T_joinL L a l)\"\n\ndeclare T_joinL.simps[simp del]\n\nfun T_join :: \"'a tree_ht \\<Rightarrow> 'a \\<Rightarrow> 'a tree_ht \\<Rightarrow> nat\" where \n\"T_join l a r = \n(if      ht l > ht r + 1 then T_joinR l a r\n else if ht r > ht l + 1 then T_joinL l a r\n else    1)\"\n\nlemma T_joinR:\"\\<lbrakk>avl l; avl r; ht l > ht r + 1\\<rbrakk> \\<Longrightarrow> T_joinR l a r \\<le> 1 + height l - height r\"\nproof(induction l a r rule: T_joinR.induct)\n  case (1 L a R)\n  then show ?case \n    using T_joinR.simps[of L a R]\n    by(auto simp: max_absorb2 split!: if_splits tree.splits) fastforce\nqed\n\nlemma T_joinL:\"\\<lbrakk>avl l; avl r; ht r > ht l + 1\\<rbrakk> \\<Longrightarrow> T_joinL l a r \\<le> 1 + height r - height l\"\nproof(induction l a r rule: T_joinL.induct)\n  case (1 L a R)\n  then show ?case \n    by(auto simp: T_joinL.simps[of L a R] max_absorb1 split!: if_splits tree.splits) fastforce\nqed\n\ncorollary rule_cost:\nassumes \"avl l \\<and> avl r\" \nshows \"T_join l a r \\<le> 1 + nat(abs(int(height l) - int(height r)))\"\nproof-\n  consider \n    (Right) R where \"R = T_joinR l a r\" and \"ht l > ht r + 1\" and \n                    \"T_join l a r = R\"\n  | (Left)  L where \"L = T_joinL l a r\" and \"ht r > ht l + 1\" and \n                    \"T_join l a r = L\"\n  | (Node)  EQ where \"EQ = 1\" and \"ht r \\<le> ht l + 1\" and \n                     \"ht l \\<le> ht r + 1\" and \"T_join l a r = EQ\"\n    by(auto split!: if_splits)linarith\n  then show ?thesis \n  proof cases\n    case Right\n    then have \"max (height l) (height r) = height l\"\n      using assms by simp\n    then moreover have \"nat(abs(int(height l) - int(height r))) = height l - height r\"\n      by simp\n    ultimately show ?thesis \n      using Right T_joinR assms by (metis Nat.add_diff_assoc max.orderI)\n  next\n    case Left\n    then have \"max (height l) (height r) = height r\"\n      using assms by simp\n    then moreover have \"nat(abs(int(height l) - int(height r))) = height r - height l\"\n      by simp\n    ultimately show ?thesis \n      using Left T_joinL assms by (metis Nat.add_diff_assoc max.cobounded1)\n  next\n    case Node\n    then show ?thesis \n      by simp\n  qed\nqed\n\ninterpretation tree_ht: StronglyJoinable\nwhere join = join and inv = avl\nand rank = height and c\\<^sub>l = 1 and c\\<^sub>u = 2\nproof (standard, goal_cases)\n  case 1 thus ?case by simp\nnext\n  case (2 l r a) thus ?case by (metis of_nat_le_iff of_nat_max rule_mono)\nnext\n  \\<comment> \\<open>this simply converts from nat to real, but takes a long time to run, expect a few minutes\\<close>\n  case (3 l' l r' r x a b) \n  then show ?case \n    by (smt (verit) diff_diff_cancel diff_le_self le_diff_iff' nat_le_linear of_nat_diff of_nat_le_iff of_nat_mono ord_le_eq_subst rule_sub_inc) \nnext\n  case (4 l' l r' r a b) thus ?case \n    by (meson of_nat_le_iff rule_sub_dec)\nnext\n  case 5 thus ?case by simp\nnext\n  case (6 t) thus ?case by(rule rule_bal)\nqed\n\nend", "meta": {"author": "mitcoef", "repo": "StronglyJoinableIsa", "sha": "f47ed9e76813346862305d0f69e744ad295f55c3", "save_path": "github-repos/isabelle/mitcoef-StronglyJoinableIsa", "path": "github-repos/isabelle/mitcoef-StronglyJoinableIsa/StronglyJoinableIsa-f47ed9e76813346862305d0f69e744ad295f55c3/Thm7AVL.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8757869851639066, "lm_q2_score": 0.8479677545357568, "lm_q1q2_score": 0.7426391232610781}}
{"text": "theory tut4 imports Main\nbegin\n\nlemma 1: \"(P \u27f6(Q\u27f6R))\u27f6((P\u27f6Q)\u27f6(P\u27f6R))\"\nproof (rule impI)+\n  assume 1: \"(P \u27f6(Q\u27f6R))\" and 2: \"P\u27f6Q\" and 3: \"P\"\n  from 2 and 3\n  have 4: \"Q\" by (rule mp)\n  from 1 and 3\n  have 5: \"Q\u27f6R\" by (rule mp)\n  from 5 and 4\n  show \"R\" by (rule mp) (* replace with blast *)\nqed\n\n\nlemma 2: \"(\u2200x. P x \u27f6 Q) \u27f6 (\u2203x. P x \u27f6 Q)\"\nproof \n  assume \"(\u2200x. P x \u27f6 Q)\" then have \"P a \u27f6 Q\"\n    by (simp add: \u2039\u2200x. P x \u27f6 Q\u203a)\n  then show \"(\u2203x. P x \u27f6 Q)\"\n    by simp\nqed\n\nlemma three_try: \"\u00ac(\u2203x. P x) \u27f9 (\u2200x.\u00acP x)\"\n  apply (rule allI)\n  apply (rule notI)\n  apply (erule notE)\n  apply (rule exI)\n  apply assumption\n  done\n\nlemma 3: \"\u00ac(\u2203x. P x) \u27f9 (\u2200x.\u00acP x)\"\nproof (rule allI, rule notI)\n  fix x\n  assume forContra: \"P x\"\n  have 0: \"\u2203x. P x\"\n    using forContra by (rule exI)\n  assume notExist: \"\u2204x. P x\"\n  then show \"False\"\n    using forContra by auto\nqed\n\nlemma 31: \"\u00ac(\u2203x. P x) \u27f9 (\u2200x.\u00acP x)\"\nproof (safe)\n  fix x\n  assume \"P x\" then have \"(\u2203x. P x)\" ..\n  assume ex: \"\u00ac(\u2203x. P x)\"\n  then show False using ex\n    using \u2039P x\u203a by auto\nqed\n\n(* safe is a method that will not make any provable goal become unprovable.\nIt does not do any exI or spec/allE steps. You can use other methods instead. *)\n\nlemma assumes n_all: \"\u00ac(\u2200x. P x)\" shows \"\u2203x. \u00acP x\"\nproof (rule ccontr)\n  assume n_ex: \"\u2204x. \u00ac P x\"\n  { fix x\n    have \"P x\"\n    proof (rule ccontr)\n      assume \"\u00acP x\" then have \"\u2203x. \u00acP x\" ..\n      then show False using n_ex by simp\n    qed\n  }\n  then have \"\u2200x. P x\" .. \n  then show False using n_all by simp\nqed\n\nlemma 5: \"(R\u27f6P)\u27f6(((\u00acR \u2228 P)\u27f6(Q\u27f6S))\u27f6(Q\u27f6S))\"\nproof (rule impI)+ \n  assume \"R \u27f6 P\" and \"\u00acR \u2228 P \u27f6 Q \u27f6 S\" and \"Q\" \n  show \"S\"\n  (* show the possible cases: \n      1. R  \n      2. \u00acR \n  *)\n  proof (cases)\n    assume \"R\"\n    then have \"P\"\n      using \u2039R \u27f6 P\u203a by blast\n    then have \"\u00acR \u2228 P\"\n      by simp\n    then have \"Q \u27f6 S\"\n      using \u2039\u00ac R \u2228 P \u27f6 Q \u27f6 S\u203a by blast\n    then show \"S\"\n      using \u2039Q\u203a by simp\n  next\n    assume \"\u00acR\"\n    then have \"\u00acR \u2228 P\"\n      by simp\n    then have \"Q \u27f6 S\"\n      using \u2039\u00ac R \u2228 P \u27f6 Q \u27f6 S\u203a by blast\n    then show \"S\"\n      using \u2039Q\u203a by simp\n  qed\nqed\n\nend\n", "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/tutorial_4.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096044278532, "lm_q2_score": 0.8104789132480439, "lm_q1q2_score": 0.7424875166127818}}
{"text": "theory prop_72\nimports Main\n        \"$HIPSTER_HOME/IsaHipster\"\nbegin\n  datatype 'a list = Nil2 | Cons2 \"'a\" \"'a list\"\n  datatype Nat = Z | S \"Nat\"\n  fun take :: \"Nat => Nat list => Nat 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  fun minus :: \"Nat => Nat => Nat\" where\n  \"minus (Z) y = Z\"\n  | \"minus (S z) (Z) = S z\"\n  | \"minus (S z) (S x2) = minus z x2\"\n  fun len :: \"'a list => Nat\" where\n  \"len (Nil2) = Z\"\n  | \"len (Cons2 y xs) = S (len xs)\"\n  fun 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  fun append :: \"Nat list => Nat list => Nat list\" where\n  \"append (Nil2) y = y\"\n  | \"append (Cons2 z xs) y = Cons2 z (append xs y)\"\n  fun rev :: \"Nat list => Nat list\" where\n  \"rev (Nil2) = Nil2\"\n  | \"rev (Cons2 y xs) = append (rev xs) (Cons2 y (Nil2))\"\n  (*hipster take minus len drop append rev *)\n\nlemma lemma_da [thy_expl]: \"drop x3 Nil2 = Nil2\"\nby (hipster_induct_schemes drop.simps)\n\nlemma lemma_daa [thy_expl]: \"drop (S Z) (drop x3 y3) = drop (S x3) y3\"\nby (hipster_induct_schemes drop.simps)\n\nlemma lemma_dab [thy_expl]: \"drop x (drop y z) = drop y (drop x z)\"\nby (hipster_induct_schemes drop.simps Nat.exhaust)\n\nlemma lemma_ah [thy_expl]: \"drop (len x2) x2 = Nil2\"\nby (hipster_induct_schemes len.simps append.simps rev.simps drop.simps take.simps minus.simps)\n\nlemma lemma_ta [thy_expl]: \"take x2 (take x2 y2) = take x2 y2\"\nby (hipster_induct_schemes take.simps)\n\nlemma lemma_taa [thy_expl]: \"take x1 (take Z y1) = take Z y1\"\nby (hipster_induct_schemes take.simps)\n\nlemma lemma_tab [thy_expl]: \"take (S x2) (take x2 y2) = take x2 y2\"\nby (hipster_induct_schemes take.simps)\n\nlemma lemma_tac []: \"take x (take y z) = take y (take x z)\"\napply(induction y z arbitrary: x rule: take.induct)\napply(simp_all)\napply(metis take.simps thy_expl)\napply(metis take.simps thy_expl)\nby (metis take.simps list.exhaust Nat.exhaust)\n\nlemma lemma_a [thy_expl]: \"minus x2 x2 = Z\"\nby (hipster_induct_schemes minus.simps)\n\nlemma lemma_aa [thy_expl]: \"minus x3 Z = x3\"\nby (hipster_induct_schemes minus.simps)\n\nlemma lemma_ab [thy_expl]: \"minus x2 (S x2) = Z\"\nby (hipster_induct_schemes)\n\nlemma lemma_ac [thy_expl]: \"minus (S x2) x2 = S Z\"\nby (hipster_induct_schemes)\n\nlemma lemma_ad [thy_expl]: \"minus (minus x3 y3) (minus y3 x3) = minus x3 y3\"\nby (hipster_induct_schemes minus.simps)\n\nlemma lemma_ae [thy_expl]: \"minus (minus x3 y3) (S Z) = minus x3 (S y3)\"\nby (hipster_induct_schemes minus.simps)\n\nlemma lemma_af [thy_expl]: \"minus (minus x4 y4) x4 = Z\"\nby (hipster_induct_schemes minus.simps)\n\nlemma lemma_aq [thy_expl]: \"append x2 Nil2 = x2\"\nby (hipster_induct_schemes append.simps)\n\nlemma lemma_ar [thy_expl]: \"append (append x1 y1) z1 = append x1 (append y1 z1)\"\nby (hipster_induct_schemes append.simps)\n\nlemma lemma_as [thy_expl]: \"minus (len x3) y3 = len (drop y3 x3)\"\nby (hipster_induct_schemes rev.simps append.simps take.simps drop.simps len.simps minus.simps)\n\nlemma lemma_at [thy_expl]: \"append (take x2 y2) (drop x2 y2) = y2\"\nby (hipster_induct_schemes rev.simps append.simps take.simps drop.simps len.simps minus.simps)\n\nlemma lemma_au [thy_expl]: \"append (rev x4) (rev y4) = rev (append y4 x4)\"\nby (hipster_induct_schemes rev.simps append.simps take.simps drop.simps len.simps minus.simps)\n\nlemma lemma_av [thy_expl]: \"take (len x2) (append x2 y2) = x2\"\nby (hipster_induct_schemes rev.simps append.simps take.simps drop.simps len.simps minus.simps)\n\nlemma lemma_aw [thy_expl]: \"drop (len x2) (append x2 y2) = y2\"\nby (hipster_induct_schemes rev.simps append.simps take.simps drop.simps len.simps minus.simps)\n\nlemma lemma_ax [thy_expl]: \"take (S Z) (append x1 x1) = take (S Z) x1\"\nby (hipster_induct_schemes append.simps take.simps)\n\nlemma lemma_ay [thy_expl]: \"rev (rev x3) = x3\"\nby (hipster_induct_schemes rev.simps append.simps take.simps drop.simps len.simps minus.simps)\n\n(*\n4: xs++[] == xs\n5: []++xs == xs\n6: (x:xs)++ys == x:(xs++ys)\n7: (xs++ys)++zs == xs++(ys++zs)\n\n== Equations about several functions ==\n8: (length (xs++ys)) == (length (ys++xs))\n9: (length (x:(xs++ys))) == (length (x:(ys++xs)))\n10: (length (xs++(ys++zs))) == (length (xs++(zs++ys)))\n11: (length ((x:xs)++(y:ys))) == (length ((x:xs)++(z:ys)))\n12: (length ((x:xs)++(ys++zs))) == (length ((x:ys)++(xs++zs)))\n13: (length ((x:xs)++(ys++zs))) == (length ((y:xs)++(ys++zs)))\n14: (length ((xs++ys)++(zs++ys))) == (length ((xs++zs)++(ys++ys)))*)\n\n\nlemma ax2[thy_expl]: \"len (append y (Cons2 ya xs)) = S (len (append y xs))\"\nby(hipster_induct_schemes)\n\nlemma lemma_applen [thy_expl]: \"len (append x y) = len (append y x)\"\n(*apply(induction x)\napply(simp_all)\napply(metis thy_expl append.simps len.simps)*)\nby (hipster_induct_schemes)\n\nlemma lemma_revlen [thy_expl]: \"len (rev x) = len x\"\nby (hipster_induct_schemes len.simps rev.simps)\n\nlemma lemma_takerev [thy_expl]: \"take (len x) (rev x) = rev x\"\nby (hipster_induct_schemes take.simps len.simps rev.simps append.simps)\n\nlemma lemma_droprev [thy_expl]: \"drop (len x) (rev x) = Nil2\"\nby (hipster_induct_schemes drop.simps len.simps rev.simps)\n(*hipster len append rev drop take minus*)\n\nsetup\\<open>Hip_Tac_Ops.set_metis_to @{context} 800\\<close>\n\nlemma unknown [thy_expl]: \"minus (minus x y) z = minus (minus x z) y\"\noops\n\nlemma unknown [thy_expl]: \"minus x (minus x y) = minus y (minus y x)\"\noops\n\nlemma unknown [thy_expl]: \"minus (minus x y) (minus z y) =\nminus (minus x z) (minus y z)\"\noops\n\nlemma unknown [thy_expl]: \"minus (minus x y) (S z) =\nminus (minus x z) (S y)\"\noops\n\nlemma unknown [thy_expl]: \"minus (minus x y) (minus x z) =\nminus (minus z y) (minus z x)\"\noops\n\nlemma unknown [thy_expl]: \"drop (minus x y) (drop y z) =\ndrop (minus y x) (drop x z)\"\noops\n\nlemma unknown [thy_expl]: \"take (minus x y) (take x z) =\ntake (minus x y) z\"\noops\n\nlemma unknown [thy_expl]: \"drop (S x) (drop y z) =\ndrop (S y) (drop x z)\"\noops\n\nlemma unknown [thy_expl]: \"minus (S x) (minus x y) =\nminus (S y) (minus y x)\"\noops\n\nlemma unknown [thy_expl]: \"drop (S x) (drop y z) =\ndrop (S y) (drop x z)\"\noops\n\n  theorem x0 :\n    \"(rev (drop i xs)) = (take (minus (len xs) i) (rev xs))\"\nby (hipster_induct_schemes rev.simps append.simps take.simps drop.simps len.simps minus.simps Nat.exhaust list.exhaust)\n\n    by (tactic \\<open>Subgoal.FOCUS_PARAMS (K (Tactic_Data.hard_tac @{context})) @{context} 1\\<close>)\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/isaplanner/prop_72.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094032139577, "lm_q2_score": 0.8311430499496096, "lm_q1q2_score": 0.7424679019359144}}
{"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 n) = True\" |\n\"optimal (V x) = True\" |\n\"optimal (Plus (N a) (N b)) = False\" |\n\"optimal (Plus a b) = ((optimal a) \\<and> (optimal b))\"\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 (simp split: aexp.split)\n  apply (simp split: aexp.split)\n  apply (simp split: aexp.split)\n  apply (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(* 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": "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/Chapter3.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8311430353105599, "lm_q2_score": 0.8933094081846421, "lm_q1q2_score": 0.7424678929900633}}
{"text": "theory 10\n  imports Main \"~~/src/HOL/Library/Code_Target_Nat\" \nbegin\n  \n  (* section 2.5 *)\n  \n  (* I don't understand this:\nIn particular, let-expressions can be unfolded by making Let_def a simplification\nrule *)\n  \n  (* exercise 2.10 *) \ndatatype tree0 = Leaf | Node tree0 tree0\n  \nfun nodes :: \"tree0 \\<Rightarrow> nat\" where\n  \"nodes Leaf = Suc 0\"|\n  \"nodes (Node l r) = Suc(nodes l + nodes r)\"\n  \nvalue \"nodes Leaf\"\nvalue \"nodes (Node Leaf Leaf)\"\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 1 (Node Leaf Leaf))\" (* x*2+1 where x=3, is 7 *)\nvalue \"nodes (explode 2 (Node Leaf Leaf))\" (* do it twice where x=3, is 15 *)\n  \nvalue \"nodes (explode 1 (Leaf))\" (* x*2+1 where x=1, is 3 *)\nvalue \"nodes (explode 2 (Leaf))\" (* do it twice where x=1, is 7 *)\n  \nvalue \"nodes (explode 1 (Node Leaf (Node Leaf Leaf)))\" (* go once where x=5, is 11 *)  \nvalue \"nodes (explode 2 (Node Leaf (Node Leaf Leaf)))\" (* go twice where x=5, is 23 *)  \n  \nvalue \"x*2+1 :: int\"  \nvalue \"(x*2+1)*2+1 :: int\"\n  \n  (* Find 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   *)\nlemma nodes_explode[simp]: \"nodes (explode n t) = (2^n) * (nodes t) + (2^n - 1)\"\n  \n  (* apply(induction n) *)\n  (* After simp_all, this goal remains:\n 1. \\<And>n. nodes (explode n t) = 2 ^ n + nodes t * 2 ^ n - Suc 0 \\<Longrightarrow>\n         nodes (explode n (Node t t)) = 2 * 2 ^ n + nodes t * (2 * 2 ^ n) - Suc 0 *)\n  \n  apply(induction n arbitrary: t)\n   apply(simp_all add: algebra_simps)\n  done\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 2/exercise 2.10.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392756357327, "lm_q2_score": 0.8397339736884711, "lm_q1q2_score": 0.7423578138262714}}
{"text": "(*<*)\ntheory simplification imports Main begin\n(*>*)\n\ntext{*\nOnce we have proved all the termination conditions, the \\isacommand{recdef} \nrecursion equations become simplification rules, just as with\n\\isacommand{primrec}. In most cases this works fine, but there is a subtle\nproblem that must be mentioned: simplification may not\nterminate because of automatic splitting of @{text \"if\"}.\n\\index{*if expressions!splitting of}\nLet us look at an example:\n*}\n\nconsts gcd :: \"nat\\<times>nat \\<Rightarrow> nat\"\nrecdef gcd \"measure (\\<lambda>(m,n).n)\"\n  \"gcd (m, n) = (if n=0 then m else gcd(n, m mod n))\"\n\ntext{*\\noindent\nAccording to the measure function, the second argument should decrease with\neach recursive call. The resulting termination condition\n@{term[display]\"n ~= (0::nat) ==> m mod n < n\"}\nis proved automatically because it is already present as a lemma in\nHOL\\@.  Thus the recursion equation becomes a simplification\nrule. Of course the equation is nonterminating if we are allowed to unfold\nthe recursive call inside the @{text else} branch, which is why programming\nlanguages and our simplifier don't do that. Unfortunately the simplifier does\nsomething else that leads to the same problem: it splits \neach @{text \"if\"}-expression unless its\ncondition simplifies to @{term True} or @{term False}.  For\nexample, simplification reduces\n@{term[display]\"gcd(m,n) = k\"}\nin one step to\n@{term[display]\"(if n=0 then m else gcd(n, m mod n)) = k\"}\nwhere the condition cannot be reduced further, and splitting leads to\n@{term[display]\"(n=0 --> m=k) & (n ~= 0 --> gcd(n, m mod n)=k)\"}\nSince the recursive call @{term\"gcd(n, m mod n)\"} is no longer protected by\nan @{text \"if\"}, it is unfolded again, which leads to an infinite chain of\nsimplification steps. Fortunately, this problem can be avoided in many\ndifferent ways.\n\nThe most radical solution is to disable the offending theorem\n@{thm[source]if_split},\nas shown in \\S\\ref{sec:AutoCaseSplits}.  However, we do not recommend this\napproach: you will often have to invoke the rule explicitly when\n@{text \"if\"} is involved.\n\nIf possible, the definition should be given by pattern matching on the left\nrather than @{text \"if\"} on the right. In the case of @{term gcd} the\nfollowing alternative definition suggests itself:\n*}\n\nconsts gcd1 :: \"nat\\<times>nat \\<Rightarrow> nat\"\nrecdef gcd1 \"measure (\\<lambda>(m,n).n)\"\n  \"gcd1 (m, 0) = m\"\n  \"gcd1 (m, n) = gcd1(n, m mod n)\"\n\n\ntext{*\\noindent\nThe order of equations is important: it hides the side condition\n@{prop\"n ~= (0::nat)\"}.  Unfortunately, in general the case distinction\nmay not be expressible by pattern matching.\n\nA simple alternative is to replace @{text \"if\"} by @{text case}, \nwhich is also available for @{typ bool} and is not split automatically:\n*}\n\nconsts gcd2 :: \"nat\\<times>nat \\<Rightarrow> nat\"\nrecdef gcd2 \"measure (\\<lambda>(m,n).n)\"\n  \"gcd2(m,n) = (case n=0 of True \\<Rightarrow> m | False \\<Rightarrow> gcd2(n,m mod n))\"\n\ntext{*\\noindent\nThis is probably the neatest solution next to pattern matching, and it is\nalways available.\n\nA final alternative is to replace the offending simplification rules by\nderived conditional ones. For @{term gcd} it means we have to prove\nthese lemmas:\n*}\n\n\n\nlemma [simp]: \"n \\<noteq> 0 \\<Longrightarrow> gcd(m, n) = gcd(n, m mod n)\"\napply(simp)\ndone\n\ntext{*\\noindent\nSimplification terminates for these proofs because the condition of the @{text\n\"if\"} simplifies to @{term True} or @{term False}.\nNow we can disable the original simplification rule:\n*}\n\ndeclare gcd.simps [simp del]\n\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/Recdef/simplification.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637505099168, "lm_q2_score": 0.8633916064586998, "lm_q1q2_score": 0.742226466567068}}
{"text": "(*  Title:      HOL/Library/Quotient_Type.thy\n    Author:     Markus Wenzel, TU Muenchen\n*)\n\nsection {* Quotient types *}\n\ntheory Quotient_Type\nimports Main\nbegin\n\ntext {*\n We introduce the notion of quotient types over equivalence relations\n via type classes.\n*}\n\nsubsection {* Equivalence relations and quotient types *}\n\ntext {*\n \\medskip Type class @{text equiv} models equivalence relations @{text\n \"\\<sim> :: 'a => 'a => bool\"}.\n*}\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  assumes equiv_trans [trans]: \"x \\<sim> y \\<Longrightarrow> y \\<sim> z \\<Longrightarrow> x \\<sim> z\"\n  assumes equiv_sym [sym]: \"x \\<sim> y \\<Longrightarrow> y \\<sim> x\"\n\nlemma equiv_not_sym [sym]: \"\\<not> (x \\<sim> y) ==> \\<not> (y \\<sim> (x::'a::equiv))\"\nproof -\n  assume \"\\<not> (x \\<sim> y)\" then show \"\\<not> (y \\<sim> x)\"\n    by (rule contrapos_nn) (rule equiv_sym)\nqed\n\nlemma not_equiv_trans1 [trans]: \"\\<not> (x \\<sim> y) ==> y \\<sim> z ==> \\<not> (x \\<sim> (z::'a::equiv))\"\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 `y \\<sim> z` have \"z \\<sim> y\" ..\n    finally have \"x \\<sim> y\" .\n    with `\\<not> (x \\<sim> y)` show False by contradiction\n  qed\nqed\n\nlemma not_equiv_trans2 [trans]: \"x \\<sim> y ==> \\<not> (y \\<sim> z) ==> \\<not> (x \\<sim> (z::'a::equiv))\"\nproof -\n  assume \"\\<not> (y \\<sim> z)\" then have \"\\<not> (z \\<sim> y)\" ..\n  also assume \"x \\<sim> y\" then have \"y \\<sim> x\" ..\n  finally have \"\\<not> (z \\<sim> x)\" . then show \"(\\<not> x \\<sim> z)\" ..\nqed\n\ntext {*\n \\medskip The quotient type @{text \"'a quot\"} consists of all\n \\emph{equivalence classes} over elements of the base type @{typ 'a}.\n*}\n\ndefinition \"quot = {{x. a \\<sim> x} | a::'a::eqv. True}\"\n\ntypedef '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]: \"R \\<in> quot ==> (!!a. R = {x. a \\<sim> x} ==> C) ==> C\"\n  unfolding quot_def by blast\n\ntext {*\n \\medskip Abstracted equivalence classes are the canonical\n representation of elements of a quotient type.\n*}\n\ndefinition\n  \"class\" :: \"'a::equiv => 'a quot\"  (\"\\<lfloor>_\\<rfloor>\") where\n  \"\\<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 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 unfolding class_def .\nqed\n\nlemma quot_cases [cases type: quot]: \"(!!a. A = \\<lfloor>a\\<rfloor> ==> C) ==> C\"\n  using quot_exhaust by blast\n\n\nsubsection {* Equality on quotients *}\n\ntext {*\n Equality of canonical quotient elements coincides with the original\n relation.\n*}\n\ntheorem quot_equality [iff?]: \"(\\<lfloor>a\\<rfloor> = \\<lfloor>b\\<rfloor>) = (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 {* Picking representing elements *}\n\ndefinition\n  pick :: \"'a::equiv quot => 'a\" where\n  \"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\" .. 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 {*\n \\medskip The following rules support canonical function definitions\n on quotient types (with up to two arguments).  Note that the\n stripped-down version without additional conditions is sufficient\n most of the time.\n*}\n\ntheorem quot_cond_function:\n  assumes eq: \"!!X Y. P X Y ==> f X Y == g (pick X) (pick Y)\"\n    and cong: \"!!x x' y y'. \\<lfloor>x\\<rfloor> = \\<lfloor>x'\\<rfloor> ==> \\<lfloor>y\\<rfloor> = \\<lfloor>y'\\<rfloor>\n      ==> P \\<lfloor>x\\<rfloor> \\<lfloor>y\\<rfloor> ==> P \\<lfloor>x'\\<rfloor> \\<lfloor>y'\\<rfloor> ==> 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 \"!!X Y. f X Y == g (pick X) (pick Y)\"\n    and \"!!x x' y y'. \\<lfloor>x\\<rfloor> = \\<lfloor>x'\\<rfloor> ==> \\<lfloor>y\\<rfloor> = \\<lfloor>y'\\<rfloor> ==> 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  \"(!!X Y. f X Y == g (pick X) (pick Y)) ==>\n    (!!x x' y y'. x \\<sim> x' ==> y \\<sim> y' ==> g x y = g x' y') ==>\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": "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/Quotient_Type.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681158979307, "lm_q2_score": 0.8652240912652671, "lm_q1q2_score": 0.7421616385941074}}
{"text": "(*\n  File:    Harmonic_Numbers_Are_Not_Integers.thy \n  Author:  Jose Manuel Rodriguez Caballero, University of Tartu\n*)\nsection \\<open>Harmonic numbers are not integers, except for the trivial case of 1\\<close>\ntheory Harmonic_Numbers_Are_Not_Integers\n\nimports \n  Complex_Main \n  Pnorm\nbegin\n\ntext \\<open>\n In 1915, L. Theisinger ~\\cite{theisinger1915bemerkung} proved that, except for the trivial \n case of 1, the harmonic numbers are not integers. In 1918, \n J. K{\\\"u}rsch{\\'a}k  ~\\cite{kurschak1918harmonic} provided a sufficient condition for the \n difference between two harmonic numbers not to be an integer. We formalize these result as theorems\n @{text Taeisinger} and @{text Kurschak}, respectively. These results will be deduced from the \n computation of the 2-adic norm of harmonic numbers (lemma @{text harmonic_numbers_2norm}).\n\\<close>\n\nsubsection \\<open>Main definition\\<close>\n\n\ntext \\<open>\n We start by defining the harmonic numbers.\n\\<close>\n\nfun harmonic :: \\<open>nat \\<Rightarrow> rat\\<close> where\n  \\<open>harmonic 0 = 0\\<close> |\n  \\<open>harmonic (Suc n) = harmonic n + Fract 1 (Suc n)\\<close>\n\nlemma harmonic_explicit:\n  \\<open>harmonic n = (\\<Sum>k = 1..n. (Fract 1 (of_nat k)))\\<close>\nproof(induction n)\n  case 0\n  thus ?case\n    by simp \nnext\n  case (Suc n)\n  thus ?case\n    by simp \nqed\n\nlemma harmonic_diff_explicit:\n  \\<open>n \\<ge> m+1 \\<Longrightarrow> harmonic n - harmonic m = (\\<Sum>k = m+1..n. (Fract 1 (of_nat k)))\\<close>\nproof-\n  assume \\<open>n \\<ge> m+1\\<close>\n  then obtain k::nat where \\<open>n = m + 1 + k\\<close>\n    using le_Suc_ex \n    by blast    \n  show ?thesis\n  proof -\n    have \"\\<forall>n na f nb. \\<not> (n::nat) \\<le> na + 1 \\<or> sum f {n..na + nb} = (sum f {n..na}::rat) + sum f {na + 1..na + nb}\"\n      by (meson sum.ub_add_nat)\n    then show ?thesis\n      by (metis (no_types) \\<open>n = m + 1 + k\\<close> add_diff_cancel_left' harmonic_explicit le_add2 linordered_field_class.sign_simps(1))\n  qed \nqed\n\nsubsection \\<open>Auxiliary result\\<close>\n\nlemma sum_last:\n  fixes n::nat and a::\\<open>nat \\<Rightarrow> real\\<close>\n  assumes \\<open>n \\<ge> 2\\<close>\n  shows \\<open>(\\<Sum>k = 1..n - 1. (a k)) + (a n) = (\\<Sum>k = 1..n. (a k))\\<close>\n  using \\<open>n \\<ge> 2\\<close>\n  apply auto\n  by (smt Suc_leD le_add_diff_inverse numeral_1_eq_Suc_0 numeral_2_eq_2 numeral_One plus_1_eq_Suc sum.nat_ivl_Suc')\n\nlemma harmonic_numbers_2norm:\n  fixes n :: nat\n  assumes \\<open>n \\<ge> 1\\<close>\n  shows \\<open>pnorm 2 (harmonic n) = 2^(nat(\\<lfloor>log 2 n\\<rfloor>))\\<close>\nproof(cases \\<open>n = 1\\<close>)\n  case True\n  have \\<open>prime (2::nat)\\<close>\n    by simp\n  hence \\<open>harmonic (1::nat) = 1\\<close>\n    by (simp add: One_rat_def)\n  hence \\<open>pnorm 2 (harmonic (1::nat)) = pnorm 2 1\\<close>\n    by simp\n  also have \\<open>\\<dots> = 1\\<close>\n    by (simp add: pnorm_1)\n  also have \\<open>\\<dots> = 2^(nat(\\<lfloor>log 2 1\\<rfloor>))\\<close>\n  proof-\n    have \\<open>log 2 1 = 0\\<close>\n      by simp\n    hence \\<open>\\<lfloor>log 2 1\\<rfloor> = 0\\<close>\n      by simp      \n    thus ?thesis\n      by auto\n  qed\n  finally show ?thesis\n    using \\<open>n = 1\\<close>\n    by auto\nnext\n  case False\n  hence \\<open>n \\<ge> 2\\<close>\n    using \\<open>n \\<ge> 1\\<close>\n    by auto\n  define l where \\<open>l = nat(\\<lfloor>log 2 n\\<rfloor>)\\<close>\n  define H where \\<open>H = (\\<Sum>k = 1..n. (Fract 1 (of_nat k)))\\<close>\n  have \\<open>prime (2::nat)\\<close>\n    by simp\n  have \\<open>l \\<ge> 1\\<close>\n  proof-\n    have \\<open>log 2 n \\<ge> 1\\<close>\n      using \\<open>n \\<ge> 2\\<close>\n      by auto\n    hence \\<open>\\<lfloor>log 2 n\\<rfloor> \\<ge> 1\\<close>\n      by simp\n    thus ?thesis \n      using \\<open>l = nat(\\<lfloor>log 2 n\\<rfloor>)\\<close> \\<open>1 \\<le> \\<lfloor>log 2 (real n)\\<rfloor>\\<close> \\<open>l = nat \\<lfloor>log 2 (real n)\\<rfloor>\\<close> nat_mono \n      by presburger            \n  qed\n  hence \\<open>(2::nat)^l \\<ge> 2\\<close>\n  proof -\n    have \"(2::nat) ^ 1 \\<le> 2 ^ l\"\n      by (metis \\<open>1 \\<le> l\\<close> one_le_numeral power_increasing)\n    then show ?thesis\n      by (metis semiring_normalization_rules(33))\n  qed\n  have \\<open>pnorm 2 ((2^l) * H) = 1\\<close>\n  proof-\n    define pre_H where \\<open>pre_H = (\\<Sum>k = 1..(2^l-1). (Fract 1 (of_nat k)))\\<close>\n    define post_H where \\<open>post_H = (\\<Sum>k = (2^l+1)..n. (Fract 1 (of_nat k)))\\<close>\n    have \\<open>H = pre_H + (Fract 1 (of_nat (2^l))) + post_H\\<close>\n    proof-\n      have \\<open>pre_H + (Fract 1 (of_nat (2^l))) = (\\<Sum>k = 1..(2^l-1). (Fract 1 (of_nat k))) \n                  + (Fract 1 (of_nat (2^l)))\\<close>\n        unfolding pre_H_def\n        by auto\n      also have \\<open>\\<dots> = (\\<Sum>k = 1..2^l. (Fract 1 (of_nat k)))\\<close>\n      proof-\n        have \\<open>(\\<Sum>k = 1..2 ^ l - 1. real_of_rat (Fract 1 (int k))) \n                + real_of_rat (Fract 1 (int (2 ^ l))) \n                = (\\<Sum>k = 1..2 ^ l. real_of_rat (Fract 1 (int k)))\\<close>\n          using sum_last[where n = \\<open>2^l\\<close> and a = \\<open>(\\<lambda> k. of_rat (Fract 1 (of_nat k)))\\<close>]\n            \\<open>(2::nat)^l \\<ge> 2\\<close>\n          by auto\n        moreover have \\<open>(\\<Sum>k = 1..2 ^ l - 1. real_of_rat (Fract 1 (int k))) \n                + real_of_rat (Fract 1 (int (2 ^ l)))\n                = real_of_rat ((\\<Sum>k = 1..2 ^ l - 1. (Fract 1 (int k))) \n                +  (Fract 1 (int (2 ^ l))))\\<close>\n          by (simp add: of_rat_add of_rat_sum)\n        moreover have \\<open>(\\<Sum>k = 1..2 ^ l. real_of_rat (Fract 1 (int k)))\n                      = real_of_rat (\\<Sum>k = 1..2 ^ l. (Fract 1 (int k)))\\<close>\n          by (simp add: of_rat_sum)\n        ultimately have \\<open>real_of_rat ((\\<Sum>k = 1..2 ^ l - 1. (Fract 1 (int k))) \n                +  (Fract 1 (int (2 ^ l)))) = real_of_rat (\\<Sum>k = 1..2 ^ l. (Fract 1 (int k)))\\<close>\n          by simp\n        thus ?thesis\n          by simp\n      qed\n      finally have \\<open>pre_H + Fract 1 (int (2 ^ l)) =\n                  (\\<Sum>k = 1..2 ^ l. Fract 1 (int k))\\<close>\n        by blast\n      moreover have \\<open>(\\<Sum>k = 1..2 ^ l. Fract 1 (int k)) + post_H = H\\<close>\n      proof-\n        have \\<open>(\\<Sum>k = 1..2 ^ l. Fract 1 (int k)) + post_H\n              = (\\<Sum>k = 1..2 ^ l. Fract 1 (int k)) +\n                (\\<Sum>k = 2 ^ l + 1..n. Fract 1 (int k))\\<close>\n          unfolding post_H_def\n          by blast\n        also have \\<open>\\<dots>  = (\\<Sum>k = 1..n. Fract 1 (int k))\\<close>\n        proof-\n          have \\<open>2 ^ l \\<le> n\\<close>\n          proof-\n            have \\<open>2 ^ l =  2 ^ nat \\<lfloor>log 2 (real n)\\<rfloor>\\<close>\n              unfolding l_def\n              by simp\n            also have \\<open>\\<dots> =  2 powr (nat \\<lfloor>log 2 (real n)\\<rfloor>)\\<close>\n              by (simp add: powr_realpow)              \n            also have \\<open>\\<dots> \\<le>  2 powr (log 2 (real n))\\<close>\n            proof-\n              have \\<open>\\<lfloor>log 2 (real n)\\<rfloor> \\<le> log 2 (real n)\\<close>\n                by simp\n              moreover have \\<open>(2::real) > 1\\<close>\n                by simp\n              ultimately show ?thesis \n                using Transcendental.powr_le_cancel_iff[where x = 2 \n                    and a = \"\\<lfloor>log 2 (real n)\\<rfloor>\" and b = \"log 2 (real n)\"]\n                using assms \n                by auto\n            qed\n            also have \\<open>\\<dots> = n\\<close>\n            proof-\n              have \\<open>(2::real) > 1\\<close>\n                by simp                \n              moreover have \\<open>n > 0\\<close>\n                using \\<open>n \\<ge> 2\\<close>\n                by auto\n              ultimately show ?thesis\n                by simp\n            qed\n            finally show ?thesis \n              by simp\n          qed\n          thus ?thesis\n            by (metis le_add2 le_add_diff_inverse sum.ub_add_nat)\n        qed\n        finally have \\<open>(\\<Sum>k = 1..2 ^ l. Fract 1 (int k)) + post_H = (\\<Sum>k = 1..n. Fract 1 (int k))\\<close>\n          by blast\n        thus ?thesis\n          unfolding pre_H_def H_def\n          by blast\n      qed\n      ultimately show ?thesis\n        by simp\n    qed\n    moreover have \\<open>pnorm 2 ((2^l) * (Fract 1 (of_nat (2^l)))) = 1\\<close>\n    proof-\n      have \\<open>(2::nat)^l \\<noteq> 0\\<close>\n        by auto\n      hence \\<open>((2::nat)^l) * (Fract 1 (of_nat ((2::nat)^l))) = 1\\<close>\n      proof -\n        have \"int (2 ^ l) \\<noteq> 0\"\n          using \\<open>2 ^ l \\<noteq> 0\\<close> by linarith\n        hence \"1 = Fract (int (2 ^ l) * 1) (int (2 ^ l) * 1)\"\n          by (metis (no_types) One_rat_def mult_rat_cancel)\n        thus ?thesis\n          by (metis (full_types) Fract_of_nat_eq mult_rat of_rat_1 of_rat_mult of_rat_of_nat_eq semiring_normalization_rules(7))\n      qed        \n      hence \\<open>pnorm 2 (((2::rat)^l) * (Fract 1 (of_nat ((2::nat)^l)))) = pnorm 2 1\\<close>\n        by (metis (mono_tags, lifting) of_nat_numeral of_nat_power of_rat_1 of_rat_eq_iff \n            of_rat_mult of_rat_of_nat_eq)\n      also have \\<open>\\<dots> = 1\\<close>\n        using pnorm_1\n        by blast\n      finally show ?thesis \n        by blast\n    qed\n    moreover have \\<open>pnorm 2 ((2^l) * pre_H) < 1\\<close>\n    proof-\n      have \\<open>(2^l) * pre_H = (\\<Sum>k = 1..2 ^ l - 1. (2^l) * (Fract 1 (int k)))\\<close>\n        unfolding pre_H_def\n        using Groups_Big.semiring_0_class.sum_distrib_left[where r = \\<open>2^l\\<close> \n            and f = \\<open>(\\<lambda> k. Fract 1 (int k))\\<close> and A = \\<open>{1..(2^l - 1)}\\<close>]\n        by blast\n      also have \\<open>\\<dots> = (\\<Sum>k = 1..2 ^ l - 1. (Fract (2^l) (int k)))\\<close>\n        by (metis Fract_of_nat_eq mult.left_neutral mult.right_neutral mult_rat of_nat_numeral \n            of_nat_power)\n      finally have \\<open>2 ^ l * pre_H =\n              (\\<Sum>k = 1..2 ^ l - 1. Fract (2 ^ l) (int k))\\<close>\n        by blast\n      hence \\<open>pnorm 2 (2 ^ l * pre_H) =\n              pnorm 2 (\\<Sum>k = 1..2 ^ l - 1. Fract (2 ^ l) (int k))\\<close>\n        by simp\n      also have \\<open>\\<dots> \\<le>\n              Max ((\\<lambda> k. pnorm 2 (Fract (2 ^ l) (int k)))`{1..2^l-1})\\<close>\n      proof-\n        have \\<open>pnorm 2 (\\<Sum>k = 1..2 ^ l - 1. Fract (2 ^ l) (int k))\n           = pnorm 2 (sum (\\<lambda> k. Fract (2 ^ l) (int k)) {1..(2::nat)^l-1})\\<close>\n          by blast\n        also have \\<open>\\<dots> \\<le> Max ((\\<lambda> k. pnorm 2 (Fract (2 ^ l) (int k)))`{1..2^l-1})\\<close>\n          using \\<open>prime 2\\<close>  pnorm_ultrametric_sum[where p = 2 and A = \\<open>{1..2^l-1}\\<close> \n              and x = \\<open>(\\<lambda> k. (Fract (2 ^ l) (int k)))\\<close>]\n          by (metis Nat.le_diff_conv2 \\<open>2 \\<le> 2 ^ l\\<close> atLeastatMost_empty_iff2 finite_atLeastAtMost \n              nat_1_add_1 one_le_power prime_ge_1_nat)\n        finally show ?thesis\n          using \\<open>pnorm 2 (\\<Sum>k = 1..2 ^ l - 1. Fract (2 ^ l) (int k)) \\<le> (MAX k\\<in>{1..2 ^ l - 1}. \n              pnorm 2 (Fract (2 ^ l) (int k)))\\<close> \n          by blast\n      qed\n      also have \\<open>\\<dots> < 1\\<close>\n      proof-\n        have \\<open>finite ((\\<lambda> k. pnorm 2 (Fract (2 ^ l) (int k)))`{1..2^l-1})\\<close>\n          by blast          \n        moreover have \\<open>((\\<lambda> k. pnorm 2 (Fract (2 ^ l) (int k)))`{1..2^l-1}) \\<noteq> {}\\<close>\n        proof-\n          have \\<open>(1::nat) \\<le> (2::nat)^l-1\\<close>\n            using \\<open>(2::nat)^l \\<ge> 2\\<close>\n            by auto\n          hence \\<open>{(1::nat)..(2::nat)^l-1} \\<noteq> {}\\<close>\n            using Set_Interval.order_class.atLeastatMost_empty_iff2[where a = \"1::nat\" \n                and b = \"(2::nat)^l - 1\"]\n            by auto\n          thus ?thesis\n            by blast\n        qed\n        moreover have \\<open>x \\<in> ((\\<lambda> k. pnorm 2 (Fract (2 ^ l) (int k)))`{1..2^l-1}) \\<Longrightarrow> x < 1\\<close>\n          for x\n        proof-\n          assume \\<open>x \\<in> ((\\<lambda> k. pnorm 2 (Fract (2 ^ l) (int k)))`{1..2^l-1})\\<close>\n          then obtain k where \\<open>x = pnorm 2 (Fract (2 ^ l) (int k))\\<close> and \\<open>k \\<in> {1..2^l-1}\\<close>\n            by blast\n          have \\<open>pnorm 2 (Fract (2 ^ l) (int k)) < 1\\<close>\n          proof-\n            have \\<open>Fract (2 ^ l) (int k) = (2 ^ l)*(Fract 1 (int k))\\<close>\n              by (metis (no_types) Fract_of_nat_eq mult_numeral_1 mult_of_nat_commute mult_rat \n                  numeral_One of_nat_numeral of_nat_power)              \n            hence \\<open>pnorm 2 (Fract (2 ^ l) (int k)) = pnorm 2 ((2 ^ l)*(Fract 1 (int k)))\\<close>\n              by simp\n            also have \\<open>\\<dots> < 1\\<close>\n            proof-\n              have \\<open>pnorm 2 ((2::rat)^l) = 1/(2::nat)^l\\<close>\n                using  \\<open>prime (2::nat)\\<close> pnorm_primepow[where p = \"(2::nat)\"]\n                by auto\n              moreover have \\<open>pnorm 2 (Fract 1 k) < (2::nat)^l\\<close>\n              proof-\n                have \\<open>2 powr (- pval 2 (Fract 1 k)) < (2::nat)^l\\<close>\n                proof-\n                  have \\<open>pval 2 (Fract k 1) < l\\<close>\n                  proof-\n                    have \\<open>pval 2 (Fract k 1) = multiplicity (2::int) k\\<close>\n                      using \\<open>prime 2\\<close>  pval_integer[where p = 2 and k = k]\n                      by auto\n                    also have \\<open>\\<dots> < l\\<close>\n                    proof(rule classical)\n                      assume \\<open>\\<not>(multiplicity 2 (int k) < int l)\\<close>\n                      hence \\<open>multiplicity 2 (int k) \\<ge> int l\\<close>\n                        by simp\n                      hence \\<open>((2::nat)^l) dvd k\\<close>\n                        by (metis (full_types) int_dvd_int_iff multiplicity_dvd' of_nat_numeral\n                            of_nat_power zle_int)\n                      hence \\<open>(2::nat)^l \\<le> k\\<close>\n                        using \\<open>k \\<in> {1..2 ^ l - 1}\\<close> dvd_nat_bounds\n                        by auto\n                      moreover have \\<open>k < (2::nat)^l\\<close>\n                        using  \\<open>k\\<in>{1..(2::nat)^l - 1}\\<close>\n                        by auto                        \n                      ultimately show ?thesis\n                        by linarith \n                    qed\n                    finally show ?thesis\n                      by blast\n                  qed\n                  hence \\<open>- pval 2 (Fract 1 k) < l\\<close>\n                    using \\<open>prime 2\\<close> pval_inverse[where p = \"2\" and x = \\<open>Fract 1 k\\<close>] \n                      Fract_of_int_quotient \n                    by auto\n                  hence \\<open>2 powr (- pval 2 (Fract 1 k)) < 2 powr l\\<close>\n                    by auto\n                  also have \\<open>\\<dots> = (2::nat)^l\\<close>\n                  proof -\n                    have f1: \"\\<not> 2 \\<le> (1::real)\"\n                      by auto\n                    have f2: \"\\<forall>x1. ((1::real) < x1) = (\\<not> x1 \\<le> 1)\"\n                      by force\n                    have \"real (2 ^ l) = 2 ^ l\"\n                      by simp\n                    hence \"real l = log 2 (real (2 ^ l))\"\n                      using f2 f1 by (meson log_of_power_eq)\n                    thus ?thesis\n                      by simp\n                  qed\n                  finally show ?thesis \n                    by blast\n                qed\n                moreover have \\<open>pnorm 2 (Fract 1 k) = 2 powr (- pval 2 (Fract 1 k))\\<close>\n                proof-\n                  have \\<open>k \\<noteq> 0\\<close>\n                    using \\<open>k\\<in>{1..2^l - 1}\\<close>\n                    by simp\n                  hence \\<open>Fract 1 k \\<noteq> 0\\<close>\n                    by (smt Fract_le_zero_iff le_numeral_extra(3) of_nat_le_0_iff)\n                  thus \\<open>pnorm 2 (Fract 1 k) = 2 powr (- pval 2 (Fract 1 k))\\<close>\n                    using \\<open>prime 2\\<close>\n                    by (simp add: pnorm_simplified)\n                qed\n                ultimately show ?thesis\n                  by simp\n              qed\n              moreover have \\<open>pnorm 2 ((2::rat)^l) > 0\\<close>\n              proof-\n                have \\<open>(2::rat)^l \\<noteq> 0\\<close>\n                  by simp                  \n                moreover have \\<open>pnorm 2 ((2::rat)^l) \\<ge> 0\\<close>\n                  using \\<open>prime (2::nat)\\<close> pnorm_geq_zero\n                  by simp                  \n                ultimately show ?thesis\n                  using pnorm_eq_zero \\<open>prime (2::nat)\\<close>\n                  by (simp add: less_eq_real_def)                  \n              qed\n              moreover have \\<open>pnorm 2 (Fract 1 k) > 0\\<close>\n              proof-\n                have \\<open>Fract 1 k \\<noteq> 0\\<close>\n                  using \\<open>k \\<in> {1..2^l-1}\\<close>\n                  by (metis Fract_le_zero_iff atLeastAtMost_iff int.nat_pow_one int.zero_not_one int_ops(1) less_le_not_le less_one linorder_neqE_nat nat_int_comparison(2) not_less0 order_refl power2_less_eq_zero_iff)\n                moreover have \\<open>pnorm 2 (Fract 1 k) \\<ge> 0\\<close>\n                  using \\<open>prime (2::nat)\\<close> pnorm_geq_zero\n                  by blast\n                ultimately show ?thesis\n                  using pnorm_eq_zero \\<open>prime (2::nat)\\<close>\n                  by (simp add: less_eq_real_def)                  \n              qed\n              ultimately have \\<open>(pnorm 2 ((2::rat)^l))*(pnorm 2 (Fract 1 k)) \n                  < (1/(2::nat)^l)*((2::nat)^l)\\<close>\n                by simp\n              also have \\<open>\\<dots> = 1\\<close>\n              proof-\n                have \\<open>(2::nat)^l \\<noteq> 0\\<close>\n                  by simp                  \n                thus ?thesis\n                  by simp \n              qed\n              finally have \\<open>(pnorm 2 ((2::rat)^l))*(pnorm 2 (Fract 1 k)) < 1\\<close>\n                by blast\n              moreover have \\<open>(pnorm 2 ((2::rat)^l))*(pnorm 2 (Fract 1 k)) \n                  = pnorm 2 (2 ^ l * Fract 1 (int k))\\<close>\n                using \\<open>prime 2\\<close>\n                by (simp add: pnorm_multiplicativity)\n              ultimately show ?thesis\n                by simp\n            qed\n            finally show \\<open>pnorm 2 (Fract (2 ^ l) (int k)) < 1\\<close>\n              by blast\n          qed\n          thus ?thesis\n            using \\<open>x = pnorm 2 (Fract (2 ^ l) (int k))\\<close>\n            by blast\n        qed\n        ultimately show ?thesis \n          using Lattices_Big.linorder_class.Max_less_iff\n            [where A = \"((\\<lambda> k. pnorm 2 (Fract (2 ^ l) (int k)))`{1..2^l-1})\"]\n          by blast\n      qed\n      finally show \\<open>pnorm 2 (2 ^ l * pre_H) < 1\\<close>\n        by blast\n    qed\n    ultimately have \\<open>pnorm 2 ((2^l) * (Fract 1 (of_nat (2^l))) + (2^l) * pre_H) = 1\\<close>\n      using pnorm_unit_ball[where p = 2 and x = \"(2^l) *  (Fract 1 (of_nat (2^l)))\" and y = \"(2^l) * pre_H\"]\n      by simp\n    moreover have \\<open>pnorm 2 ((2^l) * post_H) < 1\\<close>\n    proof(cases \\<open>2^l + 1 \\<le> n\\<close>)\n      case True\n      have \\<open>pnorm 2 ((2^l) * post_H) = pnorm 2 (\\<Sum>k = 2 ^ l + 1..n.  (2 ^ l)*(Fract 1 k))\\<close>\n      proof-\n        have \\<open>(2^l) * post_H = (\\<Sum>k = 2 ^ l+1..n. (2 ^ l)*(Fract 1 k))\\<close>\n          unfolding post_H_def\n          using Groups_Big.semiring_0_class.sum_distrib_left[where r = \\<open>2^l\\<close> \n              and f = \\<open>(\\<lambda> k. Fract 1 k)\\<close> and A = \\<open>{2 ^ l+1..n}\\<close>]\n          by auto\n        thus ?thesis\n          by simp\n      qed\n      also have \\<open>\\<dots>\n           = pnorm 2 (sum (\\<lambda> k. (2 ^ l)*(Fract 1 k)) {2 ^ l + 1..n})\\<close>\n        by blast\n      also have \\<open>\\<dots>\n           \\<le> Max ((\\<lambda> k. pnorm 2 ((2 ^ l)*(Fract 1 k))) ` {2 ^ l + 1..n})\\<close>\n      proof-\n        have \\<open>finite {2 ^ l + 1..n}\\<close>\n          by simp          \n        moreover have \\<open>{2 ^ l + 1..n} \\<noteq> {}\\<close>\n          using True \n          by auto          \n        ultimately show ?thesis \n          using \\<open>prime 2\\<close>  pnorm_ultrametric_sum[where p = 2 and A = \\<open>{2 ^ l + 1..n}\\<close> \n              and x = \\<open>(\\<lambda> k. (2 ^ l)*(Fract 1 k))\\<close>]\n          by auto\n      qed\n      finally have \\<open>pnorm 2 ((2^l) * post_H) \\<le> \n          Max ((\\<lambda> k. pnorm 2 ((2 ^ l)*(Fract 1 k))) ` {2 ^ l + 1..n})\\<close>\n        using \\<open>pnorm 2 (2 ^ l * post_H) = pnorm 2 (\\<Sum>k = 2 ^ l + 1..n. 2 ^ l * Fract 1 (int k))\\<close> \\<open>pnorm 2 (\\<Sum>k = 2 ^ l + 1..n. 2 ^ l * Fract 1 (int k)) \\<le> (MAX k\\<in>{2 ^ l + 1..n}. pnorm 2 (2 ^ l * Fract 1 (int k)))\\<close> \n        by linarith\n      moreover have \\<open>((\\<lambda> k. pnorm 2 ((2 ^ l)*(Fract 1 k))) ` {2 ^ l + 1..n}) \\<noteq> {}\\<close>\n        using True \n        by auto        \n      moreover have \\<open>finite ((\\<lambda> k. pnorm 2 ((2 ^ l)*(Fract 1 k))) ` {2 ^ l + 1..n})\\<close>\n        by blast        \n      moreover have \\<open>x \\<in> (\\<lambda> k. pnorm 2 ((2 ^ l)*(Fract 1 k))) ` {2 ^ l + 1..n} \\<Longrightarrow> x < 1\\<close>\n        for x\n      proof-\n        assume \\<open>x \\<in> (\\<lambda> k. pnorm 2 ((2 ^ l)*(Fract 1 k))) ` {2 ^ l + 1..n}\\<close>\n        then obtain t where \\<open>t \\<in> {2 ^ l + 1..n}\\<close> and \\<open>x = pnorm 2 ((2 ^ l)*(Fract 1 t))\\<close>\n          by auto\n        have  \\<open>x = (pnorm 2 (2 ^ l)) * (pnorm 2 (Fract 1 t))\\<close>\n          using \\<open>prime 2\\<close> \\<open>x = pnorm 2 ((2 ^ l)*(Fract 1 t))\\<close> pnorm_multiplicativity\n          by auto\n        moreover have \\<open>pnorm 2 (2 ^ l) = 1/(2^l)\\<close>\n          using \\<open>prime 2\\<close> pval_primepow[where p = \"2::nat\"]\n          by (metis of_int_numeral of_nat_numeral pnorm_primepow)          \n        moreover have \\<open>pnorm 2 (Fract 1 t) < 2^l\\<close>\n        proof(rule classical)\n          assume \\<open>\\<not> (pnorm 2 (Fract 1 t) < 2^l)\\<close>\n          hence \\<open>pnorm 2 (Fract 1 t) \\<ge> 2^l\\<close>\n            by auto\n          moreover have \\<open>2 powr l = 2^l\\<close>\n            using powr_realpow \n            by auto            \n          ultimately have \\<open>pnorm 2 (Fract 1 t) \\<ge> 2 powr l\\<close>\n            by auto\n          moreover have \\<open>pnorm 2 (Fract 1 t) = 2 powr (-pval 2 (Fract 1 t))\\<close>\n          proof-\n            have \\<open>t \\<noteq> 0\\<close>\n              using \\<open>t \\<in> {2^l + 1 .. n}\\<close>\n              by simp\n            hence \\<open>Fract 1 t \\<noteq> 0\\<close>\n            proof -\n              have \"\\<not> int t \\<le> 0\"\n                by (metis \\<open>t \\<noteq> 0\\<close> of_nat_le_0_iff)\n              hence \"\\<not> Fract 1 (int t) \\<le> 0\"\n                by (simp add: Fract_le_zero_iff)\n              thus ?thesis\n                by linarith\n            qed              \n            thus ?thesis \n              using pnorm_simplified\n              by simp\n          qed\n          ultimately have \\<open>-pval 2 (Fract 1 t) \\<ge> l\\<close>\n            by simp            \n          hence \\<open>-(multiplicity 2 (fst (quotient_of (Fract 1 t))))\n               + (multiplicity 2 (snd (quotient_of (Fract 1 t))))\n                     \\<ge> l\\<close>\n            unfolding pval_def \n            by auto\n          have \\<open>quotient_of (Fract (1::int) t) = (1, t)\\<close>\n          proof-\n            have \\<open>coprime (1::int) t\\<close>\n              by simp              \n            moreover have \\<open>t > 0\\<close>\n              using \\<open>t \\<in> {2^l + 1 .. n}\\<close>\n              by simp\n            ultimately show ?thesis\n              by (simp add: quotient_of_Fract)              \n          qed\n          hence \\<open>fst (quotient_of (Fract 1 t)) = 1\\<close>\n            by simp\n          moreover have \\<open>snd (quotient_of (Fract 1 t)) = t\\<close>\n            using \\<open>quotient_of (Fract (1::int) t) = (1, t)\\<close>\n            by auto\n          ultimately have \\<open>- int(multiplicity (2::int) 1) + int(multiplicity (2::int) t) \\<ge> l\\<close>\n            using \\<open>-(multiplicity 2 (fst (quotient_of (Fract 1 t))))\n               + (multiplicity 2 (snd (quotient_of (Fract 1 t))))\n                     \\<ge> l\\<close>\n            by auto\n          moreover have \\<open>multiplicity (2::int) 1 = 0\\<close>\n            by simp\n          ultimately have \\<open>multiplicity (2::int) t \\<ge> l\\<close>\n            by auto\n          hence \\<open>2^l dvd t\\<close>\n            by (metis int_dvd_int_iff multiplicity_dvd' of_nat_numeral of_nat_power)\n          hence \\<open>\\<exists> k::nat. 2^l * k = t\\<close>\n            by auto\n          then obtain k::nat where \\<open>2^l * k = t\\<close>\n            by blast\n          have \\<open>k \\<ge> 2\\<close>\n          proof(rule classical)\n            assume \\<open>\\<not>(k \\<ge> 2)\\<close>\n            hence \\<open>k < 2\\<close>\n              by simp\n            moreover have \\<open>k \\<noteq> 0\\<close>\n            proof(rule classical)\n              assume \\<open>\\<not>(k \\<noteq> 0)\\<close>\n              hence \\<open>k = 0\\<close>\n                by simp\n              hence \\<open>t = 0\\<close>\n                using \\<open>2^l * k = t\\<close>\n                by auto\n              thus ?thesis\n                using \\<open>t \\<in> {2^l + 1 .. n}\\<close>\n                by auto\n            qed\n            moreover have \\<open>k \\<noteq> 1\\<close>\n            proof(rule classical)\n              assume \\<open>\\<not>(k \\<noteq> 1)\\<close>\n              hence \\<open>k = 1\\<close>\n                by simp\n              hence \\<open>t = 2^l\\<close>\n                using \\<open>2^l * k = t\\<close>\n                by auto\n              thus ?thesis\n                using \\<open>t \\<in> {2^l + 1 .. n}\\<close>\n                by auto\n            qed\n            ultimately show ?thesis\n              by auto\n          qed\n          hence \\<open>2^(Suc l) \\<le> t\\<close>\n            using \\<open>2 ^ l * k = t\\<close> \n            by auto\n          hence \\<open>2^(Suc l) \\<le> n\\<close>\n            using \\<open>t \\<in> {2^l + 1 .. n}\\<close>\n            by auto\n          moreover have \\<open>n < 2^(Suc l)\\<close>\n          proof -\n            have f1: \"\\<forall>n na. (n \\<le> na) = (int n + - 1 * int na \\<le> 0)\"\n              by auto\n            have f2: \"int (Suc (nat \\<lfloor>log 2 (real n)\\<rfloor>)) + - 1 * int (Suc l) \\<le> 0\"\n              by (simp add: l_def)\n            have f3: \"(- 1 * log 2 (real n) + real (Suc l) \\<le> 0) = (0 \\<le> log 2 (real n) + - 1 * real (Suc l))\"\n              by fastforce\n            have f4: \"real (Suc l) + - 1 * log 2 (real n) = - 1 * log 2 (real n) + real (Suc l)\"\n              by auto\n            have f5: \"\\<forall>n na. \\<not> 2 ^ n \\<le> na \\<or> real n + - 1 * log 2 (real na) \\<le> 0\"\n              by (simp add: le_log2_of_power)\n            have f6: \"\\<forall>x0 x1. (- 1 * int x0 + int (2 ^ x1) \\<le> 0) = (0 \\<le> int x0 + - 1 * int (2 ^ x1))\"\n              by auto\n            have f7: \"\\<forall>x0 x1. int (2 ^ x1) + - 1 * int x0 = - 1 * int x0 + int (2 ^ x1)\"\n              by auto\n            have \"\\<not> 0 \\<le> log 2 (real n) + - 1 * real (Suc l)\"\n              using f2 by linarith\n            then have \"\\<not> 0 \\<le> int n + - 1 * int (2 ^ Suc l)\"\n              using f7 f6 f5 f4 f3 f1 by (metis (no_types))\n            then show ?thesis\n              by linarith\n          qed                    \n          ultimately show ?thesis\n            by auto\n        qed\n        moreover have \\<open>pnorm 2 (2 ^ l) \\<ge> 0\\<close>\n          using \\<open>prime 2\\<close> pnorm_geq_zero \n          by blast\n        moreover have \\<open>pnorm 2 (Fract 1 t) \\<ge> 0\\<close>\n          using \\<open>prime 2\\<close> pnorm_geq_zero \n          by blast\n        ultimately show ?thesis \n          by simp\n      qed\n      ultimately show ?thesis\n        by (smt Max_in)\n    next\n      case False\n      hence \\<open>2 ^ l + 1 > n\\<close>\n        by simp\n      hence \\<open>{2 ^ l + 1..n} = {}\\<close>\n        by simp\n      hence \\<open>post_H = 0\\<close>\n        unfolding post_H_def\n        by simp        \n      hence \\<open>(2^l) * post_H = 0\\<close>\n        by (simp add: \\<open>post_H = 0\\<close>)        \n      thus ?thesis\n        unfolding pnorm_def\n        by auto\n    qed\n    ultimately have \\<open>pnorm 2 (((2^l) *  (Fract 1 (of_nat (2^l))) \n                                  + (2^l) * pre_H) + ((2^l) * post_H)) = 1\\<close>\n      using pnorm_unit_ball[where p = 2 and x = \"(2^l) *  (Fract 1 (of_nat (2^l))) + (2^l) * pre_H\" \n          and y = \"(2^l) * post_H\"]\n      by simp\n    thus ?thesis\n      by (simp add: \\<open>H = pre_H + Fract 1 (int (2 ^ l)) + post_H\\<close> semiring_normalization_rules(24) semiring_normalization_rules(34))      \n  qed\n  hence \\<open>(pnorm 2 (2^l)) * (pnorm 2 H) = 1\\<close>\n    using pnorm_multiplicativity\n    by auto\n  hence \\<open>(1/2^l) * (pnorm 2 H) = 1\\<close>\n  proof-\n    have \\<open>prime (2::nat)\\<close>\n      by simp\n    hence \\<open>pnorm 2 (2^l) = 1/2^l\\<close>\n      using pnorm_primepow[where p = 2 and l = \"l\"] \n      by simp\n    thus ?thesis\n      using \\<open>pnorm 2 (2 ^ l) * pnorm 2 H = 1\\<close> \n      by auto\n  qed\n  hence \\<open>pnorm 2 H = 2^l\\<close>\n    by simp\n  thus ?thesis\n    using H_def l_def harmonic_explicit[where n = n]\n    by simp   \nqed\n\n\nsubsection \\<open>Main results\\<close>\n\ntext\\<open>The following result is due to L. Taeisinger ~\\cite{theisinger1915bemerkung}.\\<close>\ntheorem Taeisinger:\n  fixes n :: nat\n  assumes \\<open>n \\<ge> 2\\<close>\n  shows \\<open>harmonic n \\<notin> \\<int>\\<close>\nproof-\n  have \\<open>pnorm 2 (\\<Sum>k = 1..n. (Fract 1 (of_nat k)) ) > 1\\<close>\n    using harmonic_numbers_2norm[where n = \"n\"] \\<open>n \\<ge> 2\\<close> harmonic_explicit \n    by auto    \n  thus ?thesis\n  proof -\n    have \"\\<not> pnorm 2 (\\<Sum>n = 1..n. Fract 1 (int n)) \\<le> 1\"\n      using \\<open>1 < pnorm 2 (\\<Sum>k = 1..n. Fract 1 (int k))\\<close> by linarith\n    then show ?thesis\n      by (metis (no_types) harmonic_explicit integers_pnorm_D two_is_prime_nat)\n  qed\nqed\n\ntext\\<open>The following result is due to J. K{\\\"u}rsch{\\'a}k  ~\\cite{kurschak1918harmonic}.\\<close>\ntheorem Kurschak:\n  fixes n m :: nat\n  assumes \\<open>m + 2 \\<le> n\\<close>\n  shows \\<open>harmonic n - harmonic m \\<notin> \\<int>\\<close>\nproof(cases \\<open>2*m \\<le> n\\<close>)\n  case True\n  show ?thesis\n  proof(cases \\<open>m = 0\\<close>)\n    case True\n    thus ?thesis\n      using Taeisinger assms \n      by auto \n  next\n    case False\n    hence \\<open>m \\<ge> 1\\<close>\n      by simp\n    have \\<open>n \\<ge> 2\\<close>\n      using \\<open>m+2 \\<le> n\\<close>\n      by auto\n    have \\<open>prime (2::nat)\\<close>\n      by auto\n    have \\<open>harmonic n = (harmonic n - harmonic m) + (harmonic m)\\<close>\n      by simp\n    hence \\<open>pnorm 2 (harmonic n) \\<le> max (pnorm 2 (harmonic n - harmonic m)) (pnorm 2 (harmonic m))\\<close>\n      using \\<open>prime 2\\<close> pnorm_ultrametric[where p = \"2::nat\" and x = \"harmonic n - harmonic m\" \n          and y = \"harmonic m\"]\n      by auto\n    moreover have \\<open>pnorm 2 (harmonic m) < pnorm 2 (harmonic n)\\<close>\n    proof-\n      have \\<open>pnorm 2 (harmonic m) =  2 ^ nat \\<lfloor>log 2 (real m)\\<rfloor>\\<close>\n        using harmonic_numbers_2norm[where n = \"n\"] \\<open>m \\<ge> 1\\<close>\n        by (meson \\<open>1 \\<le> m\\<close> harmonic_numbers_2norm)\n      moreover have \\<open>pnorm 2 (harmonic n) =  2 ^ nat \\<lfloor>log 2 (real n)\\<rfloor>\\<close>\n        using harmonic_numbers_2norm[where n = \"n\"] \\<open>2 \\<le> n\\<close> \n        by linarith\n      moreover have \\<open>(2::nat) ^ nat \\<lfloor>log 2 (real m)\\<rfloor> < (2::nat) ^ nat \\<lfloor>log 2 (real n)\\<rfloor>\\<close>\n      proof-\n        have \\<open>log 2 (real m) + 1 = log 2 (real m) + log 2 (2::real)\\<close>\n        proof-\n          have \\<open>log 2 (real 2) = 1\\<close>\n            by simp\n          thus ?thesis \n            by simp\n        qed\n        also have \\<open>\\<dots> = log 2 ((real m) * (2::real)) \\<close>\n        proof-\n          have \\<open>(2::real) > 0\\<close>\n            by simp\n          moreover have \\<open>(2::real) \\<noteq> 1\\<close>\n            by simp\n          moreover have \\<open>m > 0\\<close>\n            using False \n            by auto            \n          ultimately show ?thesis\n            using log_mult[where a = 2 and x = \"real m\" and y = \"2::real\"]\n            by simp\n        qed\n        also have \\<open>\\<dots> = log 2 (2*real m) \\<close>\n        proof-\n          have \\<open>(real m)*(2::real) = 2*m\\<close>\n            by auto\n          thus ?thesis\n            by (simp add: \\<open>real m * 2 = real (2 * m)\\<close>)             \n        qed\n        also have \\<open>\\<dots> \\<le> log 2 (real n)\\<close>\n          using \\<open>2*m \\<le> n\\<close>  \\<open>m \\<noteq> 0\\<close>\n          by auto\n        finally have \\<open>log 2 (real m) + 1 \\<le> log 2 (real n)\\<close>\n          by blast\n        hence \\<open>\\<lfloor>log 2 (real m)\\<rfloor> < \\<lfloor>log 2 (real n)\\<rfloor>\\<close>\n          by linarith          \n        moreover have \\<open>(2::nat) > 1\\<close>\n          by auto\n        ultimately show ?thesis\n          by (smt \\<open>1 \\<le> m\\<close> floor_less_zero log_less_zero_cancel_iff nat_mono_iff of_nat_1 \n              of_nat_mono power_strict_increasing)\n      qed\n      ultimately show ?thesis \n        by auto\n    qed\n    ultimately have \\<open>pnorm 2 (harmonic n) \\<le> pnorm 2 (harmonic n - harmonic m)\\<close>\n      by linarith\n    moreover have \\<open>1 < pnorm 2 (harmonic n)\\<close>\n      using harmonic_numbers_2norm[where n = \"n\"] \\<open>n \\<ge> 2\\<close>\n      by auto\n    ultimately have \\<open>1 < pnorm 2 (harmonic n - harmonic m) \\<close>\n      by auto\n    thus ?thesis\n      using integers_pnorm_D[where p = \"2::nat\" and x = \"harmonic n - harmonic m\"] \\<open>prime 2\\<close>\n      by auto      \n  qed\nnext\n  case False\n  have explicit: \\<open>harmonic n - harmonic m = (\\<Sum>k = m + 1..n. Fract 1 (int k))\\<close>\n    using \\<open>n \\<ge> m + 2\\<close> harmonic_diff_explicit[where m = m and n = n]\n    by linarith\n  have \\<open>harmonic n - harmonic m < 1\\<close>\n  proof-\n    have \\<open>(\\<Sum>k = m + 1..n. Fract 1 (int k)) < 1\\<close>\n    proof-\n      have \\<open>finite {m + 1..n}\\<close>\n        by simp\n      moreover have \\<open>{m + 1..n} \\<noteq> {}\\<close>\n        using \\<open>m+2 \\<le> n\\<close>\n        by simp\n      moreover have \\<open>k \\<in> {m + 1..n} \\<Longrightarrow> Fract 1 k \\<le> Fract 1 (m+1)\\<close>\n        for k\n      proof-\n        assume \\<open>k \\<in> {m + 1..n}\\<close>\n        have \\<open>k \\<ge> m+1\\<close>\n          using \\<open>k \\<in> {m + 1..n}\\<close>\n          by auto\n        thus ?thesis\n          by auto\n      qed\n      ultimately have \\<open>(\\<Sum>k = m + 1..n. Fract 1 k) \\<le> of_nat (card {m + 1..n})*Fract 1 (int (m + 1))\\<close>\n        using  Groups_Big.sum_bounded_above[where A = \"{m+1..n}\" and K = \"Fract 1 (m+1)\"\n            and f = \"\\<lambda> k. Fract 1 k\"]\n        by auto\n      also  have \\<open>\\<dots> \\<le> of_nat m*Fract 1 ((m + 1))\\<close>\n      proof-\n        have \\<open>card {m+1..n} \\<le> m\\<close>\n        proof-\n          have \\<open>card {m+1..n} = n - m\\<close>\n            by auto\n          thus ?thesis\n            using False\n            by simp\n        qed\n        moreover have \\<open>card  {m + 1..n} > 0\\<close>\n          using \\<open>{m + 1..n} \\<noteq> {}\\<close> card_gt_0_iff \n          by blast          \n        ultimately show ?thesis\n          by (smt add_is_0 less_eq_rat_def mult_mono of_nat_0_le_iff of_nat_le_0_iff of_nat_mono \n              zero_le_Fract_iff)\n      qed\n      also have \\<open>\\<dots> < 1\\<close>\n      proof -\n        have \"Fract (int m * 1) (int (1 + m)) < 1\"\n          by (simp add: Fract_less_one_iff)\n        then show ?thesis\n          by (metis (no_types) Fract_of_nat_eq add.commute mult.left_neutral mult_rat)\n      qed\n      finally show ?thesis\n        by blast\n    qed\n    thus ?thesis\n      using explicit \n      by simp\n  qed\n  moreover have \\<open>0 < harmonic n - harmonic m\\<close>\n  proof-\n    have \\<open>finite {m + 1..n}\\<close>\n      by simp\n    moreover have \\<open>{m + 1..n} \\<noteq> {}\\<close>\n      using \\<open>m+2 \\<le> n\\<close>\n      by simp\n    moreover have \\<open>k \\<in> {m + 1..n} \\<Longrightarrow> 0 < Fract 1 k\\<close>\n      for k\n    proof-\n      assume \\<open>k \\<in> {m + 1..n}\\<close>\n      hence \\<open>k \\<ge> 1\\<close>\n        by auto\n      thus ?thesis\n        by (simp add: zero_less_Fract_iff) \n    qed\n    ultimately have \\<open>0 < (\\<Sum>k = m + 1..n. Fract 1 k)\\<close>\n      using Groups_Big.ordered_comm_monoid_add_class.sum_pos[where I = \"{m+1..n}\" \n          and f = \"\\<lambda> k. Fract 1 k\"]\n      by blast\n    thus ?thesis\n      using explicit \n      by simp\n  qed\n  ultimately show ?thesis\n  proof -\n    have f1: \"sgn (harmonic n - harmonic m) = 1\"\n      by (metis \\<open>0 < harmonic n - harmonic m\\<close> sgn_pos)\n    have \"0 \\<le> harmonic n - harmonic m\"\n      by (metis \\<open>0 < harmonic n - harmonic m\\<close> less_eq_rat_def)\n    thus ?thesis\n      using f1 by (metis (no_types) Ints_0 \\<open>harmonic n - harmonic m < 1\\<close> eq_iff_diff_eq_0 frac_eq_0_iff frac_unique_iff sgn_if zero_neq_one)\n  qed    \nqed\n\nend\n\n", "meta": {"author": "josephcmac", "repo": "harmonic-numbers-are-not-integers", "sha": "d7efebc677af38b93add985fd6814e5a7edd2058", "save_path": "github-repos/isabelle/josephcmac-harmonic-numbers-are-not-integers", "path": "github-repos/isabelle/josephcmac-harmonic-numbers-are-not-integers/harmonic-numbers-are-not-integers-d7efebc677af38b93add985fd6814e5a7edd2058/Harmonic_Numbers_Are_Not_Integers.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8652240895276223, "lm_q2_score": 0.8577681031721325, "lm_q1q2_score": 0.7421616260929439}}
{"text": "(*\n    File:     Miscellaneous_Groups.thy\n    Author:   Joseph Thommes, TU M\u00fcnchen\n*)\nsection \\<open>Miscellaneous group facts\\<close>\n\ntheory Miscellaneous_Groups\n  imports Set_Multiplication\nbegin\n\ntext \\<open>As the name suggests, this section contains several smaller lemmas about groups.\\<close>\n\n(* Manuel Eberl *)\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\n(* Manuel Eberl *)\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 (in group) subgroup_card_dvd_group_ord:\n  assumes \"subgroup H G\"\n  shows \"card H dvd order G\"\n  using Coset.group.lagrange[of G H] assms group_axioms by (metis dvd_triv_right)\n\nlemma (in group) subgroup_card_eq_order:\n  assumes \"subgroup H G\"\n  shows \"card H = order (G\\<lparr>carrier := H\\<rparr>)\"\n  unfolding order_def by simp\n\nlemma (in group) finite_subgroup_card_neq_0:\n  assumes \"subgroup H G\" \"finite H\"\n  shows \"card H \\<noteq> 0\"\n  using subgroup_nonempty assms by auto\n\nlemma (in group) subgroup_order_dvd_group_order:\n  assumes \"subgroup H G\"\n  shows \"order (G\\<lparr>carrier := H\\<rparr>) dvd order G\"\n  by (metis subgroup_card_dvd_group_ord[of H] assms subgroup_card_eq_order)\n\nlemma (in group) sub_subgroup_dvd_card:\n  assumes \"subgroup H G\" \"subgroup J G\" \"J \\<subseteq> H\"\n  shows \"card J dvd card H\"\n  by (metis subgroup_incl[of J H] subgroup_card_eq_order[of H]\n            group.subgroup_card_dvd_group_ord[of \"(G\\<lparr>carrier := H\\<rparr>)\" J] assms\n            subgroup.subgroup_is_group[of H G] group_axioms)\n\nlemma (in group) inter_subgroup_dvd_card:\n  assumes \"subgroup H G\" \"subgroup J G\"\n  shows \"card (H \\<inter> J) dvd card H\"\n  using subgroups_Inter_pair[of H J] assms sub_subgroup_dvd_card[of H \"H \\<inter> J\"] by blast\n\nlemma (in group) subgroups_card_coprime_inter_card_one:\n  assumes \"subgroup H G\" \"subgroup J G\" \"coprime (card H) (card J)\"\n  shows \"card (H \\<inter> J) = 1\"\nproof -\n  from assms inter_subgroup_dvd_card have \"is_unit (card (H \\<inter> J))\" unfolding coprime_def\n    by (metis assms(3) coprime_common_divisor inf_commute)\n  then show ?thesis by simp\nqed\n\nlemma (in group) coset_neq_imp_empty_inter:\n  assumes \"subgroup H G\" \"a \\<in> carrier G\" \"b \\<in> carrier G\"\n  shows \"H #> a \\<noteq> H #> b \\<Longrightarrow> (H #> a) \\<inter> (H #> b) = {}\"\n  by (metis Int_emptyI assms repr_independence)\n\nlemma (in comm_group) subgroup_is_comm_group:\n  assumes \"subgroup H G\"\n  shows \"comm_group (G\\<lparr>carrier := H\\<rparr>)\" unfolding comm_group_def\nproof\n  interpret H: subgroup H G by fact\n  interpret H: submonoid H G using H.subgroup_is_submonoid .\n  show \"Group.group (G\\<lparr>carrier := H\\<rparr>)\" by blast\n  show \"comm_monoid (G\\<lparr>carrier := H\\<rparr>)\" using submonoid_is_comm_monoid H.submonoid_axioms by blast\nqed\n\nlemma (in group) pow_int_mod_ord:\n  assumes [simp]:\"a \\<in> carrier G\" \"ord a \\<noteq> 0\"\n  shows \"a [^] (n::int) = a [^] (n mod ord a)\"\nproof -\n  obtain q r where d: \"q = n div ord a\" \"r = n mod ord a\" \"n = q * ord a + r\"\n    using mod_div_decomp by blast\n  hence \"a [^] n = (a [^] int (ord a)) [^] q \\<otimes> a [^] r\"\n    using assms(1) int_pow_mult int_pow_pow\n    by (metis mult_of_nat_commute)\n  also have \"\\<dots> = \\<one> [^] q \\<otimes> a [^] r\"\n    by (simp add: int_pow_int)\n  also have \"\\<dots> = a [^] r\" by simp\n  finally show ?thesis using d(2) by blast\nqed\n\nlemma (in group) pow_nat_mod_ord:\n  assumes [simp]:\"a \\<in> carrier G\" \"ord a \\<noteq> 0\"\n  shows \"a [^] (n::nat) = a [^] (n mod ord a)\"\nproof -\n  obtain q r where d: \"q = n div ord a\" \"r = n mod ord a\" \"n = q * ord a + r\"\n    using mod_div_decomp by blast\n  hence \"a [^] n = (a [^] ord a) [^] q \\<otimes> a [^] r\"\n    using assms(1) nat_pow_mult nat_pow_pow by presburger\n  also have \"\\<dots> = \\<one> [^] q \\<otimes> a [^] r\" by auto\n  also have \"\\<dots> = a [^] r\" by simp\n  finally show ?thesis using d(2) by blast\nqed\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\n(* Manuel Eberl *)\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\n(* Manuel Eberl *)\nlemma (in subgroup) inv_in_iff:\n  assumes \"x \\<in> carrier G\" \"group G\"\n  shows   \"inv x \\<in> H \\<longleftrightarrow> x \\<in> H\"\nproof safe\n  assume \"inv x \\<in> H\"\n  hence \"inv (inv x) \\<in> H\" by blast\n  also have \"inv (inv x) = x\"\n    by (intro group.inv_inv) (use assms in auto)\n  finally show \"x \\<in> H\" .\nqed auto\n\n(* Manuel Eberl *)\nlemma (in subgroup) mult_in_cancel_left:\n  assumes \"y \\<in> carrier G\" \"x \\<in> H\" \"group G\"\n  shows   \"x \\<otimes> y \\<in> H \\<longleftrightarrow> y \\<in> H\"\nproof safe\n  assume \"x \\<otimes> y \\<in> H\"\n  hence \"inv x \\<otimes> (x \\<otimes> y) \\<in> H\"\n    using assms by blast\n  also have \"inv x \\<otimes> (x \\<otimes> y) = y\"\n    using assms by (simp add: \\<open>x \\<otimes> y \\<in> H\\<close> group.inv_solve_left')\n  finally show \"y \\<in> H\" .\nqed (use assms in auto)\n\n(* Manuel Eberl *)\nlemma (in subgroup) mult_in_cancel_right:\n  assumes \"x \\<in> carrier G\" \"y \\<in> H\" \"group G\"\n  shows   \"x \\<otimes> y \\<in> H \\<longleftrightarrow> x \\<in> H\"\nproof safe\n  assume \"x \\<otimes> y \\<in> H\"\n  hence \"(x \\<otimes> y) \\<otimes> inv y \\<in> H\"\n    using assms by blast\n  also have \"(x \\<otimes> y) \\<otimes> inv y = x\"\n    using assms by (simp add: \\<open>x \\<otimes> y \\<in> H\\<close> group.inv_solve_right')\n  finally show \"x \\<in> H\" .\nqed (use assms in auto)\n\nlemma (in group) (* Manuel Eberl *)\n  assumes \"x \\<in> carrier G\" and \"x [^] n = \\<one>\" and \"n > 0\"\n  shows   ord_le: \"ord x \\<le> n\" and ord_pos: \"ord x > 0\"\nproof -\n  have \"ord x dvd n\"\n    using pow_eq_id[of x n] assms by auto\n  thus \"ord x \\<le> n\" \"ord x > 0\"\n    using assms by (auto intro: dvd_imp_le)\nqed\n\nlemma (in group) ord_conv_Least: (* Manuel Eberl *)\n  assumes \"x \\<in> carrier G\" \"\\<exists>n::nat > 0. x [^] n = \\<one>\"\n  shows   \"ord x = (LEAST n::nat. 0 < n \\<and> x [^] n = \\<one>)\"\nproof (rule antisym)\n  show \"ord x \\<le> (LEAST n::nat. 0 < n \\<and> x [^] n = \\<one>)\"\n    using assms LeastI_ex[OF assms(2)] by (intro ord_le) auto\n  show \"ord x \\<ge> (LEAST n::nat. 0 < n \\<and> x [^] n = \\<one>)\"\n    using assms by (intro Least_le) (auto intro: pow_ord_eq_1 ord_pos)\nqed\n\nlemma (in group) ord_conv_Gcd: (* Manuel Eberl *)\n  assumes \"x \\<in> carrier G\"\n  shows   \"ord x = Gcd {n. x [^] n = \\<one>}\"\n  by (rule sym, rule Gcd_eqI) (use assms in \\<open>auto simp: pow_eq_id\\<close>)\n\nlemma (in group) subgroup_ord_eq:\n  assumes \"subgroup H G\" \"x \\<in> H\"\n  shows \"group.ord (G\\<lparr>carrier := H\\<rparr>) x = ord x\"\n  using nat_pow_consistent ord_def group.ord_def[of \"(G\\<lparr>carrier := H\\<rparr>)\" x]\n        subgroup.subgroup_is_group[of H G] assms by simp\n\nlemma (in group) ord_FactGroup:\n  assumes \"subgroup P G\" \"group (G Mod P)\"\n  shows \"order (G Mod P) * card P = order G\"\n  using lagrange[of P] FactGroup_def[of G P] assms order_def[of \"(G Mod P)\"] by fastforce\n\nlemma (in group) one_is_same:\n  assumes \"subgroup H G\"\n  shows \"\\<one>\\<^bsub>G\\<lparr>carrier := H\\<rparr>\\<^esub> = \\<one>\"\n  by simp\n\nlemma (in group) kernel_FactGroup:\n  assumes \"P \\<lhd> G\"\n  shows \"kernel G (G Mod P) (\\<lambda>x. P #> x) = P\"\nproof(rule equalityI; rule subsetI)\n  fix x\n  assume \"x \\<in> kernel G (G Mod P) ((#>) P)\"\n  then have \"P #> x = \\<one>\\<^bsub>G Mod P\\<^esub>\" \"x \\<in> carrier G\" unfolding kernel_def by simp+\n  with coset_join1[of P x] show \"x \\<in> P\" using assms unfolding normal_def by simp\nnext\n  fix x\n  assume x:\"x \\<in> P\"\n  then have xc: \"x \\<in> carrier G\" using assms subgroup.subset unfolding normal_def by fast\n  from x have \"P #> x = P\" using assms\n    by (simp add: normal_imp_subgroup subgroup.rcos_const)\n  thus \"x \\<in> kernel G (G Mod P) ((#>) P)\" unfolding kernel_def using xc by simp\nqed\n\nlemma (in group) sub_subgroup_coprime:\n  assumes \"subgroup H G\" \"subgroup J G\" \"coprime (card H) (card J)\"\n  and \"subgroup sH G\" \"subgroup sJ G\" \"sH \\<subseteq> H\" \"sJ \\<subseteq> J\"\nshows \"coprime (card sH) (card sJ)\"\n  using assms by (meson coprime_divisors sub_subgroup_dvd_card)\n\nlemma (in group) pow_eq_nat_mod:\n  assumes \"a \\<in> carrier G\" \"a [^] n = a [^] m\"\n  shows \"n mod (ord a) = m mod (ord a)\"\nproof -\n  from assms have \"a [^] (n - m) = \\<one>\" using pow_eq_div2 by blast\n  hence \"ord a dvd n - m\" using assms(1) pow_eq_id by blast\n  thus ?thesis\n    by (metis assms mod_eq_dvd_iff_nat nat_le_linear pow_eq_div2 pow_eq_id)\nqed\n\nlemma (in group) pow_eq_int_mod:\n  fixes n m::int\n  assumes \"a \\<in> carrier G\" \"a [^] n = a [^] m\"\n  shows \"n mod (ord a) = m mod (ord a)\"\nproof -\n  from assms have \"a [^] (n - m) = \\<one>\" using int_pow_closed int_pow_diff r_inv by presburger\n  hence \"ord a dvd n - m\" using assms(1) int_pow_eq_id by blast\n  thus ?thesis by (meson mod_eq_dvd_iff)\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/Finitely_Generated_Abelian_Groups/Miscellaneous_Groups.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8577681049901036, "lm_q2_score": 0.8652240808393984, "lm_q1q2_score": 0.7421616202134149}}
{"text": "theory Exercise11\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 x = x\"\n  | \"eval (Const n) x = n\"\n  | \"eval (Add l r) x = (eval l x) + (eval r x)\"\n  | \"eval (Mult l r) x = (eval l x) * (eval r x)\"\n\n(*\nfun polynomiate :: \"int list \\<Rightarrow> exp\" where\n  \"polynomiate Nil = Const 0\"\n  | \"polynomiate (Cons x xs) = Add (Const x) (Mult (Var) (polynomiate xs))\"\n\nfun evalp :: \"int list \\<Rightarrow> int \\<Rightarrow> int\" where\n  \"evalp xs n = eval (polynomiate xs) n\"\n*)\n\nfun evalp :: \"int list \\<Rightarrow> int \\<Rightarrow> int\" where\n  \"evalp Nil n = 0\"\n  | \"evalp (Cons x xs) n = x + n * (evalp xs n)\"\n\n(* 2*(7^2) + 4*7 + 3 = 129 *)\nlemma evalp_sanity [simp]: \"evalp [3, 4, 2] 7 = 129\"\n  apply auto\ndone\n\nfun linear_add :: \"int list \\<Rightarrow> int list \\<Rightarrow> int list\" where\n  \"linear_add Nil ys = ys\"\n  | \"linear_add xs Nil = xs\"\n  | \"linear_add (Cons x xs) (Cons y ys) = Cons (x + y) (linear_add xs ys)\"\n\nfun linear_scale :: \"int \\<Rightarrow> int list \\<Rightarrow> int list\" where\n  \"linear_scale x Nil = Nil\"\n  | \"linear_scale x (Cons y ys) = Cons (x*y) (linear_scale x ys)\"\n\nfun linear_mult :: \"int list \\<Rightarrow> int list \\<Rightarrow> int list\" where\n  \"linear_mult Nil ys = Nil\"\n  | \"linear_mult (Cons x xs) ys = linear_add (linear_scale x ys) (Cons 0 (linear_mult xs ys))\"\n\nlemma linear_mult_binomial_sanity [simp]: \"linear_mult [a, b] [c, d] = [(a*c), ((a*d) + (b*c)), (b*d)]\"\n  apply auto\ndone\n\nfun coeffs :: \"exp \\<Rightarrow> int list\" where\n  \"coeffs (Const n) = [n]\"\n  | \"coeffs Var = [0, 1]\"\n  | \"coeffs (Add l r) = linear_add (coeffs l) (coeffs r)\"\n  | \"coeffs (Mult l r) = linear_mult (coeffs l) (coeffs r)\"\n\n(* (x^2 + 3) * (2x + 7) = 2x^3 + 7x^2 + 6x + 21 *)\nlemma coeffs_sanity [simp]: \"coeffs (Mult (Add (Mult (Var) (Var)) (Const 3)) (Add (Mult (Const 2) (Var)) (Const 7))) = [21, 6, 7, 2]\"\n  apply auto\ndone\n\nlemma linear_add_zero [simp]: \"linear_add xs Nil = xs\"\n  apply (induction xs)\n  apply auto\ndone\n\nlemma evalp_linear_add [simp]: \"evalp (linear_add xs ys) n = (evalp xs n) + (evalp ys n)\"\n(*\n  apply (induction xs rule: polynomiate.induct)\n  apply (auto simp add: algebra_simps)\n*)\n  apply (induction xs rule: linear_add.induct)\n  apply (auto simp add: algebra_simps)\ndone\n\nlemma evalp_nil_zero [simp]: \"evalp (linear_mult xs Nil) n = 0\"\n  apply (induction xs arbitrary: n)\n  apply auto\ndone\n\nlemma evalp_linear_scale [simp]: \"evalp (linear_scale x xs) n = x * (evalp xs n)\"\n  apply (induction xs)\n  apply (auto simp add: algebra_simps)\ndone\n\nlemma evalp_linear_mult [simp]: \"evalp (linear_mult xs ys) n = (evalp xs n) * (evalp ys n)\"\n  apply (induction xs)\n  apply (auto simp add: algebra_simps)\ndone\n\ntheorem evalp_coeffs_preserves_eval: \"evalp (coeffs e) x = eval e x\"\n  apply (induction e arbitrary: x)\n  apply simp\n  apply simp\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/Exercise11.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952975813453, "lm_q2_score": 0.8267118004748677, "lm_q1q2_score": 0.7421352957412961}}
{"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\n\nfun \"and\" :: \"bexp \\<Rightarrow> bexp \\<Rightarrow> bexp\" where\n\"and = \"\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/BExp.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976953003183443, "lm_q2_score": 0.8267117876664789, "lm_q1q2_score": 0.742135286505975}}
{"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_Division\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\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 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\nend\n\nclass ring_parity = ring + semiring_parity\nbegin\n\nsubclass comm_ring_1 ..\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>Special case: euclidean rings containing the natural numbers\\<close>\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\n\nsubsection \\<open>Instance for \\<^typ>\\<open>nat\\<close>\\<close>\n\ninstance nat :: unique_euclidean_semiring_with_nat\n  by standard (simp_all add: dvd_eq_mod_eq_0)\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  using even_succ_div_two [of n] by simp\n\nlemma odd_Suc_div_two [simp]:\n  \"odd n \\<Longrightarrow> Suc n div 2 = Suc (n div 2)\"\n  using odd_succ_div_two [of n] by simp\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 (rule odd_two_times_div_two_succ)\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\nlemma 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\ncontext semiring_parity\nbegin\n\nlemma even_of_nat_iff [simp]:\n  \"even (of_nat n) \\<longleftrightarrow> even n\"\n  by (induction n) simp_all\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_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 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\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\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>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>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": "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/Parity.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511543206819, "lm_q2_score": 0.8670357718273068, "lm_q1q2_score": 0.7420535661557239}}
{"text": "theory sample2\n  imports Main begin\ntype_synonym string = \"char list\"\n\ndatatype \n  'a tree = Leaf |\n  Node \"'a tree\" 'a \"'a tree\"\n\nfun mirror :: \"'a tree\\<Rightarrow>'a tree\" where\n  \"mirror Leaf = Leaf\" |\n  (*left and right is swapped*)\n  \"mirror (Node left a right) = Node (mirror right) a (mirror left)\"\n\nlemma \"mirror (mirror t) = t\"\n  apply(induction t)\n   apply(auto)\n  done\n\ndatatype 'a option = None | Some 'a\n\n(* t1 * t2 is the type of pairs*)\nfun lookup :: \"('a * 'b) list \\<Rightarrow> 'a \\<Rightarrow> 'b option\" where\n  \"lookup Nil x = None\" |\n  \"lookup ((a, b) # ps) x = (\n    if a = x then \n      Some b \n    else \n    lookup ps x\n)\"\n\n(*\n  Pairs can be taken apart either by pattern\n  matching(as above) or with the projection\n  functions fst and snd (first, second)\n  Tuples are simulated by pairs nested to the\n  right: (a, b, c) is short for (a, (b, c))\n  and t1 * t2 * t3 is short for \n  t1 * (t2 * t3)\n*)\n\n(*non-recursive function*)\ndefinition sq :: \"nat\\<Rightarrow>nat\" where\n  \"sq n = n * n\"\n\n(*abbreviations*)\nabbreviations sq' :: \"nat\\<Rightarrow>nat\" where\n  \"sq' n = n * n\"\n\n(*\n  the key difference is that sq' is only\n  syntactic suger, sq' t is replaced by\n  t * t; \n  before printing, every occurrence\n  of u * u is replaced by sq' u.\n  Internally, sq' does not exist\n*)\n\n(*recursive functions: defined with fun\n  by pattern matching over datatype \n  constructors\n  The order of equations matters! ! !\n  (as in functional programming languages)\n  However, all HOL functions must be total.\n  This simplifies the logic - \n  terms are always defined - \n  but means that recursive functions must\n  terminate.\n  Otherwise one could define a function\n  f n = f n + 1 and conclude 0 = 1 by\n  subtracting f n on both sides.\n*)\n(*\n  Isabelle's automatic termination checker\n  requires that arguments of ercursive calls\n  on the right-hand side must be strictly\n  smaller than the arguments on the left-hand\n  side.\n  This means that one fixed argument position\n  decreases in size with each recursive call.\n  The size is measured as the number of  \n  constructor(excluding 0-ary ones, e.g. Nil)\n  Lexicographic combinations are also \n  recognized.\n*)\n\n(*functions defined with fun come with their\n  own induction schema that mirrors the \n  recursion schema and is derived from the \n  termination order.*)\n\nfun div2 :: \"nat\\<Rightarrow>nat\" where\n  \"div2 0 = 0\" | (* 0 *)\n  \"div2 (Suc 0) = 0\" | (* 1 *)\n  \"div2 (Suc (Suc n)) = Suc(div2 n)\" (* 2~ *)\n  (*e.g.: div2 (Suc (Suc 2)) = Suc (div2 2)\n   Suc (Suc 2) \\<Rightarrow> 4 *)\n\n(*it does not just define div2 but also proves\n  a customized induction rule\n  P 0  P (Suc 0)  \\<forall>n. P n \\<Longrightarrow> P (Suc (Suc n))\n  -------------------------------------------\n              P m\n\n  This induction rule can simplify inductive\n  proofs.\n*)\n\nlemma \"div2(n) = n div 2\"\n  apply(induction n rule: div2.induct)\n  apply(auto)\n  done\n\n(*\n  Function rev has quadratic worst-case \n  running time because it calls append \n  for each element of the list and append \n  is linear in its first argument. A linear \n  time version of rev requires an extra \n  argument where the result is accumulated \n  gradually, using only #\n*)\n\nfun itrev :: \"'a list \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where\n  \"itrev Nil ys = ys\" |\n  \"itrev (x # xs) ys = itrev xs (x # ys)\"\n\nthm itrev.induct\n\n(*\n  it reverses its first argument by stacking \n  its elements onto the second argument, and \n  it returns that second argument when the \n  first one becomes empty. Note that itrev \n  is tail-recursive: it can be compiled \n  into a loop; no stack is necessary \n  for executing it.\n*)\n\n\nlemma \"itrev xs Nil = rev xs\"\n  apply(induction xs)\n   apply(auto)\n  (* IH is too weak to remove subgoal*)\n  sorry\n\n(*xs @ ys = app xs ys*)\nlemma \"itrev xs ys = rev xs @ ys\"\n  (*apply(induction xs)*)\n  (*apply(auto)*)\n  (*IH is still too weak, use this instead*)\n  apply(induction xs arbitrary: ys)\n  apply(auto)\n  done\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/sample2.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357666736772, "lm_q2_score": 0.8558511524823263, "lm_q1q2_score": 0.742053560151064}}
{"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.*)\n  theory TIP_prop_01\n  imports \"../../Test_Base\"\nbegin\n\ndatatype Nat = Z | S \"Nat\"\n\nfun double :: \"Nat => Nat\" where\n  \"double (Z) = Z\"\n| \"double (S y) = S (S (double y))\"\n\nfun t2 :: \"Nat => Nat => Nat\" where\n  \"t2 (Z) y = y\"\n| \"t2 (S z) y = S (t2 z y)\"\n\n(* manipulation of sub-terms (t2 x (S x) = t2 (S x) x)) and generalization by renaming.*)\ntheorem property0 :\n  \"((double x) = (t2 x x))\"\n  apply(induct x)\n   apply simp\n  apply clarsimp\n  apply(subgoal_tac\n      \"(\\<And>x. t2 x (S x) = t2 (S x) x) &&& \n     (\\<And>x. double x = t2 x x \\<Longrightarrow> S (t2 x x) = t2 (S x) x)\")\n   apply presburger\n  apply(thin_tac \"double x = t2 x x\")\n  apply (rule conjunctionI)\n   apply simp(*mostly to get rid of x, a bit of simplification as well*)\n   apply(subgoal_tac \"(\\<And>x y. t2 x (S y) = S (t2 x y))\")(*generalization by renaming*)\n    apply presburger\n   apply simp(*to get rid of xa*)\n   apply(induct_tac x)\n    apply auto[1]\n   apply auto[1]\n  apply auto[1]\n  done\n\nlemma aux2:\n  shows \"double x = t2 x x \\<Longrightarrow> S (t2 x x) = t2 (S x) x\"\n  apply auto done\n\ntheorem aux11:\n  shows \"t2 x (S y) = t2 (S x) y\"\n  apply(induct x)\n  apply auto done\n\ntheorem aux1:\n  assumes \"\\<And>x y. t2 x (S y) = t2 (S x) y\"\n  shows \"t2 x (S x) = t2 (S x) x\"\n  apply(fastforce simp: assms) done\n\ntheorem aux0:\n  assumes \"(\\<And>x. t2 x (S x) = t2 (S x) x)\" (*the original term equals the new term whose arguments swapped*)\n          \"(\\<And>x. double x = t2 x x \\<Longrightarrow> S (t2 x x) = t2 (S x) x)\" (*swaps two unequal arguments*)\n        shows \"double x = t2 x x \\<Longrightarrow> S (t2 x x) = t2 x (S x)\"\n  using assms\n  apply metis done\n\ntheorem property0' :\n  \"((double x) = (t2 x x))\"\n  apply(induct x)\n   apply clarsimp\n  apply clarsimp\n  apply(rule aux0)\n    apply(rule aux1)\n    apply(rule aux11)\n   apply(rule aux2)\n   apply clarsimp\n  apply clarsimp\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_01.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.867035752930664, "lm_q2_score": 0.8558511488056151, "lm_q1q2_score": 0.7420535452012502}}
{"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_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_with_Proof/TIP15/TIP15/TIP_sort_nat_MSortTDSorts.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533051062237, "lm_q2_score": 0.7956581097540519, "lm_q1q2_score": 0.7419140341747362}}
{"text": "subsection \\<open>Theorems about the extended naturals\\<close>\n\ntext \\<open>Extended naturals are the natural numbers plus infinity.\n      They are slightly more cumbersome to reason about, and this file contains\n      some lemmas that should help with that.\\<close>\n\ntheory MoreENat\n  imports MoreCoinductiveList2\nbegin\n\nlemma eSuc_n_not_le_n[simp]:\n\"(eSuc x \\<le> x) \\<longleftrightarrow> x = \\<infinity>\"\n  by (metis enat_ord_simps(3) Suc_n_not_le_n antisym ile_eSuc le_add2 plus_1_eq_Suc the_enat_eSuc)\n\nlemma mult_two_impl1[elim]:\n  assumes \"a * 2 = 2 * b\"\n  shows \"(a::enat) = b\" using assms by(cases a;cases b,auto simp add: mult_2 mult_2_right)\n\nlemma mult_two_impl2[dest]:\n  assumes \"a * 2 = 1 + 2 * b\"\n  shows \"(a::enat) = \\<infinity> \\<and> b=\\<infinity>\"\n  apply(cases a;cases b)\n  using assms Suc_double_not_eq_double[unfolded mult_2, symmetric] \n  by (auto simp add: mult_2 one_enat_def mult_2_right)\n\nlemma mult_two_impl3[dest]:\n  assumes \"a * 2 = 1 + (2 * b - 1)\"\n  shows \"(a::enat) = b \\<and> a \\<ge> 1\"\n  using assms by(cases a;cases b,auto simp add: one_enat_def mult_2 mult_2_right)\n\nlemma mult_two_impl4[dest]:\n  assumes \"a * 2 = 2 * b - 1\"\n  shows \"((a::enat) = 0 \\<and> b = 0) \\<or> (a = \\<infinity> \\<and> b=\\<infinity>)\"\nproof(cases a;cases b)\n  fix anat bnat\n  assume *:\"a = enat anat\" \"b = enat bnat\"\n  hence \"anat + anat = bnat + bnat - Suc 0\"\n    using assms by (auto simp add:enat_0_iff one_enat_def mult_2 mult_2_right)\n  thus ?thesis unfolding * using Suc_double_not_eq_double[unfolded mult_2, symmetric]\n    by (metis Suc_pred add_gr_0 enat_0_iff(1) neq0_conv not_less0 zero_less_diff)\nqed(insert assms,auto simp add:enat_0_iff one_enat_def mult_2 mult_2_right)\n\n\nlemma times_two_div_two[intro]:\n  assumes \"enat n < x\" shows \"2 * enat (n div 2) < x\"\nproof -\n  have \"2 * n div 2 \\<le> n\" by auto\n  hence \"2 * enat (n div 2) \\<le> enat n\"\n    using enat_numeral enat_ord_simps(2) linorder_not_less mult.commute times_enat_simps(1) \n  by (metis div_times_less_eq_dividend)\n  with assms show ?thesis by auto\nqed\n\nlemma enat_sum_le[simp]:\n  shows \"enat (a + b) \\<le> c \\<Longrightarrow> b \\<le> c\"\n  by (meson dual_order.trans enat_ord_simps(1) le_add2)\n\n\nlemma enat_Suc_nonzero[simp]:\nshows \"enat (Suc n)\\<noteq> 0\"\n by (metis Zero_not_Suc enat.inject zero_enat_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/GaleStewart_Games/MoreENat.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467580102418, "lm_q2_score": 0.8438951025545426, "lm_q1q2_score": 0.7419076435115466}}
{"text": "(*\n    Author:     Ren\u00e9 Thiemann\n    License:    BSD\n*)\nsection \\<open>Calculating All Possible Sums of Sub-Multisets\\<close>\ntheory Sub_Sums\n  imports \n    Main \n    \"HOL-Library.Multiset\"\nbegin\n\nfun sub_mset_sums :: \"'a :: comm_monoid_add list \\<Rightarrow> 'a set\" where\n  \"sub_mset_sums [] = {0}\"\n| \"sub_mset_sums (x # xs) = (let S = sub_mset_sums xs in S \\<union> ( (+) x) ` S)\" \n\nlemma subset_add_mset: \"ys \\<subseteq># add_mset x zs \\<longleftrightarrow> (ys \\<subseteq># zs \\<or> (\\<exists> xs. xs \\<subseteq># zs \\<and> ys = add_mset x xs))\" \n  (is \"?l = ?r\")\nproof \n  have sub: \"ys \\<subseteq># zs \\<Longrightarrow> ys \\<subseteq># add_mset x zs\"\n    by (metis add_mset_remove_trivial diff_subset_eq_self subset_mset.dual_order.trans)\n  assume ?r\n  thus ?l using sub by auto\nnext\n  assume l: ?l\n  show ?r\n  proof (cases \"x \\<in># ys\")\n    case True\n    define xs where \"xs = (ys - {# x #})\" \n    from True have ys: \"ys = add_mset x xs\" unfolding xs_def by auto \n    from l[unfolded ys] have \"xs \\<subseteq># zs\" by auto\n    thus ?r unfolding ys by auto\n  next\n    case False\n    with l have \"ys \\<subseteq># zs\" by (simp add: subset_mset.le_iff_sup)\n    thus ?thesis by auto\n  qed\nqed\n\nlemma sub_mset_sums[simp]: \"sub_mset_sums xs = sum_mset ` { ys. ys \\<subseteq># mset xs }\" \nproof (induct xs)\n  case (Cons x xs)\n  have id: \"{ys. ys \\<subseteq># mset (x # xs)} = {ys. ys \\<subseteq># mset xs} \\<union> {add_mset x ys | ys. ys \\<subseteq># mset xs}\" \n    unfolding mset.simps subset_add_mset by auto\n  show ?case unfolding sub_mset_sums.simps Let_def Cons id image_Un \n    by force\nqed 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/LLL_Factorization/Sub_Sums.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467548438126, "lm_q2_score": 0.8438950986284991, "lm_q1q2_score": 0.7419076373878442}}
{"text": "chapter {* R7: \u00c1rboles binarios completos *}\n\ntheory R7_Arboles_binarios_completos\nimports Main \nbegin \n\ntext {*  \n  En esta relaci\u00f3n se piden demostraciones autom\u00e1ticas (lo m\u00e1s cortas\n  posibles). Para ello, en algunos casos es necesario incluir lemas\n  auxiliares (que se demuestran autom\u00e1ticamente) y usar ejercicios\n  anteriores. \n\n  --------------------------------------------------------------------- \n  Ejercicio 1. Definir el tipo de datos arbol para representar los\n  \u00e1rboles binarios que no tienen informaci\u00f3n ni en los nodos y ni en las\n  hojas. Por ejemplo, el \u00e1rbol\n          \u00b7\n         / \\\n        /   \\\n       \u00b7     \u00b7\n      / \\   / \\\n     \u00b7   \u00b7 \u00b7   \u00b7 \n  se representa por \"N (N H H) (N H H)\".\n  --------------------------------------------------------------------- \n*}\n\ndatatype arbol = H | N arbol arbol\n\nvalue \"N (N H H) (N H H) = (N (N H H) (N H H) :: arbol)\"\n\ntext {*  \n  --------------------------------------------------------------------- \n  Ejercicio 2. Definir la funci\u00f3n\n     hojas :: \"arbol => nat\" \n  tal que (hojas a) es el n\u00famero de hojas del \u00e1rbol a. Por ejemplo,\n     hojas (N (N H H) (N H H)) = 4\n  --------------------------------------------------------------------- \n*}\n\nfun hojas :: \"arbol => nat\" where\n  \"hojas H = 1\"\n| \"hojas (N i d) = hojas i + hojas d\"\n\nvalue \"hojas (N (N H H) (N H H)) = 4\"\n\ntext {*  \n  --------------------------------------------------------------------- \n  Ejercicio 4. Definir la funci\u00f3n\n     profundidad :: \"arbol => nat\" \n  tal que (profundidad a) es la profundidad del \u00e1rbol a. Por ejemplo,\n     profundidad (N (N H H) (N H H)) = 2\n  --------------------------------------------------------------------- \n*}\n\nfun profundidad :: \"arbol => nat\" where\n  \"profundidad H = 0\"\n| \"profundidad (N i d) = 1 + (max (profundidad i)(profundidad d))\"\n\nvalue \"profundidad (N (N H H) (N H H)) = 2\"\n\ntext {*  \n  --------------------------------------------------------------------- \n  Ejercicio 5. Definir la funci\u00f3n\n     abc :: \"nat \\<Rightarrow> arbol\" \n  tal que (abc n) es el \u00e1rbol binario completo de profundidad n. Por\n  ejemplo,  \n     abc 3 = N (N (N H H) (N H H)) (N (N H H) (N H H))\n  --------------------------------------------------------------------- \n*}\n\nfun abc :: \"nat \\<Rightarrow> arbol\" where\n  \"abc 0 = H\"\n| \"abc (Suc n) = (N (abc n) (abc n))\"\n\nvalue \"abc 3 = N (N (N H H) (N H H)) (N (N H H) (N H H))\"\n\ntext {*  \n  --------------------------------------------------------------------- \n  Ejercicio 6. Un \u00e1rbol binario a es completo respecto de la medida f si\n  a es una hoja o bien a es de la forma (N i d) y se cumple que tanto i\n  como d son \u00e1rboles binarios completos respecto de f y, adem\u00e1s, \n  f(i) = f(r).\n\n  Definir la funci\u00f3n\n     es_abc :: \"(arbol => 'a) => arbol => bool\n  tal que (es_abc f a) se verifica si a es un \u00e1rbol binario completo\n  respecto de f.\n  --------------------------------------------------------------------- \n*}\n\nfun es_abc :: \"(arbol => 'a) => arbol => bool\" where\n  \"es_abc _ H = True\"\n|  \"es_abc f (N i d) = (es_abc f i \\<and> es_abc f d \\<and> (f i = f d))\"\n\ntext {*  \n  --------------------------------------------------------------------- \n  Nota. (size a) es el n\u00famero de nodos del \u00e1rbol a. Por ejemplo,\n     size (N (N H H) (N H H)) = 3\n  --------------------------------------------------------------------- \n*}\n\nvalue \"size (N (N H H) (N H H)) = 3\"\nvalue \"size (N (N (N H H) (N H H)) (N (N H H) (N H H))) = 7\"\n\ntext {*  \n  --------------------------------------------------------------------- \n  Nota. Tenemos 3 funciones de medida sobre los \u00e1rboles: n\u00famero de\n  hojas, n\u00famero de nodos y profundidad. A cada una le corresponde un\n  concepto de completitud. En los siguientes ejercicios demostraremos\n  que los tres conceptos de completitud son iguales.\n  --------------------------------------------------------------------- \n*}\n\ntext {*  \n  --------------------------------------------------------------------- \n  Ejercicio 7. Demostrar que un \u00e1rbol binario a es completo respecto de\n  la profundidad syss es completo respecto del n\u00famero de hojas.\n  --------------------------------------------------------------------- \n*}\n\nlemma arbol_profundidad_respecto_num_hojas:\n  assumes \"es_abc profundidad n\"\n  shows \"hojas n = 2^(profundidad n)\"\nusing assms\nby (induct n) auto\n\nlemma lej7: \"es_abc profundidad a = es_abc hojas a\"\nby (induct a) (auto simp add: arbol_profundidad_respecto_num_hojas)\n\ntext {*  \n  --------------------------------------------------------------------- \n  Ejercicio 8. Demostrar que un \u00e1rbol binario a es completo respecto del\n  n\u00famero de hojas syss es completo respecto del n\u00famero de nodos.\n  --------------------------------------------------------------------- \n*}\n\nlemma arbol_completo_respecto_num_hojas:\n  assumes \"es_abc hojas n\"\n  shows \"Suc(size n) = hojas n\"\nusing assms\nby (induct n) auto\n\nlemma lej8: \"es_abc hojas a = es_abc size a\"\nby (induct a) (auto simp add:arbol_completo_respecto_num_hojas [symmetric])\n\ntext {*  \n  --------------------------------------------------------------------- \n  Ejercicio 9. Demostrar que un \u00e1rbol binario a es completo respecto de\n  la profundidad syss es completo respecto del n\u00famero de nodos.\n  --------------------------------------------------------------------- \n*}\n\nlemma arbol_completo_respecto_profundidad: \"es_abc profundidad n = es_abc size n\"\nby (simp add: lej7 lej8) \n\ntext {*  \n  --------------------------------------------------------------------- \n  Ejercicio 10. Demostrar que (abc n) es un \u00e1rbol binario completo.\n  --------------------------------------------------------------------- \n*}\n\nlemma lej10:  \"es_abc profundidad (abc n)\"\nby (induct n) auto\n\ntext {*  \n  --------------------------------------------------------------------- \n  Ejercicio 11. Demostrar que si a es un \u00e1rbolo binario completo\n  respecto de la profundidad, entonces a es igual a\n  (abc (profundidad a)).\n  --------------------------------------------------------------------- \n*}\n\nlemma lej11: \n  assumes \" es_abc profundidad n\"\n  shows \"n = (abc (profundidad n))\"\nusing assms\nby (induct n) auto\n\ntext {*  \n  --------------------------------------------------------------------- \n  Ejercicio 12. Encontrar una medida f tal que (es_abc f) es distinto de \n  (es_abc size).\n  --------------------------------------------------------------------- \n*}\n\nlemma \"es_abc f n =  es_abc size n\"\nquickcheck\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/R7_Arboles_binarios_completos.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245953120233, "lm_q2_score": 0.8902942246666267, "lm_q1q2_score": 0.7419040744789482}}
{"text": "(*  Title:      HOL/ex/MergeSort.thy\n    Author:     Tobias Nipkow\n    Copyright   2002 TU Muenchen\n*)\n\nsection\\<open>Merge Sort\\<close>\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 mset_merge [simp]:\n  \"mset (merge xs ys) = mset xs + mset 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 mset_msort:\n  \"mset (msort xs) = mset xs\"\n  by (induct xs rule: msort.induct)\n    (simp_all, metis append_take_drop_id drop_Suc_Cons mset.simps(2) mset_append take_Suc_Cons)\n\ntheorem msort_sort:\n  \"sort = msort\"\n  by (rule ext, rule properties_for_sort) (fact mset_msort sorted_msort)+\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/ex/MergeSort.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.853912760387131, "lm_q2_score": 0.8688267864276108, "lm_q1q2_score": 0.7419022794966815}}
{"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\nsection \\<open>Abstract Topology 2\\<close>\n\ntheory Abstract_Topology_2\n  imports\n    Elementary_Topology\n    Abstract_Topology\n    \"HOL-Library.Indicator_Function\"\nbegin\n\ntext \\<open>Combination of Elementary and Abstract Topology\\<close>\n\nlemma approachable_lt_le2: \n    \"(\\<exists>(d::real) > 0. \\<forall>x. Q x \\<longrightarrow> f x < d \\<longrightarrow> P x) \\<longleftrightarrow> (\\<exists>d>0. \\<forall>x. f x \\<le> d \\<longrightarrow> Q x \\<longrightarrow> P x)\"\n  apply auto\n  apply (rule_tac x=\"d/2\" in exI, auto)\n  done\n\nlemma triangle_lemma:\n  fixes x y z :: real\n  assumes x: \"0 \\<le> x\"\n    and y: \"0 \\<le> y\"\n    and z: \"0 \\<le> z\"\n    and xy: \"x\\<^sup>2 \\<le> y\\<^sup>2 + z\\<^sup>2\"\n  shows \"x \\<le> y + z\"\nproof -\n  have \"y\\<^sup>2 + z\\<^sup>2 \\<le> y\\<^sup>2 + 2 * y * z + z\\<^sup>2\"\n    using z y by simp\n  with xy have th: \"x\\<^sup>2 \\<le> (y + z)\\<^sup>2\"\n    by (simp add: power2_eq_square field_simps)\n  from y z have yz: \"y + z \\<ge> 0\"\n    by arith\n  from power2_le_imp_le[OF th yz] show ?thesis .\nqed\n\nlemma isCont_indicator:\n  fixes x :: \"'a::t2_space\"\n  shows \"isCont (indicator A :: 'a \\<Rightarrow> real) x = (x \\<notin> frontier A)\"\nproof auto\n  fix x\n  assume cts_at: \"isCont (indicator A :: 'a \\<Rightarrow> real) x\" and fr: \"x \\<in> frontier A\"\n  with continuous_at_open have 1: \"\\<forall>V::real set. open V \\<and> indicator A x \\<in> V \\<longrightarrow>\n    (\\<exists>U::'a set. open U \\<and> x \\<in> U \\<and> (\\<forall>y\\<in>U. indicator A y \\<in> V))\" by auto\n  show False\n  proof (cases \"x \\<in> A\")\n    assume x: \"x \\<in> A\"\n    hence \"indicator A x \\<in> ({0<..<2} :: real set)\" by simp\n    with 1 obtain U where U: \"open U\" \"x \\<in> U\" \"\\<forall>y\\<in>U. indicator A y \\<in> ({0<..<2} :: real set)\"\n      using open_greaterThanLessThan by metis\n    hence \"\\<forall>y\\<in>U. indicator A y > (0::real)\"\n      unfolding greaterThanLessThan_def by auto\n    hence \"U \\<subseteq> A\" using indicator_eq_0_iff by force\n    hence \"x \\<in> interior A\" using U interiorI by auto\n    thus ?thesis using fr unfolding frontier_def by simp\n  next\n    assume x: \"x \\<notin> A\"\n    hence \"indicator A x \\<in> ({-1<..<1} :: real set)\" by simp\n    with 1 obtain U where U: \"open U\" \"x \\<in> U\" \"\\<forall>y\\<in>U. indicator A y \\<in> ({-1<..<1} :: real set)\"\n      using 1 open_greaterThanLessThan by metis\n    hence \"\\<forall>y\\<in>U. indicator A y < (1::real)\"\n      unfolding greaterThanLessThan_def by auto\n    hence \"U \\<subseteq> -A\" by auto\n    hence \"x \\<in> interior (-A)\" using U interiorI by auto\n    thus ?thesis using fr interior_complement unfolding frontier_def by auto\n  qed\nnext\n  assume nfr: \"x \\<notin> frontier A\"\n  hence \"x \\<in> interior A \\<or> x \\<in> interior (-A)\"\n    by (auto simp: frontier_def closure_interior)\n  thus \"isCont ((indicator A)::'a \\<Rightarrow> real) x\"\n  proof\n    assume int: \"x \\<in> interior A\"\n    then obtain U where U: \"open U\" \"x \\<in> U\" \"U \\<subseteq> A\" unfolding interior_def by auto\n    hence \"\\<forall>y\\<in>U. indicator A y = (1::real)\" unfolding indicator_def by auto\n    hence \"continuous_on U (indicator A)\" by (simp add: indicator_eq_1_iff)\n    thus ?thesis using U continuous_on_eq_continuous_at by auto\n  next\n    assume ext: \"x \\<in> interior (-A)\"\n    then obtain U where U: \"open U\" \"x \\<in> U\" \"U \\<subseteq> -A\" unfolding interior_def by auto\n    then have \"continuous_on U (indicator A)\"\n      using continuous_on_topological by (auto simp: subset_iff)\n    thus ?thesis using U continuous_on_eq_continuous_at by auto\n  qed\nqed\n\nlemma closedin_limpt:\n  \"closedin (top_of_set T) S \\<longleftrightarrow> S \\<subseteq> T \\<and> (\\<forall>x. x islimpt S \\<and> x \\<in> T \\<longrightarrow> x \\<in> S)\"\n  apply (simp add: closedin_closed, safe)\n   apply (simp add: closed_limpt islimpt_subset)\n  apply (rule_tac x=\"closure S\" in exI, simp)\n  apply (force simp: closure_def)\n  done\n\nlemma closedin_closed_eq: \"closed S \\<Longrightarrow> closedin (top_of_set S) T \\<longleftrightarrow> closed T \\<and> T \\<subseteq> S\"\n  by (meson closedin_limpt closed_subset closedin_closed_trans)\n\nlemma connected_closed_set:\n   \"closed S\n    \\<Longrightarrow> connected S \\<longleftrightarrow> (\\<nexists>A B. closed A \\<and> closed B \\<and> A \\<noteq> {} \\<and> B \\<noteq> {} \\<and> A \\<union> B = S \\<and> A \\<inter> B = {})\"\n  unfolding connected_closedin_eq closedin_closed_eq connected_closedin_eq by blast\n\ntext \\<open>If a connnected set is written as the union of two nonempty closed sets, then these sets\nhave to intersect.\\<close>\n\nlemma connected_as_closed_union:\n  assumes \"connected C\" \"C = A \\<union> B\" \"closed A\" \"closed B\" \"A \\<noteq> {}\" \"B \\<noteq> {}\"\n  shows \"A \\<inter> B \\<noteq> {}\"\nby (metis assms closed_Un connected_closed_set)\n\nlemma closedin_subset_trans:\n  \"closedin (top_of_set U) S \\<Longrightarrow> S \\<subseteq> T \\<Longrightarrow> T \\<subseteq> U \\<Longrightarrow>\n    closedin (top_of_set T) S\"\n  by (meson closedin_limpt subset_iff)\n\nlemma openin_subset_trans:\n  \"openin (top_of_set U) S \\<Longrightarrow> S \\<subseteq> T \\<Longrightarrow> T \\<subseteq> U \\<Longrightarrow>\n    openin (top_of_set T) S\"\n  by (auto simp: openin_open)\n\nlemma closedin_compact:\n   \"\\<lbrakk>compact S; closedin (top_of_set S) T\\<rbrakk> \\<Longrightarrow> compact T\"\nby (metis closedin_closed compact_Int_closed)\n\nlemma closedin_compact_eq:\n  fixes S :: \"'a::t2_space set\"\n  shows\n   \"compact S\n         \\<Longrightarrow> (closedin (top_of_set S) T \\<longleftrightarrow>\n              compact T \\<and> T \\<subseteq> S)\"\nby (metis closedin_imp_subset closedin_compact closed_subset compact_imp_closed)\n\n\nsubsection \\<open>Closure\\<close>\n\nlemma euclidean_closure_of [simp]: \"euclidean closure_of S = closure S\"\n  by (auto simp: closure_of_def closure_def islimpt_def)\n\nlemma closure_openin_Int_closure:\n  assumes ope: \"openin (top_of_set U) S\" and \"T \\<subseteq> U\"\n  shows \"closure(S \\<inter> closure T) = closure(S \\<inter> T)\"\nproof\n  obtain V where \"open V\" and S: \"S = U \\<inter> V\"\n    using ope using openin_open by metis\n  show \"closure (S \\<inter> closure T) \\<subseteq> closure (S \\<inter> T)\"\n    proof (clarsimp simp: S)\n      fix x\n      assume  \"x \\<in> closure (U \\<inter> V \\<inter> closure T)\"\n      then have \"V \\<inter> closure T \\<subseteq> A \\<Longrightarrow> x \\<in> closure A\" for A\n          by (metis closure_mono subsetD inf.coboundedI2 inf_assoc)\n      then have \"x \\<in> closure (T \\<inter> V)\"\n         by (metis \\<open>open V\\<close> closure_closure inf_commute open_Int_closure_subset)\n      then show \"x \\<in> closure (U \\<inter> V \\<inter> T)\"\n        by (metis \\<open>T \\<subseteq> U\\<close> inf.absorb_iff2 inf_assoc inf_commute)\n    qed\nnext\n  show \"closure (S \\<inter> T) \\<subseteq> closure (S \\<inter> closure T)\"\n    by (meson Int_mono closure_mono closure_subset order_refl)\nqed\n\ncorollary infinite_openin:\n  fixes S :: \"'a :: t1_space set\"\n  shows \"\\<lbrakk>openin (top_of_set U) S; x \\<in> S; x islimpt U\\<rbrakk> \\<Longrightarrow> infinite S\"\n  by (clarsimp simp add: openin_open islimpt_eq_acc_point inf_commute)\n\nlemma closure_Int_ballI:\n  assumes \"\\<And>U. \\<lbrakk>openin (top_of_set S) U; U \\<noteq> {}\\<rbrakk> \\<Longrightarrow> T \\<inter> U \\<noteq> {}\"\n  shows \"S \\<subseteq> closure T\"\nproof (clarsimp simp: closure_iff_nhds_not_empty)\n  fix x and A and V\n  assume \"x \\<in> S\" \"V \\<subseteq> A\" \"open V\" \"x \\<in> V\" \"T \\<inter> A = {}\"\n  then have \"openin (top_of_set S) (A \\<inter> V \\<inter> S)\"\n    by (auto simp: openin_open intro!: exI[where x=\"V\"])\n  moreover have \"A \\<inter> V \\<inter> S \\<noteq> {}\" using \\<open>x \\<in> V\\<close> \\<open>V \\<subseteq> A\\<close> \\<open>x \\<in> S\\<close>\n    by auto\n  ultimately have \"T \\<inter> (A \\<inter> V \\<inter> S) \\<noteq> {}\"\n    by (rule assms)\n  with \\<open>T \\<inter> A = {}\\<close> show False by auto\nqed\n\n\nsubsection \\<open>Frontier\\<close>\n\nlemma euclidean_interior_of [simp]: \"euclidean interior_of S = interior S\"\n  by (auto simp: interior_of_def interior_def)\n\nlemma euclidean_frontier_of [simp]: \"euclidean frontier_of S = frontier S\"\n  by (auto simp: frontier_of_def frontier_def)\n\nlemma connected_Int_frontier:\n     \"\\<lbrakk>connected s; s \\<inter> t \\<noteq> {}; s - t \\<noteq> {}\\<rbrakk> \\<Longrightarrow> (s \\<inter> frontier t \\<noteq> {})\"\n  apply (simp add: frontier_interiors connected_openin, safe)\n  apply (drule_tac x=\"s \\<inter> interior t\" in spec, safe)\n   apply (drule_tac [2] x=\"s \\<inter> interior (-t)\" in spec)\n   apply (auto simp: disjoint_eq_subset_Compl dest: interior_subset [THEN subsetD])\n  done\n\nsubsection \\<open>Compactness\\<close>\n\nlemma openin_delete:\n  fixes a :: \"'a :: t1_space\"\n  shows \"openin (top_of_set u) s\n         \\<Longrightarrow> openin (top_of_set u) (s - {a})\"\nby (metis Int_Diff open_delete openin_open)\n\nlemma compact_eq_openin_cover:\n  \"compact S \\<longleftrightarrow>\n    (\\<forall>C. (\\<forall>c\\<in>C. openin (top_of_set S) c) \\<and> S \\<subseteq> \\<Union>C \\<longrightarrow>\n      (\\<exists>D\\<subseteq>C. finite D \\<and> S \\<subseteq> \\<Union>D))\"\nproof safe\n  fix C\n  assume \"compact S\" and \"\\<forall>c\\<in>C. openin (top_of_set S) c\" and \"S \\<subseteq> \\<Union>C\"\n  then have \"\\<forall>c\\<in>{T. open T \\<and> S \\<inter> T \\<in> C}. open c\" and \"S \\<subseteq> \\<Union>{T. open T \\<and> S \\<inter> T \\<in> C}\"\n    unfolding openin_open by force+\n  with \\<open>compact S\\<close> obtain D where \"D \\<subseteq> {T. open T \\<and> S \\<inter> T \\<in> C}\" and \"finite D\" and \"S \\<subseteq> \\<Union>D\"\n    by (meson compactE)\n  then have \"image (\\<lambda>T. S \\<inter> T) D \\<subseteq> C \\<and> finite (image (\\<lambda>T. S \\<inter> T) D) \\<and> S \\<subseteq> \\<Union>(image (\\<lambda>T. S \\<inter> T) D)\"\n    by auto\n  then show \"\\<exists>D\\<subseteq>C. finite D \\<and> S \\<subseteq> \\<Union>D\" ..\nnext\n  assume 1: \"\\<forall>C. (\\<forall>c\\<in>C. openin (top_of_set S) c) \\<and> S \\<subseteq> \\<Union>C \\<longrightarrow>\n        (\\<exists>D\\<subseteq>C. finite D \\<and> S \\<subseteq> \\<Union>D)\"\n  show \"compact S\"\n  proof (rule compactI)\n    fix C\n    let ?C = \"image (\\<lambda>T. S \\<inter> T) C\"\n    assume \"\\<forall>t\\<in>C. open t\" and \"S \\<subseteq> \\<Union>C\"\n    then have \"(\\<forall>c\\<in>?C. openin (top_of_set S) c) \\<and> S \\<subseteq> \\<Union>?C\"\n      unfolding openin_open by auto\n    with 1 obtain D where \"D \\<subseteq> ?C\" and \"finite D\" and \"S \\<subseteq> \\<Union>D\"\n      by metis\n    let ?D = \"inv_into C (\\<lambda>T. S \\<inter> T) ` D\"\n    have \"?D \\<subseteq> C \\<and> finite ?D \\<and> S \\<subseteq> \\<Union>?D\"\n    proof (intro conjI)\n      from \\<open>D \\<subseteq> ?C\\<close> show \"?D \\<subseteq> C\"\n        by (fast intro: inv_into_into)\n      from \\<open>finite D\\<close> show \"finite ?D\"\n        by (rule finite_imageI)\n      from \\<open>S \\<subseteq> \\<Union>D\\<close> show \"S \\<subseteq> \\<Union>?D\"\n        apply (rule subset_trans)\n        by (metis Int_Union Int_lower2 \\<open>D \\<subseteq> (\\<inter>) S ` C\\<close> image_inv_into_cancel)\n    qed\n    then show \"\\<exists>D\\<subseteq>C. finite D \\<and> S \\<subseteq> \\<Union>D\" ..\n  qed\nqed\n\n\nsubsection \\<open>Continuity\\<close>\n\nlemma interior_image_subset:\n  assumes \"inj f\" \"\\<And>x. continuous (at x) f\"\n  shows \"interior (f ` S) \\<subseteq> f ` (interior S)\"\nproof\n  fix x assume \"x \\<in> interior (f ` S)\"\n  then obtain T where as: \"open T\" \"x \\<in> T\" \"T \\<subseteq> f ` S\" ..\n  then have \"x \\<in> f ` S\" by auto\n  then obtain y where y: \"y \\<in> S\" \"x = f y\" by auto\n  have \"open (f -` T)\"\n    using assms \\<open>open T\\<close> by (simp add: continuous_at_imp_continuous_on open_vimage)\n  moreover have \"y \\<in> vimage f T\"\n    using \\<open>x = f y\\<close> \\<open>x \\<in> T\\<close> by simp\n  moreover have \"vimage f T \\<subseteq> S\"\n    using \\<open>T \\<subseteq> image f S\\<close> \\<open>inj f\\<close> unfolding inj_on_def subset_eq by auto\n  ultimately have \"y \\<in> interior S\" ..\n  with \\<open>x = f y\\<close> show \"x \\<in> f ` interior S\" ..\nqed\n\nsubsection\\<^marker>\\<open>tag unimportant\\<close> \\<open>Equality of continuous functions on closure and related results\\<close>\n\nlemma continuous_closedin_preimage_constant:\n  fixes f :: \"_ \\<Rightarrow> 'b::t1_space\"\n  shows \"continuous_on S f \\<Longrightarrow> closedin (top_of_set S) {x \\<in> S. f x = a}\"\n  using continuous_closedin_preimage[of S f \"{a}\"] by (simp add: vimage_def Collect_conj_eq)\n\nlemma continuous_closed_preimage_constant:\n  fixes f :: \"_ \\<Rightarrow> 'b::t1_space\"\n  shows \"continuous_on S f \\<Longrightarrow> closed S \\<Longrightarrow> closed {x \\<in> S. f x = a}\"\n  using continuous_closed_preimage[of S f \"{a}\"] by (simp add: vimage_def Collect_conj_eq)\n\nlemma continuous_constant_on_closure:\n  fixes f :: \"_ \\<Rightarrow> 'b::t1_space\"\n  assumes \"continuous_on (closure S) f\"\n      and \"\\<And>x. x \\<in> S \\<Longrightarrow> f x = a\"\n      and \"x \\<in> closure S\"\n  shows \"f x = a\"\n    using continuous_closed_preimage_constant[of \"closure S\" f a]\n      assms closure_minimal[of S \"{x \\<in> closure S. f x = a}\"] closure_subset\n    unfolding subset_eq\n    by auto\n\nlemma image_closure_subset:\n  assumes contf: \"continuous_on (closure S) f\"\n    and \"closed T\"\n    and \"(f ` S) \\<subseteq> T\"\n  shows \"f ` (closure S) \\<subseteq> T\"\nproof -\n  have \"S \\<subseteq> {x \\<in> closure S. f x \\<in> T}\"\n    using assms(3) closure_subset by auto\n  moreover have \"closed (closure S \\<inter> f -` T)\"\n    using continuous_closed_preimage[OF contf] \\<open>closed T\\<close> by auto\n  ultimately have \"closure S = (closure S \\<inter> f -` T)\"\n    using closure_minimal[of S \"(closure S \\<inter> f -` T)\"] by auto\n  then show ?thesis by auto\nqed\n\nsubsection\\<^marker>\\<open>tag unimportant\\<close> \\<open>A function constant on a set\\<close>\n\ndefinition constant_on  (infixl \"(constant'_on)\" 50)\n  where \"f constant_on A \\<equiv> \\<exists>y. \\<forall>x\\<in>A. f x = y\"\n\nlemma constant_on_subset: \"\\<lbrakk>f constant_on A; B \\<subseteq> A\\<rbrakk> \\<Longrightarrow> f constant_on B\"\n  unfolding constant_on_def by blast\n\nlemma injective_not_constant:\n  fixes S :: \"'a::{perfect_space} set\"\n  shows \"\\<lbrakk>open S; inj_on f S; f constant_on S\\<rbrakk> \\<Longrightarrow> S = {}\"\nunfolding constant_on_def\nby (metis equals0I inj_on_contraD islimpt_UNIV islimpt_def)\n\nlemma constant_on_closureI:\n  fixes f :: \"_ \\<Rightarrow> 'b::t1_space\"\n  assumes cof: \"f constant_on S\" and contf: \"continuous_on (closure S) f\"\n    shows \"f constant_on (closure S)\"\nusing continuous_constant_on_closure [OF contf] cof unfolding constant_on_def\nby metis\n\n\nsubsection\\<^marker>\\<open>tag unimportant\\<close> \\<open>Continuity relative to a union.\\<close>\n\nlemma continuous_on_Un_local:\n    \"\\<lbrakk>closedin (top_of_set (s \\<union> t)) s; closedin (top_of_set (s \\<union> t)) t;\n      continuous_on s f; continuous_on t f\\<rbrakk>\n     \\<Longrightarrow> continuous_on (s \\<union> t) f\"\n  unfolding continuous_on closedin_limpt\n  by (metis Lim_trivial_limit Lim_within_union Un_iff trivial_limit_within)\n\nlemma continuous_on_cases_local:\n     \"\\<lbrakk>closedin (top_of_set (s \\<union> t)) s; closedin (top_of_set (s \\<union> t)) t;\n       continuous_on s f; continuous_on t g;\n       \\<And>x. \\<lbrakk>x \\<in> s \\<and> \\<not>P x \\<or> x \\<in> t \\<and> P x\\<rbrakk> \\<Longrightarrow> f x = g x\\<rbrakk>\n      \\<Longrightarrow> continuous_on (s \\<union> t) (\\<lambda>x. if P x then f x else g x)\"\n  by (rule continuous_on_Un_local) (auto intro: continuous_on_eq)\n\nlemma continuous_on_cases_le:\n  fixes h :: \"'a :: topological_space \\<Rightarrow> real\"\n  assumes \"continuous_on {t \\<in> s. h t \\<le> a} f\"\n      and \"continuous_on {t \\<in> s. a \\<le> h t} g\"\n      and h: \"continuous_on s h\"\n      and \"\\<And>t. \\<lbrakk>t \\<in> s; h t = a\\<rbrakk> \\<Longrightarrow> f t = g t\"\n    shows \"continuous_on s (\\<lambda>t. if h t \\<le> a then f(t) else g(t))\"\nproof -\n  have s: \"s = (s \\<inter> h -` atMost a) \\<union> (s \\<inter> h -` atLeast a)\"\n    by force\n  have 1: \"closedin (top_of_set s) (s \\<inter> h -` atMost a)\"\n    by (rule continuous_closedin_preimage [OF h closed_atMost])\n  have 2: \"closedin (top_of_set s) (s \\<inter> h -` atLeast a)\"\n    by (rule continuous_closedin_preimage [OF h closed_atLeast])\n  have eq: \"s \\<inter> h -` {..a} = {t \\<in> s. h t \\<le> a}\" \"s \\<inter> h -` {a..} = {t \\<in> s. a \\<le> h t}\"\n    by auto\n  show ?thesis\n    apply (rule continuous_on_subset [of s, OF _ order_refl])\n    apply (subst s)\n    apply (rule continuous_on_cases_local)\n    using 1 2 s assms apply (auto simp: eq)\n    done\nqed\n\nlemma continuous_on_cases_1:\n  fixes s :: \"real set\"\n  assumes \"continuous_on {t \\<in> s. t \\<le> a} f\"\n      and \"continuous_on {t \\<in> s. a \\<le> t} g\"\n      and \"a \\<in> s \\<Longrightarrow> f a = g a\"\n    shows \"continuous_on s (\\<lambda>t. if t \\<le> a then f(t) else g(t))\"\nusing assms\nby (auto intro: continuous_on_cases_le [where h = id, simplified])\n\n\nsubsection\\<^marker>\\<open>tag unimportant\\<close>\\<open>Inverse function property for open/closed maps\\<close>\n\nlemma continuous_on_inverse_open_map:\n  assumes contf: \"continuous_on S f\"\n    and imf: \"f ` S = T\"\n    and injf: \"\\<And>x. x \\<in> S \\<Longrightarrow> g (f x) = x\"\n    and oo: \"\\<And>U. openin (top_of_set S) U \\<Longrightarrow> openin (top_of_set T) (f ` U)\"\n  shows \"continuous_on T g\"\nproof -\n  from imf injf have gTS: \"g ` T = S\"\n    by force\n  from imf injf have fU: \"U \\<subseteq> S \\<Longrightarrow> (f ` U) = T \\<inter> g -` U\" for U\n    by force\n  show ?thesis\n    by (simp add: continuous_on_open [of T g] gTS) (metis openin_imp_subset fU oo)\nqed\n\nlemma continuous_on_inverse_closed_map:\n  assumes contf: \"continuous_on S f\"\n    and imf: \"f ` S = T\"\n    and injf: \"\\<And>x. x \\<in> S \\<Longrightarrow> g(f x) = x\"\n    and oo: \"\\<And>U. closedin (top_of_set S) U \\<Longrightarrow> closedin (top_of_set T) (f ` U)\"\n  shows \"continuous_on T g\"\nproof -\n  from imf injf have gTS: \"g ` T = S\"\n    by force\n  from imf injf have fU: \"U \\<subseteq> S \\<Longrightarrow> (f ` U) = T \\<inter> g -` U\" for U\n    by force\n  show ?thesis\n    by (simp add: continuous_on_closed [of T g] gTS) (metis closedin_imp_subset fU oo)\nqed\n\nlemma homeomorphism_injective_open_map:\n  assumes contf: \"continuous_on S f\"\n    and imf: \"f ` S = T\"\n    and injf: \"inj_on f S\"\n    and oo: \"\\<And>U. openin (top_of_set S) U \\<Longrightarrow> openin (top_of_set T) (f ` U)\"\n  obtains g where \"homeomorphism S T f g\"\nproof\n  have \"continuous_on T (inv_into S f)\"\n    by (metis contf continuous_on_inverse_open_map imf injf inv_into_f_f oo)\n  with imf injf contf show \"homeomorphism S T f (inv_into S f)\"\n    by (auto simp: homeomorphism_def)\nqed\n\nlemma homeomorphism_injective_closed_map:\n  assumes contf: \"continuous_on S f\"\n    and imf: \"f ` S = T\"\n    and injf: \"inj_on f S\"\n    and oo: \"\\<And>U. closedin (top_of_set S) U \\<Longrightarrow> closedin (top_of_set T) (f ` U)\"\n  obtains g where \"homeomorphism S T f g\"\nproof\n  have \"continuous_on T (inv_into S f)\"\n    by (metis contf continuous_on_inverse_closed_map imf injf inv_into_f_f oo)\n  with imf injf contf show \"homeomorphism S T f (inv_into S f)\"\n    by (auto simp: homeomorphism_def)\nqed\n\nlemma homeomorphism_imp_open_map:\n  assumes hom: \"homeomorphism S T f g\"\n    and oo: \"openin (top_of_set S) U\"\n  shows \"openin (top_of_set T) (f ` U)\"\nproof -\n  from hom oo have [simp]: \"f ` U = T \\<inter> g -` U\"\n    using openin_subset by (fastforce simp: homeomorphism_def rev_image_eqI)\n  from hom have \"continuous_on T g\"\n    unfolding homeomorphism_def by blast\n  moreover have \"g ` T = S\"\n    by (metis hom homeomorphism_def)\n  ultimately show ?thesis\n    by (simp add: continuous_on_open oo)\nqed\n\nlemma homeomorphism_imp_closed_map:\n  assumes hom: \"homeomorphism S T f g\"\n    and oo: \"closedin (top_of_set S) U\"\n  shows \"closedin (top_of_set T) (f ` U)\"\nproof -\n  from hom oo have [simp]: \"f ` U = T \\<inter> g -` U\"\n    using closedin_subset by (fastforce simp: homeomorphism_def rev_image_eqI)\n  from hom have \"continuous_on T g\"\n    unfolding homeomorphism_def by blast\n  moreover have \"g ` T = S\"\n    by (metis hom homeomorphism_def)\n  ultimately show ?thesis\n    by (simp add: continuous_on_closed oo)\nqed\n\nsubsection\\<^marker>\\<open>tag unimportant\\<close> \\<open>Seperability\\<close>\n\nlemma subset_second_countable:\n  obtains \\<B> :: \"'a:: second_countable_topology set set\"\n    where \"countable \\<B>\"\n          \"{} \\<notin> \\<B>\"\n          \"\\<And>C. C \\<in> \\<B> \\<Longrightarrow> openin(top_of_set S) C\"\n          \"\\<And>T. openin(top_of_set S) T \\<Longrightarrow> \\<exists>\\<U>. \\<U> \\<subseteq> \\<B> \\<and> T = \\<Union>\\<U>\"\nproof -\n  obtain \\<B> :: \"'a set set\"\n    where \"countable \\<B>\"\n      and opeB: \"\\<And>C. C \\<in> \\<B> \\<Longrightarrow> openin(top_of_set S) C\"\n      and \\<B>:    \"\\<And>T. openin(top_of_set S) T \\<Longrightarrow> \\<exists>\\<U>. \\<U> \\<subseteq> \\<B> \\<and> T = \\<Union>\\<U>\"\n  proof -\n    obtain \\<C> :: \"'a set set\"\n      where \"countable \\<C>\" and ope: \"\\<And>C. C \\<in> \\<C> \\<Longrightarrow> open C\"\n        and \\<C>: \"\\<And>S. open S \\<Longrightarrow> \\<exists>U. U \\<subseteq> \\<C> \\<and> S = \\<Union>U\"\n      by (metis univ_second_countable that)\n    show ?thesis\n    proof\n      show \"countable ((\\<lambda>C. S \\<inter> C) ` \\<C>)\"\n        by (simp add: \\<open>countable \\<C>\\<close>)\n      show \"\\<And>C. C \\<in> (\\<inter>) S ` \\<C> \\<Longrightarrow> openin (top_of_set S) C\"\n        using ope by auto\n      show \"\\<And>T. openin (top_of_set S) T \\<Longrightarrow> \\<exists>\\<U>\\<subseteq>(\\<inter>) S ` \\<C>. T = \\<Union>\\<U>\"\n        by (metis \\<C> image_mono inf_Sup openin_open)\n    qed\n  qed\n  show ?thesis\n  proof\n    show \"countable (\\<B> - {{}})\"\n      using \\<open>countable \\<B>\\<close> by blast\n    show \"\\<And>C. \\<lbrakk>C \\<in> \\<B> - {{}}\\<rbrakk> \\<Longrightarrow> openin (top_of_set S) C\"\n      by (simp add: \\<open>\\<And>C. C \\<in> \\<B> \\<Longrightarrow> openin (top_of_set S) C\\<close>)\n    show \"\\<exists>\\<U>\\<subseteq>\\<B> - {{}}. T = \\<Union>\\<U>\" if \"openin (top_of_set S) T\" for T\n      using \\<B> [OF that]\n      apply clarify\n      apply (rule_tac x=\"\\<U> - {{}}\" in exI, auto)\n        done\n  qed auto\nqed\n\nlemma Lindelof_openin:\n  fixes \\<F> :: \"'a::second_countable_topology set set\"\n  assumes \"\\<And>S. S \\<in> \\<F> \\<Longrightarrow> openin (top_of_set U) S\"\n  obtains \\<F>' where \"\\<F>' \\<subseteq> \\<F>\" \"countable \\<F>'\" \"\\<Union>\\<F>' = \\<Union>\\<F>\"\nproof -\n  have \"\\<And>S. S \\<in> \\<F> \\<Longrightarrow> \\<exists>T. open T \\<and> S = U \\<inter> T\"\n    using assms by (simp add: openin_open)\n  then obtain tf where tf: \"\\<And>S. S \\<in> \\<F> \\<Longrightarrow> open (tf S) \\<and> (S = U \\<inter> tf S)\"\n    by metis\n  have [simp]: \"\\<And>\\<F>'. \\<F>' \\<subseteq> \\<F> \\<Longrightarrow> \\<Union>\\<F>' = U \\<inter> \\<Union>(tf ` \\<F>')\"\n    using tf by fastforce\n  obtain \\<G> where \"countable \\<G> \\<and> \\<G> \\<subseteq> tf ` \\<F>\" \"\\<Union>\\<G> = \\<Union>(tf ` \\<F>)\"\n    using tf by (force intro: Lindelof [of \"tf ` \\<F>\"])\n  then obtain \\<F>' where \\<F>': \"\\<F>' \\<subseteq> \\<F>\" \"countable \\<F>'\" \"\\<Union>\\<F>' = \\<Union>\\<F>\"\n    by (clarsimp simp add: countable_subset_image)\n  then show ?thesis ..\nqed\n\n\nsubsection\\<^marker>\\<open>tag unimportant\\<close>\\<open>Closed Maps\\<close>\n\nlemma continuous_imp_closed_map:\n  fixes f :: \"'a::t2_space \\<Rightarrow> 'b::t2_space\"\n  assumes \"closedin (top_of_set S) U\"\n          \"continuous_on S f\" \"f ` S = T\" \"compact S\"\n    shows \"closedin (top_of_set T) (f ` U)\"\n  by (metis assms closedin_compact_eq compact_continuous_image continuous_on_subset subset_image_iff)\n\nlemma closed_map_restrict:\n  assumes cloU: \"closedin (top_of_set (S \\<inter> f -` T')) U\"\n    and cc: \"\\<And>U. closedin (top_of_set S) U \\<Longrightarrow> closedin (top_of_set T) (f ` U)\"\n    and \"T' \\<subseteq> T\"\n  shows \"closedin (top_of_set T') (f ` U)\"\nproof -\n  obtain V where \"closed V\" \"U = S \\<inter> f -` T' \\<inter> V\"\n    using cloU by (auto simp: closedin_closed)\n  with cc [of \"S \\<inter> V\"] \\<open>T' \\<subseteq> T\\<close> show ?thesis\n    by (fastforce simp add: closedin_closed)\nqed\n\nsubsection\\<^marker>\\<open>tag unimportant\\<close>\\<open>Open Maps\\<close>\n\nlemma open_map_restrict:\n  assumes opeU: \"openin (top_of_set (S \\<inter> f -` T')) U\"\n    and oo: \"\\<And>U. openin (top_of_set S) U \\<Longrightarrow> openin (top_of_set T) (f ` U)\"\n    and \"T' \\<subseteq> T\"\n  shows \"openin (top_of_set T') (f ` U)\"\nproof -\n  obtain V where \"open V\" \"U = S \\<inter> f -` T' \\<inter> V\"\n    using opeU by (auto simp: openin_open)\n  with oo [of \"S \\<inter> V\"] \\<open>T' \\<subseteq> T\\<close> show ?thesis\n    by (fastforce simp add: openin_open)\nqed\n\n\nsubsection\\<^marker>\\<open>tag unimportant\\<close>\\<open>Quotient maps\\<close>\n\nlemma quotient_map_imp_continuous_open:\n  assumes T: \"f ` S \\<subseteq> T\"\n      and ope: \"\\<And>U. U \\<subseteq> T\n              \\<Longrightarrow> (openin (top_of_set S) (S \\<inter> f -` U) \\<longleftrightarrow>\n                   openin (top_of_set T) U)\"\n    shows \"continuous_on S f\"\nproof -\n  have [simp]: \"S \\<inter> f -` f ` S = S\" by auto\n  show ?thesis\n    by (meson T continuous_on_open_gen ope openin_imp_subset)\nqed\n\nlemma quotient_map_imp_continuous_closed:\n  assumes T: \"f ` S \\<subseteq> T\"\n      and ope: \"\\<And>U. U \\<subseteq> T\n                  \\<Longrightarrow> (closedin (top_of_set S) (S \\<inter> f -` U) \\<longleftrightarrow>\n                       closedin (top_of_set T) U)\"\n    shows \"continuous_on S f\"\nproof -\n  have [simp]: \"S \\<inter> f -` f ` S = S\" by auto\n  show ?thesis\n    by (meson T closedin_imp_subset continuous_on_closed_gen ope)\nqed\n\nlemma open_map_imp_quotient_map:\n  assumes contf: \"continuous_on S f\"\n      and T: \"T \\<subseteq> f ` S\"\n      and ope: \"\\<And>T. openin (top_of_set S) T\n                   \\<Longrightarrow> openin (top_of_set (f ` S)) (f ` T)\"\n    shows \"openin (top_of_set S) (S \\<inter> f -` T) =\n           openin (top_of_set (f ` S)) T\"\nproof -\n  have \"T = f ` (S \\<inter> f -` T)\"\n    using T by blast\n  then show ?thesis\n    using \"ope\" contf continuous_on_open by metis\nqed\n\nlemma closed_map_imp_quotient_map:\n  assumes contf: \"continuous_on S f\"\n      and T: \"T \\<subseteq> f ` S\"\n      and ope: \"\\<And>T. closedin (top_of_set S) T\n              \\<Longrightarrow> closedin (top_of_set (f ` S)) (f ` T)\"\n    shows \"openin (top_of_set S) (S \\<inter> f -` T) \\<longleftrightarrow>\n           openin (top_of_set (f ` S)) T\"\n          (is \"?lhs = ?rhs\")\nproof\n  assume ?lhs\n  then have *: \"closedin (top_of_set S) (S - (S \\<inter> f -` T))\"\n    using closedin_diff by fastforce\n  have [simp]: \"(f ` S - f ` (S - (S \\<inter> f -` T))) = T\"\n    using T by blast\n  show ?rhs\n    using ope [OF *, unfolded closedin_def] by auto\nnext\n  assume ?rhs\n  with contf show ?lhs\n    by (auto simp: continuous_on_open)\nqed\n\nlemma continuous_right_inverse_imp_quotient_map:\n  assumes contf: \"continuous_on S f\" and imf: \"f ` S \\<subseteq> T\"\n      and contg: \"continuous_on T g\" and img: \"g ` T \\<subseteq> S\"\n      and fg [simp]: \"\\<And>y. y \\<in> T \\<Longrightarrow> f(g y) = y\"\n      and U: \"U \\<subseteq> T\"\n    shows \"openin (top_of_set S) (S \\<inter> f -` U) \\<longleftrightarrow>\n           openin (top_of_set T) U\"\n          (is \"?lhs = ?rhs\")\nproof -\n  have f: \"\\<And>Z. openin (top_of_set (f ` S)) Z \\<Longrightarrow>\n                openin (top_of_set S) (S \\<inter> f -` Z)\"\n  and  g: \"\\<And>Z. openin (top_of_set (g ` T)) Z \\<Longrightarrow>\n                openin (top_of_set T) (T \\<inter> g -` Z)\"\n    using contf contg by (auto simp: continuous_on_open)\n  show ?thesis\n  proof\n    have \"T \\<inter> g -` (g ` T \\<inter> (S \\<inter> f -` U)) = {x \\<in> T. f (g x) \\<in> U}\"\n      using imf img by blast\n    also have \"... = U\"\n      using U by auto\n    finally have eq: \"T \\<inter> g -` (g ` T \\<inter> (S \\<inter> f -` U)) = U\" .\n    assume ?lhs\n    then have *: \"openin (top_of_set (g ` T)) (g ` T \\<inter> (S \\<inter> f -` U))\"\n      by (meson img openin_Int openin_subtopology_Int_subset openin_subtopology_self)\n    show ?rhs\n      using g [OF *] eq by auto\n  next\n    assume rhs: ?rhs\n    show ?lhs\n      by (metis f fg image_eqI image_subset_iff imf img openin_subopen openin_subtopology_self openin_trans rhs)\n  qed\nqed\n\nlemma continuous_left_inverse_imp_quotient_map:\n  assumes \"continuous_on S f\"\n      and \"continuous_on (f ` S) g\"\n      and  \"\\<And>x. x \\<in> S \\<Longrightarrow> g(f x) = x\"\n      and \"U \\<subseteq> f ` S\"\n    shows \"openin (top_of_set S) (S \\<inter> f -` U) \\<longleftrightarrow>\n           openin (top_of_set (f ` S)) U\"\napply (rule continuous_right_inverse_imp_quotient_map)\nusing assms apply force+\ndone\n\nlemma continuous_imp_quotient_map:\n  fixes f :: \"'a::t2_space \\<Rightarrow> 'b::t2_space\"\n  assumes \"continuous_on S f\" \"f ` S = T\" \"compact S\" \"U \\<subseteq> T\"\n    shows \"openin (top_of_set S) (S \\<inter> f -` U) \\<longleftrightarrow>\n           openin (top_of_set T) U\"\n  by (metis (no_types, lifting) assms closed_map_imp_quotient_map continuous_imp_closed_map)\n\nsubsection\\<^marker>\\<open>tag unimportant\\<close>\\<open>Pasting lemmas for functions, for of casewise definitions\\<close>\n\nsubsubsection\\<open>on open sets\\<close>\n\nlemma pasting_lemma:\n  assumes ope: \"\\<And>i. i \\<in> I \\<Longrightarrow> openin X (T i)\"\n      and cont: \"\\<And>i. i \\<in> I \\<Longrightarrow> continuous_map(subtopology X (T i)) Y (f i)\"\n      and f: \"\\<And>i j x. \\<lbrakk>i \\<in> I; j \\<in> I; x \\<in> topspace X \\<inter> T i \\<inter> T j\\<rbrakk> \\<Longrightarrow> f i x = f j x\"\n      and g: \"\\<And>x. x \\<in> topspace X \\<Longrightarrow> \\<exists>j. j \\<in> I \\<and> x \\<in> T j \\<and> g x = f j x\"\n    shows \"continuous_map X Y g\"\n  unfolding continuous_map_openin_preimage_eq\nproof (intro conjI allI impI)\n  show \"g ` topspace X \\<subseteq> topspace Y\"\n    using g cont continuous_map_image_subset_topspace by fastforce\nnext\n  fix U\n  assume Y: \"openin Y U\"\n  have T: \"T i \\<subseteq> topspace X\" if \"i \\<in> I\" for i\n    using ope by (simp add: openin_subset that)\n  have *: \"topspace X \\<inter> g -` U = (\\<Union>i \\<in> I. T i \\<inter> f i -` U)\"\n    using f g T by fastforce\n  have \"\\<And>i. i \\<in> I \\<Longrightarrow> openin X (T i \\<inter> f i -` U)\"\n    using cont unfolding continuous_map_openin_preimage_eq\n    by (metis Y T inf.commute inf_absorb1 ope topspace_subtopology openin_trans_full)\n  then show \"openin X (topspace X \\<inter> g -` U)\"\n    by (auto simp: *)\nqed\n\nlemma pasting_lemma_exists:\n  assumes X: \"topspace X \\<subseteq> (\\<Union>i \\<in> I. T i)\"\n      and ope: \"\\<And>i. i \\<in> I \\<Longrightarrow> openin X (T i)\"\n      and cont: \"\\<And>i. i \\<in> I \\<Longrightarrow> continuous_map (subtopology X (T i)) Y (f i)\"\n      and f: \"\\<And>i j x. \\<lbrakk>i \\<in> I; j \\<in> I; x \\<in> topspace X \\<inter> T i \\<inter> T j\\<rbrakk> \\<Longrightarrow> f i x = f j x\"\n    obtains g where \"continuous_map X Y g\" \"\\<And>x i. \\<lbrakk>i \\<in> I; x \\<in> topspace X \\<inter> T i\\<rbrakk> \\<Longrightarrow> g x = f i x\"\nproof\n  let ?h = \"\\<lambda>x. f (SOME i. i \\<in> I \\<and> x \\<in> T i) x\"\n  show \"continuous_map X Y ?h\"\n    apply (rule pasting_lemma [OF ope cont])\n     apply (blast intro: f)+\n    by (metis (no_types, lifting) UN_E X subsetD someI_ex)\n  show \"f (SOME i. i \\<in> I \\<and> x \\<in> T i) x = f i x\" if \"i \\<in> I\" \"x \\<in> topspace X \\<inter> T i\" for i x\n    by (metis (no_types, lifting) IntD2 IntI f someI_ex that)\nqed\n\nlemma pasting_lemma_locally_finite:\n  assumes fin: \"\\<And>x. x \\<in> topspace X \\<Longrightarrow> \\<exists>V. openin X V \\<and> x \\<in> V \\<and> finite {i \\<in> I. T i \\<inter> V \\<noteq> {}}\"\n    and clo: \"\\<And>i. i \\<in> I \\<Longrightarrow> closedin X (T i)\"\n    and cont:  \"\\<And>i. i \\<in> I \\<Longrightarrow> continuous_map(subtopology X (T i)) Y (f i)\"\n    and f: \"\\<And>i j x. \\<lbrakk>i \\<in> I; j \\<in> I; x \\<in> topspace X \\<inter> T i \\<inter> T j\\<rbrakk> \\<Longrightarrow> f i x = f j x\"\n    and g: \"\\<And>x. x \\<in> topspace X \\<Longrightarrow> \\<exists>j. j \\<in> I \\<and> x \\<in> T j \\<and> g x = f j x\"\n  shows \"continuous_map X Y g\"\n  unfolding continuous_map_closedin_preimage_eq\nproof (intro conjI allI impI)\n  show \"g ` topspace X \\<subseteq> topspace Y\"\n    using g cont continuous_map_image_subset_topspace by fastforce\nnext\n  fix U\n  assume Y: \"closedin Y U\"\n  have T: \"T i \\<subseteq> topspace X\" if \"i \\<in> I\" for i\n    using clo by (simp add: closedin_subset that)\n  have *: \"topspace X \\<inter> g -` U = (\\<Union>i \\<in> I. T i \\<inter> f i -` U)\"\n    using f g T by fastforce\n  have cTf: \"\\<And>i. i \\<in> I \\<Longrightarrow> closedin X (T i \\<inter> f i -` U)\"\n    using cont unfolding continuous_map_closedin_preimage_eq topspace_subtopology\n    by (simp add: Int_absorb1 T Y clo closedin_closed_subtopology)\n  have sub: \"{Z \\<in> (\\<lambda>i. T i \\<inter> f i -` U) ` I. Z \\<inter> V \\<noteq> {}}\n           \\<subseteq> (\\<lambda>i. T i \\<inter> f i -` U) ` {i \\<in> I. T i \\<inter> V \\<noteq> {}}\" for V\n    by auto\n  have 1: \"(\\<Union>i\\<in>I. T i \\<inter> f i -` U) \\<subseteq> topspace X\"\n    using T by blast\n  then have lf: \"locally_finite_in X ((\\<lambda>i. T i \\<inter> f i -` U) ` I)\"\n    unfolding locally_finite_in_def\n    using finite_subset [OF sub] fin by force\n  show \"closedin X (topspace X \\<inter> g -` U)\"\n    apply (subst *)\n    apply (rule closedin_locally_finite_Union)\n     apply (auto intro: cTf lf)\n    done\nqed\n\nsubsubsection\\<open>Likewise on closed sets, with a finiteness assumption\\<close>\n\nlemma pasting_lemma_closed:\n  assumes fin: \"finite I\"\n    and clo: \"\\<And>i. i \\<in> I \\<Longrightarrow> closedin X (T i)\"\n    and cont:  \"\\<And>i. i \\<in> I \\<Longrightarrow> continuous_map(subtopology X (T i)) Y (f i)\"\n    and f: \"\\<And>i j x. \\<lbrakk>i \\<in> I; j \\<in> I; x \\<in> topspace X \\<inter> T i \\<inter> T j\\<rbrakk> \\<Longrightarrow> f i x = f j x\"\n    and g: \"\\<And>x. x \\<in> topspace X \\<Longrightarrow> \\<exists>j. j \\<in> I \\<and> x \\<in> T j \\<and> g x = f j x\"\n  shows \"continuous_map X Y g\"\n  using pasting_lemma_locally_finite [OF _ clo cont f g] fin by auto\n\nlemma pasting_lemma_exists_locally_finite:\n  assumes fin: \"\\<And>x. x \\<in> topspace X \\<Longrightarrow> \\<exists>V. openin X V \\<and> x \\<in> V \\<and> finite {i \\<in> I. T i \\<inter> V \\<noteq> {}}\"\n    and X: \"topspace X \\<subseteq> \\<Union>(T ` I)\"\n    and clo: \"\\<And>i. i \\<in> I \\<Longrightarrow> closedin X (T i)\"\n    and cont:  \"\\<And>i. i \\<in> I \\<Longrightarrow> continuous_map(subtopology X (T i)) Y (f i)\"\n    and f: \"\\<And>i j x. \\<lbrakk>i \\<in> I; j \\<in> I; x \\<in> topspace X \\<inter> T i \\<inter> T j\\<rbrakk> \\<Longrightarrow> f i x = f j x\"\n    and g: \"\\<And>x. x \\<in> topspace X \\<Longrightarrow> \\<exists>j. j \\<in> I \\<and> x \\<in> T j \\<and> g x = f j x\"\n  obtains g where \"continuous_map X Y g\" \"\\<And>x i. \\<lbrakk>i \\<in> I; x \\<in> topspace X \\<inter> T i\\<rbrakk> \\<Longrightarrow> g x = f i x\"\nproof\n  show \"continuous_map X Y (\\<lambda>x. f(@i. i \\<in> I \\<and> x \\<in> T i) x)\"\n    apply (rule pasting_lemma_locally_finite [OF fin])\n        apply (blast intro: assms)+\n    by (metis (no_types, lifting) UN_E X set_rev_mp someI_ex)\nnext\n  fix x i\n  assume \"i \\<in> I\" and \"x \\<in> topspace X \\<inter> T i\"\n  show \"f (SOME i. i \\<in> I \\<and> x \\<in> T i) x = f i x\"\n    apply (rule someI2_ex)\n    using \\<open>i \\<in> I\\<close> \\<open>x \\<in> topspace X \\<inter> T i\\<close> apply blast\n    by (meson Int_iff \\<open>i \\<in> I\\<close> \\<open>x \\<in> topspace X \\<inter> T i\\<close> f)\nqed\n\nlemma pasting_lemma_exists_closed:\n  assumes fin: \"finite I\"\n    and X: \"topspace X \\<subseteq> \\<Union>(T ` I)\"\n    and clo: \"\\<And>i. i \\<in> I \\<Longrightarrow> closedin X (T i)\"\n    and cont:  \"\\<And>i. i \\<in> I \\<Longrightarrow> continuous_map(subtopology X (T i)) Y (f i)\"\n    and f: \"\\<And>i j x. \\<lbrakk>i \\<in> I; j \\<in> I; x \\<in> topspace X \\<inter> T i \\<inter> T j\\<rbrakk> \\<Longrightarrow> f i x = f j x\"\n  obtains g where \"continuous_map X Y g\" \"\\<And>x i. \\<lbrakk>i \\<in> I; x \\<in> topspace X \\<inter> T i\\<rbrakk> \\<Longrightarrow> g x = f i x\"\nproof\n  show \"continuous_map X Y (\\<lambda>x. f (SOME i. i \\<in> I \\<and> x \\<in> T i) x)\"\n    apply (rule pasting_lemma_closed [OF \\<open>finite I\\<close> clo cont])\n     apply (blast intro: f)+\n    by (metis (mono_tags, lifting) UN_iff X someI_ex subset_iff)\nnext\n  fix x i\n  assume \"i \\<in> I\" \"x \\<in> topspace X \\<inter> T i\"\n  then show \"f (SOME i. i \\<in> I \\<and> x \\<in> T i) x = f i x\"\n    by (metis (no_types, lifting) IntD2 IntI f someI_ex)\nqed\n\nlemma continuous_map_cases:\n  assumes f: \"continuous_map (subtopology X (X closure_of {x. P x})) Y f\"\n      and g: \"continuous_map (subtopology X (X closure_of {x. \\<not> P x})) Y g\"\n      and fg: \"\\<And>x. x \\<in> X frontier_of {x. P x} \\<Longrightarrow> f x = g x\"\n  shows \"continuous_map X Y (\\<lambda>x. if P x then f x else g x)\"\nproof (rule pasting_lemma_closed)\n  let ?f = \"\\<lambda>b. if b then f else g\"\n  let ?g = \"\\<lambda>x. if P x then f x else g x\"\n  let ?T = \"\\<lambda>b. if b then X closure_of {x. P x} else X closure_of {x. ~P x}\"\n  show \"finite {True,False}\" by auto\n  have eq: \"topspace X - Collect P = topspace X \\<inter> {x. \\<not> P x}\"\n    by blast\n  show \"?f i x = ?f j x\"\n    if \"i \\<in> {True,False}\" \"j \\<in> {True,False}\" and x: \"x \\<in> topspace X \\<inter> ?T i \\<inter> ?T j\" for i j x\n  proof -\n    have \"f x = g x\"\n      if \"i\" \"\\<not> j\"\n      apply (rule fg)\n      unfolding frontier_of_closures eq\n      using x that closure_of_restrict by fastforce\n    moreover\n    have \"g x = f x\"\n      if \"x \\<in> X closure_of {x. \\<not> P x}\" \"x \\<in> X closure_of Collect P\" \"\\<not> i\" \"j\" for x\n        apply (rule fg [symmetric])\n        unfolding frontier_of_closures eq\n        using x that closure_of_restrict by fastforce\n    ultimately show ?thesis\n      using that by (auto simp flip: closure_of_restrict)\n  qed\n  show \"\\<exists>j. j \\<in> {True,False} \\<and> x \\<in> ?T j \\<and> (if P x then f x else g x) = ?f j x\"\n    if \"x \\<in> topspace X\" for x\n    apply simp\n    apply safe\n    apply (metis Int_iff closure_of inf_sup_absorb mem_Collect_eq that)\n    by (metis DiffI eq closure_of_subset_Int contra_subsetD mem_Collect_eq that)\nqed (auto simp: f g)\n\nlemma continuous_map_cases_alt:\n  assumes f: \"continuous_map (subtopology X (X closure_of {x \\<in> topspace X. P x})) Y f\"\n      and g: \"continuous_map (subtopology X (X closure_of {x \\<in> topspace X. ~P x})) Y g\"\n      and fg: \"\\<And>x. x \\<in> X frontier_of {x \\<in> topspace X. P x} \\<Longrightarrow> f x = g x\"\n    shows \"continuous_map X Y (\\<lambda>x. if P x then f x else g x)\"\n  apply (rule continuous_map_cases)\n  using assms\n    apply (simp_all add: Collect_conj_eq closure_of_restrict [symmetric] frontier_of_restrict [symmetric])\n  done\n\nlemma continuous_map_cases_function:\n  assumes contp: \"continuous_map X Z p\"\n    and contf: \"continuous_map (subtopology X {x \\<in> topspace X. p x \\<in> Z closure_of U}) Y f\"\n    and contg: \"continuous_map (subtopology X {x \\<in> topspace X. p x \\<in> Z closure_of (topspace Z - U)}) Y g\"\n    and fg: \"\\<And>x. \\<lbrakk>x \\<in> topspace X; p x \\<in> Z frontier_of U\\<rbrakk> \\<Longrightarrow> f x = g x\"\n  shows \"continuous_map X Y (\\<lambda>x. if p x \\<in> U then f x else g x)\"\nproof (rule continuous_map_cases_alt)\n  show \"continuous_map (subtopology X (X closure_of {x \\<in> topspace X. p x \\<in> U})) Y f\"\n  proof (rule continuous_map_from_subtopology_mono)\n    let ?T = \"{x \\<in> topspace X. p x \\<in> Z closure_of U}\"\n    show \"continuous_map (subtopology X ?T) Y f\"\n      by (simp add: contf)\n    show \"X closure_of {x \\<in> topspace X. p x \\<in> U} \\<subseteq> ?T\"\n      by (rule continuous_map_closure_preimage_subset [OF contp])\n  qed\n  show \"continuous_map (subtopology X (X closure_of {x \\<in> topspace X. p x \\<notin> U})) Y g\"\n  proof (rule continuous_map_from_subtopology_mono)\n    let ?T = \"{x \\<in> topspace X. p x \\<in> Z closure_of (topspace Z - U)}\"\n    show \"continuous_map (subtopology X ?T) Y g\"\n      by (simp add: contg)\n    have \"X closure_of {x \\<in> topspace X. p x \\<notin> U} \\<subseteq> X closure_of {x \\<in> topspace X. p x \\<in> topspace Z - U}\"\n      apply (rule closure_of_mono)\n      using continuous_map_closedin contp by fastforce\n    then show \"X closure_of {x \\<in> topspace X. p x \\<notin> U} \\<subseteq> ?T\"\n      by (rule order_trans [OF _ continuous_map_closure_preimage_subset [OF contp]])\n  qed\nnext\n  show \"f x = g x\" if \"x \\<in> X frontier_of {x \\<in> topspace X. p x \\<in> U}\" for x\n    using that continuous_map_frontier_frontier_preimage_subset [OF contp, of U] fg by blast\nqed\n\nsubsection \\<open>Retractions\\<close>\n\ndefinition\\<^marker>\\<open>tag important\\<close> retraction :: \"('a::topological_space) set \\<Rightarrow> 'a set \\<Rightarrow> ('a \\<Rightarrow> 'a) \\<Rightarrow> bool\"\nwhere \"retraction S T r \\<longleftrightarrow>\n  T \\<subseteq> S \\<and> continuous_on S r \\<and> r ` S \\<subseteq> T \\<and> (\\<forall>x\\<in>T. r x = x)\"\n\ndefinition\\<^marker>\\<open>tag important\\<close> retract_of (infixl \"retract'_of\" 50) where\n\"T retract_of S  \\<longleftrightarrow>  (\\<exists>r. retraction S T r)\"\n\nlemma retraction_idempotent: \"retraction S T r \\<Longrightarrow> x \\<in> S \\<Longrightarrow>  r (r x) = r x\"\n  unfolding retraction_def by auto\n\ntext \\<open>Preservation of fixpoints under (more general notion of) retraction\\<close>\n\nlemma invertible_fixpoint_property:\n  fixes S :: \"'a::topological_space set\"\n    and T :: \"'b::topological_space set\"\n  assumes contt: \"continuous_on T i\"\n    and \"i ` T \\<subseteq> S\"\n    and contr: \"continuous_on S r\"\n    and \"r ` S \\<subseteq> T\"\n    and ri: \"\\<And>y. y \\<in> T \\<Longrightarrow> r (i y) = y\"\n    and FP: \"\\<And>f. \\<lbrakk>continuous_on S f; f ` S \\<subseteq> S\\<rbrakk> \\<Longrightarrow> \\<exists>x\\<in>S. f x = x\"\n    and contg: \"continuous_on T g\"\n    and \"g ` T \\<subseteq> T\"\n  obtains y where \"y \\<in> T\" and \"g y = y\"\nproof -\n  have \"\\<exists>x\\<in>S. (i \\<circ> g \\<circ> r) x = x\"\n  proof (rule FP)\n    show \"continuous_on S (i \\<circ> g \\<circ> r)\"\n      by (meson contt contr assms(4) contg assms(8) continuous_on_compose continuous_on_subset)\n    show \"(i \\<circ> g \\<circ> r) ` S \\<subseteq> S\"\n      using assms(2,4,8) by force\n  qed\n  then obtain x where x: \"x \\<in> S\" \"(i \\<circ> g \\<circ> r) x = x\" ..\n  then have *: \"g (r x) \\<in> T\"\n    using assms(4,8) by auto\n  have \"r ((i \\<circ> g \\<circ> r) x) = r x\"\n    using x by auto\n  then show ?thesis\n    using \"*\" ri that by auto\nqed\n\nlemma homeomorphic_fixpoint_property:\n  fixes S :: \"'a::topological_space set\"\n    and T :: \"'b::topological_space set\"\n  assumes \"S homeomorphic T\"\n  shows \"(\\<forall>f. continuous_on S f \\<and> f ` S \\<subseteq> S \\<longrightarrow> (\\<exists>x\\<in>S. f x = x)) \\<longleftrightarrow>\n         (\\<forall>g. continuous_on T g \\<and> g ` T \\<subseteq> T \\<longrightarrow> (\\<exists>y\\<in>T. g y = y))\"\n         (is \"?lhs = ?rhs\")\nproof -\n  obtain r i where r:\n      \"\\<forall>x\\<in>S. i (r x) = x\" \"r ` S = T\" \"continuous_on S r\"\n      \"\\<forall>y\\<in>T. r (i y) = y\" \"i ` T = S\" \"continuous_on T i\"\n    using assms unfolding homeomorphic_def homeomorphism_def  by blast\n  show ?thesis\n  proof\n    assume ?lhs\n    with r show ?rhs\n      by (metis invertible_fixpoint_property[of T i S r] order_refl)\n  next\n    assume ?rhs\n    with r show ?lhs\n      by (metis invertible_fixpoint_property[of S r T i] order_refl)\n  qed\nqed\n\nlemma retract_fixpoint_property:\n  fixes f :: \"'a::topological_space \\<Rightarrow> 'b::topological_space\"\n    and S :: \"'a set\"\n  assumes \"T retract_of S\"\n    and FP: \"\\<And>f. \\<lbrakk>continuous_on S f; f ` S \\<subseteq> S\\<rbrakk> \\<Longrightarrow> \\<exists>x\\<in>S. f x = x\"\n    and contg: \"continuous_on T g\"\n    and \"g ` T \\<subseteq> T\"\n  obtains y where \"y \\<in> T\" and \"g y = y\"\nproof -\n  obtain h where \"retraction S T h\"\n    using assms(1) unfolding retract_of_def ..\n  then show ?thesis\n    unfolding retraction_def\n    using invertible_fixpoint_property[OF continuous_on_id _ _ _ _ FP]\n    by (metis assms(4) contg image_ident that)\nqed\n\nlemma retraction:\n  \"retraction S T r \\<longleftrightarrow>\n    T \\<subseteq> S \\<and> continuous_on S r \\<and> r ` S = T \\<and> (\\<forall>x \\<in> T. r x = x)\"\n  by (force simp: retraction_def)\n\nlemma retractionE: \\<comment> \\<open>yields properties normalized wrt. simp -- less likely to loop\\<close>\n  assumes \"retraction S T r\"\n  obtains \"T = r ` S\" \"r ` S \\<subseteq> S\" \"continuous_on S r\" \"\\<And>x. x \\<in> S \\<Longrightarrow> r (r x) = r x\"\nproof (rule that)\n  from retraction [of S T r] assms\n  have \"T \\<subseteq> S\" \"continuous_on S r\" \"r ` S = T\" and \"\\<forall>x \\<in> T. r x = x\"\n    by simp_all\n  then show \"T = r ` S\" \"r ` S \\<subseteq> S\" \"continuous_on S r\"\n    by simp_all\n  from \\<open>\\<forall>x \\<in> T. r x = x\\<close> have \"r x = x\" if \"x \\<in> T\" for x\n    using that by simp\n  with \\<open>r ` S = T\\<close> show \"r (r x) = r x\" if \"x \\<in> S\" for x\n    using that by auto\nqed\n\nlemma retract_ofE: \\<comment> \\<open>yields properties normalized wrt. simp -- less likely to loop\\<close>\n  assumes \"T retract_of S\"\n  obtains r where \"T = r ` S\" \"r ` S \\<subseteq> S\" \"continuous_on S r\" \"\\<And>x. x \\<in> S \\<Longrightarrow> r (r x) = r x\"\nproof -\n  from assms obtain r where \"retraction S T r\"\n    by (auto simp add: retract_of_def)\n  with that show thesis\n    by (auto elim: retractionE)\nqed\n\nlemma retract_of_imp_extensible:\n  assumes \"S retract_of T\" and \"continuous_on S f\" and \"f ` S \\<subseteq> U\"\n  obtains g where \"continuous_on T g\" \"g ` T \\<subseteq> U\" \"\\<And>x. x \\<in> S \\<Longrightarrow> g x = f x\"\nproof -\n  from \\<open>S retract_of T\\<close> obtain r where \"retraction T S r\"\n    by (auto simp add: retract_of_def)\n  show thesis\n    by (rule that [of \"f \\<circ> r\"])\n      (use \\<open>continuous_on S f\\<close> \\<open>f ` S \\<subseteq> U\\<close> \\<open>retraction T S r\\<close> in \\<open>auto simp: continuous_on_compose2 retraction\\<close>)\nqed\n\nlemma idempotent_imp_retraction:\n  assumes \"continuous_on S f\" and \"f ` S \\<subseteq> S\" and \"\\<And>x. x \\<in> S \\<Longrightarrow> f(f x) = f x\"\n    shows \"retraction S (f ` S) f\"\nby (simp add: assms retraction)\n\nlemma retraction_subset:\n  assumes \"retraction S T r\" and \"T \\<subseteq> s'\" and \"s' \\<subseteq> S\"\n  shows \"retraction s' T r\"\n  unfolding retraction_def\n  by (metis assms continuous_on_subset image_mono retraction)\n\nlemma retract_of_subset:\n  assumes \"T retract_of S\" and \"T \\<subseteq> s'\" and \"s' \\<subseteq> S\"\n    shows \"T retract_of s'\"\nby (meson assms retract_of_def retraction_subset)\n\nlemma retraction_refl [simp]: \"retraction S S (\\<lambda>x. x)\"\nby (simp add: retraction)\n\nlemma retract_of_refl [iff]: \"S retract_of S\"\n  unfolding retract_of_def retraction_def\n  using continuous_on_id by blast\n\nlemma retract_of_imp_subset:\n   \"S retract_of T \\<Longrightarrow> S \\<subseteq> T\"\nby (simp add: retract_of_def retraction_def)\n\nlemma retract_of_empty [simp]:\n     \"({} retract_of S) \\<longleftrightarrow> S = {}\"  \"(S retract_of {}) \\<longleftrightarrow> S = {}\"\nby (auto simp: retract_of_def retraction_def)\n\nlemma retract_of_singleton [iff]: \"({x} retract_of S) \\<longleftrightarrow> x \\<in> S\"\n  unfolding retract_of_def retraction_def by force\n\nlemma retraction_comp:\n   \"\\<lbrakk>retraction S T f; retraction T U g\\<rbrakk>\n        \\<Longrightarrow> retraction S U (g \\<circ> f)\"\napply (auto simp: retraction_def intro: continuous_on_compose2)\nby blast\n\nlemma retract_of_trans [trans]:\n  assumes \"S retract_of T\" and \"T retract_of U\"\n    shows \"S retract_of U\"\nusing assms by (auto simp: retract_of_def intro: retraction_comp)\n\nlemma closedin_retract:\n  fixes S :: \"'a :: t2_space set\"\n  assumes \"S retract_of T\"\n    shows \"closedin (top_of_set T) S\"\nproof -\n  obtain r where r: \"S \\<subseteq> T\" \"continuous_on T r\" \"r ` T \\<subseteq> S\" \"\\<And>x. x \\<in> S \\<Longrightarrow> r x = x\"\n    using assms by (auto simp: retract_of_def retraction_def)\n  have \"S = {x\\<in>T. x = r x}\"\n    using r by auto\n  also have \"\\<dots> = T \\<inter> ((\\<lambda>x. (x, r x)) -` ({y. \\<exists>x. y = (x, x)}))\"\n    unfolding vimage_def mem_Times_iff fst_conv snd_conv\n    using r\n    by auto\n  also have \"closedin (top_of_set T) \\<dots>\"\n    by (rule continuous_closedin_preimage) (auto intro!: closed_diagonal continuous_on_Pair r)\n  finally show ?thesis .\nqed\n\nlemma closedin_self [simp]: \"closedin (top_of_set S) S\"\n  by simp\n\nlemma retract_of_closed:\n    fixes S :: \"'a :: t2_space set\"\n    shows \"\\<lbrakk>closed T; S retract_of T\\<rbrakk> \\<Longrightarrow> closed S\"\n  by (metis closedin_retract closedin_closed_eq)\n\nlemma retract_of_compact:\n     \"\\<lbrakk>compact T; S retract_of T\\<rbrakk> \\<Longrightarrow> compact S\"\n  by (metis compact_continuous_image retract_of_def retraction)\n\nlemma retract_of_connected:\n    \"\\<lbrakk>connected T; S retract_of T\\<rbrakk> \\<Longrightarrow> connected S\"\n  by (metis Topological_Spaces.connected_continuous_image retract_of_def retraction)\n\nlemma retraction_openin_vimage_iff:\n  \"openin (top_of_set S) (S \\<inter> r -` U) \\<longleftrightarrow> openin (top_of_set T) U\"\n  if retraction: \"retraction S T r\" and \"U \\<subseteq> T\"\n  using retraction apply (rule retractionE)\n  apply (rule continuous_right_inverse_imp_quotient_map [where g=r])\n  using \\<open>U \\<subseteq> T\\<close> apply (auto elim: continuous_on_subset)\n  done\n\nlemma retract_of_Times:\n   \"\\<lbrakk>S retract_of s'; T retract_of t'\\<rbrakk> \\<Longrightarrow> (S \\<times> T) retract_of (s' \\<times> t')\"\napply (simp add: retract_of_def retraction_def Sigma_mono, clarify)\napply (rename_tac f g)\napply (rule_tac x=\"\\<lambda>z. ((f \\<circ> fst) z, (g \\<circ> snd) z)\" in exI)\napply (rule conjI continuous_intros | erule continuous_on_subset | force)+\ndone\n\nsubsection\\<open>Retractions on a topological space\\<close>\n\ndefinition retract_of_space :: \"'a set \\<Rightarrow> 'a topology \\<Rightarrow> bool\" (infix \"retract'_of'_space\" 50)\n  where \"S retract_of_space X\n         \\<equiv> S \\<subseteq> topspace X \\<and> (\\<exists>r. continuous_map X (subtopology X S) r \\<and> (\\<forall>x \\<in> S. r x = x))\"\n\nlemma retract_of_space_retraction_maps:\n   \"S retract_of_space X \\<longleftrightarrow> S \\<subseteq> topspace X \\<and> (\\<exists>r. retraction_maps X (subtopology X S) r id)\"\n  by (auto simp: retract_of_space_def retraction_maps_def)\n\nlemma retract_of_space_section_map:\n   \"S retract_of_space X \\<longleftrightarrow> S \\<subseteq> topspace X \\<and> section_map (subtopology X S) X id\"\n  unfolding retract_of_space_def retraction_maps_def section_map_def\n  by (auto simp: continuous_map_from_subtopology)\n\nlemma retract_of_space_imp_subset:\n   \"S retract_of_space X \\<Longrightarrow> S \\<subseteq> topspace X\"\n  by (simp add: retract_of_space_def)\n\nlemma retract_of_space_topspace:\n   \"topspace X retract_of_space X\"\n  using retract_of_space_def by force\n\nlemma retract_of_space_empty [simp]:\n   \"{} retract_of_space X \\<longleftrightarrow> topspace X = {}\"\n  by (auto simp: continuous_map_def retract_of_space_def)\n\nlemma retract_of_space_singleton [simp]:\n  \"{a} retract_of_space X \\<longleftrightarrow> a \\<in> topspace X\"\nproof -\n  have \"continuous_map X (subtopology X {a}) (\\<lambda>x. a) \\<and> (\\<lambda>x. a) a = a\" if \"a \\<in> topspace X\"\n    using that by simp\n  then show ?thesis\n    by (force simp: retract_of_space_def)\nqed\n\nlemma retract_of_space_clopen:\n  assumes \"openin X S\" \"closedin X S\" \"S = {} \\<Longrightarrow> topspace X = {}\"\n  shows \"S retract_of_space X\"\nproof (cases \"S = {}\")\n  case False\n  then obtain a where \"a \\<in> S\"\n    by blast\n  show ?thesis\n    unfolding retract_of_space_def\n  proof (intro exI conjI)\n    show \"S \\<subseteq> topspace X\"\n      by (simp add: assms closedin_subset)\n    have \"continuous_map X X (\\<lambda>x. if x \\<in> S then x else a)\"\n    proof (rule continuous_map_cases)\n      show \"continuous_map (subtopology X (X closure_of {x. x \\<in> S})) X (\\<lambda>x. x)\"\n        by (simp add: continuous_map_from_subtopology)\n      show \"continuous_map (subtopology X (X closure_of {x. x \\<notin> S})) X (\\<lambda>x. a)\"\n        using \\<open>S \\<subseteq> topspace X\\<close> \\<open>a \\<in> S\\<close> by force\n      show \"x = a\" if \"x \\<in> X frontier_of {x. x \\<in> S}\" for x\n        using assms that clopenin_eq_frontier_of by fastforce\n    qed\n    then show \"continuous_map X (subtopology X S) (\\<lambda>x. if x \\<in> S then x else a)\"\n      using \\<open>S \\<subseteq> topspace X\\<close> \\<open>a \\<in> S\\<close>  by (auto simp: continuous_map_in_subtopology)\n  qed auto\nqed (use assms in auto)\n\nlemma retract_of_space_disjoint_union:\n  assumes \"openin X S\" \"openin X T\" and ST: \"disjnt S T\" \"S \\<union> T = topspace X\" and \"S = {} \\<Longrightarrow> topspace X = {}\"\n  shows \"S retract_of_space X\"\nproof (rule retract_of_space_clopen)\n  have \"S \\<inter> T = {}\"\n    by (meson ST disjnt_def)\n  then have \"S = topspace X - T\"\n    using ST by auto\n  then show \"closedin X S\"\n    using \\<open>openin X T\\<close> by blast\nqed (auto simp: assms)\n\nlemma retraction_maps_section_image1:\n  assumes \"retraction_maps X Y r s\"\n  shows \"s ` (topspace Y) retract_of_space X\"\n  unfolding retract_of_space_section_map\nproof\n  show \"s ` topspace Y \\<subseteq> topspace X\"\n    using assms continuous_map_image_subset_topspace retraction_maps_def by blast\n  show \"section_map (subtopology X (s ` topspace Y)) X id\"\n    unfolding section_map_def\n    using assms retraction_maps_to_retract_maps by blast\nqed\n\nlemma retraction_maps_section_image2:\n   \"retraction_maps X Y r s\n        \\<Longrightarrow> subtopology X (s ` (topspace Y)) homeomorphic_space Y\"\n  using embedding_map_imp_homeomorphic_space homeomorphic_space_sym section_imp_embedding_map\n        section_map_def by blast\n\nsubsection\\<open>Paths and path-connectedness\\<close>\n\ndefinition pathin :: \"'a topology \\<Rightarrow> (real \\<Rightarrow> 'a) \\<Rightarrow> bool\" where\n   \"pathin X g \\<equiv> continuous_map (subtopology euclideanreal {0..1}) X g\"\n\nlemma pathin_compose:\n     \"\\<lbrakk>pathin X g; continuous_map X Y f\\<rbrakk> \\<Longrightarrow> pathin Y (f \\<circ> g)\"\n   by (simp add: continuous_map_compose pathin_def)\n\nlemma pathin_subtopology:\n     \"pathin (subtopology X S) g \\<longleftrightarrow> pathin X g \\<and> (\\<forall>x \\<in> {0..1}. g x \\<in> S)\"\n  by (auto simp: pathin_def continuous_map_in_subtopology)\n\nlemma pathin_const:\n   \"pathin X (\\<lambda>x. a) \\<longleftrightarrow> a \\<in> topspace X\"\n  by (simp add: pathin_def)\n   \nlemma path_start_in_topspace: \"pathin X g \\<Longrightarrow> g 0 \\<in> topspace X\"\n  by (force simp: pathin_def continuous_map)\n\nlemma path_finish_in_topspace: \"pathin X g \\<Longrightarrow> g 1 \\<in> topspace X\"\n  by (force simp: pathin_def continuous_map)\n\nlemma path_image_subset_topspace: \"pathin X g \\<Longrightarrow> g ` ({0..1}) \\<subseteq> topspace X\"\n  by (force simp: pathin_def continuous_map)\n\ndefinition path_connected_space :: \"'a topology \\<Rightarrow> bool\"\n  where \"path_connected_space X \\<equiv> \\<forall>x \\<in> topspace X. \\<forall> y \\<in> topspace X. \\<exists>g. pathin X g \\<and> g 0 = x \\<and> g 1 = y\"\n\ndefinition path_connectedin :: \"'a topology \\<Rightarrow> 'a set \\<Rightarrow> bool\"\n  where \"path_connectedin X S \\<equiv> S \\<subseteq> topspace X \\<and> path_connected_space(subtopology X S)\"\n\nlemma path_connectedin_absolute [simp]:\n     \"path_connectedin (subtopology X S) S \\<longleftrightarrow> path_connectedin X S\"\n  by (simp add: path_connectedin_def subtopology_subtopology)\n\nlemma path_connectedin_subset_topspace:\n     \"path_connectedin X S \\<Longrightarrow> S \\<subseteq> topspace X\"\n  by (simp add: path_connectedin_def)\n\nlemma path_connectedin_subtopology:\n     \"path_connectedin (subtopology X S) T \\<longleftrightarrow> path_connectedin X T \\<and> T \\<subseteq> S\"\n  by (auto simp: path_connectedin_def subtopology_subtopology inf.absorb2)\n\nlemma path_connectedin:\n     \"path_connectedin X S \\<longleftrightarrow>\n        S \\<subseteq> topspace X \\<and>\n        (\\<forall>x \\<in> S. \\<forall>y \\<in> S. \\<exists>g. pathin X g \\<and> g ` {0..1} \\<subseteq> S \\<and> g 0 = x \\<and> g 1 = y)\"\n  unfolding path_connectedin_def path_connected_space_def pathin_def continuous_map_in_subtopology\n  by (intro conj_cong refl ball_cong) (simp_all add: inf.absorb_iff2)\n\nlemma path_connectedin_topspace:\n     \"path_connectedin X (topspace X) \\<longleftrightarrow> path_connected_space X\"\n  by (simp add: path_connectedin_def)\n\nlemma path_connected_imp_connected_space:\n  assumes \"path_connected_space X\"\n  shows \"connected_space X\"\nproof -\n  have *: \"\\<exists>S. connectedin X S \\<and> g 0 \\<in> S \\<and> g 1 \\<in> S\" if \"pathin X g\" for g\n  proof (intro exI conjI)\n    have \"continuous_map (subtopology euclideanreal {0..1}) X g\"\n      using connectedin_absolute that by (simp add: pathin_def)\n    then show \"connectedin X (g ` {0..1})\"\n      by (rule connectedin_continuous_map_image) auto\n  qed auto\n  show ?thesis\n    using assms\n    by (auto intro: * simp add: path_connected_space_def connected_space_subconnected Ball_def)\nqed\n\nlemma path_connectedin_imp_connectedin:\n     \"path_connectedin X S \\<Longrightarrow> connectedin X S\"\n  by (simp add: connectedin_def path_connected_imp_connected_space path_connectedin_def)\n\nlemma path_connected_space_topspace_empty:\n     \"topspace X = {} \\<Longrightarrow> path_connected_space X\"\n  by (simp add: path_connected_space_def)\n\nlemma path_connectedin_empty [simp]: \"path_connectedin X {}\"\n  by (simp add: path_connectedin)\n\nlemma path_connectedin_singleton [simp]: \"path_connectedin X {a} \\<longleftrightarrow> a \\<in> topspace X\"\nproof\n  show \"path_connectedin X {a} \\<Longrightarrow> a \\<in> topspace X\"\n    by (simp add: path_connectedin)\n  show \"a \\<in> topspace X \\<Longrightarrow> path_connectedin X {a}\"\n    unfolding path_connectedin\n    using pathin_const by fastforce\nqed\n\nlemma path_connectedin_continuous_map_image:\n  assumes f: \"continuous_map X Y f\" and S: \"path_connectedin X S\"\n  shows \"path_connectedin Y (f ` S)\"\nproof -\n  have fX: \"f ` (topspace X) \\<subseteq> topspace Y\"\n    by (metis f continuous_map_image_subset_topspace)\n  show ?thesis\n    unfolding path_connectedin\n  proof (intro conjI ballI; clarify?)\n    fix x\n    assume \"x \\<in> S\"\n    show \"f x \\<in> topspace Y\"\n      by (meson S fX \\<open>x \\<in> S\\<close> image_subset_iff path_connectedin_subset_topspace set_mp)\n  next\n    fix x y\n    assume \"x \\<in> S\" and \"y \\<in> S\"\n    then obtain g where g: \"pathin X g\" \"g ` {0..1} \\<subseteq> S\" \"g 0 = x\" \"g 1 = y\"\n      using S  by (force simp: path_connectedin)\n    show \"\\<exists>g. pathin Y g \\<and> g ` {0..1} \\<subseteq> f ` S \\<and> g 0 = f x \\<and> g 1 = f y\"\n    proof (intro exI conjI)\n      show \"pathin Y (f \\<circ> g)\"\n        using \\<open>pathin X g\\<close> f pathin_compose by auto\n    qed (use g in auto)\n  qed\nqed\n\nlemma path_connectedin_discrete_topology:\n  \"path_connectedin (discrete_topology U) S \\<longleftrightarrow> S \\<subseteq> U \\<and> (\\<exists>a. S \\<subseteq> {a})\"\n  apply safe\n  using path_connectedin_subset_topspace apply fastforce\n   apply (meson connectedin_discrete_topology path_connectedin_imp_connectedin)\n  using subset_singletonD by fastforce\n\nlemma path_connected_space_discrete_topology:\n   \"path_connected_space (discrete_topology U) \\<longleftrightarrow> (\\<exists>a. U \\<subseteq> {a})\"\n  by (metis path_connectedin_discrete_topology path_connectedin_topspace path_connected_space_topspace_empty\n            subset_singletonD topspace_discrete_topology)\n\n\nlemma homeomorphic_path_connected_space_imp:\n     \"\\<lbrakk>path_connected_space X; X homeomorphic_space Y\\<rbrakk> \\<Longrightarrow> path_connected_space Y\"\n  unfolding homeomorphic_space_def homeomorphic_maps_def\n  by (metis (no_types, opaque_lifting) continuous_map_closedin continuous_map_image_subset_topspace imageI order_class.order.antisym path_connectedin_continuous_map_image path_connectedin_topspace subsetI)\n\nlemma homeomorphic_path_connected_space:\n   \"X homeomorphic_space Y \\<Longrightarrow> path_connected_space X \\<longleftrightarrow> path_connected_space Y\"\n  by (meson homeomorphic_path_connected_space_imp homeomorphic_space_sym)\n\nlemma homeomorphic_map_path_connectedness:\n  assumes \"homeomorphic_map X Y f\" \"U \\<subseteq> topspace X\"\n  shows \"path_connectedin Y (f ` U) \\<longleftrightarrow> path_connectedin X U\"\n  unfolding path_connectedin_def\nproof (intro conj_cong homeomorphic_path_connected_space)\n  show \"(f ` U \\<subseteq> topspace Y) = (U \\<subseteq> topspace X)\"\n    using assms homeomorphic_imp_surjective_map by blast\nnext\n  assume \"U \\<subseteq> topspace X\"\n  show \"subtopology Y (f ` U) homeomorphic_space subtopology X U\"\n    using assms unfolding homeomorphic_eq_everything_map\n    by (metis (no_types, opaque_lifting) assms homeomorphic_map_subtopologies homeomorphic_space homeomorphic_space_sym image_mono inf.absorb_iff2)\nqed\n\nlemma homeomorphic_map_path_connectedness_eq:\n   \"homeomorphic_map X Y f \\<Longrightarrow> path_connectedin X U \\<longleftrightarrow> U \\<subseteq> topspace X \\<and> path_connectedin Y (f ` U)\"\n  by (meson homeomorphic_map_path_connectedness path_connectedin_def)\n\nsubsection\\<open>Connected components\\<close>\n\ndefinition connected_component_of :: \"'a topology \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> bool\"\n  where \"connected_component_of X x y \\<equiv>\n        \\<exists>T. connectedin X T \\<and> x \\<in> T \\<and> y \\<in> T\"\n\nabbreviation connected_component_of_set\n  where \"connected_component_of_set X x \\<equiv> Collect (connected_component_of X x)\"\n\ndefinition connected_components_of :: \"'a topology \\<Rightarrow> ('a set) set\"\n  where \"connected_components_of X \\<equiv> connected_component_of_set X ` topspace X\"\n\nlemma connected_component_in_topspace:\n   \"connected_component_of X x y \\<Longrightarrow> x \\<in> topspace X \\<and> y \\<in> topspace X\"\n  by (meson connected_component_of_def connectedin_subset_topspace in_mono)\n\nlemma connected_component_of_refl:\n   \"connected_component_of X x x \\<longleftrightarrow> x \\<in> topspace X\"\n  by (meson connected_component_in_topspace connected_component_of_def connectedin_sing insertI1)\n\nlemma connected_component_of_sym:\n   \"connected_component_of X x y \\<longleftrightarrow> connected_component_of X y x\"\n  by (meson connected_component_of_def)\n\nlemma connected_component_of_trans:\n   \"\\<lbrakk>connected_component_of X x y; connected_component_of X y z\\<rbrakk>\n        \\<Longrightarrow> connected_component_of X x z\"\n  unfolding connected_component_of_def\n  using connectedin_Un by blast\n\nlemma connected_component_of_mono:\n   \"\\<lbrakk>connected_component_of (subtopology X S) x y; S \\<subseteq> T\\<rbrakk>\n        \\<Longrightarrow> connected_component_of (subtopology X T) x y\"\n  by (metis connected_component_of_def connectedin_subtopology inf.absorb_iff2 subtopology_subtopology)\n\nlemma connected_component_of_set:\n   \"connected_component_of_set X x = {y. \\<exists>T. connectedin X T \\<and> x \\<in> T \\<and> y \\<in> T}\"\n  by (meson connected_component_of_def)\n\nlemma connected_component_of_subset_topspace:\n   \"connected_component_of_set X x \\<subseteq> topspace X\"\n  using connected_component_in_topspace by force\n\nlemma connected_component_of_eq_empty:\n   \"connected_component_of_set X x = {} \\<longleftrightarrow> (x \\<notin> topspace X)\"\n  using connected_component_in_topspace connected_component_of_refl by fastforce\n\nlemma connected_space_iff_connected_component:\n   \"connected_space X \\<longleftrightarrow> (\\<forall>x \\<in> topspace X. \\<forall>y \\<in> topspace X. connected_component_of X x y)\"\n  by (simp add: connected_component_of_def connected_space_subconnected)\n\nlemma connected_space_imp_connected_component_of:\n   \"\\<lbrakk>connected_space X; a \\<in> topspace X; b \\<in> topspace X\\<rbrakk>\n    \\<Longrightarrow> connected_component_of X a b\"\n  by (simp add: connected_space_iff_connected_component)\n\nlemma connected_space_connected_component_set:\n   \"connected_space X \\<longleftrightarrow> (\\<forall>x \\<in> topspace X. connected_component_of_set X x = topspace X)\"\n  using connected_component_of_subset_topspace connected_space_iff_connected_component by fastforce\n\nlemma connected_component_of_maximal:\n   \"\\<lbrakk>connectedin X S; x \\<in> S\\<rbrakk> \\<Longrightarrow> S \\<subseteq> connected_component_of_set X x\"\n  by (meson Ball_Collect connected_component_of_def)\n\nlemma connected_component_of_equiv:\n   \"connected_component_of X x y \\<longleftrightarrow>\n    x \\<in> topspace X \\<and> y \\<in> topspace X \\<and> connected_component_of X x = connected_component_of X y\"\n  apply (simp add: connected_component_in_topspace fun_eq_iff)\n  by (meson connected_component_of_refl connected_component_of_sym connected_component_of_trans)\n\nlemma connected_component_of_disjoint:\n   \"disjnt (connected_component_of_set X x) (connected_component_of_set X y)\n    \\<longleftrightarrow> ~(connected_component_of X x y)\"\n  using connected_component_of_equiv unfolding disjnt_iff by force\n\nlemma connected_component_of_eq:\n   \"connected_component_of X x = connected_component_of X y \\<longleftrightarrow>\n        (x \\<notin> topspace X) \\<and> (y \\<notin> topspace X) \\<or>\n        x \\<in> topspace X \\<and> y \\<in> topspace X \\<and>\n        connected_component_of X x y\"\n  by (metis Collect_empty_eq_bot connected_component_of_eq_empty connected_component_of_equiv)\n\nlemma connectedin_connected_component_of:\n   \"connectedin X (connected_component_of_set X x)\"\nproof -\n  have \"connected_component_of_set X x = \\<Union> {T. connectedin X T \\<and> x \\<in> T}\"\n    by (auto simp: connected_component_of_def)\n  then show ?thesis\n    apply (rule ssubst)\n    by (blast intro: connectedin_Union)\nqed\n\n\nlemma Union_connected_components_of:\n   \"\\<Union>(connected_components_of X) = topspace X\"\n  unfolding connected_components_of_def\n  apply (rule equalityI)\n  apply (simp add: SUP_least connected_component_of_subset_topspace)\n  using connected_component_of_refl by fastforce\n\nlemma connected_components_of_maximal:\n   \"\\<lbrakk>C \\<in> connected_components_of X; connectedin X S; ~disjnt C S\\<rbrakk> \\<Longrightarrow> S \\<subseteq> C\"\n  unfolding connected_components_of_def disjnt_def\n  apply clarify\n  by (metis Int_emptyI connected_component_of_def connected_component_of_trans mem_Collect_eq)\n\nlemma pairwise_disjoint_connected_components_of:\n   \"pairwise disjnt (connected_components_of X)\"\n  unfolding connected_components_of_def pairwise_def\n  apply clarify\n  by (metis connected_component_of_disjoint connected_component_of_equiv)\n\nlemma complement_connected_components_of_Union:\n   \"C \\<in> connected_components_of X\n      \\<Longrightarrow> topspace X - C = \\<Union> (connected_components_of X - {C})\"\n  apply (rule equalityI)\n  using Union_connected_components_of apply fastforce\n  by (metis Diff_cancel Diff_subset Union_connected_components_of cSup_singleton diff_Union_pairwise_disjoint equalityE insert_subsetI pairwise_disjoint_connected_components_of)\n\nlemma nonempty_connected_components_of:\n   \"C \\<in> connected_components_of X \\<Longrightarrow> C \\<noteq> {}\"\n  unfolding connected_components_of_def\n  by (metis (no_types, lifting) connected_component_of_eq_empty imageE)\n\nlemma connected_components_of_subset:\n   \"C \\<in> connected_components_of X \\<Longrightarrow> C \\<subseteq> topspace X\"\n  using Union_connected_components_of by fastforce\n\nlemma connectedin_connected_components_of:\n  assumes \"C \\<in> connected_components_of X\"\n  shows \"connectedin X C\"\nproof -\n  have \"C \\<in> connected_component_of_set X ` topspace X\"\n    using assms connected_components_of_def by blast\nthen show ?thesis\n  using connectedin_connected_component_of by fastforce\nqed\n\nlemma connected_component_in_connected_components_of:\n   \"connected_component_of_set X a \\<in> connected_components_of X \\<longleftrightarrow> a \\<in> topspace X\"\n  apply (rule iffI)\n  using connected_component_of_eq_empty nonempty_connected_components_of apply fastforce\n  by (simp add: connected_components_of_def)\n\nlemma connected_space_iff_components_eq:\n   \"connected_space X \\<longleftrightarrow> (\\<forall>C \\<in> connected_components_of X. \\<forall>C' \\<in> connected_components_of X. C = C')\"\n  apply (rule iffI)\n  apply (force simp: connected_components_of_def connected_space_connected_component_set image_iff)\n  by (metis connected_component_in_connected_components_of connected_component_of_refl connected_space_iff_connected_component mem_Collect_eq)\n\nlemma connected_components_of_eq_empty:\n   \"connected_components_of X = {} \\<longleftrightarrow> topspace X = {}\"\n  by (simp add: connected_components_of_def)\n\nlemma connected_components_of_empty_space:\n   \"topspace X = {} \\<Longrightarrow> connected_components_of X = {}\"\n  by (simp add: connected_components_of_eq_empty)\n\nlemma connected_components_of_subset_sing:\n   \"connected_components_of X \\<subseteq> {S} \\<longleftrightarrow> connected_space X \\<and> (topspace X = {} \\<or> topspace X = S)\"\nproof (cases \"topspace X = {}\")\n  case True\n  then show ?thesis\n    by (simp add: connected_components_of_empty_space connected_space_topspace_empty)\nnext\n  case False\n  then show ?thesis\n    by (metis (no_types, opaque_lifting) Union_connected_components_of ccpo_Sup_singleton\n        connected_components_of_eq_empty connected_space_iff_components_eq insertI1 singletonD\n        subsetI subset_singleton_iff)\nqed\n\nlemma connected_space_iff_components_subset_singleton:\n   \"connected_space X \\<longleftrightarrow> (\\<exists>a. connected_components_of X \\<subseteq> {a})\"\n  by (simp add: connected_components_of_subset_sing)\n\nlemma connected_components_of_eq_singleton:\n   \"connected_components_of X = {S}\n\\<longleftrightarrow> connected_space X \\<and> topspace X \\<noteq> {} \\<and> S = topspace X\"\n  by (metis ccpo_Sup_singleton connected_components_of_subset_sing insert_not_empty subset_singleton_iff)\n\nlemma connected_components_of_connected_space:\n   \"connected_space X \\<Longrightarrow> connected_components_of X = (if topspace X = {} then {} else {topspace X})\"\n  by (simp add: connected_components_of_eq_empty connected_components_of_eq_singleton)\n\nlemma exists_connected_component_of_superset:\n  assumes \"connectedin X S\" and ne: \"topspace X \\<noteq> {}\"\n  shows \"\\<exists>C. C \\<in> connected_components_of X \\<and> S \\<subseteq> C\"\nproof (cases \"S = {}\")\n  case True\n  then show ?thesis\n    using ne connected_components_of_def by blast\nnext\n  case False\n  then show ?thesis\n    by (meson all_not_in_conv assms(1) connected_component_in_connected_components_of connected_component_of_maximal connectedin_subset_topspace in_mono)\nqed\n\nlemma closedin_connected_components_of:\n  assumes \"C \\<in> connected_components_of X\"\n  shows   \"closedin X C\"\nproof -\n  obtain x where \"x \\<in> topspace X\" and x: \"C = connected_component_of_set X x\"\n    using assms by (auto simp: connected_components_of_def)\n  have \"connected_component_of_set X x \\<subseteq> topspace X\"\n    by (simp add: connected_component_of_subset_topspace)\n  moreover have \"X closure_of connected_component_of_set X x \\<subseteq> connected_component_of_set X x\"\n  proof (rule connected_component_of_maximal)\n    show \"connectedin X (X closure_of connected_component_of_set X x)\"\n      by (simp add: connectedin_closure_of connectedin_connected_component_of)\n    show \"x \\<in> X closure_of connected_component_of_set X x\"\n      by (simp add: \\<open>x \\<in> topspace X\\<close> closure_of connected_component_of_refl)\n  qed\n  ultimately\n  show ?thesis\n    using closure_of_subset_eq x by auto\nqed\n\nlemma closedin_connected_component_of:\n   \"closedin X (connected_component_of_set X x)\"\n  by (metis closedin_connected_components_of closedin_empty connected_component_in_connected_components_of connected_component_of_eq_empty)\n\nlemma connected_component_of_eq_overlap:\n   \"connected_component_of_set X x = connected_component_of_set X y \\<longleftrightarrow>\n      (x \\<notin> topspace X) \\<and> (y \\<notin> topspace X) \\<or>\n      ~(connected_component_of_set X x \\<inter> connected_component_of_set X y = {})\"\n  using connected_component_of_equiv by fastforce\n\nlemma connected_component_of_nonoverlap:\n   \"connected_component_of_set X x \\<inter> connected_component_of_set X y = {} \\<longleftrightarrow>\n     (x \\<notin> topspace X) \\<or> (y \\<notin> topspace X) \\<or>\n     ~(connected_component_of_set X x = connected_component_of_set X y)\"\n  by (metis connected_component_of_eq_empty connected_component_of_eq_overlap inf.idem)\n\nlemma connected_component_of_overlap:\n   \"~(connected_component_of_set X x \\<inter> connected_component_of_set X y = {}) \\<longleftrightarrow>\n    x \\<in> topspace X \\<and> y \\<in> topspace X \\<and>\n    connected_component_of_set X x = connected_component_of_set X y\"\n  by (meson connected_component_of_nonoverlap)\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/Analysis/Abstract_Topology_2.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8688267898240861, "lm_q2_score": 0.8539127510928477, "lm_q1q2_score": 0.7419022743218527}}
{"text": "theory Ex4_6\n  imports Main \"~~/src/HOL/Library/Code_Target_Nat\" \"../Chapter 3/AExp\"  \nbegin\n  \nsection \"Exercise 4.6\"\n  \ninductive aval_rel :: \"aexp \\<Rightarrow> state \\<Rightarrow> val \\<Rightarrow> bool\" where\n  literal: \"aval_rel (N x) s x\" |  \n  variable: \"aval_rel (V name) state (state name)\" |  \n  plus: \"aval_rel exp\\<^sub>0 s value\\<^sub>0 \\<Longrightarrow> aval_rel exp\\<^sub>1 s value\\<^sub>1 \n              \\<Longrightarrow> aval_rel (Plus exp\\<^sub>0 exp\\<^sub>1) s (value\\<^sub>0 + value\\<^sub>1)\"   \n  \nlemma \"aval_rel (N 2) <> 2\"\n  using literal by simp\n    \nlemma \"aval_rel (Plus (N 2) (N 4)) <> 6\"\nproof -\n  have \"aval_rel (N 2) <> 2\" using literal by simp\n  moreover have \"aval_rel (N 4) <> 4\" using literal by simp\n  ultimately show \"aval_rel (Plus (N 2) (N 4)) <> 6\" using plus by fastforce\nqed\n  \nlemma aval_rel_implies_aval:\"aval_rel exp state v \\<Longrightarrow> aval exp state = v\"\n  apply(induction rule: aval_rel.induct)\n  by simp_all\n    \nlemma aval_implies_aval_rel:\"aval exp state = v \\<Longrightarrow> aval_rel exp state v\"\n  (* This is a great example of 'arbitrary' being required.\nIf you do induction without arbitrary v, then the third case, plus, can't be solved. The inductive\nhypotheses are too weak; if you used them you would essentially be saying: (v + v = v)\nThe two premises of the induction hypothesis each say that the evaluation of their own\nexpression equals some v; we need 'arbitrary' to indicate that these v may be different from each\nother, and different from the v in the proposition we are proving.\nThis is what the goal looks like without aribtrary:\n\n 3. \\<And>exp1 exp2.\n       (aval exp1 state = v \\<Longrightarrow> Ex4_6.aval_rel exp1 state v) \\<Longrightarrow>\n       (aval exp2 state = v \\<Longrightarrow> Ex4_6.aval_rel exp2 state v) \\<Longrightarrow> \n        aval (Plus exp1 exp2) state = v \n    \\<Longrightarrow> Ex4_6.aval_rel (Plus exp1 exp2) state v\n\nObviously, the 'v' in the first two lines should be different from the v in the last line, hence\n'arbitrary' is required. *)\n  apply(induction exp arbitrary: v)\n    apply (simp add: literal)\n  using variable apply auto[1]\n  using plus by auto\n    \nlemma \"aval exp state = v \\<longleftrightarrow> aval_rel exp state v\"\n  apply rule\n   apply (simp add: aval_implies_aval_rel)\n  by (simp add: aval_rel_implies_aval)\n    \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 4/Ex4_6.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267694452331, "lm_q2_score": 0.8539127566694178, "lm_q1q2_score": 0.7419022617651637}}
{"text": "(*\n  File:    Gaussian_Integers.thy\n  Author:  Manuel Eberl, TU M\u00fcnchen\n*)\nsection \\<open>Gaussian Integers\\<close>\ntheory Gaussian_Integers\nimports\n  \"HOL-Computational_Algebra.Computational_Algebra\"\n  \"HOL-Number_Theory.Number_Theory\"\nbegin\n\nsubsection \\<open>Auxiliary material\\<close>\n\nlemma coprime_iff_prime_factors_disjoint:\n  fixes x y :: \"'a :: factorial_semiring\"\n  assumes \"x \\<noteq> 0\" \"y \\<noteq> 0\"\n  shows \"coprime x y \\<longleftrightarrow> prime_factors x \\<inter> prime_factors y = {}\"\nproof \n  assume \"coprime x y\"\n  have False if \"p \\<in> prime_factors x\" \"p \\<in> prime_factors y\" for p\n  proof -\n    from that assms have \"p dvd x\" \"p dvd y\"\n      by (auto simp: prime_factors_dvd)\n    with \\<open>coprime x y\\<close> have \"p dvd 1\"\n      using coprime_common_divisor by auto\n    with that assms show False by (auto simp: prime_factors_dvd)\n  qed\n  thus \"prime_factors x \\<inter> prime_factors y = {}\" by auto\nnext\n  assume disjoint: \"prime_factors x \\<inter> prime_factors y = {}\"\n  show \"coprime x y\"\n  proof (rule coprimeI)\n    fix d assume d: \"d dvd x\" \"d dvd y\"\n    show \"is_unit d\"\n    proof (rule ccontr)\n      assume \"\\<not>is_unit d\"\n      moreover from this and d assms have \"d \\<noteq> 0\" by auto\n      ultimately obtain p where p: \"prime p\" \"p dvd d\"\n        using prime_divisor_exists by auto\n      with d and assms have \"p \\<in> prime_factors x \\<inter> prime_factors y\"\n        by (auto simp: prime_factors_dvd)\n      with disjoint show False by auto\n    qed\n  qed\nqed\n\nlemma product_dvd_irreducibleD:\n  fixes a b x :: \"'a :: algebraic_semidom\"\n  assumes \"irreducible x\"\n  assumes \"a * b dvd x\"\n  shows \"a dvd 1 \\<or> b dvd 1\"\nproof -\n  from assms obtain c where \"x = a * b * c\"\n    by auto\n  hence \"x = a * (b * c)\"\n    by (simp add: mult_ac)\n  from irreducibleD[OF assms(1) this] show \"a dvd 1 \\<or> b dvd 1\"\n    by (auto simp: is_unit_mult_iff)\nqed\n\nlemma prime_elem_mult_dvdI:\n  assumes \"prime_elem p\" \"p dvd c\" \"b dvd c\" \"\\<not>p dvd b\"\n  shows   \"p * b dvd c\"\nproof -\n  from assms(3) obtain a where c: \"c = a * b\"\n    using mult.commute by blast\n  with assms(2) have \"p dvd a * b\"\n    by simp\n  with assms have \"p dvd a\"\n    by (subst (asm) prime_elem_dvd_mult_iff) auto\n  with c show ?thesis by (auto intro: mult_dvd_mono)\nqed\n\nlemma prime_elem_power_mult_dvdI:\n  fixes p :: \"'a :: algebraic_semidom\"\n  assumes \"prime_elem p\" \"p ^ n dvd c\" \"b dvd c\" \"\\<not>p dvd b\"\n  shows   \"p ^ n * b dvd c\"\nproof (cases \"n = 0\")\n  case False\n  from assms(3) obtain a where c: \"c = a * b\"\n    using mult.commute by blast\n  with assms(2) have \"p ^ n dvd b * a\"\n    by (simp add: mult_ac)\n  hence \"p ^ n dvd a\"\n    by (rule prime_power_dvd_multD[OF assms(1)]) (use assms False in auto)\n  with c show ?thesis by (auto intro: mult_dvd_mono)\nqed (use assms in auto)\n\nlemma prime_mod_4_cases:\n  fixes p :: nat\n  assumes \"prime p\"\n  shows   \"p = 2 \\<or> [p = 1] (mod 4) \\<or> [p = 3] (mod 4)\"\nproof (cases \"p = 2\")\n  case False\n  with prime_gt_1_nat[of p] assms have \"p > 2\" by auto\n  have \"\\<not>4 dvd p\"\n    using assms product_dvd_irreducibleD[of p 2 2]\n    by (auto simp: prime_elem_iff_irreducible simp flip: prime_elem_nat_iff)\n  hence \"p mod 4 \\<noteq> 0\"\n    by (auto simp: mod_eq_0_iff_dvd)\n  moreover have \"p mod 4 \\<noteq> 2\"\n  proof\n    assume \"p mod 4 = 2\"\n    hence \"p mod 4 mod 2 = 0\"\n      by (simp add: cong_def)\n    thus False using \\<open>prime p\\<close> \\<open>p > 2\\<close> prime_odd_nat[of p]\n      by (auto simp: mod_mod_cancel)\n  qed\n  moreover have \"p mod 4 \\<in> {0,1,2,3}\"\n    by auto\n  ultimately show ?thesis by (auto simp: cong_def)\nqed auto\n\nlemma of_nat_prod_mset: \"of_nat (prod_mset A) = prod_mset (image_mset of_nat A)\"\n  by (induction A) auto\n\nlemma multiplicity_0_left [simp]: \"multiplicity 0 x = 0\"\n  by (cases \"x = 0\") (auto simp: not_dvd_imp_multiplicity_0)\n\nlemma is_unit_power [intro]: \"is_unit x \\<Longrightarrow> is_unit (x ^ n)\"\n  by (subst is_unit_power_iff) auto\n\nlemma (in factorial_semiring) pow_divides_pow_iff:\n  assumes \"n > 0\"\n  shows   \"a ^ n dvd b ^ n \\<longleftrightarrow> a dvd b\"\nproof (cases \"b = 0\")\n  case False\n  show ?thesis\n  proof\n    assume dvd: \"a ^ n dvd b ^ n\"\n    with \\<open>b \\<noteq> 0\\<close> have \"a \\<noteq> 0\"\n      using \\<open>n > 0\\<close> by (auto simp: power_0_left)\n    show \"a dvd b\"\n    proof (rule multiplicity_le_imp_dvd)\n      fix p :: 'a assume p: \"prime p\"\n      from dvd \\<open>b \\<noteq> 0\\<close> have \"multiplicity p (a ^ n) \\<le> multiplicity p (b ^ n)\"\n        by (intro dvd_imp_multiplicity_le) auto\n      thus \"multiplicity p a \\<le> multiplicity p b\"\n        using p \\<open>a \\<noteq> 0\\<close> \\<open>b \\<noteq> 0\\<close> \\<open>n > 0\\<close> by (simp add: prime_elem_multiplicity_power_distrib)\n    qed fact+\n  qed (auto intro: dvd_power_same)\nqed (use assms in \\<open>auto simp: power_0_left\\<close>)\n\nlemma multiplicity_power_power:\n  fixes p :: \"'a :: {factorial_semiring, algebraic_semidom}\"\n  assumes \"n > 0\"\n  shows   \"multiplicity (p ^ n) (x ^ n) = multiplicity p x\"\nproof (cases \"x = 0 \\<or> p = 0 \\<or> is_unit p\")\n  case True\n  thus ?thesis using \\<open>n > 0\\<close>\n    by (auto simp: power_0_left is_unit_power_iff multiplicity_unit_left)\nnext\n  case False\n  show ?thesis\n  proof (intro antisym multiplicity_geI)\n    have \"(p ^ multiplicity p x) ^ n dvd x ^ n\"\n      by (intro dvd_power_same) (simp add: multiplicity_dvd)\n    thus \"(p ^ n) ^ multiplicity p x dvd x ^ n\"\n      by (simp add: mult_ac flip: power_mult)\n  next\n    have \"(p ^ n) ^ multiplicity (p ^ n) (x ^ n) dvd x ^ n\"\n      by (simp add: multiplicity_dvd)\n    hence \"(p ^ multiplicity (p ^ n) (x ^ n)) ^ n dvd x ^ n\"\n      by (simp add: mult_ac flip: power_mult)\n    thus \"p ^ multiplicity (p ^ n) (x ^ n) dvd x\"\n      by (subst (asm) pow_divides_pow_iff) (use assms in auto)\n  qed (use False \\<open>n > 0\\<close> in \\<open>auto simp: is_unit_power_iff\\<close>)\nqed\n\nlemma even_square_cong_4_int:\n  fixes x :: int\n  assumes \"even x\"\n  shows   \"[x ^ 2 = 0] (mod 4)\"\nproof -\n  from assms have \"even \\<bar>x\\<bar>\"\n    by simp\n  hence [simp]: \"\\<bar>x\\<bar> mod 2 = 0\"\n    by presburger\n  have \"(\\<bar>x\\<bar> ^ 2) mod 4 = ((\\<bar>x\\<bar> mod 4) ^ 2) mod 4\"\n    by (simp add: power_mod)\n  also from assms have \"\\<bar>x\\<bar> mod 4 = 0 \\<or> \\<bar>x\\<bar> mod 4 = 2\"\n    using mod_double_modulus[of 2 \"\\<bar>x\\<bar>\"] by simp\n  hence \"((\\<bar>x\\<bar> mod 4) ^ 2) mod 4 = 0\"\n    by auto\n  finally show ?thesis by (simp add: cong_def)\nqed\n\nlemma even_square_cong_4_nat: \"even (x::nat) \\<Longrightarrow> [x ^ 2 = 0] (mod 4)\"\n  using even_square_cong_4_int[of \"int x\"] by (auto simp flip: cong_int_iff)\n\nlemma odd_square_cong_4_int:\n  fixes x :: int\n  assumes \"odd x\"\n  shows   \"[x ^ 2 = 1] (mod 4)\"\nproof -\n  from assms have \"odd \\<bar>x\\<bar>\"\n    by simp\n  hence [simp]: \"\\<bar>x\\<bar> mod 2 = 1\"\n    by presburger\n  have \"(\\<bar>x\\<bar> ^ 2) mod 4 = ((\\<bar>x\\<bar> mod 4) ^ 2) mod 4\"\n    by (simp add: power_mod)\n  also from assms have \"\\<bar>x\\<bar> mod 4 = 1 \\<or> \\<bar>x\\<bar> mod 4 = 3\"\n    using mod_double_modulus[of 2 \"\\<bar>x\\<bar>\"] by simp\n  hence \"((\\<bar>x\\<bar> mod 4) ^ 2) mod 4 = 1\"\n    by auto\n  finally show ?thesis by (simp add: cong_def)\nqed\n\nlemma odd_square_cong_4_nat: \"odd (x::nat) \\<Longrightarrow> [x ^ 2 = 1] (mod 4)\"\n  using odd_square_cong_4_int[of \"int x\"] by (auto simp flip: cong_int_iff)\n\n\ntext \\<open>\n  Gaussian integers will require a notion of an element being a power up to a unit,\n  so we introduce this here. This should go in the library eventually.\n\\<close>\ndefinition is_nth_power_upto_unit where\n  \"is_nth_power_upto_unit n x \\<longleftrightarrow> (\\<exists>u. is_unit u \\<and> is_nth_power n (u * x))\"\n\nlemma is_nth_power_upto_unit_base: \"is_nth_power n x \\<Longrightarrow> is_nth_power_upto_unit n x\"\n  by (auto simp: is_nth_power_upto_unit_def intro: exI[of _ 1])\n\nlemma is_nth_power_upto_unitI:\n  assumes \"normalize (x ^ n) = normalize y\"\n  shows   \"is_nth_power_upto_unit n y\"\nproof -\n  from associatedE1[OF assms] obtain u where \"is_unit u\" \"u * y = x ^ n\"\n    by metis\n  thus ?thesis\n    by (auto simp: is_nth_power_upto_unit_def intro!: exI[of _ u])\nqed\n\nlemma is_nth_power_upto_unit_conv_multiplicity: \n  fixes x :: \"'a :: factorial_semiring\"\n  assumes \"n > 0\"\n  shows   \"is_nth_power_upto_unit n x \\<longleftrightarrow> (\\<forall>p. prime p \\<longrightarrow> n dvd multiplicity p x)\"\nproof (cases \"x = 0\")\n  case False\n  show ?thesis\n  proof safe\n    fix p :: 'a assume p: \"prime p\"\n    assume \"is_nth_power_upto_unit n x\"\n    then obtain u y where uy: \"is_unit u\" \"u * x = y ^ n\"\n      by (auto simp: is_nth_power_upto_unit_def elim!: is_nth_powerE)\n    from p uy assms False have [simp]: \"y \\<noteq> 0\" by (auto simp: power_0_left)\n    have \"multiplicity p (u * x) = multiplicity p (y ^ n)\"\n      by (subst uy(2) [symmetric]) simp\n    also have \"multiplicity p (u * x) = multiplicity p x\"\n      by (simp add: multiplicity_times_unit_right uy(1))\n    finally show \"n dvd multiplicity p x\"\n      using False and p and uy and assms\n      by (auto simp: prime_elem_multiplicity_power_distrib)\n  next\n    assume *: \"\\<forall>p. prime p \\<longrightarrow> n dvd multiplicity p x\"\n    have \"multiplicity p ((\\<Prod>p\\<in>prime_factors x. p ^ (multiplicity p x div n)) ^ n) = \n            multiplicity p x\" if \"prime p\" for p\n    proof -\n      from that and * have \"n dvd multiplicity p x\" by blast\n      have \"multiplicity p x = 0\" if \"p \\<notin> prime_factors x\"\n        using that and \\<open>prime p\\<close> by (simp add: prime_factors_multiplicity)\n      with that and * and assms show ?thesis unfolding prod_power_distrib power_mult [symmetric]\n        by (subst multiplicity_prod_prime_powers) (auto simp: in_prime_factors_imp_prime elim: dvdE)\n    qed\n    with assms False \n      have \"normalize ((\\<Prod>p\\<in>prime_factors x. p ^ (multiplicity p x div n)) ^ n) = normalize x\"\n      by (intro multiplicity_eq_imp_eq) (auto simp: multiplicity_prod_prime_powers)\n    thus \"is_nth_power_upto_unit n x\"\n      by (auto intro: is_nth_power_upto_unitI)\n  qed\nqed (use assms in \\<open>auto simp: is_nth_power_upto_unit_def\\<close>)\n\nlemma is_nth_power_upto_unit_0_left [simp, intro]: \"is_nth_power_upto_unit 0 x \\<longleftrightarrow> is_unit x\"\nproof\n  assume \"is_unit x\"\n  thus \"is_nth_power_upto_unit 0 x\"\n    unfolding is_nth_power_upto_unit_def by (intro exI[of _ \"1 div x\"]) auto\nnext\n  assume \"is_nth_power_upto_unit 0 x\"\n  then obtain u where \"is_unit u\" \"u * x = 1\"\n    by (auto simp: is_nth_power_upto_unit_def)\n  thus \"is_unit x\"\n    by (metis dvd_triv_right)\nqed\n\nlemma is_nth_power_upto_unit_unit [simp, intro]:\n  assumes \"is_unit x\"\n  shows   \"is_nth_power_upto_unit n x\"\n  using assms by (auto simp: is_nth_power_upto_unit_def intro!: exI[of _ \"1 div x\"])\n\nlemma is_nth_power_upto_unit_1_left [simp, intro]: \"is_nth_power_upto_unit 1 x\"\n  by (auto simp: is_nth_power_upto_unit_def intro: exI[of _ 1])\n\nlemma is_nth_power_upto_unit_mult_coprimeD1:\n  fixes x y :: \"'a :: factorial_semiring\"\n  assumes \"coprime x y\" \"is_nth_power_upto_unit n (x * y)\"\n  shows   \"is_nth_power_upto_unit n x\"\nproof -\n  consider \"n = 0\" | \"x = 0\" \"n > 0\" | \"x \\<noteq> 0\" \"y = 0\" \"n > 0\" | \"n > 0\" \"x \\<noteq> 0\" \"y \\<noteq> 0\"\n    by force\n  thus ?thesis\n  proof cases\n    assume [simp]: \"n = 0\"\n    from assms have \"is_unit (x * y)\"\n      by auto\n    hence \"is_unit x\"\n      using is_unit_mult_iff by blast\n    thus ?thesis using assms by auto\n  next\n    assume \"x = 0\" \"n > 0\"\n    thus ?thesis by (auto simp: is_nth_power_upto_unit_def)\n  next\n    assume *: \"x \\<noteq> 0\" \"y = 0\" \"n > 0\"\n    with assms show ?thesis by auto\n  next\n    assume *: \"n > 0\" and [simp]: \"x \\<noteq> 0\" \"y \\<noteq> 0\"\n    show ?thesis\n    proof (subst is_nth_power_upto_unit_conv_multiplicity[OF \\<open>n > 0\\<close>]; safe)\n      fix p :: 'a assume p: \"prime p\"\n      show \"n dvd multiplicity p x\"\n      proof (cases \"p dvd x\")\n        case False\n        thus ?thesis\n          by (simp add: not_dvd_imp_multiplicity_0)\n      next\n        case True\n        have \"n dvd multiplicity p (x * y)\"\n          using assms(2) \\<open>n > 0\\<close> p by (auto simp: is_nth_power_upto_unit_conv_multiplicity)\n        also have \"\\<dots> = multiplicity p x + multiplicity p y\"\n          using p by (subst prime_elem_multiplicity_mult_distrib) auto\n        also have \"\\<not>p dvd y\"\n          using \\<open>coprime x y\\<close> \\<open>p dvd x\\<close> p not_prime_unit coprime_common_divisor by blast\n        hence \"multiplicity p y = 0\"\n          by (rule not_dvd_imp_multiplicity_0)\n        finally show ?thesis by simp\n      qed\n    qed\n  qed\nqed\n\nlemma is_nth_power_upto_unit_mult_coprimeD2:\n  fixes x y :: \"'a :: factorial_semiring\"\n  assumes \"coprime x y\" \"is_nth_power_upto_unit n (x * y)\"\n  shows   \"is_nth_power_upto_unit n y\"\n  using assms is_nth_power_upto_unit_mult_coprimeD1[of y x]\n  by (simp_all add: mult_ac coprime_commute)\n\n\nsubsection \\<open>Definition\\<close>\n\ntext \\<open>\n  Gaussian integers are the ring $\\mathbb{Z}[i]$ which is formed either by formally adjoining\n  an element $i$ with $i^2 = -1$ to $\\mathbb{Z}$ or by taking all the complex numbers with\n  integer real and imaginary part.\n\n  We define them simply by giving an appropriate ring structure to $\\mathbb{Z}^2$, with the first\n  component representing the real part and the second component the imaginary part:\n\\<close>\ncodatatype gauss_int = Gauss_Int (ReZ: int) (ImZ: int)\n\ntext \\<open>\n  The following is the imaginary unit $i$ in the Gaussian integers, which we will denote as\n  \\<open>\\<i>\\<^sub>\\<int>\\<close>:\n\\<close>\nprimcorec gauss_i where\n  \"ReZ gauss_i = 0\"\n| \"ImZ gauss_i = 1\"\n\nlemma gauss_int_eq_iff: \"x = y \\<longleftrightarrow> ReZ x = ReZ y \\<and> ImZ x = ImZ y\"\n  by (cases x; cases y) auto\n\n\n(*<*)\nbundle gauss_int_notation\nbegin\n\nnotation gauss_i (\"\\<i>\\<^sub>\\<int>\")\n\nend\n\nbundle no_gauss_int_notation\nbegin\n\nno_notation (output) gauss_i (\"\\<i>\\<^sub>\\<int>\")\n\nend\n\nbundle gauss_int_output_notation\nbegin\n\nnotation (output) gauss_i (\"\\<ii>\")\n\nend\n\nunbundle gauss_int_notation\n(*>*)\n\n\ntext \\<open>\n  Next, we define the canonical injective homomorphism from the Gaussian integers into the\n  complex numbers:\n\\<close>\nprimcorec gauss2complex where\n  \"Re (gauss2complex z) = of_int (ReZ z)\"\n| \"Im (gauss2complex z) = of_int (ImZ z)\"\n\ndeclare [[coercion gauss2complex]]\n\nlemma gauss2complex_eq_iff [simp]: \"gauss2complex z = gauss2complex u \\<longleftrightarrow> z = u\"\n  by (simp add: complex_eq_iff gauss_int_eq_iff)\n\ntext \\<open>\n  Gaussian integers also have conjugates, just like complex numbers:\n\\<close>\nprimcorec gauss_cnj where\n  \"ReZ (gauss_cnj z) = ReZ z\"\n| \"ImZ (gauss_cnj z) = -ImZ z\"\n\n\ntext \\<open>\n  In the remainder of this section, we prove that Gaussian integers are a commutative ring\n  of characteristic 0 and several other trivial algebraic properties.\n\\<close>\n\ninstantiation gauss_int :: comm_ring_1\nbegin\n\nprimcorec zero_gauss_int where\n  \"ReZ zero_gauss_int = 0\"\n| \"ImZ zero_gauss_int = 0\"\n\nprimcorec one_gauss_int where\n  \"ReZ one_gauss_int = 1\"\n| \"ImZ one_gauss_int = 0\"\n\nprimcorec uminus_gauss_int where\n  \"ReZ (uminus_gauss_int x) = -ReZ x\"\n| \"ImZ (uminus_gauss_int x) = -ImZ x\"\n\nprimcorec plus_gauss_int where\n  \"ReZ (plus_gauss_int x y) = ReZ x + ReZ y\"\n| \"ImZ (plus_gauss_int x y) = ImZ x + ImZ y\"\n\nprimcorec minus_gauss_int where\n  \"ReZ (minus_gauss_int x y) = ReZ x - ReZ y\"\n| \"ImZ (minus_gauss_int x y) = ImZ x - ImZ y\"\n\nprimcorec times_gauss_int where\n  \"ReZ (times_gauss_int x y) = ReZ x * ReZ y - ImZ x * ImZ y\"\n| \"ImZ (times_gauss_int x y) = ReZ x * ImZ y + ImZ x * ReZ y\"\n\ninstance\n  by intro_classes (auto simp: gauss_int_eq_iff algebra_simps)\n\nend\n\nlemma gauss_i_times_i [simp]: \"\\<i>\\<^sub>\\<int> * \\<i>\\<^sub>\\<int> = (-1 :: gauss_int)\"\n  and gauss_cnj_i [simp]: \"gauss_cnj \\<i>\\<^sub>\\<int> = -\\<i>\\<^sub>\\<int>\"\n  by (simp_all add: gauss_int_eq_iff)\n\nlemma gauss_cnj_eq_0_iff [simp]: \"gauss_cnj z = 0 \\<longleftrightarrow> z = 0\"\n  by (auto simp: gauss_int_eq_iff)\n\nlemma gauss_cnj_eq_self: \"Im z = 0 \\<Longrightarrow> gauss_cnj z = z\"\n  and gauss_cnj_eq_minus_self: \"Re z = 0 \\<Longrightarrow> gauss_cnj z = -z\"\n  by (auto simp: gauss_int_eq_iff)\n\nlemma ReZ_of_nat [simp]: \"ReZ (of_nat n) = of_nat n\"\n  and ImZ_of_nat [simp]: \"ImZ (of_nat n) = 0\"\n  by (induction n; simp)+\n\nlemma ReZ_of_int [simp]: \"ReZ (of_int n) = n\"\n  and ImZ_of_int [simp]: \"ImZ (of_int n) = 0\"\n  by (induction n; simp)+\n\nlemma ReZ_numeral [simp]: \"ReZ (numeral n) = numeral n\"\n  and ImZ_numeral [simp]: \"ImZ (numeral n) = 0\"\n  by (subst of_nat_numeral [symmetric], subst ReZ_of_nat ImZ_of_nat, simp)+\n\nlemma gauss2complex_0 [simp]: \"gauss2complex 0 = 0\"\n  and gauss2complex_1 [simp]: \"gauss2complex 1 = 1\"\n  and gauss2complex_i [simp]: \"gauss2complex \\<i>\\<^sub>\\<int> = \\<i>\"\n  and gauss2complex_add [simp]: \"gauss2complex (x + y) = gauss2complex x + gauss2complex y\"\n  and gauss2complex_diff [simp]: \"gauss2complex (x - y) = gauss2complex x - gauss2complex y\"\n  and gauss2complex_mult [simp]: \"gauss2complex (x * y) = gauss2complex x * gauss2complex y\"\n  and gauss2complex_uminus [simp]: \"gauss2complex (-x) = -gauss2complex x\"\n  and gauss2complex_cnj [simp]: \"gauss2complex (gauss_cnj x) = cnj (gauss2complex x)\"\n  by (simp_all add: complex_eq_iff)\n\nlemma gauss2complex_of_nat [simp]: \"gauss2complex (of_nat n) = of_nat n\"\n  by (simp add: complex_eq_iff)\n\nlemma gauss2complex_eq_0_iff [simp]: \"gauss2complex x = 0 \\<longleftrightarrow> x = 0\"\n  and gauss2complex_eq_1_iff [simp]: \"gauss2complex x = 1 \\<longleftrightarrow> x = 1\"\n  and zero_eq_gauss2complex_iff [simp]: \"0 = gauss2complex x \\<longleftrightarrow> x = 0\"\n  and one_eq_gauss2complex_iff [simp]: \"1 = gauss2complex x \\<longleftrightarrow> x = 1\"\n  by (simp_all add: complex_eq_iff gauss_int_eq_iff)\n\nlemma gauss_i_times_gauss_i_times [simp]: \"\\<i>\\<^sub>\\<int> * (\\<i>\\<^sub>\\<int> * x) = (-x :: gauss_int)\"\n  by (subst mult.assoc [symmetric], subst gauss_i_times_i) auto\n\nlemma gauss_i_neq_0 [simp]: \"\\<i>\\<^sub>\\<int> \\<noteq> 0\" \"0 \\<noteq> \\<i>\\<^sub>\\<int>\"\n  and gauss_i_neq_1 [simp]: \"\\<i>\\<^sub>\\<int> \\<noteq> 1\" \"1 \\<noteq> \\<i>\\<^sub>\\<int>\"\n  and gauss_i_neq_of_nat [simp]: \"\\<i>\\<^sub>\\<int> \\<noteq> of_nat n\" \"of_nat n \\<noteq> \\<i>\\<^sub>\\<int>\"\n  and gauss_i_neq_of_int [simp]: \"\\<i>\\<^sub>\\<int> \\<noteq> of_int n\" \"of_int n \\<noteq> \\<i>\\<^sub>\\<int>\"\n  and gauss_i_neq_numeral [simp]: \"\\<i>\\<^sub>\\<int> \\<noteq> numeral m\" \"numeral m \\<noteq> \\<i>\\<^sub>\\<int>\"\n  by (auto simp: gauss_int_eq_iff)\n\nlemma gauss_cnj_0 [simp]: \"gauss_cnj 0 = 0\"\n  and gauss_cnj_1 [simp]: \"gauss_cnj 1 = 1\"\n  and gauss_cnj_cnj [simp]: \"gauss_cnj (gauss_cnj z) = z\"\n  and gauss_cnj_uminus [simp]: \"gauss_cnj (-a) = -gauss_cnj a\"\n  and gauss_cnj_add [simp]: \"gauss_cnj (a + b) = gauss_cnj a + gauss_cnj b\"\n  and gauss_cnj_diff [simp]: \"gauss_cnj (a - b) = gauss_cnj a - gauss_cnj b\"\n  and gauss_cnj_mult [simp]: \"gauss_cnj (a * b) = gauss_cnj a * gauss_cnj b\"\n  and gauss_cnj_of_nat [simp]: \"gauss_cnj (of_nat n1) = of_nat n1\"\n  and gauss_cnj_of_int [simp]: \"gauss_cnj (of_int n2) = of_int n2\"\n  and gauss_cnj_numeral [simp]: \"gauss_cnj (numeral n3) = numeral n3\"\n  by (simp_all add: gauss_int_eq_iff)\n\nlemma gauss_cnj_power [simp]: \"gauss_cnj (a ^ n) = gauss_cnj a ^ n\"\n  by (induction n) auto\n\nlemma gauss_cnj_sum [simp]: \"gauss_cnj (sum f A) = (\\<Sum>x\\<in>A. gauss_cnj (f x))\"\n  by (induction A rule: infinite_finite_induct) auto\n\nlemma gauss_cnj_prod [simp]: \"gauss_cnj (prod f A) = (\\<Prod>x\\<in>A. gauss_cnj (f x))\"\n  by (induction A rule: infinite_finite_induct) auto\n\nlemma of_nat_dvd_of_nat:\n  assumes \"a dvd b\"\n  shows   \"of_nat a dvd (of_nat b :: 'a :: comm_semiring_1)\"\n  using assms by auto\n\nlemma of_int_dvd_imp_dvd_gauss_cnj:\n  fixes z :: gauss_int\n  assumes \"of_int n dvd z\"\n  shows   \"of_int n dvd gauss_cnj z\"\nproof -\n  from assms obtain u where \"z = of_int n * u\" by blast\n  hence \"gauss_cnj z = of_int n * gauss_cnj u\"\n    by simp\n  thus ?thesis by auto\nqed\n\nlemma of_nat_dvd_imp_dvd_gauss_cnj:\n  fixes z :: gauss_int\n  assumes \"of_nat n dvd z\"\n  shows   \"of_nat n dvd gauss_cnj z\"\n  using of_int_dvd_imp_dvd_gauss_cnj[of \"int n\"] assms by simp\n\nlemma of_int_dvd_of_int_gauss_int_iff:\n  \"(of_int m :: gauss_int) dvd of_int n \\<longleftrightarrow> m dvd n\"\nproof\n  assume \"of_int m dvd (of_int n :: gauss_int)\"\n  then obtain a :: gauss_int where \"of_int n = of_int m * a\"\n    by blast\n  thus \"m dvd n\"\n    by (auto simp: gauss_int_eq_iff)\nqed auto\n\nlemma of_nat_dvd_of_nat_gauss_int_iff:\n  \"(of_nat m :: gauss_int) dvd of_nat n \\<longleftrightarrow> m dvd n\"\n  using of_int_dvd_of_int_gauss_int_iff[of \"int m\" \"int n\"] by simp\n\nlemma gauss_cnj_dvd:\n  assumes \"a dvd b\"\n  shows   \"gauss_cnj a dvd gauss_cnj b\"\nproof -\n  from assms obtain c where \"b = a * c\"\n    by blast\n  hence \"gauss_cnj b = gauss_cnj a * gauss_cnj c\"\n    by simp\n  thus ?thesis by auto\nqed\n\nlemma gauss_cnj_dvd_iff: \"gauss_cnj a dvd gauss_cnj b \\<longleftrightarrow> a dvd b\"\n  using gauss_cnj_dvd[of a b] gauss_cnj_dvd[of \"gauss_cnj a\" \"gauss_cnj b\"] by auto\n\nlemma gauss_cnj_dvd_left_iff: \"gauss_cnj a dvd b \\<longleftrightarrow> a dvd gauss_cnj b\"\n  by (subst gauss_cnj_dvd_iff [symmetric]) auto\n\nlemma gauss_cnj_dvd_right_iff: \"a dvd gauss_cnj b \\<longleftrightarrow> gauss_cnj a dvd b\"\n  by (rule gauss_cnj_dvd_left_iff [symmetric])\n\n\ninstance gauss_int :: idom\nproof\n  fix z u :: gauss_int\n  assume \"z \\<noteq> 0\" \"u \\<noteq> 0\"\n  hence \"gauss2complex z * gauss2complex u \\<noteq> 0\"\n    by simp\n  also have \"gauss2complex z * gauss2complex u = gauss2complex (z * u)\"\n    by simp\n  finally show \"z * u \\<noteq> 0\"\n    unfolding gauss2complex_eq_0_iff .\nqed\n\ninstance gauss_int :: ring_char_0\n  by intro_classes (auto intro!: injI simp: gauss_int_eq_iff)\n\n\nsubsection \\<open>Pretty-printing\\<close>\n\ntext \\<open>\n  The following lemma collection provides better pretty-printing of Gaussian integers so that\n  e.g.\\ evaluation with the `value' command produces nicer results.\n\\<close>\nlemma gauss_int_code_post [code_post]:\n  \"Gauss_Int 0 0 = 0\"\n  \"Gauss_Int 0 1 = \\<i>\\<^sub>\\<int>\"\n  \"Gauss_Int 0 (-1) = -\\<i>\\<^sub>\\<int>\"\n  \"Gauss_Int 1 0 = 1\"\n  \"Gauss_Int 1 1 = 1 + \\<i>\\<^sub>\\<int>\"\n  \"Gauss_Int 1 (-1) = 1 - \\<i>\\<^sub>\\<int>\"\n  \"Gauss_Int (-1) 0 = -1\"\n  \"Gauss_Int (-1) 1 = -1 + \\<i>\\<^sub>\\<int>\"\n  \"Gauss_Int (-1) (-1) = -1 - \\<i>\\<^sub>\\<int>\"  \n  \"Gauss_Int (numeral b) 0 = numeral b\"\n  \"Gauss_Int (-numeral b) 0 = -numeral b\"\n  \"Gauss_Int (numeral b) 1 = numeral b + \\<i>\\<^sub>\\<int>\"\n  \"Gauss_Int (-numeral b) 1 = -numeral b + \\<i>\\<^sub>\\<int>\"\n  \"Gauss_Int (numeral b) (-1) = numeral b - \\<i>\\<^sub>\\<int>\"\n  \"Gauss_Int (-numeral b) (-1) = -numeral b - \\<i>\\<^sub>\\<int>\"\n  \"Gauss_Int 0 (numeral b) = numeral b * \\<i>\\<^sub>\\<int>\"\n  \"Gauss_Int 0 (-numeral b) = -numeral b * \\<i>\\<^sub>\\<int>\"\n  \"Gauss_Int 1 (numeral b) = 1 + numeral b * \\<i>\\<^sub>\\<int>\"\n  \"Gauss_Int 1 (-numeral b) = 1 - numeral b * \\<i>\\<^sub>\\<int>\"\n  \"Gauss_Int (-1) (numeral b) = -1 + numeral b * \\<i>\\<^sub>\\<int>\"\n  \"Gauss_Int (-1) (-numeral b) = -1 - numeral b * \\<i>\\<^sub>\\<int>\"\n  \"Gauss_Int (numeral a) (numeral b) = numeral a + numeral b * \\<i>\\<^sub>\\<int>\"\n  \"Gauss_Int (numeral a) (-numeral b) = numeral a - numeral b * \\<i>\\<^sub>\\<int>\"\n  \"Gauss_Int (-numeral a) (numeral b) = -numeral a + numeral b * \\<i>\\<^sub>\\<int>\"\n  \"Gauss_Int (-numeral a) (-numeral b) = -numeral a - numeral b * \\<i>\\<^sub>\\<int>\"\n  by (simp_all add: gauss_int_eq_iff)\n\nvalue \"\\<i>\\<^sub>\\<int> ^ 3\"\nvalue \"2 * (3 + \\<i>\\<^sub>\\<int>)\"\nvalue \"(2 + \\<i>\\<^sub>\\<int>) * (2 - \\<i>\\<^sub>\\<int>)\"\n\n\nsubsection \\<open>Norm\\<close>\n\ntext \\<open>\n  The square of the complex norm (or complex modulus) on the Gaussian integers gives us a norm\n  that always returns a natural number. We will later show that this is also a Euclidean norm\n  (in the sense of a Euclidean ring).\n\\<close>\ndefinition gauss_int_norm :: \"gauss_int \\<Rightarrow> nat\" where\n  \"gauss_int_norm z = nat (ReZ z ^ 2 + ImZ z ^ 2)\"\n\nlemma gauss_int_norm_0 [simp]: \"gauss_int_norm 0 = 0\"\n  and gauss_int_norm_1 [simp]: \"gauss_int_norm 1 = 1\"\n  and gauss_int_norm_i [simp]: \"gauss_int_norm \\<i>\\<^sub>\\<int> = 1\"\n  and gauss_int_norm_cnj [simp]: \"gauss_int_norm (gauss_cnj z) = gauss_int_norm z\"\n  and gauss_int_norm_of_nat [simp]: \"gauss_int_norm (of_nat n) = n ^ 2\"\n  and gauss_int_norm_of_int [simp]: \"gauss_int_norm (of_int m) = nat (m ^ 2)\"\n  and gauss_int_norm_of_numeral [simp]: \"gauss_int_norm (numeral n') = numeral (Num.sqr n')\"\n  by (simp_all add: gauss_int_norm_def nat_power_eq)\n\nlemma gauss_int_norm_uminus [simp]: \"gauss_int_norm (-z) = gauss_int_norm z\"\n  by (simp add: gauss_int_norm_def)\n\nlemma gauss_int_norm_eq_0_iff [simp]: \"gauss_int_norm z = 0 \\<longleftrightarrow> z = 0\"\nproof\n  assume \"gauss_int_norm z = 0\"\n  hence \"ReZ z ^ 2 + ImZ z ^ 2 \\<le> 0\"\n    by (simp add: gauss_int_norm_def)\n  moreover have \"ReZ z ^ 2 + ImZ z ^ 2 \\<ge> 0\"\n    by simp\n  ultimately have \"ReZ z ^ 2 + ImZ z ^ 2 = 0\"\n    by linarith\n  thus \"z = 0\"\n    by (auto simp: gauss_int_eq_iff)\nqed auto\n\nlemma gauss_int_norm_pos_iff [simp]: \"gauss_int_norm z > 0 \\<longleftrightarrow> z \\<noteq> 0\"\n  using gauss_int_norm_eq_0_iff[of z] by (auto intro: Nat.gr0I)\n\nlemma real_gauss_int_norm: \"real (gauss_int_norm z) = norm (gauss2complex z) ^ 2\"\n  by (auto simp: cmod_def gauss_int_norm_def)\n\nlemma gauss_int_norm_mult: \"gauss_int_norm (z * u) = gauss_int_norm z * gauss_int_norm u\"\nproof -\n  have \"real (gauss_int_norm (z * u)) = real (gauss_int_norm z * gauss_int_norm u)\"\n    unfolding of_nat_mult by (simp add: real_gauss_int_norm norm_power norm_mult power_mult_distrib)\n  thus ?thesis by (subst (asm) of_nat_eq_iff)\nqed\n\nlemma self_mult_gauss_cnj: \"z * gauss_cnj z = of_nat (gauss_int_norm z)\"\n  by (simp add: gauss_int_norm_def gauss_int_eq_iff algebra_simps power2_eq_square)\n\nlemma gauss_cnj_mult_self: \"gauss_cnj z * z = of_nat (gauss_int_norm z)\"\n  by (subst mult.commute, rule self_mult_gauss_cnj)\n\nlemma self_plus_gauss_cnj: \"z + gauss_cnj z = of_int (2 * ReZ z)\"\n  and self_minus_gauss_cnj: \"z - gauss_cnj z = of_int (2 * ImZ z) * \\<i>\\<^sub>\\<int>\"\n  by (auto simp: gauss_int_eq_iff)\n\nlemma gauss_int_norm_dvd_mono:\n  assumes \"a dvd b\"\n  shows \"gauss_int_norm a dvd gauss_int_norm b\"\nproof -\n  from assms obtain c where \"b = a * c\" by blast\n  hence \"gauss_int_norm b = gauss_int_norm (a * c)\"\n    by metis\n  thus ?thesis by (simp add: gauss_int_norm_mult)\nqed\n\ntext \\<open>\n  A Gaussian integer is a unit iff its norm is 1, and this is the case precisely for the four\n  elements \\<open>\\<plusminus>1\\<close> and \\<open>\\<plusminus>\\<i>\\<close>:\n\\<close>\nlemma is_unit_gauss_int_iff: \"x dvd 1 \\<longleftrightarrow> x \\<in> {1, -1, \\<i>\\<^sub>\\<int>, -\\<i>\\<^sub>\\<int> :: gauss_int}\"\n  and is_unit_gauss_int_iff': \"x dvd 1 \\<longleftrightarrow> gauss_int_norm x = 1\"\nproof -\n  have \"x dvd 1\" if \"x \\<in> {1, -1, \\<i>\\<^sub>\\<int>, -\\<i>\\<^sub>\\<int>}\"\n  proof -\n    from that have *: \"x * gauss_cnj x = 1\"\n      by (auto simp: gauss_int_norm_def)\n    show \"x dvd 1\" by (subst * [symmetric]) simp\n  qed\n  moreover have \"gauss_int_norm x = 1\" if \"x dvd 1\"\n    using gauss_int_norm_dvd_mono[OF that] by simp\n  moreover have \"x \\<in> {1, -1, \\<i>\\<^sub>\\<int>, -\\<i>\\<^sub>\\<int>}\" if \"gauss_int_norm x = 1\"\n  proof -\n    from that have *: \"(ReZ x)\\<^sup>2 + (ImZ x)\\<^sup>2 = 1\"\n      by (auto simp: gauss_int_norm_def nat_eq_iff)\n    hence \"ReZ x ^ 2 \\<le> 1\" and \"ImZ x ^ 2 \\<le> 1\"\n      using zero_le_power2[of \"ImZ x\"] zero_le_power2[of \"ReZ x\"] by linarith+\n    hence \"\\<bar>ReZ x\\<bar> \\<le> 1\" and \"\\<bar>ImZ x\\<bar> \\<le> 1\"\n      by (auto simp: abs_square_le_1)\n    hence \"ReZ x \\<in> {-1, 0, 1}\" and \"ImZ x \\<in> {-1, 0, 1}\"\n      by auto\n    thus \"x \\<in> {1, -1, \\<i>\\<^sub>\\<int>, -\\<i>\\<^sub>\\<int> :: gauss_int}\"\n      using * by (auto simp: gauss_int_eq_iff)    \n  qed\n  ultimately show \"x dvd 1 \\<longleftrightarrow> x \\<in> {1, -1, \\<i>\\<^sub>\\<int>, -\\<i>\\<^sub>\\<int> :: gauss_int}\"\n              and \"x dvd 1 \\<longleftrightarrow> gauss_int_norm x = 1\"\n    by blast+\nqed\n\nlemma is_unit_gauss_i [simp, intro]: \"(gauss_i :: gauss_int) dvd 1\"\n  by (simp add: is_unit_gauss_int_iff)\n\nlemma gauss_int_norm_eq_Suc_0_iff: \"gauss_int_norm x = Suc 0 \\<longleftrightarrow> x dvd 1\"\n  by (simp add: is_unit_gauss_int_iff')\n\nlemma is_unit_gauss_cnj [intro]: \"z dvd 1 \\<Longrightarrow> gauss_cnj z dvd 1\"\n  by (simp add: is_unit_gauss_int_iff')\n\nlemma is_unit_gauss_cnj_iff [simp]: \"gauss_cnj z dvd 1 \\<longleftrightarrow> z dvd 1\"\n  by (simp add: is_unit_gauss_int_iff')\n\n\nsubsection \\<open>Division and normalisation\\<close>\n\ntext \\<open>\n  We define a rounding operation that takes a complex number and returns a Gaussian integer\n  by rounding the real and imaginary parts separately:\n\\<close>\nprimcorec round_complex :: \"complex \\<Rightarrow> gauss_int\" where\n  \"ReZ (round_complex z) = round (Re z)\"\n| \"ImZ (round_complex z) = round (Im z)\"\n\ntext \\<open>\n  The distance between a rounded complex number and the original one is no more than\n  $\\frac{1}{2}\\sqrt{2}$:\n\\<close>\nlemma norm_round_complex_le: \"norm (z - gauss2complex (round_complex z)) ^ 2 \\<le> 1 / 2\"\nproof -\n  have \"(Re z - ReZ (round_complex z)) ^ 2 \\<le> (1 / 2) ^ 2\"\n    using of_int_round_abs_le[of \"Re z\"]\n    by (subst abs_le_square_iff [symmetric]) (auto simp: abs_minus_commute)\n  moreover have \"(Im z - ImZ (round_complex z)) ^ 2 \\<le> (1 / 2) ^ 2\"\n    using of_int_round_abs_le[of \"Im z\"]\n    by (subst abs_le_square_iff [symmetric]) (auto simp: abs_minus_commute)\n  ultimately have \"(Re z - ReZ (round_complex z)) ^ 2 + (Im z - ImZ (round_complex z)) ^ 2 \\<le>\n                     (1 / 2) ^ 2 + (1 / 2) ^ 2\"\n    by (rule add_mono)\n  thus \"norm (z - gauss2complex (round_complex z)) ^ 2 \\<le> 1 / 2\"\n    by (simp add: cmod_def power2_eq_square)\nqed\n\nlemma dist_round_complex_le: \"dist z (gauss2complex (round_complex z)) \\<le> sqrt 2 / 2\"\nproof -\n  have \"dist z (gauss2complex (round_complex z)) ^ 2 =\n        norm (z - gauss2complex (round_complex z)) ^ 2\"\n    by (simp add: dist_norm)\n  also have \"\\<dots> \\<le> 1 / 2\"\n    by (rule norm_round_complex_le)\n  also have \"\\<dots> = (sqrt 2 / 2) ^ 2\"\n    by (simp add: power2_eq_square)\n  finally show ?thesis\n    by (rule power2_le_imp_le) auto\nqed\n\n\ntext \\<open>\n  We can now define division on Gaussian integers simply by performing the division in the\n  complex numbers and rounding the result. This also gives us a remainder operation defined\n  accordingly for which the norm of the remainder is always smaller than the norm of the divisor.\n\n  We can also define a normalisation operation that returns a canonical representative for each\n  association class. Since the four units of the Gaussian integers are \\<open>\\<plusminus>1\\<close> and \\<open>\\<plusminus>\\<i>\\<close>, each\n  association class (other than \\<open>0\\<close>) has four representatives, one in each quadrant. We simply\n  define the on in the upper-right quadrant (i.e.\\ the one with non-negative imaginary part\n  and positive real part) as the canonical one.\n\n  Thus, the Gaussian integers form a Euclidean ring. This gives us many things, most importantly\n  the existence of GCDs and LCMs and unique factorisation.\n\\<close>\ninstantiation gauss_int :: algebraic_semidom\nbegin\n\ndefinition divide_gauss_int :: \"gauss_int \\<Rightarrow> gauss_int \\<Rightarrow> gauss_int\" where\n  \"divide_gauss_int a b = round_complex (gauss2complex a / gauss2complex b)\"\n\ninstance proof\n  fix a :: gauss_int\n  show \"a div 0 = 0\"\n    by (auto simp: gauss_int_eq_iff divide_gauss_int_def)\nnext\n  fix a b :: gauss_int assume \"b \\<noteq> 0\"\n  thus \"a * b div b = a\"\n    by (auto simp: gauss_int_eq_iff divide_gauss_int_def)\nqed\n\nend\n\ninstantiation gauss_int :: semidom_divide_unit_factor\nbegin\n\ndefinition unit_factor_gauss_int :: \"gauss_int \\<Rightarrow> gauss_int\" where\n  \"unit_factor_gauss_int z =\n     (if z = 0 then 0 else \n      if ImZ z \\<ge> 0 \\<and> ReZ z > 0 then 1\n      else if ReZ z \\<le> 0 \\<and> ImZ z > 0 then \\<i>\\<^sub>\\<int>\n      else if ImZ z \\<le> 0 \\<and> ReZ z < 0 then -1\n      else -\\<i>\\<^sub>\\<int>)\"\n\ninstance proof\n  show \"unit_factor (0 :: gauss_int) = 0\"\n    by (simp add: unit_factor_gauss_int_def)\nnext\n  fix z :: gauss_int\n  assume \"is_unit z\"\n  thus \"unit_factor z = z\"\n    by (subst (asm) is_unit_gauss_int_iff) (auto simp: unit_factor_gauss_int_def)\nnext\n  fix z :: gauss_int\n  assume z: \"z \\<noteq> 0\"\n  thus \"is_unit (unit_factor z)\"\n    by (subst is_unit_gauss_int_iff) (auto simp: unit_factor_gauss_int_def)\nnext\n  fix z u :: gauss_int\n  assume \"is_unit z\"\n  hence \"z \\<in> {1, -1, \\<i>\\<^sub>\\<int>, -\\<i>\\<^sub>\\<int>}\"\n    by (subst (asm) is_unit_gauss_int_iff)\n  thus \"unit_factor (z * u) = z * unit_factor u\"\n    by (safe; auto simp: unit_factor_gauss_int_def gauss_int_eq_iff[of u 0])\nqed\n\nend\n\ninstantiation gauss_int :: normalization_semidom\nbegin\n\ndefinition normalize_gauss_int :: \"gauss_int \\<Rightarrow> gauss_int\" where\n  \"normalize_gauss_int z =\n     (if z = 0 then 0 else \n      if ImZ z \\<ge> 0 \\<and> ReZ z > 0 then z\n      else if ReZ z \\<le> 0 \\<and> ImZ z > 0 then -\\<i>\\<^sub>\\<int> * z\n      else if ImZ z \\<le> 0 \\<and> ReZ z < 0 then -z\n      else \\<i>\\<^sub>\\<int> * z)\"\n\ninstance proof\n  show \"normalize (0 :: gauss_int) = 0\"\n    by (simp add: normalize_gauss_int_def)\nnext\n  fix z :: gauss_int\n  show \"unit_factor z * normalize z = z\"\n    by (auto simp: normalize_gauss_int_def unit_factor_gauss_int_def algebra_simps)\nqed\n\nend\n\nlemma normalize_gauss_int_of_nat [simp]: \"normalize (of_nat n :: gauss_int) = of_nat n\"\n  and normalize_gauss_int_of_int [simp]: \"normalize (of_int m :: gauss_int) = of_int \\<bar>m\\<bar>\"\n  and normalize_gauss_int_of_numeral [simp]: \"normalize (numeral n' :: gauss_int) = numeral n'\"\n  by (auto simp: normalize_gauss_int_def)\n\nlemma normalize_gauss_i [simp]: \"normalize \\<i>\\<^sub>\\<int> = 1\"\n  by (simp add: normalize_gauss_int_def)\n\nlemma gauss_int_norm_normalize [simp]: \"gauss_int_norm (normalize x) = gauss_int_norm x\"\n  by (simp add: normalize_gauss_int_def gauss_int_norm_mult)\n\nlemma normalized_gauss_int:\n  assumes \"normalize z = z\"\n  shows   \"ReZ z \\<ge> 0\" \"ImZ z \\<ge> 0\"\n  using assms\n  by (cases \"ReZ z\" \"0 :: int\" rule: linorder_cases;\n      cases \"ImZ z\" \"0 :: int\" rule: linorder_cases;\n      simp add: normalize_gauss_int_def gauss_int_eq_iff)+\n\n\n\nlemma normalized_gauss_int_iff:\n  \"normalize z = z \\<longleftrightarrow> z = 0 \\<or> ReZ z > 0 \\<and> ImZ z \\<ge> 0\"\n  by (cases \"ReZ z\" \"0 :: int\" rule: linorder_cases;\n      cases \"ImZ z\" \"0 :: int\" rule: linorder_cases;\n      simp add: normalize_gauss_int_def gauss_int_eq_iff)+\n\ninstantiation gauss_int :: idom_modulo\nbegin\n\ndefinition modulo_gauss_int :: \"gauss_int \\<Rightarrow> gauss_int \\<Rightarrow> gauss_int\" where\n  \"modulo_gauss_int a b = a - a div b * b\"\n\ninstance proof\n  fix a b :: gauss_int\n  show \"a div b * b + a mod b = a\"\n    by (simp add: modulo_gauss_int_def)\nqed\n\nend\n\nlemma gauss_int_norm_mod_less_aux:\n  assumes [simp]: \"b \\<noteq> 0\"\n  shows   \"2 * gauss_int_norm (a mod b) \\<le> gauss_int_norm b\"\nproof -\n  define a' b' where \"a' = gauss2complex a\" and \"b' = gauss2complex b\"\n  have [simp]: \"b' \\<noteq> 0\" by (simp add: b'_def)\n  have \"gauss_int_norm (a mod b) = \n          norm (gauss2complex (a - round_complex (a' / b') * b)) ^ 2\"\n    unfolding modulo_gauss_int_def\n    by (subst real_gauss_int_norm [symmetric]) (auto simp add: divide_gauss_int_def a'_def b'_def)\n  also have \"gauss2complex (a - round_complex (a' / b') * b) =\n               a' - gauss2complex (round_complex (a' / b')) * b'\"\n    by (simp add: a'_def b'_def)\n  also have \"\\<dots> = (a' / b' - gauss2complex (round_complex (a' / b'))) * b'\"\n    by (simp add: field_simps)\n  also have \"norm \\<dots> ^ 2 = norm (a' / b' - gauss2complex (round_complex (a' / b'))) ^ 2 * norm b' ^ 2\"\n    by (simp add: norm_mult power_mult_distrib)\n  also have \"\\<dots> \\<le> 1 / 2 * norm b' ^ 2\"\n    by (intro mult_right_mono norm_round_complex_le) auto\n  also have \"norm b' ^ 2 = gauss_int_norm b\"\n    by (simp add: b'_def real_gauss_int_norm)\n  finally show ?thesis by linarith\nqed\n\nlemma gauss_int_norm_mod_less:\n  assumes [simp]: \"b \\<noteq> 0\"\n  shows   \"gauss_int_norm (a mod b) < gauss_int_norm b\"\nproof -\n  have \"gauss_int_norm b > 0\" by simp\n  thus \"gauss_int_norm (a mod b) < gauss_int_norm b\"\n    using gauss_int_norm_mod_less_aux[OF assms, of a] by presburger\nqed\n\nlemma gauss_int_norm_dvd_imp_le:\n  assumes \"b \\<noteq> 0\"\n  shows   \"gauss_int_norm a \\<le> gauss_int_norm (a * b)\"\nproof (cases \"a = 0\")\n  case False\n  thus ?thesis using assms by (intro dvd_imp_le gauss_int_norm_dvd_mono) auto\nqed auto\n\ninstantiation gauss_int :: euclidean_ring\nbegin\n\ndefinition euclidean_size_gauss_int :: \"gauss_int \\<Rightarrow> nat\" where\n  [simp]: \"euclidean_size_gauss_int = gauss_int_norm\"\n\ninstance proof\n  show \"euclidean_size (0 :: gauss_int) = 0\"\n    by simp\nnext\n  fix a b :: gauss_int assume [simp]: \"b \\<noteq> 0\"\n  show \"euclidean_size (a mod b) < euclidean_size b\"\n    using gauss_int_norm_mod_less[of b a] by simp\n  show \"euclidean_size a \\<le> euclidean_size (a * b)\"\n    by (simp add: gauss_int_norm_dvd_imp_le)\nqed\n\nend\n\ninstance gauss_int :: normalization_euclidean_semiring ..\n\ninstantiation gauss_int :: euclidean_ring_gcd\nbegin\n\ndefinition gcd_gauss_int :: \"gauss_int \\<Rightarrow> gauss_int \\<Rightarrow> gauss_int\" where\n  \"gcd_gauss_int \\<equiv> normalization_euclidean_semiring_class.gcd\"\ndefinition lcm_gauss_int :: \"gauss_int \\<Rightarrow> gauss_int \\<Rightarrow> gauss_int\" where\n  \"lcm_gauss_int \\<equiv> normalization_euclidean_semiring_class.lcm\"\ndefinition Gcd_gauss_int :: \"gauss_int set \\<Rightarrow> gauss_int\" where\n  \"Gcd_gauss_int \\<equiv> normalization_euclidean_semiring_class.Gcd\"\ndefinition Lcm_gauss_int :: \"gauss_int set \\<Rightarrow> gauss_int\" where\n  \"Lcm_gauss_int \\<equiv> normalization_euclidean_semiring_class.Lcm\"\n\ninstance \n  by intro_classes\n     (simp_all add: gcd_gauss_int_def lcm_gauss_int_def Gcd_gauss_int_def Lcm_gauss_int_def)\n\nend\n\nlemma multiplicity_gauss_cnj: \"multiplicity (gauss_cnj a) (gauss_cnj b) = multiplicity a b\"\n  unfolding multiplicity_def gauss_cnj_power [symmetric] gauss_cnj_dvd_iff ..\n    \nlemma multiplicity_gauss_int_of_nat:\n  \"multiplicity (of_nat a) (of_nat b :: gauss_int) = multiplicity a b\"\n  unfolding multiplicity_def of_nat_power [symmetric] of_nat_dvd_of_nat_gauss_int_iff ..\n\nlemma gauss_int_dvd_same_norm_imp_associated:\n  assumes \"z1 dvd z2\" \"gauss_int_norm z1 = gauss_int_norm z2\"\n  shows   \"normalize z1 = normalize z2\"\nproof (cases \"z1 = 0\")\n  case [simp]: False\n  from assms(1) obtain u where u: \"z2 = z1 * u\" by blast\n  from assms have \"gauss_int_norm u = 1\"\n    by (auto simp: gauss_int_norm_mult u)\n  hence \"is_unit u\"\n    by (simp add: is_unit_gauss_int_iff')\n  with u show ?thesis by simp\nqed (use assms in auto)\n\nlemma gcd_of_int_gauss_int: \"gcd (of_int a :: gauss_int) (of_int b) = of_int (gcd a b)\"\nproof (induction \"nat \\<bar>b\\<bar>\" arbitrary: a b rule: less_induct)\n  case (less b a)\n  show ?case\n  proof (cases \"b = 0\")\n    case False\n    have \"of_int (gcd a b) = (of_int (gcd b (a mod b)) :: gauss_int)\"\n      by (subst gcd_red_int) auto\n    also have \"\\<dots> = gcd (of_int b) (of_int (a mod b))\"\n      using False by (intro less [symmetric]) (auto intro!: abs_mod_less)\n    also have \"a mod b = (a - a div b * b)\"\n      by (simp add: minus_div_mult_eq_mod)\n    also have \"of_int \\<dots> = of_int (-(a div b)) * of_int b + (of_int a :: gauss_int)\"\n      by (simp add: algebra_simps)\n    also have \"gcd (of_int b) \\<dots> = gcd (of_int b) (of_int a)\"\n      by (rule gcd_add_mult)\n    finally show ?thesis by (simp add: gcd.commute)\n  qed auto\nqed\n\nlemma coprime_of_int_gauss_int: \"coprime (of_int a :: gauss_int) (of_int b) = coprime a b\"\n  unfolding coprime_iff_gcd_eq_1 gcd_of_int_gauss_int by auto\n\n\n\nlemma coprime_of_nat_gauss_int: \"coprime (of_nat a :: gauss_int) (of_nat b) = coprime a b\"\n  unfolding coprime_iff_gcd_eq_1 gcd_of_nat_gauss_int by auto\n\n\n\nlemma self_dvd_gauss_cnj_iff: \"z dvd gauss_cnj z \\<longleftrightarrow> ReZ z = 0 \\<or> ImZ z = 0 \\<or> \\<bar>ReZ z\\<bar> = \\<bar>ImZ z\\<bar>\"\n  using gauss_cnj_dvd_self_iff[of z] by (subst (asm) gauss_cnj_dvd_left_iff) auto\n\n\nsubsection \\<open>Prime elements\\<close>\n\ntext \\<open>\n  Next, we analyse what the prime elements of the Gaussian integers are. First, note that\n  according to the conventions of Isabelle's computational algebra library, a prime element\n  is called a prime iff it is also normalised, i.e.\\ in our case it lies in the upper right\n  quadrant.\n\n  As a first fact, we can show that a Gaussian integer whose norm is \\<open>\\<int>\\<close>-prime must be\n  $\\mathbb{Z}[i]$-prime:\n\\<close>\n\nlemma prime_gauss_int_norm_imp_prime_elem:\n  assumes \"prime (gauss_int_norm q)\"\n  shows   \"prime_elem q\"\nproof -\n  have \"irreducible q\"\n  proof (rule irreducibleI)\n    fix a b assume \"q = a * b\"\n    hence \"gauss_int_norm q = gauss_int_norm a * gauss_int_norm b\"\n      by (simp_all add: gauss_int_norm_mult)\n    thus \"is_unit a \\<or> is_unit b\"\n      using assms by (auto dest!: prime_product simp: gauss_int_norm_eq_Suc_0_iff)\n  qed (use assms in \\<open>auto simp: is_unit_gauss_int_iff'\\<close>)\n  thus \"prime_elem q\"\n    using irreducible_imp_prime_elem_gcd by blast\nqed\n\ntext \\<open>\n  Also, a conjugate is a prime element iff the original element is a prime element:\n\\<close>\nlemma prime_elem_gauss_cnj [intro]: \"prime_elem z \\<Longrightarrow> prime_elem (gauss_cnj z)\"\n  by (auto simp: prime_elem_def gauss_cnj_dvd_left_iff)\n\nlemma prime_elem_gauss_cnj_iff [simp]: \"prime_elem (gauss_cnj z) \\<longleftrightarrow> prime_elem z\"\n  using prime_elem_gauss_cnj[of z] prime_elem_gauss_cnj[of \"gauss_cnj z\"] by auto\n\n\nsubsubsection \\<open>The factorisation of 2\\<close>\n\ntext \\<open>\n  2 factors as $-i (1 + i)^2$ in the Gaussian integers, where $-i$ is a unit and\n  $1 + i$ is prime.\n\\<close>\n\nlemma gauss_int_2_eq: \"2 = -\\<i>\\<^sub>\\<int> * (1 + \\<i>\\<^sub>\\<int>) ^ 2\"\n  by (simp add: gauss_int_eq_iff power2_eq_square)\n\nlemma prime_elem_one_plus_i_gauss_int: \"prime_elem (1 + \\<i>\\<^sub>\\<int>)\"\n  by (rule prime_gauss_int_norm_imp_prime_elem) (auto simp: gauss_int_norm_def)\n\nlemma prime_one_plus_i_gauss_int: \"prime (1 + \\<i>\\<^sub>\\<int>)\"\n  by (simp add: prime_def prime_elem_one_plus_i_gauss_int\n                gauss_int_eq_iff normalize_gauss_int_def)\n\nlemma prime_factorization_2_gauss_int:\n  \"prime_factorization (2 :: gauss_int) = {#1 + \\<i>\\<^sub>\\<int>, 1 + \\<i>\\<^sub>\\<int>#}\"\nproof -\n  have \"prime_factorization (2 :: gauss_int) =\n        (prime_factorization (prod_mset {#1 + gauss_i, 1 + gauss_i#}))\"\n    by (subst prime_factorization_unique) (auto simp: gauss_int_eq_iff normalize_gauss_int_def)\n  also have \"prime_factorization (prod_mset {#1 + gauss_i, 1 + gauss_i#}) =\n               {#1 + gauss_i, 1 + gauss_i#}\"\n    using prime_one_plus_i_gauss_int by (subst prime_factorization_prod_mset_primes) auto\n  finally show ?thesis .\nqed\n\n\nsubsubsection \\<open>Inert primes\\<close>\n\ntext \\<open>\n  Any \\<open>\\<int>\\<close>-prime congruent 3 modulo 4 is also a Gaussian prime. These primes are called\n  \\<^emph>\\<open>inert\\<close>, because they do not decompose when moving from \\<open>\\<int>\\<close> to $\\mathbb{Z}[i]$.\n\\<close>\n\nlemma gauss_int_norm_not_3_mod_4: \"[gauss_int_norm z \\<noteq> 3] (mod 4)\"\nproof -\n  have A: \"ReZ z mod 4 \\<in> {0..3}\" \"ImZ z mod 4 \\<in> {0..3}\" by auto\n  have B: \"{0..3} = {0, 1, 2, 3 :: int}\" by auto\n\n  have \"[ReZ z ^ 2 + ImZ z ^ 2 = (ReZ z mod 4) ^ 2 + (ImZ z mod 4) ^ 2] (mod 4)\"\n    by (intro cong_add cong_pow) (auto simp: cong_def)\n  moreover have \"((ReZ z mod 4) ^ 2 + (ImZ z mod 4) ^ 2) mod 4 \\<noteq> 3 mod 4\"\n    using A unfolding B by auto\n  ultimately have \"[ReZ z ^ 2 + ImZ z ^ 2 \\<noteq> 3] (mod 4)\"\n    unfolding cong_def by metis\n  hence \"[int (nat (ReZ z ^ 2 + ImZ z ^ 2)) \\<noteq> int 3] (mod (int 4))\"\n    by simp\n  thus ?thesis unfolding gauss_int_norm_def\n    by (subst (asm) cong_int_iff)\nqed\n\nlemma prime_elem_gauss_int_of_nat:\n  fixes n :: nat\n  assumes prime: \"prime n\" and \"[n = 3] (mod 4)\"\n  shows   \"prime_elem (of_nat n :: gauss_int)\"\nproof (intro irreducible_imp_prime_elem irreducibleI)\n  from assms show \"of_nat n \\<noteq> (0 :: gauss_int)\"\n    by (auto simp: gauss_int_eq_iff)\nnext\n  show \"\\<not>is_unit (of_nat n :: gauss_int)\"\n    using assms by (subst is_unit_gauss_int_iff) (auto simp: gauss_int_eq_iff)\nnext\n  fix a b :: gauss_int\n  assume *: \"of_nat n = a * b\"\n  hence \"gauss_int_norm (a * b) = gauss_int_norm (of_nat n)\"\n    by metis\n  hence *: \"gauss_int_norm a * gauss_int_norm b = n ^ 2\"\n    by (simp add: gauss_int_norm_mult power2_eq_square flip: nat_mult_distrib)\n  from prime_power_mult_nat[OF prime this] obtain i j :: nat\n    where ij: \"gauss_int_norm a = n ^ i\" \"gauss_int_norm b = n ^ j\" by blast\n  \n  have \"i + j = 2\"\n  proof -\n    have \"n ^ (i + j) = n ^ 2\"\n      using ij * by (simp add: power_add)\n    from prime_power_inj[OF prime this] show ?thesis by simp\n  qed\n  hence \"i = 0 \\<and> j = 2 \\<or> i = 1 \\<and> j = 1 \\<or> i = 2 \\<and> j = 0\"\n    by auto\n  thus \"is_unit a \\<or> is_unit b\"\n  proof (elim disjE)\n    assume \"i = 1 \\<and> j = 1\"\n    with ij have \"gauss_int_norm a = n\"\n      by auto\n    hence \"[gauss_int_norm a = n] (mod 4)\"\n      by simp\n    also have \"[n = 3] (mod 4)\" by fact\n    finally have \"[gauss_int_norm a = 3] (mod 4)\" .\n    moreover have \"[gauss_int_norm a \\<noteq> 3] (mod 4)\"\n      by (rule gauss_int_norm_not_3_mod_4)\n    ultimately show ?thesis by contradiction\n  qed (use ij in \\<open>auto simp: is_unit_gauss_int_iff'\\<close>)\nqed\n\ntheorem prime_gauss_int_of_nat:\n  fixes n :: nat\n  assumes prime: \"prime n\" and \"[n = 3] (mod 4)\"\n  shows   \"prime (of_nat n :: gauss_int)\"\n  using prime_elem_gauss_int_of_nat[OF assms]\n  unfolding prime_def by simp\n\n\nsubsubsection \\<open>Non-inert primes\\<close>\n\ntext \\<open>\n  Any \\<open>\\<int>\\<close>-prime congruent 1 modulo 4 factors into two conjugate Gaussian primes.\n\\<close>\n\nlemma minimal_QuadRes_neg1:\n  assumes \"QuadRes n (-1)\" \"n > 1\" \"odd n\"\n  obtains x :: nat where \"x \\<le> (n - 1) div 2\" and \"[x ^ 2 + 1 = 0] (mod n)\"\nproof -\n  from \\<open>QuadRes n (-1)\\<close> obtain x where \"[x ^ 2 = (-1)] (mod (int n))\"\n    by (auto simp: QuadRes_def)\n  hence \"[x ^ 2 + 1 = -1 + 1] (mod (int n))\"\n    by (intro cong_add) auto\n  also have \"x ^ 2 + 1 = int (nat \\<bar>x\\<bar> ^ 2 + 1)\"\n    by simp\n  finally have \"[int (nat \\<bar>x\\<bar> ^ 2 + 1) = int 0] (mod (int n))\"\n    by simp\n  hence \"[nat \\<bar>x\\<bar> ^ 2 + 1 = 0] (mod n)\"\n    by (subst (asm) cong_int_iff)\n\n  define x' where\n    \"x' = (if nat \\<bar>x\\<bar> mod n \\<le> (n - 1) div 2 then nat \\<bar>x\\<bar> mod n else n - (nat \\<bar>x\\<bar> mod n))\"\n  have x'_quadres: \"[x' ^ 2 + 1 = 0] (mod n)\"\n  proof (cases \"nat \\<bar>x\\<bar> mod n \\<le> (n - 1) div 2\")\n    case True\n    hence \"[x' ^ 2 + 1 = (nat \\<bar>x\\<bar> mod n) ^ 2 + 1] (mod n)\"\n      by (simp add: x'_def)\n    also have \"[(nat \\<bar>x\\<bar> mod n) ^ 2 + 1 = nat \\<bar>x\\<bar> ^ 2 + 1] (mod n)\"\n      by (intro cong_add cong_pow) (auto simp: cong_def)\n    also have \"[nat \\<bar>x\\<bar> ^ 2 + 1 = 0] (mod n)\" by fact\n    finally show ?thesis .\n  next\n    case False\n    hence \"[int (x' ^ 2 + 1) = (int n - int (nat \\<bar>x\\<bar> mod n)) ^ 2 + 1] (mod int n)\"\n      using \\<open>n > 1\\<close> by (simp add: x'_def of_nat_diff add_ac)\n    also have \"[(int n - int (nat \\<bar>x\\<bar> mod n)) ^ 2 + 1 =\n                (0 - int (nat \\<bar>x\\<bar> mod n)) ^ 2 + 1] (mod int n)\"\n      by (intro cong_add cong_pow) (auto simp: cong_def)\n    also have \"[(0 - int (nat \\<bar>x\\<bar> mod n)) ^ 2 + 1 = int ((nat \\<bar>x\\<bar> mod n) ^ 2 + 1)] (mod (int n))\"\n      by (simp add: add_ac)\n    finally have \"[x' ^ 2 + 1 = (nat \\<bar>x\\<bar> mod n)\\<^sup>2 + 1] (mod n)\"\n      by (subst (asm) cong_int_iff)\n    also have \"[(nat \\<bar>x\\<bar> mod n)\\<^sup>2 + 1 = nat \\<bar>x\\<bar> ^ 2 + 1] (mod n)\"\n      by (intro cong_add cong_pow) (auto simp: cong_def)\n    also have \"[nat \\<bar>x\\<bar> ^ 2 + 1 = 0] (mod n)\" by fact\n    finally show ?thesis .\n  qed\n  moreover have x'_le: \"x' \\<le> (n - 1) div 2\"\n    using \\<open>odd n\\<close> by (auto elim!: oddE simp: x'_def)\n  ultimately show ?thesis by (intro that[of x'])\nqed\n\ntext \\<open>\n  Let \\<open>p\\<close> be some prime number that is congruent 1 modulo 4.\n\\<close>\nlocale noninert_gauss_int_prime =\n  fixes p :: nat\n  assumes prime_p: \"prime p\" and cong_1_p: \"[p = 1] (mod 4)\"\nbegin\n\nlemma p_gt_2: \"p > 2\" and odd_p: \"odd p\"\nproof -\n  from prime_p and cong_1_p have \"p > 1\" \"p \\<noteq> 2\"\n    by (auto simp: prime_gt_Suc_0_nat cong_def)\n  thus \"p > 2\" by auto\n  with prime_p show \"odd p\"\n    using primes_dvd_imp_eq two_is_prime_nat by blast\nqed\n\ntext \\<open>\n  -1 is a quadratic residue modulo \\<open>p\\<close>, so there exists some \\<open>x\\<close> such that\n  $x^2 + 1$ is divisible by \\<open>p\\<close>. Moreover, we can choose \\<open>x\\<close> such that it is positive and\n  no greater than $\\frac{1}{2}(p-1)$:\n\\<close>\nlemma minimal_QuadRes_neg1:\n  obtains x where \"x > 0\" \"x \\<le> (p - 1) div 2\" \"[x ^ 2 + 1 = 0] (mod p)\"\nproof -\n  have \"[Legendre (-1) (int p) = (- 1) ^ ((p - 1) div 2)] (mod (int p))\"\n    using prime_p p_gt_2 by (intro euler_criterion) auto\n  also have \"[p - 1 = 1 - 1] (mod 4)\"\n    using p_gt_2 by (intro cong_diff_nat cong_refl) (use cong_1_p in auto)\n  hence \"2 * 2 dvd p - 1\"\n    by (simp add: cong_0_iff)\n  hence \"even ((p - 1) div 2)\"\n    using dvd_mult_imp_div by blast\n  hence \"(-1) ^ ((p - 1) div 2) = (1 :: int)\"\n    by simp\n  finally have \"Legendre (-1) (int p) mod p = 1\"\n    using p_gt_2 by (auto simp: cong_def)\n  hence \"Legendre (-1) (int p) = 1\"\n    using p_gt_2 by (auto simp: Legendre_def cong_def zmod_minus1 split: if_splits)\n  hence \"QuadRes p (-1)\"\n    by (simp add: Legendre_def split: if_splits)\n  from minimal_QuadRes_neg1[OF this] p_gt_2 odd_p\n    obtain x where x: \"x \\<le> (p - 1) div 2\" \"[x ^ 2 + 1 = 0] (mod p)\" by auto\n  have \"x > 0\"\n    using x p_gt_2 by (auto intro!: Nat.gr0I simp: cong_def)\n  from x and this show ?thesis by (intro that[of x]) auto\nqed\n\ntext \\<open>\n  We can show from this that \\<open>p\\<close> is not prime as a Gaussian integer.\n\\<close>\nlemma not_prime: \"\\<not>prime_elem (of_nat p :: gauss_int)\"\nproof\n  assume prime: \"prime_elem (of_nat p :: gauss_int)\"\n  obtain x where x: \"x > 0\" \"x \\<le> (p - 1) div 2\" \"[x ^ 2 + 1 = 0] (mod p)\"\n    using  minimal_QuadRes_neg1 .\n\n  have \"of_nat p dvd (of_nat (x ^ 2 + 1) :: gauss_int)\"\n    using x by (intro of_nat_dvd_of_nat) (auto simp: cong_0_iff)\n  also have eq: \"of_nat (x ^ 2 + 1) = ((of_nat x + \\<i>\\<^sub>\\<int>) * (of_nat x - \\<i>\\<^sub>\\<int>) :: gauss_int)\"\n    using \\<open>x > 0\\<close> by (simp add: algebra_simps gauss_int_eq_iff power2_eq_square of_nat_diff)\n  finally have \"of_nat p dvd ((of_nat x + \\<i>\\<^sub>\\<int>) * (of_nat x - \\<i>\\<^sub>\\<int>) :: gauss_int)\" .\n\n  from prime and this\n    have \"of_nat p dvd (of_nat x + \\<i>\\<^sub>\\<int> :: gauss_int) \\<or> of_nat p dvd (of_nat x - \\<i>\\<^sub>\\<int> :: gauss_int)\"\n    by (rule prime_elem_dvd_multD)\n  hence dvd: \"of_nat p dvd (of_nat x + \\<i>\\<^sub>\\<int> :: gauss_int)\" \"of_nat p dvd (of_nat x - \\<i>\\<^sub>\\<int> :: gauss_int)\"\n    by (auto dest: of_nat_dvd_imp_dvd_gauss_cnj)\n\n  have \"of_nat (p ^ 2) = (of_nat p * of_nat p :: gauss_int)\"\n    by (simp add: power2_eq_square)\n  also from dvd have \"\\<dots> dvd ((of_nat x + \\<i>\\<^sub>\\<int>) * (of_nat x - \\<i>\\<^sub>\\<int>))\"\n    by (intro mult_dvd_mono)\n  also have \"\\<dots> = of_nat (x ^ 2 + 1)\"\n    by (rule eq [symmetric])\n  finally have \"p ^ 2 dvd (x ^ 2 + 1)\"\n    by (subst (asm) of_nat_dvd_of_nat_gauss_int_iff)\n  hence \"p ^ 2 \\<le> x ^ 2 + 1\"\n    by (intro dvd_imp_le) auto\n  moreover have \"p ^ 2 > x ^ 2 + 1\"\n  proof -\n    have \"x ^ 2 + 1 \\<le> ((p - 1) div 2) ^ 2 + 1\"\n      using x by (intro add_mono power_mono) auto\n    also have \"\\<dots> \\<le> (p - 1) ^ 2 + 1\"\n      by auto\n    also have \"(p - 1) * (p - 1) < (p - 1) * (p + 1)\"\n      using p_gt_2 by (intro mult_strict_left_mono) auto\n    hence \"(p - 1) ^ 2 + 1 < p ^ 2\"\n      by (simp add: algebra_simps power2_eq_square)\n    finally show ?thesis .\n  qed\n  ultimately show False by linarith\nqed\n\ntext \\<open>\n  Any prime factor of \\<open>p\\<close> in the Gaussian integers must have norm \\<open>p\\<close>.\n\\<close>\nlemma norm_prime_divisor:\n  fixes q :: gauss_int\n  assumes q: \"prime_elem q\" \"q dvd of_nat p\"\n  shows \"gauss_int_norm q = p\"\nproof -\n  from assms obtain r where r: \"of_nat p = q * r\"\n    by auto\n  have \"p ^ 2 = gauss_int_norm (of_nat p)\"\n    by simp\n  also have \"\\<dots> = gauss_int_norm q * gauss_int_norm r\"\n    by (auto simp: r gauss_int_norm_mult)\n  finally have *: \"gauss_int_norm q * gauss_int_norm r = p ^ 2\"\n    by simp\n  hence \"\\<exists>i j. gauss_int_norm q = p ^ i \\<and> gauss_int_norm r = p ^ j\"\n    using prime_p by (intro prime_power_mult_nat)\n  then obtain i j where ij: \"gauss_int_norm q = p ^ i\" \"gauss_int_norm r = p ^ j\"\n    by blast\n  have ij_eq_2: \"i + j = 2\"\n  proof -\n    from * have \"p ^ (i + j) = p ^ 2\"\n      by (simp add: power_add ij)\n    thus ?thesis\n      using p_gt_2 by (subst (asm) power_inject_exp) auto\n  qed\n  hence \"i = 0 \\<and> j = 2 \\<or> i = 1 \\<and> j = 1 \\<or> i = 2 \\<and> j = 0\" by auto\n  hence \"i = 1\"\n  proof (elim disjE)\n    assume \"i = 2 \\<and> j = 0\"\n    hence \"is_unit r\"\n      using ij by (simp add: gauss_int_norm_eq_Suc_0_iff)\n    hence \"prime_elem (of_nat p :: gauss_int)\" using \\<open>prime_elem q\\<close>\n      by (simp add: prime_elem_mult_unit_left r mult.commute[of _ r])\n    with not_prime show \"i = 1\" by contradiction\n  qed (use q ij in \\<open>auto simp: gauss_int_norm_eq_Suc_0_iff\\<close>)\n  thus ?thesis using ij by simp\nqed\n\ntext \\<open>\n  We now show two lemmas that characterise the two prime factors of \\<open>p\\<close> in the\n  Gaussian integers: they are two conjugates $x\\pm iy$ for positive integers \\<open>x\\<close> and \\<open>y\\<close> such\n  that $x^2 + y^2 = p$.\n\\<close>\nlemma prime_divisor_exists:\n  obtains q where \"prime q\" \"prime_elem (gauss_cnj q)\" \"ReZ q > 0\" \"ImZ q > 0\"\n                  \"of_nat p = q * gauss_cnj q\" \"gauss_int_norm q = p\"\nproof -\n  have \"\\<exists>q::gauss_int. q dvd of_nat p \\<and> prime q\"\n    by (rule prime_divisor_exists) (use prime_p in \\<open>auto simp: is_unit_gauss_int_iff'\\<close>)\n  then obtain q :: gauss_int where q: \"prime q\" \"q dvd of_nat p\"\n    by blast\n  from \\<open>prime q\\<close> have [simp]: \"q \\<noteq> 0\" by auto\n  have \"normalize q = q\"\n    using q by simp\n  hence q_signs: \"ReZ q > 0\" \"ImZ q \\<ge> 0\"\n    by (subst (asm) normalized_gauss_int_iff; simp)+\n  \n  from q have \"gauss_int_norm q = p\"\n    using norm_prime_divisor[of q] by simp\n  moreover from this have \"gauss_int_norm (gauss_cnj q) = p\"\n    by simp\n  hence \"prime_elem (gauss_cnj q)\"\n    using prime_p by (intro prime_gauss_int_norm_imp_prime_elem) auto\n  moreover have \"of_nat p = q * gauss_cnj q\"\n    using \\<open>gauss_int_norm q = p\\<close> by (simp add: self_mult_gauss_cnj)\n  moreover have \"ImZ q \\<noteq> 0\"\n  proof\n    assume [simp]: \"ImZ q = 0\"\n    define m where \"m = nat (ReZ q)\"\n    have [simp]: \"q = of_nat m\"\n      using q_signs by (auto simp: gauss_int_eq_iff m_def)\n    with q have \"m dvd p\"\n      by (simp add: of_nat_dvd_of_nat_gauss_int_iff)\n    with prime_p have \"m = 1 \\<or> m = p\"\n      using prime_nat_iff by blast\n    with q show False using not_prime by auto\n  qed\n  with q_signs have \"ImZ q > 0\" by simp\n  ultimately show ?thesis using q q_signs by (intro that[of q])\nqed\n\ntheorem prime_factorization:\n  obtains q1 q2\n  where \"prime q1\" \"prime q2\" \"prime_factorization (of_nat p) = {#q1, q2#}\" \n        \"gauss_int_norm q1 = p\" \"gauss_int_norm q2 = p\" \"q2 = \\<i>\\<^sub>\\<int> * gauss_cnj q1\"\n        \"ReZ q1 > 0\" \"ImZ q1 > 0\" \"ReZ q1 > 0\" \"ImZ q2 > 0\"\nproof -\n  obtain q where q: \"prime q\" \"prime_elem (gauss_cnj q)\" \"ReZ q > 0\" \"ImZ q > 0\"\n                    \"of_nat p = q * gauss_cnj q\" \"gauss_int_norm q = p\"\n    using prime_divisor_exists by metis\n  from \\<open>prime q\\<close> have [simp]: \"q \\<noteq> 0\" by auto\n  define q' where \"q' = normalize (gauss_cnj q)\"\n  have \"prime_factorization (of_nat p) = prime_factorization (prod_mset {#q, q'#})\"\n    by (subst prime_factorization_unique) (auto simp: q q'_def)\n  also have \"\\<dots> = {#q, q'#}\"\n    using q by (subst prime_factorization_prod_mset_primes) (auto simp: q'_def)\n  finally have \"prime_factorization (of_nat p) = {#q, q'#}\" .\n  moreover have \"q' = \\<i>\\<^sub>\\<int> * gauss_cnj q\"\n    using q by (auto simp: normalize_gauss_int_def q'_def)\n  moreover have \"prime q'\"\n    using q by (auto simp: q'_def)\n  ultimately show ?thesis using q\n    by (intro that[of q q']) (auto simp: q'_def gauss_int_norm_mult)\nqed\n\nend\n\ntext \\<open>\n  In particular, a consequence of this is that any prime congruent 1 modulo 4\n  can be written as a sum of squares of positive integers.\n\\<close>\nlemma prime_cong_1_mod_4_gauss_int_norm_exists:\n  fixes p :: nat\n  assumes \"prime p\" \"[p = 1] (mod 4)\"\n  shows   \"\\<exists>z. gauss_int_norm z = p \\<and> ReZ z > 0 \\<and> ImZ z > 0\"\nproof -\n  from assms interpret noninert_gauss_int_prime p\n    by unfold_locales\n  from prime_divisor_exists obtain q\n    where q: \"prime q\" \"of_nat p = q * gauss_cnj q\" \n             \"ReZ q > 0\" \"ImZ q > 0\" \"gauss_int_norm q = p\" by metis\n  have \"p = gauss_int_norm q\"\n    using q by simp\n  thus ?thesis using q by blast\nqed\n\n\nsubsubsection \\<open>Full classification of Gaussian primes\\<close>\n\ntext \\<open>\n  Any prime in the ring of Gaussian integers is of the form\n\n    \\<^item> \\<open>1 + \\<i>\\<^sub>\\<int>\\<close>\n\n    \\<^item> \\<open>p\\<close> where \\<open>p \\<in> \\<nat>\\<close> is prime in \\<open>\\<nat>\\<close> and congruent 1 modulo 4\n\n    \\<^item> $x + iy$ where $x,y$ are positive integers and $x^2 + y^2$ is a prime congruent 3 modulo 4\n\n  or an associated element of one of these.  \n\\<close>\ntheorem gauss_int_prime_classification:\n  fixes x :: gauss_int\n  assumes \"prime x\"\n  obtains \n    (one_plus_i) \"x = 1 + \\<i>\\<^sub>\\<int>\"\n  | (cong_3_mod_4) p where \"x = of_nat p\" \"prime p\" \"[p = 3] (mod 4)\"\n  | (cong_1_mod_4) \"prime (gauss_int_norm x)\" \"[gauss_int_norm x = 1] (mod 4)\"\n                   \"ReZ x > 0\" \"ImZ x > 0\" \"ReZ x \\<noteq> ImZ x\"\nproof -\n  define N where \"N = gauss_int_norm x\"\n  have \"x dvd x * gauss_cnj x\"\n    by simp\n  also have \"\\<dots> = of_nat (gauss_int_norm x)\"\n    by (simp add: self_mult_gauss_cnj)\n  finally have \"x \\<in> prime_factors (of_nat N)\"\n    using assms by (auto simp: in_prime_factors_iff N_def)\n  also have \"N = prod_mset (prime_factorization N)\"\n    using assms unfolding N_def by (subst prod_mset_prime_factorization_nat) auto\n  also have \"(of_nat \\<dots> :: gauss_int) = \n               prod_mset (image_mset of_nat (prime_factorization N))\"\n    by (subst of_nat_prod_mset) auto\n  also have \"prime_factors \\<dots> = (\\<Union>p\\<in>prime_factors N. prime_factors (of_nat p))\"\n    by (subst prime_factorization_prod_mset) auto\n  finally obtain p where p: \"p \\<in> prime_factors N\" \"x \\<in> prime_factors (of_nat p)\"\n    by auto\n\n  have \"prime p\"\n    using p by auto\n  hence \"\\<not>(2 * 2) dvd p\"\n    using product_dvd_irreducibleD[of p 2 2]\n    by (auto simp flip: prime_elem_iff_irreducible)\n  hence \"[p \\<noteq> 0] (mod 4)\"\n    using p by (auto simp: cong_0_iff in_prime_factors_iff)\n  hence \"p mod 4 \\<in> {1,2,3}\" by (auto simp: cong_def)\n  thus ?thesis\n  proof (elim singletonE insertE)\n    assume \"p mod 4 = 2\"\n    hence \"p mod 4 mod 2 = 0\"\n      by simp\n    hence \"p mod 2 = 0\"\n      by (simp add: mod_mod_cancel)\n    with \\<open>prime p\\<close> have [simp]: \"p = 2\"\n      using prime_prime_factor two_is_prime_nat by blast\n    have \"prime_factors (of_nat p) = {1 + \\<i>\\<^sub>\\<int> :: gauss_int}\"\n      by (simp add: prime_factorization_2_gauss_int)\n    with p show ?thesis using that(1) by auto\n  next\n    assume *: \"p mod 4 = 3\"\n    hence \"prime_factors (of_nat p) = {of_nat p :: gauss_int}\"\n      using prime_gauss_int_of_nat[of p] \\<open>prime p\\<close>\n      by (subst prime_factorization_prime) (auto simp: cong_def)\n    with p show ?thesis using that(2)[of p] *\n      by (auto simp: cong_def)\n  next\n    assume *: \"p mod 4 = 1\"\n    then interpret noninert_gauss_int_prime p\n      by unfold_locales (use \\<open>prime p\\<close> in \\<open>auto simp: cong_def\\<close>)\n    obtain q1 q2 :: gauss_int where q12:\n      \"prime q1\" \"prime q2\" \"prime_factorization (of_nat p) = {#q1, q2#}\"\n      \"gauss_int_norm q1 = p\" \"gauss_int_norm q2 = p\" \"q2 = \\<i>\\<^sub>\\<int> * gauss_cnj q1\"\n      \"ReZ q1 > 0\" \"ImZ q1 > 0\" \"ReZ q1 > 0\" \"ImZ q2 > 0\"\n      using prime_factorization by metis\n    from p q12 have \"x = q1 \\<or> x = q2\" by auto\n    with q12 have **: \"gauss_int_norm x = p\" \"ReZ x > 0\" \"ImZ x > 0\"\n      by auto\n    have \"ReZ x \\<noteq> ImZ x\"\n    proof\n      assume \"ReZ x = ImZ x\"\n      hence \"even (gauss_int_norm x)\"\n        by (auto simp: gauss_int_norm_def nat_mult_distrib)\n      hence \"even p\" using \\<open>gauss_int_norm x = p\\<close>\n        by simp\n      with \\<open>p mod 4 = 1\\<close> show False\n        by presburger\n    qed\n    thus ?thesis using that(3) \\<open>prime p\\<close> * **\n      by (simp add: cong_def)\n  qed\nqed\n\nlemma prime_gauss_int_norm_squareD:\n  fixes z :: gauss_int\n  assumes \"prime z\" \"gauss_int_norm z = p ^ 2\"\n  shows   \"prime p \\<and> z = of_nat p\"\n  using assms(1)\nproof (cases rule: gauss_int_prime_classification)\n  case one_plus_i\n  have \"prime (2 :: nat)\" by simp\n  also from one_plus_i have \"2 = p ^ 2\"\n    using assms(2) by (auto simp: gauss_int_norm_def)\n  finally show ?thesis by (simp add: prime_power_iff)\nnext\n  case (cong_3_mod_4 p)\n  thus ?thesis using assms by auto\nnext\n  case cong_1_mod_4\n  with assms show ?thesis\n    by (auto simp: prime_power_iff)\nqed\n\nlemma gauss_int_norm_eq_prime_squareD:\n  assumes \"prime p\" and \"[p = 3] (mod 4)\" and \"gauss_int_norm z = p ^ 2\"\n  shows   \"normalize z = of_nat p\" and \"prime_elem z\"\nproof -\n  have \"\\<exists>q::gauss_int. q dvd z \\<and> prime q\"\n    by (rule prime_divisor_exists) (use assms in \\<open>auto simp: is_unit_gauss_int_iff'\\<close>)\n  then obtain q :: gauss_int where q: \"q dvd z\" \"prime q\" by blast\n  have \"gauss_int_norm q dvd gauss_int_norm z\"\n    by (rule gauss_int_norm_dvd_mono) fact\n  also have \"\\<dots> = p ^ 2\" by fact\n  finally obtain i where i: \"i \\<le> 2\" \"gauss_int_norm q = p ^ i\"\n    by (subst (asm) divides_primepow_nat) (use assms q in auto)\n  from i assms q have \"i \\<noteq> 0\"\n    by (auto intro!: Nat.gr0I simp: gauss_int_norm_eq_Suc_0_iff)\n  moreover from i assms q have \"i \\<noteq> 1\"\n    using gauss_int_norm_not_3_mod_4[of q] by auto\n  ultimately have \"i = 2\" using i by auto\n  with i have \"gauss_int_norm q = p ^ 2\" by auto\n  hence [simp]: \"q = of_nat p\"\n    using prime_gauss_int_norm_squareD[of q p] q by auto\n  have \"normalize (of_nat p) = normalize z\"\n    using q assms\n    by (intro gauss_int_dvd_same_norm_imp_associated) auto\n  thus *: \"normalize z = of_nat p\" by simp\n\n  have \"prime (normalize z)\"\n    using prime_gauss_int_of_nat[of p] assms by (subst *) auto\n  thus \"prime_elem z\" by simp\nqed\n\ntext \\<open>\n  The following can be used as a primality test for Gaussian integers. It effectively\n  reduces checking the primality of a Gaussian integer to checking the primality of an\n  integer.\n\n  A Gaussian integer is prime if either its norm is either \\<open>\\<int>\\<close>-prime or the square of\n  a \\<open>\\<int>\\<close>-prime that is congruent 3 modulo 4.\n\\<close>\nlemma prime_elem_gauss_int_iff:\n  fixes z :: gauss_int\n  defines \"n \\<equiv> gauss_int_norm z\"\n  shows   \"prime_elem z \\<longleftrightarrow> prime n \\<or> (\\<exists>p. n = p ^ 2 \\<and> prime p \\<and> [p = 3] (mod 4))\"\nproof\n  assume \"prime n \\<or> (\\<exists>p. n = p ^ 2 \\<and> prime p \\<and> [p = 3] (mod 4))\"\n  thus \"prime_elem z\"\n    by (auto intro: gauss_int_norm_eq_prime_squareD(2)\n                    prime_gauss_int_norm_imp_prime_elem simp: n_def)\nnext\n  assume \"prime_elem z\"\n  hence \"prime (normalize z)\" by simp\n  thus \"prime n \\<or> (\\<exists>p. n = p ^ 2 \\<and> prime p \\<and> [p = 3] (mod 4))\"\n  proof (cases rule: gauss_int_prime_classification)\n    case one_plus_i\n    have \"n = gauss_int_norm (normalize z)\"\n      by (simp add: n_def)\n    also have \"normalize z = 1 + \\<i>\\<^sub>\\<int>\"\n      by fact\n    also have \"gauss_int_norm \\<dots> = 2\"\n      by (simp add: gauss_int_norm_def)\n    finally show ?thesis by simp\n  next\n    case (cong_3_mod_4 p)\n    have \"n = gauss_int_norm (normalize z)\"\n      by (simp add: n_def)\n    also have \"normalize z = of_nat p\"\n      by fact\n    also have \"gauss_int_norm \\<dots> = p ^ 2\"\n      by simp\n    finally show ?thesis using cong_3_mod_4 by simp\n  next\n    case cong_1_mod_4\n    thus ?thesis by (simp add: n_def)\n  qed\nqed\n\n\nsubsubsection \\<open>Multiplicities of primes\\<close>\n\ntext \\<open>\n  In this section, we will show some results connecting the multiplicity of a Gaussian prime \\<open>p\\<close>\n  in a Gaussian integer \\<open>z\\<close> to the \\<open>\\<int>\\<close>-multiplicity of the norm of \\<open>p\\<close> in the norm of \\<open>z\\<close>.\n\\<close>\n\ntext \\<open>\n  The multiplicity of the Gaussian prime \\<^term>\\<open>1 + \\<i>\\<^sub>\\<int>\\<close> in an integer \\<open>c\\<close> is simply\n  twice the \\<open>\\<int>\\<close>-multiplicity of 2 in \\<open>c\\<close>:\n\\<close>\nlemma multiplicity_prime_1_plus_i_aux: \"multiplicity (1 + \\<i>\\<^sub>\\<int>) (of_nat c) = 2 * multiplicity 2 c\"\nproof (cases \"c = 0\")\n  case [simp]: False\n  have \"2 * multiplicity 2 c = multiplicity 2 (c ^ 2)\"\n    by (simp add: prime_elem_multiplicity_power_distrib)\n  also have \"multiplicity 2 (c ^ 2) = multiplicity (of_nat 2) (of_nat c ^ 2 :: gauss_int)\"\n    by (simp flip: multiplicity_gauss_int_of_nat)\n  also have \"of_nat 2 = (-\\<i>\\<^sub>\\<int>) * (1 + \\<i>\\<^sub>\\<int>) ^ 2\"\n    by (simp add: algebra_simps power2_eq_square)\n  also have \"multiplicity \\<dots> (of_nat c ^ 2) = multiplicity ((1 + \\<i>\\<^sub>\\<int>) ^ 2) (of_nat c ^ 2)\"\n    by (subst multiplicity_times_unit_left) auto\n  also have \"\\<dots> = multiplicity (1 + \\<i>\\<^sub>\\<int>) (of_nat c)\"\n    by (subst multiplicity_power_power) auto\n  finally show ?thesis ..\nqed auto\n\ntext \\<open>\n  Tha multiplicity of an inert Gaussian prime $q\\in\\mathbb{Z}$ in a Gaussian integer \\<open>z\\<close> is \n  precisely half the \\<open>\\<int>\\<close>-multiplicity of \\<open>q\\<close> in the norm of \\<open>z\\<close>.\n\\<close>\nlemma multiplicity_prime_cong_3_mod_4:\n  assumes \"prime (of_nat q :: gauss_int)\"\n  shows   \"multiplicity q (gauss_int_norm z) = 2 * multiplicity (of_nat q) z\"\nproof (cases \"z = 0\")\n  case [simp]: False\n  have \"multiplicity q (gauss_int_norm z) =\n          multiplicity (of_nat q) (of_nat (gauss_int_norm z) :: gauss_int)\"\n    by (simp add: multiplicity_gauss_int_of_nat)\n  also have \"\\<dots> = multiplicity (of_nat q) (z * gauss_cnj z)\"\n    by (simp add: self_mult_gauss_cnj)\n  also have \"\\<dots> = multiplicity (of_nat q) z + multiplicity (gauss_cnj (of_nat q)) (gauss_cnj z)\"\n    using assms by (subst prime_elem_multiplicity_mult_distrib) auto\n  also have \"multiplicity (gauss_cnj (of_nat q)) (gauss_cnj z) = multiplicity (of_nat q) z\"\n    by (subst multiplicity_gauss_cnj) auto\n  also have \"\\<dots> + \\<dots> = 2 * \\<dots>\"\n    by simp\n  finally show ?thesis .\nqed auto\n\ntext \\<open>\n  For Gaussian primes \\<open>p\\<close> whose norm is congruent 1 modulo 4, the $\\mathbb{Z}[i]$-multiplicity\n  of \\<open>p\\<close> in an integer \\<open>c\\<close> is just the \\<open>\\<int>\\<close>-multiplicity of their norm in \\<open>c\\<close>.\n\\<close>\nlemma multiplicity_prime_cong_1_mod_4_aux:\n  fixes p :: gauss_int\n  assumes \"prime_elem p\" \"ReZ p > 0\" \"ImZ p > 0\" \"ImZ p \\<noteq> ReZ p\"\n  shows \"multiplicity p (of_nat c) = multiplicity (gauss_int_norm p) c\"\nproof (cases \"c = 0\")\n  case [simp]: False\n  show ?thesis\n  proof (intro antisym multiplicity_geI)\n    define k where \"k = multiplicity p (of_nat c)\"\n    have \"p ^ k dvd of_nat c\"\n      by (simp add: multiplicity_dvd k_def)\n    moreover have \"gauss_cnj p ^ k dvd of_nat c\"\n      using multiplicity_dvd[of \"gauss_cnj p\" \"of_nat c\"]\n            multiplicity_gauss_cnj[of p \"of_nat c\"] by (simp add: k_def)\n    moreover have \"\\<not>p dvd gauss_cnj p\"\n      using assms by (subst self_dvd_gauss_cnj_iff) auto\n    hence \"\\<not>p dvd gauss_cnj p ^ k\"\n      using assms prime_elem_dvd_power by blast\n    ultimately have \"p ^ k * gauss_cnj p ^ k dvd of_nat c\"\n      using assms by (intro prime_elem_power_mult_dvdI) auto\n    also have \"p ^ k * gauss_cnj p ^ k = of_nat (gauss_int_norm p ^ k)\"\n      by (simp flip: self_mult_gauss_cnj add: power_mult_distrib)\n    finally show \"gauss_int_norm p ^ k dvd c\"\n      by (subst (asm) of_nat_dvd_of_nat_gauss_int_iff)\n  next\n    define k where \"k = multiplicity (gauss_int_norm p) c\"\n    have \"p ^ k dvd (p * gauss_cnj p) ^ k\"\n      by (intro dvd_power_same) auto\n    also have \"\\<dots> = of_nat (gauss_int_norm p ^ k)\"\n      by (simp add: self_mult_gauss_cnj)\n    also have \"\\<dots> dvd of_nat c\"\n      unfolding of_nat_dvd_of_nat_gauss_int_iff by (auto simp: k_def multiplicity_dvd)\n    finally show \"p ^ k dvd of_nat c\" .\n  qed (use assms in \\<open>auto simp: gauss_int_norm_eq_Suc_0_iff\\<close>)\nqed auto\n\ntext \\<open>\n  The multiplicity of a Gaussian prime with norm congruent 1 modulo 4 in some Gaussian integer \\<open>z\\<close>\n  and the multiplicity of its conjugate in \\<open>z\\<close> sum to the the \\<open>\\<int>\\<close>-multiplicity of their norm in\n  the norm of \\<open>z\\<close>:\n\\<close>\nlemma multiplicity_prime_cong_1_mod_4:\n  fixes p :: gauss_int\n  assumes \"prime_elem p\" \"ReZ p > 0\" \"ImZ p > 0\" \"ImZ p \\<noteq> ReZ p\"\n  shows \"multiplicity (gauss_int_norm p) (gauss_int_norm z) =\n           multiplicity p z + multiplicity (gauss_cnj p) z\"\nproof (cases \"z = 0\")\n  case [simp]: False\n  have \"multiplicity (gauss_int_norm p) (gauss_int_norm z) = \n          multiplicity p (of_nat (gauss_int_norm z))\"\n    using assms by (subst multiplicity_prime_cong_1_mod_4_aux) auto\n  also have \"\\<dots> = multiplicity p (z * gauss_cnj z)\"\n    by (simp add: self_mult_gauss_cnj)\n  also have \"\\<dots> = multiplicity p z + multiplicity p (gauss_cnj z)\"\n    using assms by (subst prime_elem_multiplicity_mult_distrib) auto\n  also have \"multiplicity p (gauss_cnj z) = multiplicity (gauss_cnj p) z\"\n    by (subst multiplicity_gauss_cnj [symmetric]) auto\n  finally show ?thesis .\nqed auto\n\ntext \\<open>\n  The multiplicity of the Gaussian prime \\<^term>\\<open>1 + \\<i>\\<^sub>\\<int>\\<close> in a Gaussian integer \\<open>z\\<close> is precisely\n  the \\<open>\\<int>\\<close>-multiplicity of 2 in the norm of \\<open>z\\<close>:\n\\<close>\nlemma multiplicity_prime_1_plus_i: \"multiplicity (1 + \\<i>\\<^sub>\\<int>) z = multiplicity 2 (gauss_int_norm z)\"\nproof (cases \"z = 0\")\n  case [simp]: False\n  note [simp] = prime_elem_one_plus_i_gauss_int\n  have \"2 * multiplicity 2 (gauss_int_norm z) = multiplicity (1 + \\<i>\\<^sub>\\<int>) (of_nat (gauss_int_norm z))\" \n    by (rule multiplicity_prime_1_plus_i_aux [symmetric])\n  also have \"\\<dots> = multiplicity (1 + \\<i>\\<^sub>\\<int>) (z * gauss_cnj z)\"\n    by (simp add: self_mult_gauss_cnj)\n  also have \"\\<dots> = multiplicity (1 + \\<i>\\<^sub>\\<int>) z + multiplicity (gauss_cnj (1 - \\<i>\\<^sub>\\<int>)) (gauss_cnj z)\"\n    by (subst prime_elem_multiplicity_mult_distrib) auto\n  also have \"multiplicity (gauss_cnj (1 - \\<i>\\<^sub>\\<int>)) (gauss_cnj z) = multiplicity (1 - \\<i>\\<^sub>\\<int>) z\"\n    by (subst multiplicity_gauss_cnj) auto\n  also have \"1 - \\<i>\\<^sub>\\<int> = (-\\<i>\\<^sub>\\<int>) * (1 + \\<i>\\<^sub>\\<int>)\"\n    by (simp add: algebra_simps)\n  also have \"multiplicity \\<dots> z = multiplicity (1 + \\<i>\\<^sub>\\<int>) z\"\n    by (subst multiplicity_times_unit_left) auto\n  also have \"\\<dots> + \\<dots> = 2 * \\<dots>\"\n    by simp\n  finally show ?thesis by simp\nqed auto\n\n\nsubsection \\<open>Coprimality of an element and its conjugate\\<close>\n\ntext \\<open>\n  Using the classification of the primes, we now show that if the real and imaginary parts of a\n  Gaussian integer are coprime and its norm is odd, then it is coprime to its own conjugate.\n\\<close>\nlemma coprime_self_gauss_cnj:\n  assumes \"coprime (ReZ z) (ImZ z)\" and \"odd (gauss_int_norm z)\"\n  shows   \"coprime z (gauss_cnj z)\"\nproof (rule coprimeI)\n  fix d assume \"d dvd z\" \"d dvd gauss_cnj z\"\n  have *: False if \"p \\<in> prime_factors z\" \"p \\<in> prime_factors (gauss_cnj z)\" for p\n  proof -\n    from that have p: \"prime p\" \"p dvd z\" \"p dvd gauss_cnj z\"\n      by auto\n\n    define p' where \"p' = gauss_cnj p\"\n    define d where \"d = gauss_int_norm p\"\n    have of_nat_d_eq: \"of_nat d = p * p'\"\n      by (simp add: p'_def self_mult_gauss_cnj d_def)\n    have \"prime_elem p\" \"prime_elem p'\" \"p dvd z\" \"p' dvd z\" \"p dvd gauss_cnj z\" \"p' dvd gauss_cnj z\"\n      using that by (auto simp: in_prime_factors_iff p'_def gauss_cnj_dvd_left_iff)\n\n    have \"prime p\"\n      using that by auto\n    then obtain q where q: \"prime q\" \"of_nat q dvd z\"\n    proof (cases rule: gauss_int_prime_classification)\n      case one_plus_i\n      hence \"2 = gauss_int_norm p\"\n        by (auto simp: gauss_int_norm_def)\n      also have \"gauss_int_norm p dvd gauss_int_norm z\"\n        using p by (intro gauss_int_norm_dvd_mono) auto\n      finally have \"even (gauss_int_norm z)\" .\n      with \\<open>odd (gauss_int_norm z)\\<close> show ?thesis\n        by contradiction\n    next\n      case (cong_3_mod_4 q)\n      thus ?thesis using that[of q] p by simp\n    next\n      case cong_1_mod_4\n      hence \"\\<not>p dvd p'\"\n        unfolding p'_def by (subst self_dvd_gauss_cnj_iff) auto\n      hence \"p * p' dvd z\" using p\n        by (intro prime_elem_mult_dvdI) (auto simp: p'_def gauss_cnj_dvd_left_iff)\n      also have \"p * p' = of_nat (gauss_int_norm p)\"\n        by (simp add: p'_def self_mult_gauss_cnj)\n      finally show ?thesis using that[of \"gauss_int_norm p\"] cong_1_mod_4\n        by simp\n    qed\n\n    have \"of_nat q dvd gcd (2 * of_int (ReZ z)) (2 * \\<i>\\<^sub>\\<int> * of_int (ImZ z))\"\n    proof (rule gcd_greatest)\n      have \"of_nat q dvd (z + gauss_cnj z)\"\n        using q by (auto simp: gauss_cnj_dvd_right_iff)\n      also have \"\\<dots> = 2 * of_int (ReZ z)\"\n        by (simp add: self_plus_gauss_cnj)\n      finally show \"of_nat q dvd (2 * of_int (ReZ z) :: gauss_int)\" .\n    next\n      have \"of_nat q dvd (z - gauss_cnj z)\"\n        using q by (auto simp: gauss_cnj_dvd_right_iff)\n      also have \"\\<dots> = 2 * \\<i>\\<^sub>\\<int> * of_int (ImZ z)\"\n        by (simp add: self_minus_gauss_cnj)\n      finally show \"of_nat q dvd (2 * \\<i>\\<^sub>\\<int> * of_int (ImZ z))\" .\n    qed\n    also have \"\\<dots> = 2\"\n    proof -\n      have \"odd (ReZ z) \\<or> odd (ImZ z)\"\n        using assms by (auto simp: gauss_int_norm_def even_nat_iff)\n      thus ?thesis\n      proof\n        assume \"odd (ReZ z)\"\n        hence \"coprime (of_int (ReZ z)) (of_int 2 :: gauss_int)\"\n          unfolding coprime_of_int_gauss_int coprime_right_2_iff_odd .\n        thus ?thesis\n          using assms\n          by (subst gcd_mult_left_right_cancel)\n             (auto simp: coprime_of_int_gauss_int coprime_commute is_unit_left_imp_coprime\n                         is_unit_right_imp_coprime gcd_proj1_if_dvd gcd_proj2_if_dvd)\n      next\n        assume \"odd (ImZ z)\"\n        hence \"coprime (of_int (ImZ z)) (of_int 2 :: gauss_int)\"\n          unfolding coprime_of_int_gauss_int coprime_right_2_iff_odd .\n        hence \"gcd (2 * of_int (ReZ z)) (2 * \\<i>\\<^sub>\\<int> * of_int (ImZ z)) = gcd (2 * of_int (ReZ z)) (2 * \\<i>\\<^sub>\\<int>)\"\n          using assms\n          by (subst gcd_mult_right_right_cancel)\n             (auto simp: coprime_of_int_gauss_int coprime_commute is_unit_left_imp_coprime\n                         is_unit_right_imp_coprime)\n        also have \"\\<dots> = normalize (2 * gcd (of_int (ReZ z)) \\<i>\\<^sub>\\<int>)\"\n          by (subst gcd_mult_left) auto\n        also have \"gcd (of_int (ReZ z)) \\<i>\\<^sub>\\<int> = 1\"\n          by (subst coprime_iff_gcd_eq_1 [symmetric], rule is_unit_right_imp_coprime) auto\n        finally show ?thesis by simp\n      qed\n    qed\n    finally have \"of_nat q dvd (of_nat 2 :: gauss_int)\"\n      by simp\n    hence \"q dvd 2\"\n      by (simp only: of_nat_dvd_of_nat_gauss_int_iff)\n    with \\<open>prime q\\<close> have \"q = 2\"\n      using primes_dvd_imp_eq two_is_prime_nat by blast\n    with q have \"2 dvd z\"\n      by auto\n\n    have \"2 dvd gauss_int_norm 2\"\n      by simp\n    also have \"\\<dots> dvd gauss_int_norm z\"\n      using \\<open>2 dvd z\\<close> by (intro gauss_int_norm_dvd_mono)\n    finally show False using \\<open>odd (gauss_int_norm z)\\<close> by contradiction\n  qed\n\n  fix d :: gauss_int\n  assume d: \"d dvd z\" \"d dvd gauss_cnj z\"\n  show \"is_unit d\"\n  proof (rule ccontr)\n    assume \"\\<not>is_unit d\"\n    moreover from d assms have \"d \\<noteq> 0\"\n      by auto\n    ultimately obtain p where p: \"prime p\" \"p dvd d\"\n      using prime_divisorE by blast\n    with d have \"p \\<in> prime_factors z\" \"p \\<in> prime_factors (gauss_cnj z)\"\n      using assms by (auto simp: in_prime_factors_iff)\n    with *[of p] show False by blast\n  qed\nqed\n\n\nsubsection \\<open>Square decompositions of prime numbers congruent 1 mod 4\\<close>\n\nlemma prime_1_mod_4_sum_of_squares_unique_aux:\n  fixes p x y :: nat\n  assumes \"prime p\" \"[p = 1] (mod 4)\" \"x ^ 2 + y ^ 2 = p\"\n  shows   \"x > 0 \\<and> y > 0 \\<and> x \\<noteq> y\"\nproof safe\n  from assms show \"x > 0\" \"y > 0\"\n    by (auto intro!: Nat.gr0I simp: prime_power_iff)\nnext\n  assume \"x = y\"\n  with assms have \"p = 2 * x ^ 2\"\n    by simp\n  with \\<open>prime p\\<close> have \"p = 2\"\n    by (auto dest: prime_product)\n  with \\<open>[p = 1] (mod 4)\\<close> show False\n    by (simp add: cong_def)\nqed\n\ntext \\<open>\n  Any prime number congruent 1 modulo 4 can be written \\<^emph>\\<open>uniquely\\<close> as a sum of two squares\n  $x^2 + y^2$ (up to commutativity of the addition). Additionally, we have shown above that\n  \\<open>x\\<close> and \\<open>y\\<close> are both positive and \\<open>x \\<noteq> y\\<close>.\n\\<close>\nlemma prime_1_mod_4_sum_of_squares_unique:\n  fixes p :: nat\n  assumes \"prime p\" \"[p = 1] (mod 4)\"\n  shows   \"\\<exists>!(x,y). x \\<le> y \\<and> x ^ 2 + y ^ 2 = p\"\nproof (rule ex_ex1I)\n  obtain z where z: \"gauss_int_norm z = p\"\n    using prime_cong_1_mod_4_gauss_int_norm_exists[OF assms] by blast\n  show \"\\<exists>z. case z of (x,y) \\<Rightarrow> x \\<le> y \\<and> x ^ 2 + y ^ 2 = p\"\n  proof (cases \"\\<bar>ReZ z\\<bar> \\<le> \\<bar>ImZ z\\<bar>\")\n    case True\n    with z show ?thesis by\n      (intro exI[of _ \"(nat \\<bar>ReZ z\\<bar>, nat \\<bar>ImZ z\\<bar>)\"])\n      (auto simp: gauss_int_norm_def nat_add_distrib simp flip: nat_power_eq)\n  next\n    case False\n    with z show ?thesis by\n      (intro exI[of _ \"(nat \\<bar>ImZ z\\<bar>, nat \\<bar>ReZ z\\<bar>)\"])\n      (auto simp: gauss_int_norm_def nat_add_distrib simp flip: nat_power_eq)\n  qed\nnext\n  fix z1 z2\n  assume z1: \"case z1 of (x, y) \\<Rightarrow> x \\<le> y \\<and> x\\<^sup>2 + y\\<^sup>2 = p\"\n  assume z2: \"case z2 of (x, y) \\<Rightarrow> x \\<le> y \\<and> x\\<^sup>2 + y\\<^sup>2 = p\"\n  define z1' :: gauss_int where \"z1' = of_nat (fst z1) + \\<i>\\<^sub>\\<int> * of_nat (snd z1)\"\n  define z2' :: gauss_int where \"z2' = of_nat (fst z2) + \\<i>\\<^sub>\\<int> * of_nat (snd z2)\"\n  from assms interpret noninert_gauss_int_prime p\n    by unfold_locales auto\n  have norm_z1': \"gauss_int_norm z1' = p\"\n    using z1 by (simp add: z1'_def gauss_int_norm_def case_prod_unfold nat_add_distrib nat_power_eq)\n  have norm_z2': \"gauss_int_norm z2' = p\"\n    using z2 by (simp add: z2'_def gauss_int_norm_def case_prod_unfold nat_add_distrib nat_power_eq)\n\n  have sgns: \"fst z1 > 0\" \"snd z1 > 0\" \"fst z2 > 0\" \"snd z2 > 0\" \"fst z1 \\<noteq> snd z1\" \"fst z2 \\<noteq> snd z2\"\n    using prime_1_mod_4_sum_of_squares_unique_aux[OF assms, of \"fst z1\" \"snd z1\"] z1\n          prime_1_mod_4_sum_of_squares_unique_aux[OF assms, of \"fst z2\" \"snd z2\"] z2 by auto\n  have [simp]: \"normalize z1' = z1'\" \"normalize z2' = z2'\"\n    using sgns by (subst normalized_gauss_int_iff; simp add: z1'_def z2'_def)+\n  have \"prime z1'\" \"prime z2'\"\n    using norm_z1' norm_z2' assms unfolding prime_def\n    by (auto simp: prime_gauss_int_norm_imp_prime_elem)\n\n  have \"of_nat p = z1' * gauss_cnj z1'\"\n    by (simp add: self_mult_gauss_cnj norm_z1')\n  hence \"z1' dvd of_nat p\"\n    by simp\n  also have \"of_nat p = z2' * gauss_cnj z2'\"\n    by (simp add: self_mult_gauss_cnj norm_z2')\n  finally have \"z1' dvd z2' \\<or> z1' dvd gauss_cnj z2'\" using assms\n    by (subst (asm) prime_elem_dvd_mult_iff)\n       (simp add: norm_z1' prime_gauss_int_norm_imp_prime_elem)\n  thus \"z1 = z2\"\n  proof\n    assume \"z1' dvd z2'\"\n    with \\<open>prime z1'\\<close> \\<open>prime z2'\\<close> have \"z1' = z2'\"\n      by (simp add: primes_dvd_imp_eq)\n    thus ?thesis\n      by (simp add: z1'_def z2'_def gauss_int_eq_iff prod_eq_iff)\n  next\n    assume dvd: \"z1' dvd gauss_cnj z2'\"\n    have \"normalize (\\<i>\\<^sub>\\<int> * gauss_cnj z2') = \\<i>\\<^sub>\\<int> * gauss_cnj z2'\"\n      using sgns by (subst normalized_gauss_int_iff) (auto simp: z2'_def)\n    moreover have \"prime_elem (\\<i>\\<^sub>\\<int> * gauss_cnj z2')\"\n      by (rule prime_gauss_int_norm_imp_prime_elem)\n         (simp add: gauss_int_norm_mult norm_z2' \\<open>prime p\\<close>)\n    ultimately have \"prime (\\<i>\\<^sub>\\<int> * gauss_cnj z2')\"\n      by (simp add: prime_def)\n    moreover from dvd have \"z1' dvd \\<i>\\<^sub>\\<int> * gauss_cnj z2'\"\n      by simp\n    ultimately have \"z1' = \\<i>\\<^sub>\\<int> * gauss_cnj z2'\"\n      using \\<open>prime z1'\\<close> by (simp add: primes_dvd_imp_eq)\n    hence False using z1 z2 sgns\n      by (auto simp: gauss_int_eq_iff z1'_def z2'_def)\n    thus ?thesis ..\n  qed\nqed\n\nlemma two_sum_of_squares_nat_iff: \"(x :: nat) ^ 2 + y ^ 2 = 2 \\<longleftrightarrow> x = 1 \\<and> y = 1\"\nproof\n  assume eq: \"x ^ 2 + y ^ 2 = 2\"\n  have square_neq_2: \"n ^ 2 \\<noteq> 2\" for n :: nat\n  proof\n    assume *: \"n ^ 2 = 2\"\n    have \"prime (2 :: nat)\"\n      by simp\n    thus False by (subst (asm) * [symmetric]) (auto simp: prime_power_iff)\n  qed\n\n  from eq have \"x ^ 2 < 2 ^ 2\" \"y ^ 2 < 2 ^ 2\"\n    by simp_all\n  hence \"x < 2\" \"y < 2\"\n    using power2_less_imp_less[of x 2] power2_less_imp_less[of y 2] by auto\n  moreover have \"x > 0\" \"y > 0\"\n    using eq square_neq_2[of x] square_neq_2[of y] by (auto intro!: Nat.gr0I)\n  ultimately show \"x = 1 \\<and> y = 1\"\n    by auto\nqed auto\n\nlemma prime_sum_of_squares_unique:\n  fixes p :: nat\n  assumes \"prime p\" \"p = 2 \\<or> [p = 1] (mod 4)\"\n  shows   \"\\<exists>!(x,y). x \\<le> y \\<and> x ^ 2 + y ^ 2 = p\"\n  using assms(2)\nproof\n  assume [simp]: \"p = 2\"\n  have **: \"(\\<lambda>(x,y). x \\<le> y \\<and> x ^ 2 + y ^ 2 = p) = (\\<lambda>z. z = (1,1 :: nat))\"\n    using two_sum_of_squares_nat_iff by (auto simp: fun_eq_iff)\n  thus ?thesis\n    by (subst **) auto\nqed (use prime_1_mod_4_sum_of_squares_unique[of p] assms in auto)\n\ntext \\<open>\n  We now give a simple and inefficient algorithm to compute the canonical decomposition\n  $x ^ 2 + y ^ 2$ with $x\\leq y$.\n\\<close>\ndefinition prime_square_sum_nat_decomp :: \"nat \\<Rightarrow> nat \\<times> nat\" where\n  \"prime_square_sum_nat_decomp p =\n     (if prime p \\<and> (p = 2 \\<or> [p = 1] (mod 4))\n      then THE (x,y). x \\<le> y \\<and> x ^ 2 + y ^ 2 = p else (0, 0))\"\n\nlemma prime_square_sum_nat_decomp_eqI:\n  assumes \"prime p\" \"x ^ 2 + y ^ 2 = p\" \"x \\<le> y\"\n  shows   \"prime_square_sum_nat_decomp p = (x, y)\"\nproof -\n  have \"[gauss_int_norm (of_nat x + \\<i>\\<^sub>\\<int> * of_nat y) \\<noteq> 3] (mod 4)\"\n    by (rule gauss_int_norm_not_3_mod_4)\n  also have \"gauss_int_norm (of_nat x + \\<i>\\<^sub>\\<int> * of_nat y) = p\"\n    using assms by (auto simp: gauss_int_norm_def nat_add_distrib nat_power_eq)\n  finally have \"[p \\<noteq> 3] (mod 4)\" .\n  with prime_mod_4_cases[of p] assms have *: \"p = 2 \\<or> [p = 1] (mod 4)\"\n    by auto\n\n  have \"prime_square_sum_nat_decomp p = (THE (x,y). x \\<le> y \\<and> x ^ 2 + y ^ 2 = p)\"\n    using * \\<open>prime p\\<close> by (simp add: prime_square_sum_nat_decomp_def)\n  also have \"\\<dots> = (x, y)\"\n  proof (rule the1_equality)\n    show \"\\<exists>!(x,y). x \\<le> y \\<and> x ^ 2 + y ^ 2 = p\"\n      using \\<open>prime p\\<close> * by (rule prime_sum_of_squares_unique)\n  qed (use assms in auto)\n  finally show ?thesis .\nqed\n\nlemma prime_square_sum_nat_decomp_correct:\n  assumes \"prime p\" \"p = 2 \\<or> [p = 1] (mod 4)\"\n  defines \"z \\<equiv> prime_square_sum_nat_decomp p\"\n  shows \"fst z ^ 2 + snd z ^ 2 = p\" \"fst z \\<le> snd z\"\nproof -\n  define z' where \"z' = (THE (x,y). x \\<le> y \\<and> x ^ 2 + y ^ 2 = p)\"\n  have \"z = z'\"\n    unfolding z_def z'_def using assms by (simp add: prime_square_sum_nat_decomp_def)\n  also have\"\\<exists>!(x,y). x \\<le> y \\<and> x ^ 2 + y ^ 2 = p\"\n    using assms by (intro prime_sum_of_squares_unique)\n  hence \"case z' of (x, y) \\<Rightarrow> x \\<le> y \\<and> x ^ 2 + y ^ 2 = p\"\n    unfolding z'_def by (rule theI')\n  finally show \"fst z ^ 2 + snd z ^ 2 = p\" \"fst z \\<le> snd z\"\n    by auto\nqed\n\nlemma sum_of_squares_nat_bound:\n  fixes x y n :: nat\n  assumes \"x ^ 2 + y ^ 2 = n\"\n  shows   \"x \\<le> n\"\nproof (cases \"x = 0\")\n  case False\n  hence \"x * 1 \\<le> x ^ 2\"\n    unfolding power2_eq_square by (intro mult_mono) auto\n  also have \"\\<dots> \\<le> x ^ 2 + y ^ 2\"\n    by simp\n  also have \"\\<dots> = n\"\n    by fact\n  finally show ?thesis by simp\nqed auto\n\nlemma sum_of_squares_nat_bound':\n  fixes x y n :: nat\n  assumes \"x ^ 2 + y ^ 2 = n\"\n  shows   \"y \\<le> n\"\n  using sum_of_squares_nat_bound[of y x] assms by (simp add: add.commute)\n\nlemma is_singleton_conv_Ex1:\n  \"is_singleton A \\<longleftrightarrow> (\\<exists>!x. x \\<in> A)\"\nproof\n  assume \"is_singleton A\"\n  thus \"\\<exists>!x. x \\<in> A\"\n    by (auto elim!: is_singletonE)\nnext\n  assume \"\\<exists>!x. x \\<in> A\"\n  thus \"is_singleton A\"\n    by (metis equals0D is_singletonI')\nqed\n\nlemma the_elemI:\n  assumes \"is_singleton A\"\n  shows   \"the_elem A \\<in> A\"\n  using assms by (elim is_singletonE) auto\n\nlemma prime_square_sum_nat_decomp_code_aux:\n  assumes \"prime p\" \"p = 2 \\<or> [p = 1] (mod 4)\"\n  defines \"z \\<equiv> the_elem (Set.filter (\\<lambda>(x,y). x ^ 2 + y ^ 2 = p) (SIGMA x:{0..p}. {x..p}))\"\n  shows \"prime_square_sum_nat_decomp p = z\"\nproof -\n  let ?A = \"Set.filter (\\<lambda>(x,y). x ^ 2 + y ^ 2 = p) (SIGMA x:{0..p}. {x..p})\"\n  have eq: \"?A = {(x,y). x \\<le> y \\<and> x ^ 2 + y ^ 2 = p}\"\n    using sum_of_squares_nat_bound sum_of_squares_nat_bound' by auto\n  have z: \"z \\<in> Set.filter (\\<lambda>(x,y). x ^ 2 + y ^ 2 = p) (SIGMA x:{0..p}. {x..p})\"\n    unfolding z_def eq using prime_sum_of_squares_unique[OF assms(1,2)]\n    by (intro the_elemI) (simp add: is_singleton_conv_Ex1)\n  have \"prime_square_sum_nat_decomp p = (fst z, snd z)\"\n    using z by (intro prime_square_sum_nat_decomp_eqI[OF assms(1)]) auto\n  also have \"\\<dots> = z\"\n    by simp\n  finally show ?thesis .\nqed\n\nlemma prime_square_sum_nat_decomp_code [code]:\n  \"prime_square_sum_nat_decomp p =\n     (if prime p \\<and> (p = 2 \\<or> [p = 1] (mod 4))\n      then the_elem (Set.filter (\\<lambda>(x,y). x ^ 2 + y ^ 2 = p) (SIGMA x:{0..p}. {x..p}))\n      else (0, 0))\"\n  using prime_square_sum_nat_decomp_code_aux[of p]\n  by (auto simp: prime_square_sum_nat_decomp_def)\n\n\nsubsection \\<open>Executable factorisation of Gaussian integers\\<close>\n\ntext \\<open>\n  Lastly, we use all of the above to give an executable (albeit not very efficient) factorisation\n  algorithm for Gaussian integers based on factorisation of regular integers. Note that we will\n  only compute the set of prime factors without multiplicity, but given that, it would be fairly\n  easy to determine the multiplicity as well.\n\n  First, we need the following function that computes the Gaussian integer factors of a \n  \\<open>\\<int>\\<close>-prime \\<open>p\\<close>:\n\\<close>\ndefinition factor_gauss_int_prime_nat :: \"nat \\<Rightarrow> gauss_int list\" where\n  \"factor_gauss_int_prime_nat p =\n     (if p = 2 then [1 + \\<i>\\<^sub>\\<int>]\n      else if [p = 3] (mod 4) then [of_nat p]\n      else case prime_square_sum_nat_decomp p of\n             (x, y) \\<Rightarrow> [of_nat x + \\<i>\\<^sub>\\<int> * of_nat y, of_nat y + \\<i>\\<^sub>\\<int> * of_nat x])\"\n\nlemma factor_gauss_int_prime_nat_correct:\n  assumes \"prime p\"\n  shows   \"set (factor_gauss_int_prime_nat p) = prime_factors (of_nat p)\"\n  using prime_mod_4_cases[OF assms]\nproof (elim disjE)\n  assume \"p = 2\"\n  thus ?thesis\n    by (auto simp: prime_factorization_2_gauss_int factor_gauss_int_prime_nat_def)\nnext\n  assume *: \"[p = 3] (mod 4)\"\n  with assms have \"prime (of_nat p :: gauss_int)\"\n    by (intro prime_gauss_int_of_nat)\n  thus ?thesis using assms *\n    by (auto simp: prime_factorization_prime factor_gauss_int_prime_nat_def cong_def)\nnext\n  assume *: \"[p = 1] (mod 4)\"\n  then interpret noninert_gauss_int_prime p\n    using \\<open>prime p\\<close> by unfold_locales\n  define z where \"z = prime_square_sum_nat_decomp p\"\n  define x y where \"x = fst z\" and \"y = snd z\"\n  have xy: \"x ^ 2 + y ^ 2 = p\" \"x \\<le> y\"\n    using prime_square_sum_nat_decomp_correct[of p] * assms\n    by (auto simp: x_def y_def z_def)\n  from xy have xy_signs: \"x > 0\" \"y > 0\"\n    using prime_1_mod_4_sum_of_squares_unique_aux[of p x y] assms * by auto\n  have norms: \"gauss_int_norm (of_nat x + \\<i>\\<^sub>\\<int> * of_nat y) = p\"\n              \"gauss_int_norm (of_nat y + \\<i>\\<^sub>\\<int> * of_nat x) = p\"\n    using xy by (auto simp: gauss_int_norm_def nat_add_distrib nat_power_eq)\n  have prime: \"prime (of_nat x + \\<i>\\<^sub>\\<int> * of_nat y)\" \"prime (of_nat y + \\<i>\\<^sub>\\<int> * of_nat x)\"\n    using norms xy_signs \\<open>prime p\\<close> unfolding prime_def normalized_gauss_int_iff\n    by (auto intro!: prime_gauss_int_norm_imp_prime_elem)\n\n  have \"normalize ((of_nat x + \\<i>\\<^sub>\\<int> * of_nat y) * (of_nat y + \\<i>\\<^sub>\\<int> * of_nat x)) = of_nat p\"\n  proof -\n    have \"(of_nat x + \\<i>\\<^sub>\\<int> * of_nat y) * (of_nat y + \\<i>\\<^sub>\\<int> * of_nat x) = (\\<i>\\<^sub>\\<int> * of_nat p :: gauss_int)\"\n      by (subst xy(1) [symmetric]) (auto simp: gauss_int_eq_iff power2_eq_square)\n    also have \"normalize \\<dots> = of_nat p\"\n      by simp\n    finally show ?thesis .\n  qed\n  hence \"prime_factorization (of_nat p) =\n         prime_factorization (prod_mset {#of_nat x + \\<i>\\<^sub>\\<int> * of_nat y, of_nat y + \\<i>\\<^sub>\\<int> * of_nat x#})\"\n    using assms xy by (subst prime_factorization_unique) (auto simp: gauss_int_eq_iff)\n  also have \"\\<dots> = {#of_nat x + \\<i>\\<^sub>\\<int> * of_nat y, of_nat y + \\<i>\\<^sub>\\<int> * of_nat x#}\"\n    using prime by (subst prime_factorization_prod_mset_primes) auto\n  finally have \"prime_factors (of_nat p) = {of_nat x + \\<i>\\<^sub>\\<int> * of_nat y, of_nat y + \\<i>\\<^sub>\\<int> * of_nat x}\"\n    by simp\n  also have \"\\<dots> = set (factor_gauss_int_prime_nat p)\"\n    using * unfolding factor_gauss_int_prime_nat_def case_prod_unfold\n    by (auto simp: cong_def x_def y_def z_def)\n  finally show ?thesis ..\nqed\n\ntext \\<open>\n  Next, we lift this to compute the prime factorisation of any integer in the Gaussian integers:\n\\<close>\ndefinition prime_factors_gauss_int_of_nat :: \"nat \\<Rightarrow> gauss_int set\" where\n  \"prime_factors_gauss_int_of_nat n = (if n = 0 then {} else \n     (\\<Union>p\\<in>prime_factors n. set (factor_gauss_int_prime_nat p)))\"\n\nlemma prime_factors_gauss_int_of_nat_correct:\n  \"prime_factors_gauss_int_of_nat n = prime_factors (of_nat n)\"\nproof (cases \"n = 0\")\n  case False\n  from False have [simp]: \"n > 0\" by auto\n  have \"prime_factors (of_nat n :: gauss_int) =\n          prime_factors (of_nat (prod_mset (prime_factorization n)))\"\n    by (subst prod_mset_prime_factorization_nat [symmetric]) auto\n  also have \"\\<dots> = prime_factors (prod_mset (image_mset of_nat (prime_factorization n)))\"\n    by (subst of_nat_prod_mset) auto\n  also have \"\\<dots> = (\\<Union>p\\<in>prime_factors n. prime_factors (of_nat p))\"\n    by (subst prime_factorization_prod_mset) auto\n  also have \"\\<dots> = (\\<Union>p\\<in>prime_factors n. set (factor_gauss_int_prime_nat p))\"\n    by (intro SUP_cong refl factor_gauss_int_prime_nat_correct [symmetric]) auto\n  finally show ?thesis by (simp add: prime_factors_gauss_int_of_nat_def)\nqed (auto simp:  prime_factors_gauss_int_of_nat_def)\n\ntext \\<open>\n  We can now use this to factor any Gaussian integer by computing a factorisation of its\n  norm and removing all the prime divisors that do not actually divide it.\n\\<close>\ndefinition prime_factors_gauss_int :: \"gauss_int \\<Rightarrow> gauss_int set\" where\n  \"prime_factors_gauss_int z = (if z = 0 then {} \n     else Set.filter (\\<lambda>p. p dvd z) (prime_factors_gauss_int_of_nat (gauss_int_norm z)))\"\n\nlemma prime_factors_gauss_int_correct [code_unfold]: \"prime_factors z = prime_factors_gauss_int z\"\nproof (cases \"z = 0\")\n  case [simp]: False\n  define n where \"n = gauss_int_norm z\"\n  from False have [simp]: \"n > 0\" by (auto simp: n_def)\n\n  have \"prime_factors_gauss_int z = Set.filter (\\<lambda>p. p dvd z) (prime_factors (of_nat n))\"\n    by (simp add: prime_factors_gauss_int_of_nat_correct prime_factors_gauss_int_def n_def)\n  also have \"of_nat n = z * gauss_cnj z\"\n    by (simp add: n_def self_mult_gauss_cnj)\n  also have \"prime_factors \\<dots> = prime_factors z \\<union> prime_factors (gauss_cnj z)\"\n    by (subst prime_factors_product) auto\n  also have \"Set.filter (\\<lambda>p. p dvd z) \\<dots> = prime_factors z\"\n    by (auto simp: in_prime_factors_iff)\n  finally show ?thesis by simp\nqed (auto simp: prime_factors_gauss_int_def)\n\n(*<*)\nunbundle no_gauss_int_notation\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/Gaussian_Integers/Gaussian_Integers.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267626522813, "lm_q2_score": 0.8539127548105611, "lm_q1q2_score": 0.741902254349551}}
{"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_01\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 take :: \"Nat => 'a list => 'a list\" where\n  \"take (Z) z = nil2\"\n| \"take (S z2) (nil2) = nil2\"\n| \"take (S z2) (cons2 x2 x3) = cons2 x2 (take z2 x3)\"\n\nfun drop :: \"Nat => 'a list => 'a list\" where\n  \"drop (Z) z = z\"\n| \"drop (S z2) (nil2) = nil2\"\n| \"drop (S z2) (cons2 x2 x3) = drop z2 x3\"\n\ntheorem property0 :(*Probably the best proof.*)\n  \"x (take n xs) (drop n xs) = xs\"\n(*\n  find_proof DInd\n*)\n  (*\"induct rule:take.induct also works well.*)\n  (*Because take.induct and drop.induct are identical.*)\n  (*why \"induct rule:take.induct\" or \"induct rule:drop.induct\"?\n    Because all the definitions of the innermost recursively defined constants (\"take\" and \"drop\") \n    produce the same rule. *)\n  (*Why induction on xs?*)\n  (* Induction on \"n xs rule: TIP_prop_01.drop.induct\" works as well.\n   * Induction on \"n\" rule: TIP_prop_01.drop.induct is bad\n   * because the resulting proof goal is identical to the original goal. *)\n  apply (induct xs rule: TIP_prop_01.drop.induct)\n    apply auto\n  done\n\ntheorem property0'(*sub-optimal proof*):\n  \"x (take n xs) (drop n xs) = xs\"\n  (*Induction on n might look promising in the first try\n    since both \"take\" and \"drop\" are defined recursively on the first argument, but...*)\n  apply(induct n arbitrary: xs)\n   apply auto[1]\n    (*This is problematic:\n    We cannot use the simplification rule of \"x\"\n    because we cannot simplify \"TIP_prop_01.take (S n) xs\".\n   *)\n  apply(case_tac n)\n   apply(case_tac xs)\n    apply auto[1]\n   apply auto[1]\n  apply(case_tac xs)\n   apply auto[1]\n  apply auto[1](*To discharge the last sub-goal using this auto[1], we need to generalize xs*)\n  done\n\ntheorem property0''(*sub-optimal proof*):\n  \"x (take n xs) (drop n xs) = xs\"\n  (*Induction on \"xs\" without \"rule:take.induct\" might look promising in the first try\n    since both \"take\" and \"drop\" are defined recursively on the first argument, but...*)\n  apply (induct xs arbitrary: n)\n   apply (induct n)\n    apply(case_tac n)(*cases is not good enough because \"n\" is quantified by \\<And>*)\n     apply fastforce+\n    (*It is not so easy from this point\n    \"(inductino hypothesis) \\<Longrightarrow>\n     x (TIP_prop_01.take n (cons2 x1 xs)) (TIP_prop_01.drop n (cons2 x1 xs)) = cons2 x1 xs\"\n    because we cannot apply any of the following simplification rules.\n     x.simps   : because \"(TIP_prop_01.take n (cons2 x1 xs))\" is not fully evaluated.\n     take.simps: because \"n\" is a variable and Isabelle cannot do patter matching.\n     drop.simps: because \"n\" is a variable and Isabelle cannot do patter matching. \n   *)\n  apply(case_tac n)\n   apply auto[1]\n  apply(simp del: take.simps drop.simps)\n  apply(thin_tac \"n = S x2\")\n  apply(subst \"take.simps\")\n  apply(subst \"drop.simps\")\n  apply(subst \"x.simps\")\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_01.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127492339909, "lm_q2_score": 0.8688267677469951, "lm_q1q2_score": 0.7419022538549186}}
{"text": "theory dec41 imports Main begin \n\ntext {*\n  Proving two exercises in dec41 Proof Theory notes in propositional calculus\n*}\n\nlemma \"A  \\<longrightarrow>((((A \\<longrightarrow> B) \\<longrightarrow> B) \\<longrightarrow> C) \\<longrightarrow> C)\"\n  apply (rule impI)+\n  apply (erule impE)\n   apply (rule impI)\n   apply (erule mp)\n   apply assumption+\n  done\n\nlemma \"((((P \\<longrightarrow> Q) \\<longrightarrow> P) \\<longrightarrow> P) \\<longrightarrow> Q) \\<longrightarrow> Q\"\n  apply (rule impI)+\n  apply(erule impE)\n   apply (rule impI)+\n   apply(rule classical)\n   apply(erule mp)\n  apply(rule impI)\n  apply (erule notE)\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/dec41.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.929440403812707, "lm_q2_score": 0.7981867873410141, "lm_q1q2_score": 0.7418670499441994}}
{"text": "theory Tensor_LValues\n  imports LValues_Typed Complex_Main\nbegin\n\n\nsection Matrices\n\n(* TODO: make non-square *)\ntypedef ('row,'col) matrix = \"UNIV::('row\\<Rightarrow>'col\\<Rightarrow>complex) set\" by simp\nsetup_lifting type_definition_matrix\ntype_synonym 'a square = \"('a,'a) matrix\"\n\nlift_definition tensor :: \"('ar,'ac) matrix \\<Rightarrow> ('br,'bc) matrix \\<Rightarrow> ('ar*'br,'ac*'bc) matrix\" is\n  \"%A B. \\<lambda>(r1,r2) (c1,c2). A r1 c1 * B r2 c2\" .\n\n(* TODO associator *)\n(* TODO swapper *)\n\ninstantiation matrix :: (type, type) ab_group_add begin\nlift_definition plus_matrix :: \"('r,'c) matrix \\<Rightarrow> ('r,'c) matrix \\<Rightarrow> ('r,'c) matrix\" is \"%A B i j. A i j + B i j\".\nlift_definition minus_matrix :: \"('r,'c) matrix \\<Rightarrow> ('r,'c) matrix \\<Rightarrow> ('r,'c) matrix\" is \"%A B i j. A i j - B i j\".\nlift_definition uminus_matrix :: \"('r,'c) matrix \\<Rightarrow> ('r,'c) matrix\" is \"%A i j. - A i j\".\nlift_definition zero_matrix :: \"('r,'c) matrix\" is \"\\<lambda>i j. 0\".\ninstance sorry\nend\n\nlift_definition mat_mul :: \"('a,'b) matrix \\<Rightarrow> ('b,'c) matrix \\<Rightarrow> ('a,'c) matrix\" is \"%A B i k. (\\<Sum>j\\<in>UNIV. A i j * B j k)\".\nlift_definition mat_one :: \"'a square\" is \"\\<lambda>i j. if i=j then 1 else 0\".\n\nabbreviation \"delta x y == (if x=y then 1 else 0)\"\n\n(*\nlift_definition matrix_on :: \"('br,'bc) matrix \\<Rightarrow> ('a,'br) lvalue \\<Rightarrow> ('a,'bc) lvalue \\<Rightarrow> 'a square\" is\n  \"\\<lambda>B xr xc (r::'a) (c::'a). B (fst (split_memory xr r)) (fst (split_memory xc c))\n  * delta (snd (split_memory xr r)) (snd (split_memory xc c))\" .\n\nlemma matrix_on_lift_left:\n  fixes xc :: \"('a,'bc) lvalue\" and xr :: \"('a,'br) lvalue\"\n  assumes compatc[simp]: \"compatible_lvalues xc y\"\n  assumes compatr[simp]: \"compatible_lvalues xr y\"\n  defines \"xyr == lvalue_pair xr y\"\n  defines \"xyc == lvalue_pair xc y\"\n  shows \"matrix_on A xr xc = matrix_on (tensor A mat_one) xyr xyc\"\nproof (transfer fixing: xr xc y xyc xyr, rule ext, rule ext)\n  fix A :: \"'br \\<Rightarrow> 'bc \\<Rightarrow> complex\" and r c\n\n  define xcrest xrrest yrest xycrest xyrrest\n    where \"xcrest m = snd (split_memory xc m)\" \n      and \"xrrest m = snd (split_memory xr m)\" \n      and \"yrest m = snd (split_memory y m)\"\n      and \"xycrest m = snd (split_memory xyc m)\"\n      and \"xyrrest m = snd (split_memory xyr m)\" for m\n\n  have [simp]: \"valid_lvalue xyc\"\n    unfolding xyc_def by simp\n  have [simp]: \"valid_lvalue xyr\"\n    unfolding xyr_def by simp\n  have [simp]: \"valid_lvalue xc\"\n    using LValues_Typed.compatible_valid1 compatc by blast\n  have [simp]: \"valid_lvalue xr\"\n    using LValues_Typed.compatible_valid1 compatr by blast\n  have [simp]: \"valid_lvalue y\"\n    using LValues_Typed.compatible_valid2 compatc by blast\n\n  have [simp]: \"fst (split_memory xc r) = getter xc r\" for r\n    by simp\n  have [simp]: \"fst (split_memory xr r) = getter xr r\" for r\n    by simp\n  have [simp]: \"fst (split_memory y r) = getter y r\" for r\n    by simp\n\n  have [simp]: \"fst (split_memory xyc r) = (getter xc r, getter y r)\" for r\n    apply (subst fst_split_memory)\n    unfolding xyc_def by simp_all\n  have [simp]: \"fst (split_memory xyr r) = (getter xr r, getter y r)\" for r\n    apply (subst fst_split_memory)\n    unfolding xyr_def by simp_all\n\n  (* TODO: not true without extra assumptions *)\n  have [simp]: \"xycrest m = xyrrest m\" for m\n    sorry\n\n  have [simp]: \"xrrest a = xrrest b \\<longleftrightarrow> xyrrest a = xyrrest b \\<and> getter y a = getter y b\" for a b\n    unfolding xrrest_def xyrrest_def xyr_def\n    apply (rule split_pair_eq_typed)\n    by (rule compatr)\n  have [simp]: \"xcrest a = xcrest b \\<longleftrightarrow> xycrest a = xycrest b \\<and> getter y a = getter y b\" for a b\n    unfolding xcrest_def xycrest_def xyc_def\n    apply (rule split_pair_eq_typed)\n    by (rule compatc)\n\n  show \"A (fst (split_memory xr r)) (fst (split_memory xc c)) *\n           delta (xrrest r) (xcrest c)\n        =\n          (\\<lambda>(r1, r2) (c1, c2). A r1 c1 * delta r2 c2)\n              (fst (split_memory xyr r))\n              (fst (split_memory xyc c))\n           *\n           delta (xyrrest r) (xycrest c)\"\n\n    apply simp\n    apply auto\n\n    by simp\nqed\n*)\n\nend", "meta": {"author": "dominique-unruh", "repo": "registers", "sha": "6e88a095c3dabe8e4c0b869eac65454d0d281340", "save_path": "github-repos/isabelle/dominique-unruh-registers", "path": "github-repos/isabelle/dominique-unruh-registers/registers-6e88a095c3dabe8e4c0b869eac65454d0d281340/attic/Tensor_LValues_NonSquare.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404057671714, "lm_q2_score": 0.7981867825403176, "lm_q1q2_score": 0.7418670470422658}}
{"text": "theory Ex028\n  imports Main \nbegin \n  \n  \n  \nlemma \"\\<not>(A \\<and> B) \\<longleftrightarrow> (\\<not>A \\<or> \\<not>B)\" \nproof -\n  {\n    \n    assume a:\"\\<not>(A \\<and> B)\"\n    {\n      assume b:\"\\<not>(\\<not>A \\<or> \\<not>B)\"\n      {\n        assume \"\\<not>A\"\n        hence \"\\<not>A \\<or> \\<not>B\" by (rule disjI1)\n        with b have False by contradiction\n      }\n      hence \"\\<not>\\<not>A\" by (rule notI)\n      hence c:A by (rule notnotD)\n      {\n        assume \"\\<not>B\"\n        hence \"\\<not>A \\<or> \\<not>B\" by (rule disjI2)\n        with b have False by contradiction\n      }\n      hence \"\\<not>\\<not>B\" by (rule notI)\n      hence B by (rule notnotD)\n      with c have \"A \\<and> B\" by (rule conjI)\n      with a have False by contradiction\n    }\n    hence \"\\<not>\\<not>(\\<not>A \\<or> \\<not>B)\" by (rule notI)\n    hence \"\\<not>A \\<or> \\<not>B\" by (rule notnotD)\n  }\n  moreover\n  {\n    assume a:\"\\<not>A \\<or> \\<not>B\"\n    {\n      assume b:\"A \\<and> B\"\n      hence c:A by (rule conjE)\n      from b have d:B by (rule conjE)\n      {\n        assume \"\\<not>A\"\n        with c have False by contradiction\n      }\n      note e=this\n      {\n        assume \"\\<not>B\"\n        with d have False by contradiction\n      }\n      with a and e have False by (rule disjE)\n    }\n    hence \"\\<not>(A \\<and> B)\" by (rule notI)\n  }\n  ultimately show ?thesis by (rule iffI)\nqed\n  \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/Ex028.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404096760996, "lm_q2_score": 0.798186775339273, "lm_q1q2_score": 0.7418670434693788}}
{"text": "theory Section2_6\n  imports Main\nbegin\n\nprimrec sum :: \"nat \\<Rightarrow> nat\" where\n  \"sum 0 = 0\" |\n  \"sum (Suc n) = Suc n + sum n\"\n\nlemma \"sum n + sum n = n*(Suc n)\"\n  apply (induct_tac n)\n  apply auto\n  done\n\nlemma \"\\<lbrakk>\\<not> m < n; m < n + (1::nat)\\<rbrakk> \\<Longrightarrow> m = n\"\n  apply arith\n  done\n\n\nlemma \"m \\<noteq> (n::nat) \\<Longrightarrow> m < n \\<or> n < m\"\n  apply arith\n  done\n\nlemma \"min i (max j (k*k)) = max (min (k*k) i) (min i (j::nat))\"\n  apply arith\n  done\n\n\nend", "meta": {"author": "KeenS", "repo": "Isabelle", "sha": "3411f313acf33fb18d2229906b4fd1ea5e8f9033", "save_path": "github-repos/isabelle/KeenS-Isabelle", "path": "github-repos/isabelle/KeenS-Isabelle/Isabelle-3411f313acf33fb18d2229906b4fd1ea5e8f9033/2.6.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9294403999037782, "lm_q2_score": 0.7981867825403177, "lm_q1q2_score": 0.741867042362183}}
{"text": "(*  Title:      HOL/UNITY/ListOrder.thy\n    Author:     Lawrence C Paulson, Cambridge University Computer Laboratory\n    Copyright   1998  University of Cambridge\n\nLists are partially ordered by Charpentier's Generalized Prefix Relation\n   (xs,ys) : genPrefix(r)\n     if ys = xs' @ zs where length xs = length xs'\n     and corresponding elements of xs, xs' are pairwise related by r\n\nAlso overloads <= and < for lists!\n*)\n\nsection \\<open>The Prefix Ordering on Lists\\<close>\n\ntheory ListOrder\nimports Main\nbegin\n\ninductive_set\n  genPrefix :: \"('a * 'a)set => ('a list * 'a list)set\"\n  for r :: \"('a * 'a)set\"\n where\n   Nil:     \"([],[]) : genPrefix(r)\"\n\n | prepend: \"[| (xs,ys) : genPrefix(r);  (x,y) : r |] ==>\n             (x#xs, y#ys) : genPrefix(r)\"\n\n | append:  \"(xs,ys) : genPrefix(r) ==> (xs, ys@zs) : genPrefix(r)\"\n\ninstantiation list :: (type) ord \nbegin\n\ndefinition\n  prefix_def:        \"xs <= zs \\<longleftrightarrow>  (xs, zs) : genPrefix Id\"\n\ndefinition\n  strict_prefix_def: \"xs < zs  \\<longleftrightarrow>  xs \\<le> zs \\<and> \\<not> zs \\<le> (xs :: 'a list)\"\n\ninstance ..  \n\n(*Constants for the <= and >= relations, used below in translations*)\n\nend\n\ndefinition Le :: \"(nat*nat) set\" where\n    \"Le == {(x,y). x <= y}\"\n\ndefinition  Ge :: \"(nat*nat) set\" where\n    \"Ge == {(x,y). y <= x}\"\n\nabbreviation\n  pfixLe :: \"[nat list, nat list] => bool\"  (infixl \"pfixLe\" 50)  where\n  \"xs pfixLe ys == (xs,ys) : genPrefix Le\"\n\nabbreviation\n  pfixGe :: \"[nat list, nat list] => bool\"  (infixl \"pfixGe\" 50)  where\n  \"xs pfixGe ys == (xs,ys) : genPrefix Ge\"\n\n\nsubsection\\<open>preliminary lemmas\\<close>\n\nlemma Nil_genPrefix [iff]: \"([], xs) : genPrefix r\"\nby (cut_tac genPrefix.Nil [THEN genPrefix.append], auto)\n\nlemma genPrefix_length_le: \"(xs,ys) : genPrefix r ==> length xs <= length ys\"\nby (erule genPrefix.induct, auto)\n\nlemma cdlemma:\n     \"[| (xs', ys'): genPrefix r |]  \n      ==> (ALL x xs. xs' = x#xs --> (EX y ys. ys' = y#ys & (x,y) : r & (xs, ys) : genPrefix r))\"\napply (erule genPrefix.induct, blast, blast)\napply (force intro: genPrefix.append)\ndone\n\n(*As usual converting it to an elimination rule is tiresome*)\nlemma cons_genPrefixE [elim!]: \n     \"[| (x#xs, zs): genPrefix r;   \n         !!y ys. [| zs = y#ys;  (x,y) : r;  (xs, ys) : genPrefix r |] ==> P  \n      |] ==> P\"\nby (drule cdlemma, simp, blast)\n\nlemma Cons_genPrefix_Cons [iff]:\n     \"((x#xs,y#ys) : genPrefix r) = ((x,y) : r & (xs,ys) : genPrefix r)\"\nby (blast intro: genPrefix.prepend)\n\n\nsubsection\\<open>genPrefix is a partial order\\<close>\n\nlemma refl_genPrefix: \"refl r ==> refl (genPrefix r)\"\napply (unfold refl_on_def, auto)\napply (induct_tac \"x\")\nprefer 2 apply (blast intro: genPrefix.prepend)\napply (blast intro: genPrefix.Nil)\ndone\n\nlemma genPrefix_refl [simp]: \"refl r ==> (l,l) : genPrefix r\"\nby (erule refl_onD [OF refl_genPrefix UNIV_I])\n\nlemma genPrefix_mono: \"r<=s ==> genPrefix r <= genPrefix s\"\napply clarify\napply (erule genPrefix.induct)\napply (auto intro: genPrefix.append)\ndone\n\n\n(** Transitivity **)\n\n(*A lemma for proving genPrefix_trans_O*)\nlemma append_genPrefix:\n     \"(xs @ ys, zs) : genPrefix r \\<Longrightarrow> (xs, zs) : genPrefix r\"\n  by (induct xs arbitrary: zs) auto\n\n(*Lemma proving transitivity and more*)\nlemma genPrefix_trans_O:\n  assumes \"(x, y) : genPrefix r\"\n  shows \"\\<And>z. (y, z) : genPrefix s \\<Longrightarrow> (x, z) : genPrefix (r O s)\"\n  apply (atomize (full))\n  using assms\n  apply induct\n    apply blast\n   apply (blast intro: genPrefix.prepend)\n  apply (blast dest: append_genPrefix)\n  done\n\nlemma genPrefix_trans:\n  \"(x, y) : genPrefix r \\<Longrightarrow> (y, z) : genPrefix r \\<Longrightarrow> trans r\n    \\<Longrightarrow> (x, z) : genPrefix r\"\n  apply (rule trans_O_subset [THEN genPrefix_mono, THEN subsetD])\n   apply assumption\n  apply (blast intro: genPrefix_trans_O)\n  done\n\nlemma prefix_genPrefix_trans:\n  \"[| x<=y;  (y,z) : genPrefix r |] ==> (x, z) : genPrefix r\"\napply (unfold prefix_def)\napply (drule genPrefix_trans_O, assumption)\napply simp\ndone\n\nlemma genPrefix_prefix_trans:\n  \"[| (x,y) : genPrefix r;  y<=z |] ==> (x,z) : genPrefix r\"\napply (unfold prefix_def)\napply (drule genPrefix_trans_O, assumption)\napply simp\ndone\n\nlemma trans_genPrefix: \"trans r ==> trans (genPrefix r)\"\nby (blast intro: transI genPrefix_trans)\n\n\n(** Antisymmetry **)\n\nlemma genPrefix_antisym:\n  assumes 1: \"(xs, ys) : genPrefix r\"\n    and 2: \"antisym r\"\n    and 3: \"(ys, xs) : genPrefix r\"\n  shows \"xs = ys\"\n  using 1 3\nproof induct\n  case Nil\n  then show ?case by blast\nnext\n  case prepend\n  then show ?case using 2 by (simp add: antisym_def)\nnext\n  case (append xs ys zs)\n  then show ?case\n    apply -\n    apply (subgoal_tac \"length zs = 0\", force)\n    apply (drule genPrefix_length_le)+\n    apply (simp del: length_0_conv)\n    done\nqed\n\nlemma antisym_genPrefix: \"antisym r ==> antisym (genPrefix r)\"\n  by (blast intro: antisymI genPrefix_antisym)\n\n\nsubsection\\<open>recursion equations\\<close>\n\nlemma genPrefix_Nil [simp]: \"((xs, []) : genPrefix r) = (xs = [])\"\n  by (induct xs) auto\n\nlemma same_genPrefix_genPrefix [simp]: \n    \"refl r ==> ((xs@ys, xs@zs) : genPrefix r) = ((ys,zs) : genPrefix r)\"\n  by (induct xs) (simp_all add: refl_on_def)\n\nlemma genPrefix_Cons:\n     \"((xs, y#ys) : genPrefix r) =  \n      (xs=[] | (EX z zs. xs=z#zs & (z,y) : r & (zs,ys) : genPrefix r))\"\n  by (cases xs) auto\n\nlemma genPrefix_take_append:\n     \"[| refl r;  (xs,ys) : genPrefix r |]  \n      ==>  (xs@zs, take (length xs) ys @ zs) : genPrefix r\"\napply (erule genPrefix.induct)\napply (frule_tac [3] genPrefix_length_le)\napply (simp_all (no_asm_simp) add: diff_is_0_eq [THEN iffD2])\ndone\n\nlemma genPrefix_append_both:\n     \"[| refl r;  (xs,ys) : genPrefix r;  length xs = length ys |]  \n      ==>  (xs@zs, ys @ zs) : genPrefix r\"\napply (drule genPrefix_take_append, assumption)\napply simp\ndone\n\n\n(*NOT suitable for rewriting since [y] has the form y#ys*)\nlemma append_cons_eq: \"xs @ y # ys = (xs @ [y]) @ ys\"\nby auto\n\nlemma aolemma:\n     \"[| (xs,ys) : genPrefix r;  refl r |]  \n      ==> length xs < length ys --> (xs @ [ys ! length xs], ys) : genPrefix r\"\napply (erule genPrefix.induct)\n  apply blast\n apply simp\ntxt\\<open>Append case is hardest\\<close>\napply simp\napply (frule genPrefix_length_le [THEN le_imp_less_or_eq])\napply (erule disjE)\napply (simp_all (no_asm_simp) add: neq_Nil_conv nth_append)\napply (blast intro: genPrefix.append, auto)\napply (subst append_cons_eq, fast intro: genPrefix_append_both genPrefix.append)\ndone\n\nlemma append_one_genPrefix:\n     \"[| (xs,ys) : genPrefix r;  length xs < length ys;  refl r |]  \n      ==> (xs @ [ys ! length xs], ys) : genPrefix r\"\nby (blast intro: aolemma [THEN mp])\n\n\n(** Proving the equivalence with Charpentier's definition **)\n\nlemma genPrefix_imp_nth:\n    \"i < length xs \\<Longrightarrow> (xs, ys) : genPrefix r \\<Longrightarrow> (xs ! i, ys ! i) : r\"\n  apply (induct xs arbitrary: i ys)\n   apply auto\n  apply (case_tac i)\n   apply auto\n  done\n\nlemma nth_imp_genPrefix:\n  \"length xs <= length ys \\<Longrightarrow>\n     (\\<forall>i. i < length xs --> (xs ! i, ys ! i) : r) \\<Longrightarrow>\n     (xs, ys) : genPrefix r\"\n  apply (induct xs arbitrary: ys)\n   apply (simp_all add: less_Suc_eq_0_disj all_conj_distrib)\n  apply (case_tac ys)\n   apply (force+)\n  done\n\nlemma genPrefix_iff_nth:\n     \"((xs,ys) : genPrefix r) =  \n      (length xs <= length ys & (ALL i. i < length xs --> (xs!i, ys!i) : r))\"\napply (blast intro: genPrefix_length_le genPrefix_imp_nth nth_imp_genPrefix)\ndone\n\n\nsubsection\\<open>The type of lists is partially ordered\\<close>\n\ndeclare refl_Id [iff] \n        antisym_Id [iff] \n        trans_Id [iff]\n\nlemma prefix_refl [iff]: \"xs <= (xs::'a list)\"\nby (simp add: prefix_def)\n\nlemma prefix_trans: \"!!xs::'a list. [| xs <= ys; ys <= zs |] ==> xs <= zs\"\napply (unfold prefix_def)\napply (blast intro: genPrefix_trans)\ndone\n\nlemma prefix_antisym: \"!!xs::'a list. [| xs <= ys; ys <= xs |] ==> xs = ys\"\napply (unfold prefix_def)\napply (blast intro: genPrefix_antisym)\ndone\n\nlemma prefix_less_le_not_le: \"!!xs::'a list. (xs < zs) = (xs <= zs & \\<not> zs \\<le> xs)\"\nby (unfold strict_prefix_def, auto)\n\ninstance list :: (type) order\n  by (intro_classes,\n      (assumption | rule prefix_refl prefix_trans prefix_antisym\n                     prefix_less_le_not_le)+)\n\n(*Monotonicity of \"set\" operator WRT prefix*)\nlemma set_mono: \"xs <= ys ==> set xs <= set ys\"\napply (unfold prefix_def)\napply (erule genPrefix.induct, auto)\ndone\n\n\n(** recursion equations **)\n\nlemma Nil_prefix [iff]: \"[] <= xs\"\nby (simp add: prefix_def)\n\nlemma prefix_Nil [simp]: \"(xs <= []) = (xs = [])\"\nby (simp add: prefix_def)\n\nlemma Cons_prefix_Cons [simp]: \"(x#xs <= y#ys) = (x=y & xs<=ys)\"\nby (simp add: prefix_def)\n\nlemma same_prefix_prefix [simp]: \"(xs@ys <= xs@zs) = (ys <= zs)\"\nby (simp add: prefix_def)\n\nlemma append_prefix [iff]: \"(xs@ys <= xs) = (ys <= [])\"\nby (insert same_prefix_prefix [of xs ys \"[]\"], simp)\n\nlemma prefix_appendI [simp]: \"xs <= ys ==> xs <= ys@zs\"\napply (unfold prefix_def)\napply (erule genPrefix.append)\ndone\n\nlemma prefix_Cons: \n   \"(xs <= y#ys) = (xs=[] | (? zs. xs=y#zs & zs <= ys))\"\nby (simp add: prefix_def genPrefix_Cons)\n\nlemma append_one_prefix: \n  \"[| xs <= ys; length xs < length ys |] ==> xs @ [ys ! length xs] <= ys\"\napply (unfold prefix_def)\napply (simp add: append_one_genPrefix)\ndone\n\nlemma prefix_length_le: \"xs <= ys ==> length xs <= length ys\"\napply (unfold prefix_def)\napply (erule genPrefix_length_le)\ndone\n\nlemma splemma: \"xs<=ys ==> xs~=ys --> length xs < length ys\"\napply (unfold prefix_def)\napply (erule genPrefix.induct, auto)\ndone\n\nlemma strict_prefix_length_less: \"xs < ys ==> length xs < length ys\"\napply (unfold strict_prefix_def)\napply (blast intro: splemma [THEN mp])\ndone\n\nlemma mono_length: \"mono length\"\nby (blast intro: monoI prefix_length_le)\n\n(*Equivalence to the definition used in Lex/Prefix.thy*)\nlemma prefix_iff: \"(xs <= zs) = (EX ys. zs = xs@ys)\"\napply (unfold prefix_def)\napply (auto simp add: genPrefix_iff_nth nth_append)\napply (rule_tac x = \"drop (length xs) zs\" in exI)\napply (rule nth_equalityI)\napply (simp_all (no_asm_simp) add: nth_append)\ndone\n\nlemma prefix_snoc [simp]: \"(xs <= ys@[y]) = (xs = ys@[y] | xs <= ys)\"\napply (simp add: prefix_iff)\napply (rule iffI)\n apply (erule exE)\n apply (rename_tac \"zs\")\n apply (rule_tac xs = zs in rev_exhaust)\n  apply simp\n apply clarify\n apply (simp del: append_assoc add: append_assoc [symmetric], force)\ndone\n\nlemma prefix_append_iff:\n     \"(xs <= ys@zs) = (xs <= ys | (? us. xs = ys@us & us <= zs))\"\napply (rule_tac xs = zs in rev_induct)\n apply force\napply (simp del: append_assoc add: append_assoc [symmetric], force)\ndone\n\n(*Although the prefix ordering is not linear, the prefixes of a list\n  are linearly ordered.*)\nlemma common_prefix_linear:\n  fixes xs ys zs :: \"'a list\"\n  shows \"xs <= zs \\<Longrightarrow> ys <= zs \\<Longrightarrow> xs <= ys | ys <= xs\"\n  by (induct zs rule: rev_induct) auto\n\nsubsection\\<open>pfixLe, pfixGe: properties inherited from the translations\\<close>\n\n(** pfixLe **)\n\nlemma refl_Le [iff]: \"refl Le\"\nby (unfold refl_on_def Le_def, auto)\n\nlemma antisym_Le [iff]: \"antisym Le\"\nby (unfold antisym_def Le_def, auto)\n\nlemma trans_Le [iff]: \"trans Le\"\nby (unfold trans_def Le_def, auto)\n\nlemma pfixLe_refl [iff]: \"x pfixLe x\"\nby simp\n\nlemma pfixLe_trans: \"[| x pfixLe y; y pfixLe z |] ==> x pfixLe z\"\nby (blast intro: genPrefix_trans)\n\nlemma pfixLe_antisym: \"[| x pfixLe y; y pfixLe x |] ==> x = y\"\nby (blast intro: genPrefix_antisym)\n\nlemma prefix_imp_pfixLe: \"xs<=ys ==> xs pfixLe ys\"\napply (unfold prefix_def Le_def)\napply (blast intro: genPrefix_mono [THEN [2] rev_subsetD])\ndone\n\nlemma refl_Ge [iff]: \"refl Ge\"\nby (unfold refl_on_def Ge_def, auto)\n\nlemma antisym_Ge [iff]: \"antisym Ge\"\nby (unfold antisym_def Ge_def, auto)\n\nlemma trans_Ge [iff]: \"trans Ge\"\nby (unfold trans_def Ge_def, auto)\n\nlemma pfixGe_refl [iff]: \"x pfixGe x\"\nby simp\n\nlemma pfixGe_trans: \"[| x pfixGe y; y pfixGe z |] ==> x pfixGe z\"\nby (blast intro: genPrefix_trans)\n\nlemma pfixGe_antisym: \"[| x pfixGe y; y pfixGe x |] ==> x = y\"\nby (blast intro: genPrefix_antisym)\n\nlemma prefix_imp_pfixGe: \"xs<=ys ==> xs pfixGe ys\"\napply (unfold prefix_def Ge_def)\napply (blast intro: genPrefix_mono [THEN [2] rev_subsetD])\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/UNITY/ListOrder.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314828740729, "lm_q2_score": 0.8376199714402812, "lm_q1q2_score": 0.7418226173915948}}
{"text": "theory FiniteListGraph\nimports \n  FiniteGraph\n  \"../../Transitive-Closure/Transitive_Closure_List_Impl\"\nbegin\n\nsection {*Specification of a finite graph, implemented by lists*}\n\ntext{* A graph @{text \"G=(V,E)\"} consits of a list of vertices @{term V}, also called nodes, \n       and a list of edges @{term E}. The edges are tuples of vertices.\n       Using lists instead of sets, code can be easily created. *}\n\n  record 'v list_graph =\n    nodesL :: \"'v list\"\n    edgesL :: \"('v \\<times>'v) list\"\n\ntext{*Correspondence the FiniteGraph*}\n  definition list_graph_to_graph :: \"'v list_graph \\<Rightarrow> 'v graph\" where \n    \"list_graph_to_graph G = \\<lparr> nodes = set (nodesL G), edges = set (edgesL G) \\<rparr>\"\n\n\n  definition valid_list_graph_axioms :: \"'v list_graph \\<Rightarrow> bool\" where\n    \"valid_list_graph_axioms G \\<longleftrightarrow> fst` set (edgesL G) \\<subseteq> set (nodesL G) \\<and> snd` set (edgesL G) \\<subseteq> set (nodesL G)\"\n\n\n  lemma valid_list_graph_iff_valid_graph: \"valid_graph (list_graph_to_graph G) \\<longleftrightarrow> valid_list_graph_axioms G\"\n  unfolding list_graph_to_graph_def valid_graph_def valid_list_graph_axioms_def\n  by simp\n\n  text{*We say a @{typ \"'v list_graph\"} is valid if it fulfills the graph axioms and its lists are distinct*}\n  definition valid_list_graph::\"('v) list_graph \\<Rightarrow> bool\" where\n   \"valid_list_graph G = (distinct (nodesL G) \\<and> distinct (edgesL G) \\<and> valid_list_graph_axioms G)\"\n\n\nsection{*FiniteListGraph operations*}\n\n  text {* Adds a node to a graph. *}\n  definition add_node :: \"'v \\<Rightarrow> 'v list_graph \\<Rightarrow> 'v list_graph\" where \n    \"add_node v G = \\<lparr> nodesL = (if v \\<in> set (nodesL G) then nodesL G else v#nodesL G), edgesL=edgesL G \\<rparr>\"\n\n  text {* Adds an edge to a graph. *}\n  definition add_edge :: \"'v \\<Rightarrow> 'v \\<Rightarrow> 'v list_graph \\<Rightarrow> 'v list_graph\" where \n    \"add_edge v v' G = (add_node v (add_node v' G)) \\<lparr>edgesL := (if (v, v') \\<in> set (edgesL G) then edgesL G else (v, v')#edgesL G) \\<rparr>\"\n\n  text {* Deletes a node from a graph. Also deletes all adjacent edges. *}\n  definition delete_node :: \"'v \\<Rightarrow> 'v list_graph \\<Rightarrow> 'v list_graph\" where \n  \"delete_node v G = \\<lparr> \n    nodesL = remove1 v (nodesL G), edgesL = [(e1,e2) \\<leftarrow> (edgesL G). e1 \\<noteq> v \\<and> e2 \\<noteq> v]\n    \\<rparr>\"\n\n  text {* Deletes an edge from a graph. *}\n  definition delete_edge :: \"'v \\<Rightarrow> 'v \\<Rightarrow> 'v list_graph \\<Rightarrow> 'v list_graph\" where \n    \"delete_edge v v' G = \\<lparr>nodesL = nodesL G, edgesL = [(e1,e2) \\<leftarrow> edgesL G. e1 \\<noteq> v \\<or> e2 \\<noteq> v'] \\<rparr>\"\n\n  \n  fun delete_edges::\"'v list_graph \\<Rightarrow> ('v \\<times> 'v) list \\<Rightarrow> 'v list_graph\" where \n    \"delete_edges G [] = G\"|\n    \"delete_edges G ((v,v')#es) = delete_edges (delete_edge v v' G) es\"\n\n\n\ntext {* extended graph operations *}\n   text {* Reflexive transitive successors of a node. Or: All reachable nodes for v including v. *}\n    definition succ_rtran :: \"'v list_graph \\<Rightarrow> 'v \\<Rightarrow> 'v list\" where\n      \"succ_rtran G v = rtrancl_list_impl (edgesL G) [v]\"\n\n   text {* Transitive successors of a node. Or: All reachable nodes for v. *}\n    definition succ_tran :: \"'v list_graph \\<Rightarrow> 'v \\<Rightarrow> 'v list\" where\n      \"succ_tran G v = trancl_list_impl (edgesL G) [v]\"\n  \n   text {* The number of reachable nodes from v *}\n    definition num_reachable :: \"'v list_graph \\<Rightarrow> 'v \\<Rightarrow> nat\" where\n      \"num_reachable G v = length (succ_tran G v)\"\n\n\n    definition num_reachable_norefl :: \"'v list_graph \\<Rightarrow> 'v \\<Rightarrow> nat\" where\n      \"num_reachable_norefl G v = length ([ x \\<leftarrow> succ_tran G v. x \\<noteq> v])\"\n\n\nsubsection{*undirected graph simulation*}\n  text {* Create undirected graph from directed graph by adding backward links *}\n  fun backlinks :: \"('v \\<times> 'v) list \\<Rightarrow> ('v \\<times> 'v) list\" where\n    \"backlinks [] = []\" |\n    \"backlinks ((e1, e2)#es) = (e2, e1)#(backlinks es)\"\n\n  definition undirected :: \"'v list_graph \\<Rightarrow> 'v list_graph\"\n    where \"undirected G \\<equiv> \\<lparr> nodesL = nodesL G, edgesL = remdups (edgesL G @ backlinks (edgesL G)) \\<rparr>\"\n\nsection{*Correctness lemmata*}\n\n  -- \"add node\"\n  lemma add_node_valid: \"valid_list_graph G \\<Longrightarrow> valid_list_graph (add_node v G)\"\n  unfolding valid_list_graph_def valid_list_graph_axioms_def add_node_def\n  by auto\n\n  lemma add_node_set_nodes: \"set (nodesL (add_node v G)) = set (nodesL G) \\<union> {v}\"\n  unfolding add_node_def\n  by auto\n\n  lemma add_node_set_edges: \"set (edgesL (add_node v G)) = set (edgesL G)\"\n  unfolding add_node_def\n  by auto\n\n  lemma add_node_correct: \"FiniteGraph.add_node v (list_graph_to_graph G) = list_graph_to_graph (add_node v G)\"\n  unfolding FiniteGraph.add_node_def list_graph_to_graph_def\n  by (simp add: add_node_set_edges add_node_set_nodes)\n\n  lemma add_node_valid2: \"valid_graph (list_graph_to_graph G) \\<Longrightarrow> valid_graph (list_graph_to_graph (add_node v G))\"\n  by (subst add_node_correct[symmetric]) simp\n\n  -- \"add edge\"\n  lemma add_edge_valid: \"valid_list_graph G \\<Longrightarrow> valid_list_graph (add_edge v v' G)\"\n  unfolding valid_list_graph_def add_edge_def add_node_def valid_list_graph_axioms_def\n  by auto\n\n  lemma add_edge_set_nodes: \"set (nodesL (add_edge v v' G)) = set (nodesL G) \\<union> {v,v'}\"\n  unfolding add_edge_def add_node_def\n  by auto\n\n  lemma add_edge_set_edges: \"set (edgesL (add_edge v v' G)) = set (edgesL G) \\<union> {(v,v')}\"\n  unfolding add_edge_def add_node_def\n  by auto\n\n  lemma add_edge_correct: \"FiniteGraph.add_edge v v' (list_graph_to_graph G) = list_graph_to_graph (add_edge v v' G)\"\n  unfolding FiniteGraph.add_edge_def add_edge_def list_graph_to_graph_def\n  by (auto simp: add_node_set_nodes)\n\n  lemma add_edge_valid2: \"valid_graph (list_graph_to_graph G) \\<Longrightarrow> valid_graph (list_graph_to_graph (add_edge v v' G))\"\n  by (subst add_edge_correct[symmetric]) simp\n\n  -- \"delete node\"\n  lemma delete_node_valid: \"valid_list_graph G \\<Longrightarrow> valid_list_graph (delete_node v G)\"\n  unfolding valid_list_graph_def delete_node_def valid_list_graph_axioms_def\n  by auto\n\n  lemma delete_node_set_edges:\n    \"set (edgesL (delete_node v G)) = {(a,b). (a, b) \\<in> set (edgesL G) \\<and> a \\<noteq> v \\<and> b \\<noteq> v}\"\n  unfolding delete_node_def\n  by auto\n\n  lemma delete_node_correct:\n    assumes \"valid_list_graph G\"\n    shows \"FiniteGraph.delete_node v (list_graph_to_graph G) = list_graph_to_graph (delete_node v G)\"\n  using assms\n  unfolding FiniteGraph.delete_node_def delete_node_def list_graph_to_graph_def valid_list_graph_def\n  by auto\n\n  -- \"delete edge\"\n  lemma delete_edge_set_nodes: \"set (nodesL (delete_edge v v' G)) = set (nodesL G)\"\n  unfolding delete_edge_def\n  by simp\n\n  lemma delete_edge_set_edges:\n    \"set (edgesL (delete_edge v v' G)) = {(a,b). (a,b) \\<in> set (edgesL G) \\<and> (a,b) \\<noteq> (v,v')}\"\n  unfolding delete_edge_def\n  by auto\n\n  \n\n  lemma delete_edge_valid: \"valid_list_graph G \\<Longrightarrow> valid_list_graph (delete_edge v v' G)\"\n  unfolding valid_list_graph_def delete_edge_def valid_list_graph_axioms_def\n  by auto\n    \n  \n\n  lemma delete_edge_commute: \"delete_edge a1 a2 (delete_edge b1 b2 G) = delete_edge b1 b2 (delete_edge a1 a2 G)\"\n  unfolding delete_edge_def\n  by simp metis (* auto doesn't seem to like filter_cong *)\n\n  lemma delete_edge_correct: \"FiniteGraph.delete_edge v v' (list_graph_to_graph G) = list_graph_to_graph (delete_edge v v' G)\"\n  unfolding FiniteGraph.delete_edge_def delete_edge_def list_graph_to_graph_def\n  by auto\n\n  lemma delete_edge_valid2: \"valid_graph (list_graph_to_graph G) \\<Longrightarrow> valid_graph (list_graph_to_graph (delete_edge v v' G))\"\n  by (subst delete_edge_correct[symmetric]) simp\n\n  -- \"delete edges\"\n  lemma delete_edges_valid: \"valid_list_graph G \\<Longrightarrow> valid_list_graph (delete_edges G E)\"\n  by (induction E arbitrary: G) (auto simp: delete_edge_valid)\n\n  lemma delete_edges_set_nodes: \"set (nodesL (delete_edges G E)) = set (nodesL G)\"\n  by (induction E arbitrary: G) (auto simp: delete_edge_set_nodes)\n\n  lemma delete_edges_nodes: \"nodesL (delete_edges G es) = nodesL G\"\n  by (induction es arbitrary: G) (auto simp: delete_edge_def)\n\n  lemma delete_edges_set_edges: \"set (edgesL (delete_edges G E)) = set (edgesL G) - set E\"\n  by (induction E arbitrary: G) (auto simp: delete_edge_def delete_edge_set_nodes)\n\n  lemma delete_edges_set_edges2:\n    \"set (edgesL (delete_edges G E)) = {(a,b). (a,b) \\<in> set (edgesL G) \\<and> (a,b) \\<notin> set E}\"\n  by (auto simp: delete_edges_set_edges)\n\n  lemma delete_edges_length: \"length (edgesL (delete_edges G f)) \\<le> length (edgesL G)\"\n  proof (induction f arbitrary:G)\n    case (Cons f fs)\n    thus ?case\n      apply (cases f, hypsubst)\n      apply (subst delete_edges.simps(2))\n      apply (metis delete_edge_length le_trans)\n      done\n  qed simp\n\n  lemma delete_edges_chain: \"delete_edges G (as @ bs) = delete_edges (delete_edges G as) bs\"\n  proof (induction as arbitrary: bs G)\n    case (Cons f fs)\n    thus ?case\n      by (cases f) auto\n  qed simp\n\n  lemma delete_edges_delete_edge_commute:\n    \"delete_edges (delete_edge a1 a2 G) as = delete_edge a1 a2 (delete_edges G as)\"\n  proof (induction as arbitrary: G a1 a2)\n    case (Cons f fs)\n    thus ?case\n      by (cases f) (simp add: delete_edge_commute)\n  qed simp\n\n  lemma delete_edges_commute:\n    \"delete_edges (delete_edges G as) bs = delete_edges (delete_edges G bs) as\"\n  proof (induction as arbitrary: bs G)\n    case (Cons f fs)\n    thus ?case\n      by (cases f) (simp add: delete_edges_delete_edge_commute)\n  qed simp\n\n  lemma delete_edges_as_filter:\n    \"delete_edges G l = \\<lparr> nodesL = nodesL G,  edgesL = [x \\<leftarrow> edgesL G. x \\<notin> set l] \\<rparr>\"\n  proof (induction l)\n    case (Cons f fs)\n    thus ?case\n      apply (cases f)\n      apply (simp add: delete_edges_delete_edge_commute)\n      apply (simp add: delete_edge_def)\n      apply (metis (lifting, full_types) prod.exhaust splitI split_conv)\n      done\n  qed simp\n\n  declare delete_edges.simps[simp del] (*do not automatically expand definition*)\n\n  lemma delete_edges_correct:\n    \"FiniteGraph.delete_edges (list_graph_to_graph G) (set E) = list_graph_to_graph (delete_edges G E)\"\n  unfolding list_graph_to_graph_def FiniteGraph.delete_edges_def\n  by (auto simp add: delete_edges_as_filter )\n  \n  lemma delete_edges_valid2:\n    \"valid_graph (list_graph_to_graph G) \\<Longrightarrow> valid_graph (list_graph_to_graph (delete_edges G E))\"\n  by (subst delete_edges_correct[symmetric]) simp\n\n  -- \"helper about reflexive transitive closure impl\"\n  lemma distinct_relpow_impl:\n    \"distinct L \\<Longrightarrow> distinct new \\<Longrightarrow> distinct have \\<Longrightarrow> distinct (new@have) \\<Longrightarrow> \n     distinct (relpow_impl (\\<lambda>as. remdups (map snd [(a, b)\\<leftarrow>L . a \\<in> set as])) (\\<lambda>xs ys. [x\\<leftarrow>xs . x \\<notin> set ys] @ ys) (\\<lambda>x xs. x \\<in> set xs) new have M)\"\n  proof (induction M arbitrary: \"new\" \"have\")\n    case Suc\n    hence\n      \"distinct ([x\\<leftarrow>new . x \\<notin> set have] @ have)\"\n      \"set ([n\\<leftarrow>remdups (map snd [(a, b)\\<leftarrow>L . a \\<in> set new]) . (n \\<in> set new \\<longrightarrow> n \\<in> set have) \\<and> n \\<notin> set have]) \\<inter> set ([x\\<leftarrow>new . x \\<notin> set have] @ have) = {}\"\n      by auto\n\n    with Suc show ?case\n      by auto\n  qed auto\n\n  lemma distinct_rtrancl_list_impl: \"distinct L \\<Longrightarrow> distinct ls \\<Longrightarrow> distinct (rtrancl_list_impl L ls)\"\n  unfolding rtrancl_list_impl_def rtrancl_impl_def\n  by (simp add:distinct_relpow_impl)\n\n  lemma distinct_trancl_list_impl: \"distinct L \\<Longrightarrow> distinct ls \\<Longrightarrow> distinct (trancl_list_impl L ls)\"\n  unfolding trancl_list_impl_def trancl_impl_def\n  by (simp add:distinct_relpow_impl)\n\n  -- \"succ rtran\"\n  value \"succ_rtran \\<lparr> nodesL = [1::nat,2,3,4,8,9,10], edgesL = [(1,2), (2,3), (3,4), (8,9),(9,8)] \\<rparr> 1\"\n\n  lemma succ_rtran_correct: \"FiniteGraph.succ_rtran (list_graph_to_graph G) v = set (succ_rtran G v)\"\n  unfolding FiniteGraph.succ_rtran_def succ_rtran_def list_graph_to_graph_def\n  by (simp add: rtrancl_list_impl)\n\n  lemma distinct_succ_rtran: \"valid_list_graph G \\<Longrightarrow> distinct (succ_rtran G v)\"\n  unfolding succ_rtran_def valid_list_graph_def\n  by (auto intro: distinct_rtrancl_list_impl)\n\n  -- \"succ tran\"\n  lemma distinct_succ_tran: \"valid_list_graph G \\<Longrightarrow> distinct (succ_tran G v)\"\n  unfolding succ_tran_def valid_list_graph_def\n  by (auto intro: distinct_trancl_list_impl)\n\n  lemma succ_tran_set: \"set (succ_tran G v) = {e2. (v,e2) \\<in> (set (edgesL G))\\<^sup>+}\"\n  unfolding succ_tran_def\n  by (simp add: trancl_list_impl)\n\n  value \"succ_tran \\<lparr> nodesL = [1::nat,2,3,4,8,9,10], edgesL = [(1,2), (2,3), (3,4), (8,9),(9,8)] \\<rparr> 1\"\n\n  lemma succ_tran_correct: \"FiniteGraph.succ_tran (list_graph_to_graph G) v = set (succ_tran G v)\"\n  unfolding FiniteGraph.succ_tran_def succ_tran_def list_graph_to_graph_def\n  by (simp add:trancl_list_impl)\n  \n  --\"num_reachable\"\n  lemma num_reachable_correct:\n    \"valid_list_graph G \\<Longrightarrow> FiniteGraph.num_reachable (list_graph_to_graph G) v = num_reachable G v\"\n  unfolding num_reachable_def FiniteGraph.num_reachable_def\n  by (metis List.distinct_card distinct_succ_tran succ_tran_correct)\n\n  --\"num_reachable_norefl\"\n  lemma num_reachable_norefl_correct:\n    \"valid_list_graph G \\<Longrightarrow> \n     FiniteGraph.num_reachable_norefl (list_graph_to_graph G) v = num_reachable_norefl G v\"\n unfolding num_reachable_norefl_def FiniteGraph.num_reachable_norefl_def\n by (metis (full_types) List.distinct_card distinct_filter distinct_succ_tran set_minus_filter_out succ_tran_correct)\n\n  -- \"backlinks, i.e. backflows in formal def\"\n  lemma backlinks_alt: \"backlinks E = [(snd e, fst e). e \\<leftarrow> E]\"\n  by (induction E) auto\n\n  lemma backlinks_set: \"set (backlinks E) = {(e2, e1). (e1, e2) \\<in> set E}\"\n  by (induction E) auto\n\n  lemma undirected_nodes_set: \"set (edgesL (undirected G)) = set (edgesL G) \\<union> {(e2, e1). (e1, e2) \\<in> set (edgesL G)}\"\n  unfolding undirected_def\n  by (simp add: backlinks_set)\n\n  lemma undirected_succ_tran_set: \"set (succ_tran (undirected G) v) = {e2. (v,e2) \\<in> (set (edgesL (undirected G)))\\<^sup>+}\"\n  by (fact succ_tran_set)\n\n  lemma backlinks_in_nodes_G: \"\\<lbrakk> fst ` set (edgesL G) \\<subseteq> set (nodesL G); snd ` set (edgesL G) \\<subseteq> set (nodesL G) \\<rbrakk> \\<Longrightarrow> \n    fst` set (edgesL (undirected G)) \\<subseteq> set (nodesL (undirected G)) \\<and> snd` set (edgesL (undirected G)) \\<subseteq> set (nodesL (undirected G))\"\n  unfolding undirected_def\n  by(auto simp: backlinks_set)\n\n  lemma backlinks_distinct: \"distinct E \\<Longrightarrow> distinct (backlinks E)\"\n  by (induction E) (auto simp: backlinks_alt)\n\n  lemma backlinks_subset: \"set (backlinks X) \\<subseteq> set (backlinks Y) <-> set X \\<subseteq> set Y\"\n  by (auto simp: backlinks_set)\n\n  lemma backlinks_correct: \"FiniteGraph.backflows (set E) = set (backlinks E)\"\n  unfolding backflows_def\n  by(simp add: backlinks_set)\n\n  -- \"undirected\"\n  lemma undirected_valid: \"valid_list_graph G \\<Longrightarrow> valid_list_graph (undirected G)\"\n  unfolding valid_list_graph_def valid_list_graph_axioms_def\n  by (simp add:backlinks_in_nodes_G) (simp add: undirected_def)\n\n  lemma undirected_correct: \n    \"FiniteGraph.undirected (list_graph_to_graph G) = list_graph_to_graph (undirected G)\"\n  unfolding FiniteGraph.undirected_def undirected_def list_graph_to_graph_def\n  by (simp add: backlinks_set)\n      \nlemmas valid_list_graph_valid =\n  add_node_valid\n  add_edge_valid\n  delete_node_valid\n  delete_edge_valid\n  delete_edges_valid\n  undirected_valid\n\nlemmas list_graph_correct =\n  add_node_correct\n  add_edge_correct\n  delete_node_correct\n  delete_edge_correct\n  delete_edges_correct\n  succ_rtran_correct\n  succ_tran_correct\n  num_reachable_correct\n  undirected_correct\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/Network_Security_Policy_Verification/Lib/FiniteListGraph.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8856314828740728, "lm_q2_score": 0.8376199714402812, "lm_q1q2_score": 0.7418226173915947}}
{"text": "\nsection \\<open>Example: First-Order Logic\\<close>\n\ntheory %visible First_Order_Logic\nimports Base  (* FIXME Pure!? *)\nbegin\n\ntext \\<open>\n  \\noindent In order to commence a new object-logic within\n  Isabelle/Pure we introduce abstract syntactic categories @{text \"i\"}\n  for individuals and @{text \"o\"} for object-propositions.  The latter\n  is embedded into the language of Pure propositions by means of a\n  separate judgment.\n\\<close>\n\ntypedecl i\ntypedecl o\n\njudgment\n  Trueprop :: \"o \\<Rightarrow> prop\"    (\"_\" 5)\n\ntext \\<open>\n  \\noindent Note that the object-logic judgment is implicit in the\n  syntax: writing @{prop A} produces @{term \"Trueprop A\"} internally.\n  From the Pure perspective this means ``@{prop A} is derivable in the\n  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\n  principle.  Note that the latter is particularly convenient in a\n  framework like Isabelle, because syntactic congruences are\n  implicitly produced by unification of @{term \"B x\"} against\n  expressions containing occurrences of @{term x}.\n\\<close>\n\naxiomatization\n  equal :: \"i \\<Rightarrow> i \\<Rightarrow> o\"  (infix \"=\" 50)\nwhere\n  refl [intro]: \"x = x\" and\n  subst [elim]: \"x = y \\<Longrightarrow> B x \\<Longrightarrow> B y\"\n\ntext \\<open>\n  \\noindent Substitution is very powerful, but also hard to control in\n  full generality.  We derive some common symmetry~/ transitivity\n  schemes of @{term equal} as 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\n  group theory.  The subsequent locale definition postulates group\n  operations and axioms; we also derive some consequences of this\n  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  \\noindent Reasoning from basic axioms is often tedious.  Our proofs\n  work by producing various instances of the given rules (potentially\n  the symmetric form) using the pattern ``@{command have}~@{text\n  eq}~@{command \"by\"}~@{text \"(rule r)\"}'' and composing the chain of\n  results via @{command also}/@{command finally}.  These steps may\n  involve any of the transitivity rules declared in\n  \\secref{sec:framework-ex-equal}, namely @{thm trans} in combining\n  the first two results in @{thm right_inv} and in the final steps of\n  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\n  not be over-emphasized.  The other extreme is to compose a chain by\n  plain transitivity only, with replacements occurring always in\n  topmost position. 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  \\noindent Here we have re-used the built-in mechanism for unfolding\n  definitions in order to normalize each equational problem.  A more\n  realistic object-logic would include proper setup for the Simplifier\n  (\\secref{sec:simplifier}), the main automated tool for equational\n  reasoning in Isabelle.  Then ``@{command unfolding}~@{thm\n  left_inv}~@{command \"..\"}'' would become ``@{command \"by\"}~@{text\n  \"(simp only: left_inv)\"}'' 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\n  after Gentzen's system of Natural Deduction @{cite \"Gentzen:1935\"}.\n\\<close>\n\naxiomatization\n  imp :: \"o \\<Rightarrow> o \\<Rightarrow> o\"  (infixr \"\\<longrightarrow>\" 25) where\n  impI [intro]: \"(A \\<Longrightarrow> B) \\<Longrightarrow> A \\<longrightarrow> B\" and\n  impD [dest]: \"(A \\<longrightarrow> B) \\<Longrightarrow> A \\<Longrightarrow> B\"\n\naxiomatization\n  disj :: \"o \\<Rightarrow> o \\<Rightarrow> o\"  (infixr \"\\<or>\" 30) where\n  disjI\\<^sub>1 [intro]: \"A \\<Longrightarrow> A \\<or> B\" and\n  disjI\\<^sub>2 [intro]: \"B \\<Longrightarrow> A \\<or> B\" and\n  disjE [elim]: \"A \\<or> B \\<Longrightarrow> (A \\<Longrightarrow> C) \\<Longrightarrow> (B \\<Longrightarrow> C) \\<Longrightarrow> C\"\n\naxiomatization\n  conj :: \"o \\<Rightarrow> o \\<Rightarrow> o\"  (infixr \"\\<and>\" 35) where\n  conjI [intro]: \"A \\<Longrightarrow> B \\<Longrightarrow> A \\<and> B\" and\n  conjD\\<^sub>1: \"A \\<and> B \\<Longrightarrow> A\" and\n  conjD\\<^sub>2: \"A \\<and> B \\<Longrightarrow> B\"\n\ntext \\<open>\n  \\noindent The conjunctive destructions have the disadvantage that\n  decomposing @{prop \"A \\<and> B\"} involves an immediate decision which\n  component should be projected.  The more convenient simultaneous\n  elimination @{prop \"A \\<and> B \\<Longrightarrow> (A \\<Longrightarrow> B \\<Longrightarrow> C) \\<Longrightarrow> C\"} can be derived as\n  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  \\noindent Here is an example of swapping conjuncts with a single\n  intermediate elimination step:\n\\<close>\n\n(*<*)\nlemma \"\\<And>A. PROP A \\<Longrightarrow> PROP A\"\nproof -\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  \\noindent Note that the analogous elimination rule for disjunction\n  ``@{text \"\\<ASSUMES> A \\<or> B \\<OBTAINS> A \\<BBAR> B\"}'' coincides with\n  the original axiomatization of @{thm disjE}.\n\n  \\medskip We continue propositional logic by introducing absurdity\n  with its characteristic elimination.  Plain truth may then be\n  defined as a proposition that is trivially true.\n\\<close>\n\naxiomatization\n  false :: o  (\"\\<bottom>\") where\n  falseE [elim]: \"\\<bottom> \\<Longrightarrow> A\"\n\ndefinition\n  true :: o  (\"\\<top>\") where\n  \"\\<top> \\<equiv> \\<bottom> \\<longrightarrow> \\<bottom>\"\n\ntheorem trueI [intro]: \\<top>\n  unfolding true_def ..\n\ntext \\<open>\n  \\medskip\\noindent Now negation represents an implication towards\n  absurdity:\n\\<close>\n\ndefinition\n  not :: \"o \\<Rightarrow> o\"  (\"\\<not> _\" [40] 40) where\n  \"\\<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\n  local assumption.  Thus we refrain from forcing the object-logic\n  into the classical perspective.  Within that context, we may derive\n  well-known consequences of 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  \\noindent These examples illustrate both classical reasoning and\n  non-trivial propositional proofs in general.  All three rules\n  characterize classical logic independently, but the original rule is\n  already the most convenient to use, because it leaves the conclusion\n  unchanged.  Note that @{prop \"(\\<not> C \\<Longrightarrow> C) \\<Longrightarrow> C\"} fits again into our\n  format for eliminations, despite the additional twist that the\n  context refers to the main conclusion.  So we may write @{thm\n  classical} as the Isar statement ``@{text \"\\<OBTAINS> \\<not> thesis\"}''.\n  This also explains nicely how classical reasoning really works:\n  whatever the main @{text thesis} might be, we may always assume its\n  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\n  of the underlying framework.  According to the well-known technique\n  introduced by Church @{cite \"church40\"}, quantifiers are operators on\n  predicates, which are syntactically represented as @{text \"\\<lambda>\"}-terms\n  of type @{typ \"i \\<Rightarrow> o\"}.  Binder notation turns @{text \"All (\\<lambda>x. B\n  x)\"} into @{text \"\\<forall>x. B x\"} etc.\n\\<close>\n\naxiomatization\n  All :: \"(i \\<Rightarrow> o) \\<Rightarrow> o\"  (binder \"\\<forall>\" 10) where\n  allI [intro]: \"(\\<And>x. B x) \\<Longrightarrow> \\<forall>x. B x\" and\n  allD [dest]: \"(\\<forall>x. B x) \\<Longrightarrow> B a\"\n\naxiomatization\n  Ex :: \"(i \\<Rightarrow> o) \\<Rightarrow> o\"  (binder \"\\<exists>\" 10) where\n  exI [intro]: \"B a \\<Longrightarrow> (\\<exists>x. B x)\" and\n  exE [elim]: \"(\\<exists>x. B x) \\<Longrightarrow> (\\<And>x. B x \\<Longrightarrow> C) \\<Longrightarrow> C\"\n\ntext \\<open>\n  \\noindent The statement of @{thm exE} corresponds to ``@{text\n  \"\\<ASSUMES> \\<exists>x. B x \\<OBTAINS> x \\<WHERE> B x\"}'' in Isar.  In the\n  subsequent example we illustrate quantifier reasoning involving all\n  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    -- \\<open>@{text \"\\<forall>\"} introduction\\<close>\n  obtain x where \"\\<forall>y. R x y\" using \\<open>\\<exists>x. \\<forall>y. R x y\\<close> ..    -- \\<open>@{text \"\\<exists>\"} elimination\\<close>\n  fix y have \"R x y\" using \\<open>\\<forall>y. R x y\\<close> ..    -- \\<open>@{text \"\\<forall>\"} destruction\\<close>\n  then show \"\\<exists>x. R x y\" ..    -- \\<open>@{text \"\\<exists>\"} 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}\n  can now be summarized as follows, using the native Isar statement\n  format of \\secref{sec:framework-stmt}.\n\n  \\medskip\n  \\begin{tabular}{l}\n  @{text \"impI: \\<ASSUMES> A \\<Longrightarrow> B \\<SHOWS> A \\<longrightarrow> B\"} \\\\\n  @{text \"impD: \\<ASSUMES> A \\<longrightarrow> B \\<AND> A \\<SHOWS> B\"} \\\\[1ex]\n\n  @{text \"disjI\\<^sub>1: \\<ASSUMES> A \\<SHOWS> A \\<or> B\"} \\\\\n  @{text \"disjI\\<^sub>2: \\<ASSUMES> B \\<SHOWS> A \\<or> B\"} \\\\\n  @{text \"disjE: \\<ASSUMES> A \\<or> B \\<OBTAINS> A \\<BBAR> B\"} \\\\[1ex]\n\n  @{text \"conjI: \\<ASSUMES> A \\<AND> B \\<SHOWS> A \\<and> B\"} \\\\\n  @{text \"conjE: \\<ASSUMES> A \\<and> B \\<OBTAINS> A \\<AND> B\"} \\\\[1ex]\n\n  @{text \"falseE: \\<ASSUMES> \\<bottom> \\<SHOWS> A\"} \\\\\n  @{text \"trueI: \\<SHOWS> \\<top>\"} \\\\[1ex]\n\n  @{text \"notI: \\<ASSUMES> A \\<Longrightarrow> \\<bottom> \\<SHOWS> \\<not> A\"} \\\\\n  @{text \"notE: \\<ASSUMES> \\<not> A \\<AND> A \\<SHOWS> B\"} \\\\[1ex]\n\n  @{text \"allI: \\<ASSUMES> \\<And>x. B x \\<SHOWS> \\<forall>x. B x\"} \\\\\n  @{text \"allE: \\<ASSUMES> \\<forall>x. B x \\<SHOWS> B a\"} \\\\[1ex]\n\n  @{text \"exI: \\<ASSUMES> B a \\<SHOWS> \\<exists>x. B x\"} \\\\\n  @{text \"exE: \\<ASSUMES> \\<exists>x. B x \\<OBTAINS> a \\<WHERE> B a\"}\n  \\end{tabular}\n  \\medskip\n\n  \\noindent This essentially provides a declarative reading of Pure\n  rules as Isar reasoning patterns: the rule statements tells how a\n  canonical proof outline shall look like.  Since the above rules have\n  already been declared as @{attribute (Pure) intro}, @{attribute\n  (Pure) elim}, @{attribute (Pure) dest} --- each according to its\n  particular shape --- we can immediately write Isar proof texts as\n  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 sorry %noproof\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 sorry %noproof\n  then have B ..\n\n  text_raw \\<open>\\end{minipage}\\\\[3ex]\\begin{minipage}[t]{0.4\\textwidth}\\<close>(*<*)next(*>*)\n\n  have A sorry %noproof\n  then have \"A \\<or> B\" ..\n\n  have B sorry %noproof\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\" sorry %noproof\n  then have C\n  proof\n    assume A\n    then show C sorry %noproof\n  next\n    assume B\n    then show C sorry %noproof\n  qed\n\n  text_raw \\<open>\\end{minipage}\\\\[3ex]\\begin{minipage}[t]{0.4\\textwidth}\\<close>(*<*)next(*>*)\n\n  have A and B sorry %noproof\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\" sorry %noproof\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>\" sorry %noproof\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>\" sorry %noproof\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 sorry %noproof\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\" sorry %noproof\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\" sorry %noproof\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\" sorry %noproof\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\" sorry %noproof\n  then obtain a where \"B a\" ..\n\n  text_raw \\<open>\\end{minipage}\\<close>\n\n(*<*)\nqed\n(*>*)\n\ntext \\<open>\n  \\bigskip\\noindent Of course, these proofs are merely examples.  As\n  sketched in \\secref{sec:framework-subproof}, there is a fair amount\n  of flexibility in expressing Pure deductions in Isar.  Here the user\n  is asked to express himself adequately, aiming at proof texts of\n  literary quality.\n\\<close>\n\nend %visible\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/Doc/Isar_Ref/First_Order_Logic.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8856314738181875, "lm_q2_score": 0.8376199694135332, "lm_q1q2_score": 0.7418226080112525}}
{"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{*\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\ntext{*\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(* your definition/proof here *)\n\nfun ord :: \"int tree \\<Rightarrow> bool\"  where\n(* your definition/proof here *)\n\ntext{* 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(* your definition/proof here *)\n\ntext{* Prove correctness of @{const ins}: *}\n\nlemma set_ins: \"set(ins x t) = {x} \\<union> set t\"\n(* your definition/proof here *)\n\ntheorem ord_ins: \"ord t \\<Longrightarrow> ord(ins i t)\"\n(* your definition/proof here *)\n\ntext{*\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\ninductive palindrome :: \"'a list \\<Rightarrow> bool\" where\n(* your definition/proof here *)\n\ntext {* and prove *}\n\nlemma \"palindrome xs \\<Longrightarrow> rev xs = xs\"\n(* your definition/proof here *)\n\ntext{*\n\\endexercise\n\n\\exercise\nWe could also have defined @{const star} as follows:\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\ntext{*\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(* your definition/proof here *)\n\n\n\nlemma \"star r x y \\<Longrightarrow> star' r x y\"\n(* your definition/proof here *)\n\ntext{*\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*}\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\ntext{*\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\ntext{*\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\ntext{*\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\ntext{*\n\\endexercise\n*}\n(* your definition/proof here *)\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(* 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": "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/Chapter4.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8376199552262967, "lm_q2_score": 0.8856314723088733, "lm_q1q2_score": 0.7418225941823577}}
{"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 MainRLT\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": "dtraytel", "repo": "HOLRLT", "sha": "e9029da59bb3af0c835604a65308498f9696a364", "save_path": "github-repos/isabelle/dtraytel-HOLRLT", "path": "github-repos/isabelle/dtraytel-HOLRLT/HOLRLT-e9029da59bb3af0c835604a65308498f9696a364/HOLRLT/Isar_Examples/Expr_Compiler.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199511728004, "lm_q2_score": 0.885631470799559, "lm_q1q2_score": 0.741822589328222}}
{"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\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 $-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\n\nend\n", "meta": {"author": "helli", "repo": "field-extensions", "sha": "e3f3ab110355827caebc2b195843fcd7b2eb0dbd", "save_path": "github-repos/isabelle/helli-field-extensions", "path": "github-repos/isabelle/helli-field-extensions/field-extensions-e3f3ab110355827caebc2b195843fcd7b2eb0dbd/VectorSpace_by_HoldenLee/RingModuleFacts.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894604912848, "lm_q2_score": 0.8289388125473628, "lm_q1q2_score": 0.741725712859541}}
{"text": "theory Exercise2\n  imports Main\nbegin\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)\n\" (is \"?EVEN \\<or> ?ODD\")\nproof cases\n  assume \"2 dvd (length xs)\"\n  then obtain k\n    where even_xs: \"length xs = 2*k\"\n    by auto\n  then obtain ys zs\n    where ys_def: \"ys = take k xs\"\n      and zs_def: \"zs = drop k xs\"\n    by simp\n  hence xs_part: \"xs = ys @ zs\" by simp\n  have \"length zs = k\"\n    using even_xs zs_def\n    by simp\n  hence ?EVEN using xs_part even_xs by auto\n  thus ?thesis by simp\nnext\n  assume \"\\<not> (2 dvd (length xs))\"\n  hence \"\\<exists>k. length xs = (2*k) + 1\" by arith\n  then obtain k\n    where odd_xs: \"length xs = (2*k) + 1\"\n    by auto\n  then obtain ys zs\n    where ys_def: \"ys = take (k+1) xs\"\n      and zs_def: \"zs = drop (k+1) xs\"\n    by simp\n  hence xs_part: \"xs = ys @ zs\" by simp\n  hence \"length zs = k\"\n    using odd_xs zs_def\n    by simp\n  hence ?ODD using xs_part odd_xs by auto\n  thus ?thesis by simp\nqed\n\nend\n", "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/ch5/Exercise2.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505351008906, "lm_q2_score": 0.8198933425148214, "lm_q1q2_score": 0.7417169510316909}}
{"text": "theory MyList\nimports Main\nbegin\n\ndatatype 'a list = Nil | Cons 'a \" 'a list \"\n\nfun app :: \" 'a list \\<Rightarrow> 'a list \\<Rightarrow> 'a list \" \n  where \"app Nil x = x\" | \"app (Cons x xs) y = Cons x (app xs y) \"\n\nfun rev :: \" 'a list \\<Rightarrow> 'a list \"\n  where \"rev Nil = Nil\" | \"rev (Cons x xs) = app (rev xs) (Cons x Nil) \"\n\nlemma app_Nil2[simp] : \"app xs Nil = xs\"\n  apply(induction xs)\n  apply(auto)\ndone\n\nlemma app_assoc[simp] : \"app (app xs ys) zs = app xs (app ys zs)\"\n  apply(induction xs)\n  apply(auto)\ndone\n\nlemma rev_app_rev[simp] : \"rev (app xs ys) = app (rev ys) (rev xs)\"\n  apply(induction xs)\n  apply(auto)\ndone\n\n\ntheorem rev_rev [simp] : \"rev (rev xs) = xs\"\n  apply(induction xs)\n  apply(auto)\ndone\n\nend\n\n\n\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/MyList.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505248181417, "lm_q2_score": 0.8198933315126792, "lm_q1q2_score": 0.7417169326478399}}
{"text": "(*  Title:      HOL/Library/Ramsey.thy\n    Author:     Tom Ridge.  Converted to structured Isar by L C Paulson\n*)\n\nsection \"Ramsey's Theorem\"\n\ntheory Ramsey\nimports Main Infinite_Set\nbegin\n\nsubsection\\<open>Finite Ramsey theorem(s)\\<close>\n\ntext\\<open>To distinguish the finite and infinite ones, lower and upper case\nnames are used.\n\nThis is the most basic version in terms of cliques and independent\nsets, i.e. the version for graphs and 2 colours.\\<close>\n\ndefinition \"clique V E = (\\<forall>v\\<in>V. \\<forall>w\\<in>V. v\\<noteq>w \\<longrightarrow> {v,w} : E)\"\ndefinition \"indep V E = (\\<forall>v\\<in>V. \\<forall>w\\<in>V. v\\<noteq>w \\<longrightarrow> \\<not> {v,w} : E)\"\n\nlemma ramsey2:\n  \"\\<exists>r\\<ge>1. \\<forall> (V::'a set) (E::'a set set). finite V \\<and> card V \\<ge> r \\<longrightarrow>\n  (\\<exists> R \\<subseteq> V. card R = m \\<and> clique R E \\<or> card R = n \\<and> indep R E)\"\n  (is \"\\<exists>r\\<ge>1. ?R m n r\")\nproof(induct k == \"m+n\" arbitrary: m n)\n  case 0\n  show ?case (is \"EX r. ?R r\")\n  proof\n    show \"?R 1\" using 0\n      by (clarsimp simp: indep_def)(metis card.empty emptyE empty_subsetI)\n  qed\nnext\n  case (Suc k)\n  { assume \"m=0\"\n    have ?case (is \"EX r. ?R r\")\n    proof\n      show \"?R 1\" using \\<open>m=0\\<close>\n        by (simp add:clique_def)(metis card.empty emptyE empty_subsetI)\n    qed\n  } moreover\n  { assume \"n=0\"\n    have ?case (is \"EX r. ?R r\")\n    proof\n      show \"?R 1\" using \\<open>n=0\\<close>\n        by (simp add:indep_def)(metis card.empty emptyE empty_subsetI)\n    qed\n  } moreover\n  { assume \"m\\<noteq>0\" \"n\\<noteq>0\"\n    then have \"k = (m - 1) + n\" \"k = m + (n - 1)\" using \\<open>Suc k = m+n\\<close> by auto\n    from Suc(1)[OF this(1)] Suc(1)[OF this(2)]\n    obtain r1 r2 where \"r1\\<ge>1\" \"r2\\<ge>1\" \"?R (m - 1) n r1\" \"?R m (n - 1) r2\"\n      by auto\n    then have \"r1+r2 \\<ge> 1\" by arith\n    moreover\n    have \"?R m n (r1+r2)\" (is \"ALL V E. _ \\<longrightarrow> ?EX V E m n\")\n    proof clarify\n      fix V :: \"'a set\" and E :: \"'a set set\"\n      assume \"finite V\" \"r1+r2 \\<le> card V\"\n      with \\<open>r1\\<ge>1\\<close> have \"V \\<noteq> {}\" by auto\n      then obtain v where \"v : V\" by blast\n      let ?M = \"{w : V. w\\<noteq>v & {v,w} : E}\"\n      let ?N = \"{w : V. w\\<noteq>v & {v,w} ~: E}\"\n      have \"V = insert v (?M \\<union> ?N)\" using \\<open>v : V\\<close> by auto\n      then have \"card V = card(insert v (?M \\<union> ?N))\" by metis\n      also have \"\\<dots> = card ?M + card ?N + 1\" using \\<open>finite V\\<close>\n        by(fastforce intro: card_Un_disjoint)\n      finally have \"card V = card ?M + card ?N + 1\" .\n      then have \"r1+r2 \\<le> card ?M + card ?N + 1\" using \\<open>r1+r2 \\<le> card V\\<close> by simp\n      then have \"r1 \\<le> card ?M \\<or> r2 \\<le> card ?N\" by arith\n      moreover\n      { assume \"r1 \\<le> card ?M\"\n        moreover have \"finite ?M\" using \\<open>finite V\\<close> by auto\n        ultimately have \"?EX ?M E (m - 1) n\" using \\<open>?R (m - 1) n r1\\<close> by blast\n        then obtain R where \"R \\<subseteq> ?M\" \"v ~: R\" and\n          CI: \"card R = m - 1 \\<and> clique R E \\<or>\n               card R = n \\<and> indep R E\" (is \"?C \\<or> ?I\")\n          by blast\n        have \"R <= V\" using \\<open>R <= ?M\\<close> by auto\n        have \"finite R\" using \\<open>finite V\\<close> \\<open>R \\<subseteq> V\\<close> by (metis finite_subset)\n        { assume \"?I\"\n          with \\<open>R <= V\\<close> have \"?EX V E m n\" by blast\n        } moreover\n        { assume \"?C\"\n          then have \"clique (insert v R) E\" using \\<open>R <= ?M\\<close>\n           by(auto simp:clique_def insert_commute)\n          moreover have \"card(insert v R) = m\"\n            using \\<open>?C\\<close> \\<open>finite R\\<close> \\<open>v ~: R\\<close> \\<open>m\\<noteq>0\\<close> by simp\n          ultimately have \"?EX V E m n\" using \\<open>R <= V\\<close> \\<open>v : V\\<close> by (metis insert_subset)\n        } ultimately have \"?EX V E m n\" using CI by blast\n      } moreover\n      { assume \"r2 \\<le> card ?N\"\n        moreover have \"finite ?N\" using \\<open>finite V\\<close> by auto\n        ultimately have \"?EX ?N E m (n - 1)\" using \\<open>?R m (n - 1) r2\\<close> by blast\n        then obtain R where \"R \\<subseteq> ?N\" \"v ~: R\" and\n          CI: \"card R = m \\<and> clique R E \\<or>\n               card R = n - 1 \\<and> indep R E\" (is \"?C \\<or> ?I\")\n          by blast\n        have \"R <= V\" using \\<open>R <= ?N\\<close> by auto\n        have \"finite R\" using \\<open>finite V\\<close> \\<open>R \\<subseteq> V\\<close> by (metis finite_subset)\n        { assume \"?C\"\n          with \\<open>R <= V\\<close> have \"?EX V E m n\" by blast\n        } moreover\n        { assume \"?I\"\n          then have \"indep (insert v R) E\" using \\<open>R <= ?N\\<close>\n            by(auto simp:indep_def insert_commute)\n          moreover have \"card(insert v R) = n\"\n            using \\<open>?I\\<close> \\<open>finite R\\<close> \\<open>v ~: R\\<close> \\<open>n\\<noteq>0\\<close> by simp\n          ultimately have \"?EX V E m n\" using \\<open>R <= V\\<close> \\<open>v : V\\<close> by (metis insert_subset)\n        } ultimately have \"?EX V E m n\" using CI by blast\n      } ultimately show \"?EX V E m n\" by blast\n    qed\n    ultimately have ?case by blast\n  } ultimately show ?case by blast\nqed\n\n\nsubsection \\<open>Preliminaries\\<close>\n\nsubsubsection \\<open>``Axiom'' of Dependent Choice\\<close>\n\nprimrec choice :: \"('a => bool) => ('a * 'a) set => nat => 'a\" where\n  \\<comment>\\<open>An integer-indexed chain of choices\\<close>\n    choice_0:   \"choice P r 0 = (SOME x. P x)\"\n  | choice_Suc: \"choice P r (Suc n) = (SOME y. P y & (choice P r n, y) \\<in> r)\"\n\nlemma choice_n:\n  assumes P0: \"P x0\"\n      and Pstep: \"!!x. P x ==> \\<exists>y. P y & (x,y) \\<in> r\"\n  shows \"P (choice P r n)\"\nproof (induct n)\n  case 0 show ?case by (force intro: someI P0)\nnext\n  case Suc then show ?case by (auto intro: someI2_ex [OF Pstep])\nqed\n\nlemma dependent_choice:\n  assumes trans: \"trans r\"\n      and P0: \"P x0\"\n      and Pstep: \"!!x. P x ==> \\<exists>y. P y & (x,y) \\<in> r\"\n  obtains f :: \"nat => 'a\" where\n    \"!!n. P (f n)\" and \"!!n m. n < m ==> (f n, f m) \\<in> r\"\nproof\n  fix n\n  show \"P (choice P r n)\" by (blast intro: choice_n [OF P0 Pstep])\nnext\n  have PSuc: \"\\<forall>n. (choice P r n, choice P r (Suc n)) \\<in> r\"\n    using Pstep [OF choice_n [OF P0 Pstep]]\n    by (auto intro: someI2_ex)\n  fix n m :: nat\n  assume less: \"n < m\"\n  show \"(choice P r n, choice P r m) \\<in> r\" using PSuc\n    by (auto intro: less_Suc_induct [OF less] transD [OF trans])\nqed\n\n\nsubsubsection \\<open>Partitions of a Set\\<close>\n\ndefinition part :: \"nat => nat => 'a set => ('a set => nat) => bool\"\n  \\<comment>\\<open>the function @{term f} partitions the @{term r}-subsets of the typically\n       infinite set @{term Y} into @{term s} distinct categories.\\<close>\nwhere\n  \"part r s Y f = (\\<forall>X. X \\<subseteq> Y & finite X & card X = r --> f X < s)\"\n\ntext\\<open>For induction, we decrease the value of @{term r} in partitions.\\<close>\nlemma part_Suc_imp_part:\n     \"[| infinite Y; part (Suc r) s Y f; y \\<in> Y |]\n      ==> part r s (Y - {y}) (%u. f (insert y u))\"\n  apply(simp add: part_def, clarify)\n  apply(drule_tac x=\"insert y X\" in spec)\n  apply(force)\n  done\n\nlemma part_subset: \"part r s YY f ==> Y \\<subseteq> YY ==> part r s Y f\"\n  unfolding part_def by blast\n\n\nsubsection \\<open>Ramsey's Theorem: Infinitary Version\\<close>\n\nlemma Ramsey_induction:\n  fixes s and r::nat\n  shows\n  \"!!(YY::'a set) (f::'a set => nat).\n      [|infinite YY; part r s YY f|]\n      ==> \\<exists>Y' t'. Y' \\<subseteq> YY & infinite Y' & t' < s &\n                  (\\<forall>X. X \\<subseteq> Y' & finite X & card X = r --> f X = t')\"\nproof (induct r)\n  case 0\n  then show ?case by (auto simp add: part_def card_eq_0_iff cong: conj_cong)\nnext\n  case (Suc r)\n  show ?case\n  proof -\n    from Suc.prems infinite_imp_nonempty obtain yy where yy: \"yy \\<in> YY\" by blast\n    let ?ramr = \"{((y,Y,t),(y',Y',t')). y' \\<in> Y & Y' \\<subseteq> Y}\"\n    let ?propr = \"%(y,Y,t).\n                 y \\<in> YY & y \\<notin> Y & Y \\<subseteq> YY & infinite Y & t < s\n                 & (\\<forall>X. X\\<subseteq>Y & finite X & card X = r --> (f o insert y) X = t)\"\n    have infYY': \"infinite (YY-{yy})\" using Suc.prems by auto\n    have partf': \"part r s (YY - {yy}) (f \\<circ> insert yy)\"\n      by (simp add: o_def part_Suc_imp_part yy Suc.prems)\n    have transr: \"trans ?ramr\" by (force simp add: trans_def)\n    from Suc.hyps [OF infYY' partf']\n    obtain Y0 and t0\n    where \"Y0 \\<subseteq> YY - {yy}\"  \"infinite Y0\"  \"t0 < s\"\n          \"\\<forall>X. X\\<subseteq>Y0 \\<and> finite X \\<and> card X = r \\<longrightarrow> (f \\<circ> insert yy) X = t0\"\n        by blast\n    with yy have propr0: \"?propr(yy,Y0,t0)\" by blast\n    have proprstep: \"\\<And>x. ?propr x \\<Longrightarrow> \\<exists>y. ?propr y \\<and> (x, y) \\<in> ?ramr\"\n    proof -\n      fix x\n      assume px: \"?propr x\" then show \"?thesis x\"\n      proof (cases x)\n        case (fields yx Yx tx)\n        then obtain yx' where yx': \"yx' \\<in> Yx\" using px\n               by (blast dest: infinite_imp_nonempty)\n        have infYx': \"infinite (Yx-{yx'})\" using fields px by auto\n        with fields px yx' Suc.prems\n        have partfx': \"part r s (Yx - {yx'}) (f \\<circ> insert yx')\"\n          by (simp add: o_def part_Suc_imp_part part_subset [where YY=YY and Y=Yx])\n        from Suc.hyps [OF infYx' partfx']\n        obtain Y' and t'\n        where Y': \"Y' \\<subseteq> Yx - {yx'}\"  \"infinite Y'\"  \"t' < s\"\n               \"\\<forall>X. X\\<subseteq>Y' \\<and> finite X \\<and> card X = r \\<longrightarrow> (f \\<circ> insert yx') X = t'\"\n            by blast\n        show ?thesis\n        proof\n          show \"?propr (yx',Y',t') & (x, (yx',Y',t')) \\<in> ?ramr\"\n            using fields Y' yx' px by blast\n        qed\n      qed\n    qed\n    from dependent_choice [OF transr propr0 proprstep]\n    obtain g where pg: \"?propr (g n)\" and rg: \"n<m ==> (g n, g m) \\<in> ?ramr\" for n m :: nat\n      by blast\n    let ?gy = \"fst o g\"\n    let ?gt = \"snd o snd o g\"\n    have rangeg: \"\\<exists>k. range ?gt \\<subseteq> {..<k}\"\n    proof (intro exI subsetI)\n      fix x\n      assume \"x \\<in> range ?gt\"\n      then obtain n where \"x = ?gt n\" ..\n      with pg [of n] show \"x \\<in> {..<s}\" by (cases \"g n\") auto\n    qed\n    have \"finite (range ?gt)\"\n      by (simp add: finite_nat_iff_bounded rangeg)\n    then obtain s' and n'\n      where s': \"s' = ?gt n'\"\n        and infeqs': \"infinite {n. ?gt n = s'}\"\n      by (rule inf_img_fin_domE) (auto simp add: vimage_def intro: infinite_UNIV_nat)\n    with pg [of n'] have less': \"s'<s\" by (cases \"g n'\") auto\n    have inj_gy: \"inj ?gy\"\n    proof (rule linorder_injI)\n      fix m m' :: nat assume less: \"m < m'\" show \"?gy m \\<noteq> ?gy m'\"\n        using rg [OF less] pg [of m] by (cases \"g m\", cases \"g m'\") auto\n    qed\n    show ?thesis\n    proof (intro exI conjI)\n      show \"?gy ` {n. ?gt n = s'} \\<subseteq> YY\" using pg\n        by (auto simp add: Let_def split_beta)\n      show \"infinite (?gy ` {n. ?gt n = s'})\" using infeqs'\n        by (blast intro: inj_gy [THEN subset_inj_on] dest: finite_imageD)\n      show \"s' < s\" by (rule less')\n      show \"\\<forall>X. X \\<subseteq> ?gy ` {n. ?gt n = s'} & finite X & card X = Suc r\n          --> f X = s'\"\n      proof -\n        {fix X\n         assume \"X \\<subseteq> ?gy ` {n. ?gt n = s'}\"\n            and cardX: \"finite X\" \"card X = Suc r\"\n         then obtain AA where AA: \"AA \\<subseteq> {n. ?gt n = s'}\" and Xeq: \"X = ?gy`AA\"\n             by (auto simp add: subset_image_iff)\n         with cardX have \"AA\\<noteq>{}\" by auto\n         then have AAleast: \"(LEAST x. x \\<in> AA) \\<in> AA\" by (auto intro: LeastI_ex)\n         have \"f X = s'\"\n         proof (cases \"g (LEAST x. x \\<in> AA)\")\n           case (fields ya Ya ta)\n           with AAleast Xeq\n           have ya: \"ya \\<in> X\" by (force intro!: rev_image_eqI)\n           then have \"f X = f (insert ya (X - {ya}))\" by (simp add: insert_absorb)\n           also have \"... = ta\"\n           proof -\n             have \"X - {ya} \\<subseteq> Ya\"\n             proof\n               fix x assume x: \"x \\<in> X - {ya}\"\n               then obtain a' where xeq: \"x = ?gy a'\" and a': \"a' \\<in> AA\"\n                 by (auto simp add: Xeq)\n               then have \"a' \\<noteq> (LEAST x. x \\<in> AA)\" using x fields by auto\n               then have lessa': \"(LEAST x. x \\<in> AA) < a'\"\n                 using Least_le [of \"%x. x \\<in> AA\", OF a'] by arith\n               show \"x \\<in> Ya\" using xeq fields rg [OF lessa'] by auto\n             qed\n             moreover\n             have \"card (X - {ya}) = r\"\n               by (simp add: cardX ya)\n             ultimately show ?thesis\n               using pg [of \"LEAST x. x \\<in> AA\"] fields cardX\n               by (clarsimp simp del:insert_Diff_single)\n           qed\n           also have \"... = s'\" using AA AAleast fields by auto\n           finally show ?thesis .\n         qed}\n        then show ?thesis by blast\n      qed\n    qed\n  qed\nqed\n\n\ntheorem Ramsey:\n  fixes s r :: nat and Z::\"'a set\" and f::\"'a set => nat\"\n  shows\n   \"[|infinite Z;\n      \\<forall>X. X \\<subseteq> Z & finite X & card X = r --> f X < s|]\n  ==> \\<exists>Y t. Y \\<subseteq> Z & infinite Y & t < s\n            & (\\<forall>X. X \\<subseteq> Y & finite X & card X = r --> f X = t)\"\nby (blast intro: Ramsey_induction [unfolded part_def])\n\n\ncorollary Ramsey2:\n  fixes s::nat and Z::\"'a set\" and f::\"'a set => nat\"\n  assumes infZ: \"infinite Z\"\n      and part: \"\\<forall>x\\<in>Z. \\<forall>y\\<in>Z. x\\<noteq>y --> f{x,y} < s\"\n  shows\n   \"\\<exists>Y t. Y \\<subseteq> Z & infinite Y & t < s & (\\<forall>x\\<in>Y. \\<forall>y\\<in>Y. x\\<noteq>y --> f{x,y} = t)\"\nproof -\n  have part2: \"\\<forall>X. X \\<subseteq> Z & finite X & card X = 2 --> f X < s\"\n    using part by (fastforce simp add: eval_nat_numeral card_Suc_eq)\n  obtain Y t\n    where *: \"Y \\<subseteq> Z\" \"infinite Y\" \"t < s\"\n          \"(\\<forall>X. X \\<subseteq> Y & finite X & card X = 2 --> f X = t)\"\n    by (insert Ramsey [OF infZ part2]) auto\n  then have \"\\<forall>x\\<in>Y. \\<forall>y\\<in>Y. x \\<noteq> y \\<longrightarrow> f {x, y} = t\" by auto\n  with * show ?thesis by iprover\nqed\n\n\nsubsection \\<open>Disjunctive Well-Foundedness\\<close>\n\ntext \\<open>\n  An application of Ramsey's theorem to program termination. See\n  @{cite \"Podelski-Rybalchenko\"}.\n\\<close>\n\ndefinition disj_wf :: \"('a * 'a)set => bool\"\n  where \"disj_wf r = (\\<exists>T. \\<exists>n::nat. (\\<forall>i<n. wf(T i)) & r = (\\<Union>i<n. T i))\"\n\ndefinition transition_idx :: \"[nat => 'a, nat => ('a*'a)set, nat set] => nat\"\n  where\n    \"transition_idx s T A =\n      (LEAST k. \\<exists>i j. A = {i,j} & i<j & (s j, s i) \\<in> T k)\"\n\n\nlemma transition_idx_less:\n    \"[|i<j; (s j, s i) \\<in> T k; k<n|] ==> transition_idx s T {i,j} < n\"\napply (subgoal_tac \"transition_idx s T {i, j} \\<le> k\", simp)\napply (simp add: transition_idx_def, blast intro: Least_le)\ndone\n\nlemma transition_idx_in:\n    \"[|i<j; (s j, s i) \\<in> T k|] ==> (s j, s i) \\<in> T (transition_idx s T {i,j})\"\napply (simp add: transition_idx_def doubleton_eq_iff conj_disj_distribR\n            cong: conj_cong)\napply (erule LeastI)\ndone\n\ntext\\<open>To be equal to the union of some well-founded relations is equivalent\nto being the subset of such a union.\\<close>\nlemma disj_wf:\n     \"disj_wf(r) = (\\<exists>T. \\<exists>n::nat. (\\<forall>i<n. wf(T i)) & r \\<subseteq> (\\<Union>i<n. T i))\"\napply (auto simp add: disj_wf_def)\napply (rule_tac x=\"%i. T i Int r\" in exI)\napply (rule_tac x=n in exI)\napply (force simp add: wf_Int1)\ndone\n\ntheorem trans_disj_wf_implies_wf:\n  assumes transr: \"trans r\"\n      and dwf:    \"disj_wf(r)\"\n  shows \"wf r\"\nproof (simp only: wf_iff_no_infinite_down_chain, rule notI)\n  assume \"\\<exists>s. \\<forall>i. (s (Suc i), s i) \\<in> r\"\n  then obtain s where sSuc: \"\\<forall>i. (s (Suc i), s i) \\<in> r\" ..\n  have s: \"!!i j. i < j ==> (s j, s i) \\<in> r\"\n  proof -\n    fix i and j::nat\n    assume less: \"i<j\"\n    then show \"(s j, s i) \\<in> r\"\n    proof (rule less_Suc_induct)\n      show \"\\<And>i. (s (Suc i), s i) \\<in> r\" by (simp add: sSuc)\n      show \"\\<And>i j k. \\<lbrakk>(s j, s i) \\<in> r; (s k, s j) \\<in> r\\<rbrakk> \\<Longrightarrow> (s k, s i) \\<in> r\"\n        using transr by (unfold trans_def, blast)\n    qed\n  qed\n  from dwf\n  obtain T and n::nat where wfT: \"\\<forall>k<n. wf(T k)\" and r: \"r = (\\<Union>k<n. T k)\"\n    by (auto simp add: disj_wf_def)\n  have s_in_T: \"\\<And>i j. i<j ==> \\<exists>k. (s j, s i) \\<in> T k & k<n\"\n  proof -\n    fix i and j::nat\n    assume less: \"i<j\"\n    then have \"(s j, s i) \\<in> r\" by (rule s [of i j])\n    then show \"\\<exists>k. (s j, s i) \\<in> T k & k<n\" by (auto simp add: r)\n  qed\n  have trless: \"!!i j. i\\<noteq>j ==> transition_idx s T {i,j} < n\"\n    apply (auto simp add: linorder_neq_iff)\n    apply (blast dest: s_in_T transition_idx_less)\n    apply (subst insert_commute)\n    apply (blast dest: s_in_T transition_idx_less)\n    done\n  have\n   \"\\<exists>K k. K \\<subseteq> UNIV & infinite K & k < n &\n          (\\<forall>i\\<in>K. \\<forall>j\\<in>K. i\\<noteq>j --> transition_idx s T {i,j} = k)\"\n    by (rule Ramsey2) (auto intro: trless infinite_UNIV_nat)\n  then obtain K and k\n    where infK: \"infinite K\" and less: \"k < n\" and\n          allk: \"\\<forall>i\\<in>K. \\<forall>j\\<in>K. i\\<noteq>j --> transition_idx s T {i,j} = k\"\n    by auto\n  have \"\\<forall>m. (s (enumerate K (Suc m)), s(enumerate K m)) \\<in> T k\"\n  proof\n    fix m::nat\n    let ?j = \"enumerate K (Suc m)\"\n    let ?i = \"enumerate K m\"\n    have jK: \"?j \\<in> K\" by (simp add: enumerate_in_set infK)\n    have iK: \"?i \\<in> K\" by (simp add: enumerate_in_set infK)\n    have ij: \"?i < ?j\" by (simp add: enumerate_step infK)\n    have ijk: \"transition_idx s T {?i,?j} = k\" using iK jK ij\n      by (simp add: allk)\n    obtain k' where \"(s ?j, s ?i) \\<in> T k'\" \"k'<n\"\n      using s_in_T [OF ij] by blast\n    then show \"(s ?j, s ?i) \\<in> T k\"\n      by (simp add: ijk [symmetric] transition_idx_in ij)\n  qed\n  then have \"~ wf(T k)\" by (force simp add: wf_iff_no_infinite_down_chain)\n  then show False using wfT less 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/Library/Ramsey.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528019683106, "lm_q2_score": 0.8705972818382005, "lm_q1q2_score": 0.74170779364805}}
{"text": "(*\nAuthors: \n  Hanna Lachnitt, TU Wien, lachnitt@student.tuwien.ac.at\n  Anthony Bordg, University of Cambridge, apdb3@cam.ac.uk\n*)\n                                                                                  \ntheory Deutsch_Jozsa\nimports\n  Deutsch\n  More_Tensor\n  Binary_Nat\nbegin\n\n\nsection \\<open>The Deutsch-Jozsa Algorithm\\<close>\n\ntext \\<open>\nGiven a function $f:{0,1}^n \\mapsto {0,1}$, the Deutsch-Jozsa algorithm decides if this function is \nconstant or balanced with a single $f(x)$ circuit to evaluate the function for multiple values of $x$ \nsimultaneously. The algorithm makes use of quantum parallelism and quantum interference.\n\\<close>\n\nsubsection \\<open>Input function\\<close>\n\ntext \\<open>\nA constant function with values in {0,1} returns either always 0 or always 1. \nA balanced function is 0 for half of the inputs and 1 for the other half. \n\\<close>\n\nlocale bob_fun =\n  fixes f:: \"nat \\<Rightarrow> nat\" and n:: \"nat\"\n  assumes dom: \"f \\<in> ({(i::nat). i < 2^n} \\<rightarrow>\\<^sub>E {0,1})\"\n  assumes dim: \"n \\<ge> 1\"\n\ncontext bob_fun\nbegin\n\ndefinition const:: \"nat \\<Rightarrow> bool\" where \n\"const c = (\\<forall>x\\<in>{i::nat. i<2^n}. f x = c)\"\n\ndefinition is_const:: bool where \n\"is_const \\<equiv> const 0 \\<or> const 1\"\n\ndefinition is_balanced:: bool where\n\"is_balanced \\<equiv> \\<exists>A B ::nat set. A \\<subseteq> {i::nat. i < 2^n} \\<and> B \\<subseteq> {i::nat. i < 2^n}\n                   \\<and> card A = 2^(n-1) \\<and> card B = 2^(n-1)  \n                   \\<and> (\\<forall>x\\<in>A. f x = 0)  \\<and> (\\<forall>x\\<in>B. f x = 1)\"\n\nlemma is_balanced_inter: \n  fixes A B:: \"nat set\"\n  assumes \"\\<forall>x \\<in> A. f x = 0\" and \"\\<forall>x \\<in> B. f x = 1\" \n  shows \"A \\<inter> B = {}\" \n  using assms by auto\n\nlemma is_balanced_union:\n  fixes A B:: \"nat set\"\n  assumes \"A \\<subseteq> {i::nat. i < 2^n}\" and \"B \\<subseteq> {i::nat. i < 2^n}\" \n      and \"card A = 2^(n-1)\" and \"card B = 2^(n-1)\" \n      and \"A \\<inter> B = {}\"\n  shows \"A \\<union> B = {i::nat. i < 2^n}\"\nproof-\n  have \"finite A\" and \"finite B\" \n    apply (simp add: assms(3) card_ge_0_finite)\n    apply (simp add: assms(4) card_ge_0_finite).\n  then have \"card(A \\<union> B) = 2 * 2^(n-1)\" \n    using assms(3-5) by (simp add: card_Un_disjoint)\n  then have \"card(A \\<union> B) = 2^n\"\n    by (metis Nat.nat.simps(3) One_nat_def dim le_0_eq power_eq_if)\n  moreover have \"\\<dots> = card({i::nat. i < 2^n})\" by simp\n  moreover have \"A \\<union> B \\<subseteq> {i::nat. i < 2^n}\" \n    using assms(1,2) by simp\n  moreover have \"finite ({i::nat. i < 2^n})\" by simp\n  ultimately show ?thesis \n    using card_subset_eq[of \"{i::nat. i < 2^n}\" \"A \\<union> B\"] by simp\nqed\n\nlemma f_ge_0: \"\\<forall>x. f x \\<ge> 0\" by simp\n\nlemma f_dom_not_zero: \n  shows \"f \\<in> ({i::nat. n \\<ge> 1 \\<and> i < 2^n} \\<rightarrow>\\<^sub>E {0,1})\" \n  using dim dom by simp\n\nlemma f_values: \"\\<forall>x \\<in> {(i::nat). i < 2^n} . f x = 0 \\<or> f x = 1\" \n  using dom by auto\n\nend (* bob_fun *)\n\ntext \\<open>The input function has to be constant or balanced.\\<close>\n\nlocale jozsa = bob_fun +\n  assumes const_or_balanced: \"is_const \\<or> is_balanced \"\n\ntext \\<open>\nIntroduce two customised rules: disjunctions with four disjuncts and induction starting from one \ninstead of zero.\n\\<close>\n\n(* To deal with Uf it is often necessary to do a case distinction with four different cases.*)\nlemma disj_four_cases:\n  assumes \"A \\<or> B \\<or> C \\<or> D\" and \"A \\<Longrightarrow> P\" and \"B \\<Longrightarrow> P\" and \"C \\<Longrightarrow> P\" and \"D \\<Longrightarrow> P\"\n  shows \"P\" \n  using assms by auto\n\ntext \\<open>The unitary transform @{term U\\<^sub>f}.\\<close>\n\ndefinition (in jozsa) jozsa_transform:: \"complex Matrix.mat\" (\"U\\<^sub>f\") where \n\"U\\<^sub>f \\<equiv> Matrix.mat (2^(n+1)) (2^(n+1)) (\\<lambda>(i,j). \n  if i = j then (1-f(i div 2)) else \n    if i = j + 1 \\<and> odd i then f(i div 2) else\n      if i = j - 1 \\<and> even i \\<and> j\\<ge>1 then f(i div 2) else 0)\"\n\nlemma (in jozsa) jozsa_transform_dim [simp]:\n  shows \"dim_row U\\<^sub>f = 2^(n+1)\" and \"dim_col U\\<^sub>f = 2^(n+1)\" \n  by (auto simp add: jozsa_transform_def)\n\nlemma (in jozsa) jozsa_transform_coeff_is_zero [simp]:\n  assumes \"i < dim_row U\\<^sub>f \\<and> j < dim_col U\\<^sub>f\"\n  shows \"(i\\<noteq>j \\<and> \\<not>(i=j+1 \\<and> odd i) \\<and> \\<not> (i=j-1 \\<and> even i \\<and> j\\<ge>1)) \\<longrightarrow> U\\<^sub>f $$ (i,j) = 0\"\n  using jozsa_transform_def assms by auto\n\nlemma (in jozsa) jozsa_transform_coeff [simp]: \n  assumes \"i < dim_row U\\<^sub>f \\<and> j < dim_col U\\<^sub>f\"\n  shows \"i = j \\<longrightarrow> U\\<^sub>f $$ (i,j) = 1 - f (i div 2)\"\n  and \"i = j + 1 \\<and> odd i \\<longrightarrow> U\\<^sub>f $$ (i,j) = f (i div 2)\"\n  and \"j \\<ge> 1 \\<and> i = j - 1 \\<and> even i \\<longrightarrow> U\\<^sub>f $$ (i,j) = f (i div 2)\" \n  using jozsa_transform_def assms by auto\n\nlemma (in jozsa) U\\<^sub>f_mult_without_empty_summands_sum_even:\n  fixes i j A\n  assumes \"i < dim_row U\\<^sub>f\" and \"j < dim_col A\" and \"even i\" and \"dim_col U\\<^sub>f = dim_row A\"\n  shows \"(\\<Sum>k\\<in>{0..< dim_row A}. U\\<^sub>f $$ (i,k) * A $$ (k,j)) =(\\<Sum>k\\<in>{i,i+1}. U\\<^sub>f $$ (i,k) * A $$ (k,j))\"\nproof-\n  have \"(\\<Sum>k \\<in> {0..< 2^(n+1)}. U\\<^sub>f $$ (i,k) * A $$ (k,j)) = \n             (\\<Sum>k \\<in> {0..<i}. U\\<^sub>f $$ (i,k) * A $$ (k,j)) +\n             (\\<Sum>k \\<in> {i,i+1}. U\\<^sub>f $$ (i,k) * A $$ (k,j)) +\n             (\\<Sum>k \\<in> {(i+2)..< 2^(n+1)}. U\\<^sub>f $$ (i,k) * A $$ (k,j))\" \n  proof- \n    have \"{0..< 2^(n+1)} = {0..<i} \\<union> {i..< 2^(n+1)} \n          \\<and> {i..< 2^(n+1)} = {i,i+1} \\<union> {(i+2)..<2^(n+1)}\" using assms(1-3) by auto\n    moreover have \"{0..<i} \\<inter> {i,i+1} = {} \n                  \\<and> {i,i+1} \\<inter> {(i+2)..< 2^(n+1)} = {} \n                  \\<and> {0..<i} \\<inter> {(i+2)..< 2^(n+1)} = {}\" using assms by simp\n    ultimately show ?thesis\n      using sum.union_disjoint\n      by (metis (no_types, lifting) finite_Un finite_atLeastLessThan is_num_normalize(1) ivl_disj_int_two(3))\n  qed\n  moreover have \"(\\<Sum>k \\<in> {0..<i}. U\\<^sub>f $$ (i,k) * A $$ (k,j)) = 0\" \n  proof-\n    have \"k \\<in> {0..<i} \\<longrightarrow> (i\\<noteq>k \\<and> \\<not>(i=k+1 \\<and> odd i) \\<and> \\<not> (i=k-1 \\<and> even i \\<and> k\\<ge>1))\" for k \n      using assms by auto\n    then have \"k \\<in> {0..<i} \\<longrightarrow> U\\<^sub>f $$ (i,k) = 0\" for k\n      using assms(1) by auto\n    then show ?thesis by simp\n  qed\n  moreover have \"(\\<Sum>k \\<in> {(i+2)..< 2^(n+1)}. U\\<^sub>f $$ (i,k) * A $$ (k,j)) = 0\" \n  proof- \n    have \"k\\<in>{(i+2)..< 2^(n+1)} \\<longrightarrow> (i\\<noteq>k \\<and> \\<not>(i=k+1 \\<and> odd i) \\<and> \\<not> (i=k-1 \\<and> even i \\<and> k\\<ge>1))\" for k by auto\n    then have \"k \\<in> {(i+2)..< 2^(n+1)}\\<longrightarrow> U\\<^sub>f $$ (i,k) = 0\" for k\n      using assms(1) by auto\n    then show ?thesis by simp\n  qed\n  moreover have  \"dim_row A = 2^(n+1)\" using assms(4) by simp\n  ultimately show \"?thesis\" by(metis (no_types, lifting) add.left_neutral add.right_neutral)\nqed\n\nlemma (in jozsa) U\\<^sub>f_mult_without_empty_summands_even: \n  fixes i j A\n  assumes \"i < dim_row U\\<^sub>f\" and \"j < dim_col A\" and \"even i\" and \"dim_col U\\<^sub>f = dim_row A\"\n  shows \"(U\\<^sub>f * A) $$ (i,j) = (\\<Sum>k \\<in> {i,i+1}. U\\<^sub>f $$ (i,k) * A $$ (k,j))\"\nproof-\n  have \"(U\\<^sub>f * A) $$ (i,j) = (\\<Sum> k\\<in>{0..< dim_row A}. (U\\<^sub>f $$ (i,k)) * (A $$ (k,j)))\"\n    using assms(1,2,4) index_matrix_prod by (simp add: atLeast0LessThan)\n  then show ?thesis\n    using assms U\\<^sub>f_mult_without_empty_summands_sum_even by simp\nqed\n\nlemma (in jozsa) U\\<^sub>f_mult_without_empty_summands_sum_odd:\n  fixes i j A\n  assumes \"i < dim_row U\\<^sub>f\" and \"j < dim_col A\" and \"odd i\" and \"dim_col U\\<^sub>f = dim_row A\"\n  shows \"(\\<Sum>k\\<in>{0..< dim_row A}. U\\<^sub>f $$ (i,k) * A $$ (k,j)) =(\\<Sum>k\\<in>{i-1,i}. U\\<^sub>f $$ (i,k) * A $$ (k,j))\"\nproof-\n  have \"(\\<Sum>k\\<in>{0..< 2^(n+1)}. U\\<^sub>f $$ (i,k) * A $$ (k,j)) = \n             (\\<Sum>k \\<in> {0..<i-1}. U\\<^sub>f $$ (i,k) * A $$ (k,j)) +\n             (\\<Sum>k \\<in> {i-1,i}. U\\<^sub>f $$ (i,k) * A $$ (k,j)) +\n             (\\<Sum>k \\<in> {i+1..< 2^(n+1)}. U\\<^sub>f $$ (i,k) * A $$ (k,j))\" \n  proof- \n    have \"{0..< 2^(n+1)} = {0..<i-1} \\<union> {i-1..< 2^(n+1)} \n          \\<and> {i-1..< 2^(n+1)} = {i-1,i} \\<union> {i+1..<2^(n+1)}\" using assms(1-3) by auto\n    moreover have \"{0..<i-1} \\<inter> {i-1,i} = {} \n                  \\<and> {i-1,i} \\<inter> {i+1..< 2^(n+1)} = {} \n                  \\<and> {0..<i-1} \\<inter> {i+1..< 2^(n+1)} = {}\" using assms by simp\n    ultimately show ?thesis\n      using sum.union_disjoint \n      by(metis (no_types, lifting) finite_Un finite_atLeastLessThan is_num_normalize(1) ivl_disj_int_two(3))\n  qed\n  moreover have \"(\\<Sum>k \\<in> {0..<i-1}. U\\<^sub>f $$ (i,k) * A $$ (k,j)) = 0\"\n  proof-\n    have \"k \\<in> {0..<i-1} \\<longrightarrow> (i\\<noteq>k \\<and> \\<not>(i=k+1 \\<and> odd i) \\<and> \\<not> (i=k-1 \\<and> even i \\<and> k\\<ge>1))\" for k by auto\n    then have \"k \\<in> {0..<i-1} \\<longrightarrow> U\\<^sub>f $$ (i,k) = 0\" for k\n      using assms(1) by auto\n    then show ?thesis by simp\n  qed\n  moreover have \"(\\<Sum>k \\<in> {i+1..< 2^(n+1)}. U\\<^sub>f $$ (i,k) * A $$ (k,j)) = 0\" \n    using assms(3) by auto \n  moreover have  \"dim_row A = 2^(n+1)\" using assms(4) by simp\n  ultimately show \"?thesis\" by(metis (no_types, lifting) add.left_neutral add.right_neutral)\nqed\n\nlemma (in jozsa) U\\<^sub>f_mult_without_empty_summands_odd: \n  fixes i j A\n  assumes \"i < dim_row U\\<^sub>f\" and \"j < dim_col A\" and \"odd i\" and \"dim_col U\\<^sub>f = dim_row A\"\n  shows \"(U\\<^sub>f * A) $$ (i,j) = (\\<Sum>k \\<in> {i-1,i}. U\\<^sub>f $$ (i,k) * A $$ (k,j)) \"\nproof-\n  have \"(U\\<^sub>f * A) $$ (i,j) = (\\<Sum>k \\<in> {0 ..< dim_row A}. (U\\<^sub>f $$ (i,k)) * (A $$ (k,j)))\"\n    using assms(1,2,4) index_matrix_prod by (simp add: atLeast0LessThan)\n  then show \"?thesis\" \n    using assms U\\<^sub>f_mult_without_empty_summands_sum_odd by auto\nqed\n\ntext \\<open>@{term U\\<^sub>f} is a gate.\\<close>\n\nlemma (in jozsa) transpose_of_jozsa_transform:\n  shows \"(U\\<^sub>f)\\<^sup>t = U\\<^sub>f\"\nproof\n  show \"dim_row (U\\<^sub>f\\<^sup>t) = dim_row U\\<^sub>f\" by simp\nnext\n  show \"dim_col (U\\<^sub>f\\<^sup>t) = dim_col U\\<^sub>f\" by simp\nnext\n  fix i j:: nat\n  assume a0: \"i < dim_row U\\<^sub>f\" and a1: \"j < dim_col U\\<^sub>f\"\n  then show \"U\\<^sub>f\\<^sup>t $$ (i, j) = U\\<^sub>f $$ (i, j)\" \n  proof (induct rule: disj_four_cases)\n    show \"i=j \\<or> (i=j+1 \\<and> odd i) \\<or> (i=j-1 \\<and> even i \\<and> j\\<ge>1) \\<or> (i\\<noteq>j \\<and> \\<not>(i=j+1 \\<and> odd i) \\<and> \\<not> (i=j-1 \\<and> even i \\<and> j\\<ge>1))\" \n      by linarith\n  next\n    assume \"i = j\"\n    then show \"U\\<^sub>f\\<^sup>t $$ (i,j) = U\\<^sub>f $$ (i,j)\" using a0 by simp\n  next\n    assume \"(i=j+1 \\<and> odd i)\"\n    then show \"U\\<^sub>f\\<^sup>t $$ (i,j) = U\\<^sub>f $$ (i,j)\" using transpose_mat_def a0 a1 by auto\n  next\n    assume a2:\"(i=j-1 \\<and> even i \\<and> j\\<ge>1)\"\n    then have \"U\\<^sub>f $$ (i,j) = f (i div 2)\" \n      using a0 a1 jozsa_transform_coeff by auto\n    moreover have \"U\\<^sub>f $$ (j,i) = f (i div 2)\" \n      using a0 a1 a2 jozsa_transform_coeff\n      by (metis add_diff_assoc2 diff_add_inverse2 even_plus_one_iff even_succ_div_two jozsa_transform_dim)\n    ultimately show \"?thesis\"\n      using transpose_mat_def a0 a1 by simp\n  next \n    assume a2:\"(i\\<noteq>j \\<and> \\<not>(i=j+1 \\<and> odd i) \\<and> \\<not> (i=j-1 \\<and> even i \\<and> j\\<ge>1))\"\n    then have \"(j\\<noteq>i \\<and> \\<not>(j=i+1 \\<and> odd j) \\<and> \\<not> (j=i-1 \\<and> even j \\<and> i\\<ge>1))\" \n      by (metis le_imp_diff_is_add diff_add_inverse even_plus_one_iff le_add1)\n    then have \"U\\<^sub>f $$ (j,i) = 0\" \n      using jozsa_transform_coeff_is_zero a0 a1 by auto\n    moreover have \"U\\<^sub>f $$ (i,j) = 0\" \n      using jozsa_transform_coeff_is_zero a0 a1 a2 by auto\n    ultimately show \"U\\<^sub>f\\<^sup>t $$ (i,j) = U\\<^sub>f $$ (i,j)\"\n      using transpose_mat_def a0 a1 by simp\n  qed \nqed\n\nlemma (in jozsa) adjoint_of_jozsa_transform: \n  shows \"(U\\<^sub>f)\\<^sup>\\<dagger> = U\\<^sub>f\"\nproof\n  show \"dim_row (U\\<^sub>f\\<^sup>\\<dagger>) = dim_row U\\<^sub>f\" by simp\nnext\n  show \"dim_col (U\\<^sub>f\\<^sup>\\<dagger>) = dim_col U\\<^sub>f\" by simp\nnext\n  fix i j:: nat\n  assume a0: \"i < dim_row U\\<^sub>f\" and a1: \"j < dim_col U\\<^sub>f\"\n  then show \"U\\<^sub>f\\<^sup>\\<dagger> $$ (i,j) = U\\<^sub>f $$ (i,j)\"\n  proof (induct rule: disj_four_cases)\n  show \"i=j \\<or> (i=j+1 \\<and> odd i) \\<or> (i=j-1 \\<and> even i \\<and> j\\<ge>1) \\<or> (i\\<noteq>j \\<and> \\<not>(i=j+1 \\<and> odd i) \\<and> \\<not> (i=j-1 \\<and> even i \\<and> j\\<ge>1))\"\n    by linarith\n  next\n    assume \"i=j\"\n    then show \"U\\<^sub>f\\<^sup>\\<dagger> $$ (i,j) = U\\<^sub>f $$ (i,j)\" using a0 dagger_def by simp\n  next\n    assume \"(i=j+1 \\<and> odd i)\"\n    then show \"U\\<^sub>f\\<^sup>\\<dagger> $$ (i,j) = U\\<^sub>f $$ (i,j)\" using a0 dagger_def by auto\n  next\n    assume a2:\"(i=j-1 \\<and> even i \\<and> j\\<ge>1)\"\n    then have \"U\\<^sub>f $$ (i,j) = f (i div 2)\" \n      using a0 a1 jozsa_transform_coeff by auto\n    moreover have \"U\\<^sub>f\\<^sup>\\<dagger>  $$ (j,i) = f (i div 2)\" \n      using a1 a2 jozsa_transform_coeff dagger_def by auto\n    ultimately show \"U\\<^sub>f\\<^sup>\\<dagger> $$ (i,j) = U\\<^sub>f $$ (i,j)\"\n      by(metis a0 a1 cnj_transpose_is_dagger dim_row_of_dagger index_transpose_mat dagger_of_transpose_is_cnj transpose_of_jozsa_transform)\n  next \n    assume a2: \"(i\\<noteq>j \\<and> \\<not>(i=j+1 \\<and> odd i) \\<and> \\<not> (i=j-1 \\<and> even i \\<and> j\\<ge>1))\"\n    then have f0:\"(i\\<noteq>j \\<and> \\<not>(j=i+1 \\<and> odd j) \\<and> \\<not> (j=i-1 \\<and> even j \\<and> i\\<ge>1))\" \n      by (metis le_imp_diff_is_add diff_add_inverse even_plus_one_iff le_add1)\n    then have \"U\\<^sub>f $$ (j,i) = 0\" and \"cnj 0 = 0\"\n      using jozsa_transform_coeff_is_zero a0 a1 a2 by auto\n    then have \"U\\<^sub>f\\<^sup>\\<dagger> $$ (i,j) = 0\" \n      using a0 a1 dagger_def by simp\n    then show \"U\\<^sub>f\\<^sup>\\<dagger> $$ (i, j) = U\\<^sub>f $$ (i, j)\" \n      using a0 a1 a2 jozsa_transform_coeff_is_zero by auto\n  qed \nqed\n\nlemma (in jozsa) jozsa_transform_is_unitary_index_even:\n  fixes i j:: nat\n  assumes \"i < dim_row U\\<^sub>f\" and \"j < dim_col U\\<^sub>f\" and \"even i\"\n  shows \"(U\\<^sub>f * U\\<^sub>f) $$ (i,j) = 1\\<^sub>m (dim_col U\\<^sub>f) $$ (i,j)\"\nproof-\n  have \"(U\\<^sub>f * U\\<^sub>f) $$ (i,j) = (\\<Sum>k \\<in> {i,i+1}. U\\<^sub>f $$ (i,k) * U\\<^sub>f $$ (k,j)) \" \n    using U\\<^sub>f_mult_without_empty_summands_even[of i j U\\<^sub>f ] assms by simp\n  moreover have \"U\\<^sub>f $$ (i,i) * U\\<^sub>f $$ (i,j) = (1-f(i div 2)) * U\\<^sub>f $$ (i,j)\"\n    using assms(1,3) by simp\n  moreover have f0: \"U\\<^sub>f $$ (i,i+1) * U\\<^sub>f $$ (i+1,j) = f(i div 2) * U\\<^sub>f $$ (i+1,j)\"\n    by (metis One_nat_def Suc_leI add.right_neutral add_Suc_right assms(1) assms(3) diff_add_inverse2 \neven_add even_mult_iff jozsa_transform_coeff(3) jozsa_transform_dim le_add2 le_eq_less_or_eq odd_one \none_add_one power.simps(2))\n  ultimately have f1: \"(U\\<^sub>f * U\\<^sub>f) $$ (i,j) = (1-f(i div 2)) * U\\<^sub>f $$ (i,j) +  f(i div 2) * U\\<^sub>f $$ (i+1,j)\" by auto\n  thus ?thesis\n  proof (induct rule: disj_four_cases)\n    show \"j=i \\<or> (j=i+1 \\<and> odd j) \\<or> (j=i-1 \\<and> even j \\<and> i\\<ge>1) \\<or> (j\\<noteq>i \\<and> \\<not>(j=i+1 \\<and> odd j) \\<and> \\<not> (j=i-1 \\<and> even j \\<and> i\\<ge>1))\"\n      by linarith\n  next\n    assume a0:\"j=i\"\n    then have \"U\\<^sub>f $$ (i,j) = (1-f(i div 2))\" \n      using assms(1,2) a0 by simp\n    moreover have \"U\\<^sub>f $$ (i+1,j) = f(i div 2)\"\n      using assms(1,3) a0 by auto\n    ultimately have \"(U\\<^sub>f * U\\<^sub>f) $$ (i,j) = (1-f(i div 2)) * (1-f(i div 2)) +  f(i div 2) * f(i div 2)\" \n      using f1 by simp\n    moreover have \"(1-f(i div 2)) * (1-f(i div 2)) + f(i div 2) * f(i div 2) = 1\" \n      using f_values assms(1)\n      by (metis (no_types, lifting) Nat.minus_nat.diff_0 diff_add_0 diff_add_inverse jozsa_transform_dim(1) \n          less_power_add_imp_div_less mem_Collect_eq mult_eq_if one_power2 power2_eq_square power_one_right) \n    ultimately show \"(U\\<^sub>f * U\\<^sub>f) $$ (i,j) = 1\\<^sub>m (dim_col U\\<^sub>f) $$ (i,j)\"  by(metis assms(2) a0 index_one_mat(1) of_nat_1)\n  next\n    assume a0: \"(j=i+1 \\<and> odd j)\"\n    then have \"U\\<^sub>f $$ (i,j) = f(i div 2)\" \n      using assms(1,2) a0 by simp\n    moreover have \"U\\<^sub>f $$ (i+1,j) = (1-f(i div 2))\"\n      using assms(2,3) a0 by simp\n    ultimately have \"(U\\<^sub>f * U\\<^sub>f) $$ (i,j) = (1-f(i div 2)) * f(i div 2) + f(i div 2) * (1-f(i div 2))\"\n      using f0 f1 assms by simp\n    then show \"(U\\<^sub>f * U\\<^sub>f) $$ (i,j) = 1\\<^sub>m (dim_col U\\<^sub>f) $$ (i,j)\" \n      using assms(1,2) a0 by auto\n  next\n    assume \"(j=i-1 \\<and> even j \\<and> i\\<ge>1)\"\n    then show \"(U\\<^sub>f * U\\<^sub>f) $$ (i,j) = 1\\<^sub>m (dim_col U\\<^sub>f) $$ (i,j)\" \n      using assms(3) dvd_diffD1 odd_one by blast\n  next \n    assume a0:\"(j\\<noteq>i \\<and> \\<not>(j=i+1 \\<and> odd j) \\<and> \\<not> (j=i-1 \\<and> even j \\<and> i\\<ge>1))\"\n    then have \"U\\<^sub>f $$ (i,j) = 0\" \n      using assms(1,2) by(metis index_transpose_mat(1) jozsa_transform_coeff_is_zero jozsa_transform_dim transpose_of_jozsa_transform)\n    moreover have \"U\\<^sub>f $$ (i+1,j) = 0\" \n      using assms a0 by auto\n    ultimately have \"(U\\<^sub>f * U\\<^sub>f) $$ (i,j) = (1-f(i div 2)) * 0 +  f(i div 2) * 0\" \n      by (simp add: f1)\n    then show \"(U\\<^sub>f * U\\<^sub>f) $$ (i,j) = 1\\<^sub>m (dim_col U\\<^sub>f) $$ (i,j)\" \n      using a0 assms(1,2) by(metis add.left_neutral index_one_mat(1) jozsa_transform_dim mult_0_right of_nat_0)\n  qed\nqed\n\nlemma (in jozsa) jozsa_transform_is_unitary_index_odd:\n  fixes i j:: nat\n  assumes \"i < dim_row U\\<^sub>f\" and \"j < dim_col U\\<^sub>f\" and \"odd i\"\n  shows \"(U\\<^sub>f * U\\<^sub>f) $$ (i,j) = 1\\<^sub>m (dim_col U\\<^sub>f) $$ (i,j)\"\nproof-\n  have f0: \"i \\<ge> 1\"  \n    using linorder_not_less assms(3) by auto\n  have \"(U\\<^sub>f * U\\<^sub>f) $$ (i,j) = (\\<Sum>k \\<in> {i-1,i}. U\\<^sub>f $$ (i,k) * U\\<^sub>f $$ (k,j)) \" \n    using U\\<^sub>f_mult_without_empty_summands_odd[of i j U\\<^sub>f ] assms by simp\n  moreover have \"(\\<Sum>k \\<in> {i-1,i}. U\\<^sub>f $$ (i,k) * U\\<^sub>f $$ (k,j)) \n                 = U\\<^sub>f $$ (i,i-1) * U\\<^sub>f $$ (i-1,j) +  U\\<^sub>f $$ (i,i) * U\\<^sub>f $$ (i,j)\"\n    using f0 by simp\n  moreover have \"U\\<^sub>f $$ (i,i) * U\\<^sub>f $$ (i,j) = (1-f(i div 2)) * U\\<^sub>f $$ (i,j)\" \n    using assms(1,2) by simp\n  moreover have f1: \"U\\<^sub>f $$ (i,i-1) * U\\<^sub>f $$ (i-1,j) = f(i div 2) * U\\<^sub>f $$ (i-1,j)\" \n    using assms(1) assms(3) by simp\n  ultimately have f2: \"(U\\<^sub>f * U\\<^sub>f) $$ (i,j) = f(i div 2) * U\\<^sub>f $$ (i-1,j) + (1-f(i div 2)) * U\\<^sub>f $$ (i,j)\" by simp\n  then show \"?thesis\"\n  proof (induct rule: disj_four_cases)\n    show \"j=i \\<or> (j=i+1 \\<and> odd j) \\<or> (j=i-1 \\<and> even j \\<and> i\\<ge>1) \\<or> (j\\<noteq>i \\<and> \\<not>(j=i+1 \\<and> odd j) \\<and> \\<not> (j=i-1 \\<and> even j \\<and> i\\<ge>1))\"\n      by linarith\n  next\n    assume a0:\"j=i\"\n    then have \"U\\<^sub>f $$ (i,j) = (1-f(i div 2))\"\n      using assms(1,2) by simp\n    moreover have \"U\\<^sub>f $$ (i-1,j) = f(i div 2)\"\n      using a0 assms\n      by (metis index_transpose_mat(1) jozsa_transform_coeff(2) less_imp_diff_less odd_two_times_div_two_nat \n          odd_two_times_div_two_succ transpose_of_jozsa_transform)\n    ultimately have \"(U\\<^sub>f * U\\<^sub>f) $$ (i,j) = f(i div 2) * f(i div 2) + (1-f(i div 2)) * (1-f(i div 2))\"\n      using f2 by simp\n    moreover have \"f(i div 2) * f(i div 2) + (1-f(i div 2)) * (1-f(i div 2)) = 1\" \n      using f_values assms(1)\n      by (metis (no_types, lifting) Nat.minus_nat.diff_0 diff_add_0 diff_add_inverse jozsa_transform_dim(1) \n          less_power_add_imp_div_less mem_Collect_eq mult_eq_if one_power2 power2_eq_square power_one_right) \n    ultimately show \"(U\\<^sub>f * U\\<^sub>f) $$ (i,j) = 1\\<^sub>m (dim_col U\\<^sub>f) $$ (i,j)\" by(metis assms(2) a0 index_one_mat(1) of_nat_1)\n  next\n    assume a0:\"(j=i+1 \\<and> odd j)\"\n    then show \"(U\\<^sub>f * U\\<^sub>f) $$ (i,j) = 1\\<^sub>m (dim_col U\\<^sub>f) $$ (i,j)\" \n      using assms(3) dvd_diffD1 odd_one even_plus_one_iff by blast\n  next\n    assume a0:\"(j=i-1 \\<and> even j \\<and> i\\<ge>1)\"\n    then have \"(U\\<^sub>f * U\\<^sub>f) $$ (i,j) = f(i div 2) * (1-f(i div 2)) + (1-f(i div 2)) * f(i div 2)\" \n      using f0 f1 f2 assms\n      by (metis jozsa_transform_coeff(1) Groups.ab_semigroup_mult_class.mult.commute even_succ_div_two f2 \n          jozsa_transform_dim odd_two_times_div_two_nat odd_two_times_div_two_succ of_nat_add of_nat_mult)\n    then show \"(U\\<^sub>f * U\\<^sub>f) $$ (i,j) = 1\\<^sub>m (dim_col U\\<^sub>f) $$ (i,j)\" \n      using assms(1) a0 by auto\n  next \n    assume a0:\"j\\<noteq>i \\<and> \\<not>(j=i+1 \\<and> odd j) \\<and> \\<not> (j=i-1 \\<and> even j \\<and> i\\<ge>1)\"\n    then have \"U\\<^sub>f $$ (i,j) = 0\" \n      by (metis assms(1,2) index_transpose_mat(1) jozsa_transform_coeff_is_zero jozsa_transform_dim transpose_of_jozsa_transform)\n    moreover have \"U\\<^sub>f $$ (i-1,j) = 0\" \n      using assms a0 f0 apply auto\n      by (smt One_nat_def Suc_n_not_le_n add_diff_inverse_nat assms(1) assms(2) diff_Suc_less even_add \njozsa_transform_coeff_is_zero jozsa_axioms less_imp_le less_le_trans less_one odd_one)\n    ultimately have \"(U\\<^sub>f * U\\<^sub>f) $$ (i,j) = (1-f(i div 2)) * 0 +  f(i div 2) * 0\" \n      using f2 by simp\n    then show \"(U\\<^sub>f * U\\<^sub>f) $$ (i,j) = 1\\<^sub>m (dim_col U\\<^sub>f) $$ (i,j)\" \n      using a0 assms by (metis add.left_neutral index_one_mat(1) jozsa_transform_dim mult_0_right of_nat_0)\n  qed\nqed\n\nlemma (in jozsa) jozsa_transform_is_gate:\n  shows \"gate (n+1) U\\<^sub>f\"\nproof\n  show \"dim_row U\\<^sub>f = 2^(n+1)\" by simp\nnext\n  show \"square_mat U\\<^sub>f\" by simp\nnext\n  show \"unitary U\\<^sub>f\"\n  proof-\n    have \"U\\<^sub>f * U\\<^sub>f = 1\\<^sub>m (dim_col U\\<^sub>f)\"\n    proof\n      show \"dim_row (U\\<^sub>f * U\\<^sub>f) = dim_row (1\\<^sub>m (dim_col U\\<^sub>f))\" by simp\n    next\n      show \"dim_col (U\\<^sub>f * U\\<^sub>f) = dim_col (1\\<^sub>m (dim_col U\\<^sub>f))\" by simp\n    next\n      fix i j:: nat\n      assume \"i < dim_row (1\\<^sub>m (dim_col U\\<^sub>f))\" and \"j < dim_col (1\\<^sub>m (dim_col U\\<^sub>f))\"\n      then have \"i < dim_row U\\<^sub>f\" and \"j < dim_col U\\<^sub>f\" by auto\n      then show \"(U\\<^sub>f * U\\<^sub>f) $$ (i,j) = 1\\<^sub>m (dim_col U\\<^sub>f) $$ (i,j)\" \n        using jozsa_transform_is_unitary_index_odd jozsa_transform_is_unitary_index_even by blast\n    qed\n    thus ?thesis by (simp add: adjoint_of_jozsa_transform unitary_def)\n  qed\nqed\n\ntext \\<open>N-fold application of the tensor product\\<close>\n\nfun iter_tensor:: \"complex Matrix.mat \\<Rightarrow> nat \\<Rightarrow> complex Matrix.mat\" (\"_ \\<otimes>\\<^bsup>_\\<^esup>\" 75)  where\n  \"A \\<otimes>\\<^bsup>(Suc 0)\\<^esup> = A\"  \n| \"A \\<otimes>\\<^bsup>(Suc k)\\<^esup> = A \\<Otimes> (A \\<otimes>\\<^bsup>k\\<^esup>)\"\n\nlemma one_tensor_is_id [simp]:\n  fixes A\n  shows \"A \\<otimes>\\<^bsup>1\\<^esup> = A\"\n  using one_mat_def by simp\n\nlemma iter_tensor_suc: \n  fixes n\n  assumes \"n \\<ge> 1\"\n  shows \" A \\<otimes>\\<^bsup>(Suc n)\\<^esup> = A \\<Otimes> (A \\<otimes>\\<^bsup>n\\<^esup>)\" \n  using assms by (metis Deutsch_Jozsa.iter_tensor.simps(2) One_nat_def Suc_le_D)\n\nlemma dim_row_of_iter_tensor [simp]:\n  fixes A n\n  assumes \"n \\<ge> 1\"\n  shows \"dim_row(A \\<otimes>\\<^bsup>n\\<^esup>) = (dim_row A)^n\"\n  using assms\nproof (rule nat_induct_at_least)\n  show \"dim_row (A \\<otimes>\\<^bsup>1\\<^esup>) = (dim_row A)^1\"\n    using one_tensor_is_id by simp\nnext\n  fix n:: nat\n  assume \"n \\<ge> 1\" and \"dim_row (A \\<otimes>\\<^bsup>n\\<^esup>) = (dim_row A)^n\"\n  then show \"dim_row (A \\<otimes>\\<^bsup>Suc n\\<^esup>) = (dim_row A)^Suc n\"\n    using iter_tensor_suc assms dim_row_tensor_mat by simp\nqed\n\nlemma dim_col_of_iter_tensor [simp]:\n  fixes A n\n  assumes \"n \\<ge> 1\"\n  shows \"dim_col(A \\<otimes>\\<^bsup>n\\<^esup>) = (dim_col A)^n\"\n  using assms\nproof (rule nat_induct_at_least)\n  show \"dim_col (A \\<otimes>\\<^bsup>1\\<^esup>) = (dim_col A)^1\"\n    using one_tensor_is_id by simp\nnext\n  fix n:: nat\n  assume \"n \\<ge> 1\" and \"dim_col (A \\<otimes>\\<^bsup>n\\<^esup>) = (dim_col A)^n\"\n  then show \"dim_col (A \\<otimes>\\<^bsup>Suc n\\<^esup>) = (dim_col A)^Suc n\"\n    using iter_tensor_suc assms dim_col_tensor_mat by simp\nqed\n\nlemma iter_tensor_values:\n  fixes A n i j\n  assumes \"n \\<ge> 1\" and \"i < dim_row (A \\<Otimes> (A \\<otimes>\\<^bsup>n\\<^esup>))\" and \"j < dim_col (A \\<Otimes> (A \\<otimes>\\<^bsup>n\\<^esup>))\"\n  shows \"(A \\<otimes>\\<^bsup>(Suc n)\\<^esup>) $$ (i,j) = (A \\<Otimes> (A \\<otimes>\\<^bsup>n\\<^esup>)) $$ (i,j)\"\n  using assms by (metis One_nat_def le_0_eq not0_implies_Suc iter_tensor.simps(2))\n\nlemma iter_tensor_mult_distr:\n  assumes \"n \\<ge> 1\" and \"dim_col A = dim_row B\" and \"dim_col A > 0\" and \"dim_col B > 0\"\n  shows \"(A \\<otimes>\\<^bsup>(Suc n)\\<^esup>) * (B \\<otimes>\\<^bsup>(Suc n)\\<^esup>) = (A * B) \\<Otimes> ((A \\<otimes>\\<^bsup>n\\<^esup>) * (B \\<otimes>\\<^bsup>n\\<^esup>))\" \nproof-\n  have \"(A \\<otimes>\\<^bsup>(Suc n)\\<^esup>) * (B \\<otimes>\\<^bsup>(Suc n)\\<^esup>) = (A \\<Otimes> (A \\<otimes>\\<^bsup>n\\<^esup>)) * (B \\<Otimes> (B \\<otimes>\\<^bsup>n\\<^esup>))\" \n    using Suc_le_D assms(1) by fastforce\n  then show \"?thesis\" \n    using mult_distr_tensor[of \"A\" \"B\" \"(iter_tensor A n)\" \"(iter_tensor B n)\"] assms by simp\nqed\n\nlemma index_tensor_mat_with_vec2_row_cond:\n  fixes A B:: \"complex Matrix.mat\" and i:: \"nat\" \n  assumes \"i < 2 * (dim_row B)\" and \"i \\<ge> dim_row B\" and \"dim_col B > 0\"\nand \"dim_row A = 2\" and \"dim_col A = 1\"\n  shows \"(A \\<Otimes> B) $$ (i,0) = (A $$ (1,0)) * (B $$ (i-dim_row B,0))\"\nproof-\n  have \"(A \\<Otimes> B) $$ (i,0) = A $$ (i div (dim_row B),0) * B $$ (i mod (dim_row B),0)\"\n    using assms index_tensor_mat[of A \"dim_row A\" \"dim_col A\" B \"dim_row B\" \"dim_col B\" i 0] by simp\n  moreover have \"i div (dim_row B) = 1\" \n    using assms(1,2,4) by simp\n  then have \"i mod (dim_row B) = i - (dim_row B)\" \n    by (simp add: modulo_nat_def)\n  ultimately show \"(A \\<Otimes> B) $$ (i,0) = (A $$ (1,0)) * (B $$ (i-dim_row B,0))\" \n    by (simp add: \\<open>i div dim_row B = 1\\<close>)\nqed\n\nlemma iter_tensor_of_gate_is_gate:\n  fixes A:: \"complex Matrix.mat\" and n m:: \"nat\" \n  assumes \"gate m A\" and \"n \\<ge> 1\" \n  shows \"gate (m*n) (A \\<otimes>\\<^bsup>n\\<^esup>)\"\n  using assms(2)\nproof(rule nat_induct_at_least)\n  show \"gate (m * 1) (A \\<otimes>\\<^bsup>1\\<^esup>)\" using assms(1) by simp\nnext\n  fix n:: nat\n  assume \"n \\<ge> 1\" and IH:\"gate (m * n) (A \\<otimes>\\<^bsup>n\\<^esup>)\"\n  then have \"A \\<otimes>\\<^bsup>(Suc n)\\<^esup> = A \\<Otimes> (A \\<otimes>\\<^bsup>n\\<^esup>)\" \n    by (simp add: iter_tensor_suc)\n  moreover have \"gate (m*n + m) (A \\<otimes>\\<^bsup>(Suc n)\\<^esup>)\"  \n    using tensor_gate assms(1) by (simp add: IH add.commute calculation(1))\n  then show \"gate (m*(Suc n)) (A \\<otimes>\\<^bsup>(Suc n)\\<^esup>)\"\n    by (simp add: add.commute)\nqed\n\nlemma iter_tensor_of_state_is_state:\n  fixes A:: \"complex Matrix.mat\" and n m:: \"nat\" \n  assumes \"state m A\" and \"n\\<ge>1\" \n  shows \"state (m*n) (A \\<otimes>\\<^bsup>n\\<^esup>)\"\n  using assms(2)\nproof(rule nat_induct_at_least)\n  show \"state (m * 1) (A \\<otimes>\\<^bsup>1\\<^esup>)\"\n    using one_tensor_is_id assms(1) by simp\nnext\n  fix n:: nat\n  assume \"n \\<ge> 1\" and IH:\"state (m * n) (A \\<otimes>\\<^bsup>n\\<^esup>)\"\n  then have \"A \\<otimes>\\<^bsup>(Suc n)\\<^esup> = A \\<Otimes> (A \\<otimes>\\<^bsup>n\\<^esup>)\" \n    by (simp add: iter_tensor_suc)\n  moreover have \"state (m*n + m) (A \\<otimes>\\<^bsup>(Suc n)\\<^esup>)\"  \n    using tensor_gate assms(1) by (simp add: IH add.commute calculation)\n  then show \"state (m*(Suc n)) (A \\<otimes>\\<^bsup>(Suc n)\\<^esup>)\" \n    by (simp add: add.commute)\nqed\n\ntext \\<open>\nWe prepare n+1 qubits. The first n qubits in the state $|0\\rangle$, the last one in the state \n$|1\\rangle$.\n\\<close>\n\nabbreviation \\<psi>\\<^sub>1\\<^sub>0:: \"nat \\<Rightarrow> complex Matrix.mat\" where\n\"\\<psi>\\<^sub>1\\<^sub>0 n \\<equiv> Matrix.mat (2^n) 1 (\\<lambda>(i,j). 1/(sqrt 2)^n)\" \n\nlemma \\<psi>\\<^sub>1\\<^sub>0_values:\n  fixes i j n\n  assumes \"i < dim_row (\\<psi>\\<^sub>1\\<^sub>0 n)\" and \"j < dim_col (\\<psi>\\<^sub>1\\<^sub>0 n)\" \n  shows \"(\\<psi>\\<^sub>1\\<^sub>0 n) $$ (i,j) = 1/(sqrt 2)^n\" \n  using assms case_prod_conv by simp\n\ntext \\<open>$H^{\\otimes n}$ is applied to $|0\\rangle^{\\otimes n}$.\\<close>\n\nlemma H_on_ket_zero: \n  shows \"(H * |zero\\<rangle>) = \\<psi>\\<^sub>1\\<^sub>0 1\"\nproof \n  fix i j:: nat\n  assume \"i < dim_row (\\<psi>\\<^sub>1\\<^sub>0 1)\" and \"j < dim_col (\\<psi>\\<^sub>1\\<^sub>0 1)\"\n  then have f1: \"i \\<in> {0,1} \\<and> j = 0\" by (simp add: less_2_cases)\n  then show \"(H * |zero\\<rangle>) $$ (i,j) = (\\<psi>\\<^sub>1\\<^sub>0 1) $$ (i,j)\"\n    by (auto simp add: times_mat_def scalar_prod_def H_def ket_vec_def)\nnext\n  show \"dim_row (H * |zero\\<rangle>) = dim_row (\\<psi>\\<^sub>1\\<^sub>0 1)\"  by (simp add: H_def)\nnext \n  show \"dim_col (H * |zero\\<rangle>) = dim_col (\\<psi>\\<^sub>1\\<^sub>0 1)\" using H_def  \n    by (simp add: ket_vec_def)\nqed\n\nlemma \\<psi>\\<^sub>1\\<^sub>0_tensor: \n  assumes \"n \\<ge> 1\"\n  shows \"(\\<psi>\\<^sub>1\\<^sub>0 1) \\<Otimes> (\\<psi>\\<^sub>1\\<^sub>0 n) = (\\<psi>\\<^sub>1\\<^sub>0 (Suc n))\"\nproof\n  have \"dim_row (\\<psi>\\<^sub>1\\<^sub>0 1) * dim_row (\\<psi>\\<^sub>1\\<^sub>0 n) = 2^(Suc n)\" by simp \n  then show \"dim_row ((\\<psi>\\<^sub>1\\<^sub>0 1) \\<Otimes> (\\<psi>\\<^sub>1\\<^sub>0 n)) = dim_row (\\<psi>\\<^sub>1\\<^sub>0 (Suc n))\" by simp\nnext\n  have \"dim_col (\\<psi>\\<^sub>1\\<^sub>0 1) * dim_col (\\<psi>\\<^sub>1\\<^sub>0 n) = 1\" by simp\n  then show \"dim_col ((\\<psi>\\<^sub>1\\<^sub>0 1) \\<Otimes> (\\<psi>\\<^sub>1\\<^sub>0 n)) = dim_col (\\<psi>\\<^sub>1\\<^sub>0 (Suc n))\" by simp\nnext\n  fix i j:: nat\n  assume a0: \"i < dim_row (\\<psi>\\<^sub>1\\<^sub>0 (Suc n))\" and a1: \"j < dim_col (\\<psi>\\<^sub>1\\<^sub>0 (Suc n))\"\n  then have f0: \"j = 0\" and f1: \"i < 2^(Suc n)\" by auto\n  then have f2:\"(\\<psi>\\<^sub>1\\<^sub>0 (Suc n)) $$ (i,j) = 1/(sqrt 2)^(Suc n)\" \n    using \\<psi>\\<^sub>1\\<^sub>0_values[of \"i\" \"(Suc n)\" \"j\"] a0 a1 by simp\n  show \"((\\<psi>\\<^sub>1\\<^sub>0 1) \\<Otimes> (\\<psi>\\<^sub>1\\<^sub>0 n)) $$ (i,j) = (\\<psi>\\<^sub>1\\<^sub>0 (Suc n)) $$ (i,j)\" \n  proof (rule disjE) (*case distinction*)\n    show \"i < dim_row (\\<psi>\\<^sub>1\\<^sub>0 n) \\<or> i \\<ge> dim_row (\\<psi>\\<^sub>1\\<^sub>0 n)\" by linarith\n  next (* case i < dim_row (\\<psi>\\<^sub>1\\<^sub>0 n) *)\n    assume a2: \"i < dim_row (\\<psi>\\<^sub>1\\<^sub>0 n)\"\n    then have \"((\\<psi>\\<^sub>1\\<^sub>0 1) \\<Otimes> (\\<psi>\\<^sub>1\\<^sub>0 n)) $$ (i,j) = (\\<psi>\\<^sub>1\\<^sub>0 1) $$ (0,0) * (\\<psi>\\<^sub>1\\<^sub>0 n) $$ (i,0)\"\n      using index_tensor_mat f0 assms by simp\n    also have \"... = 1/sqrt(2) * 1/(sqrt(2)^n)\"\n      using \\<psi>\\<^sub>1\\<^sub>0_values a2 assms by simp\n    finally show \"((\\<psi>\\<^sub>1\\<^sub>0 1) \\<Otimes> (\\<psi>\\<^sub>1\\<^sub>0 n)) $$ (i,j) = (\\<psi>\\<^sub>1\\<^sub>0 (Suc n)) $$ (i,j)\" \n      using f2 divide_divide_eq_left power_Suc by simp\n  next (* case i \\<ge> dim_row (\\<psi>\\<^sub>1\\<^sub>0 n) *)\n    assume \"i \\<ge> dim_row (\\<psi>\\<^sub>1\\<^sub>0 n)\"\n    then have \"((\\<psi>\\<^sub>1\\<^sub>0 1) \\<Otimes> (\\<psi>\\<^sub>1\\<^sub>0 n)) $$ (i,0) = ((\\<psi>\\<^sub>1\\<^sub>0 1) $$ (1, 0)) * ((\\<psi>\\<^sub>1\\<^sub>0 n) $$ ( i -dim_row (\\<psi>\\<^sub>1\\<^sub>0 n),0))\"\n      using index_tensor_mat_with_vec2_row_cond[of i \"(\\<psi>\\<^sub>1\\<^sub>0 1)\" \"(\\<psi>\\<^sub>1\\<^sub>0 n)\" ] a0 a1 f0\n      by (metis dim_col_mat(1) dim_row_mat(1) index_tensor_mat_with_vec2_row_cond power_Suc power_one_right)  \n    then have \"((\\<psi>\\<^sub>1\\<^sub>0 1) \\<Otimes> (\\<psi>\\<^sub>1\\<^sub>0 n)) $$ (i,0) = 1/sqrt(2) * 1/(sqrt 2)^n\"\n      using \\<psi>\\<^sub>1\\<^sub>0_values[of \"i -dim_row (\\<psi>\\<^sub>1\\<^sub>0 n)\" \"n\" \"j\"] a0 a1 by simp\n    then show  \"((\\<psi>\\<^sub>1\\<^sub>0 1) \\<Otimes> (\\<psi>\\<^sub>1\\<^sub>0 n)) $$ (i,j) = (\\<psi>\\<^sub>1\\<^sub>0 (Suc n)) $$ (i,j)\" \n      using f0 f1 divide_divide_eq_left power_Suc by simp\n  qed\nqed\n\nlemma \\<psi>\\<^sub>1\\<^sub>0_tensor_is_state:\n  assumes \"n \\<ge> 1\"\n  shows \"state n ( |zero\\<rangle> \\<otimes>\\<^bsup>n\\<^esup>)\"  \n  using iter_tensor_of_state_is_state ket_zero_is_state assms by fastforce\n\nlemma iter_tensor_of_H_is_gate:\n  assumes \"n \\<ge> 1\"\n  shows \"gate n (H \\<otimes>\\<^bsup>n\\<^esup>)\" \n  using iter_tensor_of_gate_is_gate H_is_gate assms by fastforce\n\nlemma iter_tensor_of_H_on_zero_tensor: \n  assumes \"n \\<ge> 1\"\n  shows \"(H \\<otimes>\\<^bsup>n\\<^esup>) * ( |zero\\<rangle> \\<otimes>\\<^bsup>n\\<^esup>) = \\<psi>\\<^sub>1\\<^sub>0 n\"\n  using assms\nproof(rule nat_induct_at_least)\n  show \"(H \\<otimes>\\<^bsup>1\\<^esup>) * ( |zero\\<rangle> \\<otimes>\\<^bsup>1\\<^esup>) = \\<psi>\\<^sub>1\\<^sub>0 1\"\n    using H_on_ket_zero by simp\nnext\n  fix n:: nat\n  assume a0: \"n \\<ge> 1\" and IH: \"(H \\<otimes>\\<^bsup>n\\<^esup>) * ( |zero\\<rangle> \\<otimes>\\<^bsup>n\\<^esup>) = \\<psi>\\<^sub>1\\<^sub>0 n\"\n  then have \"(H \\<otimes>\\<^bsup>(Suc n)\\<^esup>) * ( |zero\\<rangle> \\<otimes>\\<^bsup>(Suc n)\\<^esup>) = (H * |zero\\<rangle>) \\<Otimes> ((H \\<otimes>\\<^bsup>n\\<^esup>) * ( |zero\\<rangle> \\<otimes>\\<^bsup>n\\<^esup>))\" \n    using iter_tensor_mult_distr[of \"n\" \"H\" \"|zero\\<rangle>\"] a0 ket_vec_def H_def by(simp add: H_def) \n  also have  \"... = (H * |zero\\<rangle>) \\<Otimes> (\\<psi>\\<^sub>1\\<^sub>0 n)\" using IH by simp \n  also have \"... = (\\<psi>\\<^sub>1\\<^sub>0 1) \\<Otimes> (\\<psi>\\<^sub>1\\<^sub>0 n)\" using H_on_ket_zero by simp\n  also have \"... = (\\<psi>\\<^sub>1\\<^sub>0 (Suc n))\" using \\<psi>\\<^sub>1\\<^sub>0_tensor a0 by simp\n  finally show \"(H \\<otimes>\\<^bsup>(Suc n)\\<^esup>) * ( |zero\\<rangle> \\<otimes>\\<^bsup>(Suc n)\\<^esup>) = (\\<psi>\\<^sub>1\\<^sub>0 (Suc n))\" by simp\nqed\n\nlemma \\<psi>\\<^sub>1\\<^sub>0_is_state:\n  assumes \"n \\<ge> 1\"\n  shows \"state n (\\<psi>\\<^sub>1\\<^sub>0 n)\"\n  using iter_tensor_of_H_is_gate \\<psi>\\<^sub>1\\<^sub>0_tensor_is_state assms gate_on_state_is_state iter_tensor_of_H_on_zero_tensor assms by metis\n\nabbreviation \\<psi>\\<^sub>1\\<^sub>1:: \"complex Matrix.mat\" where\n\"\\<psi>\\<^sub>1\\<^sub>1 \\<equiv> Matrix.mat 2 1 (\\<lambda>(i,j). if i=0 then 1/sqrt(2) else -1/sqrt(2))\"\n\nlemma H_on_ket_one_is_\\<psi>\\<^sub>1\\<^sub>1: \n  shows \"(H * |one\\<rangle>) = \\<psi>\\<^sub>1\\<^sub>1\"\nproof \n  fix i j:: nat\n  assume \"i < dim_row \\<psi>\\<^sub>1\\<^sub>1\" and \"j < dim_col \\<psi>\\<^sub>1\\<^sub>1\"\n  then have \"i \\<in> {0,1} \\<and> j = 0\" by (simp add: less_2_cases)\n  then show \"(H * |one\\<rangle>) $$ (i,j) = \\<psi>\\<^sub>1\\<^sub>1 $$ (i,j)\"\n    by (auto simp add: times_mat_def scalar_prod_def H_def ket_vec_def)\nnext\n  show \"dim_row (H * |one\\<rangle>) = dim_row \\<psi>\\<^sub>1\\<^sub>1\" by (simp add: H_def)\nnext \n  show \"dim_col (H * |one\\<rangle>) = dim_col \\<psi>\\<^sub>1\\<^sub>1\" by (simp add: H_def ket_vec_def)\nqed\n\nabbreviation \\<psi>\\<^sub>1:: \"nat \\<Rightarrow> complex Matrix.mat\" where\n\"\\<psi>\\<^sub>1 n \\<equiv> Matrix.mat (2^(n+1)) 1 (\\<lambda>(i,j). if even i then 1/(sqrt 2)^(n+1) else -1/(sqrt 2)^(n+1))\"\n\nlemma \\<psi>\\<^sub>1_values_even[simp]:\n  fixes i j n\n  assumes \"i < dim_row (\\<psi>\\<^sub>1 n)\" and \"j < dim_col (\\<psi>\\<^sub>1 n)\" and \"even i\"\n  shows \"(\\<psi>\\<^sub>1 n) $$ (i,j) = 1/(sqrt 2)^(n+1)\" \n  using assms case_prod_conv by simp\n\nlemma \\<psi>\\<^sub>1_values_odd [simp]:\n  fixes i j n\n  assumes \"i < dim_row (\\<psi>\\<^sub>1 n)\" and \"j < dim_col (\\<psi>\\<^sub>1 n)\" and \"odd i\"\n  shows \"(\\<psi>\\<^sub>1 n) $$ (i,j) = -1/(sqrt 2)^(n+1)\" \n  using assms case_prod_conv by simp\n\nlemma \"\\<psi>\\<^sub>1\\<^sub>0_tensor_\\<psi>\\<^sub>1\\<^sub>1_is_\\<psi>\\<^sub>1\":\n  assumes \"n \\<ge> 1\"\n  shows \"(\\<psi>\\<^sub>1\\<^sub>0 n) \\<Otimes> \\<psi>\\<^sub>1\\<^sub>1 = \\<psi>\\<^sub>1 n\" \nproof \n show \"dim_col ((\\<psi>\\<^sub>1\\<^sub>0 n) \\<Otimes> \\<psi>\\<^sub>1\\<^sub>1) = dim_col (\\<psi>\\<^sub>1 n)\" by simp\nnext\n  show \"dim_row ((\\<psi>\\<^sub>1\\<^sub>0 n) \\<Otimes> \\<psi>\\<^sub>1\\<^sub>1) = dim_row (\\<psi>\\<^sub>1 n)\" by simp\nnext\n  fix i j:: nat\n  assume a0: \"i < dim_row (\\<psi>\\<^sub>1 n)\" and a1: \"j < dim_col (\\<psi>\\<^sub>1 n)\"\n  then have \"i < 2^(n+1)\" and \"j = 0\" by auto \n  then have f0: \"((\\<psi>\\<^sub>1\\<^sub>0 n) \\<Otimes> \\<psi>\\<^sub>1\\<^sub>1) $$ (i,j) = 1/(sqrt 2)^n * \\<psi>\\<^sub>1\\<^sub>1 $$ (i mod 2, j)\" \n    using \\<psi>\\<^sub>1\\<^sub>0_values[of \"i div 2\" n \"j div 1\"] a0 a1 by simp\n  show \"((\\<psi>\\<^sub>1\\<^sub>0 n) \\<Otimes> \\<psi>\\<^sub>1\\<^sub>1) $$ (i,j) = (\\<psi>\\<^sub>1 n) $$ (i,j)\" \n    using f0 \\<psi>\\<^sub>1_values_even \\<psi>\\<^sub>1_values_odd a0 a1 by auto \nqed\n\nlemma \\<psi>\\<^sub>1_is_state:\n  assumes \"n \\<ge> 1\"\n  shows \"state (n+1) (\\<psi>\\<^sub>1 n)\" \n  using assms \\<psi>\\<^sub>1\\<^sub>0_tensor_\\<psi>\\<^sub>1\\<^sub>1_is_\\<psi>\\<^sub>1 \\<psi>\\<^sub>1\\<^sub>0_is_state H_on_ket_one_is_state H_on_ket_one_is_\\<psi>\\<^sub>1\\<^sub>1 tensor_state by metis\n\nabbreviation (in jozsa) \\<psi>\\<^sub>2:: \"complex Matrix.mat\" where\n\"\\<psi>\\<^sub>2 \\<equiv> Matrix.mat (2^(n+1)) 1 (\\<lambda>(i,j). if even i then (-1)^f(i div 2)/(sqrt 2)^(n+1) \n                                        else (-1)^(f(i div 2)+1)/(sqrt 2)^(n+1))\"\n\nlemma (in jozsa) \\<psi>\\<^sub>2_values_even [simp]:\n  fixes i j \n  assumes \"i < dim_row \\<psi>\\<^sub>2 \" and \"j < dim_col \\<psi>\\<^sub>2\" and \"even i\"\n  shows \"\\<psi>\\<^sub>2 $$ (i,j) = (-1)^f(i div 2)/(sqrt 2)^(n+1)\" \n  using assms case_prod_conv by simp\n\nlemma (in jozsa) \\<psi>\\<^sub>2_values_odd [simp]:\n  fixes i j \n  assumes \"i < dim_row \\<psi>\\<^sub>2\" and \"j < dim_col \\<psi>\\<^sub>2\" and \"odd i\"\n  shows \"\\<psi>\\<^sub>2 $$ (i,j) = (-1)^(f(i div 2)+1)/(sqrt 2)^(n+1)\" \n  using assms case_prod_conv by simp\n\nlemma (in jozsa) \\<psi>\\<^sub>2_values_odd_hidden [simp]:\n  assumes \"2*k+1 < dim_row \\<psi>\\<^sub>2\" and \"j < dim_col \\<psi>\\<^sub>2\" \n  shows \"\\<psi>\\<^sub>2 $$ (2*k+1,j) = ((-1)^(f((2*k+1) div 2)+1))/(sqrt 2)^(n+1)\" \n  using assms by simp\n\nlemma (in jozsa) snd_rep_of_\\<psi>\\<^sub>2:\n  assumes \"i < dim_row \\<psi>\\<^sub>2\"\n  shows \"((1-f(i div 2)) + -f(i div 2)) * 1/(sqrt 2)^(n+1) = (-1)^f(i div 2)/(sqrt 2)^(n+1)\"\n    and \"(-(1-f(i div 2))+(f(i div 2)))* 1/(sqrt 2)^(n+1) = (-1)^(f(i div 2)+1)/(sqrt 2)^(n+1)\"\nproof- \n  have \"i div 2 \\<in> {i. i < 2 ^ n}\" \n    using assms by auto\n  then have \"real (Suc 0 - f (i div 2)) - real (f (i div 2)) = (- 1) ^ f (i div 2)\" \n    using assms f_values by auto\n  thus \"((1-f(i div 2)) + -f(i div 2)) * 1/(sqrt 2)^(n+1) = (-1)^f(i div 2)/(sqrt 2)^(n+1)\" by auto\nnext\n  have \"i div 2 \\<in> {i. i < 2^n}\" \n    using assms by simp\n  then have \"(real (f (i div 2)) - real (Suc 0 - f (i div 2))) / (sqrt 2 ^ (n+1)) =\n           - ((- 1) ^ f (i div 2) / (sqrt 2 ^ (n+1)))\" \n   using assms f_values by fastforce\n  then show \"(-(1-f(i div 2))+(f(i div 2)))* 1/(sqrt 2)^(n+1) = (-1)^(f(i div 2)+1)/(sqrt 2)^(n+1)\" by simp\nqed\n\nlemma (in jozsa) jozsa_transform_times_\\<psi>\\<^sub>1_is_\\<psi>\\<^sub>2:\n  shows \"U\\<^sub>f * (\\<psi>\\<^sub>1 n) = \\<psi>\\<^sub>2\" \nproof \n  show \"dim_row (U\\<^sub>f * (\\<psi>\\<^sub>1 n)) = dim_row \\<psi>\\<^sub>2\" by simp\nnext\n  show \"dim_col (U\\<^sub>f * (\\<psi>\\<^sub>1 n)) = dim_col \\<psi>\\<^sub>2\" by simp\nnext\n  fix i j ::nat\n  assume a0: \"i < dim_row \\<psi>\\<^sub>2\" and a1: \"j < dim_col \\<psi>\\<^sub>2\"\n  then have f0:\"i \\<in> {0..2^(n+1)} \\<and> j=0\" by simp\n  then have f1: \"i < dim_row U\\<^sub>f \\<and> j < dim_col U\\<^sub>f \" using a0 by simp\n  have f2: \"i < dim_row (\\<psi>\\<^sub>1 n) \\<and> j < dim_col (\\<psi>\\<^sub>1 n)\" using a0 a1 by simp\n  show \"(U\\<^sub>f * (\\<psi>\\<^sub>1 n)) $$ (i,j) = \\<psi>\\<^sub>2 $$ (i,j)\"\n  proof (rule disjE)\n    show \"even i \\<or> odd i\" by auto\n  next\n    assume a2: \"even i\"\n    then have \"(U\\<^sub>f * (\\<psi>\\<^sub>1 n)) $$ (i,j) = (\\<Sum>k \\<in> {i,i+1}. U\\<^sub>f $$ (i,k) * (\\<psi>\\<^sub>1 n) $$ (k,j))\"\n      using f1 f2 U\\<^sub>f_mult_without_empty_summands_even[of i j \"(\\<psi>\\<^sub>1 n)\"] by simp \n    moreover have \"U\\<^sub>f $$ (i,i) * (\\<psi>\\<^sub>1 n) $$ (i,j) = (1-f(i div 2))* 1/(sqrt 2)^(n+1)\" \n      using f0 f1 a2 by simp\n    moreover have \"U\\<^sub>f $$ (i,i+1) * (\\<psi>\\<^sub>1 n) $$ (i+1,j) = (-f(i div 2))* 1/(sqrt 2)^(n+1)\" \n      using f0 f1 a2 by auto\n    ultimately have \"(U\\<^sub>f * (\\<psi>\\<^sub>1 n)) $$ (i,j) = (1-f(i div 2))* 1/(sqrt 2)^(n+1) + (-f(i div 2))* 1/(sqrt 2)^(n+1)\" by simp\n    also have \"... = ((1-f(i div 2))+-f(i div 2)) * 1/(sqrt 2)^(n+1)\" \n      using add_divide_distrib \n      by (metis (no_types, hide_lams) mult.right_neutral of_int_add of_int_of_nat_eq)\n    also have \"... = \\<psi>\\<^sub>2 $$ (i,j)\" \n      using a0 a1 a2 snd_rep_of_\\<psi>\\<^sub>2 by simp\n    finally show \"(U\\<^sub>f * (\\<psi>\\<^sub>1 n)) $$ (i,j) = \\<psi>\\<^sub>2 $$ (i,j)\" by simp\n  next \n    assume a2: \"odd i\"\n    then have f6: \"i\\<ge>1\"  \n    using linorder_not_less by auto\n    have \"(U\\<^sub>f * (\\<psi>\\<^sub>1 n)) $$ (i,j) = (\\<Sum>k \\<in> {i-1,i}. U\\<^sub>f $$ (i,k) * (\\<psi>\\<^sub>1 n) $$ (k,j))\"\n      using f1 f2 a2 U\\<^sub>f_mult_without_empty_summands_odd[of i j \"(\\<psi>\\<^sub>1 n)\"]  \n      by (metis dim_row_mat(1) jozsa_transform_dim(2)) \n    moreover have \"(\\<Sum>k \\<in> {i-1,i}. U\\<^sub>f $$ (i,k) * (\\<psi>\\<^sub>1 n) $$ (k,j)) \n                 = U\\<^sub>f $$ (i,i-1) * (\\<psi>\\<^sub>1 n) $$ (i-1,j) +  U\\<^sub>f $$ (i,i) * (\\<psi>\\<^sub>1 n) $$ (i,j)\" \n      using a2 f6 by simp\n    moreover have  \"U\\<^sub>f $$ (i,i) * (\\<psi>\\<^sub>1 n) $$ (i,j) = (1-f(i div 2))* -1/(sqrt 2)^(n+1)\" \n      using f1 f2 a2 by simp\n    moreover have \"U\\<^sub>f $$ (i,i-1) * (\\<psi>\\<^sub>1 n) $$ (i-1,j) = f(i div 2)* 1/(sqrt 2)^(n+1)\" \n      using a0 a1 a2 by simp\n    ultimately have \"(U\\<^sub>f * (\\<psi>\\<^sub>1 n)) $$ (i,j) = (1-f(i div 2))* -1/(sqrt 2)^(n+1) +(f(i div 2))* 1/(sqrt 2)^(n+1)\" \n      using of_real_add by simp\n    also have \"... = (-(1-f(i div 2)) + (f(i div 2))) * 1/(sqrt 2)^(n+1)\" \n      by (metis (no_types, hide_lams) mult.right_neutral add_divide_distrib mult_minus1_right \n          of_int_add of_int_of_nat_eq)\n    also have \"... = (-1)^(f(i div 2)+1)/(sqrt 2)^(n+1)\" \n       using a0 a1 a2 snd_rep_of_\\<psi>\\<^sub>2 by simp\n   finally show \"(U\\<^sub>f * (\\<psi>\\<^sub>1 n)) $$ (i,j) = \\<psi>\\<^sub>2 $$ (i,j)\" \n      using a0 a1 a2 by simp\n  qed\nqed\n\nlemma (in jozsa) \\<psi>\\<^sub>2_is_state:\n  shows \"state (n+1) \\<psi>\\<^sub>2\" \n  using jozsa_transform_times_\\<psi>\\<^sub>1_is_\\<psi>\\<^sub>2 jozsa_transform_is_gate \\<psi>\\<^sub>1_is_state dim gate_on_state_is_state by fastforce\n\ntext \\<open>@{text \"H^\\<^sub>\\<otimes> n\"} is the result of taking the nth tensor product of H\\<close>\n\nabbreviation iter_tensor_of_H_rep:: \"nat \\<Rightarrow> complex Matrix.mat\" (\"H^\\<^sub>\\<otimes> _\") where\n\"iter_tensor_of_H_rep n \\<equiv> Matrix.mat (2^n) (2^n) (\\<lambda>(i,j).(-1)^(i \\<cdot>\\<^bsub>n\\<^esub> j)/(sqrt 2)^n)\"\n\nlemma tensor_of_H_values [simp]:\n  fixes n i j:: nat\n  assumes \"i < dim_row (H^\\<^sub>\\<otimes> n)\" and \"j < dim_col (H^\\<^sub>\\<otimes> n)\"\n  shows \"(H^\\<^sub>\\<otimes> n) $$ (i,j) = (-1)^(i \\<cdot>\\<^bsub>n\\<^esub> j)/(sqrt 2)^n\"\n  using assms by simp\n\nlemma dim_row_of_iter_tensor_of_H [simp]:\n  assumes \"n \\<ge> 1\"\n  shows \"1 < dim_row (H^\\<^sub>\\<otimes> n)\" \n  using assms by(metis One_nat_def Suc_1 dim_row_mat(1) le_trans lessI linorder_not_less one_less_power)\n\nlemma iter_tensor_of_H_fst_pos:\n  fixes n i j:: nat\n  assumes \"i < 2^n \\<or> j < 2^n\" and \"i < 2^(n+1) \\<and> j < 2^(n+1)\"\n  shows \"(H^\\<^sub>\\<otimes> (Suc n)) $$ (i,j) = 1/sqrt(2) * ((H^\\<^sub>\\<otimes> n) $$ (i mod 2^n, j mod 2^n))\"\nproof-\n  have \"(H^\\<^sub>\\<otimes> (Suc n)) $$ (i,j) = (-1)^(bip i (Suc n) j)/(sqrt 2)^(Suc n)\"\n    using assms by simp\n  moreover have \"bip i (Suc n) j = bip (i mod 2^n) n (j mod 2^n)\" \n    using bitwise_inner_prod_fst_el_0 assms(1) by simp \n  ultimately show ?thesis \n    using bitwise_inner_prod_def by simp\nqed\n\nlemma iter_tensor_of_H_fst_neg:\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 \"(H^\\<^sub>\\<otimes> (Suc n)) $$ (i,j) = -1/sqrt(2) * (H^\\<^sub>\\<otimes> n) $$ (i mod 2^n, j mod 2^n)\"\nproof-\n  have \"(H^\\<^sub>\\<otimes> (Suc n)) $$ (i,j) = (-1)^(bip i (n+1) j)/(sqrt 2)^(n+1)\" \n    using assms(2) by simp\n  moreover have \"bip i (n+1) j = 1 + bip (i mod 2^n) n (j mod 2^n)\" \n    using bitwise_inner_prod_fst_el_is_1 assms by simp\n  ultimately show ?thesis by simp\nqed \n\nlemma H_tensor_iter_tensor_of_H:   \n  fixes n:: nat\n  shows  \"(H \\<Otimes> H^\\<^sub>\\<otimes> n) = H^\\<^sub>\\<otimes> (Suc n)\" \nproof\n  fix i j:: nat\n  assume a0: \"i < dim_row (H^\\<^sub>\\<otimes> (Suc n))\" and a1: \"j < dim_col (H^\\<^sub>\\<otimes> (Suc n))\"\n  then have f0: \"i \\<in> {0..<2^(n+1)} \\<and> j \\<in> {0..<2^(n+1)}\" by simp\n  then have f1: \"(H \\<Otimes> H^\\<^sub>\\<otimes> n) $$ (i,j) = H $$ (i div (dim_row (H^\\<^sub>\\<otimes> n)),j div (dim_col (H^\\<^sub>\\<otimes> n))) \n                                       * (H^\\<^sub>\\<otimes> n) $$ (i mod (dim_row (H^\\<^sub>\\<otimes> n)),j mod (dim_col (H^\\<^sub>\\<otimes> n)))\"\n    by (simp add: H_without_scalar_prod)\n  show \"(H \\<Otimes> H^\\<^sub>\\<otimes> n) $$ (i,j) = (H^\\<^sub>\\<otimes> (Suc n)) $$ (i,j)\"\n  proof (rule disjE) \n    show \"(i < 2^n \\<or> j < 2^n) \\<or> \\<not>(i < 2^n \\<or> j < 2^n)\" by auto\n  next\n    assume a2: \"(i < 2^n \\<or> j < 2^n)\"\n    then have \"(H^\\<^sub>\\<otimes> (Suc n)) $$ (i,j) = 1/sqrt(2) * ((H^\\<^sub>\\<otimes> n) $$ (i mod 2^n, j mod 2^n))\" \n      using a0 a1 f0 iter_tensor_of_H_fst_pos by (metis (mono_tags, lifting) atLeastLessThan_iff)\n    moreover have \"H $$ (i div (dim_row (H^\\<^sub>\\<otimes> n)),j div (dim_col (H^\\<^sub>\\<otimes> n))) = 1/sqrt 2\"\n      using a0 a1 f0 H_without_scalar_prod H_values a2\n      by (metis (no_types, lifting) dim_col_mat(1) dim_row_mat(1) div_less le_eq_less_or_eq \n          le_numeral_extra(2) less_power_add_imp_div_less plus_1_eq_Suc power_one_right) \n    ultimately show \"(H \\<Otimes> H^\\<^sub>\\<otimes> n) $$ (i,j) = (H^\\<^sub>\\<otimes> (Suc n)) $$ (i,j)\" \n      using f1 by simp\n  next \n    assume a2: \"\\<not>(i < 2^n \\<or> j < 2^n)\"\n    then have \"i \\<ge> 2^n \\<and> j \\<ge> 2^n\" by simp\n    then have f2:\"(H^\\<^sub>\\<otimes> (Suc n)) $$ (i,j) = -1/sqrt(2) * ((H^\\<^sub>\\<otimes> n) $$ (i mod 2^n, j mod 2^n))\" \n      using a0 a1 f0 iter_tensor_of_H_fst_neg by simp\n    have \"i div (dim_row (H^\\<^sub>\\<otimes> n)) =1\" and \"j div (dim_row (H^\\<^sub>\\<otimes> n)) = 1\"  \n      using a2 a0 a1 by auto\n    then have \"H $$ (i div (dim_row (H^\\<^sub>\\<otimes> n)),j div (dim_col (H^\\<^sub>\\<otimes> n))) = -1/sqrt 2\"\n      using a0 a1 f0 H_values_right_bottom[of \"i div (dim_row (H^\\<^sub>\\<otimes> n))\" \"j div (dim_col (H^\\<^sub>\\<otimes> n))\"] a2 \n      by fastforce\n    then show \"(H \\<Otimes> H^\\<^sub>\\<otimes> n) $$ (i,j) = (H^\\<^sub>\\<otimes> (Suc n)) $$ (i,j)\" \n      using f1 f2 by simp\n  qed\nnext\n  show \"dim_row (H \\<Otimes> H^\\<^sub>\\<otimes> n) = dim_row (H^\\<^sub>\\<otimes> (Suc n))\" \n    by (simp add: H_without_scalar_prod) \nnext\n  show \"dim_col (H \\<Otimes> H^\\<^sub>\\<otimes> n) = dim_col (H^\\<^sub>\\<otimes> (Suc n))\" \n    by (simp add: H_without_scalar_prod) \nqed\n\ntext \\<open>\nWe prove that @{term \"H^\\<^sub>\\<otimes> n\"} is indeed the matrix representation of @{term \"H \\<otimes>\\<^bsup>n\\<^esup>\"}, the iterated \ntensor product of the Hadamard gate H.\n\\<close>\n\nlemma one_tensor_of_H_is_H:\n  shows \"(H^\\<^sub>\\<otimes> 1) = H\"\nproof(rule eq_matI)\n  show \"dim_row (H^\\<^sub>\\<otimes> 1) = dim_row H\"\n    by (simp add: H_without_scalar_prod)\nnext\n  show \"dim_col (H^\\<^sub>\\<otimes> 1) = dim_col H\"\n    by (simp add: H_without_scalar_prod)\nnext\n  fix i j:: nat\n  assume a0:\"i < dim_row H\" and a1:\"j < dim_col H\"\n  then show \"(H^\\<^sub>\\<otimes> 1) $$ (i,j) = H $$ (i,j)\"\n  proof-\n    have \"(H^\\<^sub>\\<otimes> 1) $$ (0, 0) = 1/sqrt(2)\" \n       using bitwise_inner_prod_def bin_rep_def by simp \n    moreover have \"(H^\\<^sub>\\<otimes> 1) $$ (0,1) = 1/sqrt(2)\" \n       using bitwise_inner_prod_def bin_rep_def by simp \n    moreover have \"(H^\\<^sub>\\<otimes> 1) $$ (1,0) = 1/sqrt(2)\" \n       using bitwise_inner_prod_def bin_rep_def by simp \n    moreover have \"(H^\\<^sub>\\<otimes> 1) $$ (1,1) = -1/sqrt(2)\" \n       using bitwise_inner_prod_def bin_rep_def by simp \n     ultimately show \"(H^\\<^sub>\\<otimes> 1) $$ (i,j) = H $$ (i,j)\" \n       using a0 a1 H_values H_values_right_bottom\n       by (metis (no_types, lifting) H_without_scalar_prod One_nat_def dim_col_mat(1) dim_row_mat(1) \ndivide_minus_left less_2_cases)\n  qed\nqed\n\nlemma iter_tensor_of_H_rep_is_correct:\n  fixes n:: nat\n  assumes \"n \\<ge> 1\"\n  shows \"(H \\<otimes>\\<^bsup>n\\<^esup>) = H^\\<^sub>\\<otimes> n\"\n  using assms\nproof(rule nat_induct_at_least)\n  show \"(H \\<otimes>\\<^bsup>1\\<^esup>) = H^\\<^sub>\\<otimes> 1\" \n    using one_tensor_is_id one_tensor_of_H_is_H by simp\nnext\n  fix n:: nat\n  assume a0:\"n \\<ge> 1\" and IH:\"(H \\<otimes>\\<^bsup>n\\<^esup>) = H^\\<^sub>\\<otimes> n\"\n  then have \"(H \\<otimes>\\<^bsup>(Suc n)\\<^esup>) = H \\<Otimes> (H \\<otimes>\\<^bsup>n\\<^esup>)\" \n    using iter_tensor_suc Nat.Suc_eq_plus1 by metis\n  also have \"... = H \\<Otimes> (H^\\<^sub>\\<otimes> n)\" \n    using IH by simp\n  also have \"... = H^\\<^sub>\\<otimes> (Suc n)\" \n    using a0 H_tensor_iter_tensor_of_H by simp\n  finally show \"(H \\<otimes>\\<^bsup>(Suc n)\\<^esup>) = H^\\<^sub>\\<otimes> (Suc n)\" \n    by simp\nqed\n\ntext \\<open>@{text \"HId^\\<^sub>\\<otimes> 1\"} is the result of taking the tensor product of the nth tensor of H and Id 1 \\<close>\n\nabbreviation tensor_of_H_tensor_Id:: \"nat \\<Rightarrow> complex Matrix.mat\" (\"HId^\\<^sub>\\<otimes> _\") where\n\"tensor_of_H_tensor_Id n \\<equiv> Matrix.mat (2^(n+1)) (2^(n+1)) (\\<lambda>(i,j).\n  if (i mod 2 = j mod 2) then (-1)^((i div 2) \\<cdot>\\<^bsub>n\\<^esub> (j div 2))/(sqrt 2)^n else 0)\"\n\nlemma mod_2_is_both_even_or_odd:\n  \"((even i \\<and> even j) \\<or> (odd i \\<and> odd j)) \\<longleftrightarrow> (i mod 2 = j mod 2)\" \n  by (metis dvd_eq_mod_eq_0 odd_iff_mod_2_eq_one)\n  \nlemma HId_values [simp]:\n  assumes \"n \\<ge> 1\" and \"i < dim_row (HId^\\<^sub>\\<otimes> n)\" and \"j < dim_col (HId^\\<^sub>\\<otimes> n)\"\n  shows \"even i \\<and> even j \\<longrightarrow> (HId^\\<^sub>\\<otimes> n) $$ (i,j) = (-1)^((i div 2) \\<cdot>\\<^bsub>n\\<^esub> (j div 2))/(sqrt 2)^n\"\nand \"odd i \\<and> odd j \\<longrightarrow> (HId^\\<^sub>\\<otimes> n) $$ (i,j) = (-1)^((i div 2) \\<cdot>\\<^bsub>n\\<^esub> (j div 2))/(sqrt 2)^n\"\nand \"(i mod 2 = j mod 2) \\<longrightarrow> (HId^\\<^sub>\\<otimes> n) $$ (i,j) = (-1)^((i div 2) \\<cdot>\\<^bsub>n\\<^esub> (j div 2))/(sqrt 2)^n\"\nand \"\\<not>(i mod 2 = j mod 2) \\<longrightarrow> (HId^\\<^sub>\\<otimes> n) $$ (i,j) = 0\"\n  using assms mod_2_is_both_even_or_odd by auto\n\nlemma iter_tensor_of_H_tensor_Id_is_HId:\n  shows \"(H^\\<^sub>\\<otimes> n) \\<Otimes> Id 1 = HId^\\<^sub>\\<otimes> n\"\nproof\n  show \"dim_row ((H^\\<^sub>\\<otimes> n) \\<Otimes> Id 1) = dim_row (HId^\\<^sub>\\<otimes> n)\" \n    by (simp add: Quantum.Id_def)\nnext\n  show \"dim_col ((H^\\<^sub>\\<otimes> n) \\<Otimes> Id 1) = dim_col (HId^\\<^sub>\\<otimes> n)\" \n    by (simp add: Quantum.Id_def)\nnext\n  fix i j:: nat\n  assume a0: \"i < dim_row (HId^\\<^sub>\\<otimes> n)\" and a1: \"j < dim_col (HId^\\<^sub>\\<otimes> n)\"\n  then have f0: \"i < (2^(n+1)) \\<and> j < (2^(n+1))\" by simp\n  then have \"i < dim_row (H^\\<^sub>\\<otimes> n) * dim_row (Id 1) \\<and> j < dim_col (H^\\<^sub>\\<otimes> n) * dim_col (Id 1)\"   \n    using Id_def by simp\n  moreover have \"dim_col (H^\\<^sub>\\<otimes> n) \\<ge> 0 \\<and> dim_col (Id 1) \\<ge> 0\"  \n    using Id_def by simp\n  ultimately have f1: \"((H^\\<^sub>\\<otimes> n) \\<Otimes> (Id 1)) $$ (i,j) \n    = (H^\\<^sub>\\<otimes> n) $$ (i div (dim_row (Id 1)),j div (dim_col (Id 1))) * \n      (Id 1) $$ (i mod (dim_row (Id 1)),j mod (dim_col (Id 1)))\"\n    by (simp add: Quantum.Id_def)\n  show \"((H^\\<^sub>\\<otimes> n)\\<Otimes>Id 1) $$ (i,j) = (HId^\\<^sub>\\<otimes> n) $$ (i,j)\" \n  proof (rule disjE)\n    show \"(i mod 2 = j mod 2) \\<or> \\<not> (i mod 2 = j mod 2)\" by simp\n  next\n    assume a2:\"(i mod 2 = j mod 2)\"\n    then have \"(Id 1) $$ (i mod (dim_row (Id 1)),j mod (dim_col (Id 1))) = 1\" \n      by (simp add: Quantum.Id_def)\n    moreover have \"(H^\\<^sub>\\<otimes> n) $$ (i div (dim_row (Id 1)), j div (dim_col (Id 1))) \n                    = (-1)^((i div (dim_row (Id 1))) \\<cdot>\\<^bsub>n\\<^esub> (j div (dim_col (Id 1))))/(sqrt 2)^n\" \n      using tensor_of_H_values Id_def f0 less_mult_imp_div_less by simp\n    ultimately show \"((H^\\<^sub>\\<otimes> n) \\<Otimes> Id 1) $$ (i,j) = (HId^\\<^sub>\\<otimes> n) $$ (i,j)\" \n      using a2 f0 f1 Id_def by simp\n  next\n    assume a2: \"\\<not>(i mod 2 = j mod 2)\" \n    then have \"(Id 1) $$ (i mod (dim_row (Id 1)),j mod (dim_col (Id 1))) = 0\" \n      by (simp add: Quantum.Id_def)\n    then show \"((H^\\<^sub>\\<otimes> n) \\<Otimes> Id 1) $$ (i,j) = (HId^\\<^sub>\\<otimes> n) $$ (i,j)\" \n      using a2 f0 f1 by simp\n  qed\nqed\n\nlemma HId_is_gate:\n  assumes \"n \\<ge> 1\"\n  shows \"gate (n+1) (HId^\\<^sub>\\<otimes> n)\" \nproof- \n  have \"(HId^\\<^sub>\\<otimes> n) = (H^\\<^sub>\\<otimes> n) \\<Otimes> Id 1\" \n    using iter_tensor_of_H_tensor_Id_is_HId by simp\n  moreover have \"gate 1 (Id 1)\" \n    using id_is_gate by simp\n  moreover have \"gate n (H^\\<^sub>\\<otimes> n)\"\n    using H_is_gate iter_tensor_of_gate_is_gate[of 1 H n] assms by(simp add: iter_tensor_of_H_rep_is_correct)\n  ultimately show \"gate (n+1) (HId^\\<^sub>\\<otimes> n)\" \n    using tensor_gate by presburger\nqed\n\ntext \\<open>State @{term \"\\<psi>\\<^sub>3\"} is obtained by the multiplication of @{term \"HId^\\<^sub>\\<otimes> n\"} and @{term \"\\<psi>\\<^sub>2\"}\\<close>\n\nabbreviation (in jozsa) \\<psi>\\<^sub>3:: \"complex Matrix.mat\" where\n\"\\<psi>\\<^sub>3 \\<equiv> Matrix.mat (2^(n+1)) 1 (\\<lambda>(i,j). \nif even i \n  then (\\<Sum>k<2^n. (-1)^(f(k) + ((i div 2) \\<cdot>\\<^bsub>n\\<^esub> k))/((sqrt 2)^n * (sqrt 2)^(n+1))) \n    else  (\\<Sum>k<2^n. (-1)^(f(k)+ 1 + ((i div 2) \\<cdot>\\<^bsub>n\\<^esub> k)) /((sqrt 2)^n * (sqrt 2)^(n+1))))\"\n\nlemma (in jozsa) \\<psi>\\<^sub>3_values:\n  assumes \"i < dim_row \\<psi>\\<^sub>3\"\n  shows \"odd i \\<longrightarrow> \\<psi>\\<^sub>3 $$ (i,0) = (\\<Sum>k<2^n. (-1)^(f(k) + 1 + ((i div 2) \\<cdot>\\<^bsub>n\\<^esub> k))/((sqrt 2)^n * (sqrt 2)^(n+1)))\"\n  using assms by simp\n\nlemma (in jozsa) \\<psi>\\<^sub>3_dim [simp]:\n  shows \"1 < dim_row \\<psi>\\<^sub>3\"\n  using dim_row_mat(1) nat_neq_iff by fastforce\n\nlemma sum_every_odd_summand_is_zero:\n  fixes n:: nat \n  assumes \"n \\<ge> 1\"\n  shows \"\\<forall>f::(nat \\<Rightarrow> complex).(\\<forall>i. i<2^(n+1) \\<and> odd i \\<longrightarrow> f i = 0) \\<longrightarrow> \n            (\\<Sum>k\\<in>{0..<2^(n+1)}. f k) = (\\<Sum>k\\<in>{0..<2^n}. f (2*k))\"\n  using assms\nproof(rule nat_induct_at_least)\n  show \"\\<forall>f::(nat \\<Rightarrow> complex).(\\<forall>i. i<2^(1+1) \\<and> odd i \\<longrightarrow> f i = 0) \\<longrightarrow>\n            (\\<Sum>k\\<in>{0..<2^(1+1)}. f k) = (\\<Sum>k \\<in> {0..<2^1}. f (2*k))\"\n  proof(rule allI,rule impI)\n    fix f:: \"(nat \\<Rightarrow> complex)\"\n    assume asm: \"(\\<forall>i. i<2^(1+1) \\<and> odd i \\<longrightarrow> f i = 0)\" \n    moreover have \"(\\<Sum>k\\<in>{0..<4}. f k) = f 0 + f 1 + f 2 + f 3\" \n      by (simp add: add.commute add.left_commute)\n    moreover have \"f 1 = 0\" \n      using asm by simp \n    moreover have \"f 3 = 0\" \n      using asm by simp \n    moreover have \"(\\<Sum>k\\<in>{0..<2^1}. f (2*k)) = f 0 + f 2\" \n      using add.commute add.left_commute by simp\n    ultimately show \"(\\<Sum>k\\<in>{0..<2^(1+1)}. f k) = (\\<Sum>k\\<in>{0..<2^1}. f (2*k))\" \n      by simp\n  qed\nnext\n  fix n:: nat\n  assume \"n \\<ge> 1\"\n  and IH: \"\\<forall>f::(nat \\<Rightarrow>complex).(\\<forall>i. i<2^(n+1) \\<and> odd i \\<longrightarrow> f i = 0) \\<longrightarrow>\n(\\<Sum>k\\<in>{0..<2^(n+1)}. f k) = (\\<Sum>k\\<in>{0..<2^n}. f (2*k))\" \n  show \"\\<forall>f::(nat \\<Rightarrow>complex).(\\<forall>i. i<2^(Suc n +1) \\<and> odd i \\<longrightarrow> f i = 0) \\<longrightarrow>\n(\\<Sum>k\\<in>{0..<2^(Suc n +1)}. f k) = (\\<Sum>k\\<in>{0..< 2^(Suc n)}. f (2*k))\" \n  proof (rule allI,rule impI)\n    fix f::\"nat \\<Rightarrow> complex\"\n    assume asm: \"(\\<forall>i. i<2^(Suc n +1) \\<and> odd i \\<longrightarrow> f i = 0)\"\n    have f0: \"(\\<Sum>k\\<in>{0..<2^(n+1)}. f k) = (\\<Sum>k\\<in>{0..<2^n}. f (2*k))\" \n      using asm IH by simp\n    have f1: \"(\\<Sum>k\\<in>{0..<2^(n+1)}. (\\<lambda>x. f (x+2^(n+1))) k) = (\\<Sum>k\\<in>{0..< 2^n}. (\\<lambda>x. f (x+2^(n+1))) (2*k))\" \n      using asm IH by simp\n    have \"(\\<Sum>k\\<in>{0..<2^(n+2)}. f k) = (\\<Sum>k\\<in>{0..<2^(n+1)}. f k) + (\\<Sum>k\\<in>{2^(n+1)..<2^(n+2)}. f k)\"\n      by (simp add: sum.atLeastLessThan_concat)\n    also have \"... = (\\<Sum>k\\<in>{0..<2^n}. f (2*k)) + (\\<Sum>k\\<in>{2^(n+1)..<2^(n+2)}. f k)\"  \n      using f0 by simp\n    also have \"... = (\\<Sum>k\\<in>{0..<2^n}. f (2*k)) + (\\<Sum>k\\<in>{0..<2^(n+1)}. f (k+2^(n+1)))\"  \n      using sum.shift_bounds_nat_ivl[of \"f\" \"0\" \"2^(n+1)\" \"2^(n+1)\"] by simp\n    also have \"... = (\\<Sum>k\\<in>{0..<2^n}. f (2*k)) + (\\<Sum>k\\<in>{0..< 2^n}. (\\<lambda>x. f (x+2^(n+1))) (2*k))\"\n      using f1 by simp\n    also have \"... = (\\<Sum>k\\<in>{0..<2^n}. f (2*k)) + (\\<Sum>k\\<in>{2^n..< 2^(n+1)}. f (2 *k))\"\n      using sum.shift_bounds_nat_ivl[of \"\\<lambda>x. (f::nat\\<Rightarrow>complex) (2*(x-2^n)+2^(n+1))\" \"0\" \"2^n\" \"2^n\"] \n      by (simp add: mult_2)\n    also have \"... = (\\<Sum>k \\<in> {0..<2^(n+1)}. f (2*k))\" \n      by (metis Suc_eq_plus1 lessI less_imp_le_nat one_le_numeral power_increasing sum.atLeastLessThan_concat zero_le)\n    finally show \"(\\<Sum>k\\<in>{0..<2^((Suc n)+1)}. f k) = (\\<Sum>k\\<in>{0..< 2^(Suc n)}. f (2*k))\"\n      by (metis Suc_eq_plus1 add_2_eq_Suc')\n  qed\nqed\n\nlemma sum_every_even_summand_is_zero:\n  fixes n:: nat \n  assumes \"n \\<ge> 1\"\n  shows \"\\<forall>f::(nat \\<Rightarrow> complex).(\\<forall>i. i<2^(n+1) \\<and> even i \\<longrightarrow> f i = 0) \\<longrightarrow> \n            (\\<Sum>k\\<in>{0..<2^(n+1)}. f k) = (\\<Sum>k\\<in>{0..< 2^n}. f (2*k+1))\"\n  using assms\nproof(rule nat_induct_at_least)\n  show \"\\<forall>f::(nat \\<Rightarrow> complex).(\\<forall>i. i<2^(1+1) \\<and> even i \\<longrightarrow> f i = 0) \\<longrightarrow> \n            (\\<Sum>k\\<in>{0..<2^(1+1)}. f k) = (\\<Sum>k\\<in>{0..< 2^1}. f (2*k+1))\"\n  proof(rule allI,rule impI)\n    fix f:: \"nat \\<Rightarrow>complex\"\n    assume asm: \"(\\<forall>i. i<2^(1+1) \\<and> even i \\<longrightarrow> f i = 0)\" \n    moreover have \"(\\<Sum>k\\<in>{0..<4}. f k) = f 0 + f 1 + f 2 + f 3\" \n      by (simp add: add.commute add.left_commute)\n    moreover have \"f 0 = 0\" using asm by simp \n    moreover have \"f 2 = 0\" using asm by simp \n    moreover have \"(\\<Sum>k \\<in> {0..< 2^1}. f (2*k+1)) = f 1 + f 3\" \n      using add.commute add.left_commute by simp\n    ultimately show \"(\\<Sum>k\\<in>{0..<2^(1+1)}. f k) = (\\<Sum>k\\<in>{0..< 2^1}. f (2*k+1))\" by simp\n  qed\nnext\n  fix n:: nat\n  assume \"n \\<ge> 1\"\n  and IH: \"\\<forall>f::(nat \\<Rightarrow>complex).(\\<forall>i. i<2^(n+1) \\<and> even i \\<longrightarrow> f i = 0) \\<longrightarrow>\n(\\<Sum>k\\<in>{0..<2^(n+1)}. f k) = (\\<Sum>k\\<in>{0..< 2^n}. f (2*k+1))\" \n  show \"\\<forall>f::(nat \\<Rightarrow>complex).(\\<forall>i. i<2^((Suc n)+1) \\<and> even i \\<longrightarrow> f i = 0) \\<longrightarrow>\n(\\<Sum>k\\<in>{0..<2^((Suc n)+1)}. f k) = (\\<Sum>k\\<in>{0..< 2^(Suc n)}. f (2*k+1))\" \n  proof (rule allI,rule impI)\n    fix f::\"nat \\<Rightarrow>complex\"\n    assume asm: \"(\\<forall>i. i<2^((Suc n)+1) \\<and> even i \\<longrightarrow> f i = 0)\"\n    have f0: \"(\\<Sum>k \\<in>{0..<2^(n+1)}. f k) = (\\<Sum>k \\<in> {0..< 2^n}. f (2*k+1))\" \n      using asm IH by simp\n    have f1: \"(\\<Sum>k\\<in>{0..<2^(n+1)}. (\\<lambda>x. f (x+2^(n+1))) k) \n              = (\\<Sum>k\\<in>{0..< 2^n}. (\\<lambda>x. f (x+2^(n+1))) (2*k+1))\" \n      using asm IH by simp\n    have \"(\\<Sum>k\\<in>{0..<2^(n+2)}. f k) \n               = (\\<Sum>k\\<in>{0..<2^(n+1)}. f k) + (\\<Sum>k\\<in>{2^(n+1)..<2^(n+2)}. f k)\"\n      by (simp add: sum.atLeastLessThan_concat)\n    also have \"... = (\\<Sum>k\\<in>{0..< 2^n}. f (2*k+1)) + (\\<Sum>k\\<in>{2^(n+1)..<2^(n+2)}. f k)\"  \n      using f0 by simp\n    also have \"... = (\\<Sum>k\\<in>{0..< 2^n}. f (2*k+1)) + (\\<Sum>k\\<in>{0..<2^(n+1)}. f (k+(2^(n+1))))\"  \n      using sum.shift_bounds_nat_ivl[of \"f\" \"0\" \"2^(n+1)\" \"2^(n+1)\"] by simp\n    also have \"... = (\\<Sum>k\\<in>{0..< 2^n}. f (2*k+1)) + (\\<Sum>k\\<in>{0..< 2^n}. (\\<lambda>x. f (x+2^(n+1))) (2*k+1))\"\n      using f1 by simp\n    also have \"... = (\\<Sum>k\\<in>{0..< 2^n}. f (2*k+1)) + (\\<Sum>k\\<in>{2^n..< 2^(n+1)}. f (2 *k+1))\"\n      using sum.shift_bounds_nat_ivl[of \"\\<lambda>x. (f::nat\\<Rightarrow>complex) (2*(x-2^n)+1+2^(n+1))\" \"0\" \"2^n\" \"2^n\"] \n      by (simp add: mult_2)\n    also have \"... = (\\<Sum>k\\<in>{0..< 2^(n+1)}. f (2*k+1))\" \n      by (metis Suc_eq_plus1 lessI less_imp_le_nat one_le_numeral power_increasing sum.atLeastLessThan_concat zero_le)\n    finally show \"(\\<Sum>k\\<in>{0..<2^((Suc n)+1)}. f k) = (\\<Sum>k\\<in>{0..< 2^(Suc n)}. f (2*k+1))\"\n      by (metis Suc_eq_plus1 add_2_eq_Suc')\n  qed\nqed\n\nlemma (in jozsa) iter_tensor_of_H_times_\\<psi>\\<^sub>2_is_\\<psi>\\<^sub>3:\n  shows \"((H^\\<^sub>\\<otimes> n) \\<Otimes> Id 1) * \\<psi>\\<^sub>2 = \\<psi>\\<^sub>3\"\nproof\n  fix i j\n  assume a0:\"i < dim_row \\<psi>\\<^sub>3\" and a1:\"j < dim_col \\<psi>\\<^sub>3\" \n  then have f0: \"i < (2^(n+1)) \\<and> j = 0\" by simp\n  have f1: \"((HId^\\<^sub>\\<otimes> n)* \\<psi>\\<^sub>2) $$ (i,j) = (\\<Sum>k<(2^(n+1)). ((HId^\\<^sub>\\<otimes> n) $$ (i,k)) * (\\<psi>\\<^sub>2 $$ (k,j)))\" \n    using a1 f0 by (simp add: atLeast0LessThan)\n  show \"(((H^\\<^sub>\\<otimes> n) \\<Otimes> Id 1) * \\<psi>\\<^sub>2) $$ (i,j) = \\<psi>\\<^sub>3 $$ (i,j)\"\n  proof(rule disjE)\n    show \"even i \\<or> odd i\" by simp\n  next\n    assume a2: \"even i\"\n    have \"(\\<not>(i mod 2 = k mod 2) \\<and> k<dim_col (HId^\\<^sub>\\<otimes> n)) \\<longrightarrow> ((HId^\\<^sub>\\<otimes> n) $$ (i,k)) * (\\<psi>\\<^sub>2 $$ (k,j)) = 0\" for k \n      using f0 by simp\n    then have \"k<(2^(n+1)) \\<and> odd k \\<longrightarrow> ((HId^\\<^sub>\\<otimes> n) $$ (i,k)) * (\\<psi>\\<^sub>2 $$ (k,j)) = 0\" for k \n      using a2 mod_2_is_both_even_or_odd f0 by (metis (no_types, lifting) dim_col_mat(1))\n    then have \"(\\<Sum>k\\<in>{(0::nat)..<(2^(n+1))}. ((HId^\\<^sub>\\<otimes> n) $$ (i,k)) * (\\<psi>\\<^sub>2 $$ (k,j)))\n             = (\\<Sum>k\\<in>{(0::nat)..< (2^n)}. ((HId^\\<^sub>\\<otimes> n) $$ (i,2*k)) * (\\<psi>\\<^sub>2 $$ (2*k,j)))\" \n      using sum_every_odd_summand_is_zero dim by simp\n    moreover have \"(\\<Sum>k<2^n. ((HId^\\<^sub>\\<otimes> n) $$ (i,2*k)) * (\\<psi>\\<^sub>2 $$ (2*k,j))) \n                 = (\\<Sum>k<2^n.(-1)^((i div 2) \\<cdot>\\<^bsub>n\\<^esub> k)/(sqrt(2)^n) *((-1)^f(k))/(sqrt(2)^(n+1)))\" \n    proof-\n        have \"(even k \\<and> k<dim_row \\<psi>\\<^sub>2) \\<longrightarrow> (\\<psi>\\<^sub>2 $$ (k,j)) = ((-1)^f(k div 2))/(sqrt(2)^(n+1))\" for k \n          using a0 a1 by simp\n      then have \"(\\<Sum>k<2^n. ((HId^\\<^sub>\\<otimes> n) $$ (i,2*k)) * (\\<psi>\\<^sub>2 $$ (2*k,j))) \n               = (\\<Sum>k<2^n. ((HId^\\<^sub>\\<otimes> n) $$ (i,2*k)) *((-1)^f((2*k) div 2))/(sqrt(2)^(n+1)))\" \n        by simp\n      moreover have \"(even k \\<and> k<dim_col (HId^\\<^sub>\\<otimes> n))\n                 \\<longrightarrow> ((HId^\\<^sub>\\<otimes> n) $$ (i,k)) = (-1)^ ((i div 2) \\<cdot>\\<^bsub>n\\<^esub> (k div 2))/(sqrt(2)^n)\" for k\n        using a2 a0 a1 by simp\n      ultimately have \"(\\<Sum>k<2^n. ((HId^\\<^sub>\\<otimes> n) $$ (i,2*k)) * (\\<psi>\\<^sub>2 $$ (2*k,j))) \n                     = (\\<Sum>k<2^n. (-1)^((i div 2) \\<cdot>\\<^bsub>n\\<^esub>  ((2*k) div 2))/(sqrt(2)^n) * \n                                   ((-1)^f((2*k) div 2))/(sqrt(2)^(n+1)))\" \n      by simp\n      then show \"(\\<Sum>k<2^n. ((HId^\\<^sub>\\<otimes> n) $$ (i,2*k)) * (\\<psi>\\<^sub>2 $$ (2*k,j))) \n               = (\\<Sum>k<2^n. (-1)^((i div 2) \\<cdot>\\<^bsub>n\\<^esub>  k)/(sqrt(2)^n) *((-1)^f(k))/(sqrt(2)^(n+1)))\" \n        by simp\n    qed\n    ultimately have \"((HId^\\<^sub>\\<otimes> n)* \\<psi>\\<^sub>2) $$ (i,j) = (\\<Sum>k<2^n. (-1)^((i div 2) \\<cdot>\\<^bsub>n\\<^esub> k)/(sqrt(2)^n) \n                                                        * ((-1)^f(k))/(sqrt(2)^(n+1)))\" \n      using f1 by (metis atLeast0LessThan) \n    also have \"... =  (\\<Sum>k<2^n. (-1)^(f(k)+((i div 2) \\<cdot>\\<^bsub>n\\<^esub> k))/((sqrt(2)^n)*(sqrt(2)^(n+1))))\" \n      by (simp add: power_add mult.commute)\n    finally have \"((HId^\\<^sub>\\<otimes> n)* \\<psi>\\<^sub>2) $$ (i,j) = (\\<Sum>k<2^n. (-1)^(f(k)+((i div 2) \\<cdot>\\<^bsub>n\\<^esub> k))/((sqrt(2)^n)*(sqrt(2)^(n+1))))\" \n       by simp\n    moreover have \"\\<psi>\\<^sub>3 $$ (i,j) = (\\<Sum>k<2^n. (-1)^(f(k) + ((i div 2) \\<cdot>\\<^bsub>n\\<^esub> k))/(sqrt(2)^n * sqrt(2)^(n+1)))\" \n      using a0 a1 a2 by simp\n    ultimately show \"(((H^\\<^sub>\\<otimes> n) \\<Otimes> Id 1)* \\<psi>\\<^sub>2) $$ (i,j) = \\<psi>\\<^sub>3 $$ (i,j)\" \n      using iter_tensor_of_H_tensor_Id_is_HId dim by simp\n  next\n    assume a2: \"odd i\"\n    have \"(\\<not>(i mod 2 = k mod 2) \\<and> k<dim_col (HId^\\<^sub>\\<otimes> n)) \\<longrightarrow> ((HId^\\<^sub>\\<otimes> n) $$ (i,k)) * (\\<psi>\\<^sub>2 $$ (k,j)) = 0\" for k \n      using f0 by simp\n    then have \"k<(2^(n+1)) \\<and> even k \\<longrightarrow> ((HId^\\<^sub>\\<otimes> n) $$ (i,k)) * (\\<psi>\\<^sub>2 $$ (k,j)) = 0\" for k \n      using a2 mod_2_is_both_even_or_odd f0 by (metis (no_types, lifting) dim_col_mat(1))\n    then have \"(\\<Sum>k\\<in>{0..<2^(n+1)}. ((HId^\\<^sub>\\<otimes> n) $$ (i,k)) * (\\<psi>\\<^sub>2 $$ (k,j)))\n             = (\\<Sum>k\\<in>{0..<2^n}. ((HId^\\<^sub>\\<otimes> n) $$ (i,2*k+1)) * (\\<psi>\\<^sub>2 $$ (2*k+1,j)))\" \n      using sum_every_even_summand_is_zero dim by simp\n    moreover have \"(\\<Sum>k<2^n. ((HId^\\<^sub>\\<otimes> n) $$ (i,2*k+1)) * (\\<psi>\\<^sub>2 $$ (2*k+1,j))) \n                 = (\\<Sum> k<2^n. (-1)^((i div 2) \\<cdot>\\<^bsub>n\\<^esub> k)/(sqrt(2)^n) * ((-1)^(f(k)+1))/(sqrt(2)^(n+1)))\" \n    proof-\n      have \"(odd k \\<and> k<dim_row \\<psi>\\<^sub>2) \\<longrightarrow> (\\<psi>\\<^sub>2 $$ (k,j)) = ((-1)^(f(k div 2)+1))/(sqrt(2)^(n+1))\" for k \n        using a0 a1 a2 by simp\n      then have f2:\"(\\<Sum>k<2^n. ((HId^\\<^sub>\\<otimes> n) $$ (i,2*k+1)) * (\\<psi>\\<^sub>2 $$ (2*k+1,j))) \n                  = (\\<Sum>k<2^n. ((HId^\\<^sub>\\<otimes> n) $$ (i,2*k+1)) * ((-1)^(f((2*k+1) div 2)+1))/(sqrt(2)^(n+1)))\" \n        by simp\n      have \"i < dim_row (HId^\\<^sub>\\<otimes> n)\" \n        using f0 a2 mod_2_is_both_even_or_odd by simp\n      then have \"((i mod 2 = k mod 2) \\<and> k<dim_col (HId^\\<^sub>\\<otimes> n))\n                 \\<longrightarrow> ((HId^\\<^sub>\\<otimes> n) $$ (i,k)) = (-1)^((i div 2) \\<cdot>\\<^bsub>n\\<^esub> (k div 2))/(sqrt(2)^n) \" for k\n        using a2 a0 a1 f0 dim HId_values by simp\n      moreover have \"odd k \\<longrightarrow> (i mod 2 = k mod 2)\" for k \n        using a2 mod_2_is_both_even_or_odd by auto\n      ultimately have \"(odd k \\<and> k<dim_col (HId^\\<^sub>\\<otimes> n))\n                 \\<longrightarrow> ((HId^\\<^sub>\\<otimes> n) $$ (i,k)) = (-1)^((i div 2) \\<cdot>\\<^bsub>n\\<^esub> (k div 2))/(sqrt(2)^n)\" for k\n        by simp\n      then have \"k<2^n \\<longrightarrow> ((HId^\\<^sub>\\<otimes> n) $$ (i,2*k+1)) = (-1)^((i div 2) \\<cdot>\\<^bsub>n\\<^esub> ((2*k+1) div 2))/(sqrt(2)^n) \" for k\n        by simp\n      then have \"(\\<Sum>k<2^n. ((HId^\\<^sub>\\<otimes> n) $$ (i,2*k+1)) * (\\<psi>\\<^sub>2 $$ (2*k+1,j))) \n               = (\\<Sum>k<2^n. (-1)^((i div 2) \\<cdot>\\<^bsub>n\\<^esub> ((2*k+1) div 2))/(sqrt(2)^n) \n                             * ((-1)^(f((2*k+1) div 2)+1))/(sqrt(2)^(n+1)))\" \n        using f2 by simp\n      then show \"(\\<Sum>k<2^n. ((HId^\\<^sub>\\<otimes> n) $$ (i,2*k+1)) * (\\<psi>\\<^sub>2 $$ (2*k+1,j))) \n               = (\\<Sum>k<2^n. (-1)^((i div 2) \\<cdot>\\<^bsub>n\\<^esub> k)/(sqrt(2)^n) *((-1)^(f(k)+1))/(sqrt(2)^(n+1)))\" \n        by simp\n    qed\n    ultimately have \"((HId^\\<^sub>\\<otimes> n)* \\<psi>\\<^sub>2) $$ (i,j) = (\\<Sum>k<2^n. (-1)^((i div 2) \\<cdot>\\<^bsub>n\\<^esub> k)/(sqrt(2)^n) \n                * ((-1)^(f(k)+1))/(sqrt(2)^(n+1)))\" \n      using f1 by (metis atLeast0LessThan) \n    also have \"... = (\\<Sum>k<2^n. (-1)^(f(k)+1+((i div 2) \\<cdot>\\<^bsub>n\\<^esub> k))/((sqrt(2)^n)*(sqrt(2)^(n+1))))\"\n      by (simp add: mult.commute power_add)\n    finally have \"((HId^\\<^sub>\\<otimes> n)* \\<psi>\\<^sub>2) $$ (i,j) \n                = (\\<Sum>k< 2^n. (-1)^(f(k)+1+((i div 2) \\<cdot>\\<^bsub>n\\<^esub> k))/((sqrt(2)^n)*(sqrt(2)^(n+1))))\" \n      by simp\n    then show \"(((H^\\<^sub>\\<otimes> n) \\<Otimes> Id 1)* \\<psi>\\<^sub>2) $$ (i,j) = \\<psi>\\<^sub>3 $$ (i,j)\" \n      using iter_tensor_of_H_tensor_Id_is_HId dim a2 a0 a1 by simp\n  qed\nnext\n  show \"dim_row (((H^\\<^sub>\\<otimes> n) \\<Otimes> Id 1) * \\<psi>\\<^sub>2) = dim_row \\<psi>\\<^sub>3\"  \n    using iter_tensor_of_H_tensor_Id_is_HId dim by simp\nnext\n  show \"dim_col (((H^\\<^sub>\\<otimes> n) \\<Otimes> Id 1)* \\<psi>\\<^sub>2) = dim_col \\<psi>\\<^sub>3\" \n    using iter_tensor_of_H_tensor_Id_is_HId dim by simp\nqed\n\nlemma (in jozsa) \\<psi>\\<^sub>3_is_state:\n  shows \"state (n+1) \\<psi>\\<^sub>3\"\nproof-\n  have \"((H^\\<^sub>\\<otimes> n) \\<Otimes> Id 1) * \\<psi>\\<^sub>2 = \\<psi>\\<^sub>3\" \n    using iter_tensor_of_H_times_\\<psi>\\<^sub>2_is_\\<psi>\\<^sub>3 by simp\n  moreover have \"gate (n+1) ((H^\\<^sub>\\<otimes> n) \\<Otimes> Id 1)\" \n    using iter_tensor_of_H_tensor_Id_is_HId HId_is_gate dim by simp\n  moreover have \"state (n+1) \\<psi>\\<^sub>2\" \n    using \\<psi>\\<^sub>2_is_state by simp\n  ultimately show \"state (n+1) \\<psi>\\<^sub>3\"\n    using gate_on_state_is_state dim by (metis (no_types, lifting))\nqed\n\ntext \\<open>\nFinally, all steps are put together. The result depends on the function f. If f is constant\nthe first n qubits are 0, if f is balanced there is at least one qubit in state 1 among the \nfirst n qubits. \nThe algorithm only uses one evaluation of f(x) and will always succeed. \n\\<close>\n\ndefinition (in jozsa) jozsa_algo:: \"complex Matrix.mat\" where \n\"jozsa_algo \\<equiv> ((H \\<otimes>\\<^bsup>n\\<^esup>) \\<Otimes> Id 1) * (U\\<^sub>f * (((H \\<otimes>\\<^bsup>n\\<^esup>) * ( |zero\\<rangle> \\<otimes>\\<^bsup>n\\<^esup>)) \\<Otimes> (H * |one\\<rangle>)))\"\n\nlemma (in jozsa) jozsa_algo_result [simp]: \n  shows \"jozsa_algo = \\<psi>\\<^sub>3\" \n  using jozsa_algo_def H_on_ket_one_is_\\<psi>\\<^sub>1\\<^sub>1 iter_tensor_of_H_on_zero_tensor \\<psi>\\<^sub>1\\<^sub>0_tensor_\\<psi>\\<^sub>1\\<^sub>1_is_\\<psi>\\<^sub>1\n  jozsa_transform_times_\\<psi>\\<^sub>1_is_\\<psi>\\<^sub>2 iter_tensor_of_H_times_\\<psi>\\<^sub>2_is_\\<psi>\\<^sub>3 dim iter_tensor_of_H_rep_is_correct \n  by simp\n\nlemma (in jozsa) jozsa_algo_result_is_state: \n  shows \"state (n+1) jozsa_algo\" \n  using \\<psi>\\<^sub>3_is_state by simp\n\nlemma (in jozsa) prob0_fst_qubits_of_jozsa_algo: \n  shows \"(prob0_fst_qubits n jozsa_algo) = (\\<Sum>j\\<in>{0,1}. (cmod(jozsa_algo $$ (j,0)))\\<^sup>2)\"\n  using prob0_fst_qubits_eq by simp\n\ntext \\<open>General lemmata required to compute probabilities.\\<close>\n\nlemma aux_comp_with_sqrt2:\n  shows \"(sqrt 2)^n * (sqrt 2)^n = 2^n\"\n  by (smt power_mult_distrib real_sqrt_mult_self)\n\nlemma aux_comp_with_sqrt2_bis [simp]:\n  shows \"2^n/(sqrt(2)^n * sqrt(2)^(n+1)) = 1/sqrt 2\"\n  using aux_comp_with_sqrt2 by (simp add: mult.left_commute)\n\nlemma aux_ineq_with_card: \n  fixes g:: \"nat \\<Rightarrow> nat\" and A:: \"nat set\"\n  assumes \"finite A\" \n  shows \"(\\<Sum>k\\<in>A. (-1)^(g k)) \\<le> card A\" and \"(\\<Sum>k\\<in>A. (-1)^(g k)) \\<ge> -card A\" \n   apply (smt assms neg_one_even_power neg_one_odd_power card_eq_sum of_nat_1 of_nat_sum sum_mono)\n  apply (smt assms neg_one_even_power neg_one_odd_power card_eq_sum of_nat_1 of_nat_sum sum_mono sum_negf).\n\nlemma aux_comp_with_cmod:\n  fixes g:: \"nat \\<Rightarrow> nat\"\n  assumes \"(\\<forall>x<2^n. g x = 0) \\<or> (\\<forall>x<2^n. g x = 1)\"\n  shows \"(cmod (\\<Sum>k<2^n. (-1)^(g k)))\\<^sup>2  = 2^(2*n)\"\nproof(rule disjE)\n  show \"(\\<forall>x<2^n. g x = 0) \\<or> (\\<forall>x<2^n. g x = 1)\" \n    using assms by simp\nnext\n  assume \"\\<forall>x<2^n. g x = 0\"\n  then have \"(cmod (\\<Sum>k<2^n. (-1)^(g k)))\\<^sup>2 = (2^n)\\<^sup>2\" \n    by (simp add: norm_power)\n  then show \"?thesis\" \n    by (simp add: power_even_eq)\nnext \n  assume \"\\<forall>x<2^n. g x = 1\" \n  then have \"(cmod (\\<Sum>k<2^n. (-1)^(g k)))\\<^sup>2 = (2^n)\\<^sup>2\" \n    by (simp add: norm_power)\n  then show \"?thesis\" \n    by (simp add: power_even_eq)\nqed\n\nlemma cmod_less:\n  fixes a n:: int\n  assumes \"a < n\" and \"a > -n\"\n  shows \"cmod a < n\" \n  using assms by simp\n\nlemma square_less:\n  fixes a n:: real\n  assumes \"a < n\" and \"a > -n\" \n  shows \"a\\<^sup>2 < n\\<^sup>2\"\n  using assms by (smt power2_eq_iff power2_minus power_less_imp_less_base)\n\nlemma cmod_square_real [simp]:\n  fixes n:: real\n  shows \"(cmod n)\\<^sup>2 = n\\<^sup>2\" \n  by simp\n\nlemma aux_comp_sum_divide_cmod:\n  fixes n:: nat and g:: \"nat \\<Rightarrow> int\" and a:: real\n  shows \"(cmod(complex_of_real(\\<Sum>k<n. g k / a)))\\<^sup>2 = (cmod (\\<Sum>k<n. g k) / a)\\<^sup>2\"\n  by (metis cmod_square_real of_int_sum of_real_of_int_eq power_divide sum_divide_distrib)\n\n\ntext \\<open>\nThe function is constant if and only if the first n qubits are 0. So, if the function is constant, \nthen the probability of measuring 0 for the first n qubits is 1.\n\\<close>\n\nlemma (in jozsa) prob0_jozsa_algo_of_const_0:\n  assumes \"const 0\"\n  shows \"prob0_fst_qubits n jozsa_algo = 1\"\nproof-\n  have \"prob0_fst_qubits n jozsa_algo = (\\<Sum>j\\<in>{0,1}. (cmod(jozsa_algo $$ (j,0)))\\<^sup>2)\"\n    using prob0_fst_qubits_of_jozsa_algo by simp\n  moreover have \"(cmod(jozsa_algo $$ (0,0)))\\<^sup>2 = 1/2\"\n  proof-\n    have \"k<2^n \\<longrightarrow> ((0 div 2) \\<cdot>\\<^bsub>n\\<^esub>  k) = 0\" for k::nat \n      using bitwise_inner_prod_with_zero by simp \n    then have \"(cmod(jozsa_algo $$ (0,0)))\\<^sup>2 = (cmod(\\<Sum>k::nat<2^n. 1/(sqrt(2)^n * sqrt(2)^(n+1))))\\<^sup>2\" \n      using jozsa_algo_result const_def assms by simp\n    also have \"... = (cmod((2::nat)^n/(sqrt(2)^n * sqrt(2)^(n+1))))\\<^sup>2\"  by simp\n    also have \"... = (cmod(1/(sqrt(2))))\\<^sup>2\" \n      using aux_comp_with_sqrt2_bis by simp\n    also have \"... = 1/2\" \n      by (simp add: norm_divide power2_eq_square)\n    finally show \"?thesis\" by simp\n  qed\n  moreover have \"(cmod(jozsa_algo $$ (1,0)))\\<^sup>2 = 1/2\"\n  proof-\n    have \"k<2^n \\<longrightarrow> ((1 div 2) \\<cdot>\\<^bsub>n\\<^esub>  k) = 0\" for k:: nat\n      using bitwise_inner_prod_with_zero by simp\n    then have \"k<2^n \\<longrightarrow> f k + 1 + ((1 div 2) \\<cdot>\\<^bsub>n\\<^esub>  k) = 1\" for k::nat \n      using const_def assms by simp\n    moreover have \"(cmod(jozsa_algo $$ (1,0)))\\<^sup>2 \n    = (cmod (\\<Sum>k::nat<2^n. (-1)^(f k + 1 + ((1 div 2) \\<cdot>\\<^bsub>n\\<^esub> k))/(sqrt(2)^n * sqrt(2)^(n+1))))\\<^sup>2\"\n      using \\<psi>\\<^sub>3_dim by simp\n    ultimately have \"(cmod(jozsa_algo $$ (1,0)))\\<^sup>2 = (cmod(\\<Sum>k::nat<2^n. -1/(sqrt(2)^n * sqrt(2)^(n+1))))\\<^sup>2\"\n      by (smt lessThan_iff power_one_right sum.cong)\n    also have \"... = (cmod(-1/(sqrt(2))))\\<^sup>2\" \n      using aux_comp_with_sqrt2_bis by simp\n    also have \"... = 1/2\" \n      by (simp add: norm_divide power2_eq_square)\n    finally show \"?thesis\" by simp\n  qed\n  ultimately have \"prob0_fst_qubits n jozsa_algo = 1/2 + 1/2\" by simp\n  then show  \"?thesis\" by simp\nqed\n\nlemma (in jozsa) prob0_jozsa_algo_of_const_1:\n  assumes \"const 1\"\n  shows \"prob0_fst_qubits n jozsa_algo = 1\"\nproof-\n  have \"prob0_fst_qubits n jozsa_algo = (\\<Sum>j\\<in>{0,1}. (cmod(jozsa_algo $$ (j,0)))\\<^sup>2)\"\n    using prob0_fst_qubits_of_jozsa_algo by simp\n  moreover have \"(cmod(jozsa_algo $$ (0,0)))\\<^sup>2 = 1/2\"\n  proof-\n     have \"k<2^n \\<longrightarrow> ((0 div 2) \\<cdot>\\<^bsub>n\\<^esub>  k) = 0\" for k::nat\n      using bitwise_inner_prod_with_zero by simp \n    then have \"(cmod(jozsa_algo $$ (0,0)))\\<^sup>2 = (cmod(\\<Sum>k::nat<2^n. 1/(sqrt(2)^n * sqrt(2)^(n+1))))\\<^sup>2\" \n      using jozsa_algo_result const_def assms by simp\n    also have \"... = (cmod((-1)/(sqrt(2))))\\<^sup>2 \" \n      using aux_comp_with_sqrt2_bis by simp\n    also have \"... = 1/2\" \n      by (simp add: norm_divide power2_eq_square)\n    finally show \"?thesis\" by simp\n  qed\n  moreover have \"(cmod(jozsa_algo $$ (1,0)))\\<^sup>2 = 1/2\"\n  proof-\n    have \"k<2^n \\<longrightarrow> ((1 div 2) \\<cdot>\\<^bsub>n\\<^esub>  k) = 0\" for k::nat\n      using bitwise_inner_prod_with_zero by simp\n    then have \"(\\<Sum>k::nat<2^n. (-1)^(f k +1 + ((1 div 2) \\<cdot>\\<^bsub>n\\<^esub>  k))/(sqrt(2)^n * sqrt(2)^(n+1)))\n             = (\\<Sum>k::nat<2^n. 1/(sqrt(2)^n * sqrt(2)^(n+1)))\"\n      using const_def assms by simp\n    moreover have \"(cmod(jozsa_algo $$ (1,0)))\\<^sup>2 \n    = (cmod (\\<Sum>k::nat<2^n. (-1)^(f k + 1 + ((1 div 2) \\<cdot>\\<^bsub>n\\<^esub>  k))/(sqrt(2)^n * sqrt(2)^(n+1))))\\<^sup>2\"\n      using  \\<psi>\\<^sub>3_dim by simp\n    ultimately have \"(cmod(jozsa_algo $$ (1,0)))\\<^sup>2 = (cmod(\\<Sum>k::nat<2^n. 1/(sqrt(2)^n * sqrt(2)^(n+1))))\\<^sup>2\" by simp\n    also have \"... = (cmod(1/(sqrt(2))))\\<^sup>2 \" \n      using aux_comp_with_sqrt2_bis by simp\n    also have \"... = 1/2\" \n      by (simp add: norm_divide power2_eq_square)\n    finally show \"?thesis\" by simp\n  qed\n  ultimately have \"prob0_fst_qubits n jozsa_algo = 1/2 + 1/2\" by simp\n  then show  \"?thesis\" by simp\nqed\n\ntext \\<open>If the probability of measuring 0 for the first n qubits is 1, then the function is constant.\\<close>\n\nlemma (in jozsa) max_value_of_not_const_less:\n  assumes \"\\<not> const 0\" and \"\\<not> const 1\"\n  shows \"(cmod (\\<Sum>k::nat<2^n. (-(1::nat))^(f k)))\\<^sup>2 < (2::nat)^(2*n)\"\nproof-\n  have \"cmod (\\<Sum>k::nat<2^n. (-(1::nat))^(f k)) < 2^n\"\n  proof-\n    have \"(\\<Sum>k::nat<2^n. (-(1::nat))^(f k)) < 2^n\"\n    proof-\n      obtain x where f0:\"x < 2^n\" and f1:\"f x = 1\"\n        using assms(1) const_def f_values by auto\n      then have \"(\\<Sum>k::nat<2^n. (-(1::nat))^(f k)) < (\\<Sum>k\\<in>{i| i:: nat. i < 2^n}-{x}. (-(1::nat))^(f k))\"\n      proof-\n        have \"(-(1::nat))^ f x = -1\" using f1 by simp\n        moreover have \"x\\<in>{i| i::nat. i<2^n}\" using f0 by simp\n        moreover have \"finite {i| i::nat. i<2^n}\" by simp\n        moreover have \"(\\<Sum>k\\<in>{i| i::nat. i<2^n}. (-(1::nat))^(f k)) < \n(\\<Sum>k\\<in>{i| i:: nat. i<2^n}-{x}. (-(1::nat))^(f k))\"\n          using calculation(1,2,3) sum_diff1 by (simp add: sum_diff1)\n        ultimately show ?thesis by (metis Collect_cong Collect_mem_eq lessThan_iff)\n      qed\n      moreover have \"\\<dots> \\<le> int (2^n - 1)\"\n        using aux_ineq_with_card(1)[of \"{i| i:: nat. i<2^n}-{x}\"] f0 by simp\n      ultimately show ?thesis\n        by (meson diff_le_self less_le_trans of_nat_le_numeral_power_cancel_iff)\n   qed\n   moreover have \"(\\<Sum>k::nat<2^n. (-(1::nat))^(f k)) > - (2^n)\"\n   proof-\n      obtain x where f0:\"x < 2^n\" and f1:\"f x = 0\"\n        using assms(2) const_def f_values by auto\n      then have \"(\\<Sum>k::nat<2^n. (-(1::nat))^(f k)) > (\\<Sum>k\\<in>{i| i:: nat. i < 2^n}-{x}. (-(1::nat))^(f k))\"\n      proof-\n        have \"(-(1::nat))^ f x = 1\" using f1 by simp\n        moreover have \"x\\<in>{i| i::nat. i<2^n}\" using f0 by simp\n        moreover have \"finite {i| i::nat. i<2^n}\" by simp\n        moreover have \"(\\<Sum>k\\<in>{i| i::nat. i<2^n}. (-(1::nat))^(f k)) > \n(\\<Sum>k\\<in>{i| i:: nat. i<2^n}-{x}. (-(1::nat))^(f k))\"\n          using calculation(1,2,3) sum_diff1 by (simp add: sum_diff1)\n        ultimately show ?thesis by (metis Collect_cong Collect_mem_eq lessThan_iff)\n      qed\n      moreover have \"- int (2^n - 1) \\<le> (\\<Sum>k\\<in>{i| i:: nat. i < 2^n}-{x}. (-(1::nat))^(f k))\"\n        using aux_ineq_with_card(2)[of \"{i| i:: nat. i<2^n}-{x}\"] f0 by simp\n      ultimately show ?thesis\n        by (smt diff_le_self of_nat_1 of_nat_add of_nat_power_le_of_nat_cancel_iff one_add_one)\n   qed\n   ultimately show ?thesis\n     using cmod_less of_int_of_nat_eq of_nat_numeral of_nat_power by (metis (no_types, lifting))\n  qed\n  then have \"(cmod (\\<Sum>k::nat<2^n. (-(1::nat))^(f k)))\\<^sup>2 < (2^n)\\<^sup>2\"\n    using square_less norm_ge_zero by smt\n  thus ?thesis\n    by (simp add: power_even_eq)\nqed\n\nlemma (in jozsa) max_value_of_not_const_less_bis:\n  assumes \"\\<not> const 0\" and \"\\<not> const 1\"\n  shows \"(cmod (\\<Sum>k::nat<2^n. (-(1::nat))^(f k + 1)))\\<^sup>2 < (2::nat)^(2*n)\"\nproof-\n  have \"cmod (\\<Sum>k::nat<2^n. (-(1::nat))^(f k + 1)) < 2^n\"\n  proof-\n    have \"(\\<Sum>k::nat<2^n. (-(1::nat))^(f k + 1)) < 2^n\"\n    proof-\n      obtain x where f0:\"x < 2^n\" and f1:\"f x = 0\"\n        using assms(2) const_def f_values by auto\n      then have \"(\\<Sum>k::nat<2^n. (-(1::nat))^(f k + 1)) < (\\<Sum>k\\<in>{i| i:: nat. i < 2^n}-{x}. (-(1::nat))^(f k + 1))\"\n      proof-\n        have \"(-(1::nat))^ (f x + 1) = -1\" using f1 by simp\n        moreover have \"x\\<in>{i| i::nat. i<2^n}\" using f0 by simp\n        moreover have \"finite {i| i::nat. i<2^n}\" by simp\n        moreover have \"(\\<Sum>k\\<in>{i| i::nat. i<2^n}. (-(1::nat))^(f k + 1)) < \n(\\<Sum>k\\<in>{i| i:: nat. i<2^n}-{x}. (-(1::nat))^(f k + 1))\"\n          using calculation(1,2,3) sum_diff1 by (simp add: sum_diff1)\n        ultimately show ?thesis by (metis Collect_cong Collect_mem_eq lessThan_iff)\n      qed\n      moreover have \"\\<dots> \\<le> int (2^n - 1)\"\n        using aux_ineq_with_card(1)[of \"{i| i:: nat. i<2^n}-{x}\" \"\\<lambda>k. f k + 1\"] f0 by simp\n      ultimately show ?thesis\n        by (meson diff_le_self less_le_trans of_nat_le_numeral_power_cancel_iff)\n   qed\n   moreover have \"(\\<Sum>k::nat<2^n. (-(1::nat))^(f k + 1)) > - (2^n)\"\n   proof-\n      obtain x where f0:\"x < 2^n\" and f1:\"f x = 1\"\n        using assms(1) const_def f_values by auto\n      then have \"(\\<Sum>k::nat<2^n. (-(1::nat))^(f k + 1)) > (\\<Sum>k\\<in>{i| i:: nat. i < 2^n}-{x}. (-(1::nat))^(f k + 1))\"\n      proof-\n        have \"(-(1::nat))^ (f x + 1) = 1\" using f1 by simp\n        moreover have \"x\\<in>{i| i::nat. i<2^n}\" using f0 by simp\n        moreover have \"finite {i| i::nat. i<2^n}\" by simp\n        moreover have \"(\\<Sum>k\\<in>{i| i::nat. i<2^n}. (-(1::nat))^(f k + 1)) > \n(\\<Sum>k\\<in>{i| i:: nat. i<2^n}-{x}. (-(1::nat))^(f k + 1))\"\n          using calculation(1,2,3) sum_diff1 by (simp add: sum_diff1)\n        ultimately show ?thesis by (metis Collect_cong Collect_mem_eq lessThan_iff)\n      qed\n      moreover have \"- int (2^n - 1) \\<le> (\\<Sum>k\\<in>{i| i:: nat. i < 2^n}-{x}. (-(1::nat))^(f k + 1))\"\n        using aux_ineq_with_card(2)[of \"{i| i:: nat. i<2^n}-{x}\" \"\\<lambda>k. f k + 1\"] f0 by simp\n      ultimately show ?thesis\n        by (smt diff_le_self of_nat_1 of_nat_add of_nat_power_le_of_nat_cancel_iff one_add_one)\n   qed\n   ultimately show ?thesis\n     using cmod_less of_int_of_nat_eq of_nat_numeral of_nat_power by (metis (no_types, lifting))\n  qed\n  then have \"(cmod (\\<Sum>k::nat<2^n. (-(1::nat))^(f k + 1)))\\<^sup>2 < (2^n)\\<^sup>2\"\n    using square_less norm_ge_zero by smt\n  thus ?thesis\n    by (simp add: power_even_eq)\nqed\n\nlemma (in jozsa) f_const_has_max_value: \n  assumes \"const 0 \\<or> const 1\"\n  shows \"(cmod (\\<Sum>k<(2::nat)^n. (-1)^(f k)))\\<^sup>2 = (2::nat)^(2*n)\" \n  and \"(cmod (\\<Sum>k<(2::nat)^n. (-1)^(f k + 1)))\\<^sup>2 = (2::nat)^(2*n)\" \n  using aux_comp_with_cmod[of n \"\\<lambda>k. f k\"] aux_comp_with_cmod[of n \"\\<lambda>k. f k + 1\"] const_def assms by auto\n\nlemma (in jozsa) prob0_fst_qubits_leq:\n  shows \"(cmod (\\<Sum>k<(2::nat)^n. (-1)^(f k)))\\<^sup>2 \\<le> (2::nat)^(2*n)\" \n    and \"(cmod (\\<Sum>k<(2::nat)^n. (-1)^(f k + 1)))\\<^sup>2 \\<le> (2::nat)^(2*n)\"  \nproof-\n  show \"(cmod (\\<Sum>k<(2::nat)^n. (-1)^(f k)))\\<^sup>2 \\<le> (2::nat)^(2*n)\" \n  proof(rule disjE)\n    show \"(const 0 \\<or> const 1) \\<or> (\\<not> const 0 \\<and> \\<not> const 1)\" by auto\n  next\n    assume \"const 0 \\<or> const 1\" \n    then show \"(cmod (\\<Sum>k<(2::nat)^n. (-1)^(f k)))\\<^sup>2 \\<le> (2::nat)^(2*n)\" \n      using f_const_has_max_value by simp\n  next\n    assume \"\\<not> const 0 \\<and> \\<not> const 1\"\n    then show \"(cmod (\\<Sum>k<(2::nat)^n. (-1)^(f k)))\\<^sup>2 \\<le> (2::nat)^(2*n)\" \n      using max_value_of_not_const_less by simp\n  qed\nnext\n  show \"(cmod (\\<Sum>k<(2::nat)^n. (-1)^(f k + 1)))\\<^sup>2 \\<le> (2::nat)^(2*n)\" \n  proof(rule disjE)\n    show \"(const 0 \\<or> const 1) \\<or> (\\<not> const 0 \\<and> \\<not> const 1)\" by auto\n  next\n    assume \"const 0 \\<or> const 1\" \n    then show \"(cmod (\\<Sum>k<(2::nat)^n. (-1)^(f k + 1)))\\<^sup>2 \\<le> (2::nat)^(2*n)\" \n      using f_const_has_max_value by simp\n  next\n    assume \"\\<not> const 0 \\<and> \\<not> const 1\"\n    then show \"(cmod (\\<Sum>k<(2::nat)^n. (-1)^(f k + 1)))\\<^sup>2 \\<le> (2::nat)^(2*n)\" \n      using max_value_of_not_const_less_bis by simp\n  qed\nqed\n\nlemma (in jozsa) prob0_jozsa_algo_1_is_const:\n  assumes \"prob0_fst_qubits n jozsa_algo = 1\"\n  shows \"const 0 \\<or> const 1\"\nproof-\n  have f0: \"(\\<Sum>j\\<in>{0,1}. (cmod(jozsa_algo $$ (j,0)))\\<^sup>2) = 1\"\n    using prob0_fst_qubits_of_jozsa_algo assms by simp\n  have \"k < 2^n\\<longrightarrow>((0 div 2) \\<cdot>\\<^bsub>n\\<^esub>  k) = 0\" for k::nat\n    using bitwise_inner_prod_with_zero by simp \n  then have f1: \"(cmod(jozsa_algo $$ (0,0)))\\<^sup>2 = (cmod(\\<Sum>k<(2::nat)^n. (-1)^(f k)/(sqrt(2)^n * sqrt(2)^(n+1))))\\<^sup>2\" \n    by simp\n  have \"k < 2^n\\<longrightarrow>((1 div 2) \\<cdot>\\<^bsub>n\\<^esub>  k) = 0\" for k::nat\n    using bitwise_inner_prod_with_zero by simp\n  moreover have \"(cmod(jozsa_algo $$ (1,0)))\\<^sup>2 \n               = (cmod (\\<Sum>k<(2::nat)^n. (-1)^(f k+ 1 + ((1 div 2) \\<cdot>\\<^bsub>n\\<^esub>  k))/(sqrt(2)^n * sqrt(2)^(n+1))))\\<^sup>2\"\n      using \\<psi>\\<^sub>3_dim by simp\n  ultimately have f2: \"(cmod(jozsa_algo $$ (1,0)))\\<^sup>2 \n                     = (cmod (\\<Sum>k<(2::nat)^n. (-1)^(f k + 1)/(sqrt(2)^n * sqrt(2)^(n+1))))\\<^sup>2\" by simp   \n  have f3: \"1 = (cmod(\\<Sum>k::nat<(2::nat)^n.(-1)^(f k)/(sqrt(2)^n * sqrt(2)^(n+1))))\\<^sup>2\n        + (cmod (\\<Sum>k::nat<(2::nat)^n. (-1)^(f k + 1)/(sqrt(2)^n * sqrt(2)^(n+1))))\\<^sup>2\" \n    using f0 f1 f2 by simp \n  also have \"... = ((cmod (\\<Sum>k::nat<(2::nat)^n. (-1)^(f k)) ) /(sqrt(2)^n * sqrt(2)^(n+1)))\\<^sup>2\n                 + ((cmod(\\<Sum>k::nat<(2::nat)^n. (-1)^(f k + 1))) /(sqrt(2)^n * sqrt(2)^(n+1)))\\<^sup>2\"\n    using aux_comp_sum_divide_cmod[of \"\\<lambda>k. (-1)^(f k)\" \"(sqrt(2)^n * sqrt(2)^(n+1))\" \"(2::nat)^n\"] \n          aux_comp_sum_divide_cmod[of \"\\<lambda>k. (-1)^(f k + 1)\" \"(sqrt(2)^n * sqrt(2)^(n+1))\" \"(2::nat)^n\"] \n    by simp\n  also have \"... = ((cmod (\\<Sum>k::nat<(2::nat)^n. (-1)^(f k))))\\<^sup>2 /((sqrt(2)^n * sqrt(2)^(n+1)))\\<^sup>2\n                 + ((cmod(\\<Sum>k::nat<(2::nat)^n. (-1)^(f k +1))))\\<^sup>2 /((sqrt(2)^n * sqrt(2)^(n+1)))\\<^sup>2\"\n    by (simp add: power_divide)\n  also have \"... = ((cmod (\\<Sum>k::nat<(2::nat)^n. (-1)^(f k)) ) )\\<^sup>2/(2^(2*n+1))\n                 + ((cmod(\\<Sum>k::nat<(2::nat)^n. (-1)^(f k + 1))))\\<^sup>2 /(2^(2*n+1))\"\n    by (smt left_add_twice power2_eq_square power_add power_mult_distrib real_sqrt_pow2)\n  also have \"... = (((cmod (\\<Sum>k::nat<(2::nat)^n. (-1)^(f k))))\\<^sup>2 \n                 + ((cmod(\\<Sum>k::nat<(2::nat)^n. (-1)^(f k + 1))))\\<^sup>2)/(2^(2*n+1)) \"\n    by (simp add: add_divide_distrib)\n  finally have \"((2::nat)^(2*n+1)) = (((cmod (\\<Sum>k::nat<(2::nat)^n. (-1)^(f k))))\\<^sup>2 \n                 + ((cmod(\\<Sum>k::nat<(2::nat)^n. (-1)^(f k + 1))))\\<^sup>2)\" by simp\n  moreover have \"((2::nat)^(2*n+1)) = 2^(2*n) + 2^(2*n)\" by auto\n  moreover have \"(cmod (\\<Sum>k<(2::nat)^n. (-1)^(f k)))\\<^sup>2 \\<le> 2^(2*n)\" \n    using prob0_fst_qubits_leq by simp \n  moreover have \"(cmod (\\<Sum>k<(2::nat)^n. (-1)^(f k + 1)))\\<^sup>2 \\<le> 2^(2*n)\" \n    using prob0_fst_qubits_leq by simp \n  ultimately have \"2^(2*n) = ((cmod (\\<Sum>k::nat<(2::nat)^n. (-1)^(f k))))\\<^sup>2\" by simp\n  then show ?thesis\n    using  max_value_of_not_const_less by auto\nqed\n\ntext \\<open>\nThe function is balanced if and only if at least one qubit among the first n qubits is not zero.\nSo, if the function is balanced then the probability of measuring 0 for the first n qubits is 0.\n\\<close>\n\nlemma sum_union_disjoint_finite_set:\n  fixes C::\"nat set\" and g::\"nat \\<Rightarrow> int\"\n  assumes \"finite C\"\n  shows \"\\<forall>A B. A \\<inter> B = {} \\<and> A \\<union> B = C \\<longrightarrow> (\\<Sum>k\\<in>C. g k) = (\\<Sum>k\\<in>A. g k) + (\\<Sum>k\\<in>B. g k)\" \n  using assms sum.union_disjoint by auto\n\n\n\nlemma (in jozsa) balanced_pos_and_neg_terms_cancel_out2:\n  assumes \"is_balanced\" \n  shows \"(\\<Sum>k<(2::nat)^n. (-(1::nat))^(f k + 1)) = 0\"\nproof-\n  have \"\\<And>A B. A \\<subseteq> {i::nat. i < (2::nat)^n} \\<and> B \\<subseteq> {i::nat. i < (2::nat)^n}\n             \\<and> card A = ((2::nat)^(n-1)) \\<and> card B = ((2::nat)^(n-1))  \n             \\<and> (\\<forall>(x::nat)\\<in>A. f x = (0::nat))  \\<and> (\\<forall>(x::nat)\\<in>B. f x = 1)\n        \\<longrightarrow> (\\<Sum>k<(2::nat)^n. (-(1::nat))^(f k + 1)) = 0\"\n  proof\n    fix A B::\"nat set\"\n    assume asm: \"A \\<subseteq> {i::nat. i < (2::nat)^n} \\<and> B \\<subseteq> {i::nat. i < (2::nat)^n}\n             \\<and> card A = ((2::nat)^(n-1)) \\<and> card B = ((2::nat)^(n-1))  \n             \\<and> (\\<forall>(x::nat) \\<in> A. f x = (0::nat))  \\<and> (\\<forall>(x::nat) \\<in> B. f x = 1)\" \n    have \"A \\<inter> B = {}\" and \"{0..<(2::nat)^n} = A \\<union> B\" \n      using is_balanced_union is_balanced_inter asm by auto\n    then have \"(\\<Sum>k\\<in>{0..<(2::nat)^n}. (-(1::nat))^(f k + 1)) =\n               (\\<Sum>k\\<in>A. (-(1::nat))^(f k + 1)) \n             + (\\<Sum>k\\<in>B. (-(1::nat))^(f k + 1))\" \n      by (metis finite_atLeastLessThan sum_union_disjoint_finite_set)\n    moreover have \"(\\<Sum>k\\<in>A. (-1)^(f k + 1)) = -((2::nat)^(n-1))\" \n      using asm by simp\n    moreover have \"(\\<Sum>k\\<in>B. (-1)^(f k + 1)) = ((2::nat)^(n-1))\" \n      using asm by simp\n    ultimately have \"(\\<Sum>k\\<in>{0..<(2::nat)^n}. (-(1::nat))^(f k + 1)) = 0 \" by simp\n    then show \"(\\<Sum>k<(2::nat)^n. (-(1::nat))^(f k + 1)) = 0\"\n      by (simp add: lessThan_atLeast0)\n  qed\n  then show \"(\\<Sum>k<(2::nat)^n. (-(1::nat))^(f k + 1)) = 0\" \n    using assms is_balanced_def by auto\nqed\n\nlemma (in jozsa) prob0_jozsa_algo_of_balanced:\nassumes \"is_balanced\"\n  shows \"prob0_fst_qubits n jozsa_algo = 0\"\nproof-\n  have \"prob0_fst_qubits n jozsa_algo = (\\<Sum>j\\<in>{0,1}. (cmod(jozsa_algo $$ (j,0)))\\<^sup>2)\"\n    using prob0_fst_qubits_of_jozsa_algo by simp\n  moreover have \"(cmod(jozsa_algo $$ (0,0)))\\<^sup>2 = 0\"\n  proof-\n     have \"k < 2^n\\<longrightarrow>((1 div 2) \\<cdot>\\<^bsub>n\\<^esub>  k) = 0\" for k::nat\n      using bitwise_inner_prod_with_zero by simp\n    then have \"(cmod(jozsa_algo $$ (0,0)))\\<^sup>2 = (cmod(\\<Sum> k < (2::nat)^n. (-1)^(f k)/(sqrt(2)^n * sqrt(2)^(n+1))))\\<^sup>2\" \n      using \\<psi>\\<^sub>3_values by simp\n    also have \"... = (cmod(\\<Sum>k<(2::nat)^n. (-(1::nat))^(f k))/(sqrt(2)^n * sqrt(2)^(n+1)))\\<^sup>2\" \n      using aux_comp_sum_divide_cmod[of \"\\<lambda>k.(-(1::nat))^(f k)\" \"(sqrt(2)^n * sqrt(2)^(n+1))\" \"2^n\"] \n      by simp\n    also have \"... = (cmod ((0::int)/(sqrt(2)^n * sqrt(2)^(n+1))))\\<^sup>2\" \n      using balanced_pos_and_neg_terms_cancel_out1 assms by (simp add: bob_fun_axioms)\n    also have \"... = 0\" by simp\n    finally show ?thesis by simp\n  qed\n  moreover have \"(cmod(jozsa_algo $$ (1,0)))\\<^sup>2 = 0\" \n  proof-\n     have \"k < 2^n \\<longrightarrow> (((1::nat) div 2) \\<cdot>\\<^bsub>n\\<^esub>  k) = 0\" for k::nat\n       using bitwise_inner_prod_with_zero by auto\n     moreover have \"(cmod(jozsa_algo $$ (1,0)))\\<^sup>2 \n     = (cmod (\\<Sum>k<(2::nat)^n. (-(1::nat))^(f k + (1::nat) + ((1 div 2) \\<cdot>\\<^bsub>n\\<^esub>  k))/(sqrt(2)^n * sqrt(2)^(n+1))))\\<^sup>2\"\n      using \\<psi>\\<^sub>3_dim by simp\n    ultimately have \"(cmod(jozsa_algo $$ (1,0)))\\<^sup>2 \n    = (cmod(\\<Sum>k<(2::nat)^n. (-(1::nat))^(f k + (1::nat))/(sqrt(2)^n * sqrt(2)^(n+1))))\\<^sup>2\" \n       by simp\n    also have \"... = (cmod(\\<Sum>k<(2::nat)^n. (-(1::nat))^(f k + 1))/(sqrt(2)^n * sqrt(2)^(n+1)))\\<^sup>2\" \n      using aux_comp_sum_divide_cmod[of \"\\<lambda>k.(-(1::nat))^(f k + 1)\" \"(sqrt(2)^n * sqrt(2)^(n+1))\" \"2^n\"] \n      by simp\n    also have \"... = (cmod ((0::int)/(sqrt(2)^n * sqrt(2)^(n+1))))\\<^sup>2\" \n      using balanced_pos_and_neg_terms_cancel_out2 assms by (simp add: bob_fun_axioms)\n    also have \"... = 0\" by simp\n    finally show ?thesis by simp\n  qed\n  ultimately have \"prob0_fst_qubits n jozsa_algo = 0 + 0\" by simp\n  then show  ?thesis by simp\nqed\n\ntext \\<open>If the probability that the first n qubits are 0 is 0, then the function is balanced.\\<close>\n\nlemma (in jozsa) balanced_prob0_jozsa_algo:\n  assumes \"prob0_fst_qubits n jozsa_algo = 0\"\n  shows \"is_balanced\"\nproof-\n  have \"is_const \\<or> is_balanced\" \n    using const_or_balanced by simp\n  moreover have \"is_const \\<longrightarrow> \\<not> prob0_fst_qubits n jozsa_algo = 0\"\n    using is_const_def prob0_jozsa_algo_of_const_0 prob0_jozsa_algo_of_const_1 by simp\n  ultimately show ?thesis \n    using assms by simp\nqed\n\ntext \\<open>We prove the correctness of the algorithm.\\<close>\n\ndefinition (in jozsa) jozsa_algo_eval:: \"real\" where\n\"jozsa_algo_eval \\<equiv> prob0_fst_qubits n jozsa_algo\"\n\ntheorem (in jozsa) jozsa_algo_is_correct:\n  shows \"jozsa_algo_eval = 1 \\<longleftrightarrow> is_const\" \n    and \"jozsa_algo_eval = 0 \\<longleftrightarrow> is_balanced\" \n  using prob0_jozsa_algo_of_const_1 prob0_jozsa_algo_of_const_0 jozsa_algo_eval_def\nprob0_jozsa_algo_1_is_const is_const_def balanced_prob0_jozsa_algo prob0_jozsa_algo_of_balanced \n  by auto\n\n\nend\n", "meta": {"author": "AnthonyBordg", "repo": "Isabelle_marries_Dirac", "sha": "ab313fb4028c99bd5d97f8e30aaf1644e200d57b", "save_path": "github-repos/isabelle/AnthonyBordg-Isabelle_marries_Dirac", "path": "github-repos/isabelle/AnthonyBordg-Isabelle_marries_Dirac/Isabelle_marries_Dirac-ab313fb4028c99bd5d97f8e30aaf1644e200d57b/Deutsch_Jozsa.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8705972583359805, "lm_q2_score": 0.8519528019683106, "lm_q1q2_score": 0.7417077736252676}}
{"text": "theory estudosP1\nimports Main\nbegin\n(* Conjunto Indutivo \\<nat>\n\n                                    x0:Nat\n                                    P(x0)     hI\n    \\<dots>                              \\<dots>\n    \\<dots>                              \\<dots>\n    \\<dots>                              \\<dots>\n    P(zero)                         P(suc x0)\n    ------------------------------------------------- Ind Nat\n                         \\<forall>n:Nat. P(n)\n*)\n\ndatatype Nat = Z | suc Nat\n\n(* Primitiva Recursiva add: \\<nat> \\<Rightarrow> \\<nat> \\<Rightarrow> \\<nat>\n\n  add: \\<nat> \\<Rightarrow> \\<nat> \\<Rightarrow> \\<nat>, onde\n    add x 0 = x                    (add01)\n    add x (suc y) = suc (add x y)  (add02)\n*)\n\nprimrec add::\"Nat \\<Rightarrow> Nat \\<Rightarrow> Nat\" where\n  add01: \"add x Z = x\" |\n  add02: \"add x (suc y) = suc (add x y)\"\n\nvalue \"add Z (suc (suc Z))\"\nvalue \"add (suc Z) (suc (suc (suc Z)))\"\n\n(* Provas por Indu\u00e7\u00e3o Estrutural\n\n  add 0 (suc (suc 0)) = suc (add 0 (suc 0))   (by add02, [x:=0, y:=suc 0])\n                      = suc (suc (add 0 0))   (by add02, [x:=0, y:=0])\n                      = suc (suc 0)           (by add01, [x:=0])\n                      = 2                     (por defini\u00e7\u00e3o de suc)\n\n  add (suc 0) (suc (suc (suc 0))) = suc (add (suc 0) (suc (suc 0)))  (by add02, [x:=suc 0, y:=suc (suc 0)])\n                                  = suc (suc (add (suc 0) (suc 0)))  (by add02, [x:=suc 0, y:=suc 0])\n                                  = suc (suc (suc (add (suc 0) 0)))  (by add02, [x:=suc 0, y:=0])\n                                  = suc (suc (suc (suc 0)))          (by add01, [x:=suc 0])\n                                  = 4                                (por defini\u00e7\u00e3o de suc)\n*)\n\n(*\n  Provar os teoremas:\n\n    Th-add-01: \\<forall>x:\\<nat>. \\<forall>y:\\<nat>. \\<forall>z:\\<nat>. add x (add y z) = add (add x y) z\n    Th-add-02: \\<forall>x:\\<nat>. \\<forall>y:\\<nat>. add x y = add y x\n    Th-add-03: \\<forall>x:\\<nat>. add 0 x = x\n    Th-add-04: \\<forall>x:\\<nat>. \\<forall>y:\\<nat>. add x (suc y) = add (suc x) y\n    Th-add-05: \\<forall>x:\\<nat>. \\<forall>y:\\<nat>. add (suc x) y = suc (add x y)\n*)\n\n(*\n1) Provando Th-add-01 (associatividade da fun\u00e7\u00e3o add)\n  1.1) Formaliza\u00e7\u00e3o da propriedade\n\n    P \\<triangleq> \\<forall>x:\\<nat>. \\<forall>y:\\<nat>. \\<forall>z:\\<nat>. add x (add y z) = add (add x y) z\n\n  1.2) Escolha da vari\u00e1vel indutiva\n\n    P(n) \\<triangleq> \\<forall>x:\\<nat>. \\<forall>y:\\<nat>. add x (add y n) = add (add x y) n\n\n    Logo, temos que provar que \\<forall>n:\\<nat>. P(n).\n\n  1.2.1) Prova do caso base P(0)\n  \n    Temos que mostrar que:\n      \\<forall>x:\\<nat>. \\<forall>y:\\<nat>. add x (add y 0) = add (add x y) 0\n  \n    Sejam x0 e y0 valores arbitr\u00e1rios em \\<nat>, ent\u00e3o \u00e9 suficiente mostrar que:\n      add x0 (add y0 0) = add (add x0 y0) 0\n  \n    Agora, veja que:\n  \n      add x0 (add y0 0)\n        = add x0 y0           (by add01, [x:=y0])\n        = add (add x0 y0) 0   (by add01, [x:=add x0 y0])\n  \n        q.e.d.\n  \n  1.2.2) Prova do caso indutivo P(x0) \\<longrightarrow> P(suc x0)\n  \n    Seja x0 um valor arbitr\u00e1rio em \\<nat>, assumimos como hip\u00f3tese de indu\u00e7\u00e3o:\n      \\<forall>x:\\<nat>. \\<forall>y:\\<nat>. add x (add y x0) = add (add x y) x0\n  \n    Temos que mostrar que:\n      \\<forall>x:\\<nat>. \\<forall>y:\\<nat>. add x (add y (suc x0)) = add (add x y) (suc x0)\n  \n    Sejam x1 e y1 valores arbitr\u00e1rios em \\<nat>. Logo, \u00e9 suficiente mostrar que:\n      add x1 (add y1 (suc x0)) = add (add x1 y1) (suc x0)\n  \n    Agora, veja que:\n  \n      add x1 (add y1 (suc x0))\n        = add x1 (suc (add y1 x0))        (by add02, [x:=y1, y:=suc x0])\n        = suc (add x1 (add y1 x0))        (by add02, [x:=x1, y:=add y1 x0])\n        = suc (add (add x1 y1) x0)        (by HI, [x:=x1, y:=y1])\n        = add (add x1 y1) (suc x0)        (by add02, [x:=(add x1 y1), y:=x0])\n  \n        q.e.d\n*)\n\ntheorem thadd01: \"\\<forall>x. \\<forall>y. add x (add y n) = add (add x y) n\"\n  proof (induction n)\n    show \"\\<forall>x. \\<forall>y. add x (add y Z) = add (add x y) Z\"\n      proof (rule allI, rule allI)\n        fix x0::Nat and y0::Nat\n          have \"add x0 (add y0 Z) = add x0 y0\" by (simp only:add01)\n          also have \"add x0 y0 = add (add x0 y0) Z\" by (simp only:add01)\n          finally show \"add x0 (add y0 Z) = add (add x0 y0) Z\" by this\n      qed\n      next\n        fix x0::Nat\n        assume IH:\"\\<forall>x. \\<forall>y. add x (add y x0) = add (add x y) x0\"\n        show \"\\<forall>x. \\<forall>y. add x (add y (suc x0)) = add (add x y) (suc x0)\"\n        proof (rule allI, rule allI)\n          fix x1::Nat and y1::Nat\n          have \"add x1 (add y1 (suc x0)) = add x1 (suc (add y1 x0))\" by (simp only:add02)\n          also have \"add x1 (suc (add y1 x0)) = suc (add x1 (add y1 x0))\" by (simp only:add02)\n          also have \"suc (add x1 (add y1 x0)) = suc (add (add x1 y1) x0)\" by (simp only:IH)\n          also have \"suc (add (add x1 y1) x0) = add (add x1 y1) (suc x0)\" by (simp only:add02)\n          finally show \"add x1 (add y1 (suc x0)) = add (add x1 y1) (suc x0)\" by this\n        qed\n  qed\n\n(*\n2) Provando Th-add-03 (0 \u00e9 neutro \u00e0 esquerda)\n  2.1) Formaliza\u00e7\u00e3o da propriedade\n\n    P \\<triangleq> \\<forall>x:\\<nat>. add 0 x = x\n\n  2.2) Escolha da vari\u00e1vel indutiva\n\n    P(n) \\<triangleq> add 0 n = n\n\n    Logo, temos que provar que \\<forall>n:\\<nat>. P(n).\n\n  2.2.1) Prova do caso base P(0)\n\n    Temos que mostrar que:\n      add 0 0 = 0\n\n    Agora veja que:\n\n      add 0 0\n        = 0     (by add01, [x:=0])\n\n        q.e.d.\n\n  2.2.2) Prova do caso indutivo P(x0) \\<longrightarrow> P(suc x0)\n  \n    Seja x0 um valor arbitr\u00e1rio em \\<nat>, assumimos como hip\u00f3tese de indu\u00e7\u00e3o:\n      add 0 x0 = x0\n\n    Temos que mostrar que:\n      add 0 (suc x0) = suc x0\n\n    Agora, veja que:\n      \n      add 0 (suc x0)\n        = suc (add 0 x0)            (by add02, [x:=0, y:=x0])\n        = suc x0                    (by HI, [x0:=x0])\n\n        q.e.d.\n*)\n\ntheorem thadd03: \"add Z n = n\"\n  proof (induction n)\n    show \"add Z Z = Z\" by (simp only:add01)\n    next\n     fix x0::Nat\n      assume IH:\"add Z x0 = x0\"\n      show \"add Z (suc x0) = suc x0\"\n      proof -\n        have \"add Z (suc x0) = suc (add Z x0)\" by (simp only:add02) also\n        have \"suc (add Z x0) = suc x0\" by (simp only:IH)\n        finally show \"add Z (suc x0) = suc x0\" by this\n      qed\n  qed\n\n(*\n3) Provando Th-add-02 (comutatividade da fun\u00e7\u00e3o add)\n  3.1) Formaliza\u00e7\u00e3o da propriedade\n\n    P \\<triangleq> \\<forall>x:\\<nat>. \\<forall>y:\\<nat>. add x y = add y x\n\n  3.2) Escolha da vari\u00e1vel indutiva\n\n    P(n) \\<triangleq> \\<forall>x:\\<nat>. add x n = add n x\n\n    Logo, temos que provar que \\<forall>n:\\<nat>. P(n).\n\n  3.2.1) Prova do caso base P(0)\n  \n    Temos que mostrar que:\n      \\<forall>x:\\<nat>. add x 0 = add 0 x\n  \n    Seja x0 um valor arbitr\u00e1rio em \\<nat>, ent\u00e3o \u00e9 suficiente mostrar que:\n      add x0 0 = add 0 x0\n  \n    Agora, veja que:\n  \n      add x0 0\n        = x0          (by add01, [x:=x0])\n        = add 0 x0    (by Th-add-03, [x:=x0])\n  \n        q.e.d.\n\n  3.2.2.) Prova do caso indutivo P(x0) \\<longrightarrow> P(suc x0)\n\n    Seja x0 um valor arbitr\u00e1rio em \\<nat>, assumimos como hip\u00f3tese de indu\u00e7\u00e3o:\n      \\<forall>x:\\<nat>. add x x0 = add x0 x\n\n    Temos que mostrar que:\n      \\<forall>x:\\<nat>. add x (suc x0) = add (suc x0) x\n\n    Seja x1 um valor arbitr\u00e1rio em \\<nat>, \u00e9 suficiente provar que:\n      add x1 (suc x0) = add (suc x0) x1\n\n    Agora, veja que:\n      \n      add x1 (suc x0)\n        = add (suc x0) x1           (by HI, x:=x1, x0=x0])\n\n      add x1 (suc x0) \n      = suc (add x1 x0).   (by add02, x:=x1, y:=x0)\n      = suc (add x0 x1).   (by IH, allE)\n      = add (x0 (suc x1))  (by add02, x:=x0, y:=x1)\n      = add (suc x0) x1.   (by Th-add04, allE, x:=x0, y:=x1\n\n        q.e.d.\n*)\n\ntheorem thadd02: \"\\<forall>x. add x n = add n x\"\n  proof (induction n)\n    show \"\\<forall>x. add x Z = add Z x\"\n      proof (rule allI)\n        fix x0::Nat\n        have \"add x0 Z = x0\" by (simp only:add01) also\n        have \"x0 = add Z x0\" by (simp only:thadd03)\n        finally show \"add x0 Z = add Z x0\" by this\n      qed\n      next\n        fix x0::Nat\n        assume IH:\"\\<forall>x. add x x0 = add x0 x\"\n        show \"\\<forall>x. add x (suc x0) = add (suc x0) x\"\n        proof (rule allI)\n          fix x1::Nat\n          have \"add x1 (suc x0) = suc (add x1 x0)\" by (simp only:add02) also\n          have \"suc (add x1 x0) = suc (add x0 x1)\" by (simp only:IH) also\n          have \"suc (add x0 x1) = add (suc x0) x1\" by (simp only:thadd05)\n          finally show \"add x1 (suc x0) = add (suc x0) x1\" by this\n        qed\n  qed\n\n(*\n4) Provando Th-add-04\n  4.1) Formaliza\u00e7\u00e3o da propriedade\n\n    P \\<triangleq> \\<forall>x:\\<nat>. \\<forall>y:\\<nat>. add x (suc y) = add (suc x) y\n\n  4.2) Escolha da vari\u00e1vel indutiva\n\n    P(n) \\<triangleq> \\<forall>x:\\<nat>. add x (suc n) = add (suc x) n\n\n    Logo, temos que provar que \\<forall>n:\\<nat>. P(n).\n\n  4.2.1) Prova do caso base P(0)\n  \n    Temos que mostrar que:\n      P(0) \\<triangleq> \\<forall>x:\\<nat>. add x (suc 0) = add (suc x) 0\n  \n    Seja x0 um valor arbitr\u00e1rio em \\<nat>, ent\u00e3o \u00e9 suficiente mostrar que:\n      add x0 (suc 0) = add (suc x0) 0\n  \n    Agora, veja que:\n  \n      add x0 (suc 0)\n        = suc (add x0 0)          (by add02, [x:=x0, y:=0])\n        = suc (add 0 x0)          (by th-add-02, [x:=x0, y:=0])\n        = add 0 (suc x0)          (by add02, [x:=0, y:=x0])\n        = add (suc x0) 0          (by th-add-02, [x:=suc x0, y:=0])\n  \n        q.e.d.\n\n  4.2.2.) Prova do caso indutivo P(x0) \\<longrightarrow> P(suc x0)\n\n    Seja x0 um valor arbitr\u00e1rio em \\<nat>, assumimos como hip\u00f3tese de indu\u00e7\u00e3o:\n      P(x0) \\<triangleq> \\<forall>x:\\<nat>. add x (suc x0) = add (suc x) x0\n\n    Temos que mostrar que:\n      P(suc x0) \\<triangleq> \\<forall>x:\\<nat>. add x (suc (suc x0)) = add (suc x) (suc x0)\n\n    Seja x1 um valor arbitr\u00e1rio em \\<nat>, \u00e9 suficiente provar que:\n      add x1 (suc (suc x0)) = add (suc x1) (suc x0)\n\n    Agora, veja que:\n      \n      add x1 (suc (suc x0))\n        = suc (add x1 (suc x0))          (by add02, [x:=x1, y:=suc x0])\n        = suc (add (suc x1) x0)          (by HI, [x:=x1, x0:=x0])\n        = add (suc x1) (suc x0)          (by add02, [x:=suc x1, y:=x0])\n\n        q.e.d.\n*)\n\ntheorem thadd04: \"\\<forall>x. add x (suc n) = add (suc x) n\"\n  proof (induction n)\n    show \"\\<forall>x. add x (suc Z) = add (suc x) Z\"\n      proof (rule allI)\n        fix x0::Nat\n        have \"add x0 (suc Z) = suc (add x0 Z)\" by (simp only:add02)\n        also have \"suc (add x0 Z) = suc (add Z x0)\" by (simp only:thadd02)\n        also have \"suc (add Z x0) = add Z (suc x0)\" by (simp only:add02)\n        also have \"add Z (suc x0) = add (suc x0) Z\" by (simp only:thadd02)\n        finally show \"add x0 (suc Z) = add (suc x0) Z\" by this\n      qed\n      next\n        fix x0::Nat\n        assume IH:\"\\<forall>x. add x (suc x0) = add (suc x) x0\"\n        show \"\\<forall>x. add x (suc (suc x0)) = add (suc x) (suc x0)\"\n        proof (rule allI)\n          fix x1::Nat\n          have \"add x1 (suc (suc x0)) = suc (add x1 (suc x0))\" by (simp only:add02) also\n          have \"suc (add x1 (suc x0)) = suc (add (suc x1) x0)\" by (simp only:IH) also \n          have \"suc (add (suc x1) x0) = add (suc x1) (suc x0)\" by (simp only:add02)\n          finally show \"add x1 (suc (suc x0)) = add (suc x1) (suc x0)\" by this\n        qed\n  qed\n\n(*\n5) Provando Th-add-05\n  5.1) Formaliza\u00e7\u00e3o da propriedade\n\n    P \\<triangleq> \\<forall>x:\\<nat>. \\<forall>y:\\<nat>. add (suc x) y = suc (add x y)\n\n  5.2) Escolha da vari\u00e1vel indutiva\n\n    P(n) \\<triangleq> \\<forall>x:\\<nat>. add (suc x) n = suc (add x n)\n\n    Logo, temos que provar que \\<forall>n:\\<nat>. P(n).\n\n  5.2.1) Prova do caso base P(0)\n  \n    Temos que mostrar que:\n      P(0) \\<triangleq> \\<forall>x:\\<nat>. add (suc x) 0 = suc (add x 0)\n  \n    Seja x0 um valor arbitr\u00e1rio em \\<nat>, ent\u00e3o \u00e9 suficiente mostrar que:\n      add (suc x0) 0 = suc (add x0 0)\n  \n    Agora, veja que:\n  \n      add (suc x0) 0\n        = add 0 (suc x0)          (by th-add-02, [x:=suc x0, y:=0])\n        = suc (add 0 x0)          (by add02, [x:=0, y:=x0])\n        = suc (add x0 0)          (by th-add-02, [x:=x0, y:=0]\n  \n        q.e.d.\n\n  5.2.2.) Prova do caso indutivo P(x0) \\<longrightarrow> P(suc x0)\n\n    Seja x0 um valor arbitr\u00e1rio em \\<nat>, assumimos como hip\u00f3tese de indu\u00e7\u00e3o:\n      P(x0) \\<triangleq> \\<forall>x:\\<nat>. add (suc x) x0 = suc (add x x0)\n\n    Temos que mostrar que:\n      P(suc x0) \\<triangleq> \\<forall>x:\\<nat>. add (suc x) (suc x0) = suc (add x (suc x0))\n\n    Seja x1 um valor arbitr\u00e1rio em \\<nat>, \u00e9 suficiente provar que:\n      add (suc x1) (suc x0) = suc (add x1 (suc x0))\n\n    Agora, veja que:\n      \n      add (suc x1) (suc x0)\n        = suc (add (suc x1) x0)          (by add02, [x:=suc x1, y:=x0])\n        = suc (add x1 (suc x0))          (by th-add-04, [x:=x1, y:=x0])\n\n        q.e.d.\n*)\n\ntheorem thadd05: \"\\<forall>x. add (suc x) n = suc (add x n)\"\n  proof (induction n)\n    show \"\\<forall>x. add (suc x) Z = suc (add x Z)\"\n    proof (rule allI)\n      fix x0::Nat\n      have \"add (suc x0) Z = add Z (suc x0)\" by (simp only:thadd02) also\n      have \"add Z (suc x0) = suc (add Z x0)\" by (simp only:add02) also\n      have \"suc (add Z x0) = suc (add x0 Z)\" by (simp only:thadd02)\n      finally show \"add (suc x0) Z = suc (add x0 Z)\" by this\n    qed\n    next\n      fix x0::Nat\n      assume IH: \"\\<forall>x. add (suc x) x0 = suc (add x x0)\"\n      show \"\\<forall>x. add (suc x) (suc x0) = suc (add x (suc x0))\"\n      proof (rule allI)\n        fix x1::Nat\n        have \"add (suc x1) (suc x0) = suc (add (suc x1) x0)\" by (simp only:add02) also\n        have \"suc (add (suc x1) x0) = suc (add x1 (suc x0))\" by (simp only:thadd04)\n        finally show \"add (suc x1) (suc x0) = suc (add x1 (suc x0))\" by this\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\nvalue \"mult Z (suc (suc Z))\"\nvalue \"mult (suc Z) (suc Z)\"\nvalue \"mult (suc (suc Z)) (suc (suc (suc Z)))\"\n\n(*\n  Th-mult-01:   \\<forall>x:\\<nat>. \\<forall>y:\\<nat>. \\<forall>z:\\<nat>. mult x (mult y z) = mult (mult x y) z\n  Th-mult-02:   \\<forall>x:\\<nat>. \\<forall>y:\\<nat>. mult x y = mult y z\n  Th-mult-03:   \\<forall>x:\\<nat>. \\<forall>y:\\<nat>. \\<forall>z:\\<nat>. mult x (add y z) = add (mult x y) (mult x z)\n*)\n\ntheorem thmult01: \"\\<forall>x. \\<forall>y. mult x (mult y n) = mult (mult x y) n\"\n  proof (induction n)\n    show \"\\<forall>x. \\<forall>y. mult x (mult y Z) = mult (mult x y) Z\"\n    proof (rule allI, rule allI)\n      fix x0::Nat and y0::Nat\n      have \"mult x0 (mult y0 Z) = mult x0 Z\" by (simp only:mult01) also\n      have \"mult x0 Z = mult (mult x0 y0) Z\" by (simp only:mult01)\n      finally show \"mult x0 (mult y0 Z) = mult (mult x0 y0) Z\" by this\n    qed\n    next\n      fix x0::Nat\n      assume IH: \"\\<forall>x. \\<forall>y. mult x (mult y x0) = mult (mult x y) x0\"\n      show \"\\<forall>x. \\<forall>y. mult x (mult y (suc x0)) = mult (mult x y) (suc x0)\"\n      proof (rule allI, rule allI)\n        fix x1::Nat and y1::Nat\n        have \"mult x1 (mult y1 (suc x0)) = mult x1 (add y1 (mult y1 x0))\" by (simp only:mult02) also\n        have \"mult x1 (add y1 (mult y1 x0)) = mult x1 (add (mult y1 x0) y1)\" by (simp only:thadd02) also\n        finally show \"mult x1 (mult y1 (suc x0)) = mult (mult x1 y1) (suc x0)\" by this\n      qed\n  qed\n", "meta": {"author": "taschetto", "repo": "formalMethods", "sha": "58a1eef1326ad463d8893d8604d7f246d64bf5ae", "save_path": "github-repos/isabelle/taschetto-formalMethods", "path": "github-repos/isabelle/taschetto-formalMethods/formalMethods-58a1eef1326ad463d8893d8604d7f246d64bf5ae/estudosP1.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527906914787, "lm_q2_score": 0.8705972667296309, "lm_q1q2_score": 0.7417077709586827}}
{"text": "theory Monotony\n  imports Main\nbegin\n\ntype_synonym variable = string\n\ndatatype bexpr =\n    Const bool\n  | Var variable\n  | And bexpr bexpr\n  | Or bexpr bexpr\n  | Imp bexpr bexpr\n  | Neg bexpr\n\ndatatype occ =\n    Even\n  | Odd\n  | Both\n\nfun negate :: \"occ \\<Rightarrow> occ\" where\n\"negate Even = Odd\" |\n\"negate Odd = Even\" |\n\"negate Both = Both\"\n\nfun merge :: \"occ \\<Rightarrow> occ \\<Rightarrow> occ\" where\n\"merge x y = (if x = y then x else Both)\"\n\nprimrec occurrences :: \"bexpr \\<Rightarrow> variable \\<Rightarrow> occ\" where\n\"occurrences (Const _) _ = Even\" |\n\"occurrences (Var y) x = Even\" |\n\"occurrences (And phi psi) x = (merge (occurrences phi x) (occurrences psi x))\" |\n\"occurrences (Or phi psi) x = (merge (occurrences phi x) (occurrences psi x))\" |\n\"occurrences (Imp phi psi) x = (merge (negate (occurrences phi x)) (occurrences psi x))\" |\n\"occurrences (Neg phi) x = (negate (occurrences phi x))\"\n\ntype_synonym environment = \"string \\<Rightarrow> bool\"\n\nfun update :: \"environment \\<Rightarrow> variable \\<Rightarrow> bool \\<Rightarrow> environment\" where\n\"update env x b y = (if y = x then b else env y)\"\n\nfun update2 :: \"environment \\<Rightarrow> variable \\<Rightarrow> bool \\<Rightarrow> environment\" where\n\"update2 env x b = (\\<lambda>y. (if y = x then b else env y))\"\n\nfun update3 :: \"environment \\<Rightarrow> variable \\<Rightarrow> bool \\<Rightarrow> environment\" where\n\"update3 env x = (\\<lambda>b. (\\<lambda>y. (if y = x then b else env y)))\"\n\ndefinition env0 :: environment where\n\"env0 _ \\<equiv> False\"\n\nvalue \"(update env0 ''x'' True) ''y''\"\n\nprimrec eval :: \"bexpr \\<Rightarrow> environment \\<Rightarrow> bool\" where\n\"eval (Const b) _ = b\" |\n\"eval (Var x) env = (env x)\" |\n\"eval (And phi psi) env = ((eval phi env) \\<and> (eval psi env))\" |\n\"eval (Or phi psi) env = ((eval phi env) \\<or> (eval psi env))\" |\n\"eval (Imp phi psi) env = ((eval phi env) \\<longrightarrow> (eval psi env))\" |\n\"eval (Neg phi) env = (\\<not> (eval phi env))\"\n\ndefinition monotonic_in :: \"bexpr \\<Rightarrow> variable \\<Rightarrow> bool\" where\n\"monotonic_in phi x \\<equiv> \\<forall>env. (eval phi (update env x False)) \\<longrightarrow> (eval phi (update env x True))\"\n\ndefinition antitonic_in :: \"bexpr \\<Rightarrow> variable \\<Rightarrow> bool\" where\n\"antitonic_in phi x \\<equiv>  \\<forall>env. (eval phi (update env x True)) \\<longrightarrow> (eval phi (update env x False))\"\n\n\n\n\nlemma mergeBothEven: \"merge x y = Even \\<longrightarrow> x = Even \\<and> y = Even\"\n  by simp\n\nlemma mergeBothOdd: \"merge x y = Odd \\<longrightarrow> x = Odd \\<and> y = Odd\"\n  by simp\n\nlemma negateOccEvenIsOdd: \"negate (occurrences phi x) = Even \\<longrightarrow> occurrences phi x = Odd\"\n  using negate.elims by auto\n \nlemma negateOccOddIsEven: \"negate (occurrences phi x) = Odd \\<longrightarrow> occurrences phi x = Even\"\n  using negate.elims by auto\n\nlemma occNegEvenIsOdd: \"occurrences (Neg phi) x = Even \\<longrightarrow> occurrences phi x = Odd\"\n  using negateOccEvenIsOdd by auto\n\nlemma occNegOddIsEven: \"occurrences (Neg phi) x = Odd \\<longrightarrow> occurrences phi x = Even\"\n  using negateOccOddIsEven by auto\n  \n  \n\nlemma aux: \"((occurrences phi x = Even) \\<longrightarrow> (monotonic_in phi x)) \\<and>\n            ((occurrences phi x = Odd) \\<longrightarrow> (antitonic_in phi x))\"\nproof (induction phi arbitrary: x)\n  case (Const x)\n  show ?case by (simp add: monotonic_in_def antitonic_in_def)\nnext\n  case (Var x)\n  show ?case by (simp add: monotonic_in_def antitonic_in_def)\nnext\n  case (And phi1 phi2)\n  show ?case\n  proof\n    show \"occurrences (And phi1 phi2) x = Even \\<longrightarrow> monotonic_in (And phi1 phi2) x\"\n    proof (rule impI)\n      assume \"occurrences (And phi1 phi2) x = Even\"\n      then have \"merge (occurrences phi1 x) (occurrences phi2 x) = Even\" \n        by simp\n      then have bothEven: \"occurrences phi1 x = Even \\<and> occurrences phi2 x = Even\"\n        using mergeBothEven by blast\n      from bothEven have \"occurrences phi1 x = Even\" ..\n      with And.IH have mono1: \"monotonic_in phi1 x\" \n        by simp\n      from bothEven have \"occurrences phi2 x = Even\" ..\n      with And.IH have mono2: \"monotonic_in phi2 x\"\n        by simp\n      from mono1 mono2 show \"monotonic_in (And phi1 phi2) x\"\n        by (simp add: monotonic_in_def)\n    qed\n\n    show \"occurrences (And phi1 phi2) x = Odd \\<longrightarrow> antitonic_in (And phi1 phi2) x\"\n    proof (rule impI)\n      assume \"occurrences (And phi1 phi2) x = Odd\"\n      then have \"merge (occurrences phi1 x) (occurrences phi2 x) = Odd\" \n        by simp\n      then have bothOdd: \"occurrences phi1 x = Odd \\<and> occurrences phi2 x = Odd\"\n        using mergeBothOdd by blast\n      from bothOdd have \"occurrences phi1 x = Odd\" ..\n      with And.IH have anti1: \"antitonic_in phi1 x\"\n        by simp\n      from bothOdd have \"occurrences phi2 x = Odd\" ..\n      with And.IH have anti2: \"antitonic_in phi2 x\" \n        by simp\n      from anti1 anti2 show \"antitonic_in (And phi1 phi2) x\"\n        by (simp add: antitonic_in_def)\n    qed\n  qed\nnext\n  case (Or phi1 phi2)\n  show ?case\n  proof\n    show \"occurrences (Or phi1 phi2) x = Even \\<longrightarrow> monotonic_in (Or phi1 phi2) x\" \n    proof\n      assume \"occurrences (Or phi1 phi2) x = Even\"\n      then have \"merge (occurrences phi1 x) (occurrences phi2 x) = Even\"\n        by simp\n      then have bothEven: \"occurrences phi1 x = Even \\<and> occurrences phi2 x = Even\"\n        using mergeBothEven by blast\n      from bothEven have \"occurrences phi1 x = Even\" ..\n      with Or.IH have mono1: \"monotonic_in phi1 x\" \n        by simp\n      from bothEven have \"occurrences phi2 x = Even\" ..\n      with Or.IH have mono2: \"monotonic_in phi2 x\"\n        by simp\n      from mono1 mono2 show \"monotonic_in (Or phi1 phi2) x\"\n        by (simp add: monotonic_in_def)\n    qed\n\n    show \"occurrences (Or phi1 phi2) x = Odd \\<longrightarrow> antitonic_in (Or phi1 phi2) x\" \n    proof\n      assume \"occurrences (Or phi1 phi2) x = Odd\"\n      then have \"merge (occurrences phi1 x) (occurrences phi2 x) = Odd\"\n        by simp\n      then have bothOdd: \"occurrences phi1 x = Odd \\<and> occurrences phi2 x = Odd\"\n        using mergeBothOdd by blast\n      from bothOdd have \"occurrences phi1 x = Odd\" ..\n      with Or.IH have anti1: \"antitonic_in phi1 x\"\n        by simp\n      from bothOdd have \"occurrences phi2 x = Odd\" ..\n      with Or.IH have anti2: \"antitonic_in phi2 x\"\n        by simp\n      from anti1 anti2 show \"antitonic_in (Or phi1 phi2) x\"\n        by (simp add: antitonic_in_def)\n    qed\n  qed\nnext\n  case (Imp phi1 phi2)\n  show ?case\n  proof\n    show \"occurrences (Imp phi1 phi2) x = Even \\<longrightarrow> monotonic_in (Imp phi1 phi2) x\"\n    proof\n      assume \"occurrences (Imp phi1 phi2) x = Even\"\n      then have \"merge (negate (occurrences phi1 x)) (occurrences phi2 x) = Even\"\n        by simp\n      then have bothEven: \"negate (occurrences phi1 x) = Even \\<and> occurrences phi2 x = Even\"\n        using mergeBothEven by blast\n      from bothEven have \"negate (occurrences phi1 x) = Even\" ..\n      then have \"occurrences phi1 x = Odd\"\n        using negateOccEvenIsOdd by simp\n      with Imp.IH have anti1: \"antitonic_in phi1 x\"\n        by simp\n      from bothEven have \"occurrences phi2 x = Even\" ..\n      with Imp.IH have mono2: \"monotonic_in phi2 x\"\n        by simp\n      from anti1 mono2 show \"monotonic_in (Imp phi1 phi2) x\" \n        by (simp add: antitonic_in_def monotonic_in_def)\n    qed\n\n    show \"occurrences (Imp phi1 phi2) x = Odd \\<longrightarrow> antitonic_in (Imp phi1 phi2) x\"\n    proof\n      assume \"occurrences (Imp phi1 phi2) x = Odd\"\n      then have \"merge (negate (occurrences phi1 x)) (occurrences phi2 x) = Odd\"\n        by simp\n      then have bothOdd: \"negate (occurrences phi1 x) = Odd \\<and> occurrences phi2 x = Odd\"\n        using mergeBothOdd by blast\n      from bothOdd have \"negate (occurrences phi1 x) = Odd\" ..\n      then have \"occurrences phi1 x = Even\"\n        using negateOccOddIsEven by simp\n      with Imp.IH have mono1: \"monotonic_in phi1 x\"\n        by simp\n      from bothOdd have \"occurrences phi2 x = Odd\" ..\n      with Imp.IH have anti2: \"antitonic_in phi2 x\"\n        by simp\n      from mono1 anti2 show \"antitonic_in (Imp phi1 phi2) x\" \n        by (simp add: antitonic_in_def monotonic_in_def)\n    qed\n  qed\nnext\n  case (Neg phi)\n  show ?case\n  proof\n    show \"occurrences (Neg phi) x = Even \\<longrightarrow> monotonic_in (Neg phi) x\"\n    proof\n      assume \"occurrences (Neg phi) x = Even\"\n      then have \"occurrences phi x = Odd\"\n        using occNegEvenIsOdd by simp\n      with Neg.IH have \"antitonic_in phi x\" \n        by simp\n      then show \"monotonic_in (Neg phi) x\" \n        by (auto simp add: antitonic_in_def monotonic_in_def)\n    qed\n\n    show \"occurrences (Neg phi) x = Odd \\<longrightarrow> antitonic_in (Neg phi) x\"\n    proof\n      assume \"occurrences (Neg phi) x = Odd\"\n      then have \"occurrences phi x = Even\"\n        using occNegOddIsEven by simp\n      with Neg.IH have \"monotonic_in phi x\" \n        by simp\n      then show \"antitonic_in (Neg phi) x\" \n        by (auto simp add: antitonic_in_def monotonic_in_def)\n    qed\n  qed\nqed\n\n\n\ntheorem \"(occurrences phi x = Even) \\<longrightarrow> (monotonic_in phi x)\" \n  by (simp add: aux)\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/Monotony.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.91243616285804, "lm_q2_score": 0.8128673201042493, "lm_q1q2_score": 0.7416895384686194}}
{"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_ISortCount\nimports \"../../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 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 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 (isort 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_ISortCount.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037282594921, "lm_q2_score": 0.8006920092299293, "lm_q1q2_score": 0.7416839933372672}}
{"text": "section \\<open>Root Filter via Interval Arithmetic\\<close>\n\nsubsection \\<open>Generic Framework\\<close>\n\ntext \\<open>We provide algorithms for finding all real or complex roots of a polynomial\n  from a superset of the roots via interval arithmetic. \n  These algorithms are much faster than just\n  evaluating the polynomial via algebraic number computations.\\<close>\n\ntheory Roots_via_IA\n  imports \n    Algebraic_Numbers.Interval_Arithmetic\nbegin\n\ndefinition interval_of_real :: \"nat \\<Rightarrow> real \\<Rightarrow> real interval\" where\n  \"interval_of_real prec x =\n      (if is_rat x then Interval x x\n       else let n = 2 ^ prec; x' = x * of_int n\n            in  Interval (of_rat (Rat.Fract \\<lfloor>x'\\<rfloor> n)) (of_rat (Rat.Fract \\<lceil>x'\\<rceil> n)))\"\n\ndefinition interval_of_complex :: \"nat \\<Rightarrow> complex \\<Rightarrow> complex_interval\" where\n  \"interval_of_complex prec z =\n     Complex_Interval (interval_of_real prec (Re z)) (interval_of_real prec (Im z))\"\n\nfun poly_interval :: \"'a :: {plus,times,zero} list \\<Rightarrow> 'a \\<Rightarrow> 'a\" where\n  \"poly_interval [] _ = 0\"\n| \"poly_interval [c] _ = c\"\n| \"poly_interval (c # cs) x = c + x * poly_interval cs x\"\n\ndefinition filter_fun_complex :: \"complex poly \\<Rightarrow> nat \\<Rightarrow> complex \\<Rightarrow> bool\" where\n  \"filter_fun_complex p = (let c = coeffs p in\n      (\\<lambda> prec. let cs = map (interval_of_complex prec) c\n      in (\\<lambda> x. 0 \\<in>\\<^sub>c poly_interval cs (interval_of_complex prec x))))\" \n\ndefinition filter_fun_real :: \"real poly \\<Rightarrow> nat \\<Rightarrow> real \\<Rightarrow> bool\" where\n  \"filter_fun_real p = (let c = coeffs p in\n      (\\<lambda> prec. let cs = map (interval_of_real prec) c\n      in (\\<lambda> x. 0 \\<in>\\<^sub>i poly_interval cs (interval_of_real prec x))))\" \n\ndefinition genuine_roots :: \"_ poly \\<Rightarrow> _ list \\<Rightarrow> _ list\" where\n  \"genuine_roots p xs = filter (\\<lambda>x. poly p x = 0) xs\"\n\nlemma zero_in_interval_0 [simp, intro]: \"0 \\<in>\\<^sub>i 0\"\n  unfolding zero_interval_def by auto\n\nlemma zero_in_complex_interval_0 [simp, intro]: \"0 \\<in>\\<^sub>c 0\"\n  unfolding zero_complex_interval_def by (auto simp: in_complex_interval_def)\n\nlemma length_coeffs_degree':\n  \"length (coeffs p) = (if p = 0 then 0 else Suc (degree p))\"\n  by (cases \"p = 0\") (auto simp: length_coeffs_degree)\n\nlemma poly_in_poly_interval_complex:\n  assumes \"list_all2 (\\<lambda>c ivl. c \\<in>\\<^sub>c ivl) (coeffs p) cs\" \"x \\<in>\\<^sub>c ivl\"\n  shows   \"poly p x \\<in>\\<^sub>c poly_interval cs ivl\"\nproof -\n  have len_eq: \"length (coeffs p) = length cs\"\n    using assms(1) list_all2_lengthD by blast\n  have \"coeffs p = map (\\<lambda>i. coeffs p ! i) [0..<length cs]\"\n    by (subst len_eq [symmetric], rule map_nth [symmetric])\n  also have \"\\<dots> = map (poly.coeff p) [0..<length cs]\"\n    by (intro map_cong) (auto simp: nth_coeffs_coeff len_eq)\n  finally have \"list_all2 (\\<lambda>c ivl. c \\<in>\\<^sub>c ivl) (map (poly.coeff p) [0..<length cs]) cs\"\n    using assms by simp\n  moreover have \"length cs \\<ge> length (coeffs p)\"\n    using len_eq by simp\n  ultimately show ?thesis using assms(2)\n  proof (induction cs ivl arbitrary: p x rule: poly_interval.induct)\n    case (1 ivl p x)\n    thus ?case by auto\n  next\n    case (2 c ivl p x)\n    have \"degree p = 0\"\n      using 2 by (auto simp: degree_eq_length_coeffs)\n    then obtain c' where [simp]: \"p = [:c':]\"\n      by (meson degree_eq_zeroE)\n    show ?case using 2 by auto\n  next\n    case (3 c1 c2 cs ivl p x)\n    obtain q c where [simp]: \"p = pCons c q\"\n      by (cases p rule: pCons_cases)\n    have \"list_all2 in_complex_interval (map (poly.coeff p) [0..<length (c1 # c2 # cs)])\n                  (c1 # c2 # cs)\"\n      using \"3.prems\"(1) by simp\n    also have \"[0..<length (c1 # c2 # cs)] = 0 # map Suc [0..<length (c2 # cs)]\"\n      by (metis length_Cons map_Suc_upt upt_conv_Cons zero_less_Suc)\n    also have \"map (poly.coeff p) \\<dots> = c # map (poly.coeff q) [0..<length (c2 # cs)]\"\n      by auto\n    finally have \"c \\<in>\\<^sub>c c1\" and\n        \"list_all2 in_complex_interval (map (poly.coeff q) [0..<length (c2 # cs)]) (c2 # cs)\"\n      using \"3.prems\" by (simp_all del: upt_Suc)\n\n    have IH: \"poly q x \\<in>\\<^sub>c poly_interval (c2 # cs) ivl\"\n    proof (rule \"3.IH\")\n      show \"length (coeffs q) \\<le> length (c2 # cs)\"\n        using \"3.prems\"(2) unfolding length_coeffs_degree' by auto\n    qed fact+\n\n    show ?case\n      using IH \"3.prems\" \\<open>c \\<in>\\<^sub>c c1\\<close>\n      by (auto intro!: plus_complex_interval times_complex_interval)\n  qed\nqed\n\nlemma poly_in_poly_interval_real: fixes x :: real \n  assumes \"list_all2 (\\<lambda>c ivl. c \\<in>\\<^sub>i ivl) (coeffs p) cs\" \"x \\<in>\\<^sub>i ivl\"\n  shows   \"poly p x \\<in>\\<^sub>i poly_interval cs ivl\"\nproof -\n  have len_eq: \"length (coeffs p) = length cs\"\n    using assms(1) list_all2_lengthD by blast\n  have \"coeffs p = map (\\<lambda>i. coeffs p ! i) [0..<length cs]\"\n    by (subst len_eq [symmetric], rule map_nth [symmetric])\n  also have \"\\<dots> = map (poly.coeff p) [0..<length cs]\"\n    by (intro map_cong) (auto simp: nth_coeffs_coeff len_eq)\n  finally have \"list_all2 (\\<lambda>c ivl. c \\<in>\\<^sub>i ivl) (map (poly.coeff p) [0..<length cs]) cs\"\n    using assms by simp\n  moreover have \"length cs \\<ge> length (coeffs p)\"\n    using len_eq by simp\n  ultimately show ?thesis using assms(2)\n  proof (induction cs ivl arbitrary: p x rule: poly_interval.induct)\n    case (1 ivl p x)\n    thus ?case by auto\n  next\n    case (2 c ivl p x)\n    have \"degree p = 0\"\n      using 2 by (auto simp: degree_eq_length_coeffs)\n    then obtain c' where [simp]: \"p = [:c':]\"\n      by (meson degree_eq_zeroE)\n    show ?case using 2 by auto\n  next\n    case (3 c1 c2 cs ivl p x)\n    obtain q c where [simp]: \"p = pCons c q\"\n      by (cases p rule: pCons_cases)\n    have \"list_all2 in_interval (map (poly.coeff p) [0..<length (c1 # c2 # cs)])\n                  (c1 # c2 # cs)\"\n      using \"3.prems\"(1) by simp\n    also have \"[0..<length (c1 # c2 # cs)] = 0 # map Suc [0..<length (c2 # cs)]\"\n      by (metis length_Cons map_Suc_upt upt_conv_Cons zero_less_Suc)\n    also have \"map (poly.coeff p) \\<dots> = c # map (poly.coeff q) [0..<length (c2 # cs)]\"\n      by auto\n    finally have \"c \\<in>\\<^sub>i c1\" and\n        \"list_all2 in_interval (map (poly.coeff q) [0..<length (c2 # cs)]) (c2 # cs)\"\n      using \"3.prems\" by (simp_all del: upt_Suc)\n\n    have IH: \"poly q x \\<in>\\<^sub>i poly_interval (c2 # cs) ivl\"\n    proof (rule \"3.IH\")\n      show \"length (coeffs q) \\<le> length (c2 # cs)\"\n        using \"3.prems\"(2) unfolding length_coeffs_degree' by auto\n    qed fact+\n\n    show ?case\n      using IH \"3.prems\" \\<open>c \\<in>\\<^sub>i c1\\<close>\n      by (auto intro!: plus_in_interval times_in_interval)\n  qed\nqed\n\n\nlemma in_interval_of_real [simp, intro]: \"x \\<in>\\<^sub>i interval_of_real prec x\"\n  unfolding interval_of_real_def by (auto simp: Let_def of_rat_rat field_simps)\n\nlemma in_interval_of_complex [simp, intro]: \"z \\<in>\\<^sub>c interval_of_complex prec z\"\n  unfolding interval_of_complex_def in_complex_interval_def by auto\n\nlemma distinct_genuine_roots [simp, intro]: \n  \"distinct xs \\<Longrightarrow> distinct (genuine_roots p xs)\"\n  by (simp add: genuine_roots_def)\n\ndefinition filter_fun :: \"'a poly \\<Rightarrow> (nat \\<Rightarrow> 'a :: comm_ring \\<Rightarrow> bool) \\<Rightarrow> bool\" where\n  \"filter_fun p f = (\\<forall> n x. poly p x = 0 \\<longrightarrow> f n x)\" \n\nlemma filter_fun_complex: \"filter_fun p (filter_fun_complex p)\"\n  unfolding filter_fun_def\nproof (intro impI allI)\n  fix prec x\n  assume root: \"poly p x = 0\" \n  define cs where \"cs = map (interval_of_complex prec) (coeffs p)\"\n  have cs: \"list_all2 in_complex_interval (coeffs p) cs\"\n    unfolding cs_def list_all2_map2 by (intro list_all2_refl in_interval_of_complex)\n  define P where \"P = (\\<lambda>x. 0 \\<in>\\<^sub>c poly_interval cs (interval_of_complex prec x))\"\n  have \"P x\" \n  proof -\n    have \"poly p x \\<in>\\<^sub>c poly_interval cs (interval_of_complex prec x)\"\n      by (intro poly_in_poly_interval_complex in_interval_of_complex cs)\n    with root show ?thesis\n      by (simp add: P_def)\n  qed\n  thus \"filter_fun_complex p prec x\" unfolding filter_fun_complex_def Let_def P_def\n    using cs_def by blast\nqed\n\nlemma filter_fun_real: \"filter_fun p (filter_fun_real p)\"\n  unfolding filter_fun_def\nproof (intro impI allI)\n  fix prec x\n  assume root: \"poly p x = 0\" \n  define cs where \"cs = map (interval_of_real prec) (coeffs p)\"\n  have cs: \"list_all2 in_interval (coeffs p) cs\"\n    unfolding cs_def list_all2_map2 by (intro list_all2_refl in_interval_of_real)\n  define P where \"P = (\\<lambda>x. 0 \\<in>\\<^sub>i poly_interval cs (interval_of_real prec x))\"\n  have \"P x\" \n  proof -\n    have \"poly p x \\<in>\\<^sub>i poly_interval cs (interval_of_real prec x)\"\n      by (intro poly_in_poly_interval_real in_interval_of_real cs)\n    with root show ?thesis\n      by (simp add: P_def)\n  qed\n  thus \"filter_fun_real p prec x\" unfolding filter_fun_real_def Let_def P_def\n    using cs_def by blast\nqed\n\ncontext\n  fixes p :: \"'a :: comm_ring poly\" and f\n  assumes ff: \"filter_fun p f\" \nbegin\n\nlemma genuine_roots_step:\n  \"genuine_roots p xs = genuine_roots p (filter (f prec) xs)\"\n  unfolding genuine_roots_def filter_filter \n  using ff[unfolded filter_fun_def, rule_format, of _ prec] by metis \n\nlemma genuine_roots_step_preserve_invar:\n  assumes \"{z. poly p z = 0} \\<subseteq> set xs\"\n  shows   \"{z. poly p z = 0} \\<subseteq> set (filter (f prec) xs)\"\nproof -\n  have \"{z. poly p z = 0} = set (genuine_roots p xs)\"\n    using assms by (auto simp: genuine_roots_def)\n  also have \"\\<dots> = set (genuine_roots p (filter (f prec) xs))\"\n    using genuine_roots_step[of _ prec] by simp\n  also have \"\\<dots> \\<subseteq> set (filter (f prec) xs)\"\n    by (auto simp: genuine_roots_def)\n  finally show ?thesis .\nqed\nend\n\nlemma genuine_roots_finish:\n  fixes p :: \"'a :: field_char_0 poly\" \n  assumes \"{z. poly p z = 0} \\<subseteq> set xs\" \"distinct xs\"\n  assumes \"length xs = card {z. poly p z = 0}\"\n  shows   \"genuine_roots p xs = xs\"\nproof -\n  have [simp]: \"p \\<noteq> 0\"\n    using finite_subset[OF assms(1) finite_set] infinite_UNIV_char_0 by auto\n  have \"length (genuine_roots p xs) = length xs\"\n    unfolding genuine_roots_def using assms \n    by (simp add: Int_absorb2 distinct_length_filter)\n  thus ?thesis\n    unfolding genuine_roots_def\n    by (metis filter_True length_filter_less linorder_not_less order_eq_iff)\nqed\n\ntext \\<open>This is type of the initial search problem. It consists of a polynomial $p$, \n  a list $xs$ of candidate roots, the cardinality of the set of roots of $p$ and a filter function to\n  drop non-roots that is parametric in a precision parameter.\\<close>\ntypedef (overloaded) 'a genuine_roots_aux =\n  \"{(p :: 'a :: field_char_0 poly, xs, n, ff). \n    distinct xs \\<and> \n    {z. poly p z = 0} \\<subseteq> set xs \\<and> \n    card {z. poly p z = 0} = n \\<and>\n    filter_fun p ff}\"\n  by (rule exI[of _ \"(1, [], 0, \\<lambda> _ _. False)\"], auto simp: filter_fun_def)\n\nsetup_lifting type_definition_genuine_roots_aux\n\nlift_definition genuine_roots' :: \"nat \\<Rightarrow> 'a :: field_char_0 genuine_roots_aux \\<Rightarrow> 'a list\" is\n  \"\\<lambda>prec (p, xs, n, ff). genuine_roots p xs\" .\n\nlift_definition genuine_roots_impl_step' :: \"nat \\<Rightarrow> 'a :: field_char_0 genuine_roots_aux \\<Rightarrow> 'a genuine_roots_aux\" is\n  \"\\<lambda>prec (p, xs, n, ff). (p, filter (ff prec) xs, n, ff)\"\n  by (safe, intro distinct_filter, auto simp: filter_fun_def)\n\nlift_definition gr_poly :: \"'a :: field_char_0 genuine_roots_aux \\<Rightarrow> 'a poly\" is\n  \"\\<lambda>(p :: 'a poly, _, _, _). p\" .\n\nlift_definition gr_list :: \"'a :: field_char_0 genuine_roots_aux \\<Rightarrow> 'a list\" is\n  \"\\<lambda>(_, xs :: 'a list, _, _). xs\" .\n\nlift_definition gr_numroots :: \"'a :: field_char_0 genuine_roots_aux \\<Rightarrow> nat\" is\n  \"\\<lambda>(_, _, n, _). n\" .\n\nlemma genuine_roots'_code [code]:\n  \"genuine_roots' prec gr =\n     (if length (gr_list gr) = gr_numroots gr then gr_list gr\n      else genuine_roots' (2 * prec) (genuine_roots_impl_step' prec gr))\"\nproof (transfer, clarify)\n  fix prec :: nat and p :: \"'a poly\" and xs :: \"'a list\" and ff\n  assume *: \"{z. poly p z = 0} \\<subseteq> set xs\" \"distinct xs\" \"filter_fun p ff\" \n  show \"genuine_roots p xs =\n          (if length xs = card {z. poly p z = 0} then xs\n           else genuine_roots p (filter (ff prec) xs))\"\n    using genuine_roots_finish[of p xs] genuine_roots_step[of p] * by auto\nqed\n\ndefinition initial_precision :: nat where \"initial_precision = 10\" \n\ndefinition genuine_roots_impl :: \"'a genuine_roots_aux \\<Rightarrow> 'a :: field_char_0 list\" where\n  \"genuine_roots_impl = genuine_roots' initial_precision\" \n\nlemma genuine_roots_impl: \"set (genuine_roots_impl p) = {z. poly (gr_poly p) z = 0}\" \n  \"distinct (genuine_roots_impl p)\" \n  unfolding genuine_roots_impl_def\n  by (transfer, auto simp: genuine_roots_def, transfer, 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/Factor_Algebraic_Polynomial/Roots_via_IA.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.880797071719777, "lm_q2_score": 0.8418256532040708, "lm_q1q2_score": 0.741477570240734}}
{"text": "(*\n  File:    Angles.thy\n  Author:  Manuel Eberl <manuel@pruvisto.org>\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": "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/Angles.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970685907242, "lm_q2_score": 0.8418256551882382, "lm_q1q2_score": 0.7414775693542659}}
{"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\ntext \\<open>Conflicting notation from \\<^theory>\\<open>HOL-Analysis.Infinite_Sum\\<close>\\<close>\nno_notation Infinite_Sum.abs_summable_on (infixr \"abs'_summable'_on\" 46)\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 A g\" \"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": "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/Skip_Lists/Skip_List.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.880797071719777, "lm_q2_score": 0.8418256472515683, "lm_q1q2_score": 0.7414775649977873}}
{"text": "(*  Title:      HOL/Taylor.thy\n    Author:     Lukas Bulwahn, Bernhard Haeupler, Technische Universitaet Muenchen\n*)\n\nsection {* Taylor series *}\n\ntheory Taylor\nimports MacLaurin\nbegin\n\ntext {*\nWe use MacLaurin and the translation of the expansion point @{text c} to @{text 0}\nto prove Taylor's theorem.\n*}\n\nlemma taylor_up: \n  assumes INIT: \"n>0\" \"diff 0 = f\"\n  and DERIV: \"(\\<forall> m t. m < n & a \\<le> t & t \\<le> b \\<longrightarrow> DERIV (diff m) t :> (diff (Suc m) t))\"\n  and INTERV: \"a \\<le> c\" \"c < b\" \n  shows \"\\<exists> t. c < t & t < b & \n    f b = (\\<Sum>m<n. (diff m c / real (fact m)) * (b - c)^m) + (diff n t / real (fact n)) * (b - c)^n\"\nproof -\n  from INTERV have \"0 < b-c\" by arith\n  moreover \n  from INIT have \"n>0\" \"((\\<lambda>m x. diff m (x + c)) 0) = (\\<lambda>x. f (x + c))\" by auto\n  moreover\n  have \"ALL m t. m < n & 0 <= t & t <= b - c --> DERIV (%x. diff m (x + c)) t :> diff (Suc m) (t + c)\"\n  proof (intro strip)\n    fix m t\n    assume \"m < n & 0 <= t & t <= b - c\"\n    with DERIV and INTERV have \"DERIV (diff m) (t + c) :> diff (Suc m) (t + c)\" by auto\n    moreover\n    from DERIV_ident and DERIV_const have \"DERIV (%x. x + c) t :> 1+0\" by (rule DERIV_add)\n    ultimately have \"DERIV (%x. diff m (x + c)) t :> diff (Suc m) (t + c) * (1+0)\"\n      by (rule DERIV_chain2)\n    thus \"DERIV (%x. diff m (x + c)) t :> diff (Suc m) (t + c)\" by simp\n  qed\n  ultimately \n  have EX:\"EX t>0. t < b - c & \n    f (b - c + c) = (SUM m<n. diff m (0 + c) / real (fact m) * (b - c) ^ m) +\n      diff n (t + c) / real (fact n) * (b - c) ^ n\" \n    by (rule Maclaurin)\n  show ?thesis\n  proof -\n    from EX obtain x where \n      X: \"0 < x & x < b - c & \n        f (b - c + c) = (\\<Sum>m<n. diff m (0 + c) / real (fact m) * (b - c) ^ m) +\n          diff n (x + c) / real (fact n) * (b - c) ^ n\" ..\n    let ?H = \"x + c\"\n    from X have \"c<?H & ?H<b \\<and> f b = (\\<Sum>m<n. diff m c / real (fact m) * (b - c) ^ m) +\n      diff n ?H / real (fact n) * (b - c) ^ n\"\n      by fastforce\n    thus ?thesis by fastforce\n  qed\nqed\n\nlemma taylor_down:\n  assumes INIT: \"n>0\" \"diff 0 = f\"\n  and DERIV: \"(\\<forall> m t. m < n & a \\<le> t & t \\<le> b \\<longrightarrow> DERIV (diff m) t :> (diff (Suc m) t))\"\n  and INTERV: \"a < c\" \"c \\<le> b\"\n  shows \"\\<exists> t. a < t & t < c & \n    f a = (\\<Sum>m<n. (diff m c / real (fact m)) * (a - c)^m) + (diff n t / real (fact n)) * (a - c)^n\" \nproof -\n  from INTERV have \"a-c < 0\" by arith\n  moreover \n  from INIT have \"n>0\" \"((\\<lambda>m x. diff m (x + c)) 0) = (\\<lambda>x. f (x + c))\" by auto\n  moreover\n  have \"ALL m t. m < n & a-c <= t & t <= 0 --> DERIV (%x. diff m (x + c)) t :> diff (Suc m) (t + c)\"\n  proof (rule allI impI)+\n    fix m t\n    assume \"m < n & a-c <= t & t <= 0\"\n    with DERIV and INTERV have \"DERIV (diff m) (t + c) :> diff (Suc m) (t + c)\" by auto \n    moreover\n    from DERIV_ident and DERIV_const have \"DERIV (%x. x + c) t :> 1+0\" by (rule DERIV_add)\n    ultimately have \"DERIV (%x. diff m (x + c)) t :> diff (Suc m) (t + c) * (1+0)\" by (rule DERIV_chain2)\n    thus \"DERIV (%x. diff m (x + c)) t :> diff (Suc m) (t + c)\" by simp\n  qed\n  ultimately \n  have EX: \"EX t>a - c. t < 0 &\n    f (a - c + c) = (SUM m<n. diff m (0 + c) / real (fact m) * (a - c) ^ m) +\n      diff n (t + c) / real (fact n) * (a - c) ^ n\" \n    by (rule Maclaurin_minus)\n  show ?thesis\n  proof -\n    from EX obtain x where X: \"a - c < x & x < 0 &\n      f (a - c + c) = (SUM m<n. diff m (0 + c) / real (fact m) * (a - c) ^ m) +\n        diff n (x + c) / real (fact n) * (a - c) ^ n\" ..\n    let ?H = \"x + c\"\n    from X have \"a<?H & ?H<c \\<and> f a = (\\<Sum>m<n. diff m c / real (fact m) * (a - c) ^ m) +\n      diff n ?H / real (fact n) * (a - c) ^ n\"\n      by fastforce\n    thus ?thesis by fastforce\n  qed\nqed\n\nlemma taylor:\n  assumes INIT: \"n>0\" \"diff 0 = f\"\n  and DERIV: \"(\\<forall> m t. m < n & a \\<le> t & t \\<le> b \\<longrightarrow> DERIV (diff m) t :> (diff (Suc m) t))\"\n  and INTERV: \"a \\<le> c \" \"c \\<le> b\" \"a \\<le> x\" \"x \\<le> b\" \"x \\<noteq> c\" \n  shows \"\\<exists> t. (if x<c then (x < t & t < c) else (c < t & t < x)) &\n    f x = (\\<Sum>m<n. (diff m c / real (fact m)) * (x - c)^m) + (diff n t / real (fact n)) * (x - c)^n\" \nproof (cases \"x<c\")\n  case True\n  note INIT\n  moreover from DERIV and INTERV\n  have \"\\<forall>m t. m < n \\<and> x \\<le> t \\<and> t \\<le> b \\<longrightarrow> DERIV (diff m) t :> diff (Suc m) t\"\n    by fastforce\n  moreover note True\n  moreover from INTERV have \"c \\<le> b\" by simp\n  ultimately have EX: \"\\<exists>t>x. t < c \\<and> f x =\n    (\\<Sum>m<n. diff m c / real (fact m) * (x - c) ^ m) + diff n t / real (fact n) * (x - c) ^ n\"\n    by (rule taylor_down)\n  with True show ?thesis by simp\nnext\n  case False\n  note INIT\n  moreover from DERIV and INTERV\n  have \"\\<forall>m t. m < n \\<and> a \\<le> t \\<and> t \\<le> x \\<longrightarrow> DERIV (diff m) t :> diff (Suc m) t\"\n    by fastforce\n  moreover from INTERV have \"a \\<le> c\" by arith\n  moreover from False and INTERV have \"c < x\" by arith\n  ultimately have EX: \"\\<exists>t>c. t < x \\<and> f x =\n    (\\<Sum>m<n. diff m c / real (fact m) * (x - c) ^ m) + diff n t / real (fact n) * (x - c) ^ n\" \n    by (rule taylor_up)\n  with False show ?thesis 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/Taylor.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473846343393, "lm_q2_score": 0.849971181358171, "lm_q1q2_score": 0.7414701370723601}}
{"text": "section \"Sorts\"\n\n(* \n  Some stuff on sorts. Mostly from Sort.ML I think.\n*)\n\ntheory Sorts\nimports Term\nbegin\n\ndefinition [simp]: \"empty_osig = ({}, Map.empty)\"\n\ndefinition \"sort_les cs s1 s2 = (sort_leq cs s1 s2 \\<and> \\<not> sort_leq cs s2 s1)\"\ndefinition \"sort_eqv cs s1 s2 = (sort_leq cs s1 s2 \\<and> sort_leq cs s2 s1)\"\n\nlemmas class_defs = class_leq_def class_les_def class_ex_def\nlemmas sort_defs = sort_leq_def sort_les_def sort_eqv_def sort_ex_def\n\nlemma sort_ex_class_ex: \"sort_ex cs S \\<equiv> \\<forall>c \\<in> S. class_ex cs c\"\n  by (auto simp add: sort_ex_def class_ex_def subset_eq)\n\n(* Did not want to write the wf_subclass cs assumption each time + allowed type class instances inside\n  Now probably more trouble than help\n*)\nlocale wf_subclass_loc =\n  fixes cs :: \"class rel\"\n  assumes wf[simp]: \"wf_subclass cs\"\nbegin \n\nlemma class_les_irrefl: \"\\<not> class_les cs c c\"\n  using wf by (simp add: class_les_def)\nlemma class_les_trans: \"class_les cs x y \\<Longrightarrow> class_les cs y z \\<Longrightarrow> class_les cs x z\"\n  using wf by (auto simp add: class_les_def class_leq_def trans_def)\n\nlemma class_leq_refl[iff]: \"class_ex cs c \\<Longrightarrow> class_leq cs c c\" \n  using wf by (simp add: class_leq_def class_ex_def refl_on_def) \nlemma class_leq_trans: \"class_leq cs x y \\<Longrightarrow> class_leq cs y z \\<Longrightarrow> class_leq cs x z\"\n  using wf by (auto simp add: class_leq_def elim: transE)\nlemma class_leq_antisym: \"class_leq cs c1 c2 \\<Longrightarrow> class_leq cs c2 c1 \\<Longrightarrow> c1=c2\" \n  using wf by (auto intro: antisymD simp: trans_def class_leq_def)\n\n(* classes form a ~ partial order with class_les/class_leq a for a well-formed a*)\nlemma sort_leq_refl[iff]: \"sort_ex cs s \\<Longrightarrow> sort_leq cs s s\" \n  using class_leq_refl by (auto simp add: sort_ex_class_ex sort_leq_def)\nlemma sort_leq_trans: \"sort_leq cs x y \\<Longrightarrow> sort_leq cs y z \\<Longrightarrow> sort_leq cs x z\"\n  by (meson class_leq_trans sort_leq_def)\nlemma sort_leq_ex: \"sort_leq cs s1 s2 \\<Longrightarrow> sort_ex cs s2\"\n  by (auto simp add: sort_ex_def class_leq_def sort_leq_def intro: FieldI2)\n(* ... *)\n\nlemma sort_leq_minimize: \n  \"sort_leq cs s1 s2 \\<Longrightarrow> \\<exists>s1'. (\\<forall>c1 \\<in> s1' . \\<exists>c2 \\<in> s2. class_leq cs c1 c2) \\<and> sort_leq cs s1' s2\"\n  by (meson class_leq_refl sort_ex_class_ex sort_leq_ex sort_leq_refl)\n\nlemma \"sort_ex cs s2 \\<Longrightarrow> s1 \\<subseteq> s2 \\<Longrightarrow> sort_ex cs s1\"\n  by (meson sort_ex_def subset_trans)\n\nlemma superset_imp_sort_leq: \"sort_ex cs s2 \\<Longrightarrow> s1 \\<supseteq> s2 \\<Longrightarrow> sort_leq cs s1 s2\"\n  by (auto simp add: sort_ex_class_ex sort_leq_def sort_ex_def)\nlemma full_sort_top: \"sort_ex cs s \\<Longrightarrow> sort_leq cs s full_sort\" \n  by (simp add: sort_leq_def)\n\n(* Is this even useful? *)\nlemma sort_les_trans: \"sort_les cs x y \\<Longrightarrow> sort_les cs y z \\<Longrightarrow> sort_les cs x z\"\n  using sort_les_def sort_leq_trans by blast\n                                                               \nlemma sort_eqvI: \"sort_leq cs s1 s2 \\<Longrightarrow> sort_leq cs s2 s1 \\<Longrightarrow> sort_eqv cs s1 s2\" \n  by (simp add: sort_eqv_def)\nlemma sort_eqv_refl: \"sort_ex cs s \\<Longrightarrow> sort_eqv cs s s\" \n  using sort_leq_refl by (auto simp add: sort_eqv_def)\nlemma sort_eqv_trans: \"sort_eqv cs x y \\<Longrightarrow> sort_eqv cs y z \\<Longrightarrow> sort_eqv cs x z\"\n  using sort_eqv_def sort_leq_trans by blast\nlemma sort_eqv_sym: \"sort_eqv cs x y \\<Longrightarrow> sort_eqv cs y x\"\n  by (auto simp add: sort_eqv_def)\n(* sort_eqv a is ~ equivalence relation.. *)\n\nlemma normalize_sort_empty[simp]: \"normalize_sort cs full_sort = full_sort\"\n  by (simp add: normalize_sort_def)\nlemma normalize_sort_normalize_sort[simp]: \n  \"normalize_sort cs (normalize_sort cs s) = normalize_sort cs s\" \n  by (auto simp add: normalize_sort_def)\n\nlemma sort_ex_norm_sort: \"sort_ex cs s \\<Longrightarrow> sort_ex cs (normalize_sort cs s)\"\n  by (simp add: normalize_sort_def sort_ex_class_ex)\n\nlemma normalized_sort_subset: \"normalize_sort cs s \\<subseteq> s\"\n  by (auto simp add: normalize_sort_def)\n\nlemma normalize_sort_removed_elem_irrelevant':\n  assumes \"sort_ex cs (insert c s)\"\n  assumes \"c \\<notin> (normalize_sort cs (insert c s))\"\n  shows \"normalize_sort cs (insert c s) = normalize_sort cs s\"\nproof-\n  have \"class_ex cs c\" using assms(1) by (auto simp add: sort_ex_class_ex)\n  from this assms(2) obtain c' where \"class_les cs c' c\" \"c' \\<in> s\"\n    using class_les_irrefl by (auto simp add: normalize_sort_def)\n  thus ?thesis \n    using \\<open>class_ex cs c\\<close> class_les_irrefl class_les_trans by (simp add: normalize_sort_def) blast\nqed\n\ncorollary normalize_sort_removed_elem_irrelevant:\n  assumes \"sort_ex cs (insert c s)\"\n  assumes \"c \\<notin> (normalize_sort cs (insert c s))\"\n  shows \"normalize_sort cs (insert c s) = normalize_sort cs s\"\n  using assms normalize_sort_removed_elem_irrelevant' \n  by (simp add: normalize_sort_def)\n\nlemma normalize_sort_nempt_is_nempty:\n  assumes finite: \"finite s\"\n  assumes nempty: \"s \\<noteq> full_sort\"\n  assumes \"sort_ex cs s\"\n  shows \"normalize_sort cs s \\<noteq> full_sort\"\nusing assms proof (induction s rule: finite_induct)\n  case empty\n  then show ?case by simp\nnext\n  case (insert c s)\n  note ICons = this\n  then show ?case\n  proof(cases s)\n    case emptyI\n    hence \"normalize_sort cs (insert c s) = {c}\"\n      using insert class_les_irrefl by (auto simp add: normalize_sort_def sort_ex_class_ex)\n    then show ?thesis by simp\n  next\n    case (insertI c' s')\n    hence \"normalize_sort cs s \\<noteq> full_sort\" \n      using ICons by (auto simp add: normalize_sort_def sort_ex_class_ex)\n    then show ?thesis\n    proof (cases \"c \\<in> (normalize_sort cs s)\")\n      case True\n      hence \"insert c s = s\" \n        using normalized_sort_subset by fastforce\n      then show ?thesis \n        using ICons by (auto simp add: normalize_sort_def sort_ex_class_ex class_les_def)\n    next\n      case False\n      then show ?thesis \n        using normalize_sort_removed_elem_irrelevant\n        using insert.prems(2) ICons(3) \\<open>normalize_sort cs s \\<noteq> full_sort\\<close> by auto\n    qed\n  qed\nqed\n\nlemma choose_smaller_in_sort:\n  assumes elem: \"c \\<in> s\" and nelem: \"c \\<notin> (normalize_sort cs s)\" and \"sort_ex cs s\"\n  obtains c' where \"c' \\<in> s\" and \"class_les cs c' c\"\n  using assms by (auto simp add: normalize_sort_def sort_ex_class_ex)\n\nlemma normalize_ex_bound':\n  assumes finite: \"finite s\" and elem: \"c \\<in> s\" and nelem: \"c \\<notin> (normalize_sort cs s)\" \n    and \"sort_ex cs s\"\n  shows \"\\<exists>c' \\<in> (normalize_sort cs s) . class_les cs c' c\"\nusing assms proof (induction s arbitrary: c)\n  case empty\n  then show ?case by simp\nnext\n  case (insert ic s)\n  then show ?case\n  proof(cases \"ic=c\")\n    case True\n    then show ?thesis\n      by (smt choose_smaller_in_sort class_les_irrefl class_les_trans insert.IH insert.prems(2) \n          insert.prems(3) insert_iff insert_subset normalize_sort_removed_elem_irrelevant' sort_ex_def)\n  next\n    case False\n    hence \"c \\<in> s\" using insert.prems by simp\n    then show ?thesis\n    proof(cases \"ic \\<in> (normalize_sort cs (insert ic s))\")\n      case True\n      then show ?thesis\n      proof(cases \"class_les cs ic c\")\n        case True\n        then show ?thesis\n          using insert \\<open>c \\<in> s\\<close> normalize_sort_removed_elem_irrelevant' sort_ex_def\n          by (metis insert_subset)\n      next\n        case False\n        \n        obtain c'' where c'': \"c'' \\<in> (normalize_sort cs s)\" \"class_les cs c'' c\"\n          using insert \\<open>c \\<in> s\\<close> normalize_sort_removed_elem_irrelevant' sort_ex_def\n          by (metis False choose_smaller_in_sort class_les_trans insert_iff insert_subset)\n        moreover have \"(c'', c) \\<in> cs\" \"(c, c'') \\<notin> cs\"\n          using c'' by (simp_all add: class_leq_def class_les_def)\n        moreover hence \"\\<not> class_les cs ic c''\"\n          by (meson False class_leq_def class_les_def class_les_trans)\n\n        ultimately show ?thesis \n          by (auto simp add: normalize_sort_def sort_ex_class_ex class_ex_def class_leq_def class_les_def)\n      qed\n    next\n      case False\n      then show ?thesis\n        by (metis (full_types) insert.IH insert.prems(2) insert.prems(3) \\<open>c \\<in> s\\<close> \n            normalize_sort_removed_elem_irrelevant sort_ex_def insert_subset)\n    qed\n  qed\nqed\n\ncorollary normalize_ex_bound:\n  assumes finite: \"finite s\" and elem: \"c \\<in> s\" and nelem: \"c \\<notin> (normalize_sort cs s)\" \n    and \"sort_ex cs s\"\n  obtains c' where \"c' \\<in> (normalize_sort cs s)\" and \"class_les cs c' c\"\n  using assms normalize_ex_bound' by auto\n\nlemma \"sort_ex cs s \\<Longrightarrow> sort_leq cs s (normalize_sort cs s)\" \n  by (auto simp add: normalize_sort_def sort_leq_def sort_ex_class_ex)\nlemma sort_eqv_normalize_sort:\n  assumes \"finite s\"\n  assumes \"sort_ex cs s\" \n  shows \"sort_eqv cs s (normalize_sort cs s)\"\nproof (intro sort_eqvI)\n  show \"sort_leq cs s (normalize_sort cs s)\" \n    using assms(2) by (auto simp add:  normalize_sort_def sort_leq_def sort_ex_class_ex)\nnext\n  show \"sort_leq cs (normalize_sort cs s) s\"\n  proof (unfold sort_leq_def; intro ballI)\n    fix c2 assume \"c2 \\<in> s\"\n    show \"\\<exists>c1 \\<in> normalize_sort cs s. class_leq cs c1 c2\"\n    proof (cases \"c2 \\<in> normalize_sort cs s\")\n      case True\n      then show ?thesis using \\<open>c2 \\<in> s\\<close> assms sort_ex_class_ex by fast\n    next\n      case False\n      from this obtain c' where \"c' \\<in> normalize_sort cs s\" and \"class_les cs c' c2\" \n        using \\<open>c2 \\<in> s\\<close> normalize_ex_bound assms by metis\n      then show ?thesis using class_les_def by metis\n    qed \n  qed\nqed\n\nlemma normalize_sort_eq_imp_sort_eqv: \"sort_ex cs s1 \\<Longrightarrow> sort_ex cs s2 \\<Longrightarrow> finite s1 \\<Longrightarrow> finite s2\n  \\<Longrightarrow> normalize_sort cs s1 = normalize_sort cs s2\n  \\<Longrightarrow> sort_eqv cs s1 s2\"\n  by (metis sort_eqv_sym sort_eqv_trans wf_subclass_loc.sort_eqv_normalize_sort wf_subclass_loc_axioms)\n\nlemma \"class_leq cs c1 c2 \\<longleftrightarrow> class_les cs c1 c2 \\<or> (c1=c2 \\<and> class_ex cs c1)\"\n  by (meson FieldI1 class_ex_def class_leq_antisym class_leq_def class_leq_refl class_les_def)\n\nlemma sort_eqv_imp_normalize_sort_eq:\n  assumes \"sort_ex cs s1\" \"sort_ex cs s2\" \"sort_eqv cs s1 s2\"\n  shows \"normalize_sort cs s1 = normalize_sort cs s2\"\nproof (rule ccontr)\n  have \"sort_leq cs s1 s2\" \"sort_leq cs s2 s1\"\n    using assms(3) by (auto simp add: sort_eqv_def)\n\n  assume \"normalize_sort cs s1 \\<noteq> normalize_sort cs s2\"\n  hence \"\\<not> normalize_sort cs s1 \\<subseteq> normalize_sort cs s2 \\<or> \n    \\<not> normalize_sort cs s2 \\<subseteq> normalize_sort cs s1\"\n    by simp\n  from this consider \"\\<not> normalize_sort cs s1 \\<subseteq> normalize_sort cs s2\"\n    | \"normalize_sort cs s1 \\<subseteq> normalize_sort cs s2\" \n      \"\\<not> normalize_sort cs s2 \\<subseteq> normalize_sort cs s1\"\n    by blast\n  thus False\n  proof cases\n    case 1\n    from this obtain c where c: \"c \\<in> normalize_sort cs s1\" \"c \\<notin> normalize_sort cs s2\"\n      by blast\n    from this obtain c' where c': \"c' \\<in> normalize_sort cs s2\" \"class_les cs c' c\"\n      by (smt \\<open>sort_leq cs s1 s2\\<close> \\<open>sort_leq cs s2 s1\\<close> class_les_def mem_Collect_eq normalize_sort_def \n          sort_leq_def wf_subclass_loc.class_leq_antisym wf_subclass_loc.class_leq_trans wf_subclass_loc_axioms)\n    then show ?thesis\n    proof(cases \"c' \\<in> normalize_sort cs s1\")\n      case True\n      hence \"c \\<notin> normalize_sort cs s1\"\n        using c c' by (auto simp add: normalize_sort_def)\n      then show ?thesis using c(1) by simp\n    next\n      case False\n      from False c' obtain c'' where c'': \"c'' \\<in> normalize_sort cs s1\" \"class_les cs c'' c'\"\n      by (smt \\<open>sort_leq cs s1 s2\\<close> \\<open>sort_leq cs s2 s1\\<close> class_les_def mem_Collect_eq normalize_sort_def \n          sort_leq_def wf_subclass_loc.class_leq_antisym wf_subclass_loc.class_leq_trans wf_subclass_loc_axioms)\n      hence \"class_les cs c'' c\"\n        using c'(2) class_les_trans by blast\n      hence \"c \\<notin> normalize_sort cs s1\"\n        using c c'' by (auto simp add: normalize_sort_def)\n      then show ?thesis using c(1) by simp\n    qed\n  next\n    (* Should work analogous, let's see *)\n    case 2\n    from this obtain c where c: \"c \\<in> normalize_sort cs s2\" \"c \\<notin> normalize_sort cs s1\"\n      by blast\n    from this obtain c' where c': \"c' \\<in> normalize_sort cs s1\" \"class_les cs c' c\"\n      by (smt \\<open>sort_leq cs s1 s2\\<close> \\<open>sort_leq cs s2 s1\\<close> class_les_def mem_Collect_eq normalize_sort_def \n          sort_leq_def wf_subclass_loc.class_leq_antisym wf_subclass_loc.class_leq_trans wf_subclass_loc_axioms)\n    then show ?thesis\n    proof(cases \"c' \\<in> normalize_sort cs s2\")\n      case True\n      hence \"c \\<notin> normalize_sort cs s2\"\n        using c c' by (auto simp add: normalize_sort_def)\n      then show ?thesis using c(1) by simp\n    next\n      case False\n      from False c' obtain c'' where c'':\"c''\\<in> normalize_sort cs s2\" \"class_les cs c'' c'\"\n      by (smt \\<open>sort_leq cs s1 s2\\<close> \\<open>sort_leq cs s2 s1\\<close> class_les_def mem_Collect_eq normalize_sort_def \n          sort_leq_def wf_subclass_loc.class_leq_antisym wf_subclass_loc.class_leq_trans wf_subclass_loc_axioms)\n      hence \"class_les cs c'' c\"\n        using c'(2) class_les_trans by blast\n      hence \"c \\<notin> normalize_sort cs s2\"\n        using c c'' by (auto simp add: normalize_sort_def)\n      then show ?thesis using c(1) by simp\n    qed\n  qed\nqed\n\ncorollary sort_eqv_iff_normalize_sort_eq:\n  assumes \"finite s1\" \"finite s2\"\n  assumes \"sort_ex cs s1\" \"sort_ex cs s2\"\n  shows \"sort_eqv cs s1 s2 \\<longleftrightarrow> normalize_sort cs s1 = normalize_sort cs s2\"\nusing assms normalize_sort_eq_imp_sort_eqv sort_eqv_imp_normalize_sort_eq by blast\n\nend\n\nlemma tcsigs_sorts_defined: \"wf_osig oss \\<Longrightarrow> \n  (\\<forall>ars \\<in> ran (tcsigs oss) . \\<forall>ss \\<in> ran ars . \\<forall>s \\<in> set ss. sort_ex (subclass oss) s)\"\n  by (cases oss) (simp add: wf_sort_def all_normalized_and_ex_tcsigs_def)\n\nlemma osig_subclass_loc: \"wf_osig oss \\<Longrightarrow> wf_subclass_loc (subclass oss)\"\n  using wf_subclass_loc.intro by (cases oss) simp\n\nlemma wf_osig_imp_wf_subclass_loc: \"wf_osig oss \\<Longrightarrow> wf_subclass_loc (subclass oss)\"\n  by (cases oss) (simp add: wf_subclass_loc_def)\n\nlemma has_sort_Tv_imp_sort_leq: \"has_sort oss (Tv idn S) S' \\<Longrightarrow> sort_leq (subclass oss) S S'\"\n  by (auto simp add: has_sort.simps)\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/Metalogic_ProofChecker/Sorts.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473779969194, "lm_q2_score": 0.8499711718571774, "lm_q1q2_score": 0.7414701231425777}}
{"text": "\n\n(*<*) theory ex3_2 imports Main begin (*>*)\n\ntext{*\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\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*}\nfun sq ::\"nat \\<Rightarrow> nat\" where\n\"sq 0 =0\"\n|\"sq x = sq(x-1) +x-1 +x\"\n\n\n\nlemma aux[rule_format]: \"!m. m <= n \\<longrightarrow> sq n = ((n + (n-m))* m) + sq (n-m)\"\n  apply (induct_tac n, auto)\n  apply (case_tac m, auto)\ndone\n\nlemma \"\\<forall>y.(y<x \\<longrightarrow> (sq x  = ((x+(x-y))*y)+sq (x-y)))\"\n  apply (induct_tac x )\n   apply auto\n  apply(case_tac y)\n   apply auto\n  done\nlemma [simp]:\"(sq (a+b) = sq a + sq b + 2*a*b)\" \n  apply(induct b)\n   apply auto\n  done\n\nlemma [simp]:\"(sq (a*b) = (sq a) * (sq b) )\" \n\n  by (simp add: add_mult_distrib2 mult.commute)\n\n\n\nlemma \"sq((a*10)+5) =a*(a+1)*100+ 25\"\n\n  by (simp add: add_mult_distrib2 mult.commute)\n\n\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/ex3_2.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8723473680407889, "lm_q2_score": 0.849971181358171, "lm_q1q2_score": 0.7414701229683205}}
{"text": "(*<*)theory PDL imports Base begin(*>*)\n\nsubsection\\<open>Propositional Dynamic Logic --- PDL\\<close>\n\ntext\\<open>\\index{PDL|(}\nThe formulae of PDL are built up from atomic propositions via\nnegation and conjunction and the two temporal\nconnectives \\<open>AX\\<close> and \\<open>EF\\<close>\\@. Since formulae are essentially\nsyntax trees, they are naturally modelled as a datatype:%\n\\footnote{The customary definition of PDL\n\\<^cite>\\<open>\"HarelKT-DL\"\\<close> looks quite different from ours, but the two are easily\nshown to be equivalent.}\n\\<close>\n\ndatatype formula = Atom \"atom\"\n                  | Neg formula\n                  | And formula formula\n                  | AX formula\n                  | EF formula\n\ntext\\<open>\\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 \\<open>s \\<Turnstile> f\\<close> instead of\n\\hbox{\\<open>valid s f\\<close>}. The definition is by recursion over the syntax:\n\\<close>\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\\<open>\\noindent\nThe first three equations should be self-explanatory. The temporal formula\n\\<^term>\\<open>AX f\\<close> means that \\<^term>\\<open>f\\<close> is true in \\emph{A}ll ne\\emph{X}t states whereas\n\\<^term>\\<open>EF f\\<close> means that there \\emph{E}xists some \\emph{F}uture state in which \\<^term>\\<open>f\\<close> is\ntrue. The future is expressed via \\<open>\\<^sup>*\\<close>, 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:\\<close>\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\\<open>\\noindent\nOnly the equation for \\<^term>\\<open>EF\\<close> deserves some comments. Remember that the\npostfix \\<open>\\<inverse>\\<close> and the infix \\<open>``\\<close> are predefined and denote the\nconverse of a relation and the image of a set under a relation.  Thus\n\\<^term>\\<open>M\\<inverse> `` T\\<close> is the set of all predecessors of \\<^term>\\<open>T\\<close> and the least\nfixed point (\\<^term>\\<open>lfp\\<close>) of \\<^term>\\<open>\\<lambda>T. mc f \\<union> M\\<inverse> `` T\\<close> is the least set\n\\<^term>\\<open>T\\<close> containing \\<^term>\\<open>mc f\\<close> and all predecessors of \\<^term>\\<open>T\\<close>. If you\nfind it hard to see that \\<^term>\\<open>mc(EF f)\\<close> contains exactly those states from\nwhich there is a path to a state where \\<^term>\\<open>f\\<close> is true, do not worry --- this\nwill be proved in a moment.\n\nFirst we prove monotonicity of the function inside \\<^term>\\<open>lfp\\<close>\nin order to make sure it really has a least fixed point.\n\\<close>\n\nlemma mono_ef: \"mono(\\<lambda>T. A \\<union> (M\\<inverse> `` T))\"\napply(rule monoI)\napply blast\ndone\n\ntext\\<open>\\noindent\nNow we can relate model checking and semantics. For the \\<open>EF\\<close> case we need\na separate lemma:\n\\<close>\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\\<open>\\noindent\nThe equality is proved in the canonical fashion by proving that each set\nincludes the other; the inclusion is shown pointwise:\n\\<close>\n\napply(rule equalityI)\n apply(rule subsetI)\n apply(simp)(*<*)apply(rename_tac s)(*>*)\n\ntxt\\<open>\\noindent\nSimplification leaves us with the following first subgoal\n@{subgoals[display,indent=0,goals_limit=1]}\nwhich is proved by \\<^term>\\<open>lfp\\<close>-induction:\n\\<close>\n\n apply(erule lfp_induct_set)\n  apply(rule mono_ef)\n apply(simp)\ntxt\\<open>\\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 \\<open>blast\\<close>, using the transitivity of \n\\isa{M\\isactrlsup {\\isacharasterisk}}.\n\\<close>\n\n apply(blast intro: rtrancl_trans)\n\ntxt\\<open>\nWe now return to the second set inclusion subgoal, which is again proved\npointwise:\n\\<close>\n\napply(rule subsetI)\napply(simp, clarify)\n\ntxt\\<open>\\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>\\<open>(s,t)\\<in>M\\<^sup>*\\<close>. But since the model\nchecker works backwards (from \\<^term>\\<open>t\\<close> to \\<^term>\\<open>s\\<close>), 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>\\<open>(a,b)\\<in>r\\<^sup>*\\<close> and we know \\<^prop>\\<open>P b\\<close> then we can infer\n\\<^prop>\\<open>P a\\<close> provided each step backwards from a predecessor \\<^term>\\<open>z\\<close> of\n\\<^term>\\<open>b\\<close> preserves \\<^term>\\<open>P\\<close>.\n\\<close>\n\napply(erule converse_rtrancl_induct)\n\ntxt\\<open>\\noindent\nThe base case\n@{subgoals[display,indent=0,goals_limit=1]}\nis solved by unrolling \\<^term>\\<open>lfp\\<close> once\n\\<close>\n\n apply(subst lfp_unfold[OF mono_ef])\n\ntxt\\<open>\n@{subgoals[display,indent=0,goals_limit=1]}\nand disposing of the resulting trivial subgoal automatically:\n\\<close>\n\n apply(blast)\n\ntxt\\<open>\\noindent\nThe proof of the induction step is identical to the one for the base case:\n\\<close>\n\napply(subst lfp_unfold[OF mono_ef])\napply(blast)\ndone\n\ntext\\<open>\nThe main theorem is proved in the familiar manner: induction followed by\n\\<open>auto\\<close> augmented with the lemma as a simplification rule.\n\\<close>\n\ntheorem \"mc f = {s. s \\<Turnstile> f}\"\napply(induct_tac f)\napply(auto simp add: EF_lemma)\ndone\n\ntext\\<open>\n\\begin{exercise}\n\\<^term>\\<open>AX\\<close> has a dual operator \\<^term>\\<open>EN\\<close> \n(``there exists a next state such that'')%\n\\footnote{We cannot use the customary \\<open>EX\\<close>: it is reserved\nas the \\textsc{ascii}-equivalent of \\<open>\\<exists>\\<close>.}\nwith the intended semantics\n@{prop[display]\"(s \\<Turnstile> EN f) = (\\<exists>t. (s,t) \\<in> M \\<and> t \\<Turnstile> f)\"}\nFortunately, \\<^term>\\<open>EN f\\<close> can already be expressed as a PDL formula. How?\n\nShow that the semantics for \\<^term>\\<open>EF\\<close> 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\\<close>\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 \\<in> 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": "seL4", "repo": "isabelle", "sha": "e1ab32a3bb41728cd19541063283e37919978a4c", "save_path": "github-repos/isabelle/seL4-isabelle", "path": "github-repos/isabelle/seL4-isabelle/isabelle-e1ab32a3bb41728cd19541063283e37919978a4c/src/Doc/Tutorial/CTL/PDL.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.84997116805678, "lm_q2_score": 0.8723473796562744, "lm_q1q2_score": 0.7414701212377148}}
{"text": "(* File: boolexp.thy *)\n\ntheory boolexp\nimports Main\nbegin\n\nsection{* Basic Type and Evaluation Function\n         for Boolean Expressions *}\n\ntext{*\n The following type mirrors the BNF grammar\nwe gave in for boolean expressions.  We will use\nonly prefixed connectives here\n*}\n\ndatatype 'a boolexp =\n   TRUE | FALSE |Var 'a | Not \"'a boolexp\"\n  | And \"'a boolexp\" \"'a boolexp\"\n  | Or \"'a boolexp\" \"'a boolexp\"\n  | Implies \"'a boolexp\" \"'a boolexp\"\n\nvalue \"TRUE\"\n\ntext{*\nThe following is a recursive definition of the function for evaluating\nboolean expressions. It is the same as the definition\nof \\textit{models} given in class. \n*}\n\nfun boolexp_eval \nwhere\n   \"boolexp_eval env TRUE = True\"\n | \"boolexp_eval env FALSE = False\"\n | \"boolexp_eval env (Var x) = env x\"\n | \"boolexp_eval env (Not b) = (\\<not> (boolexp_eval env b))\"\n | \"boolexp_eval env (And a b) =\n    ((boolexp_eval env a) \\<and> (boolexp_eval env b))\"\n | \"boolexp_eval env (Or a b) =\n    ((boolexp_eval env a) \\<or> (boolexp_eval env b))\"\n | \"boolexp_eval env (Implies a b) =\n    ((\\<not> (boolexp_eval env a))\\<or> (boolexp_eval env b))\"\n\ntext{*\nBecause all our definition have been purely\ncomputational, we may use \\tettt{value} to evaluate\nexpressions using the type \\texttt{boolexp} and the term\nboolexp_eval.\n*}\n\n(*\nvalue \"boolexp_eval\n(\\<lambda> x. case x of ''a'' \\<Rightarrow> True | _ \\<Rightarrow> False)\n (Implies (Var ''b'') (Var ''a''))\"\n*)\n\n\nvalue \"boolexp_eval\n(\\<lambda> x. case x of (0::nat) \\<Rightarrow> True | _ \\<Rightarrow> False)\n (Implies (Var (1::nat)) (Var (0::nat)))\"\n\n\ntext{*\nOur objective is to build a function that will tell\nus all the ways a boolean expression can be satisfied.\nOur approach is to put the boolean expression in\ndisjunctive normal form.\nWe start by eliminating implies.\n*}\n\nfun remove_implies where\n   \"remove_implies TRUE = TRUE\"\n | \"remove_implies FALSE = FALSE\"\n | \"remove_implies (Var x) = Var x\"\n | \"remove_implies (Not a) = Not (remove_implies a)\"\n | \"remove_implies (And a b) =\n    And (remove_implies a) (remove_implies b)\"\n | \"remove_implies (Or a b) =\n    Or (remove_implies a) (remove_implies b)\"\n | \"remove_implies (Implies a b) =\n    (Or (Not (remove_implies a)) (remove_implies b))\"\n\nthm boolexp.induct\n\nlemma remove_implies_same_eval [simp]:\n\"boolexp_eval env (remove_implies a) =\n boolexp_eval env a\"\napply (induct \"a\")\nby simp_all\n(*\nby (induct \"a\", auto)\n*)\n\nfun number_of_implies where\n   \"number_of_implies TRUE = (0::nat)\"\n | \"number_of_implies FALSE = 0\"\n | \"number_of_implies (Var x) = 0\"\n | \"number_of_implies (Not a) = number_of_implies a\"\n | \"number_of_implies (And a b) =\n   (number_of_implies a) + (number_of_implies b)\"\n | \"number_of_implies (Or a b) =\n   (number_of_implies a) + (number_of_implies b)\"\n | \"number_of_implies (Implies a b) =\n   (number_of_implies a) + (number_of_implies b) + 1\" \n\nlemma number_of_implies_remove_implies_0 [simp]:\n\"number_of_implies (remove_implies a) = 0\"\nby (induct \"a\", auto)\n\n\nfun push_not where   \n   \"push_not TRUE = TRUE\"\n | \"push_not FALSE = FALSE\"\n | \"push_not (Var x) = Var x\"          \n | \"push_not (Not TRUE) = FALSE\"\n | \"push_not (Not FALSE) = TRUE\"\n | \"push_not (Not (Var x)) = Not (Var x)\"\n | \"push_not (Not (Not a)) = push_not a\"\n | \"push_not (Not (And a b)) =\n    (Or (push_not (Not a)) (push_not (Not b)))\"\n | \"push_not (Not (Or a b)) =\n    (And (push_not (Not a)) (push_not (Not b)))\"\n | \"push_not (Not (Implies a b)) =\n   (And (push_not a) (push_not (Not b)))\"\n | \"push_not (And a b) =\n   (And (push_not a) (push_not b))\"      \n | \"push_not (Or a b) =\n   (Or (push_not a) (push_not b))\"      \n | \"push_not (Implies a b) =\n    (Implies (push_not a) (push_not b))\"\n\nlemma push_not_same_eval [simp]:\n \"(boolexp_eval env (push_not (Not a))\n   = (\\<not> (boolexp_eval env (push_not a)))) \\<and>\n  (boolexp_eval env (push_not a) = boolexp_eval env a)\"\nby (induct \"a\", auto)\n\nlemma push_not_preserves_no_implies_helper:\n\"number_of_implies a = 0 \\<Longrightarrow>\n (number_of_implies (push_not a) = 0) \\<and>\n (number_of_implies (push_not (Not a)) = 0)\"\nby (induct \"a\", auto)\n\nlemma push_not_preserves_no_implies:\n\"number_of_implies a = 0 \\<Longrightarrow>\n (number_of_implies (push_not a) = 0)\"\nby (auto simp add: push_not_preserves_no_implies_helper)\n\nlemma push_not_remove_implies_no_implies [simp]:\n\"number_of_implies (push_not (remove_implies a)) = 0\"\napply (rule push_not_preserves_no_implies)\napply (rule number_of_implies_remove_implies_0)\ndone\n\n\nexport_code boolexp_eval push_not remove_implies\nin OCaml\n module_name Boolexp file \"boolexp.ml\"\n\n\ndatatype 'a boolexp_no_imp =\n      TRUE_ni | FALSE_ni |Var_ni 'a\n    | Not_ni \"'a boolexp_no_imp\"\n    | And_ni \"'a boolexp_no_imp\" \"'a boolexp_no_imp\"\n    | Or_ni \"'a boolexp_no_imp\" \"'a boolexp_no_imp\"\n\nfun boolexp_no_imp_eval where\n   \"boolexp_no_imp_eval env TRUE_ni = True\"\n | \"boolexp_no_imp_eval env FALSE_ni = False\"\n | \"boolexp_no_imp_eval env (Var_ni x) = env x\"\n | \"boolexp_no_imp_eval env (Not_ni a) =\n    (\\<not> (boolexp_no_imp_eval env a))\"\n | \"boolexp_no_imp_eval env (And_ni a b) =\n    ((boolexp_no_imp_eval env a) \\<and>\n     (boolexp_no_imp_eval env b))\"\n | \"boolexp_no_imp_eval env (Or_ni a b) =\n    ((boolexp_no_imp_eval env a) \\<or>\n     (boolexp_no_imp_eval env b))\"\n\n\nfun remove_implies_ni where\n   \"remove_implies_ni TRUE = TRUE_ni\"\n | \"remove_implies_ni FALSE = FALSE_ni\"\n | \"remove_implies_ni (Var x) = Var_ni x\"\n | \"remove_implies_ni (Not a) =\n    Not_ni (remove_implies_ni a)\"\n | \"remove_implies_ni (And a b) =\n    And_ni (remove_implies_ni a) (remove_implies_ni b)\"\n | \"remove_implies_ni (Or a b) =\n    Or_ni (remove_implies_ni a) (remove_implies_ni b)\"\n | \"remove_implies_ni (Implies a b) =\n    (Or_ni (Not_ni (remove_implies_ni a))\n           (remove_implies_ni b))\"\n\nlemma remove_implies_ni_same_eval:\n  \"boolexp_no_imp_eval env (remove_implies_ni a) =\n   boolexp_eval env (remove_implies a)\"\nby (induct_tac a, auto)\n\ndatatype 'a boolexp_nipn =\n    TRUE_nipn | FALSE_nipn |Var_nipn 'a\n    | Not_Var_nipn 'a\n    | And_nipn \"'a boolexp_nipn\" \"'a boolexp_nipn\"\n    | Or_nipn \"'a boolexp_nipn\" \"'a boolexp_nipn\"\n\nfun push_not_pn where\n   \"push_not_pn TRUE_ni = TRUE_nipn\"\n | \"push_not_pn FALSE_ni = FALSE_nipn\"\n | \"push_not_pn (Var_ni x) = Var_nipn x\"      \n | \"push_not_pn (Not_ni TRUE_ni) = FALSE_nipn\"\n | \"push_not_pn (Not_ni FALSE_ni) = TRUE_nipn\"\n | \"push_not_pn (Not_ni (Var_ni x)) = Not_Var_nipn x\"\n | \"push_not_pn (Not_ni (Not_ni a)) = push_not_pn a\"\n | \"push_not_pn (Not_ni (And_ni a b)) =\n    (Or_nipn (push_not_pn (Not_ni a))\n             (push_not_pn (Not_ni b)))\"\n | \"push_not_pn (Not_ni (Or_ni a b)) =\n    (And_nipn (push_not_pn (Not_ni a))\n              (push_not_pn (Not_ni b)))\"\n | \"push_not_pn (And_ni a b) = \n   (And_nipn (push_not_pn a) (push_not_pn b))\"    \n | \"push_not_pn (Or_ni a b) =\n   (Or_nipn (push_not_pn a) (push_not_pn b))\"\n\nfun boolexp_nipn_eval where\n   \"boolexp_nipn_eval env TRUE_nipn = True\"\n | \"boolexp_nipn_eval env FALSE_nipn = False\"\n | \"boolexp_nipn_eval env (Var_nipn x) = env x\"\n | \"boolexp_nipn_eval env (Not_Var_nipn a) =\n    (\\<not> (env a))\"\n | \"boolexp_nipn_eval env (And_nipn a b) =\n    ((boolexp_nipn_eval env a) \\<and>\n     (boolexp_nipn_eval env b))\"\n | \"boolexp_nipn_eval env (Or_nipn a b) =\n    ((boolexp_nipn_eval env a) \\<or>\n     (boolexp_nipn_eval env b))\"\n\nlemma push_not_pn_same_eval [simp]:\n\"(boolexp_nipn_eval env (push_not_pn (Not_ni b)) =\n  (\\<not> (boolexp_no_imp_eval env b))) \\<and>\n (boolexp_nipn_eval env (push_not_pn b) =\n  boolexp_no_imp_eval env b)\"\nby (induct_tac b, auto)\n\nfun node_count where     \n   \"node_count TRUE = (1::nat)\"\n | \"node_count FALSE = 1\"\n | \"node_count (Var x) = 1\"\n | \"node_count (Not x) = 1 + node_count x\"\n | \"node_count (And a b) =\n    1 + (node_count a) + (node_count b)\"\n | \"node_count (Or a b) =\n    1 + (node_count a) + (node_count b)\"\n | \"node_count (Implies a b) =\n    1 + (node_count a) + (node_count b)\" \n \nlemma node_count_non_zero [simp]:\n\"0 < node_count b\"\nby (induct_tac b, auto)\n\nfunction push_not_elim_imp where   \n   \"push_not_elim_imp TRUE = TRUE_nipn\"\n | \"push_not_elim_imp FALSE = FALSE_nipn\"\n | \"push_not_elim_imp (Var x) = Var_nipn x\"          \n | \"push_not_elim_imp (Not TRUE) = FALSE_nipn\"\n | \"push_not_elim_imp (Not FALSE) = TRUE_nipn\"\n | \"push_not_elim_imp (Not (Var x)) = Not_Var_nipn x\"\n | \"push_not_elim_imp (Not (Not b)) =\n    push_not_elim_imp b\"\n | \"push_not_elim_imp (Not (And a b)) =\n    (Or_nipn (push_not_elim_imp (Not a))\n             (push_not_elim_imp (Not b)))\"\n | \"push_not_elim_imp (Not (Or a b)) =\n    (And_nipn (push_not_elim_imp (Not a))\n              (push_not_elim_imp (Not b)))\"\n | \"push_not_elim_imp (Not (Implies a b)) =\n   (And_nipn (push_not_elim_imp a)\n             (push_not_elim_imp (Not b)))\"\n | \"push_not_elim_imp (And a b) =\n   (And_nipn (push_not_elim_imp a)\n             (push_not_elim_imp b))\"      \n | \"push_not_elim_imp (Or a b) =\n   (Or_nipn (push_not_elim_imp a)\n            (push_not_elim_imp b))\"      \n | \"push_not_elim_imp (Implies a b) =\n    (Or_nipn (push_not_elim_imp (Not a))\n             (push_not_elim_imp b))\"                   \nby (pat_completeness, auto)\nterm \"op <*mlex*>\"\ntermination\nby (relation \"measures [node_count]\", auto)\n\nlemma push_not_elim_imp_push_not_pn_remove_implies_ni [simp]:\n\"(push_not_elim_imp (boolexp.Not a) =\n  push_not_pn (Not_ni (remove_implies_ni a))) \\<and>\n (push_not_elim_imp a =\n  push_not_pn (remove_implies_ni a))\"\nby (induct_tac a, auto)\n\nlemma push_not_elim_imp_same_eval [simp]:\n\"(boolexp_nipn_eval env (push_not_elim_imp (Not a)) =\n  (\\<not>(boolexp_eval env a))) \\<and>\n (boolexp_nipn_eval env (push_not_elim_imp a) =\n  boolexp_eval env a)\"\nby (induct_tac a, auto)\n\ndatatype 'a bool_atom =\n   TRUE_at | FALSE_at |Var_at 'a | Not_Var_at 'a\n   \nfun bool_atom_eval where\n   \"bool_atom_eval env TRUE_at = True\"\n | \"bool_atom_eval env FALSE_at = False\"\n | \"bool_atom_eval env (Var_at x) = env x\"\n | \"bool_atom_eval env (Not_Var_at x) = (\\<not>(env x))\"\n \ndatatype 'a bool_conj =\n   Atom \"'a bool_atom\"\n | And_conj \"'a bool_atom\" \"'a bool_conj\"\n\nfun bool_conj_eval where\n   \"bool_conj_eval env (Atom a) = bool_atom_eval env a\"\n | \"bool_conj_eval env (And_conj a b) =\n    ((bool_atom_eval env a) \\<and>\n     (bool_conj_eval env b))\"\n     \nfun conj_and where\n   \"conj_and (Atom a) b = And_conj a b\"\n | \"conj_and (And_conj a b) c =\n    And_conj a (conj_and b c)\"\n    \nlemma conj_and_eval [simp]:\n\"bool_conj_eval env (conj_and a b) =\n ((bool_conj_eval env a) \\<and> (bool_conj_eval env b))\"\nby (induct_tac a, auto)\n\ndatatype 'a bool_dnf =\n   Conj \"'a bool_conj\"\n | Or_dnf \"'a bool_conj\" \"'a bool_dnf\"\n\nfun bool_dnf_eval where\n   \"bool_dnf_eval env (Conj c) = bool_conj_eval env c\"\n | \"bool_dnf_eval env (Or_dnf a b) =\n    ((bool_conj_eval env a) \\<or> (bool_dnf_eval env b))\"\n\nfun dnf_or where\n   \"dnf_or (Conj a) b = Or_dnf a b\"\n | \"dnf_or (Or_dnf a b) c = Or_dnf a (dnf_or b c)\"\n \nlemma dnf_or_eval [simp]:\n\"bool_dnf_eval env (dnf_or a b) =\n  ((bool_dnf_eval env a) \\<or> (bool_dnf_eval env b))\"\nby (induct_tac \"a\", auto)\n\nfun conj_or where\n   \"conj_or a (Conj b) = Conj (conj_and a b)\"\n | \"conj_or a (Or_dnf b c) =\n    Or_dnf(conj_and a b) (conj_or a c)\"\n\nlemma conj_or_eval [simp]:\n\"bool_dnf_eval env (conj_or a b) =\n  ((bool_conj_eval env a) \\<and> (bool_dnf_eval env b))\"\nby (induct_tac \"b\", auto)\n\nfun dist_and_or where\n   \"dist_and_or (Conj a) b = conj_or a b\"\n | \"dist_and_or (Or_dnf a b) c =\n    dnf_or (conj_or a c) (dist_and_or b c)\"\n\nlemma dist_and_or_and_eval [simp]:\n\"bool_dnf_eval env (dist_and_or a b) =\n ((bool_dnf_eval env a) \\<and> (bool_dnf_eval env b))\"\nby (induct_tac a, auto)\n\nfun basic_dnf where\n   \"basic_dnf TRUE_nipn = Conj(Atom TRUE_at)\"\n | \"basic_dnf FALSE_nipn = Conj(Atom FALSE_at)\"\n | \"basic_dnf (Var_nipn x) = Conj(Atom (Var_at x))\"\n | \"basic_dnf (Not_Var_nipn x) =\n    Conj(Atom (Not_Var_at x))\"\n | \"basic_dnf (And_nipn a b) =\n    dist_and_or (basic_dnf a) (basic_dnf b)\"\n | \"basic_dnf (Or_nipn a b) =\n    dnf_or (basic_dnf a) (basic_dnf b)\"\n    \nlemma basic_dnv_eval [simp]:\n\"bool_dnf_eval env (basic_dnf a) =\n boolexp_nipn_eval env a\"\nby (induct_tac a, auto)\n\ndefinition dnf where\n\"dnf a = basic_dnf (push_not_elim_imp a)\"\n\nlemma dnf_eval [simp]:\n\"boolexp_eval env a = bool_dnf_eval env (dnf a)\"\nby (auto simp only: dnf_def push_not_elim_imp_same_eval basic_dnv_eval)\n\nfun sat_bool_atom where\n   \"sat_bool_atom TRUE_at = Some (None)\"\n | \"sat_bool_atom FALSE_at = None\"\n | \"sat_bool_atom (Var_at x) = Some(Some(x,True))\"\n | \"sat_bool_atom (Not_Var_at x) = Some(Some(x,False))\"\n\nlemma sat_bool_atom_no_sat [simp]:\n\"sat_bool_atom a = None \\<Longrightarrow> \\<not>(bool_atom_eval env a)\"\nby (case_tac \"a\", simp_all)\n\nlemma sat_bool_atom_sound [simp]:\n\"\\<lbrakk> sat_bool_atom a = Some l;\n   (l = None) \\<or> l = Some (y, env y) \\<rbrakk> \\<Longrightarrow>\n bool_atom_eval env a\"\nby (induct a, auto)\n\nlemma sat_bool_atom_complete [simp]:\n\"bool_atom_eval env a \\<Longrightarrow>\n\\<exists> l y. ((sat_bool_atom a = Some l) \\<and> \n     ((l = None) \\<or> l = Some(y, env y)))\"\napply (case_tac \"sat_bool_atom a\", auto)\nby (induct a, auto)\n\nfun member where\n   \"member x [] = False\"\n | \"member x (y#ys) = ((x = y) \\<or> (member x ys))\"\n \nfun sat_conj where\n   \"sat_conj (Atom a) = \n    (case sat_bool_atom a of None \\<Rightarrow> None\n        | Some None \\<Rightarrow> Some []\n        | Some (Some (y,t)) \\<Rightarrow> Some[(y,t)])\"\n | \"sat_conj (And_conj a b) =\n    (case sat_bool_atom a of None \\<Rightarrow> None\n        | Some None \\<Rightarrow> sat_conj b\n        | Some (Some (y,t)) \\<Rightarrow>\n         (case sat_conj b of None \\<Rightarrow> None\n             | Some l \\<Rightarrow>\n               (if member (y,\\<not>t) l then None\n                else if member (y,t) l then Some l\n                else Some ((y,t)#l))))\"\n\nfun sat_to_env where\n   \"sat_to_env [] = {env. True}\"\n | \"sat_to_env ((y,b)#l) = {env. env y = b} \\<inter> (sat_to_env l)\"\n\n(*\nlemma sat_conj_sound:\n\"\\<lbrakk> sat_conj a = Some l; env \\<in> sat_to_env l \\<rbrakk> \\<Longrightarrow> bool_conj_eval env a\"\napply (induct \"a\", simp_all)  \napply (case_tac \"bool_atom\", simp_all)\napply auto\n*)\n\nfun sat_dnf where\n    \"sat_dnf (Conj a) =\n     (case sat_conj a of None \\<Rightarrow> []\n         | Some l \\<Rightarrow> [l])\"\n | \"sat_dnf (Or_dnf a b) =\n    (case sat_conj a of None \\<Rightarrow> sat_dnf b\n        | Some l => l# (sat_dnf b))\"\n\n        \ndefinition sat where\n\"sat a \\<equiv> sat_dnf (dnf a)\"\n\nexport_code sat\nin OCaml\n module_name Sat file \"sat.ml\"\n\n\nend\n", "meta": {"author": "brando90", "repo": "cs477", "sha": "665326c27c24669db79c3e5e070f2b8e00a73d02", "save_path": "github-repos/isabelle/brando90-cs477", "path": "github-repos/isabelle/brando90-cs477/cs477-665326c27c24669db79c3e5e070f2b8e00a73d02/lectures/boolexp.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8723473614033683, "lm_q2_score": 0.8499711775577736, "lm_q1q2_score": 0.7414701140114377}}
{"text": "theory Insertion_Sort\nimports Sorting\nbegin\n\ncontext begin\n\nqualified primrec insert :: \"'a::linorder \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where\n\"insert x [] = [x]\" |\n\"insert x (y # ys) = (if x \\<le> y then x # y # ys else y # insert x ys)\"\n\nqualified lemma insert_sorted: \"sorted xs \\<Longrightarrow> sorted (insert x xs)\"\nproof (induction xs rule: sorted.induct)\n  case empty\n  show ?case\n    by (auto intro: single)\nnext\n  case (single y)\n  show ?case\n    by (cases \"x \\<le> y\") (auto intro: sorted.intros) (* if_splits *)\nnext\n  case (cons x\\<^sub>1 x\\<^sub>2 xs)\n  show ?case\n    proof (cases \"x \\<le> x\\<^sub>1\")\n      case True\n      hence \"insert x (x\\<^sub>1 # x\\<^sub>2 # xs) = x # x\\<^sub>1 # x\\<^sub>2 # xs\"\n        by simp\n      moreover have \"sorted (x # x\\<^sub>1 # x\\<^sub>2 # xs)\"\n        apply (rule sorted.intros)\n        apply fact\n        apply (rule sorted.intros)\n        apply fact+\n        done\n      ultimately show ?thesis\n        by simp\n    next\n      case False\n      hence \"insert x (x\\<^sub>1 # x\\<^sub>2 # xs) = x\\<^sub>1 # insert x (x\\<^sub>2 # xs)\"\n        by simp\n      moreover have \"sorted (x\\<^sub>1 # insert x (x\\<^sub>2 # xs))\"\n        apply (cases \"x \\<le> x\\<^sub>2\")\n        using cons apply (auto intro: sorted.intros)\n        apply (rule sorted.cons)\n        using False apply simp\n        apply assumption\n        done\n      ultimately show ?thesis\n        by simp\n    qed\nqed\n\nqualified lemma insert_permutation: \"mset (insert x xs) = {#x#} + mset xs\"\nproof (induction xs)\n  case Nil\n  show ?case\n    by simp\nnext\n  case (Cons y ys)\n  show ?case\n    proof (cases \"x \\<le> y\")\n      case True\n      thus ?thesis\n        by (simp add: union_commute)\n    next\n      case False\n      thus ?thesis\n        apply simp\n        apply (subst Cons)\n        by (simp add: union_assoc)\n    qed\nqed\n\nprimrec insort :: \"'a::linorder list \\<Rightarrow> 'a list\" where\n\"insort [] = []\" |\n\"insort (x # xs) = insert x (insort xs)\"\n\nend\n\nglobal_interpretation insertion_sort: sorting insort\nproof\n  fix xs :: \"'a::linorder list\"\n  show \"sorted (insort xs)\"\n    proof (induction xs)\n      case Nil\n      show ?case\n        apply simp\n        apply (rule sorted.empty)\n        done\n    next\n      case (Cons y ys)\n      show ?case\n        apply simp\n        apply (rule Insertion_Sort.insert_sorted)\n        apply (rule Cons)\n        done\n  qed\n\n  show \"mset (insort xs) = mset xs\"\n    by (induction xs) (auto simp: Insertion_Sort.insert_permutation union_commute)\nqed\n\nexport_code insort\n  checking Scala\n\nend", "meta": {"author": "larsrh", "repo": "sorting", "sha": "da6faf36458676983300f7fbf37037fa12430031", "save_path": "github-repos/isabelle/larsrh-sorting", "path": "github-repos/isabelle/larsrh-sorting/sorting-da6faf36458676983300f7fbf37037fa12430031/Insertion_Sort.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213772699435, "lm_q2_score": 0.8244619263765707, "lm_q1q2_score": 0.7412913427503329}}
{"text": "(*\n  File: Semiring.thy\n  Author: Bohua Zhan\n\n  Semirings.\n*)\n\ntheory Semiring\n  imports Group AbGroup OrderRel\nbegin\n\n(* We define semirings to be commutative (it is only used for Nat). *)\n  \nsection \\<open>Semirings\\<close>\n\ndefinition is_zero_mult :: \"i \\<Rightarrow> o\" where [rewrite]:\n  \"is_zero_mult(R) \\<longleftrightarrow> (\\<forall>x\\<in>.R. \\<zero>\\<^sub>R *\\<^sub>R x = \\<zero>\\<^sub>R \\<and> x *\\<^sub>R \\<zero>\\<^sub>R = \\<zero>\\<^sub>R)\"\n  \nlemma is_zero_multD [rewrite]:\n  \"is_zero_mult(R) \\<Longrightarrow> x \\<in>. R \\<Longrightarrow> \\<zero>\\<^sub>R *\\<^sub>R x = \\<zero>\\<^sub>R\"\n  \"is_zero_mult(R) \\<Longrightarrow> x \\<in>. R \\<Longrightarrow> x *\\<^sub>R \\<zero>\\<^sub>R = \\<zero>\\<^sub>R\" by auto2+\nsetup {* del_prfstep_thm_eqforward @{thm is_zero_mult_def} *}\n\ndefinition is_semiring :: \"i \\<Rightarrow> o\" where [rewrite]:\n  \"is_semiring(R) \\<longleftrightarrow> (is_ring_raw(R) \\<and> is_ab_monoid(R) \\<and> is_monoid(R) \\<and>\n    is_times_comm(R) \\<and> is_left_distrib(R) \\<and> is_zero_mult(R) \\<and> \\<zero>\\<^sub>R \\<noteq> \\<one>\\<^sub>R)\"\n\nlemma is_semiringD [forward]:\n  \"is_semiring(R) \\<Longrightarrow> is_ring_raw(R)\"\n  \"is_semiring(R) \\<Longrightarrow> is_ab_monoid(R)\"\n  \"is_semiring(R) \\<Longrightarrow> is_monoid(R)\"\n  \"is_semiring(R) \\<Longrightarrow> is_times_comm(R)\"\n  \"is_semiring(R) \\<Longrightarrow> is_left_distrib(R)\"\n  \"is_semiring(R) \\<Longrightarrow> is_zero_mult(R)\" by auto2+\n\nlemma is_semiringD' [resolve]: \"is_semiring(R) \\<Longrightarrow> \\<zero>\\<^sub>R \\<noteq> \\<one>\\<^sub>R\" by auto2\nsetup {* del_prfstep_thm_eqforward @{thm is_semiring_def} *}\n\nML_file \"alg_semiring.ML\"\n\nsection \\<open>Ordered semirings\\<close>\n\ndefinition is_ord_semiring :: \"i \\<Rightarrow> o\" where [rewrite]:\n  \"is_ord_semiring(R) \\<longleftrightarrow> (is_ord_ring_raw(R) \\<and> is_semiring(R) \\<and> linorder(R) \\<and>\n                           ord_ring_add_left(R) \\<and> ord_semiring_mult_left(R))\"\n\nlemma is_ord_semiringD [forward]:\n  \"is_ord_semiring(R) \\<Longrightarrow> is_ord_ring_raw(R)\"\n  \"is_ord_semiring(R) \\<Longrightarrow> is_semiring(R)\"\n  \"is_ord_semiring(R) \\<Longrightarrow> linorder(R)\"\n  \"is_ord_semiring(R) \\<Longrightarrow> ord_ring_add_left(R)\"\n  \"is_ord_semiring(R) \\<Longrightarrow> ord_semiring_mult_left(R)\" by auto2+\nsetup {* del_prfstep_thm_eqforward @{thm is_ord_semiring_def} *}\n\nlemma ord_semiring_mult_right [backward]:\n  \"is_ord_semiring(R) \\<Longrightarrow> c \\<in>. R \\<Longrightarrow> a \\<le>\\<^sub>R b \\<Longrightarrow> a *\\<^sub>R c \\<le>\\<^sub>R b *\\<^sub>R c\"\n@proof @have \"c *\\<^sub>R a \\<le>\\<^sub>R c *\\<^sub>R b\" @qed\n\nlemma ord_semiring_add_right [backward]:\n  \"is_ord_semiring(R) \\<Longrightarrow> c \\<in>. R \\<Longrightarrow> a \\<le>\\<^sub>R b \\<Longrightarrow> a +\\<^sub>R c \\<le>\\<^sub>R b +\\<^sub>R c\"\n@proof @have \"c +\\<^sub>R a \\<le>\\<^sub>R c +\\<^sub>R b\" @qed\n\nlemma ord_semiring_add_mix [backward1, backward2]:\n  \"is_ord_semiring(R) \\<Longrightarrow> p \\<le>\\<^sub>R q \\<Longrightarrow> r \\<le>\\<^sub>R s \\<Longrightarrow> p +\\<^sub>R r \\<le>\\<^sub>R q +\\<^sub>R s\"\n@proof @have \"p +\\<^sub>R r \\<le>\\<^sub>R p +\\<^sub>R s\" @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/Semiring.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8991213772699435, "lm_q2_score": 0.8244619242200082, "lm_q1q2_score": 0.7412913408113215}}
{"text": "header \"Sequents\"\n\ntheory Sequents\nimports Formula\nbegin \n\ntype_synonym sequent = \"formula list\"\n\ndefinition\n  evalS :: \"[model,vbl => object,formula list] => bool\" where\n  \"evalS M phi fs \\<longleftrightarrow> (? f : set fs . evalF M phi f = True)\"\n\nlemma evalS_nil[simp]: \"evalS M phi [] = False\"\n  by(simp add: evalS_def)\n\nlemma evalS_cons[simp]: \"evalS M phi (A # Gamma) = (evalF M phi A | evalS M phi Gamma)\"\n  by(simp add: evalS_def)\n\nlemma evalS_append: \"evalS M phi (Gamma @ Delta) = (evalS M phi Gamma | evalS M phi Delta)\"\n  by(force simp add: evalS_def)\n\nlemma evalS_equiv[rule_format]: \"(equalOn (freeVarsFL Gamma) f g) --> (evalS M f Gamma = evalS M g Gamma)\"\n  apply (induct Gamma, simp, rule)\n  apply(simp add: freeVarsFL_cons)\n  apply(drule_tac equalOn_UnD)\n  apply(blast dest: evalF_equiv)\n  done\n\n\ndefinition\n  modelAssigns :: \"[model] => (vbl => object) set\" where\n  \"modelAssigns M = { phi . range phi <= objects M }\"\n\nlemma modelAssignsI: \"range f <= objects M \\<Longrightarrow> f : modelAssigns M\" \n  by(simp add: modelAssigns_def)\n\nlemma modelAssignsD: \"f : modelAssigns M \\<Longrightarrow> range f <= objects M\" \n  by(simp add: modelAssigns_def)\n  \ndefinition\n  validS :: \"formula list => bool\" where\n  \"validS fs \\<longleftrightarrow> (! M . ! phi : modelAssigns M . evalS M phi fs = True)\"\n\n\nsubsection \"Rules\"\n\ntype_synonym rule = \"sequent * (sequent set)\"\n\ndefinition\n  concR :: \"rule => sequent\" where\n  \"concR = (%(conc,prems). conc)\"\n\ndefinition\n  premsR :: \"rule => sequent set\" where\n  \"premsR = (%(conc,prems). prems)\"\n\ndefinition\n  mapRule :: \"(formula => formula) => rule => rule\" where\n  \"mapRule = (%f (conc,prems) . (map f conc,(map f) ` prems))\"\n\nlemma mapRuleI: \"[| A = map f a; B = (map f) ` b |] ==> (A,B) = mapRule f (a,b)\"\n  by(simp add: mapRule_def)\n    -- \"FIXME tjr would like symmetric\"\n\n\nsubsection \"Deductions\"\n\n(*FIXME. I don't see why plain Pow_mono is rejected.*)\nlemmas Powp_mono [mono] = Pow_mono [to_pred pred_subset_eq]\n\ninductive_set\n  deductions  :: \"rule set => formula list set\"\n  for rules :: \"rule set\"\n  (******\n   * Given a set of rules,\n   *   1. Given a rule conc/prem(i) in rules,\n   *       and the prem(i) are deductions from rules,\n   *       then conc is a deduction from rules.\n   *   2. can derive permutation of any deducible formula list.\n   *      (supposed to be multisets not lists).\n   ******)\n  where\n    inferI: \"[| (conc,prems) : rules;\n               prems : Pow(deductions(rules))\n            |] ==> conc : deductions(rules)\"\n(*\n    perms   \"[| permutation conc' conc;\n                conc' : deductions(rules)\n             |] ==> conc : deductions(rules)\"\n*)\n \nlemma mono_deductions: \"[| A <= B |] ==> deductions(A) <= deductions(B)\"\n  apply(best intro: deductions.inferI elim: deductions.induct) done\n  \n(*lemmas deductionsMono = mono_deductions*)\n\n(*\n-- \"tjr following should be subsetD?\"\nlemmas deductionSubsetI = mono_deductions[THEN subsetD]\nthm deductionSubsetI\n*)\n\n(******\n * (f : formula -> formula) extended structurally over rules, deductions etc...\n * (((If f maps rules into themselves then can consider mapping derivation trees.)))\n * (((Is the asm necessary - think not?)))\n * The mapped deductions from the rules are same as\n * the deductions from the mapped rules.\n *\n * WHY:\n *\n * map f `` deductions rules <= deductions (mapRule f `` rules)     (this thm)\n *                           <= deductions rules                    (closed)\n *\n * If rules are closed under f then so are deductions.\n * Can take f = (subst u v) and have application to exercise #1.\n *\n * Q: maybe also make f dual mapping, (what about quantifier side conditions...?).\n ******)\n\n(*\nlemma map_deductions: \"map f ` deductions rules <= deductions (mapRule f ` rules)\"\n  apply(rule subsetI)\n  apply (erule_tac imageE, simp)\n  apply(erule deductions.induct)\n  apply(blast intro: deductions.inferI mapRuleI)\n  done\n\nlemma deductionsCloseRules: \"! (conc,prems) : S . prems <= deductions R --> conc : deductions R ==> deductions (R Un S) = deductions R\"\n  apply(rule equalityI)\n  prefer 2\n  apply(rule mono_deductions) apply blast\n  apply(rule subsetI)\n  apply (erule_tac deductions.induct, simp) apply(erule conjE) apply(thin_tac \"prems \\<subseteq> deductions (R \\<union> S)\")\n  apply(erule disjE)\n  apply(rule inferI) apply assumption apply force\n  apply blast\n  done\n*)\n\n\nsubsection \"Basic Rule sets\"\n\ndefinition\n  \"Axioms  = { z. ? p vs.              z = ([FAtom Pos p vs,FAtom Neg p vs],{}) }\"\ndefinition\n  \"Conjs   = { z. ? A0 A1 Delta Gamma. z = (FConj Pos A0 A1#Gamma @ Delta,{A0#Gamma,A1#Delta}) }\"\ndefinition\n  \"Disjs   = { z. ? A0 A1       Gamma. z = (FConj Neg A0 A1#Gamma,{A0#A1#Gamma}) }\"\ndefinition\n  \"Alls    = { z. ? A x         Gamma. z = (FAll Pos A#Gamma,{instanceF x A#Gamma}) & x ~: freeVarsFL (FAll Pos A#Gamma) }\"\ndefinition\n  \"Exs     = { z. ? A x         Gamma. z = (FAll Neg A#Gamma,{instanceF x A#Gamma})}\"\ndefinition\n  \"Weaks   = { z. ? A           Gamma. z = (A#Gamma,{Gamma})}\"\ndefinition\n  \"Contrs  = { z. ? A           Gamma. z = (A#Gamma,{A#A#Gamma})}\"\ndefinition\n  \"Cuts    = { z. ? C Delta     Gamma. z = (Gamma @ Delta,{C#Gamma,FNot C#Delta})}\"\ndefinition\n  \"Perms   = { z. ? Gamma Gamma'     . z = (Gamma,{Gamma'}) & Gamma <~~> Gamma'}\"\ndefinition\n  \"DAxioms = { z. ? p vs.              z = ([FAtom Neg p vs,FAtom Pos p vs],{}) }\"\n\n\nlemma AxiomI: \"[| Axioms <= A |] ==> [FAtom Pos p vs,FAtom Neg p vs] : deductions(A)\"\n  apply(rule deductions.inferI)\n  apply(auto simp add: Axioms_def) done\n\nlemma DAxiomsI: \"[| DAxioms <= A |] ==> [FAtom Neg p vs,FAtom Pos p vs] : deductions(A)\"\n  apply(rule deductions.inferI)\n  apply(auto simp add: DAxioms_def) done\n\nlemma DisjI: \"[| A0#A1#Gamma : deductions(A); Disjs <= A |] ==> (FConj Neg A0 A1#Gamma) : deductions(A)\"\n  apply(rule deductions.inferI)\n  apply(auto simp add: Disjs_def) done\n\nlemma ConjI: \"[| (A0#Gamma) : deductions(A); (A1#Delta) : deductions(A); Conjs <= A |] ==> FConj Pos A0 A1#Gamma @ Delta : deductions(A)\"\n  apply(rule_tac prems=\"{A0#Gamma,A1#Delta}\" in deductions.inferI)\n  apply(auto simp add: Conjs_def) apply force done\n\nlemma AllI: \"[| instanceF w A#Gamma : deductions(R); w ~: freeVarsFL (FAll Pos A#Gamma); Alls <= R |] ==> (FAll Pos A#Gamma) : deductions(R)\"\n  apply(rule_tac prems=\"{instanceF w A#Gamma}\" in deductions.inferI)\n  apply(auto simp add: Alls_def) done\n\nlemma ExI: \"[| instanceF w A#Gamma : deductions(R); Exs <= R |] ==> (FAll Neg A#Gamma) : deductions(R)\"\n  apply(rule_tac prems = \"{instanceF w A#Gamma}\" in deductions.inferI)\n  apply(auto simp add: Exs_def) done\n\nlemma WeakI: \"[| Gamma : deductions R; Weaks <= R |] ==> A#Gamma : deductions(R)\"\n  apply(rule_tac prems=\"{Gamma}\" in deductions.inferI)\n  apply(auto simp add: Weaks_def) done\n\nlemma ContrI: \"[| A#A#Gamma : deductions R; Contrs <= R |] ==> A#Gamma : deductions(R)\"\n  apply(rule_tac prems=\"{A#A#Gamma}\" in deductions.inferI)\n  apply(auto simp add: Contrs_def) done\n\nlemma PermI: \"[| Gamma' : deductions R; Gamma <~~> Gamma'; Perms <= R |] ==> Gamma : deductions(R)\"\n  apply(rule_tac prems=\"{Gamma'}\" in deductions.inferI)\n  apply(auto simp add: Perms_def) done\n\n\nsubsection \"Derived Rules\"\n\nlemma WeakI1: \"[| Gamma : deductions(A); Weaks <= A |] ==> (Delta @ Gamma) : deductions(A)\"\n  apply (induct Delta, simp)\n  apply(auto intro: WeakI) done\n\nlemma WeakI2: \"[| Gamma : deductions(A); Perms <= A; Weaks <= A |] ==> (Gamma @ Delta) : deductions(A)\"\n  apply(blast intro: PermI perm_append_swap WeakI1) done\n\nlemma SATAxiomI: \"[| Axioms <= A; Weaks <= A; Perms <= A; forms = [FAtom Pos n vs,FAtom Neg n vs] @ Gamma |] ==> forms : deductions(A)\"\n  apply(simp only:)\n  apply(blast intro: WeakI2 AxiomI)\n  done\n    \nlemma DisjI1: \"[| (A1#Gamma) : deductions(A); Disjs <= A; Weaks <= A |] ==> FConj Neg A0 A1#Gamma : deductions(A)\"\n  apply(blast intro: DisjI WeakI)\n  done\n\nlemma DisjI2: \"!!A. [| (A0#Gamma) : deductions(A); Disjs <= A; Weaks <= A; Perms <= A |] ==> FConj Neg A0 A1#Gamma : deductions(A)\"\n  apply(rule DisjI)\n  apply(rule PermI[OF _ perm.swap])\n  apply(rule WeakI)\n  .\n\n    -- \"FIXME the following 4 lemmas could all be proved for the standard rule sets using monotonicity as below\"\n    -- \"we keep proofs as in original, but they are slightly ugly, and do not state what is intuitively happening\"\nlemma perm_tmp4: \"Perms \\<subseteq> R \\<Longrightarrow> A @ (a # list) @ (a # list) : deductions R \\<Longrightarrow> (a # a # A) @ list @ list : deductions R\"\n  apply (rule PermI, auto)\n  apply(simp add: perm_count_conv count_append) done\n\nlemma weaken_append[rule_format]: \"Contrs <= R ==> Perms <= R ==> !A. A @ Gamma @ Gamma : deductions(R) -->  A @ Gamma : deductions(R)\"\n  apply (induct_tac Gamma, simp, rule) apply rule\n  apply(drule_tac x=\"a#a#A\" in spec)\n  apply(erule_tac impE)\n  apply(rule perm_tmp4) apply(assumption, assumption)\n  apply(thin_tac \"A @ (a # list) @ a # list \\<in> deductions R\")\n  apply simp\n  apply(frule_tac ContrI) apply assumption\n  apply(thin_tac \"a # a # A @ list \\<in> deductions R\")\n  apply(rule PermI) apply assumption \n  apply(simp add: perm_count_conv count_append) \n  by assumption\n  -- \"FIXME horrible\"\n\nlemma ListWeakI: \"Perms <= R ==> Contrs <= R ==> x # Gamma @ Gamma : deductions(R) ==> x # Gamma : deductions(R)\"\n  by(rule weaken_append[of R \"[x]\" Gamma, simplified])\n    \nlemma ConjI': \"[| (A0#Gamma) : deductions(A);  (A1#Gamma) : deductions(A); Contrs <= A; Conjs <= A; Perms <= A |] ==> FConj Pos A0 A1#Gamma : deductions(A)\"\n  apply(rule ListWeakI, assumption, assumption)\n  apply(rule ConjI) .\n\n\n\nsubsection \"Standard Rule Sets For Predicate Calculus\"\n\ndefinition\n  PC :: \"rule set\" where\n  \"PC = Union {Perms,Axioms,Conjs,Disjs,Alls,Exs,Weaks,Contrs,Cuts}\"\n\ndefinition\n  CutFreePC :: \"rule set\" where\n  \"CutFreePC = Union {Perms,Axioms,Conjs,Disjs,Alls,Exs,Weaks,Contrs}\"\n\nlemma rulesInPCs: \"Axioms <= PC\" \"Axioms <= CutFreePC\"\n  \"Conjs  <= PC\" \"Conjs  <= CutFreePC\"\n  \"Disjs  <= PC\" \"Disjs  <= CutFreePC\"\n  \"Alls   <= PC\" \"Alls   <= CutFreePC\"\n  \"Exs    <= PC\" \"Exs    <= CutFreePC\"\n  \"Weaks  <= PC\" \"Weaks  <= CutFreePC\"\n  \"Contrs <= PC\" \"Contrs <= CutFreePC\"\n  \"Perms  <= PC\" \"Perms  <= CutFreePC\"\n  \"Cuts   <= PC\"\n  \"CutFreePC <= PC\"\n  by(auto simp: PC_def CutFreePC_def)\n\n\nsubsection \"Monotonicity for CutFreePC deductions\"\n\n  -- \"these lemmas can be used to replace complicated permutation reasoning above\"\n  -- \"essentially if x is a deduction, and set x subset set y, then y is a deduction\"\n\ndefinition\n  inDed :: \"formula list => bool\" where\n  \"inDed xs \\<longleftrightarrow> xs : deductions CutFreePC\"\n\nlemma perm: \"! xs ys. xs <~~> ys --> (inDed xs = inDed ys)\"\n  apply(subgoal_tac \"! xs ys. xs <~~> ys --> inDed xs --> inDed ys\")\n  apply (blast intro: perm_sym, clarify)\n  apply(simp add: inDed_def)\n  apply (rule PermI, assumption)\n  apply(rule perm_sym) apply assumption\n  by(blast intro!: rulesInPCs)\n\nlemma contr: \"! x xs. inDed (x#x#xs) --> inDed (x#xs)\"\n  apply(simp add: inDed_def)\n  apply(blast intro!: ContrI rulesInPCs)\n  done\n\nlemma weak: \"! x xs. inDed xs --> inDed (x#xs)\"\n  apply(simp add: inDed_def)\n  apply(blast intro!: WeakI rulesInPCs)\n  done\n\n\n\nlemma inDed_mono[simplified inDed_def]: \"inDed x ==> set x <= set y ==> inDed y\"\n  using perm_weak_contr_mono[OF perm contr weak] .\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/Completeness/Sequents.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045966995027, "lm_q2_score": 0.8354835452961425, "lm_q1q2_score": 0.7412448418535348}}
{"text": "section \\<open>Horner Evaluation\\<close>\ntheory Horner_Eval\n  imports \"HOL-Library.Interval\"\nbegin\n\ntext \\<open>Function and lemmas for evaluating polynomials via the horner scheme.\n   Because interval multiplication is not distributive, interval polynomials\n   expressed as a sum of monomials are not equivalent to their respective horner form.\n   The functions and lemmas in this theory can be used to express interval\n   polynomials in horner form and prove facts about them.\\<close>\n\nfun horner_eval' where\n  \"horner_eval' f x v 0 = v\"\n| \"horner_eval' f x v (Suc i) = horner_eval' f x (f i + x * v) i\"\n\ndefinition horner_eval\n  where \"horner_eval f x n = horner_eval' f x 0 n\"\n\nlemma horner_eval_cong:\n  assumes \"\\<And>i. i < n \\<Longrightarrow> f i = g i\"\n  assumes \"x = y\"\n  assumes \"n = m\"\n  shows \"horner_eval f x n = horner_eval g y m\"\nproof-\n  {\n    fix v have \"horner_eval' f x v n = horner_eval' g x v n\"\n      using assms(1) by (induction n arbitrary: v, simp_all)\n  }\n  thus ?thesis\n    by (simp add: assms(2,3) horner_eval_def)\nqed\n\nlemma horner_eval_eq_setsum:\n  fixes x::\"'a::linordered_idom\"\n  shows \"horner_eval f x n = (\\<Sum>i<n. f i * x^i)\"\nproof-\n  {\n    fix v have \"horner_eval' f x v n = (\\<Sum>i<n. f i * x^i) + v * x^n\"\n      by (induction n arbitrary: v, simp_all add: distrib_left mult.commute)\n  }\n  thus ?thesis by (simp add: horner_eval_def)\nqed\n\nlemma horner_eval_Suc[simp]:\n  fixes x::\"'a::linordered_idom\"\n  shows \"horner_eval f x (Suc n) = horner_eval f x n + (f n) * x^n\"\n  unfolding horner_eval_eq_setsum\n  by simp\n\nlemma horner_eval_Suc'[simp]:\n  fixes x::\"'a::{comm_monoid_add, times}\"\n  shows \"horner_eval f x (Suc n) = f 0 + x * (horner_eval (\\<lambda>i. f (Suc i)) x n)\"\nproof-\n  {\n    fix v have \"horner_eval' f x v (Suc n) = f 0 + x * horner_eval' (\\<lambda>i. f (Suc i)) x v n\"\n      by (induction n arbitrary: v, simp_all)\n  }\n  thus ?thesis by (simp add: horner_eval_def)\nqed\n\nlemma horner_eval_0[simp]:\n  shows \"horner_eval f x 0 = 0\"\n  by (simp add: horner_eval_def)\n\nlemma horner_eval'_interval:\n  fixes x::\"'a::linordered_ring\"\n  assumes \"\\<And>i. i < n \\<Longrightarrow> f i \\<in> set_of (g i)\"\n  assumes \"x \\<in>\\<^sub>i I\" \"v \\<in>\\<^sub>i V\"\n  shows \"horner_eval' f x v n \\<in>\\<^sub>i horner_eval' g I V n\"\n  using assms\n  by (induction n arbitrary: v V) (auto intro!: plus_in_intervalI times_in_intervalI)\n\nlemma horner_eval_interval:\n  fixes x::\"'a::linordered_idom\"\n  assumes \"\\<And>i. i < n \\<Longrightarrow> f i \\<in> set_of (g i)\"\n  assumes \"x \\<in> set_of I\"\n  shows \"horner_eval f x n \\<in>\\<^sub>i horner_eval g I n\"\n  unfolding horner_eval_def\n  using assms\n  by (rule horner_eval'_interval) (auto simp: set_of_eq)\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/Taylor_Models/Horner_Eval.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8872045996818986, "lm_q2_score": 0.8354835289107309, "lm_q1q2_score": 0.7412448298080649}}
{"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>\\<open>\"Kleinberg-Tardos\"\\<close>\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": "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/Monad_Memo_DP/example/Knapsack.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430562234877, "lm_q2_score": 0.8918110511888302, "lm_q1q2_score": 0.7412225626589656}}
{"text": "(*  Title:      HOL/Transcendental.thy\n    Author:     Jacques D. Fleuriot, University of Cambridge, University of Edinburgh\n    Author:     Lawrence C Paulson\n    Author:     Jeremy Avigad\n*)\n\nsection \\<open>Power Series, Transcendental Functions etc.\\<close>\n\ntheory Transcendental\nimports Series Deriv NthRoot\nbegin\n\ntext \\<open>A theorem about the factcorial function on the reals.\\<close>\n\nlemma square_fact_le_2_fact: \"fact n * fact n \\<le> (fact (2 * n) :: real)\"\nproof (induct n)\n  case 0\n  then show ?case by simp\nnext\n  case (Suc n)\n  have \"(fact (Suc n)) * (fact (Suc n)) = of_nat (Suc n) * of_nat (Suc n) * (fact n * fact n :: real)\"\n    by (simp add: field_simps)\n  also have \"\\<dots> \\<le> of_nat (Suc n) * of_nat (Suc n) * fact (2 * n)\"\n    by (rule mult_left_mono [OF Suc]) simp\n  also have \"\\<dots> \\<le> of_nat (Suc (Suc (2 * n))) * of_nat (Suc (2 * n)) * fact (2 * n)\"\n    by (rule mult_right_mono)+ (auto simp: field_simps)\n  also have \"\\<dots> = fact (2 * Suc n)\" by (simp add: field_simps)\n  finally show ?case .\nqed\n\nlemma fact_in_Reals: \"fact n \\<in> \\<real>\"\n  by (induction n) auto\n\nlemma of_real_fact [simp]: \"of_real (fact n) = fact n\"\n  by (metis of_nat_fact of_real_of_nat_eq)\n\nlemma pochhammer_of_real: \"pochhammer (of_real x) n = of_real (pochhammer x n)\"\n  by (simp add: pochhammer_prod)\n\nlemma norm_fact [simp]: \"norm (fact n :: 'a::real_normed_algebra_1) = fact n\"\nproof -\n  have \"(fact n :: 'a) = of_real (fact n)\"\n    by simp\n  also have \"norm \\<dots> = fact n\"\n    by (subst norm_of_real) simp\n  finally show ?thesis .\nqed\n\nlemma root_test_convergence:\n  fixes f :: \"nat \\<Rightarrow> 'a::banach\"\n  assumes f: \"(\\<lambda>n. root n (norm (f n))) \\<longlonglongrightarrow> x\" \\<comment> \\<open>could be weakened to lim sup\\<close>\n    and \"x < 1\"\n  shows \"summable f\"\nproof -\n  have \"0 \\<le> x\"\n    by (rule LIMSEQ_le[OF tendsto_const f]) (auto intro!: exI[of _ 1])\n  from \\<open>x < 1\\<close> obtain z where z: \"x < z\" \"z < 1\"\n    by (metis dense)\n  from f \\<open>x < z\\<close> have \"eventually (\\<lambda>n. root n (norm (f n)) < z) sequentially\"\n    by (rule order_tendstoD)\n  then have \"eventually (\\<lambda>n. norm (f n) \\<le> z^n) sequentially\"\n    using eventually_ge_at_top\n  proof eventually_elim\n    fix n\n    assume less: \"root n (norm (f n)) < z\" and n: \"1 \\<le> n\"\n    from power_strict_mono[OF less, of n] n show \"norm (f n) \\<le> z ^ n\"\n      by simp\n  qed\n  then show \"summable f\"\n    unfolding eventually_sequentially\n    using z \\<open>0 \\<le> x\\<close> by (auto intro!: summable_comparison_test[OF _  summable_geometric])\nqed\n\nsubsection \\<open>More facts about binomial coefficients\\<close>\n\ntext \\<open>\n  These facts could have been proven before, but having real numbers\n  makes the proofs a lot easier.\n\\<close>\n\nlemma central_binomial_odd:\n  \"odd n \\<Longrightarrow> n choose (Suc (n div 2)) = n choose (n div 2)\"\nproof -\n  assume \"odd n\"\n  hence \"Suc (n div 2) \\<le> n\" by presburger\n  hence \"n choose (Suc (n div 2)) = n choose (n - Suc (n div 2))\"\n    by (rule binomial_symmetric)\n  also from \\<open>odd n\\<close> have \"n - Suc (n div 2) = n div 2\" by presburger\n  finally show ?thesis .\nqed\n\nlemma binomial_less_binomial_Suc:\n  assumes k: \"k < n div 2\"\n  shows   \"n choose k < n choose (Suc k)\"\nproof -\n  from k have k': \"k \\<le> n\" \"Suc k \\<le> n\" by simp_all\n  from k' have \"real (n choose k) = fact n / (fact k * fact (n - k))\"\n    by (simp add: binomial_fact)\n  also from k' have \"n - k = Suc (n - Suc k)\" by simp\n  also from k' have \"fact \\<dots> = (real n - real k) * fact (n - Suc k)\"\n    by (subst fact_Suc) (simp_all add: of_nat_diff)\n  also from k have \"fact k = fact (Suc k) / (real k + 1)\" by (simp add: field_simps)\n  also have \"fact n / (fact (Suc k) / (real k + 1) * ((real n - real k) * fact (n - Suc k))) =\n               (n choose (Suc k)) * ((real k + 1) / (real n - real k))\"\n    using k by (simp add: field_split_simps binomial_fact)\n  also from assms have \"(real k + 1) / (real n - real k) < 1\" by simp\n  finally show ?thesis using k by (simp add: mult_less_cancel_left)\nqed\n\nlemma binomial_strict_mono:\n  assumes \"k < k'\" \"2*k' \\<le> n\"\n  shows   \"n choose k < n choose k'\"\nproof -\n  from assms have \"k \\<le> k' - 1\" by simp\n  thus ?thesis\n  proof (induction rule: inc_induct)\n    case base\n    with assms binomial_less_binomial_Suc[of \"k' - 1\" n]\n      show ?case by simp\n  next\n    case (step k)\n    from step.prems step.hyps assms have \"n choose k < n choose (Suc k)\"\n      by (intro binomial_less_binomial_Suc) simp_all\n    also have \"\\<dots> < n choose k'\" by (rule step.IH)\n    finally show ?case .\n  qed\nqed\n\nlemma binomial_mono:\n  assumes \"k \\<le> k'\" \"2*k' \\<le> n\"\n  shows   \"n choose k \\<le> n choose k'\"\n  using assms binomial_strict_mono[of k k' n] by (cases \"k = k'\") simp_all\n\nlemma binomial_strict_antimono:\n  assumes \"k < k'\" \"2 * k \\<ge> n\" \"k' \\<le> n\"\n  shows   \"n choose k > n choose k'\"\nproof -\n  from assms have \"n choose (n - k) > n choose (n - k')\"\n    by (intro binomial_strict_mono) (simp_all add: algebra_simps)\n  with assms show ?thesis by (simp add: binomial_symmetric [symmetric])\nqed\n\nlemma binomial_antimono:\n  assumes \"k \\<le> k'\" \"k \\<ge> n div 2\" \"k' \\<le> n\"\n  shows   \"n choose k \\<ge> n choose k'\"\nproof (cases \"k = k'\")\n  case False\n  note not_eq = False\n  show ?thesis\n  proof (cases \"k = n div 2 \\<and> odd n\")\n    case False\n    with assms(2) have \"2*k \\<ge> n\" by presburger\n    with not_eq assms binomial_strict_antimono[of k k' n]\n      show ?thesis by simp\n  next\n    case True\n    have \"n choose k' \\<le> n choose (Suc (n div 2))\"\n    proof (cases \"k' = Suc (n div 2)\")\n      case False\n      with assms True not_eq have \"Suc (n div 2) < k'\" by simp\n      with assms binomial_strict_antimono[of \"Suc (n div 2)\" k' n] True\n        show ?thesis by auto\n    qed simp_all\n    also from True have \"\\<dots> = n choose k\" by (simp add: central_binomial_odd)\n    finally show ?thesis .\n  qed\nqed simp_all\n\nlemma binomial_maximum: \"n choose k \\<le> n choose (n div 2)\"\nproof -\n  have \"k \\<le> n div 2 \\<longleftrightarrow> 2*k \\<le> n\" by linarith\n  consider \"2*k \\<le> n\" | \"2*k \\<ge> n\" \"k \\<le> n\" | \"k > n\" by linarith\n  thus ?thesis\n  proof cases\n    case 1\n    thus ?thesis by (intro binomial_mono) linarith+\n  next\n    case 2\n    thus ?thesis by (intro binomial_antimono) simp_all\n  qed (simp_all add: binomial_eq_0)\nqed\n\nlemma binomial_maximum': \"(2*n) choose k \\<le> (2*n) choose n\"\n  using binomial_maximum[of \"2*n\"] by simp\n\nlemma central_binomial_lower_bound:\n  assumes \"n > 0\"\n  shows   \"4^n / (2*real n) \\<le> real ((2*n) choose n)\"\nproof -\n  from binomial[of 1 1 \"2*n\"]\n    have \"4 ^ n = (\\<Sum>k\\<le>2*n. (2*n) choose k)\"\n    by (simp add: power_mult power2_eq_square One_nat_def [symmetric] del: One_nat_def)\n  also have \"{..2*n} = {0<..<2*n} \\<union> {0,2*n}\" by auto\n  also have \"(\\<Sum>k\\<in>\\<dots>. (2*n) choose k) =\n             (\\<Sum>k\\<in>{0<..<2*n}. (2*n) choose k) + (\\<Sum>k\\<in>{0,2*n}. (2*n) choose k)\"\n    by (subst sum.union_disjoint) auto\n  also have \"(\\<Sum>k\\<in>{0,2*n}. (2*n) choose k) \\<le> (\\<Sum>k\\<le>1. (n choose k)\\<^sup>2)\"\n    by (cases n) simp_all\n  also from assms have \"\\<dots> \\<le> (\\<Sum>k\\<le>n. (n choose k)\\<^sup>2)\"\n    by (intro sum_mono2) auto\n  also have \"\\<dots> = (2*n) choose n\" by (rule choose_square_sum)\n  also have \"(\\<Sum>k\\<in>{0<..<2*n}. (2*n) choose k) \\<le> (\\<Sum>k\\<in>{0<..<2*n}. (2*n) choose n)\"\n    by (intro sum_mono binomial_maximum')\n  also have \"\\<dots> = card {0<..<2*n} * ((2*n) choose n)\" by simp\n  also have \"card {0<..<2*n} \\<le> 2*n - 1\" by (cases n) simp_all\n  also have \"(2 * n - 1) * (2 * n choose n) + (2 * n choose n) = ((2*n) choose n) * (2*n)\"\n    using assms by (simp add: algebra_simps)\n  finally have \"4 ^ n \\<le> (2 * n choose n) * (2 * n)\" by simp_all\n  hence \"real (4 ^ n) \\<le> real ((2 * n choose n) * (2 * n))\"\n    by (subst of_nat_le_iff)\n  with assms show ?thesis by (simp add: field_simps)\nqed\n\n\nsubsection \\<open>Properties of Power Series\\<close>\n\nlemma powser_zero [simp]: \"(\\<Sum>n. f n * 0 ^ n) = f 0\"\n  for f :: \"nat \\<Rightarrow> 'a::real_normed_algebra_1\"\nproof -\n  have \"(\\<Sum>n<1. f n * 0 ^ n) = (\\<Sum>n. f n * 0 ^ n)\"\n    by (subst suminf_finite[where N=\"{0}\"]) (auto simp: power_0_left)\n  then show ?thesis by simp\nqed\n\nlemma powser_sums_zero: \"(\\<lambda>n. a n * 0^n) sums a 0\"\n  for a :: \"nat \\<Rightarrow> 'a::real_normed_div_algebra\"\n  using sums_finite [of \"{0}\" \"\\<lambda>n. a n * 0 ^ n\"]\n  by simp\n\nlemma powser_sums_zero_iff [simp]: \"(\\<lambda>n. a n * 0^n) sums x \\<longleftrightarrow> a 0 = x\"\n  for a :: \"nat \\<Rightarrow> 'a::real_normed_div_algebra\"\n  using powser_sums_zero sums_unique2 by blast\n\ntext \\<open>\n  Power series has a circle or radius of convergence: if it sums for \\<open>x\\<close>,\n  then it sums absolutely for \\<open>z\\<close> with \\<^term>\\<open>\\<bar>z\\<bar> < \\<bar>x\\<bar>\\<close>.\\<close>\n\nlemma powser_insidea:\n  fixes x z :: \"'a::real_normed_div_algebra\"\n  assumes 1: \"summable (\\<lambda>n. f n * x^n)\"\n    and 2: \"norm z < norm x\"\n  shows \"summable (\\<lambda>n. norm (f n * z ^ n))\"\nproof -\n  from 2 have x_neq_0: \"x \\<noteq> 0\" by clarsimp\n  from 1 have \"(\\<lambda>n. f n * x^n) \\<longlonglongrightarrow> 0\"\n    by (rule summable_LIMSEQ_zero)\n  then have \"convergent (\\<lambda>n. f n * x^n)\"\n    by (rule convergentI)\n  then have \"Cauchy (\\<lambda>n. f n * x^n)\"\n    by (rule convergent_Cauchy)\n  then have \"Bseq (\\<lambda>n. f n * x^n)\"\n    by (rule Cauchy_Bseq)\n  then obtain K where 3: \"0 < K\" and 4: \"\\<forall>n. norm (f n * x^n) \\<le> K\"\n    by (auto simp: Bseq_def)\n  have \"\\<exists>N. \\<forall>n\\<ge>N. norm (norm (f n * z ^ n)) \\<le> K * norm (z ^ n) * inverse (norm (x^n))\"\n  proof (intro exI allI impI)\n    fix n :: nat\n    assume \"0 \\<le> n\"\n    have \"norm (norm (f n * z ^ n)) * norm (x^n) =\n          norm (f n * x^n) * norm (z ^ n)\"\n      by (simp add: norm_mult abs_mult)\n    also have \"\\<dots> \\<le> K * norm (z ^ n)\"\n      by (simp only: mult_right_mono 4 norm_ge_zero)\n    also have \"\\<dots> = K * norm (z ^ n) * (inverse (norm (x^n)) * norm (x^n))\"\n      by (simp add: x_neq_0)\n    also have \"\\<dots> = K * norm (z ^ n) * inverse (norm (x^n)) * norm (x^n)\"\n      by (simp only: mult.assoc)\n    finally show \"norm (norm (f n * z ^ n)) \\<le> K * norm (z ^ n) * inverse (norm (x^n))\"\n      by (simp add: mult_le_cancel_right x_neq_0)\n  qed\n  moreover have \"summable (\\<lambda>n. K * norm (z ^ n) * inverse (norm (x^n)))\"\n  proof -\n    from 2 have \"norm (norm (z * inverse x)) < 1\"\n      using x_neq_0\n      by (simp add: norm_mult nonzero_norm_inverse divide_inverse [where 'a=real, symmetric])\n    then have \"summable (\\<lambda>n. norm (z * inverse x) ^ n)\"\n      by (rule summable_geometric)\n    then have \"summable (\\<lambda>n. K * norm (z * inverse x) ^ n)\"\n      by (rule summable_mult)\n    then show \"summable (\\<lambda>n. K * norm (z ^ n) * inverse (norm (x^n)))\"\n      using x_neq_0\n      by (simp add: norm_mult nonzero_norm_inverse power_mult_distrib\n          power_inverse norm_power mult.assoc)\n  qed\n  ultimately show \"summable (\\<lambda>n. norm (f n * z ^ n))\"\n    by (rule summable_comparison_test)\nqed\n\nlemma powser_inside:\n  fixes f :: \"nat \\<Rightarrow> 'a::{real_normed_div_algebra,banach}\"\n  shows\n    \"summable (\\<lambda>n. f n * (x^n)) \\<Longrightarrow> norm z < norm x \\<Longrightarrow>\n      summable (\\<lambda>n. f n * (z ^ n))\"\n  by (rule powser_insidea [THEN summable_norm_cancel])\n\nlemma powser_times_n_limit_0:\n  fixes x :: \"'a::{real_normed_div_algebra,banach}\"\n  assumes \"norm x < 1\"\n    shows \"(\\<lambda>n. of_nat n * x ^ n) \\<longlonglongrightarrow> 0\"\nproof -\n  have \"norm x / (1 - norm x) \\<ge> 0\"\n    using assms by (auto simp: field_split_simps)\n  moreover obtain N where N: \"norm x / (1 - norm x) < of_int N\"\n    using ex_le_of_int by (meson ex_less_of_int)\n  ultimately have N0: \"N>0\"\n    by auto\n  then have *: \"real_of_int (N + 1) * norm x / real_of_int N < 1\"\n    using N assms by (auto simp: field_simps)\n  have **: \"real_of_int N * (norm x * (real_of_nat (Suc n) * norm (x ^ n))) \\<le>\n      real_of_nat n * (norm x * ((1 + N) * norm (x ^ n)))\" if \"N \\<le> int n\" for n :: nat\n  proof -\n    from that have \"real_of_int N * real_of_nat (Suc n) \\<le> real_of_nat n * real_of_int (1 + N)\"\n      by (simp add: algebra_simps)\n    then have \"(real_of_int N * real_of_nat (Suc n)) * (norm x * norm (x ^ n)) \\<le>\n        (real_of_nat n *  (1 + N)) * (norm x * norm (x ^ n))\"\n      using N0 mult_mono by fastforce\n    then show ?thesis\n      by (simp add: algebra_simps)\n  qed\n  show ?thesis using *\n    by (rule summable_LIMSEQ_zero [OF summable_ratio_test, where N1=\"nat N\"])\n      (simp add: N0 norm_mult field_simps ** del: of_nat_Suc of_int_add)\nqed\n\ncorollary lim_n_over_pown:\n  fixes x :: \"'a::{real_normed_field,banach}\"\n  shows \"1 < norm x \\<Longrightarrow> ((\\<lambda>n. of_nat n / x^n) \\<longlongrightarrow> 0) sequentially\"\n  using powser_times_n_limit_0 [of \"inverse x\"]\n  by (simp add: norm_divide field_split_simps)\n\nlemma sum_split_even_odd:\n  fixes f :: \"nat \\<Rightarrow> real\"\n  shows \"(\\<Sum>i<2 * n. if even i then f i else g i) = (\\<Sum>i<n. f (2 * i)) + (\\<Sum>i<n. g (2 * i + 1))\"\nproof (induct n)\n  case 0\n  then show ?case by simp\nnext\n  case (Suc n)\n  have \"(\\<Sum>i<2 * Suc n. if even i then f i else g i) =\n    (\\<Sum>i<n. f (2 * i)) + (\\<Sum>i<n. g (2 * i + 1)) + (f (2 * n) + g (2 * n + 1))\"\n    using Suc.hyps unfolding One_nat_def by auto\n  also have \"\\<dots> = (\\<Sum>i<Suc n. f (2 * i)) + (\\<Sum>i<Suc n. g (2 * i + 1))\"\n    by auto\n  finally show ?case .\nqed\n\nlemma sums_if':\n  fixes g :: \"nat \\<Rightarrow> real\"\n  assumes \"g sums x\"\n  shows \"(\\<lambda> n. if even n then 0 else g ((n - 1) div 2)) sums x\"\n  unfolding sums_def\nproof (rule LIMSEQ_I)\n  fix r :: real\n  assume \"0 < r\"\n  from \\<open>g sums x\\<close>[unfolded sums_def, THEN LIMSEQ_D, OF this]\n  obtain no where no_eq: \"\\<And>n. n \\<ge> no \\<Longrightarrow> (norm (sum g {..<n} - x) < r)\"\n    by blast\n\n  let ?SUM = \"\\<lambda> m. \\<Sum>i<m. if even i then 0 else g ((i - 1) div 2)\"\n  have \"(norm (?SUM m - x) < r)\" if \"m \\<ge> 2 * no\" for m\n  proof -\n    from that have \"m div 2 \\<ge> no\" by auto\n    have sum_eq: \"?SUM (2 * (m div 2)) = sum g {..< m div 2}\"\n      using sum_split_even_odd by auto\n    then have \"(norm (?SUM (2 * (m div 2)) - x) < r)\"\n      using no_eq unfolding sum_eq using \\<open>m div 2 \\<ge> no\\<close> by auto\n    moreover\n    have \"?SUM (2 * (m div 2)) = ?SUM m\"\n    proof (cases \"even m\")\n      case True\n      then show ?thesis\n        by (auto simp: even_two_times_div_two)\n    next\n      case False\n      then have eq: \"Suc (2 * (m div 2)) = m\" by simp\n      then have \"even (2 * (m div 2))\" using \\<open>odd m\\<close> by auto\n      have \"?SUM m = ?SUM (Suc (2 * (m div 2)))\" unfolding eq ..\n      also have \"\\<dots> = ?SUM (2 * (m div 2))\" using \\<open>even (2 * (m div 2))\\<close> by auto\n      finally show ?thesis by auto\n    qed\n    ultimately show ?thesis by auto\n  qed\n  then show \"\\<exists>no. \\<forall> m \\<ge> no. norm (?SUM m - x) < r\"\n    by blast\nqed\n\nlemma sums_if:\n  fixes g :: \"nat \\<Rightarrow> real\"\n  assumes \"g sums x\" and \"f sums y\"\n  shows \"(\\<lambda> n. if even n then f (n div 2) else g ((n - 1) div 2)) sums (x + y)\"\nproof -\n  let ?s = \"\\<lambda> n. if even n then 0 else f ((n - 1) div 2)\"\n  have if_sum: \"(if B then (0 :: real) else E) + (if B then T else 0) = (if B then T else E)\"\n    for B T E\n    by (cases B) auto\n  have g_sums: \"(\\<lambda> n. if even n then 0 else g ((n - 1) div 2)) sums x\"\n    using sums_if'[OF \\<open>g sums x\\<close>] .\n  have if_eq: \"\\<And>B T E. (if \\<not> B then T else E) = (if B then E else T)\"\n    by auto\n  have \"?s sums y\" using sums_if'[OF \\<open>f sums y\\<close>] .\n  from this[unfolded sums_def, THEN LIMSEQ_Suc]\n  have \"(\\<lambda>n. if even n then f (n div 2) else 0) sums y\"\n    by (simp add: lessThan_Suc_eq_insert_0 sum.atLeast1_atMost_eq image_Suc_lessThan\n        if_eq sums_def cong del: if_weak_cong)\n  from sums_add[OF g_sums this] show ?thesis\n    by (simp only: if_sum)\nqed\n\nsubsection \\<open>Alternating series test / Leibniz formula\\<close>\n(* FIXME: generalise these results from the reals via type classes? *)\n\nlemma sums_alternating_upper_lower:\n  fixes a :: \"nat \\<Rightarrow> real\"\n  assumes mono: \"\\<And>n. a (Suc n) \\<le> a n\"\n    and a_pos: \"\\<And>n. 0 \\<le> a n\"\n    and \"a \\<longlonglongrightarrow> 0\"\n  shows \"\\<exists>l. ((\\<forall>n. (\\<Sum>i<2*n. (- 1)^i*a i) \\<le> l) \\<and> (\\<lambda> n. \\<Sum>i<2*n. (- 1)^i*a i) \\<longlonglongrightarrow> l) \\<and>\n             ((\\<forall>n. l \\<le> (\\<Sum>i<2*n + 1. (- 1)^i*a i)) \\<and> (\\<lambda> n. \\<Sum>i<2*n + 1. (- 1)^i*a i) \\<longlonglongrightarrow> l)\"\n  (is \"\\<exists>l. ((\\<forall>n. ?f n \\<le> l) \\<and> _) \\<and> ((\\<forall>n. l \\<le> ?g n) \\<and> _)\")\nproof (rule nested_sequence_unique)\n  have fg_diff: \"\\<And>n. ?f n - ?g n = - a (2 * n)\" by auto\n\n  show \"\\<forall>n. ?f n \\<le> ?f (Suc n)\"\n  proof\n    show \"?f n \\<le> ?f (Suc n)\" for n\n      using mono[of \"2*n\"] by auto\n  qed\n  show \"\\<forall>n. ?g (Suc n) \\<le> ?g n\"\n  proof\n    show \"?g (Suc n) \\<le> ?g n\" for n\n      using mono[of \"Suc (2*n)\"] by auto\n  qed\n  show \"\\<forall>n. ?f n \\<le> ?g n\"\n  proof\n    show \"?f n \\<le> ?g n\" for n\n      using fg_diff a_pos by auto\n  qed\n  show \"(\\<lambda>n. ?f n - ?g n) \\<longlonglongrightarrow> 0\"\n    unfolding fg_diff\n  proof (rule LIMSEQ_I)\n    fix r :: real\n    assume \"0 < r\"\n    with \\<open>a \\<longlonglongrightarrow> 0\\<close>[THEN LIMSEQ_D] obtain N where \"\\<And> n. n \\<ge> N \\<Longrightarrow> norm (a n - 0) < r\"\n      by auto\n    then have \"\\<forall>n \\<ge> N. norm (- a (2 * n) - 0) < r\"\n      by auto\n    then show \"\\<exists>N. \\<forall>n \\<ge> N. norm (- a (2 * n) - 0) < r\"\n      by auto\n  qed\nqed\n\nlemma summable_Leibniz':\n  fixes a :: \"nat \\<Rightarrow> real\"\n  assumes a_zero: \"a \\<longlonglongrightarrow> 0\"\n    and a_pos: \"\\<And>n. 0 \\<le> a n\"\n    and a_monotone: \"\\<And>n. a (Suc n) \\<le> a n\"\n  shows summable: \"summable (\\<lambda> n. (-1)^n * a n)\"\n    and \"\\<And>n. (\\<Sum>i<2*n. (-1)^i*a i) \\<le> (\\<Sum>i. (-1)^i*a i)\"\n    and \"(\\<lambda>n. \\<Sum>i<2*n. (-1)^i*a i) \\<longlonglongrightarrow> (\\<Sum>i. (-1)^i*a i)\"\n    and \"\\<And>n. (\\<Sum>i. (-1)^i*a i) \\<le> (\\<Sum>i<2*n+1. (-1)^i*a i)\"\n    and \"(\\<lambda>n. \\<Sum>i<2*n+1. (-1)^i*a i) \\<longlonglongrightarrow> (\\<Sum>i. (-1)^i*a i)\"\nproof -\n  let ?S = \"\\<lambda>n. (-1)^n * a n\"\n  let ?P = \"\\<lambda>n. \\<Sum>i<n. ?S i\"\n  let ?f = \"\\<lambda>n. ?P (2 * n)\"\n  let ?g = \"\\<lambda>n. ?P (2 * n + 1)\"\n  obtain l :: real\n    where below_l: \"\\<forall> n. ?f n \\<le> l\"\n      and \"?f \\<longlonglongrightarrow> l\"\n      and above_l: \"\\<forall> n. l \\<le> ?g n\"\n      and \"?g \\<longlonglongrightarrow> l\"\n    using sums_alternating_upper_lower[OF a_monotone a_pos a_zero] by blast\n\n  let ?Sa = \"\\<lambda>m. \\<Sum>n<m. ?S n\"\n  have \"?Sa \\<longlonglongrightarrow> l\"\n  proof (rule LIMSEQ_I)\n    fix r :: real\n    assume \"0 < r\"\n    with \\<open>?f \\<longlonglongrightarrow> l\\<close>[THEN LIMSEQ_D]\n    obtain f_no where f: \"\\<And>n. n \\<ge> f_no \\<Longrightarrow> norm (?f n - l) < r\"\n      by auto\n    from \\<open>0 < r\\<close> \\<open>?g \\<longlonglongrightarrow> l\\<close>[THEN LIMSEQ_D]\n    obtain g_no where g: \"\\<And>n. n \\<ge> g_no \\<Longrightarrow> norm (?g n - l) < r\"\n      by auto\n    have \"norm (?Sa n - l) < r\" if \"n \\<ge> (max (2 * f_no) (2 * g_no))\" for n\n    proof -\n      from that have \"n \\<ge> 2 * f_no\" and \"n \\<ge> 2 * g_no\" by auto\n      show ?thesis\n      proof (cases \"even n\")\n        case True\n        then have n_eq: \"2 * (n div 2) = n\"\n          by (simp add: even_two_times_div_two)\n        with \\<open>n \\<ge> 2 * f_no\\<close> have \"n div 2 \\<ge> f_no\"\n          by auto\n        from f[OF this] show ?thesis\n          unfolding n_eq atLeastLessThanSuc_atLeastAtMost .\n      next\n        case False\n        then have \"even (n - 1)\" by simp\n        then have n_eq: \"2 * ((n - 1) div 2) = n - 1\"\n          by (simp add: even_two_times_div_two)\n        then have range_eq: \"n - 1 + 1 = n\"\n          using odd_pos[OF False] by auto\n        from n_eq \\<open>n \\<ge> 2 * g_no\\<close> have \"(n - 1) div 2 \\<ge> g_no\"\n          by auto\n        from g[OF this] show ?thesis\n          by (simp only: n_eq range_eq)\n      qed\n    qed\n    then show \"\\<exists>no. \\<forall>n \\<ge> no. norm (?Sa n - l) < r\" by blast\n  qed\n  then have sums_l: \"(\\<lambda>i. (-1)^i * a i) sums l\"\n    by (simp only: sums_def)\n  then show \"summable ?S\"\n    by (auto simp: summable_def)\n\n  have \"l = suminf ?S\" by (rule sums_unique[OF sums_l])\n\n  fix n\n  show \"suminf ?S \\<le> ?g n\"\n    unfolding sums_unique[OF sums_l, symmetric] using above_l by auto\n  show \"?f n \\<le> suminf ?S\"\n    unfolding sums_unique[OF sums_l, symmetric] using below_l by auto\n  show \"?g \\<longlonglongrightarrow> suminf ?S\"\n    using \\<open>?g \\<longlonglongrightarrow> l\\<close> \\<open>l = suminf ?S\\<close> by auto\n  show \"?f \\<longlonglongrightarrow> suminf ?S\"\n    using \\<open>?f \\<longlonglongrightarrow> l\\<close> \\<open>l = suminf ?S\\<close> by auto\nqed\n\ntheorem summable_Leibniz:\n  fixes a :: \"nat \\<Rightarrow> real\"\n  assumes a_zero: \"a \\<longlonglongrightarrow> 0\"\n    and \"monoseq a\"\n  shows \"summable (\\<lambda> n. (-1)^n * a n)\" (is \"?summable\")\n    and \"0 < a 0 \\<longrightarrow>\n      (\\<forall>n. (\\<Sum>i. (- 1)^i*a i) \\<in> { \\<Sum>i<2*n. (- 1)^i * a i .. \\<Sum>i<2*n+1. (- 1)^i * a i})\" (is \"?pos\")\n    and \"a 0 < 0 \\<longrightarrow>\n      (\\<forall>n. (\\<Sum>i. (- 1)^i*a i) \\<in> { \\<Sum>i<2*n+1. (- 1)^i * a i .. \\<Sum>i<2*n. (- 1)^i * a i})\" (is \"?neg\")\n    and \"(\\<lambda>n. \\<Sum>i<2*n. (- 1)^i*a i) \\<longlonglongrightarrow> (\\<Sum>i. (- 1)^i*a i)\" (is \"?f\")\n    and \"(\\<lambda>n. \\<Sum>i<2*n+1. (- 1)^i*a i) \\<longlonglongrightarrow> (\\<Sum>i. (- 1)^i*a i)\" (is \"?g\")\nproof -\n  have \"?summable \\<and> ?pos \\<and> ?neg \\<and> ?f \\<and> ?g\"\n  proof (cases \"(\\<forall>n. 0 \\<le> a n) \\<and> (\\<forall>m. \\<forall>n\\<ge>m. a n \\<le> a m)\")\n    case True\n    then have ord: \"\\<And>n m. m \\<le> n \\<Longrightarrow> a n \\<le> a m\"\n      and ge0: \"\\<And>n. 0 \\<le> a n\"\n      by auto\n    have mono: \"a (Suc n) \\<le> a n\" for n\n      using ord[where n=\"Suc n\" and m=n] by auto\n    note leibniz = summable_Leibniz'[OF \\<open>a \\<longlonglongrightarrow> 0\\<close> ge0]\n    from leibniz[OF mono]\n    show ?thesis using \\<open>0 \\<le> a 0\\<close> by auto\n  next\n    let ?a = \"\\<lambda>n. - a n\"\n    case False\n    with monoseq_le[OF \\<open>monoseq a\\<close> \\<open>a \\<longlonglongrightarrow> 0\\<close>]\n    have \"(\\<forall> n. a n \\<le> 0) \\<and> (\\<forall>m. \\<forall>n\\<ge>m. a m \\<le> a n)\" by auto\n    then have ord: \"\\<And>n m. m \\<le> n \\<Longrightarrow> ?a n \\<le> ?a m\" and ge0: \"\\<And> n. 0 \\<le> ?a n\"\n      by auto\n    have monotone: \"?a (Suc n) \\<le> ?a n\" for n\n      using ord[where n=\"Suc n\" and m=n] by auto\n    note leibniz =\n      summable_Leibniz'[OF _ ge0, of \"\\<lambda>x. x\",\n        OF tendsto_minus[OF \\<open>a \\<longlonglongrightarrow> 0\\<close>, unfolded minus_zero] monotone]\n    have \"summable (\\<lambda> n. (-1)^n * ?a n)\"\n      using leibniz(1) by auto\n    then obtain l where \"(\\<lambda> n. (-1)^n * ?a n) sums l\"\n      unfolding summable_def by auto\n    from this[THEN sums_minus] have \"(\\<lambda> n. (-1)^n * a n) sums -l\"\n      by auto\n    then have ?summable by (auto simp: summable_def)\n    moreover\n    have \"\\<bar>- a - - b\\<bar> = \\<bar>a - b\\<bar>\" for a b :: real\n      unfolding minus_diff_minus by auto\n\n    from suminf_minus[OF leibniz(1), unfolded mult_minus_right minus_minus]\n    have move_minus: \"(\\<Sum>n. - ((- 1) ^ n * a n)) = - (\\<Sum>n. (- 1) ^ n * a n)\"\n      by auto\n\n    have ?pos using \\<open>0 \\<le> ?a 0\\<close> by auto\n    moreover have ?neg\n      using leibniz(2,4)\n      unfolding mult_minus_right sum_negf move_minus neg_le_iff_le\n      by auto\n    moreover have ?f and ?g\n      using leibniz(3,5)[unfolded mult_minus_right sum_negf move_minus, THEN tendsto_minus_cancel]\n      by auto\n    ultimately show ?thesis by auto\n  qed\n  then show ?summable and ?pos and ?neg and ?f and ?g\n    by safe\nqed\n\n\nsubsection \\<open>Term-by-Term Differentiability of Power Series\\<close>\n\ndefinition diffs :: \"(nat \\<Rightarrow> 'a::ring_1) \\<Rightarrow> nat \\<Rightarrow> 'a\"\n  where \"diffs c = (\\<lambda>n. of_nat (Suc n) * c (Suc n))\"\n\ntext \\<open>Lemma about distributing negation over it.\\<close>\nlemma diffs_minus: \"diffs (\\<lambda>n. - c n) = (\\<lambda>n. - diffs c n)\"\n  by (simp add: diffs_def)\n\nlemma diffs_equiv:\n  fixes x :: \"'a::{real_normed_vector,ring_1}\"\n  shows \"summable (\\<lambda>n. diffs c n * x^n) \\<Longrightarrow>\n    (\\<lambda>n. of_nat n * c n * x^(n - Suc 0)) sums (\\<Sum>n. diffs c n * x^n)\"\n  unfolding diffs_def\n  by (simp add: summable_sums sums_Suc_imp)\n\nlemma lemma_termdiff1:\n  fixes z :: \"'a :: {monoid_mult,comm_ring}\"\n  shows \"(\\<Sum>p<m. (((z + h) ^ (m - p)) * (z ^ p)) - (z ^ m)) =\n    (\\<Sum>p<m. (z ^ p) * (((z + h) ^ (m - p)) - (z ^ (m - p))))\"\n  by (auto simp: algebra_simps power_add [symmetric])\n\nlemma sumr_diff_mult_const2: \"sum f {..<n} - of_nat n * r = (\\<Sum>i<n. f i - r)\"\n  for r :: \"'a::ring_1\"\n  by (simp add: sum_subtractf)\n\nlemma lemma_termdiff2:\n  fixes h :: \"'a::field\"\n  assumes h: \"h \\<noteq> 0\"\n  shows \"((z + h) ^ n - z ^ n) / h - of_nat n * z ^ (n - Suc 0) =\n         h * (\\<Sum>p< n - Suc 0. \\<Sum>q< n - Suc 0 - p. (z + h) ^ q * z ^ (n - 2 - q))\"\n    (is \"?lhs = ?rhs\")\nproof (cases n)\n  case (Suc m)\n  have 0: \"\\<And>x k. (\\<Sum>n<Suc k. h * (z ^ x * (z ^ (k - n) * (h + z) ^ n))) =\n                 (\\<Sum>j<Suc k.  h * ((h + z) ^ j * z ^ (x + k - j)))\"\n    by (auto simp add: power_add [symmetric] mult.commute intro: sum.cong)\n  have *: \"(\\<Sum>i<m. z ^ i * ((z + h) ^ (m - i) - z ^ (m - i))) =\n           (\\<Sum>i<m. \\<Sum>j<m - i. h * ((z + h) ^ j * z ^ (m - Suc j)))\"\n    by (force simp add: less_iff_Suc_add sum_distrib_left diff_power_eq_sum ac_simps 0\n        simp del: sum.lessThan_Suc power_Suc intro: sum.cong)\n  have \"h * ?lhs = (z + h) ^ n - z ^ n - h * of_nat n * z ^ (n - Suc 0)\"\n    by (simp add: right_diff_distrib diff_divide_distrib h mult.assoc [symmetric])\n  also have \"... = h * ((\\<Sum>p<Suc m. (z + h) ^ p * z ^ (m - p)) - of_nat (Suc m) * z ^ m)\"\n    by (simp add: Suc diff_power_eq_sum h right_diff_distrib [symmetric] mult.assoc\n        del: power_Suc sum.lessThan_Suc of_nat_Suc)\n  also have \"... = h * ((\\<Sum>p<Suc m. (z + h) ^ (m - p) * z ^ p) - of_nat (Suc m) * z ^ m)\"\n    by (subst sum.nat_diff_reindex[symmetric]) simp\n  also have \"... = h * (\\<Sum>i<Suc m. (z + h) ^ (m - i) * z ^ i - z ^ m)\"\n    by (simp add: sum_subtractf)\n  also have \"... = h * ?rhs\"\n    by (simp add: lemma_termdiff1 sum_distrib_left Suc *)\n  finally have \"h * ?lhs = h * ?rhs\" .\n  then show ?thesis\n    by (simp add: h)\nqed auto\n\n\nlemma real_sum_nat_ivl_bounded2:\n  fixes K :: \"'a::linordered_semidom\"\n  assumes f: \"\\<And>p::nat. p < n \\<Longrightarrow> f p \\<le> K\" and K: \"0 \\<le> K\"\n  shows \"sum f {..<n-k} \\<le> of_nat n * K\"\nproof -\n  have \"sum f {..<n-k} \\<le> (\\<Sum>i<n - k. K)\"\n    by (rule sum_mono [OF f]) auto\n  also have \"... \\<le> of_nat n * K\"\n    by (auto simp: mult_right_mono K)\n  finally show ?thesis .\nqed\n\nlemma lemma_termdiff3:\n  fixes h z :: \"'a::real_normed_field\"\n  assumes 1: \"h \\<noteq> 0\"\n    and 2: \"norm z \\<le> K\"\n    and 3: \"norm (z + h) \\<le> K\"\n  shows \"norm (((z + h) ^ n - z ^ n) / h - of_nat n * z ^ (n - Suc 0)) \\<le>\n    of_nat n * of_nat (n - Suc 0) * K ^ (n - 2) * norm h\"\nproof -\n  have \"norm (((z + h) ^ n - z ^ n) / h - of_nat n * z ^ (n - Suc 0)) =\n    norm (\\<Sum>p<n - Suc 0. \\<Sum>q<n - Suc 0 - p. (z + h) ^ q * z ^ (n - 2 - q)) * norm h\"\n    by (metis (lifting, no_types) lemma_termdiff2 [OF 1] mult.commute norm_mult)\n  also have \"\\<dots> \\<le> of_nat n * (of_nat (n - Suc 0) * K ^ (n - 2)) * norm h\"\n  proof (rule mult_right_mono [OF _ norm_ge_zero])\n    from norm_ge_zero 2 have K: \"0 \\<le> K\"\n      by (rule order_trans)\n    have le_Kn: \"norm ((z + h) ^ i * z ^ j) \\<le> K ^ n\" if \"i + j = n\" for i j n\n    proof -\n      have \"norm (z + h) ^ i * norm z ^ j \\<le> K ^ i * K ^ j\"\n        by (intro mult_mono power_mono 2 3 norm_ge_zero zero_le_power K)\n      also have \"... = K^n\"\n        by (metis power_add that)\n      finally show ?thesis\n        by (simp add: norm_mult norm_power) \n    qed\n    then have \"\\<And>p q.\n       \\<lbrakk>p < n; q < n - Suc 0\\<rbrakk> \\<Longrightarrow> norm ((z + h) ^ q * z ^ (n - 2 - q)) \\<le> K ^ (n - 2)\"\n      by (simp del: subst_all)\n    then\n    show \"norm (\\<Sum>p<n - Suc 0. \\<Sum>q<n - Suc 0 - p. (z + h) ^ q * z ^ (n - 2 - q)) \\<le>\n        of_nat n * (of_nat (n - Suc 0) * K ^ (n - 2))\"\n      by (intro order_trans [OF norm_sum]\n          real_sum_nat_ivl_bounded2 mult_nonneg_nonneg of_nat_0_le_iff zero_le_power K)\n  qed\n  also have \"\\<dots> = of_nat n * of_nat (n - Suc 0) * K ^ (n - 2) * norm h\"\n    by (simp only: mult.assoc)\n  finally show ?thesis .\nqed\n\nlemma lemma_termdiff4:\n  fixes f :: \"'a::real_normed_vector \\<Rightarrow> 'b::real_normed_vector\"\n    and k :: real\n  assumes k: \"0 < k\"\n    and le: \"\\<And>h. h \\<noteq> 0 \\<Longrightarrow> norm h < k \\<Longrightarrow> norm (f h) \\<le> K * norm h\"\n  shows \"f \\<midarrow>0\\<rightarrow> 0\"\nproof (rule tendsto_norm_zero_cancel)\n  show \"(\\<lambda>h. norm (f h)) \\<midarrow>0\\<rightarrow> 0\"\n  proof (rule real_tendsto_sandwich)\n    show \"eventually (\\<lambda>h. 0 \\<le> norm (f h)) (at 0)\"\n      by simp\n    show \"eventually (\\<lambda>h. norm (f h) \\<le> K * norm h) (at 0)\"\n      using k by (auto simp: eventually_at dist_norm le)\n    show \"(\\<lambda>h. 0) \\<midarrow>(0::'a)\\<rightarrow> (0::real)\"\n      by (rule tendsto_const)\n    have \"(\\<lambda>h. K * norm h) \\<midarrow>(0::'a)\\<rightarrow> K * norm (0::'a)\"\n      by (intro tendsto_intros)\n    then show \"(\\<lambda>h. K * norm h) \\<midarrow>(0::'a)\\<rightarrow> 0\"\n      by simp\n  qed\nqed\n\nlemma lemma_termdiff5:\n  fixes g :: \"'a::real_normed_vector \\<Rightarrow> nat \\<Rightarrow> 'b::banach\"\n    and k :: real\n  assumes k: \"0 < k\"\n    and f: \"summable f\"\n    and le: \"\\<And>h n. h \\<noteq> 0 \\<Longrightarrow> norm h < k \\<Longrightarrow> norm (g h n) \\<le> f n * norm h\"\n  shows \"(\\<lambda>h. suminf (g h)) \\<midarrow>0\\<rightarrow> 0\"\nproof (rule lemma_termdiff4 [OF k])\n  fix h :: 'a\n  assume \"h \\<noteq> 0\" and \"norm h < k\"\n  then have 1: \"\\<forall>n. norm (g h n) \\<le> f n * norm h\"\n    by (simp add: le)\n  then have \"\\<exists>N. \\<forall>n\\<ge>N. norm (norm (g h n)) \\<le> f n * norm h\"\n    by simp\n  moreover from f have 2: \"summable (\\<lambda>n. f n * norm h)\"\n    by (rule summable_mult2)\n  ultimately have 3: \"summable (\\<lambda>n. norm (g h n))\"\n    by (rule summable_comparison_test)\n  then have \"norm (suminf (g h)) \\<le> (\\<Sum>n. norm (g h n))\"\n    by (rule summable_norm)\n  also from 1 3 2 have \"(\\<Sum>n. norm (g h n)) \\<le> (\\<Sum>n. f n * norm h)\"\n    by (simp add: suminf_le)\n  also from f have \"(\\<Sum>n. f n * norm h) = suminf f * norm h\"\n    by (rule suminf_mult2 [symmetric])\n  finally show \"norm (suminf (g h)) \\<le> suminf f * norm h\" .\nqed\n\n\n(* FIXME: Long proofs *)\n\nlemma termdiffs_aux:\n  fixes x :: \"'a::{real_normed_field,banach}\"\n  assumes 1: \"summable (\\<lambda>n. diffs (diffs c) n * K ^ n)\"\n    and 2: \"norm x < norm K\"\n  shows \"(\\<lambda>h. \\<Sum>n. c n * (((x + h) ^ n - x^n) / h - of_nat n * x ^ (n - Suc 0))) \\<midarrow>0\\<rightarrow> 0\"\nproof -\n  from dense [OF 2] obtain r where r1: \"norm x < r\" and r2: \"r < norm K\"\n    by fast\n  from norm_ge_zero r1 have r: \"0 < r\"\n    by (rule order_le_less_trans)\n  then have r_neq_0: \"r \\<noteq> 0\" by simp\n  show ?thesis\n  proof (rule lemma_termdiff5)\n    show \"0 < r - norm x\"\n      using r1 by simp\n    from r r2 have \"norm (of_real r::'a) < norm K\"\n      by simp\n    with 1 have \"summable (\\<lambda>n. norm (diffs (diffs c) n * (of_real r ^ n)))\"\n      by (rule powser_insidea)\n    then have \"summable (\\<lambda>n. diffs (diffs (\\<lambda>n. norm (c n))) n * r ^ n)\"\n      using r by (simp add: diffs_def norm_mult norm_power del: of_nat_Suc)\n    then have \"summable (\\<lambda>n. of_nat n * diffs (\\<lambda>n. norm (c n)) n * r ^ (n - Suc 0))\"\n      by (rule diffs_equiv [THEN sums_summable])\n    also have \"(\\<lambda>n. of_nat n * diffs (\\<lambda>n. norm (c n)) n * r ^ (n - Suc 0)) =\n               (\\<lambda>n. diffs (\\<lambda>m. of_nat (m - Suc 0) * norm (c m) * inverse r) n * (r ^ n))\"\n      by (simp add: diffs_def r_neq_0 fun_eq_iff split: nat_diff_split)\n    finally have \"summable\n      (\\<lambda>n. of_nat n * (of_nat (n - Suc 0) * norm (c n) * inverse r) * r ^ (n - Suc 0))\"\n      by (rule diffs_equiv [THEN sums_summable])\n    also have\n      \"(\\<lambda>n. of_nat n * (of_nat (n - Suc 0) * norm (c n) * inverse r) * r ^ (n - Suc 0)) =\n       (\\<lambda>n. norm (c n) * of_nat n * of_nat (n - Suc 0) * r ^ (n - 2))\"\n      by (rule ext) (simp add: r_neq_0 split: nat_diff_split)\n    finally show \"summable (\\<lambda>n. norm (c n) * of_nat n * of_nat (n - Suc 0) * r ^ (n - 2))\" .\n  next\n    fix h :: 'a and n\n    assume h: \"h \\<noteq> 0\"\n    assume \"norm h < r - norm x\"\n    then have \"norm x + norm h < r\" by simp\n    with norm_triangle_ineq \n    have xh: \"norm (x + h) < r\"\n      by (rule order_le_less_trans)\n    have \"norm (((x + h) ^ n - x ^ n) / h - of_nat n * x ^ (n - Suc 0))\n    \\<le> real n * (real (n - Suc 0) * (r ^ (n - 2) * norm h))\"\n      by (metis (mono_tags, lifting) h mult.assoc lemma_termdiff3 less_eq_real_def r1 xh)\n    then show \"norm (c n * (((x + h) ^ n - x^n) / h - of_nat n * x ^ (n - Suc 0))) \\<le>\n      norm (c n) * of_nat n * of_nat (n - Suc 0) * r ^ (n - 2) * norm h\"\n      by (simp only: norm_mult mult.assoc mult_left_mono [OF _ norm_ge_zero])\n  qed\nqed\n\nlemma termdiffs:\n  fixes K x :: \"'a::{real_normed_field,banach}\"\n  assumes 1: \"summable (\\<lambda>n. c n * K ^ n)\"\n    and 2: \"summable (\\<lambda>n. (diffs c) n * K ^ n)\"\n    and 3: \"summable (\\<lambda>n. (diffs (diffs c)) n * K ^ n)\"\n    and 4: \"norm x < norm K\"\n  shows \"DERIV (\\<lambda>x. \\<Sum>n. c n * x^n) x :> (\\<Sum>n. (diffs c) n * x^n)\"\n  unfolding DERIV_def\nproof (rule LIM_zero_cancel)\n  show \"(\\<lambda>h. (suminf (\\<lambda>n. c n * (x + h) ^ n) - suminf (\\<lambda>n. c n * x^n)) / h\n            - suminf (\\<lambda>n. diffs c n * x^n)) \\<midarrow>0\\<rightarrow> 0\"\n  proof (rule LIM_equal2)\n    show \"0 < norm K - norm x\"\n      using 4 by (simp add: less_diff_eq)\n  next\n    fix h :: 'a\n    assume \"norm (h - 0) < norm K - norm x\"\n    then have \"norm x + norm h < norm K\" by simp\n    then have 5: \"norm (x + h) < norm K\"\n      by (rule norm_triangle_ineq [THEN order_le_less_trans])\n    have \"summable (\\<lambda>n. c n * x^n)\"\n      and \"summable (\\<lambda>n. c n * (x + h) ^ n)\"\n      and \"summable (\\<lambda>n. diffs c n * x^n)\"\n      using 1 2 4 5 by (auto elim: powser_inside)\n    then have \"((\\<Sum>n. c n * (x + h) ^ n) - (\\<Sum>n. c n * x^n)) / h - (\\<Sum>n. diffs c n * x^n) =\n          (\\<Sum>n. (c n * (x + h) ^ n - c n * x^n) / h - of_nat n * c n * x ^ (n - Suc 0))\"\n      by (intro sums_unique sums_diff sums_divide diffs_equiv summable_sums)\n    then show \"((\\<Sum>n. c n * (x + h) ^ n) - (\\<Sum>n. c n * x^n)) / h - (\\<Sum>n. diffs c n * x^n) =\n          (\\<Sum>n. c n * (((x + h) ^ n - x^n) / h - of_nat n * x ^ (n - Suc 0)))\"\n      by (simp add: algebra_simps)\n  next\n    show \"(\\<lambda>h. \\<Sum>n. c n * (((x + h) ^ n - x^n) / h - of_nat n * x ^ (n - Suc 0))) \\<midarrow>0\\<rightarrow> 0\"\n      by (rule termdiffs_aux [OF 3 4])\n  qed\nqed\n\nsubsection \\<open>The Derivative of a Power Series Has the Same Radius of Convergence\\<close>\n\nlemma termdiff_converges:\n  fixes x :: \"'a::{real_normed_field,banach}\"\n  assumes K: \"norm x < K\"\n    and sm: \"\\<And>x. norm x < K \\<Longrightarrow> summable(\\<lambda>n. c n * x ^ n)\"\n  shows \"summable (\\<lambda>n. diffs c n * x ^ n)\"\nproof (cases \"x = 0\")\n  case True\n  then show ?thesis\n    using powser_sums_zero sums_summable by auto\nnext\n  case False\n  then have \"K > 0\"\n    using K less_trans zero_less_norm_iff by blast\n  then obtain r :: real where r: \"norm x < norm r\" \"norm r < K\" \"r > 0\"\n    using K False\n    by (auto simp: field_simps abs_less_iff add_pos_pos intro: that [of \"(norm x + K) / 2\"])\n  have to0: \"(\\<lambda>n. of_nat n * (x / of_real r) ^ n) \\<longlonglongrightarrow> 0\"\n    using r by (simp add: norm_divide powser_times_n_limit_0 [of \"x / of_real r\"])\n  obtain N where N: \"\\<And>n. n\\<ge>N \\<Longrightarrow> real_of_nat n * norm x ^ n < r ^ n\"\n    using r LIMSEQ_D [OF to0, of 1]\n    by (auto simp: norm_divide norm_mult norm_power field_simps)\n  have \"summable (\\<lambda>n. (of_nat n * c n) * x ^ n)\"\n  proof (rule summable_comparison_test')\n    show \"summable (\\<lambda>n. norm (c n * of_real r ^ n))\"\n      apply (rule powser_insidea [OF sm [of \"of_real ((r+K)/2)\"]])\n      using N r norm_of_real [of \"r + K\", where 'a = 'a] by auto\n    show \"\\<And>n. N \\<le> n \\<Longrightarrow> norm (of_nat n * c n * x ^ n) \\<le> norm (c n * of_real r ^ n)\"\n      using N r by (fastforce simp add: norm_mult norm_power less_eq_real_def)\n  qed\n  then have \"summable (\\<lambda>n. (of_nat (Suc n) * c(Suc n)) * x ^ Suc n)\"\n    using summable_iff_shift [of \"\\<lambda>n. of_nat n * c n * x ^ n\" 1]\n    by simp\n  then have \"summable (\\<lambda>n. (of_nat (Suc n) * c(Suc n)) * x ^ n)\"\n    using False summable_mult2 [of \"\\<lambda>n. (of_nat (Suc n) * c(Suc n) * x ^ n) * x\" \"inverse x\"]\n    by (simp add: mult.assoc) (auto simp: ac_simps)\n  then show ?thesis\n    by (simp add: diffs_def)\nqed\n\nlemma termdiff_converges_all:\n  fixes x :: \"'a::{real_normed_field,banach}\"\n  assumes \"\\<And>x. summable (\\<lambda>n. c n * x^n)\"\n  shows \"summable (\\<lambda>n. diffs c n * x^n)\"\n  by (rule termdiff_converges [where K = \"1 + norm x\"]) (use assms in auto)\n\nlemma termdiffs_strong:\n  fixes K x :: \"'a::{real_normed_field,banach}\"\n  assumes sm: \"summable (\\<lambda>n. c n * K ^ n)\"\n    and K: \"norm x < norm K\"\n  shows \"DERIV (\\<lambda>x. \\<Sum>n. c n * x^n) x :> (\\<Sum>n. diffs c n * x^n)\"\nproof -\n  have \"norm K + norm x < norm K + norm K\"\n    using K by force\n  then have K2: \"norm ((of_real (norm K) + of_real (norm x)) / 2 :: 'a) < norm K\"\n    by (auto simp: norm_triangle_lt norm_divide field_simps)\n  then have [simp]: \"norm ((of_real (norm K) + of_real (norm x)) :: 'a) < norm K * 2\"\n    by simp\n  have \"summable (\\<lambda>n. c n * (of_real (norm x + norm K) / 2) ^ n)\"\n    by (metis K2 summable_norm_cancel [OF powser_insidea [OF sm]] add.commute of_real_add)\n  moreover have \"\\<And>x. norm x < norm K \\<Longrightarrow> summable (\\<lambda>n. diffs c n * x ^ n)\"\n    by (blast intro: sm termdiff_converges powser_inside)\n  moreover have \"\\<And>x. norm x < norm K \\<Longrightarrow> summable (\\<lambda>n. diffs(diffs c) n * x ^ n)\"\n    by (blast intro: sm termdiff_converges powser_inside)\n  ultimately show ?thesis\n    by (rule termdiffs [where K = \"of_real (norm x + norm K) / 2\"])\n       (use K in \\<open>auto simp: field_simps simp flip: of_real_add\\<close>)\nqed\n\nlemma termdiffs_strong_converges_everywhere:\n  fixes K x :: \"'a::{real_normed_field,banach}\"\n  assumes \"\\<And>y. summable (\\<lambda>n. c n * y ^ n)\"\n  shows \"((\\<lambda>x. \\<Sum>n. c n * x^n) has_field_derivative (\\<Sum>n. diffs c n * x^n)) (at x)\"\n  using termdiffs_strong[OF assms[of \"of_real (norm x + 1)\"], of x]\n  by (force simp del: of_real_add)\n\nlemma termdiffs_strong':\n  fixes z :: \"'a :: {real_normed_field,banach}\"\n  assumes \"\\<And>z. norm z < K \\<Longrightarrow> summable (\\<lambda>n. c n * z ^ n)\"\n  assumes \"norm z < K\"\n  shows   \"((\\<lambda>z. \\<Sum>n. c n * z^n) has_field_derivative (\\<Sum>n. diffs c n * z^n)) (at z)\"\nproof (rule termdiffs_strong)\n  define L :: real where \"L =  (norm z + K) / 2\"\n  have \"0 \\<le> norm z\" by simp\n  also note \\<open>norm z < K\\<close>\n  finally have K: \"K \\<ge> 0\" by simp\n  from assms K have L: \"L \\<ge> 0\" \"norm z < L\" \"L < K\" by (simp_all add: L_def)\n  from L show \"norm z < norm (of_real L :: 'a)\" by simp\n  from L show \"summable (\\<lambda>n. c n * of_real L ^ n)\" by (intro assms(1)) simp_all\nqed\n\nlemma termdiffs_sums_strong:\n  fixes z :: \"'a :: {banach,real_normed_field}\"\n  assumes sums: \"\\<And>z. norm z < K \\<Longrightarrow> (\\<lambda>n. c n * z ^ n) sums f z\"\n  assumes deriv: \"(f has_field_derivative f') (at z)\"\n  assumes norm: \"norm z < K\"\n  shows   \"(\\<lambda>n. diffs c n * z ^ n) sums f'\"\nproof -\n  have summable: \"summable (\\<lambda>n. diffs c n * z^n)\"\n    by (intro termdiff_converges[OF norm] sums_summable[OF sums])\n  from norm have \"eventually (\\<lambda>z. z \\<in> norm -` {..<K}) (nhds z)\"\n    by (intro eventually_nhds_in_open open_vimage)\n       (simp_all add: continuous_on_norm)\n  hence eq: \"eventually (\\<lambda>z. (\\<Sum>n. c n * z^n) = f z) (nhds z)\"\n    by eventually_elim (insert sums, simp add: sums_iff)\n\n  have \"((\\<lambda>z. \\<Sum>n. c n * z^n) has_field_derivative (\\<Sum>n. diffs c n * z^n)) (at z)\"\n    by (intro termdiffs_strong'[OF _ norm] sums_summable[OF sums])\n  hence \"(f has_field_derivative (\\<Sum>n. diffs c n * z^n)) (at z)\"\n    by (subst (asm) DERIV_cong_ev[OF refl eq refl])\n  from this and deriv have \"(\\<Sum>n. diffs c n * z^n) = f'\" by (rule DERIV_unique)\n  with summable show ?thesis by (simp add: sums_iff)\nqed\n\nlemma isCont_powser:\n  fixes K x :: \"'a::{real_normed_field,banach}\"\n  assumes \"summable (\\<lambda>n. c n * K ^ n)\"\n  assumes \"norm x < norm K\"\n  shows \"isCont (\\<lambda>x. \\<Sum>n. c n * x^n) x\"\n  using termdiffs_strong[OF assms] by (blast intro!: DERIV_isCont)\n\nlemmas isCont_powser' = isCont_o2[OF _ isCont_powser]\n\nlemma isCont_powser_converges_everywhere:\n  fixes K x :: \"'a::{real_normed_field,banach}\"\n  assumes \"\\<And>y. summable (\\<lambda>n. c n * y ^ n)\"\n  shows \"isCont (\\<lambda>x. \\<Sum>n. c n * x^n) x\"\n  using termdiffs_strong[OF assms[of \"of_real (norm x + 1)\"], of x]\n  by (force intro!: DERIV_isCont simp del: of_real_add)\n\nlemma powser_limit_0:\n  fixes a :: \"nat \\<Rightarrow> 'a::{real_normed_field,banach}\"\n  assumes s: \"0 < s\"\n    and sm: \"\\<And>x. norm x < s \\<Longrightarrow> (\\<lambda>n. a n * x ^ n) sums (f x)\"\n  shows \"(f \\<longlongrightarrow> a 0) (at 0)\"\nproof -\n  have \"norm (of_real s / 2 :: 'a) < s\"\n    using s  by (auto simp: norm_divide)\n  then have \"summable (\\<lambda>n. a n * (of_real s / 2) ^ n)\"\n    by (rule sums_summable [OF sm])\n  then have \"((\\<lambda>x. \\<Sum>n. a n * x ^ n) has_field_derivative (\\<Sum>n. diffs a n * 0 ^ n)) (at 0)\"\n    by (rule termdiffs_strong) (use s in \\<open>auto simp: norm_divide\\<close>)\n  then have \"isCont (\\<lambda>x. \\<Sum>n. a n * x ^ n) 0\"\n    by (blast intro: DERIV_continuous)\n  then have \"((\\<lambda>x. \\<Sum>n. a n * x ^ n) \\<longlongrightarrow> a 0) (at 0)\"\n    by (simp add: continuous_within)\n  moreover have \"(\\<lambda>x. f x - (\\<Sum>n. a n * x ^ n)) \\<midarrow>0\\<rightarrow> 0\"\n    apply (clarsimp simp: LIM_eq)\n    apply (rule_tac x=s in exI)\n    using s sm sums_unique by fastforce\n  ultimately show ?thesis\n    by (rule Lim_transform)\nqed\n\nlemma powser_limit_0_strong:\n  fixes a :: \"nat \\<Rightarrow> 'a::{real_normed_field,banach}\"\n  assumes s: \"0 < s\"\n    and sm: \"\\<And>x. x \\<noteq> 0 \\<Longrightarrow> norm x < s \\<Longrightarrow> (\\<lambda>n. a n * x ^ n) sums (f x)\"\n  shows \"(f \\<longlongrightarrow> a 0) (at 0)\"\nproof -\n  have *: \"((\\<lambda>x. if x = 0 then a 0 else f x) \\<longlongrightarrow> a 0) (at 0)\"\n    by (rule powser_limit_0 [OF s]) (auto simp: powser_sums_zero sm)\n  show ?thesis\n    using \"*\" by (auto cong: Lim_cong_within)\nqed\n\n\nsubsection \\<open>Derivability of power series\\<close>\n\nlemma DERIV_series':\n  fixes f :: \"real \\<Rightarrow> nat \\<Rightarrow> real\"\n  assumes DERIV_f: \"\\<And> n. DERIV (\\<lambda> x. f x n) x0 :> (f' x0 n)\"\n    and allf_summable: \"\\<And> x. x \\<in> {a <..< b} \\<Longrightarrow> summable (f x)\"\n    and x0_in_I: \"x0 \\<in> {a <..< b}\"\n    and \"summable (f' x0)\"\n    and \"summable L\"\n    and L_def: \"\\<And>n x y. x \\<in> {a <..< b} \\<Longrightarrow> y \\<in> {a <..< b} \\<Longrightarrow> \\<bar>f x n - f y n\\<bar> \\<le> L n * \\<bar>x - y\\<bar>\"\n  shows \"DERIV (\\<lambda> x. suminf (f x)) x0 :> (suminf (f' x0))\"\n  unfolding DERIV_def\nproof (rule LIM_I)\n  fix r :: real\n  assume \"0 < r\" then have \"0 < r/3\" by auto\n\n  obtain N_L where N_L: \"\\<And> n. N_L \\<le> n \\<Longrightarrow> \\<bar> \\<Sum> i. L (i + n) \\<bar> < r/3\"\n    using suminf_exist_split[OF \\<open>0 < r/3\\<close> \\<open>summable L\\<close>] by auto\n\n  obtain N_f' where N_f': \"\\<And> n. N_f' \\<le> n \\<Longrightarrow> \\<bar> \\<Sum> i. f' x0 (i + n) \\<bar> < r/3\"\n    using suminf_exist_split[OF \\<open>0 < r/3\\<close> \\<open>summable (f' x0)\\<close>] by auto\n\n  let ?N = \"Suc (max N_L N_f')\"\n  have \"\\<bar> \\<Sum> i. f' x0 (i + ?N) \\<bar> < r/3\" (is \"?f'_part < r/3\")\n    and L_estimate: \"\\<bar> \\<Sum> i. L (i + ?N) \\<bar> < r/3\"\n    using N_L[of \"?N\"] and N_f' [of \"?N\"] by auto\n\n  let ?diff = \"\\<lambda>i x. (f (x0 + x) i - f x0 i) / x\"\n\n  let ?r = \"r / (3 * real ?N)\"\n  from \\<open>0 < r\\<close> have \"0 < ?r\" by simp\n\n  let ?s = \"\\<lambda>n. SOME s. 0 < s \\<and> (\\<forall> x. x \\<noteq> 0 \\<and> \\<bar> x \\<bar> < s \\<longrightarrow> \\<bar> ?diff n x - f' x0 n \\<bar> < ?r)\"\n  define S' where \"S' = Min (?s ` {..< ?N })\"\n\n  have \"0 < S'\"\n    unfolding S'_def\n  proof (rule iffD2[OF Min_gr_iff])\n    show \"\\<forall>x \\<in> (?s ` {..< ?N }). 0 < x\"\n    proof\n      fix x\n      assume \"x \\<in> ?s ` {..<?N}\"\n      then obtain n where \"x = ?s n\" and \"n \\<in> {..<?N}\"\n        using image_iff[THEN iffD1] by blast\n      from DERIV_D[OF DERIV_f[where n=n], THEN LIM_D, OF \\<open>0 < ?r\\<close>, unfolded real_norm_def]\n      obtain s where s_bound: \"0 < s \\<and> (\\<forall>x. x \\<noteq> 0 \\<and> \\<bar>x\\<bar> < s \\<longrightarrow> \\<bar>?diff n x - f' x0 n\\<bar> < ?r)\"\n        by auto\n      have \"0 < ?s n\"\n        by (rule someI2[where a=s]) (auto simp: s_bound simp del: of_nat_Suc)\n      then show \"0 < x\" by (simp only: \\<open>x = ?s n\\<close>)\n    qed\n  qed auto\n\n  define S where \"S = min (min (x0 - a) (b - x0)) S'\"\n  then have \"0 < S\" and S_a: \"S \\<le> x0 - a\" and S_b: \"S \\<le> b - x0\"\n    and \"S \\<le> S'\" using x0_in_I and \\<open>0 < S'\\<close>\n    by auto\n\n  have \"\\<bar>(suminf (f (x0 + x)) - suminf (f x0)) / x - suminf (f' x0)\\<bar> < r\"\n    if \"x \\<noteq> 0\" and \"\\<bar>x\\<bar> < S\" for x\n  proof -\n    from that have x_in_I: \"x0 + x \\<in> {a <..< b}\"\n      using S_a S_b by auto\n\n    note diff_smbl = summable_diff[OF allf_summable[OF x_in_I] allf_summable[OF x0_in_I]]\n    note div_smbl = summable_divide[OF diff_smbl]\n    note all_smbl = summable_diff[OF div_smbl \\<open>summable (f' x0)\\<close>]\n    note ign = summable_ignore_initial_segment[where k=\"?N\"]\n    note diff_shft_smbl = summable_diff[OF ign[OF allf_summable[OF x_in_I]] ign[OF allf_summable[OF x0_in_I]]]\n    note div_shft_smbl = summable_divide[OF diff_shft_smbl]\n    note all_shft_smbl = summable_diff[OF div_smbl ign[OF \\<open>summable (f' x0)\\<close>]]\n\n    have 1: \"\\<bar>(\\<bar>?diff (n + ?N) x\\<bar>)\\<bar> \\<le> L (n + ?N)\" for n\n    proof -\n      have \"\\<bar>?diff (n + ?N) x\\<bar> \\<le> L (n + ?N) * \\<bar>(x0 + x) - x0\\<bar> / \\<bar>x\\<bar>\"\n        using divide_right_mono[OF L_def[OF x_in_I x0_in_I] abs_ge_zero]\n        by (simp only: abs_divide)\n      with \\<open>x \\<noteq> 0\\<close> show ?thesis by auto\n    qed\n    note 2 = summable_rabs_comparison_test[OF _ ign[OF \\<open>summable L\\<close>]]\n    from 1 have \"\\<bar> \\<Sum> i. ?diff (i + ?N) x \\<bar> \\<le> (\\<Sum> i. L (i + ?N))\"\n      by (metis (lifting) abs_idempotent\n          order_trans[OF summable_rabs[OF 2] suminf_le[OF _ 2 ign[OF \\<open>summable L\\<close>]]])\n    then have \"\\<bar>\\<Sum>i. ?diff (i + ?N) x\\<bar> \\<le> r / 3\" (is \"?L_part \\<le> r/3\")\n      using L_estimate by auto\n\n    have \"\\<bar>\\<Sum>n<?N. ?diff n x - f' x0 n\\<bar> \\<le> (\\<Sum>n<?N. \\<bar>?diff n x - f' x0 n\\<bar>)\" ..\n    also have \"\\<dots> < (\\<Sum>n<?N. ?r)\"\n    proof (rule sum_strict_mono)\n      fix n\n      assume \"n \\<in> {..< ?N}\"\n      have \"\\<bar>x\\<bar> < S\" using \\<open>\\<bar>x\\<bar> < S\\<close> .\n      also have \"S \\<le> S'\" using \\<open>S \\<le> S'\\<close> .\n      also have \"S' \\<le> ?s n\"\n        unfolding S'_def\n      proof (rule Min_le_iff[THEN iffD2])\n        have \"?s n \\<in> (?s ` {..<?N}) \\<and> ?s n \\<le> ?s n\"\n          using \\<open>n \\<in> {..< ?N}\\<close> by auto\n        then show \"\\<exists> a \\<in> (?s ` {..<?N}). a \\<le> ?s n\"\n          by blast\n      qed auto\n      finally have \"\\<bar>x\\<bar> < ?s n\" .\n\n      from DERIV_D[OF DERIV_f[where n=n], THEN LIM_D, OF \\<open>0 < ?r\\<close>,\n          unfolded real_norm_def diff_0_right, unfolded some_eq_ex[symmetric], THEN conjunct2]\n      have \"\\<forall>x. x \\<noteq> 0 \\<and> \\<bar>x\\<bar> < ?s n \\<longrightarrow> \\<bar>?diff n x - f' x0 n\\<bar> < ?r\" .\n      with \\<open>x \\<noteq> 0\\<close> and \\<open>\\<bar>x\\<bar> < ?s n\\<close> show \"\\<bar>?diff n x - f' x0 n\\<bar> < ?r\"\n        by blast\n    qed auto\n    also have \"\\<dots> = of_nat (card {..<?N}) * ?r\"\n      by (rule sum_constant)\n    also have \"\\<dots> = real ?N * ?r\"\n      by simp\n    also have \"\\<dots> = r/3\"\n      by (auto simp del: of_nat_Suc)\n    finally have \"\\<bar>\\<Sum>n<?N. ?diff n x - f' x0 n \\<bar> < r / 3\" (is \"?diff_part < r / 3\") .\n\n    from suminf_diff[OF allf_summable[OF x_in_I] allf_summable[OF x0_in_I]]\n    have \"\\<bar>(suminf (f (x0 + x)) - (suminf (f x0))) / x - suminf (f' x0)\\<bar> =\n        \\<bar>\\<Sum>n. ?diff n x - f' x0 n\\<bar>\"\n      unfolding suminf_diff[OF div_smbl \\<open>summable (f' x0)\\<close>, symmetric]\n      using suminf_divide[OF diff_smbl, symmetric] by auto\n    also have \"\\<dots> \\<le> ?diff_part + \\<bar>(\\<Sum>n. ?diff (n + ?N) x) - (\\<Sum> n. f' x0 (n + ?N))\\<bar>\"\n      unfolding suminf_split_initial_segment[OF all_smbl, where k=\"?N\"]\n      unfolding suminf_diff[OF div_shft_smbl ign[OF \\<open>summable (f' x0)\\<close>]]\n      apply (simp only: add.commute)\n      using abs_triangle_ineq by blast\n    also have \"\\<dots> \\<le> ?diff_part + ?L_part + ?f'_part\"\n      using abs_triangle_ineq4 by auto\n    also have \"\\<dots> < r /3 + r/3 + r/3\"\n      using \\<open>?diff_part < r/3\\<close> \\<open>?L_part \\<le> r/3\\<close> and \\<open>?f'_part < r/3\\<close>\n      by (rule add_strict_mono [OF add_less_le_mono])\n    finally show ?thesis\n      by auto\n  qed\n  then show \"\\<exists>s > 0. \\<forall> x. x \\<noteq> 0 \\<and> norm (x - 0) < s \\<longrightarrow>\n      norm (((\\<Sum>n. f (x0 + x) n) - (\\<Sum>n. f x0 n)) / x - (\\<Sum>n. f' x0 n)) < r\"\n    using \\<open>0 < S\\<close> by auto\nqed\n\nlemma DERIV_power_series':\n  fixes f :: \"nat \\<Rightarrow> real\"\n  assumes converges: \"\\<And>x. x \\<in> {-R <..< R} \\<Longrightarrow> summable (\\<lambda>n. f n * real (Suc n) * x^n)\"\n    and x0_in_I: \"x0 \\<in> {-R <..< R}\"\n    and \"0 < R\"\n  shows \"DERIV (\\<lambda>x. (\\<Sum>n. f n * x^(Suc n))) x0 :> (\\<Sum>n. f n * real (Suc n) * x0^n)\"\n    (is \"DERIV (\\<lambda>x. suminf (?f x)) x0 :> suminf (?f' x0)\")\nproof -\n  have for_subinterval: \"DERIV (\\<lambda>x. suminf (?f x)) x0 :> suminf (?f' x0)\"\n    if \"0 < R'\" and \"R' < R\" and \"-R' < x0\" and \"x0 < R'\" for R'\n  proof -\n    from that have \"x0 \\<in> {-R' <..< R'}\" and \"R' \\<in> {-R <..< R}\" and \"x0 \\<in> {-R <..< R}\"\n      by auto\n    show ?thesis\n    proof (rule DERIV_series')\n      show \"summable (\\<lambda> n. \\<bar>f n * real (Suc n) * R'^n\\<bar>)\"\n      proof -\n        have \"(R' + R) / 2 < R\" and \"0 < (R' + R) / 2\"\n          using \\<open>0 < R'\\<close> \\<open>0 < R\\<close> \\<open>R' < R\\<close> by (auto simp: field_simps)\n        then have in_Rball: \"(R' + R) / 2 \\<in> {-R <..< R}\"\n          using \\<open>R' < R\\<close> by auto\n        have \"norm R' < norm ((R' + R) / 2)\"\n          using \\<open>0 < R'\\<close> \\<open>0 < R\\<close> \\<open>R' < R\\<close> by (auto simp: field_simps)\n        from powser_insidea[OF converges[OF in_Rball] this] show ?thesis\n          by auto\n      qed\n    next\n      fix n x y\n      assume \"x \\<in> {-R' <..< R'}\" and \"y \\<in> {-R' <..< R'}\"\n      show \"\\<bar>?f x n - ?f y n\\<bar> \\<le> \\<bar>f n * real (Suc n) * R'^n\\<bar> * \\<bar>x-y\\<bar>\"\n      proof -\n        have \"\\<bar>f n * x ^ (Suc n) - f n * y ^ (Suc n)\\<bar> =\n          (\\<bar>f n\\<bar> * \\<bar>x-y\\<bar>) * \\<bar>\\<Sum>p<Suc n. x ^ p * y ^ (n - p)\\<bar>\"\n          unfolding right_diff_distrib[symmetric] diff_power_eq_sum abs_mult\n          by auto\n        also have \"\\<dots> \\<le> (\\<bar>f n\\<bar> * \\<bar>x-y\\<bar>) * (\\<bar>real (Suc n)\\<bar> * \\<bar>R' ^ n\\<bar>)\"\n        proof (rule mult_left_mono)\n          have \"\\<bar>\\<Sum>p<Suc n. x ^ p * y ^ (n - p)\\<bar> \\<le> (\\<Sum>p<Suc n. \\<bar>x ^ p * y ^ (n - p)\\<bar>)\"\n            by (rule sum_abs)\n          also have \"\\<dots> \\<le> (\\<Sum>p<Suc n. R' ^ n)\"\n          proof (rule sum_mono)\n            fix p\n            assume \"p \\<in> {..<Suc n}\"\n            then have \"p \\<le> n\" by auto\n            have \"\\<bar>x^n\\<bar> \\<le> R'^n\" if  \"x \\<in> {-R'<..<R'}\" for n and x :: real\n            proof -\n              from that have \"\\<bar>x\\<bar> \\<le> R'\" by auto\n              then show ?thesis\n                unfolding power_abs by (rule power_mono) auto\n            qed\n            from mult_mono[OF this[OF \\<open>x \\<in> {-R'<..<R'}\\<close>, of p] this[OF \\<open>y \\<in> {-R'<..<R'}\\<close>, of \"n-p\"]]\n              and \\<open>0 < R'\\<close>\n            have \"\\<bar>x^p * y^(n - p)\\<bar> \\<le> R'^p * R'^(n - p)\"\n              unfolding abs_mult by auto\n            then show \"\\<bar>x^p * y^(n - p)\\<bar> \\<le> R'^n\"\n              unfolding power_add[symmetric] using \\<open>p \\<le> n\\<close> by auto\n          qed\n          also have \"\\<dots> = real (Suc n) * R' ^ n\"\n            unfolding sum_constant card_atLeastLessThan by auto\n          finally show \"\\<bar>\\<Sum>p<Suc n. x ^ p * y ^ (n - p)\\<bar> \\<le> \\<bar>real (Suc n)\\<bar> * \\<bar>R' ^ n\\<bar>\"\n            unfolding abs_of_nonneg[OF zero_le_power[OF less_imp_le[OF \\<open>0 < R'\\<close>]]]\n            by linarith\n          show \"0 \\<le> \\<bar>f n\\<bar> * \\<bar>x - y\\<bar>\"\n            unfolding abs_mult[symmetric] by auto\n        qed\n        also have \"\\<dots> = \\<bar>f n * real (Suc n) * R' ^ n\\<bar> * \\<bar>x - y\\<bar>\"\n          unfolding abs_mult mult.assoc[symmetric] by algebra\n        finally show ?thesis .\n      qed\n    next\n      show \"DERIV (\\<lambda>x. ?f x n) x0 :> ?f' x0 n\" for n\n        by (auto intro!: derivative_eq_intros simp del: power_Suc)\n    next\n      fix x\n      assume \"x \\<in> {-R' <..< R'}\"\n      then have \"R' \\<in> {-R <..< R}\" and \"norm x < norm R'\"\n        using assms \\<open>R' < R\\<close> by auto\n      have \"summable (\\<lambda>n. f n * x^n)\"\n      proof (rule summable_comparison_test, intro exI allI impI)\n        fix n\n        have le: \"\\<bar>f n\\<bar> * 1 \\<le> \\<bar>f n\\<bar> * real (Suc n)\"\n          by (rule mult_left_mono) auto\n        show \"norm (f n * x^n) \\<le> norm (f n * real (Suc n) * x^n)\"\n          unfolding real_norm_def abs_mult\n          using le mult_right_mono by fastforce\n      qed (rule powser_insidea[OF converges[OF \\<open>R' \\<in> {-R <..< R}\\<close>] \\<open>norm x < norm R'\\<close>])\n      from this[THEN summable_mult2[where c=x], simplified mult.assoc, simplified mult.commute]\n      show \"summable (?f x)\" by auto\n    next\n      show \"summable (?f' x0)\"\n        using converges[OF \\<open>x0 \\<in> {-R <..< R}\\<close>] .\n      show \"x0 \\<in> {-R' <..< R'}\"\n        using \\<open>x0 \\<in> {-R' <..< R'}\\<close> .\n    qed\n  qed\n  let ?R = \"(R + \\<bar>x0\\<bar>) / 2\"\n  have \"\\<bar>x0\\<bar> < ?R\"\n    using assms by (auto simp: field_simps)\n  then have \"- ?R < x0\"\n  proof (cases \"x0 < 0\")\n    case True\n    then have \"- x0 < ?R\"\n      using \\<open>\\<bar>x0\\<bar> < ?R\\<close> by auto\n    then show ?thesis\n      unfolding neg_less_iff_less[symmetric, of \"- x0\"] by auto\n  next\n    case False\n    have \"- ?R < 0\" using assms by auto\n    also have \"\\<dots> \\<le> x0\" using False by auto\n    finally show ?thesis .\n  qed\n  then have \"0 < ?R\" \"?R < R\" \"- ?R < x0\" and \"x0 < ?R\"\n    using assms by (auto simp: field_simps)\n  from for_subinterval[OF this] show ?thesis .\nqed\n\nlemma geometric_deriv_sums:\n  fixes z :: \"'a :: {real_normed_field,banach}\"\n  assumes \"norm z < 1\"\n  shows   \"(\\<lambda>n. of_nat (Suc n) * z ^ n) sums (1 / (1 - z)^2)\"\nproof -\n  have \"(\\<lambda>n. diffs (\\<lambda>n. 1) n * z^n) sums (1 / (1 - z)^2)\"\n  proof (rule termdiffs_sums_strong)\n    fix z :: 'a assume \"norm z < 1\"\n    thus \"(\\<lambda>n. 1 * z^n) sums (1 / (1 - z))\" by (simp add: geometric_sums)\n  qed (insert assms, auto intro!: derivative_eq_intros simp: power2_eq_square)\n  thus ?thesis unfolding diffs_def by simp\nqed\n\nlemma isCont_pochhammer [continuous_intros]: \"isCont (\\<lambda>z. pochhammer z n) z\"\n  for z :: \"'a::real_normed_field\"\n  by (induct n) (auto simp: pochhammer_rec')\n\nlemma continuous_on_pochhammer [continuous_intros]: \"continuous_on A (\\<lambda>z. pochhammer z n)\"\n  for A :: \"'a::real_normed_field set\"\n  by (intro continuous_at_imp_continuous_on ballI isCont_pochhammer)\n\nlemmas continuous_on_pochhammer' [continuous_intros] =\n  continuous_on_compose2[OF continuous_on_pochhammer _ subset_UNIV]\n\n\nsubsection \\<open>Exponential Function\\<close>\n\ndefinition exp :: \"'a \\<Rightarrow> 'a::{real_normed_algebra_1,banach}\"\n  where \"exp = (\\<lambda>x. \\<Sum>n. x^n /\\<^sub>R fact n)\"\n\nlemma summable_exp_generic:\n  fixes x :: \"'a::{real_normed_algebra_1,banach}\"\n  defines S_def: \"S \\<equiv> \\<lambda>n. x^n /\\<^sub>R fact n\"\n  shows \"summable S\"\nproof -\n  have S_Suc: \"\\<And>n. S (Suc n) = (x * S n) /\\<^sub>R (Suc n)\"\n    unfolding S_def by (simp del: mult_Suc)\n  obtain r :: real where r0: \"0 < r\" and r1: \"r < 1\"\n    using dense [OF zero_less_one] by fast\n  obtain N :: nat where N: \"norm x < real N * r\"\n    using ex_less_of_nat_mult r0 by auto\n  from r1 show ?thesis\n  proof (rule summable_ratio_test [rule_format])\n    fix n :: nat\n    assume n: \"N \\<le> n\"\n    have \"norm x \\<le> real N * r\"\n      using N by (rule order_less_imp_le)\n    also have \"real N * r \\<le> real (Suc n) * r\"\n      using r0 n by (simp add: mult_right_mono)\n    finally have \"norm x * norm (S n) \\<le> real (Suc n) * r * norm (S n)\"\n      using norm_ge_zero by (rule mult_right_mono)\n    then have \"norm (x * S n) \\<le> real (Suc n) * r * norm (S n)\"\n      by (rule order_trans [OF norm_mult_ineq])\n    then have \"norm (x * S n) / real (Suc n) \\<le> r * norm (S n)\"\n      by (simp add: pos_divide_le_eq ac_simps)\n    then show \"norm (S (Suc n)) \\<le> r * norm (S n)\"\n      by (simp add: S_Suc inverse_eq_divide)\n  qed\nqed\n\nlemma summable_norm_exp: \"summable (\\<lambda>n. norm (x^n /\\<^sub>R fact n))\"\n  for x :: \"'a::{real_normed_algebra_1,banach}\"\nproof (rule summable_norm_comparison_test [OF exI, rule_format])\n  show \"summable (\\<lambda>n. norm x^n /\\<^sub>R fact n)\"\n    by (rule summable_exp_generic)\n  show \"norm (x^n /\\<^sub>R fact n) \\<le> norm x^n /\\<^sub>R fact n\" for n\n    by (simp add: norm_power_ineq)\nqed\n\nlemma summable_exp: \"summable (\\<lambda>n. inverse (fact n) * x^n)\"\n  for x :: \"'a::{real_normed_field,banach}\"\n  using summable_exp_generic [where x=x]\n  by (simp add: scaleR_conv_of_real nonzero_of_real_inverse)\n\nlemma exp_converges: \"(\\<lambda>n. x^n /\\<^sub>R fact n) sums exp x\"\n  unfolding exp_def by (rule summable_exp_generic [THEN summable_sums])\n\nlemma exp_fdiffs:\n  \"diffs (\\<lambda>n. inverse (fact n)) = (\\<lambda>n. inverse (fact n :: 'a::{real_normed_field,banach}))\"\n  by (simp add: diffs_def mult_ac nonzero_inverse_mult_distrib nonzero_of_real_inverse\n      del: mult_Suc of_nat_Suc)\n\nlemma diffs_of_real: \"diffs (\\<lambda>n. of_real (f n)) = (\\<lambda>n. of_real (diffs f n))\"\n  by (simp add: diffs_def)\n\nlemma DERIV_exp [simp]: \"DERIV exp x :> exp x\"\n  unfolding exp_def scaleR_conv_of_real\nproof (rule DERIV_cong)\n  have sinv: \"summable (\\<lambda>n. of_real (inverse (fact n)) * x ^ n)\" for x::'a\n    by (rule exp_converges [THEN sums_summable, unfolded scaleR_conv_of_real])\n  note xx = exp_converges [THEN sums_summable, unfolded scaleR_conv_of_real]\n  show \"((\\<lambda>x. \\<Sum>n. of_real (inverse (fact n)) * x ^ n) has_field_derivative\n        (\\<Sum>n. diffs (\\<lambda>n. of_real (inverse (fact n))) n * x ^ n))  (at x)\"\n    by (rule termdiffs [where K=\"of_real (1 + norm x)\"]) (simp_all only: diffs_of_real exp_fdiffs sinv norm_of_real)\n  show \"(\\<Sum>n. diffs (\\<lambda>n. of_real (inverse (fact n))) n * x ^ n) = (\\<Sum>n. of_real (inverse (fact n)) * x ^ n)\"\n    by (simp add: diffs_of_real exp_fdiffs)\nqed\n\ndeclare DERIV_exp[THEN DERIV_chain2, derivative_intros]\n  and DERIV_exp[THEN DERIV_chain2, unfolded has_field_derivative_def, derivative_intros]\n\nlemmas has_derivative_exp[derivative_intros] = DERIV_exp[THEN DERIV_compose_FDERIV]\n\nlemma norm_exp: \"norm (exp x) \\<le> exp (norm x)\"\nproof -\n  from summable_norm[OF summable_norm_exp, of x]\n  have \"norm (exp x) \\<le> (\\<Sum>n. inverse (fact n) * norm (x^n))\"\n    by (simp add: exp_def)\n  also have \"\\<dots> \\<le> exp (norm x)\"\n    using summable_exp_generic[of \"norm x\"] summable_norm_exp[of x]\n    by (auto simp: exp_def intro!: suminf_le norm_power_ineq)\n  finally show ?thesis .\nqed\n\nlemma isCont_exp: \"isCont exp x\"\n  for x :: \"'a::{real_normed_field,banach}\"\n  by (rule DERIV_exp [THEN DERIV_isCont])\n\nlemma isCont_exp' [simp]: \"isCont f a \\<Longrightarrow> isCont (\\<lambda>x. exp (f x)) a\"\n  for f :: \"_ \\<Rightarrow>'a::{real_normed_field,banach}\"\n  by (rule isCont_o2 [OF _ isCont_exp])\n\nlemma tendsto_exp [tendsto_intros]: \"(f \\<longlongrightarrow> a) F \\<Longrightarrow> ((\\<lambda>x. exp (f x)) \\<longlongrightarrow> exp a) F\"\n  for f:: \"_ \\<Rightarrow>'a::{real_normed_field,banach}\"\n  by (rule isCont_tendsto_compose [OF isCont_exp])\n\nlemma continuous_exp [continuous_intros]: \"continuous F f \\<Longrightarrow> continuous F (\\<lambda>x. exp (f x))\"\n  for f :: \"_ \\<Rightarrow>'a::{real_normed_field,banach}\"\n  unfolding continuous_def by (rule tendsto_exp)\n\nlemma continuous_on_exp [continuous_intros]: \"continuous_on s f \\<Longrightarrow> continuous_on s (\\<lambda>x. exp (f x))\"\n  for f :: \"_ \\<Rightarrow>'a::{real_normed_field,banach}\"\n  unfolding continuous_on_def by (auto intro: tendsto_exp)\n\n\nsubsubsection \\<open>Properties of the Exponential Function\\<close>\n\nlemma exp_zero [simp]: \"exp 0 = 1\"\n  unfolding exp_def by (simp add: scaleR_conv_of_real)\n\nlemma exp_series_add_commuting:\n  fixes x y :: \"'a::{real_normed_algebra_1,banach}\"\n  defines S_def: \"S \\<equiv> \\<lambda>x n. x^n /\\<^sub>R fact n\"\n  assumes comm: \"x * y = y * x\"\n  shows \"S (x + y) n = (\\<Sum>i\\<le>n. S x i * S y (n - i))\"\nproof (induct n)\n  case 0\n  show ?case\n    unfolding S_def by simp\nnext\n  case (Suc n)\n  have S_Suc: \"\\<And>x n. S x (Suc n) = (x * S x n) /\\<^sub>R real (Suc n)\"\n    unfolding S_def by (simp del: mult_Suc)\n  then have times_S: \"\\<And>x n. x * S x n = real (Suc n) *\\<^sub>R S x (Suc n)\"\n    by simp\n  have S_comm: \"\\<And>n. S x n * y = y * S x n\"\n    by (simp add: power_commuting_commutes comm S_def)\n\n  have \"real (Suc n) *\\<^sub>R S (x + y) (Suc n) = (x + y) * (\\<Sum>i\\<le>n. S x i * S y (n - i))\"\n    by (metis Suc.hyps times_S)\n  also have \"\\<dots> = x * (\\<Sum>i\\<le>n. S x i * S y (n - i)) + y * (\\<Sum>i\\<le>n. S x i * S y (n - i))\"\n    by (rule distrib_right)\n  also have \"\\<dots> = (\\<Sum>i\\<le>n. x * S x i * S y (n - i)) + (\\<Sum>i\\<le>n. S x i * y * S y (n - i))\"\n    by (simp add: sum_distrib_left ac_simps S_comm)\n  also have \"\\<dots> = (\\<Sum>i\\<le>n. x * S x i * S y (n - i)) + (\\<Sum>i\\<le>n. S x i * (y * S y (n - i)))\"\n    by (simp add: ac_simps)\n  also have \"\\<dots> = (\\<Sum>i\\<le>n. real (Suc i) *\\<^sub>R (S x (Suc i) * S y (n - i))) \n                + (\\<Sum>i\\<le>n. real (Suc n - i) *\\<^sub>R (S x i * S y (Suc n - i)))\"\n    by (simp add: times_S Suc_diff_le)\n  also have \"(\\<Sum>i\\<le>n. real (Suc i) *\\<^sub>R (S x (Suc i) * S y (n - i)))\n           = (\\<Sum>i\\<le>Suc n. real i *\\<^sub>R (S x i * S y (Suc n - i)))\"\n    by (subst sum.atMost_Suc_shift) simp\n  also have \"(\\<Sum>i\\<le>n. real (Suc n - i) *\\<^sub>R (S x i * S y (Suc n - i)))\n           = (\\<Sum>i\\<le>Suc n. real (Suc n - i) *\\<^sub>R (S x i * S y (Suc n - i)))\"\n    by simp\n  also have \"(\\<Sum>i\\<le>Suc n. real i *\\<^sub>R (S x i * S y (Suc n - i)))\n           + (\\<Sum>i\\<le>Suc n. real (Suc n - i) *\\<^sub>R (S x i * S y (Suc n - i))) \n           = (\\<Sum>i\\<le>Suc n. real (Suc n) *\\<^sub>R (S x i * S y (Suc n - i)))\"\n    by (simp flip: sum.distrib scaleR_add_left of_nat_add) \n  also have \"\\<dots> = real (Suc n) *\\<^sub>R (\\<Sum>i\\<le>Suc n. S x i * S y (Suc n - i))\"\n    by (simp only: scaleR_right.sum)\n  finally show \"S (x + y) (Suc n) = (\\<Sum>i\\<le>Suc n. S x i * S y (Suc n - i))\"\n    by (simp del: sum.cl_ivl_Suc)\nqed\n\nlemma exp_add_commuting: \"x * y = y * x \\<Longrightarrow> exp (x + y) = exp x * exp y\"\n  by (simp only: exp_def Cauchy_product summable_norm_exp exp_series_add_commuting)\n\nlemma exp_times_arg_commute: \"exp A * A = A * exp A\"\n  by (simp add: exp_def suminf_mult[symmetric] summable_exp_generic power_commutes suminf_mult2)\n\nlemma exp_add: \"exp (x + y) = exp x * exp y\"\n  for x y :: \"'a::{real_normed_field,banach}\"\n  by (rule exp_add_commuting) (simp add: ac_simps)\n\nlemma exp_double: \"exp(2 * z) = exp z ^ 2\"\n  by (simp add: exp_add_commuting mult_2 power2_eq_square)\n\nlemmas mult_exp_exp = exp_add [symmetric]\n\nlemma exp_of_real: \"exp (of_real x) = of_real (exp x)\"\n  unfolding exp_def\n  apply (subst suminf_of_real [OF summable_exp_generic])\n  apply (simp add: scaleR_conv_of_real)\n  done\n\nlemmas of_real_exp = exp_of_real[symmetric]\n\ncorollary exp_in_Reals [simp]: \"z \\<in> \\<real> \\<Longrightarrow> exp z \\<in> \\<real>\"\n  by (metis Reals_cases Reals_of_real exp_of_real)\n\nlemma exp_not_eq_zero [simp]: \"exp x \\<noteq> 0\"\nproof\n  have \"exp x * exp (- x) = 1\"\n    by (simp add: exp_add_commuting[symmetric])\n  also assume \"exp x = 0\"\n  finally show False by simp\nqed\n\nlemma exp_minus_inverse: \"exp x * exp (- x) = 1\"\n  by (simp add: exp_add_commuting[symmetric])\n\nlemma exp_minus: \"exp (- x) = inverse (exp x)\"\n  for x :: \"'a::{real_normed_field,banach}\"\n  by (intro inverse_unique [symmetric] exp_minus_inverse)\n\nlemma exp_diff: \"exp (x - y) = exp x / exp y\"\n  for x :: \"'a::{real_normed_field,banach}\"\n  using exp_add [of x \"- y\"] by (simp add: exp_minus divide_inverse)\n\nlemma exp_of_nat_mult: \"exp (of_nat n * x) = exp x ^ n\"\n  for x :: \"'a::{real_normed_field,banach}\"\n  by (induct n) (auto simp: distrib_left exp_add mult.commute)\n\ncorollary exp_of_nat2_mult: \"exp (x * of_nat n) = exp x ^ n\"\n  for x :: \"'a::{real_normed_field,banach}\"\n  by (metis exp_of_nat_mult mult_of_nat_commute)\n\nlemma exp_sum: \"finite I \\<Longrightarrow> exp (sum f I) = prod (\\<lambda>x. exp (f x)) I\"\n  by (induct I rule: finite_induct) (auto simp: exp_add_commuting mult.commute)\n\nlemma exp_divide_power_eq:\n  fixes x :: \"'a::{real_normed_field,banach}\"\n  assumes \"n > 0\"\n  shows \"exp (x / of_nat n) ^ n = exp x\"\n  using assms\nproof (induction n arbitrary: x)\n  case (Suc n)\n  show ?case\n  proof (cases \"n = 0\")\n    case True\n    then show ?thesis by simp\n  next\n    case False\n    have [simp]: \"1 + (of_nat n * of_nat n + of_nat n * 2) \\<noteq> (0::'a)\"\n      using of_nat_eq_iff [of \"1 + n * n + n * 2\" \"0\"]\n      by simp\n    from False have [simp]: \"x * of_nat n / (1 + of_nat n) / of_nat n = x / (1 + of_nat n)\"\n      by simp\n    have [simp]: \"x / (1 + of_nat n) + x * of_nat n / (1 + of_nat n) = x\"\n      using of_nat_neq_0\n      by (auto simp add: field_split_simps)\n    show ?thesis\n      using Suc.IH [of \"x * of_nat n / (1 + of_nat n)\"] False\n      by (simp add: exp_add [symmetric])\n  qed\nqed simp\n\nlemma exp_power_int:\n  fixes  x :: \"'a::{real_normed_field,banach}\"\n  shows \"exp x powi n = exp (of_int n * x)\"\nproof (cases \"n \\<ge> 0\")\n  case True\n  have \"exp x powi n = exp x ^ nat n\"\n    using True by (simp add: power_int_def)\n  thus ?thesis\n    using True by (subst (asm) exp_of_nat_mult [symmetric]) auto\nnext\n  case False\n  have \"exp x powi n = inverse (exp x ^ nat (-n))\"\n    using False by (simp add: power_int_def field_simps)\n  also have \"exp x ^ nat (-n) = exp (of_nat (nat (-n)) * x)\"\n    using False by (subst exp_of_nat_mult) auto\n  also have \"inverse \\<dots> = exp (-(of_nat (nat (-n)) * x))\"\n    by (subst exp_minus) (auto simp: field_simps)\n  also have \"-(of_nat (nat (-n)) * x) = of_int n * x\"\n    using False by simp\n  finally show ?thesis .\nqed\n\n\nsubsubsection \\<open>Properties of the Exponential Function on Reals\\<close>\n\ntext \\<open>Comparisons of \\<^term>\\<open>exp x\\<close> with zero.\\<close>\n\ntext \\<open>Proof: because every exponential can be seen as a square.\\<close>\nlemma exp_ge_zero [simp]: \"0 \\<le> exp x\"\n  for x :: real\nproof -\n  have \"0 \\<le> exp (x/2) * exp (x/2)\"\n    by simp\n  then show ?thesis\n    by (simp add: exp_add [symmetric])\nqed\n\nlemma exp_gt_zero [simp]: \"0 < exp x\"\n  for x :: real\n  by (simp add: order_less_le)\n\nlemma not_exp_less_zero [simp]: \"\\<not> exp x < 0\"\n  for x :: real\n  by (simp add: not_less)\n\nlemma not_exp_le_zero [simp]: \"\\<not> exp x \\<le> 0\"\n  for x :: real\n  by (simp add: not_le)\n\nlemma abs_exp_cancel [simp]: \"\\<bar>exp x\\<bar> = exp x\"\n  for x :: real\n  by simp\n\ntext \\<open>Strict monotonicity of exponential.\\<close>\n\nlemma exp_ge_add_one_self_aux:\n  fixes x :: real\n  assumes \"0 \\<le> x\"\n  shows \"1 + x \\<le> exp x\"\n  using order_le_imp_less_or_eq [OF assms]\nproof\n  assume \"0 < x\"\n  have \"1 + x \\<le> (\\<Sum>n<2. inverse (fact n) * x^n)\"\n    by (auto simp: numeral_2_eq_2)\n  also have \"\\<dots> \\<le> (\\<Sum>n. inverse (fact n) * x^n)\"\n    using \\<open>0 < x\\<close> by (auto  simp add: zero_le_mult_iff intro: sum_le_suminf [OF summable_exp])\n  finally show \"1 + x \\<le> exp x\"\n    by (simp add: exp_def)\nqed auto\n\nlemma exp_gt_one: \"0 < x \\<Longrightarrow> 1 < exp x\"\n  for x :: real\nproof -\n  assume x: \"0 < x\"\n  then have \"1 < 1 + x\" by simp\n  also from x have \"1 + x \\<le> exp x\"\n    by (simp add: exp_ge_add_one_self_aux)\n  finally show ?thesis .\nqed\n\nlemma exp_less_mono:\n  fixes x y :: real\n  assumes \"x < y\"\n  shows \"exp x < exp y\"\nproof -\n  from \\<open>x < y\\<close> have \"0 < y - x\" by simp\n  then have \"1 < exp (y - x)\" by (rule exp_gt_one)\n  then have \"1 < exp y / exp x\" by (simp only: exp_diff)\n  then show \"exp x < exp y\" by simp\nqed\n\nlemma exp_less_cancel: \"exp x < exp y \\<Longrightarrow> x < y\"\n  for x y :: real\n  unfolding linorder_not_le [symmetric]\n  by (auto simp: order_le_less exp_less_mono)\n\nlemma exp_less_cancel_iff [iff]: \"exp x < exp y \\<longleftrightarrow> x < y\"\n  for x y :: real\n  by (auto intro: exp_less_mono exp_less_cancel)\n\nlemma exp_le_cancel_iff [iff]: \"exp x \\<le> exp y \\<longleftrightarrow> x \\<le> y\"\n  for x y :: real\n  by (auto simp: linorder_not_less [symmetric])\n\nlemma exp_inj_iff [iff]: \"exp x = exp y \\<longleftrightarrow> x = y\"\n  for x y :: real\n  by (simp add: order_eq_iff)\n\ntext \\<open>Comparisons of \\<^term>\\<open>exp x\\<close> with one.\\<close>\n\nlemma one_less_exp_iff [simp]: \"1 < exp x \\<longleftrightarrow> 0 < x\"\n  for x :: real\n  using exp_less_cancel_iff [where x = 0 and y = x] by simp\n\nlemma exp_less_one_iff [simp]: \"exp x < 1 \\<longleftrightarrow> x < 0\"\n  for x :: real\n  using exp_less_cancel_iff [where x = x and y = 0] by simp\n\nlemma one_le_exp_iff [simp]: \"1 \\<le> exp x \\<longleftrightarrow> 0 \\<le> x\"\n  for x :: real\n  using exp_le_cancel_iff [where x = 0 and y = x] by simp\n\nlemma exp_le_one_iff [simp]: \"exp x \\<le> 1 \\<longleftrightarrow> x \\<le> 0\"\n  for x :: real\n  using exp_le_cancel_iff [where x = x and y = 0] by simp\n\nlemma exp_eq_one_iff [simp]: \"exp x = 1 \\<longleftrightarrow> x = 0\"\n  for x :: real\n  using exp_inj_iff [where x = x and y = 0] by simp\n\nlemma lemma_exp_total: \"1 \\<le> y \\<Longrightarrow> \\<exists>x. 0 \\<le> x \\<and> x \\<le> y - 1 \\<and> exp x = y\"\n  for y :: real\nproof (rule IVT)\n  assume \"1 \\<le> y\"\n  then have \"0 \\<le> y - 1\" by simp\n  then have \"1 + (y - 1) \\<le> exp (y - 1)\"\n    by (rule exp_ge_add_one_self_aux)\n  then show \"y \\<le> exp (y - 1)\" by simp\nqed (simp_all add: le_diff_eq)\n\nlemma exp_total: \"0 < y \\<Longrightarrow> \\<exists>x. exp x = y\"\n  for y :: real\nproof (rule linorder_le_cases [of 1 y])\n  assume \"1 \\<le> y\"\n  then show \"\\<exists>x. exp x = y\"\n    by (fast dest: lemma_exp_total)\nnext\n  assume \"0 < y\" and \"y \\<le> 1\"\n  then have \"1 \\<le> inverse y\"\n    by (simp add: one_le_inverse_iff)\n  then obtain x where \"exp x = inverse y\"\n    by (fast dest: lemma_exp_total)\n  then have \"exp (- x) = y\"\n    by (simp add: exp_minus)\n  then show \"\\<exists>x. exp x = y\" ..\nqed\n\n\nsubsection \\<open>Natural Logarithm\\<close>\n\nclass ln = real_normed_algebra_1 + banach +\n  fixes ln :: \"'a \\<Rightarrow> 'a\"\n  assumes ln_one [simp]: \"ln 1 = 0\"\n\ndefinition powr :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a::ln\"  (infixr \"powr\" 80)\n  \\<comment> \\<open>exponentation via ln and exp\\<close>\n  where \"x powr a \\<equiv> if x = 0 then 0 else exp (a * ln x)\"\n\nlemma powr_0 [simp]: \"0 powr z = 0\"\n  by (simp add: powr_def)\n\n\ninstantiation real :: ln\nbegin\n\ndefinition ln_real :: \"real \\<Rightarrow> real\"\n  where \"ln_real x = (THE u. exp u = x)\"\n\ninstance\n  by intro_classes (simp add: ln_real_def)\n\nend\n\nlemma powr_eq_0_iff [simp]: \"w powr z = 0 \\<longleftrightarrow> w = 0\"\n  by (simp add: powr_def)\n\nlemma ln_exp [simp]: \"ln (exp x) = x\"\n  for x :: real\n  by (simp add: ln_real_def)\n\nlemma exp_ln [simp]: \"0 < x \\<Longrightarrow> exp (ln x) = x\"\n  for x :: real\n  by (auto dest: exp_total)\n\nlemma exp_ln_iff [simp]: \"exp (ln x) = x \\<longleftrightarrow> 0 < x\"\n  for x :: real\n  by (metis exp_gt_zero exp_ln)\n\nlemma ln_unique: \"exp y = x \\<Longrightarrow> ln x = y\"\n  for x :: real\n  by (erule subst) (rule ln_exp)\n\nlemma ln_mult: \"0 < x \\<Longrightarrow> 0 < y \\<Longrightarrow> ln (x * y) = ln x + ln y\"\n  for x :: real\n  by (rule ln_unique) (simp add: exp_add)\n\nlemma ln_prod: \"finite I \\<Longrightarrow> (\\<And>i. i \\<in> I \\<Longrightarrow> f i > 0) \\<Longrightarrow> ln (prod f I) = sum (\\<lambda>x. ln(f x)) I\"\n  for f :: \"'a \\<Rightarrow> real\"\n  by (induct I rule: finite_induct) (auto simp: ln_mult prod_pos)\n\nlemma ln_inverse: \"0 < x \\<Longrightarrow> ln (inverse x) = - ln x\"\n  for x :: real\n  by (rule ln_unique) (simp add: exp_minus)\n\nlemma ln_div: \"0 < x \\<Longrightarrow> 0 < y \\<Longrightarrow> ln (x / y) = ln x - ln y\"\n  for x :: real\n  by (rule ln_unique) (simp add: exp_diff)\n\nlemma ln_realpow: \"0 < x \\<Longrightarrow> ln (x^n) = real n * ln x\"\n  by (rule ln_unique) (simp add: exp_of_nat_mult)\n\nlemma ln_less_cancel_iff [simp]: \"0 < x \\<Longrightarrow> 0 < y \\<Longrightarrow> ln x < ln y \\<longleftrightarrow> x < y\"\n  for x :: real\n  by (subst exp_less_cancel_iff [symmetric]) simp\n\nlemma ln_le_cancel_iff [simp]: \"0 < x \\<Longrightarrow> 0 < y \\<Longrightarrow> ln x \\<le> ln y \\<longleftrightarrow> x \\<le> y\"\n  for x :: real\n  by (simp add: linorder_not_less [symmetric])\n\nlemma ln_inj_iff [simp]: \"0 < x \\<Longrightarrow> 0 < y \\<Longrightarrow> ln x = ln y \\<longleftrightarrow> x = y\"\n  for x :: real\n  by (simp add: order_eq_iff)\n\nlemma ln_add_one_self_le_self: \"0 \\<le> x \\<Longrightarrow> ln (1 + x) \\<le> x\"\n  for x :: real\n  by (rule exp_le_cancel_iff [THEN iffD1]) (simp add: exp_ge_add_one_self_aux)\n\nlemma ln_less_self [simp]: \"0 < x \\<Longrightarrow> ln x < x\"\n  for x :: real\n  by (rule order_less_le_trans [where y = \"ln (1 + x)\"]) (simp_all add: ln_add_one_self_le_self)\n\nlemma ln_ge_iff: \"\\<And>x::real. 0 < x \\<Longrightarrow> y \\<le> ln x \\<longleftrightarrow> exp y \\<le> x\"\n  using exp_le_cancel_iff exp_total by force\n\nlemma ln_ge_zero [simp]: \"1 \\<le> x \\<Longrightarrow> 0 \\<le> ln x\"\n  for x :: real\n  using ln_le_cancel_iff [of 1 x] by simp\n\nlemma ln_ge_zero_imp_ge_one: \"0 \\<le> ln x \\<Longrightarrow> 0 < x \\<Longrightarrow> 1 \\<le> x\"\n  for x :: real\n  using ln_le_cancel_iff [of 1 x] by simp\n\nlemma ln_ge_zero_iff [simp]: \"0 < x \\<Longrightarrow> 0 \\<le> ln x \\<longleftrightarrow> 1 \\<le> x\"\n  for x :: real\n  using ln_le_cancel_iff [of 1 x] by simp\n\nlemma ln_less_zero_iff [simp]: \"0 < x \\<Longrightarrow> ln x < 0 \\<longleftrightarrow> x < 1\"\n  for x :: real\n  using ln_less_cancel_iff [of x 1] by simp\n\nlemma ln_le_zero_iff [simp]: \"0 < x \\<Longrightarrow> ln x \\<le> 0 \\<longleftrightarrow> x \\<le> 1\"\n  for x :: real\n  by (metis less_numeral_extra(1) ln_le_cancel_iff ln_one)\n\nlemma ln_gt_zero: \"1 < x \\<Longrightarrow> 0 < ln x\"\n  for x :: real\n  using ln_less_cancel_iff [of 1 x] by simp\n\nlemma ln_gt_zero_imp_gt_one: \"0 < ln x \\<Longrightarrow> 0 < x \\<Longrightarrow> 1 < x\"\n  for x :: real\n  using ln_less_cancel_iff [of 1 x] by simp\n\nlemma ln_gt_zero_iff [simp]: \"0 < x \\<Longrightarrow> 0 < ln x \\<longleftrightarrow> 1 < x\"\n  for x :: real\n  using ln_less_cancel_iff [of 1 x] by simp\n\nlemma ln_eq_zero_iff [simp]: \"0 < x \\<Longrightarrow> ln x = 0 \\<longleftrightarrow> x = 1\"\n  for x :: real\n  using ln_inj_iff [of x 1] by simp\n\nlemma ln_less_zero: \"0 < x \\<Longrightarrow> x < 1 \\<Longrightarrow> ln x < 0\"\n  for x :: real\n  by simp\n\nlemma ln_neg_is_const: \"x \\<le> 0 \\<Longrightarrow> ln x = (THE x. False)\"\n  for x :: real\n  by (auto simp: ln_real_def intro!: arg_cong[where f = The])\n\nlemma powr_eq_one_iff [simp]:\n  \"a powr x = 1 \\<longleftrightarrow> x = 0\" if \"a > 1\" for a x :: real\n  using that by (auto simp: powr_def split: if_splits)\n\nlemma isCont_ln:\n  fixes x :: real\n  assumes \"x \\<noteq> 0\"\n  shows \"isCont ln x\"\nproof (cases \"0 < x\")\n  case True\n  then have \"isCont ln (exp (ln x))\"\n    by (intro isCont_inverse_function[where d = \"\\<bar>x\\<bar>\" and f = exp]) auto\n  with True show ?thesis\n    by simp\nnext\n  case False\n  with \\<open>x \\<noteq> 0\\<close> show \"isCont ln x\"\n    unfolding isCont_def\n    by (subst filterlim_cong[OF _ refl, of _ \"nhds (ln 0)\" _ \"\\<lambda>_. ln 0\"])\n       (auto simp: ln_neg_is_const not_less eventually_at dist_real_def\n         intro!: exI[of _ \"\\<bar>x\\<bar>\"])\nqed\n\nlemma tendsto_ln [tendsto_intros]: \"(f \\<longlongrightarrow> a) F \\<Longrightarrow> a \\<noteq> 0 \\<Longrightarrow> ((\\<lambda>x. ln (f x)) \\<longlongrightarrow> ln a) F\"\n  for a :: real\n  by (rule isCont_tendsto_compose [OF isCont_ln])\n\nlemma continuous_ln:\n  \"continuous F f \\<Longrightarrow> f (Lim F (\\<lambda>x. x)) \\<noteq> 0 \\<Longrightarrow> continuous F (\\<lambda>x. ln (f x :: real))\"\n  unfolding continuous_def by (rule tendsto_ln)\n\nlemma isCont_ln' [continuous_intros]:\n  \"continuous (at x) f \\<Longrightarrow> f x \\<noteq> 0 \\<Longrightarrow> continuous (at x) (\\<lambda>x. ln (f x :: real))\"\n  unfolding continuous_at by (rule tendsto_ln)\n\nlemma continuous_within_ln [continuous_intros]:\n  \"continuous (at x within s) f \\<Longrightarrow> f x \\<noteq> 0 \\<Longrightarrow> continuous (at x within s) (\\<lambda>x. ln (f x :: real))\"\n  unfolding continuous_within by (rule tendsto_ln)\n\nlemma continuous_on_ln [continuous_intros]:\n  \"continuous_on s f \\<Longrightarrow> (\\<forall>x\\<in>s. f x \\<noteq> 0) \\<Longrightarrow> continuous_on s (\\<lambda>x. ln (f x :: real))\"\n  unfolding continuous_on_def by (auto intro: tendsto_ln)\n\nlemma DERIV_ln: \"0 < x \\<Longrightarrow> DERIV ln x :> inverse x\"\n  for x :: real\n  by (rule DERIV_inverse_function [where f=exp and a=0 and b=\"x+1\"])\n    (auto intro: DERIV_cong [OF DERIV_exp exp_ln] isCont_ln)\n\nlemma DERIV_ln_divide: \"0 < x \\<Longrightarrow> DERIV ln x :> 1 / x\"\n  for x :: real\n  by (rule DERIV_ln[THEN DERIV_cong]) (simp_all add: divide_inverse)\n\ndeclare DERIV_ln_divide[THEN DERIV_chain2, derivative_intros]\n  and DERIV_ln_divide[THEN DERIV_chain2, unfolded has_field_derivative_def, derivative_intros]\n\nlemmas has_derivative_ln[derivative_intros] = DERIV_ln[THEN DERIV_compose_FDERIV]\n\nlemma ln_series:\n  assumes \"0 < x\" and \"x < 2\"\n  shows \"ln x = (\\<Sum> n. (-1)^n * (1 / real (n + 1)) * (x - 1)^(Suc n))\"\n    (is \"ln x = suminf (?f (x - 1))\")\nproof -\n  let ?f' = \"\\<lambda>x n. (-1)^n * (x - 1)^n\"\n\n  have \"ln x - suminf (?f (x - 1)) = ln 1 - suminf (?f (1 - 1))\"\n  proof (rule DERIV_isconst3 [where x = x])\n    fix x :: real\n    assume \"x \\<in> {0 <..< 2}\"\n    then have \"0 < x\" and \"x < 2\" by auto\n    have \"norm (1 - x) < 1\"\n      using \\<open>0 < x\\<close> and \\<open>x < 2\\<close> by auto\n    have \"1 / x = 1 / (1 - (1 - x))\" by auto\n    also have \"\\<dots> = (\\<Sum> n. (1 - x)^n)\"\n      using geometric_sums[OF \\<open>norm (1 - x) < 1\\<close>] by (rule sums_unique)\n    also have \"\\<dots> = suminf (?f' x)\"\n      unfolding power_mult_distrib[symmetric]\n      by (rule arg_cong[where f=suminf], rule arg_cong[where f=\"(^)\"], auto)\n    finally have \"DERIV ln x :> suminf (?f' x)\"\n      using DERIV_ln[OF \\<open>0 < x\\<close>] unfolding divide_inverse by auto\n    moreover\n    have repos: \"\\<And> h x :: real. h - 1 + x = h + x - 1\" by auto\n    have \"DERIV (\\<lambda>x. suminf (?f x)) (x - 1) :>\n      (\\<Sum>n. (-1)^n * (1 / real (n + 1)) * real (Suc n) * (x - 1) ^ n)\"\n    proof (rule DERIV_power_series')\n      show \"x - 1 \\<in> {- 1<..<1}\" and \"(0 :: real) < 1\"\n        using \\<open>0 < x\\<close> \\<open>x < 2\\<close> by auto\n    next\n      fix x :: real\n      assume \"x \\<in> {- 1<..<1}\"\n      then show \"summable (\\<lambda>n. (- 1) ^ n * (1 / real (n + 1)) * real (Suc n) * x^n)\"\n        by (simp add: abs_if flip: power_mult_distrib)\n    qed\n    then have \"DERIV (\\<lambda>x. suminf (?f x)) (x - 1) :> suminf (?f' x)\"\n      unfolding One_nat_def by auto\n    then have \"DERIV (\\<lambda>x. suminf (?f (x - 1))) x :> suminf (?f' x)\"\n      unfolding DERIV_def repos .\n    ultimately have \"DERIV (\\<lambda>x. ln x - suminf (?f (x - 1))) x :> suminf (?f' x) - suminf (?f' x)\"\n      by (rule DERIV_diff)\n    then show \"DERIV (\\<lambda>x. ln x - suminf (?f (x - 1))) x :> 0\" by auto\n  qed (auto simp: assms)\n  then show ?thesis by auto\nqed\n\nlemma exp_first_terms:\n  fixes x :: \"'a::{real_normed_algebra_1,banach}\"\n  shows \"exp x = (\\<Sum>n<k. inverse(fact n) *\\<^sub>R (x ^ n)) + (\\<Sum>n. inverse(fact (n + k)) *\\<^sub>R (x ^ (n + k)))\"\nproof -\n  have \"exp x = suminf (\\<lambda>n. inverse(fact n) *\\<^sub>R (x^n))\"\n    by (simp add: exp_def)\n  also from summable_exp_generic have \"\\<dots> = (\\<Sum> n. inverse(fact(n+k)) *\\<^sub>R (x ^ (n + k))) +\n    (\\<Sum> n::nat<k. inverse(fact n) *\\<^sub>R (x^n))\" (is \"_ = _ + ?a\")\n    by (rule suminf_split_initial_segment)\n  finally show ?thesis by simp\nqed\n\nlemma exp_first_term: \"exp x = 1 + (\\<Sum>n. inverse (fact (Suc n)) *\\<^sub>R (x ^ Suc n))\"\n  for x :: \"'a::{real_normed_algebra_1,banach}\"\n  using exp_first_terms[of x 1] by simp\n\nlemma exp_first_two_terms: \"exp x = 1 + x + (\\<Sum>n. inverse (fact (n + 2)) *\\<^sub>R (x ^ (n + 2)))\"\n  for x :: \"'a::{real_normed_algebra_1,banach}\"\n  using exp_first_terms[of x 2] by (simp add: eval_nat_numeral)\n\nlemma exp_bound:\n  fixes x :: real\n  assumes a: \"0 \\<le> x\"\n    and b: \"x \\<le> 1\"\n  shows \"exp x \\<le> 1 + x + x\\<^sup>2\"\nproof -\n  have \"suminf (\\<lambda>n. inverse(fact (n+2)) * (x ^ (n + 2))) \\<le> x\\<^sup>2\"\n  proof -\n    have \"(\\<lambda>n. x\\<^sup>2 / 2 * (1/2) ^ n) sums (x\\<^sup>2 / 2 * (1 / (1 - 1/2)))\"\n      by (intro sums_mult geometric_sums) simp\n    then have sumsx: \"(\\<lambda>n. x\\<^sup>2 / 2 * (1/2) ^ n) sums x\\<^sup>2\"\n      by simp\n    have \"suminf (\\<lambda>n. inverse(fact (n+2)) * (x ^ (n + 2))) \\<le> suminf (\\<lambda>n. (x\\<^sup>2/2) * ((1/2)^n))\"\n    proof (intro suminf_le allI)\n      show \"inverse (fact (n + 2)) * x ^ (n + 2) \\<le> (x\\<^sup>2/2) * ((1/2)^n)\" for n :: nat\n      proof -\n        have \"(2::nat) * 2 ^ n \\<le> fact (n + 2)\"\n          by (induct n) simp_all\n        then have \"real ((2::nat) * 2 ^ n) \\<le> real_of_nat (fact (n + 2))\"\n          by (simp only: of_nat_le_iff)\n        then have \"((2::real) * 2 ^ n) \\<le> fact (n + 2)\"\n          unfolding of_nat_fact by simp\n        then have \"inverse (fact (n + 2)) \\<le> inverse ((2::real) * 2 ^ n)\"\n          by (rule le_imp_inverse_le) simp\n        then have \"inverse (fact (n + 2)) \\<le> 1/(2::real) * (1/2)^n\"\n          by (simp add: power_inverse [symmetric])\n        then have \"inverse (fact (n + 2)) * (x^n * x\\<^sup>2) \\<le> 1/2 * (1/2)^n * (1 * x\\<^sup>2)\"\n          by (rule mult_mono) (rule mult_mono, simp_all add: power_le_one a b)\n        then show ?thesis\n          unfolding power_add by (simp add: ac_simps del: fact_Suc)\n      qed\n      show \"summable (\\<lambda>n. inverse (fact (n + 2)) * x ^ (n + 2))\"\n        by (rule summable_exp [THEN summable_ignore_initial_segment])\n      show \"summable (\\<lambda>n. x\\<^sup>2 / 2 * (1/2) ^ n)\"\n        by (rule sums_summable [OF sumsx])\n    qed\n    also have \"\\<dots> = x\\<^sup>2\"\n      by (rule sums_unique [THEN sym]) (rule sumsx)\n    finally show ?thesis .\n  qed\n  then show ?thesis\n    unfolding exp_first_two_terms by auto\nqed\n\ncorollary exp_half_le2: \"exp(1/2) \\<le> (2::real)\"\n  using exp_bound [of \"1/2\"]\n  by (simp add: field_simps)\n\ncorollary exp_le: \"exp 1 \\<le> (3::real)\"\n  using exp_bound [of 1]\n  by (simp add: field_simps)\n\nlemma exp_bound_half: \"norm z \\<le> 1/2 \\<Longrightarrow> norm (exp z) \\<le> 2\"\n  by (blast intro: order_trans intro!: exp_half_le2 norm_exp)\n\nlemma exp_bound_lemma:\n  assumes \"norm z \\<le> 1/2\"\n  shows \"norm (exp z) \\<le> 1 + 2 * norm z\"\nproof -\n  have *: \"(norm z)\\<^sup>2 \\<le> norm z * 1\"\n    unfolding power2_eq_square\n    by (rule mult_left_mono) (use assms in auto)\n  have \"norm (exp z) \\<le> exp (norm z)\"\n    by (rule norm_exp)\n  also have \"\\<dots> \\<le> 1 + (norm z) + (norm z)\\<^sup>2\"\n    using assms exp_bound by auto\n  also have \"\\<dots> \\<le> 1 + 2 * norm z\"\n    using * by auto\n  finally show ?thesis .\nqed\n\nlemma real_exp_bound_lemma: \"0 \\<le> x \\<Longrightarrow> x \\<le> 1/2 \\<Longrightarrow> exp x \\<le> 1 + 2 * x\"\n  for x :: real\n  using exp_bound_lemma [of x] by simp\n\nlemma ln_one_minus_pos_upper_bound:\n  fixes x :: real\n  assumes a: \"0 \\<le> x\" and b: \"x < 1\"\n  shows \"ln (1 - x) \\<le> - x\"\nproof -\n  have \"(1 - x) * (1 + x + x\\<^sup>2) = 1 - x^3\"\n    by (simp add: algebra_simps power2_eq_square power3_eq_cube)\n  also have \"\\<dots> \\<le> 1\"\n    by (auto simp: a)\n  finally have \"(1 - x) * (1 + x + x\\<^sup>2) \\<le> 1\" .\n  moreover have c: \"0 < 1 + x + x\\<^sup>2\"\n    by (simp add: add_pos_nonneg a)\n  ultimately have \"1 - x \\<le> 1 / (1 + x + x\\<^sup>2)\"\n    by (elim mult_imp_le_div_pos)\n  also have \"\\<dots> \\<le> 1 / exp x\"\n    by (metis a abs_one b exp_bound exp_gt_zero frac_le less_eq_real_def real_sqrt_abs\n        real_sqrt_pow2_iff real_sqrt_power)\n  also have \"\\<dots> = exp (- x)\"\n    by (auto simp: exp_minus divide_inverse)\n  finally have \"1 - x \\<le> exp (- x)\" .\n  also have \"1 - x = exp (ln (1 - x))\"\n    by (metis b diff_0 exp_ln_iff less_iff_diff_less_0 minus_diff_eq)\n  finally have \"exp (ln (1 - x)) \\<le> exp (- x)\" .\n  then show ?thesis\n    by (auto simp only: exp_le_cancel_iff)\nqed\n\nlemma exp_ge_add_one_self [simp]: \"1 + x \\<le> exp x\"\n  for x :: real\nproof (cases \"0 \\<le> x \\<or> x \\<le> -1\")\n  case True\n  then show ?thesis\n    by (meson exp_ge_add_one_self_aux exp_ge_zero order.trans real_add_le_0_iff)\nnext\n  case False\n  then have ln1: \"ln (1 + x) \\<le> x\"\n    using ln_one_minus_pos_upper_bound [of \"-x\"] by simp\n  have \"1 + x = exp (ln (1 + x))\"\n    using False by auto\n  also have \"\\<dots> \\<le> exp x\"\n    by (simp add: ln1)\n  finally show ?thesis .\nqed\n\nlemma ln_one_plus_pos_lower_bound:\n  fixes x :: real\n  assumes a: \"0 \\<le> x\" and b: \"x \\<le> 1\"\n  shows \"x - x\\<^sup>2 \\<le> ln (1 + x)\"\nproof -\n  have \"exp (x - x\\<^sup>2) = exp x / exp (x\\<^sup>2)\"\n    by (rule exp_diff)\n  also have \"\\<dots> \\<le> (1 + x + x\\<^sup>2) / exp (x \\<^sup>2)\"\n    by (metis a b divide_right_mono exp_bound exp_ge_zero)\n  also have \"\\<dots> \\<le> (1 + x + x\\<^sup>2) / (1 + x\\<^sup>2)\"\n    by (simp add: a divide_left_mono add_pos_nonneg)\n  also from a have \"\\<dots> \\<le> 1 + x\"\n    by (simp add: field_simps add_strict_increasing zero_le_mult_iff)\n  finally have \"exp (x - x\\<^sup>2) \\<le> 1 + x\" .\n  also have \"\\<dots> = exp (ln (1 + x))\"\n  proof -\n    from a have \"0 < 1 + x\" by auto\n    then show ?thesis\n      by (auto simp only: exp_ln_iff [THEN sym])\n  qed\n  finally have \"exp (x - x\\<^sup>2) \\<le> exp (ln (1 + x))\" .\n  then show ?thesis\n    by (metis exp_le_cancel_iff)\nqed\n\nlemma ln_one_minus_pos_lower_bound:\n  fixes x :: real\n  assumes a: \"0 \\<le> x\" and b: \"x \\<le> 1/2\"\n  shows \"- x - 2 * x\\<^sup>2 \\<le> ln (1 - x)\"\nproof -\n  from b have c: \"x < 1\" by auto\n  then have \"ln (1 - x) = - ln (1 + x / (1 - x))\"\n    by (auto simp: ln_inverse [symmetric] field_simps intro: arg_cong [where f=ln])\n  also have \"- (x / (1 - x)) \\<le> \\<dots>\"\n  proof -\n    have \"ln (1 + x / (1 - x)) \\<le> x / (1 - x)\"\n      using a c by (intro ln_add_one_self_le_self) auto\n    then show ?thesis\n      by auto\n  qed\n  also have \"- (x / (1 - x)) = - x / (1 - x)\"\n    by auto\n  finally have d: \"- x / (1 - x) \\<le> ln (1 - x)\" .\n  have \"0 < 1 - x\" using a b by simp\n  then have e: \"- x - 2 * x\\<^sup>2 \\<le> - x / (1 - x)\"\n    using mult_right_le_one_le[of \"x * x\" \"2 * x\"] a b\n    by (simp add: field_simps power2_eq_square)\n  from e d show \"- x - 2 * x\\<^sup>2 \\<le> ln (1 - x)\"\n    by (rule order_trans)\nqed\n\nlemma ln_add_one_self_le_self2:\n  fixes x :: real\n  shows \"-1 < x \\<Longrightarrow> ln (1 + x) \\<le> x\"\n  by (metis diff_gt_0_iff_gt diff_minus_eq_add exp_ge_add_one_self exp_le_cancel_iff exp_ln minus_less_iff)\n\nlemma abs_ln_one_plus_x_minus_x_bound_nonneg:\n  fixes x :: real\n  assumes x: \"0 \\<le> x\" and x1: \"x \\<le> 1\"\n  shows \"\\<bar>ln (1 + x) - x\\<bar> \\<le> x\\<^sup>2\"\nproof -\n  from x have \"ln (1 + x) \\<le> x\"\n    by (rule ln_add_one_self_le_self)\n  then have \"ln (1 + x) - x \\<le> 0\"\n    by simp\n  then have \"\\<bar>ln(1 + x) - x\\<bar> = - (ln(1 + x) - x)\"\n    by (rule abs_of_nonpos)\n  also have \"\\<dots> = x - ln (1 + x)\"\n    by simp\n  also have \"\\<dots> \\<le> x\\<^sup>2\"\n  proof -\n    from x x1 have \"x - x\\<^sup>2 \\<le> ln (1 + x)\"\n      by (intro ln_one_plus_pos_lower_bound)\n    then show ?thesis\n      by simp\n  qed\n  finally show ?thesis .\nqed\n\nlemma abs_ln_one_plus_x_minus_x_bound_nonpos:\n  fixes x :: real\n  assumes a: \"-(1/2) \\<le> x\" and b: \"x \\<le> 0\"\n  shows \"\\<bar>ln (1 + x) - x\\<bar> \\<le> 2 * x\\<^sup>2\"\nproof -\n  have *: \"- (-x) - 2 * (-x)\\<^sup>2 \\<le> ln (1 - (- x))\"\n    by (metis a b diff_zero ln_one_minus_pos_lower_bound minus_diff_eq neg_le_iff_le) \n  have \"\\<bar>ln (1 + x) - x\\<bar> = x - ln (1 - (- x))\"\n    using a ln_add_one_self_le_self2 [of x] by (simp add: abs_if)\n  also have \"\\<dots> \\<le> 2 * x\\<^sup>2\"\n    using * by (simp add: algebra_simps)\n  finally show ?thesis .\nqed\n\nlemma abs_ln_one_plus_x_minus_x_bound:\n  fixes x :: real\n  assumes \"\\<bar>x\\<bar> \\<le> 1/2\"\n  shows \"\\<bar>ln (1 + x) - x\\<bar> \\<le> 2 * x\\<^sup>2\"\nproof (cases \"0 \\<le> x\")\n  case True\n  then show ?thesis\n    using abs_ln_one_plus_x_minus_x_bound_nonneg assms by fastforce\nnext\n  case False\n  then show ?thesis\n    using abs_ln_one_plus_x_minus_x_bound_nonpos assms by auto\nqed\n\nlemma ln_x_over_x_mono:\n  fixes x :: real\n  assumes x: \"exp 1 \\<le> x\" \"x \\<le> y\"\n  shows \"ln y / y \\<le> ln x / x\"\nproof -\n  note x\n  moreover have \"0 < exp (1::real)\" by simp\n  ultimately have a: \"0 < x\" and b: \"0 < y\"\n    by (fast intro: less_le_trans order_trans)+\n  have \"x * ln y - x * ln x = x * (ln y - ln x)\"\n    by (simp add: algebra_simps)\n  also have \"\\<dots> = x * ln (y / x)\"\n    by (simp only: ln_div a b)\n  also have \"y / x = (x + (y - x)) / x\"\n    by simp\n  also have \"\\<dots> = 1 + (y - x) / x\"\n    using x a by (simp add: field_simps)\n  also have \"x * ln (1 + (y - x) / x) \\<le> x * ((y - x) / x)\"\n    using x a\n    by (intro mult_left_mono ln_add_one_self_le_self) simp_all\n  also have \"\\<dots> = y - x\"\n    using a by simp\n  also have \"\\<dots> = (y - x) * ln (exp 1)\" by simp\n  also have \"\\<dots> \\<le> (y - x) * ln x\"\n    using a x exp_total of_nat_1 x(1)  by (fastforce intro: mult_left_mono)\n  also have \"\\<dots> = y * ln x - x * ln x\"\n    by (rule left_diff_distrib)\n  finally have \"x * ln y \\<le> y * ln x\"\n    by arith\n  then have \"ln y \\<le> (y * ln x) / x\"\n    using a by (simp add: field_simps)\n  also have \"\\<dots> = y * (ln x / x)\" by simp\n  finally show ?thesis\n    using b by (simp add: field_simps)\nqed\n\nlemma ln_le_minus_one: \"0 < x \\<Longrightarrow> ln x \\<le> x - 1\"\n  for x :: real\n  using exp_ge_add_one_self[of \"ln x\"] by simp\n\ncorollary ln_diff_le: \"0 < x \\<Longrightarrow> 0 < y \\<Longrightarrow> ln x - ln y \\<le> (x - y) / y\"\n  for x :: real\n  by (simp add: ln_div [symmetric] diff_divide_distrib ln_le_minus_one)\n\nlemma ln_eq_minus_one:\n  fixes x :: real\n  assumes \"0 < x\" \"ln x = x - 1\"\n  shows \"x = 1\"\nproof -\n  let ?l = \"\\<lambda>y. ln y - y + 1\"\n  have D: \"\\<And>x::real. 0 < x \\<Longrightarrow> DERIV ?l x :> (1 / x - 1)\"\n    by (auto intro!: derivative_eq_intros)\n\n  show ?thesis\n  proof (cases rule: linorder_cases)\n    assume \"x < 1\"\n    from dense[OF \\<open>x < 1\\<close>] obtain a where \"x < a\" \"a < 1\" by blast\n    from \\<open>x < a\\<close> have \"?l x < ?l a\"\n    proof (rule DERIV_pos_imp_increasing)\n      fix y\n      assume \"x \\<le> y\" \"y \\<le> a\"\n      with \\<open>0 < x\\<close> \\<open>a < 1\\<close> have \"0 < 1 / y - 1\" \"0 < y\"\n        by (auto simp: field_simps)\n      with D show \"\\<exists>z. DERIV ?l y :> z \\<and> 0 < z\" by blast\n    qed\n    also have \"\\<dots> \\<le> 0\"\n      using ln_le_minus_one \\<open>0 < x\\<close> \\<open>x < a\\<close> by (auto simp: field_simps)\n    finally show \"x = 1\" using assms by auto\n  next\n    assume \"1 < x\"\n    from dense[OF this] obtain a where \"1 < a\" \"a < x\" by blast\n    from \\<open>a < x\\<close> have \"?l x < ?l a\"\n    proof (rule DERIV_neg_imp_decreasing)\n      fix y\n      assume \"a \\<le> y\" \"y \\<le> x\"\n      with \\<open>1 < a\\<close> have \"1 / y - 1 < 0\" \"0 < y\"\n        by (auto simp: field_simps)\n      with D show \"\\<exists>z. DERIV ?l y :> z \\<and> z < 0\"\n        by blast\n    qed\n    also have \"\\<dots> \\<le> 0\"\n      using ln_le_minus_one \\<open>1 < a\\<close> by (auto simp: field_simps)\n    finally show \"x = 1\" using assms by auto\n  next\n    assume \"x = 1\"\n    then show ?thesis by simp\n  qed\nqed\n\nlemma ln_x_over_x_tendsto_0: \"((\\<lambda>x::real. ln x / x) \\<longlongrightarrow> 0) at_top\"\nproof (rule lhospital_at_top_at_top[where f' = inverse and g' = \"\\<lambda>_. 1\"])\n  from eventually_gt_at_top[of \"0::real\"]\n  show \"\\<forall>\\<^sub>F x in at_top. (ln has_real_derivative inverse x) (at x)\"\n    by eventually_elim (auto intro!: derivative_eq_intros simp: field_simps)\nqed (use tendsto_inverse_0 in\n      \\<open>auto simp: filterlim_ident dest!: tendsto_mono[OF at_top_le_at_infinity]\\<close>)\n\nlemma exp_ge_one_plus_x_over_n_power_n:\n  assumes \"x \\<ge> - real n\" \"n > 0\"\n  shows \"(1 + x / of_nat n) ^ n \\<le> exp x\"\nproof (cases \"x = - of_nat n\")\n  case False\n  from assms False have \"(1 + x / of_nat n) ^ n = exp (of_nat n * ln (1 + x / of_nat n))\"\n    by (subst exp_of_nat_mult, subst exp_ln) (simp_all add: field_simps)\n  also from assms False have \"ln (1 + x / real n) \\<le> x / real n\"\n    by (intro ln_add_one_self_le_self2) (simp_all add: field_simps)\n  with assms have \"exp (of_nat n * ln (1 + x / of_nat n)) \\<le> exp x\"\n    by (simp add: field_simps)\n  finally show ?thesis .\nnext\n  case True\n  then show ?thesis by (simp add: zero_power)\nqed\n\nlemma exp_ge_one_minus_x_over_n_power_n:\n  assumes \"x \\<le> real n\" \"n > 0\"\n  shows \"(1 - x / of_nat n) ^ n \\<le> exp (-x)\"\n  using exp_ge_one_plus_x_over_n_power_n[of n \"-x\"] assms by simp\n\nlemma exp_at_bot: \"(exp \\<longlongrightarrow> (0::real)) at_bot\"\n  unfolding tendsto_Zfun_iff\nproof (rule ZfunI, simp add: eventually_at_bot_dense)\n  fix r :: real\n  assume \"0 < r\"\n  have \"exp x < r\" if \"x < ln r\" for x\n    by (metis \\<open>0 < r\\<close> exp_less_mono exp_ln that)\n  then show \"\\<exists>k. \\<forall>n<k. exp n < r\" by auto\nqed\n\nlemma exp_at_top: \"LIM x at_top. exp 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=ln])\n    (auto intro: eventually_gt_at_top)\n\nlemma lim_exp_minus_1: \"((\\<lambda>z::'a. (exp(z) - 1) / z) \\<longlongrightarrow> 1) (at 0)\"\n  for x :: \"'a::{real_normed_field,banach}\"\nproof -\n  have \"((\\<lambda>z::'a. exp(z) - 1) has_field_derivative 1) (at 0)\"\n    by (intro derivative_eq_intros | simp)+\n  then show ?thesis\n    by (simp add: Deriv.has_field_derivative_iff)\nqed\n\nlemma ln_at_0: \"LIM x at_right 0. ln (x::real) :> at_bot\"\n  by (rule filterlim_at_bot_at_right[where Q=\"\\<lambda>x. 0 < x\" and P=\"\\<lambda>x. True\" and g=exp])\n     (auto simp: eventually_at_filter)\n\nlemma ln_at_top: \"LIM x at_top. ln (x::real) :> at_top\"\n  by (rule filterlim_at_top_at_top[where Q=\"\\<lambda>x. 0 < x\" and P=\"\\<lambda>x. True\" and g=exp])\n     (auto intro: eventually_gt_at_top)\n\nlemma filtermap_ln_at_top: \"filtermap (ln::real \\<Rightarrow> real) at_top = at_top\"\n  by (intro filtermap_fun_inverse[of exp] exp_at_top ln_at_top) auto\n\nlemma filtermap_exp_at_top: \"filtermap (exp::real \\<Rightarrow> real) at_top = at_top\"\n  by (intro filtermap_fun_inverse[of ln] exp_at_top ln_at_top)\n     (auto simp: eventually_at_top_dense)\n\nlemma filtermap_ln_at_right: \"filtermap ln (at_right (0::real)) = at_bot\"\n  by (auto intro!: filtermap_fun_inverse[where g=\"\\<lambda>x. exp x\"] ln_at_0\n      simp: filterlim_at exp_at_bot)\n\nlemma tendsto_power_div_exp_0: \"((\\<lambda>x. x ^ k / exp x) \\<longlongrightarrow> (0::real)) at_top\"\nproof (induct k)\n  case 0\n  show \"((\\<lambda>x. x ^ 0 / exp x) \\<longlongrightarrow> (0::real)) at_top\"\n    by (simp add: inverse_eq_divide[symmetric])\n       (metis filterlim_compose[OF tendsto_inverse_0] exp_at_top filterlim_mono\n         at_top_le_at_infinity order_refl)\nnext\n  case (Suc k)\n  show ?case\n  proof (rule lhospital_at_top_at_top)\n    show \"eventually (\\<lambda>x. DERIV (\\<lambda>x. x ^ Suc k) x :> (real (Suc k) * x^k)) at_top\"\n      by eventually_elim (intro derivative_eq_intros, auto)\n    show \"eventually (\\<lambda>x. DERIV exp x :> exp x) at_top\"\n      by eventually_elim auto\n    show \"eventually (\\<lambda>x. exp x \\<noteq> 0) at_top\"\n      by auto\n    from tendsto_mult[OF tendsto_const Suc, of \"real (Suc k)\"]\n    show \"((\\<lambda>x. real (Suc k) * x ^ k / exp x) \\<longlongrightarrow> 0) at_top\"\n      by simp\n  qed (rule exp_at_top)\nqed\n\nsubsubsection\\<open> A couple of simple bounds\\<close>\n\nlemma exp_plus_inverse_exp:\n  fixes x::real\n  shows \"2 \\<le> exp x + inverse (exp x)\"\nproof -\n  have \"2 \\<le> exp x + exp (-x)\"\n    using exp_ge_add_one_self [of x] exp_ge_add_one_self [of \"-x\"]\n    by linarith\n  then show ?thesis\n    by (simp add: exp_minus)\nqed\n\nlemma real_le_x_sinh:\n  fixes x::real\n  assumes \"0 \\<le> x\"\n  shows \"x \\<le> (exp x - inverse(exp x)) / 2\"\nproof -\n  have *: \"exp a - inverse(exp a) - 2*a \\<le> exp b - inverse(exp b) - 2*b\" if \"a \\<le> b\" for a b::real\n    using exp_plus_inverse_exp\n    by (fastforce intro: derivative_eq_intros DERIV_nonneg_imp_nondecreasing [OF that])\n  show ?thesis\n    using*[OF assms] by simp\nqed\n\nlemma real_le_abs_sinh:\n  fixes x::real\n  shows \"abs x \\<le> abs((exp x - inverse(exp x)) / 2)\"\nproof (cases \"0 \\<le> x\")\n  case True\n  show ?thesis\n    using real_le_x_sinh [OF True] True by (simp add: abs_if)\nnext\n  case False\n  have \"-x \\<le> (exp(-x) - inverse(exp(-x))) / 2\"\n    by (meson False linear neg_le_0_iff_le real_le_x_sinh)\n  also have \"\\<dots> \\<le> \\<bar>(exp x - inverse (exp x)) / 2\\<bar>\"\n    by (metis (no_types, opaque_lifting) abs_divide abs_le_iff abs_minus_cancel\n       add.inverse_inverse exp_minus minus_diff_eq order_refl)\n  finally show ?thesis\n    using False by linarith\nqed\n\nsubsection\\<open>The general logarithm\\<close>\n\ndefinition log :: \"real \\<Rightarrow> real \\<Rightarrow> real\"\n  \\<comment> \\<open>logarithm of \\<^term>\\<open>x\\<close> to base \\<^term>\\<open>a\\<close>\\<close>\n  where \"log a x = ln x / ln a\"\n\nlemma tendsto_log [tendsto_intros]:\n  \"(f \\<longlongrightarrow> a) F \\<Longrightarrow> (g \\<longlongrightarrow> b) F \\<Longrightarrow> 0 < a \\<Longrightarrow> a \\<noteq> 1 \\<Longrightarrow> 0 < b \\<Longrightarrow>\n    ((\\<lambda>x. log (f x) (g x)) \\<longlongrightarrow> log a b) F\"\n  unfolding log_def by (intro tendsto_intros) auto\n\nlemma continuous_log:\n  assumes \"continuous F f\"\n    and \"continuous F g\"\n    and \"0 < f (Lim F (\\<lambda>x. x))\"\n    and \"f (Lim F (\\<lambda>x. x)) \\<noteq> 1\"\n    and \"0 < g (Lim F (\\<lambda>x. x))\"\n  shows \"continuous F (\\<lambda>x. log (f x) (g x))\"\n  using assms unfolding continuous_def by (rule tendsto_log)\n\nlemma continuous_at_within_log[continuous_intros]:\n  assumes \"continuous (at a within s) f\"\n    and \"continuous (at a within s) g\"\n    and \"0 < f a\"\n    and \"f a \\<noteq> 1\"\n    and \"0 < g a\"\n  shows \"continuous (at a within s) (\\<lambda>x. log (f x) (g x))\"\n  using assms unfolding continuous_within by (rule tendsto_log)\n\nlemma isCont_log[continuous_intros, simp]:\n  assumes \"isCont f a\" \"isCont g a\" \"0 < f a\" \"f a \\<noteq> 1\" \"0 < g a\"\n  shows \"isCont (\\<lambda>x. log (f x) (g x)) a\"\n  using assms unfolding continuous_at by (rule tendsto_log)\n\nlemma continuous_on_log[continuous_intros]:\n  assumes \"continuous_on s f\" \"continuous_on s g\"\n    and \"\\<forall>x\\<in>s. 0 < f x\" \"\\<forall>x\\<in>s. f x \\<noteq> 1\" \"\\<forall>x\\<in>s. 0 < g x\"\n  shows \"continuous_on s (\\<lambda>x. log (f x) (g x))\"\n  using assms unfolding continuous_on_def by (fast intro: tendsto_log)\n\nlemma powr_one_eq_one [simp]: \"1 powr a = 1\"\n  by (simp add: powr_def)\n\nlemma powr_zero_eq_one [simp]: \"x powr 0 = (if x = 0 then 0 else 1)\"\n  by (simp add: powr_def)\n\nlemma powr_one_gt_zero_iff [simp]: \"x powr 1 = x \\<longleftrightarrow> 0 \\<le> x\"\n  for x :: real\n  by (auto simp: powr_def)\ndeclare powr_one_gt_zero_iff [THEN iffD2, simp]\n\nlemma powr_diff:\n  fixes w:: \"'a::{ln,real_normed_field}\" shows  \"w powr (z1 - z2) = w powr z1 / w powr z2\"\n  by (simp add: powr_def algebra_simps exp_diff)\n\nlemma powr_mult: \"0 \\<le> x \\<Longrightarrow> 0 \\<le> y \\<Longrightarrow> (x * y) powr a = (x powr a) * (y powr a)\"\n  for a x y :: real\n  by (simp add: powr_def exp_add [symmetric] ln_mult distrib_left)\n\nlemma powr_ge_pzero [simp]: \"0 \\<le> x powr y\"\n  for x y :: real\n  by (simp add: powr_def)\n\nlemma powr_non_neg[simp]: \"\\<not>a powr x < 0\" for a x::real\n  using powr_ge_pzero[of a x] by arith\n\nlemma inverse_powr: \"\\<And>y::real. 0 \\<le> y \\<Longrightarrow> inverse y powr a = inverse (y powr a)\"\n    by (simp add: exp_minus ln_inverse powr_def)\n\nlemma powr_divide: \"\\<lbrakk>0 \\<le> x; 0 \\<le> y\\<rbrakk> \\<Longrightarrow> (x / y) powr a = (x powr a) / (y powr a)\"\n  for a b x :: real\n    by (simp add: divide_inverse powr_mult inverse_powr)\n\nlemma powr_add: \"x powr (a + b) = (x powr a) * (x powr b)\"\n  for a b x :: \"'a::{ln,real_normed_field}\"\n  by (simp add: powr_def exp_add [symmetric] distrib_right)\n\nlemma powr_mult_base: \"0 \\<le> x \\<Longrightarrow>x * x powr y = x powr (1 + y)\"\n  for x :: real\n  by (auto simp: powr_add)\n\nlemma powr_powr: \"(x powr a) powr b = x powr (a * b)\"\n  for a b x :: real\n  by (simp add: powr_def)\n\nlemma powr_powr_swap: \"(x powr a) powr b = (x powr b) powr a\"\n  for a b x :: real\n  by (simp add: powr_powr mult.commute)\n\nlemma powr_minus: \"x powr (- a) = inverse (x powr a)\"\n      for a x :: \"'a::{ln,real_normed_field}\"\n  by (simp add: powr_def exp_minus [symmetric])\n\nlemma powr_minus_divide: \"x powr (- a) = 1/(x powr a)\"\n      for a x :: \"'a::{ln,real_normed_field}\"\n  by (simp add: divide_inverse powr_minus)\n\nlemma powr_sum: \"x \\<noteq> 0 \\<Longrightarrow> finite A \\<Longrightarrow> x powr sum f A = (\\<Prod>y\\<in>A. x powr f y)\"\n  by (simp add: powr_def exp_sum sum_distrib_right)\n\nlemma divide_powr_uminus: \"a / b powr c = a * b powr (- c)\"\n  for a b c :: real\n  by (simp add: powr_minus_divide)\n\nlemma powr_less_mono: \"a < b \\<Longrightarrow> 1 < x \\<Longrightarrow> x powr a < x powr b\"\n  for a b x :: real\n  by (simp add: powr_def)\n\nlemma powr_less_cancel: \"x powr a < x powr b \\<Longrightarrow> 1 < x \\<Longrightarrow> a < b\"\n  for a b x :: real\n  by (simp add: powr_def)\n\nlemma powr_less_cancel_iff [simp]: \"1 < x \\<Longrightarrow> x powr a < x powr b \\<longleftrightarrow> a < b\"\n  for a b x :: real\n  by (blast intro: powr_less_cancel powr_less_mono)\n\nlemma powr_le_cancel_iff [simp]: \"1 < x \\<Longrightarrow> x powr a \\<le> x powr b \\<longleftrightarrow> a \\<le> b\"\n  for a b x :: real\n  by (simp add: linorder_not_less [symmetric])\n\nlemma powr_realpow: \"0 < x \\<Longrightarrow> x powr (real n) = x^n\"\n  by (induction n) (simp_all add: ac_simps powr_add)\n\nlemma powr_realpow': \"(z :: real) \\<ge> 0 \\<Longrightarrow> n \\<noteq> 0 \\<Longrightarrow> z powr of_nat n = z ^ n\"\n  by (cases \"z = 0\") (auto simp: powr_realpow)\n\nlemma powr_real_of_int':\n  assumes \"x \\<ge> 0\" \"x \\<noteq> 0 \\<or> n > 0\"\n  shows   \"x powr real_of_int n = power_int x n\"\n  by (metis assms exp_ln_iff exp_power_int nless_le power_int_eq_0_iff powr_def)\n\nlemma log_ln: \"ln x = log (exp(1)) x\"\n  by (simp add: log_def)\n\nlemma DERIV_log:\n  assumes \"x > 0\"\n  shows \"DERIV (\\<lambda>y. log b y) x :> 1 / (ln b * x)\"\nproof -\n  define lb where \"lb = 1 / ln b\"\n  moreover have \"DERIV (\\<lambda>y. lb * ln y) x :> lb / x\"\n    using \\<open>x > 0\\<close> by (auto intro!: derivative_eq_intros)\n  ultimately show ?thesis\n    by (simp add: log_def)\nqed\n\nlemmas DERIV_log[THEN DERIV_chain2, derivative_intros]\n  and DERIV_log[THEN DERIV_chain2, unfolded has_field_derivative_def, derivative_intros]\n\nlemma powr_log_cancel [simp]: \"0 < a \\<Longrightarrow> a \\<noteq> 1 \\<Longrightarrow> 0 < x \\<Longrightarrow> a powr (log a x) = x\"\n  by (simp add: powr_def log_def)\n\nlemma log_powr_cancel [simp]: \"0 < a \\<Longrightarrow> a \\<noteq> 1 \\<Longrightarrow> log a (a powr y) = y\"\n  by (simp add: log_def powr_def)\n\nlemma log_mult:\n  \"0 < a \\<Longrightarrow> a \\<noteq> 1 \\<Longrightarrow> 0 < x \\<Longrightarrow> 0 < y \\<Longrightarrow>\n    log a (x * y) = log a x + log a y\"\n  by (simp add: log_def ln_mult divide_inverse distrib_right)\n\nlemma log_eq_div_ln_mult_log:\n  \"0 < a \\<Longrightarrow> a \\<noteq> 1 \\<Longrightarrow> 0 < b \\<Longrightarrow> b \\<noteq> 1 \\<Longrightarrow> 0 < x \\<Longrightarrow>\n    log a x = (ln b/ln a) * log b x\"\n  by (simp add: log_def divide_inverse)\n\ntext\\<open>Base 10 logarithms\\<close>\nlemma log_base_10_eq1: \"0 < x \\<Longrightarrow> log 10 x = (ln (exp 1) / ln 10) * ln x\"\n  by (simp add: log_def)\n\nlemma log_base_10_eq2: \"0 < x \\<Longrightarrow> log 10 x = (log 10 (exp 1)) * ln x\"\n  by (simp add: log_def)\n\nlemma log_one [simp]: \"log a 1 = 0\"\n  by (simp add: log_def)\n\nlemma log_eq_one [simp]: \"0 < a \\<Longrightarrow> a \\<noteq> 1 \\<Longrightarrow> log a a = 1\"\n  by (simp add: log_def)\n\nlemma log_inverse: \"0 < a \\<Longrightarrow> a \\<noteq> 1 \\<Longrightarrow> 0 < x \\<Longrightarrow> log a (inverse x) = - log a x\"\n  using ln_inverse log_def by auto\n\nlemma log_divide: \"0 < a \\<Longrightarrow> a \\<noteq> 1 \\<Longrightarrow> 0 < x \\<Longrightarrow> 0 < y \\<Longrightarrow> log a (x/y) = log a x - log a y\"\n  by (simp add: log_mult divide_inverse log_inverse)\n\nlemma powr_gt_zero [simp]: \"0 < x powr a \\<longleftrightarrow> x \\<noteq> 0\"\n  for a x :: real\n  by (simp add: powr_def)\n\nlemma powr_nonneg_iff[simp]: \"a powr x \\<le> 0 \\<longleftrightarrow> a = 0\"\n  for a x::real\n  by (meson not_less powr_gt_zero)\n\nlemma log_add_eq_powr: \"0 < b \\<Longrightarrow> b \\<noteq> 1 \\<Longrightarrow> 0 < x \\<Longrightarrow> log b x + y = log b (x * b powr y)\"\n  and add_log_eq_powr: \"0 < b \\<Longrightarrow> b \\<noteq> 1 \\<Longrightarrow> 0 < x \\<Longrightarrow> y + log b x = log b (b powr y * x)\"\n  and log_minus_eq_powr: \"0 < b \\<Longrightarrow> b \\<noteq> 1 \\<Longrightarrow> 0 < x \\<Longrightarrow> log b x - y = log b (x * b powr -y)\"\n  and minus_log_eq_powr: \"0 < b \\<Longrightarrow> b \\<noteq> 1 \\<Longrightarrow> 0 < x \\<Longrightarrow> y - log b x = log b (b powr y / x)\"\n  by (simp_all add: log_mult log_divide)\n\nlemma log_less_cancel_iff [simp]: \"1 < a \\<Longrightarrow> 0 < x \\<Longrightarrow> 0 < y \\<Longrightarrow> log a x < log a y \\<longleftrightarrow> x < y\"\n  using powr_less_cancel_iff [of a] powr_log_cancel [of a x] powr_log_cancel [of a y]\n  by (metis less_eq_real_def less_trans not_le zero_less_one)\n\nlemma log_inj:\n  assumes \"1 < b\"\n  shows \"inj_on (log b) {0 <..}\"\nproof (rule inj_onI, simp)\n  fix x y\n  assume pos: \"0 < x\" \"0 < y\" and *: \"log b x = log b y\"\n  show \"x = y\"\n  proof (cases rule: linorder_cases)\n    assume \"x = y\"\n    then show ?thesis by simp\n  next\n    assume \"x < y\"\n    then have \"log b x < log b y\"\n      using log_less_cancel_iff[OF \\<open>1 < b\\<close>] pos by simp\n    then show ?thesis using * by simp\n  next\n    assume \"y < x\"\n    then have \"log b y < log b x\"\n      using log_less_cancel_iff[OF \\<open>1 < b\\<close>] pos by simp\n    then show ?thesis using * by simp\n  qed\nqed\n\nlemma log_le_cancel_iff [simp]: \"1 < a \\<Longrightarrow> 0 < x \\<Longrightarrow> 0 < y \\<Longrightarrow> log a x \\<le> log a y \\<longleftrightarrow> x \\<le> y\"\n  by (simp add: linorder_not_less [symmetric])\n\nlemma zero_less_log_cancel_iff[simp]: \"1 < a \\<Longrightarrow> 0 < x \\<Longrightarrow> 0 < log a x \\<longleftrightarrow> 1 < x\"\n  using log_less_cancel_iff[of a 1 x] by simp\n\nlemma zero_le_log_cancel_iff[simp]: \"1 < a \\<Longrightarrow> 0 < x \\<Longrightarrow> 0 \\<le> log a x \\<longleftrightarrow> 1 \\<le> x\"\n  using log_le_cancel_iff[of a 1 x] by simp\n\nlemma log_less_zero_cancel_iff[simp]: \"1 < a \\<Longrightarrow> 0 < x \\<Longrightarrow> log a x < 0 \\<longleftrightarrow> x < 1\"\n  using log_less_cancel_iff[of a x 1] by simp\n\nlemma log_le_zero_cancel_iff[simp]: \"1 < a \\<Longrightarrow> 0 < x \\<Longrightarrow> log a x \\<le> 0 \\<longleftrightarrow> x \\<le> 1\"\n  using log_le_cancel_iff[of a x 1] by simp\n\nlemma one_less_log_cancel_iff[simp]: \"1 < a \\<Longrightarrow> 0 < x \\<Longrightarrow> 1 < log a x \\<longleftrightarrow> a < x\"\n  using log_less_cancel_iff[of a a x] by simp\n\nlemma one_le_log_cancel_iff[simp]: \"1 < a \\<Longrightarrow> 0 < x \\<Longrightarrow> 1 \\<le> log a x \\<longleftrightarrow> a \\<le> x\"\n  using log_le_cancel_iff[of a a x] by simp\n\nlemma log_less_one_cancel_iff[simp]: \"1 < a \\<Longrightarrow> 0 < x \\<Longrightarrow> log a x < 1 \\<longleftrightarrow> x < a\"\n  using log_less_cancel_iff[of a x a] by simp\n\nlemma log_le_one_cancel_iff[simp]: \"1 < a \\<Longrightarrow> 0 < x \\<Longrightarrow> log a x \\<le> 1 \\<longleftrightarrow> x \\<le> a\"\n  using log_le_cancel_iff[of a x a] by simp\n\nlemma le_log_iff:\n  fixes b x y :: real\n  assumes \"1 < b\" \"x > 0\"\n  shows \"y \\<le> log b x \\<longleftrightarrow> b powr y \\<le> x\"\n  using assms\n  by (metis less_irrefl less_trans powr_le_cancel_iff powr_log_cancel zero_less_one)\n\nlemma less_log_iff:\n  assumes \"1 < b\" \"x > 0\"\n  shows \"y < log b x \\<longleftrightarrow> b powr y < x\"\n  by (metis assms dual_order.strict_trans less_irrefl powr_less_cancel_iff\n    powr_log_cancel zero_less_one)\n\nlemma\n  assumes \"1 < b\" \"x > 0\"\n  shows log_less_iff: \"log b x < y \\<longleftrightarrow> x < b powr y\"\n    and log_le_iff: \"log b x \\<le> y \\<longleftrightarrow> x \\<le> b powr y\"\n  using le_log_iff[OF assms, of y] less_log_iff[OF assms, of y]\n  by auto\n\nlemmas powr_le_iff = le_log_iff[symmetric]\n  and powr_less_iff = less_log_iff[symmetric]\n  and less_powr_iff = log_less_iff[symmetric]\n  and le_powr_iff = log_le_iff[symmetric]\n\nlemma le_log_of_power:\n  assumes \"b ^ n \\<le> m\" \"1 < b\"\n  shows \"n \\<le> log b m\"\nproof -\n  from assms have \"0 < m\" by (metis less_trans zero_less_power less_le_trans zero_less_one)\n  thus ?thesis using assms by (simp add: le_log_iff powr_realpow)\nqed\n\nlemma le_log2_of_power: \"2 ^ n \\<le> m \\<Longrightarrow> n \\<le> log 2 m\" for m n :: nat\nusing le_log_of_power[of 2] by simp\n\nlemma log_of_power_le: \"\\<lbrakk> m \\<le> b ^ n; b > 1; m > 0 \\<rbrakk> \\<Longrightarrow> log b (real m) \\<le> n\"\nby (simp add: log_le_iff powr_realpow)\n\nlemma log2_of_power_le: \"\\<lbrakk> m \\<le> 2 ^ n; m > 0 \\<rbrakk> \\<Longrightarrow> log 2 m \\<le> n\" for m n :: nat\nusing log_of_power_le[of _ 2] by simp\n\nlemma log_of_power_less: \"\\<lbrakk> m < b ^ n; b > 1; m > 0 \\<rbrakk> \\<Longrightarrow> log b (real m) < n\"\nby (simp add: log_less_iff powr_realpow)\n\nlemma log2_of_power_less: \"\\<lbrakk> m < 2 ^ n; m > 0 \\<rbrakk> \\<Longrightarrow> log 2 m < n\" for m n :: nat\nusing log_of_power_less[of _ 2] by simp\n\nlemma less_log_of_power:\n  assumes \"b ^ n < m\" \"1 < b\"\n  shows \"n < log b m\"\nproof -\n  have \"0 < m\" by (metis assms less_trans zero_less_power zero_less_one)\n  thus ?thesis using assms by (simp add: less_log_iff powr_realpow)\nqed\n\nlemma less_log2_of_power: \"2 ^ n < m \\<Longrightarrow> n < log 2 m\" for m n :: nat\nusing less_log_of_power[of 2] by simp\n\nlemma gr_one_powr[simp]:\n  fixes x y :: real shows \"\\<lbrakk> x > 1; y > 0 \\<rbrakk> \\<Longrightarrow> 1 < x powr y\"\nby(simp add: less_powr_iff)\n\nlemma log_pow_cancel [simp]:\n  \"a > 0 \\<Longrightarrow> a \\<noteq> 1 \\<Longrightarrow> log a (a ^ b) = b\"\n  by (simp add: ln_realpow log_def)\n\nlemma floor_log_eq_powr_iff: \"x > 0 \\<Longrightarrow> b > 1 \\<Longrightarrow> \\<lfloor>log b x\\<rfloor> = k \\<longleftrightarrow> b powr k \\<le> x \\<and> x < b powr (k + 1)\"\n  by (auto simp: floor_eq_iff powr_le_iff less_powr_iff)\n\nlemma floor_log_nat_eq_powr_iff: fixes b n k :: nat\n  shows \"\\<lbrakk> b \\<ge> 2; k > 0 \\<rbrakk> \\<Longrightarrow>\n  floor (log b (real k)) = n \\<longleftrightarrow> b^n \\<le> k \\<and> k < b^(n+1)\"\nby (auto simp: floor_log_eq_powr_iff powr_add powr_realpow\n               of_nat_power[symmetric] of_nat_mult[symmetric] ac_simps\n         simp del: of_nat_power of_nat_mult)\n\nlemma floor_log_nat_eq_if: fixes b n k :: nat\n  assumes \"b^n \\<le> k\" \"k < b^(n+1)\" \"b \\<ge> 2\"\n  shows \"floor (log b (real k)) = n\"\nproof -\n  have \"k \\<ge> 1\" using assms(1,3) one_le_power[of b n] by linarith\n  with assms show ?thesis by(simp add: floor_log_nat_eq_powr_iff)\nqed\n\nlemma ceiling_log_eq_powr_iff: \"\\<lbrakk> x > 0; b > 1 \\<rbrakk>\n  \\<Longrightarrow> \\<lceil>log b x\\<rceil> = int k + 1 \\<longleftrightarrow> b powr k < x \\<and> x \\<le> b powr (k + 1)\"\nby (auto simp: ceiling_eq_iff powr_less_iff le_powr_iff)\n\nlemma ceiling_log_nat_eq_powr_iff: fixes b n k :: nat\n  shows \"\\<lbrakk> b \\<ge> 2; k > 0 \\<rbrakk> \\<Longrightarrow>\n  ceiling (log b (real k)) = int n + 1 \\<longleftrightarrow> (b^n < k \\<and> k \\<le> b^(n+1))\"\nusing ceiling_log_eq_powr_iff\nby (auto simp: powr_add powr_realpow of_nat_power[symmetric] of_nat_mult[symmetric] ac_simps\n         simp del: of_nat_power of_nat_mult)\n\nlemma ceiling_log_nat_eq_if: fixes b n k :: nat\n  assumes \"b^n < k\" \"k \\<le> b^(n+1)\" \"b \\<ge> 2\"\n  shows \"ceiling (log b (real k)) = int n + 1\"\nproof -\n  have \"k \\<ge> 1\" using assms(1,3) one_le_power[of b n] by linarith\n  with assms show ?thesis by(simp add: ceiling_log_nat_eq_powr_iff)\nqed\n\nlemma floor_log2_div2: fixes n :: nat assumes \"n \\<ge> 2\"\nshows \"floor(log 2 n) = floor(log 2 (n div 2)) + 1\"\nproof cases\n  assume \"n=2\" thus ?thesis by simp\nnext\n  let ?m = \"n div 2\"\n  assume \"n\\<noteq>2\"\n  hence \"1 \\<le> ?m\" using assms by arith\n  then obtain i where i: \"2 ^ i \\<le> ?m\" \"?m < 2 ^ (i + 1)\"\n    using ex_power_ivl1[of 2 ?m] by auto\n  have \"2^(i+1) \\<le> 2*?m\" using i(1) by simp\n  also have \"2*?m \\<le> n\" by arith\n  finally have *: \"2^(i+1) \\<le> \\<dots>\" .\n  have \"n < 2^(i+1+1)\" using i(2) by simp\n  from floor_log_nat_eq_if[OF * this] floor_log_nat_eq_if[OF i]\n  show ?thesis by simp\nqed\n\nlemma ceiling_log2_div2: assumes \"n \\<ge> 2\"\nshows \"ceiling(log 2 (real n)) = ceiling(log 2 ((n-1) div 2 + 1)) + 1\"\nproof cases\n  assume \"n=2\" thus ?thesis by simp\nnext\n  let ?m = \"(n-1) div 2 + 1\"\n  assume \"n\\<noteq>2\"\n  hence \"2 \\<le> ?m\" using assms by arith\n  then obtain i where i: \"2 ^ i < ?m\" \"?m \\<le> 2 ^ (i + 1)\"\n    using ex_power_ivl2[of 2 ?m] by auto\n  have \"n \\<le> 2*?m\" by arith\n  also have \"2*?m \\<le> 2 ^ ((i+1)+1)\" using i(2) by simp\n  finally have *: \"n \\<le> \\<dots>\" .\n  have \"2^(i+1) < n\" using i(1) by (auto simp: less_Suc_eq_0_disj)\n  from ceiling_log_nat_eq_if[OF this *] ceiling_log_nat_eq_if[OF i]\n  show ?thesis by simp\nqed\n\nlemma powr_real_of_int:\n  \"x > 0 \\<Longrightarrow> x powr real_of_int n = (if n \\<ge> 0 then x ^ nat n else inverse (x ^ nat (- n)))\"\n  using powr_realpow[of x \"nat n\"] powr_realpow[of x \"nat (-n)\"]\n  by (auto simp: field_simps powr_minus)\n\nlemma powr_numeral [simp]: \"0 \\<le> x \\<Longrightarrow> x powr (numeral n :: real) = x ^ (numeral n)\"\n  by (metis less_le power_zero_numeral powr_0 of_nat_numeral powr_realpow)\n\nlemma powr_int:\n  assumes \"x > 0\"\n  shows \"x powr i = (if i \\<ge> 0 then x ^ nat i else 1 / x ^ nat (-i))\"\nproof (cases \"i < 0\")\n  case True\n  have r: \"x powr i = 1 / x powr (- i)\"\n    by (simp add: powr_minus field_simps)\n  show ?thesis using \\<open>i < 0\\<close> \\<open>x > 0\\<close>\n    by (simp add: r field_simps powr_realpow[symmetric])\nnext\n  case False\n  then show ?thesis\n    by (simp add: assms powr_realpow[symmetric])\nqed\n\ndefinition powr_real :: \"real \\<Rightarrow> real \\<Rightarrow> real\"\n  where [code_abbrev, simp]: \"powr_real = Transcendental.powr\"\n\nlemma compute_powr_real [code]:\n  \"powr_real b i =\n    (if b \\<le> 0 then Code.abort (STR ''powr_real with nonpositive base'') (\\<lambda>_. powr_real b i)\n     else if \\<lfloor>i\\<rfloor> = i then (if 0 \\<le> i then b ^ nat \\<lfloor>i\\<rfloor> else 1 / b ^ nat \\<lfloor>- i\\<rfloor>)\n     else Code.abort (STR ''powr_real with non-integer exponent'') (\\<lambda>_. powr_real b i))\"\n    for b i :: real\n  by (auto simp: powr_int)\n\nlemma powr_one: \"0 \\<le> x \\<Longrightarrow> x powr 1 = x\"\n  for x :: real\n  using powr_realpow [of x 1] by simp\n\nlemma powr_neg_one: \"0 < x \\<Longrightarrow> x powr - 1 = 1 / x\"\n  for x :: real\n  using powr_int [of x \"- 1\"] by simp\n\nlemma powr_neg_numeral: \"0 < x \\<Longrightarrow> x powr - numeral n = 1 / x ^ numeral n\"\n  for x :: real\n  using powr_int [of x \"- numeral n\"] by simp\n\nlemma root_powr_inverse: \"0 < n \\<Longrightarrow> 0 < x \\<Longrightarrow> root n x = x powr (1/n)\"\n  by (rule real_root_pos_unique) (auto simp: powr_realpow[symmetric] powr_powr)\n\nlemma ln_powr: \"x \\<noteq> 0 \\<Longrightarrow> ln (x powr y) = y * ln x\"\n  for x :: real\n  by (simp add: powr_def)\n\nlemma ln_root: \"n > 0 \\<Longrightarrow> b > 0 \\<Longrightarrow> ln (root n b) =  ln b / n\"\n  by (simp add: root_powr_inverse ln_powr)\n\nlemma ln_sqrt: \"0 < x \\<Longrightarrow> ln (sqrt x) = ln x / 2\"\n  by (simp add: ln_powr ln_powr[symmetric] mult.commute)\n\nlemma log_root: \"n > 0 \\<Longrightarrow> a > 0 \\<Longrightarrow> log b (root n a) =  log b a / n\"\n  by (simp add: log_def ln_root)\n\nlemma log_powr: \"x \\<noteq> 0 \\<Longrightarrow> log b (x powr y) = y * log b x\"\n  by (simp add: log_def ln_powr)\n\n(* [simp] is not worth it, interferes with some proofs *)\nlemma log_nat_power: \"0 < x \\<Longrightarrow> log b (x^n) = real n * log b x\"\n  by (simp add: log_powr powr_realpow [symmetric])\n\nlemma log_of_power_eq:\n  assumes \"m = b ^ n\" \"b > 1\"\n  shows \"n = log b (real m)\"\nproof -\n  have \"n = log b (b ^ n)\" using assms(2) by (simp add: log_nat_power)\n  also have \"\\<dots> = log b m\" using assms by simp\n  finally show ?thesis .\nqed\n\nlemma log2_of_power_eq: \"m = 2 ^ n \\<Longrightarrow> n = log 2 m\" for m n :: nat\nusing log_of_power_eq[of _ 2] by simp\n\nlemma log_base_change: \"0 < a \\<Longrightarrow> a \\<noteq> 1 \\<Longrightarrow> log b x = log a x / log a b\"\n  by (simp add: log_def)\n\nlemma log_base_pow: \"0 < a \\<Longrightarrow> log (a ^ n) x = log a x / n\"\n  by (simp add: log_def ln_realpow)\n\nlemma log_base_powr: \"a \\<noteq> 0 \\<Longrightarrow> log (a powr b) x = log a x / b\"\n  by (simp add: log_def ln_powr)\n\nlemma log_base_root: \"n > 0 \\<Longrightarrow> b > 0 \\<Longrightarrow> log (root n b) x = n * (log b x)\"\n  by (simp add: log_def ln_root)\n\nlemma ln_bound: \"0 < x \\<Longrightarrow> ln x \\<le> x\" for x :: real\n  using ln_le_minus_one by force\n\nlemma powr_mono:\n  fixes x :: real\n  assumes \"a \\<le> b\" and \"1 \\<le> x\" shows \"x powr a \\<le> x powr b\"\n  using assms less_eq_real_def by auto\n\nlemma ge_one_powr_ge_zero: \"1 \\<le> x \\<Longrightarrow> 0 \\<le> a \\<Longrightarrow> 1 \\<le> x powr a\"\n  for x :: real\n  using powr_mono by fastforce\n\nlemma powr_less_mono2: \"0 < a \\<Longrightarrow> 0 \\<le> x \\<Longrightarrow> x < y \\<Longrightarrow> x powr a < y powr a\"\n  for x :: real\n  by (simp add: powr_def)\n\nlemma powr_less_mono2_neg: \"a < 0 \\<Longrightarrow> 0 < x \\<Longrightarrow> x < y \\<Longrightarrow> y powr a < x powr a\"\n  for x :: real\n  by (simp add: powr_def)\n\nlemma powr_mono2: \"x powr a \\<le> y powr a\" if \"0 \\<le> a\" \"0 \\<le> x\" \"x \\<le> y\"\n  for x :: real\n  using less_eq_real_def powr_less_mono2 that by auto\n\nlemma powr_le1: \"0 \\<le> a \\<Longrightarrow> 0 \\<le> x \\<Longrightarrow> x \\<le> 1 \\<Longrightarrow> x powr a \\<le> 1\"\n  for x :: real\n  using powr_mono2 by fastforce\n\nlemma powr_mono2':\n  fixes a x y :: real\n  assumes \"a \\<le> 0\" \"x > 0\" \"x \\<le> y\"\n  shows \"x powr a \\<ge> y powr a\"\nproof -\n  from assms have \"x powr - a \\<le> y powr - a\"\n    by (intro powr_mono2) simp_all\n  with assms show ?thesis\n    by (auto simp: powr_minus field_simps)\nqed\n\nlemma powr_mono_both:\n  fixes x :: real\n  assumes \"0 \\<le> a\" \"a \\<le> b\" \"1 \\<le> x\" \"x \\<le> y\"\n    shows \"x powr a \\<le> y powr b\"\n  by (meson assms order.trans powr_mono powr_mono2 zero_le_one)\n\nlemma powr_inj: \"0 < a \\<Longrightarrow> a \\<noteq> 1 \\<Longrightarrow> a powr x = a powr y \\<longleftrightarrow> x = y\"\n  for x :: real\n  unfolding powr_def exp_inj_iff by simp\n\nlemma powr_half_sqrt: \"0 \\<le> x \\<Longrightarrow> x powr (1/2) = sqrt x\"\n  by (simp add: powr_def root_powr_inverse sqrt_def)\n\nlemma square_powr_half [simp]:\n  fixes x::real shows \"x\\<^sup>2 powr (1/2) = \\<bar>x\\<bar>\"\n  by (simp add: powr_half_sqrt)\n\nlemma ln_powr_bound: \"1 \\<le> x \\<Longrightarrow> 0 < a \\<Longrightarrow> ln x \\<le> (x powr a) / a\"\n  for x :: real\n  by (metis exp_gt_zero linear ln_eq_zero_iff ln_exp ln_less_self ln_powr mult.commute\n      mult_imp_le_div_pos not_less powr_gt_zero)\n\nlemma ln_powr_bound2:\n  fixes x :: real\n  assumes \"1 < x\" and \"0 < a\"\n  shows \"(ln x) powr a \\<le> (a powr a) * x\"\nproof -\n  from assms have \"ln x \\<le> (x powr (1 / a)) / (1 / a)\"\n    by (metis less_eq_real_def ln_powr_bound zero_less_divide_1_iff)\n  also have \"\\<dots> = a * (x powr (1 / a))\"\n    by simp\n  finally have \"(ln x) powr a \\<le> (a * (x powr (1 / a))) powr a\"\n    by (metis assms less_imp_le ln_gt_zero powr_mono2)\n  also have \"\\<dots> = (a powr a) * ((x powr (1 / a)) powr a)\"\n    using assms powr_mult by auto\n  also have \"(x powr (1 / a)) powr a = x powr ((1 / a) * a)\"\n    by (rule powr_powr)\n  also have \"\\<dots> = x\" using assms\n    by auto\n  finally show ?thesis .\nqed\n\nlemma tendsto_powr:\n  fixes a b :: real\n  assumes f: \"(f \\<longlongrightarrow> a) F\"\n    and g: \"(g \\<longlongrightarrow> b) F\"\n    and a: \"a \\<noteq> 0\"\n  shows \"((\\<lambda>x. f x powr g x) \\<longlongrightarrow> a powr b) F\"\n  unfolding powr_def\nproof (rule filterlim_If)\n  from f show \"((\\<lambda>x. 0) \\<longlongrightarrow> (if a = 0 then 0 else exp (b * ln a))) (inf F (principal {x. f x = 0}))\"\n    by simp (auto simp: filterlim_iff eventually_inf_principal elim: eventually_mono dest: t1_space_nhds)\n  from f g a show \"((\\<lambda>x. exp (g x * ln (f x))) \\<longlongrightarrow> (if a = 0 then 0 else exp (b * ln a)))\n      (inf F (principal {x. f x \\<noteq> 0}))\"\n    by (auto intro!: tendsto_intros intro: tendsto_mono inf_le1)\nqed\n\nlemma tendsto_powr'[tendsto_intros]:\n  fixes a :: real\n  assumes f: \"(f \\<longlongrightarrow> a) F\"\n    and g: \"(g \\<longlongrightarrow> b) F\"\n    and a: \"a \\<noteq> 0 \\<or> (b > 0 \\<and> eventually (\\<lambda>x. f x \\<ge> 0) F)\"\n  shows \"((\\<lambda>x. f x powr g x) \\<longlongrightarrow> a powr b) F\"\nproof -\n  from a consider \"a \\<noteq> 0\" | \"a = 0\" \"b > 0\" \"eventually (\\<lambda>x. f x \\<ge> 0) F\"\n    by auto\n  then show ?thesis\n  proof cases\n    case 1\n    with f g show ?thesis by (rule tendsto_powr)\n  next\n    case 2\n    have \"((\\<lambda>x. if f x = 0 then 0 else exp (g x * ln (f x))) \\<longlongrightarrow> 0) F\"\n    proof (intro filterlim_If)\n      have \"filterlim f (principal {0<..}) (inf F (principal {z. f z \\<noteq> 0}))\"\n        using \\<open>eventually (\\<lambda>x. f x \\<ge> 0) F\\<close>\n        by (auto simp: filterlim_iff eventually_inf_principal\n            eventually_principal elim: eventually_mono)\n      moreover have \"filterlim f (nhds a) (inf F (principal {z. f z \\<noteq> 0}))\"\n        by (rule tendsto_mono[OF _ f]) simp_all\n      ultimately have f: \"filterlim f (at_right 0) (inf F (principal {x. f x \\<noteq> 0}))\"\n        by (simp add: at_within_def filterlim_inf \\<open>a = 0\\<close>)\n      have g: \"(g \\<longlongrightarrow> b) (inf F (principal {z. f z \\<noteq> 0}))\"\n        by (rule tendsto_mono[OF _ g]) simp_all\n      show \"((\\<lambda>x. exp (g x * ln (f x))) \\<longlongrightarrow> 0) (inf F (principal {x. f x \\<noteq> 0}))\"\n        by (rule filterlim_compose[OF exp_at_bot] filterlim_tendsto_pos_mult_at_bot\n                 filterlim_compose[OF ln_at_0] f g \\<open>b > 0\\<close>)+\n    qed simp_all\n    with \\<open>a = 0\\<close> show ?thesis\n      by (simp add: powr_def)\n  qed\nqed\n\nlemma continuous_powr:\n  assumes \"continuous F f\"\n    and \"continuous F g\"\n    and \"f (Lim F (\\<lambda>x. x)) \\<noteq> 0\"\n  shows \"continuous F (\\<lambda>x. (f x) powr (g x :: real))\"\n  using assms unfolding continuous_def by (rule tendsto_powr)\n\nlemma continuous_at_within_powr[continuous_intros]:\n  fixes f g :: \"_ \\<Rightarrow> real\"\n  assumes \"continuous (at a within s) f\"\n    and \"continuous (at a within s) g\"\n    and \"f a \\<noteq> 0\"\n  shows \"continuous (at a within s) (\\<lambda>x. (f x) powr (g x))\"\n  using assms unfolding continuous_within by (rule tendsto_powr)\n\nlemma isCont_powr[continuous_intros, simp]:\n  fixes f g :: \"_ \\<Rightarrow> real\"\n  assumes \"isCont f a\" \"isCont g a\" \"f a \\<noteq> 0\"\n  shows \"isCont (\\<lambda>x. (f x) powr g x) a\"\n  using assms unfolding continuous_at by (rule tendsto_powr)\n\nlemma continuous_on_powr[continuous_intros]:\n  fixes f g :: \"_ \\<Rightarrow> real\"\n  assumes \"continuous_on s f\" \"continuous_on s g\" and \"\\<forall>x\\<in>s. f x \\<noteq> 0\"\n  shows \"continuous_on s (\\<lambda>x. (f x) powr (g x))\"\n  using assms unfolding continuous_on_def by (fast intro: tendsto_powr)\n\nlemma tendsto_powr2:\n  fixes a :: real\n  assumes f: \"(f \\<longlongrightarrow> a) F\"\n    and g: \"(g \\<longlongrightarrow> b) F\"\n    and \"\\<forall>\\<^sub>F x in F. 0 \\<le> f x\"\n    and b: \"0 < b\"\n  shows \"((\\<lambda>x. f x powr g x) \\<longlongrightarrow> a powr b) F\"\n  using tendsto_powr'[of f a F g b] assms by auto\n\nlemma has_derivative_powr[derivative_intros]:\n  assumes g[derivative_intros]: \"(g has_derivative g') (at x within X)\"\n    and f[derivative_intros]:\"(f has_derivative f') (at x within X)\"\n  assumes pos: \"0 < g x\" and \"x \\<in> X\"\n  shows \"((\\<lambda>x. g x powr f x::real) has_derivative (\\<lambda>h. (g x powr f x) * (f' h * ln (g x) + g' h * f x / g x))) (at x within X)\"\nproof -\n  have \"\\<forall>\\<^sub>F x in at x within X. g x > 0\"\n    by (rule order_tendstoD[OF _ pos])\n      (rule has_derivative_continuous[OF g, unfolded continuous_within])\n  then obtain d where \"d > 0\" and pos': \"\\<And>x'. x' \\<in> X \\<Longrightarrow> dist x' x < d \\<Longrightarrow> 0 < g x'\"\n    using pos unfolding eventually_at by force\n  have \"((\\<lambda>x. exp (f x * ln (g x))) has_derivative\n    (\\<lambda>h. (g x powr f x) * (f' h * ln (g x) + g' h * f x / g x))) (at x within X)\"\n    using pos\n    by (auto intro!: derivative_eq_intros simp: field_split_simps powr_def)\n  then show ?thesis\n    by (rule has_derivative_transform_within[OF _ \\<open>d > 0\\<close> \\<open>x \\<in> X\\<close>]) (auto simp: powr_def dest: pos')\nqed\n\nlemma DERIV_powr:\n  fixes r :: real\n  assumes g: \"DERIV g x :> m\"\n    and pos: \"g x > 0\"\n    and f: \"DERIV f x :> r\"\n  shows \"DERIV (\\<lambda>x. g x powr f x) x :> (g x powr f x) * (r * ln (g x) + m * f x / g x)\"\n  using assms\n  by (auto intro!: derivative_eq_intros ext simp: has_field_derivative_def algebra_simps)\n\nlemma DERIV_fun_powr:\n  fixes r :: real\n  assumes g: \"DERIV g x :> m\"\n    and pos: \"g x > 0\"\n  shows \"DERIV (\\<lambda>x. (g x) powr r) x :> r * (g x) powr (r - of_nat 1) * m\"\n  using DERIV_powr[OF g pos DERIV_const, of r] pos\n  by (simp add: powr_diff field_simps)\n\nlemma has_real_derivative_powr:\n  assumes \"z > 0\"\n  shows \"((\\<lambda>z. z powr r) has_real_derivative r * z powr (r - 1)) (at z)\"\nproof (subst DERIV_cong_ev[OF refl _ refl])\n  from assms have \"eventually (\\<lambda>z. z \\<noteq> 0) (nhds z)\"\n    by (intro t1_space_nhds) auto\n  then show \"eventually (\\<lambda>z. z powr r = exp (r * ln z)) (nhds z)\"\n    unfolding powr_def by eventually_elim simp\n  from assms show \"((\\<lambda>z. exp (r * ln z)) has_real_derivative r * z powr (r - 1)) (at z)\"\n    by (auto intro!: derivative_eq_intros simp: powr_def field_simps exp_diff)\nqed\n\ndeclare has_real_derivative_powr[THEN DERIV_chain2, derivative_intros]\n\nlemma tendsto_zero_powrI:\n  assumes \"(f \\<longlongrightarrow> (0::real)) F\" \"(g \\<longlongrightarrow> b) F\" \"\\<forall>\\<^sub>F x in F. 0 \\<le> f x\" \"0 < b\"\n  shows \"((\\<lambda>x. f x powr g x) \\<longlongrightarrow> 0) F\"\n  using tendsto_powr2[OF assms] by simp\n\nlemma continuous_on_powr':\n  fixes f g :: \"_ \\<Rightarrow> real\"\n  assumes \"continuous_on s f\" \"continuous_on s g\"\n    and \"\\<forall>x\\<in>s. f x \\<ge> 0 \\<and> (f x = 0 \\<longrightarrow> g x > 0)\"\n  shows \"continuous_on s (\\<lambda>x. (f x) powr (g x))\"\n  unfolding continuous_on_def\nproof\n  fix x\n  assume x: \"x \\<in> s\"\n  from assms x show \"((\\<lambda>x. f x powr g x) \\<longlongrightarrow> f x powr g x) (at x within s)\"\n  proof (cases \"f x = 0\")\n    case True\n    from assms(3) have \"eventually (\\<lambda>x. f x \\<ge> 0) (at x within s)\"\n      by (auto simp: at_within_def eventually_inf_principal)\n    with True x assms show ?thesis\n      by (auto intro!: tendsto_zero_powrI[of f _ g \"g x\"] simp: continuous_on_def)\n  next\n    case False\n    with assms x show ?thesis\n      by (auto intro!: tendsto_powr' simp: continuous_on_def)\n  qed\nqed\n\nlemma tendsto_neg_powr:\n  assumes \"s < 0\"\n    and f: \"LIM x F. f x :> at_top\"\n  shows \"((\\<lambda>x. f x powr s) \\<longlongrightarrow> (0::real)) F\"\nproof -\n  have \"((\\<lambda>x. exp (s * ln (f x))) \\<longlongrightarrow> (0::real)) F\" (is \"?X\")\n    by (auto intro!: filterlim_compose[OF exp_at_bot] filterlim_compose[OF ln_at_top]\n        filterlim_tendsto_neg_mult_at_bot assms)\n  also have \"?X \\<longleftrightarrow> ((\\<lambda>x. f x powr s) \\<longlongrightarrow> (0::real)) F\"\n    using f filterlim_at_top_dense[of f F]\n    by (intro filterlim_cong[OF refl refl]) (auto simp: neq_iff powr_def elim: eventually_mono)\n  finally show ?thesis .\nqed\n\nlemma tendsto_exp_limit_at_right: \"((\\<lambda>y. (1 + x * y) powr (1 / y)) \\<longlongrightarrow> exp x) (at_right 0)\"\n  for x :: real\nproof (cases \"x = 0\")\n  case True\n  then show ?thesis by simp\nnext\n  case False\n  have \"((\\<lambda>y. ln (1 + x * y)::real) has_real_derivative 1 * x) (at 0)\"\n    by (auto intro!: derivative_eq_intros)\n  then have \"((\\<lambda>y. ln (1 + x * y) / y) \\<longlongrightarrow> x) (at 0)\"\n    by (auto simp: has_field_derivative_def field_has_derivative_at)\n  then have *: \"((\\<lambda>y. exp (ln (1 + x * y) / y)) \\<longlongrightarrow> exp x) (at 0)\"\n    by (rule tendsto_intros)\n  then show ?thesis\n  proof (rule filterlim_mono_eventually)\n    show \"eventually (\\<lambda>xa. exp (ln (1 + x * xa) / xa) = (1 + x * xa) powr (1 / xa)) (at_right 0)\"\n      unfolding eventually_at_right[OF zero_less_one]\n      using False\n      by (intro exI[of _ \"1 / \\<bar>x\\<bar>\"]) (auto simp: field_simps powr_def abs_if add_nonneg_eq_0_iff)\n  qed (simp_all add: at_eq_sup_left_right)\nqed\n\nlemma tendsto_exp_limit_at_top: \"((\\<lambda>y. (1 + x / y) powr y) \\<longlongrightarrow> exp x) at_top\"\n  for x :: real\n  by (simp add: filterlim_at_top_to_right inverse_eq_divide tendsto_exp_limit_at_right)\n\nlemma tendsto_exp_limit_sequentially: \"(\\<lambda>n. (1 + x / n) ^ n) \\<longlonglongrightarrow> exp x\"\n  for x :: real\nproof (rule filterlim_mono_eventually)\n  from reals_Archimedean2 [of \"\\<bar>x\\<bar>\"] obtain n :: nat where *: \"real n > \\<bar>x\\<bar>\" ..\n  then have \"eventually (\\<lambda>n :: nat. 0 < 1 + x / real n) at_top\"\n    by (intro eventually_sequentiallyI [of n]) (auto simp: field_split_simps)\n  then show \"eventually (\\<lambda>n. (1 + x / n) powr n = (1 + x / n) ^ n) at_top\"\n    by (rule eventually_mono) (erule powr_realpow)\n  show \"(\\<lambda>n. (1 + x / real n) powr real n) \\<longlonglongrightarrow> exp x\"\n    by (rule filterlim_compose [OF tendsto_exp_limit_at_top filterlim_real_sequentially])\nqed auto\n\n\nsubsection \\<open>Sine and Cosine\\<close>\n\ndefinition sin_coeff :: \"nat \\<Rightarrow> real\"\n  where \"sin_coeff = (\\<lambda>n. if even n then 0 else (- 1) ^ ((n - Suc 0) div 2) / (fact n))\"\n\ndefinition cos_coeff :: \"nat \\<Rightarrow> real\"\n  where \"cos_coeff = (\\<lambda>n. if even n then ((- 1) ^ (n div 2)) / (fact n) else 0)\"\n\ndefinition sin :: \"'a \\<Rightarrow> 'a::{real_normed_algebra_1,banach}\"\n  where \"sin = (\\<lambda>x. \\<Sum>n. sin_coeff n *\\<^sub>R x^n)\"\n\ndefinition cos :: \"'a \\<Rightarrow> 'a::{real_normed_algebra_1,banach}\"\n  where \"cos = (\\<lambda>x. \\<Sum>n. cos_coeff n *\\<^sub>R x^n)\"\n\nlemma sin_coeff_0 [simp]: \"sin_coeff 0 = 0\"\n  unfolding sin_coeff_def by simp\n\nlemma cos_coeff_0 [simp]: \"cos_coeff 0 = 1\"\n  unfolding cos_coeff_def by simp\n\nlemma sin_coeff_Suc: \"sin_coeff (Suc n) = cos_coeff n / real (Suc n)\"\n  unfolding cos_coeff_def sin_coeff_def\n  by (simp del: mult_Suc)\n\nlemma cos_coeff_Suc: \"cos_coeff (Suc n) = - sin_coeff n / real (Suc n)\"\n  unfolding cos_coeff_def sin_coeff_def\n  by (simp del: mult_Suc) (auto elim: oddE)\n\nlemma summable_norm_sin: \"summable (\\<lambda>n. norm (sin_coeff n *\\<^sub>R x^n))\"\n  for x :: \"'a::{real_normed_algebra_1,banach}\"\nproof (rule summable_comparison_test [OF _ summable_norm_exp])\n  show \"\\<exists>N. \\<forall>n\\<ge>N. norm (norm (sin_coeff n *\\<^sub>R x ^ n)) \\<le> norm (x ^ n /\\<^sub>R fact n)\"\n    unfolding sin_coeff_def\n    by (auto simp: divide_inverse abs_mult power_abs [symmetric] zero_le_mult_iff)\nqed\n\nlemma summable_norm_cos: \"summable (\\<lambda>n. norm (cos_coeff n *\\<^sub>R x^n))\"\n  for x :: \"'a::{real_normed_algebra_1,banach}\"\nproof (rule summable_comparison_test [OF _ summable_norm_exp])\n  show \"\\<exists>N. \\<forall>n\\<ge>N. norm (norm (cos_coeff n *\\<^sub>R x ^ n)) \\<le> norm (x ^ n /\\<^sub>R fact n)\"\n    unfolding cos_coeff_def\n    by (auto simp: divide_inverse abs_mult power_abs [symmetric] zero_le_mult_iff)\nqed\n\n\nlemma sin_converges: \"(\\<lambda>n. sin_coeff n *\\<^sub>R x^n) sums sin x\"\n  unfolding sin_def\n  by (metis (full_types) summable_norm_cancel summable_norm_sin summable_sums)\n\nlemma cos_converges: \"(\\<lambda>n. cos_coeff n *\\<^sub>R x^n) sums cos x\"\n  unfolding cos_def\n  by (metis (full_types) summable_norm_cancel summable_norm_cos summable_sums)\n\nlemma sin_of_real: \"sin (of_real x) = of_real (sin x)\"\n  for x :: real\nproof -\n  have \"(\\<lambda>n. of_real (sin_coeff n *\\<^sub>R  x^n)) = (\\<lambda>n. sin_coeff n *\\<^sub>R  (of_real x)^n)\"\n  proof\n    show \"of_real (sin_coeff n *\\<^sub>R  x^n) = sin_coeff n *\\<^sub>R of_real x^n\" for n\n      by (simp add: scaleR_conv_of_real)\n  qed\n  also have \"\\<dots> sums (sin (of_real x))\"\n    by (rule sin_converges)\n  finally have \"(\\<lambda>n. of_real (sin_coeff n *\\<^sub>R x^n)) sums (sin (of_real x))\" .\n  then show ?thesis\n    using sums_unique2 sums_of_real [OF sin_converges] by blast\nqed\n\ncorollary sin_in_Reals [simp]: \"z \\<in> \\<real> \\<Longrightarrow> sin z \\<in> \\<real>\"\n  by (metis Reals_cases Reals_of_real sin_of_real)\n\nlemma cos_of_real: \"cos (of_real x) = of_real (cos x)\"\n  for x :: real\nproof -\n  have \"(\\<lambda>n. of_real (cos_coeff n *\\<^sub>R  x^n)) = (\\<lambda>n. cos_coeff n *\\<^sub>R  (of_real x)^n)\"\n  proof\n    show \"of_real (cos_coeff n *\\<^sub>R  x^n) = cos_coeff n *\\<^sub>R of_real x^n\" for n\n      by (simp add: scaleR_conv_of_real)\n  qed\n  also have \"\\<dots> sums (cos (of_real x))\"\n    by (rule cos_converges)\n  finally have \"(\\<lambda>n. of_real (cos_coeff n *\\<^sub>R x^n)) sums (cos (of_real x))\" .\n  then show ?thesis\n    using sums_unique2 sums_of_real [OF cos_converges]\n    by blast\nqed\n\ncorollary cos_in_Reals [simp]: \"z \\<in> \\<real> \\<Longrightarrow> cos z \\<in> \\<real>\"\n  by (metis Reals_cases Reals_of_real cos_of_real)\n\nlemma diffs_sin_coeff: \"diffs sin_coeff = cos_coeff\"\n  by (simp add: diffs_def sin_coeff_Suc del: of_nat_Suc)\n\nlemma diffs_cos_coeff: \"diffs cos_coeff = (\\<lambda>n. - sin_coeff n)\"\n  by (simp add: diffs_def cos_coeff_Suc del: of_nat_Suc)\n\nlemma sin_int_times_real: \"sin (of_int m * of_real x) = of_real (sin (of_int m * x))\"\n  by (metis sin_of_real of_real_mult of_real_of_int_eq)\n\nlemma cos_int_times_real: \"cos (of_int m * of_real x) = of_real (cos (of_int m * x))\"\n  by (metis cos_of_real of_real_mult of_real_of_int_eq)\n\ntext \\<open>Now at last we can get the derivatives of exp, sin and cos.\\<close>\n\nlemma DERIV_sin [simp]: \"DERIV sin x :> cos x\"\n  for x :: \"'a::{real_normed_field,banach}\"\n  unfolding sin_def cos_def scaleR_conv_of_real\n  apply (rule DERIV_cong)\n   apply (rule termdiffs [where K=\"of_real (norm x) + 1 :: 'a\"])\n      apply (simp_all add: norm_less_p1 diffs_of_real diffs_sin_coeff diffs_cos_coeff\n              summable_minus_iff scaleR_conv_of_real [symmetric]\n              summable_norm_sin [THEN summable_norm_cancel]\n              summable_norm_cos [THEN summable_norm_cancel])\n  done\n\ndeclare DERIV_sin[THEN DERIV_chain2, derivative_intros]\n  and DERIV_sin[THEN DERIV_chain2, unfolded has_field_derivative_def, derivative_intros]\n\nlemmas has_derivative_sin[derivative_intros] = DERIV_sin[THEN DERIV_compose_FDERIV]\n\nlemma DERIV_cos [simp]: \"DERIV cos x :> - sin x\"\n  for x :: \"'a::{real_normed_field,banach}\"\n  unfolding sin_def cos_def scaleR_conv_of_real\n  apply (rule DERIV_cong)\n   apply (rule termdiffs [where K=\"of_real (norm x) + 1 :: 'a\"])\n      apply (simp_all add: norm_less_p1 diffs_of_real diffs_minus suminf_minus\n              diffs_sin_coeff diffs_cos_coeff\n              summable_minus_iff scaleR_conv_of_real [symmetric]\n              summable_norm_sin [THEN summable_norm_cancel]\n              summable_norm_cos [THEN summable_norm_cancel])\n  done\n\ndeclare DERIV_cos[THEN DERIV_chain2, derivative_intros]\n  and DERIV_cos[THEN DERIV_chain2, unfolded has_field_derivative_def, derivative_intros]\n\nlemmas has_derivative_cos[derivative_intros] = DERIV_cos[THEN DERIV_compose_FDERIV]\n\nlemma isCont_sin: \"isCont sin x\"\n  for x :: \"'a::{real_normed_field,banach}\"\n  by (rule DERIV_sin [THEN DERIV_isCont])\n\nlemma continuous_on_sin_real: \"continuous_on {a..b} sin\" for a::real\n  using continuous_at_imp_continuous_on isCont_sin by blast\n\nlemma isCont_cos: \"isCont cos x\"\n  for x :: \"'a::{real_normed_field,banach}\"\n  by (rule DERIV_cos [THEN DERIV_isCont])\n\nlemma continuous_on_cos_real: \"continuous_on {a..b} cos\" for a::real\n  using continuous_at_imp_continuous_on isCont_cos by blast\n\n\ncontext\n  fixes f :: \"'a::t2_space \\<Rightarrow> 'b::{real_normed_field,banach}\"\nbegin\n\nlemma isCont_sin' [simp]: \"isCont f a \\<Longrightarrow> isCont (\\<lambda>x. sin (f x)) a\"\n  by (rule isCont_o2 [OF _ isCont_sin])\n\nlemma isCont_cos' [simp]: \"isCont f a \\<Longrightarrow> isCont (\\<lambda>x. cos (f x)) a\"\n  by (rule isCont_o2 [OF _ isCont_cos])\n\nlemma tendsto_sin [tendsto_intros]: \"(f \\<longlongrightarrow> a) F \\<Longrightarrow> ((\\<lambda>x. sin (f x)) \\<longlongrightarrow> sin a) F\"\n  by (rule isCont_tendsto_compose [OF isCont_sin])\n\nlemma tendsto_cos [tendsto_intros]: \"(f \\<longlongrightarrow> a) F \\<Longrightarrow> ((\\<lambda>x. cos (f x)) \\<longlongrightarrow> cos a) F\"\n  by (rule isCont_tendsto_compose [OF isCont_cos])\n\nlemma continuous_sin [continuous_intros]: \"continuous F f \\<Longrightarrow> continuous F (\\<lambda>x. sin (f x))\"\n  unfolding continuous_def by (rule tendsto_sin)\n\nlemma continuous_on_sin [continuous_intros]: \"continuous_on s f \\<Longrightarrow> continuous_on s (\\<lambda>x. sin (f x))\"\n  unfolding continuous_on_def by (auto intro: tendsto_sin)\n\nlemma continuous_cos [continuous_intros]: \"continuous F f \\<Longrightarrow> continuous F (\\<lambda>x. cos (f x))\"\n  unfolding continuous_def by (rule tendsto_cos)\n\nlemma continuous_on_cos [continuous_intros]: \"continuous_on s f \\<Longrightarrow> continuous_on s (\\<lambda>x. cos (f x))\"\n  unfolding continuous_on_def by (auto intro: tendsto_cos)\n\nend\n\nlemma continuous_within_sin: \"continuous (at z within s) sin\"     \n  for z :: \"'a::{real_normed_field,banach}\"\n  by (simp add: continuous_within tendsto_sin)\n\nlemma continuous_within_cos: \"continuous (at z within s) cos\"\n  for z :: \"'a::{real_normed_field,banach}\"\n  by (simp add: continuous_within tendsto_cos)\n\n\nsubsection \\<open>Properties of Sine and Cosine\\<close>\n\nlemma sin_zero [simp]: \"sin 0 = 0\"\n  by (simp add: sin_def sin_coeff_def scaleR_conv_of_real)\n\nlemma cos_zero [simp]: \"cos 0 = 1\"\n  by (simp add: cos_def cos_coeff_def scaleR_conv_of_real)\n\nlemma DERIV_fun_sin: \"DERIV g x :> m \\<Longrightarrow> DERIV (\\<lambda>x. sin (g x)) x :> cos (g x) * m\"\n  by (fact derivative_intros)\n\nlemma DERIV_fun_cos: \"DERIV g x :> m \\<Longrightarrow> DERIV (\\<lambda>x. cos(g x)) x :> - sin (g x) * m\"\n  by (fact derivative_intros)\n\n\nsubsection \\<open>Deriving the Addition Formulas\\<close>\n\ntext \\<open>The product of two cosine series.\\<close>\nlemma cos_x_cos_y:\n  fixes x :: \"'a::{real_normed_field,banach}\"\n  shows\n    \"(\\<lambda>p. \\<Sum>n\\<le>p.\n        if even p \\<and> even n\n        then ((-1) ^ (p div 2) * (p choose n) / (fact p)) *\\<^sub>R (x^n) * y^(p-n) else 0)\n      sums (cos x * cos y)\"\nproof -\n  have \"(cos_coeff n * cos_coeff (p - n)) *\\<^sub>R (x^n * y^(p - n)) =\n    (if even p \\<and> even n then ((-1) ^ (p div 2) * (p choose n) / (fact p)) *\\<^sub>R (x^n) * y^(p - n)\n     else 0)\"\n    if \"n \\<le> p\" for n p :: nat\n  proof -\n    from that have *: \"even n \\<Longrightarrow> even p \\<Longrightarrow>\n        (-1) ^ (n div 2) * (-1) ^ ((p - n) div 2) = (-1 :: real) ^ (p div 2)\"\n      by (metis div_add power_add le_add_diff_inverse odd_add)\n    with that show ?thesis\n      by (auto simp: algebra_simps cos_coeff_def binomial_fact)\n  qed\n  then have \"(\\<lambda>p. \\<Sum>n\\<le>p. if even p \\<and> even n\n                  then ((-1) ^ (p div 2) * (p choose n) / (fact p)) *\\<^sub>R (x^n) * y^(p-n) else 0) =\n             (\\<lambda>p. \\<Sum>n\\<le>p. (cos_coeff n * cos_coeff (p - n)) *\\<^sub>R (x^n * y^(p-n)))\"\n    by simp\n  also have \"\\<dots> = (\\<lambda>p. \\<Sum>n\\<le>p. (cos_coeff n *\\<^sub>R x^n) * (cos_coeff (p - n) *\\<^sub>R y^(p-n)))\"\n    by (simp add: algebra_simps)\n  also have \"\\<dots> sums (cos x * cos y)\"\n    using summable_norm_cos\n    by (auto simp: cos_def scaleR_conv_of_real intro!: Cauchy_product_sums)\n  finally show ?thesis .\nqed\n\ntext \\<open>The product of two sine series.\\<close>\nlemma sin_x_sin_y:\n  fixes x :: \"'a::{real_normed_field,banach}\"\n  shows\n    \"(\\<lambda>p. \\<Sum>n\\<le>p.\n        if even p \\<and> odd n\n        then - ((-1) ^ (p div 2) * (p choose n) / (fact p)) *\\<^sub>R (x^n) * y^(p-n)\n        else 0)\n      sums (sin x * sin y)\"\nproof -\n  have \"(sin_coeff n * sin_coeff (p - n)) *\\<^sub>R (x^n * y^(p-n)) =\n    (if even p \\<and> odd n\n     then -((-1) ^ (p div 2) * (p choose n) / (fact p)) *\\<^sub>R (x^n) * y^(p-n)\n     else 0)\"\n    if \"n \\<le> p\" for n p :: nat\n  proof -\n    have \"(-1) ^ ((n - Suc 0) div 2) * (-1) ^ ((p - Suc n) div 2) = - ((-1 :: real) ^ (p div 2))\"\n      if np: \"odd n\" \"even p\"\n    proof -\n      have \"p > 0\"\n        using \\<open>n \\<le> p\\<close> neq0_conv that(1) by blast\n      then have \\<section>: \"(- 1::real) ^ (p div 2 - Suc 0) = - ((- 1) ^ (p div 2))\"\n        using \\<open>even p\\<close> by (auto simp add: dvd_def power_eq_if)\n      from \\<open>n \\<le> p\\<close> np have *: \"n - Suc 0 + (p - Suc n) = p - Suc (Suc 0)\" \"Suc (Suc 0) \\<le> p\"\n        by arith+\n      have \"(p - Suc (Suc 0)) div 2 = p div 2 - Suc 0\"\n        by simp\n      with \\<open>n \\<le> p\\<close> np  \\<section> * show ?thesis\n        by (simp add: flip: div_add power_add)\n    qed\n    then show ?thesis\n      using \\<open>n\\<le>p\\<close> by (auto simp: algebra_simps sin_coeff_def binomial_fact)\n  qed\n  then have \"(\\<lambda>p. \\<Sum>n\\<le>p. if even p \\<and> odd n\n               then - ((-1) ^ (p div 2) * (p choose n) / (fact p)) *\\<^sub>R (x^n) * y^(p-n) else 0) =\n             (\\<lambda>p. \\<Sum>n\\<le>p. (sin_coeff n * sin_coeff (p - n)) *\\<^sub>R (x^n * y^(p-n)))\"\n    by simp\n  also have \"\\<dots> = (\\<lambda>p. \\<Sum>n\\<le>p. (sin_coeff n *\\<^sub>R x^n) * (sin_coeff (p - n) *\\<^sub>R y^(p-n)))\"\n    by (simp add: algebra_simps)\n  also have \"\\<dots> sums (sin x * sin y)\"\n    using summable_norm_sin\n    by (auto simp: sin_def scaleR_conv_of_real intro!: Cauchy_product_sums)\n  finally show ?thesis .\nqed\n\nlemma sums_cos_x_plus_y:\n  fixes x :: \"'a::{real_normed_field,banach}\"\n  shows\n    \"(\\<lambda>p. \\<Sum>n\\<le>p.\n        if even p\n        then ((-1) ^ (p div 2) * (p choose n) / (fact p)) *\\<^sub>R (x^n) * y^(p-n)\n        else 0)\n      sums cos (x + y)\"\nproof -\n  have\n    \"(\\<Sum>n\\<le>p.\n      if even p then ((-1) ^ (p div 2) * (p choose n) / (fact p)) *\\<^sub>R (x^n) * y^(p-n)\n      else 0) = cos_coeff p *\\<^sub>R ((x + y) ^ p)\"\n    for p :: nat\n  proof -\n    have\n      \"(\\<Sum>n\\<le>p. if even p then ((-1) ^ (p div 2) * (p choose n) / (fact p)) *\\<^sub>R (x^n) * y^(p-n) else 0) =\n       (if even p then \\<Sum>n\\<le>p. ((-1) ^ (p div 2) * (p choose n) / (fact p)) *\\<^sub>R (x^n) * y^(p-n) else 0)\"\n      by simp\n    also have \"\\<dots> =\n       (if even p\n        then of_real ((-1) ^ (p div 2) / (fact p)) * (\\<Sum>n\\<le>p. (p choose n) *\\<^sub>R (x^n) * y^(p-n))\n        else 0)\"\n      by (auto simp: sum_distrib_left field_simps scaleR_conv_of_real nonzero_of_real_divide)\n    also have \"\\<dots> = cos_coeff p *\\<^sub>R ((x + y) ^ p)\"\n      by (simp add: cos_coeff_def binomial_ring [of x y]  scaleR_conv_of_real atLeast0AtMost)\n    finally show ?thesis .\n  qed\n  then have\n    \"(\\<lambda>p. \\<Sum>n\\<le>p.\n        if even p\n        then ((-1) ^ (p div 2) * (p choose n) / (fact p)) *\\<^sub>R (x^n) * y^(p-n)\n        else 0) = (\\<lambda>p. cos_coeff p *\\<^sub>R ((x+y)^p))\"\n    by simp\n   also have \"\\<dots> sums cos (x + y)\"\n    by (rule cos_converges)\n   finally show ?thesis .\nqed\n\ntheorem cos_add:\n  fixes x :: \"'a::{real_normed_field,banach}\"\n  shows \"cos (x + y) = cos x * cos y - sin x * sin y\"\nproof -\n  have\n    \"(if even p \\<and> even n\n      then ((- 1) ^ (p div 2) * int (p choose n) / (fact p)) *\\<^sub>R (x^n) * y^(p-n) else 0) -\n     (if even p \\<and> odd n\n      then - ((- 1) ^ (p div 2) * int (p choose n) / (fact p)) *\\<^sub>R (x^n) * y^(p-n) else 0) =\n     (if even p then ((-1) ^ (p div 2) * (p choose n) / (fact p)) *\\<^sub>R (x^n) * y^(p-n) else 0)\"\n    if \"n \\<le> p\" for n p :: nat\n    by simp\n  then have\n    \"(\\<lambda>p. \\<Sum>n\\<le>p. (if even p then ((-1) ^ (p div 2) * (p choose n) / (fact p)) *\\<^sub>R (x^n) * y^(p-n) else 0))\n      sums (cos x * cos y - sin x * sin y)\"\n    using sums_diff [OF cos_x_cos_y [of x y] sin_x_sin_y [of x y]]\n    by (simp add: sum_subtractf [symmetric])\n  then show ?thesis\n    by (blast intro: sums_cos_x_plus_y sums_unique2)\nqed\n\nlemma sin_minus_converges: \"(\\<lambda>n. - (sin_coeff n *\\<^sub>R (-x)^n)) sums sin x\"\nproof -\n  have [simp]: \"\\<And>n. - (sin_coeff n *\\<^sub>R (-x)^n) = (sin_coeff n *\\<^sub>R x^n)\"\n    by (auto simp: sin_coeff_def elim!: oddE)\n  show ?thesis\n    by (simp add: sin_def summable_norm_sin [THEN summable_norm_cancel, THEN summable_sums])\nqed\n\nlemma sin_minus [simp]: \"sin (- x) = - sin x\"\n  for x :: \"'a::{real_normed_algebra_1,banach}\"\n  using sin_minus_converges [of x]\n  by (auto simp: sin_def summable_norm_sin [THEN summable_norm_cancel]\n      suminf_minus sums_iff equation_minus_iff)\n\nlemma cos_minus_converges: \"(\\<lambda>n. (cos_coeff n *\\<^sub>R (-x)^n)) sums cos x\"\nproof -\n  have [simp]: \"\\<And>n. (cos_coeff n *\\<^sub>R (-x)^n) = (cos_coeff n *\\<^sub>R x^n)\"\n    by (auto simp: Transcendental.cos_coeff_def elim!: evenE)\n  show ?thesis\n    by (simp add: cos_def summable_norm_cos [THEN summable_norm_cancel, THEN summable_sums])\nqed\n\nlemma cos_minus [simp]: \"cos (-x) = cos x\"\n  for x :: \"'a::{real_normed_algebra_1,banach}\"\n  using cos_minus_converges [of x] by (metis cos_def sums_unique)\n\nlemma cos_abs_real [simp]: \"cos \\<bar>x :: real\\<bar> = cos x\"\n  by (simp add: abs_if)\n\nlemma sin_cos_squared_add [simp]: \"(sin x)\\<^sup>2 + (cos x)\\<^sup>2 = 1\"\n  for x :: \"'a::{real_normed_field,banach}\"\n  using cos_add [of x \"-x\"]\n  by (simp add: power2_eq_square algebra_simps)\n\nlemma sin_cos_squared_add2 [simp]: \"(cos x)\\<^sup>2 + (sin x)\\<^sup>2 = 1\"\n  for x :: \"'a::{real_normed_field,banach}\"\n  by (subst add.commute, rule sin_cos_squared_add)\n\nlemma sin_cos_squared_add3 [simp]: \"cos x * cos x + sin x * sin x = 1\"\n  for x :: \"'a::{real_normed_field,banach}\"\n  using sin_cos_squared_add2 [unfolded power2_eq_square] .\n\nlemma sin_squared_eq: \"(sin x)\\<^sup>2 = 1 - (cos x)\\<^sup>2\"\n  for x :: \"'a::{real_normed_field,banach}\"\n  unfolding eq_diff_eq by (rule sin_cos_squared_add)\n\nlemma cos_squared_eq: \"(cos x)\\<^sup>2 = 1 - (sin x)\\<^sup>2\"\n  for x :: \"'a::{real_normed_field,banach}\"\n  unfolding eq_diff_eq by (rule sin_cos_squared_add2)\n\nlemma abs_sin_le_one [simp]: \"\\<bar>sin x\\<bar> \\<le> 1\"\n  for x :: real\n  by (rule power2_le_imp_le) (simp_all add: sin_squared_eq)\n\nlemma sin_ge_minus_one [simp]: \"- 1 \\<le> sin x\"\n  for x :: real\n  using abs_sin_le_one [of x] by (simp add: abs_le_iff)\n\nlemma sin_le_one [simp]: \"sin x \\<le> 1\"\n  for x :: real\n  using abs_sin_le_one [of x] by (simp add: abs_le_iff)\n\nlemma abs_cos_le_one [simp]: \"\\<bar>cos x\\<bar> \\<le> 1\"\n  for x :: real\n  by (rule power2_le_imp_le) (simp_all add: cos_squared_eq)\n\nlemma cos_ge_minus_one [simp]: \"- 1 \\<le> cos x\"\n  for x :: real\n  using abs_cos_le_one [of x] by (simp add: abs_le_iff)\n\nlemma cos_le_one [simp]: \"cos x \\<le> 1\"\n  for x :: real\n  using abs_cos_le_one [of x] by (simp add: abs_le_iff)\n\nlemma cos_diff: \"cos (x - y) = cos x * cos y + sin x * sin y\"\n  for x :: \"'a::{real_normed_field,banach}\"\n  using cos_add [of x \"- y\"] by simp\n\nlemma cos_double: \"cos(2*x) = (cos x)\\<^sup>2 - (sin x)\\<^sup>2\"\n  for x :: \"'a::{real_normed_field,banach}\"\n  using cos_add [where x=x and y=x] by (simp add: power2_eq_square)\n\nlemma sin_cos_le1: \"\\<bar>sin x * sin y + cos x * cos y\\<bar> \\<le> 1\"\n  for x :: real\n  using cos_diff [of x y] by (metis abs_cos_le_one add.commute)\n\nlemma DERIV_fun_pow: \"DERIV g x :> m \\<Longrightarrow> DERIV (\\<lambda>x. (g x) ^ n) x :> real n * (g x) ^ (n - 1) * m\"\n  by (auto intro!: derivative_eq_intros simp:)\n\nlemma DERIV_fun_exp: \"DERIV g x :> m \\<Longrightarrow> DERIV (\\<lambda>x. exp (g x)) x :> exp (g x) * m\"\n  by (auto intro!: derivative_intros)\n\n\nsubsection \\<open>The Constant Pi\\<close>\n\ndefinition pi :: real\n  where \"pi = 2 * (THE x. 0 \\<le> x \\<and> x \\<le> 2 \\<and> cos x = 0)\"\n\ntext \\<open>Show that there's a least positive \\<^term>\\<open>x\\<close> with \\<^term>\\<open>cos x = 0\\<close>;\n   hence define pi.\\<close>\n\nlemma sin_paired: \"(\\<lambda>n. (- 1) ^ n / (fact (2 * n + 1)) * x ^ (2 * n + 1)) sums  sin x\"\n  for x :: real\nproof -\n  have \"(\\<lambda>n. \\<Sum>k = n*2..<n * 2 + 2. sin_coeff k * x ^ k) sums sin x\"\n    by (rule sums_group) (use sin_converges [of x, unfolded scaleR_conv_of_real] in auto)\n  then show ?thesis\n    by (simp add: sin_coeff_def ac_simps)\nqed\n\nlemma sin_gt_zero_02:\n  fixes x :: real\n  assumes \"0 < x\" and \"x < 2\"\n  shows \"0 < sin x\"\nproof -\n  let ?f = \"\\<lambda>n::nat. \\<Sum>k = n*2..<n*2+2. (- 1) ^ k / (fact (2*k+1)) * x^(2*k+1)\"\n  have pos: \"\\<forall>n. 0 < ?f n\"\n  proof\n    fix n :: nat\n    let ?k2 = \"real (Suc (Suc (4 * n)))\"\n    let ?k3 = \"real (Suc (Suc (Suc (4 * n))))\"\n    have \"x * x < ?k2 * ?k3\"\n      using assms by (intro mult_strict_mono', simp_all)\n    then have \"x * x * x * x ^ (n * 4) < ?k2 * ?k3 * x * x ^ (n * 4)\"\n      by (intro mult_strict_right_mono zero_less_power \\<open>0 < x\\<close>)\n    then show \"0 < ?f n\"\n      by (simp add: ac_simps divide_less_eq)\nqed\n  have sums: \"?f sums sin x\"\n    by (rule sin_paired [THEN sums_group]) simp\n  show \"0 < sin x\"\n    unfolding sums_unique [OF sums] using sums_summable [OF sums] pos by (simp add: suminf_pos)\nqed\n\nlemma cos_double_less_one: \"0 < x \\<Longrightarrow> x < 2 \\<Longrightarrow> cos (2 * x) < 1\"\n  for x :: real\n  using sin_gt_zero_02 [where x = x] by (auto simp: cos_squared_eq cos_double)\n\nlemma cos_paired: \"(\\<lambda>n. (- 1) ^ n / (fact (2 * n)) * x ^ (2 * n)) sums cos x\"\n  for x :: real\nproof -\n  have \"(\\<lambda>n. \\<Sum>k = n * 2..<n * 2 + 2. cos_coeff k * x ^ k) sums cos x\"\n    by (rule sums_group) (use cos_converges [of x, unfolded scaleR_conv_of_real] in auto)\n  then show ?thesis\n    by (simp add: cos_coeff_def ac_simps)\nqed\n\nlemma sum_pos_lt_pair:\n  fixes f :: \"nat \\<Rightarrow> real\"\n  assumes f: \"summable f\" and fplus: \"\\<And>d. 0 < f (k + (Suc(Suc 0) * d)) + f (k + ((Suc (Suc 0) * d) + 1))\"\n  shows \"sum f {..<k} < suminf f\"\nproof -\n  have \"(\\<lambda>n. \\<Sum>n = n * Suc (Suc 0)..<n * Suc (Suc 0) +  Suc (Suc 0). f (n + k)) \n             sums (\\<Sum>n. f (n + k))\"\n  proof (rule sums_group)\n    show \"(\\<lambda>n. f (n + k)) sums (\\<Sum>n. f (n + k))\"\n      by (simp add: f summable_iff_shift summable_sums)\n  qed auto\n  with fplus have \"0 < (\\<Sum>n. f (n + k))\"\n    apply (simp add: add.commute)\n    apply (metis (no_types, lifting) suminf_pos summable_def sums_unique)\n    done\n  then show ?thesis\n    by (simp add: f suminf_minus_initial_segment)\nqed\n\nlemma cos_two_less_zero [simp]: \"cos 2 < (0::real)\"\nproof -\n  note fact_Suc [simp del]\n  from sums_minus [OF cos_paired]\n  have *: \"(\\<lambda>n. - ((- 1) ^ n * 2 ^ (2 * n) / fact (2 * n))) sums - cos (2::real)\"\n    by simp\n  then have sm: \"summable (\\<lambda>n. - ((- 1::real) ^ n * 2 ^ (2 * n) / (fact (2 * n))))\"\n    by (rule sums_summable)\n  have \"0 < (\\<Sum>n<Suc (Suc (Suc 0)). - ((- 1::real) ^ n * 2 ^ (2 * n) / (fact (2 * n))))\"\n    by (simp add: fact_num_eq_if power_eq_if)\n  moreover have \"(\\<Sum>n<Suc (Suc (Suc 0)). - ((- 1::real) ^ n  * 2 ^ (2 * n) / (fact (2 * n)))) <\n    (\\<Sum>n. - ((- 1) ^ n * 2 ^ (2 * n) / (fact (2 * n))))\"\n  proof -\n    {\n      fix d\n      let ?six4d = \"Suc (Suc (Suc (Suc (Suc (Suc (4 * d))))))\"\n      have \"(4::real) * (fact (?six4d)) < (Suc (Suc (?six4d)) * fact (Suc (?six4d)))\"\n        unfolding of_nat_mult by (rule mult_strict_mono) (simp_all add: fact_less_mono)\n      then have \"(4::real) * (fact (?six4d)) < (fact (Suc (Suc (?six4d))))\"\n        by (simp only: fact_Suc [of \"Suc (?six4d)\"] of_nat_mult of_nat_fact)\n      then have \"(4::real) * inverse (fact (Suc (Suc (?six4d)))) < inverse (fact (?six4d))\"\n        by (simp add: inverse_eq_divide less_divide_eq)\n    }\n    then show ?thesis\n      by (force intro!: sum_pos_lt_pair [OF sm] simp add: divide_inverse algebra_simps)\n  qed\n  ultimately have \"0 < (\\<Sum>n. - ((- 1::real) ^ n * 2 ^ (2 * n) / (fact (2 * n))))\"\n    by (rule order_less_trans)\n  moreover from * have \"- cos 2 = (\\<Sum>n. - ((- 1::real) ^ n * 2 ^ (2 * n) / (fact (2 * n))))\"\n    by (rule sums_unique)\n  ultimately have \"(0::real) < - cos 2\" by simp\n  then show ?thesis by simp\nqed\n\nlemmas cos_two_neq_zero [simp] = cos_two_less_zero [THEN less_imp_neq]\nlemmas cos_two_le_zero [simp] = cos_two_less_zero [THEN order_less_imp_le]\n\nlemma cos_is_zero: \"\\<exists>!x::real. 0 \\<le> x \\<and> x \\<le> 2 \\<and> cos x = 0\"\nproof (rule ex_ex1I)\n  show \"\\<exists>x::real. 0 \\<le> x \\<and> x \\<le> 2 \\<and> cos x = 0\"\n    by (rule IVT2) simp_all\nnext\n  fix a b :: real\n  assume ab: \"0 \\<le> a \\<and> a \\<le> 2 \\<and> cos a = 0\" \"0 \\<le> b \\<and> b \\<le> 2 \\<and> cos b = 0\"\n  have cosd: \"\\<And>x::real. cos differentiable (at x)\"\n    unfolding real_differentiable_def by (auto intro: DERIV_cos)\n  show \"a = b\"\n  proof (cases a b rule: linorder_cases)\n    case less\n    then obtain z where \"a < z\" \"z < b\" \"(cos has_real_derivative 0) (at z)\"\n      using Rolle by (metis cosd continuous_on_cos_real ab)\n    then have \"sin z = 0\"\n      using DERIV_cos DERIV_unique neg_equal_0_iff_equal by blast\n    then show ?thesis\n      by (metis \\<open>a < z\\<close> \\<open>z < b\\<close> ab order_less_le_trans less_le sin_gt_zero_02)\n  next\n    case greater\n    then obtain z where \"b < z\" \"z < a\" \"(cos has_real_derivative 0) (at z)\"\n      using Rolle by (metis cosd continuous_on_cos_real ab)\n    then have \"sin z = 0\"\n      using DERIV_cos DERIV_unique neg_equal_0_iff_equal by blast\n    then show ?thesis\n      by (metis \\<open>b < z\\<close> \\<open>z < a\\<close> ab order_less_le_trans less_le sin_gt_zero_02)\n  qed auto\nqed\n\nlemma pi_half: \"pi/2 = (THE x. 0 \\<le> x \\<and> x \\<le> 2 \\<and> cos x = 0)\"\n  by (simp add: pi_def)\n\nlemma cos_pi_half [simp]: \"cos (pi/2) = 0\"\n  by (simp add: pi_half cos_is_zero [THEN theI'])\n\nlemma cos_of_real_pi_half [simp]: \"cos ((of_real pi/2) :: 'a) = 0\"\n  if \"SORT_CONSTRAINT('a::{real_field,banach,real_normed_algebra_1})\"\n  by (metis cos_pi_half cos_of_real eq_numeral_simps(4)\n      nonzero_of_real_divide of_real_0 of_real_numeral)\n\nlemma pi_half_gt_zero [simp]: \"0 < pi/2\"\nproof -\n  have \"0 \\<le> pi/2\"\n    by (simp add: pi_half cos_is_zero [THEN theI'])\n  then show ?thesis\n    by (metis cos_pi_half cos_zero less_eq_real_def one_neq_zero)\nqed\n\nlemmas pi_half_neq_zero [simp] = pi_half_gt_zero [THEN less_imp_neq, symmetric]\nlemmas pi_half_ge_zero [simp] = pi_half_gt_zero [THEN order_less_imp_le]\n\nlemma pi_half_less_two [simp]: \"pi/2 < 2\"\nproof -\n  have \"pi/2 \\<le> 2\"\n    by (simp add: pi_half cos_is_zero [THEN theI'])\n  then show ?thesis\n    by (metis cos_pi_half cos_two_neq_zero le_less)\nqed\n\nlemmas pi_half_neq_two [simp] = pi_half_less_two [THEN less_imp_neq]\nlemmas pi_half_le_two [simp] =  pi_half_less_two [THEN order_less_imp_le]\n\nlemma pi_gt_zero [simp]: \"0 < pi\"\n  using pi_half_gt_zero by simp\n\nlemma pi_ge_zero [simp]: \"0 \\<le> pi\"\n  by (rule pi_gt_zero [THEN order_less_imp_le])\n\nlemma pi_neq_zero [simp]: \"pi \\<noteq> 0\"\n  by (rule pi_gt_zero [THEN less_imp_neq, symmetric])\n\nlemma pi_not_less_zero [simp]: \"\\<not> pi < 0\"\n  by (simp add: linorder_not_less)\n\nlemma minus_pi_half_less_zero: \"-(pi/2) < 0\"\n  by simp\n\nlemma m2pi_less_pi: \"- (2*pi) < pi\"\n  by simp\n\nlemma sin_pi_half [simp]: \"sin(pi/2) = 1\"\n  using sin_cos_squared_add2 [where x = \"pi/2\"]\n  using sin_gt_zero_02 [OF pi_half_gt_zero pi_half_less_two]\n  by (simp add: power2_eq_1_iff)\n\nlemma sin_of_real_pi_half [simp]: \"sin ((of_real pi/2) :: 'a) = 1\"\n  if \"SORT_CONSTRAINT('a::{real_field,banach,real_normed_algebra_1})\"\n  using sin_pi_half\n  by (metis sin_pi_half eq_numeral_simps(4) nonzero_of_real_divide of_real_1 of_real_numeral sin_of_real)\n\nlemma sin_cos_eq: \"sin x = cos (of_real pi/2 - x)\"\n  for x :: \"'a::{real_normed_field,banach}\"\n  by (simp add: cos_diff)\n\nlemma minus_sin_cos_eq: \"- sin x = cos (x + of_real pi/2)\"\n  for x :: \"'a::{real_normed_field,banach}\"\n  by (simp add: cos_add nonzero_of_real_divide)\n\nlemma cos_sin_eq: \"cos x = sin (of_real pi/2 - x)\"\n  for x :: \"'a::{real_normed_field,banach}\"\n  using sin_cos_eq [of \"of_real pi/2 - x\"] by simp\n\nlemma sin_add: \"sin (x + y) = sin x * cos y + cos x * sin y\"\n  for x :: \"'a::{real_normed_field,banach}\"\n  using cos_add [of \"of_real pi/2 - x\" \"-y\"]\n  by (simp add: cos_sin_eq) (simp add: sin_cos_eq)\n\nlemma sin_diff: \"sin (x - y) = sin x * cos y - cos x * sin y\"\n  for x :: \"'a::{real_normed_field,banach}\"\n  using sin_add [of x \"- y\"] by simp\n\nlemma sin_double: \"sin(2 * x) = 2 * sin x * cos x\"\n  for x :: \"'a::{real_normed_field,banach}\"\n  using sin_add [where x=x and y=x] by simp\n\nlemma cos_of_real_pi [simp]: \"cos (of_real pi) = -1\"\n  using cos_add [where x = \"pi/2\" and y = \"pi/2\"]\n  by (simp add: cos_of_real)\n\nlemma sin_of_real_pi [simp]: \"sin (of_real pi) = 0\"\n  using sin_add [where x = \"pi/2\" and y = \"pi/2\"]\n  by (simp add: sin_of_real)\n\nlemma cos_pi [simp]: \"cos pi = -1\"\n  using cos_add [where x = \"pi/2\" and y = \"pi/2\"] by simp\n\nlemma sin_pi [simp]: \"sin pi = 0\"\n  using sin_add [where x = \"pi/2\" and y = \"pi/2\"] by simp\n\nlemma sin_periodic_pi [simp]: \"sin (x + pi) = - sin x\"\n  by (simp add: sin_add)\n\nlemma sin_periodic_pi2 [simp]: \"sin (pi + x) = - sin x\"\n  by (simp add: sin_add)\n\nlemma cos_periodic_pi [simp]: \"cos (x + pi) = - cos x\"\n  by (simp add: cos_add)\n\nlemma cos_periodic_pi2 [simp]: \"cos (pi + x) = - cos x\"\n  by (simp add: cos_add)\n\nlemma sin_periodic [simp]: \"sin (x + 2 * pi) = sin x\"\n  by (simp add: sin_add sin_double cos_double)\n\nlemma cos_periodic [simp]: \"cos (x + 2 * pi) = cos x\"\n  by (simp add: cos_add sin_double cos_double)\n\nlemma cos_npi [simp]: \"cos (real n * pi) = (- 1) ^ n\"\n  by (induct n) (auto simp: distrib_right)\n\nlemma cos_npi2 [simp]: \"cos (pi * real n) = (- 1) ^ n\"\n  by (metis cos_npi mult.commute)\n\nlemma sin_npi [simp]: \"sin (real n * pi) = 0\"\n  for n :: nat\n  by (induct n) (auto simp: distrib_right)\n\nlemma sin_npi2 [simp]: \"sin (pi * real n) = 0\"\n  for n :: nat\n  by (simp add: mult.commute [of pi])\n\nlemma cos_two_pi [simp]: \"cos (2 * pi) = 1\"\n  by (simp add: cos_double)\n\nlemma sin_two_pi [simp]: \"sin (2 * pi) = 0\"\n  by (simp add: sin_double)\n\ncontext\n  fixes w :: \"'a::{real_normed_field,banach}\"\n\nbegin\n\nlemma sin_times_sin: \"sin w * sin z = (cos (w - z) - cos (w + z)) / 2\"\n  by (simp add: cos_diff cos_add)\n\nlemma sin_times_cos: \"sin w * cos z = (sin (w + z) + sin (w - z)) / 2\"\n  by (simp add: sin_diff sin_add)\n\nlemma cos_times_sin: \"cos w * sin z = (sin (w + z) - sin (w - z)) / 2\"\n  by (simp add: sin_diff sin_add)\n\nlemma cos_times_cos: \"cos w * cos z = (cos (w - z) + cos (w + z)) / 2\"\n  by (simp add: cos_diff cos_add)\n\nlemma cos_double_cos: \"cos (2 * w) = 2 * cos w ^ 2 - 1\"\n  by (simp add: cos_double sin_squared_eq)\n\nlemma cos_double_sin: \"cos (2 * w) = 1 - 2 * sin w ^ 2\"\n  by (simp add: cos_double sin_squared_eq)\n\nend\n\nlemma sin_plus_sin: \"sin w + sin z = 2 * sin ((w + z) / 2) * cos ((w - z) / 2)\"\n  for w :: \"'a::{real_normed_field,banach}\" \n  apply (simp add: mult.assoc sin_times_cos)\n  apply (simp add: field_simps)\n  done\n\nlemma sin_diff_sin: \"sin w - sin z = 2 * sin ((w - z) / 2) * cos ((w + z) / 2)\"\n  for w :: \"'a::{real_normed_field,banach}\"\n  apply (simp add: mult.assoc sin_times_cos)\n  apply (simp add: field_simps)\n  done\n\nlemma cos_plus_cos: \"cos w + cos z = 2 * cos ((w + z) / 2) * cos ((w - z) / 2)\"\n  for w :: \"'a::{real_normed_field,banach,field}\"\n  apply (simp add: mult.assoc cos_times_cos)\n  apply (simp add: field_simps)\n  done\n\nlemma cos_diff_cos: \"cos w - cos z = 2 * sin ((w + z) / 2) * sin ((z - w) / 2)\"\n  for w :: \"'a::{real_normed_field,banach,field}\"\n  apply (simp add: mult.assoc sin_times_sin)\n  apply (simp add: field_simps)\n  done\n\nlemma sin_pi_minus [simp]: \"sin (pi - x) = sin x\"\n  by (metis sin_minus sin_periodic_pi minus_minus uminus_add_conv_diff)\n\nlemma cos_pi_minus [simp]: \"cos (pi - x) = - (cos x)\"\n  by (metis cos_minus cos_periodic_pi uminus_add_conv_diff)\n\nlemma sin_minus_pi [simp]: \"sin (x - pi) = - (sin x)\"\n  by (simp add: sin_diff)\n\nlemma cos_minus_pi [simp]: \"cos (x - pi) = - (cos x)\"\n  by (simp add: cos_diff)\n\nlemma sin_2pi_minus [simp]: \"sin (2 * pi - x) = - (sin x)\"\n  by (metis sin_periodic_pi2 add_diff_eq mult_2 sin_pi_minus)\n\nlemma cos_2pi_minus [simp]: \"cos (2 * pi - x) = cos x\"\n  by (metis (no_types, opaque_lifting) cos_add cos_minus cos_two_pi sin_minus sin_two_pi\n      diff_0_right minus_diff_eq mult_1 mult_zero_left uminus_add_conv_diff)\n\nlemma sin_gt_zero2: \"0 < x \\<Longrightarrow> x < pi/2 \\<Longrightarrow> 0 < sin x\"\n  by (metis sin_gt_zero_02 order_less_trans pi_half_less_two)\n\nlemma sin_less_zero:\n  assumes \"- pi/2 < x\" and \"x < 0\"\n  shows \"sin x < 0\"\nproof -\n  have \"0 < sin (- x)\"\n    using assms by (simp only: sin_gt_zero2)\n  then show ?thesis by simp\nqed\n\nlemma pi_less_4: \"pi < 4\"\n  using pi_half_less_two by auto\n\nlemma cos_gt_zero: \"0 < x \\<Longrightarrow> x < pi/2 \\<Longrightarrow> 0 < cos x\"\n  by (simp add: cos_sin_eq sin_gt_zero2)\n\nlemma cos_gt_zero_pi: \"-(pi/2) < x \\<Longrightarrow> x < pi/2 \\<Longrightarrow> 0 < cos x\"\n  using cos_gt_zero [of x] cos_gt_zero [of \"-x\"]\n  by (cases rule: linorder_cases [of x 0]) auto\n\nlemma cos_ge_zero: \"-(pi/2) \\<le> x \\<Longrightarrow> x \\<le> pi/2 \\<Longrightarrow> 0 \\<le> cos x\"\n  by (auto simp: order_le_less cos_gt_zero_pi)\n    (metis cos_pi_half eq_divide_eq eq_numeral_simps(4))\n\nlemma sin_gt_zero: \"0 < x \\<Longrightarrow> x < pi \\<Longrightarrow> 0 < sin x\"\n  by (simp add: sin_cos_eq cos_gt_zero_pi)\n\nlemma sin_lt_zero: \"pi < x \\<Longrightarrow> x < 2 * pi \\<Longrightarrow> sin x < 0\"\n  using sin_gt_zero [of \"x - pi\"]\n  by (simp add: sin_diff)\n\nlemma pi_ge_two: \"2 \\<le> pi\"\nproof (rule ccontr)\n  assume \"\\<not> ?thesis\"\n  then have \"pi < 2\" by auto\n  have \"\\<exists>y > pi. y < 2 \\<and> y < 2 * pi\"\n  proof (cases \"2 < 2 * pi\")\n    case True\n    with dense[OF \\<open>pi < 2\\<close>] show ?thesis by auto\n  next\n    case False\n    have \"pi < 2 * pi\" by auto\n    from dense[OF this] and False show ?thesis by auto\n  qed\n  then obtain y where \"pi < y\" and \"y < 2\" and \"y < 2 * pi\"\n    by blast\n  then have \"0 < sin y\"\n    using sin_gt_zero_02 by auto\n  moreover have \"sin y < 0\"\n    using sin_gt_zero[of \"y - pi\"] \\<open>pi < y\\<close> and \\<open>y < 2 * pi\\<close> sin_periodic_pi[of \"y - pi\"]\n    by auto\n  ultimately show False by auto\nqed\n\nlemma sin_ge_zero: \"0 \\<le> x \\<Longrightarrow> x \\<le> pi \\<Longrightarrow> 0 \\<le> sin x\"\n  by (auto simp: order_le_less sin_gt_zero)\n\nlemma sin_le_zero: \"pi \\<le> x \\<Longrightarrow> x < 2 * pi \\<Longrightarrow> sin x \\<le> 0\"\n  using sin_ge_zero [of \"x - pi\"] by (simp add: sin_diff)\n\nlemma sin_pi_divide_n_ge_0 [simp]:\n  assumes \"n \\<noteq> 0\"\n  shows \"0 \\<le> sin (pi/real n)\"\n  by (rule sin_ge_zero) (use assms in \\<open>simp_all add: field_split_simps\\<close>)\n\nlemma sin_pi_divide_n_gt_0:\n  assumes \"2 \\<le> n\"\n  shows \"0 < sin (pi/real n)\"\n  by (rule sin_gt_zero) (use assms in \\<open>simp_all add: field_split_simps\\<close>)\n\ntext\\<open>Proof resembles that of \\<open>cos_is_zero\\<close> but with \\<^term>\\<open>pi\\<close> for the upper bound\\<close>\nlemma cos_total:\n  assumes y: \"-1 \\<le> y\" \"y \\<le> 1\"\n  shows \"\\<exists>!x. 0 \\<le> x \\<and> x \\<le> pi \\<and> cos x = y\"\nproof (rule ex_ex1I)\n  show \"\\<exists>x::real. 0 \\<le> x \\<and> x \\<le> pi \\<and> cos x = y\"\n    by (rule IVT2) (simp_all add: y)\nnext\n  fix a b :: real\n  assume ab: \"0 \\<le> a \\<and> a \\<le> pi \\<and> cos a = y\" \"0 \\<le> b \\<and> b \\<le> pi \\<and> cos b = y\"\n  have cosd: \"\\<And>x::real. cos differentiable (at x)\"\n    unfolding real_differentiable_def by (auto intro: DERIV_cos)\n  show \"a = b\"\n  proof (cases a b rule: linorder_cases)\n    case less\n    then obtain z where \"a < z\" \"z < b\" \"(cos has_real_derivative 0) (at z)\"\n      using Rolle by (metis cosd continuous_on_cos_real ab)\n    then have \"sin z = 0\"\n      using DERIV_cos DERIV_unique neg_equal_0_iff_equal by blast\n    then show ?thesis\n      by (metis \\<open>a < z\\<close> \\<open>z < b\\<close> ab order_less_le_trans less_le sin_gt_zero)\n  next\n    case greater\n    then obtain z where \"b < z\" \"z < a\" \"(cos has_real_derivative 0) (at z)\"\n      using Rolle by (metis cosd continuous_on_cos_real ab)\n    then have \"sin z = 0\"\n      using DERIV_cos DERIV_unique neg_equal_0_iff_equal by blast\n    then show ?thesis\n      by (metis \\<open>b < z\\<close> \\<open>z < a\\<close> ab order_less_le_trans less_le sin_gt_zero)\n  qed auto\nqed\n\nlemma sin_total:\n  assumes y: \"-1 \\<le> y\" \"y \\<le> 1\"\n  shows \"\\<exists>!x. - (pi/2) \\<le> x \\<and> x \\<le> pi/2 \\<and> sin x = y\"\nproof -\n  from cos_total [OF y]\n  obtain x where x: \"0 \\<le> x\" \"x \\<le> pi\" \"cos x = y\"\n    and uniq: \"\\<And>x'. 0 \\<le> x' \\<Longrightarrow> x' \\<le> pi \\<Longrightarrow> cos x' = y \\<Longrightarrow> x' = x \"\n    by blast\n  show ?thesis\n    unfolding sin_cos_eq\n  proof (rule ex1I [where a=\"pi/2 - x\"])\n    show \"- (pi/2) \\<le> z \\<and> z \\<le> pi/2 \\<and> cos (of_real pi/2 - z) = y \\<Longrightarrow>\n          z = pi/2 - x\" for z\n      using uniq [of \"pi/2 -z\"] by auto\n  qed (use x in auto)\nqed\n\nlemma cos_zero_lemma:\n  assumes \"0 \\<le> x\" \"cos x = 0\"\n  shows \"\\<exists>n. odd n \\<and> x = of_nat n * (pi/2)\"\nproof -\n  have xle: \"x < (1 + real_of_int \\<lfloor>x/pi\\<rfloor>) * pi\"\n    using floor_correct [of \"x/pi\"]\n    by (simp add: add.commute divide_less_eq)\n  obtain n where \"real n * pi \\<le> x\" \"x < real (Suc n) * pi\"\n  proof \n    show \"real (nat \\<lfloor>x / pi\\<rfloor>) * pi \\<le> x\"\n      using assms floor_divide_lower [of pi x] by auto\n    show \"x < real (Suc (nat \\<lfloor>x / pi\\<rfloor>)) * pi\"\n      using assms floor_divide_upper [of pi x]  by (simp add: xle)\n  qed\n  then have x: \"0 \\<le> x - n * pi\" \"(x - n * pi) \\<le> pi\" \"cos (x - n * pi) = 0\"\n    by (auto simp: algebra_simps cos_diff assms)\n  then have \"\\<exists>!x. 0 \\<le> x \\<and> x \\<le> pi \\<and> cos x = 0\"\n    by (auto simp: intro!: cos_total)\n  then obtain \\<theta> where \\<theta>: \"0 \\<le> \\<theta>\" \"\\<theta> \\<le> pi\" \"cos \\<theta> = 0\"\n    and uniq: \"\\<And>\\<phi>. 0 \\<le> \\<phi> \\<Longrightarrow> \\<phi> \\<le> pi \\<Longrightarrow> cos \\<phi> = 0 \\<Longrightarrow> \\<phi> = \\<theta>\"\n    by blast\n  then have \"x - real n * pi = \\<theta>\"\n    using x by blast\n  moreover have \"pi/2 = \\<theta>\"\n    using pi_half_ge_zero uniq by fastforce\n  ultimately show ?thesis\n    by (rule_tac x = \"Suc (2 * n)\" in exI) (simp add: algebra_simps)\nqed\n\nlemma sin_zero_lemma:\n  assumes \"0 \\<le> x\" \"sin x = 0\"\n  shows \"\\<exists>n::nat. even n \\<and> x = real n * (pi/2)\"\nproof -\n  obtain n where \"odd n\" and n: \"x + pi/2 = of_nat n * (pi/2)\" \"n > 0\"\n    using cos_zero_lemma [of \"x + pi/2\"] assms by (auto simp add: cos_add)\n  then have \"x = real (n - 1) * (pi/2)\"\n    by (simp add: algebra_simps of_nat_diff)\n  then show ?thesis\n    by (simp add: \\<open>odd n\\<close>)\nqed\n\nlemma cos_zero_iff:\n  \"cos x = 0 \\<longleftrightarrow> ((\\<exists>n. odd n \\<and> x = real n * (pi/2)) \\<or> (\\<exists>n. odd n \\<and> x = - (real n * (pi/2))))\"\n  (is \"?lhs = ?rhs\")\nproof -\n  have *: \"cos (real n * pi/2) = 0\" if \"odd n\" for n :: nat\n  proof -\n    from that obtain m where \"n = 2 * m + 1\" ..\n    then show ?thesis\n      by (simp add: field_simps) (simp add: cos_add add_divide_distrib)\n  qed\n  show ?thesis\n  proof\n    show ?rhs if ?lhs\n      using that cos_zero_lemma [of x] cos_zero_lemma [of \"-x\"] by force\n    show ?lhs if ?rhs\n      using that by (auto dest: * simp del: eq_divide_eq_numeral1)\n  qed\nqed\n\nlemma sin_zero_iff:\n  \"sin x = 0 \\<longleftrightarrow> ((\\<exists>n. even n \\<and> x = real n * (pi/2)) \\<or> (\\<exists>n. even n \\<and> x = - (real n * (pi/2))))\"\n  (is \"?lhs = ?rhs\")\nproof\n  show ?rhs if ?lhs\n    using that sin_zero_lemma [of x] sin_zero_lemma [of \"-x\"] by force\n  show ?lhs if ?rhs\n    using that by (auto elim: evenE)\nqed\n\nlemma sin_zero_pi_iff:\n  fixes x::real\n  assumes \"\\<bar>x\\<bar> < pi\"\n  shows \"sin x = 0 \\<longleftrightarrow> x = 0\"\nproof\n  show \"x = 0\" if \"sin x = 0\"\n    using that assms by (auto simp: sin_zero_iff)\nqed auto\n\nlemma cos_zero_iff_int: \"cos x = 0 \\<longleftrightarrow> (\\<exists>i. odd i \\<and> x = of_int i * (pi/2))\"\nproof -\n  have 1: \"\\<And>n. odd n \\<Longrightarrow> \\<exists>i. odd i \\<and> real n = real_of_int i\"\n    by (metis even_of_nat_iff of_int_of_nat_eq)\n  have 2: \"\\<And>n. odd n \\<Longrightarrow> \\<exists>i. odd i \\<and> - (real n * pi) = real_of_int i * pi\"\n    by (metis even_minus even_of_nat_iff mult.commute mult_minus_right of_int_minus of_int_of_nat_eq)\n  have 3: \"\\<lbrakk>odd i;  \\<forall>n. even n \\<or> real_of_int i \\<noteq> - (real n)\\<rbrakk>\n         \\<Longrightarrow> \\<exists>n. odd n \\<and> real_of_int i = real n\" for i\n    by (cases i rule: int_cases2) auto\n  show ?thesis\n    by (force simp: cos_zero_iff intro!: 1 2 3)\nqed\n\nlemma sin_zero_iff_int: \"sin x = 0 \\<longleftrightarrow> (\\<exists>i. even i \\<and> x = of_int i * (pi/2))\" (is \"?lhs = ?rhs\")\nproof safe\n  assume ?lhs\n  then consider (plus) n where \"even n\" \"x = real n * (pi/2)\" | (minus) n where \"even n\"  \"x = - (real n * (pi/2))\"\n    using sin_zero_iff by auto\n  then show \"\\<exists>n. even n \\<and> x = of_int n * (pi/2)\"\n  proof cases\n    case plus\n    then show ?rhs\n      by (metis even_of_nat_iff of_int_of_nat_eq)\n  next\n    case minus\n    then show ?thesis\n      by (rule_tac x=\"- (int n)\" in exI) simp\n  qed\nnext\n  fix i :: int\n  assume \"even i\"\n  then show \"sin (of_int i * (pi/2)) = 0\"\n    by (cases i rule: int_cases2, simp_all add: sin_zero_iff)\nqed\n\nlemma sin_zero_iff_int2: \"sin x = 0 \\<longleftrightarrow> (\\<exists>i::int. x = of_int i * pi)\"\nproof -\n  have \"sin x = 0 \\<longleftrightarrow> (\\<exists>i. even i \\<and> x = real_of_int i * (pi/2))\"\n    by (auto simp: sin_zero_iff_int)\n  also have \"... = (\\<exists>j. x = real_of_int (2*j) * (pi/2))\"\n    using dvd_triv_left by blast\n  also have \"... = (\\<exists>i::int. x = of_int i * pi)\"\n    by auto\n  finally show ?thesis .\nqed\n\nlemma cos_zero_iff_int2:\n  fixes x::real\n  shows \"cos x = 0 \\<longleftrightarrow> (\\<exists>n::int. x = n * pi +  pi/2)\"\n  using sin_zero_iff_int2[of \"x-pi/2\"] unfolding sin_cos_eq \n  by (auto simp add: algebra_simps)\n\nlemma sin_npi_int [simp]: \"sin (pi * of_int n) = 0\"\n  by (simp add: sin_zero_iff_int2)\n\nlemma cos_monotone_0_pi:\n  assumes \"0 \\<le> y\" and \"y < x\" and \"x \\<le> pi\"\n  shows \"cos x < cos y\"\nproof -\n  have \"- (x - y) < 0\" using assms by auto\n  from MVT2[OF \\<open>y < x\\<close> DERIV_cos]\n  obtain z where \"y < z\" and \"z < x\" and cos_diff: \"cos x - cos y = (x - y) * - sin z\"\n    by auto\n  then have \"0 < z\" and \"z < pi\"\n    using assms by auto\n  then have \"0 < sin z\"\n    using sin_gt_zero by auto\n  then have \"cos x - cos y < 0\"\n    unfolding cos_diff minus_mult_commute[symmetric]\n    using \\<open>- (x - y) < 0\\<close> by (rule mult_pos_neg2)\n  then show ?thesis by auto\nqed\n\nlemma cos_monotone_0_pi_le:\n  assumes \"0 \\<le> y\" and \"y \\<le> x\" and \"x \\<le> pi\"\n  shows \"cos x \\<le> cos y\"\nproof (cases \"y < x\")\n  case True\n  show ?thesis\n    using cos_monotone_0_pi[OF \\<open>0 \\<le> y\\<close> True \\<open>x \\<le> pi\\<close>] by auto\nnext\n  case False\n  then have \"y = x\" using \\<open>y \\<le> x\\<close> by auto\n  then show ?thesis by auto\nqed\n\nlemma cos_monotone_minus_pi_0:\n  assumes \"- pi \\<le> y\" and \"y < x\" and \"x \\<le> 0\"\n  shows \"cos y < cos x\"\nproof -\n  have \"0 \\<le> - x\" and \"- x < - y\" and \"- y \\<le> pi\"\n    using assms by auto\n  from cos_monotone_0_pi[OF this] show ?thesis\n    unfolding cos_minus .\nqed\n\nlemma cos_monotone_minus_pi_0':\n  assumes \"- pi \\<le> y\" and \"y \\<le> x\" and \"x \\<le> 0\"\n  shows \"cos y \\<le> cos x\"\nproof (cases \"y < x\")\n  case True\n  show ?thesis using cos_monotone_minus_pi_0[OF \\<open>-pi \\<le> y\\<close> True \\<open>x \\<le> 0\\<close>]\n    by auto\nnext\n  case False\n  then have \"y = x\" using \\<open>y \\<le> x\\<close> by auto\n  then show ?thesis by auto\nqed\n\nlemma sin_monotone_2pi:\n  assumes \"- (pi/2) \\<le> y\" and \"y < x\" and \"x \\<le> pi/2\"\n  shows \"sin y < sin x\"\n  unfolding sin_cos_eq\n  using assms by (auto intro: cos_monotone_0_pi)\n\nlemma sin_monotone_2pi_le:\n  assumes \"- (pi/2) \\<le> y\" and \"y \\<le> x\" and \"x \\<le> pi/2\"\n  shows \"sin y \\<le> sin x\"\n  by (metis assms le_less sin_monotone_2pi)\n\nlemma sin_x_le_x:\n  fixes x :: real\n  assumes \"x \\<ge> 0\"\n  shows \"sin x \\<le> x\"\nproof -\n  let ?f = \"\\<lambda>x. x - sin x\"\n  have \"\\<And>u. \\<lbrakk>0 \\<le> u; u \\<le> x\\<rbrakk> \\<Longrightarrow> \\<exists>y. (?f has_real_derivative 1 - cos u) (at u)\"\n    by (auto intro!: derivative_eq_intros simp: field_simps)\n  then have \"?f x \\<ge> ?f 0\"\n    by (metis cos_le_one diff_ge_0_iff_ge DERIV_nonneg_imp_nondecreasing [OF assms])\n  then show \"sin x \\<le> x\" by simp\nqed\n\nlemma sin_x_ge_neg_x:\n  fixes x :: real\n  assumes x: \"x \\<ge> 0\"\n  shows \"sin x \\<ge> - x\"\nproof -\n  let ?f = \"\\<lambda>x. x + sin x\"\n  have \\<section>: \"\\<And>u. \\<lbrakk>0 \\<le> u; u \\<le> x\\<rbrakk> \\<Longrightarrow> \\<exists>y. (?f has_real_derivative 1 + cos u) (at u)\"\n    by (auto intro!: derivative_eq_intros simp: field_simps)\n  have \"?f x \\<ge> ?f 0\"\n    by (rule DERIV_nonneg_imp_nondecreasing [OF assms]) (use \\<section> real_0_le_add_iff in force)\n  then show \"sin x \\<ge> -x\" by simp\nqed\n\nlemma abs_sin_x_le_abs_x: \"\\<bar>sin x\\<bar> \\<le> \\<bar>x\\<bar>\"\n  for x :: real\n  using sin_x_ge_neg_x [of x] sin_x_le_x [of x] sin_x_ge_neg_x [of \"-x\"] sin_x_le_x [of \"-x\"]\n  by (auto simp: abs_real_def)\n\n\nsubsection \\<open>More Corollaries about Sine and Cosine\\<close>\n\nlemma sin_cos_npi [simp]: \"sin (real (Suc (2 * n)) * pi/2) = (-1) ^ n\"\nproof -\n  have \"sin ((real n + 1/2) * pi) = cos (real n * pi)\"\n    by (auto simp: algebra_simps sin_add)\n  then show ?thesis\n    by (simp add: distrib_right add_divide_distrib add.commute mult.commute [of pi])\nqed\n\nlemma cos_2npi [simp]: \"cos (2 * real n * pi) = 1\"\n  for n :: nat\n  by (cases \"even n\") (simp_all add: cos_double mult.assoc)\n\nlemma cos_3over2_pi [simp]: \"cos (3/2*pi) = 0\"\nproof -\n  have \"cos (3/2*pi) = cos (pi + pi/2)\"\n    by simp\n  also have \"... = 0\"\n    by (subst cos_add, simp)\n  finally show ?thesis .\nqed\n\nlemma sin_2npi [simp]: \"sin (2 * real n * pi) = 0\"\n  for n :: nat\n  by (auto simp: mult.assoc sin_double)\n\nlemma sin_3over2_pi [simp]: \"sin (3/2*pi) = - 1\"\nproof -\n  have \"sin (3/2*pi) = sin (pi + pi/2)\"\n    by simp\n  also have \"... = -1\"\n    by (subst sin_add, simp)\n  finally show ?thesis .\nqed\n\nlemma cos_pi_eq_zero [simp]: \"cos (pi * real (Suc (2 * m)) / 2) = 0\"\n  by (simp only: cos_add sin_add of_nat_Suc distrib_right distrib_left add_divide_distrib, auto)\n\nlemma DERIV_cos_add [simp]: \"DERIV (\\<lambda>x. cos (x + k)) xa :> - sin (xa + k)\"\n  by (auto intro!: derivative_eq_intros)\n\nlemma sin_zero_norm_cos_one:\n  fixes x :: \"'a::{real_normed_field,banach}\"\n  assumes \"sin x = 0\"\n  shows \"norm (cos x) = 1\"\n  using sin_cos_squared_add [of x, unfolded assms]\n  by (simp add: square_norm_one)\n\nlemma sin_zero_abs_cos_one: \"sin x = 0 \\<Longrightarrow> \\<bar>cos x\\<bar> = (1::real)\"\n  using sin_zero_norm_cos_one by fastforce\n\nlemma cos_one_sin_zero:\n  fixes x :: \"'a::{real_normed_field,banach}\"\n  assumes \"cos x = 1\"\n  shows \"sin x = 0\"\n  using sin_cos_squared_add [of x, unfolded assms]\n  by simp\n\nlemma sin_times_pi_eq_0: \"sin (x * pi) = 0 \\<longleftrightarrow> x \\<in> \\<int>\"\n  by (simp add: sin_zero_iff_int2) (metis Ints_cases Ints_of_int)\n\nlemma cos_one_2pi: \"cos x = 1 \\<longleftrightarrow> (\\<exists>n::nat. x = n * 2 * pi) \\<or> (\\<exists>n::nat. x = - (n * 2 * pi))\"\n  (is \"?lhs = ?rhs\")\nproof\n  assume ?lhs\n  then have \"sin x = 0\"\n    by (simp add: cos_one_sin_zero)\n  then show ?rhs\n  proof (simp only: sin_zero_iff, elim exE disjE conjE)\n    fix n :: nat\n    assume n: \"even n\" \"x = real n * (pi/2)\"\n    then obtain m where m: \"n = 2 * m\"\n      using dvdE by blast\n    then have me: \"even m\" using \\<open>?lhs\\<close> n\n      by (auto simp: field_simps) (metis one_neq_neg_one  power_minus_odd power_one)\n    show ?rhs\n      using m me n\n      by (auto simp: field_simps elim!: evenE)\n  next\n    fix n :: nat\n    assume n: \"even n\" \"x = - (real n * (pi/2))\"\n    then obtain m where m: \"n = 2 * m\"\n      using dvdE by blast\n    then have me: \"even m\" using \\<open>?lhs\\<close> n\n      by (auto simp: field_simps) (metis one_neq_neg_one  power_minus_odd power_one)\n    show ?rhs\n      using m me n\n      by (auto simp: field_simps elim!: evenE)\n  qed\nnext\n  assume ?rhs\n  then show \"cos x = 1\"\n    by (metis cos_2npi cos_minus mult.assoc mult.left_commute)\nqed\n\nlemma cos_one_2pi_int: \"cos x = 1 \\<longleftrightarrow> (\\<exists>n::int. x = n * 2 * pi)\" (is \"?lhs = ?rhs\")\nproof\n  assume \"cos x = 1\"\n  then show ?rhs\n    by (metis cos_one_2pi mult.commute mult_minus_right of_int_minus of_int_of_nat_eq)\nnext\n  assume ?rhs\n  then show \"cos x = 1\"\n    by (clarsimp simp add: cos_one_2pi) (metis mult_minus_right of_int_of_nat)\nqed\n\nlemma cos_npi_int [simp]:\n  fixes n::int shows \"cos (pi * of_int n) = (if even n then 1 else -1)\"\n    by (auto simp: algebra_simps cos_one_2pi_int elim!: oddE evenE)\n\nlemma sin_cos_sqrt: \"0 \\<le> sin x \\<Longrightarrow> sin x = sqrt (1 - (cos(x) ^ 2))\"\n  using sin_squared_eq real_sqrt_unique by fastforce\n\nlemma sin_eq_0_pi: \"- pi < x \\<Longrightarrow> x < pi \\<Longrightarrow> sin x = 0 \\<Longrightarrow> x = 0\"\n  by (metis sin_gt_zero sin_minus minus_less_iff neg_0_less_iff_less not_less_iff_gr_or_eq)\n\nlemma cos_treble_cos: \"cos (3 * x) = 4 * cos x ^ 3 - 3 * cos x\"\n  for x :: \"'a::{real_normed_field,banach}\"\nproof -\n  have *: \"(sin x * (sin x * 3)) = 3 - (cos x * (cos x * 3))\"\n    by (simp add: mult.assoc [symmetric] sin_squared_eq [unfolded power2_eq_square])\n  have \"cos(3 * x) = cos(2*x + x)\"\n    by simp\n  also have \"\\<dots> = 4 * cos x ^ 3 - 3 * cos x\"\n    unfolding cos_add cos_double sin_double\n    by (simp add: * field_simps power2_eq_square power3_eq_cube)\n  finally show ?thesis .\nqed\n\nlemma cos_45: \"cos (pi/4) = sqrt 2 / 2\"\nproof -\n  let ?c = \"cos (pi/4)\"\n  let ?s = \"sin (pi/4)\"\n  have nonneg: \"0 \\<le> ?c\"\n    by (simp add: cos_ge_zero)\n  have \"0 = cos (pi/4 + pi/4)\"\n    by simp\n  also have \"cos (pi/4 + pi/4) = ?c\\<^sup>2 - ?s\\<^sup>2\"\n    by (simp only: cos_add power2_eq_square)\n  also have \"\\<dots> = 2 * ?c\\<^sup>2 - 1\"\n    by (simp add: sin_squared_eq)\n  finally have \"?c\\<^sup>2 = (sqrt 2 / 2)\\<^sup>2\"\n    by (simp add: power_divide)\n  then show ?thesis\n    using nonneg by (rule power2_eq_imp_eq) simp\nqed\n\nlemma cos_30: \"cos (pi/6) = sqrt 3/2\"\nproof -\n  let ?c = \"cos (pi/6)\"\n  let ?s = \"sin (pi/6)\"\n  have pos_c: \"0 < ?c\"\n    by (rule cos_gt_zero) simp_all\n  have \"0 = cos (pi/6 + pi/6 + pi/6)\"\n    by simp\n  also have \"\\<dots> = (?c * ?c - ?s * ?s) * ?c - (?s * ?c + ?c * ?s) * ?s\"\n    by (simp only: cos_add sin_add)\n  also have \"\\<dots> = ?c * (?c\\<^sup>2 - 3 * ?s\\<^sup>2)\"\n    by (simp add: algebra_simps power2_eq_square)\n  finally have \"?c\\<^sup>2 = (sqrt 3/2)\\<^sup>2\"\n    using pos_c by (simp add: sin_squared_eq power_divide)\n  then show ?thesis\n    using pos_c [THEN order_less_imp_le]\n    by (rule power2_eq_imp_eq) simp\nqed\n\nlemma sin_45: \"sin (pi/4) = sqrt 2 / 2\"\n  by (simp add: sin_cos_eq cos_45)\n\nlemma sin_60: \"sin (pi/3) = sqrt 3/2\"\n  by (simp add: sin_cos_eq cos_30)\n\nlemma cos_60: \"cos (pi/3) = 1/2\"\nproof -\n  have \"0 \\<le> cos (pi/3)\"\n    by (rule cos_ge_zero) (use pi_half_ge_zero in \\<open>linarith+\\<close>)\n  then show ?thesis\n    by (simp add: cos_squared_eq sin_60 power_divide power2_eq_imp_eq)\nqed\n\nlemma sin_30: \"sin (pi/6) = 1/2\"\n  by (simp add: sin_cos_eq cos_60)\n\nlemma cos_120: \"cos (2 * pi/3) = -1/2\"\n  and sin_120: \"sin (2 * pi/3) = sqrt 3 / 2\"\n  using sin_double[of \"pi/3\"] cos_double[of \"pi/3\"]\n  by (simp_all add: power2_eq_square sin_60 cos_60)\n\nlemma cos_120': \"cos (pi * 2 / 3) = -1/2\"\n  using cos_120 by (subst mult.commute)\n\nlemma sin_120': \"sin (pi * 2 / 3) = sqrt 3 / 2\"\n  using sin_120 by (subst mult.commute)\n\nlemma cos_integer_2pi: \"n \\<in> \\<int> \\<Longrightarrow> cos(2 * pi * n) = 1\"\n  by (metis Ints_cases cos_one_2pi_int mult.assoc mult.commute)\n\nlemma sin_integer_2pi: \"n \\<in> \\<int> \\<Longrightarrow> sin(2 * pi * n) = 0\"\n  by (metis sin_two_pi Ints_mult mult.assoc mult.commute sin_times_pi_eq_0)\n\nlemma cos_int_2pin [simp]: \"cos ((2 * pi) * of_int n) = 1\"\n  by (simp add: cos_one_2pi_int)\n\nlemma sin_int_2pin [simp]: \"sin ((2 * pi) * of_int n) = 0\"\n  by (metis Ints_of_int sin_integer_2pi)\n\nlemma sincos_principal_value: \"\\<exists>y. (- pi < y \\<and> y \\<le> pi) \\<and> (sin y = sin x \\<and> cos y = cos x)\"\nproof -\n  define y where \"y \\<equiv> pi - (2 * pi) * frac ((pi - x) / (2 * pi))\"\n  have \"-pi < y\"\" y \\<le> pi\"\n    by (auto simp: field_simps frac_lt_1 y_def)\n  moreover\n  have \"sin y = sin x\" \"cos y = cos x\"\n    unfolding y_def\n     apply (simp_all add: frac_def divide_simps sin_add cos_add)\n    by (metis sin_int_2pin cos_int_2pin diff_zero add.right_neutral mult.commute mult.left_neutral mult_zero_left)+\n  ultimately\n  show ?thesis by metis\nqed\n\n\nsubsection \\<open>Tangent\\<close>\n\ndefinition tan :: \"'a \\<Rightarrow> 'a::{real_normed_field,banach}\"\n  where \"tan = (\\<lambda>x. sin x / cos x)\"\n\nlemma tan_of_real: \"of_real (tan x) = (tan (of_real x) :: 'a::{real_normed_field,banach})\"\n  by (simp add: tan_def sin_of_real cos_of_real)\n\nlemma tan_in_Reals [simp]: \"z \\<in> \\<real> \\<Longrightarrow> tan z \\<in> \\<real>\"\n  for z :: \"'a::{real_normed_field,banach}\"\n  by (simp add: tan_def)\n\nlemma tan_zero [simp]: \"tan 0 = 0\"\n  by (simp add: tan_def)\n\nlemma tan_pi [simp]: \"tan pi = 0\"\n  by (simp add: tan_def)\n\nlemma tan_npi [simp]: \"tan (real n * pi) = 0\"\n  for n :: nat\n  by (simp add: tan_def)\n\nlemma tan_pi_half [simp]: \"tan (pi / 2) = 0\"\n  by (simp add: tan_def)\n\nlemma tan_minus [simp]: \"tan (- x) = - tan x\"\n  by (simp add: tan_def)\n\nlemma tan_periodic [simp]: \"tan (x + 2 * pi) = tan x\"\n  by (simp add: tan_def)\n\nlemma lemma_tan_add1: \"cos x \\<noteq> 0 \\<Longrightarrow> cos y \\<noteq> 0 \\<Longrightarrow> 1 - tan x * tan y = cos (x + y)/(cos x * cos y)\"\n  by (simp add: tan_def cos_add field_simps)\n\nlemma add_tan_eq: \"cos x \\<noteq> 0 \\<Longrightarrow> cos y \\<noteq> 0 \\<Longrightarrow> tan x + tan y = sin(x + y)/(cos x * cos y)\"\n  for x :: \"'a::{real_normed_field,banach}\"\n  by (simp add: tan_def sin_add field_simps)\n\nlemma tan_eq_0_cos_sin: \"tan x = 0 \\<longleftrightarrow> cos x = 0 \\<or> sin x = 0\"\n  by (auto simp: tan_def)\n\ntext \\<open>Note: half of these zeros would normally be regarded as undefined cases.\\<close>\nlemma tan_eq_0_Ex:\n  assumes \"tan x = 0\"\n  obtains k::int where \"x = (k/2) * pi\"\n  using assms\n  by (metis cos_zero_iff_int mult.commute sin_zero_iff_int tan_eq_0_cos_sin times_divide_eq_left) \n\nlemma tan_add:\n  \"cos x \\<noteq> 0 \\<Longrightarrow> cos y \\<noteq> 0 \\<Longrightarrow> cos (x + y) \\<noteq> 0 \\<Longrightarrow> tan (x + y) = (tan x + tan y)/(1 - tan x * tan y)\"\n  for x :: \"'a::{real_normed_field,banach}\"\n  by (simp add: add_tan_eq lemma_tan_add1 field_simps) (simp add: tan_def)\n\nlemma tan_double: \"cos x \\<noteq> 0 \\<Longrightarrow> cos (2 * x) \\<noteq> 0 \\<Longrightarrow> tan (2 * x) = (2 * tan x) / (1 - (tan x)\\<^sup>2)\"\n  for x :: \"'a::{real_normed_field,banach}\"\n  using tan_add [of x x] by (simp add: power2_eq_square)\n\nlemma tan_gt_zero: \"0 < x \\<Longrightarrow> x < pi/2 \\<Longrightarrow> 0 < tan x\"\n  by (simp add: tan_def zero_less_divide_iff sin_gt_zero2 cos_gt_zero_pi)\n\nlemma tan_less_zero:\n  assumes \"- pi/2 < x\" and \"x < 0\"\n  shows \"tan x < 0\"\nproof -\n  have \"0 < tan (- x)\"\n    using assms by (simp only: tan_gt_zero)\n  then show ?thesis by simp\nqed\n\nlemma tan_half: \"tan x = sin (2 * x) / (cos (2 * x) + 1)\"\n  for x :: \"'a::{real_normed_field,banach,field}\"\n  unfolding tan_def sin_double cos_double sin_squared_eq\n  by (simp add: power2_eq_square)\n\nlemma tan_30: \"tan (pi/6) = 1 / sqrt 3\"\n  unfolding tan_def by (simp add: sin_30 cos_30)\n\nlemma tan_45: \"tan (pi/4) = 1\"\n  unfolding tan_def by (simp add: sin_45 cos_45)\n\nlemma tan_60: \"tan (pi/3) = sqrt 3\"\n  unfolding tan_def by (simp add: sin_60 cos_60)\n\nlemma DERIV_tan [simp]: \"cos x \\<noteq> 0 \\<Longrightarrow> DERIV tan x :> inverse ((cos x)\\<^sup>2)\"\n  for x :: \"'a::{real_normed_field,banach}\"\n  unfolding tan_def\n  by (auto intro!: derivative_eq_intros, simp add: divide_inverse power2_eq_square)\n\ndeclare DERIV_tan[THEN DERIV_chain2, derivative_intros]\n  and DERIV_tan[THEN DERIV_chain2, unfolded has_field_derivative_def, derivative_intros]\n\nlemmas has_derivative_tan[derivative_intros] = DERIV_tan[THEN DERIV_compose_FDERIV]\n\nlemma isCont_tan: \"cos x \\<noteq> 0 \\<Longrightarrow> isCont tan x\"\n  for x :: \"'a::{real_normed_field,banach}\"\n  by (rule DERIV_tan [THEN DERIV_isCont])\n\nlemma isCont_tan' [simp,continuous_intros]:\n  fixes a :: \"'a::{real_normed_field,banach}\" and f :: \"'a \\<Rightarrow> 'a\"\n  shows \"isCont f a \\<Longrightarrow> cos (f a) \\<noteq> 0 \\<Longrightarrow> isCont (\\<lambda>x. tan (f x)) a\"\n  by (rule isCont_o2 [OF _ isCont_tan])\n\nlemma tendsto_tan [tendsto_intros]:\n  fixes f :: \"'a \\<Rightarrow> 'a::{real_normed_field,banach}\"\n  shows \"(f \\<longlongrightarrow> a) F \\<Longrightarrow> cos a \\<noteq> 0 \\<Longrightarrow> ((\\<lambda>x. tan (f x)) \\<longlongrightarrow> tan a) F\"\n  by (rule isCont_tendsto_compose [OF isCont_tan])\n\nlemma continuous_tan:\n  fixes f :: \"'a \\<Rightarrow> 'a::{real_normed_field,banach}\"\n  shows \"continuous F f \\<Longrightarrow> cos (f (Lim F (\\<lambda>x. x))) \\<noteq> 0 \\<Longrightarrow> continuous F (\\<lambda>x. tan (f x))\"\n  unfolding continuous_def by (rule tendsto_tan)\n\nlemma continuous_on_tan [continuous_intros]:\n  fixes f :: \"'a \\<Rightarrow> 'a::{real_normed_field,banach}\"\n  shows \"continuous_on s f \\<Longrightarrow> (\\<forall>x\\<in>s. cos (f x) \\<noteq> 0) \\<Longrightarrow> continuous_on s (\\<lambda>x. tan (f x))\"\n  unfolding continuous_on_def by (auto intro: tendsto_tan)\n\nlemma continuous_within_tan [continuous_intros]:\n  fixes f :: \"'a \\<Rightarrow> 'a::{real_normed_field,banach}\"\n  shows \"continuous (at x within s) f \\<Longrightarrow>\n    cos (f x) \\<noteq> 0 \\<Longrightarrow> continuous (at x within s) (\\<lambda>x. tan (f x))\"\n  unfolding continuous_within by (rule tendsto_tan)\n\nlemma LIM_cos_div_sin: \"(\\<lambda>x. cos(x)/sin(x)) \\<midarrow>pi/2\\<rightarrow> 0\"\n  by (rule tendsto_cong_limit, (rule tendsto_intros)+, simp_all)\n\nlemma lemma_tan_total: \n  assumes \"0 < y\" shows \"\\<exists>x. 0 < x \\<and> x < pi/2 \\<and> y < tan x\"\nproof -\n  obtain s where \"0 < s\" \n    and s: \"\\<And>x. \\<lbrakk>x \\<noteq> pi/2; norm (x - pi/2) < s\\<rbrakk> \\<Longrightarrow> norm (cos x / sin x - 0) < inverse y\"\n    using LIM_D [OF LIM_cos_div_sin, of \"inverse y\"] that assms by force\n  obtain e where e: \"0 < e\" \"e < s\" \"e < pi/2\"\n    using \\<open>0 < s\\<close> field_lbound_gt_zero pi_half_gt_zero by blast\n  show ?thesis\n  proof (intro exI conjI)\n    have \"0 < sin e\" \"0 < cos e\"\n      using e by (auto intro: cos_gt_zero sin_gt_zero2 simp: mult.commute)\n    then \n    show \"y < tan (pi/2 - e)\"\n      using s [of \"pi/2 - e\"] e assms\n      by (simp add: tan_def sin_diff cos_diff) (simp add: field_simps split: if_split_asm)\n  qed (use e in auto)\nqed\n\nlemma tan_total_pos: \n  assumes \"0 \\<le> y\" shows \"\\<exists>x. 0 \\<le> x \\<and> x < pi/2 \\<and> tan x = y\"\nproof (cases \"y = 0\")\n  case True\n  then show ?thesis\n    using pi_half_gt_zero tan_zero by blast\nnext\n  case False\n  with assms have \"y > 0\"\n    by linarith\n  obtain x where x: \"0 < x\" \"x < pi/2\" \"y < tan x\"\n    using lemma_tan_total \\<open>0 < y\\<close> by blast\n  have \"\\<exists>u\\<ge>0. u \\<le> x \\<and> tan u = y\"\n  proof (intro IVT allI impI)\n    show \"isCont tan u\" if \"0 \\<le> u \\<and> u \\<le> x\" for u\n    proof -\n      have \"cos u \\<noteq> 0\"\n        using antisym_conv2 cos_gt_zero that x(2) by fastforce\n      with assms show ?thesis\n        by (auto intro!: DERIV_tan [THEN DERIV_isCont])\n    qed\n  qed (use assms x in auto)\n  then show ?thesis\n    using x(2) by auto\nqed\n    \nlemma lemma_tan_total1: \"\\<exists>x. -(pi/2) < x \\<and> x < (pi/2) \\<and> tan x = y\"\nproof (cases \"0::real\" y rule: le_cases)\n  case le\n  then show ?thesis\n    by (meson less_le_trans minus_pi_half_less_zero tan_total_pos)\nnext\n  case ge\n  with tan_total_pos [of \"-y\"] obtain x where \"0 \\<le> x\" \"x < pi/2\" \"tan x = - y\"\n    by force\n  then show ?thesis\n    by (rule_tac x=\"-x\" in exI) auto\nqed\n\nproposition tan_total: \"\\<exists>! x. -(pi/2) < x \\<and> x < (pi/2) \\<and> tan x = y\"\nproof -\n  have \"u = v\" if u: \"- (pi/2) < u\" \"u < pi/2\" and v: \"- (pi/2) < v\" \"v < pi/2\"\n    and eq: \"tan u = tan v\" for u v\n  proof (cases u v rule: linorder_cases)\n    case less\n    have \"\\<And>x. u \\<le> x \\<and> x \\<le> v \\<longrightarrow> isCont tan x\"\n      by (metis cos_gt_zero_pi isCont_tan le_less_trans less_irrefl less_le_trans u(1) v(2))\n    then have \"continuous_on {u..v} tan\"\n      by (simp add: continuous_at_imp_continuous_on)\n    moreover have \"\\<And>x. u < x \\<and> x < v \\<Longrightarrow> tan differentiable (at x)\"\n      by (metis DERIV_tan cos_gt_zero_pi real_differentiable_def less_numeral_extra(3) order.strict_trans u(1) v(2))\n    ultimately obtain z where \"u < z\" \"z < v\" \"DERIV tan z :> 0\"\n      by (metis less Rolle eq)\n    moreover have \"cos z \\<noteq> 0\"\n      by (metis (no_types) \\<open>u < z\\<close> \\<open>z < v\\<close> cos_gt_zero_pi less_le_trans linorder_not_less not_less_iff_gr_or_eq u(1) v(2))\n    ultimately show ?thesis\n      using DERIV_unique [OF _ DERIV_tan] by fastforce\n  next\n    case greater\n    have \"\\<And>x. v \\<le> x \\<and> x \\<le> u \\<Longrightarrow> isCont tan x\"\n      by (metis cos_gt_zero_pi isCont_tan le_less_trans less_irrefl less_le_trans u(2) v(1))\n    then have \"continuous_on {v..u} tan\"\n      by (simp add: continuous_at_imp_continuous_on)\n    moreover have \"\\<And>x. v < x \\<and> x < u \\<Longrightarrow> tan differentiable (at x)\"\n      by (metis DERIV_tan cos_gt_zero_pi real_differentiable_def less_numeral_extra(3) order.strict_trans u(2) v(1))\n    ultimately obtain z where \"v < z\" \"z < u\" \"DERIV tan z :> 0\"\n      by (metis greater Rolle eq)\n    moreover have \"cos z \\<noteq> 0\"\n      by (metis \\<open>v < z\\<close> \\<open>z < u\\<close> cos_gt_zero_pi less_eq_real_def less_le_trans order_less_irrefl u(2) v(1))\n    ultimately show ?thesis\n      using DERIV_unique [OF _ DERIV_tan] by fastforce\n  qed auto\n  then have \"\\<exists>!x. - (pi/2) < x \\<and> x < pi/2 \\<and> tan x = y\" \n    if x: \"- (pi/2) < x\" \"x < pi/2\" \"tan x = y\" for x\n    using that by auto\n  then show ?thesis\n    using lemma_tan_total1 [where y = y]\n    by auto\nqed\n\nlemma tan_monotone:\n  assumes \"- (pi/2) < y\" and \"y < x\" and \"x < pi/2\"\n  shows \"tan y < tan x\"\nproof -\n  have \"DERIV tan x' :> inverse ((cos x')\\<^sup>2)\" if \"y \\<le> x'\" \"x' \\<le> x\" for x'\n  proof -\n    have \"-(pi/2) < x'\" and \"x' < pi/2\"\n      using that assms by auto\n    with cos_gt_zero_pi have \"cos x' \\<noteq> 0\" by force\n    then show \"DERIV tan x' :> inverse ((cos x')\\<^sup>2)\"\n      by (rule DERIV_tan)\n  qed\n  from MVT2[OF \\<open>y < x\\<close> this]\n  obtain z where \"y < z\" and \"z < x\"\n    and tan_diff: \"tan x - tan y = (x - y) * inverse ((cos z)\\<^sup>2)\" by auto\n  then have \"- (pi/2) < z\" and \"z < pi/2\"\n    using assms by auto\n  then have \"0 < cos z\"\n    using cos_gt_zero_pi by auto\n  then have inv_pos: \"0 < inverse ((cos z)\\<^sup>2)\"\n    by auto\n  have \"0 < x - y\" using \\<open>y < x\\<close> by auto\n  with inv_pos have \"0 < tan x - tan y\"\n    unfolding tan_diff by auto\n  then show ?thesis by auto\nqed\n\nlemma tan_monotone':\n  assumes \"- (pi/2) < y\"\n    and \"y < pi/2\"\n    and \"- (pi/2) < x\"\n    and \"x < pi/2\"\n  shows \"y < x \\<longleftrightarrow> tan y < tan x\"\nproof\n  assume \"y < x\"\n  then show \"tan y < tan x\"\n    using tan_monotone and \\<open>- (pi/2) < y\\<close> and \\<open>x < pi/2\\<close> by auto\nnext\n  assume \"tan y < tan x\"\n  show \"y < x\"\n  proof (rule ccontr)\n    assume \"\\<not> ?thesis\"\n    then have \"x \\<le> y\" by auto\n    then have \"tan x \\<le> tan y\"\n    proof (cases \"x = y\")\n      case True\n      then show ?thesis by auto\n    next\n      case False\n      then have \"x < y\" using \\<open>x \\<le> y\\<close> by auto\n      from tan_monotone[OF \\<open>- (pi/2) < x\\<close> this \\<open>y < pi/2\\<close>] show ?thesis\n        by auto\n    qed\n    then show False\n      using \\<open>tan y < tan x\\<close> by auto\n  qed\nqed\n\nlemma tan_inverse: \"1 / (tan y) = tan (pi/2 - y)\"\n  unfolding tan_def sin_cos_eq[of y] cos_sin_eq[of y] by auto\n\nlemma tan_periodic_pi[simp]: \"tan (x + pi) = tan x\"\n  by (simp add: tan_def)\n\nlemma tan_periodic_nat[simp]: \"tan (x + real n * pi) = tan x\"\nproof (induct n arbitrary: x)\n  case 0\n  then show ?case by simp\nnext\n  case (Suc n)\n  have split_pi_off: \"x + real (Suc n) * pi = (x + real n * pi) + pi\"\n    unfolding Suc_eq_plus1 of_nat_add  distrib_right by auto\n  show ?case\n    unfolding split_pi_off using Suc by auto\nqed\n\nlemma tan_periodic_int[simp]: \"tan (x + of_int i * pi) = tan x\"\nproof (cases \"0 \\<le> i\")\n  case False\n  then have i_nat: \"of_int i = - of_int (nat (- i))\" by auto\n  then show ?thesis\n    by (smt (verit, best) mult_minus_left of_int_of_nat_eq tan_periodic_nat)\nqed (use zero_le_imp_eq_int in fastforce)\n\nlemma tan_periodic_n[simp]: \"tan (x + numeral n * pi) = tan x\"\n  using tan_periodic_int[of _ \"numeral n\" ] by simp\n\nlemma tan_minus_45 [simp]: \"tan (-(pi/4)) = -1\"\n  unfolding tan_def by (simp add: sin_45 cos_45)\n\nlemma tan_diff:\n  \"cos x \\<noteq> 0 \\<Longrightarrow> cos y \\<noteq> 0 \\<Longrightarrow> cos (x - y) \\<noteq> 0 \\<Longrightarrow> tan (x - y) = (tan x - tan y)/(1 + tan x * tan y)\"\n  for x :: \"'a::{real_normed_field,banach}\"\n  using tan_add [of x \"-y\"] by simp\n\nlemma tan_pos_pi2_le: \"0 \\<le> x \\<Longrightarrow> x < pi/2 \\<Longrightarrow> 0 \\<le> tan x\"\n  using less_eq_real_def tan_gt_zero by auto\n\nlemma cos_tan: \"\\<bar>x\\<bar> < pi/2 \\<Longrightarrow> cos x = 1 / sqrt (1 + tan x ^ 2)\"\n  using cos_gt_zero_pi [of x]\n  by (simp add: field_split_simps tan_def real_sqrt_divide abs_if split: if_split_asm)\n\nlemma cos_tan_half: \"cos x \\<noteq>0 \\<Longrightarrow>  cos (2*x) = (1 - (tan x)^2) / (1 + (tan x)^2)\"\n  unfolding cos_double tan_def by (auto simp add:field_simps )\n\nlemma sin_tan: \"\\<bar>x\\<bar> < pi/2 \\<Longrightarrow> sin x = tan x / sqrt (1 + tan x ^ 2)\"\n  using cos_gt_zero [of \"x\"] cos_gt_zero [of \"-x\"]\n  by (force simp: field_split_simps tan_def real_sqrt_divide abs_if split: if_split_asm)\n\nlemma sin_tan_half: \"sin (2*x) = 2 * tan x / (1 + (tan x)^2)\"\n  unfolding sin_double tan_def\n  by (cases \"cos x=0\") (auto simp add:field_simps power2_eq_square)\n\nlemma tan_mono_le: \"-(pi/2) < x \\<Longrightarrow> x \\<le> y \\<Longrightarrow> y < pi/2 \\<Longrightarrow> tan x \\<le> tan y\"\n  using less_eq_real_def tan_monotone by auto\n\nlemma tan_mono_lt_eq:\n  \"-(pi/2) < x \\<Longrightarrow> x < pi/2 \\<Longrightarrow> -(pi/2) < y \\<Longrightarrow> y < pi/2 \\<Longrightarrow> tan x < tan y \\<longleftrightarrow> x < y\"\n  using tan_monotone' by blast\n\nlemma tan_mono_le_eq:\n  \"-(pi/2) < x \\<Longrightarrow> x < pi/2 \\<Longrightarrow> -(pi/2) < y \\<Longrightarrow> y < pi/2 \\<Longrightarrow> tan x \\<le> tan y \\<longleftrightarrow> x \\<le> y\"\n  by (meson tan_mono_le not_le tan_monotone)\n\nlemma tan_bound_pi2: \"\\<bar>x\\<bar> < pi/4 \\<Longrightarrow> \\<bar>tan x\\<bar> < 1\"\n  using tan_45 tan_monotone [of x \"pi/4\"] tan_monotone [of \"-x\" \"pi/4\"]\n  by (auto simp: abs_if split: if_split_asm)\n\nlemma tan_cot: \"tan(pi/2 - x) = inverse(tan x)\"\n  by (simp add: tan_def sin_diff cos_diff)\n\n\nsubsection \\<open>Cotangent\\<close>\n\ndefinition cot :: \"'a \\<Rightarrow> 'a::{real_normed_field,banach}\"\n  where \"cot = (\\<lambda>x. cos x / sin x)\"\n\nlemma cot_of_real: \"of_real (cot x) = (cot (of_real x) :: 'a::{real_normed_field,banach})\"\n  by (simp add: cot_def sin_of_real cos_of_real)\n\nlemma cot_in_Reals [simp]: \"z \\<in> \\<real> \\<Longrightarrow> cot z \\<in> \\<real>\"\n  for z :: \"'a::{real_normed_field,banach}\"\n  by (simp add: cot_def)\n\nlemma cot_zero [simp]: \"cot 0 = 0\"\n  by (simp add: cot_def)\n\nlemma cot_pi [simp]: \"cot pi = 0\"\n  by (simp add: cot_def)\n\nlemma cot_npi [simp]: \"cot (real n * pi) = 0\"\n  for n :: nat\n  by (simp add: cot_def)\n\nlemma cot_minus [simp]: \"cot (- x) = - cot x\"\n  by (simp add: cot_def)\n\nlemma cot_periodic [simp]: \"cot (x + 2 * pi) = cot x\"\n  by (simp add: cot_def)\n\nlemma cot_altdef: \"cot x = inverse (tan x)\"\n  by (simp add: cot_def tan_def)\n\nlemma tan_altdef: \"tan x = inverse (cot x)\"\n  by (simp add: cot_def tan_def)\n\nlemma tan_cot': \"tan (pi/2 - x) = cot x\"\n  by (simp add: tan_cot cot_altdef)\n\nlemma cot_gt_zero: \"0 < x \\<Longrightarrow> x < pi/2 \\<Longrightarrow> 0 < cot x\"\n  by (simp add: cot_def zero_less_divide_iff sin_gt_zero2 cos_gt_zero_pi)\n\nlemma cot_less_zero:\n  assumes lb: \"- pi/2 < x\" and \"x < 0\"\n  shows \"cot x < 0\"\n  by (smt (verit) assms cot_gt_zero cot_minus divide_minus_left)\n\nlemma DERIV_cot [simp]: \"sin x \\<noteq> 0 \\<Longrightarrow> DERIV cot x :> -inverse ((sin x)\\<^sup>2)\"\n  for x :: \"'a::{real_normed_field,banach}\"\n  unfolding cot_def using cos_squared_eq[of x]\n  by (auto intro!: derivative_eq_intros) (simp add: divide_inverse power2_eq_square)\n\nlemma isCont_cot: \"sin x \\<noteq> 0 \\<Longrightarrow> isCont cot x\"\n  for x :: \"'a::{real_normed_field,banach}\"\n  by (rule DERIV_cot [THEN DERIV_isCont])\n\nlemma isCont_cot' [simp,continuous_intros]:\n  \"isCont f a \\<Longrightarrow> sin (f a) \\<noteq> 0 \\<Longrightarrow> isCont (\\<lambda>x. cot (f x)) a\"\n  for a :: \"'a::{real_normed_field,banach}\" and f :: \"'a \\<Rightarrow> 'a\"\n  by (rule isCont_o2 [OF _ isCont_cot])\n\nlemma tendsto_cot [tendsto_intros]: \"(f \\<longlongrightarrow> a) F \\<Longrightarrow> sin a \\<noteq> 0 \\<Longrightarrow> ((\\<lambda>x. cot (f x)) \\<longlongrightarrow> cot a) F\"\n  for f :: \"'a \\<Rightarrow> 'a::{real_normed_field,banach}\"\n  by (rule isCont_tendsto_compose [OF isCont_cot])\n\nlemma continuous_cot:\n  \"continuous F f \\<Longrightarrow> sin (f (Lim F (\\<lambda>x. x))) \\<noteq> 0 \\<Longrightarrow> continuous F (\\<lambda>x. cot (f x))\"\n  for f :: \"'a \\<Rightarrow> 'a::{real_normed_field,banach}\"\n  unfolding continuous_def by (rule tendsto_cot)\n\nlemma continuous_on_cot [continuous_intros]:\n  fixes f :: \"'a \\<Rightarrow> 'a::{real_normed_field,banach}\"\n  shows \"continuous_on s f \\<Longrightarrow> (\\<forall>x\\<in>s. sin (f x) \\<noteq> 0) \\<Longrightarrow> continuous_on s (\\<lambda>x. cot (f x))\"\n  unfolding continuous_on_def by (auto intro: tendsto_cot)\n\nlemma continuous_within_cot [continuous_intros]:\n  fixes f :: \"'a \\<Rightarrow> 'a::{real_normed_field,banach}\"\n  shows \"continuous (at x within s) f \\<Longrightarrow> sin (f x) \\<noteq> 0 \\<Longrightarrow> continuous (at x within s) (\\<lambda>x. cot (f x))\"\n  unfolding continuous_within by (rule tendsto_cot)\n\n\nsubsection \\<open>Inverse Trigonometric Functions\\<close>\n\ndefinition arcsin :: \"real \\<Rightarrow> real\"\n  where \"arcsin y = (THE x. -(pi/2) \\<le> x \\<and> x \\<le> pi/2 \\<and> sin x = y)\"\n\ndefinition arccos :: \"real \\<Rightarrow> real\"\n  where \"arccos y = (THE x. 0 \\<le> x \\<and> x \\<le> pi \\<and> cos x = y)\"\n\ndefinition arctan :: \"real \\<Rightarrow> real\"\n  where \"arctan y = (THE x. -(pi/2) < x \\<and> x < pi/2 \\<and> tan x = y)\"\n\nlemma arcsin: \"- 1 \\<le> y \\<Longrightarrow> y \\<le> 1 \\<Longrightarrow> - (pi/2) \\<le> arcsin y \\<and> arcsin y \\<le> pi/2 \\<and> sin (arcsin y) = y\"\n  unfolding arcsin_def by (rule theI' [OF sin_total])\n\nlemma arcsin_pi: \"- 1 \\<le> y \\<Longrightarrow> y \\<le> 1 \\<Longrightarrow> - (pi/2) \\<le> arcsin y \\<and> arcsin y \\<le> pi \\<and> sin (arcsin y) = y\"\n  by (drule (1) arcsin) (force intro: order_trans)\n\nlemma sin_arcsin [simp]: \"- 1 \\<le> y \\<Longrightarrow> y \\<le> 1 \\<Longrightarrow> sin (arcsin y) = y\"\n  by (blast dest: arcsin)\n\nlemma arcsin_bounded: \"- 1 \\<le> y \\<Longrightarrow> y \\<le> 1 \\<Longrightarrow> - (pi/2) \\<le> arcsin y \\<and> arcsin y \\<le> pi/2\"\n  by (blast dest: arcsin)\n\nlemma arcsin_lbound: \"- 1 \\<le> y \\<Longrightarrow> y \\<le> 1 \\<Longrightarrow> - (pi/2) \\<le> arcsin y\"\n  by (blast dest: arcsin)\n\nlemma arcsin_ubound: \"- 1 \\<le> y \\<Longrightarrow> y \\<le> 1 \\<Longrightarrow> arcsin y \\<le> pi/2\"\n  by (blast dest: arcsin)\n\nlemma arcsin_lt_bounded:\n  assumes \"- 1 < y\" \"y < 1\"\n  shows  \"- (pi/2) < arcsin y \\<and> arcsin y < pi/2\"\nproof -\n  have \"arcsin y \\<noteq> pi/2\"\n    by (metis arcsin assms not_less not_less_iff_gr_or_eq sin_pi_half)\n  moreover have \"arcsin y \\<noteq> - pi/2\"\n    by (metis arcsin assms minus_divide_left not_less not_less_iff_gr_or_eq sin_minus sin_pi_half)\n  ultimately show ?thesis\n    using arcsin_bounded [of y] assms by auto\nqed\n\nlemma arcsin_sin: \"- (pi/2) \\<le> x \\<Longrightarrow> x \\<le> pi/2 \\<Longrightarrow> arcsin (sin x) = x\"\n  unfolding arcsin_def\n  using the1_equality [OF sin_total]  by simp\n\nlemma arcsin_unique:\n  assumes \"-pi/2 \\<le> x\" and \"x \\<le> pi/2\" and \"sin x = y\" shows \"arcsin y = x\"\n  using arcsin_sin[of x] assms by force\n\nlemma arcsin_0 [simp]: \"arcsin 0 = 0\"\n  using arcsin_sin [of 0] by simp\n\nlemma arcsin_1 [simp]: \"arcsin 1 = pi/2\"\n  using arcsin_sin [of \"pi/2\"] by simp\n\nlemma arcsin_minus_1 [simp]: \"arcsin (- 1) = - (pi/2)\"\n  using arcsin_sin [of \"- pi/2\"] by simp\n\nlemma arcsin_minus: \"- 1 \\<le> x \\<Longrightarrow> x \\<le> 1 \\<Longrightarrow> arcsin (- x) = - arcsin x\"\n  by (metis (no_types, opaque_lifting) arcsin arcsin_sin minus_minus neg_le_iff_le sin_minus)\n\nlemma arcsin_one_half [simp]: \"arcsin (1/2) = pi / 6\"\n  and arcsin_minus_one_half [simp]: \"arcsin (-(1/2)) = -pi / 6\"\n  by (intro arcsin_unique; simp add: sin_30 field_simps)+\n  \nlemma arcsin_one_over_sqrt_2: \"arcsin (1 / sqrt 2) = pi / 4\"\n  by (rule arcsin_unique) (auto simp: sin_45 field_simps)\n\nlemma arcsin_eq_iff: \"\\<bar>x\\<bar> \\<le> 1 \\<Longrightarrow> \\<bar>y\\<bar> \\<le> 1 \\<Longrightarrow> arcsin x = arcsin y \\<longleftrightarrow> x = y\"\n  by (metis abs_le_iff arcsin minus_le_iff)\n\nlemma cos_arcsin_nonzero: \"- 1 < x \\<Longrightarrow> x < 1 \\<Longrightarrow> cos (arcsin x) \\<noteq> 0\"\n  using arcsin_lt_bounded cos_gt_zero_pi by force\n\nlemma arccos: \"- 1 \\<le> y \\<Longrightarrow> y \\<le> 1 \\<Longrightarrow> 0 \\<le> arccos y \\<and> arccos y \\<le> pi \\<and> cos (arccos y) = y\"\n  unfolding arccos_def by (rule theI' [OF cos_total])\n\nlemma cos_arccos [simp]: \"- 1 \\<le> y \\<Longrightarrow> y \\<le> 1 \\<Longrightarrow> cos (arccos y) = y\"\n  by (blast dest: arccos)\n\nlemma arccos_bounded: \"- 1 \\<le> y \\<Longrightarrow> y \\<le> 1 \\<Longrightarrow> 0 \\<le> arccos y \\<and> arccos y \\<le> pi\"\n  by (blast dest: arccos)\n\nlemma arccos_lbound: \"- 1 \\<le> y \\<Longrightarrow> y \\<le> 1 \\<Longrightarrow> 0 \\<le> arccos y\"\n  by (blast dest: arccos)\n\nlemma arccos_ubound: \"- 1 \\<le> y \\<Longrightarrow> y \\<le> 1 \\<Longrightarrow> arccos y \\<le> pi\"\n  by (blast dest: arccos)\n\nlemma arccos_lt_bounded: \n  assumes \"- 1 < y\" \"y < 1\"\n  shows  \"0 < arccos y \\<and> arccos y < pi\"\nproof -\n  have \"arccos y \\<noteq> 0\"\n    by (metis (no_types) arccos assms(1) assms(2) cos_zero less_eq_real_def less_irrefl)\n  moreover have \"arccos y \\<noteq> -pi\"\n    by (metis arccos assms(1) assms(2) cos_minus cos_pi not_less not_less_iff_gr_or_eq)\n  ultimately show ?thesis\n    using arccos_bounded [of y] assms\n    by (metis arccos cos_pi not_less not_less_iff_gr_or_eq)\nqed\n\nlemma arccos_cos: \"0 \\<le> x \\<Longrightarrow> x \\<le> pi \\<Longrightarrow> arccos (cos x) = x\"\n  by (auto simp: arccos_def intro!: the1_equality cos_total)\n\nlemma arccos_cos2: \"x \\<le> 0 \\<Longrightarrow> - pi \\<le> x \\<Longrightarrow> arccos (cos x) = -x\"\n  by (auto simp: arccos_def intro!: the1_equality cos_total)\n\nlemma arccos_unique:\n  assumes \"0 \\<le> x\" and \"x \\<le> pi\" and \"cos x = y\" shows \"arccos y = x\"\n  using arccos_cos assms by blast\n\nlemma cos_arcsin:\n  assumes \"- 1 \\<le> x\" \"x \\<le> 1\"\n  shows \"cos (arcsin x) = sqrt (1 - x\\<^sup>2)\"\nproof (rule power2_eq_imp_eq)\n  show \"(cos (arcsin x))\\<^sup>2 = (sqrt (1 - x\\<^sup>2))\\<^sup>2\"\n    by (simp add: square_le_1 assms cos_squared_eq)\n  show \"0 \\<le> cos (arcsin x)\"\n    using arcsin assms cos_ge_zero by blast\n  show \"0 \\<le> sqrt (1 - x\\<^sup>2)\"\n    by (simp add: square_le_1 assms)\nqed\n\nlemma sin_arccos:\n  assumes \"- 1 \\<le> x\" \"x \\<le> 1\"\n  shows \"sin (arccos x) = sqrt (1 - x\\<^sup>2)\"\nproof (rule power2_eq_imp_eq)\n  show \"(sin (arccos x))\\<^sup>2 = (sqrt (1 - x\\<^sup>2))\\<^sup>2\"\n    by (simp add: square_le_1 assms sin_squared_eq)\n  show \"0 \\<le> sin (arccos x)\"\n    by (simp add: arccos_bounded assms sin_ge_zero)\n  show \"0 \\<le> sqrt (1 - x\\<^sup>2)\"\n    by (simp add: square_le_1 assms)\nqed\n\nlemma arccos_0 [simp]: \"arccos 0 = pi/2\"\n  using arccos_cos pi_half_ge_zero by fastforce\n\nlemma arccos_1 [simp]: \"arccos 1 = 0\"\n  using arccos_cos by force\n\nlemma arccos_minus_1 [simp]: \"arccos (- 1) = pi\"\n  by (metis arccos_cos cos_pi order_refl pi_ge_zero)\n\nlemma arccos_minus: \"-1 \\<le> x \\<Longrightarrow> x \\<le> 1 \\<Longrightarrow> arccos (- x) = pi - arccos x\"\n  by (smt (verit, ccfv_threshold) arccos arccos_cos cos_minus cos_minus_pi)\n\nlemma arccos_one_half [simp]: \"arccos (1/2) = pi / 3\"\n  and arccos_minus_one_half [simp]: \"arccos (-(1/2)) = 2 * pi / 3\"\n  by (intro arccos_unique; simp add: cos_60 cos_120)+\n\nlemma arccos_one_over_sqrt_2: \"arccos (1 / sqrt 2) = pi / 4\"\n  by (rule arccos_unique) (auto simp: cos_45 field_simps)\n\ncorollary arccos_minus_abs:\n  assumes \"\\<bar>x\\<bar> \\<le> 1\"\n  shows \"arccos (- x) = pi - arccos x\"\nusing assms by (simp add: arccos_minus)\n\nlemma sin_arccos_nonzero: \"- 1 < x \\<Longrightarrow> x < 1 \\<Longrightarrow> sin (arccos x) \\<noteq> 0\"\n  using arccos_lt_bounded sin_gt_zero by force\n\nlemma arctan: \"- (pi/2) < arctan y \\<and> arctan y < pi/2 \\<and> tan (arctan y) = y\"\n  unfolding arctan_def by (rule theI' [OF tan_total])\n\nlemma tan_arctan: \"tan (arctan y) = y\"\n  by (simp add: arctan)\n\nlemma arctan_bounded: \"- (pi/2) < arctan y \\<and> arctan y < pi/2\"\n  by (auto simp only: arctan)\n\nlemma arctan_lbound: \"- (pi/2) < arctan y\"\n  by (simp add: arctan)\n\nlemma arctan_ubound: \"arctan y < pi/2\"\n  by (auto simp only: arctan)\n\nlemma arctan_unique:\n  assumes \"-(pi/2) < x\"\n    and \"x < pi/2\"\n    and \"tan x = y\"\n  shows \"arctan y = x\"\n  using assms arctan [of y] tan_total [of y] by (fast elim: ex1E)\n\nlemma arctan_tan: \"-(pi/2) < x \\<Longrightarrow> x < pi/2 \\<Longrightarrow> arctan (tan x) = x\"\n  by (rule arctan_unique) simp_all\n\nlemma arctan_zero_zero [simp]: \"arctan 0 = 0\"\n  by (rule arctan_unique) simp_all\n\nlemma arctan_minus: \"arctan (- x) = - arctan x\"\n  using arctan [of \"x\"] by (auto simp: arctan_unique)\n\nlemma cos_arctan_not_zero [simp]: \"cos (arctan x) \\<noteq> 0\"\n  by (intro less_imp_neq [symmetric] cos_gt_zero_pi arctan_lbound arctan_ubound)\n\nlemma tan_eq_arctan_Ex:\n  shows \"tan x = y \\<longleftrightarrow> (\\<exists>k::int. x = arctan y + k*pi \\<or> (x = pi/2 + k*pi \\<and> y=0))\"\nproof\n  assume lhs: \"tan x = y\"\n  obtain k::int where k:\"-pi/2 < x-k*pi\" \"x-k*pi \\<le> pi/2\"\n  proof \n    define k where \"k \\<equiv> ceiling (x/pi - 1/2)\"\n    show \"- pi / 2 < x - real_of_int k * pi\" \n      using ceiling_divide_lower [of \"pi*2\" \"(x * 2 - pi)\"] by (auto simp: k_def field_simps)\n    show  \"x-k*pi \\<le> pi/2\"\n      using ceiling_divide_upper [of \"pi*2\" \"(x * 2 - pi)\"] by (auto simp: k_def field_simps)\n  qed\n  have \"x = arctan y + of_int k * pi\" when \"x \\<noteq> pi/2 + k*pi\"\n  proof -\n    have \"tan (x - k * pi) = y\" using lhs tan_periodic_int[of _ \"-k\"] by auto\n    then have \"arctan y = x - real_of_int k * pi\"\n      by (smt (verit) arctan_tan lhs divide_minus_left k mult_minus_left of_int_minus tan_periodic_int that)\n    then show ?thesis by auto\n  qed\n  then show \"\\<exists>k. x = arctan y + of_int k * pi \\<or> (x = pi/2 + k*pi \\<and> y=0)\"\n    using lhs k by force\nqed (auto simp: arctan)\n\nlemma arctan_tan_eq_abs_pi:\n  assumes \"cos \\<theta> \\<noteq> 0\"\n  obtains k where \"arctan (tan \\<theta>) = \\<theta> - of_int k * pi\"\n  by (metis add.commute assms cos_zero_iff_int2 eq_diff_eq tan_eq_arctan_Ex)\n\nlemma tan_eq:\n  assumes \"tan x = tan y\" \"tan x \\<noteq> 0\"\n  obtains k::int where \"x = y + k * pi\"\nproof -\n  obtain k0 where k0: \"x = arctan (tan y) + real_of_int k0 * pi\"\n    using assms tan_eq_arctan_Ex[of x \"tan y\"] by auto\n  obtain k1 where k1: \"arctan (tan y) = y - of_int k1 * pi\"\n    using arctan_tan_eq_abs_pi assms tan_eq_0_cos_sin by auto\n  have \"x = y + (k0-k1)*pi\"\n    using k0 k1 by (auto simp: algebra_simps)\n  with that show ?thesis\n    by blast\nqed\n\nlemma cos_arctan: \"cos (arctan x) = 1 / sqrt (1 + x\\<^sup>2)\"\nproof (rule power2_eq_imp_eq)\n  have \"0 < 1 + x\\<^sup>2\" by (simp add: add_pos_nonneg)\n  show \"0 \\<le> 1 / sqrt (1 + x\\<^sup>2)\" by simp\n  show \"0 \\<le> cos (arctan x)\"\n    by (intro less_imp_le cos_gt_zero_pi arctan_lbound arctan_ubound)\n  have \"(cos (arctan x))\\<^sup>2 * (1 + (tan (arctan x))\\<^sup>2) = 1\"\n    unfolding tan_def by (simp add: distrib_left power_divide)\n  then show \"(cos (arctan x))\\<^sup>2 = (1 / sqrt (1 + x\\<^sup>2))\\<^sup>2\"\n    using \\<open>0 < 1 + x\\<^sup>2\\<close> by (simp add: arctan power_divide eq_divide_eq)\nqed\n\nlemma sin_arctan: \"sin (arctan x) = x / sqrt (1 + x\\<^sup>2)\"\n  using add_pos_nonneg [OF zero_less_one zero_le_power2 [of x]]\n  using tan_arctan [of x] unfolding tan_def cos_arctan\n  by (simp add: eq_divide_eq)\n\nlemma tan_sec: \"cos x \\<noteq> 0 \\<Longrightarrow> 1 + (tan x)\\<^sup>2 = (inverse (cos x))\\<^sup>2\"\n  for x :: \"'a::{real_normed_field,banach,field}\"\n  by (simp add: add_divide_eq_iff inverse_eq_divide power2_eq_square tan_def)\n\nlemma arctan_less_iff: \"arctan x < arctan y \\<longleftrightarrow> x < y\"\n  by (metis tan_monotone' arctan_lbound arctan_ubound tan_arctan)\n\nlemma arctan_le_iff: \"arctan x \\<le> arctan y \\<longleftrightarrow> x \\<le> y\"\n  by (simp only: not_less [symmetric] arctan_less_iff)\n\nlemma arctan_eq_iff: \"arctan x = arctan y \\<longleftrightarrow> x = y\"\n  by (simp only: eq_iff [where 'a=real] arctan_le_iff)\n\nlemma zero_less_arctan_iff [simp]: \"0 < arctan x \\<longleftrightarrow> 0 < x\"\n  using arctan_less_iff [of 0 x] by simp\n\nlemma arctan_less_zero_iff [simp]: \"arctan x < 0 \\<longleftrightarrow> x < 0\"\n  using arctan_less_iff [of x 0] by simp\n\nlemma zero_le_arctan_iff [simp]: \"0 \\<le> arctan x \\<longleftrightarrow> 0 \\<le> x\"\n  using arctan_le_iff [of 0 x] by simp\n\nlemma arctan_le_zero_iff [simp]: \"arctan x \\<le> 0 \\<longleftrightarrow> x \\<le> 0\"\n  using arctan_le_iff [of x 0] by simp\n\nlemma arctan_eq_zero_iff [simp]: \"arctan x = 0 \\<longleftrightarrow> x = 0\"\n  using arctan_eq_iff [of x 0] by simp\n\nlemma continuous_on_arcsin': \"continuous_on {-1 .. 1} arcsin\"\nproof -\n  have \"continuous_on (sin ` {- pi/2 .. pi/2}) arcsin\"\n    by (rule continuous_on_inv) (auto intro: continuous_intros simp: arcsin_sin)\n  also have \"sin ` {- pi/2 .. pi/2} = {-1 .. 1}\"\n  proof safe\n    fix x :: real\n    assume \"x \\<in> {-1..1}\"\n    then show \"x \\<in> sin ` {- pi/2..pi/2}\"\n      using arcsin_lbound arcsin_ubound\n      by (intro image_eqI[where x=\"arcsin x\"]) auto\n  qed simp\n  finally show ?thesis .\nqed\n\nlemma continuous_on_arcsin [continuous_intros]:\n  \"continuous_on s f \\<Longrightarrow> (\\<forall>x\\<in>s. -1 \\<le> f x \\<and> f x \\<le> 1) \\<Longrightarrow> continuous_on s (\\<lambda>x. arcsin (f x))\"\n  using continuous_on_compose[of s f, OF _ continuous_on_subset[OF  continuous_on_arcsin']]\n  by (auto simp: comp_def subset_eq)\n\nlemma isCont_arcsin: \"-1 < x \\<Longrightarrow> x < 1 \\<Longrightarrow> isCont arcsin x\"\n  using continuous_on_arcsin'[THEN continuous_on_subset, of \"{ -1 <..< 1 }\"]\n  by (auto simp: continuous_on_eq_continuous_at subset_eq)\n\nlemma continuous_on_arccos': \"continuous_on {-1 .. 1} arccos\"\nproof -\n  have \"continuous_on (cos ` {0 .. pi}) arccos\"\n    by (rule continuous_on_inv) (auto intro: continuous_intros simp: arccos_cos)\n  also have \"cos ` {0 .. pi} = {-1 .. 1}\"\n  proof safe\n    fix x :: real\n    assume \"x \\<in> {-1..1}\"\n    then show \"x \\<in> cos ` {0..pi}\"\n      using arccos_lbound arccos_ubound\n      by (intro image_eqI[where x=\"arccos x\"]) auto\n  qed simp\n  finally show ?thesis .\nqed\n\nlemma continuous_on_arccos [continuous_intros]:\n  \"continuous_on s f \\<Longrightarrow> (\\<forall>x\\<in>s. -1 \\<le> f x \\<and> f x \\<le> 1) \\<Longrightarrow> continuous_on s (\\<lambda>x. arccos (f x))\"\n  using continuous_on_compose[of s f, OF _ continuous_on_subset[OF  continuous_on_arccos']]\n  by (auto simp: comp_def subset_eq)\n\nlemma isCont_arccos: \"-1 < x \\<Longrightarrow> x < 1 \\<Longrightarrow> isCont arccos x\"\n  using continuous_on_arccos'[THEN continuous_on_subset, of \"{ -1 <..< 1 }\"]\n  by (auto simp: continuous_on_eq_continuous_at subset_eq)\n\nlemma isCont_arctan: \"isCont arctan x\"\nproof -\n  obtain u where u: \"- (pi/2) < u\" \"u < arctan x\"\n    by (meson arctan arctan_less_iff linordered_field_no_lb)\n  obtain v where v: \"arctan x < v\" \"v < pi/2\"\n    by (meson arctan_less_iff arctan_ubound linordered_field_no_ub)\n  have \"isCont arctan (tan (arctan x))\"\n  proof (rule isCont_inverse_function2 [of u \"arctan x\" v])\n    show \"\\<And>z. \\<lbrakk>u \\<le> z; z \\<le> v\\<rbrakk> \\<Longrightarrow> arctan (tan z) = z\"\n      using arctan_unique u(1) v(2) by auto\n    then show \"\\<And>z. \\<lbrakk>u \\<le> z; z \\<le> v\\<rbrakk> \\<Longrightarrow> isCont tan z\"\n      by (metis arctan cos_gt_zero_pi isCont_tan less_irrefl)\n  qed (use u v in auto)\n  then show ?thesis\n    by (simp add: arctan)\nqed\n\nlemma tendsto_arctan [tendsto_intros]: \"(f \\<longlongrightarrow> x) F \\<Longrightarrow> ((\\<lambda>x. arctan (f x)) \\<longlongrightarrow> arctan x) F\"\n  by (rule isCont_tendsto_compose [OF isCont_arctan])\n\nlemma continuous_arctan [continuous_intros]: \"continuous F f \\<Longrightarrow> continuous F (\\<lambda>x. arctan (f x))\"\n  unfolding continuous_def by (rule tendsto_arctan)\n\nlemma continuous_on_arctan [continuous_intros]:\n  \"continuous_on s f \\<Longrightarrow> continuous_on s (\\<lambda>x. arctan (f x))\"\n  unfolding continuous_on_def by (auto intro: tendsto_arctan)\n\nlemma DERIV_arcsin:\n  assumes \"- 1 < x\" \"x < 1\"\n  shows \"DERIV arcsin x :> inverse (sqrt (1 - x\\<^sup>2))\"\nproof (rule DERIV_inverse_function)\n  show \"(sin has_real_derivative sqrt (1 - x\\<^sup>2)) (at (arcsin x))\"\n    by (rule derivative_eq_intros | use assms cos_arcsin in force)+\n  show \"sqrt (1 - x\\<^sup>2) \\<noteq> 0\"\n    using abs_square_eq_1 assms by force\nqed (use assms isCont_arcsin in auto)\n\nlemma DERIV_arccos:\n  assumes \"- 1 < x\" \"x < 1\"\n  shows \"DERIV arccos x :> inverse (- sqrt (1 - x\\<^sup>2))\"\nproof (rule DERIV_inverse_function)\n  show \"(cos has_real_derivative - sqrt (1 - x\\<^sup>2)) (at (arccos x))\"\n    by (rule derivative_eq_intros | use assms sin_arccos in force)+\n  show \"- sqrt (1 - x\\<^sup>2) \\<noteq> 0\"\n    using abs_square_eq_1 assms by force\nqed (use assms isCont_arccos in auto)\n\nlemma DERIV_arctan: \"DERIV arctan x :> inverse (1 + x\\<^sup>2)\"\nproof (rule DERIV_inverse_function)\n  have \"inverse ((cos (arctan x))\\<^sup>2) = 1 + x\\<^sup>2\"\n    by (metis arctan cos_arctan_not_zero power_inverse tan_sec)\n  then show \"(tan has_real_derivative 1 + x\\<^sup>2) (at (arctan x))\"\n    by (auto intro!: derivative_eq_intros)\n  show \"\\<And>y. \\<lbrakk>x - 1 < y; y < x + 1\\<rbrakk> \\<Longrightarrow> tan (arctan y) = y\"\n    using tan_arctan by blast\n  show \"1 + x\\<^sup>2 \\<noteq> 0\"\n    by (metis power_one sum_power2_eq_zero_iff zero_neq_one)\nqed (use isCont_arctan in auto)\n\ndeclare\n  DERIV_arcsin[THEN DERIV_chain2, derivative_intros]\n  DERIV_arcsin[THEN DERIV_chain2, unfolded has_field_derivative_def, derivative_intros]\n  DERIV_arccos[THEN DERIV_chain2, derivative_intros]\n  DERIV_arccos[THEN DERIV_chain2, unfolded has_field_derivative_def, derivative_intros]\n  DERIV_arctan[THEN DERIV_chain2, derivative_intros]\n  DERIV_arctan[THEN DERIV_chain2, unfolded has_field_derivative_def, derivative_intros]\n\nlemmas has_derivative_arctan[derivative_intros] = DERIV_arctan[THEN DERIV_compose_FDERIV]\n  and has_derivative_arccos[derivative_intros] = DERIV_arccos[THEN DERIV_compose_FDERIV]\n  and has_derivative_arcsin[derivative_intros] = DERIV_arcsin[THEN DERIV_compose_FDERIV]\n\nlemma filterlim_tan_at_right: \"filterlim tan at_bot (at_right (- (pi/2)))\"\n  by (rule filterlim_at_bot_at_right[where Q=\"\\<lambda>x. - pi/2 < x \\<and> x < pi/2\" and P=\"\\<lambda>x. True\" and g=arctan])\n     (auto simp: arctan le_less eventually_at dist_real_def simp del: less_divide_eq_numeral1\n           intro!: tan_monotone exI[of _ \"pi/2\"])\n\nlemma filterlim_tan_at_left: \"filterlim tan at_top (at_left (pi/2))\"\n  by (rule filterlim_at_top_at_left[where Q=\"\\<lambda>x. - pi/2 < x \\<and> x < pi/2\" and P=\"\\<lambda>x. True\" and g=arctan])\n     (auto simp: arctan le_less eventually_at dist_real_def simp del: less_divide_eq_numeral1\n           intro!: tan_monotone exI[of _ \"pi/2\"])\n\nlemma tendsto_arctan_at_top: \"(arctan \\<longlongrightarrow> (pi/2)) at_top\"\nproof (rule tendstoI)\n  fix e :: real\n  assume \"0 < e\"\n  define y where \"y = pi/2 - min (pi/2) e\"\n  then have y: \"0 \\<le> y\" \"y < pi/2\" \"pi/2 \\<le> e + y\"\n    using \\<open>0 < e\\<close> by auto\n  show \"eventually (\\<lambda>x. dist (arctan x) (pi/2) < e) at_top\"\n  proof (intro eventually_at_top_dense[THEN iffD2] exI allI impI)\n    fix x\n    assume \"tan y < x\"\n    then have \"arctan (tan y) < arctan x\"\n      by (simp add: arctan_less_iff)\n    with y have \"y < arctan x\"\n      by (subst (asm) arctan_tan) simp_all\n    with arctan_ubound[of x, arith] y \\<open>0 < e\\<close>\n    show \"dist (arctan x) (pi/2) < e\"\n      by (simp add: dist_real_def)\n  qed\nqed\n\nlemma tendsto_arctan_at_bot: \"(arctan \\<longlongrightarrow> - (pi/2)) at_bot\"\n  unfolding filterlim_at_bot_mirror arctan_minus\n  by (intro tendsto_minus tendsto_arctan_at_top)\n\n\nsubsection \\<open>Prove Totality of the Trigonometric Functions\\<close>\n\nlemma cos_arccos_abs: \"\\<bar>y\\<bar> \\<le> 1 \\<Longrightarrow> cos (arccos y) = y\"\n  by (simp add: abs_le_iff)\n\nlemma sin_arccos_abs: \"\\<bar>y\\<bar> \\<le> 1 \\<Longrightarrow> sin (arccos y) = sqrt (1 - y\\<^sup>2)\"\n  by (simp add: sin_arccos abs_le_iff)\n\nlemma sin_mono_less_eq:\n  \"- (pi/2) \\<le> x \\<Longrightarrow> x \\<le> pi/2 \\<Longrightarrow> - (pi/2) \\<le> y \\<Longrightarrow> y \\<le> pi/2 \\<Longrightarrow> sin x < sin y \\<longleftrightarrow> x < y\"\n  by (metis not_less_iff_gr_or_eq sin_monotone_2pi)\n\nlemma sin_mono_le_eq:\n  \"- (pi/2) \\<le> x \\<Longrightarrow> x \\<le> pi/2 \\<Longrightarrow> - (pi/2) \\<le> y \\<Longrightarrow> y \\<le> pi/2 \\<Longrightarrow> sin x \\<le> sin y \\<longleftrightarrow> x \\<le> y\"\n  by (meson leD le_less_linear sin_monotone_2pi sin_monotone_2pi_le)\n\nlemma sin_inj_pi:\n  \"- (pi/2) \\<le> x \\<Longrightarrow> x \\<le> pi/2 \\<Longrightarrow> - (pi/2) \\<le> y \\<Longrightarrow> y \\<le> pi/2 \\<Longrightarrow> sin x = sin y \\<Longrightarrow> x = y\"\n  by (metis arcsin_sin)\n\nlemma arcsin_le_iff:\n  assumes \"x \\<ge> -1\" \"x \\<le> 1\" \"y \\<ge> -pi/2\" \"y \\<le> pi/2\"\n  shows   \"arcsin x \\<le> y \\<longleftrightarrow> x \\<le> sin y\"\nproof -\n  have \"arcsin x \\<le> y \\<longleftrightarrow> sin (arcsin x) \\<le> sin y\"\n    using arcsin_bounded[of x] assms by (subst sin_mono_le_eq) auto\n  also from assms have \"sin (arcsin x) = x\" by simp\n  finally show ?thesis .\nqed\n\nlemma le_arcsin_iff:\n  assumes \"x \\<ge> -1\" \"x \\<le> 1\" \"y \\<ge> -pi/2\" \"y \\<le> pi/2\"\n  shows   \"arcsin x \\<ge> y \\<longleftrightarrow> x \\<ge> sin y\"\nproof -\n  have \"arcsin x \\<ge> y \\<longleftrightarrow> sin (arcsin x) \\<ge> sin y\"\n    using arcsin_bounded[of x] assms by (subst sin_mono_le_eq) auto\n  also from assms have \"sin (arcsin x) = x\" by simp\n  finally show ?thesis .\nqed\n\nlemma cos_mono_less_eq: \"0 \\<le> x \\<Longrightarrow> x \\<le> pi \\<Longrightarrow> 0 \\<le> y \\<Longrightarrow> y \\<le> pi \\<Longrightarrow> cos x < cos y \\<longleftrightarrow> y < x\"\n  by (meson cos_monotone_0_pi cos_monotone_0_pi_le leD le_less_linear)\n\nlemma cos_mono_le_eq: \"0 \\<le> x \\<Longrightarrow> x \\<le> pi \\<Longrightarrow> 0 \\<le> y \\<Longrightarrow> y \\<le> pi \\<Longrightarrow> cos x \\<le> cos y \\<longleftrightarrow> y \\<le> x\"\n  by (metis arccos_cos cos_monotone_0_pi_le eq_iff linear)\n\nlemma cos_inj_pi: \"0 \\<le> x \\<Longrightarrow> x \\<le> pi \\<Longrightarrow> 0 \\<le> y \\<Longrightarrow> y \\<le> pi \\<Longrightarrow> cos x = cos y \\<Longrightarrow> x = y\"\n  by (metis arccos_cos)\n\nlemma arccos_le_pi2: \"\\<lbrakk>0 \\<le> y; y \\<le> 1\\<rbrakk> \\<Longrightarrow> arccos y \\<le> pi/2\"\n  by (metis (mono_tags) arccos_0 arccos cos_le_one cos_monotone_0_pi_le\n      cos_pi cos_pi_half pi_half_ge_zero antisym_conv less_eq_neg_nonpos linear minus_minus order.trans order_refl)\n\nlemma sincos_total_pi_half:\n  assumes \"0 \\<le> x\" \"0 \\<le> y\" \"x\\<^sup>2 + y\\<^sup>2 = 1\"\n  shows \"\\<exists>t. 0 \\<le> t \\<and> t \\<le> pi/2 \\<and> x = cos t \\<and> y = sin t\"\nproof -\n  have x1: \"x \\<le> 1\"\n    using assms by (metis le_add_same_cancel1 power2_le_imp_le power_one zero_le_power2)\n  with assms have *: \"0 \\<le> arccos x\" \"cos (arccos x) = x\"\n    by (auto simp: arccos)\n  from assms have \"y = sqrt (1 - x\\<^sup>2)\"\n    by (metis abs_of_nonneg add.commute add_diff_cancel real_sqrt_abs)\n  with x1 * assms arccos_le_pi2 [of x] show ?thesis\n    by (rule_tac x=\"arccos x\" in exI) (auto simp: sin_arccos)\nqed\n\nlemma sincos_total_pi:\n  assumes \"0 \\<le> y\" \"x\\<^sup>2 + y\\<^sup>2 = 1\"\n  shows \"\\<exists>t. 0 \\<le> t \\<and> t \\<le> pi \\<and> x = cos t \\<and> y = sin t\"\nproof (cases rule: le_cases [of 0 x])\n  case le\n  from sincos_total_pi_half [OF le] show ?thesis\n    by (metis pi_ge_two pi_half_le_two add.commute add_le_cancel_left add_mono assms)\nnext\n  case ge\n  then have \"0 \\<le> -x\"\n    by simp\n  then obtain t where t: \"t\\<ge>0\" \"t \\<le> pi/2\" \"-x = cos t\" \"y = sin t\"\n    using sincos_total_pi_half assms\n    by auto (metis \\<open>0 \\<le> - x\\<close> power2_minus)\n  show ?thesis\n    by (rule exI [where x = \"pi -t\"]) (use t in auto)\nqed\n\nlemma sincos_total_2pi_le:\n  assumes \"x\\<^sup>2 + y\\<^sup>2 = 1\"\n  shows \"\\<exists>t. 0 \\<le> t \\<and> t \\<le> 2 * pi \\<and> x = cos t \\<and> y = sin t\"\nproof (cases rule: le_cases [of 0 y])\n  case le\n  from sincos_total_pi [OF le] show ?thesis\n    by (metis assms le_add_same_cancel1 mult.commute mult_2_right order.trans)\nnext\n  case ge\n  then have \"0 \\<le> -y\"\n    by simp\n  then obtain t where t: \"t\\<ge>0\" \"t \\<le> pi\" \"x = cos t\" \"-y = sin t\"\n    using sincos_total_pi assms\n    by auto (metis \\<open>0 \\<le> - y\\<close> power2_minus)\n  show ?thesis\n    by (rule exI [where x = \"2 * pi - t\"]) (use t in auto)\nqed\n\nlemma sincos_total_2pi:\n  assumes \"x\\<^sup>2 + y\\<^sup>2 = 1\"\n  obtains t where \"0 \\<le> t\" \"t < 2*pi\" \"x = cos t\" \"y = sin t\"\nproof -\n  from sincos_total_2pi_le [OF assms]\n  obtain t where t: \"0 \\<le> t\" \"t \\<le> 2*pi\" \"x = cos t\" \"y = sin t\"\n    by blast\n  show ?thesis\n    by (cases \"t = 2 * pi\") (use t that in \\<open>force+\\<close>)\nqed\n\nlemma arcsin_less_mono: \"\\<bar>x\\<bar> \\<le> 1 \\<Longrightarrow> \\<bar>y\\<bar> \\<le> 1 \\<Longrightarrow> arcsin x < arcsin y \\<longleftrightarrow> x < y\"\n  by (rule trans [OF sin_mono_less_eq [symmetric]]) (use arcsin_ubound arcsin_lbound in auto)\n\nlemma arcsin_le_mono: \"\\<bar>x\\<bar> \\<le> 1 \\<Longrightarrow> \\<bar>y\\<bar> \\<le> 1 \\<Longrightarrow> arcsin x \\<le> arcsin y \\<longleftrightarrow> x \\<le> y\"\n  using arcsin_less_mono not_le by blast\n\nlemma arcsin_less_arcsin: \"- 1 \\<le> x \\<Longrightarrow> x < y \\<Longrightarrow> y \\<le> 1 \\<Longrightarrow> arcsin x < arcsin y\"\n  using arcsin_less_mono by auto\n\nlemma arcsin_le_arcsin: \"- 1 \\<le> x \\<Longrightarrow> x \\<le> y \\<Longrightarrow> y \\<le> 1 \\<Longrightarrow> arcsin x \\<le> arcsin y\"\n  using arcsin_le_mono by auto\n\nlemma arcsin_nonneg: \"x \\<in> {0..1} \\<Longrightarrow> arcsin x \\<ge> 0\"\n  using arcsin_le_arcsin[of 0 x] by simp\n  \nlemma arccos_less_mono: \"\\<bar>x\\<bar> \\<le> 1 \\<Longrightarrow> \\<bar>y\\<bar> \\<le> 1 \\<Longrightarrow> arccos x < arccos y \\<longleftrightarrow> y < x\"\n  by (rule trans [OF cos_mono_less_eq [symmetric]]) (use arccos_ubound arccos_lbound in auto)\n\nlemma arccos_le_mono: \"\\<bar>x\\<bar> \\<le> 1 \\<Longrightarrow> \\<bar>y\\<bar> \\<le> 1 \\<Longrightarrow> arccos x \\<le> arccos y \\<longleftrightarrow> y \\<le> x\"\n  using arccos_less_mono [of y x] by (simp add: not_le [symmetric])\n\nlemma arccos_less_arccos: \"- 1 \\<le> x \\<Longrightarrow> x < y \\<Longrightarrow> y \\<le> 1 \\<Longrightarrow> arccos y < arccos x\"\n  using arccos_less_mono by auto\n\nlemma arccos_le_arccos: \"- 1 \\<le> x \\<Longrightarrow> x \\<le> y \\<Longrightarrow> y \\<le> 1 \\<Longrightarrow> arccos y \\<le> arccos x\"\n  using arccos_le_mono by auto\n\nlemma arccos_eq_iff: \"\\<bar>x\\<bar> \\<le> 1 \\<and> \\<bar>y\\<bar> \\<le> 1 \\<Longrightarrow> arccos x = arccos y \\<longleftrightarrow> x = y\"\n  using cos_arccos_abs by fastforce\n\n\nlemma arccos_cos_eq_abs:\n  assumes \"\\<bar>\\<theta>\\<bar> \\<le> pi\"\n  shows \"arccos (cos \\<theta>) = \\<bar>\\<theta>\\<bar>\"\n  unfolding arccos_def\nproof (intro the_equality conjI; clarify?)\n  show \"cos \\<bar>\\<theta>\\<bar> = cos \\<theta>\"\n    by (simp add: abs_real_def)\n  show \"x = \\<bar>\\<theta>\\<bar>\" if \"cos x = cos \\<theta>\" \"0 \\<le> x\" \"x \\<le> pi\" for x\n    by (simp add: \\<open>cos \\<bar>\\<theta>\\<bar> = cos \\<theta>\\<close> assms cos_inj_pi that)\nqed (use assms in auto)\n\nlemma arccos_cos_eq_abs_2pi:\n  obtains k where \"arccos (cos \\<theta>) = \\<bar>\\<theta> - of_int k * (2 * pi)\\<bar>\"\nproof -\n  define k where \"k \\<equiv>  \\<lfloor>(\\<theta> + pi) / (2 * pi)\\<rfloor>\"\n  have lepi: \"\\<bar>\\<theta> - of_int k * (2 * pi)\\<bar> \\<le> pi\"\n    using floor_divide_lower [of \"2*pi\" \"\\<theta> + pi\"] floor_divide_upper [of \"2*pi\" \"\\<theta> + pi\"]\n    by (auto simp: k_def abs_if algebra_simps)\n  have \"arccos (cos \\<theta>) = arccos (cos (\\<theta> - of_int k * (2 * pi)))\"\n    using cos_int_2pin sin_int_2pin by (simp add: cos_diff mult.commute)\n  also have \"\\<dots> = \\<bar>\\<theta> - of_int k * (2 * pi)\\<bar>\"\n    using arccos_cos_eq_abs lepi by blast\n  finally show ?thesis\n    using that by metis\nqed\n\nlemma arccos_arctan:\n  assumes \"-1 < x\" \"x < 1\"\n  shows \"arccos x = pi/2 - arctan(x / sqrt(1 - x\\<^sup>2))\"\nproof -\n  have \"arctan(x / sqrt(1 - x\\<^sup>2)) - (pi/2 - arccos x) = 0\"\n  proof (rule sin_eq_0_pi)\n    show \"- pi < arctan (x / sqrt (1 - x\\<^sup>2)) - (pi/2 - arccos x)\"\n      using arctan_lbound [of \"x / sqrt(1 - x\\<^sup>2)\"]  arccos_bounded [of x] assms\n      by (simp add: algebra_simps)\n  next\n    show \"arctan (x / sqrt (1 - x\\<^sup>2)) - (pi/2 - arccos x) < pi\"\n      using arctan_ubound [of \"x / sqrt(1 - x\\<^sup>2)\"]  arccos_bounded [of x] assms\n      by (simp add: algebra_simps)\n  next\n    show \"sin (arctan (x / sqrt (1 - x\\<^sup>2)) - (pi/2 - arccos x)) = 0\"\n      using assms\n      by (simp add: algebra_simps sin_diff cos_add sin_arccos sin_arctan cos_arctan\n                    power2_eq_square square_eq_1_iff)\n  qed\n  then show ?thesis\n    by simp\nqed\n\nlemma arcsin_plus_arccos:\n  assumes \"-1 \\<le> x\" \"x \\<le> 1\"\n    shows \"arcsin x + arccos x = pi/2\"\nproof -\n  have \"arcsin x = pi/2 - arccos x\"\n    apply (rule sin_inj_pi)\n    using assms arcsin [OF assms] arccos [OF assms]\n    by (auto simp: algebra_simps sin_diff)\n  then show ?thesis\n    by (simp add: algebra_simps)\nqed\n\nlemma arcsin_arccos_eq: \"-1 \\<le> x \\<Longrightarrow> x \\<le> 1 \\<Longrightarrow> arcsin x = pi/2 - arccos x\"\n  using arcsin_plus_arccos by force\n\nlemma arccos_arcsin_eq: \"-1 \\<le> x \\<Longrightarrow> x \\<le> 1 \\<Longrightarrow> arccos x = pi/2 - arcsin x\"\n  using arcsin_plus_arccos by force\n\nlemma arcsin_arctan: \"-1 < x \\<Longrightarrow> x < 1 \\<Longrightarrow> arcsin x = arctan(x / sqrt(1 - x\\<^sup>2))\"\n  by (simp add: arccos_arctan arcsin_arccos_eq)\n\nlemma arcsin_arccos_sqrt_pos: \"0 \\<le> x \\<Longrightarrow> x \\<le> 1 \\<Longrightarrow> arcsin x = arccos(sqrt(1 - x\\<^sup>2))\"\n  by (smt (verit, del_insts) arccos_cos arcsin_0 arcsin_le_arcsin arcsin_pi cos_arcsin)\n\nlemma arcsin_arccos_sqrt_neg: \"-1 \\<le> x \\<Longrightarrow> x \\<le> 0 \\<Longrightarrow> arcsin x = -arccos(sqrt(1 - x\\<^sup>2))\"\n  using arcsin_arccos_sqrt_pos [of \"-x\"]\n  by (simp add: arcsin_minus)\n\nlemma arccos_arcsin_sqrt_pos: \"0 \\<le> x \\<Longrightarrow> x \\<le> 1 \\<Longrightarrow> arccos x = arcsin(sqrt(1 - x\\<^sup>2))\"\n  by (smt (verit, del_insts) arccos_lbound arccos_le_pi2 arcsin_sin sin_arccos)\n\nlemma arccos_arcsin_sqrt_neg: \"-1 \\<le> x \\<Longrightarrow> x \\<le> 0 \\<Longrightarrow> arccos x = pi - arcsin(sqrt(1 - x\\<^sup>2))\"\n  using arccos_arcsin_sqrt_pos [of \"-x\"]\n  by (simp add: arccos_minus)\n\nlemma cos_limit_1:\n  assumes \"(\\<lambda>j. cos (\\<theta> j)) \\<longlonglongrightarrow> 1\"\n  shows \"\\<exists>k. (\\<lambda>j. \\<theta> j - of_int (k j) * (2 * pi)) \\<longlonglongrightarrow> 0\"\nproof -\n  have \"\\<forall>\\<^sub>F j in sequentially. cos (\\<theta> j) \\<in> {- 1..1}\"\n    by auto\n  then have \"(\\<lambda>j. arccos (cos (\\<theta> j))) \\<longlonglongrightarrow> arccos 1\"\n    using continuous_on_tendsto_compose [OF continuous_on_arccos' assms] by auto\n  moreover have \"\\<And>j. \\<exists>k. arccos (cos (\\<theta> j)) = \\<bar>\\<theta> j - of_int k * (2 * pi)\\<bar>\"\n    using arccos_cos_eq_abs_2pi by metis\n  then have \"\\<exists>k. \\<forall>j. arccos (cos (\\<theta> j)) = \\<bar>\\<theta> j - of_int (k j) * (2 * pi)\\<bar>\"\n    by metis\n  ultimately have \"\\<exists>k. (\\<lambda>j. \\<bar>\\<theta> j - of_int (k j) * (2 * pi)\\<bar>) \\<longlonglongrightarrow> 0\"\n    by auto\n  then show ?thesis\n    by (simp add: tendsto_rabs_zero_iff)\nqed\n\nlemma cos_diff_limit_1:\n  assumes \"(\\<lambda>j. cos (\\<theta> j - \\<Theta>)) \\<longlonglongrightarrow> 1\"\n  obtains k where \"(\\<lambda>j. \\<theta> j - of_int (k j) * (2 * pi)) \\<longlonglongrightarrow> \\<Theta>\"\nproof -\n  obtain k where \"(\\<lambda>j. (\\<theta> j - \\<Theta>) - of_int (k j) * (2 * pi)) \\<longlonglongrightarrow> 0\"\n    using cos_limit_1 [OF assms] by auto\n  then have \"(\\<lambda>j. \\<Theta> + ((\\<theta> j - \\<Theta>) - of_int (k j) * (2 * pi))) \\<longlonglongrightarrow> \\<Theta> + 0\"\n    by (rule tendsto_add [OF tendsto_const])\n  with that show ?thesis\n    by auto\nqed\n\nsubsection \\<open>Machin's formula\\<close>\n\nlemma arctan_one: \"arctan 1 = pi/4\"\n  by (rule arctan_unique) (simp_all add: tan_45 m2pi_less_pi)\n\nlemma tan_total_pi4:\n  assumes \"\\<bar>x\\<bar> < 1\"\n  shows \"\\<exists>z. - (pi/4) < z \\<and> z < pi/4 \\<and> tan z = x\"\nproof\n  show \"- (pi/4) < arctan x \\<and> arctan x < pi/4 \\<and> tan (arctan x) = x\"\n    unfolding arctan_one [symmetric] arctan_minus [symmetric]\n    unfolding arctan_less_iff\n    using assms by (auto simp: arctan)\nqed\n\nlemma arctan_add:\n  assumes \"\\<bar>x\\<bar> \\<le> 1\" \"\\<bar>y\\<bar> < 1\"\n  shows \"arctan x + arctan y = arctan ((x + y) / (1 - x * y))\"\nproof (rule arctan_unique [symmetric])\n  have \"- (pi/4) \\<le> arctan x\" \"- (pi/4) < arctan y\"\n    unfolding arctan_one [symmetric] arctan_minus [symmetric]\n    unfolding arctan_le_iff arctan_less_iff\n    using assms by auto\n  from add_le_less_mono [OF this] show 1: \"- (pi/2) < arctan x + arctan y\"\n    by simp\n  have \"arctan x \\<le> pi/4\" \"arctan y < pi/4\"\n    unfolding arctan_one [symmetric]\n    unfolding arctan_le_iff arctan_less_iff\n    using assms by auto\n  from add_le_less_mono [OF this] show 2: \"arctan x + arctan y < pi/2\"\n    by simp\n  show \"tan (arctan x + arctan y) = (x + y) / (1 - x * y)\"\n    using cos_gt_zero_pi [OF 1 2] by (simp add: arctan tan_add)\nqed\n\nlemma arctan_double: \"\\<bar>x\\<bar> < 1 \\<Longrightarrow> 2 * arctan x = arctan ((2 * x) / (1 - x\\<^sup>2))\"\n  by (metis arctan_add linear mult_2 not_less power2_eq_square)\n\ntheorem machin: \"pi/4 = 4 * arctan (1 / 5) - arctan (1/239)\"\nproof -\n  have \"\\<bar>1 / 5\\<bar> < (1 :: real)\"\n    by auto\n  from arctan_add[OF less_imp_le[OF this] this] have \"2 * arctan (1 / 5) = arctan (5 / 12)\"\n    by auto\n  moreover\n  have \"\\<bar>5 / 12\\<bar> < (1 :: real)\"\n    by auto\n  from arctan_add[OF less_imp_le[OF this] this] have \"2 * arctan (5 / 12) = arctan (120 / 119)\"\n    by auto\n  moreover\n  have \"\\<bar>1\\<bar> \\<le> (1::real)\" and \"\\<bar>1/239\\<bar> < (1::real)\"\n    by auto\n  from arctan_add[OF this] have \"arctan 1 + arctan (1/239) = arctan (120 / 119)\"\n    by auto\n  ultimately have \"arctan 1 + arctan (1/239) = 4 * arctan (1 / 5)\"\n    by auto\n  then show ?thesis\n    unfolding arctan_one by algebra\nqed\n\nlemma machin_Euler: \"5 * arctan (1 / 7) + 2 * arctan (3 / 79) = pi/4\"\nproof -\n  have 17: \"\\<bar>1 / 7\\<bar> < (1 :: real)\" by auto\n  with arctan_double have \"2 * arctan (1 / 7) = arctan (7 / 24)\"\n    by simp (simp add: field_simps)\n  moreover\n  have \"\\<bar>7 / 24\\<bar> < (1 :: real)\" by auto\n  with arctan_double have \"2 * arctan (7 / 24) = arctan (336 / 527)\"\n    by simp (simp add: field_simps)\n  moreover\n  have \"\\<bar>336 / 527\\<bar> < (1 :: real)\" by auto\n  from arctan_add[OF less_imp_le[OF 17] this]\n  have \"arctan(1/7) + arctan (336 / 527) = arctan (2879 / 3353)\"\n    by auto\n  ultimately have I: \"5 * arctan (1 / 7) = arctan (2879 / 3353)\" by auto\n  have 379: \"\\<bar>3 / 79\\<bar> < (1 :: real)\" by auto\n  with arctan_double have II: \"2 * arctan (3 / 79) = arctan (237 / 3116)\"\n    by simp (simp add: field_simps)\n  have *: \"\\<bar>2879 / 3353\\<bar> < (1 :: real)\" by auto\n  have \"\\<bar>237 / 3116\\<bar> < (1 :: real)\" by auto\n  from arctan_add[OF less_imp_le[OF *] this] have \"arctan (2879/3353) + arctan (237/3116) = pi/4\"\n    by (simp add: arctan_one)\n  with I II show ?thesis by auto\nqed\n\n(*But could also prove MACHIN_GAUSS:\n  12 * arctan(1/18) + 8 * arctan(1/57) - 5 * arctan(1/239) = pi/4*)\n\n\nsubsection \\<open>Introducing the inverse tangent power series\\<close>\n\nlemma monoseq_arctan_series:\n  fixes x :: real\n  assumes \"\\<bar>x\\<bar> \\<le> 1\"\n  shows \"monoseq (\\<lambda>n. 1 / real (n * 2 + 1) * x^(n * 2 + 1))\"\n    (is \"monoseq ?a\")\nproof (cases \"x = 0\")\n  case True\n  then show ?thesis by (auto simp: monoseq_def)\nnext\n  case False\n  have \"norm x \\<le> 1\" and \"x \\<le> 1\" and \"-1 \\<le> x\"\n    using assms by auto\n  show \"monoseq ?a\"\n  proof -\n    have mono: \"1 / real (Suc (Suc n * 2)) * x ^ Suc (Suc n * 2) \\<le>\n        1 / real (Suc (n * 2)) * x ^ Suc (n * 2)\"\n      if \"0 \\<le> x\" and \"x \\<le> 1\" for n and x :: real\n    proof (rule mult_mono)\n      show \"1 / real (Suc (Suc n * 2)) \\<le> 1 / real (Suc (n * 2))\"\n        by (rule frac_le) simp_all\n      show \"0 \\<le> 1 / real (Suc (n * 2))\"\n        by auto\n      show \"x ^ Suc (Suc n * 2) \\<le> x ^ Suc (n * 2)\"\n        by (rule power_decreasing) (simp_all add: \\<open>0 \\<le> x\\<close> \\<open>x \\<le> 1\\<close>)\n      show \"0 \\<le> x ^ Suc (Suc n * 2)\"\n        by (rule zero_le_power) (simp add: \\<open>0 \\<le> x\\<close>)\n    qed\n    show ?thesis\n    proof (cases \"0 \\<le> x\")\n      case True\n      from mono[OF this \\<open>x \\<le> 1\\<close>, THEN allI]\n      show ?thesis\n        unfolding Suc_eq_plus1[symmetric] by (rule mono_SucI2)\n    next\n      case False\n      then have \"0 \\<le> - x\" and \"- x \\<le> 1\"\n        using \\<open>-1 \\<le> x\\<close> by auto\n      from mono[OF this]\n      have \"1 / real (Suc (Suc n * 2)) * x ^ Suc (Suc n * 2) \\<ge>\n          1 / real (Suc (n * 2)) * x ^ Suc (n * 2)\" for n\n        using \\<open>0 \\<le> -x\\<close> by auto\n      then show ?thesis\n        unfolding Suc_eq_plus1[symmetric] by (rule mono_SucI1[OF allI])\n    qed\n  qed\nqed\n\nlemma zeroseq_arctan_series:\n  fixes x :: real\n  assumes \"\\<bar>x\\<bar> \\<le> 1\"\n  shows \"(\\<lambda>n. 1 / real (n * 2 + 1) * x^(n * 2 + 1)) \\<longlonglongrightarrow> 0\"\n    (is \"?a \\<longlonglongrightarrow> 0\")\nproof (cases \"x = 0\")\n  case True\n  then show ?thesis by simp\nnext\n  case False\n  have \"norm x \\<le> 1\" and \"x \\<le> 1\" and \"-1 \\<le> x\"\n    using assms by auto\n  show \"?a \\<longlonglongrightarrow> 0\"\n  proof (cases \"\\<bar>x\\<bar> < 1\")\n    case True\n    then have \"norm x < 1\" by auto\n    from tendsto_mult[OF LIMSEQ_inverse_real_of_nat LIMSEQ_power_zero[OF \\<open>norm x < 1\\<close>, THEN LIMSEQ_Suc]]\n    have \"(\\<lambda>n. 1 / real (n + 1) * x ^ (n + 1)) \\<longlonglongrightarrow> 0\"\n      unfolding inverse_eq_divide Suc_eq_plus1 by simp\n    then show ?thesis\n      using pos2 by (rule LIMSEQ_linear)\n  next\n    case False\n    then have \"x = -1 \\<or> x = 1\"\n      using \\<open>\\<bar>x\\<bar> \\<le> 1\\<close> by auto\n    then have n_eq: \"\\<And> n. x ^ (n * 2 + 1) = x\"\n      unfolding One_nat_def by auto\n    from tendsto_mult[OF LIMSEQ_inverse_real_of_nat[THEN LIMSEQ_linear, OF pos2, unfolded inverse_eq_divide] tendsto_const[of x]]\n    show ?thesis\n      unfolding n_eq Suc_eq_plus1 by auto\n  qed\nqed\n\nlemma summable_arctan_series:\n  fixes n :: nat\n  assumes \"\\<bar>x\\<bar> \\<le> 1\"\n  shows \"summable (\\<lambda> k. (-1)^k * (1 / real (k*2+1) * x ^ (k*2+1)))\"\n    (is \"summable (?c x)\")\n  by (rule summable_Leibniz(1),\n      rule zeroseq_arctan_series[OF assms],\n      rule monoseq_arctan_series[OF assms])\n\nlemma DERIV_arctan_series:\n  assumes \"\\<bar>x\\<bar> < 1\"\n  shows \"DERIV (\\<lambda>x'. \\<Sum>k. (-1)^k * (1 / real (k * 2 + 1) * x' ^ (k * 2 + 1))) x :>\n      (\\<Sum>k. (-1)^k * x^(k * 2))\"\n    (is \"DERIV ?arctan _ :> ?Int\")\nproof -\n  let ?f = \"\\<lambda>n. if even n then (-1)^(n div 2) * 1 / real (Suc n) else 0\"\n\n  have n_even: \"even n \\<Longrightarrow> 2 * (n div 2) = n\" for n :: nat\n    by presburger\n  then have if_eq: \"?f n * real (Suc n) * x'^n =\n      (if even n then (-1)^(n div 2) * x'^(2 * (n div 2)) else 0)\"\n    for n x'\n    by auto\n\n  have summable_Integral: \"summable (\\<lambda> n. (- 1) ^ n * x^(2 * n))\" if \"\\<bar>x\\<bar> < 1\" for x :: real\n  proof -\n    from that have \"x\\<^sup>2 < 1\"\n      by (simp add: abs_square_less_1)\n    have \"summable (\\<lambda> n. (- 1) ^ n * (x\\<^sup>2) ^n)\"\n      by (rule summable_Leibniz(1))\n        (auto intro!: LIMSEQ_realpow_zero monoseq_realpow \\<open>x\\<^sup>2 < 1\\<close> order_less_imp_le[OF \\<open>x\\<^sup>2 < 1\\<close>])\n    then show ?thesis\n      by (simp only: power_mult)\n  qed\n\n  have sums_even: \"(sums) f = (sums) (\\<lambda> n. if even n then f (n div 2) else 0)\"\n    for f :: \"nat \\<Rightarrow> real\"\n  proof -\n    have \"f sums x = (\\<lambda> n. if even n then f (n div 2) else 0) sums x\" for x :: real\n    proof\n      assume \"f sums x\"\n      from sums_if[OF sums_zero this] show \"(\\<lambda>n. if even n then f (n div 2) else 0) sums x\"\n        by auto\n    next\n      assume \"(\\<lambda> n. if even n then f (n div 2) else 0) sums x\"\n      from LIMSEQ_linear[OF this[simplified sums_def] pos2, simplified sum_split_even_odd[simplified mult.commute]]\n      show \"f sums x\"\n        unfolding sums_def by auto\n    qed\n    then show ?thesis ..\n  qed\n\n  have Int_eq: \"(\\<Sum>n. ?f n * real (Suc n) * x^n) = ?Int\"\n    unfolding if_eq mult.commute[of _ 2]\n      suminf_def sums_even[of \"\\<lambda> n. (- 1) ^ n * x ^ (2 * n)\", symmetric]\n    by auto\n\n  have arctan_eq: \"(\\<Sum>n. ?f n * x^(Suc n)) = ?arctan x\" for x\n  proof -\n    have if_eq': \"\\<And>n. (if even n then (- 1) ^ (n div 2) * 1 / real (Suc n) else 0) * x ^ Suc n =\n      (if even n then (- 1) ^ (n div 2) * (1 / real (Suc (2 * (n div 2))) * x ^ Suc (2 * (n div 2))) else 0)\"\n      using n_even by auto\n    have idx_eq: \"\\<And>n. n * 2 + 1 = Suc (2 * n)\"\n      by auto\n    then show ?thesis\n      unfolding if_eq' idx_eq suminf_def\n        sums_even[of \"\\<lambda> n. (- 1) ^ n * (1 / real (Suc (2 * n)) * x ^ Suc (2 * n))\", symmetric]\n      by auto\n  qed\n\n  have \"DERIV (\\<lambda> x. \\<Sum> n. ?f n * x^(Suc n)) x :> (\\<Sum>n. ?f n * real (Suc n) * x^n)\"\n  proof (rule DERIV_power_series')\n    show \"x \\<in> {- 1 <..< 1}\"\n      using \\<open>\\<bar> x \\<bar> < 1\\<close> by auto\n    show \"summable (\\<lambda> n. ?f n * real (Suc n) * x'^n)\"\n      if x'_bounds: \"x' \\<in> {- 1 <..< 1}\" for x' :: real\n    proof -\n      from that have \"\\<bar>x'\\<bar> < 1\" by auto\n      then show ?thesis\n        using that sums_summable sums_if [OF sums_0 [of \"\\<lambda>x. 0\"] summable_sums [OF summable_Integral]]   \n        by (auto simp add: if_distrib [of \"\\<lambda>x. x * y\" for y] cong: if_cong)\n    qed\n  qed auto\n  then show ?thesis\n    by (simp only: Int_eq arctan_eq)\nqed\n\nlemma arctan_series:\n  assumes \"\\<bar>x\\<bar> \\<le> 1\"\n  shows \"arctan x = (\\<Sum>k. (-1)^k * (1 / real (k * 2 + 1) * x ^ (k * 2 + 1)))\"\n    (is \"_ = suminf (\\<lambda> n. ?c x n)\")\nproof -\n  let ?c' = \"\\<lambda>x n. (-1)^n * x^(n*2)\"\n\n  have DERIV_arctan_suminf: \"DERIV (\\<lambda> x. suminf (?c x)) x :> (suminf (?c' x))\"\n    if \"0 < r\" and \"r < 1\" and \"\\<bar>x\\<bar> < r\" for r x :: real\n  proof (rule DERIV_arctan_series)\n    from that show \"\\<bar>x\\<bar> < 1\"\n      using \\<open>r < 1\\<close> and \\<open>\\<bar>x\\<bar> < r\\<close> by auto\n  qed\n\n  {\n    fix x :: real\n    assume \"\\<bar>x\\<bar> \\<le> 1\"\n    note summable_Leibniz[OF zeroseq_arctan_series[OF this] monoseq_arctan_series[OF this]]\n  } note arctan_series_borders = this\n\n  have when_less_one: \"arctan x = (\\<Sum>k. ?c x k)\" if \"\\<bar>x\\<bar> < 1\" for x :: real\n  proof -\n    obtain r where \"\\<bar>x\\<bar> < r\" and \"r < 1\"\n      using dense[OF \\<open>\\<bar>x\\<bar> < 1\\<close>] by blast\n    then have \"0 < r\" and \"- r < x\" and \"x < r\" by auto\n\n    have suminf_eq_arctan_bounded: \"suminf (?c x) - arctan x = suminf (?c a) - arctan a\"\n      if \"-r < a\" and \"b < r\" and \"a < b\" and \"a \\<le> x\" and \"x \\<le> b\" for x a b\n    proof -\n      from that have \"\\<bar>x\\<bar> < r\" by auto\n      show \"suminf (?c x) - arctan x = suminf (?c a) - arctan a\"\n      proof (rule DERIV_isconst2[of \"a\" \"b\"])\n        show \"a < b\" and \"a \\<le> x\" and \"x \\<le> b\"\n          using \\<open>a < b\\<close> \\<open>a \\<le> x\\<close> \\<open>x \\<le> b\\<close> by auto\n        have \"\\<forall>x. - r < x \\<and> x < r \\<longrightarrow> DERIV (\\<lambda> x. suminf (?c x) - arctan x) x :> 0\"\n        proof (rule allI, rule impI)\n          fix x\n          assume \"-r < x \\<and> x < r\"\n          then have \"\\<bar>x\\<bar> < r\" by auto\n          with \\<open>r < 1\\<close> have \"\\<bar>x\\<bar> < 1\" by auto\n          have \"\\<bar>- (x\\<^sup>2)\\<bar> < 1\" using abs_square_less_1 \\<open>\\<bar>x\\<bar> < 1\\<close> by auto\n          then have \"(\\<lambda>n. (- (x\\<^sup>2)) ^ n) sums (1 / (1 - (- (x\\<^sup>2))))\"\n            unfolding real_norm_def[symmetric] by (rule geometric_sums)\n          then have \"(?c' x) sums (1 / (1 - (- (x\\<^sup>2))))\"\n            unfolding power_mult_distrib[symmetric] power_mult mult.commute[of _ 2] by auto\n          then have suminf_c'_eq_geom: \"inverse (1 + x\\<^sup>2) = suminf (?c' x)\"\n            using sums_unique unfolding inverse_eq_divide by auto\n          have \"DERIV (\\<lambda> x. suminf (?c x)) x :> (inverse (1 + x\\<^sup>2))\"\n            unfolding suminf_c'_eq_geom\n            by (rule DERIV_arctan_suminf[OF \\<open>0 < r\\<close> \\<open>r < 1\\<close> \\<open>\\<bar>x\\<bar> < r\\<close>])\n          from DERIV_diff [OF this DERIV_arctan] show \"DERIV (\\<lambda>x. suminf (?c x) - arctan x) x :> 0\"\n            by auto\n        qed\n        then have DERIV_in_rball: \"\\<forall>y. a \\<le> y \\<and> y \\<le> b \\<longrightarrow> DERIV (\\<lambda>x. suminf (?c x) - arctan x) y :> 0\"\n          using \\<open>-r < a\\<close> \\<open>b < r\\<close> by auto\n        then show \"\\<And>y. \\<lbrakk>a < y; y < b\\<rbrakk> \\<Longrightarrow> DERIV (\\<lambda>x. suminf (?c x) - arctan x) y :> 0\"\n          using \\<open>\\<bar>x\\<bar> < r\\<close> by auto\n        show \"continuous_on {a..b} (\\<lambda>x. suminf (?c x) - arctan x)\"\n          using DERIV_in_rball DERIV_atLeastAtMost_imp_continuous_on by blast\n      qed\n    qed\n\n    have suminf_arctan_zero: \"suminf (?c 0) - arctan 0 = 0\"\n      unfolding Suc_eq_plus1[symmetric] power_Suc2 mult_zero_right arctan_zero_zero suminf_zero\n      by auto\n\n    have \"suminf (?c x) - arctan x = 0\"\n    proof (cases \"x = 0\")\n      case True\n      then show ?thesis\n        using suminf_arctan_zero by auto\n    next\n      case False\n      then have \"0 < \\<bar>x\\<bar>\" and \"- \\<bar>x\\<bar> < \\<bar>x\\<bar>\"\n        by auto\n      have \"suminf (?c (- \\<bar>x\\<bar>)) - arctan (- \\<bar>x\\<bar>) = suminf (?c 0) - arctan 0\"\n        by (rule suminf_eq_arctan_bounded[where x1=0 and a1=\"-\\<bar>x\\<bar>\" and b1=\"\\<bar>x\\<bar>\", symmetric])\n          (simp_all only: \\<open>\\<bar>x\\<bar> < r\\<close> \\<open>-\\<bar>x\\<bar> < \\<bar>x\\<bar>\\<close> neg_less_iff_less)\n      moreover\n      have \"suminf (?c x) - arctan x = suminf (?c (- \\<bar>x\\<bar>)) - arctan (- \\<bar>x\\<bar>)\"\n        by (rule suminf_eq_arctan_bounded[where x1=x and a1=\"- \\<bar>x\\<bar>\" and b1=\"\\<bar>x\\<bar>\"])\n           (simp_all only: \\<open>\\<bar>x\\<bar> < r\\<close> \\<open>- \\<bar>x\\<bar> < \\<bar>x\\<bar>\\<close> neg_less_iff_less)\n      ultimately show ?thesis\n        using suminf_arctan_zero by auto\n    qed\n    then show ?thesis by auto\n  qed\n\n  show \"arctan x = suminf (\\<lambda>n. ?c x n)\"\n  proof (cases \"\\<bar>x\\<bar> < 1\")\n    case True\n    then show ?thesis by (rule when_less_one)\n  next\n    case False\n    then have \"\\<bar>x\\<bar> = 1\" using \\<open>\\<bar>x\\<bar> \\<le> 1\\<close> by auto\n    let ?a = \"\\<lambda>x n. \\<bar>1 / real (n * 2 + 1) * x^(n * 2 + 1)\\<bar>\"\n    let ?diff = \"\\<lambda>x n. \\<bar>arctan x - (\\<Sum>i<n. ?c x i)\\<bar>\"\n    have \"?diff 1 n \\<le> ?a 1 n\" for n :: nat\n    proof -\n      have \"0 < (1 :: real)\" by auto\n      moreover\n      have \"?diff x n \\<le> ?a x n\" if \"0 < x\" and \"x < 1\" for x :: real\n      proof -\n        from that have \"\\<bar>x\\<bar> \\<le> 1\" and \"\\<bar>x\\<bar> < 1\"\n          by auto\n        from \\<open>0 < x\\<close> have \"0 < 1 / real (0 * 2 + (1::nat)) * x ^ (0 * 2 + 1)\"\n          by auto\n        note bounds = mp[OF arctan_series_borders(2)[OF \\<open>\\<bar>x\\<bar> \\<le> 1\\<close>] this, unfolded when_less_one[OF \\<open>\\<bar>x\\<bar> < 1\\<close>, symmetric], THEN spec]\n        have \"0 < 1 / real (n*2+1) * x^(n*2+1)\"\n          by (rule mult_pos_pos) (simp_all only: zero_less_power[OF \\<open>0 < x\\<close>], auto)\n        then have a_pos: \"?a x n = 1 / real (n*2+1) * x^(n*2+1)\"\n          by (rule abs_of_pos)\n        show ?thesis\n        proof (cases \"even n\")\n          case True\n          then have sgn_pos: \"(-1)^n = (1::real)\" by auto\n          from \\<open>even n\\<close> obtain m where \"n = 2 * m\" ..\n          then have \"2 * m = n\" ..\n          from bounds[of m, unfolded this atLeastAtMost_iff]\n          have \"\\<bar>arctan x - (\\<Sum>i<n. (?c x i))\\<bar> \\<le> (\\<Sum>i<n + 1. (?c x i)) - (\\<Sum>i<n. (?c x i))\"\n            by auto\n          also have \"\\<dots> = ?c x n\" by auto\n          also have \"\\<dots> = ?a x n\" unfolding sgn_pos a_pos by auto\n          finally show ?thesis .\n        next\n          case False\n          then have sgn_neg: \"(-1)^n = (-1::real)\" by auto\n          from \\<open>odd n\\<close> obtain m where \"n = 2 * m + 1\" ..\n          then have m_def: \"2 * m + 1 = n\" ..\n          then have m_plus: \"2 * (m + 1) = n + 1\" by auto\n          from bounds[of \"m + 1\", unfolded this atLeastAtMost_iff, THEN conjunct1] bounds[of m, unfolded m_def atLeastAtMost_iff, THEN conjunct2]\n          have \"\\<bar>arctan x - (\\<Sum>i<n. (?c x i))\\<bar> \\<le> (\\<Sum>i<n. (?c x i)) - (\\<Sum>i<n+1. (?c x i))\" by auto\n          also have \"\\<dots> = - ?c x n\" by auto\n          also have \"\\<dots> = ?a x n\" unfolding sgn_neg a_pos by auto\n          finally show ?thesis .\n        qed\n      qed\n      hence \"\\<forall>x \\<in> { 0 <..< 1 }. 0 \\<le> ?a x n - ?diff x n\" by auto\n      moreover have \"isCont (\\<lambda> x. ?a x n - ?diff x n) x\" for x\n        unfolding diff_conv_add_uminus divide_inverse\n        by (auto intro!: isCont_add isCont_rabs continuous_ident isCont_minus isCont_arctan\n          continuous_at_within_inverse isCont_mult isCont_power continuous_const isCont_sum\n          simp del: add_uminus_conv_diff)\n      ultimately have \"0 \\<le> ?a 1 n - ?diff 1 n\"\n        by (rule LIM_less_bound)\n      then show ?thesis by auto\n    qed\n    have \"?a 1 \\<longlonglongrightarrow> 0\"\n      unfolding tendsto_rabs_zero_iff power_one divide_inverse One_nat_def\n      by (auto intro!: tendsto_mult LIMSEQ_linear LIMSEQ_inverse_real_of_nat simp del: of_nat_Suc)\n    have \"?diff 1 \\<longlonglongrightarrow> 0\"\n    proof (rule LIMSEQ_I)\n      fix r :: real\n      assume \"0 < r\"\n      obtain N :: nat where N_I: \"N \\<le> n \\<Longrightarrow> ?a 1 n < r\" for n\n        using LIMSEQ_D[OF \\<open>?a 1 \\<longlonglongrightarrow> 0\\<close> \\<open>0 < r\\<close>] by auto\n      have \"norm (?diff 1 n - 0) < r\" if \"N \\<le> n\" for n\n        using \\<open>?diff 1 n \\<le> ?a 1 n\\<close> N_I[OF that] by auto\n      then show \"\\<exists>N. \\<forall> n \\<ge> N. norm (?diff 1 n - 0) < r\" by blast\n    qed\n    from this [unfolded tendsto_rabs_zero_iff, THEN tendsto_add [OF _ tendsto_const], of \"- arctan 1\", THEN tendsto_minus]\n    have \"(?c 1) sums (arctan 1)\" unfolding sums_def by auto\n    then have \"arctan 1 = (\\<Sum>i. ?c 1 i)\" by (rule sums_unique)\n\n    show ?thesis\n    proof (cases \"x = 1\")\n      case True\n      then show ?thesis by (simp add: \\<open>arctan 1 = (\\<Sum> i. ?c 1 i)\\<close>)\n    next\n      case False\n      then have \"x = -1\" using \\<open>\\<bar>x\\<bar> = 1\\<close> by auto\n\n      have \"- (pi/2) < 0\" using pi_gt_zero by auto\n      have \"- (2 * pi) < 0\" using pi_gt_zero by auto\n\n      have c_minus_minus: \"?c (- 1) i = - ?c 1 i\" for i by auto\n\n      have \"arctan (- 1) = arctan (tan (-(pi/4)))\"\n        unfolding tan_45 tan_minus ..\n      also have \"\\<dots> = - (pi/4)\"\n        by (rule arctan_tan) (auto simp: order_less_trans[OF \\<open>- (pi/2) < 0\\<close> pi_gt_zero])\n      also have \"\\<dots> = - (arctan (tan (pi/4)))\"\n        unfolding neg_equal_iff_equal\n        by (rule arctan_tan[symmetric]) (auto simp: order_less_trans[OF \\<open>- (2 * pi) < 0\\<close> pi_gt_zero])\n      also have \"\\<dots> = - (arctan 1)\"\n        unfolding tan_45 ..\n      also have \"\\<dots> = - (\\<Sum> i. ?c 1 i)\"\n        using \\<open>arctan 1 = (\\<Sum> i. ?c 1 i)\\<close> by auto\n      also have \"\\<dots> = (\\<Sum> i. ?c (- 1) i)\"\n        using suminf_minus[OF sums_summable[OF \\<open>(?c 1) sums (arctan 1)\\<close>]]\n        unfolding c_minus_minus by auto\n      finally show ?thesis using \\<open>x = -1\\<close> by auto\n    qed\n  qed\nqed\n\nlemma arctan_half: \"arctan x = 2 * arctan (x / (1 + sqrt(1 + x\\<^sup>2)))\"\n  for x :: real\nproof -\n  obtain y where low: \"- (pi/2) < y\" and high: \"y < pi/2\" and y_eq: \"tan y = x\"\n    using tan_total by blast\n  then have low2: \"- (pi/2) < y / 2\" and high2: \"y / 2 < pi/2\"\n    by auto\n\n  have \"0 < cos y\" by (rule cos_gt_zero_pi[OF low high])\n  then have \"cos y \\<noteq> 0\" and cos_sqrt: \"sqrt ((cos y)\\<^sup>2) = cos y\"\n    by auto\n\n  have \"1 + (tan y)\\<^sup>2 = 1 + (sin y)\\<^sup>2 / (cos y)\\<^sup>2\"\n    unfolding tan_def power_divide ..\n  also have \"\\<dots> = (cos y)\\<^sup>2 / (cos y)\\<^sup>2 + (sin y)\\<^sup>2 / (cos y)\\<^sup>2\"\n    using \\<open>cos y \\<noteq> 0\\<close> by auto\n  also have \"\\<dots> = 1 / (cos y)\\<^sup>2\"\n    unfolding add_divide_distrib[symmetric] sin_cos_squared_add2 ..\n  finally have \"1 + (tan y)\\<^sup>2 = 1 / (cos y)\\<^sup>2\" .\n\n  have \"sin y / (cos y + 1) = tan y / ((cos y + 1) / cos y)\"\n    unfolding tan_def using \\<open>cos y \\<noteq> 0\\<close> by (simp add: field_simps)\n  also have \"\\<dots> = tan y / (1 + 1 / cos y)\"\n    using \\<open>cos y \\<noteq> 0\\<close> unfolding add_divide_distrib by auto\n  also have \"\\<dots> = tan y / (1 + 1 / sqrt ((cos y)\\<^sup>2))\"\n    unfolding cos_sqrt ..\n  also have \"\\<dots> = tan y / (1 + sqrt (1 / (cos y)\\<^sup>2))\"\n    unfolding real_sqrt_divide by auto\n  finally have eq: \"sin y / (cos y + 1) = tan y / (1 + sqrt(1 + (tan y)\\<^sup>2))\"\n    unfolding \\<open>1 + (tan y)\\<^sup>2 = 1 / (cos y)\\<^sup>2\\<close> .\n\n  have \"arctan x = y\"\n    using arctan_tan low high y_eq by auto\n  also have \"\\<dots> = 2 * (arctan (tan (y/2)))\"\n    using arctan_tan[OF low2 high2] by auto\n  also have \"\\<dots> = 2 * (arctan (sin y / (cos y + 1)))\"\n    unfolding tan_half by auto\n  finally show ?thesis\n    unfolding eq \\<open>tan y = x\\<close> .\nqed\n\nlemma arctan_monotone: \"x < y \\<Longrightarrow> arctan x < arctan y\"\n  by (simp only: arctan_less_iff)\n\nlemma arctan_monotone': \"x \\<le> y \\<Longrightarrow> arctan x \\<le> arctan y\"\n  by (simp only: arctan_le_iff)\n\nlemma arctan_inverse:\n  assumes \"x \\<noteq> 0\"\n  shows \"arctan (1 / x) = sgn x * pi/2 - arctan x\"\nproof (rule arctan_unique)\n  have \\<section>: \"x > 0 \\<Longrightarrow> arctan x < pi\"\n    using arctan_bounded [of x] by linarith \n  show \"- (pi/2) < sgn x * pi/2 - arctan x\"\n    using assms by (auto simp: sgn_real_def arctan algebra_simps \\<section>)\n  show \"sgn x * pi/2 - arctan x < pi/2\"\n    using arctan_bounded [of \"- x\"] assms\n    by (auto simp: algebra_simps sgn_real_def arctan_minus)\n  show \"tan (sgn x * pi/2 - arctan x) = 1 / x\"\n    unfolding tan_inverse [of \"arctan x\", unfolded tan_arctan] sgn_real_def\n    by (simp add: tan_def cos_arctan sin_arctan sin_diff cos_diff)\nqed\n\ntheorem pi_series: \"pi/4 = (\\<Sum>k. (-1)^k * 1 / real (k * 2 + 1))\"\n  (is \"_ = ?SUM\")\nproof -\n  have \"pi/4 = arctan 1\"\n    using arctan_one by auto\n  also have \"\\<dots> = ?SUM\"\n    using arctan_series[of 1] by auto\n  finally show ?thesis by auto\nqed\n\n\nsubsection \\<open>Existence of Polar Coordinates\\<close>\n\nlemma cos_x_y_le_one: \"\\<bar>x / sqrt (x\\<^sup>2 + y\\<^sup>2)\\<bar> \\<le> 1\"\n  by (rule power2_le_imp_le [OF _ zero_le_one])\n    (simp add: power_divide divide_le_eq not_sum_power2_lt_zero)\n\nlemma polar_Ex: \"\\<exists>r::real. \\<exists>a. x = r * cos a \\<and> y = r * sin a\"\nproof -\n  have polar_ex1: \"\\<exists>r a. x = r * cos a \\<and> y = r * sin a\" if \"0 < y\" for y\n  proof -\n    have \"x = sqrt (x\\<^sup>2 + y\\<^sup>2) * cos (arccos (x / sqrt (x\\<^sup>2 + y\\<^sup>2)))\"\n      by (simp add: cos_arccos_abs [OF cos_x_y_le_one])\n    moreover have \"y = sqrt (x\\<^sup>2 + y\\<^sup>2) * sin (arccos (x / sqrt (x\\<^sup>2 + y\\<^sup>2)))\"\n      using that\n      by (simp add: sin_arccos_abs [OF cos_x_y_le_one] power_divide right_diff_distrib flip: real_sqrt_mult)\n    ultimately show ?thesis\n      by blast\n  qed\n  show ?thesis\n  proof (cases \"0::real\" y rule: linorder_cases)\n    case less\n    then show ?thesis\n      by (rule polar_ex1)\n  next\n    case equal\n    then show ?thesis\n      by (force simp: intro!: cos_zero sin_zero)\n  next\n    case greater\n    with polar_ex1 [where y=\"-y\"] show ?thesis\n      by auto (metis cos_minus minus_minus minus_mult_right sin_minus)\n  qed\nqed\n\n\nsubsection \\<open>Basics about polynomial functions: products, extremal behaviour and root counts\\<close>\n\nlemma pairs_le_eq_Sigma: \"{(i, j). i + j \\<le> m} = Sigma (atMost m) (\\<lambda>r. atMost (m - r))\"\n  for m :: nat\n  by auto\n\nlemma sum_up_index_split: \"(\\<Sum>k\\<le>m + n. f k) = (\\<Sum>k\\<le>m. f k) + (\\<Sum>k = Suc m..m + n. f k)\"\n  by (metis atLeast0AtMost Suc_eq_plus1 le0 sum.ub_add_nat)\n\nlemma Sigma_interval_disjoint: \"(SIGMA i:A. {..v i}) \\<inter> (SIGMA i:A.{v i<..w}) = {}\"\n  for w :: \"'a::order\"\n  by auto\n\nlemma product_atMost_eq_Un: \"A \\<times> {..m} = (SIGMA i:A.{..m - i}) \\<union> (SIGMA i:A.{m - i<..m})\"\n  for m :: nat\n  by auto\n\nlemma polynomial_product: (*with thanks to Chaitanya Mangla*)\n  fixes x :: \"'a::idom\"\n  assumes m: \"\\<And>i. i > m \\<Longrightarrow> a i = 0\"\n    and n: \"\\<And>j. j > n \\<Longrightarrow> b j = 0\"\n  shows \"(\\<Sum>i\\<le>m. (a i) * x ^ i) * (\\<Sum>j\\<le>n. (b j) * x ^ j) =\n         (\\<Sum>r\\<le>m + n. (\\<Sum>k\\<le>r. (a k) * (b (r - k))) * x ^ r)\"\nproof -\n  have \"\\<And>i j. \\<lbrakk>m + n - i < j; a i \\<noteq> 0\\<rbrakk> \\<Longrightarrow> b j = 0\"\n    by (meson le_add_diff leI le_less_trans m n)\n  then have \\<section>: \"(\\<Sum>(i,j)\\<in>(SIGMA i:{..m+n}. {m+n - i<..m+n}). a i * x ^ i * (b j * x ^ j)) = 0\"\n    by (clarsimp simp add: sum_Un Sigma_interval_disjoint intro!: sum.neutral)\n  have \"(\\<Sum>i\\<le>m. (a i) * x ^ i) * (\\<Sum>j\\<le>n. (b j) * x ^ j) = (\\<Sum>i\\<le>m. \\<Sum>j\\<le>n. (a i * x ^ i) * (b j * x ^ j))\"\n    by (rule sum_product)\n  also have \"\\<dots> = (\\<Sum>i\\<le>m + n. \\<Sum>j\\<le>n + m. a i * x ^ i * (b j * x ^ j))\"\n    using assms by (auto simp: sum_up_index_split)\n  also have \"\\<dots> = (\\<Sum>r\\<le>m + n. \\<Sum>j\\<le>m + n - r. a r * x ^ r * (b j * x ^ j))\"\n    by (simp add: add_ac sum.Sigma product_atMost_eq_Un sum_Un Sigma_interval_disjoint \\<section>)\n  also have \"\\<dots> = (\\<Sum>(i,j)\\<in>{(i,j). i+j \\<le> m+n}. (a i * x ^ i) * (b j * x ^ j))\"\n    by (auto simp: pairs_le_eq_Sigma sum.Sigma)\n  also have \"... = (\\<Sum>k\\<le>m + n. \\<Sum>i\\<le>k. a i * x ^ i * (b (k - i) * x ^ (k - i)))\"\n    by (rule sum.triangle_reindex_eq)\n  also have \"\\<dots> = (\\<Sum>r\\<le>m + n. (\\<Sum>k\\<le>r. (a k) * (b (r - k))) * x ^ r)\"\n    by (auto simp: algebra_simps sum_distrib_left simp flip: power_add intro!: sum.cong)\n  finally show ?thesis .\nqed\n\nlemma polynomial_product_nat:\n  fixes x :: nat\n  assumes m: \"\\<And>i. i > m \\<Longrightarrow> a i = 0\"\n    and n: \"\\<And>j. j > n \\<Longrightarrow> b j = 0\"\n  shows \"(\\<Sum>i\\<le>m. (a i) * x ^ i) * (\\<Sum>j\\<le>n. (b j) * x ^ j) =\n         (\\<Sum>r\\<le>m + n. (\\<Sum>k\\<le>r. (a k) * (b (r - k))) * x ^ r)\"\n  using polynomial_product [of m a n b x] assms\n  by (simp only: of_nat_mult [symmetric] of_nat_power [symmetric]\n      of_nat_eq_iff Int.int_sum [symmetric])\n\nlemma polyfun_diff: (*COMPLEX_SUB_POLYFUN in HOL Light*)\n  fixes x :: \"'a::idom\"\n  assumes \"1 \\<le> n\"\n  shows \"(\\<Sum>i\\<le>n. a i * x^i) - (\\<Sum>i\\<le>n. a i * y^i) =\n    (x - y) * (\\<Sum>j<n. (\\<Sum>i=Suc j..n. a i * y^(i - j - 1)) * x^j)\"\nproof -\n  have h: \"bij_betw (\\<lambda>(i,j). (j,i)) ((SIGMA i : atMost n. lessThan i)) (SIGMA j : lessThan n. {Suc j..n})\"\n    by (auto simp: bij_betw_def inj_on_def)\n  have \"(\\<Sum>i\\<le>n. a i * x^i) - (\\<Sum>i\\<le>n. a i * y^i) = (\\<Sum>i\\<le>n. a i * (x^i - y^i))\"\n    by (simp add: right_diff_distrib sum_subtractf)\n  also have \"\\<dots> = (\\<Sum>i\\<le>n. a i * (x - y) * (\\<Sum>j<i. y^(i - Suc j) * x^j))\"\n    by (simp add: power_diff_sumr2 mult.assoc)\n  also have \"\\<dots> = (\\<Sum>i\\<le>n. \\<Sum>j<i. a i * (x - y) * (y^(i - Suc j) * x^j))\"\n    by (simp add: sum_distrib_left)\n  also have \"\\<dots> = (\\<Sum>(i,j) \\<in> (SIGMA i : atMost n. lessThan i). a i * (x - y) * (y^(i - Suc j) * x^j))\"\n    by (simp add: sum.Sigma)\n  also have \"\\<dots> = (\\<Sum>(j,i) \\<in> (SIGMA j : lessThan n. {Suc j..n}). a i * (x - y) * (y^(i - Suc j) * x^j))\"\n    by (auto simp: sum.reindex_bij_betw [OF h, symmetric] intro: sum.cong_simp)\n  also have \"\\<dots> = (\\<Sum>j<n. \\<Sum>i=Suc j..n. a i * (x - y) * (y^(i - Suc j) * x^j))\"\n    by (simp add: sum.Sigma)\n  also have \"\\<dots> = (x - y) * (\\<Sum>j<n. (\\<Sum>i=Suc j..n. a i * y^(i - j - 1)) * x^j)\"\n    by (simp add: sum_distrib_left mult_ac)\n  finally show ?thesis .\nqed\n\nlemma polyfun_diff_alt: (*COMPLEX_SUB_POLYFUN_ALT in HOL Light*)\n  fixes x :: \"'a::idom\"\n  assumes \"1 \\<le> n\"\n  shows \"(\\<Sum>i\\<le>n. a i * x^i) - (\\<Sum>i\\<le>n. a i * y^i) =\n    (x - y) * ((\\<Sum>j<n. \\<Sum>k<n-j. a(j + k + 1) * y^k * x^j))\"\nproof -\n  have \"(\\<Sum>i=Suc j..n. a i * y^(i - j - 1)) = (\\<Sum>k<n-j. a(j+k+1) * y^k)\"\n    if \"j < n\" for j :: nat\n  proof -\n    have \"\\<And>k. k < n - j \\<Longrightarrow> k \\<in> (\\<lambda>i. i - Suc j) ` {Suc j..n}\"\n      by (rule_tac x=\"k + Suc j\" in image_eqI, auto)\n    then have h: \"bij_betw (\\<lambda>i. i - (j + 1)) {Suc j..n} (lessThan (n-j))\"\n      by (auto simp: bij_betw_def inj_on_def)\n    then show ?thesis\n      by (auto simp: sum.reindex_bij_betw [OF h, symmetric] intro: sum.cong_simp)\n  qed\n  then show ?thesis\n    by (simp add: polyfun_diff [OF assms] sum_distrib_right)\nqed\n\nlemma polyfun_linear_factor:  (*COMPLEX_POLYFUN_LINEAR_FACTOR in HOL Light*)\n  fixes a :: \"'a::idom\"\n  shows \"\\<exists>b. \\<forall>z. (\\<Sum>i\\<le>n. c(i) * z^i) = (z - a) * (\\<Sum>i<n. b(i) * z^i) + (\\<Sum>i\\<le>n. c(i) * a^i)\"\nproof (cases \"n = 0\")\n  case True then show ?thesis\n    by simp\nnext\n  case False\n  have \"(\\<exists>b. \\<forall>z. (\\<Sum>i\\<le>n. c i * z^i) = (z - a) * (\\<Sum>i<n. b i * z^i) + (\\<Sum>i\\<le>n. c i * a^i)) \\<longleftrightarrow>\n        (\\<exists>b. \\<forall>z. (\\<Sum>i\\<le>n. c i * z^i) - (\\<Sum>i\\<le>n. c i * a^i) = (z - a) * (\\<Sum>i<n. b i * z^i))\"\n    by (simp add: algebra_simps)\n  also have \"\\<dots> \\<longleftrightarrow>\n    (\\<exists>b. \\<forall>z. (z - a) * (\\<Sum>j<n. (\\<Sum>i = Suc j..n. c i * a^(i - Suc j)) * z^j) =\n      (z - a) * (\\<Sum>i<n. b i * z^i))\"\n    using False by (simp add: polyfun_diff)\n  also have \"\\<dots> = True\" by auto\n  finally show ?thesis\n    by simp\nqed\n\nlemma polyfun_linear_factor_root:  (*COMPLEX_POLYFUN_LINEAR_FACTOR_ROOT in HOL Light*)\n  fixes a :: \"'a::idom\"\n  assumes \"(\\<Sum>i\\<le>n. c(i) * a^i) = 0\"\n  obtains b where \"\\<And>z. (\\<Sum>i\\<le>n. c i * z^i) = (z - a) * (\\<Sum>i<n. b i * z^i)\"\n  using polyfun_linear_factor [of c n a] assms by auto\n\n(*The material of this section, up until this point, could go into a new theory of polynomials\n  based on Main alone. The remaining material involves limits, continuity, series, etc.*)\n\nlemma isCont_polynom: \"isCont (\\<lambda>w. \\<Sum>i\\<le>n. c i * w^i) a\"\n  for c :: \"nat \\<Rightarrow> 'a::real_normed_div_algebra\"\n  by simp\n\nlemma zero_polynom_imp_zero_coeffs:\n  fixes c :: \"nat \\<Rightarrow> 'a::{ab_semigroup_mult,real_normed_div_algebra}\"\n  assumes \"\\<And>w. (\\<Sum>i\\<le>n. c i * w^i) = 0\"  \"k \\<le> n\"\n  shows \"c k = 0\"\n  using assms\nproof (induction n arbitrary: c k)\n  case 0\n  then show ?case\n    by simp\nnext\n  case (Suc n c k)\n  have [simp]: \"c 0 = 0\" using Suc.prems(1) [of 0]\n    by simp\n  have \"(\\<Sum>i\\<le>Suc n. c i * w^i) = w * (\\<Sum>i\\<le>n. c (Suc i) * w^i)\" for w\n  proof -\n    have \"(\\<Sum>i\\<le>Suc n. c i * w^i) = (\\<Sum>i\\<le>n. c (Suc i) * w ^ Suc i)\"\n      unfolding Set_Interval.sum.atMost_Suc_shift\n      by simp\n    also have \"\\<dots> = w * (\\<Sum>i\\<le>n. c (Suc i) * w^i)\"\n      by (simp add: sum_distrib_left ac_simps)\n    finally show ?thesis .\n  qed\n  then have w: \"\\<And>w. w \\<noteq> 0 \\<Longrightarrow> (\\<Sum>i\\<le>n. c (Suc i) * w^i) = 0\"\n    using Suc  by auto\n  then have \"(\\<lambda>h. \\<Sum>i\\<le>n. c (Suc i) * h^i) \\<midarrow>0\\<rightarrow> 0\"\n    by (simp cong: LIM_cong)  \\<comment> \\<open>the case \\<open>w = 0\\<close> by continuity\\<close>\n  then have \"(\\<Sum>i\\<le>n. c (Suc i) * 0^i) = 0\"\n    using isCont_polynom [of 0 \"\\<lambda>i. c (Suc i)\" n] LIM_unique\n    by (force simp: Limits.isCont_iff)\n  then have \"\\<And>w. (\\<Sum>i\\<le>n. c (Suc i) * w^i) = 0\"\n    using w by metis\n  then have \"\\<And>i. i \\<le> n \\<Longrightarrow> c (Suc i) = 0\"\n    using Suc.IH [of \"\\<lambda>i. c (Suc i)\"] by blast\n  then show ?case using \\<open>k \\<le> Suc n\\<close>\n    by (cases k) auto\nqed\n\nlemma polyfun_rootbound: (*COMPLEX_POLYFUN_ROOTBOUND in HOL Light*)\n  fixes c :: \"nat \\<Rightarrow> 'a::{idom,real_normed_div_algebra}\"\n  assumes \"c k \\<noteq> 0\" \"k\\<le>n\"\n  shows \"finite {z. (\\<Sum>i\\<le>n. c(i) * z^i) = 0} \\<and> card {z. (\\<Sum>i\\<le>n. c(i) * z^i) = 0} \\<le> n\"\n  using assms\nproof (induction n arbitrary: c k)\n  case 0\n  then show ?case\n    by simp\nnext\n  case (Suc m c k)\n  let ?succase = ?case\n  show ?case\n  proof (cases \"{z. (\\<Sum>i\\<le>Suc m. c(i) * z^i) = 0} = {}\")\n    case True\n    then show ?succase\n      by simp\n  next\n    case False\n    then obtain z0 where z0: \"(\\<Sum>i\\<le>Suc m. c(i) * z0^i) = 0\"\n      by blast\n    then obtain b where b: \"\\<And>w. (\\<Sum>i\\<le>Suc m. c i * w^i) = (w - z0) * (\\<Sum>i\\<le>m. b i * w^i)\"\n      using polyfun_linear_factor_root [OF z0, unfolded lessThan_Suc_atMost]\n      by blast\n    then have eq: \"{z. (\\<Sum>i\\<le>Suc m. c i * z^i) = 0} = insert z0 {z. (\\<Sum>i\\<le>m. b i * z^i) = 0}\"\n      by auto\n    have \"\\<not> (\\<forall>k\\<le>m. b k = 0)\"\n    proof\n      assume [simp]: \"\\<forall>k\\<le>m. b k = 0\"\n      then have \"\\<And>w. (\\<Sum>i\\<le>m. b i * w^i) = 0\"\n        by simp\n      then have \"\\<And>w. (\\<Sum>i\\<le>Suc m. c i * w^i) = 0\"\n        using b by simp\n      then have \"\\<And>k. k \\<le> Suc m \\<Longrightarrow> c k = 0\"\n        using zero_polynom_imp_zero_coeffs by blast\n      then show False using Suc.prems by blast\n    qed\n    then obtain k' where bk': \"b k' \\<noteq> 0\" \"k' \\<le> m\"\n      by blast\n    show ?succase\n      using Suc.IH [of b k'] bk'\n      by (simp add: eq card_insert_if del: sum.atMost_Suc)\n    qed\nqed\n\nlemma\n  fixes c :: \"nat \\<Rightarrow> 'a::{idom,real_normed_div_algebra}\"\n  assumes \"c k \\<noteq> 0\" \"k\\<le>n\"\n  shows polyfun_roots_finite: \"finite {z. (\\<Sum>i\\<le>n. c(i) * z^i) = 0}\"\n    and polyfun_roots_card: \"card {z. (\\<Sum>i\\<le>n. c(i) * z^i) = 0} \\<le> n\"\n  using polyfun_rootbound assms by auto\n\nlemma polyfun_finite_roots: (*COMPLEX_POLYFUN_FINITE_ROOTS in HOL Light*)\n  fixes c :: \"nat \\<Rightarrow> 'a::{idom,real_normed_div_algebra}\"\n  shows \"finite {x. (\\<Sum>i\\<le>n. c i * x^i) = 0} \\<longleftrightarrow> (\\<exists>i\\<le>n. c i \\<noteq> 0)\"\n    (is \"?lhs = ?rhs\")\nproof\n  assume ?lhs\n  moreover have \"\\<not> finite {x. (\\<Sum>i\\<le>n. c i * x^i) = 0}\" if \"\\<forall>i\\<le>n. c i = 0\"\n  proof -\n    from that have \"\\<And>x. (\\<Sum>i\\<le>n. c i * x^i) = 0\"\n      by simp\n    then show ?thesis\n      using ex_new_if_finite [OF infinite_UNIV_char_0 [where 'a='a]]\n      by auto\n  qed\n  ultimately show ?rhs by metis\nnext\n  assume ?rhs\n  with polyfun_rootbound show ?lhs by blast\nqed\n\nlemma polyfun_eq_0: \"(\\<forall>x. (\\<Sum>i\\<le>n. c i * x^i) = 0) \\<longleftrightarrow> (\\<forall>i\\<le>n. c i = 0)\"\n  for c :: \"nat \\<Rightarrow> 'a::{idom,real_normed_div_algebra}\"\n  (*COMPLEX_POLYFUN_EQ_0 in HOL Light*)\n  using zero_polynom_imp_zero_coeffs by auto\n\nlemma polyfun_eq_coeffs: \"(\\<forall>x. (\\<Sum>i\\<le>n. c i * x^i) = (\\<Sum>i\\<le>n. d i * x^i)) \\<longleftrightarrow> (\\<forall>i\\<le>n. c i = d i)\"\n  for c :: \"nat \\<Rightarrow> 'a::{idom,real_normed_div_algebra}\"\nproof -\n  have \"(\\<forall>x. (\\<Sum>i\\<le>n. c i * x^i) = (\\<Sum>i\\<le>n. d i * x^i)) \\<longleftrightarrow> (\\<forall>x. (\\<Sum>i\\<le>n. (c i - d i) * x^i) = 0)\"\n    by (simp add: left_diff_distrib Groups_Big.sum_subtractf)\n  also have \"\\<dots> \\<longleftrightarrow> (\\<forall>i\\<le>n. c i - d i = 0)\"\n    by (rule polyfun_eq_0)\n  finally show ?thesis\n    by simp\nqed\n\nlemma polyfun_eq_const: (*COMPLEX_POLYFUN_EQ_CONST in HOL Light*)\n  fixes c :: \"nat \\<Rightarrow> 'a::{idom,real_normed_div_algebra}\"\n  shows \"(\\<forall>x. (\\<Sum>i\\<le>n. c i * x^i) = k) \\<longleftrightarrow> c 0 = k \\<and> (\\<forall>i \\<in> {1..n}. c i = 0)\"\n    (is \"?lhs = ?rhs\")\nproof -\n  have *: \"\\<forall>x. (\\<Sum>i\\<le>n. (if i=0 then k else 0) * x^i) = k\"\n    by (induct n) auto\n  show ?thesis\n  proof\n    assume ?lhs\n    with * have \"(\\<forall>i\\<le>n. c i = (if i=0 then k else 0))\"\n      by (simp add: polyfun_eq_coeffs [symmetric])\n    then show ?rhs by simp\n  next\n    assume ?rhs\n    then show ?lhs by (induct n) auto\n  qed\nqed\n\nlemma root_polyfun:\n  fixes z :: \"'a::idom\"\n  assumes \"1 \\<le> n\"\n  shows \"z^n = a \\<longleftrightarrow> (\\<Sum>i\\<le>n. (if i = 0 then -a else if i=n then 1 else 0) * z^i) = 0\"\n  using assms by (cases n) (simp_all add: sum.atLeast_Suc_atMost atLeast0AtMost [symmetric])\n\nlemma\n  assumes \"SORT_CONSTRAINT('a::{idom,real_normed_div_algebra})\"\n    and \"1 \\<le> n\"\n  shows finite_roots_unity: \"finite {z::'a. z^n = 1}\"\n    and card_roots_unity: \"card {z::'a. z^n = 1} \\<le> n\"\n  using polyfun_rootbound [of \"\\<lambda>i. if i = 0 then -1 else if i=n then 1 else 0\" n n] assms(2)\n  by (auto simp: root_polyfun [OF assms(2)])\n\n\nsubsection \\<open>Hyperbolic functions\\<close>\n\ndefinition sinh :: \"'a :: {banach, real_normed_algebra_1} \\<Rightarrow> 'a\" where\n  \"sinh x = (exp x - exp (-x)) /\\<^sub>R 2\"\n\ndefinition cosh :: \"'a :: {banach, real_normed_algebra_1} \\<Rightarrow> 'a\" where\n  \"cosh x = (exp x + exp (-x)) /\\<^sub>R 2\"\n\ndefinition tanh :: \"'a :: {banach, real_normed_field} \\<Rightarrow> 'a\" where\n  \"tanh x = sinh x / cosh x\"\n\ndefinition arsinh :: \"'a :: {banach, real_normed_algebra_1, ln} \\<Rightarrow> 'a\" where\n  \"arsinh x = ln (x + (x^2 + 1) powr of_real (1/2))\"\n\ndefinition arcosh :: \"'a :: {banach, real_normed_algebra_1, ln} \\<Rightarrow> 'a\" where\n  \"arcosh x = ln (x + (x^2 - 1) powr of_real (1/2))\"\n\ndefinition artanh :: \"'a :: {banach, real_normed_field, ln} \\<Rightarrow> 'a\" where\n  \"artanh x = ln ((1 + x) / (1 - x)) / 2\"\n\nlemma arsinh_0 [simp]: \"arsinh 0 = 0\"\n  by (simp add: arsinh_def)\n\nlemma arcosh_1 [simp]: \"arcosh 1 = 0\"\n  by (simp add: arcosh_def)\n\nlemma artanh_0 [simp]: \"artanh 0 = 0\"\n  by (simp add: artanh_def)\n\nlemma tanh_altdef:\n  \"tanh x = (exp x - exp (-x)) / (exp x + exp (-x))\"\nproof -\n  have \"tanh x = (2 *\\<^sub>R sinh x) / (2 *\\<^sub>R cosh x)\"\n    by (simp add: tanh_def scaleR_conv_of_real)\n  also have \"2 *\\<^sub>R sinh x = exp x - exp (-x)\"\n    by (simp add: sinh_def)\n  also have \"2 *\\<^sub>R cosh x = exp x + exp (-x)\"\n    by (simp add: cosh_def)\n  finally show ?thesis .\nqed\n\nlemma tanh_real_altdef: \"tanh (x::real) = (1 - exp (- 2 * x)) / (1 + exp (- 2 * x))\"\nproof -\n  have [simp]: \"exp (2 * x) = exp x * exp x\" \"exp (x * 2) = exp x * exp x\"\n    by (subst exp_add [symmetric]; simp)+\n  have \"tanh x = (2 * exp (-x) * sinh x) / (2 * exp (-x) * cosh x)\"\n    by (simp add: tanh_def)\n  also have \"2 * exp (-x) * sinh x = 1 - exp (-2*x)\"\n    by (simp add: exp_minus field_simps sinh_def)\n  also have \"2 * exp (-x) * cosh x = 1 + exp (-2*x)\"\n    by (simp add: exp_minus field_simps cosh_def)\n  finally show ?thesis .\nqed\n\n\nlemma sinh_converges: \"(\\<lambda>n. if even n then 0 else x ^ n /\\<^sub>R fact n) sums sinh x\"\nproof -\n  have \"(\\<lambda>n. (x ^ n /\\<^sub>R fact n - (-x) ^ n /\\<^sub>R fact n) /\\<^sub>R 2) sums sinh x\"\n    unfolding sinh_def by (intro sums_scaleR_right sums_diff exp_converges)\n  also have \"(\\<lambda>n. (x ^ n /\\<^sub>R fact n - (-x) ^ n /\\<^sub>R fact n) /\\<^sub>R 2) =\n               (\\<lambda>n. if even n then 0 else x ^ n /\\<^sub>R fact n)\" by auto\n  finally show ?thesis .\nqed\n\nlemma cosh_converges: \"(\\<lambda>n. if even n then x ^ n /\\<^sub>R fact n else 0) sums cosh x\"\nproof -\n  have \"(\\<lambda>n. (x ^ n /\\<^sub>R fact n + (-x) ^ n /\\<^sub>R fact n) /\\<^sub>R 2) sums cosh x\"\n    unfolding cosh_def by (intro sums_scaleR_right sums_add exp_converges)\n  also have \"(\\<lambda>n. (x ^ n /\\<^sub>R fact n + (-x) ^ n /\\<^sub>R fact n) /\\<^sub>R 2) =\n               (\\<lambda>n. if even n then x ^ n /\\<^sub>R fact n else 0)\" by auto\n  finally show ?thesis .\nqed\n\nlemma sinh_0 [simp]: \"sinh 0 = 0\"\n  by (simp add: sinh_def)\n\nlemma cosh_0 [simp]: \"cosh 0 = 1\"\nproof -\n  have \"cosh 0 = (1/2) *\\<^sub>R (1 + 1)\" by (simp add: cosh_def)\n  also have \"\\<dots> = 1\" by (rule scaleR_half_double)\n  finally show ?thesis .\nqed\n\nlemma tanh_0 [simp]: \"tanh 0 = 0\"\n  by (simp add: tanh_def)\n\nlemma sinh_minus [simp]: \"sinh (- x) = -sinh x\"\n  by (simp add: sinh_def algebra_simps)\n\nlemma cosh_minus [simp]: \"cosh (- x) = cosh x\"\n  by (simp add: cosh_def algebra_simps)\n\nlemma tanh_minus [simp]: \"tanh (-x) = -tanh x\"\n  by (simp add: tanh_def)\n\nlemma sinh_ln_real: \"x > 0 \\<Longrightarrow> sinh (ln x :: real) = (x - inverse x) / 2\"\n  by (simp add: sinh_def exp_minus)\n\nlemma cosh_ln_real: \"x > 0 \\<Longrightarrow> cosh (ln x :: real) = (x + inverse x) / 2\"\n  by (simp add: cosh_def exp_minus)\n\nlemma tanh_ln_real:\n  \"tanh (ln x :: real) = (x ^ 2 - 1) / (x ^ 2 + 1)\" if \"x > 0\"\nproof -\n  from that have \"(x * 2 - inverse x * 2) * (x\\<^sup>2 + 1) =\n    (x\\<^sup>2 - 1) * (2 * x + 2 * inverse x)\"\n    by (simp add: field_simps power2_eq_square)\n  moreover have \"x\\<^sup>2 + 1 > 0\"\n    using that by (simp add: ac_simps add_pos_nonneg)\n  moreover have \"2 * x + 2 * inverse x > 0\"\n    using that by (simp add: add_pos_pos)\n  ultimately have \"(x * 2 - inverse x * 2) /\n    (2 * x + 2 * inverse x) =\n    (x\\<^sup>2 - 1) / (x\\<^sup>2 + 1)\"\n    by (simp add: frac_eq_eq)\n  with that show ?thesis\n    by (simp add: tanh_def sinh_ln_real cosh_ln_real)\nqed\n\nlemma has_field_derivative_scaleR_right [derivative_intros]:\n  \"(f has_field_derivative D) F \\<Longrightarrow> ((\\<lambda>x. c *\\<^sub>R f x) has_field_derivative (c *\\<^sub>R D)) F\"\n  unfolding has_field_derivative_def\n  using has_derivative_scaleR_right[of f \"\\<lambda>x. D * x\" F c]\n  by (simp add: mult_scaleR_left [symmetric] del: mult_scaleR_left)\n\nlemma has_field_derivative_sinh [THEN DERIV_chain2, derivative_intros]:\n  \"(sinh has_field_derivative cosh x) (at (x :: 'a :: {banach, real_normed_field}))\"\n  unfolding sinh_def cosh_def by (auto intro!: derivative_eq_intros)\n\nlemma has_field_derivative_cosh [THEN DERIV_chain2, derivative_intros]:\n  \"(cosh has_field_derivative sinh x) (at (x :: 'a :: {banach, real_normed_field}))\"\n  unfolding sinh_def cosh_def by (auto intro!: derivative_eq_intros)\n\nlemma has_field_derivative_tanh [THEN DERIV_chain2, derivative_intros]:\n  \"cosh x \\<noteq> 0 \\<Longrightarrow> (tanh has_field_derivative 1 - tanh x ^ 2)\n                     (at (x :: 'a :: {banach, real_normed_field}))\"\n  unfolding tanh_def by (auto intro!: derivative_eq_intros simp: power2_eq_square field_split_simps)\n\nlemma has_derivative_sinh [derivative_intros]:\n  fixes g :: \"'a \\<Rightarrow> ('a :: {banach, real_normed_field})\"\n  assumes \"(g has_derivative (\\<lambda>x. Db * x)) (at x within s)\"\n  shows   \"((\\<lambda>x. sinh (g x)) has_derivative (\\<lambda>y. (cosh (g x) * Db) * y)) (at x within s)\"\nproof -\n  have \"((\\<lambda>x. - g x) has_derivative (\\<lambda>y. -(Db * y))) (at x within s)\"\n    using assms by (intro derivative_intros)\n  also have \"(\\<lambda>y. -(Db * y)) = (\\<lambda>x. (-Db) * x)\" by (simp add: fun_eq_iff)\n  finally have \"((\\<lambda>x. sinh (g x)) has_derivative\n    (\\<lambda>y. (exp (g x) * Db * y - exp (-g x) * (-Db) * y) /\\<^sub>R 2)) (at x within s)\"\n    unfolding sinh_def by (intro derivative_intros assms)\n  also have \"(\\<lambda>y. (exp (g x) * Db * y - exp (-g x) * (-Db) * y) /\\<^sub>R 2) = (\\<lambda>y. (cosh (g x) * Db) * y)\"\n    by (simp add: fun_eq_iff cosh_def algebra_simps)\n  finally show ?thesis .\nqed\n\nlemma has_derivative_cosh [derivative_intros]:\n  fixes g :: \"'a \\<Rightarrow> ('a :: {banach, real_normed_field})\"\n  assumes \"(g has_derivative (\\<lambda>y. Db * y)) (at x within s)\"\n  shows   \"((\\<lambda>x. cosh (g x)) has_derivative (\\<lambda>y. (sinh (g x) * Db) * y)) (at x within s)\"\nproof -\n  have \"((\\<lambda>x. - g x) has_derivative (\\<lambda>y. -(Db * y))) (at x within s)\"\n    using assms by (intro derivative_intros)\n  also have \"(\\<lambda>y. -(Db * y)) = (\\<lambda>y. (-Db) * y)\" by (simp add: fun_eq_iff)\n  finally have \"((\\<lambda>x. cosh (g x)) has_derivative\n    (\\<lambda>y. (exp (g x) * Db * y + exp (-g x) * (-Db) * y) /\\<^sub>R 2)) (at x within s)\"\n    unfolding cosh_def by (intro derivative_intros assms)\n  also have \"(\\<lambda>y. (exp (g x) * Db * y + exp (-g x) * (-Db) * y) /\\<^sub>R 2) = (\\<lambda>y. (sinh (g x) * Db) * y)\"\n    by (simp add: fun_eq_iff sinh_def algebra_simps)\n  finally show ?thesis .\nqed\n\nlemma sinh_plus_cosh: \"sinh x + cosh x = exp x\"\nproof -\n  have \"sinh x + cosh x = (1/2) *\\<^sub>R (exp x + exp x)\"\n    by (simp add: sinh_def cosh_def algebra_simps)\n  also have \"\\<dots> = exp x\" by (rule scaleR_half_double)\n  finally show ?thesis .\nqed\n\nlemma cosh_plus_sinh: \"cosh x + sinh x = exp x\"\n  by (subst add.commute) (rule sinh_plus_cosh)\n\nlemma cosh_minus_sinh: \"cosh x - sinh x = exp (-x)\"\nproof -\n  have \"cosh x - sinh x = (1/2) *\\<^sub>R (exp (-x) + exp (-x))\"\n    by (simp add: sinh_def cosh_def algebra_simps)\n  also have \"\\<dots> = exp (-x)\" by (rule scaleR_half_double)\n  finally show ?thesis .\nqed\n\nlemma sinh_minus_cosh: \"sinh x - cosh x = -exp (-x)\"\n  using cosh_minus_sinh[of x] by (simp add: algebra_simps)\n\n\ncontext\n  fixes x :: \"'a :: {real_normed_field, banach}\"\nbegin\n\nlemma sinh_zero_iff: \"sinh x = 0 \\<longleftrightarrow> exp x \\<in> {1, -1}\"\n  by (auto simp: sinh_def field_simps exp_minus power2_eq_square square_eq_1_iff)\n\nlemma cosh_zero_iff: \"cosh x = 0 \\<longleftrightarrow> exp x ^ 2 = -1\"\n  by (auto simp: cosh_def exp_minus field_simps power2_eq_square eq_neg_iff_add_eq_0)\n\nlemma cosh_square_eq: \"cosh x ^ 2 = sinh x ^ 2 + 1\"\n  by (simp add: cosh_def sinh_def algebra_simps power2_eq_square exp_add [symmetric]\n                scaleR_conv_of_real)\n\nlemma sinh_square_eq: \"sinh x ^ 2 = cosh x ^ 2 - 1\"\n  by (simp add: cosh_square_eq)\n\nlemma hyperbolic_pythagoras: \"cosh x ^ 2 - sinh x ^ 2 = 1\"\n  by (simp add: cosh_square_eq)\n\nlemma sinh_add: \"sinh (x + y) = sinh x * cosh y + cosh x * sinh y\"\n  by (simp add: sinh_def cosh_def algebra_simps scaleR_conv_of_real exp_add [symmetric])\n\nlemma sinh_diff: \"sinh (x - y) = sinh x * cosh y - cosh x * sinh y\"\n  by (simp add: sinh_def cosh_def algebra_simps scaleR_conv_of_real exp_add [symmetric])\n\nlemma cosh_add: \"cosh (x + y) = cosh x * cosh y + sinh x * sinh y\"\n  by (simp add: sinh_def cosh_def algebra_simps scaleR_conv_of_real exp_add [symmetric])\n\nlemma cosh_diff: \"cosh (x - y) = cosh x * cosh y - sinh x * sinh y\"\n  by (simp add: sinh_def cosh_def algebra_simps scaleR_conv_of_real exp_add [symmetric])\n\nlemma tanh_add:\n  \"tanh (x + y) = (tanh x + tanh y) / (1 + tanh x * tanh y)\"\n  if \"cosh x \\<noteq> 0\" \"cosh y \\<noteq> 0\"\nproof -\n  have \"(sinh x * cosh y + cosh x * sinh y) * (1 + sinh x * sinh y / (cosh x * cosh y)) =\n    (cosh x * cosh y + sinh x * sinh y) * ((sinh x * cosh y + sinh y * cosh x) / (cosh y * cosh x))\"\n    using that by (simp add: field_split_simps)\n  also have \"(sinh x * cosh y + sinh y * cosh x) / (cosh y * cosh x) = sinh x / cosh x + sinh y / cosh y\"\n    using that by (simp add: field_split_simps)\n  finally have \"(sinh x * cosh y + cosh x * sinh y) * (1 + sinh x * sinh y / (cosh x * cosh y)) =\n    (sinh x / cosh x + sinh y / cosh y) * (cosh x * cosh y + sinh x * sinh y)\"\n    by simp\n  then show ?thesis\n    using that by (auto simp add: tanh_def sinh_add cosh_add eq_divide_eq)\n     (simp_all add: field_split_simps)\nqed\n\nlemma sinh_double: \"sinh (2 * x) = 2 * sinh x * cosh x\"\n  using sinh_add[of x] by simp\n\nlemma cosh_double: \"cosh (2 * x) = cosh x ^ 2 + sinh x ^ 2\"\n  using cosh_add[of x] by (simp add: power2_eq_square)\n\nend\n\nlemma sinh_field_def: \"sinh z = (exp z - exp (-z)) / (2 :: 'a :: {banach, real_normed_field})\"\n  by (simp add: sinh_def scaleR_conv_of_real)\n\nlemma cosh_field_def: \"cosh z = (exp z + exp (-z)) / (2 :: 'a :: {banach, real_normed_field})\"\n  by (simp add: cosh_def scaleR_conv_of_real)\n\n\nsubsubsection \\<open>More specific properties of the real functions\\<close>\n\nlemma plus_inverse_ge_2:\n  fixes x :: real\n  assumes \"x > 0\"\n  shows   \"x + inverse x \\<ge> 2\"\nproof -\n  have \"0 \\<le> (x - 1) ^ 2\" by simp\n  also have \"\\<dots> = x^2 - 2*x + 1\" by (simp add: power2_eq_square algebra_simps)\n  finally show ?thesis using assms by (simp add: field_simps power2_eq_square)\nqed\n\nlemma sinh_real_nonneg_iff [simp]: \"sinh (x :: real) \\<ge> 0 \\<longleftrightarrow> x \\<ge> 0\"\n  by (simp add: sinh_def)\n\nlemma sinh_real_pos_iff [simp]: \"sinh (x :: real) > 0 \\<longleftrightarrow> x > 0\"\n  by (simp add: sinh_def)\n\nlemma sinh_real_nonpos_iff [simp]: \"sinh (x :: real) \\<le> 0 \\<longleftrightarrow> x \\<le> 0\"\n  by (simp add: sinh_def)\n\nlemma sinh_real_neg_iff [simp]: \"sinh (x :: real) < 0 \\<longleftrightarrow> x < 0\"\n  by (simp add: sinh_def)\n\nlemma cosh_real_ge_1: \"cosh (x :: real) \\<ge> 1\"\n  using plus_inverse_ge_2[of \"exp x\"] by (simp add: cosh_def exp_minus)\n\nlemma cosh_real_pos [simp]: \"cosh (x :: real) > 0\"\n  using cosh_real_ge_1[of x] by simp\n\nlemma cosh_real_nonneg[simp]: \"cosh (x :: real) \\<ge> 0\"\n  using cosh_real_ge_1[of x] by simp\n\nlemma cosh_real_nonzero [simp]: \"cosh (x :: real) \\<noteq> 0\"\n  using cosh_real_ge_1[of x] by simp\n\nlemma arsinh_real_def: \"arsinh (x::real) = ln (x + sqrt (x^2 + 1))\"\n  by (simp add: arsinh_def powr_half_sqrt)\n\nlemma arcosh_real_def: \"x \\<ge> 1 \\<Longrightarrow> arcosh (x::real) = ln (x + sqrt (x^2 - 1))\"\n  by (simp add: arcosh_def powr_half_sqrt)\n\nlemma arsinh_real_aux: \"0 < x + sqrt (x ^ 2 + 1 :: real)\"\nproof (cases \"x < 0\")\n  case True\n  have \"(-x) ^ 2 = x ^ 2\" by simp\n  also have \"x ^ 2 < x ^ 2 + 1\" by simp\n  finally have \"sqrt ((-x) ^ 2) < sqrt (x ^ 2 + 1)\"\n    by (rule real_sqrt_less_mono)\n  thus ?thesis using True by simp\nqed (auto simp: add_nonneg_pos)\n\nlemma arsinh_minus_real [simp]: \"arsinh (-x::real) = -arsinh x\"\nproof -\n  have \"arsinh (-x) = ln (sqrt (x\\<^sup>2 + 1) - x)\"\n    by (simp add: arsinh_real_def)\n  also have \"sqrt (x^2 + 1) - x = inverse (sqrt (x^2 + 1) + x)\"\n    using arsinh_real_aux[of x] by (simp add: field_split_simps algebra_simps power2_eq_square)\n  also have \"ln \\<dots> = -arsinh x\"\n    using arsinh_real_aux[of x] by (simp add: arsinh_real_def ln_inverse)\n  finally show ?thesis .\nqed\n\nlemma artanh_minus_real [simp]:\n  assumes \"abs x < 1\"\n  shows   \"artanh (-x::real) = -artanh x\"\n  using assms by (simp add: artanh_def ln_div field_simps)\n\nlemma sinh_less_cosh_real: \"sinh (x :: real) < cosh x\"\n  by (simp add: sinh_def cosh_def)\n\nlemma sinh_le_cosh_real: \"sinh (x :: real) \\<le> cosh x\"\n  by (simp add: sinh_def cosh_def)\n\nlemma tanh_real_lt_1: \"tanh (x :: real) < 1\"\n  by (simp add: tanh_def sinh_less_cosh_real)\n\nlemma tanh_real_gt_neg1: \"tanh (x :: real) > -1\"\nproof -\n  have \"- cosh x < sinh x\" by (simp add: sinh_def cosh_def field_split_simps)\n  thus ?thesis by (simp add: tanh_def field_simps)\nqed\n\nlemma tanh_real_bounds: \"tanh (x :: real) \\<in> {-1<..<1}\"\n  using tanh_real_lt_1 tanh_real_gt_neg1 by simp\n\ncontext\n  fixes x :: real\nbegin\n\nlemma arsinh_sinh_real: \"arsinh (sinh x) = x\"\n  by (simp add: arsinh_real_def powr_def sinh_square_eq sinh_plus_cosh)\n\nlemma arcosh_cosh_real: \"x \\<ge> 0 \\<Longrightarrow> arcosh (cosh x) = x\"\n  by (simp add: arcosh_real_def powr_def cosh_square_eq cosh_real_ge_1 cosh_plus_sinh)\n\nlemma artanh_tanh_real: \"artanh (tanh x) = x\"\nproof -\n  have \"artanh (tanh x) = ln (cosh x * (cosh x + sinh x) / (cosh x * (cosh x - sinh x))) / 2\"\n    by (simp add: artanh_def tanh_def field_split_simps)\n  also have \"cosh x * (cosh x + sinh x) / (cosh x * (cosh x - sinh x)) =\n               (cosh x + sinh x) / (cosh x - sinh x)\" by simp\n  also have \"\\<dots> = (exp x)^2\"\n    by (simp add: cosh_plus_sinh cosh_minus_sinh exp_minus field_simps power2_eq_square)\n  also have \"ln ((exp x)^2) / 2 = x\" by (simp add: ln_realpow)\n  finally show ?thesis .\nqed\n\nlemma sinh_real_zero_iff [simp]: \"sinh x = 0 \\<longleftrightarrow> x = 0\"\n  by (metis arsinh_0 arsinh_sinh_real sinh_0)\n\nlemma cosh_real_one_iff [simp]: \"cosh x = 1 \\<longleftrightarrow> x = 0\"\n  by (smt (verit, best) Transcendental.arcosh_cosh_real cosh_0 cosh_minus)\n\nlemma tanh_real_nonneg_iff [simp]: \"tanh x \\<ge> 0 \\<longleftrightarrow> x \\<ge> 0\"\n  by (simp add: tanh_def field_simps)\n\nlemma tanh_real_pos_iff [simp]: \"tanh x > 0 \\<longleftrightarrow> x > 0\"\n  by (simp add: tanh_def field_simps)\n\nlemma tanh_real_nonpos_iff [simp]: \"tanh x \\<le> 0 \\<longleftrightarrow> x \\<le> 0\"\n  by (simp add: tanh_def field_simps)\n\nlemma tanh_real_neg_iff [simp]: \"tanh x < 0 \\<longleftrightarrow> x < 0\"\n  by (simp add: tanh_def field_simps)\n\nlemma tanh_real_zero_iff [simp]: \"tanh x = 0 \\<longleftrightarrow> x = 0\"\n  by (simp add: tanh_def field_simps)\n\nend\n  \nlemma sinh_real_strict_mono: \"strict_mono (sinh :: real \\<Rightarrow> real)\"\n  by (rule pos_deriv_imp_strict_mono derivative_intros)+ auto\n\nlemma cosh_real_strict_mono:\n  assumes \"0 \\<le> x\" and \"x < (y::real)\"\n  shows   \"cosh x < cosh y\"\nproof -\n  from assms have \"\\<exists>z>x. z < y \\<and> cosh y - cosh x = (y - x) * sinh z\"\n    by (intro MVT2) (auto dest: connectedD_interval intro!: derivative_eq_intros)\n  then obtain z where z: \"z > x\" \"z < y\" \"cosh y - cosh x = (y - x) * sinh z\" by blast\n  note \\<open>cosh y - cosh x = (y - x) * sinh z\\<close>\n  also from \\<open>z > x\\<close> and assms have \"(y - x) * sinh z > 0\" by (intro mult_pos_pos) auto\n  finally show \"cosh x < cosh y\" by simp\nqed\n\nlemma tanh_real_strict_mono: \"strict_mono (tanh :: real \\<Rightarrow> real)\"\nproof -\n  have *: \"tanh x ^ 2 < 1\" for x :: real\n    using tanh_real_bounds[of x] by (simp add: abs_square_less_1 abs_if)\n  show ?thesis\n    by (rule pos_deriv_imp_strict_mono) (insert *, auto intro!: derivative_intros)\nqed\n\nlemma sinh_real_abs [simp]: \"sinh (abs x :: real) = abs (sinh x)\"\n  by (simp add: abs_if)\n\nlemma cosh_real_abs [simp]: \"cosh (abs x :: real) = cosh x\"\n  by (simp add: abs_if)\n\nlemma tanh_real_abs [simp]: \"tanh (abs x :: real) = abs (tanh x)\"\n  by (auto simp: abs_if)\n\nlemma sinh_real_eq_iff [simp]: \"sinh x = sinh y \\<longleftrightarrow> x = (y :: real)\"\n  using sinh_real_strict_mono by (simp add: strict_mono_eq)\n\nlemma tanh_real_eq_iff [simp]: \"tanh x = tanh y \\<longleftrightarrow> x = (y :: real)\"\n  using tanh_real_strict_mono by (simp add: strict_mono_eq)\n\nlemma cosh_real_eq_iff [simp]: \"cosh x = cosh y \\<longleftrightarrow> abs x = abs (y :: real)\"\nproof -\n  have \"cosh x = cosh y \\<longleftrightarrow> x = y\" if \"x \\<ge> 0\" \"y \\<ge> 0\" for x y :: real\n    using cosh_real_strict_mono[of x y] cosh_real_strict_mono[of y x] that\n    by (cases x y rule: linorder_cases) auto\n  from this[of \"abs x\" \"abs y\"] show ?thesis by simp\nqed\n\nlemma sinh_real_le_iff [simp]: \"sinh x \\<le> sinh y \\<longleftrightarrow> x \\<le> (y::real)\"\n  using sinh_real_strict_mono by (simp add: strict_mono_less_eq)\n\nlemma cosh_real_nonneg_le_iff: \"x \\<ge> 0 \\<Longrightarrow> y \\<ge> 0 \\<Longrightarrow> cosh x \\<le> cosh y \\<longleftrightarrow> x \\<le> (y::real)\"\n  using cosh_real_strict_mono[of x y] cosh_real_strict_mono[of y x]\n  by (cases x y rule: linorder_cases) auto\n\nlemma cosh_real_nonpos_le_iff: \"x \\<le> 0 \\<Longrightarrow> y \\<le> 0 \\<Longrightarrow> cosh x \\<le> cosh y \\<longleftrightarrow> x \\<ge> (y::real)\"\n  using cosh_real_nonneg_le_iff[of \"-x\" \"-y\"] by simp\n\nlemma tanh_real_le_iff [simp]: \"tanh x \\<le> tanh y \\<longleftrightarrow> x \\<le> (y::real)\"\n  using tanh_real_strict_mono by (simp add: strict_mono_less_eq)\n\n\nlemma sinh_real_less_iff [simp]: \"sinh x < sinh y \\<longleftrightarrow> x < (y::real)\"\n  using sinh_real_strict_mono by (simp add: strict_mono_less)\n\nlemma cosh_real_nonneg_less_iff: \"x \\<ge> 0 \\<Longrightarrow> y \\<ge> 0 \\<Longrightarrow> cosh x < cosh y \\<longleftrightarrow> x < (y::real)\"\n  using cosh_real_strict_mono[of x y] cosh_real_strict_mono[of y x]\n  by (cases x y rule: linorder_cases) auto\n\nlemma cosh_real_nonpos_less_iff: \"x \\<le> 0 \\<Longrightarrow> y \\<le> 0 \\<Longrightarrow> cosh x < cosh y \\<longleftrightarrow> x > (y::real)\"\n  using cosh_real_nonneg_less_iff[of \"-x\" \"-y\"] by simp\n\nlemma tanh_real_less_iff [simp]: \"tanh x < tanh y \\<longleftrightarrow> x < (y::real)\"\n  using tanh_real_strict_mono by (simp add: strict_mono_less)\n\n\nsubsubsection \\<open>Limits\\<close>\n\nlemma sinh_real_at_top: \"filterlim (sinh :: real \\<Rightarrow> real) at_top at_top\"\nproof -\n  have *: \"((\\<lambda>x. - exp (- x)) \\<longlongrightarrow> (-0::real)) at_top\"\n    by (intro tendsto_minus filterlim_compose[OF exp_at_bot] filterlim_uminus_at_bot_at_top)\n  have \"filterlim (\\<lambda>x. (1/2) * (-exp (-x) + exp x) :: real) at_top at_top\"\n    by (rule filterlim_tendsto_pos_mult_at_top[OF _ _\n               filterlim_tendsto_add_at_top[OF *]] tendsto_const)+ (auto simp: exp_at_top)\n  also have \"(\\<lambda>x. (1/2) * (-exp (-x) + exp x) :: real) = sinh\"\n    by (simp add: fun_eq_iff sinh_def)\n  finally show ?thesis .\nqed\n\nlemma sinh_real_at_bot: \"filterlim (sinh :: real \\<Rightarrow> real) at_bot at_bot\"\nproof -\n  have \"filterlim (\\<lambda>x. -sinh x :: real) at_bot at_top\"\n    by (simp add: filterlim_uminus_at_top [symmetric] sinh_real_at_top)\n  also have \"(\\<lambda>x. -sinh x :: real) = (\\<lambda>x. sinh (-x))\" by simp\n  finally show ?thesis by (subst filterlim_at_bot_mirror)\nqed\n\nlemma cosh_real_at_top: \"filterlim (cosh :: real \\<Rightarrow> real) at_top at_top\"\nproof -\n  have *: \"((\\<lambda>x. exp (- x)) \\<longlongrightarrow> (0::real)) at_top\"\n    by (intro filterlim_compose[OF exp_at_bot] filterlim_uminus_at_bot_at_top)\n  have \"filterlim (\\<lambda>x. (1/2) * (exp (-x) + exp x) :: real) at_top at_top\"\n    by (rule filterlim_tendsto_pos_mult_at_top[OF _ _\n               filterlim_tendsto_add_at_top[OF *]] tendsto_const)+ (auto simp: exp_at_top)\n  also have \"(\\<lambda>x. (1/2) * (exp (-x) + exp x) :: real) = cosh\"\n    by (simp add: fun_eq_iff cosh_def)\n  finally show ?thesis .\nqed\n\nlemma cosh_real_at_bot: \"filterlim (cosh :: real \\<Rightarrow> real) at_top at_bot\"\nproof -\n  have \"filterlim (\\<lambda>x. cosh (-x) :: real) at_top at_top\"\n    by (simp add: cosh_real_at_top)\n  thus ?thesis by (subst filterlim_at_bot_mirror)\nqed\n\nlemma tanh_real_at_top: \"(tanh \\<longlongrightarrow> (1::real)) at_top\"\nproof -\n  have \"((\\<lambda>x::real. (1 - exp (- 2 * x)) / (1 + exp (- 2 * x))) \\<longlongrightarrow> (1 - 0) / (1 + 0)) at_top\"\n    by (intro tendsto_intros filterlim_compose[OF exp_at_bot]\n              filterlim_tendsto_neg_mult_at_bot[OF tendsto_const] filterlim_ident) auto\n  also have \"(\\<lambda>x::real. (1 - exp (- 2 * x)) / (1 + exp (- 2 * x))) = tanh\"\n    by (rule ext) (simp add: tanh_real_altdef)\n  finally show ?thesis by simp\nqed\n\nlemma tanh_real_at_bot: \"(tanh \\<longlongrightarrow> (-1::real)) at_bot\"\nproof -\n  have \"((\\<lambda>x::real. -tanh x) \\<longlongrightarrow> -1) at_top\"\n    by (intro tendsto_minus tanh_real_at_top)\n  also have \"(\\<lambda>x. -tanh x :: real) = (\\<lambda>x. tanh (-x))\" by simp\n  finally show ?thesis by (subst filterlim_at_bot_mirror)\nqed\n\n\nsubsubsection \\<open>Properties of the inverse hyperbolic functions\\<close>\n\nlemma isCont_sinh: \"isCont sinh (x :: 'a :: {real_normed_field, banach})\"\n  unfolding sinh_def [abs_def] by (auto intro!: continuous_intros)\n\nlemma isCont_cosh: \"isCont cosh (x :: 'a :: {real_normed_field, banach})\"\n  unfolding cosh_def [abs_def] by (auto intro!: continuous_intros)\n\nlemma isCont_tanh: \"cosh x \\<noteq> 0 \\<Longrightarrow> isCont tanh (x :: 'a :: {real_normed_field, banach})\"\n  unfolding tanh_def [abs_def]\n  by (auto intro!: continuous_intros isCont_divide isCont_sinh isCont_cosh)\n\nlemma continuous_on_sinh [continuous_intros]:\n  fixes f :: \"_ \\<Rightarrow>'a::{real_normed_field,banach}\"\n  assumes \"continuous_on A f\"\n  shows   \"continuous_on A (\\<lambda>x. sinh (f x))\"\n  unfolding sinh_def using assms by (intro continuous_intros)\n\nlemma continuous_on_cosh [continuous_intros]:\n  fixes f :: \"_ \\<Rightarrow>'a::{real_normed_field,banach}\"\n  assumes \"continuous_on A f\"\n  shows   \"continuous_on A (\\<lambda>x. cosh (f x))\"\n  unfolding cosh_def using assms by (intro continuous_intros)\n\nlemma continuous_sinh [continuous_intros]:\n  fixes f :: \"_ \\<Rightarrow>'a::{real_normed_field,banach}\"\n  assumes \"continuous F f\"\n  shows   \"continuous F (\\<lambda>x. sinh (f x))\"\n  unfolding sinh_def using assms by (intro continuous_intros)\n\nlemma continuous_cosh [continuous_intros]:\n  fixes f :: \"_ \\<Rightarrow>'a::{real_normed_field,banach}\"\n  assumes \"continuous F f\"\n  shows   \"continuous F (\\<lambda>x. cosh (f x))\"\n  unfolding cosh_def using assms by (intro continuous_intros)\n\nlemma continuous_on_tanh [continuous_intros]:\n  fixes f :: \"_ \\<Rightarrow>'a::{real_normed_field,banach}\"\n  assumes \"continuous_on A f\" \"\\<And>x. x \\<in> A \\<Longrightarrow> cosh (f x) \\<noteq> 0\"\n  shows   \"continuous_on A (\\<lambda>x. tanh (f x))\"\n  unfolding tanh_def using assms by (intro continuous_intros) auto\n\nlemma continuous_at_within_tanh [continuous_intros]:\n  fixes f :: \"_ \\<Rightarrow>'a::{real_normed_field,banach}\"\n  assumes \"continuous (at x within A) f\" \"cosh (f x) \\<noteq> 0\"\n  shows   \"continuous (at x within A) (\\<lambda>x. tanh (f x))\"\n  unfolding tanh_def using assms by (intro continuous_intros continuous_divide) auto\n\nlemma continuous_tanh [continuous_intros]:\n  fixes f :: \"_ \\<Rightarrow>'a::{real_normed_field,banach}\"\n  assumes \"continuous F f\" \"cosh (f (Lim F (\\<lambda>x. x))) \\<noteq> 0\"\n  shows   \"continuous F (\\<lambda>x. tanh (f x))\"\n  unfolding tanh_def using assms by (intro continuous_intros continuous_divide) auto\n\nlemma tendsto_sinh [tendsto_intros]:\n  fixes f :: \"_ \\<Rightarrow>'a::{real_normed_field,banach}\"\n  shows \"(f \\<longlongrightarrow> a) F \\<Longrightarrow> ((\\<lambda>x. sinh (f x)) \\<longlongrightarrow> sinh a) F\"\n  by (rule isCont_tendsto_compose [OF isCont_sinh])\n\nlemma tendsto_cosh [tendsto_intros]:\n  fixes f :: \"_ \\<Rightarrow>'a::{real_normed_field,banach}\"\n  shows \"(f \\<longlongrightarrow> a) F \\<Longrightarrow> ((\\<lambda>x. cosh (f x)) \\<longlongrightarrow> cosh a) F\"\n  by (rule isCont_tendsto_compose [OF isCont_cosh])\n\nlemma tendsto_tanh [tendsto_intros]:\n  fixes f :: \"_ \\<Rightarrow>'a::{real_normed_field,banach}\"\n  shows \"(f \\<longlongrightarrow> a) F \\<Longrightarrow> cosh a \\<noteq> 0 \\<Longrightarrow> ((\\<lambda>x. tanh (f x)) \\<longlongrightarrow> tanh a) F\"\n  by (rule isCont_tendsto_compose [OF isCont_tanh])\n\n\nlemma arsinh_real_has_field_derivative [derivative_intros]:\n  fixes x :: real\n  shows \"(arsinh has_field_derivative (1 / (sqrt (x ^ 2 + 1)))) (at x within A)\"\nproof -\n  have pos: \"1 + x ^ 2 > 0\" by (intro add_pos_nonneg) auto\n  from pos arsinh_real_aux[of x] show ?thesis unfolding arsinh_def [abs_def]\n    by (auto intro!: derivative_eq_intros simp: powr_minus powr_half_sqrt field_split_simps)\nqed\n\nlemma arcosh_real_has_field_derivative [derivative_intros]:\n  fixes x :: real\n  assumes \"x > 1\"\n  shows   \"(arcosh has_field_derivative (1 / (sqrt (x ^ 2 - 1)))) (at x within A)\"\nproof -\n  from assms have \"x + sqrt (x\\<^sup>2 - 1) > 0\" by (simp add: add_pos_pos)\n  thus ?thesis using assms unfolding arcosh_def [abs_def]\n    by (auto intro!: derivative_eq_intros\n             simp: powr_minus powr_half_sqrt field_split_simps power2_eq_1_iff)\nqed\n\nlemma artanh_real_has_field_derivative [derivative_intros]:\n  \"(artanh has_field_derivative (1 / (1 - x ^ 2))) (at x within A)\" if\n    \"\\<bar>x\\<bar> < 1\" for x :: real\nproof -\n  from that have \"- 1 < x\" \"x < 1\" by linarith+\n  hence \"(artanh has_field_derivative (4 - 4 * x) / ((1 + x) * (1 - x) * (1 - x) * 4))\n           (at x within A)\" unfolding artanh_def [abs_def]\n    by (auto intro!: derivative_eq_intros simp: powr_minus powr_half_sqrt)\n  also have \"(4 - 4 * x) / ((1 + x) * (1 - x) * (1 - x) * 4) = 1 / ((1 + x) * (1 - x))\"\n    using \\<open>-1 < x\\<close> \\<open>x < 1\\<close> by (simp add: frac_eq_eq)\n  also have \"(1 + x) * (1 - x) = 1 - x ^ 2\"\n    by (simp add: algebra_simps power2_eq_square)\n  finally show ?thesis .\nqed\n\nlemma continuous_on_arsinh [continuous_intros]: \"continuous_on A (arsinh :: real \\<Rightarrow> real)\"\n  by (rule DERIV_continuous_on derivative_intros)+\n\nlemma continuous_on_arcosh [continuous_intros]:\n  assumes \"A \\<subseteq> {1..}\"\n  shows   \"continuous_on A (arcosh :: real \\<Rightarrow> real)\"\nproof -\n  have pos: \"x + sqrt (x ^ 2 - 1) > 0\" if \"x \\<ge> 1\" for x\n    using that by (intro add_pos_nonneg) auto\n  show ?thesis\n  unfolding arcosh_def [abs_def]\n  by (intro continuous_on_subset [OF _ assms] continuous_on_ln continuous_on_add\n               continuous_on_id continuous_on_powr')\n     (auto dest: pos simp: powr_half_sqrt intro!: continuous_intros)\nqed\n\nlemma continuous_on_artanh [continuous_intros]:\n  assumes \"A \\<subseteq> {-1<..<1}\"\n  shows   \"continuous_on A (artanh :: real \\<Rightarrow> real)\"\n  unfolding artanh_def [abs_def]\n  by (intro continuous_on_subset [OF _ assms]) (auto intro!: continuous_intros)\n\nlemma continuous_on_arsinh' [continuous_intros]:\n  fixes f :: \"real \\<Rightarrow> real\"\n  assumes \"continuous_on A f\"\n  shows   \"continuous_on A (\\<lambda>x. arsinh (f x))\"\n  by (rule continuous_on_compose2[OF continuous_on_arsinh assms]) auto\n\nlemma continuous_on_arcosh' [continuous_intros]:\n  fixes f :: \"real \\<Rightarrow> real\"\n  assumes \"continuous_on A f\" \"\\<And>x. x \\<in> A \\<Longrightarrow> f x \\<ge> 1\"\n  shows   \"continuous_on A (\\<lambda>x. arcosh (f x))\"\n  by (rule continuous_on_compose2[OF continuous_on_arcosh assms(1) order.refl])\n     (use assms(2) in auto)\n\nlemma continuous_on_artanh' [continuous_intros]:\n  fixes f :: \"real \\<Rightarrow> real\"\n  assumes \"continuous_on A f\" \"\\<And>x. x \\<in> A \\<Longrightarrow> f x \\<in> {-1<..<1}\"\n  shows   \"continuous_on A (\\<lambda>x. artanh (f x))\"\n  by (rule continuous_on_compose2[OF continuous_on_artanh assms(1) order.refl])\n     (use assms(2) in auto)\n\nlemma isCont_arsinh [continuous_intros]: \"isCont arsinh (x :: real)\"\n  using continuous_on_arsinh[of UNIV] by (auto simp: continuous_on_eq_continuous_at)\n\nlemma isCont_arcosh [continuous_intros]:\n  assumes \"x > 1\"\n  shows   \"isCont arcosh (x :: real)\"\nproof -\n  have \"continuous_on {1::real<..} arcosh\"\n    by (rule continuous_on_arcosh) auto\n  with assms show ?thesis by (auto simp: continuous_on_eq_continuous_at)\nqed\n\nlemma isCont_artanh [continuous_intros]:\n  assumes \"x > -1\" \"x < 1\"\n  shows   \"isCont artanh (x :: real)\"\nproof -\n  have \"continuous_on {-1<..<(1::real)} artanh\"\n    by (rule continuous_on_artanh) auto\n  with assms show ?thesis by (auto simp: continuous_on_eq_continuous_at)\nqed\n\nlemma tendsto_arsinh [tendsto_intros]: \"(f \\<longlongrightarrow> a) F \\<Longrightarrow> ((\\<lambda>x. arsinh (f x)) \\<longlongrightarrow> arsinh a) F\"\n  for f :: \"_ \\<Rightarrow> real\"\n  by (rule isCont_tendsto_compose [OF isCont_arsinh])\n\nlemma tendsto_arcosh_strong [tendsto_intros]:\n  fixes f :: \"_ \\<Rightarrow> real\"\n  assumes \"(f \\<longlongrightarrow> a) F\" \"a \\<ge> 1\" \"eventually (\\<lambda>x. f x \\<ge> 1) F\"\n  shows   \"((\\<lambda>x. arcosh (f x)) \\<longlongrightarrow> arcosh a) F\"\n  by (rule continuous_on_tendsto_compose[OF continuous_on_arcosh[OF order.refl]])\n     (use assms in auto)\n\nlemma tendsto_arcosh:\n  fixes f :: \"_ \\<Rightarrow> real\"\n  assumes \"(f \\<longlongrightarrow> a) F\" \"a > 1\"\n  shows \"((\\<lambda>x. arcosh (f x)) \\<longlongrightarrow> arcosh a) F\"\n  by (rule isCont_tendsto_compose [OF isCont_arcosh]) (use assms in auto)\n\nlemma tendsto_arcosh_at_left_1: \"(arcosh \\<longlongrightarrow> 0) (at_right (1::real))\"\nproof -\n  have \"(arcosh \\<longlongrightarrow> arcosh 1) (at_right (1::real))\"\n    by (rule tendsto_arcosh_strong) (auto simp: eventually_at intro!: exI[of _ 1])\n  thus ?thesis by simp\nqed\n\nlemma tendsto_artanh [tendsto_intros]:\n  fixes f :: \"'a \\<Rightarrow> real\"\n  assumes \"(f \\<longlongrightarrow> a) F\" \"a > -1\" \"a < 1\"\n  shows   \"((\\<lambda>x. artanh (f x)) \\<longlongrightarrow> artanh a) F\"\n  by (rule isCont_tendsto_compose [OF isCont_artanh]) (use assms in auto)\n\nlemma continuous_arsinh [continuous_intros]:\n  \"continuous F f \\<Longrightarrow> continuous F (\\<lambda>x. arsinh (f x :: real))\"\n  unfolding continuous_def by (rule tendsto_arsinh)\n\n(* TODO: This rule does not work for one-sided continuity at 1 *)\nlemma continuous_arcosh_strong [continuous_intros]:\n  assumes \"continuous F f\" \"eventually (\\<lambda>x. f x \\<ge> 1) F\"\n  shows   \"continuous F (\\<lambda>x. arcosh (f x :: real))\"\nproof (cases \"F = bot\")\n  case False\n  show ?thesis\n    unfolding continuous_def\n  proof (intro tendsto_arcosh_strong)\n    show \"1 \\<le> f (Lim F (\\<lambda>x. x))\"\n      using assms False unfolding continuous_def by (rule tendsto_lowerbound)\n  qed (insert assms, auto simp: continuous_def)\nqed auto\n\nlemma continuous_arcosh:\n  \"continuous F f \\<Longrightarrow> f (Lim F (\\<lambda>x. x)) > 1 \\<Longrightarrow> continuous F (\\<lambda>x. arcosh (f x :: real))\"\n  unfolding continuous_def by (rule tendsto_arcosh) auto\n\nlemma continuous_artanh [continuous_intros]:\n  \"continuous F f \\<Longrightarrow> f (Lim F (\\<lambda>x. x)) \\<in> {-1<..<1} \\<Longrightarrow> continuous F (\\<lambda>x. artanh (f x :: real))\"\n  unfolding continuous_def by (rule tendsto_artanh) auto\n\nlemma arsinh_real_at_top:\n  \"filterlim (arsinh :: real \\<Rightarrow> real) at_top at_top\"\nproof (subst filterlim_cong[OF refl refl])\n  show \"filterlim (\\<lambda>x. ln (x + sqrt (1 + x\\<^sup>2))) at_top at_top\"\n    by (intro filterlim_compose[OF ln_at_top filterlim_at_top_add_at_top] filterlim_ident\n              filterlim_compose[OF sqrt_at_top] filterlim_tendsto_add_at_top[OF tendsto_const]\n              filterlim_pow_at_top) auto\nqed (auto intro!: eventually_mono[OF eventually_ge_at_top[of 1]] simp: arsinh_real_def add_ac)\n\nlemma arsinh_real_at_bot:\n  \"filterlim (arsinh :: real \\<Rightarrow> real) at_bot at_bot\"\nproof -\n  have \"filterlim (\\<lambda>x::real. -arsinh x) at_bot at_top\"\n    by (subst filterlim_uminus_at_top [symmetric]) (rule arsinh_real_at_top)\n  also have \"(\\<lambda>x::real. -arsinh x) = (\\<lambda>x. arsinh (-x))\" by simp\n  finally show ?thesis\n    by (subst filterlim_at_bot_mirror)\nqed\n\nlemma arcosh_real_at_top:\n  \"filterlim (arcosh :: real \\<Rightarrow> real) at_top at_top\"\nproof (subst filterlim_cong[OF refl refl])\n  show \"filterlim (\\<lambda>x. ln (x + sqrt (-1 + x\\<^sup>2))) at_top at_top\"\n    by (intro filterlim_compose[OF ln_at_top filterlim_at_top_add_at_top] filterlim_ident\n              filterlim_compose[OF sqrt_at_top] filterlim_tendsto_add_at_top[OF tendsto_const]\n              filterlim_pow_at_top) auto\nqed (auto intro!: eventually_mono[OF eventually_ge_at_top[of 1]] simp: arcosh_real_def)\n\nlemma artanh_real_at_left_1:\n  \"filterlim (artanh :: real \\<Rightarrow> real) at_top (at_left 1)\"\nproof -\n  have *: \"filterlim (\\<lambda>x::real. (1 + x) / (1 - x)) at_top (at_left 1)\"\n    by (rule LIM_at_top_divide)\n       (auto intro!: tendsto_eq_intros eventually_mono[OF eventually_at_left_real[of 0]])\n  have \"filterlim (\\<lambda>x::real. (1/2) * ln ((1 + x) / (1 - x))) at_top (at_left 1)\"\n    by (intro filterlim_tendsto_pos_mult_at_top[OF tendsto_const] *\n                 filterlim_compose[OF ln_at_top]) auto\n  also have \"(\\<lambda>x::real. (1/2) * ln ((1 + x) / (1 - x))) = artanh\"\n    by (simp add: artanh_def [abs_def])\n  finally show ?thesis .\nqed\n\nlemma artanh_real_at_right_1:\n  \"filterlim (artanh :: real \\<Rightarrow> real) at_bot (at_right (-1))\"\nproof -\n  have \"?thesis \\<longleftrightarrow> filterlim (\\<lambda>x::real. -artanh x) at_top (at_right (-1))\"\n    by (simp add: filterlim_uminus_at_bot)\n  also have \"\\<dots> \\<longleftrightarrow> filterlim (\\<lambda>x::real. artanh (-x)) at_top (at_right (-1))\"\n    by (intro filterlim_cong refl eventually_mono[OF eventually_at_right_real[of \"-1\" \"1\"]]) auto\n  also have \"\\<dots> \\<longleftrightarrow> filterlim (artanh :: real \\<Rightarrow> real) at_top (at_left 1)\"\n    by (simp add: filterlim_at_left_to_right)\n  also have \\<dots> by (rule artanh_real_at_left_1)\n  finally show ?thesis .\nqed\n\n\nsubsection \\<open>Simprocs for root and power literals\\<close>\n\nlemma numeral_powr_numeral_real [simp]:\n  \"numeral m powr numeral n = (numeral m ^ numeral n :: real)\"\n  by (simp add: powr_numeral)\n\ncontext\nbegin\n\nprivate lemma sqrt_numeral_simproc_aux:\n  assumes \"m * m \\<equiv> n\"\n  shows   \"sqrt (numeral n :: real) \\<equiv> numeral m\"\nproof -\n  have \"numeral n \\<equiv> numeral m * (numeral m :: real)\" by (simp add: assms [symmetric])\n  moreover have \"sqrt \\<dots> \\<equiv> numeral m\" by (subst real_sqrt_abs2) simp\n  ultimately show \"sqrt (numeral n :: real) \\<equiv> numeral m\" by simp\nqed\n\nprivate lemma root_numeral_simproc_aux:\n  assumes \"Num.pow m n \\<equiv> x\"\n  shows   \"root (numeral n) (numeral x :: real) \\<equiv> numeral m\"\n  by (subst assms [symmetric], subst numeral_pow, subst real_root_pos2) simp_all\n\nprivate lemma powr_numeral_simproc_aux:\n  assumes \"Num.pow y n = x\"\n  shows   \"numeral x powr (m / numeral n :: real) \\<equiv> numeral y powr m\"\n  by (subst assms [symmetric], subst numeral_pow, subst powr_numeral [symmetric])\n     (simp, subst powr_powr, simp_all)\n\nprivate lemma numeral_powr_inverse_eq:\n  \"numeral x powr (inverse (numeral n)) = numeral x powr (1 / numeral n :: real)\"\n  by simp\n\n\nML \\<open>\n\nsignature ROOT_NUMERAL_SIMPROC = sig\n\nval sqrt : int option -> int -> int option\nval sqrt' : int option -> int -> int option\nval nth_root : int option -> int -> int -> int option\nval nth_root' : int option -> int -> int -> int option\nval sqrt_simproc : Proof.context -> cterm -> thm option\nval root_simproc : int * int -> Proof.context -> cterm -> thm option\nval powr_simproc : int * int -> Proof.context -> cterm -> thm option\n\nend\n\nstructure Root_Numeral_Simproc : ROOT_NUMERAL_SIMPROC = struct\n\nfun iterate NONE p f x =\n      let\n        fun go x = if p x then x else go (f x)\n      in\n        SOME (go x)\n      end\n  | iterate (SOME threshold) p f x =\n      let\n        fun go (threshold, x) = \n          if p x then SOME x else if threshold = 0 then NONE else go (threshold - 1, f x)\n      in\n        go (threshold, x)\n      end  \n\n\nfun nth_root _ 1 x = SOME x\n  | nth_root _ _ 0 = SOME 0\n  | nth_root _ _ 1 = SOME 1\n  | nth_root threshold n x =\n  let\n    fun newton_step y = ((n - 1) * y + x div Integer.pow (n - 1) y) div n\n    fun is_root y = Integer.pow n y <= x andalso x < Integer.pow n (y + 1)\n  in\n    if x < n then\n      SOME 1\n    else if x < Integer.pow n 2 then \n      SOME 1 \n    else \n      let\n        val y = Real.floor (Math.pow (Real.fromInt x, Real.fromInt 1 / Real.fromInt n))\n      in\n        if is_root y then\n          SOME y\n        else\n          iterate threshold is_root newton_step ((x + n - 1) div n)\n      end\n  end\n\nfun nth_root' _ 1 x = SOME x\n  | nth_root' _ _ 0 = SOME 0\n  | nth_root' _ _ 1 = SOME 1\n  | nth_root' threshold n x = if x < n then NONE else if x < Integer.pow n 2 then NONE else\n      case nth_root threshold n x of\n        NONE => NONE\n      | SOME y => if Integer.pow n y = x then SOME y else NONE\n\nfun sqrt _ 0 = SOME 0\n  | sqrt _ 1 = SOME 1\n  | sqrt threshold n =\n    let\n      fun aux (a, b) = if n >= b * b then aux (b, b * b) else (a, b)\n      val (lower_root, lower_n) = aux (1, 2)\n      fun newton_step x = (x + n div x) div 2\n      fun is_sqrt r = r*r <= n andalso n < (r+1)*(r+1)\n      val y = Real.floor (Math.sqrt (Real.fromInt n))\n    in\n      if is_sqrt y then \n        SOME y\n      else\n        Option.mapPartial (iterate threshold is_sqrt newton_step o (fn x => x * lower_root)) \n          (sqrt threshold (n div lower_n))\n    end\n\nfun sqrt' threshold x =\n  case sqrt threshold x of\n    NONE => NONE\n  | SOME y => if y * y = x then SOME y else NONE\n\nfun sqrt_simproc ctxt ct =\n  let\n    val n = ct |> Thm.term_of |> dest_comb |> snd |> dest_comb |> snd |> HOLogic.dest_numeral\n  in\n    case sqrt' (SOME 10000) n of\n      NONE => NONE\n    | SOME m => \n        SOME (Thm.instantiate' [] (map (SOME o Thm.cterm_of ctxt o HOLogic.mk_numeral) [m, n])\n                  @{thm sqrt_numeral_simproc_aux})\n  end\n    handle TERM _ => NONE\n\nfun root_simproc (threshold1, threshold2) ctxt ct =\n  let\n    val [n, x] = \n      ct |> Thm.term_of |> strip_comb |> snd |> map (dest_comb #> snd #> HOLogic.dest_numeral)\n  in\n    if n > threshold1 orelse x > threshold2 then NONE else\n      case nth_root' (SOME 100) n x of\n        NONE => NONE\n      | SOME m => \n          SOME (Thm.instantiate' [] (map (SOME o Thm.cterm_of ctxt o HOLogic.mk_numeral) [m, n, x])\n            @{thm root_numeral_simproc_aux})\n  end\n    handle TERM _ => NONE\n         | Match => NONE\n\nfun powr_simproc (threshold1, threshold2) ctxt ct =\n  let\n    val eq_thm = Conv.try_conv (Conv.rewr_conv @{thm numeral_powr_inverse_eq}) ct\n    val ct = Thm.dest_equals_rhs (Thm.cprop_of eq_thm)\n    val (_, [x, t]) = strip_comb (Thm.term_of ct)\n    val (_, [m, n]) = strip_comb t\n    val [x, n] = map (dest_comb #> snd #> HOLogic.dest_numeral) [x, n]\n  in\n    if n > threshold1 orelse x > threshold2 then NONE else\n      case nth_root' (SOME 100) n x of\n        NONE => NONE\n      | SOME y => \n          let\n            val [y, n, x] = map HOLogic.mk_numeral [y, n, x]\n            val thm = Thm.instantiate' [] (map (SOME o Thm.cterm_of ctxt) [y, n, x, m])\n              @{thm powr_numeral_simproc_aux}\n          in\n            SOME (@{thm transitive} OF [eq_thm, thm])\n          end\n  end\n    handle TERM _ => NONE\n         | Match => NONE\n\nend\n\\<close>\n\nend\n\nsimproc_setup sqrt_numeral (\"sqrt (numeral n)\") = \n  \\<open>K Root_Numeral_Simproc.sqrt_simproc\\<close>\n  \nsimproc_setup root_numeral (\"root (numeral n) (numeral x)\") = \n  \\<open>K (Root_Numeral_Simproc.root_simproc (200, Integer.pow 200 2))\\<close>\n\nsimproc_setup powr_divide_numeral \n  (\"numeral x powr (m / numeral n :: real)\" | \"numeral x powr (inverse (numeral n) :: real)\") = \n    \\<open>K (Root_Numeral_Simproc.powr_simproc (200, Integer.pow 200 2))\\<close>\n\n\nlemma \"root 100 1267650600228229401496703205376 = 2\"\n  by simp\n    \nlemma \"sqrt 196 = 14\" \n  by simp\n\nlemma \"256 powr (7 / 4 :: real) = 16384\"\n  by simp\n    \nlemma \"27 powr (inverse 3) = (3::real)\"\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/Transcendental.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.89181104831338, "lm_q2_score": 0.8311430499496096, "lm_q1q2_score": 0.7412225546739413}}
{"text": "(*  Title:   TwiceFieldDifferentiable.thy\n    Authors: Jacques Fleuriot and Filip Smola, University of Edinburgh, 2020\n*)\n\nsection \\<open>Twice Field Differentiable\\<close>\n\ntheory TwiceFieldDifferentiable\n  imports \"HOL-Analysis.Analysis\"\nbegin\n\nsubsection\\<open>Differentiability on a Set\\<close>\n\ntext\\<open>A function is differentiable on a set iff it is differentiable at any point within that set.\\<close>\ndefinition field_differentiable_on :: \"('a \\<Rightarrow> 'a::real_normed_field) \\<Rightarrow> 'a set \\<Rightarrow> bool\"\n  (infix \"field'_differentiable'_on\" 50)\n  where \"f field_differentiable_on s \\<equiv> \\<forall>x\\<in>s. f field_differentiable (at x within s)\"\n\ntext\\<open>This is preserved for subsets.\\<close>\nlemma field_differentiable_on_subset:\n  assumes \"f field_differentiable_on S\"\n      and \"T \\<subseteq> S\"\n    shows \"f field_differentiable_on T\"\n  by (meson assms field_differentiable_on_def field_differentiable_within_subset in_mono)\n\nsubsection\\<open>Twice Differentiability\\<close>\ntext\\<open>\n  Informally, a function is twice differentiable at x iff it is differentiable on some neighbourhood\n  of x and its derivative is differentiable at x.\n\\<close>\ndefinition twice_field_differentiable_at :: \"['a \\<Rightarrow> 'a::real_normed_field, 'a ] \\<Rightarrow> bool\"\n  (infixr \"(twice'_field'_differentiable'_at)\" 50)\n  where \"f twice_field_differentiable_at x \\<equiv>\n           \\<exists>S. f field_differentiable_on S \\<and> x \\<in> interior S \\<and> (deriv f) field_differentiable (at x)\"\n\nlemma once_field_differentiable_at:\n  \"f twice_field_differentiable_at x \\<Longrightarrow> f field_differentiable (at x)\"\n  by (metis at_within_interior field_differentiable_on_def interior_subset subsetD twice_field_differentiable_at_def)\n\nlemma deriv_field_differentiable_at:\n  \"f twice_field_differentiable_at x \\<Longrightarrow> deriv f field_differentiable (at x)\"\n  using twice_field_differentiable_at_def by blast\n\ntext\\<open>\n  For a composition of two functions twice differentiable at x, the chain rule eventually holds on\n  some neighbourhood of x.\n\\<close>\nlemma eventually_deriv_compose:\n  assumes \"\\<exists>S. f field_differentiable_on S \\<and> x \\<in> interior S\"\n      and \"g twice_field_differentiable_at (f x)\"\n    shows \"\\<forall>\\<^sub>F x in nhds x. deriv (\\<lambda>x. g (f x)) x = deriv g (f x) * deriv f x\"\nproof -\n  obtain S S'\n   where Df_on_S:  \"f field_differentiable_on S\" and x_int_S: \"x \\<in> interior S\"\n     and Dg_on_S': \"g field_differentiable_on S'\" and fx_int_S': \"f x \\<in> interior S'\"\n    using assms twice_field_differentiable_at_def by blast\n\n  let ?T = \"{x \\<in> interior S. f x \\<in> interior S'}\"\n\n  have \"continuous_on (interior S) f\"\n    by (meson Df_on_S continuous_on_eq_continuous_within continuous_on_subset field_differentiable_imp_continuous_at\n         field_differentiable_on_def interior_subset)\n  then have \"open (interior S \\<inter> {x. f x \\<in> interior S'})\"\n    by (metis continuous_open_preimage open_interior vimage_def)\n  then have x_int_T: \"x \\<in> interior ?T\"\n    by (metis (no_types) Collect_conj_eq Collect_mem_eq Int_Collect fx_int_S' interior_eq x_int_S)\n  moreover have  Dg_on_fT: \"g field_differentiable_on f`?T\"\n   by (metis (no_types, lifting) Dg_on_S' field_differentiable_on_subset image_Collect_subsetI interior_subset)\n  moreover have Df_on_T: \"f field_differentiable_on ?T\"\n    using  field_differentiable_on_subset Df_on_S\n    by (metis Collect_subset interior_subset)\n  moreover have \"\\<forall>x \\<in> interior ?T. deriv (\\<lambda>x. g (f x)) x = deriv g (f x) * deriv f x\"\n  proof\n    fix x\n    assume x_int_T: \"x \\<in> interior ?T\"\n    have \"f field_differentiable at x\"\n      by (metis (no_types, lifting) Df_on_T at_within_interior field_differentiable_on_def\n          interior_subset subsetD x_int_T)\n    moreover have \"g field_differentiable at (f x)\"\n      by (metis (no_types, lifting) Dg_on_S' at_within_interior field_differentiable_on_def\n          interior_subset mem_Collect_eq subsetD x_int_T)\n    ultimately have \"deriv (g \\<circ> f) x = deriv g (f x) * deriv f x\"\n      using deriv_chain[of f x g] by simp\n    then show \"deriv (\\<lambda>x. g (f x)) x = deriv g (f x) * deriv f x\"\n      by (simp add: comp_def)\n  qed\n  ultimately show ?thesis\n    using eventually_nhds by blast\nqed\n\nlemma eventually_deriv_compose':\n  assumes \"f twice_field_differentiable_at x\"\n      and \"g twice_field_differentiable_at (f x)\"\n    shows \"\\<forall>\\<^sub>F x in nhds x. deriv (\\<lambda>x. g (f x)) x = deriv g (f x) * deriv f x\"\n  using assms eventually_deriv_compose twice_field_differentiable_at_def by blast\n\ntext\\<open>Composition of twice differentiable functions is twice differentiable.\\<close>\nlemma twice_field_differentiable_at_compose:\n  assumes \"f twice_field_differentiable_at x\"\n      and \"g twice_field_differentiable_at (f x)\"\n    shows \"(\\<lambda>x. g (f x)) twice_field_differentiable_at x\"\nproof -\n  obtain S S'\n   where Df_on_S:  \"f field_differentiable_on S\" and x_int_S: \"x \\<in> interior S\"\n     and Dg_on_S': \"g field_differentiable_on S'\" and fx_int_S': \"f x \\<in> interior S'\"\n    using assms twice_field_differentiable_at_def by blast\n\n  let ?T = \"{x \\<in> interior S. f x \\<in> interior S'}\"\n\n  have \"continuous_on (interior S) f\"\n    by (meson Df_on_S continuous_on_eq_continuous_within continuous_on_subset field_differentiable_imp_continuous_at\n         field_differentiable_on_def interior_subset)\n  then have \"open (interior S \\<inter> {x. f x \\<in> interior S'})\"\n    by (metis continuous_open_preimage open_interior vimage_def)\n  then have x_int_T: \"x \\<in> interior ?T\"\n    by (metis (no_types) Collect_conj_eq Collect_mem_eq Int_Collect fx_int_S' interior_eq x_int_S)\n\n  have  Dg_on_fT: \"g field_differentiable_on f`?T\"\n    by (metis (no_types, lifting) Dg_on_S' field_differentiable_on_subset image_Collect_subsetI interior_subset)\n\n  have Df_on_T: \"f field_differentiable_on ?T\"\n    using  field_differentiable_on_subset Df_on_S\n    by (metis Collect_subset interior_subset)\n\n  have \"(\\<lambda>x. g (f x)) field_differentiable_on ?T\"\n    unfolding field_differentiable_on_def\n  proof\n    fix x assume x_int: \"x \\<in> {x \\<in> interior S. f x \\<in> interior S'}\"\n    have \"f field_differentiable at x\"\n      by (metis Df_on_S at_within_interior field_differentiable_on_def interior_subset mem_Collect_eq subsetD x_int)\n    moreover have \"g field_differentiable at (f x)\"\n      by (metis Dg_on_S' at_within_interior field_differentiable_on_def interior_subset mem_Collect_eq subsetD x_int)\n    ultimately have \"(g \\<circ> f) field_differentiable at x\"\n      by (simp add: field_differentiable_compose)\n    then have \"(\\<lambda>x. g (f x)) field_differentiable at x\"\n      by (simp add: comp_def)\n    then show \"(\\<lambda>x. g (f x)) field_differentiable at x within {x \\<in> interior S. f x \\<in> interior S'}\"\n      using field_differentiable_at_within by blast\n  qed\n  moreover have \"deriv (\\<lambda>x. g (f x)) field_differentiable at x\"\n  proof -\n    have \"(\\<lambda>x. deriv g (f x)) field_differentiable at x\"\n      by (metis DERIV_chain2 assms deriv_field_differentiable_at field_differentiable_def once_field_differentiable_at)\n    then have \"(\\<lambda>x. deriv g (f x) * deriv f x) field_differentiable at x\"\n      using assms field_differentiable_mult[of \"\\<lambda>x. deriv g (f x)\"]\n      by (simp add: deriv_field_differentiable_at)\n    moreover have \"deriv (deriv (\\<lambda>x. g (f x))) x = deriv (\\<lambda>x. deriv g (f x) * deriv f x) x\"\n      using assms Df_on_S x_int_S deriv_cong_ev eventually_deriv_compose by fastforce\n    ultimately show ?thesis\n      using assms eventually_deriv_compose DERIV_deriv_iff_field_differentiable Df_on_S x_int_S\n            DERIV_cong_ev[of x x \"deriv (\\<lambda>x. g (f x))\" \"\\<lambda>x. deriv g (f x) * deriv f x\"]\n      by blast\n  qed\n  ultimately show ?thesis\n    using twice_field_differentiable_at_def x_int_T by blast\nqed\n\nsubsubsection\\<open>Constant\\<close>\nlemma twice_field_differentiable_at_const [simp, intro]:\n  \"(\\<lambda>x. a) twice_field_differentiable_at x\"\n  by (auto intro: exI [of _ UNIV] simp add: twice_field_differentiable_at_def field_differentiable_on_def)\n\nsubsubsection\\<open>Identity\\<close>\nlemma twice_field_differentiable_at_ident [simp, intro]:\n  \"(\\<lambda>x. x) twice_field_differentiable_at x\"\nproof -\n  have \"\\<forall>x\\<in>UNIV. (\\<lambda>x. x) field_differentiable at x\"\n   and \"deriv ((\\<lambda>x. x)) field_differentiable at x\"\n    by simp_all\n  then show ?thesis\n    unfolding twice_field_differentiable_at_def field_differentiable_on_def\n    by fastforce\nqed\n\nsubsubsection\\<open>Constant Multiplication\\<close>\nlemma twice_field_differentiable_at_cmult [simp, intro]:\n\"(*) k twice_field_differentiable_at x\"\nproof -\n  have \"\\<forall>x\\<in>UNIV. (*) k field_differentiable at x\"\n    by simp\n  moreover have \"deriv ((*) k) field_differentiable at x\"\n    by simp\n  ultimately show ?thesis\n    unfolding twice_field_differentiable_at_def field_differentiable_on_def\n    by fastforce\nqed\n\nlemma twice_field_differentiable_at_uminus [simp, intro]:\n  \"uminus twice_field_differentiable_at x\"\nproof -\n  have \"\\<forall>x\\<in>UNIV. uminus field_differentiable at x\"\n    by (simp add: field_differentiable_minus)\n  moreover have \"deriv uminus field_differentiable at x\"\n    by simp\n  ultimately show ?thesis\n    unfolding twice_field_differentiable_at_def field_differentiable_on_def\n    by auto\nqed\n\nlemma twice_field_differentiable_at_uminus_fun [intro]:\n  assumes \"f twice_field_differentiable_at x\"\n    shows \"(\\<lambda>x. - f x) twice_field_differentiable_at x\"\n  by (simp add: assms twice_field_differentiable_at_compose)\n\nsubsubsection\\<open>Real Scaling\\<close>\n\nlemma deriv_scaleR_right_id [simp]:\n  \"(deriv ((*\\<^sub>R) k)) = (\\<lambda>z. k *\\<^sub>R 1)\"\n  using DERIV_imp_deriv has_field_derivative_scaleR_right DERIV_ident by blast\n\nlemma deriv_deriv_scaleR_right_id [simp]:\n  \"deriv (deriv ((*\\<^sub>R) k)) = (\\<lambda>z. 0)\"\n  by simp\n\nlemma deriv_scaleR_right:\n  \"f field_differentiable (at z) \\<Longrightarrow> deriv (\\<lambda>x. k *\\<^sub>R f x) z = k *\\<^sub>R deriv f z\"\n  by (simp add: DERIV_imp_deriv field_differentiable_derivI has_field_derivative_scaleR_right)\n\nlemma field_differentiable_scaleR_right [intro]:\n  \"f field_differentiable F \\<Longrightarrow> (\\<lambda>x. c *\\<^sub>R f x) field_differentiable F\"\n  using field_differentiable_def has_field_derivative_scaleR_right by blast\n\nlemma has_field_derivative_scaleR_deriv_right:\n  assumes \"f twice_field_differentiable_at z\"\n  shows \"((\\<lambda>x. k *\\<^sub>R deriv f x) has_field_derivative k *\\<^sub>R deriv (deriv f) z) (at z)\"\n  by (simp add: DERIV_deriv_iff_field_differentiable assms deriv_field_differentiable_at has_field_derivative_scaleR_right)\n\nlemma deriv_scaleR_deriv_right:\n  assumes \"f twice_field_differentiable_at z\"\n  shows \"deriv (\\<lambda>x. k *\\<^sub>R deriv f x) z = k *\\<^sub>R deriv (deriv f) z\"\n  using assms deriv_scaleR_right twice_field_differentiable_at_def by blast\n\nlemma twice_field_differentiable_at_scaleR [simp, intro]:\n  \"(*\\<^sub>R) k twice_field_differentiable_at x\"\nproof -\n  have \"\\<forall>x\\<in>UNIV. (*\\<^sub>R) k field_differentiable at x\"\n    by (simp add: field_differentiable_scaleR_right)\n  moreover have \"deriv ((*\\<^sub>R) k) field_differentiable at x\"\n    by simp\n  ultimately show ?thesis\n    unfolding twice_field_differentiable_at_def field_differentiable_on_def\n    by auto\nqed\n\nlemma twice_field_differentiable_at_scaleR_fun [simp, intro]:\n  assumes \"f twice_field_differentiable_at x\"\n  shows \"(\\<lambda>x. k *\\<^sub>R f x) twice_field_differentiable_at x\"\n  by (simp add: assms twice_field_differentiable_at_compose)\n\nsubsubsection\\<open>Addition\\<close>\n\nlemma eventually_deriv_add:\n  assumes \"f twice_field_differentiable_at x\"\n      and \"g twice_field_differentiable_at x\"\n    shows \"\\<forall>\\<^sub>F x in nhds x. deriv (\\<lambda>x. f x + g x) x = deriv f x + deriv g x\"\nproof -\n  obtain S where Df_on_S: \"f field_differentiable_on S\" and x_int_S: \"x \\<in> interior S\"\n    using assms twice_field_differentiable_at_def by blast\n  obtain S' where Dg_on_S: \"g field_differentiable_on S'\" and x_int_S': \"x \\<in> interior S'\"\n    using assms twice_field_differentiable_at_def by blast\n  have \"x \\<in> interior (S \\<inter> S')\"\n     by (simp add: x_int_S x_int_S')\n  moreover have Df_on_SS': \"f field_differentiable_on (S \\<inter> S')\"\n     by (meson Df_on_S IntD1 field_differentiable_on_def field_differentiable_within_subset inf_sup_ord(1))\n  moreover have Dg_on_SS': \"g field_differentiable_on (S \\<inter> S')\"\n     by (meson Dg_on_S IntD2 field_differentiable_on_def field_differentiable_within_subset inf_le2)\n  moreover have \"open (interior (S \\<inter> S'))\"\n    by blast\n  moreover have \"\\<forall>x\\<in> interior (S \\<inter> S'). deriv (\\<lambda>x. f x + g x) x = deriv f x + deriv g x\"\n    by (metis (full_types) Df_on_SS' Dg_on_SS' at_within_interior deriv_add field_differentiable_on_def in_mono interior_subset)\n  ultimately show ?thesis\n    using eventually_nhds by blast\nqed\n\nlemma twice_field_differentiable_at_add [intro]:\n  assumes \"f twice_field_differentiable_at x\"\n      and \"g twice_field_differentiable_at x\"\n    shows \"(\\<lambda>x. f x + g x) twice_field_differentiable_at x\"\nproof -\n  obtain S S'\n   where Df_on_S:  \"f field_differentiable_on S\" and x_int_S: \"x \\<in> interior S\"\n     and Dg_on_S': \"g field_differentiable_on S'\" and x_int_S': \" x \\<in> interior S'\"\n    using assms twice_field_differentiable_at_def by blast\n\n  let ?T = \"interior (S \\<inter> S')\"\n\n  have x_int_T: \"x \\<in> interior ?T\"\n     by (simp add: x_int_S x_int_S')\n\n  have Df_on_T: \"f field_differentiable_on ?T\"\n    by (meson Df_on_S field_differentiable_on_subset inf_sup_ord(1) interior_subset)\n  have  Dg_on_fT: \"g field_differentiable_on ?T\"\n    by (meson Dg_on_S' field_differentiable_on_subset interior_subset le_infE)\n\n   have \"(\\<lambda>x. f x + g x) field_differentiable_on ?T\"\n     unfolding field_differentiable_on_def\n  proof\n    fix x assume x_in_T: \"x \\<in> ?T\"\n    have \"f field_differentiable at x\"\n      by (metis x_in_T Df_on_T at_within_open field_differentiable_on_def open_interior)\n    moreover have \"g field_differentiable at x\"\n      by (metis x_in_T Dg_on_fT at_within_open field_differentiable_on_def open_interior)\n    ultimately have \"(\\<lambda>x. f x + g x) field_differentiable at x\"\n      by (simp add: field_differentiable_add)\n    then show \"(\\<lambda>x. f x + g x) field_differentiable at x within ?T\"\n      using field_differentiable_at_within by blast\n  qed\n  moreover have \"deriv (\\<lambda>x. f x + g x) field_differentiable at x\"\n  proof -\n    have \"deriv (\\<lambda>x. f x + g x) x = deriv f x + deriv g x\"\n      by (simp add: assms once_field_differentiable_at)\n    moreover have \"(\\<lambda>x. deriv f x + deriv g x) field_differentiable at x\"\n      by (simp add: field_differentiable_add assms deriv_field_differentiable_at)\n    ultimately show ?thesis\n      using assms DERIV_deriv_iff_field_differentiable\n            DERIV_cong_ev[of x x \"deriv (\\<lambda>x. f x + g x)\" \"\\<lambda>x. deriv f x + deriv g x\"]\n      by (simp add: eventually_deriv_add field_differentiable_def)\n  qed\n  ultimately show ?thesis\n    using twice_field_differentiable_at_def x_int_T by blast\nqed\n\nlemma deriv_add_id_const [simp]:\n  \"deriv (\\<lambda>x. x + a) = (\\<lambda>z. 1)\"\n  using ext trans[OF deriv_add] by force\n\nlemma deriv_deriv_add_id_const [simp]:\n  \"deriv (deriv (\\<lambda>x. x + a)) z = 0\"\n  by simp\n\nlemma twice_field_differentiable_at_cadd [simp]:\n  \"(\\<lambda>x. x + a) twice_field_differentiable_at x\"\nproof -\n  have \"\\<forall>x\\<in>UNIV. (\\<lambda>x. x + a) field_differentiable at x\"\n    by (simp add: field_differentiable_add)\n  moreover have \"deriv ((\\<lambda>x. x + a)) field_differentiable at x\"\n    by (simp add: ext)\n  ultimately show ?thesis\n    unfolding twice_field_differentiable_at_def field_differentiable_on_def\n    by auto\nqed\n\nsubsubsection\\<open>Linear Function\\<close>\nlemma twice_field_differentiable_at_linear [simp, intro]:\n  \"(\\<lambda>x. k * x + a) twice_field_differentiable_at x\"\nproof -\n  have \"\\<forall>x\\<in>UNIV. (\\<lambda>x. k * x + a) field_differentiable at x\"\n    by (simp add: field_differentiable_add)\n  moreover have \"deriv ((\\<lambda>x. k * x + a)) field_differentiable at x\"\n  proof -\n    have \"deriv ((\\<lambda>x. k * x + a)) = (\\<lambda>x. k)\"\n      by (simp add: ext)\n    then show ?thesis\n      by simp\n  qed\n  ultimately show ?thesis\n    unfolding twice_field_differentiable_at_def field_differentiable_on_def\n    by auto\nqed\n\nlemma twice_field_differentiable_at_linearR [simp, intro]:\n  \"(\\<lambda>x. k *\\<^sub>R x + a) twice_field_differentiable_at x\"\nproof -\n  have \"\\<forall>x\\<in>UNIV. (\\<lambda>x. k *\\<^sub>R x + a) field_differentiable at x\"\n    by (simp add: field_differentiable_scaleR_right field_differentiable_add)\n  moreover have \"deriv ((\\<lambda>x. k *\\<^sub>R x + a)) field_differentiable at x\"\n  proof -\n    have \"deriv ((\\<lambda>x. k *\\<^sub>R x + a)) = (\\<lambda>x. k *\\<^sub>R 1)\"\n      by (simp add: ext once_field_differentiable_at)\n    then show ?thesis\n      by simp\n  qed\n  ultimately show ?thesis\n    unfolding twice_field_differentiable_at_def field_differentiable_on_def\n    by auto\nqed\n\nsubsubsection\\<open>Multiplication\\<close>\n\nlemma eventually_deriv_mult:\n  assumes \"f twice_field_differentiable_at x\"\n      and \"g twice_field_differentiable_at x\"\n    shows \"\\<forall>\\<^sub>F x in nhds x. deriv (\\<lambda>x. f x * g x) x = f x * deriv g x + deriv f x * g x\"\nproof -\n  obtain S and S'\n    where \"f field_differentiable_on S\"   and in_S:  \"x \\<in> interior S\"\n      and \"g field_differentiable_on S'\"  and in_S': \"x \\<in> interior S'\"\n    using assms twice_field_differentiable_at_def by blast\n  then have Df_on_SS': \"f field_differentiable_on (S \\<inter> S')\"\n        and Dg_on_SS': \"g field_differentiable_on (S \\<inter> S')\"\n    using field_differentiable_on_subset by blast+\n\n  have \"\\<forall>x\\<in> interior (S \\<inter> S'). deriv (\\<lambda>x. f x * g x) x = f x * deriv g x + deriv f x * g x\"\n  proof\n    fix x assume \"x \\<in> interior (S \\<inter> S')\"\n    then have \"f field_differentiable (at x)\"\n          and \"g field_differentiable (at x)\"\n      using Df_on_SS' Dg_on_SS' field_differentiable_on_def at_within_interior interior_subset subsetD by metis+\n    then show \"deriv (\\<lambda>x. f x * g x) x = f x * deriv g x + deriv f x * g x\"\n      by simp\n  qed\n  moreover have \"x \\<in> interior (S \\<inter> S')\"\n    by (simp add: in_S in_S')\n  moreover have \"open (interior (S \\<inter> S'))\"\n    by blast\n  ultimately show ?thesis\n    using eventually_nhds by blast\nqed\n\nlemma twice_field_differentiable_at_mult [intro]:\n  assumes \"f twice_field_differentiable_at x\"\n      and \"g twice_field_differentiable_at x\"\n    shows \"(\\<lambda>x. f x * g x) twice_field_differentiable_at x\"\nproof -\n  obtain S S'\n   where Df_on_S:  \"f field_differentiable_on S\" and x_int_S: \"x \\<in> interior S\"\n     and Dg_on_S': \"g field_differentiable_on S'\" and x_int_S': \" x \\<in> interior S'\"\n    using assms twice_field_differentiable_at_def by blast\n\n  let ?T = \"interior (S \\<inter> S')\"\n\n  have x_int_T: \"x \\<in> interior ?T\"\n     by (simp add: x_int_S x_int_S')\n\n  have Df_on_T: \"f field_differentiable_on ?T\"\n    by (meson Df_on_S field_differentiable_on_subset inf_sup_ord(1) interior_subset)\n  have  Dg_on_fT: \"g field_differentiable_on ?T\"\n    by (meson Dg_on_S' field_differentiable_on_subset interior_subset le_infE)\n\n   have \"(\\<lambda>x. f x * g x) field_differentiable_on ?T\"\n     unfolding field_differentiable_on_def\n  proof\n    fix x assume x_in_T: \"x \\<in> ?T\"\n    have \"f field_differentiable at x\"\n      by (metis x_in_T Df_on_T at_within_open field_differentiable_on_def open_interior)\n    moreover have \"g field_differentiable at x\"\n      by (metis x_in_T Dg_on_fT at_within_open field_differentiable_on_def open_interior)\n    ultimately have \"(\\<lambda>x. f x * g x) field_differentiable at x\"\n      by (simp add: field_differentiable_mult)\n    then show \"(\\<lambda>x. f x * g x) field_differentiable at x within ?T\"\n      using field_differentiable_at_within by blast\n  qed\n  moreover have \"deriv (\\<lambda>x. f x * g x) field_differentiable at x\"\n  proof -\n    have \"deriv (\\<lambda>x. f x * g x) x = f x * deriv g x + deriv f x * g x\"\n      by (simp add: assms once_field_differentiable_at)\n    moreover have \"(\\<lambda>x. f x * deriv g x + deriv f x * g x) field_differentiable at x\"\n      by (rule field_differentiable_add, simp_all add: field_differentiable_mult assms once_field_differentiable_at deriv_field_differentiable_at)\n    ultimately show ?thesis\n      using assms DERIV_deriv_iff_field_differentiable\n            DERIV_cong_ev[of x x \"deriv (\\<lambda>x. f x * g x)\" \"\\<lambda>x. f x * deriv g x + deriv f x * g x\"]\n      by (simp add: eventually_deriv_mult field_differentiable_def)\n  qed\n  ultimately show ?thesis\n    using twice_field_differentiable_at_def x_int_T by blast\nqed\n\nsubsubsection\\<open>Sine and Cosine\\<close>\n\nlemma deriv_sin [simp]: \"deriv sin a = cos a\"\n  by (simp add: DERIV_imp_deriv)\n\nlemma deriv_sinf [simp]: \"deriv sin = (\\<lambda>x. cos x)\"\n  by auto\n\nlemma deriv_cos [simp]: \"deriv cos a = - sin a\"\n  by (simp add: DERIV_imp_deriv)\n\nlemma deriv_cosf [simp]: \"deriv cos = (\\<lambda>x. - sin x)\"\n  by auto\n\nlemma deriv_sin_minus [simp]:\n  \"deriv (\\<lambda>x. - sin x) a = - deriv (\\<lambda>x. sin x) a\"\n  by (simp add: DERIV_imp_deriv Deriv.field_differentiable_minus)\n\nlemma twice_field_differentiable_at_sin [simp, intro]:\n  \"sin twice_field_differentiable_at x\"\n  by (auto intro!: exI [of _ UNIV] simp add: field_differentiable_at_sin\n      field_differentiable_on_def twice_field_differentiable_at_def field_differentiable_at_cos)\n\nlemma twice_field_differentiable_at_sin_fun [intro]:\n  assumes \"f twice_field_differentiable_at x\"\n  shows   \"(\\<lambda>x. sin (f x)) twice_field_differentiable_at x\"\n  by (simp add: assms twice_field_differentiable_at_compose)\n\nlemma twice_field_differentiable_at_cos [simp, intro]:\n  \"cos twice_field_differentiable_at x\"\n  by (auto intro!: exI [of _ UNIV] simp add:  field_differentiable_within_sin field_differentiable_minus\n      field_differentiable_on_def twice_field_differentiable_at_def field_differentiable_at_cos)\n\nlemma twice_field_differentiable_at_cos_fun [intro]:\n  assumes \"f twice_field_differentiable_at x\"\n  shows   \"(\\<lambda>x. cos (f x)) twice_field_differentiable_at x\"\n  by (simp add: assms twice_field_differentiable_at_compose)\n\nsubsubsection\\<open>Exponential\\<close>\n\nlemma deriv_exp [simp]: \"deriv exp x = exp x\"\n  using DERIV_exp DERIV_imp_deriv by blast\n\nlemma deriv_expf [simp]: \"deriv exp = exp\"\n  by (simp add: ext)\n\nlemma deriv_deriv_exp [simp]: \"deriv (deriv exp) x = exp x\"\n  by simp\n\nlemma twice_field_differentiable_at_exp [simp, intro]:\n  \"exp twice_field_differentiable_at x\"\nproof -\n  have \"\\<forall>x\\<in>UNIV. exp field_differentiable at x\"\n   and \"deriv exp field_differentiable at x\"\n    by (simp_all add: field_differentiable_within_exp)\n  then show ?thesis\n    unfolding twice_field_differentiable_at_def field_differentiable_on_def\n    by auto\nqed\n\nlemma twice_field_differentiable_at_exp_fun [simp, intro]:\n  assumes \"f twice_field_differentiable_at x\"\n  shows \"(\\<lambda>x. exp (f x)) twice_field_differentiable_at x\"\n  by (simp add: assms twice_field_differentiable_at_compose)\n\nsubsubsection\\<open>Square Root\\<close>\n\nlemma deriv_real_sqrt [simp]: \"x > 0 \\<Longrightarrow> deriv sqrt x = inverse (sqrt x) / 2\"\n  using DERIV_imp_deriv DERIV_real_sqrt by blast\n\nlemma has_real_derivative_inverse_sqrt:\n  assumes \"x > 0\"\n  shows \"((\\<lambda>x. inverse (sqrt x) / 2) has_real_derivative - (inverse (sqrt x ^ 3) / 4)) (at x)\"\nproof -\n  have inv_sqrt_mult: \"(inverse (sqrt x)/2) * (sqrt x * 2) = 1\"\n    using assms by simp\n  have inv_sqrt_mult2: \"(- inverse ((sqrt x)^3)/2)* x * (sqrt x * 2) = -1\"\n    using assms by (simp add: field_simps power3_eq_cube)\n  then show ?thesis\n    using assms by (safe intro!: DERIV_imp_deriv derivative_eq_intros)\n        (auto intro: derivative_eq_intros inv_sqrt_mult [THEN ssubst] inv_sqrt_mult2 [THEN ssubst]\n              simp add: divide_simps power3_eq_cube)\nqed\n\nlemma deriv_deriv_real_sqrt':\n  assumes \"x > 0\"\n  shows \"deriv (\\<lambda>x. inverse (sqrt x) / 2) x = - inverse ((sqrt x)^3)/4\"\n  by (simp add: DERIV_imp_deriv assms has_real_derivative_inverse_sqrt)\n\nlemma has_real_derivative_deriv_sqrt:\n  assumes \"x > 0\"\n  shows \"(deriv sqrt has_real_derivative - inverse (sqrt x ^ 3) / 4) (at x)\"\nproof -\n  have \"((\\<lambda>x. inverse (sqrt x) / 2) has_real_derivative - inverse (sqrt x ^ 3) / 4) (at x)\"\n    using assms has_real_derivative_inverse_sqrt by auto\n  moreover\n  {fix xa :: real\n   assume \"xa \\<in> {0<..}\"\n   then have \"inverse (sqrt xa) / 2 = deriv sqrt xa\"\n     by simp\n  }\n  ultimately show ?thesis\n    using has_field_derivative_transform_within_open [where S=\"{0 <..}\" and f=\"(\\<lambda>x. inverse (sqrt x) / 2)\"]\n    by (meson assms greaterThan_iff open_greaterThan)\nqed\n\nlemma deriv_deriv_real_sqrt [simp]:\n  assumes \"x > 0\"\n  shows \"deriv(deriv sqrt) x = - inverse ((sqrt x)^3)/4\"\n  using DERIV_imp_deriv assms has_real_derivative_deriv_sqrt by blast\n\nlemma twice_field_differentiable_at_sqrt [simp, intro]:\n  assumes \"x > 0\"\n    shows \"sqrt twice_field_differentiable_at x\"\nproof -\n  have \"sqrt field_differentiable_on {0<..}\"\n    by (metis DERIV_real_sqrt at_within_open field_differentiable_def field_differentiable_on_def\n        greaterThan_iff open_greaterThan)\n  moreover have \"x \\<in> interior {0<..}\"\n    by (metis assms greaterThan_iff interior_interior interior_real_atLeast)\n  moreover have \"deriv sqrt field_differentiable at x\"\n    using assms field_differentiable_def has_real_derivative_deriv_sqrt by blast\n  ultimately show ?thesis\n    using twice_field_differentiable_at_def by blast\nqed\n\nlemma twice_field_differentiable_at_sqrt_fun [intro]:\n  assumes \"f twice_field_differentiable_at x\"\n    and \"f x > 0\"\n  shows \"(\\<lambda>x. sqrt (f x)) twice_field_differentiable_at x\"\n  by (simp add: assms(1) assms(2) twice_field_differentiable_at_compose)\n\nsubsubsection\\<open>Natural Power\\<close>\n\nlemma field_differentiable_power [simp]:\n  \"(\\<lambda>x. x ^ n) field_differentiable at x\"\n  using DERIV_power DERIV_ident field_differentiable_def\n  by blast\n\nlemma deriv_power_fun [simp]:\n  assumes \"f field_differentiable at x\"\n    shows \"deriv (\\<lambda>x. f x ^ n) x = of_nat n * deriv f x * f x ^ (n - 1)\"\n  using DERIV_power[of f \"deriv f x\"]\n  by (simp add:  DERIV_imp_deriv assms field_differentiable_derivI mult.assoc [symmetric])\n\nlemma deriv_power [simp]:\n  \"deriv (\\<lambda>x. x ^ n) x = of_nat n * x ^ (n - 1)\"\n  using DERIV_power[of \"\\<lambda>x. x\" 1] DERIV_imp_deriv by force\n\nlemma deriv_deriv_power [simp]:\n  \"deriv (deriv (\\<lambda>x. x ^ n)) x = of_nat n * of_nat (n - Suc 0) * x ^ (n - 2)\"\nproof -\n  have \"(\\<lambda>x. x ^ (n - 1)) field_differentiable at x\"\n    by simp\n  then have \"deriv (\\<lambda>x. of_nat n * x ^ (n - 1)) x = of_nat n * of_nat (n - Suc 0) * x ^ (n - 2)\"\n    by (simp add: diff_diff_add mult.assoc numeral_2_eq_2)\n  then show ?thesis\n    by (simp add: ext[OF deriv_power])\nqed\n\nlemma twice_field_differentiable_at_power [simp, intro]:\n  \"(\\<lambda>x. x ^ n) twice_field_differentiable_at x\"\nproof -\n  have \"\\<forall>x\\<in>UNIV. (\\<lambda>x. x ^ n) field_differentiable at x\"\n    by simp\n  moreover have \"deriv ((\\<lambda>x. x ^ n)) field_differentiable at x\"\n  proof -\n    have \"deriv ((\\<lambda>x. x ^ n)) = (\\<lambda>x. of_nat n * x ^ (n - 1))\"\n      by (simp add: ext)\n    then show ?thesis\n      using field_differentiable_mult[of \"\\<lambda>x. of_nat n\" x UNIV \"\\<lambda>x. x ^ (n - 1)\"]\n      by (simp add: field_differentiable_caratheodory_at)\n  qed\n  ultimately show ?thesis\n    unfolding twice_field_differentiable_at_def field_differentiable_on_def\n    by force\nqed\n\nlemma twice_field_differentiable_at_power_fun [intro]:\n  assumes \"f twice_field_differentiable_at x\"\n    shows \"(\\<lambda>x. f x ^ n) twice_field_differentiable_at x\"\n  by (blast intro: assms twice_field_differentiable_at_compose [OF _ twice_field_differentiable_at_power])\n\nsubsubsection\\<open>Inverse\\<close>\n\nlemma eventually_deriv_inverse:\n  assumes \"x \\<noteq> 0\"\n    shows \"\\<forall>\\<^sub>F x in nhds x. deriv inverse x = - 1 / (x ^ 2)\"\nproof -\n  obtain T where open_T: \"open T\" and \"\\<forall>z\\<in>T. z \\<noteq> 0\" and x_in_T: \"x \\<in> T\"\n    using assms t1_space by blast\n\n  then have \"\\<forall>x \\<in> T. deriv inverse x = - 1 / (x ^ 2)\"\n    by simp\n  then show ?thesis\n    using eventually_nhds open_T x_in_T by blast\nqed\n\nlemma deriv_deriv_inverse [simp]:\n  assumes \"x \\<noteq> 0\"\n  shows \"deriv (deriv inverse) x = 2 * inverse (x ^ 3)\"\nproof -\n  have \"deriv (\\<lambda>x. inverse (x ^ 2)) x = - (of_nat 2 * x) / ((x ^ 2) ^ 2)\"\n    using assms by simp\n  moreover have \"(\\<lambda>x. inverse (x ^ 2)) field_differentiable at x\"\n    using assms by (simp add: field_differentiable_inverse)\n  ultimately have \"deriv (\\<lambda>x. - (inverse (x ^ 2))) x = of_nat 2 * x / (x ^ 4)\"\n    using deriv_chain[of \"\\<lambda>x. inverse (x ^ 2)\" x]\n    by (simp add: comp_def field_differentiable_minus field_simps)\n  then have \"deriv (\\<lambda>x. - 1 / (x ^ 2)) x = 2 * inverse (x ^ 3)\"\n    by (simp add: power4_eq_xxxx power3_eq_cube field_simps)\n  then show ?thesis\n    using assms eventually_deriv_inverse deriv_cong_ev by fastforce\nqed\n\nlemma twice_field_differentiable_at_inverse [simp, intro]:\n  assumes \"x \\<noteq> 0\"\n  shows \"inverse twice_field_differentiable_at x\"\nproof -\n  obtain T where zero_T: \"0 \\<notin> T\" and x_in_T: \"x \\<in> T\" and open_T: \"open T\"\n    using assms t1_space by blast\n  then have \"T \\<subseteq> {z. z \\<noteq> 0}\"\n    by blast\n  then have \"\\<forall>x\\<in>T. inverse field_differentiable at x within T\"\n    using DERIV_inverse field_differentiable_def by blast\n  moreover have \"deriv inverse field_differentiable at x\"\n  proof -\n    have \"(\\<lambda>x. - inverse (x ^ 2)) field_differentiable at x\"\n      using assms by (simp add: field_differentiable_inverse field_differentiable_minus)\n    then have \"(\\<lambda>x. - 1 / (x ^ 2)) field_differentiable at x\"\n      by (simp add: inverse_eq_divide)\n    then show ?thesis\n      using eventually_deriv_inverse[OF assms]\n      by (simp add: DERIV_cong_ev field_differentiable_def)\n  qed\n  moreover have \"x \\<in> interior T\"\n    by (simp add: x_in_T open_T interior_open)\n  ultimately show ?thesis\n    unfolding twice_field_differentiable_at_def field_differentiable_on_def\n    by blast\nqed\n\nlemma twice_field_differentiable_at_inverse_fun [simp, intro]:\n  assumes \"f twice_field_differentiable_at x\"\n          \"f x \\<noteq> 0\"\n  shows \"(\\<lambda>x. inverse (f x)) twice_field_differentiable_at x\"\n  by (simp add: assms twice_field_differentiable_at_compose)\n\nlemma twice_field_differentiable_at_divide [intro]:\n  assumes \"f twice_field_differentiable_at x\"\n      and \"g twice_field_differentiable_at x\"\n      and \"g x \\<noteq> 0\"\n    shows \"(\\<lambda>x. f x / g x) twice_field_differentiable_at x\"\n  by (simp add: assms divide_inverse twice_field_differentiable_at_mult)\n\nsubsubsection\\<open>Polynomial\\<close>\n\nlemma twice_field_differentiable_at_polyn [simp, intro]:\n  fixes coef :: \"nat \\<Rightarrow> 'a :: {real_normed_field}\"\n    and n :: nat\n  shows \"(\\<lambda>x. \\<Sum>i<n. coef i * x ^ i) twice_field_differentiable_at x\"\nproof (induction n)\n  case 0\n  then show ?case\n    by simp\nnext\n  case hyp: (Suc n)\n  show ?case\n  proof (simp, rule twice_field_differentiable_at_add)\n    show \"(\\<lambda>x. \\<Sum>i<n. coef i * x ^ i) twice_field_differentiable_at x\"\n      by (rule hyp)\n    show \"(\\<lambda>x. coef n * x ^ n) twice_field_differentiable_at x\"\n      using twice_field_differentiable_at_compose[of \"\\<lambda>x. x ^ n\" x \"(*) (coef n)\"]\n      by simp\n  qed\nqed\n\nlemma twice_field_differentiable_at_polyn_fun [simp]:\n  fixes coef :: \"nat \\<Rightarrow> 'a :: {real_normed_field}\"\n    and n :: nat\n  assumes \"f twice_field_differentiable_at x\"\n  shows \"(\\<lambda>x. \\<Sum>i<n. coef i * f x ^ i) twice_field_differentiable_at x\"\n  by (blast intro: assms twice_field_differentiable_at_compose [OF _ twice_field_differentiable_at_polyn])\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/Hyperdual/TwiceFieldDifferentiable.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8918110511888303, "lm_q2_score": 0.8311430415844384, "lm_q1q2_score": 0.7412225496036997}}
{"text": "(*\n  File:     Jacobi_Symbol.thy\n  Authors:  Daniel St\u00fcwe, Manuel Eberl\n\n  The Jacobi symbol, a generalisation of the Legendre symbol.\n  This is used in the Solovay--Strassen test.\n*)\nsection \\<open>The Jacobi Symbol\\<close>\ntheory Jacobi_Symbol\nimports \n  Legendre_Symbol\n  Algebraic_Auxiliaries\nbegin\n\ntext \\<open>\n  The Jacobi symbol is a generalisation of the Legendre symbol to non-primes \\<^cite>\\<open>\"Legendre_Symbol\" and \"Jacobi_Symbol\"\\<close>.\n  It is defined as\n  \\[\\left(\\frac{a}{n}\\right) =\n      \\left(\\frac{a}{p_1}\\right)^{k_1} \\ldots \\left(\\frac{a}{p_l}\\right)^{k_l}\\]\n  where $(\\frac{a}{p})$ denotes the Legendre symbol, \\<open>a\\<close> is an integer, \\<open>n\\<close> is an odd natural\n  number and $p_1^{k_1}\\ldots p_l^{k_l}$ is its prime factorisation.\n\n  There is, however, a fairly natural generalisation to all non-zero integers for \\<open>n\\<close>.\n  It is less clear what a good choice for \\<open>n = 0\\<close> is; Mathematica and Maxima adopt\n  the convention that $(\\frac{\\pm 1}{0}) = 1$ and $(\\frac{a}{0}) = 0$ otherwise. However,\n  we chose the slightly different convention $(\\frac{a}{0}) = 0$ for \\<^emph>\\<open>all\\<close> \\<open>a\\<close> because then\n  the Jacobi symbol is completely multiplicative in both arguments without any restrictions.\n\\<close>\ndefinition Jacobi :: \"int \\<Rightarrow> int \\<Rightarrow> int\" where\n  \"Jacobi a n = (if n = 0 then 0 else\n                  (\\<Prod>p\\<in>#prime_factorization n. Legendre a p))\"\n\nlemma Jacobi_0_right [simp]: \"Jacobi a 0 = 0\"\n  by (simp add: Jacobi_def)\n\nlemma Jacobi_mult_left [simp]: \"Jacobi (a * b) n = Jacobi a n * Jacobi b n\"\nproof (cases \"n = 0\")\n  case False\n  have *: \"{# Legendre (a * b) p          . p \\<in># prime_factorization n #} =\n           {# Legendre a p * Legendre b p . p \\<in># prime_factorization n #}\"\n    by (meson Legendre_mult in_prime_factors_imp_prime image_mset_cong)\n\n  show ?thesis using False unfolding Jacobi_def * prod_mset.distrib by auto\nqed auto\n\nlemma Jacobi_mult_right [simp]: \"Jacobi a (n * m) = Jacobi a n * Jacobi a m\"\n  by (cases \"m = 0\"; cases \"n = 0\")\n     (auto simp: Jacobi_def prime_factorization_mult)\n\nlemma prime_p_Jacobi_eq_Legendre[intro!]: \"prime p \\<Longrightarrow> Jacobi a p = Legendre a p\"\n  unfolding Jacobi_def prime_factorization_prime by simp\n\nlemma Jacobi_mod [simp]: \"Jacobi (a mod m) n = Jacobi a n\" if \"n dvd m\"\nproof -\n  have *: \"{# Legendre (a mod m) p . p \\<in># prime_factorization n #} =\n           {# Legendre a p . p \\<in># prime_factorization n #}\" using that\n    by (intro image_mset_cong, subst Legendre_mod)\n       (auto intro: dvd_trans[OF in_prime_factors_imp_dvd])\n  thus ?thesis by (simp add: Jacobi_def)\nqed\n\nlemma Jacobi_mod_cong: \"[a = b] (mod n) \\<Longrightarrow> Jacobi a n = Jacobi b n\"\n  by (metis Jacobi_mod cong_def dvd_refl)\n\nlemma Jacobi_1_eq_1 [simp]: \"p \\<noteq> 0 \\<Longrightarrow> Jacobi 1 p = 1\"\n  by (simp add: Jacobi_def in_prime_factors_imp_prime cong: image_mset_cong)\n\n\n\nlemma Jacobi_p_eq_2'[simp]: \"n > 0 \\<Longrightarrow> Jacobi a (2^n) = a mod 2\"\n  by (auto simp add: Jacobi_def prime_factorization_prime_power)\n\nlemma Jacobi_prod_mset[simp]: \"n \\<noteq> 0 \\<Longrightarrow> Jacobi (prod_mset M) n = (\\<Prod>q\\<in>#M. Jacobi q n)\"\n  by (induction M) simp_all\n\nlemma non_trivial_coprime_neq:\n  \"1 < a \\<Longrightarrow> 1 < b \\<Longrightarrow> coprime a b \\<Longrightarrow> a \\<noteq> b\" for a b :: int by auto\n\n\nlemma odd_odd_even: \n  fixes a b :: int \n  assumes \"odd a\" \"odd b\"\n  shows \"even ((a*b-1) div 2) = even ((a-1) div 2 + (b-1) div 2)\"\n  using assms by (auto elim!: oddE simp: algebra_simps)\n\nlemma prime_nonprime_wlog [case_names primes nonprime sym]:\n  assumes \"\\<And>p q. prime p \\<Longrightarrow> prime q \\<Longrightarrow> P p q\"\n  assumes \"\\<And>p q. \\<not>prime p \\<Longrightarrow> P p q\"\n  assumes \"\\<And>p q. P p q \\<Longrightarrow> P q p\"\n  shows   \"P p q\"\n  by (cases \"prime p\"; cases \"prime q\") (auto intro: assms)\n\nlemma Quadratic_Reciprocity_Jacobi:\n  fixes p q :: int\n  assumes \"coprime p q\"\n      and \"2 < p\" \"2 < q\"\n      and \"odd p\" \"odd q\"\n    shows \"Jacobi p q * Jacobi q p =\n           (- 1) ^ (nat ((p - 1) div 2 * ((q - 1) div 2)))\"\n  using assms\nproof (induction \"nat p\" \"nat q\" arbitrary: p q \n         rule: measure_induct_rule[where f = \"\\<lambda>(a, b). a + b\", split_format(complete), simplified])\n  case (1 p q)\n  thus ?case\n  proof (induction p q rule: prime_nonprime_wlog)\n    case (sym p q)\n    thus ?case by (simp only: add_ac coprime_commute mult_ac) blast\n  next\n    case (primes p q)\n    from \\<open>prime p\\<close> \\<open>prime q\\<close> have \"prime (nat p)\" \"prime (nat q)\" \"p \\<noteq> q\"\n      using prime_int_nat_transfer primes(4) non_trivial_coprime_neq prime_gt_1_int\n      by blast+\n\n    with Quadratic_Reciprocity_int and prime_p_Jacobi_eq_Legendre\n    show ?case\n      using \\<open>prime p\\<close> \\<open>prime q\\<close> primes(5-) \n      by presburger\n  next\n    case (nonprime p q)\n    from \\<open>\\<not>prime p\\<close> obtain a b where *: \"p = a * b\" \"1 < b\" \"1 < a\"\n      using \\<open>2 < p\\<close> prime_divisor_exists_strong[of p] by auto\n\n    hence odd_ab: \"odd a\" \"odd b\" using \\<open>odd p\\<close> by simp_all\n\n    moreover have \"2 < b\" and \"2 < a\" \n      using odd_ab and * by presburger+\n\n    moreover have \"coprime a q\" and \"coprime b q\" using \\<open>coprime p q\\<close> \n      unfolding * by simp_all\n\n    ultimately have IH: \"Jacobi a q * Jacobi q a = (- 1) ^ nat ((a - 1) div 2 * ((q - 1) div 2))\"\n                        \"Jacobi b q * Jacobi q b = (- 1) ^ nat ((b - 1) div 2 * ((q - 1) div 2))\"\n      by (auto simp: * nonprime)\n\n    have pos: \"0 < q\" \"0 < p\" \"0 < a\" \"0 < b\" \n      using * \\<open>2 < q\\<close> by simp_all\n\n    have \"Jacobi p q * Jacobi q p = (Jacobi a q * Jacobi q a) * (Jacobi b q * Jacobi q b)\"\n      using * by simp\n\n    also have \"... = (- 1) ^ nat ((a - 1) div 2 * ((q - 1) div 2)) *\n                     (- 1) ^ nat ((b - 1) div 2 * ((q - 1) div 2))\"\n      using IH by presburger\n\n    also from odd_odd_even[OF odd_ab]\n    have \"... = (- 1) ^ nat ((p - 1) div 2 * ((q - 1) div 2))\"\n      unfolding * minus_one_power_iff using \\<open>2 < q\\<close> *\n      by (auto simp add: even_nat_iff pos_imp_zdiv_nonneg_iff)\n\n    finally show ?case .\n  qed\nqed\n\nlemma Jacobi_values: \"Jacobi p q \\<in> {1, -1, 0}\"\nproof (cases \"q = 0\")\n  case False\n  hence \"\\<bar>Legendre p x\\<bar> = 1\" if \"x \\<in># prime_factorization q\" \"Jacobi p q \\<noteq> 0\" for x\n    using that prod_mset_zero_iff Legendre_values[of p x]\n    unfolding Jacobi_def is_unit_prod_mset_iff set_image_mset\n    by fastforce\n\n  then have \"is_unit (prod_mset (image_mset (Legendre p) (prime_factorization q)))\"\n    if \"Jacobi p q \\<noteq> 0\"\n    using that False\n    unfolding Jacobi_def is_unit_prod_mset_iff \n    by auto\n\n  thus ?thesis by (auto simp: Jacobi_def)\nqed auto\n\nlemma Quadratic_Reciprocity_Jacobi':\n  fixes p q :: int\n  assumes \"coprime p q\"\n      and \"2 < p\" \"2 < q\"\n      and \"odd p\" \"odd q\"\n    shows \"Jacobi q p = (if p mod 4 = 3 \\<and> q mod 4 = 3 then -1 else 1) * Jacobi p q\"\nproof -\n  have aux: \"a \\<in> {1, -1, 0} \\<Longrightarrow> c \\<noteq> 0 \\<Longrightarrow> a*b = c \\<Longrightarrow> b = c * a\" for b c a :: int by auto\n\n  from Quadratic_Reciprocity_Jacobi[OF assms] \n  have \"Jacobi q p = (-1) ^ nat ((p - 1) div 2 * ((q - 1) div 2)) * Jacobi p q\"\n    using Jacobi_values by (fastforce intro!: aux)\n\n  also have \"(-1 :: int) ^ nat ((p - 1) div 2 * ((q - 1) div 2)) = (if even ((p - 1) div 2) \\<or> even ((q - 1) div 2) then 1 else - 1)\"\n    unfolding minus_one_power_iff using \\<open>2 < p\\<close> \\<open>2 < q\\<close>\n    by (auto simp: even_nat_iff)\n\n  also have \"... = (if p mod 4 = 3 \\<and> q mod 4 = 3 then -1 else 1)\"\n    using \\<open>odd p\\<close> \\<open>odd q\\<close> by presburger\n\n  finally show ?thesis .\n\nqed\n\n\n\nlemma odd_odd_even': \n  fixes a b :: int \n  assumes \"odd a\" \"odd b\"\n  shows \"even (((a * b)\\<^sup>2 - 1) div 8) \\<longleftrightarrow> even (((a\\<^sup>2 - 1) div 8) + ((b\\<^sup>2 - 1) div 8))\"\nproof -\n  obtain x where [simp]: \"a = 2*x + 1\" using \\<open>odd a\\<close> by (auto elim: oddE)\n  obtain y where [simp]: \"b = 2*y + 1\" using \\<open>odd b\\<close> by (auto elim: oddE)\n  show ?thesis\n    by (cases \"even x\"; cases \"even y\"; elim oddE evenE)\n       (auto simp: power2_eq_square algebra_simps)\nqed\n\nlemma odd_odd_even_nat': \n  fixes a b :: nat \n  assumes \"odd a\" \"odd b\"\n  shows \"even (((a * b)\\<^sup>2 - 1) div 8) \\<longleftrightarrow> even (((a\\<^sup>2 - 1) div 8) + ((b\\<^sup>2 - 1) div 8))\"\nproof -\n  obtain x where [simp]: \"a = 2*x + 1\" using \\<open>odd a\\<close> by (auto elim: oddE)\n  obtain y where [simp]: \"b = 2*y + 1\" using \\<open>odd b\\<close> by (auto elim: oddE)\n  show ?thesis\n    by (cases \"even x\"; cases \"even y\"; elim oddE evenE)\n       (auto simp: power2_eq_square algebra_simps)\nqed\n\nlemma supplement2_Jacobi: \"odd p \\<Longrightarrow> p > 1 \\<Longrightarrow> Jacobi 2 p = (- 1) ^ (((nat p)\\<^sup>2 - 1) div 8)\"\nproof (induction p rule: prime_divisors_induct)\n  case (factor p x)\n\n  then have \"odd x\" by force\n\n  have \"2 < p\" \n    using \\<open>odd (p * x)\\<close> prime_gt_1_int[OF \\<open>prime p\\<close>] \n    by (cases \"p = 2\") auto\n\n  have \"odd p\" using prime_odd_int[OF \\<open>prime p\\<close> \\<open>2 < p\\<close>] .\n\n  have \"0 < x\"\n    using \\<open>1 < (p * x)\\<close> prime_gt_0_int[OF \\<open>prime p\\<close>]\n    and less_trans less_numeral_extra(1) zero_less_mult_pos by blast\n\n  have base_case : \"Jacobi 2 p = (- 1) ^ (((nat p)\\<^sup>2 - 1) div 8)\" \n    using \\<open>2 < p\\<close> \\<open>prime p\\<close> supplement2_Legendre and prime_p_Jacobi_eq_Legendre\n    by presburger\n\n  show ?case proof (cases \"x = 1\")\n    case True\n    thus ?thesis using base_case by force\n  next\n    case False\n    have \"Jacobi 2 (p * x) = Jacobi 2 p * Jacobi 2 x\"\n      using \\<open>2 < p\\<close> \\<open>0 < x\\<close> by simp\n\n    also have \"Jacobi 2 x = (- 1) ^ (((nat x)\\<^sup>2 - 1) div 8)\"\n      using \\<open>odd x\\<close> \\<open>0 < x\\<close> \\<open>x \\<noteq> 1\\<close> by (intro factor.IH) auto\n\n    also note base_case\n\n    also have \"(-1) ^ (((nat p)\\<^sup>2 - 1) div 8) * (-1) ^ (((nat x)\\<^sup>2 - 1) div 8)\n             = (-1 :: int) ^ (((nat (p * x))\\<^sup>2 - 1) div 8)\" \n      unfolding minus_one_power_iff\n      using \\<open>2 < p\\<close> \\<open>0 < x\\<close> \\<open>odd x\\<close> \\<open>odd p\\<close> and odd_odd_even_nat'\n      using [[linarith_split_limit = 0]]\n      by (force simp add: nat_mult_distrib even_nat_iff)\n\n    finally show ?thesis .\n  qed\nqed simp_all\n\n\n\nlemma mod_int_wlog [consumes 1, case_names modulo]:\n  fixes P :: \"int \\<Rightarrow> bool\"\n  assumes \"b > 0\"\n  assumes \"\\<And>k. 0 \\<le> k \\<Longrightarrow> k < b \\<Longrightarrow> n mod b = k \\<Longrightarrow> P n\"\n  shows   \"P n\"\n  using \\<open>b > 0\\<close> assms(2) [of \\<open>n mod b\\<close>] by simp\n\nlemma supplement2_Jacobi':\n  assumes \"odd p\" and \"p > 1\"\n  shows \"Jacobi 2 p = (if p mod 8 = 1 \\<or> p mod 8 = 7 then 1 else -1)\"\nproof -\n  have \"0 < (4 :: nat)\" by simp\n  then have *: \"even ((p\\<^sup>2 - 1) div 8) = (p mod 8 = 1 \\<or> p mod 8 = 7)\" if \"odd p\" for p :: nat\n  proof(induction p rule: mod_nat_wlog)\n    case (modulo k)\n    then consider \"p mod 4 = 1\" | \"p mod 4 = 3\"\n      using \\<open>odd p\\<close>\n      by (metis dvd_0_right even_even_mod_4_iff even_numeral mod_exhaust_less_4)\n\n    then show ?case proof (cases)\n      case 1\n      then obtain l where l: \"p = 4 * l + 1\" using mod_natE by blast\n      have \"even l = ((4 * l + 1) mod 8 = 1 \\<or> (4 * l + 1) mod 8 = 7)\" by presburger\n      thus ?thesis by (simp add: l power2_eq_square algebra_simps)\n    next\n      case 2\n      then obtain l where l: \"p = 4 * l + 3\" using mod_natE by blast\n      have \"odd l = ((3 + l * 4) mod 8 = Suc 0 \\<or> (3 + l * 4) mod 8 = 7)\" by presburger\n      thus ?thesis by (simp add: l power2_eq_square algebra_simps)\n    qed\n  qed\n\n  have [simp]: \"nat p mod 8 = nat (p mod 8)\"\n    using \\<open>p > 1\\<close> using nat_mod_distrib[of p 8] by simp\n  from assms have \"odd (nat p)\" by (simp add: even_nat_iff)\n  show ?thesis\n    unfolding supplement2_Jacobi[OF assms]\n              minus_one_power_iff *[OF \\<open>odd (nat p)\\<close>]\n    by (simp add: nat_eq_iff)\nqed\n\ntheorem supplement1_Jacobi:\n  \"odd p \\<Longrightarrow> 1 < p \\<Longrightarrow> Jacobi (-1) p = (-1) ^ (nat ((p - 1) div 2))\"\nproof (induction p rule: prime_divisors_induct)\n  case (factor p x)\n  then have \"odd x\" by force\n\n  have \"2 < p\" \n    using \\<open>odd (p * x)\\<close> prime_gt_1_int[OF \\<open>prime p\\<close>]\n    by (cases \"p = 2\") auto\n\n  have \"prime (nat p)\"\n    using \\<open>prime p\\<close> prime_int_nat_transfer\n    by blast\n\n  have \"Jacobi (-1) p = Legendre (-1) p\"\n    using prime_p_Jacobi_eq_Legendre[OF \\<open>prime p\\<close>] .\n\n  also have \"... = (-1) ^ ((nat p - 1) div 2)\"\n    using \\<open>prime p\\<close> \\<open>2 < p\\<close> and supplement1_Legendre[of \"nat p\"]\n    by (metis int_nat_eq nat_mono_iff nat_numeral_as_int prime_gt_0_int prime_int_nat_transfer) \n\n  also have \"((nat p - 1) div 2) = nat ((p - 1) div 2)\" by force\n\n  finally have base_case: \"Jacobi (-1) p = (-1) ^ nat ((p - 1) div 2)\" .\n\n  show ?case proof (cases \"x = 1\")\n    case True\n    then show ?thesis using base_case by simp\n  next\n    case False\n    have \"0 < x\" \n      using \\<open>1 < (p * x)\\<close> prime_gt_0_int[OF \\<open>prime p\\<close>]\n      by (meson int_one_le_iff_zero_less not_less not_less_iff_gr_or_eq zero_less_mult_iff)\n  \n    have \"odd p\" using \\<open>prime p\\<close> \\<open>2 < p\\<close> by (simp add: prime_odd_int) \n\n    have \"Jacobi (-1) (p * x) = Jacobi (-1) p * Jacobi (-1) x\"\n      using \\<open>2 < p\\<close> \\<open>0 < x\\<close> by simp\n\n    also note base_case\n\n    also have \"Jacobi (-1) x = (-1) ^ nat ((x - 1) div 2)\"\n      using \\<open>0 < x\\<close> False \\<open>odd x\\<close> factor.IH \n      by fastforce\n\n    also have \"(- 1) ^ nat ((p - 1) div 2) * (- 1) ^ nat ((x - 1) div 2) =\n               (- 1 :: int) ^ nat ((p*x - 1) div 2)\"\n      unfolding minus_one_power_iff\n      using \\<open>2 < p\\<close> \\<open>0 < x\\<close> and \\<open>odd x\\<close> \\<open>odd p\\<close>\n      by (fastforce elim!: oddE simp: even_nat_iff algebra_simps)\n\n    finally show ?thesis .\n  qed\nqed simp_all\n\ntheorem supplement1_Jacobi':\n  \"odd n \\<Longrightarrow> 1 < n \\<Longrightarrow> Jacobi (-1) n = (if n mod 4 = 1 then 1 else -1)\"\n  by (simp add: even_nat_iff minus_one_power_iff supplement1_Jacobi)\n     presburger?\n\nlemma Jacobi_0_eq_0: \"\\<not>is_unit n \\<Longrightarrow> Jacobi 0 n = 0\"\n  by (cases \"prime_factorization n = {#}\")\n     (auto simp: Jacobi_def prime_factorization_empty_iff image_iff intro: Nat.gr0I)\n\nlemma is_unit_Jacobi_aux: \"is_unit x \\<Longrightarrow> Jacobi a x = 1\"\n  unfolding Jacobi_def using prime_factorization_empty_iff[of x] by auto\n\nlemma is_unit_Jacobi[simp]: \"Jacobi a 1 = 1\" \"Jacobi a (-1) = 1\"\n  using is_unit_Jacobi_aux by simp_all\n\nlemma Jacobi_neg_right [simp]:\n  \"Jacobi a (-n) = Jacobi a n\"\nproof -\n  have * : \"-n = (-1) * n\" by simp\n  show ?thesis unfolding *\n    by (subst Jacobi_mult_right) auto\nqed\n\nlemma Jacobi_neg_left:\n  assumes \"odd n\" \"1 < n\" \n  shows   \"Jacobi (-a) n = (if n mod 4 = 1 then 1 else -1) * Jacobi a n\"\nproof -\n  have * : \"-a = (-1) * a\" by simp\n  show ?thesis unfolding * Jacobi_mult_left supplement1_Jacobi'[OF assms] ..\nqed\n\nfunction jacobi_code :: \"int \\<Rightarrow> int \\<Rightarrow> int\" where\n\"jacobi_code a n = ( \n        if n = 0 then 0\n   else if n = 1 then 1\n   else if a = 1 then 1\n   else if n < 0 then jacobi_code a (-n)\n   else if even n then if even a then 0 else jacobi_code a (n div 2)\n   else if a < 0 then (if n mod 4 = 1 then 1 else -1) * jacobi_code (-a) n\n   else if a = 0 then 0\n   else if a \\<ge> n then jacobi_code (a mod n) n\n   else if even a      then (if n mod 8 \\<in> {1, 7} then 1 else -1) * jacobi_code (a div 2) n\n   else if coprime a n then (if n mod 4 = 3 \\<and> a mod 4 = 3 then -1 else 1) * jacobi_code n a\n   else 0)\"\n  by auto\ntermination\nproof (relation \"measure (\\<lambda>(a, n). nat(abs(a) + abs(n)*2) + \n                   (if n < 0 then 1 else 0) + (if a < 0 then 1 else 0))\", goal_cases)\n  case (5 a n)\n  thus ?case by (fastforce intro!: less_le_trans[OF pos_mod_bound])\nqed auto\n\nlemmas [simp del] = jacobi_code.simps\n\nlemma Jacobi_code [code]: \"Jacobi a n = jacobi_code a n\"\nproof (induction a n rule: jacobi_code.induct)\n  case (1 a n)\n  show ?case\n  proof (cases \"n = 0\")\n    case 2: False\n    then show ?thesis proof (cases \"n = 1\")\n      case 3: False\n      then show ?thesis proof (cases \"a = 1\")\n        case 4: False\n          then show ?thesis proof (cases \"n < 0\")\n            case True\n            then show ?thesis using 2 3 4 1(1) by (subst jacobi_code.simps) simp\n            next\n            case 5: False\n            then show ?thesis proof (cases \"even n\")\n              case True\n              then show ?thesis using 2 3 4 5 1(2)\n                by (elim evenE, subst jacobi_code.simps) (auto simp: prime_p_Jacobi_eq_Legendre)\n            next\n              case 6: False\n              then show ?thesis  proof (cases \"a < 0\")\n                case True\n                then show ?thesis using 2 3 4 5 6\n                  by(subst jacobi_code.simps, subst 1(3)[symmetric]) (simp_all add: Jacobi_neg_left)\n              next\n                case 7: False\n                then show ?thesis proof (cases \"a = 0\")\n                  case True\n                  have *: \"\\<not> is_unit n\" using 3 5 by simp\n                  then show ?thesis\n                    using Jacobi_0_eq_0[OF *] 2 3 4 5 7 True\n                    by (subst jacobi_code.simps) simp\n                next\n                  case 8: False\n                  then show ?thesis proof (cases \"a \\<ge> n\")\n                    case True\n                    then show ?thesis using 2 3 4 5 6 7 8 1(4)\n                      by (subst jacobi_code.simps) simp\n                  next\n                    case 9: False\n                    then show ?thesis proof (cases \"even a\")\n                      case True\n                      hence \"a = 2 * (a div 2)\" by simp\n                      also have \"Jacobi \\<dots> n = Jacobi 2 n * Jacobi (a div 2) n\"\n                        by simp\n                      also have \"Jacobi (a div 2) n = jacobi_code (a div 2) n\"\n                        using 2 3 4 5 6 7 8 9 True by (intro 1(5))\n                      also have \"Jacobi 2 n = (if n mod 8 \\<in> {1, 7} then 1 else - 1)\"\n                        using 2 3 5 supplement2_Jacobi'[OF 6] by simp\n                      also have \"\\<dots> * jacobi_code (a div 2) n = jacobi_code a n\"\n                        using 2 3 4 5 6 7 8 9 True\n                        by (subst (2) jacobi_code.simps) (simp only: if_False if_True HOL.simp_thms)\n                      finally show ?thesis .\n                    next\n                      case 10: False\n                      note foo = 1 2 3\n                      then show ?thesis proof (cases \"coprime a n\")\n                        case True\n                        note this_case = 2 3 4 5 6 7 8 9 10 True\n                        have \"2 < a\" using 10 4 7 by presburger\n                        moreover have \"2 < n\" using 3 5 6 by presburger\n                        ultimately have \"jacobi_code a n = (if n mod 4 = 3 \\<and> a mod 4 = 3 then - 1 else 1)\n                                                        * jacobi_code n a\"\n                          using this_case by (subst jacobi_code.simps) simp\n                        also have \"jacobi_code n a = Jacobi n a\"\n                          using this_case by (intro 1(6) [symmetric]) auto\n                        also have \"(if n mod 4 = 3 \\<and> a mod 4 = 3 then -1 else 1) * \\<dots> = Jacobi a n\"\n                          using this_case and \\<open>2 < a\\<close>\n                          by (intro Quadratic_Reciprocity_Jacobi' [symmetric])\n                             (auto simp: coprime_commute)\n                        finally show ?thesis ..\n                      next\n                        case False\n                        have *: \"0 < a\" \"0 < n\" using 5 7 8 9 by linarith+ \n                        show ?thesis\n                          using 1 2 3 4 5 6 7 8 9 10 False *\n                          by (subst jacobi_code.simps) (auto simp: Jacobi_eq_0_not_coprime)\n                      qed\n                    qed\n                  qed\n                qed\n              qed\n            qed\n        qed\n      qed (subst jacobi_code.simps, simp)\n    qed (subst jacobi_code.simps, simp)\n  qed (subst jacobi_code.simps, simp)\nqed\n\nlemma Jacobi_eq_0_imp_not_coprime:\n  assumes \"p \\<noteq> 0\" \"p \\<noteq> 1\"\n  shows   \"Jacobi n p = 0 \\<Longrightarrow> \\<not>coprime n p\"\n  using assms Jacobi_mod_cong coprime_iff_invertible_int by force\n\nlemma Jacobi_eq_0_iff_not_coprime:\n  assumes \"p \\<noteq> 0\" \"p \\<noteq> 1\"\n  shows \"Jacobi n p = 0 \\<longleftrightarrow> \\<not>coprime n p\"\nproof -\n  from assms and Jacobi_eq_0_imp_not_coprime \n  show ?thesis using Jacobi_eq_0_not_coprime by 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/Probabilistic_Prime_Tests/Jacobi_Symbol.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8740772318846387, "lm_q2_score": 0.847967764140929, "lm_q1q2_score": 0.7411893160077094}}
{"text": "(*  \n    Author:      Ren\u00e9 Thiemann \n                 Akihisa Yamada\n    License:     BSD\n*)\nsection \\<open>Schur Decomposition\\<close>\n\ntext \\<open>We implement Schur decomposition as an algorithm which, given a square matrix $A$\n  and a list eigenvalues, computes $B$, $P$, and $Q$ such that \n  $A = PBQ$, $B$ is upper-triangular and $PQ = 1$. The algorithm works is generic in\n  the kind of field and can be applied on the rationals, the reals, and the complex numbers.\n  The algorithm relies on the method of Gram-Schmidt to create an orthogonal basis,\n  and on the Gauss-Jordan algorithm to find eigenvectors to a given eigenvalue.\n  \n The algorithm is a key ingredient to show that every matrix with a linear factorizable \n characteristic polynomial has a Jordan normal form. \n\n  A further consequence of the algorithm is that the characteristic polynomial of \n  a block diagonal matrix is the product of the characteristic polynomials of the blocks.\\<close>\n\ntheory Schur_Decomposition\nimports \n  Polynomial_Interpolation.Missing_Polynomial\n  Gram_Schmidt \n  Char_Poly\nbegin\n\ndefinition vec_inv :: \"'a::conjugatable_field vec \\<Rightarrow> 'a vec\"\n  where \"vec_inv v = 1 / (v \\<bullet>c v) \\<cdot>\\<^sub>v conjugate v\"\n\nlemma vec_inv_closed[simp]: \"v \\<in> carrier_vec n \\<Longrightarrow> vec_inv v \\<in> carrier_vec n\"\n  unfolding vec_inv_def by auto\n\nlemma vec_inv_dim[simp]: \"dim_vec (vec_inv v) = dim_vec v\"\n  unfolding vec_inv_def by auto\n\nlemma vec_inv[simp]:\n  assumes v: \"v : carrier_vec n\"\n      and v0: \"(v::'a::conjugatable_ordered_field vec) \\<noteq> 0\\<^sub>v n\"\n  shows \"vec_inv v \\<bullet> v = 1\"\nproof -\n  { assume \"v \\<bullet>c v = 0\"\n    hence \"v = 0\\<^sub>v n\" using conjugate_square_eq_0_vec[OF v] by auto\n    hence False using v0 by auto\n  }\n  moreover have \"conjugate v \\<bullet> v = v \\<bullet>c v\"\n    apply (rule comm_scalar_prod) using v by auto\n  ultimately show ?thesis\n    unfolding vec_inv_def\n    apply (subst smult_scalar_prod_distrib)\n    using assms by auto\nqed\n\nlemma corthogonal_inv:\n  assumes orth: \"corthogonal (vs ::'a::conjugatable_field vec list)\"\n      and V: \"set vs \\<subseteq> carrier_vec n\"\n  shows \"inverts_mat (mat_of_rows n (map vec_inv vs)) (mat_of_cols n vs)\"\n    (is \"inverts_mat ?W ?V\")\nproof -\n  define l where \"l = length vs\"\n  have rW[simp]: \"dim_row ?W = l\" using l_def by auto\n  have cV[simp]:\"dim_col ?V = l\" using l_def by auto\n  have dim: \"\\<And>i. i < length vs \\<Longrightarrow> vs!i \\<in> carrier_vec n\" using V by auto\n  show ?thesis\n    unfolding inverts_mat_def\n    apply rule\n    unfolding mat_of_rows_carrier length_map l_def[symmetric]\n    unfolding index_one_mat\n  proof -\n    show \"dim_row (?W * ?V) = l\" \"dim_col (?W * ?V) = l\"\n      unfolding times_mat_def rW cV by auto\n    fix i j assume i:\"i<l\" and j: \"j<l\"\n    hence i2: \"i<length vs\"\n      and i3: \"i<length (map vec_inv vs)\"\n      and j2: \"j<length vs\" using l_def by auto\n    hence id2: \"vs ! i \\<in> carrier_vec n\"\n      and id3: \"map vec_inv vs ! i \\<in> carrier_vec n\"\n      and id4: \"conjugate (vs ! i) \\<in> carrier_vec n\"\n      and jd2: \"vs ! j \\<in> carrier_vec n\" using dim by auto\n    show \"(?W * ?V) $$ (i,j) = (if i = j then 1 else 0)\"\n      unfolding times_mat_def rW cV\n      unfolding index_mat[OF i j] split\n      unfolding mat_of_rows_row[OF i3 id3]\n      unfolding col_mat_of_cols[OF j2 jd2]\n      unfolding nth_map[OF i2]\n      unfolding vec_inv_def\n      unfolding smult_scalar_prod_distrib[OF id4 jd2]\n      unfolding comm_scalar_prod[OF id4 jd2]\n      using corthogonalD[OF orth j2 i2] by auto\n  qed\nqed\n\ndefinition corthogonal_inv :: \"'a::conjugatable_field mat \\<Rightarrow> 'a mat\"\n  where \"corthogonal_inv A = mat_of_rows (dim_row A) (map vec_inv (cols A))\"\n\ndefinition mat_adjoint :: \"'a :: conjugatable_field mat \\<Rightarrow> 'a mat\"\n  where \"mat_adjoint A \\<equiv> mat_of_rows (dim_row A) (map conjugate (cols A))\"\n\ndefinition corthogonal_mat :: \"'a::conjugatable_field mat \\<Rightarrow> bool\"\n  where \"corthogonal_mat A \\<equiv>\n    let B = mat_adjoint A * A in\n    diagonal_mat B \\<and> (\\<forall>i<dim_col A. B $$ (i,i) \\<noteq> 0)\"\n\nlemma corthogonal_matD[elim]:\n  assumes orth: \"corthogonal_mat A\"\n      and i: \"i < dim_col A\"\n      and j: \"j < dim_col A\"\n  shows \"(col A i \\<bullet>c col A j = 0) = (i \\<noteq> j)\"\nproof\n  have ci: \"col A i : carrier_vec (dim_row A)\"\n   and cj: \"col A j : carrier_vec (dim_row A)\" by auto\n  note [simp] = conjugate_conjugate_sprod[OF ci cj]\n\n  let ?B = \"mat_adjoint A * A\"\n  have diag: \"diagonal_mat ?B\" and zero: \"\\<And>i. i<dim_col A \\<Longrightarrow> ?B $$ (i,i) \\<noteq> 0\"\n    using orth unfolding corthogonal_mat_def Let_def by auto\n  { assume \"i = j\"\n    hence \"conjugate (col A i) \\<bullet> col A j \\<noteq> 0\"\n      using zero[OF i] unfolding mat_adjoint_def using i by simp\n    hence \"conjugate (conjugate (col A i) \\<bullet> col A j) \\<noteq> 0\"\n      unfolding conjugate_zero_iff.\n    hence \"col A i \\<bullet>c col A j \\<noteq> 0\" by simp\n  }\n  thus \"col A i \\<bullet>c col A j = 0 \\<Longrightarrow> i \\<noteq> j\" by auto\n  { assume \"i \\<noteq> j\"\n    hence \"conjugate (col A i) \\<bullet> col A j = 0\"\n      using diag\n      unfolding diagonal_mat_def\n      unfolding mat_adjoint_def using i j by simp\n    hence \"conjugate (conjugate (col A i) \\<bullet> col A j) = 0\" by simp\n    thus \"col A i \\<bullet>c col A j = 0\" by simp\n  }\nqed\n\n\n\nlemma corthogonal_inv_result:\n  assumes o: \"corthogonal_mat (A::'a::conjugatable_field mat)\"\n  shows \"inverts_mat (corthogonal_inv A) A\"\nproof -\n  have oc: \"corthogonal (cols A)\"\n    apply (intro corthogonalI) using corthogonal_matD[OF o] by auto\n  show ?thesis unfolding corthogonal_inv_def\n    using corthogonal_inv[OF oc cols_dim] by auto\nqed\n\ntext \"extends a vector to a basis\"\n\ndefinition basis_completion :: \"'a::ring_1 vec \\<Rightarrow> 'a vec list\" where\n  \"basis_completion v \\<equiv> let \n     n = dim_vec v;\n     drop_index = hd ([ i . i <- [0..<n], v $ i \\<noteq> 0]);\n     vs = [unit_vec n i. i <- [0..<n], i \\<noteq> drop_index] \n   in v # vs\"\n\nlemma (in vec_space) basis_completion: fixes v :: \"'a :: field vec\"\n  assumes v: \"v \\<in> carrier_vec n\"\n      and v0: \"v \\<noteq> 0\\<^sub>v n\"\n  shows \n    \"basis (set (basis_completion v))\"\n    \"set (basis_completion v) \\<subseteq> carrier_vec n\"\n    \"span (set (basis_completion v)) = carrier_vec n\" \n    \"distinct (basis_completion v)\"\n    \"\\<not> lin_dep (set (basis_completion v))\"\n    \"length (basis_completion v) = n\"\n    \"hd (basis_completion v) = v\"\nproof -\n  let ?b = \"basis_completion v\"\n  note d = basis_completion_def Let_def\n  from v have dim: \"dim_vec v = n\" by auto\n  let ?is = \"[ i . i <- [0..<n], v $ i \\<noteq> 0]\"\n  {\n    assume empty: \"set ?is = {}\"\n    have \"v = 0\\<^sub>v n\"\n      by (rule eq_vecI, insert empty v, auto)\n  }\n  with v0 obtain k ids where id: \"?is = k # ids\" and mem: \"k \\<in> set ?is\" by (cases ?is, auto)\n  from mem have vk: \"v $ k \\<noteq> 0\" and k: \"k < n\" by auto\n  {\n    fix i \n    assume i: \"\\<not> i < k\"\n    have id: \"k # [Suc k..<n] = [k ..< n]\" using k by (simp add: upt_conv_Cons)\n    from i have \"i < n \\<Longrightarrow> (k # [Suc k..<n]) ! (i - k) = i\" \n      unfolding id\n      by (subst nth_upt, auto)\n  }\n  hence split: \"[0 ..< n] = [0 ..< k] @ k # [Suc k ..< n]\"\n    by (intro nth_equalityI, insert k, auto simp: nth_append) \n  {\n    fix as\n    assume \"k \\<notin> set as\"\n    hence \"[unit_vec n i. i <- as, i \\<noteq> k] = [unit_vec n i. i <- as]\"\n      by (induct as, auto)\n  } note conv = this\n  have b_all: \"?b = v # [unit_vec n i. i <- [0..<n], i \\<noteq> k]\"\n    unfolding d dim id by simp \n  also have \"[unit_vec n i. i <- [0..<n], i \\<noteq> k] = [unit_vec n i. i <- [0..<k]] @ [unit_vec n i. i <- [Suc k..<n]]\"\n    unfolding split by (auto simp: conv)\n  finally have b: \"?b = v # [unit_vec n i. i <- [0..<k]] @ [unit_vec n i. i <- [Suc k..<n]]\" by simp\n  show carr: \"set ?b \\<subseteq> carrier_vec n\" (is \"?S \\<subseteq> _\")\n    unfolding b using assms by auto\n  show \"hd ?b = v\" unfolding b by auto\n  show len: \"length (basis_completion v) = n\" unfolding b using k\n    by auto\n  define I where \"I = (\\<lambda> i. if i < k then i else Suc i)\"\n  have I: \"\\<And> i. I i \\<noteq> k\" \"\\<And> i. Suc i < n \\<Longrightarrow> I i < n\" unfolding I_def by auto\n  {\n    fix i\n    assume i: \"i < n\"\n    have \"?b ! i = (if i = 0 then v else unit_vec n (I (i - 1)))\"\n      unfolding b I_def using i\n      by (auto split: if_splits simp: nth_append)\n  } note bi = this\n  show dist: \"distinct ?b\" unfolding distinct_conv_nth len\n  proof (intro allI impI)\n    fix i j\n    assume i: \"i < n\" and j: \"j < n\" and ij: \"i \\<noteq> j\"\n    show \"?b ! i \\<noteq> ?b ! j\"\n    proof \n      assume id1: \"?b ! i = ?b ! j\" \n      hence id2: \"\\<And> l. ?b ! i $ l = ?b ! j $ l\" by auto\n      have \"i = j\" \n      proof (cases \"i = 0\")\n        case True\n        hence biv: \"?b ! i = v\" unfolding b by simp\n        from True ij have bj: \"?b ! j = unit_vec n (I (j - 1))\" \"Suc (j - 1) = j\" unfolding bi[OF j] by auto\n        with id2[of k, unfolded biv bj] vk I[of \"j - 1\"] k j\n        have False by simp\n        thus ?thesis ..\n      next\n        case False note i0 = this\n        hence bi': \"?b ! i = unit_vec n (I (i - 1))\" \"Suc (i - 1) = i\" unfolding bi[OF i] by auto\n        show ?thesis\n        proof (cases \"j = 0\")\n          case True\n          hence bj: \"?b ! j = v\" unfolding b by simp\n          from id2[of k, unfolded bi' bj] vk I[of \"i - 1\"] k i bi'\n          have False by simp\n          thus ?thesis by simp\n        next\n          case False note j0 = this\n          hence bj: \"?b ! j = unit_vec n (I (j - 1))\" \"Suc (j - 1) = j\" unfolding bi[OF j] by auto\n          have \"1 = ?b ! i $ I (i - 1)\" unfolding bi' using I[of \"i - 1\"] i i0 by auto\n          also have \"\\<dots> = unit_vec n (I (j - 1)) $ I (i - 1)\" unfolding id1 bj by simp\n          also have \"\\<dots> = (if I (i - 1) = I (j - 1) then 1 else 0)\"\n            using I[of \"i - 1\"] I[of \"j - 1\"] i0 j0 i j by auto\n          finally have \"I (i - 1) = I (j - 1)\" by (auto split: if_splits)\n          with i0 j0 show \"i = j\" unfolding I_def by (auto split: if_splits)\n        qed\n      qed   \n      thus False using ij by simp\n    qed\n  qed\n  have \"span (set ?b) \\<subseteq> carrier_vec n\" using carr by auto\n  moreover\n  {\n    fix w :: \"'a vec\"\n    assume w: \"w \\<in> carrier_vec n\"\n    define lookup where \"lookup = (v,k) # [(unit_vec n i, i). i <- [0..<n], i \\<noteq> k]\"\n    define a where \"a = (\\<lambda> vi. case map_of lookup vi of Some i \\<Rightarrow> if i = k then w $ k / v $ k else\n       w $ i - w $ k / v $ k * v $ i)\" \n    have \"map fst lookup = ?b\" unfolding b_all lookup_def \n      by (auto simp: map_concat o_def if_distrib, unfold list.simps fst_def prod.simps, simp)\n    with dist have dist: \"distinct (map fst lookup)\" by simp\n    let ?w = \"lincomb a (set ?b)\"\n    have \"?w \\<in> carrier_vec n\" using carr by auto\n    with w have dim: \"dim_vec w = n\" \"dim_vec ?w = n\" by auto\n    have \"w = ?w\" \n    proof (rule eq_vecI; unfold dim)\n      fix i\n      assume i: \"i < n\"\n      show \"w $ i = ?w $ i\" unfolding lincomb_def \n      proof (subst finsum_index[OF i _ carr]) \n        show \"(\\<lambda>v. a v \\<cdot>\\<^sub>v v) \\<in> set ?b \\<rightarrow> carrier_vec n\" using carr by auto\n        {\n          fix x :: \"'a vec\" and j\n          assume \"x = unit_vec n j\" \"j \\<noteq> k\" \"j < n\"\n          hence \"(x,j) \\<in> set lookup\" unfolding lookup_def by auto\n          from map_of_is_SomeI[OF dist this]\n          have \"a x = w $ j - w $ k / v $ k * v $ j\" unfolding a_def using \\<open>j \\<noteq> k\\<close> by auto\n        } note a = this          \n        have \"(\\<Sum>x\\<in>set ?b. (a x \\<cdot>\\<^sub>v x) $ i) = (a v \\<cdot>\\<^sub>v v) $ i + (\\<Sum>x\\<in>(set ?b) - {v}. (a x \\<cdot>\\<^sub>v x) $ i)\"\n          by (rule sum.remove[OF finite_set], auto simp: b)\n        also have \"a v = w $ k / v $ k\" unfolding a_def lookup_def by auto\n        also have \"(\\<dots> \\<cdot>\\<^sub>v v) $ i = w $ k / v $ k * v $ i\" using i v by auto\n        finally have \"(\\<Sum>x\\<in>set ?b. (a x \\<cdot>\\<^sub>v x) $ i) = w $ k / v $ k * v $ i + (\\<Sum>x\\<in>(set ?b) - {v}. (a x \\<cdot>\\<^sub>v x) $ i)\" .\n        also have \"\\<dots> = w $ i\"\n        proof (cases \"i = k\")\n          case True\n          hence \"w $ k / v $ k * v $ i = w $ k\" using vk by auto\n          moreover have \"(\\<Sum>x\\<in>(set ?b) - {v}. (a x \\<cdot>\\<^sub>v x) $ i) = 0\" unfolding True\n          proof (rule sum.neutral, intro ballI)\n            fix x\n            assume \"x \\<in> set ?b - {v}\"\n            then obtain j where x: \"x = unit_vec n j\" \"j \\<noteq> k\" \"j < n\" using k unfolding b by auto\n            show \"(a x \\<cdot>\\<^sub>v x) $ k = 0\" unfolding a[OF x] unfolding x using x k by auto\n          qed\n          ultimately show ?thesis unfolding True by simp\n        next\n          case False\n          let ?ui = \"unit_vec n i :: 'a vec\"\n          {\n            assume \"?ui = v\"\n            from arg_cong[OF this, of \"\\<lambda> v. v $ k\"] vk i k False have False by auto\n          }\n          hence diff: \"?ui \\<noteq> v\" by auto\n          from a[OF refl False] have ai: \"(a ?ui \\<cdot>\\<^sub>v ?ui) $ i = w $ i - w $ k / v $ k * v $ i\" \n            using i by auto          \n          have \"?ui \\<in> set ?b\" unfolding b_all using False k i by auto\n          with diff have mem: \"unit_vec n i \\<in> set ?b - {v}\" by auto\n          have \"w $ k / v $ k * v $ i + (\\<Sum>x\\<in>(set ?b) - {v}. (a x \\<cdot>\\<^sub>v x) $ i)\n            = w $ i + (\\<Sum>x\\<in>(set ?b) - {v,?ui}. (a x \\<cdot>\\<^sub>v x) $ i)\"\n            by (subst sum.remove[OF _ mem], auto simp: ai intro!: sum.cong)\n          also have \"(\\<Sum>x\\<in>(set ?b) - {v,?ui}. (a x \\<cdot>\\<^sub>v x) $ i) = 0\"\n            by (rule sum.neutral, unfold b_all, insert i k, auto)\n          finally show ?thesis by simp\n        qed\n        finally show \"w $ i = (\\<Sum>x\\<in>set ?b. (a x \\<cdot>\\<^sub>v x) $ i)\" by simp\n      qed\n    qed auto\n    hence \"w \\<in> span (set ?b)\" unfolding span_def by auto\n  }\n  ultimately show span: \"span (set ?b) = carrier_vec n\" by blast\n  show \"basis (set ?b)\"\n  proof (rule dim_gen_is_basis[OF finite_set carr span])\n    have \"card (set ?b) = dim\" using dist len distinct_card unfolding dim_is_n by blast\n    thus \"card (set ?b) \\<le> dim\" by simp\n  qed\n  thus \"\\<not> lin_dep (set ?b)\" unfolding basis_def by auto\nqed\n\nlemma orthogonal_mat_of_cols:\n  assumes W: \"set ws \\<subseteq> carrier_vec n\"\n    and orth: \"corthogonal ws\"\n    and len: \"length ws = n\"\n  shows \"corthogonal_mat (mat_of_cols n ws)\" (is \"corthogonal_mat ?W\")\nproof\n    fix i j assume i: \"i < dim_col ?W\" and j: \"j < dim_col ?W\"\n    hence [simp]: \"ws ! i : carrier_vec n\" \"ws ! j : carrier_vec n\"\n      using W len by auto\n    have \"i < length ws\" and \"j < length ws\" using i j using len W by auto\n    thus \"col ?W i \\<bullet>c col ?W j = 0 \\<longleftrightarrow> i \\<noteq> j\"\n      using orth\n      unfolding corthogonal_def\n      by simp\nqed\n\nlemma corthogonal_col_ev_0: fixes A :: \"'a :: conjugatable_ordered_field mat\"\n  assumes A: \"A \\<in> carrier_mat n n\"\n  and v: \"v \\<in> carrier_vec n\"\n  and v0: \"v \\<noteq> 0\\<^sub>v n\"\n  and eigen[simp]: \"A *\\<^sub>v v = e \\<cdot>\\<^sub>v v\"\n  and n: \"n \\<noteq> 0\"\n  and hdws: \"hd ws = v\"\n  and ws: \"set ws \\<subseteq> carrier_vec n\" \"corthogonal ws\" \"length ws = n\"\n  defines \"W == mat_of_cols n ws\"\n  defines \"W' == corthogonal_inv W\"\n  defines \"A' == W' * A * W\"\n  shows \"col A' 0 = vec n (\\<lambda> i. if i = 0 then e else 0)\"\nproof -\n  let ?f = \"(\\<lambda> i. if i = 0 then e else 0)\"\n  from ws have W: \"W \\<in> carrier_mat n n\" unfolding W_def by auto\n  from W have W': \"W' \\<in> carrier_mat n n\" unfolding W'_def \n    corthogonal_inv_def mat_of_rows_def by auto\n  from A W W' have A': \"A' \\<in> carrier_mat n n\" unfolding A'_def by auto\n  show \"col A' 0 = vec n ?f\"\n  proof (rule,unfold dim_vec)\n    show dim: \"dim_vec (col A' 0) = n\" using A' by simp\n    have row0: \"vec_inv v \\<bullet> (A *\\<^sub>v v) = e\"\n      using scalar_prod_smult_distrib[OF vec_inv_closed[OF v] v]\n      using vec_inv[OF v v0] by auto\n    fix i assume i: \"i < n\"\n    hence i2: \"i < length ws\" using ws by auto\n    let ?wsi = \"ws ! i\"\n    have z: \"0 < dim_col A'\" using A' n by auto\n    hence z2: \"0 < length ws\" using A' ws by auto\n    have wsi[simp]: \"ws!i : carrier_vec n\" using ws i by auto\n    hence ws0[simp]: \"ws!0 = v\" using hd_conv_nth[symmetric] hdws z2 by auto\n    have \"col A' 0 $ i = A' $$ (i, 0)\" using A' i by auto\n    also have \"... = (W' * (A * W)) $$ (i, 0)\" unfolding A'_def using W' A W by auto\n    also have \"... = row W' i \\<bullet> col (A * W) 0\"\n      apply (subst index_mult_mat) using W W' A i by auto\n    also have \"row W' i = vec_inv ?wsi\"\n      unfolding W'_def W_def unfolding corthogonal_inv_def using i ws by auto\n    also have \"col (A * W) 0 = A *\\<^sub>v col W 0\" using A W z A' by auto\n    also have \"col W 0 = v\" unfolding W_def using z2 ws0 n col_mat_of_cols v by blast\n    also have \"A *\\<^sub>v v = e \\<cdot>\\<^sub>v v\" using eigen.\n    also have \"vec_inv ?wsi \\<bullet> (e \\<cdot>\\<^sub>v v) = e * (vec_inv ?wsi \\<bullet> v)\"\n      using scalar_prod_smult_distrib[OF vec_inv_closed[OF wsi] v].\n    also have \"... = ?f i\"\n    proof(cases \"i = 0\")\n      case True thus ?thesis using vec_inv[OF v v0] by simp\n    next \n      case False\n      hence z: \"0 < length ws\" using i ws by auto\n      note cwsi = carrier_vec_conjugate[OF wsi]\n      have \"vec_inv ?wsi \\<bullet> v = 1 / (?wsi \\<bullet>c ?wsi) * (conjugate ?wsi \\<bullet> v)\"\n        unfolding vec_inv_def unfolding smult_scalar_prod_distrib[OF cwsi v].. \n      also have \"conjugate ?wsi \\<bullet> v = v \\<bullet>c ?wsi\"\n        using comm_scalar_prod[OF cwsi v].\n      also have \"... = 0\"\n        using corthogonalD[OF ws(2) z i2] False unfolding ws0 by auto\n      finally show ?thesis using False by auto\n    qed\n    also have \"... = vec n ?f $ i\" using i by simp\n    finally show \"col A' 0 $ i = vec n ?f $ i\" .\n  qed\nqed\n\n\ntext \"Schur decomposition\"\nfun schur_decomposition :: \"'a::conjugatable_field mat \\<Rightarrow> 'a list \\<Rightarrow> 'a mat \\<times> 'a mat \\<times> 'a mat\" where \n  \"schur_decomposition A [] = (A, 1\\<^sub>m (dim_row A), 1\\<^sub>m (dim_row A))\"\n| \"schur_decomposition A (e # es) = (let\n       n = dim_row A;\n       n1 = n - 1;\n       v = find_eigenvector A e;\n       ws = gram_schmidt n (basis_completion v);\n       W = mat_of_cols n ws;\n       W' = corthogonal_inv W;\n       A' = W' * A * W;\n       (A1,A2,A0,A3) = split_block A' 1 1;\n       (B,P,Q) = schur_decomposition A3 es;\n       z_row = (0\\<^sub>m 1 n1);\n       z_col = (0\\<^sub>m n1 1);\n       one_1 = 1\\<^sub>m 1\n     in (four_block_mat A1 (A2 * P) A0 B, \n     W * four_block_mat one_1 z_row z_col P, \n     four_block_mat one_1 z_row z_col Q * W'))\"\n\n\ntheorem schur_decomposition:\n  assumes A: \"(A::'a::conjugatable_ordered_field mat) \\<in> carrier_mat n n\"\n      and c: \"char_poly A = (\\<Prod> (e :: 'a) \\<leftarrow> es. [:- e, 1:])\"\n      and B: \"schur_decomposition A es = (B,P,Q)\"\n  shows \"similar_mat_wit A B P Q \\<and> upper_triangular B \\<and> diag_mat B = es\"\n  using assms\nproof (induct es arbitrary: n A B P Q)\n  case Nil\n  with degree_monic_char_poly[of A n]\n  show ?case by (auto intro: similar_mat_wit_refl simp: diag_mat_def)\nnext\n  case (Cons e es n A C P Q)\n  let ?n1 = \"n - 1\"\n  from Cons have A: \"A \\<in> carrier_mat n n\" and dim: \"dim_row A = n\" by auto\n  let ?cp = \"char_poly A\"\n  from Cons(3)\n  have cp: \"?cp = [: -e, 1 :] * (\\<Prod>e \\<leftarrow> es. [:- e, 1:])\" by auto\n  have mon: \"monic (\\<Prod>e\\<leftarrow> es. [:- e, 1:])\" by (rule monic_prod_list, auto)\n  have deg: \"degree ?cp = Suc (degree (\\<Prod>e\\<leftarrow> es. [:- e, 1:]))\" unfolding cp\n    by (subst degree_mult_eq, insert mon, auto)\n  with degree_monic_char_poly[OF A] have n: \"n \\<noteq> 0\" by auto\n  define v where \"v = find_eigenvector A e\"\n  define b where \"b = basis_completion v\"\n  define ws where \"ws = gram_schmidt n b\"\n  define W where \"W = mat_of_cols n ws\"\n  define W' where \"W' = corthogonal_inv W\"\n  define A' where \"A' = W' * A * W\"\n  obtain A1 A2 A0 A3 where splitA': \"split_block A' 1 1 = (A1,A2,A0,A3)\"\n    by (cases \"split_block A' 1 1\", auto)\n  obtain B P' Q' where schur: \"schur_decomposition A3 es = (B,P',Q')\" \n    by (cases \"schur_decomposition A3 es\", auto)\n  let ?P' = \"four_block_mat (1\\<^sub>m 1) (0\\<^sub>m 1 ?n1) (0\\<^sub>m ?n1 1) P'\"\n  let ?Q' = \"four_block_mat (1\\<^sub>m 1) (0\\<^sub>m 1 ?n1) (0\\<^sub>m ?n1 1) Q'\"\n  have C: \"C = four_block_mat A1 (A2 * P') A0 B\" and P: \"P = W * ?P'\" and Q: \"Q = ?Q' * W'\"\n    using Cons(4) unfolding schur_decomposition.simps\n    Let_def list.sel dim\n    v_def[symmetric] b_def[symmetric] ws_def[symmetric] W'_def[symmetric] W_def[symmetric]\n    A'_def[symmetric] split splitA' schur by auto\n  have e: \"eigenvalue A e\" \n    unfolding eigenvalue_root_char_poly[OF A] cp by simp\n  from find_eigenvector[OF A e] have ev: \"eigenvector A v e\" unfolding v_def .\n  from this[unfolded eigenvector_def]\n  have v[simp]: \"v \\<in> carrier_vec n\" and v0: \"v \\<noteq> 0\\<^sub>v n\" using A by auto\n  interpret cof_vec_space n \"TYPE('a)\" .\n  from basis_completion[OF v v0, folded b_def]\n  have span_b: \"span (set b) = carrier_vec n\" and dist_b: \"distinct b\" \n    and indep: \"\\<not> lin_dep (set b)\" and b: \"set b \\<subseteq> carrier_vec n\" and hdb: \"hd b = v\" \n    and len_b: \"length b = n\" by auto\n  from hdb len_b n obtain vs where bv: \"b = v # vs\" by (cases b, auto)\n  from gram_schmidt_result[OF b dist_b indep refl, folded ws_def]\n  have ws: \"set ws \\<subseteq> carrier_vec n\" \"corthogonal ws\" \"length ws = n\" \n    by (auto simp: len_b)\n  from gram_schmidt_hd[OF v, of vs, folded bv] have hdws: \"hd ws = v\" unfolding ws_def .\n  have orth_W: \"corthogonal_mat W\" using orthogonal_mat_of_cols ws unfolding W_def.\n  have W: \"W \\<in> carrier_mat n n\"\n    using ws unfolding W_def using mat_of_cols_carrier(1)[of n ws] by auto\n  have W': \"W' \\<in> carrier_mat n n\" unfolding W'_def corthogonal_inv_def using W \n    by (auto simp: mat_of_rows_def)  \n  from corthogonal_inv_result[OF orth_W] \n  have W'W: \"inverts_mat W' W\" unfolding W'_def .\n  hence WW': \"inverts_mat W W'\" using mat_mult_left_right_inverse[OF W' W] W' W\n    unfolding inverts_mat_def by auto\n  have A': \"A' \\<in> carrier_mat n n\" using W W' A unfolding A'_def by auto\n  have A'A_wit: \"similar_mat_wit A' A W' W\"\n    by (rule similar_mat_witI[of _ _ n], insert W W' A A' W'W WW', auto simp: A'_def\n    inverts_mat_def)\n  hence A'A: \"similar_mat A' A\" unfolding similar_mat_def by blast\n  from similar_mat_wit_sym[OF A'A_wit] have simAA': \"similar_mat_wit A A' W W'\" by auto\n  have eigen[simp]: \"A *\\<^sub>v v = e \\<cdot>\\<^sub>v v\" and v0: \"v \\<noteq> 0\\<^sub>v n\"\n    using v_def find_eigenvector[OF A e] A\n    unfolding eigenvector_def by auto\n  let ?f = \"(\\<lambda> i. if i = 0 then e else 0)\"\n  have col0: \"col A' 0 = vec n ?f\"\n    unfolding A'_def W'_def W_def\n    using corthogonal_col_ev_0[OF A v v0 eigen n hdws ws].\n  from A' n have \"dim_row A' = 1 + ?n1\" \"dim_col A' = 1 + ?n1\" by auto\n  from split_block[OF splitA' this] have A2: \"A2 \\<in> carrier_mat 1 ?n1\"\n    and A3: \"A3 \\<in> carrier_mat ?n1 ?n1\" \n    and A'block: \"A' = four_block_mat A1 A2 A0 A3\" by auto\n  have A1id: \"A1 = mat 1 1 (\\<lambda> _. e)\"\n    using splitA'[unfolded split_block_def Let_def] arg_cong[OF col0, of \"\\<lambda> v. v $ 0\"] A' n\n    by (auto simp: col_def)\n  have A1: \"A1 \\<in> carrier_mat 1 1\" unfolding A1id by auto\n  {\n    fix i\n    assume \"i < ?n1\"\n    with arg_cong[OF col0, of \"\\<lambda> v. v $ Suc i\"] A'\n    have \"A' $$ (Suc i, 0) = 0\" by auto\n  } note A'0 = this\n  have A0id: \"A0 = 0\\<^sub>m ?n1 1\"\n    using splitA'[unfolded split_block_def Let_def] A'0 A' by auto\n  have A0: \"A0 \\<in> carrier_mat ?n1 1\" unfolding A0id by auto\n  from cp char_poly_similar[OF A'A]\n  have cp: \"char_poly A' = [: -e,1 :] * (\\<Prod> e \\<leftarrow> es. [:- e, 1:])\" by simp\n  also have \"char_poly A' = char_poly A1 * char_poly A3\" \n    unfolding A'block A0id\n    by (rule char_poly_four_block_zeros_col[OF A1 A2 A3])\n  also have \"char_poly A1 = [: -e,1 :]\"\n    by (simp add: A1id char_poly_defs det_def signof_def sign_def)\n  finally have cp: \"char_poly A3 = (\\<Prod> e \\<leftarrow> es. [:- e, 1:])\"\n    by (metis mult_cancel_left pCons_eq_0_iff zero_neq_one)\n  from Cons(1)[OF A3 cp schur]\n  have simIH: \"similar_mat_wit A3 B P' Q'\" and ut: \"upper_triangular B\" and diag: \"diag_mat B = es\" by auto\n  from similar_mat_witD2[OF A3 simIH] \n  have B: \"B \\<in> carrier_mat ?n1 ?n1\" and P': \"P' \\<in> carrier_mat ?n1 ?n1\" and Q': \"Q' \\<in> carrier_mat ?n1 ?n1\" \n    and PQ': \"P' * Q' = 1\\<^sub>m ?n1\" by auto\n  have A0_eq: \"A0 = P' * A0 * 1\\<^sub>m 1\" unfolding A0id using P' by auto\n  have simA'C: \"similar_mat_wit A' C ?P' ?Q'\" unfolding A'block C\n    by (rule similar_mat_wit_four_block[OF similar_mat_wit_refl[OF A1] simIH _ A0_eq A1 A3 A0],\n    insert PQ' A2 P' Q', auto)\n  have ut1: \"upper_triangular A1\" unfolding A1id by auto\n  have ut: \"upper_triangular C\" unfolding C A0id\n    by (intro upper_triangular_four_block[OF _ B ut1 ut], auto simp: A1id)\n  from A1id have diagA1: \"diag_mat A1 = [e]\" unfolding diag_mat_def by auto\n  from diag_four_block_mat[OF A1 B] have diag: \"diag_mat C = e # es\" unfolding diag diagA1 C by simp\n  from ut similar_mat_wit_trans[OF simAA' simA'C, folded P Q] diag\n  show ?case by blast\nqed\n\ndefinition schur_upper_triangular :: \"'a::conjugatable_field mat \\<Rightarrow> 'a list \\<Rightarrow> 'a mat\" where \n  \"schur_upper_triangular A es = (case schur_decomposition A es of (B,_,_) \\<Rightarrow> B)\"\n\n\nlemma schur_upper_triangular:\n  assumes A: \"(A :: 'a :: conjugatable_ordered_field mat) \\<in> carrier_mat n n\"\n  and linear: \"char_poly A = (\\<Prod> a \\<leftarrow> es. [:- a, 1:])\"\n  defines B: \"B \\<equiv> schur_upper_triangular A es\"\n  shows \"B \\<in> carrier_mat n n\" \"upper_triangular B\" \"similar_mat A B\" \nproof -\n  let ?B = \"schur_upper_triangular A es\"\n  obtain C P Q where schur: \"schur_decomposition A es = (C,P,Q)\" \n    by (cases \"schur_decomposition A es\", auto)\n  hence B: \"B = C\" using A unfolding schur_upper_triangular_def B by auto\n  from schur_decomposition[OF A linear schur]\n  have sim: \"similar_mat_wit A B P Q\" and B: \"upper_triangular B\" unfolding B by auto\n  from sim show \"similar_mat A B\" unfolding similar_mat_def by auto\n  from similar_mat_witD2[OF A sim] show \"B \\<in> carrier_mat n n\" by auto\n  show \"upper_triangular B\" by fact\nqed\n\nlemma schur_decomposition_exists: assumes A: \"A \\<in> carrier_mat n n\"\n  and linear: \"char_poly A = (\\<Prod> (a :: 'a :: conjugatable_ordered_field) \\<leftarrow> es. [:- a, 1:])\"\n  shows \"\\<exists> B \\<in> carrier_mat n n. upper_triangular B \\<and> similar_mat A B\" \n  using schur_upper_triangular[OF A linear] by blast\n\nlemma char_poly_0_block: fixes A :: \"'a :: conjugatable_ordered_field mat\"\n  assumes A: \"A = four_block_mat B C (0\\<^sub>m m n) D\"\n  and linearB: \"\\<exists> es. char_poly B = (\\<Prod> a \\<leftarrow> es. [:- a, 1:])\"\n  and linearD: \"\\<exists> es. char_poly D = (\\<Prod> a \\<leftarrow> es. [:- a, 1:])\"\n  and B: \"B \\<in> carrier_mat n n\"\n  and C: \"C \\<in> carrier_mat n m\"\n  and D: \"D \\<in> carrier_mat m m\"\n  shows \"char_poly A = char_poly B * char_poly D\"\nproof -\n  from linearB obtain bs where cB: \"char_poly B = (\\<Prod>a\\<leftarrow>bs. [:- a, 1:])\" by auto\n  from linearD obtain ds where cD: \"char_poly D = (\\<Prod>a\\<leftarrow>ds. [:- a, 1:])\" by auto\n  from schur_decomposition_exists[OF B cB] \n  obtain B' PB QB where sB: \"schur_decomposition B bs = (B',PB,QB)\" \n    by (cases \"schur_decomposition B bs\", auto)\n  obtain D' PD QD where sD: \"schur_decomposition D ds = (D',PD,QD)\" \n    by (cases \"schur_decomposition D ds\", auto)\n  from schur_decomposition[OF B cB sB] similar_mat_witD2[OF B, of B'] have \n    simB: \"similar_mat B B'\" and utB: \"upper_triangular B'\" and diagB: \"diag_mat B' = bs\"\n    and B': \"B' \\<in> carrier_mat n n\"\n    by (auto simp: similar_mat_def)\n  from schur_decomposition[OF D cD sD] similar_mat_witD2[OF D, of D'] have \n    simD: \"similar_mat D D'\" and utD: \"upper_triangular D'\" and diagD: \"diag_mat D' = ds\"\n    and D': \"D' \\<in> carrier_mat m m\"\n    by (auto simp: similar_mat_def)\n  let ?z = \"0\\<^sub>m m n\"\n  from similar_mat_four_block_0_ex[OF simB simD C B D, folded A]\n    obtain B0 where B0: \"B0 \\<in> carrier_mat n m\" and sim: \"similar_mat A (four_block_mat B' B0 ?z D')\" \n    by auto\n  let ?block = \"four_block_mat B' B0 ?z D'\"\n  let ?cp = char_poly\n  let ?prod = \"QB * C * PD\"\n  let ?diag = \"\\<lambda> A. (\\<Prod>a\\<leftarrow>diag_mat A. [:- a, 1:])\"\n  from char_poly_similar[OF sim] have \"?cp A = ?cp ?block\" by simp\n  also have \"\\<dots> = ?diag ?block\"\n    by (rule char_poly_upper_triangular[OF four_block_carrier_mat[OF B' D'] upper_triangular_four_block[OF B' D' utB utD]])      \n  also have \"\\<dots> = ?diag B' * ?diag D'\" unfolding diag_four_block_mat[OF B' D']\n    by auto\n  also have \"?diag B' = ?cp B'\"\n    by (subst char_poly_upper_triangular[OF B' utB], simp)\n  also have \"\\<dots> = ?cp B\"\n    by (rule char_poly_similar[OF similar_mat_sym[OF simB]])\n  also have \"?diag D' = ?cp D'\"\n    by (subst char_poly_upper_triangular[OF D' utD], simp)\n  also have \"\\<dots> = ?cp D\"\n    by (rule char_poly_similar[OF similar_mat_sym[OF simD]])\n  finally show ?thesis .\nqed\n\n\nlemma char_poly_0_block': fixes A :: \"'a :: conjugatable_ordered_field mat\"\n  assumes A: \"A = four_block_mat B (0\\<^sub>m n m) C D\"\n  and linearB: \"\\<exists> es. char_poly B = (\\<Prod> a \\<leftarrow> es. [:- a, 1:])\"\n  and linearD: \"\\<exists> es. char_poly D = (\\<Prod> a \\<leftarrow> es. [:- a, 1:])\"\n  and B: \"B \\<in> carrier_mat n n\"\n  and C: \"C \\<in> carrier_mat m n\"\n  and D: \"D \\<in> carrier_mat m m\"\n  shows \"char_poly A = char_poly B * char_poly D\"\nproof -\n  let ?A = \"four_block_mat B (0\\<^sub>m n m) C D\"\n  let ?B = \"transpose_mat B\"\n  let ?D = \"transpose_mat D\"\n  have AC: \"?A \\<in> carrier_mat (n + m) (n + m)\" using B D by auto\n  from arg_cong[OF transpose_four_block_mat[OF B zero_carrier_mat C D], of char_poly,\n    unfolded char_poly_transpose_mat[OF AC], folded A]\n  have \"char_poly A =\n    char_poly (four_block_mat ?B (transpose_mat C) (0\\<^sub>m m n) ?D)\" by auto\n  also have \"\\<dots> = char_poly ?B * char_poly ?D\"\n    by (rule char_poly_0_block[OF refl], insert B C D linearB linearD, auto)\n  also have \"\\<dots> = char_poly B * char_poly D\" using B D\n    by simp\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/Evaluation/Jordan_Normal_Form/Schur_Decomposition.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8740772417253256, "lm_q2_score": 0.8479677526147223, "lm_q1q2_score": 0.7411893142774998}}
{"text": "theory BoolosATP imports Main\nbegin\n\ntypedecl i\nconsts \n e :: \"i\"  (* one *) \n s :: \"i\\<Rightarrow>i\"  (* successor function *)\n F :: \"i\\<Rightarrow>i\\<Rightarrow>i\"  (* binary function; axiomatised below as Ackermann function *)\n D :: \"i\\<Rightarrow>bool\"  (* arbitrary uninterpreted unary predicate *)\n\naxiomatization where \n    A1: \"\\<forall>n. F n e = s e\"  (* Axiom for Ackermann function F *)\nand A2: \"\\<forall>y. F e (s y) = s (s (F e y))\"  (* Axiom for Ackermann function F *)\nand A3: \"\\<forall>x y. F (s x) (s y) = F x (F (s x) y)\"  (* Axiom for Ackermann function F *)\nand A4: \"D e\"  (* D holds for one *)\nand A5: \"\\<forall>x. D x \\<longrightarrow> D (s x)\" (* if D holds for x it also holds for the successor of x *)\n\nlemma \"D (F (s (s (s (s e)))) (s (s (s (s e)))))\" sledgehammer oops (* no proof; hopeless! *)\n\ndefinition isIndSet where \"isIndSet X \\<equiv> (X e) \\<and> (\\<forall>x. X x \\<longrightarrow> X (s x))\"  (* X is inductive *)\ndefinition N where \"N x \\<equiv> (\\<forall>X::i\\<Rightarrow>bool. isIndSet X \\<longrightarrow> X x)\"   (* N is smallest inductive set *)\ndefinition P where \"P x y \\<equiv> N (F x y)\"   (* P(x,y) iff F(x,y) is in N *)\n\nlemma \"D (F (s (s (s (s e)))) (s (s (s (s e)))))\"  (* ATPs can now proof this: using the Defs *)\n  sledgehammer  (* proof found *)\n  by (metis A1 A2 A3 A4 A5 N_def P_def isIndSet_def)  (* proof reconstruction succeeds *)\nend \n", "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/BoolosATP.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625107731765, "lm_q2_score": 0.7956581049086031, "lm_q1q2_score": 0.741125696115195}}
{"text": "(*  Title:      Isomorphism Classes of Groups\n    Author:     Jakob von Raumer, Karlsruhe Institute of Technology\n    Maintainer: Jakob von Raumer <jakob.raumer@student.kit.edu>\n*)\n\ntheory GroupIsoClasses\nimports\n  \"Groups\"\n  \"List\"\n  \"Coset\"\nbegin\n\nsection {* Isomorphism Classes of Groups *}\n\ntext {* We construct a quotient type for isomorphism classes of groups. *}\n\ntypedef 'a group = \"{G :: 'a monoid. group G}\"\nproof\n  show \"\\<And>a. \\<lparr>carrier = {a}, mult = (\\<lambda>x y. x), one = a\\<rparr> \\<in> {G. group G}\"\n  unfolding group_def group_axioms_def monoid_def Units_def by auto\nqed\n\ndefinition group_iso_rel :: \"'a group \\<Rightarrow> 'a group \\<Rightarrow> bool\"\n  where \"group_iso_rel G H = (\\<exists>\\<phi>. \\<phi> \\<in> Rep_group G \\<cong> Rep_group H)\"\n\nquotient_type 'a group_iso_class = \"'a group\" / group_iso_rel\n  morphisms Rep_group_iso Abs_group_iso\nproof (rule equivpI)\n  show \"reflp group_iso_rel\"\n  proof (rule reflpI)\n    fix G :: \"'b group\"\n    show \"group_iso_rel G G\"\n    unfolding group_iso_rel_def using Rep_group iso_refl by auto\n  qed\nnext\n  show \"symp group_iso_rel\"\n  proof (rule sympI)\n    fix G H :: \"'b group\"\n    assume \"group_iso_rel G H\"\n    then obtain \\<phi> where \"\\<phi> \\<in> Rep_group G \\<cong> Rep_group H\" unfolding group_iso_rel_def by auto\n    then obtain \\<phi>' where \"\\<phi>' \\<in> Rep_group H \\<cong> Rep_group G\" using group.iso_sym Rep_group by fastforce\n    thus \"group_iso_rel H G\" unfolding group_iso_rel_def by auto\n  qed\nnext\n  show \"transp group_iso_rel\" \n  proof (rule transpI)\n    fix G H I :: \"'b group\"\n    assume \"group_iso_rel G H\" \"group_iso_rel H I\"\n    then obtain \\<phi> \\<psi> where \"\\<phi> \\<in> Rep_group G \\<cong> Rep_group H\" \"\\<psi> \\<in> Rep_group H \\<cong> Rep_group I\" unfolding group_iso_rel_def by auto\n    then obtain \\<pi> where \"\\<pi> \\<in> Rep_group G \\<cong> Rep_group I\" using group.iso_trans Rep_group by fastforce\n    thus \"group_iso_rel G I\" unfolding group_iso_rel_def by auto\n  qed\nqed\n\ntext {* This assigns to a given group the group isomorphism class *}\n\ndefinition (in group) iso_class :: \"'a group_iso_class\"\n  where \"iso_class = Abs_group_iso (Abs_group (monoid.truncate G))\"\n\ntext {* Two isomorphic groups do indeed have the same isomorphism class: *}\n\nlemma iso_classes_iff:\n  assumes \"group G\"\n  assumes \"group H\"\n  shows \"(\\<exists>\\<phi>. \\<phi> \\<in> G \\<cong> H) = (group.iso_class G = group.iso_class H)\"\nproof -\n  from assms(1,2) have groups:\"group (monoid.truncate G)\" \"group (monoid.truncate H)\"\n    unfolding monoid.truncate_def group_def group_axioms_def Units_def monoid_def by auto\n  have \"(\\<exists>\\<phi>. \\<phi> \\<in> G \\<cong> H) = (\\<exists>\\<phi>. \\<phi> \\<in> (monoid.truncate G) \\<cong> (monoid.truncate H))\"\n    unfolding iso_def hom_def monoid.truncate_def by auto\n  also have \"\\<dots> = group_iso_rel (Abs_group (monoid.truncate G)) (Abs_group (monoid.truncate H))\"\n    unfolding group_iso_rel_def using groups group.Abs_group_inverse by (metis mem_Collect_eq)\n  also have \"\\<dots> = (group.iso_class G = group.iso_class H)\" using group.iso_class_def assms group_iso_class.abs_eq_iff by metis\n  finally show ?thesis.\nqed\n\nend\n", "meta": {"author": "javra", "repo": "isabelle_algebra", "sha": "922a6962b451ef543ca18feaecae92ece373d535", "save_path": "github-repos/isabelle/javra-isabelle_algebra", "path": "github-repos/isabelle/javra-isabelle_algebra/isabelle_algebra-922a6962b451ef543ca18feaecae92ece373d535/Jordan_Holder/GroupIsoClasses.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278788223265, "lm_q2_score": 0.839733963661418, "lm_q1q2_score": 0.7410046603288096}}
{"text": "(*\n    Author:   Benedikt Seidl\n    Author:   Salomon Sickert\n    License:  BSD\n*)\n\nsection \\<open>Disjunctive Normal Form of LTL formulas\\<close>\n\ntheory Disjunctive_Normal_Form\nimports\n  LTL Equivalence_Relations \"HOL-Library.FSet\" \"Eval_Base.Eval_Base\"\nbegin\n\ntext \\<open>\n  We use the propositional representation of LTL formulas to define\n  the minimal disjunctive normal form of our formulas. For this purpose\n  we define the minimal product \\<open>\\<otimes>\\<^sub>m\\<close> and union \\<open>\\<union>\\<^sub>m\\<close>.\n  In the end we show that for a set \\<open>\\<A>\\<close> of literals,\n  @{term \"\\<A> \\<Turnstile>\\<^sub>P \\<phi>\"} if, and only if, there exists a subset\n  of \\<open>\\<A>\\<close> in the minimal DNF of \\<open>\\<phi>\\<close>.\n\\<close>\n\nsubsection \\<open>Definition of Minimum Sets\\<close>\n\ndefinition (in ord) min_set :: \"'a set \\<Rightarrow> 'a set\" where\n  \"min_set X = {y \\<in> X. \\<forall>x \\<in> X. x \\<le> y \\<longrightarrow> x = y}\"\n\nlemma min_set_iff:\n  \"x \\<in> min_set X \\<longleftrightarrow> x \\<in> X \\<and> (\\<forall>y \\<in> X. y \\<le> x \\<longrightarrow> y = x)\"\n  unfolding min_set_def by blast\n\nlemma min_set_subset:\n  \"min_set X \\<subseteq> X\"\n  by (auto simp: min_set_def)\n\nlemma min_set_idem[simp]:\n  \"min_set (min_set X) = min_set X\"\n  by (auto simp: min_set_def)\n\nlemma min_set_empty[simp]:\n  \"min_set {} = {}\"\n  using min_set_subset by blast\n\nlemma min_set_singleton[simp]:\n  \"min_set {x} = {x}\"\n  by (auto simp: min_set_def)\n\n\n\nlemma min_set_obtains_helper:\n  \"A \\<in> B \\<Longrightarrow> \\<exists>C. C |\\<subseteq>| A \\<and> C \\<in> min_set B\"\nproof2 (induction \"fcard A\" arbitrary: A rule: less_induct)\n  case less\n\n  then have \"(\\<forall>A'. A' \\<notin> B \\<or> \\<not> A' |\\<subseteq>| A \\<or> A' = A) \\<or> (\\<exists>A'. A' |\\<subseteq>| A \\<and> A' \\<in> min_set B)\"\n    by (metis (no_types) dual_order.trans order.not_eq_order_implies_strict pfsubset_fcard_mono)\n\n  then show ?case\n    using less.prems min_set_def by auto\nqed\n\nlemma min_set_obtains:\n  assumes \"A \\<in> B\"\n  obtains C where \"C |\\<subseteq>| A\" and \"C \\<in> min_set B\"\n  using min_set_obtains_helper assms by metis\n\n\n\nsubsection \\<open>Minimal operators on sets\\<close>\n\ndefinition product :: \"'a fset set \\<Rightarrow> 'a fset set \\<Rightarrow> 'a fset set\" (infixr \"\\<otimes>\" 65)\n  where \"A \\<otimes> B = {a |\\<union>| b | a b. a \\<in> A \\<and> b \\<in> B}\"\n\ndefinition min_product :: \"'a fset set \\<Rightarrow> 'a fset set \\<Rightarrow> 'a fset set\" (infixr \"\\<otimes>\\<^sub>m\" 65)\n  where \"A \\<otimes>\\<^sub>m B = min_set (A \\<otimes> B)\"\n\ndefinition min_union :: \"'a fset set \\<Rightarrow> 'a fset set \\<Rightarrow> 'a fset set\" (infixr \"\\<union>\\<^sub>m\" 65)\n  where \"A \\<union>\\<^sub>m B = min_set (A \\<union> B)\"\n\ndefinition product_set :: \"'a fset set set \\<Rightarrow> 'a fset set\" (\"\\<Otimes>\")\n  where \"\\<Otimes> X = Finite_Set.fold product {{||}} X\"\n\ndefinition min_product_set :: \"'a fset set set \\<Rightarrow> 'a fset set\" (\"\\<Otimes>\\<^sub>m\")\n  where \"\\<Otimes>\\<^sub>m X = Finite_Set.fold min_product {{||}} X\"\n\n\nlemma min_product_idem[simp]:\n  \"A \\<otimes>\\<^sub>m A = min_set A\"\n  by (auto simp: min_product_def product_def min_set_def) fastforce\n\nlemma min_union_idem[simp]:\n  \"A \\<union>\\<^sub>m A = min_set A\"\n  by (simp add: min_union_def)\n\n\nlemma product_empty[simp]:\n  \"A \\<otimes> {} = {}\"\n  \"{} \\<otimes> A = {}\"\n  by (simp_all add: product_def)\n\nlemma min_product_empty[simp]:\n  \"A \\<otimes>\\<^sub>m {} = {}\"\n  \"{} \\<otimes>\\<^sub>m A = {}\"\n  by (simp_all add: min_product_def)\n\nlemma min_union_empty[simp]:\n  \"A \\<union>\\<^sub>m {} = min_set A\"\n  \"{} \\<union>\\<^sub>m A = min_set A\"\n  by (simp_all add: min_union_def)\n\nlemma product_empty_singleton[simp]:\n  \"A \\<otimes> {{||}} = A\"\n  \"{{||}} \\<otimes> A = A\"\n  by (simp_all add: product_def)\n\nlemma min_product_empty_singleton[simp]:\n  \"A \\<otimes>\\<^sub>m {{||}} = min_set A\"\n  \"{{||}} \\<otimes>\\<^sub>m A = min_set A\"\n  by (simp_all add: min_product_def)\n\nlemma product_singleton_singleton:\n  \"A \\<otimes> {{|x|}} = finsert x ` A\"\n  \"{{|x|}} \\<otimes> A = finsert x ` A\"\n  unfolding product_def by blast+\n\nlemma product_mono:\n  \"A \\<subseteq> B \\<Longrightarrow> A \\<otimes> C \\<subseteq> B \\<otimes> C\"\n  \"B \\<subseteq> C \\<Longrightarrow> A \\<otimes> B \\<subseteq> A \\<otimes> C\"\n  unfolding product_def by auto\n\n\n\nlemma product_finite:\n  \"finite A \\<Longrightarrow> finite B \\<Longrightarrow> finite (A \\<otimes> B)\"\n  by (simp add: product_def finite_image_set2)\n\nlemma min_product_finite:\n  \"finite A \\<Longrightarrow> finite B \\<Longrightarrow> finite (A \\<otimes>\\<^sub>m B)\"\n  by (metis min_product_def product_finite min_set_finite)\n\nlemma min_union_finite:\n  \"finite A \\<Longrightarrow> finite B \\<Longrightarrow> finite (A \\<union>\\<^sub>m B)\"\n  by (simp add: min_union_def min_set_finite)\n\n\nlemma product_set_infinite[simp]:\n  \"infinite X \\<Longrightarrow> \\<Otimes> X = {{||}}\"\n  by (simp add: product_set_def)\n\nlemma min_product_set_infinite[simp]:\n  \"infinite X \\<Longrightarrow> \\<Otimes>\\<^sub>m X = {{||}}\"\n  by (simp add: min_product_set_def)\n\n\nlemma product_comm:\n  \"A \\<otimes> B = B \\<otimes> A\"\n  unfolding product_def by blast\n\n\n\nlemma min_union_comm:\n  \"A \\<union>\\<^sub>m B = B \\<union>\\<^sub>m A\"\n  unfolding min_union_def\n  by (simp add: sup.commute)\n\n\nlemma product_iff:\n  \"x \\<in> A \\<otimes> B \\<longleftrightarrow> (\\<exists>a \\<in> A. \\<exists>b \\<in> B. x = a |\\<union>| b)\"\n  unfolding product_def by blast\n\nlemma min_product_iff:\n  \"x \\<in> A \\<otimes>\\<^sub>m B \\<longleftrightarrow> (\\<exists>a \\<in> A. \\<exists>b \\<in> B. x = a |\\<union>| b) \\<and> (\\<forall>a \\<in> A. \\<forall>b \\<in> B. a |\\<union>| b |\\<subseteq>| x \\<longrightarrow> a |\\<union>| b = x)\"\n  unfolding min_product_def min_set_iff product_iff product_def by blast\n\nlemma min_union_iff:\n  \"x \\<in> A \\<union>\\<^sub>m B \\<longleftrightarrow> x \\<in> A \\<union> B \\<and> (\\<forall>a \\<in> A. a |\\<subseteq>| x \\<longrightarrow> a = x) \\<and> (\\<forall>b \\<in> B. b |\\<subseteq>| x \\<longrightarrow> b = x)\"\n  unfolding min_union_def min_set_iff by blast\n\n\n\n\n  then obtain a b where \"a \\<in> min_set A\" and \"b \\<in> B\" and \"x = a |\\<union>| b\" and 1: \"\\<forall>a \\<in> min_set A. \\<forall>b \\<in> B. a |\\<union>| b |\\<subseteq>| x \\<longrightarrow> a |\\<union>| b = x\"\n    unfolding min_product_iff by blast\n\n  moreover\n\n  {\n    fix a' b'\n    assume \"a' \\<in> A\" and \"b' \\<in> B\" and \"a' |\\<union>| b' |\\<subseteq>| x\"\n\n    then obtain a'' where \"a'' |\\<subseteq>| a'\" and \"a'' \\<in> min_set A\"\n      using min_set_obtains by metis\n\n    then have \"a'' |\\<union>| b' = x\"\n      by (metis (full_types) 1 \\<open>b' \\<in> B\\<close> \\<open>a' |\\<union>| b' |\\<subseteq>| x\\<close> dual_order.trans le_sup_iff)\n\n    then have \"a' |\\<union>| b' = x\"\n      using \\<open>a' |\\<union>| b' |\\<subseteq>| x\\<close> \\<open>a'' |\\<subseteq>| a'\\<close> by blast\n  }\n\n  ultimately show \"x \\<in> A \\<otimes>\\<^sub>m B\"\n    by (metis min_product_iff min_set_iff)\nnext\n  fix x\n  assume \"x \\<in> A \\<otimes>\\<^sub>m B\"\n\n  then have 1: \"x \\<in> A \\<otimes> B\" and \"\\<forall>y \\<in> A \\<otimes> B. y |\\<subseteq>| x \\<longrightarrow> y = x\"\n    unfolding min_product_def min_set_iff by simp+\n\n  then have 2: \"\\<forall>y\\<in>min_set A \\<otimes> B. y |\\<subseteq>| x \\<longrightarrow> y = x\"\n    by (metis product_iff min_set_iff)\n\n  then have \"x \\<in> min_set A \\<otimes> B\"\n    by (metis 1 funion_mono min_set_obtains order_refl product_iff)\n\n  then show \"x \\<in> min_set A \\<otimes>\\<^sub>m B\"\n    by (simp add: 2 min_product_def min_set_iff)\nqed\n\nlemma min_set_min_product[simp]:\n  \"(min_set A) \\<otimes>\\<^sub>m B = A \\<otimes>\\<^sub>m B\"\n  \"A \\<otimes>\\<^sub>m (min_set B) = A \\<otimes>\\<^sub>m B\"\n  using min_product_comm min_set_min_product_helper by blast+\n\nlemma min_set_min_union[simp]:\n  \"(min_set A) \\<union>\\<^sub>m B = A \\<union>\\<^sub>m B\"\n  \"A \\<union>\\<^sub>m (min_set B) = A \\<union>\\<^sub>m B\"\nproof (unfold min_union_def min_set_def, safe)\n  show \"\\<And>x xa xb. \\<lbrakk>\\<forall>xa\\<in>{y \\<in> A. \\<forall>x\\<in>A. x |\\<subseteq>| y \\<longrightarrow> x = y} \\<union> B. xa |\\<subseteq>| x \\<longrightarrow> xa = x; x \\<in> B; xa |\\<subseteq>| x; xb |\\<in>| x; xa \\<in> A\\<rbrakk> \\<Longrightarrow> xb |\\<in>| xa\"\n    by (metis (mono_tags) UnCI dual_order.trans fequalityI min_set_def min_set_obtains)\nnext\n  show \"\\<And>x xa xb. \\<lbrakk>\\<forall>xa\\<in>A \\<union> {y \\<in> B. \\<forall>x\\<in>B. x |\\<subseteq>| y \\<longrightarrow> x = y}. xa |\\<subseteq>| x \\<longrightarrow> xa = x; x \\<in> A; xa |\\<subseteq>| x; xb |\\<in>| x; xa \\<in> B\\<rbrakk> \\<Longrightarrow> xb |\\<in>| xa\"\n    by (metis (mono_tags) UnCI dual_order.trans fequalityI min_set_def min_set_obtains)\nqed blast+\n\n\nlemma product_assoc[simp]:\n  \"(A \\<otimes> B) \\<otimes> C = A \\<otimes> (B \\<otimes> C)\"\nproof (unfold product_def, safe)\n  fix a b c\n  assume \"a \\<in> A\" and \"c \\<in> C\" and \"b \\<in> B\"\n  then have \"b |\\<union>| c \\<in> {b |\\<union>| c |b c. b \\<in> B \\<and> c \\<in> C}\"\n    by blast\n  then show \"\\<exists>a' bc. a |\\<union>| b |\\<union>| c = a' |\\<union>| bc \\<and> a' \\<in> A \\<and> bc \\<in> {b |\\<union>| c |b c. b \\<in> B \\<and> c \\<in> C}\"\n    using `a \\<in> A` by (metis (no_types) inf_sup_aci(5) sup_left_commute)\nqed (metis (mono_tags, lifting) mem_Collect_eq sup_assoc)\n\nlemma min_product_assoc[simp]:\n  \"(A \\<otimes>\\<^sub>m B) \\<otimes>\\<^sub>m C = A \\<otimes>\\<^sub>m (B \\<otimes>\\<^sub>m C)\"\n  unfolding min_product_def[of A B] min_product_def[of B C]\n  by simp (simp add: min_product_def)\n\nlemma min_union_assoc[simp]:\n  \"(A \\<union>\\<^sub>m B) \\<union>\\<^sub>m C = A \\<union>\\<^sub>m (B \\<union>\\<^sub>m C)\"\n  unfolding min_union_def[of A B] min_union_def[of B C]\n  by simp (simp add: min_union_def sup_assoc)\n\n\nlemma min_product_comp:\n  \"a \\<in> A \\<Longrightarrow> b \\<in> B \\<Longrightarrow> \\<exists>c. c |\\<subseteq>| (a |\\<union>| b) \\<and> c \\<in> A \\<otimes>\\<^sub>m B\"\n  by (metis (mono_tags, lifting) mem_Collect_eq min_product_def product_def min_set_obtains)\n\nlemma min_union_comp:\n  \"a \\<in> A \\<Longrightarrow> \\<exists>c. c |\\<subseteq>| a \\<and> c \\<in> A \\<union>\\<^sub>m B\"\n  by (metis Un_iff min_set_obtains min_union_def)\n\n\ninterpretation product_set_thms: Finite_Set.comp_fun_commute product\nproof unfold_locales\n  have \"\\<And>x y z. x \\<otimes> (y \\<otimes> z) = y \\<otimes> (x \\<otimes> z)\"\n    by (simp only: product_assoc[symmetric]) (simp only: product_comm)\n\n  then show \"\\<And>x y. (\\<otimes>) y \\<circ> (\\<otimes>) x = (\\<otimes>) x \\<circ> (\\<otimes>) y\"\n    by fastforce\nqed\n\ninterpretation min_product_set_thms: Finite_Set.comp_fun_idem min_product\nproof unfold_locales\n  have \"\\<And>x y z. x \\<otimes>\\<^sub>m (y \\<otimes>\\<^sub>m z) = y \\<otimes>\\<^sub>m (x \\<otimes>\\<^sub>m z)\"\n    by (simp only: min_product_assoc[symmetric]) (simp only: min_product_comm)\n\n  then show \"\\<And>x y. (\\<otimes>\\<^sub>m) y \\<circ> (\\<otimes>\\<^sub>m) x = (\\<otimes>\\<^sub>m) x \\<circ> (\\<otimes>\\<^sub>m) y\"\n    by fastforce\nnext\n  have \"\\<And>x y. x \\<otimes>\\<^sub>m (x \\<otimes>\\<^sub>m y) = x \\<otimes>\\<^sub>m y\"\n    by (simp add: min_product_assoc[symmetric])\n\n  then show \"\\<And>x. (\\<otimes>\\<^sub>m) x \\<circ> (\\<otimes>\\<^sub>m) x = (\\<otimes>\\<^sub>m) x\"\n    by fastforce\nqed\n\n\ninterpretation min_union_set_thms: Finite_Set.comp_fun_idem min_union\nproof unfold_locales\n  have \"\\<And>x y z. x \\<union>\\<^sub>m (y \\<union>\\<^sub>m z) = y \\<union>\\<^sub>m (x \\<union>\\<^sub>m z)\"\n    by (simp only: min_union_assoc[symmetric]) (simp only: min_union_comm)\n\n  then show \"\\<And>x y. (\\<union>\\<^sub>m) y \\<circ> (\\<union>\\<^sub>m) x = (\\<union>\\<^sub>m) x \\<circ> (\\<union>\\<^sub>m) y\"\n    by fastforce\nnext\n  have \"\\<And>x y. x \\<union>\\<^sub>m (x \\<union>\\<^sub>m y) = x \\<union>\\<^sub>m y\"\n    by (simp add: min_union_assoc[symmetric])\n\n  then show \"\\<And>x. (\\<union>\\<^sub>m) x \\<circ> (\\<union>\\<^sub>m) x = (\\<union>\\<^sub>m) x\"\n    by fastforce\nqed\n\n\nlemma product_set_empty[simp]:\n  \"\\<Otimes> {} = {{||}}\"\n  \"\\<Otimes> {{}} = {}\"\n  \"\\<Otimes> {{{||}}} = {{||}}\"\n  by (simp_all add: product_set_def)\n\nlemma min_product_set_empty[simp]:\n  \"\\<Otimes>\\<^sub>m {} = {{||}}\"\n  \"\\<Otimes>\\<^sub>m {{}} = {}\"\n  \"\\<Otimes>\\<^sub>m {{{||}}} = {{||}}\"\n  by (simp_all add: min_product_set_def)\n\nlemma product_set_code[code]:\n  \"\\<Otimes> (set xs) = fold product (remdups xs) {{||}}\"\n  by (simp add: product_set_def product_set_thms.fold_set_fold_remdups)\n\nlemma min_product_set_code[code]:\n  \"\\<Otimes>\\<^sub>m (set xs) = fold min_product (remdups xs) {{||}}\"\n  by (simp add: min_product_set_def min_product_set_thms.fold_set_fold_remdups)\n\nlemma product_set_insert[simp]:\n  \"finite X \\<Longrightarrow> \\<Otimes> (insert x X) = x \\<otimes> (\\<Otimes> (X - {x}))\"\n  unfolding product_set_def product_set_thms.fold_insert_remove ..\n\nlemma min_product_set_insert[simp]:\n  \"finite X \\<Longrightarrow> \\<Otimes>\\<^sub>m (insert x X) = x \\<otimes>\\<^sub>m (\\<Otimes>\\<^sub>m X)\"\n  unfolding min_product_set_def min_product_set_thms.fold_insert_idem ..\n\nlemma min_product_subseteq:\n  \"x \\<in> A \\<otimes>\\<^sub>m B \\<Longrightarrow> \\<exists>a. a |\\<subseteq>| x \\<and> a \\<in> A\"\n  by (metis funion_upper1 min_product_iff)\n\nlemma min_product_set_subseteq:\n  \"finite X \\<Longrightarrow> x \\<in> \\<Otimes>\\<^sub>m X \\<Longrightarrow> A \\<in> X \\<Longrightarrow> \\<exists>a \\<in> A. a |\\<subseteq>| x\"\n  apply2 (induction X rule: finite_induct) by (blast, metis finite_insert insert_absorb min_product_set_insert min_product_subseteq)\n\n\n\nlemma min_product_min_set[simp]:\n  \"min_set (A \\<otimes>\\<^sub>m B) = A \\<otimes>\\<^sub>m B\"\n  by (simp add: min_product_def)\n\nlemma min_union_min_set[simp]:\n  \"min_set (A \\<union>\\<^sub>m B) = A \\<union>\\<^sub>m B\"\n  by (simp add: min_union_def)\n\nlemma min_product_set_min_set[simp]:\n  \"finite X \\<Longrightarrow> min_set (\\<Otimes>\\<^sub>m X) = \\<Otimes>\\<^sub>m X\"\n  apply2 (induction X rule: finite_induct) by (auto simp add: min_product_set_def min_set_iff)\n\nlemma min_set_min_product_set[simp]:\n  \"finite X \\<Longrightarrow> \\<Otimes>\\<^sub>m (min_set ` X) = \\<Otimes>\\<^sub>m X\"\n  apply2 (induction X rule: finite_induct) by simp_all\n\nlemma min_product_set_union[simp]:\n  \"finite X \\<Longrightarrow> finite Y \\<Longrightarrow> \\<Otimes>\\<^sub>m (X \\<union> Y) = (\\<Otimes>\\<^sub>m X) \\<otimes>\\<^sub>m (\\<Otimes>\\<^sub>m Y)\"\n  apply2 (induction X rule: finite_induct) by simp_all\n\n\nlemma product_set_finite:\n  \"(\\<And>x. x \\<in> X \\<Longrightarrow> finite x) \\<Longrightarrow> finite (\\<Otimes> X)\"\n  apply (cases \"finite X\", rotate_tac) apply2(induction X rule: finite_induct) by (simp_all add: product_set_def, insert product_finite, blast)(*Yutaka rewrote this for evaluation. Originally it was: apply (cases \"finite X\", rotate_tac, induction X rule: finite_induct, simp_all add: product_set_def, insert product_finite, blast)*)\n\nlemma min_product_set_finite:\n  \"(\\<And>x. x \\<in> X \\<Longrightarrow> finite x) \\<Longrightarrow> finite (\\<Otimes>\\<^sub>m X)\"\n  apply (cases \"finite X\", rotate_tac) apply2(induction X rule: finite_induct) by (simp_all add: min_product_set_def, insert min_product_finite, blast)(*Yutaka rewrote this for evaluation. Originally it was: by (cases \"finite X\", rotate_tac, induction X rule: finite_induct, simp_all add: min_product_set_def, insert min_product_finite, blast)*)\n\n\n\nsubsection \\<open>Disjunctive Normal Form\\<close>\n\nfun dnf :: \"'a ltln \\<Rightarrow> 'a ltln fset set\"\nwhere\n  \"dnf true\\<^sub>n = {{||}}\"\n| \"dnf false\\<^sub>n = {}\"\n| \"dnf (\\<phi> and\\<^sub>n \\<psi>) = (dnf \\<phi>) \\<otimes> (dnf \\<psi>)\"\n| \"dnf (\\<phi> or\\<^sub>n \\<psi>) = (dnf \\<phi>) \\<union> (dnf \\<psi>)\"\n| \"dnf \\<phi> = {{|\\<phi>|}}\"\n\nfun min_dnf :: \"'a ltln \\<Rightarrow> 'a ltln fset set\"\nwhere\n  \"min_dnf true\\<^sub>n = {{||}}\"\n| \"min_dnf false\\<^sub>n = {}\"\n| \"min_dnf (\\<phi> and\\<^sub>n \\<psi>) = (min_dnf \\<phi>) \\<otimes>\\<^sub>m (min_dnf \\<psi>)\"\n| \"min_dnf (\\<phi> or\\<^sub>n \\<psi>) = (min_dnf \\<phi>) \\<union>\\<^sub>m (min_dnf \\<psi>)\"\n| \"min_dnf \\<phi> = {{|\\<phi>|}}\"\n\nlemma dnf_min_set:\n  \"min_dnf \\<phi> = min_set (dnf \\<phi>)\"\n  apply2 (induction \\<phi>) by (simp_all, simp_all only: min_product_def min_union_def)\n\nlemma dnf_finite:\n  \"finite (dnf \\<phi>)\"\n  apply2 (induction \\<phi>) by (auto simp: product_finite)\n\nlemma min_dnf_finite:\n  \"finite (min_dnf \\<phi>)\"\n  apply2 (induction \\<phi>) by (auto simp: min_product_finite min_union_finite)\n\nlemma dnf_Abs_fset[simp]:\n  \"fset (Abs_fset (dnf \\<phi>)) = dnf \\<phi>\"\n  by (simp add: dnf_finite Abs_fset_inverse)\n\nlemma min_dnf_Abs_fset[simp]:\n  \"fset (Abs_fset (min_dnf \\<phi>)) = min_dnf \\<phi>\"\n  by (simp add: min_dnf_finite Abs_fset_inverse)\n\nlemma dnf_prop_atoms:\n  \"\\<Phi> \\<in> dnf \\<phi> \\<Longrightarrow> fset \\<Phi> \\<subseteq> prop_atoms \\<phi>\"\n  apply2 (induction \\<phi> arbitrary: \\<Phi>) by (auto simp: product_def, blast+)\n\nlemma min_dnf_prop_atoms:\n  \"\\<Phi> \\<in> min_dnf \\<phi> \\<Longrightarrow> fset \\<Phi> \\<subseteq> prop_atoms \\<phi>\"\n  using dnf_min_set dnf_prop_atoms min_set_subset by blast\n\nlemma min_dnf_atoms_dnf:\n  \"\\<Phi> \\<in> min_dnf \\<psi> \\<Longrightarrow> \\<phi> \\<in> fset \\<Phi> \\<Longrightarrow> dnf \\<phi> = {{|\\<phi>|}}\"\nproof2 (induction \\<phi>)\n  case True_ltln\n  then show ?case\n    using min_dnf_prop_atoms prop_atoms_notin(1) by blast\nnext\n  case False_ltln\n  then show ?case\n    using min_dnf_prop_atoms prop_atoms_notin(2) by blast\nnext\n  case (And_ltln \\<phi>1 \\<phi>2)\n  then show ?case\n    using min_dnf_prop_atoms prop_atoms_notin(3) by force\nnext\n  case (Or_ltln \\<phi>1 \\<phi>2)\n  then show ?case\n    using min_dnf_prop_atoms prop_atoms_notin(4) by force\nqed auto\n\nlemma min_dnf_min_set[simp]:\n  \"min_set (min_dnf \\<phi>) = min_dnf \\<phi>\"\n  apply2 (induction \\<phi>) by (simp_all add: min_set_def min_product_def min_union_def, blast+)\n\n\nlemma min_dnf_iff_prop_assignment_subset:\n  \"\\<A> \\<Turnstile>\\<^sub>P \\<phi> \\<longleftrightarrow> (\\<exists>B. fset B \\<subseteq> \\<A> \\<and> B \\<in> min_dnf \\<phi>)\"\nproof\n  assume \"\\<A> \\<Turnstile>\\<^sub>P \\<phi>\"\n\n  then show \"\\<exists>B. fset B \\<subseteq> \\<A> \\<and> B \\<in> min_dnf \\<phi>\"\n  proof2 (induction \\<phi> arbitrary: \\<A>)\n    case (And_ltln \\<phi>\\<^sub>1 \\<phi>\\<^sub>2)\n\n    then obtain B\\<^sub>1 B\\<^sub>2 where 1: \"fset B\\<^sub>1 \\<subseteq> \\<A> \\<and> B\\<^sub>1 \\<in> min_dnf \\<phi>\\<^sub>1\" and 2: \"fset B\\<^sub>2 \\<subseteq> \\<A> \\<and> B\\<^sub>2 \\<in> min_dnf \\<phi>\\<^sub>2\"\n      by fastforce\n\n    then obtain C where \"C |\\<subseteq>| B\\<^sub>1 |\\<union>| B\\<^sub>2\" and \"C \\<in> min_dnf \\<phi>\\<^sub>1 \\<otimes>\\<^sub>m min_dnf \\<phi>\\<^sub>2\"\n      using min_product_comp by metis\n\n    then show ?case\n      by (metis 1 2 le_sup_iff min_dnf.simps(3) sup.absorb_iff1 sup_fset.rep_eq)\n  next\n    case (Or_ltln \\<phi>\\<^sub>1 \\<phi>\\<^sub>2)\n\n    {\n      assume \"\\<A> \\<Turnstile>\\<^sub>P \\<phi>\\<^sub>1\"\n\n      then obtain B where 1: \"fset B \\<subseteq> \\<A> \\<and> B \\<in> min_dnf \\<phi>\\<^sub>1\"\n        using Or_ltln by fastforce\n\n      then obtain C where \"C |\\<subseteq>| B\" and \"C \\<in> min_dnf \\<phi>\\<^sub>1 \\<union>\\<^sub>m min_dnf \\<phi>\\<^sub>2\"\n        using min_union_comp by metis\n\n      then have ?case\n        by (metis 1 dual_order.trans less_eq_fset.rep_eq min_dnf.simps(4))\n    }\n\n    moreover\n\n    {\n      assume \"\\<A> \\<Turnstile>\\<^sub>P \\<phi>\\<^sub>2\"\n\n      then obtain B where 2: \"fset B \\<subseteq> \\<A> \\<and> B \\<in> min_dnf \\<phi>\\<^sub>2\"\n        using Or_ltln by fastforce\n\n      then obtain C where \"C |\\<subseteq>| B\" and \"C \\<in> min_dnf \\<phi>\\<^sub>1 \\<union>\\<^sub>m min_dnf \\<phi>\\<^sub>2\"\n        using min_union_comp min_union_comm by metis\n\n      then have ?case\n        by (metis 2 dual_order.trans less_eq_fset.rep_eq min_dnf.simps(4))\n    }\n\n    ultimately show ?case\n      using Or_ltln.prems by auto\n  qed simp_all\nnext\n  assume \"\\<exists>B. fset B \\<subseteq> \\<A> \\<and> B \\<in> min_dnf \\<phi>\"\n\n  then obtain B where \"fset B \\<subseteq> \\<A>\" and \"B \\<in> min_dnf \\<phi>\"\n    by auto\n\n  then have \"fset B \\<Turnstile>\\<^sub>P \\<phi>\"\n    apply2 (induction \\<phi> arbitrary: B) by (auto simp: min_set_def min_product_def product_def min_union_def, blast+)\n\n  then show \"\\<A> \\<Turnstile>\\<^sub>P \\<phi>\"\n    using \\<open>fset B \\<subseteq> \\<A>\\<close> by blast\nqed\n\n\nlemma ltl_prop_implies_min_dnf:\n  \"\\<phi> \\<longrightarrow>\\<^sub>P \\<psi> = (\\<forall>A \\<in> min_dnf \\<phi>. \\<exists>B \\<in> min_dnf \\<psi>. B |\\<subseteq>| A)\"\n  by (meson less_eq_fset.rep_eq ltl_prop_implies_def min_dnf_iff_prop_assignment_subset order_refl dual_order.trans)\n\nlemma ltl_prop_equiv_min_dnf:\n  \"\\<phi> \\<sim>\\<^sub>P \\<psi> = (min_dnf \\<phi> = min_dnf \\<psi>)\"\nproof\n  assume \"\\<phi> \\<sim>\\<^sub>P \\<psi>\"\n\n  then have \"\\<And>x. x \\<in> min_set (min_dnf \\<phi>) \\<longleftrightarrow> x \\<in> min_set (min_dnf \\<psi>)\"\n    unfolding ltl_prop_implies_equiv ltl_prop_implies_min_dnf min_set_iff\n    by fastforce\n\n  then show \"min_dnf \\<phi> = min_dnf \\<psi>\"\n    by auto\nqed (simp add: ltl_prop_equiv_def min_dnf_iff_prop_assignment_subset)\n\n\n\n\nsubsection \\<open>Folding of \\<open>and\\<^sub>n\\<close> and \\<open>or\\<^sub>n\\<close> over Finite Sets\\<close>\n\ndefinition And\\<^sub>n :: \"'a ltln set \\<Rightarrow> 'a ltln\"\nwhere\n  \"And\\<^sub>n \\<Phi> \\<equiv> SOME \\<phi>. fold_graph And_ltln True_ltln \\<Phi> \\<phi>\"\n\ndefinition Or\\<^sub>n :: \"'a ltln set \\<Rightarrow> 'a ltln\"\nwhere\n  \"Or\\<^sub>n \\<Phi> \\<equiv> SOME \\<phi>. fold_graph Or_ltln False_ltln \\<Phi> \\<phi>\"\n\nlemma fold_graph_And\\<^sub>n:\n  \"finite \\<Phi> \\<Longrightarrow> fold_graph And_ltln True_ltln \\<Phi> (And\\<^sub>n \\<Phi>)\"\n  unfolding And\\<^sub>n_def by (rule someI2_ex[OF finite_imp_fold_graph])\n\nlemma fold_graph_Or\\<^sub>n:\n  \"finite \\<Phi> \\<Longrightarrow> fold_graph Or_ltln False_ltln \\<Phi> (Or\\<^sub>n \\<Phi>)\"\n  unfolding Or\\<^sub>n_def by (rule someI2_ex[OF finite_imp_fold_graph])\n\nlemma Or\\<^sub>n_empty[simp]:\n  \"Or\\<^sub>n {} = False_ltln\"\n  by (metis empty_fold_graphE finite.emptyI fold_graph_Or\\<^sub>n)\n\nlemma And\\<^sub>n_empty[simp]:\n  \"And\\<^sub>n {} = True_ltln\"\n  by (metis empty_fold_graphE finite.emptyI fold_graph_And\\<^sub>n)\n\ninterpretation dnf_union_thms: Finite_Set.comp_fun_commute \"\\<lambda>\\<phi>. (\\<union>) (f \\<phi>)\"\n  by unfold_locales fastforce\n\ninterpretation dnf_product_thms: Finite_Set.comp_fun_commute \"\\<lambda>\\<phi>. (\\<otimes>) (f \\<phi>)\"\n  by unfold_locales (simp add: product_set_thms.comp_fun_commute)\n\n\\<comment> \\<open>Copied from locale @{locale comp_fun_commute}\\<close>\n\n\n\ntext \\<open>Taking the DNF of @{const And\\<^sub>n} and @{const Or\\<^sub>n} is the same as folding over the individual DNFs.\\<close>\n\nlemma And\\<^sub>n_dnf:\n  \"finite \\<Phi> \\<Longrightarrow> dnf (And\\<^sub>n \\<Phi>) = Finite_Set.fold (\\<lambda>\\<phi>. (\\<otimes>) (dnf \\<phi>)) {{||}} \\<Phi>\"\n  apply (drule fold_graph_And\\<^sub>n) proof2 (induction rule: fold_graph.induct)(*Yutaka rewrote this for evaluation. Originally, it was: proof (drule fold_graph_And\\<^sub>n, induction rule: fold_graph.induct)*)\n  case (insertI x A y)\n\n  then have \"finite A\"\n    using fold_graph_finite by fast\n\n  then show ?case\n    using insertI by auto\nqed simp\n\nlemma Or\\<^sub>n_dnf:\n  \"finite \\<Phi> \\<Longrightarrow> dnf (Or\\<^sub>n \\<Phi>) = Finite_Set.fold (\\<lambda>\\<phi>. (\\<union>) (dnf \\<phi>)) {} \\<Phi>\"\n  apply (drule fold_graph_Or\\<^sub>n)proof2(induction rule: fold_graph.induct)(*Yutaka rewrote this for evaluation. Originally, it was: proof (drule fold_graph_Or\\<^sub>n, induction rule: fold_graph.induct)*)\n  case (insertI x A y)\n\n  then have \"finite A\"\n    using fold_graph_finite by fast\n\n  then show ?case\n    using insertI by auto\nqed simp\n\n\ntext \\<open>@{const And\\<^sub>n} and @{const Or\\<^sub>n} are injective on finite sets.\\<close>\n\nlemma And\\<^sub>n_inj:\n  \"inj_on And\\<^sub>n {s. finite s}\"\nproof (standard, simp)\n  fix x y :: \"'a ltln set\"\n  assume \"finite x\" and \"finite y\"\n\n  then have 1: \"fold_graph And_ltln True_ltln x (And\\<^sub>n x)\" and 2: \"fold_graph And_ltln True_ltln y (And\\<^sub>n y)\"\n    using fold_graph_And\\<^sub>n by blast+\n\n  assume \"And\\<^sub>n x = And\\<^sub>n y\"\n\n  with 1 show \"x = y\"\n  proof2 (induction rule: fold_graph.induct)\n    case emptyI\n    then show ?case\n      using 2 fold_graph.cases by force\n  next\n    case (insertI x A y)\n    with 2 show ?case\n    proof2 (induction arbitrary: x A y rule: fold_graph.induct)\n      case (insertI x A y)\n      then show ?case\n        by (metis fold_graph.cases insertI1 ltln.distinct(7) ltln.inject(3))\n    qed blast\n  qed\nqed\n\nlemma Or\\<^sub>n_inj:\n  \"inj_on Or\\<^sub>n {s. finite s}\"\nproof (standard, simp)\n  fix x y :: \"'a ltln set\"\n  assume \"finite x\" and \"finite y\"\n\n  then have 1: \"fold_graph Or_ltln False_ltln x (Or\\<^sub>n x)\" and 2: \"fold_graph Or_ltln False_ltln y (Or\\<^sub>n y)\"\n    using fold_graph_Or\\<^sub>n by blast+\n\n  assume \"Or\\<^sub>n x = Or\\<^sub>n y\"\n\n  with 1 show \"x = y\"\n  proof2 (induction rule: fold_graph.induct)\n    case emptyI\n    then show ?case\n      using 2 fold_graph.cases by force\n  next\n    case (insertI x A y)\n    with 2 show ?case\n    proof2 (induction arbitrary: x A y rule: fold_graph.induct)\n      case (insertI x A y)\n      then show ?case\n        by (metis fold_graph.cases insertI1 ltln.distinct(27) ltln.inject(4))\n    qed blast\n  qed\nqed\n\n\ntext \\<open>The semantics of @{const And\\<^sub>n} and @{const Or\\<^sub>n} can be expressed using quantifiers.\\<close>\n\nlemma And\\<^sub>n_semantics:\n  \"finite \\<Phi> \\<Longrightarrow> w \\<Turnstile>\\<^sub>n And\\<^sub>n \\<Phi> \\<longleftrightarrow> (\\<forall>\\<phi> \\<in> \\<Phi>. w \\<Turnstile>\\<^sub>n \\<phi>)\"\nproof -\n  assume \"finite \\<Phi>\"\n  have \"\\<And>\\<psi>. fold_graph And_ltln True_ltln \\<Phi> \\<psi> \\<Longrightarrow> w \\<Turnstile>\\<^sub>n \\<psi> \\<longleftrightarrow> (\\<forall>\\<phi> \\<in> \\<Phi>. w \\<Turnstile>\\<^sub>n \\<phi>)\"\n    by (rule fold_graph.induct) auto\n  then show ?thesis\n    using fold_graph_And\\<^sub>n[OF \\<open>finite \\<Phi>\\<close>] by simp\nqed\n\nlemma Or\\<^sub>n_semantics:\n  \"finite \\<Phi> \\<Longrightarrow> w \\<Turnstile>\\<^sub>n Or\\<^sub>n \\<Phi> \\<longleftrightarrow> (\\<exists>\\<phi> \\<in> \\<Phi>. w \\<Turnstile>\\<^sub>n \\<phi>)\"\nproof -\n  assume \"finite \\<Phi>\"\n  have \"\\<And>\\<psi>. fold_graph Or_ltln False_ltln \\<Phi> \\<psi> \\<Longrightarrow> w \\<Turnstile>\\<^sub>n \\<psi> \\<longleftrightarrow> (\\<exists>\\<phi> \\<in> \\<Phi>. w \\<Turnstile>\\<^sub>n \\<phi>)\"\n    by (rule fold_graph.induct) auto\n  then show ?thesis\n    using fold_graph_Or\\<^sub>n[OF \\<open>finite \\<Phi>\\<close>] by simp\nqed\n\nlemma And\\<^sub>n_prop_semantics:\n  \"finite \\<Phi> \\<Longrightarrow> \\<A> \\<Turnstile>\\<^sub>P And\\<^sub>n \\<Phi> \\<longleftrightarrow> (\\<forall>\\<phi> \\<in> \\<Phi>. \\<A> \\<Turnstile>\\<^sub>P \\<phi>)\"\nproof -\n  assume \"finite \\<Phi>\"\n  have \"\\<And>\\<psi>. fold_graph And_ltln True_ltln \\<Phi> \\<psi> \\<Longrightarrow> \\<A> \\<Turnstile>\\<^sub>P \\<psi> \\<longleftrightarrow> (\\<forall>\\<phi> \\<in> \\<Phi>. \\<A> \\<Turnstile>\\<^sub>P \\<phi>)\"\n    by (rule fold_graph.induct) auto\n  then show ?thesis\n    using fold_graph_And\\<^sub>n[OF \\<open>finite \\<Phi>\\<close>] by simp\nqed\n\nlemma Or\\<^sub>n_prop_semantics:\n  \"finite \\<Phi> \\<Longrightarrow> \\<A> \\<Turnstile>\\<^sub>P Or\\<^sub>n \\<Phi> \\<longleftrightarrow> (\\<exists>\\<phi> \\<in> \\<Phi>. \\<A> \\<Turnstile>\\<^sub>P \\<phi>)\"\nproof -\n  assume \"finite \\<Phi>\"\n  have \"\\<And>\\<psi>. fold_graph Or_ltln False_ltln \\<Phi> \\<psi> \\<Longrightarrow> \\<A> \\<Turnstile>\\<^sub>P \\<psi> \\<longleftrightarrow> (\\<exists>\\<phi> \\<in> \\<Phi>. \\<A> \\<Turnstile>\\<^sub>P \\<phi>)\"\n    by (rule fold_graph.induct) auto\n  then show ?thesis\n    using fold_graph_Or\\<^sub>n[OF \\<open>finite \\<Phi>\\<close>] by simp\nqed\n\nlemma Or\\<^sub>n_And\\<^sub>n_image_semantics:\n  assumes \"finite \\<A>\" and \"\\<And>\\<Phi>. \\<Phi> \\<in> \\<A> \\<Longrightarrow> finite \\<Phi>\"\n  shows \"w \\<Turnstile>\\<^sub>n Or\\<^sub>n (And\\<^sub>n ` \\<A>) \\<longleftrightarrow> (\\<exists>\\<Phi> \\<in> \\<A>. \\<forall>\\<phi> \\<in> \\<Phi>. w \\<Turnstile>\\<^sub>n \\<phi>)\"\nproof -\n  have \"w \\<Turnstile>\\<^sub>n Or\\<^sub>n (And\\<^sub>n ` \\<A>) \\<longleftrightarrow> (\\<exists>\\<Phi> \\<in> \\<A>. w \\<Turnstile>\\<^sub>n And\\<^sub>n \\<Phi>)\"\n    using Or\\<^sub>n_semantics assms by auto\n  then show ?thesis\n    using And\\<^sub>n_semantics assms by fast\nqed\n\nlemma Or\\<^sub>n_And\\<^sub>n_image_prop_semantics:\n  assumes \"finite \\<A>\" and \"\\<And>\\<Phi>. \\<Phi> \\<in> \\<A> \\<Longrightarrow> finite \\<Phi>\"\n  shows \"\\<I> \\<Turnstile>\\<^sub>P Or\\<^sub>n (And\\<^sub>n ` \\<A>) \\<longleftrightarrow> (\\<exists>\\<Phi> \\<in> \\<A>. \\<forall>\\<phi> \\<in> \\<Phi>. \\<I> \\<Turnstile>\\<^sub>P \\<phi>)\"\nproof -\n  have \"\\<I> \\<Turnstile>\\<^sub>P Or\\<^sub>n (And\\<^sub>n ` \\<A>) \\<longleftrightarrow> (\\<exists>\\<Phi> \\<in> \\<A>. \\<I> \\<Turnstile>\\<^sub>P And\\<^sub>n \\<Phi>)\"\n    using Or\\<^sub>n_prop_semantics assms by blast\n  then show ?thesis\n    using And\\<^sub>n_prop_semantics assms by metis\nqed\n\n\nsubsection \\<open>DNF to LTL conversion\\<close>\n\ndefinition ltln_of_dnf :: \"'a ltln fset set \\<Rightarrow> 'a ltln\"\nwhere\n  \"ltln_of_dnf \\<A> = Or\\<^sub>n (And\\<^sub>n ` fset ` \\<A>)\"\n\nlemma ltln_of_dnf_semantics:\n  assumes \"finite \\<A>\"\n  shows \"w \\<Turnstile>\\<^sub>n ltln_of_dnf \\<A> \\<longleftrightarrow> (\\<exists>\\<Phi> \\<in> \\<A>. \\<forall>\\<phi>. \\<phi> |\\<in>| \\<Phi> \\<longrightarrow> w \\<Turnstile>\\<^sub>n \\<phi>)\"\nproof -\n  have \"finite (fset ` \\<A>)\"\n    using assms by blast\n\n  then have \"w \\<Turnstile>\\<^sub>n ltln_of_dnf \\<A> \\<longleftrightarrow> (\\<exists>\\<Phi> \\<in> fset ` \\<A>. \\<forall>\\<phi> \\<in> \\<Phi>. w \\<Turnstile>\\<^sub>n \\<phi>)\"\n    unfolding ltln_of_dnf_def using Or\\<^sub>n_And\\<^sub>n_image_semantics by fastforce\n\n  then show ?thesis\n    by (metis image_iff notin_fset)\nqed\n\nlemma ltln_of_dnf_prop_semantics:\n  assumes \"finite \\<A>\"\n  shows \"\\<I> \\<Turnstile>\\<^sub>P ltln_of_dnf \\<A> \\<longleftrightarrow> (\\<exists>\\<Phi> \\<in> \\<A>. \\<forall>\\<phi>. \\<phi> |\\<in>| \\<Phi> \\<longrightarrow> \\<I> \\<Turnstile>\\<^sub>P \\<phi>)\"\nproof -\n  have \"finite (fset ` \\<A>)\"\n    using assms by blast\n\n  then have \"\\<I> \\<Turnstile>\\<^sub>P ltln_of_dnf \\<A> \\<longleftrightarrow> (\\<exists>\\<Phi> \\<in> fset ` \\<A>. \\<forall>\\<phi> \\<in> \\<Phi>. \\<I> \\<Turnstile>\\<^sub>P \\<phi>)\"\n    unfolding ltln_of_dnf_def using Or\\<^sub>n_And\\<^sub>n_image_prop_semantics by fastforce\n\n  then show ?thesis\n    by (metis image_iff notin_fset)\nqed\n\nlemma ltln_of_dnf_prop_equiv:\n  \"ltln_of_dnf (min_dnf \\<phi>) \\<sim>\\<^sub>P \\<phi>\"\n  unfolding ltl_prop_equiv_def\nproof\n  fix \\<A>\n  have \"\\<A> \\<Turnstile>\\<^sub>P ltln_of_dnf (min_dnf \\<phi>) \\<longleftrightarrow> (\\<exists>\\<Phi> \\<in> min_dnf \\<phi>. \\<forall>\\<phi>. \\<phi> |\\<in>| \\<Phi> \\<longrightarrow> \\<A> \\<Turnstile>\\<^sub>P \\<phi>)\"\n    using ltln_of_dnf_prop_semantics min_dnf_finite by metis\n  also have \"\\<dots> \\<longleftrightarrow> (\\<exists>\\<Phi> \\<in> min_dnf \\<phi>. fset \\<Phi> \\<subseteq> \\<A>)\"\n    by (metis min_dnf_prop_atoms prop_atoms_entailment_iff notin_fset subset_eq)\n  also have \"\\<dots> \\<longleftrightarrow> \\<A> \\<Turnstile>\\<^sub>P \\<phi>\"\n    using min_dnf_iff_prop_assignment_subset by blast\n  finally show \"\\<A> \\<Turnstile>\\<^sub>P ltln_of_dnf (min_dnf \\<phi>) = \\<A> \\<Turnstile>\\<^sub>P \\<phi>\" .\nqed\n\nlemma min_dnf_ltln_of_dnf[simp]:\n  \"min_dnf (ltln_of_dnf (min_dnf \\<phi>)) = min_dnf \\<phi>\"\n  using ltl_prop_equiv_min_dnf ltln_of_dnf_prop_equiv by blast\n\n\nsubsection \\<open>Substitution in DNF formulas\\<close>\n\ndefinition subst_clause :: \"'a ltln fset \\<Rightarrow> ('a ltln \\<rightharpoonup> 'a ltln) \\<Rightarrow> 'a ltln fset set\"\nwhere\n  \"subst_clause \\<Phi> m = \\<Otimes>\\<^sub>m {min_dnf (subst \\<phi> m) | \\<phi>. \\<phi> \\<in> fset \\<Phi>}\"\n\ndefinition subst_dnf :: \"'a ltln fset set \\<Rightarrow> ('a ltln \\<rightharpoonup> 'a ltln) \\<Rightarrow> 'a ltln fset set\"\nwhere\n  \"subst_dnf \\<A> m = (\\<Union>\\<Phi> \\<in> \\<A>. subst_clause \\<Phi> m)\"\n\nlemma subst_clause_empty[simp]:\n  \"subst_clause {||} m = {{||}}\"\n  by (simp add: subst_clause_def)\n\nlemma subst_dnf_empty[simp]:\n  \"subst_dnf {} m = {}\"\n  by (simp add: subst_dnf_def)\n\nlemma subst_clause_inner_finite:\n  \"finite {min_dnf (subst \\<phi> m) | \\<phi>. \\<phi> \\<in> \\<Phi>}\" if \"finite \\<Phi>\"\n  using that by simp\n\nlemma subst_clause_finite:\n  \"finite (subst_clause \\<Phi> m)\"\n  unfolding subst_clause_def\n  by (auto intro: min_dnf_finite min_product_set_finite)\n\nlemma subst_dnf_finite:\n  \"finite \\<A> \\<Longrightarrow> finite (subst_dnf \\<A> m)\"\n  unfolding subst_dnf_def using subst_clause_finite by blast\n\nlemma subst_dnf_mono:\n  \"\\<A> \\<subseteq> \\<B> \\<Longrightarrow> subst_dnf \\<A> m \\<subseteq> subst_dnf \\<B> m\"\n  unfolding subst_dnf_def by blast\n\nlemma subst_clause_min_set[simp]:\n  \"min_set (subst_clause \\<Phi> m) = subst_clause \\<Phi> m\"\n  unfolding subst_clause_def by simp\n\nlemma subst_clause_finsert[simp]:\n  \"subst_clause (finsert \\<phi> \\<Phi>) m = (min_dnf (subst \\<phi> m)) \\<otimes>\\<^sub>m (subst_clause \\<Phi> m)\"\nproof -\n  have \"{min_dnf (subst \\<psi> m) | \\<psi>. \\<psi> \\<in> fset (finsert \\<phi> \\<Phi>)}\n    = insert (min_dnf (subst \\<phi> m)) {min_dnf (subst \\<psi> m) | \\<psi>. \\<psi> \\<in> fset \\<Phi>}\"\n    by auto\n\n  then show ?thesis\n    by (simp add: subst_clause_def)\nqed\n\nlemma subst_clause_funion[simp]:\n  \"subst_clause (\\<Phi> |\\<union>| \\<Psi>) m = (subst_clause \\<Phi> m) \\<otimes>\\<^sub>m (subst_clause \\<Psi> m)\"\nproof2 (induction \\<Psi>)\n  case (insert x F)\n  then show ?case\n    using min_product_set_thms.fun_left_comm by fastforce\nqed simp\n\n\ntext \\<open>For the proof of correctness, we redefine the @{const product} operator on lists.\\<close>\n\ndefinition list_product :: \"'a list set \\<Rightarrow> 'a list set \\<Rightarrow> 'a list set\" (infixl \"\\<otimes>\\<^sub>l\" 65)\nwhere\n  \"A \\<otimes>\\<^sub>l B = {a @ b | a b. a \\<in> A \\<and> b \\<in> B}\"\n\nlemma list_product_fset_of_list[simp]:\n  \"fset_of_list ` (A \\<otimes>\\<^sub>l B) = (fset_of_list ` A) \\<otimes> (fset_of_list ` B)\"\n  unfolding list_product_def product_def image_def by fastforce\n\nlemma list_product_finite:\n  \"finite A \\<Longrightarrow> finite B \\<Longrightarrow> finite (A \\<otimes>\\<^sub>l B)\"\n  unfolding list_product_def by (simp add: finite_image_set2)\n\nlemma list_product_iff:\n  \"x \\<in> A \\<otimes>\\<^sub>l B \\<longleftrightarrow> (\\<exists>a b. a \\<in> A \\<and> b \\<in> B \\<and> x = a @ b)\"\n  unfolding list_product_def by blast\n\nlemma list_product_assoc[simp]:\n  \"A \\<otimes>\\<^sub>l (B \\<otimes>\\<^sub>l C) = A \\<otimes>\\<^sub>l B \\<otimes>\\<^sub>l C\"\n  unfolding set_eq_iff list_product_iff by fastforce\n\n\ntext \\<open>Furthermore, we introduct DNFs where the clauses are represented as lists.\\<close>\n\nfun list_dnf :: \"'a ltln \\<Rightarrow> 'a ltln list set\"\nwhere\n  \"list_dnf true\\<^sub>n = {[]}\"\n| \"list_dnf false\\<^sub>n = {}\"\n| \"list_dnf (\\<phi> and\\<^sub>n \\<psi>) = (list_dnf \\<phi>) \\<otimes>\\<^sub>l (list_dnf \\<psi>)\"\n| \"list_dnf (\\<phi> or\\<^sub>n \\<psi>) = (list_dnf \\<phi>) \\<union> (list_dnf \\<psi>)\"\n| \"list_dnf \\<phi> = {[\\<phi>]}\"\n\ndefinition list_dnf_to_dnf :: \"'a list set \\<Rightarrow> 'a fset set\"\nwhere\n  \"list_dnf_to_dnf X = fset_of_list ` X\"\n\nlemma list_dnf_to_dnf_list_dnf[simp]:\n  \"list_dnf_to_dnf (list_dnf \\<phi>) = dnf \\<phi>\"\n  apply2 (induction \\<phi>) by (simp_all add: list_dnf_to_dnf_def image_Un)\n\nlemma list_dnf_finite:\n  \"finite (list_dnf \\<phi>)\"\n  apply2 (induction \\<phi>) by (simp_all add: list_product_finite)\n\n\ntext \\<open>We use this to redefine @{const subst_clause} and @{const subst_dnf} on list DNFs.\\<close>\n\ndefinition subst_clause' :: \"'a ltln list \\<Rightarrow> ('a ltln \\<rightharpoonup> 'a ltln) \\<Rightarrow> 'a ltln list set\"\nwhere\n  \"subst_clause' \\<Phi> m = fold (\\<lambda>\\<phi> acc. acc \\<otimes>\\<^sub>l list_dnf (subst \\<phi> m)) \\<Phi> {[]}\"\n\ndefinition subst_dnf' :: \"'a ltln list set \\<Rightarrow> ('a ltln \\<rightharpoonup> 'a ltln) \\<Rightarrow> 'a ltln list set\"\nwhere\n  \"subst_dnf' \\<A> m = (\\<Union>\\<Phi> \\<in> \\<A>. subst_clause' \\<Phi> m)\"\n\nlemma subst_clause'_finite:\n  \"finite (subst_clause' \\<Phi> m)\"\n  apply2 (induction \\<Phi> rule: rev_induct) by (simp_all add: subst_clause'_def list_dnf_finite list_product_finite)\n\nlemma subst_clause'_nil[simp]:\n  \"subst_clause' [] m = {[]}\"\n  by (simp add: subst_clause'_def)\n\nlemma subst_clause'_cons[simp]:\n  \"subst_clause' (xs @ [x]) m = subst_clause' xs m \\<otimes>\\<^sub>l list_dnf (subst x m)\"\n  by (simp add: subst_clause'_def)\n\nlemma subst_clause'_append[simp]:\n  \"subst_clause' (A @ B) m = subst_clause' A m \\<otimes>\\<^sub>l subst_clause' B m\"\nproof2 (induction B rule: rev_induct)\n  case (snoc x xs)\n  then show ?case\n    by simp (metis append_assoc subst_clause'_cons)\nqed(simp add: list_product_def)\n\n\nlemma subst_dnf'_iff:\n  \"x \\<in> subst_dnf' A m \\<longleftrightarrow> (\\<exists>\\<Phi> \\<in> A. x \\<in> subst_clause' \\<Phi> m)\"\n  by (simp add: subst_dnf'_def)\n\nlemma subst_dnf'_product:\n  \"subst_dnf' (A \\<otimes>\\<^sub>l B) m = (subst_dnf' A m) \\<otimes>\\<^sub>l (subst_dnf' B m)\" (is \"?lhs = ?rhs\")\nproof (unfold set_eq_iff, safe)\n  fix x\n  assume \"x \\<in> ?lhs\"\n\n  then obtain \\<Phi> where \"\\<Phi> \\<in> A \\<otimes>\\<^sub>l B\" and \"x \\<in> subst_clause' \\<Phi> m\"\n    unfolding subst_dnf'_iff by blast\n\n  then obtain a b where \"a \\<in> A\" and \"b \\<in> B\" and \"\\<Phi> = a @ b\"\n    unfolding list_product_def by blast\n\n  then have \"x \\<in> (subst_clause' a m) \\<otimes>\\<^sub>l (subst_clause' b m)\"\n    using \\<open>x \\<in> subst_clause' \\<Phi> m\\<close> by simp\n\n  then obtain a' b' where \"a' \\<in> subst_clause' a m\" and \"b' \\<in> subst_clause' b m\" and \"x = a' @ b'\"\n    unfolding list_product_iff by blast\n\n  then have \"a' \\<in> subst_dnf' A m\" and \"b' \\<in> subst_dnf' B m\"\n    unfolding subst_dnf'_iff using \\<open>a \\<in> A\\<close> \\<open>b \\<in> B\\<close> by auto\n\n  then have \"\\<exists>a\\<in>subst_dnf' A m. \\<exists>b\\<in>subst_dnf' B m. x = a @ b\"\n    using \\<open>x = a' @ b'\\<close> by blast\n\n  then show \"x \\<in> ?rhs\"\n    unfolding list_product_iff by blast\nnext\n  fix x\n  assume \"x \\<in> ?rhs\"\n\n  then obtain a b where \"a \\<in> subst_dnf' A m\" and \"b \\<in> subst_dnf' B m\" and \"x = a @ b\"\n    unfolding list_product_iff by blast\n\n  then obtain a' b' where \"a' \\<in> A\" and \"b' \\<in> B\" and a: \"a \\<in> subst_clause' a' m\" and b: \"b \\<in> subst_clause' b' m\"\n    unfolding subst_dnf'_iff by blast\n\n  then have \"x \\<in> (subst_clause' a' m) \\<otimes>\\<^sub>l (subst_clause' b' m)\"\n    unfolding list_product_iff using \\<open>x = a @ b\\<close> by blast\n\n  moreover\n\n  have \"a' @ b' \\<in> A \\<otimes>\\<^sub>l B\"\n    unfolding list_product_iff using \\<open>a' \\<in> A\\<close> \\<open>b' \\<in> B\\<close> by blast\n\n  ultimately show \"x \\<in> ?lhs\"\n    unfolding subst_dnf'_iff by force\nqed\n\nlemma subst_dnf'_list_dnf:\n  \"subst_dnf' (list_dnf \\<phi>) m = list_dnf (subst \\<phi> m)\"\nproof2 (induction \\<phi>)\n  case (And_ltln \\<phi>1 \\<phi>2)\n  then show ?case\n    by (simp add: subst_dnf'_product)\nqed (simp_all add: subst_dnf'_def subst_clause'_def list_product_def)\n\n\nlemma min_set_Union:\n  \"finite X \\<Longrightarrow> min_set (\\<Union> (min_set ` X)) = min_set (\\<Union> X)\" for X :: \"'a fset set set\"\n  apply2 (induction X rule: finite_induct) by (force, metis Sup_insert image_insert min_set_min_union min_union_def)\n\nlemma min_set_Union_image:\n  \"finite X \\<Longrightarrow> min_set (\\<Union>x \\<in> X. min_set (f x)) = min_set (\\<Union>x \\<in> X. f x)\" for f :: \"'b \\<Rightarrow> 'a fset set\"\nproof -\n  assume \"finite X\"\n\n  then have *: \"finite (f ` X)\" by auto\n\n  with min_set_Union show ?thesis\n    unfolding image_image by fastforce\nqed\n\nlemma subst_clause_fset_of_list:\n  \"subst_clause (fset_of_list \\<Phi>) m = min_set (list_dnf_to_dnf (subst_clause' \\<Phi> m))\"\n  unfolding list_dnf_to_dnf_def subst_clause'_def\nproof2 (induction \\<Phi> rule: rev_induct)\n  case (snoc x xs)\n  then show ?case\n    by simp (metis (no_types, lifting) dnf_min_set list_dnf_to_dnf_def list_dnf_to_dnf_list_dnf min_product_comm min_product_def min_set_min_product(1))\nqed simp\n\nlemma min_set_list_dnf_to_dnf_subst_dnf':\n  \"finite X \\<Longrightarrow> min_set (list_dnf_to_dnf (subst_dnf' X m)) = min_set (subst_dnf (list_dnf_to_dnf X) m)\"\n  by (simp add: subst_dnf'_def subst_dnf_def subst_clause_fset_of_list list_dnf_to_dnf_def min_set_Union_image image_Union)\n\nlemma subst_dnf_dnf:\n  \"min_set (subst_dnf (dnf \\<phi>) m) = min_dnf (subst \\<phi> m)\"\n  unfolding dnf_min_set\n  unfolding list_dnf_to_dnf_list_dnf[symmetric]\n  unfolding subst_dnf'_list_dnf[symmetric]\n  unfolding min_set_list_dnf_to_dnf_subst_dnf'[OF list_dnf_finite]\n  by simp\n\n\ntext \\<open>This is almost the lemma we need. However, we need to show that the same holds for @{term \"min_dnf \\<phi>\"}, too.\\<close>\n\nlemma fold_product:\n  \"Finite_Set.fold (\\<lambda>x. (\\<otimes>) {{|x|}}) {{||}} (fset x) = {x}\"\n  apply2 (induction x) by (simp_all add: notin_fset, simp add: product_singleton_singleton)\n\nlemma fold_union:\n  \"Finite_Set.fold (\\<lambda>x. (\\<union>) {x}) {} (fset x) = fset x\"\n  apply2 (induction x) by (simp_all add: notin_fset comp_fun_idem.fold_insert_idem comp_fun_idem_insert)\n\nlemma fold_union_fold_product:\n  assumes \"finite X\" and \"\\<And>\\<Psi> \\<psi>. \\<Psi> \\<in> X \\<Longrightarrow> \\<psi> \\<in> fset \\<Psi> \\<Longrightarrow> dnf \\<psi> = {{|\\<psi>|}}\"\n  shows \"Finite_Set.fold (\\<lambda>x. (\\<union>) (Finite_Set.fold (\\<lambda>\\<phi>. (\\<otimes>) (dnf \\<phi>)) {{||}} (fset x))) {} X = X\" (is \"?lhs = X\")\nproof -\n  from assms have \"?lhs = Finite_Set.fold (\\<lambda>x. (\\<union>) (Finite_Set.fold (\\<lambda>\\<phi>. (\\<otimes>) {{|\\<phi>|}}) {{||}} (fset x))) {} X\"\n  proof2 (induction X rule: finite_induct)\n    case (insert \\<Phi> X)\n\n    from insert.prems have 1: \"\\<And>\\<Psi> \\<psi>. \\<lbrakk>\\<Psi> \\<in> X; \\<psi> \\<in> fset \\<Psi>\\<rbrakk> \\<Longrightarrow> dnf \\<psi> = {{|\\<psi>|}}\"\n      by force\n\n    from insert.prems have \"Finite_Set.fold (\\<lambda>\\<phi>. (\\<otimes>) (dnf \\<phi>)) {{||}} (fset \\<Phi>) = Finite_Set.fold (\\<lambda>\\<phi>. (\\<otimes>) {{|\\<phi>|}}) {{||}} (fset \\<Phi>)\"\n      apply2 (induction \\<Phi>) by (force simp: notin_fset)+\n\n    with insert 1 show ?case\n      by simp\n  qed simp\n\n  with \\<open>finite X\\<close> show ?thesis\n    unfolding fold_product by (metis fset_to_fset fold_union)\nqed\n\nlemma dnf_ltln_of_dnf_min_dnf:\n  \"dnf (ltln_of_dnf (min_dnf \\<phi>)) = min_dnf \\<phi>\"\nproof -\n  have 1: \"finite (And\\<^sub>n ` fset ` min_dnf \\<phi>)\"\n    using min_dnf_finite by blast\n\n  have 2: \"inj_on And\\<^sub>n (fset ` min_dnf \\<phi>)\"\n    by (metis (mono_tags, lifting) And\\<^sub>n_inj f_inv_into_f fset inj_onI inj_on_contraD)\n\n  have 3: \"inj_on fset (min_dnf \\<phi>)\"\n    by (meson fset_inject inj_onI)\n\n  show ?thesis\n    unfolding ltln_of_dnf_def\n    unfolding Or\\<^sub>n_dnf[OF 1]\n    unfolding fold_image[OF 2]\n    unfolding fold_image[OF 3]\n    unfolding comp_def\n    unfolding And\\<^sub>n_dnf[OF finite_fset]\n    by (metis fold_union_fold_product min_dnf_finite min_dnf_atoms_dnf)\nqed\n\nlemma min_dnf_subst:\n  \"min_set (subst_dnf (min_dnf \\<phi>) m) = min_dnf (subst \\<phi> m)\" (is \"?lhs = ?rhs\")\nproof -\n  let ?\\<phi>' = \"ltln_of_dnf (min_dnf \\<phi>)\"\n\n  have \"?lhs = min_set (subst_dnf (dnf ?\\<phi>') m)\"\n    unfolding dnf_ltln_of_dnf_min_dnf ..\n\n  also have \"\\<dots> = min_dnf (subst ?\\<phi>' m)\"\n    unfolding subst_dnf_dnf ..\n\n  also have \"\\<dots> = min_dnf (subst \\<phi> m)\"\n    using ltl_prop_equiv_min_dnf ltln_of_dnf_prop_equiv subst_respects_ltl_prop_entailment(2) by blast\n\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/Evaluation/LTL/Disjunctive_Normal_Form.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8824278602705731, "lm_q2_score": 0.8397339616560072, "lm_q1q2_score": 0.741004642980642}}
{"text": "theory Powers3844\n\nimports Main Kyber_Values\n\nbegin\nsection \\<open>Checking Powers of Root of Unity\\<close>\ntext \\<open>In order to check, that $3844$ is indeed a root of unity, we need to calculate all powers \nand show that they are not equal to one.\\<close>\nfun fast_exp_7681 ::\" int \\<Rightarrow> nat \\<Rightarrow> int\" where\n\"fast_exp_7681 x 0 = 1\" |\n\"fast_exp_7681 x (Suc e) = (x * (fast_exp_7681 x e)) mod 7681\"\n\nlemma list_all_fast_exp_7681: \n\"list_all (\\<lambda>l. fast_exp_7681 (3844::int) l \\<noteq> 1) [1..<256]\"\nby (subst upt_conv_Cons, simp, subst list_all_simps(1), intro conjI, eval)+ \n   force\n\nlemma fast_exp_7681_to_mod_ring: \n\"fast_exp_7681 x e = to_int_mod_ring ((of_int_mod_ring x :: fin7681 mod_ring)^e)\"\nproof (induct e arbitrary: x rule: fast_exp_7681.induct)\n  case (2 x e)\n  then show ?case \n  by (metis Suc_inject fast_exp_7681.elims kyber7681.CARD_a kyber7681.of_int_mod_ring_mult \n    nat.discI of_int_mod_ring.rep_eq of_int_mod_ring_to_int_mod_ring power_Suc \n    to_int_mod_ring.rep_eq)\nqed auto\n\nlemma fast_exp_7681_less256:\nassumes \"0<l\" \"l<256\"\nshows \"fast_exp_7681 3844 l \\<noteq> 1\"\nusing list_all_fast_exp_7681 assms \nby (smt (verit, ccfv_threshold) Ball_set One_nat_def atLeastLessThan_iff \n  bot_nat_0.not_eq_extremum fast_exp_7681.elims less_Suc_numeral less_nat_zero_code \n  not_less numeral_One numeral_less_iff set_upt)\n\nlemma powr_less256:\nassumes \"0<l\" \"l<256\"\nshows \"(3844::fin7681 mod_ring)^l \\<noteq> 1\"\nusing fast_exp_7681_less256[OF assms] unfolding fast_exp_7681_to_mod_ring\nby (metis of_int_numeral of_int_of_int_mod_ring to_int_mod_ring_hom.hom_one)\n\n\nend", "meta": {"author": "ThikaXer", "repo": "Kyber_Formalization", "sha": "a1832e7b8e29852c35f252b5703083f912cfe5ff", "save_path": "github-repos/isabelle/ThikaXer-Kyber_Formalization", "path": "github-repos/isabelle/ThikaXer-Kyber_Formalization/Kyber_Formalization-a1832e7b8e29852c35f252b5703083f912cfe5ff/Powers3844.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513842182777, "lm_q2_score": 0.8267118004748677, "lm_q1q2_score": 0.7409415955251848}}
{"text": "section \\<open>java.lang.Long\\<close>\n\ntext \\<open>\nUtility functions from the Java Long class that Graal occasionally makes use of.\n\\<close>\n\ntheory JavaLong\n  imports JavaWords\n          \"HOL-Library.FSet\"\nbegin\n\nlemma negative_all_set_32:\n  \"n < 32 \\<Longrightarrow> bit (-1::int32) n\"\n  apply transfer by auto\n\n(* TODO: better handle empty *)\ndefinition MaxOrNeg :: \"nat set \\<Rightarrow> int\" where\n  \"MaxOrNeg s = (if s = {} then -1 else Max s)\"\n\ndefinition MinOrHighest :: \"nat set \\<Rightarrow> nat \\<Rightarrow> nat\" where\n  \"MinOrHighest s m = (if s = {} then m else Min s)\"\n\nlemma MaxOrNegEmpty:\n  \"MaxOrNeg s = -1 \\<longleftrightarrow> s = {}\"\n  unfolding MaxOrNeg_def by auto\n\n\nsubsection Long.highestOneBit\n\n(* This is a different definition to Long.highestOneBit *)\ndefinition highestOneBit :: \"('a::len) word \\<Rightarrow> int\" where\n  \"highestOneBit v = MaxOrNeg {n. bit v n}\"\n\nlemma highestOneBitInvar:\n  \"highestOneBit v = j \\<Longrightarrow> (\\<forall>i::nat. (int i > j \\<longrightarrow> \\<not> (bit v i)))\"\n  apply (induction \"size v\")\n  apply simp\n  by (smt (verit) MaxOrNeg_def Max_ge empty_iff finite_bit_word highestOneBit_def mem_Collect_eq of_nat_mono)\n\n\nlemma highestOneBitNeg:\n  \"highestOneBit v = -1 \\<longleftrightarrow> v = 0\"\n  unfolding highestOneBit_def MaxOrNeg_def\n  by (metis Collect_empty_eq_bot bit_0_eq bit_word_eqI int_ops(2) negative_eq_positive one_neq_zero)\n\nlemma higherBitsFalse:\n  fixes v :: \"'a :: len word\"\n  shows \"i > size v \\<Longrightarrow> \\<not> (bit v i)\"\n  by (simp add: bit_word.rep_eq size_word.rep_eq)\n\n\nlemma highestOneBitN:\n  assumes \"bit v n\"\n  assumes \"\\<forall>i::nat. (int i > n \\<longrightarrow> \\<not> (bit v i))\"\n  shows \"highestOneBit v = n\"\n  unfolding highestOneBit_def MaxOrNeg_def\n  by (metis Max_ge Max_in all_not_in_conv assms(1) assms(2) finite_bit_word mem_Collect_eq of_nat_less_iff order_less_le)\n\nlemma highestOneBitSize:\n  assumes \"bit v n\"\n  assumes \"n = size v\"\n  shows \"highestOneBit v = n\"\n  by (metis assms(1) assms(2) not_bit_length wsst_TYs(3))\n\nlemma highestOneBitMax:\n  \"highestOneBit v < size v\"\n  unfolding highestOneBit_def MaxOrNeg_def\n  using higherBitsFalse\n  by (simp add: bit_imp_le_length size_word.rep_eq)\n\nlemma highestOneBitAtLeast:\n  assumes \"bit v n\"\n  shows \"highestOneBit v \\<ge> n\"\nproof (induction \"size v\")\n  case 0\n  then show ?case by simp\nnext\n  case (Suc x)\n  then have \"\\<forall>i. bit v i \\<longrightarrow> i < Suc x\"\n    by (simp add: bit_imp_le_length wsst_TYs(3))\n  then show ?case\n    unfolding highestOneBit_def MaxOrNeg_def\n    using assms by auto\nqed\n\nlemma highestOneBitElim:\n  \"highestOneBit v = n\n     \\<Longrightarrow> ((n = -1 \\<and> v = 0) \\<or> (n \\<ge> 0 \\<and> bit v n))\"\n  unfolding highestOneBit_def MaxOrNeg_def\n  by (metis Max_in finite_bit_word le0 le_minus_one_simps(3) mem_Collect_eq of_nat_0_le_iff of_nat_eq_iff)\n\n\ntext \\<open>A recursive implementation of highestOneBit that is suitable for code generation.\\<close>\n\nfun highestOneBitRec :: \"nat \\<Rightarrow> ('a::len) word \\<Rightarrow> int\" where\n  \"highestOneBitRec n v =\n    (if bit v n then n \n     else if n = 0 then -1\n     else highestOneBitRec (n - 1) v)\"\n\nlemma highestOneBitRecTrue:\n  \"highestOneBitRec n v = j \\<Longrightarrow> j \\<ge> 0 \\<Longrightarrow> bit v j\"\nproof (induction \"n\")\n  case 0\n  then show ?case\n    by (metis diff_0 highestOneBitRec.simps leD of_nat_0_eq_iff of_nat_0_le_iff zle_diff1_eq) \nnext\n  case (Suc n)\n  then show ?case\n    by (metis diff_Suc_1 highestOneBitRec.elims nat.discI nat_int) \nqed\n\nlemma highestOneBitRecN:\n  assumes \"bit v n\"\n  shows \"highestOneBitRec n v = n\"\n  by (simp add: assms)\n\nlemma highestOneBitRecMax:\n  \"highestOneBitRec n v \\<le> n\"\n  by (induction n; simp)\n\nlemma highestOneBitRecElim:\n  assumes \"highestOneBitRec n v = j\"\n  shows \"((j = -1 \\<and> v = 0) \\<or> (j \\<ge> 0 \\<and> bit v j))\"\n  using assms highestOneBitRecTrue by blast\n\nlemma highestOneBitRecZero:\n  \"v = 0 \\<Longrightarrow> highestOneBitRec (size v) v = -1\"\n  by (induction rule: \"highestOneBitRec.induct\"; simp)\n\nlemma highestOneBitRecLess:\n  assumes \"\\<not> bit v n\"\n  shows \"highestOneBitRec n v = highestOneBitRec (n - 1) v\"\n  using assms by force\n\n\ntext \\<open>Some lemmas that use masks to restrict highestOneBit\n  and relate it to highestOneBitRec.\\<close>\n\nlemma highestOneBitMask:\n  assumes \"size v = n\"\n  shows \"highestOneBit v = highestOneBit (and v (mask n))\"\n  by (metis assms dual_order.refl lt2p_lem mask_eq_iff size_word.rep_eq)\n\nlemma maskSmaller:\n  fixes v :: \"'a :: len word\"\n  assumes \"\\<not> bit v n\"\n  shows \"and v (mask (Suc n)) = and v (mask n)\" \n  unfolding bit_eq_iff\n  by (metis assms bit_and_iff bit_mask_iff less_Suc_eq) \n\nlemma highestOneBitSmaller:\n  assumes \"size v = Suc n\"\n  assumes \"\\<not> bit v n\"\n  shows \"highestOneBit v = highestOneBit (and v (mask n))\"\n  by (metis assms highestOneBitMask maskSmaller)\n\nlemma highestOneBitRecMask:\n  shows \"highestOneBit (and v (mask (Suc n))) = highestOneBitRec n v\"\nproof (induction n)\n  case 0\n  then show ?case\n    by (smt (verit, ccfv_SIG) Word.mask_Suc_0 and_mask_lt_2p and_nonnegative_int_iff bit_1_iff bit_and_iff highestOneBitN highestOneBitNeg highestOneBitRec.simps mask_eq_exp_minus_1 of_int_0 uint_1_eq uint_and word_and_def) \nnext\n  case (Suc n)\n  then show ?case \n  proof (cases \"bit v (Suc n)\")\n    case True\n    have 1: \"highestOneBitRec (Suc n) v = Suc n\"\n      by (simp add: True)\n    have \"\\<forall>i::nat. (int i > (Suc n) \\<longrightarrow> \\<not> (bit (and v (mask (Suc (Suc n)))) i))\"\n      by (simp add: bit_and_iff bit_mask_iff)\n    then have 2: \"highestOneBit (and v (mask (Suc (Suc n)))) = Suc n\"\n      using True highestOneBitN\n      by (metis bit_take_bit_iff lessI take_bit_eq_mask) \n    then show ?thesis \n      using 1 2 by auto\n  next\n    case False\n    then show ?thesis\n      by (simp add: Suc maskSmaller) \n  qed\nqed\n\n\ntext \\<open>Finally - we can use the mask lemmas to relate highestOneBitRec to its spec.\\<close>\n\nlemma highestOneBitImpl[code]:\n  \"highestOneBit v = highestOneBitRec (size v) v\"\n  by (metis highestOneBitMask highestOneBitRecMask maskSmaller not_bit_length wsst_TYs(3))\n\n\nlemma \"highestOneBit (0x5 :: int8) = 2\" by code_simp\n\n\n\nsubsection \\<open>Long.lowestOneBit\\<close>\n\ndefinition lowestOneBit :: \"('a::len) word \\<Rightarrow> nat\" where\n  \"lowestOneBit v = MinOrHighest {n . bit v n} (size v)\"\n\nlemma max_bit: \"bit (v::('a::len) word) n \\<Longrightarrow> n < size v\"\n  by (simp add: bit_imp_le_length size_word.rep_eq)\n\nlemma max_set_bit: \"MaxOrNeg {n . bit (v::('a::len) word) n} < Nat.size v\"\n  using max_bit unfolding MaxOrNeg_def\n  by force\n\n\nsubsection \\<open>Long.numberOfLeadingZeros\\<close>\n\ndefinition numberOfLeadingZeros :: \"('a::len) word \\<Rightarrow> nat\" where\n  \"numberOfLeadingZeros v = nat (Nat.size v - highestOneBit v - 1)\"\n\nlemma MaxOrNeg_neg: \"MaxOrNeg {} = -1\"\n  by (simp add: MaxOrNeg_def)\n\nlemma MaxOrNeg_max: \"s \\<noteq> {} \\<Longrightarrow> MaxOrNeg s = Max s\"\n  by (simp add: MaxOrNeg_def)\n\nlemma zero_no_bits:\n  \"{n . bit 0 n} = {}\"\n  by simp\n\nlemma \"highestOneBit (0::64 word) = -1\"\n  by (simp add: MaxOrNeg_neg highestOneBit_def)\n\nlemma \"numberOfLeadingZeros (0::64 word) = 64\"\n  unfolding numberOfLeadingZeros_def using  MaxOrNeg_neg highestOneBit_def size64\n  by (smt (verit) nat_int zero_no_bits)\n\nlemma highestOneBit_top: \"Max {highestOneBit (v::64 word)} < 64\"\n  unfolding highestOneBit_def\n  by (metis Max_singleton int_eq_iff_numeral max_set_bit size64)\n\nlemma numberOfLeadingZeros_top: \"Max {numberOfLeadingZeros (v::64 word)} \\<le> 64\"\n  unfolding numberOfLeadingZeros_def\n  using size64\n  by (simp add: MaxOrNeg_def highestOneBit_def nat_le_iff)\n\nlemma numberOfLeadingZeros_range: \"0 \\<le> numberOfLeadingZeros a \\<and> numberOfLeadingZeros a \\<le> Nat.size a\"\n  unfolding numberOfLeadingZeros_def\n  using MaxOrNeg_def highestOneBit_def nat_le_iff\n  by (smt (verit) bot_nat_0.extremum int_eq_iff)\n\nlemma leadingZerosAddHighestOne: \"numberOfLeadingZeros v + highestOneBit v = Nat.size v - 1\"\n  unfolding numberOfLeadingZeros_def highestOneBit_def\n  using MaxOrNeg_def int_nat_eq int_ops(6) max_bit order_less_irrefl by fastforce\n\nsubsection \\<open>Long.numberOfTrailingZeros\\<close>\n\ndefinition numberOfTrailingZeros :: \"('a::len) word \\<Rightarrow> nat\" where\n  \"numberOfTrailingZeros v = lowestOneBit v\"\n\nlemma lowestOneBit_bot: \"lowestOneBit (0::64 word) = 64\"\n  unfolding lowestOneBit_def MinOrHighest_def\n  by (simp add: size64)\n\nlemma bit_zero_set_in_top: \"bit (-1::'a::len word) 0\"\n  by auto\n\nlemma nat_bot_set: \"(0::nat) \\<in> xs \\<longrightarrow> (\\<forall>x \\<in> xs . 0 \\<le> x)\"\n  by fastforce\n\nlemma \"numberOfTrailingZeros (0::64 word) = 64\"\n  unfolding numberOfTrailingZeros_def\n  using lowestOneBit_bot by simp\n\nsubsection \\<open>Long.bitCount\\<close>\n\ndefinition bitCount :: \"('a::len) word \\<Rightarrow> nat\" where\n  \"bitCount v = card {n . bit v n}\"\n\nlemma \"bitCount 0 = 0\"\n  unfolding bitCount_def\n  by (metis card.empty zero_no_bits)\n\nsubsection \\<open>Long.zeroCount\\<close>\n\ndefinition zeroCount :: \"('a::len) word \\<Rightarrow> nat\" where\n  \"zeroCount v = card {n. n < Nat.size v \\<and> \\<not>(bit v n)}\"\n\nlemma zeroCount_finite: \"finite {n. n < Nat.size v \\<and> \\<not>(bit v n)}\"\n  using finite_nat_set_iff_bounded by blast\n\nlemma negone_set:\n  \"bit (-1::('a::len) word) n \\<longleftrightarrow> n < LENGTH('a)\"\n  by simp\n\nlemma negone_all_bits:\n  \"{n . bit (-1::('a::len) word) n} = {n . 0 \\<le> n \\<and> n < LENGTH('a)}\"\n  using negone_set\n  by auto\n\nlemma bitCount_finite:\n  \"finite {n . bit (v::('a::len) word) n}\"\n  by simp\n\nlemma card_of_range:\n  \"x = card {n . 0 \\<le> n \\<and> n < x}\"\n  by simp\n\nlemma range_of_nat:\n  \"{(n::nat) . 0 \\<le> n \\<and> n < x} = {n . n < x}\"\n  by simp\n\nlemma finite_range:\n  \"finite {n::nat . n < x}\"\n  by simp\n\n\nlemma range_eq:\n  fixes x y :: nat\n  shows \"card {y..<x} = card {y<..x}\"\n  using card_atLeastLessThan card_greaterThanAtMost by presburger\n\nlemma card_of_range_bound:\n  fixes x y :: nat\n  assumes \"x > y\"\n  shows \"x - y = card {n . y < n \\<and> n \\<le> x}\"\nproof -\n  have finite: \"finite {n . y \\<le> n \\<and> n < x}\"\n    by auto\n  have nonempty: \"{n . y \\<le> n \\<and> n < x} \\<noteq> {}\"\n    using assms by blast\n  have simprep: \"{n . y < n \\<and> n \\<le> x} = {y<..x}\"\n    by auto\n  have \"x - y = card {y<..x}\"\n    by auto\n  then show ?thesis\n    unfolding simprep by blast\nqed\n\nlemma \"bitCount (-1::('a::len) word) = LENGTH('a)\"\n  unfolding bitCount_def using card_of_range\n  by (metis (no_types, lifting) Collect_cong negone_all_bits)\n\nlemma bitCount_range:\n  fixes n :: \"('a::len) word\"\n  shows \"0 \\<le> bitCount n \\<and> bitCount n \\<le> Nat.size n\"\n  unfolding bitCount_def\n  by (metis atLeastLessThan_iff bot_nat_0.extremum max_bit mem_Collect_eq subsetI subset_eq_atLeast0_lessThan_card)\n\nlemma zerosAboveHighestOne:\n  \"n > highestOneBit a \\<Longrightarrow> \\<not>(bit a n)\"\n  unfolding highestOneBit_def MaxOrNeg_def\n  by (metis (mono_tags, opaque_lifting) Collect_empty_eq Max_ge finite_bit_word less_le_not_le mem_Collect_eq of_nat_le_iff)\n\nlemma zerosBelowLowestOne:\n  assumes \"n < lowestOneBit a\"\n  shows \"\\<not>(bit a n)\"\nproof (cases \"{i. bit a i} = {}\")\n  case True\n  then show ?thesis by simp\nnext\n  case False\n  have \"n < Min (Collect (bit a)) \\<Longrightarrow> \\<not> bit a n\"\n    using False by auto\n  then show ?thesis\n    by (metis False MinOrHighest_def assms lowestOneBit_def)\nqed\n\nlemma union_bit_sets:\n  fixes a :: \"('a::len) word\"\n  shows \"{n . n < Nat.size a \\<and> bit a n} \\<union> {n . n < Nat.size a \\<and> \\<not>(bit a n)} = {n . n < Nat.size a}\"\n  by fastforce\n\nlemma disjoint_bit_sets:\n  fixes a :: \"('a::len) word\"\n  shows \"{n . n < Nat.size a \\<and> bit a n} \\<inter> {n . n < Nat.size a \\<and> \\<not>(bit a n)} = {}\"\n  by blast\n\nlemma qualified_bitCount:\n  \"bitCount v = card {n . n < Nat.size v \\<and> bit v n}\"\n  by (metis (no_types, lifting) Collect_cong bitCount_def max_bit)\n\nlemma card_eq:\n  assumes \"finite x \\<and> finite y \\<and> finite z\"\n  assumes \"x \\<union> y = z\"\n  assumes \"y \\<inter> x = {}\"\n  shows \"card z - card y = card x\"\n  using assms add_diff_cancel_right' card_Un_disjoint\n  by (metis inf.commute)\n\nlemma card_add:\n  assumes \"finite x \\<and> finite y \\<and> finite z\"\n  assumes \"x \\<union> y = z\"\n  assumes \"y \\<inter> x = {}\"\n  shows \"card x + card y = card z\"\n  using assms card_Un_disjoint\n  by (metis inf.commute)\n\n\nlemma card_add_inverses:\n  assumes \"finite {n. Q n \\<and> \\<not>(P n)} \\<and> finite {n. Q n \\<and> P n} \\<and> finite {n. Q n}\"\n  shows \"card {n. Q n \\<and> P n} + card {n. Q n \\<and> \\<not>(P n)} = card {n. Q n}\"\n  apply (rule card_add)\n  using assms apply simp\n  apply auto[1]\n  by auto\n\nlemma ones_zero_sum_to_width:\n  \"bitCount a + zeroCount a = Nat.size a\"\nproof -\n  have add_cards: \"card {n. (\\<lambda>n. n < size a) n \\<and> (bit a n)} + card {n. (\\<lambda>n. n < size a) n \\<and> \\<not>(bit a n)} = card {n. (\\<lambda>n. n < size a) n}\"\n    apply (rule card_add_inverses) by simp\n  then have \"... = Nat.size a\"\n    by auto\n then show ?thesis \n    unfolding bitCount_def zeroCount_def using max_bit\n    by (metis (mono_tags, lifting) Collect_cong add_cards)\nqed\n\nlemma intersect_bitCount_helper:\n  \"card {n . n < Nat.size a} - bitCount a = card {n . n < Nat.size a \\<and> \\<not>(bit a n)}\"\nproof -\n  have size_def: \"Nat.size a = card {n . n < Nat.size a}\"\n    using card_of_range by simp\n  have bitCount_def: \"bitCount a = card {n . n < Nat.size a \\<and> bit a n}\"\n    using qualified_bitCount by auto\n  have disjoint: \"{n . n < Nat.size a \\<and> bit a n} \\<inter> {n . n < Nat.size a \\<and> \\<not>(bit a n)} = {}\"\n    using disjoint_bit_sets by auto\n  have union: \"{n . n < Nat.size a \\<and> bit a n} \\<union> {n . n < Nat.size a \\<and> \\<not>(bit a n)} = {n . n < Nat.size a}\"\n    using union_bit_sets by auto\n  show ?thesis\n    unfolding bitCount_def\n    apply (rule card_eq)\n    using finite_range apply simp\n    using union apply blast\n    using disjoint by simp\nqed\n\nlemma intersect_bitCount:\n  \"Nat.size a - bitCount a = card {n . n < Nat.size a \\<and> \\<not>(bit a n)}\"\n  using card_of_range intersect_bitCount_helper by auto\n\nhide_fact intersect_bitCount_helper\n\nend\n\n", "meta": {"author": "uqcyber", "repo": "veriopt-releases", "sha": "4ffab3c91bbd699772889dbf263bb6d2582256d7", "save_path": "github-repos/isabelle/uqcyber-veriopt-releases", "path": "github-repos/isabelle/uqcyber-veriopt-releases/veriopt-releases-4ffab3c91bbd699772889dbf263bb6d2582256d7/Graph/JavaLong.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8962513675912912, "lm_q2_score": 0.8267118004748677, "lm_q1q2_score": 0.7409415817794588}}
{"text": "theory Karatsuba\n  imports \"Auto2_HOL.Auto2_Main\" Berlekamp_Zassenhaus.Karatsuba_Multiplication\nbegin\n\nsection \\<open>List version of polynomial operations\\<close>\n\nfun coeffs_smult :: \"'a::comm_ring_1 \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where\n  \"coeffs_smult m [] = []\"\n| \"coeffs_smult m (x # xs) = m * x # coeffs_smult m xs\"\nsetup \\<open>fold add_rewrite_rule @{thms coeffs_smult.simps}\\<close>\n\nlemma coeffs_smult [rewrite]: \"Poly (coeffs_smult m xs) = smult m (Poly xs)\"\n  by (induct xs, auto)\n\nlemma coeffs_smult_length [rewrite_arg]:\n  \"length (coeffs_smult m xs) = length xs\"\n@proof @induct xs @qed\n\nlemma coeffs_smult_nth [rewrite]:\n  \"i < length (coeffs_smult m xs) \\<Longrightarrow> coeffs_smult m xs ! i = m * xs ! i\"\n@proof @induct xs arbitrary i @qed\n\nlemma coeffs_smult_one [rewrite]:\n  \"coeffs_smult 1 xs = xs\" by auto2\n\ndefinition coeffs_plus :: \"'a::comm_ring_1 list \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" (infixl \"+\\<^sub>l\" 65) where\n  \"xs +\\<^sub>l ys = list (\\<lambda>i. nth_default 0 xs i + nth_default 0 ys i) (max (length xs) (length ys))\"\n\nlemma coeffs_plus_length [rewrite_arg]:\n  \"length ys \\<le> length xs \\<Longrightarrow> length (xs +\\<^sub>l ys) = length xs\"\n@proof @unfold \"xs +\\<^sub>l ys\" @qed\n\nlemma coeffs_plus_length' [rewrite_arg]:\n  \"length xs \\<le> length ys \\<Longrightarrow> length (xs +\\<^sub>l ys) = length ys\"\n@proof @unfold \"xs +\\<^sub>l ys\" @qed\n\nlemma coeffs_plus_Poly [rewrite]: \"Poly (f1 +\\<^sub>l f0) = Poly f1 + Poly f0\" \nproof (rule poly_eqI, unfold poly_of_list_def coeff_add coeff_Poly)\n  fix i\n  show \"nth_default 0 (f1 +\\<^sub>l f0) i = nth_default 0 f1 i + nth_default 0 f0 i\" \n    unfolding coeffs_plus_def\n    by (simp add: list_length list_nth max_def nth_default_def)\nqed\n\ndefinition coeffs_minus :: \"'a::comm_ring_1 list \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" (infixl \"-\\<^sub>l\" 65) where\n  \"xs -\\<^sub>l ys = list (\\<lambda>i. nth_default 0 xs i - nth_default 0 ys i) (max (length xs) (length ys))\"\n\nlemma coeffs_minus_length [rewrite_arg]:\n  \"length ys \\<le> length xs \\<Longrightarrow> length (xs -\\<^sub>l ys) = length xs\"\n@proof @unfold \"xs -\\<^sub>l ys\" @qed\n\nlemma coeffs_minus_Poly [rewrite]: \"Poly (f1 -\\<^sub>l f0) = Poly f1 - Poly f0\" \nproof (rule poly_eqI, unfold poly_of_list_def coeff_diff coeff_Poly)\n  fix i\n  show \"nth_default 0 (f1 -\\<^sub>l f0) i = nth_default 0 f1 i - nth_default 0 f0 i\" \n    unfolding coeffs_minus_def\n    by (simp add: list_length list_nth max_def nth_default_def)\nqed\n\nlemma arith1 [rewrite_back]: \"(a::'a::comm_ring_1) - b = a + (-1) * b\" by simp\nlemma mult0_right [rewrite]: \"(m::('a::comm_ring_1)) * 0 = 0\" by auto\nsetup \\<open>add_rewrite_rule @{thm nth_default_def}\\<close>\n\nlemma coeffs_plus_neg_is_minus [rewrite_back]:\n  \"xs +\\<^sub>l coeffs_smult (-1) ys = xs -\\<^sub>l ys\"\n@proof\n  @unfold \"xs -\\<^sub>l ys\"\n  @unfold \"xs +\\<^sub>l coeffs_smult (-1) ys\"\n  @have \"length (xs -\\<^sub>l ys) = length (xs +\\<^sub>l coeffs_smult (-1) ys)\"\n  @have \"\\<forall>i<length (xs -\\<^sub>l ys). (xs -\\<^sub>l ys) ! i = (xs +\\<^sub>l coeffs_smult (-1) ys) ! i\" @with\n    @let \"x = nth_default 0 xs i\"\n    @let \"y = nth_default 0 ys i\"\n    @have \"(xs -\\<^sub>l ys) ! i = x - y\"\n    @have \"(xs +\\<^sub>l coeffs_smult (-1) ys) ! i = x + (-1) * y\"\n  @end\n@qed\n\ndefinition coeffs_monom_mult :: \"nat \\<Rightarrow> 'a::comm_ring_1 list \\<Rightarrow> 'a list\" where\n  \"coeffs_monom_mult n xs = replicate n 0 @ xs\"\n\nlemma coeffs_mono_mult [rewrite]:\n  \"Poly (coeffs_monom_mult n xs) = monom_mult n (Poly xs)\"\nproof (cases \"Poly xs = 0\")\n  case True\n  then show ?thesis by (auto simp: coeffs_monom_mult_def monom_mult_def Poly_append)\nnext\n  case False\n  then have N: \"coeffs (Poly xs) \\<noteq> []\" and\n      N2: \"xs \\<noteq> []\"\n    by (auto simp add: coeffs_eq_iff)  \n  have \"monom_mult n (Poly xs) = Poly (coeffs (monom_mult n (Poly xs)))\"\n    by simp\n  also have \"\\<dots> = Poly (let xs = coeffs (Poly xs) in\n    if xs = [] then xs else replicate n 0 @ xs)\" unfolding monom_mult_code by simp\n  also have \"\\<dots> = Poly (replicate n 0 @ coeffs (Poly xs))\"\n    using N by presburger\n  also have \"\\<dots> = poly_of_list (coeffs_monom_mult n xs)\"\n    unfolding coeffs_monom_mult_def using N2 apply auto\n    by (metis Poly_append Poly_coeffs coeffs_Poly)\n  finally show ?thesis by simp\nqed\n\nlemma length_coeffs_monom_mult [rewrite_arg]:\n  \"length (coeffs_monom_mult n as) = n + length as\"\n@proof @unfold \"coeffs_monom_mult n as\" @qed\n\nlemma coeffs_monom_mult_0 [rewrite]: \"coeffs_monom_mult 0 xs = xs\"\n@proof @unfold \"coeffs_monom_mult 0 xs\" @qed\n\nsection \\<open>General addition function\\<close>\n\ndefinition coeffs_shift_plus :: \"nat \\<Rightarrow> 'a::comm_ring_1 \\<Rightarrow> 'a list \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where [rewrite]:\n  \"coeffs_shift_plus s m xs ys = list (\\<lambda>i.\n     if i < s then ys ! i else if i \\<ge> s + length xs then ys ! i\n     else ys ! i + m * xs ! (i - s)) (length ys)\"\nsetup \\<open>register_wellform_data (\"coeffs_shift_plus s m xs ys\", [\"s + length xs \\<le> length ys\"])\\<close>\n\nlemma coeffs_shift_plus_correct [rewrite]:\n  \"s + length xs \\<le> length ys \\<Longrightarrow>\n   coeffs_shift_plus s m xs ys = ys +\\<^sub>l coeffs_smult m (coeffs_monom_mult s xs)\"\n@proof\n  @unfold \"ys +\\<^sub>l coeffs_smult m (coeffs_monom_mult s xs)\"\n  @unfold \"coeffs_monom_mult s xs\"\n@qed\n\nlemma smult_monom_mult' [rewrite]: \"smult a (monom_mult n q) = monom a n * q\"\n  by (metis monom_mult_unfold(1) mult.right_neutral smult_monom_mult)\n\nlemma coeffs_shift_plus_Poly [rewrite]:\n  \"s + length xs \\<le> length ys \\<Longrightarrow>\n   Poly (coeffs_shift_plus s m xs ys) = Poly ys + monom m s * Poly xs\" by auto2\n\nlemma coeffs_shift_plus_1 [rewrite]:\n  \"s + length xs \\<le> length ys \\<Longrightarrow>\n   coeffs_shift_plus s 1 xs ys = ys +\\<^sub>l coeffs_monom_mult s xs\" by auto2\n\nlemma coeffs_shift_minus_1 [rewrite]:\n  \"0 + length xs \\<le> length ys \\<Longrightarrow>\n   coeffs_shift_plus 0 (-1) xs ys = ys -\\<^sub>l xs\" by auto2\n\nfun coeffs_shift_add_array :: \"nat \\<Rightarrow> 'a::comm_ring_1 \\<Rightarrow> 'a list \\<Rightarrow> 'a list \\<Rightarrow> nat \\<Rightarrow> 'a list\" where\n  \"coeffs_shift_add_array s m xs ys 0 = ys\"\n| \"coeffs_shift_add_array s m xs ys (Suc n) =\n   (let ys' = coeffs_shift_add_array s m xs ys n in\n      list_update ys' (s + n) (m * xs ! n + ys' ! (s + n)))\"\nsetup \\<open>fold add_rewrite_rule @{thms coeffs_shift_add_array.simps}\\<close>\n\nlemma coeffs_shift_add_array_length [rewrite_arg]:\n  \"n \\<le> length xs \\<Longrightarrow> s + length xs \\<le> length ys \\<Longrightarrow>\n   length (coeffs_shift_add_array s m xs ys n) = length ys\"\n@proof @induct n @qed\n\nlemma coeffs_shift_add_array_ind [rewrite]:\n  \"n \\<le> length xs \\<Longrightarrow> s + length xs \\<le> length ys \\<Longrightarrow> i < length ys \\<Longrightarrow>\n   coeffs_shift_add_array s m xs ys n ! i = (if i < s + n then coeffs_shift_plus s m xs ys ! i else ys ! i)\"\n@proof @induct n @with\n  @subgoal \"n = 0\" @case \"i < s\" @endgoal\n  @subgoal \"n = Suc n\"\n    @case \"i < s + Suc n\" @with\n      @case \"i < s + n\" @case \"i = s + n\"\n      @have \"s + Suc n = Suc (s + n)\"\n    @end\n  @endgoal @end\n@qed\n\nlemma coeffs_shift_add_array [rewrite]:\n  \"s + length xs \\<le> length ys \\<Longrightarrow>\n   coeffs_shift_add_array s m xs ys (length xs) = coeffs_shift_plus s m xs ys\" by auto2\n\nsection \\<open>Naive multiplication procedure\\<close>\n\nsetup \\<open>add_rewrite_rule @{thm Poly_snoc}\\<close>\nsetup \\<open>add_rewrite_rule @{thm Poly.simps(1)}\\<close>\nsetup \\<open>add_rewrite_rule @{thm Poly_replicate_0}\\<close>\n\nlemma ring_norm1 [resolve]: \"(a + b) * c = a * c + b * (c::'a::comm_ring_1 poly)\"\n  by (simp add: comm_semiring_class.distrib)\n\n(* Compute product by adding terms in g one-by-one. *)\nfun coeffs_prod_ind :: \"'a::comm_ring_1 list \\<Rightarrow> 'a list \\<Rightarrow> nat \\<Rightarrow> 'a list\" where\n  \"coeffs_prod_ind xs ys 0 = replicate (length xs + length ys - 1) 0\"\n| \"coeffs_prod_ind xs ys (Suc n) =\n   (let zs = coeffs_prod_ind xs ys n in\n      coeffs_shift_plus n (xs ! n) ys zs)\"\nsetup \\<open>fold add_rewrite_rule @{thms coeffs_prod_ind.simps}\\<close>\n\nlemma coeffs_prod_ind_length [rewrite_arg]:\n  \"length (coeffs_prod_ind xs ys n) = length xs + length ys - 1\"\n@proof @induct n @qed\n\nlemma poly_mult_ind [rewrite]:\n  \"length (p::'a::comm_ring_1 list) + length q \\<le> length ys \\<Longrightarrow>\n   Poly ys = Poly p * Poly q \\<Longrightarrow>\n   Poly (coeffs_shift_plus (length p) a q ys) = Poly (p @ [a]) * Poly q\" by auto2\n\nlemma coeffs_prod_correct_ind [rewrite]:\n  \"n \\<le> length xs \\<Longrightarrow>\n   Poly (coeffs_prod_ind xs ys n) = Poly (take n xs) * Poly ys\"\n@proof @induct n @with\n  @subgoal \"n = Suc n\"\n    @have \"n + length ys \\<le> length xs + length ys - 1\"\n  @endgoal @end\n@qed\n\ndefinition coeffs_prod :: \"'a::comm_ring_1 list \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where [rewrite]:\n  \"coeffs_prod xs ys = coeffs_prod_ind xs ys (length xs)\"\n\nlemma coeffs_prod_correct [rewrite]:\n  \"Poly (coeffs_prod xs ys) = Poly xs * Poly ys\" by auto2\n\nsection \\<open>Functional version of karatsuba\\<close>\n\nfun karatsuba_main_list :: \"'a::comm_ring_1 list \\<Rightarrow> 'a list \\<Rightarrow> nat \\<Rightarrow> 'a list\" where\n  \"karatsuba_main_list f g n = (\n   if n \\<le> karatsuba_lower_bound then\n     coeffs_prod f g\n   else let\n     n2 = n div 2;\n     f0 = take n2 f; f1 = drop n2 f;\n     g0 = take n2 g; g1 = drop n2 g;\n     p1 = karatsuba_main_list f1 g1 (n - n2);\n     p2 = karatsuba_main_list (f1 -\\<^sub>l f0) (g1 -\\<^sub>l g0) (n - n2);\n     p3 = karatsuba_main_list f0 g0 n2\n   in\n     coeffs_monom_mult (n2 + n2) p1 +\\<^sub>l coeffs_monom_mult n2 (p1 -\\<^sub>l p2 +\\<^sub>l p3) +\\<^sub>l p3)\"\ndeclare karatsuba_main_list.simps [simp del]\n\nlemma Poly_split_at [rewrite]:\n  \"monom_mult n (Poly (drop n f)) + Poly (take n f) = Poly f\"\n  by (metis (no_types, lifting) Lists_Thms.length_take Poly_append Poly_coeffs add.commute\n       append_take_drop_id coeffs_0_eq_Nil drop_eq_Nil le_less monom_mult_unfold mult_zero_left not_less)\n\nsetup \\<open>add_backward_prfstep @{thm div_le_mono}\\<close>\n\nlemma karatsuba_lower_bound_div [rewrite]: \"karatsuba_lower_bound div 2 = 3\"\n  by (simp add: karatsuba_lower_bound_def)\n\nlemma n_div_2_compl [resolve]: \"(n::nat) - n div 2 = (n + 1) div 2\" by linarith\n\nlemma karatsuba_basic [resolve]:\n  \"n > karatsuba_lower_bound \\<Longrightarrow> n div 2 \\<ge> 1\"\n@proof @have \"karatsuba_lower_bound div 2 = 3\" @qed\n\nlemma karatsuba_basic2 [resolve]:\n  \"n > karatsuba_lower_bound \\<Longrightarrow> n - n div 2 \\<ge> 1\"\n@proof @have \"n - n div 2 = (n + 1) div 2\" @qed\n\nlemma karatsuba_diff1 [resolve]:\n  \"n > karatsuba_lower_bound \\<Longrightarrow> n div 2 + n div 2 \\<ge> 1\" by auto2\n\nlemma karatsuba_diff2 [resolve]:\n  \"n > karatsuba_lower_bound \\<Longrightarrow> n \\<ge> n div 2\" by auto\n\nlemma karatsuba_diff2' [resolve]:\n  \"n > karatsuba_lower_bound \\<Longrightarrow> n > n div 2\" by auto\n\nlemma karatsuba_diff3 [resolve]:\n  \"n > karatsuba_lower_bound \\<Longrightarrow> (n - n div 2) + (n - n div 2) \\<ge> 1\" by auto2\n\nlemma karatsuba_diff4 [resolve]:\n  \"n > karatsuba_lower_bound \\<Longrightarrow> n - n div 2 < n\"\n@proof @have \"n div 2 \\<ge> 1\" @qed\n\nlemma karatsuba_diff5 [resolve]:\n  \"n > karatsuba_lower_bound \\<Longrightarrow> n div 2 \\<le> n - n div 2\" by auto\n\nsetup \\<open>add_rewrite_rule @{thm karatsuba_main_step}\\<close>\n\nlemma karatsuba_main_list_length [rewrite_arg]:\n  \"length f = n \\<Longrightarrow> length g = n \\<Longrightarrow>\n   length (karatsuba_main_list f g n) = n + n - 1\"\n@proof\n  @strong_induct n arbitrary f g\n  @case \"n \\<le> karatsuba_lower_bound\" @with\n    @unfold \"karatsuba_main_list f g n\"\n  @end\n  @let \"n2 = n div 2\"\n  @let \"f0 = take n2 f\" \"f1 = drop n2 f\"\n  @let \"g0 = take n2 g\" \"g1 = drop n2 g\"\n  @let \"p1 = karatsuba_main_list f1 g1 (n - n2)\"\n  @let \"p2 = karatsuba_main_list (f1 -\\<^sub>l f0) (g1 -\\<^sub>l g0) (n - n2)\"\n  @let \"p3 = karatsuba_main_list f0 g0 n2\"\n  @let \"res = coeffs_monom_mult (n2 + n2) p1 +\\<^sub>l coeffs_monom_mult n2 (p1 -\\<^sub>l p2 +\\<^sub>l p3) +\\<^sub>l p3\"\n  @have \"n2 \\<le> n - n2\"\n  @apply_induct_hyp \"n - n2\" f1 g1\n  @apply_induct_hyp \"n - n2\" \"f1 -\\<^sub>l f0\" \"g1 -\\<^sub>l g0\"\n  @apply_induct_hyp n2 f0 g0\n  @have \"length (coeffs_monom_mult n2 (p1 -\\<^sub>l p2 +\\<^sub>l p3)) = n + (n - n2) - 1\" @with\n    @have \"n2 + n2 - 1 \\<le> (n - n2) + (n - n2) - 1\"\n  @end\n  @have \"length (coeffs_monom_mult (n2 + n2) p1) = n + n - 1\"\n  @have \"length res = n + n - 1\" @with\n    @have \"n2 + n2 - 1 \\<le> (n - n2) + (n - n2) - 1\"\n    @have \"(n - n2) + (n - n2) - 1 \\<le> n + n - 1\"\n    @have \"n + (n - n2) - 1 \\<le> n + n - 1\"\n  @end\n  @unfold \"karatsuba_main_list f g n\"\n@qed\n\nlemma karatsuba_main_list_correct:\n  \"Poly (karatsuba_main_list f g n) = Poly f * Poly g\"\n@proof\n  @strong_induct n arbitrary f g\n  @case \"n \\<le> karatsuba_lower_bound\" @with\n    @unfold \"karatsuba_main_list f g n\"\n  @end\n  @let \"n2 = n div 2\"\n  @let \"f0 = take n2 f\" \"f1 = drop n2 f\"\n  @let \"g0 = take n2 g\" \"g1 = drop n2 g\"\n  @apply_induct_hyp \"n - n2\" f1 g1\n  @apply_induct_hyp \"n - n2\" \"f1 -\\<^sub>l f0\" \"g1 -\\<^sub>l g0\"\n  @apply_induct_hyp n2 f0 g0\n  @let \"p1 = karatsuba_main_list f1 g1 (n - n2)\"\n  @let \"p2 = karatsuba_main_list (f1 -\\<^sub>l f0) (g1 -\\<^sub>l g0) (n - n2)\"\n  @let \"p3 = karatsuba_main_list f0 g0 n2\"\n  @let \"res = coeffs_monom_mult (n2 + n2) p1 +\\<^sub>l coeffs_monom_mult n2 (p1 -\\<^sub>l p2 +\\<^sub>l p3) +\\<^sub>l p3\"\n  @have \"Poly res = monom_mult (n2 + n2) (Poly p1) + monom_mult n2 (Poly p1 - Poly p2 + Poly p3) + Poly p3\"\n  @have \"Poly res = monom_mult (n2 + n2) (Poly p1) + (monom_mult n2 (Poly p1 - Poly p2 + Poly p3) + Poly p3)\"\n  @unfold \"karatsuba_main_list f g n\"\n@qed\n\nend\n", "meta": {"author": "bzhan", "repo": "Imperative_HOL_Time", "sha": "09f9bc7a7cf177d3adf1e9ce6adae09a85ebe5ec", "save_path": "github-repos/isabelle/bzhan-Imperative_HOL_Time", "path": "github-repos/isabelle/bzhan-Imperative_HOL_Time/Imperative_HOL_Time-09f9bc7a7cf177d3adf1e9ce6adae09a85ebe5ec/Functional/Karatsuba.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.875787001374006, "lm_q2_score": 0.8459424353665381, "lm_q1q2_score": 0.7408653888046843}}
{"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_65\n  imports \"../../Test_Base\"\nbegin\n\ndatatype Nat = Z | S \"Nat\"\n\nfun t22 :: \"Nat => Nat => Nat\" where\n  \"t22 (Z) y = y\"\n| \"t22 (S z) y = S (t22 z y)\"\n\nfun t2 :: \"Nat => Nat => bool\" where\n  \"t2 x (Z) = False\"\n| \"t2 (Z) (S z) = True\"\n| \"t2 (S x2) (S z) = t2 x2 z\"\n\nlemma \"t2 i (S_t22_m_i) \\<Longrightarrow> t2 i (S S_t22_m_i)\"\n  apply(induct S_t22_m_i rule:t2.induct)\n  apply fastforce+\n  oops\n\ntheorem property0 :\n  \"t2 i (S (t22 m i))\"\n  (*\"induct m\" is the natural choice as the innermost recursive function \"t22\" is defined \n   recursively on its first argument, which is \"m\" in this case and\n   the other recursive function \"t2\" is defined recursively on the second argument, which is\n   \"t22 m i\" in this case.\n *)\n  apply(induct m)\n   apply clarsimp\n   apply(induct_tac i)(*\"i\" is the only variable*)\n    apply fastforce+\n  apply clarsimp\n    (*generalization \"t22 m i\" \\<rightarrow> \"t22_m_i\".\n      A stronger generalization \"(S (t22_m_i))\" \\<rightarrow> \"S_t22_m_i\" would be less optimal,\n      since it blocks Isabelle using pattern-matching on \"S\" for \"t2.simps\"(?) *)\n  apply(subgoal_tac \"\\<And>t22_m_i. t2 i (S (t22_m_i)) \\<Longrightarrow> t2 i (S (S (t22_m_i)))\")\n   apply fastforce\n  apply(thin_tac \"t2 i (S (t22 m i))\")\n  apply clarsimp\n  apply(subgoal_tac \"\\<And>t22_m_i. t2 i (S t22_m_i) \\<longrightarrow> t2 i (S (S t22_m_i))\")\n   apply fastforce\n  apply(thin_tac \"t2 i (S t22_m_i)\")\n  apply (induct_tac t22_m_ia i rule: t2.induct)\n    apply auto\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_65.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869916479466, "lm_q2_score": 0.8459424411924673, "lm_q1q2_score": 0.740865385679271}}
{"text": "(*  \n  Title:    Missing_PMF.thy\n  Author:   Manuel Eberl, TU M\u00fcnchen\n\n  Auxiliary facts about PMFs that should go in the library at some point\n*)\n\nsection \\<open>Auxiliary facts about PMFs\\<close>\n\ntheory Missing_PMF\n  imports Complex_Main \"~~/src/HOL/Probability/Probability\" PMF_Of_List Missing_Multiset\nbegin\n\n(* TODO: Move? *)\nadhoc_overloading Monad_Syntax.bind bind_pmf\n\nlemma pmf_not_neg [simp]: \"\\<not>pmf p x < 0\"\n  by (simp add: not_less pmf_nonneg)\n\nlemma set_pmf_eq': \"set_pmf p = {x. pmf p x > 0}\"\nproof safe\n  fix x assume \"x \\<in> set_pmf p\"\n  hence \"pmf p x \\<noteq> 0\" by (auto simp: set_pmf_eq)\n  with pmf_nonneg[of p x] show \"pmf p x > 0\" by simp\nqed (auto simp: set_pmf_eq)\n\nlemma setsum_pmf_eq_1:\n  assumes \"finite A\" \"set_pmf p \\<subseteq> A\"\n  shows   \"(\\<Sum>x\\<in>A. pmf p x) = 1\"\nproof -\n  have \"(\\<Sum>x\\<in>A. pmf p x) = measure_pmf.prob p A\"\n    by (simp add: measure_measure_pmf_finite assms)\n  also from assms have \"\\<dots> = 1\"\n    by (subst measure_pmf.prob_eq_1) (auto simp: AE_measure_pmf_iff)\n  finally show ?thesis .\nqed\n\nlemma map_pmf_of_set:\n  assumes \"finite A\" \"A \\<noteq> {}\"\n  shows   \"map_pmf f (pmf_of_set A) = pmf_of_multiset (image_mset f (mset_set A))\" \n    (is \"?lhs = ?rhs\")\nproof (intro pmf_eqI)\n  fix x\n  from assms have \"ereal (pmf ?lhs x) = ereal (pmf ?rhs x)\"\n    by (subst ereal_pmf_map)\n       (simp_all add: emeasure_pmf_of_set mset_set_empty_iff count_image_mset Int_commute)\n  thus \"pmf ?lhs x = pmf ?rhs x\" by simp\nqed\n\nlemma pmf_bind_pmf_of_set:\n  assumes \"A \\<noteq> {}\" \"finite A\"\n  shows   \"pmf (bind_pmf (pmf_of_set A) f) x = \n             (\\<Sum>xa\\<in>A. pmf (f xa) x) / real_of_nat (card A)\" (is \"?lhs = ?rhs\")\nproof -\n  from assms have \"ereal ?lhs = ereal ?rhs\"\n    by (subst ereal_pmf_bind) (simp_all add: nn_integral_pmf_of_set max_def pmf_nonneg)\n  thus ?thesis by simp\nqed\n\n\ntext \\<open>The type of lotteries (a probability mass function)\\<close>\ntype_synonym 'alt lottery = \"'alt pmf\"\n\ndefinition lotteries_on :: \"'a set \\<Rightarrow> 'a lottery set\" where\n  \"lotteries_on A = {p. set_pmf p \\<subseteq> A}\"\n\nlemma pmf_of_set_lottery:\n  \"A \\<noteq> {} \\<Longrightarrow> finite A \\<Longrightarrow> A \\<subseteq> B \\<Longrightarrow> pmf_of_set A \\<in> lotteries_on B\"\n  unfolding lotteries_on_def by auto\n\nlemma pmf_of_list_lottery: \n  \"pmf_of_list_wf xs \\<Longrightarrow> set (map fst xs) \\<subseteq> A \\<Longrightarrow> pmf_of_list xs \\<in> lotteries_on A\"\n  using set_pmf_of_list[of xs] by (auto simp: lotteries_on_def)\n\nlemma return_pmf_in_lotteries_on [simp,intro]: \n  \"x \\<in> A \\<Longrightarrow> return_pmf x \\<in> lotteries_on A\"\n  by (simp add: lotteries_on_def)\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/Missing_PMF.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8757869884059266, "lm_q2_score": 0.8459424373085145, "lm_q1q2_score": 0.7408653795351933}}
{"text": "theory Ch3\n  imports Main\nbegin\n\ntype_synonym vname = string\ntype_synonym val = int\ntype_synonym state = \"vname \\<Rightarrow> val\"\ndatatype aexp = N val | 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 a1 a2) s = aval a1 s + aval a2 s\"\n\nfun asimp_const :: \"aexp \\<Rightarrow> aexp\" where\n\"asimp_const (Plus a1 a2) = (case (asimp_const a1, asimp_const a2) of\n  (N n1, N n2) \\<Rightarrow> N (n1 + n2) |\n  (a1s, a2s) \\<Rightarrow> Plus a1s a2s\n)\" |\n\"asimp_const a = a\"\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*)\n\nlemma aval_asimp_const: \"aval (asimp_const a) s = aval a s\"\napply(induction a)\napply(auto split: aexp.split)\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\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/Ch3.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178944582995, "lm_q2_score": 0.815232480373843, "lm_q1q2_score": 0.7407348198112982}}
{"text": "theory prop_06\nimports Main\n        \"$HIPSTER_HOME/IsaHipster\"\nbegin\n  datatype 'a list = Nil2 | Cons2 \"'a\" \"'a list\"\n  datatype Nat = Z | S \"Nat\"\n  fun plus :: \"Nat => Nat => Nat\" where\n  \"plus (Z) y = y\"\n  | \"plus (S z) y = S (plus z y)\"\n  fun length :: \"'a list => Nat\" where\n  \"length (Nil2) = Z\"\n  | \"length (Cons2 y xs) = S (length xs)\"\n  fun append :: \"'a list => 'a list => 'a list\" where\n  \"append (Nil2) y = y\"\n  | \"append (Cons2 z xs) y = Cons2 z (append xs y)\"\n  fun rev :: \"'a list => 'a list\" where\n  \"rev (Nil2) = Nil2\"\n  | \"rev (Cons2 y xs) = append (rev xs) (Cons2 y (Nil2))\"\n  (*hipster plus length append rev *)\n\n(*hipster append rev length*)\nlemma lemma_a [thy_expl]: \"append x2 Nil2 = x2\"\nby (hipster_induct_schemes append.simps rev.simps length.simps)\n\nlemma lemma_aa [thy_expl]: \"append (append x2 y2) z2 = append x2 (append y2 z2)\"\nby (hipster_induct_schemes append.simps rev.simps length.simps)\n\nlemma lemma_ab [thy_expl]: \"append (rev x5) (rev y5) = rev (append y5 x5)\"\nby (hipster_induct_schemes append.simps rev.simps length.simps)\n\nlemma lemma_ac [thy_expl]: \"rev (rev x5) = x5\"\nby (hipster_induct_schemes append.simps rev.simps length.simps)\n\nlemma unknown []: \"length (append x y) = length (append y x)\"\noops\n\nlemma unknown []: \"length (rev x) = length x\"\noops\n\nlemma lemma_ad [thy_expl]: \"plus x2 Z = x2\"\nby (hipster_induct_schemes plus.simps)\n\nlemma lemma_ae [thy_expl]: \"plus (plus x2 y2) z2 = plus x2 (plus y2 z2)\"\nby (hipster_induct_schemes plus.simps)\n\nlemma lemma_af [thy_expl]: \"plus x2 (S y2) = S (plus x2 y2)\"\nby (hipster_induct_schemes plus.simps)\n\nlemma lemma_ag [thy_expl]: \"plus x1 (plus y1 x1) = plus y1 (plus x1 x1)\"\nby (hipster_induct_schemes plus.simps)\n\nlemma lemma_ah [thy_expl]: \"plus x2 (plus y2 y2) = plus y2 (plus y2 x2)\"\nby (hipster_induct_schemes plus.simps)\n\nlemma lemma_ai [thy_expl]: \"plus x2 (S y2) = S (plus y2 x2)\"\nby (hipster_induct_schemes plus.simps)\n\nlemma lemma_aj [thy_expl]: \"plus (S x2) y2 = S (plus y2 x2)\"\nby (hipster_induct_schemes plus.simps)\n\nlemma lemma_ak [thy_expl]: \"plus (plus x2 y2) (plus x2 z2) = plus (plus x2 z2) (plus x2 y2)\"\nby (hipster_induct_schemes plus.simps)\n\nlemma lemma_al [thy_expl]: \"plus (plus x2 y2) (plus z2 x2) = plus (plus z2 x2) (plus x2 y2)\"\nby (hipster_induct_schemes plus.simps)\n\nlemma lemma_am [thy_expl]: \"plus x2 (plus y2 z2) = plus y2 (plus z2 x2)\"\nby (hipster_induct_schemes plus.simps)\n\n\n(*hipster length plus append rev*)\nlemma lemma_an [thy_expl]: \"plus (length x2) (length y2) = length (append x2 y2)\"\nby (hipster_induct_schemes length.simps plus.simps append.simps rev.simps)\n\nlemma lemma_ao [thy_expl]: \"plus (length x1) (length y1) = length (append y1 x1)\"\nby (hipster_induct_schemes length.simps plus.simps append.simps rev.simps)\n\nlemma lemma_ap [thy_expl]: \"length (rev x3) = length x3\"\nby (hipster_induct_schemes length.simps plus.simps append.simps rev.simps)\n\n  theorem x0 :\n    \"(length (rev (append x y))) = (plus (length x) (length y))\"\n    by (hipster_induct_schemes)\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/prod/prop_06.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898279984214, "lm_q2_score": 0.8175744695262775, "lm_q1q2_score": 0.7407141530220128}}
{"text": "(*  Title:      HOL/ex/Abstract_NAT.thy\n    Author:     Makarius\n*)\n\nsection \\<open>Abstract Natural Numbers primitive recursion\\<close>\n\ntheory Abstract_NAT\nimports Main\nbegin\n\ntext \\<open>Axiomatic Natural Numbers (Peano) -- a monomorphic theory.\\<close>\n\nlocale NAT =\n  fixes zero :: 'n\n    and succ :: \"'n \\<Rightarrow> 'n\"\n  assumes succ_inject [simp]: \"succ m = succ n \\<longleftrightarrow> m = n\"\n    and succ_neq_zero [simp]: \"succ m \\<noteq> zero\"\n    and 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:\n  fixes x :: 'n\n  shows \"\\<exists>!y::'a. Rec e r x y\"\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      fix y assume \"?R zero y\"\n      then show \"y = e\" 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\"\n      and yy': \"\\<And>y'. ?R m y' \\<Longrightarrow> y = y'\" by blast\n    show \"\\<exists>!z. ?R (succ m) z\"\n    proof\n      from y show \"?R (succ m) (r m y)\" ..\n      fix z assume \"?R (succ m) z\"\n      then obtain u where \"z = r m u\" and \"?R m u\" by cases simp_all\n      with yy' show \"z = r m y\" 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 NAT 0 Suc\nproof (rule NAT.intro)\n  fix m n\n  show \"Suc m = Suc n \\<longleftrightarrow> m = n\" by simp\n  show \"Suc m \\<noteq> 0\" by simp\n  fix P\n  assume zero: \"P 0\"\n    and succ: \"\\<And>n. P n \\<Longrightarrow> P (Suc n)\"\n  show \"P n\"\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": "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/Abstract_NAT.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898178450965, "lm_q2_score": 0.817574471748733, "lm_q1q2_score": 0.7407141467344356}}
{"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\\<inverse>)\"\n    \\<comment> \\<open>symmetric closure: removes the orientation of a relation\\<close>\n\ndefinition neighbors :: \"[vertex, (vertex*vertex)set]=>vertex set\" where\n  \"neighbors i r == ((r \\<union> r\\<inverse>)``{i}) - {i}\"\n    \\<comment> \\<open>Neighbors of a vertex i\\<close>\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\\<inverse>)``{i}\"\n\ndefinition reach :: \"[vertex, (vertex*vertex)set]=> vertex set\" where\n  \"reach i r == (r\\<^sup>+)``{i}\"\n    \\<comment> \\<open>reachable and above vertices: the original notation was R* and A*\\<close>\n\ndefinition above :: \"[vertex, (vertex*vertex)set]=> vertex set\" where\n  \"above i r == ((r\\<inverse>)\\<^sup>+)``{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)\\<inverse>\"\n\ndefinition derive1 :: \"[vertex, (vertex*vertex)set, (vertex*vertex)set]=>bool\" where\n    \\<comment> \\<open>The original definition\\<close>\n  \"derive1 i r q == symcl r = symcl q &\n                    (\\<forall>k k'. k\\<noteq>i & k'\\<noteq>i -->((k,k') \\<in> r) = ((k,k') \\<in> q)) \\<and>\n                    A i r = {} & R i q = {}\"\n\ndefinition derive :: \"[vertex, (vertex*vertex)set, (vertex*vertex)set]=>bool\" where\n    \\<comment> \\<open>Our alternative definition\\<close>\n  \"derive i r q == A i r = {} & (q = reverse i r)\"\n\naxiomatization where\n  finite_vertex_univ:  \"finite (UNIV :: vertex set)\"\n    \\<comment> \\<open>we assume that the universe of vertices is finite\\<close>\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\\<open>All vertex sets are finite\\<close>\ndeclare finite_subset [OF subset_UNIV finite_vertex_univ, iff]\n\ntext\\<open>and relatons over vertex are finite too\\<close>\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\\<^sup>+)``{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}={}) = (\\<forall>x. ((i,x) \\<in> r\\<^sup>+) = 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) \\<in> r\\<^sup>+ \\<Longrightarrow> (\\<forall>y. (y, z) \\<in> r \\<longrightarrow> (y,i) \\<notin> r\\<^sup>+) = ((r\\<inverse>)``{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\\<inverse>)\\<^sup>+) ``{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": "seL4", "repo": "isabelle", "sha": "e1ab32a3bb41728cd19541063283e37919978a4c", "save_path": "github-repos/isabelle/seL4-isabelle", "path": "github-repos/isabelle/seL4-isabelle/isabelle-e1ab32a3bb41728cd19541063283e37919978a4c/src/HOL/UNITY/Comp/PriorityAux.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797100118214, "lm_q2_score": 0.8128673110375458, "lm_q1q2_score": 0.7406682007492801}}
{"text": "(* Author: Tobias Nipkow *)\n\nsection {* Association List Update and Deletion *}\n\ntheory AList_Upd_Del\nimports Sorted_Less\nbegin\n\nabbreviation \"sorted1 ps \\<equiv> sorted(map fst ps)\"\n\ntext{* Define own @{text map_of} function to avoid pulling in an unknown\namount of lemmas implicitly (via the simpset). *}\n\nhide_const (open) map_of\n\nfun map_of :: \"('a*'b)list \\<Rightarrow> 'a \\<Rightarrow> 'b option\" where\n\"map_of [] = (\\<lambda>x. None)\" |\n\"map_of ((a,b)#ps) = (\\<lambda>x. if x=a then Some b else map_of ps x)\"\n\ntext \\<open>Updating an association list:\\<close>\n\nfun upd_list :: \"'a::linorder \\<Rightarrow> 'b \\<Rightarrow> ('a*'b) list \\<Rightarrow> ('a*'b) list\" where\n\"upd_list x y [] = [(x,y)]\" |\n\"upd_list x y ((a,b)#ps) =\n  (if x < a then (x,y)#(a,b)#ps else\n  if x = a then (x,y)#ps else (a,b) # upd_list x y ps)\"\n\nfun del_list :: \"'a::linorder \\<Rightarrow> ('a*'b)list \\<Rightarrow> ('a*'b)list\" where\n\"del_list x [] = []\" |\n\"del_list x ((a,b)#ps) = (if x = a then ps else (a,b) # del_list x ps)\"\n\n\nsubsection \\<open>Lemmas for @{const map_of}\\<close>\n\nlemma map_of_ins_list: \"map_of (upd_list x y ps) = (map_of ps)(x := Some y)\"\nby(induction ps) auto\n\nlemma map_of_append: \"map_of (ps @ qs) x =\n  (case map_of ps x of None \\<Rightarrow> map_of qs x | Some y \\<Rightarrow> Some y)\"\nby(induction ps)(auto)\n\nlemma map_of_None: \"sorted (x # map fst ps) \\<Longrightarrow> map_of ps x = None\"\nby (induction ps) (auto simp: sorted_lems sorted_Cons_iff)\n\nlemma map_of_None2: \"sorted (map fst ps @ [x]) \\<Longrightarrow> map_of ps x = None\"\nby (induction ps) (auto simp: sorted_lems)\n\nlemma map_of_del_list: \"sorted1 ps \\<Longrightarrow>\n  map_of(del_list x ps) = (map_of ps)(x := None)\"\nby(induction ps) (auto simp: map_of_None sorted_lems fun_eq_iff)\n\nlemma map_of_sorted_Cons: \"sorted (a # map fst ps) \\<Longrightarrow> x < a \\<Longrightarrow>\n   map_of ps x = None\"\nby (meson less_trans map_of_None sorted_Cons_iff)\n\nlemma map_of_sorted_snoc: \"sorted (map fst ps @ [a]) \\<Longrightarrow> a \\<le> x \\<Longrightarrow>\n  map_of ps x = None\"\nby (meson le_less_trans map_of_None2 not_less sorted_snoc_iff)\n\nlemmas map_of_sorteds = map_of_sorted_Cons map_of_sorted_snoc\nlemmas map_of_simps = sorted_lems map_of_append map_of_sorteds\n\n\nsubsection \\<open>Lemmas for @{const upd_list}\\<close>\n\nlemma sorted_upd_list: \"sorted1 ps \\<Longrightarrow> sorted1 (upd_list x y ps)\"\napply(induction ps)\n apply simp\napply(case_tac ps)\n apply auto\ndone\n\nlemma upd_list_sorted: \"sorted1 (ps @ [(a,b)]) \\<Longrightarrow>\n  upd_list x y (ps @ (a,b) # qs) =\n    (if x < a then upd_list x y ps @ (a,b) # qs\n    else ps @ upd_list x y ((a,b) # qs))\"\nby(induction ps) (auto simp: sorted_lems)\n\ntext\\<open>In principle, @{thm upd_list_sorted} suffices, but the following two\ncorollaries speed up proofs.\\<close>\n\ncorollary upd_list_sorted1: \"\\<lbrakk> sorted (map fst ps @ [a]); x < a \\<rbrakk> \\<Longrightarrow>\n  upd_list x y (ps @ (a,b) # qs) =  upd_list x y ps @ (a,b) # qs\"\nby (auto simp: upd_list_sorted)\n\ncorollary upd_list_sorted2: \"\\<lbrakk> sorted (map fst ps @ [a]); a \\<le> x \\<rbrakk> \\<Longrightarrow>\n  upd_list x y (ps @ (a,b) # qs) = ps @ upd_list x y ((a,b) # qs)\"\nby (auto simp: upd_list_sorted)\n\nlemmas upd_list_simps = sorted_lems upd_list_sorted1 upd_list_sorted2\n\ntext\\<open>Splay trees need two additional @{const upd_list} lemmas:\\<close>\n\nlemma upd_list_Cons:\n  \"sorted1 ((x,y) # xs) \\<Longrightarrow> upd_list x y xs = (x,y) # xs\"\nby (induction xs) auto\n\nlemma upd_list_snoc:\n  \"sorted1 (xs @ [(x,y)]) \\<Longrightarrow> upd_list x y xs = xs @ [(x,y)]\"\nby(induction xs) (auto simp add: sorted_mid_iff2)\n\n\nsubsection \\<open>Lemmas for @{const del_list}\\<close>\n\nlemma sorted_del_list: \"sorted1 ps \\<Longrightarrow> sorted1 (del_list x ps)\"\napply(induction ps)\n apply simp\napply(case_tac ps)\napply auto\nby (meson order.strict_trans sorted_Cons_iff)\n\nlemma del_list_idem: \"x \\<notin> set(map fst xs) \\<Longrightarrow> del_list x xs = xs\"\nby (induct xs) auto\n\nlemma del_list_sorted: \"sorted1 (ps @ (a,b) # qs) \\<Longrightarrow>\n  del_list x (ps @ (a,b) # qs) =\n    (if x < a then del_list x ps @ (a,b) # qs\n     else ps @ del_list x ((a,b) # qs))\"\nby(induction ps)\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: \"sorted1 (xs @ (a,b) # ys) \\<Longrightarrow> a \\<le> x \\<Longrightarrow>\n  del_list x (xs @ (a,b) # ys) = xs @ del_list x ((a,b) # ys)\"\nby (auto simp: del_list_sorted)\n\nlemma del_list_sorted2: \"sorted1 (xs @ (a,b) # ys) \\<Longrightarrow> x < a \\<Longrightarrow>\n  del_list x (xs @ (a,b) # ys) = del_list x xs @ (a,b) # ys\"\nby (auto simp: del_list_sorted)\n\nlemma del_list_sorted3:\n  \"sorted1 (xs @ (a,a') # ys @ (b,b') # zs) \\<Longrightarrow> x < b \\<Longrightarrow>\n  del_list x (xs @ (a,a') # ys @ (b,b') # zs) = del_list x (xs @ (a,a') # ys) @ (b,b') # zs\"\nby (auto simp: del_list_sorted sorted_lems)\n\nlemma del_list_sorted4:\n  \"sorted1 (xs @ (a,a') # ys @ (b,b') # zs @ (c,c') # us) \\<Longrightarrow> x < c \\<Longrightarrow>\n  del_list x (xs @ (a,a') # ys @ (b,b') # zs @ (c,c') # us) = del_list x (xs @ (a,a') # ys @ (b,b') # zs) @ (c,c') # us\"\nby (auto simp: del_list_sorted sorted_lems)\n\nlemma del_list_sorted5:\n  \"sorted1 (xs @ (a,a') # ys @ (b,b') # zs @ (c,c') # us @ (d,d') # vs) \\<Longrightarrow> x < d \\<Longrightarrow>\n   del_list x (xs @ (a,a') # ys @ (b,b') # zs @ (c,c') # us @ (d,d') # vs) =\n   del_list x (xs @ (a,a') # ys @ (b,b') # zs @ (c,c') # us) @ (d,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 # map fst xs) \\<Longrightarrow> del_list x xs = xs\"\nby(induction xs)(auto simp: sorted_Cons_iff)\n\nlemma del_list_sorted_app:\n  \"sorted(map fst 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/AList_Upd_Del.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8596637648915617, "lm_q2_score": 0.8615382147637195, "lm_q1q2_score": 0.7406331853017339}}
{"text": "theory Scratch3\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 v) s = s v\"|\n\"aval (Plus a1 a2) s = (aval a1 s) + (aval a2 s)\"\n\n\nvalue \"aval (Plus (N 3) (V ''x'')) ((\\<lambda>x.0)(''x'':=7))\"\n\ndefinition null_state (\"<>\") where\n  \"null_state \\<equiv> \\<lambda>x.0\"\nsyntax\n  \"_State\" :: \"updbinds \\<Rightarrow> 'a\" (\"<_>\")\ntranslations\n  \"_State ms\" == \"_Update <> ms\"\n  \"_State (_updbinds b bs)\" <= \"_Update (_State b) bs\"\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 a1 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)\n  apply (simp add : aval_plus)\n  done\n\n(* Exercise 3.1 *)\nfun optimal:: \"aexp \\<Rightarrow> bool\" where\n\"optimal (N _) = True\"|\n\"optimal (V _) = True\"|\n\"optimal (Plus (N _) (N _)) = False\"|\n\"optimal (Plus a1 a2) = ((optimal a1) \\<and> (optimal a2))\"\n\nlemma \"optimal (asimp_const a)\"\n  apply (induction a rule : optimal.induct)\n        apply(auto split: aexp.split)\n  done\n\n(* Exercise 3.2 *)\nfun plus_complete:: \"aexp \\<Rightarrow> aexp \\<Rightarrow> aexp\" where\n\"plus_complete (N i1) (N i2) = N (i1 + i2)\"|\n\"plus_complete (N i1) (Plus (V v) (N i2)) = Plus (V v) (N (i1 + i2))\"|\n\"plus_complete (N i1) (Plus (N i2) (V v)) = Plus (V v) (N (i1 + i2))\"|\n\"plus_complete (Plus (V v) (N i1)) (N i2) = Plus (V v) (N (i1 + i2))\"|\n\"plus_complete (Plus (N i1) (V v)) (N i2) = Plus (V v) (N (i1 + i2))\"|\n\"plus_complete a1 a2 = Plus a1 a2\"\n\nlemma aval_plus_complete: \"aval (plus_complete a1 a2) s = aval a1 s + aval a2 s\"\n  apply (induction a1 rule : plus_complete.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 v) = V v\"|\n\"full_asimp (Plus a1 a2) = plus_complete (full_asimp a1) (full_asimp a2)\"\n\nlemma \"aval (full_asimp a) s = aval a s\"\n  apply (induction a)\n    apply (auto)\n  apply (simp add : aval_plus_complete)\n  done\n\n(* Exercise 3.3 *)\nfun subst :: \"vname \\<Rightarrow> aexp \\<Rightarrow> aexp \\<Rightarrow> aexp\" where\n\"subst v a  (N x) = (N x)\"|\n\"subst v1 a (V v2) = (if (v1 = v2) then a else (V v2))\"|\n\"subst v a (Plus e1 e2) = Plus (subst v a e1) (subst v a e2)\"\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 subst_equiv:\"aval a\\<^sub>1 s = aval a\\<^sub>2 s \\<Longrightarrow> aval (subst x a\\<^sub>1 e) s = aval (subst x a\\<^sub>2 e) s\"\n  apply (induction e)\n    apply (auto)\n  done\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) _ = 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' n) e = (if (n = 0) then e else (Plus' (N' n) e))\"|\n\"plus' e (N' n) = (if (n = 0) then e else (Plus' e (N' n)))\"|\n\"plus' e1 e2 = Plus' e1 e2\"\n\nfun times' :: \"aexp' \\<Rightarrow> aexp' \\<Rightarrow> aexp'\" where\n\"times' (N' n1) (N' n2) = N' (n1 * n2)\"|\n\"times' (N' n) e = (if n = 0\n                  then (N' 0)\n                  else (if n = 1\n                       then e\n                       else (Times' (N' n) e)))\"|\n\"times' e (N' n) = (if n = 0\n                  then (N' 0)\n                  else (if n = 1\n                       then e\n                       else (Times' e (N' n))))\"|\n\"times' e1 e2 = Times' e1 e2\"\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' e1 e2\"|\n\"asimp' (Times' e1 e2) = times' e1 e2\"\n\nlemma aval_plus': \"aval' (plus' a1 a2) s = aval' a1 s + aval' a2 s\"\n  apply (induction a1 rule : plus'.induct)\n              apply (auto)\n  done\n\nlemma aval_times : \"aval' (times' a1 a2) s = aval' a1 s * aval' a2 s\"\n  apply (induction a1 rule : times'.induct)\n                      apply(auto)\n  done\n\nlemma \"aval' (asimp' a) s = aval' a s\"\n  apply (induction a)\n     apply (auto)\n   apply (simp_all add: aval_plus' aval_times)\n  done\n\ndatatype aexp2 = N2 int |\n                 V2 vname |\n                 Plus2 aexp2 aexp2 |\n                 Times2 aexp2 aexp2 |\n                 PostInc vname|\n                 Div2 aexp2 aexp2\nvalue \"(1::nat, 2::nat)\"\nvalue \"fst (1::nat, 2::nat)\"\nvalue \"let x = 2::nat in x\"\nvalue \"let (a, b) = (1::nat, 2::nat) in a\"\nvalue \"(1::int) div (2::int)\"\n\n(* Argument application order is always first then second *)\nfun aval2 :: \"aexp2 \\<Rightarrow> state \\<Rightarrow> (val \\<times> state) option\" where\n\"aval2 (PostInc v) s = Some (s v, s(v := (s v) + 1))\"|\n\"aval2 (N2 n) s = Some (n, s)\"|\n\"aval2 (V2 v) s = Some (s v, s)\"|\n\"aval2 (Plus2 a1 a2) s = (case aval2 a1 s of\n                         None \\<Rightarrow> None |\n                         Some (r1, s1) \\<Rightarrow> \n                            (case aval2 a2 s1 of\n                            None \\<Rightarrow> None |\n                            Some (r2, s2) \\<Rightarrow> Some (r1 + r2, s2)))\"|\n\"aval2 (Times2 a1 a2) s = (case aval2 a1 s of\n                         None \\<Rightarrow> None |\n                         Some (r1, s1) \\<Rightarrow> \n                            (case aval2 a2 s1 of\n                            None \\<Rightarrow> None |\n                            Some (r2, s2) \\<Rightarrow> Some (r1 * r2, s2)))\"|\n\"aval2 (Div2 a1 a2) s = (case aval2 a1 s of\n                         None \\<Rightarrow> None |\n                         Some (r1, s1) \\<Rightarrow> \n                            (case aval2 a2 s1 of\n                            None \\<Rightarrow> None |\n                            Some (r2, s2) \\<Rightarrow> (if r2 = 0 then None else Some (r1 div r2, s2))))\"\n\nvalue \"(snd (case (aval2 (N2 2) <>) of\n        None \\<Rightarrow> (0, <>) |\n        Some (v, s) \\<Rightarrow> (v, s))) ''x''\"\n\nvalue \"(snd (case (aval2 (PostInc ''x'') <>) of\n        None \\<Rightarrow> (0, <>) |\n        Some (v, s) \\<Rightarrow> (v, s))) ''x''\"\n\nvalue \"(snd (case (aval2 (Div2 (PostInc ''x'') (PostInc ''x'')) <''x'':=6>) of\n        None \\<Rightarrow> (0, <>) |\n        Some (v, s) \\<Rightarrow> (v, s))) ''x''\"\nvalue \"(fst (case (aval2 (Div2 (PostInc ''x'') (PostInc ''x'')) <''x'':=6>) of\n        None \\<Rightarrow> (0, <>) |\n        Some (v, s) \\<Rightarrow> (v, s)))\"\n\nvalue \"aval2 (Div2 (V2 ''x'') (N2 2)) <''x'':=6>\"\n\n(* Exercise 3.6 *)\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) _ = n\"|\n\"lval (Vl v) s = s v\"|\n\"lval (Plusl l1 l2) s = (lval l1 s) + (lval l2 s)\"|\n\"lval (LET v l1 l2) s = lval l2 (s(v:=(lval l1 s)))\"\n\nfun inline :: \"lexp \\<Rightarrow> aexp\" where\n\"inline (Nl n) = (N n)\"|\n\"inline (Vl v) = (V v)\"|\n\"inline (Plusl l1 l2) = Plus (inline l1) (inline l2)\"|\n\"inline (LET v l1 l2) = subst v (inline l1) (inline l2)\"\n\n\n\nlemma inline_correct : \"aval (inline l) s = lval l s\"\n  apply(induction l arbitrary:s)\n     apply(auto)\n  apply(simp add:subst_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 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 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 b\\<^sub>1 b\\<^sub>2 = And b\\<^sub>1 b\\<^sub>2\"\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\n(* Exercise 3.7 *)\ndefinition Eq :: \"aexp \\<Rightarrow> aexp \\<Rightarrow> bexp\" where\n\"Eq a\\<^sub>1 a\\<^sub>2 = And (Not (Less a\\<^sub>1 a\\<^sub>2)) (Not (Less a\\<^sub>2 a\\<^sub>1))\"\n\nvalue \"bval (Eq (N 1) (N 1)) <>\"\nvalue \"bval (Eq (N 1) (N 2)) <>\"\nvalue \"bval (Eq (N 2) (N 1)) <>\"\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\ndefinition Le :: \"aexp \\<Rightarrow> aexp \\<Rightarrow> bexp\" where\n\"Le a\\<^sub>1 a\\<^sub>2 = Or (Eq a\\<^sub>1 a\\<^sub>2) (Less a\\<^sub>1 a\\<^sub>2)\"\n\nvalue \"bval (Le (N 1) (N 1)) <>\"\nvalue \"bval (Le (N 1) (N 2)) <>\"\nvalue \"bval (Le (N 2) (N 1)) <>\"\n\nlemma \"bval (Eq a\\<^sub>1 a\\<^sub>2) s = (aval a\\<^sub>1 s = aval a\\<^sub>2 s)\"\n  apply (auto simp add: Eq_def)\n  done  \n\nlemma \"bval (Le a\\<^sub>1 a\\<^sub>2) s = ((aval a\\<^sub>1 s) \\<le> (aval a\\<^sub>2 s))\"\n  apply (auto simp add: Le_def Or_def Eq_def)\n  done\n\n(* Exercise 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 b) _ = b\"|\n\"ifval (Less2 a\\<^sub>1 a\\<^sub>2) s = ((aval a\\<^sub>1 s) < (aval a\\<^sub>2 s))\"|\n\"ifval (If i\\<^sub>1 i\\<^sub>2 i\\<^sub>3) s = (if (ifval i\\<^sub>1 s) then (ifval i\\<^sub>2 s) else (ifval i\\<^sub>3 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 b\\<^sub>1 b\\<^sub>2) = If (b2ifexp b\\<^sub>1) (b2ifexp b\\<^sub>2) (Bc2 False)\"|\n\"b2ifexp (Less a\\<^sub>1 a\\<^sub>2) = Less2 a\\<^sub>1 a\\<^sub>2\"\n\nfun if2bexp :: \"ifexp \\<Rightarrow> bexp\" where\n\"if2bexp (Bc2 v) = Bc v\"|\n\"if2bexp (Less2 a\\<^sub>1 a\\<^sub>2) = Less a\\<^sub>1 a\\<^sub>2\"|\n\"if2bexp (If i\\<^sub>1 i\\<^sub>2 i\\<^sub>3) = Or (And (if2bexp i\\<^sub>1) (if2bexp i\\<^sub>2))\n                            (And (Not (if2bexp i\\<^sub>1)) (if2bexp i\\<^sub>3))\"\n\nlemma \"ifval (b2ifexp b) s = bval b s\"\n  apply (induction b)\n     apply (auto)\n  done\nlemma \"bval (if2bexp i) s = ifval i s\"\n  apply (induction i)\n    apply (auto simp add : Or_def)\n  done\n\n(* Exercise 3.8 *)\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 b\\<^sub>1 b\\<^sub>2) s = (pbval b\\<^sub>1 s \\<and> pbval b\\<^sub>2 s)\"|\n\"pbval (OR b\\<^sub>1 b\\<^sub>2) s = (pbval b\\<^sub>1 s \\<or> pbval b\\<^sub>2 s)\"\n\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 b\\<^sub>1 b\\<^sub>2) = (is_nnf b\\<^sub>1 \\<and> is_nnf b\\<^sub>2)\"|\n\"is_nnf (OR b\\<^sub>1 b\\<^sub>2) = (is_nnf b\\<^sub>1 \\<or> is_nnf b\\<^sub>2)\"\n\nfun nnf :: \"pbexp \\<Rightarrow> pbexp\" where\n\"nnf (VAR v) = VAR v\"|\n\"nnf (NOT (VAR v)) = NOT (VAR v)\"|\n\"nnf (NOT (NOT b)) = nnf b\"|\n\"nnf (AND b\\<^sub>1 b\\<^sub>2) = AND (nnf b\\<^sub>1) (nnf b\\<^sub>2)\"|\n\"nnf (NOT (AND b\\<^sub>1 b\\<^sub>2)) = OR (nnf (NOT b\\<^sub>1)) (nnf (NOT b\\<^sub>2))\"|\n\"nnf (OR b\\<^sub>1 b\\<^sub>2) = OR (nnf b\\<^sub>1) (nnf b\\<^sub>2)\"|\n\"nnf (NOT (OR b\\<^sub>1 b\\<^sub>2)) = AND (nnf (NOT b\\<^sub>1)) (nnf (NOT b\\<^sub>2))\"\n\nlemma \"(pbval (nnf b) s = pbval b s)\"\n  apply (induction b rule:nnf.induct)\n     apply(auto)\n  done\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 v) s stk = (s v) # 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\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 instr_app_stack:\"exec (is\\<^sub>1 @ is\\<^sub>2) s stk = exec is\\<^sub>2 s (exec is\\<^sub>1 s stk)\"\n  apply (induction is\\<^sub>1 arbitrary: stk)\n   apply (auto)\n  done\n\nlemma \"exec (comp a) s stk = aval a s # stk\"\n  apply (induction a arbitrary: stk)  \n  apply(auto)\n    apply (auto simp add: instr_app_stack)\n  done\n\n(* Exercise 3.10 *)\nfun exec1' :: \"instr \\<Rightarrow> state \\<Rightarrow> stack \\<Rightarrow> stack option\" where\n\"exec1' (LOADI n) _ stk = Some (n # stk)\"|\n\"exec1' (LOAD v) s stk = Some ((s v) # stk)\"|\n\"exec1' ADD _ (j # i # stk) = Some ((i + j) # stk)\"|\n\"exec1' ADD _ _ = 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 = (case (exec1' i s stk) of\n                      None \\<Rightarrow> None |\n                      Some stk' \\<Rightarrow> exec' is s stk')\"\n\nlemma instr_app_stack':\"(exec' is\\<^sub>1 s stk) = Some v \\<Longrightarrow> exec' (is\\<^sub>1 @ is\\<^sub>2) s stk = exec' is\\<^sub>2 s v\"\n  apply (induction is\\<^sub>1 arbitrary: stk)\n   apply (auto split:option.split)\n  done\n\n\nlemma \"exec' (comp a) s stk = Some  (aval a s # stk)\"\n  apply (induction a arbitrary: stk)\n    apply(auto simp add: instr_app_stack')\n  done\n\n\n(* Exercise 3.11 *)\ntype_synonym reg = nat\n\n(* (ADD r\\<^sub>1 r\\<^sub>2) adds value in r\\<^sub>1 and value in r\\<^sub>2 and puts result in r\\<^sub>1 *)\ndatatype rinstr = LDI int 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 i r) st regs  = regs(r := i)\"|\n\"rexec1 (LD v r) st regs = regs(r := (st v))\"|\n\"rexec1 (ADD r\\<^sub>1 r\\<^sub>2) st regs = regs(r\\<^sub>1 := ((regs r\\<^sub>1) + (regs r\\<^sub>2)))\"\n\nfun rexec:: \"rinstr list \\<Rightarrow> state \\<Rightarrow> (reg \\<Rightarrow> int) \\<Rightarrow> reg \\<Rightarrow> int\" where\n\"rexec [] _ regs = regs\"|\n\"rexec (i#is) st regs = rexec is st (rexec1 i st regs)\"\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 e\\<^sub>1 e\\<^sub>2) r = (rcomp e\\<^sub>1 r) @ (rcomp e\\<^sub>2 (r+1)) @ [ADD r (r+1)]\"\n\nlemma rinstr_app_reg:\"rexec (is\\<^sub>1 @ is\\<^sub>2) s r = rexec is\\<^sub>2 s (rexec is\\<^sub>1 s r)\"\n  apply (induction is\\<^sub>1 arbitrary: r)\n   apply (auto)\n  done\n\n\n\n\nlemma \"rexec(rcomp a r) s rs r = aval a s\"\n  apply (induction a arbitrary: rs r)\n  apply (auto)\n  apply (auto simp add: rinstr_app_reg )\n  done\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/Chapter3/Scratch3.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887588023318196, "lm_q2_score": 0.8333245870332531, "lm_q1q2_score": 0.7406245619253321}}
{"text": "theory ChoiceFunction\n  imports Main Common Base\nbegin\n\n(* A choice function maps a set of presented alternatives to a set of chosen alternatives *)\ntype_synonym 'a CF = \"'a set \\<Rightarrow> 'a set\"\n\nabbreviation invalid_cf :: \"'a CF\" where \"invalid_cf \\<equiv> \\<lambda>_. {}\"\nabbreviation trivial_cf :: \"'a CF\" where \"trivial_cf \\<equiv> id\"\n\nlocale choice_function = choice_setting +\n  constrains U :: \"'a set\"\n  fixes S :: \"'a CF\"\n  (* S has to choose some nonempty subset of the given alternatives A *)\n  assumes S: \"A \\<sqsubseteq> U \\<Longrightarrow> S A \\<sqsubseteq> A\"\n  assumes S_domain: \"(\\<not> A \\<sqsubseteq> U) = (S A = invalid_cf A)\"\nbegin\n\nlemma S_subset: \"S A \\<subseteq> A\" using S S_domain by (cases \"A \\<sqsubseteq> U\") auto\n\n(* The base relation of S *)\ndefinition R\\<^sub>S (infixl \"R\\<^sub>S\" 50) where \"x R\\<^sub>S y = (x \\<in> S {x, y})\"\ninterpretation base_complete: complete_preference U \"(R\\<^sub>S)\" proof\n  show \"\\<And>x y. x \\<notin> U \\<or> y \\<notin> U \\<Longrightarrow> \\<not> x R\\<^sub>S y\" unfolding R\\<^sub>S_def using S_domain by auto next\n  show \"\\<And>x y. x \\<in> U \\<Longrightarrow> y \\<in> U \\<Longrightarrow> x R\\<^sub>S y \\<or> y R\\<^sub>S x\" unfolding R\\<^sub>S_def by (smt (verit) Diff_eq_empty_iff Diff_insert_absorb S Un_Diff_cancel Un_upper1 insert_Diff insert_commute insert_is_Un insert_not_empty insert_subsetI subset_insert) \nqed\nlemma base_complete: \"complete_preference U (R\\<^sub>S)\" by (simp add: base_complete.complete_preference_axioms) \n\nlemma eq_base_max: \"A \\<sqsubseteq> U \\<Longrightarrow> x \\<in> A \\<Longrightarrow> (\\<forall>y \\<in> A. x \\<in> S {x, y}) = (x \\<in> general_preference.Max (R\\<^sub>S) A)\" using base_complete.Max_comp R\\<^sub>S_def by auto\n\nlemma trivial_choice: \"x \\<in> U \\<Longrightarrow> S {x} = {x}\" using S[of \"{x}\"] by auto\n\nend\n\n(* Contraction *)\nlocale sat_\\<alpha> = choice_function +\n  assumes \\<alpha>: \"A \\<sqsubseteq> U \\<Longrightarrow> B \\<sqsubseteq> U \\<Longrightarrow> x \\<in> A \\<Longrightarrow> x \\<in> B \\<Longrightarrow> x \\<in> S (A \\<union> B) \\<Longrightarrow> x \\<in> S A \\<and> x \\<in> S B\"\n\n(* Expansion *)\nlocale sat_\\<gamma> = choice_function +\n  assumes \\<gamma>: \"A \\<sqsubseteq> U \\<Longrightarrow> B \\<sqsubseteq> U \\<Longrightarrow> x \\<in> A \\<Longrightarrow> x \\<in> B \\<Longrightarrow> x \\<in> S A \\<Longrightarrow> x \\<in> S B \\<Longrightarrow> x \\<in> S (A \\<union> B)\"\n\nlocale sat_\\<gamma>_plus = choice_function +\n  assumes \\<gamma>_plus: \"A \\<sqsubseteq> U \\<Longrightarrow> B \\<sqsubseteq> U \\<Longrightarrow> S A \\<subseteq> S (A \\<union> B) \\<or> S B \\<subseteq> S (A \\<union> B)\"\n\n(* Strong Expansion *)\nlocale sat_\\<beta>_plus = choice_function +\n  assumes \\<beta>_plus: \"A \\<sqsubseteq> U \\<Longrightarrow> B \\<sqsubseteq> U \\<Longrightarrow> B \\<subseteq> A \\<Longrightarrow> S A \\<inter> B \\<noteq> {} \\<Longrightarrow> S B \\<subseteq> S A\"\n\nsublocale sat_\\<beta>_plus \\<subseteq> sat_\\<gamma>_plus proof\n  fix A B assume au: \"A \\<sqsubseteq> U\" and bu: \"B \\<sqsubseteq> U\"\n  hence ab: \"A \\<union> B \\<sqsubseteq> U\" by auto\n\n  have \"S (A \\<union> B) \\<noteq> {}\" using S[of \"A \\<union> B\"] ab by auto\n  then obtain x where x: \"x \\<in> S (A \\<union> B)\" using S by auto\n\n  have \"S (A \\<union> B) \\<subseteq> A \\<union> B\" using ab S[of \"A \\<union> B\"] by auto\n  hence \"x \\<in> A \\<or> x \\<in> B\" using x by auto\n  thus \"S A \\<subseteq> S (A \\<union> B) \\<or> S B \\<subseteq> S (A \\<union> B)\" using \\<beta>_plus[OF ab] ab x by auto\nqed\n\nsublocale sat_\\<gamma>_plus \\<subseteq> sat_\\<gamma> proof\n  fix A B x assume \"A \\<sqsubseteq> U\" \"B \\<sqsubseteq> U\" \"x \\<in> A\" \"x \\<in> B\" \"x \\<in> S A\" \"x \\<in> S B\"\n  thus \"x \\<in> S (A \\<union> B)\" using \\<gamma>_plus by auto\nqed\n\nlocale rationalizable_choice_function = choice_function +\n  (* A CF is rationalizable iff it is rationalized by its  base relation *)\n  assumes rationalized: \"A \\<sqsubseteq> U \\<Longrightarrow> S A = general_preference.Max (R\\<^sub>S) A\"\n\nlocale sat_\\<alpha>_\\<gamma> = sat_\\<alpha> + sat_\\<gamma>\n\n(* Sen's theorem rationalizable \\<Longleftrightarrow> \\<alpha> \\<and> \\<gamma> *)\n(* Direction \\<Longleftarrow> *)\nsublocale sat_\\<alpha>_\\<gamma> \\<subseteq> rationalizable_choice_function proof\n  fix A assume AU: \"A \\<sqsubseteq> U\"\n\n  show \"S A = general_preference.Max (R\\<^sub>S) A\" proof (rule set_eqI; rule iffI)\n    fix x assume xsa: \"x \\<in> S A\" hence xa: \"x \\<in> A\" using S_subset by auto\n    {\n      fix y assume ya: \"y \\<in> A\"\n      hence xyu: \"{x, y} \\<sqsubseteq> U\" using AU xa by blast\n      have \"x \\<in> S A \\<and> x \\<in> S {x, y}\" using \\<alpha>[OF AU xyu xa] by (simp add: xsa insert_absorb xa ya) \n    }\n    thus \"x \\<in> general_preference.Max (R\\<^sub>S) A\" using eq_base_max[OF AU xa] by auto\n  next\n    fix x assume xmax: \"x \\<in> general_preference.Max (R\\<^sub>S) A\"\n\n    have xa: \"x \\<in> A\" using general_preference.Max_def[of U \"(R\\<^sub>S)\"] xmax AU base_complete complete_preference.Max_comp by blast\n\n    have \"finite A\" using AU finite_subset finite_universe by auto \n    moreover have \"A \\<subseteq> A\" by auto\n    ultimately have \"A \\<sqsubseteq> U \\<Longrightarrow> x \\<in> S (A \\<union> {x})\" proof (induction rule: finite_subset_induct)\n      case empty thus ?case using AU xa trivial_choice by auto\n    next\n      case (insert a F)\n      moreover have fxu: \"F \\<union> {x} \\<sqsubseteq> U\" using AU xa insert.prems by auto\n      moreover have \"{x, a} \\<sqsubseteq> U\" using insert fxu insert.prems by auto\n      moreover have \"x \\<in> F \\<union> {x}\" by auto\n      moreover have \"x \\<in> {x, a}\" by auto\n      moreover have \"x \\<in> S (F \\<union> {x})\" using fxu insert.IH trivial_choice by force \n      moreover have \"x \\<in> S {x, a}\" using AU eq_base_max insert.hyps(2) xa xmax by auto\n      ultimately show ?case using \\<gamma>[of \"F \\<union> {x}\" \"{x, a}\" x] by (simp add: Un_commute) \n    qed\n    thus \"x \\<in> S A\" using AU xa by (simp add: insert_absorb) \n  qed\nqed\n\n(* Sen's theorem rationalizable \\<Longleftrightarrow> \\<alpha> \\<and> \\<gamma> *)\n(* Direction \\<Longrightarrow> *)\nsublocale rationalizable_choice_function \\<subseteq> sat_\\<alpha>_\\<gamma> proof\n  fix A B x assume AU: \"A \\<sqsubseteq> U\" and BU: \"B \\<sqsubseteq> U\" and xa:  \"x \\<in> A\" and xb: \"x \\<in> B\"\n\n  have g: \"general_preference U (R\\<^sub>S)\" using base_complete complete_preference_def by auto\n\n  show \"x \\<in> S (A \\<union> B) \\<Longrightarrow> x \\<in> S A \\<and> x \\<in> S B\" proof\n    assume \"x \\<in> S (A \\<union> B)\"\n    hence x: \"x \\<in> general_preference.Max (R\\<^sub>S) (A \\<union> B)\" by (metis S_domain empty_iff rationalized)\n\n    show \"x \\<in> S A\" using x rationalized[OF AU] xa general_preference.Max_def[OF g] by auto \n    show \"x \\<in> S B\" using x rationalized[OF BU] xb general_preference.Max_def[OF g] by auto \n  qed\n\n  assume \"x \\<in> S A\"\n  hence \"x \\<in> general_preference.Max (R\\<^sub>S) A\" by (metis S_domain empty_iff rationalized)\n  hence a_max: \"y \\<in> A \\<Longrightarrow> \\<not>general_preference.P (R\\<^sub>S) y x\" for y using general_preference.Max_def[OF g, of A] by auto\n\n  assume \"x \\<in> S B\"\n  hence \"x \\<in> general_preference.Max (R\\<^sub>S) B\" by (metis S_domain empty_iff rationalized)\n  hence b_max: \"y \\<in> B \\<Longrightarrow> \\<not>general_preference.P (R\\<^sub>S) y x\" for y using general_preference.Max_def[OF g, of B] by auto\n\n  have \"y \\<in> B \\<union> A \\<Longrightarrow> \\<not>general_preference.P (R\\<^sub>S) y x\" for y using a_max b_max by auto\n  hence \"x \\<in> general_preference.Max (R\\<^sub>S) (A \\<union> B)\" using general_preference.Max_def[OF g] using xb by blast\n  thus \"x \\<in> S (A \\<union> B)\" by (simp add: AU BU rationalized)\nqed\n\nend", "meta": {"author": "RWalkling", "repo": "Social-Choice-Theory", "sha": "67eeb15c321aa06381015736f6755b398d636c30", "save_path": "github-repos/isabelle/RWalkling-Social-Choice-Theory", "path": "github-repos/isabelle/RWalkling-Social-Choice-Theory/Social-Choice-Theory-67eeb15c321aa06381015736f6755b398d636c30/ChoiceFunction.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587875995482, "lm_q2_score": 0.8333245891029457, "lm_q1q2_score": 0.7406245514880256}}
{"text": "theory Lazy_List\n  imports Main \"$HIPSTER_HOME/IsaHipster\"\nbegin\nsetup Tactic_Data.set_coinduct_sledgehammer \n(*setup Tactic_Data.set_no_proof*) (* For measuring exploration time *)\nsetup Misc_Data.set_time (* Print out timing info *)\nsetup Misc_Data.set_noisy (* Verbose output on hipster calls *)\n\n(* Lazy list codatatype *)\ncodatatype (lset: 'a) Llist =\n      lnull: LNil\n    | LCons (lhd: 'a) (ltl: \"'a Llist\")\nwhere\n \"ltl LNil = LNil\"\n\n(* Appending lazy lists *)\nprimcorec lappend :: \"'a Llist \\<Rightarrow> 'a Llist \\<Rightarrow> 'a Llist\"\nwhere\n  \"lappend xs ys = (case xs of LNil \\<Rightarrow> ys | LCons x xs' \\<Rightarrow> LCons x (lappend xs' ys))\"\n\ncohipster lappend\n(* The lemmas and proofs below are the output of the hipster call above \n   lemma_ac is lappend_LNil2 and lemma_ab is lappend_assoc from Coinductive_List *)\nlemma lemma_a [thy_expl]: \"lappend LNil y = y\"\n  by(coinduction arbitrary: y rule: Llist.coinduct_strong)\n    (simp add: lappend.code)\n\nlemma lemma_aa [thy_expl]: \"lappend (LCons y z) x2 = LCons y (lappend z x2)\"\n  by(coinduction arbitrary: x2 y z rule: Llist.coinduct_strong)\n    simp\n\nlemma lemma_ab [thy_expl]: \"lappend (lappend y z) x2 = lappend y (lappend z x2)\"\n  by(coinduction arbitrary: x2 y z rule: Llist.coinduct_strong)\n    (smt Llist.collapse(1) Llist.collapse(2) Llist.simps(4) Llist.simps(5) lappend.code lappend.disc(1) lappend.disc_iff(1) lappend.simps(4) lhd_def)\n\nlemma lemma_ac [thy_expl]: \"lappend y LNil = y\"\n  by(coinduction arbitrary: y rule: Llist.coinduct_strong)\n    (smt Llist.collapse(2) Llist.disc_eq_case(1) Llist.simps(4) Llist.simps(5) lappend.code lappend.simps(4) lhd_def lnull_def)\n\n(* Mapping a function over a lazy list *)\nprimcorec lmap :: \"('a \\<Rightarrow> 'b) \\<Rightarrow> 'a Llist \\<Rightarrow> 'b Llist\" where\n \"lmap f xs = (case xs of LNil \\<Rightarrow> LNil | LCons x xs \\<Rightarrow> LCons (f x) (lmap f xs))\"\n\ncohipster lmap\n(* The lemmas and proofs below are the output of the hipster call above *)\n\nlemma lemma_ad [thy_expl]: \"lmap z (LCons x2 LNil) = LCons (z x2) LNil\"\n  by(coinduction arbitrary: x2 z rule: Llist.coinduct_strong)\nsimp\n\nlemma lemma_ae [thy_expl]: \"LCons (z x2) (lmap z x3) = lmap z (LCons x2 x3)\"\n  by(coinduction arbitrary: x2 x3 z rule: Llist.coinduct_strong)\n    simp\n\nlemma lemma_af [thy_expl]: \"LCons (z x2) (LCons (z x3) LNil) = lmap z (LCons x2 (LCons x3 LNil))\"\nby(coinduction arbitrary: x2 x3 z rule: Llist.coinduct_strong)\n  (simp add: lemma_ad)\n\ncohipster lmap lappend\n(* The lemmas and proofs below are the output of the hipster call above\n   lemma_ag is lmap_lappend_distrib from Coinductive_List *)\nlemma lemma_ag [thy_expl]: \"lappend (lmap z x2) (lmap z x3) = lmap z (lappend x2 x3)\"\n  by(coinduction arbitrary: x2 x3 z rule: Llist.coinduct_strong)\n    (smt Llist.case_eq_if lappend.disc_iff(1) lappend.simps(3) lappend.simps(4) lmap.disc_iff(2) lmap.simps(3) lmap.simps(4))\n\n(* Converting a standard list to a lazy list *)\nprimrec llist_of :: \"'a list \\<Rightarrow> 'a Llist\"\nwhere\n  \"llist_of [] = LNil\"\n| \"llist_of (x#xs) = LCons x (llist_of xs)\"\n\n\ncohipster llist_of lappend append\n(* The lemmas and proofs below are the output of the hipster call above\n   lemma_ah is lappend_llist_of_llist_of from Coinductive_List *)\nlemma lemma_ah [thy_expl]: \"lappend (llist_of y) (llist_of z) = llist_of (y @ z)\"\n  apply (induct y arbitrary: z)\n  apply (simp add: lappend.code)\n  apply (simp add: lemma_aa)\n  done\n\ncohipster llist_of lmap map\n(* The lemmas and proofs below are the output of the hipster call above\n   lemma_ai is lmap_llist_of from Coinductive_List *)\nlemma lemma_ai [thy_expl]: \"lmap z (llist_of x2) = llist_of (map z x2)\"\n  apply (induct x2)\n  apply simp\n  apply (metis lemma_ae list.simps(9) llist_of.simps(2))\n  done\n\n(* Extended natural numbers *)\ncodatatype ENat = is_zero: EZ | ESuc (epred: ENat)\n\n(* Length of a lazy list *)\nprimcorec llength :: \"'a Llist \\<Rightarrow> ENat\" where\n\"llength xs = (case xs of LNil \\<Rightarrow> EZ | LCons y ys \\<Rightarrow> ESuc (llength ys))\"\n\ncohipster llength\n(* The lemmas and proofs below are the output of the hipster call above *)\nlemma lemma_aj [thy_expl]: \"llength (LCons y z) = ESuc (llength z)\"\n  by(coinduction arbitrary: y z rule: ENat.coinduct_strong)\n    simp\n\ncohipster llength lmap\n(* The lemmas and proofs below are the output of the hipster call above\n   lemma_ak is llength_lmap from Coinductive_List *)\nlemma lemma_ak [thy_expl]: \"llength (lmap z x2) = llength x2\"\n  by(coinduction arbitrary: x2 z rule: ENat.coinduct_strong)\n    (metis Llist.case_eq_if llength.disc_iff(2) llength.sel lmap.disc_iff(2) lmap.simps(4))\n\n(* Addition on extended natural numbers *)\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\ncohipster eplus\n(* The lemmas and proofs below are the output of the hipster call above\n   lemma_am is iadd_Suc_right and lemma_an and unknown lemma in line 130\n   are proved in lines 171-180 of Extended_Nat *)\nlemma lemma_al [thy_expl]: \"eplus x EZ = x\"\n  by(coinduction arbitrary: x rule: ENat.coinduct_strong)\nsimp\n\nlemma lemma_am [thy_expl]: \"eplus x (ESuc y) = ESuc (eplus x y)\"\n by(coinduction arbitrary: x y rule: ENat.coinduct_strong)\n    (metis ENat.disc(2) ENat.sel eplus.code)\n\nlemma lemma_an [thy_expl]: \"eplus (eplus x y) z = eplus x (eplus y z)\"\n  by(coinduction arbitrary: x y z rule: ENat.coinduct_strong)\nauto\n\nlemma unknown [thy_expl]: \"eplus y x = eplus x y\"\n  oops\n\ncohipster llength lappend eplus\n(* The lemmas and proofs below are the output of the hipster call above\n   lemma_aq is llength_lappend from Coinductive_List *)\nlemma lemma_ao [thy_expl]: \"eplus EZ (llength y) = llength y\"\n  by(coinduction arbitrary: y rule: ENat.coinduct_strong)\n    simp\n\nlemma lemma_ap [thy_expl]: \"eplus (ESuc y) (llength z) = ESuc (eplus y (llength z))\"\n by(coinduction arbitrary: y z rule: ENat.coinduct_strong)\nsimp\n\nlemma lemma_aq [thy_expl]: \"eplus (llength y) (llength z) = llength (lappend y z)\"\n  by(coinduction arbitrary: y z rule: ENat.coinduct_strong)\n(smt ENat.sel Llist.case_eq_if eplus.disc_iff(1) eplus.sel lappend.ctr(2) lappend.disc_iff(1) lemma_aj llength.disc_iff(2) llength.sel)\n\nlemma lemma_ar [thy_expl]: \"llength (lappend z (LCons y x2)) = ESuc (llength (lappend z x2))\"\nby(coinduction arbitrary: x2 y z rule: ENat.coinduct_strong)\n  (metis Lazy_List.lemma_aq lemma_aj lemma_am)\n\nlemma lemma_as [thy_expl]: \"llength (lappend z y) = llength (lappend y z)\"\nby(coinduction arbitrary: y z rule: ENat.coinduct_strong)\n  (smt ENat.sel Lazy_List.lemma_aq Llist.case_eq_if eplus.code lappend.disc_iff(1) lemma_am llength.ctr(2) llength.disc_iff(2))\n\nlemma unknown [thy_expl]: \"eplus y x = eplus x y\"\n  oops\n\n(* Taking from a lazy list *)\nprimcorec ltake :: \"ENat \\<Rightarrow> 'a Llist \\<Rightarrow> 'a Llist\" where\n\"ltake n xs = (case xs of LNil \\<Rightarrow> LNil \n                  | LCons y ys \\<Rightarrow> (case n of EZ \\<Rightarrow> LNil | ESuc n \\<Rightarrow> LCons y (ltake n ys)\n                                  )\n               )\"\n\ncohipster ltake\n(* The lemmas and proofs below are the output of the hipster call above *)\nlemma lemma_at [thy_expl]: \"ltake z (ltake y x2) = ltake y (ltake z x2)\"\n  by(coinduction arbitrary: x2 y z rule: Llist.coinduct_strong)\n(smt ENat.case_eq_if Llist.case_eq_if ltake.disc(1) ltake.disc(2) ltake.simps(3) ltake.simps(4))\n\nlemma lemma_au [thy_expl]: \"ltake y (ltake y z) = ltake y z\"\nby(coinduction arbitrary: y z rule: Llist.coinduct_strong)\n  (smt ENat.collapse(2) ENat.simps(5) Llist.collapse(2) Llist.simps(5) ltake.disc_iff(1) ltake.simps(3) ltake.simps(4))\n\nlemma lemma_av [thy_expl]: \"ltake y (ltake (ESuc y) z) = ltake y z\"\nby(coinduction arbitrary: y z rule: Llist.coinduct_strong)\n  (smt ENat.collapse(2) ENat.discI(2) ENat.simps(5) Llist.case_eq_if ltake.disc(1) ltake.disc(2) ltake.simps(3) ltake.simps(4))\n\nlemma lemma_aw [thy_expl]: \"ltake (ESuc z) (LCons y x2) = LCons y (ltake z x2)\"\n  by(coinduction arbitrary: x2 y z rule: Llist.coinduct_strong)\n    simp\n\nlemma lemma_ax [thy_expl]: \"ltake y (LCons z (ltake y x2)) = ltake y (LCons z x2)\"\n by(coinduction arbitrary: x2 y z rule: Llist.coinduct_strong)\n    (metis Lazy_List.lemma_aw lemma_av)\n\nlemma lemma_ay [thy_expl]: \"ltake y (ltake (ESuc (ESuc y)) z) = ltake y z\"\nby(coinduction arbitrary: y z rule: Llist.coinduct_strong)\n  (metis lemma_av)\n\nlemma lemma_az [thy_expl]: \"ltake (ESuc y) (ltake (ESuc EZ) z) = ltake (ESuc EZ) z\"\nby(coinduction arbitrary: y z rule: Llist.coinduct_strong)\n  (smt ENat.disc(1) Lazy_List.lemma_aw Llist.collapse(2) Llist.disc(1) ltake.ctr(1))\n\ncohipster ltake lmap\n(* The lemmas and proofs below are the output of the hipster call above\n   lemma_ba is ltake_lmap from Coinductive_List *)\nlemma lemma_ba [thy_expl]: \"ltake x2 (lmap z x3) = lmap z (ltake x2 x3)\"\n  by(coinduction arbitrary: x2 x3 z rule: Llist.coinduct_strong)\n    (smt ENat.collapse(2) Llist.collapse(2) Llist.sel(1) Llist.sel(3) lemma_ae lemma_aw lmap.disc_iff(2) ltake.disc(1) ltake.disc(2))\n\nlemma lemma_bb [thy_expl]: \"lmap x2 (ltake z (LCons x3 LNil)) = ltake z (LCons (x2 x3) LNil)\"\n  by(coinduction arbitrary: x2 x3 z rule: Llist.coinduct_strong)\n    (metis lemma_ad lemma_ba)\n\n(* Iteratively building a lazy list from a function and an element *)\nprimcorec iterates :: \"('a \\<Rightarrow> 'a) \\<Rightarrow> 'a \\<Rightarrow> 'a Llist\" \nwhere \"iterates f x = LCons x (iterates f (f x))\"\n\ncohipster lmap iterates\n(* The lemmas and proofs below are the output of the hipster call above\n   lemma_bc is ltake_lmap from Coinductive_List *)\nlemma lemma_bc [thy_expl]: \"lmap y (iterates y z) = iterates y (y z)\"\n  by(coinduction arbitrary: y z rule: Llist.coinduct_strong)\n    (smt Lazy_List.iterates.simps(2) Llist.case_eq_if Llist.sel(3) iterates.code lemma_ae lmap.disc_iff(2) lmap.simps(3) lnull_def)\n\nlemma lemma_bd [thy_expl]: \"lmap z (LCons y (iterates z x2)) = LCons (z y) (iterates z (z x2))\"\n  by(coinduction arbitrary: x2 y z rule: Llist.coinduct_strong)\n    (simp add: lemma_bc)\n\ncohipster lappend iterates\n(* The lemmas and proofs below are the output of the hipster call above\n   lemma_be is lmap_iterates from Coinductive_List *)\nlemma lemma_be [thy_expl]: \"lappend (iterates z x2) y = iterates z x2\"\n  by(coinduction arbitrary: x2 y z rule: Llist.coinduct_strong)\n    (smt Llist.sel(3) Llist.simps(5) iterates.code iterates.disc_iff lappend.disc_iff(2) lemma_aa lhd_def)\n\nend\n\n", "meta": {"author": "moajohansson", "repo": "IsaHipster", "sha": "91f6ea3f1166a9de547722ece6445fe843ad89b4", "save_path": "github-repos/isabelle/moajohansson-IsaHipster", "path": "github-repos/isabelle/moajohansson-IsaHipster/IsaHipster-91f6ea3f1166a9de547722ece6445fe843ad89b4/benchmark/AISC18/Lazy_List.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942119105695, "lm_q2_score": 0.819893340314393, "lm_q1q2_score": 0.7406049086900139}}
{"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_TSortCount\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 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 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 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\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  \"((count x (tsort 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_TSortCount.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942041005328, "lm_q2_score": 0.8198933425148213, "lm_q1q2_score": 0.7406049042742511}}
{"text": "(*\n  File:    Buffons_Needle.thy\n  Author:  Manuel Eberl <eberlm@in.tum.de>\n\n  A formal solution of Buffon's needle problem.\n*)\nsection \\<open>Buffon's Needle Problem\\<close>\ntheory Buffons_Needle\n  imports \"HOL-Probability.Probability\"\nbegin\n\nsubsection \\<open>Auxiliary material\\<close>\n\nlemma sin_le_zero': \"sin x \\<le> 0\" if \"x \\<ge> -pi\" \"x \\<le> 0\" for x\n  by (metis minus_le_iff neg_0_le_iff_le sin_ge_zero sin_minus that(1) that(2))\n\n\nsubsection \\<open>Problem definition\\<close>\n\ntext \\<open>\n  Consider a needle of length $l$ whose centre has the $x$-coordinate $x$. The following then\n  defines the set of all $x$-coordinates that the needle covers \n  (i.e. the projection of the needle onto the $x$-axis.)\n\\<close>\ndefinition needle :: \"real \\<Rightarrow> real \\<Rightarrow> real \\<Rightarrow> real set\" where\n  \"needle l x \\<phi> = closed_segment (x - l / 2 * sin \\<phi>) (x + l / 2 * sin \\<phi>)\"\n\ntext \\<open>\n  Buffon's Needle problem is then this: Assuming the needle's $x$ position is chosen uniformly\n  at random in a strip of width $d$ centred at the origin, what is the probability that the \n  needle crosses at least one of the left/right boundaries of that strip (located at \n  $x = \\pm\\frac{1}{2}d$)?\n\\<close>\ndefinition buffon :: \"real \\<Rightarrow> real \\<Rightarrow> bool measure\" where\n  \"buffon l d = \n     do {\n       (x, \\<phi>) \\<leftarrow> uniform_measure lborel ({-d/2..d/2} \\<times> {-pi..pi});\n       return (count_space UNIV) (needle l x \\<phi> \\<inter> {-d/2, d/2} \\<noteq> {})\n     }\"\n\n\nsubsection \\<open>Derivation of the solution\\<close>\n\ntext \\<open>\n  The following form is a bit easier to handle.\n\\<close>\nlemma buffon_altdef:\n  \"buffon l d =\n     do {\n       (x, \\<phi>) \\<leftarrow> uniform_measure lborel ({-d/2..d/2} \\<times> {-pi..pi});\n       return (count_space UNIV) \n         (let a = x - l / 2 * sin \\<phi>; b = x + l / 2 * sin \\<phi>\n          in  min a b + d/2 \\<le> 0 \\<and> max a b + d/2 \\<ge> 0 \\<or> min a b - d/2 \\<le> 0 \\<and> max a b - d/2 \\<ge> 0)\n     }\"\nproof -\n  note buffon_def[of l d]\n  also {\n    have \"(\\<lambda>(x,\\<phi>). needle l x \\<phi> \\<inter> {-d/2, d/2} \\<noteq> {}) =\n        (\\<lambda>(x,\\<phi>). let a = x - l / 2 * sin \\<phi>; b = x + l / 2 * sin \\<phi>\n                 in  -d/2 \\<ge> min a b \\<and> -d/2 \\<le> max a b \\<or> min a b \\<le> d/2 \\<and> max a b \\<ge> d/2)\"\n      by (auto simp: needle_def Let_def closed_segment_eq_real_ivl min_def max_def)\n    also have \"\\<dots> = \n      (\\<lambda>(x,\\<phi>). let a = x - l / 2 * sin \\<phi>; b = x + l / 2 * sin \\<phi>\n               in  min a b + d/2 \\<le> 0 \\<and> max a b + d/2 \\<ge> 0 \\<or> min a b - d/2 \\<le> 0 \\<and> max a b - d/2 \\<ge> 0)\"\n      by (auto simp add: algebra_simps Let_def)\n    finally have \"(\\<lambda>(x, \\<phi>). return (count_space UNIV) (needle l x \\<phi> \\<inter> {- d/2, d/2} \\<noteq> {})) =\n                  (\\<lambda>(x,\\<phi>). return (count_space UNIV) \n                    (let a = x - l / 2 * sin \\<phi>; b = x + l / 2 * sin \\<phi>\n                     in  min a b + d/2 \\<le> 0 \\<and> max a b + d/2 \\<ge> 0 \\<or> min a b - d/2 \\<le> 0 \\<and> max a b - d/2 \\<ge> 0))\"\n      by (simp add: case_prod_unfold fun_eq_iff)\n  }\n  finally show ?thesis .\nqed\n    \ntext \\<open>\n  It is obvious that the problem boils down to determining the measure of the following set:\n\\<close>\ndefinition buffon_set :: \"real \\<Rightarrow> real \\<Rightarrow> (real \\<times> real) set\" where\n  \"buffon_set l d = {(x,\\<phi>) \\<in> {-d/2..d/2} \\<times> {-pi..pi}. abs x \\<ge> d / 2 - abs (sin \\<phi>) * l / 2}\"\n\ntext \\<open>\n  By using the symmetry inherent in the problem, we can reduce the problem to the following \n  set, which corresponds to one quadrant of the original set:\n\\<close>\ndefinition buffon_set' :: \"real \\<Rightarrow> real \\<Rightarrow> (real \\<times> real) set\" where\n  \"buffon_set' l d = {(x,\\<phi>) \\<in> {0..d/2} \\<times> {0..pi}. x \\<ge> d / 2 - sin \\<phi> * l / 2}\"\n\nlemma closed_buffon_set [simp, intro, measurable]: \"closed (buffon_set l d)\"\nproof -\n  have \"buffon_set l d = ({-d/2..d/2} \\<times> {-pi..pi}) \\<inter> \n          (\\<lambda>z. abs (fst z) + abs (sin (snd z)) * l / 2 - d / 2) -` {0..}\" \n    (is \"_ = ?A\") unfolding buffon_set_def by auto\n  also have \"closed \\<dots>\"\n    by (intro closed_Int closed_vimage closed_Times) (auto intro!: continuous_intros)\n  finally show ?thesis by simp\nqed\n\nlemma closed_buffon_set' [simp, intro, measurable]: \"closed (buffon_set' l d)\"\nproof -\n  have \"buffon_set' l d = ({0..d/2} \\<times> {0..pi}) \\<inter> \n          (\\<lambda>z. fst z + sin (snd z) * l / 2 - d / 2) -` {0..}\" \n    (is \"_ = ?A\") unfolding buffon_set'_def by auto\n  also have \"closed \\<dots>\"\n    by (intro closed_Int closed_vimage closed_Times) (auto intro!: continuous_intros)\n  finally show ?thesis by simp\nqed\n\nlemma measurable_buffon_set [measurable]: \"buffon_set l d \\<in> sets borel\" \n  by measurable\n\nlemma measurable_buffon_set' [measurable]: \"buffon_set' l d \\<in> sets borel\" \n  by measurable\n\n\ncontext\n  fixes d l :: real\n  assumes d: \"d > 0\" and l: \"l > 0\"\nbegin\n\nlemma buffon_altdef':\n  \"buffon l d = distr (uniform_measure lborel ({-d/2..d/2} \\<times> {-pi..pi}))\n                  (count_space UNIV) (\\<lambda>z. z \\<in> buffon_set l d)\"\nproof -\n  let ?P = \"\\<lambda>(x,\\<phi>). let a = x - l / 2 * sin \\<phi>; b = x + l / 2 * sin \\<phi>\n                    in  min a b + d/2 \\<le> 0 \\<and> max a b + d/2 \\<ge> 0 \\<or> min a b - d/2 \\<le> 0 \\<and> max a b - d/2 \\<ge> 0\"\n  have \"buffon l d = \n          uniform_measure lborel ({- d / 2..d / 2} \\<times> {-pi..pi}) \\<bind>\n          (\\<lambda>z. return (count_space UNIV) (?P z))\"\n    unfolding buffon_altdef case_prod_unfold by simp\n  also have \"\\<dots> = uniform_measure lborel ({- d / 2..d / 2} \\<times> {-pi..pi}) \\<bind>\n          (\\<lambda>z. return (count_space UNIV) (z \\<in> buffon_set l d))\"\n  proof (intro bind_cong_AE AE_uniform_measureI AE_I2 impI refl return_measurable, goal_cases)\n    show \"(\\<lambda>z. return (count_space UNIV) (?P z))\n             \\<in> uniform_measure lborel ({- d / 2..d / 2} \\<times> {- pi..pi}) \\<rightarrow>\\<^sub>M\n                 subprob_algebra (count_space UNIV)\"\n      unfolding Let_def case_prod_unfold lborel_prod [symmetric] by measurable\n    show \"(\\<lambda>z. return (count_space UNIV) (z \\<in> buffon_set l d))\n            \\<in> uniform_measure lborel ({- d / 2..d / 2} \\<times> {- pi..pi}) \\<rightarrow>\\<^sub>M\n                subprob_algebra (count_space UNIV)\" by simp\n    \n    case (4 z)\n    hence \"?P z \\<longleftrightarrow> z \\<in> buffon_set l d\"\n    proof (cases \"snd z \\<ge> 0\")\n      case True\n      with 4 have \"fst z - l / 2 * sin (snd z) \\<le> fst z + l / 2 * sin (snd z)\" using l\n        by (auto simp: sin_ge_zero)\n      moreover from True and 4 have \"sin (snd z) \\<ge> 0\" by (auto simp: sin_ge_zero)\n      ultimately show ?thesis using 4 True unfolding buffon_set_def\n        by (force simp: field_simps Let_def min_def max_def case_prod_unfold abs_if)\n    next\n      case False\n      with 4 have \"fst z - l / 2 * sin (snd z) \\<ge> fst z + l / 2 * sin (snd z)\" using l\n        by (auto simp: sin_le_zero' mult_nonneg_nonpos)\n      moreover from False and 4 have \"sin (snd z) \\<le> 0\" by (auto simp: sin_le_zero')\n      ultimately show ?thesis using 4 and False\n        unfolding buffon_set_def using l d\n        by (force simp: field_simps Let_def min_def max_def case_prod_unfold abs_if)\n    qed\n    thus ?case by (simp only: )\n  qed (simp_all add: borel_prod [symmetric])\n  also have \"\\<dots> = distr (uniform_measure lborel ({-d/2..d/2} \\<times> {-pi..pi})) \n                    (count_space UNIV) (\\<lambda>z. z \\<in> buffon_set l d)\"\n    by (rule bind_return_distr') simp_all\n  finally show ?thesis .\nqed\n\nlemma buffon_prob_aux:\n  \"emeasure (buffon l d) {True} = emeasure lborel (buffon_set l d) / ennreal (2 * d * pi)\"\nproof -\n  have [measurable]: \"A \\<times> B \\<in> sets borel\" if \"A \\<in> sets borel\" \"B \\<in> sets borel\" \n    for A B :: \"real set\" using that unfolding borel_prod [symmetric] by simp\n    \n  have \"emeasure (buffon l d) {True} = \n          emeasure (uniform_measure lborel ({- (d / 2)..d / 2} \\<times> {-pi..pi}))\n          ((\\<lambda>z. z \\<in> buffon_set l d) -` {True})\" (is \"_ = emeasure ?M _\")\n    by (simp add: buffon_altdef' emeasure_distr)\n  also have \"(\\<lambda>z. z \\<in> buffon_set l d) -` {True} = buffon_set l d\" by auto\n  also have \"buffon_set l d \\<subseteq> {-d/2..d/2} \\<times> {-pi..pi}\"\n    using l d by (auto simp: buffon_set_def)\n  hence \"emeasure ?M (buffon_set l d) = \n           emeasure lborel (buffon_set l d) / emeasure lborel ({- (d / 2)..d / 2} \\<times> {-pi..pi})\"\n    by (subst emeasure_uniform_measure) (simp_all add: Int_absorb1)\n  also have \"emeasure lborel ({- (d / 2)..d / 2} \\<times> {-pi..pi}) = ennreal (2 * pi * d)\"\n    using d by (simp add: lborel_prod [symmetric] lborel.emeasure_pair_measure_Times\n                          ennreal_mult algebra_simps)\n  finally show ?thesis by (simp add: mult_ac)\nqed\n\nlemma emeasure_buffon_set_conv_buffon_set':\n  \"emeasure lborel (buffon_set l d) = 4 * emeasure lborel (buffon_set' l d)\"\nproof -\n  have distr_lborel [simp]: \"distr M lborel f = distr M borel f\" for M and f :: \"real \\<Rightarrow> real\"\n    by (rule distr_cong) simp_all\n    \n  define A where \"A = buffon_set' l d\"\n  define B C D where \"B = (\\<lambda>x. (-fst x, snd x)) -` A\" and \"C = (\\<lambda>x. (fst x, -snd x)) -` A\" and\n      \"D = (\\<lambda>x. (-fst x, -snd x)) -` A\"\n  have meas [measurable]:\n     \"(\\<lambda>x::real \\<times> real. (-fst x, snd x)) \\<in> borel_measurable borel\"\n     \"(\\<lambda>x::real \\<times> real. (fst x, -snd x)) \\<in> borel_measurable borel\"\n     \"(\\<lambda>x::real \\<times> real. (-fst x, -snd x)) \\<in> borel_measurable borel\"\n    unfolding borel_prod [symmetric] by measurable\n  have meas' [measurable]: \"A \\<in> sets borel\" \"B \\<in> sets borel\" \"C \\<in> sets borel\" \"D \\<in> sets borel\"\n    unfolding A_def B_def C_def D_def by (rule measurable_buffon_set' measurable_sets_borel meas)+\n  \n  have *: \"buffon_set l d = A \\<union> B \\<union> C \\<union> D\"\n  proof (intro equalityI subsetI, goal_cases)\n    case (1 z)\n    show ?case\n    proof (cases \"fst z \\<ge> 0\"; cases \"snd z \\<ge> 0\")\n      assume \"fst z \\<ge> 0\" \"snd z \\<ge> 0\"\n      with 1 have \"z \\<in> A\"\n        by (auto split: prod.splits simp: buffon_set_def buffon_set'_def sin_ge_zero A_def)\n      thus ?thesis by blast   \n    next\n      assume \"\\<not>(fst z \\<ge> 0)\" \"snd z \\<ge> 0\"\n      with 1 have \"z \\<in> B\"\n        by (auto split: prod.splits simp: buffon_set_def buffon_set'_def sin_ge_zero A_def B_def)\n      thus ?thesis by blast\n    next    \n      assume \"fst z \\<ge> 0\" \"\\<not>(snd z \\<ge> 0)\"\n      with 1 have \"z \\<in> C\"\n        by (auto split: prod.splits simp: buffon_set_def buffon_set'_def sin_le_zero' A_def C_def)\n      thus ?thesis by blast   \n    next\n      assume \"\\<not>(fst z \\<ge> 0)\" \"\\<not>(snd z \\<ge> 0)\"\n      with 1 have \"z \\<in> D\"\n        by (auto split: prod.splits simp: buffon_set_def buffon_set'_def sin_le_zero' A_def D_def)\n      thus ?thesis by blast\n    qed\n  qed (auto simp: buffon_set_def buffon_set'_def sin_ge_zero sin_le_zero'  A_def B_def C_def D_def)\n  \n  have \"A \\<inter> B = {0} \\<times> ({0..pi} \\<inter> {\\<phi>. sin \\<phi> * l - d \\<ge> 0})\"\n    using d l by (auto simp: buffon_set'_def  A_def B_def C_def D_def)\n  moreover have \"emeasure lborel \\<dots> = 0\"\n    unfolding lborel_prod [symmetric] by (subst lborel.emeasure_pair_measure_Times) simp_all\n  ultimately have AB: \"(A \\<inter> B) \\<in> null_sets lborel\"\n    unfolding lborel_prod [symmetric] by (simp add: null_sets_def)\n  \n  have \"C \\<inter> D = {0} \\<times> ({-pi..0} \\<inter> {\\<phi>. -sin \\<phi> * l - d \\<ge> 0})\"\n    using d l by (auto simp: buffon_set'_def  A_def B_def C_def D_def)\n  moreover have \"emeasure lborel \\<dots> = 0\"\n    unfolding lborel_prod [symmetric] by (subst lborel.emeasure_pair_measure_Times) simp_all\n  ultimately have CD: \"(C \\<inter> D) \\<in> null_sets lborel\"\n    unfolding lborel_prod [symmetric] by (simp add: null_sets_def)\n\n  have \"A \\<inter> D = {}\" \"B \\<inter> C = {}\" using d l \n    by (auto simp: buffon_set'_def A_def D_def B_def C_def)\n  moreover have \"A \\<inter> C = {(d/2, 0)}\" \"B \\<inter> D = {(-d/2, 0)}\"\n    using d l by (auto simp: case_prod_unfold buffon_set'_def A_def B_def C_def D_def)\n  ultimately have AD: \"A \\<inter> D \\<in> null_sets lborel\" and BC: \"B \\<inter> C \\<in> null_sets lborel\" and\n    AC: \"A \\<inter> C \\<in> null_sets lborel\" and BD: \"B \\<inter> D \\<in> null_sets lborel\" by auto\n  \n  note *\n  also have \"emeasure lborel (A \\<union> B \\<union> C \\<union> D) = emeasure lborel (A \\<union> B \\<union> C) + emeasure lborel D\"\n    using AB AC AD BC BD CD by (intro emeasure_Un') (auto simp: Int_Un_distrib2)\n  also have \"emeasure lborel (A \\<union> B \\<union> C) = emeasure lborel (A \\<union> B) + emeasure lborel C\"\n    using AB AC BC using AB AC AD BC BD CD by (intro emeasure_Un') (auto simp: Int_Un_distrib2)\n  also have \"emeasure lborel (A \\<union> B) = emeasure lborel A + emeasure lborel B\"\n    using AB using AB AC AD BC BD CD by (intro emeasure_Un') (auto simp: Int_Un_distrib2)\n  also have \"emeasure lborel B = emeasure (distr lborel lborel (\\<lambda>(x,y). (-x, y))) A\"\n    (is \"_ = emeasure ?M _\") unfolding B_def \n    by (subst emeasure_distr) (simp_all add: case_prod_unfold)\n  also have \"?M = lborel\" unfolding lborel_prod [symmetric]\n    by (subst pair_measure_distr [symmetric]) (simp_all add: sigma_finite_lborel lborel_distr_uminus)\n  also have \"emeasure lborel C = emeasure (distr lborel lborel (\\<lambda>(x,y). (x, -y))) A\"\n    (is \"_ = emeasure ?M _\") unfolding C_def \n    by (subst emeasure_distr) (simp_all add: case_prod_unfold)\n  also have \"?M = lborel\" unfolding lborel_prod [symmetric]\n    by (subst pair_measure_distr [symmetric]) (simp_all add: sigma_finite_lborel lborel_distr_uminus)\n  also have \"emeasure lborel D = emeasure (distr lborel lborel (\\<lambda>(x,y). (-x, -y))) A\"\n    (is \"_ = emeasure ?M _\") unfolding D_def \n    by (subst emeasure_distr) (simp_all add: case_prod_unfold)\n  also have \"?M = lborel\" unfolding lborel_prod [symmetric]\n    by (subst pair_measure_distr [symmetric]) (simp_all add: sigma_finite_lborel lborel_distr_uminus)\n  finally have \"emeasure lborel (buffon_set l d) = \n                  of_nat (Suc (Suc (Suc (Suc 0)))) * emeasure lborel A\"\n    unfolding of_nat_Suc ring_distribs by simp\n  also have \"of_nat (Suc (Suc (Suc (Suc 0)))) = (4 :: ennreal)\" by simp\n  finally show ?thesis unfolding A_def .\nqed \n\ntext \\<open>\n  It only remains now to compute the measure of @{const buffon_set'}. We first reduce this\n  problem to a relatively simple integral:\n\\<close>\nlemma emeasure_buffon_set':\n  \"emeasure lborel (buffon_set' l d) = \n     ennreal (integral {0..pi} (\\<lambda>x. min (d / 2) (sin x * l / 2)))\"\n  (is \"emeasure lborel ?A = _\")\nproof -  \n  have \"emeasure lborel ?A = nn_integral lborel (\\<lambda>x. indicator ?A x)\"\n    by (intro nn_integral_indicator [symmetric]) simp_all\n  also have \"(lborel :: (real \\<times> real) measure) = lborel \\<Otimes>\\<^sub>M lborel\" \n    by (simp only: lborel_prod)\n  also have \"nn_integral \\<dots> (indicator ?A) = (\\<integral>\\<^sup>+\\<phi>. \\<integral>\\<^sup>+x. indicator ?A (x, \\<phi>) \\<partial>lborel \\<partial>lborel)\"\n    by (subst lborel_pair.nn_integral_snd [symmetric]) (simp_all add: lborel_prod borel_prod)\n  also have \"\\<dots> = (\\<integral>\\<^sup>+\\<phi>. \\<integral>\\<^sup>+x. indicator {0..pi} \\<phi> * indicator {max 0 (d/2 - sin \\<phi> * l / 2) .. d/2} x \\<partial>lborel \\<partial>lborel)\"\n    using d l by (intro nn_integral_cong) (auto simp: indicator_def field_simps buffon_set'_def)\n  also have \"\\<dots> = \\<integral>\\<^sup>+ \\<phi>. indicator {0..pi} \\<phi> * emeasure lborel {max 0 (d / 2 - sin \\<phi> * l / 2)..d / 2} \\<partial>lborel\"\n    by (subst nn_integral_cmult) simp_all\n  also have \"\\<dots> = \\<integral>\\<^sup>+ \\<phi>. ennreal (indicator {0..pi} \\<phi> * min (d / 2) (sin \\<phi> * l / 2)) \\<partial>lborel\"\n    (is \"_ = ?I\") using d l by (intro nn_integral_cong) (auto simp: indicator_def sin_ge_zero max_def min_def)\n  also have \"integrable lborel (\\<lambda>\\<phi>. (d / 2) * indicator {0..pi} \\<phi>)\" by simp\n  hence int: \"integrable lborel (\\<lambda>\\<phi>. indicator {0..pi} \\<phi> * min (d / 2) (sin \\<phi> * l / 2))\"\n    by (rule Bochner_Integration.integrable_bound)\n       (insert l d, auto intro!: AE_I2 simp: indicator_def min_def sin_ge_zero)\n  hence \"?I = set_lebesgue_integral lborel {0..pi} (\\<lambda>\\<phi>. min (d / 2) (sin \\<phi> * l / 2))\"\n    by (subst nn_integral_eq_integral, assumption)\n       (insert d l, auto intro!: AE_I2 simp: sin_ge_zero min_def indicator_def set_lebesgue_integral_def)\n  also have \"\\<dots> = ennreal (integral {0..pi} (\\<lambda>x. min (d / 2) (sin x * l / 2)))\"\n    (is \"_ = ennreal ?I\") using int by (subst set_borel_integral_eq_integral) (simp_all add: set_integrable_def)\n  finally show ?thesis by (simp add: lborel_prod)\nqed\n\n  \ntext \\<open>\n  We now have to distinguish two cases: The first and easier one is that where the length \n  of the needle, $l$, is less than or equal to the strip width, $d$:\n\\<close>\ncontext\n  assumes l_le_d: \"l \\<le> d\"\nbegin\n\nlemma emeasure_buffon_set'_short: \"emeasure lborel (buffon_set' l d) = ennreal l\"\nproof -\n  have \"emeasure lborel (buffon_set' l d) =\n          ennreal (integral {0..pi} (\\<lambda>x. min (d / 2) (sin x * l / 2)))\" (is \"_ = ennreal ?I\")\n    by (rule emeasure_buffon_set')\n  also have *: \"sin \\<phi> * l \\<le> d\" if \"\\<phi> \\<ge> 0\" \"\\<phi> \\<le> pi\" for \\<phi>\n    using mult_mono[OF l_le_d sin_le_one _ sin_ge_zero] that d by (simp add: algebra_simps)\n  have \"?I = integral {0..pi} (\\<lambda>x. (l / 2) * sin x)\"\n    using l d l_le_d  \n    by (intro integral_cong) (auto dest: * simp: min_def sin_ge_zero)\n  also have \"\\<dots> = l / 2 * integral {0..pi} sin\" by simp\n  also have \"(sin has_integral (-cos pi - (- cos 0))) {0..pi}\"\n    by (intro fundamental_theorem_of_calculus)\n       (auto intro!: derivative_eq_intros simp: has_field_derivative_iff_has_vector_derivative [symmetric])\n  hence \"integral {0..pi} sin = -cos pi - (-cos 0)\"\n    by (simp add: has_integral_iff)\n  finally show ?thesis by (simp add: lborel_prod)\nqed\n\nlemma emeasure_buffon_set_short: \"emeasure lborel (buffon_set l d) = 4 * ennreal l\"\n  by (simp add: emeasure_buffon_set_conv_buffon_set' emeasure_buffon_set'_short l_le_d)\n\ntheorem buffon_short: \"emeasure (buffon l d) {True} = ennreal (2 * l / (d * pi))\"\nproof -\n  have \"emeasure (buffon l d) {True} = ennreal (4 * l) / ennreal (2 * d * pi)\"\n    using d l by (subst buffon_prob_aux) (simp add: emeasure_buffon_set_short ennreal_mult)\n  also have \"\\<dots> = ennreal (4 * l / (2 * d * pi))\"\n    using d l by (subst divide_ennreal) simp_all\n  also have \"4 * l / (2 * d * pi) = 2 * l / (d * pi)\" by simp\n  finally show ?thesis .\nqed\n\nend\n\n\ntext \\<open>\n  The other case where the needle is at least as long as the strip width is more complicated:\n\\<close>\ncontext\n  assumes l_ge_d: \"l \\<ge> d\"\nbegin\n\nlemma emeasure_buffon_set'_long: \n  \"emeasure lborel (buffon_set' l d) =\n     ennreal (l * (1 - sqrt (1 - (d / l)\\<^sup>2)) + arccos (d / l) * d)\"\nproof -\n  define \\<phi>' where \"\\<phi>' = arcsin (d / l)\"\n  have \\<phi>'_nonneg: \"\\<phi>' \\<ge> 0\" unfolding \\<phi>'_def using d l l_ge_d arcsin_le_mono[of 0 \"d/l\"] \n    by (simp add: \\<phi>'_def)\n  have \\<phi>'_le: \"\\<phi>' \\<le> pi / 2\" unfolding \\<phi>'_def using arcsin_bounded[of \"d/l\"] d l l_ge_d\n    by (simp add: field_simps)\n  have ge_phi': \"sin \\<phi> \\<ge> d / l\" if \"\\<phi> \\<ge> \\<phi>'\" \"\\<phi> \\<le> pi / 2\" for \\<phi>\n    using arcsin_le_iff[of \"d / l\" \"\\<phi>\"] d l_ge_d that \\<phi>'_nonneg by (auto simp: \\<phi>'_def field_simps)\n  have le_phi': \"sin \\<phi> \\<le> d / l\" if \"\\<phi> \\<le> \\<phi>'\" \"\\<phi> \\<ge> 0\" for \\<phi>\n    using le_arcsin_iff[of \"d / l\" \"\\<phi>\"] d l_ge_d that \\<phi>'_le by (auto simp: \\<phi>'_def field_simps)\n    \n  let ?f = \"(\\<lambda>x. min (d / 2) (sin x * l / 2))\"\n  have \"emeasure lborel (buffon_set' l d) = ennreal (integral {0..pi} ?f)\" (is \"_ = ennreal ?I\")\n    by (rule emeasure_buffon_set')\n  also have \"?I = integral {0..pi/2} ?f + integral {pi/2..pi} ?f\"\n    by (rule Henstock_Kurzweil_Integration.integral_combine [symmetric]) (auto intro!: integrable_continuous_real continuous_intros)\n  also have \"integral {pi/2..pi} ?f = integral {-pi/2..0} (?f \\<circ> (\\<lambda>\\<phi>. \\<phi> + pi))\"\n    by (subst integral_shift) (auto intro!: continuous_intros)\n  also have \"\\<dots> = integral {-(pi/2)..-0} (\\<lambda>x. min (d / 2) (sin (-x) * l / 2))\" by (simp add: o_def)\n  also have \"\\<dots> = integral {0..pi/2} ?f\" (is \"_ = ?I\") by (subst Henstock_Kurzweil_Integration.integral_reflect_real) simp_all\n  also have \"\\<dots> + \\<dots> = 2 * \\<dots>\" by simp\n  also have \"?I = integral {0..\\<phi>'} ?f + integral {\\<phi>'..pi/2} ?f\"\n    using l d l_ge_d \\<phi>'_nonneg \\<phi>'_le\n    by (intro Henstock_Kurzweil_Integration.integral_combine [symmetric]) (auto intro!: integrable_continuous_real continuous_intros)\n  also have \"integral {0..\\<phi>'} ?f = integral {0..\\<phi>'} (\\<lambda>x. l / 2 * sin x)\"\n    using l by (intro integral_cong) (auto simp: min_def field_simps dest: le_phi')\n  also have \"((\\<lambda>x. l / 2 * sin x) has_integral (- (l / 2 * cos \\<phi>') - (- (l / 2 * cos 0)))) {0..\\<phi>'}\"\n    using \\<phi>'_nonneg\n    by (intro fundamental_theorem_of_calculus)\n       (auto simp: has_field_derivative_iff_has_vector_derivative [symmetric] intro!: derivative_eq_intros)\n  hence \"integral {0..\\<phi>'} (\\<lambda>x. l / 2 * sin x) = (1 - cos \\<phi>') * l / 2\"\n    by (simp add: has_integral_iff algebra_simps)\n  also have \"integral {\\<phi>'..pi/2} ?f = integral {\\<phi>'..pi/2} (\\<lambda>_. d / 2)\"\n    using l by (intro integral_cong) (auto simp: min_def field_simps dest: ge_phi')\n  also have \"\\<dots> = arccos (d / l) * d / 2\" using \\<phi>'_le d l l_ge_d \n    by (subst arccos_arcsin_eq) (auto simp: field_simps \\<phi>'_def)\n  also have \"cos \\<phi>' = sqrt (1 - (d / l)^2)\"\n    unfolding \\<phi>'_def by (rule cos_arcsin) (insert d l l_ge_d, auto simp: field_simps)\n  also have \"2 * ((1 - sqrt (1 - (d / l)\\<^sup>2)) * l / 2 + arccos (d / l) * d / 2) = \n               l * (1 - sqrt (1 - (d / l)\\<^sup>2)) + arccos (d / l) * d\"\n    using d l by (simp add: field_simps)\n  finally show ?thesis .\nqed\n\nlemma emeasure_buffon_set_long: \"emeasure lborel (buffon_set l d) = \n        4 * ennreal (l * (1 - sqrt (1 - (d / l)\\<^sup>2)) + arccos (d / l) * d)\"\n  by (simp add: emeasure_buffon_set_conv_buffon_set' emeasure_buffon_set'_long l_ge_d)\n\ntheorem buffon_long: \n  \"emeasure (buffon l d) {True} = \n     ennreal (2 / pi * ((l / d) - sqrt ((l / d)\\<^sup>2 - 1) + arccos (d / l)))\"\nproof -\n  have *: \"l * sqrt ((l\\<^sup>2 - d\\<^sup>2) / l\\<^sup>2) + 0 \\<le> l + d * arccos (d / l)\"\n    using d l_ge_d by (intro add_mono mult_nonneg_nonneg arccos_lbound) (auto simp: field_simps)\n  have \"emeasure (buffon l d) {True} = \n          ennreal (4 * (l - l * sqrt (1 - (d / l)\\<^sup>2) + arccos (d / l) * d)) / ennreal (2 * d * pi)\"\n    using d l l_ge_d * unfolding buffon_prob_aux emeasure_buffon_set_long ennreal_numeral [symmetric]\n    by (subst ennreal_mult [symmetric])\n       (auto intro!: add_nonneg_nonneg mult_nonneg_nonneg simp: field_simps)\n  also have \"\\<dots> = ennreal ((4 * (l - l * sqrt (1 - (d / l)\\<^sup>2) + arccos (d / l) * d)) / (2 * d * pi))\"\n    using d l * by (subst divide_ennreal) (auto simp: field_simps)\n  also have \"(4 * (l - l * sqrt (1 - (d / l)\\<^sup>2) + arccos (d / l) * d)) / (2 * d * pi) =\n               2 / pi * (l / d - l / d * sqrt ((d / l)^2 * ((l / d)^2 - 1)) + arccos (d / l))\"\n    using d l by (simp add: field_simps)\n  also have \"l / d * sqrt ((d / l)^2 * ((l / d)^2 - 1)) = sqrt ((l / d) ^ 2 - 1)\"\n    using d l l_ge_d unfolding real_sqrt_mult real_sqrt_abs by simp\n  finally show ?thesis .\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/Buffons_Needle/Buffons_Needle.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8633916134888613, "lm_q2_score": 0.8577681104440172, "lm_q1q2_score": 0.7405897928755518}}
{"text": "(*  Title:      HOL/Topological_Spaces.thy\n    Author:     Brian Huffman\n    Author:     Johannes H\u00f6lzl\n*)\n\nsection {* Topological Spaces *}\n\ntheory Topological_Spaces\nimports Main Conditionally_Complete_Lattices\nbegin\n\nnamed_theorems continuous_intros \"structural introduction rules for continuity\"\n\n\nsubsection {* Topological space *}\n\nclass \"open\" =\n  fixes \"open\" :: \"'a set \\<Rightarrow> bool\"\n\nclass topological_space = \"open\" +\n  assumes open_UNIV [simp, intro]: \"open UNIV\"\n  assumes open_Int [intro]: \"open S \\<Longrightarrow> open T \\<Longrightarrow> open (S \\<inter> T)\"\n  assumes open_Union [intro]: \"\\<forall>S\\<in>K. open S \\<Longrightarrow> open (\\<Union> K)\"\nbegin\n\ndefinition\n  closed :: \"'a set \\<Rightarrow> bool\" where\n  \"closed S \\<longleftrightarrow> open (- S)\"\n\nlemma open_empty [continuous_intros, intro, simp]: \"open {}\"\n  using open_Union [of \"{}\"] by simp\n\nlemma open_Un [continuous_intros, intro]: \"open S \\<Longrightarrow> open T \\<Longrightarrow> open (S \\<union> T)\"\n  using open_Union [of \"{S, T}\"] by simp\n\nlemma open_UN [continuous_intros, intro]: \"\\<forall>x\\<in>A. open (B x) \\<Longrightarrow> open (\\<Union>x\\<in>A. B x)\"\n  using open_Union [of \"B ` A\"] by simp\n\nlemma open_Inter [continuous_intros, intro]: \"finite S \\<Longrightarrow> \\<forall>T\\<in>S. open T \\<Longrightarrow> open (\\<Inter>S)\"\n  by (induct set: finite) auto\n\nlemma open_INT [continuous_intros, intro]: \"finite A \\<Longrightarrow> \\<forall>x\\<in>A. open (B x) \\<Longrightarrow> open (\\<Inter>x\\<in>A. B x)\"\n  using open_Inter [of \"B ` A\"] by simp\n\nlemma openI:\n  assumes \"\\<And>x. x \\<in> S \\<Longrightarrow> \\<exists>T. open T \\<and> x \\<in> T \\<and> T \\<subseteq> S\"\n  shows \"open S\"\nproof -\n  have \"open (\\<Union>{T. open T \\<and> T \\<subseteq> S})\" by auto\n  moreover have \"\\<Union>{T. open T \\<and> T \\<subseteq> S} = S\" by (auto dest!: assms)\n  ultimately show \"open S\" by simp\nqed\n\nlemma closed_empty [continuous_intros, intro, simp]:  \"closed {}\"\n  unfolding closed_def by simp\n\nlemma closed_Un [continuous_intros, intro]: \"closed S \\<Longrightarrow> closed T \\<Longrightarrow> closed (S \\<union> T)\"\n  unfolding closed_def by auto\n\nlemma closed_UNIV [continuous_intros, intro, simp]: \"closed UNIV\"\n  unfolding closed_def by simp\n\nlemma closed_Int [continuous_intros, intro]: \"closed S \\<Longrightarrow> closed T \\<Longrightarrow> closed (S \\<inter> T)\"\n  unfolding closed_def by auto\n\nlemma closed_INT [continuous_intros, intro]: \"\\<forall>x\\<in>A. closed (B x) \\<Longrightarrow> closed (\\<Inter>x\\<in>A. B x)\"\n  unfolding closed_def by auto\n\nlemma closed_Inter [continuous_intros, intro]: \"\\<forall>S\\<in>K. closed S \\<Longrightarrow> closed (\\<Inter> K)\"\n  unfolding closed_def uminus_Inf by auto\n\nlemma closed_Union [continuous_intros, intro]: \"finite S \\<Longrightarrow> \\<forall>T\\<in>S. closed T \\<Longrightarrow> closed (\\<Union>S)\"\n  by (induct set: finite) auto\n\nlemma closed_UN [continuous_intros, intro]: \"finite A \\<Longrightarrow> \\<forall>x\\<in>A. closed (B x) \\<Longrightarrow> closed (\\<Union>x\\<in>A. B x)\"\n  using closed_Union [of \"B ` A\"] by simp\n\nlemma open_closed: \"open S \\<longleftrightarrow> closed (- S)\"\n  unfolding closed_def by simp\n\nlemma closed_open: \"closed S \\<longleftrightarrow> open (- S)\"\n  unfolding closed_def by simp\n\nlemma open_Diff [continuous_intros, intro]: \"open S \\<Longrightarrow> closed T \\<Longrightarrow> open (S - T)\"\n  unfolding closed_open Diff_eq by (rule open_Int)\n\nlemma closed_Diff [continuous_intros, intro]: \"closed S \\<Longrightarrow> open T \\<Longrightarrow> closed (S - T)\"\n  unfolding open_closed Diff_eq by (rule closed_Int)\n\nlemma open_Compl [continuous_intros, intro]: \"closed S \\<Longrightarrow> open (- S)\"\n  unfolding closed_open .\n\nlemma closed_Compl [continuous_intros, intro]: \"open S \\<Longrightarrow> closed (- S)\"\n  unfolding open_closed .\n\nlemma open_Collect_neg: \"closed {x. P x} \\<Longrightarrow> open {x. \\<not> P x}\"\n  unfolding Collect_neg_eq by (rule open_Compl)\n\nlemma open_Collect_conj: assumes \"open {x. P x}\" \"open {x. Q x}\" shows \"open {x. P x \\<and> Q x}\"\n  using open_Int[OF assms] by (simp add: Int_def)\n\nlemma open_Collect_disj: assumes \"open {x. P x}\" \"open {x. Q x}\" shows \"open {x. P x \\<or> Q x}\"\n  using open_Un[OF assms] by (simp add: Un_def)\n\nlemma open_Collect_ex: \"(\\<And>i. open {x. P i x}) \\<Longrightarrow> open {x. \\<exists>i. P i x}\"\n  using open_UN[of UNIV \"\\<lambda>i. {x. P i x}\"] unfolding Collect_ex_eq by simp \n\nlemma open_Collect_imp: \"closed {x. P x} \\<Longrightarrow> open {x. Q x} \\<Longrightarrow> open {x. P x \\<longrightarrow> Q x}\"\n  unfolding imp_conv_disj by (intro open_Collect_disj open_Collect_neg)\n\nlemma open_Collect_const: \"open {x. P}\"\n  by (cases P) auto\n\nlemma closed_Collect_neg: \"open {x. P x} \\<Longrightarrow> closed {x. \\<not> P x}\"\n  unfolding Collect_neg_eq by (rule closed_Compl)\n\nlemma closed_Collect_conj: assumes \"closed {x. P x}\" \"closed {x. Q x}\" shows \"closed {x. P x \\<and> Q x}\"\n  using closed_Int[OF assms] by (simp add: Int_def)\n\nlemma closed_Collect_disj: assumes \"closed {x. P x}\" \"closed {x. Q x}\" shows \"closed {x. P x \\<or> Q x}\"\n  using closed_Un[OF assms] by (simp add: Un_def)\n\nlemma closed_Collect_all: \"(\\<And>i. closed {x. P i x}) \\<Longrightarrow> closed {x. \\<forall>i. P i x}\"\n  using closed_INT[of UNIV \"\\<lambda>i. {x. P i x}\"] unfolding Collect_all_eq by simp \n\nlemma closed_Collect_imp: \"open {x. P x} \\<Longrightarrow> closed {x. Q x} \\<Longrightarrow> closed {x. P x \\<longrightarrow> Q x}\"\n  unfolding imp_conv_disj by (intro closed_Collect_disj closed_Collect_neg)\n\nlemma closed_Collect_const: \"closed {x. P}\"\n  by (cases P) auto\n\nend\n\nsubsection{* Hausdorff and other separation properties *}\n\nclass t0_space = topological_space +\n  assumes t0_space: \"x \\<noteq> y \\<Longrightarrow> \\<exists>U. open U \\<and> \\<not> (x \\<in> U \\<longleftrightarrow> y \\<in> U)\"\n\nclass t1_space = topological_space +\n  assumes t1_space: \"x \\<noteq> y \\<Longrightarrow> \\<exists>U. open U \\<and> x \\<in> U \\<and> y \\<notin> U\"\n\ninstance t1_space \\<subseteq> t0_space\nproof qed (fast dest: t1_space)\n\nlemma separation_t1:\n  fixes x y :: \"'a::t1_space\"\n  shows \"x \\<noteq> y \\<longleftrightarrow> (\\<exists>U. open U \\<and> x \\<in> U \\<and> y \\<notin> U)\"\n  using t1_space[of x y] by blast\n\nlemma closed_singleton:\n  fixes a :: \"'a::t1_space\"\n  shows \"closed {a}\"\nproof -\n  let ?T = \"\\<Union>{S. open S \\<and> a \\<notin> S}\"\n  have \"open ?T\" by (simp add: open_Union)\n  also have \"?T = - {a}\"\n    by (simp add: set_eq_iff separation_t1, auto)\n  finally show \"closed {a}\" unfolding closed_def .\nqed\n\nlemma closed_insert [continuous_intros, simp]:\n  fixes a :: \"'a::t1_space\"\n  assumes \"closed S\" shows \"closed (insert a S)\"\nproof -\n  from closed_singleton assms\n  have \"closed ({a} \\<union> S)\" by (rule closed_Un)\n  thus \"closed (insert a S)\" by simp\nqed\n\nlemma finite_imp_closed:\n  fixes S :: \"'a::t1_space set\"\n  shows \"finite S \\<Longrightarrow> closed S\"\nby (induct set: finite, simp_all)\n\ntext {* T2 spaces are also known as Hausdorff spaces. *}\n\nclass t2_space = topological_space +\n  assumes hausdorff: \"x \\<noteq> y \\<Longrightarrow> \\<exists>U V. open U \\<and> open V \\<and> x \\<in> U \\<and> y \\<in> V \\<and> U \\<inter> V = {}\"\n\ninstance t2_space \\<subseteq> t1_space\nproof qed (fast dest: hausdorff)\n\nlemma separation_t2:\n  fixes x y :: \"'a::t2_space\"\n  shows \"x \\<noteq> y \\<longleftrightarrow> (\\<exists>U V. open U \\<and> open V \\<and> x \\<in> U \\<and> y \\<in> V \\<and> U \\<inter> V = {})\"\n  using hausdorff[of x y] by blast\n\nlemma separation_t0:\n  fixes x y :: \"'a::t0_space\"\n  shows \"x \\<noteq> y \\<longleftrightarrow> (\\<exists>U. open U \\<and> ~(x\\<in>U \\<longleftrightarrow> y\\<in>U))\"\n  using t0_space[of x y] by blast\n\ntext {* A perfect space is a topological space with no isolated points. *}\n\nclass perfect_space = topological_space +\n  assumes not_open_singleton: \"\\<not> open {x}\"\n\n\nsubsection {* Generators for toplogies *}\n\ninductive generate_topology for S where\n  UNIV: \"generate_topology S UNIV\"\n| Int: \"generate_topology S a \\<Longrightarrow> generate_topology S b \\<Longrightarrow> generate_topology S (a \\<inter> b)\"\n| UN: \"(\\<And>k. k \\<in> K \\<Longrightarrow> generate_topology S k) \\<Longrightarrow> generate_topology S (\\<Union>K)\"\n| Basis: \"s \\<in> S \\<Longrightarrow> generate_topology S s\"\n\nhide_fact (open) UNIV Int UN Basis \n\nlemma generate_topology_Union: \n  \"(\\<And>k. k \\<in> I \\<Longrightarrow> generate_topology S (K k)) \\<Longrightarrow> generate_topology S (\\<Union>k\\<in>I. K k)\"\n  using generate_topology.UN [of \"K ` I\"] by auto\n\nlemma topological_space_generate_topology:\n  \"class.topological_space (generate_topology S)\"\n  by default (auto intro: generate_topology.intros)\n\nsubsection {* Order topologies *}\n\nclass order_topology = order + \"open\" +\n  assumes open_generated_order: \"open = generate_topology (range (\\<lambda>a. {..< a}) \\<union> range (\\<lambda>a. {a <..}))\"\nbegin\n\nsubclass topological_space\n  unfolding open_generated_order\n  by (rule topological_space_generate_topology)\n\nlemma open_greaterThan [continuous_intros, simp]: \"open {a <..}\"\n  unfolding open_generated_order by (auto intro: generate_topology.Basis)\n\nlemma open_lessThan [continuous_intros, simp]: \"open {..< a}\"\n  unfolding open_generated_order by (auto intro: generate_topology.Basis)\n\nlemma open_greaterThanLessThan [continuous_intros, simp]: \"open {a <..< b}\"\n   unfolding greaterThanLessThan_eq by (simp add: open_Int)\n\nend\n\nclass linorder_topology = linorder + order_topology\n\nlemma closed_atMost [continuous_intros, simp]: \"closed {.. a::'a::linorder_topology}\"\n  by (simp add: closed_open)\n\nlemma closed_atLeast [continuous_intros, simp]: \"closed {a::'a::linorder_topology ..}\"\n  by (simp add: closed_open)\n\nlemma closed_atLeastAtMost [continuous_intros, simp]: \"closed {a::'a::linorder_topology .. b}\"\nproof -\n  have \"{a .. b} = {a ..} \\<inter> {.. b}\"\n    by auto\n  then show ?thesis\n    by (simp add: closed_Int)\nqed\n\nlemma (in linorder) less_separate:\n  assumes \"x < y\"\n  shows \"\\<exists>a b. x \\<in> {..< a} \\<and> y \\<in> {b <..} \\<and> {..< a} \\<inter> {b <..} = {}\"\nproof (cases \"\\<exists>z. x < z \\<and> z < y\")\n  case True\n  then obtain z where \"x < z \\<and> z < y\" ..\n  then have \"x \\<in> {..< z} \\<and> y \\<in> {z <..} \\<and> {z <..} \\<inter> {..< z} = {}\"\n    by auto\n  then show ?thesis by blast\nnext\n  case False\n  with `x < y` have \"x \\<in> {..< y} \\<and> y \\<in> {x <..} \\<and> {x <..} \\<inter> {..< y} = {}\"\n    by auto\n  then show ?thesis by blast\nqed\n\ninstance linorder_topology \\<subseteq> t2_space\nproof\n  fix x y :: 'a\n  from less_separate[of x y] less_separate[of y x]\n  show \"x \\<noteq> y \\<Longrightarrow> \\<exists>U V. open U \\<and> open V \\<and> x \\<in> U \\<and> y \\<in> V \\<and> U \\<inter> V = {}\"\n    by (elim neqE) (metis open_lessThan open_greaterThan Int_commute)+\nqed\n\nlemma (in linorder_topology) open_right:\n  assumes \"open S\" \"x \\<in> S\" and gt_ex: \"x < y\" shows \"\\<exists>b>x. {x ..< b} \\<subseteq> S\"\n  using assms unfolding open_generated_order\nproof induction\n  case (Int A B)\n  then obtain a b where \"a > x\" \"{x ..< a} \\<subseteq> A\"  \"b > x\" \"{x ..< b} \\<subseteq> B\" by auto\n  then show ?case by (auto intro!: exI[of _ \"min a b\"])\nnext\n  case (Basis S) then show ?case by (fastforce intro: exI[of _ y] gt_ex)\nqed blast+\n\nlemma (in linorder_topology) open_left:\n  assumes \"open S\" \"x \\<in> S\" and lt_ex: \"y < x\" shows \"\\<exists>b<x. {b <.. x} \\<subseteq> S\"\n  using assms unfolding open_generated_order\nproof induction\n  case (Int A B)\n  then obtain a b where \"a < x\" \"{a <.. x} \\<subseteq> A\"  \"b < x\" \"{b <.. x} \\<subseteq> B\" by auto\n  then show ?case by (auto intro!: exI[of _ \"max a b\"])\nnext\n  case (Basis S) then show ?case by (fastforce intro: exI[of _ y] lt_ex)\nqed blast+\n\nsubsubsection {* Boolean is an order topology *}\n\ntext {* It also is a discrete topology, but don't have a type class for it (yet). *}\n\ninstantiation bool :: order_topology\nbegin\n\ndefinition open_bool :: \"bool set \\<Rightarrow> bool\" where\n  \"open_bool = generate_topology (range (\\<lambda>a. {..< a}) \\<union> range (\\<lambda>a. {a <..}))\"\n\ninstance\n  proof qed (rule open_bool_def)\n\nend\n\nlemma open_bool[simp, intro!]: \"open (A::bool set)\"\nproof -\n  have *: \"{False <..} = {True}\" \"{..< True} = {False}\"\n    by auto\n  have \"A = UNIV \\<or> A = {} \\<or> A = {False <..} \\<or> A = {..< True}\"\n    using subset_UNIV[of A] unfolding UNIV_bool * by auto\n  then show \"open A\"\n    by auto\nqed\n\nsubsection {* Filters *}\n\ntext {*\n  This definition also allows non-proper filters.\n*}\n\nlocale is_filter =\n  fixes F :: \"('a \\<Rightarrow> bool) \\<Rightarrow> bool\"\n  assumes True: \"F (\\<lambda>x. True)\"\n  assumes conj: \"F (\\<lambda>x. P x) \\<Longrightarrow> F (\\<lambda>x. Q x) \\<Longrightarrow> F (\\<lambda>x. P x \\<and> Q x)\"\n  assumes mono: \"\\<forall>x. P x \\<longrightarrow> Q x \\<Longrightarrow> F (\\<lambda>x. P x) \\<Longrightarrow> F (\\<lambda>x. Q x)\"\n\ntypedef 'a filter = \"{F :: ('a \\<Rightarrow> bool) \\<Rightarrow> bool. is_filter F}\"\nproof\n  show \"(\\<lambda>x. True) \\<in> ?filter\" by (auto intro: is_filter.intro)\nqed\n\nlemma is_filter_Rep_filter: \"is_filter (Rep_filter F)\"\n  using Rep_filter [of F] by simp\n\nlemma Abs_filter_inverse':\n  assumes \"is_filter F\" shows \"Rep_filter (Abs_filter F) = F\"\n  using assms by (simp add: Abs_filter_inverse)\n\n\nsubsubsection {* Eventually *}\n\ndefinition eventually :: \"('a \\<Rightarrow> bool) \\<Rightarrow> 'a filter \\<Rightarrow> bool\"\n  where \"eventually P F \\<longleftrightarrow> Rep_filter F P\"\n\nlemma eventually_Abs_filter:\n  assumes \"is_filter F\" shows \"eventually P (Abs_filter F) = F P\"\n  unfolding eventually_def using assms by (simp add: Abs_filter_inverse)\n\nlemma filter_eq_iff:\n  shows \"F = F' \\<longleftrightarrow> (\\<forall>P. eventually P F = eventually P F')\"\n  unfolding Rep_filter_inject [symmetric] fun_eq_iff eventually_def ..\n\nlemma eventually_True [simp]: \"eventually (\\<lambda>x. True) F\"\n  unfolding eventually_def\n  by (rule is_filter.True [OF is_filter_Rep_filter])\n\nlemma always_eventually: \"\\<forall>x. P x \\<Longrightarrow> eventually P F\"\nproof -\n  assume \"\\<forall>x. P x\" hence \"P = (\\<lambda>x. True)\" by (simp add: ext)\n  thus \"eventually P F\" by simp\nqed\n\nlemma eventually_mono:\n  \"(\\<forall>x. P x \\<longrightarrow> Q x) \\<Longrightarrow> eventually P F \\<Longrightarrow> eventually Q F\"\n  unfolding eventually_def\n  by (rule is_filter.mono [OF is_filter_Rep_filter])\n\nlemma eventually_conj:\n  assumes P: \"eventually (\\<lambda>x. P x) F\"\n  assumes Q: \"eventually (\\<lambda>x. Q x) F\"\n  shows \"eventually (\\<lambda>x. P x \\<and> Q x) F\"\n  using assms unfolding eventually_def\n  by (rule is_filter.conj [OF is_filter_Rep_filter])\n\nlemma eventually_Ball_finite:\n  assumes \"finite A\" and \"\\<forall>y\\<in>A. eventually (\\<lambda>x. P x y) net\"\n  shows \"eventually (\\<lambda>x. \\<forall>y\\<in>A. P x y) net\"\nusing assms by (induct set: finite, simp, simp add: eventually_conj)\n\nlemma eventually_all_finite:\n  fixes P :: \"'a \\<Rightarrow> 'b::finite \\<Rightarrow> bool\"\n  assumes \"\\<And>y. eventually (\\<lambda>x. P x y) net\"\n  shows \"eventually (\\<lambda>x. \\<forall>y. P x y) net\"\nusing eventually_Ball_finite [of UNIV P] assms by simp\n\nlemma eventually_mp:\n  assumes \"eventually (\\<lambda>x. P x \\<longrightarrow> Q x) F\"\n  assumes \"eventually (\\<lambda>x. P x) F\"\n  shows \"eventually (\\<lambda>x. Q x) F\"\nproof (rule eventually_mono)\n  show \"\\<forall>x. (P x \\<longrightarrow> Q x) \\<and> P x \\<longrightarrow> Q x\" by simp\n  show \"eventually (\\<lambda>x. (P x \\<longrightarrow> Q x) \\<and> P x) F\"\n    using assms by (rule eventually_conj)\nqed\n\nlemma eventually_rev_mp:\n  assumes \"eventually (\\<lambda>x. P x) F\"\n  assumes \"eventually (\\<lambda>x. P x \\<longrightarrow> Q x) F\"\n  shows \"eventually (\\<lambda>x. Q x) F\"\nusing assms(2) assms(1) by (rule eventually_mp)\n\nlemma eventually_conj_iff:\n  \"eventually (\\<lambda>x. P x \\<and> Q x) F \\<longleftrightarrow> eventually P F \\<and> eventually Q F\"\n  by (auto intro: eventually_conj elim: eventually_rev_mp)\n\nlemma eventually_elim1:\n  assumes \"eventually (\\<lambda>i. P i) F\"\n  assumes \"\\<And>i. P i \\<Longrightarrow> Q i\"\n  shows \"eventually (\\<lambda>i. Q i) F\"\n  using assms by (auto elim!: eventually_rev_mp)\n\nlemma eventually_elim2:\n  assumes \"eventually (\\<lambda>i. P i) F\"\n  assumes \"eventually (\\<lambda>i. Q i) F\"\n  assumes \"\\<And>i. P i \\<Longrightarrow> Q i \\<Longrightarrow> R i\"\n  shows \"eventually (\\<lambda>i. R i) F\"\n  using assms by (auto elim!: eventually_rev_mp)\n\nlemma not_eventually_impI: \"eventually P F \\<Longrightarrow> \\<not> eventually Q F \\<Longrightarrow> \\<not> eventually (\\<lambda>x. P x \\<longrightarrow> Q x) F\"\n  by (auto intro: eventually_mp)\n\nlemma not_eventuallyD: \"\\<not> eventually P F \\<Longrightarrow> \\<exists>x. \\<not> P x\"\n  by (metis always_eventually)\n\nlemma eventually_subst:\n  assumes \"eventually (\\<lambda>n. P n = Q n) F\"\n  shows \"eventually P F = eventually Q F\" (is \"?L = ?R\")\nproof -\n  from assms have \"eventually (\\<lambda>x. P x \\<longrightarrow> Q x) F\"\n      and \"eventually (\\<lambda>x. Q x \\<longrightarrow> P x) F\"\n    by (auto elim: eventually_elim1)\n  then show ?thesis by (auto elim: eventually_elim2)\nqed\n\nML {*\n  fun eventually_elim_tac ctxt thms = SUBGOAL_CASES (fn (_, _, st) =>\n    let\n      val thy = Proof_Context.theory_of ctxt\n      val mp_thms = thms RL [@{thm eventually_rev_mp}]\n      val raw_elim_thm =\n        (@{thm allI} RS @{thm always_eventually})\n        |> fold (fn thm1 => fn thm2 => thm2 RS thm1) mp_thms\n        |> fold (fn _ => fn thm => @{thm impI} RS thm) thms\n      val cases_prop = prop_of (raw_elim_thm RS st)\n      val cases = (Rule_Cases.make_common (thy, cases_prop) [((\"elim\", []), [])])\n    in\n      CASES cases (rtac raw_elim_thm 1)\n    end) 1\n*}\n\nmethod_setup eventually_elim = {*\n  Scan.succeed (fn ctxt => METHOD_CASES (eventually_elim_tac ctxt))\n*} \"elimination of eventually quantifiers\"\n\n\nsubsubsection {* Finer-than relation *}\n\ntext {* @{term \"F \\<le> F'\"} means that filter @{term F} is finer than\nfilter @{term F'}. *}\n\ninstantiation filter :: (type) complete_lattice\nbegin\n\ndefinition le_filter_def:\n  \"F \\<le> F' \\<longleftrightarrow> (\\<forall>P. eventually P F' \\<longrightarrow> eventually P F)\"\n\ndefinition\n  \"(F :: 'a filter) < F' \\<longleftrightarrow> F \\<le> F' \\<and> \\<not> F' \\<le> F\"\n\ndefinition\n  \"top = Abs_filter (\\<lambda>P. \\<forall>x. P x)\"\n\ndefinition\n  \"bot = Abs_filter (\\<lambda>P. True)\"\n\ndefinition\n  \"sup F F' = Abs_filter (\\<lambda>P. eventually P F \\<and> eventually P F')\"\n\ndefinition\n  \"inf F F' = Abs_filter\n      (\\<lambda>P. \\<exists>Q R. eventually Q F \\<and> eventually R F' \\<and> (\\<forall>x. Q x \\<and> R x \\<longrightarrow> P x))\"\n\ndefinition\n  \"Sup S = Abs_filter (\\<lambda>P. \\<forall>F\\<in>S. eventually P F)\"\n\ndefinition\n  \"Inf S = Sup {F::'a filter. \\<forall>F'\\<in>S. F \\<le> F'}\"\n\nlemma eventually_top [simp]: \"eventually P top \\<longleftrightarrow> (\\<forall>x. P x)\"\n  unfolding top_filter_def\n  by (rule eventually_Abs_filter, rule is_filter.intro, auto)\n\nlemma eventually_bot [simp]: \"eventually P bot\"\n  unfolding bot_filter_def\n  by (subst eventually_Abs_filter, rule is_filter.intro, auto)\n\nlemma eventually_sup:\n  \"eventually P (sup F F') \\<longleftrightarrow> eventually P F \\<and> eventually P F'\"\n  unfolding sup_filter_def\n  by (rule eventually_Abs_filter, rule is_filter.intro)\n     (auto elim!: eventually_rev_mp)\n\nlemma eventually_inf:\n  \"eventually P (inf F F') \\<longleftrightarrow>\n   (\\<exists>Q R. eventually Q F \\<and> eventually R F' \\<and> (\\<forall>x. Q x \\<and> R x \\<longrightarrow> P x))\"\n  unfolding inf_filter_def\n  apply (rule eventually_Abs_filter, rule is_filter.intro)\n  apply (fast intro: eventually_True)\n  apply clarify\n  apply (intro exI conjI)\n  apply (erule (1) eventually_conj)\n  apply (erule (1) eventually_conj)\n  apply simp\n  apply auto\n  done\n\nlemma eventually_Sup:\n  \"eventually P (Sup S) \\<longleftrightarrow> (\\<forall>F\\<in>S. eventually P F)\"\n  unfolding Sup_filter_def\n  apply (rule eventually_Abs_filter, rule is_filter.intro)\n  apply (auto intro: eventually_conj elim!: eventually_rev_mp)\n  done\n\ninstance proof\n  fix F F' F'' :: \"'a filter\" and S :: \"'a filter set\"\n  { show \"F < F' \\<longleftrightarrow> F \\<le> F' \\<and> \\<not> F' \\<le> F\"\n    by (rule less_filter_def) }\n  { show \"F \\<le> F\"\n    unfolding le_filter_def by simp }\n  { assume \"F \\<le> F'\" and \"F' \\<le> F''\" thus \"F \\<le> F''\"\n    unfolding le_filter_def by simp }\n  { assume \"F \\<le> F'\" and \"F' \\<le> F\" thus \"F = F'\"\n    unfolding le_filter_def filter_eq_iff by fast }\n  { show \"inf F F' \\<le> F\" and \"inf F F' \\<le> F'\"\n    unfolding le_filter_def eventually_inf by (auto intro: eventually_True) }\n  { assume \"F \\<le> F'\" and \"F \\<le> F''\" thus \"F \\<le> inf F' F''\"\n    unfolding le_filter_def eventually_inf\n    by (auto elim!: eventually_mono intro: eventually_conj) }\n  { show \"F \\<le> sup F F'\" and \"F' \\<le> sup F F'\"\n    unfolding le_filter_def eventually_sup by simp_all }\n  { assume \"F \\<le> F''\" and \"F' \\<le> F''\" thus \"sup F F' \\<le> F''\"\n    unfolding le_filter_def eventually_sup by simp }\n  { assume \"F'' \\<in> S\" thus \"Inf S \\<le> F''\"\n    unfolding le_filter_def Inf_filter_def eventually_Sup Ball_def by simp }\n  { assume \"\\<And>F'. F' \\<in> S \\<Longrightarrow> F \\<le> F'\" thus \"F \\<le> Inf S\"\n    unfolding le_filter_def Inf_filter_def eventually_Sup Ball_def by simp }\n  { assume \"F \\<in> S\" thus \"F \\<le> Sup S\"\n    unfolding le_filter_def eventually_Sup by simp }\n  { assume \"\\<And>F. F \\<in> S \\<Longrightarrow> F \\<le> F'\" thus \"Sup S \\<le> F'\"\n    unfolding le_filter_def eventually_Sup by simp }\n  { show \"Inf {} = (top::'a filter)\"\n    by (auto simp: top_filter_def Inf_filter_def Sup_filter_def)\n      (metis (full_types) top_filter_def always_eventually eventually_top) }\n  { show \"Sup {} = (bot::'a filter)\"\n    by (auto simp: bot_filter_def Sup_filter_def) }\nqed\n\nend\n\nlemma filter_leD:\n  \"F \\<le> F' \\<Longrightarrow> eventually P F' \\<Longrightarrow> eventually P F\"\n  unfolding le_filter_def by simp\n\nlemma filter_leI:\n  \"(\\<And>P. eventually P F' \\<Longrightarrow> eventually P F) \\<Longrightarrow> F \\<le> F'\"\n  unfolding le_filter_def by simp\n\nlemma eventually_False:\n  \"eventually (\\<lambda>x. False) F \\<longleftrightarrow> F = bot\"\n  unfolding filter_eq_iff by (auto elim: eventually_rev_mp)\n\nabbreviation (input) trivial_limit :: \"'a filter \\<Rightarrow> bool\"\n  where \"trivial_limit F \\<equiv> F = bot\"\n\nlemma trivial_limit_def: \"trivial_limit F \\<longleftrightarrow> eventually (\\<lambda>x. False) F\"\n  by (rule eventually_False [symmetric])\n\nlemma eventually_const: \"\\<not> trivial_limit net \\<Longrightarrow> eventually (\\<lambda>x. P) net \\<longleftrightarrow> P\"\n  by (cases P) (simp_all add: eventually_False)\n\nlemma eventually_Inf: \"eventually P (Inf B) \\<longleftrightarrow> (\\<exists>X\\<subseteq>B. finite X \\<and> eventually P (Inf X))\"\nproof -\n  let ?F = \"\\<lambda>P. \\<exists>X\\<subseteq>B. finite X \\<and> eventually P (Inf X)\"\n  \n  { fix P have \"eventually P (Abs_filter ?F) \\<longleftrightarrow> ?F P\"\n    proof (rule eventually_Abs_filter is_filter.intro)+\n      show \"?F (\\<lambda>x. True)\"\n        by (rule exI[of _ \"{}\"]) (simp add: le_fun_def)\n    next\n      fix P Q\n      assume \"?F P\" then guess X ..\n      moreover\n      assume \"?F Q\" then guess Y ..\n      ultimately show \"?F (\\<lambda>x. P x \\<and> Q x)\"\n        by (intro exI[of _ \"X \\<union> Y\"])\n           (auto simp: Inf_union_distrib eventually_inf)\n    next\n      fix P Q\n      assume \"?F P\" then guess X ..\n      moreover assume \"\\<forall>x. P x \\<longrightarrow> Q x\"\n      ultimately show \"?F Q\"\n        by (intro exI[of _ X]) (auto elim: eventually_elim1)\n    qed }\n  note eventually_F = this\n\n  have \"Inf B = Abs_filter ?F\"\n  proof (intro antisym Inf_greatest)\n    show \"Inf B \\<le> Abs_filter ?F\"\n      by (auto simp: le_filter_def eventually_F dest: Inf_superset_mono)\n  next\n    fix F assume \"F \\<in> B\" then show \"Abs_filter ?F \\<le> F\"\n      by (auto simp add: le_filter_def eventually_F intro!: exI[of _ \"{F}\"])\n  qed\n  then show ?thesis\n    by (simp add: eventually_F)\nqed\n\nlemma eventually_INF: \"eventually P (INF b:B. F b) \\<longleftrightarrow> (\\<exists>X\\<subseteq>B. finite X \\<and> eventually P (INF b:X. F b))\"\n  unfolding INF_def[of B] eventually_Inf[of P \"F`B\"]\n  by (metis Inf_image_eq finite_imageI image_mono finite_subset_image)\n\nlemma Inf_filter_not_bot:\n  fixes B :: \"'a filter set\"\n  shows \"(\\<And>X. X \\<subseteq> B \\<Longrightarrow> finite X \\<Longrightarrow> Inf X \\<noteq> bot) \\<Longrightarrow> Inf B \\<noteq> bot\"\n  unfolding trivial_limit_def eventually_Inf[of _ B]\n    bot_bool_def [symmetric] bot_fun_def [symmetric] bot_unique by simp\n\nlemma INF_filter_not_bot:\n  fixes F :: \"'i \\<Rightarrow> 'a filter\"\n  shows \"(\\<And>X. X \\<subseteq> B \\<Longrightarrow> finite X \\<Longrightarrow> (INF b:X. F b) \\<noteq> bot) \\<Longrightarrow> (INF b:B. F b) \\<noteq> bot\"\n  unfolding trivial_limit_def eventually_INF[of _ B]\n    bot_bool_def [symmetric] bot_fun_def [symmetric] bot_unique by simp\n\nlemma eventually_Inf_base:\n  assumes \"B \\<noteq> {}\" and base: \"\\<And>F G. F \\<in> B \\<Longrightarrow> G \\<in> B \\<Longrightarrow> \\<exists>x\\<in>B. x \\<le> inf F G\"\n  shows \"eventually P (Inf B) \\<longleftrightarrow> (\\<exists>b\\<in>B. eventually P b)\"\nproof (subst eventually_Inf, safe)\n  fix X assume \"finite X\" \"X \\<subseteq> B\"\n  then have \"\\<exists>b\\<in>B. \\<forall>x\\<in>X. b \\<le> x\"\n  proof induct\n    case empty then show ?case\n      using `B \\<noteq> {}` by auto\n  next\n    case (insert x X)\n    then obtain b where \"b \\<in> B\" \"\\<And>x. x \\<in> X \\<Longrightarrow> b \\<le> x\"\n      by auto\n    with `insert x X \\<subseteq> B` base[of b x] show ?case\n      by (auto intro: order_trans)\n  qed\n  then obtain b where \"b \\<in> B\" \"b \\<le> Inf X\"\n    by (auto simp: le_Inf_iff)\n  then show \"eventually P (Inf X) \\<Longrightarrow> Bex B (eventually P)\"\n    by (intro bexI[of _ b]) (auto simp: le_filter_def)\nqed (auto intro!: exI[of _ \"{x}\" for x])\n\nlemma eventually_INF_base:\n  \"B \\<noteq> {} \\<Longrightarrow> (\\<And>a b. a \\<in> B \\<Longrightarrow> b \\<in> B \\<Longrightarrow> \\<exists>x\\<in>B. F x \\<le> inf (F a) (F b)) \\<Longrightarrow>\n    eventually P (INF b:B. F b) \\<longleftrightarrow> (\\<exists>b\\<in>B. eventually P (F b))\"\n  unfolding INF_def by (subst eventually_Inf_base) auto\n\n\nsubsubsection {* Map function for filters *}\n\ndefinition filtermap :: \"('a \\<Rightarrow> 'b) \\<Rightarrow> 'a filter \\<Rightarrow> 'b filter\"\n  where \"filtermap f F = Abs_filter (\\<lambda>P. eventually (\\<lambda>x. P (f x)) F)\"\n\nlemma eventually_filtermap:\n  \"eventually P (filtermap f F) = eventually (\\<lambda>x. P (f x)) F\"\n  unfolding filtermap_def\n  apply (rule eventually_Abs_filter)\n  apply (rule is_filter.intro)\n  apply (auto elim!: eventually_rev_mp)\n  done\n\nlemma filtermap_ident: \"filtermap (\\<lambda>x. x) F = F\"\n  by (simp add: filter_eq_iff eventually_filtermap)\n\nlemma filtermap_filtermap:\n  \"filtermap f (filtermap g F) = filtermap (\\<lambda>x. f (g x)) F\"\n  by (simp add: filter_eq_iff eventually_filtermap)\n\nlemma filtermap_mono: \"F \\<le> F' \\<Longrightarrow> filtermap f F \\<le> filtermap f F'\"\n  unfolding le_filter_def eventually_filtermap by simp\n\nlemma filtermap_bot [simp]: \"filtermap f bot = bot\"\n  by (simp add: filter_eq_iff eventually_filtermap)\n\nlemma filtermap_sup: \"filtermap f (sup F1 F2) = sup (filtermap f F1) (filtermap f F2)\"\n  by (auto simp: filter_eq_iff eventually_filtermap eventually_sup)\n\nlemma filtermap_inf: \"filtermap f (inf F1 F2) \\<le> inf (filtermap f F1) (filtermap f F2)\"\n  by (auto simp: le_filter_def eventually_filtermap eventually_inf)\n\nlemma filtermap_INF: \"filtermap f (INF b:B. F b) \\<le> (INF b:B. filtermap f (F b))\"\nproof -\n  { fix X :: \"'c set\" assume \"finite X\"\n    then have \"filtermap f (INFIMUM X F) \\<le> (INF b:X. filtermap f (F b))\"\n    proof induct\n      case (insert x X)\n      have \"filtermap f (INF a:insert x X. F a) \\<le> inf (filtermap f (F x)) (filtermap f (INF a:X. F a))\"\n        by (rule order_trans[OF _ filtermap_inf]) simp\n      also have \"\\<dots> \\<le> inf (filtermap f (F x)) (INF a:X. filtermap f (F a))\"\n        by (intro inf_mono insert order_refl)\n      finally show ?case\n        by simp\n    qed simp }\n  then show ?thesis\n    unfolding le_filter_def eventually_filtermap\n    by (subst (1 2) eventually_INF) auto\nqed\nsubsubsection {* Standard filters *}\n\ndefinition principal :: \"'a set \\<Rightarrow> 'a filter\" where\n  \"principal S = Abs_filter (\\<lambda>P. \\<forall>x\\<in>S. P x)\"\n\nlemma eventually_principal: \"eventually P (principal S) \\<longleftrightarrow> (\\<forall>x\\<in>S. P x)\"\n  unfolding principal_def\n  by (rule eventually_Abs_filter, rule is_filter.intro) auto\n\nlemma eventually_inf_principal: \"eventually P (inf F (principal s)) \\<longleftrightarrow> eventually (\\<lambda>x. x \\<in> s \\<longrightarrow> P x) F\"\n  unfolding eventually_inf eventually_principal by (auto elim: eventually_elim1)\n\nlemma principal_UNIV[simp]: \"principal UNIV = top\"\n  by (auto simp: filter_eq_iff eventually_principal)\n\nlemma principal_empty[simp]: \"principal {} = bot\"\n  by (auto simp: filter_eq_iff eventually_principal)\n\nlemma principal_eq_bot_iff: \"principal X = bot \\<longleftrightarrow> X = {}\"\n  by (auto simp add: filter_eq_iff eventually_principal)\n\nlemma principal_le_iff[iff]: \"principal A \\<le> principal B \\<longleftrightarrow> A \\<subseteq> B\"\n  by (auto simp: le_filter_def eventually_principal)\n\nlemma le_principal: \"F \\<le> principal A \\<longleftrightarrow> eventually (\\<lambda>x. x \\<in> A) F\"\n  unfolding le_filter_def eventually_principal\n  apply safe\n  apply (erule_tac x=\"\\<lambda>x. x \\<in> A\" in allE)\n  apply (auto elim: eventually_elim1)\n  done\n\nlemma principal_inject[iff]: \"principal A = principal B \\<longleftrightarrow> A = B\"\n  unfolding eq_iff by simp\n\nlemma sup_principal[simp]: \"sup (principal A) (principal B) = principal (A \\<union> B)\"\n  unfolding filter_eq_iff eventually_sup eventually_principal by auto\n\nlemma inf_principal[simp]: \"inf (principal A) (principal B) = principal (A \\<inter> B)\"\n  unfolding filter_eq_iff eventually_inf eventually_principal\n  by (auto intro: exI[of _ \"\\<lambda>x. x \\<in> A\"] exI[of _ \"\\<lambda>x. x \\<in> B\"])\n\nlemma SUP_principal[simp]: \"(SUP i : I. principal (A i)) = principal (\\<Union>i\\<in>I. A i)\"\n  unfolding filter_eq_iff eventually_Sup SUP_def by (auto simp: eventually_principal)\n\nlemma INF_principal_finite: \"finite X \\<Longrightarrow> (INF x:X. principal (f x)) = principal (\\<Inter>x\\<in>X. f x)\"\n  by (induct X rule: finite_induct) auto\n\nlemma filtermap_principal[simp]: \"filtermap f (principal A) = principal (f ` A)\"\n  unfolding filter_eq_iff eventually_filtermap eventually_principal by simp\n\nsubsubsection {* Order filters *}\n\ndefinition at_top :: \"('a::order) filter\"\n  where \"at_top = (INF k. principal {k ..})\"\n\nlemma at_top_sub: \"at_top = (INF k:{c::'a::linorder..}. principal {k ..})\"\n  by (auto intro!: INF_eq max.cobounded1 max.cobounded2 simp: at_top_def)\n\nlemma eventually_at_top_linorder: \"eventually P at_top \\<longleftrightarrow> (\\<exists>N::'a::linorder. \\<forall>n\\<ge>N. P n)\"\n  unfolding at_top_def\n  by (subst eventually_INF_base) (auto simp: eventually_principal intro: max.cobounded1 max.cobounded2)\n\nlemma eventually_ge_at_top:\n  \"eventually (\\<lambda>x. (c::_::linorder) \\<le> x) at_top\"\n  unfolding eventually_at_top_linorder by auto\n\nlemma eventually_at_top_dense: \"eventually P at_top \\<longleftrightarrow> (\\<exists>N::'a::{no_top, linorder}. \\<forall>n>N. P n)\"\nproof -\n  have \"eventually P (INF k. principal {k <..}) \\<longleftrightarrow> (\\<exists>N::'a. \\<forall>n>N. P n)\"\n    by (subst eventually_INF_base) (auto simp: eventually_principal intro: max.cobounded1 max.cobounded2)\n  also have \"(INF k. principal {k::'a <..}) = at_top\"\n    unfolding at_top_def \n    by (intro INF_eq) (auto intro: less_imp_le simp: Ici_subset_Ioi_iff gt_ex)\n  finally show ?thesis .\nqed\n\nlemma eventually_gt_at_top:\n  \"eventually (\\<lambda>x. (c::_::unbounded_dense_linorder) < x) at_top\"\n  unfolding eventually_at_top_dense by auto\n\ndefinition at_bot :: \"('a::order) filter\"\n  where \"at_bot = (INF k. principal {.. k})\"\n\nlemma at_bot_sub: \"at_bot = (INF k:{.. c::'a::linorder}. principal {.. k})\"\n  by (auto intro!: INF_eq min.cobounded1 min.cobounded2 simp: at_bot_def)\n\nlemma eventually_at_bot_linorder:\n  fixes P :: \"'a::linorder \\<Rightarrow> bool\" shows \"eventually P at_bot \\<longleftrightarrow> (\\<exists>N. \\<forall>n\\<le>N. P n)\"\n  unfolding at_bot_def\n  by (subst eventually_INF_base) (auto simp: eventually_principal intro: min.cobounded1 min.cobounded2)\n\nlemma eventually_le_at_bot:\n  \"eventually (\\<lambda>x. x \\<le> (c::_::linorder)) at_bot\"\n  unfolding eventually_at_bot_linorder by auto\n\nlemma eventually_at_bot_dense: \"eventually P at_bot \\<longleftrightarrow> (\\<exists>N::'a::{no_bot, linorder}. \\<forall>n<N. P n)\"\nproof -\n  have \"eventually P (INF k. principal {..< k}) \\<longleftrightarrow> (\\<exists>N::'a. \\<forall>n<N. P n)\"\n    by (subst eventually_INF_base) (auto simp: eventually_principal intro: min.cobounded1 min.cobounded2)\n  also have \"(INF k. principal {..< k::'a}) = at_bot\"\n    unfolding at_bot_def \n    by (intro INF_eq) (auto intro: less_imp_le simp: Iic_subset_Iio_iff lt_ex)\n  finally show ?thesis .\nqed\n\nlemma eventually_gt_at_bot:\n  \"eventually (\\<lambda>x. x < (c::_::unbounded_dense_linorder)) at_bot\"\n  unfolding eventually_at_bot_dense by auto\n\nlemma trivial_limit_at_bot_linorder: \"\\<not> trivial_limit (at_bot ::('a::linorder) filter)\"\n  unfolding trivial_limit_def\n  by (metis eventually_at_bot_linorder order_refl)\n\nlemma trivial_limit_at_top_linorder: \"\\<not> trivial_limit (at_top ::('a::linorder) filter)\"\n  unfolding trivial_limit_def\n  by (metis eventually_at_top_linorder order_refl)\n\nsubsection {* Sequentially *}\n\nabbreviation sequentially :: \"nat filter\"\n  where \"sequentially \\<equiv> at_top\"\n\nlemma eventually_sequentially:\n  \"eventually P sequentially \\<longleftrightarrow> (\\<exists>N. \\<forall>n\\<ge>N. P n)\"\n  by (rule eventually_at_top_linorder)\n\nlemma sequentially_bot [simp, intro]: \"sequentially \\<noteq> bot\"\n  unfolding filter_eq_iff eventually_sequentially by auto\n\nlemmas trivial_limit_sequentially = sequentially_bot\n\nlemma eventually_False_sequentially [simp]:\n  \"\\<not> eventually (\\<lambda>n. False) sequentially\"\n  by (simp add: eventually_False)\n\nlemma le_sequentially:\n  \"F \\<le> sequentially \\<longleftrightarrow> (\\<forall>N. eventually (\\<lambda>n. N \\<le> n) F)\"\n  by (simp add: at_top_def le_INF_iff le_principal)\n\nlemma eventually_sequentiallyI:\n  assumes \"\\<And>x. c \\<le> x \\<Longrightarrow> P x\"\n  shows \"eventually P sequentially\"\nusing assms by (auto simp: eventually_sequentially)\n\nlemma eventually_sequentially_seg:\n  \"eventually (\\<lambda>n. P (n + k)) sequentially \\<longleftrightarrow> eventually P sequentially\"\n  unfolding eventually_sequentially\n  apply safe\n   apply (rule_tac x=\"N + k\" in exI)\n   apply rule\n   apply (erule_tac x=\"n - k\" in allE)\n   apply auto []\n  apply (rule_tac x=N in exI)\n  apply auto []\n  done\n\nsubsubsection {* Topological filters *}\n\ndefinition (in topological_space) nhds :: \"'a \\<Rightarrow> 'a filter\"\n  where \"nhds a = (INF S:{S. open S \\<and> a \\<in> S}. principal S)\"\n\ndefinition (in topological_space) at_within :: \"'a \\<Rightarrow> 'a set \\<Rightarrow> 'a filter\" (\"at (_) within (_)\" [1000, 60] 60)\n  where \"at a within s = inf (nhds a) (principal (s - {a}))\"\n\nabbreviation (in topological_space) at :: \"'a \\<Rightarrow> 'a filter\" (\"at\") where\n  \"at x \\<equiv> at x within (CONST UNIV)\"\n\nabbreviation (in order_topology) at_right :: \"'a \\<Rightarrow> 'a filter\" where\n  \"at_right x \\<equiv> at x within {x <..}\"\n\nabbreviation (in order_topology) at_left :: \"'a \\<Rightarrow> 'a filter\" where\n  \"at_left x \\<equiv> at x within {..< x}\"\n\nlemma (in topological_space) nhds_generated_topology:\n  \"open = generate_topology T \\<Longrightarrow> nhds x = (INF S:{S\\<in>T. x \\<in> S}. principal S)\"\n  unfolding nhds_def\nproof (safe intro!: antisym INF_greatest)\n  fix S assume \"generate_topology T S\" \"x \\<in> S\"\n  then show \"(INF S:{S \\<in> T. x \\<in> S}. principal S) \\<le> principal S\"\n    by induction \n       (auto intro: INF_lower order_trans simp add: inf_principal[symmetric] simp del: inf_principal)\nqed (auto intro!: INF_lower intro: generate_topology.intros)\n\nlemma (in topological_space) eventually_nhds:\n  \"eventually P (nhds a) \\<longleftrightarrow> (\\<exists>S. open S \\<and> a \\<in> S \\<and> (\\<forall>x\\<in>S. P x))\"\n  unfolding nhds_def by (subst eventually_INF_base) (auto simp: eventually_principal)\n\nlemma nhds_neq_bot [simp]: \"nhds a \\<noteq> bot\"\n  unfolding trivial_limit_def eventually_nhds by simp\n\nlemma at_within_eq: \"at x within s = (INF S:{S. open S \\<and> x \\<in> S}. principal (S \\<inter> s - {x}))\"\n  unfolding nhds_def at_within_def by (subst INF_inf_const2[symmetric]) (auto simp add: Diff_Int_distrib)\n\nlemma eventually_at_filter:\n  \"eventually P (at a within s) \\<longleftrightarrow> eventually (\\<lambda>x. x \\<noteq> a \\<longrightarrow> x \\<in> s \\<longrightarrow> P x) (nhds a)\"\n  unfolding at_within_def eventually_inf_principal by (simp add: imp_conjL[symmetric] conj_commute)\n\nlemma at_le: \"s \\<subseteq> t \\<Longrightarrow> at x within s \\<le> at x within t\"\n  unfolding at_within_def by (intro inf_mono) auto\n\nlemma eventually_at_topological:\n  \"eventually P (at a within s) \\<longleftrightarrow> (\\<exists>S. open S \\<and> a \\<in> S \\<and> (\\<forall>x\\<in>S. x \\<noteq> a \\<longrightarrow> x \\<in> s \\<longrightarrow> P x))\"\n  unfolding eventually_nhds eventually_at_filter by simp\n\nlemma at_within_open: \"a \\<in> S \\<Longrightarrow> open S \\<Longrightarrow> at a within S = at a\"\n  unfolding filter_eq_iff eventually_at_topological by (metis open_Int Int_iff UNIV_I)\n\nlemma at_within_empty [simp]: \"at a within {} = bot\"\n  unfolding at_within_def by simp\n\nlemma at_within_union: \"at x within (S \\<union> T) = sup (at x within S) (at x within T)\"\n  unfolding filter_eq_iff eventually_sup eventually_at_filter\n  by (auto elim!: eventually_rev_mp)\n\nlemma at_eq_bot_iff: \"at a = bot \\<longleftrightarrow> open {a}\"\n  unfolding trivial_limit_def eventually_at_topological\n  by (safe, case_tac \"S = {a}\", simp, fast, fast)\n\nlemma at_neq_bot [simp]: \"at (a::'a::perfect_space) \\<noteq> bot\"\n  by (simp add: at_eq_bot_iff not_open_singleton)\n\nlemma (in order_topology) nhds_order: \"nhds x =\n  inf (INF a:{x <..}. principal {..< a}) (INF a:{..< x}. principal {a <..})\"\nproof -\n  have 1: \"{S \\<in> range lessThan \\<union> range greaterThan. x \\<in> S} = \n      (\\<lambda>a. {..< a}) ` {x <..} \\<union> (\\<lambda>a. {a <..}) ` {..< x}\"\n    by auto\n  show ?thesis\n    unfolding nhds_generated_topology[OF open_generated_order] INF_union 1 INF_image comp_def ..\nqed\n\nlemma (in linorder_topology) at_within_order: \"UNIV \\<noteq> {x} \\<Longrightarrow> \n  at x within s = inf (INF a:{x <..}. principal ({..< a} \\<inter> s - {x}))\n                      (INF a:{..< x}. principal ({a <..} \\<inter> s - {x}))\"\nproof (cases \"{x <..} = {}\" \"{..< x} = {}\" rule: case_split[case_product case_split])\n  assume \"UNIV \\<noteq> {x}\" \"{x<..} = {}\" \"{..< x} = {}\"\n  moreover have \"UNIV = {..< x} \\<union> {x} \\<union> {x <..}\"\n    by auto\n  ultimately show ?thesis\n    by auto\nqed (auto simp: at_within_def nhds_order Int_Diff inf_principal[symmetric] INF_inf_const2\n                inf_sup_aci[where 'a=\"'a filter\"]\n          simp del: inf_principal)\n\nlemma (in linorder_topology) at_left_eq:\n  \"y < x \\<Longrightarrow> at_left x = (INF a:{..< x}. principal {a <..< x})\"\n  by (subst at_within_order)\n     (auto simp: greaterThan_Int_greaterThan greaterThanLessThan_eq[symmetric] min.absorb2 INF_constant\n           intro!: INF_lower2 inf_absorb2)\n\nlemma (in linorder_topology) eventually_at_left:\n  \"y < x \\<Longrightarrow> eventually P (at_left x) \\<longleftrightarrow> (\\<exists>b<x. \\<forall>y>b. y < x \\<longrightarrow> P y)\"\n  unfolding at_left_eq by (subst eventually_INF_base) (auto simp: eventually_principal Ball_def)\n\nlemma (in linorder_topology) at_right_eq:\n  \"x < y \\<Longrightarrow> at_right x = (INF a:{x <..}. principal {x <..< a})\"\n  by (subst at_within_order)\n     (auto simp: lessThan_Int_lessThan greaterThanLessThan_eq[symmetric] max.absorb2 INF_constant Int_commute\n           intro!: INF_lower2 inf_absorb1)\n\nlemma (in linorder_topology) eventually_at_right:\n  \"x < y \\<Longrightarrow> eventually P (at_right x) \\<longleftrightarrow> (\\<exists>b>x. \\<forall>y>x. y < b \\<longrightarrow> P y)\"\n  unfolding at_right_eq by (subst eventually_INF_base) (auto simp: eventually_principal Ball_def)\n\nlemma trivial_limit_at_right_top: \"at_right (top::_::{order_top, linorder_topology}) = bot\"\n  unfolding filter_eq_iff eventually_at_topological by auto\n\nlemma trivial_limit_at_left_bot: \"at_left (bot::_::{order_bot, linorder_topology}) = bot\"\n  unfolding filter_eq_iff eventually_at_topological by auto\n\nlemma trivial_limit_at_left_real [simp]:\n  \"\\<not> trivial_limit (at_left (x::'a::{no_bot, dense_order, linorder_topology}))\"\n  using lt_ex[of x]\n  by safe (auto simp add: trivial_limit_def eventually_at_left dest: dense)\n\nlemma trivial_limit_at_right_real [simp]:\n  \"\\<not> trivial_limit (at_right (x::'a::{no_top, dense_order, linorder_topology}))\"\n  using gt_ex[of x]\n  by safe (auto simp add: trivial_limit_def eventually_at_right dest: dense)\n\nlemma at_eq_sup_left_right: \"at (x::'a::linorder_topology) = sup (at_left x) (at_right x)\"\n  by (auto simp: eventually_at_filter filter_eq_iff eventually_sup \n           elim: eventually_elim2 eventually_elim1)\n\nlemma eventually_at_split:\n  \"eventually P (at (x::'a::linorder_topology)) \\<longleftrightarrow> eventually P (at_left x) \\<and> eventually P (at_right x)\"\n  by (subst at_eq_sup_left_right) (simp add: eventually_sup)\n\nsubsection {* Limits *}\n\ndefinition filterlim :: \"('a \\<Rightarrow> 'b) \\<Rightarrow> 'b filter \\<Rightarrow> 'a filter \\<Rightarrow> bool\" where\n  \"filterlim f F2 F1 \\<longleftrightarrow> filtermap f F1 \\<le> F2\"\n\nsyntax\n  \"_LIM\" :: \"pttrns \\<Rightarrow> 'a \\<Rightarrow> 'b \\<Rightarrow> 'a \\<Rightarrow> bool\" (\"(3LIM (_)/ (_)./ (_) :> (_))\" [1000, 10, 0, 10] 10)\n\ntranslations\n  \"LIM x F1. f :> F2\"   == \"CONST filterlim (%x. f) F2 F1\"\n\nlemma filterlim_iff:\n  \"(LIM x F1. f x :> F2) \\<longleftrightarrow> (\\<forall>P. eventually P F2 \\<longrightarrow> eventually (\\<lambda>x. P (f x)) F1)\"\n  unfolding filterlim_def le_filter_def eventually_filtermap ..\n\nlemma filterlim_compose:\n  \"filterlim g F3 F2 \\<Longrightarrow> filterlim f F2 F1 \\<Longrightarrow> filterlim (\\<lambda>x. g (f x)) F3 F1\"\n  unfolding filterlim_def filtermap_filtermap[symmetric] by (metis filtermap_mono order_trans)\n\nlemma filterlim_mono:\n  \"filterlim f F2 F1 \\<Longrightarrow> F2 \\<le> F2' \\<Longrightarrow> F1' \\<le> F1 \\<Longrightarrow> filterlim f F2' F1'\"\n  unfolding filterlim_def by (metis filtermap_mono order_trans)\n\nlemma filterlim_ident: \"LIM x F. x :> F\"\n  by (simp add: filterlim_def filtermap_ident)\n\nlemma filterlim_cong:\n  \"F1 = F1' \\<Longrightarrow> F2 = F2' \\<Longrightarrow> eventually (\\<lambda>x. f x = g x) F2 \\<Longrightarrow> filterlim f F1 F2 = filterlim g F1' F2'\"\n  by (auto simp: filterlim_def le_filter_def eventually_filtermap elim: eventually_elim2)\n\nlemma filterlim_mono_eventually:\n  assumes \"filterlim f F G\" and ord: \"F \\<le> F'\" \"G' \\<le> G\"\n  assumes eq: \"eventually (\\<lambda>x. f x = f' x) G'\"\n  shows \"filterlim f' F' G'\"\n  apply (rule filterlim_cong[OF refl refl eq, THEN iffD1])\n  apply (rule filterlim_mono[OF _ ord])\n  apply fact\n  done\n\nlemma filtermap_mono_strong: \"inj f \\<Longrightarrow> filtermap f F \\<le> filtermap f G \\<longleftrightarrow> F \\<le> G\"\n  apply (auto intro!: filtermap_mono) []\n  apply (auto simp: le_filter_def eventually_filtermap)\n  apply (erule_tac x=\"\\<lambda>x. P (inv f x)\" in allE)\n  apply auto\n  done\n\nlemma filtermap_eq_strong: \"inj f \\<Longrightarrow> filtermap f F = filtermap f G \\<longleftrightarrow> F = G\"\n  by (simp add: filtermap_mono_strong eq_iff)\n\nlemma filterlim_principal:\n  \"(LIM x F. f x :> principal S) \\<longleftrightarrow> (eventually (\\<lambda>x. f x \\<in> S) F)\"\n  unfolding filterlim_def eventually_filtermap le_principal ..\n\nlemma filterlim_inf:\n  \"(LIM x F1. f x :> inf F2 F3) \\<longleftrightarrow> ((LIM x F1. f x :> F2) \\<and> (LIM x F1. f x :> F3))\"\n  unfolding filterlim_def by simp\n\nlemma filterlim_INF:\n  \"(LIM x F. f x :> (INF b:B. G b)) \\<longleftrightarrow> (\\<forall>b\\<in>B. LIM x F. f x :> G b)\"\n  unfolding filterlim_def le_INF_iff ..\n\nlemma filterlim_INF_INF:\n  \"(\\<And>m. m \\<in> J \\<Longrightarrow> \\<exists>i\\<in>I. filtermap f (F i) \\<le> G m) \\<Longrightarrow> LIM x (INF i:I. F i). f x :> (INF j:J. G j)\"\n  unfolding filterlim_def by (rule order_trans[OF filtermap_INF INF_mono])\n\nlemma filterlim_base:\n  \"(\\<And>m x. m \\<in> J \\<Longrightarrow> i m \\<in> I) \\<Longrightarrow> (\\<And>m x. m \\<in> J \\<Longrightarrow> x \\<in> F (i m) \\<Longrightarrow> f x \\<in> G m) \\<Longrightarrow> \n    LIM x (INF i:I. principal (F i)). f x :> (INF j:J. principal (G j))\"\n  by (force intro!: filterlim_INF_INF simp: image_subset_iff)\n\nlemma filterlim_base_iff: \n  assumes \"I \\<noteq> {}\" and chain: \"\\<And>i j. i \\<in> I \\<Longrightarrow> j \\<in> I \\<Longrightarrow> F i \\<subseteq> F j \\<or> F j \\<subseteq> F i\"\n  shows \"(LIM x (INF i:I. principal (F i)). f x :> INF j:J. principal (G j)) \\<longleftrightarrow>\n    (\\<forall>j\\<in>J. \\<exists>i\\<in>I. \\<forall>x\\<in>F i. f x \\<in> G j)\"\n  unfolding filterlim_INF filterlim_principal\nproof (subst eventually_INF_base)\n  fix i j assume \"i \\<in> I\" \"j \\<in> I\"\n  with chain[OF this] show \"\\<exists>x\\<in>I. principal (F x) \\<le> inf (principal (F i)) (principal (F j))\"\n    by auto\nqed (auto simp: eventually_principal `I \\<noteq> {}`)\n\nlemma filterlim_filtermap: \"filterlim f F1 (filtermap g F2) = filterlim (\\<lambda>x. f (g x)) F1 F2\"\n  unfolding filterlim_def filtermap_filtermap ..\n\nlemma filterlim_sup:\n  \"filterlim f F F1 \\<Longrightarrow> filterlim f F F2 \\<Longrightarrow> filterlim f F (sup F1 F2)\"\n  unfolding filterlim_def filtermap_sup by auto\n\nlemma eventually_sequentially_Suc: \"eventually (\\<lambda>i. P (Suc i)) sequentially \\<longleftrightarrow> eventually P sequentially\"\n  unfolding eventually_sequentially by (metis Suc_le_D Suc_le_mono le_Suc_eq)\n\nlemma filterlim_sequentially_Suc:\n  \"(LIM x sequentially. f (Suc x) :> F) \\<longleftrightarrow> (LIM x sequentially. f x :> F)\"\n  unfolding filterlim_iff by (subst eventually_sequentially_Suc) simp\n\nlemma filterlim_Suc: \"filterlim Suc sequentially sequentially\"\n  by (simp add: filterlim_iff eventually_sequentially) (metis le_Suc_eq)\n\nsubsubsection {* Tendsto *}\n\nabbreviation (in topological_space)\n  tendsto :: \"('b \\<Rightarrow> 'a) \\<Rightarrow> 'a \\<Rightarrow> 'b filter \\<Rightarrow> bool\" (infixr \"--->\" 55) where\n  \"(f ---> l) F \\<equiv> filterlim f (nhds l) F\"\n\ndefinition (in t2_space) Lim :: \"'f filter \\<Rightarrow> ('f \\<Rightarrow> 'a) \\<Rightarrow> 'a\" where\n  \"Lim A f = (THE l. (f ---> l) A)\"\n\nlemma tendsto_eq_rhs: \"(f ---> x) F \\<Longrightarrow> x = y \\<Longrightarrow> (f ---> y) F\"\n  by simp\n\nnamed_theorems tendsto_intros \"introduction rules for tendsto\"\nsetup {*\n  Global_Theory.add_thms_dynamic (@{binding tendsto_eq_intros},\n    fn context =>\n      Named_Theorems.get (Context.proof_of context) @{named_theorems tendsto_intros}\n      |> map_filter (try (fn thm => @{thm tendsto_eq_rhs} OF [thm])))\n*}\n\nlemma (in topological_space) tendsto_def:\n   \"(f ---> l) F \\<longleftrightarrow> (\\<forall>S. open S \\<longrightarrow> l \\<in> S \\<longrightarrow> eventually (\\<lambda>x. f x \\<in> S) F)\"\n   unfolding nhds_def filterlim_INF filterlim_principal by auto\n\nlemma tendsto_mono: \"F \\<le> F' \\<Longrightarrow> (f ---> l) F' \\<Longrightarrow> (f ---> l) F\"\n  unfolding tendsto_def le_filter_def by fast\n\nlemma tendsto_within_subset: \"(f ---> l) (at x within S) \\<Longrightarrow> T \\<subseteq> S \\<Longrightarrow> (f ---> l) (at x within T)\"\n  by (blast intro: tendsto_mono at_le)\n\nlemma filterlim_at:\n  \"(LIM x F. f x :> at b within s) \\<longleftrightarrow> (eventually (\\<lambda>x. f x \\<in> s \\<and> f x \\<noteq> b) F \\<and> (f ---> b) F)\"\n  by (simp add: at_within_def filterlim_inf filterlim_principal conj_commute)\n\nlemma (in topological_space) topological_tendstoI:\n  \"(\\<And>S. open S \\<Longrightarrow> l \\<in> S \\<Longrightarrow> eventually (\\<lambda>x. f x \\<in> S) F) \\<Longrightarrow> (f ---> l) F\"\n  unfolding tendsto_def by auto\n\nlemma (in topological_space) topological_tendstoD:\n  \"(f ---> l) F \\<Longrightarrow> open S \\<Longrightarrow> l \\<in> S \\<Longrightarrow> eventually (\\<lambda>x. f x \\<in> S) F\"\n  unfolding tendsto_def by auto\n\nlemma (in order_topology) order_tendsto_iff:\n  \"(f ---> x) F \\<longleftrightarrow> (\\<forall>l<x. eventually (\\<lambda>x. l < f x) F) \\<and> (\\<forall>u>x. eventually (\\<lambda>x. f x < u) F)\"\n  unfolding nhds_order filterlim_inf filterlim_INF filterlim_principal by auto\n\nlemma (in order_topology) order_tendstoI:\n  \"(\\<And>a. a < y \\<Longrightarrow> eventually (\\<lambda>x. a < f x) F) \\<Longrightarrow> (\\<And>a. y < a \\<Longrightarrow> eventually (\\<lambda>x. f x < a) F) \\<Longrightarrow>\n    (f ---> y) F\"\n  unfolding order_tendsto_iff by auto\n\nlemma (in order_topology) order_tendstoD:\n  assumes \"(f ---> y) F\"\n  shows \"a < y \\<Longrightarrow> eventually (\\<lambda>x. a < f x) F\"\n    and \"y < a \\<Longrightarrow> eventually (\\<lambda>x. f x < a) F\"\n  using assms unfolding order_tendsto_iff by auto\n\nlemma tendsto_bot [simp]: \"(f ---> a) bot\"\n  unfolding tendsto_def by simp\n\nlemma (in linorder_topology) tendsto_max:\n  assumes X: \"(X ---> x) net\"\n  assumes Y: \"(Y ---> y) net\"\n  shows \"((\\<lambda>x. max (X x) (Y x)) ---> max x y) net\"\nproof (rule order_tendstoI)\n  fix a assume \"a < max x y\"\n  then show \"eventually (\\<lambda>x. a < max (X x) (Y x)) net\"\n    using order_tendstoD(1)[OF X, of a] order_tendstoD(1)[OF Y, of a]\n    by (auto simp: less_max_iff_disj elim: eventually_elim1)\nnext\n  fix a assume \"max x y < a\"\n  then show \"eventually (\\<lambda>x. max (X x) (Y x) < a) net\"\n    using order_tendstoD(2)[OF X, of a] order_tendstoD(2)[OF Y, of a]\n    by (auto simp: eventually_conj_iff)\nqed\n\nlemma (in linorder_topology) tendsto_min:\n  assumes X: \"(X ---> x) net\"\n  assumes Y: \"(Y ---> y) net\"\n  shows \"((\\<lambda>x. min (X x) (Y x)) ---> min x y) net\"\nproof (rule order_tendstoI)\n  fix a assume \"a < min x y\"\n  then show \"eventually (\\<lambda>x. a < min (X x) (Y x)) net\"\n    using order_tendstoD(1)[OF X, of a] order_tendstoD(1)[OF Y, of a]\n    by (auto simp: eventually_conj_iff)\nnext\n  fix a assume \"min x y < a\"\n  then show \"eventually (\\<lambda>x. min (X x) (Y x) < a) net\"\n    using order_tendstoD(2)[OF X, of a] order_tendstoD(2)[OF Y, of a]\n    by (auto simp: min_less_iff_disj elim: eventually_elim1)\nqed\n\nlemma tendsto_ident_at [tendsto_intros, simp, intro]: \"((\\<lambda>x. x) ---> a) (at a within s)\"\n  unfolding tendsto_def eventually_at_topological by auto\n\nlemma (in topological_space) tendsto_const [tendsto_intros, simp, intro]: \"((\\<lambda>x. k) ---> k) F\"\n  by (simp add: tendsto_def)\n\nlemma (in t2_space) tendsto_unique:\n  assumes \"F \\<noteq> bot\" and \"(f ---> a) F\" and \"(f ---> b) F\"\n  shows \"a = b\"\nproof (rule ccontr)\n  assume \"a \\<noteq> b\"\n  obtain U V where \"open U\" \"open V\" \"a \\<in> U\" \"b \\<in> V\" \"U \\<inter> V = {}\"\n    using hausdorff [OF `a \\<noteq> b`] by fast\n  have \"eventually (\\<lambda>x. f x \\<in> U) F\"\n    using `(f ---> a) F` `open U` `a \\<in> U` by (rule topological_tendstoD)\n  moreover\n  have \"eventually (\\<lambda>x. f x \\<in> V) F\"\n    using `(f ---> b) F` `open V` `b \\<in> V` by (rule topological_tendstoD)\n  ultimately\n  have \"eventually (\\<lambda>x. False) F\"\n  proof eventually_elim\n    case (elim x)\n    hence \"f x \\<in> U \\<inter> V\" by simp\n    with `U \\<inter> V = {}` show ?case by simp\n  qed\n  with `\\<not> trivial_limit F` show \"False\"\n    by (simp add: trivial_limit_def)\nqed\n\nlemma (in t2_space) tendsto_const_iff:\n  assumes \"\\<not> trivial_limit F\" shows \"((\\<lambda>x. a :: 'a) ---> b) F \\<longleftrightarrow> a = b\"\n  by (auto intro!: tendsto_unique [OF assms tendsto_const])\n\nlemma increasing_tendsto:\n  fixes f :: \"_ \\<Rightarrow> 'a::order_topology\"\n  assumes bdd: \"eventually (\\<lambda>n. f n \\<le> l) F\"\n      and en: \"\\<And>x. x < l \\<Longrightarrow> eventually (\\<lambda>n. x < f n) F\"\n  shows \"(f ---> l) F\"\n  using assms by (intro order_tendstoI) (auto elim!: eventually_elim1)\n\nlemma decreasing_tendsto:\n  fixes f :: \"_ \\<Rightarrow> 'a::order_topology\"\n  assumes bdd: \"eventually (\\<lambda>n. l \\<le> f n) F\"\n      and en: \"\\<And>x. l < x \\<Longrightarrow> eventually (\\<lambda>n. f n < x) F\"\n  shows \"(f ---> l) F\"\n  using assms by (intro order_tendstoI) (auto elim!: eventually_elim1)\n\nlemma tendsto_sandwich:\n  fixes f g h :: \"'a \\<Rightarrow> 'b::order_topology\"\n  assumes ev: \"eventually (\\<lambda>n. f n \\<le> g n) net\" \"eventually (\\<lambda>n. g n \\<le> h n) net\"\n  assumes lim: \"(f ---> c) net\" \"(h ---> c) net\"\n  shows \"(g ---> c) net\"\nproof (rule order_tendstoI)\n  fix a show \"a < c \\<Longrightarrow> eventually (\\<lambda>x. a < g x) net\"\n    using order_tendstoD[OF lim(1), of a] ev by (auto elim: eventually_elim2)\nnext\n  fix a show \"c < a \\<Longrightarrow> eventually (\\<lambda>x. g x < a) net\"\n    using order_tendstoD[OF lim(2), of a] ev by (auto elim: eventually_elim2)\nqed\n\nlemma tendsto_le:\n  fixes f g :: \"'a \\<Rightarrow> 'b::linorder_topology\"\n  assumes F: \"\\<not> trivial_limit F\"\n  assumes x: \"(f ---> x) F\" and y: \"(g ---> y) F\"\n  assumes ev: \"eventually (\\<lambda>x. g x \\<le> f x) F\"\n  shows \"y \\<le> x\"\nproof (rule ccontr)\n  assume \"\\<not> y \\<le> x\"\n  with less_separate[of x y] obtain a b where xy: \"x < a\" \"b < y\" \"{..<a} \\<inter> {b<..} = {}\"\n    by (auto simp: not_le)\n  then have \"eventually (\\<lambda>x. f x < a) F\" \"eventually (\\<lambda>x. b < g x) F\"\n    using x y by (auto intro: order_tendstoD)\n  with ev have \"eventually (\\<lambda>x. False) F\"\n    by eventually_elim (insert xy, fastforce)\n  with F show False\n    by (simp add: eventually_False)\nqed\n\nlemma tendsto_le_const:\n  fixes f :: \"'a \\<Rightarrow> 'b::linorder_topology\"\n  assumes F: \"\\<not> trivial_limit F\"\n  assumes x: \"(f ---> x) F\" and a: \"eventually (\\<lambda>i. a \\<le> f i) F\"\n  shows \"a \\<le> x\"\n  using F x tendsto_const a by (rule tendsto_le)\n\nlemma tendsto_ge_const:\n  fixes f :: \"'a \\<Rightarrow> 'b::linorder_topology\"\n  assumes F: \"\\<not> trivial_limit F\"\n  assumes x: \"(f ---> x) F\" and a: \"eventually (\\<lambda>i. a \\<ge> f i) F\"\n  shows \"a \\<ge> x\"\n  by (rule tendsto_le [OF F tendsto_const x a])\n\nsubsubsection {* Rules about @{const Lim} *}\n\nlemma tendsto_Lim:\n  \"\\<not>(trivial_limit net) \\<Longrightarrow> (f ---> l) net \\<Longrightarrow> Lim net f = l\"\n  unfolding Lim_def using tendsto_unique[of net f] by auto\n\nlemma Lim_ident_at: \"\\<not> trivial_limit (at x within s) \\<Longrightarrow> Lim (at x within s) (\\<lambda>x. x) = x\"\n  by (rule tendsto_Lim[OF _ tendsto_ident_at]) auto\n\nsubsection {* Limits to @{const at_top} and @{const at_bot} *}\n\nlemma filterlim_at_top:\n  fixes f :: \"'a \\<Rightarrow> ('b::linorder)\"\n  shows \"(LIM x F. f x :> at_top) \\<longleftrightarrow> (\\<forall>Z. eventually (\\<lambda>x. Z \\<le> f x) F)\"\n  by (auto simp: filterlim_iff eventually_at_top_linorder elim!: eventually_elim1)\n\nlemma filterlim_at_top_mono:\n  \"LIM x F. f x :> at_top \\<Longrightarrow> eventually (\\<lambda>x. f x \\<le> (g x::'a::linorder)) F \\<Longrightarrow>\n    LIM x F. g x :> at_top\"\n  by (auto simp: filterlim_at_top elim: eventually_elim2 intro: order_trans)\n\nlemma filterlim_at_top_dense:\n  fixes f :: \"'a \\<Rightarrow> ('b::unbounded_dense_linorder)\"\n  shows \"(LIM x F. f x :> at_top) \\<longleftrightarrow> (\\<forall>Z. eventually (\\<lambda>x. Z < f x) F)\"\n  by (metis eventually_elim1[of _ F] eventually_gt_at_top order_less_imp_le\n            filterlim_at_top[of f F] filterlim_iff[of f at_top F])\n\nlemma filterlim_at_top_ge:\n  fixes f :: \"'a \\<Rightarrow> ('b::linorder)\" and c :: \"'b\"\n  shows \"(LIM x F. f x :> at_top) \\<longleftrightarrow> (\\<forall>Z\\<ge>c. eventually (\\<lambda>x. Z \\<le> f x) F)\"\n  unfolding at_top_sub[of c] filterlim_INF by (auto simp add: filterlim_principal)\n\nlemma filterlim_at_top_at_top:\n  fixes f :: \"'a::linorder \\<Rightarrow> 'b::linorder\"\n  assumes mono: \"\\<And>x y. Q x \\<Longrightarrow> Q y \\<Longrightarrow> x \\<le> y \\<Longrightarrow> f x \\<le> f y\"\n  assumes bij: \"\\<And>x. P x \\<Longrightarrow> f (g x) = x\" \"\\<And>x. P x \\<Longrightarrow> Q (g x)\"\n  assumes Q: \"eventually Q at_top\"\n  assumes P: \"eventually P at_top\"\n  shows \"filterlim f at_top at_top\"\nproof -\n  from P obtain x where x: \"\\<And>y. x \\<le> y \\<Longrightarrow> P y\"\n    unfolding eventually_at_top_linorder by auto\n  show ?thesis\n  proof (intro filterlim_at_top_ge[THEN iffD2] allI impI)\n    fix z assume \"x \\<le> z\"\n    with x have \"P z\" by auto\n    have \"eventually (\\<lambda>x. g z \\<le> x) at_top\"\n      by (rule eventually_ge_at_top)\n    with Q show \"eventually (\\<lambda>x. z \\<le> f x) at_top\"\n      by eventually_elim (metis mono bij `P z`)\n  qed\nqed\n\nlemma filterlim_at_top_gt:\n  fixes f :: \"'a \\<Rightarrow> ('b::unbounded_dense_linorder)\" and c :: \"'b\"\n  shows \"(LIM x F. f x :> at_top) \\<longleftrightarrow> (\\<forall>Z>c. eventually (\\<lambda>x. Z \\<le> f x) F)\"\n  by (metis filterlim_at_top order_less_le_trans gt_ex filterlim_at_top_ge)\n\nlemma filterlim_at_bot: \n  fixes f :: \"'a \\<Rightarrow> ('b::linorder)\"\n  shows \"(LIM x F. f x :> at_bot) \\<longleftrightarrow> (\\<forall>Z. eventually (\\<lambda>x. f x \\<le> Z) F)\"\n  by (auto simp: filterlim_iff eventually_at_bot_linorder elim!: eventually_elim1)\n\nlemma filterlim_at_bot_dense:\n  fixes f :: \"'a \\<Rightarrow> ('b::{dense_linorder, no_bot})\"\n  shows \"(LIM x F. f x :> at_bot) \\<longleftrightarrow> (\\<forall>Z. eventually (\\<lambda>x. f x < Z) F)\"\nproof (auto simp add: filterlim_at_bot[of f F])\n  fix Z :: 'b\n  from lt_ex [of Z] obtain Z' where 1: \"Z' < Z\" ..\n  assume \"\\<forall>Z. eventually (\\<lambda>x. f x \\<le> Z) F\"\n  hence \"eventually (\\<lambda>x. f x \\<le> Z') F\" by auto\n  thus \"eventually (\\<lambda>x. f x < Z) F\"\n    apply (rule eventually_mono[rotated])\n    using 1 by auto\n  next \n    fix Z :: 'b \n    show \"\\<forall>Z. eventually (\\<lambda>x. f x < Z) F \\<Longrightarrow> eventually (\\<lambda>x. f x \\<le> Z) F\"\n      by (drule spec [of _ Z], erule eventually_mono[rotated], auto simp add: less_imp_le)\nqed\n\nlemma filterlim_at_bot_le:\n  fixes f :: \"'a \\<Rightarrow> ('b::linorder)\" and c :: \"'b\"\n  shows \"(LIM x F. f x :> at_bot) \\<longleftrightarrow> (\\<forall>Z\\<le>c. eventually (\\<lambda>x. Z \\<ge> f x) F)\"\n  unfolding filterlim_at_bot\nproof safe\n  fix Z assume *: \"\\<forall>Z\\<le>c. eventually (\\<lambda>x. Z \\<ge> f x) F\"\n  with *[THEN spec, of \"min Z c\"] show \"eventually (\\<lambda>x. Z \\<ge> f x) F\"\n    by (auto elim!: eventually_elim1)\nqed simp\n\nlemma filterlim_at_bot_lt:\n  fixes f :: \"'a \\<Rightarrow> ('b::unbounded_dense_linorder)\" and c :: \"'b\"\n  shows \"(LIM x F. f x :> at_bot) \\<longleftrightarrow> (\\<forall>Z<c. eventually (\\<lambda>x. Z \\<ge> f x) F)\"\n  by (metis filterlim_at_bot filterlim_at_bot_le lt_ex order_le_less_trans)\n\nlemma filterlim_at_bot_at_right:\n  fixes f :: \"'a::linorder_topology \\<Rightarrow> 'b::linorder\"\n  assumes mono: \"\\<And>x y. Q x \\<Longrightarrow> Q y \\<Longrightarrow> x \\<le> y \\<Longrightarrow> f x \\<le> f y\"\n  assumes bij: \"\\<And>x. P x \\<Longrightarrow> f (g x) = x\" \"\\<And>x. P x \\<Longrightarrow> Q (g x)\"\n  assumes Q: \"eventually Q (at_right a)\" and bound: \"\\<And>b. Q b \\<Longrightarrow> a < b\"\n  assumes P: \"eventually P at_bot\"\n  shows \"filterlim f at_bot (at_right a)\"\nproof -\n  from P obtain x where x: \"\\<And>y. y \\<le> x \\<Longrightarrow> P y\"\n    unfolding eventually_at_bot_linorder by auto\n  show ?thesis\n  proof (intro filterlim_at_bot_le[THEN iffD2] allI impI)\n    fix z assume \"z \\<le> x\"\n    with x have \"P z\" by auto\n    have \"eventually (\\<lambda>x. x \\<le> g z) (at_right a)\"\n      using bound[OF bij(2)[OF `P z`]]\n      unfolding eventually_at_right[OF bound[OF bij(2)[OF `P z`]]] by (auto intro!: exI[of _ \"g z\"])\n    with Q show \"eventually (\\<lambda>x. f x \\<le> z) (at_right a)\"\n      by eventually_elim (metis bij `P z` mono)\n  qed\nqed\n\nlemma filterlim_at_top_at_left:\n  fixes f :: \"'a::linorder_topology \\<Rightarrow> 'b::linorder\"\n  assumes mono: \"\\<And>x y. Q x \\<Longrightarrow> Q y \\<Longrightarrow> x \\<le> y \\<Longrightarrow> f x \\<le> f y\"\n  assumes bij: \"\\<And>x. P x \\<Longrightarrow> f (g x) = x\" \"\\<And>x. P x \\<Longrightarrow> Q (g x)\"\n  assumes Q: \"eventually Q (at_left a)\" and bound: \"\\<And>b. Q b \\<Longrightarrow> b < a\"\n  assumes P: \"eventually P at_top\"\n  shows \"filterlim f at_top (at_left a)\"\nproof -\n  from P obtain x where x: \"\\<And>y. x \\<le> y \\<Longrightarrow> P y\"\n    unfolding eventually_at_top_linorder by auto\n  show ?thesis\n  proof (intro filterlim_at_top_ge[THEN iffD2] allI impI)\n    fix z assume \"x \\<le> z\"\n    with x have \"P z\" by auto\n    have \"eventually (\\<lambda>x. g z \\<le> x) (at_left a)\"\n      using bound[OF bij(2)[OF `P z`]]\n      unfolding eventually_at_left[OF bound[OF bij(2)[OF `P z`]]] by (auto intro!: exI[of _ \"g z\"])\n    with Q show \"eventually (\\<lambda>x. z \\<le> f x) (at_left a)\"\n      by eventually_elim (metis bij `P z` mono)\n  qed\nqed\n\nlemma filterlim_split_at:\n  \"filterlim f F (at_left x) \\<Longrightarrow> filterlim f F (at_right x) \\<Longrightarrow> filterlim f F (at (x::'a::linorder_topology))\"\n  by (subst at_eq_sup_left_right) (rule filterlim_sup)\n\nlemma filterlim_at_split:\n  \"filterlim f F (at (x::'a::linorder_topology)) \\<longleftrightarrow> filterlim f F (at_left x) \\<and> filterlim f F (at_right x)\"\n  by (subst at_eq_sup_left_right) (simp add: filterlim_def filtermap_sup)\n\nlemma eventually_nhds_top:\n  fixes P :: \"'a :: {order_top, linorder_topology} \\<Rightarrow> bool\"\n  assumes \"(b::'a) < top\"\n  shows \"eventually P (nhds top) \\<longleftrightarrow> (\\<exists>b<top. (\\<forall>z. b < z \\<longrightarrow> P z))\"\n  unfolding eventually_nhds\nproof safe\n  fix S :: \"'a set\" assume \"open S\" \"top \\<in> S\"\n  note open_left[OF this `b < top`]\n  moreover assume \"\\<forall>s\\<in>S. P s\"\n  ultimately show \"\\<exists>b<top. \\<forall>z>b. P z\"\n    by (auto simp: subset_eq Ball_def)\nnext\n  fix b assume \"b < top\" \"\\<forall>z>b. P z\"\n  then show \"\\<exists>S. open S \\<and> top \\<in> S \\<and> (\\<forall>xa\\<in>S. P xa)\"\n    by (intro exI[of _ \"{b <..}\"]) auto\nqed\n\nlemma tendsto_at_within_iff_tendsto_nhds:\n  \"(g ---> g l) (at l within S) \\<longleftrightarrow> (g ---> g l) (inf (nhds l) (principal S))\"\n  unfolding tendsto_def eventually_at_filter eventually_inf_principal\n  by (intro ext all_cong imp_cong) (auto elim!: eventually_elim1)\n\nsubsection {* Limits on sequences *}\n\nabbreviation (in topological_space)\n  LIMSEQ :: \"[nat \\<Rightarrow> 'a, 'a] \\<Rightarrow> bool\"\n    (\"((_)/ ----> (_))\" [60, 60] 60) where\n  \"X ----> L \\<equiv> (X ---> L) sequentially\"\n\nabbreviation (in t2_space) lim :: \"(nat \\<Rightarrow> 'a) \\<Rightarrow> 'a\" where\n  \"lim X \\<equiv> Lim sequentially X\"\n\ndefinition (in topological_space) convergent :: \"(nat \\<Rightarrow> 'a) \\<Rightarrow> bool\" where\n  \"convergent X = (\\<exists>L. X ----> L)\"\n\nlemma lim_def: \"lim X = (THE L. X ----> L)\"\n  unfolding Lim_def ..\n\nsubsubsection {* Monotone sequences and subsequences *}\n\ndefinition\n  monoseq :: \"(nat \\<Rightarrow> 'a::order) \\<Rightarrow> bool\" where\n    --{*Definition of monotonicity.\n        The use of disjunction here complicates proofs considerably.\n        One alternative is to add a Boolean argument to indicate the direction.\n        Another is to develop the notions of increasing and decreasing first.*}\n  \"monoseq X = ((\\<forall>m. \\<forall>n\\<ge>m. X m \\<le> X n) \\<or> (\\<forall>m. \\<forall>n\\<ge>m. X n \\<le> X m))\"\n\nabbreviation incseq :: \"(nat \\<Rightarrow> 'a::order) \\<Rightarrow> bool\" where\n  \"incseq X \\<equiv> mono X\"\n\nlemma incseq_def: \"incseq X \\<longleftrightarrow> (\\<forall>m. \\<forall>n\\<ge>m. X n \\<ge> X m)\"\n  unfolding mono_def ..\n\nabbreviation decseq :: \"(nat \\<Rightarrow> 'a::order) \\<Rightarrow> bool\" where\n  \"decseq X \\<equiv> antimono X\"\n\nlemma decseq_def: \"decseq X \\<longleftrightarrow> (\\<forall>m. \\<forall>n\\<ge>m. X n \\<le> X m)\"\n  unfolding antimono_def ..\n\ndefinition\n  subseq :: \"(nat \\<Rightarrow> nat) \\<Rightarrow> bool\" where\n    --{*Definition of subsequence*}\n  \"subseq f \\<longleftrightarrow> (\\<forall>m. \\<forall>n>m. f m < f n)\"\n\nlemma incseq_SucI:\n  \"(\\<And>n. X n \\<le> X (Suc n)) \\<Longrightarrow> incseq X\"\n  using lift_Suc_mono_le[of X]\n  by (auto simp: incseq_def)\n\nlemma incseqD: \"\\<And>i j. incseq f \\<Longrightarrow> i \\<le> j \\<Longrightarrow> f i \\<le> f j\"\n  by (auto simp: incseq_def)\n\nlemma incseq_SucD: \"incseq A \\<Longrightarrow> A i \\<le> A (Suc i)\"\n  using incseqD[of A i \"Suc i\"] by auto\n\nlemma incseq_Suc_iff: \"incseq f \\<longleftrightarrow> (\\<forall>n. f n \\<le> f (Suc n))\"\n  by (auto intro: incseq_SucI dest: incseq_SucD)\n\nlemma incseq_const[simp, intro]: \"incseq (\\<lambda>x. k)\"\n  unfolding incseq_def by auto\n\nlemma decseq_SucI:\n  \"(\\<And>n. X (Suc n) \\<le> X n) \\<Longrightarrow> decseq X\"\n  using order.lift_Suc_mono_le[OF dual_order, of X]\n  by (auto simp: decseq_def)\n\nlemma decseqD: \"\\<And>i j. decseq f \\<Longrightarrow> i \\<le> j \\<Longrightarrow> f j \\<le> f i\"\n  by (auto simp: decseq_def)\n\nlemma decseq_SucD: \"decseq A \\<Longrightarrow> A (Suc i) \\<le> A i\"\n  using decseqD[of A i \"Suc i\"] by auto\n\nlemma decseq_Suc_iff: \"decseq f \\<longleftrightarrow> (\\<forall>n. f (Suc n) \\<le> f n)\"\n  by (auto intro: decseq_SucI dest: decseq_SucD)\n\nlemma decseq_const[simp, intro]: \"decseq (\\<lambda>x. k)\"\n  unfolding decseq_def by auto\n\nlemma monoseq_iff: \"monoseq X \\<longleftrightarrow> incseq X \\<or> decseq X\"\n  unfolding monoseq_def incseq_def decseq_def ..\n\nlemma monoseq_Suc:\n  \"monoseq X \\<longleftrightarrow> (\\<forall>n. X n \\<le> X (Suc n)) \\<or> (\\<forall>n. X (Suc n) \\<le> X n)\"\n  unfolding monoseq_iff incseq_Suc_iff decseq_Suc_iff ..\n\nlemma monoI1: \"\\<forall>m. \\<forall> n \\<ge> m. X m \\<le> X n ==> monoseq X\"\nby (simp add: monoseq_def)\n\nlemma monoI2: \"\\<forall>m. \\<forall> n \\<ge> m. X n \\<le> X m ==> monoseq X\"\nby (simp add: monoseq_def)\n\nlemma mono_SucI1: \"\\<forall>n. X n \\<le> X (Suc n) ==> monoseq X\"\nby (simp add: monoseq_Suc)\n\nlemma mono_SucI2: \"\\<forall>n. X (Suc n) \\<le> X n ==> monoseq X\"\nby (simp add: monoseq_Suc)\n\nlemma monoseq_minus:\n  fixes a :: \"nat \\<Rightarrow> 'a::ordered_ab_group_add\"\n  assumes \"monoseq a\"\n  shows \"monoseq (\\<lambda> n. - a n)\"\nproof (cases \"\\<forall> m. \\<forall> n \\<ge> m. a m \\<le> a n\")\n  case True\n  hence \"\\<forall> m. \\<forall> n \\<ge> m. - a n \\<le> - a m\" by auto\n  thus ?thesis by (rule monoI2)\nnext\n  case False\n  hence \"\\<forall> m. \\<forall> n \\<ge> m. - a m \\<le> - a n\" using `monoseq a`[unfolded monoseq_def] by auto\n  thus ?thesis by (rule monoI1)\nqed\n\ntext{*Subsequence (alternative definition, (e.g. Hoskins)*}\n\nlemma subseq_Suc_iff: \"subseq f = (\\<forall>n. (f n) < (f (Suc n)))\"\napply (simp add: subseq_def)\napply (auto dest!: less_imp_Suc_add)\napply (induct_tac k)\napply (auto intro: less_trans)\ndone\n\ntext{* for any sequence, there is a monotonic subsequence *}\nlemma seq_monosub:\n  fixes s :: \"nat => 'a::linorder\"\n  shows \"\\<exists>f. subseq f \\<and> monoseq (\\<lambda>n. (s (f n)))\"\nproof cases\n  assume \"\\<forall>n. \\<exists>p>n. \\<forall>m\\<ge>p. s m \\<le> s p\"\n  then have \"\\<exists>f. \\<forall>n. (\\<forall>m\\<ge>f n. s m \\<le> s (f n)) \\<and> f n < f (Suc n)\"\n    by (intro dependent_nat_choice) (auto simp: conj_commute)\n  then obtain f where \"subseq f\" and mono: \"\\<And>n m. f n \\<le> m \\<Longrightarrow> s m \\<le> s (f n)\"\n    by (auto simp: subseq_Suc_iff)\n  moreover \n  then have \"incseq f\"\n    unfolding subseq_Suc_iff incseq_Suc_iff by (auto intro: less_imp_le)\n  then have \"monoseq (\\<lambda>n. s (f n))\"\n    by (auto simp add: incseq_def intro!: mono monoI2)\n  ultimately show ?thesis\n    by auto\nnext\n  assume \"\\<not> (\\<forall>n. \\<exists>p>n. (\\<forall>m\\<ge>p. s m \\<le> s p))\"\n  then obtain N where N: \"\\<And>p. p > N \\<Longrightarrow> \\<exists>m>p. s p < s m\" by (force simp: not_le le_less)\n  have \"\\<exists>f. \\<forall>n. N < f n \\<and> f n < f (Suc n) \\<and> s (f n) \\<le> s (f (Suc n))\"\n  proof (intro dependent_nat_choice)\n    fix x assume \"N < x\" with N[of x] show \"\\<exists>y>N. x < y \\<and> s x \\<le> s y\"\n      by (auto intro: less_trans)\n  qed auto\n  then show ?thesis\n    by (auto simp: monoseq_iff incseq_Suc_iff subseq_Suc_iff)\nqed\n\nlemma seq_suble: assumes sf: \"subseq f\" shows \"n \\<le> f n\"\nproof(induct n)\n  case 0 thus ?case by simp\nnext\n  case (Suc n)\n  from sf[unfolded subseq_Suc_iff, rule_format, of n] Suc.hyps\n  have \"n < f (Suc n)\" by arith\n  thus ?case by arith\nqed\n\nlemma eventually_subseq:\n  \"subseq r \\<Longrightarrow> eventually P sequentially \\<Longrightarrow> eventually (\\<lambda>n. P (r n)) sequentially\"\n  unfolding eventually_sequentially by (metis seq_suble le_trans)\n\nlemma not_eventually_sequentiallyD:\n  assumes P: \"\\<not> eventually P sequentially\"\n  shows \"\\<exists>r. subseq r \\<and> (\\<forall>n. \\<not> P (r n))\"\nproof -\n  from P have \"\\<forall>n. \\<exists>m\\<ge>n. \\<not> P m\"\n    unfolding eventually_sequentially by (simp add: not_less)\n  then obtain r where \"\\<And>n. r n \\<ge> n\" \"\\<And>n. \\<not> P (r n)\"\n    by (auto simp: choice_iff)\n  then show ?thesis\n    by (auto intro!: exI[of _ \"\\<lambda>n. r (((Suc \\<circ> r) ^^ Suc n) 0)\"]\n             simp: less_eq_Suc_le subseq_Suc_iff)\nqed\n\nlemma filterlim_subseq: \"subseq f \\<Longrightarrow> filterlim f sequentially sequentially\"\n  unfolding filterlim_iff by (metis eventually_subseq)\n\nlemma subseq_o: \"subseq r \\<Longrightarrow> subseq s \\<Longrightarrow> subseq (r \\<circ> s)\"\n  unfolding subseq_def by simp\n\nlemma subseq_mono: assumes \"subseq r\" \"m < n\" shows \"r m < r n\"\n  using assms by (auto simp: subseq_def)\n\nlemma incseq_imp_monoseq:  \"incseq X \\<Longrightarrow> monoseq X\"\n  by (simp add: incseq_def monoseq_def)\n\nlemma decseq_imp_monoseq:  \"decseq X \\<Longrightarrow> monoseq X\"\n  by (simp add: decseq_def monoseq_def)\n\nlemma decseq_eq_incseq:\n  fixes X :: \"nat \\<Rightarrow> 'a::ordered_ab_group_add\" shows \"decseq X = incseq (\\<lambda>n. - X n)\" \n  by (simp add: decseq_def incseq_def)\n\nlemma INT_decseq_offset:\n  assumes \"decseq F\"\n  shows \"(\\<Inter>i. F i) = (\\<Inter>i\\<in>{n..}. F i)\"\nproof safe\n  fix x i assume x: \"x \\<in> (\\<Inter>i\\<in>{n..}. F i)\"\n  show \"x \\<in> F i\"\n  proof cases\n    from x have \"x \\<in> F n\" by auto\n    also assume \"i \\<le> n\" with `decseq F` have \"F n \\<subseteq> F i\"\n      unfolding decseq_def by simp\n    finally show ?thesis .\n  qed (insert x, simp)\nqed auto\n\nlemma LIMSEQ_const_iff:\n  fixes k l :: \"'a::t2_space\"\n  shows \"(\\<lambda>n. k) ----> l \\<longleftrightarrow> k = l\"\n  using trivial_limit_sequentially by (rule tendsto_const_iff)\n\nlemma LIMSEQ_SUP:\n  \"incseq X \\<Longrightarrow> X ----> (SUP i. X i :: 'a :: {complete_linorder, linorder_topology})\"\n  by (intro increasing_tendsto)\n     (auto simp: SUP_upper less_SUP_iff incseq_def eventually_sequentially intro: less_le_trans)\n\nlemma LIMSEQ_INF:\n  \"decseq X \\<Longrightarrow> X ----> (INF i. X i :: 'a :: {complete_linorder, linorder_topology})\"\n  by (intro decreasing_tendsto)\n     (auto simp: INF_lower INF_less_iff decseq_def eventually_sequentially intro: le_less_trans)\n\nlemma LIMSEQ_ignore_initial_segment:\n  \"f ----> a \\<Longrightarrow> (\\<lambda>n. f (n + k)) ----> a\"\n  unfolding tendsto_def\n  by (subst eventually_sequentially_seg[where k=k])\n\nlemma LIMSEQ_offset:\n  \"(\\<lambda>n. f (n + k)) ----> a \\<Longrightarrow> f ----> a\"\n  unfolding tendsto_def\n  by (subst (asm) eventually_sequentially_seg[where k=k])\n\nlemma LIMSEQ_Suc: \"f ----> l \\<Longrightarrow> (\\<lambda>n. f (Suc n)) ----> l\"\nby (drule_tac k=\"Suc 0\" in LIMSEQ_ignore_initial_segment, simp)\n\nlemma LIMSEQ_imp_Suc: \"(\\<lambda>n. f (Suc n)) ----> l \\<Longrightarrow> f ----> l\"\nby (rule_tac k=\"Suc 0\" in LIMSEQ_offset, simp)\n\nlemma LIMSEQ_Suc_iff: \"(\\<lambda>n. f (Suc n)) ----> l = f ----> l\"\nby (blast intro: LIMSEQ_imp_Suc LIMSEQ_Suc)\n\nlemma LIMSEQ_unique:\n  fixes a b :: \"'a::t2_space\"\n  shows \"\\<lbrakk>X ----> a; X ----> b\\<rbrakk> \\<Longrightarrow> a = b\"\n  using trivial_limit_sequentially by (rule tendsto_unique)\n\nlemma LIMSEQ_le_const:\n  \"\\<lbrakk>X ----> (x::'a::linorder_topology); \\<exists>N. \\<forall>n\\<ge>N. a \\<le> X n\\<rbrakk> \\<Longrightarrow> a \\<le> x\"\n  using tendsto_le_const[of sequentially X x a] by (simp add: eventually_sequentially)\n\nlemma LIMSEQ_le:\n  \"\\<lbrakk>X ----> x; Y ----> y; \\<exists>N. \\<forall>n\\<ge>N. X n \\<le> Y n\\<rbrakk> \\<Longrightarrow> x \\<le> (y::'a::linorder_topology)\"\n  using tendsto_le[of sequentially Y y X x] by (simp add: eventually_sequentially)\n\nlemma LIMSEQ_le_const2:\n  \"\\<lbrakk>X ----> (x::'a::linorder_topology); \\<exists>N. \\<forall>n\\<ge>N. X n \\<le> a\\<rbrakk> \\<Longrightarrow> x \\<le> a\"\n  by (rule LIMSEQ_le[of X x \"\\<lambda>n. a\"]) auto\n\nlemma convergentD: \"convergent X ==> \\<exists>L. (X ----> L)\"\nby (simp add: convergent_def)\n\nlemma convergentI: \"(X ----> L) ==> convergent X\"\nby (auto simp add: convergent_def)\n\nlemma convergent_LIMSEQ_iff: \"convergent X = (X ----> lim X)\"\nby (auto intro: theI LIMSEQ_unique simp add: convergent_def lim_def)\n\nlemma convergent_const: \"convergent (\\<lambda>n. c)\"\n  by (rule convergentI, rule tendsto_const)\n\nlemma monoseq_le:\n  \"monoseq a \\<Longrightarrow> a ----> (x::'a::linorder_topology) \\<Longrightarrow>\n    ((\\<forall> n. a n \\<le> x) \\<and> (\\<forall>m. \\<forall>n\\<ge>m. a m \\<le> a n)) \\<or> ((\\<forall> n. x \\<le> a n) \\<and> (\\<forall>m. \\<forall>n\\<ge>m. a n \\<le> a m))\"\n  by (metis LIMSEQ_le_const LIMSEQ_le_const2 decseq_def incseq_def monoseq_iff)\n\nlemma LIMSEQ_subseq_LIMSEQ:\n  \"\\<lbrakk> X ----> L; subseq f \\<rbrakk> \\<Longrightarrow> (X o f) ----> L\"\n  unfolding comp_def by (rule filterlim_compose[of X, OF _ filterlim_subseq])\n\nlemma convergent_subseq_convergent:\n  \"\\<lbrakk>convergent X; subseq f\\<rbrakk> \\<Longrightarrow> convergent (X o f)\"\n  unfolding convergent_def by (auto intro: LIMSEQ_subseq_LIMSEQ)\n\nlemma limI: \"X ----> L ==> lim X = L\"\n  by (rule tendsto_Lim) (rule trivial_limit_sequentially)\n\nlemma lim_le: \"convergent f \\<Longrightarrow> (\\<And>n. f n \\<le> (x::'a::linorder_topology)) \\<Longrightarrow> lim f \\<le> x\"\n  using LIMSEQ_le_const2[of f \"lim f\" x] by (simp add: convergent_LIMSEQ_iff)\n\nsubsubsection{*Increasing and Decreasing Series*}\n\nlemma incseq_le: \"incseq X \\<Longrightarrow> X ----> L \\<Longrightarrow> X n \\<le> (L::'a::linorder_topology)\"\n  by (metis incseq_def LIMSEQ_le_const)\n\nlemma decseq_le: \"decseq X \\<Longrightarrow> X ----> L \\<Longrightarrow> (L::'a::linorder_topology) \\<le> X n\"\n  by (metis decseq_def LIMSEQ_le_const2)\n\nsubsection {* First countable topologies *}\n\nclass first_countable_topology = topological_space +\n  assumes first_countable_basis:\n    \"\\<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))\"\n\nlemma (in first_countable_topology) countable_basis_at_decseq:\n  obtains A :: \"nat \\<Rightarrow> 'a set\" where\n    \"\\<And>i. open (A i)\" \"\\<And>i. x \\<in> (A i)\"\n    \"\\<And>S. open S \\<Longrightarrow> x \\<in> S \\<Longrightarrow> eventually (\\<lambda>i. A i \\<subseteq> S) sequentially\"\nproof atomize_elim\n  from first_countable_basis[of x] obtain A :: \"nat \\<Rightarrow> 'a set\" where\n    nhds: \"\\<And>i. open (A i)\" \"\\<And>i. x \\<in> A i\"\n    and incl: \"\\<And>S. open S \\<Longrightarrow> x \\<in> S \\<Longrightarrow> \\<exists>i. A i \\<subseteq> S\"  by auto\n  def F \\<equiv> \"\\<lambda>n. \\<Inter>i\\<le>n. A i\"\n  show \"\\<exists>A. (\\<forall>i. open (A i)) \\<and> (\\<forall>i. x \\<in> A i) \\<and>\n      (\\<forall>S. open S \\<longrightarrow> x \\<in> S \\<longrightarrow> eventually (\\<lambda>i. A i \\<subseteq> S) sequentially)\"\n  proof (safe intro!: exI[of _ F])\n    fix i\n    show \"open (F i)\" using nhds(1) by (auto simp: F_def)\n    show \"x \\<in> F i\" using nhds(2) by (auto simp: F_def)\n  next\n    fix S assume \"open S\" \"x \\<in> S\"\n    from incl[OF this] obtain i where \"F i \\<subseteq> S\" unfolding F_def by auto\n    moreover have \"\\<And>j. i \\<le> j \\<Longrightarrow> F j \\<subseteq> F i\"\n      by (auto simp: F_def)\n    ultimately show \"eventually (\\<lambda>i. F i \\<subseteq> S) sequentially\"\n      by (auto simp: eventually_sequentially)\n  qed\nqed\n\nlemma (in first_countable_topology) nhds_countable:\n  obtains X :: \"nat \\<Rightarrow> 'a set\"\n  where \"decseq X\" \"\\<And>n. open (X n)\" \"\\<And>n. x \\<in> X n\" \"nhds x = (INF n. principal (X n))\"\nproof -\n  from first_countable_basis obtain A :: \"nat \\<Rightarrow> 'a set\"\n    where A: \"\\<And>n. x \\<in> A n\" \"\\<And>n. open (A n)\" \"\\<And>S. open S \\<Longrightarrow> x \\<in> S \\<Longrightarrow> \\<exists>i. A i \\<subseteq> S\"\n    by metis\n  show thesis\n  proof\n    show \"decseq (\\<lambda>n. \\<Inter>i\\<le>n. A i)\"\n      by (auto simp: decseq_def)\n    show \"\\<And>n. x \\<in> (\\<Inter>i\\<le>n. A i)\" \"\\<And>n. open (\\<Inter>i\\<le>n. A i)\"\n      using A by auto\n    show \"nhds x = (INF n. principal (\\<Inter> i\\<le>n. A i))\"\n      using A unfolding nhds_def\n      apply (intro INF_eq)\n      apply simp_all\n      apply force\n      apply (intro exI[of _ \"\\<Inter> i\\<le>n. A i\" for n] conjI open_INT)\n      apply auto\n      done\n  qed\nqed\n\nlemma (in first_countable_topology) countable_basis:\n  obtains A :: \"nat \\<Rightarrow> 'a set\" where\n    \"\\<And>i. open (A i)\" \"\\<And>i. x \\<in> A i\"\n    \"\\<And>F. (\\<forall>n. F n \\<in> A n) \\<Longrightarrow> F ----> x\"\nproof atomize_elim\n  obtain A :: \"nat \\<Rightarrow> 'a set\" 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 (rule countable_basis_at_decseq) blast\n  {\n    fix F S assume \"\\<forall>n. F n \\<in> A n\" \"open S\" \"x \\<in> S\"\n    with A(3)[of S] have \"eventually (\\<lambda>n. F n \\<in> S) sequentially\"\n      by (auto elim: eventually_elim1 simp: subset_eq)\n  }\n  with A show \"\\<exists>A. (\\<forall>i. open (A i)) \\<and> (\\<forall>i. x \\<in> A i) \\<and> (\\<forall>F. (\\<forall>n. F n \\<in> A n) \\<longrightarrow> F ----> x)\"\n    by (intro exI[of _ A]) (auto simp: tendsto_def)\nqed\n\nlemma (in first_countable_topology) sequentially_imp_eventually_nhds_within:\n  assumes \"\\<forall>f. (\\<forall>n. f n \\<in> s) \\<and> f ----> a \\<longrightarrow> eventually (\\<lambda>n. P (f n)) sequentially\"\n  shows \"eventually P (inf (nhds a) (principal s))\"\nproof (rule ccontr)\n  obtain A :: \"nat \\<Rightarrow> 'a set\" where A:\n    \"\\<And>i. open (A i)\"\n    \"\\<And>i. a \\<in> A i\"\n    \"\\<And>F. \\<forall>n. F n \\<in> A n \\<Longrightarrow> F ----> a\"\n    by (rule countable_basis) blast\n  assume \"\\<not> ?thesis\"\n  with A have P: \"\\<exists>F. \\<forall>n. F n \\<in> s \\<and> F n \\<in> A n \\<and> \\<not> P (F n)\"\n    unfolding eventually_inf_principal eventually_nhds by (intro choice) fastforce\n  then obtain F where F0: \"\\<forall>n. F n \\<in> s\" and F2: \"\\<forall>n. F n \\<in> A n\" and F3: \"\\<forall>n. \\<not> P (F n)\"\n    by blast\n  with A have \"F ----> a\" by auto\n  hence \"eventually (\\<lambda>n. P (F n)) sequentially\"\n    using assms F0 by simp\n  thus \"False\" by (simp add: F3)\nqed\n\nlemma (in first_countable_topology) eventually_nhds_within_iff_sequentially:\n  \"eventually P (inf (nhds a) (principal s)) \\<longleftrightarrow> \n    (\\<forall>f. (\\<forall>n. f n \\<in> s) \\<and> f ----> a \\<longrightarrow> eventually (\\<lambda>n. P (f n)) sequentially)\"\nproof (safe intro!: sequentially_imp_eventually_nhds_within)\n  assume \"eventually P (inf (nhds a) (principal s))\" \n  then obtain S where \"open S\" \"a \\<in> S\" \"\\<forall>x\\<in>S. x \\<in> s \\<longrightarrow> P x\"\n    by (auto simp: eventually_inf_principal eventually_nhds)\n  moreover fix f assume \"\\<forall>n. f n \\<in> s\" \"f ----> a\"\n  ultimately show \"eventually (\\<lambda>n. P (f n)) sequentially\"\n    by (auto dest!: topological_tendstoD elim: eventually_elim1)\nqed\n\nlemma (in first_countable_topology) eventually_nhds_iff_sequentially:\n  \"eventually P (nhds a) \\<longleftrightarrow> (\\<forall>f. f ----> a \\<longrightarrow> eventually (\\<lambda>n. P (f n)) sequentially)\"\n  using eventually_nhds_within_iff_sequentially[of P a UNIV] by simp\n\nlemma tendsto_at_iff_sequentially:\n  fixes f :: \"'a :: first_countable_topology \\<Rightarrow> _\"\n  shows \"(f ---> a) (at x within s) \\<longleftrightarrow> (\\<forall>X. (\\<forall>i. X i \\<in> s - {x}) \\<longrightarrow> X ----> x \\<longrightarrow> ((f \\<circ> X) ----> a))\"\n  unfolding filterlim_def[of _ \"nhds a\"] le_filter_def eventually_filtermap at_within_def eventually_nhds_within_iff_sequentially comp_def\n  by metis\n\nsubsection {* Function limit at a point *}\n\nabbreviation\n  LIM :: \"('a::topological_space \\<Rightarrow> 'b::topological_space) \\<Rightarrow> 'a \\<Rightarrow> 'b \\<Rightarrow> bool\"\n        (\"((_)/ -- (_)/ --> (_))\" [60, 0, 60] 60) where\n  \"f -- a --> L \\<equiv> (f ---> L) (at a)\"\n\nlemma tendsto_within_open: \"a \\<in> S \\<Longrightarrow> open S \\<Longrightarrow> (f ---> l) (at a within S) \\<longleftrightarrow> (f -- a --> l)\"\n  unfolding tendsto_def by (simp add: at_within_open[where S=S])\n\nlemma LIM_const_not_eq[tendsto_intros]:\n  fixes a :: \"'a::perfect_space\"\n  fixes k L :: \"'b::t2_space\"\n  shows \"k \\<noteq> L \\<Longrightarrow> \\<not> (\\<lambda>x. k) -- a --> L\"\n  by (simp add: tendsto_const_iff)\n\nlemmas LIM_not_zero = LIM_const_not_eq [where L = 0]\n\nlemma LIM_const_eq:\n  fixes a :: \"'a::perfect_space\"\n  fixes k L :: \"'b::t2_space\"\n  shows \"(\\<lambda>x. k) -- a --> L \\<Longrightarrow> k = L\"\n  by (simp add: tendsto_const_iff)\n\nlemma LIM_unique:\n  fixes a :: \"'a::perfect_space\" and L M :: \"'b::t2_space\"\n  shows \"f -- a --> L \\<Longrightarrow> f -- a --> M \\<Longrightarrow> L = M\"\n  using at_neq_bot by (rule tendsto_unique)\n\ntext {* Limits are equal for functions equal except at limit point *}\n\nlemma LIM_equal: \"\\<forall>x. x \\<noteq> a --> (f x = g x) \\<Longrightarrow> (f -- a --> l) \\<longleftrightarrow> (g -- a --> l)\"\n  unfolding tendsto_def eventually_at_topological by simp\n\nlemma LIM_cong: \"a = b \\<Longrightarrow> (\\<And>x. x \\<noteq> b \\<Longrightarrow> f x = g x) \\<Longrightarrow> l = m \\<Longrightarrow> (f -- a --> l) \\<longleftrightarrow> (g -- b --> m)\"\n  by (simp add: LIM_equal)\n\nlemma LIM_cong_limit: \"f -- x --> L \\<Longrightarrow> K = L \\<Longrightarrow> f -- x --> K\"\n  by simp\n\nlemma tendsto_at_iff_tendsto_nhds:\n  \"g -- l --> g l \\<longleftrightarrow> (g ---> g l) (nhds l)\"\n  unfolding tendsto_def eventually_at_filter\n  by (intro ext all_cong imp_cong) (auto elim!: eventually_elim1)\n\nlemma tendsto_compose:\n  \"g -- l --> g l \\<Longrightarrow> (f ---> l) F \\<Longrightarrow> ((\\<lambda>x. g (f x)) ---> g l) F\"\n  unfolding tendsto_at_iff_tendsto_nhds by (rule filterlim_compose[of g])\n\nlemma LIM_o: \"\\<lbrakk>g -- l --> g l; f -- a --> l\\<rbrakk> \\<Longrightarrow> (g \\<circ> f) -- a --> g l\"\n  unfolding o_def by (rule tendsto_compose)\n\nlemma tendsto_compose_eventually:\n  \"g -- l --> m \\<Longrightarrow> (f ---> l) F \\<Longrightarrow> eventually (\\<lambda>x. f x \\<noteq> l) F \\<Longrightarrow> ((\\<lambda>x. g (f x)) ---> m) F\"\n  by (rule filterlim_compose[of g _ \"at l\"]) (auto simp add: filterlim_at)\n\nlemma LIM_compose_eventually:\n  assumes f: \"f -- a --> b\"\n  assumes g: \"g -- b --> c\"\n  assumes inj: \"eventually (\\<lambda>x. f x \\<noteq> b) (at a)\"\n  shows \"(\\<lambda>x. g (f x)) -- a --> c\"\n  using g f inj by (rule tendsto_compose_eventually)\n\nlemma tendsto_compose_filtermap: \"((g \\<circ> f) ---> T) F \\<longleftrightarrow> (g ---> T) (filtermap f F)\"\n  by (simp add: filterlim_def filtermap_filtermap comp_def)\n\nsubsubsection {* Relation of LIM and LIMSEQ *}\n\nlemma (in first_countable_topology) sequentially_imp_eventually_within:\n  \"(\\<forall>f. (\\<forall>n. f n \\<in> s \\<and> f n \\<noteq> a) \\<and> f ----> a \\<longrightarrow> eventually (\\<lambda>n. P (f n)) sequentially) \\<Longrightarrow>\n    eventually P (at a within s)\"\n  unfolding at_within_def\n  by (intro sequentially_imp_eventually_nhds_within) auto\n\nlemma (in first_countable_topology) sequentially_imp_eventually_at:\n  \"(\\<forall>f. (\\<forall>n. f n \\<noteq> a) \\<and> f ----> a \\<longrightarrow> eventually (\\<lambda>n. P (f n)) sequentially) \\<Longrightarrow> eventually P (at a)\"\n  using assms sequentially_imp_eventually_within [where s=UNIV] by simp\n\nlemma LIMSEQ_SEQ_conv1:\n  fixes f :: \"'a::topological_space \\<Rightarrow> 'b::topological_space\"\n  assumes f: \"f -- a --> l\"\n  shows \"\\<forall>S. (\\<forall>n. S n \\<noteq> a) \\<and> S ----> a \\<longrightarrow> (\\<lambda>n. f (S n)) ----> l\"\n  using tendsto_compose_eventually [OF f, where F=sequentially] by simp\n\nlemma LIMSEQ_SEQ_conv2:\n  fixes f :: \"'a::first_countable_topology \\<Rightarrow> 'b::topological_space\"\n  assumes \"\\<forall>S. (\\<forall>n. S n \\<noteq> a) \\<and> S ----> a \\<longrightarrow> (\\<lambda>n. f (S n)) ----> l\"\n  shows \"f -- a --> l\"\n  using assms unfolding tendsto_def [where l=l] by (simp add: sequentially_imp_eventually_at)\n\nlemma LIMSEQ_SEQ_conv:\n  \"(\\<forall>S. (\\<forall>n. S n \\<noteq> a) \\<and> S ----> (a::'a::first_countable_topology) \\<longrightarrow> (\\<lambda>n. X (S n)) ----> L) =\n   (X -- a --> (L::'b::topological_space))\"\n  using LIMSEQ_SEQ_conv2 LIMSEQ_SEQ_conv1 ..\n\nlemma sequentially_imp_eventually_at_left:\n  fixes a :: \"'a :: {dense_linorder, linorder_topology, first_countable_topology}\"\n  assumes b[simp]: \"b < a\"\n  assumes *: \"\\<And>f. (\\<And>n. b < f n) \\<Longrightarrow> (\\<And>n. f n < a) \\<Longrightarrow> incseq f \\<Longrightarrow> f ----> a \\<Longrightarrow> eventually (\\<lambda>n. P (f n)) sequentially\"\n  shows \"eventually P (at_left a)\"\nproof (safe intro!: sequentially_imp_eventually_within)\n  fix X assume X: \"\\<forall>n. X n \\<in> {..< a} \\<and> X n \\<noteq> a\" \"X ----> a\"\n  show \"eventually (\\<lambda>n. P (X n)) sequentially\"\n  proof (rule ccontr)\n    assume neg: \"\\<not> eventually (\\<lambda>n. P (X n)) sequentially\"\n    have \"\\<exists>s. \\<forall>n. (\\<not> P (X (s n)) \\<and> b < X (s n)) \\<and> (X (s n) \\<le> X (s (Suc n)) \\<and> Suc (s n) \\<le> s (Suc n))\"\n    proof (rule dependent_nat_choice)\n      have \"\\<not> eventually (\\<lambda>n. b < X n \\<longrightarrow> P (X n)) sequentially\"\n        by (intro not_eventually_impI neg order_tendstoD(1) [OF X(2) b])\n      then show \"\\<exists>x. \\<not> P (X x) \\<and> b < X x\"\n        by (auto dest!: not_eventuallyD)\n    next\n      fix x n\n      have \"\\<not> eventually (\\<lambda>n. Suc x \\<le> n \\<longrightarrow> b < X n \\<longrightarrow> X x < X n \\<longrightarrow> P (X n)) sequentially\"\n        using X by (intro not_eventually_impI order_tendstoD(1)[OF X(2)] eventually_ge_at_top neg) auto\n      then show \"\\<exists>n. (\\<not> P (X n) \\<and> b < X n) \\<and> (X x \\<le> X n \\<and> Suc x \\<le> n)\"\n        by (auto dest!: not_eventuallyD)\n    qed\n    then guess s ..\n    then have \"\\<And>n. b < X (s n)\" \"\\<And>n. X (s n) < a\" \"incseq (\\<lambda>n. X (s n))\" \"(\\<lambda>n. X (s n)) ----> a\" \"\\<And>n. \\<not> P (X (s n))\"\n      using X by (auto simp: subseq_Suc_iff Suc_le_eq incseq_Suc_iff intro!: LIMSEQ_subseq_LIMSEQ[OF `X ----> a`, unfolded comp_def])\n    from *[OF this(1,2,3,4)] this(5) show False by auto\n  qed\nqed\n\nlemma tendsto_at_left_sequentially:\n  fixes a :: \"_ :: {dense_linorder, linorder_topology, first_countable_topology}\"\n  assumes \"b < a\"\n  assumes *: \"\\<And>S. (\\<And>n. S n < a) \\<Longrightarrow> (\\<And>n. b < S n) \\<Longrightarrow> incseq S \\<Longrightarrow> S ----> a \\<Longrightarrow> (\\<lambda>n. X (S n)) ----> L\"\n  shows \"(X ---> L) (at_left a)\"\n  using assms unfolding tendsto_def [where l=L]\n  by (simp add: sequentially_imp_eventually_at_left)\n\nlemma sequentially_imp_eventually_at_right:\n  fixes a :: \"'a :: {dense_linorder, linorder_topology, first_countable_topology}\"\n  assumes b[simp]: \"a < b\"\n  assumes *: \"\\<And>f. (\\<And>n. a < f n) \\<Longrightarrow> (\\<And>n. f n < b) \\<Longrightarrow> decseq f \\<Longrightarrow> f ----> a \\<Longrightarrow> eventually (\\<lambda>n. P (f n)) sequentially\"\n  shows \"eventually P (at_right a)\"\nproof (safe intro!: sequentially_imp_eventually_within)\n  fix X assume X: \"\\<forall>n. X n \\<in> {a <..} \\<and> X n \\<noteq> a\" \"X ----> a\"\n  show \"eventually (\\<lambda>n. P (X n)) sequentially\"\n  proof (rule ccontr)\n    assume neg: \"\\<not> eventually (\\<lambda>n. P (X n)) sequentially\"\n    have \"\\<exists>s. \\<forall>n. (\\<not> P (X (s n)) \\<and> X (s n) < b) \\<and> (X (s (Suc n)) \\<le> X (s n) \\<and> Suc (s n) \\<le> s (Suc n))\"\n    proof (rule dependent_nat_choice)\n      have \"\\<not> eventually (\\<lambda>n. X n < b \\<longrightarrow> P (X n)) sequentially\"\n        by (intro not_eventually_impI neg order_tendstoD(2) [OF X(2) b])\n      then show \"\\<exists>x. \\<not> P (X x) \\<and> X x < b\"\n        by (auto dest!: not_eventuallyD)\n    next\n      fix x n\n      have \"\\<not> eventually (\\<lambda>n. Suc x \\<le> n \\<longrightarrow> X n < b \\<longrightarrow> X n < X x \\<longrightarrow> P (X n)) sequentially\"\n        using X by (intro not_eventually_impI order_tendstoD(2)[OF X(2)] eventually_ge_at_top neg) auto\n      then show \"\\<exists>n. (\\<not> P (X n) \\<and> X n < b) \\<and> (X n \\<le> X x \\<and> Suc x \\<le> n)\"\n        by (auto dest!: not_eventuallyD)\n    qed\n    then guess s ..\n    then have \"\\<And>n. a < X (s n)\" \"\\<And>n. X (s n) < b\" \"decseq (\\<lambda>n. X (s n))\" \"(\\<lambda>n. X (s n)) ----> a\" \"\\<And>n. \\<not> P (X (s n))\"\n      using X by (auto simp: subseq_Suc_iff Suc_le_eq decseq_Suc_iff intro!: LIMSEQ_subseq_LIMSEQ[OF `X ----> a`, unfolded comp_def])\n    from *[OF this(1,2,3,4)] this(5) show False by auto\n  qed\nqed\n\nlemma tendsto_at_right_sequentially:\n  fixes a :: \"_ :: {dense_linorder, linorder_topology, first_countable_topology}\"\n  assumes \"a < b\"\n  assumes *: \"\\<And>S. (\\<And>n. a < S n) \\<Longrightarrow> (\\<And>n. S n < b) \\<Longrightarrow> decseq S \\<Longrightarrow> S ----> a \\<Longrightarrow> (\\<lambda>n. X (S n)) ----> L\"\n  shows \"(X ---> L) (at_right a)\"\n  using assms unfolding tendsto_def [where l=L]\n  by (simp add: sequentially_imp_eventually_at_right)\n\nsubsection {* Continuity *}\n\nsubsubsection {* Continuity on a set *}\n\ndefinition continuous_on :: \"'a set \\<Rightarrow> ('a :: topological_space \\<Rightarrow> 'b :: topological_space) \\<Rightarrow> bool\" where\n  \"continuous_on s f \\<longleftrightarrow> (\\<forall>x\\<in>s. (f ---> f x) (at x within s))\"\n\nlemma continuous_on_cong [cong]:\n  \"s = t \\<Longrightarrow> (\\<And>x. x \\<in> t \\<Longrightarrow> f x = g x) \\<Longrightarrow> continuous_on s f \\<longleftrightarrow> continuous_on t g\"\n  unfolding continuous_on_def by (intro ball_cong filterlim_cong) (auto simp: eventually_at_filter)\n\nlemma continuous_on_topological:\n  \"continuous_on s f \\<longleftrightarrow>\n    (\\<forall>x\\<in>s. \\<forall>B. open B \\<longrightarrow> f x \\<in> B \\<longrightarrow> (\\<exists>A. open A \\<and> x \\<in> A \\<and> (\\<forall>y\\<in>s. y \\<in> A \\<longrightarrow> f y \\<in> B)))\"\n  unfolding continuous_on_def tendsto_def eventually_at_topological by metis\n\nlemma continuous_on_open_invariant:\n  \"continuous_on s f \\<longleftrightarrow> (\\<forall>B. open B \\<longrightarrow> (\\<exists>A. open A \\<and> A \\<inter> s = f -` B \\<inter> s))\"\nproof safe\n  fix B :: \"'b set\" assume \"continuous_on s f\" \"open B\"\n  then have \"\\<forall>x\\<in>f -` B \\<inter> s. (\\<exists>A. open A \\<and> x \\<in> A \\<and> s \\<inter> A \\<subseteq> f -` B)\"\n    by (auto simp: continuous_on_topological subset_eq Ball_def imp_conjL)\n  then obtain A where \"\\<forall>x\\<in>f -` B \\<inter> s. open (A x) \\<and> x \\<in> A x \\<and> s \\<inter> A x \\<subseteq> f -` B\"\n    unfolding bchoice_iff ..\n  then show \"\\<exists>A. open A \\<and> A \\<inter> s = f -` B \\<inter> s\"\n    by (intro exI[of _ \"\\<Union>x\\<in>f -` B \\<inter> s. A x\"]) auto\nnext\n  assume B: \"\\<forall>B. open B \\<longrightarrow> (\\<exists>A. open A \\<and> A \\<inter> s = f -` B \\<inter> s)\"\n  show \"continuous_on s f\"\n    unfolding continuous_on_topological\n  proof safe\n    fix x B assume \"x \\<in> s\" \"open B\" \"f x \\<in> B\"\n    with B obtain A where A: \"open A\" \"A \\<inter> s = f -` B \\<inter> s\" by auto\n    with `x \\<in> s` `f x \\<in> B` show \"\\<exists>A. open A \\<and> x \\<in> A \\<and> (\\<forall>y\\<in>s. y \\<in> A \\<longrightarrow> f y \\<in> B)\"\n      by (intro exI[of _ A]) auto\n  qed\nqed\n\nlemma continuous_on_open_vimage:\n  \"open s \\<Longrightarrow> continuous_on s f \\<longleftrightarrow> (\\<forall>B. open B \\<longrightarrow> open (f -` B \\<inter> s))\"\n  unfolding continuous_on_open_invariant\n  by (metis open_Int Int_absorb Int_commute[of s] Int_assoc[of _ _ s])\n\ncorollary continuous_imp_open_vimage:\n  assumes \"continuous_on s f\" \"open s\" \"open B\" \"f -` B \\<subseteq> s\"\n    shows \"open (f -` B)\"\nby (metis assms continuous_on_open_vimage le_iff_inf)\n\ncorollary open_vimage[continuous_intros]:\n  assumes \"open s\" and \"continuous_on UNIV f\"\n  shows \"open (f -` s)\"\n  using assms unfolding continuous_on_open_vimage [OF open_UNIV]\n  by simp\n\nlemma continuous_on_closed_invariant:\n  \"continuous_on s f \\<longleftrightarrow> (\\<forall>B. closed B \\<longrightarrow> (\\<exists>A. closed A \\<and> A \\<inter> s = f -` B \\<inter> s))\"\nproof -\n  have *: \"\\<And>P Q::'b set\\<Rightarrow>bool. (\\<And>A. P A \\<longleftrightarrow> Q (- A)) \\<Longrightarrow> (\\<forall>A. P A) \\<longleftrightarrow> (\\<forall>A. Q A)\"\n    by (metis double_compl)\n  show ?thesis\n    unfolding continuous_on_open_invariant by (intro *) (auto simp: open_closed[symmetric])\nqed\n\nlemma continuous_on_closed_vimage:\n  \"closed s \\<Longrightarrow> continuous_on s f \\<longleftrightarrow> (\\<forall>B. closed B \\<longrightarrow> closed (f -` B \\<inter> s))\"\n  unfolding continuous_on_closed_invariant\n  by (metis closed_Int Int_absorb Int_commute[of s] Int_assoc[of _ _ s])\n\ncorollary closed_vimage[continuous_intros]:\n  assumes \"closed s\" and \"continuous_on UNIV f\"\n  shows \"closed (f -` s)\"\n  using assms unfolding continuous_on_closed_vimage [OF closed_UNIV]\n  by simp\n\nlemma continuous_on_open_Union:\n  \"(\\<And>s. s \\<in> S \\<Longrightarrow> open s) \\<Longrightarrow> (\\<And>s. s \\<in> S \\<Longrightarrow> continuous_on s f) \\<Longrightarrow> continuous_on (\\<Union>S) f\"\n  unfolding continuous_on_def by safe (metis open_Union at_within_open UnionI)\n\nlemma continuous_on_open_UN:\n  \"(\\<And>s. s \\<in> S \\<Longrightarrow> open (A s)) \\<Longrightarrow> (\\<And>s. s \\<in> S \\<Longrightarrow> continuous_on (A s) f) \\<Longrightarrow> continuous_on (\\<Union>s\\<in>S. A s) f\"\n  unfolding Union_image_eq[symmetric] by (rule continuous_on_open_Union) auto\n\nlemma continuous_on_closed_Un:\n  \"closed s \\<Longrightarrow> closed t \\<Longrightarrow> continuous_on s f \\<Longrightarrow> continuous_on t f \\<Longrightarrow> continuous_on (s \\<union> t) f\"\n  by (auto simp add: continuous_on_closed_vimage closed_Un Int_Un_distrib)\n\nlemma continuous_on_If:\n  assumes closed: \"closed s\" \"closed t\" and cont: \"continuous_on s f\" \"continuous_on t g\"\n    and P: \"\\<And>x. x \\<in> s \\<Longrightarrow> \\<not> P x \\<Longrightarrow> f x = g x\" \"\\<And>x. x \\<in> t \\<Longrightarrow> P x \\<Longrightarrow> f x = g x\"\n  shows \"continuous_on (s \\<union> t) (\\<lambda>x. if P x then f x else g x)\" (is \"continuous_on _ ?h\")\nproof-\n  from P have \"\\<forall>x\\<in>s. f x = ?h x\" \"\\<forall>x\\<in>t. g x = ?h x\"\n    by auto\n  with cont have \"continuous_on s ?h\" \"continuous_on t ?h\"\n    by simp_all\n  with closed show ?thesis\n    by (rule continuous_on_closed_Un)\nqed\n\nlemma continuous_on_id[continuous_intros]: \"continuous_on s (\\<lambda>x. x)\"\n  unfolding continuous_on_def by fast\n\nlemma continuous_on_const[continuous_intros]: \"continuous_on s (\\<lambda>x. c)\"\n  unfolding continuous_on_def by auto\n\nlemma continuous_on_compose[continuous_intros]:\n  \"continuous_on s f \\<Longrightarrow> continuous_on (f ` s) g \\<Longrightarrow> continuous_on s (g o f)\"\n  unfolding continuous_on_topological by simp metis\n\nlemma continuous_on_compose2:\n  \"continuous_on t g \\<Longrightarrow> continuous_on s f \\<Longrightarrow> t = f ` s \\<Longrightarrow> continuous_on s (\\<lambda>x. g (f x))\"\n  using continuous_on_compose[of s f g] by (simp add: comp_def)\n\nsubsubsection {* Continuity at a point *}\n\ndefinition continuous :: \"'a::t2_space filter \\<Rightarrow> ('a \\<Rightarrow> 'b::topological_space) \\<Rightarrow> bool\" where\n  \"continuous F f \\<longleftrightarrow> (f ---> f (Lim F (\\<lambda>x. x))) F\"\n\nlemma continuous_bot[continuous_intros, simp]: \"continuous bot f\"\n  unfolding continuous_def by auto\n\nlemma continuous_trivial_limit: \"trivial_limit net \\<Longrightarrow> continuous net f\"\n  by simp\n\nlemma continuous_within: \"continuous (at x within s) f \\<longleftrightarrow> (f ---> f x) (at x within s)\"\n  by (cases \"trivial_limit (at x within s)\") (auto simp add: Lim_ident_at continuous_def)\n\nlemma continuous_within_topological:\n  \"continuous (at x within s) f \\<longleftrightarrow>\n    (\\<forall>B. open B \\<longrightarrow> f x \\<in> B \\<longrightarrow> (\\<exists>A. open A \\<and> x \\<in> A \\<and> (\\<forall>y\\<in>s. y \\<in> A \\<longrightarrow> f y \\<in> B)))\"\n  unfolding continuous_within tendsto_def eventually_at_topological by metis\n\nlemma continuous_within_compose[continuous_intros]:\n  \"continuous (at x within s) f \\<Longrightarrow> continuous (at (f x) within f ` s) g \\<Longrightarrow>\n  continuous (at x within s) (g o f)\"\n  by (simp add: continuous_within_topological) metis\n\nlemma continuous_within_compose2:\n  \"continuous (at x within s) f \\<Longrightarrow> continuous (at (f x) within f ` s) g \\<Longrightarrow>\n  continuous (at x within s) (\\<lambda>x. g (f x))\"\n  using continuous_within_compose[of x s f g] by (simp add: comp_def)\n\nlemma continuous_at: \"continuous (at x) f \\<longleftrightarrow> f -- x --> f x\"\n  using continuous_within[of x UNIV f] by simp\n\nlemma continuous_ident[continuous_intros, simp]: \"continuous (at x within S) (\\<lambda>x. x)\"\n  unfolding continuous_within by (rule tendsto_ident_at)\n\nlemma continuous_const[continuous_intros, simp]: \"continuous F (\\<lambda>x. c)\"\n  unfolding continuous_def by (rule tendsto_const)\n\nlemma continuous_on_eq_continuous_within:\n  \"continuous_on s f \\<longleftrightarrow> (\\<forall>x\\<in>s. continuous (at x within s) f)\"\n  unfolding continuous_on_def continuous_within ..\n\nabbreviation isCont :: \"('a::t2_space \\<Rightarrow> 'b::topological_space) \\<Rightarrow> 'a \\<Rightarrow> bool\" where\n  \"isCont f a \\<equiv> continuous (at a) f\"\n\nlemma isCont_def: \"isCont f a \\<longleftrightarrow> f -- a --> f a\"\n  by (rule continuous_at)\n\nlemma continuous_at_within: \"isCont f x \\<Longrightarrow> continuous (at x within s) f\"\n  by (auto intro: tendsto_mono at_le simp: continuous_at continuous_within)\n\nlemma continuous_on_eq_continuous_at: \"open s \\<Longrightarrow> continuous_on s f \\<longleftrightarrow> (\\<forall>x\\<in>s. isCont f x)\"\n  by (simp add: continuous_on_def continuous_at at_within_open[of _ s])\n\nlemma continuous_on_subset: \"continuous_on s f \\<Longrightarrow> t \\<subseteq> s \\<Longrightarrow> continuous_on t f\"\n  unfolding continuous_on_def by (metis subset_eq tendsto_within_subset)\n\nlemma continuous_at_imp_continuous_on: \"\\<forall>x\\<in>s. isCont f x \\<Longrightarrow> continuous_on s f\"\n  by (auto intro: continuous_at_within simp: continuous_on_eq_continuous_within)\n\nlemma isContI_continuous: \"continuous (at x within UNIV) f \\<Longrightarrow> isCont f x\"\n  by simp\n\nlemma isCont_ident[continuous_intros, simp]: \"isCont (\\<lambda>x. x) a\"\n  using continuous_ident by (rule isContI_continuous)\n\nlemmas isCont_const = continuous_const\n\nlemma isCont_o2: \"isCont f a \\<Longrightarrow> isCont g (f a) \\<Longrightarrow> isCont (\\<lambda>x. g (f x)) a\"\n  unfolding isCont_def by (rule tendsto_compose)\n\nlemma isCont_o[continuous_intros]: \"isCont f a \\<Longrightarrow> isCont g (f a) \\<Longrightarrow> isCont (g \\<circ> f) a\"\n  unfolding o_def by (rule isCont_o2)\n\nlemma isCont_tendsto_compose: \"isCont g l \\<Longrightarrow> (f ---> l) F \\<Longrightarrow> ((\\<lambda>x. g (f x)) ---> g l) F\"\n  unfolding isCont_def by (rule tendsto_compose)\n\nlemma continuous_within_compose3:\n  \"isCont g (f x) \\<Longrightarrow> continuous (at x within s) f \\<Longrightarrow> continuous (at x within s) (\\<lambda>x. g (f x))\"\n  using continuous_within_compose2[of x s f g] by (simp add: continuous_at_within)\n\nlemma filtermap_nhds_open_map:\n  assumes cont: \"isCont f a\" and open_map: \"\\<And>S. open S \\<Longrightarrow> open (f`S)\"\n  shows \"filtermap f (nhds a) = nhds (f a)\"\n  unfolding filter_eq_iff\nproof safe\n  fix P assume \"eventually P (filtermap f (nhds a))\"\n  then guess S unfolding eventually_filtermap eventually_nhds ..\n  then show \"eventually P (nhds (f a))\"\n    unfolding eventually_nhds by (intro exI[of _ \"f`S\"]) (auto intro!: open_map)\nqed (metis filterlim_iff tendsto_at_iff_tendsto_nhds isCont_def eventually_filtermap cont)\n\nlemma continuous_at_split: \n  \"continuous (at (x::'a::linorder_topology)) f = (continuous (at_left x) f \\<and> continuous (at_right x) f)\"\n  by (simp add: continuous_within filterlim_at_split)\n\nsubsubsection{* Open-cover compactness *}\n\ncontext topological_space\nbegin\n\ndefinition compact :: \"'a set \\<Rightarrow> bool\" where\n  compact_eq_heine_borel: -- \"This name is used for backwards compatibility\"\n    \"compact S \\<longleftrightarrow> (\\<forall>C. (\\<forall>c\\<in>C. open c) \\<and> S \\<subseteq> \\<Union>C \\<longrightarrow> (\\<exists>D\\<subseteq>C. finite D \\<and> S \\<subseteq> \\<Union>D))\"\n\nlemma compactI:\n  assumes \"\\<And>C. \\<forall>t\\<in>C. open t \\<Longrightarrow> s \\<subseteq> \\<Union> C \\<Longrightarrow> \\<exists>C'. C' \\<subseteq> C \\<and> finite C' \\<and> s \\<subseteq> \\<Union> C'\"\n  shows \"compact s\"\n  unfolding compact_eq_heine_borel using assms by metis\n\nlemma compact_empty[simp]: \"compact {}\"\n  by (auto intro!: compactI)\n\nlemma compactE:\n  assumes \"compact s\" and \"\\<forall>t\\<in>C. open t\" and \"s \\<subseteq> \\<Union>C\"\n  obtains C' where \"C' \\<subseteq> C\" and \"finite C'\" and \"s \\<subseteq> \\<Union>C'\"\n  using assms unfolding compact_eq_heine_borel by metis\n\nlemma compactE_image:\n  assumes \"compact s\" and \"\\<forall>t\\<in>C. open (f t)\" and \"s \\<subseteq> (\\<Union>c\\<in>C. f c)\"\n  obtains C' where \"C' \\<subseteq> C\" and \"finite C'\" and \"s \\<subseteq> (\\<Union>c\\<in>C'. f c)\"\n  using assms unfolding ball_simps[symmetric] SUP_def\n  by (metis (lifting) finite_subset_image compact_eq_heine_borel[of s])\n\nlemma compact_inter_closed [intro]:\n  assumes \"compact s\" and \"closed t\"\n  shows \"compact (s \\<inter> t)\"\nproof (rule compactI)\n  fix C assume C: \"\\<forall>c\\<in>C. open c\" and cover: \"s \\<inter> t \\<subseteq> \\<Union>C\"\n  from C `closed t` have \"\\<forall>c\\<in>C \\<union> {-t}. open c\" by auto\n  moreover from cover have \"s \\<subseteq> \\<Union>(C \\<union> {-t})\" by auto\n  ultimately have \"\\<exists>D\\<subseteq>C \\<union> {-t}. finite D \\<and> s \\<subseteq> \\<Union>D\"\n    using `compact s` unfolding compact_eq_heine_borel by auto\n  then obtain D where \"D \\<subseteq> C \\<union> {- t} \\<and> finite D \\<and> s \\<subseteq> \\<Union>D\" ..\n  then show \"\\<exists>D\\<subseteq>C. finite D \\<and> s \\<inter> t \\<subseteq> \\<Union>D\"\n    by (intro exI[of _ \"D - {-t}\"]) auto\nqed\n\nlemma inj_setminus: \"inj_on uminus (A::'a set set)\"\n  by (auto simp: inj_on_def)\n\nlemma compact_fip:\n  \"compact U \\<longleftrightarrow>\n    (\\<forall>A. (\\<forall>a\\<in>A. closed a) \\<longrightarrow> (\\<forall>B \\<subseteq> A. finite B \\<longrightarrow> U \\<inter> \\<Inter>B \\<noteq> {}) \\<longrightarrow> U \\<inter> \\<Inter>A \\<noteq> {})\"\n  (is \"_ \\<longleftrightarrow> ?R\")\nproof (safe intro!: compact_eq_heine_borel[THEN iffD2])\n  fix A\n  assume \"compact U\"\n    and A: \"\\<forall>a\\<in>A. closed a\" \"U \\<inter> \\<Inter>A = {}\"\n    and fi: \"\\<forall>B \\<subseteq> A. finite B \\<longrightarrow> U \\<inter> \\<Inter>B \\<noteq> {}\"\n  from A have \"(\\<forall>a\\<in>uminus`A. open a) \\<and> U \\<subseteq> \\<Union>(uminus`A)\"\n    by auto\n  with `compact U` obtain B where \"B \\<subseteq> A\" \"finite (uminus`B)\" \"U \\<subseteq> \\<Union>(uminus`B)\"\n    unfolding compact_eq_heine_borel by (metis subset_image_iff)\n  with fi[THEN spec, of B] show False\n    by (auto dest: finite_imageD intro: inj_setminus)\nnext\n  fix A\n  assume ?R\n  assume \"\\<forall>a\\<in>A. open a\" \"U \\<subseteq> \\<Union>A\"\n  then have \"U \\<inter> \\<Inter>(uminus`A) = {}\" \"\\<forall>a\\<in>uminus`A. closed a\"\n    by auto\n  with `?R` obtain B where \"B \\<subseteq> A\" \"finite (uminus`B)\" \"U \\<inter> \\<Inter>(uminus`B) = {}\"\n    by (metis subset_image_iff)\n  then show \"\\<exists>T\\<subseteq>A. finite T \\<and> U \\<subseteq> \\<Union>T\"\n    by  (auto intro!: exI[of _ B] inj_setminus dest: finite_imageD)\nqed\n\nlemma compact_imp_fip:\n  \"compact s \\<Longrightarrow> \\<forall>t \\<in> f. closed t \\<Longrightarrow> \\<forall>f'. finite f' \\<and> f' \\<subseteq> f \\<longrightarrow> (s \\<inter> (\\<Inter> f') \\<noteq> {}) \\<Longrightarrow>\n    s \\<inter> (\\<Inter> f) \\<noteq> {}\"\n  unfolding compact_fip by auto\n\nlemma compact_imp_fip_image:\n  assumes \"compact s\"\n    and P: \"\\<And>i. i \\<in> I \\<Longrightarrow> closed (f i)\"\n    and Q: \"\\<And>I'. finite I' \\<Longrightarrow> I' \\<subseteq> I \\<Longrightarrow> (s \\<inter> (\\<Inter>i\\<in>I'. f i) \\<noteq> {})\"\n  shows \"s \\<inter> (\\<Inter>i\\<in>I. f i) \\<noteq> {}\"\nproof -\n  note `compact s`\n  moreover from P have \"\\<forall>i \\<in> f ` I. closed i\" by blast\n  moreover have \"\\<forall>A. finite A \\<and> A \\<subseteq> f ` I \\<longrightarrow> (s \\<inter> (\\<Inter>A) \\<noteq> {})\"\n  proof (rule, rule, erule conjE)\n    fix A :: \"'a set set\"\n    assume \"finite A\"\n    moreover assume \"A \\<subseteq> f ` I\"\n    ultimately obtain B where \"B \\<subseteq> I\" and \"finite B\" and \"A = f ` B\"\n      using finite_subset_image [of A f I] by blast\n    with Q [of B] show \"s \\<inter> \\<Inter>A \\<noteq> {}\" by simp\n  qed\n  ultimately have \"s \\<inter> (\\<Inter>(f ` I)) \\<noteq> {}\" by (rule compact_imp_fip)\n  then show ?thesis by simp\nqed\n\nend\n\nlemma (in t2_space) compact_imp_closed:\n  assumes \"compact s\" shows \"closed s\"\nunfolding closed_def\nproof (rule openI)\n  fix y assume \"y \\<in> - s\"\n  let ?C = \"\\<Union>x\\<in>s. {u. open u \\<and> x \\<in> u \\<and> eventually (\\<lambda>y. y \\<notin> u) (nhds y)}\"\n  note `compact s`\n  moreover have \"\\<forall>u\\<in>?C. open u\" by simp\n  moreover have \"s \\<subseteq> \\<Union>?C\"\n  proof\n    fix x assume \"x \\<in> s\"\n    with `y \\<in> - s` have \"x \\<noteq> y\" by clarsimp\n    hence \"\\<exists>u v. open u \\<and> open v \\<and> x \\<in> u \\<and> y \\<in> v \\<and> u \\<inter> v = {}\"\n      by (rule hausdorff)\n    with `x \\<in> s` show \"x \\<in> \\<Union>?C\"\n      unfolding eventually_nhds by auto\n  qed\n  ultimately obtain D where \"D \\<subseteq> ?C\" and \"finite D\" and \"s \\<subseteq> \\<Union>D\"\n    by (rule compactE)\n  from `D \\<subseteq> ?C` have \"\\<forall>x\\<in>D. eventually (\\<lambda>y. y \\<notin> x) (nhds y)\" by auto\n  with `finite D` have \"eventually (\\<lambda>y. y \\<notin> \\<Union>D) (nhds y)\"\n    by (simp add: eventually_Ball_finite)\n  with `s \\<subseteq> \\<Union>D` have \"eventually (\\<lambda>y. y \\<notin> s) (nhds y)\"\n    by (auto elim!: eventually_mono [rotated])\n  thus \"\\<exists>t. open t \\<and> y \\<in> t \\<and> t \\<subseteq> - s\"\n    by (simp add: eventually_nhds subset_eq)\nqed\n\nlemma compact_continuous_image:\n  assumes f: \"continuous_on s f\" and s: \"compact s\"\n  shows \"compact (f ` s)\"\nproof (rule compactI)\n  fix C assume \"\\<forall>c\\<in>C. open c\" and cover: \"f`s \\<subseteq> \\<Union>C\"\n  with f have \"\\<forall>c\\<in>C. \\<exists>A. open A \\<and> A \\<inter> s = f -` c \\<inter> s\"\n    unfolding continuous_on_open_invariant by blast\n  then obtain A where A: \"\\<forall>c\\<in>C. open (A c) \\<and> A c \\<inter> s = f -` c \\<inter> s\"\n    unfolding bchoice_iff ..\n  with cover have \"\\<forall>c\\<in>C. open (A c)\" \"s \\<subseteq> (\\<Union>c\\<in>C. A c)\"\n    by (fastforce simp add: subset_eq set_eq_iff)+\n  from compactE_image[OF s this] obtain D where \"D \\<subseteq> C\" \"finite D\" \"s \\<subseteq> (\\<Union>c\\<in>D. A c)\" .\n  with A show \"\\<exists>D \\<subseteq> C. finite D \\<and> f`s \\<subseteq> \\<Union>D\"\n    by (intro exI[of _ D]) (fastforce simp add: subset_eq set_eq_iff)+\nqed\n\nlemma continuous_on_inv:\n  fixes f :: \"'a::topological_space \\<Rightarrow> 'b::t2_space\"\n  assumes \"continuous_on s f\"  \"compact s\"  \"\\<forall>x\\<in>s. g (f x) = x\"\n  shows \"continuous_on (f ` s) g\"\nunfolding continuous_on_topological\nproof (clarsimp simp add: assms(3))\n  fix x :: 'a and B :: \"'a set\"\n  assume \"x \\<in> s\" and \"open B\" and \"x \\<in> B\"\n  have 1: \"\\<forall>x\\<in>s. f x \\<in> f ` (s - B) \\<longleftrightarrow> x \\<in> s - B\"\n    using assms(3) by (auto, metis)\n  have \"continuous_on (s - B) f\"\n    using `continuous_on s f` Diff_subset\n    by (rule continuous_on_subset)\n  moreover have \"compact (s - B)\"\n    using `open B` and `compact s`\n    unfolding Diff_eq by (intro compact_inter_closed closed_Compl)\n  ultimately have \"compact (f ` (s - B))\"\n    by (rule compact_continuous_image)\n  hence \"closed (f ` (s - B))\"\n    by (rule compact_imp_closed)\n  hence \"open (- f ` (s - B))\"\n    by (rule open_Compl)\n  moreover have \"f x \\<in> - f ` (s - B)\"\n    using `x \\<in> s` and `x \\<in> B` by (simp add: 1)\n  moreover have \"\\<forall>y\\<in>s. f y \\<in> - f ` (s - B) \\<longrightarrow> y \\<in> B\"\n    by (simp add: 1)\n  ultimately show \"\\<exists>A. open A \\<and> f x \\<in> A \\<and> (\\<forall>y\\<in>s. f y \\<in> A \\<longrightarrow> y \\<in> B)\"\n    by fast\nqed\n\nlemma continuous_on_inv_into:\n  fixes f :: \"'a::topological_space \\<Rightarrow> 'b::t2_space\"\n  assumes s: \"continuous_on s f\" \"compact s\" and f: \"inj_on f s\"\n  shows \"continuous_on (f ` s) (the_inv_into s f)\"\n  by (rule continuous_on_inv[OF s]) (auto simp: the_inv_into_f_f[OF f])\n\nlemma (in linorder_topology) compact_attains_sup:\n  assumes \"compact S\" \"S \\<noteq> {}\"\n  shows \"\\<exists>s\\<in>S. \\<forall>t\\<in>S. t \\<le> s\"\nproof (rule classical)\n  assume \"\\<not> (\\<exists>s\\<in>S. \\<forall>t\\<in>S. t \\<le> s)\"\n  then obtain t where t: \"\\<forall>s\\<in>S. t s \\<in> S\" and \"\\<forall>s\\<in>S. s < t s\"\n    by (metis not_le)\n  then have \"\\<forall>s\\<in>S. open {..< t s}\" \"S \\<subseteq> (\\<Union>s\\<in>S. {..< t s})\"\n    by auto\n  with `compact S` obtain C where \"C \\<subseteq> S\" \"finite C\" and C: \"S \\<subseteq> (\\<Union>s\\<in>C. {..< t s})\"\n    by (erule compactE_image)\n  with `S \\<noteq> {}` have Max: \"Max (t`C) \\<in> t`C\" and \"\\<forall>s\\<in>t`C. s \\<le> Max (t`C)\"\n    by (auto intro!: Max_in)\n  with C have \"S \\<subseteq> {..< Max (t`C)}\"\n    by (auto intro: less_le_trans simp: subset_eq)\n  with t Max `C \\<subseteq> S` show ?thesis\n    by fastforce\nqed\n\nlemma (in linorder_topology) compact_attains_inf:\n  assumes \"compact S\" \"S \\<noteq> {}\"\n  shows \"\\<exists>s\\<in>S. \\<forall>t\\<in>S. s \\<le> t\"\nproof (rule classical)\n  assume \"\\<not> (\\<exists>s\\<in>S. \\<forall>t\\<in>S. s \\<le> t)\"\n  then obtain t where t: \"\\<forall>s\\<in>S. t s \\<in> S\" and \"\\<forall>s\\<in>S. t s < s\"\n    by (metis not_le)\n  then have \"\\<forall>s\\<in>S. open {t s <..}\" \"S \\<subseteq> (\\<Union>s\\<in>S. {t s <..})\"\n    by auto\n  with `compact S` obtain C where \"C \\<subseteq> S\" \"finite C\" and C: \"S \\<subseteq> (\\<Union>s\\<in>C. {t s <..})\"\n    by (erule compactE_image)\n  with `S \\<noteq> {}` have Min: \"Min (t`C) \\<in> t`C\" and \"\\<forall>s\\<in>t`C. Min (t`C) \\<le> s\"\n    by (auto intro!: Min_in)\n  with C have \"S \\<subseteq> {Min (t`C) <..}\"\n    by (auto intro: le_less_trans simp: subset_eq)\n  with t Min `C \\<subseteq> S` show ?thesis\n    by fastforce\nqed\n\nlemma continuous_attains_sup:\n  fixes f :: \"'a::topological_space \\<Rightarrow> 'b::linorder_topology\"\n  shows \"compact s \\<Longrightarrow> s \\<noteq> {} \\<Longrightarrow> continuous_on s f \\<Longrightarrow> (\\<exists>x\\<in>s. \\<forall>y\\<in>s.  f y \\<le> f x)\"\n  using compact_attains_sup[of \"f ` s\"] compact_continuous_image[of s f] by auto\n\nlemma continuous_attains_inf:\n  fixes f :: \"'a::topological_space \\<Rightarrow> 'b::linorder_topology\"\n  shows \"compact s \\<Longrightarrow> s \\<noteq> {} \\<Longrightarrow> continuous_on s f \\<Longrightarrow> (\\<exists>x\\<in>s. \\<forall>y\\<in>s. f x \\<le> f y)\"\n  using compact_attains_inf[of \"f ` s\"] compact_continuous_image[of s f] by auto\n\nsubsection {* Connectedness *}\n\ncontext topological_space\nbegin\n\ndefinition \"connected S \\<longleftrightarrow>\n  \\<not> (\\<exists>A B. open A \\<and> open B \\<and> S \\<subseteq> A \\<union> B \\<and> A \\<inter> B \\<inter> S = {} \\<and> A \\<inter> S \\<noteq> {} \\<and> B \\<inter> S \\<noteq> {})\"\n\nlemma connectedI:\n  \"(\\<And>A B. open A \\<Longrightarrow> open B \\<Longrightarrow> A \\<inter> U \\<noteq> {} \\<Longrightarrow> B \\<inter> U \\<noteq> {} \\<Longrightarrow> A \\<inter> B \\<inter> U = {} \\<Longrightarrow> U \\<subseteq> A \\<union> B \\<Longrightarrow> False)\n  \\<Longrightarrow> connected U\"\n  by (auto simp: connected_def)\n\nlemma connected_empty[simp]: \"connected {}\"\n  by (auto intro!: connectedI)\n\nlemma connectedD:\n  \"connected A \\<Longrightarrow> open U \\<Longrightarrow> open V \\<Longrightarrow> U \\<inter> V \\<inter> A = {} \\<Longrightarrow> A \\<subseteq> U \\<union> V \\<Longrightarrow> U \\<inter> A = {} \\<or> V \\<inter> A = {}\" \n  by (auto simp: connected_def)\n\nend\n\nlemma connected_iff_const:\n  fixes S :: \"'a::topological_space set\"\n  shows \"connected S \\<longleftrightarrow> (\\<forall>P::'a \\<Rightarrow> bool. continuous_on S P \\<longrightarrow> (\\<exists>c. \\<forall>s\\<in>S. P s = c))\"\nproof safe\n  fix P :: \"'a \\<Rightarrow> bool\" assume \"connected S\" \"continuous_on S P\"\n  then have \"\\<And>b. \\<exists>A. open A \\<and> A \\<inter> S = P -` {b} \\<inter> S\"\n    unfolding continuous_on_open_invariant by simp\n  from this[of True] this[of False]\n  obtain t f where \"open t\" \"open f\" and *: \"f \\<inter> S = P -` {False} \\<inter> S\" \"t \\<inter> S = P -` {True} \\<inter> S\"\n    by auto\n  then have \"t \\<inter> S = {} \\<or> f \\<inter> S = {}\"\n    by (intro connectedD[OF `connected S`])  auto\n  then show \"\\<exists>c. \\<forall>s\\<in>S. P s = c\"\n  proof (rule disjE)\n    assume \"t \\<inter> S = {}\" then show ?thesis\n      unfolding * by (intro exI[of _ False]) auto\n  next\n    assume \"f \\<inter> S = {}\" then show ?thesis\n      unfolding * by (intro exI[of _ True]) auto\n  qed\nnext\n  assume P: \"\\<forall>P::'a \\<Rightarrow> bool. continuous_on S P \\<longrightarrow> (\\<exists>c. \\<forall>s\\<in>S. P s = c)\"\n  show \"connected S\"\n  proof (rule connectedI)\n    fix A B assume *: \"open A\" \"open B\" \"A \\<inter> S \\<noteq> {}\" \"B \\<inter> S \\<noteq> {}\" \"A \\<inter> B \\<inter> S = {}\" \"S \\<subseteq> A \\<union> B\"\n    have \"continuous_on S (\\<lambda>x. x \\<in> A)\"\n      unfolding continuous_on_open_invariant\n    proof safe\n      fix C :: \"bool set\"\n      have \"C = UNIV \\<or> C = {True} \\<or> C = {False} \\<or> C = {}\"\n        using subset_UNIV[of C] unfolding UNIV_bool by auto\n      with * show \"\\<exists>T. open T \\<and> T \\<inter> S = (\\<lambda>x. x \\<in> A) -` C \\<inter> S\"\n        by (intro exI[of _ \"(if True \\<in> C then A else {}) \\<union> (if False \\<in> C then B else {})\"]) auto\n    qed\n    from P[rule_format, OF this] obtain c where \"\\<And>s. s \\<in> S \\<Longrightarrow> (s \\<in> A) = c\" by blast\n    with * show False\n      by (cases c) auto\n  qed\nqed\n\nlemma connectedD_const:\n  fixes P :: \"'a::topological_space \\<Rightarrow> bool\"\n  shows \"connected S \\<Longrightarrow> continuous_on S P \\<Longrightarrow> \\<exists>c. \\<forall>s\\<in>S. P s = c\"\n  unfolding connected_iff_const by auto\n\nlemma connectedI_const:\n  \"(\\<And>P::'a::topological_space \\<Rightarrow> bool. continuous_on S P \\<Longrightarrow> \\<exists>c. \\<forall>s\\<in>S. P s = c) \\<Longrightarrow> connected S\"\n  unfolding connected_iff_const by auto\n\nlemma connected_local_const:\n  assumes \"connected A\" \"a \\<in> A\" \"b \\<in> A\"\n  assumes *: \"\\<forall>a\\<in>A. eventually (\\<lambda>b. f a = f b) (at a within A)\"\n  shows \"f a = f b\"\nproof -\n  obtain S where S: \"\\<And>a. a \\<in> A \\<Longrightarrow> a \\<in> S a\" \"\\<And>a. a \\<in> A \\<Longrightarrow> open (S a)\"\n    \"\\<And>a x. a \\<in> A \\<Longrightarrow> x \\<in> S a \\<Longrightarrow> x \\<in> A \\<Longrightarrow> f a = f x\"\n    using * unfolding eventually_at_topological by metis\n\n  let ?P = \"\\<Union>b\\<in>{b\\<in>A. f a = f b}. S b\" and ?N = \"\\<Union>b\\<in>{b\\<in>A. f a \\<noteq> f b}. S b\"\n  have \"?P \\<inter> A = {} \\<or> ?N \\<inter> A = {}\"\n    using `connected A` S `a\\<in>A`\n    by (intro connectedD) (auto, metis)\n  then show \"f a = f b\"\n  proof\n    assume \"?N \\<inter> A = {}\"\n    then have \"\\<forall>x\\<in>A. f a = f x\"\n      using S(1) by auto\n    with `b\\<in>A` show ?thesis by auto\n  next\n    assume \"?P \\<inter> A = {}\" then show ?thesis\n      using `a \\<in> A` S(1)[of a] by auto\n  qed\nqed\n\nlemma (in linorder_topology) connectedD_interval:\n  assumes \"connected U\" and xy: \"x \\<in> U\" \"y \\<in> U\" and \"x \\<le> z\" \"z \\<le> y\"\n  shows \"z \\<in> U\"\nproof -\n  have eq: \"{..<z} \\<union> {z<..} = - {z}\"\n    by auto\n  { assume \"z \\<notin> U\" \"x < z\" \"z < y\"\n    with xy have \"\\<not> connected U\"\n      unfolding connected_def simp_thms\n      apply (rule_tac exI[of _ \"{..< z}\"])\n      apply (rule_tac exI[of _ \"{z <..}\"])\n      apply (auto simp add: eq)\n      done }\n  with assms show \"z \\<in> U\"\n    by (metis less_le)\nqed\n\nlemma connected_continuous_image:\n  assumes *: \"continuous_on s f\"\n  assumes \"connected s\"\n  shows \"connected (f ` s)\"\nproof (rule connectedI_const)\n  fix P :: \"'b \\<Rightarrow> bool\" assume \"continuous_on (f ` s) P\"\n  then have \"continuous_on s (P \\<circ> f)\"\n    by (rule continuous_on_compose[OF *])\n  from connectedD_const[OF `connected s` this] show \"\\<exists>c. \\<forall>s\\<in>f ` s. P s = c\"\n    by auto\nqed\n\nsection {* Connectedness *}\n\nclass linear_continuum_topology = linorder_topology + linear_continuum\nbegin\n\nlemma Inf_notin_open:\n  assumes A: \"open A\" and bnd: \"\\<forall>a\\<in>A. x < a\"\n  shows \"Inf A \\<notin> A\"\nproof\n  assume \"Inf A \\<in> A\"\n  then obtain b where \"b < Inf A\" \"{b <.. Inf A} \\<subseteq> A\"\n    using open_left[of A \"Inf A\" x] assms by auto\n  with dense[of b \"Inf A\"] obtain c where \"c < Inf A\" \"c \\<in> A\"\n    by (auto simp: subset_eq)\n  then show False\n    using cInf_lower[OF `c \\<in> A`] bnd by (metis not_le less_imp_le bdd_belowI)\nqed\n\nlemma Sup_notin_open:\n  assumes A: \"open A\" and bnd: \"\\<forall>a\\<in>A. a < x\"\n  shows \"Sup A \\<notin> A\"\nproof\n  assume \"Sup A \\<in> A\"\n  then obtain b where \"Sup A < b\" \"{Sup A ..< b} \\<subseteq> A\"\n    using open_right[of A \"Sup A\" x] assms by auto\n  with dense[of \"Sup A\" b] obtain c where \"Sup A < c\" \"c \\<in> A\"\n    by (auto simp: subset_eq)\n  then show False\n    using cSup_upper[OF `c \\<in> A`] bnd by (metis less_imp_le not_le bdd_aboveI)\nqed\n\nend\n\ninstance linear_continuum_topology \\<subseteq> perfect_space\nproof\n  fix x :: 'a\n  obtain y where \"x < y \\<or> y < x\"\n    using ex_gt_or_lt [of x] ..\n  with Inf_notin_open[of \"{x}\" y] Sup_notin_open[of \"{x}\" y]\n  show \"\\<not> open {x}\"\n    by auto\nqed\n\nlemma connectedI_interval:\n  fixes U :: \"'a :: linear_continuum_topology set\"\n  assumes *: \"\\<And>x y z. x \\<in> U \\<Longrightarrow> y \\<in> U \\<Longrightarrow> x \\<le> z \\<Longrightarrow> z \\<le> y \\<Longrightarrow> z \\<in> U\"\n  shows \"connected U\"\nproof (rule connectedI)\n  { fix A B assume \"open A\" \"open B\" \"A \\<inter> B \\<inter> U = {}\" \"U \\<subseteq> A \\<union> B\"\n    fix x y assume \"x < y\" \"x \\<in> A\" \"y \\<in> B\" \"x \\<in> U\" \"y \\<in> U\"\n\n    let ?z = \"Inf (B \\<inter> {x <..})\"\n\n    have \"x \\<le> ?z\" \"?z \\<le> y\"\n      using `y \\<in> B` `x < y` by (auto intro: cInf_lower cInf_greatest)\n    with `x \\<in> U` `y \\<in> U` have \"?z \\<in> U\"\n      by (rule *)\n    moreover have \"?z \\<notin> B \\<inter> {x <..}\"\n      using `open B` by (intro Inf_notin_open) auto\n    ultimately have \"?z \\<in> A\"\n      using `x \\<le> ?z` `A \\<inter> B \\<inter> U = {}` `x \\<in> A` `U \\<subseteq> A \\<union> B` by auto\n\n    { assume \"?z < y\"\n      obtain a where \"?z < a\" \"{?z ..< a} \\<subseteq> A\"\n        using open_right[OF `open A` `?z \\<in> A` `?z < y`] by auto\n      moreover obtain b where \"b \\<in> B\" \"x < b\" \"b < min a y\"\n        using cInf_less_iff[of \"B \\<inter> {x <..}\" \"min a y\"] `?z < a` `?z < y` `x < y` `y \\<in> B`\n        by (auto intro: less_imp_le)\n      moreover have \"?z \\<le> b\"\n        using `b \\<in> B` `x < b`\n        by (intro cInf_lower) auto\n      moreover have \"b \\<in> U\"\n        using `x \\<le> ?z` `?z \\<le> b` `b < min a y`\n        by (intro *[OF `x \\<in> U` `y \\<in> U`]) (auto simp: less_imp_le)\n      ultimately have \"\\<exists>b\\<in>B. b \\<in> A \\<and> b \\<in> U\"\n        by (intro bexI[of _ b]) auto }\n    then have False\n      using `?z \\<le> y` `?z \\<in> A` `y \\<in> B` `y \\<in> U` `A \\<inter> B \\<inter> U = {}` unfolding le_less by blast }\n  note not_disjoint = this\n\n  fix A B assume AB: \"open A\" \"open B\" \"U \\<subseteq> A \\<union> B\" \"A \\<inter> B \\<inter> U = {}\"\n  moreover assume \"A \\<inter> U \\<noteq> {}\" then obtain x where x: \"x \\<in> U\" \"x \\<in> A\" by auto\n  moreover assume \"B \\<inter> U \\<noteq> {}\" then obtain y where y: \"y \\<in> U\" \"y \\<in> B\" by auto\n  moreover note not_disjoint[of B A y x] not_disjoint[of A B x y]\n  ultimately show False by (cases x y rule: linorder_cases) auto\nqed\n\nlemma connected_iff_interval:\n  fixes U :: \"'a :: linear_continuum_topology set\"\n  shows \"connected U \\<longleftrightarrow> (\\<forall>x\\<in>U. \\<forall>y\\<in>U. \\<forall>z. x \\<le> z \\<longrightarrow> z \\<le> y \\<longrightarrow> z \\<in> U)\"\n  by (auto intro: connectedI_interval dest: connectedD_interval)\n\nlemma connected_UNIV[simp]: \"connected (UNIV::'a::linear_continuum_topology set)\"\n  unfolding connected_iff_interval by auto\n\nlemma connected_Ioi[simp]: \"connected {a::'a::linear_continuum_topology <..}\"\n  unfolding connected_iff_interval by auto\n\nlemma connected_Ici[simp]: \"connected {a::'a::linear_continuum_topology ..}\"\n  unfolding connected_iff_interval by auto\n\nlemma connected_Iio[simp]: \"connected {..< a::'a::linear_continuum_topology}\"\n  unfolding connected_iff_interval by auto\n\nlemma connected_Iic[simp]: \"connected {.. a::'a::linear_continuum_topology}\"\n  unfolding connected_iff_interval by auto\n\nlemma connected_Ioo[simp]: \"connected {a <..< b::'a::linear_continuum_topology}\"\n  unfolding connected_iff_interval by auto\n\nlemma connected_Ioc[simp]: \"connected {a <.. b::'a::linear_continuum_topology}\"\n  unfolding connected_iff_interval by auto\n\nlemma connected_Ico[simp]: \"connected {a ..< b::'a::linear_continuum_topology}\"\n  unfolding connected_iff_interval by auto\n\nlemma connected_Icc[simp]: \"connected {a .. b::'a::linear_continuum_topology}\"\n  unfolding connected_iff_interval by auto\n\nlemma connected_contains_Ioo: \n  fixes A :: \"'a :: linorder_topology set\"\n  assumes A: \"connected A\" \"a \\<in> A\" \"b \\<in> A\" shows \"{a <..< b} \\<subseteq> A\"\n  using connectedD_interval[OF A] by (simp add: subset_eq Ball_def less_imp_le)\n\nsubsection {* Intermediate Value Theorem *}\n\nlemma IVT':\n  fixes f :: \"'a :: linear_continuum_topology \\<Rightarrow> 'b :: linorder_topology\"\n  assumes y: \"f a \\<le> y\" \"y \\<le> f b\" \"a \\<le> b\"\n  assumes *: \"continuous_on {a .. b} f\"\n  shows \"\\<exists>x. a \\<le> x \\<and> x \\<le> b \\<and> f x = y\"\nproof -\n  have \"connected {a..b}\"\n    unfolding connected_iff_interval by auto\n  from connected_continuous_image[OF * this, THEN connectedD_interval, of \"f a\" \"f b\" y] y\n  show ?thesis\n    by (auto simp add: atLeastAtMost_def atLeast_def atMost_def)\nqed\n\nlemma IVT2':\n  fixes f :: \"'a :: linear_continuum_topology \\<Rightarrow> 'b :: linorder_topology\"\n  assumes y: \"f b \\<le> y\" \"y \\<le> f a\" \"a \\<le> b\"\n  assumes *: \"continuous_on {a .. b} f\"\n  shows \"\\<exists>x. a \\<le> x \\<and> x \\<le> b \\<and> f x = y\"\nproof -\n  have \"connected {a..b}\"\n    unfolding connected_iff_interval by auto\n  from connected_continuous_image[OF * this, THEN connectedD_interval, of \"f b\" \"f a\" y] y\n  show ?thesis\n    by (auto simp add: atLeastAtMost_def atLeast_def atMost_def)\nqed\n\nlemma IVT:\n  fixes f :: \"'a :: linear_continuum_topology \\<Rightarrow> 'b :: linorder_topology\"\n  shows \"f a \\<le> y \\<Longrightarrow> y \\<le> f b \\<Longrightarrow> a \\<le> b \\<Longrightarrow> (\\<forall>x. a \\<le> x \\<and> x \\<le> b \\<longrightarrow> isCont f x) \\<Longrightarrow> \\<exists>x. a \\<le> x \\<and> x \\<le> b \\<and> f x = y\"\n  by (rule IVT') (auto intro: continuous_at_imp_continuous_on)\n\nlemma IVT2:\n  fixes f :: \"'a :: linear_continuum_topology \\<Rightarrow> 'b :: linorder_topology\"\n  shows \"f b \\<le> y \\<Longrightarrow> y \\<le> f a \\<Longrightarrow> a \\<le> b \\<Longrightarrow> (\\<forall>x. a \\<le> x \\<and> x \\<le> b \\<longrightarrow> isCont f x) \\<Longrightarrow> \\<exists>x. a \\<le> x \\<and> x \\<le> b \\<and> f x = y\"\n  by (rule IVT2') (auto intro: continuous_at_imp_continuous_on)\n\nlemma continuous_inj_imp_mono:\n  fixes f :: \"'a::linear_continuum_topology \\<Rightarrow> 'b :: linorder_topology\"\n  assumes x: \"a < x\" \"x < b\"\n  assumes cont: \"continuous_on {a..b} f\"\n  assumes inj: \"inj_on f {a..b}\"\n  shows \"(f a < f x \\<and> f x < f b) \\<or> (f b < f x \\<and> f x < f a)\"\nproof -\n  note I = inj_on_iff[OF inj]\n  { assume \"f x < f a\" \"f x < f b\"\n    then obtain s t where \"x \\<le> s\" \"s \\<le> b\" \"a \\<le> t\" \"t \\<le> x\" \"f s = f t\" \"f x < f s\"\n      using IVT'[of f x \"min (f a) (f b)\" b] IVT2'[of f x \"min (f a) (f b)\" a] x\n      by (auto simp: continuous_on_subset[OF cont] less_imp_le)\n    with x I have False by auto }\n  moreover\n  { assume \"f a < f x\" \"f b < f x\"\n    then obtain s t where \"x \\<le> s\" \"s \\<le> b\" \"a \\<le> t\" \"t \\<le> x\" \"f s = f t\" \"f s < f x\"\n      using IVT'[of f a \"max (f a) (f b)\" x] IVT2'[of f b \"max (f a) (f b)\" x] x\n      by (auto simp: continuous_on_subset[OF cont] less_imp_le)\n    with x I have False by auto }\n  ultimately show ?thesis\n    using I[of a x] I[of x b] x less_trans[OF x] by (auto simp add: le_less less_imp_neq neq_iff)\nqed\n\nsubsection {* Setup @{typ \"'a filter\"} for lifting and transfer *}\n\ncontext begin interpretation lifting_syntax .\n\ndefinition rel_filter :: \"('a \\<Rightarrow> 'b \\<Rightarrow> bool) \\<Rightarrow> 'a filter \\<Rightarrow> 'b filter \\<Rightarrow> bool\"\nwhere \"rel_filter R F G = ((R ===> op =) ===> op =) (Rep_filter F) (Rep_filter G)\"\n\nlemma rel_filter_eventually:\n  \"rel_filter R F G \\<longleftrightarrow> \n  ((R ===> op =) ===> op =) (\\<lambda>P. eventually P F) (\\<lambda>P. eventually P G)\"\nby(simp add: rel_filter_def eventually_def)\n\nlemma filtermap_id [simp, id_simps]: \"filtermap id = id\"\nby(simp add: fun_eq_iff id_def filtermap_ident)\n\nlemma filtermap_id' [simp]: \"filtermap (\\<lambda>x. x) = (\\<lambda>F. F)\"\nusing filtermap_id unfolding id_def .\n\nlemma Quotient_filter [quot_map]:\n  assumes Q: \"Quotient R Abs Rep T\"\n  shows \"Quotient (rel_filter R) (filtermap Abs) (filtermap Rep) (rel_filter T)\"\nunfolding Quotient_alt_def\nproof(intro conjI strip)\n  from Q have *: \"\\<And>x y. T x y \\<Longrightarrow> Abs x = y\"\n    unfolding Quotient_alt_def by blast\n\n  fix F G\n  assume \"rel_filter T F G\"\n  thus \"filtermap Abs F = G\" unfolding filter_eq_iff\n    by(auto simp add: eventually_filtermap rel_filter_eventually * rel_funI del: iffI elim!: rel_funD)\nnext\n  from Q have *: \"\\<And>x. T (Rep x) x\" unfolding Quotient_alt_def by blast\n\n  fix F\n  show \"rel_filter T (filtermap Rep F) F\" \n    by(auto elim: rel_funD intro: * intro!: ext arg_cong[where f=\"\\<lambda>P. eventually P F\"] rel_funI\n            del: iffI simp add: eventually_filtermap rel_filter_eventually)\nqed(auto simp add: map_fun_def o_def eventually_filtermap filter_eq_iff fun_eq_iff rel_filter_eventually\n         fun_quotient[OF fun_quotient[OF Q identity_quotient] identity_quotient, unfolded Quotient_alt_def])\n\nlemma eventually_parametric [transfer_rule]:\n  \"((A ===> op =) ===> rel_filter A ===> op =) eventually eventually\"\nby(simp add: rel_fun_def rel_filter_eventually)\n\nlemma rel_filter_eq [relator_eq]: \"rel_filter op = = op =\"\nby(auto simp add: rel_filter_eventually rel_fun_eq fun_eq_iff filter_eq_iff)\n\nlemma rel_filter_mono [relator_mono]:\n  \"A \\<le> B \\<Longrightarrow> rel_filter A \\<le> rel_filter B\"\nunfolding rel_filter_eventually[abs_def]\nby(rule le_funI)+(intro fun_mono fun_mono[THEN le_funD, THEN le_funD] order.refl)\n\nlemma rel_filter_conversep [simp]: \"rel_filter A\\<inverse>\\<inverse> = (rel_filter A)\\<inverse>\\<inverse>\"\nby(auto simp add: rel_filter_eventually fun_eq_iff rel_fun_def)\n\nlemma is_filter_parametric_aux:\n  assumes \"is_filter F\"\n  assumes [transfer_rule]: \"bi_total A\" \"bi_unique A\"\n  and [transfer_rule]: \"((A ===> op =) ===> op =) F G\"\n  shows \"is_filter G\"\nproof -\n  interpret is_filter F by fact\n  show ?thesis\n  proof\n    have \"F (\\<lambda>_. True) = G (\\<lambda>x. True)\" by transfer_prover\n    thus \"G (\\<lambda>x. True)\" by(simp add: True)\n  next\n    fix P' Q'\n    assume \"G P'\" \"G Q'\"\n    moreover\n    from bi_total_fun[OF `bi_unique A` bi_total_eq, unfolded bi_total_def]\n    obtain P Q where [transfer_rule]: \"(A ===> op =) P P'\" \"(A ===> op =) Q Q'\" by blast\n    have \"F P = G P'\" \"F Q = G Q'\" by transfer_prover+\n    ultimately have \"F (\\<lambda>x. P x \\<and> Q x)\" by(simp add: conj)\n    moreover have \"F (\\<lambda>x. P x \\<and> Q x) = G (\\<lambda>x. P' x \\<and> Q' x)\" by transfer_prover\n    ultimately show \"G (\\<lambda>x. P' x \\<and> Q' x)\" by simp\n  next\n    fix P' Q'\n    assume \"\\<forall>x. P' x \\<longrightarrow> Q' x\" \"G P'\"\n    moreover\n    from bi_total_fun[OF `bi_unique A` bi_total_eq, unfolded bi_total_def]\n    obtain P Q where [transfer_rule]: \"(A ===> op =) P P'\" \"(A ===> op =) Q Q'\" by blast\n    have \"F P = G P'\" by transfer_prover\n    moreover have \"(\\<forall>x. P x \\<longrightarrow> Q x) \\<longleftrightarrow> (\\<forall>x. P' x \\<longrightarrow> Q' x)\" by transfer_prover\n    ultimately have \"F Q\" by(simp add: mono)\n    moreover have \"F Q = G Q'\" by transfer_prover\n    ultimately show \"G Q'\" by simp\n  qed\nqed\n\nlemma is_filter_parametric [transfer_rule]:\n  \"\\<lbrakk> bi_total A; bi_unique A \\<rbrakk>\n  \\<Longrightarrow> (((A ===> op =) ===> op =) ===> op =) is_filter is_filter\"\napply(rule rel_funI)\napply(rule iffI)\n apply(erule (3) is_filter_parametric_aux)\napply(erule is_filter_parametric_aux[where A=\"conversep A\"])\napply(auto simp add: rel_fun_def)\ndone\n\nlemma left_total_rel_filter [transfer_rule]:\n  assumes [transfer_rule]: \"bi_total A\" \"bi_unique A\"\n  shows \"left_total (rel_filter A)\"\nproof(rule left_totalI)\n  fix F :: \"'a filter\"\n  from bi_total_fun[OF bi_unique_fun[OF `bi_total A` bi_unique_eq] bi_total_eq]\n  obtain G where [transfer_rule]: \"((A ===> op =) ===> op =) (\\<lambda>P. eventually P F) G\" \n    unfolding  bi_total_def by blast\n  moreover have \"is_filter (\\<lambda>P. eventually P F) \\<longleftrightarrow> is_filter G\" by transfer_prover\n  hence \"is_filter G\" by(simp add: eventually_def is_filter_Rep_filter)\n  ultimately have \"rel_filter A F (Abs_filter G)\"\n    by(simp add: rel_filter_eventually eventually_Abs_filter)\n  thus \"\\<exists>G. rel_filter A F G\" ..\nqed\n\nlemma right_total_rel_filter [transfer_rule]:\n  \"\\<lbrakk> bi_total A; bi_unique A \\<rbrakk> \\<Longrightarrow> right_total (rel_filter A)\"\nusing left_total_rel_filter[of \"A\\<inverse>\\<inverse>\"] by simp\n\nlemma bi_total_rel_filter [transfer_rule]:\n  assumes \"bi_total A\" \"bi_unique A\"\n  shows \"bi_total (rel_filter A)\"\nunfolding bi_total_alt_def using assms\nby(simp add: left_total_rel_filter right_total_rel_filter)\n\nlemma left_unique_rel_filter [transfer_rule]:\n  assumes \"left_unique A\"\n  shows \"left_unique (rel_filter A)\"\nproof(rule left_uniqueI)\n  fix F F' G\n  assume [transfer_rule]: \"rel_filter A F G\" \"rel_filter A F' G\"\n  show \"F = F'\"\n    unfolding filter_eq_iff\n  proof\n    fix P :: \"'a \\<Rightarrow> bool\"\n    obtain P' where [transfer_rule]: \"(A ===> op =) P P'\"\n      using left_total_fun[OF assms left_total_eq] unfolding left_total_def by blast\n    have \"eventually P F = eventually P' G\" \n      and \"eventually P F' = eventually P' G\" by transfer_prover+\n    thus \"eventually P F = eventually P F'\" by simp\n  qed\nqed\n\nlemma right_unique_rel_filter [transfer_rule]:\n  \"right_unique A \\<Longrightarrow> right_unique (rel_filter A)\"\nusing left_unique_rel_filter[of \"A\\<inverse>\\<inverse>\"] by simp\n\nlemma bi_unique_rel_filter [transfer_rule]:\n  \"bi_unique A \\<Longrightarrow> bi_unique (rel_filter A)\"\nby(simp add: bi_unique_alt_def left_unique_rel_filter right_unique_rel_filter)\n\nlemma top_filter_parametric [transfer_rule]:\n  \"bi_total A \\<Longrightarrow> (rel_filter A) top top\"\nby(simp add: rel_filter_eventually All_transfer)\n\nlemma bot_filter_parametric [transfer_rule]: \"(rel_filter A) bot bot\"\nby(simp add: rel_filter_eventually rel_fun_def)\n\nlemma sup_filter_parametric [transfer_rule]:\n  \"(rel_filter A ===> rel_filter A ===> rel_filter A) sup sup\"\nby(fastforce simp add: rel_filter_eventually[abs_def] eventually_sup dest: rel_funD)\n\nlemma Sup_filter_parametric [transfer_rule]:\n  \"(rel_set (rel_filter A) ===> rel_filter A) Sup Sup\"\nproof(rule rel_funI)\n  fix S T\n  assume [transfer_rule]: \"rel_set (rel_filter A) S T\"\n  show \"rel_filter A (Sup S) (Sup T)\"\n    by(simp add: rel_filter_eventually eventually_Sup) transfer_prover\nqed\n\nlemma principal_parametric [transfer_rule]:\n  \"(rel_set A ===> rel_filter A) principal principal\"\nproof(rule rel_funI)\n  fix S S'\n  assume [transfer_rule]: \"rel_set A S S'\"\n  show \"rel_filter A (principal S) (principal S')\"\n    by(simp add: rel_filter_eventually eventually_principal) transfer_prover\nqed\n\ncontext\n  fixes A :: \"'a \\<Rightarrow> 'b \\<Rightarrow> bool\"\n  assumes [transfer_rule]: \"bi_unique A\" \nbegin\n\nlemma le_filter_parametric [transfer_rule]:\n  \"(rel_filter A ===> rel_filter A ===> op =) op \\<le> op \\<le>\"\nunfolding le_filter_def[abs_def] by transfer_prover\n\nlemma less_filter_parametric [transfer_rule]:\n  \"(rel_filter A ===> rel_filter A ===> op =) op < op <\"\nunfolding less_filter_def[abs_def] by transfer_prover\n\ncontext\n  assumes [transfer_rule]: \"bi_total A\"\nbegin\n\nlemma Inf_filter_parametric [transfer_rule]:\n  \"(rel_set (rel_filter A) ===> rel_filter A) Inf Inf\"\nunfolding Inf_filter_def[abs_def] by transfer_prover\n\nlemma inf_filter_parametric [transfer_rule]:\n  \"(rel_filter A ===> rel_filter A ===> rel_filter A) inf inf\"\nproof(intro rel_funI)+\n  fix F F' G G'\n  assume [transfer_rule]: \"rel_filter A F F'\" \"rel_filter A G G'\"\n  have \"rel_filter A (Inf {F, G}) (Inf {F', G'})\" by transfer_prover\n  thus \"rel_filter A (inf F G) (inf F' G')\" by simp\nqed\n\nend\n\nend\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/Topological_Spaces.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916099737806, "lm_q2_score": 0.8577681086260461, "lm_q1q2_score": 0.7405897882908067}}
{"text": "(*    Title:              SATSolver/CNF.thy\n      Author:             Filip Maric\n      Maintainer:         Filip Maric <filip at matf.bg.ac.yu>\n*)\n\nheader {* CNF *}\ntheory CNF\nimports MoreList\nbegin\ntext{* Theory describing formulae in Conjunctive Normal Form. *}\n\n\n(********************************************************************)\nsubsection{* Syntax *}\n(********************************************************************)\n\n(*------------------------------------------------------------------*)\nsubsubsection{* Basic datatypes *}\ntype_synonym Variable  = nat\ndatatype Literal = Pos Variable | Neg Variable\ntype_synonym Clause = \"Literal list\"\ntype_synonym Formula = \"Clause list\"\n\ntext{* Notice that instead of set or multisets, lists are used in\ndefinitions of clauses and formulae. This is done because SAT solver\nimplementation usually use list-like data structures for representing\nthese datatypes. *}\n\n(*------------------------------------------------------------------*)\nsubsubsection{* Membership *}\n\ntext{* Check if the literal is member of a clause, clause is a member \n  of a formula or the literal is a member of a formula *}\nconsts member  :: \"'a \\<Rightarrow> 'b \\<Rightarrow> bool\" (infixl \"el\" 55)\n\ndefs (overloaded)\nliteralElClause_def [simp]: \"((literal::Literal) el (clause::Clause)) == literal \\<in> set clause\"\ndefs (overloaded)\nclauseElFormula_def [simp]: \"((clause::Clause) el (formula::Formula)) == clause \\<in> set formula\"\n\noverloading\n  el_literal \\<equiv> \"op el :: Literal \\<Rightarrow> Formula \\<Rightarrow> bool\"\nbegin\n\nprimrec el_literal where\n\"(literal::Literal) el ([]::Formula) = False\" |\n\"((literal::Literal) el ((clause # formula)::Formula)) = ((literal el clause) \\<or> (literal el formula))\"\n\nend\n\nlemma literalElFormulaCharacterization:\n  fixes literal :: Literal and formula :: Formula\n  shows \"(literal el formula) = (\\<exists> (clause::Clause). clause el formula \\<and> literal el clause)\"\nby (induct formula) auto\n\n\n(*------------------------------------------------------------------*)\nsubsubsection{* Variables *}\n\ntext{* The variable of a given literal *}\nprimrec \nvar      :: \"Literal \\<Rightarrow> Variable\"\nwhere \n  \"var (Pos v) = v\"\n| \"var (Neg v) = v\"\n\ntext{* Set of variables of a given clause, formula or valuation *}\nprimrec\nvarsClause :: \"(Literal list) \\<Rightarrow> (Variable set)\"\nwhere\n  \"varsClause [] = {}\"\n| \"varsClause (literal # list) = {var literal} \\<union> (varsClause list)\"\n\nprimrec\nvarsFormula :: \"Formula \\<Rightarrow> (Variable set)\"\nwhere\n  \"varsFormula [] = {}\"\n| \"varsFormula (clause # formula) = (varsClause clause) \\<union> (varsFormula formula)\"\n\nconsts vars           :: \"'a \\<Rightarrow> Variable set\"\ndefs (overloaded)\nvars_def_clause  [simp]: \"vars (clause::Clause) == varsClause clause\"\nvars_def_formula [simp]: \"vars (formula::Formula) == varsFormula formula\"\nvars_def_set     [simp]: \"vars (s::Literal set) == {vbl. \\<exists> l. l \\<in> s \\<and> var l = vbl}\"\n\n\nlemma clauseContainsItsLiteralsVariable: \n  fixes literal :: Literal and clause :: Clause\n  assumes \"literal el clause\"\n  shows \"var literal \\<in> vars clause\"\nusing assms\nby (induct clause) auto\n\nlemma formulaContainsItsLiteralsVariable:\n  fixes literal :: Literal and formula::Formula\n  assumes \"literal el formula\" \n  shows \"var literal \\<in> vars formula\"\nusing assms\nproof (induct formula)\n  case Nil\n  thus ?case \n    by simp\nnext\n  case (Cons clause formula)\n  thus ?case\n  proof (cases \"literal el clause\")\n    case True\n    with clauseContainsItsLiteralsVariable\n    have \"var literal \\<in> vars clause\" \n      by simp\n    thus ?thesis \n      by simp\n  next\n    case False\n    with Cons\n    show ?thesis \n      by simp\n  qed\nqed\n\nlemma formulaContainsItsClausesVariables:\n  fixes clause :: Clause and formula :: Formula\n  assumes \"clause el formula\"\n  shows \"vars clause \\<subseteq> vars formula\"\nusing assms\nby (induct formula) auto\n\nlemma varsAppendFormulae:\n  fixes formula1 :: Formula and formula2 :: Formula\n  shows \"vars (formula1 @ formula2) = vars formula1 \\<union> vars formula2\"\nby (induct formula1) auto\n\nlemma varsAppendClauses:\n  fixes clause1 :: Clause and clause2 :: Clause\n  shows \"vars (clause1 @ clause2) = vars clause1 \\<union> vars clause2\"\nby (induct clause1) auto\n\nlemma varsRemoveLiteral:\n  fixes literal :: Literal and clause :: Clause\n  shows \"vars (removeAll literal clause) \\<subseteq> vars clause\"\nby (induct clause) auto\n\nlemma varsRemoveLiteralSuperset:\n  fixes literal :: Literal and clause :: Clause\n  shows \"vars clause - {var literal}  \\<subseteq> vars (removeAll literal clause)\"\nby (induct clause) auto\n\nlemma varsRemoveAllClause:\n  fixes clause :: Clause and formula :: Formula\n  shows \"vars (removeAll clause formula) \\<subseteq> vars formula\"\nby (induct formula) auto\n\nlemma varsRemoveAllClauseSuperset:\n  fixes clause :: Clause and formula :: Formula\n  shows \"vars formula - vars clause \\<subseteq> vars (removeAll clause formula)\"\nby (induct formula) auto\n\nlemma varInClauseVars:\n  fixes variable :: Variable and clause :: Clause\n  shows \"variable \\<in> vars clause = (\\<exists> literal. literal el clause \\<and> var literal = variable)\"\nby (induct clause) auto\n\nlemma varInFormulaVars: \n  fixes variable :: Variable and formula :: Formula\n  shows \"variable \\<in> vars formula = (\\<exists> literal. literal el formula \\<and> var literal = variable)\" (is \"?lhs formula = ?rhs formula\")\nproof (induct formula)\n  case Nil\n  show ?case \n    by simp\nnext\n  case (Cons clause formula)\n  show ?case\n  proof\n    assume P: \"?lhs (clause # formula)\"\n    thus \"?rhs (clause # formula)\"\n    proof (cases \"variable \\<in> vars clause\")\n      case True\n      with varInClauseVars \n      have \"\\<exists> literal. literal el clause \\<and> var literal = variable\" \n        by simp\n      thus ?thesis \n        by auto\n    next\n      case False\n      with P \n      have \"variable \\<in> vars formula\" \n        by simp\n      with Cons\n      show ?thesis \n        by auto\n    qed\n  next\n    assume \"?rhs (clause # formula)\"\n    then obtain l \n      where lEl: \"l el clause # formula\" and varL:\"var l = variable\" \n      by auto\n    from lEl formulaContainsItsLiteralsVariable [of \"l\" \"clause # formula\"] \n    have \"var l \\<in> vars (clause # formula)\" \n      by auto\n    with varL \n    show \"?lhs (clause # formula)\" \n      by simp\n  qed\nqed\n\nlemma varsSubsetFormula:\n  fixes F :: Formula and F' :: Formula\n  assumes \"\\<forall> c::Clause. c el F \\<longrightarrow> c el F'\"\n  shows \"vars F \\<subseteq> vars F'\"\nusing assms\nproof (induct F)\n  case Nil\n  thus ?case\n    by simp\nnext\n  case (Cons c' F'')\n  thus ?case\n    using formulaContainsItsClausesVariables[of \"c'\" \"F'\"]\n    by simp\nqed\n\nlemma varsClauseVarsSet:\nfixes \n  clause :: Clause\nshows\n  \"vars clause = vars (set clause)\"\nby (induct clause) auto\n\n\n(*------------------------------------------------------------------*)\nsubsubsection{* Opposite literals *}\n\nprimrec\nopposite :: \"Literal \\<Rightarrow> Literal\"\nwhere\n  \"opposite (Pos v) = (Neg v)\"\n| \"opposite (Neg v) = (Pos v)\"\n\nlemma oppositeIdempotency [simp]:\n  fixes literal::Literal\n  shows \"opposite (opposite literal) = literal\"\nby (induct literal) auto\n\nlemma oppositeSymmetry [simp]:\n  fixes literal1::Literal and literal2::Literal\n  shows \"(opposite literal1 = literal2) = (opposite literal2 = literal1)\"\nby auto\n\nlemma oppositeUniqueness [simp]:\n  fixes literal1::Literal and literal2::Literal\n  shows \"(opposite literal1 = opposite literal2) = (literal1 = literal2)\"\nproof\n  assume \"opposite literal1 = opposite literal2\"\n  hence \"opposite (opposite literal1) = opposite (opposite literal2)\" \n    by simp\n  thus \"literal1 = literal2\" \n    by simp \nqed simp\n\nlemma oppositeIsDifferentFromLiteral [simp]:\n  fixes literal::Literal\n  shows \"opposite literal \\<noteq> literal\"\nby (induct literal) auto\n\nlemma oppositeLiteralsHaveSameVariable [simp]:\n  fixes literal::Literal\n  shows \"var (opposite literal) = var literal\"\nby (induct literal) auto\n\nlemma literalsWithSameVariableAreEqualOrOpposite:\n  fixes literal1::Literal and literal2::Literal\n  shows \"(var literal1 = var literal2) = (literal1 = literal2 \\<or> opposite literal1 = literal2)\" (is \"?lhs = ?rhs\")\nproof\n  assume ?lhs\n  show ?rhs\n  proof (cases literal1)\n    case \"Pos\"\n    note Pos1 = this\n    show ?thesis\n    proof (cases literal2)\n      case \"Pos\"\n      with `?lhs` Pos1 show ?thesis \n        by simp\n    next\n      case \"Neg\"\n      with `?lhs` Pos1 show ?thesis \n        by simp\n    qed\n  next\n    case \"Neg\"\n    note Neg1 = this\n    show ?thesis\n    proof (cases literal2)\n      case \"Pos\"\n      with `?lhs` Neg1 show ?thesis \n        by simp\n    next\n      case \"Neg\"\n      with `?lhs` Neg1 show ?thesis \n        by simp\n    qed\n  qed\nnext\n  assume ?rhs\n  thus ?lhs \n    by auto\nqed\n\ntext{* The list of literals obtained by negating all literals of a\nliteral list (clause, valuation). Notice that this is not a negation \nof a clause, because the negation of a clause is a conjunction and \nnot a disjunction. *}\ndefinition\noppositeLiteralList :: \"Literal list \\<Rightarrow> Literal list\"\nwhere\n\"oppositeLiteralList clause == map opposite clause\"\n\nlemma literalElListIffOppositeLiteralElOppositeLiteralList: \n  fixes literal :: Literal and literalList :: \"Literal list\"\n  shows \"literal el literalList = (opposite literal) el (oppositeLiteralList literalList)\"\nunfolding oppositeLiteralList_def\nproof (induct literalList)\n  case Nil\n  thus ?case\n    by simp\nnext\n  case (Cons l literalLlist')\n  show ?case\n  proof (cases \"l = literal\")\n    case True\n    thus ?thesis\n      by simp\n  next\n    case False\n    thus ?thesis\n      by auto\n  qed\nqed\n\nlemma oppositeLiteralListIdempotency [simp]: \n  fixes literalList :: \"Literal list\"\n  shows \"oppositeLiteralList (oppositeLiteralList literalList) = literalList\"\nunfolding oppositeLiteralList_def\nby (induct literalList) auto\n\nlemma oppositeLiteralListRemove: \n  fixes literal :: Literal and literalList :: \"Literal list\"\n  shows \"oppositeLiteralList (removeAll literal literalList) = removeAll (opposite literal) (oppositeLiteralList literalList)\"\nunfolding oppositeLiteralList_def\nby (induct literalList) auto\n\nlemma oppositeLiteralListNonempty:\n  fixes literalList :: \"Literal list\"\n  shows \"(literalList \\<noteq> []) = ((oppositeLiteralList literalList) \\<noteq> [])\"\nunfolding oppositeLiteralList_def\nby (induct literalList) auto\n\nlemma varsOppositeLiteralList:\nshows \"vars (oppositeLiteralList clause) = vars clause\"\nunfolding oppositeLiteralList_def\nby (induct clause) auto\n\n\n(*------------------------------------------------------------------*)\nsubsubsection{* Tautological clauses *}\n\ntext{* Check if the clause contains both a literal and its opposite *}\nprimrec\nclauseTautology :: \"Clause \\<Rightarrow> bool\"\nwhere\n  \"clauseTautology [] = False\"\n| \"clauseTautology (literal # clause) = (opposite literal el clause \\<or> clauseTautology clause)\"\n\nlemma clauseTautologyCharacterization: \n  fixes clause :: Clause\n  shows \"clauseTautology clause = (\\<exists> literal. literal el clause \\<and> (opposite literal) el clause)\"\nby (induct clause) auto\n\n\n(********************************************************************)\nsubsection{* Semantics *}\n(********************************************************************)\n\n(*------------------------------------------------------------------*)\nsubsubsection{* Valuations *}\n\ntype_synonym Valuation = \"Literal list\"\n\nlemma valuationContainsItsLiteralsVariable: \n  fixes literal :: Literal and valuation :: Valuation\n  assumes \"literal el valuation\"\n  shows \"var literal \\<in> vars valuation\"\nusing assms\nby (induct valuation) auto\n\nlemma varsSubsetValuation: \n  fixes valuation1 :: Valuation and valuation2 :: Valuation\n  assumes \"set valuation1  \\<subseteq> set valuation2\"\n  shows \"vars valuation1 \\<subseteq> vars valuation2\"\nusing assms\nproof (induct valuation1)\n  case Nil\n  show ?case \n    by simp\nnext\n  case (Cons literal valuation)\n  note caseCons = this\n  hence \"literal el valuation2\" \n    by auto\n  with valuationContainsItsLiteralsVariable [of \"literal\" \"valuation2\"]\n  have \"var literal \\<in> vars valuation2\" .\n  with caseCons \n  show ?case \n    by simp\nqed\n\nlemma varsAppendValuation:\n  fixes valuation1 :: Valuation and valuation2 :: Valuation\n  shows \"vars (valuation1 @ valuation2) = vars valuation1 \\<union> vars valuation2\"\nby (induct valuation1) auto\nlemma varsPrefixValuation:\n  fixes valuation1 :: Valuation and valuation2 :: Valuation\n  assumes \"isPrefix valuation1 valuation2\"\n  shows \"vars valuation1 \\<subseteq> vars valuation2\"\nproof-\n  from assms \n  have \"set valuation1 \\<subseteq> set valuation2\"\n    by (auto simp add:isPrefix_def)\n  thus ?thesis\n    by (rule varsSubsetValuation)\nqed\n\n(*------------------------------------------------------------------*)\nsubsubsection{* True/False literals *}\n\ntext{* Check if the literal is contained in the given valuation *}\ndefinition literalTrue     :: \"Literal \\<Rightarrow> Valuation \\<Rightarrow> bool\"\nwhere\nliteralTrue_def [simp]: \"literalTrue literal valuation == literal el valuation\"\n\ntext{* Check if the opposite literal is contained in the given valuation *}\ndefinition literalFalse    :: \"Literal \\<Rightarrow> Valuation \\<Rightarrow> bool\"\nwhere\nliteralFalse_def [simp]: \"literalFalse literal valuation == opposite literal el valuation\"\n\n\nlemma variableDefinedImpliesLiteralDefined:\n  fixes literal :: Literal and valuation :: Valuation\n  shows \"var literal \\<in> vars valuation = (literalTrue literal valuation \\<or> literalFalse literal valuation)\" \n    (is \"(?lhs valuation) = (?rhs valuation)\")\nproof\n  assume \"?rhs valuation\"\n  thus \"?lhs valuation\" \n  proof\n    assume \"literalTrue literal valuation\"\n    hence \"literal el valuation\" \n      by simp\n    thus ?thesis\n      using valuationContainsItsLiteralsVariable[of \"literal\" \"valuation\"] \n      by simp\n  next\n    assume \"literalFalse literal valuation\"\n    hence \"opposite literal el valuation\" \n      by simp\n    thus ?thesis\n      using valuationContainsItsLiteralsVariable[of \"opposite literal\" \"valuation\"] \n      by simp\n  qed\nnext\n  assume \"?lhs valuation\" \n  thus \"?rhs valuation\"\n  proof (induct valuation)\n    case Nil\n    thus ?case \n      by simp\n  next\n    case (Cons literal' valuation')\n    note ih=this\n    show ?case\n    proof (cases \"var literal \\<in> vars valuation'\")\n      case True\n      with ih \n      show \"?rhs (literal' # valuation')\" \n        by auto\n    next\n      case False\n      with ih \n      have \"var literal' = var literal\" \n        by simp\n      hence \"literal' = literal \\<or> opposite literal' = literal\"\n        by (simp add:literalsWithSameVariableAreEqualOrOpposite)\n      thus \"?rhs (literal' # valuation')\" \n        by auto\n    qed\n  qed\nqed\n\n(*------------------------------------------------------------------*)\nsubsubsection{* True/False clauses *}\n\ntext{* Check if there is a literal from the clause which is true in the given valuation *}\nprimrec\nclauseTrue      :: \"Clause \\<Rightarrow> Valuation \\<Rightarrow> bool\"\nwhere\n  \"clauseTrue [] valuation = False\"\n| \"clauseTrue (literal # clause) valuation = (literalTrue literal valuation \\<or> clauseTrue clause valuation)\"\n\ntext{* Check if all the literals from the clause are false in the given valuation *}\nprimrec\nclauseFalse     :: \"Clause \\<Rightarrow> Valuation \\<Rightarrow> bool\"\nwhere\n  \"clauseFalse [] valuation = True\"\n| \"clauseFalse (literal # clause) valuation = (literalFalse literal valuation \\<and> clauseFalse clause valuation)\"\n\n\nlemma clauseTrueIffContainsTrueLiteral: \n  fixes clause :: Clause and valuation :: Valuation  \n  shows \"clauseTrue clause valuation = (\\<exists> literal. literal el clause \\<and> literalTrue literal valuation)\"\nby (induct clause) auto\n\nlemma clauseFalseIffAllLiteralsAreFalse:\n  fixes clause :: Clause and valuation :: Valuation  \n  shows \"clauseFalse clause valuation = (\\<forall> literal. literal el clause \\<longrightarrow> literalFalse literal valuation)\"\nby (induct clause) auto\n\nlemma clauseFalseRemove:\n  assumes \"clauseFalse clause valuation\"\n  shows \"clauseFalse (removeAll literal clause) valuation\"\nproof-\n  {\n    fix l::Literal\n    assume \"l el removeAll literal clause\"\n    hence \"l el clause\"\n      by simp\n   with `clauseFalse clause valuation` \n   have \"literalFalse l valuation\"\n     by (simp add:clauseFalseIffAllLiteralsAreFalse)\n  }\n  thus ?thesis\n    by (simp add:clauseFalseIffAllLiteralsAreFalse)\nqed\n\nlemma clauseFalseAppendValuation: \n  fixes clause :: Clause and valuation :: Valuation and valuation' :: Valuation\n  assumes \"clauseFalse clause valuation\"\n  shows \"clauseFalse clause (valuation @ valuation')\"\nusing assms\nby (induct clause) auto\n\nlemma clauseTrueAppendValuation:\n  fixes clause :: Clause and valuation :: Valuation and valuation' :: Valuation\n  assumes \"clauseTrue clause valuation\"\n  shows \"clauseTrue clause (valuation @ valuation')\"\nusing assms\nby (induct clause) auto\n\nlemma emptyClauseIsFalse:\n  fixes valuation :: Valuation\n  shows \"clauseFalse [] valuation\"\nby auto\n\nlemma emptyValuationFalsifiesOnlyEmptyClause:\n  fixes clause :: Clause\n  assumes \"clause \\<noteq> []\"\n  shows \"\\<not>  clauseFalse clause []\"\nusing assms\nby (induct clause) auto\n  \n\nlemma valuationContainsItsFalseClausesVariables:\n  fixes clause::Clause and valuation::Valuation\n  assumes \"clauseFalse clause valuation\"\n  shows \"vars clause \\<subseteq> vars valuation\"\nproof\n  fix v::Variable\n  assume \"v \\<in> vars clause\"\n  hence \"\\<exists> l. var l = v \\<and> l el clause\"\n    by (induct clause) auto\n  then obtain l \n    where \"var l = v\" \"l el clause\"\n    by auto\n  from `l el clause` `clauseFalse clause valuation`\n  have \"literalFalse l valuation\"\n    by (simp add: clauseFalseIffAllLiteralsAreFalse)\n  with `var l = v` \n  show \"v \\<in> vars valuation\"\n    using valuationContainsItsLiteralsVariable[of \"opposite l\"]\n    by simp\nqed\n  \n\n(*------------------------------------------------------------------*)\nsubsubsection{* True/False formulae *}\n\ntext{* Check if all the clauses from the formula are false in the given valuation *}\nprimrec\nformulaTrue     :: \"Formula \\<Rightarrow> Valuation \\<Rightarrow> bool\"\nwhere\n  \"formulaTrue [] valuation = True\"\n| \"formulaTrue (clause # formula) valuation = (clauseTrue clause valuation \\<and> formulaTrue formula valuation)\"\n\ntext{* Check if there is a clause from the formula which is false in the given valuation *}\nprimrec\nformulaFalse    :: \"Formula \\<Rightarrow> Valuation \\<Rightarrow> bool\"\nwhere\n  \"formulaFalse [] valuation = False\"\n| \"formulaFalse (clause # formula) valuation = (clauseFalse clause valuation \\<or> formulaFalse formula valuation)\"\n\n\nlemma formulaTrueIffAllClausesAreTrue: \n  fixes formula :: Formula and valuation :: Valuation\n  shows \"formulaTrue formula valuation = (\\<forall> clause. clause el formula \\<longrightarrow> clauseTrue clause valuation)\"\nby (induct formula) auto\n\nlemma formulaFalseIffContainsFalseClause: \n  fixes formula :: Formula and valuation :: Valuation\n  shows \"formulaFalse formula valuation = (\\<exists> clause. clause el formula \\<and> clauseFalse clause valuation)\"\nby (induct formula) auto\n\nlemma formulaTrueAssociativity:\n  fixes f1 :: Formula and f2 :: Formula and f3 :: Formula and valuation :: Valuation\n  shows \"formulaTrue ((f1 @ f2) @ f3) valuation = formulaTrue (f1 @ (f2 @ f3)) valuation\"\nby (auto simp add:formulaTrueIffAllClausesAreTrue)\n\nlemma formulaTrueCommutativity:\n  fixes f1 :: Formula and f2 :: Formula and valuation :: Valuation\n  shows \"formulaTrue (f1 @ f2) valuation = formulaTrue (f2 @ f1) valuation\"\nby (auto simp add:formulaTrueIffAllClausesAreTrue)\n\nlemma formulaTrueSubset:\n  fixes formula :: Formula and formula' :: Formula and valuation :: Valuation\n  assumes \n  formulaTrue: \"formulaTrue formula valuation\" and\n  subset: \"\\<forall> (clause::Clause). clause el formula' \\<longrightarrow> clause el formula\"\n  shows \"formulaTrue formula' valuation\"\nproof -\n  {\n    fix clause :: Clause\n    assume \"clause el formula'\"\n    with formulaTrue subset \n    have \"clauseTrue clause valuation\"\n      by (simp add:formulaTrueIffAllClausesAreTrue)\n  }\n  thus ?thesis\n    by (simp add:formulaTrueIffAllClausesAreTrue)\nqed\n\nlemma formulaTrueAppend:\n  fixes formula1 :: Formula and formula2 :: Formula and valuation :: Valuation\n  shows \"formulaTrue (formula1 @ formula2) valuation = (formulaTrue formula1 valuation \\<and> formulaTrue formula2 valuation)\"\nby (induct formula1) auto\n\nlemma formulaTrueRemoveAll:\n  fixes formula :: Formula and clause :: Clause and valuation :: Valuation    \n  assumes \"formulaTrue formula valuation\"\n  shows \"formulaTrue (removeAll clause formula) valuation\"\nusing assms\nby (induct formula) auto\n\nlemma formulaFalseAppend: \n  fixes formula :: Formula and formula' :: Formula and valuation :: Valuation  \n  assumes \"formulaFalse formula valuation\"\n  shows \"formulaFalse (formula @ formula') valuation\"\nusing assms \nby (induct formula) auto\n\nlemma formulaTrueAppendValuation: \n  fixes formula :: Formula and valuation :: Valuation and valuation' :: Valuation\n  assumes \"formulaTrue formula valuation\"\n  shows \"formulaTrue formula (valuation @ valuation')\"\nusing assms\nby (induct formula) (auto simp add:clauseTrueAppendValuation)\n\nlemma formulaFalseAppendValuation: \n  fixes formula :: Formula and valuation :: Valuation and valuation' :: Valuation\n  assumes \"formulaFalse formula valuation\"\n  shows \"formulaFalse formula (valuation @ valuation')\"\nusing assms\nby (induct formula) (auto simp add:clauseFalseAppendValuation)\n\nlemma trueFormulaWithSingleLiteralClause:\n  fixes formula :: Formula and literal :: Literal and valuation :: Valuation\n  assumes \"formulaTrue (removeAll [literal] formula) (valuation @ [literal])\"\n  shows \"formulaTrue formula (valuation @ [literal])\"\nproof -\n  {\n    fix clause :: Clause\n    assume \"clause el formula\"\n    with assms \n    have \"clauseTrue clause (valuation @ [literal])\"\n    proof (cases \"clause = [literal]\")\n      case True\n      thus ?thesis\n        by simp\n    next\n      case False\n      with `clause el formula`\n      have \"clause el (removeAll [literal] formula)\"\n        by simp\n      with `formulaTrue (removeAll [literal] formula) (valuation @ [literal])` \n      show ?thesis\n        by (simp add: formulaTrueIffAllClausesAreTrue)\n    qed\n  }\n  thus ?thesis\n    by (simp add: formulaTrueIffAllClausesAreTrue)\nqed\n\n(*------------------------------------------------------------------*)\nsubsubsection{* Valuation viewed as a formula *}\n\ntext{* Converts a valuation (the list of literals) into formula (list of single member lists of literals) *}\nprimrec\nval2form    :: \"Valuation \\<Rightarrow> Formula\"\nwhere\n  \"val2form [] = []\"\n| \"val2form (literal # valuation) = [literal] # val2form valuation\"\n\nlemma val2FormEl: \n  fixes literal :: Literal and valuation :: Valuation \n  shows \"literal el valuation = [literal] el val2form valuation\"\nby (induct valuation) auto\n\nlemma val2FormAreSingleLiteralClauses: \n  fixes clause :: Clause and valuation :: Valuation\n  shows \"clause el val2form valuation \\<longrightarrow> (\\<exists> literal. clause = [literal] \\<and> literal el valuation)\"\nby (induct valuation) auto\n\n\n\nlemma val2FormRemoveAll: \n  fixes literal :: Literal and valuation :: Valuation \n  shows \"removeAll [literal] (val2form valuation) = val2form (removeAll literal valuation)\"\nby (induct valuation) auto\n\nlemma val2formAppend: \n  fixes valuation1 :: Valuation and valuation2 :: Valuation\n  shows \"val2form (valuation1 @ valuation2) = (val2form valuation1 @ val2form valuation2)\"\nby (induct valuation1) auto\n\nlemma val2formFormulaTrue: \n  fixes valuation1 :: Valuation and valuation2 :: Valuation\n  shows \"formulaTrue (val2form valuation1) valuation2 = (\\<forall> (literal :: Literal). literal el valuation1 \\<longrightarrow> literal el valuation2)\"\nby (induct valuation1) auto\n\n\n(*------------------------------------------------------------------*)\nsubsubsection{* Consistency of valuations *}\n\ntext{*  Valuation is inconsistent if it contains both a literal and its opposite. *}\nprimrec\ninconsistent   :: \"Valuation \\<Rightarrow> bool\"\nwhere\n  \"inconsistent [] = False\"\n| \"inconsistent (literal # valuation) = (opposite literal el valuation \\<or> inconsistent valuation)\"\ndefinition [simp]: \"consistent valuation == \\<not> inconsistent valuation\"\n\nlemma inconsistentCharacterization: \n  fixes valuation :: Valuation\n  shows \"inconsistent valuation = (\\<exists> literal. literalTrue literal valuation \\<and> literalFalse literal valuation)\"\nby (induct valuation) auto\n\nlemma clauseTrueAndClauseFalseImpliesInconsistent: \n  fixes clause :: Clause and valuation :: Valuation\n  assumes \"clauseTrue clause valuation\" and \"clauseFalse clause valuation\"\n  shows \"inconsistent valuation\"\nproof -\n  from `clauseTrue clause valuation` obtain literal :: Literal \n    where \"literal el clause\" and \"literalTrue literal valuation\"\n    by (auto simp add: clauseTrueIffContainsTrueLiteral)\n  with `clauseFalse clause valuation` \n  have \"literalFalse literal valuation\" \n    by (auto simp add: clauseFalseIffAllLiteralsAreFalse)\n  from `literalTrue literal valuation` `literalFalse literal valuation` \n  show ?thesis \n    by (auto simp add: inconsistentCharacterization)\nqed\n\nlemma formulaTrueAndFormulaFalseImpliesInconsistent: \n  fixes formula :: Formula and valuation :: Valuation\n  assumes \"formulaTrue formula valuation\" and \"formulaFalse formula valuation\"\n  shows \"inconsistent valuation\"\nproof -\n  from `formulaFalse formula valuation` obtain clause :: Clause \n    where \"clause el formula\" and \"clauseFalse clause valuation\"\n    by (auto simp add: formulaFalseIffContainsFalseClause)\n  with `formulaTrue formula valuation` \n  have \"clauseTrue clause valuation\" \n    by (auto simp add: formulaTrueIffAllClausesAreTrue)\n  from `clauseTrue clause valuation` `clauseFalse clause valuation` \n  show ?thesis \n    by (auto simp add: clauseTrueAndClauseFalseImpliesInconsistent)\nqed\n\nlemma inconsistentAppend:\n  fixes valuation1 :: Valuation and valuation2 :: Valuation\n  assumes \"inconsistent (valuation1 @ valuation2)\"\n  shows \"inconsistent valuation1 \\<or> inconsistent valuation2 \\<or> (\\<exists> literal. literalTrue literal valuation1 \\<and> literalFalse literal valuation2)\"\nusing assms\nproof (cases \"inconsistent valuation1\")\n  case True\n  thus ?thesis \n    by simp\nnext\n  case False\n  thus ?thesis\n  proof (cases \"inconsistent valuation2\")\n    case True\n    thus ?thesis \n      by simp\n  next\n    case False\n    from `inconsistent (valuation1 @ valuation2)` obtain literal :: Literal \n      where \"literalTrue literal (valuation1 @ valuation2)\" and \"literalFalse literal (valuation1 @ valuation2)\"\n      by (auto simp add:inconsistentCharacterization)\n    hence \"(\\<exists> literal. literalTrue literal valuation1 \\<and> literalFalse literal valuation2)\"\n    proof (cases \"literalTrue literal valuation1\")\n      case True\n      with `\\<not> inconsistent valuation1` \n      have \"\\<not> literalFalse literal valuation1\" \n        by (auto simp add:inconsistentCharacterization)\n      with `literalFalse literal (valuation1 @ valuation2)` \n      have \"literalFalse literal valuation2\" \n        by auto\n      with True \n      show ?thesis \n        by auto\n    next\n      case False\n      with `literalTrue literal (valuation1 @ valuation2)` \n      have \"literalTrue literal valuation2\"\n        by auto\n      with `\\<not> inconsistent valuation2` \n      have \"\\<not> literalFalse literal valuation2\"\n        by (auto simp add:inconsistentCharacterization)\n      with `literalFalse literal (valuation1 @ valuation2)` \n      have \"literalFalse literal valuation1\"\n        by auto\n      with `literalTrue literal valuation2`\n      show ?thesis \n        by auto\n    qed\n    thus ?thesis \n      by simp\n  qed\nqed\n\nlemma consistentAppendElement:\nassumes \"consistent v\" and \"\\<not> literalFalse l v\"\nshows \"consistent (v @ [l])\"\nproof-\n  {\n    assume \"\\<not> ?thesis\"\n    with `consistent v`\n    have \"(opposite l) el v\"\n      using inconsistentAppend[of \"v\" \"[l]\"]\n      by auto\n    with `\\<not> literalFalse l v`\n    have False\n      by simp\n  }\n  thus ?thesis\n    by auto\nqed\n\nlemma inconsistentRemoveAll:\n  fixes literal :: Literal and valuation :: Valuation\n  assumes \"inconsistent (removeAll literal valuation)\" \n  shows \"inconsistent valuation\"\nusing assms\nproof -\n  from `inconsistent (removeAll literal valuation)` obtain literal' :: Literal \n    where l'True: \"literalTrue literal' (removeAll literal valuation)\" and l'False: \"literalFalse literal' (removeAll literal valuation)\"\n    by (auto simp add:inconsistentCharacterization)\n  from l'True \n  have \"literalTrue literal' valuation\"\n    by simp\n  moreover\n  from l'False \n  have \"literalFalse literal' valuation\"\n    by simp\n  ultimately\n  show ?thesis \n    by (auto simp add:inconsistentCharacterization)\nqed\n\nlemma inconsistentPrefix: \n  assumes \"isPrefix valuation1 valuation2\" and \"inconsistent valuation1\"\n  shows \"inconsistent valuation2\"\nusing assms\nby (auto simp add:inconsistentCharacterization isPrefix_def)\n\nlemma consistentPrefix:\n  assumes \"isPrefix valuation1 valuation2\" and \"consistent valuation2\"\n  shows \"consistent valuation1\"\nusing assms\nby (auto simp add:inconsistentCharacterization isPrefix_def)\n\n\n(*------------------------------------------------------------------*)\nsubsubsection{* Totality of valuations *}\n\ntext{* Checks if the valuation contains all the variables from the given set of variables *}\ndefinition total where\n[simp]: \"total valuation variables == variables \\<subseteq> vars valuation\"\n\nlemma totalSubset: \n  fixes A :: \"Variable set\" and B :: \"Variable set\" and valuation :: \"Valuation\"\n  assumes \"A \\<subseteq> B\" and \"total valuation B\"\n  shows \"total valuation A\"\nusing assms\nby auto\n\nlemma totalFormulaImpliesTotalClause:\n  fixes clause :: Clause and formula :: Formula and valuation :: Valuation\n  assumes clauseEl: \"clause el formula\" and totalFormula: \"total valuation (vars formula)\"\n  shows totalClause: \"total valuation (vars clause)\"\nproof -\n  from clauseEl \n  have \"vars clause \\<subseteq> vars formula\" \n    using formulaContainsItsClausesVariables [of \"clause\" \"formula\"] \n    by simp\n  with totalFormula \n  show ?thesis \n    by (simp add: totalSubset)\nqed\n\nlemma totalValuationForClauseDefinesAllItsLiterals:\n  fixes clause :: Clause and valuation :: Valuation and literal :: Literal\n  assumes \n  totalClause: \"total valuation (vars clause)\" and\n  literalEl: \"literal el clause\"\n  shows trueOrFalse: \"literalTrue literal valuation \\<or> literalFalse literal valuation\"\nproof -\n  from literalEl \n  have \"var literal \\<in> vars clause\"\n    using clauseContainsItsLiteralsVariable \n    by auto\n  with totalClause \n  have \"var literal \\<in> vars valuation\" \n    by auto\n  thus ?thesis \n    using  variableDefinedImpliesLiteralDefined [of \"literal\" \"valuation\"] \n    by simp\nqed\n\nlemma totalValuationForClauseDefinesItsValue:\n  fixes clause :: Clause and valuation :: Valuation\n  assumes totalClause: \"total valuation (vars clause)\"\n  shows \"clauseTrue clause valuation \\<or> clauseFalse clause valuation\"\nproof (cases \"clauseFalse clause valuation\")\n  case True\n  thus ?thesis \n    by (rule disjI2)\nnext\n  case False\n  hence \"\\<not> (\\<forall> l. l el clause \\<longrightarrow> literalFalse l valuation)\" \n    by (auto simp add:clauseFalseIffAllLiteralsAreFalse)\n  then obtain l :: Literal \n    where \"l el clause\" and \"\\<not> literalFalse l valuation\" \n    by auto\n  with totalClause \n  have \"literalTrue l valuation \\<or> literalFalse l valuation\"\n    using totalValuationForClauseDefinesAllItsLiterals [of \"valuation\" \"clause\" \"l\"] \n    by auto\n  with `\\<not> literalFalse l valuation` \n  have \"literalTrue l valuation\" \n    by simp\n  with `l el clause` \n  have \"(clauseTrue clause valuation)\" \n    by (auto simp add:clauseTrueIffContainsTrueLiteral)\n  thus ?thesis \n    by (rule disjI1) \nqed\n\nlemma totalValuationForFormulaDefinesAllItsLiterals: \n  fixes formula::Formula and valuation::Valuation\n  assumes totalFormula: \"total valuation (vars formula)\" and\n  literalElFormula: \"literal el formula\"\n  shows \"literalTrue literal valuation \\<or> literalFalse literal valuation\"\nproof -\n  from literalElFormula \n  have \"var literal \\<in> vars formula\" \n    by (rule formulaContainsItsLiteralsVariable)\n  with totalFormula \n  have \"var literal \\<in> vars valuation\" \n    by auto\n  thus ?thesis using variableDefinedImpliesLiteralDefined [of \"literal\" \"valuation\"] \n    by simp\nqed\n\nlemma totalValuationForFormulaDefinesAllItsClauses:\n  fixes formula :: Formula and valuation :: Valuation and clause :: Clause\n  assumes totalFormula: \"total valuation (vars formula)\" and \n  clauseElFormula: \"clause el formula\" \n  shows \"clauseTrue clause valuation \\<or> clauseFalse clause valuation\"\nproof -\n  from clauseElFormula totalFormula \n  have \"total valuation (vars clause)\"\n    by (rule totalFormulaImpliesTotalClause)\n  thus ?thesis\n    by (rule totalValuationForClauseDefinesItsValue)\nqed\n\nlemma totalValuationForFormulaDefinesItsValue:\n  assumes totalFormula: \"total valuation (vars formula)\"\n  shows \"formulaTrue formula valuation \\<or> formulaFalse formula valuation\"\nproof (cases \"formulaTrue formula valuation\")\n  case True\n  thus ?thesis\n    by simp\nnext\n  case False\n  then obtain clause :: Clause \n    where clauseElFormula: \"clause el formula\" and notClauseTrue: \"\\<not> clauseTrue clause valuation\" \n    by (auto simp add: formulaTrueIffAllClausesAreTrue)\n  from clauseElFormula totalFormula\n  have \"total valuation (vars clause)\"\n    using totalFormulaImpliesTotalClause [of \"clause\" \"formula\" \"valuation\"]\n    by simp\n  with notClauseTrue \n  have \"clauseFalse clause valuation\" \n    using totalValuationForClauseDefinesItsValue [of \"valuation\" \"clause\"]\n    by simp\n  with clauseElFormula \n  show ?thesis \n    by (auto simp add:formulaFalseIffContainsFalseClause)\nqed\n\nlemma totalRemoveAllSingleLiteralClause:\n  fixes literal :: Literal and valuation :: Valuation and formula :: Formula\n  assumes varLiteral: \"var literal \\<in> vars valuation\" and totalRemoveAll: \"total valuation (vars (removeAll [literal] formula))\"\n  shows \"total valuation (vars formula)\"\nproof -\n  have \"vars formula - vars [literal] \\<subseteq> vars (removeAll [literal] formula)\"\n    by (rule varsRemoveAllClauseSuperset)\n  with assms \n  show ?thesis \n    by auto\nqed\n\n\n(*------------------------------------------------------------------*)\nsubsubsection{* Models and satisfiability *}\n\ntext{* Model of a formula is a consistent valuation under which formula/clause is true*}\nconsts model :: \"Valuation \\<Rightarrow> 'a \\<Rightarrow> bool\"\ndefs (overloaded)\nmodelFormula_def [simp]: \"model valuation (formula::Formula)== consistent valuation \\<and> (formulaTrue formula valuation)\"\nmodelClause_def [simp]: \"model valuation (clause::Clause) == consistent valuation \\<and> (clauseTrue clause valuation)\"\n\ntext{* Checks if a formula has a model *}\ndefinition satisfiable :: \"Formula \\<Rightarrow> bool\"\nwhere\n\"satisfiable formula == \\<exists> valuation. model valuation formula\"\n\nlemma formulaWithEmptyClauseIsUnsatisfiable:\n  fixes formula :: Formula\n  assumes \"([]::Clause) el formula\"\n  shows \"\\<not> satisfiable formula\"\nusing assms\nby (auto simp add: satisfiable_def formulaTrueIffAllClausesAreTrue)\n\nlemma satisfiableSubset: \n  fixes formula0 :: Formula and formula :: Formula\n  assumes subset: \"\\<forall> (clause::Clause). clause el formula0 \\<longrightarrow> clause el formula\"\n  shows  \"satisfiable formula \\<longrightarrow> satisfiable formula0\"\nproof\n  assume \"satisfiable formula\"\n  show \"satisfiable formula0\"\n  proof -\n    from `satisfiable formula` obtain valuation :: Valuation\n      where \"model valuation formula\" \n      by (auto simp add: satisfiable_def)\n    {\n      fix clause :: Clause\n      assume \"clause el formula0\"\n      with subset \n      have \"clause el formula\" \n        by simp\n      with `model valuation formula` \n      have \"clauseTrue clause valuation\" \n        by (simp add: formulaTrueIffAllClausesAreTrue)\n    } hence \"formulaTrue formula0 valuation\" \n      by (simp add: formulaTrueIffAllClausesAreTrue)\n    with `model valuation formula` \n    have \"model valuation formula0\" \n      by simp\n    thus ?thesis \n      by (auto simp add: satisfiable_def)\n  qed\nqed\n\nlemma satisfiableAppend: \n  fixes formula1 :: Formula and formula2 :: Formula\n  assumes \"satisfiable (formula1 @ formula2)\" \n  shows \"satisfiable formula1\" \"satisfiable formula2\"\nusing assms\nunfolding satisfiable_def\nby (auto simp add:formulaTrueAppend)\n\nlemma modelExpand: \n  fixes formula :: Formula and literal :: Literal and valuation :: Valuation\n  assumes \"model valuation formula\" and \"var literal \\<notin> vars valuation\"\n  shows \"model (valuation @ [literal]) formula\"\nproof -\n  from `model valuation formula` \n  have \"formulaTrue formula (valuation @ [literal])\"\n    by (simp add:formulaTrueAppendValuation)\n  moreover\n  from `model valuation formula` \n  have \"consistent valuation\" \n    by simp\n  with `var literal \\<notin> vars valuation` \n  have \"consistent (valuation @ [literal])\"\n  proof (cases \"inconsistent (valuation @ [literal])\")\n    case True\n    hence \"inconsistent valuation \\<or> inconsistent [literal] \\<or> (\\<exists> l. literalTrue l valuation \\<and> literalFalse l [literal])\"\n      by (rule inconsistentAppend)\n    with `consistent valuation` \n    have \"\\<exists> l. literalTrue l valuation \\<and> literalFalse l [literal]\"\n      by auto\n    hence \"literalFalse literal valuation\" \n      by auto\n    hence \"var (opposite literal) \\<in> (vars valuation)\"\n      using valuationContainsItsLiteralsVariable [of \"opposite literal\" \"valuation\"]\n      by simp\n    with `var literal \\<notin> vars valuation` \n    have \"False\"\n      by simp\n    thus ?thesis ..\n  qed simp\n  ultimately \n  show ?thesis \n    by auto\nqed\n\n\n\n(*--------------------------------------------------------------------------------*)\nsubsubsection{* Tautological clauses *}\n\nlemma tautologyNotFalse:\n  fixes clause :: Clause and valuation :: Valuation\n  assumes \"clauseTautology clause\" \"consistent valuation\"\n  shows \"\\<not> clauseFalse clause valuation\"\nusing assms\n  clauseTautologyCharacterization[of \"clause\"]\n  clauseFalseIffAllLiteralsAreFalse[of \"clause\" \"valuation\"]\n  inconsistentCharacterization\nby auto\n  \n\nlemma tautologyInTotalValuation:\nassumes \n  \"clauseTautology clause\"\n  \"vars clause \\<subseteq> vars valuation\"\nshows\n  \"clauseTrue clause valuation\"\nproof-\n  from `clauseTautology clause`\n  obtain literal\n    where \"literal el clause\" \"opposite literal el clause\"\n    by (auto simp add: clauseTautologyCharacterization)\n  hence \"var literal \\<in> vars clause\"\n    using clauseContainsItsLiteralsVariable[of \"literal\" \"clause\"]\n    using clauseContainsItsLiteralsVariable[of \"opposite literal\" \"clause\"]\n    by simp\n  hence \"var literal \\<in> vars valuation\"\n    using `vars clause \\<subseteq> vars valuation`\n    by auto\n  hence \"literalTrue literal valuation \\<or> literalFalse literal valuation\"\n    using varInClauseVars[of \"var literal\" \"valuation\"]\n    using varInClauseVars[of \"var (opposite literal)\" \"valuation\"]\n    using literalsWithSameVariableAreEqualOrOpposite\n    by auto\n  thus ?thesis\n    using `literal el clause` `opposite literal el clause`\n    by (auto simp add: clauseTrueIffContainsTrueLiteral)\nqed\n\nlemma modelAppendTautology:\nassumes\n  \"model valuation F\" \"clauseTautology c\"\n  \"vars valuation \\<supseteq> vars F \\<union> vars c\"\nshows\n  \"model valuation (F @ [c])\"\nusing assms\nusing tautologyInTotalValuation[of \"c\" \"valuation\"]\nby (auto simp add: formulaTrueAppend)\n\nlemma satisfiableAppendTautology:\nassumes \n  \"satisfiable F\" \"clauseTautology c\"\nshows\n  \"satisfiable (F @ [c])\"\nproof-\n  from `clauseTautology c` \n  obtain l \n    where \"l el c\" \"opposite l el c\"\n    by (auto simp add: clauseTautologyCharacterization)\n  from `satisfiable F`\n  obtain valuation\n    where \"consistent valuation\" \"formulaTrue F valuation\"\n    unfolding satisfiable_def\n    by auto\n  show ?thesis\n  proof (cases \"var l \\<in> vars valuation\")\n    case True\n    hence \"literalTrue l valuation \\<or> literalFalse l valuation\"\n      using varInClauseVars[of \"var l\" \"valuation\"]\n      by (auto simp add: literalsWithSameVariableAreEqualOrOpposite)\n    hence \"clauseTrue c valuation\"\n      using `l el c` `opposite l el c`\n      by (auto simp add: clauseTrueIffContainsTrueLiteral)\n    thus ?thesis\n      using `consistent valuation` `formulaTrue F valuation`\n      unfolding satisfiable_def\n      by (auto simp add: formulaTrueIffAllClausesAreTrue)\n  next\n    case False\n    let ?valuation' = \"valuation @ [l]\"\n    have \"model ?valuation' F\"\n      using `var l \\<notin> vars valuation`\n      using `formulaTrue F valuation` `consistent valuation`\n      using modelExpand[of \"valuation\" \"F\" \"l\"]\n      by simp\n    moreover\n    have \"formulaTrue [c] ?valuation'\"\n      using `l el c`\n      using clauseTrueIffContainsTrueLiteral[of \"c\" \"?valuation'\"]\n      using formulaTrueIffAllClausesAreTrue[of \"[c]\" \"?valuation'\"]\n      by auto\n    ultimately\n    show ?thesis\n      unfolding satisfiable_def\n      by (auto simp add: formulaTrueAppend)\n  qed\nqed\n\nlemma modelAppendTautologicalFormula:\nfixes\n  F :: Formula and F' :: Formula\nassumes\n  \"model valuation F\" \"\\<forall> c. c el F' \\<longrightarrow> clauseTautology c\"\n  \"vars valuation \\<supseteq> vars F \\<union> vars F'\"\nshows\n  \"model valuation (F @ F')\"\nusing assms\nproof (induct F')\n  case Nil\n  thus ?case\n    by simp\nnext\n  case (Cons c F'')\n  hence \"model valuation (F @ F'')\"\n    by simp\n  hence \"model valuation ((F @ F'') @ [c])\"\n    using Cons(3)\n    using Cons(4)\n    using modelAppendTautology[of \"valuation\" \"F @ F''\" \"c\"]\n    using varsAppendFormulae[of \"F\" \"F''\"]\n    by simp\n  thus ?case\n    by (simp add: formulaTrueAppend)\nqed\n\n\nlemma satisfiableAppendTautologicalFormula:\nassumes \n  \"satisfiable F\" \"\\<forall> c. c el F' \\<longrightarrow> clauseTautology c\"\nshows\n  \"satisfiable (F @ F')\"\nusing assms\nproof (induct F')\n  case Nil\n  thus ?case\n    by simp\nnext\n  case (Cons c F'')\n  hence \"satisfiable (F @ F'')\"\n    by simp\n  thus ?case\n    using Cons(3)\n    using satisfiableAppendTautology[of \"F @ F''\" \"c\"]\n    unfolding satisfiable_def\n    by (simp add: formulaTrueIffAllClausesAreTrue)\nqed\n\nlemma satisfiableFilterTautologies:\nshows \"satisfiable F = satisfiable (filter (% c. \\<not> clauseTautology c) F)\"\nproof (induct F)\n  case Nil\n  thus ?case\n    by simp\nnext\n  case (Cons c' F')\n  let ?filt  = \"\\<lambda> F. filter (% c. \\<not> clauseTautology c) F\"\n  let ?filt'  = \"\\<lambda> F. filter (% c. clauseTautology c) F\"\n  show ?case\n  proof\n    assume \"satisfiable (c' # F')\"\n    thus \"satisfiable (?filt (c' # F'))\"\n      unfolding satisfiable_def\n      by (auto simp add: formulaTrueIffAllClausesAreTrue)\n  next\n    assume \"satisfiable (?filt (c' # F'))\"\n    thus \"satisfiable (c' # F')\"\n    proof (cases \"clauseTautology c'\")\n      case True\n      hence \"?filt (c' # F') = ?filt F'\"\n        by auto\n      hence \"satisfiable (?filt F')\"\n        using `satisfiable (?filt (c' # F'))`\n        by simp\n      hence \"satisfiable F'\"\n        using Cons\n        by simp\n      thus ?thesis\n        using satisfiableAppendTautology[of \"F'\" \"c'\"]\n        using `clauseTautology c'`\n        unfolding satisfiable_def\n        by (auto simp add: formulaTrueIffAllClausesAreTrue)\n    next\n      case False\n      hence \"?filt (c' # F') = c' # ?filt F'\"\n        by auto   \n      hence \"satisfiable (c' # ?filt F')\"\n        using `satisfiable (?filt (c' # F'))`\n        by simp\n      moreover\n      have \"\\<forall> c. c el ?filt' F' \\<longrightarrow> clauseTautology c\"\n        by simp\n      ultimately\n      have \"satisfiable ((c' # ?filt F') @ ?filt' F')\"\n        using satisfiableAppendTautologicalFormula[of \"c' # ?filt F'\" \"?filt' F'\"]\n        by (simp (no_asm_use))\n      thus ?thesis\n        unfolding satisfiable_def\n        by (auto simp add: formulaTrueIffAllClausesAreTrue)\n    qed\n  qed\nqed\n\nlemma modelFilterTautologies:\nassumes \n  \"model valuation (filter (% c. \\<not> clauseTautology c) F)\" \n  \"vars F \\<subseteq> vars valuation\"\nshows \"model valuation F\"\nusing assms\nproof (induct F)\n  case Nil\n  thus ?case\n    by simp\nnext\n  case (Cons c' F')\n  let ?filt  = \"\\<lambda> F. filter (% c. \\<not> clauseTautology c) F\"\n  let ?filt'  = \"\\<lambda> F. filter (% c. clauseTautology c) F\"\n  show ?case\n  proof (cases \"clauseTautology c'\")\n    case True\n    thus ?thesis\n      using Cons\n      using tautologyInTotalValuation[of \"c'\" \"valuation\"]\n      by auto\n  next\n    case False\n    hence \"?filt (c' # F') = c' # ?filt F'\"\n      by auto   \n    hence \"model valuation (c' # ?filt F')\"\n      using `model valuation (?filt (c' # F'))`\n      by simp\n    moreover\n    have \"\\<forall> c. c el ?filt' F' \\<longrightarrow> clauseTautology c\"\n      by simp\n    moreover \n    have \"vars ((c' # ?filt F') @ ?filt' F') \\<subseteq> vars valuation\"\n      using varsSubsetFormula[of \"?filt F'\" \"F'\"]\n      using varsSubsetFormula[of \"?filt' F'\" \"F'\"]\n      using varsAppendFormulae[of \"c' # ?filt F'\" \"?filt' F'\"]\n      using Cons(3)\n      using formulaContainsItsClausesVariables[of _ \"?filt F'\"]\n      by auto\n    ultimately\n    have \"model valuation ((c' # ?filt F') @ ?filt' F')\"\n      using modelAppendTautologicalFormula[of \"valuation\" \"c' # ?filt F'\" \"?filt' F'\"]\n      using varsAppendFormulae[of \"c' # ?filt F'\" \"?filt' F'\"]\n      by (simp (no_asm_use)) (blast)\n    thus ?thesis\n      using formulaTrueAppend[of \"?filt F'\" \"?filt' F'\" \"valuation\"]\n      using formulaTrueIffAllClausesAreTrue[of \"?filt F'\" \"valuation\"]\n      using formulaTrueIffAllClausesAreTrue[of \"?filt' F'\" \"valuation\"]\n      using formulaTrueIffAllClausesAreTrue[of \"F'\" \"valuation\"]      \n      by auto\n  qed\nqed\n\n(*------------------------------------------------------------------*)\nsubsubsection{* Entailment *}\n\ntext{* Formula entails literal if it is true in all its models *}\ndefinition formulaEntailsLiteral :: \"Formula \\<Rightarrow> Literal \\<Rightarrow> bool\"\nwhere\n\"formulaEntailsLiteral formula literal == \n  \\<forall> (valuation::Valuation). model valuation formula \\<longrightarrow> literalTrue literal valuation\"\n\ntext{* Clause implies literal if it is true in all its models *}\ndefinition clauseEntailsLiteral  :: \"Clause \\<Rightarrow> Literal \\<Rightarrow> bool\"\nwhere\n\"clauseEntailsLiteral clause literal == \n  \\<forall> (valuation::Valuation). model valuation clause \\<longrightarrow> literalTrue literal valuation\"\n\ntext{* Formula entails clause if it is true in all its models *}\ndefinition formulaEntailsClause  :: \"Formula \\<Rightarrow> Clause \\<Rightarrow> bool\"\nwhere\n\"formulaEntailsClause formula clause == \n  \\<forall> (valuation::Valuation). model valuation formula \\<longrightarrow> model valuation clause\"\n\ntext{* Formula entails valuation if it entails its every literal *}\ndefinition formulaEntailsValuation :: \"Formula \\<Rightarrow> Valuation \\<Rightarrow> bool\"\nwhere\n\"formulaEntailsValuation formula valuation ==\n    \\<forall> literal. literal el valuation \\<longrightarrow> formulaEntailsLiteral formula literal\"\n\ntext{* Formula entails formula if it is true in all its models *}\ndefinition formulaEntailsFormula  :: \"Formula \\<Rightarrow> Formula \\<Rightarrow> bool\"\nwhere\nformulaEntailsFormula_def: \"formulaEntailsFormula formula formula' == \n  \\<forall> (valuation::Valuation). model valuation formula \\<longrightarrow> model valuation formula'\"\n\nlemma singleLiteralClausesEntailItsLiteral: \n  fixes clause :: Clause and literal :: Literal\n  assumes \"length clause = 1\" and \"literal el clause\"\n  shows \"clauseEntailsLiteral clause literal\"\nproof -\n  from assms \n  have onlyLiteral: \"\\<forall> l. l el clause \\<longrightarrow> l = literal\" \n    using lengthOneImpliesOnlyElement[of \"clause\" \"literal\"]\n    by simp\n  {\n    fix valuation :: Valuation\n    assume \"clauseTrue clause valuation\"\n    with onlyLiteral  \n    have \"literalTrue literal valuation\" \n      by (auto simp add:clauseTrueIffContainsTrueLiteral)\n  }\n  thus ?thesis \n    by (simp add:clauseEntailsLiteral_def)\nqed\n\nlemma clauseEntailsLiteralThenFormulaEntailsLiteral:\n  fixes clause :: Clause and formula :: Formula and literal :: Literal\n  assumes \"clause el formula\" and \"clauseEntailsLiteral clause literal\"\n  shows \"formulaEntailsLiteral formula literal\"\nproof -\n  {\n    fix valuation :: Valuation\n    assume modelFormula: \"model valuation formula\"\n\n    with `clause el formula` \n    have \"clauseTrue clause valuation\"\n      by (simp add:formulaTrueIffAllClausesAreTrue)\n    with modelFormula `clauseEntailsLiteral clause literal` \n    have \"literalTrue literal valuation\"\n      by (auto simp add: clauseEntailsLiteral_def)\n  }\n  thus ?thesis \n    by (simp add:formulaEntailsLiteral_def)\nqed\n\nlemma formulaEntailsLiteralAppend: \n  fixes formula :: Formula and formula' :: Formula and literal :: Literal\n  assumes \"formulaEntailsLiteral formula literal\"\n  shows  \"formulaEntailsLiteral (formula @ formula') literal\"\nproof -\n  {\n    fix valuation :: Valuation\n    assume modelFF': \"model valuation (formula @ formula')\"\n\n    hence \"formulaTrue formula valuation\" \n      by (simp add: formulaTrueAppend)\n    with modelFF' and `formulaEntailsLiteral formula literal` \n    have \"literalTrue literal valuation\" \n      by (simp add: formulaEntailsLiteral_def)\n  }\n  thus ?thesis \n    by (simp add: formulaEntailsLiteral_def)\nqed\n\nlemma formulaEntailsLiteralSubset: \n  fixes formula :: Formula and formula' :: Formula and literal :: Literal\n  assumes \"formulaEntailsLiteral formula literal\" and \"\\<forall> (c::Clause) . c el formula \\<longrightarrow> c el formula'\"\n  shows \"formulaEntailsLiteral formula' literal\"\nproof -\n  {\n    fix valuation :: Valuation\n    assume modelF': \"model valuation formula'\"\n    with `\\<forall> (c::Clause) . c el formula \\<longrightarrow> c el formula'` \n    have \"formulaTrue formula valuation\"\n      by (auto simp add: formulaTrueIffAllClausesAreTrue)\n    with modelF' `formulaEntailsLiteral formula literal` \n    have \"literalTrue literal valuation\"\n      by (simp add: formulaEntailsLiteral_def)\n  }\n  thus ?thesis \n    by (simp add:formulaEntailsLiteral_def)\nqed\n\n\nlemma formulaEntailsLiteralRemoveAll:\n  fixes formula :: Formula and clause :: Clause and literal :: Literal\n  assumes \"formulaEntailsLiteral (removeAll clause formula) literal\"\n  shows \"formulaEntailsLiteral formula literal\"\nproof -\n  {\n    fix valuation :: Valuation\n    assume modelF: \"model valuation formula\"\n    hence \"formulaTrue (removeAll clause formula) valuation\" \n      by (auto simp add:formulaTrueRemoveAll)\n    with modelF `formulaEntailsLiteral (removeAll clause formula) literal` \n    have \"literalTrue literal valuation\"\n      by (auto simp add:formulaEntailsLiteral_def)\n  }\n  thus ?thesis \n    by (simp add:formulaEntailsLiteral_def)\nqed\n\nlemma formulaEntailsLiteralRemoveAllAppend:\n  fixes formula1 :: Formula and formula2 :: Formula and clause :: Clause and valuation :: Valuation\n  assumes \"formulaEntailsLiteral ((removeAll clause formula1) @ formula2) literal\" \n  shows \"formulaEntailsLiteral (formula1 @ formula2) literal\"\nproof -\n  {\n    fix valuation :: Valuation\n    assume modelF: \"model valuation (formula1 @ formula2)\"\n    hence \"formulaTrue ((removeAll clause formula1) @ formula2) valuation\" \n      by (auto simp add:formulaTrueRemoveAll formulaTrueAppend)\n    with modelF `formulaEntailsLiteral ((removeAll clause formula1) @ formula2) literal` \n    have \"literalTrue literal valuation\"\n      by (auto simp add:formulaEntailsLiteral_def)\n  }\n  thus ?thesis \n    by (simp add:formulaEntailsLiteral_def)\nqed\n\nlemma formulaEntailsItsClauses: \n  fixes clause :: Clause and formula :: Formula\n  assumes \"clause el formula\"\n  shows \"formulaEntailsClause formula clause\"\nusing assms\nby (simp add: formulaEntailsClause_def formulaTrueIffAllClausesAreTrue)\n\nlemma formulaEntailsClauseAppend: \n  fixes clause :: Clause and formula :: Formula and formula' :: Formula\n  assumes \"formulaEntailsClause formula clause\"\n  shows \"formulaEntailsClause (formula @ formula') clause\"\nproof -\n  { \n    fix valuation :: Valuation\n    assume \"model valuation (formula @ formula')\"\n    hence \"model valuation formula\"\n      by (simp add:formulaTrueAppend)\n    with `formulaEntailsClause formula clause` \n    have \"clauseTrue clause valuation\"\n      by (simp add:formulaEntailsClause_def)\n  }\n  thus ?thesis \n    by (simp add: formulaEntailsClause_def)\nqed\n\nlemma formulaUnsatIffImpliesEmptyClause: \n  fixes formula :: Formula\n  shows \"formulaEntailsClause formula [] = (\\<not> satisfiable formula)\"\nby (auto simp add: formulaEntailsClause_def satisfiable_def)\n\nlemma formulaTrueExtendWithEntailedClauses:\n  fixes formula :: Formula and formula0 :: Formula and valuation :: Valuation\n  assumes formulaEntailed: \"\\<forall> (clause::Clause). clause el formula \\<longrightarrow> formulaEntailsClause formula0 clause\" and \"consistent valuation\"\n  shows \"formulaTrue formula0 valuation \\<longrightarrow> formulaTrue formula valuation\"\nproof\n  assume \"formulaTrue formula0 valuation\"\n  {\n    fix clause :: Clause\n    assume \"clause el formula\"\n    with formulaEntailed \n    have \"formulaEntailsClause formula0 clause\"\n      by simp\n    with `formulaTrue formula0 valuation` `consistent valuation` \n    have \"clauseTrue clause valuation\"\n      by (simp add:formulaEntailsClause_def)\n  }\n  thus \"formulaTrue formula valuation\"\n    by (simp add:formulaTrueIffAllClausesAreTrue)\nqed\n\n\nlemma formulaEntailsFormulaIffEntailsAllItsClauses: \n  fixes formula :: Formula and formula' :: Formula\n  shows \"formulaEntailsFormula formula formula' = (\\<forall> clause::Clause. clause el formula' \\<longrightarrow> formulaEntailsClause formula clause)\"\n     (is \"?lhs = ?rhs\")\nproof\n  assume ?lhs\n  show ?rhs\n  proof\n    fix clause :: Clause\n    show \"clause el formula' \\<longrightarrow> formulaEntailsClause formula clause\"\n    proof\n      assume \"clause el formula'\"\n      show \"formulaEntailsClause formula clause\"\n      proof -\n        {\n          fix valuation :: Valuation\n          assume \"model valuation formula\"\n          with `?lhs` \n          have \"model valuation formula'\"\n            by (simp add:formulaEntailsFormula_def)\n          with `clause el formula'` \n          have \"clauseTrue clause valuation\"\n            by (simp add:formulaTrueIffAllClausesAreTrue)\n        }\n        thus ?thesis \n          by (simp add:formulaEntailsClause_def)\n      qed\n    qed\n  qed\nnext\n  assume ?rhs\n  thus ?lhs\n  proof -\n    {\n      fix valuation :: Valuation\n      assume \"model valuation formula\"\n      {\n        fix clause :: Clause\n        assume \"clause el formula'\"\n        with `?rhs` \n        have \"formulaEntailsClause formula clause\"\n          by auto\n        with `model valuation formula` \n        have \"clauseTrue clause valuation\"\n          by (simp add:formulaEntailsClause_def)\n      }\n      hence \"(formulaTrue formula' valuation)\"\n        by (simp add:formulaTrueIffAllClausesAreTrue)\n    }\n    thus ?thesis\n      by (simp add:formulaEntailsFormula_def)\n  qed\nqed\n\nlemma formulaEntailsFormulaThatEntailsClause: \n  fixes formula1 :: Formula and formula2 :: Formula and clause :: Clause\n  assumes \"formulaEntailsFormula formula1 formula2\" and \"formulaEntailsClause formula2 clause\"\n  shows \"formulaEntailsClause formula1 clause\"\nusing assms\nby (simp add: formulaEntailsClause_def formulaEntailsFormula_def)\n\n\nlemma \n  fixes formula1 :: Formula and formula2 :: Formula and formula1' :: Formula and literal :: Literal\n  assumes \"formulaEntailsLiteral (formula1 @ formula2) literal\" and \"formulaEntailsFormula formula1' formula1\"\n  shows \"formulaEntailsLiteral (formula1' @ formula2) literal\"\nproof -\n  {\n    fix valuation :: Valuation\n    assume \"model valuation (formula1' @ formula2)\"\n    hence \"consistent valuation\" and \"formulaTrue formula1' valuation\"  \"formulaTrue formula2 valuation\"\n      by (auto simp add: formulaTrueAppend)\n    with `formulaEntailsFormula formula1' formula1` \n    have \"model valuation formula1\"\n      by (simp add:formulaEntailsFormula_def)\n    with `formulaTrue formula2 valuation` \n    have \"model valuation (formula1 @ formula2)\"\n      by (simp add: formulaTrueAppend)\n    with `formulaEntailsLiteral (formula1 @ formula2) literal` \n    have \"literalTrue literal valuation\"\n      by (simp add:formulaEntailsLiteral_def)\n  }\n  thus ?thesis\n    by (simp add:formulaEntailsLiteral_def)\nqed\n\n\nlemma formulaFalseInEntailedValuationIsUnsatisfiable: \n  fixes formula :: Formula and valuation :: Valuation\n  assumes \"formulaFalse formula valuation\" and \n          \"formulaEntailsValuation formula valuation\"\n  shows \"\\<not> satisfiable formula\"\nproof -\n  from `formulaFalse formula valuation` obtain clause :: Clause\n    where \"clause el formula\" and \"clauseFalse clause valuation\"\n    by (auto simp add:formulaFalseIffContainsFalseClause)\n  {\n    fix valuation' :: Valuation\n    assume modelV': \"model valuation' formula\"\n    with `clause el formula` obtain literal :: Literal \n      where \"literal el clause\" and \"literalTrue literal valuation'\"\n      by (auto simp add: formulaTrueIffAllClausesAreTrue clauseTrueIffContainsTrueLiteral)\n    with `clauseFalse clause valuation` \n    have \"literalFalse literal valuation\"\n      by (auto simp add:clauseFalseIffAllLiteralsAreFalse)\n    with `formulaEntailsValuation formula valuation` \n    have \"formulaEntailsLiteral formula (opposite literal)\"\n      unfolding formulaEntailsValuation_def\n      by simp\n    with modelV' \n    have \"literalFalse literal valuation'\"\n      by (auto simp add:formulaEntailsLiteral_def)\n    from `literalTrue literal valuation'` `literalFalse literal valuation'` modelV' \n    have \"False\"\n      by (simp add:inconsistentCharacterization)\n  }\n  thus ?thesis\n    by (auto simp add:satisfiable_def)\nqed\n\nlemma formulaFalseInEntailedOrPureValuationIsUnsatisfiable: \n  fixes formula :: Formula and valuation :: Valuation\n  assumes \"formulaFalse formula valuation\" and \n  \"\\<forall> literal'. literal' el valuation \\<longrightarrow> formulaEntailsLiteral formula literal' \\<or>  \\<not> opposite literal' el formula\"\n  shows \"\\<not> satisfiable formula\"\nproof -\n  from `formulaFalse formula valuation` obtain clause :: Clause\n    where \"clause el formula\" and \"clauseFalse clause valuation\"\n    by (auto simp add:formulaFalseIffContainsFalseClause)\n  {\n    fix valuation' :: Valuation\n    assume modelV': \"model valuation' formula\"\n    with `clause el formula` obtain literal :: Literal \n      where \"literal el clause\" and \"literalTrue literal valuation'\"\n      by (auto simp add: formulaTrueIffAllClausesAreTrue clauseTrueIffContainsTrueLiteral)\n    with `clauseFalse clause valuation` \n    have \"literalFalse literal valuation\"\n      by (auto simp add:clauseFalseIffAllLiteralsAreFalse)\n    with `\\<forall> literal'. literal' el valuation \\<longrightarrow> formulaEntailsLiteral formula literal' \\<or>  \\<not> opposite literal' el formula` \n    have \"formulaEntailsLiteral formula (opposite literal) \\<or> \\<not> literal el formula\"\n      by auto\n    moreover\n    {\n      assume \"formulaEntailsLiteral formula (opposite literal)\"\n      with modelV' \n      have \"literalFalse literal valuation'\"\n        by (auto simp add:formulaEntailsLiteral_def)\n      from `literalTrue literal valuation'` `literalFalse literal valuation'` modelV' \n      have \"False\"\n        by (simp add:inconsistentCharacterization)\n    }\n    moreover\n    {\n      assume \"\\<not> literal el formula\"\n      with `clause el formula` `literal el clause`\n      have \"False\"\n        by (simp add:literalElFormulaCharacterization)\n    }\n    ultimately\n    have \"False\"\n      by auto\n  }\n  thus ?thesis\n    by (auto simp add:satisfiable_def)\nqed\n\n\nlemma unsatisfiableFormulaWithSingleLiteralClause:\n  fixes formula :: Formula and literal :: Literal\n  assumes \"\\<not> satisfiable formula\" and \"[literal] el formula\"\n  shows \"formulaEntailsLiteral (removeAll [literal] formula) (opposite literal)\"\nproof -\n  {\n    fix valuation :: Valuation\n    assume \"model valuation (removeAll [literal] formula)\"\n    hence \"literalFalse literal valuation\"\n    proof (cases \"var literal \\<in> vars valuation\")\n      case True\n      {\n        assume \"literalTrue literal valuation\"\n        with `model valuation (removeAll [literal] formula)` \n        have \"model valuation formula\"\n          by (auto simp add:formulaTrueIffAllClausesAreTrue)\n        with `\\<not> satisfiable formula` \n        have \"False\"\n          by (auto simp add:satisfiable_def)\n      }\n      with True \n      show ?thesis \n        using variableDefinedImpliesLiteralDefined [of \"literal\" \"valuation\"]\n        by auto\n    next\n      case False\n      with `model valuation (removeAll [literal] formula)` \n      have \"model (valuation @ [literal]) (removeAll [literal] formula)\"\n        by (rule modelExpand)\n      hence \n        \"formulaTrue (removeAll [literal] formula) (valuation @ [literal])\" and \"consistent (valuation @ [literal])\"\n        by auto\n      from `formulaTrue (removeAll [literal] formula) (valuation @ [literal])` \n      have \"formulaTrue formula (valuation @ [literal])\"\n        by (rule trueFormulaWithSingleLiteralClause)\n      with `consistent (valuation @ [literal])` \n      have \"model (valuation @ [literal]) formula\"\n        by simp\n      with `\\<not> satisfiable formula` \n      have \"False\"\n        by (auto simp add:satisfiable_def)\n      thus ?thesis ..\n    qed\n  }\n  thus ?thesis \n    by (simp add:formulaEntailsLiteral_def)\nqed\n\nlemma unsatisfiableFormulaWithSingleLiteralClauses:\n  fixes F::Formula and c::Clause\n  assumes \"\\<not> satisfiable (F @ val2form (oppositeLiteralList c))\" \"\\<not> clauseTautology c\"\n  shows \"formulaEntailsClause F c\"\nproof-\n  {\n    fix v::Valuation\n    assume \"model v F\"\n    with `\\<not> satisfiable (F @ val2form (oppositeLiteralList c))`\n    have \"\\<not> formulaTrue (val2form (oppositeLiteralList c)) v\"\n      unfolding satisfiable_def\n      by (auto simp add: formulaTrueAppend)\n    have \"clauseTrue c v\"\n    proof (cases \"\\<exists> l. l el c \\<and> (literalTrue l v)\")\n      case True\n      thus ?thesis\n        using clauseTrueIffContainsTrueLiteral\n        by simp\n    next\n      case False\n      let ?v' = \"v @ (oppositeLiteralList c)\"\n\n      have \"\\<not> inconsistent (oppositeLiteralList c)\"\n      proof-\n        {\n          assume \"\\<not> ?thesis\"\n          then obtain l::Literal\n            where \"l el (oppositeLiteralList c)\" \"opposite l el (oppositeLiteralList c)\"\n            using inconsistentCharacterization [of \"oppositeLiteralList c\"]\n            by auto\n          hence \"(opposite l) el c\" \"l el c\"\n            using literalElListIffOppositeLiteralElOppositeLiteralList[of \"l\" \"c\"]\n            using literalElListIffOppositeLiteralElOppositeLiteralList[of \"opposite l\" \"c\"]\n            by auto\n          hence \"clauseTautology c\"\n            using clauseTautologyCharacterization[of \"c\"]\n            by auto\n          with `\\<not> clauseTautology c`\n          have \"False\"\n            by simp\n        }\n        thus ?thesis\n          by auto\n      qed\n      with False `model v F`\n      have \"consistent ?v'\"\n        using inconsistentAppend[of \"v\" \"oppositeLiteralList c\"]\n        unfolding consistent_def\n        using literalElListIffOppositeLiteralElOppositeLiteralList\n        by auto\n      moreover\n      from `model v F`\n      have \"formulaTrue F ?v'\"\n        using formulaTrueAppendValuation\n        by simp\n      moreover\n      have \"formulaTrue (val2form (oppositeLiteralList c)) ?v'\"\n        using val2formFormulaTrue[of \"oppositeLiteralList c\" \"v @ oppositeLiteralList c\"]\n        by simp\n      ultimately\n      have \"model ?v' (F @ val2form (oppositeLiteralList c))\"\n        by (simp add: formulaTrueAppend)\n      with `\\<not> satisfiable (F @ val2form (oppositeLiteralList c))`\n      have \"False\"\n        unfolding satisfiable_def\n        by auto\n      thus ?thesis\n        by simp\n    qed\n  }\n  thus ?thesis\n    unfolding formulaEntailsClause_def\n    by simp\nqed\n\nlemma satisfiableEntailedFormula:\n  fixes formula0 :: Formula and formula :: Formula\n  assumes \"formulaEntailsFormula formula0 formula\"\n  shows \"satisfiable formula0 \\<longrightarrow> satisfiable formula\"\nproof\n  assume \"satisfiable formula0\"\n  show \"satisfiable formula\"\n  proof -\n    from `satisfiable formula0` obtain valuation :: Valuation\n      where \"model valuation formula0\" \n      by (auto simp add: satisfiable_def)\n    with `formulaEntailsFormula formula0 formula` \n    have \"model valuation formula\" \n      by (simp add: formulaEntailsFormula_def)\n    thus ?thesis \n      by (auto simp add: satisfiable_def)\n  qed\nqed\n\nlemma val2formIsEntailed:\nshows \"formulaEntailsValuation (F' @ val2form valuation @ F'') valuation\"\nproof-\n  {\n    fix l::Literal\n    assume \"l el valuation\"\n    hence \"[l] el val2form valuation\"\n      by (induct valuation) (auto)\n\n    have \"formulaEntailsLiteral (F' @ val2form valuation @ F'') l\"\n    proof-\n      {\n        fix valuation'::Valuation\n        assume \"formulaTrue (F' @ val2form valuation @ F'') valuation'\"\n        hence \"literalTrue l valuation'\"\n          using `[l] el val2form valuation`\n          using formulaTrueIffAllClausesAreTrue[of \"F' @ val2form valuation @ F''\" \"valuation'\"]\n          by (auto simp add: clauseTrueIffContainsTrueLiteral)\n      } thus ?thesis\n        unfolding formulaEntailsLiteral_def\n        by simp\n    qed\n  }\n  thus ?thesis\n    unfolding formulaEntailsValuation_def\n    by simp\nqed\n\n\n(*------------------------------------------------------------------*)\nsubsubsection{* Equivalency *}\n\ntext{* Formulas are equivalent if they have same models. *}\ndefinition equivalentFormulae :: \"Formula \\<Rightarrow> Formula \\<Rightarrow> bool\"\nwhere\n\"equivalentFormulae formula1 formula2 ==\n  \\<forall> (valuation::Valuation). model valuation formula1 = model valuation formula2\"\n\nlemma equivalentFormulaeIffEntailEachOther:\n  fixes formula1 :: Formula and formula2 :: Formula\n  shows \"equivalentFormulae formula1 formula2 = (formulaEntailsFormula formula1 formula2 \\<and> formulaEntailsFormula formula2 formula1)\"\nby (auto simp add:formulaEntailsFormula_def equivalentFormulae_def)\n\nlemma equivalentFormulaeReflexivity: \n  fixes formula :: Formula\n  shows \"equivalentFormulae formula formula\"\nunfolding equivalentFormulae_def\nby auto\n\nlemma equivalentFormulaeSymmetry: \n  fixes formula1 :: Formula and formula2 :: Formula\n  shows \"equivalentFormulae formula1 formula2 = equivalentFormulae formula2 formula1\"\nunfolding equivalentFormulae_def\nby auto\n\nlemma equivalentFormulaeTransitivity: \n  fixes formula1 :: Formula and formula2 :: Formula and formula3 :: Formula\n  assumes \"equivalentFormulae formula1 formula2\" and \"equivalentFormulae formula2 formula3\"\n  shows \"equivalentFormulae formula1 formula3\"\nusing assms\nunfolding equivalentFormulae_def\nby auto\n\nlemma equivalentFormulaeAppend: \n  fixes formula1 :: Formula and formula1' :: Formula and formula2 :: Formula\n  assumes \"equivalentFormulae formula1 formula1'\"\n  shows \"equivalentFormulae (formula1 @ formula2) (formula1' @ formula2)\"\nusing assms\nunfolding equivalentFormulae_def\nby (auto simp add: formulaTrueAppend)\n\nlemma satisfiableEquivalent: \n  fixes formula1 :: Formula and formula2 :: Formula\n  assumes \"equivalentFormulae formula1 formula2\"\n  shows \"satisfiable formula1 = satisfiable formula2\"\nusing assms\nunfolding equivalentFormulae_def\nunfolding satisfiable_def\nby auto\n\nlemma satisfiableEquivalentAppend: \n  fixes formula1 :: Formula and formula1' :: Formula and formula2 :: Formula\n  assumes \"equivalentFormulae formula1 formula1'\" and \"satisfiable (formula1 @ formula2)\"\n  shows \"satisfiable (formula1' @ formula2)\"\nusing assms\nproof -\n  from `satisfiable (formula1 @ formula2)` obtain valuation::Valuation\n    where \"consistent valuation\" \"formulaTrue formula1 valuation\" \"formulaTrue formula2 valuation\"\n    unfolding satisfiable_def\n    by (auto simp add: formulaTrueAppend)\n  from `equivalentFormulae formula1 formula1'` `consistent valuation` `formulaTrue formula1 valuation` \n  have \"formulaTrue formula1' valuation\"\n    unfolding equivalentFormulae_def\n    by auto\n  show ?thesis\n    using `consistent valuation` `formulaTrue formula1' valuation` `formulaTrue formula2 valuation`\n    unfolding satisfiable_def\n    by (auto simp add: formulaTrueAppend)\nqed\n\n\nlemma replaceEquivalentByEquivalent:\n  fixes formula :: Formula and formula' :: Formula and formula1 :: Formula and formula2 :: Formula\n  assumes \"equivalentFormulae formula formula'\" \n  shows \"equivalentFormulae (formula1 @ formula @ formula2) (formula1 @ formula' @ formula2)\"\nunfolding equivalentFormulae_def\nproof\n  fix v :: Valuation\n  show \"model v (formula1 @ formula @ formula2) = model v (formula1 @ formula' @ formula2)\"\n  proof\n    assume \"model v (formula1 @ formula @ formula2)\"\n    hence *: \"consistent v\" \"formulaTrue formula1 v\" \"formulaTrue formula v\" \"formulaTrue formula2 v\"\n      by (auto simp add: formulaTrueAppend)\n    from `consistent v` `formulaTrue formula v` `equivalentFormulae formula formula'`\n    have \"formulaTrue formula' v\"\n      unfolding equivalentFormulae_def\n      by auto\n    thus \"model v (formula1 @ formula' @ formula2)\"\n      using *\n      by (simp add: formulaTrueAppend)\n  next\n    assume \"model v (formula1 @ formula' @ formula2)\"\n    hence *: \"consistent v\" \"formulaTrue formula1 v\" \"formulaTrue formula' v\" \"formulaTrue formula2 v\"\n      by (auto simp add: formulaTrueAppend)\n    from `consistent v` `formulaTrue formula' v` `equivalentFormulae formula formula'`\n    have \"formulaTrue formula v\"\n      unfolding equivalentFormulae_def\n      by auto\n    thus \"model v (formula1 @ formula @ formula2)\"\n      using *\n      by (simp add: formulaTrueAppend)\n  qed\nqed\n\nlemma clauseOrderIrrelevant:\n  shows \"equivalentFormulae (F1 @ F @ F' @ F2) (F1 @ F' @ F @ F2)\"\nunfolding equivalentFormulae_def\nby (auto simp add: formulaTrueIffAllClausesAreTrue)\n\nlemma extendEquivalentFormulaWithEntailedClause:\n  fixes formula1 :: Formula and formula2 :: Formula and clause :: Clause\n  assumes \"equivalentFormulae formula1 formula2\" and \"formulaEntailsClause formula2 clause\"\n  shows \"equivalentFormulae formula1 (formula2 @ [clause])\"\n  unfolding equivalentFormulae_def\nproof\n  fix valuation :: Valuation\n  show \"model valuation formula1 = model valuation (formula2 @ [clause])\"\n  proof\n    assume \"model valuation formula1\"\n    hence \"consistent valuation\"\n      by simp\n    from `model valuation formula1` `equivalentFormulae formula1 formula2`\n    have \"model valuation formula2\"\n      unfolding equivalentFormulae_def\n      by simp\n    moreover\n    from `model valuation formula2` `formulaEntailsClause formula2 clause`\n    have \"clauseTrue clause valuation\"\n      unfolding formulaEntailsClause_def\n      by simp\n    ultimately show\n      \"model valuation (formula2 @ [clause])\"\n      by (simp add: formulaTrueAppend)\n  next\n    assume \"model valuation (formula2 @ [clause])\"\n    hence \"consistent valuation\"\n      by simp\n    from `model valuation (formula2 @ [clause])`\n    have \"model valuation formula2\"\n      by (simp add:formulaTrueAppend)\n    with `equivalentFormulae formula1 formula2`\n    show \"model valuation formula1\"\n      unfolding equivalentFormulae_def\n      by auto\n  qed\nqed\n\nlemma entailsLiteralRelpacePartWithEquivalent:\n  assumes \"equivalentFormulae F F'\" and \"formulaEntailsLiteral (F1 @ F @ F2) l\"\n  shows \"formulaEntailsLiteral (F1 @ F' @ F2) l\"\nproof-\n  {\n    fix v::Valuation\n    assume \"model v (F1 @ F' @ F2)\"\n    hence \"consistent v\" and \"formulaTrue F1 v\" and \"formulaTrue F' v\" and \"formulaTrue F2 v\"\n      by (auto simp add:formulaTrueAppend)\n    with `equivalentFormulae F F'`\n    have \"formulaTrue F v\"\n      unfolding equivalentFormulae_def\n      by auto\n    with `consistent v` `formulaTrue F1 v` `formulaTrue F2 v`\n    have \"model v (F1 @ F @ F2)\"\n      by (auto simp add:formulaTrueAppend)\n    with `formulaEntailsLiteral (F1 @ F @ F2) l`\n    have \"literalTrue l v\"\n      unfolding formulaEntailsLiteral_def\n      by auto\n  }\n  thus ?thesis\n    unfolding formulaEntailsLiteral_def\n    by auto\nqed\n\n\n\n(*--------------------------------------------------------------------------------*)\nsubsubsection{* Remove false and duplicate literals of a clause *}\n\ndefinition\nremoveFalseLiterals :: \"Clause \\<Rightarrow> Valuation \\<Rightarrow> Clause\"\nwhere\n\"removeFalseLiterals clause valuation = filter (\\<lambda> l. \\<not> literalFalse l valuation) clause\"\n\nlemma clauseTrueRemoveFalseLiterals:\n  assumes \"consistent v\"\n  shows \"clauseTrue c v = clauseTrue (removeFalseLiterals c v) v\"\nusing assms\nunfolding removeFalseLiterals_def\nby (auto simp add: clauseTrueIffContainsTrueLiteral inconsistentCharacterization)\n\nlemma clauseTrueRemoveDuplicateLiterals:\n  shows \"clauseTrue c v = clauseTrue (remdups c) v\"\nby (induct c) (auto simp add: clauseTrueIffContainsTrueLiteral)\n\nlemma removeDuplicateLiteralsEquivalentClause:\n  shows \"equivalentFormulae [remdups clause] [clause]\"\nunfolding equivalentFormulae_def\nby (auto simp add: formulaTrueIffAllClausesAreTrue clauseTrueIffContainsTrueLiteral)\n\nlemma falseLiteralsCanBeRemoved:\n(* val2form v - some single literal clauses *)\nfixes F::Formula and F'::Formula and v::Valuation\nassumes \"equivalentFormulae (F1 @ val2form v @ F2) F'\"\nshows \"equivalentFormulae (F1 @ val2form v @ [removeFalseLiterals c v] @ F2) (F' @ [c])\" \n            (is \"equivalentFormulae ?lhs ?rhs\")\nunfolding equivalentFormulae_def\nproof\n  fix v' :: Valuation\n  show \"model v' ?lhs = model v' ?rhs\"\n  proof\n    assume \"model v' ?lhs\"\n    hence \"consistent v'\" and  \n      \"formulaTrue (F1 @ val2form v @ F2) v'\" and \n      \"clauseTrue (removeFalseLiterals c v) v'\"\n      by (auto simp add: formulaTrueAppend formulaTrueIffAllClausesAreTrue)\n\n    from `consistent v'` `formulaTrue (F1 @ val2form v @ F2) v'` `equivalentFormulae (F1 @ val2form v @ F2) F'`\n    have \"model v' F'\"\n      unfolding equivalentFormulae_def\n      by auto\n    moreover\n    from `clauseTrue (removeFalseLiterals c v) v'`\n    have \"clauseTrue c v'\"\n      unfolding removeFalseLiterals_def\n      by (auto simp add: clauseTrueIffContainsTrueLiteral)\n    ultimately\n    show \"model v' ?rhs\"\n      by (simp add: formulaTrueAppend)\n  next\n    assume \"model v' ?rhs\"\n    hence \"consistent v'\" and \"formulaTrue F' v'\" and \"clauseTrue c v'\"\n      by (auto simp add: formulaTrueAppend formulaTrueIffAllClausesAreTrue)\n\n    from `consistent v'` `formulaTrue F' v'` `equivalentFormulae (F1 @ val2form v @ F2) F'`\n    have \"model v' (F1 @ val2form v @ F2)\"\n      unfolding equivalentFormulae_def\n      by auto\n    moreover\n    have \"clauseTrue (removeFalseLiterals c v) v'\"\n    proof-\n      from `clauseTrue c v'` \n      obtain l :: Literal\n        where \"l el c\" and \"literalTrue l v'\"\n        by (auto simp add: clauseTrueIffContainsTrueLiteral)\n      have \"\\<not> literalFalse l v\"\n      proof-\n        {\n          assume \"\\<not> ?thesis\"\n          hence \"opposite l el v\"\n            by simp\n          with `model v' (F1 @ val2form v @ F2)`\n          have \"opposite l el v'\"\n            using val2formFormulaTrue[of \"v\" \"v'\"]\n            by auto (simp add: formulaTrueAppend)\n          with `literalTrue l v'` `consistent v'`\n          have \"False\"\n            by (simp add: inconsistentCharacterization)\n        }\n        thus ?thesis\n          by auto\n      qed\n      with `l el c`\n      have  \"l el (removeFalseLiterals c v)\"\n        unfolding removeFalseLiterals_def\n        by simp\n      with `literalTrue l v'`\n      show ?thesis\n        by (auto simp add: clauseTrueIffContainsTrueLiteral)\n    qed\n    ultimately\n    show \"model v' ?lhs\"\n      by (simp add: formulaTrueAppend)\n  qed\nqed\n\nlemma falseAndDuplicateLiteralsCanBeRemoved:\n(* val2form v - some single literal clauses *)\nassumes \"equivalentFormulae (F1 @ val2form v @ F2) F'\"\nshows \"equivalentFormulae (F1 @ val2form v @ [remdups (removeFalseLiterals c v)] @ F2) (F' @ [c])\" \n  (is \"equivalentFormulae ?lhs ?rhs\")\nproof-\n  from `equivalentFormulae (F1 @ val2form v @ F2) F'` \n  have \"equivalentFormulae (F1 @ val2form v @ [removeFalseLiterals c v] @ F2) (F' @ [c])\"\n    using falseLiteralsCanBeRemoved\n    by simp\n  have \"equivalentFormulae [remdups (removeFalseLiterals c v)] [removeFalseLiterals c v]\"\n    using removeDuplicateLiteralsEquivalentClause\n    by simp\n  hence \"equivalentFormulae (F1 @ val2form v @ [remdups (removeFalseLiterals c v)] @ F2)\n    (F1 @ val2form v @ [removeFalseLiterals c v] @ F2)\"\n    using replaceEquivalentByEquivalent\n    [of \"[remdups (removeFalseLiterals c v)]\" \"[removeFalseLiterals c v]\" \"F1 @ val2form v\" \"F2\"]\n    by auto\n  thus ?thesis\n    using `equivalentFormulae (F1 @ val2form v @ [removeFalseLiterals c v] @ F2) (F' @ [c])`\n    using equivalentFormulaeTransitivity[of \n              \"(F1 @ val2form v @ [remdups (removeFalseLiterals c v)] @ F2)\"\n              \"(F1 @ val2form v @ [removeFalseLiterals c v] @ F2)\" \n              \"F' @ [c]\"]\n    by simp\nqed\n\n\n\nlemma formulaEntailsClauseRemoveEntailedLiteralOpposites:\nassumes\n  \"formulaEntailsClause F clause\"\n  \"formulaEntailsValuation F valuation\"\nshows\n  \"formulaEntailsClause F (list_diff clause (oppositeLiteralList valuation))\"\nproof-\n  {\n    fix valuation'\n    assume \"model valuation' F\"\n    hence \"consistent valuation'\" \"formulaTrue F valuation'\"\n      by (auto simp add: formulaTrueAppend)\n\n    have \"model valuation' clause\"\n      using `consistent valuation'`\n      using `formulaTrue F valuation'`\n      using `formulaEntailsClause F clause`\n      unfolding formulaEntailsClause_def\n      by simp\n\n    then obtain l::Literal\n      where \"l el clause\" \"literalTrue l valuation'\"\n      by (auto simp add: clauseTrueIffContainsTrueLiteral)\n    moreover\n    hence \"\\<not> l el (oppositeLiteralList valuation)\"\n    proof-\n      {\n        assume \"l el (oppositeLiteralList valuation)\"\n        hence \"(opposite l) el valuation\"\n          using literalElListIffOppositeLiteralElOppositeLiteralList[of \"l\" \"oppositeLiteralList valuation\"]\n          by simp\n        hence \"formulaEntailsLiteral F (opposite l)\"\n          using `formulaEntailsValuation F valuation`\n          unfolding formulaEntailsValuation_def\n          by simp\n        hence \"literalFalse l valuation'\"\n          using `consistent valuation'`\n          using `formulaTrue F valuation'`\n          unfolding formulaEntailsLiteral_def\n          by simp\n        with `literalTrue l valuation'`\n          `consistent valuation'`\n        have False\n          by (simp add: inconsistentCharacterization)\n      } thus ?thesis\n        by auto\n    qed\n    ultimately\n    have \"model valuation' (list_diff clause (oppositeLiteralList valuation))\"\n      using `consistent valuation'`\n      using listDiffIff[of \"l\" \"clause\" \"oppositeLiteralList valuation\"]\n      by (auto simp add: clauseTrueIffContainsTrueLiteral)\n  } thus ?thesis\n    unfolding formulaEntailsClause_def\n    by simp\nqed\n\n\n\n(*--------------------------------------------------------------------------------*)\nsubsubsection{* Resolution *}\n\ndefinition\n\"resolve clause1 clause2 literal == removeAll literal clause1 @ removeAll (opposite literal) clause2\"\n\nlemma resolventIsEntailed: \n  fixes clause1 :: Clause and clause2 :: Clause and literal :: Literal\n  shows \"formulaEntailsClause [clause1, clause2] (resolve clause1 clause2 literal)\"\nproof -\n  {\n    fix valuation :: Valuation\n    assume \"model valuation [clause1, clause2]\"\n    from `model valuation [clause1, clause2]` obtain l1 :: Literal\n      where \"l1 el clause1\" and \"literalTrue l1 valuation\"\n      by (auto simp add: formulaTrueIffAllClausesAreTrue clauseTrueIffContainsTrueLiteral)\n    from `model valuation [clause1, clause2]` obtain l2 :: Literal\n      where \"l2 el clause2\" and \"literalTrue l2 valuation\"\n      by (auto simp add: formulaTrueIffAllClausesAreTrue clauseTrueIffContainsTrueLiteral)\n    have \"clauseTrue (resolve clause1 clause2 literal) valuation\"\n    proof (cases \"literal = l1\")\n      case False\n      with `l1 el clause1` \n      have \"l1 el (resolve clause1 clause2 literal)\" \n        by (auto simp add:resolve_def)\n      with `literalTrue l1 valuation` \n      show ?thesis \n        by (auto simp add: clauseTrueIffContainsTrueLiteral)\n    next\n      case True\n      from `model valuation [clause1, clause2]` \n      have \"consistent valuation\" \n        by simp\n      from True `literalTrue l1 valuation` `literalTrue l2 valuation` `consistent valuation` \n      have \"literal \\<noteq> opposite l2\"\n        by (auto simp add:inconsistentCharacterization)\n      with `l2 el clause2` \n      have \"l2 el (resolve clause1 clause2 literal)\"\n        by (auto simp add:resolve_def)\n      with `literalTrue l2 valuation` \n      show ?thesis\n        by (auto simp add: clauseTrueIffContainsTrueLiteral)\n    qed\n  } \n  thus ?thesis \n    by (simp add: formulaEntailsClause_def)\nqed\n\nlemma formulaEntailsResolvent:\n  fixes formula :: Formula and clause1 :: Clause and clause2 :: Clause\n  assumes \"formulaEntailsClause formula clause1\" and \"formulaEntailsClause formula clause2\"\n  shows \"formulaEntailsClause formula (resolve clause1 clause2 literal)\"\nproof -\n  {\n    fix valuation :: Valuation\n    assume \"model valuation formula\"\n    hence \"consistent valuation\" \n      by simp\n    from `model valuation formula` `formulaEntailsClause formula clause1` \n    have \"clauseTrue clause1 valuation\"\n      by (simp add:formulaEntailsClause_def)\n    from `model valuation formula` `formulaEntailsClause formula clause2` \n    have \"clauseTrue clause2 valuation\"\n      by (simp add:formulaEntailsClause_def)\n    from `clauseTrue clause1 valuation` `clauseTrue clause2 valuation` `consistent valuation` \n    have \"clauseTrue (resolve clause1 clause2 literal) valuation\" \n      using resolventIsEntailed\n      by (auto simp add: formulaEntailsClause_def)\n    with `consistent valuation` \n    have \"model valuation (resolve clause1 clause2 literal)\"\n      by simp\n  }\n  thus ?thesis\n    by (simp add: formulaEntailsClause_def)\nqed\n\nlemma resolveFalseClauses:\n  fixes literal :: Literal and clause1 :: Clause and clause2 :: Clause and valuation :: Valuation\n  assumes \n  \"clauseFalse (removeAll literal clause1) valuation\" and\n  \"clauseFalse (removeAll (opposite literal) clause2) valuation\"\n  shows \"clauseFalse (resolve clause1 clause2 literal) valuation\"\nproof -\n  {\n    fix l :: Literal\n    assume \"l el (resolve clause1 clause2 literal)\"\n    have \"literalFalse l valuation\"\n    proof-\n      from `l el (resolve clause1 clause2 literal)` \n      have \"l el (removeAll literal clause1) \\<or> l el (removeAll (opposite literal) clause2)\"\n        unfolding resolve_def\n        by simp\n      thus ?thesis \n      proof\n        assume \"l el (removeAll literal clause1)\"\n        thus \"literalFalse l valuation\"\n          using `clauseFalse (removeAll literal clause1) valuation`\n          by (simp add: clauseFalseIffAllLiteralsAreFalse)\n      next\n        assume \"l el (removeAll (opposite literal) clause2)\"\n        thus \"literalFalse l valuation\"\n          using `clauseFalse (removeAll (opposite literal) clause2) valuation`\n          by (simp add: clauseFalseIffAllLiteralsAreFalse)\n      qed\n    qed\n  }\n  thus ?thesis\n    by (simp add: clauseFalseIffAllLiteralsAreFalse)\nqed\n\n(*--------------------------------------------------------------------------------*)\nsubsubsection{* Unit clauses *}\n\ntext{* Clause is unit in a valuation if all its literals but one are false, and that one is undefined. *}\ndefinition isUnitClause :: \"Clause \\<Rightarrow> Literal \\<Rightarrow> Valuation \\<Rightarrow> bool\"\nwhere\n\"isUnitClause uClause uLiteral valuation == \n   uLiteral el uClause \\<and> \n   \\<not> (literalTrue uLiteral valuation) \\<and> \n   \\<not> (literalFalse uLiteral valuation) \\<and> \n   (\\<forall> literal. literal el uClause \\<and> literal \\<noteq> uLiteral \\<longrightarrow> literalFalse literal valuation)\"\n\n\nlemma unitLiteralIsEntailed:\n  fixes uClause :: Clause and uLiteral :: Literal and formula :: Formula and valuation :: Valuation\n  assumes \"isUnitClause uClause uLiteral valuation\" and \"formulaEntailsClause formula uClause\"\n  shows \"formulaEntailsLiteral (formula @ val2form valuation) uLiteral\"\nproof -\n  {\n    fix valuation'\n    assume \"model valuation' (formula @ val2form valuation)\"\n    hence \"consistent valuation'\"\n      by simp\n    from `model valuation' (formula @ val2form valuation)` \n    have \"formulaTrue formula valuation'\" and \"formulaTrue (val2form valuation) valuation'\"\n      by (auto simp add:formulaTrueAppend)\n    from `formulaTrue formula valuation'` `consistent valuation'` `formulaEntailsClause formula uClause` \n    have \"clauseTrue uClause valuation'\"\n      by (simp add:formulaEntailsClause_def)\n    then obtain l :: Literal\n      where \"l el uClause\" \"literalTrue l valuation'\"\n      by (auto simp add: clauseTrueIffContainsTrueLiteral)\n    hence \"literalTrue uLiteral valuation'\" \n    proof (cases \"l = uLiteral\")\n      case True\n      with `literalTrue l valuation'` \n      show ?thesis\n        by simp\n    next\n      case False\n      with `l el uClause` `isUnitClause uClause uLiteral valuation` \n      have \"literalFalse l valuation\"\n        by (simp add: isUnitClause_def)\n      from `formulaTrue (val2form valuation) valuation'` \n      have \"\\<forall> literal :: Literal. literal el valuation \\<longrightarrow> literal el valuation'\"\n        using val2formFormulaTrue [of \"valuation\" \"valuation'\"]\n        by simp\n      with `literalFalse l valuation` \n      have \"literalFalse l valuation'\"\n        by auto\n      with `literalTrue l valuation'` `consistent valuation'` \n      have \"False\"\n        by (simp add:inconsistentCharacterization)\n      thus ?thesis ..\n    qed\n  }\n  thus ?thesis\n    by (simp add: formulaEntailsLiteral_def)\nqed\n\nlemma isUnitClauseRemoveAllUnitLiteralIsFalse: \n  fixes uClause :: Clause and uLiteral :: Literal and valuation :: Valuation\n  assumes \"isUnitClause uClause uLiteral valuation\"\n  shows \"clauseFalse (removeAll uLiteral uClause) valuation\"\nproof -\n  {\n    fix literal :: Literal\n    assume \"literal el (removeAll uLiteral uClause)\"\n    hence \"literal el uClause\" and \"literal \\<noteq> uLiteral\"\n      by auto\n    with `isUnitClause uClause uLiteral valuation` \n    have \"literalFalse literal valuation\"\n      by (simp add: isUnitClause_def)\n  }\n  thus ?thesis \n    by (simp add: clauseFalseIffAllLiteralsAreFalse)\nqed\n\nlemma isUnitClauseAppendValuation:\n  assumes \"isUnitClause uClause uLiteral valuation\" \"l \\<noteq> uLiteral\" \"l \\<noteq> opposite uLiteral\"\n  shows \"isUnitClause uClause uLiteral (valuation @ [l])\"\nusing assms\nunfolding isUnitClause_def\nby auto\n\nlemma containsTrueNotUnit:\nassumes\n  \"l el c\" and \"literalTrue l v\" and \"consistent v\"\nshows\n  \"\\<not> (\\<exists> ul. isUnitClause c ul v)\"\nusing assms\nunfolding isUnitClause_def\nby (auto simp add: inconsistentCharacterization)\n\nlemma unitBecomesFalse:\nassumes\n  \"isUnitClause uClause uLiteral valuation\" \nshows\n  \"clauseFalse uClause (valuation @ [opposite uLiteral])\"\nusing assms\nusing isUnitClauseRemoveAllUnitLiteralIsFalse[of \"uClause\" \"uLiteral\" \"valuation\"]\nby (auto simp add: clauseFalseIffAllLiteralsAreFalse)\n\n\n(*--------------------------------------------------------------------------------*)\nsubsubsection{* Reason clauses *}\n\ntext{* A clause is @{term reason} for unit propagation of a given literal if it was a unit clause before it \n  is asserted, and became true when it is asserted. *}\n  \ndefinition\nisReason::\"Clause \\<Rightarrow> Literal \\<Rightarrow> Valuation \\<Rightarrow> bool\"\nwhere\n\"(isReason clause literal valuation) ==\n  (literal el clause) \\<and> \n  (clauseFalse (removeAll literal clause) valuation) \\<and>\n  (\\<forall> literal'. literal' el (removeAll literal clause) \n       \\<longrightarrow> precedes (opposite literal') literal valuation \\<and> opposite literal' \\<noteq> literal)\"\n\nlemma isReasonAppend: \n  fixes clause :: Clause and literal :: Literal and valuation :: Valuation and valuation' :: Valuation\n  assumes \"isReason clause literal valuation\" \n  shows \"isReason clause literal (valuation @ valuation')\"\nproof -\n  from assms \n  have \"literal el clause\" and \n    \"clauseFalse (removeAll literal clause) valuation\" (is \"?false valuation\") and\n    \"\\<forall> literal'. literal' el (removeAll literal clause) \\<longrightarrow> \n          precedes (opposite literal') literal valuation \\<and> opposite literal' \\<noteq> literal\" (is \"?precedes valuation\")\n    unfolding isReason_def\n    by auto\n  moreover\n  from  `?false valuation` \n  have \"?false (valuation @ valuation')\"\n    by (rule clauseFalseAppendValuation)\n  moreover\n  from  `?precedes valuation` \n  have \"?precedes (valuation @ valuation')\"\n    by (simp add:precedesAppend)\n  ultimately \n  show ?thesis\n    unfolding isReason_def\n    by auto\nqed\n\nlemma isUnitClauseIsReason: \n  fixes uClause :: Clause and uLiteral :: Literal and valuation :: Valuation\n  assumes \"isUnitClause uClause uLiteral valuation\" \"uLiteral el valuation'\"\n  shows \"isReason uClause uLiteral (valuation @ valuation')\"\nproof -\n  from assms \n  have \"uLiteral el uClause\" and \"\\<not> literalTrue uLiteral valuation\" and \"\\<not> literalFalse uLiteral valuation\"\n    and \"\\<forall> literal. literal el uClause \\<and> literal \\<noteq> uLiteral \\<longrightarrow> literalFalse literal valuation\"\n    unfolding isUnitClause_def\n    by auto\n  hence \"clauseFalse (removeAll uLiteral uClause) valuation\" \n    by (simp add: clauseFalseIffAllLiteralsAreFalse)\n  hence \"clauseFalse (removeAll uLiteral uClause) (valuation @ valuation')\"\n    by (simp add: clauseFalseAppendValuation)\n  moreover\n  have \"\\<forall> literal'. literal' el (removeAll uLiteral uClause) \\<longrightarrow> \n    precedes (opposite literal') uLiteral (valuation @ valuation') \\<and> (opposite literal') \\<noteq> uLiteral\"\n  proof -\n    {\n      fix literal' :: Literal\n      assume \"literal' el (removeAll uLiteral uClause)\"\n      with `clauseFalse (removeAll uLiteral uClause) valuation` \n      have \"literalFalse literal' valuation\"\n        by (simp add:clauseFalseIffAllLiteralsAreFalse)\n      with `\\<not> literalTrue uLiteral valuation` `\\<not> literalFalse uLiteral valuation`\n      have \"precedes (opposite literal') uLiteral (valuation @ valuation') \\<and> (opposite literal') \\<noteq> uLiteral\"\n        using `uLiteral el valuation'`\n        using precedesMemberHeadMemberTail [of \"opposite literal'\" \"valuation\" \"uLiteral\" \"valuation'\"]\n        by auto\n    }\n    thus ?thesis \n      by simp\n  qed\n  ultimately\n  show ?thesis using `uLiteral el uClause`\n    by (auto simp add: isReason_def)\nqed\n\nlemma isReasonHoldsInPrefix: \n  fixes prefix :: Valuation and valuation :: Valuation and clause :: Clause and literal :: Literal\n  assumes \n  \"literal el prefix\" and \n  \"isPrefix prefix valuation\" and \n  \"isReason clause literal valuation\"\n  shows \n  \"isReason clause literal prefix\"\nproof -\n  from `isReason clause literal valuation` \n  have\n    \"literal el clause\" and \n    \"clauseFalse (removeAll literal clause) valuation\" (is \"?false valuation\") and\n    \"\\<forall> literal'. literal' el (removeAll literal clause) \\<longrightarrow> \n         precedes (opposite literal') literal valuation \\<and> opposite literal' \\<noteq> literal\" (is \"?precedes valuation\")\n    unfolding isReason_def\n    by auto\n  {\n    fix literal' :: Literal\n    assume \"literal' el (removeAll literal clause)\"\n    with `?precedes valuation` \n    have \"precedes (opposite literal') literal valuation\" \"(opposite literal') \\<noteq> literal\"\n      by auto\n    with `literal el prefix` `isPrefix prefix valuation`\n    have \"precedes (opposite literal') literal prefix \\<and> (opposite literal') \\<noteq> literal\" \n      using laterInPrefixRetainsPrecedes [of \"prefix\" \"valuation\" \"opposite literal'\" \"literal\"]\n      by auto\n  } \n  note * = this\n  hence \"?precedes prefix\"\n    by auto\n  moreover\n  have \"?false prefix\" \n  proof -\n    {\n      fix literal' :: Literal\n      assume \"literal' el (removeAll literal clause)\"\n      from `literal' el (removeAll literal clause)` * \n      have \"precedes (opposite literal') literal prefix\"\n        by simp\n      with `literal el prefix` \n      have \"literalFalse literal' prefix\"\n        unfolding precedes_def\n        by (auto split: split_if_asm)\n    }\n    thus ?thesis\n      by (auto simp add:clauseFalseIffAllLiteralsAreFalse)\n  qed\n  ultimately\n  show ?thesis using `literal el clause`\n    unfolding isReason_def\n    by auto\nqed\n\n\n(*--------------------------------------------------------------------------------*)\nsubsubsection{* Last asserted literal of a list *}\n\ntext{* @{term lastAssertedLiteral} from a list is the last literal from a clause that is asserted in \n  a valuation. *}\ndefinition \nisLastAssertedLiteral::\"Literal \\<Rightarrow> Literal list \\<Rightarrow> Valuation \\<Rightarrow> bool\"\nwhere\n\"isLastAssertedLiteral literal clause valuation ==\n  literal el clause \\<and> \n  literalTrue literal valuation \\<and> \n  (\\<forall> literal'. literal' el clause \\<and> literal' \\<noteq> literal \\<longrightarrow> \\<not> precedes literal literal' valuation)\"\n\ntext{* Function that gets the last asserted literal of a list - specified only by its postcondition. *}\ndefinition\ngetLastAssertedLiteral :: \"Literal list \\<Rightarrow> Valuation \\<Rightarrow> Literal\"\nwhere\n\"getLastAssertedLiteral clause valuation == \n   last (filter (\\<lambda> l::Literal. l el clause) valuation)\"\n\nlemma getLastAssertedLiteralCharacterization:\nassumes\n  \"clauseFalse clause valuation\"\n  \"clause \\<noteq> []\"\n  \"uniq valuation\"\nshows\n  \"isLastAssertedLiteral (getLastAssertedLiteral (oppositeLiteralList clause) valuation) (oppositeLiteralList clause) valuation\"\nproof-\n  let ?oppc = \"oppositeLiteralList clause\"\n  let ?l = \"getLastAssertedLiteral ?oppc valuation\"\n  let ?f = \"filter (\\<lambda> l. l el ?oppc) valuation\"\n\n  have \"?oppc \\<noteq> []\" \n    using `clause \\<noteq> []`\n    using oppositeLiteralListNonempty[of \"clause\"]\n    by simp\n  then obtain l'::Literal\n    where \"l' el ?oppc\"\n    by force\n  \n  have \"\\<forall> l::Literal. l el ?oppc \\<longrightarrow> l el valuation\"\n  proof\n    fix l::Literal\n    show \"l el ?oppc \\<longrightarrow> l el valuation\"\n    proof\n      assume \"l el ?oppc\"\n      hence \"opposite l el clause\"\n        using literalElListIffOppositeLiteralElOppositeLiteralList[of \"l\" \"?oppc\"]\n        by simp\n      thus \"l el valuation\"\n        using `clauseFalse clause valuation`\n        using clauseFalseIffAllLiteralsAreFalse[of \"clause\" \"valuation\"]\n        by auto\n    qed\n  qed\n  hence \"l' el valuation\"\n    using `l' el ?oppc`\n    by simp\n  hence \"l' el ?f\"\n    using `l' el ?oppc`\n    by simp\n  hence \"?f \\<noteq> []\"\n    using set_empty[of \"?f\"]\n    by auto\n  hence \"last ?f el ?f\"\n    using last_in_set[of \"?f\"]\n    by simp\n  hence \"?l el ?oppc\" \"literalTrue ?l valuation\"\n    unfolding getLastAssertedLiteral_def\n    by auto\n  moreover\n  have \"\\<forall>literal'. literal' el ?oppc \\<and> literal' \\<noteq> ?l \\<longrightarrow>\n                    \\<not> precedes ?l literal' valuation\"\n  proof\n    fix literal'\n    show \"literal' el ?oppc \\<and> literal' \\<noteq> ?l \\<longrightarrow> \\<not> precedes ?l literal' valuation\"\n    proof\n      assume \"literal' el ?oppc \\<and> literal' \\<noteq> ?l\"\n      show \"\\<not> precedes ?l literal' valuation\"\n      proof (cases \"literalTrue literal' valuation\")\n        case False\n        thus ?thesis\n          unfolding precedes_def\n          by simp\n      next\n        case True\n        with `literal' el ?oppc \\<and> literal' \\<noteq> ?l`\n        have \"literal' el ?f\"\n          by simp\n        have \"uniq ?f\"\n          using `uniq valuation`\n          by (simp add: uniqDistinct)\n        hence \"\\<not> precedes ?l literal' ?f\"\n          using lastPrecedesNoElement[of \"?f\"]\n          using `literal' el ?oppc \\<and> literal' \\<noteq> ?l`\n          unfolding getLastAssertedLiteral_def\n          by auto\n        thus ?thesis\n          using precedesFilter[of \"?l\" \"literal'\" \"valuation\" \"\\<lambda> l. l el ?oppc\"]\n          using `literal' el ?oppc \\<and> literal' \\<noteq> ?l`\n          using `?l el ?oppc`\n          by auto\n      qed\n    qed\n  qed\n  ultimately\n  show ?thesis\n    unfolding isLastAssertedLiteral_def\n    by simp\nqed\n\nlemma lastAssertedLiteralIsUniq: \n  fixes literal :: Literal and literal' :: Literal and literalList :: \"Literal list\" and valuation :: Valuation\n  assumes \n  lastL: \"isLastAssertedLiteral literal  literalList valuation\" and\n  lastL': \"isLastAssertedLiteral literal' literalList valuation\"\n  shows \"literal = literal'\"\nusing assms\nproof -\n  from lastL have *: \n    \"literal el literalList\"  \n    \"\\<forall> l. l el literalList \\<and> l \\<noteq> literal \\<longrightarrow> \\<not>  precedes literal l valuation\" \n    and\n    \"literalTrue literal valuation\"  \n    by (auto simp add: isLastAssertedLiteral_def)\n  from lastL' have **: \n    \"literal' el literalList\"\n    \"\\<forall> l. l el literalList \\<and> l \\<noteq> literal' \\<longrightarrow> \\<not>  precedes literal' l valuation\"\n    and\n    \"literalTrue literal' valuation\"\n    by (auto simp add: isLastAssertedLiteral_def)\n  {\n    assume \"literal' \\<noteq> literal\"\n    with * ** have \"\\<not> precedes literal literal' valuation\" and \"\\<not> precedes literal' literal valuation\"\n      by auto\n    with `literalTrue literal valuation` `literalTrue literal' valuation` \n    have \"False\"\n      using precedesTotalOrder[of \"literal\" \"valuation\" \"literal'\"]\n      unfolding precedes_def\n      by simp\n  }\n  thus ?thesis\n    by auto\nqed\n\nlemma isLastAssertedCharacterization: \n  fixes literal :: Literal and literalList :: \"Literal list\" and v :: Valuation\n  assumes \"isLastAssertedLiteral literal (oppositeLiteralList literalList) valuation\"\n  shows \"opposite literal el literalList\" and \"literalTrue literal valuation\"\nproof -\n  from assms have\n    *: \"literal el (oppositeLiteralList literalList)\" and **: \"literalTrue literal valuation\"  \n    by (auto simp add: isLastAssertedLiteral_def)\n  from * show \"opposite literal el literalList\"\n    using literalElListIffOppositeLiteralElOppositeLiteralList [of \"literal\" \"oppositeLiteralList literalList\"]\n    by simp\n  from ** show \"literalTrue literal valuation\" \n    by simp\nqed\n\nlemma isLastAssertedLiteralSubset:\nassumes\n  \"isLastAssertedLiteral l c M\"\n  \"set c' \\<subseteq> set c\"\n  \"l el c'\"\nshows\n  \"isLastAssertedLiteral l c' M\"\nusing assms\nunfolding isLastAssertedLiteral_def\nby auto\n\nlemma lastAssertedLastInValuation: \n  fixes literal :: Literal and literalList :: \"Literal list\" and valuation :: Valuation\n  assumes \"literal el literalList\" and \"\\<not> literalTrue literal valuation\" \n  shows \"isLastAssertedLiteral literal literalList (valuation @ [literal])\"\nproof -\n  have \"literalTrue literal [literal]\" \n    by simp\n  hence \"literalTrue literal (valuation @ [literal])\"\n    by simp\n  moreover\n  have \"\\<forall> l. l el literalList \\<and> l \\<noteq> literal \\<longrightarrow> \\<not>  precedes literal l (valuation @ [literal])\"\n  proof -\n    {\n      fix l\n      assume \"l el literalList\" \"l \\<noteq> literal\"\n      have \"\\<not> precedes literal l (valuation @ [literal])\" \n      proof (cases \"literalTrue l valuation\")\n        case False\n        with `l \\<noteq> literal` \n        show ?thesis\n          unfolding precedes_def\n          by simp\n      next\n        case True\n        from `\\<not> literalTrue literal valuation` `literalTrue literal [literal]` `literalTrue l valuation` \n        have \"precedes l literal (valuation @ [literal])\"\n          using precedesMemberHeadMemberTail[of \"l\" \"valuation\" \"literal\" \"[literal]\"]\n          by auto\n        with `l \\<noteq> literal` `literalTrue l valuation` `literalTrue literal [literal]`\n        show ?thesis\n          using precedesAntisymmetry[of \"l\" \"valuation @ [literal]\" \"literal\"]\n          unfolding precedes_def\n          by auto\n      qed\n    } thus ?thesis \n      by simp\n  qed\n  ultimately\n  show ?thesis using `literal el literalList`\n    by (simp add:isLastAssertedLiteral_def)\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/SATSolverVerification/CNF.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8577681122619885, "lm_q2_score": 0.863391595913457, "lm_q1q2_score": 0.7405897793695516}}
{"text": "(*  Title:      HOL/Induct/ABexp.thy\n    Author:     Stefan Berghofer, TU Muenchen\n*)\n\nsection \\<open>Arithmetic and boolean expressions\\<close>\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 \\<open>\\medskip Evaluation of arithmetic and boolean expressions\\<close>\n\nprimrec evala :: \"('a \\<Rightarrow> nat) \\<Rightarrow> 'a aexp \\<Rightarrow> nat\"\n  and evalb :: \"('a \\<Rightarrow> nat) \\<Rightarrow> 'a bexp \\<Rightarrow> 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 \\<open>\\medskip Substitution on arithmetic and boolean expressions\\<close>\n\nprimrec substa :: \"('a \\<Rightarrow> 'b aexp) \\<Rightarrow> 'a aexp \\<Rightarrow> 'b aexp\"\n  and substb :: \"('a \\<Rightarrow> 'b aexp) \\<Rightarrow> 'a bexp \\<Rightarrow> '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    \\<comment> \\<open>one variable\\<close>\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": "seL4", "repo": "isabelle", "sha": "e1ab32a3bb41728cd19541063283e37919978a4c", "save_path": "github-repos/isabelle/seL4-isabelle", "path": "github-repos/isabelle/seL4-isabelle/isabelle-e1ab32a3bb41728cd19541063283e37919978a4c/src/HOL/Induct/ABexp.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9136765257642906, "lm_q2_score": 0.8104789086703225, "lm_q1q2_score": 0.740515553479134}}
{"text": "(*  Title:      HOL/Induct/Comb.thy\n    Author:     Lawrence C Paulson\n    Copyright   1996  University of Cambridge\n*)\n\nsection {* Combinatory Logic example: the Church-Rosser Theorem *}\n\ntheory Comb imports Main begin\n\ntext {*\n  Curiously, combinators do not include free variables.\n\n  Example taken from @{cite camilleri92}.\n\nHOL system proofs may be found in the HOL distribution at\n   .../contrib/rule-induction/cl.ml\n*}\n\nsubsection {* Definitions *}\n\ntext {* Datatype definition of combinators @{text S} and @{text K}. *}\n\ndatatype comb = K\n              | S\n              | Ap comb comb (infixl \"##\" 90)\n\nnotation (xsymbols)\n  Ap  (infixl \"\\<bullet>\" 90)\n\n\ntext {*\n  Inductive definition of contractions, @{text \"-1->\"} and\n  (multi-step) reductions, @{text \"--->\"}.\n*}\n\ninductive_set\n  contract :: \"(comb*comb) set\"\n  and contract_rel1 :: \"[comb,comb] => bool\"  (infixl \"-1->\" 50)\n  where\n    \"x -1-> y == (x,y) \\<in> contract\"\n   | K:     \"K##x##y -1-> x\"\n   | S:     \"S##x##y##z -1-> (x##z)##(y##z)\"\n   | Ap1:   \"x-1->y ==> x##z -1-> y##z\"\n   | Ap2:   \"x-1->y ==> z##x -1-> z##y\"\n\nabbreviation\n  contract_rel :: \"[comb,comb] => bool\"   (infixl \"--->\" 50) where\n  \"x ---> y == (x,y) \\<in> contract^*\"\n\ntext {*\n  Inductive definition of parallel contractions, @{text \"=1=>\"} and\n  (multi-step) parallel reductions, @{text \"===>\"}.\n*}\n\ninductive_set\n  parcontract :: \"(comb*comb) set\"\n  and parcontract_rel1 :: \"[comb,comb] => bool\"  (infixl \"=1=>\" 50)\n  where\n    \"x =1=> y == (x,y) \\<in> parcontract\"\n  | refl:  \"x =1=> x\"\n  | K:     \"K##x##y =1=> x\"\n  | S:     \"S##x##y##z =1=> (x##z)##(y##z)\"\n  | Ap:    \"[| x=1=>y;  z=1=>w |] ==> x##z =1=> y##w\"\n\nabbreviation\n  parcontract_rel :: \"[comb,comb] => bool\"   (infixl \"===>\" 50) where\n  \"x ===> y == (x,y) \\<in> parcontract^*\"\n\ntext {*\n  Misc definitions.\n*}\n\ndefinition\n  I :: comb where\n  \"I = S##K##K\"\n\ndefinition\n  diamond   :: \"('a * 'a)set => bool\" where\n    --{*confluence; Lambda/Commutation treats this more abstractly*}\n  \"diamond(r) = (\\<forall>x y. (x,y) \\<in> r --> \n                  (\\<forall>y'. (x,y') \\<in> r --> \n                    (\\<exists>z. (y,z) \\<in> r & (y',z) \\<in> r)))\"\n\n\nsubsection {*Reflexive/Transitive closure preserves Church-Rosser property*}\n\ntext{*So does the Transitive closure, with a similar proof*}\n\ntext{*Strip lemma.  \n   The induction hypothesis covers all but the last diamond of the strip.*}\nlemma diamond_strip_lemmaE [rule_format]: \n    \"[| diamond(r);  (x,y) \\<in> r^* |] ==>   \n          \\<forall>y'. (x,y') \\<in> r --> (\\<exists>z. (y',z) \\<in> r^* & (y,z) \\<in> r)\"\napply (unfold diamond_def)\napply (erule rtrancl_induct)\napply (meson rtrancl_refl)\napply (meson rtrancl_trans r_into_rtrancl)\ndone\n\nlemma diamond_rtrancl: \"diamond(r) ==> diamond(r^*)\"\napply (simp (no_asm_simp) add: diamond_def)\napply (rule impI [THEN allI, THEN allI])\napply (erule rtrancl_induct, blast)\napply (meson rtrancl_trans r_into_rtrancl diamond_strip_lemmaE)\ndone\n\n\nsubsection {* Non-contraction results *}\n\ntext {* Derive a case for each combinator constructor. *}\n\ninductive_cases\n      K_contractE [elim!]: \"K -1-> r\"\n  and S_contractE [elim!]: \"S -1-> r\"\n  and Ap_contractE [elim!]: \"p##q -1-> r\"\n\ndeclare contract.K [intro!] contract.S [intro!]\ndeclare contract.Ap1 [intro] contract.Ap2 [intro]\n\nlemma I_contract_E [elim!]: \"I -1-> z ==> P\"\nby (unfold I_def, blast)\n\nlemma K1_contractD [elim!]: \"K##x -1-> z ==> (\\<exists>x'. z = K##x' & x -1-> x')\"\nby blast\n\nlemma Ap_reduce1 [intro]: \"x ---> y ==> x##z ---> y##z\"\napply (erule rtrancl_induct)\napply (blast intro: rtrancl_trans)+\ndone\n\nlemma Ap_reduce2 [intro]: \"x ---> y ==> z##x ---> z##y\"\napply (erule rtrancl_induct)\napply (blast intro: rtrancl_trans)+\ndone\n\ntext {*Counterexample to the diamond property for @{term \"x -1-> y\"}*}\n\nlemma not_diamond_contract: \"~ diamond(contract)\"\nby (unfold diamond_def, metis S_contractE contract.K) \n\n\nsubsection {* Results about Parallel Contraction *}\n\ntext {* Derive a case for each combinator constructor. *}\n\ninductive_cases\n      K_parcontractE [elim!]: \"K =1=> r\"\n  and S_parcontractE [elim!]: \"S =1=> r\"\n  and Ap_parcontractE [elim!]: \"p##q =1=> r\"\n\ndeclare parcontract.intros [intro]\n\n(*** Basic properties of parallel contraction ***)\n\nsubsection {* Basic properties of parallel contraction *}\n\nlemma K1_parcontractD [dest!]: \"K##x =1=> z ==> (\\<exists>x'. z = K##x' & x =1=> x')\"\nby blast\n\nlemma S1_parcontractD [dest!]: \"S##x =1=> z ==> (\\<exists>x'. z = S##x' & x =1=> x')\"\nby blast\n\nlemma S2_parcontractD [dest!]:\n     \"S##x##y =1=> z ==> (\\<exists>x' y'. z = S##x'##y' & x =1=> x' & y =1=> y')\"\nby blast\n\ntext{*The rules above are not essential but make proofs much faster*}\n\ntext{*Church-Rosser property for parallel contraction*}\nlemma diamond_parcontract: \"diamond parcontract\"\napply (unfold diamond_def)\napply (rule impI [THEN allI, THEN allI])\napply (erule parcontract.induct, fast+)\ndone\n\ntext {*\n  \\medskip Equivalence of @{prop \"p ---> q\"} and @{prop \"p ===> q\"}.\n*}\n\nlemma contract_subset_parcontract: \"contract <= parcontract\"\nby (auto, erule contract.induct, blast+)\n\ntext{*Reductions: simply throw together reflexivity, transitivity and\n  the one-step reductions*}\n\ndeclare r_into_rtrancl [intro]  rtrancl_trans [intro]\n\n(*Example only: not used*)\nlemma reduce_I: \"I##x ---> x\"\nby (unfold I_def, blast)\n\nlemma parcontract_subset_reduce: \"parcontract <= contract^*\"\nby (auto, erule parcontract.induct, blast+)\n\nlemma reduce_eq_parreduce: \"contract^* = parcontract^*\"\nby (metis contract_subset_parcontract parcontract_subset_reduce rtrancl_subset)\n\ntheorem diamond_reduce: \"diamond(contract^*)\"\nby (simp add: reduce_eq_parreduce diamond_rtrancl diamond_parcontract)\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/Comb.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511506439708, "lm_q2_score": 0.8652240964782011, "lm_q1q2_score": 0.7405030385357584}}
{"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\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\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  unfolding divide_complex_def times_complex.sel inverse_complex.sel\n  by (simp 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 [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 Reals\\<close>\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\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 divide_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 divide_simps power2_eq_square del: of_nat_Suc)\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 complex_Im_fact [simp]: \"Im (fact n) = 0\"\n  by (subst of_nat_fact [symmetric]) (simp only: complex_Im_of_nat)\n\n\nsubsection \\<open>The Complex Number $i$\\<close>\n\nprimcorec \"ii\" :: complex  (\"\\<i>\")\n  where\n    \"Re \\<i> = 0\"\n  | \"Im \\<i> = 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]: \"\\<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 Re_ii_times [simp]: \"Re (\\<i> * z) = - Im z\"\n  by simp\n\nlemma Im_ii_times [simp]: \"Im (\\<i> * z) = Re z\"\n  by simp\n\nlemma ii_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\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:{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  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)\\<^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 divide_simps complex_eq_iff)\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\ninstantiation complex :: field_abs_sgn\nbegin\n\ndefinition abs_complex :: \"complex \\<Rightarrow> complex\"\n  where \"abs_complex = of_real \\<circ> norm\"\n\ninstance\n  apply standard\n         apply (auto simp add: abs_complex_def complex_sgn_def norm_mult)\n  apply (auto simp add: scaleR_conv_of_real field_simps)\n  done\n\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]\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  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 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 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))) \\<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 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_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 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 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\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\n\nsubsection \\<open>Basic Lemmas\\<close>\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: \"r \\<in> Reals \\<Longrightarrow> Re (z / r) = Re z / Re r\"\n  by (metis Re_divide_of_real of_real_Re)\n\nlemma Im_divide_Reals: \"r \\<in> Reals \\<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 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 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    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\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_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: 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\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\n\nsubsubsection \\<open>Complex exponential\\<close>\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: 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\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)\n\nlemma complex_exp_exists: \"\\<exists>a r. z = complex_of_real r * exp a\"\n  apply (insert rcis_Ex [of z])\n  apply (auto simp add: exp_eq_polar rcis_def mult.assoc [symmetric])\n  apply (rule_tac x = \"\\<i> * complex_of_real a\" in exI)\n  apply auto\n  done\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\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 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 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\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_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 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 = \\<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_cn: \"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 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": "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/Complex.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8558511359371249, "lm_q2_score": 0.865224091265267, "lm_q1q2_score": 0.7405030213495454}}
{"text": "theory Interest\n  imports Preliminaries\nbegin\n\n\nsection \\<open>List of Actuarial Notations (Global Scope)\\<close>\n\ndefinition i_nom :: \"real \\<Rightarrow> nat \\<Rightarrow> real\" (\"$i[_]^{_}\" [0,0] 200)\n  where \"$i[i]^{m} \\<equiv> m * ((1+i).^(1/m) - 1)\"  \\<comment> \\<open>nominal interest rate\\<close>\ndefinition i_force :: \"real \\<Rightarrow> real\" (\"$\\<delta>[_]\" [0] 200)\n  where \"$\\<delta>[i] \\<equiv> ln (1+i)\" \\<comment> \\<open>force of interest\\<close>\ndefinition d_nom :: \"real \\<Rightarrow> nat \\<Rightarrow> real\" (\"$d[_]^{_}\" [0,0] 200)\n  where \"$d[i]^{m} \\<equiv> $i[i]^{m} / (1 + $i[i]^{m}/m)\"  \\<comment> \\<open>discount rate\\<close> \nabbreviation d_nom_yr :: \"real \\<Rightarrow> real\" (\"$d[_]\" [0] 200)\n  where \"$d[i] \\<equiv> $d[i]^{1}\"  \\<comment> \\<open>Post-fix \"yr\" stands for \"year\".\\<close>\ndefinition v_pres :: \"real \\<Rightarrow> real\" (\"$v[_]\" [0] 200)\n  where \"$v[i] \\<equiv> 1 / (1+i)\"  \\<comment> \\<open>present value factor\\<close>\ndefinition ann :: \"real \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> real\" (\"$a[_]^{_}'__\" [0,0,101] 200)\n  where \"$a[i]^{m}_n \\<equiv> \\<Sum>k<n*m. $v[i].^((k+1::nat)/m) / m\"\n    \\<comment> \\<open>present value of an immediate annuity\\<close>\nabbreviation ann_yr :: \"real \\<Rightarrow> nat \\<Rightarrow> real\" (\"$a[_]'__\" [0,101] 200)\n  where \"$a[i]_n \\<equiv> $a[i]^{1}_n\"\ndefinition acc :: \"real \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> real\" (\"$s[_]^{_}'__\" [0,0,101] 200)\n  where \"$s[i]^{m}_n \\<equiv> \\<Sum>k<n*m. (1+i).^((k::nat)/m) / m\"\n    \\<comment> \\<open>future value of an immediate annuity\\<close>\n    \\<comment> \\<open>The name \"acc\" stands for \"accumulation\".\\<close>\nabbreviation acc_yr :: \"real \\<Rightarrow> nat \\<Rightarrow> real\" (\"$s[_]'__\" [0] 200)\n  where \"$s[i]_n \\<equiv> $s[i]^{1}_n\"\ndefinition ann_due :: \"real \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> real\" (\"$a''''[_]^{_}'__\" [0,0,101] 200)\n  where \"$a''[i]^{m}_n \\<equiv> \\<Sum>k<n*m. $v[i].^((k::nat)/m) / m\"\n    \\<comment> \\<open>present value of an annuity-due\\<close>\nabbreviation ann_due_yr :: \"real \\<Rightarrow> nat \\<Rightarrow> real\" (\"$a''''[_]'__\" [0,101] 200)\n  where \"$a''[i]_n \\<equiv> $a''[i]^{1}_n\"\ndefinition acc_due :: \"real \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> real\" (\"$s''''[_]^{_}'__\" [0,0,101] 200)\n  where \"$s''[i]^{m}_n \\<equiv> \\<Sum>k<n*m. (1+i).^((k+1::nat)/m) / m\"\n    \\<comment> \\<open>future value of an annuity-due\\<close>\nabbreviation acc_due_yr :: \"real \\<Rightarrow> nat \\<Rightarrow> real\" (\"$s''''[_]'__\" [0,101] 200)\n  where \"$s''[i]_n \\<equiv> $s''[i]^{1}_n\"\ndefinition ann_cont :: \"real \\<Rightarrow> real \\<Rightarrow> real\" (\"$a''[_]'__\" [0,101] 200)\n  where \"$a'[i]_n \\<equiv> integral {0..n} (\\<lambda>t::real. $v[i].^t)\"\n    \\<comment> \\<open>present value of a continuous annuity\\<close>\ndefinition acc_cont :: \"real \\<Rightarrow> real \\<Rightarrow> real\" (\"$s''[_]'__\" [0,101] 200)\n  where \"$s'[i]_n \\<equiv> integral {0..n} (\\<lambda>t::real. (1+i).^t)\"\n    \\<comment> \\<open>future value of a continuous annuity\\<close>\ndefinition perp :: \"real \\<Rightarrow> nat \\<Rightarrow> real\" (\"$a[_]^{_}'_\\<infinity>\" [0,0] 200)\n  where \"$a[i]^{m}_\\<infinity> \\<equiv> 1 / $i[i]^{m}\"\n    \\<comment> \\<open>present value of a perpetual annuity\\<close>\nabbreviation perp_yr :: \"real \\<Rightarrow> real\" (\"$a[_]'_\\<infinity>\" [0] 200)\n  where \"$a[i]_\\<infinity> \\<equiv> $a[i]^{1}_\\<infinity>\"\ndefinition perp_due :: \"real \\<Rightarrow> nat \\<Rightarrow> real\" (\"$a''''[_]^{_}'_\\<infinity>\" [0,0] 200)\n  where \"$a''[i]^{m}_\\<infinity> \\<equiv> 1 / $d[i]^{m}\"\n    \\<comment> \\<open>present value of a perpetual annuity-due\\<close>\nabbreviation perp_due_yr :: \"real \\<Rightarrow> real\" (\"$a''''[_]'_\\<infinity>\" [0] 200)\n  where \"$a''[i]_\\<infinity> \\<equiv> $a''[i]^{1}_\\<infinity>\"\ndefinition ann_incr :: \"nat \\<Rightarrow> real \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> real\"\n  (\"$'(I^{_}a')[_]^{_}'__\" [0,0,0,101] 200)\n  where \"$(I^{l}a)[i]^{m}_n \\<equiv> \\<Sum>k<n*m. $v[i].^((k+1::nat)/m) * \\<lceil>l*(k+1::nat)/m\\<rceil> / (l*m)\"\n    \\<comment> \\<open>present value of an increasing annuity\\<close>\n    \\<comment> \\<open>This is my original definition.\\<close>\n    \\<comment> \\<open>Here, \"l\" represents the number of increments per unit time.\\<close>\nabbreviation ann_incr_lvl :: \"real \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> real\"\n  (\"$'(Ia')[_]^{_}'__\" [0,0,101] 200)\n  where \"$(Ia)[i]^{m}_n \\<equiv> $(I^{1}a)[i]^{m}_n\"\n    \\<comment> \\<open>The post-fix \"lvl\" stands for \"level\".\\<close>\nabbreviation ann_incr_yr :: \"real \\<Rightarrow> nat \\<Rightarrow> real\" (\"$'(Ia')[_]'__\" [0,101] 200)\n  where \"$(Ia)[i]_n \\<equiv> $(Ia)[i]^{1}_n\"\ndefinition acc_incr :: \"nat \\<Rightarrow> real \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> real\"\n  (\"$'(I^{_}s')[_]^{_}'__\" [0,0,0,101] 200)\n  where \"$(I^{l}s)[i]^{m}_n \\<equiv> \\<Sum>k<n*m. (1+i).^(n-(k+1::nat)/m) * \\<lceil>l*(k+1::nat)/m\\<rceil> / (l*m)\"\n    \\<comment> \\<open>future value of an increasing annuity\\<close>\nabbreviation acc_incr_lvl :: \"real \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> real\"\n  (\"$'(Is')[_]^{_}'__\" [0,0,101] 200)\n  where \"$(Is)[i]^{m}_n \\<equiv> $(I^{1}s)[i]^{m}_n\"\nabbreviation acc_incr_yr :: \"real \\<Rightarrow> nat \\<Rightarrow> real\" (\"$'(Is')[_]'__\" [0,101] 200)\n  where \"$(Is)[i]_n \\<equiv> $(Is)[i]^{1}_n\"\ndefinition ann_due_incr :: \"nat \\<Rightarrow> real \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> real\"\n  (\"$'(I^{_}a''''')[_]^{_}'__\" [0,0,0,101] 200)\n  where \"$(I^{l}a'')[i]^{m}_n \\<equiv> \\<Sum>k<n*m. $v[i].^((k::nat)/m) * \\<lceil>l*(k+1::nat)/m\\<rceil> / (l*m)\"\nabbreviation ann_due_incr_lvl :: \"real \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> real\"\n  (\"$'(Ia''''')[_]^{_}'__\" [0,0,101] 200)\n  where \"$(Ia'')[i]^{m}_n \\<equiv> $(I^{1}a'')[i]^{m}_n\"\nabbreviation ann_due_incr_yr :: \"real \\<Rightarrow> nat \\<Rightarrow> real\" (\"$'(Ia''''')[_]'__\" [0,101] 200)\n  where \"$(Ia'')[i]_n \\<equiv> $(Ia'')[i]^{1}_n\"\ndefinition acc_due_incr :: \"nat \\<Rightarrow> real \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> real\"\n  (\"$'(I^{_}s''''')[_]^{_}'__\" [0,0,0,101] 200)\n  where \"$(I^{l}s'')[i]^{m}_n \\<equiv> \\<Sum>k<n*m. (1+i).^(n-(k::nat)/m) * \\<lceil>l*(k+1::nat)/m\\<rceil> / (l*m)\"\nabbreviation acc_due_incr_lvl :: \"real \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> real\"\n  (\"$'(Is''''')[_]^{_}'__\" [0,0,101] 200)\n  where \"$(Is'')[i]^{m}_n \\<equiv> $(I^{1}s'')[i]^{m}_n\"\nabbreviation acc_due_incr_yr :: \"real \\<Rightarrow> nat \\<Rightarrow> real\" (\"$'(Is''''')[_]'__\" [0,101] 200)\n  where \"$(Is'')[i]_n \\<equiv> $(Is'')[i]^{1}_n\"\ndefinition perp_incr :: \"nat \\<Rightarrow> real \\<Rightarrow> nat \\<Rightarrow> real\" (\"$'(I^{_}a')[_]^{_}'_\\<infinity>\" [0,0,0] 200)\n  where \"$(I^{l}a)[i]^{m}_\\<infinity> \\<equiv> lim (\\<lambda>n. $(I^{l}a)[i]^{m}_n)\"\nabbreviation perp_incr_lvl :: \"real \\<Rightarrow> nat \\<Rightarrow> real\" (\"$'(Ia')[_]^{_}'_\\<infinity>\" [0,0] 200)\n  where \"$(Ia)[i]^{m}_\\<infinity> \\<equiv> $(I^{1}a)[i]^{m}_\\<infinity>\"\nabbreviation perp_incr_yr :: \"real \\<Rightarrow> real\" (\"$'(Ia')[_]'_\\<infinity>\" [0] 200)\n  where \"$(Ia)[i]_\\<infinity> \\<equiv> $(Ia)[i]^{1}_\\<infinity>\"\ndefinition perp_due_incr :: \"nat \\<Rightarrow> real \\<Rightarrow> nat \\<Rightarrow> real\" (\"$'(I^{_}a''''')[_]^{_}'_\\<infinity>\" [0,0,0] 200)\n  where \"$(I^{l}a'')[i]^{m}_\\<infinity> \\<equiv> lim (\\<lambda>n. $(I^{l}a'')[i]^{m}_n)\"\nabbreviation perp_due_incr_lvl :: \"real \\<Rightarrow> nat \\<Rightarrow> real\" (\"$'(Ia''''')[_]^{_}'_\\<infinity>\" [0,0] 200)\n  where \"$(Ia'')[i]^{m}_\\<infinity> \\<equiv> $(I^{1}a'')[i]^{m}_\\<infinity>\"\nabbreviation perp_due_incr_yr :: \"real \\<Rightarrow> real\" (\"$'(Ia''''')[_]'_\\<infinity>\" [0] 200)\n  where \"$(Ia'')[i]_\\<infinity> \\<equiv> $(Ia'')[i]^{1}_\\<infinity>\"\n\n\nsection \\<open>Theory of Interest\\<close>\n\nlocale interest =\n  fixes i :: real  \\<comment> \\<open>i stands for an interest rate.\\<close>\n  assumes v_futr_pos: \"1 + i > 0\"  \\<comment> \\<open>Assume that the future value is positive.\\<close>\n\ncontext interest\nbegin\n\nabbreviation i_nom' :: \"nat \\<Rightarrow> real\" (\"$i^{_}\" [0] 200)\n  where \"$i^{m} \\<equiv> $i[i]^{m}\"\nabbreviation i_force' :: real (\"$\\<delta>\")\n  where \"$\\<delta> \\<equiv> $\\<delta>[i]\"\nabbreviation d_nom' :: \"nat \\<Rightarrow> real\" (\"$d^{_}\" [0] 200)\n  where \"$d^{m} \\<equiv> $d[i]^{m}\"\nabbreviation d_nom_yr' :: real (\"$d\")\n  where \"$d \\<equiv> $d[i]\"\nabbreviation v_pres' :: real (\"$v\")\n  where \"$v \\<equiv> $v[i]\"\nabbreviation ann' :: \"nat \\<Rightarrow> nat \\<Rightarrow> real\" (\"$a^{_}'__\" [0,101] 200)\n  where \"$a^{m}_n \\<equiv> $a[i]^{m}_n\"\nabbreviation ann_yr' :: \"nat \\<Rightarrow> real\" (\"$a'__\" [101] 200)\n  where \"$a_n \\<equiv> $a[i]_n\"\nabbreviation acc' :: \"nat \\<Rightarrow> nat \\<Rightarrow> real\" (\"$s^{_}'__\" [0,101] 200)\n  where \"$s^{m}_n \\<equiv> $s[i]^{m}_n\"\nabbreviation acc_yr' :: \"nat \\<Rightarrow> real\" (\"$s'__\" [101] 200)\n  where \"$s_n \\<equiv> $s[i]_n\"\nabbreviation ann_due' :: \"nat \\<Rightarrow> nat \\<Rightarrow> real\" (\"$a''''^{_}'__\" [0,101] 200)\n  where \"$a''^{m}_n \\<equiv> $a''[i]^{m}_n\"\nabbreviation ann_due_yr' :: \"nat \\<Rightarrow> real\" (\"$a'''''__\" [101] 200)\n  where \"$a''_n \\<equiv> $a''[i]_n\"\nabbreviation acc_due' :: \"nat \\<Rightarrow> nat \\<Rightarrow> real\" (\"$s''''^{_}'__\" [0,101] 200)\n  where \"$s''^{m}_n \\<equiv> $s''[i]^{m}_n\"\nabbreviation acc_due_yr' :: \"nat \\<Rightarrow> real\" (\"$s'''''__\" [101] 200)\n  where \"$s''_n \\<equiv> $s''[i]_n\"\nabbreviation ann_cont' :: \"real \\<Rightarrow> real\" (\"$a'''__\" [101] 200)\n  where \"$a'_n \\<equiv> $a'[i]_n\"\nabbreviation acc_cont' :: \"real \\<Rightarrow> real\" (\"$s'''__\" [101] 200)\n  where \"$s'_n \\<equiv> $s'[i]_n\"\nabbreviation perp' :: \"nat \\<Rightarrow> real\" (\"$a^{_}'_\\<infinity>\" [0] 200)\n  where \"$a^{m}_\\<infinity> \\<equiv> $a[i]^{m}_\\<infinity>\"\nabbreviation perp_yr' :: real (\"$a'_\\<infinity>\")\n  where \"$a_\\<infinity> \\<equiv> $a[i]_\\<infinity>\"\nabbreviation perp_due' :: \"nat \\<Rightarrow> real\" (\"$a''''^{_}'_\\<infinity>\" [0] 200)\n  where \"$a''^{m}_\\<infinity> \\<equiv> $a''[i]^{m}_\\<infinity>\"\nabbreviation perp_due_yr' :: real (\"$a'''''_\\<infinity>\")\n  where \"$a''_\\<infinity> \\<equiv> $a''[i]_\\<infinity>\"\nabbreviation ann_incr' :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> real\" (\"$'(I^{_}a')^{_}'__\" [0,0,101] 200)\n  where \"$(I^{l}a)^{m}_n \\<equiv> $(I^{l}a)[i]^{m}_n\"\nabbreviation ann_incr_lvl' :: \"nat \\<Rightarrow> nat \\<Rightarrow> real\" (\"$'(Ia')^{_}'__\" [0,101] 200)\n  where \"$(Ia)^{m}_n \\<equiv> $(Ia)[i]^{m}_n\"\nabbreviation ann_incr_yr' :: \"nat \\<Rightarrow> real\" (\"$'(Ia')'__\" [101] 200)\n  where \"$(Ia)_n \\<equiv> $(Ia)[i]_n\"\nabbreviation acc_incr' :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> real\" (\"$'(I^{_}s')^{_}'__\" [0,0,101] 200)\n  where \"$(I^{l}s)^{m}_n \\<equiv> $(I^{l}s)[i]^{m}_n\"\nabbreviation acc_incr_lvl' :: \"nat \\<Rightarrow> nat \\<Rightarrow> real\" (\"$'(Is')^{_}'__\" [0,101] 200)\n  where \"$(Is)^{m}_n \\<equiv> $(Is)[i]^{m}_n\"\nabbreviation acc_incr_yr' :: \"nat \\<Rightarrow> real\" (\"$'(Is')'__\" [101] 200)\n  where \"$(Is)_n \\<equiv> $(Is)[i]_n\"\nabbreviation ann_due_incr' :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> real\" (\"$'(I^{_}a''''')^{_}'__\" [0,0,101] 200)\n  where \"$(I^{l}a'')^{m}_n \\<equiv> $(I^{l}a'')[i]^{m}_n\"\nabbreviation ann_due_incr_lvl' :: \"nat \\<Rightarrow> nat \\<Rightarrow> real\" (\"$'(Ia''''')^{_}'__\" [0,101] 200)\n  where \"$(Ia'')^{m}_n \\<equiv> $(Ia'')[i]^{m}_n\"\nabbreviation ann_due_incr_yr' :: \"nat \\<Rightarrow> real\" (\"$'(Ia''''')'__\" [101] 200)\n  where \"$(Ia'')_n \\<equiv> $(Ia'')[i]_n\"\nabbreviation acc_due_incr' :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> real\" (\"$'(I^{_}s''''')^{_}'__\" [0,0,101] 200)\n  where \"$(I^{l}s'')^{m}_n \\<equiv> $(I^{l}s'')[i]^{m}_n\"\nabbreviation acc_due_incr_lvl' :: \"nat \\<Rightarrow> nat \\<Rightarrow> real\" (\"$'(Is''''')^{_}'__\" [0,101] 200)\n  where \"$(Is'')^{m}_n \\<equiv> $(Is'')[i]^{m}_n\"\nabbreviation acc_due_incr_yr' :: \"nat \\<Rightarrow> real\" (\"$'(Is''''')'__\" [101] 200)\n  where \"$(Is'')_n \\<equiv> $(Is'')[i]_n\"\nabbreviation perp_incr' :: \"nat \\<Rightarrow> nat \\<Rightarrow> real\" (\"$'(I^{_}a')^{_}'_\\<infinity>\" [0,0] 200)\n  where \"$(I^{l}a)^{m}_\\<infinity> \\<equiv> $(I^{l}a)[i]^{m}_\\<infinity>\"\nabbreviation perp_incr_lvl' :: \"nat \\<Rightarrow> real\" (\"$'(Ia')^{_}'_\\<infinity>\" [0] 200)\n  where \"$(Ia)^{m}_\\<infinity> \\<equiv> $(Ia)[i]^{m}_\\<infinity>\"\nabbreviation perp_incr_yr' :: real (\"$'(Ia')'_\\<infinity>\")\n  where \"$(Ia)_\\<infinity> \\<equiv> $(Ia)[i]_\\<infinity>\"\nabbreviation perp_due_incr' :: \"nat \\<Rightarrow> nat \\<Rightarrow> real\" (\"$'(I^{_}a''''')^{_}'_\\<infinity>\" [0,0] 200)\n  where \"$(I^{l}a'')^{m}_\\<infinity> \\<equiv> $(I^{l}a'')[i]^{m}_\\<infinity>\"\nabbreviation perp_due_incr_lvl' :: \"nat \\<Rightarrow> real\" (\"$'(Ia''''')^{_}'_\\<infinity>\" [0] 200)\n  where \"$(Ia'')^{m}_\\<infinity> \\<equiv> $(Ia'')[i]^{m}_\\<infinity>\"\nabbreviation perp_due_incr_yr' :: real (\"$'(Ia''''')'_\\<infinity>\")\n  where \"$(Ia'')_\\<infinity> \\<equiv> $(Ia'')[i]_\\<infinity>\"\n\nlemma v_futr_m_pos: \"1 + $i^{m}/m > 0\" if \"m \\<noteq> 0\" for m::nat\n  using v_futr_pos i_nom_def by force\n\nlemma i_nom_1[simp]: \"$i^{1} = i\"\n  using v_futr_pos i_nom_def by force\n\nlemma i_nom_eff: \"(1 + $i^{m}/m)^m = 1 + i\" if \"m \\<noteq> 0\" for m::nat\n  unfolding i_nom_def using less_imp_neq v_futr_pos that\n  apply (simp, subst powr_realpow[THEN sym], simp)\n  by (subst powr_powr, simp)\n\nlemma i_nom_i: \"1 + $i^{m}/m = (1+i).^(1/m)\" if \"m \\<noteq> 0\" for m::nat\n  unfolding i_nom_def by (simp add: that)\n\nlemma i_nom_0_iff_i_0: \"$i^{m} = 0 \\<longleftrightarrow> i = 0\" if \"m \\<noteq> 0\" for m::nat\nproof\n  assume \"$i^{m} = 0\"\n  hence \\<star>: \"(1+i).^(1/m) = (1+i).^0\"\n    unfolding i_nom_def using v_futr_pos that by simp\n  show \"i = 0\"\n  proof (rule ccontr)\n    assume \"i \\<noteq> 0\"\n    hence \"1/m = 0\" using powr_inj \\<star> v_futr_pos by smt\n    thus False using that by simp\n  qed\nnext\n  assume \"i = 0\"\n  thus \"$i^{m} = 0\"\n    unfolding i_nom_def by simp\nqed\n\nlemma i_nom_pos_iff_i_pos: \"$i^{m} > 0 \\<longleftrightarrow> i > 0\" if \"m \\<noteq> 0\" for m::nat\nproof\n  assume \"$i^{m} > 0\"\n  hence \\<star>: \"(1+i).^(1/m) > 1.^(1/m)\"\n    unfolding i_nom_def using v_futr_pos that by (simp add: zero_less_mult_iff)\n  thus \"i > 0\"\n    using powr_less_cancel2[of \"1/m\" 1 \"1+i\"] v_futr_pos that by simp\nnext\n  assume \"i > 0\"\n  hence \"(1+i).^(1/m) > 1.^(1/m)\"\n    using powr_less_mono2 v_futr_pos that by simp\n  thus \"$i^{m} > 0\"\n    unfolding i_nom_def using that by (simp add: zero_less_mult_iff)\nqed\n\nlemma e_delta: \"exp $\\<delta> = 1 + i\"\n  unfolding i_force_def by (simp add: v_futr_pos)\n\nlemma delta_0_iff_i_0: \"$\\<delta> = 0 \\<longleftrightarrow> i = 0\"\nproof\n  assume \"$\\<delta> = 0\"\n  thus \"i = 0\"\n    using e_delta by auto\nnext\n  assume \"i = 0\"\n  thus \"$\\<delta> = 0\"\n    unfolding i_force_def by simp\nqed\n\nlemma lim_i_nom: \"(\\<lambda>m. $i^{m}) \\<longlonglongrightarrow> $\\<delta>\"\nproof -\n  let ?f = \"\\<lambda>h. ((1+i).^h - 1) / h\"\n  have D1ipwr: \"DERIV (\\<lambda>h. (1+i).^h) 0 :> $\\<delta>\"\n    unfolding i_force_def\n    using has_real_derivative_powr2[OF v_futr_pos, where x=0] v_futr_pos by simp\n  hence limf: \"(?f \\<longlongrightarrow> $\\<delta>) (at 0)\"\n    unfolding DERIV_def using v_futr_pos by auto\n  hence \"(\\<lambda>m. $i^{Suc m}) \\<longlonglongrightarrow> $\\<delta>\"\n    unfolding i_nom_def using tendsto_at_iff_sequentially[of ?f \"$\\<delta>\" 0 \\<real>, THEN iffD1]\n    apply simp\n    apply (drule_tac x=\"\\<lambda>m. 1 / Suc m\" in spec, simp, drule mp)\n    subgoal using lim_1_over_n LIMSEQ_Suc by force\n    by (simp add: o_def mult.commute)\n  thus ?thesis\n    by (simp add: LIMSEQ_imp_Suc)\nqed\n\nlemma d_nom_0_iff_i_0: \"$d^{m} = 0 \\<longleftrightarrow> i = 0\" if \"m \\<noteq> 0\" for m::nat\nproof -\n  have \"$d^{m} = 0 \\<longleftrightarrow> $i^{m} = 0\"\n    unfolding d_nom_def using v_futr_m_pos by (smt (verit) divide_eq_0_iff of_nat_0)\n  thus ?thesis\n    using i_nom_0_iff_i_0 that by auto\nqed\n\nlemma d_nom_pos_iff_i_pos: \"$d^{m} > 0 \\<longleftrightarrow> i > 0\" if \"m \\<noteq> 0\" for m::nat\nproof -\n  have \"$d^{m} > 0 \\<longleftrightarrow> $i^{m} > 0\"\n    unfolding d_nom_def using zero_less_divide_iff i_nom_pos_iff_i_pos v_futr_m_pos that by smt\n  thus ?thesis\n    using i_nom_pos_iff_i_pos that by auto\nqed\n\nlemma d_nom_i_nom: \"1 - $d^{m}/m = 1 / (1 + $i^{m}/m)\" if \"m \\<noteq> 0\" for m::nat\nproof -\n  have \"1 - $d^{m}/m = 1 - ($i^{m}/m) / (1 + $i^{m}/m)\"\n    by (simp add: d_nom_def)\n  also have \"\\<dots> = 1 / (1 + $i^{m}/m)\"\n    using v_futr_m_pos\n    by (smt (verit, ccfv_SIG) add_divide_distrib that div_self)\n  finally show ?thesis .\nqed\n\nlemma lim_d_nom: \"(\\<lambda>m. $d^{m}) \\<longlonglongrightarrow> $\\<delta>\"\nproof -\n  have \"(\\<lambda>m. $i^{m}/m) \\<longlonglongrightarrow> 0\"\n    using lim_i_nom tendsto_divide_0 tendsto_of_nat by blast\n  hence \"(\\<lambda>m. 1 + $i^{m}/m) \\<longlonglongrightarrow> 1\"\n    by (metis add.right_neutral tendsto_add_const_iff)\n  thus ?thesis\n    unfolding d_nom_def using lim_i_nom tendsto_divide div_by_1 by fastforce\nqed\n\nlemma v_pos: \"$v > 0\"\n  unfolding v_pres_def using v_futr_pos by auto\n\nlemma v_1_iff_i_0: \"$v = 1 \\<longleftrightarrow> i = 0\"\nproof\n  assume \"$v = 1\"\n  thus \"i = 0\"\n    unfolding v_pres_def by simp\nnext\n  assume \"i = 0\"\n  thus \"$v = 1\"\n    unfolding v_pres_def by simp\nqed\n\nlemma v_lt_1_iff_i_pos: \"$v < 1 \\<longleftrightarrow> i > 0\"\nproof\n  assume \"$v < 1\"\n  thus \"i > 0\"\n    unfolding v_pres_def by (simp add: v_futr_pos)\nnext\n  assume \"i > 0\"\n  thus \"$v < 1\"\n    unfolding v_pres_def by (simp add: v_futr_pos)\nqed\n\nlemma v_i_nom: \"$v = (1 + $i^{m}/m).^-m\" if \"m \\<noteq> 0\" for m::nat\nproof -\n  have \"$v = (1 + i).^-1\"\n    unfolding v_pres_def using v_futr_pos powr_real_def that by (simp add: powr_neg_one)\n  also have \"\\<dots> = ((1 + $i^{m}/m)^m).^-1\"\n    using i_nom_eff that by presburger\n  also have \"\\<dots> = (1 + $i^{m}/m).^-m\"\n    using powr_powr powr_realpow[THEN sym] v_futr_m_pos that by simp\n  finally show ?thesis .\nqed\n\nlemma i_v: \"1 + i = $v.^-1\"\n  unfolding v_pres_def powr_real_def using v_futr_pos powr_neg_one by simp\n\nlemma i_v_powr: \"(1 + i).^a = $v.^-a\" for a::real\n  by (subst i_v, subst powr_powr, simp)\n\nlemma v_delta: \"ln $v = - $\\<delta>\"\n  unfolding i_force_def v_pres_def using v_futr_pos by (simp add: ln_div)\n\nlemma is_derive_vpow: \"DERIV (\\<lambda>t. $v.^t) t :> - $\\<delta> * $v.^t\"\n  using v_delta has_real_derivative_powr2 v_pos by (metis mult.commute)\n\nlemma d_nom_v: \"$d^{m} = m * (1 - $v.^(1/m))\" if \"m \\<noteq> 0\" for m::nat\nproof -\n  have \"$d^{m} = m * (1 - 1 / (1 + $i^{m}/m))\"\n    using d_nom_i_nom[THEN sym] that by force\n  also have \"\\<dots> = m * (1 - 1 / (1 + i).^(1/m))\"\n    using i_nom_i that powr_minus_divide by simp\n  also have \"\\<dots> = m * (1 - $v.^(1/m))\"\n    using v_pres_def v_futr_pos powr_divide by simp\n  finally show ?thesis .\nqed\n\nlemma d_nom_i_nom_v: \"$d^{m} = $i^{m} * $v.^(1/m)\" if \"m \\<noteq>0\" for m::nat\n  unfolding d_nom_def v_pres_def using i_nom_i powr_divide v_futr_pos that by auto\n\nlemma a_calc: \"$a^{m}_n = (1 - $v^n) / $i^{m}\" if \"m \\<noteq> 0\" \"i \\<noteq> 0\" for n m ::nat\nproof -\n  have \"\\<And>l::nat. l/m = (1/m) * l\" by simp\n  hence \\<star>: \"\\<And>l::nat. $v.^(l/m) = ($v.^(1/m))^l\"\n    using powr_powr powr_realpow v_pos by (metis powr_gt_zero)\n  hence \"$a^{m}_n = (\\<Sum>k<n*m. ($v.^(1/m))^(k+1::nat) / m)\"\n    unfolding ann_def by presburger\n  also have \"\\<dots> = $v.^(1/m) * (\\<Sum>k<n*m. ($v.^(1/m))^k) / m\"\n    by (simp, subst sum_divide_distrib[THEN sym], subst sum_distrib_left[THEN sym], simp)\n  also have \"\\<dots> = $v.^(1/m) * ((($v.^(1/m))^(n*m) - 1) / ($v.^(1/m) - 1)) / m\"\n    apply (subst geometric_sum[of \"$v.^(1/m)\" \"n*m\"]; simp?)\n    using powr_zero_eq_one[of \"$v\"] v_pos v_1_iff_i_0 powr_inj that\n    by (smt (verit, del_insts) divide_eq_0_iff of_nat_eq_0_iff)\n  also have \"\\<dots> = (($v.^(1/m))^(n*m) - 1) / (m * ($v.^(1/m) - 1) / $v.^(1/m))\"\n    by (simp add: field_simps)\n  also have \"\\<dots> = ($v^n - 1) / (m * (1 - 1 / $v.^(1/m)))\"\n    apply (subst \\<star>[of \"n*m::nat\", THEN sym], simp only: of_nat_simps)\n    apply (subst nonzero_mult_div_cancel_right[where 'a=real, of m n], simp add: that)\n    apply (subst powr_realpow[OF v_pos])\n    apply (subst times_divide_eq_right[of _ _ \"$v.^(1/m)\", THEN sym])\n    using v_pos by (subst diff_divide_distrib[of _ _ \"$v.^(1/m)\"], simp)\n  also have \"\\<dots> = (1 - $v^n) / (m * (1 / $v.^(1/m) - 1))\"\n    using minus_divide_divide by (smt mult_minus_right)\n  also have \"\\<dots> = (1 - $v^n) / $i^{m}\"\n    unfolding i_nom_def v_pres_def using v_futr_pos powr_divide by auto\n  finally show ?thesis .\nqed\n\nlemma a_calc_i_0: \"$a^{m}_n = n\" if \"m \\<noteq> 0\" \"i = 0\" for n m :: nat \n  unfolding ann_def v_pres_def using that by simp\n\nlemma s_calc_i_0: \"$s^{m}_n = n\" if \"m \\<noteq> 0\" \"i = 0\" for n m :: nat\n  unfolding acc_def using that by simp\n\nlemma s_a: \"$s^{m}_n = (1+i)^n * $a^{m}_n\" if \"m \\<noteq> 0\" for n m :: nat\nproof -\n  have \"(1+i)^n * $a^{m}_n = (\\<Sum>k<n*m. (1+i)^n * ($v.^((k+1::nat)/m) / m))\"\n    unfolding ann_def using sum_distrib_left by blast\n  also have \"\\<dots> = (\\<Sum>k<n*m. (1+i).^((n*m - Suc k)/m) / m)\"\n  proof -\n    have \"\\<And>k::nat. k < n*m \\<Longrightarrow> (1+i)^n * ($v.^((k+1::nat)/m) / m) = (1+i).^((n*m - Suc k)/m) / m\"\n      unfolding v_pres_def\n      apply (subst powr_realpow[THEN sym], simp add: v_futr_pos)\n      apply (subst inverse_powr, simp add: v_futr_pos)\n      apply (subst times_divide_eq_right, subst powr_add[THEN sym], simp add: that)\n      by (subst of_nat_diff, simp add: Suc_le_eq, simp add: diff_divide_distrib that)\n    thus ?thesis by (meson lessThan_iff sum.cong)\n  qed\n  also have \"\\<dots> = (\\<Sum>k<n*m. (1+i).^(k/m) / m)\"\n    apply (subst atLeast0LessThan[THEN sym])+\n    by (subst sum.atLeastLessThan_rev[THEN sym, of _ \"n*m\" 0, simplified add_0_right], simp)\n  also have \"\\<dots> = $s^{m}_n\"\n    unfolding acc_def by simp\n  finally show ?thesis ..\nqed\n\nlemma s_calc: \"$s^{m}_n = ((1+i)^n - 1) / $i^{m}\" if \"m \\<noteq> 0\" \"i \\<noteq> 0\" for n m :: nat\n  using that v_futr_pos\n  apply (subst s_a, simp, subst a_calc; simp?)\n  apply (rule disjI2)\n  apply (subst right_diff_distrib, simp)\n  apply (rule left_right_inverse_power)\n  unfolding v_pres_def by auto\n\nlemma a''_a: \"$a''^{m}_n = (1+i).^(1/m) * $a^{m}_n\" if \"m \\<noteq> 0\" for m::nat\n  unfolding ann_def ann_due_def\n  apply (subst sum_distrib_left, subst times_divide_eq_right, simp)\n  by (subst i_v, subst powr_powr, subst powr_add[THEN sym], simp, subst add_divide_distrib, simp)\n\nlemma a_a'': \"$a^{m}_n = $v.^(1/m) * $a''^{m}_n\" if \"m \\<noteq> 0\" for m::nat\n  unfolding ann_def ann_due_def\n  apply (subst sum_distrib_left, subst times_divide_eq_right, simp)\n  by (subst powr_add[THEN sym], subst add_divide_distrib, simp)\n\nlemma a''_calc_i_0: \"$a''^{m}_n = n\" if \"m \\<noteq> 0\" \"i = 0\" for n m :: nat\n  unfolding ann_due_def v_pres_def using that by simp\n\nlemma s''_calc_i_0: \"$s''^{m}_n = n\" if \"m \\<noteq> 0\" \"i = 0\" for n m :: nat\n  unfolding acc_due_def using that by simp\n\nlemma a''_calc: \"$a''^{m}_n = (1 - $v^n) / $d^{m}\" if \"m \\<noteq> 0\" \"i \\<noteq> 0\" for n m :: nat\nproof -\n  have \"$a''^{m}_n = (1+i).^(1/m) * ((1 - $v^n) / $i^{m})\"\n    using a''_a a_calc times_divide_eq_right that by simp\n  also have \"\\<dots> = (1 - $v^n) / ($v.^(1/m) * $i^{m})\"\n    by (subst i_v, subst powr_powr, simp, subst powr_minus_divide, simp)\n  also have \"\\<dots> = (1 - $v^n) / $d^{m}\"\n    using d_nom_i_nom_v that by simp\n  finally show ?thesis .\nqed\n\nlemma s''_s: \"$s''^{m}_n = (1+i).^(1/m) * $s^{m}_n\" if \"m \\<noteq> 0\" for m::nat\n  unfolding acc_def acc_due_def\n  by (simp add: sum_distrib_left add_divide_distrib powr_add)\n\nlemma s_s'': \"$s^{m}_n = $v.^(1/m) * $s''^{m}_n\" if \"m \\<noteq> 0\" for m::nat\n  unfolding acc_def acc_due_def v_pres_def using v_futr_pos\n  apply (simp add: sum_distrib_left inverse_powr add_divide_distrib)\n  by (metis (no_types) add_diff_cancel_left' powr_add uminus_add_conv_diff)\n\nlemma s''_calc: \"$s''^{m}_n = ((1+i)^n - 1) / $d^{m}\" if \"m \\<noteq> 0\" \"i \\<noteq> 0\" for n m :: nat\nproof -\n  have \"$s''^{m}_n = (1+i).^(1/m) * ((1+i)^n - 1) / $i^{m}\"\n    using s''_s s_calc times_divide_eq_right that by simp\n  also have \"\\<dots> = ((1+i)^n - 1) / ($v.^(1/m) * $i^{m})\"\n    by (subst i_v, subst powr_powr, simp, subst powr_minus_divide, simp)\n  also have \"\\<dots> = ((1+i)^n - 1) / $d^{m}\"\n    using d_nom_i_nom_v that by simp\n  finally show ?thesis .\nqed\n\nlemma s''_a'': \"$s''^{m}_n = (1+i)^n * $a''^{m}_n\" if \"m \\<noteq> 0\" for m::nat\n  using that s''_s a''_a s_a by simp\n\nlemma a'_calc: \"$a'_n = (1 - $v.^n) / $\\<delta>\" if \"i \\<noteq> 0\" \"n \\<ge> 0\" for n::real\n  unfolding ann_cont_def\n  apply (rule integral_unique)\n  using has_integral_powr2_from_0[OF v_pos _ that(2)] v_delta v_1_iff_i_0 that\n  by (smt minus_divide_divide)\n\nlemma a'_calc_i_0: \"$a'_n = n\" if \"i = 0\" \"n \\<ge> 0\" for n::real\n  unfolding ann_cont_def\n  apply (subst iffD2[OF v_1_iff_i_0], simp add: that)\n  by (simp add: integral_cong that)\n\nlemma s'_calc: \"$s'_n = ((1+i).^n - 1) / $\\<delta>\" if \"i \\<noteq> 0\" \"n \\<ge> 0\" for n::real\n  unfolding acc_cont_def\n  apply (rule integral_unique)\n  using has_integral_powr2_from_0[OF v_futr_pos _ that(2)] i_force_def that\n  by simp\n\nlemma s'_calc_i_0: \"$s'_n = n\" if \"i = 0\" \"n \\<ge> 0\" for n::real\n  unfolding acc_cont_def\n  apply (subst \\<open>i = 0\\<close>, simp)\n  by (simp add: integral_cong that)\n\nlemma s'_a': \"$s'_n = (1+i).^n * $a'_n\" if \"n \\<ge> 0\" for n::real\nproof -\n  have \"(1+i).^n * $a'_n = integral {0..n} (\\<lambda>t. (1+i).^(n-t))\"\n    unfolding ann_cont_def\n    using integrable_on_powr2_from_0_general[of \"$v\" n] v_pos v_futr_pos that\n    apply (subst integral_mult, simp)\n    apply (rule integral_cong)\n    unfolding v_pres_def using inverse_powr powr_add[THEN sym] by smt\n  also have \"\\<dots> = $s'_n\"\n    unfolding acc_cont_def using v_futr_pos that\n    apply (subst has_integral_interval_reverse[of 0 n, simplified, THEN integral_unique]; simp?)\n    by (rule continuous_on_powr; auto)\n  finally show ?thesis ..\nqed\n\nlemma lim_m_a: \"(\\<lambda>m. $a^{m}_n) \\<longlonglongrightarrow> $a'_n\" for n::nat\nproof (rule LIMSEQ_imp_Suc)\n  show \"(\\<lambda>m. $a^{Suc m}_n) \\<longlonglongrightarrow> $a'_n\"\n  proof (cases \"i = 0\")\n    case True\n    show ?thesis\n      using a_calc_i_0 a'_calc_i_0 True by simp\n  next\n    case False\n    show ?thesis\n      using False v_pos delta_0_iff_i_0\n      apply (subst a_calc; simp?)\n      apply (subst a'_calc; simp?)\n      apply (subst powr_realpow, simp)\n      apply (rule tendsto_divide; simp?)\n      by (rule LIMSEQ_Suc[OF lim_i_nom])\n  qed\nqed\n\nlemma lim_m_a'': \"(\\<lambda>m. $a''^{m}_n) \\<longlonglongrightarrow> $a'_n\" for n::nat\nproof (rule LIMSEQ_imp_Suc)\n  show \"(\\<lambda>m. $a''^{Suc m}_n) \\<longlonglongrightarrow> $a'_n\"\n  proof (cases \"i = 0\")\n    case True\n    show ?thesis\n      using a''_calc_i_0 a'_calc_i_0 True by simp\n  next\n    case False\n    show ?thesis\n      using False v_pos delta_0_iff_i_0\n      apply (subst a''_calc; simp?)\n      apply (subst a'_calc; simp?)\n      apply (subst powr_realpow, simp)\n      apply (rule tendsto_divide; simp?)\n      by (rule LIMSEQ_Suc[OF lim_d_nom])\n  qed\nqed\n\nlemma lim_m_s: \"(\\<lambda>m. $s^{m}_n) \\<longlonglongrightarrow> $s'_n\" for n::nat\nproof (rule LIMSEQ_imp_Suc)\n  show \"(\\<lambda>m. $s^{Suc m}_n) \\<longlonglongrightarrow> $s'_n\"\n  proof (cases \"i = 0\")\n    case True\n    show ?thesis\n      using s_calc_i_0 s'_calc_i_0 True by simp\n  next\n    case False\n    show ?thesis\n      using False v_futr_pos delta_0_iff_i_0\n      apply (subst s_calc; simp?)\n      apply (subst s'_calc; simp?)\n      apply (subst powr_realpow, simp)\n      apply (rule tendsto_divide; simp?)\n      by (rule LIMSEQ_Suc[OF lim_i_nom])\n  qed\nqed\n\nlemma lim_m_s'': \"(\\<lambda>m. $s''^{m}_n) \\<longlonglongrightarrow> $s'_n\" for n::nat\nproof (rule LIMSEQ_imp_Suc)\n  show \"(\\<lambda>m. $s''^{Suc m}_n) \\<longlonglongrightarrow> $s'_n\"\n  proof (cases \"i = 0\")\n    case True\n    show ?thesis\n      using s''_calc_i_0 s'_calc_i_0 True by simp\n  next\n    case False\n    show ?thesis\n      using False v_futr_pos delta_0_iff_i_0\n      apply (subst s''_calc; simp?)\n      apply (subst s'_calc; simp?)\n      apply (subst powr_realpow, simp)\n      apply (rule tendsto_divide; simp?)\n      by (rule LIMSEQ_Suc[OF lim_d_nom])\n  qed\nqed\n\nlemma lim_n_a: \"(\\<lambda>n. $a^{m}_n) \\<longlonglongrightarrow> $a^{m}_\\<infinity>\" if \"m \\<noteq> 0\" \"i > 0\" for m::nat\nproof -\n  have \"$i^{m} \\<noteq> 0\" using i_nom_pos_iff_i_pos that by smt\n  moreover have \"(\\<lambda>n. $v^n) \\<longlonglongrightarrow> 0\"\n    using LIMSEQ_realpow_zero[of \"$v\"] v_pos v_lt_1_iff_i_pos that by simp\n  ultimately show ?thesis\n    using that apply (subst a_calc; simp?)\n    unfolding perp_def apply (rule tendsto_divide; simp?)\n    using tendsto_diff[where a=1 and b=0] by auto\nqed\n\nlemma lim_n_a'': \"(\\<lambda>n. $a''^{m}_n) \\<longlonglongrightarrow> $a''^{m}_\\<infinity>\" if \"m \\<noteq> 0\" \"i > 0\" for m::nat\nproof -\n  have \"$d^{m} \\<noteq> 0\" using d_nom_pos_iff_i_pos that by smt\n  moreover have \"(\\<lambda>n. $v^n) \\<longlonglongrightarrow> 0\"\n    using LIMSEQ_realpow_zero[of \"$v\"] v_pos v_lt_1_iff_i_pos that by simp\n  ultimately show ?thesis\n    using that apply (subst a''_calc; simp?)\n    unfolding perp_due_def apply (rule tendsto_divide; simp?)\n    using tendsto_diff[where a=1 and b=0] by auto\nqed\n\nlemma Ilsm_Ilam: \"$(I^{l}s)^{m}_n = (1+i)^n * $(I^{l}a)^{m}_n\"\n  if \"l \\<noteq> 0\" \"m \\<noteq> 0\" for l n m :: nat\n  unfolding acc_incr_def ann_incr_def v_pres_def using v_futr_pos powr_realpow\n  apply (subst inverse_powr, simp)\n  apply (subst sum_distrib_left)\n  by (subst minus_real_def, subst powr_add, subst times_divide_eq_right, subst mult.assoc, simp)\n\nlemma Iam_calc: \"$(Ia)^{m}_n = (\\<Sum>j<n. (j+1)/m * (\\<Sum>k=j*m..<(j+1)*m. $v.^((k+1)/m)))\"\n  if \"m \\<noteq> 0\" for n m :: nat\nproof -\n  let ?I = \"{..<n}\"\n  let ?A = \"\\<lambda>j. {j*m..<(j+1)*m}\"\n  let ?g = \"\\<lambda>k. $v.^((k+1::nat)/m) * \\<lceil>(k+1::nat)/m\\<rceil> / m\"\n  have \"$(Ia)^{m}_n = (\\<Sum>j<n. \\<Sum>k=j*m..<(j+1)*m. $v.^((k+1)/m) * \\<lceil>(k+1)/m\\<rceil> / m)\"\n    unfolding ann_incr_def using seq_part_multiple that\n    apply (simp only: mult_1)\n    by (subst sum.UNION_disjoint[of ?I ?A ?g, THEN sym]; simp)\n  also have \"\\<dots> = (\\<Sum>j<n. (j+1)/m * (\\<Sum>k=j*m..<(j+1)*m. $v.^((k+1)/m)))\"\n  proof -\n    { fix j k\n      assume \"j*m \\<le> k \\<and> k < (j+1)*m\"\n      hence \"j*m < k+1 \\<and> k+1 \\<le> (j+1)*m\" by force\n      hence \"j < (k+1)/m \\<and> (k+1)/m \\<le> j+1\"\n        using pos_less_divide_eq pos_divide_le_eq of_nat_less_iff of_nat_le_iff that\n        by (smt (verit) of_nat_le_0_iff of_nat_mult)\n      hence \"\\<lceil>(k+1)/m\\<rceil> = j+1\"\n        by (simp add: ceiling_unique) }\n    hence \"\\<And>j k. j*m \\<le> k \\<and> k < (j+1)*m \\<Longrightarrow> \\<lceil>(k+1)/m\\<rceil> = j+1\"\n      by (metis (no_types) of_nat_1 of_nat_add)\n    with v_pos show ?thesis\n      apply (intro sum.cong, simp)\n      apply (subst sum_distrib_left, rule sum.cong; simp)\n      by (smt (verit, ccfv_SIG) of_int_1 of_int_diff of_int_of_nat_eq)\n  qed\n  finally show ?thesis .\nqed\n\nlemma Ism_calc: \"$(Is)^{m}_n = (\\<Sum>j<n. (j+1)/m * (\\<Sum>k=j*m..<(j+1)*m. (1+i).^(n-(k+1)/m)))\"\n  if \"m \\<noteq> 0\" for n m :: nat\n  using v_pos that\n  apply (subst Ilsm_Ilam; simp)\n  apply (subst Iam_calc[simplified]; simp?)\n  apply ((subst sum_distrib_left, rule sum.cong; simp))+\n  unfolding v_pres_def using v_futr_pos\n  apply (subst inverse_powr; simp)\n  apply (subst powr_realpow[THEN sym], simp)\n  by (subst powr_add[THEN sym]; simp)\n\nlemma Imam_calc_aux: \"$(I^{m}a)^{m}_n = (\\<Sum>k<n*m. $v.^((k+1)/m) * (k+1) / m^2)\"\n  if \"m \\<noteq> 0\" for m::nat\n  unfolding ann_incr_def power_def\n  apply (rule sum.cong, simp)\n  apply (subst of_nat_mult)\n  using v_pos that\n  apply (subst nonzero_mult_div_cancel_left, simp)\n  by (subst ceiling_of_nat; simp)\n\nlemma Imam_calc:\n  \"$(I^{m}a)^{m}_n = ($v.^(1/m) * (1 - (n*m+1)*$v^n + n*m*$v.^(n+1/m))) / (m*(1-$v.^(1/m)))^2\"\n  if \"i \\<noteq> 0\" \"m \\<noteq> 0\" for n m :: nat\nproof -\n  have \\<star>: \"$v.^(1/m) > 0\" using v_pos by force\n  hence \"$(I^{m}a)^{m}_n = (\\<Sum>k<n*m. (k+1)*($v.^(1/m))^(k+1)) / m^2\"\n    using that\n    apply (subst Imam_calc_aux, simp)\n    apply (subst sum_divide_distrib[THEN sym], simp)\n    apply (rule sum.cong; simp)\n    using powr_realpow[THEN sym] powr_powr by (simp add: add_divide_distrib powr_add)\n  also have \"\\<dots> = $v.^(1/m) * (\\<Sum>k<n*m. (k+1)*($v.^(1/m))^k) / m^2\"\n    by (subst sum_distrib_left, simp add: that, rule sum.cong; simp)\n  also have \"\\<dots> = $v.^(1/m) *\n    ((1 - (n*m+1)*($v.^(1/m))^(n*m) + n*m*($v.^(1/m))^(n*m+1)) / (1 - $v.^(1/m))^2) / m^2\"\n    using v_pos v_1_iff_i_0 that by (subst geometric_increasing_sum; simp?)\n  also have \"\\<dots> = ($v.^(1/m) * (1 - (n*m+1)*$v^n + n*m*$v.^(n+1/m))) / (m*(1-$v.^(1/m)))^2\"\n    using \\<star>\n    apply (subst powr_realpow[of \"$v.^(1/m)\", THEN sym], simp)+\n    apply (subst powr_powr)+\n    apply (subst times_divide_eq_right[THEN sym], subst divide_divide_eq_left)\n    apply (subst power_mult_distrib)\n    using powr_eq_one_iff_gen v_pos v_1_iff_i_0 apply (simp add: field_simps)\n    by ((subst powr_realpow, simp)+, simp)\n  finally show ?thesis .\nqed\n\nlemma Imam_calc_i_0: \"$(I^{m}a)^{m}_n = (n*m+1)*n / (2*m)\" if \"i = 0\" \"m \\<noteq> 0\" for n m :: nat\nproof -\n  have \"$(I^{m}a)^{m}_n = (\\<Sum>k<n*m. $v.^((k+1)/m) * (k+1) / m^2)\"\n    by (subst Imam_calc_aux, simp_all add: that)\n  also have \"\\<dots> = (\\<Sum>k<n*m. k+1) / m^2\"\n    apply (subst v_1_iff_i_0[THEN iffD2], simp_all add: that)\n    by (subst sum_divide_distrib[THEN sym], simp)\n  also have \"\\<dots> = (n*m*(n*m+1) div 2) / m^2\"\n    apply (subst Suc_eq_plus1[THEN sym], subst sum_bounds_lt_plus1[of id, simplified])\n    by (subst Sum_Icc_nat, simp)\n  also have \"\\<dots> = (n*m+1)*n / (2*m)\"\n    apply (subst real_of_nat_div, simp)\n    using that by (subst power2_eq_square, simp add: field_simps)\n  finally show ?thesis .\nqed\n\nlemma Imsm_calc:\n  \"$(I^{m}s)^{m}_n = ((1+i).^(n+1/m) - (n*m+1)*(1+i).^(1/m) + n*m) / (m*((1+i).^(1/m)-1))^2\"\n  if \"i \\<noteq> 0\" \"m \\<noteq> 0\" for n m :: nat\nproof -\n  have \"$(I^{m}a)^{m}_n =\n    ($v^n * ((1+i).^(n+1/m) - (n*m+1)*(1+i).^(1/m) + n*m)) / (m*((1+i).^(1/m)-1))^2\"\n  proof -\n    have \"$(I^{m}a)^{m}_n =\n      ($v.^(1/m) * (1 - (n*m+1)*$v^n + n*m*$v.^(n+1/m))) / (m*(1-$v.^(1/m)))^2\"\n      using that by (subst Imam_calc; simp)\n    also have \"\\<dots> = (1 - (n*m+1)*$v^n + n*m*$v.^(n+1/m)) / ($v.^(1/m)*(m*($v.^(-1/m)-1))^2)\"\n      apply (subgoal_tac \"$v.^(-1/m) = 1 / $v.^(1/m)\", erule ssubst)\n       apply ((subst power2_eq_square)+, simp add: field_simps that)\n      by (simp add: powr_minus_divide)\n    also have \"\\<dots> =\n      ($v.^(n+1/m) * ($v.^(-n-1/m) - (n*m+1)*$v.^(-1/m) + n*m)) / ($v.^(1/m)*(m*($v.^(-1/m)-1))^2)\"\n      apply (subgoal_tac \"$v.^(-n-1/m) = 1 / $v.^(n+1/m)\" \"$v.^(-1/m) = $v^n / $v.^(n+1/m)\")\n        apply ((erule ssubst)+, simp_all add: field_simps)\n      using v_pos\n       apply (simp add: powr_diff[THEN sym] powr_realpow[THEN sym])\n      by (smt powr_minus_divide)\n    also have \"\\<dots> =\n      ($v^n * ($v.^(-n-1/m) - (n*m+1)*$v.^(-1/m) + n*m)) / ((m*($v.^(-1/m)-1))^2)\"\n      apply (subst powr_add[of _ n \"1/m\"])\n      using v_pos powr_realpow by simp\n    also have \"\\<dots> =\n      ($v^n * ((1+i).^(n+1/m) - (n*m+1)*(1+i).^(1/m) + n*m)) / ((m*((1+i).^(1/m)-1))^2)\"\n      apply (subgoal_tac \"-n-1/m = -(n+1/m)\" \"-1/m = -(1/m)\", (erule ssubst)+)\n        apply (subst i_v_powr[THEN sym])+\n      by simp_all\n    finally show ?thesis .\n  qed\n  thus ?thesis\n    apply -\n    using that v_futr_pos\n    apply (subst Ilsm_Ilam, simp)\n    apply (erule ssubst, simp)\n    apply (rule disjI2)\n    by (subst power_mult_distrib[THEN sym], simp add: v_pres_def)\nqed\n\nlemma Imsm_calc_i_0: \"$(I^{m}s)^{m}_n = (n*m+1)*n / (2*m)\" if \"i = 0\" \"m \\<noteq> 0\" for n m :: nat\n  using that\n  apply (subst Ilsm_Ilam, simp)\n  by (subst Imam_calc_i_0; simp)\n\nlemma Ila''m_Ilam: \"$(I^{l}a'')^{m}_n = (1+i).^(1/m) * $(I^{l}a)^{m}_n\"\n  if \"l \\<noteq> 0\" \"m \\<noteq> 0\" for l m n :: nat\n  unfolding ann_incr_def ann_due_incr_def using that\n  apply (subst i_v, subst powr_powr, simp)\n  apply (subst sum_distrib_left)\n  apply (rule sum.cong; simp)\n  apply (rule disjI2)\n  by (smt (verit) add_divide_distrib powr_add)\n\nlemma Ia''m_calc: \"$(Ia'')^{m}_n = (\\<Sum>j<n. (j+1)/m * (\\<Sum>k=j*m..<(j+1)*m. $v.^(k/m)))\"\n  if \"m \\<noteq> 0\" for n m :: nat\n  using that\n  apply (subst Ila''m_Ilam; simp del: One_nat_def)\n  apply (subst Iam_calc; simp)\n  apply (subst sum_distrib_left)\n  apply (rule sum.cong; simp)\n  apply (subst sum_distrib_left)+\n  apply (rule sum.cong; simp)\n  apply (subst i_v_powr)\n  using powr_add[of \"$v\", THEN sym] by (simp add: field_simps)\n\nlemma Ima''m_calc_aux: \"$(I^{m}a'')^{m}_n = (\\<Sum>k<n*m. $v.^(k/m) * (k+1) / m^2)\"\n  if \"m \\<noteq> 0\" for m::nat\n  using that\n  apply (subst Ila''m_Ilam, simp)\n  apply (subst Imam_calc_aux, simp)\n  apply (subst sum_distrib_left)\n  apply (rule sum.cong; simp)\n  using powr_add[of \"$v\", THEN sym] i_v_powr by (simp add: field_simps)\n\nlemma Ima''m_calc: \"$(I^{m}a'')^{m}_n = (1 - (n*m+1)*$v^n + n*m*$v.^(n+1/m)) / (m*(1-$v.^(1/m)))^2\"\n  if \"i \\<noteq> 0\" \"m \\<noteq> 0\" for n m :: nat\n  using that v_pos\n  apply (subst Ila''m_Ilam, simp)\n  apply (subst Imam_calc; simp)\n  by (smt (verit, del_insts) i_v_powr powr_add powr_zero_eq_one)\n\nlemma Ils''m_Ilsm: \"$(I^{l}s'')^{m}_n = (1+i).^(1/m) * $(I^{l}s)^{m}_n\"\n  if \"l \\<noteq> 0\" \"m \\<noteq> 0\" for l m n :: nat\n  unfolding acc_incr_def acc_due_incr_def sum_distrib_left using that\n  apply (intro sum.cong; simp)\n  by (smt (verit, ccfv_SIG) add_divide_distrib powr_add)\n\nlemma Ims''m_calc:\n  \"$(I^{m}s'')^{m}_n =\n    (1+i).^(1/m) * ((1+i).^(n+1/m) - (n*m+1)*(1+i).^(1/m) + n*m) / (m*((1+i).^(1/m)-1))^2\"\n  if \"i \\<noteq> 0\" \"m \\<noteq> 0\" for n m :: nat\n  using that by (simp add: Ils''m_Ilsm Imsm_calc)\n\nlemma lim_Imam: \"(\\<lambda>n. $(I^{m}a)^{m}_n) \\<longlonglongrightarrow> 1 / ($i^{m}*$d^{m})\" if \"m \\<noteq> 0\" \"i > 0\" for m::nat\nproof -\n  have \"(\\<lambda>n. $(I^{m}a)^{m}_n) = \n    (\\<lambda>n. $v.^(1/m) * (1 - (n*m+1)*$v^n + n*m*$v.^(n+1/m)) / (m*(1-$v.^(1/m)))^2)\"\n    using that by (subst Imam_calc; simp)\n  moreover have \"(\\<lambda>n. $v.^(1/m) * (1 - (n*m+1)*$v^n + n*m*$v.^(n+1/m)) / (m*(1-$v.^(1/m)))^2)\n    \\<longlonglongrightarrow> 1 / ($i^{m}*$d^{m})\"\n  proof -\n    have \\<star>: \"\\<bar>$v\\<bar> < 1\"\n      using v_lt_1_iff_i_pos v_pos that by force\n    hence \"(\\<lambda>n. (n*m+1)*$v^n) \\<longlonglongrightarrow> 0\"\n      apply (subst tendsto_cong[of _ \"(\\<lambda>n. n*m*$v^n + $v^n)\"])\n       apply (rule always_eventually, rule allI)\n       apply (simp add: distrib_right)\n      apply (subgoal_tac \"0 = 0 + 0\", erule ssubst, intro tendsto_intros; simp)\n      apply (subst mult.commute, subst mult.assoc)\n      apply (subgoal_tac \"0 = real m * 0\", erule ssubst, intro tendsto_intros; simp?)\n      by (rule powser_times_n_limit_0; simp)\n    moreover have \"(\\<lambda>n. n*m*$v.^(n+1/m)) \\<longlonglongrightarrow> 0\"\n      apply (subst tendsto_cong[of _ \"(\\<lambda>n. (m*$v.^(1/m))*(n*$v^n))\"])\n       apply (rule always_eventually, rule allI)\n      apply (simp add: powr_add powr_realpow v_pos)\n      apply (subgoal_tac \"0 = m*$v.^(1/m) * 0\", erule ssubst, intro tendsto_intros; simp?)\n      by (rule powser_times_n_limit_0, simp add: \\<star>)\n    ultimately have \"(\\<lambda>n. $v.^(1/m) * (1 - (n*m+1)*$v^n + n*m*$v.^(n+1/m)) / (m*(1-$v.^(1/m)))^2)\n      \\<longlonglongrightarrow> $v.^(1/m) * (1 - 0 + 0)/ (m*(1-$v.^(1/m)))^2\"\n      using v_lt_1_iff_i_pos v_pos that by (intro tendsto_intros; simp)\n    thus ?thesis\n      unfolding i_nom_def using v_pos that\n      apply (subst i_v_powr, subst powr_minus_divide, subst d_nom_v; simp)\n      by (subst(asm)(2) power2_eq_square, simp add: field_simps)\n  qed\n  ultimately show ?thesis by simp\nqed\n\nlemma perp_incr_calc: \"$(I^{m}a)^{m}_\\<infinity> = 1 / ($i^{m}*$d^{m})\" if \"m \\<noteq> 0\" \"i > 0\" for m::nat\n  unfolding perp_incr_def by (rule limI, rule lim_Imam; simp add: that)\n\nlemma lim_Ima''m: \"(\\<lambda>n. $(I^{m}a'')^{m}_n) \\<longlonglongrightarrow> 1 / ($d^{m})^2\" if \"m \\<noteq> 0\" \"i > 0\" for m::nat\n  unfolding perp_due_incr_def using that\n  apply (subst Ila''m_Ilam, simp, subst mult.commute, subst i_v_powr, subst powr_minus_divide)\n  apply (subgoal_tac \"1/($d^{m})^2 = (1/($i^{m}*$d^{m}))*(1/$v.^(1/m))\", erule ssubst)\n   apply (intro tendsto_intros, simp add: lim_Imam)\n  by (simp add: d_nom_i_nom_v power2_eq_square)\n\nlemma perp_due_incr_calc: \"$(I^{m}a'')^{m}_\\<infinity> = 1 / ($d^{m})^2\" if \"m \\<noteq> 0\" \"i > 0\" for m::nat\n  unfolding perp_due_incr_def by (rule limI, rule lim_Ima''m; simp add: that)\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/Actuarial_Mathematics/Interest.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094145755219, "lm_q2_score": 0.828938806208442, "lm_q1q2_score": 0.7404988396929953}}
{"text": "(*  Title:      Subgroup Conjugation\n    Author:     Jakob von Raumer, Karlsruhe Institute of Technology\n    Maintainer: Jakob von Raumer <jakob.raumer at student.kit.edu>\n*)\n\ntheory SubgroupConjugation\nimports GroupAction\nbegin\n\nsection \\<open>Conjugation of Subgroups and Cosets\\<close>\n\ntext \\<open>This theory examines properties of the conjugation of subgroups\nof a fixed group as a group action\\<close>\n\nsubsection \\<open>Definitions and Preliminaries\\<close>\n\ntext \\<open>We define the set of all subgroups of @{term G} which have a certain\ncardinality. @{term G} will act on those sets. Afterwards some theorems which\nare already available for right cosets are dualized into statements about\nleft cosets.\\<close>\n\nlemma (in subgroup) subgroup_of_subset:\n  assumes G:\"group G\"\n  assumes PH:\"H \\<subseteq> K\"\n  assumes KG:\"subgroup K G\"\n  shows \"subgroup H (G\\<lparr>carrier := K\\<rparr>)\"\nusing assms subgroup_def group.m_inv_consistent m_inv_closed by fastforce\n\ncontext group\nbegin\n\ndefinition subgroups_of_size ::\"nat \\<Rightarrow> _\"\n  where \"subgroups_of_size p = {H. subgroup H G \\<and> card H = p}\"\n\nlemma lcosI: \"[| h \\<in> H; H \\<subseteq> carrier G; x \\<in> carrier G|] ==> x \\<otimes> h \\<in> x <# H\"\n  by (auto simp add: l_coset_def)\n\nlemma lcoset_join2:\n  assumes H:\"subgroup H G\"\n  assumes g:\"g \\<in> H\"\n  shows \"g <# H = H\"\nproof auto\n  fix x\n  assume x:\"x \\<in> g <# H\"\n  then obtain h where h:\"h \\<in> H\" \"x = g \\<otimes> h\" unfolding l_coset_def by auto\n  with g H show \"x \\<in> H\" by (metis subgroup.m_closed)\nnext\n  fix x\n  assume x:\"x \\<in> H\"\n  with g H have \"inv g \\<otimes> x \\<in> H\" by (metis subgroup.m_closed subgroup.m_inv_closed)\n  with x g H show \"x \\<in> g <# H\" by (metis is_group subgroup.lcos_module_rev subgroup.mem_carrier)\nqed\n\nlemma cardeq_rcoset:\n  assumes \"finite (carrier G)\"\n  assumes \"M \\<subseteq> carrier G\"\n  assumes \"g \\<in> carrier G\"\n  shows \"card (M #> g) = card  M\"\nproof -\n  have \"M #> g \\<in> rcosets M\" by (metis assms(2) assms(3) rcosetsI)\n  thus \"card (M #> g) = card M\"\n    using assms(2) card_rcosets_equal by auto\nqed\n\nlemma cardeq_lcoset:\n  assumes \"finite (carrier G)\"\n  assumes M:\"M \\<subseteq> carrier G\"\n  assumes g:\"g \\<in> carrier G\"\n  shows \"card (g <# M) = card  M\"\nproof -\n  have \"bij_betw (\\<lambda>m. g \\<otimes> m) M (g <# M)\"\n  proof(auto simp add: bij_betw_def)\n    show \"inj_on ((\\<otimes>) g) M\"\n    proof(rule inj_onI)\n        from g have invg:\"inv g \\<in> carrier G\" by (rule inv_closed)\n        fix x y\n        assume x:\"x \\<in> M\" and y:\"y \\<in> M\"\n        with M have xG:\"x \\<in> carrier G\" and yG:\"y \\<in> carrier G\" by auto \n        assume \"g \\<otimes> x = g \\<otimes> y\"\n        hence \"(inv g) \\<otimes> (g \\<otimes> x) = (inv g) \\<otimes> (g \\<otimes> y)\" by simp\n        with g invg xG yG have \"(inv g \\<otimes> g) \\<otimes> x = (inv g \\<otimes> g) \\<otimes> y\" by (metis m_assoc)\n        with g invg xG yG show  \"x = y\" by simp\n    qed\n  next\n    fix x\n    assume \"x \\<in> M\"\n    thus \"g \\<otimes> x \\<in> g <# M\" unfolding l_coset_def by auto\n  next\n    fix x\n    assume x:\"x \\<in> g <# M\"\n    then obtain m where \"x = g \\<otimes> m\" \"m \\<in> M\" unfolding l_coset_def by auto\n    thus \"x \\<in> (\\<otimes>) g ` M\" by simp\n  qed\n  thus \"card (g <# M) = card M\" by (metis bij_betw_same_card)\nqed\n\nsubsection \\<open>Conjugation is a group action\\<close>\n\ntext \\<open>We will now prove that conjugation acts on the subgroups\nof a certain group. A large part of this proof consists of showing that\nthe conjugation of a subgroup with a group element is, again, a subgroup.\\<close>\n\nlemma conjugation_subgroup:\n  assumes HG:\"subgroup H G\"\n  assumes gG:\"g \\<in> carrier G\"\n  shows \"subgroup (g <# (H #> inv g)) G\"\nproof\n  from gG have \"inv g \\<in> carrier G\" by (rule inv_closed)\n  with HG have \"(H #> inv g) \\<subseteq> carrier G\" by (metis r_coset_subset_G subgroup.subset)\n  with gG show \"g <# (H #> inv g) \\<subseteq> carrier G\" by (metis l_coset_subset_G)\nnext\n  from gG have invgG:\"inv g \\<in> carrier G\" by (metis inv_closed)\n  with HG have lcosSubset:\"(H #> inv g) \\<subseteq> carrier G\" by (metis r_coset_subset_G subgroup.subset)\n  fix x y\n  assume x:\"x \\<in> g <# (H #> inv g)\" and y:\"y \\<in> g <# (H #> inv g)\"\n  then obtain x' y' where x':\"x' \\<in> H #> inv g\" \"x = g \\<otimes> x'\" and y':\"y' \\<in> H #> inv g\" \"y = g \\<otimes> y'\" unfolding l_coset_def by auto\n  then obtain hx hy where hx:\"hx \\<in> H\" \"x' = hx \\<otimes> inv g\" and hy:\"hy \\<in> H\" \"y' = hy \\<otimes> inv g\" unfolding r_coset_def by auto\n  with x' y' have x2:\"x = g \\<otimes> (hx \\<otimes> inv g)\" and y2:\"y = g \\<otimes> (hy \\<otimes> inv g)\" by auto\n  hence \"x \\<otimes> y = (g \\<otimes> (hx \\<otimes> inv g)) \\<otimes> (g \\<otimes> (hy \\<otimes> inv g))\" by simp\n  also from hx hy HG have hxG:\"hx \\<in> carrier G\" and hyG:\"hy \\<in> carrier G\" by (metis subgroup.mem_carrier)+\n  with gG hy x2 invgG have \"(g \\<otimes> (hx \\<otimes> inv g)) \\<otimes> (g \\<otimes> (hy \\<otimes> inv g)) = g \\<otimes> hx \\<otimes> (inv g \\<otimes> g) \\<otimes> hy \\<otimes> inv g\" by (metis m_assoc m_closed)\n  also from invgG gG have \"... = g \\<otimes> hx \\<otimes> \\<one> \\<otimes> hy \\<otimes> inv g\" by simp\n  also from gG hxG have \"... = g \\<otimes> hx \\<otimes> hy \\<otimes> inv g\" by (metis m_closed r_one)\n  also from gG hxG invgG have \"... = g \\<otimes> ((hx \\<otimes> hy) \\<otimes> inv g)\" by (metis gG hxG hyG invgG m_assoc m_closed)\n  finally have xy:\"x \\<otimes> y = g \\<otimes> (hx \\<otimes> hy \\<otimes> inv g)\".\n  from hx hy HG have \"hx \\<otimes> hy \\<in> H\" by (metis subgroup.m_closed)\n  with invgG HG have \"(hx \\<otimes> hy) \\<otimes> inv g \\<in> H #> inv g\" by (metis rcosI subgroup.subset)\n  with gG lcosSubset have \"g \\<otimes> (hx \\<otimes> hy \\<otimes> inv g) \\<in> g <# (H #> inv g)\" by (metis lcosI)\n  with xy show \"x \\<otimes> y \\<in> g <# (H #> inv g)\" by simp\nnext\n  from gG have invgG:\"inv g \\<in> carrier G\" by (metis inv_closed)\n  with HG have lcosSubset:\"(H #> inv g) \\<subseteq> carrier G\" by (metis r_coset_subset_G subgroup.subset)\n  from HG have \"\\<one> \\<in> H\" by (rule subgroup.one_closed)\n  with invgG HG have  \"\\<one> \\<otimes> inv g \\<in> H #> inv g\" by (metis rcosI subgroup.subset)\n  with gG lcosSubset have \"g \\<otimes> (\\<one> \\<otimes> inv g) \\<in> g <# (H #> inv g)\" by (metis lcosI)\n  with gG invgG show \"\\<one> \\<in> g <# (H #> inv g)\" by simp\nnext\n  from gG have invgG:\"inv g \\<in> carrier G\" by (metis inv_closed)\n  with HG have lcosSubset:\"(H #> inv g) \\<subseteq> carrier G\" by (metis r_coset_subset_G subgroup.subset)\n  fix x\n  assume \"x \\<in> g <# (H #> inv g)\"\n  then obtain x' where x':\"x' \\<in> H #> inv g\" \"x = g \\<otimes> x'\" unfolding l_coset_def by auto\n  then obtain hx where hx:\"hx \\<in> H\" \"x' = hx \\<otimes> inv g\"  unfolding r_coset_def by auto\n  with HG have invhx:\"inv hx \\<in> H\" by (metis subgroup.m_inv_closed)\n  from x' hx have \"inv x = inv (g \\<otimes> (hx \\<otimes> inv g))\" by simp\n  also from x' hx HG gG invgG have \"... = inv (inv g) \\<otimes> inv hx \\<otimes> inv g\" by (metis calculation in_mono inv_mult_group lcosSubset subgroup.mem_carrier)\n  also from gG have \"... = g \\<otimes> inv hx \\<otimes> inv g\" by simp\n  also from gG invgG invhx HG have \"... = g \\<otimes> (inv hx \\<otimes> inv g)\" by (metis m_assoc subgroup.mem_carrier)\n  finally have invx:\"inv x = g \\<otimes> (inv hx \\<otimes> inv g)\".\n  with invhx invgG HG have \"(inv hx) \\<otimes> inv g \\<in> H #> inv g\" by (metis rcosI subgroup.subset)\n  with gG lcosSubset have \"g \\<otimes> (inv hx \\<otimes> inv g) \\<in> g <# (H #> inv g)\" by (metis lcosI)\n  with invx show \"inv x \\<in> g <# (H #> inv g)\" by simp\nqed\n\ndefinition conjugation_action::\"nat \\<Rightarrow> _\"\n  where \"conjugation_action p = (\\<lambda>g\\<in>carrier G. \\<lambda>P\\<in>subgroups_of_size p. g <# (P #> inv g))\"\n\nlemma conjugation_is_size_invariant:\n  assumes fin:\"finite (carrier G)\"\n  assumes P:\"P \\<in> subgroups_of_size p\"\n  assumes g:\"g \\<in> carrier G\"\n  shows \"conjugation_action p g P \\<in> subgroups_of_size p\"\nproof -\n  from g have invg:\"inv g \\<in> carrier G\" by (metis inv_closed)\n  from P have PG:\"subgroup P G\" and card:\"card P = p\" unfolding subgroups_of_size_def by simp+\n  hence PsubG:\"P \\<subseteq> carrier G\" by (metis subgroup.subset)\n  hence PinvgsubG:\"P #> inv g \\<subseteq> carrier G\" by (metis invg r_coset_subset_G)\n  have \" g <# (P #> inv g) \\<in> subgroups_of_size p\"\n  proof(auto simp add:subgroups_of_size_def)\n    show \"subgroup (g <# (P #> inv g)) G\" by (metis g PG conjugation_subgroup)\n  next\n    from card PsubG fin invg have \"card (P #> inv g) = p\" by (metis cardeq_rcoset)\n    with g PinvgsubG fin show \"card (g <# (P #> inv g)) = p\" by (metis cardeq_lcoset)\n  qed\n  with P g show ?thesis unfolding conjugation_action_def by simp\nqed\n\nlemma conjugation_is_Bij:\n  assumes fin:\"finite (carrier G)\"\n  assumes g:\"g \\<in> carrier G\"\n  shows \"conjugation_action p g \\<in> Bij (subgroups_of_size p)\"\nproof -\n  from g have invg:\"inv g \\<in> carrier G\" by (rule inv_closed)\n  from g have \"conjugation_action p g \\<in> extensional (subgroups_of_size p)\" unfolding conjugation_action_def by simp\n  moreover have \"bij_betw (conjugation_action p g) (subgroups_of_size p) (subgroups_of_size p)\"\n  proof(auto simp add:bij_betw_def)\n    show \"inj_on (conjugation_action p g) (subgroups_of_size p)\"\n    proof(rule inj_onI)\n      fix U V\n      assume U:\"U \\<in> subgroups_of_size p\" and V:\"V \\<in> subgroups_of_size p\"\n      hence subsetG:\"U \\<subseteq> carrier G\" \"V \\<subseteq> carrier G\" unfolding subgroups_of_size_def by (metis (lifting) mem_Collect_eq subgroup.subset)+\n      hence subsetL:\"U #> inv g \\<subseteq> carrier G\" \"V #> inv g \\<subseteq> carrier G\" by (metis invg r_coset_subset_G)+\n      assume \"conjugation_action p g U = conjugation_action p g V\"\n      with g U V have \"g <# (U #> inv g) = g <# (V #> inv g)\" unfolding conjugation_action_def by simp\n      hence \"(inv g) <# (g <# (U #> inv g)) = (inv g) <# (g <# (V #> inv g))\" by simp\n      hence \"(inv g \\<otimes> g) <# (U #> inv g) = (inv g \\<otimes> g) <# (V #> inv g)\" by (metis g invg lcos_m_assoc r_coset_subset_G subsetG)\n      hence \"\\<one> <# (U #> inv g) = \\<one> <# (V #> inv g)\" by (metis g l_inv)\n      hence \"U #> inv g = V #> inv g\" by (metis subsetL lcos_mult_one)\n      hence \"(U #> inv g) #> g = (V #> inv g) #> g\" by simp\n      hence \"U #> (inv g \\<otimes> g) = V #> (inv g \\<otimes> g)\" by (metis coset_mult_assoc g inv_closed subsetG)\n      hence \"U #> \\<one> = V #> \\<one>\" by (metis g l_inv)\n      thus \"U = V\" by (metis coset_mult_one subsetG)\n    qed\n  next\n    fix P\n    assume \"P \\<in> subgroups_of_size p\"\n    thus \"conjugation_action p g P \\<in> subgroups_of_size p\" by (metis fin g conjugation_is_size_invariant)\n  next\n    fix P\n    assume P:\"P \\<in> subgroups_of_size p\"\n    with invg have \"conjugation_action p (inv g) P \\<in> subgroups_of_size p\" by (metis fin invg conjugation_is_size_invariant)\n    with invg P have \"(inv g) <# (P #> (inv (inv g))) \\<in> subgroups_of_size p\" unfolding conjugation_action_def by simp\n    hence 1:\"(inv g) <# (P #> g) \\<in> subgroups_of_size p\" by (metis g inv_inv)\n    have \"g <# (((inv g) <# (P #> g)) #> inv g) = (\\<Union>p \\<in> P. {g \\<otimes> (inv g \\<otimes> (p \\<otimes> g) \\<otimes> inv g)})\" unfolding r_coset_def l_coset_def by (simp add:m_assoc)\n    also from P have PG:\"P \\<subseteq> carrier G\" unfolding subgroups_of_size_def by (auto simp add:subgroup.subset)\n    have \"\\<forall>p \\<in> P.  g \\<otimes> (inv g \\<otimes> (p \\<otimes> g) \\<otimes> inv g) = p\"\n    proof(auto)\n      fix p\n      assume \"p \\<in> P\"\n      with PG have p:\"p \\<in> carrier G\"..\n      with g invg have \"g \\<otimes> (inv g \\<otimes> (p \\<otimes> g) \\<otimes> inv g) = (g \\<otimes> inv g) \\<otimes> p \\<otimes> (g \\<otimes> inv g)\" by (metis m_assoc m_closed)\n      also with g invg g p have \"... = p\" by (metis l_one r_inv r_one)\n      finally show \"g \\<otimes> (inv g \\<otimes> (p \\<otimes> g) \\<otimes> inv g) = p\". \n    qed\n    hence \"(\\<Union>p \\<in> P. {g \\<otimes> (inv g \\<otimes> (p \\<otimes> g) \\<otimes> inv g)}) = P\" by simp\n    finally have \"g <# (((inv g) <# (P #> g)) #> inv g) = P\".\n    with 1 have \"P \\<in> (\\<lambda>P. g <# (P #> inv g)) ` subgroups_of_size p\" by auto\n    with P g show \"P \\<in> conjugation_action p g ` subgroups_of_size p\" unfolding conjugation_action_def by simp\n  qed\n  ultimately show ?thesis unfolding BijGroup_def Bij_def by simp\nqed\n\nlemma lr_coset_assoc:\n  assumes g:\"g \\<in> carrier G\"\n  assumes h:\"h \\<in> carrier G\"\n  assumes P:\"P \\<subseteq> carrier G\"\n  shows \"g <# (P #> h) = (g <# P) #> h\"\nproof(auto)\n  fix x\n  assume \"x \\<in> g <# (P #> h)\"\n  then obtain p where \"p \\<in> P\" and p:\"x = g \\<otimes> (p \\<otimes> h)\" unfolding l_coset_def r_coset_def by auto\n  with P have \"p \\<in> carrier G\" by auto\n  with g h p have \"x = (g \\<otimes> p) \\<otimes> h\" by (metis m_assoc)\n  with \\<open>p \\<in> P\\<close> show \"x \\<in> (g <# P) #> h\" unfolding l_coset_def r_coset_def by auto\nnext\n  fix x\n  assume \"x \\<in> (g <# P) #> h\"\n  then obtain p where \"p \\<in> P\" and p:\"x = (g \\<otimes> p) \\<otimes> h\" unfolding l_coset_def r_coset_def by auto\n  with P have \"p \\<in> carrier G\" by auto\n  with g h p have \"x = g \\<otimes> (p \\<otimes> h)\" by (metis m_assoc)\n  with \\<open>p \\<in> P\\<close> show \"x \\<in> g <# (P #> h)\" unfolding l_coset_def r_coset_def by auto\nqed\n\ntheorem acts_on_subsets:\n  assumes fin:\"finite (carrier G)\"\n  shows \"group_action G (conjugation_action p) (subgroups_of_size p)\"\nunfolding group_action_def group_action_axioms_def group_hom_def group_hom_axioms_def hom_def\napply(auto simp add:is_group group_BijGroup)\nproof -\n  fix g\n  assume g:\"g \\<in> carrier G\"\n  with fin show \"conjugation_action p g \\<in> carrier (BijGroup (subgroups_of_size p))\"\n    unfolding BijGroup_def by (metis conjugation_is_Bij partial_object.select_convs(1))\nnext\n  fix x y\n  assume x:\"x \\<in> carrier G\" and y:\"y \\<in> carrier G\"\n  hence invx:\"inv x \\<in> carrier G\" and invy:\"inv y \\<in> carrier G\" by (metis inv_closed)+\n  from x y have xyG:\"x \\<otimes> y \\<in> carrier G\" by (metis m_closed)\n  define conjx where \"conjx = conjugation_action p x\"\n  define conjy where \"conjy = conjugation_action p y\"\n  from fin x have xBij:\"conjx \\<in> Bij (subgroups_of_size p)\" unfolding conjx_def by (metis conjugation_is_Bij)\n  from fin y have yBij:\"conjy \\<in> Bij (subgroups_of_size p)\" unfolding conjy_def by (metis conjugation_is_Bij)\n  have \"conjx \\<otimes>\\<^bsub>BijGroup (subgroups_of_size p)\\<^esub> conjy\n    = (\\<lambda>g\\<in>Bij (subgroups_of_size p). restrict (compose (subgroups_of_size p) g) (Bij (subgroups_of_size p))) conjx conjy\" unfolding BijGroup_def by simp\n  also from xBij yBij have \"... = compose (subgroups_of_size p) conjx conjy\" by simp\n  also have \"... = (\\<lambda>P\\<in>subgroups_of_size p. conjx (conjy P))\" by (metis compose_def)\n  also have \"... = (\\<lambda>P\\<in>subgroups_of_size p. x \\<otimes> y <# (P #> inv (x \\<otimes> y)))\"\n  proof(rule restrict_ext)\n    fix P\n    assume P:\"P \\<in> subgroups_of_size p\"\n    hence PG:\"P \\<subseteq> carrier G\" unfolding subgroups_of_size_def by (auto simp:subgroup.subset)\n    with y have yPG:\"y <# P \\<subseteq> carrier G\" by (metis l_coset_subset_G)\n    from x y have invxyG:\"inv (x \\<otimes> y) \\<in> carrier G\" and xyG:\"x \\<otimes> y \\<in> carrier G\" using inv_closed m_closed by auto\n    from yBij have \"conjy ` subgroups_of_size p = subgroups_of_size p\" unfolding Bij_def bij_betw_def by simp\n    with P have conjyP:\"conjy P \\<in> subgroups_of_size p\" unfolding Bij_def bij_betw_def by (metis (full_types) imageI) \n    with x y P have \"conjx (conjy P) = x <# ((y <# (P #> inv y)) #> inv x)\" unfolding conjy_def conjx_def conjugation_action_def by simp\n    also from y invy PG have \"... = x <# (((y <# P) #> inv y) #> inv x)\" by (metis lr_coset_assoc)\n    also from PG invx invy y have \"... = x <# ((y <# P) #> (inv y \\<otimes> inv x))\" by (metis coset_mult_assoc yPG)\n    also from x y have \"... = x <# ((y <# P) #> inv (x \\<otimes> y))\" by (metis inv_mult_group)\n    also from invxyG x yPG have \"... = (x <# (y <# P)) #> inv (x \\<otimes> y)\" by (metis lr_coset_assoc)\n    also from x y PG have \"... = ((x \\<otimes> y) <# P) #> inv (x \\<otimes> y)\" by (metis lcos_m_assoc)\n    also from xyG invxyG PG have \"... = (x \\<otimes> y) <# (P #> inv (x \\<otimes> y))\" by (metis lr_coset_assoc)\n    finally show \"conjx (conjy P) = x \\<otimes> y <# (P #> inv (x \\<otimes> y))\".\n  qed\n  finally have \"conjx \\<otimes>\\<^bsub>BijGroup (subgroups_of_size p)\\<^esub> conjy = (\\<lambda>P\\<in>subgroups_of_size p. x \\<otimes> y <# (P #> inv (x \\<otimes> y)))\".\n  with xyG show \"conjugation_action p (x \\<otimes> y)\n    = conjugation_action p x \\<otimes>\\<^bsub>BijGroup (subgroups_of_size p)\\<^esub> conjugation_action p y\"\n    unfolding conjx_def conjy_def conjugation_action_def by simp\nqed\n\nsubsection \\<open>Properties of the Conjugation Action\\<close>\n\n\n\ncorollary stabilizer_supergrp_P:\n  assumes fin:\"finite (carrier G)\"\n  assumes P:\"P \\<in> subgroups_of_size p\"\n  shows \"subgroup P (G\\<lparr>carrier := group_action.stabilizer G (conjugation_action p) P\\<rparr>)\"\nproof -\n  from assms have \"P \\<subseteq> group_action.stabilizer G (conjugation_action p) P\" by (rule stabilizer_contains_P)\n  moreover from P have \"subgroup P G\" unfolding subgroups_of_size_def by simp\n  moreover from P fin have \"subgroup (group_action.stabilizer G (conjugation_action p) P) G\" by (metis acts_on_subsets group_action.stabilizer_is_subgroup)\n  ultimately show ?thesis by (metis is_group subgroup.subgroup_of_subset)\nqed\n\nlemma (in group) P_fixed_point_of_P_conj:\n  assumes fin:\"finite (carrier G)\"\n  assumes P:\"P \\<in> subgroups_of_size p\"\n  shows \"P \\<in> group_action.fixed_points (G\\<lparr>carrier := P\\<rparr>) (conjugation_action p) (subgroups_of_size p)\"\nproof -\n  from fin interpret conjG: group_action G \"conjugation_action p\" \"subgroups_of_size p\" by (rule acts_on_subsets)\n  from P have \"subgroup P G\" unfolding subgroups_of_size_def by simp\n  with fin interpret conjP: group_action \"G\\<lparr>carrier := P\\<rparr>\" \"(conjugation_action p)\" \"(subgroups_of_size p)\" by (metis acts_on_subsets group_action.subgroup_action)\n  from fin P have \"P \\<subseteq> conjG.stabilizer P\" by (rule stabilizer_contains_P)\n  hence \"P \\<subseteq> conjP.stabilizer P\" using conjG.stabilizer_def conjP.stabilizer_def by auto\n  with P show \"P \\<in> conjP.fixed_points\" unfolding conjP.fixed_points_def by auto\nqed\n\nlemma conj_wo_inv:\n  assumes QG:\"subgroup Q G\"\n  assumes PG:\"subgroup P G\"\n  assumes g:\"g \\<in> carrier G\"\n  assumes conj:\"inv g <# (Q #> g) = P\"\n  shows \"Q #> g = g <# P\"\nproof -\n  from g have invg:\"inv g \\<in> carrier G\" by (metis inv_closed)\n  from conj have \"g <# (inv g <# (Q #> g)) = g <# P\" by simp\n  with QG g invg have \"(g \\<otimes> inv g) <# (Q #> g) = g <# P\" by (metis lcos_m_assoc r_coset_subset_G subgroup.subset)\n  with g invg have \"\\<one> <# (Q #> g) = g <# P\" by (metis r_inv)\n  with QG g show \"Q #> g = g <# P\" by (metis lcos_mult_one r_coset_subset_G subgroup.subset)\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/Secondary_Sylow/SubgroupConjugation.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094174159127, "lm_q2_score": 0.8289387998695209, "lm_q1q2_score": 0.7404988363848876}}
{"text": "(*\n    Authors:    Jose Divas\u00f3n\n                Maximilian Haslbeck\n                Sebastiaan Joosten\n                Ren\u00e9 Thiemann\n                Akihisa Yamada\n    License:    BSD\n*)\n\nsection \\<open>The LLL Algorithm\\<close>\n\ntext \\<open>Soundness of the LLL algorithm is proven in four steps. \n  In the basic version, we do recompute the Gram-Schmidt ortogonal (GSO) basis \n  in every step. This basic version will have a full functional soundness proof, \n  i.e., termination and the property that the returned basis is reduced.\n  Then in LLL-Number-Bounds we will strengthen the invariant and prove that\n  all intermediate numbers stay polynomial in size.\n  Moreover, in LLL-Impl we will refine the basic version, so that\n  the GSO does not need to be recomputed in every step. \n  Finally, in LLL-Complexity, we develop an cost-annotated version\n  of the refined algorithm and prove a polynomial upper bound on the \n  number of arithmetic operations.\\<close> \n\n\ntext \\<open>This theory provides a basic implementation and a soundness proof of the LLL algorithm\n      to compute a \"short\" vector in a lattice.\\<close> \n\ntheory LLL\n  imports \n    Gram_Schmidt_2 \n    Missing_Lemmas \n    Jordan_Normal_Form.Determinant \n    \"Abstract-Rewriting.SN_Order_Carrier\"\nbegin\n\nsubsection \\<open>Core Definitions, Invariants, and Theorems for Basic Version\\<close>\n\n(* Note/TODO by Max Haslbeck:\n  Up to here I refactored the code in Gram_Schmidt_2 and Gram_Schmidt_Int which now makes heavy\n  use of locales. In the future I would also like to do this here (instead of using LLL_invariant\n  everywhere). *)\n\nlocale LLL =\n  fixes n :: nat (* n-dimensional vectors, *)\n    and m :: nat (* number of vectors *)\n    and fs_init :: \"int vec list\" (* initial basis *)\n    and \\<alpha> :: rat (* approximation factor *)\n\nbegin\n\nsublocale vec_module \"TYPE(int)\" n.\n\n\n\n\nabbreviation RAT where \"RAT \\<equiv> map (map_vec rat_of_int)\" \nabbreviation SRAT where \"SRAT xs \\<equiv> set (RAT xs)\" \nabbreviation Rn where \"Rn \\<equiv> carrier_vec n :: rat vec set\" \n\nsublocale gs: gram_schmidt_fs n \"RAT fs_init\" .\n\nabbreviation lin_indep where \"lin_indep fs \\<equiv> gs.lin_indpt_list (RAT fs)\" \nabbreviation gso where \"gso fs \\<equiv> gram_schmidt_fs.gso n (RAT fs)\"\nabbreviation \\<mu> where \"\\<mu> fs \\<equiv> gram_schmidt_fs.\\<mu> n (RAT fs)\"\n\nabbreviation reduced where \"reduced fs \\<equiv> gram_schmidt_fs.reduced n (RAT fs) \\<alpha>\" \nabbreviation weakly_reduced where \"weakly_reduced fs \\<equiv> gram_schmidt_fs.weakly_reduced n (RAT fs) \\<alpha>\" \n  \ntext \\<open>lattice of initial basis\\<close>\ndefinition \"L = lattice_of fs_init\" \n\ntext \\<open>maximum squared norm of initial basis\\<close>\ndefinition \"N = max_list (map (nat \\<circ> sq_norm) fs_init)\" \n\ntext \\<open>maximum absolute value in initial basis\\<close>\ndefinition \"M = Max ({abs (fs_init ! i $ j) | i j. i < m \\<and> j < n} \\<union> {0})\" \n\ntext \\<open>This is the core invariant which enables to prove functional correctness.\\<close>\n\ndefinition \"\\<mu>_small fs i = (\\<forall> j < i. abs (\\<mu> fs i j) \\<le> 1/2)\" \n\ndefinition LLL_invariant :: \"bool \\<Rightarrow> nat \\<Rightarrow> int vec list \\<Rightarrow> bool\" where \n  \"LLL_invariant upw i fs = ( \n    gs.lin_indpt_list (RAT fs) \\<and> \n    lattice_of fs = L \\<and>\n    reduced fs i \\<and>\n    i \\<le> m \\<and> \n    length fs = m \\<and>\n    (upw \\<or> \\<mu>_small fs i)    \n  )\" \n\nlemma LLL_invD: assumes \"LLL_invariant upw i fs\"\n  shows \n  \"lin_indep fs\" \n  \"length (RAT fs) = m\" \n  \"set fs \\<subseteq> carrier_vec n\"\n  \"\\<And> i. i < m \\<Longrightarrow> fs ! i \\<in> carrier_vec n\" \n  \"\\<And> i. i < m \\<Longrightarrow> gso fs i \\<in> carrier_vec n\" \n  \"length fs = m\"\n  \"lattice_of fs = L\" \n  \"weakly_reduced fs i\"\n  \"i \\<le> m\"\n  \"reduced fs i\" \n  \"upw \\<or> \\<mu>_small fs i\"\nproof (atomize (full), goal_cases)\n  case 1\n  interpret gs': gram_schmidt_fs_lin_indpt n \"RAT fs\"\n    by (standard) (use assms LLL_invariant_def gs.lin_indpt_list_def in auto)\n  show ?case\n    using assms gs'.fs_carrier gs'.f_carrier gs'.gso_carrier\n    by (auto simp add: LLL_invariant_def gram_schmidt_fs.reduced_def)\nqed\n\nlemma LLL_invI: assumes  \n  \"set fs \\<subseteq> carrier_vec n\"\n  \"length fs = m\"\n  \"lattice_of fs = L\" \n  \"i \\<le> m\"\n  \"lin_indep fs\" \n  \"reduced fs i\" \n  \"upw \\<or> \\<mu>_small fs i\" \nshows \"LLL_invariant upw i fs\" \n  unfolding LLL_invariant_def Let_def split using assms by auto\n\n\n\nend\n\nlocale fs_int' =\n  fixes n m fs_init \\<alpha> upw i fs \n  assumes LLL_inv: \"LLL.LLL_invariant n m fs_init \\<alpha> upw i fs\"\n\nsublocale fs_int' \\<subseteq> fs_int_indpt\n   using LLL_inv unfolding LLL.LLL_invariant_def by (unfold_locales) blast\n\ncontext LLL\nbegin\n\nlemma gso_cong: assumes \"\\<And> i. i \\<le> x \\<Longrightarrow> f1 ! i = f2 ! i\"\n   \"x < length f1\" \"x < length f2\" \n  shows \"gso f1 x = gso f2 x\"\n  by (rule gs.gso_cong, insert assms, auto)\n  \nlemma \\<mu>_cong: assumes \"\\<And> k. j < i \\<Longrightarrow> k \\<le> j \\<Longrightarrow> f1 ! k = f2 ! k\"\n  and i: \"i < length f1\" \"i < length f2\" \n  and \"j < i \\<Longrightarrow> f1 ! i = f2 ! i\" \n  shows \"\\<mu> f1 i j = \\<mu> f2 i j\"\n  by (rule gs.\\<mu>_cong, insert assms, auto)\n    \ndefinition reduction where \"reduction = (4+\\<alpha>)/(4*\\<alpha>)\"\n\n\ndefinition d :: \"int vec list \\<Rightarrow> nat \\<Rightarrow> int\" where \"d fs k = gs.Gramian_determinant fs k\"\ndefinition D :: \"int vec list \\<Rightarrow> nat\" where \"D fs = nat (\\<Prod> i < m. d fs i)\" \n\ndefinition \"d\\<mu> gs i j = int_of_rat (of_int (d gs (Suc j)) * \\<mu> gs i j)\" \n\ndefinition logD :: \"int vec list \\<Rightarrow> nat\"\n  where \"logD fs = (if \\<alpha> = 4/3 then (D fs) else nat (floor (log (1 / of_rat reduction) (D fs))))\" \n\ndefinition LLL_measure :: \"nat \\<Rightarrow> int vec list \\<Rightarrow> nat\" where \n  \"LLL_measure i fs = (2 * logD fs + m - i)\" \n\ncontext\n  fixes upw i fs\n  assumes Linv: \"LLL_invariant upw i fs\"\nbegin\n\ninterpretation fs: fs_int' n m fs_init \\<alpha> upw i fs\n  by (standard) (use Linv in auto)\n\nlemma Gramian_determinant:\n  assumes k: \"k \\<le> m\" \nshows \"of_int (gs.Gramian_determinant fs k) = (\\<Prod> j<k. sq_norm (gso fs j))\" (is ?g1)\n  \"gs.Gramian_determinant fs k > 0\" (is ?g2)\n  using assms fs.Gramian_determinant LLL_invD[OF Linv]  by auto\n   \nlemma LLL_d_pos [intro]: assumes k: \"k \\<le> m\" \nshows \"d fs k > 0\"\n  unfolding d_def using fs.Gramian_determinant k LLL_invD[OF Linv] by auto\n\nlemma LLL_d_Suc: assumes k: \"k < m\" \nshows \"of_int (d fs (Suc k)) = sq_norm (gso fs k) * of_int (d fs k)\" \n  using assms fs.fs_int_d_Suc  LLL_invD[OF Linv] unfolding fs.d_def d_def by auto\n\nlemma LLL_D_pos:\n  shows \"D fs > 0\"\n  using fs.fs_int_D_pos LLL_invD[OF Linv] unfolding D_def fs.D_def fs.d_def d_def by auto\n\ntext \\<open>Condition when we can increase the value of $i$\\<close>\n\nlemma increase_i:\n  assumes i: \"i < m\" \n  and upw: \"upw \\<Longrightarrow> i = 0\" \n  and red_i: \"i \\<noteq> 0 \\<Longrightarrow> sq_norm (gso fs (i - 1)) \\<le> \\<alpha> * sq_norm (gso fs i)\"\nshows \"LLL_invariant True (Suc i) fs\" \"LLL_measure i fs > LLL_measure (Suc i) fs\" \nproof -\n  note inv = LLL_invD[OF Linv]\n  from inv(8,10) have red: \"weakly_reduced fs i\" \n    and sred: \"reduced fs i\" by (auto)\n  from red red_i i have red: \"weakly_reduced fs (Suc i)\" \n    unfolding gram_schmidt_fs.weakly_reduced_def\n    by (intro allI impI, rename_tac ii, case_tac \"Suc ii = i\", auto)\n  from inv(11) upw have sred_i: \"\\<And> j. j < i \\<Longrightarrow> \\<bar>\\<mu> fs i j\\<bar> \\<le> 1 / 2\" \n    unfolding \\<mu>_small_def by auto\n  from sred sred_i have sred: \"reduced fs (Suc i)\"\n    unfolding gram_schmidt_fs.reduced_def\n    by (intro conjI[OF red] allI impI, rename_tac ii j, case_tac \"ii = i\", auto)\n  show \"LLL_invariant True (Suc i) fs\" \n    by (intro LLL_invI, insert inv red sred i, auto)\n  show \"LLL_measure i fs > LLL_measure (Suc i) fs\" unfolding LLL_measure_def using i by auto\nqed\n\nend\n\ntext \\<open>Standard addition step which makes $\\mu_{i,j}$ small\\<close>\n\ndefinition \"\\<mu>_small_row i fs j = (\\<forall> j'. j \\<le> j' \\<longrightarrow> j' < i \\<longrightarrow> abs (\\<mu> fs i j') \\<le> inverse 2)\"\n\nlemma basis_reduction_add_row_main: assumes Linv: \"LLL_invariant True i fs\"\n  and i: \"i < m\"  and j: \"j < i\" \n  and fs': \"fs' = fs[ i := fs ! i - c \\<cdot>\\<^sub>v fs ! j]\" \nshows \"LLL_invariant True i fs'\"\n  \"c = round (\\<mu> fs i j) \\<Longrightarrow> \\<mu>_small_row i fs (Suc j) \\<Longrightarrow> \\<mu>_small_row i fs' j\" (* mu-value at position i j gets small *)\n  \"LLL_measure i fs' = LLL_measure i fs\" \n  (* new values of gso: no change *)\n  \"\\<And> i. i < m \\<Longrightarrow> gso fs' i = gso fs i\" \n  (* new values of mu *)\n  \"\\<And> i' j'. i' < m \\<Longrightarrow> j' < m \\<Longrightarrow>       \n     \\<mu> fs' i' j' = (if i' = i \\<and> j' \\<le> j then \\<mu> fs i j' - of_int c * \\<mu> fs j j' else \\<mu> fs i' j')\"\n  (* new values of d *)\n  \"\\<And> ii. ii \\<le> m \\<Longrightarrow> d fs' ii = d fs ii\" \nproof -\n  define bnd :: rat where bnd: \"bnd = 4 ^ (m - 1 - Suc j) * of_nat (N ^ (m - 1) * m)\" \n  define M where \"M = map (\\<lambda>i. map (\\<mu> fs i) [0..<m]) [0..<m]\"\n  note inv = LLL_invD[OF Linv]\n  note Gr = inv(1)\n  have ji: \"j \\<le> i\" \"j < m\" and jstrict: \"j < i\" \n    and add: \"set fs \\<subseteq> carrier_vec n\" \"i < length fs\" \"j < length fs\" \"i \\<noteq> j\" \n    and len: \"length fs = m\" and red: \"weakly_reduced fs i\"\n    and indep: \"lin_indep fs\" \n    using inv j i by auto \n  let ?R = rat_of_int\n  let ?RV = \"map_vec ?R\"   \n  from inv i j\n  have Fij: \"fs ! i \\<in> carrier_vec n\" \"fs ! j \\<in> carrier_vec n\" by auto\n  let ?x = \"fs ! i - c \\<cdot>\\<^sub>v fs ! j\"  \n  let ?g = \"gso fs\"\n  let ?g' = \"gso fs'\"\n  let ?mu = \"\\<mu> fs\"\n  let ?mu' = \"\\<mu> fs'\"\n  from inv j i \n  have Fi:\"\\<And> i. i < length (RAT fs) \\<Longrightarrow> (RAT fs) ! i \\<in> carrier_vec n\"\n    and gs_carr: \"?g j \\<in> carrier_vec n\"\n                \"?g i \\<in> carrier_vec n\"\n                \"\\<And> i. i < j \\<Longrightarrow> ?g i \\<in> carrier_vec n\"\n                \"\\<And> j. j < i \\<Longrightarrow> ?g j \\<in> carrier_vec n\" \n    and len': \"length (RAT fs) = m\"\n    and add':\"set (map ?RV fs) \\<subseteq> carrier_vec n\"\n    by auto \n  have RAT_F1: \"RAT fs' = (RAT fs)[i := (RAT fs) ! i - ?R c \\<cdot>\\<^sub>v (RAT fs) ! j]\" \n    unfolding fs'\n  proof (rule nth_equalityI[rule_format], goal_cases)\n    case (2 k)\n    show ?case \n    proof (cases \"k = i\")\n      case False\n      thus ?thesis using 2 by auto\n    next\n      case True\n      hence \"?thesis = (?RV (fs ! i - c \\<cdot>\\<^sub>v fs ! j) =\n          ?RV (fs ! i) - ?R c \\<cdot>\\<^sub>v ?RV (fs ! j))\" \n        using 2 add by auto\n      also have \"\\<dots>\" by (rule eq_vecI, insert Fij, auto)\n      finally show ?thesis by simp\n    qed\n  qed auto\n  hence RAT_F1_i:\"RAT fs' ! i = (RAT fs) ! i - ?R c \\<cdot>\\<^sub>v (RAT fs) ! j\" (is \"_ = _ - ?mui\")\n    using i len by auto\n  have uminus: \"fs ! i - c \\<cdot>\\<^sub>v fs ! j = fs ! i + -c \\<cdot>\\<^sub>v fs ! j\" \n    by (subst minus_add_uminus_vec, insert Fij, auto)\n  have \"lattice_of fs' = lattice_of fs\" unfolding fs' uminus\n    by (rule lattice_of_add[OF add, of _ \"- c\"], auto)\n  with inv have lattice: \"lattice_of fs' = L\" by auto\n  from add len\n  have \"k < length fs \\<Longrightarrow> \\<not> k \\<noteq> i \\<Longrightarrow> fs' ! k \\<in> carrier_vec n\" for k\n    unfolding fs'\n    by (metis (no_types, lifting) nth_list_update nth_mem subset_eq carrier_dim_vec index_minus_vec(2) \n        index_smult_vec(2))\n  hence \"k < length fs \\<Longrightarrow> fs' ! k \\<in> carrier_vec n\" for k\n    unfolding fs' using add len by (cases \"k \\<noteq> i\",auto)\n  with len have F1: \"set fs' \\<subseteq> carrier_vec n\" \"length fs' = m\" unfolding fs' by (auto simp: set_conv_nth)\n  hence F1': \"length (RAT fs') = m\" \"SRAT fs' \\<subseteq> Rn\" by auto\n  from indep have dist: \"distinct (RAT fs)\" by (auto simp: gs.lin_indpt_list_def)\n  have Fij': \"(RAT fs) ! i \\<in> Rn\" \"(RAT fs) ! j \\<in> Rn\" using add'[unfolded set_conv_nth] i \\<open>j < m\\<close> len by auto\n  have uminus': \"(RAT fs) ! i - ?R c \\<cdot>\\<^sub>v (RAT fs) ! j = (RAT fs) ! i + - ?R c \\<cdot>\\<^sub>v (RAT fs) ! j\" \n    by (subst minus_add_uminus_vec[where n = n], insert Fij', auto) \n  have span_F_F1: \"gs.span (SRAT fs) = gs.span (SRAT fs')\" unfolding RAT_F1 uminus' \n    by (rule gs.add_vec_span, insert len add, auto)\n  have **: \"?RV (fs ! i) + - ?R c \\<cdot>\\<^sub>v (RAT fs) ! j =  ?RV (fs ! i - c \\<cdot>\\<^sub>v fs ! j)\"\n    by (rule eq_vecI, insert Fij len i j, auto)\n  from i j len have \"j < length (RAT fs)\" \"i < length (RAT fs)\" \"i \\<noteq> j\" by auto\n  from gs.lin_indpt_list_add_vec[OF this indep, of \"- of_int c\"]\n  have \"gs.lin_indpt_list ((RAT fs) [i := (RAT fs) ! i + - ?R c \\<cdot>\\<^sub>v (RAT fs) ! j])\" (is \"gs.lin_indpt_list ?F1\") .\n  also have \"?F1 = RAT fs'\" unfolding fs' using i len Fij' **\n    by (auto simp: map_update)\n  finally have indep_F1: \"lin_indep fs'\" .\n  have conn1: \"set (RAT fs) \\<subseteq> carrier_vec n\"  \"length (RAT fs) = m\" \"distinct (RAT fs)\"\n    \"gs.lin_indpt (set (RAT fs))\"\n    using inv unfolding gs.lin_indpt_list_def by auto\n  have conn2: \"set (RAT fs') \\<subseteq> carrier_vec n\"  \"length (RAT fs') = m\" \"distinct (RAT fs')\"\n    \"gs.lin_indpt (set (RAT fs'))\"\n    using indep_F1 F1' unfolding gs.lin_indpt_list_def by auto\n  interpret gs1: gram_schmidt_fs_lin_indpt n \"RAT fs\"\n    by (standard) (use LLL_invD[OF assms(1)] gs.lin_indpt_list_def in auto)\n  interpret gs2: gram_schmidt_fs_lin_indpt n \"RAT fs'\"\n    by (standard) (use indep_F1 F1' gs.lin_indpt_list_def in auto)\n  let ?G = \"map ?g [0 ..< m]\" \n  let ?G' = \"map ?g' [0 ..< m]\" \n  from gs1.span_gso gs2.span_gso gs1.gso_carrier gs2.gso_carrier conn1 conn2 span_F_F1 len \n  have span_G_G1: \"gs.span (set ?G) = gs.span (set ?G')\"\n   and lenG: \"length ?G = m\" \n   and Gi: \"i < length ?G \\<Longrightarrow> ?G ! i \\<in> Rn\"\n   and G1i: \"i < length ?G' \\<Longrightarrow> ?G' ! i \\<in> Rn\" for i\n    by auto\n  have eq: \"x \\<noteq> i \\<Longrightarrow> RAT fs' ! x = (RAT fs) ! x\" for x unfolding RAT_F1 by auto\n  hence eq_part: \"x < i \\<Longrightarrow> ?g' x = ?g x\" for x\n    by (intro gs.gso_cong, insert len, auto)\n  have G: \"i < m \\<Longrightarrow> (RAT fs) ! i \\<in> Rn\"\n       \"i < m \\<Longrightarrow> fs ! i \\<in> carrier_vec n\" for i by(insert add len', auto)\n  note carr1[intro] = this[OF i] this[OF ji(2)]\n  have \"x < m \\<Longrightarrow> ?g x \\<in> Rn\" \n       \"x < m \\<Longrightarrow> ?g' x \\<in> Rn\"\n       \"x < m \\<Longrightarrow> dim_vec (gso fs x) = n\"\n       \"x < m \\<Longrightarrow> dim_vec (gso fs' x) = n\"\n       for x using inv G1i by (auto simp:o_def Gi G1i)\n  hence carr2[intro!]:\"?g i \\<in> Rn\" \"?g' i \\<in> Rn\"\n                 \"?g ` {0..<i} \\<subseteq> Rn\"\n                 \"?g ` {0..<Suc i} \\<subseteq> Rn\" using i by auto\n  have F1_RV: \"?RV (fs' ! i) = RAT fs' ! i\" using i F1 by auto\n  have F_RV: \"?RV (fs ! i) = (RAT fs) ! i\" using i len by auto\n  from eq_part \n  have span_G1_G: \"gs.span (?g' ` {0..<i}) = gs.span (?g ` {0..<i})\" (is \"?ls = ?rs\")\n    apply(intro cong[OF refl[of \"gs.span\"]],rule image_cong[OF refl]) using eq by auto\n  have \"(RAT fs') ! i - ?g' i = ((RAT fs) ! i - ?g' i) - ?mui\"\n    unfolding RAT_F1_i using carr1 carr2\n    by (intro eq_vecI, auto)\n  hence in1:\"((RAT fs) ! i - ?g' i) - ?mui \\<in> ?rs\"\n    using gs2.oc_projection_exist[of i] conn2 i unfolding span_G1_G by auto\n  from \\<open>j < i\\<close> have Gj_mem: \"(RAT fs) ! j \\<in> (\\<lambda> x. ((RAT fs) ! x)) ` {0 ..< i}\" by auto  \n  have id1: \"set (take i (RAT fs)) = (\\<lambda>x. ?RV (fs ! x)) ` {0..<i}\"\n    using \\<open>i \\<le> m\\<close> len\n    by (subst nth_image[symmetric], force+)\n  have \"(RAT fs) ! j \\<in> ?rs \\<longleftrightarrow> (RAT fs) ! j \\<in> gs.span ((\\<lambda>x. ?RV (fs ! x)) ` {0..<i})\"\n    using gs1.partial_span  \\<open>i \\<le> m\\<close> id1 inv by auto\n  also have \"(\\<lambda>x. ?RV (fs ! x)) ` {0..<i} = (\\<lambda>x. ((RAT fs) ! x)) ` {0..<i}\" using \\<open>i < m\\<close> len by force\n  also have \"(RAT fs) ! j \\<in> gs.span \\<dots>\"\n    by (rule gs.span_mem[OF _ Gj_mem], insert \\<open>i < m\\<close> G, auto)\n  finally have \"(RAT fs) ! j \\<in> ?rs\" .\n  hence in2:\"?mui \\<in> ?rs\"\n    apply(intro gs.prod_in_span) by force+\n  have ineq:\"((RAT fs) ! i - ?g' i) + ?mui - ?mui = ((RAT fs) ! i - ?g' i)\"\n    using carr1 carr2 by (intro eq_vecI, auto)\n  have cong': \"A = B \\<Longrightarrow> A \\<in> C \\<Longrightarrow> B \\<in> C\" for A B :: \"'a vec\" and C by auto\n  have *: \"?g ` {0..<i} \\<subseteq> Rn\" by auto\n  have in_span: \"(RAT fs) ! i - ?g' i \\<in> ?rs\"\n    by (rule cong'[OF eq_vecI gs.span_add1[OF * in1 in2,unfolded ineq]], insert carr1 carr2, auto)\n  { \n    fix x assume x:\"x < i\" hence \"x < m\" \"i \\<noteq> x\" using i by auto\n    from gs2.orthogonal this inv assms\n    have \"?g' i \\<bullet> ?g' x = 0\" by auto\n  }\n  hence G1_G: \"?g' i = ?g i\"\n    by (intro gs1.oc_projection_unique) (use inv i eq_part in_span in auto)\n  show eq_fs:\"x < m \\<Longrightarrow> ?g' x = ?g x\"\n    for x proof(induct x rule:nat_less_induct[rule_format])\n    case (1 x)\n    hence ind: \"m < x \\<Longrightarrow> ?g' m = ?g m\"\n       for m by auto\n    { assume \"x > i\"\n      hence ?case unfolding gs2.gso.simps[of x] gs1.gso.simps[of x] unfolding gs1.\\<mu>.simps gs2.\\<mu>.simps\n        using ind eq by (auto intro: cong[OF _ cong[OF refl[of \"gs.sumlist\"]]])\n    } note eq_rest = this\n    show ?case by (rule linorder_class.linorder_cases[of x i],insert G1_G eq_part eq_rest,auto)\n  qed\n  hence Hs:\"?G' = ?G\" by (auto simp:o_def)\n  have red: \"weakly_reduced fs' i\" using red using eq_fs \\<open>i < m\\<close>\n    unfolding gram_schmidt_fs.weakly_reduced_def by simp\n  let ?Mi = \"M ! i ! j\"  \n  have Gjn: \"dim_vec (fs ! j) = n\" using Fij(2) carrier_vecD by blast\n  define E where \"E = addrow_mat m (- ?R c) i j\"\n  define M' where \"M' = gs1.M m\"\n  define N' where \"N' = gs2.M m\"\n  have E: \"E \\<in> carrier_mat m m\" unfolding E_def by simp\n  have M: \"M' \\<in> carrier_mat m m\" unfolding gs1.M_def M'_def by auto\n  have N: \"N' \\<in> carrier_mat m m\" unfolding gs2.M_def N'_def by auto\n  let ?mat = \"mat_of_rows n\" \n  let ?GsM = \"?mat ?G\" \n  have Gs: \"?GsM \\<in> carrier_mat m n\" by auto\n  hence GsT: \"?GsM\\<^sup>T \\<in> carrier_mat n m\" by auto\n  have Gnn: \"?mat (RAT fs) \\<in> carrier_mat m n\" unfolding mat_of_rows_def using len by auto\n  have \"?mat (RAT fs') = addrow (- ?R c) i j (?mat (RAT fs))\" \n    unfolding RAT_F1 by (rule eq_matI, insert Gjn ji(2), auto simp: len mat_of_rows_def)\n  also have \"\\<dots> = E * ?mat (RAT fs)\" unfolding E_def\n    by (rule addrow_mat, insert j i, auto simp: mat_of_rows_def len)\n  finally have HEG: \"?mat (RAT fs') = E * ?mat (RAT fs)\" . (* lemma 16.12(i), part 1 *)\n  have \"(E * M') * ?mat ?G = E * (M' * ?mat ?G)\" \n    by (rule assoc_mult_mat[OF E M Gs])\n  also have \"M' * ?GsM = ?mat (RAT fs)\" using gs1.matrix_equality conn1 M'_def by simp\n  also have \"E * \\<dots> = ?mat (RAT fs')\" unfolding HEG ..\n  also have \"\\<dots> = N' * ?mat ?G'\" using gs2.matrix_equality conn2 unfolding N'_def by simp\n  also have \"?mat ?G' = ?GsM\" unfolding Hs ..\n  finally have \"(E * M') * ?GsM = N' * ?GsM\" .\n  from arg_cong[OF this, of \"\\<lambda> x. x * ?GsM\\<^sup>T\"] E M N \n  have EMN: \"(E * M') * (?GsM * ?GsM\\<^sup>T) = N' * (?GsM * ?GsM\\<^sup>T)\" \n    by (subst (1 2) assoc_mult_mat[OF _ Gs GsT, of _ m, symmetric], auto)\n  have \"det (?GsM * ?GsM\\<^sup>T) = gs.Gramian_determinant ?G m\" \n    unfolding gs.Gramian_determinant_def\n    by (subst gs.Gramian_matrix_alt_def, auto simp: Let_def)\n  also have \"\\<dots> > 0\" \n  proof -\n    have 1: \"gs.lin_indpt_list ?G\"\n      using conn1 gs1.orthogonal_gso gs1.gso_carrier by (intro gs.orthogonal_imp_lin_indpt_list) (auto)\n    interpret G: gram_schmidt_fs_lin_indpt n ?G\n      by  (standard) (use 1 gs.lin_indpt_list_def in auto)\n    show ?thesis\n      by (intro G.Gramian_determinant) auto\n  qed\n  finally have \"det (?GsM * ?GsM\\<^sup>T) \\<noteq> 0\" by simp\n  from vec_space.det_nonzero_congruence[OF EMN this _ _ N] Gs E M\n  have EMN: \"E * M' = N'\" by auto (* lemma 16.12(i), part 2 *) \n  from inv have sred: \"reduced fs i\" by auto\n  {\n    fix i' j'\n    assume ij: \"i' < m\" \"j' < m\" and choice: \"i' \\<noteq> i \\<or> j < j'\" \n    have \"?mu' i' j' \n      = N' $$ (i',j')\" using ij F1 unfolding N'_def gs2.M_def by auto\n    also have \"\\<dots> = addrow (- ?R c) i j M' $$ (i',j')\" unfolding EMN[symmetric] E_def\n      by (subst addrow_mat[OF M], insert ji, auto)\n    also have \"\\<dots> = (if i = i' then - ?R c * M' $$ (j, j') + M' $$ (i', j') else M' $$ (i', j'))\" \n      by (rule index_mat_addrow, insert ij M, auto)\n    also have \"\\<dots> = M' $$ (i', j')\"\n    proof (cases \"i = i'\")\n      case True\n      with choice have jj: \"j < j'\" by auto\n      have \"M' $$ (j, j') = ?mu j j'\" \n        using ij ji len unfolding M'_def gs1.M_def by auto\n      also have \"\\<dots> = 0\" unfolding gs1.\\<mu>.simps using jj by auto\n      finally show ?thesis using True by auto\n    qed auto\n    also have \"\\<dots> = ?mu i' j'\"\n      using ij len unfolding M'_def gs1.M_def by auto\n    also note calculation\n  } note mu_no_change = this\n  {\n    fix j'\n    assume jj': \"j' \\<le> j\" with j i have j': \"j' < m\" by auto\n    have \"?mu' i j' \n      = N' $$ (i,j')\" using jj' j i F1 unfolding N'_def gs2.M_def by auto\n    also have \"\\<dots> = addrow (- ?R c) i j M' $$ (i,j')\" unfolding EMN[symmetric] E_def\n      by (subst addrow_mat[OF M], insert ji, auto)\n    also have \"\\<dots> = - ?R c * M' $$ (j, j') + M' $$ (i, j')\" \n      by (rule index_mat_addrow, insert j' i M, auto)\n    also have \"\\<dots> = M' $$ (i, j') - ?R c * M' $$ (j, j')\" by simp\n    also have \"M' $$ (i, j') = ?mu i j'\"\n      using i j' len unfolding M'_def gs1.M_def by auto\n    also have \"M' $$ (j, j') = ?mu j j'\" \n      using i j j' len unfolding M'_def gs1.M_def by auto\n    finally have \"?mu' i j' = ?mu i j' - ?R c * ?mu j j'\" by auto\n  } note mu_change = this  \n  show mu_update: \"i' < m \\<Longrightarrow> j' < m \\<Longrightarrow> \n    ?mu' i' j' = (if i' = i \\<and> j' \\<le> j then ?mu i j' - ?R c * ?mu j j' else ?mu i' j')\" \n    for i' j' using mu_change[of j'] mu_no_change[of i' j']\n    by auto\n  have sred: \"reduced fs' i\"\n    unfolding gram_schmidt_fs.reduced_def \n  proof (intro conjI[OF red] impI allI, goal_cases)\n    case (1 i' j)\n    with mu_no_change[of i' j] sred[unfolded gram_schmidt_fs.reduced_def, THEN conjunct2, rule_format, of i' j] i \n    show ?case by auto\n  qed\n\n  have mudiff:\"?mu i j - of_int c = ?mu' i j\"\n    by (subst mu_change, auto simp: gs1.\\<mu>.simps)\n  have lin_indpt_list_fs: \"gs.lin_indpt_list (RAT fs')\"\n    unfolding gs.lin_indpt_list_def using conn2 by auto\n  { \n    assume c: \"c = round (\\<mu> fs i j)\" \n    assume mu_small: \"\\<mu>_small_row i fs (Suc j)\" \n    have small: \"abs (?mu i j - of_int c) \\<le> inverse 2\" unfolding j c\n      using of_int_round_abs_le by (auto simp add: abs_minus_commute)\n    from this[unfolded mudiff] \n    have mu'_2: \"abs (?mu' i j) \\<le> inverse 2\" .\n\n    show \"\\<mu>_small_row i fs' j\" \n      unfolding \\<mu>_small_row_def \n    proof (intro allI, goal_cases)\n      case (1 j')\n      show ?case using mu'_2 mu_small[unfolded \\<mu>_small_row_def, rule_format, of j'] \n        by (cases \"j' > j\", insert mu_update[of i j'] i, auto)\n    qed\n  }\n\n  show Linv': \"LLL_invariant True i fs'\" \n    by (intro LLL_invI[OF F1 lattice \\<open>i \\<le> m\\<close> lin_indpt_list_fs sred], auto)\n  {\n    fix i\n    assume i: \"i \\<le> m\"\n    have \"rat_of_int (d fs' i) = of_int (d fs i)\" \n      unfolding d_def Gramian_determinant(1)[OF Linv i] Gramian_determinant(1)[OF Linv' i]\n      by (rule prod.cong[OF refl], subst eq_fs, insert i, auto)\n    thus \"d fs' i = d fs i\" by simp\n  } note d = this \n  have D: \"D fs' = D fs\" \n    unfolding D_def\n    by (rule arg_cong[of _ _ nat], rule prod.cong[OF refl], auto simp: d)\n  show \"LLL_measure i fs' = LLL_measure i fs\" \n    unfolding LLL_measure_def logD_def D ..\nqed\n\ntext \\<open>Addition step which can be skipped since $\\mu$-value is already small\\<close>\n\nlemma basis_reduction_add_row_main_0: assumes Linv: \"LLL_invariant True i fs\"\n  and i: \"i < m\"  and j: \"j < i\" \n  and 0: \"round (\\<mu> fs i j) = 0\" \n  and mu_small: \"\\<mu>_small_row i fs (Suc j)\"\nshows \"\\<mu>_small_row i fs j\" (is ?g1)\nproof -\n  note inv = LLL_invD[OF Linv]\n  from inv(5)[OF i] inv(5)[of j] i j\n  have id: \"fs[i := fs ! i - 0 \\<cdot>\\<^sub>v fs ! j] = fs\" \n    by (intro nth_equalityI, insert inv i, auto)\n  show ?g1\n    using basis_reduction_add_row_main[OF Linv i j _, of fs] 0 id mu_small by auto\nqed\n\nlemma \\<mu>_small_row_refl: \"\\<mu>_small_row i fs i\" \n  unfolding \\<mu>_small_row_def by auto\n\nlemma basis_reduction_add_row_done: assumes Linv: \"LLL_invariant True i fs\"\n  and i: \"i < m\" \n  and mu_small: \"\\<mu>_small_row i fs 0\" \nshows \"LLL_invariant False i fs\"\nproof -\n  note inv = LLL_invD[OF Linv]\n  from mu_small \n  have mu_small: \"\\<mu>_small fs i\" unfolding \\<mu>_small_row_def \\<mu>_small_def by auto\n  show ?thesis\n    using i mu_small by (intro LLL_invI[OF inv(3,6,7,9,1,10)], auto)\nqed     \n\n(* lemma 16.16 (ii), one case *)\nlemma d_swap_unchanged: assumes len: \"length F1 = m\" \n  and i0: \"i \\<noteq> 0\" and i: \"i < m\" and ki: \"k \\<noteq> i\" and km: \"k \\<le> m\"   \n  and swap: \"F2 = F1[i := F1 ! (i - 1), i - 1 := F1 ! i]\"\nshows \"d F1 k = d F2 k\"\nproof -\n  let ?F1_M = \"mat k n (\\<lambda>(i, y). F1 ! i $ y)\" \n  let ?F2_M = \"mat k n (\\<lambda>(i, y). F2 ! i $ y)\" \n  have \"\\<exists> P. P \\<in> carrier_mat k k \\<and> det P \\<in> {-1, 1} \\<and> ?F2_M = P * ?F1_M\" \n  proof cases\n    assume ki: \"k < i\" \n    hence H: \"?F2_M = ?F1_M\" unfolding swap\n      by (intro eq_matI, auto)\n    let ?P = \"1\\<^sub>m k\" \n    have \"?P \\<in> carrier_mat k k\" \"det ?P \\<in> {-1, 1}\" \"?F2_M = ?P * ?F1_M\" unfolding H by auto\n    thus ?thesis by blast\n  next\n    assume \"\\<not> k < i\" \n    with ki have ki: \"k > i\" by auto\n    let ?P = \"swaprows_mat k i (i - 1)\" \n    from i0 ki have neq: \"i \\<noteq> i - 1\" and kmi: \"i - 1 < k\" by auto\n    have *: \"?P \\<in> carrier_mat k k\" \"det ?P \\<in> {-1, 1}\" using det_swaprows_mat[OF ki kmi neq] ki by auto\n    from i len have iH: \"i < length F1\" \"i - 1 < length F1\" by auto \n    have \"?P * ?F1_M = swaprows i (i - 1) ?F1_M\" \n      by (subst swaprows_mat[OF _ ki kmi], auto)\n    also have \"\\<dots> = ?F2_M\" unfolding swap\n      by (intro eq_matI, rename_tac ii jj, \n          case_tac \"ii = i\", (insert iH, simp add: nth_list_update)[1],\n          case_tac \"ii = i - 1\", insert iH neq ki, auto simp: nth_list_update)\n    finally show ?thesis using * by metis\n  qed\n  then obtain P where P: \"P \\<in> carrier_mat k k\" and detP: \"det P \\<in> {-1, 1}\" and H': \"?F2_M = P * ?F1_M\" by auto\n  have \"d F2 k = det (gs.Gramian_matrix F2 k)\" \n    unfolding d_def gs.Gramian_determinant_def by simp\n  also have \"\\<dots> = det (?F2_M * ?F2_M\\<^sup>T)\" unfolding gs.Gramian_matrix_def Let_def by simp\n  also have \"?F2_M * ?F2_M\\<^sup>T = ?F2_M * (?F1_M\\<^sup>T * P\\<^sup>T)\" unfolding H'\n    by (subst transpose_mult[OF P], auto)\n  also have \"\\<dots> = P * (?F1_M * (?F1_M\\<^sup>T * P\\<^sup>T))\" unfolding H' \n    by (subst assoc_mult_mat[OF P], auto)\n  also have \"det \\<dots> = det P * det (?F1_M * (?F1_M\\<^sup>T * P\\<^sup>T))\" \n    by (rule det_mult[OF P], insert P, auto)\n  also have \"?F1_M * (?F1_M\\<^sup>T * P\\<^sup>T) = (?F1_M * ?F1_M\\<^sup>T) * P\\<^sup>T\" \n    by (subst assoc_mult_mat, insert P, auto)\n  also have \"det \\<dots> = det (?F1_M * ?F1_M\\<^sup>T) * det P\" \n    by (subst det_mult, insert P, auto simp: det_transpose)\n  also have \"det (?F1_M * ?F1_M\\<^sup>T) = det (gs.Gramian_matrix F1 k)\" unfolding gs.Gramian_matrix_def Let_def by simp\n  also have \"\\<dots> = d F1 k\" \n    unfolding d_def gs.Gramian_determinant_def by simp\n  finally have \"d F2 k = (det P * det P) * d F1 k\" by simp\n  also have \"det P * det P = 1\" using detP by auto\n  finally show \"d F1 k = d F2 k\" by simp\nqed\n\ndefinition base where \"base = real_of_rat ((4 * \\<alpha>) / (4 + \\<alpha>))\" \n\ndefinition g_bound :: \"int vec list \\<Rightarrow> bool\" where \n  \"g_bound fs = (\\<forall> i < m. sq_norm (gso fs i) \\<le> of_nat N)\" \n\nend\n\nlocale LLL_with_assms = LLL + \n  assumes \\<alpha>: \"\\<alpha> \\<ge> 4/3\"\n    and lin_dep: \"lin_indep fs_init\" \n    and len: \"length fs_init = m\" \nbegin\nlemma \\<alpha>0: \"\\<alpha> > 0\" \"\\<alpha> \\<noteq> 0\" \n  using \\<alpha> by auto\n\nlemma fs_init: \"set fs_init \\<subseteq> carrier_vec n\" \n  using lin_dep[unfolded gs.lin_indpt_list_def] by auto\n\n\nlemma reduction: \"0 < reduction\" \"reduction \\<le> 1\" \n  \"\\<alpha> > 4/3 \\<Longrightarrow> reduction < 1\" \n  \"\\<alpha> = 4/3 \\<Longrightarrow> reduction = 1\" \n  using \\<alpha> unfolding reduction_def by auto\n\nlemma base: \"\\<alpha> > 4/3 \\<Longrightarrow> base > 1\" using reduction(1,3) unfolding reduction_def base_def by auto\n\nlemma basis_reduction_swap_main: assumes Linv: \"LLL_invariant False i fs\"\n  and i: \"i < m\"\n  and i0: \"i \\<noteq> 0\" \n  and norm_ineq: \"sq_norm (gso fs (i - 1)) > \\<alpha> * sq_norm (gso fs i)\" \n  and fs'_def: \"fs' = fs[i := fs ! (i - 1), i - 1 := fs ! i]\" \nshows \"LLL_invariant False (i - 1) fs'\" \n  and \"LLL_measure i fs > LLL_measure (i - 1) fs'\" \n  (* new values of gso *)\n  and \"\\<And> k. k < m \\<Longrightarrow> gso fs' k = (if k = i - 1 then\n         gso fs i + \\<mu> fs i (i - 1) \\<cdot>\\<^sub>v gso fs (i - 1) \n      else if k = i then\n         gso fs (i - 1) - (RAT fs ! (i - 1) \\<bullet> gso fs' (i - 1) / sq_norm (gso fs' (i - 1))) \\<cdot>\\<^sub>v gso fs' (i - 1)\n      else gso fs k)\" (is \"\\<And> k. _ \\<Longrightarrow> _ = ?newg k\")\n  (* new values of norms of gso *)\n  and \"\\<And> k. k < m \\<Longrightarrow> sq_norm (gso fs' k) = (if k = i - 1 then\n          sq_norm (gso fs i) + (\\<mu> fs i (i - 1) * \\<mu> fs i (i - 1)) * sq_norm (gso fs (i - 1))\n      else if k = i then\n         sq_norm (gso fs i) * sq_norm (gso fs (i - 1)) / sq_norm (gso fs' (i - 1))\n      else sq_norm (gso fs k))\" (is \"\\<And> k. _ \\<Longrightarrow> _ = ?new_norm k\")\n  (* new values of \\<mu>-values *)\n  and \"\\<And> ii j. ii < m \\<Longrightarrow> j < ii \\<Longrightarrow> \\<mu> fs' ii j = (\n        if ii = i - 1 then \n           \\<mu> fs i j\n        else if ii = i then \n          if j = i - 1 then \n             \\<mu> fs i (i - 1) * sq_norm (gso fs (i - 1)) / sq_norm (gso fs' (i - 1))\n          else \n             \\<mu> fs (i - 1) j\n        else if ii > i \\<and> j = i then\n           \\<mu> fs ii (i - 1) - \\<mu> fs i (i - 1) * \\<mu> fs ii i\n        else if ii > i \\<and> j = i - 1 then \n           \\<mu> fs ii (i - 1) * \\<mu> fs' i (i - 1) + \\<mu> fs ii i * sq_norm (gso fs i) / sq_norm (gso fs' (i - 1))\n        else \\<mu> fs ii j)\" (is \"\\<And> ii j. _ \\<Longrightarrow> _ \\<Longrightarrow> _ = ?new_mu ii j\")\n  (* new d-values *)\n  and \"\\<And> ii. ii \\<le> m \\<Longrightarrow> of_int (d fs' ii) = (if ii = i then \n       sq_norm (gso fs' (i - 1)) / sq_norm (gso fs (i - 1)) * of_int (d fs i)\n       else of_int (d fs ii))\" \nproof -\n  note inv = LLL_invD[OF Linv]\n  interpret fs: fs_int' n m fs_init \\<alpha> False i fs\n    by (standard) (use Linv in auto)\n  let ?mu1 = \"\\<mu> fs\" \n  let ?mu2 = \"\\<mu> fs'\" \n  let ?g1 = \"gso fs\" \n  let ?g2 = \"gso fs'\" \n  from inv(11)[unfolded \\<mu>_small_def]\n  have mu_F1_i: \"\\<And> j. j<i \\<Longrightarrow> \\<bar>?mu1 i j\\<bar> \\<le> 1 / 2\" by auto\n  from mu_F1_i[of \"i-1\"] have m12: \"\\<bar>?mu1 i (i - 1)\\<bar> \\<le> inverse 2\" using i0\n    by auto\n  note d = d_def  \n  note Gd = Gramian_determinant(1)\n  note Gd12 = Gd[OF Linv]\n  let ?x = \"?g1 (i - 1)\" let ?y = \"?g1 i\" \n  let ?cond = \"\\<alpha> * sq_norm ?y < sq_norm ?x\" \n  from inv have red: \"weakly_reduced fs i\" \n    and len: \"length fs = m\" and HC: \"set fs \\<subseteq> carrier_vec n\" \n    and L: \"lattice_of fs = L\" \n    using i by auto \n  from i0 inv i have swap: \"set fs \\<subseteq> carrier_vec n\" \"i < length fs\" \"i - 1 < length fs\" \"i \\<noteq> i - 1\" \n    unfolding Let_def by auto\n  have RAT_fs': \"RAT fs' = (RAT fs)[i := (RAT fs) ! (i - 1), i - 1 := (RAT fs) ! i]\" \n    unfolding fs'_def using swap by (intro nth_equalityI, auto simp: nth_list_update)\n  have span': \"gs.span (SRAT fs) = gs.span (SRAT fs')\" unfolding fs'_def\n    by (rule arg_cong[of _ _ gs.span], insert swap, auto)\n  have lfs': \"lattice_of fs' = lattice_of fs\" unfolding fs'_def\n    by (rule lattice_of_swap[OF swap refl])\n  with inv have lattice: \"lattice_of fs' = L\" by auto\n  have len': \"length fs' = m\" using inv unfolding fs'_def by auto\n  have fs': \"set fs' \\<subseteq> carrier_vec n\" using swap unfolding fs'_def set_conv_nth\n    by (auto, rename_tac k, case_tac \"k = i\", force, case_tac \"k = i - 1\", auto)\n  let ?rv = \"map_vec rat_of_int\" \n  from inv(1) have indepH: \"lin_indep fs\" .\n  from i i0 len have \"i < length (RAT fs)\" \"i - 1 < length (RAT fs)\" by auto\n  with distinct_swap[OF this] len have \"distinct (RAT fs') = distinct (RAT fs)\" unfolding RAT_fs'\n    by (auto simp: map_update)\n  with len' fs' span' indepH have indepH': \"lin_indep fs'\" unfolding fs'_def using i i0\n    by (auto simp: gs.lin_indpt_list_def)\n  have lenR': \"length (RAT fs') = m\" using len' by auto\n  have conn1: \"set (RAT fs) \\<subseteq> carrier_vec n\"  \"length (RAT fs) = m\" \"distinct (RAT fs)\"\n    \"gs.lin_indpt (set (RAT fs))\"\n    using inv unfolding gs.lin_indpt_list_def by auto\n  have conn2: \"set (RAT fs') \\<subseteq> carrier_vec n\"  \"length (RAT fs') = m\" \"distinct (RAT fs')\"\n    \"gs.lin_indpt (set (RAT fs'))\"\n    using indepH' lenR'  unfolding gs.lin_indpt_list_def by auto\n  interpret gs2: gram_schmidt_fs_lin_indpt n \"RAT fs'\"\n    by (standard) (use indepH' lenR' gs.lin_indpt_list_def in auto)\n  have fs'_fs: \"k < i - 1 \\<Longrightarrow> fs' ! k = fs ! k\" for k unfolding fs'_def by auto\n  { \n    fix k\n    assume ki: \"k < i - 1\" \n    with i have kn: \"k < m\" by simp\n    have \"?g2 k = ?g1 k\" \n      by (rule gs.gso_cong, insert ki kn len, auto simp: fs'_def)\n  } note G2_G = this\n  have take_eq: \"take (Suc i - 1 - 1) fs' = take (Suc i - 1 - 1) fs\" \n    by (intro nth_equalityI, insert len len' i swap(2-), auto intro!: fs'_fs) \n  from inv have \"weakly_reduced fs i\" by auto\n  hence \"weakly_reduced fs (i - 1)\" unfolding gram_schmidt_fs.weakly_reduced_def by auto\n  hence red: \"weakly_reduced fs' (i - 1)\"\n    unfolding gram_schmidt_fs.weakly_reduced_def using i G2_G by simp\n  have i1n: \"i - 1 < m\" using i by auto\n  let ?R = rat_of_int\n  let ?RV = \"map_vec ?R\"  \n  let ?f1 = \"\\<lambda> i. RAT fs ! i\"\n  let ?f2 = \"\\<lambda> i. RAT fs' ! i\" \n  let ?n1 = \"\\<lambda> i. sq_norm (?g1 i)\" \n  let ?n2 = \"\\<lambda> i. sq_norm (?g2 i)\" \n  have heq:\"fs ! (i - 1) = fs' ! i\" \"take (i-1) fs = take (i-1) fs'\"\n           \"?f2 (i - 1) = ?f1 i\" \"?f2 i = ?f1 (i - 1)\"\n    unfolding fs'_def using i len i0 by auto\n  have norm_pos2: \"j < m \\<Longrightarrow> ?n2 j > 0\" for j \n    using gs2.sq_norm_pos len' by simp\n  have norm_pos1: \"j < m \\<Longrightarrow> ?n1 j > 0\" for j \n    using fs.gs.sq_norm_pos inv by simp\n  have norm_zero2: \"j < m \\<Longrightarrow> ?n2 j \\<noteq> 0\" for j using norm_pos2[of j] by linarith\n  have norm_zero1: \"j < m \\<Longrightarrow> ?n1 j \\<noteq> 0\" for j using norm_pos1[of j] by linarith\n  have gs: \"\\<And> j. j < m \\<Longrightarrow> ?g1 j \\<in> Rn\" using inv by blast\n  have gs2: \"\\<And> j. j < m \\<Longrightarrow> ?g2 j \\<in> Rn\" using fs.gs.gso_carrier conn2 by auto\n  have g: \"\\<And> j. j < m \\<Longrightarrow> ?f1 j \\<in> Rn\" using inv by auto\n  have g2: \"\\<And> j. j < m \\<Longrightarrow> ?f2 j \\<in> Rn\" using gs2.f_carrier conn2 by blast\n  let ?fs1 = \"?f1 ` {0..< (i - 1)}\" \n  have G: \"?fs1 \\<subseteq> Rn\" using g i by auto\n  let ?gs1 = \"?g1 ` {0..< (i - 1)}\" \n  have G': \"?gs1 \\<subseteq> Rn\" using gs i by auto\n  let ?S = \"gs.span ?fs1\" \n  let ?S' = \"gs.span ?gs1\" \n  have S'S: \"?S' = ?S\" \n    by (rule fs.gs.partial_span', insert conn1 i, auto)\n  have \"gs.is_oc_projection (?g2 (i - 1)) (gs.span (?g2 ` {0..< (i - 1)})) (?f2 (i - 1))\" \n    using i len' by (intro  gs2.gso_oc_projection_span(2)) auto\n  also have \"?f2 (i - 1) = ?f1 i\" unfolding fs'_def using len i by auto\n  also have \"gs.span (?g2 ` {0 ..< (i - 1)}) = gs.span (?f2 ` {0 ..< (i - 1)})\" \n    using i len' by (intro gs2.partial_span') auto\n  also have \"?f2 ` {0 ..< (i - 1)} = ?fs1\" \n    by (rule image_cong[OF refl], insert len i, auto simp: fs'_def)\n  finally have claim1: \"gs.is_oc_projection (?g2 (i - 1)) ?S (?f1 i)\" .\n  have list_id: \"[0..<Suc (i - 1)] = [0..< i - 1] @ [i - 1]\" \n    \"[0..< Suc i] = [0..< i] @ [i]\" \"map f [x] = [f x]\" for f x using i by auto\n  (* f1i_sum is claim 2 *)\n  have f1i_sum: \"?f1 i = gs.sumlist (map (\\<lambda>j. ?mu1 i j \\<cdot>\\<^sub>v ?g1 j) [0 ..< i]) + ?g1 i\" (is \"_ = ?sum + _\") \n    apply(subst fs.gs.fi_is_sum_of_mu_gso, insert len i, force)\n    unfolding map_append list_id\n    by (subst gs.M.sumlist_snoc, insert i gs conn1, auto simp: fs.gs.\\<mu>.simps)\n  have f1im1_sum: \"?f1 (i - 1) = gs.sumlist (map (\\<lambda>j. ?mu1 (i - 1) j \\<cdot>\\<^sub>v ?g1 j) [0..<i - 1]) + ?g1 (i - 1)\" (is \"_ = ?sum1 + _\")\n    apply(subst fs.gs.fi_is_sum_of_mu_gso, insert len i, force)\n    unfolding map_append list_id\n    by (subst gs.M.sumlist_snoc, insert i gs, auto simp: fs.gs.\\<mu>.simps)\n\n  have sum: \"?sum \\<in> Rn\" by (rule gs.sumlist_carrier, insert gs i, auto)\n  have sum1: \"?sum1 \\<in> Rn\" by (rule gs.sumlist_carrier, insert gs i, auto)\n  from gs.span_closed[OF G] have S: \"?S \\<subseteq> Rn\" by auto\n  from gs i have gs': \"\\<And> j. j < i - 1 \\<Longrightarrow> ?g1 j \\<in> Rn\" and gsi: \"?g1 (i - 1) \\<in> Rn\" by auto\n  have \"[0 ..< i] = [0 ..< Suc (i - 1)]\" using i0 by simp\n  also have \"\\<dots> = [0 ..< i - 1] @ [i - 1]\" by simp\n  finally have list: \"[0 ..< i] = [0 ..< i - 1] @ [i - 1]\" .\n\n  { (* d does not change for k \\<noteq> i *)\n    fix k\n    assume kn: \"k \\<le> m\" and ki: \"k \\<noteq> i\" \n    from d_swap_unchanged[OF len i0 i ki kn fs'_def]  \n    have \"d fs k = d fs' k\" by simp\n  } note d = this\n\n  (* new value of g (i-1) *)\n  have g2_im1: \"?g2 (i - 1) = ?g1 i + ?mu1 i (i - 1) \\<cdot>\\<^sub>v ?g1 (i - 1)\" (is \"_ = _ + ?mu_f1\")\n  proof (rule gs.is_oc_projection_eq[OF  claim1 _ S g[OF i]])\n    show \"gs.is_oc_projection (?g1 i + ?mu_f1) ?S (?f1 i)\" unfolding gs.is_oc_projection_def\n    proof (intro conjI allI impI)\n      let ?sum' = \"gs.sumlist (map (\\<lambda>j. ?mu1 i j \\<cdot>\\<^sub>v ?g1 j) [0 ..< i - 1])\" \n      have sum': \"?sum' \\<in> Rn\" by (rule gs.sumlist_carrier, insert gs i, auto)\n      show inRn: \"(?g1 i + ?mu_f1) \\<in> Rn\" using gs[OF i] gsi i by auto\n      have carr: \"?sum \\<in> Rn\" \"?g1 i \\<in> Rn\" \"?mu_f1 \\<in> Rn\" \"?sum' \\<in> Rn\" using sum' sum gs[OF i] gsi i by auto\n      have \"?f1 i - (?g1 i + ?mu_f1) = (?sum + ?g1 i) - (?g1 i + ?mu_f1)\"\n        unfolding f1i_sum by simp\n      also have \"\\<dots> = ?sum - ?mu_f1\" using carr by auto\n      also have \"?sum = gs.sumlist (map (\\<lambda>j. ?mu1 i j \\<cdot>\\<^sub>v ?g1 j) [0 ..< i - 1] @ [?mu_f1])\" \n        unfolding list by simp \n      also have \"\\<dots> = ?sum' + ?mu_f1\" \n        by (subst gs.sumlist_append, insert gs' gsi, auto)\n      also have \"\\<dots> - ?mu_f1 = ?sum'\" using sum' gsi by auto\n      finally have id: \"?f1 i - (?g1 i + ?mu_f1) = ?sum'\" .\n      show \"?f1 i - (?g1 i + ?mu_f1) \\<in> gs.span ?S\" unfolding id gs.span_span[OF G]\n      proof (rule gs.sumlist_in_span[OF G])\n        fix v\n        assume \"v \\<in> set (map (\\<lambda>j. ?mu1 i j \\<cdot>\\<^sub>v ?g1 j) [0 ..< i - 1])\" \n        then obtain j where j: \"j < i - 1\" and v: \"v = ?mu1 i j \\<cdot>\\<^sub>v ?g1 j\" by auto\n        show \"v \\<in> ?S\" unfolding v\n          by (rule gs.smult_in_span[OF G], unfold S'S[symmetric], rule gs.span_mem, insert gs i j, auto)\n      qed\n      fix x\n      assume \"x \\<in> ?S\"\n      hence x: \"x \\<in> ?S'\" using S'S by simp\n      show \"(?g1 i + ?mu_f1) \\<bullet> x = 0\"\n      proof (rule gs.orthocompl_span[OF _ G' inRn x])\n        fix x\n        assume \"x \\<in> ?gs1\"\n        then obtain j where j: \"j < i - 1\" and x_id: \"x = ?g1 j\" by auto\n        from j i x_id gs[of j] have x: \"x \\<in> Rn\" by auto\n        {\n          fix k\n          assume k: \"k > j\" \"k < m\" \n          have \"?g1 k \\<bullet> x = 0\" unfolding x_id \n            by (rule fs.gs.orthogonal, insert conn1 k, auto)\n        }\n        from this[of i] this[of \"i - 1\"] j i \n        have main: \"?g1 i \\<bullet> x = 0\" \"?g1 (i - 1) \\<bullet> x = 0\" by auto\n        have \"(?g1 i + ?mu_f1) \\<bullet> x = ?g1 i \\<bullet> x + ?mu_f1 \\<bullet> x\" \n          by (rule add_scalar_prod_distrib[OF gs[OF i] _ x], insert gsi, auto)\n        also have \"\\<dots> = 0\" using main\n          by (subst smult_scalar_prod_distrib[OF gsi x], auto)\n        finally show \"(?g1 i + ?mu_f1) \\<bullet> x = 0\" .\n      qed\n    qed\n  qed\n  { (* 16.13 (i): for g, only g_i and g_{i-1} can change *)\n    fix k\n    assume kn: \"k < m\" \n      and ki: \"k \\<noteq> i\" \"k \\<noteq> i - 1\"\n    have \"?g2 k = gs.oc_projection (gs.span (?g2 ` {0..<k})) (?f2 k)\" \n      by (rule gs2.gso_oc_projection_span, insert kn conn2, auto)\n    also have \"gs.span (?g2 ` {0..<k}) = gs.span (?f2 ` {0..<k})\" \n      by (rule gs2.partial_span', insert conn2 kn, auto)\n    also have \"?f2 ` {0..<k} = ?f1 ` {0..<k}\"\n    proof(cases \"k\\<le>i\")\n      case True hence \"k < i - 1\" using ki by auto\n      then show ?thesis apply(intro image_cong) unfolding fs'_def using len i by auto\n    next\n      case False \n      have \"?f2 ` {0..<k} = Fun.swap i (i - 1) ?f1 ` {0..<k}\"\n        unfolding Fun.swap_def fs'_def o_def using len i \n        by (intro image_cong, insert len kn, force+)\n      also have \"\\<dots> = ?f1 ` {0..<k}\"\n        apply(rule swap_image_eq) using False by auto\n      finally show ?thesis.\n    qed\n    also have \"gs.span \\<dots> = gs.span (?g1 ` {0..<k})\" \n      by (rule sym, rule fs.gs.partial_span', insert conn1 kn, auto)\n    also have \"?f2 k = ?f1 k\" using ki kn len unfolding fs'_def by auto\n    also have \"gs.oc_projection (gs.span (?g1 ` {0..<k})) \\<dots> = ?g1 k\" \n      by (subst fs.gs.gso_oc_projection_span, insert kn conn1, auto)\n    finally have \"?g2 k = ?g1 k\" . \n  } note g2_g1_identical = this\n\n  (* calculation of new mu-values *)\n  { (* no change of mu for lines before line i - 1 *)\n    fix jj ii\n    assume ii: \"ii < i - 1\"  \n    have \"?mu2 ii jj = ?mu1 ii jj\" using ii i len\n      by (subst gs.\\<mu>_cong[of _ _ \"RAT fs\" \"RAT fs'\"], auto simp: fs'_def)\n  } note mu'_mu_small_i = this\n  { (* swap of mu-values in lines i - 1 and i for j < i - 1 *)\n    fix jj\n    assume jj: \"jj < i - 1\"  \n    hence id1: \"jj < i - 1 \\<longleftrightarrow> True\" \"jj < i \\<longleftrightarrow> True\" by auto\n    have id2: \"?g2 jj = ?g1 jj\" by (subst g2_g1_identical, insert jj i, auto)       \n    have \"?mu2 i jj = ?mu1 (i - 1) jj\" \"?mu2 (i - 1) jj = ?mu1 i jj\" \n      unfolding gs2.\\<mu>.simps fs.gs.\\<mu>.simps id1 id2 if_True using len i i0 by (auto simp: fs'_def)\n  } note mu'_mu_i_im1_j = this\n\n  have im1: \"i - 1 < m\" using i by auto\n\n  (* calculation of new value of g_i *)\n  let ?g2_im1 = \"?g2 (i - 1)\" \n  have g2_im1_Rn: \"?g2_im1 \\<in> Rn\" using i conn2 by (auto intro!: fs.gs.gso_carrier)\n  {\n    let ?mu2_f2 = \"\\<lambda> j. - ?mu2 i j \\<cdot>\\<^sub>v ?g2 j\" \n    let ?sum = \"gs.sumlist (map (\\<lambda>j. - ?mu1 (i - 1) j \\<cdot>\\<^sub>v ?g1 j) [0 ..< i - 1])\" \n    have mhs: \"?mu2_f2 (i - 1) \\<in> Rn\" using i conn2 by (auto intro!: fs.gs.gso_carrier)\n    have sum': \"?sum \\<in> Rn\" by (rule gs.sumlist_carrier, insert gs i, auto)\n    have gim1: \"?f1 (i - 1) \\<in> Rn\" using g i by auto\n    have \"?g2 i = ?f2 i + gs.sumlist (map ?mu2_f2 [0 ..< i-1] @ [?mu2_f2 (i-1)])\" \n      unfolding gs2.gso.simps[of i] list by simp\n    also have \"?f2 i = ?f1 (i - 1)\" unfolding fs'_def using len i i0 by auto\n    also have \"map ?mu2_f2 [0 ..< i-1] = map (\\<lambda>j. - ?mu1 (i - 1) j \\<cdot>\\<^sub>v ?g1 j) [0 ..< i - 1]\"\n      by (rule map_cong[OF refl], subst g2_g1_identical, insert i, auto simp: mu'_mu_i_im1_j)\n    also have \"gs.sumlist (\\<dots> @ [?mu2_f2 (i - 1)]) = ?sum + ?mu2_f2 (i - 1)\" \n      by (subst gs.sumlist_append, insert gs i mhs, auto)\n    also have \"?f1 (i - 1) + \\<dots> = (?f1 (i - 1) + ?sum) + ?mu2_f2 (i - 1)\"\n      using gim1 sum' mhs by auto\n    also have \"?f1 (i - 1) + ?sum = ?g1 (i - 1)\" unfolding fs.gs.gso.simps[of \"i - 1\"] by simp\n    also have \"?mu2_f2 (i - 1) = - (?f2 i \\<bullet> ?g2_im1 / sq_norm ?g2_im1) \\<cdot>\\<^sub>v ?g2_im1\" unfolding gs2.\\<mu>.simps using i0 by simp\n    also have \"\\<dots> = - ((?f2 i \\<bullet> ?g2_im1 / sq_norm ?g2_im1) \\<cdot>\\<^sub>v ?g2_im1)\" by auto\n    also have \"?g1 (i - 1) + \\<dots> = ?g1 (i - 1) - ((?f2 i \\<bullet> ?g2_im1 / sq_norm ?g2_im1) \\<cdot>\\<^sub>v ?g2_im1)\"\n      by (rule sym, rule minus_add_uminus_vec[of _ n], insert gsi g2_im1_Rn, auto)\n    also have \"?f2 i = ?f1 (i - 1)\" by fact\n    finally have \"?g2 i = ?g1 (i - 1) - (?f1 (i - 1) \\<bullet> ?g2 (i - 1) / sq_norm (?g2 (i - 1))) \\<cdot>\\<^sub>v ?g2 (i - 1)\" .\n  } note g2_i = this\n\n  let ?n1 = \"\\<lambda> i. sq_norm (?g1 i)\" \n  let ?n2 = \"\\<lambda> i. sq_norm (?g2 i)\" \n\n  (* calculation of new norms *)\n  { (* norm of g (i - 1) *)\n    have \"?n2 (i - 1) = sq_norm (?g1 i + ?mu_f1)\" unfolding g2_im1 by simp\n    also have \"\\<dots> = (?g1 i + ?mu_f1) \\<bullet> (?g1 i + ?mu_f1)\" \n      by (simp add: sq_norm_vec_as_cscalar_prod)\n    also have \"\\<dots> = (?g1 i + ?mu_f1) \\<bullet> ?g1 i + (?g1 i + ?mu_f1) \\<bullet> ?mu_f1\" \n      by (rule scalar_prod_add_distrib, insert gs i, auto)\n    also have \"(?g1 i + ?mu_f1) \\<bullet> ?g1 i = ?g1 i \\<bullet> ?g1 i + ?mu_f1 \\<bullet> ?g1 i\" \n      by (rule add_scalar_prod_distrib, insert gs i, auto)\n    also have \"(?g1 i + ?mu_f1) \\<bullet> ?mu_f1 = ?g1 i \\<bullet> ?mu_f1 + ?mu_f1 \\<bullet> ?mu_f1\" \n      by (rule add_scalar_prod_distrib, insert gs i, auto)\n    also have \"?mu_f1 \\<bullet> ?g1 i = ?g1 i \\<bullet> ?mu_f1\"\n      by (rule comm_scalar_prod, insert gs i, auto)\n    also have \"?g1 i \\<bullet> ?g1 i = sq_norm (?g1 i)\" \n      by (simp add: sq_norm_vec_as_cscalar_prod)\n    also have \"?g1 i \\<bullet> ?mu_f1 = ?mu1 i (i - 1) * (?g1 i \\<bullet> ?g1 (i - 1))\" \n      by (rule scalar_prod_smult_right, insert gs[OF i] gs[OF \\<open>i - 1 < m\\<close>], auto)\n    also have \"?g1 i \\<bullet> ?g1 (i - 1) = 0\" \n      using orthogonalD[OF fs.gs.orthogonal_gso, of i \"i - 1\"] i len i0  \n      by (auto simp: o_def)\n    also have \"?mu_f1 \\<bullet> ?mu_f1 = ?mu1 i (i - 1) * (?mu_f1 \\<bullet> ?g1 (i - 1))\" \n      by (rule scalar_prod_smult_right, insert gs[OF i] gs[OF \\<open>i - 1 < m\\<close>], auto)\n    also have \"?mu_f1 \\<bullet> ?g1 (i - 1) = ?mu1 i (i - 1) * (?g1 (i - 1) \\<bullet> ?g1 (i - 1))\" \n      by (rule scalar_prod_smult_left, insert gs[OF i] gs[OF \\<open>i - 1 < m\\<close>], auto)\n    also have \"?g1 (i - 1) \\<bullet> ?g1 (i - 1) = sq_norm (?g1 (i - 1))\" \n      by (simp add: sq_norm_vec_as_cscalar_prod)\n    finally have \"?n2 (i - 1) = ?n1 i + (?mu1 i (i - 1) * ?mu1 i (i - 1)) * ?n1 (i - 1)\" \n      by (simp add: ac_simps o_def)\n  } note sq_norm_g2_im1 = this\n\n  from norm_pos1[OF i] norm_pos1[OF im1] norm_pos2[OF i] norm_pos2[OF im1]\n  have norm0: \"?n1 i \\<noteq> 0\" \"?n1 (i - 1) \\<noteq> 0\" \"?n2 i \\<noteq> 0\" \"?n2 (i - 1) \\<noteq> 0\" by auto\n  hence norm0': \"?n2 (i - 1) \\<noteq> 0\" using i by auto\n\n  { (* new norm of g i *)\n    have si: \"Suc i \\<le> m\" and im1: \"i - 1 \\<le> m\" using i by auto\n    have det1: \"gs.Gramian_determinant (RAT fs) (Suc i) = (\\<Prod>j<Suc i. \\<parallel>fs.gs.gso j\\<parallel>\\<^sup>2)\"\n      using fs.gs.Gramian_determinant si len by auto\n    have det2: \"gs.Gramian_determinant (RAT fs') (Suc i) = (\\<Prod>j<Suc i. \\<parallel>gs2.gso j\\<parallel>\\<^sup>2)\"\n      using gs2.Gramian_determinant si len' by auto\n    from norm_zero1[OF less_le_trans[OF _ im1]] have 0: \"(\\<Prod>j < i-1. ?n1 j) \\<noteq> 0\" \n      by (subst prod_zero_iff, auto)\n    have \"rat_of_int (d fs' (Suc i)) = rat_of_int (d fs (Suc i))\" \n      using d_swap_unchanged[OF len i0 i _ si fs'_def] by auto\n    also have \"rat_of_int (d fs' (Suc i)) = gs.Gramian_determinant (RAT fs') (Suc i)\" unfolding d_def \n      by (subst fs.of_int_Gramian_determinant[symmetric], insert conn2 i g fs', auto simp: set_conv_nth)\n    also have \"\\<dots> = (\\<Prod>j<Suc i. ?n2 j)\" unfolding det2 by (rule prod.cong, insert i, auto)\n    also have \"rat_of_int (d fs (Suc i)) = gs.Gramian_determinant (RAT fs) (Suc i)\" unfolding d_def \n      by (subst fs.of_int_Gramian_determinant[symmetric], insert conn1 i g, auto)\n    also have \"\\<dots> = (\\<Prod>j<Suc i. ?n1 j)\" unfolding det1 by (rule prod.cong, insert i, auto)\n    also have \"{..<Suc i} = insert i (insert (i-1) {..<i-1})\" (is \"_ = ?set\") by auto\n    also have \"(\\<Prod>j\\<in> ?set. ?n2 j) = ?n2 i * ?n2 (i - 1) * (\\<Prod>j < i-1. ?n2 j)\" using i0\n      by (subst prod.insert; (subst prod.insert)?; auto)\n    also have \"(\\<Prod>j\\<in> ?set. ?n1 j) = ?n1 i * ?n1 (i - 1) * (\\<Prod>j < i-1. ?n1 j)\" using i0\n      by (subst prod.insert; (subst prod.insert)?; auto)\n    also have \"(\\<Prod>j < i-1. ?n2 j) = (\\<Prod>j < i-1. ?n1 j)\" \n      by (rule prod.cong, insert G2_G, auto)\n    finally have \"?n2 i = ?n1 i * ?n1 (i - 1) / ?n2 (i - 1)\" \n      using 0 norm0' by (auto simp: field_simps)\n  } note sq_norm_g2_i = this\n\n  (* mu values in rows > i do not change with j \\<notin> {i, i - 1} *)\n  {\n    fix ii j\n    assume ii: \"ii > i\" \"ii < m\" \n     and ji: \"j \\<noteq> i\" \"j \\<noteq> i - 1\" \n    {\n      assume j: \"j < ii\" \n      have \"?mu2 ii j = (?f2 ii \\<bullet> ?g2 j) / sq_norm (?g2 j)\" \n        unfolding gs2.\\<mu>.simps using j by auto\n      also have \"?f2 ii = ?f1 ii\" using ii len unfolding fs'_def by auto\n      also have \"?g2 j = ?g1 j\" using g2_g1_identical[of j] j ii ji by auto\n      finally have \"?mu2 ii j = ?mu1 ii j\" \n        unfolding fs.gs.\\<mu>.simps using j by auto\n    }\n    hence \"?mu2 ii j = ?mu1 ii j\" by (cases \"j < ii\", auto simp: gs2.\\<mu>.simps fs.gs.\\<mu>.simps)\n  } note mu_no_change_large_row = this\n\n  { (* the new value of mu i (i - 1) *)\n    have \"?mu2 i (i - 1) = (?f2 i \\<bullet> ?g2 (i - 1)) / ?n2 (i - 1)\" \n      unfolding gs2.\\<mu>.simps using i0 by auto\n    also have \"?f2 i \\<bullet> ?g2 (i - 1) = ?f1 (i - 1) \\<bullet> ?g2 (i - 1)\" \n      using len i i0 unfolding fs'_def by auto\n    also have \"\\<dots> = ?f1 (i - 1) \\<bullet> (?g1 i + ?mu1 i (i - 1) \\<cdot>\\<^sub>v ?g1 (i - 1))\" \n      unfolding g2_im1 by simp\n    also have \"\\<dots> = ?f1 (i - 1) \\<bullet> ?g1 i + ?f1 (i - 1) \\<bullet> (?mu1 i (i - 1) \\<cdot>\\<^sub>v ?g1 (i - 1))\" \n      by (rule scalar_prod_add_distrib[of _ n], insert i gs g, auto)\n    also have \"?f1 (i - 1) \\<bullet> ?g1 i = 0\" \n      by (subst fs.gs.fi_scalar_prod_gso, insert conn1 im1 i i0, auto simp: fs.gs.\\<mu>.simps fs.gs.\\<mu>.simps)\n    also have \"?f1 (i - 1) \\<bullet> (?mu1 i (i - 1) \\<cdot>\\<^sub>v ?g1 (i - 1)) = \n       ?mu1 i (i - 1) * (?f1 (i - 1) \\<bullet> ?g1 (i - 1))\"  \n      by (rule scalar_prod_smult_distrib, insert gs g i, auto)\n    also have \"?f1 (i - 1) \\<bullet> ?g1 (i - 1) = ?n1 (i - 1)\" \n      by (subst fs.gs.fi_scalar_prod_gso, insert conn1 im1, auto simp: fs.gs.\\<mu>.simps)\n    finally \n    have \"?mu2 i (i - 1) = ?mu1 i (i - 1) * ?n1 (i - 1) / ?n2 (i - 1)\" \n      by (simp add: sq_norm_vec_as_cscalar_prod)\n  } note mu'_mu_i_im1 = this\n\n  { (* the new values of mu ii (i - 1) for ii > i *)\n    fix ii assume iii: \"ii > i\" and ii: \"ii < m\" \n    hence iii1: \"i - 1 < ii\" by auto\n    have \"?mu2 ii (i - 1) = (?f2 ii \\<bullet> ?g2 (i - 1)) / ?n2 (i - 1)\" \n      unfolding gs2.\\<mu>.simps using i0 iii1 by auto\n    also have \"?f2 ii \\<bullet> ?g2 (i-1) = ?f1 ii \\<bullet> ?g2 (i - 1)\" \n      using len i i0 iii ii unfolding fs'_def by auto\n    also have \"\\<dots> = ?f1 ii \\<bullet> (?g1 i + ?mu1 i (i - 1) \\<cdot>\\<^sub>v ?g1 (i - 1))\" \n      unfolding g2_im1 by simp\n    also have \"\\<dots> = ?f1 ii \\<bullet> ?g1 i + ?f1 ii \\<bullet> (?mu1 i (i - 1) \\<cdot>\\<^sub>v ?g1 (i - 1))\" \n      by (rule scalar_prod_add_distrib[of _ n], insert i ii gs g, auto)\n    also have \"?f1 ii \\<bullet> ?g1 i = ?mu1 ii i * ?n1 i\" \n      by (rule fs.gs.fi_scalar_prod_gso, insert conn1 ii i, auto)\n    also have \"?f1 ii \\<bullet> (?mu1 i (i - 1) \\<cdot>\\<^sub>v ?g1 (i - 1)) = \n       ?mu1 i (i - 1) * (?f1 ii \\<bullet> ?g1 (i - 1))\"  \n      by (rule scalar_prod_smult_distrib, insert gs g i ii, auto)\n    also have \"?f1 ii \\<bullet> ?g1 (i - 1) = ?mu1 ii (i - 1) * ?n1 (i - 1)\" \n      by (rule fs.gs.fi_scalar_prod_gso, insert conn1 ii im1, auto)\n    finally have \"?mu2 ii (i - 1) = ?mu1 ii (i - 1) * ?mu2 i (i - 1) + ?mu1 ii i * ?n1 i / ?n2 (i - 1)\" \n      unfolding mu'_mu_i_im1 using norm0 by (auto simp: field_simps)\n  } note mu'_mu_large_row_im1 = this    \n\n  { (* the new values of mu ii i for ii > i *)\n    fix ii assume iii: \"ii > i\" and ii: \"ii < m\" \n    have \"?mu2 ii i = (?f2 ii \\<bullet> ?g2 i) / ?n2 i\" \n      unfolding gs2.\\<mu>.simps using i0 iii by auto\n    also have \"?f2 ii \\<bullet> ?g2 i = ?f1 ii \\<bullet> ?g2 i\" \n      using len i i0 iii ii unfolding fs'_def by auto\n    also have \"\\<dots> = ?f1 ii \\<bullet> (?g1 (i - 1) - (?f1 (i - 1) \\<bullet> ?g2 (i - 1) / ?n2 (i - 1)) \\<cdot>\\<^sub>v ?g2 (i - 1))\" \n      unfolding g2_i by simp\n    also have \"?f1 (i - 1) = ?f2 i\" using i i0 len unfolding fs'_def by auto\n    also have \"?f2 i \\<bullet> ?g2 (i - 1) / ?n2 (i - 1) = ?mu2 i (i - 1)\" \n      unfolding gs2.\\<mu>.simps using i i0 by auto\n    also have \"?f1 ii \\<bullet> (?g1 (i - 1) - ?mu2 i (i - 1) \\<cdot>\\<^sub>v ?g2 (i - 1))\n       = ?f1 ii \\<bullet> ?g1 (i - 1) - ?f1 ii \\<bullet> (?mu2 i (i - 1) \\<cdot>\\<^sub>v ?g2 (i - 1))\" \n      by (rule scalar_prod_minus_distrib[OF g gs], insert gs2 ii i, auto)\n    also have \"?f1 ii \\<bullet> ?g1 (i - 1) = ?mu1 ii (i - 1) * ?n1 (i - 1)\" \n      by (rule fs.gs.fi_scalar_prod_gso, insert conn1 ii im1, auto)\n    also have \"?f1 ii \\<bullet> (?mu2 i (i - 1) \\<cdot>\\<^sub>v ?g2 (i - 1)) = \n       ?mu2 i (i - 1) * (?f1 ii \\<bullet> ?g2 (i - 1))\" \n      by (rule scalar_prod_smult_distrib, insert gs gs2 g i ii, auto)\n    also have \"?f1 ii \\<bullet> ?g2 (i - 1) = (?f1 ii \\<bullet> ?g2 (i - 1) / ?n2 (i - 1)) * ?n2 (i - 1)\" \n      using norm0 by (auto simp: field_simps)\n    also have \"?f1 ii \\<bullet> ?g2 (i - 1) = ?f2 ii \\<bullet> ?g2 (i - 1)\" \n      using len ii iii unfolding fs'_def by auto\n    also have \"\\<dots> / ?n2 (i - 1) = ?mu2 ii (i - 1)\" unfolding gs2.\\<mu>.simps using iii by auto\n    finally \n    have \"?mu2 ii i = \n       (?mu1 ii (i - 1) * ?n1 (i - 1) - ?mu2 i (i - 1) * ?mu2 ii (i - 1) * ?n2 (i - 1)) / ?n2 i\" by simp\n    also have \"\\<dots> = (?mu1 ii (i - 1) - ?mu1 i (i - 1) * ?mu2 ii (i - 1)) * ?n2 (i - 1) / ?n1 i\" \n      unfolding sq_norm_g2_i mu'_mu_i_im1 using norm0 by (auto simp: field_simps)\n    also have \"\\<dots> = (?mu1 ii (i - 1) * ?n2 (i - 1) - \n      ?mu1 i (i - 1) * ((?mu1 ii i * ?n1 i + ?mu1 i (i - 1) * ?mu1 ii (i - 1) * ?n1 (i - 1)))) / ?n1 i\" \n      unfolding mu'_mu_large_row_im1[OF iii ii] mu'_mu_i_im1 using norm0 by (auto simp: field_simps)\n    also have \"\\<dots> = ?mu1 ii (i - 1) - ?mu1 i (i - 1) * ?mu1 ii i\" \n      unfolding sq_norm_g2_im1 using norm0 by (auto simp: field_simps)\n    finally have \"?mu2 ii i = ?mu1 ii (i - 1) - ?mu1 i (i - 1) * ?mu1 ii i\" .\n  } note mu'_mu_large_row_i = this\n\n\n  {\n    fix k assume k: \"k < m\" \n    show \"?g2 k = ?newg k\" \n      unfolding g2_i[symmetric] \n      unfolding g2_im1[symmetric]\n      using g2_g1_identical[OF k] by auto\n    show \"?n2 k = ?new_norm k\" \n      unfolding sq_norm_g2_i[symmetric]\n      unfolding sq_norm_g2_im1[symmetric]\n      using g2_g1_identical[OF k] by auto\n    fix j assume jk: \"j < k\" hence j: \"j < m\" using k by auto\n    have \"k < i - 1 \\<or> k = i - 1 \\<or> k = i \\<or> k > i\" by linarith\n    thus \"?mu2 k j = ?new_mu k j\" \n      unfolding mu'_mu_i_im1[symmetric]\n      using\n        mu'_mu_large_row_i[OF _ k]\n        mu'_mu_large_row_im1 [OF _ k]\n        mu_no_change_large_row[OF _ k, of j]\n        mu'_mu_small_i\n        mu'_mu_i_im1_j jk j k\n      by auto\n  } note new_g = this\n\n  (* stay reduced *)\n  from inv have sred: \"reduced fs i\" by auto\n  have sred: \"reduced fs' (i - 1)\"\n    unfolding gram_schmidt_fs.reduced_def\n  proof (intro conjI[OF red] allI impI, goal_cases)\n    case (1 i' j)\n    with sred have \"\\<bar>?mu1 i' j\\<bar> \\<le> 1 / 2\" unfolding gram_schmidt_fs.reduced_def by auto\n    thus ?case using mu'_mu_small_i[OF 1(1)] by simp\n  qed\n\n  { (* 16.13 (ii) : norm of g (i - 1) decreases by reduction factor *)\n    note sq_norm_g2_im1\n    also have \"?n1 i + (?mu1 i (i - 1) * ?mu1 i (i - 1)) * ?n1 (i - 1)\n      < 1/\\<alpha> * (?n1 (i - 1)) + (1/2 * 1/2) * (?n1 (i - 1))\"\n    proof (rule add_less_le_mono[OF _ mult_mono])\n      from norm_ineq[unfolded mult.commute[of \\<alpha>],\n          THEN linordered_field_class.mult_imp_less_div_pos[OF \\<alpha>0(1)]]\n      show \"?n1 i < 1/\\<alpha> * ?n1 (i - 1)\" using len i by auto\n      from m12 have abs: \"abs (?mu1 i (i - 1)) \\<le> 1/2\" by auto\n      have \"?mu1 i (i - 1) * ?mu1 i (i - 1) \\<le> abs (?mu1 i (i - 1)) * abs (?mu1 i (i - 1))\" by auto\n      also have \"\\<dots> \\<le> 1/2 * 1/2\" using mult_mono[OF abs abs] by auto\n      finally show \"?mu1 i (i - 1) * ?mu1 i (i - 1) \\<le> 1/2 * 1/2\" by auto\n    qed auto\n    also have \"\\<dots> = reduction * sq_norm (?g1 (i - 1))\" unfolding reduction_def  \n      using \\<alpha>0 by (simp add: ring_distribs add_divide_distrib)\n    finally have \"?n2 (i - 1) < reduction * ?n1 (i - 1)\" .\n  } note g_reduction = this (* Lemma 16.13 (ii) *)\n\n  have lin_indpt_list_fs': \"gs.lin_indpt_list (RAT fs')\"\n    unfolding gs.lin_indpt_list_def using conn2 by auto\n\n  have mu_small: \"\\<mu>_small fs' (i - 1)\" \n    unfolding \\<mu>_small_def\n  proof (intro allI impI, goal_cases)\n    case (1 j)\n    thus ?case using inv(11) unfolding mu'_mu_i_im1_j[OF 1] \\<mu>_small_def by auto\n  qed      \n      \n  (* invariant is established *)\n  show newInv: \"LLL_invariant False (i - 1) fs'\"\n    by (rule LLL_invI, insert lin_indpt_list_fs' conn2 mu_small span' lattice fs' sred i, auto)\n\n  (* show decrease in measure *)\n  { (* 16.16 (ii), the decreasing case *)\n    have ile: \"i \\<le> m\" using i by auto\n    from Gd[OF newInv, folded d_def, OF ile] \n    have \"?R (d fs' i) = (\\<Prod>j<i. ?n2 j )\" by auto\n    also have \"\\<dots> = prod ?n2 ({0 ..< i-1} \\<union> {i - 1})\" \n      by (rule sym, rule prod.cong, (insert i0, auto)[1], insert i, auto)\n    also have \"\\<dots> = ?n2 (i - 1) * prod ?n2 ({0 ..< i-1})\" \n      by simp\n    also have \"prod ?n2 ({0 ..< i-1}) = prod ?n1 ({0 ..< i-1})\" \n      by (rule prod.cong[OF refl], subst g2_g1_identical, insert i, auto)\n    also have \"\\<dots> = (prod ?n1 ({0 ..< i-1} \\<union> {i - 1})) / ?n1 (i - 1)\" \n      by (subst prod.union_disjoint, insert norm_pos1[OF im1], auto)\n    also have \"prod ?n1 ({0 ..< i-1} \\<union> {i - 1}) = prod ?n1 {0..<i}\"\n      by (rule arg_cong[of _ _ \"prod ?n1\"], insert i0, auto)\n    also have \"\\<dots> = (\\<Prod>j<i. ?n1 j)\"\n      by (rule prod.cong, insert i0, auto)\n    also have \"\\<dots> = ?R (d fs i)\" unfolding d_def Gd[OF Linv ile]\n      by (rule prod.cong[OF refl], insert i, auto)\n    finally have new_di: \"?R (d fs' i) = ?n2 (i - 1) / ?n1 (i - 1) * ?R (d fs i)\" by simp\n    also have \"\\<dots> < (reduction * ?n1 (i - 1)) / ?n1 (i - 1) * ?R (d fs i)\"\n      by (rule mult_strict_right_mono[OF divide_strict_right_mono[OF g_reduction norm_pos1[OF im1]]],\n        insert LLL_d_pos[OF Linv] i, auto)  \n    also have \"\\<dots> = reduction * ?R (d fs i)\" using norm_pos1[OF im1] by auto\n    finally have \"d fs' i < real_of_rat reduction * d fs i\" \n      using of_rat_less of_rat_mult of_rat_of_int_eq by metis\n    note this new_di\n  } note d_i = this\n  show \"ii \\<le> m \\<Longrightarrow> ?R (d fs' ii) = (if ii = i then ?n2 (i - 1) / ?n1 (i - 1) * ?R (d fs i) else ?R (d fs ii))\" \n    for ii using d_i d by auto\n  have pos: \"k < m \\<Longrightarrow> 0 < d fs' k\" \"k < m \\<Longrightarrow> 0 \\<le> d fs' k\" for k \n    using LLL_d_pos[OF newInv, of k] by auto\n  have prodpos:\"0< (\\<Prod>i<m. d fs' i)\" apply (rule prod_pos)\n    using LLL_d_pos[OF newInv] by auto\n  have prod_pos':\"0 < (\\<Prod>x\\<in>{0..<m} - {i}. real_of_int (d fs' x))\" apply (rule prod_pos)\n    using LLL_d_pos[OF newInv] pos by auto\n  have prod_nonneg:\"0 \\<le> (\\<Prod>x\\<in>{0..<m} - {i}. real_of_int (d fs' x))\" apply (rule prod_nonneg)\n    using LLL_d_pos[OF newInv] pos by auto\n  have prodpos2:\"0<(\\<Prod>ia<m. d fs ia)\" apply (rule prod_pos)\n    using LLL_d_pos[OF assms(1)] by auto\n  have \"D fs' = real_of_int (\\<Prod>i<m. d fs' i)\" unfolding D_def using prodpos by simp\n  also have \"(\\<Prod>i<m. d fs' i) = (\\<Prod> j \\<in> {0 ..< m} - {i} \\<union> {i}. d fs' j)\"\n    by (rule prod.cong, insert i, auto)\n  also have \"real_of_int \\<dots> = real_of_int (\\<Prod> j \\<in> {0 ..< m} - {i}. d fs' j) * real_of_int (d fs' i)\" \n    by (subst prod.union_disjoint, auto)\n  also have \"\\<dots> < (\\<Prod> j \\<in> {0 ..< m} - {i}. d fs' j) * (of_rat reduction * d fs i)\"\n    by(rule mult_strict_left_mono[OF d_i(1)],insert prod_pos',auto)\n  also have \"(\\<Prod> j \\<in> {0 ..< m} - {i}. d fs' j) = (\\<Prod> j \\<in> {0 ..< m} - {i}. d fs j)\"\n    by (rule prod.cong, insert d, auto)\n  also have \"\\<dots> * (of_rat reduction * d fs i) \n    = of_rat reduction * (\\<Prod> j \\<in> {0 ..< m} - {i} \\<union> {i}. d fs j)\" \n    by (subst prod.union_disjoint, auto)\n  also have \"(\\<Prod> j \\<in> {0 ..< m} - {i} \\<union> {i}. d fs j) = (\\<Prod> j<m. d fs j)\" \n    by (subst prod.cong, insert i, auto)\n  finally have D: \"D fs' < real_of_rat reduction * D fs\"\n    unfolding D_def using prodpos2 by auto\n  have logD: \"logD fs' < logD fs\" \n  proof (cases \"\\<alpha> = 4/3\")\n    case True\n    show ?thesis using D unfolding reduction(4)[OF True] logD_def unfolding True by simp\n  next\n    case False\n    hence False': \"\\<alpha> = 4/3 \\<longleftrightarrow> False\" by simp\n    from False \\<alpha> have \"\\<alpha> > 4/3\" by simp\n    with reduction have reduction1: \"reduction < 1\" by simp\n    let ?new = \"real (D fs')\" \n    let ?old = \"real (D fs)\" \n    let ?log = \"log (1/of_rat reduction)\" \n    note pos = LLL_D_pos[OF newInv] LLL_D_pos[OF assms(1)]\n    from reduction have \"real_of_rat reduction > 0\" by auto\n    hence gediv:\"1/real_of_rat reduction > 0\" by auto\n    have \"(1/of_rat reduction) * ?new \\<le> ((1/of_rat reduction) * of_rat reduction) * ?old\"\n      unfolding mult.assoc real_mult_le_cancel_iff2[OF gediv] using D by simp\n    also have \"(1/of_rat reduction) * of_rat reduction = 1\" using reduction by auto\n    finally have \"(1/of_rat reduction) * ?new \\<le> ?old\" by auto\n    hence \"?log ((1/of_rat reduction) * ?new) \\<le> ?log ?old\"\n      by (subst log_le_cancel_iff, auto simp: pos reduction1 reduction)\n    hence \"floor (?log ((1/of_rat reduction) * ?new)) \\<le> floor (?log ?old)\" \n      by (rule floor_mono)\n    hence \"nat (floor (?log ((1/of_rat reduction) * ?new))) \\<le> nat (floor (?log ?old))\" by simp\n    also have \"\\<dots> = logD fs\" unfolding logD_def False' by simp\n    also have \"?log ((1/of_rat reduction) * ?new) = 1 + ?log ?new\" \n      by (subst log_mult, insert reduction reduction1, auto simp: pos )\n    also have \"floor (1 + ?log ?new) = 1 + floor (?log ?new)\" by simp\n    also have \"nat (1 + floor (?log ?new)) = 1 + nat (floor (?log ?new))\" \n      by (subst nat_add_distrib, insert pos reduction reduction1, auto)\n    also have \"nat (floor (?log ?new)) = logD fs'\" unfolding logD_def False' by simp\n    finally show \"logD fs' < logD fs\" by simp\n  qed\n  show \"LLL_measure i fs > LLL_measure (i - 1) fs'\" unfolding LLL_measure_def \n    using i logD by simp\nqed\n\nlemma LLL_inv_initial_state: \"LLL_invariant True 0 fs_init\" \nproof - \n  from lin_dep[unfolded gs.lin_indpt_list_def]\n  have \"set (RAT fs_init) \\<subseteq> Rn\" by auto\n  hence fs_init: \"set fs_init \\<subseteq> carrier_vec n\" by auto\n  show ?thesis \n    by (rule LLL_invI[OF fs_init len _ _ lin_dep], auto simp: L_def gs.reduced_def gs.weakly_reduced_def)\nqed\n\nlemma LLL_inv_m_imp_reduced: assumes \"LLL_invariant True m fs\" \n  shows \"reduced fs m\" \n  using LLL_invD[OF assms] by blast\n\nlemma basis_reduction_short_vector: assumes LLL_inv: \"LLL_invariant True m fs\" \n  and v: \"v = hd fs\" \n  and m0: \"m \\<noteq> 0\"\nshows \"v \\<in> carrier_vec n\"\n  \"v \\<in> L - {0\\<^sub>v n}\"  \n  \"h \\<in> L - {0\\<^sub>v n} \\<Longrightarrow> rat_of_int (sq_norm v) \\<le> \\<alpha> ^ (m - 1) * rat_of_int (sq_norm h)\" \n  \"v \\<noteq> 0\\<^sub>v j\" \nproof -\n  let ?L = \"lattice_of fs_init\" \n  have a1: \"\\<alpha> \\<ge> 1\" using \\<alpha> by auto \n  from LLL_invD[OF LLL_inv] have\n    L: \"lattice_of fs = L\" \n    and red: \"gram_schmidt_fs.weakly_reduced n (RAT fs) \\<alpha> (length (RAT fs))\" \n    and basis: \"lin_indep fs\" \n    and lenH: \"length fs = m\" \n    and H: \"set fs \\<subseteq> carrier_vec n\" \n    by (auto simp: gs.lin_indpt_list_def gs.reduced_def)\n  from lin_dep have G: \"set fs_init \\<subseteq> carrier_vec n\" unfolding gs.lin_indpt_list_def by auto\n  with m0 len have \"dim_vec (hd fs_init) = n\" by (cases fs_init, auto)\n  from v m0 lenH v have v: \"v = fs ! 0\" by (cases fs, auto)\n  interpret gs1: gram_schmidt_fs_lin_indpt n \"RAT fs\"\n    by (standard) (use assms LLL_invariant_def gs.lin_indpt_list_def in auto)\n  let ?r = \"rat_of_int\" \n  let ?rv = \"map_vec ?r\" \n  let ?F = \"RAT fs\" \n  let ?h = \"?rv h\" \n  { assume h:\"h \\<in> L - {0\\<^sub>v n}\" (is ?h_req)\n    from h[folded L] have h: \"h \\<in> lattice_of fs\" \"h \\<noteq> 0\\<^sub>v n\" by auto\n    {\n      assume f: \"?h = 0\\<^sub>v n\" \n      have \"?h = ?rv (0\\<^sub>v n)\" unfolding f by (intro eq_vecI, auto)\n      hence \"h = 0\\<^sub>v n\"\n        using of_int_hom.vec_hom_zero_iff[of h] of_int_hom.vec_hom_inj by auto\n      with h have False by simp\n    } hence h0: \"?h \\<noteq> 0\\<^sub>v n\" by auto\n    with lattice_of_of_int[OF H h(1)]\n    have \"?h \\<in> gs.lattice_of ?F - {0\\<^sub>v n}\" by auto\n  } \n  from gs1.weakly_reduced_imp_short_vector[OF red this a1] lenH\n  show \"h \\<in> L - {0\\<^sub>v n} \\<Longrightarrow> ?r (sq_norm v) \\<le> \\<alpha> ^ (m - 1) * ?r (sq_norm h)\"\n    using basis unfolding L v gs.lin_indpt_list_def  by (auto simp: sq_norm_of_int)\n  from m0 H lenH show vn: \"v \\<in> carrier_vec n\" unfolding v by (cases fs, auto)\n  have vL: \"v \\<in> L\" unfolding L[symmetric] v using m0 H lenH\n    by (intro basis_in_latticeI, cases fs, auto)\n  {\n    assume \"v = 0\\<^sub>v n\" \n    hence \"hd ?F = 0\\<^sub>v n\" unfolding v using m0 lenH by (cases fs, auto)\n    with gs.lin_indpt_list_nonzero[OF basis] have False using m0 lenH by (cases fs, auto)\n  }\n  with vL show v: \"v \\<in> L - {0\\<^sub>v n}\" by auto\n  have jn:\"0\\<^sub>v j \\<in> carrier_vec n \\<Longrightarrow> j = n\" unfolding zero_vec_def carrier_vec_def by auto\n  with v vn show \"v \\<noteq> 0\\<^sub>v j\" by auto\nqed\n\n\nlemma LLL_mu_d_Z: assumes inv: \"LLL_invariant upw i fs\" \n  and j: \"j \\<le> ii\" and ii: \"ii < m\" \nshows \"of_int (d fs (Suc j)) * \\<mu> fs ii j \\<in> \\<int>\"\nproof -\n  interpret fs: fs_int' n m fs_init \\<alpha> upw i fs\n    by standard (use inv in auto)\n  show ?thesis\n    using assms fs.fs_int_mu_d_Z LLL_invD[OF inv] unfolding d_def fs.d_def by auto\nqed\n\ncontext fixes upw i fs\n  assumes Linv: \"LLL_invariant upw i fs\" and gbnd: \"g_bound fs\" \nbegin\n\ninterpretation gs1: gram_schmidt_fs_lin_indpt n \"RAT fs\"\n  by (standard) (use Linv LLL_invariant_def gs.lin_indpt_list_def in auto)\n\nlemma LLL_inv_N_pos: assumes m: \"m \\<noteq> 0\" \nshows \"N > 0\" \nproof -\n  let ?r = rat_of_int\n  note inv = LLL_invD[OF Linv]\n  from inv have F: \"RAT fs ! 0 \\<in> Rn\" \"fs ! 0 \\<in> carrier_vec n\" using m by auto\n  from m have upt: \"[0..< m] = 0 # [1 ..< m]\" using upt_add_eq_append[of 0 1 \"m - 1\"] by auto\n  from inv(6) m have \"map_vec ?r (fs ! 0) \\<noteq> 0\\<^sub>v n\" using gs.lin_indpt_list_nonzero[OF inv(1)]\n    unfolding set_conv_nth by force\n  hence F0: \"fs ! 0 \\<noteq> 0\\<^sub>v n\" by auto\n  hence \"sq_norm (fs ! 0) \\<noteq> 0\" using F by simp\n  hence 1: \"sq_norm (fs ! 0) \\<ge> 1\" using sq_norm_vec_ge_0[of \"fs ! 0\"] by auto\n  from gbnd m have \"sq_norm (gso fs 0) \\<le> of_nat N\" unfolding g_bound_def by auto\n  also have \"gso fs 0 = RAT fs ! 0\" unfolding upt using F by (simp add: gs1.gso.simps[of 0])\n  also have \"RAT fs ! 0 = map_vec ?r (fs ! 0)\" using inv(6) m by auto\n  also have \"sq_norm \\<dots> = ?r (sq_norm (fs ! 0))\" by (simp add: sq_norm_of_int)\n  finally show ?thesis using 1 by (cases N, auto)\nqed\n\n\n(* equation (3) in front of Lemma 16.18 *)\nlemma d_approx_main: assumes i: \"ii \\<le> m\" \"m \\<noteq> 0\" \nshows \"rat_of_int (d fs ii) \\<le> rat_of_nat (N^ii)\" \nproof -\n  note inv = LLL_invD[OF Linv]\n  from LLL_inv_N_pos i have A: \"0 < N\" by auto\n  note main = inv(2)[unfolded gram_schmidt_int_def gram_schmidt_wit_def]\n  have \"rat_of_int (d fs ii) = (\\<Prod>j<ii. \\<parallel>gso fs j\\<parallel>\\<^sup>2)\" unfolding d_def using i\n    by (auto simp: Gramian_determinant [OF Linv])\n  also have \"\\<dots> \\<le> (\\<Prod>j<ii. of_nat N)\" using i\n    by (intro prod_mono ballI conjI prod_nonneg, insert gbnd[unfolded g_bound_def], auto)\n  also have \"\\<dots> = (of_nat N)^ii\" unfolding prod_constant by simp\n  also have \"\\<dots> = of_nat (N^ii)\" by simp\n  finally show ?thesis by simp\nqed\n\nlemma d_approx: assumes i: \"ii < m\"  \n  shows \"rat_of_int (d fs ii) \\<le> rat_of_nat (N^ii)\" \n  using d_approx_main[of ii] assms by auto\n\n\nlemma d_bound: assumes i: \"ii < m\" \n  shows \"d fs ii \\<le> N^ii\" \n  using d_approx[OF assms] unfolding d_def by linarith\n\n\nlemma D_approx: \"D fs \\<le> N ^ (m * m)\" \nproof - \n  note inv = LLL_invD[OF Linv]\n  from LLL_inv_N_pos have N: \"m \\<noteq> 0 \\<Longrightarrow> 0 < N\" by auto\n  note main = inv(2)[unfolded gram_schmidt_int_def gram_schmidt_wit_def]\n  have \"rat_of_int (\\<Prod>i<m. d fs i) = (\\<Prod>i<m. rat_of_int (d fs i))\" by simp\n  also have \"\\<dots> \\<le> (\\<Prod>i<m. (of_nat N) ^ i)\" \n    by (rule prod_mono, insert d_approx LLL_d_pos[OF Linv], auto simp: less_le)\n  also have \"\\<dots> \\<le> (\\<Prod>i<m. (of_nat N ^ m))\" \n    by (rule prod_mono, insert N, auto intro: pow_mono_exp)\n  also have \"\\<dots> = (of_nat N)^(m * m)\" unfolding prod_constant power_mult by simp\n  also have \"\\<dots> = of_nat (N ^ (m * m))\" by simp\n  finally have \"(\\<Prod>i<m. d fs i) \\<le> N ^ (m * m)\" by linarith\n  also have \"(\\<Prod>i<m. d fs i) = D fs\" unfolding D_def \n    by (subst nat_0_le, rule prod_nonneg, insert LLL_d_pos[OF Linv], auto simp: le_less)  \n  finally show \"D fs \\<le> N ^ (m * m)\" by linarith \nqed\n\n\nlemma LLL_measure_approx: assumes \"\\<alpha> > 4/3\" \"m \\<noteq> 0\" \nshows \"LLL_measure i fs \\<le> m + 2 * m * m * log base N\"\nproof -   \n  have b1: \"base > 1\" using base assms by auto\n  have id: \"base = 1 / real_of_rat reduction\" unfolding base_def reduction_def using \\<alpha>0 by\n    (auto simp: field_simps of_rat_divide)\n  from LLL_D_pos[OF Linv] have D1: \"real (D fs) \\<ge> 1\" by auto\n  note invD = LLL_invD[OF Linv]  \n  from invD\n  have F: \"set fs \\<subseteq> carrier_vec n\" and len: \"length fs = m\" by auto\n  have N0: \"N > 0\" using LLL_inv_N_pos[OF assms(2)] .\n  from D_approx \n  have D: \"D fs \\<le> N ^ (m * m)\" .\n  hence \"real (D fs) \\<le> real (N ^ (m * m))\" by linarith\n  also have \"\\<dots> = real N ^ (m * m)\" by simp\n  finally have log: \"log base (real (D fs)) \\<le> log base (real N ^ (m * m))\"   \n    by (subst log_le_cancel_iff[OF b1], insert D1 N0, auto)\n\n  have \"real (logD fs) = real (nat \\<lfloor>log base (real (D fs))\\<rfloor>)\" \n    unfolding logD_def id using assms by auto\n  also have \"\\<dots> \\<le> log base (real (D fs))\" using b1 D1 by auto\n  also have \"\\<dots> \\<le> log base (real N ^ (m * m))\" by fact\n  also have \"\\<dots> = (m * m) * log base (real N)\" \n    by (rule log_nat_power, insert N0, auto)\n  finally have main: \"logD fs \\<le> m * m * log base N\" by simp\n\n  have \"real (LLL_measure i fs) = real (2 * logD fs + m - i)\"\n    unfolding LLL_measure_def split invD(1) by simp\n  also have \"\\<dots> \\<le> 2 * real (logD fs) + m\" using invD by simp\n  also have \"\\<dots> \\<le> 2 * (m * m * log base N) + m\" using main by auto\n  finally show ?thesis by simp\nqed\nend\n\nlemma g_bound_fs_init: \"g_bound fs_init\" \nproof -\n  {\n    fix i\n    assume i: \"i < m\" \n    let ?N = \"map (nat o sq_norm) fs_init\"\n    let ?r = rat_of_int\n    from i have mem: \"nat (sq_norm (fs_init ! i)) \\<in> set ?N\" using fs_init len unfolding set_conv_nth by force\n    interpret gs: gram_schmidt_fs_lin_indpt n \"RAT fs_init\"\n      by (standard) (use len lin_dep LLL_invariant_def gs.lin_indpt_list_def in auto)\n    from mem_set_imp_le_max_list[OF _ mem]\n    have FN: \"nat (sq_norm (fs_init ! i)) \\<le> N\" unfolding N_def by force\n    hence \"\\<parallel>fs_init ! i\\<parallel>\\<^sup>2 \\<le> int N\" using i by auto\n    also have \"\\<dots> \\<le> int (N * m)\" using i by fastforce\n    finally have f_bnd:  \"\\<parallel>fs_init ! i\\<parallel>\\<^sup>2 \\<le> int (N * m)\" .\n    from FN have \"rat_of_nat (nat (sq_norm (fs_init ! i))) \\<le> rat_of_nat N\" by simp\n    also have \"rat_of_nat (nat (sq_norm (fs_init ! i))) = ?r (sq_norm (fs_init ! i))\" \n      using sq_norm_vec_ge_0[of \"fs_init ! i\"] by auto\n    also have \"\\<dots> = sq_norm (RAT fs_init ! i)\" unfolding sq_norm_of_int[symmetric] using fs_init len i by auto\n    finally have \"sq_norm (RAT fs_init ! i) \\<le> rat_of_nat N\" .\n    with gs.sq_norm_gso_le_f i len lin_dep\n    have g_bnd: \"\\<parallel>gs.gso i\\<parallel>\\<^sup>2 \\<le> rat_of_nat N\"\n      unfolding gs.lin_indpt_list_def by fastforce\n    note f_bnd g_bnd\n  }\n  thus \"g_bound fs_init\" unfolding g_bound_def by auto\nqed\n\nlemma LLL_measure_approx_fs_init: \n  \"LLL_invariant upw i fs_init \\<Longrightarrow> 4 / 3 < \\<alpha> \\<Longrightarrow> m \\<noteq> 0 \\<Longrightarrow> \n  real (LLL_measure i fs_init) \\<le> real m + real (2 * m * m) * log base (real N)\" \n  using LLL_measure_approx[OF _ g_bound_fs_init] .\n\nlemma N_le_MMn: assumes m0: \"m \\<noteq> 0\" \n  shows \"N \\<le> nat M * nat M * n\" \n  unfolding N_def\nproof (rule max_list_le, unfold set_map o_def)\n  fix ni\n  assume \"ni \\<in> (\\<lambda>x. nat \\<parallel>x\\<parallel>\\<^sup>2) ` set fs_init\" \n  then obtain fi where ni: \"ni = nat (\\<parallel>fi\\<parallel>\\<^sup>2)\" and fi: \"fi \\<in> set fs_init\" by auto\n  from fi len obtain i where fii: \"fi = fs_init ! i\" and i: \"i < m\" unfolding set_conv_nth by auto\n  from fi fs_init have fi: \"fi \\<in> carrier_vec n\" by auto\n  let ?set = \"{\\<bar>fs_init ! i $ j\\<bar> |i j. i < m \\<and> j < n} \\<union> {0}\" \n  have id: \"?set = (\\<lambda> (i,j). abs (fs_init ! i $ j)) ` ({0..<m} \\<times> {0..<n}) \\<union> {0}\" \n    by force\n  have fin: \"finite ?set\" unfolding id by auto\n  { \n    fix j assume \"j < n\" \n    hence \"M \\<ge> \\<bar>fs_init ! i $ j\\<bar>\" unfolding M_def using i\n      by (intro Max_ge[of _ \"abs (fs_init ! i $ j)\"], intro fin, auto)\n  } note M = this\n  from Max_ge[OF fin, of 0] have M0: \"M \\<ge> 0\" unfolding M_def by auto\n  have \"ni = nat (\\<parallel>fi\\<parallel>\\<^sup>2)\" unfolding ni by auto\n  also have \"\\<dots> \\<le> nat (int n * \\<parallel>fi\\<parallel>\\<^sub>\\<infinity>\\<^sup>2)\" using sq_norm_vec_le_linf_norm[OF fi]\n    by (intro nat_mono, auto)\n  also have \"\\<dots> = n * nat (\\<parallel>fi\\<parallel>\\<^sub>\\<infinity>\\<^sup>2)\"\n    by (simp add: nat_mult_distrib)\n  also have \"\\<dots> \\<le> n * nat (M^2)\" \n  proof (rule mult_left_mono[OF nat_mono])\n    have fi: \"\\<parallel>fi\\<parallel>\\<^sub>\\<infinity> \\<le> M\" unfolding linf_norm_vec_def    \n    proof (rule max_list_le, unfold set_append set_map, rule ccontr)\n      fix x\n      assume \"x \\<in> abs ` set (list_of_vec fi) \\<union> set [0]\" and xM: \"\\<not> x \\<le> M\"  \n      with M0 obtain fij where fij: \"fij \\<in> set (list_of_vec fi)\" and x: \"x = abs fij\" by auto\n      from fij fi obtain j where j: \"j < n\" and fij: \"fij = fi $ j\" \n        unfolding set_list_of_vec vec_set_def by auto\n      from M[OF j] xM[unfolded x fij fii] show False by auto\n    qed auto                \n    show \"\\<parallel>fi\\<parallel>\\<^sub>\\<infinity>\\<^sup>2 \\<le> M^2\" unfolding abs_le_square_iff[symmetric] using fi \n      using linf_norm_vec_ge_0[of fi] by auto\n  qed auto\n  finally show \"ni \\<le> nat M * nat M * n\" using M0 \n    by (subst nat_mult_distrib[symmetric], auto simp: power2_eq_square ac_simps)\nqed (insert m0 len, auto)\n\n\n\nsubsection \\<open>Basic LLL implementation based on previous results\\<close>\n\ntext \\<open>We now assemble a basic implementation of the LLL algorithm,\n  where only the lattice basis is updated, and where the GSO and the $\\mu$-values\n  are always computed from scratch. This enables a simple soundness proof \n  and permits to separate an efficient implementation from the soundness reasoning.\\<close>\n\nfun basis_reduction_add_rows_loop where\n  \"basis_reduction_add_rows_loop i fs 0 = fs\" \n| \"basis_reduction_add_rows_loop i fs (Suc j) = (\n     let c = round (\\<mu> fs i j);\n         fs' = (if c = 0 then fs else fs[ i := fs ! i - c \\<cdot>\\<^sub>v fs ! j])\n      in basis_reduction_add_rows_loop i fs' j)\" \n\ndefinition basis_reduction_add_rows where\n  \"basis_reduction_add_rows upw i fs = \n     (if upw then basis_reduction_add_rows_loop i fs i else fs)\" \n\ndefinition basis_reduction_swap where\n  \"basis_reduction_swap i fs = (False, i - 1, fs[i := fs ! (i - 1), i - 1 := fs ! i])\" \n\ndefinition basis_reduction_step where\n  \"basis_reduction_step upw i fs = (if i = 0 then (True, Suc i, fs)\n     else let \n       fs' = basis_reduction_add_rows upw i fs\n     in if sq_norm (gso fs' (i - 1)) \\<le> \\<alpha> * sq_norm (gso fs' i) then\n          (True, Suc i, fs') \n        else basis_reduction_swap i fs')\" \n\nfunction basis_reduction_main where\n  \"basis_reduction_main (upw,i,fs) = (if i < m \\<and> LLL_invariant upw i fs\n     then basis_reduction_main (basis_reduction_step upw i fs) else\n     fs)\"\n  by pat_completeness auto\n\ndefinition \"reduce_basis = basis_reduction_main (True, 0, fs_init)\" \n\ndefinition \"short_vector = hd reduce_basis\" \n\ntext \\<open>Soundness of this implementation is easily proven\\<close>\n\nlemma basis_reduction_add_rows_loop: assumes \n  inv: \"LLL_invariant True i fs\" \n  and mu_small: \"\\<mu>_small_row i fs j\"\n  and res: \"basis_reduction_add_rows_loop i fs j = fs'\" \n  and i: \"i < m\" \n  and j: \"j \\<le> i\" \nshows \"LLL_invariant False i fs'\" \"LLL_measure i fs' = LLL_measure i fs\" \nproof (atomize(full), insert assms, induct j arbitrary: fs)\n  case (0 fs)\n  thus ?case using basis_reduction_add_row_done[of i fs] by auto\nnext\n  case (Suc j fs)\n  hence j: \"j < i\" by auto\n  let ?c = \"round (\\<mu> fs i j)\" \n  show ?case\n  proof (cases \"?c = 0\")\n    case True\n    thus ?thesis using Suc(1)[OF Suc(2) basis_reduction_add_row_main_0[OF Suc(2) i j True Suc(3)]]\n      Suc(2-) by auto\n  next\n    case False\n    note step = basis_reduction_add_row_main[OF Suc(2) i j refl]\n    show ?thesis using Suc(1)[OF step(1-2)] False Suc(2-) step(3) by auto\n  qed\nqed\n\nlemma basis_reduction_add_rows: assumes \n  inv: \"LLL_invariant upw i fs\" \n  and res: \"basis_reduction_add_rows upw i fs = fs'\" \n  and i: \"i < m\" \nshows \"LLL_invariant False i fs'\" \"LLL_measure i fs' = LLL_measure i fs\" \nproof (atomize(full), goal_cases)\n  case 1\n  note def = basis_reduction_add_rows_def\n  show ?case\n  proof (cases upw)\n    case False\n    with res inv show ?thesis by (simp add: def)\n  next\n    case True\n    with inv have \"LLL_invariant True i fs\" by auto\n    note start = this \\<mu>_small_row_refl[of i fs]\n    from res[unfolded def] True have \"basis_reduction_add_rows_loop i fs i = fs'\" by auto\n    from basis_reduction_add_rows_loop[OF start this i]\n    show ?thesis by auto\n  qed\nqed\n\nlemma basis_reduction_swap: assumes \n  inv: \"LLL_invariant False i fs\" \n  and res: \"basis_reduction_swap i fs = (upw',i',fs')\" \n  and cond: \"sq_norm (gso fs (i - 1)) > \\<alpha> * sq_norm (gso fs i)\" \n  and i: \"i < m\" \"i \\<noteq> 0\" \nshows \"LLL_invariant upw' i' fs'\" (is ?g1)\n  \"LLL_measure i' fs' < LLL_measure i fs\" (is ?g2)\nproof -\n  note def = basis_reduction_swap_def\n  from res[unfolded basis_reduction_swap_def]\n  have id: \"upw' = False\" \"i' = i - 1\" \"fs' = fs[i := fs ! (i - 1), i - 1 := fs ! i]\" by auto\n  from basis_reduction_swap_main(1-2)[OF inv i cond id(3)] show ?g1 ?g2 unfolding id by auto\nqed\n\nlemma basis_reduction_step: assumes \n  inv: \"LLL_invariant upw i fs\" \n  and res: \"basis_reduction_step upw i fs = (upw',i',fs')\" \n  and i: \"i < m\" \nshows \"LLL_invariant upw' i' fs'\" \"LLL_measure i' fs' < LLL_measure i fs\" \nproof (atomize(full), goal_cases)\n  case 1\n  note def = basis_reduction_step_def\n  obtain fs'' where fs'': \"basis_reduction_add_rows upw i fs = fs''\" by auto\n  show ?case\n  proof (cases \"i = 0\")\n    case True\n    from increase_i[OF inv i True] True\n      res show ?thesis by (auto simp: def)\n  next\n    case False\n    hence id: \"(i = 0) = False\" by auto\n    note res = res[unfolded def id if_False fs'' Let_def]\n    let ?x = \"sq_norm (gso fs'' (i - 1))\" \n    let ?y = \"\\<alpha> * sq_norm (gso fs'' i)\" \n    from basis_reduction_add_rows[OF inv fs'' i]\n    have inv: \"LLL_invariant False i fs''\"\n      and meas: \"LLL_measure i fs'' = LLL_measure i fs\" by auto\n    show ?thesis\n    proof (cases \"?x \\<le> ?y\")\n      case True\n      from increase_i[OF inv i _ True] True res meas\n      show ?thesis by auto\n    next\n      case gt: False\n      hence \"?x > ?y\" by auto\n      from basis_reduction_swap[OF inv _ this i False] gt res meas\n      show ?thesis by auto\n    qed\n  qed\nqed\n\ntermination by (relation \"measure (\\<lambda> (upw,i,fs). LLL_measure i fs)\", insert basis_reduction_step, auto split: prod.splits)\n\ndeclare basis_reduction_main.simps[simp del]\n\nlemma basis_reduction_main: assumes \"LLL_invariant upw i fs\" \n  and res: \"basis_reduction_main (upw,i,fs) = fs'\" \nshows \"LLL_invariant True m fs'\" \n  using assms\nproof (induct \"LLL_measure i fs\" arbitrary: i fs upw rule: less_induct)\n  case (less i fs upw)\n  have id: \"LLL_invariant upw i fs = True\" using less by auto\n  note res = less(3)[unfolded basis_reduction_main.simps[of upw i fs] id]\n  note inv = less(2)\n  note IH = less(1)\n  show ?case\n  proof (cases \"i < m\")\n    case i: True\n    obtain i' fs' upw' where step: \"basis_reduction_step upw i fs = (upw',i',fs')\" \n      (is \"?step = _\") by (cases ?step, auto)\n    from IH[OF basis_reduction_step(2,1)[OF inv step i]] res[unfolded step] i\n    show ?thesis by auto\n  next\n    case False\n    with LLL_invD[OF inv] have i: \"i = m\" by auto\n    with False res inv have \"LLL_invariant upw m fs'\" by auto\n    thus \"LLL_invariant True m fs'\" unfolding LLL_invariant_def by auto\n  qed\nqed\n\nlemma reduce_basis_inv: assumes res: \"reduce_basis = fs\" \n  shows \"LLL_invariant True m fs\" \n  using basis_reduction_main[OF LLL_inv_initial_state res[unfolded reduce_basis_def]] .\n\nlemma reduce_basis: assumes res: \"reduce_basis = fs\"\n  shows \"lattice_of fs = L\" \n  \"reduced fs m\" \n  \"lin_indep fs\" \n  \"length fs = m\" \n  using LLL_invD[OF reduce_basis_inv[OF res]] by blast+\n  \nlemma short_vector: assumes res: \"short_vector = v\" \n  and m0: \"m \\<noteq> 0\"\nshows \"v \\<in> carrier_vec n\"\n  \"v \\<in> L - {0\\<^sub>v n}\"  \n  \"h \\<in> L - {0\\<^sub>v n} \\<Longrightarrow> rat_of_int (sq_norm v) \\<le> \\<alpha> ^ (m - 1) * rat_of_int (sq_norm h)\" \n  \"v \\<noteq> 0\\<^sub>v j\" \n  using basis_reduction_short_vector[OF reduce_basis_inv[OF refl] res[symmetric, unfolded short_vector_def] m0] \n  by blast+\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/LLL_Basis_Reduction/LLL.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.877476793890012, "lm_q2_score": 0.8438951045175643, "lm_q1q2_score": 0.7404983706915489}}
{"text": "chapter \"Expresiones aritm\u00e9ticas y booleanas\"\n\ntheory ExpA \nimports Main \nbegin\n\nsection \"Expresiones aritm\u00e9ticas\"\n\nsubsection \"Sintaxis\"\n\ntext {* Los nombres de las variables de las expresiones aritm\u00e9ticas son\ncadenas y se representan por nombreV *} \ntype_synonym nombreV = string\n\ntext {* Una expresi\u00f3n aritm\u00e9tica ~expA~ es un n\u00famero entero, una\n  variable o la suma de dos expresiones aritm\u00e9ticas. Por ejemplo,\n     Suma (N 5) (V x1)      :: expA\n     Suma (N 5) (V ''x 1'') :: expA\n  *} \ndatatype expA = N int | V nombreV | Suma expA expA\n\nterm \"N 5\"\nterm \"V x1\"\nterm \"Suma (N 5) (V x1)\"\nterm \"Suma (N 5) (V ''x 1'')\"\n\ntext {* La igualdad entre expresiones aritm\u00e9ticas es sint\u00e1tica, no\n  sem\u00e1ntica. Por ejemplo,\n     N 0 = N 0\n     Suma (N 0) (N 0) \\<noteq> N 0\n  *} \n\nvalue \"N 0 = N 0\"\nvalue \"Suma (N 0) (N 0) \\<noteq> N 0\"\n  \nsubsection \"Sem\u00e1ntica\"\n\ntext {* Los valores son n\u00fameros enteros y su tipo se representa por val\n*} \ntype_synonym val = int\n\ntext {* Los estados son funciones de los nombres de variables en\n  valores. *} \ntype_synonym estado = \"nombreV \\<Rightarrow> val\"\n\ntext {* (valor a s) es el valor de la expresi\u00f3n aritm\u00e9tica a en el\n  estado s. Por ejemplo, \n     valorA (Suma (V x) (N 5)) (\\<lambda>y. 0) = 5\n     valorA (Suma (V x) (N 5)) (\\<lambda>y. if y = x then 7 else 0) = 12\n     valorA (Suma (V x) (N 5)) ((\\<lambda>x. 0) (x:= 7)) = 12\n  *} \nfun valorA :: \"expA \\<Rightarrow> estado \\<Rightarrow> val\" where\n  \"valorA (N n) s       = n\" \n| \"valorA (V x) s       = s x\" \n| \"valorA (Suma a\\<^sub>1 a\\<^sub>2) s = valorA a\\<^sub>1 s + valorA a\\<^sub>2 s\"\n\nvalue \"valorA (Suma (V x) (N 5)) (\\<lambda>y. 0) = 5\"\nvalue \"valorA (Suma (V x) (N 5)) (\\<lambda>y. if y = x then 7 else 0) = 12\"\nvalue \"valorA (Suma (V x) (N 5)) ((\\<lambda>x. 0) (x:= 7)) = 12\"\n\ntext {* <x1 := a1, x2 := a2, ..., xn := an> es el estado que le asigna a\n  x1 el valor a1, a x2 el valor a2, ..., a xn el valor an y a las dem\u00e1s\n  variables el valor 0. Por ejemplo,\n     <''a'' := 3::int, ''b'' := 2> ''a'' = 3\n     <''a'' := 3::int, ''b'' := 2> ''b'' = 2\n     <''a'' := 3::int, ''b'' := 2> ''c'' = 0\n     <a := 3, b := 2> = (<> (a := 3)) (b := 2) \n     <a := 3, b := 2> = ((\\<lambda>x. 0) (a := 3)) (b := 2) \n*}\ndefinition null_estado (\"<>\") where\n  \"null_estado \\<equiv> \\<lambda>x. 0\"\nsyntax \n  \"_Estado\" :: \"updbinds => 'a\" (\"<_>\")\ntranslations\n  \"_Estado ms\" == \"_Update <> ms\"\n\nvalue \"<''a'' := 3::int, ''b'' := 2> ''a''\"\n  (* da 3 *)\nvalue \"<''a'' := 3::int, ''b'' := 2> ''b''\"\n  (* da 2 *)\nvalue \"<''a'' := 3::int, ''b'' := 2> ''c''\"\n  (* da 0 *)\n\nlemma \"\\<lbrakk>x \\<noteq> ''a''; x \\<noteq> ''b''\\<rbrakk> \\<Longrightarrow> \n       <''a'' := 3::int, ''b'' := 2> x = 0\"\n  by (simp add: null_estado_def)    \n\nlemma \"<a := 3, b := 2> = (<> (a := 3)) (b := 2)\" \n  by simp\n\nlemma \"<a := 3, b := 2> = ((\\<lambda>x. 0) (a := 3)) (b := 2)\" \n  by (simp add: null_estado_def)\n  \nvalue \"valorA (Suma (V ''x'') (N 5)) <''x'' := 7>\"\n  (* da 12 *)\nvalue \"valorA (Suma (V ''x'') (N 5)) <''y'' := 7>\"\n  (* da 5 *)\n\nsection \"Propagaci\u00f3n de constantes\"\n\ntext {* (simp_constA e) es la expresi\u00f3n aritm\u00e9tica obtenida aplicando\n  propagaci\u00f3n de constantes a la expresi\u00f3n e. Por ejemplo, \n     simp_constA (Suma (V ''x'') (Suma (N 3) (N 1))) \n       = Suma (V ''x'') (N 4)\n     simp_constA (Suma (N 3) (Suma (V ''x'') (N 1)))\n       = Suma (N 3) (Suma (V ''x'') (N 1))    \n     simp_constA (Suma (N 3) (Suma (V ''x'') (N 0))) \n       = Suma (N 3) (Suma (V ''x'') (N 0))\n*}\n\nfun simp_constA :: \"expA \\<Rightarrow> expA\" where\n\"simp_constA (N n) = N n\" |\n\"simp_constA (V x) = V x\" |\n\"simp_constA (Suma a\\<^sub>1 a\\<^sub>2) =\n  (case (simp_constA a\\<^sub>1, simp_constA 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> Suma b\\<^sub>1 b\\<^sub>2)\"\n\nvalue \"simp_constA (Suma (V ''x'') (Suma (N 3) (N 1)))\" \n  (* da \"Suma (V ''x'') (N 4)\" *)\nvalue \"simp_constA (Suma (N 3) (Suma (V ''x'') (N 1)))\" \n  (* da \"Suma (N 3) (Suma (V ''x'') (N 1))\" *)    \nvalue \"simp_constA (Suma (N 3) (Suma (V ''x'') (N 0)))\" \n  (* da \"Suma (N 3) (Suma (V ''x'') (N 0))\" *)\n  \ntext {* Prop.: La funci\u00f3n simp_constA es correcta; es decir, conserva el\n  valor de las expresiones aritm\u00e9ticas. *}\n\ntext {* 1\\<ordmasculine> intento *}  \ntheorem valorA_simp_constA1:\n  \"valorA (simp_constA a) s = valorA a s\"\napply (induction a)\napply auto\noops\n\ntext {* Se observa que no ha expandido la expresi\u00f3n case. Para que lo\n  haga, se a\u00f1ade \"split: expA.split\" *} \n\ntheorem valorA_simp_constA:\n  \"valorA (simp_constA a) s = valorA a s\"\napply(induction a)\napply (auto split: expA.split)\ndone\n\ntext {* (suma a1 a2) es la suma de las expresiones aritm\u00e9tica con\n  propagaci\u00f3n de constantes y usando las reglas de simplificaci\u00f3n\n  + 0 + a = a\n  + a + 0 = a\n  Por ejemplo, \n     suma (V ''x'') (suma (N 3) (N 1)) \n       = Suma (V ''x'') (N 4)\" *)\n     suma (N 3) (suma (V ''x'') (N 1)) \n       = Suma (N 3) (Suma (V ''x'') (N 1))    \n     suma (N 3) (suma (V ''x'') (N 0)) \n       = Suma (N 3) (V ''x'')\n*}\nfun suma :: \"expA \\<Rightarrow> expA \\<Rightarrow> expA\" where\n\"suma (N i1) (N i2) = N(i1+i2)\" |\n\"suma (N i) a = (if i=0 then a else Suma (N i) a)\" |\n\"suma a (N i) = (if i=0 then a else Suma a (N i))\" |\n\"suma a1 a2 = Suma a1 a2\"\n\nvalue \"suma (V ''x'') (suma (N 3) (N 1))\" \n  (* da \"Suma (V ''x'') (N 4)\" *)\nvalue \"suma (N 3) (suma (V ''x'') (N 1))\" \n  (* da \"Suma (N 3) (Suma (V ''x'') (N 1))\" *)    \nvalue \"suma (N 3) (suma (V ''x'') (N 0))\" \n  (* da \"Suma (N 3) (V ''x'')\" *)\n\ntext {* Prop.: La funci\u00f3n suma es correcta; es decir, conserva el\n  valor de las expresiones aritm\u00e9ticas. *}\nlemma valorA_suma[simp]:\n  \"valorA (suma a1 a2) s = valorA a1 s + valorA a2 s\"\napply (induction a1 a2 rule: suma.induct)\napply simp_all\ndone\n\ntext {* (simpA e) es la expresi\u00f3n aritm\u00e9tica obtenida simplificando e\n  con propagaci\u00f3n de constantes y las reglas del elemento neutro. Por\n  ejemplo, \n     simpA (Suma (V ''x'') (Suma (N 3) (N 1))) \n       = Suma (V ''x'') (N 4)\n     simpA (Suma (N 3) (Suma (V ''x'') (N 1))) \n       = Suma (N 3) (Suma (V ''x'') (N 1))    \n     simpA (Suma (N 3) (Suma (V ''x'') (N 0))) \n       = Suma (N 3) (V ''x'')\n     simpA (Suma (Suma (N 0) (N 0)) (Suma (V ''x'') (N 0)))\n       = V ''x''\n*}\nfun simpA :: \"expA \\<Rightarrow> expA\" where\n\"simpA (N n)        = N n\" |\n\"simpA (V x)        = V x\" |\n\"simpA (Suma a1 a2) = suma (simpA a1) (simpA a2)\"\n\nvalue \"simpA (Suma (V ''x'') (Suma (N 3) (N 1)))\" \n  (* da \"Suma (V ''x'') (N 4)\" *)\nvalue \"simpA (Suma (N 3) (Suma (V ''x'') (N 1)))\" \n  (* da \"Suma (N 3) (Suma (V ''x'') (N 1))\" *)    \nvalue \"simpA (Suma (N 3) (Suma (V ''x'') (N 0)))\" \n  (* da \"Suma (N 3) (V ''x'')\" *)\nvalue \"simpA (Suma (Suma (N 0) (N 0)) (Suma (V ''x'') (N 0)))\"\n  (* da \"V ''x''\" *)\n\ntext {* Prop.: La funci\u00f3n simpA es correcta; es decir, conserva el\n  valor de las expresiones aritm\u00e9ticas. *}\ntheorem valorA_simpA [simp]:\n  \"valorA (simpA a) s = valorA a s\"\napply (induction a)\napply simp_all\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/ExpA.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767874818408, "lm_q2_score": 0.8438950966654772, "lm_q1q2_score": 0.7404983583937005}}
{"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\nheader {* (More) Boolean Algebra *}\n\ntheory More_Boolean_Algebra\n  imports Main\nbegin\n\nsubsection {* Laws of Boolean Algebra *}\n\ntext {* 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. *}\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 {* Finally we prove the Galois connections for complementation. *}\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 {* Boolean Algebras with Operators *}\n\ntext {* 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. *}\n\ntext{* We define conjugation as a predicate which holds if a pair of functions\nare conjugates. *}\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 {* We now prove the standard lemmas. First we show that conjugation is\nsymmetric and that conjugates are uniqely defined. *}\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 {* Next we show that conjugates give rise to adjoints in a Galois\nconnection. *}\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 {* 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. *}\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 {* Additivity of adjoints obviously implies their isotonicity. *}\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 {* Next we prove cancellation and strictness laws. *}\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 {* The following variants of modular laws have more concrete counterparts\nin relation algebra. *}\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": "Josh-Tilles", "repo": "AFP", "sha": "f4bf1d502bde2a3469d482b62c531f1c3af3e881", "save_path": "github-repos/isabelle/Josh-Tilles-AFP", "path": "github-repos/isabelle/Josh-Tilles-AFP/AFP-f4bf1d502bde2a3469d482b62c531f1c3af3e881/thys/Relation_Algebra/More_Boolean_Algebra.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950868503681, "lm_q2_score": 0.8774767858797979, "lm_q1q2_score": 0.7404983484292139}}
{"text": "(*  Title:      Isomorphism Classes of Groups\n    Author:     Jakob von Raumer, Karlsruhe Institute of Technology\n    Maintainer: Jakob von Raumer <jakob.raumer@student.kit.edu>\n*)\n\ntheory GroupIsoClasses\nimports\n  \"HOL-Algebra.Coset\"\nbegin\n\nsection \\<open>Isomorphism Classes of Groups\\<close>\n\ntext \\<open>We construct a quotient type for isomorphism classes of groups.\\<close>\n\ntypedef 'a group = \"{G :: 'a monoid. group G}\"\nproof\n  show \"\\<And>a. \\<lparr>carrier = {a}, mult = (\\<lambda>x y. x), one = a\\<rparr> \\<in> {G. group G}\"\n  unfolding group_def group_axioms_def monoid_def Units_def by auto\nqed\n\ndefinition group_iso_rel :: \"'a group \\<Rightarrow> 'a group \\<Rightarrow> bool\"\n  where \"group_iso_rel G H = (\\<exists>\\<phi>. \\<phi> \\<in> iso (Rep_group G) (Rep_group H))\"\n\nquotient_type 'a group_iso_class = \"'a group\" / group_iso_rel\n  morphisms Rep_group_iso Abs_group_iso\nproof (rule equivpI)\n  show \"reflp group_iso_rel\"\n  proof (rule reflpI)\n    fix G :: \"'b group\"\n    show \"group_iso_rel G G\"\n      unfolding group_iso_rel_def using iso_set_refl by blast\n  qed\nnext\n  show \"symp group_iso_rel\"\n  proof (rule sympI)\n    fix G H :: \"'b group\"\n    assume \"group_iso_rel G H\"\n    then obtain \\<phi> where \"\\<phi> \\<in> iso (Rep_group G) (Rep_group H)\" unfolding group_iso_rel_def by auto\n    then obtain \\<phi>' where \"\\<phi>' \\<in> iso (Rep_group H) (Rep_group G)\" using group.iso_sym Rep_group\n      using group.iso_set_sym by blast\n    thus \"group_iso_rel H G\" unfolding group_iso_rel_def by auto\n  qed\nnext\n  show \"transp group_iso_rel\" \n  proof (rule transpI)\n    fix G H I :: \"'b group\"\n    assume \"group_iso_rel G H\" \"group_iso_rel H I\"\n    then obtain \\<phi> \\<psi> where \"\\<phi> \\<in> iso (Rep_group G) (Rep_group H)\" \"\\<psi> \\<in> iso (Rep_group H) (Rep_group I)\"\n      unfolding group_iso_rel_def by auto\n    then obtain \\<pi> where \"\\<pi> \\<in> iso (Rep_group G) (Rep_group I)\" \n      using iso_set_trans by blast\n    thus \"group_iso_rel G I\" unfolding group_iso_rel_def by auto\n  qed\nqed\n\ntext \\<open>This assigns to a given group the group isomorphism class\\<close>\n\ndefinition (in group) iso_class :: \"'a group_iso_class\"\n  where \"iso_class = Abs_group_iso (Abs_group (monoid.truncate G))\"\n\ntext \\<open>Two isomorphic groups do indeed have the same isomorphism class:\\<close>\n\nlemma iso_classes_iff:\n  assumes \"group G\"\n  assumes \"group H\"\n  shows \"(\\<exists>\\<phi>. \\<phi> \\<in> iso G H) = (group.iso_class G = group.iso_class H)\"\nproof -\n  from assms(1,2) have groups:\"group (monoid.truncate G)\" \"group (monoid.truncate H)\"\n    unfolding monoid.truncate_def group_def group_axioms_def Units_def monoid_def by auto\n  have \"(\\<exists>\\<phi>. \\<phi> \\<in> iso G H) = (\\<exists>\\<phi>. \\<phi> \\<in> iso (monoid.truncate G) (monoid.truncate H))\"\n    unfolding iso_def hom_def monoid.truncate_def by auto\n  also have \"\\<dots> = group_iso_rel (Abs_group (monoid.truncate G)) (Abs_group (monoid.truncate H))\"\n    unfolding group_iso_rel_def using groups group.Abs_group_inverse by (metis mem_Collect_eq)\n  also have \"\\<dots> = (group.iso_class G = group.iso_class H)\" using group.iso_class_def assms group_iso_class.abs_eq_iff by metis\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/Jordan_Hoelder/GroupIsoClasses.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392909114836, "lm_q2_score": 0.8376199633332891, "lm_q1q2_score": 0.7404889584384639}}
{"text": "theory Concrete_Semantics_2_4\n  imports Main\nbegin\n\n(* generalize the goal before induction. *)\n\n(*\ndatatype 'a list = Nil | Cons 'a \"'a list\"\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*)\n(* A linear time version of rev *)\n\n\n\nfun itrev :: \"'a list => 'a list => 'a list\" where\n\"itrev [] ys = ys\" |\n\"itrev (x # xs) ys = itrev xs (x # ys)\"\n\n(* Note that itrev is tail-recursive: it can be\ncompiled into a loop; no stack is necessary for executing it. *)\n\n(* lemma \"itrev xs [] = rev xs\" *)\n(* The induction hypothesis is too weak, we met the following formula needed to prove:\n \\<And> a xs: itrev xs [] = rev xs =) itrev xs [a] = rev xs @ [a] *)\n(* heuristic: \n    Generalize goals for induction by replacing constants by variables: \n        e.g., \"itrev xs [] = rev xs\" -> \"itrev xs ys = rev xs @ ys\" *)\n(* The induction hypothesis is ttile  weak\n  \\<And>a xs.\n       itrev xs ys = rev xs @ ys \\<Longrightarrow>\n       itrev xs (a # ys) = app (rev xs) [a] @ ys  \n\nwe prove the theorem for all ys instead of a fixed one: apply(induction xs ) -> apply(induction xs arbitrary: ys)\n*)\nlemma \"itrev xs ys = rev xs @ ys\"\napply(induction xs arbitrary: ys)\napply(auto)\ndone\n\n(* another heuristic for generalization:\n    Generalize induction by generalizing all free variables:\n        e.g., apply(induction xs ) -> apply(induction xs arbitrary: ys)\n    (except the induction variable itself).\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/ConcreteSemanticsChapter2/Concrete_Semantics_2_4.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199552262966, "lm_q2_score": 0.8840392893839085, "lm_q1q2_score": 0.7404889499920365}}
{"text": "theory sample3\n  imports Main begin\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\nterm \"\\<lambda>x::vname. 0::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 xs ys) s = aval xs s + aval ys 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 xs ys) = \n  (case (asimp_const xs, asimp_const ys) of\n    (N n, N m) \\<Rightarrow> N(n + m) |\n    (p, q) \\<Rightarrow> Plus p q)\"\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 x) (N y) = N(x + y)\" |\n  \"plus (N x) a = \n    (if x = 0 then\n      a\n    else\n      Plus (N x) a)\" |\n  \"plus a (N x) = \n    (if x = 0 then\n      a\n    else\n      Plus a (N x))\" |\n  \"plus x y = Plus x y\"\n\nthm plus.induct\n\nlemma aval_plus [simp]: \"aval (plus x y) s = aval x s + aval y s\"\n  apply (induction x y 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 x y) =  plus (asimp x) (asimp y)\"\n\nlemma \"aval (asimp a) s = aval a s\"\n  apply(induction a)\n  apply(auto)\n  done\n\ndatatype bexp = Bc bool | Not bexp | \n  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 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 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 x y = And x y\"\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\nfun bsimp :: \"bexp \\<Rightarrow> bexp\" where\n  \"bsimp (Bc value) = Bc value\" |\n  \"bsimp (Not b) = not (bsimp b)\" |\n  \"bsimp (And bx by) = and (bsimp bx) (bsimp by)\" |\n  \"bsimp (Less ax ay) = less (asimp ax) (asimp ay)\"\n\nlemma \"bval (bsimp b) s = bval b s\"\n  sorry\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/sample3.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218434359675, "lm_q2_score": 0.8031738034238807, "lm_q1q2_score": 0.7404634734520215}}
{"text": "theory Ex025\n  imports Main \nbegin \n  \n  \nlemma \"A \\<longleftrightarrow> \\<not>\\<not>A\" \nproof -\n  {\n    assume a:A \n    {\n      assume \"\\<not>A\"\n      with a have False by contradiction\n    }\n    hence \"\\<not>\\<not>A\" by (rule notI)\n  }\n  moreover \n  {\n    assume \"\\<not>\\<not>A\"\n    hence A by (rule notnotD)     \n  }    \n  ultimately show ?thesis by (rule iffI)    \nqed\n\n(*without notnotD*)\n    \ntheorem \"A \\<longleftrightarrow> \\<not>\\<not>A\"\nproof -\n {\n    assume a:A \n    {\n      assume \"\\<not>A\"\n      with a have False by contradiction\n    }\n    hence \"\\<not>\\<not>A\" by (rule notI)\n  }\n  moreover \n  {\n    assume \"\\<not>\\<not>A\"\n    {\n      assume \"\\<not>A\"\n      with \\<open>\\<not>\\<not>A\\<close> have False by (rule notE)\n      hence A by (rule FalseE)\n    }\n    hence A by (rule classical)\n  }    \n  ultimately show ?thesis by (rule iffI)    \nqed  \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/Ex025.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9219218348550491, "lm_q2_score": 0.8031737940012418, "lm_q1q2_score": 0.7404634578731161}}
{"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 {* First-Order Logic: quantifier examples (classical version) *}\n\ntheory Quantifiers_Cla\nimports FOL\nbegin\n\nlemma \"(ALL x y. P(x,y))  -->  (ALL y x. P(x,y))\"\n  by fast\n\nlemma \"(EX x y. P(x,y)) --> (EX y x. P(x,y))\"\n  by fast\n\n\n-- {* Converse is false *}\nlemma \"(ALL x. P(x)) | (ALL x. Q(x)) --> (ALL x. P(x) | Q(x))\"\n  by fast\n\nlemma \"(ALL x. P-->Q(x))  <->  (P--> (ALL x. Q(x)))\"\n  by fast\n\n\nlemma \"(ALL x. P(x)-->Q)  <->  ((EX x. P(x)) --> Q)\"\n  by fast\n\n\ntext {* Some harder ones *}\n\nlemma \"(EX x. P(x) | Q(x)) <-> (EX x. P(x)) | (EX x. Q(x))\"\n  by fast\n\n-- {* Converse is false *}\nlemma \"(EX x. P(x)&Q(x)) --> (EX x. P(x))  &  (EX x. Q(x))\"\n  by fast\n\n\ntext {* Basic test of quantifier reasoning *}\n\n-- {* TRUE *}\nlemma \"(EX y. ALL x. Q(x,y)) -->  (ALL x. EX y. Q(x,y))\"\n  by fast\n\nlemma \"(ALL x. Q(x))  -->  (EX x. Q(x))\"\n  by fast\n\n\ntext {* The following should fail, as they are false! *}\n\nlemma \"(ALL x. EX y. Q(x,y))  -->  (EX y. ALL x. Q(x,y))\"\n  apply fast?\n  oops\n\nlemma \"(EX x. Q(x))  -->  (ALL x. Q(x))\"\n  apply fast?\n  oops\n\nschematic_lemma \"P(?a) --> (ALL x. P(x))\"\n  apply fast?\n  oops\n\nschematic_lemma \"(P(?a) --> (ALL x. Q(x))) --> (ALL x. P(x) --> Q(x))\"\n  apply fast?\n  oops\n\n\ntext {* Back to things that are provable \\dots *}\n\nlemma \"(ALL x. P(x)-->Q(x)) & (EX x. P(x)) --> (EX x. Q(x))\"\n  by fast\n\n-- {* An example of why exI should be delayed as long as possible *}\nlemma \"(P --> (EX x. Q(x))) & P --> (EX x. Q(x))\"\n  by fast\n\nschematic_lemma \"(ALL x. P(x)-->Q(f(x))) & (ALL x. Q(x)-->R(g(x))) & P(d) --> R(?a)\"\n  by fast\n\nlemma \"(ALL x. Q(x))  -->  (EX x. Q(x))\"\n  by fast\n\n\ntext {* Some slow ones *}\n\n-- {* Principia Mathematica *11.53 *}\nlemma \"(ALL x y. P(x) --> Q(y)) <-> ((EX x. P(x)) --> (ALL y. Q(y)))\"\n  by fast\n\n(*Principia Mathematica *11.55  *)\nlemma \"(EX x y. P(x) & Q(x,y)) <-> (EX x. P(x) & (EX y. Q(x,y)))\"\n  by fast\n\n(*Principia Mathematica *11.61  *)\nlemma \"(EX y. ALL x. P(x) --> Q(x,y)) --> (ALL x. P(x) --> (EX y. Q(x,y)))\"\n  by fast\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/Quantifiers_Cla.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.900529778109184, "lm_q2_score": 0.8221891327004133, "lm_q1q2_score": 0.7404057972344856}}
{"text": "(*  Author: Lukas Bulwahn <lukas.bulwahn-at-gmail.com> *)\n\nsection \\<open>Stewart's Theorem and Apollonius' Theorem\\<close>\n\ntheory Stewart_Apollonius\nimports\n  Triangle.Triangle\nbegin\n\nsubsection \\<open>Stewart's Theorem\\<close>\n\ntheorem Stewart:\n  fixes A B C D :: \"'a::euclidean_space\"\n  assumes \"between (B, C) D\"\n  assumes \"a = dist B C\"\n  assumes \"b = dist A C\"\n  assumes \"c = dist B A\"\n  assumes \"d = dist A D\"\n  assumes \"m = dist B D\"\n  assumes \"n = dist C D\"\n  shows \"b\\<^sup>2 * m + c\\<^sup>2 * n = a * (d\\<^sup>2 + m * n)\"\nproof (cases)\n  assume \"B \\<noteq> D \\<and> C \\<noteq> D\"\n  let ?\\<theta> = \"angle B D A\"\n  let ?\\<theta>' = \"angle A D C\"\n  from \\<open>B \\<noteq> D \\<and> C \\<noteq> D\\<close> \\<open>between _ _\\<close> have cos: \"cos ?\\<theta>' = - cos ?\\<theta>\"\n    by (auto simp add: angle_inverse[of B C D] angle_commute[of A D C])\n  from \\<open>between _ _\\<close> have \"m + n = a\"\n    unfolding \\<open>a = _\\<close> \\<open>m = _\\<close> \\<open>n = _\\<close>\n    by (metis (no_types) between dist_commute)\n  have \"c\\<^sup>2 = m\\<^sup>2 + d\\<^sup>2 - 2 * d * m * cos ?\\<theta>\"\n    unfolding \\<open>c = _\\<close> \\<open>m = _\\<close> \\<open>d = _\\<close>\n    by (simp add: cosine_law_triangle[of B A D] dist_commute[of D A] dist_commute[of D B])\n  moreover have \"b\\<^sup>2 = n\\<^sup>2 + d\\<^sup>2 + 2 * d * n * cos ?\\<theta>\"\n    unfolding \\<open>b = _\\<close> \\<open>n = _\\<close> \\<open>d = _\\<close>\n    by (simp add: cosine_law_triangle[of A C D] cos dist_commute[of D A] dist_commute[of D C])\n  ultimately have \"b\\<^sup>2 * m + c\\<^sup>2 * n = n * m\\<^sup>2 + n\\<^sup>2 * m + (m + n) * d\\<^sup>2\" by algebra\n  also have \"\\<dots> = (m + n) * (m * n + d\\<^sup>2)\" by algebra\n  also from \\<open>m + n = a\\<close> have \"\\<dots> = a * (d\\<^sup>2 + m * n)\" by simp\n  finally show ?thesis .\nnext\n  assume \"\\<not> (B \\<noteq> D \\<and> C \\<noteq> D)\"\n  from this assms show ?thesis by (auto simp add: dist_commute)\nqed\n\ntext \\<open>\nHere is an equivalent formulation that is probably more suitable for further use\nin other geometry theories in Isabelle.\n\\<close>\n\ntheorem Stewart':\n  fixes A B C D :: \"'a::euclidean_space\"\n  assumes \"between (B, C) D\"\n  shows \"(dist A C)\\<^sup>2 * dist B D + (dist B A)\\<^sup>2 * dist C D = dist B C * ((dist A D)\\<^sup>2 + dist B D * dist C D)\"\nusing assms by (auto intro: Stewart)\n\nsubsection \\<open>Apollonius' Theorem\\<close>\n\ntext \\<open>\nApollonius' theorem is a simple specialisation of Stewart's theorem,\nbut historically predated Stewart's theorem by many centuries.\n\\<close>\n\nlemma Apollonius:\n  fixes A B C :: \"'a::euclidean_space\"\n  assumes \"B \\<noteq> C\"\n  assumes \"b = dist A C\"\n  assumes \"c = dist B A\"\n  assumes \"d = dist A (midpoint B C)\"\n  assumes \"m = dist B (midpoint B C)\"\n  shows \"b\\<^sup>2 + c\\<^sup>2 = 2 * (m\\<^sup>2 + d\\<^sup>2)\"\nproof -\n  from \\<open>B \\<noteq> C\\<close> have \"m \\<noteq> 0\"\n    unfolding \\<open>m = _\\<close> using midpoint_eq_endpoint(1) by fastforce\n  have \"between (B, C) (midpoint B C)\"\n    by (simp add: between_midpoint)\n  moreover have \"dist C (midpoint B C) = dist B (midpoint B C)\"\n    by (simp add: dist_midpoint)\n  moreover have \"dist B C = 2 * dist B (midpoint B C)\"\n    by (simp add: dist_midpoint)\n  moreover note assms(2-5)\n  ultimately have \"b\\<^sup>2 * m + c\\<^sup>2 * m = (2 * m) * (m\\<^sup>2 + d\\<^sup>2)\"\n    by (auto dest!: Stewart[where a=\"2 * m\"] simp add: power2_eq_square)\n  from this have \"m * (b\\<^sup>2 + c\\<^sup>2) = m * (2 * (m\\<^sup>2 + d\\<^sup>2))\"\n    by (simp add: distrib_left semiring_normalization_rules(7))\n  from this \\<open>m \\<noteq> 0\\<close> show ?thesis by auto\nqed\n\ntext \\<open>\nHere is the equivalent formulation that is probably more suitable for further use\nin other geometry theories in Isabelle.\n\\<close>\n\nlemma Apollonius':\n  fixes A B C :: \"'a::euclidean_space\"\n  assumes \"B \\<noteq> C\"\n  shows \"(dist A C)\\<^sup>2 + (dist B A)\\<^sup>2 = 2 * ((dist B (midpoint B C))\\<^sup>2 + (dist A (midpoint B C))\\<^sup>2)\"\nusing assms by (rule Apollonius) 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/Stewart_Apollonius/Stewart_Apollonius.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357666736772, "lm_q2_score": 0.8539127585282744, "lm_q1q2_score": 0.740372903262997}}
{"text": "(*\n  File: Arrays_Ex.thy\n  Author: Bohua Zhan\n*)\n\nsection \\<open>Arrays\\<close>\n\ntheory Arrays_Ex\n  imports \"Auto2_HOL.Auto2_Main\"\nbegin\n\ntext \\<open>Basic examples for arrays.\\<close>\n\nsubsection \\<open>List swap\\<close>\n\ndefinition list_swap :: \"'a list \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> 'a list\" where [rewrite]:\n  \"list_swap xs i j = xs[i := xs ! j, j := xs ! i]\"\nsetup \\<open>register_wellform_data (\"list_swap xs i j\", [\"i < length xs\", \"j < length xs\"])\\<close>\nsetup \\<open>add_prfstep_check_req (\"list_swap xs i j\", \"i < length xs \\<and> j < length xs\")\\<close>\n\nlemma list_swap_eval:\n  \"i < length xs \\<Longrightarrow> j < length xs \\<Longrightarrow>\n   (list_swap xs i j) ! k = (if k = i then xs ! j else if k = j then xs ! i else xs ! k)\" by auto2\nsetup \\<open>add_rewrite_rule_cond @{thm list_swap_eval} [with_cond \"?k \\<noteq> ?i\", with_cond \"?k \\<noteq> ?j\"]\\<close>\n\nlemma list_swap_eval_triv [rewrite]:\n  \"i < length xs \\<Longrightarrow> j < length xs \\<Longrightarrow> (list_swap xs i j) ! i = xs ! j\"\n  \"i < length xs \\<Longrightarrow> j < length xs \\<Longrightarrow> (list_swap xs i j) ! j = xs ! i\" by auto2+\n\nlemma length_list_swap [rewrite_arg]:\n  \"length (list_swap xs i j) = length xs\" by auto2\n\nlemma mset_list_swap [rewrite]:\n  \"i < length xs \\<Longrightarrow> j < length xs \\<Longrightarrow> mset (list_swap xs i j) = mset xs\" by auto2\n\n\n\nsubsection \\<open>Reverse\\<close>\n\nlemma rev_nth [rewrite]:\n  \"n < length xs \\<Longrightarrow> rev xs ! n = xs ! (length xs - 1 - n)\"\n@proof @induct xs @qed\n\nfun rev_swap :: \"'a list \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> 'a list\" where\n  \"rev_swap xs i j = (if i < j then rev_swap (list_swap xs i j) (i + 1) (j - 1) else xs)\"\nsetup \\<open>register_wellform_data (\"rev_swap xs i j\", [\"j < length xs\"])\\<close>\nsetup \\<open>add_prfstep_check_req (\"rev_swap xs i j\", \"j < length xs\")\\<close>\n\nlemma rev_swap_length [rewrite_arg]:\n  \"j < length xs \\<Longrightarrow> length (rev_swap xs i j) = length xs\"\n@proof @fun_induct \"rev_swap xs i j\" @unfold \"rev_swap xs i j\" @qed\n\nlemma rev_swap_eval [rewrite]:\n  \"j < length xs \\<Longrightarrow> (rev_swap xs i j) ! k =\n    (if k < i then xs ! k else if k > j then xs ! k else xs ! (j - (k - i)))\"\n@proof @fun_induct \"rev_swap xs i j\" @unfold \"rev_swap xs i j\"\n  @case \"i < j\" @with\n    @case \"k < i\" @case \"k > j\" @have \"j - (k - i) = j - k + i\"\n  @end\n@qed\n\nlemma rev_swap_is_rev [rewrite]:\n  \"length xs \\<ge> 1 \\<Longrightarrow> rev_swap xs 0 (length xs - 1) = rev xs\" by auto2\n\nsubsection \\<open>Copy one array to the beginning of another\\<close>\n\nfun array_copy :: \"'a list \\<Rightarrow> 'a list \\<Rightarrow> nat \\<Rightarrow> 'a list\" where\n  \"array_copy xs xs' 0 = xs'\"\n| \"array_copy xs xs' (Suc n) = list_update (array_copy xs xs' n) n (xs ! n)\"\nsetup \\<open>fold add_rewrite_rule @{thms array_copy.simps}\\<close>\nsetup \\<open>register_wellform_data (\"array_copy xs xs' n\", [\"n \\<le> length xs\", \"n \\<le> length xs'\"])\\<close>\nsetup \\<open>add_prfstep_check_req (\"array_copy xs xs' n\", \"n \\<le> length xs \\<and> n \\<le> length xs'\")\\<close>\n\nlemma array_copy_length [rewrite_arg]:\n  \"n \\<le> length xs \\<Longrightarrow> n \\<le> length xs' \\<Longrightarrow> length (array_copy xs xs' n) = length xs'\"\n@proof @induct n @qed\n\nlemma array_copy_ind [rewrite]:\n  \"n \\<le> length xs \\<Longrightarrow> n \\<le> length xs' \\<Longrightarrow> k < n \\<Longrightarrow> (array_copy xs xs' n) ! k = xs ! k\"\n@proof @induct n @qed\n\nlemma array_copy_correct [rewrite]:\n  \"n \\<le> length xs \\<Longrightarrow> n \\<le> length xs' \\<Longrightarrow> take n (array_copy xs xs' n) = take n xs\" by auto2\n\nsubsection \\<open>Sublist\\<close>\n\ndefinition sublist :: \"nat \\<Rightarrow> nat \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where [rewrite]:\n  \"sublist l r xs = drop l (take r xs)\"\nsetup \\<open>register_wellform_data (\"sublist l r xs\", [\"l \\<le> r\", \"r \\<le> length xs\"])\\<close>\nsetup \\<open>add_prfstep_check_req (\"sublist l r xs\", \"l \\<le> r \\<and> r \\<le> length xs\")\\<close>\n\nlemma length_sublist [rewrite_arg]:\n  \"r \\<le> length xs \\<Longrightarrow> length (sublist l r xs) = r - l\" by auto2\n\nlemma nth_sublist [rewrite]:\n  \"r \\<le> length xs \\<Longrightarrow> xs' = sublist l r xs \\<Longrightarrow> i < length xs' \\<Longrightarrow> xs' ! i = xs ! (i + l)\" by auto2\n\nlemma sublist_nil [rewrite]:\n  \"r \\<le> length xs \\<Longrightarrow> r \\<le> l \\<Longrightarrow> sublist l r xs = []\" by auto2\n\nlemma sublist_0 [rewrite]:\n  \"sublist 0 l xs = take l xs\" by auto2\n\nlemma sublist_drop [rewrite]:\n  \"sublist l r (drop n xs) = sublist (l + n) (r + n) xs\" by auto2\n\nsetup \\<open>del_prfstep_thm @{thm sublist_def}\\<close>\n\nlemma sublist_single [rewrite]:\n  \"l + 1 \\<le> length xs \\<Longrightarrow> sublist l (l + 1) xs = [xs ! l]\"\n@proof @have \"length [xs ! l] = 1\" @qed\n\nlemma sublist_append [rewrite]:\n  \"l \\<le> m \\<Longrightarrow> m \\<le> r \\<Longrightarrow> r \\<le> length xs \\<Longrightarrow> sublist l m xs @ sublist m r xs = sublist l r xs\"\n@proof\n  @let \"xs1 = sublist l r xs\" \"xs2 = sublist l m xs\" \"xs3 = sublist m r xs\"\n  @have \"length (xs2 @ xs3) = (r - m) + (m - l)\"\n  @have \"\\<forall>i<length xs1. xs1 ! i = (xs2 @ xs3) ! i\" @with\n    @case \"i < length xs2\"\n    @have \"i - length xs2 < length xs3\"\n  @end\n@qed\n\nlemma sublist_Cons [rewrite]:\n  \"r \\<le> length xs \\<Longrightarrow> l < r \\<Longrightarrow> xs ! l # sublist (l + 1) r xs = sublist l r xs\"\n@proof\n  @have \"sublist l r xs = sublist l (l + 1) xs @ sublist (l + 1) r xs\"\n@qed\n\nlemma sublist_equalityI:\n  \"i \\<le> j \\<Longrightarrow> j \\<le> length xs \\<Longrightarrow> length xs = length ys \\<Longrightarrow>\n   \\<forall>k. i \\<le> k \\<longrightarrow> k < j \\<longrightarrow> xs ! k = ys ! k \\<Longrightarrow> sublist i j xs = sublist i j ys\" by auto2\nsetup \\<open>add_backward2_prfstep_cond @{thm sublist_equalityI} [with_filt (order_filter \"xs\" \"ys\")]\\<close>\n\nlemma set_sublist [resolve]:\n  \"j \\<le> length xs \\<Longrightarrow> x \\<in> set (sublist i j xs) \\<Longrightarrow> \\<exists>k. k \\<ge> i \\<and> k < j \\<and> x = xs ! k\"\n@proof\n  @let \"xs' = sublist i j xs\"\n  @obtain l where \"l < length xs'\" \"xs' ! l = x\"\n@qed\n\nlemma list_take_sublist_drop_eq [rewrite]:\n  \"l \\<le> r \\<Longrightarrow> r \\<le> length xs \\<Longrightarrow> take l xs @ sublist l r xs @ drop r xs = xs\"\n@proof\n  @have \"take l xs = sublist 0 l xs\"\n  @have \"drop r xs = sublist r (length xs) xs\"\n@qed\n\nsubsection \\<open>Updating a set of elements in an array\\<close>\n\ndefinition list_update_set :: \"(nat \\<Rightarrow> bool) \\<Rightarrow> (nat \\<Rightarrow> 'a) \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where [rewrite]:\n  \"list_update_set S f xs = list (\\<lambda>i. if S i then f i else xs ! i) (length xs)\"\n\nlemma list_update_set_length [rewrite_arg]:\n  \"length (list_update_set S f xs) = length xs\" by auto2\n\nlemma list_update_set_nth [rewrite]:\n  \"xs' = list_update_set S f xs \\<Longrightarrow> i < length xs' \\<Longrightarrow> xs' ! i = (if S i then f i else xs ! i)\" by auto2\nsetup \\<open>del_prfstep_thm @{thm list_update_set_def}\\<close>\n\nfun list_update_set_impl :: \"(nat \\<Rightarrow> bool) \\<Rightarrow> (nat \\<Rightarrow> 'a) \\<Rightarrow> 'a list \\<Rightarrow> nat \\<Rightarrow> 'a list\" where\n  \"list_update_set_impl S f xs 0 = xs\"\n| \"list_update_set_impl S f xs (Suc k) =\n   (let xs' = list_update_set_impl S f xs k in\n      if S k then xs' [k := f k] else xs')\"\nsetup \\<open>fold add_rewrite_rule @{thms list_update_set_impl.simps}\\<close>\nsetup \\<open>register_wellform_data (\"list_update_set_impl S f xs n\", [\"n \\<le> length xs\"])\\<close>\n\nlemma list_update_set_impl_ind [rewrite]:\n  \"n \\<le> length xs \\<Longrightarrow> list_update_set_impl S f xs n =\n   list (\\<lambda>i. if i < n then if S i then f i else xs ! i else xs ! i) (length xs)\"\n@proof @induct n arbitrary xs @qed\n\nlemma list_update_set_impl_correct [rewrite]:\n  \"list_update_set_impl S f xs (length xs) = list_update_set S f xs\" 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/Arrays_Ex.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8539127492339907, "lm_q2_score": 0.8670357615200474, "lm_q1q2_score": 0.7403728908037704}}
{"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>\\<open>\"BalbesDwinger1974\" and \"Birkhoff1967\" and \"Blyth2005\" and \"Curry1977\" and \"Graetzer1971\" and \"Maddux1996\"\\<close>.\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 order.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 order.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 order.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 order.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.order_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 order.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 order.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\nlemma half_shunting:\n  \"x \\<le> y \\<squnion> z \\<Longrightarrow> x \\<sqinter> -z \\<le> y\"\n  by (metis inf.sup_right_isotone inf_commute inf_sup_distrib1 sup.boundedE maddux_3_12)\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 order.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 order.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 order.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 order.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 order.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 order.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 order.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 order.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": "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/Stone_Algebras/P_Algebras.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8670357598021707, "lm_q2_score": 0.8539127492339909, "lm_q1q2_score": 0.7403728893368537}}
{"text": "theory DInduction\nimports Main BDatatypes\nbegin\n\n(* Section 3.2 *)\n\n(* Rules of thumb (ROT) for generalizing the goal before induction *)\n\n(* Linear-time, tail-recursive version of rev with accumulator *)\nprimrec 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(*\nlemma \"itrev xs [] = rev xs\"\napply (induct_tac xs)\napply simp_all (* Does not include the induction hypothesis *)\n*)\n\n(* ROT: Generalize goals for induction by replacing constants with variables *)\n\n\n(*\nlemma \"itrev xs ys = rev xs @ ys\"\napply (induct_tac xs)\napply simp_all (* Requires specific ys but should be for all ys *)\n*)\n\n(* We're not doing induction on ys, so they should be quantified over. *)\n\n(* ROT: Generalize goals for induction by universally quantifying over all free\n   variables, except the induction variable itself. *)\n\nlemma \"\\<forall>ys. itrev xs ys = rev xs @ ys\"\napply (induct_tac xs)\napply simp_all\ndone\n\n(* ROT: The rhs of an equation should be (in some sense) simpler than the lhs. *)\n\n(* What happens if the lhs is simpler that the rhs? *)\n(*\nlemma \"\\<forall>ys. rev xs @ ys = itrev xs ys\"\napply (induct_tac xs)\napply simp_all\n(* What to do here? *)\n*)\n\n(* Exercise 3.2.1 *)\nprimrec add :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\" where\n\"add m 0       = m\" |\n\"add m (Suc n) = add (Suc m) n\"\n\nlemma \"\\<forall>m. add m n = m + n\"\napply (induct_tac n)\napply simp_all\ndone\n\n(* Exercise 3.2.2 *)\nprimrec flatten\\<^sub>2 :: \"'a tree \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where\n\"flatten\\<^sub>2 Tip           ys = ys\" |\n\"flatten\\<^sub>2 (Node t\\<^sub>1 x t\\<^sub>2) ys = flatten\\<^sub>2 t\\<^sub>1 (x # flatten\\<^sub>2 t\\<^sub>2 ys)\"\n\nlemma \"\\<forall>ys. flatten\\<^sub>2 t ys = flatten t @ ys\"\napply (induct_tac t)\napply simp_all\ndone\n\nend\n", "meta": {"author": "spl", "repo": "isabelle-tutorial", "sha": "56ee8d748d6d639ea7238e5fbb9edce4330637f2", "save_path": "github-repos/isabelle/spl-isabelle-tutorial", "path": "github-repos/isabelle/spl-isabelle-tutorial/isabelle-tutorial-56ee8d748d6d639ea7238e5fbb9edce4330637f2/DInduction.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357494949105, "lm_q2_score": 0.8539127566694178, "lm_q1q2_score": 0.7403728869821338}}
{"text": "theory Exercise5p5\nimports Main\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\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 r n x y \\<Longrightarrow> star r x y\"\nproof (induction rule: iter.induct)\n  case zero\n  fix x\n  show \"star r x x\" by (simp add: star.refl star.step)\nnext\n  case step\n  fix x n y z\n  assume \"r x y\"\n     and \"star r y z\"\n  then show \"star r x z\" by (simp add: star.step)\nqed\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/Exercise5p5.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096204605946, "lm_q2_score": 0.8080672112416737, "lm_q1q2_score": 0.7402781461972608}}
{"text": "(*  Title:      Shattering.thy\n    Author:     Ata Keskin, TU M\u00fcnchen\n*)\n\nsection \\<open>Definitions and lemmas about shattering\\<close>\n\ntext \\<open>In this section, we introduce the predicate @{term \"shatters\"} and the term for the family of sets that a family shatters @{term \"shattered_by\"}.\\<close>\n\ntheory Shattering\n  imports Main\nbegin\n\nsubsection \\<open>Intersection of a family of sets with a set\\<close>\n\nabbreviation IntF :: \"'a set set \\<Rightarrow> 'a set \\<Rightarrow> 'a set set\" (infixl \"\\<inter>*\" 60)\n  where \"F \\<inter>* S \\<equiv> ((\\<inter>) S) ` F\"\n\nlemma idem_IntF:\n  assumes \"\\<Union>A \\<subseteq> Y\"\n  shows \"A \\<inter>* Y = A\"\nproof -\n  from assms have \"A \\<subseteq> A \\<inter>* Y\" by blast\n  thus ?thesis by fastforce\nqed\n\nlemma subset_IntF: \n  assumes \"A \\<subseteq> B\"\n  shows \"A \\<inter>* X \\<subseteq> B \\<inter>* X\"\n  using assms by (rule image_mono)\n\nlemma Int_IntF: \"(A \\<inter>* Y) \\<inter>* X = A \\<inter>* (Y \\<inter> X)\"\nproof\n  show \"A \\<inter>* Y \\<inter>* X \\<subseteq> A \\<inter>* (Y \\<inter> X)\"\n  proof\n    fix S\n    assume \"S \\<in> A \\<inter>* Y \\<inter>* X\"\n    then obtain a_y where A_Y0: \"a_y \\<in> A \\<inter>* Y\" and A_Y1: \"a_y \\<inter> X = S\" by blast\n    from A_Y0 obtain a where A0: \"a \\<in> A\" and A1: \"a \\<inter> Y = a_y\" by blast\n    from A_Y1 A1 have \"a \\<inter> (Y \\<inter> X) = S\" by fast\n    with A0 show \"S \\<in> A \\<inter>* (Y \\<inter> X)\" by blast\n  qed\nnext\n  show \"A \\<inter>* (Y \\<inter> X) \\<subseteq> A \\<inter>* Y \\<inter>* X\"\n  proof\n    fix S\n    assume \"S \\<in> A \\<inter>* (Y \\<inter> X)\"\n    then obtain a where A0: \"a \\<in> A\" and A1: \"a \\<inter> (Y \\<inter> X) = S\" by blast\n    from A0 have \"a \\<inter> Y \\<in> A \\<inter>* Y\" by blast\n    with A1 show \"S \\<in> (A \\<inter>* Y) \\<inter>* X\" by blast\n  qed\nqed\n\ntext \\<open>@{term insert} distributes over @{term IntF}\\<close>\nlemma insert_IntF: \n  shows \"insert x ` (H \\<inter>* S) = (insert x ` H) \\<inter>* (insert x S)\"\nproof\n  show \"insert x ` (H \\<inter>* S) \\<subseteq> (insert x ` H) \\<inter>* (insert x S)\"\n  proof\n    fix y_x\n    assume \"y_x \\<in> insert x ` (H \\<inter>* S)\"\n    then obtain y where 0: \"y \\<in> (H \\<inter>* S)\" and 1: \"y_x = y \\<union> {x}\" by blast\n    from 0 obtain yh where 2: \"yh \\<in> H\" and 3: \"y = yh \\<inter> S\" by blast\n    from 1 3 have \"y_x = (yh \\<union> {x}) \\<inter> (S \\<union> {x})\" by simp\n    with 2 show \"y_x \\<in> (insert x ` H) \\<inter>* (insert x S)\" by blast\n  qed\nnext\n  show \"insert x ` H \\<inter>* (insert x S) \\<subseteq> insert x ` (H \\<inter>* S)\"\n  proof\n    fix y_x\n    assume \"y_x \\<in> insert x ` H \\<inter>* (insert x S)\"\n    then obtain yh_x where 0: \"yh_x \\<in> (\\<lambda>Y. Y \\<union> {x}) ` H\" and 1: \"y_x = yh_x \\<inter> (S \\<union> {x})\" by blast\n    from 0 obtain yh where 2: \"yh \\<in> H\" and 3: \"yh_x = yh \\<union> {x}\" by blast\n    from 1 3 have \"y_x = (yh \\<inter> S) \\<union> {x}\" by simp\n    with 2 show \"y_x \\<in> insert x ` (H \\<inter>* S)\" by blast\n  qed\nqed\n\nsubsection \\<open>Definition of @{term shatters}, @{term VC_dim} and @{term shattered_by}\\<close>\n\nabbreviation shatters :: \"'a set set \\<Rightarrow> 'a set \\<Rightarrow> bool\" (infixl \"shatters\" 70)\n  where \"H shatters A \\<equiv> H \\<inter>* A = Pow A\"\n\ndefinition VC_dim :: \"'a set set \\<Rightarrow> nat\"\n  where \"VC_dim F = Sup {card S | S. F shatters S}\"\n\ndefinition shattered_by :: \"'a set set \\<Rightarrow> 'a set set\"\n  where \"shattered_by F \\<equiv> {A. F shatters A}\"\n\nlemma shattered_by_in_Pow:\n  shows \"shattered_by F \\<subseteq> Pow (\\<Union> F)\"\n  unfolding shattered_by_def by blast\n\nlemma subset_shatters:\n  assumes \"A \\<subseteq> B\" and \"A shatters X\"\n  shows \"B shatters X\"\nproof -\n  from assms(1) have \"A \\<inter>* X \\<subseteq> B \\<inter>* X\" by blast\n  with assms(2) have \"Pow X \\<subseteq> B \\<inter>* X\"  by presburger\n  thus ?thesis by blast\nqed\n\nlemma supset_shatters:\n  assumes \"Y \\<subseteq> X\" and \"A shatters X\"\n  shows \"A shatters Y\"\nproof -\n  have h: \"\\<Union>(Pow Y) \\<subseteq> Y\" by simp\n  from assms have 0: \"Pow Y \\<subseteq> A \\<inter>* X\" by auto\n  from subset_IntF[OF 0, of Y] Int_IntF[of Y X A] idem_IntF[OF h] have \"Pow Y \\<subseteq> A \\<inter>* (X \\<inter> Y)\" by argo\n  with Int_absorb2[OF assms(1)] Int_commute[of X Y] have \"Pow Y \\<subseteq> A \\<inter>* Y\" by presburger\n  then show ?thesis by fast\nqed\n\nlemma shatters_empty:\n  assumes \"F \\<noteq> {}\"\n  shows \"F shatters {}\" \nusing assms by fastforce\n\nlemma subset_shattered_by:\n  assumes \"A \\<subseteq> B\"\n  shows \"shattered_by A \\<subseteq> shattered_by B\" \nunfolding shattered_by_def using subset_shatters[OF assms] by force\n\nlemma finite_shattered_by:\n  assumes \"finite (\\<Union> F)\"\n  shows \"finite (shattered_by F)\"\n  using assms rev_finite_subset[OF _ shattered_by_in_Pow, of F] by fast\n\ntext \\<open>The following example shows that requiring finiteness of a family of sets is not enough, to ensure that @{term \"shattered_by\"} also stays finite.\\<close>\n\nlemma \"\\<exists>F::nat set set. finite F \\<and> infinite (shattered_by F)\"\nproof -           \n  let ?F = \"{odd -` {True}, odd -` {False}}\"\n  have 0: \"finite ?F\" by simp\n\n  let ?f = \"\\<lambda>n::nat. {n}\" \n  let ?N = \"range ?f\"\n  have \"inj (\\<lambda>n. {n})\" by simp\n  with infinite_iff_countable_subset[of ?N] have infinite_N: \"infinite ?N\" by blast\n  have F_shatters_any_singleton: \"?F shatters {n::nat}\" for n\n  proof -\n    have Pow_n: \"Pow {n} = {{n}, {}}\" by blast\n    have 1: \"Pow {n} \\<subseteq> ?F \\<inter>* {n}\" \n    proof (cases \"odd n\")\n      case True\n      from True have \"(odd -` {False}) \\<inter> {n} = {}\" by blast\n      hence 0: \"{} \\<in> ?F \\<inter>* {n}\"  by blast\n      from True have \"(odd -` {True}) \\<inter> {n} = {n}\" by blast\n      hence 1: \"{n} \\<in> ?F \\<inter>* {n}\"  by blast\n      from 0 1 Pow_n show ?thesis by simp\n    next\n      case False\n      from False have \"(odd -` {True}) \\<inter> {n} = {}\" by blast\n      hence 0: \"{} \\<in> ?F \\<inter>* {n}\" by blast\n      from False have \"(odd -` {False}) \\<inter> {n} = {n}\" by blast\n      hence 1: \"{n} \\<in> ?F \\<inter>* {n}\" by blast\n      from 0 1 Pow_n show ?thesis by simp\n    qed\n    thus ?thesis by fastforce\n  qed\n  then have \"?N \\<subseteq> shattered_by ?F\" unfolding shattered_by_def by force\n  from 0 infinite_super[OF this infinite_N] show ?thesis 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/Sauer_Shelah_Lemma/Shattering.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.851952809486198, "lm_q2_score": 0.8688267728417087, "lm_q1q2_score": 0.7401994100793206}}
{"text": "(*  \n    Title:      Gauss_Jordan_IArrays.thy\n    Author:     Jose Divas\u00f3n <jose.divasonm at unirioja.es>\n    Author:     Jes\u00fas Aransay <jesus-maria.aransay at unirioja.es>\n*)\n\nheader{*Gauss Jordan algorithm over nested IArrays*}\n\ntheory Gauss_Jordan_IArrays\nimports\n  Matrix_To_IArray\n  Gauss_Jordan\nbegin\n\nsubsection{*Definitions and functions to compute the Gauss-Jordan algorithm over matrices represented as nested iarrays*}\n\ndefinition \"least_non_zero_position_of_vector_from_index A i = the (List.find (\\<lambda>x. A !! x \\<noteq> 0) [i..<IArray.length A])\"\ndefinition \"least_non_zero_position_of_vector A = least_non_zero_position_of_vector_from_index A 0\"\n\ndefinition vector_all_zero_from_index :: \"(nat \\<times> 'a::{zero} iarray) => bool\"\n  where \"vector_all_zero_from_index A' = (let i=fst A'; A=(snd A') in IArray_Addenda.all (\\<lambda>x. A!!x = 0) (IArray [i..<(IArray.length A)]))\"\n\ndefinition Gauss_Jordan_in_ij_iarrays :: \"'a::{field} iarray iarray => nat => nat => 'a iarray iarray \"\n  where \"Gauss_Jordan_in_ij_iarrays A i j = (let n = least_non_zero_position_of_vector_from_index (column_iarray j A) i;\n  interchange_A = interchange_rows_iarray A i n; \n  A' = mult_row_iarray interchange_A i (1/interchange_A!!i!!j) \n  in IArray.of_fun (\\<lambda>s. if s = i then A' !! s else row_add_iarray A' s i (- interchange_A !! s !! j) !! s) (nrows_iarray A))\"\n\ndefinition Gauss_Jordan_column_k_iarrays :: \"(nat \\<times> 'a::{field} iarray iarray) => nat => (nat \\<times> 'a iarray iarray)\"\n  where \"Gauss_Jordan_column_k_iarrays A' k=(let A=(snd A'); i=(fst A') in \n  if ((vector_all_zero_from_index (i, (column_iarray k A)))) \\<or> i = (nrows_iarray A) then (i,A) else (Suc i, (Gauss_Jordan_in_ij_iarrays A i k)))\"\n\ndefinition Gauss_Jordan_upt_k_iarrays :: \"'a::{field} iarray iarray => nat => 'a::{field} iarray iarray\"\n  where \"Gauss_Jordan_upt_k_iarrays A k = snd (foldl Gauss_Jordan_column_k_iarrays (0,A) [0..<Suc k])\"\n\ndefinition Gauss_Jordan_iarrays :: \"'a::{field} iarray iarray => 'a::{field} iarray iarray\"\n  where \"Gauss_Jordan_iarrays A = Gauss_Jordan_upt_k_iarrays A (ncols_iarray A - 1)\"\n\n\nsubsection{*Proving the equivalence between Gauss-Jordan algorithm over nested iarrays and over nested vecs (abstract matrices).*}\n\nlemma vector_all_zero_from_index_eq:\nfixes A::\"'a::{zero}^'n::{mod_type}\"\nshows \"(\\<forall>m\\<ge>i. A $ m = 0) = (vector_all_zero_from_index (to_nat i, vec_to_iarray A))\"\nproof (auto simp add: vector_all_zero_from_index_def Let_def is_none_def find_None_iff)\n  fix x\n  assume zero: \"\\<forall>m\\<ge>i. A $ m = 0\"\n    and x_length: \"x<length (IArray.list_of (vec_to_iarray A))\" and i_le_x: \"to_nat i \\<le> x\"\n  have x_le_card: \"x < CARD('n)\"  using x_length unfolding vec_to_iarray_def by auto\n  have i_le_from_nat_x: \"i \\<le> from_nat x\"  using from_nat_mono'[OF i_le_x x_le_card] unfolding from_nat_to_nat_id .\n  hence Axk: \"A $ (from_nat x) = 0\" using zero by simp\n  have \"vec_to_iarray A !! x = vec_to_iarray A !! to_nat (from_nat x::'n)\" unfolding to_nat_from_nat_id[OF x_le_card] ..\n  also have \"... = A $ (from_nat x)\" unfolding vec_to_iarray_nth' ..\n  also have \"... = 0\" unfolding Axk ..\n  finally show\" IArray.list_of (vec_to_iarray A) ! x = 0\"\n    unfolding IArray.sub_def .\nnext\n  fix m::'n\n  assume zero_assm: \"\\<forall>x\\<in>{mod_type_class.to_nat i..<length (IArray.list_of (vec_to_iarray A))}. IArray.list_of (vec_to_iarray A) ! x = 0\"\n   and i_le_m: \"i \\<le> m\"\n  have zero: \"\\<forall>x<length (IArray.list_of (vec_to_iarray A)). mod_type_class.to_nat i \\<le> x \\<longrightarrow> IArray.list_of (vec_to_iarray A) ! x = 0\"\n    using zero_assm by auto\n  have to_nat_i_le_m:\"to_nat i \\<le> to_nat m\" using to_nat_mono'[OF i_le_m] .\n  have m_le_length: \"to_nat m < IArray.length (vec_to_iarray A)\" unfolding vec_to_iarray_def using to_nat_less_card by auto\n  have \"A $ m = vec_to_iarray A !! (to_nat m)\" unfolding vec_to_iarray_nth' ..\n  also have \"... = 0\" using zero to_nat_i_le_m m_le_length unfolding nrows_iarray_def by (metis IArray.sub_def length_def)\n  finally show \"A $ m = 0\" .\nqed\n\nlemma matrix_vector_all_zero_from_index:\n  fixes A::\"'a::{zero}^'columns::{mod_type}^'rows::{mod_type}\"\n  shows \"(\\<forall>m\\<ge>i. A $ m $ k = 0) = (vector_all_zero_from_index (to_nat i, vec_to_iarray (column k A)))\"\n  unfolding vector_all_zero_from_index_eq[symmetric] column_def by simp\n\n\nlemma vec_to_iarray_least_non_zero_position_of_vector_from_index:\nfixes A::\"'a::{zero}^'n::{mod_type}\"\nassumes not_all_zero: \"\\<not> (vector_all_zero_from_index (to_nat i,  vec_to_iarray A))\"\nshows \"least_non_zero_position_of_vector_from_index (vec_to_iarray A) (to_nat i) = to_nat (LEAST n. A $ n \\<noteq> 0 \\<and> i \\<le> n)\"\nproof -\n  have \"\\<exists>a. List.find (\\<lambda>x. vec_to_iarray A !! x \\<noteq> 0) [to_nat i..<IArray.length (vec_to_iarray A)] = Some a\"\n    proof (rule ccontr, simp, unfold sub_def[symmetric] length_def[symmetric])\n      assume \"List.find (\\<lambda>x. (vec_to_iarray A) !! x \\<noteq> 0) [to_nat i..<IArray.length (vec_to_iarray A)] = None\"\n      hence \"\\<not> (\\<exists>x. x \\<in> set [mod_type_class.to_nat i..<IArray.length (vec_to_iarray A)] \\<and> vec_to_iarray A !! x \\<noteq> 0)\" \n        unfolding find_None_iff .\n      thus False using not_all_zero unfolding vector_all_zero_from_index_eq[symmetric]\n      by (simp del: length_def sub_def, unfold length_vec_to_iarray, metis to_nat_less_card to_nat_mono' vec_to_iarray_nth')\n     qed\n  from this obtain a where a: \"List.find (\\<lambda>x. vec_to_iarray A !! x \\<noteq> 0) [to_nat i..<IArray.length (vec_to_iarray A)] = Some a\"\n    by blast\n  from this obtain ia where \n    ia_less_length: \"ia<length [to_nat i..<IArray.length (vec_to_iarray A)]\" and\n    not_eq_zero: \"vec_to_iarray A !! ([to_nat i..<IArray.length (vec_to_iarray A)] ! ia) \\<noteq> 0\" and\n    a_eq: \"a = [to_nat i..<IArray.length (vec_to_iarray A)] ! ia\"\n    and least: \"(\\<forall>ja<ia. \\<not> vec_to_iarray A !! ([to_nat i..<IArray.length (vec_to_iarray A)] ! ja) \\<noteq> 0)\" \n    unfolding find_Some_iff by blast  \n  have not_eq_zero': \"vec_to_iarray A !! a \\<noteq> 0\" using not_eq_zero unfolding a_eq .\n  have i_less_a: \"to_nat i \\<le> a\" using  ia_less_length length_upt nth_upt a_eq by auto\n  have a_less_card: \"a<CARD('n)\" using a_eq ia_less_length unfolding vec_to_iarray_def by auto\n  have \"(LEAST n. A $ n \\<noteq> 0 \\<and> i \\<le> n) = from_nat a\"\n  proof (rule Least_equality, rule conjI)\n    show \"A $ from_nat a \\<noteq> 0\"  unfolding vec_to_iarray_nth'[symmetric] using not_eq_zero' unfolding to_nat_from_nat_id[OF a_less_card] .\n    show \"i \\<le> from_nat a\" using a_less_card from_nat_mono' from_nat_to_nat_id i_less_a by fastforce\n    fix x assume \"A $ x  \\<noteq> 0 \\<and> i \\<le> x\" hence Axj: \"A $ x \\<noteq> 0\" and i_le_x: \"i \\<le> x\" by fast+   \n    show \"from_nat a \\<le> x\"\n    proof (rule ccontr)\n      assume \"\\<not> from_nat a \\<le> x\" hence x_less_from_nat_a: \"x < from_nat a\" by simp\n      def ja\\<equiv>\"(to_nat x) - (to_nat i)\"\n      have to_nat_x_less_card: \"to_nat x < CARD ('n)\" using bij_to_nat[where ?'a='n] unfolding bij_betw_def by fastforce\n      hence ja_less_length: \"ja < IArray.length (vec_to_iarray A)\" unfolding ja_def vec_to_iarray_def by auto\n      have \"[to_nat i..<IArray.length (vec_to_iarray A)] ! ja = to_nat i + ja\" \n      by (rule nth_upt, unfold vec_to_iarray_def,auto, metis add_diff_inverse diff_add_zero ja_def not_less_iff_gr_or_eq to_nat_less_card)\n      also have i_plus_ja: \"... = to_nat x\" unfolding ja_def by (simp add: i_le_x to_nat_mono')\n      finally have list_rw: \"[to_nat i..<IArray.length (vec_to_iarray A)] ! ja = to_nat x\" .\n      moreover have \"ja<ia\"\n      proof -\n        have \"a = to_nat i + ia\" unfolding a_eq \n          by (rule nth_upt, metis ia_less_length length_upt less_diff_conv add.commute)\n        thus ?thesis by (metis i_plus_ja add_less_cancel_right add.commute to_nat_le x_less_from_nat_a)\n      qed\n      ultimately have \"vec_to_iarray A !! (to_nat x) = 0\" using least by auto\n      hence \"A $ x = 0\" unfolding vec_to_iarray_nth' .  \n      thus False using Axj by contradiction\n    qed\n  qed\n  hence \"a = to_nat (LEAST n. A $ n \\<noteq> 0 \\<and> i \\<le> n)\" using to_nat_from_nat_id[OF a_less_card] by simp\n  thus ?thesis unfolding least_non_zero_position_of_vector_from_index_def unfolding a by simp\nqed\n\n\ncorollary vec_to_iarray_least_non_zero_position_of_vector_from_index':\nfixes A::\"'a::{zero}^'cols::{mod_type}^'rows::{mod_type}\"\nassumes not_all_zero: \"\\<not> (vector_all_zero_from_index (to_nat i, vec_to_iarray (column j A)))\"\nshows \"least_non_zero_position_of_vector_from_index (vec_to_iarray (column j A)) (to_nat i) = to_nat (LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n)\"\nunfolding vec_to_iarray_least_non_zero_position_of_vector_from_index[OF not_all_zero]\nunfolding column_def by fastforce\n\ncorollary vec_to_iarray_least_non_zero_position_of_vector_from_index'':\nfixes A::\"'a::{zero}^'cols::{mod_type}^'rows::{mod_type}\"\nassumes not_all_zero: \"\\<not> (vector_all_zero_from_index (to_nat j, vec_to_iarray (row i A)))\"\nshows \"least_non_zero_position_of_vector_from_index (vec_to_iarray (row i A)) (to_nat j) = to_nat (LEAST n. A $ i $ n \\<noteq> 0 \\<and> j \\<le> n)\"\nunfolding vec_to_iarray_least_non_zero_position_of_vector_from_index[OF not_all_zero]\nunfolding row_def by fastforce\n\n\nlemma matrix_to_iarray_Gauss_Jordan_in_ij[code_unfold]:\n  fixes A::\"'a::{field}^'columns::{mod_type}^'rows::{mod_type}\"\n  assumes not_all_zero: \"\\<not> (vector_all_zero_from_index (to_nat i, vec_to_iarray (column j A)))\"\n  shows \"matrix_to_iarray (Gauss_Jordan_in_ij A i j) = Gauss_Jordan_in_ij_iarrays (matrix_to_iarray A) (to_nat i) (to_nat j)\"\nproof (unfold Gauss_Jordan_in_ij_def Gauss_Jordan_in_ij_iarrays_def Let_def, rule matrix_to_iarray_eq_of_fun, auto simp del: sub_def length_def)\n  show \"vec_to_iarray (mult_row (interchange_rows A i (LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n)) i (1 / A $ (LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n) $ j) $ i) =\n    mult_row_iarray\n     (interchange_rows_iarray (matrix_to_iarray A) (to_nat i)\n       (least_non_zero_position_of_vector_from_index (column_iarray (to_nat j) (matrix_to_iarray A)) (to_nat i)))\n     (to_nat i) (1 / interchange_rows_iarray (matrix_to_iarray A) (to_nat i)\n           (least_non_zero_position_of_vector_from_index (column_iarray (to_nat j) (matrix_to_iarray A)) (to_nat i)) !! to_nat i !! to_nat j) !! to_nat i\" \n    unfolding vec_to_iarray_column[symmetric]\n    unfolding vec_to_iarray_least_non_zero_position_of_vector_from_index'[OF not_all_zero]\n    unfolding matrix_to_iarray_interchange_rows[symmetric]\n    unfolding matrix_to_iarray_mult_row[symmetric] \n    unfolding matrix_to_iarray_nth\n    unfolding interchange_rows_i\n    unfolding vec_matrix ..\nnext\n  fix ia\n  show \"vec_to_iarray\n          (row_add (mult_row (interchange_rows A i (LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n)) i (1 / A $ (LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n) $ j)) ia i\n            (- interchange_rows A i (LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n) $ ia $ j) $ ia) =\n         row_add_iarray\n          (mult_row_iarray\n            (interchange_rows_iarray (matrix_to_iarray A) (to_nat i)\n              (least_non_zero_position_of_vector_from_index (column_iarray (to_nat j) (matrix_to_iarray A)) (to_nat i)))\n            (to_nat i)\n            (1 / interchange_rows_iarray (matrix_to_iarray A) (to_nat i)\n                  (least_non_zero_position_of_vector_from_index (column_iarray (to_nat j) (matrix_to_iarray A)) (to_nat i)) !!\n                 to_nat i !! to_nat j))\n          (to_nat ia) (to_nat i)\n          (- interchange_rows_iarray (matrix_to_iarray A) (to_nat i)\n              (least_non_zero_position_of_vector_from_index (column_iarray (to_nat j) (matrix_to_iarray A)) (to_nat i)) !!\n             to_nat ia !! to_nat j) !! to_nat ia\"\n    unfolding vec_to_iarray_column[symmetric]\n    unfolding vec_to_iarray_least_non_zero_position_of_vector_from_index'[OF not_all_zero]\n    unfolding matrix_to_iarray_interchange_rows[symmetric]\n    unfolding matrix_to_iarray_mult_row[symmetric]\n    unfolding matrix_to_iarray_nth\n    unfolding interchange_rows_i\n    unfolding matrix_to_iarray_row_add[symmetric]\n    unfolding vec_matrix ..\nnext\n  show \"nrows_iarray (matrix_to_iarray A) =\n    IArray.length (matrix_to_iarray\n    (\\<chi> s. if s = i then 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) $ s\n    else row_add (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)) s i\n    (- interchange_rows A i (LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n) $ s $ j) $ s))\" \n    unfolding length_eq_card_rows nrows_eq_card_rows ..\nqed\n\n\n\nlemma matrix_to_iarray_Gauss_Jordan_column_k_1:\n  fixes A::\"'a::{field}^'columns::{mod_type}^'rows::{mod_type}\"\n  assumes k: \"k<ncols A\"\n  and i: \"i\\<le>nrows A\"\n  shows \"(fst (Gauss_Jordan_column_k (i, A) k)) = fst (Gauss_Jordan_column_k_iarrays (i, matrix_to_iarray A) k)\"\nproof (cases \"i<nrows A\")\n  case True\n  show ?thesis\n    unfolding Gauss_Jordan_column_k_def Let_def Gauss_Jordan_column_k_iarrays_def fst_conv snd_conv\n    unfolding vec_to_iarray_column[of \"from_nat k\" A, unfolded to_nat_from_nat_id[OF k[unfolded ncols_def]], symmetric]\n    using matrix_vector_all_zero_from_index[symmetric, of \"from_nat i::'rows\" \"from_nat k::'columns\"]\n    unfolding to_nat_from_nat_id[OF True[unfolded nrows_def]] to_nat_from_nat_id[OF k[unfolded ncols_def]]\n    using matrix_to_iarray_Gauss_Jordan_in_ij    \n    unfolding matrix_to_iarray_nrows snd_conv by auto\nnext\n  case False\n  have \"vector_all_zero_from_index (nrows A, column_iarray k (matrix_to_iarray A))\" unfolding vector_all_zero_from_index_def unfolding Let_def  snd_conv fst_conv\n  unfolding nrows_def column_iarray_def\n  unfolding length_eq_card_rows by (simp add: is_none_code(1))\n  thus ?thesis\n    using i False\n    unfolding Gauss_Jordan_column_k_iarrays_def Gauss_Jordan_column_k_def Let_def by auto\nqed\n\nlemma matrix_to_iarray_Gauss_Jordan_column_k_2:\n  fixes A::\"'a::{field}^'columns::{mod_type}^'rows::{mod_type}\"\n  assumes k: \"k<ncols A\"\n  and i: \"i\\<le>nrows A\"\n  shows \"matrix_to_iarray (snd (Gauss_Jordan_column_k (i, A) k)) = snd (Gauss_Jordan_column_k_iarrays (i, matrix_to_iarray A) k)\"\nproof (cases \"i<nrows A\")\n  case True show ?thesis\n    unfolding Gauss_Jordan_column_k_def Let_def Gauss_Jordan_column_k_iarrays_def fst_conv snd_conv\n    unfolding vec_to_iarray_column[of \"from_nat k\" A, unfolded to_nat_from_nat_id[OF k[unfolded ncols_def]], symmetric]\n    unfolding matrix_vector_all_zero_from_index[symmetric, of \"from_nat i::'rows\" \"from_nat k::'columns\", symmetric]\n    using matrix_to_iarray_Gauss_Jordan_in_ij[of \"from_nat i::'rows\" \"from_nat k::'columns\"]    \n    unfolding to_nat_from_nat_id[OF True[unfolded nrows_def]] to_nat_from_nat_id[OF k[unfolded ncols_def]]\n    unfolding matrix_to_iarray_nrows by auto\nnext\n  case False show ?thesis\n    using assms False unfolding Gauss_Jordan_column_k_def Let_def Gauss_Jordan_column_k_iarrays_def\n    by (auto simp add: matrix_to_iarray_nrows)  \nqed\n\n\ntext{*Due to the assumptions presented in @{thm \"matrix_to_iarray_Gauss_Jordan_column_k_2\"}, the following lemma must have three shows.\nThe proof style is similar to @{thm \"rref_and_index_Gauss_Jordan_upt_k\"}.*}\n\nlemma foldl_Gauss_Jordan_column_k_eq:\n  fixes A::\"'a::{field}^'columns::{mod_type}^'rows::{mod_type}\"\n  assumes k: \"k<ncols A\"\n  shows matrix_to_iarray_Gauss_Jordan_upt_k[code_unfold]: \"matrix_to_iarray (Gauss_Jordan_upt_k A k) = Gauss_Jordan_upt_k_iarrays (matrix_to_iarray A) k\"\n  and fst_foldl_Gauss_Jordan_column_k_eq: \"fst (foldl Gauss_Jordan_column_k_iarrays (0, matrix_to_iarray A) [0..<Suc k]) = fst (foldl Gauss_Jordan_column_k (0, A) [0..<Suc k])\"\n  and fst_foldl_Gauss_Jordan_column_k_less: \"fst (foldl Gauss_Jordan_column_k (0, A) [0..<Suc k]) \\<le> nrows A\"\n  using assms\nproof (induct k)\n  show \"matrix_to_iarray (Gauss_Jordan_upt_k A 0) = Gauss_Jordan_upt_k_iarrays (matrix_to_iarray A) 0\"\n    unfolding Gauss_Jordan_upt_k_def Gauss_Jordan_upt_k_iarrays_def  by (auto, metis k le0 less_nat_zero_code matrix_to_iarray_Gauss_Jordan_column_k_2 neq0_conv) \n  show \"fst (foldl Gauss_Jordan_column_k_iarrays (0, matrix_to_iarray A) [0..<Suc 0]) = fst (foldl Gauss_Jordan_column_k (0, A) [0..<Suc 0])\"\n    unfolding Gauss_Jordan_upt_k_def Gauss_Jordan_upt_k_iarrays_def by (auto, metis gr_implies_not0 k le0 matrix_to_iarray_Gauss_Jordan_column_k_1 neq0_conv) \n  show \"fst (foldl Gauss_Jordan_column_k (0, A) [0..<Suc 0]) \\<le> nrows A\" unfolding Gauss_Jordan_upt_k_def by (simp add: Gauss_Jordan_column_k_def Let_def size1 nrows_def)\nnext\n  fix k\n  assume \"(k < ncols A \\<Longrightarrow> matrix_to_iarray (Gauss_Jordan_upt_k A k) = Gauss_Jordan_upt_k_iarrays (matrix_to_iarray A) k)\" and\n    \"(k < ncols A \\<Longrightarrow> fst (foldl Gauss_Jordan_column_k_iarrays (0, matrix_to_iarray A) [0..<Suc k]) = fst (foldl Gauss_Jordan_column_k (0, A) [0..<Suc k]))\"\n    and \"(k < ncols A \\<Longrightarrow> fst (foldl Gauss_Jordan_column_k (0, A) [0..<Suc k]) \\<le> nrows A)\"\n    and Suc_k_less_card: \"Suc k < ncols A\"\n  hence hyp1: \"matrix_to_iarray (Gauss_Jordan_upt_k A k) = Gauss_Jordan_upt_k_iarrays (matrix_to_iarray A) k\"\n    and hyp2: \"fst (foldl Gauss_Jordan_column_k_iarrays (0, matrix_to_iarray A) [0..<Suc k]) = fst (foldl Gauss_Jordan_column_k (0, A) [0..<Suc k])\"\n    and hyp3: \"fst (foldl Gauss_Jordan_column_k (0, A) [0..<Suc k]) \\<le> nrows A\"\n    by auto\n  hence hyp1_unfolded: \"matrix_to_iarray (snd (foldl Gauss_Jordan_column_k (0, A) [0..<Suc k])) = snd (foldl Gauss_Jordan_column_k_iarrays (0, matrix_to_iarray A) [0..<Suc k])\" \n    using hyp1 unfolding Gauss_Jordan_upt_k_def Gauss_Jordan_upt_k_iarrays_def by simp\n  have upt_rw: \"[0..<Suc (Suc k)] = [0..<Suc k] @ [(Suc k)]\" by auto\n  have fold_rw: \"(foldl Gauss_Jordan_column_k_iarrays (0, matrix_to_iarray A) [0..<Suc k]) \n    = (fst (foldl Gauss_Jordan_column_k_iarrays (0, matrix_to_iarray A) [0..<Suc k]), snd (foldl Gauss_Jordan_column_k_iarrays (0, matrix_to_iarray A) [0..<Suc k]))\"\n    by simp\n  have fold_rw': \"(foldl Gauss_Jordan_column_k (0, A) [0..<(Suc k)]) \n    = (fst (foldl Gauss_Jordan_column_k (0, A) [0..<(Suc k)]), snd (foldl Gauss_Jordan_column_k (0, A) [0..<(Suc k)]))\" by simp\n  show \"fst (foldl Gauss_Jordan_column_k_iarrays (0, matrix_to_iarray A) [0..<Suc (Suc k)]) = fst (foldl Gauss_Jordan_column_k (0, A) [0..<Suc (Suc k)])\"\n    unfolding upt_rw foldl_append unfolding List.foldl.simps apply (subst fold_rw) apply (subst fold_rw') unfolding hyp2 unfolding hyp1_unfolded[symmetric]\n  proof (rule matrix_to_iarray_Gauss_Jordan_column_k_1[symmetric, of \"Suc k\" \"(snd (foldl Gauss_Jordan_column_k (0, A) [0..<Suc k]))\"])\n    show \"Suc k < ncols (snd (foldl Gauss_Jordan_column_k (0, A) [0..<Suc k]))\"  using Suc_k_less_card unfolding ncols_def .\n    show \" fst (foldl Gauss_Jordan_column_k (0, A) [0..<Suc k]) \\<le> nrows (snd (foldl Gauss_Jordan_column_k (0, A) [0..<Suc k]))\" using hyp3 unfolding nrows_def .\n  qed\n  show \"matrix_to_iarray (Gauss_Jordan_upt_k A (Suc k)) = Gauss_Jordan_upt_k_iarrays (matrix_to_iarray A) (Suc k)\"\n    unfolding Gauss_Jordan_upt_k_def Gauss_Jordan_upt_k_iarrays_def  upt_rw foldl_append  List.foldl.simps\n    apply (subst fold_rw) apply (subst fold_rw') unfolding hyp2 hyp1_unfolded[symmetric]\n  proof (rule matrix_to_iarray_Gauss_Jordan_column_k_2, unfold ncols_def nrows_def)\n    show \"Suc k < CARD('columns)\" using Suc_k_less_card unfolding ncols_def .\n    show \"fst (foldl Gauss_Jordan_column_k (0, A) [0..<Suc k]) \\<le> CARD('rows)\" using hyp3 unfolding nrows_def .\n  qed\n  show \"fst (foldl Gauss_Jordan_column_k (0, A) [0..<Suc (Suc k)]) \\<le> nrows A\"\n    unfolding upt_rw foldl_append unfolding List.foldl.simps apply (subst fold_rw')\n    unfolding Gauss_Jordan_column_k_def Let_def\n    using hyp3 le_antisym not_less_eq_eq unfolding nrows_def by fastforce\nqed\n\n\n\nlemma matrix_to_iarray_Gauss_Jordan[code_unfold]:\n  fixes A::\"'a::{field}^'columns::{mod_type}^'rows::{mod_type}\"\n  shows \"matrix_to_iarray (Gauss_Jordan A) = Gauss_Jordan_iarrays (matrix_to_iarray A)\"\n  unfolding Gauss_Jordan_iarrays_def ncols_iarray_def unfolding length_eq_card_columns\n  by (auto simp add: Gauss_Jordan_def matrix_to_iarray_Gauss_Jordan_upt_k ncols_def)\n\n\n\nsubsection{*Implementation over IArrays of the computation of the @{term \"rank\"} of a matrix*}\n\ndefinition rank_iarray :: \"'a::{field} iarray iarray => nat\"\n  where \"rank_iarray A = (let A' = (Gauss_Jordan_iarrays A); nrows = (IArray.length A') in card {i. i<nrows \\<and> \\<not> is_zero_iarray (A' !! i)})\"\n\nsubsubsection{*Proving the equivalence between @{term \"rank\"} and @{term \"rank_iarray\"}.*}\n\ntext{*First of all, some code equations are removed to allow the execution of Gauss-Jordan algorithm using iarrays*}\nlemmas card'_code(2)[code del]\nlemmas rank_Gauss_Jordan_code[code del]\n\n\nlemma rank_eq_card_iarrays:\n  fixes A::\"'a::{field}^'columns::{mod_type}^'rows::{mod_type}\"\n  shows \"rank A = card {vec_to_iarray (row i (Gauss_Jordan A)) |i. \\<not> is_zero_iarray (vec_to_iarray (row i (Gauss_Jordan A)))}\"\nproof (unfold rank_Gauss_Jordan_eq Let_def, rule bij_betw_same_card[of \"vec_to_iarray\"], auto simp add: bij_betw_def)\n  show \"inj_on vec_to_iarray {row i (Gauss_Jordan A) |i. row i (Gauss_Jordan A) \\<noteq> 0}\" using inj_vec_to_iarray unfolding inj_on_def by blast\n  fix i assume r: \"row i (Gauss_Jordan A) \\<noteq> 0\"\n  show \"\\<exists>ia. vec_to_iarray (row i (Gauss_Jordan A)) = vec_to_iarray (row ia (Gauss_Jordan A)) \\<and> \\<not> is_zero_iarray (vec_to_iarray (row ia (Gauss_Jordan A)))\"\n  proof (rule exI[of _ i], simp)\n    show \"\\<not> is_zero_iarray (vec_to_iarray (row i (Gauss_Jordan A)))\" using r unfolding is_zero_iarray_eq_iff .\n  qed\nnext\n  fix i\n  assume not_zero_iarray: \"\\<not> is_zero_iarray (vec_to_iarray (row i (Gauss_Jordan A)))\"\n  show \"vec_to_iarray (row i (Gauss_Jordan A)) \\<in> vec_to_iarray ` {row i (Gauss_Jordan A) |i. row i (Gauss_Jordan A) \\<noteq> 0}\"\n    by (rule imageI, auto simp add: not_zero_iarray  is_zero_iarray_eq_iff)\nqed\n\n\nlemma rank_eq_card_iarrays':\n  fixes A::\"'a::{field}^'columns::{mod_type}^'rows::{mod_type}\"\n  shows \"rank A = (let A' = (Gauss_Jordan_iarrays (matrix_to_iarray A)) in card {row_iarray (to_nat i) A' |i::'rows. \\<not> is_zero_iarray (A' !! (to_nat i))})\"\n  unfolding Let_def unfolding rank_eq_card_iarrays vec_to_iarray_row'  matrix_to_iarray_Gauss_Jordan row_iarray_def ..\n\nlemma rank_eq_card_iarrays_code:\n  fixes A::\"'a::{field}^'columns::{mod_type}^'rows::{mod_type}\"\n  shows \"rank A = (let A' = (Gauss_Jordan_iarrays (matrix_to_iarray A)) in card {i::'rows. \\<not> is_zero_iarray (A' !! (to_nat i))})\" \nproof (unfold rank_eq_card_iarrays' Let_def, rule bij_betw_same_card[symmetric, of \"\\<lambda>i. row_iarray (to_nat i) (Gauss_Jordan_iarrays (matrix_to_iarray A))\"],\n    unfold bij_betw_def inj_on_def, auto, unfold sub_def[symmetric]) \n  fix x y::'rows\n  assume x: \"\\<not> is_zero_iarray (Gauss_Jordan_iarrays (matrix_to_iarray A) !! to_nat x)\"\n    and y: \"\\<not> is_zero_iarray (Gauss_Jordan_iarrays (matrix_to_iarray A) !! to_nat y)\"\n    and eq: \"row_iarray (to_nat x) (Gauss_Jordan_iarrays (matrix_to_iarray A)) = row_iarray (to_nat y) (Gauss_Jordan_iarrays (matrix_to_iarray A))\"\n  have eq': \"(Gauss_Jordan A) $ x = (Gauss_Jordan A) $ y\" by (metis eq matrix_to_iarray_Gauss_Jordan row_iarray_def vec_matrix vec_to_iarray_morph)\n  hence not_zero_x: \"\\<not> is_zero_row x (Gauss_Jordan A)\" and not_zero_y: \"\\<not> is_zero_row y (Gauss_Jordan A)\"\n    by (metis  is_zero_iarray_eq_iff is_zero_row_def' matrix_to_iarray_Gauss_Jordan vec_eq_iff vec_matrix x zero_index)+\n  hence x_in: \"row x (Gauss_Jordan A) \\<in> {row i (Gauss_Jordan A) |i::'rows. row i (Gauss_Jordan A) \\<noteq> 0}\"\n    and y_in: \"row y (Gauss_Jordan A) \\<in> {row i (Gauss_Jordan A) |i::'rows. row i (Gauss_Jordan A) \\<noteq> 0}\"\n    by (metis (lifting, mono_tags) is_zero_iarray_eq_iff matrix_to_iarray_Gauss_Jordan mem_Collect_eq vec_to_iarray_row' x y)+\n  show \"x = y\" using inj_index_independent_rows[OF _ x_in eq'] rref_Gauss_Jordan by fast\nqed\n\nsubsubsection{*Code equations for computing the rank over nested iarrays and the dimensions of the elementary subspaces*}\n\nlemma rank_iarrays_code[code]:\n  \"rank_iarray A = length (filter (\\<lambda>x. \\<not> is_zero_iarray x) (IArray.list_of (Gauss_Jordan_iarrays A)))\"\nproof -\n  obtain xs where A_eq_xs: \"(Gauss_Jordan_iarrays A) = IArray xs\" by (metis iarray.exhaust)\n  have \"rank_iarray A = card {i. i<(IArray.length (Gauss_Jordan_iarrays A)) \\<and> \\<not> is_zero_iarray ((Gauss_Jordan_iarrays A) !! i)}\" unfolding rank_iarray_def Let_def ..\n  also have \"... = length (filter (\\<lambda>x. \\<not> is_zero_iarray x) (IArray.list_of (Gauss_Jordan_iarrays A)))\"\n    unfolding A_eq_xs using length_filter_conv_card[symmetric] by force\n  finally show ?thesis .\nqed\n\nlemma matrix_to_iarray_rank[code_unfold]:\n  shows \"rank A = rank_iarray (matrix_to_iarray A)\"\n  unfolding rank_eq_card_iarrays_code rank_iarray_def Let_def\n  apply (rule bij_betw_same_card[of \"to_nat\"])\n  unfolding bij_betw_def\n  apply auto\n  unfolding length_def[symmetric] sub_def[symmetric] apply (metis inj_onI to_nat_eq)\n  unfolding  matrix_to_iarray_Gauss_Jordan[symmetric] length_eq_card_rows\n  using bij_to_nat[where ?'a='c] unfolding bij_betw_def by auto\n\nlemma dim_null_space_iarray[code_unfold]:\n  fixes A::\"'a::{field}^'columns::{mod_type}^'rows::{mod_type}\"\n  shows \"vec.dim (null_space A) = ncols_iarray (matrix_to_iarray A) - rank_iarray (matrix_to_iarray A)\"\n  unfolding dim_null_space ncols_eq_card_columns matrix_to_iarray_rank dimension_vector by simp\n\nlemma dim_col_space_iarray[code_unfold]:\n  fixes A::\"'a::{field}^'columns::{mod_type}^'rows::{mod_type}\"\n  shows \"vec.dim (col_space A) = rank_iarray (matrix_to_iarray A)\"\n  unfolding rank_eq_dim_col_space[of A, symmetric]  matrix_to_iarray_rank ..\n\nlemma dim_row_space_iarray[code_unfold]:\n  fixes A::\"'a::{field}^'columns::{mod_type}^'rows::{mod_type}\"\n  shows \"vec.dim (row_space A) = rank_iarray (matrix_to_iarray A)\" \n  unfolding row_rank_def[symmetric] rank_def[symmetric] matrix_to_iarray_rank ..\n\nlemma dim_left_null_space_space_iarray[code_unfold]:\n  fixes A::\"'a::{field}^'columns::{mod_type}^'rows::{mod_type}\"\n  shows \"vec.dim (left_null_space A) = nrows_iarray (matrix_to_iarray A) - rank_iarray (matrix_to_iarray A)\"\n  unfolding dim_left_null_space nrows_eq_card_rows matrix_to_iarray_rank dimension_vector 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/Gauss_Jordan/Gauss_Jordan_IArrays.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8976953030553434, "lm_q2_score": 0.824461932846258, "lm_q1q2_score": 0.7401156046640157}}
{"text": "(*  Title:      RSAPSS/Productdivides.thy\n    Author:     Christina Lindenberg, Kai Wirt, Technische Universit\u00e4t Darmstadt\n    Copyright:  2005 - Technische Universit\u00e4t Darmstadt \n*)\n\nsection \"Lemmata for modular arithmetic with primes\"\n\ntheory Productdivides\nimports Pdifference\nbegin\n\nlemma productdivides: \"\\<lbrakk>x mod a = (0::nat); x mod b = 0; prime a; prime b; a \\<noteq> b\\<rbrakk> \\<Longrightarrow> x mod (a*b) = 0\"\n  by (simp add: mod_eq_0_iff_dvd primes_coprime divides_mult)\n\nlemma specializedtoprimes1: \n  fixes p::nat \n  shows \"\\<lbrakk>prime p; prime q; p \\<noteq> q; a mod p = b mod p ; a mod q = b mod q\\<rbrakk>\n         \\<Longrightarrow> a mod (p*q) = b mod (p*q)\"\nby (metis equalmodstrick1 equalmodstrick2 productdivides) \n\nlemma specializedtoprimes1a:\n  fixes p::nat \n  shows \"\\<lbrakk>prime p; prime q; p \\<noteq> q; a mod p = b mod p; a mod q = b mod q; b < p*q \\<rbrakk>\n    \\<Longrightarrow> a mod (p*q) = b\"\n  by (simp add: specializedtoprimes1)\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/RSAPSS/Productdivides.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952811593495, "lm_q2_score": 0.824461932846258, "lm_q1q2_score": 0.7401155866116023}}
{"text": "theory locales imports Main\nbegin\n\nlocale partial_order = \n    fixes le:: \"'a \\<Rightarrow> 'a \\<Rightarrow> bool\" (infixl \"\\<sqsubseteq>\" 50)\n    assumes refl [intro, simp]: \"x\\<sqsubseteq>x\"\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\"\n\nprint_locale! partial_order\n\nthm partial_order_def\n\nprint_statement partial_order.trans\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\n\nprint_statement partial_order.less_def\n\ncontext partial_order\nbegin\n\n  definition\n  is_inf where \"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\n  definition\n  is_sup where \"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\n  theorem is_inf_uniq: \"\\<lbrakk>is_inf x y i; is_inf x y i'\\<rbrakk> \\<Longrightarrow> i=i'\"\n  by (simp add: anti_sym is_inf_def)\n\n  theorem is_sup_uniq: \"\\<lbrakk>is_sup x y s; is_sup x y s'\\<rbrakk> \\<Longrightarrow> s=s'\"\n  by (simp add: anti_sym is_sup_def)\n\nend\n\nlocale lattice = partial_order +\n  assumes ex_inf: \"\\<exists> inf. is_inf x y inf\"\n      and ex_sup: \"\\<exists> sup. is_sup x y sup\"\nbegin\n  definition\n  meet (infixl \"\\<sqinter>\" 70) where \"x\\<sqinter>y = (THE inf. is_inf x y inf)\"\n\n  definition\n  join (infixl \"\\<squnion>\" 65) where \"x\\<squnion>y = (THE sup. is_sup x y sup)\"\n\n  lemma meet_left: \"x\\<sqinter>y\\<sqsubseteq>x\"\n  by (metis is_inf_def is_inf_uniq lattice.ex_inf local.lattice_axioms meet_def the_equality)\n\n  lemma join_right: \"x\\<sqsubseteq>(x\\<squnion>y)\"\n  by (metis ex_sup is_sup_def is_sup_uniq join_def the_equality)\n\nend\n\nlocale total_order = partial_order +\n  assumes total: \"x\\<sqsubseteq>y \\<or> y\\<sqsubseteq>x\"\n\nlemma (in total_order) less_order: \"x\\<sqsubset>y \\<or> y\\<sqsubset>x \\<or> x=y\"\n  using less_def total by auto\n\nlocale distrib_lattice = lattice +\n  assumes meet_distr: \"x\\<sqinter>(y\\<squnion>z) = (x\\<sqinter>y)\\<squnion>(x\\<sqinter>z)\"\n\nlemma (in distrib_lattice) join_distr: \"x\\<squnion>(y\\<sqinter>z) = (x\\<squnion>y) \\<sqinter> (x\\<squnion>z)\"\nsorry\n\nsublocale total_order \\<subseteq> lattice\nproof unfold_locales\nfix x y\nfrom total have \"is_inf x y (if x\\<sqsubseteq>y then x else y)\" by (auto simp: is_inf_def)\nthen show \"\\<exists> inf. is_inf x y inf\" ..\nfrom total have \"is_sup x y (if x\\<sqsubseteq>y then y else x)\" by (auto simp: is_sup_def)\nthen show \"\\<exists> sup. is_sup x y sup\" ..\nqed\n\nsublocale total_order \\<subseteq> distrib_lattice\nsorry\n\ninterpretation int:partial_order \"op\\<le> :: int \\<Rightarrow> int \\<Rightarrow> bool\"\nrewrites \"int.less x y = (x < y)\"\nproof -\nshow \"partial_order (op \\<le> :: int \\<Rightarrow> int \\<Rightarrow> bool)\" by unfold_locales auto\nthen\nshow \"partial_order.less op \\<le> x y = (x < y)\"\nunfolding partial_order.less_def [OF \\<open>partial_order op\\<le>\\<close>] by auto\nqed\n\ninterpretation int:partial_order \"op\\<le> ::[int, int] \\<Rightarrow> bool\"\nrewrites \"int.less x y = (x < y)\"\nproof -\nshow \"partial_order (op \\<le> :: int \\<Rightarrow> int \\<Rightarrow> bool)\"\nby unfold_locales auto\nthen interpret int:partial_order \"op\\<le> :: [int, int] \\<Rightarrow> bool\" .\nshow \"int.less x y = (x < y)\"\nunfolding int.less_def by auto\nqed\n\ninterpretation int:lattice \"op\\<le> ::int \\<Rightarrow> int \\<Rightarrow> bool\"\n rewrites int_min_eq: \"int.meet x y = min x y\" and int_max_eq: \"int.join x y = max x y\"\nproof -\nshow \"lattice (op \\<le> :: int \\<Rightarrow> int \\<Rightarrow> bool)\"\napply unfold_locales\napply (unfold int.is_inf_def int.is_sup_def)\nby arith+\nthen interpret int: lattice \"op\\<le> :: int \\<Rightarrow> int \\<Rightarrow> bool\" .\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\ninterpretation int: total_order \"op\\<le> :: int \\<Rightarrow> int \\<Rightarrow> bool\"\nby unfold_locales arith\n\nprint_interps partial_order\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/locales.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467738423873, "lm_q2_score": 0.8418256551882382, "lm_q1q2_score": 0.7400883088964935}}
{"text": "(*  Title:      HOL/Isar_Examples/Cantor.thy\n    Author:     Makarius\n*)\n\nsection \\<open>Cantor's Theorem\\<close>\n\ntheory Cantor\n  imports Main\nbegin\n\nsubsection \\<open>Mathematical statement and proof\\<close>\n\ntext \\<open>\n  Cantor's Theorem states that there is no surjection from\n  a set to its powerset.  The proof works by diagonalization.  E.g.\\ see\n  \\<^item> \\<^url>\\<open>http://mathworld.wolfram.com/CantorDiagonalMethod.html\\<close>\n  \\<^item> \\<^url>\\<open>https://en.wikipedia.org/wiki/Cantor's_diagonal_argument\\<close>\n\\<close>\n\ntheorem Cantor: \"\\<nexists>f :: 'a \\<Rightarrow> 'a set. \\<forall>A. \\<exists>x. A = f x\"\nproof\n  assume \"\\<exists>f :: 'a \\<Rightarrow> 'a set. \\<forall>A. \\<exists>x. A = f x\"\n  then obtain f :: \"'a \\<Rightarrow> 'a set\" where *: \"\\<forall>A. \\<exists>x. A = f x\" ..\n  let ?D = \"{x. x \\<notin> f x}\"\n  from * obtain a where \"?D = f a\" by blast\n  moreover have \"a \\<in> ?D \\<longleftrightarrow> a \\<notin> f a\" by blast\n  ultimately show False by blast\nqed\n\n\nsubsection \\<open>Automated proofs\\<close>\n\ntext \\<open>\n  These automated proofs are much shorter, but lack information why and how it\n  works.\n\\<close>\n\ntheorem \"\\<nexists>f :: 'a \\<Rightarrow> 'a set. \\<forall>A. \\<exists>x. f x = A\"\n  by best\n\ntheorem \"\\<nexists>f :: 'a \\<Rightarrow> 'a set. \\<forall>A. \\<exists>x. f x = A\"\n  by force\n\n\nsubsection \\<open>Elementary version in higher-order predicate logic\\<close>\n\ntext \\<open>\n  The subsequent formulation bypasses set notation of HOL; it uses elementary\n  \\<open>\\<lambda>\\<close>-calculus and predicate logic, with standard introduction and elimination\n  rules. This also shows that the proof does not require classical reasoning.\n\\<close>\n\nlemma iff_contradiction:\n  assumes *: \"\\<not> A \\<longleftrightarrow> A\"\n  shows False\nproof (rule notE)\n  show \"\\<not> A\"\n  proof\n    assume A\n    with * have \"\\<not> A\" ..\n    from this and \\<open>A\\<close> show False ..\n  qed\n  with * show A ..\nqed\n\ntheorem Cantor': \"\\<nexists>f :: 'a \\<Rightarrow> 'a \\<Rightarrow> bool. \\<forall>A. \\<exists>x. A = f x\"\nproof\n  assume \"\\<exists>f :: 'a \\<Rightarrow> 'a \\<Rightarrow> bool. \\<forall>A. \\<exists>x. A = f x\"\n  then obtain f :: \"'a \\<Rightarrow> 'a \\<Rightarrow> bool\" where *: \"\\<forall>A. \\<exists>x. A = f x\" ..\n  let ?D = \"\\<lambda>x. \\<not> f x x\"\n  from * have \"\\<exists>x. ?D = f x\" ..\n  then obtain a where \"?D = f a\" ..\n  then have \"?D a \\<longleftrightarrow> f a a\" by (rule arg_cong)\n  then have \"\\<not> f a a \\<longleftrightarrow> f a a\" .\n  then show False by (rule iff_contradiction)\nqed\n\n\nsubsection \\<open>Classic Isabelle/HOL example\\<close>\n\ntext \\<open>\n  The following treatment of Cantor's Theorem follows the classic example from\n  the early 1990s, e.g.\\ see the file @{verbatim \"92/HOL/ex/set.ML\"} in\n  Isabelle92 or @{cite \\<open>\\S18.7\\<close> \"paulson-isa-book\"}. The old tactic scripts\n  synthesize key information of the proof by refinement of schematic goal\n  states. In contrast, the Isar proof needs to say explicitly what is proven.\n\n  \\<^bigskip>\n  Cantor's Theorem states that every set has more subsets than it has\n  elements. It has become a favourite basic example in pure higher-order logic\n  since it is so easily expressed:\n\n  @{text [display]\n  \\<open>\\<forall>f::\\<alpha> \\<Rightarrow> \\<alpha> \\<Rightarrow> bool. \\<exists>S::\\<alpha> \\<Rightarrow> bool. \\<forall>x::\\<alpha>. f x \\<noteq> S\\<close>}\n\n  Viewing types as sets, \\<open>\\<alpha> \\<Rightarrow> bool\\<close> represents the powerset of \\<open>\\<alpha>\\<close>. This\n  version of the theorem states that for every function from \\<open>\\<alpha>\\<close> to its\n  powerset, some subset is outside its range. The Isabelle/Isar proofs below\n  uses HOL's set theory, with the type \\<open>\\<alpha> set\\<close> and the operator \\<open>range :: (\\<alpha> \\<Rightarrow>\n  \\<beta>) \\<Rightarrow> \\<beta> set\\<close>.\n\\<close>\n\ntheorem \"\\<exists>S. S \\<notin> range (f :: 'a \\<Rightarrow> 'a set)\"\nproof\n  let ?S = \"{x. x \\<notin> f x}\"\n  show \"?S \\<notin> range f\"\n  proof\n    assume \"?S \\<in> range f\"\n    then obtain y where \"?S = f y\" ..\n    then show False\n    proof (rule equalityCE)\n      assume \"y \\<in> f y\"\n      assume \"y \\<in> ?S\"\n      then have \"y \\<notin> f y\" ..\n      with \\<open>y \\<in> f y\\<close> show ?thesis by contradiction\n    next\n      assume \"y \\<notin> ?S\"\n      assume \"y \\<notin> f y\"\n      then have \"y \\<in> ?S\" ..\n      with \\<open>y \\<notin> ?S\\<close> show ?thesis by contradiction\n    qed\n  qed\nqed\n\ntext \\<open>\n  How much creativity is required? As it happens, Isabelle can prove this\n  theorem automatically using best-first search. Depth-first search would\n  diverge, but best-first search successfully navigates through the large\n  search space. The context of Isabelle's classical prover contains rules for\n  the relevant constructs of HOL's set theory.\n\\<close>\n\ntheorem \"\\<exists>S. S \\<notin> range (f :: 'a \\<Rightarrow> 'a set)\"\n  by best\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/Cantor.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8418256551882382, "lm_q2_score": 0.879146761176671, "lm_q1q2_score": 0.7400882982341686}}
{"text": "(*  Title:      HOL/Hahn_Banach/Subspace.thy\n    Author:     Gertrud Bauer, TU Munich\n*)\n\nsection \\<open>Subspaces\\<close>\n\ntheory Subspace\nimports Vector_Space \"~~/src/HOL/Library/Set_Algebras\"\nbegin\n\nsubsection \\<open>Definition\\<close>\n\ntext \\<open>\n  A non-empty subset @{text U} of a vector space @{text V} is a\n  \\emph{subspace} of @{text V}, iff @{text U} is closed under addition\n  and scalar multiplication.\n\\<close>\n\nlocale subspace =\n  fixes U :: \"'a\\<Colon>{minus, plus, zero, uminus} set\" and V\n  assumes non_empty [iff, intro]: \"U \\<noteq> {}\"\n    and subset [iff]: \"U \\<subseteq> V\"\n    and add_closed [iff]: \"x \\<in> U \\<Longrightarrow> y \\<in> U \\<Longrightarrow> x + y \\<in> U\"\n    and mult_closed [iff]: \"x \\<in> U \\<Longrightarrow> a \\<cdot> x \\<in> U\"\n\nnotation (symbols)\n  subspace  (infix \"\\<unlhd>\" 50)\n\ndeclare vectorspace.intro [intro?] subspace.intro [intro?]\n\nlemma subspace_subset [elim]: \"U \\<unlhd> V \\<Longrightarrow> U \\<subseteq> V\"\n  by (rule subspace.subset)\n\nlemma (in subspace) subsetD [iff]: \"x \\<in> U \\<Longrightarrow> x \\<in> V\"\n  using subset by blast\n\nlemma subspaceD [elim]: \"U \\<unlhd> V \\<Longrightarrow> x \\<in> U \\<Longrightarrow> x \\<in> V\"\n  by (rule subspace.subsetD)\n\nlemma rev_subspaceD [elim?]: \"x \\<in> U \\<Longrightarrow> U \\<unlhd> V \\<Longrightarrow> x \\<in> V\"\n  by (rule subspace.subsetD)\n\nlemma (in subspace) diff_closed [iff]:\n  assumes \"vectorspace V\"\n  assumes x: \"x \\<in> U\" and y: \"y \\<in> U\"\n  shows \"x - y \\<in> U\"\nproof -\n  interpret vectorspace V by fact\n  from x y show ?thesis by (simp add: diff_eq1 negate_eq1)\nqed\n\ntext \\<open>\n  \\medskip Similar as for linear spaces, the existence of the zero\n  element in every subspace follows from the non-emptiness of the\n  carrier set and by vector space laws.\n\\<close>\n\nlemma (in subspace) zero [intro]:\n  assumes \"vectorspace V\"\n  shows \"0 \\<in> U\"\nproof -\n  interpret V: vectorspace V by fact\n  have \"U \\<noteq> {}\" by (rule non_empty)\n  then obtain x where x: \"x \\<in> U\" by blast\n  then have \"x \\<in> V\" .. then have \"0 = x - x\" by simp\n  also from \\<open>vectorspace V\\<close> x x have \"\\<dots> \\<in> U\" by (rule diff_closed)\n  finally show ?thesis .\nqed\n\nlemma (in subspace) neg_closed [iff]:\n  assumes \"vectorspace V\"\n  assumes x: \"x \\<in> U\"\n  shows \"- x \\<in> U\"\nproof -\n  interpret vectorspace V by fact\n  from x show ?thesis by (simp add: negate_eq1)\nqed\n\ntext \\<open>\\medskip Further derived laws: every subspace is a vector space.\\<close>\n\nlemma (in subspace) vectorspace [iff]:\n  assumes \"vectorspace V\"\n  shows \"vectorspace U\"\nproof -\n  interpret vectorspace V by fact\n  show ?thesis\n  proof\n    show \"U \\<noteq> {}\" ..\n    fix x y z assume x: \"x \\<in> U\" and y: \"y \\<in> U\" and z: \"z \\<in> U\"\n    fix a b :: real\n    from x y show \"x + y \\<in> U\" by simp\n    from x show \"a \\<cdot> x \\<in> U\" by simp\n    from x y z show \"(x + y) + z = x + (y + z)\" by (simp add: add_ac)\n    from x y show \"x + y = y + x\" by (simp add: add_ac)\n    from x show \"x - x = 0\" by simp\n    from x show \"0 + x = x\" by simp\n    from x y show \"a \\<cdot> (x + y) = a \\<cdot> x + a \\<cdot> y\" by (simp add: distrib)\n    from x show \"(a + b) \\<cdot> x = a \\<cdot> x + b \\<cdot> x\" by (simp add: distrib)\n    from x show \"(a * b) \\<cdot> x = a \\<cdot> b \\<cdot> x\" by (simp add: mult_assoc)\n    from x show \"1 \\<cdot> x = x\" by simp\n    from x show \"- x = - 1 \\<cdot> x\" by (simp add: negate_eq1)\n    from x y show \"x - y = x + - y\" by (simp add: diff_eq1)\n  qed\nqed\n\n\ntext \\<open>The subspace relation is reflexive.\\<close>\n\nlemma (in vectorspace) subspace_refl [intro]: \"V \\<unlhd> V\"\nproof\n  show \"V \\<noteq> {}\" ..\n  show \"V \\<subseteq> V\" ..\nnext\n  fix x y assume x: \"x \\<in> V\" and y: \"y \\<in> V\"\n  fix a :: real\n  from x y show \"x + y \\<in> V\" by simp\n  from x show \"a \\<cdot> x \\<in> V\" by simp\nqed\n\ntext \\<open>The subspace relation is transitive.\\<close>\n\nlemma (in vectorspace) subspace_trans [trans]:\n  \"U \\<unlhd> V \\<Longrightarrow> V \\<unlhd> W \\<Longrightarrow> U \\<unlhd> W\"\nproof\n  assume uv: \"U \\<unlhd> V\" and vw: \"V \\<unlhd> W\"\n  from uv show \"U \\<noteq> {}\" by (rule subspace.non_empty)\n  show \"U \\<subseteq> W\"\n  proof -\n    from uv have \"U \\<subseteq> V\" by (rule subspace.subset)\n    also from vw have \"V \\<subseteq> W\" by (rule subspace.subset)\n    finally show ?thesis .\n  qed\n  fix x y assume x: \"x \\<in> U\" and y: \"y \\<in> U\"\n  from uv and x y show \"x + y \\<in> U\" by (rule subspace.add_closed)\n  from uv and x show \"\\<And>a. a \\<cdot> x \\<in> U\" by (rule subspace.mult_closed)\nqed\n\n\nsubsection \\<open>Linear closure\\<close>\n\ntext \\<open>\n  The \\emph{linear closure} of a vector @{text x} is the set of all\n  scalar multiples of @{text x}.\n\\<close>\n\ndefinition lin :: \"('a::{minus,plus,zero}) \\<Rightarrow> 'a set\"\n  where \"lin x = {a \\<cdot> x | a. True}\"\n\nlemma linI [intro]: \"y = a \\<cdot> x \\<Longrightarrow> y \\<in> lin x\"\n  unfolding lin_def by blast\n\nlemma linI' [iff]: \"a \\<cdot> x \\<in> lin x\"\n  unfolding lin_def by blast\n\nlemma linE [elim]: \"x \\<in> lin v \\<Longrightarrow> (\\<And>a::real. x = a \\<cdot> v \\<Longrightarrow> C) \\<Longrightarrow> C\"\n  unfolding lin_def by blast\n\n\ntext \\<open>Every vector is contained in its linear closure.\\<close>\n\nlemma (in vectorspace) x_lin_x [iff]: \"x \\<in> V \\<Longrightarrow> x \\<in> lin x\"\nproof -\n  assume \"x \\<in> V\"\n  then have \"x = 1 \\<cdot> x\" by simp\n  also have \"\\<dots> \\<in> lin x\" ..\n  finally show ?thesis .\nqed\n\nlemma (in vectorspace) \"0_lin_x\" [iff]: \"x \\<in> V \\<Longrightarrow> 0 \\<in> lin x\"\nproof\n  assume \"x \\<in> V\"\n  then show \"0 = 0 \\<cdot> x\" by simp\nqed\n\ntext \\<open>Any linear closure is a subspace.\\<close>\n\nlemma (in vectorspace) lin_subspace [intro]:\n  assumes x: \"x \\<in> V\"\n  shows \"lin x \\<unlhd> V\"\nproof\n  from x show \"lin x \\<noteq> {}\" by auto\nnext\n  show \"lin x \\<subseteq> V\"\n  proof\n    fix x' assume \"x' \\<in> lin x\"\n    then obtain a where \"x' = a \\<cdot> x\" ..\n    with x show \"x' \\<in> V\" by simp\n  qed\nnext\n  fix x' x'' assume x': \"x' \\<in> lin x\" and x'': \"x'' \\<in> lin x\"\n  show \"x' + x'' \\<in> lin x\"\n  proof -\n    from x' obtain a' where \"x' = a' \\<cdot> x\" ..\n    moreover from x'' obtain a'' where \"x'' = a'' \\<cdot> x\" ..\n    ultimately have \"x' + x'' = (a' + a'') \\<cdot> x\"\n      using x by (simp add: distrib)\n    also have \"\\<dots> \\<in> lin x\" ..\n    finally show ?thesis .\n  qed\n  fix a :: real\n  show \"a \\<cdot> x' \\<in> lin x\"\n  proof -\n    from x' obtain a' where \"x' = a' \\<cdot> x\" ..\n    with x have \"a \\<cdot> x' = (a * a') \\<cdot> x\" by (simp add: mult_assoc)\n    also have \"\\<dots> \\<in> lin x\" ..\n    finally show ?thesis .\n  qed\nqed\n\n\ntext \\<open>Any linear closure is a vector space.\\<close>\n\nlemma (in vectorspace) lin_vectorspace [intro]:\n  assumes \"x \\<in> V\"\n  shows \"vectorspace (lin x)\"\nproof -\n  from \\<open>x \\<in> V\\<close> have \"subspace (lin x) V\"\n    by (rule lin_subspace)\n  from this and vectorspace_axioms show ?thesis\n    by (rule subspace.vectorspace)\nqed\n\n\nsubsection \\<open>Sum of two vectorspaces\\<close>\n\ntext \\<open>\n  The \\emph{sum} of two vectorspaces @{text U} and @{text V} is the\n  set of all sums of elements from @{text U} and @{text V}.\n\\<close>\n\nlemma sum_def: \"U + V = {u + v | u v. u \\<in> U \\<and> v \\<in> V}\"\n  unfolding set_plus_def by auto\n\nlemma sumE [elim]:\n    \"x \\<in> U + V \\<Longrightarrow> (\\<And>u v. x = u + v \\<Longrightarrow> u \\<in> U \\<Longrightarrow> v \\<in> V \\<Longrightarrow> C) \\<Longrightarrow> C\"\n  unfolding sum_def by blast\n\nlemma sumI [intro]:\n    \"u \\<in> U \\<Longrightarrow> v \\<in> V \\<Longrightarrow> x = u + v \\<Longrightarrow> x \\<in> U + V\"\n  unfolding sum_def by blast\n\nlemma sumI' [intro]:\n    \"u \\<in> U \\<Longrightarrow> v \\<in> V \\<Longrightarrow> u + v \\<in> U + V\"\n  unfolding sum_def by blast\n\ntext \\<open>@{text U} is a subspace of @{text \"U + V\"}.\\<close>\n\nlemma subspace_sum1 [iff]:\n  assumes \"vectorspace U\" \"vectorspace V\"\n  shows \"U \\<unlhd> U + V\"\nproof -\n  interpret vectorspace U by fact\n  interpret vectorspace V by fact\n  show ?thesis\n  proof\n    show \"U \\<noteq> {}\" ..\n    show \"U \\<subseteq> U + V\"\n    proof\n      fix x assume x: \"x \\<in> U\"\n      moreover have \"0 \\<in> V\" ..\n      ultimately have \"x + 0 \\<in> U + V\" ..\n      with x show \"x \\<in> U + V\" by simp\n    qed\n    fix x y assume x: \"x \\<in> U\" and \"y \\<in> U\"\n    then show \"x + y \\<in> U\" by simp\n    from x show \"\\<And>a. a \\<cdot> x \\<in> U\" by simp\n  qed\nqed\n\ntext \\<open>The sum of two subspaces is again a subspace.\\<close>\n\nlemma sum_subspace [intro?]:\n  assumes \"subspace U E\" \"vectorspace E\" \"subspace V E\"\n  shows \"U + V \\<unlhd> E\"\nproof -\n  interpret subspace U E by fact\n  interpret vectorspace E by fact\n  interpret subspace V E by fact\n  show ?thesis\n  proof\n    have \"0 \\<in> U + V\"\n    proof\n      show \"0 \\<in> U\" using \\<open>vectorspace E\\<close> ..\n      show \"0 \\<in> V\" using \\<open>vectorspace E\\<close> ..\n      show \"(0::'a) = 0 + 0\" by simp\n    qed\n    then show \"U + V \\<noteq> {}\" by blast\n    show \"U + V \\<subseteq> E\"\n    proof\n      fix x assume \"x \\<in> U + V\"\n      then obtain u v where \"x = u + v\" and\n        \"u \\<in> U\" and \"v \\<in> V\" ..\n      then show \"x \\<in> E\" by simp\n    qed\n  next\n    fix x y assume x: \"x \\<in> U + V\" and y: \"y \\<in> U + V\"\n    show \"x + y \\<in> U + V\"\n    proof -\n      from x obtain ux vx where \"x = ux + vx\" and \"ux \\<in> U\" and \"vx \\<in> V\" ..\n      moreover\n      from y obtain uy vy where \"y = uy + vy\" and \"uy \\<in> U\" and \"vy \\<in> V\" ..\n      ultimately\n      have \"ux + uy \\<in> U\"\n        and \"vx + vy \\<in> V\"\n        and \"x + y = (ux + uy) + (vx + vy)\"\n        using x y by (simp_all add: add_ac)\n      then show ?thesis ..\n    qed\n    fix a show \"a \\<cdot> x \\<in> U + V\"\n    proof -\n      from x obtain u v where \"x = u + v\" and \"u \\<in> U\" and \"v \\<in> V\" ..\n      then have \"a \\<cdot> u \\<in> U\" and \"a \\<cdot> v \\<in> V\"\n        and \"a \\<cdot> x = (a \\<cdot> u) + (a \\<cdot> v)\" by (simp_all add: distrib)\n      then show ?thesis ..\n    qed\n  qed\nqed\n\ntext\\<open>The sum of two subspaces is a vectorspace.\\<close>\n\nlemma sum_vs [intro?]:\n    \"U \\<unlhd> E \\<Longrightarrow> V \\<unlhd> E \\<Longrightarrow> vectorspace E \\<Longrightarrow> vectorspace (U + V)\"\n  by (rule subspace.vectorspace) (rule sum_subspace)\n\n\nsubsection \\<open>Direct sums\\<close>\n\ntext \\<open>\n  The sum of @{text U} and @{text V} is called \\emph{direct}, iff the\n  zero element is the only common element of @{text U} and @{text\n  V}. For every element @{text x} of the direct sum of @{text U} and\n  @{text V} the decomposition in @{text \"x = u + v\"} with\n  @{text \"u \\<in> U\"} and @{text \"v \\<in> V\"} is unique.\n\\<close>\n\nlemma decomp:\n  assumes \"vectorspace E\" \"subspace U E\" \"subspace V E\"\n  assumes direct: \"U \\<inter> V = {0}\"\n    and u1: \"u1 \\<in> U\" and u2: \"u2 \\<in> U\"\n    and v1: \"v1 \\<in> V\" and v2: \"v2 \\<in> V\"\n    and sum: \"u1 + v1 = u2 + v2\"\n  shows \"u1 = u2 \\<and> v1 = v2\"\nproof -\n  interpret vectorspace E by fact\n  interpret subspace U E by fact\n  interpret subspace V E by fact\n  show ?thesis\n  proof\n    have U: \"vectorspace U\"  (* FIXME: use interpret *)\n      using \\<open>subspace U E\\<close> \\<open>vectorspace E\\<close> by (rule subspace.vectorspace)\n    have V: \"vectorspace V\"\n      using \\<open>subspace V E\\<close> \\<open>vectorspace E\\<close> by (rule subspace.vectorspace)\n    from u1 u2 v1 v2 and sum have eq: \"u1 - u2 = v2 - v1\"\n      by (simp add: add_diff_swap)\n    from u1 u2 have u: \"u1 - u2 \\<in> U\"\n      by (rule vectorspace.diff_closed [OF U])\n    with eq have v': \"v2 - v1 \\<in> U\" by (simp only:)\n    from v2 v1 have v: \"v2 - v1 \\<in> V\"\n      by (rule vectorspace.diff_closed [OF V])\n    with eq have u': \" u1 - u2 \\<in> V\" by (simp only:)\n    \n    show \"u1 = u2\"\n    proof (rule add_minus_eq)\n      from u1 show \"u1 \\<in> E\" ..\n      from u2 show \"u2 \\<in> E\" ..\n      from u u' and direct show \"u1 - u2 = 0\" by blast\n    qed\n    show \"v1 = v2\"\n    proof (rule add_minus_eq [symmetric])\n      from v1 show \"v1 \\<in> E\" ..\n      from v2 show \"v2 \\<in> E\" ..\n      from v v' and direct show \"v2 - v1 = 0\" by blast\n    qed\n  qed\nqed\n\ntext \\<open>\n  An application of the previous lemma will be used in the proof of\n  the Hahn-Banach Theorem (see page \\pageref{decomp-H-use}): for any\n  element @{text \"y + a \\<cdot> x\\<^sub>0\"} of the direct sum of a\n  vectorspace @{text H} and the linear closure of @{text \"x\\<^sub>0\"}\n  the components @{text \"y \\<in> H\"} and @{text a} are uniquely\n  determined.\n\\<close>\n\nlemma decomp_H':\n  assumes \"vectorspace E\" \"subspace H E\"\n  assumes y1: \"y1 \\<in> H\" and y2: \"y2 \\<in> H\"\n    and x': \"x' \\<notin> H\"  \"x' \\<in> E\"  \"x' \\<noteq> 0\"\n    and eq: \"y1 + a1 \\<cdot> x' = y2 + a2 \\<cdot> x'\"\n  shows \"y1 = y2 \\<and> a1 = a2\"\nproof -\n  interpret vectorspace E by fact\n  interpret subspace H E by fact\n  show ?thesis\n  proof\n    have c: \"y1 = y2 \\<and> a1 \\<cdot> x' = a2 \\<cdot> x'\"\n    proof (rule decomp)\n      show \"a1 \\<cdot> x' \\<in> lin x'\" ..\n      show \"a2 \\<cdot> x' \\<in> lin x'\" ..\n      show \"H \\<inter> lin x' = {0}\"\n      proof\n        show \"H \\<inter> lin x' \\<subseteq> {0}\"\n        proof\n          fix x assume x: \"x \\<in> H \\<inter> lin x'\"\n          then obtain a where xx': \"x = a \\<cdot> x'\"\n            by blast\n          have \"x = 0\"\n          proof cases\n            assume \"a = 0\"\n            with xx' and x' show ?thesis by simp\n          next\n            assume a: \"a \\<noteq> 0\"\n            from x have \"x \\<in> H\" ..\n            with xx' have \"inverse a \\<cdot> a \\<cdot> x' \\<in> H\" by simp\n            with a and x' have \"x' \\<in> H\" by (simp add: mult_assoc2)\n            with \\<open>x' \\<notin> H\\<close> show ?thesis by contradiction\n          qed\n          then show \"x \\<in> {0}\" ..\n        qed\n        show \"{0} \\<subseteq> H \\<inter> lin x'\"\n        proof -\n          have \"0 \\<in> H\" using \\<open>vectorspace E\\<close> ..\n          moreover have \"0 \\<in> lin x'\" using \\<open>x' \\<in> E\\<close> ..\n          ultimately show ?thesis by blast\n        qed\n      qed\n      show \"lin x' \\<unlhd> E\" using \\<open>x' \\<in> E\\<close> ..\n    qed (rule \\<open>vectorspace E\\<close>, rule \\<open>subspace H E\\<close>, rule y1, rule y2, rule eq)\n    then show \"y1 = y2\" ..\n    from c have \"a1 \\<cdot> x' = a2 \\<cdot> x'\" ..\n    with x' show \"a1 = a2\" by (simp add: mult_right_cancel)\n  qed\nqed\n\ntext \\<open>\n  Since for any element @{text \"y + a \\<cdot> x'\"} of the direct sum of a\n  vectorspace @{text H} and the linear closure of @{text x'} the\n  components @{text \"y \\<in> H\"} and @{text a} are unique, it follows from\n  @{text \"y \\<in> H\"} that @{text \"a = 0\"}.\n\\<close>\n\nlemma decomp_H'_H:\n  assumes \"vectorspace E\" \"subspace H E\"\n  assumes t: \"t \\<in> H\"\n    and x': \"x' \\<notin> H\"  \"x' \\<in> E\"  \"x' \\<noteq> 0\"\n  shows \"(SOME (y, a). t = y + a \\<cdot> x' \\<and> y \\<in> H) = (t, 0)\"\nproof -\n  interpret vectorspace E by fact\n  interpret subspace H E by fact\n  show ?thesis\n  proof (rule, simp_all only: split_paired_all split_conv)\n    from t x' show \"t = t + 0 \\<cdot> x' \\<and> t \\<in> H\" by simp\n    fix y and a assume ya: \"t = y + a \\<cdot> x' \\<and> y \\<in> H\"\n    have \"y = t \\<and> a = 0\"\n    proof (rule decomp_H')\n      from ya x' show \"y + a \\<cdot> x' = t + 0 \\<cdot> x'\" by simp\n      from ya show \"y \\<in> H\" ..\n    qed (rule \\<open>vectorspace E\\<close>, rule \\<open>subspace H E\\<close>, rule t, (rule x')+)\n    with t x' show \"(y, a) = (y + a \\<cdot> x', 0)\" by simp\n  qed\nqed\n\ntext \\<open>\n  The components @{text \"y \\<in> H\"} and @{text a} in @{text \"y + a \\<cdot> x'\"}\n  are unique, so the function @{text h'} defined by\n  @{text \"h' (y + a \\<cdot> x') = h y + a \\<cdot> \\<xi>\"} is definite.\n\\<close>\n\nlemma h'_definite:\n  fixes H\n  assumes h'_def:\n    \"h' \\<equiv> \\<lambda>x.\n      let (y, a) = SOME (y, a). (x = y + a \\<cdot> x' \\<and> y \\<in> H)\n      in (h y) + a * xi\"\n    and x: \"x = y + a \\<cdot> x'\"\n  assumes \"vectorspace E\" \"subspace H E\"\n  assumes y: \"y \\<in> H\"\n    and x': \"x' \\<notin> H\"  \"x' \\<in> E\"  \"x' \\<noteq> 0\"\n  shows \"h' x = h y + a * xi\"\nproof -\n  interpret vectorspace E by fact\n  interpret subspace H E by fact\n  from x y x' have \"x \\<in> H + lin x'\" by auto\n  have \"\\<exists>!p. (\\<lambda>(y, a). x = y + a \\<cdot> x' \\<and> y \\<in> H) p\" (is \"\\<exists>!p. ?P p\")\n  proof (rule ex_ex1I)\n    from x y show \"\\<exists>p. ?P p\" by blast\n    fix p q assume p: \"?P p\" and q: \"?P q\"\n    show \"p = q\"\n    proof -\n      from p have xp: \"x = fst p + snd p \\<cdot> x' \\<and> fst p \\<in> H\"\n        by (cases p) simp\n      from q have xq: \"x = fst q + snd q \\<cdot> x' \\<and> fst q \\<in> H\"\n        by (cases q) simp\n      have \"fst p = fst q \\<and> snd p = snd q\"\n      proof (rule decomp_H')\n        from xp show \"fst p \\<in> H\" ..\n        from xq show \"fst q \\<in> H\" ..\n        from xp and xq show \"fst p + snd p \\<cdot> x' = fst q + snd q \\<cdot> x'\"\n          by simp\n      qed (rule \\<open>vectorspace E\\<close>, rule \\<open>subspace H E\\<close>, (rule x')+)\n      then show ?thesis by (cases p, cases q) simp\n    qed\n  qed\n  then have eq: \"(SOME (y, a). x = y + a \\<cdot> x' \\<and> y \\<in> H) = (y, a)\"\n    by (rule some1_equality) (simp add: x y)\n  with h'_def show \"h' x = h y + a * xi\" by (simp add: Let_def)\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/Hahn_Banach/Subspace.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256313782277, "lm_q2_score": 0.8791467611766711, "lm_q1q2_score": 0.7400882773016751}}
{"text": "theory Stuff\n  imports \"HOL-Algebra.Algebra\"\nbegin\n\nlemma inter_imp_subset: \"A \\<inter> B = A \\<Longrightarrow> A \\<subseteq> B\"\n  by blast\n\nlemma card_inter_eq:\n  assumes \"finite A\" \"card (A \\<inter> B) = card A\"\n  shows \"A \\<subseteq> B\"\nproof -\n  have \"A \\<inter> B \\<subseteq> A\" by blast\n  with assms have \"A \\<inter> B = A\" using card_subset_eq by blast\n  thus ?thesis by blast\nqed\n\nlemma coprime_eq_empty_prime_inter:\n  assumes \"(n::nat) \\<noteq> 0\" \"m \\<noteq> 0\"\n  shows \"coprime n m \\<longleftrightarrow> (prime_factors n) \\<inter> (prime_factors m) = {}\"\nproof\n  show \"coprime n m \\<Longrightarrow> prime_factors n \\<inter> prime_factors m = {}\"\n  proof (rule ccontr)\n    assume cp: \"coprime n m\"\n    assume pf: \"prime_factors n \\<inter> prime_factors m \\<noteq> {}\"\n    then obtain p where p: \"p \\<in> prime_factors n\" \"p \\<in> prime_factors m\" by blast\n    then have p_dvd: \"p dvd n\" \"p dvd m\" by blast+\n    moreover have \"\\<not>is_unit p\" using p using not_prime_unit by blast\n    ultimately show \"False\" using cp unfolding coprime_def by simp\n  qed\n  assume assm: \"prime_factors n \\<inter> prime_factors m = {}\"\n  show \"coprime n m\" unfolding coprime_def\n  proof\n    fix c\n    show \"c dvd n \\<longrightarrow> c dvd m \\<longrightarrow> is_unit c\"\n    proof(rule; rule)\n      assume c: \"c dvd n\" \"c dvd m\"\n      then have \"prime_factors c \\<subseteq> prime_factors n\" \"prime_factors c \\<subseteq> prime_factors m\"\n        using assms dvd_prime_factors by blast+\n      then have \"prime_factors c = {}\" using assm by blast\n      thus \"is_unit c\" using assms c\n        by (metis dvd_0_left_iff prime_factorization_empty_iff set_mset_eq_empty_iff)\n    qed\n  qed\nqed\n\nlemma prime_factors_Prod:\n  assumes \"finite S\" \"\\<And>a. a \\<in> S \\<Longrightarrow> f a \\<noteq> 0\"\n  shows \"prime_factors (prod f S) = \\<Union>(prime_factors ` f ` S)\"\n  using assms\nproof(induction S rule: finite_induct)\n  case empty\n  then show ?case by simp\nnext\n  case i: (insert x F)\n  from i have x: \"f x \\<noteq> 0\" by blast\n  from i have F: \"prod f F \\<noteq> 0\" by simp\n  from i have \"prime_factors(prod f F) = \\<Union> (prime_factors ` f ` F)\" by blast\n  moreover have \"prod f (insert x F) = (prod f F) * f x\" using i mult.commute by force\n  ultimately have \"prime_factors (prod f (insert x F)) = (\\<Union>(prime_factors ` f ` F)) \\<union> prime_factors (f x)\"\n    using prime_factors_product[OF F x] by argo\n  thus ?case by force\nqed\n\nlemma lcm_is_Min_multiple_nat:\n  assumes \"c \\<noteq> 0\" \"(a::nat) dvd c\" \"(b::nat) dvd c\"\n  shows \"c \\<ge> lcm a b\"\n  using lcm_least[of a c b] assms by fastforce\n\nlemma diff_prime_power_imp_coprime:\n  assumes \"p \\<noteq> q\" \"Factorial_Ring.prime (p::nat)\" \"Factorial_Ring.prime q\"\n  shows \"coprime (p ^ (n::nat)) (q ^ m)\"\n  using assms\n  by (metis power_0 power_one_right prime_dvd_power prime_imp_power_coprime_nat prime_nat_iff prime_power_inj'')\n\nlemma \"finite (prime_factors x)\"\n  using finite_set_mset by blast\n\nlemma card_ge_1_two_diff:\n  assumes \"card A > 1\"\n  obtains x y where \"x \\<in> A\" \"y \\<in> A\" \"x \\<noteq> y\"\nproof -\n  have fA: \"finite A\" using assms by (metis card.infinite not_one_less_zero)\n  from assms obtain x where x: \"x \\<in> A\" by fastforce\n  with assms fA have \"card (A - {x}) > 0\" by simp\n  then obtain y where y: \"y \\<in> (A - {x})\" by (metis card_gt_0_iff ex_in_conv)\n  thus ?thesis using that[of x y] x by blast\nqed\n\nlemma infinite_two_diff:\n  assumes \"infinite A\"\n  obtains x y where \"x \\<in> A\" \"y \\<in> A\" \"x \\<noteq> y\"\nproof -\n  from assms obtain x where x: \"x \\<in> A\" by fastforce\n  from assms have \"infinite (A - {x})\" by simp\n  then obtain y where y: \"y \\<in> (A - {x})\"\n    by (metis ex_in_conv finite.emptyI)\n  show ?thesis using that[of x y] using x y by blast\nqed\n\nlemma Inf_le:\n  \"Inf A \\<le> x\" if \"x \\<in> (A::nat set)\" for x\nproof (cases \"A = {}\")\n  case True\n  then show ?thesis using that by simp\nnext\n  case False\n  hence \"Inf A \\<le> Inf {x}\" using that by (simp add: cInf_lower)\n  also have \"\\<dots> = x\" by simp\n  finally show \"Inf A \\<le> x\" by blast\nqed\n\nlemma switch_elem_card_le:\n  assumes \"a \\<in> A\"\n  shows \"card (A - {a} \\<union> {b}) \\<le> card A\"\n  using assms\n  by (metis Diff_insert_absorb Set.set_insert Un_commute card.infinite card_insert_disjoint card_mono finite_insert insert_is_Un insert_subset order_refl)\n\nlemma pairwise_coprime_dvd:\n  assumes \"finite A\" \"pairwise coprime A\" \"(n::nat) = prod id A\" \"\\<forall>a\\<in>A. a dvd j\"\n  shows \"n dvd j\"\n  using assms\nproof (induction A arbitrary: n)\n  case i: (insert x F)\n  have \"prod id F dvd j\" \"x dvd j\" using i unfolding pairwise_def by auto\n  moreover have \"coprime (prod id F) x\"\n    by (metis i(2, 4) id_apply pairwise_insert prod_coprime_left)\n  ultimately show ?case using i(1, 2, 5) by (simp add: coprime_commute divides_mult)\nqed simp\n\nlemma pairwise_coprime_dvd':\n  assumes \"finite A\" \"\\<And>i j. \\<lbrakk>i \\<in> A; j \\<in> A; i \\<noteq> j\\<rbrakk> \\<Longrightarrow> coprime (f i) (f j)\" \"(n::nat) = prod f A\" \"\\<forall>a\\<in>A. f a dvd j\"\n  shows \"n dvd j\"\n  using assms\nproof (induction A arbitrary: n)\n  case i: (insert x F)\n  have \"prod f F dvd j\" \"f x dvd j\" using i unfolding pairwise_def by auto\n  moreover have \"coprime (prod f F) (f x)\" by(intro prod_coprime_left, use i in blast)\n  ultimately show ?case using i by (simp add: coprime_commute divides_mult)\nqed simp\n\nlemma transp_successively_remove1:\n  assumes \"transp f\" \"successively f l\"\n  shows \"successively f (remove1 a l)\" using assms(2)\nproof(induction l rule: induct_list012)\n  case (3 x y zs)\n  from 3(3)[unfolded successively.simps] have fs: \"f x y\" \"successively f (y # zs)\" by auto\n  moreover from this(2) successively.simps have s: \"successively f zs\" by(cases zs, auto)\n  ultimately have s2: \"successively f (remove1 a zs)\" \"successively f (remove1 a (y # zs))\" using 3 by auto\n  consider (x) \"x = a\" | (y) \"y = a \\<and> x \\<noteq> a\" | (zs) \"a \\<noteq> x \\<and> a \\<noteq> y\" by blast\n  thus ?case\n  proof (cases)\n    case x\n    then show ?thesis using 3 by simp\n  next\n    case y\n    then show ?thesis\n    proof (cases zs)\n      case Nil\n      then show ?thesis using fs by simp\n    next\n      case (Cons a list)\n      hence \"f y a\" using fs by simp\n      hence \"f x a\" using fs(1) assms(1)[unfolded transp_def] by blast\n      then show ?thesis using Cons y s by auto\n    qed\n  next\n    case zs\n    then show ?thesis using s2 fs by auto\n  qed\nqed auto\n\n\nlemma exp_one_2pi_iff:\n  fixes x::real shows \"exp (2 * of_real pi * \\<i> * x) = 1 \\<longleftrightarrow> x \\<in> \\<int>\"\nproof -\n  have c: \"cis (2 * x * pi) = 1 \\<longleftrightarrow> x \\<in> \\<int>\" by (auto simp: complex_eq_iff sin_times_pi_eq_0 cos_one_2pi_int, meson Ints_cases)\n  have \"exp (2 * of_real pi * \\<i> * x) = exp (\\<i> * complex_of_real (2 * x * pi))\"\n  proof -\n    have \"2 * of_real pi * \\<i> * x = \\<i> * complex_of_real (2 * x * pi)\" by simp\n    thus ?thesis by argo\n  qed\n  also from cis_conv_exp have \"\\<dots> = cis (2 * x * pi)\" by simp\n  finally show ?thesis using c by simp\nqed\n\n(* Manuel *)\nlemma of_int_divide_in_Ints_iff:\n  assumes \"b \\<noteq> 0\"\n  shows   \"(of_int a / of_int b :: 'a :: field_char_0) \\<in> \\<int> \\<longleftrightarrow> b dvd a\"\nproof\n  assume *: \"(of_int a / of_int b :: 'a :: field_char_0) \\<in> \\<int>\"\n  from * obtain n where \"of_int a / of_int b = (of_int n :: 'a)\"\n    by (elim Ints_cases)\n  hence \"of_int (b * n) = (of_int a :: 'a)\"\n    using assms by (subst of_int_mult) (auto simp: field_simps)\n  hence \"b * n = a\"\n    by (subst (asm) of_int_eq_iff)\n  thus \"b dvd a\" by auto\nqed auto\n\n(* Manuel *)\nlemma of_nat_divide_in_Ints_iff:\n  assumes \"b \\<noteq> 0\"\n  shows   \"(of_nat a / of_nat b :: 'a :: field_char_0) \\<in> \\<int> \\<longleftrightarrow> b dvd a\"\n  using of_int_divide_in_Ints_iff[of \"int b\" \"int a\"] assms by simp\n\nlemma true_nth_unity_root:\n  fixes n::nat\n  obtains x::complex where \"x ^ n = 1\" \"\\<And>m. \\<lbrakk>0<m; m<n\\<rbrakk> \\<Longrightarrow> x ^ m \\<noteq> 1\"\nproof(cases \"n = 0\")\n  case False\n  show ?thesis\n  proof (rule that)\n    show \"cis (2 * pi / n) ^ n = 1\"\n      by (simp add: DeMoivre)\n  next\n    fix m assume m: \"m > 0\" \"m < n\"\n    have \"cis (2 * pi / n) ^ m = cis (2 * pi * m / n)\"\n      by (simp add: DeMoivre algebra_simps)\n    also have \"\\<dots> = 1 \\<longleftrightarrow> real m / real n \\<in> \\<int>\"\n      using exp_one_2pi_iff[of \"m / n\"] by (simp add: cis_conv_exp algebra_simps)\n    also have \"\\<dots> \\<longleftrightarrow> n dvd m\"\n      using m by (subst of_nat_divide_in_Ints_iff) auto\n    also have \"\\<not>n dvd m\"\n      using m by auto\n    finally show \"cis (2 * pi / real n) ^ m \\<noteq> 1\" .\n  qed\nqed simp\n\nlemma finite_bij_betwI:\n  assumes \"finite A\" \"finite B\" \"inj_on f A\" \"f \\<in> A \\<rightarrow> B\" \"card A = card B\"\n  shows \"bij_betw f A B\"\nproof (intro bij_betw_imageI)\n  show \"inj_on f A\" by fact\n  show \"f ` A = B\"\n  proof -\n    have \"card (f ` A) = card B\" using assms by (simp add: card_image)\n    moreover have \"f ` A \\<subseteq> B\" using assms by blast\n    ultimately show ?thesis using assms by (meson card_subset_eq)\n  qed\nqed\n\nlemma powi_mod:\n  \"x powi m = x powi (m mod n)\" if \"x ^ n = 1\" \"n > 0\" for x::complex and m::int\nproof -\n  have xnz: \"x \\<noteq> 0\" using that by (metis zero_neq_one zero_power)\n  obtain k::int where k: \"m = k*n + (m mod n)\" using div_mod_decomp_int by blast\n  have \"x powi m = x powi (k*n) * x powi (m mod n)\" by (subst k, intro power_int_add, use xnz in auto)\n  moreover have \"x powi (k*n) = 1\" using that by (metis mult.commute power_int_1_left power_int_mult power_int_of_nat)\n  ultimately show ?thesis by force\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/Stuff.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8705972684083609, "lm_q2_score": 0.8499711718571775, "lm_q1q2_score": 0.7399825804447122}}
{"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\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\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\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 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 complex_Im_fact [simp]: \"Im (fact n) = 0\"\n  by (subst of_nat_fact [symmetric]) (simp only: complex_Im_of_nat)\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 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 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\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 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\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\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\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_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\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/Complex.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8856314798554444, "lm_q2_score": 0.8354835371034368, "lm_q1q2_score": 0.7399305213597779}}
{"text": "section \\<open>Bernstein Polynomials over any finite interval\\<close>\n\ntheory Bernstein\n  imports \"Bernstein_01\"\nbegin\n\nsubsection \\<open>Definition and relation to Bernstein Polynomials over [0, 1]\\<close>\n\ndefinition Bernstein_Poly :: \"nat \\<Rightarrow> nat \\<Rightarrow> real \\<Rightarrow> real \\<Rightarrow> real poly\" where\n  \"Bernstein_Poly j p c d = smult ((p choose j)/(d - c)^p)\n      (((monom 1 j) \\<circ>\\<^sub>p [:-c, 1:]) * (monom 1 (p-j) \\<circ>\\<^sub>p [:d, -1:]))\"\n\nlemma Bernstein_Poly_altdef: \n  assumes \"c \\<noteq> d\" and \"j \\<le> p\"\n  shows \"Bernstein_Poly j p c d = smult (p choose j) \n            ([:-c/(d-c), 1/(d-c):]^j * [:d/(d-c), -1/(d-c):]^(p-j))\" \n    (is \"?L = ?R\")\nproof -\n  have \"?L = smult (p choose j) (smult ((1/(d - c))^j)\n        (smult ((1/(d - c))^(p-j)) ([:-c, 1:]^j * [:d, -1:]^(p-j))))\"\n    using assms by (auto simp: Bernstein_Poly_def monom_altdef hom_distribs\n                    pcompose_pCons smult_eq_iff field_simps power_add[symmetric])\n  also have \"... = ?R\"\n    apply (subst mult_smult_right[symmetric])\n    apply (subst mult_smult_left[symmetric])\n    apply (subst smult_power)\n    apply (subst smult_power)\n    by auto\n  finally show ?thesis .\nqed\n\nlemma Bernstein_Poly_nonneg: \n  assumes \"c \\<le> x\" and \"x \\<le> d\"\n  shows \"poly (Bernstein_Poly j p c d) x \\<ge> 0\"\n  using assms by (auto simp: Bernstein_Poly_def poly_pcompose poly_monom)\n\nlemma Bernstein_Poly_01: \"Bernstein_Poly j p 0 1 = Bernstein_Poly_01 j p\"\n  by (auto simp: Bernstein_Poly_def Bernstein_Poly_01_def monom_altdef)\n\nlemma Bernstein_Poly_rescale: \n  assumes \"a \\<noteq> b\"\n  shows \"Bernstein_Poly j p c d \\<circ>\\<^sub>p [:a, 1:] \\<circ>\\<^sub>p [:0, b-a:] \n            = Bernstein_Poly j p ((c-a)/(b-a)) ((d-a)/(b-a))\"\n  (is \"?L = ?R\")\nproof -\n  have \"?R = smult (real (p choose j) \n      / ((d - a) / (b - a) - (c - a) / (b - a)) ^ p)\n      ([:- ((c - a) / (b - a)), 1:] ^ j \n      * [:(d - a) / (b - a), - 1:] ^ (p - j))\"\n    by (auto simp: Bernstein_Poly_def monom_altdef hom_distribs \n        pcompose_pCons) \n  also have \"... = smult (real (p choose j) / ((d - c) / (b - a)) ^ p)\n              ([:- ((c - a) / (b - a)), 1:] ^ j * [:(d - a) / (b - a), - 1:] \n            ^ (p - j))\"\n    by argo\n  also have \"... = smult (real (p choose j) / (d - c) ^ p) \n      (smult ((b - a) ^ (p - j)) (smult ((b - a) ^ j)\n      ([:- ((c - a) / (b - a)), 1:] ^ j * [:(d - a) / (b - a), - 1:] \n      ^ (p - j))))\"\n    by (auto simp: power_add[symmetric] power_divide)\n  also have \"... = smult (real (p choose j) / (d - c) ^ p)\n              ([:- (c - a), b - a:] ^ j * [:d - a, -(b - a):] ^ (p - j))\"\n    apply (subst mult_smult_left[symmetric])\n    apply (subst mult_smult_right[symmetric])\n    using assms by (auto simp: smult_power)\n  also have \"... = ?L\"\n    using assms \n    by (auto simp: Bernstein_Poly_def monom_altdef pcompose_mult \n        pcompose_smult hom_distribs pcompose_pCons)\n  finally show ?thesis by presburger\nqed\n\nlemma Bernstein_Poly_rescale_01: \n  assumes \"c \\<noteq> d\"\n  shows \"Bernstein_Poly j p c d \\<circ>\\<^sub>p [:c, 1:] \\<circ>\\<^sub>p [:0, d-c:] \n          = Bernstein_Poly_01 j p\"\n  apply (subst Bernstein_Poly_rescale)\n  using assms by (auto simp: Bernstein_Poly_01)\n\nlemma Bernstein_Poly_eq_rescale_01: \n  assumes \"c \\<noteq> d\"\n  shows \"Bernstein_Poly j p c d = Bernstein_Poly_01 j p \n            \\<circ>\\<^sub>p [:0, 1/(d-c):] \\<circ>\\<^sub>p [:-c, 1:]\"\n  apply (subst Bernstein_Poly_rescale_01[symmetric])\n  using assms by (auto simp: pcompose_pCons pcompose_assoc[symmetric])\n\nlemma coeff_Bernstein_sum: \n  fixes b::\"nat \\<Rightarrow> real\" and p::nat and c d::real\n  defines \"P \\<equiv> (\\<Sum>j = 0..p. (smult (b j) (Bernstein_Poly j p c d)))\"\n  assumes \"i \\<le> p\" and \"c \\<noteq> d\"\n  shows \"coeff ((reciprocal_poly p (P \\<circ>\\<^sub>p [:c, 1:] \n      \\<circ>\\<^sub>p [:0, d-c:])) \\<circ>\\<^sub>p [:1, 1:]) (p - i) = (p choose i) * (b i)\"\nproof -\n  have h: \"P \\<circ>\\<^sub>p [:c, 1:] \\<circ>\\<^sub>p [:0, d-c:] \n      = (\\<Sum>j = 0..p. (smult (b j) (Bernstein_Poly_01 j p)))\"\n    using assms \n    by (auto simp: P_def pcompose_sum pcompose_smult \n          pcompose_add Bernstein_Poly_rescale_01)\n  then show ?thesis\n    using coeff_Bernstein_sum_01 assms by simp\nqed\n\nlemma Bernstein_sum: \n  assumes \"c \\<noteq> d\" and \"degree P \\<le> p\"\n  shows \"P = (\\<Sum>j = 0..p. smult (inverse (real (p choose j))\n     * coeff (reciprocal_poly p (P \\<circ>\\<^sub>p [:c, 1:] \\<circ>\\<^sub>p [:0, d-c:]) \n      \\<circ>\\<^sub>p [:1, 1:]) (p-j)) (Bernstein_Poly j p c d))\"\n  apply (subst Bernstein_Poly_eq_rescale_01)\n  subgoal using assms by blast\n  subgoal \n    apply (subst pcompose_smult[symmetric])\n    apply (subst pcompose_sum[symmetric])\n    apply (subst pcompose_smult[symmetric])\n    apply (subst pcompose_sum[symmetric])\n    apply (subst Bernstein_sum_01[symmetric])\n    using assms by (auto simp: degree_pcompose pcompose_assoc[symmetric] \n        pcompose_pCons)\n  done\n\nlemma Bernstein_Poly_span1: \n  assumes \"c \\<noteq> d\" and \"degree P \\<le> p\"\n  shows \"P \\<in> poly_vs.span {Bernstein_Poly x p c d | x. x \\<le> p}\"\nproof (subst Bernstein_sum[OF assms], rule poly_vs.span_sum)\n  fix x :: nat\n  assume \"x \\<in> {0..p}\"\n  then have \"\\<exists>n. Bernstein_Poly x p c d = Bernstein_Poly n p c d \\<and> n \\<le> p\"\n    by auto\n  then have \n    \"Bernstein_Poly x p c d \\<in> poly_vs.span {Bernstein_Poly n p c d |n. n \\<le> p}\"\n    by (simp add: poly_vs.span_base)\n  thus \"smult (inverse (real (p choose x)) *\n        coeff (reciprocal_poly p (P \\<circ>\\<^sub>p [:c, 1:] \\<circ>\\<^sub>p [:0, d - c:]) \\<circ>\\<^sub>p [:1, 1:])\n        (p - x)) (Bernstein_Poly x p c d)\n         \\<in> poly_vs.span {Bernstein_Poly x p c d |x. x \\<le> p}\"\n    by (rule poly_vs.span_scale)\nqed\n\nlemma Bernstein_Poly_span: \n  assumes \"c \\<noteq> d\" \n  shows \"poly_vs.span {Bernstein_Poly x p c d | x. x \\<le> p} = {x. degree x \\<le> p}\"\nproof (subst Bernstein_Poly_01_span[symmetric], subst poly_vs.span_eq, rule conjI)\n  show \"{Bernstein_Poly x p c d |x. x \\<le> p}\n      \\<subseteq> poly_vs.span {Bernstein_Poly_01 x p |x. x \\<le> p}\"\n    apply (subst Setcompr_subset)\n    apply (rule allI, rule impI)\n    apply (rule Bernstein_Poly_01_span1)\n    using assms by (auto simp: degree_Bernstein_le Bernstein_Poly_eq_rescale_01\n                    degree_pcompose)\n\n  show \"{Bernstein_Poly_01 x p |x. x \\<le> p}\n      \\<subseteq> poly_vs.span {Bernstein_Poly x p c d |x. x \\<le> p}\"\n    apply (subst Setcompr_subset)\n    apply (rule allI, rule impI)\n    apply (rule Bernstein_Poly_span1)\n    using assms by (auto simp: degree_Bernstein_le)\nqed\n\nlemma Bernstein_Poly_independent: assumes \"c \\<noteq> d\" \n  shows \"poly_vs.independent {Bernstein_Poly x p c d | x. x \\<in> {..p}}\"\nproof (rule poly_vs.card_le_dim_spanning)\n  show \"{Bernstein_Poly x p c d |x. x \\<in> {.. p}} \\<subseteq> {x. degree x \\<le> p}\"\n    using assms \n    by (auto simp: degree_Bernstein Bernstein_Poly_eq_rescale_01 degree_pcompose)\n  show \"{x. degree x \\<le> p} \\<subseteq> poly_vs.span {Bernstein_Poly x p c d |x. x \\<in> {..p}}\"\n    using assms by (auto simp: Bernstein_Poly_span1)\n  show \"finite {Bernstein_Poly x p c d |x. x \\<in> {..p}}\" by fastforce\n  show \"card {Bernstein_Poly x p c d |x. x \\<in> {..p}} \\<le> poly_vs.dim {x. degree x \\<le> p}\"\n    apply (rule le_trans)\n     apply (subst image_Collect[symmetric], rule card_image_le, force)\n    by (force simp: dim_degree)\nqed\n\nsubsection \\<open>Bernstein coefficients and changes over any interval\\<close>\n\ndefinition Bernstein_coeffs ::\n  \"nat \\<Rightarrow> real \\<Rightarrow> real \\<Rightarrow> real poly \\<Rightarrow> real list\" where \n  \"Bernstein_coeffs p c d P = \n    [(inverse (real (p choose j)) * \n      coeff (reciprocal_poly p (P \\<circ>\\<^sub>p [:c, 1:] \\<circ>\\<^sub>p [:0, d-c:]) \\<circ>\\<^sub>p [:1, 1:]) (p-j)). \n     j \\<leftarrow> [0..<(p+1)]]\"\n\nlemma Bernstein_coeffs_eq_rescale: assumes \"c \\<noteq> d\"\n  shows \"Bernstein_coeffs p c d P = Bernstein_coeffs_01 p (P \\<circ>\\<^sub>p [:c, 1:] \\<circ>\\<^sub>p [:0, d-c:])\"\n  using assms by (auto simp: pcompose_pCons pcompose_assoc[symmetric]\n                  Bernstein_coeffs_def Bernstein_coeffs_01_def)\n\nlemma nth_default_Bernstein_coeffs: assumes \"degree P \\<le> p\"\n  shows \"nth_default 0 (Bernstein_coeffs p c d P) i =\n         inverse (p choose i) * coeff\n         (reciprocal_poly p (P \\<circ>\\<^sub>p [:c, 1:] \\<circ>\\<^sub>p [:0, d-c:]) \\<circ>\\<^sub>p [:1, 1:]) (p-i)\"\n  apply (cases \"p = i\")\n  using assms by (auto simp: Bernstein_coeffs_def nth_default_append\n                  nth_default_Cons Nitpick.case_nat_unfold binomial_eq_0)\n\nlemma Bernstein_coeffs_sum: assumes \"c \\<noteq> d\" and hP: \"degree P \\<le> p\"\n  shows \"P = (\\<Sum>j = 0..p. smult (nth_default 0 (Bernstein_coeffs p c d P) j)\n         (Bernstein_Poly j p c d))\"\n  apply (subst nth_default_Bernstein_coeffs[OF hP])\n  apply (subst Bernstein_sum[OF assms])\n  by argo\n\ndefinition Bernstein_changes :: \"nat \\<Rightarrow> real \\<Rightarrow> real \\<Rightarrow> real poly \\<Rightarrow> int\" where\n  \"Bernstein_changes p c d P = nat (changes (Bernstein_coeffs p c d P))\"\n\nlemma Bernstein_changes_eq_rescale: assumes \"c \\<noteq> d\" and \"degree P \\<le> p\"\n  shows \"Bernstein_changes p c d P =\n         Bernstein_changes_01 p (P \\<circ>\\<^sub>p [:c, 1:] \\<circ>\\<^sub>p [:0, d-c:])\"\n  using assms by (auto simp: Bernstein_coeffs_eq_rescale Bernstein_changes_def\n                  Bernstein_changes_01_def)\n\ntext \\<open>This is related and mostly equivalent to previous Descartes test \\<^cite>\\<open>\"li2019counting\"\\<close>\\<close>\nlemma Bernstein_changes_test: \n  fixes P::\"real poly\"\n  assumes \"degree P \\<le> p\" and \"P \\<noteq> 0\" and \"c < d\"\n  shows \"proots_count P {x. c < x \\<and> x < d} \\<le> Bernstein_changes p c d P \\<and>\n        even (Bernstein_changes p c d P - proots_count P {x. c < x \\<and> x < d})\"\nproof -\n  define Q where \"Q=P \\<circ>\\<^sub>p [:c, 1:] \\<circ>\\<^sub>p [:0, d - c:]\"\n\n  have \"int (proots_count Q {x. 0 < x \\<and> x < 1}) \n          \\<le> Bernstein_changes_01 p Q \\<and>\n              even (Bernstein_changes_01 p Q - \n                  int (proots_count Q {x. 0 < x \\<and> x < 1}))\"\n    unfolding Q_def\n    apply (rule Bernstein_changes_01_test)\n    subgoal using assms by fastforce\n    subgoal using assms by (auto simp: pcompose_eq_0)\n    done\n  moreover have \"proots_count P {x. c < x \\<and> x < d} =\n            proots_count Q {x. 0 < x \\<and> x < 1}\"\n    unfolding Q_def\n  proof (subst proots_pcompose)\n    have \"poly [:c, 1:] ` poly [:0, d - c:] ` {x. 0 < x \\<and> x < 1} =\n        {x. c < x \\<and> x < d}\" (is \"?L = ?R\")\n    proof\n      have \"c + x * (d - c) < d\" if \"x < 1\" for x\n      proof - \n        have \"x * (d - c) < 1 * (d - c)\"\n          using \\<open>c < d\\<close> that by force\n        then show ?thesis by fastforce\n      qed\n      then show \"?L \\<subseteq> ?R\"\n        using assms by auto\n    next\n      show \"?R \\<subseteq> ?L\"\n      proof\n        fix x::real assume \"x \\<in> ?R\"\n        hence \"c < x\" and \"x < d\" by auto\n        thus \"x \\<in> ?L\"\n        proof (subst image_eqI)\n          show \"x = poly [:c, 1:] (x - c)\" by force\n          assume \"c < x\" and \"x < d\"\n          thus \"x - c \\<in> poly [:0, d - c:] ` {x. 0 < x \\<and> x < 1}\"\n          proof (subst image_eqI)\n            show \"x - c = poly [:0, d - c:] ((x - c)/(d - c))\"\n              using assms by fastforce\n            assume \"c < x\" and \"x < d\"\n            thus \"(x - c) / (d - c) \\<in> {x. 0 < x \\<and> x < 1}\"\n              by auto\n          qed fast\n        qed fast\n      qed\n    qed\n    then show \"proots_count P {x. c < x \\<and> x < d} =\n        proots_count (P \\<circ>\\<^sub>p [:c, 1:]) \n        (poly [:0, d - c:] ` {x. 0 < x \\<and> x < 1})\"\n      using assms by (auto simp:proots_pcompose)\n    show \"P \\<circ>\\<^sub>p [:c, 1:] \\<noteq> 0\"\n      by (simp add: pcompose_eq_0 assms(2))\n    show \"degree [:0, d - c:] = 1\"\n      using assms by auto\n  qed\n  moreover have \" Bernstein_changes p c d P = Bernstein_changes_01 p Q\"\n    unfolding Q_def\n    apply (rule Bernstein_changes_eq_rescale)\n    using assms by auto\n  ultimately show ?thesis by auto\nqed\n\nsubsection \\<open>The control polygon of a polynomial\\<close>\n\ndefinition control_points ::\n  \"nat \\<Rightarrow> real \\<Rightarrow> real \\<Rightarrow> real poly \\<Rightarrow> (real \\<times> real) list\"\nwhere\n  \"control_points p c d P = \n   [(((real i)*d + (real (p - i))*c)/p, \n      nth_default 0 (Bernstein_coeffs p c d P) i).\n      i \\<leftarrow> [0..<(p+1)]]\"\n\nlemma line_above: \n  fixes a b c d :: real and p :: nat and P :: \"real poly\"\n  assumes hline: \"\\<And>i. i \\<le> p \\<Longrightarrow> a * (((real i)*d + (real (p - i))*c)/p) + b \\<ge>\n                  nth_default 0 (Bernstein_coeffs p c d P) i\"\n  and hp: \"p \\<noteq> 0\" and hcd: \"c \\<noteq> d\" and hP: \"degree P \\<le> p\"\n  shows \"\\<And>x. c \\<le> x \\<Longrightarrow> x \\<le> d \\<Longrightarrow> a*x + b \\<ge> poly P x\"\nproof -\n  fix x\n  assume hc: \"c \\<le> x\" and  hd: \"x \\<le> d\"\n\n  have bern_eq:\"Bernstein_coeffs p c d [:b, a:] =\n           [a*(real i * d + real (p - i) * c)/p + b. i \\<leftarrow> [0..<(p+1)]]\"\n  proof -\n    have \"Bernstein_coeffs p c d [:b, a:] = map (nth_default 0\n          (Bernstein_coeffs_01 p ([:b, a:] \\<circ>\\<^sub>p [:c, 1:] \\<circ>\\<^sub>p [:0, d - c:])))\n         [0..<p+1]\"\n      apply (subst Bernstein_coeffs_eq_rescale[\"OF\" hcd])\n      apply (subst map_nth_default[symmetric])\n      apply (subst length_Bernstein_coeffs_01)\n      by blast\n    also have \n      \"... = map (\\<lambda>i. a * (real i * d + real (p - i) * c) / real p + b) [0..<p + 1]\"\n    proof (rule map_cong)\n      fix x assume hx: \"x \\<in> set [0..<p + 1]\"\n      have \"nth_default 0 (Bernstein_coeffs_01 p\n            ([:b, a:] \\<circ>\\<^sub>p [:c, 1:] \\<circ>\\<^sub>p [:0, d - c:])) x =\n            nth_default 0 (Bernstein_coeffs_01 p\n            (smult (b + a*c) 1 + smult (a*(d - c)) (monom 1 1))) x\"\n      proof-\n        have \"[:b, a:] \\<circ>\\<^sub>p [:c, 1:] \\<circ>\\<^sub>p [:0, d - c:] =\n                  smult (b + a*c) 1 + smult (a*(d - c)) (monom 1 1)\"\n          by (simp add: monom_altdef pcompose_pCons)\n        then show ?thesis by auto\n      qed\n      also have \"... = \n          nth_default 0 (Bernstein_coeffs_01 p (smult (b + a * c) 1)) x +\n          nth_default 0 (Bernstein_coeffs_01 p (smult (a * (d - c)) (monom 1 1))) x\"\n        apply (subst Bernstein_coeffs_01_add)\n        using hp by (auto simp: degree_monom_eq)\n      also have \"...  =\n            (b + a*c) * nth_default 0 (Bernstein_coeffs_01 p 1) x +\n            (a*(d - c)) * nth_default 0 (Bernstein_coeffs_01 p (monom 1 1)) x\"\n        apply (subst Bernstein_coeffs_01_smult)\n        using hp by (auto simp: Bernstein_coeffs_01_smult degree_monom_eq)\n      also have \"... =\n          (b + a * c) * (if x < p + 1 then 1 else 0) +\n           a * (d - c) * (real (nth_default 0 [0..<p + 1] x) / real p)\" \n        apply (subst Bernstein_coeffs_01_1, subst Bernstein_coeffs_01_x[OF hp])\n        apply (subst nth_default_replicate_eq, subst nth_default_map_eq[of _ 0])\n        by auto\n      also have \"... =\n              (b + a * c) * (if x < p + 1 then 1 else 0) +\n              a * (d - c) * (real ([0..<p + 1] ! x) / real p)\"\n        apply (subst nth_default_nth)\n        using hx by auto\n      also have \"... = (b + a * c) * (if x < p + 1 then 1 else 0) +\n              a * (d - c) * (real (0 + x) / real p)\"\n        apply (subst nth_upt)\n        using hx by auto\n      also have \"... = a * (real x * d + real (p - x) * c) / real p + b\"\n        apply (subst of_nat_diff)\n        using hx hp by (auto simp: field_simps)\n      finally show \"nth_default 0 (Bernstein_coeffs_01 p\n                    ([:b, a:] \\<circ>\\<^sub>p [:c, 1:] \\<circ>\\<^sub>p [:0, d - c:])) x =\n                    a * (real x * d + real (p - x) * c) / real p + b\" .\n    qed blast\n    finally show ?thesis .\n  qed\n\n  have nth_default_geq:\"nth_default 0 (Bernstein_coeffs p c d [:b, a:]) i \\<ge>\n           nth_default 0 (Bernstein_coeffs p c d P) i\" for i\n  proof -\n    show \"nth_default 0 (Bernstein_coeffs p c d [:b, a:]) i \\<ge>\n          nth_default 0 (Bernstein_coeffs p c d P) i\"\n    proof cases\n      define p1 where \"p1 \\<equiv> p+1\"\n      assume h: \"i \\<le> p\"\n      hence \"nth_default 0 (Bernstein_coeffs p c d P) i \\<le>\n             a * (((real i)*d + (real (p - i))*c)/p) + b\"\n        by (rule hline)\n      also have \"... = nth_default 0 (map (\\<lambda>i. a * (real i * d \n          + real (p - i) * c) / real p + b) [0..<p + 1]) i\"\n        apply (subst p1_def[symmetric])\n        using h apply (auto simp: nth_default_def)\n        by (auto simp: p1_def)\n      also have \"... = nth_default 0 (Bernstein_coeffs p c d [:b, a:]) i\"\n        using bern_eq by simp\n      finally show ?thesis .\n    next\n      assume h: \"\\<not>i \\<le> p\"\n      thus ?thesis\n        using assms \n        by (auto simp: nth_default_def Bernstein_coeffs_eq_rescale\n                        length_Bernstein_coeffs_01)\n    qed\n  qed\n  \n  have \"poly P x = (\\<Sum>k = 0..p.\n        poly (smult (nth_default 0 (Bernstein_coeffs p c d P) k)\n        (Bernstein_Poly k p c d)) x)\"\n    apply (subst Bernstein_coeffs_sum[OF hcd hP])\n    by (rule poly_sum)\n  also have \"... \\<le> (\\<Sum>k = 0..p.\n      poly (smult (nth_default 0 (Bernstein_coeffs p c d [:b, a:]) k)\n        (Bernstein_Poly k p c d)) x)\"\n    apply (rule sum_mono)\n    using mult_right_mono[OF nth_default_geq] Bernstein_Poly_nonneg[OF hc hd]\n    by auto\n  also have \"... = poly [:b, a:] x\"\n    apply (subst(2) Bernstein_coeffs_sum[of c d \"[:b, a:]\" p])\n    using assms apply auto[2]\n    by (rule poly_sum[symmetric])\n  also have \"... = a*x + b\" by force\n  finally show \"poly P x \\<le> a*x + b\" .\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/Bernstein.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314738181875, "lm_q2_score": 0.8354835330070839, "lm_q1q2_score": 0.73993051268789}}
{"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_MSortBUIsSort\n  imports \"../../Test_Base\"\nbegin\n\ndatatype 'a list = nil2 | cons2 \"'a\" \"'a list\"\n\ndatatype Nat = Z | S \"Nat\"\n\nfun map :: \"('a => 'b) => 'a list => 'b list\" where\n  \"map f (nil2) = nil2\"\n| \"map f (cons2 y xs) = cons2 (f y) (map f xs)\"\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 mergingbu :: \"(Nat list) list => Nat list\" where\n  \"mergingbu (nil2) = nil2\"\n| \"mergingbu (cons2 xs (nil2)) = xs\"\n| \"mergingbu (cons2 xs (cons2 z x2)) =\n     mergingbu (pairwise (cons2 xs (cons2 z x2)))\"\n  by pat_completeness auto\n\nfun msortbu :: \"Nat list => Nat list\" where\n  \"msortbu x = mergingbu (map (% (y :: Nat) => cons2 y (nil2)) 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  \"((msortbu 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_MSortBUIsSort.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894717137996, "lm_q2_score": 0.8267117983401363, "lm_q1q2_score": 0.7397330132963358}}
{"text": "(*  Title:      FOL/ex/Natural_Numbers.thy\n    Author:     Markus Wenzel, TU Munich\n*)\n\nsection {* Natural numbers *}\n\ntheory Natural_Numbers\nimports FOL\nbegin\n\ntext {*\n  Theory of the natural numbers: Peano's axioms, primitive recursion.\n  (Modernized version of Larry Paulson's theory \"Nat\".)  \\medskip\n*}\n\ntypedecl nat\ninstance nat :: \"term\" ..\n\naxiomatization\n  Zero :: nat    (\"0\") and\n  Suc :: \"nat => nat\" and\n  rec :: \"[nat, 'a, [nat, 'a] => 'a] => 'a\"\nwhere\n  induct [case_names 0 Suc, induct type: nat]:\n    \"P(0) ==> (!!x. P(x) ==> P(Suc(x))) ==> P(n)\" and\n  Suc_inject: \"Suc(m) = Suc(n) ==> m = n\" and\n  Suc_neq_0: \"Suc(m) = 0 ==> R\" and\n  rec_0: \"rec(0, a, f) = a\" and\n  rec_Suc: \"rec(Suc(m), a, f) = f(m, rec(m, a, f))\"\n\nlemma Suc_n_not_n: \"Suc(k) \\<noteq> k\"\nproof (induct k)\n  show \"Suc(0) \\<noteq> 0\"\n  proof\n    assume \"Suc(0) = 0\"\n    then show False by (rule Suc_neq_0)\n  qed\nnext\n  fix n assume hyp: \"Suc(n) \\<noteq> n\"\n  show \"Suc(Suc(n)) \\<noteq> Suc(n)\"\n  proof\n    assume \"Suc(Suc(n)) = Suc(n)\"\n    then have \"Suc(n) = n\" by (rule Suc_inject)\n    with hyp show False by contradiction\n  qed\nqed\n\n\ndefinition add :: \"nat => nat => nat\"    (infixl \"+\" 60)\n  where \"m + n = rec(m, n, \\<lambda>x y. Suc(y))\"\n\nlemma add_0 [simp]: \"0 + n = n\"\n  unfolding add_def by (rule rec_0)\n\nlemma add_Suc [simp]: \"Suc(m) + n = Suc(m + n)\"\n  unfolding add_def by (rule rec_Suc)\n\n\n\nlemma add_0_right: \"m + 0 = m\"\n  by (induct m) simp_all\n\nlemma add_Suc_right: \"m + Suc(n) = Suc(m + n)\"\n  by (induct m) simp_all\n\nlemma\n  assumes \"!!n. f(Suc(n)) = Suc(f(n))\"\n  shows \"f(i + j) = i + f(j)\"\n  using assms by (induct i) simp_all\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/Natural_Numbers.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894604912848, "lm_q2_score": 0.8267117983401363, "lm_q1q2_score": 0.7397330040185505}}
{"text": "section \\<open>Stochastic Matrices and Markov Models\\<close>\n\ntext \\<open>We interpret stochastic matrices as Markov chain with\n  discrete time and finite state and prove that the bind-operation\n  on probability mass functions is precisely matrix-vector multiplication.\n  As a consequence, the notion of stationary distribution is equivalent to\n  being an eigenvector with eigenvalue 1.\\<close>\n\ntheory Stochastic_Matrix_Markov_Models\nimports\n  Markov_Models.Classifying_Markov_Chain_States\n  Stochastic_Vector_PMF\nbegin\n\ndefinition transition_of_st_mat :: \"'i st_mat \\<Rightarrow> 'i :: finite \\<Rightarrow> 'i pmf\" where\n  \"transition_of_st_mat a i = pmf_as_measure.pmf_of_st_vec (transition_vec_of_st_mat a i)\" \n\nlemma st_vec_transition_vec_of_st_mat[simp]: \n  \"st_vec (transition_vec_of_st_mat A a) $ i = st_mat A $ i $ a\" \n  by (transfer, auto simp: column_def)\n\nlocale transition_matrix = pmf_as_measure +\n  fixes A :: \"'i :: finite st_mat\" \nbegin\nsublocale MC_syntax \"transition_of_st_mat A\" .\n\nlemma measure_pmf_of_st_vec[simp]: \"measure_pmf (pmf_of_st_vec x) = measure_of_st_vec x\" \n  by (rule pmf_as_measure.pmf_of_st_vec.rep_eq)\n\nlemma pmf_transition_of_st_mat[simp]: \"pmf (transition_of_st_mat A a) i = st_mat A $ i $ a\"\n  unfolding transition_of_st_mat_def\n  by (transfer, auto simp: measure_def)\n\nlemma bind_is_matrix_vector_mult: \"(bind_pmf x (transition_of_st_mat A)) =\n  pmf_as_measure.pmf_of_st_vec (A *st st_vec_of_pmf x)\" \nproof (rule pmf_eqI, goal_cases)\n  case (1 i)\n  define X where \"X = st_vec_of_pmf x\" \n  have \"pmf (bind_pmf x (transition_of_st_mat A)) i = \n    (\\<Sum>a\\<in>UNIV. pmf x a *\\<^sub>R pmf (transition_of_st_mat A a) i)\" \n    unfolding pmf_bind by (subst integral_measure_pmf[of UNIV], auto)\n  also have \"\\<dots> = (\\<Sum>a\\<in>UNIV. st_mat A $ i $ a * st_vec X $ a)\" \n    by (rule sum.cong[OF refl], auto simp: X_def)\n  also have \"\\<dots> = (st_mat A *v st_vec X) $ i\" \n    unfolding matrix_vector_mult_def by auto\n  also have \"\\<dots> = st_vec (A *st X) $ i\" unfolding st_mat_mult_st_vec by simp\n  also have \"\\<dots> = pmf (pmf_of_st_vec (A *st X)) i\" by simp\n  finally show ?case by (simp add: X_def)\nqed\n\nlemmas stationary_distribution_alt_def = \n  stationary_distribution_def[unfolded bind_is_matrix_vector_mult]\n\nlemma stationary_distribution_implies_pmf_of_st_vec:\n  assumes \"stationary_distribution N\" \n  shows \"\\<exists> x. N = pmf_of_st_vec x\" \nproof -\n  from assms[unfolded stationary_distribution_alt_def] show ?thesis by auto\nqed\n\nlemma stationary_distribution_pmf_of_st_vec:\n  \"stationary_distribution (pmf_of_st_vec x) = (A *st x = x)\" \n  unfolding stationary_distribution_alt_def pmf_of_st_vec_inj by auto\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/Stochastic_Matrices/Stochastic_Matrix_Markov_Models.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894520743981, "lm_q2_score": 0.8267117983401363, "lm_q1q2_score": 0.7397329970602109}}
{"text": "(*  Author:     Paulo Em\u00edlio de Vilhena\n*)\n\ntheory Cycles\n  imports\n    \"HOL-Library.FuncSet\"\nPermutations\nbegin\n\nsection \\<open>Cycles\\<close>\n\nsubsection \\<open>Definitions\\<close>\n\nabbreviation cycle :: \"'a list \\<Rightarrow> bool\"\n  where \"cycle cs \\<equiv> distinct cs\"\n\nfun cycle_of_list :: \"'a list \\<Rightarrow> 'a \\<Rightarrow> 'a\"\n  where\n    \"cycle_of_list (i # j # cs) = transpose i j \\<circ> cycle_of_list (j # cs)\"\n  | \"cycle_of_list cs = id\"\n\n\nsubsection \\<open>Basic Properties\\<close>\n\ntext \\<open>We start proving that the function derived from a cycle rotates its support list.\\<close>\n\nlemma id_outside_supp:\n  assumes \"x \\<notin> set cs\" shows \"(cycle_of_list cs) x = x\"\n  using assms by (induct cs rule: cycle_of_list.induct) (simp_all)\n\nlemma permutation_of_cycle: \"permutation (cycle_of_list cs)\"\nproof (induct cs rule: cycle_of_list.induct)\n  case 1 thus ?case\n    using permutation_compose[OF permutation_swap_id] unfolding comp_apply by simp\nqed simp_all\n\nlemma cycle_permutes: \"(cycle_of_list cs) permutes (set cs)\"\n  using permutation_bijective[OF permutation_of_cycle] id_outside_supp[of _ cs]\n  by (simp add: bij_iff permutes_def)\n\ntheorem cyclic_rotation:\n  assumes \"cycle cs\" shows \"map ((cycle_of_list cs) ^^ n) cs = rotate n cs\"\nproof -\n  { have \"map (cycle_of_list cs) cs = rotate1 cs\" using assms(1)\n    proof (induction cs rule: cycle_of_list.induct)\n      case (1 i j cs)\n      then have \\<open>i \\<notin> set cs\\<close> \\<open>j \\<notin> set cs\\<close>\n        by auto\n      then have \\<open>map (Transposition.transpose i j) cs = cs\\<close>\n        by (auto intro: map_idI simp add: transpose_eq_iff)\n      show ?case\n      proof (cases)\n        assume \"cs = Nil\" thus ?thesis by simp\n      next\n        assume \"cs \\<noteq> Nil\" hence ge_two: \"length (j # cs) \\<ge> 2\"\n          using not_less by auto\n        have \"map (cycle_of_list (i # j # cs)) (i # j # cs) =\n              map (transpose i j) (map (cycle_of_list (j # cs)) (i # j # cs))\" by simp\n        also have \" ... = map (transpose i j) (i # (rotate1 (j # cs)))\"\n          by (metis \"1.IH\" \"1.prems\" distinct.simps(2) id_outside_supp list.simps(9))\n        also have \" ... = map (transpose i j) (i # (cs @ [j]))\" by simp\n        also have \" ... = j # (map (transpose i j) cs) @ [i]\" by simp\n        also have \" ... = j # cs @ [i]\"\n          using \\<open>map (Transposition.transpose i j) cs = cs\\<close> by simp\n        also have \" ... = rotate1 (i # j # cs)\" by simp\n        finally show ?thesis .\n      qed\n    qed simp_all }\n  note cyclic_rotation' = this\n\n  show ?thesis\n    using cyclic_rotation' by (induct n) (auto, metis map_map rotate1_rotate_swap rotate_map)\nqed\n\ncorollary cycle_is_surj:\n  assumes \"cycle cs\" shows \"(cycle_of_list cs) ` (set cs) = (set cs)\"\n  using cyclic_rotation[OF assms, of \"Suc 0\"] by (simp add: image_set)\n\ncorollary cycle_is_id_root:\n  assumes \"cycle cs\" shows \"(cycle_of_list cs) ^^ (length cs) = id\"\nproof -\n  have \"map ((cycle_of_list cs) ^^ (length cs)) cs = cs\"\n    unfolding cyclic_rotation[OF assms] by simp\n  hence \"((cycle_of_list cs) ^^ (length cs)) i = i\" if \"i \\<in> set cs\" for i\n    using that map_eq_conv by fastforce\n  moreover have \"((cycle_of_list cs) ^^ n) i = i\" if \"i \\<notin> set cs\" for i n\n    using id_outside_supp[OF that] by (induct n) (simp_all)\n  ultimately show ?thesis\n    by fastforce\nqed\n\ncorollary cycle_of_list_rotate_independent:\n  assumes \"cycle cs\" shows \"(cycle_of_list cs) = (cycle_of_list (rotate n cs))\"\nproof -\n  { fix cs :: \"'a list\" assume cs: \"cycle cs\"\n    have \"(cycle_of_list cs) = (cycle_of_list (rotate1 cs))\"\n    proof -\n      from cs have rotate1_cs: \"cycle (rotate1 cs)\" by simp\n      hence \"map (cycle_of_list (rotate1 cs)) (rotate1 cs) = (rotate 2 cs)\"\n        using cyclic_rotation[OF rotate1_cs, of 1] by (simp add: numeral_2_eq_2)\n      moreover have \"map (cycle_of_list cs) (rotate1 cs) = (rotate 2 cs)\"\n        using cyclic_rotation[OF cs]\n        by (metis One_nat_def Suc_1 funpow.simps(2) id_apply map_map rotate0 rotate_Suc)\n      ultimately have \"(cycle_of_list cs) i = (cycle_of_list (rotate1 cs)) i\" if \"i \\<in> set cs\" for i\n        using that map_eq_conv unfolding sym[OF set_rotate1[of cs]] by fastforce  \n      moreover have \"(cycle_of_list cs) i = (cycle_of_list (rotate1 cs)) i\" if \"i \\<notin> set cs\" for i\n        using that by (simp add: id_outside_supp)\n      ultimately show \"(cycle_of_list cs) = (cycle_of_list (rotate1 cs))\"\n        by blast\n    qed } note rotate1_lemma = this\n\n  show ?thesis\n    using rotate1_lemma[of \"rotate n cs\"] by (induct n) (auto, metis assms distinct_rotate rotate1_lemma)\nqed\n\n\nsubsection\\<open>Conjugation of cycles\\<close>\n\nlemma conjugation_of_cycle:\n  assumes \"cycle cs\" and \"bij p\"\n  shows \"p \\<circ> (cycle_of_list cs) \\<circ> (inv p) = cycle_of_list (map p cs)\"\n  using assms\nproof (induction cs rule: cycle_of_list.induct)\n  case (1 i j cs)\n  have \"p \\<circ> cycle_of_list (i # j # cs) \\<circ> inv p =\n       (p \\<circ> (transpose i j) \\<circ> inv p) \\<circ> (p \\<circ> cycle_of_list (j # cs) \\<circ> inv p)\"\n    by (simp add: assms(2) bij_is_inj fun.map_comp)\n  also have \" ... = (transpose (p i) (p j)) \\<circ> (p \\<circ> cycle_of_list (j # cs) \\<circ> inv p)\"\n    using \"1.prems\"(2) by (simp add: bij_inv_eq_iff transpose_apply_commute fun_eq_iff bij_betw_inv_into_left)\n  finally have \"p \\<circ> cycle_of_list (i # j # cs) \\<circ> inv p =\n               (transpose (p i) (p j)) \\<circ> (cycle_of_list (map p (j # cs)))\"\n    using \"1.IH\" \"1.prems\"(1) assms(2) by fastforce\n  thus ?case by (simp add: fun_eq_iff)\nnext\n  case \"2_1\" thus ?case\n    by (metis bij_is_surj comp_id cycle_of_list.simps(2) list.simps(8) surj_iff) \nnext\n  case \"2_2\" thus ?case\n    by (metis bij_is_surj comp_id cycle_of_list.simps(3) list.simps(8) list.simps(9) surj_iff) \nqed\n\n\nsubsection\\<open>When Cycles Commute\\<close>\n\nlemma cycles_commute:\n  assumes \"cycle p\" \"cycle q\" and \"set p \\<inter> set q = {}\"\n  shows \"(cycle_of_list p) \\<circ> (cycle_of_list q) = (cycle_of_list q) \\<circ> (cycle_of_list p)\"\nproof\n  { fix p :: \"'a list\" and q :: \"'a list\" and i :: \"'a\"\n    assume A: \"cycle p\" \"cycle q\" \"set p \\<inter> set q = {}\" \"i \\<in> set p\" \"i \\<notin> set q\"\n    have \"((cycle_of_list p) \\<circ> (cycle_of_list q)) i =\n          ((cycle_of_list q) \\<circ> (cycle_of_list p)) i\"\n    proof -\n      have \"((cycle_of_list p) \\<circ> (cycle_of_list q)) i = (cycle_of_list p) i\"\n        using id_outside_supp[OF A(5)] by simp\n      also have \" ... = ((cycle_of_list q) \\<circ> (cycle_of_list p)) i\"\n        using id_outside_supp[of \"(cycle_of_list p) i\"] cycle_is_surj[OF A(1)] A(3,4) by fastforce\n      finally show ?thesis .\n    qed } note aui_lemma = this\n\n  fix i consider \"i \\<in> set p\" \"i \\<notin> set q\" | \"i \\<notin> set p\" \"i \\<in> set q\" | \"i \\<notin> set p\" \"i \\<notin> set q\"\n    using \\<open>set p \\<inter> set q = {}\\<close> by blast\n  thus \"((cycle_of_list p) \\<circ> (cycle_of_list q)) i = ((cycle_of_list q) \\<circ> (cycle_of_list p)) i\"\n  proof cases\n    case 1 thus ?thesis\n      using aui_lemma[OF assms] by simp\n  next\n    case 2 thus ?thesis\n      using aui_lemma[OF assms(2,1)] assms(3) by (simp add: ac_simps)\n  next\n    case 3 thus ?thesis\n      by (simp add: id_outside_supp)\n  qed\nqed\n\n\nsubsection \\<open>Cycles from Permutations\\<close>\n\nsubsubsection \\<open>Exponentiation of permutations\\<close>\n\ntext \\<open>Some important properties of permutations before defining how to extract its cycles.\\<close>\n\nlemma permutation_funpow:\n  assumes \"permutation p\" shows \"permutation (p ^^ n)\"\n  using assms by (induct n) (simp_all add: permutation_compose)\n\nlemma permutes_funpow:\n  assumes \"p permutes S\" shows \"(p ^^ n) permutes S\"\n  using assms by (induct n) (simp add: permutes_def, metis funpow_Suc_right permutes_compose)\n\nlemma funpow_diff:\n  assumes \"inj p\" and \"i \\<le> j\" \"(p ^^ i) a = (p ^^ j) a\" shows \"(p ^^ (j - i)) a = a\"\nproof -\n  have \"(p ^^ i) ((p ^^ (j - i)) a) = (p ^^ i) a\"\n    using assms(2-3) by (metis (no_types) add_diff_inverse_nat funpow_add not_le o_def)\n  thus ?thesis\n    unfolding inj_eq[OF inj_fn[OF assms(1)], of i] .\nqed\n\nlemma permutation_is_nilpotent:\n  assumes \"permutation p\" obtains n where \"(p ^^ n) = id\" and \"n > 0\"\nproof -\n  obtain S where \"finite S\" and \"p permutes S\"\n    using assms unfolding permutation_permutes by blast\n  hence \"\\<exists>n. (p ^^ n) = id \\<and> n > 0\"\n  proof (induct S arbitrary: p)\n    case empty thus ?case\n      using id_funpow[of 1] unfolding permutes_empty by blast\n  next\n    case (insert s S)\n    have \"(\\<lambda>n. (p ^^ n) s) ` UNIV \\<subseteq> (insert s S)\"\n      using permutes_in_image[OF permutes_funpow[OF insert(4)], of _ s] by auto\n    hence \"\\<not> inj_on (\\<lambda>n. (p ^^ n) s)  UNIV\"\n      using insert(1) infinite_iff_countable_subset unfolding sym[OF finite_insert, of S s] by metis\n    then obtain i j where ij: \"i < j\" \"(p ^^ i) s = (p ^^ j) s\"\n      unfolding inj_on_def by (metis nat_neq_iff) \n    hence \"(p ^^ (j - i)) s = s\"\n      using funpow_diff[OF permutes_inj[OF insert(4)]] le_eq_less_or_eq by blast\n    hence \"p ^^ (j - i) permutes S\"\n      using permutes_superset[OF permutes_funpow[OF insert(4), of \"j - i\"], of S] by auto\n    then obtain n where n: \"((p ^^ (j - i)) ^^ n) = id\" \"n > 0\"\n      using insert(3) by blast\n    thus ?case\n      using ij(1) nat_0_less_mult_iff zero_less_diff unfolding funpow_mult by metis \n  qed\n  thus thesis\n    using that by blast\nqed\n\nlemma permutation_is_nilpotent':\n  assumes \"permutation p\" obtains n where \"(p ^^ n) = id\" and \"n > m\"\nproof -\n  obtain n where \"(p ^^ n) = id\" and \"n > 0\"\n    using permutation_is_nilpotent[OF assms] by blast\n  then obtain k where \"n * k > m\"\n    by (metis dividend_less_times_div mult_Suc_right)\n  from \\<open>(p ^^ n) = id\\<close> have \"p ^^ (n * k) = id\"\n    by (induct k) (simp, metis funpow_mult id_funpow)\n  with \\<open>n * k > m\\<close> show thesis\n    using that by blast\nqed\n\n\nsubsubsection \\<open>Extraction of cycles from permutations\\<close>\n\ndefinition least_power :: \"('a \\<Rightarrow> 'a) \\<Rightarrow> 'a \\<Rightarrow> nat\"\n  where \"least_power f x = (LEAST n. (f ^^ n) x = x \\<and> n > 0)\"\n\nabbreviation support :: \"('a \\<Rightarrow> 'a) \\<Rightarrow> 'a \\<Rightarrow> 'a list\"\n  where \"support p x \\<equiv> map (\\<lambda>i. (p ^^ i) x) [0..< (least_power p x)]\"\n\n\nlemma least_powerI:\n  assumes \"(f ^^ n) x = x\" and \"n > 0\"\n  shows \"(f ^^ (least_power f x)) x = x\" and \"least_power f x > 0\"\n  using assms unfolding least_power_def by (metis (mono_tags, lifting) LeastI)+\n\nlemma least_power_le:\n  assumes \"(f ^^ n) x = x\" and \"n > 0\" shows \"least_power f x \\<le> n\"\n  using assms unfolding least_power_def by (simp add: Least_le)\n\nlemma least_power_of_permutation:\n  assumes \"permutation p\" shows \"(p ^^ (least_power p a)) a = a\" and \"least_power p a > 0\"\n  using permutation_is_nilpotent[OF assms] least_powerI by (metis id_apply)+\n\nlemma least_power_gt_one:\n  assumes \"permutation p\" and \"p a \\<noteq> a\" shows \"least_power p a > Suc 0\"\n  using least_power_of_permutation[OF assms(1)] assms(2)\n  by (metis Suc_lessI funpow.simps(2) funpow_simps_right(1) o_id) \n\nlemma least_power_minimal:\n  assumes \"(p ^^ n) a = a\" shows \"(least_power p a) dvd n\"\nproof (cases \"n = 0\", simp)\n  let ?lpow = \"least_power p\"\n\n  assume \"n \\<noteq> 0\" then have \"n > 0\" by simp\n  hence \"(p ^^ (?lpow a)) a = a\" and \"least_power p a > 0\"\n    using assms unfolding least_power_def by (metis (mono_tags, lifting) LeastI)+\n  hence aux_lemma: \"(p ^^ ((?lpow a) * k)) a = a\" for k :: nat\n    by (induct k) (simp_all add: funpow_add)\n\n  have \"(p ^^ (n mod ?lpow a)) ((p ^^ (n - (n mod ?lpow a))) a) = (p ^^ n) a\"\n    by (metis add_diff_inverse_nat funpow_add mod_less_eq_dividend not_less o_apply)\n  with \\<open>(p ^^ n) a = a\\<close> have \"(p ^^ (n mod ?lpow a)) a = a\"\n    using aux_lemma by (simp add: minus_mod_eq_mult_div) \n  hence \"?lpow a \\<le> n mod ?lpow a\" if \"n mod ?lpow a > 0\"\n    using least_power_le[OF _ that, of p a] by simp\n  with \\<open>least_power p a > 0\\<close> show \"(least_power p a) dvd n\"\n    using mod_less_divisor not_le by blast\nqed\n\nlemma least_power_dvd:\n  assumes \"permutation p\" shows \"(least_power p a) dvd n \\<longleftrightarrow> (p ^^ n) a = a\"\nproof\n  show \"(p ^^ n) a = a \\<Longrightarrow> (least_power p a) dvd n\"\n    using least_power_minimal[of _ p] by simp\nnext\n  have \"(p ^^ ((least_power p a) * k)) a = a\" for k :: nat\n    using least_power_of_permutation(1)[OF assms(1)] by (induct k) (simp_all add: funpow_add)\n  thus \"(least_power p a) dvd n \\<Longrightarrow> (p ^^ n) a = a\" by blast\nqed\n\ntheorem cycle_of_permutation:\n  assumes \"permutation p\" shows \"cycle (support p a)\"\nproof -\n  have \"(least_power p a) dvd (j - i)\" if \"i \\<le> j\" \"j < least_power p a\" and \"(p ^^ i) a = (p ^^ j) a\" for i j\n    using funpow_diff[OF bij_is_inj that(1,3)] assms by (simp add: permutation least_power_dvd)\n  moreover have \"i = j\" if \"i \\<le> j\" \"j < least_power p a\" and \"(least_power p a) dvd (j - i)\" for i j\n    using that le_eq_less_or_eq nat_dvd_not_less by auto\n  ultimately have \"inj_on (\\<lambda>i. (p ^^ i) a) {..< (least_power p a)}\"\n    unfolding inj_on_def by (metis le_cases lessThan_iff)\n  thus ?thesis\n    by (simp add: atLeast_upt distinct_map)\nqed\n\n\nsubsection \\<open>Decomposition on Cycles\\<close>\n\ntext \\<open>We show that a permutation can be decomposed on cycles\\<close>\n\nsubsubsection \\<open>Preliminaries\\<close>\n\nlemma support_set:\n  assumes \"permutation p\" shows \"set (support p a) = range (\\<lambda>i. (p ^^ i) a)\"\nproof\n  show \"set (support p a) \\<subseteq> range (\\<lambda>i. (p ^^ i) a)\"\n    by auto\nnext\n  show \"range (\\<lambda>i. (p ^^ i) a) \\<subseteq> set (support p a)\"\n  proof (auto)\n    fix i\n    have \"(p ^^ i) a = (p ^^ (i mod (least_power p a))) ((p ^^ (i - (i mod (least_power p a)))) a)\"\n      by (metis add_diff_inverse_nat funpow_add mod_less_eq_dividend not_le o_apply)\n    also have \" ... = (p ^^ (i mod (least_power p a))) a\"\n      using least_power_dvd[OF assms] by (metis dvd_minus_mod)\n    also have \" ... \\<in> (\\<lambda>i. (p ^^ i) a) ` {0..< (least_power p a)}\"\n      using least_power_of_permutation(2)[OF assms] by fastforce\n    finally show \"(p ^^ i) a \\<in> (\\<lambda>i. (p ^^ i) a) ` {0..< (least_power p a)}\" .\n  qed\nqed\n\nlemma disjoint_support:\n  assumes \"permutation p\" shows \"disjoint (range (\\<lambda>a. set (support p a)))\" (is \"disjoint ?A\")\nproof (rule disjointI)\n  { fix i j a b\n    assume \"set (support p a) \\<inter> set (support p b) \\<noteq> {}\" have \"set (support p a) \\<subseteq> set (support p b)\"\n      unfolding support_set[OF assms]\n    proof (auto)\n      from \\<open>set (support p a) \\<inter> set (support p b) \\<noteq> {}\\<close>\n      obtain i j where ij: \"(p ^^ i) a = (p ^^ j) b\"\n        by auto\n\n      fix k\n      have \"(p ^^ k) a = (p ^^ (k + (least_power p a) * l)) a\" for l\n        using least_power_dvd[OF assms] by (induct l) (simp, metis dvd_triv_left funpow_add o_def)\n      then obtain m where \"m \\<ge> i\" and \"(p ^^ m) a = (p ^^ k) a\"\n        using least_power_of_permutation(2)[OF assms]\n        by (metis dividend_less_times_div le_eq_less_or_eq mult_Suc_right trans_less_add2)\n      hence \"(p ^^ m) a = (p ^^ (m - i)) ((p ^^ i) a)\"\n        by (metis Nat.le_imp_diff_is_add funpow_add o_apply)\n      with \\<open>(p ^^ m) a = (p ^^ k) a\\<close> have \"(p ^^ k) a = (p ^^ ((m - i) + j)) b\"\n        unfolding ij by (simp add: funpow_add)\n      thus \"(p ^^ k) a \\<in> range (\\<lambda>i. (p ^^ i) b)\"\n        by blast\n    qed } note aux_lemma = this\n\n  fix supp_a supp_b\n  assume \"supp_a \\<in> ?A\" and \"supp_b \\<in> ?A\"\n  then obtain a b where a: \"supp_a = set (support p a)\" and b: \"supp_b = set (support p b)\"\n    by auto\n  assume \"supp_a \\<noteq> supp_b\" thus \"supp_a \\<inter> supp_b = {}\"\n    using aux_lemma unfolding a b by blast  \nqed\n\nlemma disjoint_support':\n  assumes \"permutation p\"\n  shows \"set (support p a) \\<inter> set (support p b) = {} \\<longleftrightarrow> a \\<notin> set (support p b)\"\nproof -\n  have \"a \\<in> set (support p a)\"\n    using least_power_of_permutation(2)[OF assms] by force\n  show ?thesis\n  proof\n    assume \"set (support p a) \\<inter> set (support p b) = {}\"\n    with \\<open>a \\<in> set (support p a)\\<close> show \"a \\<notin> set (support p b)\"\n      by blast\n  next\n    assume \"a \\<notin> set (support p b)\" show \"set (support p a) \\<inter> set (support p b) = {}\"\n    proof (rule ccontr)\n      assume \"set (support p a) \\<inter> set (support p b) \\<noteq> {}\"\n      hence \"set (support p a) = set (support p b)\"\n        using disjoint_support[OF assms] by (meson UNIV_I disjoint_def image_iff)\n      with \\<open>a \\<in> set (support p a)\\<close> and \\<open>a \\<notin> set (support p b)\\<close> show False\n        by simp\n    qed\n  qed\nqed\n\nlemma support_coverture:\n  assumes \"permutation p\" shows \"\\<Union> { set (support p a) | a. p a \\<noteq> a } = { a. p a \\<noteq> a }\"\nproof\n  show \"{ a. p a \\<noteq> a } \\<subseteq> \\<Union> { set (support p a) | a. p a \\<noteq> a }\"\n  proof\n    fix a assume \"a \\<in> { a. p a \\<noteq> a }\"\n    have \"a \\<in> set (support p a)\"\n      using least_power_of_permutation(2)[OF assms, of a] by force\n    with \\<open>a \\<in> { a. p a \\<noteq> a }\\<close> show \"a \\<in> \\<Union> { set (support p a) | a. p a \\<noteq> a }\"\n      by blast\n  qed\nnext\n  show \"\\<Union> { set (support p a) | a. p a \\<noteq> a } \\<subseteq> { a. p a \\<noteq> a }\"\n  proof\n    fix b assume \"b \\<in> \\<Union> { set (support p a) | a. p a \\<noteq> a }\"\n    then obtain a i where \"p a \\<noteq> a\" and \"(p ^^ i) a = b\"\n      by auto\n    have \"p a = a\" if \"(p ^^ i) a = (p ^^ Suc i) a\"\n      using funpow_diff[OF bij_is_inj _ that] assms unfolding permutation by simp\n    with \\<open>p a \\<noteq> a\\<close> and \\<open>(p ^^ i) a = b\\<close> show \"b \\<in> { a. p a \\<noteq> a }\"\n      by auto\n  qed\nqed\n\ntheorem cycle_restrict:\n  assumes \"permutation p\" and \"b \\<in> set (support p a)\" shows \"p b = (cycle_of_list (support p a)) b\"\nproof -\n  note least_power_props [simp] = least_power_of_permutation[OF assms(1)]\n\n  have \"map (cycle_of_list (support p a)) (support p a) = rotate1 (support p a)\"\n    using cyclic_rotation[OF cycle_of_permutation[OF assms(1)], of 1 a] by simp\n  hence \"map (cycle_of_list (support p a)) (support p a) = tl (support p a) @ [ a ]\"\n    by (simp add: hd_map rotate1_hd_tl)\n  also have \" ... = map p (support p a)\"\n  proof (rule nth_equalityI, auto)\n    fix i assume \"i < least_power p a\" show \"(tl (support p a) @ [a]) ! i = p ((p ^^ i) a)\"\n    proof (cases)\n      assume i: \"i = least_power p a - 1\"\n      hence \"(tl (support p a) @ [ a ]) ! i = a\"\n        by (metis (no_types, lifting) diff_zero length_map length_tl length_upt nth_append_length)\n      also have \" ... = p ((p ^^ i) a)\"\n        by (metis (mono_tags, opaque_lifting) least_power_props i Suc_diff_1 funpow_simps_right(2) funpow_swap1 o_apply)\n      finally show ?thesis .\n    next\n      assume \"i \\<noteq> least_power p a - 1\"\n      with \\<open>i < least_power p a\\<close> have \"i < least_power p a - 1\"\n        by simp\n      hence \"(tl (support p a) @ [ a ]) ! i = (p ^^ (Suc i)) a\"\n        by (metis One_nat_def Suc_eq_plus1 add.commute length_map length_upt map_tl nth_append nth_map_upt tl_upt)\n      thus ?thesis\n        by simp\n    qed\n  qed\n  finally have \"map (cycle_of_list (support p a)) (support p a) = map p (support p a)\" .\n  thus ?thesis\n    using assms(2) by auto\nqed\n\n\nsubsubsection\\<open>Decomposition\\<close>\n\ninductive cycle_decomp :: \"'a set \\<Rightarrow> ('a \\<Rightarrow> 'a) \\<Rightarrow> bool\"\n  where\n    empty:  \"cycle_decomp {} id\"\n  | comp: \"\\<lbrakk> cycle_decomp I p; cycle cs; set cs \\<inter> I = {} \\<rbrakk> \\<Longrightarrow>\n             cycle_decomp (set cs \\<union> I) ((cycle_of_list cs) \\<circ> p)\"\n\n\nlemma semidecomposition:\n  assumes \"p permutes S\" and \"finite S\"\n  shows \"(\\<lambda>y. if y \\<in> (S - set (support p a)) then p y else y) permutes (S - set (support p a))\"\nproof (rule bij_imp_permutes)\n  show \"(if b \\<in> (S - set (support p a)) then p b else b) = b\" if \"b \\<notin> S - set (support p a)\" for b\n    using that by auto\nnext\n  have is_permutation: \"permutation p\"\n    using assms unfolding permutation_permutes by blast\n\n  let ?q = \"\\<lambda>y. if y \\<in> (S - set (support p a)) then p y else y\"\n  show \"bij_betw ?q (S - set (support p a)) (S - set (support p a))\"\n  proof (rule bij_betw_imageI)\n    show \"inj_on ?q (S - set (support p a))\"\n      using permutes_inj[OF assms(1)] unfolding inj_on_def by auto\n  next\n    have aux_lemma: \"set (support p s) \\<subseteq> (S - set (support p a))\" if \"s \\<in> S - set (support p a)\" for s\n    proof -\n      have \"(p ^^ i) s \\<in> S\" for i\n        using that unfolding permutes_in_image[OF permutes_funpow[OF assms(1)]] by simp\n      thus ?thesis\n        using that disjoint_support'[OF is_permutation, of s a] by auto\n    qed\n    have \"(p ^^ 1) s \\<in> set (support p s)\" for s\n      unfolding support_set[OF is_permutation] by blast\n    hence \"p s \\<in> set (support p s)\" for s\n      by simp\n    hence \"p ` (S - set (support p a)) \\<subseteq> S - set (support p a)\"\n      using aux_lemma by blast\n    moreover have \"(p ^^ ((least_power p s) - 1)) s \\<in> set (support p s)\" for s\n      unfolding support_set[OF is_permutation] by blast\n    hence \"\\<exists>s' \\<in> set (support p s). p s' = s\" for s\n      using least_power_of_permutation[OF is_permutation] by (metis Suc_diff_1 funpow.simps(2) o_apply)\n    hence \"S - set (support p a) \\<subseteq> p ` (S - set (support p a))\"\n      using aux_lemma\n      by (clarsimp simp add: image_iff) (metis image_subset_iff)\n    ultimately show \"?q ` (S - set (support p a)) = (S - set (support p a))\"\n      by auto\n  qed\nqed\n\ntheorem cycle_decomposition:\n  assumes \"p permutes S\" and \"finite S\" shows \"cycle_decomp S p\"\n  using assms\nproof(induct \"card S\" arbitrary: S p rule: less_induct)\n  case less show ?case\n  proof (cases)\n    assume \"S = {}\" thus ?thesis\n      using empty less(2) by auto\n  next\n    have is_permutation: \"permutation p\"\n      using less(2-3) unfolding permutation_permutes by blast\n\n    assume \"S \\<noteq> {}\" then obtain s where \"s \\<in> S\"\n      by blast\n    define q where \"q = (\\<lambda>y. if y \\<in> (S - set (support p s)) then p y else y)\"\n    have \"(cycle_of_list (support p s) \\<circ> q) = p\"\n    proof\n      fix a\n      consider \"a \\<in> S - set (support p s)\" | \"a \\<in> set (support p s)\" | \"a \\<notin> S\" \"a \\<notin> set (support p s)\"\n        by blast\n      thus \"((cycle_of_list (support p s) \\<circ> q)) a = p a\"\n      proof cases\n        case 1\n        have \"(p ^^ 1) a \\<in> set (support p a)\"\n          unfolding support_set[OF is_permutation] by blast\n        with \\<open>a \\<in> S - set (support p s)\\<close> have \"p a \\<notin> set (support p s)\"\n          using disjoint_support'[OF is_permutation, of a s] by auto\n        with \\<open>a \\<in> S - set (support p s)\\<close> show ?thesis\n          using id_outside_supp[of _ \"support p s\"] unfolding q_def by simp\n      next\n        case 2 thus ?thesis\n          using cycle_restrict[OF is_permutation] unfolding q_def by simp\n      next\n        case 3 thus ?thesis\n          using id_outside_supp[OF 3(2)] less(2) permutes_not_in unfolding q_def by fastforce\n      qed\n    qed\n\n    moreover from \\<open>s \\<in> S\\<close> have \"(p ^^ i) s \\<in> S\" for i\n      unfolding permutes_in_image[OF permutes_funpow[OF less(2)]] .\n    hence \"set (support p s) \\<union> (S - set (support p s)) = S\"\n      by auto\n\n    moreover have \"s \\<in> set (support p s)\"\n      using least_power_of_permutation[OF is_permutation] by force\n    with \\<open>s \\<in> S\\<close> have \"card (S - set (support p s)) < card S\"\n      using less(3) by (metis DiffE card_seteq linorder_not_le subsetI)\n    hence \"cycle_decomp (S - set (support p s)) q\"\n      using less(1)[OF _ semidecomposition[OF less(2-3)], of s] less(3) unfolding q_def by blast\n\n    moreover show ?thesis\n      using comp[OF calculation(3) cycle_of_permutation[OF is_permutation], of s]\n      unfolding calculation(1-2) by blast  \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/Combinatorics/Cycles.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8479677737461007, "lm_q2_score": 0.8723473813156294, "lm_q1q2_score": 0.739722466867455}}
{"text": "(*  Title:      HOL/Deriv.thy\n    Author:     Jacques D. Fleuriot, University of Cambridge, 1998\n    Author:     Brian Huffman\n    Author:     Lawrence C Paulson, 2004\n    Author:     Benjamin Porter, 2005\n*)\n\nsection \\<open>Differentiation\\<close>\n\ntheory Deriv\n  imports Limits\nbegin\n\nsubsection \\<open>Frechet derivative\\<close>\n\ndefinition has_derivative :: \"('a::real_normed_vector \\<Rightarrow> 'b::real_normed_vector) \\<Rightarrow>\n    ('a \\<Rightarrow> 'b) \\<Rightarrow> 'a filter \\<Rightarrow> bool\"  (infix \"(has'_derivative)\" 50)\n  where \"(f has_derivative f') F \\<longleftrightarrow>\n    bounded_linear f' \\<and>\n    ((\\<lambda>y. ((f y - f (Lim F (\\<lambda>x. x))) - f' (y - Lim F (\\<lambda>x. x))) /\\<^sub>R norm (y - Lim F (\\<lambda>x. x))) \\<longlongrightarrow> 0) F\"\n\ntext \\<open>\n  Usually the filter \\<^term>\\<open>F\\<close> is \\<^term>\\<open>at x within s\\<close>.  \\<^term>\\<open>(f has_derivative D)\n  (at x within s)\\<close> means: \\<^term>\\<open>D\\<close> is the derivative of function \\<^term>\\<open>f\\<close> at point \\<^term>\\<open>x\\<close>\n  within the set \\<^term>\\<open>s\\<close>. Where \\<^term>\\<open>s\\<close> is used to express left or right sided derivatives. In\n  most cases \\<^term>\\<open>s\\<close> is either a variable or \\<^term>\\<open>UNIV\\<close>.\n\\<close>\n\ntext \\<open>These are the only cases we'll care about, probably.\\<close>\n\nlemma has_derivative_within: \"(f has_derivative f') (at x within s) \\<longleftrightarrow>\n    bounded_linear f' \\<and> ((\\<lambda>y. (1 / norm(y - x)) *\\<^sub>R (f y - (f x + f' (y - x)))) \\<longlongrightarrow> 0) (at x within s)\"\n  unfolding has_derivative_def tendsto_iff\n  by (subst eventually_Lim_ident_at) (auto simp add: field_simps)\n\nlemma has_derivative_eq_rhs: \"(f has_derivative f') F \\<Longrightarrow> f' = g' \\<Longrightarrow> (f has_derivative g') F\"\n  by simp\n\ndefinition has_field_derivative :: \"('a::real_normed_field \\<Rightarrow> 'a) \\<Rightarrow> 'a \\<Rightarrow> 'a filter \\<Rightarrow> bool\"\n    (infix \"(has'_field'_derivative)\" 50)\n  where \"(f has_field_derivative D) F \\<longleftrightarrow> (f has_derivative (*) D) F\"\n\nlemma DERIV_cong: \"(f has_field_derivative X) F \\<Longrightarrow> X = Y \\<Longrightarrow> (f has_field_derivative Y) F\"\n  by simp\n\ndefinition has_vector_derivative :: \"(real \\<Rightarrow> 'b::real_normed_vector) \\<Rightarrow> 'b \\<Rightarrow> real filter \\<Rightarrow> bool\"\n    (infix \"has'_vector'_derivative\" 50)\n  where \"(f has_vector_derivative f') net \\<longleftrightarrow> (f has_derivative (\\<lambda>x. x *\\<^sub>R f')) net\"\n\nlemma has_vector_derivative_eq_rhs:\n  \"(f has_vector_derivative X) F \\<Longrightarrow> X = Y \\<Longrightarrow> (f has_vector_derivative Y) F\"\n  by simp\n\nnamed_theorems derivative_intros \"structural introduction rules for derivatives\"\nsetup \\<open>\n  let\n    val eq_thms = @{thms has_derivative_eq_rhs DERIV_cong has_vector_derivative_eq_rhs}\n    fun eq_rule thm = get_first (try (fn eq_thm => eq_thm OF [thm])) eq_thms\n  in\n    Global_Theory.add_thms_dynamic\n      (\\<^binding>\\<open>derivative_eq_intros\\<close>,\n        fn context =>\n          Named_Theorems.get (Context.proof_of context) \\<^named_theorems>\\<open>derivative_intros\\<close>\n          |> map_filter eq_rule)\n  end\n\\<close>\n\ntext \\<open>\n  The following syntax is only used as a legacy syntax.\n\\<close>\nabbreviation (input)\n  FDERIV :: \"('a::real_normed_vector \\<Rightarrow> 'b::real_normed_vector) \\<Rightarrow> 'a \\<Rightarrow>  ('a \\<Rightarrow> 'b) \\<Rightarrow> bool\"\n  (\"(FDERIV (_)/ (_)/ :> (_))\" [1000, 1000, 60] 60)\n  where \"FDERIV f x :> f' \\<equiv> (f has_derivative f') (at x)\"\n\nlemma has_derivative_bounded_linear: \"(f has_derivative f') F \\<Longrightarrow> bounded_linear f'\"\n  by (simp add: has_derivative_def)\n\nlemma has_derivative_linear: \"(f has_derivative f') F \\<Longrightarrow> linear f'\"\n  using bounded_linear.linear[OF has_derivative_bounded_linear] .\n\nlemma has_derivative_ident[derivative_intros, simp]: \"((\\<lambda>x. x) has_derivative (\\<lambda>x. x)) F\"\n  by (simp add: has_derivative_def)\n\nlemma has_derivative_id [derivative_intros, simp]: \"(id has_derivative id) F\"\n  by (metis eq_id_iff has_derivative_ident)\n\nlemma shift_has_derivative_id: \"((+) d has_derivative (\\<lambda>x. x)) F\"\n  using has_derivative_def by fastforce\n\nlemma has_derivative_const[derivative_intros, simp]: \"((\\<lambda>x. c) has_derivative (\\<lambda>x. 0)) F\"\n  by (simp add: has_derivative_def)\n\nlemma (in bounded_linear) bounded_linear: \"bounded_linear f\" ..\n\nlemma (in bounded_linear) has_derivative:\n  \"(g has_derivative g') F \\<Longrightarrow> ((\\<lambda>x. f (g x)) has_derivative (\\<lambda>x. f (g' x))) F\"\n  unfolding has_derivative_def\n  by (auto simp add: bounded_linear_compose [OF bounded_linear] scaleR diff dest: tendsto)\n\nlemmas has_derivative_scaleR_right [derivative_intros] =\n  bounded_linear.has_derivative [OF bounded_linear_scaleR_right]\n\nlemmas has_derivative_scaleR_left [derivative_intros] =\n  bounded_linear.has_derivative [OF bounded_linear_scaleR_left]\n\nlemmas has_derivative_mult_right [derivative_intros] =\n  bounded_linear.has_derivative [OF bounded_linear_mult_right]\n\nlemmas has_derivative_mult_left [derivative_intros] =\n  bounded_linear.has_derivative [OF bounded_linear_mult_left]\n\nlemmas has_derivative_of_real[derivative_intros, simp] = \n  bounded_linear.has_derivative[OF bounded_linear_of_real] \n\nlemma has_derivative_add[simp, derivative_intros]:\n  assumes f: \"(f has_derivative f') F\"\n    and g: \"(g has_derivative g') F\"\n  shows \"((\\<lambda>x. f x + g x) has_derivative (\\<lambda>x. f' x + g' x)) F\"\n  unfolding has_derivative_def\nproof safe\n  let ?x = \"Lim F (\\<lambda>x. x)\"\n  let ?D = \"\\<lambda>f f' y. ((f y - f ?x) - f' (y - ?x)) /\\<^sub>R norm (y - ?x)\"\n  have \"((\\<lambda>x. ?D f f' x + ?D g g' x) \\<longlongrightarrow> (0 + 0)) F\"\n    using f g by (intro tendsto_add) (auto simp: has_derivative_def)\n  then show \"(?D (\\<lambda>x. f x + g x) (\\<lambda>x. f' x + g' x) \\<longlongrightarrow> 0) F\"\n    by (simp add: field_simps scaleR_add_right scaleR_diff_right)\nqed (blast intro: bounded_linear_add f g has_derivative_bounded_linear)\n\nlemma has_derivative_sum[simp, derivative_intros]:\n  \"(\\<And>i. i \\<in> I \\<Longrightarrow> (f i has_derivative f' i) F) \\<Longrightarrow>\n    ((\\<lambda>x. \\<Sum>i\\<in>I. f i x) has_derivative (\\<lambda>x. \\<Sum>i\\<in>I. f' i x)) F\"\n  by (induct I rule: infinite_finite_induct) simp_all\n\nlemma has_derivative_minus[simp, derivative_intros]:\n  \"(f has_derivative f') F \\<Longrightarrow> ((\\<lambda>x. - f x) has_derivative (\\<lambda>x. - f' x)) F\"\n  using has_derivative_scaleR_right[of f f' F \"-1\"] by simp\n\nlemma has_derivative_diff[simp, derivative_intros]:\n  \"(f has_derivative f') F \\<Longrightarrow> (g has_derivative g') F \\<Longrightarrow>\n    ((\\<lambda>x. f x - g x) has_derivative (\\<lambda>x. f' x - g' x)) F\"\n  by (simp only: diff_conv_add_uminus has_derivative_add has_derivative_minus)\n\nlemma has_derivative_at_within:\n  \"(f has_derivative f') (at x within s) \\<longleftrightarrow>\n    (bounded_linear f' \\<and> ((\\<lambda>y. ((f y - f x) - f' (y - x)) /\\<^sub>R norm (y - x)) \\<longlongrightarrow> 0) (at x within s))\"\nproof (cases \"at x within s = bot\")\n  case True\n  then show ?thesis\n    by (metis (no_types, lifting) has_derivative_within tendsto_bot)\nnext\n  case False\n  then show ?thesis\n  by (simp add: Lim_ident_at has_derivative_def)\nqed\n\nlemma has_derivative_iff_norm:\n  \"(f has_derivative f') (at x within s) \\<longleftrightarrow>\n    bounded_linear f' \\<and> ((\\<lambda>y. norm ((f y - f x) - f' (y - x)) / norm (y - x)) \\<longlongrightarrow> 0) (at x within s)\"\n  using tendsto_norm_zero_iff[of _ \"at x within s\", where 'b=\"'b\", symmetric]\n  by (simp add: has_derivative_at_within divide_inverse ac_simps)\n\nlemma has_derivative_at:\n  \"(f has_derivative D) (at x) \\<longleftrightarrow>\n    (bounded_linear D \\<and> (\\<lambda>h. norm (f (x + h) - f x - D h) / norm h) \\<midarrow>0\\<rightarrow> 0)\"\n  by (simp add: has_derivative_iff_norm LIM_offset_zero_iff)\n\nlemma field_has_derivative_at:\n  fixes x :: \"'a::real_normed_field\"\n  shows \"(f has_derivative (*) D) (at x) \\<longleftrightarrow> (\\<lambda>h. (f (x + h) - f x) / h) \\<midarrow>0\\<rightarrow> D\" (is \"?lhs = ?rhs\")\nproof -\n  have \"?lhs = (\\<lambda>h. norm (f (x + h) - f x - D * h) / norm h) \\<midarrow>0 \\<rightarrow> 0\"\n    by (simp add: bounded_linear_mult_right has_derivative_at)\n  also have \"... = (\\<lambda>y. norm ((f (x + y) - f x - D * y) / y)) \\<midarrow>0\\<rightarrow> 0\"\n    by (simp cong: LIM_cong flip: nonzero_norm_divide)\n  also have \"... = (\\<lambda>y. norm ((f (x + y) - f x) / y - D / y * y)) \\<midarrow>0\\<rightarrow> 0\"\n    by (simp only: diff_divide_distrib times_divide_eq_left [symmetric])\n  also have \"... = ?rhs\"\n    by (simp add: tendsto_norm_zero_iff LIM_zero_iff cong: LIM_cong)\n  finally show ?thesis .\nqed\n\nlemma has_derivative_iff_Ex:\n  \"(f has_derivative f') (at x) \\<longleftrightarrow>\n    bounded_linear f' \\<and> (\\<exists>e. (\\<forall>h. f (x+h) = f x + f' h + e h) \\<and> ((\\<lambda>h. norm (e h) / norm h) \\<longlongrightarrow> 0) (at 0))\"\n  unfolding has_derivative_at by force\n\nlemma has_derivative_at_within_iff_Ex:\n  assumes \"x \\<in> S\" \"open S\"\n  shows \"(f has_derivative f') (at x within S) \\<longleftrightarrow>\n         bounded_linear f' \\<and> (\\<exists>e. (\\<forall>h. x+h \\<in> S \\<longrightarrow> f (x+h) = f x + f' h + e h) \\<and> ((\\<lambda>h. norm (e h) / norm h) \\<longlongrightarrow> 0) (at 0))\"\n    (is \"?lhs = ?rhs\")\nproof safe\n  show \"bounded_linear f'\"\n    if \"(f has_derivative f') (at x within S)\"\n    using has_derivative_bounded_linear that by blast\n  show \"\\<exists>e. (\\<forall>h. x + h \\<in> S \\<longrightarrow> f (x + h) = f x + f' h + e h) \\<and> (\\<lambda>h. norm (e h) / norm h) \\<midarrow>0\\<rightarrow> 0\"\n    if \"(f has_derivative f') (at x within S)\"\n    by (metis (full_types) assms that has_derivative_iff_Ex at_within_open)\n  show \"(f has_derivative f') (at x within S)\"\n    if \"bounded_linear f'\"\n      and eq [rule_format]: \"\\<forall>h. x + h \\<in> S \\<longrightarrow> f (x + h) = f x + f' h + e h\"\n      and 0: \"(\\<lambda>h. norm (e (h::'a)::'b) / norm h) \\<midarrow>0\\<rightarrow> 0\"\n    for e \n  proof -\n    have 1: \"f y - f x = f' (y-x) + e (y-x)\" if \"y \\<in> S\" for y\n      using eq [of \"y-x\"] that by simp\n    have 2: \"((\\<lambda>y. norm (e (y-x)) / norm (y - x)) \\<longlongrightarrow> 0) (at x within S)\"\n      by (simp add: \"0\" assms tendsto_offset_zero_iff)\n    have \"((\\<lambda>y. norm (f y - f x - f' (y - x)) / norm (y - x)) \\<longlongrightarrow> 0) (at x within S)\"\n      by (simp add: Lim_cong_within 1 2)\n    then show ?thesis\n      by (simp add: has_derivative_iff_norm \\<open>bounded_linear f'\\<close>)\n  qed\nqed\n\nlemma has_derivativeI:\n  \"bounded_linear f' \\<Longrightarrow>\n    ((\\<lambda>y. ((f y - f x) - f' (y - x)) /\\<^sub>R norm (y - x)) \\<longlongrightarrow> 0) (at x within s) \\<Longrightarrow>\n    (f has_derivative f') (at x within s)\"\n  by (simp add: has_derivative_at_within)\n\nlemma has_derivativeI_sandwich:\n  assumes e: \"0 < e\"\n    and bounded: \"bounded_linear f'\"\n    and sandwich: \"(\\<And>y. y \\<in> s \\<Longrightarrow> y \\<noteq> x \\<Longrightarrow> dist y x < e \\<Longrightarrow>\n      norm ((f y - f x) - f' (y - x)) / norm (y - x) \\<le> H y)\"\n    and \"(H \\<longlongrightarrow> 0) (at x within s)\"\n  shows \"(f has_derivative f') (at x within s)\"\n  unfolding has_derivative_iff_norm\nproof safe\n  show \"((\\<lambda>y. norm (f y - f x - f' (y - x)) / norm (y - x)) \\<longlongrightarrow> 0) (at x within s)\"\n  proof (rule tendsto_sandwich[where f=\"\\<lambda>x. 0\"])\n    show \"(H \\<longlongrightarrow> 0) (at x within s)\" by fact\n    show \"eventually (\\<lambda>n. norm (f n - f x - f' (n - x)) / norm (n - x) \\<le> H n) (at x within s)\"\n      unfolding eventually_at using e sandwich by auto\n  qed (auto simp: le_divide_eq)\nqed fact\n\nlemma has_derivative_subset:\n  \"(f has_derivative f') (at x within s) \\<Longrightarrow> t \\<subseteq> s \\<Longrightarrow> (f has_derivative f') (at x within t)\"\n  by (auto simp add: has_derivative_iff_norm intro: tendsto_within_subset)\n\nlemma has_derivative_within_singleton_iff:\n  \"(f has_derivative g) (at x within {x}) \\<longleftrightarrow> bounded_linear g\"\n  by (auto intro!: has_derivativeI_sandwich[where e=1] has_derivative_bounded_linear)\n\n\nsubsubsection \\<open>Limit transformation for derivatives\\<close>\n\nlemma has_derivative_transform_within:\n  assumes \"(f has_derivative f') (at x within s)\"\n    and \"0 < d\"\n    and \"x \\<in> s\"\n    and \"\\<And>x'. \\<lbrakk>x' \\<in> s; dist x' x < d\\<rbrakk> \\<Longrightarrow> f x' = g x'\"\n  shows \"(g has_derivative f') (at x within s)\"\n  using assms\n  unfolding has_derivative_within\n  by (force simp add: intro: Lim_transform_within)\n\nlemma has_derivative_transform_within_open:\n  assumes \"(f has_derivative f') (at x within t)\"\n    and \"open s\"\n    and \"x \\<in> s\"\n    and \"\\<And>x. x\\<in>s \\<Longrightarrow> f x = g x\"\n  shows \"(g has_derivative f') (at x within t)\"\n  using assms unfolding has_derivative_within\n  by (force simp add: intro: Lim_transform_within_open)\n\nlemma has_derivative_transform:\n  assumes \"x \\<in> s\" \"\\<And>x. x \\<in> s \\<Longrightarrow> g x = f x\"\n  assumes \"(f has_derivative f') (at x within s)\"\n  shows \"(g has_derivative f') (at x within s)\"\n  using assms\n  by (intro has_derivative_transform_within[OF _ zero_less_one, where g=g]) auto\n\nlemma has_derivative_transform_eventually:\n  assumes \"(f has_derivative f') (at x within s)\"\n    \"(\\<forall>\\<^sub>F x' in at x within s. f x' = g x')\"\n  assumes \"f x = g x\" \"x \\<in> s\"\n  shows \"(g has_derivative f') (at x within s)\"\n  using assms\nproof -\n  from assms(2,3) obtain d where \"d > 0\" \"\\<And>x'. x' \\<in> s \\<Longrightarrow> dist x' x < d \\<Longrightarrow> f x' = g x'\"\n    by (force simp: eventually_at)\n  from has_derivative_transform_within[OF assms(1) this(1) assms(4) this(2)]\n  show ?thesis .\nqed\n\nlemma has_field_derivative_transform_within:\n  assumes \"(f has_field_derivative f') (at a within S)\"\n    and \"0 < d\"\n    and \"a \\<in> S\"\n    and \"\\<And>x. \\<lbrakk>x \\<in> S; dist x a < d\\<rbrakk> \\<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 (metis has_derivative_transform_within)\n\nlemma has_field_derivative_transform_within_open:\n  assumes \"(f has_field_derivative f') (at a)\"\n    and \"open S\" \"a \\<in> S\"\n    and \"\\<And>x. x \\<in> S \\<Longrightarrow> f x = g x\"\n  shows \"(g has_field_derivative f') (at a)\"\n  using assms unfolding has_field_derivative_def\n  by (metis has_derivative_transform_within_open)\n\n\nsubsection \\<open>Continuity\\<close>\n\nlemma has_derivative_continuous:\n  assumes f: \"(f has_derivative f') (at x within s)\"\n  shows \"continuous (at x within s) f\"\nproof -\n  from f interpret F: bounded_linear f'\n    by (rule has_derivative_bounded_linear)\n  note F.tendsto[tendsto_intros]\n  let ?L = \"\\<lambda>f. (f \\<longlongrightarrow> 0) (at x within s)\"\n  have \"?L (\\<lambda>y. norm ((f y - f x) - f' (y - x)) / norm (y - x))\"\n    using f unfolding has_derivative_iff_norm by blast\n  then have \"?L (\\<lambda>y. norm ((f y - f x) - f' (y - x)) / norm (y - x) * norm (y - x))\" (is ?m)\n    by (rule tendsto_mult_zero) (auto intro!: tendsto_eq_intros)\n  also have \"?m \\<longleftrightarrow> ?L (\\<lambda>y. norm ((f y - f x) - f' (y - x)))\"\n    by (intro filterlim_cong) (simp_all add: eventually_at_filter)\n  finally have \"?L (\\<lambda>y. (f y - f x) - f' (y - x))\"\n    by (rule tendsto_norm_zero_cancel)\n  then have \"?L (\\<lambda>y. ((f y - f x) - f' (y - x)) + f' (y - x))\"\n    by (rule tendsto_eq_intros) (auto intro!: tendsto_eq_intros simp: F.zero)\n  then have \"?L (\\<lambda>y. f y - f x)\"\n    by simp\n  from tendsto_add[OF this tendsto_const, of \"f x\"] show ?thesis\n    by (simp add: continuous_within)\nqed\n\n\nsubsection \\<open>Composition\\<close>\n\nlemma tendsto_at_iff_tendsto_nhds_within:\n  \"f x = y \\<Longrightarrow> (f \\<longlongrightarrow> y) (at x within s) \\<longleftrightarrow> (f \\<longlongrightarrow> y) (inf (nhds x) (principal s))\"\n  unfolding tendsto_def eventually_inf_principal eventually_at_filter\n  by (intro ext all_cong imp_cong) (auto elim!: eventually_mono)\n\nlemma has_derivative_in_compose:\n  assumes f: \"(f has_derivative f') (at x within s)\"\n    and g: \"(g has_derivative g') (at (f x) within (f`s))\"\n  shows \"((\\<lambda>x. g (f x)) has_derivative (\\<lambda>x. g' (f' x))) (at x within s)\"\nproof -\n  from f interpret F: bounded_linear f'\n    by (rule has_derivative_bounded_linear)\n  from g interpret G: bounded_linear g'\n    by (rule has_derivative_bounded_linear)\n  from F.bounded obtain kF where kF: \"\\<And>x. norm (f' x) \\<le> norm x * kF\"\n    by fast\n  from G.bounded obtain kG where kG: \"\\<And>x. norm (g' x) \\<le> norm x * kG\"\n    by fast\n  note G.tendsto[tendsto_intros]\n\n  let ?L = \"\\<lambda>f. (f \\<longlongrightarrow> 0) (at x within s)\"\n  let ?D = \"\\<lambda>f f' x y. (f y - f x) - f' (y - x)\"\n  let ?N = \"\\<lambda>f f' x y. norm (?D f f' x y) / norm (y - x)\"\n  let ?gf = \"\\<lambda>x. g (f x)\" and ?gf' = \"\\<lambda>x. g' (f' x)\"\n  define Nf where \"Nf = ?N f f' x\"\n  define Ng where [abs_def]: \"Ng y = ?N g g' (f x) (f y)\" for y\n\n  show ?thesis\n  proof (rule has_derivativeI_sandwich[of 1])\n    show \"bounded_linear (\\<lambda>x. g' (f' x))\"\n      using f g by (blast intro: bounded_linear_compose has_derivative_bounded_linear)\n  next\n    fix y :: 'a\n    assume neq: \"y \\<noteq> x\"\n    have \"?N ?gf ?gf' x y = norm (g' (?D f f' x y) + ?D g g' (f x) (f y)) / norm (y - x)\"\n      by (simp add: G.diff G.add field_simps)\n    also have \"\\<dots> \\<le> norm (g' (?D f f' x y)) / norm (y - x) + Ng y * (norm (f y - f x) / norm (y - x))\"\n      by (simp add: add_divide_distrib[symmetric] divide_right_mono norm_triangle_ineq G.zero Ng_def)\n    also have \"\\<dots> \\<le> Nf y * kG + Ng y * (Nf y + kF)\"\n    proof (intro add_mono mult_left_mono)\n      have \"norm (f y - f x) = norm (?D f f' x y + f' (y - x))\"\n        by simp\n      also have \"\\<dots> \\<le> norm (?D f f' x y) + norm (f' (y - x))\"\n        by (rule norm_triangle_ineq)\n      also have \"\\<dots> \\<le> norm (?D f f' x y) + norm (y - x) * kF\"\n        using kF by (intro add_mono) simp\n      finally show \"norm (f y - f x) / norm (y - x) \\<le> Nf y + kF\"\n        by (simp add: neq Nf_def field_simps)\n    qed (use kG in \\<open>simp_all add: Ng_def Nf_def neq zero_le_divide_iff field_simps\\<close>)\n    finally show \"?N ?gf ?gf' x y \\<le> Nf y * kG + Ng y * (Nf y + kF)\" .\n  next\n    have [tendsto_intros]: \"?L Nf\"\n      using f unfolding has_derivative_iff_norm Nf_def ..\n    from f have \"(f \\<longlongrightarrow> f x) (at x within s)\"\n      by (blast intro: has_derivative_continuous continuous_within[THEN iffD1])\n    then have f': \"LIM x at x within s. f x :> inf (nhds (f x)) (principal (f`s))\"\n      unfolding filterlim_def\n      by (simp add: eventually_filtermap eventually_at_filter le_principal)\n\n    have \"((?N g  g' (f x)) \\<longlongrightarrow> 0) (at (f x) within f`s)\"\n      using g unfolding has_derivative_iff_norm ..\n    then have g': \"((?N g  g' (f x)) \\<longlongrightarrow> 0) (inf (nhds (f x)) (principal (f`s)))\"\n      by (rule tendsto_at_iff_tendsto_nhds_within[THEN iffD1, rotated]) simp\n\n    have [tendsto_intros]: \"?L Ng\"\n      unfolding Ng_def by (rule filterlim_compose[OF g' f'])\n    show \"((\\<lambda>y. Nf y * kG + Ng y * (Nf y + kF)) \\<longlongrightarrow> 0) (at x within s)\"\n      by (intro tendsto_eq_intros) auto\n  qed simp\nqed\n\nlemma has_derivative_compose:\n  \"(f has_derivative f') (at x within s) \\<Longrightarrow> (g has_derivative g') (at (f x)) \\<Longrightarrow>\n  ((\\<lambda>x. g (f x)) has_derivative (\\<lambda>x. g' (f' x))) (at x within s)\"\n  by (blast intro: has_derivative_in_compose has_derivative_subset)\n\nlemma has_derivative_in_compose2:\n  assumes \"\\<And>x. x \\<in> t \\<Longrightarrow> (g has_derivative g' x) (at x within t)\"\n  assumes \"f ` s \\<subseteq> t\" \"x \\<in> s\"\n  assumes \"(f has_derivative f') (at x within s)\"\n  shows \"((\\<lambda>x. g (f x)) has_derivative (\\<lambda>y. g' (f x) (f' y))) (at x within s)\"\n  using assms\n  by (auto intro: has_derivative_subset intro!: has_derivative_in_compose[of f f' x s g])\n\nlemma (in bounded_bilinear) FDERIV:\n  assumes f: \"(f has_derivative f') (at x within s)\" and g: \"(g has_derivative g') (at x within s)\"\n  shows \"((\\<lambda>x. f x ** g x) has_derivative (\\<lambda>h. f x ** g' h + f' h ** g x)) (at x within s)\"\nproof -\n  from bounded_linear.bounded [OF has_derivative_bounded_linear [OF f]]\n  obtain KF where norm_F: \"\\<And>x. norm (f' x) \\<le> norm x * KF\" by fast\n\n  from pos_bounded obtain K\n    where K: \"0 < K\" and norm_prod: \"\\<And>a b. norm (a ** b) \\<le> norm a * norm b * K\"\n    by fast\n  let ?D = \"\\<lambda>f f' y. f y - f x - f' (y - x)\"\n  let ?N = \"\\<lambda>f f' y. norm (?D f f' y) / norm (y - x)\"\n  define Ng where \"Ng = ?N g g'\"\n  define Nf where \"Nf = ?N f f'\"\n\n  let ?fun1 = \"\\<lambda>y. norm (f y ** g y - f x ** g x - (f x ** g' (y - x) + f' (y - x) ** g x)) / norm (y - x)\"\n  let ?fun2 = \"\\<lambda>y. norm (f x) * Ng y * K + Nf y * norm (g y) * K + KF * norm (g y - g x) * K\"\n  let ?F = \"at x within s\"\n\n  show ?thesis\n  proof (rule has_derivativeI_sandwich[of 1])\n    show \"bounded_linear (\\<lambda>h. f x ** g' h + f' h ** g x)\"\n      by (intro bounded_linear_add\n        bounded_linear_compose [OF bounded_linear_right] bounded_linear_compose [OF bounded_linear_left]\n        has_derivative_bounded_linear [OF g] has_derivative_bounded_linear [OF f])\n  next\n    from g have \"(g \\<longlongrightarrow> g x) ?F\"\n      by (intro continuous_within[THEN iffD1] has_derivative_continuous)\n    moreover from f g have \"(Nf \\<longlongrightarrow> 0) ?F\" \"(Ng \\<longlongrightarrow> 0) ?F\"\n      by (simp_all add: has_derivative_iff_norm Ng_def Nf_def)\n    ultimately have \"(?fun2 \\<longlongrightarrow> norm (f x) * 0 * K + 0 * norm (g x) * K + KF * norm (0::'b) * K) ?F\"\n      by (intro tendsto_intros) (simp_all add: LIM_zero_iff)\n    then show \"(?fun2 \\<longlongrightarrow> 0) ?F\"\n      by simp\n  next\n    fix y :: 'd\n    assume \"y \\<noteq> x\"\n    have \"?fun1 y =\n        norm (f x ** ?D g g' y + ?D f f' y ** g y + f' (y - x) ** (g y - g x)) / norm (y - x)\"\n      by (simp add: diff_left diff_right add_left add_right field_simps)\n    also have \"\\<dots> \\<le> (norm (f x) * norm (?D g g' y) * K + norm (?D f f' y) * norm (g y) * K +\n        norm (y - x) * KF * norm (g y - g x) * K) / norm (y - x)\"\n      by (intro divide_right_mono mult_mono'\n                order_trans [OF norm_triangle_ineq add_mono]\n                order_trans [OF norm_prod mult_right_mono]\n                mult_nonneg_nonneg order_refl norm_ge_zero norm_F\n                K [THEN order_less_imp_le])\n    also have \"\\<dots> = ?fun2 y\"\n      by (simp add: add_divide_distrib Ng_def Nf_def)\n    finally show \"?fun1 y \\<le> ?fun2 y\" .\n  qed simp\nqed\n\nlemmas has_derivative_mult[simp, derivative_intros] = bounded_bilinear.FDERIV[OF bounded_bilinear_mult]\nlemmas has_derivative_scaleR[simp, derivative_intros] = bounded_bilinear.FDERIV[OF bounded_bilinear_scaleR]\n\nlemma has_derivative_prod[simp, derivative_intros]:\n  fixes f :: \"'i \\<Rightarrow> 'a::real_normed_vector \\<Rightarrow> 'b::real_normed_field\"\n  shows \"(\\<And>i. i \\<in> I \\<Longrightarrow> (f i has_derivative f' i) (at x within S)) \\<Longrightarrow>\n    ((\\<lambda>x. \\<Prod>i\\<in>I. f i x) has_derivative (\\<lambda>y. \\<Sum>i\\<in>I. f' i y * (\\<Prod>j\\<in>I - {i}. f j x))) (at x within S)\"\nproof (induct I rule: infinite_finite_induct)\n  case infinite\n  then show ?case by simp\nnext\n  case empty\n  then show ?case by simp\nnext\n  case (insert i I)\n  let ?P = \"\\<lambda>y. f i x * (\\<Sum>i\\<in>I. f' i y * (\\<Prod>j\\<in>I - {i}. f j x)) + (f' i y) * (\\<Prod>i\\<in>I. f i x)\"\n  have \"((\\<lambda>x. f i x * (\\<Prod>i\\<in>I. f i x)) has_derivative ?P) (at x within S)\"\n    using insert by (intro has_derivative_mult) auto\n  also have \"?P = (\\<lambda>y. \\<Sum>i'\\<in>insert i I. f' i' y * (\\<Prod>j\\<in>insert i I - {i'}. f j x))\"\n    using insert(1,2)\n    by (auto simp add: sum_distrib_left insert_Diff_if intro!: ext sum.cong)\n  finally show ?case\n    using insert by simp\nqed\n\nlemma has_derivative_power[simp, derivative_intros]:\n  fixes f :: \"'a :: real_normed_vector \\<Rightarrow> 'b :: real_normed_field\"\n  assumes f: \"(f has_derivative f') (at x within S)\"\n  shows \"((\\<lambda>x. f x^n) has_derivative (\\<lambda>y. of_nat n * f' y * f x^(n - 1))) (at x within S)\"\n  using has_derivative_prod[OF f, of \"{..< n}\"] by (simp add: prod_constant ac_simps)\n\nlemma has_derivative_inverse':\n  fixes x :: \"'a::real_normed_div_algebra\"\n  assumes x: \"x \\<noteq> 0\"\n  shows \"(inverse has_derivative (\\<lambda>h. - (inverse x * h * inverse x))) (at x within S)\"\n    (is \"(_ has_derivative ?f) _\")\nproof (rule has_derivativeI_sandwich)\n  show \"bounded_linear (\\<lambda>h. - (inverse x * h * inverse x))\"\n    by (simp add: bounded_linear_minus bounded_linear_mult_const bounded_linear_mult_right)\n  show \"0 < norm x\" using x by simp\n  have \"(inverse \\<longlongrightarrow> inverse x) (at x within S)\"\n    using tendsto_inverse tendsto_ident_at x by auto\n  then show \"((\\<lambda>y. norm (inverse y - inverse x) * norm (inverse x)) \\<longlongrightarrow> 0) (at x within S)\"\n    by (simp add: LIM_zero_iff tendsto_mult_left_zero tendsto_norm_zero)\nnext\n  fix y :: 'a\n  assume h: \"y \\<noteq> x\" \"dist y x < norm x\"\n  then have \"y \\<noteq> 0\" by auto\n  have \"norm (inverse y - inverse x - ?f (y -x)) / norm (y - x) \n        = norm (- (inverse y * (y - x) * inverse x - inverse x * (y - x) * inverse x)) /\n                norm (y - x)\"\n    by (simp add: \\<open>y \\<noteq> 0\\<close> inverse_diff_inverse x)\n  also have \"... = norm ((inverse y - inverse x) * (y - x) * inverse x) / norm (y - x)\"\n    by (simp add: left_diff_distrib norm_minus_commute)\n  also have \"\\<dots> \\<le> norm (inverse y - inverse x) * norm (y - x) * norm (inverse x) / norm (y - x)\"\n    by (simp add: norm_mult)\n  also have \"\\<dots> = norm (inverse y - inverse x) * norm (inverse x)\"\n    by simp\n  finally show \"norm (inverse y - inverse x - ?f (y -x)) / norm (y - x) \\<le>\n    norm (inverse y - inverse x) * norm (inverse x)\" .\nqed\n\nlemma has_derivative_inverse[simp, derivative_intros]:\n  fixes f :: \"_ \\<Rightarrow> 'a::real_normed_div_algebra\"\n  assumes x:  \"f x \\<noteq> 0\"\n    and f: \"(f has_derivative f') (at x within S)\"\n  shows \"((\\<lambda>x. inverse (f x)) has_derivative (\\<lambda>h. - (inverse (f x) * f' h * inverse (f x))))\n    (at x within S)\"\n  using has_derivative_compose[OF f has_derivative_inverse', OF x] .\n\nlemma has_derivative_divide[simp, derivative_intros]:\n  fixes f :: \"_ \\<Rightarrow> 'a::real_normed_div_algebra\"\n  assumes f: \"(f has_derivative f') (at x within S)\"\n    and g: \"(g has_derivative g') (at x within S)\"\n  assumes x: \"g x \\<noteq> 0\"\n  shows \"((\\<lambda>x. f x / g x) has_derivative\n                (\\<lambda>h. - f x * (inverse (g x) * g' h * inverse (g x)) + f' h / g x)) (at x within S)\"\n  using has_derivative_mult[OF f has_derivative_inverse[OF x g]]\n  by (simp add: field_simps)\n\nlemma has_derivative_power_int':\n  fixes x :: \"'a::real_normed_field\"\n  assumes x: \"x \\<noteq> 0\"\n  shows \"((\\<lambda>x. power_int x n) has_derivative (\\<lambda>y. y * (of_int n * power_int x (n - 1)))) (at x within S)\"\nproof (cases n rule: int_cases4)\n  case (nonneg n)\n  thus ?thesis using x\n    by (cases \"n = 0\") (auto intro!: derivative_eq_intros simp: field_simps power_int_diff fun_eq_iff\n                             simp flip: power_Suc)\nnext\n  case (neg n)\n  thus ?thesis using x\n    by (auto intro!: derivative_eq_intros simp: field_simps power_int_diff power_int_minus\n             simp flip: power_Suc power_Suc2 power_add)\nqed\n\nlemma has_derivative_power_int[simp, derivative_intros]:\n  fixes f :: \"_ \\<Rightarrow> 'a::real_normed_field\"\n  assumes x:  \"f x \\<noteq> 0\"\n    and f: \"(f has_derivative f') (at x within S)\"\n  shows \"((\\<lambda>x. power_int (f x) n) has_derivative (\\<lambda>h. f' h * (of_int n * power_int (f x) (n - 1))))\n           (at x within S)\"\n  using has_derivative_compose[OF f has_derivative_power_int', OF x] .\n\n\ntext \\<open>Conventional form requires mult-AC laws. Types real and complex only.\\<close>\n\nlemma has_derivative_divide'[derivative_intros]:\n  fixes f :: \"_ \\<Rightarrow> 'a::real_normed_field\"\n  assumes f: \"(f has_derivative f') (at x within S)\"\n    and g: \"(g has_derivative g') (at x within S)\"\n    and x: \"g x \\<noteq> 0\"\n  shows \"((\\<lambda>x. f x / g x) has_derivative (\\<lambda>h. (f' h * g x - f x * g' h) / (g x * g x))) (at x within S)\"\nproof -\n  have \"f' h / g x - f x * (inverse (g x) * g' h * inverse (g x)) =\n      (f' h * g x - f x * g' h) / (g x * g x)\" for h\n    by (simp add: field_simps x)\n  then show ?thesis\n    using has_derivative_divide [OF f g] x\n    by simp\nqed\n\n\nsubsection \\<open>Uniqueness\\<close>\n\ntext \\<open>\nThis can not generally shown for \\<^const>\\<open>has_derivative\\<close>, as we need to approach the point from\nall directions. There is a proof in \\<open>Analysis\\<close> for \\<open>euclidean_space\\<close>.\n\\<close>\n\nlemma has_derivative_at2: \"(f has_derivative f') (at x) \\<longleftrightarrow>\n    bounded_linear f' \\<and> ((\\<lambda>y. (1 / (norm(y - x))) *\\<^sub>R (f y - (f x + f' (y - x)))) \\<longlongrightarrow> 0) (at x)\"\n  using has_derivative_within [of f f' x UNIV]\n  by simp\n\nlemma has_derivative_zero_unique:\n  assumes \"((\\<lambda>x. 0) has_derivative F) (at x)\"\n  shows \"F = (\\<lambda>h. 0)\"\nproof -\n  interpret F: bounded_linear F\n    using assms by (rule has_derivative_bounded_linear)\n  let ?r = \"\\<lambda>h. norm (F h) / norm h\"\n  have *: \"?r \\<midarrow>0\\<rightarrow> 0\"\n    using assms unfolding has_derivative_at by simp\n  show \"F = (\\<lambda>h. 0)\"\n  proof\n    show \"F h = 0\" for h\n    proof (rule ccontr)\n      assume **: \"\\<not> ?thesis\"\n      then have h: \"h \\<noteq> 0\"\n        by (auto simp add: F.zero)\n      with ** have \"0 < ?r h\"\n        by simp\n      from LIM_D [OF * this] obtain S\n        where S: \"0 < S\" and r: \"\\<And>x. x \\<noteq> 0 \\<Longrightarrow> norm x < S \\<Longrightarrow> ?r x < ?r h\"\n        by auto\n      from dense [OF S] obtain t where t: \"0 < t \\<and> t < S\" ..\n      let ?x = \"scaleR (t / norm h) h\"\n      have \"?x \\<noteq> 0\" and \"norm ?x < S\"\n        using t h by simp_all\n      then have \"?r ?x < ?r h\"\n        by (rule r)\n      then show False\n        using t h by (simp add: F.scaleR)\n    qed\n  qed\nqed\n\nlemma has_derivative_unique:\n  assumes \"(f has_derivative F) (at x)\"\n    and \"(f has_derivative F') (at x)\"\n  shows \"F = F'\"\nproof -\n  have \"((\\<lambda>x. 0) has_derivative (\\<lambda>h. F h - F' h)) (at x)\"\n    using has_derivative_diff [OF assms] by simp\n  then have \"(\\<lambda>h. F h - F' h) = (\\<lambda>h. 0)\"\n    by (rule has_derivative_zero_unique)\n  then show \"F = F'\"\n    unfolding fun_eq_iff right_minus_eq .\nqed\n\nlemma has_derivative_Uniq: \"\\<exists>\\<^sub>\\<le>\\<^sub>1F. (f has_derivative F) (at x)\"\n  by (simp add: Uniq_def has_derivative_unique)\n\n\nsubsection \\<open>Differentiability predicate\\<close>\n\ndefinition differentiable :: \"('a::real_normed_vector \\<Rightarrow> 'b::real_normed_vector) \\<Rightarrow> 'a filter \\<Rightarrow> bool\"\n    (infix \"differentiable\" 50)\n  where \"f differentiable F \\<longleftrightarrow> (\\<exists>D. (f has_derivative D) F)\"\n\nlemma differentiable_subset:\n  \"f differentiable (at x within s) \\<Longrightarrow> t \\<subseteq> s \\<Longrightarrow> f differentiable (at x within t)\"\n  unfolding differentiable_def by (blast intro: has_derivative_subset)\n\nlemmas differentiable_within_subset = differentiable_subset\n\nlemma differentiable_ident [simp, derivative_intros]: \"(\\<lambda>x. x) differentiable F\"\n  unfolding differentiable_def by (blast intro: has_derivative_ident)\n\nlemma differentiable_const [simp, derivative_intros]: \"(\\<lambda>z. a) differentiable F\"\n  unfolding differentiable_def by (blast intro: has_derivative_const)\n\nlemma differentiable_in_compose:\n  \"f differentiable (at (g x) within (g`s)) \\<Longrightarrow> g differentiable (at x within s) \\<Longrightarrow>\n    (\\<lambda>x. f (g x)) differentiable (at x within s)\"\n  unfolding differentiable_def by (blast intro: has_derivative_in_compose)\n\nlemma differentiable_compose:\n  \"f differentiable (at (g x)) \\<Longrightarrow> g differentiable (at x within s) \\<Longrightarrow>\n    (\\<lambda>x. f (g x)) differentiable (at x within s)\"\n  by (blast intro: differentiable_in_compose differentiable_subset)\n\nlemma differentiable_add [simp, derivative_intros]:\n  \"f differentiable F \\<Longrightarrow> g differentiable F \\<Longrightarrow> (\\<lambda>x. f x + g x) differentiable F\"\n  unfolding differentiable_def by (blast intro: has_derivative_add)\n\nlemma differentiable_sum[simp, derivative_intros]:\n  assumes \"finite s\" \"\\<forall>a\\<in>s. (f a) differentiable net\"\n  shows \"(\\<lambda>x. sum (\\<lambda>a. f a x) s) differentiable net\"\nproof -\n  from bchoice[OF assms(2)[unfolded differentiable_def]]\n  show ?thesis\n    by (auto intro!: has_derivative_sum simp: differentiable_def)\nqed\n\nlemma differentiable_minus [simp, derivative_intros]:\n  \"f differentiable F \\<Longrightarrow> (\\<lambda>x. - f x) differentiable F\"\n  unfolding differentiable_def by (blast intro: has_derivative_minus)\n\nlemma differentiable_diff [simp, derivative_intros]:\n  \"f differentiable F \\<Longrightarrow> g differentiable F \\<Longrightarrow> (\\<lambda>x. f x - g x) differentiable F\"\n  unfolding differentiable_def by (blast intro: has_derivative_diff)\n\nlemma differentiable_mult [simp, derivative_intros]:\n  fixes f g :: \"'a::real_normed_vector \\<Rightarrow> 'b::real_normed_algebra\"\n  shows \"f differentiable (at x within s) \\<Longrightarrow> g differentiable (at x within s) \\<Longrightarrow>\n    (\\<lambda>x. f x * g x) differentiable (at x within s)\"\n  unfolding differentiable_def by (blast intro: has_derivative_mult)\n\nlemma differentiable_cmult_left_iff [simp]:\n  fixes c::\"'a::real_normed_field\" \n  shows \"(\\<lambda>t. c * q t) differentiable at t \\<longleftrightarrow> c = 0 \\<or> (\\<lambda>t. q t) differentiable at t\" (is \"?lhs = ?rhs\")\nproof\n  assume L: ?lhs\n  {assume \"c \\<noteq> 0\"\n    then have \"q differentiable at t\"\n      using differentiable_mult [OF differentiable_const L, of concl: \"1/c\"] by auto\n  } then show ?rhs\n    by auto\nqed auto\n\nlemma differentiable_cmult_right_iff [simp]:\n  fixes c::\"'a::real_normed_field\" \n  shows \"(\\<lambda>t. q t * c) differentiable at t \\<longleftrightarrow> c = 0 \\<or> (\\<lambda>t. q t) differentiable at t\" (is \"?lhs = ?rhs\")\n  by (simp add: mult.commute flip: differentiable_cmult_left_iff)\n\nlemma differentiable_inverse [simp, derivative_intros]:\n  fixes f :: \"'a::real_normed_vector \\<Rightarrow> 'b::real_normed_field\"\n  shows \"f differentiable (at x within s) \\<Longrightarrow> f x \\<noteq> 0 \\<Longrightarrow>\n    (\\<lambda>x. inverse (f x)) differentiable (at x within s)\"\n  unfolding differentiable_def by (blast intro: has_derivative_inverse)\n\nlemma differentiable_divide [simp, derivative_intros]:\n  fixes f g :: \"'a::real_normed_vector \\<Rightarrow> 'b::real_normed_field\"\n  shows \"f differentiable (at x within s) \\<Longrightarrow> g differentiable (at x within s) \\<Longrightarrow>\n    g x \\<noteq> 0 \\<Longrightarrow> (\\<lambda>x. f x / g x) differentiable (at x within s)\"\n  unfolding divide_inverse by simp\n\nlemma differentiable_power [simp, derivative_intros]:\n  fixes f g :: \"'a::real_normed_vector \\<Rightarrow> 'b::real_normed_field\"\n  shows \"f differentiable (at x within s) \\<Longrightarrow> (\\<lambda>x. f x ^ n) differentiable (at x within s)\"\n  unfolding differentiable_def by (blast intro: has_derivative_power)\n\nlemma differentiable_power_int [simp, derivative_intros]:\n  fixes f :: \"'a::real_normed_vector \\<Rightarrow> 'b::real_normed_field\"\n  shows \"f differentiable (at x within s) \\<Longrightarrow> f x \\<noteq> 0 \\<Longrightarrow>\n           (\\<lambda>x. power_int (f x) n) differentiable (at x within s)\"\n  unfolding differentiable_def by (blast intro: has_derivative_power_int)\n\nlemma differentiable_scaleR [simp, derivative_intros]:\n  \"f differentiable (at x within s) \\<Longrightarrow> g differentiable (at x within s) \\<Longrightarrow>\n    (\\<lambda>x. f x *\\<^sub>R g x) differentiable (at x within s)\"\n  unfolding differentiable_def by (blast intro: has_derivative_scaleR)\n\nlemma has_derivative_imp_has_field_derivative:\n  \"(f has_derivative D) F \\<Longrightarrow> (\\<And>x. x * D' = D x) \\<Longrightarrow> (f has_field_derivative D') F\"\n  unfolding has_field_derivative_def\n  by (rule has_derivative_eq_rhs[of f D]) (simp_all add: fun_eq_iff mult.commute)\n\nlemma has_field_derivative_imp_has_derivative:\n  \"(f has_field_derivative D) F \\<Longrightarrow> (f has_derivative (*) D) F\"\n  by (simp add: has_field_derivative_def)\n\nlemma DERIV_subset:\n  \"(f has_field_derivative f') (at x within s) \\<Longrightarrow> t \\<subseteq> s \\<Longrightarrow>\n    (f has_field_derivative f') (at x within t)\"\n  by (simp add: has_field_derivative_def has_derivative_subset)\n\nlemma has_field_derivative_at_within:\n  \"(f has_field_derivative f') (at x) \\<Longrightarrow> (f has_field_derivative f') (at x within s)\"\n  using DERIV_subset by blast\n\nabbreviation (input)\n  DERIV :: \"('a::real_normed_field \\<Rightarrow> 'a) \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> bool\"\n    (\"(DERIV (_)/ (_)/ :> (_))\" [1000, 1000, 60] 60)\n  where \"DERIV f x :> D \\<equiv> (f has_field_derivative D) (at x)\"\n\nabbreviation has_real_derivative :: \"(real \\<Rightarrow> real) \\<Rightarrow> real \\<Rightarrow> real filter \\<Rightarrow> bool\"\n    (infix \"(has'_real'_derivative)\" 50)\n  where \"(f has_real_derivative D) F \\<equiv> (f has_field_derivative D) F\"\n\nlemma real_differentiable_def:\n  \"f differentiable at x within s \\<longleftrightarrow> (\\<exists>D. (f has_real_derivative D) (at x within s))\"\nproof safe\n  assume \"f differentiable at x within s\"\n  then obtain f' where *: \"(f has_derivative f') (at x within s)\"\n    unfolding differentiable_def by auto\n  then obtain c where \"f' = ((*) c)\"\n    by (metis real_bounded_linear has_derivative_bounded_linear mult.commute fun_eq_iff)\n  with * show \"\\<exists>D. (f has_real_derivative D) (at x within s)\"\n    unfolding has_field_derivative_def by auto\nqed (auto simp: differentiable_def has_field_derivative_def)\n\nlemma real_differentiableE [elim?]:\n  assumes f: \"f differentiable (at x within s)\"\n  obtains df where \"(f has_real_derivative df) (at x within s)\"\n  using assms by (auto simp: real_differentiable_def)\n\nlemma has_field_derivative_iff:\n  \"(f has_field_derivative D) (at x within S) \\<longleftrightarrow>\n    ((\\<lambda>y. (f y - f x) / (y - x)) \\<longlongrightarrow> D) (at x within S)\"\nproof -\n  have \"((\\<lambda>y. norm (f y - f x - D * (y - x)) / norm (y - x)) \\<longlongrightarrow> 0) (at x within S) \n      = ((\\<lambda>y. (f y - f x) / (y - x) - D) \\<longlongrightarrow> 0) (at x within S)\"\n    by (smt (verit, best) Lim_cong_within divide_diff_eq_iff norm_divide right_minus_eq tendsto_norm_zero_iff)\n  then show ?thesis\n    by (simp add: has_field_derivative_def has_derivative_iff_norm bounded_linear_mult_right LIM_zero_iff)\nqed\n\nlemma DERIV_def: \"DERIV f x :> D \\<longleftrightarrow> (\\<lambda>h. (f (x + h) - f x) / h) \\<midarrow>0\\<rightarrow> D\"\n  unfolding field_has_derivative_at has_field_derivative_def has_field_derivative_iff ..\n\ntext \\<open>due to Christian Pardillo Laursen, replacing a proper epsilon-delta horror\\<close>\nlemma field_derivative_lim_unique:\n  assumes f: \"(f has_field_derivative df) (at z)\"\n    and s: \"s \\<longlonglongrightarrow> 0\"  \"\\<And>n. s n \\<noteq> 0\" \n    and a: \"(\\<lambda>n. (f (z + s n) - f z) / s n) \\<longlonglongrightarrow> a\"\n  shows \"df = a\"\nproof -\n  have \"((\\<lambda>k. (f (z + k) - f z) / k) \\<longlongrightarrow> df) (at 0)\"\n    using f by (simp add: DERIV_def)\n  with s have \"((\\<lambda>n. (f (z + s n) - f z) / s n) \\<longlonglongrightarrow> df)\"\n    by (simp flip: LIMSEQ_SEQ_conv)\n  then show ?thesis\n    using a by (rule LIMSEQ_unique)\nqed\n\nlemma mult_commute_abs: \"(\\<lambda>x. x * c) = (*) c\"\n  for c :: \"'a::ab_semigroup_mult\"\n  by (simp add: fun_eq_iff mult.commute)\n\nlemma DERIV_compose_FDERIV:\n  fixes f::\"real\\<Rightarrow>real\"\n  assumes \"DERIV f (g x) :> f'\"\n  assumes \"(g has_derivative g') (at x within s)\"\n  shows \"((\\<lambda>x. f (g x)) has_derivative (\\<lambda>x. g' x * f')) (at x within s)\"\n  using assms has_derivative_compose[of g g' x s f \"(*) f'\"]\n  by (auto simp: has_field_derivative_def ac_simps)\n\n\nsubsection \\<open>Vector derivative\\<close>\n\ntext \\<open>It's for real derivatives only, and not obviously generalisable to field derivatives\\<close>\nlemma has_real_derivative_iff_has_vector_derivative:\n  \"(f has_real_derivative y) F \\<longleftrightarrow> (f has_vector_derivative y) F\"\n  unfolding has_vector_derivative_def has_field_derivative_def real_scaleR_def mult_commute_abs ..\n\nlemma has_field_derivative_subset:\n  \"(f has_field_derivative y) (at x within s) \\<Longrightarrow> t \\<subseteq> s \\<Longrightarrow>\n    (f has_field_derivative y) (at x within t)\"\n  by (fact DERIV_subset)\n\nlemma has_vector_derivative_const[simp, derivative_intros]: \"((\\<lambda>x. c) has_vector_derivative 0) net\"\n  by (auto simp: has_vector_derivative_def)\n\nlemma has_vector_derivative_id[simp, derivative_intros]: \"((\\<lambda>x. x) has_vector_derivative 1) net\"\n  by (auto simp: has_vector_derivative_def)\n\nlemma has_vector_derivative_minus[derivative_intros]:\n  \"(f has_vector_derivative f') net \\<Longrightarrow> ((\\<lambda>x. - f x) has_vector_derivative (- f')) net\"\n  by (auto simp: has_vector_derivative_def)\n\nlemma has_vector_derivative_add[derivative_intros]:\n  \"(f has_vector_derivative f') net \\<Longrightarrow> (g has_vector_derivative g') net \\<Longrightarrow>\n    ((\\<lambda>x. f x + g x) has_vector_derivative (f' + g')) net\"\n  by (auto simp: has_vector_derivative_def scaleR_right_distrib)\n\nlemma has_vector_derivative_sum[derivative_intros]:\n  \"(\\<And>i. i \\<in> I \\<Longrightarrow> (f i has_vector_derivative f' i) net) \\<Longrightarrow>\n    ((\\<lambda>x. \\<Sum>i\\<in>I. f i x) has_vector_derivative (\\<Sum>i\\<in>I. f' i)) net\"\n  by (auto simp: has_vector_derivative_def fun_eq_iff scaleR_sum_right intro!: derivative_eq_intros)\n\nlemma has_vector_derivative_diff[derivative_intros]:\n  \"(f has_vector_derivative f') net \\<Longrightarrow> (g has_vector_derivative g') net \\<Longrightarrow>\n    ((\\<lambda>x. f x - g x) has_vector_derivative (f' - g')) net\"\n  by (auto simp: has_vector_derivative_def scaleR_diff_right)\n\nlemma has_vector_derivative_add_const:\n  \"((\\<lambda>t. g t + z) has_vector_derivative f') net = ((\\<lambda>t. g t) has_vector_derivative f') net\"\n  apply (intro iffI)\n   apply (force dest: has_vector_derivative_diff [where g = \"\\<lambda>t. z\", OF _ has_vector_derivative_const])\n  apply (force dest: has_vector_derivative_add [OF _ has_vector_derivative_const])\n  done\n\nlemma has_vector_derivative_diff_const:\n  \"((\\<lambda>t. g t - z) has_vector_derivative f') net = ((\\<lambda>t. g t) has_vector_derivative f') net\"\n  using has_vector_derivative_add_const [where z = \"-z\"]\n  by simp\n\nlemma (in bounded_linear) has_vector_derivative:\n  assumes \"(g has_vector_derivative g') F\"\n  shows \"((\\<lambda>x. f (g x)) has_vector_derivative f g') F\"\n  using has_derivative[OF assms[unfolded has_vector_derivative_def]]\n  by (simp add: has_vector_derivative_def scaleR)\n\nlemma (in bounded_bilinear) has_vector_derivative:\n  assumes \"(f has_vector_derivative f') (at x within s)\"\n    and \"(g has_vector_derivative g') (at x within s)\"\n  shows \"((\\<lambda>x. f x ** g x) has_vector_derivative (f x ** g' + f' ** g x)) (at x within s)\"\n  using FDERIV[OF assms(1-2)[unfolded has_vector_derivative_def]]\n  by (simp add: has_vector_derivative_def scaleR_right scaleR_left scaleR_right_distrib)\n\nlemma has_vector_derivative_scaleR[derivative_intros]:\n  \"(f has_field_derivative f') (at x within s) \\<Longrightarrow> (g has_vector_derivative g') (at x within s) \\<Longrightarrow>\n    ((\\<lambda>x. f x *\\<^sub>R g x) has_vector_derivative (f x *\\<^sub>R g' + f' *\\<^sub>R g x)) (at x within s)\"\n  unfolding has_real_derivative_iff_has_vector_derivative\n  by (rule bounded_bilinear.has_vector_derivative[OF bounded_bilinear_scaleR])\n\nlemma has_vector_derivative_mult[derivative_intros]:\n  \"(f has_vector_derivative f') (at x within s) \\<Longrightarrow> (g has_vector_derivative g') (at x within s) \\<Longrightarrow>\n    ((\\<lambda>x. f x * g x) has_vector_derivative (f x * g' + f' * g x)) (at x within s)\"\n  for f g :: \"real \\<Rightarrow> 'a::real_normed_algebra\"\n  by (rule bounded_bilinear.has_vector_derivative[OF bounded_bilinear_mult])\n\nlemma has_vector_derivative_of_real[derivative_intros]:\n  \"(f has_field_derivative D) F \\<Longrightarrow> ((\\<lambda>x. of_real (f x)) has_vector_derivative (of_real D)) F\"\n  by (rule bounded_linear.has_vector_derivative[OF bounded_linear_of_real])\n    (simp add: has_real_derivative_iff_has_vector_derivative)\n\nlemma has_vector_derivative_real_field:\n  \"(f has_field_derivative f') (at (of_real a)) \\<Longrightarrow> ((\\<lambda>x. f (of_real x)) has_vector_derivative f') (at a within s)\"\n  using has_derivative_compose[of of_real of_real a _ f \"(*) f'\"] \n  by (simp add: scaleR_conv_of_real ac_simps has_vector_derivative_def has_field_derivative_def)\n\nlemma has_vector_derivative_continuous:\n  \"(f has_vector_derivative D) (at x within s) \\<Longrightarrow> continuous (at x within s) f\"\n  by (auto intro: has_derivative_continuous simp: has_vector_derivative_def)\n\nlemma continuous_on_vector_derivative:\n  \"(\\<And>x. x \\<in> S \\<Longrightarrow> (f has_vector_derivative f' x) (at x within S)) \\<Longrightarrow> continuous_on S f\"\n  by (auto simp: continuous_on_eq_continuous_within intro!: has_vector_derivative_continuous)\n\nlemma has_vector_derivative_mult_right[derivative_intros]:\n  fixes a :: \"'a::real_normed_algebra\"\n  shows \"(f has_vector_derivative x) F \\<Longrightarrow> ((\\<lambda>x. a * f x) has_vector_derivative (a * x)) F\"\n  by (rule bounded_linear.has_vector_derivative[OF bounded_linear_mult_right])\n\nlemma has_vector_derivative_mult_left[derivative_intros]:\n  fixes a :: \"'a::real_normed_algebra\"\n  shows \"(f has_vector_derivative x) F \\<Longrightarrow> ((\\<lambda>x. f x * a) has_vector_derivative (x * a)) F\"\n  by (rule bounded_linear.has_vector_derivative[OF bounded_linear_mult_left])\n\nlemma has_vector_derivative_divide[derivative_intros]:\n  fixes a :: \"'a::real_normed_field\"\n  shows \"(f has_vector_derivative x) F \\<Longrightarrow> ((\\<lambda>x. f x / a) has_vector_derivative (x / a)) F\"\n  using has_vector_derivative_mult_left [of f x F \"inverse a\"]\n  by (simp add: field_class.field_divide_inverse)\n\n\nsubsection \\<open>Derivatives\\<close>\n\nlemma DERIV_D: \"DERIV f x :> D \\<Longrightarrow> (\\<lambda>h. (f (x + h) - f x) / h) \\<midarrow>0\\<rightarrow> D\"\n  by (simp add: DERIV_def)\n\nlemma has_field_derivativeD:\n  \"(f has_field_derivative D) (at x within S) \\<Longrightarrow>\n    ((\\<lambda>y. (f y - f x) / (y - x)) \\<longlongrightarrow> D) (at x within S)\"\n  by (simp add: has_field_derivative_iff)\n\nlemma DERIV_const [simp, derivative_intros]: \"((\\<lambda>x. k) has_field_derivative 0) F\"\n  by (rule has_derivative_imp_has_field_derivative[OF has_derivative_const]) auto\n\nlemma DERIV_ident [simp, derivative_intros]: \"((\\<lambda>x. x) has_field_derivative 1) F\"\n  by (rule has_derivative_imp_has_field_derivative[OF has_derivative_ident]) auto\n\nlemma field_differentiable_add[derivative_intros]:\n  \"(f has_field_derivative f') F \\<Longrightarrow> (g has_field_derivative g') F \\<Longrightarrow>\n    ((\\<lambda>z. f z + g z) has_field_derivative f' + g') F\"\n  by (rule has_derivative_imp_has_field_derivative[OF has_derivative_add])\n     (auto simp: has_field_derivative_def field_simps mult_commute_abs)\n\ncorollary DERIV_add:\n  \"(f has_field_derivative D) (at x within s) \\<Longrightarrow> (g has_field_derivative E) (at x within s) \\<Longrightarrow>\n    ((\\<lambda>x. f x + g x) has_field_derivative D + E) (at x within s)\"\n  by (rule field_differentiable_add)\n\nlemma field_differentiable_minus[derivative_intros]:\n  \"(f has_field_derivative f') F \\<Longrightarrow> ((\\<lambda>z. - (f z)) has_field_derivative -f') F\"\n  by (rule has_derivative_imp_has_field_derivative[OF has_derivative_minus])\n     (auto simp: has_field_derivative_def field_simps mult_commute_abs)\n\ncorollary DERIV_minus:\n  \"(f has_field_derivative D) (at x within s) \\<Longrightarrow>\n    ((\\<lambda>x. - f x) has_field_derivative -D) (at x within s)\"\n  by (rule field_differentiable_minus)\n\nlemma field_differentiable_diff[derivative_intros]:\n  \"(f has_field_derivative f') F \\<Longrightarrow>\n    (g has_field_derivative g') F \\<Longrightarrow> ((\\<lambda>z. f z - g z) has_field_derivative f' - g') F\"\n  by (simp only: diff_conv_add_uminus field_differentiable_add field_differentiable_minus)\n\ncorollary DERIV_diff:\n  \"(f has_field_derivative D) (at x within s) \\<Longrightarrow>\n    (g has_field_derivative E) (at x within s) \\<Longrightarrow>\n    ((\\<lambda>x. f x - g x) has_field_derivative D - E) (at x within s)\"\n  by (rule field_differentiable_diff)\n\nlemma DERIV_continuous: \"(f has_field_derivative D) (at x within s) \\<Longrightarrow> continuous (at x within s) f\"\n  by (drule has_derivative_continuous[OF has_field_derivative_imp_has_derivative]) simp\n\ncorollary DERIV_isCont: \"DERIV f x :> D \\<Longrightarrow> isCont f x\"\n  by (rule DERIV_continuous)\n\nlemma DERIV_atLeastAtMost_imp_continuous_on:\n  assumes \"\\<And>x. \\<lbrakk>a \\<le> x; x \\<le> b\\<rbrakk> \\<Longrightarrow> \\<exists>y. DERIV f x :> y\"\n  shows \"continuous_on {a..b} f\"\n  by (meson DERIV_isCont assms atLeastAtMost_iff continuous_at_imp_continuous_at_within continuous_on_eq_continuous_within)\n\nlemma DERIV_continuous_on:\n  \"(\\<And>x. x \\<in> s \\<Longrightarrow> (f has_field_derivative (D x)) (at x within s)) \\<Longrightarrow> continuous_on s f\"\n  unfolding continuous_on_eq_continuous_within\n  by (intro continuous_at_imp_continuous_on ballI DERIV_continuous)\n\nlemma DERIV_mult':\n  \"(f has_field_derivative D) (at x within s) \\<Longrightarrow> (g has_field_derivative E) (at x within s) \\<Longrightarrow>\n    ((\\<lambda>x. f x * g x) has_field_derivative f x * E + D * g x) (at x within s)\"\n  by (rule has_derivative_imp_has_field_derivative[OF has_derivative_mult])\n     (auto simp: field_simps mult_commute_abs dest: has_field_derivative_imp_has_derivative)\n\nlemma DERIV_mult[derivative_intros]:\n  \"(f has_field_derivative Da) (at x within s) \\<Longrightarrow> (g has_field_derivative Db) (at x within s) \\<Longrightarrow>\n    ((\\<lambda>x. f x * g x) has_field_derivative Da * g x + Db * f x) (at x within s)\"\n  by (rule has_derivative_imp_has_field_derivative[OF has_derivative_mult])\n     (auto simp: field_simps dest: has_field_derivative_imp_has_derivative)\n\ntext \\<open>Derivative of linear multiplication\\<close>\n\nlemma DERIV_cmult:\n  \"(f has_field_derivative D) (at x within s) \\<Longrightarrow>\n    ((\\<lambda>x. c * f x) has_field_derivative c * D) (at x within s)\"\n  by (drule DERIV_mult' [OF DERIV_const]) simp\n\nlemma DERIV_cmult_right:\n  \"(f has_field_derivative D) (at x within s) \\<Longrightarrow>\n    ((\\<lambda>x. f x * c) has_field_derivative D * c) (at x within s)\"\n  using DERIV_cmult by (auto simp add: ac_simps)\n\nlemma DERIV_cmult_Id [simp]: \"((*) c has_field_derivative c) (at x within s)\"\n  using DERIV_ident [THEN DERIV_cmult, where c = c and x = x] by simp\n\nlemma DERIV_cdivide:\n  \"(f has_field_derivative D) (at x within s) \\<Longrightarrow>\n    ((\\<lambda>x. f x / c) has_field_derivative D / c) (at x within s)\"\n  using DERIV_cmult_right[of f D x s \"1 / c\"] by simp\n\nlemma DERIV_unique: \"DERIV f x :> D \\<Longrightarrow> DERIV f x :> E \\<Longrightarrow> D = E\"\n  unfolding DERIV_def by (rule LIM_unique)\n\nlemma DERIV_Uniq: \"\\<exists>\\<^sub>\\<le>\\<^sub>1D. DERIV f x :> D\"\n  by (simp add: DERIV_unique Uniq_def)\n\nlemma DERIV_sum[derivative_intros]:\n  \"(\\<And> n. n \\<in> S \\<Longrightarrow> ((\\<lambda>x. f x n) has_field_derivative (f' x n)) F) \\<Longrightarrow>\n    ((\\<lambda>x. sum (f x) S) has_field_derivative sum (f' x) S) F\"\n  by (rule has_derivative_imp_has_field_derivative [OF has_derivative_sum])\n     (auto simp: sum_distrib_left mult_commute_abs dest: has_field_derivative_imp_has_derivative)\n\nlemma DERIV_inverse'[derivative_intros]:\n  assumes \"(f has_field_derivative D) (at x within s)\"\n    and \"f x \\<noteq> 0\"\n  shows \"((\\<lambda>x. inverse (f x)) has_field_derivative - (inverse (f x) * D * inverse (f x)))\n    (at x within s)\"\nproof -\n  have \"(f has_derivative (\\<lambda>x. x * D)) = (f has_derivative (*) D)\"\n    by (rule arg_cong [of \"\\<lambda>x. x * D\"]) (simp add: fun_eq_iff)\n  with assms have \"(f has_derivative (\\<lambda>x. x * D)) (at x within s)\"\n    by (auto dest!: has_field_derivative_imp_has_derivative)\n  then show ?thesis using \\<open>f x \\<noteq> 0\\<close>\n    by (auto intro: has_derivative_imp_has_field_derivative has_derivative_inverse)\nqed\n\ntext \\<open>Power of \\<open>-1\\<close>\\<close>\n\nlemma DERIV_inverse:\n  \"x \\<noteq> 0 \\<Longrightarrow> ((\\<lambda>x. inverse(x)) has_field_derivative - (inverse x ^ Suc (Suc 0))) (at x within s)\"\n  by (drule DERIV_inverse' [OF DERIV_ident]) simp\n\ntext \\<open>Derivative of inverse\\<close>\n\nlemma DERIV_inverse_fun:\n  \"(f has_field_derivative d) (at x within s) \\<Longrightarrow> f x \\<noteq> 0 \\<Longrightarrow>\n    ((\\<lambda>x. inverse (f x)) has_field_derivative (- (d * inverse(f x ^ Suc (Suc 0))))) (at x within s)\"\n  by (drule (1) DERIV_inverse') (simp add: ac_simps nonzero_inverse_mult_distrib)\n\ntext \\<open>Derivative of quotient\\<close>\n\nlemma DERIV_divide[derivative_intros]:\n  \"(f has_field_derivative D) (at x within s) \\<Longrightarrow>\n    (g has_field_derivative E) (at x within s) \\<Longrightarrow> g x \\<noteq> 0 \\<Longrightarrow>\n    ((\\<lambda>x. f x / g x) has_field_derivative (D * g x - f x * E) / (g x * g x)) (at x within s)\"\n  by (rule has_derivative_imp_has_field_derivative[OF has_derivative_divide])\n     (auto dest: has_field_derivative_imp_has_derivative simp: field_simps)\n\nlemma DERIV_quotient:\n  \"(f has_field_derivative d) (at x within s) \\<Longrightarrow>\n    (g has_field_derivative e) (at x within s)\\<Longrightarrow> g x \\<noteq> 0 \\<Longrightarrow>\n    ((\\<lambda>y. f y / g y) has_field_derivative (d * g x - (e * f x)) / (g x ^ Suc (Suc 0))) (at x within s)\"\n  by (drule (2) DERIV_divide) (simp add: mult.commute)\n\nlemma DERIV_power_Suc:\n  \"(f has_field_derivative D) (at x within s) \\<Longrightarrow>\n    ((\\<lambda>x. f x ^ Suc n) has_field_derivative (1 + of_nat n) * (D * f x ^ n)) (at x within s)\"\n  by (rule has_derivative_imp_has_field_derivative[OF has_derivative_power])\n     (auto simp: has_field_derivative_def)\n\nlemma DERIV_power[derivative_intros]:\n  \"(f has_field_derivative D) (at x within s) \\<Longrightarrow>\n    ((\\<lambda>x. f x ^ n) has_field_derivative of_nat n * (D * f x ^ (n - Suc 0))) (at x within s)\"\n  by (rule has_derivative_imp_has_field_derivative[OF has_derivative_power])\n     (auto simp: has_field_derivative_def)\n\nlemma DERIV_pow: \"((\\<lambda>x. x ^ n) has_field_derivative real n * (x ^ (n - Suc 0))) (at x within s)\"\n  using DERIV_power [OF DERIV_ident] by simp\n\nlemma DERIV_power_int [derivative_intros]:\n  assumes [derivative_intros]: \"(f has_field_derivative d) (at x within s)\" and [simp]: \"f x \\<noteq> 0\"\n  shows   \"((\\<lambda>x. power_int (f x) n) has_field_derivative\n             (of_int n * power_int (f x) (n - 1) * d)) (at x within s)\"\nproof (cases n rule: int_cases4)\n  case (nonneg n)\n  thus ?thesis \n    by (cases \"n = 0\")\n       (auto intro!: derivative_eq_intros simp: field_simps power_int_diff\n             simp flip: power_Suc power_Suc2 power_add)\nnext\n  case (neg n)\n  thus ?thesis\n    by (auto intro!: derivative_eq_intros simp: field_simps power_int_diff power_int_minus\n             simp flip: power_Suc power_Suc2 power_add)\nqed\n\nlemma DERIV_chain': \"(f has_field_derivative D) (at x within s) \\<Longrightarrow> DERIV g (f x) :> E \\<Longrightarrow>\n  ((\\<lambda>x. g (f x)) has_field_derivative E * D) (at x within s)\"\n  using has_derivative_compose[of f \"(*) D\" x s g \"(*) E\"]\n  by (simp only: has_field_derivative_def mult_commute_abs ac_simps)\n\ncorollary DERIV_chain2: \"DERIV f (g x) :> Da \\<Longrightarrow> (g has_field_derivative Db) (at x within s) \\<Longrightarrow>\n  ((\\<lambda>x. f (g x)) has_field_derivative Da * Db) (at x within s)\"\n  by (rule DERIV_chain')\n\ntext \\<open>Standard version\\<close>\n\nlemma DERIV_chain:\n  \"DERIV f (g x) :> Da \\<Longrightarrow> (g has_field_derivative Db) (at x within s) \\<Longrightarrow>\n    (f \\<circ> g has_field_derivative Da * Db) (at x within s)\"\n  by (drule (1) DERIV_chain', simp add: o_def mult.commute)\n\nlemma DERIV_image_chain:\n  \"(f has_field_derivative Da) (at (g x) within (g ` s)) \\<Longrightarrow>\n    (g has_field_derivative Db) (at x within s) \\<Longrightarrow>\n    (f \\<circ> g has_field_derivative Da * Db) (at x within s)\"\n  using has_derivative_in_compose [of g \"(*) Db\" x s f \"(*) Da \"]\n  by (simp add: has_field_derivative_def o_def mult_commute_abs ac_simps)\n\n(*These two are from HOL Light: HAS_COMPLEX_DERIVATIVE_CHAIN*)\nlemma DERIV_chain_s:\n  assumes \"(\\<And>x. x \\<in> s \\<Longrightarrow> DERIV g x :> g'(x))\"\n    and \"DERIV f x :> f'\"\n    and \"f x \\<in> s\"\n  shows \"DERIV (\\<lambda>x. g(f x)) x :> f' * g'(f x)\"\n  by (metis (full_types) DERIV_chain' mult.commute assms)\n\nlemma DERIV_chain3: (*HAS_COMPLEX_DERIVATIVE_CHAIN_UNIV*)\n  assumes \"(\\<And>x. DERIV g x :> g'(x))\"\n    and \"DERIV f x :> f'\"\n  shows \"DERIV (\\<lambda>x. g(f x)) x :> f' * g'(f x)\"\n  by (metis UNIV_I DERIV_chain_s [of UNIV] assms)\n\ntext \\<open>Alternative definition for differentiability\\<close>\n\nlemma DERIV_LIM_iff:\n  fixes f :: \"'a::{real_normed_vector,inverse} \\<Rightarrow> 'a\"\n  shows \"((\\<lambda>h. (f (a + h) - f a) / h) \\<midarrow>0\\<rightarrow> D) = ((\\<lambda>x. (f x - f a) / (x - a)) \\<midarrow>a\\<rightarrow> D)\" (is \"?lhs = ?rhs\")\nproof\n  assume ?lhs\n  then have \"(\\<lambda>x. (f (a + (x + - a)) - f a) / (x + - a)) \\<midarrow>0 - - a\\<rightarrow> D\"\n    by (rule LIM_offset)\n  then show ?rhs\n    by simp\nnext\n  assume ?rhs\n  then have \"(\\<lambda>x. (f (x+a) - f a) / ((x+a) - a)) \\<midarrow>a-a\\<rightarrow> D\"\n    by (rule LIM_offset)\n  then show ?lhs\n    by (simp add: add.commute)\nqed\n\nlemma has_field_derivative_cong_ev:\n  assumes \"x = y\"\n    and *: \"eventually (\\<lambda>x. x \\<in> S \\<longrightarrow> f x = g x) (nhds x)\"\n    and \"u = v\" \"S = t\" \"x \\<in> S\"\n  shows \"(f has_field_derivative u) (at x within S) = (g has_field_derivative v) (at y within t)\"\n  unfolding has_field_derivative_iff\nproof (rule filterlim_cong)\n  from assms have \"f y = g y\"\n    by (auto simp: eventually_nhds)\n  with * show \"\\<forall>\\<^sub>F z in at x within S. (f z - f x) / (z - x) = (g z - g y) / (z - y)\"\n    unfolding eventually_at_filter\n    by eventually_elim (auto simp: assms \\<open>f y = g y\\<close>)\nqed (simp_all add: assms)\n\nlemma has_field_derivative_cong_eventually:\n  assumes \"eventually (\\<lambda>x. f x = g x) (at x within S)\" \"f x = g x\"\n  shows \"(f has_field_derivative u) (at x within S) = (g has_field_derivative u) (at x within S)\"\n  unfolding has_field_derivative_iff\nproof (rule tendsto_cong)\n  show \"\\<forall>\\<^sub>F y in at x within S. (f y - f x) / (y - x) = (g y - g x) / (y - x)\"\n    using assms by (auto elim: eventually_mono)\nqed\n\nlemma DERIV_cong_ev:\n  \"x = y \\<Longrightarrow> eventually (\\<lambda>x. f x = g x) (nhds x) \\<Longrightarrow> u = v \\<Longrightarrow>\n    DERIV f x :> u \\<longleftrightarrow> DERIV g y :> v\"\n  by (rule has_field_derivative_cong_ev) simp_all\n\nlemma DERIV_mirror: \"(DERIV f (- x) :> y) \\<longleftrightarrow> (DERIV (\\<lambda>x. f (- x)) x :> - y)\"\n  for f :: \"real \\<Rightarrow> real\" and x y :: real\n  by (simp add: DERIV_def filterlim_at_split filterlim_at_left_to_right\n      tendsto_minus_cancel_left field_simps conj_commute)\n\nlemma DERIV_shift:\n  \"(f has_field_derivative y) (at (x + z)) = ((\\<lambda>x. f (x + z)) has_field_derivative y) (at x)\"\n  by (simp add: DERIV_def field_simps)\n\nlemma DERIV_at_within_shift_lemma:\n  assumes \"(f has_field_derivative y) (at (z+x) within (+) z ` S)\"\n  shows \"(f \\<circ> (+)z has_field_derivative y) (at x within S)\"\nproof -\n  have \"((+)z has_field_derivative 1) (at x within S)\"\n    by (rule derivative_eq_intros | simp)+\n  with assms DERIV_image_chain show ?thesis\n    by (metis mult.right_neutral)\nqed\n\nlemma DERIV_at_within_shift:\n  \"(f has_field_derivative y) (at (z+x) within (+) z ` S) \\<longleftrightarrow> \n   ((\\<lambda>x. f (z+x)) has_field_derivative y) (at x within S)\"   (is \"?lhs = ?rhs\")\nproof\n  assume ?lhs then show ?rhs\n    using DERIV_at_within_shift_lemma unfolding o_def by blast\nnext\n  have [simp]: \"(\\<lambda>x. x - z) ` (+) z ` S = S\"\n    by force\n  assume R: ?rhs\n  have \"(f \\<circ> (+) z \\<circ> (+) (- z) has_field_derivative y) (at (z + x) within (+) z ` S)\"\n    by (rule DERIV_at_within_shift_lemma) (use R in \\<open>simp add: o_def\\<close>)\n  then show ?lhs\n    by (simp add: o_def)\nqed\n\nlemma floor_has_real_derivative:\n  fixes f :: \"real \\<Rightarrow> 'a::{floor_ceiling,order_topology}\"\n  assumes \"isCont f x\"\n    and \"f x \\<notin> \\<int>\"\n  shows \"((\\<lambda>x. floor (f x)) has_real_derivative 0) (at x)\"\nproof (subst DERIV_cong_ev[OF refl _ refl])\n  show \"((\\<lambda>_. floor (f x)) has_real_derivative 0) (at x)\"\n    by simp\n  have \"\\<forall>\\<^sub>F y in at x. \\<lfloor>f y\\<rfloor> = \\<lfloor>f x\\<rfloor>\"\n    by (rule eventually_floor_eq[OF assms[unfolded continuous_at]])\n  then show \"\\<forall>\\<^sub>F y in nhds x. real_of_int \\<lfloor>f y\\<rfloor> = real_of_int \\<lfloor>f x\\<rfloor>\"\n    unfolding eventually_at_filter\n    by eventually_elim auto\nqed\n\nlemmas has_derivative_floor[derivative_intros] =\n  floor_has_real_derivative[THEN DERIV_compose_FDERIV]\n\nlemma continuous_floor:\n  fixes x::real\n  shows \"x \\<notin> \\<int> \\<Longrightarrow> continuous (at x) (real_of_int \\<circ> floor)\"\n  using floor_has_real_derivative [where f=id]\n  by (auto simp: o_def has_field_derivative_def intro: has_derivative_continuous)\n\nlemma continuous_frac:\n  fixes x::real\n  assumes \"x \\<notin> \\<int>\"\n  shows \"continuous (at x) frac\"\nproof -\n  have \"isCont (\\<lambda>x. real_of_int \\<lfloor>x\\<rfloor>) x\"\n    using continuous_floor [OF assms] by (simp add: o_def)\n  then have *: \"continuous (at x) (\\<lambda>x. x - real_of_int \\<lfloor>x\\<rfloor>)\"\n    by (intro continuous_intros)\n  moreover have \"\\<forall>\\<^sub>F x in nhds x. frac x = x - real_of_int \\<lfloor>x\\<rfloor>\"\n    by (simp add: frac_def)\n  ultimately show ?thesis\n    by (simp add: LIM_imp_LIM frac_def isCont_def)\nqed\n\ntext \\<open>Caratheodory formulation of derivative at a point\\<close>\n\nlemma CARAT_DERIV:\n  \"(DERIV f x :> l) \\<longleftrightarrow> (\\<exists>g. (\\<forall>z. f z - f x = g z * (z - x)) \\<and> isCont g x \\<and> g x = l)\"\n  (is \"?lhs = ?rhs\")\nproof\n  assume ?lhs\n  show \"\\<exists>g. (\\<forall>z. f z - f x = g z * (z - x)) \\<and> isCont g x \\<and> g x = l\"\n  proof (intro exI conjI)\n    let ?g = \"(\\<lambda>z. if z = x then l else (f z - f x) / (z-x))\"\n    show \"\\<forall>z. f z - f x = ?g z * (z - x)\"\n      by simp\n    show \"isCont ?g x\"\n      using \\<open>?lhs\\<close> by (simp add: isCont_iff DERIV_def cong: LIM_equal [rule_format])\n    show \"?g x = l\"\n      by simp\n  qed\nnext\n  assume ?rhs\n  then show ?lhs\n    by (auto simp add: isCont_iff DERIV_def cong: LIM_cong)\nqed\n\n\nsubsection \\<open>Local extrema\\<close>\n\ntext \\<open>If \\<^term>\\<open>0 < f' x\\<close> then \\<^term>\\<open>x\\<close> is Locally Strictly Increasing At The Right.\\<close>\n\nlemma has_real_derivative_pos_inc_right:\n  fixes f :: \"real \\<Rightarrow> real\"\n  assumes der: \"(f has_real_derivative l) (at x within S)\"\n    and l: \"0 < l\"\n  shows \"\\<exists>d > 0. \\<forall>h > 0. x + h \\<in> S \\<longrightarrow> h < d \\<longrightarrow> f x < f (x + h)\"\n  using assms\nproof -\n  from der [THEN has_field_derivativeD, THEN tendstoD, OF l, unfolded eventually_at]\n  obtain s where s: \"0 < s\"\n    and all: \"\\<And>xa. xa\\<in>S \\<Longrightarrow> xa \\<noteq> x \\<and> dist xa x < s \\<longrightarrow> \\<bar>(f xa - f x) / (xa - x) - l\\<bar> < l\"\n    by (auto simp: dist_real_def)\n  then show ?thesis\n  proof (intro exI conjI strip)\n    show \"0 < s\" by (rule s)\n  next\n    fix h :: real\n    assume \"0 < h\" \"h < s\" \"x + h \\<in> S\"\n    with all [of \"x + h\"] show \"f x < f (x+h)\"\n    proof (simp add: abs_if dist_real_def pos_less_divide_eq split: if_split_asm)\n      assume \"\\<not> (f (x + h) - f x) / h < l\" and h: \"0 < h\"\n      with l have \"0 < (f (x + h) - f x) / h\"\n        by arith\n      then show \"f x < f (x + h)\"\n        by (simp add: pos_less_divide_eq h)\n    qed\n  qed\nqed\n\nlemma DERIV_pos_inc_right:\n  fixes f :: \"real \\<Rightarrow> real\"\n  assumes der: \"DERIV f x :> l\"\n    and l: \"0 < l\"\n  shows \"\\<exists>d > 0. \\<forall>h > 0. h < d \\<longrightarrow> f x < f (x + h)\"\n  using has_real_derivative_pos_inc_right[OF assms]\n  by auto\n\nlemma has_real_derivative_neg_dec_left:\n  fixes f :: \"real \\<Rightarrow> real\"\n  assumes der: \"(f has_real_derivative l) (at x within S)\"\n    and \"l < 0\"\n  shows \"\\<exists>d > 0. \\<forall>h > 0. x - h \\<in> S \\<longrightarrow> h < d \\<longrightarrow> f x < f (x - h)\"\nproof -\n  from \\<open>l < 0\\<close> have l: \"- l > 0\"\n    by simp\n  from der [THEN has_field_derivativeD, THEN tendstoD, OF l, unfolded eventually_at]\n  obtain s where s: \"0 < s\"\n    and all: \"\\<And>xa. xa\\<in>S \\<Longrightarrow> xa \\<noteq> x \\<and> dist xa x < s \\<longrightarrow> \\<bar>(f xa - f x) / (xa - x) - l\\<bar> < - l\"\n    by (auto simp: dist_real_def)\n  then show ?thesis\n  proof (intro exI conjI strip)\n    show \"0 < s\" by (rule s)\n  next\n    fix h :: real\n    assume \"0 < h\" \"h < s\" \"x - h \\<in> S\"\n    with all [of \"x - h\"] show \"f x < f (x-h)\"\n    proof (simp add: abs_if pos_less_divide_eq dist_real_def split: if_split_asm)\n      assume \"- ((f (x-h) - f x) / h) < l\" and h: \"0 < h\"\n      with l have \"0 < (f (x-h) - f x) / h\"\n        by arith\n      then show \"f x < f (x - h)\"\n        by (simp add: pos_less_divide_eq h)\n    qed\n  qed\nqed\n\nlemma DERIV_neg_dec_left:\n  fixes f :: \"real \\<Rightarrow> real\"\n  assumes der: \"DERIV f x :> l\"\n    and l: \"l < 0\"\n  shows \"\\<exists>d > 0. \\<forall>h > 0. h < d \\<longrightarrow> f x < f (x - h)\"\n  using has_real_derivative_neg_dec_left[OF assms]\n  by auto\n\nlemma has_real_derivative_pos_inc_left:\n  fixes f :: \"real \\<Rightarrow> real\"\n  shows \"(f has_real_derivative l) (at x within S) \\<Longrightarrow> 0 < l \\<Longrightarrow>\n    \\<exists>d>0. \\<forall>h>0. x - h \\<in> S \\<longrightarrow> h < d \\<longrightarrow> f (x - h) < f x\"\n  by (rule has_real_derivative_neg_dec_left [of \"\\<lambda>x. - f x\" \"-l\" x S, simplified])\n      (auto simp add: DERIV_minus)\n\nlemma DERIV_pos_inc_left:\n  fixes f :: \"real \\<Rightarrow> real\"\n  shows \"DERIV f x :> l \\<Longrightarrow> 0 < l \\<Longrightarrow> \\<exists>d > 0. \\<forall>h > 0. h < d \\<longrightarrow> f (x - h) < f x\"\n  using has_real_derivative_pos_inc_left\n  by blast\n\nlemma has_real_derivative_neg_dec_right:\n  fixes f :: \"real \\<Rightarrow> real\"\n  shows \"(f has_real_derivative l) (at x within S) \\<Longrightarrow> l < 0 \\<Longrightarrow>\n    \\<exists>d > 0. \\<forall>h > 0. x + h \\<in> S \\<longrightarrow> h < d \\<longrightarrow> f x > f (x + h)\"\n  by (rule has_real_derivative_pos_inc_right [of \"\\<lambda>x. - f x\" \"-l\" x S, simplified])\n      (auto simp add: DERIV_minus)\n\nlemma DERIV_neg_dec_right:\n  fixes f :: \"real \\<Rightarrow> real\"\n  shows \"DERIV f x :> l \\<Longrightarrow> l < 0 \\<Longrightarrow> \\<exists>d > 0. \\<forall>h > 0. h < d \\<longrightarrow> f x > f (x + h)\"\n  using has_real_derivative_neg_dec_right by blast\n\nlemma DERIV_local_max:\n  fixes f :: \"real \\<Rightarrow> real\"\n  assumes der: \"DERIV f x :> l\"\n    and d: \"0 < d\"\n    and le: \"\\<forall>y. \\<bar>x - y\\<bar> < d \\<longrightarrow> f y \\<le> f x\"\n  shows \"l = 0\"\nproof (cases rule: linorder_cases [of l 0])\n  case equal\n  then show ?thesis .\nnext\n  case less\n  from DERIV_neg_dec_left [OF der less]\n  obtain d' where d': \"0 < d'\" and lt: \"\\<forall>h > 0. h < d' \\<longrightarrow> f x < f (x - h)\"\n    by blast\n  obtain e where \"0 < e \\<and> e < d \\<and> e < d'\"\n    using field_lbound_gt_zero [OF d d']  ..\n  with lt le [THEN spec [where x=\"x - e\"]] show ?thesis\n    by (auto simp add: abs_if)\nnext\n  case greater\n  from DERIV_pos_inc_right [OF der greater]\n  obtain d' where d': \"0 < d'\" and lt: \"\\<forall>h > 0. h < d' \\<longrightarrow> f x < f (x + h)\"\n    by blast\n  obtain e where \"0 < e \\<and> e < d \\<and> e < d'\"\n    using field_lbound_gt_zero [OF d d'] ..\n  with lt le [THEN spec [where x=\"x + e\"]] show ?thesis\n    by (auto simp add: abs_if)\nqed\n\ntext \\<open>Similar theorem for a local minimum\\<close>\nlemma DERIV_local_min:\n  fixes f :: \"real \\<Rightarrow> real\"\n  shows \"DERIV f x :> l \\<Longrightarrow> 0 < d \\<Longrightarrow> \\<forall>y. \\<bar>x - y\\<bar> < d \\<longrightarrow> f x \\<le> f y \\<Longrightarrow> l = 0\"\n  by (drule DERIV_minus [THEN DERIV_local_max]) auto\n\n\ntext\\<open>In particular, if a function is locally flat\\<close>\nlemma DERIV_local_const:\n  fixes f :: \"real \\<Rightarrow> real\"\n  shows \"DERIV f x :> l \\<Longrightarrow> 0 < d \\<Longrightarrow> \\<forall>y. \\<bar>x - y\\<bar> < d \\<longrightarrow> f x = f y \\<Longrightarrow> l = 0\"\n  by (auto dest!: DERIV_local_max)\n\n\nsubsection \\<open>Rolle's Theorem\\<close>\n\ntext \\<open>Lemma about introducing open ball in open interval\\<close>\nlemma lemma_interval_lt: \n  fixes a b x :: real\n  assumes \"a < x\" \"x < b\"\n  shows \"\\<exists>d. 0 < d \\<and> (\\<forall>y. \\<bar>x - y\\<bar> < d \\<longrightarrow> a < y \\<and> y < b)\"\n  using linorder_linear [of \"x - a\" \"b - x\"]\nproof \n  assume \"x - a \\<le> b - x\"\n  with assms show ?thesis\n    by (rule_tac x = \"x - a\" in exI) auto\nnext\n  assume \"b - x \\<le> x - a\"\n  with assms show ?thesis\n    by (rule_tac x = \"b - x\" in exI) auto\nqed\n\nlemma lemma_interval: \"a < x \\<Longrightarrow> x < b \\<Longrightarrow> \\<exists>d. 0 < d \\<and> (\\<forall>y. \\<bar>x - y\\<bar> < d \\<longrightarrow> a \\<le> y \\<and> y \\<le> b)\"\n  for a b x :: real\n  by (force dest: lemma_interval_lt)\n\ntext \\<open>Rolle's Theorem.\n   If \\<^term>\\<open>f\\<close> is defined and continuous on the closed interval\n   \\<open>[a,b]\\<close> and differentiable on the open interval \\<open>(a,b)\\<close>,\n   and \\<^term>\\<open>f a = f b\\<close>,\n   then there exists \\<open>x0 \\<in> (a,b)\\<close> such that \\<^term>\\<open>f' x0 = 0\\<close>\\<close>\ntheorem Rolle_deriv:\n  fixes f :: \"real \\<Rightarrow> real\"\n  assumes \"a < b\"\n    and fab: \"f a = f b\"\n    and contf: \"continuous_on {a..b} f\"\n    and derf: \"\\<And>x. \\<lbrakk>a < x; x < b\\<rbrakk> \\<Longrightarrow> (f has_derivative f' x) (at x)\"\n  shows \"\\<exists>z. a < z \\<and> z < b \\<and> f' z = (\\<lambda>v. 0)\"\nproof -\n  have le: \"a \\<le> b\"\n    using \\<open>a < b\\<close> by simp\n    have \"(a + b) / 2 \\<in> {a..b}\"\n      using assms(1) by auto\n    then have *: \"{a..b} \\<noteq> {}\"\n      by auto\n  obtain x where x_max: \"\\<forall>z. a \\<le> z \\<and> z \\<le> b \\<longrightarrow> f z \\<le> f x\" and \"a \\<le> x\" \"x \\<le> b\"\n    using continuous_attains_sup[OF compact_Icc * contf]\n    by (meson atLeastAtMost_iff)\n  obtain x' where x'_min: \"\\<forall>z. a \\<le> z \\<and> z \\<le> b \\<longrightarrow> f x' \\<le> f z\" and \"a \\<le> x'\" \"x' \\<le> b\"\n    using continuous_attains_inf[OF compact_Icc * contf] by (meson atLeastAtMost_iff)\n  consider \"a < x\" \"x < b\" | \"x = a \\<or> x = b\"\n    using \\<open>a \\<le> x\\<close> \\<open>x \\<le> b\\<close> by arith\n  then show ?thesis\n  proof cases\n    case 1\n    \\<comment> \\<open>\\<^term>\\<open>f\\<close> attains its maximum within the interval\\<close>\n    then obtain l where der: \"DERIV f x :> l\"\n      using derf differentiable_def real_differentiable_def by blast\n    obtain d where d: \"0 < d\" and bound: \"\\<forall>y. \\<bar>x - y\\<bar> < d \\<longrightarrow> a \\<le> y \\<and> y \\<le> b\"\n      using lemma_interval [OF 1] by blast\n    then have bound': \"\\<forall>y. \\<bar>x - y\\<bar> < d \\<longrightarrow> f y \\<le> f x\"\n      using x_max by blast\n    \\<comment> \\<open>the derivative at a local maximum is zero\\<close>\n    have \"l = 0\"\n      by (rule DERIV_local_max [OF der d bound'])\n    with 1 der derf [of x] show ?thesis\n      by (metis has_derivative_unique has_field_derivative_def mult_zero_left)\n  next\n    case 2\n    then have fx: \"f b = f x\" by (auto simp add: fab)\n    consider \"a < x'\" \"x' < b\" | \"x' = a \\<or> x' = b\"\n      using \\<open>a \\<le> x'\\<close> \\<open>x' \\<le> b\\<close> by arith\n    then show ?thesis\n    proof cases\n      case 1\n        \\<comment> \\<open>\\<^term>\\<open>f\\<close> attains its minimum within the interval\\<close>\n      then obtain l where der: \"DERIV f x' :> l\"\n        using derf differentiable_def real_differentiable_def by blast \n      from lemma_interval [OF 1]\n      obtain d where d: \"0<d\" and bound: \"\\<forall>y. \\<bar>x'-y\\<bar> < d \\<longrightarrow> a \\<le> y \\<and> y \\<le> b\"\n        by blast\n      then have bound': \"\\<forall>y. \\<bar>x' - y\\<bar> < d \\<longrightarrow> f x' \\<le> f y\"\n        using x'_min by blast\n      have \"l = 0\" by (rule DERIV_local_min [OF der d bound'])\n        \\<comment> \\<open>the derivative at a local minimum is zero\\<close>\n      then show ?thesis using 1 der derf [of x'] \n        by (metis has_derivative_unique has_field_derivative_def mult_zero_left)\n    next\n      case 2\n        \\<comment> \\<open>\\<^term>\\<open>f\\<close> is constant throughout the interval\\<close>\n      then have fx': \"f b = f x'\" by (auto simp: fab)\n      from dense [OF \\<open>a < b\\<close>] obtain r where r: \"a < r\" \"r < b\" by blast\n      obtain d where d: \"0 < d\" and bound: \"\\<forall>y. \\<bar>r - y\\<bar> < d \\<longrightarrow> a \\<le> y \\<and> y \\<le> b\"\n        using lemma_interval [OF r] by blast\n      have eq_fb: \"f z = f b\" if \"a \\<le> z\" and \"z \\<le> b\" for z\n      proof (rule order_antisym)\n        show \"f z \\<le> f b\" by (simp add: fx x_max that)\n        show \"f b \\<le> f z\" by (simp add: fx' x'_min that)\n      qed\n      have bound': \"\\<forall>y. \\<bar>r - y\\<bar> < d \\<longrightarrow> f r = f y\"\n      proof (intro strip)\n        fix y :: real\n        assume lt: \"\\<bar>r - y\\<bar> < d\"\n        then have \"f y = f b\" by (simp add: eq_fb bound)\n        then show \"f r = f y\" by (simp add: eq_fb r order_less_imp_le)\n      qed\n      obtain l where der: \"DERIV f r :> l\"\n        using derf differentiable_def r(1) r(2) real_differentiable_def by blast\n      have \"l = 0\"\n        by (rule DERIV_local_const [OF der d bound'])\n        \\<comment> \\<open>the derivative of a constant function is zero\\<close>\n      with r der derf [of r] show ?thesis\n        by (metis has_derivative_unique has_field_derivative_def mult_zero_left)\n    qed\n  qed\nqed\n\ncorollary Rolle:\n  fixes a b :: real\n  assumes ab: \"a < b\" \"f a = f b\" \"continuous_on {a..b} f\"\n    and dif [rule_format]: \"\\<And>x. \\<lbrakk>a < x; x < b\\<rbrakk> \\<Longrightarrow> f differentiable (at x)\"\n  shows \"\\<exists>z. a < z \\<and> z < b \\<and> DERIV f z :> 0\"\nproof -\n  obtain f' where f': \"\\<And>x. \\<lbrakk>a < x; x < b\\<rbrakk> \\<Longrightarrow> (f has_derivative f' x) (at x)\"\n    using dif unfolding differentiable_def by metis\n  then have \"\\<exists>z. a < z \\<and> z < b \\<and> f' z = (\\<lambda>v. 0)\"\n    by (metis Rolle_deriv [OF ab])\n  then show ?thesis\n    using f' has_derivative_imp_has_field_derivative by fastforce\nqed\n\nsubsection \\<open>Mean Value Theorem\\<close>\n\ntheorem mvt:\n  fixes f :: \"real \\<Rightarrow> real\"\n  assumes \"a < b\"\n    and contf: \"continuous_on {a..b} f\"\n    and derf: \"\\<And>x. \\<lbrakk>a < x; x < b\\<rbrakk> \\<Longrightarrow> (f has_derivative f' x) (at x)\"\n  obtains \\<xi> where \"a < \\<xi>\" \"\\<xi> < b\" \"f b - f a = (f' \\<xi>) (b - a)\"\nproof -\n  have \"\\<exists>\\<xi>. a < \\<xi> \\<and> \\<xi> < b \\<and> (\\<lambda>y. f' \\<xi> y - (f b - f a) / (b - a) * y) = (\\<lambda>v. 0)\"\n  proof (intro Rolle_deriv[OF \\<open>a < b\\<close>])\n    fix x\n    assume x: \"a < x\" \"x < b\"\n    show \"((\\<lambda>x. f x - (f b - f a) / (b - a) * x) \n          has_derivative (\\<lambda>y. f' x y - (f b - f a) / (b - a) * y)) (at x)\"\n      by (intro derivative_intros derf[OF x])\n  qed (use assms in \\<open>auto intro!: continuous_intros simp: field_simps\\<close>)\n  then show ?thesis\n    by (smt (verit, ccfv_SIG) pos_le_divide_eq pos_less_divide_eq that)\nqed\n\ntheorem MVT:\n  fixes a b :: real\n  assumes lt: \"a < b\"\n    and contf: \"continuous_on {a..b} f\"\n    and dif: \"\\<And>x. \\<lbrakk>a < x; x < b\\<rbrakk> \\<Longrightarrow> f differentiable (at x)\"\n  shows \"\\<exists>l z. a < z \\<and> z < b \\<and> DERIV f z :> l \\<and> f b - f a = (b - a) * l\"\nproof -\n  obtain f' :: \"real \\<Rightarrow> real \\<Rightarrow> real\"\n    where derf: \"\\<And>x. a < x \\<Longrightarrow> x < b \\<Longrightarrow> (f has_derivative f' x) (at x)\"\n    using dif unfolding differentiable_def by metis\n  then obtain z where \"a < z\" \"z < b\" \"f b - f a = (f' z) (b - a)\"\n    using mvt [OF lt contf] by blast\n  then show ?thesis\n    by (simp add: ac_simps)\n      (metis derf dif has_derivative_unique has_field_derivative_imp_has_derivative real_differentiable_def)\nqed\n\ncorollary MVT2:\n  assumes \"a < b\" and der: \"\\<And>x. \\<lbrakk>a \\<le> x; x \\<le> b\\<rbrakk> \\<Longrightarrow> DERIV f x :> f' x\"\n  shows \"\\<exists>z::real. a < z \\<and> z < b \\<and> (f b - f a = (b - a) * f' z)\"\nproof -\n  have \"\\<exists>l z. a < z \\<and>\n           z < b \\<and>\n           (f has_real_derivative l) (at z) \\<and>\n           f b - f a = (b - a) * l\"\n  proof (rule MVT [OF \\<open>a < b\\<close>])\n    show \"continuous_on {a..b} f\"\n      by (meson DERIV_continuous atLeastAtMost_iff continuous_at_imp_continuous_on der) \n    show \"\\<And>x. \\<lbrakk>a < x; x < b\\<rbrakk> \\<Longrightarrow> f differentiable (at x)\"\n      using assms by (force dest: order_less_imp_le simp add: real_differentiable_def)\n  qed\n  with assms show ?thesis\n    by (blast dest: DERIV_unique order_less_imp_le)\nqed\n\nlemma pos_deriv_imp_strict_mono:\n  assumes \"\\<And>x. (f has_real_derivative f' x) (at x)\"\n  assumes \"\\<And>x. f' x > 0\"\n  shows   \"strict_mono f\"\nproof (rule strict_monoI)\n  fix x y :: real assume xy: \"x < y\"\n  from assms and xy have \"\\<exists>z>x. z < y \\<and> f y - f x = (y - x) * f' z\"\n    by (intro MVT2) (auto dest: connectedD_interval)\n  then obtain z where z: \"z > x\" \"z < y\" \"f y - f x = (y - x) * f' z\" by blast\n  note \\<open>f y - f x = (y - x) * f' z\\<close>\n  also have \"(y - x) * f' z > 0\" using xy assms by (intro mult_pos_pos) auto\n  finally show \"f x < f y\" by simp\nqed\n\nproposition  deriv_nonneg_imp_mono:\n  assumes deriv: \"\\<And>x. x \\<in> {a..b} \\<Longrightarrow> (g has_real_derivative g' x) (at x)\"\n  assumes nonneg: \"\\<And>x. x \\<in> {a..b} \\<Longrightarrow> g' x \\<ge> 0\"\n  assumes ab: \"a \\<le> b\"\n  shows \"g a \\<le> g b\"\nproof (cases \"a < b\")\n  assume \"a < b\"\n  from deriv have \"\\<And>x. \\<lbrakk>x \\<ge> a; x \\<le> b\\<rbrakk> \\<Longrightarrow> (g has_real_derivative g' x) (at x)\" by simp\n  with MVT2[OF \\<open>a < b\\<close>] and deriv\n    obtain \\<xi> where \\<xi>_ab: \"\\<xi> > a\" \"\\<xi> < b\" and g_ab: \"g b - g a = (b - a) * g' \\<xi>\" by blast\n  from \\<xi>_ab ab nonneg have \"(b - a) * g' \\<xi> \\<ge> 0\" by simp\n  with g_ab show ?thesis by simp\nqed (insert ab, simp)\n\n\nsubsubsection \\<open>A function is constant if its derivative is 0 over an interval.\\<close>\n\nlemma DERIV_isconst_end:\n  fixes f :: \"real \\<Rightarrow> real\"\n  assumes \"a < b\" and contf: \"continuous_on {a..b} f\"\n    and 0: \"\\<And>x. \\<lbrakk>a < x; x < b\\<rbrakk> \\<Longrightarrow> DERIV f x :> 0\"\n  shows \"f b = f a\"\n  using MVT [OF \\<open>a < b\\<close>] \"0\" DERIV_unique contf real_differentiable_def\n  by (fastforce simp: algebra_simps)\n\nlemma DERIV_isconst2:\n  fixes f :: \"real \\<Rightarrow> real\"\n  assumes \"a < b\" and contf: \"continuous_on {a..b} f\" and derf: \"\\<And>x. \\<lbrakk>a < x; x < b\\<rbrakk> \\<Longrightarrow> DERIV f x :> 0\"\n    and \"a \\<le> x\" \"x \\<le> b\"\nshows \"f x = f a\"\nproof (cases \"a < x\")\n  case True\n  have *: \"continuous_on {a..x} f\"\n    using \\<open>x \\<le> b\\<close> contf continuous_on_subset by fastforce\n  show ?thesis\n    by (rule DERIV_isconst_end [OF True *]) (use \\<open>x \\<le> b\\<close> derf in auto)\nqed (use \\<open>a \\<le> x\\<close> in auto)\n\nlemma DERIV_isconst3:\n  fixes a b x y :: real\n  assumes \"a < b\"\n    and \"x \\<in> {a <..< b}\"\n    and \"y \\<in> {a <..< b}\"\n    and derivable: \"\\<And>x. x \\<in> {a <..< b} \\<Longrightarrow> DERIV f x :> 0\"\n  shows \"f x = f y\"\nproof (cases \"x = y\")\n  case False\n  let ?a = \"min x y\"\n  let ?b = \"max x y\"\n  have *: \"DERIV f z :> 0\" if \"?a \\<le> z\" \"z \\<le> ?b\" for z\n  proof -\n    have \"a < z\" and \"z < b\"\n      using that \\<open>x \\<in> {a <..< b}\\<close> and \\<open>y \\<in> {a <..< b}\\<close> by auto\n    then have \"z \\<in> {a<..<b}\" by auto\n    then show \"DERIV f z :> 0\" by (rule derivable)\n  qed\n  have isCont: \"continuous_on {?a..?b} f\"\n    by (meson * DERIV_continuous_on atLeastAtMost_iff has_field_derivative_at_within)\n  have DERIV: \"\\<And>z. \\<lbrakk>?a < z; z < ?b\\<rbrakk> \\<Longrightarrow> DERIV f z :> 0\"\n    using * by auto\n  have \"?a < ?b\" using \\<open>x \\<noteq> y\\<close> by auto\n  from DERIV_isconst2[OF this isCont DERIV, of x] and DERIV_isconst2[OF this isCont DERIV, of y]\n  show ?thesis by auto\nqed auto\n\nlemma DERIV_isconst_all:\n  fixes f :: \"real \\<Rightarrow> real\"\n  shows \"\\<forall>x. DERIV f x :> 0 \\<Longrightarrow> f x = f y\"\n  apply (rule linorder_cases [of x y])\n  apply (metis DERIV_continuous DERIV_isconst_end continuous_at_imp_continuous_on)+\n  done\n\nlemma DERIV_const_ratio_const:\n  fixes f :: \"real \\<Rightarrow> real\"\n  assumes \"a \\<noteq> b\" and df: \"\\<And>x. DERIV f x :> k\"\n  shows \"f b - f a = (b - a) * k\"\nproof (cases a b rule: linorder_cases)\n  case less\n  show ?thesis\n    using MVT [OF less] df\n    by (metis DERIV_continuous DERIV_unique continuous_at_imp_continuous_on real_differentiable_def)\nnext\n  case greater\n  have  \"f a - f b = (a - b) * k\"\n    using MVT [OF greater] df\n    by (metis DERIV_continuous DERIV_unique continuous_at_imp_continuous_on real_differentiable_def)\n  then show ?thesis\n    by (simp add: algebra_simps)\nqed auto\n\nlemma DERIV_const_ratio_const2:\n  fixes f :: \"real \\<Rightarrow> real\"\n  assumes \"a \\<noteq> b\" and df: \"\\<And>x. DERIV f x :> k\"\n  shows \"(f b - f a) / (b - a) = k\"\n  using DERIV_const_ratio_const [OF assms] \\<open>a \\<noteq> b\\<close> by auto\n\nlemma real_average_minus_first [simp]: \"(a + b) / 2 - a = (b - a) / 2\"\n  for a b :: real\n  by simp\n\nlemma real_average_minus_second [simp]: \"(b + a) / 2 - a = (b - a) / 2\"\n  for a b :: real\n  by simp\n\ntext \\<open>Gallileo's \"trick\": average velocity = av. of end velocities.\\<close>\n\nlemma DERIV_const_average:\n  fixes v :: \"real \\<Rightarrow> real\"\n    and a b :: real\n  assumes neq: \"a \\<noteq> b\"\n    and der: \"\\<And>x. DERIV v x :> k\"\n  shows \"v ((a + b) / 2) = (v a + v b) / 2\"\nproof (cases rule: linorder_cases [of a b])\n  case equal\n  with neq show ?thesis by simp\nnext\n  case less\n  have \"(v b - v a) / (b - a) = k\"\n    by (rule DERIV_const_ratio_const2 [OF neq der])\n  then have \"(b - a) * ((v b - v a) / (b - a)) = (b - a) * k\"\n    by simp\n  moreover have \"(v ((a + b) / 2) - v a) / ((a + b) / 2 - a) = k\"\n    by (rule DERIV_const_ratio_const2 [OF _ der]) (simp add: neq)\n  ultimately show ?thesis\n    using neq by force\nnext\n  case greater\n  have \"(v b - v a) / (b - a) = k\"\n    by (rule DERIV_const_ratio_const2 [OF neq der])\n  then have \"(b - a) * ((v b - v a) / (b - a)) = (b - a) * k\"\n    by simp\n  moreover have \" (v ((b + a) / 2) - v a) / ((b + a) / 2 - a) = k\"\n    by (rule DERIV_const_ratio_const2 [OF _ der]) (simp add: neq)\n  ultimately show ?thesis\n    using neq by (force simp add: add.commute)\nqed\n\nsubsubsection\\<open>A function with positive derivative is increasing\\<close>\ntext \\<open>A simple proof using the MVT, by Jeremy Avigad. And variants.\\<close>\nlemma DERIV_pos_imp_increasing_open:\n  fixes a b :: real\n    and f :: \"real \\<Rightarrow> real\"\n  assumes \"a < b\"\n    and \"\\<And>x. a < x \\<Longrightarrow> x < b \\<Longrightarrow> (\\<exists>y. DERIV f x :> y \\<and> y > 0)\"\n    and con: \"continuous_on {a..b} f\"\n  shows \"f a < f b\"\nproof (rule ccontr)\n  assume f: \"\\<not> ?thesis\"\n  have \"\\<exists>l z. a < z \\<and> z < b \\<and> DERIV f z :> l \\<and> f b - f a = (b - a) * l\"\n    by (rule MVT) (use assms real_differentiable_def in \\<open>force+\\<close>)\n  then obtain l z where z: \"a < z\" \"z < b\" \"DERIV f z :> l\" and \"f b - f a = (b - a) * l\"\n    by auto\n  with assms f have \"\\<not> l > 0\"\n    by (metis linorder_not_le mult_le_0_iff diff_le_0_iff_le)\n  with assms z show False\n    by (metis DERIV_unique)\nqed\n\nlemma DERIV_pos_imp_increasing:\n  fixes a b :: real and f :: \"real \\<Rightarrow> real\"\n  assumes \"a < b\"\n    and der: \"\\<And>x. \\<lbrakk>a \\<le> x; x \\<le> b\\<rbrakk> \\<Longrightarrow> \\<exists>y. DERIV f x :> y \\<and> y > 0\"\n  shows \"f a < f b\"\n  by (metis less_le_not_le DERIV_atLeastAtMost_imp_continuous_on DERIV_pos_imp_increasing_open [OF \\<open>a < b\\<close>] der)\n\nlemma DERIV_nonneg_imp_nondecreasing:\n  fixes a b :: real\n    and f :: \"real \\<Rightarrow> real\"\n  assumes \"a \\<le> b\"\n    and \"\\<And>x. \\<lbrakk>a \\<le> x; x \\<le> b\\<rbrakk> \\<Longrightarrow> \\<exists>y. DERIV f x :> y \\<and> y \\<ge> 0\"\n  shows \"f a \\<le> f b\"\nproof (rule ccontr, cases \"a = b\")\n  assume \"\\<not> ?thesis\" and \"a = b\"\n  then show False by auto\nnext\n  assume *: \"\\<not> ?thesis\"\n  assume \"a \\<noteq> b\"\n  with \\<open>a \\<le> b\\<close> have \"a < b\"\n    by linarith\n  moreover have \"continuous_on {a..b} f\"\n    by (meson DERIV_isCont assms(2) atLeastAtMost_iff continuous_at_imp_continuous_on)\n  ultimately have \"\\<exists>l z. a < z \\<and> z < b \\<and> DERIV f z :> l \\<and> f b - f a = (b - a) * l\"\n    using assms MVT [OF \\<open>a < b\\<close>, of f] real_differentiable_def less_eq_real_def by blast\n  then obtain l z where lz: \"a < z\" \"z < b\" \"DERIV f z :> l\" and **: \"f b - f a = (b - a) * l\"\n    by auto\n  with * have \"a < b\" \"f b < f a\" by auto\n  with ** have \"\\<not> l \\<ge> 0\" by (auto simp add: not_le algebra_simps)\n    (metis * add_le_cancel_right assms(1) less_eq_real_def mult_right_mono add_left_mono linear order_refl)\n  with assms lz show False\n    by (metis DERIV_unique order_less_imp_le)\nqed\n\nlemma DERIV_neg_imp_decreasing_open:\n  fixes a b :: real\n    and f :: \"real \\<Rightarrow> real\"\n  assumes \"a < b\"\n    and \"\\<And>x. a < x \\<Longrightarrow> x < b \\<Longrightarrow> \\<exists>y. DERIV f x :> y \\<and> y < 0\"\n    and con: \"continuous_on {a..b} f\"\n  shows \"f a > f b\"\nproof -\n  have \"(\\<lambda>x. -f x) a < (\\<lambda>x. -f x) b\"\n  proof (rule DERIV_pos_imp_increasing_open [of a b])\n    show \"\\<And>x. \\<lbrakk>a < x; x < b\\<rbrakk> \\<Longrightarrow> \\<exists>y. ((\\<lambda>x. - f x) has_real_derivative y) (at x) \\<and> 0 < y\"\n      using assms\n      by simp (metis field_differentiable_minus neg_0_less_iff_less)\n    show \"continuous_on {a..b} (\\<lambda>x. - f x)\"\n      using con continuous_on_minus by blast\n  qed (use assms in auto)\n  then show ?thesis\n    by simp\nqed\n\nlemma DERIV_neg_imp_decreasing:\n  fixes a b :: real and f :: \"real \\<Rightarrow> real\"\n  assumes \"a < b\"\n    and der: \"\\<And>x. \\<lbrakk>a \\<le> x; x \\<le> b\\<rbrakk> \\<Longrightarrow> \\<exists>y. DERIV f x :> y \\<and> y < 0\"\n  shows \"f a > f b\"\n  by (metis less_le_not_le DERIV_atLeastAtMost_imp_continuous_on DERIV_neg_imp_decreasing_open [OF \\<open>a < b\\<close>] der)\n\nlemma DERIV_nonpos_imp_nonincreasing:\n  fixes a b :: real\n    and f :: \"real \\<Rightarrow> real\"\n  assumes \"a \\<le> b\"\n    and \"\\<And>x. \\<lbrakk>a \\<le> x; x \\<le> b\\<rbrakk> \\<Longrightarrow> \\<exists>y. DERIV f x :> y \\<and> y \\<le> 0\"\n  shows \"f a \\<ge> f b\"\nproof -\n  have \"(\\<lambda>x. -f x) a \\<le> (\\<lambda>x. -f x) b\"\n    using DERIV_nonneg_imp_nondecreasing [of a b \"\\<lambda>x. -f x\"] assms DERIV_minus by fastforce\n  then show ?thesis\n    by simp\nqed\n\nlemma DERIV_pos_imp_increasing_at_bot:\n  fixes f :: \"real \\<Rightarrow> real\"\n  assumes \"\\<And>x. x \\<le> b \\<Longrightarrow> (\\<exists>y. DERIV f x :> y \\<and> y > 0)\"\n    and lim: \"(f \\<longlongrightarrow> flim) at_bot\"\n  shows \"flim < f b\"\nproof -\n  have \"\\<exists>N. \\<forall>n\\<le>N. f n \\<le> f (b - 1)\"\n    by (rule_tac x=\"b - 2\" in exI) (force intro: order.strict_implies_order DERIV_pos_imp_increasing assms)\n  then have \"flim \\<le> f (b - 1)\"\n     by (auto simp: eventually_at_bot_linorder tendsto_upperbound [OF lim])\n  also have \"\\<dots> < f b\"\n    by (force intro: DERIV_pos_imp_increasing [where f=f] assms)\n  finally show ?thesis .\nqed\n\nlemma DERIV_neg_imp_decreasing_at_top:\n  fixes f :: \"real \\<Rightarrow> real\"\n  assumes der: \"\\<And>x. x \\<ge> b \\<Longrightarrow> \\<exists>y. DERIV f x :> y \\<and> y < 0\"\n    and lim: \"(f \\<longlongrightarrow> flim) at_top\"\n  shows \"flim < f b\"\n  apply (rule DERIV_pos_imp_increasing_at_bot [where f = \"\\<lambda>i. f (-i)\" and b = \"-b\", simplified])\n   apply (metis DERIV_mirror der le_minus_iff neg_0_less_iff_less)\n  apply (metis filterlim_at_top_mirror lim)\n  done\n\ntext \\<open>Derivative of inverse function\\<close>\n\nlemma DERIV_inverse_function:\n  fixes f g :: \"real \\<Rightarrow> real\"\n  assumes der: \"DERIV f (g x) :> D\"\n    and neq: \"D \\<noteq> 0\"\n    and x: \"a < x\" \"x < b\"\n    and inj: \"\\<And>y. \\<lbrakk>a < y; y < b\\<rbrakk> \\<Longrightarrow> f (g y) = y\"\n    and cont: \"isCont g x\"\n  shows \"DERIV g x :> inverse D\"\nunfolding has_field_derivative_iff\nproof (rule LIM_equal2)\n  show \"0 < min (x - a) (b - x)\"\n    using x by arith\nnext\n  fix y\n  assume \"norm (y - x) < min (x - a) (b - x)\"\n  then have \"a < y\" and \"y < b\"\n    by (simp_all add: abs_less_iff)\n  then show \"(g y - g x) / (y - x) = inverse ((f (g y) - x) / (g y - g x))\"\n    by (simp add: inj)\nnext\n  have \"(\\<lambda>z. (f z - f (g x)) / (z - g x)) \\<midarrow>g x\\<rightarrow> D\"\n    by (rule der [unfolded has_field_derivative_iff])\n  then have 1: \"(\\<lambda>z. (f z - x) / (z - g x)) \\<midarrow>g x\\<rightarrow> D\"\n    using inj x by simp\n  have 2: \"\\<exists>d>0. \\<forall>y. y \\<noteq> x \\<and> norm (y - x) < d \\<longrightarrow> g y \\<noteq> g x\"\n  proof (rule exI, safe)\n    show \"0 < min (x - a) (b - x)\"\n      using x by simp\n  next\n    fix y\n    assume \"norm (y - x) < min (x - a) (b - x)\"\n    then have y: \"a < y\" \"y < b\"\n      by (simp_all add: abs_less_iff)\n    assume \"g y = g x\"\n    then have \"f (g y) = f (g x)\" by simp\n    then have \"y = x\" using inj y x by simp\n    also assume \"y \\<noteq> x\"\n    finally show False by simp\n  qed\n  have \"(\\<lambda>y. (f (g y) - x) / (g y - g x)) \\<midarrow>x\\<rightarrow> D\"\n    using cont 1 2 by (rule isCont_LIM_compose2)\n  then show \"(\\<lambda>y. inverse ((f (g y) - x) / (g y - g x))) \\<midarrow>x\\<rightarrow> inverse D\"\n    using neq by (rule tendsto_inverse)\nqed\n\nsubsection \\<open>Generalized Mean Value Theorem\\<close>\n\ntheorem GMVT:\n  fixes a b :: real\n  assumes alb: \"a < b\"\n    and fc: \"\\<forall>x. a \\<le> x \\<and> x \\<le> b \\<longrightarrow> isCont f x\"\n    and fd: \"\\<forall>x. a < x \\<and> x < b \\<longrightarrow> f differentiable (at x)\"\n    and gc: \"\\<forall>x. a \\<le> x \\<and> x \\<le> b \\<longrightarrow> isCont g x\"\n    and gd: \"\\<forall>x. a < x \\<and> x < b \\<longrightarrow> g differentiable (at x)\"\n  shows \"\\<exists>g'c f'c c.\n    DERIV g c :> g'c \\<and> DERIV f c :> f'c \\<and> a < c \\<and> c < b \\<and> (f b - f a) * g'c = (g b - g a) * f'c\"\nproof -\n  let ?h = \"\\<lambda>x. (f b - f a) * g x - (g b - g a) * f x\"\n  have \"\\<exists>l z. a < z \\<and> z < b \\<and> DERIV ?h z :> l \\<and> ?h b - ?h a = (b - a) * l\"\n  proof (rule MVT)\n    from assms show \"a < b\" by simp\n    show \"continuous_on {a..b} ?h\"\n      by (simp add: continuous_at_imp_continuous_on fc gc)\n    show \"\\<And>x. \\<lbrakk>a < x; x < b\\<rbrakk> \\<Longrightarrow> ?h differentiable (at x)\"\n      using fd gd by simp\n  qed\n  then obtain l where l: \"\\<exists>z. a < z \\<and> z < b \\<and> DERIV ?h z :> l \\<and> ?h b - ?h a = (b - a) * l\" ..\n  then obtain c where c: \"a < c \\<and> c < b \\<and> DERIV ?h c :> l \\<and> ?h b - ?h a = (b - a) * l\" ..\n\n  from c have cint: \"a < c \\<and> c < b\" by auto\n  then obtain g'c where g'c: \"DERIV g c :> g'c\"\n    using gd real_differentiable_def by blast \n  from c have \"a < c \\<and> c < b\" by auto\n  then obtain f'c where f'c: \"DERIV f c :> f'c\"\n    using fd real_differentiable_def by blast \n\n  from c have \"DERIV ?h c :> l\" by auto\n  moreover have \"DERIV ?h c :>  g'c * (f b - f a) - f'c * (g b - g a)\"\n    using g'c f'c by (auto intro!: derivative_eq_intros)\n  ultimately have leq: \"l =  g'c * (f b - f a) - f'c * (g b - g a)\" by (rule DERIV_unique)\n\n  have \"?h b - ?h a = (b - a) * (g'c * (f b - f a) - f'c * (g b - g a))\"\n  proof -\n    from c have \"?h b - ?h a = (b - a) * l\" by auto\n    also from leq have \"\\<dots> = (b - a) * (g'c * (f b - f a) - f'c * (g b - g a))\" by simp\n    finally show ?thesis by simp\n  qed\n  moreover have \"?h b - ?h a = 0\"\n  proof -\n    have \"?h b - ?h a =\n      ((f b)*(g b) - (f a)*(g b) - (g b)*(f b) + (g a)*(f b)) -\n      ((f b)*(g a) - (f a)*(g a) - (g b)*(f a) + (g a)*(f a))\"\n      by (simp add: algebra_simps)\n    then show ?thesis  by auto\n  qed\n  ultimately have \"(b - a) * (g'c * (f b - f a) - f'c * (g b - g a)) = 0\" by auto\n  with alb have \"g'c * (f b - f a) - f'c * (g b - g a) = 0\" by simp\n  then have \"g'c * (f b - f a) = f'c * (g b - g a)\" by simp\n  then have \"(f b - f a) * g'c = (g b - g a) * f'c\" by (simp add: ac_simps)\n  with g'c f'c cint show ?thesis by auto\nqed\n\nlemma GMVT':\n  fixes f g :: \"real \\<Rightarrow> real\"\n  assumes \"a < b\"\n    and isCont_f: \"\\<And>z. a \\<le> z \\<Longrightarrow> z \\<le> b \\<Longrightarrow> isCont f z\"\n    and isCont_g: \"\\<And>z. a \\<le> z \\<Longrightarrow> z \\<le> b \\<Longrightarrow> isCont g z\"\n    and DERIV_g: \"\\<And>z. a < z \\<Longrightarrow> z < b \\<Longrightarrow> DERIV g z :> (g' z)\"\n    and DERIV_f: \"\\<And>z. a < z \\<Longrightarrow> z < b \\<Longrightarrow> DERIV f z :> (f' z)\"\n  shows \"\\<exists>c. a < c \\<and> c < b \\<and> (f b - f a) * g' c = (g b - g a) * f' c\"\nproof -\n  have \"\\<exists>g'c f'c c. DERIV g c :> g'c \\<and> DERIV f c :> f'c \\<and>\n      a < c \\<and> c < b \\<and> (f b - f a) * g'c = (g b - g a) * f'c\"\n    using assms by (intro GMVT) (force simp: real_differentiable_def)+\n  then obtain c where \"a < c\" \"c < b\" \"(f b - f a) * g' c = (g b - g a) * f' c\"\n    using DERIV_f DERIV_g by (force dest: DERIV_unique)\n  then show ?thesis\n    by auto\nqed\n\n\nsubsection \\<open>L'Hopitals rule\\<close>\n\nlemma isCont_If_ge:\n  fixes a :: \"'a :: linorder_topology\"\n  assumes \"continuous (at_left a) g\" and f: \"(f \\<longlongrightarrow> g a) (at_right a)\"\n  shows \"isCont (\\<lambda>x. if x \\<le> a then g x else f x) a\" (is \"isCont ?gf a\")\nproof -\n  have g: \"(g \\<longlongrightarrow> g a) (at_left a)\"\n    using assms continuous_within by blast\n  show ?thesis\n    unfolding isCont_def continuous_within\n  proof (intro filterlim_split_at; simp)\n    show \"(?gf \\<longlongrightarrow> g a) (at_left a)\"\n      by (subst filterlim_cong[OF refl refl, where g=g]) (simp_all add: eventually_at_filter less_le g)\n    show \"(?gf \\<longlongrightarrow> g a) (at_right a)\"\n      by (subst filterlim_cong[OF refl refl, where g=f]) (simp_all add: eventually_at_filter less_le f)\n  qed\nqed\n\nlemma lhopital_right_0:\n  fixes f0 g0 :: \"real \\<Rightarrow> real\"\n  assumes f_0: \"(f0 \\<longlongrightarrow> 0) (at_right 0)\"\n    and g_0: \"(g0 \\<longlongrightarrow> 0) (at_right 0)\"\n    and ev:\n      \"eventually (\\<lambda>x. g0 x \\<noteq> 0) (at_right 0)\"\n      \"eventually (\\<lambda>x. g' x \\<noteq> 0) (at_right 0)\"\n      \"eventually (\\<lambda>x. DERIV f0 x :> f' x) (at_right 0)\"\n      \"eventually (\\<lambda>x. DERIV g0 x :> g' x) (at_right 0)\"\n    and lim: \"filterlim (\\<lambda> x. (f' x / g' x)) F (at_right 0)\"\n  shows \"filterlim (\\<lambda> x. f0 x / g0 x) F (at_right 0)\"\nproof -\n  define f where [abs_def]: \"f x = (if x \\<le> 0 then 0 else f0 x)\" for x\n  then have \"f 0 = 0\" by simp\n\n  define g where [abs_def]: \"g x = (if x \\<le> 0 then 0 else g0 x)\" for x\n  then have \"g 0 = 0\" by simp\n\n  have \"eventually (\\<lambda>x. g0 x \\<noteq> 0 \\<and> g' x \\<noteq> 0 \\<and>\n      DERIV f0 x :> (f' x) \\<and> DERIV g0 x :> (g' x)) (at_right 0)\"\n    using ev by eventually_elim auto\n  then obtain a where [arith]: \"0 < a\"\n    and g0_neq_0: \"\\<And>x. 0 < x \\<Longrightarrow> x < a \\<Longrightarrow> g0 x \\<noteq> 0\"\n    and g'_neq_0: \"\\<And>x. 0 < x \\<Longrightarrow> x < a \\<Longrightarrow> g' x \\<noteq> 0\"\n    and f0: \"\\<And>x. 0 < x \\<Longrightarrow> x < a \\<Longrightarrow> DERIV f0 x :> (f' x)\"\n    and g0: \"\\<And>x. 0 < x \\<Longrightarrow> x < a \\<Longrightarrow> DERIV g0 x :> (g' x)\"\n    unfolding eventually_at by (auto simp: dist_real_def)\n\n  have g_neq_0: \"\\<And>x. 0 < x \\<Longrightarrow> x < a \\<Longrightarrow> g x \\<noteq> 0\"\n    using g0_neq_0 by (simp add: g_def)\n\n  have f: \"DERIV f x :> (f' x)\" if x: \"0 < x\" \"x < a\" for x\n    using that\n    by (intro DERIV_cong_ev[THEN iffD1, OF _ _ _ f0[OF x]])\n      (auto simp: f_def eventually_nhds_metric dist_real_def intro!: exI[of _ x])\n\n  have g: \"DERIV g x :> (g' x)\" if x: \"0 < x\" \"x < a\" for x\n    using that\n    by (intro DERIV_cong_ev[THEN iffD1, OF _ _ _ g0[OF x]])\n         (auto simp: g_def eventually_nhds_metric dist_real_def intro!: exI[of _ x])\n\n  have \"isCont f 0\"\n    unfolding f_def by (intro isCont_If_ge f_0 continuous_const)\n\n  have \"isCont g 0\"\n    unfolding g_def by (intro isCont_If_ge g_0 continuous_const)\n\n  have \"\\<exists>\\<zeta>. \\<forall>x\\<in>{0 <..< a}. 0 < \\<zeta> x \\<and> \\<zeta> x < x \\<and> f x / g x = f' (\\<zeta> x) / g' (\\<zeta> x)\"\n  proof (rule bchoice, rule ballI)\n    fix x\n    assume \"x \\<in> {0 <..< a}\"\n    then have x[arith]: \"0 < x\" \"x < a\" by auto\n    with g'_neq_0 g_neq_0 \\<open>g 0 = 0\\<close> have g': \"\\<And>x. 0 < x \\<Longrightarrow> x < a  \\<Longrightarrow> 0 \\<noteq> g' x\" \"g 0 \\<noteq> g x\"\n      by auto\n    have \"\\<And>x. 0 \\<le> x \\<Longrightarrow> x < a \\<Longrightarrow> isCont f x\"\n      using \\<open>isCont f 0\\<close> f by (auto intro: DERIV_isCont simp: le_less)\n    moreover have \"\\<And>x. 0 \\<le> x \\<Longrightarrow> x < a \\<Longrightarrow> isCont g x\"\n      using \\<open>isCont g 0\\<close> g by (auto intro: DERIV_isCont simp: le_less)\n    ultimately have \"\\<exists>c. 0 < c \\<and> c < x \\<and> (f x - f 0) * g' c = (g x - g 0) * f' c\"\n      using f g \\<open>x < a\\<close> by (intro GMVT') auto\n    then obtain c where *: \"0 < c\" \"c < x\" \"(f x - f 0) * g' c = (g x - g 0) * f' c\"\n      by blast\n    moreover\n    from * g'(1)[of c] g'(2) have \"(f x - f 0)  / (g x - g 0) = f' c / g' c\"\n      by (simp add: field_simps)\n    ultimately show \"\\<exists>y. 0 < y \\<and> y < x \\<and> f x / g x = f' y / g' y\"\n      using \\<open>f 0 = 0\\<close> \\<open>g 0 = 0\\<close> by (auto intro!: exI[of _ c])\n  qed\n  then obtain \\<zeta> where \"\\<forall>x\\<in>{0 <..< a}. 0 < \\<zeta> x \\<and> \\<zeta> x < x \\<and> f x / g x = f' (\\<zeta> x) / g' (\\<zeta> x)\" ..\n  then have \\<zeta>: \"eventually (\\<lambda>x. 0 < \\<zeta> x \\<and> \\<zeta> x < x \\<and> f x / g x = f' (\\<zeta> x) / g' (\\<zeta> x)) (at_right 0)\"\n    unfolding eventually_at by (intro exI[of _ a]) (auto simp: dist_real_def)\n  moreover\n  from \\<zeta> have \"eventually (\\<lambda>x. norm (\\<zeta> x) \\<le> x) (at_right 0)\"\n    by eventually_elim auto\n  then have \"((\\<lambda>x. norm (\\<zeta> x)) \\<longlongrightarrow> 0) (at_right 0)\"\n    by (rule_tac real_tendsto_sandwich[where f=\"\\<lambda>x. 0\" and h=\"\\<lambda>x. x\"]) auto\n  then have \"(\\<zeta> \\<longlongrightarrow> 0) (at_right 0)\"\n    by (rule tendsto_norm_zero_cancel)\n  with \\<zeta> have \"filterlim \\<zeta> (at_right 0) (at_right 0)\"\n    by (auto elim!: eventually_mono simp: filterlim_at)\n  from this lim have \"filterlim (\\<lambda>t. f' (\\<zeta> t) / g' (\\<zeta> t)) F (at_right 0)\"\n    by (rule_tac filterlim_compose[of _ _ _ \\<zeta>])\n  ultimately have \"filterlim (\\<lambda>t. f t / g t) F (at_right 0)\" (is ?P)\n    by (rule_tac filterlim_cong[THEN iffD1, OF refl refl])\n       (auto elim: eventually_mono)\n  also have \"?P \\<longleftrightarrow> ?thesis\"\n    by (rule filterlim_cong) (auto simp: f_def g_def eventually_at_filter)\n  finally show ?thesis .\nqed\n\nlemma lhopital_right:\n  \"(f \\<longlongrightarrow> 0) (at_right x) \\<Longrightarrow> (g \\<longlongrightarrow> 0) (at_right x) \\<Longrightarrow>\n    eventually (\\<lambda>x. g x \\<noteq> 0) (at_right x) \\<Longrightarrow>\n    eventually (\\<lambda>x. g' x \\<noteq> 0) (at_right x) \\<Longrightarrow>\n    eventually (\\<lambda>x. DERIV f x :> f' x) (at_right x) \\<Longrightarrow>\n    eventually (\\<lambda>x. DERIV g x :> g' x) (at_right x) \\<Longrightarrow>\n    filterlim (\\<lambda> x. (f' x / g' x)) F (at_right x) \\<Longrightarrow>\n  filterlim (\\<lambda> x. f x / g x) F (at_right x)\"\n  for x :: real\n  unfolding eventually_at_right_to_0[of _ x] filterlim_at_right_to_0[of _ _ x] DERIV_shift\n  by (rule lhopital_right_0)\n\nlemma lhopital_left:\n  \"(f \\<longlongrightarrow> 0) (at_left x) \\<Longrightarrow> (g \\<longlongrightarrow> 0) (at_left x) \\<Longrightarrow>\n    eventually (\\<lambda>x. g x \\<noteq> 0) (at_left x) \\<Longrightarrow>\n    eventually (\\<lambda>x. g' x \\<noteq> 0) (at_left x) \\<Longrightarrow>\n    eventually (\\<lambda>x. DERIV f x :> f' x) (at_left x) \\<Longrightarrow>\n    eventually (\\<lambda>x. DERIV g x :> g' x) (at_left x) \\<Longrightarrow>\n    filterlim (\\<lambda> x. (f' x / g' x)) F (at_left x) \\<Longrightarrow>\n  filterlim (\\<lambda> x. f x / g x) F (at_left x)\"\n  for x :: real\n  unfolding eventually_at_left_to_right filterlim_at_left_to_right DERIV_mirror\n  by (rule lhopital_right[where f'=\"\\<lambda>x. - f' (- x)\"]) (auto simp: DERIV_mirror)\n\nlemma lhopital:\n  \"(f \\<longlongrightarrow> 0) (at x) \\<Longrightarrow> (g \\<longlongrightarrow> 0) (at x) \\<Longrightarrow>\n    eventually (\\<lambda>x. g x \\<noteq> 0) (at x) \\<Longrightarrow>\n    eventually (\\<lambda>x. g' x \\<noteq> 0) (at x) \\<Longrightarrow>\n    eventually (\\<lambda>x. DERIV f x :> f' x) (at x) \\<Longrightarrow>\n    eventually (\\<lambda>x. DERIV g x :> g' x) (at x) \\<Longrightarrow>\n    filterlim (\\<lambda> x. (f' x / g' x)) F (at x) \\<Longrightarrow>\n  filterlim (\\<lambda> x. f x / g x) F (at x)\"\n  for x :: real\n  unfolding eventually_at_split filterlim_at_split\n  by (auto intro!: lhopital_right[of f x g g' f'] lhopital_left[of f x g g' f'])\n\n\nlemma lhopital_right_0_at_top:\n  fixes f g :: \"real \\<Rightarrow> real\"\n  assumes g_0: \"LIM x at_right 0. g x :> at_top\"\n    and ev:\n      \"eventually (\\<lambda>x. g' x \\<noteq> 0) (at_right 0)\"\n      \"eventually (\\<lambda>x. DERIV f x :> f' x) (at_right 0)\"\n      \"eventually (\\<lambda>x. DERIV g x :> g' x) (at_right 0)\"\n    and lim: \"((\\<lambda> x. (f' x / g' x)) \\<longlongrightarrow> x) (at_right 0)\"\n  shows \"((\\<lambda> x. f x / g x) \\<longlongrightarrow> x) (at_right 0)\"\n  unfolding tendsto_iff\nproof safe\n  fix e :: real\n  assume \"0 < e\"\n  with lim[unfolded tendsto_iff, rule_format, of \"e / 4\"]\n  have \"eventually (\\<lambda>t. dist (f' t / g' t) x < e / 4) (at_right 0)\"\n    by simp\n  from eventually_conj[OF eventually_conj[OF ev(1) ev(2)] eventually_conj[OF ev(3) this]]\n  obtain a where [arith]: \"0 < a\"\n    and g'_neq_0: \"\\<And>x. 0 < x \\<Longrightarrow> x < a \\<Longrightarrow> g' x \\<noteq> 0\"\n    and f0: \"\\<And>x. 0 < x \\<Longrightarrow> x \\<le> a \\<Longrightarrow> DERIV f x :> (f' x)\"\n    and g0: \"\\<And>x. 0 < x \\<Longrightarrow> x \\<le> a \\<Longrightarrow> DERIV g x :> (g' x)\"\n    and Df: \"\\<And>t. 0 < t \\<Longrightarrow> t < a \\<Longrightarrow> dist (f' t / g' t) x < e / 4\"\n    unfolding eventually_at_le by (auto simp: dist_real_def)\n\n  from Df have \"eventually (\\<lambda>t. t < a) (at_right 0)\" \"eventually (\\<lambda>t::real. 0 < t) (at_right 0)\"\n    unfolding eventually_at by (auto intro!: exI[of _ a] simp: dist_real_def)\n\n  moreover\n  have \"eventually (\\<lambda>t. 0 < g t) (at_right 0)\" \"eventually (\\<lambda>t. g a < g t) (at_right 0)\"\n    using g_0 by (auto elim: eventually_mono simp: filterlim_at_top_dense)\n\n  moreover\n  have inv_g: \"((\\<lambda>x. inverse (g x)) \\<longlongrightarrow> 0) (at_right 0)\"\n    using tendsto_inverse_0 filterlim_mono[OF g_0 at_top_le_at_infinity order_refl]\n    by (rule filterlim_compose)\n  then have \"((\\<lambda>x. norm (1 - g a * inverse (g x))) \\<longlongrightarrow> norm (1 - g a * 0)) (at_right 0)\"\n    by (intro tendsto_intros)\n  then have \"((\\<lambda>x. norm (1 - g a / g x)) \\<longlongrightarrow> 1) (at_right 0)\"\n    by (simp add: inverse_eq_divide)\n  from this[unfolded tendsto_iff, rule_format, of 1]\n  have \"eventually (\\<lambda>x. norm (1 - g a / g x) < 2) (at_right 0)\"\n    by (auto elim!: eventually_mono simp: dist_real_def)\n\n  moreover\n  from inv_g have \"((\\<lambda>t. norm ((f a - x * g a) * inverse (g t))) \\<longlongrightarrow> norm ((f a - x * g a) * 0))\n      (at_right 0)\"\n    by (intro tendsto_intros)\n  then have \"((\\<lambda>t. norm (f a - x * g a) / norm (g t)) \\<longlongrightarrow> 0) (at_right 0)\"\n    by (simp add: inverse_eq_divide)\n  from this[unfolded tendsto_iff, rule_format, of \"e / 2\"] \\<open>0 < e\\<close>\n  have \"eventually (\\<lambda>t. norm (f a - x * g a) / norm (g t) < e / 2) (at_right 0)\"\n    by (auto simp: dist_real_def)\n\n  ultimately show \"eventually (\\<lambda>t. dist (f t / g t) x < e) (at_right 0)\"\n  proof eventually_elim\n    fix t assume t[arith]: \"0 < t\" \"t < a\" \"g a < g t\" \"0 < g t\"\n    assume ineq: \"norm (1 - g a / g t) < 2\" \"norm (f a - x * g a) / norm (g t) < e / 2\"\n\n    have \"\\<exists>y. t < y \\<and> y < a \\<and> (g a - g t) * f' y = (f a - f t) * g' y\"\n      using f0 g0 t(1,2) by (intro GMVT') (force intro!: DERIV_isCont)+\n    then obtain y where [arith]: \"t < y\" \"y < a\"\n      and D_eq0: \"(g a - g t) * f' y = (f a - f t) * g' y\"\n      by blast\n    from D_eq0 have D_eq: \"(f t - f a) / (g t - g a) = f' y / g' y\"\n      using \\<open>g a < g t\\<close> g'_neq_0[of y] by (auto simp add: field_simps)\n\n    have *: \"f t / g t - x = ((f t - f a) / (g t - g a) - x) * (1 - g a / g t) + (f a - x * g a) / g t\"\n      by (simp add: field_simps)\n    have \"norm (f t / g t - x) \\<le>\n        norm (((f t - f a) / (g t - g a) - x) * (1 - g a / g t)) + norm ((f a - x * g a) / g t)\"\n      unfolding * by (rule norm_triangle_ineq)\n    also have \"\\<dots> = dist (f' y / g' y) x * norm (1 - g a / g t) + norm (f a - x * g a) / norm (g t)\"\n      by (simp add: abs_mult D_eq dist_real_def)\n    also have \"\\<dots> < (e / 4) * 2 + e / 2\"\n      using ineq Df[of y] \\<open>0 < e\\<close> by (intro add_le_less_mono mult_mono) auto\n    finally show \"dist (f t / g t) x < e\"\n      by (simp add: dist_real_def)\n  qed\nqed\n\nlemma lhopital_right_at_top:\n  \"LIM x at_right x. (g::real \\<Rightarrow> real) x :> at_top \\<Longrightarrow>\n    eventually (\\<lambda>x. g' x \\<noteq> 0) (at_right x) \\<Longrightarrow>\n    eventually (\\<lambda>x. DERIV f x :> f' x) (at_right x) \\<Longrightarrow>\n    eventually (\\<lambda>x. DERIV g x :> g' x) (at_right x) \\<Longrightarrow>\n    ((\\<lambda> x. (f' x / g' x)) \\<longlongrightarrow> y) (at_right x) \\<Longrightarrow>\n    ((\\<lambda> x. f x / g x) \\<longlongrightarrow> y) (at_right x)\"\n  unfolding eventually_at_right_to_0[of _ x] filterlim_at_right_to_0[of _ _ x] DERIV_shift\n  by (rule lhopital_right_0_at_top)\n\nlemma lhopital_left_at_top:\n  \"LIM x at_left x. g x :> at_top \\<Longrightarrow>\n    eventually (\\<lambda>x. g' x \\<noteq> 0) (at_left x) \\<Longrightarrow>\n    eventually (\\<lambda>x. DERIV f x :> f' x) (at_left x) \\<Longrightarrow>\n    eventually (\\<lambda>x. DERIV g x :> g' x) (at_left x) \\<Longrightarrow>\n    ((\\<lambda> x. (f' x / g' x)) \\<longlongrightarrow> y) (at_left x) \\<Longrightarrow>\n    ((\\<lambda> x. f x / g x) \\<longlongrightarrow> y) (at_left x)\"\n  for x :: real\n  unfolding eventually_at_left_to_right filterlim_at_left_to_right DERIV_mirror\n  by (rule lhopital_right_at_top[where f'=\"\\<lambda>x. - f' (- x)\"]) (auto simp: DERIV_mirror)\n\nlemma lhopital_at_top:\n  \"LIM x at x. (g::real \\<Rightarrow> real) x :> at_top \\<Longrightarrow>\n    eventually (\\<lambda>x. g' x \\<noteq> 0) (at x) \\<Longrightarrow>\n    eventually (\\<lambda>x. DERIV f x :> f' x) (at x) \\<Longrightarrow>\n    eventually (\\<lambda>x. DERIV g x :> g' x) (at x) \\<Longrightarrow>\n    ((\\<lambda> x. (f' x / g' x)) \\<longlongrightarrow> y) (at x) \\<Longrightarrow>\n    ((\\<lambda> x. f x / g x) \\<longlongrightarrow> y) (at x)\"\n  unfolding eventually_at_split filterlim_at_split\n  by (auto intro!: lhopital_right_at_top[of g x g' f f'] lhopital_left_at_top[of g x g' f f'])\n\nlemma lhospital_at_top_at_top:\n  fixes f g :: \"real \\<Rightarrow> real\"\n  assumes g_0: \"LIM x at_top. g x :> at_top\"\n    and g': \"eventually (\\<lambda>x. g' x \\<noteq> 0) at_top\"\n    and Df: \"eventually (\\<lambda>x. DERIV f x :> f' x) at_top\"\n    and Dg: \"eventually (\\<lambda>x. DERIV g x :> g' x) at_top\"\n    and lim: \"((\\<lambda> x. (f' x / g' x)) \\<longlongrightarrow> x) at_top\"\n  shows \"((\\<lambda> x. f x / g x) \\<longlongrightarrow> x) at_top\"\n  unfolding filterlim_at_top_to_right\nproof (rule lhopital_right_0_at_top)\n  let ?F = \"\\<lambda>x. f (inverse x)\"\n  let ?G = \"\\<lambda>x. g (inverse x)\"\n  let ?R = \"at_right (0::real)\"\n  let ?D = \"\\<lambda>f' x. f' (inverse x) * - (inverse x ^ Suc (Suc 0))\"\n  show \"LIM x ?R. ?G x :> at_top\"\n    using g_0 unfolding filterlim_at_top_to_right .\n  show \"eventually (\\<lambda>x. DERIV ?G x  :> ?D g' x) ?R\"\n    unfolding eventually_at_right_to_top\n    using Dg eventually_ge_at_top[where c=1]\n    by eventually_elim (rule derivative_eq_intros DERIV_chain'[where f=inverse] | simp)+\n  show \"eventually (\\<lambda>x. DERIV ?F x  :> ?D f' x) ?R\"\n    unfolding eventually_at_right_to_top\n    using Df eventually_ge_at_top[where c=1]\n    by eventually_elim (rule derivative_eq_intros DERIV_chain'[where f=inverse] | simp)+\n  show \"eventually (\\<lambda>x. ?D g' x \\<noteq> 0) ?R\"\n    unfolding eventually_at_right_to_top\n    using g' eventually_ge_at_top[where c=1]\n    by eventually_elim auto\n  show \"((\\<lambda>x. ?D f' x / ?D g' x) \\<longlongrightarrow> x) ?R\"\n    unfolding filterlim_at_right_to_top\n    apply (intro filterlim_cong[THEN iffD2, OF refl refl _ lim])\n    using eventually_ge_at_top[where c=1]\n    by eventually_elim simp\nqed\n\nlemma lhopital_right_at_top_at_top:\n  fixes f g :: \"real \\<Rightarrow> real\"\n  assumes f_0: \"LIM x at_right a. f x :> at_top\"\n  assumes g_0: \"LIM x at_right a. g x :> at_top\"\n    and ev:\n      \"eventually (\\<lambda>x. DERIV f x :> f' x) (at_right a)\"\n      \"eventually (\\<lambda>x. DERIV g x :> g' x) (at_right a)\"\n    and lim: \"filterlim (\\<lambda> x. (f' x / g' x)) at_top (at_right a)\"\n  shows \"filterlim (\\<lambda> x. f x / g x) at_top (at_right a)\"\nproof -\n  from lim have pos: \"eventually (\\<lambda>x. f' x / g' x > 0) (at_right a)\"\n    unfolding filterlim_at_top_dense by blast\n  have \"((\\<lambda>x. g x / f x) \\<longlongrightarrow> 0) (at_right a)\"\n  proof (rule lhopital_right_at_top)\n    from pos show \"eventually (\\<lambda>x. f' x \\<noteq> 0) (at_right a)\" by eventually_elim auto\n    from tendsto_inverse_0_at_top[OF lim]\n      show \"((\\<lambda>x. g' x / f' x) \\<longlongrightarrow> 0) (at_right a)\" by simp\n  qed fact+\n  moreover from f_0 g_0 \n    have \"eventually (\\<lambda>x. f x > 0) (at_right a)\" \"eventually (\\<lambda>x. g x > 0) (at_right a)\"\n    unfolding filterlim_at_top_dense by blast+\n  hence \"eventually (\\<lambda>x. g x / f x > 0) (at_right a)\" by eventually_elim simp\n  ultimately have \"filterlim (\\<lambda>x. inverse (g x / f x)) at_top (at_right a)\"\n    by (rule filterlim_inverse_at_top)\n  thus ?thesis by simp\nqed\n\nlemma lhopital_right_at_top_at_bot:\n  fixes f g :: \"real \\<Rightarrow> real\"\n  assumes f_0: \"LIM x at_right a. f x :> at_top\"\n  assumes g_0: \"LIM x at_right a. g x :> at_bot\"\n    and ev:\n      \"eventually (\\<lambda>x. DERIV f x :> f' x) (at_right a)\"\n      \"eventually (\\<lambda>x. DERIV g x :> g' x) (at_right a)\"\n    and lim: \"filterlim (\\<lambda> x. (f' x / g' x)) at_bot (at_right a)\"\n  shows \"filterlim (\\<lambda> x. f x / g x) at_bot (at_right a)\"\nproof -\n  from ev(2) have ev': \"eventually (\\<lambda>x. DERIV (\\<lambda>x. -g x) x :> -g' x) (at_right a)\"\n    by eventually_elim (auto intro: derivative_intros)\n  have \"filterlim (\\<lambda>x. f x / (-g x)) at_top (at_right a)\"\n    by (rule lhopital_right_at_top_at_top[where f' = f' and g' = \"\\<lambda>x. -g' x\"])\n       (insert assms ev', auto simp: filterlim_uminus_at_bot)\n  hence \"filterlim (\\<lambda>x. -(f x / g x)) at_top (at_right a)\" by simp\n  thus ?thesis by (simp add: filterlim_uminus_at_bot)\nqed\n\nlemma lhopital_left_at_top_at_top:\n  fixes f g :: \"real \\<Rightarrow> real\"\n  assumes f_0: \"LIM x at_left a. f x :> at_top\"\n  assumes g_0: \"LIM x at_left a. g x :> at_top\"\n    and ev:\n      \"eventually (\\<lambda>x. DERIV f x :> f' x) (at_left a)\"\n      \"eventually (\\<lambda>x. DERIV g x :> g' x) (at_left a)\"\n    and lim: \"filterlim (\\<lambda> x. (f' x / g' x)) at_top (at_left a)\"\n  shows \"filterlim (\\<lambda> x. f x / g x) at_top (at_left a)\"\n  by (insert assms, unfold eventually_at_left_to_right filterlim_at_left_to_right DERIV_mirror,\n      rule lhopital_right_at_top_at_top[where f'=\"\\<lambda>x. - f' (- x)\"]) \n     (insert assms, auto simp: DERIV_mirror)\n\nlemma lhopital_left_at_top_at_bot:\n  fixes f g :: \"real \\<Rightarrow> real\"\n  assumes f_0: \"LIM x at_left a. f x :> at_top\"\n  assumes g_0: \"LIM x at_left a. g x :> at_bot\"\n    and ev:\n      \"eventually (\\<lambda>x. DERIV f x :> f' x) (at_left a)\"\n      \"eventually (\\<lambda>x. DERIV g x :> g' x) (at_left a)\"\n    and lim: \"filterlim (\\<lambda> x. (f' x / g' x)) at_bot (at_left a)\"\n  shows \"filterlim (\\<lambda> x. f x / g x) at_bot (at_left a)\"\n  by (insert assms, unfold eventually_at_left_to_right filterlim_at_left_to_right DERIV_mirror,\n      rule lhopital_right_at_top_at_bot[where f'=\"\\<lambda>x. - f' (- x)\"]) \n     (insert assms, auto simp: DERIV_mirror)\n\nlemma lhopital_at_top_at_top:\n  fixes f g :: \"real \\<Rightarrow> real\"\n  assumes f_0: \"LIM x at a. f x :> at_top\"\n  assumes g_0: \"LIM x at a. g x :> at_top\"\n    and ev:\n      \"eventually (\\<lambda>x. DERIV f x :> f' x) (at a)\"\n      \"eventually (\\<lambda>x. DERIV g x :> g' x) (at a)\"\n    and lim: \"filterlim (\\<lambda> x. (f' x / g' x)) at_top (at a)\"\n  shows \"filterlim (\\<lambda> x. f x / g x) at_top (at a)\"\n  using assms unfolding eventually_at_split filterlim_at_split\n  by (auto intro!: lhopital_right_at_top_at_top[of f a g f' g'] \n                   lhopital_left_at_top_at_top[of f a g f' g'])\n\nlemma lhopital_at_top_at_bot:\n  fixes f g :: \"real \\<Rightarrow> real\"\n  assumes f_0: \"LIM x at a. f x :> at_top\"\n  assumes g_0: \"LIM x at a. g x :> at_bot\"\n    and ev:\n      \"eventually (\\<lambda>x. DERIV f x :> f' x) (at a)\"\n      \"eventually (\\<lambda>x. DERIV g x :> g' x) (at a)\"\n    and lim: \"filterlim (\\<lambda> x. (f' x / g' x)) at_bot (at a)\"\n  shows \"filterlim (\\<lambda> x. f x / g x) at_bot (at a)\"\n  using assms unfolding eventually_at_split filterlim_at_split\n  by (auto intro!: lhopital_right_at_top_at_bot[of f a g f' g'] \n                   lhopital_left_at_top_at_bot[of f a g f' g'])\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/Deriv.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8723473746782093, "lm_q2_score": 0.847967764140929, "lm_q1q2_score": 0.7397224528600904}}
{"text": "(*  Title:      Composition Series\n    Author:     Jakob von Raumer, Karlsruhe Institute of Technology\n    Maintainer: Jakob von Raumer <jakob.raumer@student.kit.edu>\n*)\n\ntheory CompositionSeries\nimports\n  MaximalNormalSubgroups Secondary_Sylow.SndSylow\nbegin\n\nhide_const (open) Divisibility.prime\n\nsection \\<open>Normal series and Composition series\\<close>\n\nsubsection \\<open>Preliminaries\\<close>\n\ntext \\<open>A subgroup which is unique in cardinality is normal:\\<close>\n\nlemma (in group) unique_sizes_subgrp_normal:\n  assumes fin: \"finite (carrier G)\"\n  assumes \"\\<exists>!Q. Q \\<in> subgroups_of_size q\"\n  shows \"(THE Q. Q \\<in> subgroups_of_size q) \\<lhd> G\"\nproof -\n  from assms obtain Q where \"Q \\<in> subgroups_of_size q\" by auto\n  define Q where \"Q = (THE Q. Q \\<in> subgroups_of_size q)\"\n  with assms have Qsize: \"Q \\<in> subgroups_of_size q\" using theI by metis\n  hence QG: \"subgroup Q G\" and cardQ: \"card Q = q\" unfolding subgroups_of_size_def by auto\n  from QG have \"Q \\<lhd> G\" apply(rule normalI)\n  proof\n    fix g\n    assume g: \"g \\<in> carrier G\"\n    hence invg: \"inv g \\<in> carrier G\" by (metis inv_closed)\n    with fin Qsize have \"conjugation_action q (inv g) Q \\<in> subgroups_of_size q\" by (metis conjugation_is_size_invariant)\n    with g Qsize have \"(inv g) <# (Q #> inv (inv g)) \\<in> subgroups_of_size q\" unfolding conjugation_action_def by auto\n    with invg g have \"inv g <# (Q #> g) = Q\" by (metis Qsize assms(2) inv_inv)\n    with QG QG g show \"Q #> g = g <# Q\" by (rule conj_wo_inv)\n  qed\n  with Q_def show ?thesis by simp\nqed\n\ntext \\<open>A group whose order is the product of two distinct\nprimes $p$ and $q$ where $p < q$ has a unique subgroup of size $q$:\\<close>\n\nlemma (in group) pq_order_unique_subgrp:\n  assumes finite: \"finite (carrier G)\"\n  assumes orderG: \"order G = q * p\"\n  assumes primep: \"prime p\" and primeq: \"prime q\" and pq: \"p < q\"\n  shows \"\\<exists>!Q. Q \\<in> (subgroups_of_size q)\"\nproof -\n  from primep primeq pq have nqdvdp: \"\\<not> (q dvd p)\" by (metis less_not_refl3 prime_nat_iff)\n  define calM where \"calM = {s. s \\<subseteq> carrier G \\<and> card s = q ^ 1}\"\n  define RelM where \"RelM = {(N1, N2). N1 \\<in> calM \\<and> N2 \\<in> calM \\<and> (\\<exists>g\\<in>carrier G. N1 = N2 #> g)}\"\n  interpret syl: snd_sylow G q 1 p calM RelM\n    unfolding snd_sylow_def sylow_def snd_sylow_axioms_def sylow_axioms_def\n    using is_group primeq orderG finite nqdvdp calM_def RelM_def by auto\n  obtain Q where Q: \"Q \\<in> subgroups_of_size q\" by (metis (lifting, mono_tags) mem_Collect_eq power_one_right subgroups_of_size_def syl.sylow_thm)\n  thus ?thesis \n  proof (rule ex1I)\n     fix P\n     assume P: \"P \\<in> subgroups_of_size q\"\n     have \"card (subgroups_of_size q) mod q = 1\" by (metis power_one_right syl.p_sylow_mod_p)     \n     moreover have \"card (subgroups_of_size q) dvd p\" by (metis power_one_right syl.num_sylow_dvd_remainder)\n     then have \"card (subgroups_of_size q) = p \\<or> card (subgroups_of_size q) = 1\"\n       using primep by (auto simp add: prime_nat_iff)\n     ultimately have \"card (subgroups_of_size q) = 1\" using pq\n       by auto\n     with Q P show \"P = Q\" by (auto simp:card_Suc_eq)\n  qed\nqed\n\ntext \\<open>... And this unique subgroup is normal.\\<close>\n\ncorollary (in group) pq_order_subgrp_normal:\n  assumes finite: \"finite (carrier G)\"\n  assumes orderG: \"order G = q * p\"\n  assumes primep: \"prime p\" and primeq: \"prime q\" and pq: \"p < q\"\n  shows \"(THE Q. Q \\<in> subgroups_of_size q) \\<lhd> G\"\nusing assms by (metis pq_order_unique_subgrp unique_sizes_subgrp_normal)\n\ntext \\<open>The trivial subgroup is normal in every group.\\<close>\n\nlemma (in group) trivial_subgroup_is_normal:\n  shows \"{\\<one>} \\<lhd> G\"\nunfolding normal_def normal_axioms_def r_coset_def l_coset_def by (auto intro: normalI subgroupI simp: is_group)\n\nsubsection \\<open>Normal Series\\<close>\n\ntext \\<open>We define a normal series as a locale which fixes one group\n@{term G} and a list @{term \\<GG>} of subsets of @{term G}'s carrier. This list\nmust begin with the trivial subgroup, end with the carrier of the group itself\nand each of the list items must be a normal subgroup of its successor.\\<close>\n\nlocale normal_series = group +\n  fixes \\<GG>\n  assumes notempty: \"\\<GG> \\<noteq> []\"\n  assumes hd: \"hd \\<GG> = {\\<one>}\"\n  assumes last: \"last \\<GG> = carrier G\"\n  assumes normal: \"\\<And>i. i + 1 < length \\<GG> \\<Longrightarrow> (\\<GG> ! i) \\<lhd> G\\<lparr>carrier := \\<GG> ! (i + 1)\\<rparr>\"\n\nlemma (in normal_series) is_normal_series: \"normal_series G \\<GG>\" by (rule normal_series_axioms)\n\ntext \\<open>For every group there is a \"trivial\" normal series consisting\nonly of the group itself and its trivial subgroup.\\<close>\n\nlemma (in group) trivial_normal_series:\n  shows \"normal_series G [{\\<one>}, carrier G]\"\nunfolding normal_series_def normal_series_axioms_def\nusing is_group trivial_subgroup_is_normal by auto\n\ntext \\<open>We can also show that the normal series presented above is the only such with\na length of two:\\<close>\n\nlemma (in normal_series) length_two_unique:\n  assumes \"length \\<GG> = 2\"\n  shows \"\\<GG> = [{\\<one>}, carrier G]\"\nproof(rule nth_equalityI)\n  from assms show \"length \\<GG> = length [{\\<one>}, carrier G]\" by auto\nnext\n  show \"\\<GG> ! i = [{\\<one>}, carrier G] ! i\" if i: \"i < length \\<GG>\" for i\n  proof -\n    have \"i = 0 \\<or> i = 1\" using that assms by auto\n    thus \"\\<GG> ! i = [{\\<one>}, carrier G] ! i\"\n    proof(rule disjE)\n      assume i: \"i = 0\"\n      hence \"\\<GG> ! i = hd \\<GG>\" by (metis hd_conv_nth notempty)\n      thus \"\\<GG> ! i = [{\\<one>}, carrier G] ! i\" using hd i by simp\n    next\n      assume i: \"i = 1\"\n      with assms have \"\\<GG> ! i = last \\<GG>\" by (metis diff_add_inverse last_conv_nth nat_1_add_1 notempty)\n      thus \"\\<GG> ! i = [{\\<one>}, carrier G] ! i\" using last i by simp\n    qed\n  qed\nqed\n\ntext \\<open>We can construct new normal series by expanding existing ones: If we\nappend the carrier of a group @{term G} to a normal series for a normal subgroup\n@{term \"H \\<lhd> G\"} we receive a normal series for @{term G}.\\<close>\n\nlemma (in group) normal_series_extend:\n  assumes normal: \"normal_series (G\\<lparr>carrier := H\\<rparr>) \\<HH>\"\n  assumes HG: \"H \\<lhd> G\"\n  shows \"normal_series G (\\<HH> @ [carrier G])\"\nproof -\n  from normal interpret normalH: normal_series \"(G\\<lparr>carrier := H\\<rparr>)\" \\<HH>.\n  from normalH.hd have \"hd \\<HH> = {\\<one>}\" by simp\n  with normalH.notempty have hdTriv: \"hd (\\<HH> @ [carrier G]) = {\\<one>}\" by (metis hd_append2)\n  show ?thesis unfolding normal_series_def normal_series_axioms_def using is_group\n  proof auto\n    fix x\n    assume \"x \\<in> hd (\\<HH> @ [carrier G])\"\n    with hdTriv show \"x = \\<one>\" by simp\n  next\n    from hdTriv show  \"\\<one> \\<in> hd (\\<HH> @ [carrier G])\" by simp\n  next\n    fix i\n    assume i: \"i < length \\<HH>\"\n    show \"(\\<HH> @ [carrier G]) ! i \\<lhd> G\\<lparr>carrier := (\\<HH> @ [carrier G]) ! Suc i\\<rparr>\"\n    proof (cases \"i + 1 < length \\<HH>\")\n      case True\n      with normalH.normal have \"\\<HH> ! i \\<lhd> G\\<lparr>carrier := \\<HH> ! (i + 1)\\<rparr>\" by auto\n      with i have \"(\\<HH> @ [carrier G]) ! i \\<lhd> G\\<lparr>carrier := \\<HH> ! (i + 1)\\<rparr>\" using nth_append by metis\n      with True show \"(\\<HH> @ [carrier G]) ! i \\<lhd> G\\<lparr>carrier := (\\<HH> @ [carrier G]) ! (Suc i)\\<rparr>\" using nth_append Suc_eq_plus1 by metis\n    next\n      case False\n      with i have i2: \"i + 1 = length \\<HH>\" by simp\n      from i have \"(\\<HH> @ [carrier G]) ! i = \\<HH> ! i\" by (metis nth_append)\n      also from i2 normalH.notempty have \"... = last \\<HH>\" by (metis add_diff_cancel_right' last_conv_nth)\n      also from normalH.last have \"... = H\" by simp\n      finally have \"(\\<HH> @ [carrier G]) ! i = H\".\n      moreover from i2 have \"(\\<HH> @ [carrier G]) ! (i + 1) = carrier G\" by (metis nth_append_length)\n      ultimately show ?thesis using HG by auto\n    qed\n  qed\nqed\n\ntext \\<open>All entries of a normal series for $G$ are subgroups of $G$.\\<close>\n\nlemma (in normal_series) normal_series_subgroups:\n  shows \"i < length \\<GG> \\<Longrightarrow> subgroup (\\<GG> ! i) G\"\nproof -\n  have \"i + 1 < length \\<GG> \\<Longrightarrow> subgroup (\\<GG> ! i) G\"\n  proof (induction \"length \\<GG> - (i + 2)\" arbitrary: i)\n    case 0\n    hence i: \"i + 2 = length \\<GG>\" by simp\n    hence ii: \"i + 1 = length \\<GG> - 1\" by force\n    from i normal have \"\\<GG> ! i \\<lhd> G\\<lparr>carrier := \\<GG> ! (i + 1)\\<rparr>\" by auto\n    with ii last notempty show \"subgroup (\\<GG> ! i) G\" using last_conv_nth normal_imp_subgroup by fastforce\n  next\n    case (Suc k)\n    from Suc(3)  normal have i: \"subgroup (\\<GG> ! i) (G\\<lparr>carrier := \\<GG> ! (i + 1)\\<rparr>)\" using normal_imp_subgroup by auto\n    from Suc(2) have k: \"k = length \\<GG> - ((i + 1) + 2)\" by arith\n    with Suc have \"subgroup (\\<GG> ! (i + 1)) G\" by simp\n    with i show \"subgroup (\\<GG> ! i) G\"\n      using incl_subgroup by blast\n  qed\n  moreover have \"i + 1 = length \\<GG> \\<Longrightarrow> subgroup (\\<GG> ! i) G\"\n    using last notempty last_conv_nth by (metis add_diff_cancel_right' subgroup_self)\n  ultimately show \"i < length \\<GG> \\<Longrightarrow> subgroup (\\<GG> ! i) G\" by force\nqed\n\ntext \\<open>The second to last entry of a normal series is a normal subgroup of G.\\<close>\n\nlemma (in normal_series) normal_series_snd_to_last:\n  shows \"\\<GG> ! (length \\<GG> - 2) \\<lhd> G\"\nproof (cases \"2 \\<le> length \\<GG>\")\n  case False\n  with notempty have length: \"length \\<GG> = 1\" by (metis Suc_eq_plus1 leI length_0_conv less_2_cases plus_nat.add_0)\n  with hd have \"\\<GG> ! (length \\<GG> - 2) = {\\<one>}\" using hd_conv_nth notempty by auto\n  with length show ?thesis by (metis trivial_subgroup_is_normal)\nnext\n  case True\n  hence \"(length \\<GG> - 2) + 1 < length \\<GG>\" by arith\n  with normal last have \"\\<GG> ! (length \\<GG> - 2) \\<lhd> G\\<lparr>carrier := \\<GG> ! ((length \\<GG> - 2) + 1)\\<rparr>\" by auto\n  have \"1 + (1 + (length \\<GG> - (1 + 1))) = length \\<GG>\"\n    using True le_add_diff_inverse by presburger\n  then have \"\\<GG> ! (length \\<GG> - 2) \\<lhd> G\\<lparr>carrier :=  \\<GG> ! (length \\<GG> - 1)\\<rparr>\"\n    by (metis \\<open>\\<GG> ! (length \\<GG> - 2) \\<lhd> G \\<lparr>carrier := \\<GG> ! (length \\<GG> - 2 + 1)\\<rparr>\\<close> add.commute add_diff_cancel_left' one_add_one)\n  with notempty last show ?thesis using last_conv_nth by force\nqed\n\ntext \\<open>Just like the expansion of normal series, every prefix of a normal series is again a normal series.\\<close>\n\nlemma (in normal_series) normal_series_prefix_closed:\n  assumes \"i \\<le> length \\<GG>\" and \"0 < i\"\n  shows \"normal_series (G\\<lparr>carrier := \\<GG> ! (i - 1)\\<rparr>) (take i \\<GG>)\"\nunfolding normal_series_def normal_series_axioms_def\nusing assms\napply (auto simp: hd del:equalityI)\n  apply (simp add: is_group normal_series_subgroups subgroup.subgroup_is_group)\n apply (simp add: last_conv_nth min.absorb2 notempty)\nusing assms(1) normal apply simp\ndone\n\ntext \\<open>If a group's order is the product of two distinct primes @{term p} and @{term q}, where\n@{term \"p < q\"}, we can construct a normal series using the only subgroup of size  @{term q}.\\<close>\n\nlemma (in group) pq_order_normal_series:\n  assumes finite: \"finite (carrier G)\"\n  assumes orderG: \"order G = q * p\"\n  assumes primep: \"prime p\" and primeq: \"prime q\" and pq: \"p < q\"\n  shows \"normal_series G [{\\<one>}, (THE H. H \\<in> subgroups_of_size q), carrier G]\"\nproof -\n  define H where \"H = (THE H. H \\<in> subgroups_of_size q)\"\n  with assms have HG: \"H \\<lhd> G\" by (metis pq_order_subgrp_normal)\n  then interpret groupH: group \"G\\<lparr>carrier := H\\<rparr>\" unfolding normal_def by (metis subgroup_imp_group)\n  have \"normal_series (G\\<lparr>carrier := H\\<rparr>) [{\\<one>}, H]\"  using groupH.trivial_normal_series by auto\n  with HG show ?thesis unfolding H_def by (metis append_Cons append_Nil normal_series_extend)\nqed\n\ntext \\<open>The following defines the list of all quotient groups of the normal series:\\<close>\n\ndefinition (in normal_series) quotients\n  where \"quotients = map (\\<lambda>i. G\\<lparr>carrier := \\<GG> ! (i + 1)\\<rparr> Mod \\<GG> ! i) [0..<((length \\<GG>) - 1)]\"\n\ntext \\<open>The list of quotient groups has one less entry than the series itself:\\<close>\n\nlemma (in normal_series) quotients_length:\n  shows \"length quotients + 1 = length \\<GG>\"\nproof -\n  have \"length quotients + 1 = length [0..<((length \\<GG>) - 1)] + 1\" unfolding quotients_def by simp\n  also have \"... = (length \\<GG> - 1) + 1\" by (metis diff_zero length_upt)\n  also with notempty have \"... = length \\<GG>\"\n    by (simp add: ac_simps)\n  finally show ?thesis .\nqed\n\nlemma (in normal_series) last_quotient:\n  assumes \"length \\<GG> > 1\"\n  shows \"last quotients = G Mod \\<GG> ! (length \\<GG> - 1 - 1)\"\nproof -\n  from assms have lsimp: \"length \\<GG> - 1 - 1 + 1 = length \\<GG> - 1\" by auto\n  from assms have \"quotients \\<noteq> []\" unfolding quotients_def by auto\n  hence \"last quotients = quotients ! (length quotients - 1)\" by (metis last_conv_nth)\n  also have \"\\<dots> = quotients ! (length \\<GG> - 1 - 1)\" by (metis add_diff_cancel_left' quotients_length add.commute)\n  also have \"\\<dots> = G\\<lparr>carrier := \\<GG> ! ((length \\<GG> - 1 - 1) + 1)\\<rparr> Mod \\<GG> ! (length \\<GG> - 1 - 1)\"\n    unfolding quotients_def using assms by auto\n  also have \"\\<dots> = G\\<lparr>carrier := \\<GG> ! (length \\<GG> - 1)\\<rparr> Mod \\<GG> ! (length \\<GG> - 1 - 1)\" using lsimp by simp\n  also have \"\\<dots> = G Mod \\<GG> ! (length \\<GG> - 1 - 1)\" using last last_conv_nth notempty by force\n  finally show ?thesis .\nqed\n\ntext \\<open>The next lemma transports the constituting properties of a normal series\nalong an isomorphism of groups.\\<close>\n\nlemma (in normal_series) normal_series_iso:\n  assumes H: \"group H\"\n  assumes iso: \"\\<Psi> \\<in> iso G H\"\n  shows \"normal_series H (map (image \\<Psi>) \\<GG>)\"\napply (simp add: normal_series_def normal_series_axioms_def)\nusing H notempty apply simp\nproof (rule conjI)\n  from H is_group iso have group_hom: \"group_hom G H \\<Psi>\" unfolding group_hom_def group_hom_axioms_def iso_def by auto\n  have \"hd (map (image \\<Psi>) \\<GG>) = \\<Psi> ` {\\<one>}\" by (metis hd_map hd notempty)\n  also have \"\\<dots> = {\\<Psi> \\<one>}\" by (metis image_empty image_insert)\n  also have \"\\<dots> = {\\<one>\\<^bsub>H\\<^esub>}\" using group_hom group_hom.hom_one by auto\n  finally show \"hd (map ((`) \\<Psi>) \\<GG>) = {\\<one>\\<^bsub>H\\<^esub>}\".\nnext\n  show \"last (map ((`) \\<Psi>) \\<GG>) = carrier H \\<and> (\\<forall>i. Suc i < length \\<GG> \\<longrightarrow> \\<Psi> ` \\<GG> ! i \\<lhd> H\\<lparr>carrier := \\<Psi> ` \\<GG> ! Suc i\\<rparr>)\"\n  proof (auto del: equalityI)\n    have \"last (map ((`) \\<Psi>) \\<GG>) = \\<Psi> ` (carrier G)\" using last last_map notempty by metis\n    also have \"\\<dots> = carrier H\" using iso unfolding iso_def bij_betw_def by simp\n    finally show \"last (map ((`) \\<Psi>) \\<GG>) = carrier H\".\n  next\n    fix i\n    assume i: \"Suc i < length \\<GG>\"\n    hence norm: \"\\<GG> ! i \\<lhd> G\\<lparr>carrier := \\<GG> ! Suc i\\<rparr>\" using normal by simp\n    moreover have \"restrict \\<Psi> (\\<GG> ! Suc i) \\<in> iso (G\\<lparr>carrier := \\<GG> ! Suc i\\<rparr>) (H\\<lparr>carrier := \\<Psi> ` \\<GG> ! Suc i\\<rparr>)\"\n      by (metis H i is_group iso iso_restrict normal_series_subgroups)\n    moreover have \"group (G\\<lparr>carrier := \\<GG> ! Suc i\\<rparr>)\" by (metis i normal_series_subgroups subgroup_imp_group)\n    moreover hence \"subgroup (\\<GG> ! Suc i) G\" by (metis i normal_series_subgroups)\n    hence \"subgroup (\\<Psi> ` \\<GG> ! Suc i) H\"\n      by (simp add: H iso subgroup.iso_subgroup)\n    hence \"group (H\\<lparr>carrier := \\<Psi> ` \\<GG> ! Suc i\\<rparr>)\" by (metis H subgroup.subgroup_is_group)\n    ultimately have \"restrict \\<Psi> (\\<GG> ! Suc i) ` \\<GG> ! i \\<lhd> H\\<lparr>carrier := \\<Psi> ` \\<GG> ! Suc i\\<rparr>\"\n      using is_group H iso_normal_subgroup by (auto cong del: image_cong_simp)\n    moreover from norm have \"\\<GG> ! i \\<subseteq> \\<GG> ! Suc i\" unfolding normal_def subgroup_def by auto\n    hence \"{y. \\<exists>x\\<in>\\<GG> ! i. y = (if x \\<in> \\<GG> ! Suc i then \\<Psi> x else undefined)} = {y. \\<exists>x\\<in>\\<GG> ! i. y = \\<Psi> x}\" by auto\n    ultimately show \"\\<Psi> ` \\<GG> ! i \\<lhd> H\\<lparr>carrier := \\<Psi> ` \\<GG> ! Suc i\\<rparr>\" unfolding restrict_def image_def by auto\n  qed\nqed\n\nsubsection \\<open>Composition Series\\<close>\n\ntext \\<open>A composition series is a normal series where all consecutive factor groups are simple:\\<close>\n\nlocale composition_series = normal_series +\n  assumes simplefact: \"\\<And>i. i + 1 <  length \\<GG> \\<Longrightarrow> simple_group (G\\<lparr>carrier := \\<GG> ! (i + 1)\\<rparr> Mod \\<GG> ! i)\"\n\nlemma (in composition_series) is_composition_series:\n  shows \"composition_series G \\<GG>\"\nby (rule composition_series_axioms)\n\ntext \\<open>A composition series for a group $G$ has length one if and only if $G$ is the trivial group.\\<close>\n\nlemma (in composition_series) composition_series_length_one:\n  shows \"(length \\<GG> = 1) = (\\<GG> = [{\\<one>}])\"\nproof\n  assume \"length \\<GG> = 1\"\n  with hd have \"length \\<GG> = length [{\\<one>}] \\<and> (\\<forall>i < length \\<GG>. \\<GG> ! i = [{\\<one>}] ! i)\" using hd_conv_nth notempty by force\n  thus \"\\<GG> = [{\\<one>}]\" using list_eq_iff_nth_eq by blast\nnext\n  assume \"\\<GG> = [{\\<one>}]\"\n  thus \"length \\<GG> = 1\" by simp\nqed\n\nlemma (in composition_series) composition_series_triv_group:\n  shows \"(carrier G = {\\<one>}) = (\\<GG> = [{\\<one>}])\"\nproof\n  assume G: \"carrier G = {\\<one>}\"\n  have \"length \\<GG> = 1\"\n  proof (rule ccontr)\n    assume \"length \\<GG> \\<noteq> 1\"\n    with notempty have length: \"length \\<GG> \\<ge> 2\" by (metis Suc_eq_plus1 length_0_conv less_2_cases not_less plus_nat.add_0)\n    with simplefact hd hd_conv_nth notempty have \"simple_group (G\\<lparr>carrier := \\<GG> ! 1\\<rparr> Mod {\\<one>})\" by force\n    moreover have SG: \"subgroup (\\<GG> ! 1) G\" using length normal_series_subgroups by auto\n    hence \"group (G\\<lparr>carrier := \\<GG> ! 1\\<rparr>)\" by (metis subgroup_imp_group)\n    ultimately have  \"simple_group (G\\<lparr>carrier := \\<GG> ! 1\\<rparr>)\" using group.trivial_factor_iso simple_group.iso_simple by fastforce\n    moreover from SG G have \"carrier (G\\<lparr>carrier := \\<GG> ! 1\\<rparr>) = {\\<one>}\" unfolding subgroup_def by auto\n    ultimately show False using simple_group.simple_not_triv by force\n  qed\n  thus \"\\<GG> = [{\\<one>}]\" by (metis composition_series_length_one)\nnext\n  assume \"\\<GG> = [{\\<one>}]\"\n  with last show \"carrier G = {\\<one>}\" by auto\nqed\n\ntext \\<open>The inner elements of a composition series may not consist of the trivial subgroup or the\ngroup itself.\\<close>\n\nlemma (in composition_series) inner_elements_not_triv:\n  assumes \"i + 1 < length \\<GG>\"\n  assumes \"i > 0\"\n  shows \"\\<GG> ! i \\<noteq> {\\<one>}\"\nproof\n  from assms have \"(i - 1) + 1 < length \\<GG>\" by simp\n  hence simple: \"simple_group (G\\<lparr>carrier := \\<GG> ! ((i - 1) + 1)\\<rparr> Mod \\<GG> ! (i - 1))\" using simplefact by auto\n  assume i: \"\\<GG> ! i = {\\<one>}\"\n  moreover from assms have \"(i - 1) + 1 = i\" by auto\n  ultimately have \"G\\<lparr>carrier := \\<GG> ! ((i - 1) + 1)\\<rparr> Mod \\<GG> ! (i - 1) = G\\<lparr>carrier := {\\<one>}\\<rparr> Mod \\<GG> ! (i - 1)\" using i by auto\n  hence \"order (G\\<lparr>carrier := \\<GG> ! ((i - 1) + 1)\\<rparr> Mod \\<GG> ! (i - 1)) = 1\" unfolding FactGroup_def order_def RCOSETS_def by force\n  thus \"False\" using i simple unfolding simple_group_def simple_group_axioms_def by auto\nqed\n\ntext \\<open>A composition series of a simple group always is its trivial one.\\<close>\n\nlemma (in composition_series) composition_series_simple_group:\n  shows \"(simple_group G) = (\\<GG> = [{\\<one>}, carrier G])\"\nproof\n  assume \"\\<GG> = [{\\<one>}, carrier G]\"\n  with simplefact have \"simple_group (G Mod {\\<one>})\" by auto\n  moreover have \"the_elem \\<in> iso (G Mod {\\<one>}) G\" by (rule trivial_factor_iso)\n  ultimately show \"simple_group G\" by (metis is_group simple_group.iso_simple)\nnext\n  assume simple: \"simple_group G\"\n  have \"length \\<GG> > 1\"\n  proof (rule ccontr)\n    assume \"\\<not> 1 < length \\<GG>\"\n    hence \"length \\<GG> = 1\" by (simp add: Suc_leI antisym notempty)\n    hence \"carrier G = {\\<one>}\" using hd last by (metis composition_series_length_one composition_series_triv_group)\n    hence \"order G = 1\" unfolding order_def by auto\n    with simple show \"False\" unfolding simple_group_def simple_group_axioms_def by auto\n  qed\n  moreover have \"length \\<GG> \\<le> 2\"\n  proof (rule ccontr)\n    define k where \"k = length \\<GG> - 2\"\n    assume \"\\<not> (length \\<GG> \\<le> 2)\"\n    hence gt2: \"length \\<GG> > 2\" by simp\n    hence ksmall: \"k + 1 < length \\<GG>\" unfolding k_def by auto\n    from gt2 have carrier: \"\\<GG> ! (k + 1) = carrier G\" using notempty last last_conv_nth k_def\n      by (metis Nat.add_diff_assoc Nat.diff_cancel \\<open>\\<not> length \\<GG> \\<le> 2\\<close> add.commute nat_le_linear one_add_one)\n    from normal ksmall have \"\\<GG> ! k \\<lhd> G\\<lparr> carrier := \\<GG> ! (k + 1)\\<rparr>\" by simp\n    from simplefact ksmall have simplek: \"simple_group (G\\<lparr>carrier := \\<GG> ! (k + 1)\\<rparr> Mod \\<GG> ! k)\" by simp\n    from simplefact ksmall have simplek': \"simple_group (G\\<lparr>carrier := \\<GG> ! ((k - 1) + 1)\\<rparr> Mod \\<GG> ! (k - 1))\" by auto\n    have \"\\<GG> ! k \\<lhd> G\" using carrier k_def gt2 normal ksmall by force\n    with simple have \"(\\<GG> ! k) = carrier G \\<or> (\\<GG> ! k) = {\\<one>}\" unfolding simple_group_def simple_group_axioms_def by simp\n    thus \"False\"\n    proof (rule disjE)\n      assume \"\\<GG> ! k = carrier G\"\n      hence \"G\\<lparr>carrier := \\<GG> ! (k + 1)\\<rparr> Mod \\<GG> ! k = G Mod (carrier G)\" using carrier by auto\n      with simplek self_factor_not_simple show \"False\" by auto\n    next\n      assume \"\\<GG> ! k = {\\<one>}\"\n      with ksmall k_def gt2 show \"False\" using inner_elements_not_triv by auto\n    qed\n  qed\n  ultimately have \"length \\<GG> = 2\" by simp\n  thus \"\\<GG> = [{\\<one>}, carrier G]\" by (rule length_two_unique)\nqed\n\ntext \\<open>Two consecutive elements in a composition series are distinct.\\<close>\n\nlemma (in composition_series) entries_distinct:\n  assumes finite: \"finite (carrier G)\"\n  assumes i: \"i + 1 < length \\<GG>\"\n  shows \"\\<GG> ! i \\<noteq> \\<GG> ! (i + 1)\"\nproof\n  from finite have \"finite  (\\<GG> ! (i + 1))\" \n    using i normal_series_subgroups subgroup.subset rev_finite_subset by metis\n  hence fin: \"finite (carrier (G\\<lparr>carrier := \\<GG> ! (i + 1)\\<rparr>))\" by auto\n  from i have norm: \"\\<GG> ! i \\<lhd> (G\\<lparr>carrier := \\<GG> ! (i + 1)\\<rparr>)\" by (rule normal)\n  assume \"\\<GG> ! i = \\<GG> ! (i + 1)\"\n  hence \"\\<GG> ! i = carrier (G\\<lparr>carrier := \\<GG> ! (i + 1)\\<rparr>)\" by auto\n  hence \"carrier ((G\\<lparr>carrier := (\\<GG> ! (i + 1))\\<rparr>) Mod (\\<GG> ! i)) = {\\<one>\\<^bsub>(G\\<lparr>carrier := \\<GG> ! (i + 1)\\<rparr>) Mod \\<GG> ! i\\<^esub>}\"\n    using norm fin normal.fact_group_trivial_iff by metis\n  hence \"\\<not> simple_group ((G\\<lparr>carrier := (\\<GG> ! (i + 1))\\<rparr>) Mod (\\<GG> ! i))\" by (metis simple_group.simple_not_triv)\n  thus False by (metis i simplefact)\nqed\n\ntext \\<open>The normal series for groups of order @{term \"p * q\"} is even a composition series:\\<close>\n\nlemma (in group) pq_order_composition_series:\n  assumes finite: \"finite (carrier G)\"\n  assumes orderG: \"order G = q * p\"\n  assumes primep: \"prime p\" and primeq: \"prime q\" and pq: \"p < q\"\n  shows \"composition_series G [{\\<one>}, (THE H. H \\<in> subgroups_of_size q), carrier G]\"\nunfolding composition_series_def composition_series_axioms_def\napply(auto)\nusing assms apply(rule pq_order_normal_series)\nproof -\n  define H where \"H = (THE H. H \\<in> subgroups_of_size q)\"\n  from assms have exi: \"\\<exists>!Q. Q \\<in> (subgroups_of_size q)\" by (auto simp: pq_order_unique_subgrp)\n  hence Hsize: \"H \\<in> subgroups_of_size q\" unfolding H_def using theI' by metis\n  hence HsubG: \"subgroup H G\" unfolding subgroups_of_size_def by auto\n  then interpret Hgroup: group \"G\\<lparr>carrier := H\\<rparr>\" by (metis subgroup_imp_group)\n  fix i\n  assume \"i < Suc (Suc 0)\"\n  hence \"i = 0 \\<or> i = 1\" by auto\n  thus \"simple_group (G\\<lparr>carrier := [H, carrier G] ! i\\<rparr> Mod [{\\<one>}, H, carrier G] ! i)\"\n  proof\n    assume i: \"i = 0\"\n    from Hsize have orderH: \"order (G\\<lparr>carrier := H\\<rparr>) = q\" unfolding subgroups_of_size_def order_def by simp\n    hence order_eq_q: \"order (G\\<lparr>carrier := H\\<rparr> Mod {\\<one>}) = q\"\n      using Hgroup.trivial_factor_iso iso_same_order by auto\n    have \"normal {\\<one>} (G\\<lparr>carrier := H\\<rparr>)\"\n      by (simp add: HsubG group.normal_restrict_supergroup subgroup.one_closed trivial_subgroup_is_normal)\n    hence \"group (G\\<lparr>carrier := H\\<rparr> Mod {\\<one>})\" by (metis normal.factorgroup_is_group)\n    with orderH primeq have \"simple_group (G\\<lparr>carrier := H\\<rparr> Mod {\\<one>})\" \n      by (metis order_eq_q group.prime_order_simple)\n    with i show ?thesis by simp\n  next\n    assume i: \"i = 1\"\n    from assms exi have \"H \\<lhd> G\" unfolding H_def by (metis pq_order_subgrp_normal)\n    hence groupGH: \"group (G Mod H)\" by (metis normal.factorgroup_is_group)\n    from primeq have \"q \\<noteq> 0\" by (metis not_prime_0)\n    from HsubG finite orderG have \"card (rcosets H) * card H = q * p\" unfolding subgroups_of_size_def using lagrange by simp\n    with Hsize have \"card (rcosets H) * q = q * p\" unfolding subgroups_of_size_def by simp\n    with \\<open>q \\<noteq> 0\\<close> have \"card (rcosets H) = p\" by auto\n    hence \"order (G Mod H) = p\" unfolding order_def FactGroup_def by auto\n    with groupGH primep have \"simple_group (G Mod H)\" by (metis group.prime_order_simple)\n    with i show ?thesis by auto\n  qed\nqed\n\ntext \\<open>Prefixes of composition series are also composition series.\\<close>\n\nlemma (in composition_series) composition_series_prefix_closed:\n  assumes \"i \\<le> length \\<GG>\" and \"0 < i\"\n  shows \"composition_series (G\\<lparr>carrier := \\<GG> ! (i - 1)\\<rparr>) (take i \\<GG>)\"\nunfolding composition_series_def composition_series_axioms_def\nproof auto\n  from assms show \"normal_series (G\\<lparr>carrier := \\<GG> ! (i - Suc 0)\\<rparr>) (take i \\<GG>)\" by (metis One_nat_def normal_series_prefix_closed)\nnext\n  fix j\n  assume j: \"Suc j < length \\<GG>\" \"Suc j < i\"\n  with simplefact show \"simple_group (G\\<lparr>carrier := \\<GG> ! Suc j\\<rparr> Mod \\<GG> ! j)\" by (metis Suc_eq_plus1)\nqed\n\ntext \\<open>The second element in a composition series is simple group.\\<close>\n\nlemma (in composition_series) composition_series_snd_simple:\n  assumes \"2 \\<le> length \\<GG>\"\n  shows \"simple_group (G\\<lparr>carrier := \\<GG> ! 1\\<rparr>)\"\nproof -\n  from assms interpret compTake: composition_series \"G\\<lparr>carrier := \\<GG> ! 1\\<rparr>\" \"take 2 \\<GG>\" by (metis add_diff_cancel_right' composition_series_prefix_closed one_add_one zero_less_numeral)\n  from assms have \"length (take 2 \\<GG>) = 2\" by (metis add_diff_cancel_right' append_take_drop_id diff_diff_cancel length_append length_drop)\n  hence \"(take 2 \\<GG>) = [{\\<one>\\<^bsub>(G\\<lparr>carrier := \\<GG> ! 1\\<rparr>)\\<^esub>}, carrier (G\\<lparr>carrier := \\<GG> ! 1\\<rparr>)]\" by (rule compTake.length_two_unique)\n  thus ?thesis by (metis compTake.composition_series_simple_group)\nqed\n\ntext \\<open>As a stronger way to state the previous lemma: An entry of a composition series is \n  simple if and only if it is the second one.\\<close>\n\nlemma (in composition_series) composition_snd_simple_iff:\n  assumes \"i < length \\<GG>\"\n  shows \"(simple_group (G\\<lparr>carrier :=  \\<GG> ! i\\<rparr>)) = (i = 1)\"\nproof\n  assume simpi: \"simple_group (G\\<lparr>carrier := \\<GG> ! i\\<rparr>)\"\n  hence \"\\<GG> ! i \\<noteq> {\\<one>}\" using simple_group.simple_not_triv by force\n  hence \"i \\<noteq> 0\" using hd hd_conv_nth notempty by auto\n  then interpret compTake: composition_series \"G\\<lparr>carrier := \\<GG> ! i\\<rparr>\" \"take (Suc i) \\<GG>\"\n    using assms composition_series_prefix_closed by (metis diff_Suc_1 less_eq_Suc_le zero_less_Suc)\n  from simpi have \"(take (Suc i) \\<GG>) = [{\\<one>\\<^bsub>G\\<lparr>carrier := \\<GG> ! i\\<rparr>\\<^esub>}, carrier (G\\<lparr>carrier := \\<GG> ! i\\<rparr>)]\"\n    by (metis compTake.composition_series_simple_group)\n  hence \"length (take (Suc i) \\<GG>) = 2\" by auto\n  hence \"min (length \\<GG>) (Suc i) = 2\" by (metis length_take)\n  with assms have \"Suc i = 2\" by force\n  thus \"i = 1\" by simp\nnext\n  assume i: \"i = 1\"\n  with assms have \"2 \\<le> length \\<GG>\" by simp\n  with i show \"simple_group (G\\<lparr>carrier := \\<GG> ! i\\<rparr>)\" by (metis composition_series_snd_simple)\nqed\n\ntext \\<open>The second to last entry of a normal series is not only a normal subgroup but\n  actually even a \\emph{maximal} normal subgroup.\\<close>\n\nlemma (in composition_series) snd_to_last_max_normal:\n  assumes finite: \"finite (carrier G)\"\n  assumes length: \"length \\<GG> > 1\"\n  shows \"max_normal_subgroup (\\<GG> ! (length \\<GG> - 2)) G\"\nunfolding max_normal_subgroup_def max_normal_subgroup_axioms_def\nproof (auto del: equalityI)\n  show \"\\<GG> ! (length \\<GG> - 2) \\<lhd> G\" by (rule normal_series_snd_to_last)\nnext \n  define G' where \"G' = \\<GG> ! (length \\<GG> - 2)\"\n  from length have length21: \"length \\<GG> - 2 + 1 = length \\<GG> - 1\" by arith\n  from length have \"length \\<GG> - 2 + 1 < length \\<GG>\" by arith\n  with simplefact have \"simple_group (G\\<lparr>carrier := \\<GG> ! ((length \\<GG> - 2) + 1)\\<rparr> Mod G')\" unfolding G'_def by auto\n  with length21 have simple_last: \"simple_group (G Mod G')\" using last notempty last_conv_nth by fastforce\n  {\n    assume snd_to_last_eq: \"G' = carrier G\"\n    hence \"carrier (G Mod G') = {\\<one>\\<^bsub>G Mod G'\\<^esub>}\"\n    using normal_series_snd_to_last finite normal.fact_group_trivial_iff unfolding G'_def by metis\n    with snd_to_last_eq have \"\\<not> simple_group (G Mod G')\" by (metis self_factor_not_simple)\n    with simple_last show False unfolding G'_def by auto\n  }\n  {\n    have G'G: \"G' \\<lhd> G\" unfolding G'_def by (rule normal_series_snd_to_last)\n    fix J\n    assume J: \"J \\<lhd> G\" \"J \\<noteq> G'\" \"J \\<noteq> carrier G\" \"G' \\<subseteq> J\"\n    hence JG'GG': \"rcosets\\<^bsub>(G\\<lparr>carrier := J\\<rparr>)\\<^esub> G' \\<lhd> G Mod G'\"  using normality_factorization normal_series_snd_to_last unfolding G'_def by auto\n    from G'G J(1,4) have G'J: \"G' \\<lhd> (G\\<lparr>carrier := J\\<rparr>)\" by (metis normal_imp_subgroup normal_restrict_supergroup)\n    from finite J(1) have finJ: \"finite J\" by (auto simp: normal_imp_subgroup subgroup_finite)\n    from JG'GG' simple_last have \"rcosets\\<^bsub>G\\<lparr>carrier := J\\<rparr>\\<^esub> G' = {\\<one>\\<^bsub>G Mod G'\\<^esub>} \\<or> rcosets\\<^bsub>G\\<lparr>carrier := J\\<rparr>\\<^esub> G' = carrier (G Mod G')\"\n      unfolding simple_group_def simple_group_axioms_def by auto\n    thus False \n    proof\n      assume \"rcosets\\<^bsub>G\\<lparr>carrier := J\\<rparr>\\<^esub> G' = {\\<one>\\<^bsub>G Mod G'\\<^esub>}\"\n      hence \"rcosets\\<^bsub>G\\<lparr>carrier := J\\<rparr>\\<^esub> G' = {\\<one>\\<^bsub>(G\\<lparr>carrier := J\\<rparr>) Mod G'\\<^esub>}\" unfolding FactGroup_def by simp\n      hence \"G' = J\" using G'J finJ normal.fact_group_trivial_iff unfolding FactGroup_def by fastforce\n      with J(2) show False by simp\n    next\n      assume facts_eq: \"rcosets\\<^bsub>G\\<lparr>carrier := J\\<rparr>\\<^esub> G' = carrier (G Mod G')\"\n      have \"J = carrier G\"\n      proof\n        show \"J \\<subseteq> carrier G\" using J(1) normal_imp_subgroup subgroup.subset by force\n      next\n        show \"carrier G \\<subseteq> J\"\n        proof\n          fix x\n          assume x: \"x \\<in> carrier G\"\n          hence \"G' #> x \\<in> carrier (G Mod G')\" unfolding FactGroup_def RCOSETS_def by auto\n          hence \"G' #> x \\<in> rcosets\\<^bsub>G\\<lparr>carrier := J\\<rparr>\\<^esub> G'\" using facts_eq by auto\n          then obtain j where j: \"j \\<in> J\" \"G' #> x = G' #> j\" unfolding RCOSETS_def r_coset_def by force\n          hence \"x \\<in> G' #> j\" using G'G normal_imp_subgroup x repr_independenceD by fastforce\n          then obtain g' where g': \"g' \\<in> G'\" \"x = g' \\<otimes> j\" unfolding r_coset_def by auto\n          hence \"g' \\<in> J\" using G'J normal_imp_subgroup subgroup.subset by force\n          with g'(2) j(1) show  \"x \\<in> J\" using J(1) normal_imp_subgroup subgroup.m_closed by fastforce\n        qed\n      qed\n      with J(3) show False by simp\n    qed\n  }\nqed\n\ntext \\<open>For the next lemma we need a few facts about removing adjacent duplicates.\\<close>\n\nlemma remdups_adj_obtain_adjacency:\n  assumes \"i + 1 < length (remdups_adj xs)\" \"length xs > 0\"\n  obtains j where \"j + 1 < length xs\"\n    \"(remdups_adj xs) ! i = xs ! j\" \"(remdups_adj xs) ! (i + 1) = xs ! (j + 1)\"\nusing assms proof (induction xs arbitrary: i thesis)\n  case Nil\n  hence False by (metis length_greater_0_conv)\n  thus thesis..\nnext\n  case (Cons x xs)\n  then have \"xs \\<noteq> []\"\n    by auto\n  then obtain y xs' where xs: \"xs = y # xs'\"\n    by (cases xs) blast\n  from \\<open>xs \\<noteq> []\\<close> have lenxs: \"length xs > 0\" by simp\n  from xs have rem: \"remdups_adj (x # xs) = (if x = y then remdups_adj (y # xs') else x # remdups_adj (y # xs'))\" using remdups_adj.simps(3) by auto\n  show thesis\n  proof (cases \"x = y\")\n    case True\n    with rem xs have rem2: \"remdups_adj (x # xs) = remdups_adj xs\" by auto\n    with Cons(3) have \"i + 1 < length (remdups_adj xs)\" by simp\n    with Cons.IH lenxs obtain k where j: \"k + 1 < length xs\" \"remdups_adj xs ! i = xs ! k\"\n        \"remdups_adj xs ! (i + 1) = xs ! (k + 1)\" by auto\n    thus thesis using Cons(2) rem2 by auto\n  next\n    case False\n    with rem xs have rem2: \"remdups_adj (x # xs) = x # remdups_adj xs\" by auto\n    show thesis\n    proof (cases i)\n      case 0\n      have \"0 + 1 < length (x # xs)\" using lenxs by auto\n      moreover have \"remdups_adj (x # xs) ! i = (x # xs) ! 0\"\n      proof -\n        have \"remdups_adj (x # xs) ! i = (x # remdups_adj (y # xs')) ! 0\" using xs rem2 0 by simp\n        also have \"\\<dots> = x\" by simp\n        also have \"\\<dots> = (x # xs) ! 0\" by simp\n        finally show ?thesis.\n      qed\n      moreover have \"remdups_adj (x # xs) ! (i + 1) = (x # xs) ! (0 + 1)\"\n      proof -\n        have \"remdups_adj (x # xs) ! (i + 1) = (x # remdups_adj (y # xs')) ! 1\" using xs rem2 0 by simp\n        also have \"\\<dots> = remdups_adj (y # xs') ! 0\" by simp\n        also have \"\\<dots> = (y # (remdups (y # xs'))) ! 0\" by (metis nth_Cons' remdups_adj_Cons_alt)\n        also have \"\\<dots> = y\" by simp\n        also have \"\\<dots> = (x # xs) ! (0 + 1)\" unfolding xs by simp\n        finally show ?thesis.\n      qed\n      ultimately show thesis by (rule Cons.prems(1))\n    next\n      case (Suc k)\n      with Cons(3) have \"k + 1 < length (remdups_adj (x # xs)) - 1\" by auto\n      also have \"\\<dots> \\<le> length (remdups_adj xs) + 1 - 1\" by (metis One_nat_def le_refl list.size(4) rem2)\n      also have \"\\<dots> = length (remdups_adj xs)\" by simp\n      finally have \"k + 1 < length (remdups_adj xs)\".\n      with Cons.IH lenxs obtain j where j: \"j + 1 < length xs\" \"remdups_adj xs ! k = xs ! j\"\n        \"remdups_adj xs ! (k + 1) = xs ! (j + 1)\" by auto\n      from j(1) have \"Suc j + 1 < length (x # xs)\" by simp\n      moreover have \"remdups_adj (x # xs) ! i = (x # xs) ! (Suc j)\"\n      proof -\n        have \"remdups_adj (x # xs) ! i = (x # remdups_adj xs) ! i\" using rem2 by simp\n        also have \"\\<dots> = (remdups_adj xs) ! k\" using Suc by simp\n        also have \"\\<dots> = xs ! j\" using j(2) .\n        also have \"\\<dots> = (x # xs) ! (Suc j)\" by simp\n        finally show ?thesis .\n      qed\n      moreover have \"remdups_adj (x # xs) ! (i + 1) = (x # xs) ! (Suc j + 1)\"\n      proof -\n        have \"remdups_adj (x # xs) ! (i + 1) = (x # remdups_adj xs) ! (i + 1)\" using rem2 by simp\n        also have \"\\<dots> = (remdups_adj xs) ! (k + 1)\" using Suc by simp\n        also have \"\\<dots> = xs ! (j + 1)\" using j(3).\n        also have \"\\<dots> = (x # xs) ! (Suc j + 1)\" by simp\n        finally show ?thesis.\n      qed\n      ultimately show thesis by (rule Cons.prems(1))\n    qed\n  qed\nqed\n\nlemma hd_remdups_adj[simp]: \"hd (remdups_adj xs) = hd xs\"\n  by (induction xs rule: remdups_adj.induct) simp_all\n\nlemma remdups_adj_adjacent:\n  \"Suc i < length (remdups_adj xs) \\<Longrightarrow> remdups_adj xs ! i \\<noteq> remdups_adj xs ! Suc i\"\nproof (induction xs arbitrary: i rule: remdups_adj.induct)\n  case (3 x y xs i)\n  thus ?case by (cases i, cases \"x = y\") (simp, auto simp: hd_conv_nth[symmetric])\nqed simp_all\n\ntext \\<open>Intersecting each entry of a composition series with a normal subgroup of $G$ and removing\n  all adjacent duplicates yields another composition series.\\<close>\n\nlemma (in composition_series) intersect_normal:\n  assumes finite: \"finite (carrier G)\"\n  assumes KG: \"K \\<lhd> G\"\n  shows \"composition_series (G\\<lparr>carrier := K\\<rparr>) (remdups_adj (map (\\<lambda>H. K \\<inter> H) \\<GG>))\"\nunfolding composition_series_def composition_series_axioms_def normal_series_def normal_series_axioms_def\napply (auto simp only: conjI del: equalityI)\nproof -\n  show \"group (G\\<lparr>carrier := K\\<rparr>)\" using KG normal_imp_subgroup subgroup_imp_group by auto\nnext\n  \\<comment> \\<open>Show, that removing adjacent duplicates doesn't result in an empty list.\\<close>\n  assume \"remdups_adj (map ((\\<inter>) K) \\<GG>) = []\"\n  hence \"map ((\\<inter>) K) \\<GG> = []\" by (metis remdups_adj_Nil_iff)\n  hence \"\\<GG> = []\" by (metis Nil_is_map_conv)\n  with notempty show False..\nnext\n  \\<comment> \\<open>Show, that the head of the reduced list is still the trivial group\\<close>\n  have \"\\<GG> = {\\<one>} # tl \\<GG>\" using notempty hd by (metis list.sel(1,3) neq_Nil_conv)\n  hence \"map ((\\<inter>) K) \\<GG> = map ((\\<inter>) K) ({\\<one>} # tl \\<GG>)\" by simp\n  hence \"remdups_adj (map ((\\<inter>) K) \\<GG>) = remdups_adj ((K \\<inter> {\\<one>}) # (map ((\\<inter>) K) (tl \\<GG>)))\" by simp\n  also have \"\\<dots> = (K \\<inter> {\\<one>}) # tl (remdups_adj ((K \\<inter> {\\<one>}) # (map ((\\<inter>) K) (tl \\<GG>))))\" by simp\n  finally have \"hd (remdups_adj (map ((\\<inter>) K) \\<GG>)) = K \\<inter> {\\<one>}\" using list.sel(1) by metis\n  thus \"hd (remdups_adj (map ((\\<inter>) K) \\<GG>)) = {\\<one>\\<^bsub>G\\<lparr>carrier := K\\<rparr>\\<^esub>}\" \n    using KG normal_imp_subgroup subgroup.one_closed by force\nnext\n  \\<comment> \\<open>Show that the last entry is really @{text \"K \\<inter> G\"}. Since we don't have a lemma ready to talk about the\n    last entry of a reduced list, we reverse the list twice.\\<close>\n  have \"rev \\<GG> = (carrier G) # tl (rev \\<GG>)\" by (metis list.sel(1,3) last last_rev neq_Nil_conv notempty rev_is_Nil_conv rev_rev_ident)\n  hence \"rev (map ((\\<inter>) K) \\<GG>) = map ((\\<inter>) K) ((carrier G) # tl (rev \\<GG>))\" by (metis rev_map)\n  hence rev: \"rev (map ((\\<inter>) K) \\<GG>) = (K \\<inter> (carrier G)) # (map ((\\<inter>) K) (tl (rev \\<GG>)))\" by simp\n  have \"last (remdups_adj (map ((\\<inter>) K) \\<GG>)) = hd (rev (remdups_adj (map ((\\<inter>) K) \\<GG>)))\"\n    by (metis hd_rev map_is_Nil_conv notempty remdups_adj_Nil_iff)\n  also have \"\\<dots> = hd (remdups_adj (rev (map ((\\<inter>) K) \\<GG>)))\" by (metis remdups_adj_rev)\n  also have \"\\<dots> = hd (remdups_adj ((K \\<inter> (carrier G)) # (map ((\\<inter>) K) (tl (rev \\<GG>)))))\" by (metis rev)\n  also have \"\\<dots> = hd ((K \\<inter> (carrier G)) # (remdups_adj ((K \\<inter> (carrier G)) # (map ((\\<inter>) K) (tl (rev \\<GG>))))))\" by (metis list.sel(1) remdups_adj_Cons_alt)\n  also have \"\\<dots> = K\" using KG normal_imp_subgroup subgroup.subset by force\n  finally show \"last (remdups_adj (map ((\\<inter>) K) \\<GG>)) = carrier (G\\<lparr>carrier := K\\<rparr>)\" by auto\nnext\n  \\<comment> \\<open>The induction step, using the second isomorphism theorem for groups.\\<close>\n  fix j\n  assume j: \"j + 1 < length (remdups_adj (map ((\\<inter>) K) \\<GG>))\"\n  have KGnotempty: \"(map ((\\<inter>) K) \\<GG>) \\<noteq> []\" using notempty by (metis Nil_is_map_conv)\n  with j obtain i where i: \"i + 1 < length (map ((\\<inter>) K) \\<GG>)\"\n    \"(remdups_adj (map ((\\<inter>) K) \\<GG>)) ! j = (map ((\\<inter>) K) \\<GG>) ! i\"\n    \"(remdups_adj (map ((\\<inter>) K) \\<GG>)) ! (j + 1) = (map ((\\<inter>) K) \\<GG>) ! (i + 1)\"\n    using remdups_adj_obtain_adjacency by force\n  from i(1) have i': \"i + 1 < length \\<GG>\" by (metis length_map)\n  hence GiSi: \"\\<GG> ! i \\<lhd> G\\<lparr>carrier := \\<GG> ! (i + 1)\\<rparr>\" by (metis normal)\n  hence GiSi': \"\\<GG> ! i \\<subseteq> \\<GG> ! (i + 1)\" using normal_imp_subgroup subgroup.subset by force\n  from i' have finGSi: \"finite (\\<GG> ! (i + 1))\" using  normal_series_subgroups finite by (metis subgroup_finite)\n  from GiSi KG i' normal_series_subgroups have GSiKnormGSi: \"\\<GG> ! (i + 1) \\<inter> K \\<lhd> G\\<lparr>carrier := \\<GG> ! (i + 1)\\<rparr>\"\n    using second_isomorphism_grp.normal_subgrp_intersection_normal\n    unfolding second_isomorphism_grp_def second_isomorphism_grp_axioms_def by auto\n  with GiSi have \"\\<GG> ! i \\<inter> (\\<GG> ! (i + 1) \\<inter> K) \\<lhd> G\\<lparr>carrier := \\<GG> ! (i + 1)\\<rparr>\"\n    by (metis group.normal_subgroup_intersect group.subgroup_imp_group i' is_group is_normal_series normal_series.normal_series_subgroups)\n  hence \"K \\<inter> (\\<GG> ! i \\<inter> \\<GG> ! (i + 1)) \\<lhd> G\\<lparr>carrier := \\<GG> ! (i + 1)\\<rparr>\" by (metis inf_commute inf_left_commute)\n  hence KGinormGSi: \"K \\<inter> \\<GG> ! i \\<lhd> G\\<lparr>carrier := \\<GG> ! (i + 1)\\<rparr>\" using GiSi' by (metis le_iff_inf)\n  moreover have \"K \\<inter> \\<GG> ! i \\<subseteq> K \\<inter> \\<GG> ! (i + 1)\" using GiSi' by auto\n  moreover have groupGSi: \"group (G\\<lparr>carrier := \\<GG> ! (i + 1)\\<rparr>)\" using i normal_series_subgroups subgroup_imp_group by auto\n  moreover have subKGSiGSi: \"subgroup (K \\<inter> \\<GG> ! (i + 1)) (G\\<lparr>carrier := \\<GG> ! (i + 1)\\<rparr>)\" by (metis GSiKnormGSi inf_sup_aci(1) normal_imp_subgroup)\n  ultimately have fstgoal: \"K \\<inter> \\<GG> ! i \\<lhd> G\\<lparr>carrier := \\<GG> ! (i + 1), carrier := K \\<inter> \\<GG> ! (i + 1)\\<rparr>\"\n    using group.normal_restrict_supergroup by force\n  thus \"remdups_adj (map ((\\<inter>) K) \\<GG>) ! j \\<lhd> G\\<lparr>carrier := K, carrier := remdups_adj (map ((\\<inter>) K) \\<GG>) ! (j + 1)\\<rparr>\"\n    using i by auto\n  from simplefact have Gisimple: \"simple_group (G\\<lparr>carrier := \\<GG> ! (i + 1)\\<rparr> Mod \\<GG> ! i)\" using i' by simp\n  hence Gimax: \"max_normal_subgroup (\\<GG> ! i) (G\\<lparr>carrier := \\<GG> ! (i + 1)\\<rparr>)\"\n    using normal.max_normal_simple_quotient GiSi finGSi by force\n  from GSiKnormGSi GiSi have \"\\<GG> ! i <#>\\<^bsub>G\\<lparr>carrier := \\<GG> ! (i + 1)\\<rparr>\\<^esub> \\<GG> ! (i + 1) \\<inter> K \\<lhd> (G\\<lparr>carrier := \\<GG> ! (i + 1)\\<rparr>)\"\n    using groupGSi group.normal_subgroup_set_mult_closed set_mult_consistent by fastforce\n  hence \"\\<GG> ! i <#> \\<GG> ! (i + 1) \\<inter> K \\<lhd> G\\<lparr>carrier := \\<GG> ! (i + 1)\\<rparr>\" unfolding set_mult_def by auto\n  hence \"\\<GG> ! i <#> K \\<inter> \\<GG> ! (i + 1) \\<lhd> G\\<lparr>carrier := \\<GG> ! (i + 1)\\<rparr>\" using inf_commute by metis\n  moreover have \"\\<GG> ! i \\<subseteq> \\<GG> ! i <#>\\<^bsub>G\\<lparr>carrier := \\<GG> ! (i + 1)\\<rparr>\\<^esub> K \\<inter> \\<GG> ! (i + 1)\"\n    using second_isomorphism_grp.H_contained_in_set_mult\n    unfolding second_isomorphism_grp_def second_isomorphism_grp_axioms_def\n    using subKGSiGSi GiSi normal_imp_subgroup by fastforce\n  hence \"\\<GG> ! i \\<subseteq> \\<GG> ! i <#> K \\<inter> \\<GG> ! (i + 1)\" unfolding set_mult_def by auto\n  ultimately have KGdisj: \"\\<GG> ! i <#> K \\<inter> \\<GG> ! (i + 1) = \\<GG> ! i \\<or> \\<GG> ! i <#> K \\<inter> \\<GG> ! (i + 1) = \\<GG> ! (i + 1)\"\n    using Gimax unfolding max_normal_subgroup_def max_normal_subgroup_axioms_def\n    by auto\n  obtain \\<phi> where \"\\<phi> \\<in> iso  (G\\<lparr>carrier := K \\<inter> \\<GG> ! (i + 1)\\<rparr> Mod (\\<GG> ! i \\<inter> (K \\<inter> \\<GG> ! (i + 1))))\n             (G\\<lparr>carrier := \\<GG> ! i <#>\\<^bsub>G\\<lparr>carrier := \\<GG> ! (i + 1)\\<rparr>\\<^esub> K \\<inter> \\<GG> ! (i + 1)\\<rparr> Mod \\<GG> ! i)\"\n    using second_isomorphism_grp.normal_intersection_quotient_isom\n    unfolding second_isomorphism_grp_def second_isomorphism_grp_axioms_def\n    using GiSi subKGSiGSi normal_imp_subgroup  by fastforce\n  hence \"\\<phi> \\<in> iso  (G\\<lparr>carrier := K \\<inter> \\<GG> ! (i + 1)\\<rparr> Mod (K \\<inter> \\<GG> ! (i + 1) \\<inter> \\<GG> ! i))\n                  (G\\<lparr>carrier := \\<GG> ! i <#>\\<^bsub>G\\<lparr>carrier := \\<GG> ! (i + 1)\\<rparr>\\<^esub> K \\<inter> \\<GG> ! (i + 1)\\<rparr> Mod \\<GG> ! i)\" \n    by (metis inf_commute)\n  hence \"\\<phi> \\<in> iso (G\\<lparr>carrier := K \\<inter> \\<GG> ! (i + 1)\\<rparr> Mod (K \\<inter> (\\<GG> ! (i + 1) \\<inter> \\<GG> ! i)))\n                 (G\\<lparr>carrier := \\<GG> ! i <#>\\<^bsub>G\\<lparr>carrier := \\<GG> ! (i + 1)\\<rparr>\\<^esub> K \\<inter> \\<GG> ! (i + 1)\\<rparr> Mod \\<GG> ! i)\"\n    by (metis Int_assoc)\n  hence \"\\<phi> \\<in> iso (G\\<lparr>carrier := K \\<inter> \\<GG> ! (i + 1)\\<rparr> Mod (K \\<inter> \\<GG> ! i))\n                 (G\\<lparr>carrier := \\<GG> ! i <#>\\<^bsub>G\\<lparr>carrier := \\<GG> ! (i + 1)\\<rparr>\\<^esub> K \\<inter> \\<GG> ! (i + 1)\\<rparr> Mod \\<GG> ! i)\" \n    by (metis GiSi' Int_absorb2 Int_commute)\n  hence \\<phi>: \"\\<phi> \\<in> iso (G\\<lparr>carrier := K \\<inter> \\<GG> ! (i + 1)\\<rparr> Mod (K \\<inter> \\<GG> ! i))\n                   (G\\<lparr>carrier := \\<GG> ! i <#> K \\<inter> \\<GG> ! (i + 1)\\<rparr> Mod \\<GG> ! i)\"\n    unfolding set_mult_def by auto\n  from fstgoal have KGsiKGigroup: \"group (G\\<lparr>carrier := K \\<inter> \\<GG> ! (i + 1)\\<rparr> Mod (K \\<inter> \\<GG> ! i))\" using normal.factorgroup_is_group by auto\n  from KGdisj show \"simple_group (G\\<lparr>carrier := K, carrier := remdups_adj (map ((\\<inter>) K) \\<GG>) ! (j + 1)\\<rparr> Mod remdups_adj (map ((\\<inter>) K) \\<GG>) ! j)\"\n  proof auto\n    have groupGi: \"group (G\\<lparr>carrier := \\<GG> ! i\\<rparr>)\" using i' normal_series_subgroups subgroup_imp_group by auto\n    assume \"\\<GG> ! i <#> K \\<inter> \\<GG> ! Suc i = \\<GG> ! i\"\n    with \\<phi> have \"\\<phi> \\<in> iso (G\\<lparr>carrier := K \\<inter> \\<GG> ! (i + 1)\\<rparr> Mod (K \\<inter> \\<GG> ! i)) (G\\<lparr>carrier := \\<GG> ! i\\<rparr> Mod \\<GG> ! i)\" by auto\n    moreover obtain \\<psi> where \"\\<psi> \\<in> iso (G\\<lparr>carrier := \\<GG> ! i\\<rparr> Mod (carrier (G\\<lparr>carrier := \\<GG> ! i\\<rparr>))) (G\\<lparr>carrier := {\\<one>\\<^bsub>G\\<lparr>carrier := \\<GG> ! i\\<rparr>\\<^esub>}\\<rparr>)\"\n      using group.self_factor_iso groupGi by force\n    ultimately obtain \\<pi> where \"\\<pi> \\<in> iso (G\\<lparr>carrier := K \\<inter> \\<GG> ! (i + 1)\\<rparr> Mod (K \\<inter> \\<GG> ! i)) (G\\<lparr>carrier := {\\<one>}\\<rparr>)\"\n      using iso_set_trans by fastforce\n    hence \"order (G\\<lparr>carrier := K \\<inter> \\<GG> ! (i + 1)\\<rparr> Mod (K \\<inter> \\<GG> ! i)) = order (G\\<lparr>carrier := {\\<one>}\\<rparr>)\"\n      by (meson iso_same_order)\n    hence \"order (G\\<lparr>carrier := K \\<inter> \\<GG> ! (i + 1)\\<rparr> Mod (K \\<inter> \\<GG> ! i)) = 1\" unfolding order_def by auto\n    hence \"carrier (G\\<lparr>carrier := K \\<inter> \\<GG> ! (i + 1)\\<rparr> Mod (K \\<inter> \\<GG> ! i)) = {\\<one>\\<^bsub>G\\<lparr>carrier := K \\<inter> \\<GG> ! (i + 1)\\<rparr> Mod (K \\<inter> \\<GG> ! i)\\<^esub>}\"\n      using group.order_one_triv_iff KGsiKGigroup by blast\n    moreover from fstgoal have \"K \\<inter> \\<GG> ! i \\<lhd> G\\<lparr>carrier := K \\<inter> \\<GG> ! (i + 1)\\<rparr>\" by auto\n    moreover from finGSi have \"finite (carrier (G\\<lparr>carrier := K \\<inter> \\<GG> ! (i + 1)\\<rparr>))\" by auto\n    ultimately have \"K \\<inter> \\<GG> ! i = carrier (G\\<lparr>carrier := K \\<inter> \\<GG> ! (i + 1)\\<rparr>)\" by (metis normal.fact_group_trivial_iff)\n    hence \"(remdups_adj (map ((\\<inter>) K) \\<GG>)) ! j = (remdups_adj (map ((\\<inter>) K) \\<GG>)) ! (j + 1)\" using i by auto\n    with j have False using remdups_adj_adjacent KGnotempty Suc_eq_plus1 by metis\n    thus \"simple_group (G\\<lparr>carrier := remdups_adj (map ((\\<inter>) K) \\<GG>) ! Suc j\\<rparr> Mod remdups_adj (map ((\\<inter>) K) \\<GG>) ! j)\"..\n  next\n    assume \"\\<GG> ! i <#> K \\<inter> \\<GG> ! Suc i = \\<GG> ! Suc i\"\n    with \\<phi> have \"\\<phi> \\<in> iso (G\\<lparr>carrier := K \\<inter> \\<GG> ! (i + 1)\\<rparr> Mod (K \\<inter> \\<GG> ! i)) (G\\<lparr>carrier := \\<GG> ! (i + 1)\\<rparr> Mod \\<GG> ! i)\"\n      by auto\n    then obtain \\<phi>' where \"\\<phi>' \\<in> iso (G\\<lparr>carrier := \\<GG> ! (i + 1)\\<rparr> Mod \\<GG> ! i) (G\\<lparr>carrier := K \\<inter> \\<GG> ! (i + 1)\\<rparr> Mod (K \\<inter> \\<GG> ! i))\"\n      using KGsiKGigroup group.iso_set_sym by auto\n    with Gisimple KGsiKGigroup have \"simple_group (G\\<lparr>carrier := K \\<inter> \\<GG> ! (i + 1)\\<rparr> Mod (K \\<inter> \\<GG> ! i))\" by (metis simple_group.iso_simple)\n    with i show \"simple_group (G\\<lparr>carrier := remdups_adj (map ((\\<inter>) K) \\<GG>) ! Suc j\\<rparr> Mod remdups_adj (map ((\\<inter>) K) \\<GG>) ! j)\"\n      by auto\n  qed\nqed\n\nlemma (in group) composition_series_extend:\n  assumes \"composition_series (G\\<lparr>carrier := H\\<rparr>) \\<HH>\"\n  assumes \"simple_group (G Mod H)\" \"H \\<lhd> G\"\n  shows \"composition_series G (\\<HH> @ [carrier G])\"\nunfolding composition_series_def composition_series_axioms_def\nproof auto\n  from assms(1) interpret comp\\<HH>: composition_series \"G\\<lparr>carrier := H\\<rparr>\" \\<HH> .\n  show \"normal_series G (\\<HH> @ [carrier G])\" using  assms(3) comp\\<HH>.is_normal_series by (metis normal_series_extend)\n  fix i\n  assume i: \"i < length \\<HH>\"\n  show \"simple_group (G\\<lparr>carrier := (\\<HH> @ [carrier G]) ! Suc i\\<rparr> Mod (\\<HH> @ [carrier G]) ! i)\"\n  proof (cases \"i = length \\<HH> - 1\")\n    case True\n    hence \"(\\<HH> @ [carrier G]) ! Suc i = carrier G\" by (metis i diff_Suc_1 lessE nth_append_length)\n    moreover have \"(\\<HH> @ [carrier G]) ! i = \\<HH> ! i\"by (metis butlast_snoc i nth_butlast)\n    hence \"(\\<HH> @ [carrier G]) ! i = H\" using True last_conv_nth comp\\<HH>.notempty comp\\<HH>.last by auto\n    ultimately show ?thesis using assms(2) by auto\n  next\n    case False\n    hence \"Suc i < length \\<HH>\" using i by auto\n    hence \"(\\<HH> @ [carrier G]) ! Suc i = \\<HH> ! Suc i\" using nth_append by metis\n    moreover from i have \"(\\<HH> @ [carrier G]) ! i = \\<HH> ! i\" using nth_append by metis\n    ultimately show ?thesis using \\<open>Suc i < length \\<HH>\\<close> comp\\<HH>.simplefact by auto\n  qed\nqed\n\nlemma (in composition_series) entries_mono:\n  assumes \"i \\<le> j\" \"j < length \\<GG>\"\n  shows \"\\<GG> ! i \\<subseteq> \\<GG> ! j\"\nusing assms proof (induction \"j - i\" arbitrary: i j)\n  case 0\n  hence \"i = j\" by auto\n  thus \"\\<GG> ! i \\<subseteq> \\<GG> ! j\" by auto\nnext\n  case (Suc k i j)\n  hence i': \"i + (Suc k) = j\" \"i + 1 < length \\<GG>\" by auto\n  hence ij: \"i + 1 \\<le> j\" by auto\n  have \"\\<GG> ! i \\<subseteq> \\<GG> ! (i + 1)\" using i' normal normal_imp_subgroup subgroup.subset by force\n  moreover have \"j - (i + 1) = k\" \"j < length \\<GG>\" using Suc assms by auto\n  hence \"\\<GG> ! (i + 1) \\<subseteq> \\<GG> ! j\" using Suc(1) ij by auto\n  ultimately show \"\\<GG> ! i \\<subseteq> \\<GG> ! j\" 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/Jordan_Hoelder/CompositionSeries.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8397339756938818, "lm_q2_score": 0.8807970889295664, "lm_q1q2_score": 0.7396352412664223}}
{"text": "theory Digits_int\n  imports Complex_Main\nbegin\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\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 :: int\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 + nat 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 * nat 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\nlemma int_from_digits:\n  \"int (from_digits n d) = (\\<Sum>i<n. int (d i) * base ^ i)\"\nunfolding from_digits_altdef using base_pos by auto\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 :: \"int \\<Rightarrow> nat \\<Rightarrow> int\" where\n  \"digit x 0 = \\<bar>x\\<bar> mod base\"\n| \"digit x (Suc i) = digit (\\<bar>x\\<bar> div base) i\"\n\ntext \\<open>Alternative definition using divisor and modulo:\\<close>\nlemma digit_altdef: \"digit x i = ( \\<bar>x\\<bar> div (base ^ i)) mod base\"\nproof (induction x i rule: digit.induct)\n  case (2 x i)\n  show ?case by (subst digit.simps(2), subst 2) (smt (verit, ccfv_SIG) base_pos \n        pos_imp_zdiv_neg_iff power.simps(2) zdiv_zmult2_eq zero_less_power)\nqed simp\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 (simp add: \"2.hyps\")\n  moreover have \"d 0 \\<le> base -1\" using 2 by simp\n  ultimately have \"d 0 + base * from_digits n (d \\<circ> Suc) \\<le> \n      base - 1 + base * (base^(n) - 1)\" \n    by (smt (verit, ccfv_SIG) base_pos mult_less_cancel_left_pos)\n  then show \"from_digits (Suc n) d < base ^ Suc n\" \n    using base_pos by (simp add: right_diff_distrib)\nqed auto\n\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    int_from_digits by simp\nqed\n\nlemma mod_base_i:  \n  assumes \"\\<And>i. i<n \\<Longrightarrow> (d i ::nat) < base\" \"n>0\" \"i<n\"\n  shows \"(\\<Sum>j=i..<n. d j * base ^ (j-i)) mod base = d i \"\nproof -\n  have eq: \"(\\<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  using assms \n    split_sum_first_elt_less[where  f = \"(\\<lambda>j. d j * base ^ (j-i) mod base)\"]\n    int_from_digits by auto\nqed\n\n\nlemma div_base_i: \n  assumes \"\\<And>i. i<n \\<Longrightarrow> (d i::nat) < 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 int_from_digits 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 int_from_digits by auto\n  have ge_0: \"0 \\<le> (\\<Sum>j<i. int (d j) * base ^ j)\" using base_pos\n  by (metis int_from_digits of_nat_0_le_iff)\n  have eq: \"(\\<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  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    unfolding eq using base_exp mult.assoc sum_distrib_right\n    by (smt (z3) mult.commute sum.cong)\n  show \"(\\<Sum>i<n. d i * base ^ i) div base ^ i = \n             (\\<Sum>j = i..<n. d j * base ^ (j - i))\" \n    unfolding split_sum using base_pos first div_pos_pos_trivial[OF ge_0 first]\n    by (subst div_mult_self2, auto)\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  using assms(1) assms(3) mod_base by force\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\n\nlemma(in digits) digits_eq_0:\n  assumes \"x = 0\"\n  shows \"digit x i = 0\"\nby (simp add: assms digit_altdef)\nend\n\n\nlemma split_digits_eq_zero:\n  assumes \"a + base * b = 0\" \"\\<bar>a\\<bar><base\" \"(base::int)>2\"\n  shows \"a = 0 \\<and> b=0\"\nusing assms proof (cases \"b = 0\")\n  case True\n  then show \"a=0 \\<and> b=0\" using assms by auto\nnext\n  case False\n  then have \"\\<bar>b\\<bar> \\<ge> 1\" by auto\n  then have \"\\<bar>a\\<bar> < \\<bar>base * b\\<bar>\" using assms(2) assms(3)\n    by (subst abs_mult) (smt (verit) mult_le_cancel_left1)\n  moreover have \"\\<bar>a\\<bar> = \\<bar>base * b\\<bar>\" using assms(1) by auto\n  ultimately have False by auto\n  then show ?thesis by auto\nqed\n\n\nlemma respresentation_in_basis_eq_zero:\n  assumes \"(\\<Sum>i<n. c i * base^i) = 0\" \"(base::int) > 2\" \"\\<And>i. i<n \\<Longrightarrow> \\<bar>c i\\<bar> < base\" \"i<n\"\n  shows \"c i = 0\"\nusing assms proof (induction n arbitrary: i c)\n  case 0\n  then show ?case by auto\nnext\n  case (Suc n)\n  have eq_0: \"c 0 + base * (\\<Sum>i<n. c (i+1) * base ^ i) = 0\" \n    using Suc(2) unfolding sum.lessThan_Suc_shift power_Suc sum.cong[of \"{..<n}\" \"{..<n}\" \n      \"(\\<lambda>i. c (Suc i) * (base * base ^ i))\" \"(\\<lambda>i. base * (c (n + 1) * base ^ n))\"]\n    by (subst sum_distrib_left)(metis (no_types, lifting) Suc_eq_plus1 mult.left_commute \n      mult_cancel_left1 power_0 sum.cong)\n  have \"c 0 = 0 \" and right: \"(\\<Sum>i<n. c (i+1) * base ^ i) = 0\" \n    using split_digits_eq_zero[OF eq_0 Suc(4)[of 0] Suc(3)] by auto\n  have lt_n: \"c (i + 1) = 0\" if \"i<n\" for i using Suc(4)\n    by (subst Suc(1)[OF right \\<open>2<base\\<close> _ \\<open>i<n\\<close>], auto) \n  then show ?case\n  proof (cases \"i=0\")\n    case False\n    then show ?thesis using Suc(5) lt_n less_Suc_eq_0_disj by auto\n  qed (use \\<open>c 0 = 0\\<close> in \\<open>auto\\<close>)\nqed\n\nend", "meta": {"author": "ThikaXer", "repo": "Formalization-of-NP-hardness-Proofs-for-Lattice-Problems", "sha": "5e54a2de9219c1bd347268611330664ac2904da2", "save_path": "github-repos/isabelle/ThikaXer-Formalization-of-NP-hardness-Proofs-for-Lattice-Problems", "path": "github-repos/isabelle/ThikaXer-Formalization-of-NP-hardness-Proofs-for-Lattice-Problems/Formalization-of-NP-hardness-Proofs-for-Lattice-Problems-5e54a2de9219c1bd347268611330664ac2904da2/Digits_int.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.880797068590724, "lm_q2_score": 0.8397339676722393, "lm_q1q2_score": 0.7396352171217662}}
{"text": " theory Q2\nimports Main\nbegin\n\ntheorem ex1 : \n  assumes rpq: \"R\u27f6P\u2228Q\"\n and rfalseq: \"R\u27f6\u00acQ\"\n    shows \"R\u27f6P\"\nproof -\n   have rp: \"R\u27f9P\"\n   proof -\n     assume r: \"R\"\n     from rpq and r have  pq: \"P\u2228Q\" by (rule impE) \n     from rfalseq and r have nq: \"\u00acQ\" by (rule impE)\n\n     have npfalse: \"\u00acP \u27f9 False\"\n     proof -\n       assume np: \"\u00acP\"\n       \n       have falseq: \"Q \u27f9 False\"\n       proof -\n         assume q: \"Q\"\n         from nq and q show \"False\" by (rule notE)\n       qed\n      \n       have pfalse: \"P \u27f9 False\"\n       proof - \n         assume p: \"P\"\n         from np and p show \"False\" by (rule notE)\n       qed\n       \n       from pq and pfalse and falseq show \"False\" by (rule disjE)\n     qed\n     from npfalse have nnp: \"\u00ac\u00acP\" by (rule notI)\n     from nnp show p: \"P\" by (rule notnotD)\n   qed\n   from rp show \"R \u27f6 P\" by (rule impI)\n qed\nend\n", "meta": {"author": "samuelluiz", "repo": "LOG_Projeto_2", "sha": "af3b8379b4da943537541b16c1a0aa033f056e55", "save_path": "github-repos/isabelle/samuelluiz-LOG_Projeto_2", "path": "github-repos/isabelle/samuelluiz-LOG_Projeto_2/LOG_Projeto_2-af3b8379b4da943537541b16c1a0aa033f056e55/Q2.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361652391386, "lm_q2_score": 0.8104789063814616, "lm_q1q2_score": 0.7395102653459117}}
{"text": "(*  \n  Title:    Preference_Profiles.thy\n  Author:   Manuel Eberl, TU M\u00fcnchen\n\n  Definition of (weak) preference profiles and functions for building\n  and manipulating them\n*)\n\nsection \\<open>Preference Profiles\\<close>\n\ntheory Preference_Profiles\nimports\n  Main \n  Order_Predicates \n  \"~~/src/HOL/Library/Multiset\"\n  \"~~/src/HOL/Library/Disjoint_Sets\"\n  Missing_Multiset\n  Missing_Permutations\nbegin\n\ntext \\<open>The type of preference profiles\\<close>\ntype_synonym ('agent, 'alt) pref_profile = \"'agent \\<Rightarrow> 'alt relation\"\n\nlocale preorder_family = \n  fixes dom :: \"'a set\" and carrier :: \"'b set\" and R :: \"'a \\<Rightarrow> 'b relation\"\n  assumes nonempty_dom: \"dom \\<noteq> {}\"\n  assumes in_dom [simp]: \"i \\<in> dom \\<Longrightarrow> preorder_on carrier (R i)\"\n  assumes not_in_dom [simp]: \"i \\<notin> dom \\<Longrightarrow> \\<not>R i x y\"\nbegin\n\n\n\nend\n\n\nlocale pref_profile_wf =\n  fixes agents :: \"'agent set\" and alts :: \"'alt set\" and R :: \"('agent, 'alt) pref_profile\"\n  assumes nonempty_agents [simp]: \"agents \\<noteq> {}\" and nonempty_alts [simp]: \"alts \\<noteq> {}\"\n  assumes prefs_wf [simp]: \"i \\<in> agents \\<Longrightarrow> finite_total_preorder_on alts (R i)\"\n  assumes prefs_undefined [simp]: \"i \\<notin> agents \\<Longrightarrow> \\<not>R i x y\"\nbegin\n\nlemma finite_alts [simp]: \"finite alts\"\nproof -\n  from nonempty_agents obtain i where \"i \\<in> agents\" by blast\n  then interpret finite_total_preorder_on alts \"R i\" by simp\n  show ?thesis by fact\nqed\n\nlemma prefs_wf' [simp]:\n  \"i \\<in> agents \\<Longrightarrow> total_preorder_on alts (R i)\" \"i \\<in> agents \\<Longrightarrow> preorder_on alts (R i)\"\n  using prefs_wf[of i]\n  by (simp_all add: finite_total_preorder_on_def total_preorder_on_def del: prefs_wf)\n\nlemma not_outside: \n  assumes \"x \\<preceq>[R i] y\"\n  shows   \"i \\<in> agents\" \"x \\<in> alts\" \"y \\<in> alts\"\nproof -\n  from assms show \"i \\<in> agents\" by (cases \"i \\<in> agents\") auto\n  then interpret preorder_on alts \"R i\" by simp\n  from assms show \"x \\<in> alts\" \"y \\<in> alts\" by (simp_all add: not_outside)\nqed\n\nsublocale preorder_family agents alts R\n  by (intro preorder_family.intro) simp_all\n\nlemmas prefs_undefined' = not_in_dom'\n\nlemma wf_update:\n  assumes \"i \\<in> agents\" \"total_preorder_on alts Ri'\"\n  shows   \"pref_profile_wf agents alts (R(i := Ri'))\"\nproof -\n  interpret total_preorder_on alts Ri' by fact\n  from finite_alts have \"finite_total_preorder_on alts Ri'\" by unfold_locales\n  with assms show ?thesis\n    by (auto intro!: pref_profile_wf.intro split: if_splits)\nqed\n\nlemma wf_permute_agents:\n  assumes \"\\<sigma> permutes agents\"\n  shows   \"pref_profile_wf agents alts (R \\<circ> \\<sigma>)\"\n  unfolding o_def using permutes_in_image[OF assms(1)]\n  by (intro pref_profile_wf.intro prefs_wf) simp_all\n\nlemma (in -) pref_profile_eqI:\n  assumes \"pref_profile_wf agents alts R1\" \"pref_profile_wf agents alts R2\"\n  assumes \"\\<And>x. x \\<in> agents \\<Longrightarrow> R1 x = R2 x\"\n  shows   \"R1 = R2\"\nproof\n  interpret R1: pref_profile_wf agents alts R1 by fact\n  interpret R2: pref_profile_wf agents alts R2 by fact\n  fix x show \"R1 x = R2 x\"\n    by (cases \"x \\<in> agents\"; intro ext) (simp_all add: assms(3)) \nqed\n\nend\n\n\ntext \\<open>\n  Permutes a preference profile w.r.t. alternatives in the way described in the paper.\n  This is needed for the definition of neutrality.\n\\<close>\ndefinition permute_profile where\n  \"permute_profile \\<sigma> R = (\\<lambda>i x y. R i (inv \\<sigma> x) (inv \\<sigma> y))\"\n  \nlemma permute_profile_map_relation:\n  \"permute_profile \\<sigma> R = (\\<lambda>i. map_relation (inv \\<sigma>) (R i))\"\n  by (simp add: permute_profile_def map_relation_def)\n\nlemma permute_profile_compose [simp]:\n  \"permute_profile \\<sigma> (R \\<circ> \\<pi>) = permute_profile \\<sigma> R \\<circ> \\<pi>\"\n  by (auto simp: fun_eq_iff permute_profile_def o_def)\n\nlemma permute_profile_id [simp]: \"permute_profile id R = R\"\n  by (simp add: permute_profile_def)\n\nlemma permute_profile_o:\n  assumes \"bij f\" \"bij g\"\n  shows   \"permute_profile f (permute_profile g R) = permute_profile (f \\<circ> g) R\"\n  using assms by (simp add: permute_profile_def o_inv_distrib)\n\nlemma (in pref_profile_wf) wf_permute_alts:\n  assumes \"\\<sigma> permutes alts\"\n  shows   \"pref_profile_wf agents alts (permute_profile \\<sigma> R)\"\nproof (rule pref_profile_wf.intro)\n  fix i assume \"i \\<in> agents\"\n  with assms interpret R: finite_total_preorder_on alts \"R i\" by simp\n    \n  from assms have [simp]: \"inv \\<sigma> x \\<in> alts \\<longleftrightarrow> x \\<in> alts\" for x\n    by (simp add: permutes_in_image permutes_inv)\n\n  show \"finite_total_preorder_on alts (permute_profile \\<sigma> R i)\"\n  proof\n    fix x y assume \"permute_profile \\<sigma> R i x y\"\n    thus \"x \\<in> alts\" \"y \\<in> alts\"\n      using R.not_outside[of \"inv \\<sigma> x\" \"inv \\<sigma> y\"]\n      by (auto simp: permute_profile_def)\n  next\n    fix x y z assume \"permute_profile \\<sigma> R i x y\" \"permute_profile \\<sigma> R i y z\"\n    thus \"permute_profile \\<sigma> R i x z\"\n      using R.trans[of \"inv \\<sigma> x\" \"inv \\<sigma> y\" \"inv \\<sigma> z\"] \n      by (simp_all add: permute_profile_def)\n  qed (insert R.total R.refl R.finite_carrier, simp_all add: permute_profile_def)\nqed (insert assms, simp_all add: permute_profile_def pref_profile_wf_def)\n\n\ntext \\<open>\n  This shows that the above definition is equivalent to that in the paper.  \n\\<close>\nlemma permute_profile_iff [simp]:\n  fixes R :: \"('agent, 'alt) pref_profile\"\n  assumes \"\\<sigma> permutes alts\" \"x \\<in> alts\" \"y \\<in> alts\"\n  defines \"R' \\<equiv> permute_profile \\<sigma> R\"\n  shows   \"\\<sigma> x \\<preceq>[R' i] \\<sigma> y \\<longleftrightarrow> x \\<preceq>[R i] y\"\n  using assms by (simp add: permute_profile_def permutes_inverses)\n\n\nsubsection \\<open>Pareto dominance\\<close>\n\ndefinition Pareto :: \"('agent \\<Rightarrow> 'alt relation) \\<Rightarrow> 'alt relation\" where\n  \"x \\<preceq>[Pareto(R)] y \\<longleftrightarrow> (\\<exists>j. x \\<preceq>[R j] x) \\<and> (\\<forall>i. x \\<preceq>[R i] x \\<longrightarrow> x \\<preceq>[R i] y)\"\n\ntext \\<open>\n  A Pareto loser is an alternative that is Pareto-dominated by some other alternative.\n\\<close>\ndefinition pareto_losers :: \"('agent, 'alt) pref_profile \\<Rightarrow> 'alt set\" where\n  \"pareto_losers R = {x. \\<exists>y. y \\<succ>[Pareto(R)] x}\"\n\nlemma pareto_losersI [intro?, simp]: \"y \\<succ>[Pareto(R)] x \\<Longrightarrow> x \\<in> pareto_losers R\"\n  by (auto simp: pareto_losers_def)\n\ncontext preorder_family\nbegin\n\nlemma Pareto_iff:\n  \"x \\<preceq>[Pareto(R)] y \\<longleftrightarrow> (\\<forall>i\\<in>dom. x \\<preceq>[R i] y)\"\nproof\n  assume A: \"x \\<preceq>[Pareto(R)] y\"\n  then obtain j where j: \"x \\<preceq>[R j] x\" by (auto simp: Pareto_def)\n  hence j': \"j \\<in> dom\" by (cases \"j \\<in> dom\") auto\n  then interpret preorder_on carrier \"R j\" by simp\n  from j have \"x \\<in> carrier\" by (auto simp: carrier_eq)\n  with A preorder_on.refl[OF in_dom]\n    show \"(\\<forall>i\\<in>dom. x \\<preceq>[R i] y)\" by (auto simp: Pareto_def)\nnext\n  assume A: \"(\\<forall>i\\<in>dom. x \\<preceq>[R i] y)\"\n  from nonempty_dom obtain j where j: \"j \\<in> dom\" by blast\n  then interpret preorder_on carrier \"R j\" by simp \n  from j A have \"x \\<preceq>[R j] y\" by simp\n  hence \"x \\<preceq>[R j] x\" using not_outside refl by blast\n  with A show \"x \\<preceq>[Pareto(R)] y\" by (auto simp: Pareto_def)\nqed\n\nlemma Pareto_strict_iff: \n  \"x \\<prec>[Pareto(R)] y \\<longleftrightarrow> (\\<forall>i\\<in>dom. x \\<preceq>[R i] y) \\<and> (\\<exists>i\\<in>dom. x \\<prec>[R i] y)\"\n  by (auto simp: strongly_preferred_def Pareto_iff nonempty_dom)\n\nlemma not_Pareto_strict_iff:\n  \"\\<not>(x \\<prec>[Pareto(R)] y) \\<longleftrightarrow> ((\\<exists>i\\<in>dom. \\<not> R i x y) \\<or> (\\<forall>i\\<in>dom. R i x y \\<and> R i y x))\"\n  unfolding Pareto_strict_iff by (auto simp: strongly_preferred_def)\n\nlemma Pareto_strictI:\n  assumes \"\\<And>i. i \\<in> dom \\<Longrightarrow> x \\<preceq>[R i] y\" \"i \\<in> dom\" \"x \\<prec>[R i] y\"\n  shows   \"x \\<prec>[Pareto(R)] y\"\n  using assms by (auto simp: Pareto_strict_iff)\n\nlemma Pareto_strictI':\n  assumes \"\\<And>i. i \\<in> dom \\<Longrightarrow> x \\<preceq>[R i] y\" \"i \\<in> dom\" \"\\<not>x \\<succeq>[R i] y\"\n  shows   \"x \\<prec>[Pareto(R)] y\"\nproof -\n  from assms interpret preorder_on carrier \"R i\" by simp\n  from assms have \"x \\<prec>[R i] y\" by (simp add: strongly_preferred_def)\n  with assms show ?thesis by (auto simp: Pareto_strict_iff )\nqed\n\n\nsublocale Pareto: preorder_on carrier \"Pareto(R)\"\nproof -\n  have \"preorder_on carrier (R i)\" if \"i \\<in> dom\" for i using that by simp_all\n  note A = preorder_on.not_outside[OF this(1)] preorder_on.refl[OF this(1)]\n           preorder_on.trans[OF this(1)]\n  from nonempty_dom obtain i where i: \"i \\<in> dom\" by blast\n  show \"preorder_on carrier (Pareto R)\"\n  proof\n    fix x y assume \"x \\<preceq>[Pareto(R)] y\"\n    with A(1,2)[OF i] i show \"x \\<in> carrier\" \"y \\<in> carrier\" by (auto simp: Pareto_iff)\n  qed (auto simp: Pareto_iff intro: A)\nqed\n\nlemma pareto_loser_in_alts: \n  assumes \"x \\<in> pareto_losers R\"\n  shows   \"x \\<in> carrier\"\nproof -\n  from assms obtain y i where \"i \\<in> dom\" \"x \\<prec>[R i] y\"\n    by (auto simp: pareto_losers_def Pareto_strict_iff)\n  then interpret preorder_on carrier \"R i\" by simp\n  from \\<open>x \\<prec>[R i] y\\<close> have \"x \\<preceq>[R i] y\" by (simp add: strongly_preferred_def)\n  thus \"x \\<in> carrier\" using not_outside by simp\nqed\n\nlemma pareto_losersE:\n  assumes \"x \\<in> pareto_losers R\"\n  obtains y where \"y \\<in> carrier\" \"y \\<succ>[Pareto(R)] x\"\nproof -\n  from assms obtain y where \"y \\<succ>[Pareto(R)] x\" unfolding pareto_losers_def by blast\n  moreover from this Pareto.not_outside[of x y] have \"y \\<in> carrier\" \n    by (simp add: strongly_preferred_def)\n  ultimately show ?thesis using that by blast\nqed\n\nend\n\n\nsubsection \\<open>Preferred alternatives\\<close>\n\ncontext pref_profile_wf\nbegin\n\nlemma preferred_alts_subset_alts: \"preferred_alts (R i) x \\<subseteq> alts\" (is ?A)\n  and finite_preferred_alts [simp,intro!]: \"finite (preferred_alts (R i) x)\" (is ?B)\nproof -\n  have \"?A \\<and> ?B\"\n  proof (cases \"i \\<in> agents\")\n    assume \"i \\<in> agents\"\n    then interpret total_preorder_on alts \"R i\" by simp\n    have \"preferred_alts (R i) x \\<subseteq> alts\" using not_outside\n      by (auto simp: preferred_alts_def)\n    thus ?thesis by (auto dest: finite_subset)\n  qed (auto simp: preferred_alts_def)\n  thus ?A ?B by blast+\nqed\n\nlemma preferred_alts_altdef: \n  \"i \\<in> agents \\<Longrightarrow> preferred_alts (R i) x = {y\\<in>alts. y \\<succeq>[R i] x}\"\n  by (simp add: preorder_on.preferred_alts_altdef)  \n\nend\n\n\nsubsection \\<open>Favourite alternatives\\<close>\n\ndefinition favorites :: \"('agent, 'alt) pref_profile \\<Rightarrow> 'agent \\<Rightarrow> 'alt set\" where\n  \"favorites R i = Max_wrt (R i)\"\n\ndefinition favorite :: \"('agent, 'alt) pref_profile \\<Rightarrow> 'agent \\<Rightarrow> 'alt\" where\n  \"favorite R i = the_elem (favorites R i)\"\n\ndefinition has_unique_favorites :: \"('agent, 'alt) pref_profile \\<Rightarrow> bool\" where\n  \"has_unique_favorites R \\<longleftrightarrow> (\\<forall>i. favorites R i = {} \\<or> is_singleton (favorites R i))\"\n\ncontext pref_profile_wf\nbegin\n\nlemma favorites_altdef:\n  \"favorites R i = Max_wrt_among (R i) alts\"\nproof (cases \"i \\<in> agents\")\n  assume \"i \\<in> agents\"\n  with assms interpret total_preorder_on alts \"R i\" by simp\n  show ?thesis \n    by (simp add: favorites_def Max_wrt_total_preorder Max_wrt_among_total_preorder)\nqed (insert assms, simp_all add: favorites_def Max_wrt_def Max_wrt_among_def pref_profile_wf_def)\n\nlemma favorites_no_agent [simp]: \"i \\<notin> agents \\<Longrightarrow> favorites R i = {}\"\n  by (auto simp: favorites_def Max_wrt_def Max_wrt_among_def)\n\nlemma favorites_altdef':\n  \"favorites R i = {x\\<in>alts. \\<forall>y\\<in>alts. x \\<succeq>[R i] y}\"\nproof (cases \"i \\<in> agents\")\n  assume \"i \\<in> agents\"\n  then interpret finite_total_preorder_on alts \"R i\" by simp\n  show ?thesis using Max_wrt_among_nonempty[of alts] Max_wrt_among_subset[of alts]\n    by (auto simp: favorites_altdef Max_wrt_among_total_preorder)\nqed simp_all\n\nlemma favorites_subset_alts: \"favorites R i \\<subseteq> alts\"\n  using assms by (auto simp: favorites_altdef')\n\nlemma finite_favorites [simp, intro]: \"finite (favorites R i)\"\n  using favorites_subset_alts finite_alts  by (rule finite_subset)\n\nlemma favorites_nonempty: \"i \\<in> agents \\<Longrightarrow> favorites R i \\<noteq> {}\"\nproof -\n  assume \"i \\<in> agents\"\n  then interpret finite_total_preorder_on alts \"R i\" by simp\n  show ?thesis unfolding favorites_def by (intro Max_wrt_nonempty) simp_all\nqed\n\nlemma favorites_permute: \n  assumes i: \"i \\<in> agents\" and perm: \"\\<sigma> permutes alts\"\n  shows   \"favorites (permute_profile \\<sigma> R) i = \\<sigma> ` favorites R i\"\nproof -\n  from i interpret finite_total_preorder_on alts \"R i\" by simp\n  from perm show ?thesis\n  unfolding favorites_def\n    by (subst Max_wrt_map_relation_bij)\n       (simp_all add: permute_profile_def map_relation_def permutes_bij)\nqed\n\nlemma has_unique_favorites_altdef:\n  \"has_unique_favorites R \\<longleftrightarrow> (\\<forall>i\\<in>agents. is_singleton (favorites R i))\"\nproof safe\n  fix i assume \"has_unique_favorites R\" \"i \\<in> agents\"\n  thus \"is_singleton (favorites R i)\" using favorites_nonempty[of i]\n    by (auto simp: has_unique_favorites_def)\nnext\n  assume \"\\<forall>i\\<in>agents. is_singleton (favorites R i)\"\n  hence \"is_singleton (favorites R i) \\<or> favorites R i = {}\" for i\n    by (cases \"i \\<in> agents\") (simp add: favorites_nonempty, simp add: favorites_altdef')\n  thus \"has_unique_favorites R\" by (auto simp: has_unique_favorites_def)\nqed\n\nend\n\n\nlocale pref_profile_unique_favorites = pref_profile_wf agents alts R\n  for agents :: \"'agent set\" and alts :: \"'alt set\" and R +\n  assumes unique_favorites': \"has_unique_favorites R\"\nbegin\n  \nlemma unique_favorites: \"i \\<in> agents \\<Longrightarrow> favorites R i = {favorite R i}\"\n  using unique_favorites' \n  by (auto simp: favorite_def has_unique_favorites_altdef is_singleton_the_elem)\n\nlemma favorite_in_alts: \"i \\<in> agents \\<Longrightarrow> favorite R i \\<in> alts\"\n  using favorites_subset_alts[of i] by (simp add: unique_favorites)\n\nend\n\n  \n\nsubsection \\<open>Anonymous profiles\\<close>\n\ntype_synonym ('agent, 'alt) apref_profile = \"'alt set list multiset\"\n\ndefinition anonymous_profile :: \"('agent, 'alt) pref_profile \\<Rightarrow> ('agent, 'alt) apref_profile\" \n  where anonymous_profile_auxdef:\n    \"anonymous_profile R = image_mset (weak_ranking \\<circ> R) (mset_set {i. R i \\<noteq> (\\<lambda>_ _. False)})\"\n\nlemma (in pref_profile_wf) agents_eq:\n  \"agents = {i. R i \\<noteq> (\\<lambda>_ _. False)}\"\nproof safe\n  fix i assume i: \"i \\<in> agents\" and Ri: \"R i = (\\<lambda>_ _. False)\"\n  from i interpret preorder_on alts \"R i\" by simp\n  from carrier_eq Ri nonempty_alts show False by simp\nnext\n  fix i assume \"R i \\<noteq> (\\<lambda>_ _. False)\"\n  thus \"i \\<in> agents\" using prefs_undefined'[of i] by (cases \"i \\<in> agents\") auto\nqed\n\nlemma (in pref_profile_wf) anonymous_profile_def:\n  \"anonymous_profile R = image_mset (weak_ranking \\<circ> R) (mset_set agents)\"\n  by (simp only: agents_eq anonymous_profile_auxdef)\n\nlemma (in pref_profile_wf) anonymous_profile_permute:\n  assumes \"\\<sigma> permutes alts\"  \"finite agents\" \n  shows   \"anonymous_profile (permute_profile \\<sigma> R) = \n             image_mset (map (op ` \\<sigma>)) (anonymous_profile R)\"\nproof -\n  from assms(1) interpret R': pref_profile_wf agents alts \"permute_profile \\<sigma> R\"\n    by (rule wf_permute_alts)\n  have \"anonymous_profile (permute_profile \\<sigma> R) = \n          {#weak_ranking (map_relation (inv \\<sigma>) (R x)). x \\<in># mset_set agents#}\"\n    unfolding R'.anonymous_profile_def\n    by (simp add:  multiset.map_comp permute_profile_map_relation o_def)\n  also from assms have \"\\<dots> = {#map (op ` \\<sigma>) (weak_ranking (R x)). x \\<in># mset_set agents#}\"\n    by (intro image_mset_cong)\n       (simp add: finite_total_preorder_on.weak_ranking_permute[of alts])\n  also have \"\\<dots> = image_mset (map (op ` \\<sigma>)) (anonymous_profile R)\"\n    by (simp add: anonymous_profile_def multiset.map_comp o_def)\n  finally show ?thesis .\nqed\n\nlemma (in pref_profile_wf) anonymous_profile_update:\n  assumes i:  \"i \\<in> agents\" and fin [simp]: \"finite agents\" and \"total_preorder_on alts Ri'\"\n  shows   \"anonymous_profile (R(i := Ri')) =\n             anonymous_profile R - {#weak_ranking (R i)#} + {#weak_ranking Ri'#}\"\nproof -\n  from assms interpret R': pref_profile_wf agents alts \"R(i := Ri')\"\n    by (simp add: finite_total_preorder_on_iff wf_update)\n  have \"anonymous_profile (R(i := Ri')) = \n          {#weak_ranking (if x = i then Ri' else R x). x \\<in># mset_set agents#}\"\n    by (simp add: R'.anonymous_profile_def o_def)\n  also have \"\\<dots> = {#if x = i then weak_ranking Ri' else weak_ranking (R x). x \\<in># mset_set agents#}\"\n    by (intro image_mset_cong) simp_all\n  also have \"\\<dots> = {#weak_ranking Ri'. x \\<in># mset_set {x \\<in> agents. x = i}#} +\n                    {#weak_ranking (R x). x \\<in># mset_set {x \\<in> agents. x \\<noteq> i}#}\"\n    by (subst image_mset_If) ((subst filter_mset_mset_set, simp)+, rule refl)\n  also from i have \"{x \\<in> agents. x = i} = {i}\" by auto\n  also have \"{x \\<in> agents. x \\<noteq> i} = agents - {i}\" by auto\n  also have \"{#weak_ranking Ri'. x \\<in># mset_set {i}#} = {#weak_ranking Ri'#}\" by simp\n  also from i have \"mset_set (agents - {i}) = mset_set agents - {#i#}\"\n    by (simp add: mset_set_Diff)\n  also from i \n    have \"{#weak_ranking (R x). x \\<in># \\<dots>#} =\n            {#weak_ranking (R x). x \\<in># mset_set agents#} - {#weak_ranking (R i)#}\"\n      by (subst image_mset_Diff) (simp_all add: in_multiset_in_set mset_le_single)\n  also have \"{#weak_ranking Ri'#} + \\<dots> = \n               anonymous_profile R - {#weak_ranking (R i)#} + {#weak_ranking Ri'#}\"\n    by (simp add: anonymous_profile_def add_ac o_def)\n  finally show ?thesis .\nqed\n\n\nsubsection \\<open>Preference profiles from lists\\<close>\n\ndefinition prefs_from_table :: \"('agent \\<times> 'alt set list) list \\<Rightarrow> ('agent, 'alt) pref_profile\" where\n  \"prefs_from_table xss = (\\<lambda>i. case_option (\\<lambda>_ _. False) of_weak_ranking (map_of xss i))\"\n\ndefinition prefs_from_table_wf where\n  \"prefs_from_table_wf agents alts xss \\<longleftrightarrow> agents \\<noteq> {} \\<and> alts \\<noteq> {} \\<and> distinct (map fst xss) \\<and> \n       set (map fst xss) = agents \\<and> (\\<forall>xs\\<in>set (map snd xss). (\\<Union>set xs) = alts \\<and> \n       is_finite_weak_ranking xs)\"\n\nlemma prefs_from_table_wfI:\n  assumes \"agents \\<noteq> {}\" \"alts \\<noteq> {}\" \"distinct (map fst xss)\"\n  assumes \"set (map fst xss) = agents\"\n  assumes \"\\<And>xs. xs \\<in> set (map snd xss) \\<Longrightarrow> (\\<Union>set xs) = alts\"\n  assumes \"\\<And>xs. xs \\<in> set (map snd xss) \\<Longrightarrow> is_finite_weak_ranking xs\"\n  shows   \"prefs_from_table_wf agents alts xss\"\n  using assms unfolding prefs_from_table_wf_def by auto\n\nlemma prefs_from_table_wfD:\n  assumes \"prefs_from_table_wf agents alts xss\"\n  shows \"agents \\<noteq> {}\" \"alts \\<noteq> {}\" \"distinct (map fst xss)\"\n    and \"set (map fst xss) = agents\"\n    and \"\\<And>xs. xs \\<in> set (map snd xss) \\<Longrightarrow> (\\<Union>set xs) = alts\"\n    and \"\\<And>xs. xs \\<in> set (map snd xss) \\<Longrightarrow> is_finite_weak_ranking xs\"\n  using assms unfolding prefs_from_table_wf_def by auto\n       \nlemma pref_profile_from_tableI: \n  \"prefs_from_table_wf agents alts xss \\<Longrightarrow> pref_profile_wf agents alts (prefs_from_table xss)\"\nusing assms\nproof (intro pref_profile_wf.intro)\n  assume wf: \"prefs_from_table_wf agents alts xss\"\n  fix i assume i: \"i \\<in> agents\"\n  with wf have \"i \\<in> set (map fst xss)\" by (simp add: prefs_from_table_wf_def)\n  then obtain xs where xs: \"xs \\<in> set (map snd xss)\" \"prefs_from_table xss i = of_weak_ranking xs\"\n    by (cases \"map_of xss i\")\n       (fastforce dest: map_of_SomeD simp: prefs_from_table_def map_of_eq_None_iff)+\n  with wf show \"finite_total_preorder_on alts (prefs_from_table xss i)\"\n    by (auto simp: prefs_from_table_wf_def intro!: finite_total_preorder_of_weak_ranking)\nnext\n  assume wf: \"prefs_from_table_wf agents alts xss\"\n  fix i x y assume i: \"i \\<notin> agents\"\n  with wf have \"i \\<notin> set (map fst xss)\" by (simp add: prefs_from_table_wf_def)\n  hence \"map_of xss i = None\" by (simp add: map_of_eq_None_iff)\n  thus \"\\<not>prefs_from_table xss i x y\" by (simp add: prefs_from_table_def)\nqed (simp_all add: prefs_from_table_wf_def)\n\nlemma prefs_from_table_eqI:\n  assumes \"distinct (map fst xs)\" \"distinct (map fst ys)\" \"set xs = set ys\"\n  shows   \"prefs_from_table xs = prefs_from_table ys\"\nproof -\n  from assms have \"map_of xs = map_of ys\" by (subst map_of_inject_set) simp_all\n  thus ?thesis by (simp add: prefs_from_table_def)\nqed\n\nlemma prefs_from_table_undef:\n  assumes \"prefs_from_table_wf agents alts xss\" \"i \\<notin> agents\"\n  shows   \"prefs_from_table xss i = (\\<lambda>_ _. False)\"\nproof -\n  from assms have \"i \\<notin> fst ` set xss\"\n    by (simp add: prefs_from_table_wf_def)\n  hence \"map_of xss i = None\" by (simp add: map_of_eq_None_iff)\n  thus ?thesis by (simp add: prefs_from_table_def)\nqed\n\nlemma prefs_from_table_map_of:\n  assumes \"prefs_from_table_wf agents alts xss\" \"i \\<in> agents\"\n  shows   \"prefs_from_table xss i = of_weak_ranking (the (map_of xss i))\"\n  using assms \n  by (auto simp: prefs_from_table_def map_of_eq_None_iff prefs_from_table_wf_def\n           split: option.splits)\n\nlemma prefs_from_table_update:\n  fixes x xs\n  assumes \"i \\<in> set (map fst xs)\"\n  defines \"xs' \\<equiv> map (\\<lambda>(j,y). if j = i then (j, x) else (j, y)) xs\"\n  shows   \"(prefs_from_table xs)(i := of_weak_ranking x) =\n             prefs_from_table xs'\" (is \"?lhs = ?rhs\")\nproof\n  have xs': \"set (map fst xs') = set (map fst xs)\" by (force simp: xs'_def)  \n  fix k\n  consider \"k = i\" | \"k \\<notin> set (map fst xs)\" | \"k \\<noteq> i\" \"k \\<in> set (map fst xs)\" by blast\n  thus \"?lhs k = ?rhs k\"\n  proof cases \n    assume k: \"k = i\"\n    moreover from k have \"y = x\" if \"(i, y) \\<in> set xs'\" for y\n      using that by (auto simp: xs'_def split: if_splits)\n    ultimately show ?thesis using assms(1) k xs'\n      by (auto simp add: prefs_from_table_def map_of_eq_None_iff \n               dest!: map_of_SomeD split: option.splits)\n  next\n    assume k: \"k \\<notin> set (map fst xs)\"\n    with assms(1) have k': \"k \\<noteq> i\" by auto\n    with k xs' have \"map_of xs k = None\" \"map_of xs' k = None\"\n      by (simp_all add: map_of_eq_None_iff)\n    thus ?thesis by (simp add: prefs_from_table_def k')\n  next\n    assume k: \"k \\<noteq> i\" \"k \\<in> set (map fst xs)\"\n    with k(1) have \"map_of xs k = map_of xs' k\" unfolding xs'_def\n      by (induction xs) fastforce+\n    with k show ?thesis by (simp add: prefs_from_table_def)\n  qed\nqed\n\nlemma prefs_from_table_swap:\n  \"x \\<noteq> y \\<Longrightarrow> prefs_from_table ((x,x')#(y,y')#xs) = prefs_from_table ((y,y')#(x,x')#xs)\"\n  by (intro ext) (auto simp: prefs_from_table_def)\n\nlemma permute_prefs_from_table:\n  assumes \"\\<sigma> permutes fst ` set xs\"\n  shows   \"prefs_from_table xs \\<circ> \\<sigma> = prefs_from_table (map (\\<lambda>(x,y). (inv \\<sigma> x, y)) xs)\"\nproof\n  fix i\n  have \"(prefs_from_table xs \\<circ> \\<sigma>) i = \n          (case map_of xs (\\<sigma> i) of\n             None \\<Rightarrow> \\<lambda>_ _. False\n           | Some x \\<Rightarrow> of_weak_ranking x)\"\n    by (simp add: prefs_from_table_def o_def)\n  also have \"map_of xs (\\<sigma> i) = map_of (map (\\<lambda>(x,y). (inv \\<sigma> x, y)) xs) i\"\n    using map_of_permute[OF assms] by (simp add: o_def fun_eq_iff)\n  finally show \"(prefs_from_table xs \\<circ> \\<sigma>) i = prefs_from_table (map (\\<lambda>(x,y). (inv \\<sigma> x, y)) xs) i\"\n    by (simp only: prefs_from_table_def)\nqed\n\nlemma permute_profile_from_table:\n  assumes wf: \"prefs_from_table_wf agents alts xss\"\n  assumes perm: \"\\<sigma> permutes alts\"\n  shows   \"permute_profile \\<sigma> (prefs_from_table xss) = \n             prefs_from_table (map (\\<lambda>(x,y). (x, map (op ` \\<sigma>) y)) xss)\" (is \"?f = ?g\")\nproof\n  fix i\n  have wf': \"prefs_from_table_wf agents alts (map (\\<lambda>(x, y). (x, map (op ` \\<sigma>) y)) xss)\"\n  proof (intro prefs_from_table_wfI, goal_cases)\n    case (5 xs)\n    then obtain y where \"y \\<in> set xss\" \"xs = map (op ` \\<sigma>) (snd y)\"\n      by (auto simp add: o_def case_prod_unfold)\n    with assms show ?case\n      by (simp add: image_Union [symmetric] prefs_from_table_wf_def permutes_image o_def case_prod_unfold)\n  next\n    case (6 xs)\n    then obtain y where \"y \\<in> set xss\" \"xs = map (op ` \\<sigma>) (snd y)\"\n      by (auto simp add: o_def case_prod_unfold)\n    with assms show ?case\n      by (auto simp: is_finite_weak_ranking_def is_weak_ranking_iff prefs_from_table_wf_def\n            distinct_map permutes_inj_on inj_on_image intro!: disjoint_image)\n  qed (insert assms, simp_all add: image_Union [symmetric] prefs_from_table_wf_def permutes_image o_def case_prod_unfold)\n  show \"?f i = ?g i\"\n  proof (cases \"i \\<in> agents\")\n    assume \"i \\<notin> agents\"\n    with assms wf' show ?thesis\n      by (simp add: permute_profile_def prefs_from_table_undef)\n  next\n    assume i: \"i \\<in> agents\"\n    def xs \\<equiv> \"the (map_of xss i)\"\n    from i wf have xs: \"map_of xss i = Some xs\"\n      by (cases \"map_of xss i\") (auto simp: prefs_from_table_wf_def xs_def)\n    have xs_in_xss: \"xs \\<in> snd ` set xss\"\n      using xs by (force dest!: map_of_SomeD)\n    with wf have set_xs: \"\\<Union>set xs = alts\"\n      by (simp add: prefs_from_table_wfD)\n\n    from i have \"prefs_from_table (map (\\<lambda>(x,y). (x, map (op ` \\<sigma>) y)) xss) i =\n                   of_weak_ranking (the (map_of (map (\\<lambda>(x,y). (x, map (op ` \\<sigma>) y)) xss) i))\"\n      using wf' by (intro prefs_from_table_map_of) simp_all\n    also have \"\\<dots> = of_weak_ranking (map (op ` \\<sigma>) xs)\"\n      by (subst map_of_map) (simp add: xs)\n    also have \"\\<dots> = (\\<lambda>a b. of_weak_ranking xs (inv \\<sigma> a) (inv \\<sigma> b))\"\n      by (intro ext) (simp add: of_weak_ranking_permute map_relation_def set_xs perm)\n    also have \"\\<dots> = permute_profile \\<sigma> (prefs_from_table xss) i\"\n      by (simp add: prefs_from_table_def xs permute_profile_def)\n    finally show ?thesis ..\n  qed\nqed\n\n\nsubsection \\<open>Automatic evaluation of preference profiles\\<close>\n\nlemma eval_prefs_from_table [simp]:\n  \"prefs_from_table []i = (\\<lambda>_ _. False)\"\n  \"prefs_from_table ((i, y) # xs) i = of_weak_ranking y\"\n  \"i \\<noteq> j \\<Longrightarrow> prefs_from_table ((j, y) # xs) i = prefs_from_table xs i\"\n  by (simp_all add: prefs_from_table_def)\n\nlemma eval_of_weak_ranking [simp]:\n  \"a \\<notin> \\<Union>set xs \\<Longrightarrow> \\<not>of_weak_ranking xs a b\"\n  \"b \\<in> x \\<Longrightarrow> a \\<in> \\<Union>set (x#xs) \\<Longrightarrow> of_weak_ranking (x # xs) a b\"\n  \"b \\<notin> x \\<Longrightarrow> of_weak_ranking (x # xs) a b \\<longleftrightarrow> of_weak_ranking xs a b\"\n  by (induction xs) (simp_all add: of_weak_ranking_Cons)\n\nlemma prefs_from_table_cong [cong]:\n  assumes \"prefs_from_table xs = prefs_from_table ys\"\n  shows   \"prefs_from_table (x#xs) = prefs_from_table (x#ys)\"\nproof\n  fix i\n  show \"prefs_from_table (x # xs) i = prefs_from_table (x # ys) i\"\n    using assms by (cases x, cases \"i = fst x\") simp_all\nqed\n\ndefinition of_weak_ranking_Collect_ge where\n  \"of_weak_ranking_Collect_ge xs x = {y. of_weak_ranking xs y x}\"\n\n\n\nlemma of_weak_ranking_Collect_ge_empty [simp]:\n  \"of_weak_ranking_Collect_ge [] x = {}\"\n  by (simp add: of_weak_ranking_Collect_ge_def)\n\nlemma of_weak_ranking_Collect_ge_Cons [simp]:\n  \"y \\<in> x \\<Longrightarrow> of_weak_ranking_Collect_ge (x#xs) y = (\\<Union>set (x#xs))\"\n  \"y \\<notin> x \\<Longrightarrow> of_weak_ranking_Collect_ge (x#xs) y = of_weak_ranking_Collect_ge xs y\"\n  by (auto simp: of_weak_ranking_Cons of_weak_ranking_Collect_ge_def)\n\nlemma of_weak_ranking_Collect_ge_Cons':\n  \"of_weak_ranking_Collect_ge (x#xs) = (\\<lambda>y.\n     (if y \\<in> x then (\\<Union>set (x#xs)) else of_weak_ranking_Collect_ge xs y))\"\n  by (auto simp: of_weak_ranking_Cons of_weak_ranking_Collect_ge_def fun_eq_iff)\n\n(* TODO Move *)\nlemma mset_set_set: \"distinct xs \\<Longrightarrow> mset_set (set xs) = mset xs\"\n  by (induction xs) (simp_all add: add_ac)\n\nlemma image_mset_map_of: \n  \"distinct (map fst xs) \\<Longrightarrow> {#the (map_of xs i). i \\<in># mset (map fst xs)#} = mset (map snd xs)\"\nproof (induction xs)\n  case (Cons x xs)\n  have \"{#the (map_of (x # xs) i). i \\<in># mset (map fst (x # xs))#} = \n          {#the (if i = fst x then Some (snd x) else map_of xs i). \n             i \\<in># mset (map fst xs)#} + {#snd x#}\" (is \"_ = ?A + _\") by simp\n  also from Cons.prems have \"?A = {#the (map_of xs i). i :# mset (map fst xs)#}\"\n    by (cases x, intro image_mset_cong) (auto simp: in_multiset_in_set)\n  also from Cons.prems have \"\\<dots> = mset (map snd xs)\" by (intro Cons.IH) simp_all\n  finally show ?case by simp\nqed simp_all\n\nlemma anonymise_prefs_from_table:\n  assumes \"prefs_from_table_wf agents alts xs\"\n  shows   \"anonymous_profile (prefs_from_table xs) = mset (map snd xs)\"\nproof -\n  from assms interpret pref_profile_wf agents alts \"prefs_from_table xs\"\n    by (simp add: pref_profile_from_tableI) \n  from assms have agents: \"agents = fst ` set xs\"\n    by (simp add: prefs_from_table_wf_def)\n  hence [simp]: \"finite agents\" by auto\n  have \"anonymous_profile (prefs_from_table xs) = \n          {#weak_ranking (prefs_from_table xs x). x \\<in># mset_set agents#}\"\n    by (simp add: o_def anonymous_profile_def)\n  also from assms have \"\\<dots> = {#the (map_of xs i). i \\<in># mset_set agents#}\"\n  proof (intro image_mset_cong)\n    fix i assume i: \"i \\<in># mset_set agents\"\n    from i assms \n      have \"weak_ranking (prefs_from_table xs i) = \n              weak_ranking (of_weak_ranking (the (map_of xs i))) \"\n      by (simp add: prefs_from_table_map_of)\n    also from assms i have \"\\<dots> = the (map_of xs i)\"\n      by (intro weak_ranking_of_weak_ranking)\n         (auto simp: prefs_from_table_wf_def)\n    finally show \"weak_ranking (prefs_from_table xs i) = the (map_of xs i)\" .\n  qed\n  also from agents have \"mset_set agents = mset_set (set (map fst xs))\" by simp\n  also from assms have \"\\<dots> = mset (map fst xs)\"\n    by (intro mset_set_set) (simp_all add: prefs_from_table_wf_def)\n  also from assms have \"{#the (map_of xs i). i \\<in># mset (map fst xs)#} = mset (map snd xs)\"\n    by (intro image_mset_map_of) (simp_all add: prefs_from_table_wf_def)\n  finally show ?thesis .\nqed\n\nlemma prefs_from_table_agent_permutation:\n  assumes wf: \"prefs_from_table_wf agents alts xs\" \"prefs_from_table_wf agents alts ys\"\n  assumes mset_eq: \"mset (map snd xs) = mset (map snd ys)\"\n  obtains \\<pi> where \"\\<pi> permutes agents\" \"prefs_from_table xs \\<circ> \\<pi> = prefs_from_table ys\"\nproof -\n  from wf(1) have agents: \"agents = set (map fst xs)\"\n    by (simp_all add: prefs_from_table_wf_def)\n  from wf(2) have agents': \"agents = set (map fst ys)\"\n    by (simp_all add: prefs_from_table_wf_def)\n  from agents agents' wf(1) wf(2) have \"mset (map fst xs) = mset (map fst ys)\"\n    by (subst set_eq_iff_mset_eq_distinct [symmetric]) (simp_all add: prefs_from_table_wfD)\n  hence same_length: \"length xs = length ys\" by (auto dest: mset_eq_length)\n\n  from \\<open>mset (map fst xs) = mset (map fst ys)\\<close>\n    obtain g where g: \"g permutes {..<length ys}\" \"permute_list g (map fst ys) = map fst xs\"\n    by (auto elim: mset_eq_permutation simp: same_length)\n\n  from mset_eq g \n    have \"mset (map snd ys) = mset (permute_list g (map snd ys))\" by simp\n  with mset_eq obtain f \n    where f: \"f permutes {..<length xs}\" \n             \"permute_list f (permute_list g (map snd ys)) = map snd xs\"\n    by (auto elim: mset_eq_permutation simp: same_length)\n  from permutes_in_image[OF f(1)]\n    have [simp]: \"f x < length xs \\<longleftrightarrow> x < length xs\" \n                 \"f x < length ys \\<longleftrightarrow> x < length ys\" for x by (simp_all add: same_length)\n\n  def idx \\<equiv> \"index (map fst xs)\" and unidx \\<equiv> \"\\<lambda>i. map fst xs ! i\"\n  from wf(1) have \"bij_betw idx agents {0..<length xs}\" unfolding idx_def\n    by (intro bij_betw_index) (simp_all add: prefs_from_table_wf_def)\n  hence bij_betw_idx: \"bij_betw idx agents {..<length xs}\" by (simp add: atLeast0LessThan)\n  have [simp]: \"idx x < length xs\" if \"x \\<in> agents\" for x\n    using that by (simp add: idx_def agents)\n  have [simp]: \"unidx i \\<in> agents\" if \"i < length xs\" for i\n    using that by (simp add: agents unidx_def)\n\n  have unidx_idx: \"unidx (idx x) = x\" if x: \"x \\<in> agents\" for x\n    using x unfolding idx_def unidx_def using nth_index[of x \"map fst xs\"]\n    by (simp add: agents set_map [symmetric] nth_map [symmetric] del: set_map)\n  have idx_unidx: \"idx (unidx i) = i\" if i: \"i < length xs\" for i\n    unfolding idx_def unidx_def using wf(1) index_nth_id[of \"map fst xs\" i] i\n    by (simp add: prefs_from_table_wfD(3))\n \n  def \\<pi> \\<equiv> \"\\<lambda>x. if x \\<in> agents then (unidx \\<circ> f \\<circ> idx) x else x\"\n  def \\<pi>' \\<equiv> \"\\<lambda>x. if x \\<in> agents then (unidx \\<circ> inv f \\<circ> idx) x else x\"\n  have \"bij_betw (unidx \\<circ> f \\<circ> idx) agents agents\" (is \"?P\") unfolding unidx_def\n    by (rule bij_betw_trans bij_betw_idx permutes_imp_bij f g bij_betw_nth)+\n       (insert wf(1) g, simp_all add: prefs_from_table_wf_def same_length)\n  also have \"?P \\<longleftrightarrow> bij_betw \\<pi> agents agents\"\n    by (intro bij_betw_cong) (simp add: \\<pi>_def)\n  finally have perm: \"\\<pi> permutes agents\"\n    by (intro bij_imp_permutes) (simp_all add: \\<pi>_def)\n\n  def h \\<equiv> \"g \\<circ> f\"\n  from f g have h: \"h permutes {..<length ys}\" unfolding h_def\n    by (intro permutes_compose) (simp_all add: same_length)\n\n  have inv_\\<pi>: \"inv \\<pi> = \\<pi>'\"\n  proof (rule permutes_invI[OF perm])\n    fix x assume \"x \\<in> agents\"\n    with f(1) show \"\\<pi>' (\\<pi> x) = x\"\n      by (simp add: \\<pi>_def \\<pi>'_def idx_unidx unidx_idx inv_f_f permutes_inj)\n  qed (simp add: \\<pi>_def \\<pi>'_def)\n  with perm have inv_\\<pi>': \"inv \\<pi>' = \\<pi>\" by (auto simp: inv_inv_eq permutes_bij)\n\n  from wf h have \"prefs_from_table ys = prefs_from_table (permute_list h ys)\"\n    by (intro prefs_from_table_eqI)\n       (simp_all add: prefs_from_table_wfD permute_list_map [symmetric])\n  also have \"permute_list h ys = permute_list h (zip (map fst ys) (map snd ys))\"\n    by (simp add: zip_map_fst_snd)\n  also from same_length f g\n    have \"permute_list h (zip (map fst ys) (map snd ys)) = \n            zip (permute_list f (map fst xs)) (map snd xs)\"\n    by (subst permute_list_zip[OF h]) (simp_all add: h_def permute_list_compose)\n  also {\n    fix i assume i: \"i < length xs\"\n    from i have \"permute_list f (map fst xs) ! i = unidx (f i)\"\n      using permutes_in_image[OF f(1)] f(1) \n      by (subst permute_list_nth) (simp_all add: same_length unidx_def)\n    also from i have \"\\<dots> = \\<pi> (unidx i)\" by (simp add: \\<pi>_def idx_unidx)\n    also from i have \"\\<dots> = map \\<pi> (map fst xs) ! i\" by (simp add: unidx_def)\n    finally have \"permute_list f (map fst xs) ! i = map \\<pi> (map fst xs) ! i\" .\n  }\n  hence \"permute_list f (map fst xs) = map \\<pi> (map fst xs)\"\n    by (intro nth_equalityI) simp_all\n  also have \"zip (map \\<pi> (map fst xs)) (map snd xs) = map (\\<lambda>(x,y). (inv \\<pi>' x, y)) xs\"\n    by (induction xs) (simp_all add: case_prod_unfold inv_\\<pi>')\n  also from permutes_inv[OF perm] inv_\\<pi> have \"prefs_from_table \\<dots> = prefs_from_table xs \\<circ> \\<pi>'\"\n    by (intro permute_prefs_from_table [symmetric]) (simp_all add: agents)\n  finally have \"prefs_from_table xs \\<circ> \\<pi>' = prefs_from_table ys\" ..\n  with that[of \\<pi>'] permutes_inv[OF perm] inv_\\<pi> show ?thesis by auto\nqed\n\nlemma permute_list_distinct:\n  assumes \"f ` {..<length xs} \\<subseteq> {..<length xs}\" \"distinct xs\"\n  shows   \"permute_list f xs = map (\\<lambda>x. xs ! f (index xs x)) xs\"\n  using assms by (intro nth_equalityI) (auto simp: index_nth_id permute_list_def)\n\nlemma image_mset_eq_permutation:\n  assumes \"{#f x. x \\<in># mset_set A#} = {#g x. x \\<in># mset_set A#}\" \"finite A\"\n  obtains \\<pi> where \"\\<pi> permutes A\" \"\\<And>x. x \\<in> A \\<Longrightarrow> g (\\<pi> x) = f x\"\nproof -\n  from assms(2) obtain xs where xs: \"A = set xs\" \"distinct xs\"\n    using finite_distinct_list by blast\n  with assms have \"mset (map f xs) = mset (map g xs)\" \n    by (simp add: mset_set_set mset_map)\n  from mset_eq_permutation[OF this] obtain \\<pi> where\n    \\<pi>: \"\\<pi> permutes {0..<length xs}\" \"permute_list \\<pi> (map g xs) = map f xs\"\n    by (auto simp: atLeast0LessThan)\n  def \\<pi>' \\<equiv> \"\\<lambda>x. if x \\<in> A then (op ! xs \\<circ> \\<pi> \\<circ> index xs) x else x\"\n  have \"bij_betw (op ! xs \\<circ> \\<pi> \\<circ> index xs) A A\" (is \"?P\")\n    by (rule bij_betw_trans bij_betw_index xs refl permutes_imp_bij \\<pi> bij_betw_nth)+\n       (simp_all add: atLeast0LessThan xs)\n  also have \"?P \\<longleftrightarrow> bij_betw \\<pi>' A A\"\n    by (intro bij_betw_cong) (simp_all add: \\<pi>'_def)\n  finally have \"\\<pi>' permutes A\"\n    by (rule bij_imp_permutes) (simp_all add: \\<pi>'_def)\n  moreover from \\<pi> xs(1)[symmetric] xs(2) have \"g (\\<pi>' x) = f x\" if \"x \\<in> A\" for x\n    by (simp add: permute_list_map permute_list_distinct\n          permutes_image \\<pi>'_def that atLeast0LessThan)\n  ultimately show ?thesis by (rule that)\nqed\n\nlemma anonymous_profile_agent_permutation:\n  assumes eq:  \"anonymous_profile R1 = anonymous_profile R2\"\n  assumes wf:  \"pref_profile_wf agents alts R1\" \"pref_profile_wf agents alts R2\"\n  assumes fin: \"finite agents\"\n  obtains \\<pi> where \"\\<pi> permutes agents\" \"R2 \\<circ> \\<pi> = R1\"\nproof -\n  interpret R1: pref_profile_wf agents alts R1 by fact\n  interpret R2: pref_profile_wf agents alts R2 by fact\n\n  from eq have \"{#weak_ranking (R1 x). x \\<in># mset_set agents#} = \n                  {#weak_ranking (R2 x). x \\<in># mset_set agents#}\"\n    by (simp add: R1.anonymous_profile_def R2.anonymous_profile_def o_def)\n  from image_mset_eq_permutation[OF this fin] guess \\<pi> . note \\<pi> = this\n  from \\<pi> have wf': \"pref_profile_wf agents alts (R2 \\<circ> \\<pi>)\"\n    by (intro R2.wf_permute_agents)\n  then interpret R2': pref_profile_wf agents alts \"R2 \\<circ> \\<pi>\" .\n  have \"R2 \\<circ> \\<pi> = R1\"\n  proof (intro pref_profile_eqI[OF wf' wf(1)])\n    fix x assume x: \"x \\<in> agents\"\n    with \\<pi> have \"weak_ranking ((R2 o \\<pi>) x) = weak_ranking (R1 x)\" by simp\n    with wf' wf(1) x show \"(R2 \\<circ> \\<pi>) x = R1 x\"\n      by (intro weak_ranking_eqD[of alts] R2'.prefs_wf) simp_all\n  qed\n  from \\<pi>(1) and this show ?thesis by (rule that)\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/Preference_Profiles.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772450055544, "lm_q2_score": 0.8459424411924673, "lm_q1q2_score": 0.739419038430785}}
{"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\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\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  show \"x islimpt s\"\n  proof (rule islimptI)\n    fix t\n    assume t: \"x \\<in> t\" \"open t\"\n    show \"\\<exists>y\\<in>s. y \\<in> t \\<and> y \\<noteq> x\"\n    proof (cases \"x = a\")\n      case True\n      obtain y where \"y \\<in> insert a s\" \"y \\<in> t\" \"y \\<noteq> x\"\n        using * t by (rule islimptE)\n      with \\<open>x = a\\<close> show ?thesis by auto\n    next\n      case False\n      with t have t': \"x \\<in> t - {a}\" \"open (t - {a})\"\n        by (simp_all add: open_Diff)\n      obtain y where \"y \\<in> insert a s\" \"y \\<in> t - {a}\" \"y \\<noteq> x\"\n        using * t' by (rule islimptE)\n      then show ?thesis by auto\n    qed\n  qed\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\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 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\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\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\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": "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/Analysis/Elementary_Topology.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.84594244507642, "lm_q2_score": 0.8740772302445241, "lm_q1q2_score": 0.7394190293386776}}
{"text": "(*\n  File:     Miller_Rabin.thy\n  Authors:  Daniel St\u00fcwe\n\n  Some facts about Quadratic Residues that are missing from the library\n*)\nsection \\<open>Additional Material on Quadratic Residues\\<close>\ntheory QuadRes\nimports \n  Jacobi_Symbol\n  Algebraic_Auxiliaries\nbegin\n\ntext \\<open>Proofs are inspired by \\cite{Quadratic_Residues}.\\<close>\n\nlemma inj_on_QuadRes:\n  fixes p :: int\n  assumes \"prime p\"\n  shows \"inj_on (\\<lambda>x. x^2 mod p) {0..(p-1) div 2}\"\nproof \n  fix x y :: int\n  assume elem: \"x \\<in> {0..(p-1) div 2}\" \"y \\<in> {0..(p-1) div 2}\"\n\n  have * : \"abs(a) < p \\<Longrightarrow> p dvd a \\<Longrightarrow> a = 0\" for a :: int\n    using dvd_imp_le_int by force\n\n  assume \"x\\<^sup>2 mod p = y\\<^sup>2 mod p\"\n\n  hence \"[x\\<^sup>2 = y\\<^sup>2] (mod p)\" unfolding cong_def .\n\n  hence \"p dvd (x\\<^sup>2 - y\\<^sup>2)\" by (simp add: cong_iff_dvd_diff)\n\n  hence \"p dvd (x + y) * (x - y)\" \n    by (simp add: power2_eq_square square_diff_square_factored) \n  \n  hence \"p dvd (x + y) \\<or> p dvd (x - y)\"\n    using \\<open>prime p\\<close> by (simp add: prime_dvd_mult_iff) \n\n  moreover have \"p dvd x + y \\<Longrightarrow> x + y = 0\" \"p dvd x - y \\<Longrightarrow> x - y = 0\" \n           and \"0 \\<le> x\" \"0 \\<le> y\"\n      using elem  \n      by (fastforce intro!: * )+\n  \n  ultimately show \"x = y\" by auto\nqed\n\nlemma QuadRes_set_prime: \n  assumes \"prime p\" and \"odd p\"\n  shows \"{x . QuadRes p x \\<and> x \\<in> {0..<p}} = {x^2 mod p | x . x \\<in> {0..(p-1) div 2}}\"\nproof(safe, goal_cases)\n  case (1 x)\n  then obtain y where \"[y\\<^sup>2 = x] (mod p)\" \n    unfolding QuadRes_def by blast\n\n  then have A: \"[(y mod p)\\<^sup>2 = x] (mod p)\" \n    unfolding cong_def\n    by (simp add: power_mod)\n\n  then have \"[(-(y mod p))\\<^sup>2 = x] (mod p)\" \n    by simp\n\n  then have B: \"[(p - (y mod p))\\<^sup>2 = x] (mod p)\" \n    unfolding cong_def \n    using minus_mod_self1\n    by (metis power_mod)\n\n  have \"p = 1 + ((p - 1) div 2) * 2\"\n    using prime_gt_0_int[OF \\<open>prime p\\<close>] \\<open>odd p\\<close>\n    by simp\n\n  then have C: \"(p - (y mod p)) \\<in> {0..(p - 1) div 2} \\<or> y mod p \\<in> {0..(p - 1) div 2}\"\n    using prime_gt_0_int[OF \\<open>prime p\\<close>] \n    by (clarsimp, auto simp: le_less)\n\n  then show ?case proof\n    show ?thesis if \"p - y mod p \\<in> {0..(p - 1) div 2}\"\n      using that B\n      unfolding cong_def\n      using \\<open>x \\<in> {0..<p}\\<close> by auto\n\n    show ?thesis if \"y mod p \\<in> {0..(p - 1) div 2}\"\n      using that A\n      unfolding cong_def\n      using \\<open>x \\<in> {0..<p}\\<close> by auto\n  qed\nqed (auto simp: QuadRes_def cong_def)\n\ncorollary QuadRes_iff: \n  assumes \"prime p\" and \"odd p\"\n  shows \"(QuadRes p x \\<and> x \\<in> {0..<p}) \\<longleftrightarrow> (\\<exists> a \\<in> {0..(p-1) div 2}. a^2 mod p = x)\"\nproof -\n  have \"(QuadRes p x \\<and> x \\<in> {0..<p}) \\<longleftrightarrow> x \\<in> {x. QuadRes p x \\<and> x \\<in> {0..<p}}\"\n    by auto\n  also note QuadRes_set_prime[OF assms]\n  also have \"(x \\<in> {x\\<^sup>2 mod p |x. x \\<in> {0..(p - 1) div 2}}) = (\\<exists>a\\<in>{0..(p - 1) div 2}. a\\<^sup>2 mod p = x)\"\n    by blast\n  finally show ?thesis .\nqed\n\ncorollary card_QuadRes_set_prime:\n  fixes p :: int\n  assumes \"prime p\" and \"odd p\"\n  shows \"card {x. QuadRes p x \\<and> x \\<in> {0..<p}} = nat (p+1) div 2\"\nproof -\n  have \"card {x. QuadRes p x \\<and> x \\<in> {0..<p}} = card {x\\<^sup>2 mod p | x . x \\<in> {0..(p-1) div 2}}\"\n    unfolding QuadRes_set_prime[OF assms] ..\n\n  also have \"{x\\<^sup>2 mod p | x . x \\<in> {0..(p-1) div 2}} = (\\<lambda>x. x\\<^sup>2 mod p) ` {0..(p-1) div 2}\"\n    by auto\n\n  also have \"card ... = card {0..(p-1) div 2}\"\n    using inj_on_QuadRes[OF \\<open>prime p\\<close>] by (rule card_image)\n\n  also have \"... = nat (p+1) div 2\" by simp\n\n  finally show ?thesis .\nqed\n\ncorollary card_not_QuadRes_set_prime:\n  fixes p :: int\n  assumes \"prime p\" and \"odd p\"\n  shows \"card {x. \\<not>QuadRes p x \\<and> x \\<in> {0..<p}} = nat (p-1) div 2\"\nproof -\n  have \"{0..<p} \\<inter> {x. QuadRes p x \\<and> x \\<in> {0..<p}} = {x. QuadRes p x \\<and> x \\<in> {0..<p}}\"\n    by blast\n\n  moreover have \"nat p - nat (p + 1) div 2 = nat (p - 1) div 2\"\n    using \\<open>odd p\\<close> prime_gt_0_int[OF \\<open>prime p\\<close>]\n    by (auto elim!: oddE simp: nat_add_distrib nat_mult_distrib)\n\n  ultimately have \"card {0..<p} - card ({0..<p} \\<inter> {x. QuadRes p x \\<and> x \\<in> {0..<p}}) = nat (p - 1) div 2\"\n    using card_QuadRes_set_prime[OF assms] and card_atLeastZeroLessThan_int by presburger    \n\n  moreover have \"{x. \\<not>QuadRes p x \\<and> x \\<in> {0..<p}} = {0..<p} - {x. QuadRes p x \\<and> x \\<in> {0..<p}}\"\n    by blast\n\n  ultimately show ?thesis by (auto simp add: card_Diff_subset_Int)\nqed\n\nlemma not_QuadRes_ex_if_prime:\n  assumes \"prime p\" and \"odd p\"\n  shows \"\\<exists> x. \\<not>QuadRes p x\"\nproof -\n  have \"2 < p\" using odd_prime_gt_2_int assms by blast\n\n  then have False if \"{x . \\<not>QuadRes p x \\<and> x \\<in> {0..<p}} = {}\"\n    using card_not_QuadRes_set_prime[OF assms]\n    unfolding that\n    by simp\n\n  thus ?thesis by blast\nqed\n\nlemma not_QuadRes_ex:\n  \"1 < p \\<Longrightarrow> odd p \\<Longrightarrow> \\<exists>x. \\<not>QuadRes p x\"\nproof (induction p rule: prime_divisors_induct)\n  case (factor p x)\n  then show ?case \n    by (meson not_QuadRes_ex_if_prime QuadRes_def cong_iff_dvd_diff dvd_mult_left even_mult_iff)\nqed simp_all\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/Probabilistic_Prime_Tests/QuadRes.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8459424295406088, "lm_q2_score": 0.8740772417253256, "lm_q1q2_score": 0.739419025471276}}
{"text": "(******************************************************************************)\n(* Project: Isabelle/UTP: Unifying Theories of Programming in Isabelle/HOL    *)\n(* File: Sum_Order.thy                                                        *)\n(* Authors: Frank Zeyda and Simon Foster (University of York, UK)             *)\n(* Emails: frank.zeyda@gmail.com and simon.foster@york.ac.uk                  *)\n(******************************************************************************)\n(* LAST REVIEWED: 09 Jun 2022 *)\n\nsection \\<open>Sum Type Order\\<close>\n\ntheory Sum_Order\nimports Main\nbegin\n\nsubsection \\<open>Instantiation of @{class ord}\\<close>\n\ninstantiation sum :: (ord, ord) ord\nbegin\nfun less_eq_sum :: \"'a + 'b \\<Rightarrow> 'a + 'b \\<Rightarrow> bool\" where\n\"less_eq_sum (Inl x) (Inl y) \\<longleftrightarrow> x \\<le> y\" |\n\"less_eq_sum (Inr x) (Inr y) \\<longleftrightarrow> x \\<le> y\" |\n\"less_eq_sum (Inl x) (Inr y) \\<longleftrightarrow> False\" |\n\"less_eq_sum (Inr x) (Inl y) \\<longleftrightarrow> False\"\n\ndefinition less_sum :: \"'a + 'b \\<Rightarrow> 'a + 'b \\<Rightarrow> bool\" where\n\"less_sum x y \\<longleftrightarrow> (x \\<le> y) \\<and> x \\<noteq> y\"\ninstance by (intro_classes)\nend\n\nsubsection \\<open>Instantiation of @{class order}\\<close>\n\ninstantiation sum :: (order, order) order\nbegin\ntheorem less_le_not_le_sum :\nfixes x :: \"'a + 'b\"\nfixes y :: \"'a + 'b\"\nshows \"(x < y) = (x \\<le> y \\<and> \\<not> y \\<le> x)\"\napply (unfold less_sum_def)\napply (induct x; induct y)\napply (auto)\ndone\n\ntheorem order_refl_sum :\nfixes x :: \"'a + 'b\"\nshows \"x \\<le> x\"\napply (induct x)\napply (auto)\ndone\n\ntheorem order_trans_sum :\nfixes x :: \"'a + 'b\"\nfixes y :: \"'a + 'b\"\nfixes z :: \"'a + 'b\"\nshows \"x \\<le> y \\<Longrightarrow> y \\<le> z \\<Longrightarrow> x \\<le> z\"\napply (atomize (full))\napply (induct x; induct y; induct z)\napply (auto)\ndone\n\ntheorem antisym_sum :\nfixes x :: \"'a + 'b\"\nfixes y :: \"'a + 'b\"\nshows \"x \\<le> y \\<Longrightarrow> y \\<le> x \\<Longrightarrow> x = y\"\napply (atomize (full))\napply (induct x; induct y)\napply (auto)\ndone\n\ninstance\napply (intro_classes)\napply (metis less_le_not_le_sum)\napply (metis order_refl_sum)\napply (metis order_trans_sum)\napply (metis antisym_sum)\ndone\nend\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/axiomatic/theories/utils/Sum_Order.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045996818986, "lm_q2_score": 0.8333245911726382, "lm_q1q2_score": 0.7393294103164023}}
{"text": "(* Title:      Demonic refinement algebra\n   Author:     Alasdair Armstrong, Victor B. F. Gomes, Georg Struth\n   Maintainer: Georg Struth <g.struth at sheffield.ac.uk>\n               Tjark Weber <tjark.weber at it.uu.se>\n*)\n\nsection \\<open>Demonic Refinement Algebras\\<close>\n\ntheory DRA\n  imports Kleene_Algebra \nbegin\n\ntext \\<open>\n  A demonic refinement algebra *DRA)~\\cite{vonwright04refinement} is a Kleene algebra without right annihilation plus \n  an operation for possibly infinite iteration.\n\\<close>\nclass dra = kleene_algebra_zerol +\n  fixes strong_iteration :: \"'a \\<Rightarrow> 'a\" (\"_\\<^sup>\\<infinity>\" [101] 100)\n  assumes iteration_unfoldl [simp] : \"1 + x \\<cdot> x\\<^sup>\\<infinity> = x\\<^sup>\\<infinity>\"\n  and coinduction: \"y \\<le> z + x \\<cdot> y \\<longrightarrow> y \\<le> x\\<^sup>\\<infinity> \\<cdot> z\"\n  and isolation [simp]: \"x\\<^sup>\\<star> + x\\<^sup>\\<infinity> \\<cdot> 0 = x\\<^sup>\\<infinity>\"\nbegin\n\ntext \\<open>$\\top$ is an abort statement, defined as an infinite skip. It is the maximal element of any DRA.\\<close>\n\nabbreviation top_elem :: \"'a\" (\"\\<top>\") where \"\\<top> \\<equiv> 1\\<^sup>\\<infinity>\"\n\ntext \\<open>Simple/basic lemmas about the iteration operator\\<close>\n\nlemma iteration_refl: \"1 \\<le> x\\<^sup>\\<infinity>\"\n  using local.iteration_unfoldl local.order_prop by blast\n\nlemma iteration_1l: \"x \\<cdot> x\\<^sup>\\<infinity> \\<le> x\\<^sup>\\<infinity>\"\n  by (metis local.iteration_unfoldl local.join.sup.cobounded2)\n\nlemma top_ref: \"x \\<le> \\<top>\"\nproof -\n  have \"x \\<le> 1 + 1 \\<cdot> x\"\n    by simp\n  thus ?thesis\n    using local.coinduction by fastforce\nqed\n\nlemma it_ext: \"x \\<le> x\\<^sup>\\<infinity>\"\nproof -\n  have \"x \\<le> x \\<cdot> x\\<^sup>\\<infinity>\"\n    using iteration_refl local.mult_isol by fastforce\n  thus ?thesis\n    by (metis (full_types) local.isolation local.join.sup.coboundedI1 local.star_ext)\nqed\n\nlemma it_idem [simp]: \"(x\\<^sup>\\<infinity>)\\<^sup>\\<infinity> = x\\<^sup>\\<infinity>\"\n(*nitpick [expect=genuine]*)\noops\n\nlemma top_mult_annil [simp]: \"\\<top> \\<cdot> x = \\<top>\"\n  by (simp add: local.coinduction local.order.antisym top_ref)\n\nlemma top_add_annil [simp]: \"\\<top> + x = \\<top>\"\n  by (simp add: local.join.sup.absorb1 top_ref)\n\nlemma top_elim: \"x \\<cdot> y \\<le> x \\<cdot> \\<top>\"\n  by (simp add: local.mult_isol top_ref)\n\nlemma iteration_unfoldl_distl [simp]: \" y + y \\<cdot> x \\<cdot> x\\<^sup>\\<infinity> = y \\<cdot> x\\<^sup>\\<infinity>\"\n  by (metis distrib_left mult.assoc mult_oner iteration_unfoldl)\n\nlemma iteration_unfoldl_distr [simp]: \" y + x \\<cdot> x\\<^sup>\\<infinity> \\<cdot> y = x\\<^sup>\\<infinity> \\<cdot> y\"\n  by (metis distrib_right' mult_1_left iteration_unfoldl)\n\nlemma iteration_unfoldl' [simp]: \"z \\<cdot> y + z \\<cdot> x \\<cdot> x\\<^sup>\\<infinity> \\<cdot> y = z \\<cdot> x\\<^sup>\\<infinity> \\<cdot> y\"\n  by (metis iteration_unfoldl_distl local.distrib_right)\n\nlemma iteration_idem [simp]: \"x\\<^sup>\\<infinity> \\<cdot> x\\<^sup>\\<infinity> = x\\<^sup>\\<infinity>\"\nproof (rule antisym)\n  have \"x\\<^sup>\\<infinity> \\<cdot> x\\<^sup>\\<infinity> \\<le> 1 + x \\<cdot> x\\<^sup>\\<infinity> \\<cdot> x\\<^sup>\\<infinity>\"\n    by (metis add_assoc iteration_unfoldl_distr local.eq_refl local.iteration_unfoldl local.subdistl_eq mult_assoc)\n  thus \"x\\<^sup>\\<infinity> \\<cdot> x\\<^sup>\\<infinity> \\<le> x\\<^sup>\\<infinity>\"\n    using local.coinduction mult_assoc by fastforce\n  show \"x\\<^sup>\\<infinity> \\<le>  x\\<^sup>\\<infinity> \\<cdot> x\\<^sup>\\<infinity>\"\n    using local.coinduction by auto\nqed\n\nlemma iteration_induct: \"x \\<cdot> x\\<^sup>\\<infinity> \\<le> x\\<^sup>\\<infinity> \\<cdot> x\"\nproof -\n  have \"x + x \\<cdot> (x \\<cdot> x\\<^sup>\\<infinity>) = x \\<cdot> x\\<^sup>\\<infinity>\"\n    by (metis (no_types) local.distrib_left local.iteration_unfoldl local.mult_oner)\n  thus ?thesis\n    by (simp add: local.coinduction)\nqed\n\nlemma iteration_ref_star: \"x\\<^sup>\\<star> \\<le> x\\<^sup>\\<infinity>\"\n  by (simp add: local.star_inductl_one)\n\nlemma iteration_subdist: \"x\\<^sup>\\<infinity> \\<le> (x + y)\\<^sup>\\<infinity>\"\n  by (metis add_assoc' distrib_right' mult_oner coinduction join.sup_ge1 iteration_unfoldl)\n\nlemma iteration_iso: \"x \\<le> y \\<Longrightarrow> x\\<^sup>\\<infinity> \\<le> y\\<^sup>\\<infinity>\"\n  using iteration_subdist local.order_prop by auto\n \nlemma iteration_unfoldr [simp]: \"1 + x\\<^sup>\\<infinity> \\<cdot> x = x\\<^sup>\\<infinity>\"\n  by (metis add_0_left annil eq_refl isolation mult.assoc iteration_idem iteration_unfoldl iteration_unfoldl_distr star_denest star_one star_prod_unfold star_slide tc)\n\nlemma iteration_unfoldr_distl [simp]: \" y + y \\<cdot> x\\<^sup>\\<infinity> \\<cdot> x = y \\<cdot> x\\<^sup>\\<infinity>\"\n  by (metis distrib_left mult.assoc mult_oner iteration_unfoldr)\n\nlemma iteration_unfoldr_distr [simp]: \" y + x\\<^sup>\\<infinity> \\<cdot> x \\<cdot> y = x\\<^sup>\\<infinity> \\<cdot> y\"\n  by (metis iteration_unfoldl_distr iteration_unfoldr_distl)\n\nlemma iteration_unfold_eq: \"x\\<^sup>\\<infinity> \\<cdot> x = x \\<cdot> x\\<^sup>\\<infinity>\"\n  by (metis iteration_unfoldl_distr iteration_unfoldr_distl)\n  \nlemma iteration_unfoldr' [simp]: \"z \\<cdot> y + z \\<cdot> x\\<^sup>\\<infinity> \\<cdot> x \\<cdot> y = z \\<cdot> x\\<^sup>\\<infinity> \\<cdot> y\"\n  by (metis distrib_left mult.assoc iteration_unfoldr_distr)\n\nlemma iteration_double [simp]: \"(x\\<^sup>\\<infinity>)\\<^sup>\\<infinity> = \\<top>\"\n  by (simp add: iteration_iso iteration_refl local.eq_iff top_ref)\n\nlemma star_iteration [simp]: \"(x\\<^sup>\\<star>)\\<^sup>\\<infinity> = \\<top>\"\n  by (simp add: iteration_iso local.eq_iff top_ref)\n\nlemma iteration_star [simp]: \"(x\\<^sup>\\<infinity>)\\<^sup>\\<star> = x\\<^sup>\\<infinity>\"\n  by (metis (no_types) iteration_idem iteration_refl local.star_inductr_var_eq2 local.sup_id_star1)\n\nlemma iteration_star2 [simp]: \"x\\<^sup>\\<star> \\<cdot> x\\<^sup>\\<infinity> = x\\<^sup>\\<infinity>\"\nproof -\n  have f1: \"(x\\<^sup>\\<infinity>)\\<^sup>\\<star> \\<cdot> x\\<^sup>\\<star> = x\\<^sup>\\<infinity>\"\n    by (metis (no_types) it_ext iteration_induct iteration_star local.bubble_sort local.join.sup.absorb1)\n  have \"x\\<^sup>\\<infinity> = x\\<^sup>\\<infinity> \\<cdot> x\\<^sup>\\<infinity>\"\n    by simp\n  hence \"x\\<^sup>\\<star> \\<cdot> x\\<^sup>\\<infinity> = x\\<^sup>\\<star> \\<cdot> (x\\<^sup>\\<infinity>)\\<^sup>\\<star> \\<cdot> (x\\<^sup>\\<star> \\<cdot> (x\\<^sup>\\<infinity>)\\<^sup>\\<star>)\\<^sup>\\<star>\"\n    using f1 by (metis (no_types) iteration_star local.star_denest_var_4 mult_assoc)\n  thus ?thesis\n    using f1 by (metis (no_types) iteration_star local.star_denest_var_4 local.star_denest_var_8)\nqed\n\nlemma iteration_zero [simp]: \"0\\<^sup>\\<infinity> = 1\"\n  by (metis add_zeror annil iteration_unfoldl)\n\n\n\nlemma iteration_subdenest: \"x\\<^sup>\\<infinity> \\<cdot> y\\<^sup>\\<infinity> \\<le> (x + y)\\<^sup>\\<infinity>\"\n  by (metis add_commute iteration_idem iteration_subdist local.mult_isol_var)\n  \nlemma sup_id_top: \"1 \\<le> y \\<Longrightarrow> y \\<cdot> \\<top> = \\<top>\"\n  using local.eq_iff local.mult_isol_var top_ref by fastforce\n\nlemma iteration_top [simp]: \"x\\<^sup>\\<infinity> \\<cdot> \\<top> = \\<top>\"\n  by (simp add: iteration_refl sup_id_top)\n\ntext \\<open>Next, we prove some simulation laws for data refinement.\\<close>\n\nlemma iteration_sim: \"z \\<cdot> y \\<le> x \\<cdot> z \\<Longrightarrow> z \\<cdot> y\\<^sup>\\<infinity> \\<le> x\\<^sup>\\<infinity> \\<cdot> z\"\nproof -\n  assume assms: \"z \\<cdot> y \\<le> x \\<cdot> z\"\n  have \"z \\<cdot> y\\<^sup>\\<infinity> = z + z \\<cdot> y \\<cdot> y\\<^sup>\\<infinity>\"\n    by simp\n  also have \"... \\<le> z + x \\<cdot> z \\<cdot> y\\<^sup>\\<infinity>\"\n    by (metis assms add.commute add_iso mult_isor)\n  finally show \"z \\<cdot> y\\<^sup>\\<infinity> \\<le> x\\<^sup>\\<infinity> \\<cdot> z\"\n    by (simp add: local.coinduction mult_assoc)\nqed\n\ntext \\<open>Nitpick gives a counterexample to the dual simulation law.\\<close>\n\nlemma \"y \\<cdot> z \\<le> z \\<cdot> x \\<Longrightarrow> y\\<^sup>\\<infinity> \\<cdot> z \\<le> z \\<cdot> x\\<^sup>\\<infinity>\"\n(*nitpick [expect=genuine]*)\noops\n  \ntext \\<open>Next, we prove some sliding laws.\\<close>\n\nlemma iteration_slide_var: \"x \\<cdot> (y \\<cdot> x)\\<^sup>\\<infinity> \\<le> (x \\<cdot> y)\\<^sup>\\<infinity> \\<cdot> x\"\n  by (simp add: iteration_sim mult_assoc)\n\nlemma iteration_prod_unfold [simp]: \"1 + y \\<cdot> (x \\<cdot> y)\\<^sup>\\<infinity> \\<cdot> x = (y \\<cdot> x)\\<^sup>\\<infinity>\"\nproof (rule antisym)\n  have \"1 + y \\<cdot> (x \\<cdot> y)\\<^sup>\\<infinity> \\<cdot> x \\<le> 1 + (y \\<cdot> x)\\<^sup>\\<infinity> \\<cdot> y \\<cdot> x\"\n    using iteration_slide_var local.join.sup_mono local.mult_isor by blast\n  thus \"1 + y \\<cdot> (x \\<cdot> y)\\<^sup>\\<infinity> \\<cdot> x \\<le>  (y \\<cdot> x)\\<^sup>\\<infinity>\"\n    by (simp add: mult_assoc)\n  have \"(y \\<cdot> x)\\<^sup>\\<infinity> = 1 + y \\<cdot> x \\<cdot> (y \\<cdot> x)\\<^sup>\\<infinity>\"\n    by simp\n  thus \"(y \\<cdot> x)\\<^sup>\\<infinity> \\<le> 1 + y \\<cdot> (x \\<cdot> y)\\<^sup>\\<infinity> \\<cdot> x\"\n    by (metis iteration_sim local.eq_refl local.join.sup.mono local.mult_isol mult_assoc)\nqed\n\nlemma iteration_slide: \"x \\<cdot> (y \\<cdot> x)\\<^sup>\\<infinity> = (x \\<cdot> y)\\<^sup>\\<infinity> \\<cdot> x\"\n  by (metis iteration_prod_unfold iteration_unfoldl_distr distrib_left mult_1_right mult.assoc)\n\nlemma star_iteration_slide [simp]: \" y\\<^sup>\\<star> \\<cdot> (x\\<^sup>\\<star> \\<cdot> y)\\<^sup>\\<infinity> = (x\\<^sup>\\<star> \\<cdot> y)\\<^sup>\\<infinity>\"\n  by (metis iteration_star2 local.conway.dagger_unfoldl_distr local.join.sup.orderE local.mult_isor local.star_invol local.star_subdist local.star_trans_eq)\n\ntext \\<open>The following laws are called denesting laws.\\<close>\n\nlemma iteration_sub_denest: \"(x + y)\\<^sup>\\<infinity> \\<le> x\\<^sup>\\<infinity> \\<cdot> (y \\<cdot> x\\<^sup>\\<infinity>)\\<^sup>\\<infinity>\"\nproof -\n  have \"(x + y)\\<^sup>\\<infinity> = x \\<cdot> (x + y)\\<^sup>\\<infinity> + y \\<cdot> (x + y)\\<^sup>\\<infinity> + 1\"\n    by (metis add.commute distrib_right' iteration_unfoldl)\n  hence \"(x + y)\\<^sup>\\<infinity> \\<le> x\\<^sup>\\<infinity> \\<cdot> (y \\<cdot> (x + y)\\<^sup>\\<infinity> + 1)\"\n    by (metis add_assoc' join.sup_least join.sup_ge1 join.sup_ge2 coinduction)\n  moreover hence \"x\\<^sup>\\<infinity> \\<cdot> (y \\<cdot> (x + y)\\<^sup>\\<infinity> + 1) \\<le> x\\<^sup>\\<infinity> \\<cdot> (y \\<cdot> x\\<^sup>\\<infinity>)\\<^sup>\\<infinity>\"\n    by (metis add_iso mult.assoc mult_isol add.commute coinduction mult_oner mult_isol)\n  ultimately show ?thesis\n    using local.order_trans by blast\nqed\n\nlemma iteration_denest: \"(x + y)\\<^sup>\\<infinity> = x\\<^sup>\\<infinity> \\<cdot> (y \\<cdot> x\\<^sup>\\<infinity>)\\<^sup>\\<infinity>\"\nproof -\n  have \"x\\<^sup>\\<infinity> \\<cdot> (y \\<cdot> x\\<^sup>\\<infinity>)\\<^sup>\\<infinity> \\<le> x \\<cdot> x\\<^sup>\\<infinity> \\<cdot> (y \\<cdot> x\\<^sup>\\<infinity>)\\<^sup>\\<infinity> + y \\<cdot> x\\<^sup>\\<infinity> \\<cdot> (y \\<cdot> x\\<^sup>\\<infinity>)\\<^sup>\\<infinity> + 1\"\n    by (metis add.commute iteration_unfoldl_distr add_assoc' add.commute iteration_unfoldl order_refl)\n  thus ?thesis\n    by (metis add.commute iteration_sub_denest order.antisym coinduction distrib_right' iteration_sub_denest mult.assoc mult_oner order.antisym)\nqed\n(*\nend\n\nsublocale dra \\<subseteq> conway_zerol strong_iteration \n  apply (unfold_locales)\n  apply (simp add: iteration_denest iteration_slide)\n  apply simp\n  by (simp add: iteration_sim)\n\n\ncontext dra\nbegin\n*)\nlemma iteration_denest2 [simp]: \"y\\<^sup>\\<star> \\<cdot> x \\<cdot> (x + y)\\<^sup>\\<infinity> + y\\<^sup>\\<infinity> = (x + y)\\<^sup>\\<infinity>\"\nproof -\n  have \"(x + y)\\<^sup>\\<infinity> = y\\<^sup>\\<infinity> \\<cdot> x \\<cdot> (y\\<^sup>\\<infinity> \\<cdot> x)\\<^sup>\\<infinity> \\<cdot> y\\<^sup>\\<infinity> + y\\<^sup>\\<infinity>\"\n    by (metis add.commute iteration_denest iteration_slide iteration_unfoldl_distr)\n  also have \"... = y\\<^sup>\\<star> \\<cdot> x \\<cdot> (y\\<^sup>\\<infinity> \\<cdot> x)\\<^sup>\\<infinity> \\<cdot> y\\<^sup>\\<infinity> + y\\<^sup>\\<infinity> \\<cdot> 0 + y\\<^sup>\\<infinity>\"\n    by (metis isolation mult.assoc distrib_right' annil mult.assoc)\n  also have \"... = y\\<^sup>\\<star> \\<cdot> x \\<cdot> (y\\<^sup>\\<infinity> \\<cdot> x)\\<^sup>\\<infinity> \\<cdot> y\\<^sup>\\<infinity> + y\\<^sup>\\<infinity>\"\n    by (metis add.assoc distrib_left mult_1_right add_0_left mult_1_right)\n  finally show ?thesis\n    by (metis add.commute iteration_denest iteration_slide mult.assoc)\nqed\n\nlemma iteration_denest3: \"(y\\<^sup>\\<star> \\<cdot> x)\\<^sup>\\<infinity> \\<cdot> y\\<^sup>\\<infinity> = (x + y)\\<^sup>\\<infinity>\"\nproof (rule antisym)\n  have  \"(y\\<^sup>\\<star> \\<cdot> x)\\<^sup>\\<infinity> \\<cdot> y\\<^sup>\\<infinity> \\<le> (y\\<^sup>\\<infinity> \\<cdot> x)\\<^sup>\\<infinity> \\<cdot> y\\<^sup>\\<infinity>\"\n    by (simp add: iteration_iso iteration_ref_star local.mult_isor)\n  thus  \"(y\\<^sup>\\<star> \\<cdot> x)\\<^sup>\\<infinity> \\<cdot> y\\<^sup>\\<infinity> \\<le> (x + y)\\<^sup>\\<infinity>\"\n    by (metis iteration_denest iteration_slide local.join.sup_commute)\n  have \"(x + y)\\<^sup>\\<infinity> = y\\<^sup>\\<infinity> + y\\<^sup>\\<star> \\<cdot> x \\<cdot> (x + y)\\<^sup>\\<infinity>\"\n    by (metis iteration_denest2 local.join.sup_commute)\n  thus \"(x + y)\\<^sup>\\<infinity> \\<le> (y\\<^sup>\\<star> \\<cdot> x)\\<^sup>\\<infinity> \\<cdot> y\\<^sup>\\<infinity>\"\n    by (simp add: local.coinduction) \nqed\n\ntext \\<open>Now we prove separation laws for reasoning about distributed systems in the context of action systems.\\<close>\n\nlemma iteration_sep: \"y \\<cdot> x \\<le> x \\<cdot> y \\<Longrightarrow> (x + y)\\<^sup>\\<infinity> = x\\<^sup>\\<infinity> \\<cdot> y\\<^sup>\\<infinity>\"\nproof -\n  assume \"y \\<cdot> x \\<le> x \\<cdot> y\"\n  hence \"y\\<^sup>\\<star> \\<cdot> x \\<le> x\\<cdot>(x + y)\\<^sup>\\<star>\"\n    by (metis star_sim1 add.commute mult_isol order_trans star_subdist)\n  hence \"y\\<^sup>\\<star> \\<cdot> x \\<cdot> (x + y)\\<^sup>\\<infinity> + y\\<^sup>\\<infinity> \\<le> x \\<cdot> (x + y)\\<^sup>\\<infinity> + y\\<^sup>\\<infinity>\"\n    by (metis mult_isor mult.assoc iteration_star2 join.sup.mono eq_refl)\n  thus ?thesis\n    by (metis iteration_denest2 add.commute coinduction add.commute less_eq_def iteration_subdenest)\nqed\n\nlemma iteration_sim2: \"y \\<cdot> x \\<le> x \\<cdot> y \\<Longrightarrow> y\\<^sup>\\<infinity> \\<cdot> x\\<^sup>\\<infinity> \\<le> x\\<^sup>\\<infinity> \\<cdot> y\\<^sup>\\<infinity>\"\n  by (metis add.commute iteration_sep iteration_subdenest)\n\nlemma iteration_sep2: \"y \\<cdot> x \\<le> x \\<cdot> y\\<^sup>\\<star> \\<Longrightarrow> (x + y)\\<^sup>\\<infinity> = x\\<^sup>\\<infinity> \\<cdot> y\\<^sup>\\<infinity>\"\nproof - \n  assume \"y \\<cdot> x \\<le> x \\<cdot> y\\<^sup>\\<star>\"\n  hence \"y\\<^sup>\\<star> \\<cdot> (y\\<^sup>\\<star> \\<cdot> x)\\<^sup>\\<infinity> \\<cdot> y\\<^sup>\\<infinity> \\<le> x\\<^sup>\\<infinity> \\<cdot> y\\<^sup>\\<star> \\<cdot> y\\<^sup>\\<infinity>\"\n    by (metis mult.assoc mult_isor iteration_sim star_denest_var_2 star_sim1 star_slide_var star_trans_eq tc_eq)\n  moreover have \"x\\<^sup>\\<infinity> \\<cdot> y\\<^sup>\\<star> \\<cdot> y\\<^sup>\\<infinity> \\<le> x\\<^sup>\\<infinity> \\<cdot> y\\<^sup>\\<infinity>\"\n    by (metis eq_refl mult.assoc iteration_star2)\n  moreover have \"(y\\<^sup>\\<star> \\<cdot> x)\\<^sup>\\<infinity> \\<cdot> y\\<^sup>\\<infinity> \\<le> y\\<^sup>\\<star> \\<cdot> (y\\<^sup>\\<star> \\<cdot> x)\\<^sup>\\<infinity> \\<cdot> y\\<^sup>\\<infinity>\"\n    by (metis mult_isor mult_onel star_ref)\n  ultimately show ?thesis\n    by (metis antisym iteration_denest3 iteration_subdenest order_trans)\nqed\n\nlemma iteration_sep3: \"y \\<cdot> x \\<le> x \\<cdot> (x + y) \\<Longrightarrow> (x + y)\\<^sup>\\<infinity> = x\\<^sup>\\<infinity> \\<cdot> y\\<^sup>\\<infinity>\"\nproof -\n  assume \"y \\<cdot> x \\<le> x \\<cdot> (x + y)\"\n  hence \"y\\<^sup>\\<star> \\<cdot> x \\<le> x \\<cdot> (x + y)\\<^sup>\\<star>\"\n    by (metis star_sim1)\n  hence \"y\\<^sup>\\<star> \\<cdot> x \\<cdot> (x + y)\\<^sup>\\<infinity> + y\\<^sup>\\<infinity> \\<le> x \\<cdot> (x + y)\\<^sup>\\<star> \\<cdot> (x + y)\\<^sup>\\<infinity> + y\\<^sup>\\<infinity>\"\n    by (metis add_iso mult_isor)\n  hence \"(x + y)\\<^sup>\\<infinity> \\<le> x\\<^sup>\\<infinity> \\<cdot> y\\<^sup>\\<infinity>\"\n    by (metis mult.assoc iteration_denest2 iteration_star2 add.commute coinduction)\n  thus ?thesis\n    by (metis add.commute less_eq_def iteration_subdenest)\nqed\n\nlemma iteration_sep4: \"y \\<cdot> 0 = 0 \\<Longrightarrow> z \\<cdot> x = 0 \\<Longrightarrow> y \\<cdot> x \\<le> (x + z) \\<cdot> y\\<^sup>\\<star> \\<Longrightarrow> (x + y + z)\\<^sup>\\<infinity> = x\\<^sup>\\<infinity> \\<cdot> (y + z)\\<^sup>\\<infinity>\"\nproof -\n  assume assms: \"y \\<cdot> 0 = 0\" \"z \\<cdot> x = 0\" \"y \\<cdot> x \\<le> (x + z) \\<cdot> y\\<^sup>\\<star>\"\n  have \"y \\<cdot> y\\<^sup>\\<star> \\<cdot> z \\<le> y\\<^sup>\\<star> \\<cdot> z \\<cdot> y\\<^sup>\\<star>\"\n    by (metis mult_isor star_1l mult_oner order_trans star_plus_one subdistl)\n  have \"y\\<^sup>\\<star> \\<cdot> z \\<cdot> x \\<le> x \\<cdot> y\\<^sup>\\<star> \\<cdot> z\"\n    by (metis join.bot_least assms(1) assms(2) independence1 mult.assoc)\n  have \"y \\<cdot> (x + y\\<^sup>\\<star> \\<cdot> z) \\<le> (x + z) \\<cdot> y\\<^sup>\\<star> + y \\<cdot> y\\<^sup>\\<star> \\<cdot> z\"\n    by (metis assms(3) distrib_left mult.assoc add_iso)\n  also have \"... \\<le> (x + y\\<^sup>\\<star> \\<cdot> z) \\<cdot> y\\<^sup>\\<star> + y \\<cdot> y\\<^sup>\\<star> \\<cdot> z\" \n    by (metis star_ref join.sup.mono eq_refl mult_1_left mult_isor)\n  also have \"... \\<le> (x + y\\<^sup>\\<star> \\<cdot> z) \\<cdot> y\\<^sup>\\<star> + y\\<^sup>\\<star> \\<cdot> z  \\<cdot> y\\<^sup>\\<star>\" using \\<open>y \\<cdot> y\\<^sup>\\<star> \\<cdot> z \\<le> y\\<^sup>\\<star> \\<cdot> z \\<cdot> y\\<^sup>\\<star>\\<close>\n    by (metis add.commute add_iso)\n  finally have \"y \\<cdot> (x + y\\<^sup>\\<star> \\<cdot> z) \\<le> (x + y\\<^sup>\\<star> \\<cdot> z) \\<cdot> y\\<^sup>\\<star>\"\n    by (metis add.commute add_idem' add.left_commute distrib_right)\n  moreover have \"(x + y + z)\\<^sup>\\<infinity> \\<le> (x + y + y\\<^sup>\\<star> \\<cdot> z)\\<^sup>\\<infinity>\"\n    by (metis star_ref join.sup.mono eq_refl mult_1_left mult_isor iteration_iso)  \n  moreover have \"... = (x + y\\<^sup>\\<star> \\<cdot> z)\\<^sup>\\<infinity> \\<cdot> y\\<^sup>\\<infinity>\"\n    by (metis add_commute calculation(1) iteration_sep2 local.add_left_comm)\n  moreover have \"... = x\\<^sup>\\<infinity> \\<cdot> (y\\<^sup>\\<star> \\<cdot> z)\\<^sup>\\<infinity> \\<cdot> y\\<^sup>\\<infinity>\" using \\<open>y\\<^sup>\\<star> \\<cdot> z \\<cdot> x \\<le> x \\<cdot> y\\<^sup>\\<star> \\<cdot> z\\<close>\n    by (metis iteration_sep mult.assoc)\n  ultimately have \"(x + y + z)\\<^sup>\\<infinity> \\<le> x\\<^sup>\\<infinity> \\<cdot> (y + z)\\<^sup>\\<infinity>\"\n    by (metis add.commute mult.assoc iteration_denest3)\n  thus ?thesis\n    by (metis add.commute add.left_commute less_eq_def iteration_subdenest)\nqed\n\ntext \\<open>Finally, we prove some blocking laws.\\<close>\n\ntext \\<open>Nitpick refutes the next lemma.\\<close>\n\nlemma \"x \\<cdot> y = 0 \\<Longrightarrow> x\\<^sup>\\<infinity> \\<cdot> y = y\"\n(*nitpick*)\noops\n\nlemma iteration_idep: \"x \\<cdot> y = 0 \\<Longrightarrow> x \\<cdot> y\\<^sup>\\<infinity> = x\"\n  by (metis add_zeror annil iteration_unfoldl_distl)\n\ntext \\<open>Nitpick refutes the next lemma.\\<close>\n\nlemma \"y \\<cdot> w \\<le> x \\<cdot> y + z \\<Longrightarrow> y \\<cdot> w\\<^sup>\\<infinity> \\<le> x\\<^sup>\\<infinity> \\<cdot> z\"\n(*nitpick [expect=genuine]*)\noops\n\ntext \\<open>At the end of this file, we consider a data refinement example from von Wright~\\cite{Wright02}.\\<close>\n\nlemma data_refinement:\n  assumes \"s' \\<le> s \\<cdot> z\" and \"z \\<cdot> e' \\<le> e\" and \"z \\<cdot> a' \\<le> a \\<cdot> z\" and \"z \\<cdot> b \\<le> z\" and \"b\\<^sup>\\<infinity> = b\\<^sup>\\<star>\"\n  shows \"s' \\<cdot> (a' + b)\\<^sup>\\<infinity> \\<cdot> e' \\<le> s \\<cdot> a\\<^sup>\\<infinity> \\<cdot> e\"\nproof -\n  have \"z \\<cdot> b\\<^sup>\\<star> \\<le> z\"\n    by (metis assms(4) star_inductr_var)\n  have \"(z \\<cdot> a') \\<cdot> b\\<^sup>\\<star> \\<le> (a \\<cdot> z) \\<cdot> b\\<^sup>\\<star>\"\n    by (metis assms(3) mult.assoc mult_isor)\n  hence \"z \\<cdot> (a' \\<cdot> b\\<^sup>\\<star>)\\<^sup>\\<infinity> \\<le>  a\\<^sup>\\<infinity> \\<cdot> z\" using \\<open>z \\<cdot> b\\<^sup>\\<star> \\<le> z\\<close>\n    by (metis mult.assoc mult_isol order_trans iteration_sim mult.assoc)\n  have \"s' \\<cdot> (a' + b)\\<^sup>\\<infinity> \\<cdot> e' \\<le> s' \\<cdot> b\\<^sup>\\<star> \\<cdot> (a' \\<cdot> b\\<^sup>\\<star>)\\<^sup>\\<infinity> \\<cdot> e'\"\n    by (metis add.commute assms(5) eq_refl iteration_denest mult.assoc)\n  also have \"... \\<le> s \\<cdot> z \\<cdot> b\\<^sup>\\<star> \\<cdot> (a' \\<cdot> b\\<^sup>\\<star>)\\<^sup>\\<infinity> \\<cdot> e'\"\n    by (metis assms(1) mult_isor)\n  also have \"... \\<le> s \\<cdot> z \\<cdot> (a' \\<cdot> b\\<^sup>\\<star>)\\<^sup>\\<infinity> \\<cdot> e'\" using \\<open>z \\<cdot> b\\<^sup>\\<star> \\<le> z\\<close>\n    by (metis mult.assoc mult_isol mult_isor)\n  also have \"... \\<le> s \\<cdot> a\\<^sup>\\<infinity> \\<cdot> z \\<cdot> e'\" using \\<open>z \\<cdot> (a' \\<cdot> b\\<^sup>\\<star>)\\<^sup>\\<infinity> \\<le>  a\\<^sup>\\<infinity> \\<cdot> z\\<close>\n    by (metis mult.assoc mult_isol mult_isor)\n  finally show ?thesis\n    by (metis assms(2) mult.assoc mult_isol mult.assoc mult_isol order_trans)\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/Kleene_Algebra/DRA.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8918110454379297, "lm_q2_score": 0.8289388125473628, "lm_q1q2_score": 0.7392567890219396}}
{"text": "(*  Title:      ZF/OrdQuant.thy\n    Authors:    Krzysztof Grabczewski and L C Paulson\n*)\n\nsection \\<open>Special quantifiers\\<close>\n\ntheory OrdQuant imports Ordinal begin\n\nsubsection \\<open>Quantifiers and union operator for ordinals\\<close>\n\ndefinition\n  (* Ordinal Quantifiers *)\n  oall :: \"[i, i \\<Rightarrow> o] \\<Rightarrow> o\"  where\n    \"oall(A, P) \\<equiv> \\<forall>x. x<A \\<longrightarrow> P(x)\"\n\ndefinition\n  oex :: \"[i, i \\<Rightarrow> o] \\<Rightarrow> o\"  where\n    \"oex(A, P)  \\<equiv> \\<exists>x. x<A \\<and> P(x)\"\n\ndefinition\n  (* Ordinal Union *)\n  OUnion :: \"[i, i \\<Rightarrow> i] \\<Rightarrow> i\"  where\n    \"OUnion(i,B) \\<equiv> {z: \\<Union>x\\<in>i. B(x). Ord(i)}\"\n\nsyntax\n  \"_oall\"     :: \"[idt, i, o] \\<Rightarrow> o\"        (\\<open>(3\\<forall>_<_./ _)\\<close> 10)\n  \"_oex\"      :: \"[idt, i, o] \\<Rightarrow> o\"        (\\<open>(3\\<exists>_<_./ _)\\<close> 10)\n  \"_OUNION\"   :: \"[idt, i, i] \\<Rightarrow> i\"        (\\<open>(3\\<Union>_<_./ _)\\<close> 10)\ntranslations\n  \"\\<forall>x<a. P\" \\<rightleftharpoons> \"CONST oall(a, \\<lambda>x. P)\"\n  \"\\<exists>x<a. P\" \\<rightleftharpoons> \"CONST oex(a, \\<lambda>x. P)\"\n  \"\\<Union>x<a. B\" \\<rightleftharpoons> \"CONST OUnion(a, \\<lambda>x. B)\"\n\n\nsubsubsection \\<open>simplification of the new quantifiers\\<close>\n\n\n(*MOST IMPORTANT that this is added to the simpset BEFORE Ord_atomize\n  is proved.  Ord_atomize would convert this rule to\n    x < 0 \\<Longrightarrow> P(x) \\<equiv> True, which causes dire effects!*)\n\n\nlemma [simp]: \"\\<not>(\\<exists>x<0. P(x))\"\nby (simp add: oex_def)\n\nlemma [simp]: \"(\\<forall>x<succ(i). P(x)) <-> (Ord(i) \\<longrightarrow> P(i) \\<and> (\\<forall>x<i. P(x)))\"\napply (simp add: oall_def le_iff)\napply (blast intro: lt_Ord2)\ndone\n\nlemma [simp]: \"(\\<exists>x<succ(i). P(x)) <-> (Ord(i) \\<and> (P(i) | (\\<exists>x<i. P(x))))\"\napply (simp add: oex_def le_iff)\napply (blast intro: lt_Ord2)\ndone\n\nsubsubsection \\<open>Union over ordinals\\<close>\n\nlemma Ord_OUN [intro,simp]:\n     \"\\<lbrakk>\\<And>x. x<A \\<Longrightarrow> Ord(B(x))\\<rbrakk> \\<Longrightarrow> Ord(\\<Union>x<A. B(x))\"\nby (simp add: OUnion_def ltI Ord_UN)\n\nlemma OUN_upper_lt:\n     \"\\<lbrakk>a<A;  i < b(a);  Ord(\\<Union>x<A. b(x))\\<rbrakk> \\<Longrightarrow> i < (\\<Union>x<A. b(x))\"\nby (unfold OUnion_def lt_def, blast )\n\nlemma OUN_upper_le:\n     \"\\<lbrakk>a<A;  i\\<le>b(a);  Ord(\\<Union>x<A. b(x))\\<rbrakk> \\<Longrightarrow> i \\<le> (\\<Union>x<A. b(x))\"\napply (unfold OUnion_def, auto)\napply (rule UN_upper_le )\napply (auto simp add: lt_def)\ndone\n\nlemma Limit_OUN_eq: \"Limit(i) \\<Longrightarrow> (\\<Union>x<i. x) = i\"\nby (simp add: OUnion_def Limit_Union_eq Limit_is_Ord)\n\n(* No < version of this theorem: consider that @{term\"(\\<Union>i\\<in>nat.i)=nat\"}! *)\nlemma OUN_least:\n     \"(\\<And>x. x<A \\<Longrightarrow> B(x) \\<subseteq> C) \\<Longrightarrow> (\\<Union>x<A. B(x)) \\<subseteq> C\"\nby (simp add: OUnion_def UN_least ltI)\n\nlemma OUN_least_le:\n     \"\\<lbrakk>Ord(i);  \\<And>x. x<A \\<Longrightarrow> b(x) \\<le> i\\<rbrakk> \\<Longrightarrow> (\\<Union>x<A. b(x)) \\<le> i\"\nby (simp add: OUnion_def UN_least_le ltI Ord_0_le)\n\nlemma le_implies_OUN_le_OUN:\n     \"\\<lbrakk>\\<And>x. x<A \\<Longrightarrow> c(x) \\<le> d(x)\\<rbrakk> \\<Longrightarrow> (\\<Union>x<A. c(x)) \\<le> (\\<Union>x<A. d(x))\"\nby (blast intro: OUN_least_le OUN_upper_le le_Ord2 Ord_OUN)\n\nlemma OUN_UN_eq:\n     \"(\\<And>x. x \\<in> A \\<Longrightarrow> Ord(B(x)))\n      \\<Longrightarrow> (\\<Union>z < (\\<Union>x\\<in>A. B(x)). C(z)) = (\\<Union>x\\<in>A. \\<Union>z < B(x). C(z))\"\nby (simp add: OUnion_def)\n\nlemma OUN_Union_eq:\n     \"(\\<And>x. x \\<in> X \\<Longrightarrow> Ord(x))\n      \\<Longrightarrow> (\\<Union>z < \\<Union>(X). C(z)) = (\\<Union>x\\<in>X. \\<Union>z < x. C(z))\"\nby (simp add: OUnion_def)\n\n(*So that rule_format will get rid of this quantifier...*)\nlemma atomize_oall [symmetric, rulify]:\n     \"(\\<And>x. x<A \\<Longrightarrow> P(x)) \\<equiv> Trueprop (\\<forall>x<A. P(x))\"\nby (simp add: oall_def atomize_all atomize_imp)\n\nsubsubsection \\<open>universal quantifier for ordinals\\<close>\n\nlemma oallI [intro!]:\n    \"\\<lbrakk>\\<And>x. x<A \\<Longrightarrow> P(x)\\<rbrakk> \\<Longrightarrow> \\<forall>x<A. P(x)\"\nby (simp add: oall_def)\n\nlemma ospec: \"\\<lbrakk>\\<forall>x<A. P(x);  x<A\\<rbrakk> \\<Longrightarrow> P(x)\"\nby (simp add: oall_def)\n\nlemma oallE:\n    \"\\<lbrakk>\\<forall>x<A. P(x);  P(x) \\<Longrightarrow> Q;  \\<not>x<A \\<Longrightarrow> Q\\<rbrakk> \\<Longrightarrow> Q\"\nby (simp add: oall_def, blast)\n\nlemma rev_oallE [elim]:\n    \"\\<lbrakk>\\<forall>x<A. P(x);  \\<not>x<A \\<Longrightarrow> Q;  P(x) \\<Longrightarrow> Q\\<rbrakk> \\<Longrightarrow> Q\"\nby (simp add: oall_def, blast)\n\n\n(*Trival rewrite rule.  @{term\"(\\<forall>x<a.P)<->P\"} holds only if a is not 0!*)\nlemma oall_simp [simp]: \"(\\<forall>x<a. True) <-> True\"\nby blast\n\n(*Congruence rule for rewriting*)\nlemma oall_cong [cong]:\n    \"\\<lbrakk>a=a';  \\<And>x. x<a' \\<Longrightarrow> P(x) <-> P'(x)\\<rbrakk>\n     \\<Longrightarrow> oall(a, \\<lambda>x. P(x)) <-> oall(a', \\<lambda>x. P'(x))\"\nby (simp add: oall_def)\n\n\nsubsubsection \\<open>existential quantifier for ordinals\\<close>\n\nlemma oexI [intro]:\n    \"\\<lbrakk>P(x);  x<A\\<rbrakk> \\<Longrightarrow> \\<exists>x<A. P(x)\"\napply (simp add: oex_def, blast)\ndone\n\n(*Not of the general form for such rules... *)\nlemma oexCI:\n   \"\\<lbrakk>\\<forall>x<A. \\<not>P(x) \\<Longrightarrow> P(a);  a<A\\<rbrakk> \\<Longrightarrow> \\<exists>x<A. P(x)\"\napply (simp add: oex_def, blast)\ndone\n\nlemma oexE [elim!]:\n    \"\\<lbrakk>\\<exists>x<A. P(x);  \\<And>x. \\<lbrakk>x<A; P(x)\\<rbrakk> \\<Longrightarrow> Q\\<rbrakk> \\<Longrightarrow> Q\"\napply (simp add: oex_def, blast)\ndone\n\nlemma oex_cong [cong]:\n    \"\\<lbrakk>a=a';  \\<And>x. x<a' \\<Longrightarrow> P(x) <-> P'(x)\\<rbrakk>\n     \\<Longrightarrow> oex(a, \\<lambda>x. P(x)) <-> oex(a', \\<lambda>x. P'(x))\"\napply (simp add: oex_def cong add: conj_cong)\ndone\n\n\nsubsubsection \\<open>Rules for Ordinal-Indexed Unions\\<close>\n\nlemma OUN_I [intro]: \"\\<lbrakk>a<i;  b \\<in> B(a)\\<rbrakk> \\<Longrightarrow> b: (\\<Union>z<i. B(z))\"\nby (unfold OUnion_def lt_def, blast)\n\nlemma OUN_E [elim!]:\n    \"\\<lbrakk>b \\<in> (\\<Union>z<i. B(z));  \\<And>a.\\<lbrakk>b \\<in> B(a);  a<i\\<rbrakk> \\<Longrightarrow> R\\<rbrakk> \\<Longrightarrow> R\"\napply (unfold OUnion_def lt_def, blast)\ndone\n\nlemma OUN_iff: \"b \\<in> (\\<Union>x<i. B(x)) <-> (\\<exists>x<i. b \\<in> B(x))\"\nby (unfold OUnion_def oex_def lt_def, blast)\n\nlemma OUN_cong [cong]:\n    \"\\<lbrakk>i=j;  \\<And>x. x<j \\<Longrightarrow> C(x)=D(x)\\<rbrakk> \\<Longrightarrow> (\\<Union>x<i. C(x)) = (\\<Union>x<j. D(x))\"\nby (simp add: OUnion_def lt_def OUN_iff)\n\nlemma lt_induct:\n    \"\\<lbrakk>i<k;  \\<And>x.\\<lbrakk>x<k;  \\<forall>y<x. P(y)\\<rbrakk> \\<Longrightarrow> P(x)\\<rbrakk>  \\<Longrightarrow>  P(i)\"\napply (simp add: lt_def oall_def)\napply (erule conjE)\napply (erule Ord_induct, assumption, blast)\ndone\n\n\nsubsection \\<open>Quantification over a class\\<close>\n\ndefinition\n  \"rall\"     :: \"[i\\<Rightarrow>o, i\\<Rightarrow>o] \\<Rightarrow> o\"  where\n    \"rall(M, P) \\<equiv> \\<forall>x. M(x) \\<longrightarrow> P(x)\"\n\ndefinition\n  \"rex\"      :: \"[i\\<Rightarrow>o, i\\<Rightarrow>o] \\<Rightarrow> o\"  where\n    \"rex(M, P) \\<equiv> \\<exists>x. M(x) \\<and> P(x)\"\n\nsyntax\n  \"_rall\"     :: \"[pttrn, i\\<Rightarrow>o, o] \\<Rightarrow> o\"        (\\<open>(3\\<forall>_[_]./ _)\\<close> 10)\n  \"_rex\"      :: \"[pttrn, i\\<Rightarrow>o, o] \\<Rightarrow> o\"        (\\<open>(3\\<exists>_[_]./ _)\\<close> 10)\ntranslations\n  \"\\<forall>x[M]. P\" \\<rightleftharpoons> \"CONST rall(M, \\<lambda>x. P)\"\n  \"\\<exists>x[M]. P\" \\<rightleftharpoons> \"CONST rex(M, \\<lambda>x. P)\"\n\n\nsubsubsection\\<open>Relativized universal quantifier\\<close>\n\nlemma rallI [intro!]: \"\\<lbrakk>\\<And>x. M(x) \\<Longrightarrow> P(x)\\<rbrakk> \\<Longrightarrow> \\<forall>x[M]. P(x)\"\nby (simp add: rall_def)\n\nlemma rspec: \"\\<lbrakk>\\<forall>x[M]. P(x); M(x)\\<rbrakk> \\<Longrightarrow> P(x)\"\nby (simp add: rall_def)\n\n(*Instantiates x first: better for automatic theorem proving?*)\nlemma rev_rallE [elim]:\n    \"\\<lbrakk>\\<forall>x[M]. P(x);  \\<not> M(x) \\<Longrightarrow> Q;  P(x) \\<Longrightarrow> Q\\<rbrakk> \\<Longrightarrow> Q\"\nby (simp add: rall_def, blast)\n\nlemma rallE: \"\\<lbrakk>\\<forall>x[M]. P(x);  P(x) \\<Longrightarrow> Q;  \\<not> M(x) \\<Longrightarrow> Q\\<rbrakk> \\<Longrightarrow> Q\"\nby blast\n\n(*Trival rewrite rule;   (\\<forall>x[M].P)<->P holds only if A is nonempty!*)\nlemma rall_triv [simp]: \"(\\<forall>x[M]. P) \\<longleftrightarrow> ((\\<exists>x. M(x)) \\<longrightarrow> P)\"\nby (simp add: rall_def)\n\n(*Congruence rule for rewriting*)\nlemma rall_cong [cong]:\n    \"(\\<And>x. M(x) \\<Longrightarrow> P(x) <-> P'(x)) \\<Longrightarrow> (\\<forall>x[M]. P(x)) <-> (\\<forall>x[M]. P'(x))\"\nby (simp add: rall_def)\n\n\nsubsubsection\\<open>Relativized existential quantifier\\<close>\n\nlemma rexI [intro]: \"\\<lbrakk>P(x); M(x)\\<rbrakk> \\<Longrightarrow> \\<exists>x[M]. P(x)\"\nby (simp add: rex_def, blast)\n\n(*The best argument order when there is only one M(x)*)\nlemma rev_rexI: \"\\<lbrakk>M(x);  P(x)\\<rbrakk> \\<Longrightarrow> \\<exists>x[M]. P(x)\"\nby blast\n\n(*Not of the general form for such rules... *)\nlemma rexCI: \"\\<lbrakk>\\<forall>x[M]. \\<not>P(x) \\<Longrightarrow> P(a); M(a)\\<rbrakk> \\<Longrightarrow> \\<exists>x[M]. P(x)\"\nby blast\n\nlemma rexE [elim!]: \"\\<lbrakk>\\<exists>x[M]. P(x);  \\<And>x. \\<lbrakk>M(x); P(x)\\<rbrakk> \\<Longrightarrow> Q\\<rbrakk> \\<Longrightarrow> Q\"\nby (simp add: rex_def, blast)\n\n(*We do not even have (\\<exists>x[M]. True) <-> True unless A is nonempty\\<And>*)\nlemma rex_triv [simp]: \"(\\<exists>x[M]. P) \\<longleftrightarrow> ((\\<exists>x. M(x)) \\<and> P)\"\nby (simp add: rex_def)\n\nlemma rex_cong [cong]:\n    \"(\\<And>x. M(x) \\<Longrightarrow> P(x) <-> P'(x)) \\<Longrightarrow> (\\<exists>x[M]. P(x)) <-> (\\<exists>x[M]. P'(x))\"\nby (simp add: rex_def cong: conj_cong)\n\nlemma rall_is_ball [simp]: \"(\\<forall>x[\\<lambda>z. z\\<in>A]. P(x)) <-> (\\<forall>x\\<in>A. P(x))\"\nby blast\n\nlemma rex_is_bex [simp]: \"(\\<exists>x[\\<lambda>z. z\\<in>A]. P(x)) <-> (\\<exists>x\\<in>A. P(x))\"\nby blast\n\nlemma atomize_rall: \"(\\<And>x. M(x) \\<Longrightarrow> P(x)) \\<equiv> Trueprop (\\<forall>x[M]. P(x))\"\nby (simp add: rall_def atomize_all atomize_imp)\n\ndeclare atomize_rall [symmetric, rulify]\n\nlemma rall_simps1:\n     \"(\\<forall>x[M]. P(x) \\<and> Q)   <-> (\\<forall>x[M]. P(x)) \\<and> ((\\<forall>x[M]. False) | Q)\"\n     \"(\\<forall>x[M]. P(x) | Q)   <-> ((\\<forall>x[M]. P(x)) | Q)\"\n     \"(\\<forall>x[M]. P(x) \\<longrightarrow> Q) <-> ((\\<exists>x[M]. P(x)) \\<longrightarrow> Q)\"\n     \"(\\<not>(\\<forall>x[M]. P(x))) <-> (\\<exists>x[M]. \\<not>P(x))\"\nby blast+\n\nlemma rall_simps2:\n     \"(\\<forall>x[M]. P \\<and> Q(x))   <-> ((\\<forall>x[M]. False) | P) \\<and> (\\<forall>x[M]. Q(x))\"\n     \"(\\<forall>x[M]. P | Q(x))   <-> (P | (\\<forall>x[M]. Q(x)))\"\n     \"(\\<forall>x[M]. P \\<longrightarrow> Q(x)) <-> (P \\<longrightarrow> (\\<forall>x[M]. Q(x)))\"\nby blast+\n\nlemmas rall_simps [simp] = rall_simps1 rall_simps2\n\nlemma rall_conj_distrib:\n    \"(\\<forall>x[M]. P(x) \\<and> Q(x)) <-> ((\\<forall>x[M]. P(x)) \\<and> (\\<forall>x[M]. Q(x)))\"\nby blast\n\nlemma rex_simps1:\n     \"(\\<exists>x[M]. P(x) \\<and> Q) <-> ((\\<exists>x[M]. P(x)) \\<and> Q)\"\n     \"(\\<exists>x[M]. P(x) | Q) <-> (\\<exists>x[M]. P(x)) | ((\\<exists>x[M]. True) \\<and> Q)\"\n     \"(\\<exists>x[M]. P(x) \\<longrightarrow> Q) <-> ((\\<forall>x[M]. P(x)) \\<longrightarrow> ((\\<exists>x[M]. True) \\<and> Q))\"\n     \"(\\<not>(\\<exists>x[M]. P(x))) <-> (\\<forall>x[M]. \\<not>P(x))\"\nby blast+\n\nlemma rex_simps2:\n     \"(\\<exists>x[M]. P \\<and> Q(x)) <-> (P \\<and> (\\<exists>x[M]. Q(x)))\"\n     \"(\\<exists>x[M]. P | Q(x)) <-> ((\\<exists>x[M]. True) \\<and> P) | (\\<exists>x[M]. Q(x))\"\n     \"(\\<exists>x[M]. P \\<longrightarrow> Q(x)) <-> (((\\<forall>x[M]. False) | P) \\<longrightarrow> (\\<exists>x[M]. Q(x)))\"\nby blast+\n\nlemmas rex_simps [simp] = rex_simps1 rex_simps2\n\nlemma rex_disj_distrib:\n    \"(\\<exists>x[M]. P(x) | Q(x)) <-> ((\\<exists>x[M]. P(x)) | (\\<exists>x[M]. Q(x)))\"\nby blast\n\n\nsubsubsection\\<open>One-point rule for bounded quantifiers\\<close>\n\nlemma rex_triv_one_point1 [simp]: \"(\\<exists>x[M]. x=a) <-> ( M(a))\"\nby blast\n\nlemma rex_triv_one_point2 [simp]: \"(\\<exists>x[M]. a=x) <-> ( M(a))\"\nby blast\n\nlemma rex_one_point1 [simp]: \"(\\<exists>x[M]. x=a \\<and> P(x)) <-> ( M(a) \\<and> P(a))\"\nby blast\n\nlemma rex_one_point2 [simp]: \"(\\<exists>x[M]. a=x \\<and> P(x)) <-> ( M(a) \\<and> P(a))\"\nby blast\n\nlemma rall_one_point1 [simp]: \"(\\<forall>x[M]. x=a \\<longrightarrow> P(x)) <-> ( M(a) \\<longrightarrow> P(a))\"\nby blast\n\nlemma rall_one_point2 [simp]: \"(\\<forall>x[M]. a=x \\<longrightarrow> P(x)) <-> ( M(a) \\<longrightarrow> P(a))\"\nby blast\n\n\nsubsubsection\\<open>Sets as Classes\\<close>\n\ndefinition\n  setclass :: \"[i,i] \\<Rightarrow> o\"       (\\<open>##_\\<close> [40] 40)  where\n   \"setclass(A) \\<equiv> \\<lambda>x. x \\<in> A\"\n\nlemma setclass_iff [simp]: \"setclass(A,x) <-> x \\<in> A\"\nby (simp add: setclass_def)\n\nlemma rall_setclass_is_ball [simp]: \"(\\<forall>x[##A]. P(x)) <-> (\\<forall>x\\<in>A. P(x))\"\nby auto\n\nlemma rex_setclass_is_bex [simp]: \"(\\<exists>x[##A]. P(x)) <-> (\\<exists>x\\<in>A. P(x))\"\nby auto\n\n\nML\n\\<open>\nval Ord_atomize =\n  atomize ([(\\<^const_name>\\<open>oall\\<close>, @{thms ospec}), (\\<^const_name>\\<open>rall\\<close>, @{thms rspec})] @\n    ZF_conn_pairs, ZF_mem_pairs);\n\\<close>\ndeclaration \\<open>fn _ =>\n  Simplifier.map_ss (Simplifier.set_mksimps (fn ctxt =>\n    map mk_eq o Ord_atomize o Variable.gen_all ctxt))\n\\<close>\n\ntext \\<open>Setting up the one-point-rule simproc\\<close>\n\nsimproc_setup defined_rex (\"\\<exists>x[M]. P(x) \\<and> Q(x)\") = \\<open>\n  fn _ => Quantifier1.rearrange_Bex\n    (fn ctxt => unfold_tac ctxt @{thms rex_def})\n\\<close>\n\nsimproc_setup defined_rall (\"\\<forall>x[M]. P(x) \\<longrightarrow> Q(x)\") = \\<open>\n  fn _ => Quantifier1.rearrange_Ball\n    (fn ctxt => unfold_tac ctxt @{thms rall_def})\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/ZF/OrdQuant.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8918110368115783, "lm_q2_score": 0.8289388083214156, "lm_q1q2_score": 0.7392567781024758}}
{"text": "theory Ex5_4 \n  imports Main \nbegin \n\ntype_synonym intervals = \"(nat \\<times> nat) list\"\n\ntype_synonym ntup = \"nat \\<times> nat\"\n\nfun inv2 :: \"nat \\<Rightarrow> intervals \\<Rightarrow> bool\" where \n\"inv2 _ [] = True\"|\n\"inv2 n ((x,y)#xs) = (n \\<le>  x \\<and>  x \\<le> y \\<and> inv2 (y + 2) xs)\"\n\n\ndefinition inv :: \"intervals \\<Rightarrow> bool\" where \n\"inv ls = inv2 0 ls\" \n\n\nfun set_of :: \"intervals \\<Rightarrow> nat set\" where \n\"set_of [] = {}\"|\n\"set_of ((x,y)#xs) = {n. x \\<le> n \\<and> n  \\<le>  y} \\<union> set_of xs\"\n\n\nprimrec add :: \"ntup \\<Rightarrow> intervals  \\<Rightarrow> intervals\" where \n\"add val [] = [val]\"|\n\"add nt (x#xs) = (if snd nt < fst x - 1 then nt # x# xs  else (if snd x < fst nt - 1 then x # add nt xs else add (min (fst nt) (fst x), max (snd nt)(snd x)) xs ) ) \"\n(*\nfun rem :: \"ntup \\<Rightarrow> intervals \\<Rightarrow> intervals\" where\n\"rem _ [] = []\"|\n\"rem (s,e) ((x,y)#xs) = (if (s = x) \\<and> (e = y) then xs else (x,y) # rem (s,e) xs)\"\n*)\nlemma inv2_monotone : \"inv2 m ins \\<Longrightarrow> n \\<le> m \\<Longrightarrow> inv2 n ins\"\nproof (induction ins arbitrary : m)\n  case Nil\n  then show ?case by simp\nnext\n  case (Cons a ins)\n  have tmp:\"inv2 n ins\" \n  proof -\n    have tmp:\"inv2 m (a#ins) = (m \\<le> fst a \\<and> fst a \\<le> snd a \\<and> inv2 (snd a + 2) ins)\" by (subst prod.collapse[symmetric], subst inv2.simps(2), rule refl) \n    with Cons(2) have tmp1:\"inv2 (snd a + 2) ins\" by simp\n    have \"n \\<le> snd a + 2\" using Cons.prems tmp by linarith\n    with Cons(1)[of \"snd a + 2\"] tmp1 show ?thesis by simp\n  qed\n  show ?case using  Cons(3) Cons(2) inv2.simps(2) tmp le_trans[of n m \"fst a\"]  prod.collapse[symmetric, of a]  by metis\nqed\n\ndeclare inv_def[simp]\n\n\nlemma helper:\"inv2 a ins \\<Longrightarrow> i \\<le> j \\<Longrightarrow> a \\<le> i  \\<Longrightarrow> inv2 a (add (i,j) ins)\" \nproof (induction ins arbitrary : a i j)\n  case Nil\n  then show ?case by simp\nnext\n  case (Cons aa ins)\n  assume hyp1:\"\\<And>a i j. inv2 a ins \\<Longrightarrow> i \\<le> j \\<Longrightarrow> a \\<le> i  \\<Longrightarrow> inv2 a (add (i, j) ins)\"\n  and hyp2:\"inv2 a (aa # ins)\"\n  and hyp3:\"i \\<le> j\"\n  and hyp4:\"a \\<le> i\"\n\n  let ?faa = \"fst aa\"\n  and ?saa = \"snd aa\"\n\n\n  show ?case \n  proof (cases \"j < fst aa - 1\")\n    case True\n    hence tmp:\"j + 2 \\<le> fst aa\" by simp\n    have \"inv2 a (add (i, j) (aa # ins)) = inv2 a ((i,j) # aa # ins)\" using True inv2.simps hyp3 prod.collapse[of aa , symmetric]  add.simps(2) prod.sel(2)[of i j] by simp\n    also have \"\\<dots>  = inv2 (j + 2) (aa # ins)\" using hyp3 hyp4 by simp\n    also have \"\\<dots> = inv2 a (aa # ins)\" using hyp2 tmp inv2.simps(2) prod.collapse[of aa , symmetric]  hyp4 by metis\n    finally show ?thesis using hyp2 by simp\n  next\n    case False\n    assume c1:\"\\<not> j < fst aa - 1\"\n    then show ?thesis \n    proof (cases \"snd aa < i- 1\")\n      case True\n      from hyp2 have \"inv2 (snd aa + 2) ins\" using inv2.simps(2) prod.collapse[of aa, symmetric] by metis\n      with hyp1[of \"snd aa + 2\" i j] hyp3 True have tmp:\"inv2 (snd aa + 2) (add (i, j) ins)\" by simp\n      have \"inv2 a (add (i, j) (aa # ins)) = inv2 a (aa # add (i,j) ins)\" using False True prod.collapse[of aa , symmetric] prod.sel add.simps(2) by simp\n      also have \"\\<dots> = inv2 (snd aa + 2) (add (i,j) ins)\" using hyp2 inv2.simps(2) prod.collapse[of aa , symmetric]  by metis\n      finally show ?thesis using tmp by simp\n    next\n      case False\n\n      have tmp:\"min i (fst aa) \\<le> max j (snd aa)\" using hyp3 hyp2 by auto\n\n      have tmp2:\"a \\<le> min i (fst aa)\" using hyp2 hyp4 min_def prod.collapse[of aa , symmetric] le_trans inv2.simps by metis\n\n      have \"a \\<le> snd aa + 2\" using hyp2 prod.collapse[symmetric , of aa]  inv2.simps(2) le_trans trans_le_add1 by metis\n\n      hence \"inv2 a ins\"  using hyp2 inv2_monotone inv2.simps(2) prod.collapse[of aa, symmetric] by metis\n\n      hence tmp3:\"inv2 a (add (min i (fst aa), max j (snd aa)) ins)\" using hyp1[of a \"min i (fst aa)\" \"max j (snd aa)\"] tmp tmp2 by simp\n\n      have \"inv2 a (add (i, j) (aa # ins)) = inv2 a (add (min  i (fst aa), max j (snd aa)) ins)\" \n        by (subst add.simps , subst prod.sel(2), subst c1, subst if_False, subst prod.sel(1), subst False , subst if_False, simp)\n      then show ?thesis using tmp3 by simp\n    qed\n  qed\nqed\n\n\n\ntheorem inv_add : \"\\<lbrakk> i \\<le> j ; inv ins \\<rbrakk> \\<Longrightarrow> inv (add (i,j) ins)\" using helper[of 0 ins i j] by simp\n\n\nlemma helper2:\"set_of (xs @ ys) = set_of xs \\<union> set_of ys\"  by (induction xs ;auto)\n\ntheorem set_of_add: \n  \"\\<lbrakk> i \\<le> j; inv ins \\<rbrakk> \\<Longrightarrow> set_of (add (i,j) ins) = set_of [(i,j)] \\<union> set_of ins\"\nproof (induction ins)\n  case Nil\n  then show ?case by simp\nnext\n  case (Cons aa ins)\n  then show ?case \n  proof (cases \"j < fst aa - 1\")\n    case True\n    then show ?thesis \n  next\n    case False\n    then show ?thesis sorry\nqed\n\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/5. Advanced/Ex5_4.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8991213772699435, "lm_q2_score": 0.8221891283434876, "lm_q1q2_score": 0.7392478214525708}}
{"text": "section \\<open>Power sum polynomials\\<close>\n(*\n  File:     Power_Sum_Polynomials.thy\n  Author:   Manuel Eberl, TU M\u00fcnchen\n*)\ntheory Power_Sum_Polynomials\nimports\n  \"Symmetric_Polynomials.Symmetric_Polynomials\"\n  \"HOL-Computational_Algebra.Field_as_Ring\"\n  Power_Sum_Polynomials_Library\nbegin\n\nsubsection \\<open>Definition\\<close>\n\ntext \\<open>\n  For $n$ indeterminates $X_1,\\ldots,X_n$, we define the $k$-th power sum polynomial as\n  \\[p_k(X_1, \\ldots, X_n) = X_1^k + \\ldots + X_n^k\\ .\\]\n\\<close>\nlift_definition powsum_mpoly_aux :: \"nat set \\<Rightarrow> nat \\<Rightarrow> (nat \\<Rightarrow>\\<^sub>0 nat) \\<Rightarrow>\\<^sub>0 'a :: {semiring_1,zero_neq_one}\" is\n  \"\\<lambda>X k mon. if infinite X \\<or> k = 0 \\<and> mon \\<noteq> 0 then 0\n             else if k = 0 \\<and> mon = 0 then of_nat (card X)\n             else if finite X \\<and> (\\<exists>x\\<in>X. mon = Poly_Mapping.single x k) then 1 else 0\"\n  by auto\n\nlemma lookup_powsum_mpoly_aux:\n  \"Poly_Mapping.lookup (powsum_mpoly_aux X k) mon =\n     (if infinite X \\<or> k = 0 \\<and> mon \\<noteq> 0 then 0\n             else if k = 0 \\<and> mon = 0 then of_nat (card X)\n             else if finite X \\<and> (\\<exists>x\\<in>X. mon = Poly_Mapping.single x k) then 1 else 0)\"\n  by transfer' simp\n\nlemma lookup_sym_mpoly_aux_monom_singleton [simp]:\n  assumes \"finite X\" \"x \\<in> X\" \"k > 0\"\n  shows   \"Poly_Mapping.lookup (powsum_mpoly_aux X k) (Poly_Mapping.single x k) = 1\"\n  using assms by (auto simp: lookup_powsum_mpoly_aux)\n\nlemma lookup_sym_mpoly_aux_monom_singleton':\n  assumes \"finite X\" \"k > 0\"\n  shows   \"Poly_Mapping.lookup (powsum_mpoly_aux X k) (Poly_Mapping.single x k) = (if x \\<in> X then 1 else 0)\"\n  using assms by (auto simp: lookup_powsum_mpoly_aux)\n\nlemma keys_powsum_mpoly_aux: \"m \\<in> keys (powsum_mpoly_aux A k) \\<Longrightarrow> keys m \\<subseteq> A\"\n  by transfer' (auto split: if_splits simp: keys_monom_of_set)\n\n\nlift_definition powsum_mpoly :: \"nat set \\<Rightarrow> nat \\<Rightarrow> 'a :: {semiring_1,zero_neq_one} mpoly\" is\n  \"powsum_mpoly_aux\" .\n\nlemma vars_powsum_mpoly_subset: \"vars (powsum_mpoly A k) \\<subseteq> A\"\n  using keys_powsum_mpoly_aux by (auto simp: vars_def powsum_mpoly.rep_eq)\n\nlemma powsum_mpoly_infinite: \"\\<not>finite A \\<Longrightarrow> powsum_mpoly A k = 0\"\n  by (transfer, transfer) auto\n\nlemma coeff_powsum_mpoly:\n  \"MPoly_Type.coeff (powsum_mpoly X k) mon =\n     (if infinite X \\<or> k = 0 \\<and> mon \\<noteq> 0 then 0\n             else if k = 0 \\<and> mon = 0 then of_nat (card X)\n             else if finite X \\<and> (\\<exists>x\\<in>X. mon = Poly_Mapping.single x k) then 1 else 0)\"\n  by transfer' (simp add: lookup_powsum_mpoly_aux)\n\nlemma coeff_powsum_mpoly_0_right:\n  \"MPoly_Type.coeff (powsum_mpoly X 0) mon = (if mon = 0 then of_nat (card X) else 0)\"\n  by transfer' (auto simp add: lookup_powsum_mpoly_aux)\n\nlemma coeff_powsum_mpoly_singleton:\n  assumes \"finite X\" \"k > 0\"\n  shows   \"MPoly_Type.coeff (powsum_mpoly X k) (Poly_Mapping.single x k) = (if x \\<in> X then 1 else 0)\"\n  using assms by transfer' (simp add: lookup_powsum_mpoly_aux)\n\nlemma coeff_powsum_mpoly_singleton_eq_1 [simp]:\n  assumes \"finite X\" \"x \\<in> X\" \"k > 0\"\n  shows   \"MPoly_Type.coeff (powsum_mpoly X k) (Poly_Mapping.single x k) = 1\"\n  using assms by (simp add: coeff_powsum_mpoly_singleton)\n\nlemma coeff_powsum_mpoly_singleton_eq_0 [simp]:\n  assumes \"finite X\" \"x \\<notin> X\" \"k > 0\"\n  shows   \"MPoly_Type.coeff (powsum_mpoly X k) (Poly_Mapping.single x k) = 0\"\n  using assms by (simp add: coeff_powsum_mpoly_singleton)\n\nlemma powsum_mpoly_0 [simp]: \"powsum_mpoly X 0 = of_nat (card X)\"\n  by (intro mpoly_eqI ext) (auto simp: coeff_powsum_mpoly_0_right of_nat_mpoly_eq mpoly_coeff_Const)\n\nlemma powsum_mpoly_empty [simp]: \"powsum_mpoly {} k = 0\"\n  by (intro mpoly_eqI) (auto simp: coeff_powsum_mpoly)\n\nlemma powsum_mpoly_altdef: \"powsum_mpoly X k = (\\<Sum>x\\<in>X. monom (Poly_Mapping.single x k) 1)\"\nproof (cases \"finite X\")\n  case [simp]: True\n  show ?thesis\n  proof (cases \"k = 0\")\n    case True\n    thus ?thesis by auto\n  next\n    case False\n    show ?thesis\n    proof (intro mpoly_eqI, goal_cases)\n      case (1 mon)\n      show ?case using False\n        by (cases \"\\<exists>x\\<in>X. mon = Poly_Mapping.single x k\")\n           (auto simp: coeff_powsum_mpoly coeff_monom when_def)\n    qed\n  qed\nqed (auto simp: powsum_mpoly_infinite)\n\ntext \\<open>\n  Power sum polynomials are symmetric:\n\\<close>\nlemma symmetric_powsum_mpoly [intro]:\n  assumes \"A \\<subseteq> B\"\n  shows   \"symmetric_mpoly A (powsum_mpoly B k)\"\n  unfolding powsum_mpoly_altdef\nproof (rule symmetric_mpoly_symmetric_sum)\n  fix x \\<pi>\n  assume \"x \\<in> B\" \"\\<pi> permutes A\"\n  thus \"mpoly_map_vars \\<pi> (MPoly_Type.monom (Poly_Mapping.single x k) 1) =\n        MPoly_Type.monom (Poly_Mapping.single (\\<pi> x) k) 1\"\n    using assms by (auto simp: mpoly_map_vars_monom permutes_bij permutep_single\n                               bij_imp_bij_inv permutes_inv_inv)\nqed (use assms in \\<open>auto simp: permutes_subset\\<close>)\n\nlemma insertion_powsum_mpoly [simp]: \"insertion f (powsum_mpoly X k) = (\\<Sum>i\\<in>X. f i ^ k)\"\n  unfolding powsum_mpoly_altdef insertion_sum insertion_single by simp\n\nlemma powsum_mpoly_nz:\n  assumes \"finite X\" \"X \\<noteq> {}\" \"k > 0\"\n  shows   \"(powsum_mpoly X k :: 'a :: {semiring_1, zero_neq_one} mpoly) \\<noteq> 0\"\nproof -\n  from assms obtain x where \"x \\<in> X\" by auto\n  hence \"coeff (powsum_mpoly X k) (Poly_Mapping.single x k) = (1 :: 'a)\"\n    using assms by (auto simp: coeff_powsum_mpoly)\n  thus ?thesis by auto\nqed\n\nlemma powsum_mpoly_eq_0_iff:\n  assumes \"k > 0\"\n  shows   \"powsum_mpoly X k = 0 \\<longleftrightarrow> infinite X \\<or> X = {}\"\n  using assms powsum_mpoly_nz[of X k] by (auto simp: powsum_mpoly_infinite)\n\n\nsubsection \\<open>The Girard--Newton Theorem\\<close>\n\ntext \\<open>\n  The following is a nice combinatorial proof of the Girard--Newton Theorem due to\n  Doron Zeilberger~\\cite{zeilberger}.\n\n  The precise statement is this:\n\n  Let $e_k$ denote the $k$-th elementary symmetric polynomial in $X_1,\\ldots,X_n$.\n  This is the sum of all monomials that can be formed by taking the product of $k$ \n  distinct variables.\n\n  Next, let $p_k = X_1^k + \\ldots + X_n^k$ denote that $k$-th symmetric power sum polynomial\n  in $X_1,\\ldots,X_n$.\n\n  Then the following equality holds:\n  \\[(-1)^k k e_k + \\sum_{i=0}^{k-1} (-1)^i e_i p_{k-i}\\]\n\\<close>\ntheorem Girard_Newton:\n  assumes \"finite X\"\n  shows   \"(-1) ^ k * of_nat k * sym_mpoly X k +\n           (\\<Sum>i<k. (-1) ^ i * sym_mpoly X i * powsum_mpoly X (k - i)) =\n             (0 :: 'a :: comm_ring_1 mpoly)\"\n  (is \"?lhs = 0\")\nproof -\n  write Poly_Mapping.single (\"sng\")\n\n  define n where \"n = card X\"\n  define \\<A> :: \"(nat set \\<times> nat) set\"\n    where \"\\<A> = {(A, j). A \\<subseteq> X \\<and> card A \\<le> k \\<and> j \\<in> X \\<and> (card A = k \\<longrightarrow> j \\<in> A)}\"\n  define \\<A>1 :: \"(nat set \\<times> nat) set\"\n    where \"\\<A>1 = {A\\<in>Pow X. card A < k} \\<times> X\"\n  define \\<A>2 :: \"(nat set \\<times> nat) set\"\n    where \"\\<A>2 = (SIGMA A:{A\\<in>Pow X. card A = k}. A)\"\n\n  have \\<A>_split: \"\\<A> = \\<A>1 \\<union> \\<A>2\" \"\\<A>1 \\<inter> \\<A>2 = {}\"\n    by (auto simp: \\<A>_def \\<A>1_def \\<A>2_def)\n  have [intro]: \"finite \\<A>1\" \"finite \\<A>2\"\n    using assms finite_subset[of _ X] by (auto simp: \\<A>1_def \\<A>2_def intro!: finite_SigmaI)\n  have [intro]: \"finite \\<A>\"\n    by (subst \\<A>_split) auto\n\n  \\<comment> \\<open>\n    We define a `weight' function \\<open>w\\<close> from \\<open>\\<A>\\<close> to the ring of polynomials as\n    \\[w(A,j) = (-1)^{|A|} x_j^{k-|A|} \\prod_{i\\in A} x_i\\ .\\]\n  \\<close>\n  define w :: \"nat set \\<times> nat \\<Rightarrow> 'a mpoly\"\n    where \"w = (\\<lambda>(A, j). monom (monom_of_set A + sng j (k - card A)) ((-1) ^ card A))\"\n\n  \\<comment> \\<open>The sum of these weights over all of \\<open>\\<A>\\<close> is precisely the sum that we want to show equals 0:\\<close>\n  have \"?lhs = (\\<Sum>x\\<in>\\<A>. w x)\"\n  proof -\n    have \"(\\<Sum>x\\<in>\\<A>. w x) = (\\<Sum>x\\<in>\\<A>1. w x) + (\\<Sum>x\\<in>\\<A>2. w x)\"\n      by (subst \\<A>_split, subst sum.union_disjoint, use \\<A>_split(2) in auto)\n\n    also have \"(\\<Sum>x\\<in>\\<A>1. w x) = (\\<Sum>i<k. (-1) ^ i * sym_mpoly X i * powsum_mpoly X (k - i))\"\n    proof -\n      have \"(\\<Sum>x\\<in>\\<A>1. w x) = (\\<Sum>A | A \\<subseteq> X \\<and> card A < k. \\<Sum>j\\<in>X. w (A, j))\"\n        using assms by (subst sum.Sigma) (auto simp: \\<A>1_def)\n      also have \"\\<dots> = (\\<Sum>A | A \\<subseteq> X \\<and> card A < k. \\<Sum>j\\<in>X.\n                        monom (monom_of_set A) ((-1) ^ card A) * monom (sng j (k - card A)) 1)\"\n        unfolding w_def by (intro sum.cong) (auto simp: mult_monom)\n      also have \"\\<dots> = (\\<Sum>A | A \\<subseteq> X \\<and> card A < k. monom (monom_of_set A) ((-1) ^ card A) *\n                        powsum_mpoly X (k - card A))\"\n        by (simp add: sum_distrib_left powsum_mpoly_altdef)\n      also have \"\\<dots> = (\\<Sum>(i,A) \\<in> (SIGMA i:{..<k}. {A. A \\<subseteq> X \\<and> card A = i}).\n                        monom (monom_of_set A) ((-1) ^ i) * powsum_mpoly X (k - i))\"\n        by (rule sum.reindex_bij_witness[of _ snd \"\\<lambda>A. (card A, A)\"]) auto\n      also have \"\\<dots> = (\\<Sum>i<k. \\<Sum>A | A \\<subseteq> X \\<and> card A = i.\n                        monom (monom_of_set A) 1 * monom 0 ((-1) ^ i) * powsum_mpoly X (k - i))\"\n        using assms by (subst sum.Sigma) (auto simp: mult_monom)\n      also have \"\\<dots> = (\\<Sum>i<k. (-1) ^ i * sym_mpoly X i * powsum_mpoly X (k - i))\"\n        by (simp add: sum_distrib_left sum_distrib_right mpoly_monom_0_eq_Const \n                      mpoly_Const_power mpoly_Const_uminus algebra_simps sym_mpoly_altdef)\n      finally show ?thesis .\n    qed\n\n    also have \"(\\<Sum>x\\<in>\\<A>2. w x) = (-1) ^ k * of_nat k * sym_mpoly X k\"\n    proof -\n      have \"(\\<Sum>x\\<in>\\<A>2. w x) = (\\<Sum>(A,j)\\<in>\\<A>2. monom (monom_of_set A) ((- 1) ^ k))\"\n        by (intro sum.cong) (auto simp: \\<A>2_def w_def mpoly_monom_0_eq_Const intro!: sum.cong)\n      also have \"\\<dots> = (\\<Sum>A | A \\<subseteq> X \\<and> card A = k. \\<Sum>j\\<in>A. monom (monom_of_set A) ((- 1) ^ k))\"\n        using assms finite_subset[of _ X] by (subst sum.Sigma) (auto simp: \\<A>2_def)\n      also have \"(\\<lambda>A. monom (monom_of_set A) ((- 1) ^ k) :: 'a mpoly) =\n                   (\\<lambda>A. monom 0 ((-1) ^ k) * monom (monom_of_set A) 1)\"\n        by (auto simp: fun_eq_iff mult_monom)\n      also have \"monom 0 ((-1) ^ k) = (-1) ^ k\"\n        by (auto simp: mpoly_monom_0_eq_Const mpoly_Const_power mpoly_Const_uminus)\n      also have \"(\\<Sum>A | A \\<subseteq> X \\<and> card A = k. \\<Sum>j\\<in>A. (- 1) ^ k * monom (monom_of_set A) 1) =\n                   ((-1) ^ k * of_nat k * sym_mpoly X k :: 'a mpoly)\"\n        by (auto simp: sum_distrib_left sum_distrib_right mult_ac sym_mpoly_altdef)\n      finally show ?thesis .\n    qed\n\n    finally show ?thesis by (simp add: algebra_simps)\n  qed\n\n  \\<comment> \\<open>Next, we show that the weights sum to 0:\\<close>\n  also have \"(\\<Sum>x\\<in>\\<A>. w x) = 0\"\n  proof -\n    \\<comment> \\<open>We define a function \\<open>T\\<close> that is a involutory permutation of \\<open>\\<A>\\<close>.\n        To be more precise, it bijectively maps those elements \\<open>(A,j)\\<close> of \\<open>\\<A>\\<close> with \\<open>j \\<in> A\\<close>\n        to those where \\<open>j \\<notin> A\\<close> and the other way round. `Involutory' means that \\<open>T\\<close> is its\n        own inverse function, i.\\,e.\\ $T(T(x)) = x$.\\<close>\n    define T :: \"nat set \\<times> nat \\<Rightarrow> nat set \\<times> nat\"\n      where \"T = (\\<lambda>(A, j). if j \\<in> A then (A - {j}, j) else (insert j A, j))\"\n    have [simp]: \"T (T x) = x\" for x\n      by (auto simp: T_def split: prod.splits)\n    have [simp]: \"T x \\<in> \\<A>\" if \"x \\<in> \\<A>\" for x\n    proof -\n      have [simp]: \"n \\<le> n - Suc 0 \\<longleftrightarrow> n = 0\" for n\n        by auto\n      show ?thesis using that assms finite_subset[of _ X]\n        by (auto simp: T_def \\<A>_def split: prod.splits)\n    qed\n    have \"snd (T x) \\<in> fst (T x) \\<longleftrightarrow> snd x \\<notin> fst x\" if \"x \\<in> \\<A>\" for x\n      by (auto simp: T_def split: prod.splits)\n    hence bij: \"bij_betw T {x\\<in>\\<A>. snd x \\<in> fst x} {x\\<in>\\<A>. snd x \\<notin> fst x}\"\n      by (intro bij_betwI[of _ _ _ T]) auto\n\n    \\<comment>\\<open>Crucially, we show that \\<^term>\\<open>T\\<close> flips the weight of each element:\\<close>\n    have [simp]: \"w (T x) = -w x\" if \"x \\<in> \\<A>\" for x\n    proof -\n      obtain A j where [simp]: \"x = (A, j)\" by force\n      \n      \\<comment> \\<open>Since \\<^term>\\<open>T\\<close> is an involution, we can assume w.\\,l.\\,o.\\,g.\\ that \\<open>j \\<in> A\\<close>:\\<close>\n      have aux: \"w (T (A, j)) = - w (A, j)\" if \"(A, j) \\<in> \\<A>\" \"j \\<in> A\" for j A\n      proof -\n        from that have [simp]: \"j \\<in> A\" \"A \\<subseteq> X\" and \"k > 0\"\n          using finite_subset[OF _ assms, of A] by (auto simp: \\<A>_def intro!: Nat.gr0I)\n        have [simp]: \"finite A\"\n          using finite_subset[OF _ assms, of A] by auto\n        from that have \"card A \\<le> k\"\n          by (auto simp: \\<A>_def)\n\n        have card: \"card A = Suc (card (A - {j}))\"\n          using card.remove[of A j] by auto\n        hence card_less: \"card (A - {j}) < card A\" by linarith\n\n        have \"w (T (A, j)) = monom (monom_of_set (A - {j}) + sng j (k - card (A - {j})))\n                         ((- 1) ^ card (A - {j}))\" by (simp add: w_def T_def)\n        also have \"(- 1) ^ card (A - {j}) = ((- 1) ^ Suc (Suc (card (A - {j}))) :: 'a)\"\n          by simp\n        also have \"Suc (card (A - {j})) = card A\"\n          using card by simp\n        also have \"k - card (A - {j}) = Suc (k - card A)\"\n          using \\<open>k > 0\\<close> \\<open>card A \\<le> k\\<close> card_less by (subst card) auto\n        also have \"monom_of_set (A - {j}) + sng j (Suc (k - card A)) =\n                   monom_of_set A + sng j (k - card A)\"\n          by (transfer fixing: A j k) (auto simp: fun_eq_iff)\n        also have \"monom \\<dots> ((-1)^ Suc (card A)) = -w (A, j)\"\n          by (simp add: w_def monom_uminus)\n        finally show ?thesis .\n      qed\n\n      show ?thesis\n      proof (cases \"j \\<in> A\")\n        case True\n        with aux[of A j] that show ?thesis by auto\n      next\n        case False\n        hence \"snd (T x) \\<in> fst (T x)\"\n          by (auto simp: T_def split: prod.splits)\n        with aux[of \"fst (T x)\" \"snd (T x)\"] that show ?thesis by auto\n      qed\n    qed\n\n    text \\<open>\n      We can now show fairly easily that the sum is equal to zero.\n    \\<close>\n    have *: \"\\<A> = {x\\<in>\\<A>. snd x \\<in> fst x} \\<union> {x\\<in>\\<A>. snd x \\<notin> fst x}\"\n      by auto\n    have \"(\\<Sum>x\\<in>\\<A>. w x) = (\\<Sum>x | x \\<in> \\<A> \\<and> snd x \\<in> fst x. w x) + (\\<Sum>x | x \\<in> \\<A> \\<and> snd x \\<notin> fst x. w x)\"\n      using \\<open>finite \\<A>\\<close> by (subst *, subst sum.union_disjoint) auto\n    also have \"(\\<Sum>x | x \\<in> \\<A> \\<and> snd x \\<notin> fst x. w x) = (\\<Sum>x | x \\<in> \\<A> \\<and> snd x \\<in> fst x. w (T x))\"\n      using sum.reindex_bij_betw[OF bij, of w] by simp\n    also have \"\\<dots> = -(\\<Sum>x | x \\<in> \\<A> \\<and> snd x \\<in> fst x. w x)\"\n      by (simp add: sum_negf)\n    finally show \"(\\<Sum>x\\<in>\\<A>. w x) = 0\"\n      by simp\n  qed\n\n  finally show ?thesis .\nqed\n\ntext \\<open>\n  The following variant of the theorem holds for \\<open>k > n\\<close>. Note that this is now a\n  linear recurrence relation with constant coefficients for $p_k$ in terms of\n  $e_0, \\ldots, e_n$.\n\\<close>\ncorollary Girard_Newton':\n  assumes \"finite X\" and \"k > card X\"\n  shows   \"(\\<Sum>i\\<le>card X. (-1) ^ i * sym_mpoly X i * powsum_mpoly X (k - i)) =\n             (0 :: 'a :: comm_ring_1 mpoly)\"\nproof -\n  have \"(0 :: 'a mpoly) = (\\<Sum>i<k. (- 1) ^ i * sym_mpoly X i * powsum_mpoly X (k - i))\"\n    using Girard_Newton[of X k] assms by simp\n  also have \"\\<dots> = (\\<Sum>i\\<le>card X. (- 1) ^ i * sym_mpoly X i * powsum_mpoly X (k - i))\"\n    using assms by (intro sum.mono_neutral_right) auto\n  finally show ?thesis ..\nqed  \n\ntext \\<open>\n  The following variant is the Newton--Girard Theorem solved for $e_k$, giving us\n  an explicit way to determine $e_k$ from $e_0, \\ldots, e_{k-1}$ and $p_1, \\ldots, p_k$:\n\\<close>\ncorollary sym_mpoly_recurrence:\n  assumes k: \"k > 0\" and \"finite X\"\n  shows   \"(sym_mpoly X k :: 'a :: field_char_0 mpoly) =\n             -smult (1 / of_nat k) (\\<Sum>i=1..k. (-1) ^ i * sym_mpoly X (k - i) * powsum_mpoly X i)\"\nproof -\n  define e p :: \"nat \\<Rightarrow> 'a mpoly\" where [simp]: \"e = sym_mpoly X\" \"p = powsum_mpoly X\"\n  have *: \"0 = (-1) ^ k * of_nat k * e k +\n              (\\<Sum>i<k. (- 1) ^ i * e i * p (k - i) :: 'a mpoly)\"\n    using Girard_Newton[of X k] assms by simp\n\n  have \"0 = (-1) ^ k * smult (1 / of_nat k) (0 :: 'a mpoly)\"\n    by simp\n  also have \"\\<dots> = smult (1 / of_nat k) (of_nat k) * e k +\n                  smult (1 / of_nat k) (\\<Sum>i<k. (-1)^(k+i) * e i * p (k - i))\"\n    unfolding smult_conv_mult\n    using k by (subst *) (simp add: power_add sum_distrib_left sum_distrib_right field_simps \n                               del: div_mult_self3 div_mult_self4 div_mult_self2 div_mult_self1)\n  also have \"smult (1 / of_nat k :: 'a) (of_nat k) = 1\"\n    using k by (simp add: of_nat_monom smult_conv_mult mult_monom del: monom_of_nat)\n  also have \"(\\<Sum>i<k. (-1) ^ (k+i) * e i * p (k - i)) = (\\<Sum>i=1..k. (-1) ^ i * e (k-i) * p i)\"\n    by (intro sum.reindex_bij_witness[of _ \"\\<lambda>i. k - i\" \"\\<lambda>i. k - i\"])\n       (auto simp: minus_one_power_iff)\n  finally show ?thesis unfolding e_p_def by algebra\nqed\n\ntext \\<open>\n  Analogously, the following is the theorem solved for $p_k$, giving us a\n  way to determine $p_k$ from $e_0, \\ldots, e_k$ and $p_1, \\ldots, p_{k-1}$:\n\\<close>\ncorollary powsum_mpoly_recurrence:\n  assumes k: \"k > 0\" and X: \"finite X\"\n  shows   \"(powsum_mpoly X k :: 'a :: comm_ring_1 mpoly) =\n             (-1) ^ (k + 1) * of_nat k * sym_mpoly X k -\n             (\\<Sum>i=1..<k. (-1) ^ i * sym_mpoly X i * powsum_mpoly X (k - i))\"\nproof -\n  define e p :: \"nat \\<Rightarrow> 'a mpoly\" where [simp]: \"e = sym_mpoly X\" \"p = powsum_mpoly X\"\n  have *: \"0 = (-1) ^ k * of_nat k * e k +\n                 (\\<Sum>i<k. (-1) ^ i * e i * p (k - i) :: 'a mpoly)\"\n    using Girard_Newton[of X k] assms by simp\n  also have \"{..<k} = insert 0 {1..<k}\"\n    using assms by auto\n  finally have \"(-1) ^ k * of_nat k * e k + (\\<Sum>i=1..<k. (-1) ^ i * e i * p (k - i)) + p k = 0\"\n    using assms by (simp add: algebra_simps)\n  from add.inverse_unique[OF this] show ?thesis by simp\nqed\n\ntext \\<open>\n  Again, if we assume $k > n$, the above takes a much simpler form and is, in fact,\n  a linear recurrence with constant coefficients:\n\\<close>\nlemma powsum_mpoly_recurrence':\n  assumes k: \"k > card X\" and X: \"finite X\"\n  shows   \"(powsum_mpoly X k :: 'a :: comm_ring_1 mpoly) =\n             -(\\<Sum>i=1..card X. (-1) ^ i * sym_mpoly X i * powsum_mpoly X (k - i))\"\nproof -\n  define e p :: \"nat \\<Rightarrow> 'a mpoly\" where [simp]: \"e = sym_mpoly X\" \"p = powsum_mpoly X\"\n  have \"p k = (-1) ^ (k + 1) * of_nat k * e k - (\\<Sum>i=1..<k. (-1) ^ i * e i * p (k - i))\"\n    unfolding e_p_def using assms by (intro powsum_mpoly_recurrence) auto\n  also have \"\\<dots> = -(\\<Sum>i=1..<k. (-1) ^ i * e i * p (k - i))\"\n    using assms by simp\n  also have \"(\\<Sum>i=1..<k. (-1) ^ i * e i * p (k - i)) = (\\<Sum>i=1..card X. (-1) ^ i * e i * p (k - i))\"\n    using assms by (intro sum.mono_neutral_right) auto\n  finally show ?thesis 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/Power_Sum_Polynomials/Power_Sum_Polynomials.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278757303677, "lm_q2_score": 0.8376199633332891, "lm_q1q2_score": 0.7391392049135429}}
{"text": "\ntheory Lists1_5\nimports Main\nbegin\n\nprimrec occurs:: \"'a \\<Rightarrow> 'a list \\<Rightarrow> nat\"\nwhere\n  \"occurs x [] = 0\"\n| \"occurs x (y#ys) = (if x = y then Suc (occurs x ys) else (occurs x ys))\"\n\nvalue \"occurs 1 [1,2,3,4,1,3::int]\"\n\nlemma occurs_append: \"occurs x (ys @ zs) = (occurs x ys) + (occurs x zs)\"\n  apply (induct ys)\n  apply auto\ndone\n\nlemma \"occurs x ys = occurs x (rev ys)\"\n  apply (induct ys)\n  apply (auto simp add:occurs_append)\ndone\n\nlemma \"occurs x ys \\<le> length ys\"\n  apply (induct ys)\n  apply auto\ndone\n\nlemma \"occurs a (map f xs) = occurs (f a) xs\"\n  quickcheck\noops\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\nprimrec remDups :: \"'a list \\<Rightarrow> 'a list\"\nwhere\n  \"remDups [] = []\"\n| \"remDups (x#xs) = (if 0 < occurs x xs then remDups xs else (x#(remDups xs)))\"\n\nvalue \"remDups [1,2,3,4,5::int,1,2,5]\"\n\n(* different from text *)\nlemma occurs_remdups: \"occurs x (remDups xs) = (if ((occurs x xs) = 0) then 0 else 1)\"\n  apply (induct xs)\n  apply auto\ndone\n\n(* different from text *)\nprimrec unique:: \"'a list \\<Rightarrow> bool\"\nwhere\n  \"unique [] = True\"\n| \"unique (x#xs) = (if 0 < occurs x xs then False else unique xs)\"\n\nvalue \"unique []\"\nvalue \"unique [1::int,2,3]\"\nvalue \"unique [1::int,1,2,3]\"\n\nlemma \"unique (remDups xs)\"\n  apply (induct xs)\n  apply (auto simp add:occurs_remdups)\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_5.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.88242786954645, "lm_q2_score": 0.8376199673867852, "lm_q1q2_score": 0.7391392033106878}}
{"text": "(*  Title:       Square Matrices\n    Author:      Jonathan Juli\u00e1n Huerta y Munive, 2020\n    Maintainer:  Jonathan Juli\u00e1n Huerta y Munive <jonjulian23@gmail.com>\n*)\n\nsection \\<open> Square Matrices \\<close>\n\ntext\\<open> The general solution for affine systems of ODEs involves the exponential function. \nUnfortunately, this operation is only available in Isabelle for the type class ``banach''. \nHence, we define a type of square matrices and prove that it is an instance of this class.\\<close>\n\ntheory SQ_MTX\n  imports MTX_Norms\n\nbegin\n\nsubsection \\<open> Definition \\<close>\n\ntypedef 'm sq_mtx = \"UNIV::(real^'m^'m) set\"\n  morphisms to_vec to_mtx by simp\n\ndeclare to_mtx_inverse [simp]\n    and to_vec_inverse [simp]\n\nsetup_lifting type_definition_sq_mtx\n\nlift_definition sq_mtx_ith :: \"'m sq_mtx \\<Rightarrow> 'm \\<Rightarrow> (real^'m)\" (infixl \"$$\" 90) is \"($)\" .\n\nlift_definition sq_mtx_vec_mult :: \"'m sq_mtx \\<Rightarrow> (real^'m) \\<Rightarrow> (real^'m)\" (infixl \"*\\<^sub>V\" 90) is \"(*v)\" .\n\nlift_definition vec_sq_mtx_prod :: \"(real^'m) \\<Rightarrow> 'm sq_mtx \\<Rightarrow> (real^'m)\" is \"(v*)\" .\n\nlift_definition sq_mtx_diag :: \"(('m::finite) \\<Rightarrow> real) \\<Rightarrow> ('m::finite) sq_mtx\" (binder \"\\<d>\\<i>\\<a>\\<g> \" 10) \n  is diag_mat .\n\nlift_definition sq_mtx_transpose :: \"('m::finite) sq_mtx \\<Rightarrow> 'm sq_mtx\" (\"_\\<^sup>\\<dagger>\") is transpose .\n\nlift_definition sq_mtx_inv :: \"('m::finite) sq_mtx \\<Rightarrow> 'm sq_mtx\" (\"_\\<^sup>-\\<^sup>1\" [90]) is matrix_inv .\n\nlift_definition sq_mtx_row :: \"'m \\<Rightarrow> ('m::finite) sq_mtx \\<Rightarrow> real^'m\" (\"\\<r>\\<o>\\<w>\") is row .\n\nlift_definition sq_mtx_col :: \"'m \\<Rightarrow> ('m::finite) sq_mtx \\<Rightarrow> real^'m\" (\"\\<c>\\<o>\\<l>\")  is column .\n\nlemma to_vec_eq_ith: \"(to_vec A) $ i = A $$ i\"\n  by transfer simp\n\nlemma to_mtx_ith[simp]: \n  \"(to_mtx A) $$ i1 = A $ i1\"\n  \"(to_mtx A) $$ i1 $ i2 = A $ i1 $ i2\"\n  by (transfer, simp)+\n\nlemma to_mtx_vec_lambda_ith[simp]: \"to_mtx (\\<chi> i j. x i j) $$ i1 $ i2 = x i1 i2\"\n  by (simp add: sq_mtx_ith_def)\n\nlemma sq_mtx_eq_iff:\n  shows \"A = B = (\\<forall>i j. A $$ i $ j = B $$ i $ j)\"\n    and \"A = B = (\\<forall>i. A $$ i = B $$ i)\"\n  by (transfer, simp add: vec_eq_iff)+\n\nlemma sq_mtx_diag_simps[simp]:\n  \"i = j \\<Longrightarrow> sq_mtx_diag f $$ i $ j = f i\"\n  \"i \\<noteq> j \\<Longrightarrow> sq_mtx_diag f $$ i $ j = 0\"\n  \"sq_mtx_diag f $$ i = axis i (f i)\"\n  unfolding sq_mtx_diag_def by (simp_all add: axis_def vec_eq_iff)\n\n\n\nlemma sq_mtx_vec_mult_diag_axis: \"(\\<d>\\<i>\\<a>\\<g> i. f i) *\\<^sub>V (axis i k) = axis i (f i * k)\"\n  unfolding sq_mtx_diag_vec_mult axis_def by auto\n\nlemma sq_mtx_vec_mult_eq: \"m *\\<^sub>V x = (\\<chi> i. sum (\\<lambda>j. (m $$ i $ j) * (x $ j)) UNIV)\"\n  by (transfer, simp add: matrix_vector_mult_def)\n\nlemma sq_mtx_transpose_transpose[simp]: \"(A\\<^sup>\\<dagger>)\\<^sup>\\<dagger> = A\"\n  by (transfer, simp)\n\nlemma transpose_mult_vec_canon_row[simp]: \"(A\\<^sup>\\<dagger>) *\\<^sub>V (\\<e> i) = \\<r>\\<o>\\<w> i A\"\n  by transfer (simp add: row_def transpose_def axis_def matrix_vector_mult_def)\n\nlemma row_ith[simp]: \"\\<r>\\<o>\\<w> i A = A $$ i\"\n  by transfer (simp add: row_def)\n\nlemma mtx_vec_mult_canon: \"A *\\<^sub>V (\\<e> i) = \\<c>\\<o>\\<l> i A\" \n  by (transfer, simp add: matrix_vector_mult_basis)\n\n\nsubsection \\<open> Ring of square matrices \\<close>\n\ninstantiation sq_mtx :: (finite) ring \nbegin\n\nlift_definition plus_sq_mtx :: \"'a sq_mtx \\<Rightarrow> 'a sq_mtx \\<Rightarrow> 'a sq_mtx\" is \"(+)\" .\n\nlift_definition zero_sq_mtx :: \"'a sq_mtx\" is \"0\" .\n\nlift_definition uminus_sq_mtx :: \"'a sq_mtx \\<Rightarrow> 'a sq_mtx\" is \"uminus\" .\n\nlift_definition minus_sq_mtx :: \"'a sq_mtx \\<Rightarrow> 'a sq_mtx \\<Rightarrow> 'a sq_mtx\" is \"(-)\" .\n\nlift_definition times_sq_mtx :: \"'a sq_mtx \\<Rightarrow> 'a sq_mtx \\<Rightarrow> 'a sq_mtx\" is \"(**)\" .\n\ndeclare plus_sq_mtx.rep_eq [simp]\n    and minus_sq_mtx.rep_eq [simp]\n\ninstance apply intro_classes\n  by(transfer, simp add: algebra_simps matrix_mul_assoc matrix_add_rdistrib matrix_add_ldistrib)+\n\nend\n\nlemma sq_mtx_zero_ith[simp]: \"0 $$ i = 0\"\n  by (transfer, simp)\n\nlemma sq_mtx_zero_nth[simp]: \"0 $$ i $ j = 0\"\n  by transfer simp\n\nlemma sq_mtx_plus_eq: \"A + B = to_mtx (\\<chi> i j. A$$i$j + B$$i$j)\"\n  by transfer (simp add: vec_eq_iff)\n\nlemma sq_mtx_plus_ith[simp]:\"(A + B) $$ i = A $$ i + B $$ i\"\n  unfolding sq_mtx_plus_eq by (simp add: vec_eq_iff)\n\n\n\nlemma sq_mtx_minus_eq: \"A - B = to_mtx (\\<chi> i j. A$$i$j - B$$i$j)\"\n  by transfer (simp add: vec_eq_iff)\n\nlemma sq_mtx_minus_ith[simp]:\"(A - B) $$ i = A $$ i - B $$ i\"\n  unfolding sq_mtx_minus_eq by (simp add: vec_eq_iff)\n\nlemma sq_mtx_times_eq: \"A * B = to_mtx (\\<chi> i j. sum (\\<lambda>k. A$$i$k * B$$k$j) UNIV)\"\n  by transfer (simp add: matrix_matrix_mult_def)\n\nlemma sq_mtx_plus_diag_diag[simp]: \"sq_mtx_diag f + sq_mtx_diag g = (\\<d>\\<i>\\<a>\\<g> i. f i + g i)\"\n  by (subst sq_mtx_eq_iff) (simp add: axis_def)\n\nlemma sq_mtx_minus_diag_diag[simp]: \"sq_mtx_diag f - sq_mtx_diag g = (\\<d>\\<i>\\<a>\\<g> i. f i - g i)\"\n  by (subst sq_mtx_eq_iff) (simp add: axis_def)\n\nlemma sum_sq_mtx_diag[simp]: \"(\\<Sum>n<m. sq_mtx_diag (g n)) = (\\<d>\\<i>\\<a>\\<g> i. \\<Sum>n<m. (g n i))\" for m::nat\n  by (induct m, simp, subst sq_mtx_eq_iff, simp_all)\n\nlemma sq_mtx_mult_diag_diag[simp]: \"sq_mtx_diag f * sq_mtx_diag g = (\\<d>\\<i>\\<a>\\<g> i. f i * g i)\"\n  by (simp add: matrix_mul_diag_diag sq_mtx_diag.abs_eq times_sq_mtx.abs_eq)\n\nlemma sq_mtx_mult_diagl: \"(\\<d>\\<i>\\<a>\\<g> i. f i) * A = to_mtx (\\<chi> i j. f i * A $$ i $ j)\"\n  by transfer (simp add: matrix_mul_diag_matl)\n\nlemma sq_mtx_mult_diagr: \"A * (\\<d>\\<i>\\<a>\\<g> i. f i) = to_mtx (\\<chi> i j. A $$ i $ j * f j)\"\n  by transfer (simp add: matrix_matrix_mul_diag_matr)\n\nlemma mtx_vec_mult_0l[simp]: \"0 *\\<^sub>V x = 0\"\n  by (simp add: sq_mtx_vec_mult.abs_eq zero_sq_mtx_def)\n\nlemma mtx_vec_mult_0r[simp]: \"A *\\<^sub>V 0 = 0\"\n  by (transfer, simp)\n\nlemma mtx_vec_mult_add_rdistr: \"(A + B) *\\<^sub>V x = A *\\<^sub>V x + B *\\<^sub>V x\"\n  unfolding plus_sq_mtx_def \n  apply(transfer)\n  by (simp add: matrix_vector_mult_add_rdistrib)\n\nlemma mtx_vec_mult_add_rdistl: \"A *\\<^sub>V (x + y) = A *\\<^sub>V x + A *\\<^sub>V y\"\n  unfolding plus_sq_mtx_def \n  apply transfer\n  by (simp add: matrix_vector_right_distrib)\n\nlemma mtx_vec_mult_minus_rdistrib: \"(A - B) *\\<^sub>V x = A *\\<^sub>V x - B *\\<^sub>V x\"\n  unfolding minus_sq_mtx_def by(transfer, simp add: matrix_vector_mult_diff_rdistrib)\n\nlemma mtx_vec_mult_minus_ldistrib: \"A *\\<^sub>V (x - y) =  A *\\<^sub>V x -  A *\\<^sub>V y\"\n  by (metis (no_types, lifting) add_diff_cancel diff_add_cancel \n      matrix_vector_right_distrib sq_mtx_vec_mult.rep_eq)\n\nlemma sq_mtx_times_vec_assoc: \"(A * B) *\\<^sub>V x = A *\\<^sub>V (B *\\<^sub>V x)\"\n  by (transfer, simp add: matrix_vector_mul_assoc)\n\nlemma sq_mtx_vec_mult_sum_cols: \"A *\\<^sub>V x = sum (\\<lambda>i. x $ i *\\<^sub>R \\<c>\\<o>\\<l> i A) UNIV\"\n  by(transfer) (simp add: matrix_mult_sum scalar_mult_eq_scaleR)\n\n\nsubsection \\<open> Real normed vector space of square matrices \\<close>\n\ninstantiation sq_mtx :: (finite) real_normed_vector \nbegin\n\ndefinition norm_sq_mtx :: \"'a sq_mtx \\<Rightarrow> real\" where \"\\<parallel>A\\<parallel> = \\<parallel>to_vec A\\<parallel>\\<^sub>o\\<^sub>p\"\n\nlift_definition scaleR_sq_mtx :: \"real \\<Rightarrow> 'a sq_mtx \\<Rightarrow> 'a sq_mtx\" is scaleR .\n\ndefinition sgn_sq_mtx :: \"'a sq_mtx \\<Rightarrow> 'a sq_mtx\" \n  where \"sgn_sq_mtx A = (inverse (\\<parallel>A\\<parallel>)) *\\<^sub>R A\"\n\ndefinition dist_sq_mtx :: \"'a sq_mtx \\<Rightarrow> 'a sq_mtx \\<Rightarrow> real\" \n  where \"dist_sq_mtx A B = \\<parallel>A - B\\<parallel>\" \n\ndefinition uniformity_sq_mtx :: \"('a sq_mtx \\<times> 'a sq_mtx) filter\" \n  where \"uniformity_sq_mtx = (INF e\\<in>{0<..}. principal {(x, y). dist x y < e})\"\n\ndefinition open_sq_mtx :: \"'a sq_mtx set \\<Rightarrow> bool\" \n  where \"open_sq_mtx U = (\\<forall>x\\<in>U. \\<forall>\\<^sub>F (x', y) in uniformity. x' = x \\<longrightarrow> y \\<in> U)\"\n\ninstance apply intro_classes \n  unfolding sgn_sq_mtx_def open_sq_mtx_def dist_sq_mtx_def uniformity_sq_mtx_def\n            prefer 10 \n            apply(transfer, simp add: norm_sq_mtx_def op_norm_triangle)\n           prefer 9 \n           apply(simp_all add: norm_sq_mtx_def zero_sq_mtx_def op_norm_eq_0)\n  by (transfer, simp add: norm_sq_mtx_def op_norm_scaleR algebra_simps)+\n\nend\n\nlemma sq_mtx_scaleR_eq: \"c *\\<^sub>R A = to_mtx (\\<chi> i j. c *\\<^sub>R A $$ i $ j)\"\n  by transfer (simp add: vec_eq_iff)\n\nlemma scaleR_to_mtx_ith[simp]: \"c *\\<^sub>R (to_mtx A) $$ i1 $ i2 = c * A $ i1 $ i2\"\n  by transfer (simp add: scaleR_vec_def)\n\nlemma sq_mtx_scaleR_ith[simp]: \"(c *\\<^sub>R A) $$ i = (c  *\\<^sub>R (A $$ i))\"\n  by (unfold scaleR_sq_mtx_def, transfer, simp)\n\nlemma scaleR_sq_mtx_diag: \"c *\\<^sub>R sq_mtx_diag f = (\\<d>\\<i>\\<a>\\<g> i. c * f i)\"\n  by (subst sq_mtx_eq_iff, simp add: axis_def)\n\nlemma scaleR_mtx_vec_assoc: \"(c *\\<^sub>R A) *\\<^sub>V x = c *\\<^sub>R (A *\\<^sub>V x)\"\n  unfolding scaleR_sq_mtx_def sq_mtx_vec_mult_def apply simp\n  by (simp add: scaleR_matrix_vector_assoc)\n\nlemma mtx_vec_scaleR_commute: \"A *\\<^sub>V (c *\\<^sub>R x) = c *\\<^sub>R (A *\\<^sub>V x)\"\n  unfolding scaleR_sq_mtx_def sq_mtx_vec_mult_def apply(simp, transfer)\n  by (simp add: vector_scaleR_commute)\n\nlemma mtx_times_scaleR_commute: \"A * (c *\\<^sub>R B) = c *\\<^sub>R (A * B)\" for A::\"('n::finite) sq_mtx\"\n  unfolding sq_mtx_scaleR_eq sq_mtx_times_eq \n  apply(simp add: to_mtx_inject)\n  apply(simp add: vec_eq_iff fun_eq_iff)\n  by (simp add: semiring_normalization_rules(19) vector_space_over_itself.scale_sum_right)\n\nlemma le_mtx_norm: \"m \\<in> {\\<parallel>A *\\<^sub>V x\\<parallel> |x. \\<parallel>x\\<parallel> = 1} \\<Longrightarrow> m \\<le> \\<parallel>A\\<parallel>\"\n  using cSup_upper[of _ \"{\\<parallel>(to_vec A) *v x\\<parallel> | x. \\<parallel>x\\<parallel> = 1}\"]\n  by (simp add: op_norm_set_proptys(2) op_norm_def norm_sq_mtx_def sq_mtx_vec_mult.rep_eq)\n\nlemma norm_vec_mult_le: \"\\<parallel>A *\\<^sub>V x\\<parallel> \\<le> (\\<parallel>A\\<parallel>) * (\\<parallel>x\\<parallel>)\"\n  by (simp add: norm_matrix_le_mult_op_norm norm_sq_mtx_def sq_mtx_vec_mult.rep_eq)\n\nlemma bounded_bilinear_sq_mtx_vec_mult: \"bounded_bilinear (\\<lambda>A s. A *\\<^sub>V s)\"\n  apply (rule bounded_bilinear.intro, simp_all add: mtx_vec_mult_add_rdistr \n      mtx_vec_mult_add_rdistl scaleR_mtx_vec_assoc mtx_vec_scaleR_commute)\n  by (rule_tac x=1 in exI, auto intro!: norm_vec_mult_le)\n\nlemma norm_sq_mtx_def2: \"\\<parallel>A\\<parallel> = Sup {\\<parallel>A *\\<^sub>V x\\<parallel> |x. \\<parallel>x\\<parallel> = 1}\"\n  unfolding norm_sq_mtx_def op_norm_def sq_mtx_vec_mult_def by simp\n\nlemma norm_sq_mtx_def3: \"\\<parallel>A\\<parallel> = (SUP x. (\\<parallel>A *\\<^sub>V x\\<parallel>) / (\\<parallel>x\\<parallel>))\"\n  unfolding norm_sq_mtx_def onorm_def sq_mtx_vec_mult_def by simp\n\nlemma norm_sq_mtx_diag: \"\\<parallel>sq_mtx_diag f\\<parallel> = Max {\\<bar>f i\\<bar> |i. i \\<in> UNIV}\"\n  unfolding norm_sq_mtx_def apply transfer\n  by (rule op_norm_diag_mat_eq)\n\nlemma sq_mtx_norm_le_sum_col: \"\\<parallel>A\\<parallel> \\<le> (\\<Sum>i\\<in>UNIV. \\<parallel>\\<c>\\<o>\\<l> i A\\<parallel>)\"\n  using op_norm_le_sum_column[of \"to_vec A\"] \n  apply(simp add: norm_sq_mtx_def)\n  by(transfer, simp add: op_norm_le_sum_column)\n\nlemma norm_le_transpose: \"\\<parallel>A\\<parallel> \\<le> \\<parallel>A\\<^sup>\\<dagger>\\<parallel>\"\n  unfolding norm_sq_mtx_def by transfer (rule op_norm_le_transpose)\n\nlemma norm_eq_norm_transpose[simp]: \"\\<parallel>A\\<^sup>\\<dagger>\\<parallel> = \\<parallel>A\\<parallel>\"\n  using norm_le_transpose[of A] and norm_le_transpose[of \"A\\<^sup>\\<dagger>\"] by simp\n\nlemma norm_column_le_norm: \"\\<parallel>A $$ i\\<parallel> \\<le> \\<parallel>A\\<parallel>\"\n  using norm_vec_mult_le[of \"A\\<^sup>\\<dagger>\" \"\\<e> i\"] by simp\n\n\nsubsection \\<open> Real normed algebra of square matrices \\<close>\n\ninstantiation sq_mtx :: (finite) real_normed_algebra_1\nbegin\n\nlift_definition one_sq_mtx :: \"'a sq_mtx\" is \"to_mtx (mat 1)\" .\n\nlemma sq_mtx_one_idty: \"1 * A = A\" \"A * 1 = A\" for A :: \"'a sq_mtx\"\n  by(transfer, transfer, unfold mat_def matrix_matrix_mult_def, simp add: vec_eq_iff)+\n\nlemma sq_mtx_norm_1: \"\\<parallel>(1::'a sq_mtx)\\<parallel> = 1\"\n  unfolding one_sq_mtx_def norm_sq_mtx_def \n  apply(simp add: op_norm_def)\n  apply(subst cSup_eq[of _ 1])\n  using ex_norm_eq_1 by auto\n\nlemma sq_mtx_norm_times: \"\\<parallel>A * B\\<parallel> \\<le> (\\<parallel>A\\<parallel>) * (\\<parallel>B\\<parallel>)\" for A :: \"'a sq_mtx\"\n  unfolding norm_sq_mtx_def times_sq_mtx_def by(simp add: op_norm_matrix_matrix_mult_le)\n\ninstance \n  apply intro_classes \n  apply(simp_all add: sq_mtx_one_idty sq_mtx_norm_1 sq_mtx_norm_times)\n  apply(simp_all add: to_mtx_inject vec_eq_iff one_sq_mtx_def zero_sq_mtx_def mat_def)\n  by(transfer, simp add: scalar_matrix_assoc matrix_scalar_ac)+\n\nend\n\nlemma sq_mtx_one_ith_simps[simp]: \"1 $$ i $ i = 1\" \"i \\<noteq> j \\<Longrightarrow> 1 $$ i $ j = 0\"\n  unfolding one_sq_mtx_def mat_def by simp_all\n\nlemma of_nat_eq_sq_mtx_diag[simp]: \"of_nat m = (\\<d>\\<i>\\<a>\\<g> i. m)\"\n  by (induct m) (simp, subst sq_mtx_eq_iff, simp add: axis_def)+\n\nlemma mtx_vec_mult_1[simp]: \"1 *\\<^sub>V s = s\"\n  by (auto simp: sq_mtx_vec_mult_def one_sq_mtx_def \n      mat_def vec_eq_iff matrix_vector_mult_def)\n\nlemma sq_mtx_diag_one[simp]: \"(\\<d>\\<i>\\<a>\\<g> i. 1) = 1\"\n  by (subst sq_mtx_eq_iff, simp add: one_sq_mtx_def mat_def axis_def)\n\nabbreviation \"mtx_invertible A \\<equiv> invertible (to_vec A)\"\n\nlemma mtx_invertible_def: \"mtx_invertible A \\<longleftrightarrow> (\\<exists>A'. A' * A = 1 \\<and> A * A' = 1)\"\n  apply (unfold sq_mtx_inv_def times_sq_mtx_def one_sq_mtx_def invertible_def, clarsimp, safe)\n   apply(rule_tac x=\"to_mtx A'\" in exI, simp)\n  by (rule_tac x=\"to_vec A'\" in exI, simp add: to_mtx_inject)\n\n\n\nlemma mtx_invertibleD[simp]:\n  assumes \"mtx_invertible A\" \n  shows \"A\\<^sup>-\\<^sup>1 * A = 1\" and \"A * A\\<^sup>-\\<^sup>1 = 1\"\n  apply (unfold sq_mtx_inv_def times_sq_mtx_def one_sq_mtx_def)\n  using assms by simp_all\n\nlemma mtx_invertible_inv[simp]: \"mtx_invertible A \\<Longrightarrow> mtx_invertible (A\\<^sup>-\\<^sup>1)\"\n  using mtx_invertibleD mtx_invertibleI by blast\n\nlemma mtx_invertible_one[simp]: \"mtx_invertible 1\"\n  by (simp add: one_sq_mtx.rep_eq)\n\nlemma sq_mtx_inv_unique:\n  assumes \"A * B = 1\" and \"B * A = 1\"\n  shows \"A\\<^sup>-\\<^sup>1 = B\"\n  by (metis (no_types, lifting) assms mtx_invertibleD(2) \n      mtx_invertibleI mult.assoc sq_mtx_one_idty(1))\n\nlemma sq_mtx_inv_idempotent[simp]: \"mtx_invertible A \\<Longrightarrow> A\\<^sup>-\\<^sup>1\\<^sup>-\\<^sup>1 = A\"\n  using mtx_invertibleD sq_mtx_inv_unique by blast\n\nlemma sq_mtx_inv_mult:\n  assumes \"mtx_invertible A\" and \"mtx_invertible B\"\n  shows \"(A * B)\\<^sup>-\\<^sup>1 = B\\<^sup>-\\<^sup>1 * A\\<^sup>-\\<^sup>1\"\n  by (simp add: assms matrix_inv_matrix_mul sq_mtx_inv_def times_sq_mtx_def)\n\nlemma sq_mtx_inv_one[simp]: \"1\\<^sup>-\\<^sup>1 = 1\"\n  by (simp add: sq_mtx_inv_unique)\n\ndefinition similar_sq_mtx :: \"('n::finite) sq_mtx \\<Rightarrow> 'n sq_mtx \\<Rightarrow> bool\" (infixr \"\\<sim>\" 25)\n  where \"(A \\<sim> B) \\<longleftrightarrow> (\\<exists> P. mtx_invertible P \\<and> A = P\\<^sup>-\\<^sup>1 * B * P)\"\n\nlemma similar_sq_mtx_matrix: \"(A \\<sim> B) = similar_matrix (to_vec A) (to_vec B)\"\n  apply(unfold similar_matrix_def similar_sq_mtx_def, safe)\n   apply (metis sq_mtx_inv.rep_eq times_sq_mtx.rep_eq)\n  by (metis UNIV_I sq_mtx_inv.abs_eq times_sq_mtx.abs_eq to_mtx_inverse to_vec_inverse)\n\nlemma similar_sq_mtx_refl[simp]: \"A \\<sim> A\"\n  by (unfold similar_sq_mtx_def, rule_tac x=\"1\" in exI, simp)\n\nlemma similar_sq_mtx_simm: \"A \\<sim> B \\<Longrightarrow> B \\<sim> A\"\n  apply(unfold similar_sq_mtx_def, clarsimp)\n  apply(rule_tac x=\"P\\<^sup>-\\<^sup>1\" in exI, simp add: mult.assoc)\n  by (metis mtx_invertibleD(2) mult.assoc mult.left_neutral)\n\nlemma similar_sq_mtx_trans: \"A \\<sim> B \\<Longrightarrow> B \\<sim> C \\<Longrightarrow> A \\<sim> C\"\n  unfolding similar_sq_mtx_matrix using similar_matrix_trans by blast\n\n\n\nlemma power_similiar_sq_mtx_diag_eq:\n  assumes \"mtx_invertible P\"\n      and \"A = P\\<^sup>-\\<^sup>1 * (sq_mtx_diag f) * P\"\n    shows \"A^n = P\\<^sup>-\\<^sup>1 * (\\<d>\\<i>\\<a>\\<g> i. f i^n) * P\"\nproof(induct n, simp_all add: assms)\n  fix n::nat\n  have \"P\\<^sup>-\\<^sup>1 * sq_mtx_diag f * P * (P\\<^sup>-\\<^sup>1 * (\\<d>\\<i>\\<a>\\<g> i. f i ^ n) * P) = \n  P\\<^sup>-\\<^sup>1 * sq_mtx_diag f * (\\<d>\\<i>\\<a>\\<g> i. f i ^ n) * P\"\n    by (metis (no_types, lifting) assms(1) mtx_invertibleD(2) mult.assoc mult.right_neutral)\n  also have \"... = P\\<^sup>-\\<^sup>1 * (\\<d>\\<i>\\<a>\\<g> i. f i * f i ^ n) * P\"\n    by (simp add: mult.assoc) \n  finally show \"P\\<^sup>-\\<^sup>1 * sq_mtx_diag f * P * (P\\<^sup>-\\<^sup>1 * (\\<d>\\<i>\\<a>\\<g> i. f i ^ n) * P) = \n  P\\<^sup>-\\<^sup>1 * (\\<d>\\<i>\\<a>\\<g> i. f i * f i ^ n) * P\" .\nqed\n\nlemma power_similar_sq_mtx_diag:\n  assumes \"A \\<sim> (sq_mtx_diag f)\"\n  shows \"A^n \\<sim> (\\<d>\\<i>\\<a>\\<g> i. f i^n)\"\n  using assms power_similiar_sq_mtx_diag_eq \n  unfolding similar_sq_mtx_def by blast\n\n\nsubsection \\<open> Banach space of square matrices \\<close>\n\nlemma Cauchy_cols:\n  fixes X :: \"nat \\<Rightarrow> ('a::finite) sq_mtx\" \n  assumes \"Cauchy X\"\n  shows \"Cauchy (\\<lambda>n. \\<c>\\<o>\\<l> i (X n))\" \nproof(unfold Cauchy_def dist_norm, clarsimp)\n  fix \\<epsilon>::real assume \"\\<epsilon> > 0\"\n  then obtain M where M_def:\"\\<forall>m\\<ge>M. \\<forall>n\\<ge>M. \\<parallel>X m - X n\\<parallel> < \\<epsilon>\"\n    using \\<open>Cauchy X\\<close> unfolding Cauchy_def by(simp add: dist_sq_mtx_def) metis\n  {fix m n assume \"m \\<ge> M\" and \"n \\<ge> M\"\n    hence \"\\<epsilon> > \\<parallel>X m - X n\\<parallel>\" \n      using M_def by blast\n    moreover have \"\\<parallel>X m - X n\\<parallel> \\<ge> \\<parallel>(X m - X n) *\\<^sub>V \\<e> i\\<parallel>\"\n      by(rule le_mtx_norm[of _ \"X m - X n\"], force)\n    moreover have \"\\<parallel>(X m - X n) *\\<^sub>V \\<e> i\\<parallel> = \\<parallel>X m *\\<^sub>V \\<e> i - X n *\\<^sub>V \\<e> i\\<parallel>\"\n      by (simp add: mtx_vec_mult_minus_rdistrib)\n    moreover have \"... = \\<parallel>\\<c>\\<o>\\<l> i (X m) - \\<c>\\<o>\\<l> i (X n)\\<parallel>\"\n      by (simp add: mtx_vec_mult_minus_rdistrib mtx_vec_mult_canon)\n    ultimately have \"\\<parallel>\\<c>\\<o>\\<l> i (X m) - \\<c>\\<o>\\<l> i (X n)\\<parallel> < \\<epsilon>\" \n      by linarith}\n  thus \"\\<exists>M. \\<forall>m\\<ge>M. \\<forall>n\\<ge>M. \\<parallel>\\<c>\\<o>\\<l> i (X m) - \\<c>\\<o>\\<l> i (X n)\\<parallel> < \\<epsilon>\" \n    by blast\nqed\n\nlemma col_convergence:\n  assumes \"\\<forall>i. (\\<lambda>n. \\<c>\\<o>\\<l> i (X n)) \\<longlonglongrightarrow> L $ i\" \n  shows \"X \\<longlonglongrightarrow> to_mtx (transpose L)\"\nproof(unfold LIMSEQ_def dist_norm, clarsimp)\n  let ?L = \"to_mtx (transpose L)\"\n  let ?a = \"CARD('a)\" fix \\<epsilon>::real assume \"\\<epsilon> > 0\"\n  hence \"\\<epsilon> / ?a > 0\" by simp\n  hence \"\\<forall>i. \\<exists> N. \\<forall>n\\<ge>N. \\<parallel>\\<c>\\<o>\\<l> i (X n) - L $ i\\<parallel> < \\<epsilon>/?a\"\n    using assms unfolding LIMSEQ_def dist_norm convergent_def by blast\n  then obtain N where \"\\<forall>i. \\<forall>n\\<ge>N. \\<parallel>\\<c>\\<o>\\<l> i (X n) - L $ i\\<parallel> < \\<epsilon>/?a\"\n    using finite_nat_minimal_witness[of \"\\<lambda> i n. \\<parallel>\\<c>\\<o>\\<l> i (X n) - L $ i\\<parallel> < \\<epsilon>/?a\"] by blast\n  also have \"\\<And>i n. (\\<c>\\<o>\\<l> i (X n) - L $ i) = (\\<c>\\<o>\\<l> i (X n - ?L))\"\n    unfolding minus_sq_mtx_def by(transfer, simp add: transpose_def vec_eq_iff column_def)\n  ultimately have N_def:\"\\<forall>i. \\<forall>n\\<ge>N. \\<parallel>\\<c>\\<o>\\<l> i (X n - ?L)\\<parallel> < \\<epsilon>/?a\" \n    by auto\n  have \"\\<forall>n\\<ge>N. \\<parallel>X n - ?L\\<parallel> < \\<epsilon>\"\n  proof(rule allI, rule impI)\n    fix n::nat assume \"N \\<le> n\"\n    hence \"\\<forall> i. \\<parallel>\\<c>\\<o>\\<l> i (X n - ?L)\\<parallel> < \\<epsilon>/?a\"\n      using N_def by blast\n    hence \"(\\<Sum>i\\<in>UNIV. \\<parallel>\\<c>\\<o>\\<l> i (X n - ?L)\\<parallel>) < (\\<Sum>(i::'a)\\<in>UNIV. \\<epsilon>/?a)\"\n      using sum_strict_mono[of _ \"\\<lambda>i. \\<parallel>\\<c>\\<o>\\<l> i (X n - ?L)\\<parallel>\"] by force\n    moreover have \"\\<parallel>X n - ?L\\<parallel> \\<le> (\\<Sum>i\\<in>UNIV. \\<parallel>\\<c>\\<o>\\<l> i (X n - ?L)\\<parallel>)\"\n      using sq_mtx_norm_le_sum_col by blast\n    moreover have \"(\\<Sum>(i::'a)\\<in>UNIV. \\<epsilon>/?a) = \\<epsilon>\" \n      by force\n    ultimately show \"\\<parallel>X n - ?L\\<parallel> < \\<epsilon>\" \n      by linarith\n  qed\n  thus \"\\<exists>no. \\<forall>n\\<ge>no. \\<parallel>X n - ?L\\<parallel> < \\<epsilon>\" \n    by blast\nqed\n\ninstance sq_mtx :: (finite) banach\nproof(standard)\n  fix X :: \"nat \\<Rightarrow> 'a sq_mtx\"\n  assume \"Cauchy X\"\n  hence \"\\<And>i. Cauchy (\\<lambda>n. \\<c>\\<o>\\<l> i (X n))\"\n    using Cauchy_cols by blast\n  hence obs: \"\\<forall>i. \\<exists>! L. (\\<lambda>n. \\<c>\\<o>\\<l> i (X n)) \\<longlonglongrightarrow> L\"\n    using Cauchy_convergent convergent_def LIMSEQ_unique by fastforce\n  define L where \"L = (\\<chi> i. lim (\\<lambda>n. \\<c>\\<o>\\<l> i (X n)))\"\n  hence \"\\<forall>i. (\\<lambda>n. \\<c>\\<o>\\<l> i (X n)) \\<longlonglongrightarrow> L $ i\" \n    using obs theI_unique[of \"\\<lambda>L. (\\<lambda>n. \\<c>\\<o>\\<l> _ (X n)) \\<longlonglongrightarrow> L\" \"L $ _\"] by (simp add: lim_def)\n  thus \"convergent X\"\n    using col_convergence unfolding convergent_def by blast\nqed\n\nlemma exp_similiar_sq_mtx_diag_eq:\n  assumes \"mtx_invertible P\"\n      and \"A = P\\<^sup>-\\<^sup>1 * (\\<d>\\<i>\\<a>\\<g> i. f i) * P\"\n    shows \"exp A = P\\<^sup>-\\<^sup>1 * exp (\\<d>\\<i>\\<a>\\<g> i. f i) * P\"\nproof(unfold exp_def power_similiar_sq_mtx_diag_eq[OF assms])\n  have \"(\\<Sum>n. P\\<^sup>-\\<^sup>1 * (\\<d>\\<i>\\<a>\\<g> i. f i ^ n) * P /\\<^sub>R fact n) = \n  (\\<Sum>n. P\\<^sup>-\\<^sup>1 * ((\\<d>\\<i>\\<a>\\<g> i. f i ^ n) /\\<^sub>R fact n) * P)\"\n    by simp\n  also have \"... = (\\<Sum>n. P\\<^sup>-\\<^sup>1 * ((\\<d>\\<i>\\<a>\\<g> i. f i ^ n) /\\<^sub>R fact n)) * P\"\n    apply(subst suminf_multr[OF bounded_linear.summable[OF bounded_linear_mult_right]])\n    unfolding power_sq_mtx_diag[symmetric] by (simp_all add: summable_exp_generic)\n  also have \"... = P\\<^sup>-\\<^sup>1 * (\\<Sum>n. (\\<d>\\<i>\\<a>\\<g> i. f i ^ n) /\\<^sub>R fact n) * P\"\n    apply(subst suminf_mult[of _ \"P\\<^sup>-\\<^sup>1\"])\n    unfolding power_sq_mtx_diag[symmetric] \n    by (simp_all add: summable_exp_generic)\n  finally show \"(\\<Sum>n. P\\<^sup>-\\<^sup>1 * (\\<d>\\<i>\\<a>\\<g> i. f i ^ n) * P /\\<^sub>R fact n) = \n  P\\<^sup>-\\<^sup>1 * (\\<Sum>n. sq_mtx_diag f ^ n /\\<^sub>R fact n) * P\"\n    unfolding power_sq_mtx_diag by simp\nqed\n\nlemma exp_similiar_sq_mtx_diag:\n  assumes \"A \\<sim> sq_mtx_diag f\"\n  shows \"exp A \\<sim> exp (sq_mtx_diag f)\"\n  using assms exp_similiar_sq_mtx_diag_eq \n  unfolding similar_sq_mtx_def by blast\n\nlemma suminf_sq_mtx_diag:\n  assumes \"\\<forall>i. (\\<lambda>n. f n i) sums (suminf (\\<lambda>n. f n i))\"\n  shows \"(\\<Sum>n. (\\<d>\\<i>\\<a>\\<g> i. f n i)) = (\\<d>\\<i>\\<a>\\<g> i. \\<Sum>n. f n i)\"\nproof(rule suminfI, unfold sums_def LIMSEQ_iff, clarsimp simp: norm_sq_mtx_diag)\n  let ?g = \"\\<lambda>n i. \\<bar>(\\<Sum>n<n. f n i) - (\\<Sum>n. f n i)\\<bar>\"\n  fix r::real assume \"r > 0\"\n  have \"\\<forall>i. \\<exists>no. \\<forall>n\\<ge>no. ?g n i < r\"\n    using assms \\<open>r > 0\\<close> unfolding sums_def LIMSEQ_iff by clarsimp \n  then obtain N where key: \"\\<forall>i. \\<forall>n\\<ge>N. ?g n i < r\"\n    using finite_nat_minimal_witness[of \"\\<lambda>i n. ?g n i < r\"] by blast\n  {fix n::nat\n    assume \"n \\<ge> N\"\n    obtain i where i_def: \"Max {x. \\<exists>i. x = ?g n i} = ?g n i\"\n      using cMax_finite_ex[of \"{x. \\<exists>i. x = ?g n i}\"] by auto\n    hence \"?g n i < r\"\n      using key \\<open>n \\<ge> N\\<close> by blast\n    hence \"Max {x. \\<exists>i. x = ?g n i} < r\"\n      unfolding i_def[symmetric] .}\n  thus \"\\<exists>N. \\<forall>n\\<ge>N. Max {x. \\<exists>i. x = ?g n i} < r\"\n    by blast\nqed\n\nlemma exp_sq_mtx_diag: \"exp (sq_mtx_diag f) = (\\<d>\\<i>\\<a>\\<g> i. exp (f i))\"\n  apply(unfold exp_def, simp add: power_sq_mtx_diag scaleR_sq_mtx_diag)\n  apply(rule suminf_sq_mtx_diag)\n  using exp_converges[of \"f _\"] \n  unfolding sums_def LIMSEQ_iff exp_def by force\n\nlemma exp_scaleR_diagonal1:\n  assumes \"mtx_invertible P\" and \"A = P\\<^sup>-\\<^sup>1 * (\\<d>\\<i>\\<a>\\<g> i. f i) * P\"\n    shows \"exp (t *\\<^sub>R A) = P\\<^sup>-\\<^sup>1 * (\\<d>\\<i>\\<a>\\<g> i. exp (t * f i)) * P\"\nproof-\n  have \"exp (t *\\<^sub>R A) = exp (P\\<^sup>-\\<^sup>1 * (t *\\<^sub>R sq_mtx_diag f) * P)\"\n    using assms by simp\n  also have \"... = P\\<^sup>-\\<^sup>1 * (\\<d>\\<i>\\<a>\\<g> i. exp (t * f i)) * P\"\n    by (metis assms(1) exp_similiar_sq_mtx_diag_eq exp_sq_mtx_diag scaleR_sq_mtx_diag)\n  finally show \"exp (t *\\<^sub>R A) = P\\<^sup>-\\<^sup>1 * (\\<d>\\<i>\\<a>\\<g> i. exp (t * f i)) * P\" .\nqed\n\nlemma exp_scaleR_diagonal2:\n  assumes \"mtx_invertible P\" and \"A = P * (\\<d>\\<i>\\<a>\\<g> i. f i) * P\\<^sup>-\\<^sup>1\"\n    shows \"exp (t *\\<^sub>R A) = P * (\\<d>\\<i>\\<a>\\<g> i. exp (t * f i)) * P\\<^sup>-\\<^sup>1\"\n  apply(subst sq_mtx_inv_idempotent[OF assms(1), symmetric])\n  apply(rule exp_scaleR_diagonal1)\n  by (simp_all add: assms)\n\n\nsubsection \\<open> Examples \\<close>\n\ndefinition \"mtx A = to_mtx (vector (map vector A))\"\n\nlemma vector_nth_eq: \"(vector A) $ i = foldr (\\<lambda>x f n. (f (n + 1))(n := x)) A (\\<lambda>n x. 0) 1 i\"\n  unfolding vector_def by simp\n\nlemma mtx_ith_eq[simp]: \"mtx A $$ i $ j = foldr (\\<lambda>x f n. (f (n + 1))(n := x))\n  (map (\\<lambda>l. vec_lambda (foldr (\\<lambda>x f n. (f (n + 1))(n := x)) l (\\<lambda>n x. 0) 1)) A) (\\<lambda>n x. 0) 1 i $ j\"\n  unfolding mtx_def vector_def by (simp add: vector_nth_eq)\n\nsubsubsection \\<open> 2x2 matrices \\<close>\n\nlemma mtx2_eq_iff: \"(mtx \n  ([a1, b1] # \n   [c1, d1] # []) :: 2 sq_mtx) = mtx \n  ([a2, b2] # \n   [c2, d2] # []) \\<longleftrightarrow> a1 = a2 \\<and> b1 = b2 \\<and> c1 = c2 \\<and> d1 = d2\"\n  apply(simp add: sq_mtx_eq_iff, safe)\n  using exhaust_2 by force+\n\nlemma mtx2_to_mtx: \"mtx \n  ([a, b] # \n   [c, d] # []) = \n  to_mtx (\\<chi> i j::2. if i=1 \\<and> j=1 then a \n  else (if i=1 \\<and> j=2 then b \n  else (if i=2 \\<and> j=1 then c \n  else d)))\"\n  apply(subst sq_mtx_eq_iff)\n  using exhaust_2 by force\n\nabbreviation diag2 :: \"real \\<Rightarrow> real \\<Rightarrow> 2 sq_mtx\" \n  where \"diag2 \\<iota>\\<^sub>1 \\<iota>\\<^sub>2 \\<equiv> mtx \n   ([\\<iota>\\<^sub>1, 0] # \n    [0, \\<iota>\\<^sub>2] # [])\"\n\nlemma diag2_eq: \"diag2 (\\<iota> 1) (\\<iota> 2) = (\\<d>\\<i>\\<a>\\<g> i. \\<iota> i)\"\n  apply(simp add: sq_mtx_eq_iff)\n  using exhaust_2 by (force simp: axis_def)\n\nlemma one_mtx2: \"(1::2 sq_mtx) = diag2 1 1\"\n  apply(subst sq_mtx_eq_iff)\n  using exhaust_2 by force\n\nlemma zero_mtx2: \"(0::2 sq_mtx) = diag2 0 0\"\n  by (simp add: sq_mtx_eq_iff)\n\nlemma scaleR_mtx2: \"k *\\<^sub>R mtx \n  ([a, b] # \n   [c, d] # []) = mtx \n  ([k*a, k*b] # \n   [k*c, k*d] # [])\"\n  by (simp add: sq_mtx_eq_iff)\n\nlemma uminus_mtx2: \"-mtx \n  ([a, b] # \n   [c, d] # []) = (mtx \n  ([-a, -b] # \n   [-c, -d] # [])::2 sq_mtx)\"\n  by (simp add: sq_mtx_uminus_eq sq_mtx_eq_iff)\n\nlemma plus_mtx2: \"mtx \n  ([a1, b1] # \n   [c1, d1] # []) + mtx \n  ([a2, b2] # \n   [c2, d2] # []) = ((mtx \n  ([a1+a2, b1+b2] # \n   [c1+c2, d1+d2] # []))::2 sq_mtx)\"\n  by (simp add: sq_mtx_eq_iff)\n\nlemma minus_mtx2: \"mtx \n  ([a1, b1] # \n   [c1, d1] # []) - mtx \n  ([a2, b2] # \n   [c2, d2] # []) = ((mtx \n  ([a1-a2, b1-b2] # \n   [c1-c2, d1-d2] # []))::2 sq_mtx)\"\n  by (simp add: sq_mtx_eq_iff)\n\nlemma times_mtx2: \"mtx \n  ([a1, b1] # \n   [c1, d1] # []) * mtx \n  ([a2, b2] # \n   [c2, d2] # []) = ((mtx \n  ([a1*a2+b1*c2, a1*b2+b1*d2] # \n   [c1*a2+d1*c2, c1*b2+d1*d2] # []))::2 sq_mtx)\"\n  unfolding sq_mtx_times_eq UNIV_2\n  by (simp add: sq_mtx_eq_iff)\n\nsubsubsection \\<open> 3x3 matrices \\<close>\n\nlemma mtx3_to_mtx: \"mtx \n  ([a\\<^sub>1\\<^sub>1, a\\<^sub>1\\<^sub>2, a\\<^sub>1\\<^sub>3] # \n   [a\\<^sub>2\\<^sub>1, a\\<^sub>2\\<^sub>2, a\\<^sub>2\\<^sub>3] # \n   [a\\<^sub>3\\<^sub>1, a\\<^sub>3\\<^sub>2, a\\<^sub>3\\<^sub>3] # []) = \n  to_mtx (\\<chi> i j::3. if i=1 \\<and> j=1 then a\\<^sub>1\\<^sub>1\n  else (if i=1 \\<and> j=2 then a\\<^sub>1\\<^sub>2 \n  else (if i=1 \\<and> j=3 then a\\<^sub>1\\<^sub>3 \n  else (if i=2 \\<and> j=1 then a\\<^sub>2\\<^sub>1\n  else (if i=2 \\<and> j=2 then a\\<^sub>2\\<^sub>2 \n  else (if i=2 \\<and> j=3 then a\\<^sub>2\\<^sub>3 \n  else (if i=3 \\<and> j=1 then a\\<^sub>3\\<^sub>1 \n  else (if i=3 \\<and> j=2 then a\\<^sub>3\\<^sub>2 \n  else a\\<^sub>3\\<^sub>3))))))))\"\n  apply(simp add: sq_mtx_eq_iff)\n  using exhaust_3 by force\n\nabbreviation diag3 :: \"real \\<Rightarrow> real \\<Rightarrow> real \\<Rightarrow> 3 sq_mtx\" \n  where \"diag3 \\<iota>\\<^sub>1 \\<iota>\\<^sub>2 \\<iota>\\<^sub>3 \\<equiv> mtx \n  ([\\<iota>\\<^sub>1, 0, 0] # \n   [0, \\<iota>\\<^sub>2, 0] # \n   [0, 0, \\<iota>\\<^sub>3] # [])\"\n\nlemma diag3_eq: \"diag3 (\\<iota> 1) (\\<iota> 2) (\\<iota> 3) = (\\<d>\\<i>\\<a>\\<g> i. \\<iota> i)\"\n  apply(simp add: sq_mtx_eq_iff)\n  using exhaust_3 by (force simp: axis_def)\n\nlemma one_mtx3: \"(1::3 sq_mtx) = diag3 1 1 1\"\n  apply(subst sq_mtx_eq_iff)\n  using exhaust_3 by force\n\nlemma zero_mtx3: \"(0::3 sq_mtx) = diag3 0 0 0\"\n  by (simp add: sq_mtx_eq_iff)\n\nlemma scaleR_mtx3: \"k *\\<^sub>R mtx \n  ([a\\<^sub>1\\<^sub>1, a\\<^sub>1\\<^sub>2, a\\<^sub>1\\<^sub>3] # \n   [a\\<^sub>2\\<^sub>1, a\\<^sub>2\\<^sub>2, a\\<^sub>2\\<^sub>3] # \n   [a\\<^sub>3\\<^sub>1, a\\<^sub>3\\<^sub>2, a\\<^sub>3\\<^sub>3] # []) = mtx \n  ([k*a\\<^sub>1\\<^sub>1, k*a\\<^sub>1\\<^sub>2, k*a\\<^sub>1\\<^sub>3] # \n   [k*a\\<^sub>2\\<^sub>1, k*a\\<^sub>2\\<^sub>2, k*a\\<^sub>2\\<^sub>3] # \n   [k*a\\<^sub>3\\<^sub>1, k*a\\<^sub>3\\<^sub>2, k*a\\<^sub>3\\<^sub>3] # [])\"\n  by (simp add: sq_mtx_eq_iff)\n\nlemma plus_mtx3: \"mtx \n  ([a\\<^sub>1\\<^sub>1, a\\<^sub>1\\<^sub>2, a\\<^sub>1\\<^sub>3] # \n   [a\\<^sub>2\\<^sub>1, a\\<^sub>2\\<^sub>2, a\\<^sub>2\\<^sub>3] # \n   [a\\<^sub>3\\<^sub>1, a\\<^sub>3\\<^sub>2, a\\<^sub>3\\<^sub>3] # []) + mtx \n  ([b\\<^sub>1\\<^sub>1, b\\<^sub>1\\<^sub>2, b\\<^sub>1\\<^sub>3] # \n   [b\\<^sub>2\\<^sub>1, b\\<^sub>2\\<^sub>2, b\\<^sub>2\\<^sub>3] # \n   [b\\<^sub>3\\<^sub>1, b\\<^sub>3\\<^sub>2, b\\<^sub>3\\<^sub>3] # []) = (mtx \n  ([a\\<^sub>1\\<^sub>1+b\\<^sub>1\\<^sub>1, a\\<^sub>1\\<^sub>2+b\\<^sub>1\\<^sub>2, a\\<^sub>1\\<^sub>3+b\\<^sub>1\\<^sub>3] # \n   [a\\<^sub>2\\<^sub>1+b\\<^sub>2\\<^sub>1, a\\<^sub>2\\<^sub>2+b\\<^sub>2\\<^sub>2, a\\<^sub>2\\<^sub>3+b\\<^sub>2\\<^sub>3] # \n   [a\\<^sub>3\\<^sub>1+b\\<^sub>3\\<^sub>1, a\\<^sub>3\\<^sub>2+b\\<^sub>3\\<^sub>2, a\\<^sub>3\\<^sub>3+b\\<^sub>3\\<^sub>3] # [])::3 sq_mtx)\"\n  by (subst sq_mtx_eq_iff) simp\n\nlemma minus_mtx3: \"mtx \n  ([a\\<^sub>1\\<^sub>1, a\\<^sub>1\\<^sub>2, a\\<^sub>1\\<^sub>3] # \n   [a\\<^sub>2\\<^sub>1, a\\<^sub>2\\<^sub>2, a\\<^sub>2\\<^sub>3] # \n   [a\\<^sub>3\\<^sub>1, a\\<^sub>3\\<^sub>2, a\\<^sub>3\\<^sub>3] # []) - mtx \n  ([b\\<^sub>1\\<^sub>1, b\\<^sub>1\\<^sub>2, b\\<^sub>1\\<^sub>3] # \n   [b\\<^sub>2\\<^sub>1, b\\<^sub>2\\<^sub>2, b\\<^sub>2\\<^sub>3] # \n   [b\\<^sub>3\\<^sub>1, b\\<^sub>3\\<^sub>2, b\\<^sub>3\\<^sub>3] # []) = (mtx \n  ([a\\<^sub>1\\<^sub>1-b\\<^sub>1\\<^sub>1, a\\<^sub>1\\<^sub>2-b\\<^sub>1\\<^sub>2, a\\<^sub>1\\<^sub>3-b\\<^sub>1\\<^sub>3] # \n   [a\\<^sub>2\\<^sub>1-b\\<^sub>2\\<^sub>1, a\\<^sub>2\\<^sub>2-b\\<^sub>2\\<^sub>2, a\\<^sub>2\\<^sub>3-b\\<^sub>2\\<^sub>3] # \n   [a\\<^sub>3\\<^sub>1-b\\<^sub>3\\<^sub>1, a\\<^sub>3\\<^sub>2-b\\<^sub>3\\<^sub>2, a\\<^sub>3\\<^sub>3-b\\<^sub>3\\<^sub>3] # [])::3 sq_mtx)\"\n  by (simp add: sq_mtx_eq_iff)\n\nlemma times_mtx3: \"mtx \n  ([a\\<^sub>1\\<^sub>1, a\\<^sub>1\\<^sub>2, a\\<^sub>1\\<^sub>3] # \n   [a\\<^sub>2\\<^sub>1, a\\<^sub>2\\<^sub>2, a\\<^sub>2\\<^sub>3] # \n   [a\\<^sub>3\\<^sub>1, a\\<^sub>3\\<^sub>2, a\\<^sub>3\\<^sub>3] # []) * mtx \n  ([b\\<^sub>1\\<^sub>1, b\\<^sub>1\\<^sub>2, b\\<^sub>1\\<^sub>3] # \n   [b\\<^sub>2\\<^sub>1, b\\<^sub>2\\<^sub>2, b\\<^sub>2\\<^sub>3] # \n   [b\\<^sub>3\\<^sub>1, b\\<^sub>3\\<^sub>2, b\\<^sub>3\\<^sub>3] # []) = (mtx \n  ([a\\<^sub>1\\<^sub>1*b\\<^sub>1\\<^sub>1+a\\<^sub>1\\<^sub>2*b\\<^sub>2\\<^sub>1+a\\<^sub>1\\<^sub>3*b\\<^sub>3\\<^sub>1, a\\<^sub>1\\<^sub>1*b\\<^sub>1\\<^sub>2+a\\<^sub>1\\<^sub>2*b\\<^sub>2\\<^sub>2+a\\<^sub>1\\<^sub>3*b\\<^sub>3\\<^sub>2, a\\<^sub>1\\<^sub>1*b\\<^sub>1\\<^sub>3+a\\<^sub>1\\<^sub>2*b\\<^sub>2\\<^sub>3+a\\<^sub>1\\<^sub>3*b\\<^sub>3\\<^sub>3] # \n   [a\\<^sub>2\\<^sub>1*b\\<^sub>1\\<^sub>1+a\\<^sub>2\\<^sub>2*b\\<^sub>2\\<^sub>1+a\\<^sub>2\\<^sub>3*b\\<^sub>3\\<^sub>1, a\\<^sub>2\\<^sub>1*b\\<^sub>1\\<^sub>2+a\\<^sub>2\\<^sub>2*b\\<^sub>2\\<^sub>2+a\\<^sub>2\\<^sub>3*b\\<^sub>3\\<^sub>2, a\\<^sub>2\\<^sub>1*b\\<^sub>1\\<^sub>3+a\\<^sub>2\\<^sub>2*b\\<^sub>2\\<^sub>3+a\\<^sub>2\\<^sub>3*b\\<^sub>3\\<^sub>3] # \n   [a\\<^sub>3\\<^sub>1*b\\<^sub>1\\<^sub>1+a\\<^sub>3\\<^sub>2*b\\<^sub>2\\<^sub>1+a\\<^sub>3\\<^sub>3*b\\<^sub>3\\<^sub>1, a\\<^sub>3\\<^sub>1*b\\<^sub>1\\<^sub>2+a\\<^sub>3\\<^sub>2*b\\<^sub>2\\<^sub>2+a\\<^sub>3\\<^sub>3*b\\<^sub>3\\<^sub>2, a\\<^sub>3\\<^sub>1*b\\<^sub>1\\<^sub>3+a\\<^sub>3\\<^sub>2*b\\<^sub>2\\<^sub>3+a\\<^sub>3\\<^sub>3*b\\<^sub>3\\<^sub>3] # [])::3 sq_mtx)\"\n  unfolding sq_mtx_times_eq\n  unfolding UNIV_3 by (simp add: sq_mtx_eq_iff)\n\nend", "meta": {"author": "isabelle-utp", "repo": "Hybrid-Verification", "sha": "ccc5876d270a436a3c4be8c44932256e5d291cf3", "save_path": "github-repos/isabelle/isabelle-utp-Hybrid-Verification", "path": "github-repos/isabelle/isabelle-utp-Hybrid-Verification/Hybrid-Verification-ccc5876d270a436a3c4be8c44932256e5d291cf3/Matrices/SQ_MTX.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8824278757303678, "lm_q2_score": 0.837619959279793, "lm_q1q2_score": 0.739139201336625}}
{"text": "theory \"Fibs\"\n  imports\n    \"../HOLCF_Prelude\"\n    \"../Definedness\"\nbegin\n\nsection \\<open>Fibonacci sequence\\<close>\n\ntext \\<open>\n  In this example, we show that the self-recursive lazy definition of the\n  fibonacci sequence is actually defined and correct.\n\\<close>\n\nfixrec fibs :: \"[Integer]\" where\n  [simp del]: \"fibs = 0 : 1 : zipWith\\<cdot>(+)\\<cdot>fibs\\<cdot>(tail\\<cdot>fibs)\"\n\nfun fib :: \"int \\<Rightarrow> int\" where\n  \"fib n = (if n \\<le> 0 then 0 else if n = 1 then 1 else fib (n - 1) + fib (n - 2))\"\n\ndeclare fib.simps [simp del]\n\nlemma fibs_0 [simp]:\n  \"fibs !! 0 = 0\"\n  by (subst fibs.simps) simp\n\nlemma fibs_1 [simp]:\n  \"fibs !! 1 = 1\"\n  by (subst fibs.simps) simp\n\ntext \\<open>And the proof that @{term \"fibs !! i\"} is defined and the fibs value.\\<close>\n\n(* Strange isabelle simplifier bug? *)\n\n\nlemma nth_fibs:\n  assumes \"defined i\" and \"\\<lbrakk> i \\<rbrakk> \\<ge> 0\" shows \"defined (fibs !! i)\" and \"\\<lbrakk> fibs !! i \\<rbrakk> = fib \\<lbrakk> i \\<rbrakk>\"\n  using assms\nproof(induction i rule:nonneg_full_Int_induct)\n  case (Suc i)\n  case 1\n  with Suc show ?case\n    apply (cases \"\\<lbrakk>i\\<rbrakk> = 0\")\n     apply (subst fibs.simps, (subst fib.simps)?, simp add: nth_zipWith nth_tail)\n    apply (cases \"\\<lbrakk>i\\<rbrakk> = 1\")\n     apply (subst fibs.simps, (subst fib.simps)?, simp add: nth_zipWith nth_tail)\n    apply (subst fibs.simps, (subst fib.simps)?, simp add: nth_zipWith nth_tail)\n    done\nqed (subst fibs.simps, (subst fib.simps)?, simp add: nth_zipWith nth_tail)+\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/HOLCF-Prelude/examples/Fibs.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.882427857178614, "lm_q2_score": 0.8376199673867852, "lm_q1q2_score": 0.7391391929511415}}
{"text": "theory HSV_chapter5 imports Main begin\n\ntext \\<open>Defining a data structure to represent fan-out-free circuits with numbered inputs\\<close>\n\ndatatype \"circuit\" = \n  NOT \"circuit\"\n| AND \"circuit\" \"circuit\"\n| OR \"circuit\" \"circuit\"\n| TRUE\n| FALSE\n| INPUT \"int\"\n\ntext \\<open>A few example circuits\\<close>\n\ndefinition \"circuit1 == AND (INPUT 1) (INPUT 2)\"\ndefinition \"circuit2 == OR (NOT circuit1) FALSE\"\ndefinition \"circuit3 == NOT (NOT circuit2)\"\ndefinition \"circuit4 == AND circuit3 (INPUT 3)\"\n\ntext \\<open>Simulates a circuit given a valuation for each input wire\\<close>\n\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\ntext \\<open>A few example valuations\\<close>\n\ndefinition \"\\<rho>0 == \\<lambda>_. True\"\ndefinition \"\\<rho>1 == \\<rho>0(1 := True, 2 := False, 3 := True)\"\ndefinition \"\\<rho>2 == \\<rho>0(1 := True, 2 := True, 3 := True)\"\n\ntext \\<open>Trying out the simulator\\<close>\n\nvalue \"simulate circuit1 \\<rho>1\"\nvalue \"simulate circuit2 \\<rho>1\"\nvalue \"simulate circuit3 \\<rho>1\"\nvalue \"simulate circuit4 \\<rho>1\"\nvalue \"simulate circuit1 \\<rho>2\"\nvalue \"simulate circuit2 \\<rho>2\"\nvalue \"simulate circuit3 \\<rho>2\"\nvalue \"simulate circuit4 \\<rho>2\"\n\ntext \\<open>A function that switches each pair of wires entering an OR or AND gate\\<close>\n\nfun mirror where\n  \"mirror (NOT c) = NOT (mirror c)\"\n| \"mirror (AND c1 c2) = AND (mirror c2) (mirror c1)\"\n| \"mirror (OR c1 c2) = OR (mirror c2) (mirror c1)\"\n| \"mirror TRUE = TRUE\"\n| \"mirror FALSE = FALSE\"\n| \"mirror (INPUT i) = INPUT i\"\n\nvalue \"circuit1\"\nvalue \"mirror circuit1\"\nvalue \"circuit2\"\nvalue \"mirror circuit2\"\n\ntext \\<open>The following non-theorem is easily contradicted.\\<close>\n\ntheorem \"mirror c = c\" \n  oops\n\ntext \\<open>Proving that mirroring doesn't affect simulation behaviour.\\<close>\n\ntheorem \"simulate (mirror c) \\<rho> = simulate c \\<rho>\"\n  by (induct c, auto)\n\ntext \\<open>A Fibonacci function that demonstrates complex recursion schemes\\<close>\n\nfun f :: \"nat \\<Rightarrow> nat\" where\n  \"f (Suc (Suc n)) = f n + f (Suc n)\"\n| \"f (Suc 0) = 1\"\n| \"f 0 = 1\"\n\nthm f.induct (* rule induction theorem for f *)\n\ntext \\<open>We need to prove a stronger version of the theorem below\n  first, in order to make the inductive step work. Just like how \n  it often goes with loop invariants in Dafny!\\<close>\nlemma helper: \"f n \\<ge> n \\<and> f n \\<ge> 1\"\n  by (rule f.induct[of \"\\<lambda>n. f n \\<ge> n \\<and> f n \\<ge> 1\"], auto)\n\ntext \\<open>The nth Fibonacci number is greater than or equal to n\\<close>\ntheorem \"f n \\<ge> n\" \n  using helper by simp\n\ntext \\<open>A function that optimises a circuit by removing pairs of consecutive NOT gates\\<close>\n\nfun opt_NOT where\n  \"opt_NOT (NOT (NOT c)) = opt_NOT c\"\n| \"opt_NOT (NOT c) = NOT (opt_NOT c)\"\n| \"opt_NOT (AND c1 c2) = AND (opt_NOT c1) (opt_NOT c2)\"\n| \"opt_NOT (OR c1 c2) = OR (opt_NOT c1) (opt_NOT c2)\"\n| \"opt_NOT TRUE = TRUE\"\n| \"opt_NOT FALSE = FALSE\"\n| \"opt_NOT (INPUT i) = INPUT i\"\n\ntext \\<open>Trying out the optimiser\\<close>\n\nvalue \"circuit1\"\nvalue \"opt_NOT circuit1\"\nvalue \"circuit2\"\nvalue \"opt_NOT circuit2\"\nvalue \"circuit3\"\nvalue \"opt_NOT circuit3\"\nvalue \"circuit4\"\nvalue \"opt_NOT circuit4\"\n\ntext \\<open>The following non-theorem is easily contradicted.\\<close>\n\ntheorem \"opt_NOT c = c\" \n  oops\n\ntext \\<open>The following theorem says that the optimiser is sound.\\<close>\n\ntheorem opt_NOT_is_sound: \"simulate (opt_NOT c) \\<rho> = simulate c \\<rho>\"\n  by (induct rule:opt_NOT.induct, auto)\n\ntext \\<open>The following function calculates the area of a circuit (i.e. number of gates).\\<close>\n\nfun area :: \"circuit \\<Rightarrow> nat\" where\n  \"area (NOT c) = 1 + area c\"\n| \"area (AND c1 c2) = 1 + area c1 + area c2\"\n| \"area (OR c1 c2) = 1 + area c1 + area c2\"\n| \"area _ = 0\"\n\nend\n", "meta": {"author": "HarryAnkers", "repo": "HardwareSoftwareCW-Software", "sha": "d95d88bd8a34c4839224a3686c531aba3be5cab9", "save_path": "github-repos/isabelle/HarryAnkers-HardwareSoftwareCW-Software", "path": "github-repos/isabelle/HarryAnkers-HardwareSoftwareCW-Software/HardwareSoftwareCW-Software-d95d88bd8a34c4839224a3686c531aba3be5cab9/Isabelle/isabelle/HSV_chapter5.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869981319863, "lm_q2_score": 0.8438951064805861, "lm_q1q2_score": 0.7390723620429055}}
{"text": "(*  Title:      HOL/ex/CTL.thy\n    Author:     Gertrud Bauer\n*)\n\nsection \\<open>CTL formulae\\<close>\n\ntheory CTL\nimports Main\nbegin\n\ntext \\<open>\n  We formalize basic concepts of Computational Tree Logic (CTL) \\<^cite>\\<open>\"McMillan-PhDThesis\"\\<close> within the simply-typed\n  set theory of HOL.\n\n  By using the common technique of ``shallow embedding'', a CTL formula is\n  identified with the corresponding set of states where it holds.\n  Consequently, CTL operations such as negation, conjunction, disjunction\n  simply become complement, intersection, union of sets. We only require a\n  separate operation for implication, as point-wise inclusion is usually not\n  encountered in plain set-theory.\n\\<close>\n\nlemmas [intro!] = Int_greatest Un_upper2 Un_upper1 Int_lower1 Int_lower2\n\ntype_synonym 'a ctl = \"'a set\"\n\ndefinition imp :: \"'a ctl \\<Rightarrow> 'a ctl \\<Rightarrow> 'a ctl\"  (infixr \"\\<rightarrow>\" 75)\n  where \"p \\<rightarrow> q = - p \\<union> q\"\n\nlemma [intro!]: \"p \\<inter> p \\<rightarrow> q \\<subseteq> q\" unfolding imp_def by auto\nlemma [intro!]: \"p \\<subseteq> (q \\<rightarrow> p)\" unfolding imp_def by rule\n\n\ntext \\<open>\n  \\<^smallskip>\n  The CTL path operators are more interesting; they are based on an arbitrary,\n  but fixed model \\<open>\\<M>\\<close>, which is simply a transition relation over states\n  \\<^typ>\\<open>'a\\<close>.\n\\<close>\n\naxiomatization \\<M> :: \"('a \\<times> 'a) set\"\n\ntext \\<open>\n  The operators \\<open>\\<^bold>E\\<^bold>X\\<close>, \\<open>\\<^bold>E\\<^bold>F\\<close>, \\<open>\\<^bold>E\\<^bold>G\\<close> are taken as primitives, while \\<open>\\<^bold>A\\<^bold>X\\<close>,\n  \\<open>\\<^bold>A\\<^bold>F\\<close>, \\<open>\\<^bold>A\\<^bold>G\\<close> are defined as derived ones. The formula \\<open>\\<^bold>E\\<^bold>X p\\<close> holds in a\n  state \\<open>s\\<close>, iff there is a successor state \\<open>s'\\<close> (with respect to the model\n  \\<open>\\<M>\\<close>), such that \\<open>p\\<close> holds in \\<open>s'\\<close>. The formula \\<open>\\<^bold>E\\<^bold>F p\\<close> holds in a state\n  \\<open>s\\<close>, iff there is a path in \\<open>\\<M>\\<close>, starting from \\<open>s\\<close>, such that there exists a\n  state \\<open>s'\\<close> on the path, such that \\<open>p\\<close> holds in \\<open>s'\\<close>. The formula \\<open>\\<^bold>E\\<^bold>G p\\<close>\n  holds in a state \\<open>s\\<close>, iff there is a path, starting from \\<open>s\\<close>, such that for\n  all states \\<open>s'\\<close> on the path, \\<open>p\\<close> holds in \\<open>s'\\<close>. It is easy to see that \\<open>\\<^bold>E\\<^bold>F\n  p\\<close> and \\<open>\\<^bold>E\\<^bold>G p\\<close> may be expressed using least and greatest fixed points\n  \\<^cite>\\<open>\"McMillan-PhDThesis\"\\<close>.\n\\<close>\n\ndefinition EX  (\"\\<^bold>E\\<^bold>X _\" [80] 90)\n  where [simp]: \"\\<^bold>E\\<^bold>X p = {s. \\<exists>s'. (s, s') \\<in> \\<M> \\<and> s' \\<in> p}\"\n\ndefinition EF (\"\\<^bold>E\\<^bold>F _\" [80] 90)\n  where [simp]: \"\\<^bold>E\\<^bold>F p = lfp (\\<lambda>s. p \\<union> \\<^bold>E\\<^bold>X s)\"\n\ndefinition EG (\"\\<^bold>E\\<^bold>G _\" [80] 90)\n  where [simp]: \"\\<^bold>E\\<^bold>G p = gfp (\\<lambda>s. p \\<inter> \\<^bold>E\\<^bold>X s)\"\n\ntext \\<open>\n  \\<open>\\<^bold>A\\<^bold>X\\<close>, \\<open>\\<^bold>A\\<^bold>F\\<close> and \\<open>\\<^bold>A\\<^bold>G\\<close> are now defined dually in terms of \\<open>\\<^bold>E\\<^bold>X\\<close>,\n  \\<open>\\<^bold>E\\<^bold>F\\<close> and \\<open>\\<^bold>E\\<^bold>G\\<close>.\n\\<close>\n\ndefinition AX  (\"\\<^bold>A\\<^bold>X _\" [80] 90)\n  where [simp]: \"\\<^bold>A\\<^bold>X p = - \\<^bold>E\\<^bold>X - p\"\ndefinition AF  (\"\\<^bold>A\\<^bold>F _\" [80] 90)\n  where [simp]: \"\\<^bold>A\\<^bold>F p = - \\<^bold>E\\<^bold>G - p\"\ndefinition AG  (\"\\<^bold>A\\<^bold>G _\" [80] 90)\n  where [simp]: \"\\<^bold>A\\<^bold>G p = - \\<^bold>E\\<^bold>F - p\"\n\n\nsubsection \\<open>Basic fixed point properties\\<close>\n\ntext \\<open>\n  First of all, we use the de-Morgan property of fixed points.\n\\<close>\n\nlemma lfp_gfp: \"lfp f = - gfp (\\<lambda>s::'a set. - (f (- s)))\"\nproof\n  show \"lfp f \\<subseteq> - gfp (\\<lambda>s. - f (- s))\"\n  proof\n    show \"x \\<in> - gfp (\\<lambda>s. - f (- s))\" if l: \"x \\<in> lfp f\" for x\n    proof\n      assume \"x \\<in> gfp (\\<lambda>s. - f (- s))\"\n      then obtain u where \"x \\<in> u\" and \"u \\<subseteq> - f (- u)\"\n        by (auto simp add: gfp_def)\n      then have \"f (- u) \\<subseteq> - u\" by auto\n      then have \"lfp f \\<subseteq> - u\" by (rule lfp_lowerbound)\n      from l and this have \"x \\<notin> u\" by auto\n      with \\<open>x \\<in> u\\<close> show False by contradiction\n    qed\n  qed\n  show \"- gfp (\\<lambda>s. - f (- s)) \\<subseteq> lfp f\"\n  proof (rule lfp_greatest)\n    fix u\n    assume \"f u \\<subseteq> u\"\n    then have \"- u \\<subseteq> - f u\" by auto\n    then have \"- u \\<subseteq> - f (- (- u))\" by simp\n    then have \"- u \\<subseteq> gfp (\\<lambda>s. - f (- s))\" by (rule gfp_upperbound)\n    then show \"- gfp (\\<lambda>s. - f (- s)) \\<subseteq> u\" by auto\n  qed\nqed\n\nlemma lfp_gfp': \"- lfp f = gfp (\\<lambda>s::'a set. - (f (- s)))\"\n  by (simp add: lfp_gfp)\n\nlemma gfp_lfp': \"- gfp f = lfp (\\<lambda>s::'a set. - (f (- s)))\"\n  by (simp add: lfp_gfp)\n\ntext \\<open>\n  In order to give dual fixed point representations of \\<^term>\\<open>\\<^bold>A\\<^bold>F p\\<close> and\n  \\<^term>\\<open>\\<^bold>A\\<^bold>G p\\<close>:\n\\<close>\n\nlemma AF_lfp: \"\\<^bold>A\\<^bold>F p = lfp (\\<lambda>s. p \\<union> \\<^bold>A\\<^bold>X s)\"\n  by (simp add: lfp_gfp)\n\nlemma AG_gfp: \"\\<^bold>A\\<^bold>G p = gfp (\\<lambda>s. p \\<inter> \\<^bold>A\\<^bold>X s)\"\n  by (simp add: lfp_gfp)\n\nlemma EF_fp: \"\\<^bold>E\\<^bold>F p = p \\<union> \\<^bold>E\\<^bold>X \\<^bold>E\\<^bold>F p\"\nproof -\n  have \"mono (\\<lambda>s. p \\<union> \\<^bold>E\\<^bold>X s)\" by rule auto\n  then show ?thesis by (simp only: EF_def) (rule lfp_unfold)\nqed\n\nlemma AF_fp: \"\\<^bold>A\\<^bold>F p = p \\<union> \\<^bold>A\\<^bold>X \\<^bold>A\\<^bold>F p\"\nproof -\n  have \"mono (\\<lambda>s. p \\<union> \\<^bold>A\\<^bold>X s)\" by rule auto\n  then show ?thesis by (simp only: AF_lfp) (rule lfp_unfold)\nqed\n\nlemma EG_fp: \"\\<^bold>E\\<^bold>G p = p \\<inter> \\<^bold>E\\<^bold>X \\<^bold>E\\<^bold>G p\"\nproof -\n  have \"mono (\\<lambda>s. p \\<inter> \\<^bold>E\\<^bold>X s)\" by rule auto\n  then show ?thesis by (simp only: EG_def) (rule gfp_unfold)\nqed\n\ntext \\<open>\n  From the greatest fixed point definition of \\<^term>\\<open>\\<^bold>A\\<^bold>G p\\<close>, we derive as\n  a consequence of the Knaster-Tarski theorem on the one hand that \\<^term>\\<open>\\<^bold>A\\<^bold>G p\\<close> is a fixed point of the monotonic function\n  \\<^term>\\<open>\\<lambda>s. p \\<inter> \\<^bold>A\\<^bold>X s\\<close>.\n\\<close>\n\nlemma AG_fp: \"\\<^bold>A\\<^bold>G p = p \\<inter> \\<^bold>A\\<^bold>X \\<^bold>A\\<^bold>G p\"\nproof -\n  have \"mono (\\<lambda>s. p \\<inter> \\<^bold>A\\<^bold>X s)\" by rule auto\n  then show ?thesis by (simp only: AG_gfp) (rule gfp_unfold)\nqed\n\ntext \\<open>\n  This fact may be split up into two inequalities (merely using transitivity\n  of \\<open>\\<subseteq>\\<close>, which is an instance of the overloaded \\<open>\\<le>\\<close> in Isabelle/HOL).\n\\<close>\n\nlemma AG_fp_1: \"\\<^bold>A\\<^bold>G p \\<subseteq> p\"\nproof -\n  note AG_fp also have \"p \\<inter> \\<^bold>A\\<^bold>X \\<^bold>A\\<^bold>G p \\<subseteq> p\" by auto\n  finally show ?thesis .\nqed\n\nlemma AG_fp_2: \"\\<^bold>A\\<^bold>G p \\<subseteq> \\<^bold>A\\<^bold>X \\<^bold>A\\<^bold>G p\"\nproof -\n  note AG_fp also have \"p \\<inter> \\<^bold>A\\<^bold>X \\<^bold>A\\<^bold>G p \\<subseteq> \\<^bold>A\\<^bold>X \\<^bold>A\\<^bold>G p\" by auto\n  finally show ?thesis .\nqed\n\ntext \\<open>\n  On the other hand, we have from the Knaster-Tarski fixed point theorem that\n  any other post-fixed point of \\<^term>\\<open>\\<lambda>s. p \\<inter> \\<^bold>A\\<^bold>X s\\<close> is smaller than\n  \\<^term>\\<open>\\<^bold>A\\<^bold>G p\\<close>. A post-fixed point is a set of states \\<open>q\\<close> such that \\<^term>\\<open>q \\<subseteq> p \\<inter> \\<^bold>A\\<^bold>X q\\<close>. This leads to the following co-induction principle for\n  \\<^term>\\<open>\\<^bold>A\\<^bold>G p\\<close>.\n\\<close>\n\nlemma AG_I: \"q \\<subseteq> p \\<inter> \\<^bold>A\\<^bold>X q \\<Longrightarrow> q \\<subseteq> \\<^bold>A\\<^bold>G p\"\n  by (simp only: AG_gfp) (rule gfp_upperbound)\n\n\nsubsection \\<open>The tree induction principle \\label{sec:calc-ctl-tree-induct}\\<close>\n\ntext \\<open>\n  With the most basic facts available, we are now able to establish a few more\n  interesting results, leading to the \\<^emph>\\<open>tree induction\\<close> principle for \\<open>\\<^bold>A\\<^bold>G\\<close>\n  (see below). We will use some elementary monotonicity and distributivity\n  rules.\n\\<close>\n\nlemma AX_int: \"\\<^bold>A\\<^bold>X (p \\<inter> q) = \\<^bold>A\\<^bold>X p \\<inter> \\<^bold>A\\<^bold>X q\" by auto\nlemma AX_mono: \"p \\<subseteq> q \\<Longrightarrow> \\<^bold>A\\<^bold>X p \\<subseteq> \\<^bold>A\\<^bold>X q\" by auto\nlemma AG_mono: \"p \\<subseteq> q \\<Longrightarrow> \\<^bold>A\\<^bold>G p \\<subseteq> \\<^bold>A\\<^bold>G q\"\n  by (simp only: AG_gfp, rule gfp_mono) auto\n\ntext \\<open>\n  The formula \\<^term>\\<open>AG p\\<close> implies \\<^term>\\<open>AX p\\<close> (we use substitution of\n  \\<open>\\<subseteq>\\<close> with monotonicity).\n\\<close>\n\nlemma AG_AX: \"\\<^bold>A\\<^bold>G p \\<subseteq> \\<^bold>A\\<^bold>X p\"\nproof -\n  have \"\\<^bold>A\\<^bold>G p \\<subseteq> \\<^bold>A\\<^bold>X \\<^bold>A\\<^bold>G p\" by (rule AG_fp_2)\n  also have \"\\<^bold>A\\<^bold>G p \\<subseteq> p\" by (rule AG_fp_1)\n  moreover note AX_mono\n  finally show ?thesis .\nqed\n\ntext \\<open>\n  Furthermore we show idempotency of the \\<open>\\<^bold>A\\<^bold>G\\<close> operator. The proof is a good\n  example of how accumulated facts may get used to feed a single rule step.\n\\<close>\n\nlemma AG_AG: \"\\<^bold>A\\<^bold>G \\<^bold>A\\<^bold>G p = \\<^bold>A\\<^bold>G p\"\nproof\n  show \"\\<^bold>A\\<^bold>G \\<^bold>A\\<^bold>G p \\<subseteq> \\<^bold>A\\<^bold>G p\" by (rule AG_fp_1)\nnext\n  show \"\\<^bold>A\\<^bold>G p \\<subseteq> \\<^bold>A\\<^bold>G \\<^bold>A\\<^bold>G p\"\n  proof (rule AG_I)\n    have \"\\<^bold>A\\<^bold>G p \\<subseteq> \\<^bold>A\\<^bold>G p\" ..\n    moreover have \"\\<^bold>A\\<^bold>G p \\<subseteq> \\<^bold>A\\<^bold>X \\<^bold>A\\<^bold>G p\" by (rule AG_fp_2)\n    ultimately show \"\\<^bold>A\\<^bold>G p \\<subseteq> \\<^bold>A\\<^bold>G p \\<inter> \\<^bold>A\\<^bold>X \\<^bold>A\\<^bold>G p\" ..\n  qed\nqed\n\ntext \\<open>\n  \\<^smallskip>\n  We now give an alternative characterization of the \\<open>\\<^bold>A\\<^bold>G\\<close> operator, which\n  describes the \\<open>\\<^bold>A\\<^bold>G\\<close> operator in an ``operational'' way by tree induction:\n  In a state holds \\<^term>\\<open>AG p\\<close> iff in that state holds \\<open>p\\<close>, and in all\n  reachable states \\<open>s\\<close> follows from the fact that \\<open>p\\<close> holds in \\<open>s\\<close>, that \\<open>p\\<close>\n  also holds in all successor states of \\<open>s\\<close>. We use the co-induction principle\n  @{thm [source] AG_I} to establish this in a purely algebraic manner.\n\\<close>\n\ntheorem AG_induct: \"p \\<inter> \\<^bold>A\\<^bold>G (p \\<rightarrow> \\<^bold>A\\<^bold>X p) = \\<^bold>A\\<^bold>G p\"\nproof\n  show \"p \\<inter> \\<^bold>A\\<^bold>G (p \\<rightarrow> \\<^bold>A\\<^bold>X p) \\<subseteq> \\<^bold>A\\<^bold>G p\"  (is \"?lhs \\<subseteq> _\")\n  proof (rule AG_I)\n    show \"?lhs \\<subseteq> p \\<inter> \\<^bold>A\\<^bold>X ?lhs\"\n    proof\n      show \"?lhs \\<subseteq> p\" ..\n      show \"?lhs \\<subseteq> \\<^bold>A\\<^bold>X ?lhs\"\n      proof -\n        {\n          have \"\\<^bold>A\\<^bold>G (p \\<rightarrow> \\<^bold>A\\<^bold>X p) \\<subseteq> p \\<rightarrow> \\<^bold>A\\<^bold>X p\" by (rule AG_fp_1)\n          also have \"p \\<inter> p \\<rightarrow> \\<^bold>A\\<^bold>X p \\<subseteq> \\<^bold>A\\<^bold>X p\" ..\n          finally have \"?lhs \\<subseteq> \\<^bold>A\\<^bold>X p\" by auto\n        }\n        moreover\n        {\n          have \"p \\<inter> \\<^bold>A\\<^bold>G (p \\<rightarrow> \\<^bold>A\\<^bold>X p) \\<subseteq> \\<^bold>A\\<^bold>G (p \\<rightarrow> \\<^bold>A\\<^bold>X p)\" ..\n          also have \"\\<dots> \\<subseteq> \\<^bold>A\\<^bold>X \\<dots>\" by (rule AG_fp_2)\n          finally have \"?lhs \\<subseteq> \\<^bold>A\\<^bold>X \\<^bold>A\\<^bold>G (p \\<rightarrow> \\<^bold>A\\<^bold>X p)\" .\n        }\n        ultimately have \"?lhs \\<subseteq> \\<^bold>A\\<^bold>X p \\<inter> \\<^bold>A\\<^bold>X \\<^bold>A\\<^bold>G (p \\<rightarrow> \\<^bold>A\\<^bold>X p)\" ..\n        also have \"\\<dots> = \\<^bold>A\\<^bold>X ?lhs\" by (simp only: AX_int)\n        finally show ?thesis .\n      qed\n    qed\n  qed\nnext\n  show \"\\<^bold>A\\<^bold>G p \\<subseteq> p \\<inter> \\<^bold>A\\<^bold>G (p \\<rightarrow> \\<^bold>A\\<^bold>X p)\"\n  proof\n    show \"\\<^bold>A\\<^bold>G p \\<subseteq> p\" by (rule AG_fp_1)\n    show \"\\<^bold>A\\<^bold>G p \\<subseteq> \\<^bold>A\\<^bold>G (p \\<rightarrow> \\<^bold>A\\<^bold>X p)\"\n    proof -\n      have \"\\<^bold>A\\<^bold>G p = \\<^bold>A\\<^bold>G \\<^bold>A\\<^bold>G p\" by (simp only: AG_AG)\n      also have \"\\<^bold>A\\<^bold>G p \\<subseteq> \\<^bold>A\\<^bold>X p\" by (rule AG_AX) moreover note AG_mono\n      also have \"\\<^bold>A\\<^bold>X p \\<subseteq> (p \\<rightarrow> \\<^bold>A\\<^bold>X p)\" .. moreover note AG_mono\n      finally show ?thesis .\n    qed\n  qed\nqed\n\n\nsubsection \\<open>An application of tree induction \\label{sec:calc-ctl-commute}\\<close>\n\ntext \\<open>\n  Further interesting properties of CTL expressions may be demonstrated with\n  the help of tree induction; here we show that \\<open>\\<^bold>A\\<^bold>X\\<close> and \\<open>\\<^bold>A\\<^bold>G\\<close> commute.\n\\<close>\n\ntheorem AG_AX_commute: \"\\<^bold>A\\<^bold>G \\<^bold>A\\<^bold>X p = \\<^bold>A\\<^bold>X \\<^bold>A\\<^bold>G p\"\nproof -\n  have \"\\<^bold>A\\<^bold>G \\<^bold>A\\<^bold>X p = \\<^bold>A\\<^bold>X p \\<inter> \\<^bold>A\\<^bold>X \\<^bold>A\\<^bold>G \\<^bold>A\\<^bold>X p\" by (rule AG_fp)\n  also have \"\\<dots> = \\<^bold>A\\<^bold>X (p \\<inter> \\<^bold>A\\<^bold>G \\<^bold>A\\<^bold>X p)\" by (simp only: AX_int)\n  also have \"p \\<inter> \\<^bold>A\\<^bold>G \\<^bold>A\\<^bold>X p = \\<^bold>A\\<^bold>G p\"  (is \"?lhs = _\")\n  proof\n    have \"\\<^bold>A\\<^bold>X p \\<subseteq> p \\<rightarrow> \\<^bold>A\\<^bold>X p\" ..\n    also have \"p \\<inter> \\<^bold>A\\<^bold>G (p \\<rightarrow> \\<^bold>A\\<^bold>X p) = \\<^bold>A\\<^bold>G p\" by (rule AG_induct)\n    also note Int_mono AG_mono\n    ultimately show \"?lhs \\<subseteq> \\<^bold>A\\<^bold>G p\" by fast\n  next\n    have \"\\<^bold>A\\<^bold>G p \\<subseteq> p\" by (rule AG_fp_1)\n    moreover\n    {\n      have \"\\<^bold>A\\<^bold>G p = \\<^bold>A\\<^bold>G \\<^bold>A\\<^bold>G p\" by (simp only: AG_AG)\n      also have \"\\<^bold>A\\<^bold>G p \\<subseteq> \\<^bold>A\\<^bold>X p\" by (rule AG_AX)\n      also note AG_mono\n      ultimately have \"\\<^bold>A\\<^bold>G p \\<subseteq> \\<^bold>A\\<^bold>G \\<^bold>A\\<^bold>X p\" .\n    }\n    ultimately show \"\\<^bold>A\\<^bold>G p \\<subseteq> ?lhs\" ..\n  qed\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/ex/CTL.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8757869948899665, "lm_q2_score": 0.843895106480586, "lm_q1q2_score": 0.7390723593069807}}
{"text": "(*  Title:      HOL/Boolean_Algebras.thy\n    Author:     Brian Huffman\n    Author:     Florian Haftmann\n*)\n\nsection \\<open>Boolean Algebras\\<close>\n\ntheory Boolean_Algebras\n  imports Lattices\nbegin\n\nsubsection \\<open>Abstract boolean algebra\\<close>\n\nlocale abstract_boolean_algebra = conj: abel_semigroup \\<open>(\\<^bold>\\<sqinter>)\\<close> + disj: abel_semigroup \\<open>(\\<^bold>\\<squnion>)\\<close>\n  for conj :: \\<open>'a \\<Rightarrow> 'a \\<Rightarrow> 'a\\<close>  (infixr \\<open>\\<^bold>\\<sqinter>\\<close> 70)\n    and disj :: \\<open>'a \\<Rightarrow> 'a \\<Rightarrow> 'a\\<close>  (infixr \\<open>\\<^bold>\\<squnion>\\<close> 65) +\n  fixes compl :: \\<open>'a \\<Rightarrow> 'a\\<close>  (\\<open>\\<^bold>- _\\<close> [81] 80)\n    and zero :: \\<open>'a\\<close>  (\\<open>\\<^bold>0\\<close>)\n    and one  :: \\<open>'a\\<close>  (\\<open>\\<^bold>1\\<close>)\n  assumes conj_disj_distrib: \\<open>x \\<^bold>\\<sqinter> (y \\<^bold>\\<squnion> z) = (x \\<^bold>\\<sqinter> y) \\<^bold>\\<squnion> (x \\<^bold>\\<sqinter> z)\\<close>\n    and disj_conj_distrib: \\<open>x \\<^bold>\\<squnion> (y \\<^bold>\\<sqinter> z) = (x \\<^bold>\\<squnion> y) \\<^bold>\\<sqinter> (x \\<^bold>\\<squnion> z)\\<close>\n    and conj_one_right: \\<open>x \\<^bold>\\<sqinter> \\<^bold>1 = x\\<close>\n    and disj_zero_right: \\<open>x \\<^bold>\\<squnion> \\<^bold>0 = x\\<close>\n    and conj_cancel_right [simp]: \\<open>x \\<^bold>\\<sqinter> \\<^bold>- x = \\<^bold>0\\<close>\n    and disj_cancel_right [simp]: \\<open>x \\<^bold>\\<squnion> \\<^bold>- x = \\<^bold>1\\<close>\nbegin\n\nsublocale conj: semilattice_neutr \\<open>(\\<^bold>\\<sqinter>)\\<close> \\<open>\\<^bold>1\\<close>\nproof\n  show \"x \\<^bold>\\<sqinter> \\<^bold>1 = x\" for x \n    by (fact conj_one_right)\n  show \"x \\<^bold>\\<sqinter> x = x\" for x\n  proof -\n    have \"x \\<^bold>\\<sqinter> x = (x \\<^bold>\\<sqinter> x) \\<^bold>\\<squnion> \\<^bold>0\"\n      by (simp add: disj_zero_right)\n    also have \"\\<dots> = (x \\<^bold>\\<sqinter> x) \\<^bold>\\<squnion> (x \\<^bold>\\<sqinter> \\<^bold>- x)\"\n      by simp\n    also have \"\\<dots> = x \\<^bold>\\<sqinter> (x \\<^bold>\\<squnion> \\<^bold>- x)\"\n      by (simp only: conj_disj_distrib)\n    also have \"\\<dots> = x \\<^bold>\\<sqinter> \\<^bold>1\"\n      by simp\n    also have \"\\<dots> = x\"\n      by (simp add: conj_one_right)\n    finally show ?thesis .\n  qed\nqed\n\nsublocale disj: semilattice_neutr \\<open>(\\<^bold>\\<squnion>)\\<close> \\<open>\\<^bold>0\\<close>\nproof\n  show \"x \\<^bold>\\<squnion> \\<^bold>0 = x\" for x\n    by (fact disj_zero_right)\n  show \"x \\<^bold>\\<squnion> x = x\" for x\n  proof -\n    have \"x \\<^bold>\\<squnion> x = (x \\<^bold>\\<squnion> x) \\<^bold>\\<sqinter> \\<^bold>1\"\n      by simp\n    also have \"\\<dots> = (x \\<^bold>\\<squnion> x) \\<^bold>\\<sqinter> (x \\<^bold>\\<squnion> \\<^bold>- x)\"\n      by simp\n    also have \"\\<dots> = x \\<^bold>\\<squnion> (x \\<^bold>\\<sqinter> \\<^bold>- x)\"\n      by (simp only: disj_conj_distrib)\n    also have \"\\<dots> = x \\<^bold>\\<squnion> \\<^bold>0\"\n      by simp\n    also have \"\\<dots> = x\"\n      by (simp add: disj_zero_right)\n    finally show ?thesis .\n  qed\nqed\n\n\nsubsubsection \\<open>Complement\\<close>\n\nlemma complement_unique:\n  assumes 1: \"a \\<^bold>\\<sqinter> x = \\<^bold>0\"\n  assumes 2: \"a \\<^bold>\\<squnion> x = \\<^bold>1\"\n  assumes 3: \"a \\<^bold>\\<sqinter> y = \\<^bold>0\"\n  assumes 4: \"a \\<^bold>\\<squnion> y = \\<^bold>1\"\n  shows \"x = y\"\nproof -\n  from 1 3 have \"(a \\<^bold>\\<sqinter> x) \\<^bold>\\<squnion> (x \\<^bold>\\<sqinter> y) = (a \\<^bold>\\<sqinter> y) \\<^bold>\\<squnion> (x \\<^bold>\\<sqinter> y)\"\n    by simp\n  then have \"(x \\<^bold>\\<sqinter> a) \\<^bold>\\<squnion> (x \\<^bold>\\<sqinter> y) = (y \\<^bold>\\<sqinter> a) \\<^bold>\\<squnion> (y \\<^bold>\\<sqinter> x)\"\n    by (simp add: ac_simps)\n  then have \"x \\<^bold>\\<sqinter> (a \\<^bold>\\<squnion> y) = y \\<^bold>\\<sqinter> (a \\<^bold>\\<squnion> x)\"\n    by (simp add: conj_disj_distrib)\n  with 2 4 have \"x \\<^bold>\\<sqinter> \\<^bold>1 = y \\<^bold>\\<sqinter> \\<^bold>1\"\n    by simp\n  then show \"x = y\"\n    by simp\nqed\n\nlemma compl_unique: \"x \\<^bold>\\<sqinter> y = \\<^bold>0 \\<Longrightarrow> x \\<^bold>\\<squnion> y = \\<^bold>1 \\<Longrightarrow> \\<^bold>- x = y\"\n  by (rule complement_unique [OF conj_cancel_right disj_cancel_right])\n\nlemma double_compl [simp]: \"\\<^bold>- (\\<^bold>- x) = x\"\nproof (rule compl_unique)\n  show \"\\<^bold>- x \\<^bold>\\<sqinter> x = \\<^bold>0\"\n    by (simp only: conj_cancel_right conj.commute)\n  show \"\\<^bold>- x \\<^bold>\\<squnion> x = \\<^bold>1\"\n    by (simp only: disj_cancel_right disj.commute)\nqed\n\nlemma compl_eq_compl_iff [simp]: \n  \\<open>\\<^bold>- x = \\<^bold>- y \\<longleftrightarrow> x = y\\<close>  (is \\<open>?P \\<longleftrightarrow> ?Q\\<close>)\nproof\n  assume \\<open>?Q\\<close>\n  then show ?P by simp\nnext\n  assume \\<open>?P\\<close>\n  then have \\<open>\\<^bold>- (\\<^bold>- x) = \\<^bold>- (\\<^bold>- y)\\<close>\n    by simp\n  then show ?Q\n    by simp\nqed\n\n\nsubsubsection \\<open>Conjunction\\<close>\n\nlemma conj_zero_right [simp]: \"x \\<^bold>\\<sqinter> \\<^bold>0 = \\<^bold>0\"\n  using conj.left_idem conj_cancel_right by fastforce\n\nlemma compl_one [simp]: \"\\<^bold>- \\<^bold>1 = \\<^bold>0\"\n  by (rule compl_unique [OF conj_zero_right disj_zero_right])\n\nlemma conj_zero_left [simp]: \"\\<^bold>0 \\<^bold>\\<sqinter> x = \\<^bold>0\"\n  by (subst conj.commute) (rule conj_zero_right)\n\nlemma conj_cancel_left [simp]: \"\\<^bold>- x \\<^bold>\\<sqinter> x = \\<^bold>0\"\n  by (subst conj.commute) (rule conj_cancel_right)\n\nlemma conj_disj_distrib2: \"(y \\<^bold>\\<squnion> z) \\<^bold>\\<sqinter> x = (y \\<^bold>\\<sqinter> x) \\<^bold>\\<squnion> (z \\<^bold>\\<sqinter> x)\"\n  by (simp only: conj.commute conj_disj_distrib)\n\nlemmas conj_disj_distribs = conj_disj_distrib conj_disj_distrib2\n\n\nsubsubsection \\<open>Disjunction\\<close>\n\ncontext\nbegin\n\ninterpretation dual: abstract_boolean_algebra \\<open>(\\<^bold>\\<squnion>)\\<close> \\<open>(\\<^bold>\\<sqinter>)\\<close> compl \\<open>\\<^bold>1\\<close> \\<open>\\<^bold>0\\<close>\n  apply standard\n       apply (rule disj_conj_distrib)\n      apply (rule conj_disj_distrib)\n     apply simp_all\n  done\n\nlemma disj_one_right [simp]: \"x \\<^bold>\\<squnion> \\<^bold>1 = \\<^bold>1\"\n  by (fact dual.conj_zero_right)\n\nlemma compl_zero [simp]: \"\\<^bold>- \\<^bold>0 = \\<^bold>1\"\n  by (fact dual.compl_one)\n\nlemma disj_one_left [simp]: \"\\<^bold>1 \\<^bold>\\<squnion> x = \\<^bold>1\"\n  by (fact dual.conj_zero_left)\n\nlemma disj_cancel_left [simp]: \"\\<^bold>- x \\<^bold>\\<squnion> x = \\<^bold>1\"\n  by (fact dual.conj_cancel_left)\n\nlemma disj_conj_distrib2: \"(y \\<^bold>\\<sqinter> z) \\<^bold>\\<squnion> x = (y \\<^bold>\\<squnion> x) \\<^bold>\\<sqinter> (z \\<^bold>\\<squnion> x)\"\n  by (fact dual.conj_disj_distrib2)\n\nlemmas disj_conj_distribs = disj_conj_distrib disj_conj_distrib2\n\nend\n\n\nsubsubsection \\<open>De Morgan's Laws\\<close>\n\nlemma de_Morgan_conj [simp]: \"\\<^bold>- (x \\<^bold>\\<sqinter> y) = \\<^bold>- x \\<^bold>\\<squnion> \\<^bold>- y\"\nproof (rule compl_unique)\n  have \"(x \\<^bold>\\<sqinter> y) \\<^bold>\\<sqinter> (\\<^bold>- x \\<^bold>\\<squnion> \\<^bold>- y) = ((x \\<^bold>\\<sqinter> y) \\<^bold>\\<sqinter> \\<^bold>- x) \\<^bold>\\<squnion> ((x \\<^bold>\\<sqinter> y) \\<^bold>\\<sqinter> \\<^bold>- y)\"\n    by (rule conj_disj_distrib)\n  also have \"\\<dots> = (y \\<^bold>\\<sqinter> (x \\<^bold>\\<sqinter> \\<^bold>- x)) \\<^bold>\\<squnion> (x \\<^bold>\\<sqinter> (y \\<^bold>\\<sqinter> \\<^bold>- y))\"\n    by (simp only: ac_simps)\n  finally show \"(x \\<^bold>\\<sqinter> y) \\<^bold>\\<sqinter> (\\<^bold>- x \\<^bold>\\<squnion> \\<^bold>- y) = \\<^bold>0\"\n    by (simp only: conj_cancel_right conj_zero_right disj_zero_right)\nnext\n  have \"(x \\<^bold>\\<sqinter> y) \\<^bold>\\<squnion> (\\<^bold>- x \\<^bold>\\<squnion> \\<^bold>- y) = (x \\<^bold>\\<squnion> (\\<^bold>- x \\<^bold>\\<squnion> \\<^bold>- y)) \\<^bold>\\<sqinter> (y \\<^bold>\\<squnion> (\\<^bold>- x \\<^bold>\\<squnion> \\<^bold>- y))\"\n    by (rule disj_conj_distrib2)\n  also have \"\\<dots> = (\\<^bold>- y \\<^bold>\\<squnion> (x \\<^bold>\\<squnion> \\<^bold>- x)) \\<^bold>\\<sqinter> (\\<^bold>- x \\<^bold>\\<squnion> (y \\<^bold>\\<squnion> \\<^bold>- y))\"\n    by (simp only: ac_simps)\n  finally show \"(x \\<^bold>\\<sqinter> y) \\<^bold>\\<squnion> (\\<^bold>- x \\<^bold>\\<squnion> \\<^bold>- y) = \\<^bold>1\"\n    by (simp only: disj_cancel_right disj_one_right conj_one_right)\nqed\n\ncontext\nbegin\n\ninterpretation dual: abstract_boolean_algebra \\<open>(\\<^bold>\\<squnion>)\\<close> \\<open>(\\<^bold>\\<sqinter>)\\<close> compl \\<open>\\<^bold>1\\<close> \\<open>\\<^bold>0\\<close>\n  apply standard\n       apply (rule disj_conj_distrib)\n      apply (rule conj_disj_distrib)\n     apply simp_all\n  done\n\nlemma de_Morgan_disj [simp]: \"\\<^bold>- (x \\<^bold>\\<squnion> y) = \\<^bold>- x \\<^bold>\\<sqinter> \\<^bold>- y\"\n  by (fact dual.de_Morgan_conj)\n\nend\n\nend\n\n\nsubsection \\<open>Symmetric Difference\\<close>\n\nlocale abstract_boolean_algebra_sym_diff = abstract_boolean_algebra +\n  fixes xor :: \\<open>'a \\<Rightarrow> 'a \\<Rightarrow> 'a\\<close>  (infixr \\<open>\\<^bold>\\<ominus>\\<close> 65)\n  assumes xor_def : \\<open>x \\<^bold>\\<ominus> y = (x \\<^bold>\\<sqinter> \\<^bold>- y) \\<^bold>\\<squnion> (\\<^bold>- x \\<^bold>\\<sqinter> y)\\<close>\nbegin\n\nsublocale xor: comm_monoid xor \\<open>\\<^bold>0\\<close>\nproof\n  fix x y z :: 'a\n  let ?t = \"(x \\<^bold>\\<sqinter> y \\<^bold>\\<sqinter> z) \\<^bold>\\<squnion> (x \\<^bold>\\<sqinter> \\<^bold>- y \\<^bold>\\<sqinter> \\<^bold>- z) \\<^bold>\\<squnion> (\\<^bold>- x \\<^bold>\\<sqinter> y \\<^bold>\\<sqinter> \\<^bold>- z) \\<^bold>\\<squnion> (\\<^bold>- x \\<^bold>\\<sqinter> \\<^bold>- y \\<^bold>\\<sqinter> z)\"\n  have \"?t \\<^bold>\\<squnion> (z \\<^bold>\\<sqinter> x \\<^bold>\\<sqinter> \\<^bold>- x) \\<^bold>\\<squnion> (z \\<^bold>\\<sqinter> y \\<^bold>\\<sqinter> \\<^bold>- y) = ?t \\<^bold>\\<squnion> (x \\<^bold>\\<sqinter> y \\<^bold>\\<sqinter> \\<^bold>- y) \\<^bold>\\<squnion> (x \\<^bold>\\<sqinter> z \\<^bold>\\<sqinter> \\<^bold>- z)\"\n    by (simp only: conj_cancel_right conj_zero_right)\n  then show \"(x \\<^bold>\\<ominus> y) \\<^bold>\\<ominus> z = x \\<^bold>\\<ominus> (y \\<^bold>\\<ominus> z)\"\n    by (simp only: xor_def de_Morgan_disj de_Morgan_conj double_compl)\n      (simp only: conj_disj_distribs conj_ac ac_simps)\n  show \"x \\<^bold>\\<ominus> y = y \\<^bold>\\<ominus> x\"\n    by (simp only: xor_def ac_simps)\n  show \"x \\<^bold>\\<ominus> \\<^bold>0 = x\"\n    by (simp add: xor_def)\nqed\n\nlemma xor_def2:\n  \\<open>x \\<^bold>\\<ominus> y = (x \\<^bold>\\<squnion> y) \\<^bold>\\<sqinter> (\\<^bold>- x \\<^bold>\\<squnion> \\<^bold>- y)\\<close>\nproof -\n  note xor_def [of x y]\n  also have \\<open>x \\<^bold>\\<sqinter> \\<^bold>- y \\<^bold>\\<squnion> \\<^bold>- x \\<^bold>\\<sqinter> y = ((x \\<^bold>\\<squnion> \\<^bold>- x) \\<^bold>\\<sqinter> (\\<^bold>- y \\<^bold>\\<squnion> \\<^bold>- x)) \\<^bold>\\<sqinter> (x \\<^bold>\\<squnion> y) \\<^bold>\\<sqinter> (\\<^bold>- y \\<^bold>\\<squnion> y)\\<close>\n    by (simp add: ac_simps disj_conj_distribs)\n  also have \\<open>\\<dots> = (x \\<^bold>\\<squnion> y) \\<^bold>\\<sqinter> (\\<^bold>- x \\<^bold>\\<squnion> \\<^bold>- y)\\<close>\n    by (simp add: ac_simps)\n  finally show ?thesis .\nqed\n\nlemma xor_one_right [simp]: \"x \\<^bold>\\<ominus> \\<^bold>1 = \\<^bold>- x\"\n  by (simp only: xor_def compl_one conj_zero_right conj_one_right disj.left_neutral)\n\nlemma xor_one_left [simp]: \"\\<^bold>1 \\<^bold>\\<ominus> x = \\<^bold>- x\"\n  using xor_one_right [of x] by (simp add: ac_simps)\n\nlemma xor_self [simp]: \"x \\<^bold>\\<ominus> x = \\<^bold>0\"\n  by (simp only: xor_def conj_cancel_right conj_cancel_left disj_zero_right)\n\nlemma xor_left_self [simp]: \"x \\<^bold>\\<ominus> (x \\<^bold>\\<ominus> y) = y\"\n  by (simp only: xor.assoc [symmetric] xor_self xor.left_neutral)\n\nlemma xor_compl_left [simp]: \"\\<^bold>- x \\<^bold>\\<ominus> y = \\<^bold>- (x \\<^bold>\\<ominus> y)\"\n  by (simp add: ac_simps flip: xor_one_left)\n\nlemma xor_compl_right [simp]: \"x \\<^bold>\\<ominus> \\<^bold>- y = \\<^bold>- (x \\<^bold>\\<ominus> y)\"\n  using xor.commute xor_compl_left by auto\n\nlemma xor_cancel_right [simp]: \"x \\<^bold>\\<ominus> \\<^bold>- x = \\<^bold>1\"\n  by (simp only: xor_compl_right xor_self compl_zero)\n\nlemma xor_cancel_left [simp]: \"\\<^bold>- x \\<^bold>\\<ominus> x = \\<^bold>1\"\n  by (simp only: xor_compl_left xor_self compl_zero)\n\nlemma conj_xor_distrib: \"x \\<^bold>\\<sqinter> (y \\<^bold>\\<ominus> z) = (x \\<^bold>\\<sqinter> y) \\<^bold>\\<ominus> (x \\<^bold>\\<sqinter> z)\"\nproof -\n  have *: \"(x \\<^bold>\\<sqinter> y \\<^bold>\\<sqinter> \\<^bold>- z) \\<^bold>\\<squnion> (x \\<^bold>\\<sqinter> \\<^bold>- y \\<^bold>\\<sqinter> z) =\n        (y \\<^bold>\\<sqinter> x \\<^bold>\\<sqinter> \\<^bold>- x) \\<^bold>\\<squnion> (z \\<^bold>\\<sqinter> x \\<^bold>\\<sqinter> \\<^bold>- x) \\<^bold>\\<squnion> (x \\<^bold>\\<sqinter> y \\<^bold>\\<sqinter> \\<^bold>- z) \\<^bold>\\<squnion> (x \\<^bold>\\<sqinter> \\<^bold>- y \\<^bold>\\<sqinter> z)\"\n    by (simp only: conj_cancel_right conj_zero_right disj.left_neutral)\n  then show \"x \\<^bold>\\<sqinter> (y \\<^bold>\\<ominus> z) = (x \\<^bold>\\<sqinter> y) \\<^bold>\\<ominus> (x \\<^bold>\\<sqinter> z)\"\n    by (simp (no_asm_use) only:\n        xor_def de_Morgan_disj de_Morgan_conj double_compl\n        conj_disj_distribs ac_simps)\nqed\n\nlemma conj_xor_distrib2: \"(y \\<^bold>\\<ominus> z) \\<^bold>\\<sqinter> x = (y \\<^bold>\\<sqinter> x) \\<^bold>\\<ominus> (z \\<^bold>\\<sqinter> x)\"\n  by (simp add: conj.commute conj_xor_distrib)\n\nlemmas conj_xor_distribs = conj_xor_distrib conj_xor_distrib2\n\nend\n\n\nsubsection \\<open>Type classes\\<close>\n\nclass boolean_algebra = distrib_lattice + bounded_lattice + minus + uminus +\n  assumes inf_compl_bot: \\<open>x \\<sqinter> - x = \\<bottom>\\<close>\n    and sup_compl_top: \\<open>x \\<squnion> - x = \\<top>\\<close>\n  assumes diff_eq: \\<open>x - y = x \\<sqinter> - y\\<close>\nbegin\n\nsublocale boolean_algebra: abstract_boolean_algebra \\<open>(\\<sqinter>)\\<close> \\<open>(\\<squnion>)\\<close> uminus \\<bottom> \\<top>\n  apply standard\n       apply (rule inf_sup_distrib1)\n      apply (rule sup_inf_distrib1)\n     apply (simp_all add: ac_simps inf_compl_bot sup_compl_top)\n  done\n\nlemma compl_inf_bot: \"- x \\<sqinter> x = \\<bottom>\"\n  by (fact boolean_algebra.conj_cancel_left)\n\nlemma compl_sup_top: \"- x \\<squnion> x = \\<top>\"\n  by (fact boolean_algebra.disj_cancel_left)\n\nlemma compl_unique:\n  assumes \"x \\<sqinter> y = \\<bottom>\"\n    and \"x \\<squnion> y = \\<top>\"\n  shows \"- x = y\"\n  using assms by (rule boolean_algebra.compl_unique)\n\nlemma double_compl: \"- (- x) = x\"\n  by (fact boolean_algebra.double_compl)\n\nlemma compl_eq_compl_iff: \"- x = - y \\<longleftrightarrow> x = y\"\n  by (fact boolean_algebra.compl_eq_compl_iff)\n\nlemma compl_bot_eq: \"- \\<bottom> = \\<top>\"\n  by (fact boolean_algebra.compl_zero)\n\nlemma compl_top_eq: \"- \\<top> = \\<bottom>\"\n  by (fact boolean_algebra.compl_one)\n\nlemma compl_inf: \"- (x \\<sqinter> y) = - x \\<squnion> - y\"\n  by (fact boolean_algebra.de_Morgan_conj)\n\nlemma compl_sup: \"- (x \\<squnion> y) = - x \\<sqinter> - y\"\n  by (fact boolean_algebra.de_Morgan_disj)\n\nlemma compl_mono:\n  assumes \"x \\<le> y\"\n  shows \"- y \\<le> - x\"\nproof -\n  from assms have \"x \\<squnion> y = y\" by (simp only: le_iff_sup)\n  then have \"- (x \\<squnion> y) = - y\" by simp\n  then have \"- x \\<sqinter> - y = - y\" by simp\n  then have \"- y \\<sqinter> - x = - y\" by (simp only: inf_commute)\n  then show ?thesis by (simp only: le_iff_inf)\nqed\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\"\nproof -\n  from assms have \"- x \\<le> - (- y)\" by (simp only: compl_le_compl_iff)\n  then show ?thesis by simp\nqed\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\"\nproof -\n  from assms have \"- (- x) < - y\" by (simp only: compl_less_compl_iff)\n  then show ?thesis by simp\nqed\n\nlemma compl_less_swap2:\n  assumes \"- y < x\"\n  shows \"- x < y\"\nproof -\n  from assms have \"- x < - (- y)\"\n    by (simp only: compl_less_compl_iff)\n  then show ?thesis by simp\nqed\n\nlemma sup_cancel_left1: \\<open>x \\<squnion> a \\<squnion> (- x \\<squnion> b) = \\<top>\\<close>\n  by (simp add: ac_simps)\n\nlemma sup_cancel_left2: \\<open>- x \\<squnion> a \\<squnion> (x \\<squnion> b) = \\<top>\\<close>\n  by (simp add: ac_simps)\n\nlemma inf_cancel_left1: \\<open>x \\<sqinter> a \\<sqinter> (- x \\<sqinter> b) = \\<bottom>\\<close>\n  by (simp add: ac_simps)\n\nlemma inf_cancel_left2: \\<open>- x \\<sqinter> a \\<sqinter> (x \\<sqinter> b) = \\<bottom>\\<close>\n  by (simp add: ac_simps)\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\n\nsubsection \\<open>Lattice on \\<^typ>\\<open>bool\\<close>\\<close>\n\ninstantiation bool :: boolean_algebra\nbegin\n\ndefinition bool_Compl_def [simp]: \"uminus = Not\"\n\ndefinition bool_diff_def [simp]: \"A - B \\<longleftrightarrow> A \\<and> \\<not> B\"\n\ndefinition [simp]: \"P \\<sqinter> Q \\<longleftrightarrow> P \\<and> Q\"\n\ndefinition [simp]: \"P \\<squnion> Q \\<longleftrightarrow> P \\<or> Q\"\n\ninstance by standard auto\n\nend\n\nlemma sup_boolI1: \"P \\<Longrightarrow> P \\<squnion> Q\"\n  by simp\n\nlemma sup_boolI2: \"Q \\<Longrightarrow> P \\<squnion> Q\"\n  by simp\n\nlemma sup_boolE: \"P \\<squnion> Q \\<Longrightarrow> (P \\<Longrightarrow> R) \\<Longrightarrow> (Q \\<Longrightarrow> R) \\<Longrightarrow> R\"\n  by auto\n\ninstance \"fun\" :: (type, boolean_algebra) boolean_algebra\n  by standard (rule ext, simp_all add: inf_compl_bot sup_compl_top diff_eq)+\n\n\nsubsection \\<open>Lattice on unary and binary predicates\\<close>\n\nlemma inf1I: \"A x \\<Longrightarrow> B x \\<Longrightarrow> (A \\<sqinter> B) x\"\n  by (simp add: inf_fun_def)\n\nlemma inf2I: \"A x y \\<Longrightarrow> B x y \\<Longrightarrow> (A \\<sqinter> B) x y\"\n  by (simp add: inf_fun_def)\n\nlemma inf1E: \"(A \\<sqinter> B) x \\<Longrightarrow> (A x \\<Longrightarrow> B x \\<Longrightarrow> P) \\<Longrightarrow> P\"\n  by (simp add: inf_fun_def)\n\nlemma inf2E: \"(A \\<sqinter> B) x y \\<Longrightarrow> (A x y \\<Longrightarrow> B x y \\<Longrightarrow> P) \\<Longrightarrow> P\"\n  by (simp add: inf_fun_def)\n\nlemma inf1D1: \"(A \\<sqinter> B) x \\<Longrightarrow> A x\"\n  by (rule inf1E)\n\nlemma inf2D1: \"(A \\<sqinter> B) x y \\<Longrightarrow> A x y\"\n  by (rule inf2E)\n\nlemma inf1D2: \"(A \\<sqinter> B) x \\<Longrightarrow> B x\"\n  by (rule inf1E)\n\nlemma inf2D2: \"(A \\<sqinter> B) x y \\<Longrightarrow> B x y\"\n  by (rule inf2E)\n\nlemma sup1I1: \"A x \\<Longrightarrow> (A \\<squnion> B) x\"\n  by (simp add: sup_fun_def)\n\nlemma sup2I1: \"A x y \\<Longrightarrow> (A \\<squnion> B) x y\"\n  by (simp add: sup_fun_def)\n\nlemma sup1I2: \"B x \\<Longrightarrow> (A \\<squnion> B) x\"\n  by (simp add: sup_fun_def)\n\nlemma sup2I2: \"B x y \\<Longrightarrow> (A \\<squnion> B) x y\"\n  by (simp add: sup_fun_def)\n\nlemma sup1E: \"(A \\<squnion> B) x \\<Longrightarrow> (A x \\<Longrightarrow> P) \\<Longrightarrow> (B x \\<Longrightarrow> P) \\<Longrightarrow> P\"\n  by (simp add: sup_fun_def) iprover\n\nlemma sup2E: \"(A \\<squnion> B) x y \\<Longrightarrow> (A x y \\<Longrightarrow> P) \\<Longrightarrow> (B x y \\<Longrightarrow> P) \\<Longrightarrow> P\"\n  by (simp add: sup_fun_def) iprover\n\ntext \\<open> \\<^medskip> Classical introduction rule: no commitment to \\<open>A\\<close> vs \\<open>B\\<close>.\\<close>\n\nlemma sup1CI: \"(\\<not> B x \\<Longrightarrow> A x) \\<Longrightarrow> (A \\<squnion> B) x\"\n  by (auto simp add: sup_fun_def)\n\nlemma sup2CI: \"(\\<not> B x y \\<Longrightarrow> A x y) \\<Longrightarrow> (A \\<squnion> B) x y\"\n  by (auto simp add: sup_fun_def)\n\n\nsubsection \\<open>Simproc setup\\<close>\n\nlocale boolean_algebra_cancel\nbegin\n\nlemma sup1: \"(A::'a::semilattice_sup) \\<equiv> sup k a \\<Longrightarrow> sup A b \\<equiv> sup k (sup a b)\"\n  by (simp only: ac_simps)\n\nlemma sup2: \"(B::'a::semilattice_sup) \\<equiv> sup k b \\<Longrightarrow> sup a B \\<equiv> sup k (sup a b)\"\n  by (simp only: ac_simps)\n\nlemma sup0: \"(a::'a::bounded_semilattice_sup_bot) \\<equiv> sup a bot\"\n  by simp\n\nlemma inf1: \"(A::'a::semilattice_inf) \\<equiv> inf k a \\<Longrightarrow> inf A b \\<equiv> inf k (inf a b)\"\n  by (simp only: ac_simps)\n\nlemma inf2: \"(B::'a::semilattice_inf) \\<equiv> inf k b \\<Longrightarrow> inf a B \\<equiv> inf k (inf a b)\"\n  by (simp only: ac_simps)\n\nlemma inf0: \"(a::'a::bounded_semilattice_inf_top) \\<equiv> inf a top\"\n  by simp\n\nend\n\nML_file \\<open>Tools/boolean_algebra_cancel.ML\\<close>\n\nsimproc_setup boolean_algebra_cancel_sup (\"sup a b::'a::boolean_algebra\") =\n  \\<open>fn phi => fn ss => try Boolean_Algebra_Cancel.cancel_sup_conv\\<close>\n\nsimproc_setup boolean_algebra_cancel_inf (\"inf a b::'a::boolean_algebra\") =\n  \\<open>fn phi => fn ss => try Boolean_Algebra_Cancel.cancel_inf_conv\\<close>\n\n\ncontext boolean_algebra\nbegin\n    \nlemma shunt1: \"(x \\<sqinter> y \\<le> z) \\<longleftrightarrow> (x \\<le> -y \\<squnion> z)\"\nproof\n  assume \"x \\<sqinter> y \\<le> z\"\n  hence  \"-y \\<squnion> (x \\<sqinter> y) \\<le> -y \\<squnion> z\"\n    using sup.mono by blast\n  hence \"-y \\<squnion> x \\<le> -y \\<squnion> z\"\n    by (simp add: sup_inf_distrib1)\n  thus \"x \\<le> -y \\<squnion> z\"\n    by simp\nnext\n  assume \"x \\<le> -y \\<squnion> z\"\n  hence \"x \\<sqinter> y \\<le> (-y \\<squnion> z) \\<sqinter> y\"\n    using inf_mono by auto\n  thus  \"x \\<sqinter> y \\<le> z\"\n    using inf.boundedE inf_sup_distrib2 by auto\nqed\n\nlemma shunt2: \"(x \\<sqinter> -y \\<le> z) \\<longleftrightarrow> (x \\<le> y \\<squnion> z)\"\n  by (simp add: shunt1)\n\nlemma inf_shunt: \"(x \\<sqinter> y = \\<bottom>) \\<longleftrightarrow> (x \\<le> - y)\"\n  by (simp add: order.eq_iff shunt1)\n  \nlemma sup_shunt: \"(x \\<squnion> y = \\<top>) \\<longleftrightarrow> (- x \\<le> y)\"\n  using inf_shunt [of \\<open>- x\\<close> \\<open>- y\\<close>, symmetric] \n  by (simp flip: compl_sup compl_top_eq)\n\nlemma diff_shunt_var: \"(x - y = \\<bottom>) \\<longleftrightarrow> (x \\<le> y)\"\n  by (simp add: diff_eq inf_shunt)\n\nlemma sup_neg_inf:\n  \\<open>p \\<le> q \\<squnion> r \\<longleftrightarrow> p \\<sqinter> -q \\<le> r\\<close>  (is \\<open>?P \\<longleftrightarrow> ?Q\\<close>)\nproof\n  assume ?P\n  then have \\<open>p \\<sqinter> - q \\<le> (q \\<squnion> r) \\<sqinter> - q\\<close>\n    by (rule inf_mono) simp\n  then show ?Q\n    by (simp add: inf_sup_distrib2)\nnext\n  assume ?Q\n  then have \\<open>p \\<sqinter> - q \\<squnion> q \\<le> r \\<squnion> q\\<close>\n    by (rule sup_mono) simp\n  then show ?P\n    by (simp add: sup_inf_distrib ac_simps)\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/Boolean_Algebras.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869916479467, "lm_q2_score": 0.8438951045175643, "lm_q1q2_score": 0.7390723548518672}}
{"text": "theory Preliminaries\nimports Main \"HOL-Library.Infinite_Set\"\nbegin\n\nsection \"Mathematical Preliminaries\"\n\ntext \\<open>\n  We begin by proving some general-purpose lemmas that underly our\n  developments, but that could also be useful in other contexts.\n\n  The first subsection establishes various random results about\n  existing theories of Isabelle/HOL. The second subsection\n  introduces general concepts of $\\omega$-words (i.e., infinite\n  sequences), and $\\omega$-dags are formalized in the third subsection.\n\\<close>\n\nsubsection \\<open> General-purpose lemmas \\<close>\n\ntext \\<open>\n  The standard library contains theorem @{text less_iff_Suc_add}\n\n  @{thm less_iff_Suc_add [no_vars]}\n\n  that can be used to reduce ``less than'' to addition and successor.\n  The following lemma is the analogous result for ``less or equal''.\n\\<close>\n\nlemma le_iff_add:\n  \"(m::nat) \\<le> n = (\\<exists> k. n = m+k)\"\nproof\n  assume le: \"m \\<le> n\"\n  thus \"\\<exists> k. n = m+k\"\n  proof (auto simp add: order_le_less)\n    assume \"m<n\"\n    then obtain k where \"n = Suc(m+k)\"\n      by (auto simp add: less_iff_Suc_add)\n    thus ?thesis by auto\n  qed\nnext\n  assume \"\\<exists> k. n = m+k\"\n  thus \"m \\<le> n\" by auto\nqed\n\nlemma exists_leI:\n  assumes hyp: \"(\\<forall>n' < n. \\<not> P n') \\<Longrightarrow> P (n::nat)\"\n  shows \"\\<exists>n' \\<le> n. P n'\"\nproof (rule classical)\n  assume contra: \"\\<not> (\\<exists>n'\\<le>n. P n')\"\n  hence \"\\<forall>n' < n. \\<not> P n'\" by auto\n  hence \"P n\" by (rule hyp)\n  thus \"\\<exists>n'\\<le>n. P n'\" by auto\nqed\n\n\ntext \\<open>\n  An ``induction'' law for modulus arithmetic: if $P$ holds for some\n  $i<p$ and if $P(i)$ implies $P((i+1) \\bmod p)$, for all $i<p$, then\n  $P(i)$ holds for all $i<p$.\n\\<close>\n\nlemma mod_induct_0:\n  assumes step: \"\\<forall>i<p. P i \\<longrightarrow> P ((Suc i) mod p)\"\n  and base: \"P i\" and i: \"i<p\"\n  shows \"P 0\"\nproof (rule ccontr)\n  assume contra: \"\\<not>(P 0)\"\n  from i have p: \"0<p\" by simp\n  have \"\\<forall>k. 0<k \\<longrightarrow> \\<not> P (p-k)\" (is \"\\<forall>k. ?A k\")\n  proof\n    fix k\n    show \"?A k\"\n    proof (induct k)\n      show \"?A 0\" by simp  \\<comment>\\<open>by contradiction\\<close>\n    next\n      fix n\n      assume ih: \"?A n\"\n      show \"?A (Suc n)\"\n      proof (clarsimp)\n\tassume y: \"P (p - Suc n)\"\n\thave n: \"Suc n < p\"\n\tproof (rule ccontr)\n\t  assume \"\\<not>(Suc n < p)\"\n\t  hence \"p - Suc n = 0\"\n\t    by simp\n\t  with y contra show \"False\"\n\t    by simp\n\tqed\n\thence n2: \"Suc (p - Suc n) = p-n\" by arith\n\tfrom p have \"p - Suc n < p\" by arith\n\twith y step have z: \"P ((Suc (p - Suc n)) mod p)\"\n\t  by blast\n\tshow \"False\"\n\tproof (cases \"n=0\")\n\t  case True\n\t  with z n2 contra show ?thesis by simp\n\tnext\n\t  case False\n\t  with p have \"p-n < p\" by arith\n\t  with z n2 False ih show ?thesis by simp\n\tqed\n      qed\n    qed\n  qed\n  moreover\n  from i obtain k where \"0<k \\<and> i+k=p\"\n    by (blast dest: less_imp_add_positive)\n  hence \"0<k \\<and> i=p-k\" by auto\n  moreover\n  note base\n  ultimately\n  show \"False\" by blast\nqed\n\nlemma mod_induct:\n  assumes step: \"\\<forall>i<p. P i \\<longrightarrow> P ((Suc i) mod p)\"\n  and base: \"P i\" and i: \"i<p\" and j: \"j<p\"\n  shows \"P j\"\nproof -\n  have \"\\<forall>j<p. P j\"\n  proof\n    fix j\n    show \"j<p \\<longrightarrow> P j\" (is \"?A j\")\n    proof (induct j)\n      from step base i show \"?A 0\"\n\tby (auto elim: mod_induct_0)\n    next\n      fix k\n      assume ih: \"?A k\"\n      show \"?A (Suc k)\"\n      proof\n\tassume suc: \"Suc k < p\"\n\thence k: \"k<p\" by simp\n\twith ih have \"P k\" ..\n\twith step k have \"P (Suc k mod p)\"\n\t  by blast\n\tmoreover\n\tfrom suc have \"Suc k mod p = Suc k\"\n\t  by simp\n\tultimately\n\tshow \"P (Suc k)\" by simp\n      qed\n    qed\n  qed\n  with j show ?thesis by blast\nqed\n\ntext \\<open>\n  Pairs and functions whose codomains are pairs.\n\\<close>\n\nlemma img_fst [intro]:\n  assumes \"(a,b) \\<in> S\"\n  shows \"a \\<in> fst ` S\"\nby (rule image_eqI[OF _ assms]) simp\n\nlemma img_snd [intro]:\n  assumes \"(a,b) \\<in> S\"\n  shows \"b \\<in> snd ` S\"\nby (rule image_eqI[OF _ assms]) simp\n\nlemma range_prod:\n  \"range f \\<subseteq> (range (fst \\<circ> f)) \\<times> (range (snd \\<circ> f))\"\nproof\n  fix y\n  assume \"y \\<in> range f\"\n  then obtain x where y: \"y = f x\" by auto\n  hence \"y = (fst(f x), snd(f x))\"\n    by simp\n  thus \"y \\<in> (range (fst \\<circ> f)) \\<times> (range (snd \\<circ> f))\"\n    by (fastforce simp add: image_def)\nqed\n\nlemma finite_range_prod:\n  assumes fst: \"finite (range (fst \\<circ> f))\"\n  and     snd: \"finite (range (snd \\<circ> f))\"\n  shows \"finite (range f)\"\nproof -\n  from fst snd have \"finite (range (fst \\<circ> f) \\<times> range (snd \\<circ> f))\"\n    by (rule finite_SigmaI)\n  thus ?thesis\n    by (rule finite_subset[OF range_prod])\nqed\n\ntext \\<open>\n  Decompose general union over sum types.\n\\<close>\n\nlemma Union_plus:\n  \"(\\<Union> x \\<in> A <+> B. f x) = (\\<Union> a \\<in> A. f (Inl a)) \\<union> (\\<Union>b \\<in> B. f (Inr b))\"\nby auto\n\nlemma Union_sum:\n  \"(\\<Union>x. f (x::'a+'b)) = (\\<Union>l. f (Inl l)) \\<union> (\\<Union>r. f (Inr r))\"\n  (is \"?lhs = ?rhs\")\nproof -\n  have \"?lhs = (\\<Union>x \\<in> UNIV <+> UNIV. f x)\"\n    by simp\n  thus ?thesis\n    by (simp only: Union_plus)\nqed\n\nlemma card_Plus:\n  assumes fina: \"finite (A::'a set)\" and finb: \"finite (B::'b set)\"\n  shows \"card (A <+> B) = (card A) + (card B)\"\nproof -\n  from fina finb\n  have \"card ((Inl ` A) \\<union> (Inr ` B)) =\n        (card ((Inl ` A)::('a+'b)set)) + (card ((Inr ` B)::('a+'b)set))\"\n    by (auto intro: card_Un_disjoint finite_imageI)\n  thus ?thesis\n    by (simp add: Plus_def card_image inj_on_def)\nqed\n\ntext \\<open>\n  The standard library proves that a generalized union is finite\n  if the index set is finite and if for every index the component\n  set is itself finite. Conversely, we show that every component\n  set must be finite when the union is finite.\n\\<close>\n(*\nlemma finite_UNION_then_finite:\n  assumes hyp: \"finite (UNION A B)\" and a: \"a \\<in> A\"\n  shows \"finite (B a)\"\nproof (rule ccontr)\n  assume cc: \"infinite (B a)\"\n  from a have \"B a \\<subseteq> UNION A B\" by auto\n  from this cc have \"infinite (UNION A B)\" by (rule infinite_super)\n  from this hyp show \"False\" ..\nqed\n*)\n\nlemma finite_UNION_then_finite:\n  \"finite (\\<Union>(B ` A)) \\<Longrightarrow> a \\<in> A \\<Longrightarrow> finite (B a)\"\nby (metis Set.set_insert UN_insert Un_infinite)\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/Automata_Merz/Preliminaries.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8596637541053281, "lm_q2_score": 0.8596637505099167, "lm_q1q2_score": 0.7390217670316213}}
{"text": "theory Game_Theory \n  imports \"HOL-Probability.Probability_Mass_Function\"\nbegin\n\nsection \"Defining a Simultaneous Move Game\"\n\nlocale strategic_game = \n  fixes pure_strategies :: \"'player :: finite  \\<Rightarrow> 'strategy set\"\n    and payoffs :: \"'strategy^'player \\<Rightarrow> ('payoff :: linorder)^'player\"\nassumes players_can_play: \"pure_strategies i \\<noteq> {}\"\nbegin\n\ncorollary players_have_a_move: \"\\<exists>s. s\\<in>pure_strategies i\"\n  using players_can_play by auto \n\n\ntext \"Strategy selection\" \ndefinition pure_profile :: \"('strategy^'player) \\<Rightarrow> bool\"\n  where \"pure_profile s = (\\<forall>i. s$i \\<in> pure_strategies i)\"\n\ndefinition payoff :: \"'strategy^'player \\<Rightarrow> 'player \\<Rightarrow> 'payoff\" \n  where \"payoff s i = (payoffs s)$i\"\n\ntext \"We prove the existence of legal plays, represented as vectors of legal strategies.\nIn particular, legal plays exist that include any particular choice of strategy for any player.\"\n\nlemma pure_profile_fix_exists: \n  fixes s\\<^sub>i :: \"'strategy\" \n    and i :: 'player\n  assumes fixed_strategy:  \"s\\<^sub>i \\<in> pure_strategies i\" \n  shows \"\\<exists>s. pure_profile s \\<and> s$i = s\\<^sub>i\" \nproof -\n  let ?s = \"(\\<chi> j. if j = i then s\\<^sub>i else (SOME s\\<^sub>j. s\\<^sub>j \\<in> pure_strategies j))\"\n  have \"\\<forall>j. ?s$j \\<in> pure_strategies j\"\n    by (simp add: fixed_strategy players_can_play some_in_eq)\n  hence \"pure_profile ?s\"\n    by (simp add: pure_profile_def)\n\n  moreover have \"?s$i = s\\<^sub>i\"\n    by simp \n\n  ultimately show ?thesis\n    by auto\nqed\n\nlemma pure_profile_exists: \"\\<exists>s. pure_profile s\" \n  using pure_profile_fix_exists players_have_a_move by blast \n\ntext \"If n denotes the number of players, we represent the (n-1)-dimensional vector of strategies\nchosen by players other than player i as a function from strategies (which player i may choose) to\n(n-dimensional) strategy vectors.\"\n\ndefinition pure_profile_completion :: \"'strategy \\<Rightarrow> 'strategy^'player \\<Rightarrow> 'player \\<Rightarrow> 'strategy^'player\"\n  where \"pure_profile_completion s\\<^sub>i s i = (\\<chi> j. if j = i then s\\<^sub>i else s$j)\"\n\nnotation pure_profile_completion (\"(_,_\\<^sub>-\\<^sub>_)\" [80, 80] 80)\n\nlemma player_chooses_completion: \"(s\\<^sub>i,s\\<^sub>-\\<^sub>i)$i = s\\<^sub>i\"\n  by (simp add: pure_profile_completion_def)\n\nlemma pure_completion_fixes_other_players: \n  fixes i :: 'player\n    and j :: 'player\n  assumes \"i \\<noteq> j\"\n  shows \"(s\\<^sub>i,s\\<^sub>-\\<^sub>i)$j = s$j\"\n  using assms pure_profile_completion_def by auto\n\nlemma pure_completion_legal_iff: \n  fixes i :: 'player \n    and s :: \"'strategy^'player\"\n  shows \"(pure_profile (s\\<^sub>i,s\\<^sub>-\\<^sub>i)) = ((s\\<^sub>i \\<in> pure_strategies i) \\<and> \n        (\\<forall>j. ((j \\<noteq> i) \\<longrightarrow> s$j \\<in> pure_strategies j)))\"\nproof - \n  have \"(pure_profile (s\\<^sub>i,s\\<^sub>-\\<^sub>i)) = (\\<forall>j. (s\\<^sub>i,s\\<^sub>-\\<^sub>i)$j \\<in> pure_strategies j)\"\n    by (simp add: pure_profile_def)\n  hence \"(pure_profile (s\\<^sub>i,s\\<^sub>-\\<^sub>i)) = (((s\\<^sub>i,s\\<^sub>-\\<^sub>i)$i \\<in> pure_strategies i) \\<and>\n         (\\<forall>j. ((j \\<noteq> i) \\<longrightarrow> (s\\<^sub>i,s\\<^sub>-\\<^sub>i)$j \\<in> pure_strategies j)))\"\n    by auto\n  thus ?thesis\n    by (simp add: player_chooses_completion pure_completion_fixes_other_players)\nqed\n\nlemma pure_completion_of_legal_play: \n    fixes s :: \"'strategy^'player\"\n  assumes legal_play: \"pure_profile s\"\n    shows \"pure_profile (s\\<^sub>i,s\\<^sub>-\\<^sub>i) = (s\\<^sub>i \\<in> pure_strategies i)\"\n  using pure_completion_legal_iff legal_play pure_profile_def by auto\n\nlemma reconstruct_pure_profile [simp]: \n  fixes s :: \"'strategy^'player\"\n    and i :: 'player \n  shows \"(s$i,s\\<^sub>-\\<^sub>i) = s\" \nproof - \n  have \"\\<forall>j. (s$i,s\\<^sub>-\\<^sub>i)$j = s$j\"\n    using pure_completion_fixes_other_players player_chooses_completion by metis \n  thus ?thesis\n    by (simp add: vec_eq_iff) \nqed\n\nsubsection \"Basic solution concepts\"\n\n(* Note that ((s')$i,s'\\<^sub>-\\<^sub>i) is just s', which simp knows due to reconstruct_pure_profile. *)\ndefinition dominant_strategy_solution :: \"'strategy^'player \\<Rightarrow> bool\"\n  where \"dominant_strategy_solution s = ((pure_profile s) \\<and> \n        (\\<forall>i. \\<forall>s'. (pure_profile s' \\<longrightarrow> payoff (s$i,s'\\<^sub>-\\<^sub>i) i \\<ge> payoff (s'$i,s'\\<^sub>-\\<^sub>i) i)))\"\n\ndefinition pure_nash_equilibrium :: \"'strategy^'player \\<Rightarrow> bool\"\n  where \"pure_nash_equilibrium s = ((pure_profile s) \\<and> \n        (\\<forall>i. \\<forall>s'\\<^sub>i \\<in> pure_strategies i. payoff (s$i,s\\<^sub>-\\<^sub>i) i \\<ge> payoff (s'\\<^sub>i,s\\<^sub>-\\<^sub>i) i))\"\n\nlemma completion_reverses_itself: \"(a,(b,s\\<^sub>-\\<^sub>i)\\<^sub>-\\<^sub>i) = (a,s\\<^sub>-\\<^sub>i)\"\nproof - \n  have \"\\<forall>j. (a,(b,s\\<^sub>-\\<^sub>i)\\<^sub>-\\<^sub>i)$j = (a,s\\<^sub>-\\<^sub>i)$j\"\n    by (metis player_chooses_completion pure_completion_fixes_other_players)\n  thus ?thesis\n    by (simp add: vec_eq_iff) \nqed\n\ntext \"Dominant pure strategy solutions are pure Nash equilibria.\"\nlemma dominant_imp_pure_nash:\n  fixes s\n  assumes dom: \"dominant_strategy_solution s\"\n  shows \"pure_nash_equilibrium s\"\nproof - \n  have \"pure_profile s\"\n    using dom dominant_strategy_solution_def by auto\n  \n  moreover have \"\\<forall>i. \\<forall>s'. (pure_profile s' \\<longrightarrow> payoff (s$i,s'\\<^sub>-\\<^sub>i) i \\<ge> payoff s' i)\"\n    using dom dominant_strategy_solution_def by auto\n  hence \"\\<forall>i. \\<forall>s'\\<^sub>i \\<in> pure_strategies i. (pure_profile (s'\\<^sub>i,s\\<^sub>-\\<^sub>i) \\<longrightarrow> \n        payoff (s$i,(s'\\<^sub>i,s\\<^sub>-\\<^sub>i)\\<^sub>-\\<^sub>i) i \\<ge> payoff (s'\\<^sub>i,s\\<^sub>-\\<^sub>i) i)\"\n    by simp\n  hence \"\\<forall>i. \\<forall>s'\\<^sub>i \\<in> pure_strategies i. (pure_profile (s'\\<^sub>i,s\\<^sub>-\\<^sub>i) \\<longrightarrow> \n        payoff s i \\<ge> payoff (s'\\<^sub>i,s\\<^sub>-\\<^sub>i) i)\"\n    by (simp add: completion_reverses_itself)\n  hence \"\\<forall>i. \\<forall>s'\\<^sub>i \\<in> pure_strategies i. (pure_profile s \\<longrightarrow> \n        payoff s i \\<ge> payoff (s'\\<^sub>i,s\\<^sub>-\\<^sub>i) i)\"\n    using pure_completion_of_legal_play by simp \n\n  ultimately show ?thesis\n    using pure_nash_equilibrium_def by auto \nqed\n\nend\n\ntext \"Strategic form games with real-valued payoffs.\"\nlocale real_out_strategic_game = strategic_game pure_strategies payoffs\n  for pure_strategies \n  and payoffs :: \"('strategy, 'player) vec \\<Rightarrow> (real, 'player :: finite) vec\"\nbegin\n\ntext \"For real-valued payoffs, costs can be defined to be their additive inverse.\"\ndefinition costs :: \"('strategy, 'player) vec \\<Rightarrow> (real, 'player) vec\"\n  where \"costs s = -payoffs s\"\n\ndefinition cost :: \"('strategy, 'player) vec \\<Rightarrow> 'player \\<Rightarrow> real\"\n  where \"cost s i = (costs s)$i\"\n\nlemma cost_neg_pay: \n  shows \"cost s i = -payoff s i\"\n  by (simp add: cost_def costs_def payoff_def)\n\nend\n\nsection \"Example Games\"\n\nsubsection \"2-player games\"\ndatatype two_player = P1 | P2\n\ninstance two_player :: finite\nproof \n  have \"(UNIV :: two_player set) = {P1, P2}\"\n    by (metis UNIV_eq_I insertCI two_player.exhaust)\n  thus \"finite (UNIV :: two_player set)\"\n    using finite.simps by auto\nqed\n\ntext \"The Prisoner's Dilemma\"\ndatatype prisoner_strat = Confess | Silent\n\ninterpretation real_out_strategic_game \n  \"(\\<lambda>(i::two_player). {Confess, Silent})\"\n  \"(\\<lambda>s. (\\<chi> i. if s$i = Confess then \n          (if s = (\\<chi> j. Confess) then 4 else 1) \n        else \n          (if s = (\\<chi> j. Silent) then 2 else 5) ))\" \nproof \n  show \"{Confess, Silent} \\<noteq> {}\"\n    by simp \nqed \n\nend", "meta": {"author": "larswe", "repo": "game-theory", "sha": "493845341fa59b1e9c1315e020ace0463b671722", "save_path": "github-repos/isabelle/larswe-game-theory", "path": "github-repos/isabelle/larswe-game-theory/game-theory-493845341fa59b1e9c1315e020ace0463b671722/Game_Theory.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637505099167, "lm_q2_score": 0.8596637469145053, "lm_q1q2_score": 0.7390217608499315}}
{"text": "section {* Arrays *}\n\ntheory Array\n  imports Main\nbegin\n\ntype_synonym 'a array = \"(nat \\<Rightarrow> 'a) \\<times> nat\"\n\ndefinition len_array :: \"'a array \\<Rightarrow> nat\" (\"len _\" [100] 100) where\n  \"len a \\<equiv> snd a\"\n\ndefinition access_array :: \"'a array \\<Rightarrow> nat \\<Rightarrow> 'a\" (\"_<_>\" [100, 50] 100) where\n  \"a<i> \\<equiv> (fst a) i\" \n\ndefinition is_empty_array :: \"'a array \\<Rightarrow> bool\" where\n  \"is_empty_array a \\<equiv> len a = 0\"\n\ndefinition upd_array :: \"'a array \\<Rightarrow> nat \\<Rightarrow> 'a \\<Rightarrow> 'a array\" (\"_<_ := _>\" [100, 50, 50] 100) where\n  \"a<i := n> \\<equiv> ((fst a)(i := n), snd a)\"\n\ndefinition new_array :: \"nat \\<Rightarrow> 'a \\<Rightarrow> 'a array\" where\n  \"new_array l n = (\\<lambda>_. n, l)\"\n\ndefinition array_rev :: \"'a array \\<Rightarrow> 'a array\" (\"rev _\" [100] 100) where\n  \"rev a \\<equiv> (\\<lambda>i. if i > 0 \\<and> i \\<le> len a then a<len a - i + 1> else a<i>, len a)\"\n\nlemma len_rev [simp]: \"len (rev a) = len a\"\n  by (auto simp: len_array_def array_rev_def)\n\nlemma rev_rev [simp]: \"rev (rev a) = a\"\n  apply (auto simp: array_rev_def len_array_def access_array_def)\n  apply (case_tac a)\n  apply auto\n  apply (rule ext)\n  apply (auto simp: len_array_def access_array_def)\ndone\n\ndefinition interval :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat set\" (\"\\<lbrace>_, _\\<rbrace>\") where\n  \"\\<lbrace>k, l\\<rbrace> \\<equiv> {i. k \\<le> i \\<and> i \\<le> l}\"\n\n(* Sum from offset the number of value n *)\nprimrec array_sum :: \"'a array \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow>  'a :: {plus, zero}\" where\n  \"array_sum a off 0 = 0\"\n| \"array_sum a off (Suc n) = a<off + n> + array_sum a off n\"\n\nfun array_sorted_off :: \"'a :: order array \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> bool\" where\n  \"array_sorted_off a off 0 \\<longleftrightarrow> True\"\n| \"array_sorted_off a off (Suc 0) \\<longleftrightarrow> True\" \n| \"array_sorted_off a off (Suc (Suc n)) \\<longleftrightarrow> a<off + n> \\<le> a<off + Suc n> \\<and> array_sorted_off a off (Suc n)\"\n\nlemma array_sorted_off_var: \"array_sorted_off a (Suc 0) N \\<longleftrightarrow> (\\<forall>i j. 0 < i \\<and> i \\<le> j \\<and> j \\<le> N \\<longrightarrow> a<i> \\<le> a <j>)\"\n  apply (induct N)\n  apply clarsimp\n  apply (case_tac N)\n  apply auto\n  using le_Suc_eq apply auto[1]\nby (metis dual_order.trans le_SucE le_less)\n\n(* Array is sorted except in one place *)\ndefinition sorted_but :: \"('a :: order) array \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> bool\" where\n  \"sorted_but a N k \\<equiv> \\<forall>i j. 0 < i \\<and> i \\<le> j \\<and> j \\<le> N \\<and> i \\<noteq> k \\<and> k \\<noteq> j \\<longrightarrow> a<i> \\<le> a<j>\"\n\n\n\ndefinition array_sorted :: \"'a :: order array \\<Rightarrow> bool\" where\n  \"array_sorted a \\<equiv> array_sorted_off a 1 (len a)\"\n\nlemma \"array_sorted_off a i n \\<Longrightarrow> array_sorted_off a (Suc i) (n - 1)\"\n  apply (induct n)\n  apply auto\n  apply (case_tac n)\n  apply auto\n  apply (case_tac nat)\nby auto\n\ndefinition bij_prop :: \"(nat \\<Rightarrow> nat) \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> bool\" where\n  \"bij_prop f x y \\<equiv> bij f \\<and> (\\<forall>i. i \\<notin> \\<lbrace>x, y\\<rbrace> \\<longrightarrow> f i = i)\"\n\nlemma bij_prop1: \"bij_prop f x y \\<Longrightarrow> \\<forall>i \\<in> \\<lbrace>x, y\\<rbrace>. f i \\<in> \\<lbrace>x, y\\<rbrace>\"\n  apply (clarsimp simp: bij_prop_def)\n  by (metis bij_pointE)\n\nlemma bij_prop2: \"bij_prop f x y \\<Longrightarrow> x' \\<le> x \\<Longrightarrow> y \\<le> y' \\<Longrightarrow> bij_prop f x' y'\"\n  by (auto simp: bij_prop_def interval_def)\n\nlemma bij_prop_id [simp, intro]: \"bij_prop id x y\"\n  by (auto simp: bij_prop_def)\n\ndefinition perm_betw :: \"'a array \\<Rightarrow> 'a array \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> bool\" where\n  \"perm_betw a b x y \\<equiv> \\<exists>f. bij_prop f x y \\<and> (\\<forall>i. a<i> = b<f i>)\" \n\ndefinition perm :: \"'a array \\<Rightarrow> 'a array \\<Rightarrow> bool\" (\"_ <~~> _\"  [50, 50] 50)  where\n  \"perm a b \\<equiv> len a = len b \\<and> perm_betw a b 1 (len a)\"\n\nlemma perm_refl [iff]: \"l <~~> l\"\n  by (auto simp: perm_def perm_betw_def)\n\nlemma xperm_empty_imp: \"is_empty_array a \\<Longrightarrow> a <~~> b \\<Longrightarrow> is_empty_array b\"\n  by (auto simp: is_empty_array_def perm_def)\n\nlemma perm_length: \"a <~~> b \\<Longrightarrow> len a = len b\"\n  by (auto simp: perm_def)\n\nlemma perm_comm: \"a <~~> b \\<Longrightarrow> b <~~> a\"\n  apply (clarsimp simp: perm_def perm_betw_def)\n  apply (rule_tac x=\"the_inv f\" in exI)\n  apply (clarsimp simp:  bij_prop_def bij_betw_the_inv_into bij_is_inj bij_is_surj f_the_inv_into_f)\n  apply (metis bij_is_inj the_inv_f_f)\ndone\n \nlemma perm_rev: \"rev a <~~> a\"\n  apply (simp add: perm_def perm_betw_def)\n  apply (rule_tac x=\"\\<lambda>i. if i > 0 \\<and> i \\<le> len a then len a - i + 1 else i\" in exI)\n  apply (auto simp: array_rev_def access_array_def bij_prop_def interval_def)\n  apply (auto simp: bij_def inj_on_def image_def)\n  by presburger\n\nend", "meta": {"author": "victorgomes", "repo": "veritas", "sha": "d0b50770f9146f18713a690b87dc8fafa6a87580", "save_path": "github-repos/isabelle/victorgomes-veritas", "path": "github-repos/isabelle/victorgomes-veritas/veritas-d0b50770f9146f18713a690b87dc8fafa6a87580/HL/Array.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.859663743319094, "lm_q2_score": 0.8596637433190939, "lm_q1q2_score": 0.739021751577397}}
{"text": "theory examples\n  imports Main\nbegin\ndeclare [[names_short]]\n\n(* datatype nat = null | Suc nat *)\n\nfun add :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\" where \n\"add 0 n = n\" |\n\"add (Suc n) m = Suc (add n m)\"\n\nlemma add_02: \"add m 0 = m\" \n  apply(induction m)\n  apply(auto)\n  done\n\nlemma add_Suc: \"Suc (add m n) = add m (Suc n)\"\n  apply (induction m)\n  apply (auto)\n  done \n\ntheorem add_comm: \"add n m = add m n\"\n  apply (induction n)\n  apply (auto simp add: add_02 add_Suc)\n  done\n\ndatatype 'a list = Nil | Cons 'a \"'a list\"\n\nfun conc :: \"'a list \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where\n\"conc Nil ys = ys\" |\n\"conc (Cons x xs) ys = Cons x (conc xs ys)\"\n\nlemma conc_nil: \"conc xs Nil = xs\"\n  apply(induction xs)\n  apply (auto)\n  done\n\nfun rev :: \"'a list \\<Rightarrow> 'a list\" where\n\"rev Nil = Nil\" |\n\"rev (Cons x xs) = conc (rev xs) (Cons x Nil)\"\n\nlemma rev_rev: \"rev (rev xs) = xs\"\n  apply (induction xs)\n  oops\n\nend", "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/examples.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026528034426, "lm_q2_score": 0.8056321843145405, "lm_q1q2_score": 0.73900853985556}}
{"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_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_with_Proof/TIP15/TIP15/TIP_sort_nat_NMSortTDSorts.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026528034426, "lm_q2_score": 0.8056321843145404, "lm_q1q2_score": 0.7390085398555599}}
{"text": "theory PBExp imports AExp begin\n  \nsubsection \"Boolean Expressions\"\n  \ndatatype pbexp = VAR vname | NOT pbexp | AND pbexp pbexp | OR pbexp pbexp\n  \ntype_synonym bstate = \"vname \\<Rightarrow> bool\"\n  \nfun pbval :: \"pbexp \\<Rightarrow> bstate \\<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  \nsubsection \"Exercise 3.9\"\n  \nlemma not_not_is_id[simp]: \"pbval (NOT (NOT exp)) s = pbval exp s\"\n  apply(induction exp)\n  by simp_all\n    \nlemma equal_implies_nots_equal:\n  assumes \"pbval e1 s = pbval e2 s\"\n  shows \"pbval (NOT e1) s = pbval (NOT e2) s\"\n  by (simp add: assms)\n    \ntext{* Optimizing constructors: *}\n  \n  (* remove extraneous NOTs, i.e. NOT(NOT(x)) = x *)\nfun not_simp :: \"pbexp \\<Rightarrow> pbexp\"where\n  \"not_simp (VAR x) = (VAR x)\" |\n  (* First recurse on b, then pattern match *)\n  \"not_simp (NOT b) = (\n    case not_simp b of\n      (NOT c) \\<Rightarrow> c|\n      _       \\<Rightarrow> NOT b)\" |\n  \"not_simp (AND b1 b2) = (AND (not_simp b1) (not_simp b2))\" |\n  \"not_simp (OR b1 b2) = (OR (not_simp b1) (not_simp b2))\"\n  \nvalue \"not_simp (NOT (NOT exp))\"\nvalue \"not_simp (NOT (NOT (NOT exp)))\"\nvalue \"not_simp (NOT (NOT (NOT (NOT exp))))\"\n  \nlemma not_preserves_value[simp]: \"pbval (not_simp exp\\<^sub>o) s = pbval exp\\<^sub>o s\"\n  apply(induction exp\\<^sub>o)\n     apply simp_all\n  apply(simp split: pbexp.splits)\n  by auto\n    \n    (* This implementation could not even be auto-proved to terminate. *)\n     (* Converts a pbexp into NNF by pushing NOT inwards as much as possible. *)\n(* fun nnf_bad :: \"pbexp \\<Rightarrow> pbexp\" where\n  \"nnf_bad (VAR x) = (VAR x)\" |\n   \"nnf_bad (NOT b) = (\n    case nnf_bad b of\n      (NOT c)     \\<Rightarrow> c |\n      (AND b1 b2) \\<Rightarrow> (OR   (nnf_bad (NOT b1)) (nnf_bad (NOT b2))) |\n      (OR b1 b2)  \\<Rightarrow> (AND  (nnf_bad (NOT b1)) (nnf_bad (NOT b2))) |\n      (VAR c)     \\<Rightarrow> NOT (VAR c))\" |   \n  \"nnf_bad (AND b1 b2) = (AND (nnf_bad b1) (nnf_bad b2))\" |\n  \"nnf_bad (OR b1 b2) = (OR (nnf_bad b1) (nnf_bad b2))\"  *)\n    \n(* https://github.com/cmr/ConcreteSemantics/blob/master/CS_Ch3.thy   *)\n \n    (* matches GH *)\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 a b)) = OR (nnf (NOT a)) (nnf (NOT b))\" |\n  \"nnf (NOT (OR a b)) = AND (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  \n    \n(*     (* How many NOTs have been encountered so far, travelling from the expression's root to this point?\nEvery time two NOTs are encountered, the count is reset to zero. *)\ndatatype num_nots = ZeroN | OneN  \n  \n  (* Convert an expression to negative normal form; pass it ZeroN to begin with   *)\nfun nnf :: \"pbexp \\<Rightarrow> num_nots \\<Rightarrow> pbexp\" where\n  \"nnf (VAR x) ZeroN = (VAR x)\" |\n  \"nnf (VAR x) OneN = NOT (VAR x)\" |\n  \"nnf (NOT b) ZeroN = nnf b OneN\" |\n  \"nnf (NOT b) OneN = nnf b ZeroN\" |\n  \"nnf (AND b1 b2) ZeroN = (AND (nnf b1 ZeroN) (nnf b2 ZeroN))\" |\n  \"nnf (AND b1 b2) OneN = (OR (nnf b1 OneN) (nnf b2 OneN))\" |\n  \"nnf (OR b1 b2) ZeroN = (OR (nnf b1 ZeroN) (nnf b2 ZeroN))\" |\n  \"nnf (OR b1 b2) OneN = (AND (nnf b1 OneN) (nnf b2 OneN))\"\n  \nvalue \"nnf (NOT (NOT (VAR ''x''))) ZeroN\"\nvalue \"nnf (NOT (NOT (NOT (VAR ''x'')))) ZeroN\"\nvalue \"nnf (NOT (NOT (NOT (NOT (VAR ''x''))))) ZeroN\"\n  \nlemma nnf_preserves_value: \n  \"pbval (nnf exp num) s = \n    (case num of ZeroN \\<Rightarrow> pbval exp s | OneN \\<Rightarrow> (\\<not> pbval exp s))\"\n  apply(simp split: num_nots.splits)\n  apply(induction exp arbitrary:num)\n  by simp_all *)\n  \nlemma nnf_preserves_value:\"pbval (nnf exp) s = pbval exp s\"\n  apply(induction rule: nnf.induct)\n  by simp_all\n    \n    (* True when NOT is only applied to VARs. Otherwise, false.\nWhat about not(not(var))? *)\nfun is_nnf::\"pbexp \\<Rightarrow> bool\"where\n  \"is_nnf (VAR x) = True\" |\n  \"is_nnf (NOT (VAR _)) = True\" |\n  \"is_nnf (NOT _) = False\" |\n(*   \"is_nnf (NOT (VAR _)) = True\" |\n  \"is_nnf (NOT _) = 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  \nvalue \"is_nnf (VAR ''x'')\"  \nvalue \"is_nnf (NOT(VAR x))\"  \nvalue \"is_nnf (NOT(NOT(VAR x)))\"\n  \n(* lemma nnf_returns_nnf_expression: \"is_nnf (nnf exp num)\"\nproof(induction exp arbitrary:num)\n  case (VAR x)\n  then show ?case\n  proof(induction num)\n    case ZeroN\n    then show ?case by simp\n  next\n    case OneN\n    then show ?case by simp\n  qed\nnext\n  case (AND exp1 exp2)\n  then show ?case\n  proof(induction num)\n    case ZeroN\n    then show ?case by simp\n  next\n    case OneN\n    then show ?case by simp\n  qed\nnext\n  case (OR exp1 exp2)\n  then show ?case\n  proof(induction num)\n    case ZeroN\n    then show ?case by simp\n  next\n    case OneN\n    then show ?case by simp\n  qed\nnext\n  case (NOT exp)\n  then show ?case\n  proof(induction num)\n    case ZeroN\n    then show ?case by simp\n  next\n    case OneN\n    then show ?case by simp\n  qed\nqed *)\n  \n  (* NB: when using 'rule: nnf.induct', you MUST specify the induction variable! *)\nlemma nnf_returns_nnf_expression: \"is_nnf (nnf exp)\"\n  (* 4. \\<And>a b. is_nnf (NOT a) \\<Longrightarrow> is_nnf (NOT b) \\<Longrightarrow> is_nnf (NOT (AND a b)) *)\n  (* apply(induction rule: nnf.induct) (* Was creating FALSE goals *) *)\n  \n    (* 4. \\<And>a b. is_nnf (nnf (NOT a)) \\<Longrightarrow> is_nnf (nnf (NOT b)) \n\\<Longrightarrow> is_nnf (nnf (NOT (AND a b))) *)\n  apply(induction exp rule: nnf.induct)\n  by simp_all\n \n(*   (* Returns true if the expression is an OR   *)\nfun is_OR :: \"pbexp \\<Rightarrow> bool\" where  \n  \"is_OR (OR _ _) = True\" |\n  \"is_OR _ = False\"\n  \n  (* No ANDs have been seen yet (when traversing the tree from root to here)\n| at least one AND has been seen. *)\ndatatype seen_and = NeverSeenAnd | SeenAnAnd  \n  \n  (* An expression is in DNF (disjunctive normal form) if it is in NNF and if no OR occurs below an\nAND.*)\nfun is_dnf:: \"pbexp \\<Rightarrow> bool\"where\n  \"is_dnf (VAR _) = True\" |\n  \"is_dnf (NOT b) = is_dnf b\"|\n  \"is_dnf (AND b1 b2) = (is_dnf b1 \\<and> is_dnf b2 \\<and> (\\<not> is_OR b1) \\<and> (\\<not> is_OR b2))\" |\n  \"is_dnf (OR b1 b2) = (is_dnf b1 \\<and> is_dnf b2)\" *)\n  \n  (* An expression is in DNF (disjunctive normal form) if it is in NNF and if no OR occurs below an\nAND.*)\nfun is_dnf:: \"pbexp \\<Rightarrow> bool\"where\n  \"is_dnf (VAR _) = True\" |\n  \"is_dnf (NOT b) = is_dnf b\"|\n  \"is_dnf (AND (OR _ _) _) = False\" |\n  \"is_dnf (AND _ (OR _ _)) = False\" |\n  \"is_dnf (AND bl br) = (is_dnf bl \\<and> is_dnf br)\" |\n  \"is_dnf (OR b1 b2) = (is_dnf b1 \\<and> is_dnf b2)\"\n  \n(* The argument must be in NNF form (NOTs may only be applied to VAR, i.e. are at the leaves) \n If the arg is in NNF form, then once we have moved up the tree past the VARs and NOTs, all that\n remains are ANDs and ORs.\n We would like to bubble up the ORs*)\n(* fun dnf_of_nnf :: \"pbexp \\<Rightarrow> pbexp\" where\n  \"dnf_of_nnf (VAR x) = (VAR x)\" |\n \n  (* No need to recurse inside NOT, because arg is already in NNF form *)\n  (* \"dnf_of_nnf (NOT b) = NOT (dnf_of_nnf b)\" | *)\n  \"dnf_of_nnf (NOT b) = NOT b\" |\n \n  \"dnf_of_nnf (OR b1 b2) = (OR (dnf_of_nnf b1) (dnf_of_nnf b2))\"|\n \n(*   I think this is wrong; needs to recurse on children of AND before \n  pattern matching on those transformed children *)\n  \"dnf_of_nnf (AND (OR ll lr) (OR rl rr)) = \n    OR (OR (AND ll rl) (AND ll rr)) (OR (AND lr rl) (AND lr rr))\"|\n  \"dnf_of_nnf (AND (OR ll lr) r) = (OR (AND ll r) (AND lr r))\"|\n  \"dnf_of_nnf (AND l (OR rl rr)) = (OR (AND l rl) (AND l rr))\"|\n  \"dnf_of_nnf (AND l r) = AND (dnf_of_nnf l) (dnf_of_nnf r)\" *)\n  \n(* Before adding extra recursion   *)\n(* args:\nfirst child on an AND, already dnf'ed\nsecond child on an AND, already dnf'ed\nreturns: the transformed expression; pulling ORs up through the parent AND as needed *)\n(* fun push_and_below_or :: \"pbexp \\<Rightarrow> pbexp \\<Rightarrow> pbexp\" where\n\"push_and_below_or (OR or\\<^sub>l\\<^sub>l or\\<^sub>l\\<^sub>r) (OR or\\<^sub>r\\<^sub>l or\\<^sub>r\\<^sub>r) = \n  (OR (OR (AND or\\<^sub>l\\<^sub>l or\\<^sub>r\\<^sub>l) (AND or\\<^sub>l\\<^sub>l or\\<^sub>r\\<^sub>r)) (OR (AND or\\<^sub>l\\<^sub>r or\\<^sub>r\\<^sub>l) (AND or\\<^sub>l\\<^sub>r or\\<^sub>r\\<^sub>r)))\"|\n\"push_and_below_or (OR or\\<^sub>l\\<^sub>l or\\<^sub>l\\<^sub>r) notOr =\n  OR (AND or\\<^sub>l\\<^sub>l notOr) (AND or\\<^sub>l\\<^sub>r notOr)\"|\n\"push_and_below_or notOr (OR or\\<^sub>r\\<^sub>l or\\<^sub>r\\<^sub>r) =\n  OR (AND or\\<^sub>r\\<^sub>l notOr) (AND or\\<^sub>r\\<^sub>r notOr)\"|\n\"push_and_below_or notOr\\<^sub>l notOr\\<^sub>r = AND notOr\\<^sub>l notOr\\<^sub>r\" *)\n  \n(* TODO I think I need a new function: push AND down, that pushes AND down below all OR\nchildren. push_and_below_or is halfway there. *) \n  (* Push AND down:\nwhen encountering an AND above an OR (in dnf_of_nnf), this function is called.\nIt recursively pushes down AND until a AND, NOT, or VAR is found.\nIt converts a\n       and\n     or   or\ninto:\n        or\n    or      or\n and and and and \nThen it recurses on the 4 AND's that were just created, because there may be ORs beneath them.\n *)\n  \n(* args:\nfirst child on an AND, already dnf'ed\nsecond child on an AND, already dnf'ed\nreturns: the transformed expression; pushing an AND below its OR children (if there are any). This\nfunction will recursively call itself until all ORs have been moved above the ANDs.\n\nBecause dnf_of_nnf is this function's only caller, and dnf_of_nnf recurses on the children of an AND\nbefore calling this function, we know that we may stop once we encounter an AND, NOT, or VAR.*)\nfun push_and_below_or :: \"pbexp \\<Rightarrow> pbexp \\<Rightarrow> pbexp\" where\n\"push_and_below_or (OR or\\<^sub>l\\<^sub>l or\\<^sub>l\\<^sub>r) (OR or\\<^sub>r\\<^sub>l or\\<^sub>r\\<^sub>r) = \n  (OR (OR (push_and_below_or or\\<^sub>l\\<^sub>l or\\<^sub>r\\<^sub>l) (push_and_below_or or\\<^sub>l\\<^sub>l or\\<^sub>r\\<^sub>r)) \n      (OR (push_and_below_or or\\<^sub>l\\<^sub>r or\\<^sub>r\\<^sub>l) (push_and_below_or or\\<^sub>l\\<^sub>r or\\<^sub>r\\<^sub>r)))\"|\n(* NB: the order of arguments to the recursive calls to push_and_below_or, found below, are\ncritical. For example, changing (push_and_below_or or\\<^sub>l\\<^sub>l notOr) to (push_and_below_or notOr or\\<^sub>l\\<^sub>l)\nwill cause auto-termination proof of this function to fail.*)\n\"push_and_below_or (OR or\\<^sub>l\\<^sub>l or\\<^sub>l\\<^sub>r) notOr =\n  OR (push_and_below_or or\\<^sub>l\\<^sub>l notOr) (push_and_below_or or\\<^sub>l\\<^sub>r notOr)\"|\n\"push_and_below_or notOr (OR or\\<^sub>r\\<^sub>l or\\<^sub>r\\<^sub>r) =\n  OR (push_and_below_or notOr or\\<^sub>r\\<^sub>l) (push_and_below_or notOr or\\<^sub>r\\<^sub>r)\"|\n\"push_and_below_or notOr\\<^sub>l notOr\\<^sub>r = AND notOr\\<^sub>l notOr\\<^sub>r\"  \n \nvalue \"push_and_below_or (OR (VAR ''1'') (OR (VAR ''2'') (VAR ''3''))) (OR (VAR ''4'') (VAR ''5''))\"\nvalue \"push_and_below_or (OR or\\<^sub>l\\<^sub>l or\\<^sub>l\\<^sub>r) (VAR ''y'')\"\nvalue \"push_and_below_or (VAR ''x'') (OR or\\<^sub>r\\<^sub>l or\\<^sub>r\\<^sub>r)\"\nvalue \"push_and_below_or (VAR ''x'') (VAR ''y'')\"\n  \nlemma push_and_below_or_preserves_eval:\"pbval (push_and_below_or el er) s = pbval (AND el er) s\"\n  apply(induction el er rule: push_and_below_or.induct)\n                      apply(simp_all)\n  by auto\n\nlemma push_and_below_or_preserves_nnf:\"is_nnf el \\<Longrightarrow> is_nnf er \\<Longrightarrow> is_nnf (push_and_below_or el er)\"\n  apply(induction el er rule: push_and_below_or.induct)\n  by (simp_all)\n\nlemma push_and_below_or_preserves_dnf:\n  \"is_dnf el \\<Longrightarrow> is_dnf er \\<Longrightarrow> is_dnf (push_and_below_or el er)\"\n  apply(induction el er rule: push_and_below_or.induct)\n  by (simp_all)\n\n(* The argument must be in NNF form (NOTs may only be applied to VAR, i.e. are at the leaves) \n If the arg is in NNF form, then once we have moved up the tree past the VARs and NOTs, all that\n remains are ANDs and ORs.\n We would like to bubble up the ORs*)\nfun dnf_of_nnf :: \"pbexp \\<Rightarrow> pbexp\" where\n  \"dnf_of_nnf (VAR x) = (VAR x)\" |\n  (* No need to recurse inside the NOT because we know it's in NNF form. *)\n  \"dnf_of_nnf (NOT b) = NOT b\" |\n  \"dnf_of_nnf (AND b\\<^sub>l b\\<^sub>r) = \n    (let dnf_b\\<^sub>l = dnf_of_nnf b\\<^sub>l;\n         dnf_b\\<^sub>r = dnf_of_nnf b\\<^sub>r\n    in push_and_below_or dnf_b\\<^sub>l dnf_b\\<^sub>r)\" |\n  \"dnf_of_nnf (OR b1 b2) = (OR (dnf_of_nnf b1) (dnf_of_nnf b2))\"\n  \nvalue \"dnf_of_nnf (AND (OR or\\<^sub>l\\<^sub>l or\\<^sub>l\\<^sub>r) (VAR ''y''))\"\n  \nlemma dnf_preserves_value[simp]:\"pbval (dnf_of_nnf exp) s = pbval exp s\"\n  apply(induction exp)\n     apply(simp_all)\n  using push_and_below_or_preserves_eval by simp\n    \nlemma dnf_of_nnf_returns_dnf:\"is_nnf exp \\<Longrightarrow> is_dnf (dnf_of_nnf exp)\"\nproof(induction exp rule: dnf_of_nnf.induct)\n  case (1 x)\n  then show ?case by simp\nnext\n  case (2 b)\n  then show ?case \n    apply simp\n      using is_dnf.simps(1) is_nnf.elims(2) by blast\nnext\n  case (3 b\\<^sub>l b\\<^sub>r)\n  then show ?case \n    by (simp add: push_and_below_or_preserves_dnf)\nnext\n  case (4 b1 b2)\n  then show ?case by simp\nqed\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/PBExp.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.855851143290548, "lm_q2_score": 0.8633916064586998, "lm_q1q2_score": 0.7389346934951412}}
{"text": "(* Author: Anthony Bordg, University of Cambridge, apdb3@cam.ac.uk *)\n\ntheory Complex_Vectors\nimports \n  Quantum\n  VectorSpace.VectorSpace\nbegin\n\n\nsection \\<open>The Vector Space of Complex Vectors of Dimension n\\<close>\n\ndefinition module_cpx_vec:: \"nat \\<Rightarrow> (complex, complex vec) module\" where\n\"module_cpx_vec n \\<equiv> module_vec TYPE(complex) n\"\n\ndefinition cpx_rng:: \"complex ring\" where\n\"cpx_rng \\<equiv> \\<lparr>carrier = UNIV, mult = (*), one = 1, zero = 0, add = (+)\\<rparr>\"\n\nlemma cpx_cring_is_field [simp]:\n  \"field cpx_rng\"\n  apply unfold_locales\n  apply (auto intro: right_inverse simp: cpx_rng_def Units_def field_simps)\n  by (metis add.right_neutral add_diff_cancel_left' add_uminus_conv_diff)\n\nlemma cpx_abelian_monoid [simp]:\n  \"abelian_monoid cpx_rng\"\n  using cpx_cring_is_field\n  by (simp add: field_def abelian_group_def cring_def domain_def ring_def)\n\nlemma vecspace_cpx_vec [simp]:\n  \"vectorspace cpx_rng (module_cpx_vec n)\"\n  apply unfold_locales\n  apply (auto simp: cpx_rng_def module_cpx_vec_def module_vec_def Units_def field_simps)\n  apply (auto intro: right_inverse add_inv_exists_vec)\n  by (metis add.right_neutral add_diff_cancel_left' add_uminus_conv_diff)\n\n\n\ndefinition state_basis:: \"nat \\<Rightarrow> nat \\<Rightarrow> complex vec\" where\n\"state_basis n i \\<equiv> unit_vec (2^n) i\"\n\ndefinition unit_vectors:: \"nat \\<Rightarrow> (complex vec) set\" where\n\"unit_vectors n \\<equiv> {unit_vec n i | i::nat. 0 \\<le> i \\<and> i < n}\"\n\nlemma unit_vectors_carrier_vec [simp]:\n  \"unit_vectors n \\<subseteq> carrier_vec n\"\n  using unit_vectors_def by auto\n\nlemma (in Module.module) finsum_over_singleton [simp]:\n  assumes \"f x \\<in> carrier M\"\n  shows \"finsum M f {x} = f x\"\n  using assms by simp\n\nlemma lincomb_over_singleton [simp]:\n  assumes \"x \\<in> carrier_vec n\" and \"f \\<in> {x} \\<rightarrow> UNIV\"\n  shows \"module.lincomb (module_cpx_vec n) f {x} = f x \\<cdot>\\<^sub>v x\" \n  using assms module.lincomb_def module_cpx_vec module_cpx_vec_def module.finsum_over_singleton\n  by (smt module_vec_simps(3) module_vec_simps(4) smult_carrier_vec)\n\nlemma dim_vec_lincomb [simp]:\n  assumes \"finite F\" and \"f: F \\<rightarrow> UNIV\" and \"F \\<subseteq> carrier_vec n\"\n  shows \"dim_vec (module.lincomb (module_cpx_vec n) f F) = n\"\n  using assms\nproof(induct F)\n  case empty\n  show \"dim_vec (module.lincomb (module_cpx_vec n) f {}) = n\"\n  proof -\n    have \"module.lincomb (module_cpx_vec n) f {} = 0\\<^sub>v n\"\n      using module.lincomb_def abelian_monoid.finsum_empty module_cpx_vec_def vecspace_cpx_vec vectorspace_def\n      by (smt abelian_group_def Module.module_def module_vec_simps(2))\n    thus ?thesis by simp\n  qed\nnext\n  case (insert x F)\n  hence \"module.lincomb (module_cpx_vec n) f (insert x F) = \n    (f x \\<cdot>\\<^sub>v x) \\<oplus>\\<^bsub>module_cpx_vec n\\<^esub> module.lincomb (module_cpx_vec n) f F\"\n    using module_cpx_vec_def module_vec_def module_cpx_vec module.lincomb_insert cpx_rng_def insert_subset\n    by (smt Pi_I' UNIV_I Un_insert_right module_vec_simps(4) partial_object.select_convs(1) sup_bot.comm_neutral)\n  hence \"dim_vec (module.lincomb (module_cpx_vec n) f (insert x F)) = \n    dim_vec (module.lincomb (module_cpx_vec n) f F)\"\n    using index_add_vec by (simp add: module_cpx_vec_def module_vec_simps(1))\n  thus \"dim_vec (module.lincomb (module_cpx_vec n) f (insert x F)) = n\"\n    using insert.hyps(3) insert.prems(2) by simp\nqed\n\nlemma lincomb_vec_index [simp]:\n  assumes \"finite F\" and a2:\"i < n\" and \"F \\<subseteq> carrier_vec n\" and \"f: F \\<rightarrow> UNIV\"\n  shows \"module.lincomb (module_cpx_vec n) f F $ i = (\\<Sum>v\\<in>F. f v * (v $ i))\"\n  using assms\nproof(induct F)\n  case empty\n  then show \"module.lincomb (module_cpx_vec n) f {} $ i = (\\<Sum>v\\<in>{}. f v * v $ i)\"\n    apply auto\n    using a2 module.lincomb_def abelian_monoid.finsum_empty module_cpx_vec_def\n    by (metis (mono_tags) abelian_group_def index_zero_vec(1) module_cpx_vec Module.module_def module_vec_simps(2))\nnext\n  case(insert x F)\n  then show \"module.lincomb (module_cpx_vec n) f (insert x F) $ i = (\\<Sum>v\\<in>insert x F. f v * v $ i)\"\n    apply auto\n  proof -\n    have \"module.lincomb (module_cpx_vec n) f (insert x F) = \n      f x \\<cdot>\\<^sub>v x \\<oplus>\\<^bsub>module_cpx_vec n\\<^esub> module.lincomb (module_cpx_vec n) f F\"\n      using module.lincomb_insert module_cpx_vec insert.hyps(1) module_cpx_vec_def module_vec_def\n        insert.prems(2) insert.hyps(2) insert.prems(3) insert_def\n      by (smt Pi_I' UNIV_I Un_insert_right cpx_rng_def insert_subset module_vec_simps(4) \n          partial_object.select_convs(1) sup_bot.comm_neutral)\n    then have \"module.lincomb (module_cpx_vec n) f (insert x F) $ i = \n      (f x \\<cdot>\\<^sub>v x) $ i + module.lincomb (module_cpx_vec n) f F $ i\"\n      using index_add_vec(1) a2 dim_vec_lincomb\n      by (metis Pi_split_insert_domain  insert.hyps(1) insert.prems(2) insert.prems(3) insert_subset \n          module_cpx_vec_def module_vec_simps(1))\n    thus \"module.lincomb (module_cpx_vec n) f (insert x F) $ i = f x * x $ i + (\\<Sum>v\\<in>F. f v * v $ i)\"\n      using index_smult_vec a2 insert.prems(2) insert_def insert.hyps(3) by auto\n  qed\nqed\n\nlemma unit_vectors_is_lin_indpt [simp]:\n  \"module.lin_indpt cpx_rng (module_cpx_vec n) (unit_vectors n)\"\nproof\n  assume \"module.lin_dep cpx_rng (module_cpx_vec n) (unit_vectors n)\"\n  hence \"\\<exists>A a v. (finite A \\<and> A \\<subseteq> (unit_vectors n) \\<and> (a \\<in> A \\<rightarrow> UNIV) \\<and> \n    (module.lincomb (module_cpx_vec n) a A = \\<zero>\\<^bsub>module_cpx_vec n\\<^esub>) \\<and> (v \\<in> A) \\<and> (a v \\<noteq> \\<zero>\\<^bsub>cpx_rng\\<^esub>))\"\n    using module.lin_dep_def cpx_rng_def module_cpx_vec by (smt Pi_UNIV UNIV_I)\n  moreover obtain A and a and v where f1:\"finite A\" and f2:\"A \\<subseteq> (unit_vectors n)\" and \"a \\<in> A \\<rightarrow> UNIV\" \n    and f4:\"module.lincomb (module_cpx_vec n) a A = \\<zero>\\<^bsub>module_cpx_vec n\\<^esub>\" and f5:\"v \\<in> A\" and \n    f6:\"a v \\<noteq> \\<zero>\\<^bsub>cpx_rng\\<^esub>\"\n    using calculation by blast\n  moreover obtain i where f7:\"v = unit_vec n i\" and f8:\"i < n\"\n    using unit_vectors_def calculation by auto\n  ultimately have f9:\"module.lincomb (module_cpx_vec n) a A $ i = (\\<Sum>u\\<in>A. a u * (u $ i))\"\n    using lincomb_vec_index \n    by (smt carrier_dim_vec index_unit_vec(3) mem_Collect_eq subset_iff sum.cong unit_vectors_def)\n  moreover have \"\\<forall>u\\<in>A.\\<forall>j<n. u = unit_vec n j \\<longrightarrow> j \\<noteq> i \\<longrightarrow> a u * (u $ i) = 0\"\n    using unit_vectors_def index_unit_vec by (simp add: f8)\n  then have \"(\\<Sum>u\\<in>A. a u * (u $ i)) = (\\<Sum>u\\<in>A. if u=v then a v * v $ i else 0)\"\n    using f2 unit_vectors_def f7 by (smt mem_Collect_eq subsetCE sum.cong)\n  also have \"\\<dots> = a v * (v $ i)\"\n    using abelian_monoid.finsum_singleton[of cpx_rng v A \"\\<lambda>u\\<in>A. a u * (u $ i)\"] cpx_abelian_monoid\n      f5 f1 cpx_rng_def by simp\n  also have \"\\<dots> = a v\"\n    using f7 index_unit_vec f8 by simp\n  also have \"\\<dots> \\<noteq> 0\"\n    using f6 by (simp add: cpx_rng_def)\n  finally show False\n    using f4 module_cpx_vec_def module_vec_def index_zero_vec f8 f9 by (simp add: module_vec_simps(2))\nqed\n\nlemma unit_vectors_is_genset [simp]:\n  \"module.gen_set cpx_rng (module_cpx_vec n) (unit_vectors n)\"\nproof\n  show \"module.span cpx_rng (module_cpx_vec n) (unit_vectors n) \\<subseteq> carrier (module_cpx_vec n)\"\n    using module.span_def dim_vec_lincomb carrier_vec_def cpx_rng_def\n    by (smt Collect_mono index_unit_vec(3) module.span_is_subset2 module_cpx_vec module_cpx_vec_def \n        module_vec_simps(3) unit_vectors_def)\nnext\n  show \"carrier (module_cpx_vec n) \\<subseteq> module.span cpx_rng (module_cpx_vec n) (unit_vectors n)\"\n  proof\n    fix v\n    assume a1:\"v \\<in> carrier (module_cpx_vec n)\"\n    define A a lc where \"A = {unit_vec n i ::complex vec| i::nat. i < n \\<and> v $ i \\<noteq> 0}\" and \n      \"a = (\\<lambda>u\\<in>A. u \\<bullet> v)\" and \"lc = module.lincomb (module_cpx_vec n) a A\"\n    then have f1:\"finite A\" by simp\n    have f2:\"A \\<subseteq> carrier_vec n\"\n      using carrier_vec_def A_def by auto\n    have f3:\"a \\<in> A \\<rightarrow> UNIV\"\n      using a_def by simp\n    then have f4:\"dim_vec v = dim_vec lc\"\n      using f1 f2 f3 a1 module_cpx_vec_def dim_vec_lincomb lc_def by (simp add: module_vec_simps(3))\n    then have f5:\"i < n \\<Longrightarrow> lc $ i = (\\<Sum>u\\<in>A. u \\<bullet> v * u $ i)\" for i\n      using lincomb_vec_index lc_def a_def f1 f2 f3 by simp\n    then have \"i < n \\<Longrightarrow> j < n \\<Longrightarrow> j \\<noteq> i \\<Longrightarrow> unit_vec n j \\<bullet> v * unit_vec n j $ i = 0\" for i j by simp\n    then have \"i < n \\<Longrightarrow> lc $ i = (\\<Sum>u\\<in>A. if u = unit_vec n i then v $ i else 0)\" for i\n      using a1 A_def f5 scalar_prod_left_unit\n      by (smt f4 carrier_vecI dim_vec_lincomb f1 f2 f3 index_unit_vec(2) lc_def \n          mem_Collect_eq mult.right_neutral sum.cong)\n    then have \"i < n \\<Longrightarrow> lc $ i = v $ i\" for i\n      using abelian_monoid.finsum_singleton[of cpx_rng i] A_def cpx_rng_def by simp\n    then have f6:\"v = lc\"\n      using eq_vecI f4 dim_vec_lincomb f1 f2 lc_def by auto\n    have \"A \\<subseteq> unit_vectors n\"\n      using A_def unit_vectors_def by auto\n    thus \"v \\<in> module.span cpx_rng (module_cpx_vec n) (unit_vectors n)\"\n      using f6 module.span_def[of cpx_rng \"module_cpx_vec n\"] lc_def f1 f2 cpx_rng_def module_cpx_vec\n      by (smt Pi_I' UNIV_I mem_Collect_eq partial_object.select_convs(1))\n  qed\nqed\n    \nlemma unit_vectors_is_basis [simp]:\n  \"vectorspace.basis cpx_rng (module_cpx_vec n) (unit_vectors n)\"\nproof -\n  fix n\n  have \"unit_vectors n \\<subseteq> carrier (module_cpx_vec n)\"\n    using unit_vectors_def module_cpx_vec_def module_vec_simps(3) by fastforce\n  then show ?thesis\n    using vectorspace.basis_def unit_vectors_is_lin_indpt unit_vectors_is_genset vecspace_cpx_vec\n    by(smt carrier_dim_vec index_unit_vec(3) mem_Collect_eq module_cpx_vec_def module_vec_simps(3) \n        subsetI unit_vectors_def)\nqed\n\nlemma state_qbit_is_lincomb [simp]:\n  \"state_qbit n = \n  {module.lincomb (module_cpx_vec (2^n)) a A|a A. \n    finite A \\<and> A\\<subseteq>(unit_vectors (2^n)) \\<and> a\\<in> A \\<rightarrow> UNIV \\<and> \\<parallel>module.lincomb (module_cpx_vec (2^n)) a A\\<parallel> = 1}\"\nproof\n  show \"state_qbit n\n    \\<subseteq> {module.lincomb (module_cpx_vec (2^n)) a A |a A.\n        finite A \\<and> A \\<subseteq> unit_vectors (2^n) \\<and> a \\<in> A \\<rightarrow> UNIV \\<and> \\<parallel>module.lincomb (module_cpx_vec (2^n)) a A\\<parallel> = 1}\"\n  proof\n    fix v\n    assume a1:\"v \\<in> state_qbit n\"\n    then show \"v \\<in> {module.lincomb (module_cpx_vec (2^n)) a A |a A.\n               finite A \\<and> A \\<subseteq> unit_vectors (2^n) \\<and> a \\<in> A \\<rightarrow> UNIV \\<and> \\<parallel>module.lincomb (module_cpx_vec (2^n)) a A\\<parallel> = 1}\"\n    proof -\n      obtain a and A where \"finite A\" and \"a\\<in> A \\<rightarrow> UNIV\" and \"A \\<subseteq> unit_vectors (2^n)\" and \n        \"v = module.lincomb (module_cpx_vec (2^n)) a A\"\n        using a1 state_qbit_def unit_vectors_is_basis vectorspace.basis_def module.span_def \n        vecspace_cpx_vec module_cpx_vec module_cpx_vec_def module_vec_def carrier_vec_def\n        by(smt Pi_UNIV UNIV_I mem_Collect_eq module_vec_simps(3))\n      thus ?thesis\n        using a1 state_qbit_def by auto\n    qed\n  qed\n  show \"{module.lincomb (module_cpx_vec (2 ^ n)) a A |a A.\n     finite A \\<and> A \\<subseteq> unit_vectors (2 ^ n) \\<and> a \\<in> A \\<rightarrow> UNIV \\<and> \\<parallel>module.lincomb (module_cpx_vec (2 ^ n)) a A\\<parallel> = 1}\n    \\<subseteq> state_qbit n\"\n  proof\n    fix v\n    assume \"v \\<in> {module.lincomb (module_cpx_vec (2 ^ n)) a A |a A.\n              finite A \\<and> A \\<subseteq> unit_vectors (2 ^ n) \\<and> a \\<in> A \\<rightarrow> UNIV \\<and> \\<parallel>module.lincomb (module_cpx_vec (2 ^ n)) a A\\<parallel> = 1}\"\n    then show \"v \\<in> state_qbit n\"\n      using state_qbit_def dim_vec_lincomb unit_vectors_carrier_vec by(smt mem_Collect_eq order_trans)\n  qed\nqed\n\n\nend\n", "meta": {"author": "AnthonyBordg", "repo": "Isabelle_marries_Dirac", "sha": "ab313fb4028c99bd5d97f8e30aaf1644e200d57b", "save_path": "github-repos/isabelle/AnthonyBordg-Isabelle_marries_Dirac", "path": "github-repos/isabelle/AnthonyBordg-Isabelle_marries_Dirac/Isabelle_marries_Dirac-ab313fb4028c99bd5d97f8e30aaf1644e200d57b/Complex_Vectors.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8962513814471134, "lm_q2_score": 0.8244619220634456, "lm_q1q2_score": 0.7389251365999054}}
{"text": "theory ex04\n  imports \"Demos/BST_Demo\"\nbegin\n\nfun in_range :: \"'a::linorder tree \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> 'a list\" where\n  \"in_range \\<langle>\\<rangle> _ _ = []\" | \n  \"in_range (Node l a r) u v = \n    (if u < a then in_range l u v else []) @\n    (if u \\<le> a \\<and> a \\<le> v then [a] else []) @\n    (if a < v then in_range r u v else [])\n\"\n\nvalue \"set_tree (Node (Node (Node \\<langle>\\<rangle> (1::nat) \\<langle>\\<rangle>) 2 (Node \\<langle>\\<rangle> (3::nat) \\<langle>\\<rangle>)) 4 (Node \\<langle>\\<rangle> (5::nat) \\<langle>\\<rangle>))\"\n\nlemma \"bst t \\<Longrightarrow> set (in_range t u v) = {x \\<in>set_tree t. u\\<le>x \\<and> x \\<le>v }\"\n  apply(induction t)\n  apply auto\n  done\n\nthm filter_empty_conv\n\n\n\nlemma [simp]: \"[] = filter P xs \\<longleftrightarrow> filter P xs = []\"\n  apply (induction xs)\n   apply auto\n  done\n\n\nlemma \"bst t \\<Longrightarrow> in_range t u v = filter (\\<lambda>x . u\\<le>x \\<and> x \\<le>v ) (inorder t)\"\n  apply(induction t)\n   apply (fastforce simp: filter_empty_conv)+\n  done\n\ntext \\<open>A version that needs less lemmas:\\<close>\n\nfun in_range' where\n  \"in_range' Leaf u v = []\"\n| \"in_range' (Node l x r) u v =\n      (if u < x \\<and> x < v then in_range' l u v @ x # in_range' r u v\n      else if u \\<le> x \\<and> x < v then x # in_range' r u v\n      else if u < x \\<and> x \\<le> v then in_range' l u v @ [x]\n      else if x < u then in_range' r u v\n      else if v < x then in_range' l u v\n      else if x = u \\<and> x = v then [x]\n      else []\n      )\"\n\nlemma \"bst t \\<Longrightarrow> set (in_range' t u v) = {x\\<in>set_tree t. u\\<le>x \\<and> x\\<le>v}\"\n  apply (induction t)\n   apply auto\n  done\n\nlemma \"bst t \\<Longrightarrow> in_range' t u v = filter (\\<lambda>x. u\\<le>x \\<and> x\\<le>v) (inorder t)\"\n  apply (induction t)\n   apply (auto simp: filter_empty_conv)\n  done\n\nterm \"()\"\n\nterm \"(\\<union>)\"\n\nfun enum :: \"nat \\<Rightarrow> unit tree set\" where\n  \"enum 0 = {}\" |\n  \"enum (Suc n) = enum n \\<union> {Node l () r | l r. l \\<in> enum n \\<and> r \\<in> enum n}\"\n\nfind_theorems \"_ \\<le> _ \\<Longrightarrow> _ \\<le> Suc _\"\n\nlemma enum_sound: \"t \\<in> enum n \\<Longrightarrow> height t \\<le> n\"\n  apply(induction n arbitrary: t)\n   apply (auto simp: le_SucI)\n  done\n\ntext \\<open>The correct definition of enum is below and the one above is the one is developed during the tutorial.\n            One cannot tell there is a mistake since the soundness theorem does not properly cover that mistake.\n            This shows how underspecifying formal properties can lead to missing bugs....\n            \\<close>\n\nfun enum' :: \"nat \\<Rightarrow> unit tree set\" where\n  \"enum' 0 = {Leaf}\" |\n  \"enum' (Suc n) = enum' n \\<union> {Node l () r | l r. l \\<in> enum' n \\<and> r \\<in> enum' n}\"\n\nend", "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/ex04.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8652240791017535, "lm_q2_score": 0.8539127510928476, "lm_q1q2_score": 0.7388258736975539}}
{"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 Main\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": "seL4", "repo": "isabelle", "sha": "e1ab32a3bb41728cd19541063283e37919978a4c", "save_path": "github-repos/isabelle/seL4-isabelle", "path": "github-repos/isabelle/seL4-isabelle/isabelle-e1ab32a3bb41728cd19541063283e37919978a4c/src/HOL/Library/Quotient_Type.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8539127380808499, "lm_q2_score": 0.865224091265267, "lm_q1q2_score": 0.7388258728258393}}
{"text": "theory LanguageModule\n  imports Language\nbegin\n\ndefinition fold_rel :: \"'a rel list \\<Rightarrow> 'a rel\" where\n  \"fold_rel xs = foldr op O xs Id\" \n\ndefinition eval_word :: \"'a rel list \\<Rightarrow> 'a set \\<Rightarrow> 'a set\" where\n  \"eval_word xs H = fold_rel xs `` H\"\n\nlemma eval_empty_word [simp]: \"eval_word [] h = h\"\n  by (auto simp add: eval_word_def fold_rel_def)\n\nlemma eval_cons_word [simp]: \"eval_word (x # xs) h = eval_word xs (x `` h)\"\n  by (auto simp add: eval_word_def fold_rel_def)\n\nlemma eval_append_word: \"eval_word (xs @ ys) h = eval_word ys (eval_word xs h)\"\n  by (induct xs arbitrary: h) simp_all\n\ndefinition module :: \"'a rel lan \\<Rightarrow> 'a set \\<Rightarrow> 'a set\" (infix \"\\<Colon>\" 60) where\n  \"x \\<Colon> h \\<equiv> \\<Union>{eval_word w h|w. w \\<in> x}\"\n\nlemma eval_word_continuous: \"eval_word w (\\<Union>X) = \\<Union>eval_word w ` X\"\n  by (induct w arbitrary: X) (auto simp add: image_def eval_word_def)\n\nlemma mod_mult: \"x\\<cdot>y \\<Colon> h = y \\<Colon> (x \\<Colon> h)\"\nproof -\n  have \"x\\<cdot>y \\<Colon> h = \\<Union>{eval_word w h|w. w \\<in> x\\<cdot>y}\"\n    by (simp add: module_def)\n  also have \"... = \\<Union>{eval_word (xw @ yw) h|xw yw. xw \\<in> x \\<and> yw \\<in> y}\"\n    by (auto simp add: l_prod_def complex_product_def)\n  also have \"... = \\<Union>{eval_word yw (eval_word xw h)|xw yw. xw \\<in> x \\<and> yw \\<in> y}\"\n    by (simp add: eval_append_word)\n  also have \"... = \\<Union>{\\<Union>{eval_word yw (eval_word xw h)|xw. xw \\<in> x}|yw. yw \\<in> y}\"\n    by blast\n  also have \"... = \\<Union>{eval_word yw (\\<Union>{eval_word xw h|xw. xw \\<in> x})|yw. yw \\<in> y}\"\n    by (subst eval_word_continuous) (auto simp add: image_def)\n  also have \"... = \\<Union>{eval_word yw (x \\<Colon> h)|yw. yw \\<in> y}\"\n    by (simp add: module_def)\n  also have \"... = y \\<Colon> (x \\<Colon> h)\"\n    by (simp add: module_def)\n  finally show ?thesis .\nqed\n\nlemma mod_one [simp]: \"{[]} \\<Colon> h = h\"\n  by (simp add: module_def)\n\nlemma mod_zero [simp]: \"{} \\<Colon> h = {}\"\n  by (simp add: module_def)\n\nlemma mod_empty [simp]: \"x \\<Colon> {} = {}\"\n  by (simp add: module_def eval_word_def)\n\nlemma mod_distl: \"(x \\<union> y) \\<Colon> h = (x \\<Colon> h) \\<union> (y \\<Colon> h)\"\nproof -\n  have \"(x \\<union> y) \\<Colon> h = \\<Union>{eval_word w h|w. w \\<in> x \\<union> y}\"\n    by (simp add: module_def)\n  also have \"... = \\<Union>{eval_word w h|w. w \\<in> x \\<or> w \\<in> y}\"\n    by blast\n  also have \"... = \\<Union>{eval_word w h|w. w \\<in> x} \\<union> \\<Union>{eval_word w h|w. w \\<in> y}\"\n    by blast\n  also have \"... = (x \\<Colon> h) \\<union> (y \\<Colon> h)\"\n    by (simp add: module_def)\n  finally show ?thesis .\nqed\n\nlemma mod_distr: \"x \\<Colon> (h \\<union> g) = (x \\<Colon> h) \\<union> (x \\<Colon> g)\"\nproof -\n  have \"x \\<Colon> (h \\<union> g) = \\<Union>{eval_word w (h \\<union> g)|w. w \\<in> x}\"\n    by (simp add: module_def)\n  also have \"... = \\<Union>{eval_word w h \\<union> eval_word w g|w. w \\<in> x}\"\n    by (simp add: eval_word_def) blast\n  also have \"... = \\<Union>{eval_word w h|w. w \\<in> x} \\<union> \\<Union>{eval_word w g|w. w \\<in> x}\"\n    by blast\n  also have \"... = (x \\<Colon> h) \\<union> (x \\<Colon> g)\"\n    by (simp add: module_def)\n  finally show ?thesis .\nqed\n\nlemma mod_isol: \"x \\<subseteq> y \\<Longrightarrow> x \\<Colon> p \\<subseteq> y \\<Colon> p\"\n  by (auto simp add: module_def)\n\nlemma mod_isor: \"p \\<subseteq> q \\<Longrightarrow> x \\<Colon> p \\<subseteq> x \\<Colon> q\"\n  by (metis mod_distr subset_Un_eq)\n\nlemma mod_continuous: \"\\<Union>X \\<Colon> p = \\<Union>{x \\<Colon> p|x. x \\<in> X}\"\n  by (simp add: module_def) blast\n\nlemma mod_continuous_var: \"\\<Union>{f x|x. P x} \\<Colon> p = \\<Union>{f x \\<Colon> p|x. P x}\"\n  by (simp add: mod_continuous) blast\n\ndefinition mod_test :: \"'a set \\<Rightarrow> 'a rel lan\" (\"_?\" [101] 100) where\n  \"p? \\<equiv> {[Id_on p]}\"\n\nlemma mod_test: \"p? \\<Colon> q = p \\<inter> q\"\n  by (auto simp add: module_def mod_test_def)\n\nlemma test_true: \"q \\<subseteq> p \\<Longrightarrow> p? \\<Colon> q = q\"\n  by (metis Int_absorb1 mod_test)\n\nlemma test_false: \"q \\<subseteq> -p \\<Longrightarrow> p? \\<Colon> q = {}\"\n  by (metis Int_commute disjoint_eq_subset_Compl mod_test)\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/Finite/LanguageModule.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887588023318196, "lm_q2_score": 0.8311430499496096, "lm_q1q2_score": 0.7386857016396308}}
{"text": "theory XO\nimports Main\nbegin\n\n(*=========================================================================================*)\nsection {* Introduction *}\n\ntext {* This example was translated from a VDM specification courtesy of Nick Battle from Fujistsu *}\n\n(*=========================================================================================*)\nsection {* VDM values *}\n\ntext {* This section defines the VDM  \\textsf{values} section of \\textsf{XO.vdmsl}. *}\n\nfind_theorems name:Relation\n\ntext {* The size of the board is 3, but we could generalise the game, or even make it 3D! *}\n\nabbreviation\n  SIZE :: nat\nwhere\n  \"SIZE \\<equiv> 3\"\n\ntext {* The maximum number of moves is the board dimensions *}\n\nabbreviation \"MAX \\<equiv> SIZE * SIZE\"\n\n\n(*=========================================================================================*)\nsection {* VDM types *}\n\ntext {* This section defines the VDM  \\textsf{types} section of \\textsf{XO.vdmsl}. *}\n\ntext {* We also define two types for the play outcome options and the players.\n        In VDM this is easier: we just need to extend the enumerated type.\n      *}\n\ndatatype GameResult = NOUGHT_WON | CROSS_WON | DRAW | UNFINISHED\n\ndatatype Player = NOUGHT | CROSS\n\nprint_theorems\n\n(* Teach proof by regular expressions *)\n(*typedef Player = \"{ NOUGHT, CROSS }\" by (rule exI,simp,rule disjI1,simp) *)\n\ntext {* We also need to know the set of valid players as all possible players. \n        This is a value in VDM *}\n\nabbreviation \"PLAYERS \\<equiv> {NOUGHT, CROSS}\"\n\ntext {* A move position is defined next as a pair of numbers with the invariant \n        they are non negative and within @{text \"SIZE\"} *}\n\ntype_synonym Pos = \"(nat \\<times> nat)\"\n\n(*\ndefinition\n  inv_Pos :: \"Pos \\<Rightarrow> bool\"\nwhere\n  \"inv_Pos pos \\<equiv> (fst pos) \\<ge> 1 \\<and> (fst pos) \\<le> SIZE \\<and> \n                  (snd pos) \\<ge> 1 \\<and> (snd pos) \\<le> SIZE\"\n*)\n\ntext {* For the @{term Pos} invariant we could either use field selection, \n        or patterns matching like in VDM $mk-Pos(x,y)$; we will choose the later. \n      *}\n\ndefinition\n  inv_Pos :: \"Pos \\<Rightarrow> bool\"\nwhere\n  \"inv_Pos z \\<equiv> let (x,y) = z in  \n                  x \\<ge> 1 \\<and> x \\<le> SIZE \\<and> \n                  y \\<ge> 1 \\<and> y \\<le> SIZE\"\n\nfind_theorems \"inv_Pos _\"\nthm inv_Pos_def\n\ntext {* Next we need to decide how the game is to be modelled. Discuss options in class/practicals *}\n\ntext {* The game is modelled as VDM Isabelle Map from position to player. The invariant\n        asserts that all positions in the domain satisfy the position type invariant as well.\n        Isabelle maps are total functions to an optional type:~it maps elements outside of \n        the domain to @{text \"None\"} and within the domain to @{text \"Some x\"}. So effectively,\n        @{text \"m :: T1 \\<rightharpoonup> T2\"} is the same as @{text \"m :: T1 \\<Rightarrow> T2 option\"}, where \n        @{text \"m x\"} can be either @{text \"None\"} if @{text \"x \\<notin> dom m\"} or @{text \"Some y\"}\n        if @{text \"x \\<in> dom m\"}.\n\n        This nesting of invariant checking is common place in our translation because VDM\n        type invariants are not maintained by Isabelle, hence we need to keep them ourselves.\n        For a manual translation, this obviously play a serious threat to correctness\n        (i.e. in case one misses checking the invariant at all necessary places).\n\n        As the @{text \"Game\"} invariant is on a set of @{text \"Pos\"}, we generalise it a bit.\n      *}\n\ntype_synonym Game = \"Pos \\<rightharpoonup> Player\"\n\ndefinition\n  inv_PosSet :: \"Pos set \\<Rightarrow> bool\"\nwhere\n  \"inv_PosSet ps \\<equiv> (\\<forall> pos \\<in> ps . inv_Pos pos)\"\n\ndefinition\n  inv_Game :: \"Game \\<Rightarrow> bool\"\nwhere\n  \"inv_Game g \\<equiv> inv_PosSet (dom g)\"\n\n\ntext {* Next we define play order and moves using lists. Play order as a list is a bit overkill.\n        Perhaps just a boolean would suffice. \\textbf{TODO: check - I guess it is modelled as a list because of Overture \n        animation or for generalisation of players to more than two?}\n      *}\n\ntype_synonym Moves = \"Pos list\"\ntype_synonym PlayOrder = \"Player list\"\n\ndefinition \n  inv_Moves :: \"Moves \\<Rightarrow> bool\"\nwhere\n  \"inv_Moves m \\<equiv> inv_PosSet (set m) \\<and> \n                 length m = card(set m) \\<and> \n                 length m > (card PLAYERS) * (SIZE-(1::nat)) \\<and> \n                 length m \\<le> MAX\" \n\ndefinition\n  inv_PlayOrder :: \"PlayOrder \\<Rightarrow> bool\"\nwhere\n  \"inv_PlayOrder po \\<equiv> length po > 0 \\<and> \n                       length po = card(set po) \\<and>  \n                       (set po) = PLAYERS\"\n\ntext {* Isabelle @{term \"length xs\"} is the same as VDM's $\\len{xs}$, whereas\n        @{term \"set xs\"} equals $\\elems{xs}$. One key difference from VDM is that\n        Isabelle lists are indexed from zero, whereas VDM sequences are indexed from one.\n      *}\n\ntype_synonym Line = \"Pos set\"\n\ndefinition\n  inv_Line :: \"Line \\<Rightarrow> bool\"\nwhere\n  \"inv_Line l \\<equiv> inv_PosSet l\"\n\n(* IJW: to me, this is not the invariant on a line! \n{(1,2), (1,3), (2,3)} does not a line make. Nor\n{(1,1)}\n*)\n\n(*-----------------------------------------------------------------------------------------*)\nsubsection {* Technical note *}\n\ntext {* Looking into Isabelle's libraries I guess there is  simpler and more efficient way\n        of calculating sequence injectivity by asking that all elements are distinct.\n      *}\n\n(* Referencial transparency; show distinct and set *)\nfind_theorems \"distinct _\"\nfind_theorems \"set _\"\nfind_theorems \"remdups _\"\n\n--\"declare [[smt_trace]]\"\nlemma \"distinct l \\<longleftrightarrow> length l = card(set l)\"\n--\"by (metis length_remdups_card_conv length_remdups_eq remdups_id_iff_distinct)\"\nby (metis card_distinct distinct_card)\n\nthm card_distinct distinct_card\n\n(* TODO: make defining this as part of coursework? *)\n\nlemma \"remdups m = m \\<longleftrightarrow> length m = card(set m)\"\nby (metis length_remdups_card_conv length_remdups_eq)\n\n(*=========================================================================================*)\nsection {* VDM functions *}\n\ntext {* This section defines the VDM \\textsf{functions} section of \\textsf{XO.vdmsl}. *}\n\n(*-----------------------------------------------------------------------------------------*)\nsubsection {* Extra VDM operators *}\n\ntext {* Certain VDM map operators are not defined, like range filtering or restriction. \n        We define it next as expected and give it a seemingly infix syntax.\n      *}\n\ndefinition\n  ran_restr :: \"('a \\<rightharpoonup> 'b) \\<Rightarrow> 'b set \\<Rightarrow> ('a \\<rightharpoonup> 'b)\" (infixl \"\\<triangleright>\" 105)\nwhere\n  \"m \\<triangleright> s \\<equiv> (\\<lambda>x . if (\\<exists> y. m x = Some y \\<and> y \\<in> s) then m x else None)\"\n\n\n(*-----------------------------------------------------------------------------------------*)\nsubsection {* Explicitly defined functions *}\n\ndefinition\n  movesForPlayer :: \"Game \\<Rightarrow> Player \\<Rightarrow> Pos set\"\nwhere\n  \"movesForPlayer g p \\<equiv> dom (g \\<triangleright> {p})\"\n\ndefinition\n  movesSoFar :: \"Game \\<Rightarrow> Pos set\"\nwhere\n  \"movesSoFar g \\<equiv> dom g\"\n\ndefinition \n  movesCountSoFar :: \"Game \\<Rightarrow> nat\"\nwhere\n  \"movesCountSoFar g \\<equiv> card (dom g)\" \n  --{* same as @{term \"(if (finite(dom g)) then card (dom g) else 0)\"} *}\n\n(* EXPLAIN: caveat about 0-3 = 0*)\ndefinition \n  movesCountLeft :: \"Game \\<Rightarrow> nat\"\nwhere\n  \"movesCountLeft g \\<equiv> MAX - movesCountSoFar g\"\n\ndefinition\n  makeMove :: \"Game \\<Rightarrow> Player \\<Rightarrow> Pos \\<Rightarrow> Game\"\nwhere\n  \"makeMove g p pos \\<equiv> g(pos \\<mapsto> p)\"\n\n(* See discussion below on post_makeMove on use or not of option types for resulting Game \ndefinition\n  makeMove :: \"Game \\<Rightarrow> Player \\<Rightarrow> Pos \\<Rightarrow> Game option\"\nwhere\n  \"makeMove g p pos \\<equiv> Some (g(pos \\<mapsto> p))\"\n*)\n\n(*-----------------------------------------------------------------------------------------*)\nsubsection {* Game solution (comparison) value *} \n\nabbreviation\n  BOARD :: \"nat set\"\nwhere\n  \"BOARD \\<equiv> {1 .. SIZE}\"\n\ndefinition\n  row :: \"nat \\<Rightarrow> Line\"\nwhere\n  \"row rr \\<equiv> { (r, c) . c \\<in> BOARD \\<and> r=rr \\<and> inv_Pos (r, c) }\"\n\ndeclare [[show_types]]\ndefinition\n  row2 :: \"nat \\<Rightarrow> Line\"\nwhere\n  \"row2 rr \\<equiv> { (rr, c) | c . c \\<in> BOARD \\<and> inv_Pos (rr, c) }\"\n\n--\"row2 1 \\<equiv> { (1, c) | c . c \\<in> 1..2 } \\<equiv> { (1, 1), (1, 2) }\"\n\nlemma \"row2 1 = { (1, 1), (1, 2), (1, 3) }\"\nunfolding row2_def inv_Pos_def\napply simp\napply auto\ndone\n\nlemma \"row2 r = row r\"\nunfolding row2_def row_def by auto\n\n(* IJW: Have a correct line invariant then prove that row(rr) satisfies it \n   IJW: Also, if c \\<in> BOARD, then surely the inv_Pos is a consequence? COuld prove to... \n  \n*)\ndefinition\n  col :: \"nat \\<Rightarrow> Line\"\nwhere\n  \"col cc \\<equiv> { (r,cc) | r . r \\<in> BOARD \\<and> inv_Pos (r, cc) }\"\n\nvalue \"{ [A,B,C] ! i | i . i \\<in> {1, 2} }\"\n\nabbreviation\n  allRows0 :: \"Line set\"\nwhere\n  \"allRows0 \\<equiv> { row 1, row 2, row 3 }\"\n\nabbreviation\n  allRows :: \"Line set\"\nwhere\n  \"allRows \\<equiv> \\<Union> r \\<in> BOARD . { row r }\"\n \nabbreviation\n  allCols :: \"Line set\"\nwhere\n  \"allCols \\<equiv> \\<Union> c \\<in> BOARD . { col c }\"\n\nabbreviation\n  downwardDiag0 :: \"Line\"\nwhere\n  \"downwardDiag0 \\<equiv> { (x,x) . x \\<in> BOARD }\" --\"variable capture on snd x?\"\n(* IJW: no capture, this just isn't set comprehension as you imagine it.\n   It should look like:\n *)\nabbreviation\n  downwardDiagIJW :: \"Line\"\nwhere\n  \"downwardDiagIJW \\<equiv> { (x,x)| x . x \\<in> BOARD }\"\n(* Now the lemma can be proved, see below. *)\n\nabbreviation\n  downwardDiag :: \"Line\"\nwhere\n  \"downwardDiag \\<equiv> { (x,y) . x \\<in> BOARD \\<and> x=y }\"\n\n\n(* IJW: you'll need to do the same for this *)\nabbreviation\n  upwardDiag0 :: \"Line\"\nwhere\n  \"upwardDiag0 \\<equiv> { (x,y) . x \\<in> BOARD \\<and> y = x-SIZE+(1::nat) }\" --\"flipped x and SIZE\"\n\nabbreviation\n  upwardDiag :: \"Line\"\nwhere\n  \"upwardDiag \\<equiv> { (x,y) . x \\<in> BOARD \\<and> y = SIZE-x+(1::nat) }\"\n\n(* Use definition to tame unfolding *)\ndefinition\n  winningLines :: \"Line set\"\nwhere\n(*  \"winningLines \\<equiv> \\<Union> {allRows, allCols, {downwardDiag}, {upwardDiag}}\"*)\n   \"winningLines \\<equiv> allRows \\<union> allCols \\<union> {downwardDiag, upwardDiag}\"\n(* IJW: Hmm, maybe rather than sets of sets, use allRows \\<union> allCols \\<union> ...? *)\n\nabbreviation\n  explicitWinningLines :: \"Line set\"\nwhere\n  \"explicitWinningLines \\<equiv> \n          { {(1, 1), (1, 2), (1, 3)}, \n\t\t\t\t\t \t{(2, 1), (2, 2), (2, 3)}, \n\t\t\t\t\t  {(3, 1), (3, 2), (3, 3)},  \n\n\t\t\t\t\t  {(1, 1), (2, 1), (3, 1)}, \n\t\t\t\t\t  {(1, 2), (2, 2), (3, 2)}, \n\t\t\t\t\t  {(1, 3), (2, 3), (3, 3)}, \n\n\t\t\t\t\t  {(1, 1), (2, 2), (3, 3)},\n \n\t\t\t\t\t  {(1, 3), (2, 2), (3, 1)}\n\t\t\t\t  }\"\t\n\n(* Give me some sanity please :-) *)\nlemma \"(\\<Union> x \\<in> BOARD . {(x,y) . inv_Pos (x,y) }) = { (r, c) . inv_Pos (r, c) }\"\nby (rule,rule,simp,rule,simp)\n\nlemma lBoardKeepsPos: \"x \\<in> BOARD \\<and> y \\<in> BOARD \\<Longrightarrow> inv_Pos (x,y) \\<and> inv_Pos (y,x)\"\nunfolding inv_Pos_def by auto\n\nlemma \"BOARD = {1,2,3}\" by auto\n\nlemma \"row 1 = ({ (r,c) . r=1 \\<and> c \\<in> BOARD })\"\nunfolding inv_Pos_def row_def by auto\nlemma \"row 1 = { (1,1), (1,2), (1,3) }\"\nunfolding inv_Pos_def row_def by auto\nlemma \"col 1 = { (1,1), (2,1), (3,1) }\"\nunfolding inv_Pos_def col_def by auto\n\nlemma ar: \"allRows = allRows0\"\napply (rule)\napply (rule_tac[1-] subsetI)\napply simp_all\napply (erule bexE)\napply simp\napply (elim conjE)\napply (case_tac r)\napply simp_all\napply (case_tac nat)\napply simp_all\napply (case_tac nata)\napply simp_all\napply (rule disjI2,rule disjI1)\ndefer\napply (rule disjI2,rule disjI2)\ndefer\napply (erule disjE)\napply (rule_tac x=\"Suc 0\" in bexI,simp_all)\napply (erule disjE)\napply (rule_tac x=\"2\" in bexI,simp_all)\napply (rule_tac x=\"SIZE\" in bexI,simp_all)\nunfolding row_def\napply auto\ndone (* why so protracted! *)\n\n(* Now provable by auto *)\nlemma \"downwardDiagIJW = { (1,1), (2,2), (3,3) }\" nitpick\n  by auto\n\nlemma \"downwardDiag0 = { (1,1), (2,2), (3,3) }\"\napply simp\nnitpick oops\n\nlemma dwd: \"downwardDiag = { (1,1), (2,2), (3,3) }\"\napply rule \napply simp_all\napply rule\napply simp (* Hum... there is something fishy about way pairs are handled *)\napply (case_tac x,simp)\napply (elim conjE)\napply (case_tac a,simp_all)\napply (case_tac nat,simp_all)\napply (case_tac nata,simp_all) (* something fishy here on range as well *)\ndone\n\n\nlemma \"upwardDiag0 = { (3,1), (2,2), (1,3) }\"\napply simp nitpick oops\n\nlemma wdd: \"upwardDiag = { (3,1), (2,2), (1,3) }\"\napply rule \napply simp_all\napply rule\napply simp (* Hum... there is something fishy about way pairs are handled *)\napply (case_tac x,simp)\napply (elim conjE)\napply (case_tac a,simp_all)\napply (case_tac nat,simp_all)\napply (case_tac nata,simp_all) (* something fishy here on range as well *)\ndone\n\n(* quit unmanageable / tedious *)\nlemma \"winningLines = explicitWinningLines\"\nunfolding winningLines_def apply rule\napply simp_all  oops\n(* IJW: maybe slightly easier with some of the simplifications above? *) \n\n(*-----------------------------------------------------------------------------------------*)\nsubsection {* Game solution (predicates) testing functions *} \n\ndefinition \n  hasWon :: \"Game \\<Rightarrow> Player \\<Rightarrow> bool\"\nwhere\n  \"hasWon g p \\<equiv> \\<exists> line \\<in> winningLines . line \\<subseteq> (movesForPlayer g p)\"\n\nfind_theorems \"\\<exists>! _ . _\"\n\ndefinition \n  isWon :: \"Game \\<Rightarrow> bool\"\nwhere\n  \"isWon g \\<equiv> \\<exists>! p . hasWon g p\"\n\ndefinition\n  whoWon :: \"Game \\<Rightarrow> Player\"\nwhere\n  \"whoWon g \\<equiv> THE p . hasWon g p\"\n\ndefinition\n  isDraw :: \"Game \\<Rightarrow> bool\"\nwhere\n  \"isDraw g \\<equiv> \\<not> isWon g \\<and> movesCountLeft g = 0\"\n\ndefinition\n  isUnfinished :: \"Game \\<Rightarrow> bool\"\nwhere\n  \"isUnfinished g \\<equiv> \\<not> isWon g \\<and> \\<not> isDraw g\"\n\n(*=========================================================================================*)\nsection {* VDM state and operations *} \n\ntext {* The only VDM operation is the one that ``plays'' the game, but first we need a conversion\n        function between the two (obviously related) datatypes. \n\n        The game play is defined recursively on the length of the moves to be played,\n        where the game remains unfinished if there are no more moves. We also augment the\n        original VDM definition to tolerate (as an unfinished game) empty player ordering\n        (i.e. it should really be ust boolean, so this is just glitch from the VDM model?).\n\n        The recursive case makes the move in the game according to who is playing and,\n        either decides the result, if possible, or else cary on playing. We should perhaps\n        consider a iterative version of the game play function.\n  *}\n\ndefinition\n  conv_playerToPlayOpt :: \"Player \\<Rightarrow> GameResult\"\nwhere\n  \"conv_playerToPlayOpt p \\<equiv> (case p of NOUGHT \\<Rightarrow> NOUGHT_WON | CROSS \\<Rightarrow> CROSS_WON)\"\n\nthm Let_def\n\nfun\n  play :: \"Game \\<Rightarrow> PlayOrder \\<Rightarrow> Moves \\<Rightarrow> GameResult\"\nwhere\n  \"play g ps []             = UNFINISHED\"\n| \"play g [] ms             = UNFINISHED\" --\"extra equation for pat-completeness\"\n| \"play g (p # ps) (m # ms) = \n      (let g' = makeMove g p m in\n          (if (isWon g') then \n                conv_playerToPlayOpt (whoWon g') \n           else if (isDraw g') then\n                DRAW\n           else\n                play g' (ps @ [p]) ms))\"\n\n(*-----------------------------------------------------------------------------------------*)\nsubsubsection {* Technical note *}\n\ntext {* extra equation + recursive def + etc *}\n\n(*\nfun\n  itplay :: \"Game \\<Rightarrow> PlayOrder \\<Rightarrow> Moves \\<Rightarrow> Game \\<Rightarrow> PlayOrder \\<Rightarrow> Moves \\<Rightarrow> GameResult\"\nwhere\n  \"itplay g ps [] g'             = UNFINISHED\"     --\"when moves finished get result\"\n| \"itplay g [] ms g'             = UNFINISHED\"     --\"when playorder is screw up it's UNFINISHED\"\n| \"itplay g (p # ps) (m # ms) g' = CROSS_WON\"\n*)\n\n(*=========================================================================================*)\nsection {* VDM test data *}\n\nfind_theorems \"insort\"\nthm Finite_Set.fold_def \n\nvalue \"sorted_list_of_set {1,2}\"\nvalue \"sorted_list_of_set BOARD\"\nvalue \"zip (sorted_list_of_set BOARD) (sorted_list_of_set BOARD)\"\nlemma \"(sorted_list_of_set BOARD) = [1,2,3]\" oops\n\nabbreviation\n  allPos :: \"Pos set\"\nwhere\n  \"allPos \\<equiv> { (r, c) . inv_Pos (r, c) }\"\n\nfind_theorems name:choice\nthm inv_def\nfind_theorems name:Hilbert\n\nabbreviation\n  somePos :: \"Pos set \\<Rightarrow> Pos\"\nwhere\n  \"somePos ps \\<equiv> Eps (\\<lambda> x . x \\<in> ps \\<and> inv_PosSet ps)\" --{* or @{text \"inv_Pos x\"}? *}\n\nvalue \"somePos\"\n\ndefinition\n  randomMove :: Moves\nwhere\n  \"randomMove \\<equiv> \n     let m1 = (somePos allPos) in \n       let m2 = (somePos (allPos - {m1})) in  \n        let m3 = (somePos (allPos - {m1,m2})) in\n          let m4 = (somePos (allPos - {m1,m2,m3})) in\n            let m5 = (somePos (allPos - {m1,m2,m3,m4})) in\n              [m1,m2,m3,m4,m5]\n    \"\n(*\nlet m1 in set ALLPOS in\t\t\t\t\t\t\t\t\t\t-- 9 1st moves\n\t\tlet m2 in set ALLPOS \\ {m1} in\t\t\t\t\t\t\t\t-- 72 1st-2nd pairs\n\t\tlet m3 in set ALLPOS \\ {m1, m2} in\t\t\t\t\t\t\t-- 504 1st-2nd-3rd etc...\n\t\tlet m4 in set ALLPOS \\ {m1, m2, m3} in\t\t\t\t\t\t-- 3024\n\t\tlet m5 in set ALLPOS \\ {m1, m2, m3, m4} in\t\t\t\t\t-- 15120 (minimum)\n--\t\tlet m6 in set ALLPOS \\ {m1, m2, m3, m4, m5} in\t\t\t\t-- 60480\n--\t\tlet m7 in set ALLPOS \\ {m1, m2, m3, m4, m5, m6} in\t\t\t-- 181440\n--\t\tlet m8 in set ALLPOS \\ {m1, m2, m3, m4, m5, m6, m7} in\t\t-- 362880\n--\t\tlet m9 in set ALLPOS \\ {m1, m2, m3, m4, m5, m6, m7, m8} in\t-- 362880\n*)\n\nfind_theorems name:induct name:Finite_Set\nthm finite_induct\n\n(* I wish! How to define recursive functions over sets? \ndefinition\n  complexMove :: \"Pos set \\<Rightarrow> Moves\" \nwhere\n  \"complexMove ps = \n      (if (ps = {}) then []\n       else \n          let x = (somePos ps) in\n             x # (complexMove (ps - {x})))\"\n*)\n\nabbreviation\n  simpleMoves :: Moves\nwhere\n  \"simpleMoves \\<equiv> [(x,y) . x \\<leftarrow> sorted_list_of_set BOARD, y \\<leftarrow> sorted_list_of_set BOARD]\"\n\nabbreviation\n  winningMoves :: Moves\nwhere\n  \"winningMoves \\<equiv> [(2,2),(1,3),(3,1),(2,3),(3,3),(1,1),(3,2)]\"\n\nvalue simpleMoves\n--\"value randomMove\"\n\ndefinition \n  testPlay0 :: \"GameResult\"\nwhere\n  \"testPlay0 \\<equiv> play empty [CROSS, NOUGHT] []\"\n\ndefinition \n  testPlayCross :: \"GameResult\"\nwhere\n  \"testPlayCross \\<equiv> play empty [CROSS, NOUGHT] winningMoves\"\n\ndefinition \n  testPlayNought :: \"GameResult\"\nwhere\n  \"testPlayNought \\<equiv> play empty [NOUGHT, CROSS] winningMoves\"\n\nthm Let_def list.split Pair_def split_if split_if_asm\n\n(*\nlemma \"testPlayCross = CROSS_WON\"\nunfolding testPlayCross_def\napply auto\n(* TODO: bugger! let's are complicated *)\noops\n*)\n\ndeclare [[smt_trace=false]]\nlemma \"allPos = { (1,1),(1,2),(1,3),(2,1),(2,2),(2,3),(3,1),(3,2),(3,3)}\"\napply (rule,rule,simp,unfold inv_Pos_def,simp_all)\napply (case_tac x,simp,elim conjE)\nby smt\n\n(*=========================================================================================*)\nsection {* VDM pre and post condition definitions for functions *}\n\n(*-----------------------------------------------------------------------------------------*)\nsubsection {* Implicitly definined pre and post *}\n\ntext {* All VDM functions have an implicitly defined pre and post condition functions.\n        If no explicit pre/post condition is defined by the user, these functions just\n        check the type invariants and return @{term \"True\"}. \n\n        In our translation, because the type invariants are not guaranteed by Isabelle,\n        we use the definitions to achieve that. Moreover, because these are functions,\n        and not operations, there is no need to check after state on postconditions.\n\n        Furthermore, when no explicit postcondition is given, we assert the explicit VDM\n        definition as part of the postcondition.\n\n        TODO: Q for nick when calling functions within the definitions are their pre/post called?\n        If so, the repetitiveness of defnitions below can be aliviated. Also, is asserting explicit\n        defs as part of (implicit) post okay? Should be?\n      *}\n\ndefinition \n  pre_movesForPlayer :: \"Game \\<Rightarrow> Player \\<Rightarrow> bool\"\nwhere\n  \"pre_movesForPlayer g p \\<equiv> inv_Game g\"\n\ndefinition \n  post_movesForPlayer :: \"Game \\<Rightarrow> Player \\<Rightarrow> Pos set \\<Rightarrow> bool\"\nwhere\n  \"post_movesForPlayer g p ps \\<equiv> inv_Game g \\<and> inv_PosSet ps \\<and> ps = movesForPlayer g p\"\n\ndefinition \n  pre_movesSoFar :: \"Game \\<Rightarrow> bool\"\nwhere\n  \"pre_movesSoFar g \\<equiv> inv_Game g\"\n\ndefinition \n  post_movesSoFar :: \"Game  \\<Rightarrow> Pos set \\<Rightarrow> bool\"\nwhere\n  \"post_movesSoFar g ps \\<equiv> inv_Game g \\<and> inv_PosSet ps \\<and> ps = movesSoFar g\"\n\ndefinition \n  pre_movesCountSoFar :: \"Game \\<Rightarrow> bool\"\nwhere\n  \"pre_movesCountSoFar g \\<equiv> inv_Game g\"\n\ndefinition \n  post_movesCountSoFar :: \"Game \\<Rightarrow> nat \\<Rightarrow> bool\"\nwhere\n  \"post_movesCountSoFar g n \\<equiv> inv_Game g \\<and> n = movesCountSoFar g\" -- {* maybe add @{term \"n > 0\"}? *}\n\ndefinition \n  pre_movesCountLeft :: \"Game \\<Rightarrow> bool\"\nwhere\n  \"pre_movesCountLeft g \\<equiv> inv_Game g\"\n  \ndefinition \n  post_movesCountLeft :: \"Game \\<Rightarrow> nat \\<Rightarrow> bool\"\nwhere\n  \"post_movesCountLeft g n \\<equiv> inv_Game g \\<and> n = MAX - movesCountSoFar(g)\" \n                        -- {* should we call here pre_movesCountSoFar g; should @{text \"n > 0\"}? *}\n\n(*-----------------------------------------------------------------------------------------*)\nsubsection {* Explicitly definined pre and post by the user *}\n\ntext {* When the user explicitly provides a pre and post condition, we need to be careful.\n        We still need our implicit translations becasue of the type invariants, yet we also\n        need the explicit definitions given by the user. \n        Thus, we define both these as boolean functions with suffix I and without suffix:~the\n        former for the type invariant, whereas the latter is for the external user's definition.\n        The user defined translation must call the implicitly defined one in order to check the\n        invariant holds.\n *}\n\ndefinition\n  pre_makeMoveI :: \"Game \\<Rightarrow> Player \\<Rightarrow> Pos \\<Rightarrow> bool\"\nwhere\n  \"pre_makeMoveI g p pos \\<equiv> inv_Game g \\<and> inv_Pos pos\"\n\ndefinition\n  pre_makeMove :: \"Game \\<Rightarrow> Player \\<Rightarrow> Pos \\<Rightarrow> bool\"\nwhere\n  \"pre_makeMove g p pos \\<equiv> pre_makeMoveI g p pos \\<and> pos \\<notin> movesSoFar g \\<and> movesCountLeft g > 0\"\n\ntext {* Note that for the postcondition we needed to make some changes. Firstly, the implicit\n        (invariant checking) definition remains the same, whereas the implicit post condition\n        does not generate a call to @{text \"makeMove\"} given there is a post condition.\n\n        \\textbf{TODO: simplify this? Yes, because makeMove doesn't have option either? \n        Moreover, it would entail having all sorts of option types in general? THINK/ASK Nick/Cliff.}\n*}\n\ndefinition\n  post_makeMoveI :: \"Game \\<Rightarrow> Player \\<Rightarrow> Pos \\<Rightarrow> Game \\<Rightarrow> bool\"\nwhere\n  \"post_makeMoveI g p pos g' \\<equiv> inv_Game g \\<and> inv_Pos pos \\<and> inv_Game g'\"\n\ndefinition\n  post_makeMove :: \"Game \\<Rightarrow> Player \\<Rightarrow> Pos \\<Rightarrow> Game \\<Rightarrow> bool\"\nwhere\n  \"post_makeMove g p pos g' \\<equiv> \n        post_makeMoveI g p pos g' \\<and>\n        pos \\<notin> dom g \\<and>\n        movesCountSoFar g' = movesCountSoFar g - 1\"\n        -- {* no call to @{term \"g' = makeMove g p pos\"}! *}\n\n(*\ndefinition \n  inv_GameOpt :: \"Game option \\<Rightarrow> bool\"\nwhere\n  \"inv_GameOpt g \\<equiv> (case g of None \\<Rightarrow> False | (Some gg) \\<Rightarrow> inv_Game gg)\"\n\ndefinition\n  post_makeMoveI :: \"Game \\<Rightarrow> Player \\<Rightarrow> Pos \\<Rightarrow> Game option \\<Rightarrow> bool\"\nwhere\n  \"post_makeMoveI g p pos g' \\<equiv> inv_Game g \\<and> inv_Pos pos \\<and> inv_GameOpt g'\"\n\ndefinition\n  post_makeMoveE :: \"Game \\<Rightarrow> Player \\<Rightarrow> Pos \\<Rightarrow> Game option \\<Rightarrow> bool\"\nwhere\n  \"post_makeMoveE g p pos g' \\<equiv> \n        post_makeMoveI g p pos g' \\<and>\n        pos \\<notin> dom g \\<and>\n        g' \\<noteq> None \\<and>\n        movesCountSoFar (the g') = movesCountSoFar g - 1\"\n*)\n\n(*-----------------------------------------------------------------------------------------*)\nsubsection {* Implicitly defined pre and post for solution (boolean-valued) functions *}\n\ntext {* Boolean valued functions (or predicates) in VDM perhaps could have a simpler translation? \n        Their very definition is already a postcondition\n      *}\n\ndefinition \n  pre_hasWon :: \"Game \\<Rightarrow> Player \\<Rightarrow> bool\"\nwhere\n  \"pre_hasWon g p \\<equiv> inv_Game g\"\n\ndefinition \n  post_hasWon :: \"Game \\<Rightarrow> Player \\<Rightarrow> bool\"\nwhere\n  \"post_hasWon g p \\<equiv> inv_Game g \\<and> hasWon g p\"\n\ndefinition \n  pre_isWon :: \"Game \\<Rightarrow> bool\"\nwhere\n  \"pre_isWon g \\<equiv> inv_Game g\"\n\ndefinition \n  post_isWon :: \"Game \\<Rightarrow> bool\"\nwhere\n  \"post_isWon g \\<equiv> inv_Game g \\<and> isWon g\"\n\ndefinition\n  pre_whoWon :: \"Game \\<Rightarrow> bool\"\nwhere\n  \"pre_whoWon g \\<equiv> inv_Game g\"\n\ndefinition\n  pre_whoWonG :: \"Game \\<Rightarrow> bool\"\nwhere\n  \"pre_whoWonG g \\<equiv> inv_Game g \\<and> isWon g\"\n\n(* This one is not quite boolean valued, though :-) *)\ndefinition\n  post_whoWon :: \"Game \\<Rightarrow> Player \\<Rightarrow> bool\"\nwhere\n  \"post_whoWon g p \\<equiv> inv_Game g \\<and> p = whoWon g\"\n\ndefinition\n  post_whoWonG :: \"Game \\<Rightarrow> Player \\<Rightarrow> bool\"\nwhere\n  \"post_whoWonG g p \\<equiv> inv_Game g \\<and> (\\<exists>! x . hasWon g x \\<and> x = p)\"\n\ndefinition\n  pre_isDraw :: \"Game \\<Rightarrow> bool\"\nwhere\n  \"pre_isDraw g \\<equiv> inv_Game g\"\n\ndefinition\n  post_isDraw :: \"Game \\<Rightarrow> bool\"\nwhere\n  \"post_isDraw g \\<equiv> inv_Game g \\<and> isDraw g\"\n\ndefinition\n  pre_isUnfinished :: \"Game \\<Rightarrow> bool\"\nwhere\n  \"pre_isUnfinished g \\<equiv> inv_Game g\"\n\ndefinition\n  post_isUnfinished :: \"Game \\<Rightarrow> bool\"\nwhere\n  \"post_isUnfinished g \\<equiv> inv_Game g \\<and> isUnfinished g\"\n\n(*=========================================================================================*)\nsection {* VDM pre and post condition definitions for operations *}\n\n(*-----------------------------------------------------------------------------------------*)\nsubsection {* Implicitly defined pre and post for operations *}\n\n(*-----------------------------------------------------------------------------------------*)\nsubsection {* Explicitly defined pre and post by the user for operations *}\n\ndefinition \n  pre_play :: \"Game \\<Rightarrow> PlayOrder \\<Rightarrow> Moves \\<Rightarrow> bool\"\nwhere\n  \"pre_play g po m \\<equiv> inv_Game g \\<and> inv_PlayOrder po \\<and> inv_Moves m\"\n \ndefinition\n  post_playI :: \"Game \\<Rightarrow> PlayOrder \\<Rightarrow> Moves \\<Rightarrow> (Game \\<times> GameResult) \\<Rightarrow> bool\"\nwhere\n  \"post_playI g po m RESULT \\<equiv> inv_Game g \\<and> inv_PlayOrder po \\<and> inv_Moves m \\<and> inv_Game (fst RESULT)\"\n\n(* Interesting: Game isn't talked about in the result? *)\ndefinition\n  post_play :: \"Game \\<Rightarrow> PlayOrder \\<Rightarrow> Moves \\<Rightarrow> (Game \\<times> GameResult) \\<Rightarrow> bool\"\nwhere \n  \"post_play g po m RESULT \\<equiv> \n       post_playI g po m RESULT \\<and>\n       (if (snd RESULT) = DRAW then \n          isDraw g\n       else if (snd RESULT) = UNFINISHED then\n          isUnfinished g\n       else \n          (snd RESULT) = conv_playerToPlayOpt (whoWon g))\"\n\n(*=========================================================================================*)\nsection {* VDM proof obligations *}\n\n(*-----------------------------------------------------------------------------------------*)\nsubsection {* Satisfiability *}\n\ntext {* From Overture proof obligations tools, we get these translated and proved *}\n\n(*\n(forall g:Game & isWon(g) =>\n  exists1 p:Player & hasWon(g, p))\n*)\nlemma \"\\<forall> g . isWon g \\<longrightarrow> (\\<exists>! p . hasWon g p)\"\nunfolding isWon_def by simp\n\n(*\n(forall g:Game &\n  pre_whoWonG(g) => exists p:Player & post_whoWonG(g, p))\n*)\nlemma \"\\<forall> g . pre_whoWonG g \\<longrightarrow> (\\<exists> p . post_whoWonG g p)\"\nunfolding pre_whoWonG_def post_whoWonG_def isWon_def by auto\n\n(*<*)\n\n(*-----------------------------------------------------------------------------------------*)\n(*=========================================================================================*)\n\nlemma \"2 = (THE n . (n::nat) + 4 = 6)\"\nby auto\n\nlemma \"3 \\<noteq> (THE n . (n::nat) + 4 = 6)\"\nby auto\n\nlemma \"1 = (THE n . n = (n::nat) + 0)\"\napply auto\noops\n\nlemma \"1 = (THE n . n = (n::nat) + 1)\"\napply auto\nnitpick\noops\n\nlemma \"(x \\<noteq> y \\<and> a=b) = (\\<not> (x = y \\<or> a \\<noteq> b))\"\nby auto\n\nlemma \"(x \\<noteq> y \\<and> a=b) = (\\<not> (a = b \\<longrightarrow> x = y))\"\nby auto\n\n\nlemma \"(\\<forall> x \\<in> S . \\<not>(\\<exists> y \\<in> S . x \\<noteq> y \\<and> a=b)) = (\\<forall> x \\<in> S . \\<not>(\\<exists> y \\<in> S . (\\<not> (a = b \\<longrightarrow> x = y))))\"\nby auto\n\nlemma \"(\\<forall> x \\<in> S . \\<not>(\\<exists> y \\<in> S . x \\<noteq> y \\<and> a=b)) = (\\<forall> x \\<in> S . (\\<forall> y \\<in> S . ((a = b \\<longrightarrow> x = y))))\"\nby auto\n\nend\n(*>*)\n", "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/experiments/isa/XO/XO.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8418256631249077, "lm_q2_score": 0.8774767826757122, "lm_q1q2_score": 0.7386824744526919}}
{"text": "section\\<open>Value Types\\<close>\n\ntheory Valuetypes\nimports ReadShow\nbegin\n\nfun iter :: \"(int \\<Rightarrow> 'b \\<Rightarrow> 'b) \\<Rightarrow> 'b \\<Rightarrow> int \\<Rightarrow> 'b\"\nwhere\n  \"iter f v x = (if x \\<le> 0 then v  \n                 else f (x-1) (iter f v (x-1)))\"\n\nfun iter' :: \"(int \\<Rightarrow> 'b \\<Rightarrow> 'b option) \\<Rightarrow> 'b \\<Rightarrow> int \\<Rightarrow> 'b option\"\nwhere\n  \"iter' f v x = (if x \\<le> 0 then Some v\n                  else case iter' f v (x-1) of\n                          Some v' \\<Rightarrow> f (x-1) v'\n                        | None \\<Rightarrow> None)\"\n\ntype_synonym Address = String.literal\ntype_synonym Location = String.literal\ntype_synonym Valuetype = String.literal\n\n(*Covered*)\ndatatype Types = TSInt nat\n               | TUInt nat\n               | TBool\n               | TAddr\n\n(*Covered*)\nfun createSInt :: \"nat \\<Rightarrow> int \\<Rightarrow> Valuetype\"\nwhere\n  \"createSInt b v =\n    (if v \\<ge> 0\n      then ShowL\\<^sub>i\\<^sub>n\\<^sub>t (-(2^(b-1)) + (v+2^(b-1)) mod (2^b))\n      else ShowL\\<^sub>i\\<^sub>n\\<^sub>t (2^(b-1) - (-v+2^(b-1)-1) mod (2^b) - 1))\"\n\nlemma upper_bound:\n  fixes b::nat\n    and c::int\n  assumes \"b > 0\"\n      and \"c < 2^(b-1)\"\n    shows \"c + 2^(b-1) < 2^b\"\nproof -\n  have a1: \"\\<And>P. (\\<forall>b::nat. P b) \\<Longrightarrow> (\\<forall>b>0. P ((b-1)::nat))\" by simp\n  have b2: \"\\<forall>b::nat. (\\<forall>(c::int)<2^b. (c + 2^b) < 2^(Suc b))\" by simp\n  show ?thesis using a1[OF b2] assms by simp\nqed\n\nlemma upper_bound2:\n  fixes b::nat\n      and c::int\n    assumes \"b > 0\"\n      and \"c < 2^b\"\n      and \"c \\<ge> 0\"\n    shows \"c - (2^(b-1)) < 2^(b-1)\"\nproof -\n  have a1: \"\\<And>P. (\\<forall>b::nat. P b) \\<Longrightarrow> (\\<forall>b>0. P ((b-1)::nat))\" by simp\n  have b2: \"\\<forall>b::nat. (\\<forall>(c::int)<2^(Suc b). c\\<ge>0 \\<longrightarrow> (c - 2^b) < 2^b)\" by simp\n  show ?thesis using a1[OF b2] assms by simp\nqed\n\nlemma upper_bound3:\n  fixes b::nat\n    and v::int\n      defines \"x \\<equiv> - (2 ^ (b - 1)) + (v + 2 ^ (b - 1)) mod 2 ^ b\"\n    assumes \"b>0\"\n    shows \"x < 2^(b-1)\"\n  using upper_bound2 assms by auto\n\nlemma lower_bound:\n    fixes b::nat\n  assumes \"b>0\"\n    shows \"\\<forall>(c::int) \\<ge> -(2^(b-1)). (-c + 2^(b-1) - 1 < 2^b)\"\nproof -\n  have a1: \"\\<And>P. (\\<forall>b::nat. P b) \\<Longrightarrow> (\\<forall>b>0. P ((b-1)::nat))\" by simp\n  have b2: \"\\<forall>b::nat. \\<forall>(c::int) \\<ge> -(2^b). (-c + (2^b) - 1) < 2^(Suc b)\" by simp\n  show ?thesis using a1[OF b2] assms by simp\nqed\n\nlemma lower_bound2:\n  fixes b::nat\n    and v::int\n      defines \"x \\<equiv> 2^(b - 1) - (-v+2^(b-1)-1) mod 2^b - 1\"\n    assumes \"b>0\"\n    shows \"x \\<ge> - (2 ^ (b - 1))\"\n  using upper_bound2 assms by auto\n\nlemma createSInt_id_g0:\n    fixes b::nat\n      and v::int\n  assumes \"v \\<ge> 0\"\n      and \"v < 2^(b-1)\"\n      and \"b > 0\"\n    shows \"createSInt b v = ShowL\\<^sub>i\\<^sub>n\\<^sub>t v\"\nproof -\n  from assms have \"v + 2^(b-1) \\<ge> 0\" by simp\n  moreover from assms have \"v + (2^(b-1)) < 2^b\" using upper_bound[of b] by auto\n  ultimately have \"(v + 2^(b-1)) mod (2^b) = v + 2^(b-1)\" by simp\n  moreover from assms have \"createSInt b v=ShowL\\<^sub>i\\<^sub>n\\<^sub>t (-(2^(b-1)) + (v+2^(b-1)) mod (2^b))\" by simp\n  ultimately show ?thesis by simp\nqed\n\nlemma createSInt_id_l0:\n    fixes b::nat\n      and v::int\n  assumes \"v < 0\"\n      and \"v \\<ge> -(2^(b-1))\"\n      and \"b > 0\"\n    shows \"createSInt b v = ShowL\\<^sub>i\\<^sub>n\\<^sub>t v\"\nproof -\n  from assms have \"-v + 2^(b-1) - 1 \\<ge> 0\" by simp\n  moreover from assms have \"-v + 2^(b-1) - 1 < 2^b\" using lower_bound[of b] by auto \n  ultimately have \"(-v + 2^(b-1) - 1) mod (2^b) = (-v + 2^(b-1) - 1)\" by simp\n  moreover from assms have \"createSInt b v= ShowL\\<^sub>i\\<^sub>n\\<^sub>t (2^(b-1) - (-v+2^(b-1)-1) mod (2^b) - 1)\" by simp\n  ultimately show ?thesis by simp\nqed\n\nlemma createSInt_id:\n    fixes b::nat\n      and v::int\n  assumes \"v < 2^(b-1)\"\n      and \"v \\<ge> -(2^(b-1))\"\n      and \"b > 0\"\n    shows \"createSInt b v = ShowL\\<^sub>i\\<^sub>n\\<^sub>t v\" using createSInt_id_g0 createSInt_id_l0 assms by simp\n\n(*Covered*)\nfun createUInt :: \"nat \\<Rightarrow> int \\<Rightarrow> Valuetype\"\n  where \"createUInt b v = ShowL\\<^sub>i\\<^sub>n\\<^sub>t (v mod (2^b))\"\n\nlemma createUInt_id:\n  assumes \"v \\<ge> 0\"\n      and \"v < 2^b\"\n    shows \"createUInt b v =  ShowL\\<^sub>i\\<^sub>n\\<^sub>t v\"\nby (simp add: assms(1) assms(2))\n\nfun createBool :: \"bool \\<Rightarrow> Valuetype\"\nwhere\n  \"createBool b = ShowL\\<^sub>b\\<^sub>o\\<^sub>o\\<^sub>l b\"\n\nfun createAddress :: \"Address \\<Rightarrow> Valuetype\"\nwhere\n  \"createAddress ad = ad\"\n\nfun convert :: \"Types \\<Rightarrow> Types \\<Rightarrow> Valuetype \\<Rightarrow> (Valuetype * Types) option\"\nwhere\n  \"convert (TSInt b1) (TSInt b2) v =\n    (if b1 \\<le> b2\n      then Some (v, TSInt b2)\n      else None)\"\n| \"convert (TUInt b1) (TUInt b2) v =\n    (if b1 \\<le> b2\n      then Some (v, TUInt b2)\n      else None)\"\n| \"convert (TUInt b1) (TSInt b2) v =\n    (if b1 < b2\n      then Some (v, TSInt b2)\n      else None)\"\n| \"convert TBool TBool v = Some (v, TBool)\"\n| \"convert TAddr TAddr v = Some (v, TAddr)\"\n| \"convert _ _ _ = None\"\n\nlemma convert_id[simp]:\n  \"convert tp tp kv = Some (kv, tp)\"\n    by (metis Types.exhaust convert.simps(1) convert.simps(2) convert.simps(4) convert.simps(5) order_refl)\n\n(*Covered informally*)\nfun olift ::\n  \"(int \\<Rightarrow> int \\<Rightarrow> int) \\<Rightarrow> Types \\<Rightarrow> Types \\<Rightarrow> Valuetype \\<Rightarrow> Valuetype \\<Rightarrow> (Valuetype * Types) option\"\nwhere\n  \"olift op (TSInt b1) (TSInt b2) v1 v2 =\n    Some (createSInt (max b1 b2) (op \\<lceil>v1\\<rceil> \\<lceil>v2\\<rceil>), TSInt (max b1 b2))\"\n| \"olift op (TUInt b1) (TUInt b2) v1 v2 =\n    Some (createUInt (max b1 b2) (op \\<lceil>v1\\<rceil> \\<lceil>v2\\<rceil>), TUInt (max b1 b2))\"\n| \"olift op (TSInt b1) (TUInt b2) v1 v2 =\n    (if b2 < b1\n      then Some (createSInt b1 (op \\<lceil>v1\\<rceil> \\<lceil>v2\\<rceil>), TSInt b1)\n      else None)\"\n| \"olift op (TUInt b1) (TSInt b2) v1 v2 =\n    (if b1 < b2\n      then Some (createSInt b2 (op \\<lceil>v1\\<rceil> \\<lceil>v2\\<rceil>), TSInt b2)\n      else None)\"\n| \"olift _ _ _ _ _ = None\"\n\n(*Covered*)\nfun plift ::\n  \"(int \\<Rightarrow> int \\<Rightarrow> bool) \\<Rightarrow> Types \\<Rightarrow> Types \\<Rightarrow> Valuetype \\<Rightarrow> Valuetype \\<Rightarrow> (Valuetype * Types) option\"\nwhere\n  \"plift op (TSInt b1) (TSInt b2) v1 v2 = Some (createBool (op \\<lceil>v1\\<rceil> \\<lceil>v2\\<rceil>), TBool)\"\n| \"plift op (TUInt b1) (TUInt b2) v1 v2 = Some (createBool (op \\<lceil>v1\\<rceil> \\<lceil>v2\\<rceil>), TBool)\"\n| \"plift op (TSInt b1) (TUInt b2) v1 v2 =\n    (if b2 < b1\n      then Some (createBool (op \\<lceil>v1\\<rceil> \\<lceil>v2\\<rceil>), TBool)\n      else None)\"\n| \"plift op (TUInt b1) (TSInt b2) v1 v2 =\n    (if b1 < b2\n      then Some (createBool (op \\<lceil>v1\\<rceil> \\<lceil>v2\\<rceil>), TBool)\n      else None)\" \n| \"plift _ _ _ _ _ = None\"\n\n(*Covered*)\ndefinition add :: \"Types \\<Rightarrow> Types \\<Rightarrow> Valuetype \\<Rightarrow> Valuetype \\<Rightarrow> (Valuetype * Types) option\"\nwhere\n  \"add = olift (+)\"\n\n(*Covered informally*)\ndefinition sub :: \"Types \\<Rightarrow> Types \\<Rightarrow> Valuetype \\<Rightarrow> Valuetype \\<Rightarrow> (Valuetype * Types) option\"\nwhere\n  \"sub = olift (-)\"\n\n(*Covered informally*)\ndefinition equal :: \"Types \\<Rightarrow> Types \\<Rightarrow> Valuetype \\<Rightarrow> Valuetype \\<Rightarrow> (Valuetype * Types) option\"\nwhere\n  \"equal = plift (=)\"\n\n(*Covered informally*)\ndefinition less :: \"Types \\<Rightarrow> Types \\<Rightarrow> Valuetype \\<Rightarrow> Valuetype \\<Rightarrow> (Valuetype * Types) option\"\nwhere\n  \"less = plift (<)\"\n\ndeclare less_def [solidity_symbex]\n\n(*Covered informally*)\ndefinition leq :: \"Types \\<Rightarrow> Types \\<Rightarrow> Valuetype \\<Rightarrow> Valuetype \\<Rightarrow> (Valuetype * Types) option\"\nwhere\n  \"leq = plift (\\<le>)\"\n\n(*Covered*)\nfun vtand :: \"Types \\<Rightarrow> Types \\<Rightarrow> Valuetype \\<Rightarrow> Valuetype \\<Rightarrow> (Valuetype * Types) option\"\nwhere\n  \"vtand TBool TBool a b =\n    (if a = ShowL\\<^sub>b\\<^sub>o\\<^sub>o\\<^sub>l True \\<and> b = ShowL\\<^sub>b\\<^sub>o\\<^sub>o\\<^sub>l True then Some (ShowL\\<^sub>b\\<^sub>o\\<^sub>o\\<^sub>l True, TBool)\n    else Some (ShowL\\<^sub>b\\<^sub>o\\<^sub>o\\<^sub>l False, TBool))\"\n| \"vtand _ _ _ _ = None\"\n\n(*Covered informally*)\nfun vtor :: \"Types \\<Rightarrow> Types \\<Rightarrow> Valuetype \\<Rightarrow> Valuetype \\<Rightarrow> (Valuetype * Types) option\"\nwhere\n  \"vtor TBool TBool a b =\n    (if a = ShowL\\<^sub>b\\<^sub>o\\<^sub>o\\<^sub>l False \\<and> b = ShowL\\<^sub>b\\<^sub>o\\<^sub>o\\<^sub>l False\n      then Some (ShowL\\<^sub>b\\<^sub>o\\<^sub>o\\<^sub>l False, TBool)\n      else Some (ShowL\\<^sub>b\\<^sub>o\\<^sub>o\\<^sub>l True, TBool))\"\n| \"vtor _ _ _ _ = None\"\n\n(*Covered informally*)\nfun ival :: \"Types \\<Rightarrow> Valuetype\"\nwhere\n  \"ival (TSInt x) = ShowL\\<^sub>i\\<^sub>n\\<^sub>t 0\"\n| \"ival (TUInt x) = ShowL\\<^sub>i\\<^sub>n\\<^sub>t 0\"\n| \"ival TBool = ShowL\\<^sub>b\\<^sub>o\\<^sub>o\\<^sub>l False\"\n| \"ival TAddr = STR ''0x0000000000000000000000000000000000000000''\"\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/Solidity/Valuetypes.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767874818409, "lm_q2_score": 0.8418256512199033, "lm_q1q2_score": 0.7386824680522494}}
{"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\"\n  \"../../../../SeLFiE\"\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)\"semantic_induct\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\"semantic_induct\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\"semantic_induct\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\"semantic_induct\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)\"semantic_induct\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)\"semantic_induct\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\"semantic_induct\n  all_induction_heuristic      [on[], arb[],rule[]]\n  all_generalization_heuristic [on[], arb[],rule[]]\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\"semantic_induct\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) {}\"semantic_induct\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": "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/Boolean_Expression_Checkers/Boolean_Expression_Checkers.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8774767906859264, "lm_q2_score": 0.8418256432832333, "lm_q1q2_score": 0.738682463785287}}
{"text": "theory hw6\n  imports \nComplex_Main\n  \"HOL-Library.Multiset\"\nbegin\nfun insert :: \"nat \\<Rightarrow> nat list \\<Rightarrow> nat list\"\n  where\n \"insert a [] = [a]\"\n|\"insert a (x#xs) = \n(if a \\<le> x then a#x#xs else x#insert a xs)\"\n\nthm insert.elims\nvalue \"insert 7 [328,4,6,78]\"\n  \nfun sort :: \"nat list \\<Rightarrow> nat list\"\n  where\n  \"sort [] = []\"\n| \"sort (x#xs) = insert x (sort xs)\"\n\nvalue \"sort [3,7,34,6,0,3,4]\"\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\nfun find_eq :: \"nat \\<Rightarrow> nat list \\<Rightarrow> bool\"\n  where\n  \"find_eq a [] = False\"\n| \"find_eq a (x#xs) = (if (x=a) then True else find_eq a xs)\"\n\nfun equal :: \"nat list \\<Rightarrow> nat list \\<Rightarrow> bool\"\n  where\n \"equal [] [] = True\" |\n \"equal [] (y#ys) = False\" |\n \"equal (x#xs) ys = ( (find_eq x ys) \\<and> equal xs (remove1 x ys))\"\n\nlemma \"equal x x\"\nproof(induction x)\n case Nil\n  then show ?case by simp\nnext\n  case (Cons a x)\n  then show ?case by simp\nqed\n\nlemma \"equal x y = equal y x\"\nproof(induction x)\n  case Nil\n  then show ?case proof(induction y)\n    case Nil\n    then show ?case by simp\n  next\n    case (Cons a y)\n    then show ?case by simp\n  qed\nnext\n  case (Cons a x)\n  then show ?case proof(induction y)\n    case Nil\n    then show ?case  by simp\n  next\n    case (Cons a y)\n    then show ?case   sorry\n\n  qed\nqed\n\nlemma \"(equal x y \\<and> equal y z) \\<Longrightarrow> equal x z\"              \nproof(induct x)\n  case Nil\n  then show ?case proof(induct z)\n    case Nil\n    then show ?case by simp\n  next\n    case (Cons a z)\n    then show ?case\n    proof -\n      show ?thesis\n        by (metis (no_types) Cons.prems equal.simps(2) sort.cases)\n    qed\n  qed\nnext\n  case (Cons a x)\n  then show ?case proof(induct z)\n    case Nil\n    then show ?case\n    proof -\n      show ?thesis\n        by (metis (no_types) Nil.prems(2) equal.elims(2) find_eq.simps(1))\n    qed\n  next\n    case (Cons a z)\n    then show ?case sorry\n  qed\nqed\n\nlemma \"sort (sort x) = sort x\"\n\n\nproof(induct x)\n  case Nil\n  then show ?case by simp\nnext\n  case (Cons a x)\n  then show ?case sorry\nqed\n\nlemma sorted_isort_key: \"sorted (map f (isort_key f xs))\"\nby(induction xs)(simp_all add: sorted_insort_key)\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)\"\n  by (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\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\" and \"A x y\"\nshows \"T x y\"\n  using A T TA assms(4) by blast\n\n\nlemma \"\\<exists> ys zs. xs = ys @ zs \\<and>\n(length ys = length zs \\<or> length ys = length zs + 1)\"\noops\n\ninductive ev :: \"nat \\<Rightarrow> bool\" where\nev0: \"ev 0\" |\nevSS : \"ev n \\<Longrightarrow> ev (Suc(Suc n))\"\n\nlemma assumes a: \"ev (Suc(Suc n))\" shows \"ev n\"\nproof -\n  obtain nn :: \"nat \\<Rightarrow> nat\" where\n    \"Suc (Suc n) = Suc (Suc (nn (Suc (Suc n)))) \\<and> ev (nn (Suc (Suc n)))\"\n    by (metis (no_types) assms ev.cases old.nat.distinct(2))\n  then show ?thesis\n    by (metis Suc_inject)\nqed\n\n\nlemma \"\\<not> ev (Suc (Suc (Suc 0)))\"\nproof -\n  have \"\\<forall>n na. Suc n \\<noteq> Suc na \\<or> n = na\"\n    by (meson Suc_inject)\nthen show ?thesis\nby (metis (no_types) ev.simps old.nat.distinct(2))\nqed\nend\n\n", "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/hw6.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.877476784277755, "lm_q2_score": 0.8418256412990658, "lm_q1q2_score": 0.7386824566496631}}
{"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>Vector Analysis\\<close>\n\ntheory Topology_Euclidean_Space\n  imports\n    Elementary_Normed_Spaces\n    Linear_Algebra\n    Norm_Arith\nbegin\n\nsection \\<open>Elementary Topology in Euclidean Space\\<close>\n\nlemma euclidean_dist_l2:\n  fixes x y :: \"'a :: euclidean_space\"\n  shows \"dist x y = L2_set (\\<lambda>i. dist (x \\<bullet> i) (y \\<bullet> i)) Basis\"\n  unfolding dist_norm norm_eq_sqrt_inner L2_set_def\n  by (subst euclidean_inner) (simp add: power2_eq_square inner_diff_left)\n\nlemma norm_nth_le: \"norm (x \\<bullet> i) \\<le> norm x\" if \"i \\<in> Basis\"\nproof -\n  have \"(x \\<bullet> i)\\<^sup>2 = (\\<Sum>i\\<in>{i}. (x \\<bullet> i)\\<^sup>2)\"\n    by simp\n  also have \"\\<dots> \\<le> (\\<Sum>i\\<in>Basis. (x \\<bullet> i)\\<^sup>2)\"\n    by (intro sum_mono2) (auto simp: that)\n  finally show ?thesis\n    unfolding norm_conv_dist euclidean_dist_l2[of x] L2_set_def\n    by (auto intro!: real_le_rsqrt)\nqed\n\nsubsection\\<^marker>\\<open>tag unimportant\\<close> \\<open>Continuity of the representation WRT an orthogonal basis\\<close>\n\nlemma orthogonal_Basis: \"pairwise orthogonal Basis\"\n  by (simp add: inner_not_same_Basis orthogonal_def pairwise_def)\n\nlemma representation_bound:\n  fixes B :: \"'N::real_inner set\"\n  assumes \"finite B\" \"independent B\" \"b \\<in> B\" and orth: \"pairwise orthogonal B\"\n  obtains m where \"m > 0\" \"\\<And>x. x \\<in> span B \\<Longrightarrow> \\<bar>representation B x b\\<bar> \\<le> m * norm x\"\nproof \n  fix x\n  assume x: \"x \\<in> span B\"\n  have \"b \\<noteq> 0\"\n    using \\<open>independent B\\<close> \\<open>b \\<in> B\\<close> dependent_zero by blast\n  have [simp]: \"b \\<bullet> b' = (if b' = b then (norm b)\\<^sup>2 else 0)\"\n    if \"b \\<in> B\" \"b' \\<in> B\" for b b'\n    using orth by (simp add: orthogonal_def pairwise_def norm_eq_sqrt_inner that)\n  have \"norm x = norm (\\<Sum>b\\<in>B. representation B x b *\\<^sub>R b)\"\n    using real_vector.sum_representation_eq [OF \\<open>independent B\\<close> x \\<open>finite B\\<close> order_refl]\n    by simp\n  also have \"\\<dots> = sqrt ((\\<Sum>b\\<in>B. representation B x b *\\<^sub>R b) \\<bullet> (\\<Sum>b\\<in>B. representation B x b *\\<^sub>R b))\"\n    by (simp add: norm_eq_sqrt_inner)\n  also have \"\\<dots> = sqrt (\\<Sum>b\\<in>B. (representation B x b *\\<^sub>R b) \\<bullet> (representation B x b *\\<^sub>R b))\"\n    using \\<open>finite B\\<close>\n    by (simp add: inner_sum_left inner_sum_right if_distrib [of \"\\<lambda>x. _ * x\"] cong: if_cong sum.cong_simp)\n  also have \"\\<dots> = sqrt (\\<Sum>b\\<in>B. (norm (representation B x b *\\<^sub>R b))\\<^sup>2)\"\n    by (simp add: mult.commute mult.left_commute power2_eq_square)\n  also have \"\\<dots> = sqrt (\\<Sum>b\\<in>B. (representation B x b)\\<^sup>2 * (norm b)\\<^sup>2)\"\n    by (simp add: norm_mult power_mult_distrib)\n  finally have \"norm x = sqrt (\\<Sum>b\\<in>B. (representation B x b)\\<^sup>2 * (norm b)\\<^sup>2)\" .\n  moreover\n  have \"sqrt ((representation B x b)\\<^sup>2 * (norm b)\\<^sup>2) \\<le> sqrt (\\<Sum>b\\<in>B. (representation B x b)\\<^sup>2 * (norm b)\\<^sup>2)\"\n    using \\<open>b \\<in> B\\<close> \\<open>finite B\\<close> by (auto intro: member_le_sum)\n  then have \"\\<bar>representation B x b\\<bar> \\<le> (1 / norm b) * sqrt (\\<Sum>b\\<in>B. (representation B x b)\\<^sup>2 * (norm b)\\<^sup>2)\"\n    using \\<open>b \\<noteq> 0\\<close> by (simp add: field_split_simps real_sqrt_mult del: real_sqrt_le_iff)\n  ultimately show \"\\<bar>representation B x b\\<bar> \\<le> (1 / norm b) * norm x\"\n    by simp\nnext\n  show \"0 < 1 / norm b\"\n    using \\<open>independent B\\<close> \\<open>b \\<in> B\\<close> dependent_zero by auto\nqed \n\nlemma continuous_on_representation:\n  fixes B :: \"'N::euclidean_space set\"\n  assumes \"finite B\" \"independent B\" \"b \\<in> B\" \"pairwise orthogonal B\" \n  shows \"continuous_on (span B) (\\<lambda>x. representation B x b)\"\nproof\n  show \"\\<exists>d>0. \\<forall>x'\\<in>span B. dist x' x < d \\<longrightarrow> dist (representation B x' b) (representation B x b) \\<le> e\"\n    if \"e > 0\" \"x \\<in> span B\" for x e\n  proof -\n    obtain m where \"m > 0\" and m: \"\\<And>x. x \\<in> span B \\<Longrightarrow> \\<bar>representation B x b\\<bar> \\<le> m * norm x\"\n      using assms representation_bound by blast\n    show ?thesis\n      unfolding dist_norm\n    proof (intro exI conjI ballI impI)\n      show \"e/m > 0\"\n        by (simp add: \\<open>e > 0\\<close> \\<open>m > 0\\<close>)\n      show \"norm (representation B x' b - representation B x b) \\<le> e\"\n        if x': \"x' \\<in> span B\" and less: \"norm (x'-x) < e/m\" for x' \n      proof -\n        have \"\\<bar>representation B (x'-x) b\\<bar> \\<le> m * norm (x'-x)\"\n          using m [of \"x'-x\"] \\<open>x \\<in> span B\\<close> span_diff x' by blast\n        also have \"\\<dots> < e\"\n          by (metis \\<open>m > 0\\<close> less mult.commute pos_less_divide_eq)\n        finally have \"\\<bar>representation B (x'-x) b\\<bar> \\<le> e\" by simp\n        then show ?thesis\n          by (simp add: \\<open>x \\<in> span B\\<close> \\<open>independent B\\<close> representation_diff x')\n      qed\n    qed\n  qed\nqed\n\nsubsection\\<^marker>\\<open>tag unimportant\\<close>\\<open>Balls in Euclidean Space\\<close>\n\nlemma cball_subset_cball_iff:\n  fixes a :: \"'a :: euclidean_space\"\n  shows \"cball a r \\<subseteq> cball a' r' \\<longleftrightarrow> dist a a' + r \\<le> r' \\<or> r < 0\"\n    (is \"?lhs \\<longleftrightarrow> ?rhs\")\nproof\n  assume ?lhs\n  then show ?rhs\n  proof (cases \"r < 0\")\n    case True\n    then show ?rhs by simp\n  next\n    case False\n    then have [simp]: \"r \\<ge> 0\" by simp\n    have \"norm (a - a') + r \\<le> r'\"\n    proof (cases \"a = a'\")\n      case True\n      then show ?thesis\n        using subsetD [where c = \"a + r *\\<^sub>R (SOME i. i \\<in> Basis)\", OF \\<open>?lhs\\<close>] subsetD [where c = a, OF \\<open>?lhs\\<close>]\n        by (force simp: SOME_Basis dist_norm)\n    next\n      case False\n      have \"norm (a' - (a + (r / norm (a - a')) *\\<^sub>R (a - a'))) = norm ((-1 - (r / norm (a - a'))) *\\<^sub>R (a - a'))\"\n        by (simp add: algebra_simps)\n      also from \\<open>a \\<noteq> a'\\<close> have \"... = \\<bar>- norm (a - a') - r\\<bar>\"\n        by (simp add: divide_simps)\n      finally have [simp]: \"norm (a' - (a + (r / norm (a - a')) *\\<^sub>R (a - a'))) = \\<bar>norm (a - a') + r\\<bar>\"\n        by linarith\n      from \\<open>a \\<noteq> a'\\<close> show ?thesis\n        using subsetD [where c = \"a' + (1 + r / norm(a - a')) *\\<^sub>R (a - a')\", OF \\<open>?lhs\\<close>]\n        by (simp add: dist_norm scaleR_add_left)\n    qed\n    then show ?rhs\n      by (simp add: dist_norm)\n  qed\nqed metric\n\nlemma cball_subset_ball_iff: \"cball a r \\<subseteq> ball a' r' \\<longleftrightarrow> dist a a' + r < r' \\<or> r < 0\"\n  (is \"?lhs \\<longleftrightarrow> ?rhs\")\n  for a :: \"'a::euclidean_space\"\nproof\n  assume ?lhs\n  then show ?rhs\n  proof (cases \"r < 0\")\n    case True then\n    show ?rhs by simp\n  next\n    case False\n    then have [simp]: \"r \\<ge> 0\" by simp\n    have \"norm (a - a') + r < r'\"\n    proof (cases \"a = a'\")\n      case True\n      then show ?thesis\n        using subsetD [where c = \"a + r *\\<^sub>R (SOME i. i \\<in> Basis)\", OF \\<open>?lhs\\<close>] subsetD [where c = a, OF \\<open>?lhs\\<close>]\n        by (force simp: SOME_Basis dist_norm)\n    next\n      case False\n      have False if \"norm (a - a') + r \\<ge> r'\"\n      proof -\n        from that have \"\\<bar>r' - norm (a - a')\\<bar> \\<le> r\"\n          by (smt (verit, best) \\<open>0 \\<le> r\\<close> \\<open>?lhs\\<close> ball_subset_cball cball_subset_cball_iff dist_norm order_trans)\n        then show ?thesis\n          using subsetD [where c = \"a + (r' / norm(a - a') - 1) *\\<^sub>R (a - a')\", OF \\<open>?lhs\\<close>] \\<open>a \\<noteq> a'\\<close>\n          apply (simp add: dist_norm)\n          apply (simp add: scaleR_left_diff_distrib)\n          apply (simp add: field_simps)\n          done\n      qed\n      then show ?thesis by force\n    qed\n    then show ?rhs by (simp add: dist_norm)\n  qed\nnext\n  assume ?rhs\n  then show ?lhs\n    by metric\nqed\n\nlemma ball_subset_cball_iff: \"ball a r \\<subseteq> cball a' r' \\<longleftrightarrow> dist a a' + r \\<le> r' \\<or> r \\<le> 0\"\n  (is \"?lhs = ?rhs\")\n  for a :: \"'a::euclidean_space\"\nproof (cases \"r \\<le> 0\")\n  case True\n  then show ?thesis\n    by metric\nnext\n  case False\n  show ?thesis\n  proof\n    assume ?lhs\n    then have \"(cball a r \\<subseteq> cball a' r')\"\n      by (metis False closed_cball closure_ball closure_closed closure_mono not_less)\n    with False show ?rhs\n      by (fastforce iff: cball_subset_cball_iff)\n  next\n    assume ?rhs\n    with False show ?lhs\n      by metric\n  qed\nqed\n\nlemma ball_subset_ball_iff:\n  fixes a :: \"'a :: euclidean_space\"\n  shows \"ball a r \\<subseteq> ball a' r' \\<longleftrightarrow> dist a a' + r \\<le> r' \\<or> r \\<le> 0\"\n        (is \"?lhs = ?rhs\")\nproof (cases \"r \\<le> 0\")\n  case True then show ?thesis\n    by metric\nnext\n  case False show ?thesis\n  proof\n    assume ?lhs\n    then have \"0 < r'\"\n      using False by metric\n    then have \"cball a r \\<subseteq> cball a' r'\"\n      by (metis False \\<open>?lhs\\<close> closure_ball closure_mono not_less)\n    then show ?rhs\n      using False cball_subset_cball_iff by fastforce\n  qed metric\nqed\n\n\nlemma ball_eq_ball_iff:\n  fixes x :: \"'a :: euclidean_space\"\n  shows \"ball x d = ball y e \\<longleftrightarrow> d \\<le> 0 \\<and> e \\<le> 0 \\<or> x=y \\<and> d=e\"\n  by (smt (verit, del_insts) ball_empty ball_subset_cball_iff dist_norm norm_pths(2))\n\nlemma cball_eq_cball_iff:\n  fixes x :: \"'a :: euclidean_space\"\n  shows \"cball x d = cball y e \\<longleftrightarrow> d < 0 \\<and> e < 0 \\<or> x=y \\<and> d=e\"\n  by (smt (verit, ccfv_SIG) cball_empty cball_subset_cball_iff dist_norm norm_pths(2) zero_le_dist)\n\nlemma ball_eq_cball_iff:\n  fixes x :: \"'a :: euclidean_space\"\n  shows \"ball x d = cball y e \\<longleftrightarrow> d \\<le> 0 \\<and> e < 0\" (is \"?lhs = ?rhs\")\n  by (smt (verit) ball_eq_empty ball_subset_cball_iff cball_eq_empty cball_subset_ball_iff order.refl)\n\nlemma cball_eq_ball_iff:\n  fixes x :: \"'a :: euclidean_space\"\n  shows \"cball x d = ball y e \\<longleftrightarrow> d < 0 \\<and> e \\<le> 0\"\n  using ball_eq_cball_iff by blast\n\nlemma finite_ball_avoid:\n  fixes S :: \"'a :: euclidean_space set\"\n  assumes \"open S\" \"finite X\" \"p \\<in> S\"\n  shows \"\\<exists>e>0. \\<forall>w\\<in>ball p e. w\\<in>S \\<and> (w\\<noteq>p \\<longrightarrow> w\\<notin>X)\"\nproof -\n  obtain e1 where \"0 < e1\" and e1_b:\"ball p e1 \\<subseteq> S\"\n    using open_contains_ball_eq[OF \\<open>open S\\<close>] assms by auto\n  obtain e2 where \"0 < e2\" and \"\\<forall>x\\<in>X. x \\<noteq> p \\<longrightarrow> e2 \\<le> dist p x\"\n    using finite_set_avoid[OF \\<open>finite X\\<close>,of p] by auto\n  hence \"\\<forall>w\\<in>ball p (min e1 e2). w\\<in>S \\<and> (w\\<noteq>p \\<longrightarrow> w\\<notin>X)\" using e1_b by auto\n  thus \"\\<exists>e>0. \\<forall>w\\<in>ball p e. w \\<in> S \\<and> (w \\<noteq> p \\<longrightarrow> w \\<notin> X)\" \n    using \\<open>e2>0\\<close> \\<open>e1>0\\<close> by (rule_tac x=\"min e1 e2\" in exI) auto\nqed\n\nlemma finite_cball_avoid:\n  fixes S :: \"'a :: euclidean_space set\"\n  assumes \"open S\" \"finite X\" \"p \\<in> S\"\n  shows \"\\<exists>e>0. \\<forall>w\\<in>cball p e. w\\<in>S \\<and> (w\\<noteq>p \\<longrightarrow> w\\<notin>X)\"\nproof -\n  obtain e1 where \"e1>0\" and e1: \"\\<forall>w\\<in>ball p e1. w\\<in>S \\<and> (w\\<noteq>p \\<longrightarrow> w\\<notin>X)\"\n    using finite_ball_avoid[OF assms] by auto\n  define e2 where \"e2 \\<equiv> e1/2\"\n  have \"e2>0\" and \"e2 < e1\" unfolding e2_def using \\<open>e1>0\\<close> by auto\n  then have \"cball p e2 \\<subseteq> ball p e1\" by (subst cball_subset_ball_iff,auto)\n  then show \"\\<exists>e>0. \\<forall>w\\<in>cball p e. w \\<in> S \\<and> (w \\<noteq> p \\<longrightarrow> w \\<notin> X)\" using \\<open>e2>0\\<close> e1 by auto\nqed\n\nlemma dim_cball:\n  assumes \"e > 0\"\n  shows \"dim (cball (0 :: 'n::euclidean_space) e) = DIM('n)\"\nproof -\n  {\n    fix x :: \"'n::euclidean_space\"\n    define y where \"y = (e / norm x) *\\<^sub>R x\"\n    then have \"y \\<in> cball 0 e\"\n      using assms by auto\n    moreover have *: \"x = (norm x / e) *\\<^sub>R y\"\n      using y_def assms by simp\n    moreover from * have \"x = (norm x/e) *\\<^sub>R y\"\n      by auto\n    ultimately have \"x \\<in> span (cball 0 e)\"\n      using span_scale[of y \"cball 0 e\" \"norm x/e\"]\n        span_superset[of \"cball 0 e\"]\n      by (simp add: span_base)\n  }\n  then have \"span (cball 0 e) = (UNIV :: 'n::euclidean_space set)\"\n    by auto\n  then show ?thesis\n    using dim_span[of \"cball (0 :: 'n::euclidean_space) e\"] by (auto)\nqed\n\n\nsubsection \\<open>Boxes\\<close>\n\nabbreviation\\<^marker>\\<open>tag important\\<close> One :: \"'a::euclidean_space\" where\n\"One \\<equiv> \\<Sum>Basis\"\n\nlemma One_non_0: assumes \"One = (0::'a::euclidean_space)\" shows False\nproof -\n  have \"dependent (Basis :: 'a set)\"\n    apply (simp add: dependent_finite)\n    apply (rule_tac x=\"\\<lambda>i. 1\" in exI)\n    using SOME_Basis apply (auto simp: assms)\n    done\n  with independent_Basis show False by force\nqed\n\ncorollary\\<^marker>\\<open>tag unimportant\\<close> One_neq_0[iff]: \"One \\<noteq> 0\"\n  by (metis One_non_0)\n\ncorollary\\<^marker>\\<open>tag unimportant\\<close> Zero_neq_One[iff]: \"0 \\<noteq> One\"\n  by (metis One_non_0)\n\ndefinition\\<^marker>\\<open>tag important\\<close> (in euclidean_space) eucl_less (infix \"<e\" 50) where \n\"eucl_less a b \\<longleftrightarrow> (\\<forall>i\\<in>Basis. a \\<bullet> i < b \\<bullet> i)\"\n\ndefinition\\<^marker>\\<open>tag important\\<close> box_eucl_less: \"box a b = {x. a <e x \\<and> x <e b}\"\ndefinition\\<^marker>\\<open>tag important\\<close> \"cbox a b = {x. \\<forall>i\\<in>Basis. a \\<bullet> i \\<le> x \\<bullet> i \\<and> x \\<bullet> i \\<le> b \\<bullet> i}\"\n\nlemma box_def: \"box a b = {x. \\<forall>i\\<in>Basis. a \\<bullet> i < x \\<bullet> i \\<and> x \\<bullet> i < b \\<bullet> i}\"\n  and in_box_eucl_less: \"x \\<in> box a b \\<longleftrightarrow> a <e x \\<and> x <e b\"\n  and mem_box: \"x \\<in> box a b \\<longleftrightarrow> (\\<forall>i\\<in>Basis. a \\<bullet> i < x \\<bullet> i \\<and> x \\<bullet> i < b \\<bullet> i)\"\n    \"x \\<in> cbox a b \\<longleftrightarrow> (\\<forall>i\\<in>Basis. a \\<bullet> i \\<le> x \\<bullet> i \\<and> x \\<bullet> i \\<le> b \\<bullet> i)\"\n  by (auto simp: box_eucl_less eucl_less_def cbox_def)\n\nlemma cbox_Pair_eq: \"cbox (a, c) (b, d) = cbox a b \\<times> cbox c d\"\n  by (force simp: cbox_def Basis_prod_def)\n\nlemma cbox_Pair_iff [iff]: \"(x, y) \\<in> cbox (a, c) (b, d) \\<longleftrightarrow> x \\<in> cbox a b \\<and> y \\<in> cbox c d\"\n  by (force simp: cbox_Pair_eq)\n\nlemma cbox_Complex_eq: \"cbox (Complex a c) (Complex b d) = (\\<lambda>(x,y). Complex x y) ` (cbox a b \\<times> cbox c d)\"\n  by (force simp: cbox_def Basis_complex_def)\n\nlemma cbox_Pair_eq_0: \"cbox (a, c) (b, d) = {} \\<longleftrightarrow> cbox a b = {} \\<or> cbox c d = {}\"\n  by (force simp: cbox_Pair_eq)\n\nlemma swap_cbox_Pair [simp]: \"prod.swap ` cbox (c, a) (d, b) = cbox (a,c) (b,d)\"\n  by auto\n\nlemma mem_box_real[simp]:\n  \"(x::real) \\<in> box a b \\<longleftrightarrow> a < x \\<and> x < b\"\n  \"(x::real) \\<in> cbox a b \\<longleftrightarrow> a \\<le> x \\<and> x \\<le> b\"\n  by (auto simp: mem_box)\n\nlemma box_real[simp]:\n  fixes a b:: real\n  shows \"box a b = {a <..< b}\" \"cbox a b = {a .. b}\"\n  by auto\n\nlemma box_Int_box:\n  fixes a :: \"'a::euclidean_space\"\n  shows \"box a b \\<inter> box c d =\n    box (\\<Sum>i\\<in>Basis. max (a\\<bullet>i) (c\\<bullet>i) *\\<^sub>R i) (\\<Sum>i\\<in>Basis. min (b\\<bullet>i) (d\\<bullet>i) *\\<^sub>R i)\"\n  unfolding set_eq_iff and Int_iff and mem_box by auto\n\nlemma rational_boxes:\n  fixes x :: \"'a::euclidean_space\"\n  assumes \"e > 0\"\n  shows \"\\<exists>a b. (\\<forall>i\\<in>Basis. a \\<bullet> i \\<in> \\<rat> \\<and> b \\<bullet> i \\<in> \\<rat>) \\<and> x \\<in> box a b \\<and> box a b \\<subseteq> ball x e\"\nproof -\n  define e' where \"e' = e / (2 * sqrt (real (DIM ('a))))\"\n  then have e: \"e' > 0\"\n    using assms by (auto)\n  have \"\\<exists>y. y \\<in> \\<rat> \\<and> y < x \\<bullet> i \\<and> x \\<bullet> i - y < e'\" for i\n    using Rats_dense_in_real[of \"x \\<bullet> i - e'\" \"x \\<bullet> i\"] e by force\n  then obtain a where\n    a: \"\\<And>u. a u \\<in> \\<rat> \\<and> a u < x \\<bullet> u \\<and> x \\<bullet> u - a u < e'\" by metis\n  have \"\\<exists>y. y \\<in> \\<rat> \\<and> x \\<bullet> i < y \\<and> y - x \\<bullet> i < e'\" for i\n    using Rats_dense_in_real[of \"x \\<bullet> i\" \"x \\<bullet> i + e'\"] e by force\n  then obtain b where\n    b: \"\\<And>u. b u \\<in> \\<rat> \\<and> x \\<bullet> u < b u \\<and> b u - x \\<bullet> u < e'\" by metis\n  let ?a = \"\\<Sum>i\\<in>Basis. a i *\\<^sub>R i\" and ?b = \"\\<Sum>i\\<in>Basis. b i *\\<^sub>R i\"\n  show ?thesis\n  proof (rule exI[of _ ?a], rule exI[of _ ?b], safe)\n    fix y :: 'a\n    assume *: \"y \\<in> box ?a ?b\"\n    have \"dist x y = sqrt (\\<Sum>i\\<in>Basis. (dist (x \\<bullet> i) (y \\<bullet> i))\\<^sup>2)\"\n      unfolding L2_set_def[symmetric] by (rule euclidean_dist_l2)\n    also have \"\\<dots> < sqrt (\\<Sum>(i::'a)\\<in>Basis. e^2 / real (DIM('a)))\"\n    proof (rule real_sqrt_less_mono, rule sum_strict_mono)\n      fix i :: \"'a\"\n      assume i: \"i \\<in> Basis\"\n      have \"a i < y\\<bullet>i \\<and> y\\<bullet>i < b i\"\n        using * i by (auto simp: box_def)\n      moreover have \"a i < x\\<bullet>i\" \"x\\<bullet>i - a i < e'\" \"x\\<bullet>i < b i\" \"b i - x\\<bullet>i < e'\"\n        using a b by auto\n      ultimately have \"\\<bar>x\\<bullet>i - y\\<bullet>i\\<bar> < 2 * e'\"\n        by auto\n      then have \"dist (x \\<bullet> i) (y \\<bullet> i) < e/sqrt (real (DIM('a)))\"\n        unfolding e'_def by (auto simp: dist_real_def)\n      then have \"(dist (x \\<bullet> i) (y \\<bullet> i))\\<^sup>2 < (e/sqrt (real (DIM('a))))\\<^sup>2\"\n        by (rule power_strict_mono) auto\n      then show \"(dist (x \\<bullet> i) (y \\<bullet> i))\\<^sup>2 < e\\<^sup>2 / real DIM('a)\"\n        by (simp add: power_divide)\n    qed auto\n    also have \"\\<dots> = e\"\n      using \\<open>0 < e\\<close> by simp\n    finally show \"y \\<in> ball x e\"\n      by (auto simp: ball_def)\n  qed (use a b in \\<open>auto simp: box_def\\<close>)\nqed\n\nlemma open_UNION_box:\n  fixes M :: \"'a::euclidean_space set\"\n  assumes \"open M\"\n  defines \"a' \\<equiv> \\<lambda>f :: 'a \\<Rightarrow> real \\<times> real. (\\<Sum>(i::'a)\\<in>Basis. fst (f i) *\\<^sub>R i)\"\n  defines \"b' \\<equiv> \\<lambda>f :: 'a \\<Rightarrow> real \\<times> real. (\\<Sum>(i::'a)\\<in>Basis. snd (f i) *\\<^sub>R i)\"\n  defines \"I \\<equiv> {f\\<in>Basis \\<rightarrow>\\<^sub>E \\<rat> \\<times> \\<rat>. box (a' f) (b' f) \\<subseteq> M}\"\n  shows \"M = (\\<Union>f\\<in>I. box (a' f) (b' f))\"\nproof -\n  have \"x \\<in> (\\<Union>f\\<in>I. box (a' f) (b' f))\" if \"x \\<in> M\" for x\n  proof -\n    obtain e where e: \"e > 0\" \"ball x e \\<subseteq> M\"\n      using openE[OF \\<open>open M\\<close> \\<open>x \\<in> M\\<close>] by auto\n    moreover obtain a b where ab:\n      \"x \\<in> box a b\"\n      \"\\<forall>i \\<in> Basis. a \\<bullet> i \\<in> \\<rat>\"\n      \"\\<forall>i\\<in>Basis. b \\<bullet> i \\<in> \\<rat>\"\n      \"box a b \\<subseteq> ball x e\"\n      using rational_boxes[OF e(1)] by metis\n    ultimately show ?thesis\n       by (intro UN_I[of \"\\<lambda>i\\<in>Basis. (a \\<bullet> i, b \\<bullet> i)\"])\n          (auto simp: euclidean_representation I_def a'_def b'_def)\n  qed\n  then show ?thesis by (auto simp: I_def)\nqed\n\ncorollary open_countable_Union_open_box:\n  fixes S :: \"'a :: euclidean_space set\"\n  assumes \"open S\"\n  obtains \\<D> where \"countable \\<D>\" \"\\<D> \\<subseteq> Pow S\" \"\\<And>X. X \\<in> \\<D> \\<Longrightarrow> \\<exists>a b. X = box a b\" \"\\<Union>\\<D> = S\"\nproof -\n  let ?a = \"\\<lambda>f. (\\<Sum>(i::'a)\\<in>Basis. fst (f i) *\\<^sub>R i)\"\n  let ?b = \"\\<lambda>f. (\\<Sum>(i::'a)\\<in>Basis. snd (f i) *\\<^sub>R i)\"\n  let ?I = \"{f\\<in>Basis \\<rightarrow>\\<^sub>E \\<rat> \\<times> \\<rat>. box (?a f) (?b f) \\<subseteq> S}\"\n  let ?\\<D> = \"(\\<lambda>f. box (?a f) (?b f)) ` ?I\"\n  show ?thesis\n  proof\n    have \"countable ?I\"\n      by (simp add: countable_PiE countable_rat)\n    then show \"countable ?\\<D>\"\n      by blast\n    show \"\\<Union>?\\<D> = S\"\n      using open_UNION_box [OF assms] by metis\n  qed auto\nqed\n\nlemma rational_cboxes:\n  fixes x :: \"'a::euclidean_space\"\n  assumes \"e > 0\"\n  shows \"\\<exists>a b. (\\<forall>i\\<in>Basis. a \\<bullet> i \\<in> \\<rat> \\<and> b \\<bullet> i \\<in> \\<rat>) \\<and> x \\<in> cbox a b \\<and> cbox a b \\<subseteq> ball x e\"\nproof -\n  define e' where \"e' = e / (2 * sqrt (real (DIM ('a))))\"\n  then have e: \"e' > 0\"\n    using assms by auto\n  have \"\\<exists>y. y \\<in> \\<rat> \\<and> y < x \\<bullet> i \\<and> x \\<bullet> i - y < e'\" for i\n    using Rats_dense_in_real[of \"x \\<bullet> i - e'\" \"x \\<bullet> i\"] e by force\n  then obtain a where\n    a: \"\\<forall>u. a u \\<in> \\<rat> \\<and> a u < x \\<bullet> u \\<and> x \\<bullet> u - a u < e'\" by metis\n  have \"\\<exists>y. y \\<in> \\<rat> \\<and> x \\<bullet> i < y \\<and> y - x \\<bullet> i < e'\" for i\n    using Rats_dense_in_real[of \"x \\<bullet> i\" \"x \\<bullet> i + e'\"] e by force\n  then obtain b where\n    b: \"\\<forall>u. b u \\<in> \\<rat> \\<and> x \\<bullet> u < b u \\<and> b u - x \\<bullet> u < e'\" by metis\n  let ?a = \"\\<Sum>i\\<in>Basis. a i *\\<^sub>R i\" and ?b = \"\\<Sum>i\\<in>Basis. b i *\\<^sub>R i\"\n  show ?thesis\n  proof (rule exI[of _ ?a], rule exI[of _ ?b], safe)\n    fix y :: 'a\n    assume *: \"y \\<in> cbox ?a ?b\"\n    have \"dist x y = sqrt (\\<Sum>i\\<in>Basis. (dist (x \\<bullet> i) (y \\<bullet> i))\\<^sup>2)\"\n      unfolding L2_set_def[symmetric] by (rule euclidean_dist_l2)\n    also have \"\\<dots> < sqrt (\\<Sum>(i::'a)\\<in>Basis. e^2 / real (DIM('a)))\"\n    proof (rule real_sqrt_less_mono, rule sum_strict_mono)\n      fix i :: \"'a\"\n      assume i: \"i \\<in> Basis\"\n      have \"a i \\<le> y\\<bullet>i \\<and> y\\<bullet>i \\<le> b i\"\n        using * i by (auto simp: cbox_def)\n      moreover have \"a i < x\\<bullet>i\" \"x\\<bullet>i - a i < e'\" \"x\\<bullet>i < b i\" \"b i - x\\<bullet>i < e'\"\n        using a b by auto\n      ultimately have \"\\<bar>x\\<bullet>i - y\\<bullet>i\\<bar> < 2 * e'\"\n        by auto\n      then have \"dist (x \\<bullet> i) (y \\<bullet> i) < e/sqrt (real (DIM('a)))\"\n        unfolding e'_def by (auto simp: dist_real_def)\n      then have \"(dist (x \\<bullet> i) (y \\<bullet> i))\\<^sup>2 < (e/sqrt (real (DIM('a))))\\<^sup>2\"\n        by (rule power_strict_mono) auto\n      then show \"(dist (x \\<bullet> i) (y \\<bullet> i))\\<^sup>2 < e\\<^sup>2 / real DIM('a)\"\n        by (simp add: power_divide)\n    qed auto\n    also have \"\\<dots> = e\"\n      using \\<open>0 < e\\<close> by simp\n    finally show \"y \\<in> ball x e\"\n      by (auto simp: ball_def)\n  next\n    show \"x \\<in> cbox (\\<Sum>i\\<in>Basis. a i *\\<^sub>R i) (\\<Sum>i\\<in>Basis. b i *\\<^sub>R i)\"\n      using a b less_imp_le by (auto simp: cbox_def)\n  qed (use a b cbox_def in auto)\nqed\n\nlemma open_UNION_cbox:\n  fixes M :: \"'a::euclidean_space set\"\n  assumes \"open M\"\n  defines \"a' \\<equiv> \\<lambda>f. (\\<Sum>(i::'a)\\<in>Basis. fst (f i) *\\<^sub>R i)\"\n  defines \"b' \\<equiv> \\<lambda>f. (\\<Sum>(i::'a)\\<in>Basis. snd (f i) *\\<^sub>R i)\"\n  defines \"I \\<equiv> {f\\<in>Basis \\<rightarrow>\\<^sub>E \\<rat> \\<times> \\<rat>. cbox (a' f) (b' f) \\<subseteq> M}\"\n  shows \"M = (\\<Union>f\\<in>I. cbox (a' f) (b' f))\"\nproof -\n  have \"x \\<in> (\\<Union>f\\<in>I. cbox (a' f) (b' f))\" if \"x \\<in> M\" for x\n  proof -\n    obtain e where e: \"e > 0\" \"ball x e \\<subseteq> M\"\n      using openE[OF \\<open>open M\\<close> \\<open>x \\<in> M\\<close>] by auto\n    moreover obtain a b where ab: \"x \\<in> cbox a b\" \"\\<forall>i \\<in> Basis. a \\<bullet> i \\<in> \\<rat>\"\n                                  \"\\<forall>i \\<in> Basis. b \\<bullet> i \\<in> \\<rat>\" \"cbox a b \\<subseteq> ball x e\"\n      using rational_cboxes[OF e(1)] by metis\n    ultimately show ?thesis\n       by (intro UN_I[of \"\\<lambda>i\\<in>Basis. (a \\<bullet> i, b \\<bullet> i)\"])\n          (auto simp: euclidean_representation I_def a'_def b'_def)\n  qed\n  then show ?thesis by (auto simp: I_def)\nqed\n\ncorollary open_countable_Union_open_cbox:\n  fixes S :: \"'a :: euclidean_space set\"\n  assumes \"open S\"\n  obtains \\<D> where \"countable \\<D>\" \"\\<D> \\<subseteq> Pow S\" \"\\<And>X. X \\<in> \\<D> \\<Longrightarrow> \\<exists>a b. X = cbox a b\" \"\\<Union>\\<D> = S\"\nproof -\n  let ?a = \"\\<lambda>f. (\\<Sum>(i::'a)\\<in>Basis. fst (f i) *\\<^sub>R i)\"\n  let ?b = \"\\<lambda>f. (\\<Sum>(i::'a)\\<in>Basis. snd (f i) *\\<^sub>R i)\"\n  let ?I = \"{f\\<in>Basis \\<rightarrow>\\<^sub>E \\<rat> \\<times> \\<rat>. cbox (?a f) (?b f) \\<subseteq> S}\"\n  let ?\\<D> = \"(\\<lambda>f. cbox (?a f) (?b f)) ` ?I\"\n  show ?thesis\n  proof\n    have \"countable ?I\"\n      by (simp add: countable_PiE countable_rat)\n    then show \"countable ?\\<D>\"\n      by blast\n    show \"\\<Union>?\\<D> = S\"\n      using open_UNION_cbox [OF assms] by metis\n  qed auto\nqed\n\nlemma box_eq_empty:\n  fixes a :: \"'a::euclidean_space\"\n  shows \"(box a b = {} \\<longleftrightarrow> (\\<exists>i\\<in>Basis. b\\<bullet>i \\<le> a\\<bullet>i))\" (is ?th1)\n    and \"(cbox a b = {} \\<longleftrightarrow> (\\<exists>i\\<in>Basis. b\\<bullet>i < a\\<bullet>i))\" (is ?th2)\nproof -\n  have False if \"i \\<in> Basis\" and \"b\\<bullet>i \\<le> a\\<bullet>i\" and \"x \\<in> box a b\" for i x\n    by (smt (verit, ccfv_SIG) mem_box(1) that)\n  moreover\n  { assume as: \"\\<forall>i\\<in>Basis. \\<not> (b\\<bullet>i \\<le> a\\<bullet>i)\"\n    let ?x = \"(1/2) *\\<^sub>R (a + b)\"\n    { fix i :: 'a\n      assume i: \"i \\<in> Basis\"\n      have \"a\\<bullet>i < b\\<bullet>i\"\n        using as i by fastforce\n      then have \"a\\<bullet>i < ((1/2) *\\<^sub>R (a+b)) \\<bullet> i\" \"((1/2) *\\<^sub>R (a+b)) \\<bullet> i < b\\<bullet>i\"\n        by (auto simp: inner_add_left)\n    }\n    then have \"box a b \\<noteq> {}\"\n      by (metis (no_types, opaque_lifting) emptyE mem_box(1))\n  }\n  ultimately show ?th1 by blast\n\n  have False if \"i\\<in>Basis\" and \"b\\<bullet>i < a\\<bullet>i\" and \"x \\<in> cbox a b\" for i x\n    using mem_box(2) that by force\n  moreover\n  have \"cbox a b \\<noteq> {}\" if \"\\<forall>i\\<in>Basis. \\<not> (b\\<bullet>i < a\\<bullet>i)\"\n    by (metis emptyE linorder_linear mem_box(2) order.strict_iff_not that)\n  ultimately show ?th2 by blast\nqed\n\nlemma box_ne_empty:\n  fixes a :: \"'a::euclidean_space\"\n  shows \"cbox a b \\<noteq> {} \\<longleftrightarrow> (\\<forall>i\\<in>Basis. a\\<bullet>i \\<le> b\\<bullet>i)\"\n  and \"box a b \\<noteq> {} \\<longleftrightarrow> (\\<forall>i\\<in>Basis. a\\<bullet>i < b\\<bullet>i)\"\n  unfolding box_eq_empty[of a b] by fastforce+\n\nlemma\n  fixes a :: \"'a::euclidean_space\"\n  shows cbox_idem [simp]: \"cbox a a = {a}\"\n    and box_idem [simp]: \"box a a = {}\"\n  unfolding set_eq_iff mem_box eq_iff [symmetric] using euclidean_eq_iff by fastforce+\n\nlemma subset_box_imp:\n  fixes a :: \"'a::euclidean_space\"\n  shows \"(\\<forall>i\\<in>Basis. a\\<bullet>i \\<le> c\\<bullet>i \\<and> d\\<bullet>i \\<le> b\\<bullet>i) \\<Longrightarrow> cbox c d \\<subseteq> cbox a b\"\n    and \"(\\<forall>i\\<in>Basis. a\\<bullet>i < c\\<bullet>i \\<and> d\\<bullet>i < b\\<bullet>i) \\<Longrightarrow> cbox c d \\<subseteq> box a b\"\n    and \"(\\<forall>i\\<in>Basis. a\\<bullet>i \\<le> c\\<bullet>i \\<and> d\\<bullet>i \\<le> b\\<bullet>i) \\<Longrightarrow> box c d \\<subseteq> cbox a b\"\n     and \"(\\<forall>i\\<in>Basis. a\\<bullet>i \\<le> c\\<bullet>i \\<and> d\\<bullet>i \\<le> b\\<bullet>i) \\<Longrightarrow> box c d \\<subseteq> box a b\"\n  unfolding subset_eq[unfolded Ball_def] unfolding mem_box\n  by (best intro: order_trans less_le_trans le_less_trans less_imp_le)+\n\nlemma box_subset_cbox:\n  fixes a :: \"'a::euclidean_space\"\n  shows \"box a b \\<subseteq> cbox a b\"\n  unfolding subset_eq [unfolded Ball_def] mem_box\n  by (fast intro: less_imp_le)\n\nlemma subset_box:\n  fixes a :: \"'a::euclidean_space\"\n  shows \"cbox c d \\<subseteq> cbox a b \\<longleftrightarrow> (\\<forall>i\\<in>Basis. c\\<bullet>i \\<le> d\\<bullet>i) \\<longrightarrow> (\\<forall>i\\<in>Basis. a\\<bullet>i \\<le> c\\<bullet>i \\<and> d\\<bullet>i \\<le> b\\<bullet>i)\" (is ?th1)\n    and \"cbox c d \\<subseteq> box a b \\<longleftrightarrow> (\\<forall>i\\<in>Basis. c\\<bullet>i \\<le> d\\<bullet>i) \\<longrightarrow> (\\<forall>i\\<in>Basis. a\\<bullet>i < c\\<bullet>i \\<and> d\\<bullet>i < b\\<bullet>i)\" (is ?th2)\n    and \"box c d \\<subseteq> cbox a b \\<longleftrightarrow> (\\<forall>i\\<in>Basis. c\\<bullet>i < d\\<bullet>i) \\<longrightarrow> (\\<forall>i\\<in>Basis. a\\<bullet>i \\<le> c\\<bullet>i \\<and> d\\<bullet>i \\<le> b\\<bullet>i)\" (is ?th3)\n    and \"box c d \\<subseteq> box a b \\<longleftrightarrow> (\\<forall>i\\<in>Basis. c\\<bullet>i < d\\<bullet>i) \\<longrightarrow> (\\<forall>i\\<in>Basis. a\\<bullet>i \\<le> c\\<bullet>i \\<and> d\\<bullet>i \\<le> b\\<bullet>i)\" (is ?th4)\nproof -\n  let ?lesscd = \"\\<forall>i\\<in>Basis. c\\<bullet>i < d\\<bullet>i\"\n  let ?lerhs = \"\\<forall>i\\<in>Basis. a\\<bullet>i \\<le> c\\<bullet>i \\<and> d\\<bullet>i \\<le> b\\<bullet>i\"\n  show ?th1 ?th2\n    by (fastforce simp: mem_box)+\n  have acdb: \"a\\<bullet>i \\<le> c\\<bullet>i \\<and> d\\<bullet>i \\<le> b\\<bullet>i\"\n    if i: \"i \\<in> Basis\" and box: \"box c d \\<subseteq> cbox a b\" and cd: \"\\<And>i. i \\<in> Basis \\<Longrightarrow> c\\<bullet>i < d\\<bullet>i\" for i\n  proof -\n    have \"box c d \\<noteq> {}\"\n      using that\n      unfolding box_eq_empty by force\n    { let ?x = \"(\\<Sum>j\\<in>Basis. (if j=i then ((min (a\\<bullet>j) (d\\<bullet>j))+c\\<bullet>j)/2 else (c\\<bullet>j+d\\<bullet>j)/2) *\\<^sub>R j)::'a\"\n      assume *: \"a\\<bullet>i > c\\<bullet>i\"\n      then have \"c \\<bullet> j < ?x \\<bullet> j \\<and> ?x \\<bullet> j < d \\<bullet> j\" if \"j \\<in> Basis\" for j\n        using cd that by (fastforce simp add: i *)\n      then have \"?x \\<in> box c d\"\n        unfolding mem_box by auto\n      moreover have \"?x \\<notin> cbox a b\"\n        using i cd * by (force simp: mem_box)\n      ultimately have False using box by auto\n    }\n    then have \"a\\<bullet>i \\<le> c\\<bullet>i\" by force\n    moreover\n    { let ?x = \"(\\<Sum>j\\<in>Basis. (if j=i then ((max (b\\<bullet>j) (c\\<bullet>j))+d\\<bullet>j)/2 else (c\\<bullet>j+d\\<bullet>j)/2) *\\<^sub>R j)::'a\"\n      assume *: \"b\\<bullet>i < d\\<bullet>i\"\n      then have \"d \\<bullet> j > ?x \\<bullet> j \\<and> ?x \\<bullet> j > c \\<bullet> j\" if \"j \\<in> Basis\" for j\n        using cd that by (fastforce simp add: i *)\n      then have \"?x \\<in> box c d\"\n        unfolding mem_box by auto\n      moreover have \"?x \\<notin> cbox a b\"\n        using i cd * by (force simp: mem_box)\n      ultimately have False using box by auto\n    }\n    then have \"b\\<bullet>i \\<ge> d\\<bullet>i\" by (rule ccontr) auto\n    ultimately show ?thesis by auto\n  qed\n  show ?th3\n    using acdb by (fastforce simp add: mem_box)\n  have acdb': \"a\\<bullet>i \\<le> c\\<bullet>i \\<and> d\\<bullet>i \\<le> b\\<bullet>i\"\n    if \"i \\<in> Basis\" \"box c d \\<subseteq> box a b\" \"\\<And>i. i \\<in> Basis \\<Longrightarrow> c\\<bullet>i < d\\<bullet>i\" for i\n      using box_subset_cbox[of a b] that acdb by auto\n  show ?th4\n    using acdb' by (fastforce simp add: mem_box)\nqed\n\nlemma eq_cbox: \"cbox a b = cbox c d \\<longleftrightarrow> cbox a b = {} \\<and> cbox c d = {} \\<or> a = c \\<and> b = d\"\n      (is \"?lhs = ?rhs\")\nproof\n  assume ?lhs\n  then have \"cbox a b \\<subseteq> cbox c d\" \"cbox c d \\<subseteq> cbox a b\"\n    by auto\n  then show ?rhs\n    by (force simp: subset_box box_eq_empty intro: antisym euclidean_eqI)\nqed auto\n\nlemma eq_cbox_box [simp]: \"cbox a b = box c d \\<longleftrightarrow> cbox a b = {} \\<and> box c d = {}\"\n  (is \"?lhs \\<longleftrightarrow> ?rhs\")\nproof\n  assume L: ?lhs\n  then have \"cbox a b \\<subseteq> box c d\" \"box c d \\<subseteq> cbox a b\"\n    by auto\n  with L subset_box show ?rhs\n    by (smt (verit) SOME_Basis box_ne_empty(1))\nqed force\n\nlemma eq_box_cbox [simp]: \"box a b = cbox c d \\<longleftrightarrow> box a b = {} \\<and> cbox c d = {}\"\n  by (metis eq_cbox_box)\n\nlemma eq_box: \"box a b = box c d \\<longleftrightarrow> box a b = {} \\<and> box c d = {} \\<or> a = c \\<and> b = d\"\n  (is \"?lhs \\<longleftrightarrow> ?rhs\")\nproof\n  assume L: ?lhs\n  then have \"box a b \\<subseteq> box c d\" \"box c d \\<subseteq> box a b\"\n    by auto\n  then show ?rhs\n    unfolding subset_box by (smt (verit) box_ne_empty(2) euclidean_eq_iff)+\nqed force\n\nlemma subset_box_complex:\n   \"cbox a b \\<subseteq> cbox c d \\<longleftrightarrow>\n      (Re a \\<le> Re b \\<and> Im a \\<le> Im b) \\<longrightarrow> Re a \\<ge> Re c \\<and> Im a \\<ge> Im c \\<and> Re b \\<le> Re d \\<and> Im b \\<le> Im d\"\n   \"cbox a b \\<subseteq> box c d \\<longleftrightarrow>\n      (Re a \\<le> Re b \\<and> Im a \\<le> Im b) \\<longrightarrow> Re a > Re c \\<and> Im a > Im c \\<and> Re b < Re d \\<and> Im b < Im d\"\n   \"box a b \\<subseteq> cbox c d \\<longleftrightarrow>\n      (Re a < Re b \\<and> Im a < Im b) \\<longrightarrow> Re a \\<ge> Re c \\<and> Im a \\<ge> Im c \\<and> Re b \\<le> Re d \\<and> Im b \\<le> Im d\"\n   \"box a b \\<subseteq> box c d \\<longleftrightarrow>\n      (Re a < Re b \\<and> Im a < Im b) \\<longrightarrow> Re a \\<ge> Re c \\<and> Im a \\<ge> Im c \\<and> Re b \\<le> Re d \\<and> Im b \\<le> Im d\"\n  by (subst subset_box; force simp: Basis_complex_def)+\n\nlemma in_cbox_complex_iff:\n  \"x \\<in> cbox a b \\<longleftrightarrow> Re x \\<in> {Re a..Re b} \\<and> Im x \\<in> {Im a..Im b}\"\n  by (cases x; cases a; cases b) (auto simp: cbox_Complex_eq)\n\nlemma cbox_complex_of_real: \"cbox (complex_of_real x) (complex_of_real y) = complex_of_real ` {x..y}\"\nproof -\n  have \"(x \\<le> Re z \\<and> Re z \\<le> y \\<and> Im z = 0) = (z \\<in> complex_of_real ` {x..y})\" for z\n    by (cases z) (simp add: complex_eq_cancel_iff2 image_iff)\n  then show ?thesis\n    by (auto simp: in_cbox_complex_iff)\nqed\n\nlemma box_Complex_eq:\n  \"box (Complex a c) (Complex b d) = (\\<lambda>(x,y). Complex x y) ` (box a b \\<times> box c d)\"\n  by (auto simp: box_def Basis_complex_def image_iff complex_eq_iff)\n\nlemma in_box_complex_iff:\n  \"x \\<in> box a b \\<longleftrightarrow> Re x \\<in> {Re a<..<Re b} \\<and> Im x \\<in> {Im a<..<Im b}\"\n  by (cases x; cases a; cases b) (auto simp: box_Complex_eq)\n\nlemma box_complex_of_real [simp]: \"box (complex_of_real x) (complex_of_real y) = {}\"\n  by (auto simp: in_box_complex_iff)\n\nlemma Int_interval:\n  fixes a :: \"'a::euclidean_space\"\n  shows \"cbox a b \\<inter> cbox c d =\n    cbox (\\<Sum>i\\<in>Basis. max (a\\<bullet>i) (c\\<bullet>i) *\\<^sub>R i) (\\<Sum>i\\<in>Basis. min (b\\<bullet>i) (d\\<bullet>i) *\\<^sub>R i)\"\n  unfolding set_eq_iff and Int_iff and mem_box\n  by auto\n\nlemma disjoint_interval:\n  fixes a::\"'a::euclidean_space\"\n  shows \"cbox a b \\<inter> cbox c d = {} \\<longleftrightarrow> (\\<exists>i\\<in>Basis. (b\\<bullet>i < a\\<bullet>i \\<or> d\\<bullet>i < c\\<bullet>i \\<or> b\\<bullet>i < c\\<bullet>i \\<or> d\\<bullet>i < a\\<bullet>i))\" (is ?th1)\n    and \"cbox a b \\<inter> box c d = {} \\<longleftrightarrow> (\\<exists>i\\<in>Basis. (b\\<bullet>i < a\\<bullet>i \\<or> d\\<bullet>i \\<le> c\\<bullet>i \\<or> b\\<bullet>i \\<le> c\\<bullet>i \\<or> d\\<bullet>i \\<le> a\\<bullet>i))\" (is ?th2)\n    and \"box a b \\<inter> cbox c d = {} \\<longleftrightarrow> (\\<exists>i\\<in>Basis. (b\\<bullet>i \\<le> a\\<bullet>i \\<or> d\\<bullet>i < c\\<bullet>i \\<or> b\\<bullet>i \\<le> c\\<bullet>i \\<or> d\\<bullet>i \\<le> a\\<bullet>i))\" (is ?th3)\n    and \"box a b \\<inter> box c d = {} \\<longleftrightarrow> (\\<exists>i\\<in>Basis. (b\\<bullet>i \\<le> a\\<bullet>i \\<or> d\\<bullet>i \\<le> c\\<bullet>i \\<or> b\\<bullet>i \\<le> c\\<bullet>i \\<or> d\\<bullet>i \\<le> a\\<bullet>i))\" (is ?th4)\nproof -\n  let ?z = \"(\\<Sum>i\\<in>Basis. (((max (a\\<bullet>i) (c\\<bullet>i)) + (min (b\\<bullet>i) (d\\<bullet>i))) / 2) *\\<^sub>R i)::'a\"\n  have **: \"\\<And>P Q. (\\<And>i :: 'a. i \\<in> Basis \\<Longrightarrow> Q ?z i \\<Longrightarrow> P i) \\<Longrightarrow>\n      (\\<And>i x :: 'a. i \\<in> Basis \\<Longrightarrow> P i \\<Longrightarrow> Q x i) \\<Longrightarrow> (\\<forall>x. \\<exists>i\\<in>Basis. Q x i) \\<longleftrightarrow> (\\<exists>i\\<in>Basis. P i)\"\n    by blast\n  note * = set_eq_iff Int_iff empty_iff mem_box ball_conj_distrib[symmetric] eq_False ball_simps(10)\n  show ?th1 unfolding * by (intro **) auto\n  show ?th2 unfolding * by (intro **) auto\n  show ?th3 unfolding * by (intro **) auto\n  show ?th4 unfolding * by (intro **) auto\nqed\n\nlemma UN_box_eq_UNIV: \"(\\<Union>i::nat. box (- (real i *\\<^sub>R One)) (real i *\\<^sub>R One)) = UNIV\"\nproof -\n  have \"\\<bar>x \\<bullet> b\\<bar> < real_of_int (\\<lceil>Max ((\\<lambda>b. \\<bar>x \\<bullet> b\\<bar>)`Basis)\\<rceil> + 1)\"\n    if [simp]: \"b \\<in> Basis\" for x b :: 'a\n  proof -\n    have \"\\<bar>x \\<bullet> b\\<bar> \\<le> real_of_int \\<lceil>\\<bar>x \\<bullet> b\\<bar>\\<rceil>\"\n      by (rule le_of_int_ceiling)\n    also have \"\\<dots> \\<le> real_of_int \\<lceil>Max ((\\<lambda>b. \\<bar>x \\<bullet> b\\<bar>)`Basis)\\<rceil>\"\n      by (auto intro!: ceiling_mono)\n    also have \"\\<dots> < real_of_int (\\<lceil>Max ((\\<lambda>b. \\<bar>x \\<bullet> b\\<bar>)`Basis)\\<rceil> + 1)\"\n      by simp\n    finally show ?thesis .\n  qed\n  then have \"\\<exists>n::nat. \\<forall>b\\<in>Basis. \\<bar>x \\<bullet> b\\<bar> < real n\" for x :: 'a\n    by (metis order.strict_trans reals_Archimedean2)\n  moreover have \"\\<And>x b::'a. \\<And>n::nat.  \\<bar>x \\<bullet> b\\<bar> < real n \\<longleftrightarrow> - real n < x \\<bullet> b \\<and> x \\<bullet> b < real n\"\n    by auto\n  ultimately show ?thesis\n    by (auto simp: box_def inner_sum_left inner_Basis sum.If_cases)\nqed\n\nlemma image_affinity_cbox: fixes m::real\n  fixes a b c :: \"'a::euclidean_space\"\n  shows \"(\\<lambda>x. m *\\<^sub>R x + c) ` cbox a b =\n    (if cbox a b = {} then {}\n     else (if 0 \\<le> m then cbox (m *\\<^sub>R a + c) (m *\\<^sub>R b + c)\n     else cbox (m *\\<^sub>R b + c) (m *\\<^sub>R a + c)))\"\nproof (cases \"m = 0\")\n  case True\n  {\n    fix x\n    assume \"\\<forall>i\\<in>Basis. x \\<bullet> i \\<le> c \\<bullet> i\" \"\\<forall>i\\<in>Basis. c \\<bullet> i \\<le> x \\<bullet> i\"\n    then have \"x = c\"\n      by (simp add: dual_order.antisym euclidean_eqI)\n  }\n  moreover have \"c \\<in> cbox (m *\\<^sub>R a + c) (m *\\<^sub>R b + c)\"\n    unfolding True by auto\n  ultimately show ?thesis using True by (auto simp: cbox_def)\nnext\n  case False\n  {\n    fix y\n    assume \"\\<forall>i\\<in>Basis. a \\<bullet> i \\<le> y \\<bullet> i\" \"\\<forall>i\\<in>Basis. y \\<bullet> i \\<le> b \\<bullet> i\" \"m > 0\"\n    then have \"\\<forall>i\\<in>Basis. (m *\\<^sub>R a + c) \\<bullet> i \\<le> (m *\\<^sub>R y + c) \\<bullet> i\" \n          and \"\\<forall>i\\<in>Basis. (m *\\<^sub>R y + c) \\<bullet> i \\<le> (m *\\<^sub>R b + c) \\<bullet> i\"\n      by (auto simp: inner_distrib)\n  }\n  moreover\n  {\n    fix y\n    assume \"\\<forall>i\\<in>Basis. a \\<bullet> i \\<le> y \\<bullet> i\" \"\\<forall>i\\<in>Basis. y \\<bullet> i \\<le> b \\<bullet> i\" \"m < 0\"\n    then have \"\\<forall>i\\<in>Basis. (m *\\<^sub>R b + c) \\<bullet> i \\<le> (m *\\<^sub>R y + c) \\<bullet> i\"\n         and  \"\\<forall>i\\<in>Basis. (m *\\<^sub>R y + c) \\<bullet> i \\<le> (m *\\<^sub>R a + c) \\<bullet> i\"\n      by (auto simp: mult_left_mono_neg inner_distrib)\n  }\n  moreover\n  {\n    fix y\n    assume \"m > 0\" and \"\\<forall>i\\<in>Basis. (m *\\<^sub>R a + c) \\<bullet> i \\<le> y \\<bullet> i\"\n      and  \"\\<forall>i\\<in>Basis. y \\<bullet> i \\<le> (m *\\<^sub>R b + c) \\<bullet> i\"\n    then have \"y \\<in> (\\<lambda>x. m *\\<^sub>R x + c) ` cbox a b\"\n      unfolding image_iff Bex_def mem_box\n      apply (intro exI[where x=\"(1 / m) *\\<^sub>R (y - c)\"])\n      apply (auto simp: pos_le_divide_eq pos_divide_le_eq mult.commute inner_distrib inner_diff_left)\n      done\n  }\n  moreover\n  {\n    fix y\n    assume \"\\<forall>i\\<in>Basis. (m *\\<^sub>R b + c) \\<bullet> i \\<le> y \\<bullet> i\" \"\\<forall>i\\<in>Basis. y \\<bullet> i \\<le> (m *\\<^sub>R a + c) \\<bullet> i\" \"m < 0\"\n    then have \"y \\<in> (\\<lambda>x. m *\\<^sub>R x + c) ` cbox a b\"\n      unfolding image_iff Bex_def mem_box\n      apply (intro exI[where x=\"(1 / m) *\\<^sub>R (y - c)\"])\n      apply (auto simp: neg_le_divide_eq neg_divide_le_eq mult.commute inner_distrib inner_diff_left)\n      done\n  }\n  ultimately show ?thesis using False by (auto simp: cbox_def)\nqed\n\nlemma image_smult_cbox:\"(\\<lambda>x. m *\\<^sub>R (x::_::euclidean_space)) ` cbox a b =\n  (if cbox a b = {} then {} else if 0 \\<le> m then cbox (m *\\<^sub>R a) (m *\\<^sub>R b) else cbox (m *\\<^sub>R b) (m *\\<^sub>R a))\"\n  using image_affinity_cbox[of m 0 a b] by auto\n\nlemma swap_continuous:\n  assumes \"continuous_on (cbox (a,c) (b,d)) (\\<lambda>(x,y). f x y)\"\n    shows \"continuous_on (cbox (c,a) (d,b)) (\\<lambda>(x, y). f y x)\"\nproof -\n  have \"(\\<lambda>(x, y). f y x) = (\\<lambda>(x, y). f x y) \\<circ> prod.swap\"\n    by auto\n  then show ?thesis\n    by (metis assms continuous_on_compose continuous_on_swap swap_cbox_Pair)\nqed\n\nlemma open_contains_cbox:\n  fixes x :: \"'a :: euclidean_space\"\n  assumes \"open A\" \"x \\<in> A\"\n  obtains a b where \"cbox a b \\<subseteq> A\" \"x \\<in> box a b\" \"\\<forall>i\\<in>Basis. a \\<bullet> i < b \\<bullet> i\"\nproof -\n  from assms obtain R where R: \"R > 0\" \"ball x R \\<subseteq> A\"\n    by (auto simp: open_contains_ball)\n  define r :: real where \"r = R / (2 * sqrt DIM('a))\"\n  from \\<open>R > 0\\<close> have [simp]: \"r > 0\" by (auto simp: r_def)\n  define d :: 'a where \"d = r *\\<^sub>R Topology_Euclidean_Space.One\"\n  have \"cbox (x - d) (x + d) \\<subseteq> A\"\n  proof safe\n    fix y assume y: \"y \\<in> cbox (x - d) (x + d)\"\n    have \"dist x y = sqrt (\\<Sum>i\\<in>Basis. (dist (x \\<bullet> i) (y \\<bullet> i))\\<^sup>2)\"\n      by (subst euclidean_dist_l2) (auto simp: L2_set_def)\n    also from y have \"sqrt (\\<Sum>i\\<in>Basis. (dist (x \\<bullet> i) (y \\<bullet> i))\\<^sup>2) \\<le> sqrt (\\<Sum>i\\<in>(Basis::'a set). r\\<^sup>2)\"\n      by (intro real_sqrt_le_mono sum_mono power_mono)\n         (auto simp: dist_norm d_def cbox_def algebra_simps)\n    also have \"\\<dots> = sqrt (DIM('a) * r\\<^sup>2)\" by simp\n    also have \"DIM('a) * r\\<^sup>2 = (R / 2) ^ 2\"\n      by (simp add: r_def power_divide)\n    also have \"sqrt \\<dots> = R / 2\"\n      using \\<open>R > 0\\<close> by simp\n    also from \\<open>R > 0\\<close> have \"\\<dots> < R\" by simp\n    finally have \"y \\<in> ball x R\" by simp\n    with R show \"y \\<in> A\" by blast\n  qed\n  thus ?thesis\n    using that[of \"x - d\" \"x + d\"] by (auto simp: algebra_simps d_def box_def)\nqed\n\nlemma open_contains_box:\n  fixes x :: \"'a :: euclidean_space\"\n  assumes \"open A\" \"x \\<in> A\"\n  obtains a b where \"box a b \\<subseteq> A\" \"x \\<in> box a b\" \"\\<forall>i\\<in>Basis. a \\<bullet> i < b \\<bullet> i\"\n  by (meson assms box_subset_cbox dual_order.trans open_contains_cbox)\n\nlemma inner_image_box:\n  assumes \"(i :: 'a :: euclidean_space) \\<in> Basis\"\n  assumes \"\\<forall>i\\<in>Basis. a \\<bullet> i < b \\<bullet> i\"\n  shows   \"(\\<lambda>x. x \\<bullet> i) ` box a b = {a \\<bullet> i<..<b \\<bullet> i}\"\nproof safe\n  fix x assume x: \"x \\<in> {a \\<bullet> i<..<b \\<bullet> i}\"\n  let ?y = \"(\\<Sum>j\\<in>Basis. (if i = j then x else (a + b) \\<bullet> j / 2) *\\<^sub>R j)\"\n  from x assms have \"?y \\<bullet> i \\<in> (\\<lambda>x. x \\<bullet> i) ` box a b\"\n    by (intro imageI) (auto simp: box_def algebra_simps)\n  also have \"?y \\<bullet> i = (\\<Sum>j\\<in>Basis. (if i = j then x else (a + b) \\<bullet> j / 2) * (j \\<bullet> i))\"\n    by (simp add: inner_sum_left)\n  also have \"\\<dots> = (\\<Sum>j\\<in>Basis. if i = j then x else 0)\"\n    by (intro sum.cong) (auto simp: inner_not_same_Basis assms)\n  also have \"\\<dots> = x\" using assms by simp\n  finally show \"x \\<in> (\\<lambda>x. x \\<bullet> i) ` box a b\"  .\nqed (insert assms, auto simp: box_def)\n\nlemma inner_image_cbox:\n  assumes \"(i :: 'a :: euclidean_space) \\<in> Basis\"\n  assumes \"\\<forall>i\\<in>Basis. a \\<bullet> i \\<le> b \\<bullet> i\"\n  shows   \"(\\<lambda>x. x \\<bullet> i) ` cbox a b = {a \\<bullet> i..b \\<bullet> i}\"\nproof safe\n  fix x assume x: \"x \\<in> {a \\<bullet> i..b \\<bullet> i}\"\n  let ?y = \"(\\<Sum>j\\<in>Basis. (if i = j then x else a \\<bullet> j) *\\<^sub>R j)\"\n  from x assms have \"?y \\<bullet> i \\<in> (\\<lambda>x. x \\<bullet> i) ` cbox a b\"\n    by (intro imageI) (auto simp: cbox_def)\n  also have \"?y \\<bullet> i = (\\<Sum>j\\<in>Basis. (if i = j then x else a \\<bullet> j) * (j \\<bullet> i))\"\n    by (simp add: inner_sum_left)\n  also have \"\\<dots> = (\\<Sum>j\\<in>Basis. if i = j then x else 0)\"\n    by (intro sum.cong) (auto simp: inner_not_same_Basis assms)\n  also have \"\\<dots> = x\" using assms by simp\n  finally show \"x \\<in> (\\<lambda>x. x \\<bullet> i) ` cbox a b\"  .\nqed (insert assms, auto simp: cbox_def)\n\nsubsection \\<open>General Intervals\\<close>\n\ndefinition\\<^marker>\\<open>tag important\\<close> \"is_interval (s::('a::euclidean_space) set) \\<longleftrightarrow>\n  (\\<forall>a\\<in>s. \\<forall>b\\<in>s. \\<forall>x. (\\<forall>i\\<in>Basis. ((a\\<bullet>i \\<le> x\\<bullet>i \\<and> x\\<bullet>i \\<le> b\\<bullet>i) \\<or> (b\\<bullet>i \\<le> x\\<bullet>i \\<and> x\\<bullet>i \\<le> a\\<bullet>i))) \\<longrightarrow> x \\<in> s)\"\n\nlemma is_interval_1:\n  \"is_interval (s::real set) \\<longleftrightarrow> (\\<forall>a\\<in>s. \\<forall>b\\<in>s. \\<forall> x. a \\<le> x \\<and> x \\<le> b \\<longrightarrow> x \\<in> s)\"\n  unfolding is_interval_def by auto\n\nlemma is_interval_Int: \"is_interval X \\<Longrightarrow> is_interval Y \\<Longrightarrow> is_interval (X \\<inter> Y)\"\n  unfolding is_interval_def\n  by blast\n\nlemma is_interval_cbox [simp]: \"is_interval (cbox a (b::'a::euclidean_space))\" (is ?th1)\n  and is_interval_box [simp]: \"is_interval (box a b)\" (is ?th2)\n  unfolding is_interval_def mem_box Ball_def atLeastAtMost_iff\n  by (meson order_trans le_less_trans less_le_trans less_trans)+\n\nlemma is_interval_empty [iff]: \"is_interval {}\"\n  unfolding is_interval_def  by simp\n\nlemma is_interval_univ [iff]: \"is_interval UNIV\"\n  unfolding is_interval_def  by simp\n\nlemma mem_is_intervalI:\n  assumes \"is_interval S\"\n    and \"a \\<in> S\" \"b \\<in> S\"\n    and \"\\<And>i. i \\<in> Basis \\<Longrightarrow> a \\<bullet> i \\<le> x \\<bullet> i \\<and> x \\<bullet> i \\<le> b \\<bullet> i \\<or> b \\<bullet> i \\<le> x \\<bullet> i \\<and> x \\<bullet> i \\<le> a \\<bullet> i\"\n  shows \"x \\<in> S\"\n  using assms is_interval_def by force\n\nlemma interval_subst:\n  fixes S::\"'a::euclidean_space set\"\n  assumes \"is_interval S\"\n    and \"x \\<in> S\" \"y j \\<in> S\"\n    and \"j \\<in> Basis\"\n  shows \"(\\<Sum>i\\<in>Basis. (if i = j then y i \\<bullet> i else x \\<bullet> i) *\\<^sub>R i) \\<in> S\"\n  by (rule mem_is_intervalI[OF assms(1,2)]) (auto simp: assms)\n\nlemma mem_box_componentwiseI:\n  fixes S::\"'a::euclidean_space set\"\n  assumes \"is_interval S\"\n  assumes \"\\<And>i. i \\<in> Basis \\<Longrightarrow> x \\<bullet> i \\<in> ((\\<lambda>x. x \\<bullet> i) ` S)\"\n  shows \"x \\<in> S\"\nproof -\n  from assms have \"\\<forall>i \\<in> Basis. \\<exists>s \\<in> S. x \\<bullet> i = s \\<bullet> i\"\n    by auto\n  with finite_Basis obtain s and bs::\"'a list\"\n    where s: \"\\<And>i. i \\<in> Basis \\<Longrightarrow> x \\<bullet> i = s i \\<bullet> i\" \"\\<And>i. i \\<in> Basis \\<Longrightarrow> s i \\<in> S\"\n      and bs: \"set bs = Basis\" \"distinct bs\"\n    by (metis finite_distinct_list)\n  from nonempty_Basis s obtain j where j: \"j \\<in> Basis\" \"s j \\<in> S\"\n    by blast\n  define y where\n    \"y = rec_list (s j) (\\<lambda>j _ Y. (\\<Sum>i\\<in>Basis. (if i = j then s i \\<bullet> i else Y \\<bullet> i) *\\<^sub>R i))\"\n  have \"x = (\\<Sum>i\\<in>Basis. (if i \\<in> set bs then s i \\<bullet> i else s j \\<bullet> i) *\\<^sub>R i)\"\n    using bs by (auto simp: s(1)[symmetric] euclidean_representation)\n  also have [symmetric]: \"y bs = \\<dots>\"\n    using bs(2) bs(1)[THEN equalityD1]\n    by (induct bs) (auto simp: y_def euclidean_representation intro!: euclidean_eqI[where 'a='a])\n  also have \"y bs \\<in> S\"\n    using bs(1)[THEN equalityD1]\n  proof (induction bs)\n    case Nil\n    then show ?case\n      by (simp add: j y_def)\n  next\n    case (Cons a bs)\n    then show ?case\n      using interval_subst[OF assms(1)] s by (simp add: y_def)\n  qed\n  finally show ?thesis .\nqed\n\nlemma cbox01_nonempty [simp]: \"cbox 0 One \\<noteq> {}\"\n  by (simp add: box_ne_empty inner_Basis inner_sum_left sum_nonneg)\n\nlemma box01_nonempty [simp]: \"box 0 One \\<noteq> {}\"\n  by (simp add: box_ne_empty inner_Basis inner_sum_left)\n\nlemma empty_as_interval: \"{} = cbox One (0::'a::euclidean_space)\"\n  using nonempty_Basis box01_nonempty box_eq_empty(1) box_ne_empty(1) by blast\n\nlemma interval_subset_is_interval:\n  assumes \"is_interval S\"\n  shows \"cbox a b \\<subseteq> S \\<longleftrightarrow> cbox a b = {} \\<or> a \\<in> S \\<and> b \\<in> S\" (is \"?lhs = ?rhs\")\nproof\n  assume ?lhs\n  then show ?rhs  using box_ne_empty(1) mem_box(2) by fastforce\nnext\n  assume ?rhs\n  have \"cbox a b \\<subseteq> S\" if \"a \\<in> S\" \"b \\<in> S\"\n    using assms that \n    by (force simp: mem_box intro: mem_is_intervalI)\n  with \\<open>?rhs\\<close> show ?lhs\n    by blast\nqed\n\nlemma is_real_interval_union:\n  \"is_interval (X \\<union> Y)\"\n  if X: \"is_interval X\" and Y: \"is_interval Y\" and I: \"(X \\<noteq> {} \\<Longrightarrow> Y \\<noteq> {} \\<Longrightarrow> X \\<inter> Y \\<noteq> {})\"\n  for X Y::\"real set\"\nproof -\n  consider \"X \\<noteq> {}\" \"Y \\<noteq> {}\" | \"X = {}\" | \"Y = {}\" by blast\n  then show ?thesis\n  proof cases\n    case 1\n    then obtain r where \"r \\<in> X \\<or> X \\<inter> Y = {}\" \"r \\<in> Y \\<or> X \\<inter> Y = {}\"\n      by blast\n    then show ?thesis\n      using I 1 X Y unfolding is_interval_1\n      by (metis (full_types) Un_iff le_cases)\n  qed (use that in auto)\nqed\n\nlemma is_interval_translationI:\n  assumes \"is_interval X\"\n  shows \"is_interval ((+) x ` X)\"\n  unfolding is_interval_def\nproof safe\n  fix b d e\n  assume \"b \\<in> X\" \"d \\<in> X\"\n    \"\\<forall>i\\<in>Basis. (x + b) \\<bullet> i \\<le> e \\<bullet> i \\<and> e \\<bullet> i \\<le> (x + d) \\<bullet> i \\<or>\n       (x + d) \\<bullet> i \\<le> e \\<bullet> i \\<and> e \\<bullet> i \\<le> (x + b) \\<bullet> i\"\n  hence \"e - x \\<in> X\"\n    by (intro mem_is_intervalI[OF assms \\<open>b \\<in> X\\<close> \\<open>d \\<in> X\\<close>, of \"e - x\"])\n      (auto simp: algebra_simps)\n  thus \"e \\<in> (+) x ` X\" by force\nqed\n\nlemma is_interval_uminusI:\n  assumes \"is_interval X\"\n  shows \"is_interval (uminus ` X)\"\n  unfolding is_interval_def\nproof safe\n  fix b d e\n  assume \"b \\<in> X\" \"d \\<in> X\"\n    \"\\<forall>i\\<in>Basis. (- b) \\<bullet> i \\<le> e \\<bullet> i \\<and> e \\<bullet> i \\<le> (- d) \\<bullet> i \\<or>\n       (- d) \\<bullet> i \\<le> e \\<bullet> i \\<and> e \\<bullet> i \\<le> (- b) \\<bullet> i\"\n  hence \"- e \\<in> X\"\n    by (smt (verit, ccfv_threshold) assms inner_minus_left mem_is_intervalI)\n  thus \"e \\<in> uminus ` X\" by force\nqed\n\nlemma is_interval_uminus[simp]: \"is_interval (uminus ` x) = is_interval x\"\n  using is_interval_uminusI[of x] is_interval_uminusI[of \"uminus ` x\"]\n  by (auto simp: image_image)\n\nlemma is_interval_neg_translationI:\n  assumes \"is_interval X\"\n  shows \"is_interval ((-) x ` X)\"\nproof -\n  have \"(-) x ` X = (+) x ` uminus ` X\"\n    by (force simp: algebra_simps)\n  also have \"is_interval \\<dots>\"\n    by (metis is_interval_uminusI is_interval_translationI assms)\n  finally show ?thesis .\nqed\n\nlemma is_interval_translation[simp]:\n  \"is_interval ((+) x ` X) = is_interval X\"\n  using is_interval_neg_translationI[of \"(+) x ` X\" x]\n  by (auto intro!: is_interval_translationI simp: image_image)\n\nlemma is_interval_minus_translation[simp]:\n  shows \"is_interval ((-) x ` X) = is_interval X\"\nproof -\n  have \"(-) x ` X = (+) x ` uminus ` X\"\n    by (force simp: algebra_simps)\n  also have \"is_interval \\<dots> = is_interval X\"\n    by simp\n  finally show ?thesis .\nqed\n\nlemma is_interval_minus_translation'[simp]:\n  shows \"is_interval ((\\<lambda>x. x - c) ` X) = is_interval X\"\n  using is_interval_translation[of \"-c\" X]\n  by (metis image_cong uminus_add_conv_diff)\n\nlemma is_interval_cball_1[intro, simp]: \"is_interval (cball a b)\" for a b::real\n  by (simp add: cball_eq_atLeastAtMost is_interval_def)\n\nlemma is_interval_ball_real: \"is_interval (ball a b)\" for a b::real\n  by (simp add: ball_eq_greaterThanLessThan is_interval_def)\n\n\nsubsection\\<^marker>\\<open>tag unimportant\\<close> \\<open>Bounded Projections\\<close>\n\nlemma bounded_inner_imp_bdd_above:\n  assumes \"bounded s\"\n    shows \"bdd_above ((\\<lambda>x. x \\<bullet> a) ` s)\"\nby (simp add: assms bounded_imp_bdd_above bounded_linear_image bounded_linear_inner_left)\n\nlemma bounded_inner_imp_bdd_below:\n  assumes \"bounded s\"\n    shows \"bdd_below ((\\<lambda>x. x \\<bullet> a) ` s)\"\nby (simp add: assms bounded_imp_bdd_below bounded_linear_image bounded_linear_inner_left)\n\n\nsubsection\\<^marker>\\<open>tag unimportant\\<close> \\<open>Structural rules for pointwise continuity\\<close>\n\nlemma continuous_infnorm[continuous_intros]:\n  \"continuous F f \\<Longrightarrow> continuous F (\\<lambda>x. infnorm (f x))\"\n  unfolding continuous_def by (rule tendsto_infnorm)\n\nlemma continuous_inner[continuous_intros]:\n  assumes \"continuous F f\"\n    and \"continuous F g\"\n  shows \"continuous F (\\<lambda>x. inner (f x) (g x))\"\n  using assms unfolding continuous_def by (rule tendsto_inner)\n\n\nsubsection\\<^marker>\\<open>tag unimportant\\<close> \\<open>Structural rules for setwise continuity\\<close>\n\nlemma continuous_on_infnorm[continuous_intros]:\n  \"continuous_on s f \\<Longrightarrow> continuous_on s (\\<lambda>x. infnorm (f x))\"\n  unfolding continuous_on by (fast intro: tendsto_infnorm)\n\nlemma continuous_on_inner[continuous_intros]:\n  fixes g :: \"'a::topological_space \\<Rightarrow> 'b::real_inner\"\n  assumes \"continuous_on s f\"\n    and \"continuous_on s g\"\n  shows \"continuous_on s (\\<lambda>x. inner (f x) (g x))\"\n  using bounded_bilinear_inner assms\n  by (rule bounded_bilinear.continuous_on)\n\n\nsubsection\\<^marker>\\<open>tag unimportant\\<close> \\<open>Openness of halfspaces.\\<close>\n\nlemma open_halfspace_lt: \"open {x. inner a x < b}\"\n  by (simp add: open_Collect_less continuous_on_inner)\n\nlemma open_halfspace_gt: \"open {x. inner a x > b}\"\n  by (simp add: open_Collect_less continuous_on_inner)\n\nlemma open_halfspace_component_lt: \"open {x::'a::euclidean_space. x\\<bullet>i < a}\"\n  by (simp add: open_Collect_less continuous_on_inner)\n\nlemma open_halfspace_component_gt: \"open {x::'a::euclidean_space. x\\<bullet>i > a}\"\n  by (simp add: open_Collect_less continuous_on_inner)\n\nlemma eucl_less_eq_halfspaces:\n  fixes a :: \"'a::euclidean_space\"\n  shows \"{x. x <e a} = (\\<Inter>i\\<in>Basis. {x. x \\<bullet> i < a \\<bullet> i})\"\n        \"{x. a <e x} = (\\<Inter>i\\<in>Basis. {x. a \\<bullet> i < x \\<bullet> i})\"\n  by (auto simp: eucl_less_def)\n\nlemma open_Collect_eucl_less[simp, intro]:\n  fixes a :: \"'a::euclidean_space\"\n  shows \"open {x. x <e a}\" \"open {x. a <e x}\"\n  by (auto simp: eucl_less_eq_halfspaces open_halfspace_component_lt open_halfspace_component_gt)\n\nsubsection\\<^marker>\\<open>tag unimportant\\<close> \\<open>Closure and Interior of halfspaces and hyperplanes\\<close>\n\nlemma continuous_at_inner: \"continuous (at x) (inner a)\"\n  unfolding continuous_at by (intro tendsto_intros)\n\nlemma closed_halfspace_le: \"closed {x. inner a x \\<le> b}\"\n  by (simp add: closed_Collect_le continuous_on_inner)\n\nlemma closed_halfspace_ge: \"closed {x. inner a x \\<ge> b}\"\n  by (simp add: closed_Collect_le continuous_on_inner)\n\nlemma closed_hyperplane: \"closed {x. inner a x = b}\"\n  by (simp add: closed_Collect_eq continuous_on_inner)\n\nlemma closed_halfspace_component_le: \"closed {x::'a::euclidean_space. x\\<bullet>i \\<le> a}\"\n  by (simp add: closed_Collect_le continuous_on_inner)\n\nlemma closed_halfspace_component_ge: \"closed {x::'a::euclidean_space. x\\<bullet>i \\<ge> a}\"\n  by (simp add: closed_Collect_le continuous_on_inner)\n\nlemma closed_interval_left:\n  fixes b :: \"'a::euclidean_space\"\n  shows \"closed {x::'a. \\<forall>i\\<in>Basis. x\\<bullet>i \\<le> b\\<bullet>i}\"\n  by (simp add: Collect_ball_eq closed_INT closed_Collect_le continuous_on_inner)\n\nlemma closed_interval_right:\n  fixes a :: \"'a::euclidean_space\"\n  shows \"closed {x::'a. \\<forall>i\\<in>Basis. a\\<bullet>i \\<le> x\\<bullet>i}\"\n  by (simp add: Collect_ball_eq closed_INT closed_Collect_le continuous_on_inner)\n\nlemma interior_halfspace_le [simp]:\n  assumes \"a \\<noteq> 0\"\n    shows \"interior {x. a \\<bullet> x \\<le> b} = {x. a \\<bullet> x < b}\"\nproof -\n  have *: \"a \\<bullet> x < b\" if x: \"x \\<in> S\" and S: \"S \\<subseteq> {x. a \\<bullet> x \\<le> b}\" and \"open S\" for S x\n  proof -\n    obtain e where \"e>0\" and e: \"cball x e \\<subseteq> S\"\n      using \\<open>open S\\<close> open_contains_cball x by blast\n    then have \"x + (e / norm a) *\\<^sub>R a \\<in> cball x e\"\n      by (simp add: dist_norm)\n    then have \"x + (e / norm a) *\\<^sub>R a \\<in> S\"\n      using e by blast\n    then have \"x + (e / norm a) *\\<^sub>R a \\<in> {x. a \\<bullet> x \\<le> b}\"\n      using S by blast\n    moreover have \"e * (a \\<bullet> a) / norm a > 0\"\n      by (simp add: \\<open>0 < e\\<close> assms)\n    ultimately show ?thesis\n      by (simp add: algebra_simps)\n  qed\n  show ?thesis\n    by (rule interior_unique) (auto simp: open_halfspace_lt *)\nqed\n\nlemma interior_halfspace_ge [simp]:\n   \"a \\<noteq> 0 \\<Longrightarrow> interior {x. a \\<bullet> x \\<ge> b} = {x. a \\<bullet> x > b}\"\nusing interior_halfspace_le [of \"-a\" \"-b\"] by simp\n\nlemma closure_halfspace_lt [simp]:\n  assumes \"a \\<noteq> 0\"\n    shows \"closure {x. a \\<bullet> x < b} = {x. a \\<bullet> x \\<le> b}\"\nproof -\n  have [simp]: \"-{x. a \\<bullet> x < b} = {x. a \\<bullet> x \\<ge> b}\"\n    by force\n  then show ?thesis\n    using interior_halfspace_ge [of a b] assms\n    by (force simp: closure_interior)\nqed\n\nlemma closure_halfspace_gt [simp]:\n   \"a \\<noteq> 0 \\<Longrightarrow> closure {x. a \\<bullet> x > b} = {x. a \\<bullet> x \\<ge> b}\"\nusing closure_halfspace_lt [of \"-a\" \"-b\"] by simp\n\nlemma interior_hyperplane [simp]:\n  assumes \"a \\<noteq> 0\"\n    shows \"interior {x. a \\<bullet> x = b} = {}\"\nproof -\n  have [simp]: \"{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 (auto simp: assms)\nqed\n\nlemma frontier_halfspace_le:\n  assumes \"a \\<noteq> 0 \\<or> b \\<noteq> 0\"\n    shows \"frontier {x. a \\<bullet> x \\<le> b} = {x. a \\<bullet> x = b}\"\nproof (cases \"a = 0\")\n  case True with assms show ?thesis by simp\nnext\n  case False then show ?thesis\n    by (force simp: frontier_def closed_halfspace_le)\nqed\n\nlemma frontier_halfspace_ge:\n  assumes \"a \\<noteq> 0 \\<or> b \\<noteq> 0\"\n    shows \"frontier {x. a \\<bullet> x \\<ge> b} = {x. a \\<bullet> x = b}\"\nproof (cases \"a = 0\")\n  case True with assms show ?thesis by simp\nnext\n  case False then show ?thesis\n    by (force simp: frontier_def closed_halfspace_ge)\nqed\n\nlemma frontier_halfspace_lt:\n  assumes \"a \\<noteq> 0 \\<or> b \\<noteq> 0\"\n    shows \"frontier {x. a \\<bullet> x < b} = {x. a \\<bullet> x = b}\"\nproof (cases \"a = 0\")\n  case True with assms show ?thesis by simp\nnext\n  case False then show ?thesis\n    by (force simp: frontier_def interior_open open_halfspace_lt)\nqed\n\nlemma frontier_halfspace_gt:\n  assumes \"a \\<noteq> 0 \\<or> b \\<noteq> 0\"\n    shows \"frontier {x. a \\<bullet> x > b} = {x. a \\<bullet> x = b}\"\nproof (cases \"a = 0\")\n  case True with assms show ?thesis by simp\nnext\n  case False then show ?thesis\n    by (force simp: frontier_def interior_open open_halfspace_gt)\nqed\n\nsubsection\\<^marker>\\<open>tag unimportant\\<close>\\<open>Some more convenient intermediate-value theorem formulations\\<close>\n\nlemma connected_ivt_hyperplane:\n  assumes \"connected S\" and xy: \"x \\<in> S\" \"y \\<in> S\" and b: \"inner a x \\<le> b\" \"b \\<le> inner a y\"\n  shows \"\\<exists>z \\<in> S. inner a z = b\"\nproof (rule ccontr)\n  assume as:\"\\<not> (\\<exists>z\\<in>S. inner a z = b)\"\n  let ?A = \"{x. inner a x < b}\"\n  let ?B = \"{x. inner a x > b}\"\n  have \"open ?A\" \"open ?B\"\n    using open_halfspace_lt and open_halfspace_gt by auto\n  moreover have \"?A \\<inter> ?B = {}\" by auto\n  moreover have \"S \\<subseteq> ?A \\<union> ?B\" using as by auto\n  ultimately show False\n    using \\<open>connected S\\<close> unfolding connected_def\n    by (smt (verit, del_insts) as b disjoint_iff empty_iff mem_Collect_eq xy)\nqed\n\nlemma connected_ivt_component:\n  fixes x::\"'a::euclidean_space\"\n  shows \"connected S \\<Longrightarrow> x \\<in> S \\<Longrightarrow> y \\<in> S \\<Longrightarrow> x\\<bullet>k \\<le> a \\<Longrightarrow> a \\<le> y\\<bullet>k \\<Longrightarrow> (\\<exists>z\\<in>S.  z\\<bullet>k = a)\"\n  using connected_ivt_hyperplane[of S x y \"k::'a\" a]\n  by (auto simp: inner_commute)\n\n\nsubsection \\<open>Limit Component Bounds\\<close>\n\nlemma Lim_component_le:\n  fixes f :: \"'a \\<Rightarrow> 'b::euclidean_space\"\n  assumes \"(f \\<longlongrightarrow> l) net\"\n    and \"\\<not> (trivial_limit net)\"\n    and \"eventually (\\<lambda>x. f(x)\\<bullet>i \\<le> b) net\"\n  shows \"l\\<bullet>i \\<le> b\"\n  by (rule tendsto_le[OF assms(2) tendsto_const tendsto_inner[OF assms(1) tendsto_const] assms(3)])\n\nlemma Lim_component_ge:\n  fixes f :: \"'a \\<Rightarrow> 'b::euclidean_space\"\n  assumes \"(f \\<longlongrightarrow> l) net\"\n    and \"\\<not> (trivial_limit net)\"\n    and \"eventually (\\<lambda>x. b \\<le> (f x)\\<bullet>i) net\"\n  shows \"b \\<le> l\\<bullet>i\"\n  by (rule tendsto_le[OF assms(2) tendsto_inner[OF assms(1) tendsto_const] tendsto_const assms(3)])\n\nlemma Lim_component_eq:\n  fixes f :: \"'a \\<Rightarrow> 'b::euclidean_space\"\n  assumes net: \"(f \\<longlongrightarrow> l) net\" \"\\<not> trivial_limit net\"\n    and ev:\"eventually (\\<lambda>x. f(x)\\<bullet>i = b) net\"\n  shows \"l\\<bullet>i = b\"\n  using ev[unfolded order_eq_iff eventually_conj_iff]\n  using Lim_component_ge[OF net, of b i]\n  using Lim_component_le[OF net, of i b]\n  by auto\n\nlemma open_box[intro]: \"open (box a b)\"\nproof -\n  have \"open (\\<Inter>i\\<in>Basis. ((\\<bullet>) i) -` {a \\<bullet> i <..< b \\<bullet> i})\"\n    by (auto intro!: continuous_open_vimage continuous_inner continuous_ident continuous_const)\n  also have \"(\\<Inter>i\\<in>Basis. ((\\<bullet>) i) -` {a \\<bullet> i <..< b \\<bullet> i}) = box a b\"\n    by (auto simp: box_def inner_commute)\n  finally show ?thesis .\nqed\n\nlemma closed_cbox[intro]:\n  fixes a b :: \"'a::euclidean_space\"\n  shows \"closed (cbox a b)\"\nproof -\n  have \"closed (\\<Inter>i\\<in>Basis. (\\<lambda>x. x\\<bullet>i) -` {a\\<bullet>i .. b\\<bullet>i})\"\n    by (intro closed_INT ballI continuous_closed_vimage allI\n      linear_continuous_at closed_real_atLeastAtMost finite_Basis bounded_linear_inner_left)\n  also have \"(\\<Inter>i\\<in>Basis. (\\<lambda>x. x\\<bullet>i) -` {a\\<bullet>i .. b\\<bullet>i}) = cbox a b\"\n    by (auto simp: cbox_def)\n  finally show \"closed (cbox a b)\" .\nqed\n\nlemma interior_cbox [simp]:\n  fixes a b :: \"'a::euclidean_space\"\n  shows \"interior (cbox a b) = box a b\" (is \"?L = ?R\")\nproof(rule subset_antisym)\n  show \"?R \\<subseteq> ?L\"\n    using box_subset_cbox open_box\n    by (rule interior_maximal)\n  {\n    fix x\n    assume \"x \\<in> interior (cbox a b)\"\n    then obtain s where s: \"open s\" \"x \\<in> s\" \"s \\<subseteq> cbox a b\" ..\n    then obtain e where \"e>0\" and e:\"\\<forall>x'. dist x' x < e \\<longrightarrow> x' \\<in> cbox a b\"\n      unfolding open_dist and subset_eq by auto\n    {\n      fix i :: 'a\n      assume i: \"i \\<in> Basis\"\n      have \"dist (x - (e / 2) *\\<^sub>R i) x < e\"\n        and \"dist (x + (e / 2) *\\<^sub>R i) x < e\"\n         using norm_Basis[OF i] \\<open>e>0\\<close> by (auto simp: dist_norm)\n      then have \"a \\<bullet> i \\<le> (x - (e / 2) *\\<^sub>R i) \\<bullet> i\" and \"(x + (e / 2) *\\<^sub>R i) \\<bullet> i \\<le> b \\<bullet> i\"\n        using e[THEN spec[where x=\"x - (e/2) *\\<^sub>R i\"]]\n          and e[THEN spec[where x=\"x + (e/2) *\\<^sub>R i\"]]\n        unfolding mem_box using i by blast+\n      then have \"a \\<bullet> i < x \\<bullet> i\" and \"x \\<bullet> i < b \\<bullet> i\"\n        using \\<open>e>0\\<close> i\n        by (auto simp: inner_diff_left inner_Basis inner_add_left)\n    }\n    then have \"x \\<in> box a b\"\n      unfolding mem_box by auto\n  }\n  then show \"?L \\<subseteq> ?R\" ..\nqed\n\nlemma bounded_cbox [simp]:\n  fixes a :: \"'a::euclidean_space\"\n  shows \"bounded (cbox a b)\"\nproof -\n  let ?b = \"\\<Sum>i\\<in>Basis. \\<bar>a\\<bullet>i\\<bar> + \\<bar>b\\<bullet>i\\<bar>\"\n  {\n    fix x :: \"'a\"\n    assume \"\\<And>i. i\\<in>Basis \\<Longrightarrow> a \\<bullet> i \\<le> x \\<bullet> i \\<and> x \\<bullet> i \\<le> b \\<bullet> i\"\n    then have \"(\\<Sum>i\\<in>Basis. \\<bar>x \\<bullet> i\\<bar>) \\<le> ?b\"\n      by (force simp: intro!: sum_mono)\n    then have \"norm x \\<le> ?b\"\n      using norm_le_l1[of x] by auto\n  }\n  then show ?thesis\n    unfolding cbox_def bounded_iff by force\nqed\n\nlemma bounded_box [simp]:\n  fixes a :: \"'a::euclidean_space\"\n  shows \"bounded (box a b)\"\n  by (metis bounded_cbox bounded_interior interior_cbox)\n\nlemma not_interval_UNIV [simp]:\n  fixes a :: \"'a::euclidean_space\"\n  shows \"cbox a b \\<noteq> UNIV\" \"box a b \\<noteq> UNIV\"\n  using bounded_box[of a b] bounded_cbox[of a b] by force+\n\nlemma not_interval_UNIV2 [simp]:\n  fixes a :: \"'a::euclidean_space\"\n  shows \"UNIV \\<noteq> cbox a b\" \"UNIV \\<noteq> box a b\"\n  using bounded_box[of a b] bounded_cbox[of a b] by force+\n\nlemma box_midpoint:\n  fixes a :: \"'a::euclidean_space\"\n  assumes \"box a b \\<noteq> {}\"\n  shows \"((1/2) *\\<^sub>R (a + b)) \\<in> box a b\"\nproof -\n  have \"a \\<bullet> i < ((1 / 2) *\\<^sub>R (a + b)) \\<bullet> i \\<and> ((1 / 2) *\\<^sub>R (a + b)) \\<bullet> i < b \\<bullet> i\" if \"i \\<in> Basis\" for i\n    using assms that by (auto simp: inner_add_left box_ne_empty)\n  then show ?thesis unfolding mem_box by auto\nqed\n\nlemma open_cbox_convex:\n  fixes x :: \"'a::euclidean_space\"\n  assumes x: \"x \\<in> box a b\"\n    and y: \"y \\<in> cbox a b\"\n    and e: \"0 < e\" \"e \\<le> 1\"\n  shows \"(e *\\<^sub>R x + (1 - e) *\\<^sub>R y) \\<in> box a b\"\nproof -\n  {\n    fix i :: 'a\n    assume i: \"i \\<in> Basis\"\n    have \"a \\<bullet> i = e * (a \\<bullet> i) + (1 - e) * (a \\<bullet> i)\"\n      unfolding left_diff_distrib by simp\n    also have \"\\<dots> < e * (x \\<bullet> i) + (1 - e) * (y \\<bullet> i)\"\n      by (smt (verit, best) e i mem_box mult_le_cancel_left_pos mult_left_mono x y)\n    finally have \"a \\<bullet> i < (e *\\<^sub>R x + (1 - e) *\\<^sub>R y) \\<bullet> i\"\n      unfolding inner_simps by auto\n    moreover\n    {\n      have \"b \\<bullet> i = e * (b\\<bullet>i) + (1 - e) * (b\\<bullet>i)\"\n        unfolding left_diff_distrib by simp\n      also have \"\\<dots> > e * (x \\<bullet> i) + (1 - e) * (y \\<bullet> i)\"\n        by (smt (verit, best) e i mem_box mult_le_cancel_left_pos mult_left_mono x y)\n      finally have \"(e *\\<^sub>R x + (1 - e) *\\<^sub>R y) \\<bullet> i < b \\<bullet> i\"\n        unfolding inner_simps by auto\n    }\n    ultimately have \"a \\<bullet> i < (e *\\<^sub>R x + (1 - e) *\\<^sub>R y) \\<bullet> i \\<and> (e *\\<^sub>R x + (1 - e) *\\<^sub>R y) \\<bullet> i < b \\<bullet> i\"\n      by auto\n  }\n  then show ?thesis\n    unfolding mem_box by auto\nqed\n\nlemma closure_cbox [simp]: \"closure (cbox a b) = cbox a b\"\n  by (simp add: closed_cbox)\n\nlemma closure_box [simp]:\n  fixes a :: \"'a::euclidean_space\"\n   assumes \"box a b \\<noteq> {}\"\n  shows \"closure (box a b) = cbox a b\"\nproof -\n  have ab: \"a <e b\"\n    using assms by (simp add: eucl_less_def box_ne_empty)\n  let ?c = \"(1 / 2) *\\<^sub>R (a + b)\"\n  {\n    fix x\n    assume as: \"x \\<in> cbox a b\"\n    define f where [abs_def]: \"f n = x + (inverse (real n + 1)) *\\<^sub>R (?c - x)\" for n\n    {\n      fix n\n      assume fn: \"f n <e b \\<longrightarrow> a <e f n \\<longrightarrow> f n = x\" and xc: \"x \\<noteq> ?c\"\n      have *: \"0 < inverse (real n + 1)\" \"inverse (real n + 1) \\<le> 1\"\n        unfolding inverse_le_1_iff by auto\n      have \"(inverse (real n + 1)) *\\<^sub>R ((1 / 2) *\\<^sub>R (a + b)) + (1 - inverse (real n + 1)) *\\<^sub>R x =\n        x + (inverse (real n + 1)) *\\<^sub>R (((1 / 2) *\\<^sub>R (a + b)) - x)\"\n        by (auto simp: algebra_simps)\n      then have \"f n <e b\" and \"a <e f n\"\n        using open_cbox_convex[OF box_midpoint[OF assms] as *]\n        unfolding f_def by (auto simp: box_def eucl_less_def)\n      then have False\n        using fn unfolding f_def using xc by auto\n    }\n    moreover\n    {\n      have \"\\<exists>N::nat. \\<forall>n\\<ge>N. inverse (real n + 1) < \\<epsilon>\" if \"\\<epsilon> > 0\" for \\<epsilon>\n          using reals_Archimedean [of \\<epsilon>] that\n          by (metis inverse_inverse_eq inverse_less_imp_less nat_le_real_less order_less_trans \n                  reals_Archimedean2)\n      then have \"(\\<lambda>n. inverse (real n + 1)) \\<longlonglongrightarrow> 0\"\n        unfolding lim_sequentially by(auto simp: dist_norm)\n      then have \"f \\<longlonglongrightarrow> x\"\n        unfolding f_def\n        using tendsto_add[OF tendsto_const, of \"\\<lambda>n. (inverse (real n + 1)) *\\<^sub>R ((1 / 2) *\\<^sub>R (a + b) - x)\" 0 sequentially x]\n        using tendsto_scaleR [OF _ tendsto_const, of \"\\<lambda>n. inverse (real n + 1)\" 0 sequentially \"((1 / 2) *\\<^sub>R (a + b) - x)\"]\n        by auto\n    }\n    ultimately have \"x \\<in> closure (box a b)\"\n      using as box_midpoint[OF assms]\n      unfolding closure_def islimpt_sequential\n      by (cases \"x=?c\") (auto simp: in_box_eucl_less)\n  }\n  then show ?thesis\n    using closure_minimal[OF box_subset_cbox, of a b] by blast\nqed\n\nlemma bounded_subset_box_symmetric:\n  fixes S :: \"('a::euclidean_space) set\"\n  assumes \"bounded S\"\n  obtains a where \"S \\<subseteq> box (-a) a\"\nproof -\n  obtain b where \"b>0\" and b: \"\\<forall>x\\<in>S. norm x \\<le> b\"\n    using assms[unfolded bounded_pos] by auto\n  define a :: 'a where \"a = (\\<Sum>i\\<in>Basis. (b + 1) *\\<^sub>R i)\"\n  have \"(-a)\\<bullet>i < x\\<bullet>i\" and \"x\\<bullet>i < a\\<bullet>i\" if \"x \\<in> S\" and i: \"i \\<in> Basis\" for x i\n    using b Basis_le_norm[OF i, of x] that by (auto simp: a_def)\n  then have \"S \\<subseteq> box (-a) a\"\n    by (auto simp: simp add: box_def)\n  then show ?thesis ..\nqed\n\nlemma bounded_subset_cbox_symmetric:\n  fixes S :: \"('a::euclidean_space) set\"\n  assumes \"bounded S\"\n  obtains a where \"S \\<subseteq> cbox (-a) a\"\n  by (meson assms bounded_subset_box_symmetric box_subset_cbox order.trans)\n\nlemma frontier_cbox:\n  fixes a b :: \"'a::euclidean_space\"\n  shows \"frontier (cbox a b) = cbox a b - box a b\"\n  unfolding frontier_def unfolding interior_cbox and closure_closed[OF closed_cbox] ..\n\nlemma frontier_box:\n  fixes a b :: \"'a::euclidean_space\"\n  shows \"frontier (box a b) = (if box a b = {} then {} else cbox a b - box a b)\"\n  by (simp add: frontier_def interior_open open_box)\n\nlemma Int_interval_mixed_eq_empty:\n  fixes a :: \"'a::euclidean_space\"\n   assumes \"box c d \\<noteq> {}\"\n  shows \"box a b \\<inter> cbox c d = {} \\<longleftrightarrow> box a b \\<inter> box c d = {}\"\n  unfolding closure_box[OF assms, symmetric]\n  unfolding open_Int_closure_eq_empty[OF open_box] ..\n\nsubsection \\<open>Class Instances\\<close>\n\nlemma compact_lemma:\n  fixes f :: \"nat \\<Rightarrow> 'a::euclidean_space\"\n  assumes \"bounded (range f)\"\n  shows \"\\<forall>d\\<subseteq>Basis. \\<exists>l::'a. \\<exists> r.\n    strict_mono r \\<and> (\\<forall>e>0. eventually (\\<lambda>n. \\<forall>i\\<in>d. dist (f (r n) \\<bullet> i) (l \\<bullet> i) < e) sequentially)\"\n  by (rule compact_lemma_general[where unproj=\"\\<lambda>e. \\<Sum>i\\<in>Basis. e i *\\<^sub>R i\"])\n     (auto intro!: assms bounded_linear_inner_left bounded_linear_image\n       simp: euclidean_representation)\n\ninstance\\<^marker>\\<open>tag important\\<close> euclidean_space \\<subseteq> heine_borel\nproof\n  fix f :: \"nat \\<Rightarrow> 'a\"\n  assume f: \"bounded (range f)\"\n  then obtain l::'a and r where r: \"strict_mono r\"\n    and l: \"\\<forall>e>0. eventually (\\<lambda>n. \\<forall>i\\<in>Basis. dist (f (r n) \\<bullet> i) (l \\<bullet> i) < e) sequentially\"\n    using compact_lemma [OF f] by blast\n  {\n    fix e::real\n    assume \"e > 0\"\n    hence \"e / real_of_nat DIM('a) > 0\" by (simp)\n    with l have \"eventually (\\<lambda>n. \\<forall>i\\<in>Basis. dist (f (r n) \\<bullet> i) (l \\<bullet> i) < e / (real_of_nat DIM('a))) sequentially\"\n      by simp\n    moreover\n    { fix n\n      assume n: \"\\<forall>i\\<in>Basis. dist (f (r n) \\<bullet> i) (l \\<bullet> i) < e / (real_of_nat DIM('a))\"\n      have \"dist (f (r n)) l \\<le> (\\<Sum>i\\<in>Basis. dist (f (r n) \\<bullet> i) (l \\<bullet> i))\"\n        using L2_set_le_sum [OF zero_le_dist] by (subst euclidean_dist_l2)\n      also have \"\\<dots> < (\\<Sum>i\\<in>(Basis::'a set). e / (real_of_nat DIM('a)))\"\n        by (meson eucl.finite_Basis n nonempty_Basis sum_strict_mono)\n      finally have \"dist (f (r n)) l < e\"\n        by auto\n    }\n    ultimately have \"\\<forall>\\<^sub>F n in sequentially. dist (f (r n)) l < e\"\n      by (rule eventually_mono)\n  }\n  then have *: \"(f \\<circ> r) \\<longlonglongrightarrow> l\"\n    unfolding o_def tendsto_iff by simp\n  with r show \"\\<exists>l r. strict_mono r \\<and> (f \\<circ> r) \\<longlonglongrightarrow> l\"\n    by auto\nqed\n\ninstance\\<^marker>\\<open>tag important\\<close> euclidean_space \\<subseteq> banach ..\n\ninstance euclidean_space \\<subseteq> second_countable_topology\nproof\n  define a where \"a f = (\\<Sum>i\\<in>Basis. fst (f i) *\\<^sub>R i)\" for f :: \"'a \\<Rightarrow> real \\<times> real\"\n  then have a: \"\\<And>f. (\\<Sum>i\\<in>Basis. fst (f i) *\\<^sub>R i) = a f\"\n    by simp\n  define b where \"b f = (\\<Sum>i\\<in>Basis. snd (f i) *\\<^sub>R i)\" for f :: \"'a \\<Rightarrow> real \\<times> real\"\n  then have b: \"\\<And>f. (\\<Sum>i\\<in>Basis. snd (f i) *\\<^sub>R i) = b f\"\n    by simp\n  define B where \"B = (\\<lambda>f. box (a f) (b f)) ` (Basis \\<rightarrow>\\<^sub>E (\\<rat> \\<times> \\<rat>))\"\n\n  have \"Ball B open\" by (simp add: B_def open_box)\n  moreover have \"(\\<forall>A. open A \\<longrightarrow> (\\<exists>B'\\<subseteq>B. \\<Union>B' = A))\"\n  proof safe\n    fix A::\"'a set\"\n    assume \"open A\"\n    show \"\\<exists>B'\\<subseteq>B. \\<Union>B' = A\"\n      using open_UNION_box[OF \\<open>open A\\<close>]\n      by (smt (verit, ccfv_threshold) B_def a b image_iff mem_Collect_eq subsetI)\n  qed\n  ultimately\n  have \"topological_basis B\"\n    unfolding topological_basis_def by blast\n  moreover\n  have \"countable B\"\n    unfolding B_def\n    by (intro countable_image countable_PiE finite_Basis countable_SIGMA countable_rat)\n  ultimately show \"\\<exists>B::'a set set. countable B \\<and> open = generate_topology B\"\n    by (blast intro: topological_basis_imp_subbasis)\nqed\n\ninstance euclidean_space \\<subseteq> polish_space ..\n\n\nsubsection \\<open>Compact Boxes\\<close>\n\nlemma compact_cbox [simp]:\n  fixes a :: \"'a::euclidean_space\"\n  shows \"compact (cbox a b)\"\n  using bounded_closed_imp_seq_compact[of \"cbox a b\"] using bounded_cbox[of a b]\n  by (auto simp: compact_eq_seq_compact_metric)\n\nproposition is_interval_compact:\n   \"is_interval S \\<and> compact S \\<longleftrightarrow> (\\<exists>a b. S = cbox a b)\"   (is \"?lhs = ?rhs\")\nproof (cases \"S = {}\")\n  case True\n  with empty_as_interval show ?thesis by auto\nnext\n  case False\n  show ?thesis\n  proof\n    assume L: ?lhs\n    then have \"is_interval S\" \"compact S\" by auto\n    define a where \"a \\<equiv> \\<Sum>i\\<in>Basis. (INF x\\<in>S. x \\<bullet> i) *\\<^sub>R i\"\n    define b where \"b \\<equiv> \\<Sum>i\\<in>Basis. (SUP x\\<in>S. x \\<bullet> i) *\\<^sub>R i\"\n    have 1: \"\\<And>x i. \\<lbrakk>x \\<in> S; i \\<in> Basis\\<rbrakk> \\<Longrightarrow> (INF x\\<in>S. x \\<bullet> i) \\<le> x \\<bullet> i\"\n      by (simp add: cInf_lower bounded_inner_imp_bdd_below compact_imp_bounded L)\n    have 2: \"\\<And>x i. \\<lbrakk>x \\<in> S; i \\<in> Basis\\<rbrakk> \\<Longrightarrow> x \\<bullet> i \\<le> (SUP x\\<in>S. x \\<bullet> i)\"\n      by (simp add: cSup_upper bounded_inner_imp_bdd_above compact_imp_bounded L)\n    have 3: \"x \\<in> S\" if inf: \"\\<And>i. i \\<in> Basis \\<Longrightarrow> (INF x\\<in>S. x \\<bullet> i) \\<le> x \\<bullet> i\"\n                   and sup: \"\\<And>i. i \\<in> Basis \\<Longrightarrow> x \\<bullet> i \\<le> (SUP x\\<in>S. x \\<bullet> i)\" for x\n    proof (rule mem_box_componentwiseI [OF \\<open>is_interval S\\<close>])\n      fix i::'a\n      assume i: \"i \\<in> Basis\"\n      have cont: \"continuous_on S (\\<lambda>x. x \\<bullet> i)\"\n        by (intro continuous_intros)\n      obtain a where \"a \\<in> S\" and a: \"\\<And>y. y\\<in>S \\<Longrightarrow> a \\<bullet> i \\<le> y \\<bullet> i\"\n        using continuous_attains_inf [OF \\<open>compact S\\<close> False cont] by blast\n      obtain b where \"b \\<in> S\" and b: \"\\<And>y. y\\<in>S \\<Longrightarrow> y \\<bullet> i \\<le> b \\<bullet> i\"\n        using continuous_attains_sup [OF \\<open>compact S\\<close> False cont] by blast\n      have \"a \\<bullet> i \\<le> (INF x\\<in>S. x \\<bullet> i)\"\n        by (simp add: False a cINF_greatest)\n      also have \"\\<dots> \\<le> x \\<bullet> i\"\n        by (simp add: i inf)\n      finally have ai: \"a \\<bullet> i \\<le> x \\<bullet> i\" .\n      have \"x \\<bullet> i \\<le> (SUP x\\<in>S. x \\<bullet> i)\"\n        by (simp add: i sup)\n      also have \"(SUP x\\<in>S. x \\<bullet> i) \\<le> b \\<bullet> i\"\n        by (simp add: False b cSUP_least)\n      finally have bi: \"x \\<bullet> i \\<le> b \\<bullet> i\" .\n      show \"x \\<bullet> i \\<in> (\\<lambda>x. x \\<bullet> i) ` S\"\n        apply (rule_tac x=\"\\<Sum>j\\<in>Basis. (((\\<bullet>)a)(i := x \\<bullet> j))j *\\<^sub>R j\" in image_eqI)\n        apply (simp add: i)\n        apply (rule mem_is_intervalI [OF \\<open>is_interval S\\<close> \\<open>a \\<in> S\\<close> \\<open>b \\<in> S\\<close>])\n        using i ai bi \n        apply force\n        done\n    qed\n    have \"S = cbox a b\"\n      by (auto simp: a_def b_def mem_box intro: 1 2 3)\n    then show ?rhs\n      by blast\n  next\n    assume R: ?rhs\n    then show ?lhs\n      using compact_cbox is_interval_cbox by blast\n  qed\nqed\n\n\nsubsection\\<^marker>\\<open>tag unimportant\\<close>\\<open>Componentwise limits and continuity\\<close>\n\ntext\\<open>But is the premise really necessary? Need to generalise @{thm euclidean_dist_l2}\\<close>\nlemma Euclidean_dist_upper: \"i \\<in> Basis \\<Longrightarrow> dist (x \\<bullet> i) (y \\<bullet> i) \\<le> dist x y\"\n  by (metis (no_types) member_le_L2_set euclidean_dist_l2 finite_Basis)\n\ntext\\<open>But is the premise \\<^term>\\<open>i \\<in> Basis\\<close> really necessary?\\<close>\nlemma open_preimage_inner:\n  assumes \"open S\" \"i \\<in> Basis\"\n    shows \"open {x. x \\<bullet> i \\<in> S}\"\nproof (rule openI, simp)\n  fix x\n  assume x: \"x \\<bullet> i \\<in> S\"\n  with assms obtain e where \"0 < e\" and e: \"ball (x \\<bullet> i) e \\<subseteq> S\"\n    by (auto simp: open_contains_ball_eq)\n  have \"\\<exists>e>0. ball (y \\<bullet> i) e \\<subseteq> S\" if dxy: \"dist x y < e / 2\" for y\n  proof (intro exI conjI)\n    have \"dist (x \\<bullet> i) (y \\<bullet> i) < e / 2\"\n      by (meson \\<open>i \\<in> Basis\\<close> dual_order.trans Euclidean_dist_upper not_le that)\n    then have \"dist (x \\<bullet> i) z < e\" if \"dist (y \\<bullet> i) z < e / 2\" for z\n      by (metis dist_commute dist_triangle_half_l that)\n    then have \"ball (y \\<bullet> i) (e / 2) \\<subseteq> ball (x \\<bullet> i) e\"\n      using mem_ball by blast\n      with e show \"ball (y \\<bullet> i) (e / 2) \\<subseteq> S\"\n        by (metis order_trans)\n  qed (simp add: \\<open>0 < e\\<close>)\n  then show \"\\<exists>e>0. ball x e \\<subseteq> {s. s \\<bullet> i \\<in> S}\"\n    by (metis (no_types, lifting) \\<open>0 < e\\<close> \\<open>open S\\<close> half_gt_zero_iff mem_Collect_eq mem_ball open_contains_ball_eq subsetI)\nqed\n\nproposition tendsto_componentwise_iff:\n  fixes f :: \"_ \\<Rightarrow> 'b::euclidean_space\"\n  shows \"(f \\<longlongrightarrow> l) F \\<longleftrightarrow> (\\<forall>i \\<in> Basis. ((\\<lambda>x. (f x \\<bullet> i)) \\<longlongrightarrow> (l \\<bullet> i)) F)\"\n         (is \"?lhs = ?rhs\")\nproof\n  assume ?lhs\n  then show ?rhs\n    unfolding tendsto_def\n    by (smt (verit) eventually_elim2 mem_Collect_eq open_preimage_inner)\nnext\n  assume R: ?rhs\n  then have \"\\<And>e. e > 0 \\<Longrightarrow> \\<forall>i\\<in>Basis. \\<forall>\\<^sub>F x in F. dist (f x \\<bullet> i) (l \\<bullet> i) < e\"\n    unfolding tendsto_iff by blast\n  then have R': \"\\<And>e. e > 0 \\<Longrightarrow> \\<forall>\\<^sub>F x in F. \\<forall>i\\<in>Basis. dist (f x \\<bullet> i) (l \\<bullet> i) < e\"\n      by (simp add: eventually_ball_finite_distrib [symmetric])\n  show ?lhs\n  unfolding tendsto_iff\n  proof clarify\n    fix e::real\n    assume \"0 < e\"\n    have *: \"L2_set (\\<lambda>i. dist (f x \\<bullet> i) (l \\<bullet> i)) Basis < e\"\n             if \"\\<forall>i\\<in>Basis. dist (f x \\<bullet> i) (l \\<bullet> i) < e / real DIM('b)\" for x\n    proof -\n      have \"L2_set (\\<lambda>i. dist (f x \\<bullet> i) (l \\<bullet> i)) Basis \\<le> sum (\\<lambda>i. dist (f x \\<bullet> i) (l \\<bullet> i)) Basis\"\n        by (simp add: L2_set_le_sum)\n      also have \"... < DIM('b) * (e / real DIM('b))\"\n        by (meson DIM_positive sum_bounded_above_strict that)\n      also have \"... = e\"\n        by (simp add: field_simps)\n      finally show \"L2_set (\\<lambda>i. dist (f x \\<bullet> i) (l \\<bullet> i)) Basis < e\" .\n    qed\n    have \"\\<forall>\\<^sub>F x in F. \\<forall>i\\<in>Basis. dist (f x \\<bullet> i) (l \\<bullet> i) < e / DIM('b)\"\n      by (simp add: R' \\<open>0 < e\\<close>)\n    then show \"\\<forall>\\<^sub>F x in F. dist (f x) l < e\"\n      by eventually_elim (metis (full_types) \"*\" euclidean_dist_l2)\n  qed\nqed\n\n\ncorollary continuous_componentwise:\n   \"continuous F f \\<longleftrightarrow> (\\<forall>i \\<in> Basis. continuous F (\\<lambda>x. (f x \\<bullet> i)))\"\nby (simp add: continuous_def tendsto_componentwise_iff [symmetric])\n\ncorollary continuous_on_componentwise:\n  fixes S :: \"'a :: t2_space set\"\n  shows \"continuous_on S f \\<longleftrightarrow> (\\<forall>i \\<in> Basis. continuous_on S (\\<lambda>x. (f x \\<bullet> i)))\"\n  by (metis continuous_componentwise continuous_on_eq_continuous_within)\n\nlemma linear_componentwise_iff:\n     \"linear f' \\<longleftrightarrow> (\\<forall>i\\<in>Basis. linear (\\<lambda>x. f' x \\<bullet> i))\" (is \"?lhs \\<longleftrightarrow> ?rhs\")\nproof\n  show \"?lhs \\<Longrightarrow> ?rhs\"\n    by (simp add: Real_Vector_Spaces.linear_iff inner_left_distrib)\n  show \"?rhs \\<Longrightarrow> ?lhs\"\n    by (simp add: linear_iff) (metis euclidean_eqI inner_left_distrib inner_scaleR_left)\nqed\n\nlemma bounded_linear_componentwise_iff:\n     \"(bounded_linear f') \\<longleftrightarrow> (\\<forall>i\\<in>Basis. bounded_linear (\\<lambda>x. f' x \\<bullet> i))\"\n     (is \"?lhs = ?rhs\")\nproof\n  assume ?rhs\n  then have \"(\\<forall>i\\<in>Basis. \\<exists>K. \\<forall>x. \\<bar>f' x \\<bullet> i\\<bar> \\<le> norm x * K)\" \"linear f'\"\n    by (auto simp: bounded_linear_def bounded_linear_axioms_def linear_componentwise_iff [symmetric] ball_conj_distrib)\n  then obtain F where F: \"\\<And>i x. i \\<in> Basis \\<Longrightarrow> \\<bar>f' x \\<bullet> i\\<bar> \\<le> norm x * F i\"\n    by metis\n  have \"norm (f' x) \\<le> norm x * sum F Basis\" for x\n  proof -\n    have \"norm (f' x) \\<le> (\\<Sum>i\\<in>Basis. \\<bar>f' x \\<bullet> i\\<bar>)\"\n      by (rule norm_le_l1)\n    also have \"... \\<le> (\\<Sum>i\\<in>Basis. norm x * F i)\"\n      by (metis F sum_mono)\n    also have \"... = norm x * sum F Basis\"\n      by (simp add: sum_distrib_left)\n    finally show ?thesis .\n  qed\n  then show ?lhs\n    by (force simp: bounded_linear_def bounded_linear_axioms_def \\<open>linear f'\\<close>)\nqed (simp add: bounded_linear_inner_left_comp)\n\nsubsection\\<^marker>\\<open>tag unimportant\\<close> \\<open>Continuous Extension\\<close>\n\ndefinition clamp :: \"'a::euclidean_space \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> 'a\" where\n  \"clamp a b x = (if (\\<forall>i\\<in>Basis. a \\<bullet> i \\<le> b \\<bullet> i)\n    then (\\<Sum>i\\<in>Basis. (if x\\<bullet>i < a\\<bullet>i then a\\<bullet>i else if x\\<bullet>i \\<le> b\\<bullet>i then x\\<bullet>i else b\\<bullet>i) *\\<^sub>R i)\n    else a)\"\n\nlemma clamp_in_interval[simp]:\n  assumes \"\\<And>i. i \\<in> Basis \\<Longrightarrow> a \\<bullet> i \\<le> b \\<bullet> i\"\n  shows \"clamp a b x \\<in> cbox a b\"\n  unfolding clamp_def\n  using box_ne_empty(1)[of a b] assms by (auto simp: cbox_def)\n\nlemma clamp_cancel_cbox[simp]:\n  fixes x a b :: \"'a::euclidean_space\"\n  assumes x: \"x \\<in> cbox a b\"\n  shows \"clamp a b x = x\"\n  using assms\n  by (auto simp: clamp_def mem_box intro!: euclidean_eqI[where 'a='a])\n\nlemma clamp_empty_interval:\n  assumes \"i \\<in> Basis\" \"a \\<bullet> i > b \\<bullet> i\"\n  shows \"clamp a b = (\\<lambda>_. a)\"\n  using assms\n  by (force simp: clamp_def[abs_def] split: if_splits intro!: ext)\n\nlemma dist_clamps_le_dist_args:\n  fixes x :: \"'a::euclidean_space\"\n  shows \"dist (clamp a b y) (clamp a b x) \\<le> dist y x\"\nproof cases\n  assume le: \"(\\<forall>i\\<in>Basis. a \\<bullet> i \\<le> b \\<bullet> i)\"\n  then have \"(\\<Sum>i\\<in>Basis. (dist (clamp a b y \\<bullet> i) (clamp a b x \\<bullet> i))\\<^sup>2) \\<le>\n    (\\<Sum>i\\<in>Basis. (dist (y \\<bullet> i) (x \\<bullet> i))\\<^sup>2)\"\n    by (auto intro!: sum_mono simp: clamp_def dist_real_def abs_le_square_iff[symmetric])\n  then show ?thesis\n    by (auto intro: real_sqrt_le_mono\n      simp: euclidean_dist_l2[where y=x] euclidean_dist_l2[where y=\"clamp a b x\"] L2_set_def)\nqed (auto simp: clamp_def)\n\nlemma clamp_continuous_at:\n  fixes f :: \"'a::euclidean_space \\<Rightarrow> 'b::metric_space\"\n    and x :: 'a\n  assumes f_cont: \"continuous_on (cbox a b) f\"\n  shows \"continuous (at x) (\\<lambda>x. f (clamp a b x))\"\nproof cases\n  assume le: \"(\\<forall>i\\<in>Basis. a \\<bullet> i \\<le> b \\<bullet> i)\"\n  show ?thesis\n    unfolding continuous_at_eps_delta\n  proof safe\n    fix x :: 'a\n    fix e :: real\n    assume \"e > 0\"\n    moreover have \"clamp a b x \\<in> cbox a b\"\n      by (simp add: le)\n    moreover note f_cont[simplified continuous_on_iff]\n    ultimately\n    obtain d where d: \"0 < d\"\n      \"\\<And>x'. x' \\<in> cbox a b \\<Longrightarrow> dist x' (clamp a b x) < d \\<Longrightarrow> dist (f x') (f (clamp a b x)) < e\"\n      by force\n    show \"\\<exists>d>0. \\<forall>x'. dist x' x < d \\<longrightarrow> dist (f (clamp a b x')) (f (clamp a b x)) < e\"\n      using le\n      by (auto intro!: d clamp_in_interval dist_clamps_le_dist_args[THEN le_less_trans])\n  qed\nqed (auto simp: clamp_empty_interval)\n\nlemma clamp_continuous_on:\n  fixes f :: \"'a::euclidean_space \\<Rightarrow> 'b::metric_space\"\n  assumes f_cont: \"continuous_on (cbox a b) f\"\n  shows \"continuous_on S (\\<lambda>x. f (clamp a b x))\"\n  using assms\n  by (auto intro: continuous_at_imp_continuous_on clamp_continuous_at)\n\nlemma clamp_bounded:\n  fixes f :: \"'a::euclidean_space \\<Rightarrow> 'b::metric_space\"\n  assumes bounded: \"bounded (f ` (cbox a b))\"\n  shows \"bounded (range (\\<lambda>x. f (clamp a b x)))\"\nproof cases\n  assume le: \"(\\<forall>i\\<in>Basis. a \\<bullet> i \\<le> b \\<bullet> i)\"\n  from bounded obtain c where f_bound: \"\\<forall>x\\<in>f ` cbox a b. dist undefined x \\<le> c\"\n    by (auto simp: bounded_any_center[where a=undefined])\n  then show ?thesis\n    by (metis bounded bounded_subset clamp_in_interval image_mono image_subsetI le range_composition)\nqed (auto simp: clamp_empty_interval image_def)\n\n\ndefinition ext_cont :: \"('a::euclidean_space \\<Rightarrow> 'b::metric_space) \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> 'b\"\n  where \"ext_cont f a b = (\\<lambda>x. f (clamp a b x))\"\n\nlemma ext_cont_cancel_cbox[simp]:\n  fixes x a b :: \"'a::euclidean_space\"\n  assumes x: \"x \\<in> cbox a b\"\n  shows \"ext_cont f a b x = f x\"\n  using assms by (simp add: ext_cont_def)\n\nlemma continuous_on_ext_cont[continuous_intros]:\n  \"continuous_on (cbox a b) f \\<Longrightarrow> continuous_on S (ext_cont f a b)\"\n  by (auto intro!: clamp_continuous_on simp: ext_cont_def)\n\n\nsubsection \\<open>Separability\\<close>\n\nlemma univ_second_countable_sequence:\n  obtains B :: \"nat \\<Rightarrow> 'a::euclidean_space set\"\n    where \"inj B\" \"\\<And>n. open(B n)\" \"\\<And>S. open S \\<Longrightarrow> \\<exists>k. S = \\<Union>{B n |n. n \\<in> k}\"\nproof -\n  obtain \\<B> :: \"'a set set\"\n  where \"countable \\<B>\"\n    and opn: \"\\<And>C. C \\<in> \\<B> \\<Longrightarrow> open C\"\n    and Un: \"\\<And>S. open S \\<Longrightarrow> \\<exists>U. U \\<subseteq> \\<B> \\<and> S = \\<Union>U\"\n    using univ_second_countable by blast\n  have *: \"infinite (range (\\<lambda>n. ball (0::'a) (inverse(Suc n))))\"\n    by (simp add: inj_on_def ball_eq_ball_iff Infinite_Set.range_inj_infinite)\n  have \"infinite \\<B>\"\n  proof\n    assume \"finite \\<B>\"\n    then have \"finite (Union ` (Pow \\<B>))\"\n      by simp\n    moreover have \"range (\\<lambda>n. ball 0 (inverse (real (Suc n)))) \\<subseteq> \\<Union> ` Pow \\<B>\"\n      by (metis (no_types, lifting) PowI image_eqI image_subset_iff Un [OF open_ball])\n    ultimately show False\n      by (metis finite_subset *)\n  qed\n  obtain f :: \"nat \\<Rightarrow> 'a set\" where \"\\<B> = range f\" \"inj f\"\n    by (blast intro: countable_as_injective_image [OF \\<open>countable \\<B>\\<close> \\<open>infinite \\<B>\\<close>])\n  have *: \"\\<exists>k. S = \\<Union>{f n |n. n \\<in> k}\" if \"open S\" for S\n    using Un [OF that]\n    apply clarify\n    apply (rule_tac x=\"f-`U\" in exI)\n    using \\<open>inj f\\<close> \\<open>\\<B> = range f\\<close> apply force\n    done\n  show ?thesis\n    using \"*\" \\<open>\\<B> = range f\\<close> \\<open>inj f\\<close> opn that by force\nqed\n\nproposition separable:\n  fixes S :: \"'a::{metric_space, second_countable_topology} set\"\n  obtains T where \"countable T\" \"T \\<subseteq> S\" \"S \\<subseteq> closure T\"\nproof -\n  obtain \\<B> :: \"'a set set\"\n    where \"countable \\<B>\"\n      and \"{} \\<notin> \\<B>\"\n      and ope: \"\\<And>C. C \\<in> \\<B> \\<Longrightarrow> openin(top_of_set S) C\"\n      and if_ope: \"\\<And>T. openin(top_of_set S) T \\<Longrightarrow> \\<exists>\\<U>. \\<U> \\<subseteq> \\<B> \\<and> T = \\<Union>\\<U>\"\n    by (meson subset_second_countable)\n  then obtain f where f: \"\\<And>C. C \\<in> \\<B> \\<Longrightarrow> f C \\<in> C\"\n    by (metis equals0I)\n  show ?thesis\n  proof\n    show \"countable (f ` \\<B>)\"\n      by (simp add: \\<open>countable \\<B>\\<close>)\n    show \"f ` \\<B> \\<subseteq> S\"\n      using ope f openin_imp_subset by blast\n    show \"S \\<subseteq> closure (f ` \\<B>)\"\n    proof (clarsimp simp: closure_approachable)\n      fix x and e::real\n      assume \"x \\<in> S\" \"0 < e\"\n      have \"openin (top_of_set S) (S \\<inter> ball x e)\"\n        by (simp add: openin_Int_open)\n      with if_ope obtain \\<U> where  \\<U>: \"\\<U> \\<subseteq> \\<B>\" \"S \\<inter> ball x e = \\<Union>\\<U>\"\n        by meson\n      show \"\\<exists>C \\<in> \\<B>. dist (f C) x < e\"\n      proof (cases \"\\<U> = {}\")\n        case True\n        then show ?thesis\n          using \\<open>0 < e\\<close>  \\<U> \\<open>x \\<in> S\\<close> by auto\n      next\n        case False\n        then show ?thesis\n          by (metis IntI Union_iff \\<U> \\<open>0 < e\\<close> \\<open>x \\<in> S\\<close> dist_commute dist_self f inf_le2 mem_ball subset_eq)\n      qed\n    qed\n  qed\nqed\n\n\nsubsection\\<^marker>\\<open>tag unimportant\\<close> \\<open>Diameter\\<close>\n\nlemma diameter_cball [simp]:\n  fixes a :: \"'a::euclidean_space\"\n  shows \"diameter(cball a r) = (if r < 0 then 0 else 2*r)\"\nproof -\n  have \"diameter(cball a r) = 2*r\" if \"r \\<ge> 0\"\n  proof (rule order_antisym)\n    show \"diameter (cball a r) \\<le> 2*r\"\n    proof (rule diameter_le)\n      fix x y assume \"x \\<in> cball a r\" \"y \\<in> cball a r\"\n      then have \"norm (x - a) \\<le> r\" \"norm (a - y) \\<le> r\"\n        by (auto simp: dist_norm norm_minus_commute)\n      then have \"norm (x - y) \\<le> r+r\"\n        using norm_diff_triangle_le by blast\n      then show \"norm (x - y) \\<le> 2*r\" by simp\n    qed (simp add: that)\n    have \"2*r = dist (a + r *\\<^sub>R (SOME i. i \\<in> Basis)) (a - r *\\<^sub>R (SOME i. i \\<in> Basis))\"\n      using \\<open>0 \\<le> r\\<close> that by (simp add: dist_norm flip: scaleR_2)\n    also have \"... \\<le> diameter (cball a r)\"\n      apply (rule diameter_bounded_bound)\n      using that by (auto simp: dist_norm)\n    finally show \"2*r \\<le> diameter (cball a r)\" .\n  qed\n  then show ?thesis by simp\nqed\n\nlemma diameter_ball [simp]:\n  fixes a :: \"'a::euclidean_space\"\n  shows \"diameter(ball a r) = (if r < 0 then 0 else 2*r)\"\nproof -\n  have \"diameter(ball a r) = 2*r\" if \"r > 0\"\n    by (metis bounded_ball diameter_closure closure_ball diameter_cball less_eq_real_def linorder_not_less that)\n  then show ?thesis\n    by (simp add: diameter_def)\nqed\n\nlemma diameter_closed_interval [simp]: \"diameter {a..b} = (if b < a then 0 else b-a)\"\nproof -\n  have \"{a..b} = cball ((a+b)/2) ((b-a)/2)\"\n    using atLeastAtMost_eq_cball by blast\n  then show ?thesis\n    by simp\nqed\n\nlemma diameter_open_interval [simp]: \"diameter {a<..<b} = (if b < a then 0 else b-a)\"\nproof -\n  have \"{a <..< b} = ball ((a+b)/2) ((b-a)/2)\"\n    using greaterThanLessThan_eq_ball by blast\n  then show ?thesis\n    by simp\nqed\n\nlemma diameter_cbox:\n  fixes a b::\"'a::euclidean_space\"\n  shows \"(\\<forall>i \\<in> Basis. a \\<bullet> i \\<le> b \\<bullet> i) \\<Longrightarrow> diameter (cbox a b) = dist a b\"\n  by (force simp: diameter_def intro!: cSup_eq_maximum L2_set_mono\n     simp: euclidean_dist_l2[where 'a='a] cbox_def dist_norm)\n\n\nsubsection\\<^marker>\\<open>tag unimportant\\<close>\\<open>Relating linear images to open/closed/interior/closure/connected\\<close>\n\nproposition open_surjective_linear_image:\n  fixes f :: \"'a::real_normed_vector \\<Rightarrow> 'b::euclidean_space\"\n  assumes \"open A\" \"linear f\" \"surj f\"\n    shows \"open(f ` A)\"\nunfolding open_dist\nproof clarify\n  fix x\n  assume \"x \\<in> A\"\n  have \"bounded (inv f ` Basis)\"\n    by (simp add: finite_imp_bounded)\n  with bounded_pos obtain B where \"B > 0\" and B: \"\\<And>x. x \\<in> inv f ` Basis \\<Longrightarrow> norm x \\<le> B\"\n    by metis\n  obtain e where \"e > 0\" and e: \"\\<And>z. dist z x < e \\<Longrightarrow> z \\<in> A\"\n    by (metis open_dist \\<open>x \\<in> A\\<close> \\<open>open A\\<close>)\n  define \\<delta> where \"\\<delta> \\<equiv> e / B / DIM('b)\"\n  show \"\\<exists>e>0. \\<forall>y. dist y (f x) < e \\<longrightarrow> y \\<in> f ` A\"\n  proof (intro exI conjI)\n    show \"\\<delta> > 0\"\n      using \\<open>e > 0\\<close> \\<open>B > 0\\<close>  by (simp add: \\<delta>_def field_split_simps)\n    have \"y \\<in> f ` A\" if \"dist y (f x) * (B * real DIM('b)) < e\" for y\n    proof -\n      define u where \"u \\<equiv> y - f x\"\n      show ?thesis\n      proof (rule image_eqI)\n        show \"y = f (x + (\\<Sum>i\\<in>Basis. (u \\<bullet> i) *\\<^sub>R inv f i))\"\n          apply (simp add: linear_add linear_sum linear.scaleR \\<open>linear f\\<close> surj_f_inv_f \\<open>surj f\\<close>)\n          apply (simp add: euclidean_representation u_def)\n          done\n        have \"dist (x + (\\<Sum>i\\<in>Basis. (u \\<bullet> i) *\\<^sub>R inv f i)) x \\<le> (\\<Sum>i\\<in>Basis. norm ((u \\<bullet> i) *\\<^sub>R inv f i))\"\n          by (simp add: dist_norm sum_norm_le)\n        also have \"... = (\\<Sum>i\\<in>Basis. \\<bar>u \\<bullet> i\\<bar> * norm (inv f i))\"\n          by simp\n        also have \"... \\<le> (\\<Sum>i\\<in>Basis. \\<bar>u \\<bullet> i\\<bar>) * B\"\n          by (simp add: B sum_distrib_right sum_mono mult_left_mono)\n        also have \"... \\<le> DIM('b) * dist y (f x) * B\"\n          apply (rule mult_right_mono [OF sum_bounded_above])\n          using \\<open>0 < B\\<close> by (auto simp: Basis_le_norm dist_norm u_def)\n        also have \"... < e\"\n          by (metis mult.commute mult.left_commute that)\n        finally show \"x + (\\<Sum>i\\<in>Basis. (u \\<bullet> i) *\\<^sub>R inv f i) \\<in> A\"\n          by (rule e)\n      qed\n    qed\n    then show \"\\<forall>y. dist y (f x) < \\<delta> \\<longrightarrow> y \\<in> f ` A\"\n      using \\<open>e > 0\\<close> \\<open>B > 0\\<close>\n      by (auto simp: \\<delta>_def field_split_simps)\n  qed\nqed\n\ncorollary open_bijective_linear_image_eq:\n  fixes f :: \"'a::euclidean_space \\<Rightarrow> 'b::euclidean_space\"\n  assumes \"linear f\" \"bij f\"\n    shows \"open(f ` A) \\<longleftrightarrow> open A\"\nproof\n  assume \"open(f ` A)\"\n  then show \"open A\"\n    by (metis assms bij_is_inj continuous_open_vimage inj_vimage_image_eq linear_continuous_at linear_linear)\nnext\n  assume \"open A\"\n  then show \"open(f ` A)\"\n    by (simp add: assms bij_is_surj open_surjective_linear_image)\nqed\n\ncorollary interior_bijective_linear_image:\n  fixes f :: \"'a::euclidean_space \\<Rightarrow> 'b::euclidean_space\"\n  assumes \"linear f\" \"bij f\"\n  shows \"interior (f ` S) = f ` interior S\" \n  by (smt (verit) assms bij_is_inj inj_image_subset_iff interior_maximal interior_subset \n      open_bijective_linear_image_eq open_interior subset_antisym subset_imageE)\n\nlemma interior_injective_linear_image:\n  fixes f :: \"'a::euclidean_space \\<Rightarrow> 'a::euclidean_space\"\n  assumes \"linear f\" \"inj f\"\n   shows \"interior(f ` S) = f ` (interior S)\"\n  by (simp add: linear_injective_imp_surjective assms bijI interior_bijective_linear_image)\n\nlemma interior_surjective_linear_image:\n  fixes f :: \"'a::euclidean_space \\<Rightarrow> 'a::euclidean_space\"\n  assumes \"linear f\" \"surj f\"\n   shows \"interior(f ` S) = f ` (interior S)\"\n  by (simp add: assms interior_injective_linear_image linear_surjective_imp_injective)\n\nlemma interior_negations:\n  fixes S :: \"'a::euclidean_space set\"\n  shows \"interior(uminus ` S) = image uminus (interior S)\"\n  by (simp add: bij_uminus interior_bijective_linear_image linear_uminus)\n\nlemma connected_linear_image:\n  fixes f :: \"'a::euclidean_space \\<Rightarrow> 'b::real_normed_vector\"\n  assumes \"linear f\" and \"connected s\"\n  shows \"connected (f ` s)\"\nusing connected_continuous_image assms linear_continuous_on linear_conv_bounded_linear by blast\n\n\nsubsection\\<^marker>\\<open>tag unimportant\\<close> \\<open>\"Isometry\" (up to constant bounds) of Injective Linear Map\\<close>\n\nproposition injective_imp_isometric:\n  fixes f :: \"'a::euclidean_space \\<Rightarrow> 'b::euclidean_space\"\n  assumes s: \"closed s\" \"subspace s\"\n    and f: \"bounded_linear f\" \"\\<forall>x\\<in>s. f x = 0 \\<longrightarrow> x = 0\"\n  shows \"\\<exists>e>0. \\<forall>x\\<in>s. norm (f x) \\<ge> e * norm x\"\nproof (cases \"s \\<subseteq> {0::'a}\")\n  case True\n  have \"norm x \\<le> norm (f x)\" if \"x \\<in> s\" for x\n  proof -\n    from True that have \"x = 0\" by auto\n    then show ?thesis by simp\n  qed\n  then show ?thesis\n    by (auto intro!: exI[where x=1])\nnext\n  case False\n  interpret f: bounded_linear f by fact\n  from False obtain a where a: \"a \\<noteq> 0\" \"a \\<in> s\"\n    by auto\n  from False have \"s \\<noteq> {}\"\n    by auto\n  let ?S = \"{f x| x. x \\<in> s \\<and> norm x = norm a}\"\n  let ?S' = \"{x::'a. x\\<in>s \\<and> norm x = norm a}\"\n  let ?S'' = \"{x::'a. norm x = norm a}\"\n\n  have \"?S'' = frontier (cball 0 (norm a))\"\n    by (simp add: sphere_def dist_norm)\n  then have \"compact ?S''\" by (metis compact_cball compact_frontier)\n  moreover have \"?S' = s \\<inter> ?S''\" by auto\n  ultimately have \"compact ?S'\"\n    using closed_Int_compact[of s ?S''] using s(1) by auto\n  moreover have *:\"f ` ?S' = ?S\" by auto\n  ultimately have \"compact ?S\"\n    using compact_continuous_image[OF linear_continuous_on[OF f(1)], of ?S'] by auto\n  then have \"closed ?S\"\n    using compact_imp_closed by auto\n  moreover from a have \"?S \\<noteq> {}\" by auto\n  ultimately obtain b' where \"b'\\<in>?S\" \"\\<forall>y\\<in>?S. norm b' \\<le> norm y\"\n    using distance_attains_inf[of ?S 0] unfolding dist_0_norm by auto\n  then obtain b where \"b\\<in>s\"\n    and ba: \"norm b = norm a\"\n    and b: \"\\<forall>x\\<in>{x \\<in> s. norm x = norm a}. norm (f b) \\<le> norm (f x)\"\n    unfolding *[symmetric] unfolding image_iff by auto\n\n  let ?e = \"norm (f b) / norm b\"\n  have \"norm b > 0\"\n    using ba and a and norm_ge_zero by auto\n  moreover have \"norm (f b) > 0\"\n    using f(2)[THEN bspec[where x=b], OF \\<open>b\\<in>s\\<close>]\n    using \\<open>norm b >0\\<close> by simp\n  ultimately have \"0 < norm (f b) / norm b\" by simp\n  moreover\n  have \"norm (f b) / norm b * norm x \\<le> norm (f x)\" if \"x\\<in>s\" for x\n  proof (cases \"x = 0\")\n    case True\n    then show \"norm (f b) / norm b * norm x \\<le> norm (f x)\"\n      by auto\n  next\n    case False\n    with \\<open>a \\<noteq> 0\\<close> have *: \"0 < norm a / norm x\"\n      unfolding zero_less_norm_iff[symmetric] by simp\n    have \"\\<forall>x\\<in>s. c *\\<^sub>R x \\<in> s\" for c\n      using s[unfolded subspace_def] by simp\n    with \\<open>x \\<in> s\\<close> \\<open>x \\<noteq> 0\\<close> have \"(norm a / norm x) *\\<^sub>R x \\<in> {x \\<in> s. norm x = norm a}\"\n      by simp\n    with \\<open>x \\<noteq> 0\\<close> \\<open>a \\<noteq> 0\\<close> show \"norm (f b) / norm b * norm x \\<le> norm (f x)\"\n      using b[THEN bspec[where x=\"(norm a / norm x) *\\<^sub>R x\"]]\n      unfolding f.scaleR and ba\n      by (auto simp: mult.commute pos_le_divide_eq pos_divide_le_eq)\n  qed\n  ultimately show ?thesis by auto\nqed\n\nproposition closed_injective_image_subspace:\n  fixes f :: \"'a::euclidean_space \\<Rightarrow> 'b::euclidean_space\"\n  assumes \"subspace s\" \"bounded_linear f\" \"\\<forall>x\\<in>s. f x = 0 \\<longrightarrow> x = 0\" \"closed s\"\n  shows \"closed(f ` s)\"\nproof -\n  obtain e where \"e > 0\" and e: \"\\<forall>x\\<in>s. e * norm x \\<le> norm (f x)\"\n    using assms injective_imp_isometric by blast\n  with assms show ?thesis\n    by (meson complete_eq_closed complete_isometric_image)\nqed\n                               \n\nlemma closure_bounded_linear_image_subset:\n  assumes f: \"bounded_linear f\"\n  shows \"f ` closure S \\<subseteq> closure (f ` S)\"\n  using linear_continuous_on [OF f] closed_closure closure_subset\n  by (rule image_closure_subset)\n\nlemma closure_linear_image_subset:\n  fixes f :: \"'m::euclidean_space \\<Rightarrow> 'n::real_normed_vector\"\n  assumes \"linear f\"\n  shows \"f ` (closure S) \\<subseteq> closure (f ` S)\"\n  using assms unfolding linear_conv_bounded_linear\n  by (rule closure_bounded_linear_image_subset)\n\nlemma closed_injective_linear_image:\n    fixes f :: \"'a::euclidean_space \\<Rightarrow> 'b::euclidean_space\"\n    assumes S: \"closed S\" and f: \"linear f\" \"inj f\"\n    shows \"closed (f ` S)\"\nproof -\n  obtain g where g: \"linear g\" \"g \\<circ> f = id\"\n    using linear_injective_left_inverse [OF f] by blast\n  then have confg: \"continuous_on (range f) g\"\n    using linear_continuous_on linear_conv_bounded_linear by blast\n  have [simp]: \"g ` f ` S = S\"\n    using g by (simp add: image_comp)\n  have cgf: \"closed (g ` f ` S)\"\n    by (simp add: \\<open>g \\<circ> f = id\\<close> S image_comp)\n  have [simp]: \"(range f \\<inter> g -` S) = f ` S\"\n    using g unfolding o_def id_def image_def by auto metis+\n  show ?thesis\n  proof (rule closedin_closed_trans [of \"range f\"])\n    show \"closedin (top_of_set (range f)) (f ` S)\"\n      using continuous_closedin_preimage [OF confg cgf] by simp\n    show \"closed (range f)\"\n      using closed_injective_image_subspace f linear_conv_bounded_linear \n          linear_injective_0 subspace_UNIV by blast\n  qed\nqed\n\nlemma closed_injective_linear_image_eq:\n    fixes f :: \"'a::euclidean_space \\<Rightarrow> 'b::euclidean_space\"\n    assumes f: \"linear f\" \"inj f\"\n      shows \"(closed(image f s) \\<longleftrightarrow> closed s)\"\n  by (metis closed_injective_linear_image closure_eq closure_linear_image_subset closure_subset_eq f(1) f(2) inj_image_subset_iff)\n\nlemma closure_injective_linear_image:\n    fixes f :: \"'a::euclidean_space \\<Rightarrow> 'b::euclidean_space\"\n    shows \"\\<lbrakk>linear f; inj f\\<rbrakk> \\<Longrightarrow> f ` (closure S) = closure (f ` S)\"\n  by (simp add: closed_injective_linear_image closure_linear_image_subset \n        closure_minimal closure_subset image_mono subset_antisym)\n\nlemma closure_bounded_linear_image:\n  fixes f :: \"'a::euclidean_space \\<Rightarrow> 'b::euclidean_space\"\n  assumes \"linear f\" \"bounded S\"\n    shows \"f ` (closure S) = closure (f ` S)\"  (is \"?lhs = ?rhs\")\nproof\n  show \"?lhs \\<subseteq> ?rhs\"\n    using assms closure_linear_image_subset by blast\n  show \"?rhs \\<subseteq> ?lhs\"\n    using assms by (meson closure_minimal closure_subset compact_closure compact_eq_bounded_closed\n                      compact_continuous_image image_mono linear_continuous_on linear_linear)\nqed\n\nlemma closure_scaleR:\n  fixes S :: \"'a::real_normed_vector set\"\n  shows \"((*\\<^sub>R) c) ` (closure S) = closure (((*\\<^sub>R) c) ` S)\"  (is \"?lhs = ?rhs\")\nproof\n  show \"?lhs \\<subseteq> ?rhs\"\n    using bounded_linear_scaleR_right by (rule closure_bounded_linear_image_subset)\n  show \"?rhs \\<subseteq> ?lhs\"\n    by (intro closure_minimal image_mono closure_subset closed_scaling closed_closure)\nqed\n\n\nsubsection\\<^marker>\\<open>tag unimportant\\<close> \\<open>Some properties of a canonical subspace\\<close>\n\nlemma closed_substandard: \"closed {x::'a::euclidean_space. \\<forall>i\\<in>Basis. P i \\<longrightarrow> x\\<bullet>i = 0}\"\n  (is \"closed ?A\")\nproof -\n  let ?D = \"{i\\<in>Basis. P i}\"\n  have \"closed (\\<Inter>i\\<in>?D. {x::'a. x\\<bullet>i = 0})\"\n    by (simp add: closed_INT closed_Collect_eq continuous_on_inner)\n  also have \"(\\<Inter>i\\<in>?D. {x::'a. x\\<bullet>i = 0}) = ?A\"\n    by auto\n  finally show \"closed ?A\" .\nqed\n\nlemma closed_subspace:\n  fixes S :: \"'a::euclidean_space set\"\n  assumes \"subspace S\"\n  shows \"closed S\"\nproof -\n  have \"dim S \\<le> card (Basis :: 'a set)\"\n    using dim_subset_UNIV by auto\n  with obtain_subset_with_card_n \n  obtain d :: \"'a set\" where cd: \"card d = dim S\" and d: \"d \\<subseteq> Basis\"\n    by metis\n  let ?t = \"{x::'a. \\<forall>i\\<in>Basis. i \\<notin> d \\<longrightarrow> x\\<bullet>i = 0}\"\n  have \"\\<exists>f. linear f \\<and> f ` {x::'a. \\<forall>i\\<in>Basis. i \\<notin> d \\<longrightarrow> x \\<bullet> i = 0} = S \\<and>\n      inj_on f {x::'a. \\<forall>i\\<in>Basis. i \\<notin> d \\<longrightarrow> x \\<bullet> i = 0}\"\n    using dim_substandard[of d] cd d assms\n    by (intro subspace_isomorphism[OF subspace_substandard[of \"\\<lambda>i. i \\<notin> d\"]]) (auto simp: inner_Basis)\n  then obtain f where f:\n      \"linear f\"\n      \"f ` {x. \\<forall>i\\<in>Basis. i \\<notin> d \\<longrightarrow> x \\<bullet> i = 0} = S\"\n      \"inj_on f {x. \\<forall>i\\<in>Basis. i \\<notin> d \\<longrightarrow> x \\<bullet> i = 0}\"\n    by blast\n  interpret f: bounded_linear f\n    using f by (simp add: linear_conv_bounded_linear)\n  have \"x \\<in> ?t \\<Longrightarrow> f x = 0 \\<Longrightarrow> x = 0\" for x\n    using f.zero d f(3)[THEN inj_onD, of x 0] by auto\n  then show ?thesis\n    using closed_injective_image_subspace[of ?t f] closed_substandard subspace_substandard\n    using f(2) f.bounded_linear_axioms by force\nqed\n\nlemma complete_subspace: \"subspace S \\<Longrightarrow> complete S\"\n  for S :: \"'a::euclidean_space set\"\n  using complete_eq_closed closed_subspace by auto\n\nlemma closed_span [iff]: \"closed (span S)\"\n  for S :: \"'a::euclidean_space set\"\n  by (simp add: closed_subspace)\n\nlemma dim_closure [simp]: \"dim (closure S) = dim S\" (is \"?dc = ?d\")\n  for S :: \"'a::euclidean_space set\"\n  by (metis closed_span closure_minimal closure_subset dim_eq_span span_eq_dim span_superset subset_le_dim)\n\n\nsubsection \\<open>Set Distance\\<close>\n\nlemma setdist_compact_closed:\n  fixes A :: \"'a::heine_borel set\"\n  assumes \"compact A\" \"closed B\"\n    and \"A \\<noteq> {}\" \"B \\<noteq> {}\"\n  shows \"\\<exists>x \\<in> A. \\<exists>y \\<in> B. dist x y = setdist A B\"\n  by (metis assms infdist_attains_inf setdist_attains_inf setdist_sym)\n\nlemma setdist_closed_compact:\n  fixes S :: \"'a::heine_borel set\"\n  assumes S: \"closed S\" and T: \"compact T\"\n      and \"S \\<noteq> {}\" \"T \\<noteq> {}\"\n    shows \"\\<exists>x \\<in> S. \\<exists>y \\<in> T. dist x y = setdist S T\"\n  using setdist_compact_closed [OF T S \\<open>T \\<noteq> {}\\<close> \\<open>S \\<noteq> {}\\<close>]\n  by (metis dist_commute setdist_sym)\n\nlemma setdist_eq_0_compact_closed:\n  assumes S: \"compact S\" and T: \"closed T\"\n    shows \"setdist S T = 0 \\<longleftrightarrow> S = {} \\<or> T = {} \\<or> S \\<inter> T \\<noteq> {}\"\nproof (cases \"S = {} \\<or> T = {}\")\n  case False\n  then show ?thesis\n    by (metis S T disjoint_iff in_closed_iff_infdist_zero setdist_attains_inf setdist_eq_0I setdist_sym)\nqed auto\n\ncorollary setdist_gt_0_compact_closed:\n  assumes S: \"compact S\" and T: \"closed T\"\n    shows \"setdist S T > 0 \\<longleftrightarrow> (S \\<noteq> {} \\<and> T \\<noteq> {} \\<and> S \\<inter> T = {})\"\n  using setdist_pos_le [of S T] setdist_eq_0_compact_closed [OF assms] by linarith\n\nlemma setdist_eq_0_closed_compact:\n  assumes S: \"closed S\" and T: \"compact T\"\n    shows \"setdist S T = 0 \\<longleftrightarrow> S = {} \\<or> T = {} \\<or> S \\<inter> T \\<noteq> {}\"\n  using setdist_eq_0_compact_closed [OF T S]\n  by (metis Int_commute setdist_sym)\n\nlemma setdist_eq_0_bounded:\n  fixes S :: \"'a::heine_borel set\"\n  assumes \"bounded S \\<or> bounded T\"\n  shows \"setdist S T = 0 \\<longleftrightarrow> S = {} \\<or> T = {} \\<or> closure S \\<inter> closure T \\<noteq> {}\"\nproof (cases \"S = {} \\<or> T = {}\")\n  case False\n  then show ?thesis\n    using setdist_eq_0_compact_closed [of \"closure S\" \"closure T\"]\n          setdist_eq_0_closed_compact [of \"closure S\" \"closure T\"] assms\n    by (force simp:  bounded_closure compact_eq_bounded_closed)\nqed force\n\nlemma setdist_eq_0_sing_1:\n  \"setdist {x} S = 0 \\<longleftrightarrow> S = {} \\<or> x \\<in> closure S\"\n  by (metis in_closure_iff_infdist_zero infdist_def infdist_eq_setdist)\n\nlemma setdist_eq_0_sing_2:\n  \"setdist S {x} = 0 \\<longleftrightarrow> S = {} \\<or> x \\<in> closure S\"\n  by (metis setdist_eq_0_sing_1 setdist_sym)\n\nlemma setdist_neq_0_sing_1:\n  \"\\<lbrakk>setdist {x} S = a; a \\<noteq> 0\\<rbrakk> \\<Longrightarrow> S \\<noteq> {} \\<and> x \\<notin> closure S\"\n  by (metis setdist_closure_2 setdist_empty2 setdist_eq_0I singletonI)\n\nlemma setdist_neq_0_sing_2:\n  \"\\<lbrakk>setdist S {x} = a; a \\<noteq> 0\\<rbrakk> \\<Longrightarrow> S \\<noteq> {} \\<and> x \\<notin> closure S\"\n  by (simp add: setdist_neq_0_sing_1 setdist_sym)\n\nlemma setdist_sing_in_set:\n   \"x \\<in> S \\<Longrightarrow> setdist {x} S = 0\"\n  by (simp add: setdist_eq_0I)\n\nlemma setdist_eq_0_closed:\n   \"closed S \\<Longrightarrow> (setdist {x} S = 0 \\<longleftrightarrow> S = {} \\<or> x \\<in> S)\"\nby (simp add: setdist_eq_0_sing_1)\n\nlemma setdist_eq_0_closedin:\n  shows \"\\<lbrakk>closedin (top_of_set U) S; x \\<in> U\\<rbrakk>\n         \\<Longrightarrow> (setdist {x} S = 0 \\<longleftrightarrow> S = {} \\<or> x \\<in> S)\"\n  by (auto simp: closedin_limpt setdist_eq_0_sing_1 closure_def)\n\nlemma setdist_gt_0_closedin:\n  shows \"\\<lbrakk>closedin (top_of_set U) S; x \\<in> U; S \\<noteq> {}; x \\<notin> S\\<rbrakk>\n         \\<Longrightarrow> setdist {x} S > 0\"\n  using less_eq_real_def setdist_eq_0_closedin by fastforce\n\nno_notation\n  eucl_less (infix \"<e\" 50)\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/Topology_Euclidean_Space.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8774767810736693, "lm_q2_score": 0.8418256432832333, "lm_q1q2_score": 0.7386824556934426}}
{"text": "(* Author: Steven Obua, TU Muenchen *)\n\nsection {* Various algebraic structures combined with a lattice *}\n\ntheory Lattice_Algebras\nimports 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 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 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  assume \"a \\<le> c\" \"b \\<le> c\"\n  then show \"- inf (- a) (- b) \\<le> c\"\n    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 {* Positive Part, Negative Part, Absolute Value *}\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    unfolding minus_zero ..\n  also have \"\\<dots> = - inf x 0\"\n    unfolding neg_inf_eq_sup ..\n  finally have \"sup (- x) 0 = - inf x 0\" .\n  then show ?thesis\n    unfolding 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 add_eq_inf_sup[symmetric])\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\" (is \"?l = ?r\")\nproof\n  assume ?l\n  then show ?r\n    apply -\n    apply (rule add_le_imp_le_right[of _ \"uminus b\" _])\n    apply (simp add: add.assoc)\n    done\nnext\n  assume ?r\n  then show ?l\n    apply -\n    apply (rule add_le_imp_le_right[of _ \"b\" _])\n    apply simp\n    done\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: \"sup a (- a) = 0 \\<Longrightarrow> a = 0\"\nproof -\n  {\n    fix a :: 'a\n    assume hyp: \"sup a (- a) = 0\"\n    then 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 have \"0 \\<le> a\"\n      by (blast intro: order_trans inf_sup_ord)\n  }\n  note p = this\n  assume hyp:\"sup a (-a) = 0\"\n  then have hyp2:\"sup (-a) (-(-a)) = 0\"\n    by (simp add: sup_commute)\n  from p[OF hyp] p[OF hyp2] 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\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\n  apply (erule sup_0_imp_0)\n  apply simp\n  done\n\nlemma zero_le_double_add_iff_zero_le_single_add [simp]:\n  \"0 \\<le> a + a \\<longleftrightarrow> 0 \\<le> a\"\nproof\n  assume \"0 \\<le> a + a\"\n  then 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 \"0 \\<le> a\"\n    unfolding le_iff_inf by (simp add: inf_commute)\nnext\n  assume a: \"0 \\<le> a\"\n  show \"0 \\<le> a + a\"\n    by (simp add: add_mono[OF a a, simplified])\nqed\n\nlemma double_zero [simp]: \"a + a = 0 \\<longleftrightarrow> a = 0\"\nproof\n  assume assm: \"a + a = 0\"\n  then have \"a + a + - a = - a\"\n    by simp\n  then have \"a + (a + - a) = - a\"\n    by (simp only: add.assoc)\n  then have a: \"- a = a\"\n    by simp\n  show \"a = 0\"\n    apply (rule antisym)\n    apply (unfold neg_le_iff_le [symmetric, of a])\n    unfolding a\n    apply simp\n    unfolding zero_le_double_add_iff_zero_le_single_add [symmetric, of a]\n    unfolding assm\n    unfolding le_less\n    apply simp_all\n    done\nnext\n  assume \"a = 0\"\n  then show \"a + a = 0\"\n    by simp\nqed\n\nlemma zero_less_double_add_iff_zero_less_single_add [simp]: \"0 < a + a \\<longleftrightarrow> 0 < a\"\nproof (cases \"a = 0\")\n  case True\n  then show ?thesis by auto\nnext\n  case False\n  then show ?thesis\n    unfolding less_le\n    apply simp\n    apply rule\n    apply clarify\n    apply rule\n    apply assumption\n    apply (rule notI)\n    unfolding double_zero [symmetric, of a]\n    apply blast\n    done\nqed\n\nlemma double_add_le_zero_iff_single_add_le_zero [simp]:\n  \"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]:\n  \"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] neg_sup_eq_inf [simp] diff_inf_eq_sup [simp] 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 add: add.assoc[symmetric])\n  then show ?thesis\n    by simp\nqed\n\nlemma minus_le_self_iff: \"- a \\<le> a \\<longleftrightarrow> 0 \\<le> a\"\nproof -\n  from add_le_cancel_left [of \"uminus a\" zero \"plus a a\"]\n  have \"- a \\<le> a \\<longleftrightarrow> 0 \\<le> a + a\"\n    by (simp add: add.assoc[symmetric])\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]: \"\\<And>a. 0 \\<le> \\<bar>a\\<bar>\"\n  proof -\n    fix a b\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: \"\\<And>a b. a \\<le> b \\<Longrightarrow> - a \\<le> b \\<Longrightarrow> \\<bar>a\\<bar> \\<le> 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  {\n    assume \"a \\<le> b\"\n    then show \"- a \\<le> b \\<Longrightarrow> \\<bar>a\\<bar> \\<le> b\"\n      by (rule abs_leI)\n  }\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)\"\nproof -\n  note add_le_cancel_right [of a a \"- a\", symmetric, simplified]\n  moreover note add_le_cancel_right [of \"-a\" a a, symmetric, simplified]\n  then show ?thesis by (auto simp: sup_max max.absorb1 max.absorb2)\nqed\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  shows \"a + b \\<le> c \\<Longrightarrow> a \\<le> c + \\<bar>b\\<bar>\"\nproof -\n  assume \"a + b \\<le> c\"\n  then 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 `a \\<le> c + (- b)` 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  {\n    fix u v :: 'a\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\"\n      apply (subst prts[of u], subst prts[of v])\n      apply (simp add: algebra_simps)\n      done\n  }\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 add: prts[symmetric])\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    apply (subst prts[symmetric])+\n    apply simp\n    done\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    apply -\n    apply (rule add_mono | simp)+\n    done\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> - 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  fix k :: int\n  show \"\\<bar>k\\<bar> = sup k (- k)\"\n    by (auto simp add: sup_int_def)\nqed\n\ninstance real :: lattice_ring\nproof\n  fix a :: real\n  show \"\\<bar>a\\<bar> = sup a (- a)\"\n    by (auto simp add: sup_real_def)\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/Lattice_Algebras.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767778695834, "lm_q2_score": 0.8418256452674008, "lm_q1q2_score": 0.7386824547372218}}
{"text": "(*\n    File:      Multiplicative_Characters.thy\n    Author:    Manuel Eberl, TU M\u00fcnchen\n*)\nsection \\<open>Multiplicative Characters of Finite Abelian Groups\\<close>\ntheory Multiplicative_Characters\nimports\n  Complex_Main\n  Group_Adjoin\nbegin\n\nsubsection \\<open>Definition of characters\\<close>\n\ntext \\<open>\n  A (multiplicative) character is a completely multiplicative function from a group to the\n  complex numbers. For simplicity, we restrict this to finite abelian groups here, which is\n  the most interesting case.\n\n  Characters form a group where the identity is the \\emph{principal} character that maps all\n  elements to $1$, multiplication is point-wise multiplication of the characters, and the inverse\n  is the point-wise complex conjugate.\n\n  This group is often called the \\emph{Pontryagin dual} group and is isomorphic to the original\n  group (in a non-natural way) while the double-dual group \\<^emph>\\<open>is\\<close> naturally isomorphic to the\n  original group.\n\n  To get extensionality of the characters, we also require characters to map anything that is\n  not in the group to $0$.\n\\<close>\n\ndefinition principal_char :: \"('a, 'b) monoid_scheme \\<Rightarrow> 'a \\<Rightarrow> complex\" where\n  \"principal_char G a = (if a \\<in> carrier G then 1 else 0)\"\n\ndefinition inv_character where\n  \"inv_character \\<chi> = (\\<lambda>a. cnj (\\<chi> a))\"\n\nlemma inv_character_principal [simp]: \"inv_character (principal_char G) = principal_char G\"\n  by (simp add: inv_character_def principal_char_def fun_eq_iff)\n\nlemma inv_character_inv_character [simp]: \"inv_character (inv_character \\<chi>) = \\<chi>\"\n  by (simp add: inv_character_def)\n\nlemma eval_inv_character: \"inv_character \\<chi> j = cnj (\\<chi> j)\"\n  by (simp add: inv_character_def)\n\n\nbundle character_syntax\nbegin\nnotation principal_char (\"\\<chi>\\<^sub>0\\<index>\")\nend\n\nlocale character = finite_comm_group +\n  fixes \\<chi> :: \"'a \\<Rightarrow> complex\"\n  assumes char_one_nz: \"\\<chi> \\<one> \\<noteq> 0\"\n  assumes char_eq_0:   \"a \\<notin> carrier G \\<Longrightarrow> \\<chi> a = 0\"\n  assumes char_mult [simp]: \"a \\<in> carrier G \\<Longrightarrow> b \\<in> carrier G \\<Longrightarrow> \\<chi> (a \\<otimes> b) = \\<chi> a * \\<chi> b\"\nbegin\n\n\nsubsection \\<open>Basic properties\\<close>\n\nlemma char_one [simp]: \"\\<chi> \\<one> = 1\"\nproof-\n  from char_mult[of \\<one> \\<one>] have \"\\<chi> \\<one> * (\\<chi> \\<one> - 1) = 0\"\n    by (auto simp del: char_mult)\n  with char_one_nz show ?thesis by simp\nqed\n\nlemma char_power [simp]: \"a \\<in> carrier G \\<Longrightarrow> \\<chi> (a [^] k) = \\<chi> a ^ k\"\n  by (induction k) auto\n\nlemma char_root:\n  assumes \"a \\<in> carrier G\"\n  shows   \"\\<chi> a ^ ord a = 1\"\nproof -\n  from assms have \"\\<chi> a ^ ord a = \\<chi> (a [^] ord a)\"\n    by (subst char_power) auto\n  also from fin and assms have \"a [^] ord a = \\<one>\" by (intro pow_ord_eq_1) auto\n  finally show ?thesis by simp\nqed\n\nlemma char_root':\n  assumes \"a \\<in> carrier G\"\n  shows   \"\\<chi> a ^ order G = 1\"\nproof -\n  from assms have \"\\<chi> a ^ order G = \\<chi> (a [^] order G)\" by simp\n  also from fin and assms have \"a [^] order G = \\<one>\" by (intro pow_order_eq_1) auto\n  finally show ?thesis by simp\nqed\n\nlemma norm_char: \"norm (\\<chi> a) = (if a \\<in> carrier G then 1 else 0)\"\nproof (cases \"a \\<in> carrier G\")\n  case True\n  have \"norm (\\<chi> a) ^ order G = norm (\\<chi> a ^ order G)\" by (simp add: norm_power)\n  also from True have \"\\<chi> a ^ order G = 1\" by (rule char_root')\n  finally have \"norm (\\<chi> a) ^ order G = 1 ^ order G\" by simp\n  hence \"norm (\\<chi> a) = 1\" by (subst (asm) power_eq_iff_eq_base) auto\n  with True show ?thesis by auto\nnext\n  case False\n  thus ?thesis by (auto simp: char_eq_0)\nqed\n\nlemma char_eq_0_iff: \"\\<chi> a = 0 \\<longleftrightarrow> a \\<notin> carrier G\"\nproof -\n  have \"\\<chi> a = 0 \\<longleftrightarrow> norm (\\<chi> a) = 0\" by simp\n  also have \"\\<dots> \\<longleftrightarrow> a \\<notin> carrier G\" by (subst norm_char) auto\n  finally show ?thesis .\nqed\n\nlemma inv_character: \"character G (inv_character \\<chi>)\"\n  by standard (auto simp: inv_character_def char_eq_0)\n\nlemma mult_inv_character: \"\\<chi> k * inv_character \\<chi> k = principal_char G k\"\nproof -\n  have \"\\<chi> k * inv_character \\<chi> k = of_real (norm (\\<chi> k) ^ 2)\"\n    by (subst complex_norm_square) (simp add: inv_character_def)\n  also have \"\\<dots> = principal_char G k\"\n    by (simp add: principal_char_def norm_char)\n  finally show ?thesis .\nqed\n\nlemma\n  assumes \"a \\<in> carrier G\"\n  shows    char_inv: \"\\<chi> (inv a) = cnj (\\<chi> a)\" and char_inv': \"\\<chi> (inv a) = inverse (\\<chi> a)\"\nproof -\n  from assms have \"inv a \\<otimes> a = \\<one>\" by simp\n  also have \"\\<chi> \\<dots> = 1\" by simp\n  also from assms have \"\\<chi> (inv a \\<otimes> a) = \\<chi> (inv a) * \\<chi> a\"\n    by (intro char_mult) auto\n  finally have *: \"\\<chi> (inv a) * \\<chi> a = 1\" .\n  thus \"\\<chi> (inv a) = inverse (\\<chi> a)\" by (auto simp: divide_simps)\n  also from mult_inv_character[of a] and assms have \"inverse (\\<chi> a) = cnj (\\<chi> a)\"\n    by (auto simp add: inv_character_def principal_char_def divide_simps mult.commute)\n  finally show \"\\<chi> (inv a) = cnj (\\<chi> a)\" .\nqed\n\nend\n\nlemma (in finite_comm_group) character_principal [simp, intro]: \"character G (principal_char G)\"\n  by standard (auto simp: principal_char_def)\n\nlemmas [simp,intro] = finite_comm_group.character_principal\n\nlemma character_ext:\n  assumes \"character G \\<chi>\" \"character G \\<chi>'\" \"\\<And>x. x \\<in> carrier G \\<Longrightarrow> \\<chi> x = \\<chi>' x\"\n  shows   \"\\<chi> = \\<chi>'\"\nproof\n  fix x :: 'a\n  show \"\\<chi> x = \\<chi>' x\"\n    using assms by (cases \"x \\<in> carrier G\") (auto simp: character.char_eq_0)\nqed\n\nlemma character_mult [intro]: \n  assumes \"character G \\<chi>\" \"character G \\<chi>'\"\n  shows   \"character G (\\<lambda>x. \\<chi> x * \\<chi>' x)\"\nproof -\n  interpret \\<chi>: character G \\<chi> by fact\n  interpret \\<chi>': character G \\<chi>' by fact\n  show ?thesis by standard (auto simp: \\<chi>.char_eq_0)\nqed\n \n\nlemma character_inv_character_iff [simp]: \"character G (inv_character \\<chi>) \\<longleftrightarrow> character G \\<chi>\"\nproof\n  assume \"character G (inv_character \\<chi>)\"\n  from character.inv_character [OF this] show \"character G \\<chi>\" by simp\nqed (auto simp: character.inv_character)\n\n\ndefinition characters :: \"('a, 'b) monoid_scheme \\<Rightarrow> ('a \\<Rightarrow> complex) set\"  where\n  \"characters G = {\\<chi>. character G \\<chi>}\"\n\n\nsubsection \\<open>The Character group\\<close>\n\ntext \\<open>\n  The characters of a finite abelian group $G$ form another group $\\widehat{G}$, which is called\n  its Pontryagin dual group. This generalises to the more general setting of locally compact\n  abelian groups, but we restrict ourselves to the finite setting because it is much easier.\n\\<close>\ndefinition Characters :: \"('a, 'b) monoid_scheme \\<Rightarrow> ('a \\<Rightarrow> complex) monoid\"\n  where \"Characters G = \\<lparr> carrier = characters G, mult = (\\<lambda>\\<chi>\\<^sub>1 \\<chi>\\<^sub>2 k. \\<chi>\\<^sub>1 k * \\<chi>\\<^sub>2 k),\n                          one = principal_char G \\<rparr>\"\n\nlemma carrier_Characters: \"carrier (Characters G) = characters G\"\n  by (simp add: Characters_def)\n\nlemma one_Characters: \"one (Characters G) = principal_char G\"\n  by (simp add: Characters_def)\n\nlemma mult_Characters: \"mult (Characters G) \\<chi>\\<^sub>1 \\<chi>\\<^sub>2 = (\\<lambda>a. \\<chi>\\<^sub>1 a * \\<chi>\\<^sub>2 a)\"\n  by (simp add: Characters_def)\n\ncontext finite_comm_group\nbegin\n\nsublocale principal: character G \"principal_char G\" ..\n\nlemma finite_characters [intro]: \"finite (characters G)\"\nproof (rule finite_subset)\n  show \"characters G \\<subseteq> (\\<lambda>f x. if x \\<in> carrier G then f x else 0) ` \n                          Pi\\<^sub>E (carrier G) (\\<lambda>_. {z. z ^ order G = 1})\" (is \"_ \\<subseteq> ?h ` ?Chars\")\n  proof (intro subsetI, goal_cases)\n    case (1 \\<chi>)\n    then interpret \\<chi>: character G \\<chi> by (simp add: characters_def)\n    have \"?h (restrict \\<chi> (carrier G)) \\<in> ?h ` ?Chars\"\n      by (intro imageI) (auto simp: \\<chi>.char_root')\n    also have \"?h (restrict \\<chi> (carrier G)) = \\<chi>\" by (simp add: fun_eq_iff \\<chi>.char_eq_0)\n    finally show ?case .\n  qed\n  show \"finite (?h ` ?Chars)\"\n    by (intro finite_imageI finite_PiE finite_roots_unity) (auto simp: Suc_le_eq)\nqed\n\nlemma finite_comm_group_Characters [intro]: \"finite_comm_group (Characters G)\"\nproof\n  fix \\<chi> \\<chi>' assume *: \"\\<chi> \\<in> carrier (Characters G)\" \"\\<chi>' \\<in> carrier (Characters G)\"\n  from * interpret \\<chi>: character G \\<chi> by (simp_all add: characters_def carrier_Characters)\n  from * interpret \\<chi>': character G \\<chi>' by (simp_all add: characters_def  carrier_Characters)\n  have \"character G (\\<lambda>k. \\<chi> k * \\<chi>' k)\"\n    by standard (insert *, simp_all add: \\<chi>.char_eq_0 one_Characters \n                                         mult_Characters characters_def  carrier_Characters)\n  thus \"\\<chi> \\<otimes>\\<^bsub>Characters G\\<^esub> \\<chi>' \\<in> carrier (Characters G)\"\n    by (simp add: characters_def one_Characters mult_Characters  carrier_Characters)\nnext\n  have \"character G (principal_char G)\" ..\n  thus \"\\<one>\\<^bsub>Characters G\\<^esub> \\<in> carrier (Characters G)\"\n    by (simp add: characters_def one_Characters mult_Characters  carrier_Characters)\nnext\n  fix \\<chi> assume *: \"\\<chi> \\<in> carrier (Characters G)\"\n  from * interpret \\<chi>: character G \\<chi> by (simp_all add: characters_def carrier_Characters)\n  show \"\\<one>\\<^bsub>Characters G\\<^esub> \\<otimes>\\<^bsub>Characters G\\<^esub> \\<chi> = \\<chi>\" and \"\\<chi> \\<otimes>\\<^bsub>Characters G\\<^esub> \\<one>\\<^bsub>Characters G\\<^esub> = \\<chi>\"\n    by (simp_all add: principal_char_def fun_eq_iff \\<chi>.char_eq_0 one_Characters mult_Characters)\nnext\n  have \"\\<chi> \\<in> Units (Characters G)\" if \"\\<chi> \\<in> carrier (Characters G)\" for \\<chi>\n  proof -\n    from that interpret \\<chi>: character G \\<chi> by (simp add: characters_def carrier_Characters)\n    have \"\\<chi> \\<otimes>\\<^bsub>Characters G\\<^esub> inv_character \\<chi> = \\<one>\\<^bsub>Characters G\\<^esub>\" and \n         \"inv_character \\<chi> \\<otimes>\\<^bsub>Characters G\\<^esub> \\<chi> = \\<one>\\<^bsub>Characters G\\<^esub>\"\n      by (simp_all add: \\<chi>.mult_inv_character mult_ac one_Characters mult_Characters)\n    moreover from that have \"inv_character \\<chi> \\<in> carrier (Characters G)\"\n      by (simp add: characters_def carrier_Characters)\n    ultimately show ?thesis using that unfolding Units_def by blast\n  qed\n  thus \"carrier (Characters G) \\<subseteq> Units (Characters G)\" ..\nqed (auto simp: principal_char_def one_Characters mult_Characters carrier_Characters)\n\nend\n\nlemma (in character) character_in_order_1:\n  assumes \"order G = 1\"\n  shows   \"\\<chi> = principal_char G\"\nproof -\n  from assms have \"card (carrier G - {\\<one>}) = 0\"\n    by (subst card_Diff_subset) (auto simp: order_def)\n  hence \"carrier G - {\\<one>} = {}\"\n    by (subst (asm) card_0_eq) auto\n  hence \"carrier G = {\\<one>}\" by auto\n  thus ?thesis\n    by (intro ext) (simp_all add: principal_char_def char_eq_0)\nqed\n\nlemma (in finite_comm_group) characters_in_order_1:\n  assumes \"order G = 1\"\n  shows   \"characters G = {principal_char G}\"\n  using character.character_in_order_1 [OF _ assms] by (auto simp: characters_def)\n\nlemma (in character) inv_Characters: \"inv\\<^bsub>Characters G\\<^esub> \\<chi> = inv_character \\<chi>\"\nproof -\n  interpret Characters: finite_comm_group \"Characters G\" ..\n  have \"character G \\<chi>\" ..\n  thus ?thesis\n    by (intro Characters.inv_equality) \n       (auto simp: characters_def mult_inv_character mult_ac \n                   carrier_Characters one_Characters mult_Characters)\nqed\n\nlemma (in finite_comm_group) inv_Characters': \n  \"\\<chi> \\<in> characters G \\<Longrightarrow> inv\\<^bsub>Characters G\\<^esub> \\<chi> = inv_character \\<chi>\"\n  by (intro character.inv_Characters) (auto simp: characters_def)\n\nlemmas (in finite_comm_group) Characters_simps = \n  carrier_Characters mult_Characters one_Characters inv_Characters'\n\nlemma inv_Characters': \"\\<chi> \\<in> characters G \\<Longrightarrow> inv\\<^bsub>Characters G\\<^esub> \\<chi> = inv_character \\<chi>\"\n  using character.inv_Characters[of G \\<chi>] by (simp add: characters_def)\n\n\n\nsubsection \\<open>Relationship of characters and adjoining\\<close>\n\ntext \\<open>\n  We now study the set of characters of two subgroups $H$ and $H_x$, where $x\\in G\\setminus H$\n  and $H_x$ is the smallest supergroup of $H$ that contains \\<open>x\\<close>.\n\n  Let $n$ denote the indicator of \\<open>x\\<close> in \\<open>H\\<close> (i.\\,e.\\ the smallest positive number such\n  that $x^n\\in H$) We show that any character on $H_x$ corresponds to a pair of\n  a character \\<open>\\<chi>\\<close> on \\<open>H\\<close> and an $n$-th root of $\\chi(x^n)$ (or, equivalently, an $n$-th\n  root of unity).\n\\<close>\n\ncontext finite_comm_group_adjoin\nbegin\n\nlemma lower_character:\n  assumes \"character (G\\<lparr>carrier := adjoin G H a\\<rparr>) \\<chi>\" \n    (is \"character ?G'' _\")\n  shows   \"character (G\\<lparr>carrier := H\\<rparr>) (\\<lambda>x. if x \\<in> H then \\<chi> x else 0)\" (is \"character ?G' ?\\<chi>\")\nproof -\n  have \"subgroup H G\" ..\n  then interpret G'': finite_comm_group ?G'' \n    by (intro subgroup_imp_finite_comm_group adjoin_subgroup) auto\n  from \\<open>subgroup H G\\<close> interpret G': finite_comm_group ?G'\n    by (intro subgroup_imp_finite_comm_group adjoin_subgroup) auto\n  from assms interpret character ?G'' \\<chi>\n    by (simp add: characters_def)\n  show ?thesis\n  proof\n    fix x y assume \"x \\<in> carrier ?G'\" \"y \\<in> carrier ?G'\"\n    thus \"?\\<chi> (x \\<otimes>\\<^bsub>?G'\\<^esub> y) = ?\\<chi> x * ?\\<chi> y\"\n      using char_mult[of x y] mem_adjoin[OF \\<open>subgroup H G\\<close>] by auto\n  qed (insert char_one, auto simp del: char_one)\nqed\n\ndefinition lift_character :: \"('a \\<Rightarrow> complex) \\<times> complex \\<Rightarrow> ('a \\<Rightarrow> complex)\" where\n  \"lift_character = \n     (\\<lambda>(\\<chi>,z) x. if x \\<in> adjoin G H a then \\<chi> (fst (unadjoin x)) * z ^ snd (unadjoin x) else 0)\"\n\nlemma lift_character:\n  defines \"h \\<equiv> subgroup_indicator G H a\"\n  assumes \"character (G\\<lparr>carrier := H\\<rparr>) \\<chi>\" (is \"character ?G' _\") and \"z ^ h = \\<chi> (a [^] h)\"\n  shows   \"character (G\\<lparr>carrier := adjoin G H a\\<rparr>) (lift_character (\\<chi>, z))\" (is \"character ?G'' _\")\nproof -\n  interpret H': subgroup \"adjoin G H a\" G by (intro adjoin_subgroup is_subgroup) auto\n  have \"subgroup H G\" ..\n  then interpret G'': finite_comm_group ?G''\n    by (intro subgroup_imp_finite_comm_group adjoin_subgroup) auto\n  from \\<open>subgroup H G\\<close> interpret G': finite_comm_group ?G'\n    by (intro subgroup_imp_finite_comm_group adjoin_subgroup) auto\n  from assms interpret character ?G' \\<chi> by (simp add: characters_def)\n  show ?thesis\n  proof (standard, goal_cases)\n    case 1\n    from char_one show ?case\n      by (auto simp: lift_character_def simp del: char_one)\n  next\n    case (2 x)\n    thus ?case by (auto simp: lift_character_def)\n  next\n    case (3 x y)\n    from 3(1) obtain x' k where x: \"x' \\<in> H\" \"x = x' \\<otimes> a [^] k\" and k: \"k < h\"\n      by (auto simp: adjoin_def h_def)\n    from 3(2) obtain y' l where y: \"y' \\<in> H\" \"y = y' \\<otimes> a [^] l\" and l: \"l < h\"\n      by (auto simp: adjoin_def h_def)\n    have [simp]: \"unadjoin x = (x', k)\" using x k by (intro unadjoin_unique') (auto simp: h_def)\n    have [simp]: \"unadjoin y = (y', l)\" using y l by (intro unadjoin_unique') (auto simp: h_def)\n    have char_mult': \"\\<chi> (x \\<otimes> y) = \\<chi> x * \\<chi> y\" if \"x \\<in> H\" \"y \\<in> H\" for x y\n      using char_mult[of x y] that by simp\n    have char_power': \"\\<chi> (x [^] n) = \\<chi> x ^ n\" if \"x \\<in> H\" for x n\n      using that char_one by (induction n) (simp_all add: char_mult' del: char_one)\n\n    define r where \"r = (k + l) mod h\"\n    have r: \"r < subgroup_indicator G H a\" unfolding h_def r_def\n      by (intro mod_less_divisor subgroup_indicator_pos is_subgroup) auto\n    define zz where \"zz = (a [^] h) [^] ((k + l) div h)\"\n    have [simp]: \"zz \\<in> H\" unfolding zz_def h_def \n      by (rule nat_pow_closed) (auto intro: pow_subgroup_indicator is_subgroup)\n    have \"a [^] k \\<otimes> a [^] l = zz \\<otimes> a [^] r\"\n      by (simp add: nat_pow_mult zz_def nat_pow_pow r_def)\n    with x y r have \"unadjoin (x \\<otimes> y) = (x' \\<otimes> y' \\<otimes> zz, r)\"\n      by (intro unadjoin_unique' m_closed) (auto simp: m_ac)\n    hence \"lift_character (\\<chi>, z) (x \\<otimes>\\<^bsub>?G''\\<^esub> y) = \\<chi> (x' \\<otimes> y' \\<otimes> zz) * z ^ r\"\n      using 3 by (simp add: lift_character_def)\n    also have \"\\<dots> = \\<chi> x' * \\<chi> y' * (\\<chi> zz * z ^ r)\"\n      using x(1) y(1) by (simp add: char_mult' char_power')\n    also have \"\\<chi> zz * z ^ r = z ^ (h * ((k + l) div h) + r)\"\n      unfolding h_def zz_def using \\<open>subgroup H G\\<close> assms(3)[symmetric] \n      by (subst char_power') (auto simp: pow_subgroup_indicator h_def power_mult power_add)\n    also have \"h * ((k + l) div h) + r = k + l\" by (simp add: r_def)\n    also have \"\\<chi> x' * \\<chi> y' * z ^ (k + l) = lift_character (\\<chi>,z) x * lift_character (\\<chi>,z) y\"\n      using 3 by (simp add: lift_character_def power_add)\n    finally show ?case .\n  qed\nqed\n\nlemma lower_character_lift_character:\n  assumes \"\\<chi> \\<in> characters (G\\<lparr>carrier := H\\<rparr>)\"\n  shows   \"(\\<lambda>x. if x \\<in> H then lift_character (\\<chi>, z) x else 0) = \\<chi>\" (is ?th1)\n          \"lift_character (\\<chi>, z) a = z\" (is ?th2)\nproof -\n  from assms interpret \\<chi>: character \"G\\<lparr>carrier := H\\<rparr>\" \\<chi> by (simp add: characters_def)\n  have char_mult: \"\\<chi> (x \\<otimes> y) = \\<chi> x * \\<chi> y\" if \"x \\<in> H\" \"y \\<in> H\" for x y\n    using \\<chi>.char_mult[of x y] that by simp\n  have char_power: \"\\<chi> (x [^] n) = \\<chi> x ^ n\" if \"x \\<in> H\" for x n\n    using \\<chi>.char_one that by (induction n) (simp_all add: char_mult)\n  show ?th1 using \\<chi>.char_eq_0 mem_adjoin[OF is_subgroup _ a_in_carrier]\n    by (auto simp: lift_character_def)\n  show ?th2 using \\<chi>.char_one is_subgroup\n    by (auto simp: lift_character_def adjoined_in_adjoin)\nqed\n\nlemma lift_character_lower_character:\n  assumes \"\\<chi> \\<in> characters (G\\<lparr>carrier := adjoin G H a\\<rparr>)\"\n  shows   \"lift_character (\\<lambda>x. if x \\<in> H then \\<chi> x else 0, \\<chi> a) = \\<chi>\"\nproof -\n  let ?G' = \"G\\<lparr>carrier := adjoin G H a\\<rparr>\"\n  from assms interpret \\<chi>: character ?G' \\<chi> by (simp add: characters_def)\n  show ?thesis\n  proof (rule ext, goal_cases)\n    case (1 x)\n    show ?case\n    proof (cases \"x \\<in> adjoin G H a\")\n      case True\n      note * = unadjoin_correct[OF this]\n      interpret H': subgroup \"adjoin G H a\" G\n        by (intro adjoin_subgroup is_subgroup a_in_carrier)\n      have \"x = fst (unadjoin x) \\<otimes>\\<^bsub>?G'\\<^esub> a [^]\\<^bsub>?G'\\<^esub> snd (unadjoin x)\" \n        using *(3) by (simp add: nat_pow_def)\n      also have \"\\<chi> \\<dots> = \\<chi> (fst (unadjoin x)) * \\<chi> (a [^]\\<^bsub>?G'\\<^esub> snd (unadjoin x))\"\n        using * is_subgroup by (intro \\<chi>.char_mult) \n                               (auto simp: nat_pow_modify_carrier mem_adjoin adjoined_in_adjoin)\n      also have \"\\<chi> (a [^]\\<^bsub>?G'\\<^esub> snd (unadjoin x)) = \\<chi> a ^ snd (unadjoin x)\"\n        using is_subgroup by (intro \\<chi>.char_power) (auto simp: adjoined_in_adjoin)\n      finally show ?thesis using True * by (auto simp: lift_character_def)\n    qed (auto simp: lift_character_def \\<chi>.char_eq_0)\n  qed\nqed\n\nlemma lift_character_unchanged [simp]:\n  assumes \"x \\<in> H\"\n  shows   \"lift_character \\<chi>z x = fst \\<chi>z x\"\n  using assms mem_adjoin[of H x a] is_subgroup\n  by (cases \\<chi>z) (auto simp: lift_character_def)\n\nlemma lift_character_adjoined [simp]:\n \"character (G\\<lparr>carrier := H\\<rparr>) (fst \\<chi>z) \\<Longrightarrow> lift_character \\<chi>z a = snd \\<chi>z\"\n  using is_subgroup character.char_one[of \"G\\<lparr>carrier := H\\<rparr>\"]\n  by (cases \\<chi>z) (auto simp: lift_character_def adjoined_in_adjoin character.char_one)\n\nlemma bij_betw_characters_adjoin:\n  defines \"h \\<equiv> subgroup_indicator G H a\"\n  shows \"bij_betw lift_character\n                  (SIGMA \\<chi>:characters (G\\<lparr>carrier := H\\<rparr>). {z. z ^ h = \\<chi> (a [^] h)})\n                  (characters (G\\<lparr>carrier := adjoin G H a\\<rparr>))\"\nproof (rule bij_betwI[where ?g = \"\\<lambda>\\<chi>. (\\<lambda>x. if x \\<in> H then \\<chi> x else 0, \\<chi> a)\"], goal_cases)\n  case 1\n  show ?case by (auto simp: characters_def h_def intro!: lift_character)\nnext\n  case 2\n  show ?case unfolding characters_def\n  proof (safe, goal_cases)\n    case (1 \\<chi>)\n    thus ?case unfolding h_def by (rule lower_character)\n  next\n    case (2 \\<chi>)\n    interpret \\<chi>: character \"G\\<lparr>carrier := adjoin G H a\\<rparr>\" \\<chi> by fact\n    have [simp]: \"\\<chi> (a [^] n) = \\<chi> a ^ n\" for n using \\<chi>.char_power[of a n] is_subgroup \n      by (auto simp: adjoined_in_adjoin nat_pow_def simp del: \\<chi>.char_power)\n    from is_subgroup a_in_carrier pow_subgroup_indicator show ?case\n      by (auto simp: h_def intro!: subgroup_indicator_pos \\<chi>.char_eq_0)\n  qed\nnext\n  case (3 w)\n  thus ?case using lower_character_lift_character[of \"fst w\" \"snd w\"]\n    by (auto cong: if_cong)\nnext\n  case (4 \\<chi>)\n  thus ?case by (rule lift_character_lower_character)\nqed\n\nend\n\n\nsubsection \\<open>Non-trivial facts about characters\\<close>\n\ncontext finite_comm_group\nbegin\n\ntext \\<open>\n  The following theorem is a very central one. It shows that any character on a subgroup \\<open>H\\<close> can\n  be extended to a character on the full group in exactly $[G : H]$ ways.\n\n  The proof is by induction; we start with \\<open>H\\<close> and then successively adjoin elements until we\n  have reached \\<open>G\\<close>. As we showed before, when we lift a character from \\<open>H\\<close> to $H_x$, we have\n  \\<open>n\\<close> choices to do so, where \\<open>n\\<close> is the indicator of \\<open>x\\<close> in \\<open>H\\<close>. Since $|H_x| = n |H|$, the\n  induction step is valid.\n\\<close>\ntheorem card_character_extensions:\n  assumes \"subgroup H G\" \"character (G\\<lparr>carrier := H\\<rparr>) \\<chi>\"\n  shows   \"card {\\<chi>'\\<in>characters G. \\<forall>x\\<in>H. \\<chi>' x = \\<chi> x} * card H = order G\"\n  using assms\nproof (induction rule: subgroup_adjoin_induct)\n  case (base )\n  have \"{\\<chi>' \\<in> characters (G\\<lparr>carrier := H\\<rparr>). \\<forall>x\\<in>H. \\<chi>' x = \\<chi> x} = {\\<chi>}\"\n    using base by (auto simp: fun_eq_iff characters_def intro: character_ext)\n  thus ?case using base by (simp add: order_def)\nnext\n  case (adjoin H' a )\n  interpret H': 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  interpret H': finite_comm_group_adjoin G H' a\n    using adjoin.hyps by unfold_locales auto\n\n  define h where \"h = subgroup_indicator G H' a\"\n  from adjoin have [simp]: \"h > 0\" unfolding h_def by (intro subgroup_indicator_pos) auto\n  define c where \"c = a [^] h\"\n  from adjoin have [simp]: \"c \\<in> H'\"\n    by (auto simp: c_def h_def pow_subgroup_indicator)\n\n  define C where \"C = (\\<lambda>H'. {\\<chi>'. \\<chi>' \\<in> characters (G\\<lparr>carrier := H'\\<rparr>) \\<and> (\\<forall>x\\<in>H. \\<chi>' x = \\<chi> x)})\"\n  define I where \"I = (\\<lambda>\\<chi>. {z::complex. z ^ h = \\<chi> c})\"\n  have [simp]: \"finite (C H')\"\n    by (rule finite_subset[OF _ H'.finite_characters]) (auto simp: C_def)\n\n  (* TODO: extract lemma *)\n  have \"bij_betw H'.lift_character (SIGMA \\<chi>:C H'. I \\<chi>) (C (adjoin G H' a))\"\n  proof (rule bij_betwI)\n    show \"H'.lift_character \\<in> Sigma (C H') I \\<rightarrow> C (adjoin G H' a)\"\n    proof safe\n      fix \\<chi> z assume *: \"\\<chi> \\<in> C H'\" \"z \\<in> I \\<chi>\"\n      have \"\\<forall>x\\<in>H. H'.lift_character (\\<chi>, z) x = \\<chi> x\"\n        using * adjoin.hyps by auto\n      with * show \"H'.lift_character (\\<chi>, z) \\<in> C (adjoin G H' a)\"\n        using H'.lift_character[of \\<chi> z]\n        by (auto simp: C_def I_def h_def c_def characters_def)\n    qed\n  next\n    show \"(\\<lambda>\\<chi>. (\\<lambda>x. if x \\<in> H' then \\<chi> x else 0, \\<chi> a)) \\<in> C (adjoin G H' a) \\<rightarrow> Sigma (C H') I\"\n    proof safe\n      fix \\<chi> assume \\<chi>: \"\\<chi> \\<in> C (adjoin G H' a)\"\n      thus \"(\\<lambda>xa. if xa \\<in> H' then \\<chi> xa else 0) \\<in> C H'\"\n        using H'.lower_character[of \\<chi>] adjoin.prems adjoin.hyps\n        by (auto simp: C_def characters_def character.char_eq_0)\n      have \"\\<chi> (a [^]\\<^bsub>G\\<lparr>carrier := adjoin G H' a\\<rparr>\\<^esub> subgroup_indicator (G\\<lparr>carrier := adjoin G H' a\\<rparr>) H' a) =\n              \\<chi> a ^ subgroup_indicator (G\\<lparr>carrier := adjoin G H' a\\<rparr>) H' a\"\n        using \\<chi> adjoin.prems adjoin.hyps\n        by (intro character.char_power) (auto simp: C_def characters_def adjoined_in_adjoin)\n      hence \"\\<chi> (a [^] h) = \\<chi> a ^ subgroup_indicator G H' a\"\n        by (simp add: nat_pow_consistent [symmetric] h_def)\n      with \\<chi> show \"\\<chi> a \\<in> I (\\<lambda>xa. if xa \\<in> H' then \\<chi> xa else 0)\"\n        using adjoin.hyps adjoin.prems\n        by (auto simp: I_def C_def characters_def character.char_power character.char_eq_0\n                       pow_subgroup_indicator h_def c_def)\n    qed\n  next\n    fix \\<chi>z assume *: \"\\<chi>z \\<in> (SIGMA \\<chi>:C H'. I \\<chi>)\"\n    obtain \\<chi> z where [simp]: \"\\<chi>z = (\\<chi>, z)\" by (cases \\<chi>z)\n    from * show \"(\\<lambda>xa. if xa \\<in> H' then H'.lift_character \\<chi>z xa else 0, H'.lift_character \\<chi>z a) = \\<chi>z\"\n      using H'.lower_character_lift_character[of \\<chi> z] by (auto simp: C_def cong: if_cong)\n  next\n    fix \\<chi> assume \"\\<chi> \\<in> C (adjoin G H' a)\"\n    thus \"H'.lift_character (\\<lambda>x. if x \\<in> H' then \\<chi> x else 0, \\<chi> a) = \\<chi>\"\n      using H'.lift_character_lower_character[of \\<chi>] by (auto simp: C_def)\n  qed\n\n  hence \"card (SIGMA \\<chi>:C H'. I \\<chi>) = card (C (adjoin G H' a))\"\n    by (rule bij_betw_same_card)\n  also have \"card (SIGMA \\<chi>:C H'. I \\<chi>) = (\\<Sum>a\\<in>C H'. card (I a))\"\n    by (intro card_SigmaI) (auto simp: I_def)\n  also have \"\\<dots> = (\\<Sum>a\\<in>C H'. h)\"\n  proof (intro sum.cong refl, goal_cases)\n    case (1 \\<chi>)\n    then interpret character \"G\\<lparr>carrier := H'\\<rparr>\" \\<chi> by (simp add: characters_def C_def)\n    have \"\\<chi> c \\<noteq> 0\"\n      by (subst char_eq_0_iff) (auto simp: c_def h_def intro!: pow_subgroup_indicator adjoin)\n    thus ?case by (simp add: I_def card_nth_roots)\n  qed\n  also have \"\\<dots> = h * card (C H')\" by simp\n  finally have \"card (C (adjoin G H' a)) * card H = h * (card (C H') * card H)\"\n    by simp\n  also have \"card (C H') * card H = card H'\"\n    unfolding C_def using adjoin.prems by (subst adjoin.IH) (auto simp: order_def)\n  also have \"h * card H' = card (adjoin G H' a)\"\n    using adjoin.hyps by (subst card_adjoin) (auto simp: h_def)\n  also have \"\\<dots> = order (G\\<lparr>carrier := adjoin G H' a\\<rparr>)\"\n    by (simp add: order_def)\n  finally show ?case by (simp add: C_def)\nqed\n\ntext \\<open>\n  By taking \\<open>H\\<close> to be the trivial subgroup, we obtain that the number of characters\n  on \\<open>G\\<close> is precisely the order of \\<open>G\\<close> itself, i.\\,e.\\ $|\\widehat{G}|=|G|$.\n\\<close>\ncorollary card_characters: \"card (characters G) = order G\"\nproof -\n  define \\<chi> where \"\\<chi> = principal_char (G\\<lparr>carrier := {\\<one>}\\<rparr>)\"\n  interpret triv: subgroup \"{\\<one>}\"\n    by standard auto\n  interpret triv: finite_comm_group \"G\\<lparr>carrier := {\\<one>}\\<rparr>\"\n    by (rule subgroup_imp_finite_comm_group) (rule triv.is_subgroup)\n  \n  have \"card {\\<chi>'\\<in>characters G. \\<forall>x\\<in>{\\<one>}. \\<chi>' x = \\<chi> x} * card {\\<one>} = order G\"\n    unfolding \\<chi>_def\n    by (intro card_character_extensions triv.is_subgroup triv.character_principal)\n  also have \"{\\<chi>'\\<in>characters G. \\<forall>x\\<in>{\\<one>}. \\<chi>' x = \\<chi> x} = characters G\"\n    by (auto simp: characters_def character.char_one principal_char_def \\<chi>_def)\n  finally show ?thesis by simp\nqed\n\nlemma order_Characters [simp]: \"order (Characters G) = order G\"\n  by (simp add: order_def card_characters carrier_Characters)\n\ntext \\<open>\n  It also follows as a simple corollary that any character on \\<open>H\\<close> \\<^emph>\\<open>can\\<close> be extended\n  to a character on \\<open>G\\<close>.\n\\<close>\ncorollary character_extension_exists:\n  assumes \"subgroup H G\" \"character (G\\<lparr>carrier := H\\<rparr>) \\<chi>\"\n  obtains \\<chi>' where \"character G \\<chi>'\" and \"\\<And>x. x \\<in> H \\<Longrightarrow> \\<chi>' x = \\<chi> x\"\nproof -\n  have \"card {\\<chi>'\\<in>characters G. \\<forall>x\\<in>H. \\<chi>' x = \\<chi> x} * card H = order G\"\n    by (intro card_character_extensions assms)\n  hence \"card {\\<chi>'\\<in>characters G. \\<forall>x\\<in>H. \\<chi>' x = \\<chi> x} \\<noteq> 0\"\n    using order_gt_0 by (intro notI) auto\n  hence \"{\\<chi>'\\<in>characters G. \\<forall>x\\<in>H. \\<chi>' x = \\<chi> x} \\<noteq> {}\"\n    by (intro notI) simp\n  then obtain \\<chi>' where \"character G \\<chi>'\" and \"\\<And>x. x \\<in> H \\<Longrightarrow> \\<chi>' x = \\<chi> x\"\n    unfolding characters_def by blast\n  thus ?thesis using that[of \\<chi>'] by blast\nqed\n\ntext \\<open>\n  Lastly, we can also show that for each $x\\in H$ of order $n > 1$ and each \\<open>n\\<close>-th root of\n  unity \\<open>z\\<close>, there exists a character \\<open>\\<chi>\\<close> on \\<open>G\\<close> such that $\\chi(x) = z$.\n\\<close>\ncorollary character_with_value_exists:\n  assumes \"x \\<in> carrier G\" and \"x \\<noteq> \\<one>\" and \"z ^ ord x = 1\"\n  obtains \\<chi> where \"character G \\<chi>\" and \"\\<chi> x = z\"\nproof -\n  define triv where \"triv = G\\<lparr>carrier := {\\<one>}\\<rparr>\"\n  interpret triv: subgroup \"{\\<one>}\"\n    by standard auto\n  interpret triv: finite_comm_group \"G\\<lparr>carrier := {\\<one>}\\<rparr>\"\n    by (rule subgroup_imp_finite_comm_group) (rule triv.is_subgroup)\n  interpret H: finite_comm_group_adjoin G \"{\\<one>}\" x\n    using assms by unfold_locales auto\n\n  define h where \"h = subgroup_indicator G {\\<one>} x\"\n  have x_pow_h: \"x [^] h = \\<one>\"\n    using pow_subgroup_indicator[OF triv.is_subgroup assms(1)] by (simp add: h_def)\n  have \"h > 0\"\n    using subgroup_indicator_pos[OF triv.is_subgroup assms(1)] by (simp add: h_def)\n  have [simp]: \"ord x = h\"\n    using x_pow_h triv.is_subgroup assms \\<open>h > 0\\<close> unfolding h_def\n    by (intro antisym subgroup_indicator_le_ord ord_min) auto\n\n  define \\<chi> where \"\\<chi> = principal_char triv\"\n  define \\<chi>' where \"\\<chi>' = H.lift_character (\\<chi>, z)\"\n  have \"subgroup (adjoin G {\\<one>} x) G\"\n    by (intro adjoin_subgroup triv.is_subgroup assms)\n  moreover have \\<chi>': \"character (G\\<lparr>carrier := adjoin G {\\<one>} x\\<rparr>) \\<chi>'\"\n    using H.lift_character[of \\<chi> z] triv.character_principal assms x_pow_h\n    by (auto simp: \\<chi>'_def \\<chi>_def principal_char_def triv_def h_def)\n  ultimately obtain \\<chi>'' where \\<chi>'': \"character G \\<chi>''\" \"\\<And>y. y \\<in> adjoin G {\\<one>} x \\<Longrightarrow> \\<chi>'' y = \\<chi>' y\"\n    by (erule character_extension_exists)\n  moreover {\n    have \"\\<chi>'' x = \\<chi>' x\"\n      using \\<chi>''(2)[of x] assms triv.is_subgroup by (auto simp: adjoined_in_adjoin)\n    also have \"\\<chi>' x = z\"\n      unfolding \\<chi>'_def by (subst H.lift_character_adjoined) (simp_all add: \\<chi>_def triv_def)\n    finally have \"\\<chi>'' x = z\" .\n  }\n  ultimately show ?thesis using that[of \\<chi>''] by blast\nqed\n\ntext \\<open>\n  In particular, for any \\<open>x\\<close> that is not the identity element, there exists a character \\<open>\\<chi>\\<close>\n  such that $\\chi(x)\\neq 1$.\n\\<close>\ncorollary character_neq_1_exists:\n  assumes \"x \\<in> carrier G\" and \"x \\<noteq> \\<one>\"\n  obtains \\<chi> where \"character G \\<chi>\" and \"\\<chi> x \\<noteq> 1\"\nproof -\n  define z where \"z = cis (2 * pi / ord x)\"\n  have z_pow_h: \"z ^ ord x = 1\"\n    by (auto simp: z_def DeMoivre)\n\n  from assms have \"ord x \\<ge> 1\" by (intro ord_ge_1) auto\n  moreover have \"ord x \\<noteq> 1\"\n    using pow_ord_eq_1[of x] assms fin by (intro notI) simp_all\n  ultimately have \"ord x > 1\" by linarith\n\n  have [simp]: \"z \\<noteq> 1\"\n  proof\n    assume \"z = 1\"\n    have \"bij_betw (\\<lambda>k. cis (2 * pi * real k / real (ord x))) {..<ord x} {z. z ^ ord x = 1}\"\n      using \\<open>ord x > 1\\<close> by (intro bij_betw_roots_unity) auto\n    hence inj: \"inj_on (\\<lambda>k. cis (2 * pi * real k / real (ord x))) {..<ord x}\"\n      by (auto simp: bij_betw_def)\n    have \"0 = (1 :: nat)\"\n      using \\<open>z = 1\\<close> and \\<open>ord x > 1\\<close> by (intro inj_onD[OF inj]) (auto simp: z_def)\n    thus False by simp\n  qed\n\n  obtain \\<chi> where \"character G \\<chi>\" and \"\\<chi> x = z\"\n    using character_with_value_exists[OF assms z_pow_h] .\n  thus ?thesis using that[of \\<chi>] by simp\nqed \n\nend\n\n\nsubsection \\<open>The first orthogonality relation\\<close>\n\ntext \\<open>\n  The entries of any non-principal character sum to 0.\n\\<close>\ntheorem (in character) sum_character:\n  \"(\\<Sum>x\\<in>carrier G. \\<chi> x) = (if \\<chi> = principal_char G then of_nat (order G) else 0)\"\nproof (cases \"\\<chi> = principal_char G\")\n  case True\n  hence \"(\\<Sum>x\\<in>carrier G. \\<chi> x) = (\\<Sum>x\\<in>carrier G. 1)\"\n    by (intro sum.cong) (auto simp: principal_char_def)\n  also have \"\\<dots> = order G\" by (simp add: order_def)\n  finally show ?thesis using True by simp\nnext\n  case False\n  define S where \"S = (\\<Sum>x\\<in>carrier G. \\<chi> x)\"\n  from False obtain y where y: \"y \\<in> carrier G\" \"\\<chi> y \\<noteq> 1\"\n    by (auto simp: principal_char_def fun_eq_iff char_eq_0_iff split: if_splits)\n  from y have \"S = (\\<Sum>x\\<in>carrier G. \\<chi> (y \\<otimes> x))\" unfolding S_def\n    by (intro sum.reindex_bij_betw [symmetric] bij_betw_mult_left)\n  also have \"\\<dots> = (\\<Sum>x\\<in>carrier G. \\<chi> y * \\<chi> x)\"\n    by (intro sum.cong refl char_mult y)\n  also have \"\\<dots> = \\<chi> y * S\" by (simp add: S_def sum_distrib_left)\n  finally have \"(\\<chi> y - 1) * S = 0\" by (simp add: algebra_simps)\n  with y have \"S = 0\" by simp\n  with False show ?thesis by (simp add: S_def)\nqed\n\ncorollary (in finite_comm_group) character_orthogonality1:\n  assumes \"character G \\<chi>\" and \"character G \\<chi>'\"\n  shows   \"(\\<Sum>x\\<in>carrier G. \\<chi> x * cnj (\\<chi>' x)) = (if \\<chi> = \\<chi>' then of_nat (order G) else 0)\"\nproof -\n  define C where [simp]: \"C = Characters G\"\n  interpret C: finite_comm_group C unfolding C_def\n    by (rule finite_comm_group_Characters)\n  let ?\\<chi> = \"\\<lambda>x. \\<chi> x * inv_character \\<chi>' x\"\n  interpret character G \"\\<lambda>x. \\<chi> x * inv_character \\<chi>' x\"\n    by (intro character_mult character.inv_character assms)\n  have \"(\\<Sum>x\\<in>carrier G. \\<chi> x * cnj (\\<chi>' x)) = (\\<Sum>x\\<in>carrier G. ?\\<chi> x)\"\n    by (intro sum.cong) (auto simp: inv_character_def)\n  also have \"\\<dots> = (if ?\\<chi> = principal_char G then of_nat (order G) else 0)\"\n    by (rule sum_character)\n  also have \"?\\<chi> = principal_char G \\<longleftrightarrow> \\<chi> \\<otimes>\\<^bsub>C\\<^esub> inv\\<^bsub>C\\<^esub> \\<chi>' = \\<one>\\<^bsub>C\\<^esub>\"\n    using assms by (simp add: Characters_simps characters_def)\n  also have \"\\<dots> \\<longleftrightarrow> \\<chi> = \\<chi>'\"\n  proof\n    assume \"\\<chi> \\<otimes>\\<^bsub>C\\<^esub> inv\\<^bsub>C\\<^esub> \\<chi>' = \\<one>\\<^bsub>C\\<^esub>\"\n    from C.inv_equality [OF this] and assms show \"\\<chi> = \\<chi>'\"\n      by (auto simp: characters_def Characters_simps)\n  next\n    assume *: \"\\<chi> = \\<chi>'\"\n    from assms show \"\\<chi> \\<otimes>\\<^bsub>C\\<^esub> inv\\<^bsub>C\\<^esub> \\<chi>' = \\<one>\\<^bsub>C\\<^esub>\" \n      by (subst *, intro C.r_inv) (auto simp: carrier_Characters characters_def)\n  qed\n  finally show ?thesis .\nqed\n\n\nsubsection \\<open>The isomorphism between a group and its double dual\\<close>\n\ntext \\<open>\n  Lastly, we show that the double dual of a finite abelian group is naturally isomorphic\n  to the original group via the obvious isomorphism $x\\mapsto (\\chi\\mapsto \\chi(x))$.\n  It is easy to see that this is a homomorphism and that it is injective. The fact \n  $|\\widehat{\\widehat{G}}| = |\\widehat{G}| = |G|$ then shows that it is also surjective.\n\\<close>\ncontext finite_comm_group\nbegin\n\ndefinition double_dual_iso :: \"'a \\<Rightarrow> ('a \\<Rightarrow> complex) \\<Rightarrow> complex\" where\n  \"double_dual_iso x = (\\<lambda>\\<chi>. if character G \\<chi> then \\<chi> x else 0)\"\n\nlemma double_dual_iso_apply [simp]: \"character G \\<chi> \\<Longrightarrow> double_dual_iso x \\<chi> = \\<chi> x\"\n  by (simp add: double_dual_iso_def)\n\nlemma character_double_dual_iso [intro]:\n  assumes x: \"x \\<in> carrier G\"\n  shows   \"character (Characters G) (double_dual_iso x)\"\nproof -\n  interpret G': finite_comm_group \"Characters G\"\n    by (rule finite_comm_group_Characters)\n  show \"character (Characters G) (double_dual_iso x)\"\n    using x by unfold_locales (auto simp: double_dual_iso_def characters_def Characters_def\n                                              principal_char_def character.char_eq_0)\nqed\n\nlemma double_dual_iso_mult [simp]:\n  assumes \"x \\<in> carrier G\" \"y \\<in> carrier G\"\n  shows   \"double_dual_iso (x \\<otimes> y) =\n             double_dual_iso x \\<otimes>\\<^bsub>Characters (Characters G)\\<^esub> double_dual_iso y\"\n  using assms by (auto simp: double_dual_iso_def Characters_def fun_eq_iff character.char_mult)\n\nlemma double_dual_iso_one [simp]:\n  \"double_dual_iso \\<one> = principal_char (Characters G)\"\n  by (auto simp: fun_eq_iff double_dual_iso_def principal_char_def\n                 carrier_Characters characters_def character.char_one)\n\nlemma inj_double_dual_iso: \"inj_on double_dual_iso (carrier G)\"\nproof -\n  interpret G': finite_comm_group \"Characters G\"\n    by (rule finite_comm_group_Characters)\n  interpret G'': finite_comm_group \"Characters (Characters G)\"\n    by (rule G'.finite_comm_group_Characters)\n  have hom: \"double_dual_iso \\<in> hom G (Characters (Characters G))\"\n    by (rule homI) (auto simp: carrier_Characters characters_def)\n  have inj_aux: \"x = \\<one>\"\n    if x: \"x \\<in> carrier G\" \"double_dual_iso x = \\<one>\\<^bsub>Characters (Characters G)\\<^esub>\" for x\n  proof (rule ccontr)\n    assume \"x \\<noteq> \\<one>\"\n    obtain \\<chi> where \\<chi>: \"character G \\<chi>\" \"\\<chi> x \\<noteq> 1\"\n      using character_neq_1_exists[OF x(1) \\<open>x \\<noteq> \\<one>\\<close>] .\n    from x have \"\\<forall>\\<chi>. (if \\<chi> \\<in> characters G then \\<chi> x else 0) = (if \\<chi> \\<in> characters G then 1 else 0)\"\n      by (auto simp: double_dual_iso_def Characters_def fun_eq_iff\n                     principal_char_def characters_def)\n    hence eq1: \"\\<forall>\\<chi>\\<in>characters G. \\<chi> x = 1\" by metis\n    with \\<chi> show False unfolding characters_def by auto\n  qed\n  thus ?thesis\n    using inj_aux hom is_group G''.is_group by (subst inj_on_one_iff') auto\nqed\n\nlemma double_dual_iso_eq_iff [simp]:\n  \"x \\<in> carrier G \\<Longrightarrow> y \\<in> carrier G \\<Longrightarrow> double_dual_iso x = double_dual_iso y \\<longleftrightarrow> x = y\"\n  by (auto dest: inj_onD[OF inj_double_dual_iso])\n\ntheorem double_dual_iso: \"double_dual_iso \\<in> iso G (Characters (Characters G))\"\nproof (rule isoI)\n  interpret G': finite_comm_group \"Characters G\"\n    by (rule finite_comm_group_Characters)\n  interpret G'': finite_comm_group \"Characters (Characters G)\"\n    by (rule G'.finite_comm_group_Characters)\n\n  show hom: \"double_dual_iso \\<in> hom G (Characters (Characters G))\"\n    by (rule homI) (auto simp: carrier_Characters characters_def)\n\n  show \"bij_betw double_dual_iso (carrier G) (carrier (Characters (Characters G)))\"\n    unfolding bij_betw_def\n  proof\n    show \"inj_on double_dual_iso (carrier G)\" by (fact inj_double_dual_iso)\n  next\n    show \"double_dual_iso ` carrier G = carrier (Characters (Characters G))\"\n    proof (rule card_subset_eq)\n      show \"finite (carrier (Characters (Characters G)))\"\n        by (fact G''.fin)\n    next\n      have \"card (carrier (Characters (Characters G))) = card (carrier G)\"\n        by (simp add: carrier_Characters G'.card_characters card_characters order_def)\n      also have \"\\<dots> = card (double_dual_iso ` carrier G)\"\n        by (intro card_image [symmetric] inj_double_dual_iso)\n      finally show \"card (double_dual_iso ` carrier G) =\n                      card (carrier (Characters (Characters G)))\" ..\n    next\n      show \"double_dual_iso ` carrier G \\<subseteq> carrier (Characters (Characters G))\"\n        using hom by (auto simp: hom_def)\n    qed\n  qed\nqed\n\nlemma double_dual_is_iso: \"Characters (Characters G) \\<cong> G\"\n  by (rule iso_sym) (use double_dual_iso in \\<open>auto simp: is_iso_def\\<close>)\n\ntext \\<open>\n  The second orthogonality relation follows from the first one via Pontryagin duality:\n\\<close>\ntheorem sum_characters:\n  assumes x: \"x \\<in> carrier G\"\n  shows   \"(\\<Sum>\\<chi>\\<in>characters G. \\<chi> x) = (if x = \\<one> then of_nat (order G) else 0)\"\nproof -\n  interpret G': finite_comm_group \"Characters G\"\n    by (rule finite_comm_group_Characters)\n  interpret x: character \"Characters G\" \"double_dual_iso x\"\n    using x by auto\n  from x.sum_character show ?thesis using double_dual_iso_eq_iff[of x \\<one>] x\n    by (auto simp: characters_def carrier_Characters simp del: double_dual_iso_eq_iff)\nqed\n\ncorollary character_orthogonality2:\n  assumes \"x \\<in> carrier G\" \"y \\<in> carrier G\"\n  shows   \"(\\<Sum>\\<chi>\\<in>characters G. \\<chi> x * cnj (\\<chi> y)) = (if x = y then of_nat (order G) else 0)\"\nproof -\n  from assms have \"(\\<Sum>\\<chi>\\<in>characters G. \\<chi> x * cnj (\\<chi> y)) = (\\<Sum>\\<chi>\\<in>characters G. \\<chi> (x \\<otimes> inv y))\"\n    by (intro sum.cong) (simp_all add: character.char_inv character.char_mult characters_def)\n  also from assms have \"\\<dots> = (if x \\<otimes> inv y = \\<one> then of_nat (order G) else 0)\"\n    by (intro sum_characters) auto\n  also from assms have \"x \\<otimes> inv y = \\<one> \\<longleftrightarrow> x = y\"\n    using inv_equality[of x \"inv y\"] by auto\n  finally show ?thesis .\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/Dirichlet_L/Multiplicative_Characters.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8670357735451835, "lm_q2_score": 0.8519527982093666, "lm_q1q2_score": 0.7386735534194419}}
{"text": "(*\n  Title:      HOL/Computational_Algebra/Formal_Laurent_Series.thy\n  Author:     Jeremy Sylvestre, University of Alberta (Augustana Campus)\n*)\n\n\nsection \\<open>A formalization of formal Laurent series\\<close>\n\ntheory Formal_Laurent_Series\nimports\n  Polynomial_FPS\nbegin\n\n\nsubsection \\<open>The type of formal Laurent series\\<close>\n\nsubsubsection \\<open>Type definition\\<close>\n\ntypedef (overloaded) 'a fls = \"{f::int \\<Rightarrow> 'a::zero. \\<forall>\\<^sub>\\<infinity> n::nat. f (- int n) = 0}\"\n  morphisms fls_nth Abs_fls\nproof\n  show \"(\\<lambda>x. 0) \\<in> {f::int \\<Rightarrow> 'a::zero. \\<forall>\\<^sub>\\<infinity> n::nat. f (- int n) = 0}\"\n    by simp\nqed\n\nsetup_lifting type_definition_fls\n\nunbundle fps_notation\nnotation fls_nth (infixl \"$$\" 75)\n\nlemmas fls_eqI = iffD1[OF fls_nth_inject, OF iffD2, OF fun_eq_iff, OF allI]\n\nlemma expand_fls_eq: \"f = g \\<longleftrightarrow> (\\<forall>n. f $$ n = g $$ n)\"\n  by (simp add: fls_nth_inject[symmetric] fun_eq_iff)\n\nlemma nth_Abs_fls [simp]: \"\\<forall>\\<^sub>\\<infinity>n. f (- int n) = 0 \\<Longrightarrow> Abs_fls f $$ n = f n\"\n by (simp add: Abs_fls_inverse[OF CollectI])\n\nlemmas nth_Abs_fls_finite_nonzero_neg_nth = nth_Abs_fls[OF iffD2, OF eventually_cofinite]\nlemmas nth_Abs_fls_ex_nat_lower_bound = nth_Abs_fls[OF iffD2, OF MOST_nat]\nlemmas nth_Abs_fls_nat_lower_bound = nth_Abs_fls_ex_nat_lower_bound[OF exI]\n\nlemma nth_Abs_fls_ex_lower_bound:\n  assumes \"\\<exists>N. \\<forall>n<N. f n = 0\"\n  shows   \"Abs_fls f $$ n = f n\"\nproof (intro nth_Abs_fls_ex_nat_lower_bound)\n  from assms obtain N::int where \"\\<forall>n<N. f n = 0\" by fast\n  hence \"\\<forall>n > (if N < 0 then nat (-N) else 0). f (-int n) = 0\" by auto\n  thus \"\\<exists>M. \\<forall>n>M. f (- int n) = 0\" by fast\nqed\n\nlemmas nth_Abs_fls_lower_bound = nth_Abs_fls_ex_lower_bound[OF exI]\n\nlemmas MOST_fls_neg_nth_eq_0 [simp] = CollectD[OF fls_nth]\nlemmas fls_finite_nonzero_neg_nth = iffD1[OF eventually_cofinite MOST_fls_neg_nth_eq_0]\n\nlemma fls_nth_vanishes_below_natE:\n  fixes   f :: \"'a::zero fls\"\n  obtains N :: nat\n  where   \"\\<forall>n>N. f$$(-int n) = 0\"\n  using   iffD1[OF MOST_nat MOST_fls_neg_nth_eq_0]\n  by      blast\n\nlemma fls_nth_vanishes_belowE:\n  fixes   f :: \"'a::zero fls\"\n  obtains N :: int\n  where   \"\\<forall>n<N. f$$n = 0\"\nproof-\n  obtain K :: nat where K: \"\\<forall>n>K. f$$(-int n) = 0\" by (elim fls_nth_vanishes_below_natE)\n  have \"\\<forall>n < -int K. f$$n = 0\"\n  proof clarify\n    fix n assume n: \"n < -int K\"\n    define m where \"m \\<equiv> nat (-n)\"\n    with n have \"m > K\" by simp\n    moreover from n m_def have \"f$$n = f $$ (-int m)\" by simp\n    ultimately show \"f $$ n = 0\" using K by simp\n  qed\n  thus \"(\\<And>N. \\<forall>n<N. f $$ n = 0 \\<Longrightarrow> thesis) \\<Longrightarrow> thesis\" by fast\nqed\n\n\nsubsubsection \\<open>Definition of basic zero, one, constant, X, and inverse X elements\\<close>\n\ninstantiation fls :: (zero) zero\nbegin\n  lift_definition zero_fls :: \"'a fls\" is \"\\<lambda>_. 0\" by simp\n  instance ..\nend\n\nlemma fls_zero_nth [simp]: \"0 $$ n = 0\"\n by (simp add: zero_fls_def)\n\nlemma fls_zero_eqI: \"(\\<And>n. f$$n = 0) \\<Longrightarrow> f = 0\"\n  by (fastforce intro: fls_eqI)\n\nlemma fls_nonzeroI: \"f$$n \\<noteq> 0 \\<Longrightarrow> f \\<noteq> 0\"\n  by auto\n\nlemma fls_nonzero_nth: \"f \\<noteq> 0 \\<longleftrightarrow> (\\<exists> n. f $$ n \\<noteq> 0)\"\n  using fls_zero_eqI by fastforce\n\nlemma fls_trivial_delta_eq_zero [simp]: \"b = 0 \\<Longrightarrow> Abs_fls (\\<lambda>n. if n=a then b else 0) = 0\"\n  by (intro fls_zero_eqI) simp\n\nlemma fls_delta_nth [simp]:\n  \"Abs_fls (\\<lambda>n. if n=a then b else 0) $$ n = (if n=a then b else 0)\"\n  using nth_Abs_fls_lower_bound[of a \"\\<lambda>n. if n=a then b else 0\"] by simp\n\ninstantiation fls :: (\"{zero,one}\") one\nbegin\n  lift_definition one_fls :: \"'a fls\" is \"\\<lambda>k. if k = 0 then 1 else 0\"\n    by (simp add: eventually_cofinite)\n  instance ..\nend\n\nlemma fls_one_nth [simp]:\n  \"1 $$ n = (if n = 0 then 1 else 0)\"\n  by (simp add: one_fls_def eventually_cofinite)\n\ninstance fls :: (zero_neq_one) zero_neq_one\nproof (standard, standard)\n  assume \"(0::'a fls) = (1::'a fls)\"\n  hence \"(0::'a fls) $$ 0 = (1::'a fls) $$ 0\" by simp\n  thus False by simp\nqed\n\ndefinition fls_const :: \"'a::zero \\<Rightarrow> 'a fls\"\n  where \"fls_const c \\<equiv> Abs_fls (\\<lambda>n. if n = 0 then c else 0)\"\n\nlemma fls_const_nth [simp]: \"fls_const c $$ n = (if n = 0 then c else 0)\"\n  by (simp add: fls_const_def eventually_cofinite)\n\nlemma fls_const_0 [simp]: \"fls_const 0 = 0\"\n  unfolding fls_const_def using fls_trivial_delta_eq_zero by fast\n\nlemma fls_const_nonzero: \"c \\<noteq> 0 \\<Longrightarrow> fls_const c \\<noteq> 0\"\n  using fls_nonzeroI[of \"fls_const c\" 0] by simp\n\nlemma fls_const_1 [simp]: \"fls_const 1 = 1\"\n  unfolding fls_const_def one_fls_def ..\n\nlift_definition fls_X :: \"'a::{zero,one} fls\"\n  is \"\\<lambda>n. if n = 1 then 1 else 0\"\n  by simp\n\nlemma fls_X_nth [simp]:\n  \"fls_X $$ n = (if n = 1 then 1 else 0)\"\n  by (simp add: fls_X_def)\n\nlemma fls_X_nonzero [simp]: \"(fls_X :: 'a :: zero_neq_one fls) \\<noteq> 0\"\n  by (intro fls_nonzeroI) simp\n\nlift_definition fls_X_inv :: \"'a::{zero,one} fls\"\n  is \"\\<lambda>n. if n = -1 then 1 else 0\"\n  by (simp add: eventually_cofinite)\n\nlemma fls_X_inv_nth [simp]:\n  \"fls_X_inv $$ n = (if n = -1 then 1 else 0)\"\n  by (simp add: fls_X_inv_def eventually_cofinite)\n\nlemma fls_X_inv_nonzero [simp]: \"(fls_X_inv :: 'a :: zero_neq_one fls) \\<noteq> 0\"\n  by (intro fls_nonzeroI) simp\n\n\nsubsection \\<open>Subdegrees\\<close>\n\nlemma unique_fls_subdegree:\n  assumes \"f \\<noteq> 0\"\n  shows   \"\\<exists>!n. f$$n \\<noteq> 0 \\<and> (\\<forall>m. f$$m \\<noteq> 0 \\<longrightarrow> n \\<le> m)\"\nproof-\n  obtain N::nat where N: \"\\<forall>n>N. f$$(-int n) = 0\" by (elim fls_nth_vanishes_below_natE)\n  define M where \"M \\<equiv> -int N\"\n  have M: \"\\<And>m. f$$m \\<noteq> 0 \\<Longrightarrow> M \\<le> m\"\n  proof-\n    fix m assume m: \"f$$m \\<noteq> 0\"\n    show \"M \\<le> m\"\n    proof (cases \"m<0\")\n      case True with m N M_def show ?thesis\n        using allE[OF N, of \"nat (-m)\" False] by force\n    qed (simp add: M_def)\n  qed\n  have \"\\<not> (\\<forall>k::nat. f$$(M + int k) = 0)\"\n  proof\n    assume above0: \"\\<forall>k::nat. f$$(M + int k) = 0\"\n    have \"f=0\"\n    proof (rule fls_zero_eqI)\n      fix n show \"f$$n = 0\"\n      proof (cases \"M \\<le> n\")\n        case True\n        define k where \"k = nat (n - M)\"\n        from True have \"n = M + int k\" by (simp add: k_def)\n        with above0 show ?thesis by simp\n      next\n        case False with M show ?thesis by auto\n      qed\n    qed\n    with assms show False by fast\n  qed\n  hence ex_k: \"\\<exists>k::nat. f$$(M + int k) \\<noteq> 0\" by fast\n  define k where \"k \\<equiv> (LEAST k::nat. f$$(M + int k) \\<noteq> 0)\"\n  define n where \"n \\<equiv> M + int k\"\n  from k_def n_def have fn: \"f$$n \\<noteq> 0\" using LeastI_ex[OF ex_k] by simp\n  moreover have \"\\<forall>m. f$$m \\<noteq> 0 \\<longrightarrow> n \\<le> m\"\n  proof (clarify)\n    fix m assume m: \"f$$m \\<noteq> 0\"\n    with M have \"M \\<le> m\" by fast\n    define l where \"l = nat (m - M)\"\n    from \\<open>M \\<le> m\\<close> have l: \"m = M + int l\" by (simp add: l_def)\n    with n_def m k_def l show \"n \\<le> m\"\n      using Least_le[of \"\\<lambda>k. f$$(M + int k) \\<noteq> 0\" l] by auto\n  qed\n  moreover have \"\\<And>n'. f$$n' \\<noteq> 0 \\<Longrightarrow> (\\<forall>m. f$$m \\<noteq> 0 \\<longrightarrow> n' \\<le> m) \\<Longrightarrow> n' = n\"\n  proof-\n    fix n' :: int\n    assume n': \"f$$n' \\<noteq> 0\" \"\\<forall>m. f$$m \\<noteq> 0 \\<longrightarrow> n' \\<le> m\"\n    from n'(1) M have \"M \\<le> n'\" by fast\n    define l where \"l = nat (n' - M)\"\n    from \\<open>M \\<le> n'\\<close> have l: \"n' = M + int l\" by (simp add: l_def)\n    with n_def k_def n' fn show \"n' = n\"\n      using Least_le[of \"\\<lambda>k. f$$(M + int k) \\<noteq> 0\" l] by force\n  qed\n  ultimately show ?thesis\n    using ex1I[of \"\\<lambda>n. f$$n \\<noteq> 0 \\<and> (\\<forall>m. f$$m \\<noteq> 0 \\<longrightarrow> n \\<le> m)\" n] by blast\nqed\n\ndefinition fls_subdegree :: \"('a::zero) fls \\<Rightarrow> int\"\n  where \"fls_subdegree f \\<equiv> (if f = 0 then 0 else LEAST n::int. f$$n \\<noteq> 0)\"\n\nlemma fls_zero_subdegree [simp]: \"fls_subdegree 0 = 0\"\n  by (simp add: fls_subdegree_def)\n\nlemma nth_fls_subdegree_nonzero [simp]: \"f \\<noteq> 0 \\<Longrightarrow> f $$ fls_subdegree f \\<noteq> 0\"\n  using Least1I[OF unique_fls_subdegree] by (simp add: fls_subdegree_def)\n\nlemma nth_fls_subdegree_zero_iff: \"(f $$ fls_subdegree f = 0) \\<longleftrightarrow> (f = 0)\"\n  using nth_fls_subdegree_nonzero by auto\n\nlemma fls_subdegree_leI: \"f $$ n \\<noteq> 0 \\<Longrightarrow> fls_subdegree f \\<le> n\"\n  using Least1_le[OF unique_fls_subdegree]\n  by    (auto simp: fls_subdegree_def)\n\nlemma fls_subdegree_leI': \"f $$ n \\<noteq> 0 \\<Longrightarrow> n \\<le> m \\<Longrightarrow> fls_subdegree f \\<le> m\"\n  using fls_subdegree_leI by fastforce\n\nlemma fls_eq0_below_subdegree [simp]: \"n < fls_subdegree f \\<Longrightarrow> f $$ n = 0\"\n  using fls_subdegree_leI by fastforce\n\nlemma fls_subdegree_geI: \"f \\<noteq> 0 \\<Longrightarrow> (\\<And>k. k < n \\<Longrightarrow> f $$ k = 0) \\<Longrightarrow> n \\<le> fls_subdegree f\"\n  using nth_fls_subdegree_nonzero by force\n\nlemma fls_subdegree_ge0I: \"(\\<And>k. k < 0 \\<Longrightarrow> f $$ k = 0) \\<Longrightarrow> 0 \\<le> fls_subdegree f\"\n  using fls_subdegree_geI[of f 0] by (cases \"f=0\") auto\n\nlemma fls_subdegree_greaterI:\n  assumes \"f \\<noteq> 0\" \"\\<And>k. k \\<le> n \\<Longrightarrow> f $$ k = 0\"\n  shows   \"n < fls_subdegree f\"\n  using   assms(1) assms(2)[of \"fls_subdegree f\"] nth_fls_subdegree_nonzero[of f]\n  by      force\n\nlemma fls_subdegree_eqI: \"f $$ n \\<noteq> 0 \\<Longrightarrow> (\\<And>k. k < n \\<Longrightarrow> f $$ k = 0) \\<Longrightarrow> fls_subdegree f = n\"\n  using fls_subdegree_leI fls_subdegree_geI[of f]\n  by    fastforce\n\nlemma fls_delta_subdegree [simp]:\n  \"b \\<noteq> 0 \\<Longrightarrow> fls_subdegree (Abs_fls (\\<lambda>n. if n=a then b else 0)) = a\"\n  by (intro fls_subdegree_eqI) simp_all\n\nlemma fls_delta0_subdegree: \"fls_subdegree (Abs_fls (\\<lambda>n. if n=0 then a else 0)) = 0\"\n  by (cases \"a=0\") simp_all\n\nlemma fls_one_subdegree [simp]: \"fls_subdegree 1 = 0\"\n  by (auto intro: fls_delta0_subdegree simp: one_fls_def)\n\nlemma fls_const_subdegree [simp]: \"fls_subdegree (fls_const c) = 0\"\n  by (cases \"c=0\") (auto intro: fls_subdegree_eqI)\n\nlemma fls_X_subdegree [simp]: \"fls_subdegree (fls_X::'a::{zero_neq_one} fls) = 1\"\n  by (intro fls_subdegree_eqI) simp_all\n\nlemma fls_X_inv_subdegree [simp]: \"fls_subdegree (fls_X_inv::'a::{zero_neq_one} fls) = -1\"\n  by (intro fls_subdegree_eqI) simp_all\n\nlemma fls_eq_above_subdegreeI:\n  assumes \"N \\<le> fls_subdegree f\" \"N \\<le> fls_subdegree g\" \"\\<forall>k\\<ge>N. f $$ k = g $$ k\"\n  shows   \"f = g\"\nproof (rule fls_eqI)\n  fix n from assms show \"f $$ n = g $$ n\" by (cases \"n < N\") auto\nqed\n\n\nsubsection \\<open>Shifting\\<close>\n\nsubsubsection \\<open>Shift definition\\<close>\n\ndefinition fls_shift :: \"int \\<Rightarrow> ('a::zero) fls \\<Rightarrow> 'a fls\"\n  where \"fls_shift n f \\<equiv> Abs_fls (\\<lambda>k. f $$ (k+n))\"\n\\<comment> \\<open>Since the index set is unbounded in both directions, we can shift in either direction.\\<close>\n\nlemma fls_shift_nth [simp]: \"fls_shift m f $$ n = f $$ (n+m)\"\n  unfolding fls_shift_def\nproof (rule nth_Abs_fls_ex_lower_bound)\n  obtain K::int where K: \"\\<forall>n<K. f$$n = 0\" by (elim fls_nth_vanishes_belowE)\n  hence \"\\<forall>n<K-m. f$$(n+m) = 0\" by auto\n  thus \"\\<exists>N. \\<forall>n<N. f $$ (n + m) = 0\" by fast\nqed\n\nlemma fls_shift_eq_iff: \"(fls_shift m f = fls_shift m g) \\<longleftrightarrow> (f = g)\"\nproof (rule iffI, rule fls_eqI)\n  fix k\n  assume 1: \"fls_shift m f = fls_shift m g\"\n  have \"f $$ k = fls_shift m g $$ (k - m)\" by (simp add: 1[symmetric])  \n  thus \"f $$ k = g $$ k\" by simp\nqed (intro fls_eqI, simp)\n\nlemma fls_shift_0 [simp]: \"fls_shift 0 f = f\"\n  by (intro fls_eqI) simp\n\nlemma fls_shift_subdegree [simp]:\n  \"f \\<noteq> 0 \\<Longrightarrow> fls_subdegree (fls_shift n f) = fls_subdegree f - n\"\n  by (intro fls_subdegree_eqI) simp_all\n\nlemma fls_shift_fls_shift [simp]: \"fls_shift m (fls_shift k f) = fls_shift (k+m) f\"\n  by (intro fls_eqI) (simp add: algebra_simps)\n\nlemma fls_shift_fls_shift_reorder:\n  \"fls_shift m (fls_shift k f) = fls_shift k (fls_shift m f)\"\n  using fls_shift_fls_shift[of m k f] fls_shift_fls_shift[of k m f] by (simp add: add.commute)\n\nlemma fls_shift_zero [simp]: \"fls_shift m 0 = 0\"\n  by (intro fls_zero_eqI) simp\n\nlemma fls_shift_eq0_iff: \"fls_shift m f = 0 \\<longleftrightarrow> f = 0\"\n  using fls_shift_eq_iff[of m f 0] by simp\n\nlemma fls_shift_eq_1_iff: \"fls_shift n f = 1 \\<longleftrightarrow> f = fls_shift (-n) 1\"\n  by (metis add_minus_cancel fls_shift_eq_iff fls_shift_fls_shift)\n\nlemma fls_shift_nonneg_subdegree: \"m \\<le> fls_subdegree f \\<Longrightarrow> fls_subdegree (fls_shift m f) \\<ge> 0\"\n  by (cases \"f=0\") (auto intro: fls_subdegree_geI)\n\nlemma fls_shift_delta:\n  \"fls_shift m (Abs_fls (\\<lambda>n. if n=a then b else 0)) = Abs_fls (\\<lambda>n. if n=a-m then b else 0)\"\n  by (intro fls_eqI) simp\n\nlemma fls_shift_const:\n  \"fls_shift m (fls_const c) = Abs_fls (\\<lambda>n. if n=-m then c else 0)\"\n  by (intro fls_eqI) simp\n\nlemma fls_shift_const_nth:\n  \"fls_shift m (fls_const c) $$ n = (if n=-m then c else 0)\"\n  by (simp add: fls_shift_const)\n\nlemma fls_X_conv_shift_1: \"fls_X = fls_shift (-1) 1\"\n  by (intro fls_eqI) simp\n\nlemma fls_X_shift_to_one [simp]: \"fls_shift 1 fls_X = 1\"\n  using fls_shift_fls_shift[of \"-1\" 1 1] by (simp add: fls_X_conv_shift_1)\n\nlemma fls_X_inv_conv_shift_1: \"fls_X_inv = fls_shift 1 1\"\n  by (intro fls_eqI) simp\n\nlemma fls_X_inv_shift_to_one [simp]: \"fls_shift (-1) fls_X_inv = 1\"\n  using fls_shift_fls_shift[of 1 \"-1\" 1] by (simp add: fls_X_inv_conv_shift_1)\n\nlemma fls_X_fls_X_inv_conv:\n  \"fls_X = fls_shift (-2) fls_X_inv\" \"fls_X_inv = fls_shift 2 fls_X\"\n  by (simp_all add: fls_X_conv_shift_1 fls_X_inv_conv_shift_1)\n\n\nsubsubsection \\<open>Base factor\\<close>\n\ntext \\<open>\n  Similarly to the @{const unit_factor} for formal power series, we can decompose a formal Laurent\n  series as a power of the implied variable times a series of subdegree 0.\n  (See lemma @{text \"fls_base_factor_X_power_decompose\"}.)\n  But we will call this something other @{const unit_factor}\n  because it will not satisfy assumption @{text \"is_unit_unit_factor\"} of\n  @{class semidom_divide_unit_factor}.\n\\<close>\n\ndefinition fls_base_factor :: \"('a::zero) fls \\<Rightarrow> 'a fls\"\n  where fls_base_factor_def[simp]: \"fls_base_factor f = fls_shift (fls_subdegree f) f\"\n\nlemma fls_base_factor_nth: \"fls_base_factor f $$ n = f $$ (n + fls_subdegree f)\"\n  by simp\n\nlemma fls_base_factor_nonzero [simp]: \"f \\<noteq> 0 \\<Longrightarrow> fls_base_factor f \\<noteq> 0\"\n  using fls_nonzeroI[of \"fls_base_factor f\" 0] by simp\n\nlemma fls_base_factor_subdegree [simp]: \"fls_subdegree (fls_base_factor f) = 0\"\n by (cases \"f=0\") auto\n\nlemma fls_base_factor_base [simp]:\n  \"fls_base_factor f $$ fls_subdegree (fls_base_factor f) = f $$ fls_subdegree f\"\n  using fls_base_factor_subdegree[of f] by simp\n\nlemma fls_conv_base_factor_shift_subdegree:\n  \"f = fls_shift (-fls_subdegree f) (fls_base_factor f)\"\n  by simp\n\nlemma fls_base_factor_idem:\n  \"fls_base_factor (fls_base_factor (f::'a::zero fls)) = fls_base_factor f\"\n  using fls_base_factor_subdegree[of f] by simp\n\nlemma fls_base_factor_zero: \"fls_base_factor (0::'a::zero fls) = 0\"\n  by simp\n\nlemma fls_base_factor_zero_iff: \"fls_base_factor (f::'a::zero fls) = 0 \\<longleftrightarrow> f = 0\"\nproof\n  have \"fls_shift (-fls_subdegree f) (fls_shift (fls_subdegree f) f) = f\" by simp\n  thus \"fls_base_factor f = 0 \\<Longrightarrow> f=0\" by simp\nqed simp\n\nlemma fls_base_factor_nth_0: \"f \\<noteq> 0 \\<Longrightarrow> fls_base_factor f $$ 0 \\<noteq> 0\"\n  by simp\n\nlemma fls_base_factor_one: \"fls_base_factor (1::'a::{zero,one} fls) = 1\"\n  by simp\n\nlemma fls_base_factor_const: \"fls_base_factor (fls_const c) = fls_const c\"\n  by simp\n\nlemma fls_base_factor_delta:\n  \"fls_base_factor (Abs_fls (\\<lambda>n. if n=a then c else 0)) = fls_const c\"\n  by  (cases \"c=0\") (auto intro: fls_eqI)\n\nlemma fls_base_factor_X: \"fls_base_factor (fls_X::'a::{zero_neq_one} fls) = 1\"\n   by simp\n\nlemma fls_base_factor_X_inv: \"fls_base_factor (fls_X_inv::'a::{zero_neq_one} fls) = 1\"\n   by simp\n\nlemma fls_base_factor_shift [simp]: \"fls_base_factor (fls_shift n f) = fls_base_factor f\"\n  by (cases \"f=0\") simp_all\n\n\nsubsection \\<open>Conversion between formal power and Laurent series\\<close>\n\nsubsubsection \\<open>Converting Laurent to power series\\<close>\n\ntext \\<open>\n  We can truncate a Laurent series at index 0 to create a power series, called the regular part.\n\\<close>\n\nlift_definition fls_regpart :: \"('a::zero) fls \\<Rightarrow> 'a fps\"\n  is \"\\<lambda>f. Abs_fps (\\<lambda>n. f (int n))\"\n  .\n\nlemma fls_regpart_nth [simp]: \"fls_regpart f $ n = f $$ (int n)\"\n  by (simp add: fls_regpart_def)\n\nlemma fls_regpart_zero [simp]: \"fls_regpart 0 = 0\"\n  by (intro fps_ext) simp\n\nlemma fls_regpart_one [simp]: \"fls_regpart 1 = 1\"\n  by (intro fps_ext) simp\n\nlemma fls_regpart_Abs_fls:\n  \"\\<forall>\\<^sub>\\<infinity>n. F (- int n) = 0 \\<Longrightarrow> fls_regpart (Abs_fls F) = Abs_fps (\\<lambda>n. F (int n))\"\n  by (intro fps_ext) auto\n\nlemma fls_regpart_delta:\n  \"fls_regpart (Abs_fls (\\<lambda>n. if n=a then b else 0)) =\n    (if a < 0 then 0 else Abs_fps (\\<lambda>n. if n=nat a then b else 0))\"\n  by (rule fps_ext, auto)\n\nlemma fls_regpart_const [simp]: \"fls_regpart (fls_const c) = fps_const c\"\n  by (intro fps_ext) simp\n\nlemma fls_regpart_fls_X [simp]: \"fls_regpart fls_X = fps_X\"\n  by (intro fps_ext) simp\n\nlemma fls_regpart_fls_X_inv [simp]: \"fls_regpart fls_X_inv = 0\"\n  by (intro fps_ext) simp\n\nlemma fls_regpart_eq0_imp_nonpos_subdegree:\n  assumes \"fls_regpart f = 0\"\n  shows   \"fls_subdegree f \\<le> 0\"\nproof (cases \"f=0\")\n  case False\n  have \"fls_subdegree f \\<ge> 0 \\<Longrightarrow> f $$ fls_subdegree f = 0\"\n  proof-\n    assume \"fls_subdegree f \\<ge> 0\"\n    hence \"f $$ (fls_subdegree f) = (fls_regpart f) $ (nat (fls_subdegree f))\" by simp\n    with assms show \"f $$ (fls_subdegree f) = 0\" by simp\n  qed\n  with False show ?thesis by fastforce\nqed simp\n\nlemma fls_subdegree_lt_fls_regpart_subdegree:\n  \"fls_subdegree f \\<le> int (subdegree (fls_regpart f))\"\n  using fls_subdegree_leI nth_subdegree_nonzero[of \"fls_regpart f\"]\n  by    (cases \"(fls_regpart f) = 0\")\n        (simp_all add: fls_regpart_eq0_imp_nonpos_subdegree)\n\nlemma fls_regpart_subdegree_conv:\n  assumes \"fls_subdegree f \\<ge> 0\"\n  shows   \"subdegree (fls_regpart f) = nat (fls_subdegree f)\"\n\\<comment>\\<open>\n  This is the best we can do since if the subdegree is negative, we might still have the bad luck\n  that the term at index 0 is equal to 0.\n\\<close>\nproof (cases \"f=0\")\n  case False with assms show ?thesis by (intro subdegreeI) simp_all\nqed simp\n\nlemma fls_eq_conv_fps_eqI:\n  assumes \"0 \\<le> fls_subdegree f\" \"0 \\<le> fls_subdegree g\" \"fls_regpart f = fls_regpart g\"\n  shows   \"f = g\"\nproof (rule fls_eq_above_subdegreeI, rule assms(1), rule assms(2), clarify)\n  fix k::int assume \"0 \\<le> k\"\n  with assms(3) show \"f $$ k = g $$ k\"\n    using fls_regpart_nth[of f \"nat k\"] fls_regpart_nth[of g] by simp\nqed\n\nlemma fls_regpart_shift_conv_fps_shift:\n  \"m \\<ge> 0 \\<Longrightarrow> fls_regpart (fls_shift m f) = fps_shift (nat m) (fls_regpart f)\"\n  by (intro fps_ext) simp_all\n\nlemma fps_shift_fls_regpart_conv_fls_shift:\n  \"fps_shift m (fls_regpart f) = fls_regpart (fls_shift m f)\"\n  by (intro fps_ext) simp_all\n\nlemma fps_unit_factor_fls_regpart:\n  \"fls_subdegree f \\<ge> 0 \\<Longrightarrow> unit_factor (fls_regpart f) = fls_regpart (fls_base_factor f)\"\n  by (auto intro: fps_ext simp: fls_regpart_subdegree_conv)\n\ntext \\<open>\n  The terms below the zeroth form a polynomial in the inverse of the implied variable,\n  called the principle part.\n\\<close>\n\nlift_definition fls_prpart :: \"('a::zero) fls \\<Rightarrow> 'a poly\"\n  is \"\\<lambda>f. Abs_poly (\\<lambda>n. if n = 0 then 0 else f (- int n))\"\n  .\n\nlemma fls_prpart_coeff [simp]: \"coeff (fls_prpart f) n = (if n = 0 then 0 else f $$ (- int n))\"\nproof-\n  have \"{x. (if x = 0 then 0 else f $$ - int x) \\<noteq> 0} \\<subseteq> {x. f $$ - int x \\<noteq> 0}\"\n    by auto\n  hence \"finite {x. (if x = 0 then 0 else f $$ - int x) \\<noteq> 0}\"\n    using fls_finite_nonzero_neg_nth[of f] by (simp add: rev_finite_subset)\n  hence \"coeff (fls_prpart f) = (\\<lambda>n. if n = 0 then 0 else f $$ (- int n))\"\n    using Abs_poly_inverse[OF CollectI, OF iffD2, OF eventually_cofinite]\n    by (simp add: fls_prpart_def)\n  thus ?thesis by simp\nqed\n\nlemma fls_prpart_eq0_iff: \"(fls_prpart f = 0) \\<longleftrightarrow> (fls_subdegree f \\<ge> 0)\"\nproof\n  assume 1: \"fls_prpart f = 0\"\n  show \"fls_subdegree f \\<ge> 0\"\n  proof (intro fls_subdegree_ge0I)\n    fix k::int assume \"k < 0\"\n    with 1 show \"f $$ k = 0\" using fls_prpart_coeff[of f \"nat (-k)\"] by simp\n  qed\nqed (intro poly_eqI, simp)\n\nlemma fls_prpart0 [simp]: \"fls_prpart 0 = 0\"\n  by (simp add: fls_prpart_eq0_iff)\n\nlemma fls_prpart_one [simp]: \"fls_prpart 1 = 0\"\n  by (simp add: fls_prpart_eq0_iff)\n\nlemma fls_prpart_delta:\n  \"fls_prpart (Abs_fls (\\<lambda>n. if n=a then b else 0)) =\n    (if a<0 then Poly (replicate (nat (-a)) 0 @ [b]) else 0)\"\n  by (intro poly_eqI) (auto simp: nth_default_def nth_append)\n\nlemma fls_prpart_const [simp]: \"fls_prpart (fls_const c) = 0\"\n  by (simp add: fls_prpart_eq0_iff)\n\nlemma fls_prpart_X [simp]: \"fls_prpart fls_X = 0\"\n  by (intro poly_eqI) simp\n\nlemma fls_prpart_X_inv: \"fls_prpart fls_X_inv = [:0,1:]\"\nproof (intro poly_eqI)\n  fix n show \"coeff (fls_prpart fls_X_inv) n = coeff [:0,1:] n\"\n  proof (cases n)\n    case (Suc i) thus ?thesis by (cases i) simp_all\n  qed simp\nqed\n\nlemma degree_fls_prpart [simp]:\n  \"degree (fls_prpart f) = nat (-fls_subdegree f)\"\nproof (cases \"f=0\")\n  case False show ?thesis unfolding degree_def\n  proof (intro Least_equality)\n    fix N assume N: \"\\<forall>i>N. coeff (fls_prpart f) i = 0\"\n    have \"\\<forall>i < -int N. f $$ i = 0\"\n    proof clarify\n      fix i assume i: \"i < -int N\"\n      hence \"nat (-i) > N\" by simp\n      with N i show \"f $$ i = 0\" using fls_prpart_coeff[of f \"nat (-i)\"] by auto\n    qed\n    with False have \"fls_subdegree f \\<ge> -int N\" using fls_subdegree_geI by auto\n    thus \"nat (- fls_subdegree f) \\<le> N\" by simp\n  qed auto\nqed simp\n\nlemma fls_prpart_shift:\n  assumes \"m \\<le> 0\"\n  shows   \"fls_prpart (fls_shift m f) = pCons 0 (poly_shift (Suc (nat (-m))) (fls_prpart f))\"\nproof (intro poly_eqI)\n  fix n\n  define LHS RHS\n    where \"LHS \\<equiv> fls_prpart (fls_shift m f)\"\n    and   \"RHS \\<equiv> pCons 0 (poly_shift (Suc (nat (-m))) (fls_prpart f))\"\n  show \"coeff LHS n = coeff RHS n\"\n  proof (cases n)\n    case (Suc k)\n    from assms have 1: \"-int (Suc k + nat (-m)) = -int (Suc k) + m\" by simp\n    have \"coeff RHS n = f $$ (-int (Suc k) + m)\"\n      using arg_cong[OF 1, of \"($$) f\"] by (simp add: Suc RHS_def coeff_poly_shift)\n    with Suc show ?thesis by (simp add: LHS_def)\n  qed (simp add: LHS_def RHS_def)\nqed\n\nlemma fls_prpart_base_factor: \"fls_prpart (fls_base_factor f) = 0\"\n  using fls_base_factor_subdegree[of f] by (simp add: fls_prpart_eq0_iff)\n\ntext \\<open>The essential data of a formal Laurant series resides from the subdegree up.\\<close>\n\nabbreviation fls_base_factor_to_fps :: \"('a::zero) fls \\<Rightarrow> 'a fps\"\n  where \"fls_base_factor_to_fps f \\<equiv> fls_regpart (fls_base_factor f)\"\n\nlemma fls_base_factor_to_fps_conv_fps_shift:\n  assumes \"fls_subdegree f \\<ge> 0\"\n  shows   \"fls_base_factor_to_fps f = fps_shift (nat (fls_subdegree f)) (fls_regpart f)\"\n  by (simp add: assms fls_regpart_shift_conv_fps_shift)\n\nlemma fls_base_factor_to_fps_nth:\n  \"fls_base_factor_to_fps f $ n = f $$ (fls_subdegree f + int n)\"\n  by (simp add: algebra_simps)\n\nlemma fls_base_factor_to_fps_base: \"f \\<noteq> 0 \\<Longrightarrow> fls_base_factor_to_fps f $ 0 \\<noteq> 0\"\n  by simp\n\nlemma fls_base_factor_to_fps_nonzero: \"f \\<noteq> 0 \\<Longrightarrow> fls_base_factor_to_fps f \\<noteq> 0\"\n  using fps_nonzeroI[of \"fls_base_factor_to_fps f\" 0] fls_base_factor_to_fps_base by simp\n\nlemma fls_base_factor_to_fps_subdegree [simp]: \"subdegree (fls_base_factor_to_fps f) = 0\"\n  by (cases \"f=0\") auto\n\nlemma fls_base_factor_to_fps_trivial:\n  \"fls_subdegree f = 0 \\<Longrightarrow> fls_base_factor_to_fps f = fls_regpart f\"\n  by simp\n\nlemma fls_base_factor_to_fps_zero: \"fls_base_factor_to_fps 0 = 0\"\n  by simp\n\nlemma fls_base_factor_to_fps_one: \"fls_base_factor_to_fps 1 = 1\"\n  by simp\n\nlemma fls_base_factor_to_fps_delta:\n  \"fls_base_factor_to_fps (Abs_fls (\\<lambda>n. if n=a then c else 0)) = fps_const c\"\n  using fls_base_factor_delta[of a c] by simp\n\nlemma fls_base_factor_to_fps_const:\n  \"fls_base_factor_to_fps (fls_const c) = fps_const c\"\n  by simp\n\nlemma fls_base_factor_to_fps_X:\n  \"fls_base_factor_to_fps (fls_X::'a::{zero_neq_one} fls) = 1\"\n  by simp\n\nlemma fls_base_factor_to_fps_X_inv:\n  \"fls_base_factor_to_fps (fls_X_inv::'a::{zero_neq_one} fls) = 1\"\n  by simp\n\nlemma fls_base_factor_to_fps_shift:\n  \"fls_base_factor_to_fps (fls_shift m f) = fls_base_factor_to_fps f\"\n  using fls_base_factor_shift[of m f] by simp\n\nlemma fls_base_factor_to_fps_base_factor:\n  \"fls_base_factor_to_fps (fls_base_factor f) = fls_base_factor_to_fps f\"\n  using fls_base_factor_to_fps_shift by simp\n\nlemma fps_unit_factor_fls_base_factor:\n  \"unit_factor (fls_base_factor_to_fps f) = fls_base_factor_to_fps f\"\n  using fls_base_factor_to_fps_subdegree[of f] by simp\n\nsubsubsection \\<open>Converting power to Laurent series\\<close>\n\ntext \\<open>We can extend a power series by 0s below to create a Laurent series.\\<close>\n\ndefinition fps_to_fls :: \"('a::zero) fps \\<Rightarrow> 'a fls\"\n  where \"fps_to_fls f \\<equiv> Abs_fls (\\<lambda>k::int. if k<0 then 0 else f $ (nat k))\"\n\nlemma fps_to_fls_nth [simp]:\n  \"(fps_to_fls f) $$ n = (if n < 0 then 0 else f$(nat n))\"\n  using     nth_Abs_fls_lower_bound[of 0 \"(\\<lambda>k::int. if k<0 then 0 else f $ (nat k))\"]\n  unfolding fps_to_fls_def\n  by        simp\n\nlemma fps_to_fls_eq_imp_fps_eq:\n  assumes \"fps_to_fls f = fps_to_fls g\"\n  shows   \"f = g\"\nproof (intro fps_ext)\n  fix n\n  have \"f $ n = fps_to_fls g $$ int n\" by (simp add: assms[symmetric])\n  thus \"f $ n = g $ n\" by simp\nqed\n\nlemma fps_to_fls_eq_iff [simp]: \"fps_to_fls f = fps_to_fls g \\<longleftrightarrow> f = g\"\n  using fps_to_fls_eq_imp_fps_eq by blast\n\nlemma fps_zero_to_fls [simp]: \"fps_to_fls 0 = 0\"\n  by (intro fls_zero_eqI) simp\n\nlemma fps_to_fls_nonzeroI: \"f \\<noteq> 0 \\<Longrightarrow> fps_to_fls f \\<noteq> 0\"\n  using fps_to_fls_eq_imp_fps_eq[of f 0] by auto\n\nlemma fps_one_to_fls [simp]: \"fps_to_fls 1 = 1\"\n  by (intro fls_eqI) simp\n\nlemma fps_to_fls_Abs_fps:\n  \"fps_to_fls (Abs_fps F) = Abs_fls (\\<lambda>n. if n<0 then 0 else F (nat n))\"\n  using nth_Abs_fls_lower_bound[of 0 \"(\\<lambda>n::int. if n<0 then 0 else F (nat n))\"]\n  by    (intro fls_eqI) simp\n\nlemma fps_delta_to_fls:\n  \"fps_to_fls (Abs_fps (\\<lambda>n. if n=a then b else 0)) = Abs_fls (\\<lambda>n. if n=int a then b else 0)\"\n  using fls_eqI[of _ \"Abs_fls (\\<lambda>n. if n=int a then b else 0)\"] by force\n\nlemma fps_const_to_fls [simp]: \"fps_to_fls (fps_const c) = fls_const c\"\n  by (intro fls_eqI) simp\n\nlemma fps_X_to_fls [simp]: \"fps_to_fls fps_X = fls_X\"\n  by (fastforce intro: fls_eqI)\n\nlemma fps_to_fls_eq_0_iff [simp]: \"(fps_to_fls f = 0) \\<longleftrightarrow> (f=0)\"\n  using fps_to_fls_nonzeroI by auto\n\nlemma fps_to_fls_eq_1_iff [simp]: \"fps_to_fls f = 1 \\<longleftrightarrow> f = 1\"\n  using fps_to_fls_eq_iff by fastforce\n\nlemma fls_subdegree_fls_to_fps_gt0: \"fls_subdegree (fps_to_fls f) \\<ge> 0\"\nproof (cases \"f=0\")\n  case False show ?thesis\n  proof (rule fls_subdegree_geI, rule fls_nonzeroI)\n    from False show \"fps_to_fls f $$ int (subdegree f) \\<noteq> 0\"\n      by simp\n  qed simp\nqed simp\n\nlemma fls_subdegree_fls_to_fps: \"fls_subdegree (fps_to_fls f) = int (subdegree f)\"\nproof (cases \"f=0\")\n  case False\n  have \"subdegree f = nat (fls_subdegree (fps_to_fls f))\"\n  proof (rule subdegreeI)\n    from False show \"f $ (nat (fls_subdegree (fps_to_fls f))) \\<noteq> 0\"\n      using fls_subdegree_fls_to_fps_gt0[of f] nth_fls_subdegree_nonzero[of \"fps_to_fls f\"]\n            fps_to_fls_nonzeroI[of f]\n      by    simp\n  next\n    fix k assume k: \"k < nat (fls_subdegree (fps_to_fls f))\"\n    thus \"f $ k = 0\"\n      using fls_eq0_below_subdegree[of \"int k\" \"fps_to_fls f\"] by simp\n  qed\n  thus ?thesis by (simp add: fls_subdegree_fls_to_fps_gt0)\nqed simp\n\nlemma fps_shift_to_fls [simp]:\n  \"n \\<le> subdegree f \\<Longrightarrow> fps_to_fls (fps_shift n f) = fls_shift (int n) (fps_to_fls f)\"\n  by (auto intro: fls_eqI simp: nat_add_distrib nth_less_subdegree_zero)\n\nlemma fls_base_factor_fps_to_fls: \"fls_base_factor (fps_to_fls f) = fps_to_fls (unit_factor f)\"\n  using nth_less_subdegree_zero[of _ f]\n  by    (auto intro: fls_eqI simp: fls_subdegree_fls_to_fps nat_add_distrib)\n\nlemma fls_regpart_to_fls_trivial [simp]:\n  \"fls_subdegree f \\<ge> 0 \\<Longrightarrow> fps_to_fls (fls_regpart f) = f\"\n  by (intro fls_eqI) simp\n\nlemma fls_regpart_fps_trivial [simp]: \"fls_regpart (fps_to_fls f) = f\"\n  by (intro fps_ext) simp\n\nlemma fps_to_fls_base_factor_to_fps:\n  \"fps_to_fls (fls_base_factor_to_fps f) = fls_base_factor f\"\n  by (intro fls_eqI) simp\n\nlemma fls_conv_base_factor_to_fps_shift_subdegree:\n  \"f = fls_shift (-fls_subdegree f) (fps_to_fls (fls_base_factor_to_fps f))\"\n  using fps_to_fls_base_factor_to_fps[of f] fps_to_fls_base_factor_to_fps[of f] by simp\n\nlemma fls_base_factor_to_fps_to_fls:\n  \"fls_base_factor_to_fps (fps_to_fls f) = unit_factor f\"\n  using fls_base_factor_fps_to_fls[of f] fls_regpart_fps_trivial[of \"unit_factor f\"]\n  by    simp\n\nlemma fls_as_fps:\n  fixes f :: \"'a :: zero fls\" and n :: int\n  assumes n: \"n \\<ge> -fls_subdegree f\"\n  obtains f' where \"f = fls_shift n (fps_to_fls f')\"\nproof -\n  have \"fls_subdegree (fls_shift (- n) f) \\<ge> 0\"\n    by (rule fls_shift_nonneg_subdegree) (use n in simp)\n  hence \"f = fls_shift n (fps_to_fls (fls_regpart (fls_shift (-n) f)))\"\n    by (subst fls_regpart_to_fls_trivial) simp_all\n  thus ?thesis\n    by (rule that)\nqed\n\nlemma fls_as_fps':\n  fixes f :: \"'a :: zero fls\" and n :: int\n  assumes n: \"n \\<ge> -fls_subdegree f\"\n  shows \"\\<exists>f'. f = fls_shift n (fps_to_fls f')\"\n  using fls_as_fps[OF assms] by metis\n\nabbreviation\n  \"fls_regpart_as_fls f \\<equiv> fps_to_fls (fls_regpart f)\"\nabbreviation\n  \"fls_prpart_as_fls f \\<equiv>\n    fls_shift (-fls_subdegree f) (fps_to_fls (fps_of_poly (reflect_poly (fls_prpart f))))\"\n\nlemma fls_regpart_as_fls_nth:\n  \"fls_regpart_as_fls f $$ n = (if n < 0 then 0 else f $$ n)\"\n  by simp\n\nlemma fls_regpart_idem:\n  \"fls_regpart (fls_regpart_as_fls f) = fls_regpart f\"\n  by simp\n\nlemma fls_prpart_as_fls_nth:\n  \"fls_prpart_as_fls f $$ n = (if n < 0 then f $$ n else 0)\"\nproof (cases \"n < fls_subdegree f\" \"n < 0\" rule: case_split[case_product case_split])\n  case False_True\n    hence \"nat (-fls_subdegree f) - nat (n - fls_subdegree f) = nat (-n)\" by auto\n    with False_True show ?thesis\n      using coeff_reflect_poly[of \"fls_prpart f\" \"nat (n - fls_subdegree f)\"] by auto\n  next\n    case False_False thus ?thesis\n      using coeff_reflect_poly[of \"fls_prpart f\" \"nat (n - fls_subdegree f)\"] by auto\nqed simp_all\n\nlemma fls_prpart_idem [simp]: \"fls_prpart (fls_prpart_as_fls f) = fls_prpart f\"\n  using fls_prpart_as_fls_nth[of f] by (intro poly_eqI) simp\n\nlemma fls_regpart_prpart: \"fls_regpart (fls_prpart_as_fls f) = 0\"\n  using fls_prpart_as_fls_nth[of f] by (intro fps_ext) simp\n\nlemma fls_prpart_regpart: \"fls_prpart (fls_regpart_as_fls f) = 0\"\n  by (intro poly_eqI) simp\n\n\nsubsection \\<open>Algebraic structures\\<close>\n\nsubsubsection \\<open>Addition\\<close>\n\ninstantiation fls :: (monoid_add) plus\nbegin\n  lift_definition plus_fls :: \"'a fls \\<Rightarrow> 'a fls \\<Rightarrow> 'a fls\" is \"\\<lambda>f g n. f n + g n\"\n  proof-\n    fix f f' :: \"int \\<Rightarrow> 'a\"\n    assume \"\\<forall>\\<^sub>\\<infinity>n. f (- int n) = 0\" \"\\<forall>\\<^sub>\\<infinity>n. f' (- int n) = 0\"\n    from this obtain N N' where \"\\<forall>n>N. f (-int n) = 0\" \"\\<forall>n>N'. f' (-int n) = 0\"\n      by (auto simp: MOST_nat)\n    hence \"\\<forall>n > max N N'. f (-int n) + f' (-int n) = 0\" by auto\n    hence \"\\<exists>K. \\<forall>n>K. f (-int n) + f' (-int n) = 0\" by fast\n    thus \"\\<forall>\\<^sub>\\<infinity>n. f (- int n) + f' (-int n) = 0\" by (simp add: MOST_nat)\n  qed\n  instance ..\nend\n\nlemma fls_plus_nth [simp]: \"(f + g) $$ n = f $$ n + g $$ n\"\n  by transfer simp\n\nlemma fls_plus_const: \"fls_const x + fls_const y = fls_const (x+y)\"\n  by (intro fls_eqI) simp\n\nlemma fls_plus_subdegree:\n  \"f + g \\<noteq> 0 \\<Longrightarrow> fls_subdegree (f + g) \\<ge> min (fls_subdegree f) (fls_subdegree g)\"\n  by (auto intro: fls_subdegree_geI)\n\nlemma fls_shift_plus [simp]:\n  \"fls_shift m (f + g) = (fls_shift m f) + (fls_shift m g)\"\n  by (intro fls_eqI) simp\n\nlemma fls_regpart_plus [simp]: \"fls_regpart (f + g) = fls_regpart f + fls_regpart g\"\n  by (intro fps_ext) simp\n\nlemma fls_prpart_plus [simp] : \"fls_prpart (f + g) = fls_prpart f + fls_prpart g\"\n  by (intro poly_eqI) simp\n\nlemma fls_decompose_reg_pr_parts:\n  fixes   f :: \"'a :: monoid_add fls\"\n  defines \"R  \\<equiv> fls_regpart_as_fls f\"\n  and     \"P  \\<equiv> fls_prpart_as_fls f\"\n  shows   \"f = P + R\"\n  and     \"f = R + P\"\n  using   fls_prpart_as_fls_nth[of f]\n  by      (auto intro: fls_eqI simp add: assms)\n\nlemma fps_to_fls_plus [simp]: \"fps_to_fls (f + g) = fps_to_fls f + fps_to_fls g\"\n  by (intro fls_eqI) simp\n\ninstance fls :: (monoid_add) monoid_add\nproof\n  fix a b c :: \"'a fls\"\n  show \"a + b + c = a + (b + c)\" by transfer (simp add: add.assoc)\n  show \"0 + a = a\" by transfer simp\n  show \"a + 0 = a\" by transfer simp\nqed\n\ninstance fls :: (comm_monoid_add) comm_monoid_add\n  by (standard, transfer, auto simp: add.commute)\n\n\nsubsubsection \\<open>Subtraction and negatives\\<close>\n\ninstantiation fls :: (group_add) minus\nbegin\n  lift_definition minus_fls :: \"'a fls \\<Rightarrow> 'a fls \\<Rightarrow> 'a fls\" is \"\\<lambda>f g n. f n - g n\"\n  proof-\n    fix f f' :: \"int \\<Rightarrow> 'a\"\n    assume \"\\<forall>\\<^sub>\\<infinity>n. f (- int n) = 0\" \"\\<forall>\\<^sub>\\<infinity>n. f' (- int n) = 0\"\n    from this obtain N N' where \"\\<forall>n>N. f (-int n) = 0\" \"\\<forall>n>N'. f' (-int n) = 0\"\n      by (auto simp: MOST_nat)\n    hence \"\\<forall>n > max N N'. f (-int n) - f' (-int n) = 0\" by auto\n    hence \"\\<exists>K. \\<forall>n>K. f (-int n) - f' (-int n) = 0\" by fast\n    thus \"\\<forall>\\<^sub>\\<infinity>n. f (- int n) - f' (-int n) = 0\" by (simp add: MOST_nat)\n  qed\n  instance ..\nend\n\nlemma fls_minus_nth [simp]: \"(f - g) $$ n = f $$ n - g $$ n\"\n  by transfer simp\n\nlemma fls_minus_const: \"fls_const x - fls_const y = fls_const (x-y)\"\n  by (intro fls_eqI) simp\n\nlemma fls_subdegree_minus:\n  \"f - g \\<noteq> 0 \\<Longrightarrow> fls_subdegree (f - g) \\<ge> min (fls_subdegree f) (fls_subdegree g)\"\n  by (intro fls_subdegree_geI) simp_all\n\nlemma fls_shift_minus [simp]: \"fls_shift m (f - g) = (fls_shift m f) - (fls_shift m g)\"\n  by (auto intro: fls_eqI)\n\nlemma fls_regpart_minus [simp]: \"fls_regpart (f - g) = fls_regpart f - fls_regpart g\"\n  by (intro fps_ext) simp\n\nlemma fls_prpart_minus [simp] : \"fls_prpart (f - g) = fls_prpart f - fls_prpart g\"\n  by (intro poly_eqI) simp\n\nlemma fps_to_fls_minus [simp]: \"fps_to_fls (f - g) = fps_to_fls f - fps_to_fls g\"\n  by (intro fls_eqI) simp\n\ninstantiation fls :: (group_add) uminus\nbegin\n  lift_definition uminus_fls :: \"'a fls \\<Rightarrow> 'a fls\" is \"\\<lambda>f n. - f n\"\n  proof-\n    fix f :: \"int \\<Rightarrow> 'a\" assume \"\\<forall>\\<^sub>\\<infinity>n. f (- int n) = 0\"\n    from this obtain N where \"\\<forall>n>N. f (-int n) = 0\"\n      by (auto simp: MOST_nat)\n    hence \"\\<forall>n>N. - f (-int n) = 0\" by auto\n    hence \"\\<exists>K. \\<forall>n>K. - f (-int n) = 0\" by fast\n    thus \"\\<forall>\\<^sub>\\<infinity>n. - f (- int n) = 0\" by (simp add: MOST_nat)\n  qed\n  instance ..\nend\n\nlemma fls_uminus_nth [simp]: \"(-f) $$ n = - (f $$ n)\"\n  by transfer simp\n\nlemma fls_const_uminus[simp]: \"fls_const (-x) = -fls_const x\"\n  by (intro fls_eqI) simp\n\nlemma fls_shift_uminus [simp]: \"fls_shift m (- f) = - (fls_shift m f)\"\n  by (auto intro: fls_eqI)\n\nlemma fls_regpart_uminus [simp]: \"fls_regpart (- f) = - fls_regpart f\"\n  by (intro fps_ext) simp\n\nlemma fls_prpart_uminus [simp] : \"fls_prpart (- f) = - fls_prpart f\"\n  by (intro poly_eqI) simp\n\nlemma fps_to_fls_uminus [simp]: \"fps_to_fls (- f) = - fps_to_fls f\"\n  by (intro fls_eqI) simp\n\ninstance fls :: (group_add) group_add\nproof\n  fix a b :: \"'a fls\"\n  show \"- a + a = 0\" by transfer simp\n  show \"a + - b = a - b\" by transfer simp\nqed\n\ninstance fls :: (ab_group_add) ab_group_add\nproof\n  fix a b :: \"'a fls\"\n  show \"- a + a = 0\" by transfer simp\n  show \"a - b = a + - b\" by transfer simp\nqed\n\nlemma fls_uminus_subdegree [simp]: \"fls_subdegree (-f) = fls_subdegree f\"\n  by (cases \"f=0\") (auto intro: fls_subdegree_eqI)\n\nlemma fls_subdegree_minus_sym: \"fls_subdegree (g - f) = fls_subdegree (f - g)\"\n  using fls_uminus_subdegree[of \"g-f\"] by (simp add: algebra_simps)\n\nlemma fls_regpart_sub_prpart: \"fls_regpart (f - fls_prpart_as_fls f) = fls_regpart f\"\n  using fls_decompose_reg_pr_parts(2)[of f]\n        add_diff_cancel[of \"fls_regpart_as_fls f\" \"fls_prpart_as_fls f\"]\n  by    simp\n\nlemma fls_prpart_sub_regpart: \"fls_prpart (f - fls_regpart_as_fls f) = fls_prpart f\"\n  using fls_decompose_reg_pr_parts(1)[of f]\n        add_diff_cancel[of \"fls_prpart_as_fls f\" \"fls_regpart_as_fls f\"]\n  by    simp\n\n\nsubsubsection \\<open>Multiplication\\<close>\n\ninstantiation fls :: (\"{comm_monoid_add, times}\") times\nbegin\n  definition fls_times_def:\n    \"(*) = (\\<lambda>f g.\n      fls_shift\n        (- (fls_subdegree f + fls_subdegree g))\n        (fps_to_fls (fls_base_factor_to_fps f * fls_base_factor_to_fps g))\n    )\"\n  instance ..\nend\n\nlemma fls_times_nth_eq0: \"n < fls_subdegree f + fls_subdegree g \\<Longrightarrow> (f * g) $$ n = 0\"\n  by (simp add: fls_times_def)\n\nlemma fls_times_nth:\n  fixes   f df g dg\n  defines \"df \\<equiv> fls_subdegree f\" and \"dg \\<equiv> fls_subdegree g\"\n  shows   \"(f * g) $$ n = (\\<Sum>i=df + dg..n. f $$ (i - dg) * g $$ (dg + n - i))\"\n  and     \"(f * g) $$ n = (\\<Sum>i=df..n - dg. f $$ i * g $$ (n - i))\"\n  and     \"(f * g) $$ n = (\\<Sum>i=dg..n - df. f $$ (df + i - dg) * g $$ (dg + n - df - i))\"\n  and     \"(f * g) $$ n = (\\<Sum>i=0..n - (df + dg). f $$ (df + i) * g $$ (n - df - i))\"\nproof-\n\n  define dfg where \"dfg \\<equiv> df + dg\"\n\n  show 4: \"(f * g) $$ n = (\\<Sum>i=0..n - dfg. f $$ (df + i) * g $$ (n - df - i))\"\n  proof (cases \"n < dfg\")\n    case False\n    from False assms have\n      \"(f * g) $$ n =\n        (\\<Sum>i = 0..nat (n - dfg). f $$ (df + int i) * g $$ (dg + int (nat (n - dfg) - i)))\"\n      using fps_mult_nth[of \"fls_base_factor_to_fps f\" \"fls_base_factor_to_fps g\"]\n            fls_base_factor_to_fps_nth[of f]\n            fls_base_factor_to_fps_nth[of g]\n      by    (simp add: dfg_def fls_times_def algebra_simps)\n    moreover from False have index:\n      \"\\<And>i. i \\<in> {0..nat (n - dfg)} \\<Longrightarrow> dg + int (nat (n - dfg) - i) = n - df - int i\"\n      by (auto simp: dfg_def)\n    ultimately have\n      \"(f * g) $$ n = (\\<Sum>i=0..nat (n - dfg). f $$ (df + int i) * g $$ (n - df - int i))\"\n      by simp\n    moreover have\n      \"(\\<Sum>i=0..nat (n - dfg). f $$ (df + int i) *  g $$ (n - df - int i)) =\n        (\\<Sum>i=0..n - dfg. f $$ (df + i) *  g $$ (n - df - i))\"\n    proof (intro sum.reindex_cong)\n      show \"inj_on nat {0..n - dfg}\" by standard auto\n      show \"{0..nat (n - dfg)} = nat ` {0..n - dfg}\"\n      proof\n        show \"{0..nat (n - dfg)} \\<subseteq> nat ` {0..n - dfg}\"\n        proof\n          fix i assume \"i \\<in> {0..nat (n - dfg)}\"\n          hence i: \"i \\<ge> 0\" \"i \\<le> nat (n - dfg)\" by auto\n          with False have \"int i \\<ge> 0\" \"int i \\<le> n - dfg\" by auto\n          hence \"int i \\<in> {0..n - dfg}\" by simp\n          moreover from i(1) have \"i = nat (int i)\" by simp\n          ultimately show \"i \\<in> nat ` {0..n - dfg}\" by fast\n        qed\n      qed (auto simp: False)\n    qed (simp add: False)\n    ultimately show \"(f * g) $$ n = (\\<Sum>i=0..n - dfg. f $$ (df + i) *  g $$ (n - df - i))\"\n      by simp\n  qed (simp add: fls_times_nth_eq0 assms dfg_def)\n\n  have\n    \"(\\<Sum>i=dfg..n. f $$ (i - dg) *  g $$ (dg + n - i)) =\n      (\\<Sum>i=0..n - dfg. f $$ (df + i) *  g $$ (n - df - i))\"\n  proof (intro sum.reindex_cong)\n    define T where \"T \\<equiv> \\<lambda>i. i + dfg\"\n    show \"inj_on T {0..n - dfg}\" by standard (simp add: T_def)\n  qed (simp_all add: dfg_def algebra_simps)\n  with 4 show 1: \"(f * g) $$ n = (\\<Sum>i=dfg..n. f $$ (i - dg) *  g $$ (dg + n - i))\"\n    by simp\n\n  have\n    \"(\\<Sum>i=dfg..n. f $$ (i - dg) *  g $$ (dg + n - i)) = (\\<Sum>i=df..n - dg. f $$ i *  g $$ (n - i))\"\n  proof (intro sum.reindex_cong)\n    define T where \"T \\<equiv> \\<lambda>i. i + dg\"\n    show \"inj_on T {df..n - dg}\" by standard (simp add: T_def)\n  qed (auto simp: dfg_def)\n  with 1 show \"(f * g) $$ n = (\\<Sum>i=df..n - dg. f $$ i *  g $$ (n - i))\"\n    by simp\n\n  have\n    \"(\\<Sum>i=dfg..n. f $$ (i - dg) *  g $$ (dg + n - i)) =\n      (\\<Sum>i=dg..n - df. f $$ (df + i - dg) *  g $$ (dg + n - df - i))\"\n  proof (intro sum.reindex_cong)\n    define T where \"T \\<equiv> \\<lambda>i. i + df\"\n    show \"inj_on T {dg..n - df}\" by standard (simp add: T_def)\n  qed (simp_all add: dfg_def algebra_simps)\n  with 1 show \"(f * g) $$ n = (\\<Sum>i=dg..n - df. f $$ (df + i - dg) *  g $$ (dg + n - df - i))\"\n    by simp\n\nqed\n\nlemma fls_times_base [simp]:\n  \"(f * g) $$ (fls_subdegree f + fls_subdegree g) =\n    (f $$ fls_subdegree f) * (g $$ fls_subdegree g)\"\n  by (simp add: fls_times_nth(1))\n\ninstance fls :: (\"{comm_monoid_add, mult_zero}\") mult_zero\nproof\n  fix a :: \"'a fls\"\n  have\n    \"(0::'a fls) * a =\n      fls_shift (fls_subdegree a) (fps_to_fls ( (0::'a fps)*(fls_base_factor_to_fps a) ))\"\n    by (simp add: fls_times_def)\n  moreover have\n    \"a * (0::'a fls) =\n      fls_shift (fls_subdegree a) (fps_to_fls ( (fls_base_factor_to_fps a)*(0::'a fps) ))\"\n    by (simp add: fls_times_def)\n  ultimately show \"0 * a = (0::'a fls)\" \"a * 0 = (0::'a fls)\"\n    by auto\nqed\n\nlemma fls_mult_one:\n  fixes f :: \"'a::{comm_monoid_add, mult_zero, monoid_mult} fls\"\n  shows \"1 * f = f\"\n  and   \"f * 1 = f\"\n  using fls_conv_base_factor_to_fps_shift_subdegree[of f]\n  by    (simp_all add: fls_times_def fps_one_mult)\n\nlemma fls_mult_const_nth [simp]:\n  fixes f :: \"'a::{comm_monoid_add, mult_zero} fls\"\n  shows \"(fls_const x * f) $$ n = x * f$$n\"\n  and   \"(f * fls_const x ) $$ n = f$$n * x\"\nproof-\n  show \"(fls_const x * f) $$ n = x * f$$n\"\n  proof (cases \"n<fls_subdegree f\")\n    case False\n    hence \"{fls_subdegree f..n} = insert (fls_subdegree f) {fls_subdegree f+1..n}\" by auto\n    thus ?thesis by (simp add: fls_times_nth(1))\n  qed (simp add: fls_times_nth_eq0)\n  show \"(f * fls_const x ) $$ n = f$$n * x\"\n  proof (cases \"n<fls_subdegree f\")\n    case False\n    hence \"{fls_subdegree f..n} = insert n {fls_subdegree f..n-1}\" by auto\n    thus ?thesis by (simp add: fls_times_nth(1))\n  qed (simp add: fls_times_nth_eq0)\nqed\n\nlemma fls_const_mult_const[simp]:\n  fixes x y :: \"'a::{comm_monoid_add, mult_zero}\"\n  shows \"fls_const x * fls_const y = fls_const (x*y)\"\n  by    (intro fls_eqI) simp\n\nlemma fls_mult_subdegree_ge:\n  fixes   f g :: \"'a::{comm_monoid_add,mult_zero} fls\"\n  assumes \"f*g \\<noteq> 0\"\n  shows   \"fls_subdegree (f*g) \\<ge> fls_subdegree f + fls_subdegree g\"\n  by      (auto intro: fls_subdegree_geI simp: assms fls_times_nth_eq0)\n\nlemma fls_mult_subdegree_ge_0:\n  fixes   f g :: \"'a::{comm_monoid_add,mult_zero} fls\"\n  assumes \"fls_subdegree f \\<ge> 0\" \"fls_subdegree g \\<ge> 0\"\n  shows   \"fls_subdegree (f*g) \\<ge> 0\"\n  using   assms fls_mult_subdegree_ge[of f g]\n  by      fastforce\n\nlemma fls_mult_nonzero_base_subdegree_eq:\n  fixes   f g :: \"'a::{comm_monoid_add,mult_zero} fls\"\n  assumes \"f $$ (fls_subdegree f) * g $$ (fls_subdegree g) \\<noteq> 0\"\n  shows   \"fls_subdegree (f*g) = fls_subdegree f + fls_subdegree g\"\nproof-\n  from assms have \"fls_subdegree (f*g) \\<ge> fls_subdegree f + fls_subdegree g\"\n    using fls_nonzeroI[of \"f*g\" \"fls_subdegree f + fls_subdegree g\"]\n          fls_mult_subdegree_ge[of f g]\n    by    simp\n  moreover from assms have \"fls_subdegree (f*g) \\<le> fls_subdegree f + fls_subdegree g\"\n    by (intro fls_subdegree_leI) simp\n  ultimately show ?thesis by simp\nqed\n\nlemma fls_subdegree_mult [simp]:\n  fixes   f g :: \"'a::semiring_no_zero_divisors fls\"\n  assumes \"f \\<noteq> 0\" \"g \\<noteq> 0\"\n  shows   \"fls_subdegree (f * g) = fls_subdegree f + fls_subdegree g\"\n  using   assms\n  by      (auto intro: fls_subdegree_eqI simp: fls_times_nth_eq0)\n\nlemma fls_shifted_times_simps:\n  fixes f g :: \"'a::{comm_monoid_add, mult_zero} fls\"\n  shows \"f * (fls_shift n g) = fls_shift n (f*g)\" \"(fls_shift n f) * g = fls_shift n (f*g)\"\nproof-\n\n  show \"f * (fls_shift n g) = fls_shift n (f*g)\"\n  proof (cases \"g=0\")\n    case False\n    hence\n      \"f * (fls_shift n g) =\n        fls_shift (- (fls_subdegree f + (fls_subdegree g - n)))\n          (fps_to_fls (fls_base_factor_to_fps f * fls_base_factor_to_fps g))\"\n      unfolding fls_times_def by (simp add: fls_base_factor_to_fps_shift)\n    thus \"f * (fls_shift n g) = fls_shift n (f*g)\"\n      by (simp add: algebra_simps fls_times_def)\n  qed auto\n\n  show \"(fls_shift n f)*g = fls_shift n (f*g)\"\n  proof (cases \"f=0\")\n    case False\n    hence\n      \"(fls_shift n f)*g =\n        fls_shift (- ((fls_subdegree f - n) + fls_subdegree g))\n          (fps_to_fls (fls_base_factor_to_fps f * fls_base_factor_to_fps g))\"\n      unfolding fls_times_def by (simp add: fls_base_factor_to_fps_shift)\n    thus \"(fls_shift n f) * g = fls_shift n (f*g)\"\n      by (simp add: algebra_simps fls_times_def)\n  qed auto\n\nqed\n\nlemma fls_shifted_times_transfer:\n  fixes f g :: \"'a::{comm_monoid_add, mult_zero} fls\"\n  shows \"fls_shift n f * g = f * fls_shift n g\"\n  using fls_shifted_times_simps(1)[of f n g] fls_shifted_times_simps(2)[of n f g]\n  by    simp\n\nlemma fls_times_both_shifted_simp:\n  fixes f g :: \"'a::{comm_monoid_add, mult_zero} fls\"\n  shows \"(fls_shift m f) * (fls_shift n g) = fls_shift (m+n) (f*g)\"\n  by    (simp add: fls_shifted_times_simps)\n\nlemma fls_base_factor_mult_base_factor:\n  fixes f g :: \"'a::{comm_monoid_add, mult_zero} fls\"\n  shows \"fls_base_factor (f * fls_base_factor g) = fls_base_factor (f * g)\"\n  and   \"fls_base_factor (fls_base_factor f * g) = fls_base_factor (f * g)\"\n  using fls_base_factor_shift[of \"fls_subdegree g\" \"f*g\"]\n        fls_base_factor_shift[of \"fls_subdegree f\" \"f*g\"]\n  by    (simp_all add: fls_shifted_times_simps)\n\nlemma fls_base_factor_mult_both_base_factor:\n  fixes f g :: \"'a::{comm_monoid_add,mult_zero} fls\"\n  shows \"fls_base_factor (fls_base_factor f * fls_base_factor g) = fls_base_factor (f * g)\"\n  using fls_base_factor_mult_base_factor(1)[of \"fls_base_factor f\" g]\n        fls_base_factor_mult_base_factor(2)[of f g]\n  by    simp\n\nlemma fls_base_factor_mult:\n  fixes f g :: \"'a::semiring_no_zero_divisors fls\"\n  shows \"fls_base_factor (f * g) = fls_base_factor f * fls_base_factor g\"\n  by    (cases \"f\\<noteq>0 \\<and> g\\<noteq>0\")\n        (auto simp: fls_times_both_shifted_simp)\n\nlemma fls_times_conv_base_factor_times:\n  fixes f g :: \"'a::{comm_monoid_add, mult_zero} fls\"\n  shows\n    \"f * g =\n      fls_shift (-(fls_subdegree f + fls_subdegree g)) (fls_base_factor f * fls_base_factor g)\"\n  by (simp add: fls_times_both_shifted_simp)\n\nlemma fls_times_base_factor_conv_shifted_times:\n\\<comment> \\<open>Convenience form of lemma @{text \"fls_times_both_shifted_simp\"}.\\<close>\n  fixes f g :: \"'a::{comm_monoid_add, mult_zero} fls\"\n  shows\n    \"fls_base_factor f * fls_base_factor g = fls_shift (fls_subdegree f + fls_subdegree g) (f * g)\"\n  by (simp add: fls_times_both_shifted_simp)\n\nlemma fls_times_conv_regpart:\n  fixes   f g :: \"'a::{comm_monoid_add,mult_zero} fls\"\n  assumes \"fls_subdegree f \\<ge> 0\" \"fls_subdegree g \\<ge> 0\"\n  shows \"fls_regpart (f * g) = fls_regpart f * fls_regpart g\"\nproof-\n  from assms have 1:\n    \"f * g =\n      fls_shift (- (fls_subdegree f + fls_subdegree g)) (\n        fps_to_fls (\n          fps_shift (nat (fls_subdegree f) + nat (fls_subdegree g)) (\n            fls_regpart f * fls_regpart g\n          )\n        )\n      )\"\n    by (simp add:\n      fls_times_def fls_base_factor_to_fps_conv_fps_shift[symmetric]\n      fls_regpart_subdegree_conv fps_shift_mult_both[symmetric]\n    )\n  show ?thesis\n  proof (cases \"fls_regpart f * fls_regpart g = 0\")\n    case False\n    with assms have\n      \"subdegree (fls_regpart f * fls_regpart g) \\<ge>\n        nat (fls_subdegree f) + nat (fls_subdegree g)\"\n      by (simp add: fps_mult_subdegree_ge fls_regpart_subdegree_conv[symmetric])\n    with 1 assms show ?thesis by simp\n  qed (simp add: 1)\nqed\n\nlemma fls_base_factor_to_fps_mult_conv_unit_factor:\n  fixes f g :: \"'a::{comm_monoid_add,mult_zero} fls\"\n  shows\n    \"fls_base_factor_to_fps (f * g) =\n      unit_factor (fls_base_factor_to_fps f * fls_base_factor_to_fps g)\"\n  using fls_base_factor_mult_both_base_factor[of f g]\n        fps_unit_factor_fls_regpart[of \"fls_base_factor f * fls_base_factor g\"]\n        fls_base_factor_subdegree[of f] fls_base_factor_subdegree[of g]\n        fls_mult_subdegree_ge_0[of \"fls_base_factor f\" \"fls_base_factor g\"]\n        fls_times_conv_regpart[of \"fls_base_factor f\" \"fls_base_factor g\"]\n  by    simp\n\nlemma fls_base_factor_to_fps_mult':\n  fixes   f g :: \"'a::{comm_monoid_add,mult_zero} fls\"\n  assumes \"(f $$ fls_subdegree f) * (g $$ fls_subdegree g) \\<noteq> 0\"\n  shows   \"fls_base_factor_to_fps (f * g) = fls_base_factor_to_fps f * fls_base_factor_to_fps g\"\n  using   assms fls_mult_nonzero_base_subdegree_eq[of f g]\n          fls_times_base_factor_conv_shifted_times[of f g]\n          fls_times_conv_regpart[of \"fls_base_factor f\" \"fls_base_factor g\"]\n          fls_base_factor_subdegree[of f] fls_base_factor_subdegree[of g]\n  by      fastforce\n\nlemma fls_base_factor_to_fps_mult:\n  fixes f g :: \"'a::semiring_no_zero_divisors fls\"\n  shows \"fls_base_factor_to_fps (f * g) = fls_base_factor_to_fps f * fls_base_factor_to_fps g\"\n  using fls_base_factor_to_fps_mult'[of f g]\n  by    (cases \"f=0 \\<or> g=0\") auto\n\nlemma fls_times_conv_fps_times:\n  fixes   f g :: \"'a::{comm_monoid_add,mult_zero} fls\"\n  assumes \"fls_subdegree f \\<ge> 0\" \"fls_subdegree g \\<ge> 0\"\n  shows   \"f * g = fps_to_fls (fls_regpart f * fls_regpart g)\"\n  using   assms fls_mult_subdegree_ge[of f g]\n  by      (cases \"f * g = 0\") (simp_all add: fls_times_conv_regpart[symmetric])\n\nlemma fps_times_conv_fls_times:\n  fixes   f g :: \"'a::{comm_monoid_add,mult_zero} fps\"\n  shows   \"f * g = fls_regpart (fps_to_fls f * fps_to_fls g)\"\n  using   fls_subdegree_fls_to_fps_gt0 fls_times_conv_regpart[symmetric]\n  by      fastforce\n\nlemma fls_times_fps_to_fls:\n  fixes f g :: \"'a::{comm_monoid_add,mult_zero} fps\"\n  shows \"fps_to_fls (f * g) = fps_to_fls f * fps_to_fls g\"\nproof (intro fls_eq_conv_fps_eqI, rule fls_subdegree_fls_to_fps_gt0)\n  show \"fls_subdegree (fps_to_fls f * fps_to_fls g) \\<ge> 0\"\n  proof (cases \"fps_to_fls f * fps_to_fls g = 0\")\n    case False thus ?thesis\n      using fls_mult_subdegree_ge fls_subdegree_fls_to_fps_gt0[of f]\n            fls_subdegree_fls_to_fps_gt0[of g]\n      by    fastforce\n  qed simp\nqed (simp add: fps_times_conv_fls_times)\n\nlemma fls_X_times_conv_shift:\n  fixes f :: \"'a::{comm_monoid_add,mult_zero,monoid_mult} fls\"\n  shows \"fls_X * f = fls_shift (-1) f\" \"f * fls_X = fls_shift (-1) f\"\n  by    (simp_all add: fls_X_conv_shift_1 fls_mult_one fls_shifted_times_simps)\n\nlemmas fls_X_times_comm = trans_sym[OF fls_X_times_conv_shift]   \n\nlemma fls_subdegree_mult_fls_X:\n  fixes   f :: \"'a::{comm_monoid_add,mult_zero,monoid_mult} fls\"\n  assumes \"f \\<noteq> 0\"\n  shows   \"fls_subdegree (fls_X * f) = fls_subdegree f + 1\"\n  and     \"fls_subdegree (f * fls_X) = fls_subdegree f + 1\"\n  by      (auto simp: fls_X_times_conv_shift assms)\n\nlemma fls_mult_fls_X_nonzero:\n  fixes   f :: \"'a::{comm_monoid_add,mult_zero,monoid_mult} fls\"\n  assumes \"f \\<noteq> 0\"\n  shows   \"fls_X * f \\<noteq> 0\"\n  and     \"f * fls_X \\<noteq> 0\"\n  by      (auto simp: fls_X_times_conv_shift fls_shift_eq0_iff assms)\n\nlemma fls_base_factor_mult_fls_X:\n  fixes f :: \"'a::{comm_monoid_add,monoid_mult,mult_zero} fls\"\n  shows \"fls_base_factor (fls_X * f) = fls_base_factor f\"\n  and   \"fls_base_factor (f * fls_X) = fls_base_factor f\"\n  using fls_base_factor_shift[of \"-1\" f]\n  by    (auto simp: fls_X_times_conv_shift)\n\nlemma fls_X_inv_times_conv_shift:\n  fixes f :: \"'a::{comm_monoid_add,mult_zero,monoid_mult} fls\"\n  shows \"fls_X_inv * f = fls_shift 1 f\" \"f * fls_X_inv = fls_shift 1 f\"\n  by    (simp_all add: fls_X_inv_conv_shift_1 fls_mult_one fls_shifted_times_simps)\n\nlemmas fls_X_inv_times_comm = trans_sym[OF fls_X_inv_times_conv_shift]\n\nlemma fls_subdegree_mult_fls_X_inv:\n  fixes   f :: \"'a::{comm_monoid_add,mult_zero,monoid_mult} fls\"\n  assumes \"f \\<noteq> 0\"\n  shows   \"fls_subdegree (fls_X_inv * f) = fls_subdegree f - 1\"\n  and     \"fls_subdegree (f * fls_X_inv) = fls_subdegree f - 1\"\n  by      (auto simp: fls_X_inv_times_conv_shift assms)\n\nlemma fls_mult_fls_X_inv_nonzero:\n  fixes   f :: \"'a::{comm_monoid_add,mult_zero,monoid_mult} fls\"\n  assumes \"f \\<noteq> 0\"\n  shows   \"fls_X_inv * f \\<noteq> 0\"\n  and     \"f * fls_X_inv \\<noteq> 0\"\n  by      (auto simp: fls_X_inv_times_conv_shift fls_shift_eq0_iff assms)\n\nlemma fls_base_factor_mult_fls_X_inv:\n  fixes f :: \"'a::{comm_monoid_add,monoid_mult,mult_zero} fls\"\n  shows \"fls_base_factor (fls_X_inv * f) = fls_base_factor f\"\n  and   \"fls_base_factor (f * fls_X_inv) = fls_base_factor f\"\n  using fls_base_factor_shift[of 1 f]\n  by    (auto simp: fls_X_inv_times_conv_shift)\n\nlemma fls_mult_assoc_subdegree_ge_0:\n  fixes   f g h :: \"'a::semiring_0 fls\"\n  assumes \"fls_subdegree f \\<ge> 0\" \"fls_subdegree g \\<ge> 0\" \"fls_subdegree h \\<ge> 0\"\n  shows   \"f * g * h = f * (g * h)\"\n  using   assms\n  by      (simp add: fls_times_conv_fps_times fls_subdegree_fls_to_fps_gt0 mult.assoc)\n\nlemma fls_mult_assoc_base_factor:\n  fixes a b c :: \"'a::semiring_0 fls\"\n  shows\n    \"fls_base_factor a * fls_base_factor b * fls_base_factor c =\n      fls_base_factor a * (fls_base_factor b * fls_base_factor c)\"\n  by    (simp add: fls_mult_assoc_subdegree_ge_0 del: fls_base_factor_def)\n\nlemma fls_mult_distrib_subdegree_ge_0:\n  fixes   f g h :: \"'a::semiring_0 fls\"\n  assumes \"fls_subdegree f \\<ge> 0\" \"fls_subdegree g \\<ge> 0\" \"fls_subdegree h \\<ge> 0\"\n  shows   \"(f + g) * h = f * h + g * h\"\n  and     \"h * (f + g) = h * f + h * g\"\nproof-\n  have \"fls_subdegree (f+g) \\<ge> 0\"\n  proof (cases \"f+g = 0\")\n    case False\n    with assms(1,2) show ?thesis\n      using fls_plus_subdegree by fastforce\n  qed simp\n  with assms show \"(f + g) * h = f * h + g * h\" \"h * (f + g) = h * f + h * g\"\n    using distrib_right[of \"fls_regpart f\"] distrib_left[of \"fls_regpart h\"]\n    by    (simp_all add: fls_times_conv_fps_times)\nqed\n\nlemma fls_mult_distrib_base_factor:\n  fixes a b c :: \"'a::semiring_0 fls\"\n  shows\n    \"fls_base_factor a * (fls_base_factor b + fls_base_factor c) =\n      fls_base_factor a * fls_base_factor b + fls_base_factor a * fls_base_factor c\"\n  by    (simp add: fls_mult_distrib_subdegree_ge_0 del: fls_base_factor_def)\n\ninstance fls :: (semiring_0) semiring_0\nproof\n\n  fix a b c :: \"'a fls\"\n  have\n    \"a * b * c =\n      fls_shift (- (fls_subdegree a + fls_subdegree b + fls_subdegree c))\n        (fls_base_factor a * fls_base_factor b * fls_base_factor c)\"\n    by (simp add: fls_times_both_shifted_simp)\n  moreover have\n    \"a * (b * c) =\n      fls_shift (- (fls_subdegree a + fls_subdegree b + fls_subdegree c))\n        (fls_base_factor a * fls_base_factor b * fls_base_factor c)\"\n    using fls_mult_assoc_base_factor[of a b c] by (simp add: fls_times_both_shifted_simp)\n  ultimately show \"a * b * c = a * (b * c)\" by simp\n\n  have ab:\n    \"fls_subdegree (fls_shift (min (fls_subdegree a) (fls_subdegree b)) a) \\<ge> 0\"\n    \"fls_subdegree (fls_shift (min (fls_subdegree a) (fls_subdegree b)) b) \\<ge> 0\"\n    by (simp_all add: fls_shift_nonneg_subdegree)\n  have\n    \"(a + b) * c =\n      fls_shift (- (min (fls_subdegree a) (fls_subdegree b) + fls_subdegree c)) (\n        (\n          fls_shift (min (fls_subdegree a) (fls_subdegree b)) a +\n          fls_shift (min (fls_subdegree a) (fls_subdegree b)) b\n        ) * fls_base_factor c)\"\n    using fls_times_both_shifted_simp[of\n            \"-min (fls_subdegree a) (fls_subdegree b)\"\n            \"fls_shift (min (fls_subdegree a) (fls_subdegree b)) a +\n            fls_shift (min (fls_subdegree a) (fls_subdegree b)) b\"\n            \"-fls_subdegree c\" \"fls_base_factor c\"\n          ]\n    by    simp\n  also have\n    \"\\<dots> =\n      fls_shift (-(min (fls_subdegree a) (fls_subdegree b) + fls_subdegree c))\n        (fls_shift (min (fls_subdegree a) (fls_subdegree b)) a * fls_base_factor c)\n      +\n      fls_shift (-(min (fls_subdegree a) (fls_subdegree b) + fls_subdegree c))\n        (fls_shift (min (fls_subdegree a) (fls_subdegree b)) b * fls_base_factor c)\"\n    using ab\n    by    (simp add: fls_mult_distrib_subdegree_ge_0(1) del: fls_base_factor_def)\n  finally show \"(a + b) * c = a * c + b * c\" by (simp add: fls_times_both_shifted_simp)\n\n  have bc:\n    \"fls_subdegree (fls_shift (min (fls_subdegree b) (fls_subdegree c)) b) \\<ge> 0\"\n    \"fls_subdegree (fls_shift (min (fls_subdegree b) (fls_subdegree c)) c) \\<ge> 0\"\n    by (simp_all add: fls_shift_nonneg_subdegree)\n  have\n    \"a * (b + c) = \n      fls_shift (- (fls_subdegree a + min (fls_subdegree b) (fls_subdegree c))) (\n        fls_base_factor a * (\n          fls_shift (min (fls_subdegree b) (fls_subdegree c)) b +\n          fls_shift (min (fls_subdegree b) (fls_subdegree c)) c\n        )\n      )\n    \"\n    using fls_times_both_shifted_simp[of\n            \"-fls_subdegree a\" \"fls_base_factor a\"\n            \"-min (fls_subdegree b) (fls_subdegree c)\"\n            \"fls_shift (min (fls_subdegree b) (fls_subdegree c)) b +\n            fls_shift (min (fls_subdegree b) (fls_subdegree c)) c\"\n          ]\n    by    simp\n  also have\n    \"\\<dots> =\n      fls_shift (-(fls_subdegree a + min (fls_subdegree b) (fls_subdegree c)))\n        (fls_base_factor a * fls_shift (min (fls_subdegree b) (fls_subdegree c)) b)\n      +\n      fls_shift (-(fls_subdegree a + min (fls_subdegree b) (fls_subdegree c)))\n        (fls_base_factor a * fls_shift (min (fls_subdegree b) (fls_subdegree c)) c)\n    \"\n    using bc\n    by    (simp add: fls_mult_distrib_subdegree_ge_0(2) del: fls_base_factor_def)\n  finally show \"a * (b + c)  = a * b + a * c\" by (simp add: fls_times_both_shifted_simp)\n\nqed\n\nlemma fls_mult_commute_subdegree_ge_0:\n  fixes   f g :: \"'a::comm_semiring_0 fls\"\n  assumes \"fls_subdegree f \\<ge> 0\" \"fls_subdegree g \\<ge> 0\"\n  shows   \"f * g = g * f\"\n  using   assms\n  by      (simp add: fls_times_conv_fps_times mult.commute)\n\nlemma fls_mult_commute_base_factor:\n  fixes a b c :: \"'a::comm_semiring_0 fls\"\n  shows \"fls_base_factor a * fls_base_factor b = fls_base_factor b * fls_base_factor a\"\n  by    (simp add: fls_mult_commute_subdegree_ge_0 del: fls_base_factor_def)\n\ninstance fls :: (comm_semiring_0) comm_semiring_0\nproof\n  fix a b c :: \"'a fls\"\n  show \"a * b = b * a\"\n    using fls_times_conv_base_factor_times[of a b] fls_times_conv_base_factor_times[of b a]\n          fls_mult_commute_base_factor[of a b]\n    by    (simp add: add.commute)\nqed (simp add: distrib_right)\n\ninstance fls :: (semiring_1) semiring_1\n  by (standard, simp_all add: fls_mult_one)\n\nlemma fls_of_nat: \"(of_nat n :: 'a::semiring_1 fls) = fls_const (of_nat n)\"\n  by (induct n) (auto intro: fls_eqI)\n\nlemma fls_of_nat_nth: \"of_nat n $$ k = (if k=0 then of_nat n else 0)\"\n  by (simp add: fls_of_nat)\n\nlemma fls_mult_of_nat_nth [simp]:\n  shows \"(of_nat k * f) $$ n = of_nat k * f$$n\"\n  and   \"(f * of_nat k ) $$ n = f$$n * of_nat k\"\n  by    (simp_all add: fls_of_nat)\n\nlemma fls_subdegree_of_nat [simp]: \"fls_subdegree (of_nat n) = 0\"\n  by (simp add: fls_of_nat)\n\nlemma fls_shift_of_nat_nth:\n  \"fls_shift k (of_nat a) $$ n = (if n=-k then of_nat a else 0)\"\n  by (simp add: fls_of_nat fls_shift_const_nth)\n\nlemma fls_base_factor_of_nat [simp]:\n  \"fls_base_factor (of_nat n :: 'a::semiring_1 fls) = (of_nat n :: 'a fls)\"\n  by (simp add: fls_of_nat)\n\nlemma fls_regpart_of_nat [simp]: \"fls_regpart (of_nat n) = (of_nat n :: 'a::semiring_1 fps)\"\n  by (simp add: fls_of_nat fps_of_nat)\n\nlemma fls_prpart_of_nat [simp]: \"fls_prpart (of_nat n) = 0\"\n  by (simp add: fls_prpart_eq0_iff)\n\nlemma fls_base_factor_to_fps_of_nat:\n  \"fls_base_factor_to_fps (of_nat n) = (of_nat n :: 'a::semiring_1 fps)\"\n  by simp\n\nlemma fps_to_fls_of_nat:\n  \"fps_to_fls (of_nat n) = (of_nat n :: 'a::semiring_1 fls)\"\nproof -\n  have \"fps_to_fls (of_nat n) = fps_to_fls (fps_const (of_nat n))\"\n    by (simp add: fps_of_nat)\n  thus ?thesis by (simp add: fls_of_nat)\nqed\n\ninstance fls :: (comm_semiring_1) comm_semiring_1\n  by standard simp\n\ninstance fls :: (ring) ring ..\n\ninstance fls :: (comm_ring) comm_ring ..\n\ninstance fls :: (ring_1) ring_1 ..\n\nlemma fls_of_int_nonneg: \"(of_int (int n) :: 'a::ring_1 fls) = fls_const (of_int (int n))\"\n  by (induct n) (auto intro: fls_eqI)\n\nlemma fls_of_int: \"(of_int i :: 'a::ring_1 fls) = fls_const (of_int i)\"\nproof (induct i)\n  case (neg i)\n  have \"of_int (int (Suc i)) = fls_const (of_int (int (Suc i)) :: 'a)\"\n    using fls_of_int_nonneg[of \"Suc i\"] by simp\n  hence \"- of_int (int (Suc i)) = - fls_const (of_int (int (Suc i)) :: 'a)\"\n    by simp\n  thus ?case by (simp add: fls_const_uminus[symmetric])\nqed (rule fls_of_int_nonneg)\n\nlemma fls_of_int_nth: \"of_int n $$ k = (if k=0 then of_int n else 0)\"\n  by (simp add: fls_of_int)\n\nlemma fls_mult_of_int_nth [simp]:\n  shows \"(of_int k * f) $$ n = of_int k * f$$n\"\n  and   \"(f * of_int k ) $$ n = f$$n * of_int k\"\n  by    (simp_all add: fls_of_int)\n\nlemma fls_subdegree_of_int [simp]: \"fls_subdegree (of_int i) = 0\"\n  by (simp add: fls_of_int)\n\nlemma fls_shift_of_int_nth:\n  \"fls_shift k (of_int i) $$ n = (if n=-k then of_int i else 0)\"\n  by (simp add: fls_of_int_nth)\n\nlemma fls_base_factor_of_int [simp]:\n  \"fls_base_factor (of_int i :: 'a::ring_1 fls) = (of_int i :: 'a fls)\"\n  by (simp add: fls_of_int)\n\nlemma fls_regpart_of_int [simp]:\n  \"fls_regpart (of_int i) = (of_int i :: 'a::ring_1 fps)\"\n  by (simp add: fls_of_int fps_of_int)\n\nlemma fls_prpart_of_int [simp]: \"fls_prpart (of_int n) = 0\"\n  by (simp add: fls_prpart_eq0_iff)\n\nlemma fls_base_factor_to_fps_of_int:\n  \"fls_base_factor_to_fps (of_int i) = (of_int i :: 'a::ring_1 fps)\"\n  by simp\n\nlemma fps_to_fls_of_int:\n  \"fps_to_fls (of_int i) = (of_int i :: 'a::ring_1 fls)\"\nproof -\n  have \"fps_to_fls (of_int i) = fps_to_fls (fps_const (of_int i))\"\n    by (simp add: fps_of_int)\n  thus ?thesis by (simp add: fls_of_int)\nqed\n\ninstance fls :: (comm_ring_1) comm_ring_1 ..\n\ninstance fls :: (semiring_no_zero_divisors) semiring_no_zero_divisors\nproof\n  fix a b :: \"'a fls\"\n  assume \"a \\<noteq> 0\" and \"b \\<noteq> 0\"\n  hence \"(a * b) $$ (fls_subdegree a + fls_subdegree b) \\<noteq> 0\" by simp\n  thus \"a * b \\<noteq> 0\" using fls_nonzeroI by fast\nqed\n\ninstance fls :: (semiring_1_no_zero_divisors) semiring_1_no_zero_divisors ..\n\ninstance fls :: (ring_no_zero_divisors) ring_no_zero_divisors ..\n\ninstance fls :: (ring_1_no_zero_divisors) ring_1_no_zero_divisors ..\n\ninstance fls :: (idom) idom ..\n\n\nsubsubsection \\<open>Powers\\<close>\n\nlemma fls_pow_subdegree_ge:\n  \"f^n \\<noteq> 0 \\<Longrightarrow> fls_subdegree (f^n) \\<ge> n * fls_subdegree f\"\nproof (induct n)\n  case (Suc n) thus ?case\n    using fls_mult_subdegree_ge[of f \"f^n\"] by (fastforce simp: algebra_simps)\nqed simp\n\nlemma fls_pow_nth_below_subdegree:\n  \"k < n * fls_subdegree f \\<Longrightarrow> (f^n) $$ k = 0\"\n  using fls_pow_subdegree_ge[of f n] by (cases \"f^n = 0\") auto\n\nlemma fls_pow_base [simp]:\n  \"(f ^ n) $$ (n * fls_subdegree f) = (f $$ fls_subdegree f) ^ n\"\nproof (induct n)\n  case (Suc n)\n  show ?case\n  proof (cases \"Suc n * fls_subdegree f < fls_subdegree f + fls_subdegree (f^n)\")\n    case True with Suc show ?thesis\n      by (simp_all add: fls_times_nth_eq0 distrib_right)\n  next\n    case False\n    from False have\n      \"{0..int n * fls_subdegree f - fls_subdegree (f ^ n)} =\n        insert 0 {1..int n * fls_subdegree f - fls_subdegree (f ^ n)}\"\n      by (auto simp: algebra_simps)\n    with False Suc show ?thesis\n      by (simp add: algebra_simps fls_times_nth(4) fls_pow_nth_below_subdegree)\n  qed\nqed simp\n\nlemma fls_pow_subdegree_eqI:\n  \"(f $$ fls_subdegree f) ^ n \\<noteq> 0 \\<Longrightarrow> fls_subdegree (f^n) = n * fls_subdegree f\"\n  using fls_pow_nth_below_subdegree by (fastforce intro: fls_subdegree_eqI)\n\nlemma fls_unit_base_subdegree_power:\n  \"x * f $$ fls_subdegree f = 1 \\<Longrightarrow> fls_subdegree (f ^ n) = n * fls_subdegree f\"\n  \"f $$ fls_subdegree f * y = 1 \\<Longrightarrow> fls_subdegree (f ^ n) = n * fls_subdegree f\"\nproof-\n  show \"x * f $$ fls_subdegree f = 1 \\<Longrightarrow> fls_subdegree (f ^ n) = n * fls_subdegree f\"\n    using left_right_inverse_power[of x \"f $$ fls_subdegree f\" n]\n    by    (auto intro: fls_pow_subdegree_eqI)\n  show \"f $$ fls_subdegree f * y = 1 \\<Longrightarrow> fls_subdegree (f ^ n) = n * fls_subdegree f\"\n    using left_right_inverse_power[of \"f $$ fls_subdegree f\" y n]\n    by    (auto intro: fls_pow_subdegree_eqI)\nqed\n\nlemma fls_base_dvd1_subdegree_power:\n  \"f $$ fls_subdegree f dvd 1 \\<Longrightarrow> fls_subdegree (f ^ n) = n * fls_subdegree f\"\n  using fls_unit_base_subdegree_power unfolding dvd_def by auto\n\nlemma fls_pow_subdegree_ge0:\n  assumes \"fls_subdegree f \\<ge> 0\"\n  shows   \"fls_subdegree (f^n) \\<ge> 0\"\nproof (cases \"f^n = 0\")\n  case False\n  moreover from assms have \"int n * fls_subdegree f \\<ge> 0\" by simp\n  ultimately show ?thesis using fls_pow_subdegree_ge by fastforce\nqed simp\n\nlemma fls_subdegree_pow:\n  fixes   f :: \"'a::semiring_1_no_zero_divisors fls\"\n  shows   \"fls_subdegree (f ^ n) = n * fls_subdegree f\"\nproof (cases \"f=0\")\n  case False thus ?thesis by (induct n) (simp_all add: algebra_simps)\nqed (cases \"n=0\", auto simp: zero_power)\n\nlemma fls_shifted_pow:\n  \"(fls_shift m f) ^ n = fls_shift (n*m) (f ^ n)\"\n  by (induct n) (simp_all add: fls_times_both_shifted_simp algebra_simps)\n\nlemma fls_pow_conv_fps_pow:\n  assumes \"fls_subdegree f \\<ge> 0\"\n  shows   \"f ^ n = fps_to_fls ( (fls_regpart f) ^ n )\"\nproof (induct n)\n  case (Suc n) with assms show ?case\n    using fls_pow_subdegree_ge0[of f n]\n    by (simp add: fls_times_conv_fps_times)\nqed simp\n\nlemma fps_to_fls_power: \"fps_to_fls (f ^ n) = fps_to_fls f ^ n\"\n  by (simp add: fls_pow_conv_fps_pow fls_subdegree_fls_to_fps_gt0)\n\nlemma fls_pow_conv_regpart:\n  \"fls_subdegree f \\<ge> 0 \\<Longrightarrow> fls_regpart (f ^ n) = (fls_regpart f) ^ n\"\n  by (simp add: fls_pow_conv_fps_pow)\n\ntext \\<open>These two lemmas show that shifting 1 is equivalent to powers of the implied variable.\\<close>\n\nlemma fls_X_power_conv_shift_1: \"fls_X ^ n = fls_shift (-n) 1\"\n  by (simp add: fls_X_conv_shift_1 fls_shifted_pow)\n\nlemma fls_X_inv_power_conv_shift_1: \"fls_X_inv ^ n = fls_shift n 1\"\n  by (simp add: fls_X_inv_conv_shift_1 fls_shifted_pow)\n\nabbreviation \"fls_X_intpow \\<equiv> (\\<lambda>i. fls_shift (-i) 1)\"\n\\<comment> \\<open>\n  Unifies @{term fls_X} and @{term fls_X_inv} so that @{term \"fls_X_intpow\"} returns the equivalent\n  of the implied variable raised to the supplied integer argument of @{term \"fls_X_intpow\"}, whether\n  positive or negative.\n\\<close>\n\nlemma fls_X_intpow_nonzero[simp]: \"(fls_X_intpow i :: 'a::zero_neq_one fls) \\<noteq> 0\"\n  by (simp add: fls_shift_eq0_iff)\n\nlemma fls_X_intpow_power: \"(fls_X_intpow i) ^ n = fls_X_intpow (n * i)\"\n  by (simp add: fls_shifted_pow)\n\nlemma fls_X_power_nth [simp]: \"fls_X ^ n $$ k = (if k=n then 1 else 0)\"\n  by (simp add: fls_X_power_conv_shift_1)\n\nlemma fls_X_inv_power_nth [simp]: \"fls_X_inv ^ n $$ k = (if k=-n then 1 else 0)\"\n  by (simp add: fls_X_inv_power_conv_shift_1)\n\nlemma fls_X_pow_nonzero[simp]: \"(fls_X ^ n :: 'a :: semiring_1 fls) \\<noteq> 0\"\nproof\n  assume \"(fls_X ^ n :: 'a fls) = 0\"\n  hence \"(fls_X ^ n :: 'a fls) $$ n = 0\" by simp\n  thus False by simp\nqed\n\nlemma fls_X_inv_pow_nonzero[simp]: \"(fls_X_inv ^ n :: 'a :: semiring_1 fls) \\<noteq> 0\"\nproof\n  assume \"(fls_X_inv ^ n :: 'a fls) = 0\"\n  hence \"(fls_X_inv ^ n :: 'a fls) $$ -n = 0\" by simp\n  thus False by simp\nqed\n\nlemma fls_subdegree_fls_X_pow [simp]: \"fls_subdegree (fls_X ^ n) = n\"\n  by (intro fls_subdegree_eqI) (simp_all add: fls_X_power_conv_shift_1)\n\nlemma fls_subdegree_fls_X_inv_pow [simp]: \"fls_subdegree (fls_X_inv ^ n) = -n\"\n  by (intro fls_subdegree_eqI) (simp_all add: fls_X_inv_power_conv_shift_1)\n\nlemma fls_subdegree_fls_X_intpow [simp]:\n  \"fls_subdegree ((fls_X_intpow i) :: 'a::zero_neq_one fls) = i\"\n  by simp\n\nlemma fls_X_pow_conv_fps_X_pow: \"fls_regpart (fls_X ^ n) = fps_X ^ n\"\n  by (simp add: fls_pow_conv_regpart)\n\nlemma fls_X_inv_pow_regpart: \"n > 0 \\<Longrightarrow> fls_regpart (fls_X_inv ^ n) = 0\"\n  by (auto intro: fps_ext simp: fls_X_inv_power_conv_shift_1)\n\nlemma fls_X_intpow_regpart:\n  \"fls_regpart (fls_X_intpow i) = (if i\\<ge>0 then fps_X ^ nat i else 0)\"\n  using fls_X_pow_conv_fps_X_pow[of \"nat i\"]\n        fls_regpart_shift_conv_fps_shift[of \"-i\" 1]\n  by    (auto simp: fls_X_power_conv_shift_1 fps_shift_one)\n\nlemma fls_X_power_times_conv_shift:\n  \"fls_X ^ n * f = fls_shift (-int n) f\" \"f * fls_X ^ n = fls_shift (-int n) f\"\n  using fls_times_both_shifted_simp[of \"-int n\" 1 0 f]\n        fls_times_both_shifted_simp[of 0 f \"-int n\" 1]\n  by    (simp_all add: fls_X_power_conv_shift_1)\n\nlemma fls_X_inv_power_times_conv_shift:\n  \"fls_X_inv ^ n * f = fls_shift (int n) f\" \"f * fls_X_inv ^ n = fls_shift (int n) f\"\n  using fls_times_both_shifted_simp[of \"int n\" 1 0 f]\n        fls_times_both_shifted_simp[of 0 f \"int n\" 1]\n  by    (simp_all add: fls_X_inv_power_conv_shift_1)\n\nlemma fls_X_intpow_times_conv_shift:\n  fixes f :: \"'a::semiring_1 fls\"\n  shows \"fls_X_intpow i * f = fls_shift (-i) f\" \"f * fls_X_intpow i = fls_shift (-i) f\"\n  by    (simp_all add: fls_shifted_times_simps)\n\nlemmas fls_X_power_times_comm     = trans_sym[OF fls_X_power_times_conv_shift]\nlemmas fls_X_inv_power_times_comm = trans_sym[OF fls_X_inv_power_times_conv_shift]\n\nlemma fls_X_intpow_times_comm:\n  fixes f :: \"'a::semiring_1 fls\"\n  shows \"fls_X_intpow i * f = f * fls_X_intpow i\"\n  by    (simp add: fls_X_intpow_times_conv_shift)\n\nlemma fls_X_intpow_times_fls_X_intpow:\n  \"(fls_X_intpow i :: 'a::semiring_1 fls) * fls_X_intpow j = fls_X_intpow (i+j)\"\n  by (simp add: fls_times_both_shifted_simp)\n\nlemma fls_X_intpow_diff_conv_times:\n  \"fls_X_intpow (i-j) = (fls_X_intpow i :: 'a::semiring_1 fls) * fls_X_intpow (-j)\"\n  using fls_X_intpow_times_fls_X_intpow[of i \"-j\",symmetric] by simp\n\nlemma fls_mult_fls_X_power_nonzero:\n  assumes \"f \\<noteq> 0\"\n  shows   \"fls_X ^ n * f \\<noteq> 0\" \"f * fls_X ^ n \\<noteq> 0\"\n  by      (auto simp: fls_X_power_times_conv_shift fls_shift_eq0_iff assms)\n\nlemma fls_mult_fls_X_inv_power_nonzero:\n  assumes \"f \\<noteq> 0\"\n  shows   \"fls_X_inv ^ n * f \\<noteq> 0\" \"f * fls_X_inv ^ n \\<noteq> 0\"\n  by      (auto simp: fls_X_inv_power_times_conv_shift fls_shift_eq0_iff assms)\n\nlemma fls_mult_fls_X_intpow_nonzero:\n  fixes f :: \"'a::semiring_1 fls\"\n  assumes \"f \\<noteq> 0\"\n  shows   \"fls_X_intpow i * f \\<noteq> 0\" \"f * fls_X_intpow i \\<noteq> 0\"\n  by      (auto simp: fls_X_intpow_times_conv_shift fls_shift_eq0_iff assms)\n\nlemma fls_subdegree_mult_fls_X_power:\n  assumes \"f \\<noteq> 0\"\n  shows   \"fls_subdegree (fls_X ^ n * f) = fls_subdegree f + n\"\n  and     \"fls_subdegree (f * fls_X ^ n) = fls_subdegree f + n\"\n  by      (auto simp: fls_X_power_times_conv_shift assms)\n\nlemma fls_subdegree_mult_fls_X_inv_power:\n  assumes \"f \\<noteq> 0\"\n  shows   \"fls_subdegree (fls_X_inv ^ n * f) = fls_subdegree f - n\"\n  and     \"fls_subdegree (f * fls_X_inv ^ n) = fls_subdegree f - n\"\n  by      (auto simp: fls_X_inv_power_times_conv_shift assms)\n\nlemma fls_subdegree_mult_fls_X_intpow:\n  fixes   f :: \"'a::semiring_1 fls\"\n  assumes \"f \\<noteq> 0\"\n  shows   \"fls_subdegree (fls_X_intpow i * f) = fls_subdegree f + i\"\n  and     \"fls_subdegree (f * fls_X_intpow i) = fls_subdegree f + i\"\n  by      (auto simp: fls_X_intpow_times_conv_shift assms)\n\nlemma fls_X_shift:\n  \"fls_shift (-int n) fls_X = fls_X ^ Suc n\"\n  \"fls_shift (int (Suc n)) fls_X = fls_X_inv ^ n\"\n  using fls_X_power_conv_shift_1[of \"Suc n\", symmetric]\n  by    (simp_all add: fls_X_conv_shift_1 fls_X_inv_power_conv_shift_1)\n\nlemma fls_X_inv_shift:\n  \"fls_shift (int n) fls_X_inv = fls_X_inv ^ Suc n\"\n  \"fls_shift (- int (Suc n)) fls_X_inv = fls_X ^ n\"\n  using fls_X_inv_power_conv_shift_1[of \"Suc n\", symmetric]\n  by    (simp_all add: fls_X_inv_conv_shift_1 fls_X_power_conv_shift_1)\n\nlemma fls_X_power_base_factor: \"fls_base_factor (fls_X ^ n) = 1\"\n  by (simp add: fls_X_power_conv_shift_1)\n\nlemma fls_X_inv_power_base_factor: \"fls_base_factor (fls_X_inv ^ n) = 1\"\n  by (simp add: fls_X_inv_power_conv_shift_1)\n\nlemma fls_X_intpow_base_factor: \"fls_base_factor (fls_X_intpow i) = 1\"\n  using fls_base_factor_shift[of \"-i\" 1] by simp\n\nlemma fls_base_factor_mult_fls_X_power:\n  shows \"fls_base_factor (fls_X ^ n * f) = fls_base_factor f\"\n  and   \"fls_base_factor (f * fls_X ^ n) = fls_base_factor f\"\n  using fls_base_factor_shift[of \"-int n\" f]\n  by    (auto simp: fls_X_power_times_conv_shift)\n\nlemma fls_base_factor_mult_fls_X_inv_power:\n  shows \"fls_base_factor (fls_X_inv ^ n * f) = fls_base_factor f\"\n  and   \"fls_base_factor (f * fls_X_inv ^ n) = fls_base_factor f\"\n  using fls_base_factor_shift[of \"int n\" f]\n  by    (auto simp: fls_X_inv_power_times_conv_shift)\n\nlemma fls_base_factor_mult_fls_X_intpow:\n  fixes f :: \"'a::semiring_1 fls\"\n  shows \"fls_base_factor (fls_X_intpow i * f) = fls_base_factor f\"\n  and   \"fls_base_factor (f * fls_X_intpow i) = fls_base_factor f\"\n  using fls_base_factor_shift[of \"-i\" f]\n  by    (auto simp: fls_X_intpow_times_conv_shift)\n\nlemma fls_X_power_base_factor_to_fps: \"fls_base_factor_to_fps (fls_X ^ n) = 1\"\nproof-\n  define X where \"X \\<equiv> fls_X :: 'a::semiring_1 fls\"\n  hence \"fls_base_factor (X ^ n) = 1\" using fls_X_power_base_factor by simp\n  thus \"fls_base_factor_to_fps (X^n) = 1\" by simp\nqed  \n\nlemma fls_X_inv_power_base_factor_to_fps: \"fls_base_factor_to_fps (fls_X_inv ^ n) = 1\"\nproof-\n  define iX where \"iX \\<equiv> fls_X_inv :: 'a::semiring_1 fls\"\n  hence \"fls_base_factor (iX ^ n) = 1\" using fls_X_inv_power_base_factor by simp\n  thus \"fls_base_factor_to_fps (iX^n) = 1\" by simp\nqed  \n\nlemma fls_X_intpow_base_factor_to_fps: \"fls_base_factor_to_fps (fls_X_intpow i) = 1\"\nproof-\n  define f :: \"'a fls\" where \"f \\<equiv> fls_X_intpow i\"\n  moreover have \"fls_base_factor (fls_X_intpow i) = 1\" by (rule fls_X_intpow_base_factor)\n  ultimately have \"fls_base_factor f = 1\" by simp\n  thus \"fls_base_factor_to_fps f = 1\" by simp\nqed\n\nlemma fls_base_factor_X_power_decompose:\n  fixes f :: \"'a::semiring_1 fls\"\n  shows \"f = fls_base_factor f * fls_X_intpow (fls_subdegree f)\"\n  and   \"f = fls_X_intpow (fls_subdegree f) * fls_base_factor f\"\n  by    (simp_all add: fls_times_both_shifted_simp)\n\nlemma fls_normalized_product_of_inverses:\n  assumes \"f * g = 1\"\n  shows   \"fls_base_factor f * fls_base_factor g =\n            fls_X ^ (nat (-(fls_subdegree f+fls_subdegree g)))\"\n  and     \"fls_base_factor f * fls_base_factor g =\n            fls_X_intpow (-(fls_subdegree f+fls_subdegree g))\"\n  using   fls_mult_subdegree_ge[of f g]\n          fls_times_base_factor_conv_shifted_times[of f g]\n  by      (simp_all add: assms fls_X_power_conv_shift_1 algebra_simps)\n\nlemma fls_fps_normalized_product_of_inverses:\n  assumes \"f * g = 1\"\n  shows   \"fls_base_factor_to_fps f * fls_base_factor_to_fps g =\n            fps_X ^ (nat (-(fls_subdegree f+fls_subdegree g)))\"\n  using fls_times_conv_regpart[of \"fls_base_factor f\" \"fls_base_factor g\"]\n        fls_base_factor_subdegree[of f] fls_base_factor_subdegree[of g]\n        fls_normalized_product_of_inverses(1)[OF assms]\n  by    (force simp: fls_X_pow_conv_fps_X_pow)\n\n\nsubsubsection \\<open>Inverses\\<close>\n\n\\<comment> \\<open>See lemma fls_left_inverse\\<close> \nabbreviation fls_left_inverse ::\n  \"'a::{comm_monoid_add,uminus,times} fls \\<Rightarrow> 'a \\<Rightarrow> 'a fls\"\n  where\n  \"fls_left_inverse f x \\<equiv>\n    fls_shift (fls_subdegree f) (fps_to_fls (fps_left_inverse (fls_base_factor_to_fps f) x))\"\n\n\\<comment> \\<open>See lemma fls_right_inverse\\<close> \nabbreviation fls_right_inverse ::\n  \"'a::{comm_monoid_add,uminus,times} fls \\<Rightarrow> 'a \\<Rightarrow> 'a fls\"\n  where\n  \"fls_right_inverse f y \\<equiv>\n    fls_shift (fls_subdegree f) (fps_to_fls (fps_right_inverse (fls_base_factor_to_fps f) y))\"\n\ninstantiation fls :: (\"{comm_monoid_add,uminus,times,inverse}\") inverse\nbegin\n  definition fls_divide_def:\n    \"f div g =\n      fls_shift (fls_subdegree g - fls_subdegree f) (\n        fps_to_fls ((fls_base_factor_to_fps f) div (fls_base_factor_to_fps g))\n      )\n    \"\n  definition fls_inverse_def:\n    \"inverse f = fls_shift (fls_subdegree f) (fps_to_fls (inverse (fls_base_factor_to_fps f)))\"\n  instance ..\nend\n\nlemma fls_inverse_def':\n  \"inverse f = fls_right_inverse f (inverse (f $$ fls_subdegree f))\"\n  by (simp add: fls_inverse_def fps_inverse_def)\n\nlemma fls_lr_inverse_base:\n  \"fls_left_inverse f x $$ (-fls_subdegree f) = x\"\n  \"fls_right_inverse f y $$ (-fls_subdegree f) = y\"\n  by auto\n\nlemma fls_inverse_base:\n  \"f \\<noteq> 0 \\<Longrightarrow> inverse f $$ (-fls_subdegree f) = inverse (f $$ fls_subdegree f)\"\n  by (simp add: fls_inverse_def')\n\nlemma fls_lr_inverse_starting0:\n  fixes f :: \"'a::{comm_monoid_add,mult_zero,uminus} fls\"\n  and   g :: \"'b::{ab_group_add,mult_zero} fls\"\n  shows \"fls_left_inverse f 0 = 0\"\n  and   \"fls_right_inverse g 0 = 0\"\n  by    (simp_all add: fps_lr_inverse_starting0)\n\nlemma fls_lr_inverse_eq0_imp_starting0:\n  \"fls_left_inverse f x = 0 \\<Longrightarrow> x = 0\"\n  \"fls_right_inverse f x = 0 \\<Longrightarrow> x = 0\"\n  by (metis fls_lr_inverse_base fls_nonzeroI)+\n\nlemma fls_lr_inverse_eq_0_iff:\n  fixes x :: \"'a::{comm_monoid_add,mult_zero,uminus}\"\n  and   y :: \"'b::{ab_group_add,mult_zero}\"\n  shows \"fls_left_inverse f x = 0 \\<longleftrightarrow> x = 0\"\n  and   \"fls_right_inverse g y = 0 \\<longleftrightarrow> y = 0\"\n  using fls_lr_inverse_starting0 fls_lr_inverse_eq0_imp_starting0\n  by    auto\n\nlemma fls_inverse_eq_0_iff':\n  fixes f :: \"'a::{ab_group_add,inverse,mult_zero} fls\"\n  shows \"inverse f = 0 \\<longleftrightarrow> (inverse (f $$ fls_subdegree f) = 0)\"\n  using fls_lr_inverse_eq_0_iff(2)[of f \"inverse (f $$ fls_subdegree f)\"]\n  by    (simp add: fls_inverse_def')\n\nlemma fls_inverse_eq_0_iff[simp]:\n  \"inverse f = (0:: ('a::division_ring) fls) \\<longleftrightarrow> f $$ fls_subdegree f = 0\"\n  using fls_inverse_eq_0_iff'[of f] by (cases \"f=0\") auto\n\nlemmas fls_inverse_eq_0' = iffD2[OF fls_inverse_eq_0_iff']\nlemmas fls_inverse_eq_0  = iffD2[OF fls_inverse_eq_0_iff]\n\nlemma fls_lr_inverse_const:\n  fixes a :: \"'a::{ab_group_add,mult_zero}\"\n  and   b :: \"'b::{comm_monoid_add,mult_zero,uminus}\"\n  shows \"fls_left_inverse (fls_const a) x = fls_const x\"\n  and   \"fls_right_inverse (fls_const b) y = fls_const y\"\n  by    (simp_all add: fps_const_lr_inverse)\n\nlemma fls_inverse_const:\n  fixes a :: \"'a::{comm_monoid_add,inverse,mult_zero,uminus}\"\n  shows \"inverse (fls_const a) = fls_const (inverse a)\"\n  using fls_lr_inverse_const(2)\n  by    (auto simp: fls_inverse_def')\n\nlemma fls_lr_inverse_of_nat:\n  fixes x :: \"'a::{ring_1,mult_zero}\"\n  and   y :: \"'b::{semiring_1,uminus}\"\n  shows \"fls_left_inverse (of_nat n) x = fls_const x\"\n  and   \"fls_right_inverse (of_nat n) y = fls_const y\"\n  using fls_lr_inverse_const\n  by    (auto simp: fls_of_nat)\n\nlemma fls_inverse_of_nat:\n  \"inverse (of_nat n :: 'a :: {semiring_1,inverse,uminus} fls) = fls_const (inverse (of_nat n))\"\n  by (simp add: fls_inverse_const fls_of_nat)\n\nlemma fls_lr_inverse_of_int:\n  fixes x :: \"'a::{ring_1,mult_zero}\"\n  shows \"fls_left_inverse (of_int n) x = fls_const x\"\n  and   \"fls_right_inverse (of_int n) x = fls_const x\"\n  using fls_lr_inverse_const\n  by    (auto simp: fls_of_int)\n\nlemma fls_inverse_of_int:\n  \"inverse (of_int n :: 'a :: {ring_1,inverse,uminus} fls) = fls_const (inverse (of_int n))\"\n  by      (simp add: fls_inverse_const fls_of_int)\n\nlemma fls_lr_inverse_zero:\n  fixes x :: \"'a::{ab_group_add,mult_zero}\"\n  and   y :: \"'b::{comm_monoid_add,mult_zero,uminus}\"\n  shows \"fls_left_inverse 0 x = fls_const x\"\n  and   \"fls_right_inverse 0 y = fls_const y\"\n  using fls_lr_inverse_const[of 0]\n  by    auto\n\nlemma fls_inverse_zero_conv_fls_const:\n  \"inverse (0::'a::{comm_monoid_add,mult_zero,uminus,inverse} fls) = fls_const (inverse 0)\"\n  using fls_lr_inverse_zero(2)[of \"inverse (0::'a)\"] by (simp add: fls_inverse_def')\n\nlemma fls_inverse_zero':\n  assumes \"inverse (0::'a::{comm_monoid_add,inverse,mult_zero,uminus}) = 0\"\n  shows   \"inverse (0::'a fls) = 0\"\n  by      (simp add: fls_inverse_zero_conv_fls_const assms)\n\nlemma fls_inverse_zero [simp]: \"inverse (0::'a::division_ring fls) = 0\"\n  by (rule fls_inverse_zero'[OF inverse_zero])\n\nlemma fls_inverse_base2:\n  fixes f :: \"'a::{comm_monoid_add,mult_zero,uminus,inverse} fls\"\n  shows \"inverse f $$ (-fls_subdegree f) = inverse (f $$ fls_subdegree f)\"\n  by    (cases \"f=0\") (simp_all add: fls_inverse_zero_conv_fls_const fls_inverse_def')\n\nlemma fls_lr_inverse_one:\n  fixes x :: \"'a::{ab_group_add,mult_zero,one}\"\n  and   y :: \"'b::{comm_monoid_add,mult_zero,uminus,one}\"\n  shows \"fls_left_inverse 1 x = fls_const x\"\n  and   \"fls_right_inverse 1 y = fls_const y\"\n  using fls_lr_inverse_const[of 1]\n  by    auto\n\nlemma fls_lr_inverse_one_one:\n  \"fls_left_inverse 1 1 =\n    (1::'a::{ab_group_add,mult_zero,one} fls)\"\n  \"fls_right_inverse 1 1 =\n    (1::'b::{comm_monoid_add,mult_zero,uminus,one} fls)\"\n  using fls_lr_inverse_one[of 1] by auto\n\nlemma fls_inverse_one:\n  assumes \"inverse (1::'a::{comm_monoid_add,inverse,mult_zero,uminus,one}) = 1\"\n  shows   \"inverse (1::'a fls) = 1\"\n  using   assms fls_lr_inverse_one_one(2)\n  by      (simp add: fls_inverse_def')\n\nlemma fls_left_inverse_delta:\n  fixes   b :: \"'a::{ab_group_add,mult_zero}\"\n  assumes \"b \\<noteq> 0\"\n  shows   \"fls_left_inverse (Abs_fls (\\<lambda>n. if n=a then b else 0)) x =\n            Abs_fls (\\<lambda>n. if n=-a then x else 0)\"\nproof (intro fls_eqI)\n  fix n from assms show\n    \"fls_left_inverse (Abs_fls (\\<lambda>n. if n=a then b else 0)) x $$ n\n      = Abs_fls (\\<lambda>n. if n = - a then x else 0) $$ n\"\n    using fls_base_factor_to_fps_delta[of a b]\n          fls_lr_inverse_const(1)[of b]\n          fls_shift_const\n    by    simp\nqed\n\nlemma fls_right_inverse_delta:\n  fixes   b :: \"'a::{comm_monoid_add,mult_zero,uminus}\"\n  assumes \"b \\<noteq> 0\"\n  shows   \"fls_right_inverse (Abs_fls (\\<lambda>n. if n=a then b else 0)) x =\n            Abs_fls (\\<lambda>n. if n=-a then x else 0)\"\nproof (intro fls_eqI)\n  fix n from assms show\n    \"fls_right_inverse (Abs_fls (\\<lambda>n. if n=a then b else 0)) x $$ n\n      = Abs_fls (\\<lambda>n. if n = - a then x else 0) $$ n\"\n    using fls_base_factor_to_fps_delta[of a b]\n          fls_lr_inverse_const(2)[of b]\n          fls_shift_const\n    by    simp\nqed\n\nlemma fls_inverse_delta_nonzero:\n  fixes   b :: \"'a::{comm_monoid_add,inverse,mult_zero,uminus}\"\n  assumes \"b \\<noteq> 0\"\n  shows   \"inverse (Abs_fls (\\<lambda>n. if n=a then b else 0)) =\n            Abs_fls (\\<lambda>n. if n=-a then inverse b else 0)\"\n  using   assms fls_nonzeroI[of \"Abs_fls (\\<lambda>n. if n=a then b else 0)\" a]\n  by      (simp add: fls_inverse_def' fls_right_inverse_delta[symmetric])\n\nlemma fls_inverse_delta:\n  fixes   b :: \"'a::division_ring\"\n  shows   \"inverse (Abs_fls (\\<lambda>n. if n=a then b else 0)) =\n            Abs_fls (\\<lambda>n. if n=-a then inverse b else 0)\"\n  by      (cases \"b=0\") (simp_all add: fls_inverse_delta_nonzero)\n\nlemma fls_lr_inverse_X:\n  fixes x :: \"'a::{ab_group_add,mult_zero,zero_neq_one}\"\n  and   y :: \"'b::{comm_monoid_add,uminus,mult_zero,zero_neq_one}\"\n  shows \"fls_left_inverse fls_X x = fls_shift 1 (fls_const x)\"\n  and   \"fls_right_inverse fls_X y = fls_shift 1 (fls_const y)\"\n  using fls_lr_inverse_one(1)[of x] fls_lr_inverse_one(2)[of y]\n  by    auto\n\nlemma fls_lr_inverse_X':\n  fixes x :: \"'a::{ab_group_add,mult_zero,zero_neq_one,monoid_mult}\"\n  and   y :: \"'b::{comm_monoid_add,uminus,mult_zero,zero_neq_one,monoid_mult}\"\n  shows \"fls_left_inverse fls_X x = fls_const x * fls_X_inv\"\n  and   \"fls_right_inverse fls_X y = fls_const y * fls_X_inv\"\n  using fls_lr_inverse_X(1)[of x] fls_lr_inverse_X(2)[of y]\n  by    (simp_all add: fls_X_inv_times_conv_shift(2))\n\nlemma fls_inverse_X':\n  assumes \"inverse 1 = (1::'a::{comm_monoid_add,inverse,mult_zero,uminus,zero_neq_one})\"\n  shows   \"inverse (fls_X::'a fls) = fls_X_inv\"\n  using   assms fls_lr_inverse_X(2)[of \"1::'a\"]\n  by      (simp add: fls_inverse_def' fls_X_inv_conv_shift_1)\n\nlemma fls_inverse_X: \"inverse (fls_X::'a::division_ring fls) = fls_X_inv\"\n  by (simp add: fls_inverse_X')\n\nlemma fls_lr_inverse_X_inv:\n  fixes x :: \"'a::{ab_group_add,mult_zero,zero_neq_one}\"\n  and   y :: \"'b::{comm_monoid_add,uminus,mult_zero,zero_neq_one}\"\n  shows \"fls_left_inverse fls_X_inv x = fls_shift (-1) (fls_const x)\"\n  and   \"fls_right_inverse fls_X_inv y = fls_shift (-1) (fls_const y)\"\n  using fls_lr_inverse_one(1)[of x] fls_lr_inverse_one(2)[of y]\n  by    auto\n\nlemma fls_lr_inverse_X_inv':\n  fixes x :: \"'a::{ab_group_add,mult_zero,zero_neq_one,monoid_mult}\"\n  and   y :: \"'b::{comm_monoid_add,uminus,mult_zero,zero_neq_one,monoid_mult}\"\n  shows \"fls_left_inverse fls_X_inv x = fls_const x * fls_X\"\n  and   \"fls_right_inverse fls_X_inv y = fls_const y * fls_X\"\n  using fls_lr_inverse_X_inv(1)[of x] fls_lr_inverse_X_inv(2)[of y]\n  by    (simp_all add: fls_X_times_conv_shift(2))\n\nlemma fls_inverse_X_inv':\n  assumes \"inverse 1 = (1::'a::{comm_monoid_add,inverse,mult_zero,uminus,zero_neq_one})\"\n  shows   \"inverse (fls_X_inv::'a fls) = fls_X\"\n  using   assms fls_lr_inverse_X_inv(2)[of \"1::'a\"]\n  by      (simp add: fls_inverse_def' fls_X_conv_shift_1)\n\nlemma fls_inverse_X_inv: \"inverse (fls_X_inv::'a::division_ring fls) = fls_X\"\n  by (simp add: fls_inverse_X_inv')\n\nlemma fls_lr_inverse_subdegree:\n  assumes \"x \\<noteq> 0\"\n  shows   \"fls_subdegree (fls_left_inverse f x) = - fls_subdegree f\"\n  and     \"fls_subdegree (fls_right_inverse f x) = - fls_subdegree f\"\n  by      (auto intro: fls_subdegree_eqI simp: assms)\n\nlemma fls_inverse_subdegree':\n  \"inverse (f $$ fls_subdegree f) \\<noteq> 0 \\<Longrightarrow> fls_subdegree (inverse f) = - fls_subdegree f\"\n  using fls_lr_inverse_subdegree(2)[of \"inverse (f $$ fls_subdegree f)\"]\n  by    (simp add: fls_inverse_def')\n\nlemma fls_inverse_subdegree [simp]:\n  fixes f :: \"'a::division_ring fls\"\n  shows \"fls_subdegree (inverse f) = - fls_subdegree f\"\n  by    (cases \"f=0\")\n        (auto intro: fls_inverse_subdegree' simp: nonzero_imp_inverse_nonzero)\n\nlemma fls_inverse_subdegree_base_nonzero:\n  assumes \"f \\<noteq> 0\" \"inverse (f $$ fls_subdegree f) \\<noteq> 0\"\n  shows   \"inverse f $$ (fls_subdegree (inverse f)) = inverse (f $$ fls_subdegree f)\"\n  using   assms fls_inverse_subdegree'[of f] fls_inverse_base[of f]\n  by      simp\n\nlemma fls_inverse_subdegree_base:\n  fixes f :: \"'a::{ab_group_add,inverse,mult_zero} fls\"\n  shows \"inverse f $$ (fls_subdegree (inverse f)) = inverse (f $$ fls_subdegree f)\"\n  using fls_inverse_eq_0_iff'[of f] fls_inverse_subdegree_base_nonzero[of f]\n  by    (cases \"f=0 \\<or> inverse (f $$ fls_subdegree f) = 0\")\n        (auto simp: fls_inverse_zero_conv_fls_const)\n\nlemma fls_lr_inverse_subdegree_0:\n  assumes \"fls_subdegree f = 0\"\n  shows   \"fls_subdegree (fls_left_inverse f x) \\<ge> 0\"\n  and     \"fls_subdegree (fls_right_inverse f x) \\<ge> 0\"\n  using   fls_subdegree_ge0I[of \"fls_left_inverse f x\"]\n          fls_subdegree_ge0I[of \"fls_right_inverse f x\"]\n  by      (auto simp: assms)\n\nlemma fls_inverse_subdegree_0:\n  \"fls_subdegree f = 0 \\<Longrightarrow> fls_subdegree (inverse f) \\<ge> 0\"\n  using fls_lr_inverse_subdegree_0(2)[of f] by (simp add: fls_inverse_def')\n\nlemma fls_lr_inverse_shift_nonzero:\n  fixes   f :: \"'a::{comm_monoid_add,mult_zero,uminus} fls\"\n  assumes \"f \\<noteq> 0\"\n  shows   \"fls_left_inverse (fls_shift m f) x = fls_shift (-m) (fls_left_inverse f x)\"\n  and     \"fls_right_inverse (fls_shift m f) x = fls_shift (-m) (fls_right_inverse f x)\"\n  using   assms fls_base_factor_to_fps_shift[of m f] fls_shift_subdegree\n  by      auto\n\nlemma fls_inverse_shift_nonzero:\n  fixes   f :: \"'a::{comm_monoid_add,inverse,mult_zero,uminus} fls\"\n  assumes \"f \\<noteq> 0\"\n  shows   \"inverse (fls_shift m f) = fls_shift (-m) (inverse f)\"\n  using   assms fls_lr_inverse_shift_nonzero(2)[of f m \"inverse (f $$ fls_subdegree f)\"]\n  by      (simp add: fls_inverse_def')\n\nlemma fls_inverse_shift:\n  fixes f :: \"'a::division_ring fls\"\n  shows \"inverse (fls_shift m f) = fls_shift (-m) (inverse f)\"\n  using fls_inverse_shift_nonzero\n  by    (cases \"f=0\") simp_all\n\nlemma fls_left_inverse_base_factor:\n  fixes   x :: \"'a::{ab_group_add,mult_zero}\"\n  assumes \"x \\<noteq> 0\"\n  shows   \"fls_left_inverse (fls_base_factor f) x = fls_base_factor (fls_left_inverse f x)\"\n  using   assms fls_lr_inverse_zero(1)[of x] fls_lr_inverse_subdegree(1)[of x]\n  by      (cases \"f=0\") auto\n\nlemma fls_right_inverse_base_factor:\n  fixes   y :: \"'a::{comm_monoid_add,mult_zero,uminus}\"\n  assumes \"y \\<noteq> 0\"\n  shows   \"fls_right_inverse (fls_base_factor f) y = fls_base_factor (fls_right_inverse f y)\"\n  using   assms fls_lr_inverse_zero(2)[of y] fls_lr_inverse_subdegree(2)[of y]\n  by      (cases \"f=0\") auto\n\nlemma fls_inverse_base_factor':\n  fixes   f :: \"'a::{comm_monoid_add,inverse,mult_zero,uminus} fls\"\n  assumes \"inverse (f $$ fls_subdegree f) \\<noteq> 0\"\n  shows   \"inverse (fls_base_factor f) = fls_base_factor (inverse f)\"\n  by      (cases \"f=0\")\n          (simp_all add:\n            assms fls_inverse_shift_nonzero fls_inverse_subdegree'\n            fls_inverse_zero_conv_fls_const\n          )\n\nlemma fls_inverse_base_factor:\n  fixes f :: \"'a::{ab_group_add,inverse,mult_zero} fls\"\n  shows \"inverse (fls_base_factor f) = fls_base_factor (inverse f)\"\n  using fls_base_factor_base[of f] fls_inverse_eq_0_iff'[of f]\n        fls_inverse_eq_0_iff'[of \"fls_base_factor f\"] fls_inverse_base_factor'[of f]\n  by    (cases \"inverse (f $$ fls_subdegree f) = 0\") simp_all\n\nlemma fls_lr_inverse_regpart:\n  assumes \"fls_subdegree f = 0\"\n  shows   \"fls_regpart (fls_left_inverse f x) = fps_left_inverse (fls_regpart f) x\"\n  and     \"fls_regpart (fls_right_inverse f y) = fps_right_inverse (fls_regpart f) y\"\n  using   assms\n  by      auto\n\nlemma fls_inverse_regpart:\n  assumes \"fls_subdegree f = 0\"\n  shows   \"fls_regpart (inverse f) = inverse (fls_regpart f)\"\n  by      (simp add: assms fls_inverse_def)\n\nlemma fls_base_factor_to_fps_left_inverse:\n  fixes   x :: \"'a::{ab_group_add,mult_zero}\"\n  shows   \"fls_base_factor_to_fps (fls_left_inverse f x) =\n            fps_left_inverse (fls_base_factor_to_fps f) x\"\n  using   fls_left_inverse_base_factor[of x f] fls_base_factor_subdegree[of f]\n  by      (cases \"x=0\") (simp_all add: fls_lr_inverse_starting0(1) fps_lr_inverse_starting0(1))\n\nlemma fls_base_factor_to_fps_right_inverse_nonzero:\n  fixes   y :: \"'a::{comm_monoid_add,mult_zero,uminus}\"\n  assumes \"y \\<noteq> 0\"\n  shows   \"fls_base_factor_to_fps (fls_right_inverse f y) =\n            fps_right_inverse (fls_base_factor_to_fps f) y\"\n  using   assms fls_right_inverse_base_factor[of y f]\n          fls_base_factor_subdegree[of f]\n  by      simp\n\nlemma fls_base_factor_to_fps_right_inverse:\n  fixes   y :: \"'a::{ab_group_add,mult_zero}\"\n  shows   \"fls_base_factor_to_fps (fls_right_inverse f y) =\n            fps_right_inverse (fls_base_factor_to_fps f) y\"\n  using   fls_base_factor_to_fps_right_inverse_nonzero[of y f]\n  by      (cases \"y=0\") (simp_all add: fls_lr_inverse_starting0(2) fps_lr_inverse_starting0(2))\n\nlemma fls_base_factor_to_fps_inverse_nonzero:\n  fixes   f :: \"'a::{comm_monoid_add,inverse,mult_zero,uminus} fls\"\n  assumes \"inverse (f $$ fls_subdegree f) \\<noteq> 0\"\n  shows   \"fls_base_factor_to_fps (inverse f) = inverse (fls_base_factor_to_fps f)\"\n  using   assms fls_base_factor_to_fps_right_inverse_nonzero\n  by      (simp add: fls_inverse_def' fps_inverse_def)\n\nlemma fls_base_factor_to_fps_inverse:\n  fixes f :: \"'a::{ab_group_add,inverse,mult_zero} fls\"\n  shows \"fls_base_factor_to_fps (inverse f) = inverse (fls_base_factor_to_fps f)\"\n  using fls_base_factor_to_fps_right_inverse\n  by    (simp add: fls_inverse_def' fps_inverse_def)\n\nlemma fls_lr_inverse_fps_to_fls:\n  assumes \"subdegree f = 0\"\n  shows   \"fls_left_inverse (fps_to_fls f) x = fps_to_fls (fps_left_inverse f x)\"\n  and     \"fls_right_inverse (fps_to_fls f) x = fps_to_fls (fps_right_inverse f x)\"\n  using   assms fls_base_factor_to_fps_to_fls[of f]\n  by      (simp_all add: fls_subdegree_fls_to_fps)\n\nlemma fls_inverse_fps_to_fls:\n  \"subdegree f = 0 \\<Longrightarrow> inverse (fps_to_fls f) = fps_to_fls (inverse f)\"\n  using nth_subdegree_nonzero[of f]\n  by  (cases \"f=0\")\n      (auto simp add:\n        fps_to_fls_nonzeroI fls_inverse_def' fls_subdegree_fls_to_fps fps_inverse_def\n        fls_lr_inverse_fps_to_fls(2)\n      )\n\nlemma fls_lr_inverse_X_power:\n  fixes x :: \"'a::ring_1\"\n  and   y :: \"'b::{semiring_1,uminus}\"\n  shows \"fls_left_inverse (fls_X ^ n) x = fls_shift n (fls_const x)\"\n  and   \"fls_right_inverse (fls_X ^ n) y = fls_shift n (fls_const y)\"\n  using fls_lr_inverse_one(1)[of x] fls_lr_inverse_one(2)[of y]\n  by    (simp_all add: fls_X_power_conv_shift_1)\n\nlemma fls_lr_inverse_X_power':\n  fixes x :: \"'a::ring_1\"\n  and   y :: \"'b::{semiring_1,uminus}\"\n  shows \"fls_left_inverse (fls_X ^ n) x = fls_const x * fls_X_inv ^ n\"\n  and   \"fls_right_inverse (fls_X ^ n) y = fls_const y * fls_X_inv ^ n\"\n  using fls_lr_inverse_X_power(1)[of n x] fls_lr_inverse_X_power(2)[of n y]\n  by    (simp_all add: fls_X_inv_power_times_conv_shift(2))\n\nlemma fls_inverse_X_power':\n  assumes \"inverse 1 = (1::'a::{semiring_1,uminus,inverse})\"\n  shows   \"inverse ((fls_X ^ n)::'a fls) = fls_X_inv ^ n\"\n  using   fls_lr_inverse_X_power'(2)[of n 1]\n  by      (simp add: fls_inverse_def' assms )\n\nlemma fls_inverse_X_power:\n  \"inverse ((fls_X::'a::division_ring fls) ^ n) = fls_X_inv ^ n\"\n  by (simp add: fls_inverse_X_power')\n\nlemma fls_lr_inverse_X_inv_power:\n  fixes x :: \"'a::ring_1\"\n  and   y :: \"'b::{semiring_1,uminus}\"\n  shows \"fls_left_inverse (fls_X_inv ^ n) x = fls_shift (-n) (fls_const x)\"\n  and   \"fls_right_inverse (fls_X_inv ^ n) y = fls_shift (-n) (fls_const y)\"\n  using fls_lr_inverse_one(1)[of x] fls_lr_inverse_one(2)[of y]\n  by    (simp_all add: fls_X_inv_power_conv_shift_1)\n\nlemma fls_lr_inverse_X_inv_power':\n  fixes x :: \"'a::ring_1\"\n  and   y :: \"'b::{semiring_1,uminus}\"\n  shows \"fls_left_inverse (fls_X_inv ^ n) x = fls_const x * fls_X ^ n\"\n  and   \"fls_right_inverse (fls_X_inv ^ n) y = fls_const y * fls_X ^ n\"\n  using fls_lr_inverse_X_inv_power(1)[of n x] fls_lr_inverse_X_inv_power(2)[of n y]\n  by    (simp_all add: fls_X_power_times_conv_shift(2))\n\nlemma fls_inverse_X_inv_power':\n  assumes \"inverse 1 = (1::'a::{semiring_1,uminus,inverse})\"\n  shows   \"inverse ((fls_X_inv ^ n)::'a fls) = fls_X ^ n\"\n  using   fls_lr_inverse_X_inv_power'(2)[of n 1]\n  by      (simp add: fls_inverse_def' assms)\n\nlemma fls_inverse_X_inv_power:\n  \"inverse ((fls_X_inv::'a::division_ring fls) ^ n) = fls_X ^ n\"\n  by (simp add: fls_inverse_X_inv_power')\n\nlemma fls_lr_inverse_X_intpow:\n  fixes x :: \"'a::ring_1\"\n  and   y :: \"'b::{semiring_1,uminus}\"\n  shows \"fls_left_inverse (fls_X_intpow i) x = fls_shift i (fls_const x)\"\n  and   \"fls_right_inverse (fls_X_intpow i) y = fls_shift i (fls_const y)\"\n  using fls_lr_inverse_one(1)[of x] fls_lr_inverse_one(2)[of y]\n  by    auto\n\nlemma fls_lr_inverse_X_intpow':\n  fixes x :: \"'a::ring_1\"\n  and   y :: \"'b::{semiring_1,uminus}\"\n  shows \"fls_left_inverse (fls_X_intpow i) x = fls_const x * fls_X_intpow (-i)\"\n  and   \"fls_right_inverse (fls_X_intpow i) y = fls_const y * fls_X_intpow (-i)\"\n  using fls_lr_inverse_X_intpow(1)[of i x] fls_lr_inverse_X_intpow(2)[of i y]\n  by    (simp_all add: fls_shifted_times_simps(1))\n\nlemma fls_inverse_X_intpow':\n  assumes \"inverse 1 = (1::'a::{semiring_1,uminus,inverse})\"\n  shows   \"inverse (fls_X_intpow i :: 'a fls) = fls_X_intpow (-i)\"\n  using   fls_lr_inverse_X_intpow'(2)[of i 1]\n  by      (simp add: fls_inverse_def' assms)\n\nlemma fls_inverse_X_intpow:\n  \"inverse (fls_X_intpow i :: 'a::division_ring fls) = fls_X_intpow (-i)\"\n  by (simp add: fls_inverse_X_intpow')\n\nlemma fls_left_inverse:\n  fixes   f :: \"'a::ring_1 fls\"\n  assumes \"x * f $$ fls_subdegree f = 1\"\n  shows   \"fls_left_inverse f x * f = 1\"\nproof-\n  from assms have \"x \\<noteq> 0\" \"x * (fls_base_factor_to_fps f$0) = 1\" by auto\n  thus ?thesis\n    using fls_base_factor_to_fps_left_inverse[of f x]\n          fls_lr_inverse_subdegree(1)[of x] fps_left_inverse\n    by    (fastforce simp: fls_times_def)\nqed\n\nlemma fls_right_inverse:\n  fixes   f :: \"'a::ring_1 fls\"\n  assumes \"f $$ fls_subdegree f * y = 1\"\n  shows   \"f * fls_right_inverse f y = 1\"\nproof-\n  from assms have \"y \\<noteq> 0\" \"(fls_base_factor_to_fps f$0) * y = 1\" by auto\n  thus ?thesis\n    using fls_base_factor_to_fps_right_inverse[of f y]\n          fls_lr_inverse_subdegree(2)[of y] fps_right_inverse\n    by    (fastforce simp: fls_times_def)\nqed\n\n\\<comment> \\<open>\n  It is possible in a ring for an element to have a left inverse but not a right inverse, or\n  vice versa. But when an element has both, they must be the same.\n\\<close>\nlemma fls_left_inverse_eq_fls_right_inverse:\n  fixes   f :: \"'a::ring_1 fls\"\n  assumes \"x * f $$ fls_subdegree f = 1\" \"f $$ fls_subdegree f * y = 1\"\n  \\<comment> \\<open>These assumptions imply x equals y, but no need to assume that.\\<close>\n  shows   \"fls_left_inverse f x = fls_right_inverse f y\"\n  using   assms\n  by      (simp add: fps_left_inverse_eq_fps_right_inverse)\n\nlemma fls_left_inverse_eq_inverse:\n  fixes   f :: \"'a::division_ring fls\"\n  shows   \"fls_left_inverse f (inverse (f $$ fls_subdegree f)) = inverse f\"\nproof (cases \"f=0\")\n  case True\n  hence \"fls_left_inverse f (inverse (f $$ fls_subdegree f)) = fls_const (0::'a)\"\n    by (simp add: fls_lr_inverse_zero(1)[symmetric])\n  with True show ?thesis by simp\nnext\n  case False thus ?thesis\n    using fls_left_inverse_eq_fls_right_inverse[of \"inverse (f $$ fls_subdegree f)\"]\n    by    (auto simp add: fls_inverse_def')\nqed\n\nlemma fls_right_inverse_eq_inverse:\n  fixes f :: \"'a::division_ring fls\"\n  shows \"fls_right_inverse f (inverse (f $$ fls_subdegree f)) = inverse f\"\nproof (cases \"f=0\")\n  case True\n  hence \"fls_right_inverse f (inverse (f $$ fls_subdegree f)) = fls_const (0::'a)\"\n    by (simp add: fls_lr_inverse_zero(2)[symmetric])\n  with True show ?thesis by simp\nqed (simp add: fls_inverse_def')\n\nlemma fls_left_inverse_eq_fls_right_inverse_comm:\n  fixes   f :: \"'a::comm_ring_1 fls\"\n  assumes \"x * f $$ fls_subdegree f = 1\"\n  shows   \"fls_left_inverse f x = fls_right_inverse f x\"\n  using   assms fls_left_inverse_eq_fls_right_inverse[of x f x]\n  by      (simp add: mult.commute)\n\nlemma fls_left_inverse':\n  fixes   f :: \"'a::ring_1 fls\"\n  assumes \"x * f $$ fls_subdegree f = 1\" \"f $$ fls_subdegree f * y = 1\"\n  \\<comment> \\<open>These assumptions imply x equals y, but no need to assume that.\\<close>\n  shows   \"fls_right_inverse f y * f = 1\"\n  using   assms fls_left_inverse_eq_fls_right_inverse[of x f y] fls_left_inverse[of x f]\n  by      simp\n\nlemma fls_right_inverse':\n  fixes   f :: \"'a::ring_1 fls\"\n  assumes \"x * f $$ fls_subdegree f = 1\" \"f $$ fls_subdegree f * y = 1\"\n  \\<comment> \\<open>These assumptions imply x equals y, but no need to assume that.\\<close>\n  shows   \"f * fls_left_inverse f x = 1\"\n  using   assms fls_left_inverse_eq_fls_right_inverse[of x f y] fls_right_inverse[of f y]\n  by      simp\n\nlemma fls_mult_left_inverse_base_factor:\n  fixes   f :: \"'a::ring_1 fls\"\n  assumes \"x * (f $$ fls_subdegree f) = 1\"\n  shows   \"fls_left_inverse (fls_base_factor f) x * f = fls_X_intpow (fls_subdegree f)\"\n  using   assms fls_base_factor_to_fps_base_factor[of f] fls_base_factor_subdegree[of f]\n          fls_shifted_times_simps(2)[of \"-fls_subdegree f\" \"fls_left_inverse f x\" f]\n          fls_left_inverse[of x f]\n  by      simp\n\nlemma fls_mult_right_inverse_base_factor:\n  fixes   f :: \"'a::ring_1 fls\"\n  assumes \"(f $$ fls_subdegree f) * y = 1\"\n  shows   \"f * fls_right_inverse (fls_base_factor f) y = fls_X_intpow (fls_subdegree f)\"\n  using   assms fls_base_factor_to_fps_base_factor[of f] fls_base_factor_subdegree[of f]\n          fls_shifted_times_simps(1)[of f \"-fls_subdegree f\" \"fls_right_inverse f y\"]\n          fls_right_inverse[of f y]\n  by      simp\n\nlemma fls_mult_inverse_base_factor:\n  fixes   f :: \"'a::division_ring fls\"\n  assumes \"f \\<noteq> 0\"\n  shows   \"f * inverse (fls_base_factor f) = fls_X_intpow (fls_subdegree f)\"\n  using   fls_mult_right_inverse_base_factor[of f \"inverse (f $$ fls_subdegree f)\"]\n          fls_base_factor_base[of f]\n  by      (simp add: assms fls_right_inverse_eq_inverse[symmetric])\n\nlemma fls_left_inverse_idempotent_ring1:\n  fixes   f :: \"'a::ring_1 fls\"\n  assumes \"x * f $$ fls_subdegree f = 1\" \"y * x = 1\"\n  \\<comment> \\<open>These assumptions imply y equals f $$ fls_subdegree f, but no need to assume that.\\<close>\n  shows   \"fls_left_inverse (fls_left_inverse f x) y = f\"\nproof-\n  from assms(1) have\n    \"fls_left_inverse (fls_left_inverse f x) y * fls_left_inverse f x * f =\n      fls_left_inverse (fls_left_inverse f x) y\"\n    using fls_left_inverse[of x f]\n    by    (simp add: mult.assoc)\n  moreover have\n    \"fls_left_inverse (fls_left_inverse f x) y * fls_left_inverse f x = 1\"\n    using assms fls_lr_inverse_subdegree(1)[of x f] fls_lr_inverse_base(1)[of f x]\n    by    (fastforce intro: fls_left_inverse)\n  ultimately show ?thesis by simp\nqed\n\nlemma fls_left_inverse_idempotent_comm_ring1:\n  fixes   f :: \"'a::comm_ring_1 fls\"\n  assumes \"x * f $$ fls_subdegree f = 1\"\n  shows   \"fls_left_inverse (fls_left_inverse f x) (f $$ fls_subdegree f) = f\"\n  using   assms fls_left_inverse_idempotent_ring1[of x f \"f $$ fls_subdegree f\"]\n  by      (simp add: mult.commute)\n\nlemma fls_right_inverse_idempotent_ring1:\n  fixes   f :: \"'a::ring_1 fls\"\n  assumes \"f $$ fls_subdegree f * x = 1\" \"x * y = 1\"\n  \\<comment> \\<open>These assumptions imply y equals f $$ fls_subdegree f, but no need to assume that.\\<close>\n  shows   \"fls_right_inverse (fls_right_inverse f x) y = f\"\nproof-\n  from assms(1) have\n    \"f * (fls_right_inverse f x * fls_right_inverse (fls_right_inverse f x) y) =\n      fls_right_inverse (fls_right_inverse f x) y\"\n    using fls_right_inverse [of f] \n    by (simp add: mult.assoc[symmetric])\n  moreover have\n    \"fls_right_inverse f x * fls_right_inverse (fls_right_inverse f x) y = 1\"\n    using assms fls_lr_inverse_subdegree(2)[of x f] fls_lr_inverse_base(2)[of f x]\n    by    (fastforce intro: fls_right_inverse)\n  ultimately show ?thesis by simp\nqed\n\nlemma fls_right_inverse_idempotent_comm_ring1:\n  fixes   f :: \"'a::comm_ring_1 fls\"\n  assumes \"f $$ fls_subdegree f * x = 1\"\n  shows   \"fls_right_inverse (fls_right_inverse f x) (f $$ fls_subdegree f) = f\"\n  using   assms fls_right_inverse_idempotent_ring1[of f x \"f $$ fls_subdegree f\"]\n  by      (simp add: mult.commute)\n\nlemma fls_lr_inverse_unique_ring1:\n  fixes   f g :: \"'a :: ring_1 fls\"\n  assumes fg: \"f * g = 1\" \"g $$ fls_subdegree g * f $$ fls_subdegree f = 1\"\n  shows   \"fls_left_inverse g (f $$ fls_subdegree f) = f\"\n  and     \"fls_right_inverse f (g $$ fls_subdegree g) = g\"\nproof-\n\n  have \"f $$ fls_subdegree f * g $$ fls_subdegree g \\<noteq> 0\"\n  proof\n    assume \"f $$ fls_subdegree f * g $$ fls_subdegree g = 0\"\n    hence \"f $$ fls_subdegree f * (g $$ fls_subdegree g * f $$ fls_subdegree f) = 0\"\n      by (simp add: mult.assoc[symmetric])\n    with fg(2) show False by simp\n  qed\n  with fg(1) have subdeg_sum: \"fls_subdegree f + fls_subdegree g = 0\"\n    using fls_mult_nonzero_base_subdegree_eq[of f g] by simp\n  hence subdeg_sum':\n    \"fls_subdegree f = -fls_subdegree g\" \"fls_subdegree g = -fls_subdegree f\"\n    by auto\n\n  from fg(1) have f_ne_0: \"f\\<noteq>0\" by auto\n  moreover have\n    \"fps_left_inverse (fls_base_factor_to_fps g) (fls_regpart (fls_shift (-fls_subdegree g) f)$0)\n      = fls_regpart (fls_shift (-fls_subdegree g) f)\"\n  proof (intro fps_lr_inverse_unique_ring1(1))\n    from fg(1) show\n      \"fls_regpart (fls_shift (-fls_subdegree g) f) * fls_base_factor_to_fps g = 1\"\n      using f_ne_0 fls_times_conv_regpart[of \"fls_shift (-fls_subdegree g) f\" \"fls_base_factor g\"]\n            fls_base_factor_subdegree[of g]\n      by    (simp add: fls_times_both_shifted_simp subdeg_sum)\n    from fg(2) show\n      \"fls_base_factor_to_fps g $ 0 * fls_regpart (fls_shift (-fls_subdegree g) f) $ 0 = 1\"\n      by (simp add: subdeg_sum'(2))\n  qed\n  ultimately show \"fls_left_inverse g (f $$ fls_subdegree f) = f\"\n    by (simp add: subdeg_sum'(2))\n\n  from fg(1) have g_ne_0: \"g\\<noteq>0\" by auto\n  moreover have\n    \"fps_right_inverse (fls_base_factor_to_fps f) (fls_regpart (fls_shift (-fls_subdegree f) g)$0)\n      = fls_regpart (fls_shift (-fls_subdegree f) g)\"\n  proof (intro fps_lr_inverse_unique_ring1(2))\n    from fg(1) show\n      \"fls_base_factor_to_fps f * fls_regpart (fls_shift (-fls_subdegree f) g) = 1\"\n      using g_ne_0 fls_times_conv_regpart[of \"fls_base_factor f\" \"fls_shift (-fls_subdegree f) g\"]\n            fls_base_factor_subdegree[of f]\n      by    (simp add: fls_times_both_shifted_simp subdeg_sum add.commute)\n    from fg(2) show\n      \"fls_regpart (fls_shift (-fls_subdegree f) g) $ 0 * fls_base_factor_to_fps f $ 0 = 1\"\n      by (simp add: subdeg_sum'(1))\n  qed\n  ultimately show \"fls_right_inverse f (g $$ fls_subdegree g) = g\"\n    by (simp add: subdeg_sum'(2))\n\nqed\n\nlemma fls_lr_inverse_unique_divring:\n  fixes   f g :: \"'a ::division_ring fls\"\n  assumes fg: \"f * g = 1\"\n  shows   \"fls_left_inverse g (f $$ fls_subdegree f) = f\"\n  and     \"fls_right_inverse f (g $$ fls_subdegree g) = g\"\nproof-\n  from fg have \"f \\<noteq>0\" \"g \\<noteq> 0\" by auto\n  with fg have \"fls_subdegree f + fls_subdegree g = 0\" using fls_subdegree_mult by force\n  with fg have \"f $$ fls_subdegree f * g $$ fls_subdegree g = 1\"\n    using fls_times_base[of f g] by simp\n  hence \"g $$ fls_subdegree g * f $$ fls_subdegree f = 1\"\n    using inverse_unique[of \"f $$ fls_subdegree f\"] left_inverse[of \"f $$ fls_subdegree f\"]\n    by    force\n  thus\n    \"fls_left_inverse g (f $$ fls_subdegree f) = f\"\n    \"fls_right_inverse f (g $$ fls_subdegree g) = g\"\n    using fg fls_lr_inverse_unique_ring1\n    by    auto\nqed\n\nlemma fls_lr_inverse_minus:\n  fixes f :: \"'a::ring_1 fls\"\n  shows \"fls_left_inverse (-f) (-x) = - fls_left_inverse f x\"\n  and   \"fls_right_inverse (-f) (-x) = - fls_right_inverse f x\"\n  by (simp_all add: fps_lr_inverse_minus)\n\nlemma fls_inverse_minus [simp]: \"inverse (-f) = -inverse (f :: 'a :: division_ring fls)\"\n  using fls_lr_inverse_minus(2)[of f] by (simp add: fls_inverse_def')\n\nlemma fls_lr_inverse_mult_ring1:\n  fixes   f g :: \"'a::ring_1 fls\"\n  assumes x: \"x * f $$ fls_subdegree f = 1\" \"f $$ fls_subdegree f * x = 1\"\n  and     y: \"y * g $$ fls_subdegree g = 1\" \"g $$ fls_subdegree g * y = 1\"\n  shows   \"fls_left_inverse (f * g) (y*x) = fls_left_inverse g y * fls_left_inverse f x\"\n  and     \"fls_right_inverse (f * g) (y*x) = fls_right_inverse g y * fls_right_inverse f x\"\nproof-\n  from x(1) y(2) have \"x * (f $$ fls_subdegree f * g $$ fls_subdegree g) * y = 1\"\n    by (simp add: mult.assoc)\n  hence base_prod: \"f $$ fls_subdegree f * g $$ fls_subdegree g \\<noteq> 0\" by auto\n  hence subdegrees: \"fls_subdegree (f*g) = fls_subdegree f + fls_subdegree g\"\n    using fls_mult_nonzero_base_subdegree_eq[of f g] by simp\n\n  have norm:\n    \"fls_base_factor_to_fps (f * g) = fls_base_factor_to_fps f * fls_base_factor_to_fps g\"\n    using base_prod fls_base_factor_to_fps_mult'[of f g] by simp\n\n  have\n    \"fls_left_inverse (f * g) (y*x) =\n      fls_shift (fls_subdegree (f * g)) (\n        fps_to_fls (\n          fps_left_inverse (fls_base_factor_to_fps f * fls_base_factor_to_fps g) (y*x)\n        )\n      )\n    \"\n    using norm\n    by    simp\n  thus \"fls_left_inverse (f * g) (y*x) = fls_left_inverse g y * fls_left_inverse f x\"\n    using x y\n          fps_lr_inverse_mult_ring1(1)[of\n            x \"fls_base_factor_to_fps f\" y \"fls_base_factor_to_fps g\"\n          ]\n    by    (simp add:\n            fls_times_both_shifted_simp fls_times_fps_to_fls subdegrees algebra_simps\n          )\n\n  have\n    \"fls_right_inverse (f * g) (y*x) =\n      fls_shift (fls_subdegree (f * g)) (\n        fps_to_fls (\n          fps_right_inverse (fls_base_factor_to_fps f * fls_base_factor_to_fps g) (y*x)\n        )\n      )\n    \"\n    using norm\n    by    simp\n  thus \"fls_right_inverse (f * g) (y*x) = fls_right_inverse g y * fls_right_inverse f x\"\n    using x y\n          fps_lr_inverse_mult_ring1(2)[of\n            x \"fls_base_factor_to_fps f\" y \"fls_base_factor_to_fps g\"\n          ]\n    by    (simp add:\n            fls_times_both_shifted_simp fls_times_fps_to_fls subdegrees algebra_simps\n          )\n\nqed\n\nlemma fls_lr_inverse_power_ring1:\n  fixes   f :: \"'a::ring_1 fls\"\n  assumes x: \"x * f $$ fls_subdegree f = 1\" \"f $$ fls_subdegree f * x = 1\"\n  shows   \"fls_left_inverse (f ^ n) (x ^ n) = (fls_left_inverse f x) ^ n\"\n          \"fls_right_inverse (f ^ n) (x ^ n) = (fls_right_inverse f x) ^ n\"\nproof-\n\n  show \"fls_left_inverse (f ^ n) (x ^ n) = (fls_left_inverse f x) ^ n\"\n  proof (induct n)\n    case 0 show ?case using fls_lr_inverse_one(1)[of 1] by simp\n  next\n    case (Suc n) with assms show ?case\n      using fls_lr_inverse_mult_ring1(1)[of x f \"x^n\" \"f^n\"]\n      by    (simp add:\n              power_Suc2[symmetric] fls_unit_base_subdegree_power(1) left_right_inverse_power\n            )\n  qed\n\n  show \"fls_right_inverse (f ^ n) (x ^ n) = (fls_right_inverse f x) ^ n\"\n  proof (induct n)\n    case 0 show ?case using fls_lr_inverse_one(2)[of 1] by simp\n  next\n    case (Suc n) with assms show ?case\n      using fls_lr_inverse_mult_ring1(2)[of x f \"x^n\" \"f^n\"]\n      by    (simp add:\n              power_Suc2[symmetric] fls_unit_base_subdegree_power(1) left_right_inverse_power\n            )\n  qed\n\nqed\n\nlemma fls_divide_convert_times_inverse:\n  fixes   f g :: \"'a::{comm_monoid_add,inverse,mult_zero,uminus} fls\"\n  shows   \"f / g = f * inverse g\"\n  using fls_base_factor_to_fps_subdegree[of g] fps_to_fls_base_factor_to_fps[of f]\n        fls_times_both_shifted_simp[of \"-fls_subdegree f\" \"fls_base_factor f\"]\n  by    (simp add:\n          fls_divide_def fps_divide_unit' fls_times_fps_to_fls\n          fls_conv_base_factor_shift_subdegree fls_inverse_def\n        )\n\ninstance fls :: (division_ring) division_ring\nproof\n  fix a b :: \"'a fls\"\n  show \"a \\<noteq> 0 \\<Longrightarrow> inverse a * a = 1\"\n    using fls_left_inverse'[of \"inverse (a $$ fls_subdegree a)\" a]\n    by    (simp add: fls_inverse_def')\n  show \"a \\<noteq> 0 \\<Longrightarrow> a * inverse a = 1\"\n    using fls_right_inverse[of a]\n    by    (simp add: fls_inverse_def')\n  show \"a / b = a * inverse b\" using fls_divide_convert_times_inverse by fast\n  show \"inverse (0::'a fls) = 0\" by simp\nqed\n\nlemma fls_lr_inverse_mult_divring:\n  fixes   f g   :: \"'a::division_ring fls\"\n  and     df dg :: int\n  defines \"df \\<equiv> fls_subdegree f\"\n  and     \"dg \\<equiv> fls_subdegree g\"\n  shows   \"fls_left_inverse (f*g) (inverse ((f*g)$$(df+dg))) =\n            fls_left_inverse g (inverse (g$$dg)) * fls_left_inverse f (inverse (f$$df))\"\n  and     \"fls_right_inverse (f*g) (inverse ((f*g)$$(df+dg))) =\n            fls_right_inverse g (inverse (g$$dg)) * fls_right_inverse f (inverse (f$$df))\"\nproof -\n  show\n    \"fls_left_inverse (f*g) (inverse ((f*g)$$(df+dg))) =\n      fls_left_inverse g (inverse (g$$dg)) * fls_left_inverse f (inverse (f$$df))\"\n  proof (cases \"f=0 \\<or> g=0\")\n    case True thus ?thesis\n      using fls_lr_inverse_zero(1)[of \"inverse (0::'a)\"] by (auto simp add: assms)\n  next\n    case False thus ?thesis\n      using fls_left_inverse_eq_inverse[of \"f*g\"] nonzero_inverse_mult_distrib[of f g]\n            fls_left_inverse_eq_inverse[of g] fls_left_inverse_eq_inverse[of f]\n      by    (simp add: assms)\n  qed\n  show\n    \"fls_right_inverse (f*g) (inverse ((f*g)$$(df+dg))) =\n      fls_right_inverse g (inverse (g$$dg)) * fls_right_inverse f (inverse (f$$df))\"\n  proof (cases \"f=0 \\<or> g=0\")\n    case True thus ?thesis\n      using fls_lr_inverse_zero(2)[of \"inverse (0::'a)\"] by (auto simp add: assms)\n  next\n    case False thus ?thesis\n      using fls_inverse_def'[of \"f*g\"] nonzero_inverse_mult_distrib[of f g]\n            fls_inverse_def'[of g] fls_inverse_def'[of f]\n      by    (simp add: assms)\n  qed\nqed\n\nlemma fls_lr_inverse_power_divring:\n  \"fls_left_inverse (f ^ n) ((inverse (f $$ fls_subdegree f)) ^ n) =\n    (fls_left_inverse f (inverse (f $$ fls_subdegree f))) ^ n\" (is ?P)\n  and \"fls_right_inverse (f ^ n) ((inverse (f $$ fls_subdegree f)) ^ n) =\n    (fls_right_inverse f (inverse (f $$ fls_subdegree f))) ^ n\" (is ?Q)\n  for f :: \"'a::division_ring fls\"\nproof -\n  note fls_left_inverse_eq_inverse [of f] fls_right_inverse_eq_inverse[of f]\n  moreover have\n    \"fls_right_inverse (f ^ n) ((inverse (f $$ fls_subdegree f)) ^ n) =\n      inverse f ^ n\"\n    using fls_right_inverse_eq_inverse [of \"f ^ n\"]\n    by (simp add: fls_subdegree_pow power_inverse)\n  moreover have\n    \"fls_left_inverse (f ^ n) ((inverse (f $$ fls_subdegree f)) ^ n) =\n      inverse f ^ n\"\n    using fls_left_inverse_eq_inverse [of \"f ^ n\"]\n    by (simp add: fls_subdegree_pow power_inverse)\n  ultimately show ?P and ?Q\n    by simp_all\nqed\n\ninstance fls :: (field) field\n  by (standard, simp_all add: field_simps)\n\n\nsubsubsection \\<open>Division\\<close>\n\nlemma fls_divide_nth_below:\n  fixes f g :: \"'a::{comm_monoid_add,uminus,times,inverse} fls\"\n  shows \"n < fls_subdegree f - fls_subdegree g \\<Longrightarrow> (f div g) $$ n = 0\"\n  by    (simp add: fls_divide_def)\n\nlemma fls_divide_nth_base:\n  fixes f g :: \"'a::division_ring fls\"\n  shows\n    \"(f div g) $$ (fls_subdegree f - fls_subdegree g) =\n      f $$ fls_subdegree f / g $$ fls_subdegree g\"\n  using fps_divide_nth_0'[of \"fls_base_factor_to_fps g\" \"fls_base_factor_to_fps f\"]\n        fls_base_factor_to_fps_subdegree[of g]\n  by    (simp add: fls_divide_def)\n\nlemma fls_div_zero [simp]:\n  \"0 div (g :: 'a :: {comm_monoid_add,inverse,mult_zero,uminus} fls) = 0\"\n  by (simp add: fls_divide_def)\n\nlemma fls_div_by_zero:\n  fixes   g :: \"'a::{comm_monoid_add,inverse,mult_zero,uminus} fls\"\n  assumes \"inverse (0::'a) = 0\"\n  shows   \"g div 0 = 0\"\n  by      (simp add: fls_divide_def assms fps_div_by_zero')\n\nlemma fls_divide_times:\n  fixes f g :: \"'a::{semiring_0,inverse,uminus} fls\"\n  shows \"(f * g) / h = f * (g / h)\"\n  by    (simp add: fls_divide_convert_times_inverse mult.assoc)\n\nlemma fls_divide_times2:\n  fixes f g :: \"'a::{comm_semiring_0,inverse,uminus} fls\"\n  shows \"(f * g) / h = (f / h) * g\"\n  using fls_divide_times[of g f h]\n  by    (simp add: mult.commute)\n\nlemma fls_divide_subdegree_ge:\n  fixes   f g :: \"'a::{comm_monoid_add,uminus,times,inverse} fls\"\n  assumes \"f / g \\<noteq> 0\"\n  shows   \"fls_subdegree (f / g) \\<ge> fls_subdegree f - fls_subdegree g\"\n  using   assms fls_divide_nth_below\n  by      (intro fls_subdegree_geI) simp\n\nlemma fls_divide_subdegree:\n  fixes   f g :: \"'a::division_ring fls\"\n  assumes \"f \\<noteq> 0\" \"g \\<noteq> 0\"\n  shows   \"fls_subdegree (f / g) = fls_subdegree f - fls_subdegree g\"\nproof (intro antisym)\n  from assms have \"f $$ fls_subdegree f / g $$ fls_subdegree g \\<noteq> 0\" by (simp add: field_simps)\n  thus \"fls_subdegree (f/g) \\<le> fls_subdegree f - fls_subdegree g\"\n    using fls_divide_nth_base[of f g] by (intro fls_subdegree_leI) simp\n  from assms have \"f / g \\<noteq> 0\" by (simp add: field_simps)\n  thus \"fls_subdegree (f/g) \\<ge> fls_subdegree f - fls_subdegree g\"\n    using fls_divide_subdegree_ge by fast\nqed\n\nlemma fls_divide_shift_numer_nonzero:\n  fixes   f g :: \"'a :: {comm_monoid_add,inverse,times,uminus} fls\"\n  assumes \"f \\<noteq> 0\"\n  shows   \"fls_shift m f / g = fls_shift m (f/g)\"\n  using   assms fls_base_factor_to_fps_shift[of m f]\n  by      (simp add: fls_divide_def algebra_simps)\n\nlemma fls_divide_shift_numer:\n  fixes f g :: \"'a :: {comm_monoid_add,inverse,mult_zero,uminus} fls\"\n  shows \"fls_shift m f / g = fls_shift m (f/g)\"\n  using fls_divide_shift_numer_nonzero\n  by    (cases \"f=0\") auto\n\nlemma fls_divide_shift_denom_nonzero:\n  fixes   f g :: \"'a :: {comm_monoid_add,inverse,times,uminus} fls\"\n  assumes \"g \\<noteq> 0\"\n  shows   \"f / fls_shift m g = fls_shift (-m) (f/g)\"\n  using   assms fls_base_factor_to_fps_shift[of m g]\n  by      (simp add: fls_divide_def algebra_simps)\n\nlemma fls_divide_shift_denom:\n  fixes   f g :: \"'a :: division_ring fls\"\n  shows   \"f / fls_shift m g = fls_shift (-m) (f/g)\"\n  using   fls_divide_shift_denom_nonzero\n  by      (cases \"g=0\") auto\n\nlemma fls_divide_shift_both_nonzero:\n  fixes   f g :: \"'a :: {comm_monoid_add,inverse,times,uminus} fls\"\n  assumes \"f \\<noteq> 0\" \"g \\<noteq> 0\"\n  shows   \"fls_shift n f / fls_shift m g = fls_shift (n-m) (f/g)\"\n  by      (simp add: assms fls_divide_shift_numer_nonzero fls_divide_shift_denom_nonzero)\n\nlemma fls_divide_shift_both [simp]:\n  fixes   f g :: \"'a :: division_ring fls\"\n  shows   \"fls_shift n f / fls_shift m g = fls_shift (n-m) (f/g)\"\n  using   fls_divide_shift_both_nonzero\n  by      (cases \"f=0 \\<or> g=0\") auto\n\nlemma fls_divide_base_factor_numer:\n  \"fls_base_factor f / g = fls_shift (fls_subdegree f) (f/g)\"\n  using fls_base_factor_to_fps_base_factor[of f]\n        fls_base_factor_subdegree[of f]\n  by    (simp add: fls_divide_def algebra_simps)\n\nlemma fls_divide_base_factor_denom:\n  \"f / fls_base_factor g = fls_shift (-fls_subdegree g) (f/g)\"\n  using fls_base_factor_to_fps_base_factor[of g]\n        fls_base_factor_subdegree[of g]\n  by    (simp add: fls_divide_def)\n\nlemma fls_divide_base_factor':\n  \"fls_base_factor f / fls_base_factor g = fls_shift (fls_subdegree f - fls_subdegree g) (f/g)\"\n  using fls_divide_base_factor_numer[of f \"fls_base_factor g\"]\n        fls_divide_base_factor_denom[of f g]\n  by    simp\n\nlemma fls_divide_base_factor:\n  fixes f g :: \"'a :: division_ring fls\"\n  shows \"fls_base_factor f / fls_base_factor g = fls_base_factor (f/g)\"\n  using fls_divide_subdegree[of f g] fls_divide_base_factor'\n  by    fastforce\n\nlemma fls_divide_regpart:\n  fixes   f g :: \"'a::{inverse,comm_monoid_add,uminus,mult_zero} fls\"\n  assumes \"fls_subdegree f \\<ge> 0\" \"fls_subdegree g \\<ge> 0\"\n  shows   \"fls_regpart (f / g) = fls_regpart f / fls_regpart g\"\nproof -\n  have deg0:\n    \"\\<And>g. fls_subdegree g = 0 \\<Longrightarrow>\n      fls_regpart (f / g) = fls_regpart f / fls_regpart g\"\n    by  (simp add:\n          assms(1) fls_divide_convert_times_inverse fls_inverse_subdegree_0\n          fls_times_conv_regpart fls_inverse_regpart fls_regpart_subdegree_conv fps_divide_unit'\n        )\n  show ?thesis\n  proof (cases \"fls_subdegree g = 0\")\n    case False\n    hence \"fls_base_factor g \\<noteq> 0\" using fls_base_factor_nonzero[of g] by force\n    with assms(2) show ?thesis\n      using fls_divide_shift_denom_nonzero[of \"fls_base_factor g\" f \"-fls_subdegree g\"]\n            fps_shift_fls_regpart_conv_fls_shift[of\n              \"nat (fls_subdegree g)\" \"f / fls_base_factor g\"\n            ]\n            fls_base_factor_subdegree[of g] deg0\n            fls_regpart_subdegree_conv[of g] fps_unit_factor_fls_regpart[of g]\n      by    (simp add:\n              fls_conv_base_factor_shift_subdegree fls_regpart_subdegree_conv fps_divide_def\n            )\n  qed (rule deg0)\nqed\n\nlemma fls_divide_fls_base_factor_to_fps':\n  fixes f g :: \"'a::{comm_monoid_add,uminus,inverse,mult_zero} fls\"\n  shows\n    \"fls_base_factor_to_fps f / fls_base_factor_to_fps g =\n      fls_regpart (fls_shift (fls_subdegree f - fls_subdegree g) (f / g))\"\n  using fls_base_factor_subdegree[of f] fls_base_factor_subdegree[of g]\n        fls_divide_regpart[of \"fls_base_factor f\" \"fls_base_factor g\"]\n        fls_divide_base_factor'[of f g]\n    by  simp\n\nlemma fls_divide_fls_base_factor_to_fps:\n  fixes f g :: \"'a::division_ring fls\"\n  shows \"fls_base_factor_to_fps f / fls_base_factor_to_fps g = fls_base_factor_to_fps (f / g)\"\n  using fls_divide_fls_base_factor_to_fps' fls_divide_subdegree[of f g]\n  by    fastforce\n\nlemma fls_divide_fps_to_fls:\n  fixes f g :: \"'a::{inverse,ab_group_add,mult_zero} fps\"\n  assumes \"subdegree f \\<ge> subdegree g\"\n  shows   \"fps_to_fls f / fps_to_fls g = fps_to_fls (f/g)\"\nproof-\n  have 1:\n    \"fps_to_fls f / fps_to_fls g =\n      fls_shift (int (subdegree g)) (fps_to_fls (f * inverse (unit_factor g)))\"\n    using fls_base_factor_to_fps_to_fls[of f] fls_base_factor_to_fps_to_fls[of g]\n          fls_subdegree_fls_to_fps[of f] fls_subdegree_fls_to_fps[of g]\n          fps_divide_def[of \"unit_factor f\" \"unit_factor g\"]\n          fls_times_fps_to_fls[of \"unit_factor f\" \"inverse (unit_factor g)\"]\n          fls_shifted_times_simps(2)[of \"-int (subdegree f)\" \"fps_to_fls (unit_factor f)\"]\n          fls_times_fps_to_fls[of f \"inverse (unit_factor g)\"]\n    by    (simp add: fls_divide_def)\n  with assms show ?thesis\n    using fps_mult_subdegree_ge[of f \"inverse (unit_factor g)\"]\n          fps_shift_to_fls[of \"subdegree g\" \"f * inverse (unit_factor g)\"]\n    by    (cases \"f * inverse (unit_factor g) = 0\") (simp_all add: fps_divide_def)\nqed\n\nlemma fls_divide_1':\n  fixes   f :: \"'a::{comm_monoid_add,inverse,mult_zero,uminus,zero_neq_one,monoid_mult} fls\"\n  assumes \"inverse (1::'a) = 1\"\n  shows   \"f / 1 = f\"\n  using   assms fls_conv_base_factor_to_fps_shift_subdegree[of f]\n  by      (simp add: fls_divide_def fps_divide_1')\n\nlemma fls_divide_1 [simp]: \"a / 1 = (a::'a::division_ring fls)\"\n  by (rule fls_divide_1'[OF inverse_1])\n\nlemma fls_const_divide_const:\n  fixes x y :: \"'a::division_ring\"\n  shows \"fls_const x / fls_const y = fls_const (x/y)\"\n  by    (simp add: fls_divide_def fls_base_factor_to_fps_const fps_const_divide)\n\nlemma fls_divide_X':\n  fixes   f :: \"'a::{comm_monoid_add,inverse,mult_zero,uminus,zero_neq_one,monoid_mult} fls\"\n  assumes \"inverse (1::'a) = 1\"\n  shows   \"f / fls_X = fls_shift 1 f\"\nproof-\n  from assms have\n    \"f / fls_X =\n      fls_shift 1 (fls_shift (-fls_subdegree f) (fps_to_fls (fls_base_factor_to_fps f)))\"\n    by (simp add: fls_divide_def fps_divide_1')\n  also have \"\\<dots> = fls_shift 1 f\"\n    using fls_conv_base_factor_to_fps_shift_subdegree[of f]\n    by simp\n  finally show ?thesis by simp\nqed\n\nlemma fls_divide_X [simp]:\n  fixes f :: \"'a::division_ring fls\"\n  shows \"f / fls_X = fls_shift 1 f\"\n  by    (rule fls_divide_X'[OF inverse_1])\n\nlemma fls_divide_X_power':\n  fixes   f :: \"'a::{semiring_1,inverse,uminus} fls\"\n  assumes \"inverse (1::'a) = 1\"\n  shows   \"f / (fls_X ^ n) = fls_shift n f\"\nproof-\n  have \"fls_base_factor_to_fps ((fls_X::'a fls) ^ n) = 1\" by (rule fls_X_power_base_factor_to_fps)\n  with assms have\n    \"f / (fls_X ^ n) =\n      fls_shift n (fls_shift (-fls_subdegree f) (fps_to_fls (fls_base_factor_to_fps f)))\"\n    by (simp add: fls_divide_def fps_divide_1')\n  also have \"\\<dots> = fls_shift n f\"\n    using fls_conv_base_factor_to_fps_shift_subdegree[of f] by simp\n  finally show ?thesis by simp\nqed\n\nlemma fls_divide_X_power [simp]:\n  fixes f :: \"'a::division_ring fls\"\n  shows \"f / (fls_X ^ n) = fls_shift n f\"\n  by    (rule fls_divide_X_power'[OF inverse_1])\n\nlemma fls_divide_X_inv':\n  fixes   f :: \"'a::{comm_monoid_add,inverse,mult_zero,uminus,zero_neq_one,monoid_mult} fls\"\n  assumes \"inverse (1::'a) = 1\"\n  shows   \"f / fls_X_inv = fls_shift (-1) f\"\nproof-\n  from assms have\n    \"f / fls_X_inv =\n      fls_shift (-1) (fls_shift (-fls_subdegree f) (fps_to_fls (fls_base_factor_to_fps f)))\"\n    by (simp add: fls_divide_def fps_divide_1' algebra_simps)\n  also have \"\\<dots> = fls_shift (-1) f\"\n    using fls_conv_base_factor_to_fps_shift_subdegree[of f]\n    by simp\n  finally show ?thesis by simp\nqed\n\nlemma fls_divide_X_inv [simp]:\n  fixes f :: \"'a::division_ring fls\"\n  shows \"f / fls_X_inv = fls_shift (-1) f\"\n  by    (rule fls_divide_X_inv'[OF inverse_1])\n\nlemma fls_divide_X_inv_power':\n  fixes   f :: \"'a::{semiring_1,inverse,uminus} fls\"\n  assumes \"inverse (1::'a) = 1\"\n  shows   \"f / (fls_X_inv ^ n) = fls_shift (-int n) f\"\nproof-\n  have \"fls_base_factor_to_fps ((fls_X_inv::'a fls) ^ n) = 1\"\n    by (rule fls_X_inv_power_base_factor_to_fps)\n  with assms have\n    \"f / (fls_X_inv ^ n) =\n      fls_shift (-int n + -fls_subdegree f) (fps_to_fls (fls_base_factor_to_fps f))\"\n    by (simp add: fls_divide_def fps_divide_1')\n  also have\n    \"\\<dots> = fls_shift (-int n) (fls_shift (-fls_subdegree f) (fps_to_fls (fls_base_factor_to_fps f)))\"\n    by (simp add: add.commute)\n  also have \"\\<dots> = fls_shift (-int n) f\"\n    using fls_conv_base_factor_to_fps_shift_subdegree[of f] by simp\n  finally show ?thesis by simp\nqed\n\nlemma fls_divide_X_inv_power [simp]:\n  fixes f :: \"'a::division_ring fls\"\n  shows \"f / (fls_X_inv ^ n) = fls_shift (-int n) f\"\n  by    (rule fls_divide_X_inv_power'[OF inverse_1])\n\nlemma fls_divide_X_intpow':\n  fixes   f :: \"'a::{semiring_1,inverse,uminus} fls\"\n  assumes \"inverse (1::'a) = 1\"\n  shows   \"f / (fls_X_intpow i) = fls_shift i f\"\n  using   assms\n  by      (simp add: fls_divide_shift_denom_nonzero fls_divide_1')\n\nlemma fls_divide_X_intpow_conv_times':\n  fixes   f :: \"'a::{semiring_1,inverse,uminus} fls\"\n  assumes \"inverse (1::'a) = 1\"\n  shows   \"f / (fls_X_intpow i) = f * fls_X_intpow (-i)\"\n  using   assms fls_X_intpow_times_conv_shift(2)[of f \"-i\"]\n  by      (simp add: fls_divide_X_intpow')\n\nlemma fls_divide_X_intpow:\n  fixes f :: \"'a::division_ring fls\"\n  shows \"f / (fls_X_intpow i) = fls_shift i f\"\n  by    (rule fls_divide_X_intpow'[OF inverse_1])\n\nlemma fls_divide_X_intpow_conv_times:\n  fixes f :: \"'a::division_ring fls\"\n  shows \"f / (fls_X_intpow i) = f * fls_X_intpow (-i)\"\n  by    (rule fls_divide_X_intpow_conv_times'[OF inverse_1])\n\nlemma fls_X_intpow_div_fls_X_intpow_semiring1:\n  assumes \"inverse (1::'a::{semiring_1,inverse,uminus}) = 1\"\n  shows   \"(fls_X_intpow i :: 'a fls) / fls_X_intpow j = fls_X_intpow (i-j)\"\n  by      (simp add: assms fls_divide_shift_both_nonzero fls_divide_1')\n\nlemma fls_X_intpow_div_fls_X_intpow:\n  \"(fls_X_intpow i :: 'a::division_ring fls) / fls_X_intpow j = fls_X_intpow (i-j)\"\n  by (rule fls_X_intpow_div_fls_X_intpow_semiring1[OF inverse_1])\n\nlemma fls_divide_add:\n  fixes   f g h :: \"'a::{semiring_0,inverse,uminus} fls\"\n  shows   \"(f + g) / h = f / h + g / h\"\n  by      (simp add: fls_divide_convert_times_inverse algebra_simps)\n\nlemma fls_divide_diff:\n  fixes f g h :: \"'a::{ring,inverse} fls\"\n  shows \"(f - g) / h = f / h - g / h\"\n  by    (simp add: fls_divide_convert_times_inverse algebra_simps)\n\nlemma fls_divide_uminus:\n  fixes f g h :: \"'a::{ring,inverse} fls\"\n  shows \"(- f) / g = - (f / g)\"\n  by    (simp add: fls_divide_convert_times_inverse)\n\nlemma fls_divide_uminus':\n  fixes f g h :: \"'a::division_ring fls\"\n  shows \"f / (- g) = - (f / g)\"\n  by    (simp add: fls_divide_convert_times_inverse)\n\n\nsubsubsection \\<open>Units\\<close>\n\nlemma fls_is_left_unit_iff_base_is_left_unit:\n  fixes f :: \"'a :: ring_1_no_zero_divisors fls\"\n  shows \"(\\<exists>g. 1 = f * g) \\<longleftrightarrow> (\\<exists>k. 1 = f $$ fls_subdegree f * k)\"\nproof\n  assume \"\\<exists>g. 1 = f * g\"\n  then obtain g where \"1 = f * g\" by fast\n  hence \"1 = (f $$ fls_subdegree f) * (g $$ fls_subdegree g)\"\n    using fls_subdegree_mult[of f g] fls_times_base[of f g] by fastforce\n  thus \"\\<exists>k. 1 = f $$ fls_subdegree f * k\" by fast\nnext\n  assume \"\\<exists>k. 1 = f $$ fls_subdegree f * k\"\n  then obtain k where \"1 = f $$ fls_subdegree f * k\" by fast\n  hence \"1 = f * fls_right_inverse f k\"\n    using fls_right_inverse by simp\n  thus \"\\<exists>g. 1 = f * g\" by fast\nqed\n\nlemma fls_is_right_unit_iff_base_is_right_unit:\n  fixes f :: \"'a :: ring_1_no_zero_divisors fls\"\n  shows \"(\\<exists>g. 1 = g * f) \\<longleftrightarrow> (\\<exists>k. 1 = k * f $$ fls_subdegree f)\"\nproof\n  assume \"\\<exists>g. 1 = g * f\"\n  then obtain g where \"1 = g * f\" by fast\n  hence \"1 = (g $$ fls_subdegree g) * (f $$ fls_subdegree f)\"\n    using fls_subdegree_mult[of g f] fls_times_base[of g f] by fastforce\n  thus \"\\<exists>k. 1 = k * f $$ fls_subdegree f\" by fast\nnext\n  assume \"\\<exists>k. 1 = k * f $$ fls_subdegree f\"\n  then obtain k where \"1 = k * f $$ fls_subdegree f\" by fast\n  hence \"1 = fls_left_inverse f k * f\"\n    using fls_left_inverse by simp\n  thus \"\\<exists>g. 1 = g * f\" by fast\nqed\n\nsubsection \\<open>Composition\\<close>\n\ndefinition fls_compose_fps :: \"'a :: field fls \\<Rightarrow> 'a fps \\<Rightarrow> 'a fls\" where\n  \"fls_compose_fps f g =\n     (if f = 0 then 0\n      else if fls_subdegree f \\<ge> 0 then fps_to_fls (fps_compose (fls_regpart f) g)\n      else fps_to_fls (fps_compose (fls_base_factor_to_fps f) g) /\n             fps_to_fls g ^ nat (-fls_subdegree f))\"\n\nlemma fls_compose_fps_fps [simp]:\n  \"fls_compose_fps (fps_to_fls f) g = fps_to_fls (fps_compose f g)\"\n  by (simp add: fls_compose_fps_def fls_subdegree_fls_to_fps_gt0 fps_to_fls_eq_0_iff)\n\nlemma fls_const_transfer [transfer_rule]:\n  \"rel_fun (=) (pcr_fls (=))\n     (\\<lambda>c n. if n = 0 then c else 0) fls_const\"\n  by (auto simp: fls_const_def rel_fun_def pcr_fls_def OO_def cr_fls_def)\n\nlemma fls_shift_transfer [transfer_rule]:\n  \"rel_fun (=) (rel_fun (pcr_fls (=)) (pcr_fls (=)))\n     (\\<lambda>n f k. f (k+n)) fls_shift\"\n  by (auto simp: fls_const_def rel_fun_def pcr_fls_def OO_def cr_fls_def)\n\nlift_definition fls_compose_power :: \"'a :: zero fls \\<Rightarrow> nat \\<Rightarrow> 'a fls\" is\n  \"\\<lambda>f d n. if d > 0 \\<and> int d dvd n then f (n div int d) else 0\"\nproof -\n  fix f :: \"int \\<Rightarrow> 'a\" and d :: nat\n  assume *: \"eventually (\\<lambda>n. f (-int n) = 0) cofinite\"\n  show \"eventually (\\<lambda>n. (if d > 0 \\<and> int d dvd -int n then f (-int n div int d) else 0) = 0) cofinite\"\n  proof (cases \"d = 0\")\n    case False\n    from * have \"eventually (\\<lambda>n. f (-int n) = 0) at_top\"\n      by (simp add: cofinite_eq_sequentially)\n    hence \"eventually (\\<lambda>n. f (-int (n div d)) = 0) at_top\"\n      by (rule eventually_compose_filterlim[OF _ filterlim_at_top_div_const_nat]) (use False in auto)\n    hence \"eventually (\\<lambda>n. (if d > 0 \\<and> int d dvd -int n then f (-int n div int d) else 0) = 0) at_top\"\n      by eventually_elim (auto simp: zdiv_int dvd_neg_div)\n    thus ?thesis\n      by (simp add: cofinite_eq_sequentially)\n  qed auto\nqed\n\nlemma fls_nth_compose_power:\n  assumes \"d > 0\"\n  shows   \"fls_nth (fls_compose_power f d) n = (if int d dvd n then fls_nth f (n div int d) else 0)\"\n  using assms by transfer auto\n     \n\nlemma fls_compose_power_0_left [simp]: \"fls_compose_power 0 d = 0\"\n  by transfer auto\n\nlemma fls_compose_power_1_left [simp]: \"d > 0 \\<Longrightarrow> fls_compose_power 1 d = 1\"\n  by transfer (auto simp: fun_eq_iff)\n\nlemma fls_compose_power_const_left [simp]:\n  \"d > 0 \\<Longrightarrow> fls_compose_power (fls_const c) d = fls_const c\"\n  by transfer (auto simp: fun_eq_iff)\n\nlemma fls_compose_power_shift [simp]:\n  \"d > 0 \\<Longrightarrow> fls_compose_power (fls_shift n f) d = fls_shift (d * n) (fls_compose_power f d)\"\n  by transfer (auto simp: fun_eq_iff add_ac mult_ac)\n\nlemma fls_compose_power_X_intpow [simp]:\n  \"d > 0 \\<Longrightarrow> fls_compose_power (fls_X_intpow n) d = fls_X_intpow (int d * n)\"\n  by simp\n\nlemma fls_compose_power_X [simp]:\n  \"d > 0 \\<Longrightarrow> fls_compose_power fls_X d = fls_X_intpow (int d)\"\n  by transfer (auto simp: fun_eq_iff)\n\nlemma fls_compose_power_X_inv [simp]:\n  \"d > 0 \\<Longrightarrow> fls_compose_power fls_X_inv d = fls_X_intpow (-int d)\"\n  by (simp add: fls_X_inv_conv_shift_1)\n\nlemma fls_compose_power_0_right [simp]: \"fls_compose_power f 0 = 0\"\n  by transfer auto\n\nlemma fls_compose_power_add [simp]:\n  \"fls_compose_power (f + g) d = fls_compose_power f d + fls_compose_power g d\"\n  by transfer auto\n\nlemma fls_compose_power_diff [simp]:\n  \"fls_compose_power (f - g) d = fls_compose_power f d - fls_compose_power g d\"\n  by transfer auto\n\nlemma fls_compose_power_uminus [simp]:\n  \"fls_compose_power (-f) d = -fls_compose_power f d\"\n  by transfer auto\n\nlemma fps_nth_compose_X_power:\n  \"fps_nth (f oo (fps_X ^ d)) n = (if d dvd n then fps_nth f (n div d) else 0)\"\nproof -\n  have \"fps_nth (f oo (fps_X ^ d)) n = (\\<Sum>i = 0..n. f $ i * (fps_X ^ (d * i)) $ n)\"\n    unfolding fps_compose_def by (simp add: power_mult)\n  also have \"\\<dots> = (\\<Sum>i\\<in>(if d dvd n then {n div d} else {}). f $ i * (fps_X ^ (d * i)) $ n)\"\n    by (intro sum.mono_neutral_right) auto\n  also have \"\\<dots> = (if d dvd n then fps_nth f (n div d) else 0)\"\n    by auto\n  finally show ?thesis .\nqed\n\nlemma fls_compose_power_fps_to_fls:\n  assumes \"d > 0\"\n  shows   \"fls_compose_power (fps_to_fls f) d = fps_to_fls (fps_compose f (fps_X ^ d))\"\n  using assms\n  by (intro fls_eqI) (auto simp: fls_nth_compose_power fps_nth_compose_X_power\n                                 pos_imp_zdiv_neg_iff div_neg_pos_less0 nat_div_distrib\n                           simp flip: int_dvd_int_iff)\n\nlemma fls_compose_power_mult [simp]:\n  \"fls_compose_power (f * g :: 'a :: idom fls) d = fls_compose_power f d * fls_compose_power g d\"\nproof (cases \"d > 0\")\n  case True\n  define n where \"n = nat (max 0 (max (- fls_subdegree f) (- fls_subdegree g)))\"\n  have n_ge: \"-fls_subdegree f \\<le> int n\" \"-fls_subdegree g \\<le> int n\"\n    unfolding n_def by auto\n  obtain f' where f': \"f = fls_shift n (fps_to_fls f')\"\n    using fls_as_fps[OF n_ge(1)] by (auto simp: n_def)\n  obtain g' where g': \"g = fls_shift n (fps_to_fls g')\"\n    using fls_as_fps[OF n_ge(2)] by (auto simp: n_def)\n  show ?thesis using \\<open>d > 0\\<close>\n    by (simp add: f' g' fls_shifted_times_simps mult_ac fls_compose_power_fps_to_fls\n                  fps_compose_mult_distrib flip: fls_times_fps_to_fls)\nqed auto\n\nlemma fls_compose_power_power [simp]:\n  assumes \"d > 0 \\<or> n > 0\"\n  shows   \"fls_compose_power (f ^ n :: 'a :: idom fls) d = fls_compose_power f d ^ n\"\nproof (cases \"d > 0\")\n  case True\n  thus ?thesis by (induction n) auto\nqed (use assms in auto)\n\nlemma fls_nth_compose_power' [simp]:\n  \"d = 0 \\<or> \\<not>d dvd n \\<Longrightarrow> fls_nth (fls_compose_power f d) n = 0\"\n  \"d dvd n \\<Longrightarrow> d > 0 \\<Longrightarrow> fls_nth (fls_compose_power f d) n = fls_nth f (n div d)\"\n  by (transfer; force; fail)+\n\nsubsection \\<open>Formal differentiation and integration\\<close>\n\nsubsubsection \\<open>Derivative definition and basic properties\\<close>\n\ndefinition \"fls_deriv f = Abs_fls (\\<lambda>n. of_int (n+1) * f$$(n+1))\"\n\nlemma fls_deriv_nth[simp]: \"fls_deriv f $$ n = of_int (n+1) * f$$(n+1)\"\nproof-\n  obtain N where \"\\<forall>n<N. f$$n = 0\" by (elim fls_nth_vanishes_belowE)\n  hence \"\\<forall>n<N-1. of_int (n+1) * f$$(n+1) = 0\" by auto\n  thus ?thesis using nth_Abs_fls_lower_bound unfolding fls_deriv_def by simp\nqed\n\nlemma fls_deriv_residue: \"fls_deriv f $$ -1 = 0\"\n  by simp\n\nlemma fls_deriv_const[simp]: \"fls_deriv (fls_const x) = 0\"\nproof (intro fls_eqI)\n  fix n show \"fls_deriv (fls_const x) $$ n = 0$$n\"\n    by (cases \"n+1=0\") auto\nqed\n\nlemma fls_deriv_of_nat[simp]: \"fls_deriv (of_nat n) = 0\"\n  by (simp add: fls_of_nat)\n\nlemma fls_deriv_of_int[simp]: \"fls_deriv (of_int i) = 0\"\n  by (simp add: fls_of_int)\n\nlemma fls_deriv_zero[simp]: \"fls_deriv 0 = 0\"\n  using fls_deriv_const[of 0] by simp\n\nlemma fls_deriv_one[simp]: \"fls_deriv 1 = 0\"\n  using fls_deriv_const[of 1] by simp\n\nlemma fls_deriv_subdegree':\n  assumes \"of_int (fls_subdegree f) * f $$ fls_subdegree f \\<noteq> 0\"\n  shows   \"fls_subdegree (fls_deriv f) = fls_subdegree f - 1\"\n  by      (auto intro: fls_subdegree_eqI simp: assms)\n\nlemma fls_deriv_subdegree0:\n  assumes \"fls_subdegree f = 0\"\n  shows   \"fls_subdegree (fls_deriv f) \\<ge> 0\"\nproof (cases \"fls_deriv f = 0\")\n  case False\n  show ?thesis\n  proof (intro fls_subdegree_geI, rule False)\n    fix k :: int assume \"k < 0\"\n    with assms show \"fls_deriv f $$ k = 0\" by (cases \"k=-1\") auto\n  qed\nqed simp\n\nlemma fls_subdegree_deriv':\n  fixes   f :: \"'a::ring_1_no_zero_divisors fls\"\n  assumes \"(of_int (fls_subdegree f) :: 'a) \\<noteq> 0\"\n  shows   \"fls_subdegree (fls_deriv f) = fls_subdegree f - 1\"\n  using   assms nth_fls_subdegree_zero_iff[of f]\n  by      (auto intro: fls_deriv_subdegree')\n\nlemma fls_subdegree_deriv:\n  fixes   f :: \"'a::{ring_1_no_zero_divisors,ring_char_0} fls\"\n  assumes \"fls_subdegree f \\<noteq> 0\"\n  shows   \"fls_subdegree (fls_deriv f) = fls_subdegree f - 1\"\n  by      (auto intro: fls_subdegree_deriv' simp: assms)\n\ntext \\<open>\n  Shifting is like multiplying by a power of the implied variable, and so satisfies a product-like\n  rule.\n\\<close>\n\nlemma fls_deriv_shift:\n  \"fls_deriv (fls_shift n f) = of_int (-n) * fls_shift (n+1) f + fls_shift n (fls_deriv f)\"\n  by (intro fls_eqI) (simp flip: fls_shift_fls_shift add: algebra_simps)\n\nlemma fls_deriv_X [simp]: \"fls_deriv fls_X = 1\"\n  by (intro fls_eqI) simp\n\nlemma fls_deriv_X_inv [simp]: \"fls_deriv fls_X_inv = - (fls_X_inv\\<^sup>2)\"\nproof-\n  have \"fls_deriv fls_X_inv = - (fls_shift 2 1)\"\n    by (simp add: fls_X_inv_conv_shift_1 fls_deriv_shift)\n  thus ?thesis by (simp add: fls_X_inv_power_conv_shift_1)\nqed\n\nlemma fls_deriv_delta:\n  \"fls_deriv (Abs_fls (\\<lambda>n. if n=m then c else 0)) =\n    Abs_fls (\\<lambda>n. if n=m-1 then of_int m * c else 0)\"\nproof-\n  have\n    \"fls_deriv (Abs_fls (\\<lambda>n. if n=m then c else 0)) = fls_shift (1-m) (fls_const (of_int m * c))\"\n    using fls_deriv_shift[of \"-m\" \"fls_const c\"]\n    by    (simp\n            add: fls_shift_const fls_of_int fls_shifted_times_simps(1)[symmetric]\n            fls_const_mult_const[symmetric]\n            del: fls_const_mult_const\n          )\n  thus ?thesis by (simp add: fls_shift_const)\nqed\n\nlemma fls_deriv_base_factor:\n  \"fls_deriv (fls_base_factor f) =\n    of_int (-fls_subdegree f) * fls_shift (fls_subdegree f + 1) f +\n    fls_shift (fls_subdegree f) (fls_deriv f)\"\n  by (simp add: fls_deriv_shift)\n\nlemma fls_regpart_deriv: \"fls_regpart (fls_deriv f) = fps_deriv (fls_regpart f)\"\nproof (intro fps_ext)\n  fix n\n  have  1: \"(of_nat n :: 'a) + 1 = of_nat (n+1)\"\n  and   2: \"int n + 1 = int (n + 1)\"\n    by  auto\n  show \"fls_regpart (fls_deriv f) $ n = fps_deriv (fls_regpart f) $ n\" by (simp add: 1 2)\nqed\n\nlemma fls_prpart_deriv:\n  fixes f :: \"'a :: {comm_ring_1,ring_no_zero_divisors} fls\"\n  \\<comment> \\<open>Commutivity and no zero divisors are required by the definition of @{const pderiv}.\\<close>\n  shows \"fls_prpart (fls_deriv f) = - pCons 0 (pCons 0 (pderiv (fls_prpart f)))\"\nproof (intro poly_eqI)\n  fix n\n  show\n    \"coeff (fls_prpart (fls_deriv f)) n =\n      coeff (- pCons 0 (pCons 0 (pderiv (fls_prpart f)))) n\"\n  proof (cases n)\n    case (Suc m)\n    hence n: \"n = Suc m\" by fast\n    show ?thesis\n    proof (cases m)\n      case (Suc k)\n      with n have\n        \"coeff (- pCons 0 (pCons 0 (pderiv (fls_prpart f)))) n =\n          - coeff (pderiv (fls_prpart f)) k\"\n        by (simp flip: coeff_minus)\n      with Suc n show ?thesis by (simp add: coeff_pderiv algebra_simps)\n    qed (simp add: n)\n  qed simp\nqed\n\nlemma pderiv_fls_prpart:\n  \"pderiv (fls_prpart f) = - poly_shift 2 (fls_prpart (fls_deriv f))\"\n  by (intro poly_eqI) (simp add: coeff_pderiv coeff_poly_shift algebra_simps)\n\nlemma fls_deriv_fps_to_fls: \"fls_deriv (fps_to_fls f) = fps_to_fls (fps_deriv f)\"\nproof (intro fls_eqI)\n  fix n\n  show \"fls_deriv (fps_to_fls f) $$ n  = fps_to_fls (fps_deriv f) $$ n\"\n  proof (cases \"n\\<ge>0\")\n    case True\n    from True have 1: \"nat (n + 1) = nat n + 1\" by simp\n    from True have 2: \"(of_int (n + 1) :: 'a) = of_nat (nat (n+1))\" by simp\n    from True show ?thesis using arg_cong[OF 2, of \"\\<lambda>x. x * f $ (nat n+1)\"] by (simp add: 1)\n  next\n    case False thus ?thesis by (cases \"n=-1\") auto\n  qed\nqed\n\n\nsubsubsection \\<open>Algebra rules of the derivative\\<close>\n\nlemma fls_deriv_add [simp]: \"fls_deriv (f+g) = fls_deriv f + fls_deriv g\"\n  by (auto intro: fls_eqI simp: algebra_simps)\n\nlemma fls_deriv_sub [simp]: \"fls_deriv (f-g) = fls_deriv f - fls_deriv g\"\n  by (auto intro: fls_eqI simp: algebra_simps)\n\nlemma fls_deriv_neg [simp]: \"fls_deriv (-f) = - fls_deriv f\"\n  using fls_deriv_sub[of 0 f] by simp\n\nlemma fls_deriv_mult [simp]:\n  \"fls_deriv (f*g) = f * fls_deriv g + fls_deriv f * g\"\nproof-\n  define df dg :: int\n    where \"df \\<equiv> fls_subdegree f\"\n    and   \"dg \\<equiv> fls_subdegree g\"\n  define uf ug :: \"'a fls\"\n    where \"uf \\<equiv> fls_base_factor f\"\n    and   \"ug \\<equiv> fls_base_factor g\"\n  have\n    \"f * fls_deriv g =\n      of_int dg * fls_shift (1 - dg) (f * ug) + fls_shift (-dg) (f * fls_deriv ug)\"\n    \"fls_deriv f * g =\n      of_int df * fls_shift (1 - df) (uf * g) + fls_shift (-df) (fls_deriv uf * g)\"\n    using fls_deriv_shift[of \"-df\" uf] fls_deriv_shift[of \"-dg\" ug]\n          mult_of_int_commute[of dg f]\n          mult.assoc[of \"of_int dg\" f]\n          fls_shifted_times_simps(1)[of f \"1 - dg\" ug]\n          fls_shifted_times_simps(1)[of f \"-dg\" \"fls_deriv ug\"]\n          fls_shifted_times_simps(2)[of \"1 - df\" uf g]\n          fls_shifted_times_simps(2)[of \"-df\" \"fls_deriv uf\" g]\n    by (auto simp add: algebra_simps df_def dg_def uf_def ug_def)\n  moreover have\n    \"fls_deriv (f*g) =\n      ( of_int dg * fls_shift (1 - dg) (f * ug) + fls_shift (-dg) (f * fls_deriv ug) ) +\n      ( of_int df * fls_shift (1 - df) (uf * g) + fls_shift (-df) (fls_deriv uf * g) )\n    \"\n    using fls_deriv_shift[of\n            \"- (df + dg)\" \"fps_to_fls (fls_base_factor_to_fps f * fls_base_factor_to_fps g)\"\n          ]\n          fls_deriv_fps_to_fls[of \"fls_base_factor_to_fps f * fls_base_factor_to_fps g\"]\n          fps_deriv_mult[of \"fls_base_factor_to_fps f\" \"fls_base_factor_to_fps g\"]\n          distrib_right[of\n            \"of_int df\" \"of_int dg\"\n            \"fls_shift (1 - (df + dg)) (\n              fps_to_fls (fls_base_factor_to_fps f * fls_base_factor_to_fps g)\n            )\"\n          ]\n          fls_times_conv_fps_times[of uf ug]\n          fls_base_factor_subdegree[of f] fls_base_factor_subdegree[of g]\n          fls_regpart_deriv[of ug]\n          fls_times_conv_fps_times[of uf \"fls_deriv ug\"]\n          fls_deriv_subdegree0[of ug]\n          fls_regpart_deriv[of uf]\n          fls_times_conv_fps_times[of \"fls_deriv uf\" ug]\n          fls_deriv_subdegree0[of uf]\n          fls_shifted_times_simps(1)[of uf \"-dg\" ug]\n          fls_shifted_times_simps(1)[of \"fls_deriv uf\" \"-dg\" ug]\n          fls_shifted_times_simps(2)[of \"-df\" uf ug]\n          fls_shifted_times_simps(2)[of \"-df\" uf \"fls_deriv ug\"]\n    by (simp add: fls_times_def algebra_simps df_def dg_def uf_def ug_def)\n  ultimately show ?thesis by simp\nqed\n\nlemma fls_deriv_mult_const_left:\n  \"fls_deriv (fls_const c * f) = fls_const c * fls_deriv f\"\n  by simp\n\nlemma fls_deriv_linear:\n  \"fls_deriv (fls_const a * f + fls_const b * g) =\n    fls_const a * fls_deriv f + fls_const b * fls_deriv g\"\n  by simp\n\nlemma fls_deriv_mult_const_right:\n  \"fls_deriv (f * fls_const c) = fls_deriv f * fls_const c\"\n  by simp\n\nlemma fls_deriv_linear2:\n  \"fls_deriv (f * fls_const a + g * fls_const b) =\n    fls_deriv f * fls_const a + fls_deriv g * fls_const b\"\n  by simp\n\nlemma fls_deriv_sum:\n  \"fls_deriv (sum f S) = sum (\\<lambda>i. fls_deriv (f i)) S\"\nproof (cases \"finite S\")\n  case True show ?thesis\n    by (induct rule: finite_induct [OF True]) simp_all\nqed simp\n\nlemma fls_deriv_power:\n  fixes f :: \"'a::comm_ring_1 fls\"\n  shows \"fls_deriv (f^n) = of_nat n * f^(n-1) * fls_deriv f\"\nproof (cases n)\n  case (Suc m)\n  have \"fls_deriv (f^Suc m) = of_nat (Suc m) * f^m * fls_deriv f\"\n    by (induct m) (simp_all add: algebra_simps)\n  with Suc show ?thesis by simp\nqed simp\n\nlemma fls_deriv_X_power:\n  \"fls_deriv (fls_X ^ n) = of_nat n * fls_X ^ (n-1)\"\nproof (cases n)\n  case (Suc m)\n  have \"fls_deriv (fls_X^Suc m) = of_nat (Suc m) * fls_X^m\"\n    by (induct m) (simp_all add: mult_of_nat_commute algebra_simps)\n  with Suc show ?thesis by simp\nqed simp\n\nlemma fls_deriv_X_inv_power:\n  \"fls_deriv (fls_X_inv ^ n) = - of_nat n * fls_X_inv ^ (Suc n)\"\nproof (cases n)\n  case (Suc m)\n  define iX :: \"'a fls\" where \"iX \\<equiv> fls_X_inv\"\n  have \"fls_deriv (iX ^ Suc m) = - of_nat (Suc m) * iX ^ (Suc (Suc m))\"\n  proof (induct m)\n    case (Suc m)\n    have \"- of_nat (Suc m + 1) * iX ^ Suc (Suc (Suc m)) =\n            iX * (-of_nat (Suc m) * iX ^ Suc (Suc m)) +\n                  - (iX ^ 2 * iX ^ Suc m)\"\n      using distrib_right[of \"-of_nat (Suc m)\" \"-(1::'a fls)\" \"fls_X_inv ^ Suc (Suc (Suc m))\"]\n      by (simp add: algebra_simps mult_of_nat_commute power2_eq_square Suc iX_def)\n    thus ?case using Suc by (simp add: iX_def)\n  qed (simp add: numeral_2_eq_2 iX_def)\n  with Suc show ?thesis by (simp add: iX_def)\nqed simp\n\nlemma fls_deriv_X_intpow:\n  \"fls_deriv (fls_X_intpow i) = of_int i * fls_X_intpow (i-1)\"\n  by (simp add: fls_deriv_shift)\n\nlemma fls_deriv_lr_inverse:\n  assumes \"x * f $$ fls_subdegree f = 1\" \"f $$ fls_subdegree f * y = 1\"\n  \\<comment> \\<open>These assumptions imply x equals y, but no need to assume that.\\<close>\n  shows   \"fls_deriv (fls_left_inverse f x) =\n            - fls_left_inverse f x * fls_deriv f * fls_left_inverse f x\"\n  and     \"fls_deriv (fls_right_inverse f y) =\n            - fls_right_inverse f y * fls_deriv f * fls_right_inverse f y\"\nproof-\n\n  define L where \"L \\<equiv> fls_left_inverse f x\"\n  hence \"fls_deriv (L * f) = 0\" using fls_left_inverse[OF assms(1)] by simp\n  with assms show \"fls_deriv L = - L * fls_deriv f * L\"\n    using fls_right_inverse'[OF assms]\n    by    (simp add: minus_unique mult.assoc L_def)\n\n  define R where \"R \\<equiv> fls_right_inverse f y\"\n  hence \"fls_deriv (f * R) = 0\" using fls_right_inverse[OF assms(2)] by simp\n  hence 1: \"f * fls_deriv R + fls_deriv f * R = 0\" by simp\n  have \"R * f * fls_deriv R = - R * fls_deriv f * R\"\n    using iffD2[OF eq_neg_iff_add_eq_0, OF 1] by (simp add: mult.assoc)\n  thus \"fls_deriv R = - R * fls_deriv f * R\"\n    using fls_left_inverse'[OF assms] by (simp add: R_def)\n\nqed\n\nlemma fls_deriv_lr_inverse_comm:\n  fixes   x y :: \"'a::comm_ring_1\"\n  assumes \"x * f $$ fls_subdegree f = 1\"\n  shows   \"fls_deriv (fls_left_inverse f x) = - fls_deriv f * (fls_left_inverse f x)\\<^sup>2\"\n  and     \"fls_deriv (fls_right_inverse f x) = - fls_deriv f * (fls_right_inverse f x)\\<^sup>2\"\n  using   assms fls_deriv_lr_inverse[of x f x]\n  by      (simp_all add: mult.commute power2_eq_square)\n\nlemma fls_inverse_deriv_divring:\n  fixes a :: \"'a::division_ring fls\"\n  shows \"fls_deriv (inverse a) = - inverse a * fls_deriv a * inverse a\"\nproof (cases \"a=0\")\n  case False thus ?thesis\n    using fls_deriv_lr_inverse(2)[of\n            \"inverse (a $$ fls_subdegree a)\" a \"inverse (a $$ fls_subdegree a)\"\n          ]\n    by    (auto simp add: fls_inverse_def')\nqed simp\n\nlemma fls_inverse_deriv:\n  fixes a :: \"'a::field fls\"\n  shows \"fls_deriv (inverse a) = - fls_deriv a * (inverse a)\\<^sup>2\"\n  by    (simp add: fls_inverse_deriv_divring power2_eq_square)\n\nlemma fls_inverse_deriv':\n  fixes a :: \"'a::field fls\"\n  shows \"fls_deriv (inverse a) = - fls_deriv a / a\\<^sup>2\"\n  using fls_inverse_deriv[of a]\n  by    (simp add: field_simps)\n\n\nsubsubsection \\<open>Equality of derivatives\\<close>\n\nlemma fls_deriv_eq_0_iff:\n  \"fls_deriv f = 0 \\<longleftrightarrow> f = fls_const (f$$0 :: 'a::{ring_1_no_zero_divisors,ring_char_0})\"\nproof\n  assume f: \"fls_deriv f = 0\"\n  show \"f = fls_const (f$$0)\"\n  proof (intro fls_eqI)\n    fix n\n    from f have \"of_int n * f$$ n = 0\" using fls_deriv_nth[of f \"n-1\"] by simp\n    thus \"f$$n = fls_const (f$$0) $$ n\" by (cases \"n=0\") auto\n  qed\nnext\n  show \"f = fls_const (f$$0) \\<Longrightarrow> fls_deriv f = 0\" using fls_deriv_const[of \"f$$0\"] by simp\nqed\n\nlemma fls_deriv_eq_iff:\n  fixes f g :: \"'a::{ring_1_no_zero_divisors,ring_char_0} fls\"\n  shows \"fls_deriv f = fls_deriv g \\<longleftrightarrow> (f = fls_const(f$$0 - g$$0) + g)\"\nproof -\n  have \"fls_deriv f = fls_deriv g \\<longleftrightarrow> fls_deriv (f - g) = 0\"\n    by simp\n  also have \"\\<dots> \\<longleftrightarrow> f - g = fls_const ((f - g) $$ 0)\"\n    unfolding fls_deriv_eq_0_iff ..\n  finally show ?thesis\n    by (simp add: field_simps)\nqed\n\nlemma fls_deriv_eq_iff_ex:\n  fixes f g :: \"'a::{ring_1_no_zero_divisors,ring_char_0} fls\"\n  shows \"(fls_deriv f = fls_deriv g) \\<longleftrightarrow> (\\<exists>c. f = fls_const c + g)\"\n  by    (auto simp: fls_deriv_eq_iff)\n\n\nsubsubsection \\<open>Residues\\<close>\n\ndefinition fls_residue_def[simp]: \"fls_residue f \\<equiv> f $$ -1\"\n\nlemma fls_residue_deriv: \"fls_residue (fls_deriv f) = 0\"\n  by simp\n\nlemma fls_residue_add: \"fls_residue (f+g) = fls_residue f + fls_residue g\"\n  by simp\n\nlemma fls_residue_times_deriv:\n  \"fls_residue (fls_deriv f * g) = - fls_residue (f * fls_deriv g)\"\n  using fls_residue_deriv[of \"f*g\"] minus_unique[of \"fls_residue (f * fls_deriv g)\"]\n  by    simp\n\nlemma fls_residue_power_series: \"fls_subdegree f \\<ge> 0 \\<Longrightarrow> fls_residue f = 0\"\n  by simp\n\nlemma fls_residue_fls_X_intpow:\n  \"fls_residue (fls_X_intpow i) = (if i=-1 then 1 else 0)\"\n  by simp\n\nlemma fls_residue_shift_nth:\n  fixes f :: \"'a::semiring_1 fls\"\n  shows \"f$$n = fls_residue (fls_X_intpow (-n-1) * f)\"\n  by    (simp add: fls_shifted_times_transfer)\n\nlemma fls_residue_fls_const_times:\n  fixes f :: \"'a::{comm_monoid_add, mult_zero} fls\"\n  shows \"fls_residue (fls_const c * f) = c * fls_residue f\"\n  and   \"fls_residue (f * fls_const c) = fls_residue f * c\"\n  by    simp_all\n\nlemma fls_residue_of_int_times:\n  fixes f :: \"'a::ring_1 fls\"\n  shows \"fls_residue (of_int i * f) = of_int i * fls_residue f\"\n  and   \"fls_residue (f * of_int i) = fls_residue f * of_int i\"\n  by    (simp_all add: fls_residue_fls_const_times fls_of_int)\n\nlemma fls_residue_deriv_times_lr_inverse_eq_subdegree:\n  fixes   f g :: \"'a::ring_1 fls\"\n  assumes \"y * (f $$ fls_subdegree f) = 1\" \"(f $$ fls_subdegree f) * y = 1\"\n  shows   \"fls_residue (fls_deriv f * fls_right_inverse f y)  = of_int (fls_subdegree f)\"\n  and     \"fls_residue (fls_deriv f * fls_left_inverse f y)   = of_int (fls_subdegree f)\"\n  and     \"fls_residue (fls_left_inverse f y * fls_deriv f)   = of_int (fls_subdegree f)\"\n  and     \"fls_residue (fls_right_inverse f y * fls_deriv f)  = of_int (fls_subdegree f)\"\nproof-\n  define df :: int where \"df \\<equiv> fls_subdegree f\"\n  define B X :: \"'a fls\"\n    where \"B \\<equiv> fls_base_factor f\"\n    and   \"X \\<equiv> (fls_X_intpow df :: 'a fls)\"\n  define D L R :: \"'a fls\"\n    where \"D \\<equiv> fls_deriv B\"\n    and   \"L \\<equiv> fls_left_inverse B y\"\n    and   \"R \\<equiv> fls_right_inverse B y\"\n  have intpow_diff: \"fls_X_intpow (df - 1) = X * fls_X_inv\"\n    using fls_X_intpow_diff_conv_times[of df 1] by (simp add: X_def fls_X_inv_conv_shift_1)\n \n\n  show \"fls_residue (fls_deriv f * fls_right_inverse f y) = of_int df\"\n  proof-\n    have subdegree_DR: \"fls_subdegree (D * R) \\<ge> 0\"\n      using fls_base_factor_subdegree[of f] fls_base_factor_subdegree[of \"fls_right_inverse f y\"]\n            assms(1) fls_right_inverse_base_factor[of y f] fls_mult_subdegree_ge_0[of D R]\n      by    (force simp: fls_deriv_subdegree0 D_def R_def B_def)\n    have decomp: \"f = X * B\"\n      unfolding X_def B_def df_def by (rule fls_base_factor_X_power_decompose(2)[of f])\n    hence \"fls_deriv f = X * D + of_int df * X * fls_X_inv * B\"\n      using intpow_diff fls_deriv_mult[of X B]\n      by    (simp add: fls_deriv_X_intpow X_def B_def D_def mult.assoc)\n    moreover from assms have \"fls_right_inverse (X * B) y = R * fls_right_inverse X 1\"\n      using fls_base_factor_base[of f] fls_lr_inverse_mult_ring1(2)[of 1 X]\n      by    (simp add: X_def B_def R_def)\n    ultimately have\n      \"fls_deriv f * fls_right_inverse f y =\n        (D + of_int df * fls_X_inv * B) * R * (X * fls_right_inverse X 1)\"\n      by (simp add: decomp algebra_simps X_def fls_X_intpow_times_comm)\n    also have \"\\<dots> = D * R + of_int df * fls_X_inv\"\n      using fls_right_inverse[of X 1]\n            assms fls_base_factor_base[of f] fls_right_inverse[of B y]\n      by    (simp add: X_def distrib_right mult.assoc B_def R_def)\n    finally show ?thesis using subdegree_DR by simp\n  qed\n\n  with assms show \"fls_residue (fls_deriv f * fls_left_inverse f y) = of_int df\"\n    using fls_left_inverse_eq_fls_right_inverse[of y f] by simp\n\n  show \"fls_residue (fls_left_inverse f y * fls_deriv f) = of_int df\"\n  proof-\n    have subdegree_LD: \"fls_subdegree (L * D) \\<ge> 0\"\n      using fls_base_factor_subdegree[of f] fls_base_factor_subdegree[of \"fls_left_inverse f y\"]\n            assms(1) fls_left_inverse_base_factor[of y f] fls_mult_subdegree_ge_0[of L D]\n      by    (force simp: fls_deriv_subdegree0 D_def L_def B_def)\n    have decomp: \"f = B * X\"\n      unfolding X_def B_def df_def by (rule fls_base_factor_X_power_decompose(1)[of f])\n    hence \"fls_deriv f = D * X + B * of_int df * X * fls_X_inv\"\n      using intpow_diff fls_deriv_mult[of B X]\n      by    (simp add: fls_deriv_X_intpow X_def D_def B_def mult.assoc)\n    moreover from assms have \"fls_left_inverse (B * X) y = fls_left_inverse X 1 * L\"\n      using fls_base_factor_base[of f] fls_lr_inverse_mult_ring1(1)[of _ _ 1 X]\n      by    (simp add: X_def B_def L_def)\n    ultimately have\n      \"fls_left_inverse f y * fls_deriv f =\n        fls_left_inverse X 1 * X * L * (D + B * (of_int df * fls_X_inv))\"\n      by (simp add: decomp algebra_simps X_def fls_X_intpow_times_comm)\n    also have \"\\<dots> = L * D + of_int df * fls_X_inv\"\n      using assms fls_left_inverse[of 1 X] fls_base_factor_base[of f] fls_left_inverse[of y B]\n       by   (simp add: X_def distrib_left mult.assoc[symmetric] L_def B_def)\n    finally show ?thesis using subdegree_LD by simp\n  qed\n\n  with assms show \"fls_residue (fls_right_inverse f y * fls_deriv f) = of_int df\"\n    using fls_left_inverse_eq_fls_right_inverse[of y f] by simp\n\nqed\n\nlemma fls_residue_deriv_times_inverse_eq_subdegree:\n  fixes f g :: \"'a::division_ring fls\"\n  shows \"fls_residue (fls_deriv f * inverse f) = of_int (fls_subdegree f)\"\n  and   \"fls_residue (inverse f * fls_deriv f) = of_int (fls_subdegree f)\"\nproof-\n  show \"fls_residue (fls_deriv f * inverse f) = of_int (fls_subdegree f)\"\n    using fls_residue_deriv_times_lr_inverse_eq_subdegree(1)[of _ f]\n    by    (cases \"f=0\") (auto simp: fls_inverse_def')\n  show \"fls_residue (inverse f * fls_deriv f) = of_int (fls_subdegree f)\"\n    using fls_residue_deriv_times_lr_inverse_eq_subdegree(4)[of _ f]\n    by    (cases \"f=0\") (auto simp: fls_inverse_def')\nqed\n\n\nsubsubsection \\<open>Integral definition and basic properties\\<close>\n\n\\<comment> \\<open>To incorporate a constant of integration, just add an fps_const.\\<close>\ndefinition fls_integral :: \"'a::{ring_1,inverse} fls \\<Rightarrow> 'a fls\"\n  where \"fls_integral a = Abs_fls (\\<lambda>n. if n=0 then 0 else inverse (of_int n) * a$$(n - 1))\"\n\nlemma fls_integral_nth [simp]:\n  \"fls_integral a $$ n = (if n=0 then 0 else inverse (of_int n) * a$$(n-1))\"\nproof-\n  define F where \"F \\<equiv> (\\<lambda>n. if n=0 then 0 else inverse (of_int n) * a$$(n - 1))\"\n  obtain N where \"\\<forall>n<N. a$$n = 0\" by (elim fls_nth_vanishes_belowE)\n  hence \"\\<forall>n<N. F n = 0\" by (auto simp add: F_def)\n  thus ?thesis using nth_Abs_fls_lower_bound[of N F] unfolding fls_integral_def F_def by simp\nqed\n\nlemma fls_integral_conv_fps_zeroth_integral:\n  assumes \"fls_subdegree a \\<ge> 0\"\n  shows   \"fls_integral a = fps_to_fls (fps_integral0 (fls_regpart a))\"\nproof (rule fls_eqI)\n  fix n\n  show \"fls_integral a $$ n = fps_to_fls (fps_integral0 (fls_regpart a)) $$ n\"\n  proof (cases \"n>0\")\n    case False with assms show ?thesis by simp\n  next\n    case True\n    hence \"int ((nat n) - 1) = n - 1\" by simp\n    with True show ?thesis by (simp add: fps_integral_def)\n  qed\nqed\n\nlemma fls_integral_zero [simp]: \"fls_integral 0 = 0\"\n  by (intro fls_eqI) simp\n\nlemma fls_integral_const':\n  fixes   x :: \"'a::{ring_1,inverse}\"\n  assumes \"inverse (1::'a) = 1\"\n  shows   \"fls_integral (fls_const x) = fls_const x * fls_X\"\n  by      (intro fls_eqI) (simp add: assms)\n\nlemma fls_integral_const:\n  fixes x :: \"'a::division_ring\"\n  shows \"fls_integral (fls_const x) = fls_const x * fls_X\"\n  by    (rule fls_integral_const'[OF inverse_1])\n\nlemma fls_integral_of_nat':\n  assumes \"inverse (1::'a::{ring_1,inverse}) = 1\"\n  shows   \"fls_integral (of_nat n :: 'a fls) = of_nat n * fls_X\"\n  by      (simp add: assms fls_integral_const' fls_of_nat)\n\nlemma fls_integral_of_nat:\n  \"fls_integral (of_nat n :: 'a::division_ring fls) = of_nat n * fls_X\"\n  by (rule fls_integral_of_nat'[OF inverse_1])\n\nlemma fls_integral_of_int':\n  assumes \"inverse (1::'a::{ring_1,inverse}) = 1\"\n  shows   \"fls_integral (of_int i :: 'a fls) = of_int i * fls_X\"\n  by      (simp add: assms fls_integral_const' fls_of_int)\n\nlemma fls_integral_of_int:\n  \"fls_integral (of_int i :: 'a::division_ring fls) = of_int i * fls_X\"\n  by (rule fls_integral_of_int'[OF inverse_1])\n\nlemma fls_integral_one':\n  assumes \"inverse (1::'a::{ring_1,inverse}) = 1\"\n  shows   \"fls_integral (1::'a fls) = fls_X\"\n  using   fls_integral_const'[of 1]\n  by      (force simp: assms)\n\nlemma fls_integral_one: \"fls_integral (1::'a::division_ring fls) = fls_X\"\n  by (rule fls_integral_one'[OF inverse_1])\n\nlemma fls_subdegree_integral_ge:\n  \"fls_integral f \\<noteq> 0 \\<Longrightarrow> fls_subdegree (fls_integral f) \\<ge> fls_subdegree f + 1\"\n  by (intro fls_subdegree_geI) simp_all\n\nlemma fls_subdegree_integral:\n  fixes   f :: \"'a::{division_ring,ring_char_0} fls\"\n  assumes \"f \\<noteq> 0\" \"fls_subdegree f \\<noteq> -1\"\n  shows   \"fls_subdegree (fls_integral f) = fls_subdegree f + 1\"\n  using   assms of_int_0_eq_iff[of \"fls_subdegree f + 1\"] fls_subdegree_integral_ge\n  by      (intro fls_subdegree_eqI) simp_all\n\nlemma fls_integral_X [simp]:\n  \"fls_integral (fls_X::'a::{ring_1,inverse} fls) =\n    fls_const (inverse (of_int 2)) * fls_X\\<^sup>2\"\nproof (intro fls_eqI)\n  fix n\n  show \"fls_integral (fls_X::'a fls) $$ n = (fls_const (inverse (of_int 2)) * fls_X\\<^sup>2) $$ n\"\n    using arg_cong[OF fls_X_power_nth, of \"\\<lambda>x. inverse (of_int 2) * x\", of 2 n, symmetric]\n    by    (auto simp add: )\nqed\n\nlemma fls_integral_X_power:\n  \"fls_integral (fls_X ^ n ::'a :: {ring_1,inverse} fls) =\n    fls_const (inverse (of_nat (Suc n))) * fls_X ^ Suc n\"\nproof (intro fls_eqI)\n  fix k\n  have \"(fls_X :: 'a fls) ^ Suc n $$ k = (if k=Suc n then 1 else 0)\"\n    by (rule fls_X_power_nth)\n  thus \n    \"fls_integral ((fls_X::'a fls) ^ n) $$ k =\n      (fls_const (inverse (of_nat (Suc n))) * (fls_X::'a fls) ^ Suc n) $$ k\"\n    by simp\nqed\n\nlemma fls_integral_X_power_char0:\n  \"fls_integral (fls_X ^ n :: 'a :: {ring_char_0,inverse} fls) =\n    inverse (of_nat (Suc n)) * fls_X ^ Suc n\"\nproof -\n  have \"(of_nat (Suc n) :: 'a) \\<noteq> 0\" by (rule of_nat_neq_0)\n  hence \"fls_const (inverse (of_nat (Suc n) :: 'a)) = inverse (fls_const (of_nat (Suc n)))\"\n    by (simp add: fls_inverse_const)\n  moreover have\n    \"fls_integral ((fls_X::'a fls) ^ n) = fls_const (inverse (of_nat (Suc n))) * fls_X ^ Suc n\"\n    by (rule fls_integral_X_power)\n  ultimately show ?thesis by (simp add: fls_of_nat)\nqed\n\nlemma fls_integral_X_inv [simp]: \"fls_integral (fls_X_inv::'a::{ring_1,inverse} fls) = 0\"\n  by (intro fls_eqI) simp\n\nlemma fls_integral_X_inv_power:\n  assumes \"n \\<ge> 2\"\n  shows\n    \"fls_integral (fls_X_inv ^ n :: 'a :: {ring_1,inverse} fls) =\n      fls_const (inverse (of_int (1 - int n))) * fls_X_inv ^ (n-1)\"\nproof (rule fls_eqI)\n  fix k show\n    \"fls_integral (fls_X_inv ^ n :: 'a fls) $$ k=\n      (fls_const (inverse (of_int (1 - int n))) * fls_X_inv ^ (n-1)) $$ k\"\n  proof (cases \"k=0\")\n    case True with assms show ?thesis by simp\n  next\n    case False\n    from assms have \"int (n-1) = int n - 1\" by simp\n    hence\n      \"(fls_const (inverse (of_int (1 - int n))) * (fls_X_inv:: 'a fls) ^ (n-1)) $$ k =\n      (if k = 1 - int n then inverse (of_int k) else 0)\"\n      by (simp add: fls_X_inv_power_times_conv_shift(2))\n    with False show ?thesis by (simp add: algebra_simps)\n  qed\nqed\n\nlemma fls_integral_X_inv_power_char0:\n  assumes \"n \\<ge> 2\"\n  shows\n    \"fls_integral (fls_X_inv ^ n :: 'a :: {ring_char_0,inverse} fls) =\n      inverse (of_int (1 - int n)) * fls_X_inv ^ (n-1)\"\nproof-\n  from assms have \"(of_int (1 - int n) :: 'a) \\<noteq> 0\" by simp\n  hence\n    \"fls_const (inverse (of_int (1 - int n) :: 'a)) = inverse (fls_const (of_int (1 - int n)))\"\n    by (simp add: fls_inverse_const)\n  moreover have\n    \"fls_integral (fls_X_inv ^ n :: 'a fls) =\n      fls_const (inverse (of_int (1 - int n))) * fls_X_inv ^ (n-1)\"\n    using assms by (rule fls_integral_X_inv_power)\n  ultimately show ?thesis by (simp add: fls_of_int)\nqed\n\nlemma fls_integral_X_inv_power':\n  assumes \"n \\<ge> 1\"\n  shows\n    \"fls_integral (fls_X_inv ^ n :: 'a :: division_ring fls) =\n      - fls_const (inverse (of_nat (n-1))) * fls_X_inv ^ (n-1)\"\nproof (cases \"n = 1\")\n  case False\n  with assms have n: \"n \\<ge> 2\" by simp\n  hence\n    \"fls_integral (fls_X_inv ^ n :: 'a fls) =\n      fls_const (inverse (- of_nat (nat (int n - 1)))) * fls_X_inv ^ (n-1)\"\n    by (simp add: fls_integral_X_inv_power)\n  moreover from n have \"nat (int n - 1) = n - 1\" by simp\n  ultimately show ?thesis\n    using inverse_minus_eq[of \"of_nat (n-1) :: 'a\"] by simp\nqed simp\n\nlemma fls_integral_X_inv_power_char0':\n  assumes \"n \\<ge> 1\"\n  shows\n    \"fls_integral (fls_X_inv ^ n :: 'a :: {division_ring,ring_char_0} fls) =\n      - inverse (of_nat (n-1)) * fls_X_inv ^ (n-1)\"\nproof (cases \"n=1\")\n  case False with assms show ?thesis\n    by (simp add: fls_integral_X_inv_power' fls_inverse_const fls_of_nat)\nqed simp    \n\nlemma fls_integral_delta:\n  assumes \"m \\<noteq> -1\"\n  shows\n    \"fls_integral (Abs_fls (\\<lambda>n. if n=m then c else 0)) =\n      Abs_fls (\\<lambda>n. if n=m+1 then inverse (of_int (m+1)) * c else 0)\"\n  using   assms\n  by      (intro fls_eqI) auto\n\nlemma fls_regpart_integral:\n  \"fls_regpart (fls_integral f) = fps_integral0 (fls_regpart f)\"\nproof (rule fps_ext)\n  fix n\n  show \"fls_regpart (fls_integral f) $ n = fps_integral0 (fls_regpart f) $ n\"\n    by (cases n) (simp_all add: fps_integral_def)\nqed\n\nlemma fls_integral_fps_to_fls:\n  \"fls_integral (fps_to_fls f) = fps_to_fls (fps_integral0 f)\"\nproof (intro fls_eqI)\n  fix n :: int\n  show \"fls_integral (fps_to_fls f) $$ n = fps_to_fls (fps_integral0 f) $$ n\"\n  proof (cases \"n<1\")\n    case True thus ?thesis by simp\n  next\n    case False\n    hence \"nat (n-1) = nat n - 1\" by simp\n    with False show ?thesis by (cases \"nat n\") auto\n  qed\nqed\n\n\nsubsubsection \\<open>Algebra rules of the integral\\<close>\n\nlemma fls_integral_add [simp]: \"fls_integral (f+g) = fls_integral f + fls_integral g\"\n  by (intro fls_eqI) (simp add: algebra_simps)\n\nlemma fls_integral_sub [simp]: \"fls_integral (f-g) = fls_integral f - fls_integral g\"\n  by (intro fls_eqI) (simp add: algebra_simps)\n\nlemma fls_integral_neg [simp]: \"fls_integral (-f) = - fls_integral f\"\n  using fls_integral_sub[of 0 f] by simp\n\nlemma fls_integral_mult_const_left:\n  \"fls_integral (fls_const c * f) = fls_const c * fls_integral (f :: 'a::division_ring fls)\"\n  by (intro fls_eqI) (simp add: mult.assoc mult_inverse_of_int_commute)\n\nlemma fls_integral_mult_const_left_comm:\n  fixes f :: \"'a::{comm_ring_1,inverse} fls\"\n  shows \"fls_integral (fls_const c * f) = fls_const c * fls_integral f\"\n  by (intro fls_eqI) (simp add: mult.assoc mult.commute)\n\nlemma fls_integral_linear:\n  fixes f g :: \"'a::division_ring fls\"\n  shows\n    \"fls_integral (fls_const a * f + fls_const b * g) =\n      fls_const a * fls_integral f + fls_const b * fls_integral g\"\n  by    (simp add: fls_integral_mult_const_left)\n\nlemma fls_integral_linear_comm:\n  fixes f g :: \"'a::{comm_ring_1,inverse} fls\"\n  shows\n    \"fls_integral (fls_const a * f + fls_const b * g) =\n      fls_const a * fls_integral f + fls_const b * fls_integral g\"\n  by    (simp add: fls_integral_mult_const_left_comm)\n\nlemma fls_integral_mult_const_right:\n  \"fls_integral (f * fls_const c) = fls_integral f * fls_const c\"\n  by (intro fls_eqI) (simp add: mult.assoc)\n\nlemma fls_integral_linear2:\n    \"fls_integral (f * fls_const a + g * fls_const b) =\n      fls_integral f * fls_const a + fls_integral g * fls_const b\"\n  by    (simp add: fls_integral_mult_const_right)\n\nlemma fls_integral_sum:\n  \"fls_integral (sum f S) = sum (\\<lambda>i. fls_integral (f i)) S\"\nproof (cases \"finite S\")\n  case True show ?thesis\n    by (induct rule: finite_induct [OF True]) simp_all\nqed simp\n\n\nsubsubsection \\<open>Derivatives of integrals and vice versa\\<close>\n\nlemma fls_integral_fls_deriv:\n  fixes a :: \"'a::{division_ring,ring_char_0} fls\"\n  shows \"fls_integral (fls_deriv a) + fls_const (a$$0) = a\"\n  by    (intro fls_eqI) (simp add: mult.assoc[symmetric])\n\nlemma fls_deriv_fls_integral:\n  fixes   a :: \"'a::{division_ring,ring_char_0} fls\"\n  assumes \"fls_residue a = 0\"\n  shows   \"fls_deriv (fls_integral a) = a\"\nproof (intro fls_eqI)\n  fix n :: int\n  show \"fls_deriv (fls_integral a) $$ n = a $$ n\"\n  proof (cases \"n=-1\")\n    case True with assms show ?thesis by simp\n  next\n    case False\n    hence \"(of_int (n+1) :: 'a) \\<noteq> 0\" using of_int_eq_0_iff[of \"n+1\"] by simp\n    hence \"(of_int (n+1) :: 'a) * inverse (of_int (n+1) :: 'a) = (1::'a)\"\n      using of_int_eq_0_iff[of \"n+1\"] by simp\n    moreover have\n      \"fls_deriv (fls_integral a) $$ n =\n        (if n=-1 then 0 else of_int (n+1) * inverse (of_int (n+1)) * a$$n)\"\n      by (simp add: mult.assoc)\n    ultimately show ?thesis\n      by (simp add: False)\n  qed\nqed\n\ntext \\<open>Series with zero residue are precisely the derivatives.\\<close>\n\nlemma fls_residue_nonzero_ex_antiderivative:\n  fixes   f :: \"'a::{division_ring,ring_char_0} fls\"\n  assumes \"fls_residue f = 0\"\n  shows   \"\\<exists>F. fls_deriv F = f\"\n  using   assms fls_deriv_fls_integral\n  by      auto\n\nlemma fls_ex_antiderivative_residue_nonzero:\n  assumes \"\\<exists>F. fls_deriv F = f\"\n  shows   \"fls_residue f = 0\"\n  using   assms fls_residue_deriv\n  by      auto\n\nlemma fls_residue_nonzero_ex_anitderivative_iff:\n  fixes f :: \"'a::{division_ring,ring_char_0} fls\"\n  shows \"fls_residue f = 0 \\<longleftrightarrow> (\\<exists>F. fls_deriv F = f)\"\n  using fls_residue_nonzero_ex_antiderivative fls_ex_antiderivative_residue_nonzero\n  by    fast\n\n\nsubsection \\<open>Topology\\<close>\n\ninstantiation fls :: (group_add) metric_space\nbegin\n\ndefinition\n  dist_fls_def:\n    \"dist (a :: 'a fls) b =\n      (if a = b\n        then 0\n        else if fls_subdegree (a-b) \\<ge> 0\n          then inverse (2 ^ nat (fls_subdegree (a-b)))\n          else 2 ^ nat (-fls_subdegree (a-b))\n      )\"\n\nlemma dist_fls_ge0: \"dist (a :: 'a fls) b \\<ge> 0\"\n  by (simp add: dist_fls_def)\n\ndefinition uniformity_fls_def [code del]:\n  \"(uniformity :: ('a fls \\<times> 'a fls) filter) = (INF e \\<in> {0 <..}. principal {(x, y). dist x y < e})\"\n\ndefinition open_fls_def' [code del]:\n  \"open (U :: 'a fls set) \\<longleftrightarrow> (\\<forall>x\\<in>U. eventually (\\<lambda>(x', y). x' = x \\<longrightarrow> y \\<in> U) uniformity)\"\n\nlemma dist_fls_sym: \"dist (a :: 'a fls) b = dist b a\"\n  by  (cases \"a\\<noteq>b\", cases \"fls_subdegree (a-b) \\<ge> 0\")\n      (simp_all add: fls_subdegree_minus_sym dist_fls_def)\n\ncontext\nbegin\n\nprivate lemma instance_helper:\n  fixes   a b c :: \"'a fls\"\n  assumes neq: \"a\\<noteq>b\" \"a\\<noteq>c\"\n  and     dist_ineq: \"dist a b > dist a c\"\n  shows   \"fls_subdegree (a - b) < fls_subdegree (a - c)\"\nproof (\n  cases \"fls_subdegree (a-b) \\<ge> 0\" \"fls_subdegree (a-c) \\<ge> 0\"\n  rule: case_split[case_product case_split]\n)\n  case True_True with neq dist_ineq show ?thesis by (simp add: dist_fls_def)\nnext\n  case False_True with dist_ineq show ?thesis by (simp add: dist_fls_def)\nnext\n  case False_False with neq dist_ineq show ?thesis by (simp add: dist_fls_def)\nnext\n  case True_False\n  with neq\n    have \"(1::real) > 2 ^ (nat (fls_subdegree (a-b)) + nat (-fls_subdegree (a-c)))\"\n    and  \"nat (fls_subdegree (a-b)) + nat (-fls_subdegree (a-c)) =\n            nat (fls_subdegree (a-b) - fls_subdegree (a-c))\"\n    using dist_ineq\n    by    (simp_all add: dist_fls_def field_simps power_add)\n  hence \"\\<not> (1::real) < 2 ^ (nat (fls_subdegree (a-b) - fls_subdegree (a-c)))\" by simp\n  hence \"\\<not> (0 < nat (fls_subdegree (a - b) - fls_subdegree (a - c)))\" by auto\n  hence \"fls_subdegree (a - b) \\<le> fls_subdegree (a - c)\" by simp\n  with True_False show ?thesis by simp\nqed\n\ninstance\nproof\n  show th: \"dist a b = 0 \\<longleftrightarrow> a = b\" for a b :: \"'a fls\"\n    by (simp add: dist_fls_def split: if_split_asm)\n  then have th'[simp]: \"dist a a = 0\" for a :: \"'a fls\" by simp\n\n  fix a b c :: \"'a fls\"\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_fls_def)\n  next\n    case 2\n    then show ?thesis\n      by (cases \"c = a\") (simp_all add: th dist_fls_sym)\n  next\n    case neq: 3\n    have False if \"dist a b > dist a c + dist b c\"\n    proof -\n      from neq have \"dist a b > 0\" \"dist b c > 0\" \"dist a c > 0\" by (simp_all add: dist_fls_def)\n      with that have dist_ineq: \"dist a b > dist a c\" \"dist a b > dist b c\" by simp_all\n      have \"fls_subdegree (a - b) < fls_subdegree (a - c)\"\n      and  \"fls_subdegree (a - b) < fls_subdegree (b - c)\"\n        using instance_helper[of a b c] instance_helper[of b a c] neq dist_ineq\n        by    (simp_all add: dist_fls_sym fls_subdegree_minus_sym)\n      hence \"(a - c) $$ fls_subdegree (a - b) = 0\" and \"(b - c) $$ fls_subdegree (a - b) = 0\"\n        by  (simp_all only: fls_eq0_below_subdegree)\n      hence \"(a - b) $$ fls_subdegree (a - b) = 0\" by simp\n      moreover from neq have \"(a - b) $$ fls_subdegree (a - b) \\<noteq> 0\"\n        by (intro nth_fls_subdegree_nonzero) simp\n      ultimately show False by contradiction\n    qed\n    thus ?thesis by (auto simp: not_le[symmetric])\n  qed\nqed (rule open_fls_def' uniformity_fls_def)+\n\nend\nend\n\ndeclare uniformity_Abort[where 'a=\"'a :: group_add fls\", code]\n\nlemma open_fls_def:\n  \"open (S :: 'a::group_add fls set) = (\\<forall>a \\<in> S. \\<exists>r. r >0 \\<and> {y. dist y a < r} \\<subseteq> S)\"\n  unfolding open_dist subset_eq by simp\n\n\nsubsection \\<open>Notation bundle\\<close>\n\nno_notation fls_nth (infixl \"$$\" 75)\n\nbundle fls_notation\nbegin\nnotation fls_nth (infixl \"$$\" 75)\nend\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/Computational_Algebra/Formal_Laurent_Series.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8670357563664174, "lm_q2_score": 0.8519528057272544, "lm_q1q2_score": 0.7386735453022215}}
{"text": "section \\<open>The Pointwise Less-Than Relation Between Two Sets\\<close>\n\ntheory Nash_Extras\n  imports \"HOL-Library.Ramsey\" \"HOL-Library.Countable_Set\"\n\nbegin\n\ndefinition less_sets :: \"['a::order set, 'a::order set] \\<Rightarrow> bool\" (infixr \"\\<lless>\" 50)\n    where \"A \\<lless> B \\<equiv> \\<forall>x\\<in>A. \\<forall>y\\<in>B. x < y\"\n\nlemma less_setsD: \"\\<lbrakk>A \\<lless> B; a \\<in> A; b \\<in> B\\<rbrakk> \\<Longrightarrow> a < b\"\n  by (auto simp: less_sets_def)\n\nlemma less_sets_irrefl [simp]: \"A \\<lless> A \\<longleftrightarrow> A = {}\"\n  by (auto simp: less_sets_def)\n\nlemma less_sets_trans: \"\\<lbrakk>A \\<lless> B; B \\<lless> C; B \\<noteq> {}\\<rbrakk> \\<Longrightarrow> A \\<lless> C\"\n  unfolding less_sets_def using less_trans by blast\n\nlemma less_sets_weaken1: \"\\<lbrakk>A' \\<lless> B; A \\<subseteq> A'\\<rbrakk> \\<Longrightarrow> A \\<lless> B\"\n  by (auto simp: less_sets_def)\n\nlemma less_sets_weaken2: \"\\<lbrakk>A \\<lless> B'; B \\<subseteq> B'\\<rbrakk> \\<Longrightarrow> A \\<lless> B\"\n  by (auto simp: less_sets_def)\n\nlemma less_sets_imp_disjnt: \"A \\<lless> B \\<Longrightarrow> disjnt A B\"\n  by (auto simp: less_sets_def disjnt_def)\n\nlemma less_sets_UN1: \"less_sets (\\<Union>\\<A>) B \\<longleftrightarrow> (\\<forall>A\\<in>\\<A>. A \\<lless> B)\"\n  by (auto simp: less_sets_def)\n\nlemma less_sets_UN2: \"less_sets A (\\<Union> \\<B>) \\<longleftrightarrow> (\\<forall>B\\<in>\\<B>. A \\<lless> B)\"\n  by (auto simp: less_sets_def)\n\nlemma less_sets_Un1: \"less_sets (A \\<union> A') B \\<longleftrightarrow> A \\<lless> B \\<and> A' \\<lless> B\"\n  by (auto simp: less_sets_def)\n\nlemma less_sets_Un2: \"less_sets A (B \\<union> B') \\<longleftrightarrow> A \\<lless> B \\<and> A \\<lless> B'\"\n  by (auto simp: less_sets_def)\n\nlemma strict_sorted_imp_less_sets:\n  \"strict_sorted (as @ bs) \\<Longrightarrow> (list.set as) \\<lless> (list.set bs)\"\n  by (simp add: less_sets_def sorted_wrt_append)\n\nlemma Sup_nat_less_sets_singleton:\n  fixes n::nat\n  assumes \"Sup T < n\" \"finite T\"\n  shows \"less_sets T {n}\"\n  using assms Max_less_iff\n  by (auto simp: Sup_nat_def less_sets_def split: if_split_asm)\n  \nend\n\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/Nash_Williams/Nash_Extras.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357460591569, "lm_q2_score": 0.8519527982093666, "lm_q1q2_score": 0.7386735300026446}}
{"text": "section \\<open>Isabelle Formalization I\\<close>\n\ntheory Boo1 imports Main\nbegin\n\ntext \"Boolos's inference\"\n\nlocale boolax_1 = \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_1\nbegin\n\ntext \"Definitions\"\n\ndefinition (in boolax_1) induct :: \"'a set => bool\"\n  where \" induct X \\<equiv> e \\<in> X \\<and> (\\<forall>x. (x \\<in> X \\<longrightarrow> s(x) \\<in>  X))\"\n\ndefinition (in boolax_1) N :: \"'a \\<Rightarrow> bool\"\n  where \"N x \\<equiv> (\\<forall>X. (induct X \\<longrightarrow> x \\<in> X))\"\n\ndefinition (in boolax_1) E :: \"'a \\<Rightarrow> bool\"\n  where \"E x \\<equiv> (N x \\<and> D x)\"\n\ndefinition (in boolax_1) M :: \"'a \\<Rightarrow> bool\"\n  where \"M x \\<equiv> (\\<forall>y. (N y \\<longrightarrow>  E(F(x, y))))\"\n\ndefinition (in boolax_1) Q :: \"'a \\<Rightarrow> bool\"\n  where \"Q x \\<equiv> E(F(e, x))\"\n\ntext \"Lemmas\"\n\nlemma lem1: \"N e\" by (simp add: N_def induct_def)\n\n\n\nlemma lem3: \"N(s(s(s(s(e)))))\" by (simp add: lem1 lem2)\n\nlemma lem4: \"E e\" using A4 E_def lem1 by auto\n\nlemma lem5: \"E x \\<longrightarrow> E(s(x))\" by (simp add: A5 E_def lem2)\n\nlemma lem6: \"E(s(e))\" by (simp add: lem4 lem5)\n\nlemma lem7: \"Q e\" by (simp add: A1 Q_def lem6)\n\nlemma lem8: \"Q x \\<longrightarrow> Q(s(x))\" by (simp add: A2 Q_def lem5)\n\nlemma lem9: \"N x \\<longrightarrow> Q x\" by (metis N_def induct_def lem7 lem8 mem_Collect_eq)\n\nlemma lem10: \"M e\"  by (meson Q_def M_def lem9)\n\nlemma lem11: \"E (F(s(n), e))\" by (simp add: A1 lem6)\n\nlemma lem12: \"M x \\<and> E (F(s(x), y)) \\<longrightarrow> E (F(s(x), s(y)))\" by (simp add: A3 E_def M_def)\n\nlemma lem13: \"M x \\<longrightarrow> induct {y. E (F(s(x), y))}\" using A1 induct_def lem12 lem6 by auto\n\nlemma lem14: \"M x \\<longrightarrow> M(s(x))\" by (metis CollectD M_def N_def lem13)\n\nlemma lem15: \"N x \\<longrightarrow> M x\" by (metis N_def induct_def lem10 lem14 mem_Collect_eq)\n\nlemma lem16: \"N x \\<and> N y \\<longrightarrow> E(F(x,y))\" using M_def lem15 by blast\n\nlemma lem17: \"E(F(s(s(s(s(e)))), s(s(s(s(e))))))\" by (simp add: lem16 lem3)\n\nlemma lem18: \"D(F(s(s(s(s(e)))), s(s(s(s(e))))))\" using E_def lem17 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/Boolos_Curious_Inference/Boo1.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951625409308, "lm_q2_score": 0.7905303137346446, "lm_q1q2_score": 0.7386677009956162}}
{"text": "theory ex_2_10\n  imports Main\nbegin\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)\"\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 explode_size_ind: \"nodes(explode (Suc n) t) = Suc(2 * nodes(explode n t))\"\n  apply(induction n arbitrary:t)\n  by(auto)\nlemma inv_Suc:\"Suc y = k \\<Longrightarrow> y = k - 1\"\n  by(auto)\n\ntheorem explode_size[simp]: \"nodes(explode n t) = 2 ^ n * Suc(nodes t) - 1\"\n  apply(rule inv_Suc)\n  apply(induction n)\n  apply(simp)\n  by(auto simp add: explode_size_ind simp del:explode.simps)\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_10.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9196425399873763, "lm_q2_score": 0.8031737987125612, "lm_q1q2_score": 0.7386327922993295}}
{"text": "(*\n    $Id: ex.thy,v 1.4 2012/01/04 14:35:44 webertj Exp $\n    Author: Farhad Mehta\n*)\n\nheader {* Recursive Functions and Induction: Zip *}\n\n(*<*) theory ex imports Main begin (*>*)\n\ntext {*\nRead the chapter about total recursive functions in the ``Tutorial on\nIsabelle/HOL'' (@{text fun}, Chapter 3.5).\n*}\n\ntext {*\nIn this exercise you will define a function @{text Zip} that merges two lists\nby interleaving.\n Examples:\n@{text \"Zip [a1, a2, a3]  [b1, b2, b3] = [a1, b1, a2, b2, a3, b3]\"} \n and\n@{text \"Zip [a1] [b1, b2, b3] = [a1, b1, b2, b3]\"}.\n\nUse three different approaches to define @{text Zip}:\n\\begin{enumerate}\n\\item by primitive recursion on the first list,\n\\item by primitive recursion on the second list,\n\\item by total recursion (using @{text fun}).\n\\end{enumerate}\n*}\n\nconsts zip1 :: \"'a list \\<Rightarrow> 'a list \\<Rightarrow> 'a list\"\nconsts zip2 :: \"'a list \\<Rightarrow> 'a list \\<Rightarrow> 'a list\"\nconsts zipr :: \"'a list \\<Rightarrow> 'a list \\<Rightarrow> 'a list\"\n\n\ntext {*\nShow that all three versions of @{text Zip} are equivalent.\n*}\n\n\ntext {*\nShow that @{text zipr} distributes over @{text append}.\n*}\n\nlemma \"\\<lbrakk>length p = length u; length q = length v\\<rbrakk> \\<Longrightarrow> \n  zipr (p@q) (u@v) = zipr p u @ zipr q v\"\n(*<*) oops (*>*)\n\n\ntext {*\n{\\bf Note:} For @{text fun}, the order of your equations is relevant.\nIf equations overlap, they will be disambiguated before they are added\nto the logic.  You can have a look at these equations using @{text\n\"thm zipr.simps\"}.\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/zip/ex.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8031738057795402, "lm_q2_score": 0.9196425256718028, "lm_q1q2_score": 0.7386327873005304}}
{"text": "theory Chap2_2\n  imports Main\nbegin\n\ndatatype nat = Z | Suc nat\n\nfun add :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\" where\n\"add Z n = n\"\n| \"add (Suc m) n = Suc (add m n)\"\n\nlemma add_b: \"add n Z = n\"\n  apply (induction n)\n   apply (rule add.simps(1))\n  apply (subst add.simps(2))\n  apply (subst nat.inject)\n  apply assumption\n  done\n\nlemma add_i:\n  assumes f1: \"\\<And>m. add m n = add n m\"\n  shows \"add m (Suc n) = add (Suc n) m\"\n  apply (induction m)\n   apply (subst add.simps(1))\n   apply (rule add_b[symmetric])\n  apply (subst (1 2) add.simps(2))\n  apply (subst nat.inject)\n  apply (subst f1[symmetric])\n  apply (subst add.simps(2))\n  apply (subst f1)\n  apply (subst add.simps(2)[symmetric])\n  by assumption\n\nlemma add_comm: \"add m n = add n m\"\n  apply (induction n arbitrary: m)\n   apply (subst add.simps(1))\n   apply (rule add_b)\n  apply (erule add_i)\n  done\n\nvalue \"1 + (2::Nat.nat)\"\n\nvalue \"1 + (2::int)\"\n\nvalue \"1 - (2::Nat.nat)\"\n\nvalue \"1 - (2::int)\"\n\n\n\nfun double :: \"nat \\<Rightarrow> nat\" where\n\"double Z = Z\"\n| \"double (Suc n) = Suc (Suc (double n))\"\n\nlemma double_add: \"double n = add n n\"\n  apply (induction n)\n   apply simp+\n  apply (subst (2) add_comm)\n  by simp\n\nfun count :: \"'a list \\<Rightarrow> 'a \\<Rightarrow> Nat.nat\" where\n\"count [] y = 0\"\n| \"count (x#xs) y = (if x = y then 1 else 0) + count xs y\"\n\nlemma count_leq_len: \"count xs y \\<le> length xs\"\n  apply (induction xs)\n  by simp+\n\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 rev :: \"'a list \\<Rightarrow> 'a list\" where\n\"rev [] = []\"\n| \"rev (x#xs) = snoc (rev xs) x\"\n\nlemma rev_snoc: \"rev (snoc xs x) = x#(rev xs)\"\n  apply (induction xs)\n   apply simp\n  apply (subst snoc.simps)\n  apply (subst rev.simps)\n  apply (rule_tac a=\"rev (snoc xs x)\" and b=\"x#rev xs\" in forw_subst)\n   apply assumption\n  apply (subst snoc.simps)\n  apply (subst rev.simps)\n  by (rule refl)\n\nlemma rev_inv: \"rev (rev xs) = xs\"\n  apply (induction xs)\n   apply simp\n  by (simp add: rev_snoc)\n\nfun sum_upto :: \"Nat.nat \\<Rightarrow> Nat.nat\" where\n\"sum_upto 0 = 0\"\n| \"sum_upto (Nat.Suc n) = n + 1 + sum_upto n\"\n\nlemma \"sum_upto n = n * (n + 1) div 2\"\n  apply (induction n)\n   apply simp\n  apply (subst sum_upto.simps)\n  apply (rule_tac a=\"sum_upto n\" and b=\"n * (n+1) div 2\" in forw_subst)\n  by simp+\n\nend\n", "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_2.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392878563335, "lm_q2_score": 0.8354835411997897, "lm_q1q2_score": 0.7386002747779498}}
{"text": "section \\<open>Matrix limits\\<close>\n\ntheory Matrix_Limit\n  imports Complex_Matrix\nbegin\n\nsubsection \\<open>Definition of limit of matrices\\<close>\n\ndefinition limit_mat :: \"(nat \\<Rightarrow> complex mat) \\<Rightarrow> complex mat \\<Rightarrow> nat \\<Rightarrow> bool\" where\n  \"limit_mat X A m \\<longleftrightarrow> (\\<forall> n. X n \\<in> carrier_mat m m \\<and> A \\<in> carrier_mat m m \\<and>\n                       (\\<forall> i < m. \\<forall> j < m. (\\<lambda> n. (X n) $$ (i, j)) \\<longlonglongrightarrow> (A $$ (i, j))))\"\n\nlemma limit_mat_unique:\n  assumes limA: \"limit_mat X A m\" and limB: \"limit_mat X B m\"\n  shows \"A = B\"\nproof -\n  have dim: \"A \\<in> carrier_mat m m\" \"B \\<in> carrier_mat m m\" using limA limB limit_mat_def by auto\n  {\n    fix i j assume i: \"i < m\" and j: \"j < m\"\n    have \"(\\<lambda> n. (X n) $$ (i, j)) \\<longlonglongrightarrow> (A $$ (i, j))\" using limit_mat_def limA i j by auto\n    moreover have \"(\\<lambda> n. (X n) $$ (i, j)) \\<longlonglongrightarrow> (B $$ (i, j))\" using limit_mat_def limB i j by auto\n    ultimately have \"(A $$ (i, j)) = (B $$ (i, j))\" using LIMSEQ_unique by auto\n  }\n  then show \"A = B\" using mat_eq_iff dim by auto\nqed\n\nlemma limit_mat_const:\n  fixes A :: \"complex mat\"\n  assumes \"A \\<in> carrier_mat m m\"\n  shows \"limit_mat (\\<lambda>k. A) A m\"\n  unfolding limit_mat_def using assms by auto\n\nlemma limit_mat_scale:\n  fixes X :: \"nat \\<Rightarrow> complex mat\" and A :: \"complex mat\"\n  assumes limX: \"limit_mat X A m\"\n  shows \"limit_mat (\\<lambda>n. c \\<cdot>\\<^sub>m X n) (c \\<cdot>\\<^sub>m A) m\"\nproof -\n  have dimA: \"A \\<in> carrier_mat m m\" using limX limit_mat_def by auto\n  have dimX: \"\\<And>n. X n \\<in> carrier_mat m m\" using limX unfolding limit_mat_def by auto\n  have \"\\<And>i j. i < m \\<Longrightarrow> j < m \\<Longrightarrow> (\\<lambda>n. (c \\<cdot>\\<^sub>m X n) $$ (i, j)) \\<longlonglongrightarrow> (c \\<cdot>\\<^sub>m A) $$ (i, j)\"\n  proof -\n    fix i j assume i: \"i < m\" and j: \"j < m\"\n    have \"(\\<lambda>n. (X n) $$ (i, j)) \\<longlonglongrightarrow> A$$(i, j)\" using limX limit_mat_def i j by auto\n    moreover have \"(\\<lambda>n. c) \\<longlonglongrightarrow> c\" by auto\n    ultimately have \"(\\<lambda>n. c * (X n) $$ (i, j)) \\<longlonglongrightarrow> c * A$$(i, j)\"\n      using tendsto_mult[of \"\\<lambda>n. c\" c] limX limit_mat_def by auto\n    moreover have \"(c \\<cdot>\\<^sub>m X n) $$ (i, j) = c * (X n) $$ (i, j)\" for n\n      using index_smult_mat(1)[of i \"X n\" j c] i j dimX[of n] by auto\n    moreover have \"(c \\<cdot>\\<^sub>m A) $$ (i, j) = c * A $$ (i, j)\"\n      using index_smult_mat(1)[of i \"A\" j c] i j dimA by auto\n    ultimately show \"(\\<lambda>n. (c \\<cdot>\\<^sub>m X n) $$ (i, j)) \\<longlonglongrightarrow> (c \\<cdot>\\<^sub>m A) $$ (i, j)\" by auto\n  qed\n  then show ?thesis unfolding limit_mat_def using dimA dimX by auto\nqed\n\nlemma limit_mat_add:\n  fixes X :: \"nat \\<Rightarrow> complex mat\" and Y :: \"nat \\<Rightarrow> complex mat\" and A :: \"complex mat\"\n    and m :: nat and B :: \"complex mat\"\n  assumes limX: \"limit_mat X A m\" and limY: \"limit_mat Y B m\"\n  shows \"limit_mat (\\<lambda>k. X k + Y k) (A + B) m\"\nproof -\n  have dimA: \"A \\<in> carrier_mat m m\" using limX limit_mat_def by auto\n  have dimB: \"B \\<in> carrier_mat m m\" using limY limit_mat_def by auto\n  have dimX: \"\\<And>n. X n \\<in> carrier_mat m m\" using limX unfolding limit_mat_def by auto\n  have dimY: \"\\<And>n. Y n \\<in> carrier_mat m m\" using limY unfolding limit_mat_def by auto\n  then have dimXAB: \"\\<forall>n. X n + Y n \\<in> carrier_mat m m \\<and> A + B \\<in> carrier_mat m m\" using dimA dimB dimX dimY\n    by (simp)\n\n  have \"(\\<And>i j. i < m \\<Longrightarrow> j < m \\<Longrightarrow> (\\<lambda>n. (X n + Y n) $$ (i, j)) \\<longlonglongrightarrow> (A + B) $$ (i, j))\"\n  proof -\n    fix i j assume i: \"i < m\" and j: \"j < m\"\n    have \"(\\<lambda>n. (X n) $$ (i, j)) \\<longlonglongrightarrow> A$$(i, j)\" using limX limit_mat_def i j by auto\n    moreover have \"(\\<lambda>n. (Y n) $$ (i, j)) \\<longlonglongrightarrow> B$$(i, j)\" using limY limit_mat_def i j by auto\n    ultimately have \"(\\<lambda>n. (X n)$$(i, j) + (Y n) $$ (i, j)) \\<longlonglongrightarrow> (A$$(i, j) + B$$(i, j))\"\n      using tendsto_add[of \"\\<lambda>n. (X n) $$ (i, j)\" \"A $$ (i, j)\"] by auto\n    moreover have \"(X n + Y n) $$ (i, j) = (X n)$$(i, j) + (Y n) $$ (i, j)\" for n\n      using i j dimX dimY index_add_mat(1)[of i \"Y n\" j \"X n\"] by fastforce\n    moreover have \"(A + B) $$ (i, j) = A$$(i, j) + B$$(i, j)\"\n      using i j dimA dimB by fastforce\n    ultimately show \"(\\<lambda>n. (X n + Y n) $$ (i, j)) \\<longlonglongrightarrow> (A + B) $$ (i, j)\" by auto\n  qed\n  then show ?thesis\n    unfolding limit_mat_def using dimXAB by auto\nqed\n\nlemma limit_mat_minus:\n  fixes X :: \"nat \\<Rightarrow> complex mat\" and Y :: \"nat \\<Rightarrow> complex mat\" and A :: \"complex mat\"\n    and m :: nat and B :: \"complex mat\"\n  assumes limX: \"limit_mat X A m\" and limY: \"limit_mat Y B m\"\n  shows \"limit_mat (\\<lambda>k. X k - Y k) (A - B) m\"\nproof -\n  have dimA: \"A \\<in> carrier_mat m m\" using limX limit_mat_def by auto\n  have dimB: \"B \\<in> carrier_mat m m\" using limY limit_mat_def by auto\n  have dimX: \"\\<And>n. X n \\<in> carrier_mat m m\" using limX unfolding limit_mat_def by auto\n  have dimY: \"\\<And>n. Y n \\<in> carrier_mat m m\" using limY unfolding limit_mat_def by auto\n  have \"-1 \\<cdot>\\<^sub>m Y n = - Y n\" for n using dimY by auto\n  moreover have \"-1 \\<cdot>\\<^sub>m B = - B\" using dimB by auto\n  ultimately have \"limit_mat (\\<lambda>n. - Y n) (- B) m\" using limit_mat_scale[OF limY, of \"-1\"] by auto\n  then have \"limit_mat (\\<lambda>n. X n + (- Y n)) (A + (- B)) m\" using limit_mat_add limX by auto\n  moreover have \"X n + (- Y n) = X n - Y n\" for n using dimX dimY by auto\n  moreover have \"A + (- B) = A - B\" by auto\n  ultimately show ?thesis by auto\nqed\n\nlemma limit_mat_mult:\n  fixes X :: \"nat \\<Rightarrow> complex mat\" and Y :: \"nat \\<Rightarrow> complex mat\" and A :: \"complex mat\"\n    and m :: nat and B :: \"complex mat\"\n  assumes limX: \"limit_mat X A m\" and limY: \"limit_mat Y B m\"\n  shows \"limit_mat (\\<lambda>k. X k * Y k) (A * B) m\"\nproof -\n  have dimA: \"A \\<in> carrier_mat m m\" using limX limit_mat_def by auto\n  have dimB: \"B \\<in> carrier_mat m m\" using limY limit_mat_def by auto\n  have dimX: \"\\<And>n. X n \\<in> carrier_mat m m\" using limX unfolding limit_mat_def by auto\n  have dimY: \"\\<And>n. Y n \\<in> carrier_mat m m\" using limY unfolding limit_mat_def by auto\n  then have dimXAB: \"\\<forall>n. X n * Y n \\<in> carrier_mat m m \\<and> A * B \\<in> carrier_mat m m\" using dimA dimB dimX dimY\n    by fastforce\n\n  have \"(\\<And>i j. i < m \\<Longrightarrow> j < m \\<Longrightarrow> (\\<lambda>n. (X n * Y n) $$ (i, j)) \\<longlonglongrightarrow> (A * B) $$ (i, j))\"\n  proof -\n    fix i j assume i: \"i < m\" and j: \"j < m\"\n    have eqn: \"(X n * Y n) $$ (i, j) = (\\<Sum>k=0..<m. (X n)$$(i, k) * (Y n)$$(k, j))\" for n\n      using i j dimX[of n] dimY[of n] by (auto simp add: scalar_prod_def)\n    have eq: \"(A * B) $$ (i, j) = (\\<Sum>k=0..<m. A$$(i,k) * B$$(k,j))\"\n      using i j dimB dimA by (auto simp add: scalar_prod_def)\n    have \"(\\<lambda>n. (X n) $$ (i, k)) \\<longlonglongrightarrow> A$$(i, k)\" if \"k < m\" for k using limX limit_mat_def that i by auto\n    moreover have \"(\\<lambda>n. (Y n) $$ (k, j)) \\<longlonglongrightarrow> B$$(k, j)\" if \"k < m\" for k using limY limit_mat_def that j by auto\n    ultimately have \"(\\<lambda>n. (X n)$$(i, k) * (Y n)$$(k,j)) \\<longlonglongrightarrow> A$$(i, k) * B$$(k, j)\" if \"k < m\" for k\n      using tendsto_mult[of \"\\<lambda>n. (X n) $$ (i, k)\" \"A$$(i, k)\" _ \"\\<lambda>n. (Y n)$$(k, j)\" \"B$$(k, j)\"] that by auto\n    then have \"(\\<lambda>n. (\\<Sum>k=0..<m. (X n)$$(i,k) * (Y n)$$(k,j))) \\<longlonglongrightarrow> (\\<Sum>k=0..<m. A$$(i,k) * B$$(k,j))\"\n      using tendsto_sum[of \"{0..<m}\" \"\\<lambda>k n. (X n)$$(i,k) * (Y n)$$(k,j)\" \"\\<lambda>k. A$$(i, k) * B$$(k, j)\"] by auto\n    then show \"(\\<lambda>n. (X n * Y n) $$ (i, j)) \\<longlonglongrightarrow> (A * B) $$ (i, j)\" using eqn eq by auto\n  qed\n  then show ?thesis\n    unfolding limit_mat_def using dimXAB by fastforce\nqed\n\ntext \\<open>Adding matrix A to the sequence X\\<close>\ndefinition mat_add_seq ::  \"complex mat \\<Rightarrow> (nat \\<Rightarrow> complex mat) \\<Rightarrow> nat \\<Rightarrow> complex mat\" where\n  \"mat_add_seq A X = (\\<lambda>n. A + X n)\"\n\nlemma mat_add_limit:\n  fixes X :: \"nat \\<Rightarrow> complex mat\" and A :: \"complex mat\" and m :: nat and B :: \"complex mat\"\n  assumes dimB: \"B \\<in> carrier_mat m m\" and limX: \"limit_mat X A m\"\n  shows \"limit_mat (mat_add_seq B X) (B + A) m\"\n  unfolding mat_add_seq_def using limit_mat_add limit_mat_const[OF dimB] limX by auto\n\nlemma mat_minus_limit:\n  fixes X :: \"nat \\<Rightarrow> complex mat\" and A :: \"complex mat\" and m :: nat and B :: \"complex mat\"\n  assumes dimB: \"B \\<in> carrier_mat m m\" and limX: \"limit_mat X A m\"\n  shows \"limit_mat (\\<lambda>n. B - X n) (B - A) m\"\n  using limit_mat_minus limit_mat_const[OF dimB] limX by auto\n\ntext \\<open>Multiply matrix A by the sequence X\\<close>\ndefinition mat_mult_seq ::  \"complex mat \\<Rightarrow> (nat \\<Rightarrow> complex mat) \\<Rightarrow> nat \\<Rightarrow> complex mat\" where\n  \"mat_mult_seq A X = (\\<lambda>n. A * X n)\"\n\nlemma mat_mult_limit:\n  fixes X :: \"nat \\<Rightarrow> complex mat\" and A B :: \"complex mat\" and m :: nat\n  assumes dimB: \"B \\<in> carrier_mat m m\" and limX: \"limit_mat X A m\"\n  shows \"limit_mat (mat_mult_seq B X) (B * A) m\"\n  unfolding mat_mult_seq_def using limit_mat_mult limit_mat_const[OF dimB] limX by auto\n\nlemma mult_mat_limit:\n  fixes X :: \"nat \\<Rightarrow> complex mat\" and A B :: \"complex mat\" and m :: nat\n  assumes dimB: \"B \\<in> carrier_mat m m\" and limX: \"limit_mat X A m\"\n  shows \"limit_mat (\\<lambda>k. X k * B) (A * B) m\"\n  unfolding mat_mult_seq_def using limit_mat_mult limit_mat_const[OF dimB] limX by auto\n\nlemma quadratic_form_mat:\n  fixes A :: \"complex mat\" and v :: \"complex vec\" and m :: nat\n  assumes dimv: \"dim_vec v = m\" and dimA: \"A \\<in> carrier_mat m m\"\n  shows \"inner_prod v (A *\\<^sub>v v) = (\\<Sum>i=0..<m. (\\<Sum>j=0..<m. conjugate (v$i) * A$$(i, j) * v$j))\"\nproof -\n  have  \"inner_prod v (A *\\<^sub>v v) = (\\<Sum>i=0..<m. (\\<Sum>j=0..<m.\n                conjugate (v$i) * A$$(i, j) * v$j))\"\n  unfolding scalar_prod_def using dimv dimA\n    apply (simp add: scalar_prod_def sum_distrib_right)\n    apply (rule sum.cong, auto, rule sum.cong, auto)\n  done\n  then show ?thesis by auto\nqed\n\nlemma sum_subtractff:\n  fixes h g :: \"nat \\<Rightarrow> nat \\<Rightarrow>'a::ab_group_add\"\n  shows \"(\\<Sum>x\\<in>A. \\<Sum>y\\<in>B. h x y - g x y) = (\\<Sum>x\\<in>A. \\<Sum>y\\<in>B. h x y) - (\\<Sum>x\\<in>A. \\<Sum>y\\<in>B. g x y)\"\nproof -\n  have \"\\<forall> x \\<in> A. (\\<Sum>y\\<in>B. h x y - g x y) = (\\<Sum>y\\<in>B. h x y) - (\\<Sum>y\\<in>B. g x y)\"\n  proof -\n    {\n      fix x assume x: \"x \\<in> A\"\n      have \"(\\<Sum>y\\<in>B. h x y - g x y) = (\\<Sum>y\\<in>B. h x y) - (\\<Sum>y\\<in>B. g x y)\"\n        using sum_subtractf by auto\n     }\n    then show ?thesis  using sum_subtractf by blast\n  qed\n  then have \"(\\<Sum>x\\<in>A.\\<Sum>y\\<in>B. h x y - g x y) = (\\<Sum>x\\<in>A. ((\\<Sum>y\\<in>B. h x y) - (\\<Sum>y\\<in>B. g x y)))\" by auto\n  also have \"\\<dots> = (\\<Sum>x\\<in>A. \\<Sum>y\\<in>B. h x y) - (\\<Sum>x\\<in>A. \\<Sum>y\\<in>B. g x y)\"\n    by (simp add: sum_subtractf)\n  finally have \" (\\<Sum>x\\<in>A. \\<Sum>y\\<in>B. h x y - g x y) = (\\<Sum>x\\<in>A. sum (h x) B) - (\\<Sum>x\\<in>A. sum (g x) B)\" by auto\n  then show ?thesis by auto\nqed\n\nlemma sum_abs_complex:\n  fixes h  :: \"nat \\<Rightarrow> nat \\<Rightarrow> complex\"\n  shows \"cmod (\\<Sum>x\\<in>A.\\<Sum>y\\<in>B. h x y) \\<le> (\\<Sum>x\\<in>A. \\<Sum>y\\<in>B. cmod(h x y))\"\nproof -\n  have B: \"\\<forall> x \\<in> A. cmod( \\<Sum>y\\<in>B .h x y) \\<le> (\\<Sum>y\\<in>B. cmod(h x y))\" using sum_abs norm_sum by blast\n  have \"cmod (\\<Sum>x\\<in>A.\\<Sum>y\\<in>B. h x y) \\<le> (\\<Sum>x\\<in>A.  cmod( \\<Sum>y\\<in>B .h x y))\" using sum_abs norm_sum by blast\n  also have \"\\<dots> \\<le> (\\<Sum>x\\<in>A. \\<Sum>y\\<in>B. cmod(h x y))\" using sum_abs norm_sum B\n    by (simp add: sum_mono)\n  finally have \"cmod (\\<Sum>x\\<in>A. \\<Sum>y\\<in>B. h x y) \\<le> (\\<Sum>x\\<in>A. \\<Sum>y\\<in>B. cmod (h x y))\" by auto\n  then show ?thesis by auto\nqed\n\nlemma hermitian_mat_lim_is_hermitian:\n  fixes X :: \"nat \\<Rightarrow> complex mat\" and A :: \"complex mat\" and m :: nat\n  assumes limX: \"limit_mat X A m\" and herX: \"\\<forall> n. hermitian (X n)\"\n  shows \"hermitian A\"\nproof -\n  have  dimX: \"\\<forall>n. X n \\<in> carrier_mat m m\" using limX unfolding limit_mat_def by auto\n  have dimA : \"A \\<in> carrier_mat m m\" using limX unfolding limit_mat_def by auto\n\n  from herX have herXn: \"\\<forall> n. adjoint (X n) = (X n)\" unfolding hermitian_def by auto\n  from limX have limXn: \"\\<forall>i<m. \\<forall>j<m. (\\<lambda>n. X n $$ (i, j)) \\<longlonglongrightarrow> A $$ (i, j)\" unfolding limit_mat_def by auto\n  have \"\\<forall>i<m. \\<forall>j<m.(adjoint A)$$ (i, j) = A$$ (i, j)\"\n  proof -\n    {\n      fix i j assume i: \"i < m\" and j: \"j < m\"\n      have aij: \"(adjoint A)$$ (i, j) = conjugate (A $$ (j,i))\" using adjoint_eval i j dimA by blast\n      have ij: \"(\\<lambda>n. X n $$ (i, j)) \\<longlonglongrightarrow> A $$ (i, j)\" using limXn i j by auto\n      have ji: \"(\\<lambda>n. X n $$ (j, i)) \\<longlonglongrightarrow> A $$ (j, i)\" using limXn i j by auto\n      then have \"\\<forall>r>0. \\<exists>no. \\<forall>n\\<ge>no. dist (conjugate (X n $$ (j, i))) (conjugate (A $$ (j, i))) < r\"\n      proof -\n        {\n          fix r :: real assume r : \"r > 0\"\n          have \"\\<exists>no. \\<forall>n\\<ge>no. cmod (X n $$ (j, i) - A $$ (j, i)) < r\" using ji r unfolding  LIMSEQ_def dist_norm by auto\n          then obtain no where Xji: \"\\<forall>n\\<ge>no. cmod (X n $$ (j, i) - A $$ (j, i)) < r\" by auto\n          then have \"\\<forall>n\\<ge>no. cmod (conjugate (X n $$ (j, i) - A $$ (j, i))) < r\"\n            using complex_mod_cnj conjugate_complex_def by presburger\n          then have \"\\<forall>n\\<ge>no. dist (conjugate (X n $$ (j, i))) (conjugate (A $$ (j, i))) < r\" unfolding dist_norm by auto\n          then have \"\\<exists>no. \\<forall>n\\<ge>no. dist (conjugate (X n $$ (j, i))) (conjugate (A $$ (j, i))) < r\" by auto\n        }\n        then show ?thesis by auto\n      qed\n      then have conjX: \"(\\<lambda>n. conjugate (X n $$ (j, i))) \\<longlonglongrightarrow>  conjugate (A $$ (j, i))\" unfolding LIMSEQ_def by auto\n\n      from herXn have \"\\<forall> n. conjugate (X n $$ (j,i)) = X n$$ (i, j)\"  using adjoint_eval i j dimX\n        by (metis adjoint_dim_col carrier_matD(1))\n      then have \"(\\<lambda>n. X n $$ (i, j)) \\<longlonglongrightarrow>  conjugate (A $$ (j, i))\" using conjX by auto\n      then have \"conjugate (A $$ (j,i)) = A$$ (i, j)\" using ij by (simp add: LIMSEQ_unique)\n      then have \"(adjoint A)$$ (i, j) = A$$ (i, j)\" using adjoint_eval i j by (simp add:aij)\n    }\n    then show ?thesis by auto\n  qed\n  then have \"hermitian A\" using hermitian_def dimA\n    by (metis adjoint_dim carrier_matD(1) carrier_matD(2) eq_matI)\n  then show ?thesis by auto\nqed\n\nlemma quantifier_change_order_once:\n  fixes P :: \"nat \\<Rightarrow> nat \\<Rightarrow> bool\" and m :: nat\n  shows \"\\<forall>j<m. \\<exists>no. \\<forall>n\\<ge>no. P n j \\<Longrightarrow> \\<exists>no. \\<forall>j<m. \\<forall>n\\<ge>no. P n j\"\nproof (induct m)\n    case 0\n    then show ?case by auto\n  next\n    case (Suc m)\n    then show ?case\n    proof -\n      have mm: \"\\<exists>no. \\<forall>j<m. \\<forall>n\\<ge>no. P n j\" using Suc by auto\n      then obtain M where MM: \"\\<forall>j<m. \\<forall>n\\<ge>M. P n j\" by auto\n      have sucm: \"\\<exists>no. \\<forall>n\\<ge>no. P n m\" using Suc(2) by auto\n      then obtain N where NN: \"\\<forall>n\\<ge>N. P n m\" by auto\n      let ?N = \"max M N\"\n      from MM NN have \"\\<forall>j<Suc m. \\<forall>n\\<ge>?N. P n j\"\n        by (metis less_antisym max.boundedE)\n      then have \"\\<exists>no. \\<forall>j<Suc m. \\<forall>n\\<ge>no. P n j\" by blast\n      then show ?thesis by auto\n    qed\n  qed\n\nlemma quantifier_change_order_twice:\n  fixes P :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> bool\" and m n :: nat\n  shows \"\\<forall>i<m. \\<forall>j<n. \\<exists> no. \\<forall>n\\<ge>no. P n i j \\<Longrightarrow> \\<exists>no. \\<forall>i<m. \\<forall>j<n. \\<forall>n\\<ge>no. P n i j\"\nproof -\n  assume fact: \"\\<forall>i<m. \\<forall>j<n. \\<exists> no. \\<forall>n\\<ge>no. P n i j\"\n  have one: \"\\<forall>i<m. \\<exists>no.\\<forall>j<n. \\<forall>n\\<ge>no. P n i j\"\n    using fact quantifier_change_order_once by auto\n  have two: \"\\<forall>i<m. \\<exists>no.\\<forall>j<n. \\<forall>n\\<ge>no. P n i j \\<Longrightarrow> \\<exists>no. \\<forall>i<m. \\<forall>j<n. \\<forall>n\\<ge>no. P n i j\"\n  proof (induct m)\n    case 0\n    then show ?case by auto\n  next\n    case (Suc m)\n    then show ?case\n    proof -\n      obtain M where MM: \"\\<forall>i<m. \\<forall>j<n. \\<forall>n\\<ge>M. P n i j\" using Suc by auto\n      obtain N where NN: \"\\<forall>j<n. \\<forall>n\\<ge>N. P n m j\" using Suc(2) by blast\n      let ?N = \"max M N\"\n      from MM NN have \"\\<forall>i<Suc m. \\<forall>j<n. \\<forall>n\\<ge>?N. P n i j\"\n        by (metis less_antisym max.boundedE)\n      then have \"\\<exists>no. \\<forall>i<Suc m. \\<forall>j<n. \\<forall>n\\<ge>no. P n i j\" by blast\n      then show ?thesis by auto\n    qed\n  qed\n  with fact show ?thesis using one by auto\nqed\n\nlemma pos_mat_lim_is_pos:\n  fixes X :: \"nat \\<Rightarrow> complex mat\" and A :: \"complex mat\" and m :: nat\n  assumes limX: \"limit_mat X A m\" and posX: \"\\<forall>n. positive (X n)\"\n  shows \"positive A\"\nproof (rule ccontr)\n  have  dimX : \"\\<forall>n. X n \\<in> carrier_mat m m\" using limX unfolding limit_mat_def by auto\n  have dimA : \"A \\<in> carrier_mat m m\" using limX unfolding limit_mat_def by auto\n  have herX : \"\\<forall> n. hermitian (X n)\" using posX positive_is_hermitian by auto\n  then have herA : \"hermitian A\"  using hermitian_mat_lim_is_hermitian limX by auto\n  then have herprod: \"\\<forall> v. dim_vec v = dim_col A \\<longrightarrow> inner_prod v (A *\\<^sub>v v) \\<in> Reals\"\n    using hermitian_inner_prod_real dimA by auto\n\n  assume npA: \" \\<not> positive A\"\n  from npA have \"\\<not> (A \\<in> carrier_mat (dim_col A) (dim_col A)) \\<or> \\<not> (\\<forall>v. dim_vec v = dim_col A \\<longrightarrow> 0 \\<le> inner_prod v (A *\\<^sub>v v))\"\n    unfolding positive_def by blast\n  then have evA: \"\\<exists> v. dim_vec v = dim_col A \\<and> \\<not> inner_prod v (A *\\<^sub>v v) \\<ge> 0\" using dimA by blast\n  then have \"\\<exists> v. dim_vec v = dim_col A \\<and>  inner_prod v (A *\\<^sub>v v) < 0\"\n  proof -\n    obtain v where vA: \"dim_vec v = dim_col A \\<and> \\<not> inner_prod v (A *\\<^sub>v v) \\<ge> 0\" using evA by auto\n    from vA herprod have \"\\<not> 0 \\<le> inner_prod v (A *\\<^sub>v v) \\<and> inner_prod v (A *\\<^sub>v v) \\<in> Reals\" by auto\n    then have \"inner_prod v (A *\\<^sub>v v) < 0\"\n      using complex_is_Real_iff by auto\n    then have  \"\\<exists> v. dim_vec v = dim_col A \\<and>  inner_prod v (A *\\<^sub>v v) < 0\" using vA by auto\n    then show ?thesis by auto\n  qed\n\n  then obtain v where neg: \"dim_vec v = dim_col A \\<and> inner_prod v (A *\\<^sub>v v) < 0\" by auto\n\n  have   nzero: \"v \\<noteq> 0\\<^sub>v m\"\n  proof (rule ccontr)\n    assume nega: \" \\<not> v \\<noteq> 0\\<^sub>v m\"\n    have zero: \"v = 0\\<^sub>v m\" using nega by auto\n    have \"(A *\\<^sub>v v) = 0\\<^sub>v m\" unfolding mult_mat_vec_def using zero\n      using dimA by auto\n    then have zerov: \"inner_prod v (A *\\<^sub>v v) = 0\" by (simp add: zero)\n    from neg zerov have \"\\<not> v \\<noteq> 0\\<^sub>v m \\<Longrightarrow> False\"  using dimA by auto\n    with nega show False by auto\n  qed\n\n  have invgeq: \"inner_prod v v > 0\"\n  proof -\n    have \"inner_prod v v = vec_norm v * vec_norm v\" unfolding vec_norm_def\n      by (metis carrier_matD(2) carrier_vec_dim_vec dimA mult_cancel_left1 neg normalized_cscalar_prod normalized_vec_norm nzero vec_norm_def)\n    moreover have \"vec_norm v > 0\" using nzero vec_norm_ge_0 neg dimA\n      by (metis carrier_matD(2) carrier_vec_dim_vec)\n    ultimately have \"inner_prod v v > 0\" by auto\n    then show ?thesis by auto\n  qed\n\n  have invv: \"inner_prod v v = (\\<Sum>i = 0..<m. cmod (conjugate (v $ i) * (v $ i)))\"\n  proof -\n    {\n      have \"\\<forall> i < m. conjugate (v $ i) * (v $ i) \\<ge> 0\" using conjugate_square_smaller_0 by simp\n      then have vi: \"\\<forall> i < m. conjugate (v $ i) * (v $ i) = cmod (conjugate (v $ i) * (v $ i))\" using cmod_eq_Re\n        by (simp add: complex.expand)\n\n      have \"inner_prod v v= (\\<Sum>i = 0..<m. ((v $ i) * conjugate (v $ i)))\"\n        unfolding scalar_prod_def conjugate_vec_def using neg dimA by auto\n      also have \"\\<dots> = (\\<Sum>i = 0..<m. (conjugate (v $ i) * (v $ i)))\"\n        by (meson mult.commute)\n      also have \"\\<dots> = (\\<Sum>i = 0..<m. cmod (conjugate (v $ i) * (v $ i)))\" using vi by auto\n      finally have  \"inner_prod v v = (\\<Sum>i = 0..<m. cmod (conjugate (v $ i) * (v $ i)))\" by auto\n    }\n    then show ?thesis by auto\n  qed\n\n  let ?r = \"inner_prod v (A *\\<^sub>v v)\" have rl: \"?r < 0\" using neg by auto\n  have vAv: \"inner_prod v (A *\\<^sub>v v) =  (\\<Sum>i=0..<m. (\\<Sum>j=0..<m.\n                conjugate (v$i) * A$$(i, j) * v$j))\" using quadratic_form_mat dimA neg by auto\n  from limX have limij: \"\\<forall>i<m. \\<forall>j<m. (\\<lambda>n. X n $$ (i, j)) \\<longlonglongrightarrow> A $$ (i, j)\" unfolding limit_mat_def by auto\n  then have limXv: \"(\\<lambda> n. inner_prod v ((X n) *\\<^sub>v v)) \\<longlonglongrightarrow> inner_prod v (A *\\<^sub>v v)\"\n  proof -\n    have XAless: \"cmod (inner_prod v (X n *\\<^sub>v v) - inner_prod v (A *\\<^sub>v v)) \\<le>\n      (\\<Sum>i = 0..<m. \\<Sum>j = 0..<m. cmod (conjugate (v $ i)) * cmod (X n $$ (i, j) - A $$ (i, j)) * cmod (v $ j))\" for n\n    proof -\n      have \"\\<forall> i < m. \\<forall> j < m. conjugate (v$i) * X n $$(i, j) * v$j - conjugate (v$i) * A$$(i, j) * v$j =\n        conjugate (v$i) * (X n $$(i, j)-A$$(i, j)) * v$j\"\n        by (simp add: mult.commute right_diff_distrib)\n      then have ele: \"\\<forall> i < m.(\\<Sum>j=0..<m.(conjugate (v$i) * X n $$(i, j) * v$j - conjugate (v$i) * A$$(i, j) * v$j)) = (\\<Sum>j=0..<m.(\n              conjugate (v$i) * (X n $$(i, j)-A$$(i, j)) * v$j))\" by auto\n      have \"\\<forall> i < m. \\<forall> j < m. cmod(conjugate (v $ i) * (X n $$ (i, j) - A $$ (i, j)) * v $ j) =\n                cmod(conjugate (v $ i)) * cmod (X n $$ (i, j) - A $$ (i, j)) * cmod(v $ j)\"\n        by (simp add: norm_mult)\n      then have less: \"\\<forall> i < m.(\\<Sum>j = 0..<m. cmod(conjugate (v $ i) * (X n $$ (i, j) - A $$ (i, j)) * v $ j)) =\n                (\\<Sum>j = 0..<m. cmod(conjugate (v $ i)) * cmod (X n $$ (i, j) - A $$ (i, j)) * cmod(v $ j))\" by auto\n\n      have \"inner_prod v (X n *\\<^sub>v v) - inner_prod v (A *\\<^sub>v v) = (\\<Sum>i=0..<m. (\\<Sum>j=0..<m.\n              conjugate (v$i) * X n $$(i, j) * v$j)) - (\\<Sum>i=0..<m. (\\<Sum>j=0..<m.\n              conjugate (v$i) * A$$(i, j) * v$j))\"  using quadratic_form_mat neg dimA dimX by auto\n      also have \"\\<dots> = (\\<Sum>i=0..<m. (\\<Sum>j=0..<m.(\n              conjugate (v$i) * X n $$(i, j) * v$j - conjugate (v$i) * A$$(i, j) * v$j)))\"\n        using sum_subtractff[of \"\\<lambda> i j. conjugate (v $ i) * X n $$ (i, j) * v $ j\" \"\\<lambda> i j. conjugate (v $ i) * A $$ (i, j) * v $ j\" \"{0..<m}\"] by auto\n      also have \"\\<dots> = (\\<Sum>i=0..<m. (\\<Sum>j=0..<m.(\n              conjugate (v$i) * (X n $$(i, j)-A$$(i, j)) * v$j)))\"  using ele by auto\n      finally have minusXA: \"inner_prod v (X n *\\<^sub>v v) - inner_prod v (A *\\<^sub>v v) = (\\<Sum>i = 0..<m. \\<Sum>j = 0..<m. conjugate (v $ i) * (X n $$ (i, j) - A $$ (i, j)) * v $ j)\" by auto\n\n      from minusXA have \"cmod (inner_prod v (X n *\\<^sub>v v) - inner_prod v (A *\\<^sub>v v)) =\n              cmod (\\<Sum>i = 0..<m. \\<Sum>j = 0..<m. conjugate (v $ i) * (X n $$ (i, j) - A $$ (i, j)) * v $ j)\" by auto\n      also have \"\\<dots> \\<le> (\\<Sum>i = 0..<m. \\<Sum>j = 0..<m. cmod(conjugate (v $ i) * (X n $$ (i, j) - A $$ (i, j)) * v $ j))\"\n        using sum_abs_complex by simp\n      also have \"\\<dots> = (\\<Sum>i = 0..<m. \\<Sum>j = 0..<m. cmod(conjugate (v $ i)) * cmod (X n $$ (i, j) - A $$ (i, j)) * cmod(v $ j))\"\n        using less by auto\n      finally show ?thesis by auto\n    qed\n\n    from limij have limijm: \" \\<forall>i<m. \\<forall>j<m. \\<forall>r>0. \\<exists>no. \\<forall>n\\<ge>no. cmod (X n $$ (i, j) - A $$ (i, j)) < r\"\n      unfolding LIMSEQ_def dist_norm by auto\n    from limX have mg: \"m > 0\" using limit_mat_def\n      by (metis carrier_matD(1) carrier_matD(2) mat_eq_iff neq0_conv not_less0 npA posX)\n\n    have cmoda: \"\\<exists>no. \\<forall>n\\<ge>no. (\\<Sum>i = 0..<m. \\<Sum>j = 0..<m. cmod (conjugate (v $ i)) * cmod (X n $$ (i, j) - A $$ (i, j)) * cmod (v $ j)) < r\"\n      if r: \"r > 0\" for r\n    proof -\n      let ?u = \"(\\<Sum>i = 0..<m. \\<Sum>j = 0..<m.((cmod (conjugate (v $ i)) * cmod (v $ j))))\"\n      have ug: \"?u > 0\"\n      proof -\n        have ur: \"?u = (\\<Sum>i = 0..<m. (cmod (conjugate (v $ i)) * (\\<Sum>j = 0..<m.( cmod (v $ j)))))\"  by (simp add: sum_distrib_left)\n        have \"(\\<Sum>j = 0..<m.( cmod (v $ j))) \\<ge> cmod (v $ i)\" if i: \"i < m\" for i\n          using member_le_sum[of i \"{0..<m}\" \"\\<lambda> j. cmod (v$j)\"] cmod_def i by simp\n        then have \"\\<forall> i < m. (cmod (conjugate (v $ i)) * (\\<Sum>j = 0..<m.( cmod (v $ j)))) \\<ge> (cmod (conjugate (v $ i)) * cmod (v $ i))\"\n          by (simp add: mult_left_mono)\n        then have \"?u \\<ge> (\\<Sum>i = 0..<m. (cmod (conjugate (v $ i)) *cmod (v $ i)))\"\n          using ur sum_mono[of \"{0..<m}\" \"\\<lambda> i.  cmod (conjugate (v $ i)) * cmod (v $ i)\" \"\\<lambda> i. cmod (conjugate (v $ i)) * (\\<Sum>j = 0..<m. cmod (v $ j))\"]\n          by auto\n        moreover have \"(\\<Sum>i = 0..<m. cmod (conjugate (v $ i)  *cmod (v $ i))) = (\\<Sum>i = 0..<m. cmod (conjugate (v $ i) * (v $ i)))\"\n          using norm_ge_zero norm_mult norm_of_real by (metis (no_types, hide_lams) abs_of_nonneg)\n        moreover have \"(\\<Sum>i = 0..<m. cmod (conjugate (v $ i) * (v $ i))) = inner_prod v v\" using invv by auto\n        ultimately have \"?u \\<ge>  inner_prod v v\"\n          by (metis (no_types, lifting) Im_complex_of_real Re_complex_of_real invv less_eq_complex_def norm_mult sum.cong)\n        then have \"?u > 0\"  using invgeq by auto\n        then show ?thesis by auto\n      qed\n\n      let ?s = \"r / (2 * ?u)\"\n      have sgz: \"?s > 0\" using ug rl\n        by (smt divide_pos_pos dual_order.strict_iff_order linordered_semiring_strict_class.mult_pos_pos zero_less_norm_iff r)\n      from limijm have sij: \"\\<exists>no. \\<forall>n\\<ge>no. cmod (X n $$ (i, j) - A $$ (i, j)) < ?s\" if i: \"i < m\" and j: \"j < m\" for i j\n      proof -\n        obtain N where Ns: \"\\<forall>n\\<ge>N. cmod (X n $$ (i, j) - A $$ (i, j)) < ?s\" using sgz limijm i j by blast\n        then show ?thesis by auto\n      qed\n      then have \"\\<exists>no. \\<forall>i<m. \\<forall>j<m. \\<forall>n\\<ge>no. cmod (X n $$ (i, j) - A $$ (i, j)) < ?s\"\n        using quantifier_change_order_twice[of m m \"\\<lambda> n i j. (cmod (X n $$ (i, j) - A $$ (i, j))<?s)\"] by auto\n      then obtain N where Nno: \"\\<forall>i<m. \\<forall>j<m. \\<forall>n\\<ge>N. cmod (X n $$ (i, j) - A $$ (i, j)) < ?s\" by auto\n      then have mmN: \"cmod (conjugate (v $ i)) * cmod (X n $$ (i, j) - A $$ (i, j)) * cmod (v $ j)\n                       \\<le> ?s * (cmod (conjugate (v $ i)) * cmod (v $ j))\"\n        if i: \"i < m\" and j: \"j < m\" and n: \"n \\<ge> N\" for i j n\n      proof -\n        have geq: \"cmod (conjugate (v $ i)) \\<ge> 0 \\<and> cmod (v $ j)\\<ge>0\" by simp\n        then have \"cmod (conjugate (v $ i)) * cmod (X n $$ (i, j) - A $$ (i, j)) \\<le>cmod (conjugate (v $ i)) * ?s\" using Nno i j n\n          by (smt mult_left_mono)\n        then have \"cmod (conjugate (v $ i)) * cmod (X n $$ (i, j) - A $$ (i, j)) * cmod (v $ j)\n                    \\<le> cmod (conjugate (v $ i)) *?s * cmod (v $ j)\" using geq mult_right_mono by blast\n        also have \"\\<dots> = ?s * (cmod (conjugate (v $ i)) * cmod (v $ j))\" by simp\n        finally show ?thesis by auto\n      qed\n      then have \"(\\<Sum>i = 0..<m. \\<Sum>j = 0..<m. cmod (conjugate (v $ i)) * cmod (X n $$ (i, j) - A $$ (i, j)) * cmod (v $ j)) < r\"\n        if n: \"n \\<ge> N\" for n\n      proof -\n        have mmX: \"\\<forall>i<m. \\<forall>j<m. cmod (conjugate (v $ i)) * cmod (X n $$ (i, j) - A $$ (i, j)) * cmod (v $ j)\n                   \\<le> ?s * (cmod (conjugate (v $ i)) * cmod (v $ j))\" using n mmN by blast\n        have \"(\\<Sum>j = 0..<m. cmod (conjugate (v $ i)) * cmod (X n $$ (i, j) - A $$ (i, j)) * cmod (v $ j))\n                   \\<le> (\\<Sum>j = 0..<m.(?s * (cmod (conjugate (v $ i)) * cmod (v $ j))))\" if i: \"i < m\" for i\n        proof -\n          have \"\\<forall>j<m. cmod (conjugate (v $ i)) * cmod (X n $$ (i, j) - A $$ (i, j)) * cmod (v $ j)\n                 \\<le> ?s * (cmod (conjugate (v $ i)) * cmod (v $ j))\" using mmX i by auto\n          then show ?thesis\n          using sum_mono[of \"{0..<m}\" \"\\<lambda> j. cmod (conjugate (v $ i)) * cmod (X n $$ (i, j) - A $$ (i, j)) * cmod (v $ j)\" \"\\<lambda> j. (?s * (cmod (conjugate (v $ i)) * cmod (v $ j)))\"]\n            atLeastLessThan_iff by blast\n        qed\n        then have \"(\\<Sum>i = 0..<m. \\<Sum>j = 0..<m. cmod (conjugate (v $ i)) * cmod (X n $$ (i, j) - A $$ (i, j)) * cmod (v $ j))\n                  \\<le> (\\<Sum>i = 0..<m. \\<Sum>j = 0..<m.(?s * (cmod (conjugate (v $ i)) * cmod (v $ j))))\" using sum_mono atLeastLessThan_iff\n          by (metis (no_types, lifting))\n        also have \"\\<dots> = ?s * (\\<Sum>i = 0..<m. \\<Sum>j = 0..<m.((cmod (conjugate (v $ i)) * cmod (v $ j))))\"  by (simp add: sum_distrib_left)\n        also have \"\\<dots> = r / 2\" using nonzero_mult_divide_mult_cancel_right sgz by fastforce\n        finally show ?thesis using r by auto\n      qed\n      then show ?thesis by auto\n    qed\n    then have XnAv:\"\\<exists>no. \\<forall>n\\<ge>no. cmod (inner_prod v (X n *\\<^sub>v v) - inner_prod v (A *\\<^sub>v v)) < r\" if r: \"r > 0\" for r\n    proof -\n      obtain no where nno: \"\\<forall>n\\<ge>no. (\\<Sum>i = 0..<m. \\<Sum>j = 0..<m. cmod (conjugate (v $ i)) * cmod (X n $$ (i, j) - A $$ (i, j)) * cmod (v $ j)) < r\"\n        using r cmoda neg by auto\n      then have \"\\<forall>n\\<ge>no. cmod (inner_prod v (X n *\\<^sub>v v) - inner_prod v (A *\\<^sub>v v)) < r\" using XAless neg by smt\n      then show ?thesis by auto\n    qed\n    then have \"(\\<lambda>n. inner_prod v (X n *\\<^sub>v v)) \\<longlonglongrightarrow> inner_prod v (A *\\<^sub>v v)\" unfolding LIMSEQ_def dist_norm by auto\n    then show ?thesis by auto\n  qed\n\n  from limXv have \"\\<forall>r>0. \\<exists>no. \\<forall>n\\<ge>no. cmod (inner_prod v (X n *\\<^sub>v v) - inner_prod v (A *\\<^sub>v v)) < r\" unfolding LIMSEQ_def dist_norm by auto\n  then have \"\\<exists>no. \\<forall>n\\<ge>no. cmod (inner_prod v (X n *\\<^sub>v v) - inner_prod v (A *\\<^sub>v v)) < -?r\" using rl by auto\n  then obtain N where Ng: \"\\<forall>n\\<ge>N. cmod (inner_prod v (X n *\\<^sub>v v) - inner_prod v (A *\\<^sub>v v)) < -?r\" by auto\n  then have XN: \"cmod (inner_prod v (X N *\\<^sub>v v) - inner_prod v (A *\\<^sub>v v)) < -?r\" by auto\n\n  from posX have \"positive (X N)\" by auto\n  then have XNv:\"inner_prod v (X N *\\<^sub>v v) \\<ge> 0\"\n    by (metis Complex_Matrix.positive_def carrier_matD(2) dimA dimX neg)\n\n  from rl XNv have XX: \"cmod (inner_prod v (X N *\\<^sub>v v) - inner_prod v (A *\\<^sub>v v)) = cmod(inner_prod v (X N *\\<^sub>v v)) - cmod(inner_prod v (A *\\<^sub>v v))\"\n    using XN cmod_eq_Re by auto\n  then have YY: \"cmod(inner_prod v (X N *\\<^sub>v v)) - cmod(inner_prod v (A *\\<^sub>v v)) < -?r\" using XN by auto\n  then have \"cmod(inner_prod v (X N *\\<^sub>v v)) - cmod(inner_prod v (A *\\<^sub>v v)) < cmod(inner_prod v (A *\\<^sub>v v))\" using rl cmod_eq_Re by auto\n  then have  \"cmod(inner_prod v (X N *\\<^sub>v v)) < 0\"  using XNv XX YY cmod_eq_Re by auto\n  then have \"False\" using XNv by simp\n  with npA show False by auto\nqed\n\nlemma limit_mat_ignore_initial_segment:\n  \"limit_mat g A d \\<Longrightarrow> limit_mat (\\<lambda>n. g (n + k)) A d\"\nproof -\n  assume asm: \"limit_mat g A d\"\n  then have lim: \"\\<forall> i < d. \\<forall> j < d. (\\<lambda> n. (g n) $$ (i, j)) \\<longlonglongrightarrow> (A $$ (i, j))\" using limit_mat_def by auto\n  then have limk: \"\\<forall> i < d. \\<forall> j < d. (\\<lambda> n. (g (n + k)) $$ (i, j)) \\<longlonglongrightarrow> (A $$ (i, j))\"\n  proof -\n    {\n      fix i j assume dims: \"i < d\" \"j < d\"\n      then have \"(\\<lambda> n. (g n) $$ (i, j)) \\<longlonglongrightarrow> (A $$ (i, j))\" using lim by auto\n      then have \"(\\<lambda> n. (g (n + k)) $$ (i, j)) \\<longlonglongrightarrow> (A $$ (i, j))\" using LIMSEQ_ignore_initial_segment by auto\n    }\n    then show \"\\<forall> i < d. \\<forall> j < d. (\\<lambda> n. (g (n + k)) $$ (i, j)) \\<longlonglongrightarrow> (A $$ (i, j))\" by auto\n  qed\n  have \"\\<forall> n. g n \\<in> carrier_mat d d\" using asm unfolding limit_mat_def by auto\n  then have \"\\<forall> n. g (n + k) \\<in> carrier_mat d d\" by auto\n  moreover have \"A \\<in> carrier_mat d d\" using asm limit_mat_def by auto\n  ultimately show \"limit_mat (\\<lambda>n. g (n + k)) A d\" using limit_mat_def limk by auto\nqed\n\nlemma mat_trace_limit:\n  \"limit_mat g A d \\<Longrightarrow> (\\<lambda>n. trace (g n)) \\<longlonglongrightarrow> trace A\"\nproof -\n  assume lim: \"limit_mat g A d\"\n  then have dgn: \"g n \\<in> carrier_mat d d\" for n using limit_mat_def by auto\n  from lim have dA: \"A \\<in> carrier_mat d d\" using limit_mat_def by auto\n  have trg: \"trace (g n) = (\\<Sum>k=0..<d. (g n)$$(k, k))\" for n unfolding trace_def using carrier_matD[OF dgn] by auto\n  have \"\\<forall>k < d. (\\<lambda>n. (g n)$$(k, k)) \\<longlonglongrightarrow> A$$(k, k)\" using limit_mat_def lim by auto\n  then have \"(\\<lambda>n. (\\<Sum>k=0..<d. (g n)$$(k, k))) \\<longlonglongrightarrow> (\\<Sum>k=0..<d. A$$(k, k))\"\n    using tendsto_sum[where ?I = \"{0..<d}\" and ?f = \"(\\<lambda>k n. (g n)$$(k, k))\"] by auto\n  then show \"(\\<lambda>n. trace (g n)) \\<longlonglongrightarrow> trace A\" unfolding trace_def\n    using trg carrier_matD[OF dgn] carrier_matD[OF dA] by auto\nqed\n\nsubsection \\<open>Existence of least upper bound for the L\\\"{o}wner order\\<close>\n\ndefinition lowner_is_lub :: \"(nat \\<Rightarrow> complex mat) \\<Rightarrow> complex mat \\<Rightarrow> bool\" where\n  \"lowner_is_lub f M \\<longleftrightarrow> (\\<forall>n. f n \\<le>\\<^sub>L M) \\<and> (\\<forall>M'. (\\<forall>n. f n \\<le>\\<^sub>L M') \\<longrightarrow> M \\<le>\\<^sub>L M')\"\n\nlocale matrix_seq =\n  fixes dim :: nat\n    and f :: \"nat \\<Rightarrow> complex mat\"\n  assumes\n    dim: \"\\<And>n. f n \\<in> carrier_mat dim dim\" and\n    pdo: \"\\<And>n. partial_density_operator (f n)\" and\n    inc: \"\\<And>n. lowner_le (f n) (f (Suc n))\"\nbegin\n\ndefinition lowner_is_lub :: \"complex mat \\<Rightarrow> bool\" where\n  \"lowner_is_lub M \\<longleftrightarrow> (\\<forall>n. f n \\<le>\\<^sub>L M) \\<and> (\\<forall>M'. (\\<forall>n. f n \\<le>\\<^sub>L M') \\<longrightarrow> M \\<le>\\<^sub>L M')\"\n\nlemma lowner_is_lub_dim:\n  assumes \"lowner_is_lub M\"\n  shows \"M \\<in> carrier_mat dim dim\"\nproof -\n  have \"f 0 \\<le>\\<^sub>L M\" using assms lowner_is_lub_def by auto\n  then have 1: \"dim_row (f 0) = dim_row M \\<and> dim_col (f 0) = dim_col M\"\n    using lowner_le_def by auto\n  moreover have 2: \"f 0 \\<in> carrier_mat dim dim\"\n    using dim by auto\n  ultimately show ?thesis by auto\nqed\n\nlemma trace_adjoint_eq_u:\n  fixes A :: \"complex mat\"\n  shows \"trace (A * adjoint A) = (\\<Sum> i \\<in> {0 ..< dim_row A}. \\<Sum> j \\<in> {0 ..< dim_col A}. (norm(A $$ (i,j)))\\<^sup>2)\"\nproof -\n  have \"trace (A * adjoint A) = (\\<Sum> i \\<in> {0 ..< dim_row A}. row A i \\<bullet> conjugate (row A i))\"\n    by (simp add: trace_def cmod_def adjoint_def scalar_prod_def)\n  also have \"\\<dots> = (\\<Sum> i \\<in> {0 ..< dim_row A}. \\<Sum> j \\<in> {0 ..< dim_col A}. (norm(A $$ (i,j)))\\<^sup>2)\"\n    proof (simp add: scalar_prod_def cmod_def)\n      have cnjmul: \"\\<forall> i ia. A $$ (i, ia) * cnj (A $$ (i, ia)) =\n                   ((complex_of_real (Re (A $$ (i, ia))))\\<^sup>2 + (complex_of_real (Im (A $$ (i, ia))))\\<^sup>2)\"\n        by (simp add: complex_mult_cnj)\n      then have \"\\<forall> i. (\\<Sum>ia = 0..<dim_col A. A $$ (i, ia) * cnj (A $$ (i, ia))) =\n                      (\\<Sum>ia = 0..<dim_col A.  ((complex_of_real (Re (A $$ (i, ia))))\\<^sup>2 + (complex_of_real (Im (A $$ (i, ia))))\\<^sup>2))\"\n        by auto\n      then show\"(\\<Sum>i = 0..<dim_row A. \\<Sum>ia = 0..<dim_col A. A $$ (i, ia) * cnj (A $$ (i, ia))) =\n        (\\<Sum>x = 0..<dim_row A. \\<Sum>xa = 0..<dim_col A. (complex_of_real (Re (A $$ (x, xa))))\\<^sup>2) +\n        (\\<Sum>x = 0..<dim_row A. \\<Sum>xa = 0..<dim_col A. (complex_of_real (Im (A $$ (x, xa))))\\<^sup>2)\"\n        by auto\n    qed\n  finally show ?thesis .\nqed\n\nlemma trace_adjoint_element_ineq:\n  fixes A :: \"complex mat\"\n  assumes rindex: \"i \\<in> {0 ..< dim_row A}\"\n     and  cindex: \"j \\<in> {0 ..< dim_col A}\"\n  shows \"(norm(A $$ (i,j)))\\<^sup>2 \\<le> trace (A * adjoint A)\"\nproof (simp add: trace_adjoint_eq_u)\n  have ineqi: \"(cmod (A $$ (i, j)))\\<^sup>2 \\<le> (\\<Sum>xa = 0..<dim_col A. (cmod (A $$ (i, xa)))\\<^sup>2)\"\n    using cindex member_le_sum[of j \" {0 ..< dim_col A}\" \"\\<lambda> x. (cmod (A $$ (i, x)))\\<^sup>2\"] by auto\n  also have ineqj: \"\\<dots> \\<le> (\\<Sum>x = 0..<dim_row A. \\<Sum>xa = 0..<dim_col A. (cmod (A $$ (x, xa)))\\<^sup>2)\"\n    using rindex member_le_sum[of i \" {0 ..< dim_row A}\" \"\\<lambda> x. \\<Sum>xa = 0..<dim_col A. (cmod (A $$ (x, xa)))\\<^sup>2\"]\n    by (simp add: sum_nonneg)\n  then show \"(cmod (A $$ (i, j)))\\<^sup>2 \\<le> (\\<Sum>x = 0..<dim_row A. \\<Sum>xa = 0..<dim_col A. (cmod (A $$ (x, xa)))\\<^sup>2)\"\n  using ineqi by linarith\n qed\n\nlemma positive_is_normal:\n  fixes A :: \"complex mat\"\n  assumes pos: \"positive A\"\n  shows \"A * adjoint A = adjoint A * A\"\nproof -\n  have hA: \"hermitian A\" using positive_is_hermitian pos by auto\n  then show ?thesis by (simp add: hA hermitian_is_normal)\nqed\n\nlemma diag_mat_mul_diag_diag:\n  fixes A B ::  \"complex mat\"\n  assumes dimA: \"A \\<in> carrier_mat n n\" and dimB: \"B \\<in> carrier_mat n n\"\n    and dA: \"diagonal_mat A\"  and dB: \"diagonal_mat B\"\n  shows \"diagonal_mat (A * B)\"\nproof  -\n  have AB: \"A * B = mat n n (\\<lambda>(i,j). (if (i = j) then (A$$(i, i)) * (B$$(i, i)) else 0))\"\n    using diag_mat_mult_diag_mat[of A n B] dimA dimB dA dB by auto\n  then have dAB: \"\\<forall>i<n. \\<forall>j<n. i \\<noteq> j \\<longrightarrow> (A*B) $$ (i,j) = 0\"\n  proof -\n    {\n      fix i j assume i: \"i < n\" and j: \"j < n\" and ij: \"i \\<noteq> j\"\n      have \"(A*B) $$ (i,j) = 0\" using AB i j ij by auto\n    }\n    then show ?thesis by auto\n  qed\n  then show ?thesis using diagonal_mat_def dAB dimA dimB\n    by (metis carrier_matD(1) carrier_matD(2) index_mult_mat(2) index_mult_mat(3))\nqed\n\nlemma diag_mat_mul_diag_ele:\n  fixes A B :: \"complex mat\"\n  assumes dimA: \"A \\<in> carrier_mat n n\" and dimB: \"B \\<in> carrier_mat n n\"\n    and dA: \"diagonal_mat A\" and dB: \"diagonal_mat B\"\n  shows \"\\<forall>i<n. (A*B) $$ (i,i) = A$$(i, i) * B$$(i, i)\"\nproof -\n  have AB: \"A * B = mat n n (\\<lambda>(i,j). if i = j then (A$$(i, i)) * (B$$(i, i)) else 0)\"\n    using diag_mat_mult_diag_mat[of A n B] dimA dimB dA dB by auto\n  then show ?thesis\n    using AB by auto\nqed\n\nlemma trace_square_less_square_trace:\n  fixes B ::  \"complex mat\"\n  assumes dimB: \"B \\<in> carrier_mat n n\"\n      and dB: \"diagonal_mat B\" and pB: \"\\<And>i. i < n \\<Longrightarrow> B$$(i, i) \\<ge> 0\"\n    shows \"trace (B*B) \\<le> (trace B)\\<^sup>2\"\nproof -\n  have tB:  \"trace B = (\\<Sum> i \\<in> {0 ..<n}. B $$ (i,i))\" using assms trace_def[of B] carrier_mat_def by auto\n  then have tBtB: \"(trace B)\\<^sup>2 = (\\<Sum> i \\<in> {0 ..<n}.\\<Sum> j \\<in> {0 ..<n}. B $$ (i,i)*B $$ (j,j))\"\n  proof -\n    show ?thesis\n      by (metis (no_types) semiring_normalization_rules(29) sum_product tB)\n  qed\n  have BB: \"\\<And>i. i < n \\<Longrightarrow> (B*B) $$ (i,i) = (B$$(i, i))\\<^sup>2\" using diag_mat_mul_diag_ele[of B n B] dimB dB\n      by (metis numeral_1_eq_Suc_0 power_Suc0_right power_add_numeral semiring_norm(2))\n  have tBB:  \"trace (B*B) = (\\<Sum> i \\<in> {0 ..<n}. (B*B) $$ (i,i))\" using assms trace_def[of \"B*B\"] carrier_mat_def by auto\n  also have \"\\<dots> =  (\\<Sum> i \\<in> {0 ..<n}. (B$$(i, i))\\<^sup>2)\" using BB by auto\n  finally have BBt: \" trace (B * B) = (\\<Sum>i = 0..<n. (B $$ (i, i))\\<^sup>2)\" by auto\n  have lesseq: \"\\<forall>i \\<in> {0 ..<n}. (B $$ (i, i))\\<^sup>2 \\<le> (\\<Sum> j \\<in> {0 ..<n}. B $$ (i,i)*B $$ (j,j))\"\n  proof -\n    {\n      fix i assume i: \"i < n\"\n      have \"(\\<Sum>j = 0..<n. B $$ (i, i) * B $$ (j, j)) = (B $$ (i, i))\\<^sup>2  + sum (\\<lambda> j. (B $$ (i, i) * B $$ (j, j))) ({0 ..<n} - {i})\"\n        by (metis (no_types, lifting) BB atLeastLessThan_iff dB diag_mat_mul_diag_ele dimB finite_atLeastLessThan i not_le not_less_zero sum.remove)\n      moreover have \"(sum (\\<lambda> j. (B $$ (i, i) * B $$ (j, j))) ({0 ..<n} - {i})) \\<ge> 0\"\n      proof (cases \"{0..<n} - {i} \\<noteq> {}\")\n        case True\n        then show ?thesis using pB i sum_nonneg[of \"{0..<n} - {i}\" \"\\<lambda> j. (B $$ (i, i) * B $$ (j, j))\"] by auto\n       next\n         case False\n         have \"(\\<Sum>j\\<in>{0..<n} - {i}. B $$ (i, i) * B $$ (j, j)) = 0\" using False by fastforce\n       then show ?thesis by auto\n     qed\n     ultimately have \"(\\<Sum>j = 0..<n. B $$ (i, i) * B $$ (j, j)) \\<ge> (B $$ (i, i))\\<^sup>2\" by auto\n   }\n   then show ?thesis by auto\n qed\n  from tBtB BBt lesseq have \"trace (B*B) \\<le> (trace B)\\<^sup>2\"\n    using sum_mono[of \"{0..<n}\" \"\\<lambda> i. (B $$ (i, i))\\<^sup>2\" \"\\<lambda> i. (\\<Sum>j = 0..<n. B $$ (i, i) * B $$ (j, j))\"]\n    by (metis (no_types, lifting))\n  then show ?thesis by auto\nqed\n\nlemma trace_positive_eq:\n   fixes A :: \"complex mat\"\n   assumes pos: \"positive A\"\n   shows \"trace (A * adjoint A) \\<le> (trace A)\\<^sup>2\"\nproof -\n  from assms  have normal: \"A * adjoint A = adjoint A * A\" by (rule positive_is_normal)\n  moreover\n  from assms positive_dim_eq obtain n where cA: \"A \\<in> carrier_mat n n\" by auto\n  moreover\n  from assms complex_mat_char_poly_factorizable cA obtain es where charpo: \" char_poly A =  (\\<Prod> a \\<leftarrow> es. [:- a, 1:]) \\<and> length es = n\" by auto\n  moreover\n  obtain B P Q where B: \"unitary_schur_decomposition A es = (B,P,Q)\" by (cases \"unitary_schur_decomposition A es\", auto)\n  ultimately have\n    smw: \"similar_mat_wit A B P (adjoint P)\"\n    and ut: \"diagonal_mat B\"\n    and uP:  \"unitary P\"\n    and dB: \"diag_mat B = es\"\n    and QaP: \"Q = adjoint P\"\n    using normal_complex_mat_has_spectral_decomposition[of A n es B P Q]  unitary_schur_decomposition by auto\n  from smw cA QaP uP have cB: \"B \\<in> carrier_mat n n\" and cP: \"P \\<in> carrier_mat n n\" and cQ: \"Q \\<in> carrier_mat n n\"\n    unfolding  similar_mat_wit_def Let_def unitary_def by auto\n  then have caP: \"adjoint P \\<in> carrier_mat n n\" using adjoint_dim[of P n] by auto\n  from smw QaP cA have A: \"A = P * B * adjoint P\" and traceA: \"trace A = trace (P * B * Q)\" and PB: \"P * Q = 1\\<^sub>m n \\<and> Q * P = 1\\<^sub>m n\"\n    unfolding similar_mat_wit_def by auto\n  have traceAB: \"trace (P * B * Q) = trace ((Q*P)*B)\"\n    using cQ cP cB by (mat_assoc n)\n  also have traceelim: \"\\<dots> = trace B\" using traceAB PB cA cB cP cQ left_mult_one_mat[of \"P*Q\" n n]\n    using similar_mat_wit_sym by auto\n  finally have traceAB: \"trace A = trace B\" using traceA by auto\n  from A cB cP have aAa: \"adjoint A = adjoint((P * B) * adjoint P)\" by auto\n  have aA: \"adjoint A = P * adjoint B * adjoint P\"\n    unfolding aAa using cP cB by (mat_assoc n)\n  have hA: \"hermitian A\" using pos positive_is_hermitian by auto\n  then have AaA: \"A = adjoint A\" using hA hermitian_def[of A] by auto\n  then have PBaP: \"P * B * adjoint P = P * adjoint B * adjoint P\" using A aA by auto\n  then have BaB: \"B = adjoint B\" using unitary_elim[of B n \"adjoint B\" P] uP cP cB adjoint_dim[of B n] by auto\n  have aPP: \"adjoint P * P = 1\\<^sub>m n\" using uP PB QaP by blast\n  have \"A * A = P * B * (adjoint P * P) * B * adjoint P\"\n    unfolding A using cP cB by (mat_assoc n)\n  also have \"\\<dots> = P * B * B * adjoint P\"\n    unfolding aPP using cP cB by (mat_assoc n)\n  finally have AA: \"A * A = P * B * B * adjoint P\" by auto\n  then have tAA: \"trace (A*A) = trace (P * B * B * adjoint P)\" by auto\n  also have tBB: \"\\<dots> = trace (adjoint P * P * B * B)\" using cP cB by (mat_assoc n)\n  also have \"\\<dots> = trace (B * B)\" using uP unitary_def[of P] inverts_mat_def[of P \"adjoint P\"]\n    using PB QaP cB by auto\n  finally have traceAABB: \"trace (A * A) = trace (B * B)\" by auto\n  have BP: \"\\<And>i. i < n \\<Longrightarrow> B$$(i, i) \\<ge> 0\"\n  proof -\n     {\n       fix i assume i: \"i < n\"\n       then have \"B$$(i, i) \\<ge> 0\" using positive_eigenvalue_positive[of A n es B P Q i] cA pos charpo B by auto\n       then show \"B$$(i, i) \\<ge> 0\" by auto\n     }\n   qed\n   have Brel: \"trace (B*B) \\<le> (trace B)\\<^sup>2\" using trace_square_less_square_trace[of B n] cB ut BP by auto\n   from AaA traceAABB traceAB Brel have \"trace (A*adjoint A) \\<le> (trace A)\\<^sup>2\" by auto\n   then show ?thesis by auto\n qed\n\nlemma lowner_le_transitive:\n  fixes m n :: nat\n  assumes re: \"n \\<ge> m\"\n  shows \"positive (f n - f m)\"\nproof -\n  from re show \"positive (f n - f m)\"\n  proof (induct n)\n    case 0\n    then show ?case using positive_zero\n          by (metis dim le_0_eq minus_r_inv_mat)\n  next\n    case (Suc n)\n    then show ?case\n    proof (cases \"Suc n = m\")\n      case True\n      then show ?thesis using positive_zero\n          by (metis dim minus_r_inv_mat)\n    next\n      case False\n      then show ?thesis\n      proof -\n        from False Suc have nm: \"n  \\<ge> m\" by linarith\n        from Suc nm have pnm:  \"positive (f n - f m)\" by auto\n        from inc have \"positive (f (Suc n) - f n)\" unfolding lowner_le_def by auto\n        then have pf:  \"positive ((f (Suc n) - f n) + (f n - f m))\" using positive_add dim pnm\n          by (meson minus_carrier_mat)\n        have \"(f (Suc n) - f n) + (f n - f m) = f (Suc n) + ((- f n) + f n) + (- f m)\"\n          using local.dim by (mat_assoc dim, auto)\n        also have \"\\<dots> = f (Suc n) + 0\\<^sub>m dim dim + (- f m)\"\n          using local.dim by (subst uminus_l_inv_mat[where nc=dim and nr=dim], auto)\n        also have \"\\<dots> = f (Suc n) - f m\"\n          using local.dim by (mat_assoc dim, auto)\n        finally have re: \"f (Suc n) - f n + (f n - f m) = f (Suc n) - f m\" .\n        from pf re have \"positive (f (Suc n) - f m)\" by auto\n        then show ?thesis by auto\n      qed\n    qed\n  qed\nqed\n\ntext \\<open>The sequence of matrices converges pointwise.\\<close>\n\n\n  have eq_minus: \"\\<forall> m n. trace (f m) - trace (f n) = trace (f m - f n)\" using trace_minus_linear dim by metis\n  from eq_minus norm_trace have norm_trace_cauchy: \"\\<forall>e>0.\\<exists>M. \\<forall>m\\<ge>M. \\<forall>n\\<ge>M. norm((trace (f n - f m))) < e\" by auto\n  then have norm_trace_cauchy_iff: \"\\<forall>e>0.\\<exists>M. \\<forall>m\\<ge>M. \\<forall>n\\<ge>m. norm((trace (f n - f m))) < e\"\n    by (meson order_trans_rules(23))\n  then have norm_square: \"\\<forall>e>0.\\<exists>M. \\<forall>m\\<ge>M. \\<forall>n\\<ge>m. (norm((trace (f n - f m))))\\<^sup>2 < e\\<^sup>2\"\n    by (metis abs_of_nonneg norm_ge_zero order_less_le real_sqrt_abs real_sqrt_less_iff)\n\n  have tr_re: \"\\<forall> m. \\<forall> n \\<ge> m. trace ((f n - f m) * adjoint (f n - f m)) \\<le> ((trace (f n- f m)))\\<^sup>2\"\n    using trace_positive_eq lowner_le_transitive by auto\n  have tr_re_g: \"\\<forall> m. \\<forall> n \\<ge> m. trace ((f n - f m) * adjoint (f n - f m)) \\<ge> 0\"\n    using lowner_le_transitive positive_trace trace_adjoint_positive by auto\n  have norm_trace_fmn: \"norm(trace ((f n - f m) * adjoint (f n - f m))) \\<le> (norm(trace (f n - f m)))\\<^sup>2\" if nm: \"n \\<ge> m\" for m n\n  proof -\n    have mnA: \"trace ((f n - f m) * adjoint (f n - f m)) \\<le> (trace (f n - f m))\\<^sup>2\" using tr_re nm by auto\n    have mnB: \"trace ((f n - f m) * adjoint (f n - f m)) \\<ge> 0\" using tr_re_g nm by auto\n    from mnA mnB show ?thesis\n      by (smt cmod_eq_Re less_eq_complex_def norm_power zero_complex.sel(1) zero_complex.sel(2))\n  qed\n  then have cauchy_adj: \"\\<exists>M. \\<forall>m\\<ge>M. \\<forall>n\\<ge>m. norm(trace ((f n- f m) * adjoint (f n - f m))) < e\\<^sup>2\" if e: \"e > 0\" for e\n  proof -\n    have \"\\<exists>M. \\<forall>m\\<ge>M. \\<forall>n\\<ge>m. (cmod (trace (f n - f m)))\\<^sup>2 < e\\<^sup>2\" using norm_square e by auto\n    then obtain M where \" \\<forall>m\\<ge>M. \\<forall>n\\<ge>m. (cmod (trace (f n - f m)))\\<^sup>2 < e\\<^sup>2\" by auto\n    then have \"\\<forall>m\\<ge>M. \\<forall>n\\<ge>m. norm(trace ((f n- f m) * adjoint (f n - f m))) < e\\<^sup>2\" using norm_trace_fmn  by fastforce\n    then show ?thesis by auto\n  qed\n\n  have norm_minus: \"\\<forall> m. \\<forall> n \\<ge> m. (norm ((f n - f m) $$ (i, j)))\\<^sup>2 \\<le> trace ((f n - f m) * adjoint (f n - f m))\"\n    using trace_adjoint_element_ineq i j\n    by (smt adjoint_dim_row carrier_matD(1) index_minus_mat(2) index_mult_mat(2) lowner_le_transitive matrix_seq_axioms matrix_seq_def positive_is_normal)\n  then have norm_minus_le: \"(norm ((f n - f m) $$ (i, j)))\\<^sup>2 \\<le> norm (trace ((f n - f m) * adjoint (f n - f m)))\" if nm: \"n \\<ge> m\" for n m\n  proof -\n    have \"(norm ((f n - f m) $$ (i, j)))\\<^sup>2 \\<le> (trace ((f n - f m) * adjoint (f n - f m)))\" using norm_minus nm by auto\n    also have \"\\<dots> = norm (trace ((f n - f m) * adjoint (f n - f m)))\" using tr_re_g nm\n      by (smt Re_complex_of_real less_eq_complex_def matrix_seq.trace_adjoint_eq_u matrix_seq_axioms mult_cancel_left2 norm_one norm_scaleR of_real_def of_real_hom.hom_zero)\n    finally show ?thesis by auto\n  qed\n\n  from norm_minus_le cauchy_adj have cauchy_ij: \"\\<exists>M. \\<forall>m\\<ge>M. \\<forall>n\\<ge>m. (norm ((f n - f m) $$ (i, j)))\\<^sup>2  < e\\<^sup>2\" if e: \"e > 0\" for e\n  proof -\n    have \"\\<exists>M. \\<forall>m\\<ge>M. \\<forall>n\\<ge>m. norm(trace ((f n- f m) * adjoint (f n - f m))) < e\\<^sup>2\" using cauchy_adj e by auto\n    then obtain M where \" \\<forall>m\\<ge>M. \\<forall>n\\<ge>m. norm(trace ((f n - f m) * adjoint (f n - f m))) < e\\<^sup>2\" by auto\n    then have \"\\<forall>m\\<ge>M. \\<forall>n\\<ge>m. (norm ((f n - f m) $$ (i, j)))\\<^sup>2 < e\\<^sup>2\" using norm_minus_le by fastforce\n    then show ?thesis by auto\n  qed\n  then have cauchy_ij_norm: \"\\<exists>M. \\<forall>m\\<ge>M. \\<forall>n\\<ge>m. (norm ((f n - f m) $$ (i, j))) < e\" if e: \"e > 0\" for e\n  proof -\n    have \"\\<exists>M. \\<forall>m\\<ge>M. \\<forall>n\\<ge>m. (norm ((f n - f m) $$ (i, j)))\\<^sup>2 < e\\<^sup>2\" using cauchy_ij e by auto\n    then obtain M where mn: \"\\<forall>m\\<ge>M. \\<forall>n\\<ge>m. (norm ((f n - f m) $$ (i, j)))\\<^sup>2 < e\\<^sup>2\" by auto\n    have \"(norm ((f n - f m) $$ (i, j))) < e\" if m: \"m \\<ge> M\" and n: \"n \\<ge> m\" for m n :: nat\n    proof -\n      from m n mn have \"(norm ((f n- f m) $$ (i, j)))\\<^sup>2 < e\\<^sup>2\" by auto\n      then show ?thesis\n      using e power_less_imp_less_base by fastforce\n    qed\n    then show ?thesis by auto\n  qed\n\n  have cauchy_final: \"\\<exists>M. \\<forall>m\\<ge>M. \\<forall>n\\<ge>M. norm ((f m) $$ (i, j) - (f n) $$ (i, j)) < e\" if e: \"e > 0\" for e\n  proof -\n    obtain M where mnm: \"\\<forall>m\\<ge>M. \\<forall>n\\<ge>m. norm ((f n - f m) $$ (i, j)) < e\" using cauchy_ij_norm e by auto\n    have \"norm ((f m) $$ (i, j) - (f n) $$ (i, j)) < e\" if m: \"m \\<ge> M\" and n: \"n \\<ge> M\" for m n\n    proof (cases \"n \\<ge> m\")\n      case True\n      then show ?thesis\n      proof -\n        from mnm m True have \"norm ((f n) $$ (i, j) - (f m) $$ (i, j)) < e\"\n          by (metis atLeastLessThan_iff carrier_matD(1) carrier_matD(2) dim i index_minus_mat(1) j)\n        then have \"norm ((f m) $$ (i, j) - (f n) $$ (i, j)) < e\" by (simp add: norm_minus_commute)\n        then show ?thesis by auto\n      qed\n    next\n      case False\n      then show ?thesis\n      proof -\n        from False n mnm have norm: \"norm ((f m - f n) $$ (i, j)) < e\" by auto\n        have minus: \"(f m - f n) $$ (i, j)   =  f m  $$ (i, j) -f n $$ (i, j)\"\n          by (metis atLeastLessThan_iff carrier_matD(1) carrier_matD(2) dim i index_minus_mat(1) j)\n        also have \"\\<dots> = - (f n - f m) $$ (i, j)\" using dim\n          by (metis atLeastLessThan_iff carrier_matD(1) carrier_matD(2) i index_minus_mat(1) j minus_diff_eq)\n        finally have fmn: \"(f m - f n) $$ (i, j) = - (f n - f m) $$ (i, j)\" by auto\n        then have \"norm ((- (f n - f m)) $$ (i, j)) < e\" using norm\n          by (metis (no_types, lifting) atLeastLessThan_iff carrier_matD(1) carrier_matD(2) i\n              index_minus_mat(2) index_minus_mat(3) index_uminus_mat(1) j matrix_seq_axioms matrix_seq_def)\n        then have \"norm (((f n - f m)) $$ (i, j)) < e\" using fmn norm by auto\n        then have \"norm (f n $$ (i, j) - f m $$ (i, j)) < e\"\n          by (metis minus norm norm_minus_commute)\n        then have \"norm (f m $$ (i, j) - f n $$ (i, j)) < e\" by (simp add: norm_minus_commute)\n        then show ?thesis by auto\n      qed\n    qed\n    then show ?thesis by auto\n  qed\n\n  from cauchy_final have \"Cauchy (\\<lambda> n. f n $$ (i, j))\" by (simp add: Cauchy_def dist_norm)\n  then show ?thesis by (simp add: Cauchy_convergent_iff)\nqed\n\n\ndefinition mat_seq_minus ::  \"(nat \\<Rightarrow> complex mat) \\<Rightarrow> complex mat \\<Rightarrow> nat \\<Rightarrow> complex mat\" where\n  \"mat_seq_minus X A = (\\<lambda>n. X n - A)\"\n\ndefinition minus_mat_seq :: \"complex mat \\<Rightarrow> (nat \\<Rightarrow> complex mat) \\<Rightarrow> nat \\<Rightarrow> complex mat\" where\n  \"minus_mat_seq A X = (\\<lambda>n. A - X n)\"\n\nlemma pos_mat_lim_is_pos_aux:\n  fixes X :: \"nat \\<Rightarrow> complex mat\" and A :: \"complex mat\" and m :: nat\n  assumes limX: \"limit_mat X A m\" and posX: \"\\<exists>k. \\<forall>n\\<ge>k. positive (X n)\"\n  shows \"positive A\"\nproof -\n  from posX obtain k where posk: \"\\<forall> n\\<ge>k. positive (X n)\" by auto\n  let ?Y = \"\\<lambda>n. X (n + k)\"\n  have posY: \"\\<forall>n. positive (?Y n)\" using posk by auto\n\n  from limX have dimXA: \"\\<forall>n. X (n + k) \\<in> carrier_mat m m \\<and> A \\<in> carrier_mat m m\"\n    unfolding limit_mat_def by auto\n\n  have \"(\\<lambda>n. X (n + k) $$ (i, j)) \\<longlonglongrightarrow> A $$ (i, j)\" if i: \"i < m\" and j: \"j < m\" for i j\n  proof -\n    have \"(\\<lambda>n. X n $$ (i, j)) \\<longlonglongrightarrow> A $$ (i, j)\" using limX limit_mat_def i j by auto\n    then have limseqX: \"\\<forall>r>0. \\<exists>no. \\<forall>n\\<ge>no. dist (X n $$ (i, j)) (A $$ (i, j)) < r\" unfolding LIMSEQ_def by auto\n    then have \"\\<exists>no. \\<forall>n\\<ge>no. dist (X (n + k) $$ (i, j)) (A $$ (i, j)) < r\" if r: \"r > 0\" for r\n    proof -\n      obtain no where \"\\<forall>n\\<ge>no. dist (X n $$ (i, j)) (A $$ (i, j)) < r\" using limseqX r by auto\n      then have \"\\<forall>n\\<ge>no. dist (X (n + k) $$ (i, j)) (A $$ (i, j)) < r\" by auto\n      then show ?thesis by auto\n    qed\n    then show ?thesis unfolding LIMSEQ_def by auto\n  qed\n  then have limXA: \"limit_mat (\\<lambda>n. X (n + k)) A m\" unfolding limit_mat_def using dimXA by auto\n\n  from posY limXA have \"positive A\" using pos_mat_lim_is_pos[of ?Y A m] by auto\n  then show ?thesis by auto\nqed\n\n\n\nlemma mat_minus_limit:\n  fixes X :: \"nat \\<Rightarrow> complex mat\" and A :: \"complex mat\" and m :: nat and B :: \"complex mat\"\n  assumes dimA: \"A \\<in> carrier_mat m m\" and limX: \"limit_mat X A m\"\n  shows \"limit_mat (minus_mat_seq B X) (B - A) m\"\nproof-\n  have dimX : \"\\<forall>n. X n \\<in> carrier_mat m m\" using limX unfolding limit_mat_def by auto\n  then have dimXAB: \"\\<forall>n. B - X n \\<in> carrier_mat m m \\<and> B - A \\<in> carrier_mat m m\" using index_minus_mat dimA\n    by (simp add: minus_carrier_mat)\n\n  have \"(\\<lambda>n. (B - X n) $$ (i, j)) \\<longlonglongrightarrow> (B - A) $$ (i, j)\" if i: \"i < m\" and j: \"j < m\" for i j\n  proof -\n    from limX i j have \"(\\<lambda>n. (X n) $$ (i, j)) \\<longlonglongrightarrow> (A) $$ (i, j)\" unfolding limit_mat_def by auto\n    then have X: \"\\<forall>r>0. \\<exists>no. \\<forall>n\\<ge>no. dist (X n $$ (i, j)) (A $$ (i, j)) < r\" unfolding LIMSEQ_def by auto\n    then have XB: \"\\<exists>no. \\<forall>n\\<ge>no. dist ((B - X n) $$ (i, j)) ((B - A) $$ (i, j)) < r\" if r: \"r > 0\" for r\n    proof -\n      obtain no where \"\\<forall>n\\<ge>no. dist (X n $$ (i, j)) (A $$ (i, j)) < r\" using r X by auto\n      then have dist: \"\\<forall>n\\<ge>no. norm (X n $$ (i, j) - A $$ (i, j)) < r\" unfolding dist_norm by auto\n      then have \"norm ((B - X n) $$ (i, j) - (B - A) $$ (i, j)) < r\" if n: \"n \\<ge> no\" for n\n      proof -\n        have \"(B - X n) $$ (i, j) - (B - A) $$ (i, j) = - ((X n) $$ (i, j) -  A $$ (i, j))\"\n          using dimA i j\n          by (smt cancel_ab_semigroup_add_class.diff_right_commute cancel_comm_monoid_add_class.diff_cancel carrier_matD(1) carrier_matD(2) diff_add_cancel dimX index_minus_mat(1) minus_diff_eq)\n        then have \"norm ((B - X n) $$ (i, j) - (B - A) $$ (i, j)) = norm ((X n) $$ (i, j) -  A $$ (i, j))\"\n          by (metis norm_minus_cancel)\n        then show ?thesis using dist n by auto\n      qed\n      then show ?thesis using dist_norm by metis\n    qed\n    then show ?thesis unfolding LIMSEQ_def by auto\n  qed\n  then have \"limit_mat (minus_mat_seq B X) (B - A) m\"\n    unfolding limit_mat_def minus_mat_seq_def using dimXAB by auto\n  then show ?thesis by auto\nqed\n\nlemma lowner_lub_form:\n  \"lowner_is_lub (mat dim dim (\\<lambda> (i, j). (lim (\\<lambda> n. (f n) $$ (i, j)))))\"\nproof -\n  from inc_partial_density_operator_converge\n  have conf: \"\\<forall> i \\<in> {0 ..<dim}.  \\<forall> j \\<in> {0 ..<dim}. convergent (\\<lambda> n. f n $$ (i, j))\" by auto\n  let ?A = \"mat dim dim (\\<lambda> (i, j). (lim (\\<lambda> n. (f n) $$ (i, j))))\"\n  have dim_A: \"?A \\<in> carrier_mat dim dim\" by auto\n  have lim_A: \"(\\<lambda>n. f n $$ (i, j)) \\<longlonglongrightarrow> mat dim dim (\\<lambda>(i, j). lim (\\<lambda>n. f n $$ (i, j))) $$ (i, j)\"\n    if i: \"i < dim\" and j: \"j < dim\" for i j\n  proof -\n    from i j have ij: \"mat dim dim (\\<lambda>(i, j). lim (\\<lambda>n. f n $$ (i, j))) $$ (i, j) = lim (\\<lambda>n. f n $$ (i, j))\"\n      by (metis case_prod_conv index_mat(1))\n    have \"convergent (\\<lambda>n. f n $$ (i, j))\" using conf i j by auto\n    then have \"(\\<lambda>n. f n $$ (i, j))  \\<longlonglongrightarrow> lim (\\<lambda>n. f n $$ (i, j)) \" using convergent_LIMSEQ_iff by auto\n    then show ?thesis using ij by auto\n  qed\n\n  from dim dim_A lim_A have lim_mat_A: \"limit_mat f ?A dim\" unfolding limit_mat_def by auto\n\n  have is_ub: \"f n \\<le>\\<^sub>L ?A\" for n\n  proof -\n    have \"\\<forall> m \\<ge> n. positive (f m - f n)\" using lowner_le_transitive by auto\n    then have le: \"\\<forall> m \\<ge> n. f n \\<le>\\<^sub>L f m \" unfolding lowner_le_def using dim\n      by (metis carrier_matD(1) carrier_matD(2))\n    have dimn: \"f n \\<in> carrier_mat dim dim\" using dim by auto\n    then have limAf: \"limit_mat (mat_seq_minus f (f n)) (?A - f n) dim\" using minus_mat_limit lim_mat_A by auto\n\n    have \" \\<forall>m\\<ge>n. positive (f m - f n)\" using lowner_le_transitive by auto\n    then have \"\\<exists>k. \\<forall>m\\<ge>k. positive (f m - f n)\" by auto\n    then have posAf: \"\\<exists> k. \\<forall> m \\<ge> k. positive ((mat_seq_minus f (f n)) m)\" unfolding mat_seq_minus_def by auto\n\n    from limAf posAf have \"positive (?A - f n)\" using pos_mat_lim_is_pos_aux by auto\n    then have \"f n \\<le>\\<^sub>L mat dim dim (\\<lambda>(i, j). lim (\\<lambda>n. f n $$ (i, j)))\" unfolding lowner_le_def using dim by auto\n    then show ?thesis by auto\n  qed\n\n  have is_lub: \"?A \\<le>\\<^sub>L M'\" if ub: \"\\<forall>n. f n \\<le>\\<^sub>L M'\" for M'\n  proof -\n    have dim_M: \"M' \\<in> carrier_mat dim dim\" using ub unfolding lowner_le_def using dim\n      by (metis carrier_matD(1) carrier_matD(2) carrier_mat_triv)\n    from ub have posAf: \"\\<forall> n. positive (minus_mat_seq M' f n)\" unfolding minus_mat_seq_def lowner_le_def by auto\n    have limAf: \"limit_mat (minus_mat_seq M' f) (M' - ?A) dim\"\n      using mat_minus_limit dim_A lim_mat_A by auto\n    from posAf limAf have  \"positive (M' - ?A)\" using pos_mat_lim_is_pos_aux by auto\n    then have \"?A \\<le>\\<^sub>L M'\" unfolding lowner_le_def using dim dim_A dim_M by auto\n    then show ?thesis by auto\n  qed\n\n  from is_ub is_lub show ?thesis unfolding lowner_is_lub_def by auto\nqed\n\ntext \\<open>Lowner partial order is a complete partial order.\\<close>\nlemma lowner_lub_exists: \"\\<exists>M. lowner_is_lub M\"\n  using lowner_lub_form by auto\n\nlemma lowner_lub_unique: \"\\<exists>!M. lowner_is_lub M\"\nproof (rule HOL.ex_ex1I)\n  show \"\\<exists>M. lowner_is_lub M\"\n    by (rule lowner_lub_exists)\nnext\n  fix M N\n  assume M: \"lowner_is_lub M\" and N: \"lowner_is_lub N\"\n  have Md: \"M \\<in> carrier_mat dim dim\" using M by (rule lowner_is_lub_dim)\n  have Nd: \"N \\<in> carrier_mat dim dim\" using N by (rule lowner_is_lub_dim)\n  have MN: \"M \\<le>\\<^sub>L N\" using M N by (simp add: lowner_is_lub_def)\n  have NM: \"N \\<le>\\<^sub>L M\" using M N by (simp add: lowner_is_lub_def)\n  show \"M = N\" using MN NM by (auto intro: lowner_le_antisym[OF Md Nd])\nqed\n\ndefinition lowner_lub :: \"complex mat\" where\n  \"lowner_lub = (THE M. lowner_is_lub M)\"\n\nlemma lowner_lub_prop: \"lowner_is_lub lowner_lub\"\n  unfolding lowner_lub_def\n  apply (rule HOL.theI')\n  by (rule lowner_lub_unique)\n\nlemma lowner_lub_is_limit:\n  \"limit_mat f lowner_lub dim\"\nproof -\n  define A where \"A = lowner_lub\"\n  then have \"A = (THE M. lowner_is_lub M)\" using lowner_lub_def by auto\n  then have Af: \"A = (mat dim dim (\\<lambda> (i, j). (lim (\\<lambda> n.  (f n) $$ (i, j)))))\"\n    using lowner_lub_form lowner_lub_unique by auto\n  show \"limit_mat f A dim\" unfolding Af limit_mat_def\n    apply (auto simp add: dim)\n  proof -\n    fix i j assume dims: \"i < dim\" \"j < dim\"\n    then have \"convergent  (\\<lambda>n. f n $$ (i, j))\" using inc_partial_density_operator_converge by auto\n    then show \"(\\<lambda>n. f n $$ (i, j)) \\<longlonglongrightarrow> lim (\\<lambda>n. f n $$ (i, j))\" using convergent_LIMSEQ_iff by auto\n  qed\nqed\n\nlemma lowner_lub_trace:\n  assumes \"\\<forall> n. trace (f n) \\<le> x\"\n  shows \"trace lowner_lub \\<le> x\"\nproof -\n  have \"\\<forall> n. trace (f n) \\<ge> 0\" using positive_trace pdo unfolding partial_density_operator_def\n    using dim by blast\n  then have Re: \"\\<forall> n. Re (trace (f n)) \\<ge> 0 \\<and> Im (trace (f n)) = 0\" by auto\n  then have lex: \"\\<forall> n. Re (trace (f n)) \\<le> Re x \\<and> Im x = 0\" using assms by auto\n\n  have \"limit_mat f lowner_lub dim\"  using lowner_lub_is_limit by auto\n  then have conv: \"(\\<lambda>n. trace (f n)) \\<longlonglongrightarrow> trace lowner_lub\" using mat_trace_limit by auto\n  then have \"(\\<lambda>n. Re (trace (f n))) \\<longlonglongrightarrow> Re (trace lowner_lub)\"\n    by (simp add: tendsto_Re)\n  then have Rell: \"Re (trace lowner_lub) \\<le> Re x\"\n    using lex Lim_bounded[of \"(\\<lambda>n. Re (trace (f n)))\" \"Re (trace lowner_lub)\" 0 \"Re x\"] by simp\n\n  from conv have \"(\\<lambda>n. Im (trace (f n))) \\<longlonglongrightarrow> Im (trace lowner_lub)\"\n    by (simp add: tendsto_Im)\n  then  have Imll: \"Im (trace lowner_lub) = 0\" using Re\n    by (simp add: Lim_bounded Lim_bounded2 dual_order.antisym)\n\n  from Rell Imll lex show ?thesis by simp\nqed\n\nlemma lowner_lub_is_positive:\n  shows \"positive lowner_lub\"\n  using lowner_lub_is_limit pos_mat_lim_is_pos pdo unfolding partial_density_operator_def by auto\n\nend\n\nsubsection \\<open>Finite sum of matrices\\<close>\n\ntext \\<open>Add f in the interval [0, n)\\<close>\nfun matrix_sum :: \"nat \\<Rightarrow> (nat \\<Rightarrow> 'b::semiring_1 mat) \\<Rightarrow> nat \\<Rightarrow> 'b mat\" where\n  \"matrix_sum d f 0 = 0\\<^sub>m d d\"\n| \"matrix_sum d f (Suc n) = f n + matrix_sum d f n\"\n\ndefinition matrix_inf_sum :: \"nat \\<Rightarrow> (nat \\<Rightarrow> complex mat) \\<Rightarrow> complex mat\" where\n  \"matrix_inf_sum d f = matrix_seq.lowner_lub (\\<lambda>n. matrix_sum d f n)\"\n\nlemma matrix_sum_dim:\n  fixes f :: \"nat \\<Rightarrow> 'b::semiring_1 mat\"\n  shows \"(\\<And>k. k < n \\<Longrightarrow> f k \\<in> carrier_mat d d) \\<Longrightarrow> matrix_sum d f n \\<in> carrier_mat d d\"\nproof (induct n)\n  case 0\n  show ?case by auto\nnext\n  case (Suc n)\n  then have \"f n \\<in> carrier_mat d d\" by auto\n  then show ?case using Suc by auto\nqed\n\nlemma matrix_sum_cong:\n  fixes f :: \"nat \\<Rightarrow> 'b::semiring_1 mat\"\n  shows \"(\\<And>k. k < n \\<Longrightarrow> f k = f' k) \\<Longrightarrow> matrix_sum d f n = matrix_sum d f' n\"\nproof (induct n)\n  case 0\n  show ?case by auto\nnext\n  case (Suc n)\n  then show ?case unfolding matrix_sum.simps by auto\nqed\n\nlemma matrix_sum_add:\n  fixes f :: \"nat \\<Rightarrow> 'b::semiring_1 mat\" and  g :: \"nat \\<Rightarrow> 'b::semiring_1 mat\" and  h :: \"nat \\<Rightarrow> 'b::semiring_1 mat\"\n  shows \"(\\<And>k. k < n \\<Longrightarrow> f k \\<in> carrier_mat d d) \\<Longrightarrow> (\\<And>k. k < n \\<Longrightarrow> g k \\<in> carrier_mat d d) \\<Longrightarrow> (\\<And>k. k < n \\<Longrightarrow> h k \\<in> carrier_mat d d) \\<Longrightarrow>\n     (\\<And>k. k < n \\<Longrightarrow> f k = g k + h k) \\<Longrightarrow> matrix_sum d f n = matrix_sum d g n + matrix_sum d h n\"\nproof (induct n)\n  case 0\n  then show ?case by auto\nnext\n  case (Suc n)\n  then show ?case\n  proof -\n    have gh: \"matrix_sum d g n \\<in> carrier_mat d d \\<and> matrix_sum d h n \\<in> carrier_mat d d\"\n      using matrix_sum_dim Suc(3, 4) by (simp add: matrix_sum_dim)\n\n    have nSuc: \"n < Suc n\" by auto\n    have sumf: \"matrix_sum d f n = matrix_sum d g n + matrix_sum d h n\" using Suc by auto\n    have \"matrix_sum d f (Suc n) = matrix_sum d g (Suc n) + matrix_sum d h (Suc n)\"\n      unfolding matrix_sum.simps Suc(5)[OF nSuc] sumf\n      apply (mat_assoc d) using gh Suc by auto\n    then show ?thesis by auto\n  qed\nqed\n\nlemma matrix_sum_smult:\n  fixes f :: \"nat \\<Rightarrow> 'b::semiring_1 mat\"\n  shows \"(\\<And>k. k < n \\<Longrightarrow> f k \\<in> carrier_mat d d) \\<Longrightarrow>\n        matrix_sum d (\\<lambda> k. c \\<cdot>\\<^sub>m f k) n = c \\<cdot>\\<^sub>m matrix_sum d f n\"\nproof (induct n)\n  case 0\n  then show ?case by auto\nnext\n  case (Suc n)\n  then show ?case\n    apply auto\n    using add_smult_distrib_left_mat Suc matrix_sum_dim\n    by (metis lessI less_SucI)\nqed\n\nlemma matrix_sum_remove:\n  fixes f :: \"nat \\<Rightarrow> 'b::semiring_1 mat\"\n  assumes j: \"j < n\"\n    and df: \"(\\<And>k. k < n \\<Longrightarrow> f k \\<in> carrier_mat d d)\"\n    and f': \"(\\<And>k. f' k = (if k = j then 0\\<^sub>m d d else f k))\"\n  shows \"matrix_sum d f n = f j + matrix_sum d f' n\"\nproof -\n  have df': \"\\<And>k. k < n \\<Longrightarrow> f' k \\<in> carrier_mat d d\" using f' df by auto\n  have dsf: \"k < n \\<Longrightarrow> matrix_sum d f k \\<in> carrier_mat d d\" for k using matrix_sum_dim[OF df] by auto\n  have dsf': \"k < n \\<Longrightarrow> matrix_sum d f' k \\<in> carrier_mat d d\" for k using matrix_sum_dim[OF df'] by auto\n  have flj: \"\\<And>k. k < j \\<Longrightarrow> f' k = f k\" using j f' by auto\n  then have \"matrix_sum d f j = matrix_sum d f' j\" using matrix_sum_cong[of j f' f, OF flj] df df' j by auto\n  then have eqj: \"matrix_sum d f (Suc j) = f j + matrix_sum d f' (Suc j)\" unfolding matrix_sum.simps\n    by (subst (1) f', simp add: df dsf' j)\n  have lm: \"(j + 1) + l \\<le> n \\<Longrightarrow> matrix_sum d f ((j + 1) + l) = f j + matrix_sum d f' ((j + 1) + l)\" for l\n  proof (induct l)\n    case 0\n    show ?case using j eqj by auto\n  next\n    case (Suc l) then have eq: \"matrix_sum d f ((j + 1) + l) = f j + matrix_sum d f' ((j + 1) + l)\" by auto\n    have s: \"((j + 1) + Suc l) = Suc ((j + 1) + l)\" by simp\n    have eqf': \"f' (j + 1 + l) = f (j + 1 + l)\" using f' Suc by auto\n    have dims: \"f (j + 1 + l) \\<in> carrier_mat d d\" \"f j \\<in> carrier_mat d d\" \"matrix_sum d f' (j + 1 + l) \\<in> carrier_mat d d\" using df df' dsf' Suc by auto\n    show ?case apply (subst (1 2) s) unfolding matrix_sum.simps\n      apply (subst eq, subst eqf')\n      apply (mat_assoc d) using dims by auto\n  qed\n  have p: \"(j + 1) + (n - j - 1) \\<le> n\" using j by auto\n  show ?thesis using lm[OF p] j by auto\nqed\n\nlemma matrix_sum_Suc_remove_head:\n  fixes f :: \"nat \\<Rightarrow> complex mat\"\n  shows \"(\\<And>k. k < n + 1 \\<Longrightarrow> f k \\<in> carrier_mat d d) \\<Longrightarrow>\n    matrix_sum d f (n + 1) = f 0 + matrix_sum d (\\<lambda>k. f (k + 1)) n\"\nproof (induct n)\n  case 0\n  then show ?case by auto\nnext\n  case (Suc n)\n  then have dSS: \"\\<And>k. k < Suc (Suc n) \\<Longrightarrow> f k \\<in> carrier_mat d d\" by auto\n  have ds: \"matrix_sum d (\\<lambda>k. f (k + 1)) n \\<in> carrier_mat d d\" using matrix_sum_dim[OF dSS, of \"n\" \"\\<lambda>k. k + 1\"] by auto\n  have \"matrix_sum d f (Suc n + 1) = f (n + 1) + matrix_sum d f (n + 1)\" by auto\n  also have \"\\<dots> = f (n + 1) + (f 0 + matrix_sum d (\\<lambda>k. f (k + 1)) n)\" using Suc by auto\n  also have \"\\<dots> = f 0 + (f (n + 1) + matrix_sum d (\\<lambda>k. f (k + 1)) n)\"\n    using ds apply (mat_assoc d) using dSS by auto\n  finally show ?case by auto\nqed\n\nlemma matrix_sum_positive:\n  fixes f :: \"nat \\<Rightarrow> complex mat\"\n  shows \"(\\<And>k. k < n \\<Longrightarrow> f k \\<in> carrier_mat d d) \\<Longrightarrow> (\\<And>k. k < n \\<Longrightarrow> positive (f k))\n    \\<Longrightarrow> positive (matrix_sum d f n)\"\nproof (induct n)\n  case 0\n  show ?case using positive_zero by auto\nnext\n  case (Suc n)\n  then have dfn: \"f n \\<in> carrier_mat d d\" and psn: \"positive (matrix_sum d f n)\" and pn: \"positive (f n)\" and d: \"k < n \\<Longrightarrow> f k \\<in> carrier_mat d d\" for k by auto\n  then have dsn: \"matrix_sum d f n \\<in> carrier_mat d d\" using matrix_sum_dim by auto\n  show ?case unfolding matrix_sum.simps using positive_add[OF pn psn dfn dsn] by auto\nqed\n\nlemma matrix_sum_mult_right:\n  shows \"(\\<And>k. k < n \\<Longrightarrow> f k \\<in> carrier_mat d d) \\<Longrightarrow> A \\<in> carrier_mat d d\n    \\<Longrightarrow> matrix_sum d (\\<lambda>k. (f k) * A) n = matrix_sum d (\\<lambda>k. f k) n * A\"\nproof (induct n)\n  case 0\n  then show ?case by auto\nnext\n  case (Suc n)\n  then have \"k < n \\<Longrightarrow> f k \\<in> carrier_mat d d\" and dfn: \"f n \\<in> carrier_mat d d\" for k by auto\n  then have dsfn: \"matrix_sum d f n \\<in> carrier_mat d d\" using matrix_sum_dim by auto\n  have \"(f n + matrix_sum d f n) * A = f n * A + matrix_sum d f n * A\"\n    apply (mat_assoc d) using Suc dsfn by auto\n  also have \"\\<dots> = f n * A + matrix_sum d (\\<lambda>k. f k * A) n\" using Suc by auto\n  finally show ?case by auto\nqed\n\nlemma matrix_sum_add_distrib:\n  shows \"(\\<And>k. k < n \\<Longrightarrow> f k \\<in> carrier_mat d d) \\<Longrightarrow> (\\<And>k. k < n \\<Longrightarrow> g k \\<in> carrier_mat d d)\n    \\<Longrightarrow> matrix_sum d (\\<lambda>k. (f k) + (g k)) n = matrix_sum d f n + matrix_sum d g n\"\nproof (induct n)\n  case 0\n  then show ?case by auto\nnext\n  case (Suc n)\n  then have dfn: \"f n \\<in> carrier_mat d d\" and dgn: \"g n \\<in> carrier_mat d d\"\n    and dfk: \"k < n \\<Longrightarrow> f k \\<in> carrier_mat d d\" and dgk: \"k < n \\<Longrightarrow> g k \\<in> carrier_mat d d\"\n    and eq: \"matrix_sum d (\\<lambda>k. f k + g k) n = matrix_sum d f n + matrix_sum d g n\" for k by auto\n  have dsf: \"matrix_sum d f n \\<in> carrier_mat d d\" using matrix_sum_dim dfk by auto\n  have dsg: \"matrix_sum d g n \\<in> carrier_mat d d\" using matrix_sum_dim dgk by auto\n  show ?case unfolding matrix_sum.simps eq\n    using dfn dgn dsf dsg by (mat_assoc d)\nqed\n\nlemma matrix_sum_minus_distrib:\n  fixes f g :: \"nat \\<Rightarrow> complex mat\"\n  shows \"(\\<And>k. k < n \\<Longrightarrow> f k \\<in> carrier_mat d d) \\<Longrightarrow> (\\<And>k. k < n \\<Longrightarrow> g k \\<in> carrier_mat d d)\n    \\<Longrightarrow> matrix_sum d (\\<lambda>k. (f k) - (g k)) n = matrix_sum d f n - matrix_sum d g n\"\nproof -\n  have eq: \"-1 \\<cdot>\\<^sub>m g k = - g k\" for k by auto\n  assume dfk: \"\\<And>k. k < n \\<Longrightarrow> f k \\<in> carrier_mat d d\" and dgk: \"\\<And>k. k < n \\<Longrightarrow> (g k) \\<in> carrier_mat d d\"\n  then have \"k < n \\<Longrightarrow> (f k) - (g k) = (f k) + (- (g k))\" for k by auto\n  then have \"matrix_sum d (\\<lambda>k. (f k) - (g k)) n = matrix_sum d (\\<lambda>k. (f k) + (- (g k))) n\"\n    using matrix_sum_cong[of n \"\\<lambda>k. (f k) - (g k)\"] dfk dgk by auto\n  also have \"\\<dots> = matrix_sum d f n + matrix_sum d (\\<lambda>k. - (g k)) n\"\n    using matrix_sum_add_distrib[of n \"f\"] dfk dgk by auto\n  also have \"\\<dots> = matrix_sum d f n - matrix_sum d g n\"\n    apply (subgoal_tac \"matrix_sum d (\\<lambda>k. - (g k)) n = - matrix_sum d g n\", auto)\n    apply (subgoal_tac \"- 1 \\<cdot>\\<^sub>m matrix_sum d g n = - matrix_sum d g n\")\n    by (simp add: matrix_sum_smult[of n g d \"-1\", OF dgk, simplified eq, simplified], auto)\n  finally show ?thesis .\nqed\n\nlemma matrix_sum_shift_Suc:\n  shows \"(\\<And>k. k < (Suc n) \\<Longrightarrow> f k \\<in> carrier_mat d d)\n    \\<Longrightarrow> matrix_sum d f (Suc n) = f 0 + matrix_sum d (\\<lambda>k. f (Suc k)) n\"\nproof (induct n)\n  case 0\n  then show ?case by auto\nnext\n  case (Suc n)\n  have dfk: \"k < Suc (Suc n) \\<Longrightarrow> f k \\<in> carrier_mat d d\" for k using Suc by auto\n  have dsSk: \"k < Suc n \\<Longrightarrow> matrix_sum d (\\<lambda>k. f (Suc k)) n \\<in> carrier_mat d d\" for k using matrix_sum_dim[of _ \"\\<lambda>k. f (Suc k)\"] dfk by fastforce\n  have \"matrix_sum d f (Suc (Suc n)) = f (Suc n) + matrix_sum d f (Suc n)\" by auto\n  also have \"\\<dots> = f (Suc n) + f 0 + matrix_sum d (\\<lambda>k. f (Suc k)) n\" using Suc dsSk assoc_add_mat[of \"f (Suc n)\" d d \"f 0\"] by fastforce\n  also have \"\\<dots> = f 0 + (f (Suc n) + matrix_sum d (\\<lambda>k. f (Suc k)) n)\" apply (mat_assoc d) using dsSk dfk by auto\n  also have \"\\<dots> = f 0 + matrix_sum d (\\<lambda>k. f (Suc k)) (Suc n)\"  by auto\n  finally show ?case .\nqed\n\nlemma lowner_le_matrix_sum:\n  fixes f g :: \"nat \\<Rightarrow> complex mat\"\n  shows \"(\\<And>k. k < n \\<Longrightarrow> f k \\<in> carrier_mat d d) \\<Longrightarrow> (\\<And>k. k < n \\<Longrightarrow> g k \\<in> carrier_mat d d)\n    \\<Longrightarrow> (\\<And>k. k < n \\<Longrightarrow> f k \\<le>\\<^sub>L g k)\n    \\<Longrightarrow> matrix_sum d f n \\<le>\\<^sub>L matrix_sum d g n\"\nproof (induct n)\n  case 0\n  show ?case unfolding matrix_sum.simps using lowner_le_refl[of \"0\\<^sub>m d d\" d] by auto\nnext\n  case (Suc n)\n  then have dfn: \"f n \\<in> carrier_mat d d\" and dgn: \"g n \\<in> carrier_mat d d\" and le1: \"f n \\<le>\\<^sub>L g n\" by auto\n  then have le2: \"matrix_sum d f n \\<le>\\<^sub>L matrix_sum d g n\" using Suc by auto\n  have \"k < n \\<Longrightarrow> f k \\<in> carrier_mat d d\" for k using Suc by auto\n  then have dsf: \"matrix_sum d f n \\<in> carrier_mat d d\" using matrix_sum_dim by auto\n  have \"k < n \\<Longrightarrow> g k \\<in> carrier_mat d d\" for k using Suc by auto\n  then have dsg: \"matrix_sum d g n \\<in> carrier_mat d d\" using matrix_sum_dim by auto\n  show ?case unfolding matrix_sum.simps using lowner_le_add dfn dsf dgn dsg le1 le2 by auto\nqed\n\nlemma lowner_lub_add:\n  assumes \"matrix_seq d f\" \"matrix_seq d g\" \"\\<forall> n. trace (f n + g n) \\<le> 1\"\n  shows \"matrix_seq.lowner_lub (\\<lambda>n. f n + g n) = matrix_seq.lowner_lub f + matrix_seq.lowner_lub g\"\nproof -\n  have msf: \"matrix_seq.lowner_is_lub f (matrix_seq.lowner_lub f)\" using assms(1) matrix_seq.lowner_lub_prop by auto\n  then have \"limit_mat f (matrix_seq.lowner_lub f) d\" using matrix_seq.lowner_lub_is_limit assms by auto\n  then have lim1: \"\\<forall>i<d. \\<forall>j<d. (\\<lambda>n. f n $$ (i, j)) \\<longlonglongrightarrow> (matrix_seq.lowner_lub f) $$ (i, j)\" using limit_mat_def assms by auto\n\n  have msg: \"matrix_seq.lowner_is_lub g (matrix_seq.lowner_lub g)\" using assms(2) matrix_seq.lowner_lub_prop by auto\n  then have \"limit_mat g (matrix_seq.lowner_lub g) d\" using matrix_seq.lowner_lub_is_limit assms by auto\n  then have lim2: \"\\<forall>i<d. \\<forall>j<d. (\\<lambda>n. g n $$ (i, j)) \\<longlonglongrightarrow> (matrix_seq.lowner_lub g) $$ (i, j)\" using limit_mat_def assms by auto\n\n  have \"\\<forall>n. f n + g n \\<in> carrier_mat d d\" using assms unfolding matrix_seq_def by fastforce\n  moreover have \"\\<forall>n. partial_density_operator (f n + g n)\" using assms\n    unfolding matrix_seq_def partial_density_operator_def using positive_add by blast\n  moreover have \"(f n + g n) \\<le>\\<^sub>L (f (Suc n) + g (Suc n))\" for n\n    using assms\n    unfolding matrix_seq_def using lowner_le_add[of \"f n\" d  \"f (Suc n)\" \"g n\" \"g (Suc n)\"] by auto\n  ultimately have msfg: \"matrix_seq d (\\<lambda>n. f n + g n)\" using assms unfolding matrix_seq_def by auto\n  then have mslfg: \"matrix_seq.lowner_is_lub (\\<lambda>n. f n + g n) (matrix_seq.lowner_lub (\\<lambda>n. f n + g n))\"\n    using matrix_seq.lowner_lub_prop by auto\n  then have \"limit_mat (\\<lambda>n. f n + g n) (matrix_seq.lowner_lub (\\<lambda>n. f n + g n)) d\" using matrix_seq.lowner_lub_is_limit msfg by auto\n  then have lim3: \"\\<forall>i<d. \\<forall>j<d. (\\<lambda>n. (f n + g n) $$ (i, j)) \\<longlonglongrightarrow> (matrix_seq.lowner_lub (\\<lambda>n. f n + g n)) $$ (i, j)\" using limit_mat_def assms by auto\n\n  have \"\\<forall> i<d. \\<forall> j<d. \\<forall> n. (f n + g n) $$ (i, j) = f n $$ (i, j) + g n $$ (i, j)\" using assms unfolding matrix_seq_def\n    by (metis carrier_matD(1) carrier_matD(2) index_add_mat(1))\n  then have add: \"\\<forall>i<d. \\<forall>j<d. (\\<lambda>n. f n $$ (i, j) + g n $$ (i, j)) \\<longlonglongrightarrow> (matrix_seq.lowner_lub (\\<lambda>n. f n + g n)) $$ (i, j)\" using lim3 by auto\n  have \"matrix_seq.lowner_lub f $$ (i, j) + matrix_seq.lowner_lub g $$ (i, j) = matrix_seq.lowner_lub (\\<lambda>n. f n + g n) $$ (i, j)\"\n    if i: \"i < d\" and j: \"j < d\" for i j\n  proof -\n    have \"(\\<lambda>n. f n $$ (i, j)) \\<longlonglongrightarrow> matrix_seq.lowner_lub f $$ (i, j)\" using lim1 i j by auto\n    moreover have \"(\\<lambda>n. g n $$ (i, j)) \\<longlonglongrightarrow> matrix_seq.lowner_lub g $$ (i, j)\" using lim2 i j by auto\n    ultimately have \"(\\<lambda>n. f n $$ (i, j) + g n $$ (i, j)) \\<longlonglongrightarrow> matrix_seq.lowner_lub f $$ (i, j) + matrix_seq.lowner_lub g $$ (i, j)\"\n      using tendsto_add[of \"\\<lambda>n. f n $$ (i, j)\" \"matrix_seq.lowner_lub f $$ (i, j)\" sequentially \"\\<lambda>n. g n $$ (i, j)\" \"matrix_seq.lowner_lub g $$ (i, j)\"] by auto\n    moreover have \"(\\<lambda>n. f n $$ (i, j) + g n $$ (i, j)) \\<longlonglongrightarrow> matrix_seq.lowner_lub (\\<lambda>n. f n + g n) $$ (i, j)\"  using add i j by auto\n    ultimately show ?thesis using LIMSEQ_unique by auto\n  qed\n  moreover have \"matrix_seq.lowner_lub f \\<in> carrier_mat d d\" using matrix_seq.lowner_is_lub_dim assms(1) msf unfolding matrix_seq_def by auto\n  moreover have \"matrix_seq.lowner_lub g \\<in> carrier_mat d d\" using matrix_seq.lowner_is_lub_dim assms(2) msg unfolding matrix_seq_def by auto\n  moreover have \"matrix_seq.lowner_lub (\\<lambda>n. f n + g n) \\<in> carrier_mat d d\" using matrix_seq.lowner_is_lub_dim  msfg mslfg unfolding matrix_seq_def by auto\n  ultimately show ?thesis  unfolding matrix_seq_def using mat_eq_iff by auto\nqed\n\nlemma lowner_lub_scale:\n  fixes c :: real\n  assumes \"matrix_seq d f\"  \"\\<forall> n. trace (c \\<cdot>\\<^sub>m f n) \\<le> 1\"  \"c\\<ge>0\"\n  shows \"matrix_seq.lowner_lub (\\<lambda>n. c \\<cdot>\\<^sub>m f n) = c \\<cdot>\\<^sub>m matrix_seq.lowner_lub f\"\nproof -\n  have msf: \"matrix_seq.lowner_is_lub f (matrix_seq.lowner_lub f)\"\n    using assms(1) matrix_seq.lowner_lub_prop by auto\n  then have \"limit_mat f (matrix_seq.lowner_lub f) d\"\n    using matrix_seq.lowner_lub_is_limit assms by auto\n  then have lim1: \"\\<forall>i<d. \\<forall>j<d. (\\<lambda>n. f n $$ (i, j)) \\<longlonglongrightarrow> (matrix_seq.lowner_lub f) $$ (i, j)\"\n    using limit_mat_def assms by auto\n\n  have dimcf: \"\\<forall>n. c \\<cdot>\\<^sub>m f n \\<in> carrier_mat d d\" using assms unfolding matrix_seq_def by fastforce\n  moreover have \"\\<forall>n. partial_density_operator (c \\<cdot>\\<^sub>m f n)\" using assms\n    unfolding matrix_seq_def partial_density_operator_def using positive_scale by blast\n  moreover have \"\\<forall>n.  c \\<cdot>\\<^sub>m f n \\<le>\\<^sub>L  c \\<cdot>\\<^sub>m f (Suc n)\" using lowner_le_smult assms(1,3)\n    unfolding matrix_seq_def partial_density_operator_def by blast\n  ultimately have mscf: \"matrix_seq d (\\<lambda>n. c \\<cdot>\\<^sub>m f n)\"  unfolding matrix_seq_def by auto\n  then have mslfg: \"matrix_seq.lowner_is_lub (\\<lambda>n. c \\<cdot>\\<^sub>m f n) (matrix_seq.lowner_lub (\\<lambda>n. c \\<cdot>\\<^sub>m f n))\"\n    using matrix_seq.lowner_lub_prop by auto\n  then have \"limit_mat (\\<lambda>n. c \\<cdot>\\<^sub>m f n) (matrix_seq.lowner_lub (\\<lambda>n. c \\<cdot>\\<^sub>m f n)) d\"\n    using matrix_seq.lowner_lub_is_limit mscf by auto\n  then have lim3: \"\\<forall>i<d. \\<forall>j<d. (\\<lambda>n. (c \\<cdot>\\<^sub>m f n) $$ (i, j)) \\<longlonglongrightarrow> (matrix_seq.lowner_lub (\\<lambda>n. c \\<cdot>\\<^sub>m f n)) $$ (i, j)\"\n    using limit_mat_def assms by auto\n\n  from mslfg mscf have dleft: \"matrix_seq.lowner_lub (\\<lambda>n. c \\<cdot>\\<^sub>m f n) \\<in> carrier_mat d d\"\n    using matrix_seq.lowner_is_lub_dim by auto\n  have dllf: \"matrix_seq.lowner_lub f \\<in> carrier_mat d d\"\n    using matrix_seq.lowner_is_lub_dim assms(1) msf unfolding matrix_seq_def by auto\n  then  have dright: \"c \\<cdot>\\<^sub>m matrix_seq.lowner_lub f \\<in> carrier_mat d d\" using index_smult_mat(2,3) by auto\n  have \"\\<forall> i<d. \\<forall> j<d. \\<forall> n. (c \\<cdot>\\<^sub>m f n) $$ (i, j) = c * f n $$ (i, j)\"\n    using assms(1) unfolding matrix_seq_def using index_smult_mat(1)\n    by (metis carrier_matD(1-2))\n  then have smult: \"\\<forall>i<d. \\<forall>j<d. (\\<lambda>n.  c * f n $$ (i, j)) \\<longlonglongrightarrow> (matrix_seq.lowner_lub (\\<lambda>n. c \\<cdot>\\<^sub>m f n)) $$ (i, j)\"\n    using lim3 by auto\n  have ij: \"(c \\<cdot>\\<^sub>m matrix_seq.lowner_lub f) $$ (i, j) = (matrix_seq.lowner_lub (\\<lambda>n. c \\<cdot>\\<^sub>m f n)) $$ (i, j)\"\n    if i: \"i < d\" and j: \"j < d\" for i j\n  proof -\n    have \"(\\<lambda>n. f n $$ (i, j)) \\<longlonglongrightarrow> matrix_seq.lowner_lub f $$ (i, j)\" using lim1 i j by auto\n    moreover have \"\\<forall>i<d. \\<forall>j<d.(c \\<cdot>\\<^sub>m matrix_seq.lowner_lub f) $$ (i, j) =  c *  matrix_seq.lowner_lub f $$ (i, j)\"\n      using index_smult_mat dllf by fastforce\n    ultimately have \"\\<forall>i<d. \\<forall>j<d. (\\<lambda>n.  c * f n $$ (i, j)) \\<longlonglongrightarrow>(c \\<cdot>\\<^sub>m matrix_seq.lowner_lub f) $$ (i, j)\"\n      using tendsto_intros(18)[of \"\\<lambda>n. c\" \"c\" sequentially \"\\<lambda>n. f n $$ (i, j)\" \"matrix_seq.lowner_lub f $$ (i, j)\"] i j\n      by (simp add: lim1 tendsto_mult_left)\n    then show ?thesis using smult i j LIMSEQ_unique by metis\n  qed\n\n  from dleft dright ij show ?thesis\n    using mat_eq_iff[of \"matrix_seq.lowner_lub  (\\<lambda>n. c \\<cdot>\\<^sub>m f n)\" \"c \\<cdot>\\<^sub>m matrix_seq.lowner_lub f\"]\n    by (metis (mono_tags) carrier_matD(1) carrier_matD(2))\nqed\n\nlemma trace_matrix_sum_linear:\n  fixes f :: \"nat \\<Rightarrow> complex mat\"\n  shows \"(\\<And>k. k < n \\<Longrightarrow> f k \\<in> carrier_mat d d) \\<Longrightarrow> trace (matrix_sum d f n) = sum (\\<lambda>k. trace (f k)) {0..<n}\"\nproof (induct n)\n  case 0\n  show ?case by auto\nnext\n  case (Suc n)\n  then have \"\\<And>k. k < n \\<Longrightarrow> f k \\<in> carrier_mat d d\" by auto\n  then have ds: \"matrix_sum d f n \\<in> carrier_mat d d\" using matrix_sum_dim by auto\n  have \"trace (matrix_sum d f (Suc n)) = trace (f n) + trace (matrix_sum d f n)\"\n    unfolding matrix_sum.simps apply (mat_assoc d) using ds Suc by auto\n  also have \"\\<dots> = sum (trace \\<circ> f) {0..<n} + (trace \\<circ> f) n\" using Suc by auto\n  also have \"\\<dots> = sum (trace \\<circ> f) {0..<Suc n}\" by auto\n  finally show ?case by auto\nqed\n\nlemma matrix_sum_distrib_left:\n  fixes f :: \"nat \\<Rightarrow> complex mat\"\n  shows \"P \\<in> carrier_mat d d \\<Longrightarrow> (\\<And>k. k < n \\<Longrightarrow> f k \\<in> carrier_mat d d) \\<Longrightarrow> matrix_sum d (\\<lambda>k. P * (f k)) n = P * (matrix_sum d f n)\"\nproof (induct n)\n  case 0\n  show ?case unfolding matrix_sum.simps using 0 by auto\nnext\n  case (Suc n)\n  then have \"\\<And>k. k < n \\<Longrightarrow> f k \\<in> carrier_mat d d\" by auto\n  then have ds: \"matrix_sum d f n \\<in> carrier_mat d d\" using matrix_sum_dim by auto\n  then have dPf: \"\\<And>k. k < n \\<Longrightarrow> P * f k \\<in> carrier_mat d d\" using Suc by auto\n  then have \"matrix_sum d (\\<lambda>k. P * f k) n \\<in> carrier_mat d d\" using matrix_sum_dim[OF dPf] by auto\n  have \"matrix_sum d (\\<lambda>k. P * f k) (Suc n) = P * f n + matrix_sum d (\\<lambda>k. P * f k) n \" unfolding matrix_sum.simps using Suc(2) by auto\n  also have \"\\<dots> = P * f n + P * matrix_sum d f n\" using Suc by auto\n  also have \"\\<dots> = P * (f n + matrix_sum d f n)\" apply (mat_assoc d) using ds dPf Suc by auto\n  finally show \"matrix_sum d (\\<lambda>k. P * f k) (Suc n) = P * (matrix_sum d f (Suc n))\" by auto\nqed\n\nsubsection \\<open>Measurement\\<close>\n\ndefinition measurement :: \"nat \\<Rightarrow> nat \\<Rightarrow> (nat \\<Rightarrow> complex mat) \\<Rightarrow> bool\" where\n  \"measurement d n M \\<longleftrightarrow> (\\<forall>j < n. M j \\<in> carrier_mat d d)\n                        \\<and> matrix_sum d (\\<lambda>j. (adjoint (M j)) * M j) n = 1\\<^sub>m d\"\n\nlemma measurement_dim:\n  assumes \"measurement d n M\"\n  shows \"\\<And>k. k < n \\<Longrightarrow> (M k) \\<in> carrier_mat d d\"\n  using assms unfolding measurement_def by auto\n\nlemma measurement_id2:\n  assumes \"measurement d 2 M\"\n  shows \"adjoint (M 0) * M 0 + adjoint (M 1) * M 1 = 1\\<^sub>m d\"\nproof -\n  have ssz: \"(Suc (Suc 0)) = 2\" by auto\n  have \"M 0 \\<in> carrier_mat d d\" \"M 1 \\<in> carrier_mat d d\" using assms measurement_def by auto\n  then have \"adjoint (M 0) * M 0 + adjoint (M 1) * M 1 = matrix_sum d (\\<lambda>j. (adjoint (M j)) * M j) (Suc (Suc 0)) \"\n    by auto\n  also have \"\\<dots> = matrix_sum d (\\<lambda>j. (adjoint (M j)) * M j) (2::nat)\" by (subst ssz, auto)\n  also have \"\\<dots> = 1\\<^sub>m d\" using measurement_def[of d 2 M] assms by auto\n  finally show ?thesis by auto\nqed\n\ntext \\<open>Result of measurement on $\\rho$ by matrix M\\<close>\ndefinition measurement_res :: \"complex mat \\<Rightarrow> complex mat \\<Rightarrow> complex mat\" where\n  \"measurement_res M \\<rho> = M * \\<rho> * adjoint M\"\n\nlemma add_positive_le_reduce1:\n  assumes dA: \"A \\<in> carrier_mat n n\" and dB: \"B \\<in> carrier_mat n n\" and dC: \"C \\<in> carrier_mat n n\"\n    and pB: \"positive B\" and le: \"A + B \\<le>\\<^sub>L C\"\n  shows \"A \\<le>\\<^sub>L C\"\n  unfolding lowner_le_def positive_def\nproof (auto simp add: carrier_matD[OF dA] carrier_matD[OF dC] simp del: less_eq_complex_def)\n  have eq: \"C - (A + B) = (C - A + (-B))\" using dA dB dC by auto\n  have \"positive (C - (A + B))\" using le lowner_le_def dA dB dC by auto\n  with eq have p: \"positive (C - A + (-B))\" by auto\n  fix v :: \"complex vec\" assume \" n = dim_vec v\"\n  then have dv: \"v \\<in> carrier_vec n\" by auto\n  have ge: \"inner_prod v (B *\\<^sub>v v) \\<ge> 0\" using pB dv dB positive_def by auto\n  have \"0 \\<le> inner_prod v ((C - A + (-B)) *\\<^sub>v v) \" using p positive_def dv dA dB dC by auto\n  also have \"\\<dots> = inner_prod v ((C - A)*\\<^sub>v v + (-B) *\\<^sub>v v) \"\n    using dv dA dB dC add_mult_distrib_mat_vec[OF minus_carrier_mat[OF dA]] by auto\n  also have \"\\<dots> = inner_prod v ((C - A) *\\<^sub>v v) + inner_prod v ((-B) *\\<^sub>v v)\"\n    apply (subst inner_prod_distrib_right)\n    by (rule dv, auto simp add: mult_mat_vec_carrier[OF minus_carrier_mat[OF dA]] mult_mat_vec_carrier[OF uminus_carrier_mat[OF dB]] dv)\n  also have \"\\<dots> = inner_prod v ((C - A) *\\<^sub>v v) - inner_prod v (B *\\<^sub>v v)\" using dB dv by auto\n  also have \"\\<dots> \\<le> inner_prod v ((C - A) *\\<^sub>v v)\" using ge by auto\n  finally show \"0 \\<le> inner_prod v ((C - A) *\\<^sub>v v)\".\nqed\n\nlemma add_positive_le_reduce2:\n  assumes dA: \"A \\<in> carrier_mat n n\" and dB: \"B \\<in> carrier_mat n n\" and dC: \"C \\<in> carrier_mat n n\"\n    and pB: \"positive B\" and le: \"B + A \\<le>\\<^sub>L C\"\n  shows \"A \\<le>\\<^sub>L C\"\n  apply (subgoal_tac \"B + A = A + B\") using add_positive_le_reduce1[of A n B C] assms by auto\n\nlemma measurement_le_one_mat:\n  assumes \"measurement d n f\"\n  shows \"\\<And>j. j < n \\<Longrightarrow> adjoint (f j) * f j \\<le>\\<^sub>L 1\\<^sub>m d\"\nproof -\n  fix j assume j: \"j < n\"\n  define M where \"M = adjoint (f j) * f j\"\n  have df: \"k < n \\<Longrightarrow> f k \\<in> carrier_mat d d\" for k using assms measurement_dim by auto\n  have daf: \"k < n \\<Longrightarrow> adjoint (f k) * f k \\<in> carrier_mat d d\" for k\n  proof -\n    assume \"k < n\"\n    then have \"f k \\<in> carrier_mat d d\" \"adjoint (f k) \\<in> carrier_mat d d\" using df adjoint_dim by auto\n    then show \"adjoint (f k) * f k \\<in> carrier_mat d d\" by auto\n  qed\n  have pafj: \"k < n \\<Longrightarrow> positive (adjoint (f k) * (f k)) \"  for k\n    apply (subst (2) adjoint_adjoint[of \"f k\", symmetric])\n    by (metis adjoint_adjoint daf positive_if_decomp)\n  define f' where \"\\<And>k. f' k = (if k = j then 0\\<^sub>m d d else adjoint (f k) * f k)\"\n  have pf': \"k < n \\<Longrightarrow> positive (f' k)\" for k unfolding f'_def using positive_zero pafj j by auto\n  have df': \"k < n \\<Longrightarrow> f' k \\<in> carrier_mat d d\" for k using daf j zero_carrier_mat f'_def by auto\n  then have dsf': \"matrix_sum d f' n \\<in> carrier_mat d d\" using matrix_sum_dim[of n f' d] by auto\n  have psf': \"positive (matrix_sum d f' n)\" using matrix_sum_positive pafj df' pf' by auto\n  have \"M + matrix_sum d f' n = matrix_sum d (\\<lambda>k. adjoint (f k) * f k) n\"\n    using matrix_sum_remove[OF j , of \"(\\<lambda>k. adjoint (f k) * f k)\", OF daf, of f'] f'_def unfolding M_def by auto\n  also have \"\\<dots> = 1\\<^sub>m d\" using measurement_def assms by auto\n  finally have \"M + matrix_sum d f' n = 1\\<^sub>m d\".\n  moreover have \"1\\<^sub>m d \\<le>\\<^sub>L 1\\<^sub>m d\" using lowner_le_refl[of _ d] by auto\n  ultimately have \"(M + matrix_sum d f' n) \\<le>\\<^sub>L 1\\<^sub>m d\" by auto\n  then show \"M \\<le>\\<^sub>L 1\\<^sub>m d\" unfolding M_def using add_positive_le_reduce1[OF _ dsf' one_carrier_mat psf'] daf j by auto\nqed\n\nlemma pdo_close_under_measurement:\n  fixes M \\<rho> :: \"complex mat\"\n  assumes dM: \"M \\<in> carrier_mat n n\" and dr: \"\\<rho> \\<in> carrier_mat n n\"\n    and pdor: \"partial_density_operator \\<rho>\"\n    and le: \"adjoint M * M \\<le>\\<^sub>L 1\\<^sub>m n\"\n  shows \"partial_density_operator (M * \\<rho> * adjoint M)\"\n  unfolding partial_density_operator_def\nproof\n  show \"positive (M * \\<rho> * adjoint M)\"\n    using positive_close_under_left_right_mult_adjoint[OF dM dr] pdor partial_density_operator_def by auto\nnext\n  have daM: \"adjoint M \\<in> carrier_mat n n\" using dM by auto\n  then have daMM: \"adjoint M * M \\<in> carrier_mat n n\" using dM by auto\n  have \"trace (M * \\<rho> * adjoint M) = trace (adjoint M * M * \\<rho>)\"\n    using dM dr by (mat_assoc n)\n  also have \"\\<dots> \\<le> trace (1\\<^sub>m n * \\<rho>)\"\n    using lowner_le_trace[where ?B = \"1\\<^sub>m n\" and ?A = \"adjoint M * M\", OF daMM one_carrier_mat] le dr pdor by auto\n  also have \"\\<dots> = trace \\<rho>\" using dr by auto\n  also have \"\\<dots> \\<le> 1\" using pdor partial_density_operator_def by auto\n  finally show \"trace (M * \\<rho> * adjoint M) \\<le> 1\" by auto\nqed\n\nlemma trace_measurement:\n  assumes m: \"measurement d n M\" and dA: \"A \\<in> carrier_mat d d\"\n  shows \"trace (matrix_sum d (\\<lambda>k. (M k) * A * adjoint (M k)) n) = trace A\"\nproof -\n  have dMk: \"k < n \\<Longrightarrow> (M k) \\<in> carrier_mat d d\" for k using m unfolding measurement_def by auto\n  then have daMk: \"k < n \\<Longrightarrow> adjoint (M k) \\<in> carrier_mat d d\" for k using m adjoint_dim unfolding measurement_def by auto\n  have d1: \"k < n \\<Longrightarrow> M k * A * adjoint (M k) \\<in> carrier_mat d d\"for k using dMk daMk dA by fastforce\n  then have ds1: \"k < n \\<Longrightarrow> matrix_sum d (\\<lambda>k. M k * A * adjoint (M k)) k \\<in> carrier_mat d d\" for k\n    using matrix_sum_dim[of k \"\\<lambda>k. M k * A * adjoint (M k)\" d] by auto\n  have d2: \"k < n \\<Longrightarrow> adjoint (M k) *M k * A  \\<in> carrier_mat d d\" for k using daMk dMk dA by fastforce\n  then have ds2: \"k < n \\<Longrightarrow> matrix_sum d (\\<lambda>k. adjoint (M k) *M k * A) k \\<in> carrier_mat d d\" for k\n    using matrix_sum_dim[of k \"\\<lambda>k. adjoint (M k) *M k * A\" d] by auto\n  have daMMk: \"k < n \\<Longrightarrow> adjoint (M k) * M k \\<in> carrier_mat d d\" for k using dMk by fastforce\n  have \"k \\<le> n \\<Longrightarrow> trace (matrix_sum d (\\<lambda>k. (M k) * A * adjoint (M k)) k) = trace (matrix_sum d (\\<lambda>k. adjoint (M k) * (M k) * A) k)\" for k\n  proof (induct k)\n    case 0\n    then show ?case by auto\n  next\n    case (Suc k)\n    then have k: \"k < n\" by auto\n    have \"trace (M k * A * adjoint (M k)) = trace (adjoint (M k) * M k * A)\"\n      using dA apply (mat_assoc d) using dMk k by auto\n    then show ?case unfolding matrix_sum.simps using ds1 ds2 d1 d2 k Suc daMk dMk dA\n      by (subst trace_add_linear[of _ d], auto)+\n  qed\n  then have \"trace (matrix_sum d (\\<lambda>k. (M k) * A * adjoint (M k)) n) = trace (matrix_sum d (\\<lambda>k. adjoint (M k) * (M k) * A) n)\" by auto\n  also have \"\\<dots> = trace (matrix_sum d (\\<lambda>k. adjoint (M k) * (M k)) n * A)\" using matrix_sum_mult_right[OF daMMk, of n id A] dA by auto\n  also have \"\\<dots> = trace A\" using m dA unfolding measurement_def by auto\n  finally show ?thesis by auto\nqed\n\nlemma mat_inc_seq_positive_transform:\n  assumes dfn: \"\\<And>n. f n \\<in> carrier_mat d d\"\n    and inc: \"\\<And>n. f n \\<le>\\<^sub>L f (Suc n)\"\n  shows \"\\<And>n. f n - f 0 \\<in> carrier_mat d d\" and \"\\<And>n. (f n - f 0) \\<le>\\<^sub>L (f (Suc n) - f 0)\"\nproof -\n  show \"\\<And>n. f n - f 0 \\<in> carrier_mat d d\" using dfn by fastforce\n  have \"f 0 \\<le>\\<^sub>L f 0\" using lowner_le_refl[of \"f 0\" d] dfn by auto\n  then show \"(f n - f 0) \\<le>\\<^sub>L (f (Suc n) - f 0)\" for n\n    using lowner_le_minus[of \"f n\" d \"f (Suc n)\" \"f 0\" \"f 0\"] dfn inc by fastforce\nqed\n\nlemma mat_inc_seq_lub:\n  assumes dfn: \"\\<And>n. f n \\<in> carrier_mat d d\"\n    and inc: \"\\<And>n. f n \\<le>\\<^sub>L f (Suc n)\"\n    and ub: \"\\<And>n. f n \\<le>\\<^sub>L A\"\n  shows \"\\<exists>B. lowner_is_lub f B \\<and> limit_mat f B d\"\nproof -\n  have dmfn0: \"\\<And>n. f n - f 0 \\<in> carrier_mat d d\" and incm0: \"\\<And>n. (f n - f 0) \\<le>\\<^sub>L (f (Suc n) - f 0)\"\n    using mat_inc_seq_positive_transform[OF dfn, of id] assms by auto\n  define c where \"c = 1 / (trace (A - f 0) + 1)\"\n  have \"f 0 \\<le>\\<^sub>L A\" using ub by auto\n  then have dA: \"A \\<in> carrier_mat d d\" using ub unfolding lowner_le_def using dfn[of 0] by fastforce\n  then have dAmf0: \"A - f 0 \\<in> carrier_mat d d\" using dfn[of 0] by auto\n  have \"positive (A - f 0)\" using ub lowner_le_def by auto\n  then have tgeq0: \"trace (A - f 0) \\<ge> 0\" using positive_trace dAmf0 by auto\n  then have \"trace (A - f 0) + 1 > 0\" by auto\n  then have gtc: \"c > 0\" unfolding c_def using complex_is_Real_iff by auto\n  then have gtci: \"(1 / c) > 0\" using complex_is_Real_iff by auto\n\n  have \"trace (c \\<cdot>\\<^sub>m (A - f 0)) = c * trace (A - f 0)\"\n    using trace_smult dAmf0 by auto\n  also have \"\\<dots> = (1 / (trace (A - f 0) + 1)) * trace (A - f 0)\" unfolding c_def by auto\n  also have \"\\<dots> < 1\" using tgeq0 by (simp add: complex_is_Real_iff)\n  finally have lt1: \"trace (c \\<cdot>\\<^sub>m (A - f 0)) < 1\".\n\n  have le0: \"- f 0 \\<le>\\<^sub>L - f 0\" using lowner_le_refl[of \"- f 0\" d] dfn by auto\n\n  have dmf0: \"- f 0 \\<in> carrier_mat d d\" using dfn by auto\n  have mf0smcle: \"(c \\<cdot>\\<^sub>m (X - f 0)) \\<le>\\<^sub>L (c \\<cdot>\\<^sub>m (Y - f 0))\" if \"X \\<le>\\<^sub>L Y\" and \"X \\<in> carrier_mat d d\" and \"Y \\<in> carrier_mat d d\" for X Y\n  proof -\n    have \"(X - f 0) \\<le>\\<^sub>L (Y - f 0)\"\n      using lowner_le_minus[of \"X\" d \"Y\" \"f 0\" \"f 0\"] that dfn lowner_le_refl by auto\n    then show ?thesis using lowner_le_smultc[of c \"(X - f 0)\" \"Y - f 0\" d] using that dfn gtc by fastforce\n  qed\n  have \"(c \\<cdot>\\<^sub>m (f n - f 0)) \\<le>\\<^sub>L (c \\<cdot>\\<^sub>m (A - f 0))\" for n\n    using mf0smcle ub dfn dA by auto\n  then have \"trace (c \\<cdot>\\<^sub>m (f n - f 0)) \\<le> trace (c \\<cdot>\\<^sub>m (A - f 0))\" for n\n    using lowner_le_imp_trace_le[of \"c \\<cdot>\\<^sub>m (f n - f 0)\" d] dmfn0 dAmf0 by auto\n  then have trlt1: \"trace (c \\<cdot>\\<^sub>m (f n - f 0)) < 1\" for n using lt1 by fastforce\n\n  have \"f 0 \\<le>\\<^sub>L f n\" for n\n  proof (induct n)\n    case 0\n    then show ?case using dfn lowner_le_refl by auto\n  next\n    case (Suc n)\n    then show ?case using dfn lowner_le_trans[of \"f 0\" d \"f n\"] inc by auto\n  qed\n  then have \"positive (f n - f 0)\" for n using lowner_le_def by auto\n  then have p: \"positive (c \\<cdot>\\<^sub>m (f n - f 0))\" for n \n    by (intro positive_smult, insert gtc dmfn0, auto)\n\n  have inc': \"c \\<cdot>\\<^sub>m (f n - f 0) \\<le>\\<^sub>L c \\<cdot>\\<^sub>m (f (Suc n) - f 0)\" for n\n    using incm0 lowner_le_smultc[of c \"f n - f 0\"] gtc dmfn0 by fastforce\n\n  define g where \"g n = c \\<cdot>\\<^sub>m (f n - f 0)\" for n\n  then have \"positive (g n)\" and \"trace (g n) < 1\" and \"(g n) \\<le>\\<^sub>L (g (Suc n))\" and dgn: \"(g n) \\<in> carrier_mat d d\" for n\n    unfolding g_def using p trlt1 inc' dmfn0 by auto\n  then have ms: \"matrix_seq d g\" unfolding matrix_seq_def partial_density_operator_def by fastforce\n  then have uniM: \"\\<exists>!M. matrix_seq.lowner_is_lub g M\" using matrix_seq.lowner_lub_unique by auto\n  then obtain M where M: \"matrix_seq.lowner_is_lub g M\" by auto\n  then have leg: \"g n \\<le>\\<^sub>L M\" and lubg: \"\\<And>M'. (\\<forall>n. g n \\<le>\\<^sub>L M') \\<longrightarrow> M \\<le>\\<^sub>L M'\" for n\n    unfolding matrix_seq.lowner_is_lub_def[OF ms] by auto\n  have \"M = matrix_seq.lowner_lub g\"\n    using matrix_seq.lowner_lub_def[OF ms] M uniM theI_unique[of \"matrix_seq.lowner_is_lub g\"] by auto\n  then have limg: \"limit_mat g M d\" using M matrix_seq.lowner_lub_is_limit[OF ms] by auto\n  then have dM: \"M \\<in> carrier_mat d d\" unfolding limit_mat_def by auto\n\n  define B where \"B = f 0 + (1 / c) \\<cdot>\\<^sub>m M\"\n  have eqinv: \"f 0 + (1 / c) \\<cdot>\\<^sub>m (c \\<cdot>\\<^sub>m (X - f 0)) = X\" if \"X \\<in> carrier_mat d d\" for X\n  proof -\n    have \"f 0 + (1 / c) \\<cdot>\\<^sub>m (c \\<cdot>\\<^sub>m (X - f 0)) = f 0 + (1 / c * c) \\<cdot>\\<^sub>m (X - f 0)\"\n      apply (subgoal_tac \"(1 / c) \\<cdot>\\<^sub>m (c \\<cdot>\\<^sub>m (X - f 0)) = (1 / c * c) \\<cdot>\\<^sub>m (X - f 0)\", simp)\n      using smult_smult_mat dfn that by auto\n    also have \"\\<dots> = f 0 + 1 \\<cdot>\\<^sub>m (X - f 0)\" using gtc by auto\n    also have \"\\<dots> = f 0 + (X - f 0)\" by auto\n    also have \"\\<dots> = (- f 0) + f 0 + X\" apply (mat_assoc d) using that dfn by auto\n    also have \"\\<dots> = 0\\<^sub>m d d + X\" using dfn uminus_l_inv_mat[of \"f 0\" d d] by fastforce\n    also have \"\\<dots> = X\" using that by auto\n    finally show ?thesis by auto\n  qed\n  have \"limit_mat (\\<lambda>n. (1 / c) \\<cdot>\\<^sub>m g n) ((1 / c) \\<cdot>\\<^sub>m M) d\" using limit_mat_scale[OF limg] gtci by auto\n  then have \"limit_mat (\\<lambda>n. f 0 + (1 / c) \\<cdot>\\<^sub>m g n) (f 0 + (1 / c) \\<cdot>\\<^sub>m M ) d\"\n    using mat_add_limit[of \"f 0\"] limg dfn unfolding mat_add_seq_def by auto\n  then have limf: \"limit_mat f B d\" using eqinv[OF dfn] unfolding B_def g_def by auto\n\n  have f0acmcile: \"(f 0 + (1 / c) \\<cdot>\\<^sub>m X) \\<le>\\<^sub>L (f 0 + (1 / c) \\<cdot>\\<^sub>m Y )\" if \"X \\<le>\\<^sub>L Y\" and \"X \\<in> carrier_mat d d\" and \"Y \\<in> carrier_mat d d\" for X Y\n  proof -\n    have \"((1 / c) \\<cdot>\\<^sub>m X) \\<le>\\<^sub>L ((1 / c) \\<cdot>\\<^sub>m Y)\"\n      using lowner_le_smultc[of \"1/c\"] that gtci by fastforce\n    then show \"(f 0 + (1 / c) \\<cdot>\\<^sub>m X) \\<le>\\<^sub>L (f 0 + (1 / c) \\<cdot>\\<^sub>m Y)\"\n      using lowner_le_add[of _ d _ \"(1 / c) \\<cdot>\\<^sub>m X\" \"(1 / c) \\<cdot>\\<^sub>m Y\"]\n        that gtci dfn lowner_le_refl[of \"f 0\", OF dfn] by fastforce\n  qed\n\n  have \"(f 0 + (1 / c) \\<cdot>\\<^sub>m g n) \\<le>\\<^sub>L (f 0 + (1 / c) \\<cdot>\\<^sub>m M )\" for n\n    using f0acmcile[OF leg dgn dM] by auto\n  then have lubf: \"f n \\<le>\\<^sub>L B\" for n using eqinv[OF dfn] g_def B_def by auto\n\n  {\n    fix B' assume asm: \"\\<forall>n. f n \\<le>\\<^sub>L B'\"\n    then have \"f 0 \\<le>\\<^sub>L B'\" by auto\n    then have dB': \"B' \\<in> carrier_mat d d\" unfolding lowner_le_def using dfn[of 0] by auto\n    have \"f n \\<le>\\<^sub>L B'\" for n using asm by auto\n    then have \"(c \\<cdot>\\<^sub>m (f n - f 0)) \\<le>\\<^sub>L (c \\<cdot>\\<^sub>m (B' - f 0))\" for n\n      using mf0smcle[of \"f n\" B'] dfn dB' by auto\n    then have \"g n \\<le>\\<^sub>L (c \\<cdot>\\<^sub>m (B' - f 0))\" for n using g_def by auto\n    then have \"M \\<le>\\<^sub>L  (c \\<cdot>\\<^sub>m (B' - f 0))\" using lubg by auto\n    then have \"(f 0 + (1 / c) \\<cdot>\\<^sub>m M) \\<le>\\<^sub>L (f 0 + (1 / c) \\<cdot>\\<^sub>m (c \\<cdot>\\<^sub>m (B' - f 0)))\"\n      using f0acmcile[of \"M\" \"(c \\<cdot>\\<^sub>m (B' - f 0))\", OF _ dM] using dB' dfn by fastforce\n    then have \"B \\<le>\\<^sub>L B'\" unfolding B_def using eqinv[OF dB'] by auto\n  }\n  with limf lubf have \"((\\<forall>n. f n \\<le>\\<^sub>L B) \\<and> (\\<forall>M'. (\\<forall>n. f n \\<le>\\<^sub>L M') \\<longrightarrow> B \\<le>\\<^sub>L M')) \\<and> limit_mat f B d\" by auto\n  then show ?thesis unfolding lowner_is_lub_def 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/QHLProver/Matrix_Limit.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392695254319, "lm_q2_score": 0.8354835411997897, "lm_q1q2_score": 0.7386002594627832}}
{"text": "(* Author: Maximilian Sch\u00e4ffeler *)\n\ntheory MDP_reward\n  imports\n    Bounded_Functions\n    MDP_reward_Util\n    Blinfun_Util\n    MDP_disc\nbegin\n\nsection \\<open>Markov Decision Processes with Rewards\\<close>\n\nlocale MDP_reward = discrete_MDP A K\n  for\n    A and \n    K :: \"'s ::countable \\<times> 'a ::countable \\<Rightarrow> 's pmf\" +\n  fixes\n    r :: \"('s \\<times> 'a) \\<Rightarrow> real\" and\n    l :: real\n  assumes\n    zero_le_disc [simp]: \"0 \\<le> l\" and\n    r_bounded: \"bounded (range r)\"\nbegin\n\ntext \\<open>\nThis extension to the basic MDPs is formalized with another locale.\nIt assumes the existence of a reward function @{term r} which takes a state-action pair to a real \nnumber. We assume that the function is bounded @{prop r_bounded}.\n\nFurthermore, we fix a discounting factor @{term l}, where @{term \"0 \\<le> l \\<and> l < 1\"}.\n\\<close>\n\nsubsection \\<open>Util\\<close>\nsubsubsection \\<open>Basic Properties of rewards\\<close>\nlemma r_bfun: \"r \\<in> bfun\"\n  using r_bounded\n  by auto\n\nlemma r_bounded': \"bounded (r ` X)\"\n  by (auto intro: r_bounded bounded_subset)\n\ndefinition \"r\\<^sub>M = (\\<Squnion>sa. \\<bar>r sa\\<bar>)\"\n\nlemma abs_r_le_r\\<^sub>M: \"\\<bar>r sa\\<bar> \\<le> r\\<^sub>M\"\n  using bounded_norm_le_SUP_norm r_bounded r\\<^sub>M_def by fastforce\n\nlemma abs_r\\<^sub>M_eq_r\\<^sub>M [simp]: \"\\<bar>r\\<^sub>M\\<bar> = r\\<^sub>M\"\n  using abs_r_le_r\\<^sub>M by fastforce\n\nlemma r\\<^sub>M_nonneg: \"0 \\<le> r\\<^sub>M\"\n  using abs_r\\<^sub>M_eq_r\\<^sub>M by linarith\n\nlemma measurable_r_nth [measurable]: \"(\\<lambda>t. r (t !! i)) \\<in> borel_measurable S\"\n  by measurable\n\nlemma integrable_r_nth [simp]: \"integrable (\\<T> p s) (\\<lambda>t. r (t !! i))\"\n  by (fastforce simp: bounded_iff intro: abs_r_le_r\\<^sub>M)\n\nlemma expectation_abs_r_le: \"measure_pmf.expectation d (\\<lambda>a. \\<bar>r (s, a)\\<bar>) \\<le> r\\<^sub>M\"\n  using abs_r_le_r\\<^sub>M\n  by (fastforce intro!: measure_pmf.integral_le_const measure_pmf.integrable_const_bound)\n\nlemma abs_exp_r_le: \"\\<bar>measure_pmf.expectation d r\\<bar> \\<le> r\\<^sub>M\"\n  using abs_r_le_r\\<^sub>M\n  by (fastforce intro!: measure_pmf.integral_le_const order.trans[OF integral_abs_bound] measure_pmf.integrable_const_bound)\n\nsubsubsection \\<open>Infinite disounted sums\\<close>\nlemma abs_disc_eq[simp]: \"\\<bar>l ^ i * x\\<bar> = l ^ i * \\<bar>x\\<bar>\"\n  by (auto simp: abs_mult)\n\nlemma norm_l_pow_eq[simp]: \"norm (l^t *\\<^sub>R F) = l^t * norm F\"\n  by auto\n\nsubsection \\<open>Total Reward for Single Traces\\<close>\n\nabbreviation \"\\<nu>_trace_fin t N \\<equiv> \\<Sum>i < N. l ^ i * r (t !! i)\"\nabbreviation \"\\<nu>_trace t \\<equiv> \\<Sum>i. l ^ i * r (t !! i)\"\n\nlemma abs_\\<nu>_trace_fin_le: \"\\<bar>\\<nu>_trace_fin t N\\<bar> \\<le> (\\<Sum>i < N. l^i * r\\<^sub>M)\"\n  by (auto intro!: sum_mono order.trans[OF sum_abs] mult_left_mono abs_r_le_r\\<^sub>M)\n\nlemma measurable_suminf_reward[measurable]: \"\\<nu>_trace \\<in> borel_measurable S\"\n  by measurable\n\nlemma integrable_\\<nu>_trace_fin: \"integrable (\\<T> p s) (\\<lambda>t. \\<nu>_trace_fin t N)\"\n  by (fastforce simp: bounded_iff intro: abs_\\<nu>_trace_fin_le)\n\n\ncontext \n  fixes p :: \"('s, 'a) pol\"\nbegin\n\nsubsection \\<open>Expected Finite-Horizon Discounted Reward\\<close>\ndefinition \"\\<nu>_fin n s = \\<integral>t. \\<nu>_trace_fin t n \\<partial>\\<T> p s\"\n\nlemma abs_\\<nu>_fin_le: \"\\<bar>\\<nu>_fin N s\\<bar> \\<le> (\\<Sum>i<N. l^i * r\\<^sub>M)\"\n  unfolding \\<nu>_fin_def\n  using abs_\\<nu>_trace_fin_le\n  by (fastforce intro!: prob_space.integral_le_const order_trans[OF integral_abs_bound])\n\nlemma \\<nu>_fin_bfun: \"(\\<lambda>s. \\<nu>_fin N s) \\<in> bfun\"\n  by (auto intro!: abs_\\<nu>_fin_le)\n\nlift_definition \\<nu>\\<^sub>b_fin :: \"nat \\<Rightarrow> 's \\<Rightarrow>\\<^sub>b real\" is \\<nu>_fin\n  using \\<nu>_fin_bfun .\n\nlemma \\<nu>_fin_Suc[simp]: \"\\<nu>_fin (Suc n) s = \\<nu>_fin n s + l ^ n * \\<integral>t.  r (t !! n) \\<partial>\\<T> p s\"\n  by (simp add: \\<nu>_fin_def)\n\nlemma \\<nu>_fin_zero[simp]: \"\\<nu>_fin 0 s = 0\"\n  by (simp add: \\<nu>_fin_def)\n\nlemma \\<nu>_fin_eq_Pn: \"\\<nu>_fin n s = (\\<Sum>i<n. l^i * measure_pmf.expectation (Pn' p s i) r)\"\n  by (induction n) (auto simp: Pn'_eq_\\<T> integral_distr)\nend\n\nsubsection \\<open>Expected Total Discounted Reward\\<close>\n\ndefinition \"\\<nu> p s = lim (\\<lambda>n. \\<nu>_fin p n s)\"\n\nlemmas \\<nu>_eq_lim = \\<nu>_def\n\nlemma \\<nu>_eq_Pn: \"\\<nu> p s = (\\<Sum>i. l^i * measure_pmf.expectation (Pn' p s i) r)\"\n  by (simp add: \\<nu>_fin_eq_Pn \\<nu>_eq_lim suminf_eq_lim)\n\n\nsubsection \\<open>Reward of a Decision Rule\\<close>\ncontext \n  fixes d :: \"('s, 'a) dec\"\nbegin\nabbreviation \"r_dec s \\<equiv> \\<integral>a. r (s, a) \\<partial>d s\"\n\nlemma abs_r_dec_le: \"\\<bar>r_dec s\\<bar> \\<le> r\\<^sub>M\"\n  using expectation_abs_r_le integral_abs_bound order_trans by fast\n\nlemma r_dec_eq_r_K0: \"r_dec s = measure_pmf.expectation (K0' d s) r\"\n  by (simp add: K0'_def)\n\nlemma r_dec_bfun: \"r_dec \\<in> bfun\"\n  using abs_r_dec_le by (auto intro!: bfun_normI)\n\nlift_definition r_dec\\<^sub>b :: \"'s \\<Rightarrow>\\<^sub>b real\" is \"r_dec\"\n  using r_dec_bfun .\n\ndeclare r_dec\\<^sub>b.rep_eq[simp] bfun.Bfun_inverse[simp]\n\nlemma norm_r_dec_le: \"norm r_dec\\<^sub>b \\<le> r\\<^sub>M\"\n  by (simp add: abs_r_dec_le norm_bound)\nend\n\nlemma r_dec_det [simp]: \"r_dec (mk_dec_det d) s = r (s, d s)\"\n  unfolding mk_dec_det_def by auto\n\nsubsection \\<open>Transition Probability Matrix for MDPs\\<close>\n\ncontext\n  fixes p :: \"nat \\<Rightarrow> ('s, 'a) dec\"\nbegin\ndefinition \"\\<P>\\<^sub>X n = push_exp (\\<lambda>s. Xn' (mk_markovian p) s n)\"\n\nlemma \\<P>\\<^sub>X_0[simp]: \"\\<P>\\<^sub>X 0 = id\"\n  by (simp add: \\<P>\\<^sub>X_def)\n\nlemma \\<P>\\<^sub>X_bounded_linear[simp]: \"bounded_linear (\\<P>\\<^sub>X t)\"\n  unfolding \\<P>\\<^sub>X_def by simp\n\nlemma norm_\\<P>\\<^sub>X [simp]: \"onorm (\\<P>\\<^sub>X t) = 1\"\n  unfolding \\<P>\\<^sub>X_def by simp\n\nlemma norm_\\<P>\\<^sub>X_apply[simp]: \"norm (\\<P>\\<^sub>X n x) \\<le> norm x\"\n  using onorm[OF \\<P>\\<^sub>X_bounded_linear] by simp\n\nlemma \\<P>\\<^sub>X_bound_r: \"norm (\\<P>\\<^sub>X t (r_dec\\<^sub>b (p t))) \\<le> r\\<^sub>M\"\n  using norm_\\<P>\\<^sub>X_apply norm_r_dec_le order.trans by blast\n\nlemma \\<P>\\<^sub>X_bounded_r: \"bounded (range (\\<lambda>t. (\\<P>\\<^sub>X t (r_dec\\<^sub>b (p t)))))\"\n  using \\<P>\\<^sub>X_bound_r by (auto intro!: boundedI)\n\nend\n\nlemma \\<nu>_fin_elem: \"\\<nu>_fin (mk_markovian p) n s = (\\<Sum>i<n. l^i * \\<P>\\<^sub>X p i (r_dec\\<^sub>b (p i)) s)\"\n  unfolding \\<P>\\<^sub>X_def \\<nu>_fin_eq_Pn Pn'_markovian_eq_Xn'_bind measure_pmf_bind\n  using measure_pmf_in_subprob_algebra abs_r_le_r\\<^sub>M\n  by (subst integral_bind) (auto simp: r_dec_eq_r_K0)\n\nlemma \\<nu>\\<^sub>b_fin_eq_\\<P>\\<^sub>X: \"\\<nu>\\<^sub>b_fin (mk_markovian p) n = (\\<Sum>i<n. l^i *\\<^sub>R \\<P>\\<^sub>X p i (r_dec\\<^sub>b (p i)))\"\n  by (auto simp: \\<nu>_fin_elem sum_apply_bfun \\<nu>\\<^sub>b_fin.rep_eq)\n\nlemma \\<nu>_fin_eq_\\<P>\\<^sub>X: \"\\<nu>_fin (mk_markovian p) n = (\\<Sum>i<n. l^i *\\<^sub>R \\<P>\\<^sub>X p i (r_dec\\<^sub>b (p i)))\"\n  by (metis \\<nu>\\<^sub>b_fin.rep_eq \\<nu>\\<^sub>b_fin_eq_\\<P>\\<^sub>X)\n\n\ntext \\<open>\n@{term \"\\<P>\\<^sub>1 d v\"} defines for each state the expected value of @{term v} \nafter taking a single step in the MDP according to the decision rule @{term d}.  \n\\<close>\n\ncontext\n  fixes d :: \"('s, 'a) dec\"\nbegin\nlift_definition \\<P>\\<^sub>1 :: \"('s \\<Rightarrow>\\<^sub>b real) \\<Rightarrow>\\<^sub>L ('s \\<Rightarrow>\\<^sub>b real)\" is \"push_exp (K_st d)\"\n  using push_exp_bounded_linear .\n\nlemma \\<P>\\<^sub>1_bfun_one [simp]:\"\\<P>\\<^sub>1 1 = 1\"\n  by (auto simp: \\<P>\\<^sub>1.rep_eq)\n\nlemma \\<P>\\<^sub>1_pow_bfun_one [simp]: \"(\\<P>\\<^sub>1^^t) 1 = 1\"\n  by (induction t) auto\n\nlemma \\<P>\\<^sub>1_pow: \"blinfun_apply (\\<P>\\<^sub>1 ^^ n) = blinfun_apply \\<P>\\<^sub>1 ^^ n\"\n  by (induction n) auto\n\nlemma norm_\\<P>\\<^sub>1 [simp]: \"norm \\<P>\\<^sub>1 = 1\"\n  by (simp add: norm_blinfun.rep_eq \\<P>\\<^sub>1.rep_eq)\nend\n\nlemma \\<P>\\<^sub>X_Suc: \"\\<P>\\<^sub>X p (Suc n) v = \\<P>\\<^sub>1 (p 0) ((\\<P>\\<^sub>X (\\<lambda>n. p (Suc n)) n) v)\"\n  unfolding \\<P>\\<^sub>X_def \\<P>\\<^sub>1.rep_eq\n  by (fastforce intro!: abs_le_norm_bfun integral_bind[where K = \"count_space UNIV\"]\n      simp: measure_pmf_in_subprob_algebra measure_pmf_bind Suc_Xn'_markovian)\n\nlemma \\<P>\\<^sub>X_Suc': \"\\<P>\\<^sub>X p (Suc n) v = \\<P>\\<^sub>X p n (\\<P>\\<^sub>1 (p n) v)\"\nproof (induction n arbitrary: p)\n  case 0\n  thus ?case\n    by (simp add: \\<P>\\<^sub>X_Suc)\nnext\n  case (Suc n)\n  thus ?case \n    by (metis \\<P>\\<^sub>X_Suc)\nqed\n\nlemma \\<P>\\<^sub>X_const: \"\\<P>\\<^sub>X (\\<lambda>_. d) n = \\<P>\\<^sub>1 d ^^ n\"\n  by (induction n) (auto simp add: \\<P>\\<^sub>1_pow \\<P>\\<^sub>X_Suc)\n\nlemma \\<P>\\<^sub>X_sconst: \"\\<P>\\<^sub>X (\\<lambda>_. p) n = \\<P>\\<^sub>1 p ^^n\"\n  using \\<P>\\<^sub>X_const.\n\nlemma norm_P_n[simp]: \"onorm (\\<P>\\<^sub>1 d ^^ n) = 1\"\n  using norm_\\<P>\\<^sub>X[of \"\\<lambda>_. d\"] by (auto simp: \\<P>\\<^sub>X_sconst)\n\nlemma norm_\\<P>\\<^sub>1_pow [simp]: \"norm (\\<P>\\<^sub>1 d ^^ t) = 1\"\n  by (simp add: norm_blinfun.rep_eq)\n\nlemma \\<P>\\<^sub>X_Suc_n_elem: \"\\<P>\\<^sub>X p n (\\<P>\\<^sub>1 (p n) v) = \\<P>\\<^sub>X p (Suc n) v\"\n  using \\<P>\\<^sub>X_Suc' \\<P>\\<^sub>1.rep_eq by auto\n\nlemma \\<P>\\<^sub>1_eq_\\<P>\\<^sub>X_one: \"blinfun_apply (\\<P>\\<^sub>1 (p 0)) = \\<P>\\<^sub>X p 1\"\n  by (auto simp: \\<P>\\<^sub>X_Suc' \\<P>\\<^sub>1.rep_eq)\n\n\nlemma \\<P>\\<^sub>1_pos: \"0 \\<le> u \\<Longrightarrow> 0 \\<le> \\<P>\\<^sub>1 d u\"\n  by (auto simp: \\<P>\\<^sub>1.rep_eq less_eq_bfun_def)\n\nlemma \\<P>\\<^sub>1_nonneg: \"nonneg_blinfun (\\<P>\\<^sub>1 d)\"\n  by (simp add: \\<P>\\<^sub>1_pos nonneg_blinfun_def)\n\nlemma \\<P>\\<^sub>1_n_pos: \"0 \\<le> u \\<Longrightarrow> 0 \\<le> (\\<P>\\<^sub>1 d ^^ n) u\"\n  by (induction n) (auto simp: \\<P>\\<^sub>1.rep_eq less_eq_bfun_def)\n\nlemma \\<P>\\<^sub>1_n_nonneg: \"nonneg_blinfun (\\<P>\\<^sub>1 d ^^ n)\"\n  by (simp add: \\<P>\\<^sub>1_n_pos nonneg_blinfun_def)\n\nlemma \\<P>\\<^sub>1_n_disc_pos: \"0 \\<le> u \\<Longrightarrow> 0 \\<le> (l^n *\\<^sub>R \\<P>\\<^sub>1 d ^^n) u\"\n  by (auto simp: \\<P>\\<^sub>1_n_pos scaleR_nonneg_nonneg blinfun.scaleR_left)\n\nlemma \\<P>\\<^sub>1_sum_pos: \"0 \\<le> u \\<Longrightarrow> 0 \\<le> (\\<Sum>t\\<le>n. l^t *\\<^sub>R (\\<P>\\<^sub>1 d ^^ t)) u\"\n  using \\<P>\\<^sub>1_n_pos \\<P>\\<^sub>1_pos\n  by (induction n) (auto simp: blinfun.add_left blinfun.scaleR_left scaleR_nonneg_nonneg)\n\nlemma \\<P>\\<^sub>1_sum_ge: \n  assumes \"0 \\<le> u\" \n  shows \"u \\<le> (\\<Sum>t\\<le>n. l^t *\\<^sub>R \\<P>\\<^sub>1 d ^^t) u\"\n  using \\<P>\\<^sub>1_n_disc_pos[OF assms, of \"Suc _\"]\n  by (induction n) (auto intro: add_increasing2 simp add: blinfun.add_left)\n\n\nsubsection \\<open>The Bellman Operator\\<close>\ndefinition \"L d v \\<equiv> r_dec\\<^sub>b d + l *\\<^sub>R \\<P>\\<^sub>1 d v\"\n\nlemma norm_L_le: \"norm (L d v) \\<le> r\\<^sub>M + l * norm v\"\n  using norm_blinfun[of \"\\<P>\\<^sub>1 d\"] norm_\\<P>\\<^sub>1 norm_r_dec_le\n  by (auto intro!: norm_add_rule_thm mult_left_mono simp: L_def)\n\nlemma abs_L_le: \"\\<bar>L d v s\\<bar> \\<le> r\\<^sub>M + l * norm v\"\n  using order.trans[OF norm_le_norm_bfun norm_L_le] by auto\n\nsubsubsection \\<open>Bellman Operator for Single Actions\\<close>\nabbreviation \"L\\<^sub>a a v s \\<equiv> r (s, a) + l * measure_pmf.expectation (K (s,a)) v\"\n\nlemma L\\<^sub>a_le:\n  fixes v :: \"'s \\<Rightarrow>\\<^sub>b real\"\n  shows \"\\<bar>L\\<^sub>a a v s\\<bar> \\<le> r\\<^sub>M + l * norm v\"\n  using abs_r_le_r\\<^sub>M\n  by (fastforce intro: order_trans[OF abs_triangle_ineq] order_trans[OF integral_abs_bound]  \n      add_mono mult_mono measure_pmf.integral_le_const abs_le_norm_bfun \n      simp: abs_mult)\n\nlemma L\\<^sub>a_bounded:\n  \"bounded (range (\\<lambda>a. L\\<^sub>a a (apply_bfun v) s))\"\n  using L\\<^sub>a_le by (auto intro!: boundedI)\n\nlemma L\\<^sub>a_int: \n  fixes d :: \"'a pmf\" and v :: \"'s \\<Rightarrow>\\<^sub>b real\"\n  shows \"(\\<integral>a. L\\<^sub>a a v s \\<partial>d) = (\\<integral>a. r (s, a) \\<partial>d) + l * \\<integral>a. \\<integral>s'. v s' \\<partial>K (s, a) \\<partial>d\"\nproof (subst Bochner_Integration.integral_add)\n  show \"integrable d (\\<lambda>a. r (s, a))\"\n    using abs_r_le_r\\<^sub>M by (fastforce intro!: bounded_integrable simp: bounded_iff)\n  show \"integrable d (\\<lambda>a. l * \\<integral>s'. v s' \\<partial>K (s, a))\"\n    by (intro bounded_integrable) \n      (auto intro!: mult_mono order_trans[OF integral_abs_bound] boundedI[of _ \"l * norm v\"]\n        measure_pmf.integral_le_const simp: abs_le_norm_bfun abs_mult)\nqed auto\n\nlemma L_eq_L\\<^sub>a: \"L d v s = measure_pmf.expectation (d s) (\\<lambda>a. L\\<^sub>a a v s)\"\n  unfolding L\\<^sub>a_int L_def K_st_def \\<P>\\<^sub>1.rep_eq\n  by (auto simp: measure_pmf_bind integral_measure_pmf_bind[where B = \"norm v\"] abs_le_norm_bfun)\n\nlemma L_eq_L\\<^sub>a_det: \"L (mk_dec_det d) v s = L\\<^sub>a (d s) v s\"\n  by (auto simp: L_eq_L\\<^sub>a mk_dec_det_def)\n\nlemma L\\<^sub>a_eq_L: \"measure_pmf.expectation p (\\<lambda>a. L\\<^sub>a a (apply_bfun v) s) = \n  L (\\<lambda>t. if t = s then p else return_pmf (SOME a. a \\<in> A t)) v s\"\n  unfolding L_eq_L\\<^sub>a by auto\n\nlemma L_le: \"L d v s \\<le> r\\<^sub>M + l * norm v\"\n  unfolding L_def\n  using norm_\\<P>\\<^sub>1 norm_blinfun[of \"(\\<P>\\<^sub>1 d)\"] abs_r_dec_le\n  by (fastforce intro: order_trans[OF le_norm_bfun] add_mono mult_left_mono dest: abs_le_D1)\n\nlemma L\\<^sub>a_le': \"L\\<^sub>a a (apply_bfun v) s \\<le> r\\<^sub>M + l * norm v\"\n  using L\\<^sub>a_le abs_le_D1 by blast\n\n\nsubsection \\<open>Optimality Equations\\<close>\n\ndefinition \"\\<L> (v :: 's \\<Rightarrow>\\<^sub>b real) s = (\\<Squnion>d \\<in> D\\<^sub>R. L d v s)\"\n\nlemma \\<L>_bfun: \"\\<L> v \\<in> bfun\"\n  unfolding \\<L>_def using abs_L_le ex_dec by (fastforce intro!: cSup_abs_le bfun_normI)\n\nlift_definition \\<L>\\<^sub>b :: \"('s \\<Rightarrow>\\<^sub>b real) \\<Rightarrow> 's \\<Rightarrow>\\<^sub>b real\" is \\<L>\n  using \\<L>_bfun .\n\nlemma L_bounded[simp, intro]: \"bounded (range (\\<lambda>p. L p v s))\"\n  using abs_L_le by (auto intro!: boundedI)\n\nlemma L_bounded'[simp, intro]: \"bounded ((\\<lambda>p. L p v s) ` X)\"\n  by (auto intro: bounded_subset)\n\nlemma L_bdd_above[simp, intro]: \"bdd_above ((\\<lambda>p. L p v s) ` X)\"\n  by (auto intro: bounded_imp_bdd_above)\n\nlemma L_le_\\<L>\\<^sub>b: \"is_dec d \\<Longrightarrow> L d v \\<le> \\<L>\\<^sub>b v\"\n  by (fastforce simp: \\<L>\\<^sub>b.rep_eq \\<L>_def intro!: cSUP_upper)\n\nsubsubsection \\<open>Equivalences involving @{const \\<L>\\<^sub>b}\\<close>\n\nlemma SUP_step_MR_eq:\n  \"\\<L> v s = (\\<Squnion>pa \\<in> {pa. set_pmf pa \\<subseteq> A s}. (\\<integral>a. L\\<^sub>a a v s \\<partial>measure_pmf pa))\"\n  unfolding \\<L>_def\nproof (intro antisym)\n  show \"(\\<Squnion>d\\<in>D\\<^sub>R. L d v s) \\<le> (\\<Squnion>pa \\<in> {pa. set_pmf pa \\<subseteq> A s}. \\<integral>a. L\\<^sub>a a v s \\<partial>measure_pmf pa)\"\n  proof (rule cSUP_mono)\n    show \"D\\<^sub>R \\<noteq> {}\"\n      using D\\<^sub>R_ne .\n  next show \"bdd_above ((\\<lambda>pa. \\<integral>a. L\\<^sub>a a v s \\<partial>measure_pmf pa) ` {pa. set_pmf pa \\<subseteq> A s})\"\n      using L\\<^sub>a_bounded L\\<^sub>a_le\n      by (auto intro!: order_trans[OF integral_abs_bound] \n          bounded_imp_bdd_above boundedI[where B = \"r\\<^sub>M + l * norm v\"] \n          measure_pmf.integral_le_const bounded_integrable)\n  next show \"\\<exists>m\\<in>{pa. set_pmf pa \\<subseteq> A s}. L n v s \\<le> \\<integral>a. L\\<^sub>a a v s \\<partial>measure_pmf m\" if \"n \\<in> D\\<^sub>R\" for n\n      using that\n      by (fastforce simp: L_eq_L\\<^sub>a L\\<^sub>a_int is_dec_def)\n  qed\nnext\n  have aux: \"{pa. set_pmf pa \\<subseteq> A s} \\<noteq> {}\"\n    using D\\<^sub>R_ne is_dec_def by auto\n  show \"(\\<Squnion>pa\\<in>{pa. set_pmf pa \\<subseteq> A s}. \\<integral>a. L\\<^sub>a a v s \\<partial>measure_pmf pa) \\<le> (\\<Squnion>d\\<in>D\\<^sub>R. L d v s)\"\n  proof (intro cSUP_least[OF aux] cSUP_upper2)\n    fix n \n    assume h: \"n \\<in> {pa. set_pmf pa \\<subseteq> A s}\"\n    let ?p = \"(\\<lambda>s'. if s = s' then n else SOME a. set_pmf a \\<subseteq> A s')\"\n    have aux: \"\\<exists>a. set_pmf a \\<subseteq> A sa\" for sa\n      using ex_dec is_dec_def by blast\n    show \"?p \\<in> D\\<^sub>R\"\n      unfolding is_dec_def using h someI_ex[OF aux] by auto\n    thus \"(\\<integral>a. L\\<^sub>a a v s \\<partial>n) \\<le> L ?p v s\"\n      by (auto simp: L_eq_L\\<^sub>a)\n    show \"bdd_above ((\\<lambda>d. L d v s) ` D\\<^sub>R)\"\n      by (fastforce intro!: bounded_imp_bdd_above simp: bounded_def)\n  next\n  qed\nqed\n\nlemma \\<L>\\<^sub>b_eq_SUP_L\\<^sub>a: \"\\<L>\\<^sub>b v s = (\\<Squnion>p \\<in> {p. set_pmf p \\<subseteq> A s}. \\<integral>a. L\\<^sub>a a v s \\<partial>measure_pmf p)\"\n  using SUP_step_MR_eq \\<L>\\<^sub>b.rep_eq by presburger\n\nlemma SUP_step_det_eq: \"(\\<Squnion>d \\<in> D\\<^sub>D. L (mk_dec_det d) v s) = (\\<Squnion>a \\<in> A s. L\\<^sub>a a v s)\"\nproof (intro antisym cSUP_mono)\n  show \"bdd_above ((\\<lambda>a. L\\<^sub>a a v s) ` A s)\"\n    using L\\<^sub>a_bounded by (fastforce intro!: bounded_imp_bdd_above simp: bounded_def)\n  show \"bdd_above ((\\<lambda>d. L (mk_dec_det d) v s) ` D\\<^sub>D)\"\n    by (auto intro!: bounded_imp_bdd_above boundedI abs_L_le)\n  show \"\\<exists>m\\<in>A s. L (mk_dec_det n) v s \\<le> L\\<^sub>a m v s\" if \"n \\<in> D\\<^sub>D\" for n\n    using that is_dec_det_def by (auto simp: L_eq_L\\<^sub>a_det intro: bexI[of _ \"n s\"])\n  show \"\\<exists>m\\<in>D\\<^sub>D. L\\<^sub>a n v s \\<le> L (mk_dec_det m) v s\" if \"n \\<in> A s\" for n\n    using that A_ne\n    by (fastforce simp: L_eq_L\\<^sub>a_det is_dec_det_def some_in_eq\n        intro!: bexI[of _ \"\\<lambda>s'. if s = s' then _ else SOME a. a \\<in> A s'\"])\nqed (auto simp: A_ne)\n\nlemma integrable_L\\<^sub>a: \"integrable (measure_pmf x) (\\<lambda>a. L\\<^sub>a a (apply_bfun v) s)\"\nproof (intro Bochner_Integration.integrable_add integrable_mult_right)\n  show \"integrable (measure_pmf x) (\\<lambda>x. r (s, x))\"\n    using abs_r_le_r\\<^sub>M \n    by (auto intro: measure_pmf.integrable_const_bound[of _ \"r\\<^sub>M\"])\nnext\n  show \"integrable (measure_pmf x) (\\<lambda>x. measure_pmf.expectation (K (s, x)) v)\"\n    by (auto intro!: bounded_integrable boundedI order.trans[OF integral_abs_bound] \n        measure_pmf.integral_le_const abs_le_norm_bfun)\nqed\n\nlemma SUP_L\\<^sub>a_eq_det:\n  fixes v :: \"'s \\<Rightarrow>\\<^sub>b real\"\n  shows \"(\\<Squnion>p\\<in>{p. set_pmf p \\<subseteq> A s}. \\<integral>a. L\\<^sub>a a v s \\<partial>measure_pmf p) = (\\<Squnion>a\\<in>A s. L\\<^sub>a a v s)\"\nproof (intro antisym)\n  show \"(\\<Squnion>pa\\<in>{pa. set_pmf pa \\<subseteq> A s}. measure_pmf.expectation pa (\\<lambda>a. L\\<^sub>a a v s))\n    \\<le> (\\<Squnion>a\\<in>A s. L\\<^sub>a a v s)\"\n    using ex_dec is_dec_def integrable_L\\<^sub>a A_ne L\\<^sub>a_bounded\n    by (fastforce intro: bounded_range_subset intro!: cSUP_least lemma_4_3_1)\n  show \"(\\<Squnion>a\\<in>A s. L\\<^sub>a a v s) \\<le> (\\<Squnion>p\\<in>{p. set_pmf p \\<subseteq> A s}. \\<integral>a. L\\<^sub>a a v s \\<partial>measure_pmf p)\"\n    unfolding SUP_step_MR_eq[symmetric] SUP_step_det_eq[symmetric] \\<L>_def\n    using ex_dec_det by (fastforce intro!: cSUP_mono)\nqed\n\nlemma \\<L>_eq_SUP_det: \"\\<L> v s = (\\<Squnion>d \\<in> D\\<^sub>D. L (mk_dec_det d) v s)\"\n  using SUP_step_MR_eq SUP_step_det_eq SUP_L\\<^sub>a_eq_det by auto\n\nlemma \\<L>\\<^sub>b_eq_SUP_det: \"\\<L>\\<^sub>b v s = (\\<Squnion>d \\<in> D\\<^sub>D. L (mk_dec_det d) v s)\"\n  using \\<L>_eq_SUP_det unfolding \\<L>\\<^sub>b.rep_eq by auto\n\n\nsubsection \\<open>Monotonicity\\<close>\n\nlemma \\<P>\\<^sub>X_mono[intro]: \"a \\<le> b \\<Longrightarrow> \\<P>\\<^sub>X p n a \\<le> \\<P>\\<^sub>X p n b\"\n  by (fastforce simp: \\<P>\\<^sub>X_def intro: integral_mono)\n\nlemma \\<P>\\<^sub>1_mono[intro]: \"a \\<le> b \\<Longrightarrow> \\<P>\\<^sub>1 p a \\<le> \\<P>\\<^sub>1 p b\"\n  using \\<P>\\<^sub>1_nonneg by auto\n\nlemma L_mono[intro]: \"u \\<le> v \\<Longrightarrow> L d u \\<le> L d v\"\n  unfolding L_def by (auto intro: scaleR_left_mono)\n\nlemma \\<L>\\<^sub>b_mono[intro]: \"u \\<le> v \\<Longrightarrow> \\<L>\\<^sub>b u \\<le> \\<L>\\<^sub>b v\"\n  using  ex_dec L_mono[of u v] \n  by (fastforce intro!: cSUP_mono simp: \\<L>\\<^sub>b.rep_eq \\<L>_def)\n\nlemma step_mono:\n  assumes \"\\<L>\\<^sub>b v \\<le> v\" \"d \\<in> D\\<^sub>R\"\n  shows \"L d v \\<le> v\"\n  using assms L_le_\\<L>\\<^sub>b order.trans by blast\n\nlemma step_mono_elem_det:\n  assumes \"v \\<le> \\<L>\\<^sub>b v\" \"e > 0\"\n  shows \"\\<exists>d\\<in>D\\<^sub>D. v \\<le> L (mk_dec_det d) v + e *\\<^sub>R 1\"\nproof -\n  have \"v s \\<le> (\\<Squnion>a\\<in>A s. L\\<^sub>a a v s)\" for s\n    using SUP_step_det_eq \\<L>\\<^sub>b_eq_SUP_det assms(1) by fastforce\n  hence \"\\<exists>a\\<in>A s. v s - e < L\\<^sub>a a v s\" for s\n    using A_ne L\\<^sub>a_le'\n    by (subst less_cSUP_iff[symmetric]) (fastforce simp: assms add_strict_increasing algebra_simps intro!: bdd_above.I2)+\n  hence aux: \"\\<exists>a\\<in>A s. v s \\<le> L\\<^sub>a a v s + e\" for s\n    by (auto simp: diff_less_eq intro: less_imp_le)\n  then obtain d where \"is_dec_det d\" \"v s \\<le> L (mk_dec_det d) v s + e\" for s\n    by (metis L_eq_L\\<^sub>a_det is_dec_det_def)\n  thus ?thesis\n    by fastforce\nqed\n\nlemma step_mono_elem:\n  assumes \"v \\<le> \\<L>\\<^sub>b v\" \"e > 0\"\n  shows \"\\<exists>d\\<in>D\\<^sub>R. v \\<le> L d v + e *\\<^sub>R 1\"\n  using assms step_mono_elem_det by blast\n\nlemma \\<P>\\<^sub>X_L_le:\n  assumes \"\\<L>\\<^sub>b v \\<le> v\" \"p \\<in> \\<Pi>\\<^sub>M\\<^sub>R\"\n  shows \"\\<P>\\<^sub>X p n (L (p n) v) \\<le> \\<P>\\<^sub>X p n v\"\n  using assms step_mono by auto\n\nend\n\nlocale MDP_reward_disc = MDP_reward A K r l\n  for\n    A and \n    K :: \"'s ::countable \\<times> 'a ::countable \\<Rightarrow> 's pmf\" and\n    r l +\n  assumes\n    disc_lt_one [simp]: \"l < 1\"\nbegin\n\ndefinition \"is_opt_act v s = is_arg_max (\\<lambda>a. L\\<^sub>a a v s) (\\<lambda>a. a \\<in> A s)\"\nabbreviation \"opt_acts v s \\<equiv> {a. is_opt_act v s a}\"\n\nlemma summable_disc [intro, simp]: \"summable (\\<lambda>i. l ^ i * x)\"\n  by (simp add: mult.commute)\n\nlemma summable_r_disc[intro, simp]:\n  \"summable (\\<lambda>i. \\<bar>l ^ i * r (sa i)\\<bar>)\"\n  \"summable (\\<lambda>i. l ^ i * \\<bar>r (sa i)\\<bar>)\"\n  \"summable (\\<lambda>i. l ^ i * r (sa i))\"\nproof -\n  show \"summable (\\<lambda>i. \\<bar>l ^ i * r (sa i)\\<bar>)\"\n    using abs_r_le_r\\<^sub>M\n    by (fastforce intro!: mult_left_mono summable_comparison_test'[OF summable_disc])\n  thus \"summable (\\<lambda>i. l ^ i * r (sa i))\" \"summable (\\<lambda>i. l ^ i * \\<bar>r (sa i)\\<bar>)\"\n    by (auto intro: summable_rabs_cancel)\nqed\n\nlemma summable_norm_disc_I[intro]:\n  assumes \"summable (\\<lambda>t. (l^t * norm F))\"\n  shows \"summable (\\<lambda>t. norm (l^t *\\<^sub>R F))\"\n  using assms by auto\n\nlemma summable_norm_disc_I'[intro]:\n  assumes \"summable (\\<lambda>t. (l^t * norm (F t)))\"\n  shows \"summable (\\<lambda>t. norm (l^t *\\<^sub>R F t))\"\n  using assms by auto\n\nlemma summable_discI [intro]:\n  assumes \"bounded (range F)\"\n  shows \"summable (\\<lambda>t. l^t * norm (F t))\"\nproof -\n  obtain b where \"norm (F x) \\<le> b\" for x\n    using assms by (auto simp: bounded_iff)\n  thus ?thesis\n    using Abel_lemma[of l 1 F b] by (auto simp: mult.commute)\nqed\n\nlemma summable_disc_reward [intro]:\n  assumes \"bounded (range (F :: nat \\<Rightarrow> 'b :: banach))\"\n  shows \"summable (\\<lambda>t. l^t *\\<^sub>R (F t))\"\n  using assms by (auto intro: summable_norm_cancel)\n\nlemma summable_norm_bfun_disc: \"summable (\\<lambda>t. l^t * norm (apply_bfun f t))\"\n  using norm_le_norm_bfun\n  by (auto simp: mult.commute[of \"l^_\"] intro!: Abel_lemma[of _ 1 _ \"norm f\"])\n\nlemma summable_bfun_disc [simp]: \"summable (\\<lambda>t. l^t * (apply_bfun f t))\"\nproof -\n  have \"norm (l^t * apply_bfun f t) = l^t * norm (apply_bfun f t)\" for t\n    by (auto simp: abs_mult)\n  hence \"summable (\\<lambda>t. norm (l^t * (apply_bfun f t)))\"\n    by (auto simp only: abs_mult)\n  thus ?thesis\n    by (auto intro: summable_norm_cancel)\nqed\n\nlemma norm_bfun_disc_le: \"norm f \\<le> B \\<Longrightarrow> (\\<Sum>x. l^x * norm (apply_bfun f x)) \\<le> (\\<Sum>x. l^x * B)\"\n  by (fastforce intro!: suminf_le mult_left_mono norm_le_norm_bfun intro: order.trans)\n\nlemma norm_bfun_disc_le': \"norm f \\<le> B \\<Longrightarrow> (\\<Sum>x. l^x * (apply_bfun f x)) \\<le> (\\<Sum>x. l^x * B)\"\n  by (auto simp: mult_left_mono intro!: suminf_le order.trans[OF _ norm_bfun_disc_le])\n\nlemma sum_disc_lim_l: \"(\\<Sum>x. l^x * B) = B /(1-l)\"\n  by (simp add: suminf_mult2[symmetric] summable_geometric suminf_geometric[of l])\n\nlemma sum_disc_bound: \"(\\<Sum>x. l^x * apply_bfun f x) \\<le> (norm f) /(1-l)\"\n  using norm_bfun_disc_le' sum_disc_lim  by auto\n\nlemma sum_disc_bound':\n  fixes f :: \"nat \\<Rightarrow> 'b \\<Rightarrow>\\<^sub>b real\"\n  assumes h: \"\\<forall>n. norm (f n) \\<le> B\"\n  shows \"norm (\\<Sum>x. l^x *\\<^sub>R f x) \\<le> B /(1-l)\"\nproof -\n  have \"norm (\\<Sum>x. l^x *\\<^sub>R f x) \\<le>  (\\<Sum>x. norm (l^x *\\<^sub>R f x))\"\n    using h\n    by (fastforce intro!: boundedI summable_norm)\n  also have \"\\<dots> \\<le> (\\<Sum>x. l^x * B)\"\n    using h\n    by (auto intro!: suminf_le boundedI simp: mult_mono')\n  also have \"\\<dots> = B /(1-l)\"\n    by (simp add: sum_disc_lim)\n  finally show \"norm (\\<Sum>x. l^x *\\<^sub>R f x) \\<le> B /(1-l)\" .\nqed\n\n\nlemma abs_\\<nu>_trace_le: \"\\<bar>\\<nu>_trace t\\<bar> \\<le> (\\<Sum>i. l ^ i * r\\<^sub>M)\"\n  by (auto intro!: abs_r_le_r\\<^sub>M mult_left_mono order_trans[OF summable_rabs] suminf_le)\n\nlemma integrable_\\<nu>_trace: \"integrable (\\<T> p s) \\<nu>_trace\"\n  by (fastforce simp: bounded_iff intro: abs_\\<nu>_trace_le)\n\ncontext \n  fixes p :: \"('s, 'a) pol\"\nbegin\n\nlemma \\<nu>_eq_\\<nu>_trace: \"\\<nu> p s = \\<integral>t. \\<nu>_trace t \\<partial>\\<T> p s\"\nproof -\n  have \"(\\<lambda>n. \\<nu>_fin p n s) \\<longlonglongrightarrow> \\<integral>t. \\<nu>_trace t \\<partial>\\<T> p s\"\n    unfolding \\<nu>_fin_def\n  proof(intro integral_dominated_convergence)\n    show \"AE x in \\<T> p s. \\<nu>_trace_fin x \\<longlonglongrightarrow> \\<nu>_trace x\"\n      using summable_LIMSEQ by blast\n  next\n    have \"(\\<Sum>i<N. l ^ i * r\\<^sub>M) \\<le> (\\<Sum>N. l ^ N * r\\<^sub>M)\" for N\n      by (auto intro: sum_le_suminf simp: r\\<^sub>M_nonneg)\n    thus \"AE x in \\<T> p s. norm (\\<nu>_trace_fin x N) \\<le> (\\<Sum>N. l ^ N * r\\<^sub>M)\" for N\n      using order_trans[OF abs_\\<nu>_trace_fin_le] by fastforce\n  qed auto\n  thus ?thesis\n    using \\<nu>_eq_lim limI by fastforce\nqed\n\nlemma abs_\\<nu>_le: \"\\<bar>\\<nu> p s\\<bar> \\<le> (\\<Sum>i. l^i * r\\<^sub>M)\"\n  unfolding \\<nu>_eq_Pn\n  using abs_exp_r_le\n  by (fastforce intro!: order.trans[OF summable_rabs] suminf_le summable_comparison_test'[OF summable_disc] mult_left_mono)\n\nlemma \\<nu>_le: \"\\<nu> p s \\<le> (\\<Sum>i. l^i * r\\<^sub>M)\"\n  by (auto intro: abs_\\<nu>_le abs_le_D1)\n\n(* 6.1.2 in Puterman *)\nlemma \\<nu>_bfun: \"\\<nu> p \\<in> bfun\"\n  by (auto intro!: abs_\\<nu>_le)\n\nlift_definition \\<nu>\\<^sub>b :: \"'s \\<Rightarrow>\\<^sub>b real\" is \"\\<nu> p\"\n  using \\<nu>_bfun by blast\n\nlemma norm_\\<nu>_le: \"norm \\<nu>\\<^sub>b \\<le> r\\<^sub>M / (1-l)\"\n  using abs_\\<nu>_le sum_disc_lim\n  by (auto simp: \\<nu>\\<^sub>b.rep_eq norm_bfun_def' intro: cSUP_least)\nend\n\nlemma \\<nu>_as_markovian: \"\\<nu> (mk_markovian (as_markovian p (return_pmf s))) s = \\<nu> p s\"\n  by (auto simp: \\<nu>_eq_Pn Pn_as_markovian_eq Pn'_def)\n\nlemma \\<nu>\\<^sub>b_as_markovian: \"\\<nu>\\<^sub>b (mk_markovian (as_markovian p (return_pmf s))) s = \\<nu>\\<^sub>b p s\"\n  using \\<nu>_as_markovian by (auto simp: \\<nu>\\<^sub>b.rep_eq)\n\nsubsection \\<open>Optimal Reward\\<close>\n\ndefinition \"\\<nu>_MD s \\<equiv> \\<Squnion>p \\<in> \\<Pi>\\<^sub>M\\<^sub>D. \\<nu> (mk_markovian_det p) s\"\ndefinition \"\\<nu>_opt s \\<equiv> \\<Squnion>p \\<in> \\<Pi>\\<^sub>H\\<^sub>R. \\<nu> p s\"\n\nlemma \\<nu>_opt_bfun: \"\\<nu>_opt \\<in> bfun\"\n  using abs_\\<nu>_le policies_ne \n  by (fastforce simp: \\<nu>_opt_def intro!: order_trans[OF cSup_abs_le] bfun_normI)\n\nlift_definition \\<nu>\\<^sub>b_opt :: \"'s \\<Rightarrow>\\<^sub>b real\" is \\<nu>_opt\n  using \\<nu>_opt_bfun .\n\nlemma \\<nu>\\<^sub>b_opt_eq: \"\\<nu>\\<^sub>b_opt s = (\\<Squnion>p \\<in> \\<Pi>\\<^sub>H\\<^sub>R. \\<nu>\\<^sub>b p s)\"\n  using \\<nu>\\<^sub>b.rep_eq \\<nu>\\<^sub>b_opt.rep_eq \\<nu>_opt_def by presburger\n\nlemma \\<nu>_le_\\<nu>_opt [intro]:\n  assumes \"is_policy p\"\n  shows \"\\<nu> p s \\<le> \\<nu>_opt s\"\n  unfolding \\<nu>_opt_def using abs_\\<nu>_le assms\n  by (force intro: cSUP_upper intro!: bounded_imp_bdd_above boundedI)\n\nlemma \\<nu>\\<^sub>b_le_opt [intro]: \"p \\<in> \\<Pi>\\<^sub>H\\<^sub>R \\<Longrightarrow> \\<nu>\\<^sub>b p \\<le> \\<nu>\\<^sub>b_opt\"\n  using \\<nu>_le by (fastforce simp: \\<nu>\\<^sub>b.rep_eq \\<nu>\\<^sub>b_opt.rep_eq)\n\nlemma \\<nu>\\<^sub>b_le_opt_MD [intro]: \"p \\<in> \\<Pi>\\<^sub>M\\<^sub>D \\<Longrightarrow> \\<nu>\\<^sub>b (mk_markovian_det p) \\<le> \\<nu>\\<^sub>b_opt\"\n  by (auto simp: mk_markovian_det_def is_dec_det_def is_dec_def is_policy_def)\n\nlemma \\<nu>\\<^sub>b_le_opt_DD [intro]: \"is_dec_det d \\<Longrightarrow> \\<nu>\\<^sub>b (mk_stationary_det d) \\<le> \\<nu>\\<^sub>b_opt\"\n  by (auto simp add: is_policy_def mk_markovian_def)\n\nlemma \\<nu>\\<^sub>b_le_opt_DR [intro]: \"is_dec d \\<Longrightarrow> \\<nu>\\<^sub>b (mk_stationary d) \\<le> \\<nu>\\<^sub>b_opt\"\n  by (auto simp add: is_policy_def mk_markovian_def)\n\nlemma \\<nu>\\<^sub>b_opt_eq_MR: \"\\<nu>\\<^sub>b_opt s = (\\<Squnion>p \\<in> \\<Pi>\\<^sub>M\\<^sub>R. \\<nu>\\<^sub>b (mk_markovian p) s)\"\nproof (rule antisym)\n  show \"\\<nu>\\<^sub>b_opt s \\<le> (\\<Squnion>p\\<in>\\<Pi>\\<^sub>M\\<^sub>R. \\<nu>\\<^sub>b (mk_markovian p) s)\"\n    unfolding \\<nu>\\<^sub>b_opt_eq\n  proof (rule cSUP_mono)\n    show \"\\<Pi>\\<^sub>H\\<^sub>R \\<noteq> {}\"\n      using policies_ne by simp\n    show \"bdd_above ((\\<lambda>p. \\<nu>\\<^sub>b (mk_markovian p) s) ` \\<Pi>\\<^sub>M\\<^sub>R)\"\n      by (auto intro!: boundedI bounded_imp_bdd_above abs_\\<nu>_le simp: \\<nu>\\<^sub>b.rep_eq) \n    show \"n \\<in> \\<Pi>\\<^sub>H\\<^sub>R \\<Longrightarrow> \\<exists>m\\<in>\\<Pi>\\<^sub>M\\<^sub>R. \\<nu>\\<^sub>b n s \\<le> \\<nu>\\<^sub>b (mk_markovian m) s\" for n\n      using is_\\<Pi>\\<^sub>M\\<^sub>R_as_markovian by (subst \\<nu>\\<^sub>b_as_markovian[symmetric]) fastforce     \n  qed\n  show \"(\\<Squnion>p\\<in>\\<Pi>\\<^sub>M\\<^sub>R. \\<nu>\\<^sub>b (mk_markovian p) s) \\<le> \\<nu>\\<^sub>b_opt s\"\n    using \\<Pi>\\<^sub>M\\<^sub>R_ne \\<Pi>\\<^sub>M\\<^sub>R_imp_policies \n    by (auto intro!: cSUP_mono bounded_imp_bdd_above boundedI abs_\\<nu>_le simp: \\<nu>\\<^sub>b_opt_eq  \\<nu>\\<^sub>b.rep_eq)\nqed\n\nlemma summable_norm_disc_reward'[simp]: \"summable (\\<lambda>t. l^t * norm (\\<P>\\<^sub>X p t (r_dec\\<^sub>b (p t))))\"\n  using \\<P>\\<^sub>X_bounded_r by auto\n\nlemma summable_disc_reward_\\<P>\\<^sub>X [simp]: \"summable (\\<lambda>t. l^t *\\<^sub>R \\<P>\\<^sub>X p t (r_dec\\<^sub>b (p t)))\"\n  using summable_disc_reward \\<P>\\<^sub>X_bounded_r by blast\n\nlemma disc_reward_tendsto:\n  \"(\\<lambda>n. \\<Sum>t<n. l^t *\\<^sub>R \\<P>\\<^sub>X p t (r_dec\\<^sub>b (p t))) \\<longlonglongrightarrow> (\\<Sum>t. l^t *\\<^sub>R \\<P>\\<^sub>X p t (r_dec\\<^sub>b (p t)))\"\n  by (simp add: summable_LIMSEQ)\n\nlemma \\<nu>_eq_\\<P>\\<^sub>X: \"\\<nu> (mk_markovian p) = (\\<Sum>i. l^i *\\<^sub>R \\<P>\\<^sub>X p i (r_dec\\<^sub>b (p i)))\"\nproof -\n  have \"\\<nu> (mk_markovian p) s = (\\<Sum>i. l^i * \\<P>\\<^sub>X p i (r_dec\\<^sub>b (p i)) s)\" for s\n    unfolding \\<nu>\\<^sub>b.rep_eq \\<P>\\<^sub>X_def \\<nu>_eq_Pn Pn'_markovian_eq_Xn'_bind measure_pmf_bind\n    using measure_pmf_in_subprob_algebra abs_r_le_r\\<^sub>M\n    by (subst integral_bind) (auto simp: r_dec_eq_r_K0)\n  thus ?thesis\n    by (auto simp: suminf_apply_bfun)\nqed\n\nlemma \\<nu>\\<^sub>b_eq_\\<P>\\<^sub>X: \"\\<nu>\\<^sub>b (mk_markovian p) = (\\<Sum>i. l^i *\\<^sub>R \\<P>\\<^sub>X p i (r_dec\\<^sub>b (p i)))\"\n  by (auto simp: \\<nu>_eq_\\<P>\\<^sub>X \\<nu>\\<^sub>b.rep_eq)\n\nlemma \\<nu>\\<^sub>b_fin_tendsto_\\<nu>\\<^sub>b: \"(\\<nu>\\<^sub>b_fin (mk_markovian p)) \\<longlonglongrightarrow> \\<nu>\\<^sub>b (mk_markovian p)\"\n  using disc_reward_tendsto \\<nu>\\<^sub>b_eq_\\<P>\\<^sub>X \\<nu>\\<^sub>b_fin_eq_\\<P>\\<^sub>X\n  by presburger\n\nlemma norm_\\<P>\\<^sub>1_l_less: \"norm (l *\\<^sub>R \\<P>\\<^sub>1 d) < 1\"\n  by auto\nlemma disc_\\<P>\\<^sub>1_tendsto: \"(\\<lambda>n. (\\<Sum>t\\<le>n. l^t *\\<^sub>R \\<P>\\<^sub>1 d ^^t)) \\<longlonglongrightarrow> (\\<Sum>t. l^t *\\<^sub>R \\<P>\\<^sub>1 d ^^t)\"\n  by (fastforce simp: bounded_iff intro: summable_LIMSEQ')\n\nlemma disc_\\<P>\\<^sub>1_lim: \"lim (\\<lambda>n. (\\<Sum>t\\<le>n. l^t *\\<^sub>R \\<P>\\<^sub>1 d ^^ t)) = (\\<Sum>t. l^t *\\<^sub>R \\<P>\\<^sub>1 d ^^t)\"\n  using limI disc_\\<P>\\<^sub>1_tendsto\n  by blast\n\nlemma convergent_disc_\\<P>\\<^sub>1: \"convergent (\\<lambda>n. (\\<Sum>t\\<le>n. l^t *\\<^sub>R \\<P>\\<^sub>1 d ^^t))\"\n  using convergentI disc_\\<P>\\<^sub>1_tendsto \n  by blast\n\nlemma \\<P>\\<^sub>1_suminf_ge: \n  assumes \"0 \\<le> u\" shows \"u \\<le> (\\<Sum>t. l^t *\\<^sub>R \\<P>\\<^sub>1 d ^^t) u\"\nproof -\n  have aux: \"\\<And>x. (\\<lambda>n. (\\<Sum>t\\<le>n. l^t *\\<^sub>R \\<P>\\<^sub>1 d ^^t) u x) \\<longlonglongrightarrow> (\\<Sum>t. l^t *\\<^sub>R \\<P>\\<^sub>1 d ^^t) u x\"\n    using bfun_tendsto_apply_bfun disc_\\<P>\\<^sub>1_lim lim_blinfun_apply[OF convergent_disc_\\<P>\\<^sub>1] \n    by fastforce\n  have \"\\<And>n. u \\<le> (\\<Sum>t\\<le>n. l^t *\\<^sub>R \\<P>\\<^sub>1 d ^^t) u\"\n    using \\<P>\\<^sub>1_sum_ge[OF assms] by auto\n  thus ?thesis\n    by (auto intro!: LIMSEQ_le_const[OF aux])\nqed\n\nlemma \\<P>\\<^sub>1_suminf_pos: \n  assumes \"0 \\<le> u\" \n  shows \"0 \\<le> (\\<Sum>t. l^t *\\<^sub>R \\<P>\\<^sub>1 d ^^t) u\"\n  using \\<P>\\<^sub>1_suminf_ge[of u] assms order.trans by auto\n\nlemma lemma_6_1_2_b:\n  assumes \"v \\<le> u\"\n  shows \"(\\<Sum>t. l^t *\\<^sub>R \\<P>\\<^sub>1 d ^^t) v \\<le> (\\<Sum>t. l^t *\\<^sub>R \\<P>\\<^sub>1 d ^^t) u\"\nproof -\n  have \"0 \\<le> (\\<Sum>n. l ^ n *\\<^sub>R \\<P>\\<^sub>1 d ^^ n) (u - v)\"\n    using \\<P>\\<^sub>1_suminf_pos assms by simp\n  thus ?thesis\n    by (simp add: blinfun.diff_right)\nqed\n\nlemma \\<nu>_stationary: \"\\<nu>\\<^sub>b (mk_stationary d) = (\\<Sum>t. l^t *\\<^sub>R (\\<P>\\<^sub>1 d ^^ t)) (r_dec\\<^sub>b d)\"\nproof -\n  have \"\\<nu>\\<^sub>b (mk_stationary d) = (\\<Sum>t. (l ^ t *\\<^sub>R (\\<P>\\<^sub>1 d ^^ t)) (r_dec\\<^sub>b d))\"\n    by (simp add: \\<nu>\\<^sub>b_eq_\\<P>\\<^sub>X scaleR_blinfun.rep_eq \\<P>\\<^sub>X_sconst)\n  also have \"...  = (\\<Sum>t. (l ^ t *\\<^sub>R (\\<P>\\<^sub>1 d ^^ t))) (r_dec\\<^sub>b d)\"\n    by (subst bounded_linear.suminf[where f = \"\\<lambda>x. blinfun_apply x (r_dec\\<^sub>b d)\"]) \n      (auto intro!: bounded_linear.suminf boundedI)\n  finally show ?thesis .\nqed\n\nlemma \\<nu>_stationary_inv: \"\\<nu>\\<^sub>b (mk_stationary d) = inv\\<^sub>L (id_blinfun - l *\\<^sub>R \\<P>\\<^sub>1 d) (r_dec\\<^sub>b d)\"\n  by (auto simp: \\<nu>_stationary inv\\<^sub>L_inf_sum blincomp_scaleR_right)\n\n\ntext \\<open>The value of a markovian policy can be expressed in terms of @{const L}.\\<close>\n\nlemma \\<nu>_step: \"\\<nu>\\<^sub>b (mk_markovian p) = L (p 0) (\\<nu>\\<^sub>b (mk_markovian (\\<lambda>n. p (Suc n))))\"\nproof -\n  have s: \"summable (\\<lambda>t. l^t *\\<^sub>R (\\<P>\\<^sub>X p (Suc t) (r_dec\\<^sub>b (p (Suc t)))))\"\n    using \\<P>\\<^sub>X_bound_r by (auto intro!: boundedI[of _ r\\<^sub>M])\n  have \n    \"\\<nu>\\<^sub>b (mk_markovian p) = r_dec\\<^sub>b (p 0) + (\\<Sum>t. l ^ (Suc t) *\\<^sub>R \\<P>\\<^sub>X p (Suc t) (r_dec\\<^sub>b (p (Suc t))))\"\n    by (subst suminf_split_head) (auto simp: \\<nu>\\<^sub>b_eq_\\<P>\\<^sub>X)\n  also have \n    \"\\<dots> = r_dec\\<^sub>b (p 0) + l *\\<^sub>R (\\<Sum>t. \\<P>\\<^sub>1 (p 0) (l^t *\\<^sub>R \\<P>\\<^sub>X (\\<lambda>n. p (Suc n)) t (r_dec\\<^sub>b (p (Suc t)))))\"\n    using suminf_scaleR_right[OF s] by (auto simp: \\<P>\\<^sub>X_Suc blinfun.scaleR_right)\n  also have \n    \"\\<dots> = L (p 0) (\\<nu>\\<^sub>b (mk_markovian (\\<lambda>n. p (Suc n))))\"\n    using blinfun.bounded_linear_right bounded_linear.suminf[of \"blinfun_apply (\\<P>\\<^sub>1 (p 0))\"]\n    by (fastforce simp add: \\<nu>\\<^sub>b_eq_\\<P>\\<^sub>X L_def)\n  finally show ?thesis .\nqed\n\nlemma L_\\<nu>_fix: \"\\<nu>\\<^sub>b (mk_stationary d) = L d (\\<nu>\\<^sub>b (mk_stationary d))\"\n  using \\<nu>_step .\n\nlemma L_fix_\\<nu>:\n  assumes \"L p v = v\"\n  shows \"v = \\<nu>\\<^sub>b (mk_stationary p)\"\nproof -\n  have \"r_dec\\<^sub>b p = (id_blinfun - l *\\<^sub>R \\<P>\\<^sub>1 p) v\"\n    using assms by (auto simp: eq_diff_eq L_def blinfun.diff_left blinfun.scaleR_left)\n  hence \"v = (\\<Sum>t. (l *\\<^sub>R \\<P>\\<^sub>1 p)^^t) (r_dec\\<^sub>b p)\"\n    using inv_norm_le'(2)[OF norm_\\<P>\\<^sub>1_l_less] by auto\n  thus \"v = \\<nu>\\<^sub>b (mk_stationary p)\"\n    by (auto simp: \\<nu>_stationary blincomp_scaleR_right)\nqed\n\nlemma L_\\<nu>_fix_iff: \"L d v = v \\<longleftrightarrow> v = \\<nu>\\<^sub>b (mk_stationary d)\"\n  using L_fix_\\<nu> L_\\<nu>_fix by auto\n\nsubsection \\<open>Properties of Solutions of the Optimality Equations\\<close>\n\nabbreviation \"\\<P>\\<^sub>d p n v \\<equiv> l^n *\\<^sub>R \\<P>\\<^sub>X p n v\"\n\nlemma \\<P>\\<^sub>d_lim: \"(\\<lambda>n. (\\<P>\\<^sub>d p n v)) \\<longlonglongrightarrow> 0\"\nproof -\n  have \"(\\<lambda>n. l^n * norm v) \\<longlonglongrightarrow> 0\"\n    by (auto intro!: tendsto_eq_intros)\n  moreover have \"norm (\\<P>\\<^sub>d p n v) \\<le> l^n * norm v\" for p n\n    by (simp add: mult_mono')\n  ultimately have \"(\\<lambda>n. norm (\\<P>\\<^sub>d p n v)) \\<longlonglongrightarrow> 0\" for p\n    by (auto simp: Lim_transform_bound[where g = \"\\<lambda>n. (l^n * norm v)\"])\n  thus \"(\\<lambda>n. (\\<P>\\<^sub>d p n v)) \\<longlonglongrightarrow> 0\" for p\n    using tendsto_norm_zero_cancel by fast\nqed\n\n\n\n(* 6.2.2 a) in Puterman *)\n\nlemma \\<L>_dec_ge_opt:\n  assumes \"\\<L>\\<^sub>b v \\<le> v\"\n  shows \"\\<nu>\\<^sub>b_opt \\<le> v\"\nproof -\n  have \"\\<nu>\\<^sub>b (mk_markovian p) \\<le> v\" if \"p \\<in> \\<Pi>\\<^sub>M\\<^sub>R\" for p\n  proof -\n    let ?p = \"mk_markovian p\"\n    have aux: \"\\<nu>\\<^sub>b_fin ?p n + l^n *\\<^sub>R \\<P>\\<^sub>X p n v \\<le> v\" for n\n    proof (induction n)\n      case (Suc n)\n      have \"\\<P>\\<^sub>X p n (r_dec\\<^sub>b (p n)) + l *\\<^sub>R (\\<P>\\<^sub>X p (Suc n) v) \\<le> \\<P>\\<^sub>X p n v\"\n        using \\<P>\\<^sub>X_L_le assms that by (simp add: \\<P>\\<^sub>X_Suc_n_elem L_def linear_simps)\n      hence \"\\<nu>\\<^sub>b_fin ?p (n + 1) + l^(n + 1) *\\<^sub>R (\\<P>\\<^sub>X p (n + 1) v) \\<le> \\<nu>\\<^sub>b_fin ?p n + l^n *\\<^sub>R (\\<P>\\<^sub>X p n v)\"\n        by (auto simp del: scaleR_scaleR intro: scaleR_left_mono simp: \\<nu>\\<^sub>b_fin_eq_\\<P>\\<^sub>X \n            mult.commute[of l] scaleR_add_right[symmetric] scaleR_scaleR[symmetric])\n      also have \"\\<dots> \\<le> v\"\n        using Suc.IH by (auto simp: \\<nu>\\<^sub>b_fin_eq_\\<P>\\<^sub>X)\n      finally show ?case\n        by auto\n    qed (auto simp: \\<nu>\\<^sub>b_fin_eq_\\<P>\\<^sub>X)\n    have 1: \"(\\<lambda>n. (\\<nu>\\<^sub>b_fin ?p n + \\<P>\\<^sub>d p n v) s) \\<longlonglongrightarrow> \\<nu>\\<^sub>b ?p s\" for s\n      using bfun_tendsto_apply_bfun Limits.tendsto_add[OF \\<nu>\\<^sub>b_fin_tendsto_\\<nu>\\<^sub>b \\<P>\\<^sub>d_lim] by fastforce\n    have \"\\<nu>\\<^sub>b ?p s \\<le> v s\" for s\n      using that aux assms by (fastforce intro!: lim_mono[OF _ 1, of  _ _ \"\\<lambda>n. v s\"])\n    thus ?thesis\n      using that by blast\n  qed\n  thus ?thesis\n    using policies_ne by (fastforce simp: is_policy_def \\<nu>\\<^sub>b_opt_eq_MR intro!: cSUP_least)\nqed\n\nlemma \\<L>_inc_le_opt:\n  assumes \"v \\<le> \\<L>\\<^sub>b v\"\n  shows \"v \\<le> \\<nu>\\<^sub>b_opt\"\nproof -\n  have le_elem: \"v s \\<le> \\<nu>\\<^sub>b_opt s + (e/(1-l))\" if \"e > 0\" for s e\n  proof -\n    obtain d where \"d \\<in> D\\<^sub>R\" and hd: \"v \\<le> L d v + e *\\<^sub>R 1\"\n      using assms step_mono_elem \\<open>e > 0\\<close> by blast\n    let ?Pinf = \"(\\<Sum>i. l^i *\\<^sub>R \\<P>\\<^sub>1 d^^i)\"\n    have \"v \\<le> r_dec\\<^sub>b d + l *\\<^sub>R (\\<P>\\<^sub>1 d) v + e *\\<^sub>R 1\"\n      using hd L_def by fastforce\n    hence \"(id_blinfun - l *\\<^sub>R \\<P>\\<^sub>1 d) v \\<le> r_dec\\<^sub>b d + e *\\<^sub>R 1\"\n      by (auto simp: blinfun.diff_left blinfun.scaleR_left algebra_simps)\n    hence \"?Pinf ((id_blinfun - l *\\<^sub>R \\<P>\\<^sub>1 d) v) \\<le> ?Pinf (r_dec\\<^sub>b d + e *\\<^sub>R 1)\"\n      using lemma_6_1_2_b \\<P>\\<^sub>1_def hd by auto\n    hence \"v \\<le> ?Pinf (r_dec\\<^sub>b d + e *\\<^sub>R 1)\"\n      using inv_norm_le'(2)[of \"l *\\<^sub>R \\<P>\\<^sub>1 d\"] by (auto simp: blincomp_scaleR_right)\n    also have \"\\<dots> = \\<nu>\\<^sub>b (mk_stationary d) + e *\\<^sub>R ?Pinf 1\"\n      by (simp add: \\<nu>_stationary blinfun.add_right blinfun.scaleR_right)\n    also have \"\\<dots> = \\<nu>\\<^sub>b (mk_stationary d) + e *\\<^sub>R (\\<Sum>i. (l^i *\\<^sub>R ((\\<P>\\<^sub>1 d^^i))) 1)\"\n      using convergent_disc_\\<P>\\<^sub>1 \n      by (auto simp: summable_iff_convergent' bounded_linear.suminf[of \"\\<lambda>x. blinfun_apply x 1\"])\n    also have \"\\<dots> = \\<nu>\\<^sub>b (mk_stationary d) + e *\\<^sub>R (\\<Sum>i. (l^i *\\<^sub>R 1))\"\n      by (auto simp: scaleR_blinfun.rep_eq)\n    also have \"\\<dots> \\<le> (\\<nu>\\<^sub>b (mk_stationary d) + (e / (1-l)) *\\<^sub>R  1)\"\n      by (auto simp: bounded_linear.suminf[symmetric, where f = \"\\<lambda>x. x *\\<^sub>R 1\"] \n          suminf_geometric bounded_linear_scaleR_left summable_geometric)\n    finally have \"v s \\<le> (\\<nu>\\<^sub>b (mk_stationary d) + (e/(1-l)) *\\<^sub>R  1) s\"\n      by auto\n    thus \"v s \\<le> \\<nu>\\<^sub>b_opt s + (e/(1-l))\"\n      using \\<open>d \\<in> D\\<^sub>R\\<close> \\<nu>\\<^sub>b_le_opt\n      by (auto simp: is_policy_def mk_markovian_def less_eq_bfun_def intro: order_trans)\n  qed\n  have \"v s \\<le> \\<nu>\\<^sub>b_opt s + e\" if \"e > 0\" for s e\n  proof -\n    have \"e * (1 - l) > 0\"\n      by (simp add: \\<open>0 < e\\<close>)\n    thus \"v s \\<le> \\<nu>\\<^sub>b_opt s + e\"\n      using disc_lt_one that le_elem by (fastforce split: if_splits)\n  qed\n  thus ?thesis\n    by (fastforce intro: field_le_epsilon)\nqed    \nlemma \\<L>_fix_imp_opt:\n  assumes \"v = \\<L>\\<^sub>b v\"\n  shows \"v = \\<nu>\\<^sub>b_opt\"\n  using assms dual_order.antisym[OF \\<L>_dec_ge_opt \\<L>_inc_le_opt] by auto\n\nlemma bounded_P: \"bounded (\\<P>\\<^sub>1 ` X)\"\n  by (auto simp: bounded_iff)\n\nsubsection \\<open>Solutions to the Optimality Equation\\<close>\nsubsubsection \\<open>@{const \\<L>\\<^sub>b} and @{const L} are Contraction Mappings\\<close>\ndeclare bounded_apply_blinfun[intro] bounded_apply_bfun'[intro]\n\nlemma contraction_\\<L>: \"dist (\\<L>\\<^sub>b v) (\\<L>\\<^sub>b u) \\<le> l * dist v u\"\nproof -\n  have \"dist (\\<L>\\<^sub>b v s) (\\<L>\\<^sub>b u s) \\<le> l * dist v u\" if \"\\<L>\\<^sub>b u s \\<le> \\<L>\\<^sub>b v s\" for s v u\n  proof -\n    have \"dist (\\<L>\\<^sub>b v s) (\\<L>\\<^sub>b u s) \\<le> (\\<Squnion>d \\<in> D\\<^sub>R. L d v s - L d u s)\"\n      using ex_dec that by (fastforce intro!: le_SUP_diff' simp: dist_real_def \\<L>\\<^sub>b.rep_eq \\<L>_def)\n    also have \"\\<dots> = (\\<Squnion>d \\<in> D\\<^sub>R. l * (\\<P>\\<^sub>1 d (v - u) s))\"\n      by (auto simp: L_def right_diff_distrib blinfun.diff_right)\n    also have \"\\<dots> = l * (\\<Squnion>d \\<in> D\\<^sub>R. \\<P>\\<^sub>1 d (v - u) s)\"\n      using D\\<^sub>R_ne bounded_P by (fastforce intro: bounded_SUP_mul)\n    also have \"\\<dots> \\<le> l * norm (\\<Squnion>d \\<in> D\\<^sub>R. \\<P>\\<^sub>1 d (v - u) s)\"\n      by (simp add: mult_left_mono)\n    also have \"\\<dots> \\<le> l * (\\<Squnion>d \\<in> D\\<^sub>R. norm ((\\<P>\\<^sub>1 d (v - u)) s))\"\n    proof -\n      have \"bounded ((\\<lambda>x. norm ((\\<P>\\<^sub>1 x (v - u)) s)) ` D\\<^sub>R)\"\n        using bounded_apply_bfun' bounded_P bounded_apply_blinfun bounded_norm_comp by metis\n      thus ?thesis\n        using D\\<^sub>R_ne ex_dec bounded_norm_comp by (fastforce intro!: mult_left_mono)\n    qed\n    also have \"\\<dots> \\<le> l * (\\<Squnion>p \\<in> D\\<^sub>R. norm (\\<P>\\<^sub>1 p ((v - u))))\"\n      using D\\<^sub>R_ne abs_le_norm_bfun bounded_P\n      by (fastforce simp: bounded_norm_comp intro!: bounded_imp_bdd_above mult_left_mono cSUP_mono)\n    also have \"\\<dots> \\<le> l * (\\<Squnion>p \\<in> D\\<^sub>R. norm ((v - u)))\"\n      using norm_push_exp_le_norm D\\<^sub>R_ne\n      by (fastforce simp: \\<P>\\<^sub>1.rep_eq intro!: mult_left_mono cSUP_mono)\n    also have \"\\<dots> = l * dist v u\"\n      by (auto simp: dist_norm)\n    finally show ?thesis .\n  qed\n  hence \"\\<L>\\<^sub>b u s \\<le> \\<L>\\<^sub>b v s \\<Longrightarrow> dist (\\<L>\\<^sub>b v s) (\\<L>\\<^sub>b u s) \\<le> l * dist v u\" \n    \"\\<L>\\<^sub>b v s \\<le> \\<L>\\<^sub>b u s \\<Longrightarrow> dist (\\<L>\\<^sub>b v s) (\\<L>\\<^sub>b u s) \\<le> l * dist v u\" for u v s\n    by (fastforce simp: dist_commute)+\n  thus ?thesis\n    using linear[of \"\\<L>\\<^sub>b u _\"] by (fastforce intro: dist_bound)\nqed\n\nlemma is_contraction_\\<L>: \"is_contraction \\<L>\\<^sub>b\"\n  using contraction_\\<L> zero_le_disc disc_lt_one unfolding is_contraction_def by blast\n\nlemma contraction_L: \"dist (L p v) (L p u) \\<le> l * dist v u\"\nproof -\n  have aux: \"L p v s - L p u s \\<le> l * dist v u\" if lea: \"L p v s \\<ge> L p u s\" for v s u\n  proof -\n    have \"L p v s - L p u s = (l *\\<^sub>R  (\\<P>\\<^sub>1 p v - \\<P>\\<^sub>1 p u)) s\"\n      by (simp add: L_def scale_right_diff_distrib)\n    also have \"\\<dots> \\<le> l * norm (\\<P>\\<^sub>1 p (v - u) s)\"\n      by (auto simp: blinfun.diff_right intro!: mult_left_mono)\n    also have \"\\<dots> \\<le> l * norm (\\<P>\\<^sub>1 p (v - u))\"\n      using abs_le_norm_bfun by (auto intro!: mult_left_mono)\n    also have \"\\<dots> \\<le> l * dist v u\"\n      by (simp add: \\<P>\\<^sub>1.rep_eq mult_left_mono norm_push_exp_le_norm dist_norm)\n    finally show ?thesis\n      by auto\n  qed\n  have \"dist (L p v s) (L p u s) \\<le> l * dist v u\" for v s u\n    using aux[of v _ u] aux[of u _ v]\n    by (cases \"L p v s \\<ge> L p u s\") (auto simp: dist_real_def dist_commute)\n  thus \"dist (L p v) (L p u) \\<le> l * dist v u\"\n    by (simp add: dist_bound)\nqed\n\nlemma is_contraction_L: \"is_contraction (L p)\"\n  unfolding is_contraction_def using contraction_L disc_lt_one zero_le_disc by blast\n\nsubsubsection \\<open>Existence of a Fixpoint of @{const \\<L>\\<^sub>b}\\<close>\nlemma \\<L>\\<^sub>b_conv:\n  \"\\<exists>!v. \\<L>\\<^sub>b v = v\" \"(\\<lambda>n. (\\<L>\\<^sub>b ^^ n) v) \\<longlonglongrightarrow> (THE v. \\<L>\\<^sub>b v = v)\"\n  using banach'[OF is_contraction_\\<L>] by auto\n\nlemma \\<L>\\<^sub>b_fix_iff_opt [simp]: \"\\<L>\\<^sub>b v = v \\<longleftrightarrow> v = \\<nu>\\<^sub>b_opt\"\n  using banach'(1) is_contraction_\\<L> \\<L>_fix_imp_opt by metis\n\nlemma \\<nu>\\<^sub>b_opt_fix: \"\\<nu>\\<^sub>b_opt = (THE v. \\<L>\\<^sub>b v = v)\"\n  by auto\n\nlemma \\<L>\\<^sub>b_opt [simp]: \"\\<L>\\<^sub>b \\<nu>\\<^sub>b_opt = \\<nu>\\<^sub>b_opt\"\n  by auto\n\nlemma \\<L>\\<^sub>b_lim: \"(\\<lambda>n. (\\<L>\\<^sub>b ^^ n) v) \\<longlonglongrightarrow> \\<nu>\\<^sub>b_opt\"\n  using \\<L>\\<^sub>b_conv(2) \\<nu>\\<^sub>b_opt_fix by presburger\n\nlemma thm_6_2_6: \"\\<nu>\\<^sub>b p = \\<nu>\\<^sub>b_opt \\<longleftrightarrow> \\<L>\\<^sub>b (\\<nu>\\<^sub>b p) = \\<nu>\\<^sub>b p\"\n  by force\n\nlemma thm_6_2_6': \"\\<nu> p = \\<nu>_opt \\<longleftrightarrow> \\<L>\\<^sub>b (\\<nu>\\<^sub>b p) = \\<nu>\\<^sub>b p\"\n  using thm_6_2_6 \\<nu>\\<^sub>b.rep_eq \\<nu>\\<^sub>b_opt.rep_eq by fastforce\n\nsubsection \\<open>Existence of Optimal Policies\\<close>\n\ndefinition \"\\<nu>_improving v d \\<longleftrightarrow> (\\<forall>s. is_arg_max (\\<lambda>d. (L d v) s) (\\<lambda>d. d \\<in> D\\<^sub>R) d)\"\n\nlemma \\<nu>_improving_iff: \"\\<nu>_improving v d \\<longleftrightarrow> d \\<in> D\\<^sub>R \\<and> (\\<forall>d' \\<in> D\\<^sub>R. \\<forall>s. L d' v s \\<le> L d v s)\"\n  by (auto simp: \\<nu>_improving_def is_arg_max_linorder)\n\nlemma \\<nu>_improving_D_MR[dest]: \"\\<nu>_improving v d \\<Longrightarrow> d \\<in> D\\<^sub>R\"\n  by (auto simp add: \\<nu>_improving_iff)\n\nlemma \\<nu>_improving_ge: \"\\<nu>_improving v d \\<Longrightarrow> d' \\<in> D\\<^sub>R \\<Longrightarrow> L d' v s \\<le> L d v s\"\n  by (auto simp: \\<nu>_improving_iff)\n\nlemma \\<nu>_improving_imp_\\<L>\\<^sub>b: \"\\<nu>_improving v d \\<Longrightarrow> \\<L>\\<^sub>b v = L d v\"\n  by (fastforce intro!: cSup_eq_maximum simp: \\<nu>_improving_iff \\<L>\\<^sub>b.rep_eq \\<L>_def)\n\nlemma \\<L>\\<^sub>b_imp_\\<nu>_improving: \n  assumes \"d \\<in> D\\<^sub>R\" \"\\<L>\\<^sub>b v = L d v\"\n  shows \"\\<nu>_improving v d\"\n  using assms L_le_\\<L>\\<^sub>b by (auto simp: \\<nu>_improving_iff assms(2)[symmetric])\n\nlemma \\<nu>_improving_alt:\n  assumes \"d \\<in> D\\<^sub>R\"\n  shows \"\\<nu>_improving v d \\<longleftrightarrow> \\<L>\\<^sub>b v = L d v\"\n  using \\<L>\\<^sub>b_imp_\\<nu>_improving \\<nu>_improving_imp_\\<L>\\<^sub>b assms by blast\n\ndefinition \"\\<nu>_conserving d = \\<nu>_improving (\\<nu>\\<^sub>b_opt) d\"\n\nlemma \\<nu>_conserving_iff: \"\\<nu>_conserving d \\<longleftrightarrow> d \\<in> D\\<^sub>R \\<and> (\\<forall>d' \\<in> D\\<^sub>R. \\<forall>s. L d' \\<nu>\\<^sub>b_opt s \\<le> L d \\<nu>\\<^sub>b_opt s)\"\n  by (auto simp: \\<nu>_conserving_def \\<nu>_improving_iff)\n\nlemma \\<nu>_conserving_ge: \"\\<nu>_conserving d \\<Longrightarrow> d' \\<in> D\\<^sub>R \\<Longrightarrow> L d' \\<nu>\\<^sub>b_opt s \\<le> L d \\<nu>\\<^sub>b_opt s\"\n  by (auto simp: \\<nu>_conserving_iff intro: \\<nu>_improving_ge)\n\nlemma \\<nu>_conserving_imp_\\<L>\\<^sub>b [simp]: \"\\<nu>_conserving d \\<Longrightarrow> L d \\<nu>\\<^sub>b_opt = \\<nu>\\<^sub>b_opt\"\n  using \\<nu>_improving_imp_\\<L>\\<^sub>b by (fastforce simp: \\<nu>_conserving_def)\n\nlemma \\<L>\\<^sub>b_imp_\\<nu>_conserving:\n  assumes \"d \\<in> D\\<^sub>R\" \"\\<L>\\<^sub>b \\<nu>\\<^sub>b_opt = L d \\<nu>\\<^sub>b_opt\"\n  shows \"\\<nu>_conserving d\"\n  using \\<L>\\<^sub>b_imp_\\<nu>_improving assms by (auto simp: \\<nu>_conserving_def)\n\nlemma \\<nu>_conserving_alt: \n  assumes \"d \\<in> D\\<^sub>R\"\n  shows \"\\<nu>_conserving d \\<longleftrightarrow> \\<L>\\<^sub>b \\<nu>\\<^sub>b_opt = L d \\<nu>\\<^sub>b_opt\"\n  unfolding \\<nu>_conserving_def using \\<nu>_improving_alt assms by auto\n\nlemma \\<nu>_conserving_alt':\n  assumes \"d \\<in> D\\<^sub>R\"\n  shows \"\\<nu>_conserving d \\<longleftrightarrow> L d \\<nu>\\<^sub>b_opt = \\<nu>\\<^sub>b_opt\"\n  using assms \\<nu>_conserving_alt by auto\n\nsubsubsection \\<open>Conserving Decision Rules are Optimal\\<close>\n\ntheorem ex_improving_imp_conserving:\n  assumes \"\\<And>v. \\<exists>d. \\<nu>_improving v (mk_dec_det d)\"\n  shows \"\\<exists>d. \\<nu>_conserving (mk_dec_det d)\"\n  by (simp add: assms \\<nu>_conserving_def)\n\ntheorem conserving_imp_opt[simp]:\n  assumes \"\\<nu>_conserving (mk_dec_det d)\"\n  shows \"\\<nu>\\<^sub>b (mk_stationary_det d) = \\<nu>\\<^sub>b_opt\"\n  using L_\\<nu>_fix_iff \\<nu>_conserving_imp_\\<L>\\<^sub>b[OF assms] by simp\n\nlemma conserving_imp_opt':\n  assumes \"\\<exists>d. \\<nu>_conserving (mk_dec_det d)\"\n  shows \"\\<exists>d \\<in> D\\<^sub>D. (\\<nu>\\<^sub>b (mk_stationary_det d)) = \\<nu>\\<^sub>b_opt\"\n  using assms by (fastforce simp: \\<nu>_conserving_def)\n\ntheorem improving_att_imp_det_opt:\n  assumes \"\\<And>v. \\<exists>d. \\<nu>_improving v (mk_dec_det d)\"\n  shows \"\\<nu>\\<^sub>b_opt s = (\\<Squnion>d \\<in> D\\<^sub>D. \\<nu>\\<^sub>b (mk_stationary_det d) s)\"\nproof -\n  obtain d where d: \"\\<nu>_conserving (mk_dec_det d)\"\n    using assms ex_improving_imp_conserving by auto\n  hence \"d \\<in> D\\<^sub>D\"\n    using \\<nu>_conserving_iff is_dec_mk_dec_det_iff by blast\n  thus ?thesis\n    using \\<Pi>\\<^sub>M\\<^sub>R_imp_policies \\<nu>\\<^sub>b_le_opt\n    by (fastforce intro!: cSup_eq_maximum[where z = \"\\<nu>\\<^sub>b_opt s\", symmetric]\n        simp: conserving_imp_opt[OF d] image_iff)\nqed\n\n\nlemma \\<L>\\<^sub>b_sup_att_dec:\n  assumes \"d \\<in> D\\<^sub>R\" \"\\<L>\\<^sub>b v = L d v\"\n  shows \"\\<exists>d' \\<in> D\\<^sub>D. \\<L>\\<^sub>b v = L (mk_dec_det d') v\"\nproof -\n  have \"\\<exists>a\\<in> A s. L d v s = L\\<^sub>a a v s\" for s\n    unfolding L_eq_L\\<^sub>a\n    using assms is_dec_def L\\<^sub>a_bounded A_ne \\<L>\\<^sub>b.rep_eq \\<L>_def\n    by (intro lemma_4_3_1') \n      (auto intro: bounded_range_subset simp: assms(2)[symmetric] L_eq_L\\<^sub>a[symmetric] SUP_step_MR_eq)\n  then obtain d' where d: \"d' s \\<in> A s\" \"L d v s = L\\<^sub>a (d' s) v s\" for s\n    by metis\n  thus ?thesis\n    using assms d\n    by (fastforce simp: is_dec_det_def mk_dec_det_def L_eq_L\\<^sub>a)\nqed\n\nlemma \\<L>\\<^sub>b_sup_att_dec':\n  assumes \"d \\<in> D\\<^sub>R\" \"\\<L>\\<^sub>b v = L d v\"\n  shows \"\\<exists>d' \\<in> D\\<^sub>D. \\<nu>_improving v (mk_dec_det d')\"\n  using \\<L>\\<^sub>b_sup_att_dec \\<nu>_improving_alt assms by force\n\nsubsubsection \\<open>Deterministic Decision Rules are Optimal\\<close>\n\nlemma opt_imp_opt_dec_det:\n  assumes \"p \\<in> \\<Pi>\\<^sub>H\\<^sub>R\" \"\\<nu>\\<^sub>b p = \\<nu>\\<^sub>b_opt\" \n  shows \"\\<exists>d \\<in> D\\<^sub>D. \\<nu>\\<^sub>b (mk_stationary_det d) = \\<nu>\\<^sub>b_opt\"\nproof -\n  have aux: \"L (as_markovian p (return_pmf s) 0) \\<nu>\\<^sub>b_opt s = \\<nu>\\<^sub>b_opt s\" for s\n  proof -\n    let ?ps = \"as_markovian p (return_pmf s)\"\n    have markovian_suc_le: \"\\<nu>\\<^sub>b (mk_markovian (\\<lambda>n. as_markovian p (return_pmf s) (Suc n))) \\<le> \\<nu>\\<^sub>b_opt\"\n      using is_\\<Pi>\\<^sub>M\\<^sub>R_as_markovian assms by (auto simp: is_policy_def mk_markovian_def)\n    have aux_le: \"\\<And>x f g. f \\<le> g \\<Longrightarrow> apply_bfun f x \\<le> apply_bfun g x\"\n      unfolding less_eq_bfun_def by auto\n    have \"\\<nu>\\<^sub>b_opt s = \\<nu>\\<^sub>b (mk_markovian ?ps) s\"\n      using assms \\<nu>\\<^sub>b_as_markovian by metis\n    also have \"\\<dots> = L (?ps 0) (\\<nu>\\<^sub>b (mk_markovian (\\<lambda>n. ?ps (Suc n)))) s\"\n      using \\<nu>_step by blast\n    also have \"\\<dots> \\<le> L (?ps 0) (\\<nu>\\<^sub>b_opt) s\"\n      unfolding L_def using markovian_suc_le \\<P>\\<^sub>1_mono by (auto intro!: mult_left_mono)\n    finally have \"\\<nu>\\<^sub>b_opt s \\<le> L (?ps 0) (\\<nu>\\<^sub>b_opt) s\" .\n    have \"as_markovian p (return_pmf s) 0 \\<in> D\\<^sub>R\"\n      using is_\\<Pi>\\<^sub>M\\<^sub>R_as_markovian assms by fast\n    have \"L (?ps 0) \\<nu>\\<^sub>b_opt \\<le> \\<nu>\\<^sub>b_opt\"\n      using \\<open>?ps 0 \\<in> D\\<^sub>R\\<close> L_le_\\<L>\\<^sub>b[of \"?ps 0\" \"\\<nu>\\<^sub>b_opt\"] by simp\n    thus \"L (?ps 0) \\<nu>\\<^sub>b_opt s = \\<nu>\\<^sub>b_opt s\"\n      using \\<open>\\<nu>\\<^sub>b_opt s \\<le> (L (?ps 0) \\<nu>\\<^sub>b_opt) s\\<close> by (auto intro!: antisym)\n  qed\n  have \"L (p []) v s = L (as_markovian p (return_pmf s) 0) v s\" for v s\n    by (auto simp: L_def \\<P>\\<^sub>1.rep_eq K_st_def)\n  hence \"L (p []) \\<nu>\\<^sub>b_opt = \\<nu>\\<^sub>b_opt\"\n    using aux by auto\n  hence \"\\<exists>d \\<in> D\\<^sub>D. L (mk_dec_det d) \\<nu>\\<^sub>b_opt = \\<nu>\\<^sub>b_opt\"\n    using \\<L>\\<^sub>b_sup_att_dec assms(1) \\<L>\\<^sub>b_opt is_policy_def mem_Collect_eq by metis\n  thus ?thesis\n    using conserving_imp_opt' \\<nu>_conserving_alt' by blast\nqed\n\nsubsubsection \\<open>Optimal Decision Rules for Finite Action Spaces\\<close>\n\n(* 6.2.10 *)\nlemma ex_opt_act: \nassumes \"\\<And>s. finite (A s)\"\nshows \"\\<exists>a \\<in> A s. L\\<^sub>a a (v :: _ \\<Rightarrow>\\<^sub>b _) s = \\<L>\\<^sub>b v s\"\n      unfolding \\<L>\\<^sub>b.rep_eq \\<L>_eq_SUP_det SUP_step_det_eq\n      using arg_max_on_in[OF assms A_ne]\n      by (auto simp: cSup_eq_Sup_fin Sup_fin_Max assms A_ne finite_arg_max_eq_Max[symmetric])\n\nlemma ex_opt_dec_det:\nassumes \"\\<And>s. finite (A s)\"\nshows \"\\<exists>d \\<in> D\\<^sub>D. L (mk_dec_det d) (v :: _ \\<Rightarrow>\\<^sub>b _) = \\<L>\\<^sub>b v\"\n  unfolding is_dec_det_def mk_dec_det_def\n  using ex_opt_act[OF assms]  someI_ex\n  apply (auto intro!: exI[of _ \\<open>\\<lambda>s. SOME a. a \\<in> A s \\<and> L\\<^sub>a a v s = \\<L>\\<^sub>b v s\\<close>] bfun_eqI)\n   apply (smt (verit, best) someI_ex)\n  apply (subst L_eq_L\\<^sub>a)\n  apply (subst expectation_return_pmf)\n  by (smt (verit, best) someI_ex)\n\nlemma thm_6_2_10:\n  assumes \"\\<And>s. finite (A s)\"\n  shows \"\\<exists>d \\<in> D\\<^sub>D. \\<nu>\\<^sub>b_opt = \\<nu>\\<^sub>b (mk_stationary_det d)\"\n  using assms conserving_imp_opt' \\<L>\\<^sub>b_opt L_\\<nu>_fix_iff ex_opt_dec_det \n  by metis\n\nsubsubsection \\<open>Existence of Epsilon-Optimal Policies\\<close>\n\nlemma ex_det_eps:\n  assumes \"0 < e\"\n  shows \"\\<exists>d \\<in> D\\<^sub>D. \\<L>\\<^sub>b v \\<le> L (mk_dec_det d) v + e *\\<^sub>R 1\"\nproof -\n  have \"\\<exists>a \\<in> A s. \\<L>\\<^sub>b v s \\<le> L\\<^sub>a a v s + e\" for s\n  proof -\n    have \"bdd_above ((\\<lambda>a. L\\<^sub>a a v s) ` A s)\"\n      using L\\<^sub>a_le by (auto intro!: boundedI bounded_imp_bdd_above)\n    hence \"\\<exists>a \\<in> A s. \\<L>\\<^sub>b v s - e < L\\<^sub>a a v s\"\n      unfolding \\<L>\\<^sub>b.rep_eq \\<L>_eq_SUP_det SUP_step_det_eq\n      by (auto simp: less_cSUP_iff[OF A_ne, symmetric] \\<open>0 < e\\<close>)\n    thus \"\\<exists>a \\<in> A s. \\<L>\\<^sub>b v s \\<le> L\\<^sub>a a v s + e\"\n      by force\n  qed\n  thus ?thesis\n    unfolding mk_dec_det_def is_dec_det_def\n    by (auto simp: L_def \\<P>\\<^sub>1.rep_eq bind_return_pmf K_st_def less_eq_bfun_def) metis\nqed\n\nlemma thm_6_2_11:\n  assumes \"eps > 0\"\n  shows \"\\<exists>d \\<in> D\\<^sub>D. \\<nu>\\<^sub>b_opt \\<le> \\<nu>\\<^sub>b (mk_stationary_det d) + eps *\\<^sub>R 1\"\nproof -\n  have \"(1-l) * eps > 0\"\n    by (simp add: assms)\n  then obtain d where \"d \\<in> D\\<^sub>D\" and d: \"\\<L>\\<^sub>b \\<nu>\\<^sub>b_opt \\<le> L (mk_dec_det d) \\<nu>\\<^sub>b_opt + ((1-l)*eps) *\\<^sub>R 1\"\n    using ex_det_eps[of _ \\<nu>\\<^sub>b_opt] by auto\n  let ?d = \"mk_dec_det d\"\n  let ?lK = \"l *\\<^sub>R \\<P>\\<^sub>1 ?d\"\n  let ?lK_opt = \"l *\\<^sub>R \\<P>\\<^sub>1 ?d \\<nu>\\<^sub>b_opt\"\n  have \"\\<nu>\\<^sub>b_opt  \\<le> r_dec\\<^sub>b ?d + ?lK_opt + ((1-l)*eps) *\\<^sub>R 1\"\n    using L_def \\<L>_fix_imp_opt d by simp\n  hence \"\\<nu>\\<^sub>b_opt - ?lK_opt - ((1-l)*eps) *\\<^sub>R 1 \\<le> r_dec\\<^sub>b ?d\"\n    by (simp add: cancel_ab_semigroup_add_class.diff_right_commute diff_le_eq)\n  hence \"(\\<Sum>i. ?lK ^^ i) (\\<nu>\\<^sub>b_opt - ?lK_opt - ((1-l)*eps) *\\<^sub>R 1) \\<le> \\<nu>\\<^sub>b (mk_stationary ?d)\"\n    using lemma_6_1_2_b suminf_cong by (simp add: blincomp_scaleR_right \\<nu>_stationary)\n  hence \"((\\<Sum>i. ?lK ^^ i) o\\<^sub>L (id_blinfun - ?lK)) \\<nu>\\<^sub>b_opt - (\\<Sum>i. ?lK ^^ i) (((1-l)*eps) *\\<^sub>R 1) \n    \\<le> (\\<nu>\\<^sub>b (mk_stationary ?d))\"\n    by (simp add: blinfun.diff_right blinfun.diff_left blinfun.scaleR_left)\n  hence le: \"\\<nu>\\<^sub>b_opt - (\\<Sum>i. ?lK ^^ i) (((1-l)*eps) *\\<^sub>R 1) \\<le> \\<nu>\\<^sub>b (mk_stationary ?d)\"\n    by (auto simp: inv_norm_le')\n  have s: \"summable (\\<lambda>i. (l *\\<^sub>R \\<P>\\<^sub>1 ?d)^^i)\"\n    using convergent_disc_\\<P>\\<^sub>1 summable_iff_convergent'\n    by (simp add: blincomp_scaleR_right summable_iff_convergent')\n  have \"(\\<Sum>i. ?lK ^^ i) (((1-l)*eps) *\\<^sub>R 1) = eps *\\<^sub>R 1\"\n  proof -\n    have \"(\\<Sum>i. ?lK ^^ i) (((1-l)*eps) *\\<^sub>R 1) = ((1-l)*eps) *\\<^sub>R (\\<Sum>i. ?lK^^i) 1\"\n      using blinfun.scaleR_right by blast\n    also have \"\\<dots> = ((1-l)*eps) *\\<^sub>R (\\<Sum>i. (?lK^^i) 1) \"\n      using s by (auto simp: bounded_linear.suminf[of \"\\<lambda>x. blinfun_apply x 1\"])\n    also have \"\\<dots> = ((1-l)*eps) *\\<^sub>R (\\<Sum>i. (l ^ i)) *\\<^sub>R 1\"\n      by (auto simp: blinfun.scaleR_left blincomp_scaleR_right bounded_linear_scaleR_left \n          bounded_linear.suminf[of \"\\<lambda>x. x *\\<^sub>R 1\"])\n    also have \"\\<dots> = ((1-l)*eps) *\\<^sub>R (1 / (1-l)) *\\<^sub>R 1\"\n      by (simp add: suminf_geometric)\n    also have \"\\<dots> = eps *\\<^sub>R 1\"\n      using disc_lt_one \\<open>0 < (1 - l) * eps\\<close> by auto\n    finally show ?thesis .\n  qed\n  thus ?thesis\n    using \\<open>d \\<in> D\\<^sub>D\\<close> diff_le_eq le\n    by auto\nqed\n\nlemma ex_det_dist_eps:\n  assumes \"0 < (e :: real)\"\n  shows \"\\<exists>d \\<in> D\\<^sub>D. dist (\\<L>\\<^sub>b v) (L (mk_dec_det d) v) \\<le> e\"\nproof -\n  obtain d where \"d \\<in> D\\<^sub>D\" \"L (mk_dec_det d) v \\<le> (\\<L>\\<^sub>b v)\" \n    and h2: \"\\<L>\\<^sub>b v \\<le> L (mk_dec_det d) v + e *\\<^sub>R 1\"\n    using assms ex_det_eps L_le_\\<L>\\<^sub>b by blast\n  hence \"0 \\<le> \\<L>\\<^sub>b v -  L (mk_dec_det d) v\"\n    by simp\n  moreover have \"\\<L>\\<^sub>b v - L (mk_dec_det d) v \\<le> e *\\<^sub>R 1\"\n    using h2 by (simp add: add.commute diff_le_eq)\n  ultimately have \"\\<forall>s. \\<bar>(\\<L>\\<^sub>b v) s -  L (mk_dec_det d) v s\\<bar> \\<le> e\"\n    unfolding less_eq_bfun_def by auto\n  hence \"dist (\\<L>\\<^sub>b v) (L (mk_dec_det d) v) \\<le> e\"\n    unfolding dist_bfun.rep_eq by (auto intro!: cSUP_least simp: dist_real_def)\n  thus ?thesis\n    using \\<open>d \\<in> D\\<^sub>D\\<close> \n    by auto\nqed\n\nlemma less_imp_ex_add_le: \"(x :: real) < y \\<Longrightarrow> \\<exists>eps>0. x + eps \\<le> y\"\n  by (meson field_le_epsilon less_le_not_le nle_le)\n\nlemma \\<nu>\\<^sub>b_opt_le_det: \"\\<nu>\\<^sub>b_opt s \\<le> (\\<Squnion>d \\<in> D\\<^sub>D. \\<nu>\\<^sub>b (mk_stationary_det d) s)\"\nproof (subst le_cSUP_iff, safe)\n  fix y\n  assume \"y < \\<nu>\\<^sub>b_opt s\"\n  then obtain eps where 1: \"y \\<le> \\<nu>\\<^sub>b_opt s - eps\" and \"eps > 0\"\n    using less_imp_ex_add_le by force\n  hence \"eps / 2 > 0\" by auto\n  obtain d where \"d \\<in> D\\<^sub>D\" and \"\\<nu>\\<^sub>b_opt s \\<le> \\<nu>\\<^sub>b (mk_stationary_det d) s + eps / 2\"\n    using thm_6_2_11[OF \\<open>eps / 2 > 0\\<close>] by fastforce\n  hence \"y < \\<nu>\\<^sub>b (mk_stationary_det d) s\"\n    using \\<open>eps > 0\\<close> by (auto simp: diff_less_eq intro: le_less_trans[OF 1])\n  thus \"\\<exists>i\\<in>D\\<^sub>D. y < \\<nu>\\<^sub>b (mk_stationary_det i) s\"\n    using \\<open>d \\<in> D\\<^sub>D\\<close> by blast\nnext\n  show \"D\\<^sub>D = {} \\<Longrightarrow> False\"\n    using D_det_ne by blast\n  show \"bdd_above ((\\<lambda>d. \\<nu>\\<^sub>b (mk_stationary_det d) s) ` D\\<^sub>D)\"\n    by (auto intro!: bounded_imp_bdd_above boundedI abs_\\<nu>_le simp: \\<nu>\\<^sub>b.rep_eq)\nqed\n\nlemma \\<nu>\\<^sub>b_opt_eq_det: \"\\<nu>\\<^sub>b_opt s = (\\<Squnion>d \\<in> D\\<^sub>D. \\<nu>\\<^sub>b (mk_stationary_det d) s)\"\n  using \\<nu>\\<^sub>b_le_opt_DD D_det_ne\n  by (fastforce intro!: antisym[OF \\<nu>\\<^sub>b_opt_le_det] cSUP_least)\n\n(* unused, delete? *)\nlemma lemma_6_3_1_a:\n  assumes \"v0 \\<in> bfun\"\n  shows \"uniform_limit UNIV (\\<lambda>n. ((\\<lambda>v. \\<L> (Bfun v)) ^^ n) v0) \\<nu>_opt sequentially\"\nproof -\n  have \\<L>_Bfun_eq: \"v0 \\<in> bfun \\<Longrightarrow> ((\\<lambda>v. \\<L> (Bfun v))^^n) v0 = (\\<L>\\<^sub>b ^^n) (Bfun v0)\" for n\n    by (induction n) (auto simp: \\<L>\\<^sub>b.rep_eq apply_bfun_inverse)\n  have \"uniform_limit UNIV (\\<lambda>n. (\\<L>\\<^sub>b ^^ n) (Bfun v0)) \\<nu>\\<^sub>b_opt sequentially\"\n    by (intro tendsto_bfun_uniform_limit[OF \\<L>\\<^sub>b_lim])\n  hence \"uniform_limit UNIV (\\<lambda>n. (\\<L>\\<^sub>b ^^ n) (Bfun v0)) \\<nu>_opt sequentially\"\n    by (simp add: \\<nu>_opt_bfun \\<nu>\\<^sub>b_opt.rep_eq)\n  thus ?thesis\n    by (auto simp: assms \\<L>_Bfun_eq)\nqed\n\nlemma dist_Suc_tendsto_zero:\n  assumes \"(\\<lambda>n. f n) \\<longlonglongrightarrow> (y::_::real_normed_vector)\"\n  shows \"(\\<lambda>n. dist (f n) (f (Suc n))) \\<longlonglongrightarrow> 0\"\n  using assms tendsto_diff tendsto_norm LIMSEQ_Suc by (fastforce simp: dist_norm)\n\nlemma dist_\\<L>\\<^sub>b_tendsto: \"(\\<lambda>n. dist ((\\<L>\\<^sub>b^^n) v) ((\\<L>\\<^sub>b^^(Suc n)) v)) \\<longlonglongrightarrow> 0\"\n  using \\<L>\\<^sub>b_lim by (fast intro!: dist_Suc_tendsto_zero)\n\ndefinition \"max_L_ex s v \\<equiv> has_arg_max (\\<lambda>a. L\\<^sub>a a v s) (A s)\"\n\nlemma \\<nu>\\<^sub>b_fin_zero[simp]: \"\\<nu>\\<^sub>b_fin p 0 = 0\"\n  by (auto simp: \\<nu>\\<^sub>b_fin.rep_eq)\n\nlemma \\<nu>\\<^sub>b_fin_Suc[simp]: \n  \"\\<nu>\\<^sub>b_fin (mk_stationary d) (Suc n) = \\<nu>\\<^sub>b_fin (mk_stationary d) n + ((l *\\<^sub>R \\<P>\\<^sub>1 d)^^ n) (r_dec\\<^sub>b d)\"\n  by (auto simp: \\<P>\\<^sub>X_sconst \\<nu>\\<^sub>b_fin.rep_eq \\<nu>_fin_eq_\\<P>\\<^sub>X blincomp_scaleR_right blinfun.scaleR_left)\n\nlemma \\<nu>\\<^sub>b_fin_eq: \"\\<nu>\\<^sub>b_fin (mk_stationary d) n = (\\<Sum>i < n. ((l *\\<^sub>R \\<P>\\<^sub>1 d)^^ i)) (r_dec\\<^sub>b d)\"\n  by (induction n) (auto simp add: plus_blinfun.rep_eq)\n\nlemma L_iter: \"(L d ^^ m) v = \\<nu>\\<^sub>b_fin (mk_stationary d) m + ((l *\\<^sub>R \\<P>\\<^sub>1 d)^^ m) v\"\nproof (induction m arbitrary: v)\n  case (Suc m)\n  have \"(L d ^^ Suc m) v = (L d ^^ m) (L d v)\"\n    by (simp add: funpow_Suc_right del: funpow.simps)\n  also have \"\\<dots> = \\<nu>\\<^sub>b_fin (mk_stationary d) m + ((l *\\<^sub>R \\<P>\\<^sub>1 d) ^^ m) (L d v)\"\n    using Suc by simp\n  also have \"\\<dots> = \\<nu>\\<^sub>b_fin (mk_stationary d) (Suc m) + ((l *\\<^sub>R \\<P>\\<^sub>1 d) ^^ Suc m) v\"\n    unfolding L_def \n    by (auto simp: \\<P>\\<^sub>1_pow blinfun.bilinear_simps blincomp_scaleR_right funpow_swap1) \n  finally show ?case .\nqed simp\n\nlemma bounded_stationary_\\<nu>\\<^sub>b_fin: \"bounded ((\\<lambda>x. (\\<nu>\\<^sub>b_fin (mk_stationary x) N) s) ` X)\"\n  using \\<nu>\\<^sub>b_fin.rep_eq abs_\\<nu>_fin_le by (auto intro!: boundedI)\n\nlemma bounded_disc_\\<P>\\<^sub>1: \"bounded ((\\<lambda>x. (((l *\\<^sub>R \\<P>\\<^sub>1 x) ^^ m) v) s) ` X)\"\n  by (auto simp: \\<P>\\<^sub>X_const[symmetric] blinfun.bilinear_simps blincomp_scaleR_right \n      intro!: boundedI[of _  \"l ^ m * norm v\"] mult_left_mono order.trans[OF abs_le_norm_bfun])\n\nlemma bounded_disc_\\<P>\\<^sub>1': \"bounded ((\\<lambda>x. ((\\<P>\\<^sub>1 x ^^ m) v) s) ` X)\"\n  by (auto simp: \\<P>\\<^sub>X_const[symmetric] intro!: boundedI[of _  \"norm v\"] order.trans[OF abs_le_norm_bfun])\n\nlemma L_iter_le_\\<L>\\<^sub>b: \"is_dec d \\<Longrightarrow> (L d ^^ n) v \\<le> (\\<L>\\<^sub>b ^^ n) v\"\n  using order_trans[OF L_mono L_le_\\<L>\\<^sub>b] by (induction n) auto\n\nend\n\nsubsection \\<open>More Restrictive MDP Locales\\<close>\nlocale MDP_fin_acts = discrete_MDP +\n  assumes \"\\<And>s. finite (A s)\"\n\nlocale MDP_att_\\<L> = MDP_reward_disc A K r l\n  for\n    A and \n    K :: \"'s ::countable \\<times> 'a ::countable \\<Rightarrow> 's pmf\" and\n    r and l +\n  assumes Sup_att: \"max_L_ex (s :: 's) v\"\nbegin\ntheorem \\<L>\\<^sub>b_eq_argmax_L\\<^sub>a:\n  fixes v :: \"'s \\<Rightarrow>\\<^sub>b real\"\n  assumes \"is_arg_max (\\<lambda>a. L\\<^sub>a a v s) (\\<lambda>a. a \\<in> A s) a\"\n  shows \"\\<L>\\<^sub>b v s = L\\<^sub>a a v s\"\n  using L\\<^sub>a_le assms A_ne \\<L>\\<^sub>b.rep_eq \\<L>_eq_SUP_det SUP_step_det_eq\n  by (auto intro!: cSUP_upper2 antisym cSUP_least simp: is_arg_max_linorder)\n\nlemma L\\<^sub>a_le_arg_max: \"a \\<in> A s \\<Longrightarrow> L\\<^sub>a a v s \\<le> L\\<^sub>a (arg_max_on (\\<lambda>a. L\\<^sub>a a v s) (A s)) v s\"\n  using Sup_att app_arg_max_ge[OF Sup_att[unfolded max_L_ex_def]]\n  by (simp add: arg_max_on_def)\n\nlemma arg_max_on_in: \"has_arg_max f Q \\<Longrightarrow> arg_max_on f Q \\<in> Q\"\n  using has_arg_max_arg_max by (auto simp: arg_max_on_def)\n\nlemma \\<L>\\<^sub>b_eq_L\\<^sub>a_max: \"\\<L>\\<^sub>b v s = L\\<^sub>a (arg_max_on (\\<lambda>a. L\\<^sub>a a v s) (A s)) v s\"\n  using app_arg_max_eq_SUP[symmetric] Sup_att max_L_ex_def \n  by (auto simp: \\<L>\\<^sub>b_eq_SUP_det SUP_step_det_eq)\n\nlemma ex_opt_det: \"\\<exists>d \\<in> D\\<^sub>D. \\<L>\\<^sub>b v = L (mk_dec_det d) v\"\nproof -\n  define d where \"d = (\\<lambda>s. arg_max_on (\\<lambda>a. L\\<^sub>a a v s) (A s))\"\n  have \"\\<L>\\<^sub>b v s = L (mk_dec_det d) v s\" for s\n    by (auto simp: d_def \\<L>\\<^sub>b_eq_L\\<^sub>a_max L_eq_L\\<^sub>a_det)\n  moreover have \"d \\<in> D\\<^sub>D\"\n    using Sup_att arg_max_on_in by (auto simp: d_def is_dec_det_def max_L_ex_def)\n  ultimately show ?thesis\n    by auto\nqed\n\nlemma ex_improving_det: \"\\<exists>d \\<in> D\\<^sub>D. \\<nu>_improving v (mk_dec_det d)\"\n  using \\<nu>_improving_alt ex_opt_det by auto\nend\n\nlocale MDP_act = discrete_MDP A K for A :: \"'s::countable \\<Rightarrow> 'a::countable set\" and K +\n  fixes arb_act ::  \"'a set \\<Rightarrow> 'a\"\n  assumes arb_act_in[simp]: \"X \\<noteq> {} \\<Longrightarrow> arb_act X \\<in> X\" \n\nlocale MDP_act_disc = MDP_act A K + MDP_att_\\<L> A K r l\n  for A :: \"'s::countable \\<Rightarrow> 'a::countable set\" and K r l\nbegin\n\n\nlemma is_opt_act_some: \"is_opt_act v s (arb_act (opt_acts v s))\"\n  using arb_act_in[of \"{a. is_arg_max (\\<lambda>a. L\\<^sub>a a v s) (\\<lambda>a. a \\<in> A s) a}\"] Sup_att has_arg_max_def\n  unfolding max_L_ex_def is_opt_act_def by auto\n\nlemma some_opt_acts_in_A: \"arb_act (opt_acts v s) \\<in> A s\"\n  using is_opt_act_some unfolding is_opt_act_def is_arg_max_def by auto\n\nlemma \\<nu>_improving_opt_acts: \"\\<nu>_improving v0 (mk_dec_det (\\<lambda>s. arb_act (opt_acts (apply_bfun v0) s)))\"\n  using is_opt_act_def is_opt_act_some some_opt_acts_in_A\n  by (subst \\<nu>_improving_alt) (fastforce simp: L_eq_L\\<^sub>a_det \\<L>\\<^sub>b_eq_argmax_L\\<^sub>a is_dec_det_def)+\n\nend\n\nlocale MDP_finite_type = MDP_reward_disc A K r l\n  for A and K :: \"'s :: finite \\<times> 'a :: finite \\<Rightarrow> 's pmf\" and r l\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/MDP-Rewards/MDP_reward.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9059898279984214, "lm_q2_score": 0.815232480373843, "lm_q1q2_score": 0.7385923346726245}}
{"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_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_with_Proof/TIP15/TIP15/TIP_sort_nat_HSortIsSort.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094145755219, "lm_q2_score": 0.8267117983401363, "lm_q1q2_score": 0.7385094325979041}}
{"text": "(*  Title:      HOL/Algebra/Solvable_Groups.thy\n    Author:     Paulo Em\u00edlio de Vilhena\n*)\n\ntheory Solvable_Groups\n  imports Generated_Groups\n    \nbegin\n\nsection \\<open>Solvable Groups\\<close>\n\nsubsection \\<open>Definitions\\<close>\n\ninductive solvable_seq :: \"('a, 'b) monoid_scheme \\<Rightarrow> 'a set \\<Rightarrow> bool\"\n  for G where\n    unity: \"solvable_seq G { \\<one>\\<^bsub>G\\<^esub> }\"\n  | extension: \"\\<lbrakk> solvable_seq G K; K \\<lhd> (G \\<lparr> carrier := H \\<rparr>); subgroup H G;\n                  comm_group ((G \\<lparr> carrier := H \\<rparr>) Mod K) \\<rbrakk> \\<Longrightarrow> solvable_seq G H\"\n\ndefinition solvable :: \"('a, 'b) monoid_scheme \\<Rightarrow> bool\"\n  where \"solvable G \\<longleftrightarrow> solvable_seq G (carrier G)\"\n\n\nsubsection \\<open>Solvable Groups and Derived Subgroups\\<close>\n\ntext \\<open>We show that a group G is solvable iff the subgroup (derived G ^^ n) (carrier G)\n      is trivial for a sufficiently large n. \\<close>\n\nlemma (in group) solvable_imp_subgroup:\n  assumes \"solvable_seq G H\" shows \"subgroup H G\"\n  using assms normal.axioms(1)[OF one_is_normal] by (induction) (auto)\n\nlemma (in group) augment_solvable_seq:\n  assumes \"subgroup H G\" and \"solvable_seq G (derived G H)\" shows \"solvable_seq G H\"\n  using extension[OF _ derived_subgroup_is_normal _ derived_quot_of_subgroup_is_comm_group] assms by simp\n\ntheorem (in group) trivial_derived_seq_imp_solvable:\n  assumes \"subgroup H G\" and \"((derived G) ^^ n) H = { \\<one> }\" shows \"solvable_seq G H\"\n  using assms\nproof (induct n arbitrary: H, simp add: unity[of G])\n  case (Suc n) thus ?case\n    using augment_solvable_seq derived_is_subgroup[OF subgroup.subset] by (simp add: funpow_swap1)\nqed\n\ntheorem (in group) solvable_imp_trivial_derived_seq:\n  assumes \"solvable_seq G H\" shows \"\\<exists>n. (derived G ^^ n) H = { \\<one> }\"\n  using assms\nproof (induction)\n  case unity\n  have \"(derived G ^^ 0) { \\<one> } = { \\<one> }\"\n    by simp\n  thus ?case by blast\nnext\n  case (extension K H)\n  obtain n where \"(derived G ^^ n) K = { \\<one> }\"\n    using solvable_imp_subgroup extension(1,5) by auto\n  hence \"(derived G ^^ (Suc n)) H \\<subseteq> { \\<one> }\"\n    using mono_exp_of_derived[OF derived_of_subgroup_minimal[OF extension(2-4)], of n] by (simp add: funpow_swap1)\n  moreover have \"{ \\<one> } \\<subseteq> (derived G ^^ (Suc n)) H\"\n    using subgroup.one_closed[OF exp_of_derived_is_subgroup[OF extension(3)], of \"Suc n\"] by auto\n  ultimately show ?case\n    by blast\nqed\n\ntheorem (in group) solvable_iff_trivial_derived_seq:\n  \"solvable G \\<longleftrightarrow> (\\<exists>n. (derived G ^^ n) (carrier G) = { \\<one> })\"\n  using solvable_imp_trivial_derived_seq subgroup_self trivial_derived_seq_imp_solvable\n  by (auto simp add: solvable_def)\n\ncorollary (in group) solvable_subgroup:\n  assumes \"subgroup H G\" and \"solvable G\" shows \"solvable_seq G H\"\nproof -\n  obtain n where n: \"(derived G ^^ n) (carrier G) = { \\<one> }\"\n    using assms(2) solvable_imp_trivial_derived_seq by (auto simp add: solvable_def)\n  show ?thesis\n  proof (rule trivial_derived_seq_imp_solvable[OF assms(1), of n])\n    show \"(derived G ^^ n) H = { \\<one> }\"\n      using subgroup.one_closed[OF exp_of_derived_is_subgroup[OF assms(1)], of n]\n            mono_exp_of_derived[OF subgroup.subset[OF assms(1)], of n] n\n      by auto\n  qed\nqed\n\n\nsubsection \\<open>Short Exact Sequences\\<close>\n\ntext \\<open>Even if we don't talk about short exact sequences explicitly, we show that given an\n      injective homomorphism from a group H to a group G, if H isn't solvable the group G\n      isn't neither. \\<close>\n\ntheorem (in group_hom) solvable_img_imp_solvable:\n  assumes \"subgroup K G\" and \"inj_on h K\" and \"solvable_seq H (h ` K)\" shows \"solvable_seq G K\"\nproof -\n  obtain n where \"(derived H ^^ n) (h ` K) = { \\<one>\\<^bsub>H\\<^esub> }\"\n    using solvable_imp_trivial_derived_seq assms(1,3) by auto\n  hence \"h ` ((derived G ^^ n) K) = { \\<one>\\<^bsub>H\\<^esub> }\"\n    unfolding exp_of_derived_img[OF subgroup.subset[OF assms(1)]] .\n  moreover have \"(derived G ^^ n) K \\<subseteq> K\"\n    using G.mono_derived[of _ K] G.derived_incl[OF _ assms(1)] by (induct n) (auto)\n  hence \"inj_on h ((derived G ^^ n) K)\"\n    using inj_on_subset[OF assms(2)] by blast\n  moreover have \"{ \\<one> } \\<subseteq> (derived G ^^ n) K\"\n    using subgroup.one_closed[OF G.exp_of_derived_is_subgroup[OF assms(1)]] by blast\n  ultimately show ?thesis\n    using G.trivial_derived_seq_imp_solvable[OF assms(1), of n]\n    by (metis (no_types, lifting) hom_one image_empty image_insert inj_on_image_eq_iff order_refl)\nqed\n\ncorollary (in group_hom) inj_hom_imp_solvable:\n  assumes \"inj_on h (carrier G)\" and \"solvable H\" shows \"solvable G\"\n  using solvable_img_imp_solvable[OF _ assms(1)] G.subgroup_self\n        solvable_subgroup[OF subgroup_img_is_subgroup assms(2)]\n  unfolding solvable_def\n  by simp\n\ntheorem (in group_hom) solvable_imp_solvable_img:\n  assumes \"solvable_seq G K\" shows \"solvable_seq H (h ` K)\"\nproof -\n  obtain n where \"(derived G ^^ n) K = { \\<one> }\"\n    using G.solvable_imp_trivial_derived_seq[OF assms] by blast\n  thus ?thesis\n    using trivial_derived_seq_imp_solvable[OF subgroup_img_is_subgroup, of _ n]\n          exp_of_derived_img[OF subgroup.subset, of _ n] G.solvable_imp_subgroup[OF assms]\n    by auto\nqed\n\ncorollary (in group_hom) surj_hom_imp_solvable:\n  assumes \"h ` carrier G = carrier H\" and \"solvable G\" shows \"solvable H\"\n  using assms solvable_imp_solvable_img[of \"carrier G\"] unfolding solvable_def by simp\n\nlemma solvable_seq_condition:\n  assumes \"group_hom G H f\" \"group_hom H K g\" and \"f ` I \\<subseteq> J\" and \"kernel H K g \\<subseteq> f ` I\"\n    and \"subgroup J H\" and \"solvable_seq G I\" \"solvable_seq K (g ` J)\"\n  shows \"solvable_seq H J\"\nproof -\n  interpret G: group G + H: group H + K: group K + J: subgroup J H + I: subgroup I G\n    using assms(1-2,5) group.solvable_imp_subgroup[OF _ assms(6)] unfolding group_hom_def by auto\n\n  obtain n m\n    where n: \"(derived G ^^ n) I = { \\<one>\\<^bsub>G\\<^esub> }\" and m: \"(derived K ^^ m) (g ` J) = { \\<one>\\<^bsub>K\\<^esub> }\"\n    using G.solvable_imp_trivial_derived_seq[OF assms(6)]\n          K.solvable_imp_trivial_derived_seq[OF assms(7)]\n    by auto\n  have \"(derived H ^^ m) J \\<subseteq> f ` I\"\n    using m H.exp_of_derived_in_carrier[OF J.subset, of m] assms(4)\n    by (auto simp add: group_hom.exp_of_derived_img[OF assms(2) J.subset] kernel_def)\n  hence \"(derived H ^^ n) ((derived H ^^ m) J) \\<subseteq> f ` ((derived G ^^ n) I)\"\n    using n H.mono_exp_of_derived unfolding sym[OF group_hom.exp_of_derived_img[OF assms(1) I.subset, of n]] by simp\n  hence \"(derived H ^^ (n + m)) J \\<subseteq> { \\<one>\\<^bsub>H\\<^esub> }\"\n    using group_hom.hom_one[OF assms(1)] unfolding n by (simp add: funpow_add)\n  moreover have \"{ \\<one>\\<^bsub>H\\<^esub> } \\<subseteq> (derived H ^^ (n + m)) J\"\n    using subgroup.one_closed[OF H.exp_of_derived_is_subgroup[OF assms(5), of \"n + m\"]] by blast\n  ultimately show ?thesis\n    using H.trivial_derived_seq_imp_solvable[OF assms(5)] by simp\nqed\n\nlemma solvable_condition:\n  assumes \"group_hom G H f\" \"group_hom H K g\"\n    and \"g ` (carrier H) = carrier K\" and \"kernel H K g \\<subseteq> f ` (carrier G)\"\n    and \"solvable G\" \"solvable K\" shows \"solvable H\"\n  using solvable_seq_condition[OF assms(1-2) _ assms(4) group.subgroup_self] assms(3,5-6)\n        subgroup.subset[OF group_hom.img_is_subgroup[OF assms(1)]] group_hom.axioms(2)[OF assms(1)]\n  by (simp add: solvable_def)\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/Algebra/Solvable_Groups.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094145755219, "lm_q2_score": 0.8267117940706734, "lm_q1q2_score": 0.7385094287839528}}
{"text": "(*  Title:      HOL/Library/Set_Algebras.thy\n    Author:     Jeremy Avigad and Kevin Donnelly; Florian Haftmann, TUM\n*)\n\nsection {* Algebraic operations on sets *}\n\ntheory Set_Algebras\nimports Main\nbegin\n\ntext {*\n  This library lifts operations like addition and multiplication to\n  sets.  It was designed to support asymptotic calculations. See the\n  comments at the top of theory @{text BigO}.\n*}\n\ninstantiation set :: (plus) plus\nbegin\n\ndefinition plus_set :: \"'a::plus set \\<Rightarrow> 'a set \\<Rightarrow> 'a set\" where\n  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\" where\n  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\n  set_zero[simp]: \"(0::'a::zero set) = {0}\"\n\ninstance ..\n\nend\n\ninstantiation set :: (one) one\nbegin\n\ndefinition\n  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) where\n  \"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) where\n  \"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) where\n  \"x =o A \\<equiv> x \\<in> A\"\n\ninstance set :: (semigroup_add) semigroup_add\n  by default (force simp add: set_plus_def add.assoc)\n\ninstance set :: (ab_semigroup_add) ab_semigroup_add\n  by default (force simp add: set_plus_def add.commute)\n\ninstance set :: (monoid_add) monoid_add\n  by default (simp_all add: set_plus_def)\n\ninstance set :: (comm_monoid_add) comm_monoid_add\n  by default (simp_all add: set_plus_def)\n\ninstance set :: (semigroup_mult) semigroup_mult\n  by default (force simp add: set_times_def mult.assoc)\n\ninstance set :: (ab_semigroup_mult) ab_semigroup_mult\n  by default (force simp add: set_times_def mult.commute)\n\ninstance set :: (monoid_mult) monoid_mult\n  by default (simp_all add: set_times_def)\n\ninstance set :: (comm_monoid_mult) comm_monoid_mult\n  by default (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:\n  \"((a::'a::comm_monoid_add) +o C) + (b +o D) = (a + b) +o (C + D)\"\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::'a::semigroup_add) +o (b +o C) = (a + b) +o C\"\n  by (auto simp add: elt_set_plus_def add.assoc)\n\nlemma set_plus_rearrange3: \"((a::'a::semigroup_add) +o B) + C = a +o (B + C)\"\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::'a::comm_monoid_add) +o D) = a +o (C + D)\"\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\ntheorems 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::'a::plus set) \\<subseteq> D \\<Longrightarrow> E \\<subseteq> F \\<Longrightarrow> C + E \\<subseteq> D + F\"\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::'a::comm_monoid_add) \\<in> C \\<Longrightarrow> a +o D \\<subseteq> D + C\"\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::'a::comm_monoid_add) : C \\<Longrightarrow> x \\<in> a +o D \\<Longrightarrow> x \\<in> D + C\"\n  apply (frule set_plus_mono4)\n  apply auto\n  done\n\nlemma set_zero_plus [simp]: \"(0::'a::comm_monoid_add) +o C = C\"\n  by (auto simp add: elt_set_plus_def)\n\nlemma set_zero_plus2: \"(0::'a::comm_monoid_add) \\<in> A \\<Longrightarrow> B \\<subseteq> A + B\"\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::'a::ab_group_add) : b +o C \\<Longrightarrow> (a - b) \\<in> C\"\n  by (auto simp add: elt_set_plus_def ac_simps)\n\nlemma set_minus_imp_plus: \"(a::'a::ab_group_add) - b : C \\<Longrightarrow> a \\<in> b +o C\"\n  apply (auto simp add: elt_set_plus_def ac_simps)\n  apply (subgoal_tac \"a = (a + - b) + b\")\n   apply (rule bexI, assumption)\n  apply (auto simp add: ac_simps)\n  done\n\nlemma set_minus_plus: \"(a::'a::ab_group_add) - b \\<in> C \\<longleftrightarrow> a \\<in> b +o C\"\n  by (rule iffI, rule set_minus_imp_plus, assumption, rule set_plus_imp_minus)\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:\n  \"((a::'a::comm_monoid_mult) *o C) * (b *o D) = (a * b) *o (C * D)\"\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:\n  \"(a::'a::semigroup_mult) *o (b *o C) = (a * b) *o C\"\n  by (auto simp add: elt_set_times_def mult.assoc)\n\nlemma set_times_rearrange3:\n  \"((a::'a::semigroup_mult) *o B) * C = a *o (B * C)\"\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:\n  \"C * ((a::'a::comm_monoid_mult) *o D) = a *o (C * D)\"\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\ntheorems 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::'a::times set) \\<subseteq> D \\<Longrightarrow> E \\<subseteq> F \\<Longrightarrow> C * E \\<subseteq> D * F\"\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::'a::comm_monoid_mult) : C \\<Longrightarrow> a *o D \\<subseteq> D * C\"\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::'a::comm_monoid_mult) \\<in> C \\<Longrightarrow> x \\<in> a *o D \\<Longrightarrow> x \\<in> D * C\"\n  apply (frule set_times_mono4)\n  apply auto\n  done\n\nlemma set_one_times [simp]: \"(1::'a::comm_monoid_mult) *o C = C\"\n  by (auto simp add: elt_set_times_def)\n\nlemma set_times_plus_distrib:\n  \"(a::'a::semiring) *o (b +o C) = (a * b) +o (a *o C)\"\n  by (auto simp add: elt_set_plus_def elt_set_times_def ring_distribs)\n\nlemma set_times_plus_distrib2:\n  \"(a::'a::semiring) *o (B + C) = (a *o B) + (a *o C)\"\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::'a::semiring) +o C) * D \\<subseteq> a *o D + C * D\"\n  apply (auto simp add:\n    elt_set_plus_def elt_set_times_def set_times_def\n    set_plus_def ring_distribs)\n  apply auto\n  done\n\ntheorems set_times_plus_distribs =\n  set_times_plus_distrib\n  set_times_plus_distrib2\n\nlemma set_neg_intro: \"(a::'a::ring_1) \\<in> (- 1) *o C \\<Longrightarrow> - a \\<in> C\"\n  by (auto simp add: elt_set_times_def)\n\nlemma set_neg_intro2: \"(a::'a::ring_1) \\<in> C \\<Longrightarrow> - a \\<in> (- 1) *o C\"\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  unfolding set_plus_def by (fastforce simp: image_iff)\n\nlemma set_times_image: \"S * T = (\\<lambda>(x, y). x * y) ` (S \\<times> T)\"\n  unfolding set_times_def by (fastforce simp: image_iff)\n\nlemma finite_set_plus: \"finite s \\<Longrightarrow> finite t \\<Longrightarrow> finite (s + t)\"\n  unfolding set_plus_image by simp\n\nlemma finite_set_times: \"finite s \\<Longrightarrow> finite t \\<Longrightarrow> finite (s * t)\"\n  unfolding set_times_image by simp\n\nlemma set_setsum_alt:\n  assumes fin: \"finite I\"\n  shows \"setsum S I = {setsum s I |s. \\<forall>i\\<in>I. s i \\<in> S i}\"\n    (is \"_ = ?setsum I\")\n  using fin\nproof induct\n  case empty\n  then show ?case by simp\nnext\n  case (insert x F)\n  have \"setsum S (insert x F) = S x + ?setsum F\"\n    using insert.hyps by auto\n  also have \"\\<dots> = {s x + setsum 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 + setsum s F = s' x + setsum 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 setsum_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 (setsum S I) = setsum (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 `finite F` `\\<And>i. i \\<in> insert x F \\<Longrightarrow> P (S i)` have \"P (setsum 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 setsum_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 (setsum S I) = setsum (f \\<circ> S) I\"\n  using setsum_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 I M = (\\<Union>i\\<in>I. A * M i)\"\n  \"UNION I M * A = (\\<Union>i\\<in>I. M i * A)\"\n  by (auto simp: set_times_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/Library/Set_Algebras.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094145755219, "lm_q2_score": 0.8267117876664789, "lm_q1q2_score": 0.7385094230630255}}
{"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_BubSortSorts\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 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 bubble :: \"Nat list => (bool, (Nat 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 le 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 :: \"Nat list => Nat 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_nat_BubSortSorts.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094032139576, "lm_q2_score": 0.8267117940706734, "lm_q1q2_score": 0.7385094193912135}}
{"text": "theory FirstExample\n(* imports theories (packages) *)\nimports Main\nbegin\n\n(* declarations *)\ntype_synonym NatType = nat\n\n(* definitions *)\nprimrec multip :: \"NatType \\<Rightarrow> NatType \\<Rightarrow> NatType\"\n  where m_zero: \"multip 0 n = 0\" |\n        m_suc:  \"multip (Suc m) n = n + multip m n\"\n\n(* proofs *)\nlemma correctness: \"multip m n = m * n\"\n  proof(induct m)\n    case 0\n    then show \"multip 0 n = 0 * n\" by simp\n  next\n    case (Suc m)\n    assume \"multip m n = m * n\"\n    then show \"multip (Suc m) n = Suc m * n\" \n      using m_suc by fastforce\n  qed\n\nend\n\n", "meta": {"author": "LVPGroup", "repo": "fpp", "sha": "7e18377ea2c553bf6e57412727a4f06832d93577", "save_path": "github-repos/isabelle/LVPGroup-fpp", "path": "github-repos/isabelle/LVPGroup-fpp/fpp-7e18377ea2c553bf6e57412727a4f06832d93577/2_functionalprog/FirstExample.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9111797075998823, "lm_q2_score": 0.8104789155369047, "lm_q1q2_score": 0.7384919412747865}}
{"text": "\ntheory Boolean_functions\n  imports \n    Main\n    \"Jordan_Normal_Form.Matrix\"\nbegin\n\nsection\\<open>Boolean functions\\<close>\n\ntext\\<open>Definition of monotonicity\\<close>\n\ntext\\<open>We consider (monotone) Boolean \n  functions over vectors of length $n$, so that we can later \n  prove that those are isomorphic to \n  simplicial complexes of dimension $n$ (in $n$ vertexes).\\<close>\n\nlocale boolean_functions\n  = fixes n::\"nat\"\nbegin\n\ndefinition bool_fun_dim_n :: \"(bool vec => bool) set\"\n  where \"bool_fun_dim_n = {f. f \\<in> carrier_vec n \\<rightarrow> (UNIV::bool set)}\"\n\ndefinition monotone_bool_fun :: \"(bool vec => bool) => bool\"\n  where \"monotone_bool_fun f \\<equiv> (mono_on f (carrier_vec n))\"\n\ndefinition monotone_bool_fun_set :: \"(bool vec => bool) set\"\n  where \"monotone_bool_fun_set = (Collect monotone_bool_fun)\"\n\ntext\\<open>Some examples of Boolean functions\\<close>\n\ndefinition bool_fun_top :: \"bool vec => bool\"\n  where \"bool_fun_top f = True\"\n\ndefinition bool_fun_bot :: \"bool vec => bool\"\n  where \"bool_fun_bot f = False\"\n\nend\n\nsection\\<open>Threshold function\\<close>\n\ndefinition count_true :: \"bool vec => nat\"\n  where \"count_true v = sum (\\<lambda>i. if vec_index v i then 1 else 0::nat) {0..<dim_vec v}\"\n\nlemma \"vec_index (vec (5::nat) (\\<lambda>i. False)) 2 = False\"\n  by simp\n\nlemma \"vec_index (vec (5::nat) (\\<lambda>i. True)) 3 = True\"\n  by simp\n\nlemma \"count_true (vec (1::nat) (\\<lambda>i. True)) = 1\"\n  unfolding count_true_def by simp\n  \nlemma \"count_true (vec (2::nat) (\\<lambda>i. True)) = 2\"\n  unfolding count_true_def by simp\n\nlemma \"count_true (vec (5::nat) (\\<lambda>i. True)) = 5\"\n  unfolding count_true_def by simp\n\ntext\\<open>The threshold function is a Boolean function\n  which also satisfies the condition of being \\emph{evasive}.\n  We follow the definition by Scoville~\\cite[Problem 6.5]{SC19}.\\<close>\n\ndefinition bool_fun_threshold :: \"nat => (bool vec => bool)\"\n  where \"bool_fun_threshold i = (\\<lambda>v. if i \\<le> count_true v then True else False)\"\n\ncontext boolean_functions\nbegin\n\nlemma \"mono_on bool_fun_top UNIV\"\n  by (simp add: bool_fun_top_def mono_onI monotone_bool_fun_def)\n\nlemma \"monotone_bool_fun bool_fun_top\"\n  by (simp add: bool_fun_top_def mono_onI monotone_bool_fun_def)\n\nlemma \"mono_on bool_fun_bot UNIV\"\n  by (simp add: bool_fun_bot_def mono_onI monotone_bool_fun_def)\n\nlemma \"monotone_bool_fun bool_fun_bot\"\n  by (simp add: bool_fun_bot_def mono_onI monotone_bool_fun_def)\n\nlemma\n  monotone_count_true:\n  assumes ulev: \"(u::bool vec) \\<le> v\"\n  shows \"count_true u \\<le> count_true v\"\n  unfolding count_true_def\n  using Groups_Big.ordered_comm_monoid_add_class.sum_mono \n    [of \"{0..<dim_vec u}\" \n      \"(\\<lambda>i. if vec_index u i then 1 else 0)\" \n      \"(\\<lambda>i. if vec_index v i then 1 else 0)\"]\n  using ulev\n  unfolding Matrix.less_eq_vec_def\n  by fastforce\n\ntext\\<open>The threshold function is monotone.\\<close>\n\nlemma\n  monotone_threshold:\n  assumes ulev: \"(u::bool vec) \\<le> v\"\n  shows \"bool_fun_threshold n u \\<le> bool_fun_threshold n v\"\n  unfolding bool_fun_threshold_def\n  using monotone_count_true [OF ulev] by simp\n\nlemma\n  assumes \"(u::bool vec) \\<le> v\"\n  and \"n < dim_vec u\"\n  shows \"bool_fun_threshold n u \\<le> bool_fun_threshold n v\"\n  using monotone_threshold [OF assms(1)] .\n\nlemma \"mono_on (bool_fun_threshold n) UNIV\"\n  by (meson mono_onI monotone_bool_fun_def monotone_threshold)\n\nlemma \"monotone_bool_fun (bool_fun_threshold n)\"\n  unfolding monotone_bool_fun_def\n  by (meson boolean_functions.monotone_threshold mono_onI)\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/Boolean_functions.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797124237604, "lm_q2_score": 0.8104789018037399, "lm_q1q2_score": 0.7384919326710568}}
{"text": "(*  Title:      HOL/Fields.thy\n    Author:     Gertrud Bauer\n    Author:     Steven Obua\n    Author:     Tobias Nipkow\n    Author:     Lawrence C Paulson\n    Author:     Markus Wenzel\n    Author:     Jeremy Avigad\n*)\n\nsection \\<open>Fields\\<close>\n\ntheory Fields\nimports Nat\nbegin\n\nsubsection \\<open>Division rings\\<close>\n\ntext \\<open>\n  A division ring is like a field, but without the commutativity requirement.\n\\<close>\n\nclass inverse = divide +\n  fixes inverse :: \"'a \\<Rightarrow> 'a\"\nbegin\n  \nabbreviation inverse_divide :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a\"  (infixl \"'/\" 70)\nwhere\n  \"inverse_divide \\<equiv> divide\"\n\nend\n\ntext \\<open>Setup for linear arithmetic prover\\<close>\n\nML_file \\<open>~~/src/Provers/Arith/fast_lin_arith.ML\\<close>\nML_file \\<open>Tools/lin_arith.ML\\<close>\nsetup \\<open>Lin_Arith.global_setup\\<close>\ndeclaration \\<open>K (                 \n  Lin_Arith.init_arith_data\n  #> Lin_Arith.add_discrete_type \\<^type_name>\\<open>nat\\<close>\n  #> Lin_Arith.add_lessD @{thm Suc_leI}\n  #> Lin_Arith.add_simps @{thms simp_thms ring_distribs if_True if_False\n      minus_diff_eq\n      add_0_left add_0_right order_less_irrefl\n      zero_neq_one zero_less_one zero_le_one\n      zero_neq_one [THEN not_sym] not_one_le_zero not_one_less_zero\n      add_Suc add_Suc_right nat.inject\n      Suc_le_mono Suc_less_eq Zero_not_Suc\n      Suc_not_Zero le_0_eq One_nat_def}\n  #> Lin_Arith.add_simprocs [\\<^simproc>\\<open>group_cancel_add\\<close>, \\<^simproc>\\<open>group_cancel_diff\\<close>,\n      \\<^simproc>\\<open>group_cancel_eq\\<close>, \\<^simproc>\\<open>group_cancel_le\\<close>,\n      \\<^simproc>\\<open>group_cancel_less\\<close>,\n      \\<^simproc>\\<open>nateq_cancel_sums\\<close>,\\<^simproc>\\<open>natless_cancel_sums\\<close>,\n      \\<^simproc>\\<open>natle_cancel_sums\\<close>])\\<close>\n\nsimproc_setup fast_arith_nat (\"(m::nat) < n\" | \"(m::nat) \\<le> n\" | \"(m::nat) = n\") =\n  \\<open>K Lin_Arith.simproc\\<close> \\<comment> \\<open>Because of this simproc, the arithmetic solver is\n   really only useful to detect inconsistencies among the premises for subgoals which are\n   \\<^emph>\\<open>not\\<close> themselves (in)equalities, because the latter activate\n   \\<^text>\\<open>fast_nat_arith_simproc\\<close> anyway. However, it seems cheaper to activate the\n   solver all the time rather than add the additional check.\\<close>\n\nlemmas [linarith_split] = nat_diff_split split_min split_max abs_split\n\ntext\\<open>Lemmas \\<open>divide_simps\\<close> move division to the outside and eliminates them on (in)equalities.\\<close>\n\nnamed_theorems divide_simps \"rewrite rules to eliminate divisions\"\n\nclass division_ring = ring_1 + inverse +\n  assumes left_inverse [simp]:  \"a \\<noteq> 0 \\<Longrightarrow> inverse a * a = 1\"\n  assumes right_inverse [simp]: \"a \\<noteq> 0 \\<Longrightarrow> a * inverse a = 1\"\n  assumes divide_inverse: \"a / b = a * inverse b\"\n  assumes inverse_zero [simp]: \"inverse 0 = 0\"\nbegin\n\nsubclass ring_1_no_zero_divisors\nproof\n  fix a b :: 'a\n  assume a: \"a \\<noteq> 0\" and b: \"b \\<noteq> 0\"\n  show \"a * b \\<noteq> 0\"\n  proof\n    assume ab: \"a * b = 0\"\n    hence \"0 = inverse a * (a * b) * inverse b\" by simp\n    also have \"\\<dots> = (inverse a * a) * (b * inverse b)\"\n      by (simp only: mult.assoc)\n    also have \"\\<dots> = 1\" using a b by simp\n    finally show False by simp\n  qed\nqed\n\nlemma nonzero_imp_inverse_nonzero:\n  \"a \\<noteq> 0 \\<Longrightarrow> inverse a \\<noteq> 0\"\nproof\n  assume ianz: \"inverse a = 0\"\n  assume \"a \\<noteq> 0\"\n  hence \"1 = a * inverse a\" by simp\n  also have \"... = 0\" by (simp add: ianz)\n  finally have \"1 = 0\" .\n  thus False by (simp add: eq_commute)\nqed\n\nlemma inverse_zero_imp_zero:\n  assumes \"inverse a = 0\" shows \"a = 0\"\nproof (rule ccontr)\n  assume \"a \\<noteq> 0\"\n  then have \"inverse a \\<noteq> 0\"\n    by (simp add: nonzero_imp_inverse_nonzero)\n  with assms show False\n    by auto\nqed\n\nlemma inverse_unique:\n  assumes ab: \"a * b = 1\"\n  shows \"inverse a = b\"\nproof -\n  have \"a \\<noteq> 0\" using ab by (cases \"a = 0\") simp_all\n  moreover have \"inverse a * (a * b) = inverse a\" by (simp add: ab)\n  ultimately show ?thesis by (simp add: mult.assoc [symmetric])\nqed\n\nlemma nonzero_inverse_minus_eq:\n  \"a \\<noteq> 0 \\<Longrightarrow> inverse (- a) = - inverse a\"\nby (rule inverse_unique) simp\n\nlemma nonzero_inverse_inverse_eq:\n  \"a \\<noteq> 0 \\<Longrightarrow> inverse (inverse a) = a\"\nby (rule inverse_unique) simp\n\nlemma nonzero_inverse_eq_imp_eq:\n  assumes \"inverse a = inverse b\" and \"a \\<noteq> 0\" and \"b \\<noteq> 0\"\n  shows \"a = b\"\nproof -\n  from \\<open>inverse a = inverse b\\<close>\n  have \"inverse (inverse a) = inverse (inverse b)\" by (rule arg_cong)\n  with \\<open>a \\<noteq> 0\\<close> and \\<open>b \\<noteq> 0\\<close> show \"a = b\"\n    by (simp add: nonzero_inverse_inverse_eq)\nqed\n\nlemma inverse_1 [simp]: \"inverse 1 = 1\"\nby (rule inverse_unique) simp\n\nlemma nonzero_inverse_mult_distrib:\n  assumes \"a \\<noteq> 0\" and \"b \\<noteq> 0\"\n  shows \"inverse (a * b) = inverse b * inverse a\"\nproof -\n  have \"a * (b * inverse b) * inverse a = 1\" using assms by simp\n  hence \"a * b * (inverse b * inverse a) = 1\" by (simp only: mult.assoc)\n  thus ?thesis by (rule inverse_unique)\nqed\n\nlemma division_ring_inverse_add:\n  \"a \\<noteq> 0 \\<Longrightarrow> b \\<noteq> 0 \\<Longrightarrow> inverse a + inverse b = inverse a * (a + b) * inverse b\"\nby (simp add: algebra_simps)\n\nlemma division_ring_inverse_diff:\n  \"a \\<noteq> 0 \\<Longrightarrow> b \\<noteq> 0 \\<Longrightarrow> inverse a - inverse b = inverse a * (b - a) * inverse b\"\nby (simp add: algebra_simps)\n\nlemma right_inverse_eq: \"b \\<noteq> 0 \\<Longrightarrow> a / b = 1 \\<longleftrightarrow> a = b\"\nproof\n  assume neq: \"b \\<noteq> 0\"\n  {\n    hence \"a = (a / b) * b\" by (simp add: divide_inverse mult.assoc)\n    also assume \"a / b = 1\"\n    finally show \"a = b\" by simp\n  next\n    assume \"a = b\"\n    with neq show \"a / b = 1\" by (simp add: divide_inverse)\n  }\nqed\n\nlemma nonzero_inverse_eq_divide: \"a \\<noteq> 0 \\<Longrightarrow> inverse a = 1 / a\"\nby (simp add: divide_inverse)\n\nlemma divide_self [simp]: \"a \\<noteq> 0 \\<Longrightarrow> a / a = 1\"\nby (simp add: divide_inverse)\n\nlemma inverse_eq_divide [field_simps, field_split_simps, divide_simps]: \"inverse a = 1 / a\"\nby (simp add: divide_inverse)\n\nlemma add_divide_distrib: \"(a+b) / c = a/c + b/c\"\nby (simp add: divide_inverse algebra_simps)\n\nlemma times_divide_eq_right [simp]: \"a * (b / c) = (a * b) / c\"\n  by (simp add: divide_inverse mult.assoc)\n\nlemma minus_divide_left: \"- (a / b) = (-a) / b\"\n  by (simp add: divide_inverse)\n\nlemma nonzero_minus_divide_right: \"b \\<noteq> 0 \\<Longrightarrow> - (a / b) = a / (- b)\"\n  by (simp add: divide_inverse nonzero_inverse_minus_eq)\n\nlemma nonzero_minus_divide_divide: \"b \\<noteq> 0 \\<Longrightarrow> (-a) / (-b) = a / b\"\n  by (simp add: divide_inverse nonzero_inverse_minus_eq)\n\nlemma divide_minus_left [simp]: \"(-a) / b = - (a / b)\"\n  by (simp add: divide_inverse)\n\nlemma diff_divide_distrib: \"(a - b) / c = a / c - b / c\"\n  using add_divide_distrib [of a \"- b\" c] by simp\n\nlemma nonzero_eq_divide_eq [field_simps]: \"c \\<noteq> 0 \\<Longrightarrow> a = b / c \\<longleftrightarrow> a * c = b\"\nproof -\n  assume [simp]: \"c \\<noteq> 0\"\n  have \"a = b / c \\<longleftrightarrow> a * c = (b / c) * c\" by simp\n  also have \"... \\<longleftrightarrow> a * c = b\" by (simp add: divide_inverse mult.assoc)\n  finally show ?thesis .\nqed\n\nlemma nonzero_divide_eq_eq [field_simps]: \"c \\<noteq> 0 \\<Longrightarrow> b / c = a \\<longleftrightarrow> b = a * c\"\nproof -\n  assume [simp]: \"c \\<noteq> 0\"\n  have \"b / c = a \\<longleftrightarrow> (b / c) * c = a * c\" by simp\n  also have \"... \\<longleftrightarrow> b = a * c\" by (simp add: divide_inverse mult.assoc)\n  finally show ?thesis .\nqed\n\nlemma nonzero_neg_divide_eq_eq [field_simps]: \"b \\<noteq> 0 \\<Longrightarrow> - (a / b) = c \\<longleftrightarrow> - a = c * b\"\n  using nonzero_divide_eq_eq[of b \"-a\" c] by simp\n\nlemma nonzero_neg_divide_eq_eq2 [field_simps]: \"b \\<noteq> 0 \\<Longrightarrow> c = - (a / b) \\<longleftrightarrow> c * b = - a\"\n  using nonzero_neg_divide_eq_eq[of b a c] by auto\n\nlemma divide_eq_imp: \"c \\<noteq> 0 \\<Longrightarrow> b = a * c \\<Longrightarrow> b / c = a\"\n  by (simp add: divide_inverse mult.assoc)\n\nlemma eq_divide_imp: \"c \\<noteq> 0 \\<Longrightarrow> a * c = b \\<Longrightarrow> a = b / c\"\n  by (drule sym) (simp add: divide_inverse mult.assoc)\n\nlemma add_divide_eq_iff [field_simps]:\n  \"z \\<noteq> 0 \\<Longrightarrow> x + y / z = (x * z + y) / z\"\n  by (simp add: add_divide_distrib nonzero_eq_divide_eq)\n\nlemma divide_add_eq_iff [field_simps]:\n  \"z \\<noteq> 0 \\<Longrightarrow> x / z + y = (x + y * z) / z\"\n  by (simp add: add_divide_distrib nonzero_eq_divide_eq)\n\nlemma diff_divide_eq_iff [field_simps]:\n  \"z \\<noteq> 0 \\<Longrightarrow> x - y / z = (x * z - y) / z\"\n  by (simp add: diff_divide_distrib nonzero_eq_divide_eq eq_diff_eq)\n\nlemma minus_divide_add_eq_iff [field_simps]:\n  \"z \\<noteq> 0 \\<Longrightarrow> - (x / z) + y = (- x + y * z) / z\"\n  by (simp add: add_divide_distrib diff_divide_eq_iff)\n\nlemma divide_diff_eq_iff [field_simps]:\n  \"z \\<noteq> 0 \\<Longrightarrow> x / z - y = (x - y * z) / z\"\n  by (simp add: field_simps)\n\nlemma minus_divide_diff_eq_iff [field_simps]:\n  \"z \\<noteq> 0 \\<Longrightarrow> - (x / z) - y = (- x - y * z) / z\"\n  by (simp add: divide_diff_eq_iff[symmetric])\n\nlemma division_ring_divide_zero [simp]:\n  \"a / 0 = 0\"\n  by (simp add: divide_inverse)\n\nlemma divide_self_if [simp]:\n  \"a / a = (if a = 0 then 0 else 1)\"\n  by simp\n\nlemma inverse_nonzero_iff_nonzero [simp]:\n  \"inverse a = 0 \\<longleftrightarrow> a = 0\"\n  by (rule iffI) (fact inverse_zero_imp_zero, simp)\n\nlemma inverse_minus_eq [simp]:\n  \"inverse (- a) = - inverse a\"\nproof cases\n  assume \"a=0\" thus ?thesis by simp\nnext\n  assume \"a\\<noteq>0\"\n  thus ?thesis by (simp add: nonzero_inverse_minus_eq)\nqed\n\nlemma inverse_inverse_eq [simp]:\n  \"inverse (inverse a) = a\"\nproof cases\n  assume \"a=0\" thus ?thesis by simp\nnext\n  assume \"a\\<noteq>0\"\n  thus ?thesis by (simp add: nonzero_inverse_inverse_eq)\nqed\n\nlemma inverse_eq_imp_eq:\n  \"inverse a = inverse b \\<Longrightarrow> a = b\"\n  by (drule arg_cong [where f=\"inverse\"], simp)\n\nlemma inverse_eq_iff_eq [simp]:\n  \"inverse a = inverse b \\<longleftrightarrow> a = b\"\n  by (force dest!: inverse_eq_imp_eq)\n\nlemma mult_commute_imp_mult_inverse_commute:\n  assumes \"y * x = x * y\"\n  shows   \"inverse y * x = x * inverse y\"\nproof (cases \"y=0\")\n  case False\n  hence \"x * inverse y = inverse y * y * x * inverse y\"\n    by simp\n  also have \"\\<dots> = inverse y * (x * y * inverse y)\"\n    by (simp add: mult.assoc assms)\n  finally show ?thesis by (simp add: mult.assoc False)\nqed simp\n\nlemmas mult_inverse_of_nat_commute =\n  mult_commute_imp_mult_inverse_commute[OF mult_of_nat_commute]\n\nlemma divide_divide_eq_left':\n  \"(a / b) / c = a / (c * b)\"\n  by (cases \"b = 0 \\<or> c = 0\")\n     (auto simp: divide_inverse mult.assoc nonzero_inverse_mult_distrib)\n\nlemma add_divide_eq_if_simps [field_split_simps, divide_simps]:\n    \"a + b / z = (if z = 0 then a else (a * z + b) / z)\"\n    \"a / z + b = (if z = 0 then b else (a + b * z) / z)\"\n    \"- (a / z) + b = (if z = 0 then b else (-a + b * z) / z)\"\n    \"a - b / z = (if z = 0 then a else (a * z - b) / z)\"\n    \"a / z - b = (if z = 0 then -b else (a - b * z) / z)\"\n    \"- (a / z) - b = (if z = 0 then -b else (- a - b * z) / z)\"\n  by (simp_all add: add_divide_eq_iff divide_add_eq_iff diff_divide_eq_iff divide_diff_eq_iff\n      minus_divide_diff_eq_iff)\n\nlemma [field_split_simps, divide_simps]:\n  shows divide_eq_eq: \"b / c = a \\<longleftrightarrow> (if c \\<noteq> 0 then b = a * c else a = 0)\"\n    and eq_divide_eq: \"a = b / c \\<longleftrightarrow> (if c \\<noteq> 0 then a * c = b else a = 0)\"\n    and minus_divide_eq_eq: \"- (b / c) = a \\<longleftrightarrow> (if c \\<noteq> 0 then - b = a * c else a = 0)\"\n    and eq_minus_divide_eq: \"a = - (b / c) \\<longleftrightarrow> (if c \\<noteq> 0 then a * c = - b else a = 0)\"\n  by (auto simp add:  field_simps)\n\nend\n\nsubsection \\<open>Fields\\<close>\n\nclass field = comm_ring_1 + inverse +\n  assumes field_inverse: \"a \\<noteq> 0 \\<Longrightarrow> inverse a * a = 1\"\n  assumes field_divide_inverse: \"a / b = a * inverse b\"\n  assumes field_inverse_zero: \"inverse 0 = 0\"\nbegin\n\nsubclass division_ring\nproof\n  fix a :: 'a\n  assume \"a \\<noteq> 0\"\n  thus \"inverse a * a = 1\" by (rule field_inverse)\n  thus \"a * inverse a = 1\" by (simp only: mult.commute)\nnext\n  fix a b :: 'a\n  show \"a / b = a * inverse b\" by (rule field_divide_inverse)\nnext\n  show \"inverse 0 = 0\"\n    by (fact field_inverse_zero) \nqed\n\nsubclass idom_divide\nproof\n  fix b a\n  assume \"b \\<noteq> 0\"\n  then show \"a * b / b = a\"\n    by (simp add: divide_inverse ac_simps)\nnext\n  fix a\n  show \"a / 0 = 0\"\n    by (simp add: divide_inverse)\nqed\n\ntext\\<open>There is no slick version using division by zero.\\<close>\nlemma inverse_add:\n  \"a \\<noteq> 0 \\<Longrightarrow> b \\<noteq> 0 \\<Longrightarrow> inverse a + inverse b = (a + b) * inverse a * inverse b\"\n  by (simp add: division_ring_inverse_add ac_simps)\n\nlemma nonzero_mult_divide_mult_cancel_left [simp]:\n  assumes [simp]: \"c \\<noteq> 0\"\n  shows \"(c * a) / (c * b) = a / b\"\nproof (cases \"b = 0\")\n  case True then show ?thesis by simp\nnext\n  case False\n  then have \"(c*a)/(c*b) = c * a * (inverse b * inverse c)\"\n    by (simp add: divide_inverse nonzero_inverse_mult_distrib)\n  also have \"... =  a * inverse b * (inverse c * c)\"\n    by (simp only: ac_simps)\n  also have \"... =  a * inverse b\" by simp\n    finally show ?thesis by (simp add: divide_inverse)\nqed\n\nlemma nonzero_mult_divide_mult_cancel_right [simp]:\n  \"c \\<noteq> 0 \\<Longrightarrow> (a * c) / (b * c) = a / b\"\n  using nonzero_mult_divide_mult_cancel_left [of c a b] by (simp add: ac_simps)\n\nlemma times_divide_eq_left [simp]: \"(b / c) * a = (b * a) / c\"\n  by (simp add: divide_inverse ac_simps)\n\nlemma divide_inverse_commute: \"a / b = inverse b * a\"\n  by (simp add: divide_inverse mult.commute)\n\nlemma add_frac_eq:\n  assumes \"y \\<noteq> 0\" and \"z \\<noteq> 0\"\n  shows \"x / y + w / z = (x * z + w * y) / (y * z)\"\nproof -\n  have \"x / y + w / z = (x * z) / (y * z) + (y * w) / (y * z)\"\n    using assms by simp\n  also have \"\\<dots> = (x * z + y * w) / (y * z)\"\n    by (simp only: add_divide_distrib)\n  finally show ?thesis\n    by (simp only: mult.commute)\nqed\n\ntext\\<open>Special Cancellation Simprules for Division\\<close>\n\nlemma nonzero_divide_mult_cancel_right [simp]:\n  \"b \\<noteq> 0 \\<Longrightarrow> b / (a * b) = 1 / a\"\n  using nonzero_mult_divide_mult_cancel_right [of b 1 a] by simp\n\nlemma nonzero_divide_mult_cancel_left [simp]:\n  \"a \\<noteq> 0 \\<Longrightarrow> a / (a * b) = 1 / b\"\n  using nonzero_mult_divide_mult_cancel_left [of a 1 b] by simp\n\nlemma nonzero_mult_divide_mult_cancel_left2 [simp]:\n  \"c \\<noteq> 0 \\<Longrightarrow> (c * a) / (b * c) = a / b\"\n  using nonzero_mult_divide_mult_cancel_left [of c a b] by (simp add: ac_simps)\n\nlemma nonzero_mult_divide_mult_cancel_right2 [simp]:\n  \"c \\<noteq> 0 \\<Longrightarrow> (a * c) / (c * b) = a / b\"\n  using nonzero_mult_divide_mult_cancel_right [of b c a] by (simp add: ac_simps)\n\nlemma diff_frac_eq:\n  \"y \\<noteq> 0 \\<Longrightarrow> z \\<noteq> 0 \\<Longrightarrow> x / y - w / z = (x * z - w * y) / (y * z)\"\n  by (simp add: field_simps)\n\nlemma frac_eq_eq:\n  \"y \\<noteq> 0 \\<Longrightarrow> z \\<noteq> 0 \\<Longrightarrow> (x / y = w / z) = (x * z = w * y)\"\n  by (simp add: field_simps)\n\nlemma divide_minus1 [simp]: \"x / - 1 = - x\"\n  using nonzero_minus_divide_right [of \"1\" x] by simp\n\ntext\\<open>This version builds in division by zero while also re-orienting\n      the right-hand side.\\<close>\nlemma inverse_mult_distrib [simp]:\n  \"inverse (a * b) = inverse a * inverse b\"\nproof cases\n  assume \"a \\<noteq> 0 \\<and> b \\<noteq> 0\"\n  thus ?thesis by (simp add: nonzero_inverse_mult_distrib ac_simps)\nnext\n  assume \"\\<not> (a \\<noteq> 0 \\<and> b \\<noteq> 0)\"\n  thus ?thesis by force\nqed\n\nlemma inverse_divide [simp]:\n  \"inverse (a / b) = b / a\"\n  by (simp add: divide_inverse mult.commute)\n\n\ntext \\<open>Calculations with fractions\\<close>\n\ntext\\<open>There is a whole bunch of simp-rules just for class \\<open>field\\<close> but none for class \\<open>field\\<close> and \\<open>nonzero_divides\\<close>\nbecause the latter are covered by a simproc.\\<close>\n\nlemmas mult_divide_mult_cancel_left = nonzero_mult_divide_mult_cancel_left\n\nlemmas mult_divide_mult_cancel_right = nonzero_mult_divide_mult_cancel_right\n\nlemma divide_divide_eq_right [simp]:\n  \"a / (b / c) = (a * c) / b\"\n  by (simp add: divide_inverse ac_simps)\n\nlemma divide_divide_eq_left [simp]:\n  \"(a / b) / c = a / (b * c)\"\n  by (simp add: divide_inverse mult.assoc)\n\nlemma divide_divide_times_eq:\n  \"(x / y) / (z / w) = (x * w) / (y * z)\"\n  by simp\n\ntext \\<open>Special Cancellation Simprules for Division\\<close>\n\nlemma mult_divide_mult_cancel_left_if [simp]:\n  shows \"(c * a) / (c * b) = (if c = 0 then 0 else a / b)\"\n  by simp\n\n\ntext \\<open>Division and Unary Minus\\<close>\n\nlemma minus_divide_right:\n  \"- (a / b) = a / - b\"\n  by (simp add: divide_inverse)\n\nlemma divide_minus_right [simp]:\n  \"a / - b = - (a / b)\"\n  by (simp add: divide_inverse)\n\nlemma minus_divide_divide:\n  \"(- a) / (- b) = a / b\"\n  by (cases \"b=0\") (simp_all add: nonzero_minus_divide_divide)\n\nlemma inverse_eq_1_iff [simp]:\n  \"inverse x = 1 \\<longleftrightarrow> x = 1\"\n  using inverse_eq_iff_eq [of x 1] by simp\n\nlemma divide_eq_0_iff [simp]:\n  \"a / b = 0 \\<longleftrightarrow> a = 0 \\<or> b = 0\"\n  by (simp add: divide_inverse)\n\nlemma divide_cancel_right [simp]:\n  \"a / c = b / c \\<longleftrightarrow> c = 0 \\<or> a = b\"\n  by (cases \"c=0\") (simp_all add: divide_inverse)\n\nlemma divide_cancel_left [simp]:\n  \"c / a = c / b \\<longleftrightarrow> c = 0 \\<or> a = b\"\n  by (cases \"c=0\") (simp_all add: divide_inverse)\n\nlemma divide_eq_1_iff [simp]:\n  \"a / b = 1 \\<longleftrightarrow> b \\<noteq> 0 \\<and> a = b\"\n  by (cases \"b=0\") (simp_all add: right_inverse_eq)\n\nlemma one_eq_divide_iff [simp]:\n  \"1 = a / b \\<longleftrightarrow> b \\<noteq> 0 \\<and> a = b\"\n  by (simp add: eq_commute [of 1])\n\nlemma divide_eq_minus_1_iff:\n   \"(a / b = - 1) \\<longleftrightarrow> b \\<noteq> 0 \\<and> a = - b\"\nusing divide_eq_1_iff by fastforce\n\nlemma times_divide_times_eq:\n  \"(x / y) * (z / w) = (x * z) / (y * w)\"\n  by simp\n\nlemma add_frac_num:\n  \"y \\<noteq> 0 \\<Longrightarrow> x / y + z = (x + z * y) / y\"\n  by (simp add: add_divide_distrib)\n\nlemma add_num_frac:\n  \"y \\<noteq> 0 \\<Longrightarrow> z + x / y = (x + z * y) / y\"\n  by (simp add: add_divide_distrib add.commute)\n\nlemma dvd_field_iff:\n  \"a dvd b \\<longleftrightarrow> (a = 0 \\<longrightarrow> b = 0)\"\nproof (cases \"a = 0\")\n  case False\n  then have \"b = a * (b / a)\"\n    by (simp add: field_simps)\n  then have \"a dvd b\" ..\n  with False show ?thesis\n    by simp\nqed simp\n\nlemma inj_divide_right [simp]:\n  \"inj (\\<lambda>b. b / a) \\<longleftrightarrow> a \\<noteq> 0\"\nproof -\n  have \"(\\<lambda>b. b / a) = (*) (inverse a)\"\n    by (simp add: field_simps fun_eq_iff)\n  then have \"inj (\\<lambda>y. y / a) \\<longleftrightarrow> inj ((*) (inverse a))\"\n    by simp\n  also have \"\\<dots> \\<longleftrightarrow> inverse a \\<noteq> 0\"\n    by simp\n  also have \"\\<dots> \\<longleftrightarrow> a \\<noteq> 0\"\n    by simp\n  finally show ?thesis\n    by simp\nqed\n\nend\n\nclass field_char_0 = field + ring_char_0\n\n\nsubsection \\<open>Ordered fields\\<close>\n\nclass field_abs_sgn = field + idom_abs_sgn\nbegin\n\nlemma sgn_inverse [simp]:\n  \"sgn (inverse a) = inverse (sgn a)\"\nproof (cases \"a = 0\")\n  case True then show ?thesis by simp\nnext\n  case False\n  then have \"a * inverse a = 1\"\n    by simp\n  then have \"sgn (a * inverse a) = sgn 1\"\n    by simp\n  then have \"sgn a * sgn (inverse a) = 1\"\n    by (simp add: sgn_mult)\n  then have \"inverse (sgn a) * (sgn a * sgn (inverse a)) = inverse (sgn a) * 1\"\n    by simp\n  then have \"(inverse (sgn a) * sgn a) * sgn (inverse a) = inverse (sgn a)\"\n    by (simp add: ac_simps)\n  with False show ?thesis\n    by (simp add: sgn_eq_0_iff)\nqed\n\nlemma abs_inverse [simp]:\n  \"\\<bar>inverse a\\<bar> = inverse \\<bar>a\\<bar>\"\nproof -\n  from sgn_mult_abs [of \"inverse a\"] sgn_mult_abs [of a]\n  have \"inverse (sgn a) * \\<bar>inverse a\\<bar> = inverse (sgn a * \\<bar>a\\<bar>)\"\n    by simp\n  then show ?thesis by (auto simp add: sgn_eq_0_iff)\nqed\n    \nlemma sgn_divide [simp]:\n  \"sgn (a / b) = sgn a / sgn b\"\n  unfolding divide_inverse sgn_mult by simp\n\nlemma abs_divide [simp]:\n  \"\\<bar>a / b\\<bar> = \\<bar>a\\<bar> / \\<bar>b\\<bar>\"\n  unfolding divide_inverse abs_mult by simp\n  \nend\n\nclass linordered_field = field + linordered_idom\nbegin\n\nlemma positive_imp_inverse_positive:\n  assumes a_gt_0: \"0 < a\"\n  shows \"0 < inverse a\"\nproof -\n  have \"0 < a * inverse a\"\n    by (simp add: a_gt_0 [THEN less_imp_not_eq2])\n  thus \"0 < inverse a\"\n    by (simp add: a_gt_0 [THEN less_not_sym] zero_less_mult_iff)\nqed\n\nlemma negative_imp_inverse_negative:\n  \"a < 0 \\<Longrightarrow> inverse a < 0\"\n  using positive_imp_inverse_positive [of \"-a\"]\n  by (simp add: nonzero_inverse_minus_eq less_imp_not_eq)\n\nlemma inverse_le_imp_le:\n  assumes invle: \"inverse a \\<le> inverse b\" and apos: \"0 < a\"\n  shows \"b \\<le> a\"\nproof (rule classical)\n  assume \"\\<not> b \\<le> a\"\n  hence \"a < b\"  by (simp add: linorder_not_le)\n  hence bpos: \"0 < b\"  by (blast intro: apos less_trans)\n  hence \"a * inverse a \\<le> a * inverse b\"\n    by (simp add: apos invle less_imp_le mult_left_mono)\n  hence \"(a * inverse a) * b \\<le> (a * inverse b) * b\"\n    by (simp add: bpos less_imp_le mult_right_mono)\n  thus \"b \\<le> a\"  by (simp add: mult.assoc apos bpos less_imp_not_eq2)\nqed\n\nlemma inverse_positive_imp_positive:\n  assumes inv_gt_0: \"0 < inverse a\" and nz: \"a \\<noteq> 0\"\n  shows \"0 < a\"\nproof -\n  have \"0 < inverse (inverse a)\"\n    using inv_gt_0 by (rule positive_imp_inverse_positive)\n  thus \"0 < a\"\n    using nz by (simp add: nonzero_inverse_inverse_eq)\nqed\n\nlemma inverse_negative_imp_negative:\n  assumes inv_less_0: \"inverse a < 0\" and nz: \"a \\<noteq> 0\"\n  shows \"a < 0\"\nproof -\n  have \"inverse (inverse a) < 0\"\n    using inv_less_0 by (rule negative_imp_inverse_negative)\n  thus \"a < 0\" using nz by (simp add: nonzero_inverse_inverse_eq)\nqed\n\nlemma linordered_field_no_lb:\n  \"\\<forall>x. \\<exists>y. y < x\"\nproof\n  fix x::'a\n  have m1: \"- (1::'a) < 0\" by simp\n  from add_strict_right_mono[OF m1, where c=x]\n  have \"(- 1) + x < x\" by simp\n  thus \"\\<exists>y. y < x\" by blast\nqed\n\nlemma linordered_field_no_ub:\n  \"\\<forall> x. \\<exists>y. y > x\"\nproof\n  fix x::'a\n  have m1: \" (1::'a) > 0\" by simp\n  from add_strict_right_mono[OF m1, where c=x]\n  have \"1 + x > x\" by simp\n  thus \"\\<exists>y. y > x\" by blast\nqed\n\nlemma less_imp_inverse_less:\n  assumes less: \"a < b\" and apos:  \"0 < a\"\n  shows \"inverse b < inverse a\"\nproof (rule ccontr)\n  assume \"\\<not> inverse b < inverse a\"\n  hence \"inverse a \\<le> inverse b\" by simp\n  hence \"\\<not> (a < b)\"\n    by (simp add: not_less inverse_le_imp_le [OF _ apos])\n  thus False by (rule notE [OF _ less])\nqed\n\nlemma inverse_less_imp_less:\n  assumes \"inverse a < inverse b\" \"0 < a\"\n  shows \"b < a\"\nproof -\n  have \"a \\<noteq> b\"\n    using assms by (simp add: less_le)\n  moreover have \"b \\<le> a\"\n    using assms by (force simp: less_le dest: inverse_le_imp_le)\n  ultimately show ?thesis\n    by (simp add: less_le)\nqed\n\ntext\\<open>Both premises are essential. Consider -1 and 1.\\<close>\nlemma inverse_less_iff_less [simp]:\n  \"0 < a \\<Longrightarrow> 0 < b \\<Longrightarrow> inverse a < inverse b \\<longleftrightarrow> b < a\"\n  by (blast intro: less_imp_inverse_less dest: inverse_less_imp_less)\n\nlemma le_imp_inverse_le:\n  \"a \\<le> b \\<Longrightarrow> 0 < a \\<Longrightarrow> inverse b \\<le> inverse a\"\n  by (force simp add: le_less less_imp_inverse_less)\n\nlemma inverse_le_iff_le [simp]:\n  \"0 < a \\<Longrightarrow> 0 < b \\<Longrightarrow> inverse a \\<le> inverse b \\<longleftrightarrow> b \\<le> a\"\n  by (blast intro: le_imp_inverse_le dest: inverse_le_imp_le)\n\n\ntext\\<open>These results refer to both operands being negative.  The opposite-sign\ncase is trivial, since inverse preserves signs.\\<close>\nlemma inverse_le_imp_le_neg:\n  assumes \"inverse a \\<le> inverse b\" \"b < 0\"\n  shows \"b \\<le> a\"\nproof (rule classical)\n  assume \"\\<not> b \\<le> a\"\n  with \\<open>b < 0\\<close> have \"a < 0\"\n    by force\n  with assms show \"b \\<le> a\"\n    using inverse_le_imp_le [of \"-b\" \"-a\"] by (simp add: nonzero_inverse_minus_eq)\nqed\n\nlemma less_imp_inverse_less_neg:\n  assumes \"a < b\" \"b < 0\"\n  shows \"inverse b < inverse a\"\nproof -\n  have \"a < 0\"\n    using assms by (blast intro: less_trans)\n  with less_imp_inverse_less [of \"-b\" \"-a\"] show ?thesis\n    by (simp add: nonzero_inverse_minus_eq assms)\nqed\n\nlemma inverse_less_imp_less_neg:\n  assumes \"inverse a < inverse b\" \"b < 0\"\n  shows \"b < a\"\nproof (rule classical)\n  assume \"\\<not> b < a\"\n  with \\<open>b < 0\\<close> have \"a < 0\"\n    by force\n  with inverse_less_imp_less [of \"-b\" \"-a\"] show ?thesis\n    by (simp add: nonzero_inverse_minus_eq assms)\nqed\n\nlemma inverse_less_iff_less_neg [simp]:\n  \"a < 0 \\<Longrightarrow> b < 0 \\<Longrightarrow> inverse a < inverse b \\<longleftrightarrow> b < a\"\n  using inverse_less_iff_less [of \"-b\" \"-a\"]\n  by (simp del: inverse_less_iff_less add: nonzero_inverse_minus_eq)\n\nlemma le_imp_inverse_le_neg:\n  \"a \\<le> b \\<Longrightarrow> b < 0 \\<Longrightarrow> inverse b \\<le> inverse a\"\n  by (force simp add: le_less less_imp_inverse_less_neg)\n\nlemma inverse_le_iff_le_neg [simp]:\n  \"a < 0 \\<Longrightarrow> b < 0 \\<Longrightarrow> inverse a \\<le> inverse b \\<longleftrightarrow> b \\<le> a\"\n  by (blast intro: le_imp_inverse_le_neg dest: inverse_le_imp_le_neg)\n\nlemma one_less_inverse:\n  \"0 < a \\<Longrightarrow> a < 1 \\<Longrightarrow> 1 < inverse a\"\n  using less_imp_inverse_less [of a 1, unfolded inverse_1] .\n\nlemma one_le_inverse:\n  \"0 < a \\<Longrightarrow> a \\<le> 1 \\<Longrightarrow> 1 \\<le> inverse a\"\n  using le_imp_inverse_le [of a 1, unfolded inverse_1] .\n\nlemma pos_le_divide_eq [field_simps]:\n  assumes \"0 < c\"\n  shows \"a \\<le> b / c \\<longleftrightarrow> a * c \\<le> b\"\nproof -\n  from assms have \"a \\<le> b / c \\<longleftrightarrow> a * c \\<le> (b / c) * c\"\n    using mult_le_cancel_right [of a c \"b * inverse c\"] by (auto simp add: field_simps)\n  also have \"... \\<longleftrightarrow> a * c \\<le> b\"\n    by (simp add: less_imp_not_eq2 [OF assms] divide_inverse mult.assoc)\n  finally show ?thesis .\nqed\n\nlemma pos_less_divide_eq [field_simps]:\n  assumes \"0 < c\"\n  shows \"a < b / c \\<longleftrightarrow> a * c < b\"\nproof -\n  from assms have \"a < b / c \\<longleftrightarrow> a * c < (b / c) * c\"\n    using mult_less_cancel_right [of a c \"b / c\"] by auto\n  also have \"... = (a*c < b)\"\n    by (simp add: less_imp_not_eq2 [OF assms] divide_inverse mult.assoc)\n  finally show ?thesis .\nqed\n\nlemma neg_less_divide_eq [field_simps]:\n  assumes \"c < 0\"\n  shows \"a < b / c \\<longleftrightarrow> b < a * c\"\nproof -\n  from assms have \"a < b / c \\<longleftrightarrow> (b / c) * c < a * c\"\n    using mult_less_cancel_right [of \"b / c\" c a] by auto\n  also have \"... \\<longleftrightarrow> b < a * c\"\n    by (simp add: less_imp_not_eq [OF assms] divide_inverse mult.assoc)\n  finally show ?thesis .\nqed\n\nlemma neg_le_divide_eq [field_simps]:\n  assumes \"c < 0\"\n  shows \"a \\<le> b / c \\<longleftrightarrow> b \\<le> a * c\"\nproof -\n  from assms have \"a \\<le> b / c \\<longleftrightarrow> (b / c) * c \\<le> a * c\"\n    using mult_le_cancel_right [of \"b * inverse c\" c a] by (auto simp add: field_simps)\n  also have \"... \\<longleftrightarrow> b \\<le> a * c\"\n    by (simp add: less_imp_not_eq [OF assms] divide_inverse mult.assoc)\n  finally show ?thesis .\nqed\n\nlemma pos_divide_le_eq [field_simps]:\n  assumes \"0 < c\"\n  shows \"b / c \\<le> a \\<longleftrightarrow> b \\<le> a * c\"\nproof -\n  from assms have \"b / c \\<le> a \\<longleftrightarrow> (b / c) * c \\<le> a * c\"\n    using mult_le_cancel_right [of \"b / c\" c a] by auto\n  also have \"... \\<longleftrightarrow> b \\<le> a * c\"\n    by (simp add: less_imp_not_eq2 [OF assms] divide_inverse mult.assoc)\n  finally show ?thesis .\nqed\n\nlemma pos_divide_less_eq [field_simps]:\n  assumes \"0 < c\"\n  shows \"b / c < a \\<longleftrightarrow> b < a * c\"\nproof -\n  from assms have \"b / c < a \\<longleftrightarrow> (b / c) * c < a * c\"\n    using mult_less_cancel_right [of \"b / c\" c a] by auto\n  also have \"... \\<longleftrightarrow> b < a * c\"\n    by (simp add: less_imp_not_eq2 [OF assms] divide_inverse mult.assoc)\n  finally show ?thesis .\nqed\n\nlemma neg_divide_le_eq [field_simps]:\n  assumes \"c < 0\"\n  shows \"b / c \\<le> a \\<longleftrightarrow> a * c \\<le> b\"\nproof -\n  from assms have \"b / c \\<le> a \\<longleftrightarrow> a * c \\<le> (b / c) * c\"\n    using mult_le_cancel_right [of a c \"b / c\"] by auto\n  also have \"... \\<longleftrightarrow> a * c \\<le> b\"\n    by (simp add: less_imp_not_eq [OF assms] divide_inverse mult.assoc)\n  finally show ?thesis .\nqed\n\nlemma neg_divide_less_eq [field_simps]:\n  assumes \"c < 0\"\n  shows \"b / c < a \\<longleftrightarrow> a * c < b\"\nproof -\n  from assms have \"b / c < a \\<longleftrightarrow> a * c < b / c * c\"\n    using mult_less_cancel_right [of a c \"b / c\"] by auto\n  also have \"... \\<longleftrightarrow> a * c < b\"\n    by (simp add: less_imp_not_eq [OF assms] divide_inverse mult.assoc)\n  finally show ?thesis .\nqed\n\ntext\\<open>The following \\<open>field_simps\\<close> rules are necessary, as minus is always moved atop of\ndivision but we want to get rid of division.\\<close>\n\nlemma pos_le_minus_divide_eq [field_simps]: \"0 < c \\<Longrightarrow> a \\<le> - (b / c) \\<longleftrightarrow> a * c \\<le> - b\"\n  unfolding minus_divide_left by (rule pos_le_divide_eq)\n\nlemma neg_le_minus_divide_eq [field_simps]: \"c < 0 \\<Longrightarrow> a \\<le> - (b / c) \\<longleftrightarrow> - b \\<le> a * c\"\n  unfolding minus_divide_left by (rule neg_le_divide_eq)\n\nlemma pos_less_minus_divide_eq [field_simps]: \"0 < c \\<Longrightarrow> a < - (b / c) \\<longleftrightarrow> a * c < - b\"\n  unfolding minus_divide_left by (rule pos_less_divide_eq)\n\nlemma neg_less_minus_divide_eq [field_simps]: \"c < 0 \\<Longrightarrow> a < - (b / c) \\<longleftrightarrow> - b < a * c\"\n  unfolding minus_divide_left by (rule neg_less_divide_eq)\n\nlemma pos_minus_divide_less_eq [field_simps]: \"0 < c \\<Longrightarrow> - (b / c) < a \\<longleftrightarrow> - b < a * c\"\n  unfolding minus_divide_left by (rule pos_divide_less_eq)\n\nlemma neg_minus_divide_less_eq [field_simps]: \"c < 0 \\<Longrightarrow> - (b / c) < a \\<longleftrightarrow> a * c < - b\"\n  unfolding minus_divide_left by (rule neg_divide_less_eq)\n\nlemma pos_minus_divide_le_eq [field_simps]: \"0 < c \\<Longrightarrow> - (b / c) \\<le> a \\<longleftrightarrow> - b \\<le> a * c\"\n  unfolding minus_divide_left by (rule pos_divide_le_eq)\n\nlemma neg_minus_divide_le_eq [field_simps]: \"c < 0 \\<Longrightarrow> - (b / c) \\<le> a \\<longleftrightarrow> a * c \\<le> - b\"\n  unfolding minus_divide_left by (rule neg_divide_le_eq)\n\nlemma frac_less_eq:\n  \"y \\<noteq> 0 \\<Longrightarrow> z \\<noteq> 0 \\<Longrightarrow> x / y < w / z \\<longleftrightarrow> (x * z - w * y) / (y * z) < 0\"\n  by (subst less_iff_diff_less_0) (simp add: diff_frac_eq )\n\nlemma frac_le_eq:\n  \"y \\<noteq> 0 \\<Longrightarrow> z \\<noteq> 0 \\<Longrightarrow> x / y \\<le> w / z \\<longleftrightarrow> (x * z - w * y) / (y * z) \\<le> 0\"\n  by (subst le_iff_diff_le_0) (simp add: diff_frac_eq )\n\nlemma divide_pos_pos[simp]:\n  \"0 < x \\<Longrightarrow> 0 < y \\<Longrightarrow> 0 < x / y\"\nby(simp add:field_simps)\n\nlemma divide_nonneg_pos:\n  \"0 \\<le> x \\<Longrightarrow> 0 < y \\<Longrightarrow> 0 \\<le> x / y\"\nby(simp add:field_simps)\n\nlemma divide_neg_pos:\n  \"x < 0 \\<Longrightarrow> 0 < y \\<Longrightarrow> x / y < 0\"\n  by(simp add:field_simps)\n\nlemma divide_nonpos_pos:\n  \"x \\<le> 0 \\<Longrightarrow> 0 < y \\<Longrightarrow> x / y \\<le> 0\"\n  by(simp add:field_simps)\n\nlemma divide_pos_neg:\n  \"0 < x \\<Longrightarrow> y < 0 \\<Longrightarrow> x / y < 0\"\n  by(simp add:field_simps)\n\nlemma divide_nonneg_neg:\n  \"0 \\<le> x \\<Longrightarrow> y < 0 \\<Longrightarrow> x / y \\<le> 0\"\n  by(simp add:field_simps)\n\nlemma divide_neg_neg:\n  \"x < 0 \\<Longrightarrow> y < 0 \\<Longrightarrow> 0 < x / y\"\n  by(simp add:field_simps)\n\nlemma divide_nonpos_neg:\n  \"x \\<le> 0 \\<Longrightarrow> y < 0 \\<Longrightarrow> 0 \\<le> x / y\"\n  by(simp add:field_simps)\n\nlemma divide_strict_right_mono:\n  \"\\<lbrakk>a < b; 0 < c\\<rbrakk> \\<Longrightarrow> a / c < b / c\"\n  by (simp add: less_imp_not_eq2 divide_inverse mult_strict_right_mono\n      positive_imp_inverse_positive)\n\n\nlemma divide_strict_right_mono_neg:\n  assumes \"b < a\" \"c < 0\" shows \"a / c < b / c\"\nproof -\n  have \"b / - c < a / - c\"\n    by (rule divide_strict_right_mono) (use assms in auto)\n  then show ?thesis\n    by (simp add: less_imp_not_eq)\nqed\n\ntext\\<open>The last premise ensures that \\<^term>\\<open>a\\<close> and \\<^term>\\<open>b\\<close>\n      have the same sign\\<close>\nlemma divide_strict_left_mono:\n  \"\\<lbrakk>b < a; 0 < c; 0 < a*b\\<rbrakk> \\<Longrightarrow> c / a < c / b\"\n  by (auto simp: field_simps zero_less_mult_iff mult_strict_right_mono)\n\nlemma divide_left_mono:\n  \"\\<lbrakk>b \\<le> a; 0 \\<le> c; 0 < a*b\\<rbrakk> \\<Longrightarrow> c / a \\<le> c / b\"\n  by (auto simp: field_simps zero_less_mult_iff mult_right_mono)\n\nlemma divide_strict_left_mono_neg:\n  \"\\<lbrakk>a < b; c < 0; 0 < a*b\\<rbrakk> \\<Longrightarrow> c / a < c / b\"\n  by (auto simp: field_simps zero_less_mult_iff mult_strict_right_mono_neg)\n\nlemma mult_imp_div_pos_le: \"0 < y \\<Longrightarrow> x \\<le> z * y \\<Longrightarrow> x / y \\<le> z\"\nby (subst pos_divide_le_eq, assumption+)\n\nlemma mult_imp_le_div_pos: \"0 < y \\<Longrightarrow> z * y \\<le> x \\<Longrightarrow> z \\<le> x / y\"\nby(simp add:field_simps)\n\nlemma mult_imp_div_pos_less: \"0 < y \\<Longrightarrow> x < z * y \\<Longrightarrow> x / y < z\"\nby(simp add:field_simps)\n\nlemma mult_imp_less_div_pos: \"0 < y \\<Longrightarrow> z * y < x \\<Longrightarrow> z < x / y\"\nby(simp add:field_simps)\n\nlemma frac_le:\n  assumes \"0 \\<le> y\" \"x \\<le> y\" \"0 < w\" \"w \\<le> z\"\n  shows \"x / z \\<le> y / w\"\nproof (rule mult_imp_div_pos_le)\n  show \"z > 0\"\n    using assms by simp\n  have \"x \\<le> y * z / w\"\n  proof (rule mult_imp_le_div_pos [OF \\<open>0 < w\\<close>])\n    show \"x * w \\<le> y * z\"\n      using assms by (auto intro: mult_mono)\n  qed\n  also have \"... = y / w * z\"\n    by simp\n  finally show \"x \\<le> y / w * z\" .\nqed\n\nlemma frac_less:\n  assumes \"0 \\<le> x\" \"x < y\" \"0 < w\" \"w \\<le> z\"\n  shows \"x / z < y / w\"\nproof (rule mult_imp_div_pos_less)\n  show \"z > 0\"\n    using assms by simp\n  have \"x < y * z / w\"\n  proof (rule mult_imp_less_div_pos [OF \\<open>0 < w\\<close>])\n    show \"x * w < y * z\"\n      using assms by (auto intro: mult_less_le_imp_less)\n  qed\n  also have \"... = y / w * z\"\n    by simp\n  finally show \"x < y / w * z\" .\nqed\n\nlemma frac_less2:\n  assumes \"0 < x\" \"x \\<le> y\" \"0 < w\" \"w < z\"\n  shows \"x / z < y / w\"\nproof (rule mult_imp_div_pos_less)\n  show \"z > 0\"\n    using assms by simp\n  show \"x < y / w * z\"\n    using assms by (force intro: mult_imp_less_div_pos mult_le_less_imp_less)\nqed\n\nlemma less_half_sum: \"a < b \\<Longrightarrow> a < (a+b) / (1+1)\"\n  by (simp add: field_simps zero_less_two)\n\nlemma gt_half_sum: \"a < b \\<Longrightarrow> (a+b)/(1+1) < b\"\n  by (simp add: field_simps zero_less_two)\n\nsubclass unbounded_dense_linorder\nproof\n  fix x y :: 'a\n  from less_add_one show \"\\<exists>y. x < y\" ..\n  from less_add_one have \"x + (- 1) < (x + 1) + (- 1)\" by (rule add_strict_right_mono)\n  then have \"x - 1 < x + 1 - 1\" by simp\n  then have \"x - 1 < x\" by (simp add: algebra_simps)\n  then show \"\\<exists>y. y < x\" ..\n  show \"x < y \\<Longrightarrow> \\<exists>z>x. z < y\" by (blast intro!: less_half_sum gt_half_sum)\nqed\n\nsubclass field_abs_sgn ..\n\nlemma inverse_sgn [simp]:\n  \"inverse (sgn a) = sgn a\"\n  by (cases a 0 rule: linorder_cases) simp_all\n\nlemma divide_sgn [simp]:\n  \"a / sgn b = a * sgn b\"\n  by (cases b 0 rule: linorder_cases) simp_all\n\nlemma nonzero_abs_inverse:\n  \"a \\<noteq> 0 \\<Longrightarrow> \\<bar>inverse a\\<bar> = inverse \\<bar>a\\<bar>\"\n  by (rule abs_inverse)\n\nlemma nonzero_abs_divide:\n  \"b \\<noteq> 0 \\<Longrightarrow> \\<bar>a / b\\<bar> = \\<bar>a\\<bar> / \\<bar>b\\<bar>\"\n  by (rule abs_divide)\n\nlemma field_le_epsilon:\n  assumes e: \"\\<And>e. 0 < e \\<Longrightarrow> x \\<le> y + e\"\n  shows \"x \\<le> y\"\nproof (rule dense_le)\n  fix t assume \"t < x\"\n  hence \"0 < x - t\" by (simp add: less_diff_eq)\n  from e [OF this] have \"x + 0 \\<le> x + (y - t)\" by (simp add: algebra_simps)\n  then have \"0 \\<le> y - t\" by (simp only: add_le_cancel_left)\n  then show \"t \\<le> y\" by (simp add: algebra_simps)\nqed\n\nlemma inverse_positive_iff_positive [simp]: \"(0 < inverse a) = (0 < a)\"\nproof (cases \"a = 0\")\n  case False\n  then show ?thesis\n    by (blast intro: inverse_positive_imp_positive positive_imp_inverse_positive)\nqed auto\n\nlemma inverse_negative_iff_negative [simp]: \"(inverse a < 0) = (a < 0)\"\nproof (cases \"a = 0\")\n  case False\n  then show ?thesis\n    by (blast intro: inverse_negative_imp_negative negative_imp_inverse_negative)\nqed auto\n\nlemma inverse_nonnegative_iff_nonnegative [simp]: \"0 \\<le> inverse a \\<longleftrightarrow> 0 \\<le> a\"\n  by (simp add: not_less [symmetric])\n\nlemma inverse_nonpositive_iff_nonpositive [simp]: \"inverse a \\<le> 0 \\<longleftrightarrow> a \\<le> 0\"\n  by (simp add: not_less [symmetric])\n\nlemma one_less_inverse_iff: \"1 < inverse x \\<longleftrightarrow> 0 < x \\<and> x < 1\"\n  using less_trans[of 1 x 0 for x]\n  by (cases x 0 rule: linorder_cases) (auto simp add: field_simps)\n\nlemma one_le_inverse_iff: \"1 \\<le> inverse x \\<longleftrightarrow> 0 < x \\<and> x \\<le> 1\"\nproof (cases \"x = 1\")\n  case True then show ?thesis by simp\nnext\n  case False then have \"inverse x \\<noteq> 1\" by simp\n  then have \"1 \\<noteq> inverse x\" by blast\n  then have \"1 \\<le> inverse x \\<longleftrightarrow> 1 < inverse x\" by (simp add: le_less)\n  with False show ?thesis by (auto simp add: one_less_inverse_iff)\nqed\n\nlemma inverse_less_1_iff: \"inverse x < 1 \\<longleftrightarrow> x \\<le> 0 \\<or> 1 < x\"\n  by (simp add: not_le [symmetric] one_le_inverse_iff)\n\nlemma inverse_le_1_iff: \"inverse x \\<le> 1 \\<longleftrightarrow> x \\<le> 0 \\<or> 1 \\<le> x\"\n  by (simp add: not_less [symmetric] one_less_inverse_iff)\n\nlemma [field_split_simps, divide_simps]:\n  shows le_divide_eq: \"a \\<le> b / c \\<longleftrightarrow> (if 0 < c then a * c \\<le> b else if c < 0 then b \\<le> a * c else a \\<le> 0)\"\n    and divide_le_eq: \"b / c \\<le> a \\<longleftrightarrow> (if 0 < c then b \\<le> a * c else if c < 0 then a * c \\<le> b else 0 \\<le> a)\"\n    and less_divide_eq: \"a < b / c \\<longleftrightarrow> (if 0 < c then a * c < b else if c < 0 then b < a * c else a < 0)\"\n    and divide_less_eq: \"b / c < a \\<longleftrightarrow> (if 0 < c then b < a * c else if c < 0 then a * c < b else 0 < a)\"\n    and le_minus_divide_eq: \"a \\<le> - (b / c) \\<longleftrightarrow> (if 0 < c then a * c \\<le> - b else if c < 0 then - b \\<le> a * c else a \\<le> 0)\"\n    and minus_divide_le_eq: \"- (b / c) \\<le> a \\<longleftrightarrow> (if 0 < c then - b \\<le> a * c else if c < 0 then a * c \\<le> - b else 0 \\<le> a)\"\n    and less_minus_divide_eq: \"a < - (b / c) \\<longleftrightarrow> (if 0 < c then a * c < - b else if c < 0 then - b < a * c else  a < 0)\"\n    and minus_divide_less_eq: \"- (b / c) < a \\<longleftrightarrow> (if 0 < c then - b < a * c else if c < 0 then a * c < - b else 0 < a)\"\n  by (auto simp: field_simps not_less dest: order.antisym)\n\ntext \\<open>Division and Signs\\<close>\n\nlemma\n  shows zero_less_divide_iff: \"0 < a / b \\<longleftrightarrow> 0 < a \\<and> 0 < b \\<or> a < 0 \\<and> b < 0\"\n    and divide_less_0_iff: \"a / b < 0 \\<longleftrightarrow> 0 < a \\<and> b < 0 \\<or> a < 0 \\<and> 0 < b\"\n    and zero_le_divide_iff: \"0 \\<le> a / b \\<longleftrightarrow> 0 \\<le> a \\<and> 0 \\<le> b \\<or> a \\<le> 0 \\<and> b \\<le> 0\"\n    and divide_le_0_iff: \"a / b \\<le> 0 \\<longleftrightarrow> 0 \\<le> a \\<and> b \\<le> 0 \\<or> a \\<le> 0 \\<and> 0 \\<le> b\"\n  by (auto simp add: field_split_simps)\n\ntext \\<open>Division and the Number One\\<close>\n\ntext\\<open>Simplify expressions equated with 1\\<close>\n\nlemma zero_eq_1_divide_iff [simp]: \"0 = 1 / a \\<longleftrightarrow> a = 0\"\n  by (cases \"a = 0\") (auto simp: field_simps)\n\nlemma one_divide_eq_0_iff [simp]: \"1 / a = 0 \\<longleftrightarrow> a = 0\"\n  using zero_eq_1_divide_iff[of a] by simp\n\ntext\\<open>Simplify expressions such as \\<open>0 < 1/x\\<close> to \\<open>0 < x\\<close>\\<close>\n\nlemma zero_le_divide_1_iff [simp]:\n  \"0 \\<le> 1 / a \\<longleftrightarrow> 0 \\<le> a\"\n  by (simp add: zero_le_divide_iff)\n\nlemma zero_less_divide_1_iff [simp]:\n  \"0 < 1 / a \\<longleftrightarrow> 0 < a\"\n  by (simp add: zero_less_divide_iff)\n\nlemma divide_le_0_1_iff [simp]:\n  \"1 / a \\<le> 0 \\<longleftrightarrow> a \\<le> 0\"\n  by (simp add: divide_le_0_iff)\n\nlemma divide_less_0_1_iff [simp]:\n  \"1 / a < 0 \\<longleftrightarrow> a < 0\"\n  by (simp add: divide_less_0_iff)\n\nlemma divide_right_mono:\n  \"\\<lbrakk>a \\<le> b; 0 \\<le> c\\<rbrakk> \\<Longrightarrow> a/c \\<le> b/c\"\n  by (force simp add: divide_strict_right_mono le_less)\n\nlemma divide_right_mono_neg: \"a \\<le> b \\<Longrightarrow> c \\<le> 0 \\<Longrightarrow> b / c \\<le> a / c\"\n  by (auto dest: divide_right_mono [of _ _ \"- c\"])\n\nlemma divide_left_mono_neg: \"a \\<le> b \\<Longrightarrow> c \\<le> 0 \\<Longrightarrow> 0 < a * b \\<Longrightarrow> c / a \\<le> c / b\"\n  by (auto simp add: mult.commute dest: divide_left_mono [of _ _ \"- c\"])\n\nlemma inverse_le_iff: \"inverse a \\<le> inverse b \\<longleftrightarrow> (0 < a * b \\<longrightarrow> b \\<le> a) \\<and> (a * b \\<le> 0 \\<longrightarrow> a \\<le> b)\"\n  by (cases a 0 b 0 rule: linorder_cases[case_product linorder_cases])\n     (auto simp add: field_simps zero_less_mult_iff mult_le_0_iff)\n\nlemma inverse_less_iff: \"inverse a < inverse b \\<longleftrightarrow> (0 < a * b \\<longrightarrow> b < a) \\<and> (a * b \\<le> 0 \\<longrightarrow> a < b)\"\n  by (subst less_le) (auto simp: inverse_le_iff)\n\nlemma divide_le_cancel: \"a / c \\<le> b / c \\<longleftrightarrow> (0 < c \\<longrightarrow> a \\<le> b) \\<and> (c < 0 \\<longrightarrow> b \\<le> a)\"\n  by (simp add: divide_inverse mult_le_cancel_right)\n\nlemma divide_less_cancel: \"a / c < b / c \\<longleftrightarrow> (0 < c \\<longrightarrow> a < b) \\<and> (c < 0 \\<longrightarrow> b < a) \\<and> c \\<noteq> 0\"\n  by (auto simp add: divide_inverse mult_less_cancel_right)\n\ntext\\<open>Simplify quotients that are compared with the value 1.\\<close>\n\nlemma le_divide_eq_1:\n  \"(1 \\<le> b / a) = ((0 < a \\<and> a \\<le> b) \\<or> (a < 0 \\<and> b \\<le> a))\"\n  by (auto simp add: le_divide_eq)\n\nlemma divide_le_eq_1:\n  \"(b / a \\<le> 1) = ((0 < a \\<and> b \\<le> a) \\<or> (a < 0 \\<and> a \\<le> b) \\<or> a=0)\"\n  by (auto simp add: divide_le_eq)\n\nlemma less_divide_eq_1:\n  \"(1 < b / a) = ((0 < a \\<and> a < b) \\<or> (a < 0 \\<and> b < a))\"\n  by (auto simp add: less_divide_eq)\n\nlemma divide_less_eq_1:\n  \"(b / a < 1) = ((0 < a \\<and> b < a) \\<or> (a < 0 \\<and> a < b) \\<or> a=0)\"\n  by (auto simp add: divide_less_eq)\n\nlemma divide_nonneg_nonneg [simp]:\n  \"0 \\<le> x \\<Longrightarrow> 0 \\<le> y \\<Longrightarrow> 0 \\<le> x / y\"\n  by (auto simp add: field_split_simps)\n\nlemma divide_nonpos_nonpos:\n  \"x \\<le> 0 \\<Longrightarrow> y \\<le> 0 \\<Longrightarrow> 0 \\<le> x / y\"\n  by (auto simp add: field_split_simps)\n\nlemma divide_nonneg_nonpos:\n  \"0 \\<le> x \\<Longrightarrow> y \\<le> 0 \\<Longrightarrow> x / y \\<le> 0\"\n  by (auto simp add: field_split_simps)\n\nlemma divide_nonpos_nonneg:\n  \"x \\<le> 0 \\<Longrightarrow> 0 \\<le> y \\<Longrightarrow> x / y \\<le> 0\"\n  by (auto simp add: field_split_simps)\n\ntext \\<open>Conditional Simplification Rules: No Case Splits\\<close>\n\nlemma le_divide_eq_1_pos [simp]:\n  \"0 < a \\<Longrightarrow> (1 \\<le> b/a) = (a \\<le> b)\"\n  by (auto simp add: le_divide_eq)\n\nlemma le_divide_eq_1_neg [simp]:\n  \"a < 0 \\<Longrightarrow> (1 \\<le> b/a) = (b \\<le> a)\"\n  by (auto simp add: le_divide_eq)\n\nlemma divide_le_eq_1_pos [simp]:\n  \"0 < a \\<Longrightarrow> (b/a \\<le> 1) = (b \\<le> a)\"\n  by (auto simp add: divide_le_eq)\n\nlemma divide_le_eq_1_neg [simp]:\n  \"a < 0 \\<Longrightarrow> (b/a \\<le> 1) = (a \\<le> b)\"\n  by (auto simp add: divide_le_eq)\n\nlemma less_divide_eq_1_pos [simp]:\n  \"0 < a \\<Longrightarrow> (1 < b/a) = (a < b)\"\n  by (auto simp add: less_divide_eq)\n\nlemma less_divide_eq_1_neg [simp]:\n  \"a < 0 \\<Longrightarrow> (1 < b/a) = (b < a)\"\n  by (auto simp add: less_divide_eq)\n\nlemma divide_less_eq_1_pos [simp]:\n  \"0 < a \\<Longrightarrow> (b/a < 1) = (b < a)\"\n  by (auto simp add: divide_less_eq)\n\nlemma divide_less_eq_1_neg [simp]:\n  \"a < 0 \\<Longrightarrow> b/a < 1 \\<longleftrightarrow> a < b\"\n  by (auto simp add: divide_less_eq)\n\nlemma eq_divide_eq_1 [simp]:\n  \"(1 = b/a) = ((a \\<noteq> 0 \\<and> a = b))\"\n  by (auto simp add: eq_divide_eq)\n\nlemma divide_eq_eq_1 [simp]:\n  \"(b/a = 1) = ((a \\<noteq> 0 \\<and> a = b))\"\n  by (auto simp add: divide_eq_eq)\n\nlemma abs_div_pos: \"0 < y \\<Longrightarrow> \\<bar>x\\<bar> / y = \\<bar>x / y\\<bar>\"\n  by (simp add: order_less_imp_le)\n\nlemma zero_le_divide_abs_iff [simp]: \"(0 \\<le> a / \\<bar>b\\<bar>) = (0 \\<le> a \\<or> b = 0)\"\n  by (auto simp: zero_le_divide_iff)\n\nlemma divide_le_0_abs_iff [simp]: \"(a / \\<bar>b\\<bar> \\<le> 0) = (a \\<le> 0 \\<or> b = 0)\"\n  by (auto simp: divide_le_0_iff)\n\nlemma field_le_mult_one_interval:\n  assumes *: \"\\<And>z. \\<lbrakk> 0 < z ; z < 1 \\<rbrakk> \\<Longrightarrow> z * x \\<le> y\"\n  shows \"x \\<le> y\"\nproof (cases \"0 < x\")\n  assume \"0 < x\"\n  thus ?thesis\n    using dense_le_bounded[of 0 1 \"y/x\"] *\n    unfolding le_divide_eq if_P[OF \\<open>0 < x\\<close>] by simp\nnext\n  assume \"\\<not>0 < x\" hence \"x \\<le> 0\" by simp\n  obtain s::'a where s: \"0 < s\" \"s < 1\" using dense[of 0 \"1::'a\"] by auto\n  hence \"x \\<le> s * x\" using mult_le_cancel_right[of 1 x s] \\<open>x \\<le> 0\\<close> by auto\n  also note *[OF s]\n  finally show ?thesis .\nqed\n\ntext\\<open>For creating values between \\<^term>\\<open>u\\<close> and \\<^term>\\<open>v\\<close>.\\<close>\nlemma scaling_mono:\n  assumes \"u \\<le> v\" \"0 \\<le> r\" \"r \\<le> s\"\n  shows \"u + r * (v - u) / s \\<le> v\"\nproof -\n  have \"r/s \\<le> 1\" using assms\n    using divide_le_eq_1 by fastforce\n  moreover have \"0 \\<le> v - u\"\n    using assms by simp\n  ultimately have \"(r/s) * (v - u) \\<le> 1 * (v - u)\"\n    by (rule mult_right_mono)\n  then show ?thesis\n    by (simp add: field_simps)\nqed\n\nend\n\ntext \\<open>Min/max Simplification Rules\\<close>\n\nlemma min_mult_distrib_left:\n  fixes x::\"'a::linordered_idom\" \n  shows \"p * min x y = (if 0 \\<le> p then min (p*x) (p*y) else max (p*x) (p*y))\"\nby (auto simp add: min_def max_def mult_le_cancel_left)\n\nlemma min_mult_distrib_right:\n  fixes x::\"'a::linordered_idom\" \n  shows \"min x y * p = (if 0 \\<le> p then min (x*p) (y*p) else max (x*p) (y*p))\"\nby (auto simp add: min_def max_def mult_le_cancel_right)\n\nlemma min_divide_distrib_right:\n  fixes x::\"'a::linordered_field\" \n  shows \"min x y / p = (if 0 \\<le> p then min (x/p) (y/p) else max (x/p) (y/p))\"\nby (simp add: min_mult_distrib_right divide_inverse)\n\nlemma max_mult_distrib_left:\n  fixes x::\"'a::linordered_idom\" \n  shows \"p * max x y = (if 0 \\<le> p then max (p*x) (p*y) else min (p*x) (p*y))\"\nby (auto simp add: min_def max_def mult_le_cancel_left)\n\nlemma max_mult_distrib_right:\n  fixes x::\"'a::linordered_idom\" \n  shows \"max x y * p = (if 0 \\<le> p then max (x*p) (y*p) else min (x*p) (y*p))\"\nby (auto simp add: min_def max_def mult_le_cancel_right)\n\nlemma max_divide_distrib_right:\n  fixes x::\"'a::linordered_field\" \n  shows \"max x y / p = (if 0 \\<le> p then max (x/p) (y/p) else min (x/p) (y/p))\"\nby (simp add: max_mult_distrib_right divide_inverse)\n\nhide_fact (open) field_inverse field_divide_inverse field_inverse_zero\n\ncode_identifier\n  code_module Fields \\<rightharpoonup> (SML) Arith and (OCaml) Arith and (Haskell) Arith\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/Fields.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8499711832583695, "lm_q2_score": 0.8688267881258485, "lm_q1q2_score": 0.7384777331498962}}
{"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\ntheory Quantum\nimports\n  Jordan_Normal_Form.Matrix\n  \"HOL-Library.Nonpos_Ints\"\n  Basics\n  Binary_Nat\nbegin\n\nsection \\<open>Qubits and Quantum Gates\\<close>\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  apply (auto simp: cpx_vec_length_def vec_of_list_def vec_of_list_index)\n  by (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    apply (auto simp: algebra_simps)\n    by (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  apply(simp add: gate_def unitary_def)\n  apply(simp add: X_def)\n  done\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  apply(simp add: gate_def unitary_def)\n  apply(simp add: Y_def)\n  done\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  apply(simp add: gate_def unitary_def)\n  apply(simp add: Z_def)\n  done\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  apply(simp add: gate_def unitary_def)\n  apply(simp add: H_def)\n  done\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  apply(simp add: gate_def unitary_def)\n  apply(simp add: CNOT_def)\n  done\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     apply (auto simp: state_def bell00_def bell01_def bell10_def bell11_def ket_vec_def)\n     apply (auto simp: cpx_vec_length_def Set_Interval.lessThan_atLeast0 cmod_def power2_eq_square) \n  done\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     apply (auto simp: bell00_def ket_vec_def)\n  done\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     apply (auto simp: bell01_def ket_vec_def)\n  done\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     apply (auto simp: bell10_def ket_vec_def)\n  done\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     apply (auto simp: bell11_def ket_vec_def)\n  done\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\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*)\n\nend\n", "meta": {"author": "AnthonyBordg", "repo": "Isabelle_marries_Dirac", "sha": "ab313fb4028c99bd5d97f8e30aaf1644e200d57b", "save_path": "github-repos/isabelle/AnthonyBordg-Isabelle_marries_Dirac", "path": "github-repos/isabelle/AnthonyBordg-Isabelle_marries_Dirac/Isabelle_marries_Dirac-ab313fb4028c99bd5d97f8e30aaf1644e200d57b/Quantum.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8688267762381844, "lm_q2_score": 0.849971181358171, "lm_q1q2_score": 0.7384777213947809}}
{"text": "theory Intervals\nimports \"~~/src/HOL/Library/Float\"\n        \"~~/src/HOL/Library/Set_Algebras\"\nbegin\n\n(* I define my own interval type here. I then define the basic arithmetic operations on intervals. \n   This way, I can define and evaluate interval polynomials. *)\ntypedef (overloaded) 'a interval = \"{(a::'a::order, b). a \\<le> b}\"\n  by auto\n\nsetup_lifting type_definition_interval\n\nlift_definition Ivl::\"'a::order \\<Rightarrow> 'a \\<Rightarrow> 'a interval\"\nis \"\\<lambda>a b. (a, max a b)\"\n  by (simp add: max_def)\n\nlift_definition proc_of::\"'a::order interval \\<Rightarrow> 'a \\<times> 'a\"\nis Rep_interval .\n  \nlift_definition lower::\"('a::order) interval \\<Rightarrow> 'a\" is fst .\nlift_definition upper::\"('a::order) interval \\<Rightarrow> 'a\" is snd .\n\ndefinition width :: \"'a::{order,minus} interval \\<Rightarrow> 'a\"\nwhere \"width i = upper i - lower i\"\n\ndefinition mid :: \"float interval \\<Rightarrow> float\"\nwhere \"mid i = (lower i + upper i) * Float 1 (-1)\"\n\ndefinition set_of :: \"'a::order interval \\<Rightarrow> 'a set\"\nwhere \"set_of i = {lower i..upper i}\"\n\ndefinition interval_of :: \"'a::order \\<Rightarrow> 'a interval\"\nwhere \"interval_of x = Ivl x x\"\n\ndefinition interval_map :: \"('a::order \\<Rightarrow> 'b::order) \\<Rightarrow> 'a interval \\<Rightarrow> 'b interval\"\nwhere \"interval_map f i = Ivl (f (lower i)) (f (upper i))\"\n\ndefinition interval_union :: \"'a::order interval \\<Rightarrow> 'a interval \\<Rightarrow> 'a interval\"\nwhere \"interval_union a b = Ivl (min (lower a) (lower b)) (max (upper a) (upper b))\"\n\nfun interval_list_union :: \"'a::linorder interval list \\<Rightarrow> 'a interval\"\nwhere \"interval_list_union [] = undefined\"\n    | \"interval_list_union [I] = I\"\n    | \"interval_list_union (I#Is) = interval_union I (interval_list_union Is)\"\n\nlemmas [simp] = proc_of_def\n\nlemma lower_le_upper:\nshows \"lower i \\<le> upper i\"\nproof-\n  obtain y where i_def: \"i = Abs_interval y\" and y_def: \"y \\<in> {(a, b). a \\<le> b}\"\n    using Abs_interval_cases by auto\n  hence \"fst y \\<le> snd y\"\n    by auto\n  thus ?thesis\n    by (simp add: i_def interval.Abs_interval_inverse[OF y_def] lower_def upper_def)\nqed\n\nlemma lower_Ivl[simp]:\nshows \"lower (Ivl a b) = a\"\nby (simp add: Ivl.rep_eq lower.rep_eq)\n\nlemma upper_Ivl_a[simp]:\nassumes \"b \\<le> a\"\nshows \"upper (Ivl a b) = a\"\nusing assms\nby (simp add: upper_def Ivl.rep_eq max_def)\n\nlemma upper_Ivl_b[simp]:\nassumes \"a \\<le> b\"\nshows \"upper (Ivl a b) = b\"\nusing assms\nby (simp add: upper_def Ivl.rep_eq max_def)\n\nlemma lower_refl[simp]:\nshows \"lower (Ivl a a) = a\"\nby (simp add: Ivl.rep_eq lower.rep_eq)\n\nlemma upper_refl[simp]:\nshows \"upper (Ivl a a) = a\"\nby (simp add: Ivl.rep_eq max_def upper.rep_eq)\n\nlemma upper_Ivl_upper_lower[simp]:\nshows \"upper (Ivl (lower I) (upper I)) = upper I\"\nusing lower_le_upper upper_Ivl_b\nby auto\n\nlemma upper_Ivl_upper_lower_real[simp]:\nfixes I::\"float interval\"\nshows \"upper (Ivl (real_of_float (lower I)) (real_of_float(upper I))) = real_of_float (upper I)\"\nusing lower_le_upper less_eq_float.rep_eq upper_Ivl_b\nby blast\n\nlemma set_of_interval_union:\nfixes A::\"'a::linorder interval\"\nshows \"set_of A \\<union> set_of B \\<subseteq> set_of (interval_union A B)\"\nby (auto simp add: min_def max_def set_of_def interval_union_def)\n\nlemma interval_union_commute:\nfixes A::\"'a::linorder interval\"\nshows \"interval_union A B = interval_union B A\"\nby (auto simp add: min_def max_def set_of_def interval_union_def)\n\nlemma interval_union_mono1:\nfixes A :: \"'a::linorder interval\"\nshows \"set_of a \\<subseteq> set_of (interval_union a A)\"\nby (auto simp add: set_of_def interval_union_def min_def max_def)\n\nlemma interval_union_mono2:\nfixes A :: \"'a::linorder interval\"\nshows \"set_of A \\<subseteq> set_of (interval_union a A)\"\nby (auto simp add: set_of_def interval_union_def min_def max_def)\n\nlemma interval_exhaust:\nobtains l u\nwhere \"(i::'a::order interval) = Ivl l u\"\nand   \"l \\<le> u\"\nby (metis Ivl.abs_eq Rep_interval_inverse lower.rep_eq lower_le_upper max_absorb2 prod.swap_def swap_simp swap_swap upper.rep_eq)\n\n(* Definitions that make some common assumptions about lists of intervals easier to write. *)\ndefinition all_in :: \"'a::order list \\<Rightarrow> 'a interval list \\<Rightarrow> bool\"\n(infix \"(all'_in)\" 50)\nwhere \"x all_in I = (length x = length I \\<and> (\\<forall>i < length I. x!i \\<in> set_of (I!i)))\"\n\ndefinition all_subset :: \"'a::order interval list \\<Rightarrow> 'a interval list \\<Rightarrow> bool\"\n(infix \"(all'_subset)\" 50)\nwhere \"I all_subset J = (length I = length J \\<and> (\\<forall>i < length I. set_of (I!i) \\<subseteq> set_of (J!i)))\"\n\nlemmas [simp] = all_in_def all_subset_def\n\nlemma mid_in_interval:\nshows \"mid i \\<in> set_of i\"\nproof-\n  obtain l u where i_def: \"i = Ivl l u\" and \"l \\<le> u\" using interval_exhaust by blast\n  \n  {\n    have \"real_of_float l * Float 1 1  \\<le> (real_of_float l + real_of_float u)\"\n      using `l \\<le> u` by (simp add: Float.compute_float_one Float.compute_float_times)\n    hence \"real_of_float l * (Float 1 1 * Float 1 (-1)) \\<le> (real_of_float l + real_of_float u) * Float 1 (-1)\"\n      by simp \n    hence \"real_of_float l \\<le> (real_of_float l + real_of_float u) * Float 1 (- 1)\"\n      by (simp add: Float.compute_float_one Float.compute_float_times)\n  }\n  moreover\n  {\n    have \"(real_of_float l + real_of_float u) \\<le> real_of_float u * Float 1 1 \"\n      using `l \\<le> u` by (simp add: Float.compute_float_one Float.compute_float_times)\n    hence \"(real_of_float l + real_of_float u) * Float 1 (-1) \\<le> real_of_float u * (Float 1 1 * Float 1 (-1))\"\n      by simp\n    hence \"(real_of_float l + real_of_float u) * Float 1 (- 1) \\<le> real_of_float u\"\n      by (simp add: Float.compute_float_one Float.compute_float_times)\n  }\n  ultimately show ?thesis\n    by (simp add: i_def set_of_def mid_def)\nqed\n\nlemma all_subsetD:\nassumes \"I all_subset J\"\nassumes \"x all_in I\"\nshows \"x all_in J\"\nusing assms\nby (auto, auto)\n\ninstantiation \"interval\" :: (\"{order,equal}\") equal\nbegin\n  definition \"equal_class.equal a b \\<equiv> (lower a = lower b) \\<and> (upper a = upper b)\"\n  instance\n  apply(standard)\n  apply(simp add: equal_interval_def)\n  by (smt interval_exhaust lower_Ivl upper_Ivl_b)\nend\n\n(* Arithmetic on intervals. *)\ninstantiation \"interval\" :: (\"{order,plus}\") plus\nbegin\n  definition \"a + b = Ivl (lower a + lower b) (upper a + upper b)\"\n  instance ..\nend\ninstantiation \"interval\" :: (\"{order,minus}\") minus\nbegin\n  definition \"a - b = Ivl (lower a - upper b) (upper a - lower b)\"\n  instance ..\nend\ninstantiation \"interval\" :: (\"{order,uminus}\") uminus\nbegin\n  definition \"-a = Ivl (-upper a) (-lower a)\"\n  instance ..\nend\ninstantiation \"interval\" :: (\"{times,order}\") times\nbegin\ndefinition \"a * b = Ivl (min (min (lower a * lower b) (upper a * lower b)) \n                             (min (lower a * upper b) (upper a * upper b)))\n                        (max (max (lower a * lower b) (upper a * lower b)) \n                             (max (lower a * upper b) (upper a * upper b)))\"\ninstance ..\nend\ninstantiation \"interval\" :: (\"{order,zero}\") zero\nbegin\n  definition \"0 = Ivl 0 0\"\n  instance ..\nend\ninstantiation \"interval\" :: (\"{order,one}\") one\nbegin\n  definition \"1 = Ivl 1 1\"\n  instance ..\nend\ninstantiation \"interval\" :: (\"{order,inverse}\") inverse\nbegin\n  definition \"inverse a = Ivl (min (inverse (lower a)) (inverse (upper a))) (max (inverse (lower a)) (inverse (upper a)))\"\n  instance ..\nend\ninstantiation \"interval\" :: (\"{order,times,one}\") power\nbegin\n  instance ..\nend\n\ninstantiation \"interval\" :: (linordered_idom) comm_monoid_add\nbegin\n  instance\n  proof\n    fix a b c::\"'a interval\"\n    show \"a + b + c = a + (b + c)\"\n      apply(cases a rule: interval_exhaust, cases b rule: interval_exhaust, cases c rule: interval_exhaust)\n      by (simp add: plus_interval_def algebra_simps)\n  next\n    fix a b::\"'a interval\"\n    show \"a + b = b + a\"\n      by (simp add: plus_interval_def algebra_simps)\n  next\n    fix a::\"'a interval\"\n    show \"0 + a = a\"\n      by (cases a rule: interval_exhaust, simp add: plus_interval_def zero_interval_def)\n  qed\nend\n\ninstantiation \"interval\" :: (linordered_idom) cancel_semigroup_add\nbegin\n  instance\n  proof\n    fix a b c::\"'a interval\"\n    assume \"a + b = a + c\"\n    thus \"b = c\"\n      apply(cases a rule: interval_exhaust, cases b rule: interval_exhaust, cases c rule: interval_exhaust)\n      apply(simp add: plus_interval_def)\n      by (metis add.commute add_mono add_right_imp_eq lower_Ivl upper_Ivl_b)\n  next\n    \n    fix a b c::\"'a interval\"\n    assume \"b + a = c + a\"\n    thus \"b = c\"\n      apply(cases a rule: interval_exhaust, cases b rule: interval_exhaust, cases c rule: interval_exhaust)\n      apply(simp add: plus_interval_def)\n      by (metis add_mono_thms_linordered_semiring(1) add_right_cancel lower_Ivl upper_Ivl_b)\n  qed\nend\n\nfun centered :: \"float interval \\<Rightarrow> float interval\"\nwhere \"centered i = i - interval_of (mid i)\"\n\nlemma interval_mul_commute:\nfixes A :: \"'a::linordered_idom interval\"\nshows \"A * B = B * A\"\nby (simp add: times_interval_def min.commute min.left_commute max.commute max.left_commute mult.commute)\n\nlemma interval_times_zero_right[simp]:\nfixes A :: \"'a::linordered_idom interval\"\nshows \"A * 0 = 0\"\nby (simp add: times_interval_def zero_interval_def)\n\nlemma interval_times_zero_left[simp]:\nfixes A :: \"'a::linordered_idom interval\"\nshows \"0 * A = 0\"\nby (simp add: times_interval_def zero_interval_def)\n\nlemma one_times_ivl_left[simp]:\nfixes A :: \"'a::linordered_idom interval\"\nshows \"1 * A = A\"\nby (cases A rule: interval_exhaust, auto simp: times_interval_def one_interval_def min_def max_def)\n\nlemma one_times_ivl_right[simp]:\nfixes A :: \"'a::linordered_idom interval\"\nshows \"A * 1 = A\"\nusing one_times_ivl_left[OF assms, unfolded interval_mul_commute]\nby assumption\n\nlemma set_of_real_to_float[simp]:\nfixes A :: \"float interval\"\nshows \"(real_of_float a \\<in> set_of (interval_map real_of_float A)) = (a \\<in> set_of A)\"\nby (cases A rule: interval_exhaust, simp add: set_of_def interval_map_def)\n\n(* Coercions on intervals. *)\nlemmas [simp] = interval_of_def\n\ndeclare [[coercion \"interval_of :: float \\<Rightarrow> float interval\"]]\ndeclare [[coercion \"interval_of :: real \\<Rightarrow> real interval\"]]\ndeclare [[coercion_map interval_map]]\n\n(* Coercion of a \"float interval\" to a \"real interval\" is homomorph. *)\nlemma interval_map_real_add[simp]:\nfixes i1::\"float interval\"\nshows \"interval_map real_of_float (i1 + i2) = interval_map real_of_float i1 + interval_map real_of_float i2\"\nby (cases i1 rule: interval_exhaust, cases i2 rule: interval_exhaust, simp add: plus_interval_def interval_map_def)\n\nlemma interval_map_real_sub[simp]:\nfixes i1::\"float interval\"\nshows \"interval_map real_of_float (i1 - i2) = interval_map real_of_float i1 - interval_map real_of_float i2\"\nby (cases i1 rule: interval_exhaust, cases i2 rule: interval_exhaust, simp add: minus_interval_def interval_map_def)\n\nlemma interval_map_real_neg[simp]:\nfixes i::\"float interval\"\nshows \"interval_map real_of_float (-i) = - interval_map real_of_float i\"\nby (cases i rule: interval_exhaust, simp add: uminus_interval_def interval_map_def)\n\nlemma interval_map_real_mul[simp]:\nfixes i1::\"float interval\"\nshows \"interval_map real_of_float (i1 * i2) = interval_map real_of_float i1 * interval_map real_of_float i2\"\nby (cases i1 rule: interval_exhaust, cases i2 rule: interval_exhaust, simp add: times_interval_def real_of_float_max real_of_float_min interval_map_def)\n\nlemma interval_map_real_pow[simp]:\nfixes i::\"float interval\"\nshows \"interval_map real_of_float (i ^ n) = interval_map real_of_float i ^  n\"\napply(cases i rule: interval_exhaust, induction n)\nusing interval_map_real_mul by (auto simp: one_interval_def interval_map_def)\n\nlemma interval_map_real_Ivl[simp]:\nfixes l::float and u::float\nshows \"interval_map real_of_float (Ivl l u) = Ivl (real_of_float l) (real_of_float u)\"\napply(simp add: interval_map_def)\nby (metis interval_exhaust less_eq_float.rep_eq lower_Ivl max.cobounded2 max_def upper_Ivl_a upper_Ivl_b)\n\n(* Operations on intervals are monotone. *)\nlemma set_of_add_mono:\nfixes a :: \"'a::ordered_ab_group_add\"\nassumes \"a \\<in> set_of A\"\nassumes \"b \\<in> set_of B\"\nshows \"a + b \\<in> set_of (A + B)\"\napply(cases A rule: interval_exhaust, cases B rule: interval_exhaust)\nusing assms\nby (simp add: set_of_def plus_interval_def add_mono)\n\nlemma set_of_minus_mono:\nfixes a :: \"'a::ordered_ab_group_add\"\nassumes \"a \\<in> set_of A\"\nassumes \"b \\<in> set_of B\"\nshows \"a - b \\<in> set_of (A - B)\"\napply(cases A rule: interval_exhaust, cases B rule: interval_exhaust)\nusing assms\nby (simp add: minus_interval_def set_of_def diff_mono)\n\nlemma set_of_uminus_mono:\nfixes a :: \"'a::ordered_ab_group_add\"\nassumes \"a \\<in> set_of A\"\nshows \"-a \\<in> set_of (-A)\"\napply(cases A rule: interval_exhaust)\nusing assms\nby (simp add: uminus_interval_def set_of_def)\n\nlemma set_of_mult_mono:\nfixes a :: \"'a::linordered_idom\"\nassumes \"a \\<in> set_of A\"\nassumes \"b \\<in> set_of B\"\nshows \"a * b \\<in> set_of (A * B)\"\nproof-\n  obtain la ua where A_def: \"A = Ivl la ua\" and lea: \"la \\<le> ua\" using interval_exhaust by auto\n  obtain lb ub where B_def: \"B = Ivl lb ub\" and leb: \"lb \\<le> ub\" using interval_exhaust by auto\n  have a_def: \"a \\<in> {la..ua}\" using assms(1) lea by (simp add: A_def set_of_def)\n  have b_def: \"b \\<in> {lb..ub}\" using assms(2) leb by (simp add: B_def set_of_def)\n    \n  have ineqs: \"la \\<le> a\" \"a \\<le> ua\" \"lb \\<le> b\" \"b \\<le> ub\"\n    using a_def b_def\n    by auto\n  hence ineqs': \"-a \\<le> -la\" \"-ua \\<le> -a\" \"-b \\<le> -lb\" \"-ub \\<le> -b\"\n    by(simp_all)\n  \n  show ?thesis\n    using mult_mono[OF ineqs(1) ineqs(3), simplified]\n          mult_mono'[OF ineqs(2) ineqs'(3), simplified]\n          mult_mono'[OF ineqs'(1) ineqs(4), simplified]\n          mult_mono[OF ineqs'(2) ineqs'(4), simplified]\n          mult_mono[OF ineqs'(1) ineqs'(3), simplified]\n          mult_mono'[OF ineqs'(2) ineqs(3), simplified]\n          mult_mono'[OF ineqs(1) ineqs'(4), simplified]\n          mult_mono[OF ineqs(2) ineqs(4), simplified]\n          lea leb\n    apply(simp add: A_def B_def times_interval_def set_of_def min_le_iff_disj le_max_iff_disj, safe)\n    by (smt ineqs(1) ineqs(2) le_less not_le order_trans zero_le_mult_iff)+\nqed\n\n\n\nlemma set_of_power_mono:\nfixes a :: \"'a::linordered_idom\"\nassumes \"a \\<in> set_of A\"\nshows \"a^n \\<in> set_of (A^n)\"\nusing assms\nby (induction n, simp_all add: set_of_mult_mono one_interval_def)\n\n(* TODO: Clean this proof up! *)\nlemma set_of_add_distrib:\nfixes A :: \"'a::linordered_idom interval\"\nshows \"set_of A + set_of B = set_of (A + B)\"\nproof-\n  obtain la ua where A_def: \"A = Ivl la ua\" and lea: \"la \\<le> ua\" using interval_exhaust by auto\n  obtain lb ub where B_def: \"B = Ivl lb ub\" and leb: \"lb \\<le> ub\" using interval_exhaust by auto\n  from assms\n  show ?thesis\n    using lea leb\n    apply(simp add: A_def B_def plus_interval_def set_plus_def)\n    apply(rule)\n    apply(rule)\n    apply(safe)\n    apply(simp_all add: add_mono set_of_def)\n    apply(safe)\n    proof(goal_cases)\n      case (1 x)\n      def wa\\<equiv>\"ua - la\"\n      def wb\\<equiv>\"ub - lb\"\n      def w\\<equiv>\"wa + wb\"\n      def d\\<equiv>\"x - la - lb\"\n      have \"0 \\<le> wa\" using 1 by (simp add: wa_def)\n      have \"0 \\<le> wb\" using 1 by (simp add: wb_def)\n      have \"0 \\<le> w\" using 1 by (simp add: w_def wa_def wb_def)\n      hence \"0 \\<le> d\" using 1 by (simp add: d_def)\n      have \"d \\<le> w\" using 1 by (simp add: d_def w_def wa_def wb_def)\n      hence \"d \\<le> wa + wb\" by (simp add: w_def)\n      \n      show ?case\n      apply(cases \"wa \\<le> wb\")\n      proof-\n        case True\n        def da\\<equiv>\"max 0 (min wa (d - wa))\"\n        def db\\<equiv>\"d - da\"\n        \n        have d_decomp: \"d = da + db\"\n          by (simp add: da_def db_def)\n        have \"x = d + la + lb\"\n          by (simp add: d_def)\n        also have \"... =  (la + da) + (lb + db)\"\n          by (simp add: d_decomp)\n        finally have x_decomp: \"x = (la + da) + (lb + db)\" .\n        show \"\\<exists>a\\<in>{la..ua}. \\<exists>b\\<in>{lb..ub}. x = a + b\"\n          apply(rule)+\n          apply(rule x_decomp)\n          apply(simp)\n          apply(safe)\n          using `0 \\<le> d` d_decomp da_def apply linarith\n          using True `d \\<le> wa + wb` d_decomp da_def wb_def apply linarith\n          apply(simp, safe)\n          apply (simp add: da_def)\n          using \"1\"(1) da_def wa_def by auto\n      next\n        case False\n        def db\\<equiv>\"max 0 (min wb (d - wb))\"\n        def da\\<equiv>\"d - db\"\n        \n        have d_decomp: \"d = da + db\"\n          by (simp add: da_def db_def)\n        have \"x = d + la + lb\"\n          by (simp add: d_def)\n        also have \"... =  (la + da) + (lb + db)\"\n          by (simp add: d_decomp)\n        finally have x_decomp: \"x = (la + da) + (lb + db)\" .\n        \n        show \"\\<exists>a\\<in>{la..ua}. \\<exists>b\\<in>{lb..ub}. x = a + b\"\n          apply(rule)+\n          apply(rule x_decomp)\n          apply(simp, safe)\n          using db_def apply auto[1]\n          using \"1\"(2) db_def wb_def apply auto[1]\n          apply(simp, safe)\n          using `0 \\<le> d` da_def db_def apply auto[1]\n          using False `d \\<le> wa + wb` d_decomp db_def wa_def by linarith\n      qed\n    qed\nqed\n\nlemma set_of_add_cong:\nfixes A :: \"'a::linordered_idom interval\"\nassumes \"set_of A = set_of A'\"\nassumes \"set_of B = set_of B'\"\nshows \"set_of (A + B) = set_of (A' + B')\"\nby (simp add: set_of_add_distrib[symmetric] assms)\n\nlemma set_of_add_inc_left:\nfixes A :: \"'a::linordered_idom interval\"\nassumes \"set_of A \\<subseteq> set_of A'\"\nshows \"set_of (A + B) \\<subseteq> set_of (A' + B)\"\nby (simp add: set_of_add_distrib[symmetric] set_plus_mono2[OF assms])\n\nlemma set_of_add_inc_right:\nfixes A :: \"'a::linordered_idom interval\"\nassumes \"set_of B \\<subseteq> set_of B'\"\nshows \"set_of (A + B) \\<subseteq> set_of (A + B')\"\nusing set_of_add_inc_left[OF assms]\nby (simp add: add.commute)\n\nlemma set_of_add_inc:\nfixes A :: \"'a::linordered_idom interval\"\nassumes \"set_of A \\<subseteq> set_of A'\"\nassumes \"set_of B \\<subseteq> set_of B'\"\nshows \"set_of (A + B) \\<subseteq> set_of (A' + B')\"\nusing set_of_add_inc_left[OF assms(1)] set_of_add_inc_right[OF assms(2)]\nby auto\n\nlemma set_of_neg_inc:\nfixes A :: \"'a::linordered_idom interval\"\nassumes \"set_of A \\<subseteq> set_of A'\"\nshows \"set_of (-A) \\<subseteq> set_of (-A')\"\napply(cases A rule: interval_exhaust, cases A' rule: interval_exhaust)\nusing assms by (simp add: uminus_interval_def set_of_def)\n\nlemma set_of_sub_inc_left:\nfixes A :: \"'a::linordered_idom interval\"\nassumes \"set_of A \\<subseteq> set_of A'\"\nshows \"set_of (A - B) \\<subseteq> set_of (A' - B)\"\napply(cases A rule: interval_exhaust, cases B rule: interval_exhaust, cases A' rule: interval_exhaust)\nusing assms by (simp add: uminus_interval_def minus_interval_def plus_interval_def set_of_def)\n\nlemma set_of_sub_inc_right:\nfixes A :: \"'a::linordered_idom interval\"\nassumes \"set_of B \\<subseteq> set_of B'\"\nshows \"set_of (A - B) \\<subseteq> set_of (A - B')\"\napply(cases A rule: interval_exhaust, cases B rule: interval_exhaust, cases B' rule: interval_exhaust)\nusing assms by (simp add: uminus_interval_def minus_interval_def plus_interval_def set_of_def)\n\nlemma set_of_sub_inc:\nfixes A :: \"'a::linordered_idom interval\"\nassumes \"set_of A \\<subseteq> set_of A'\"\nassumes \"set_of B \\<subseteq> set_of B'\"\nshows \"set_of (A - B) \\<subseteq> set_of (A' - B')\"\nusing set_of_sub_inc_left[OF assms(1)] set_of_sub_inc_right[OF assms(2)]\nby auto\n\nlemma set_of_distrib_right:\nfixes A1 :: \"'a::linordered_idom interval\"\nshows \"set_of ((A1 + A2) * B) \\<subseteq> set_of (A1 * B + A2 * B)\"\nproof\n  fix x assume assm: \"x \\<in> set_of ((A1 + A2) * B)\"\n  \n  obtain la1 ua1 where A1_def: \"A1 = Ivl la1 ua1\" and lea1: \"la1 \\<le> ua1\" using interval_exhaust by auto\n  obtain la2 ua2 where A2_def: \"A2 = Ivl la2 ua2\" and lea2: \"la2 \\<le> ua2\" using interval_exhaust by auto\n  obtain lb ub where B_def: \"B = Ivl lb ub\" and leb: \"lb \\<le> ub\" using interval_exhaust by auto\n  \n  from assm\n  have a1: \"min (min ((la1 + la2) * lb) ((ua1 + ua2) * lb)) (min ((la1 + la2) * ub) ((ua1 + ua2) * ub)) \\<le> x\"\n  and  a2: \"x \\<le> max (max ((la1 + la2) * lb) ((ua1 + ua2) * lb)) (max ((la1 + la2) * ub) ((ua1 + ua2) * ub))\"\n    using lea1 lea2 leb\n    by (auto simp: A1_def A2_def B_def times_interval_def plus_interval_def set_of_def)\n    \n  show \"x \\<in> set_of (A1 * B + A2 * B)\"\n    using lea1 lea2 leb\n    apply(simp add: A1_def A2_def B_def times_interval_def plus_interval_def set_of_def)\n    apply(rule conjI[OF order.trans[OF _ a1]  order.trans[OF a2]])\n    apply(smt add_mono distrib_right dual_order.trans min.cobounded1 min_def)\n    apply(subst upper_Ivl_b)\n    apply(simp add: add_mono max.left_commute min_le_iff_disj)\n    apply(smt add_mono distrib_right dual_order.trans max.cobounded2 max_def)\n    done\nqed\n\nlemma set_of_mul_inc_left:\nfixes A :: \"'a::linordered_idom interval\"\nassumes \"set_of A \\<subseteq> set_of A'\"\nshows \"set_of (A * B) \\<subseteq> set_of (A' * B)\"\nproof\n  fix x assume x_def: \"x \\<in> set_of (A * B)\"\n\n  obtain la ua where A_def: \"A = Ivl la ua\" and lea: \"la \\<le> ua\" using interval_exhaust by auto\n  obtain la' ua' where A'_def: \"A' = Ivl la' ua'\" and lea': \"la' \\<le> ua'\" using interval_exhaust by auto\n  obtain lb ub where B_def: \"B = Ivl lb ub\" and leb: \"lb \\<le> ub\" using interval_exhaust by auto\n  \n  from x_def assms lea lea' leb\n  show \"x \\<in> set_of (A' * B)\"\n    apply(simp add: A_def A'_def B_def times_interval_def set_of_def)\n    apply(safe)\n    apply(smt min.absorb_iff2 min.coboundedI2 min_def mult_le_cancel_right)\n    by (smt lea lea' leb max_def max_mult_distrib_right min_def min_le_iff_disj mult_compare_simps(1) order_antisym_conv order_trans)\nqed\n\nlemma set_of_mul_inc_right:\nfixes A :: \"'a::linordered_idom interval\"\nassumes \"set_of B \\<subseteq> set_of B'\"\nshows \"set_of (A * B) \\<subseteq> set_of (A * B')\"\nunfolding interval_mul_commute[of A]\nby (rule set_of_mul_inc_left[OF assms])\n\nlemma set_of_mul_inc:\nfixes A :: \"'a::linordered_idom interval\"\nassumes \"set_of A \\<subseteq> set_of A'\"\nassumes \"set_of B \\<subseteq> set_of B'\"\nshows \"set_of (A * B) \\<subseteq> set_of (A' * B')\" \nusing set_of_mul_inc_right[OF assms(2)] set_of_mul_inc_left[OF assms(1)]\nby auto\n\nlemma set_of_pow_inc:\nfixes A :: \"'a::linordered_idom interval\"\nassumes \"set_of A \\<subseteq> set_of A'\"\nshows \"set_of (A^n) \\<subseteq> set_of (A'^n)\"\nusing assms\nby (induction n, simp_all add: set_of_mul_inc)\n\nlemma set_of_distrib_left:\nfixes A1 :: \"'a::linordered_idom interval\"\nshows \"set_of (B * (A1 + A2)) \\<subseteq> set_of (B * A1 + B * A2)\"\nunfolding interval_mul_commute\nby (rule set_of_distrib_right[unfolded interval_mul_commute])\n\nlemma set_of_distrib_right_left:\nfixes A1 :: \"'a::linordered_idom interval\"\nshows \"set_of ((A1 + A2) * (B1 + B2)) \\<subseteq> set_of (A1 * B1 + A1 * B2 + A2 * B1 + A2 * B2)\"\nproof-\n  have \"set_of ((A1 + A2) * (B1 + B2)) \\<subseteq> set_of (A1 * (B1 + B2) + A2 * (B1 + B2))\"\n    by (rule set_of_distrib_right)\n  also have \"... \\<subseteq> set_of ((A1 * B1 + A1 * B2) + A2 * (B1 + B2))\"\n    by (rule set_of_add_inc_left[OF set_of_distrib_left])\n  also have \"... \\<subseteq> set_of ((A1 * B1 + A1 * B2) + (A2 * B1 + A2 * B2))\"\n    by (rule set_of_add_inc_right[OF set_of_distrib_left])\n  finally show ?thesis\n    by (simp add: add.assoc)\nqed\n\nlemma set_of_mul_contains_zero:\nfixes A :: \"'a::linordered_idom interval\"\nassumes \"0 \\<in> set_of A \\<or> 0 \\<in> set_of B\"\nshows \"0 \\<in> set_of (A * B)\"\nusing assms\napply(cases A rule: interval_exhaust, cases B rule: interval_exhaust)\napply(simp add: times_interval_def set_of_def)\napply(safe)\napply(metis (no_types, hide_lams) eq_iff min_le_iff_disj mult_zero_left mult_zero_right zero_le_mult_iff)\napply(metis le_max_iff_disj mult_zero_right order_refl zero_le_mult_iff)\napply(metis linear min.coboundedI1 min.coboundedI2 mult_nonneg_nonpos mult_nonpos_nonneg)\napply(metis linear max.coboundedI1 max.coboundedI2 mult_nonneg_nonneg mult_nonpos_nonpos)\ndone\n\n(* Subdivisions on intervals and interval vectors. *)\nfun subdivide_interval :: \"nat \\<Rightarrow> float interval \\<Rightarrow> float interval list\"\nwhere \"subdivide_interval 0 I = [I]\"\n    | \"subdivide_interval (Suc n) I = (\n         let m = mid I\n         in (subdivide_interval n (Ivl (lower I) m)) @ (subdivide_interval n (Ivl m (upper I)))\n       )\"\n\nfun split_domain :: \"(float interval \\<Rightarrow> float interval list) \\<Rightarrow> float interval list \\<Rightarrow> float interval list list\"\nwhere \"split_domain split [] = [[]]\"\n    | \"split_domain split (I#Is) = (\n         let S = split I;\n             D = split_domain split Is\n         in concat (map (\\<lambda>d. map (\\<lambda>s. s # d) S) D)\n       )\"\n\nlemma subdivide_interval_length:\nshows \"length (subdivide_interval n I) = 2^n\"\nby(induction n arbitrary: I, simp_all add: Let_def)\n\nlemma subdivide_interval_correct:\nfixes x :: real\nassumes \"x \\<in> set_of I\"\nshows \"list_ex (\\<lambda>i. x \\<in> set_of i) (subdivide_interval n I)\"\nusing assms\napply(induction n arbitrary: x I)\napply(simp_all add: Let_def  list_ex_iff)\n(* TODO: better proof. *)\nby (metis UnCI atLeastAtMost_iff interval_map_def le_cases lower_Ivl mid_in_interval set_of_def upper_Ivl_b upper_Ivl_upper_lower_real)\n\nlemma split_domain_correct:\nfixes x :: \"real list\"\nassumes \"x all_in I\"\nassumes split_correct: \"\\<And>(x::real) (a::float) I. x \\<in> set_of I \\<Longrightarrow> list_ex (\\<lambda>i::float interval. x \\<in> set_of i) (split I)\"\nshows \"list_ex (\\<lambda>s. x all_in s) (split_domain split I)\"\nusing assms(1)\nproof(induction I arbitrary: x)\n  case (Cons I Is x)\n  have \"x \\<noteq> []\"\n    using Cons(2) by auto\n  obtain x' xs where x_decomp: \"x = x' # xs\"\n    using \\<open>x \\<noteq> []\\<close> list.exhaust by auto\n  hence \"x' \\<in> set_of I\" \"xs all_in Is\"\n    using Cons(2)\n    by auto\n  show ?case\n    using Cons(1)[OF \\<open>xs all_in Is\\<close>]\n          split_correct[OF \\<open>x' \\<in> set_of I\\<close>]\n    apply(simp add: list_ex_iff set_of_def)\n    by (smt length_Cons less_Suc_eq_0_disj nth_Cons_0 nth_Cons_Suc x_decomp)\nqed simp\n\nlemma split_domain_nonempty:\nassumes \"\\<And>I. split I \\<noteq> []\"\nshows \"split_domain split I \\<noteq> []\"\nusing last_in_set assms\nby (induction I, auto)\n\nlemma interval_list_union_correct:\nassumes \"S \\<noteq> []\"\nassumes \"i < length S\"\nshows \"set_of (S!i) \\<subseteq> set_of (interval_list_union S)\"\nusing assms\nproof(induction S arbitrary: i)\n  case (Cons a S i)\n  thus ?case\n    proof(cases S)\n      fix b S'\n      assume \"S = b # S'\"\n      hence \"S \\<noteq> []\"\n        by simp\n      show ?thesis\n      proof(cases i)\n        case 0\n        show ?thesis\n          apply(cases S)\n          using interval_union_mono1\n          by (auto simp add: 0)\n      next\n        case (Suc i_prev)\n        hence \"i_prev < length S\"\n        using Cons(3) by simp\n        \n        from Cons(1)[OF \\<open>S \\<noteq> []\\<close> this] Cons(1)\n        have \"set_of ((a # S) ! i) \\<subseteq> set_of (interval_list_union S)\"\n          by (simp add: \\<open>i = Suc i_prev\\<close>)\n        also have \"... \\<subseteq> set_of (interval_list_union (a # S))\"\n          using \\<open>S \\<noteq> []\\<close>\n          apply(cases S)\n          using interval_union_mono2\n          by auto\n        finally show ?thesis .\n      qed\n    qed simp\nqed simp\n\n(* Rounding of float intervals, by increasing their width. *)\nfun round_ivl :: \"nat \\<Rightarrow> float interval \\<Rightarrow> float interval\"\nwhere \"round_ivl prec i = Ivl (float_down prec (lower i)) (float_up prec (upper i))\"\n\nlemma float_down_le:\nshows \"float_down p f \\<le> f\"\nusing round_down by simp\n\nlemma float_up_le:\nshows \"f \\<le> float_up p f\"\nusing round_up by simp\n\nlemma round_ivl_correct:\nshows \"set_of A \\<subseteq> set_of (round_ivl prec A)\"\nproof(cases A rule: interval_exhaust, rule)\n  fix l u x\n  assume A_decomp: \"A = Ivl l u\"\n  and \"l \\<le> u\"\n  and \"x \\<in> set_of A\"\n  hence \"l \\<le> x\" and \"x \\<le> u\"\n    by (simp_all add: set_of_def)\n    \n  have \"float_down prec l \\<le> x\"\n    by (rule order.trans[OF float_down_le \\<open>l \\<le> x\\<close>])\n  moreover have \"x \\<le> float_up prec u\"\n    by (rule order.trans[OF \\<open>x \\<le> u\\<close> float_up_le])\n  ultimately show \"x \\<in> set_of (round_ivl prec A)\"\n    using \\<open>l \\<le> u\\<close> by (simp add: A_decomp set_of_def)\nqed\n\n\nlemma real_of_float_round_ivl_correct:\nshows \"set_of A \\<subseteq> set_of ((round_ivl prec A) :: real interval)\"\nproof(rule)\n  fix x :: real\n  assume \"x \\<in> set_of A\"\n  obtain l u where A_decomp: \"A = Ivl l u\" and \"l \\<le> u\"\n    using interval_exhaust by blast\n  from \\<open>x \\<in> set_of A\\<close> \\<open>l \\<le> u\\<close>\n  have \"l \\<le> x\" \"x \\<le> u\"\n    by (auto simp add: set_of_def A_decomp)\n  hence \"round_down prec l \\<le> l\"\n    and \"u \\<le> round_up prec u\"\n    using round_ivl_correct[of A prec] \\<open>l \\<le> u\\<close> round_up \n    by (auto simp add: A_decomp set_of_def) \n  thus \"x \\<in> set_of (round_ivl prec A)\"\n    using \\<open>l \\<le> x\\<close> \\<open>x \\<le> u\\<close>\n    by (simp add: set_of_def A_decomp)\nqed\n\nend", "meta": {"author": "ctraut", "repo": "Taylor-Models-Isabelle", "sha": "371c28301f16209228defdc62a066532f8be6e6b", "save_path": "github-repos/isabelle/ctraut-Taylor-Models-Isabelle", "path": "github-repos/isabelle/ctraut-Taylor-Models-Isabelle/Taylor-Models-Isabelle-371c28301f16209228defdc62a066532f8be6e6b/Intervals.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267830311355, "lm_q2_score": 0.8499711718571774, "lm_q1q2_score": 0.7384777189138758}}
{"text": "theory GabrielaLimonta\nimports Main\nbegin\n\n(* Homework 4.1 *)\ntype_synonym ('q, 'l) lts = \"'q \\<Rightarrow> 'l \\<Rightarrow> 'q \\<Rightarrow> bool\"\n\ninductive word :: \"('q, 'l) lts \\<Rightarrow> 'q \\<Rightarrow> 'l list \\<Rightarrow> 'q \\<Rightarrow> bool\" for \\<delta> where\n  E: \"word \\<delta> u [] u\" |\n  NE: \"\\<lbrakk>\\<delta> u w x ; word \\<delta> x ws v\\<rbrakk> \\<Longrightarrow> word \\<delta> u (w#ws) v\"\n\ndefinition \"det \\<delta>  \\<equiv> \\<forall> q a q1 q2. \\<delta> q a q1 \\<and> \\<delta> q a q2 \\<longrightarrow> q1 = q2\"\n\ninductive_cases empty_elim: \"word \\<delta> q [] q'\"\ninductive_simps empty_simp: \"word \\<delta> q [] q'\"\n\nlemma aux[simp]: \"word \\<delta> q [] q' \\<longleftrightarrow> q=q'\"\nproof\n  assume a: \"word \\<delta> q [] q'\"\n  thus \"q = q'\" using empty_elim empty_simp by (metis a)\nnext\n  assume \"q=q'\"\n  thus \"word \\<delta> q [] q'\" using word.E by simp\nqed\n\nlemma\n  assumes det: \"det \\<delta>\"\n  shows \"word \\<delta> q w q' \\<Longrightarrow> word \\<delta> q w q'' \\<Longrightarrow> q' = q''\"\n  proof (induction rule: word.induct)\n  print_cases\n  case E show ?case using E by auto\nnext\n  case (NE u w x ws v)\n  show ?case using assms NE aux\n  using [[simp_trace]]\nsorry\nqed\n\n(* Homework 4.2 *)\ndatatype ab = a | b\n\ninductive_set S :: \"ab list set\" where\n  left: \"w1 \\<in> S \\<Longrightarrow> w2 \\<in> S \\<Longrightarrow> [a] @ w1 @ [b] @ w2 \\<in> S\"\n| nil: \"[] \\<in> S\"\n\ninductive_set T :: \"ab list set\" where\n  right: \"w1 \\<in> T \\<Longrightarrow> w2 \\<in> T \\<Longrightarrow> w1 @ [a] @ w2 @ [b] \\<in> T\"\n| nil: \"[] \\<in> T\"\n\n\nlemma S_SS[simp]: \n  assumes \"w1 \\<in> S\"\n  assumes \"w2 \\<in> S\"\n  shows \"w1 @ w2 \\<in> S\"\nusing assms\nproof (induction rule: S.induct)\nprint_cases\n  case nil show ?case using nil.prems S.left S.nil by simp\nnext\n  case (left w1 w2)\n  show ?case using S.left left append_assoc append_Cons append_Nil by auto\nqed\n\nlemma T_TT[simp]: \n  assumes \"w1 \\<in> T\"\n  assumes \"w2 \\<in> T\"\n  shows \"w2 @ w1 \\<in> T\"\nusing assms\nproof (induction rule: T.induct)\nprint_cases\n  case nil show ?case using nil.prems T.right T.nil by simp\nnext\n  case (right w1 w2)\n  show ?case using right append_assoc append_Cons append_Nil by (metis T.right)\nqed\n\n\nlemma S_imp_T:\n  assumes w: \"w \\<in> S\"\n  shows \"w \\<in> T\"\n  using assms\nproof (induction rule: S.induct)\nprint_cases\n  case nil show ?case using T.nil by simp\nnext\n  case (left w1 w2)\n  show ?case\n  using left T.intros append_assoc append_Cons append_Nil T_TT\n  by (metis Tp_T_eq)\nqed\n\nlemma T_imp_S:\n  assumes w: \"w \\<in> T\"\n  shows \"w \\<in> S\"\nusing assms\nproof (induction rule: T.induct)\nprint_cases\n  case nil show ?case using S.nil by simp\nnext\n  case (right w1 w2)\n  show ?case\n  using right S.intros append_assoc append_Cons append_Nil S_SS by simp\nqed\n\nlemma \"S = T\"\nproof\n  show \"S \\<subseteq> T\"\n  using S_imp_T by auto\nnext\n  show \"T \\<subseteq> S\"\n  using T_imp_S by auto\nqed\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/Exercise4/GabrielaLimonta.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711680567799, "lm_q2_score": 0.868826777936422, "lm_q1q2_score": 0.7384777112816291}}
{"text": "theory Typed\n  imports Type \"../00Utils/Utils\"\nbegin\n\ndatatype texpr = \n  TVar var\n  | TConst nat\n  | TLam var ty texpr\n  | TApp texpr texpr\n\nprimrec all_varst :: \"texpr \\<Rightarrow> var set\" where\n  \"all_varst (TVar x) = {x}\"\n| \"all_varst (TConst k) = {}\"\n| \"all_varst (TLam x t e) = insert x (all_varst e)\"\n| \"all_varst (TApp e\\<^sub>1 e\\<^sub>2) = all_varst e\\<^sub>1 \\<union> all_varst e\\<^sub>2\"\n\nprimrec free_varst :: \"texpr \\<Rightarrow> var set\" where\n  \"free_varst (TVar x) = {x}\"\n| \"free_varst (TConst k) = {}\"\n| \"free_varst (TLam x t e) = free_varst e - {x}\"\n| \"free_varst (TApp e\\<^sub>1 e\\<^sub>2) = free_varst e\\<^sub>1 \\<union> free_varst e\\<^sub>2\"\n\nprimrec tvarst :: \"texpr \\<Rightarrow> var set\" where\n  \"tvarst (TVar x) = {}\"\n| \"tvarst (TConst k) = {}\"\n| \"tvarst (TLam x t e) = tvars t \\<union> tvarst e\"\n| \"tvarst (TApp e\\<^sub>1 e\\<^sub>2) = tvarst e\\<^sub>1 \\<union> tvarst e\\<^sub>2\"\n\ninductive typecheckn :: \"(var \\<rightharpoonup> ty) \\<Rightarrow> texpr \\<Rightarrow> ty \\<Rightarrow> bool\" (infix \"\\<turnstile>\\<^sub>n _ :\" 50) where\n  tcn_var [simp]: \"\\<Gamma> x = Some t \\<Longrightarrow> \\<Gamma> \\<turnstile>\\<^sub>n TVar x : t\"\n| tcn_const [simp]: \"\\<Gamma> \\<turnstile>\\<^sub>n TConst k : Base\"\n| tcn_lam [simp]: \"\\<Gamma>(x \\<mapsto> t\\<^sub>1) \\<turnstile>\\<^sub>n e : t\\<^sub>2 \\<Longrightarrow> \\<Gamma> \\<turnstile>\\<^sub>n TLam x t\\<^sub>1 e : Arrow t\\<^sub>1 t\\<^sub>2\"\n| tcn_app [simp]: \"\\<Gamma> \\<turnstile>\\<^sub>n e\\<^sub>1 : Arrow t\\<^sub>1 t\\<^sub>2 \\<Longrightarrow> \\<Gamma> \\<turnstile>\\<^sub>n e\\<^sub>2 : t\\<^sub>1 \\<Longrightarrow> \\<Gamma> \\<turnstile>\\<^sub>n TApp e\\<^sub>1 e\\<^sub>2 : t\\<^sub>2\"\n\ninductive_cases [elim]: \"\\<Gamma> \\<turnstile>\\<^sub>n TVar x : t\"\ninductive_cases [elim]: \"\\<Gamma> \\<turnstile>\\<^sub>n TConst k : t\"\ninductive_cases [elim]: \"\\<Gamma> \\<turnstile>\\<^sub>n TLam x t' e : t\"\ninductive_cases [elim]: \"\\<Gamma> \\<turnstile>\\<^sub>n TApp e\\<^sub>1 e\\<^sub>2 : t\"\n\nprimrec valt :: \"texpr \\<Rightarrow> bool\" where\n  \"valt (TVar x) = False\"\n| \"valt (TConst k) = True\" \n| \"valt (TLam x t e) = True\" \n| \"valt (TApp e\\<^sub>1 e\\<^sub>2) = False\" \n\nprimrec subst_vart :: \"var \\<Rightarrow> var \\<Rightarrow> texpr \\<Rightarrow> texpr\" where\n  \"subst_vart x x' (TVar y) = TVar (if x = y then x' else y)\"\n| \"subst_vart x x' (TConst k) = TConst k\"\n| \"subst_vart x x' (TLam y t e) = TLam y t (if x = y then e else subst_vart x x' e)\"\n| \"subst_vart x x' (TApp e\\<^sub>1 e\\<^sub>2) = TApp (subst_vart x x' e\\<^sub>1) (subst_vart x x' e\\<^sub>2)\"\n\n\n\nfun substt :: \"var \\<Rightarrow> texpr \\<Rightarrow> texpr \\<Rightarrow> texpr\" where\n  \"substt x e' (TVar y) = (if x = y then e' else TVar y)\"\n| \"substt x e' (TConst k) = TConst k\"\n| \"substt x e' (TLam y t e) = (\n    let z = fresh (all_varst e' \\<union> all_varst e \\<union> {x, y})\n    in TLam z t (substt x e' (subst_vart y z e)))\"\n| \"substt x e' (TApp e\\<^sub>1 e\\<^sub>2) = TApp (substt x e' e\\<^sub>1) (substt x e' e\\<^sub>2)\"\n\ninductive evalt :: \"texpr \\<Rightarrow> texpr \\<Rightarrow> bool\" (infix \"\\<Down>\\<^sub>t\" 50) where\n  evt_const [simp]: \"TConst k \\<Down>\\<^sub>t TConst k\"\n| evt_lam [simp]: \"TLam x t e \\<Down>\\<^sub>t TLam x t e\"\n| evt_app [simp]: \"e\\<^sub>1 \\<Down>\\<^sub>t TLam x t e\\<^sub>1' \\<Longrightarrow> e\\<^sub>2 \\<Down>\\<^sub>t v\\<^sub>2 \\<Longrightarrow> substt x v\\<^sub>2 e\\<^sub>1' \\<Down>\\<^sub>t v \\<Longrightarrow> TApp e\\<^sub>1 e\\<^sub>2 \\<Down>\\<^sub>t v\"\n\nlemma [simp]: \"finite (all_varst e)\"\n  by (induction e) simp_all\n\nlemma [simp]: \"free_varst e \\<subseteq> insert x xs \\<Longrightarrow> free_varst (subst_vart x x' e) \\<subseteq> insert x' xs\"\nproof (induction e arbitrary: xs)\n  case (TLam y t e)\n  hence \"free_varst e \\<subseteq> insert x (insert y xs)\" by auto\n  with TLam have \"free_varst (subst_vart x x' e) \\<subseteq> insert x' (insert y xs)\" by simp\n  with TLam show ?case by auto\nqed auto\n\nlemma free_vars_substt [simp]: \"free_varst e \\<subseteq> insert x xs \\<Longrightarrow> free_varst e' \\<subseteq> xs \\<Longrightarrow> \n  free_varst (substt x e' e) \\<subseteq> xs\"\nproof (induction x e' e arbitrary: xs rule: substt.induct)\n  case (3 x e' y t e)\n  let ?z = \"fresh (all_varst e' \\<union> all_varst e \\<union> {x, y})\"\n  from 3 have \"free_varst e \\<subseteq> insert y (insert x xs)\" by auto\n  hence \"free_varst (subst_vart y ?z e) \\<subseteq> insert ?z (insert x xs)\" by simp\n  hence \"free_varst (subst_vart y ?z e) \\<subseteq> insert x (insert ?z xs)\" by auto\n  with 3 show ?case by (auto simp add: Let_def)\nqed auto\n\nlemma free_vars_evalt [simp]: \"e \\<Down>\\<^sub>t v \\<Longrightarrow> free_varst e = {} \\<Longrightarrow> free_varst v = {}\"\nproof (induction e v rule: evalt.induct)\n  case (evt_app e\\<^sub>1 x t e\\<^sub>1' e\\<^sub>2 v\\<^sub>2 v)\n  hence \"free_varst e\\<^sub>1' \\<subseteq> insert x {} \\<and> free_varst v\\<^sub>2 \\<subseteq> {}\" by simp\n  hence \"free_varst (substt x v\\<^sub>2 e\\<^sub>1') \\<subseteq> {}\" by (metis free_vars_substt)\n  with evt_app show ?case by simp\nqed simp_all\n\nlemma free_vars_subs [simp]: \"\\<Gamma> \\<turnstile>\\<^sub>n e : t \\<Longrightarrow> free_varst e \\<subseteq> dom \\<Gamma>\" \n  by (induction \\<Gamma> e t rule: typecheckn.induct) auto\n\nlemma [simp]: \"Map.empty \\<turnstile>\\<^sub>n e : t \\<Longrightarrow> free_varst e = {}\"\n  using free_vars_subs by fastforce\n\nlemma [simp]: \"\\<Gamma> \\<turnstile>\\<^sub>n e : t \\<Longrightarrow> v \\<notin> \\<Union> (tvars ` ran \\<Gamma>) \\<Longrightarrow> v \\<notin> tvarst e \\<Longrightarrow> v \\<notin> tvars t\"\nproof (induction \\<Gamma> e t rule: typecheckn.induct)\n  case (tcn_lam \\<Gamma> x t\\<^sub>1 e t\\<^sub>2)\n  hence \"v \\<notin> \\<Union> (tvars ` ran (\\<Gamma>(x \\<mapsto> t\\<^sub>1)))\" by (auto simp add: ran_def)\n  with tcn_lam show ?case by fastforce\nqed (auto simp add: ran_def)\n\nlemma canonical_basen [dest]: \"\\<Gamma> \\<turnstile>\\<^sub>n e : Base \\<Longrightarrow> valt e \\<Longrightarrow> \\<exists>k. e = TConst k\"\n  by (induction \\<Gamma> e Base rule: typecheckn.induct) simp_all\n\nlemma canonical_arrown [dest]: \"\\<Gamma> \\<turnstile>\\<^sub>n e : Arrow t\\<^sub>1 t\\<^sub>2 \\<Longrightarrow> valt e \\<Longrightarrow> \n    \\<exists>x e'. e = TLam x t\\<^sub>1 e' \\<and> \\<Gamma>(x \\<mapsto> t\\<^sub>1) \\<turnstile>\\<^sub>n e' : t\\<^sub>2\"\n  by (induction \\<Gamma> e \"Arrow t\\<^sub>1 t\\<^sub>2\" rule: typecheckn.induct) simp_all\n\n(* Progress not directly provable here, due to lack of proof of termination.\n   We prove it in 02Debruijn/NameRemoval *)\n\nlemma [simp]: \"\\<Gamma> \\<turnstile>\\<^sub>n e : t \\<Longrightarrow> x \\<notin> all_varst e \\<Longrightarrow> \\<Gamma>(x \\<mapsto> t') \\<turnstile>\\<^sub>n e : t\"\n  by (induction \\<Gamma> e t rule: typecheckn.induct) (simp_all add: fun_upd_twist)\n\nlemma [simp]: \"\\<Gamma>(x \\<mapsto> t') \\<turnstile>\\<^sub>n e : t \\<Longrightarrow> x' \\<notin> all_varst e \\<Longrightarrow> \\<Gamma>(x' \\<mapsto> t') \\<turnstile>\\<^sub>n subst_vart x x' e : t\"\nproof (induction \"\\<Gamma>(x \\<mapsto> t')\" e t arbitrary: \\<Gamma> rule: typecheckn.induct)\n  case (tcn_lam y t\\<^sub>1 e t\\<^sub>2)\n  thus ?case\n  proof (cases \"x = y\")\n    case False\n    moreover with tcn_lam have \"\\<Gamma>(y \\<mapsto> t\\<^sub>1, x' \\<mapsto> t') \\<turnstile>\\<^sub>n subst_vart x x' e : t\\<^sub>2\" \n      by (simp add: fun_upd_twist)\n    moreover from tcn_lam have \"x' \\<noteq> y\" by simp\n    ultimately show ?thesis by (simp add: fun_upd_twist)\n  qed (simp_all add: fun_upd_twist)\nqed fastforce+\n\nlemma [simp]: \"\\<Gamma>(x \\<mapsto> t') \\<turnstile>\\<^sub>n e : t \\<Longrightarrow> \\<Gamma> \\<turnstile>\\<^sub>n e' : t' \\<Longrightarrow> \\<Gamma> \\<turnstile>\\<^sub>n substt x e' e : t\"\nproof (induction x e' e arbitrary: \\<Gamma> t rule: substt.induct)\n  case (3 x e' y t\\<^sub>1 e)\n  then obtain t\\<^sub>2 where T: \"t = Arrow t\\<^sub>1 t\\<^sub>2 \\<and> \\<Gamma>(x \\<mapsto> t', y \\<mapsto> t\\<^sub>1) \\<turnstile>\\<^sub>n e : t\\<^sub>2\" by blast\n  let ?z = \"fresh (all_varst e' \\<union> all_varst e \\<union> {x, y})\"\n  have \"finite (all_varst e' \\<union> all_varst e \\<union> {x, y})\" by simp\n  hence Z: \"?z \\<notin> all_varst e' \\<union> all_varst e \\<union> {x, y}\" by (metis fresh_is_fresh)\n  with T have \"\\<Gamma>(x \\<mapsto> t', ?z \\<mapsto> t\\<^sub>1) \\<turnstile>\\<^sub>n subst_vart y ?z e : t\\<^sub>2\" by simp\n  with Z have X: \"\\<Gamma>(?z \\<mapsto> t\\<^sub>1, x \\<mapsto> t') \\<turnstile>\\<^sub>n subst_vart y ?z e : t\\<^sub>2\" by (simp add: fun_upd_twist)\n  from 3 Z have \"\\<Gamma>(?z \\<mapsto> t\\<^sub>1) \\<turnstile>\\<^sub>n e' : t'\" by simp\n  with 3 X have \"\\<Gamma>(?z \\<mapsto> t\\<^sub>1) \\<turnstile>\\<^sub>n substt x e' (subst_vart y ?z e) : t\\<^sub>2\" by fastforce\n  with T show ?case by (simp add: Let_def)\nqed fastforce+\n\ntheorem preservationn: \"e \\<Down>\\<^sub>t v \\<Longrightarrow> \\<Gamma> \\<turnstile>\\<^sub>n e : t \\<Longrightarrow> \\<Gamma> \\<turnstile>\\<^sub>n v : t\"\n  by (induction e v arbitrary: t rule: evalt.induct) fastforce+\n\nlemma [simp]: \"e \\<Down>\\<^sub>t v \\<Longrightarrow> valt v\"\n  by (induction e v rule: evalt.induct) simp_all\n\nlemma val_no_evaln: \"e \\<Down>\\<^sub>t v \\<Longrightarrow> valt e \\<Longrightarrow> v = e\"\n  by (induction e v rule: evalt.induct) simp_all\n\ntheorem determinismn: \"e \\<Down>\\<^sub>t v \\<Longrightarrow> e \\<Down>\\<^sub>t v' \\<Longrightarrow> v = v'\"\nproof (induction e v arbitrary: v' rule: evalt.induct)\n  case (evt_const k)\n  thus ?case by (induction \"TConst k\" v' rule: evalt.induct) simp_all\nnext\n  case (evt_lam x t e)\n  thus ?case by (induction \"TLam x t e\" v' rule: evalt.induct) simp_all\nnext\n  case (evt_app e\\<^sub>1 x t e\\<^sub>1' e\\<^sub>2 v\\<^sub>2 v)\n  from evt_app(7, 1, 2, 3, 4, 5, 6) show ?case \n    by (induction \"TApp e\\<^sub>1 e\\<^sub>2\" v' rule: evalt.induct) blast+\nqed\n\nend", "meta": {"author": "xtreme-james-cooper", "repo": "Lambda-RAM-Compiler", "sha": "24125435949fa71dfc5faafdb236d28a098beefc", "save_path": "github-repos/isabelle/xtreme-james-cooper-Lambda-RAM-Compiler", "path": "github-repos/isabelle/xtreme-james-cooper-Lambda-RAM-Compiler/Lambda-RAM-Compiler-24125435949fa71dfc5faafdb236d28a098beefc/02Typed/Typed.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297887874625, "lm_q2_score": 0.8198933293122507, "lm_q1q2_score": 0.7383383666738105}}
{"text": "(*  Title:      HOL/Imperative_HOL/ex/Imperative_Quicksort.thy\n    Author:     Lukas Bulwahn, TU Muenchen\n*)\n\nsection {* An imperative implementation of Quicksort on arrays *}\n\ntheory Imperative_Quicksort\nimports\n  \"~~/src/HOL/Imperative_HOL/Imperative_HOL\"\n  Subarray\n  \"~~/src/HOL/Library/Multiset\"\n  \"~~/src/HOL/Library/Code_Target_Numeral\"\nbegin\n\ntext {* We prove QuickSort correct in the Relational Calculus. *}\n\ndefinition swap :: \"nat array \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> unit Heap\"\nwhere\n  \"swap arr i j =\n     do {\n       x \\<leftarrow> Array.nth arr i;\n       y \\<leftarrow> Array.nth arr j;\n       Array.upd i y arr;\n       Array.upd j x arr;\n       return ()\n     }\"\n\nlemma effect_swapI [effect_intros]:\n  assumes \"i < Array.length h a\" \"j < Array.length h a\"\n    \"x = Array.get h a ! i\" \"y = Array.get h a ! j\"\n    \"h' = Array.update a j x (Array.update a i y h)\"\n  shows \"effect (swap a i j) h h' r\"\n  unfolding swap_def using assms by (auto intro!: effect_intros)\n\nlemma swap_permutes:\n  assumes \"effect (swap a i j) h h' rs\"\n  shows \"multiset_of (Array.get h' a) \n  = multiset_of (Array.get h a)\"\n  using assms\n  unfolding swap_def\n  by (auto simp add: Array.length_def multiset_of_swap dest: sym [of _ \"h'\"] elim!: effect_bindE effect_nthE effect_returnE effect_updE)\n\nfunction part1 :: \"nat array \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> nat Heap\"\nwhere\n  \"part1 a left right p = (\n     if (right \\<le> left) then return right\n     else do {\n       v \\<leftarrow> Array.nth a left;\n       (if (v \\<le> p) then (part1 a (left + 1) right p)\n                    else (do { swap a left right;\n  part1 a left (right - 1) p }))\n     })\"\nby pat_completeness auto\n\ntermination\nby (relation \"measure (\\<lambda>(_,l,r,_). r - l )\") auto\n\ndeclare part1.simps[simp del]\n\nlemma part_permutes:\n  assumes \"effect (part1 a l r p) h h' rs\"\n  shows \"multiset_of (Array.get h' a) \n  = multiset_of (Array.get h a)\"\n  using assms\nproof (induct a l r p arbitrary: h h' rs rule:part1.induct)\n  case (1 a l r p h h' rs)\n  thus ?case\n    unfolding part1.simps [of a l r p]\n    by (elim effect_bindE effect_ifE effect_returnE effect_nthE) (auto simp add: swap_permutes)\nqed\n\nlemma part_returns_index_in_bounds:\n  assumes \"effect (part1 a l r p) h h' rs\"\n  assumes \"l \\<le> r\"\n  shows \"l \\<le> rs \\<and> rs \\<le> r\"\nusing assms\nproof (induct a l r p arbitrary: h h' rs rule:part1.induct)\n  case (1 a l r p h h' rs)\n  note cr = `effect (part1 a l r p) h h' rs`\n  show ?case\n  proof (cases \"r \\<le> l\")\n    case True (* Terminating case *)\n    with cr `l \\<le> r` show ?thesis\n      unfolding part1.simps[of a l r p]\n      by (elim effect_bindE effect_ifE effect_returnE effect_nthE) auto\n  next\n    case False (* recursive case *)\n    note rec_condition = this\n    let ?v = \"Array.get h a ! l\"\n    show ?thesis\n    proof (cases \"?v \\<le> p\")\n      case True\n      with cr False\n      have rec1: \"effect (part1 a (l + 1) r p) h h' rs\"\n        unfolding part1.simps[of a l r p]\n        by (elim effect_bindE effect_nthE effect_ifE effect_returnE) auto\n      from rec_condition have \"l + 1 \\<le> r\" by arith\n      from 1(1)[OF rec_condition True rec1 `l + 1 \\<le> r`]\n      show ?thesis by simp\n    next\n      case False\n      with rec_condition cr\n      obtain h1 where swp: \"effect (swap a l r) h h1 ()\"\n        and rec2: \"effect (part1 a l (r - 1) p) h1 h' rs\"\n        unfolding part1.simps[of a l r p]\n        by (elim effect_bindE effect_nthE effect_ifE effect_returnE) auto\n      from rec_condition have \"l \\<le> r - 1\" by arith\n      from 1(2) [OF rec_condition False rec2 `l \\<le> r - 1`] show ?thesis by fastforce\n    qed\n  qed\nqed\n\nlemma part_length_remains:\n  assumes \"effect (part1 a l r p) h h' rs\"\n  shows \"Array.length h a = Array.length h' a\"\nusing assms\nproof (induct a l r p arbitrary: h h' rs rule:part1.induct)\n  case (1 a l r p h h' rs)\n  note cr = `effect (part1 a l r p) h h' rs`\n  \n  show ?case\n  proof (cases \"r \\<le> l\")\n    case True (* Terminating case *)\n    with cr show ?thesis\n      unfolding part1.simps[of a l r p]\n      by (elim effect_bindE effect_ifE effect_returnE effect_nthE) auto\n  next\n    case False (* recursive case *)\n    with cr 1 show ?thesis\n      unfolding part1.simps [of a l r p] swap_def\n      by (auto elim!: effect_bindE effect_ifE effect_nthE effect_returnE effect_updE) fastforce\n  qed\nqed\n\nlemma part_outer_remains:\n  assumes \"effect (part1 a l r p) h h' rs\"\n  shows \"\\<forall>i. i < l \\<or> r < i \\<longrightarrow> Array.get h (a::nat array) ! i = Array.get h' a ! i\"\n  using assms\nproof (induct a l r p arbitrary: h h' rs rule:part1.induct)\n  case (1 a l r p h h' rs)\n  note cr = `effect (part1 a l r p) h h' rs`\n  \n  show ?case\n  proof (cases \"r \\<le> l\")\n    case True (* Terminating case *)\n    with cr show ?thesis\n      unfolding part1.simps[of a l r p]\n      by (elim effect_bindE effect_ifE effect_returnE effect_nthE) auto\n  next\n    case False (* recursive case *)\n    note rec_condition = this\n    let ?v = \"Array.get h a ! l\"\n    show ?thesis\n    proof (cases \"?v \\<le> p\")\n      case True\n      with cr False\n      have rec1: \"effect (part1 a (l + 1) r p) h h' rs\"\n        unfolding part1.simps[of a l r p]\n        by (elim effect_bindE effect_nthE effect_ifE effect_returnE) auto\n      from 1(1)[OF rec_condition True rec1]\n      show ?thesis by fastforce\n    next\n      case False\n      with rec_condition cr\n      obtain h1 where swp: \"effect (swap a l r) h h1 ()\"\n        and rec2: \"effect (part1 a l (r - 1) p) h1 h' rs\"\n        unfolding part1.simps[of a l r p]\n        by (elim effect_bindE effect_nthE effect_ifE effect_returnE) auto\n      from swp rec_condition have\n        \"\\<forall>i. i < l \\<or> r < i \\<longrightarrow> Array.get h a ! i = Array.get h1 a ! i\"\n        unfolding swap_def\n        by (elim effect_bindE effect_nthE effect_updE effect_returnE) auto\n      with 1(2) [OF rec_condition False rec2] show ?thesis by fastforce\n    qed\n  qed\nqed\n\n\nlemma part_partitions:\n  assumes \"effect (part1 a l r p) h h' rs\"\n  shows \"(\\<forall>i. l \\<le> i \\<and> i < rs \\<longrightarrow> Array.get h' (a::nat array) ! i \\<le> p)\n  \\<and> (\\<forall>i. rs < i \\<and> i \\<le> r \\<longrightarrow> Array.get h' a ! i \\<ge> p)\"\n  using assms\nproof (induct a l r p arbitrary: h h' rs rule:part1.induct)\n  case (1 a l r p h h' rs)\n  note cr = `effect (part1 a l r p) h h' rs`\n  \n  show ?case\n  proof (cases \"r \\<le> l\")\n    case True (* Terminating case *)\n    with cr have \"rs = r\"\n      unfolding part1.simps[of a l r p]\n      by (elim effect_bindE effect_ifE effect_returnE effect_nthE) auto\n    with True\n    show ?thesis by auto\n  next\n    case False (* recursive case *)\n    note lr = this\n    let ?v = \"Array.get h a ! l\"\n    show ?thesis\n    proof (cases \"?v \\<le> p\")\n      case True\n      with lr cr\n      have rec1: \"effect (part1 a (l + 1) r p) h h' rs\"\n        unfolding part1.simps[of a l r p]\n        by (elim effect_bindE effect_nthE effect_ifE effect_returnE) auto\n      from True part_outer_remains[OF rec1] have a_l: \"Array.get h' a ! l \\<le> p\"\n        by fastforce\n      have \"\\<forall>i. (l \\<le> i = (l = i \\<or> Suc l \\<le> i))\" by arith\n      with 1(1)[OF False True rec1] a_l show ?thesis\n        by auto\n    next\n      case False\n      with lr cr\n      obtain h1 where swp: \"effect (swap a l r) h h1 ()\"\n        and rec2: \"effect (part1 a l (r - 1) p) h1 h' rs\"\n        unfolding part1.simps[of a l r p]\n        by (elim effect_bindE effect_nthE effect_ifE effect_returnE) auto\n      from swp False have \"Array.get h1 a ! r \\<ge> p\"\n        unfolding swap_def\n        by (auto simp add: Array.length_def elim!: effect_bindE effect_nthE effect_updE effect_returnE)\n      with part_outer_remains [OF rec2] lr have a_r: \"Array.get h' a ! r \\<ge> p\"\n        by fastforce\n      have \"\\<forall>i. (i \\<le> r = (i = r \\<or> i \\<le> r - 1))\" by arith\n      with 1(2)[OF lr False rec2] a_r show ?thesis\n        by auto\n    qed\n  qed\nqed\n\n\nfun partition :: \"nat array \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> nat Heap\"\nwhere\n  \"partition a left right = do {\n     pivot \\<leftarrow> Array.nth a right;\n     middle \\<leftarrow> part1 a left (right - 1) pivot;\n     v \\<leftarrow> Array.nth a middle;\n     m \\<leftarrow> return (if (v \\<le> pivot) then (middle + 1) else middle);\n     swap a m right;\n     return m\n   }\"\n\ndeclare partition.simps[simp del]\n\nlemma partition_permutes:\n  assumes \"effect (partition a l r) h h' rs\"\n  shows \"multiset_of (Array.get h' a) \n  = multiset_of (Array.get h a)\"\nproof -\n    from assms part_permutes swap_permutes show ?thesis\n      unfolding partition.simps\n      by (elim effect_bindE effect_returnE effect_nthE effect_ifE effect_updE) auto\nqed\n\nlemma partition_length_remains:\n  assumes \"effect (partition a l r) h h' rs\"\n  shows \"Array.length h a = Array.length h' a\"\nproof -\n  from assms part_length_remains show ?thesis\n    unfolding partition.simps swap_def\n    by (elim effect_bindE effect_returnE effect_nthE effect_ifE effect_updE) auto\nqed\n\nlemma partition_outer_remains:\n  assumes \"effect (partition a l r) h h' rs\"\n  assumes \"l < r\"\n  shows \"\\<forall>i. i < l \\<or> r < i \\<longrightarrow> Array.get h (a::nat array) ! i = Array.get h' a ! i\"\nproof -\n  from assms part_outer_remains part_returns_index_in_bounds show ?thesis\n    unfolding partition.simps swap_def\n    by (elim effect_bindE effect_returnE effect_nthE effect_ifE effect_updE) fastforce\nqed\n\nlemma partition_returns_index_in_bounds:\n  assumes effect: \"effect (partition a l r) h h' rs\"\n  assumes \"l < r\"\n  shows \"l \\<le> rs \\<and> rs \\<le> r\"\nproof -\n  from effect obtain middle h'' p where part: \"effect (part1 a l (r - 1) p) h h'' middle\"\n    and rs_equals: \"rs = (if Array.get h'' a ! middle \\<le> Array.get h a ! r then middle + 1\n         else middle)\"\n    unfolding partition.simps\n    by (elim effect_bindE effect_returnE effect_nthE effect_ifE effect_updE) simp \n  from `l < r` have \"l \\<le> r - 1\" by arith\n  from part_returns_index_in_bounds[OF part this] rs_equals `l < r` show ?thesis by auto\nqed\n\nlemma partition_partitions:\n  assumes effect: \"effect (partition a l r) h h' rs\"\n  assumes \"l < r\"\n  shows \"(\\<forall>i. l \\<le> i \\<and> i < rs \\<longrightarrow> Array.get h' (a::nat array) ! i \\<le> Array.get h' a ! rs) \\<and>\n  (\\<forall>i. rs < i \\<and> i \\<le> r \\<longrightarrow> Array.get h' a ! rs \\<le> Array.get h' a ! i)\"\nproof -\n  let ?pivot = \"Array.get h a ! r\" \n  from effect obtain middle h1 where part: \"effect (part1 a l (r - 1) ?pivot) h h1 middle\"\n    and swap: \"effect (swap a rs r) h1 h' ()\"\n    and rs_equals: \"rs = (if Array.get h1 a ! middle \\<le> ?pivot then middle + 1\n         else middle)\"\n    unfolding partition.simps\n    by (elim effect_bindE effect_returnE effect_nthE effect_ifE effect_updE) simp\n  from swap have h'_def: \"h' = Array.update a r (Array.get h1 a ! rs)\n    (Array.update a rs (Array.get h1 a ! r) h1)\"\n    unfolding swap_def\n    by (elim effect_bindE effect_returnE effect_nthE effect_updE) simp\n  from swap have in_bounds: \"r < Array.length h1 a \\<and> rs < Array.length h1 a\"\n    unfolding swap_def\n    by (elim effect_bindE effect_returnE effect_nthE effect_updE) simp\n  from swap have swap_length_remains: \"Array.length h1 a = Array.length h' a\"\n    unfolding swap_def by (elim effect_bindE effect_returnE effect_nthE effect_updE) auto\n  from `l < r` have \"l \\<le> r - 1\" by simp\n  note middle_in_bounds = part_returns_index_in_bounds[OF part this]\n  from part_outer_remains[OF part] `l < r`\n  have \"Array.get h a ! r = Array.get h1 a ! r\"\n    by fastforce\n  with swap\n  have right_remains: \"Array.get h a ! r = Array.get h' a ! rs\"\n    unfolding swap_def\n    by (auto simp add: Array.length_def elim!: effect_bindE effect_returnE effect_nthE effect_updE) (cases \"r = rs\", auto)\n  from part_partitions [OF part]\n  show ?thesis\n  proof (cases \"Array.get h1 a ! middle \\<le> ?pivot\")\n    case True\n    with rs_equals have rs_equals: \"rs = middle + 1\" by simp\n    { \n      fix i\n      assume i_is_left: \"l \\<le> i \\<and> i < rs\"\n      with swap_length_remains in_bounds middle_in_bounds rs_equals `l < r`\n      have i_props: \"i < Array.length h' a\" \"i \\<noteq> r\" \"i \\<noteq> rs\" by auto\n      from i_is_left rs_equals have \"l \\<le> i \\<and> i < middle \\<or> i = middle\" by arith\n      with part_partitions[OF part] right_remains True\n      have \"Array.get h1 a ! i \\<le> Array.get h' a ! rs\" by fastforce\n      with i_props h'_def in_bounds have \"Array.get h' a ! i \\<le> Array.get h' a ! rs\"\n        unfolding Array.update_def Array.length_def by simp\n    }\n    moreover\n    {\n      fix i\n      assume \"rs < i \\<and> i \\<le> r\"\n\n      hence \"(rs < i \\<and> i \\<le> r - 1) \\<or> (rs < i \\<and> i = r)\" by arith\n      hence \"Array.get h' a ! rs \\<le> Array.get h' a ! i\"\n      proof\n        assume i_is: \"rs < i \\<and> i \\<le> r - 1\"\n        with swap_length_remains in_bounds middle_in_bounds rs_equals\n        have i_props: \"i < Array.length h' a\" \"i \\<noteq> r\" \"i \\<noteq> rs\" by auto\n        from part_partitions[OF part] rs_equals right_remains i_is\n        have \"Array.get h' a ! rs \\<le> Array.get h1 a ! i\"\n          by fastforce\n        with i_props h'_def show ?thesis by fastforce\n      next\n        assume i_is: \"rs < i \\<and> i = r\"\n        with rs_equals have \"Suc middle \\<noteq> r\" by arith\n        with middle_in_bounds `l < r` have \"Suc middle \\<le> r - 1\" by arith\n        with part_partitions[OF part] right_remains \n        have \"Array.get h' a ! rs \\<le> Array.get h1 a ! (Suc middle)\"\n          by fastforce\n        with i_is True rs_equals right_remains h'_def\n        show ?thesis using in_bounds\n          unfolding Array.update_def Array.length_def\n          by auto\n      qed\n    }\n    ultimately show ?thesis by auto\n  next\n    case False\n    with rs_equals have rs_equals: \"middle = rs\" by simp\n    { \n      fix i\n      assume i_is_left: \"l \\<le> i \\<and> i < rs\"\n      with swap_length_remains in_bounds middle_in_bounds rs_equals\n      have i_props: \"i < Array.length h' a\" \"i \\<noteq> r\" \"i \\<noteq> rs\" by auto\n      from part_partitions[OF part] rs_equals right_remains i_is_left\n      have \"Array.get h1 a ! i \\<le> Array.get h' a ! rs\" by fastforce\n      with i_props h'_def have \"Array.get h' a ! i \\<le> Array.get h' a ! rs\"\n        unfolding Array.update_def by simp\n    }\n    moreover\n    {\n      fix i\n      assume \"rs < i \\<and> i \\<le> r\"\n      hence \"(rs < i \\<and> i \\<le> r - 1) \\<or> i = r\" by arith\n      hence \"Array.get h' a ! rs \\<le> Array.get h' a ! i\"\n      proof\n        assume i_is: \"rs < i \\<and> i \\<le> r - 1\"\n        with swap_length_remains in_bounds middle_in_bounds rs_equals\n        have i_props: \"i < Array.length h' a\" \"i \\<noteq> r\" \"i \\<noteq> rs\" by auto\n        from part_partitions[OF part] rs_equals right_remains i_is\n        have \"Array.get h' a ! rs \\<le> Array.get h1 a ! i\"\n          by fastforce\n        with i_props h'_def show ?thesis by fastforce\n      next\n        assume i_is: \"i = r\"\n        from i_is False rs_equals right_remains h'_def\n        show ?thesis using in_bounds\n          unfolding Array.update_def Array.length_def\n          by auto\n      qed\n    }\n    ultimately\n    show ?thesis by auto\n  qed\nqed\n\n\nfunction quicksort :: \"nat array \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> unit Heap\"\nwhere\n  \"quicksort arr left right =\n     (if (right > left)  then\n        do {\n          pivotNewIndex \\<leftarrow> partition arr left right;\n          pivotNewIndex \\<leftarrow> assert (\\<lambda>x. left \\<le> x \\<and> x \\<le> right) pivotNewIndex;\n          quicksort arr left (pivotNewIndex - 1);\n          quicksort arr (pivotNewIndex + 1) right\n        }\n     else return ())\"\nby pat_completeness auto\n\n(* For termination, we must show that the pivotNewIndex is between left and right *) \ntermination\nby (relation \"measure (\\<lambda>(a, l, r). (r - l))\") auto\n\ndeclare quicksort.simps[simp del]\n\n\nlemma quicksort_permutes:\n  assumes \"effect (quicksort a l r) h h' rs\"\n  shows \"multiset_of (Array.get h' a) \n  = multiset_of (Array.get h a)\"\n  using assms\nproof (induct a l r arbitrary: h h' rs rule: quicksort.induct)\n  case (1 a l r h h' rs)\n  with partition_permutes show ?case\n    unfolding quicksort.simps [of a l r]\n    by (elim effect_ifE effect_bindE effect_assertE effect_returnE) auto\nqed\n\nlemma length_remains:\n  assumes \"effect (quicksort a l r) h h' rs\"\n  shows \"Array.length h a = Array.length h' a\"\nusing assms\nproof (induct a l r arbitrary: h h' rs rule: quicksort.induct)\n  case (1 a l r h h' rs)\n  with partition_length_remains show ?case\n    unfolding quicksort.simps [of a l r]\n    by (elim effect_ifE effect_bindE effect_assertE effect_returnE) auto\nqed\n\nlemma quicksort_outer_remains:\n  assumes \"effect (quicksort a l r) h h' rs\"\n   shows \"\\<forall>i. i < l \\<or> r < i \\<longrightarrow> Array.get h (a::nat array) ! i = Array.get h' a ! i\"\n  using assms\nproof (induct a l r arbitrary: h h' rs rule: quicksort.induct)\n  case (1 a l r h h' rs)\n  note cr = `effect (quicksort a l r) h h' rs`\n  thus ?case\n  proof (cases \"r > l\")\n    case False\n    with cr have \"h' = h\"\n      unfolding quicksort.simps [of a l r]\n      by (elim effect_ifE effect_returnE) auto\n    thus ?thesis by simp\n  next\n  case True\n   { \n      fix h1 h2 p ret1 ret2 i\n      assume part: \"effect (partition a l r) h h1 p\"\n      assume qs1: \"effect (quicksort a l (p - 1)) h1 h2 ret1\"\n      assume qs2: \"effect (quicksort a (p + 1) r) h2 h' ret2\"\n      assume pivot: \"l \\<le> p \\<and> p \\<le> r\"\n      assume i_outer: \"i < l \\<or> r < i\"\n      from  partition_outer_remains [OF part True] i_outer\n      have 2: \"Array.get h a !i = Array.get h1 a ! i\" by fastforce\n      moreover\n      from 1(1) [OF True pivot qs1] pivot i_outer 2\n      have 3: \"Array.get h1 a ! i = Array.get h2 a ! i\" by auto\n      moreover\n      from qs2 1(2) [of p h2 h' ret2] True pivot i_outer 3\n      have \"Array.get h2 a ! i = Array.get h' a ! i\" by auto\n      ultimately have \"Array.get h a ! i= Array.get h' a ! i\" by simp\n    }\n    with cr show ?thesis\n      unfolding quicksort.simps [of a l r]\n      by (elim effect_ifE effect_bindE effect_assertE effect_returnE) auto\n  qed\nqed\n\nlemma quicksort_is_skip:\n  assumes \"effect (quicksort a l r) h h' rs\"\n  shows \"r \\<le> l \\<longrightarrow> h = h'\"\n  using assms\n  unfolding quicksort.simps [of a l r]\n  by (elim effect_ifE effect_returnE) auto\n \nlemma quicksort_sorts:\n  assumes \"effect (quicksort a l r) h h' rs\"\n  assumes l_r_length: \"l < Array.length h a\" \"r < Array.length h a\" \n  shows \"sorted (subarray l (r + 1) a h')\"\n  using assms\nproof (induct a l r arbitrary: h h' rs rule: quicksort.induct)\n  case (1 a l r h h' rs)\n  note cr = `effect (quicksort a l r) h h' rs`\n  thus ?case\n  proof (cases \"r > l\")\n    case False\n    hence \"l \\<ge> r + 1 \\<or> l = r\" by arith \n    with length_remains[OF cr] 1(5) show ?thesis\n      by (auto simp add: subarray_Nil subarray_single)\n  next\n    case True\n    { \n      fix h1 h2 p\n      assume part: \"effect (partition a l r) h h1 p\"\n      assume qs1: \"effect (quicksort a l (p - 1)) h1 h2 ()\"\n      assume qs2: \"effect (quicksort a (p + 1) r) h2 h' ()\"\n      from partition_returns_index_in_bounds [OF part True]\n      have pivot: \"l\\<le> p \\<and> p \\<le> r\" .\n     note length_remains = length_remains[OF qs2] length_remains[OF qs1] partition_length_remains[OF part]\n      from quicksort_outer_remains [OF qs2] quicksort_outer_remains [OF qs1] pivot quicksort_is_skip[OF qs1]\n      have pivot_unchanged: \"Array.get h1 a ! p = Array.get h' a ! p\" by (cases p, auto)\n        (*-- First of all, by induction hypothesis both sublists are sorted. *)\n      from 1(1)[OF True pivot qs1] length_remains pivot 1(5) \n      have IH1: \"sorted (subarray l p a h2)\"  by (cases p, auto simp add: subarray_Nil)\n      from quicksort_outer_remains [OF qs2] length_remains\n      have left_subarray_remains: \"subarray l p a h2 = subarray l p a h'\"\n        by (simp add: subarray_eq_samelength_iff)\n      with IH1 have IH1': \"sorted (subarray l p a h')\" by simp\n      from 1(2)[OF True pivot qs2] pivot 1(5) length_remains\n      have IH2: \"sorted (subarray (p + 1) (r + 1) a h')\"\n        by (cases \"Suc p \\<le> r\", auto simp add: subarray_Nil)\n           (* -- Secondly, both sublists remain partitioned. *)\n      from partition_partitions[OF part True]\n      have part_conds1: \"\\<forall>j. j \\<in> set (subarray l p a h1) \\<longrightarrow> j \\<le> Array.get h1 a ! p \"\n        and part_conds2: \"\\<forall>j. j \\<in> set (subarray (p + 1) (r + 1) a h1) \\<longrightarrow> Array.get h1 a ! p \\<le> j\"\n        by (auto simp add: all_in_set_subarray_conv)\n      from quicksort_outer_remains [OF qs1] quicksort_permutes [OF qs1] True\n        length_remains 1(5) pivot multiset_of_sublist [of l p \"Array.get h1 a\" \"Array.get h2 a\"]\n      have multiset_partconds1: \"multiset_of (subarray l p a h2) = multiset_of (subarray l p a h1)\"\n        unfolding Array.length_def subarray_def by (cases p, auto)\n      with left_subarray_remains part_conds1 pivot_unchanged\n      have part_conds2': \"\\<forall>j. j \\<in> set (subarray l p a h') \\<longrightarrow> j \\<le> Array.get h' a ! p\"\n        by (simp, subst set_of_multiset_of[symmetric], simp)\n          (* -- These steps are the analogous for the right sublist \\<dots> *)\n      from quicksort_outer_remains [OF qs1] length_remains\n      have right_subarray_remains: \"subarray (p + 1) (r + 1) a h1 = subarray (p + 1) (r + 1) a h2\"\n        by (auto simp add: subarray_eq_samelength_iff)\n      from quicksort_outer_remains [OF qs2] quicksort_permutes [OF qs2] True\n        length_remains 1(5) pivot multiset_of_sublist [of \"p + 1\" \"r + 1\" \"Array.get h2 a\" \"Array.get h' a\"]\n      have multiset_partconds2: \"multiset_of (subarray (p + 1) (r + 1) a h') = multiset_of (subarray (p + 1) (r + 1) a h2)\"\n        unfolding Array.length_def subarray_def by auto\n      with right_subarray_remains part_conds2 pivot_unchanged\n      have part_conds1': \"\\<forall>j. j \\<in> set (subarray (p + 1) (r + 1) a h') \\<longrightarrow> Array.get h' a ! p \\<le> j\"\n        by (simp, subst set_of_multiset_of[symmetric], simp)\n          (* -- Thirdly and finally, we show that the array is sorted\n          following from the facts above. *)\n      from True pivot 1(5) length_remains have \"subarray l (r + 1) a h' = subarray l p a h' @ [Array.get h' a ! p] @ subarray (p + 1) (r + 1) a h'\"\n        by (simp add: subarray_nth_array_Cons, cases \"l < p\") (auto simp add: subarray_append subarray_Nil)\n      with IH1' IH2 part_conds1' part_conds2' pivot have ?thesis\n        unfolding subarray_def\n        apply (auto simp add: sorted_append sorted_Cons all_in_set_sublist'_conv)\n        by (auto simp add: set_sublist' dest: le_trans [of _ \"Array.get h' a ! p\"])\n    }\n    with True cr show ?thesis\n      unfolding quicksort.simps [of a l r]\n      by (elim effect_ifE effect_returnE effect_bindE effect_assertE) auto\n  qed\nqed\n\n\nlemma quicksort_is_sort:\n  assumes effect: \"effect (quicksort a 0 (Array.length h a - 1)) h h' rs\"\n  shows \"Array.get h' a = sort (Array.get h a)\"\nproof (cases \"Array.get h a = []\")\n  case True\n  with quicksort_is_skip[OF effect] show ?thesis\n  unfolding Array.length_def by simp\nnext\n  case False\n  from quicksort_sorts [OF effect] False have \"sorted (sublist' 0 (List.length (Array.get h a)) (Array.get h' a))\"\n    unfolding Array.length_def subarray_def by auto\n  with length_remains[OF effect] have \"sorted (Array.get h' a)\"\n    unfolding Array.length_def by simp\n  with quicksort_permutes [OF effect] properties_for_sort show ?thesis by fastforce\nqed\n\nsubsection {* No Errors in quicksort *}\ntext {* We have proved that quicksort sorts (if no exceptions occur).\nWe will now show that exceptions do not occur. *}\n\nlemma success_part1I: \n  assumes \"l < Array.length h a\" \"r < Array.length h a\"\n  shows \"success (part1 a l r p) h\"\n  using assms\nproof (induct a l r p arbitrary: h rule: part1.induct)\n  case (1 a l r p)\n  thus ?case unfolding part1.simps [of a l r]\n  apply (auto intro!: success_intros simp add: not_le)\n  apply (auto intro!: effect_intros)\n  done\nqed\n\nlemma success_bindI' [success_intros]: (*FIXME move*)\n  assumes \"success f h\"\n  assumes \"\\<And>h' r. effect f h h' r \\<Longrightarrow> success (g r) h'\"\n  shows \"success (f \\<guillemotright>= g) h\"\nusing assms(1) proof (rule success_effectE)\n  fix h' r\n  assume *: \"effect f h h' r\"\n  with assms(2) have \"success (g r) h'\" .\n  with * show \"success (f \\<guillemotright>= g) h\" by (rule success_bind_effectI)\nqed\n\nlemma success_partitionI:\n  assumes \"l < r\" \"l < Array.length h a\" \"r < Array.length h a\"\n  shows \"success (partition a l r) h\"\nusing assms unfolding partition.simps swap_def\napply (auto intro!: success_bindI' success_ifI success_returnI success_nthI success_updI success_part1I elim!: effect_bindE effect_updE effect_nthE effect_returnE simp add:)\napply (frule part_length_remains)\napply (frule part_returns_index_in_bounds)\napply auto\napply (frule part_length_remains)\napply (frule part_returns_index_in_bounds)\napply auto\napply (frule part_length_remains)\napply auto\ndone\n\nlemma success_quicksortI:\n  assumes \"l < Array.length h a\" \"r < Array.length h a\"\n  shows \"success (quicksort a l r) h\"\nusing assms\nproof (induct a l r arbitrary: h rule: quicksort.induct)\n  case (1 a l ri h)\n  thus ?case\n    unfolding quicksort.simps [of a l ri]\n    apply (auto intro!: success_ifI success_bindI' success_returnI success_nthI success_updI success_assertI success_partitionI)\n    apply (frule partition_returns_index_in_bounds)\n    apply auto\n    apply (frule partition_returns_index_in_bounds)\n    apply auto\n    apply (auto elim!: effect_assertE dest!: partition_length_remains length_remains)\n    apply (subgoal_tac \"Suc r \\<le> ri \\<or> r = ri\") \n    apply (erule disjE)\n    apply auto\n    unfolding quicksort.simps [of a \"Suc ri\" ri]\n    apply (auto intro!: success_ifI success_returnI)\n    done\nqed\n\n\nsubsection {* Example *}\n\ndefinition \"qsort a = do {\n    k \\<leftarrow> Array.len a;\n    quicksort a 0 (k - 1);\n    return a\n  }\"\n\ncode_reserved SML upto\n\ndefinition \"example = do {\n    a \\<leftarrow> Array.of_list [42, 2, 3, 5, 0, 1705, 8, 3, 15];\n    qsort a\n  }\"\n\nML_val {* @{code example} () *}\n\nexport_code qsort checking SML SML_imp OCaml? OCaml_imp? Haskell? Scala Scala_imp\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/Imperative_HOL/ex/Imperative_Quicksort.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8791467706759584, "lm_q2_score": 0.839733963661418, "lm_q1q2_score": 0.7382494023798581}}
{"text": "theory concrete_04\n  imports Main\n\nbegin\n(*4.1 Formulas*)\n(*form ::=(form) | True | Flase | term = term |\n  \\<not> form | form \\<and> form | form \\<or> form |\n  form \\<longrightarrow> form | \\<forall>x.form | \\<exists>x.form*)\n(*4.2 Sets*)\n\n(*4.3 Proof Automation*)\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\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  \"\\<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\n(*4.3.1 Sledgehammer*)\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\n(*4.3.2 Arithmetic*)\nlemma \"\\<lbrakk>(a::nat) \\<le> x + b; 2*x < c\\<rbrakk> \\<Longrightarrow> 2*a + 1 \\<le> 2*b + c\"\n  by arith\n\n(*4.4 Single Step Proofs*)\n(*conjI[of \"a=b\" \"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\"]]\n\nthm Suc_leD\nlemma \"Suc (Suc (Suc a)) \\<le> b \\<Longrightarrow> a \\<le> b\"\n  by(blast dest:Suc_leD)\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(*Prove ev 4*)\n(*Doesnt work?\\<rightarrow>evSS[OF evSS[OF ev0]]*)\nlemma \"ev (Suc (Suc (Suc (Suc 0))))\"\n  apply(rule evSS)\n  apply(rule evSS)\n  apply(rule ev0)\n  done\n\n(*Prove the above is equivalent*)\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  by(simp_all add: ev0 evSS)\n\ndeclare ev.intros[simp, intro]\n\n(*4.5.2 The Reflexive Transitive Closure*)\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\nthm refl\nthm step\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\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/Concrete Semantics/concrete_04.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218305645895, "lm_q2_score": 0.8006920092299293, "lm_q1q2_score": 0.7381754428676957}}
{"text": "theory Ch2\nimports Main\nbegin\n  fun add :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\" where\n    \"add 0 n = n\"\n  | \"add (Suc m) n = Suc (add m n)\"\n\n  lemma add_zero: \"add m 0 = m\"\n    apply(induction m)\n    apply(auto)\n  done\n\n  lemma add_swap: \"add (Suc m) n = add m (Suc n)\"\n    apply(induction m)\n    apply(auto)\n  done\n\n  lemma add_comm: \"add m n = add n m\"\n    apply(induction m)\n    apply(simp add: add_zero[symmetric])\n    apply(simp add: add_swap[symmetric])\n  done\n\n  lemma add_asso: \"add a (add b c) = add (add a b) c\"\n    apply(induction a)\n    apply(auto)\n  done\n\n  fun double :: \"nat \\<Rightarrow> nat\" where\n    \"double 0 = 0\"\n  | \"double (Suc m) = Suc (Suc (double m))\"\n\n  lemma doub_add: \"double m = add m m\"\n    apply(induction m)\n    apply(auto)\n    apply(simp add: add_swap[symmetric])\n  done\nend", "meta": {"author": "svanderbleek", "repo": "concrete-semantics", "sha": "6aebf7315e2e9edbf7fcf012f1ea258cf4d1d20c", "save_path": "github-repos/isabelle/svanderbleek-concrete-semantics", "path": "github-repos/isabelle/svanderbleek-concrete-semantics/concrete-semantics-6aebf7315e2e9edbf7fcf012f1ea258cf4d1d20c/Ch2.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.91610961358942, "lm_q2_score": 0.8056321889812553, "lm_q1q2_score": 0.7380473933428164}}
{"text": "theory 2\n  imports Main\nbegin\n\ndatatype nat = zero | s nat\ndatatype lst = nil | cons nat lst\n\nfun add :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\" where\n\"add zero y = y\" |\n\"add (s x) y = s (add x y)\"\n\nfun app :: \"lst \\<Rightarrow> lst \\<Rightarrow> lst\" where\n\"app nil r = r\" |\n\"app (cons a l) r = cons a (app l r)\"\n\nfun len :: \"lst \\<Rightarrow> nat\" where\n\"len nil = zero\" |\n\"len (cons e l) = s (len l)\"\n\nfun leq :: \"nat \\<Rightarrow> nat \\<Rightarrow> bool\" where\n\"leq zero x = True\" |\n\"leq (s x) zero = False\" |\n\"leq (s x) (s y) = leq x y\"\n\nfun less :: \"nat \\<Rightarrow> nat \\<Rightarrow> bool\" where\n\"less x y = leq (s x) y\"\n\nfun cnt :: \"lst \\<Rightarrow> nat \\<Rightarrow> nat\" where\n\"cnt nil x = zero\" |\n\"cnt (cons x tail) e = (if (\\<not>(x=e)) then (cnt tail e) else (s (cnt tail e)))\"\n\nfun outOfBounds :: \"nat \\<Rightarrow> nat\" where\n\"outOfBounds i = i\"\n\nfun get :: \"lst \\<Rightarrow> nat \\<Rightarrow> nat\" where\n\"get nil i = outOfBounds i\" |\n\"get (cons x tail) zero = x\" |\n\"get (cons x tail) (s i) = get tail i\"\n\nlemma \"less i (len x) \\<and> get x i = e \\<Longrightarrow> less zero (cnt l e)\"", "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/2.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9161096090086367, "lm_q2_score": 0.8056321889812553, "lm_q1q2_score": 0.7380473896523899}}
{"text": "(*  Title:       Signed (Finite) Multisets\n    Author:      Jasmin Blanchette <jasmin.blanchette at inria.fr>, 2016\n    Maintainer:  Jasmin Blanchette <jasmin.blanchette at inria.fr>\n*)\n\nsection \\<open>Signed (Finite) Multisets\\<close>\n\ntheory Signed_Multiset\nimports Multiset_More\nabbrevs\n  \"!z\" = \"\\<^sub>z\"\nbegin\n\nunbundle multiset.lifting\n\n\nsubsection \\<open>Definition of Signed Multisets\\<close>\n\ndefinition equiv_zmset :: \"'a multiset \\<times> 'a multiset \\<Rightarrow> 'a multiset \\<times> 'a multiset \\<Rightarrow> bool\" where\n  \"equiv_zmset = (\\<lambda>(Mp, Mn) (Np, Nn). Mp + Nn = Np + Mn)\"\n\nquotient_type 'a zmultiset = \"'a multiset \\<times> 'a multiset\" / equiv_zmset\n  by (rule equivpI, simp_all add: equiv_zmset_def reflp_def symp_def transp_def)\n    (metis multi_union_self_other_eq union_lcomm)\n\n\nsubsection \\<open>Basic Operations on Signed Multisets\\<close>\n\ninstantiation zmultiset :: (type) cancel_comm_monoid_add\nbegin\n\nlift_definition zero_zmultiset :: \"'a zmultiset\" is \"({#}, {#})\" .\n\nabbreviation empty_zmset :: \"'a zmultiset\" (\"{#}\\<^sub>z\") where\n  \"empty_zmset \\<equiv> 0\"\n\nlift_definition minus_zmultiset :: \"'a zmultiset \\<Rightarrow> 'a zmultiset \\<Rightarrow> 'a zmultiset\" is\n  \"\\<lambda>(Mp, Mn) (Np, Nn). (Mp + Nn, Mn + Np)\"\n  by (auto simp: equiv_zmset_def union_commute union_lcomm)\n\nlift_definition plus_zmultiset :: \"'a zmultiset \\<Rightarrow> 'a zmultiset \\<Rightarrow> 'a zmultiset\" is\n  \"\\<lambda>(Mp, Mn) (Np, Nn). (Mp + Np, Mn + Nn)\"\n  by (auto simp: equiv_zmset_def union_commute union_lcomm)\n\ninstance\n  by (intro_classes; transfer) (auto simp: equiv_zmset_def)\n\nend\n\ninstantiation zmultiset :: (type) group_add\nbegin\n\nlift_definition uminus_zmultiset :: \"'a zmultiset \\<Rightarrow> 'a zmultiset\" is \"\\<lambda>(Mp, Mn). (Mn, Mp)\"\n  by (auto simp: equiv_zmset_def add.commute)\n\ninstance\n  by (intro_classes; transfer) (auto simp: equiv_zmset_def)\n\nend\n\nlift_definition zcount :: \"'a zmultiset \\<Rightarrow> 'a \\<Rightarrow> int\" is\n  \"\\<lambda>(Mp, Mn) x. int (count Mp x) - int (count Mn x)\"\n  by (auto simp del: of_nat_add simp: equiv_zmset_def fun_eq_iff multiset_eq_iff diff_eq_eq\n    diff_add_eq eq_diff_eq of_nat_add[symmetric])\n\nlemma zcount_inject: \"zcount M = zcount N \\<longleftrightarrow> M = N\"\n  by transfer (auto simp del: of_nat_add simp: equiv_zmset_def fun_eq_iff multiset_eq_iff\n    diff_eq_eq diff_add_eq eq_diff_eq of_nat_add[symmetric])\n\nlemma zmultiset_eq_iff: \"M = N \\<longleftrightarrow> (\\<forall>a. zcount M a = zcount N a)\"\n  by (simp only: zcount_inject[symmetric] fun_eq_iff)\n\nlemma zmultiset_eqI: \"(\\<And>x. zcount A x = zcount B x) \\<Longrightarrow> A = B\"\n  using zmultiset_eq_iff by auto\n\nlemma zcount_uminus[simp]: \"zcount (- A) x = - zcount A x\"\n  by transfer auto\n\nlift_definition add_zmset :: \"'a \\<Rightarrow> 'a zmultiset \\<Rightarrow> 'a zmultiset\" is\n  \"\\<lambda>x (Mp, Mn). (add_mset x Mp, Mn)\"\n  by (auto simp: equiv_zmset_def)\n\nsyntax\n  \"_zmultiset\" :: \"args \\<Rightarrow> 'a zmultiset\" (\"{#(_)#}\\<^sub>z\")\ntranslations\n  \"{#x, xs#}\\<^sub>z\" == \"CONST add_zmset x {#xs#}\\<^sub>z\"\n  \"{#x#}\\<^sub>z\" == \"CONST add_zmset x {#}\\<^sub>z\"\n\nlemma zcount_empty[simp]: \"zcount {#}\\<^sub>z a = 0\"\n  by transfer auto\n\nlemma zcount_add_zmset[simp]:\n  \"zcount (add_zmset b A) a = (if b = a then zcount A a + 1 else zcount A a)\"\n  by transfer auto\n\nlemma zcount_single: \"zcount {#b#}\\<^sub>z a = (if b = a then 1 else 0)\"\n  by simp\n\nlemma add_add_same_iff_zmset[simp]: \"add_zmset a A = add_zmset a B \\<longleftrightarrow> A = B\"\n  by (auto simp: zmultiset_eq_iff)\n\nlemma add_zmset_commute: \"add_zmset x (add_zmset y M) = add_zmset y (add_zmset x M)\"\n  by (auto simp: zmultiset_eq_iff)\n\nlemma\n  singleton_ne_empty_zmset[simp]: \"{#x#}\\<^sub>z \\<noteq> {#}\\<^sub>z\" and\n  empty_ne_singleton_zmset[simp]: \"{#}\\<^sub>z \\<noteq> {#x#}\\<^sub>z\"\n  by (auto dest!: arg_cong2[of _ _ x _ zcount])\n\nlemma\n  singleton_ne_uminus_singleton_zmset[simp]: \"{#x#}\\<^sub>z \\<noteq> - {#y#}\\<^sub>z\" and\n  uminus_singleton_ne_singleton_zmset[simp]: \"- {#x#}\\<^sub>z \\<noteq> {#y#}\\<^sub>z\"\n  by (auto dest!: arg_cong2[of _ _ x x zcount] split: if_splits)\n\n\nsubsubsection \\<open>Conversion to Set and Membership\\<close>\n\ndefinition set_zmset :: \"'a zmultiset \\<Rightarrow> 'a set\" where\n  \"set_zmset M = {x. zcount M x \\<noteq> 0}\"\n\nabbreviation elem_zmset :: \"'a \\<Rightarrow> 'a zmultiset \\<Rightarrow> bool\" where\n  \"elem_zmset a M \\<equiv> a \\<in> set_zmset M\"\n\nnotation\n  elem_zmset (\"'(\\<in>#\\<^sub>z')\") and\n  elem_zmset (\"(_/ \\<in>#\\<^sub>z _)\" [51, 51] 50)\n\nnotation (ASCII)\n  elem_zmset (\"'(:#z')\") and\n  elem_zmset (\"(_/ :#z _)\" [51, 51] 50)\n\nabbreviation not_elem_zmset :: \"'a \\<Rightarrow> 'a zmultiset \\<Rightarrow> bool\" where\n  \"not_elem_zmset a M \\<equiv> a \\<notin> set_zmset M\"\n\nnotation\n  not_elem_zmset (\"'(\\<notin>#\\<^sub>z')\") and\n  not_elem_zmset (\"(_/ \\<notin>#\\<^sub>z _)\" [51, 51] 50)\n\nnotation (ASCII)\n  not_elem_zmset (\"'(~:#z')\") and\n  not_elem_zmset (\"(_/ ~:#z _)\" [51, 51] 50)\n\ncontext\nbegin\n\nqualified abbreviation Ball :: \"'a zmultiset \\<Rightarrow> ('a \\<Rightarrow> bool) \\<Rightarrow> bool\" where\n  \"Ball M \\<equiv> Set.Ball (set_zmset M)\"\n\nqualified abbreviation Bex :: \"'a zmultiset \\<Rightarrow> ('a \\<Rightarrow> bool) \\<Rightarrow> bool\" where\n  \"Bex M \\<equiv> Set.Bex (set_zmset M)\"\n\nend\n\nsyntax\n  \"_ZMBall\" :: \"pttrn \\<Rightarrow> 'a set \\<Rightarrow> bool \\<Rightarrow> bool\" (\"(3\\<forall>_\\<in>#\\<^sub>z_./ _)\" [0, 0, 10] 10)\n  \"_ZMBex\" :: \"pttrn \\<Rightarrow> 'a set \\<Rightarrow> bool \\<Rightarrow> bool\" (\"(3\\<exists>_\\<in>#\\<^sub>z_./ _)\" [0, 0, 10] 10)\n\nsyntax (ASCII)\n  \"_ZMBall\" :: \"pttrn \\<Rightarrow> 'a set \\<Rightarrow> bool \\<Rightarrow> bool\" (\"(3\\<forall>_:#\\<^sub>z_./ _)\" [0, 0, 10] 10)\n  \"_ZMBex\" :: \"pttrn \\<Rightarrow> 'a set \\<Rightarrow> bool \\<Rightarrow> bool\" (\"(3\\<exists>_:#\\<^sub>z_./ _)\" [0, 0, 10] 10)\n\ntranslations\n  \"\\<forall>x\\<in>#\\<^sub>zA. P\" \\<rightleftharpoons> \"CONST Signed_Multiset.Ball A (\\<lambda>x. P)\"\n  \"\\<exists>x\\<in>#\\<^sub>zA. P\" \\<rightleftharpoons> \"CONST Signed_Multiset.Bex A (\\<lambda>x. P)\"\n\nlemma zcount_eq_zero_iff: \"zcount M x = 0 \\<longleftrightarrow> x \\<notin>#\\<^sub>z M\"\n  by (auto simp add: set_zmset_def)\n\nlemma not_in_iff_zmset: \"x \\<notin>#\\<^sub>z M \\<longleftrightarrow> zcount M x = 0\"\n  by (auto simp add: zcount_eq_zero_iff)\n\nlemma zcount_ne_zero_iff[simp]: \"zcount M x \\<noteq> 0 \\<longleftrightarrow> x \\<in>#\\<^sub>z M\"\n  by (auto simp add: set_zmset_def)\n\nlemma zcount_inI:\n  assumes \"zcount M x = 0 \\<Longrightarrow> False\"\n  shows \"x \\<in>#\\<^sub>z M\"\nproof (rule ccontr)\n  assume \"x \\<notin>#\\<^sub>z M\"\n  with assms show False by (simp add: not_in_iff_zmset)\nqed\n\nlemma set_zmset_empty[simp]: \"set_zmset {#}\\<^sub>z = {}\"\n  by (simp add: set_zmset_def)\n\nlemma set_zmset_single: \"set_zmset {#b#}\\<^sub>z = {b}\"\n  by (simp add: set_zmset_def)\n\nlemma set_zmset_eq_empty_iff[simp]: \"set_zmset M = {} \\<longleftrightarrow> M = {#}\\<^sub>z\"\n  by (auto simp add: zmultiset_eq_iff zcount_eq_zero_iff)\n\nlemma finite_count_ne: \"finite {x. count M x \\<noteq> count N x}\"\nproof -\n  have \"{x. count M x \\<noteq> count N x} \\<subseteq> set_mset M \\<union> set_mset N\"\n    by (auto simp: not_in_iff)\n  moreover have \"finite (set_mset M \\<union> set_mset N)\"\n    by (rule finite_UnI[OF finite_set_mset finite_set_mset])\n  ultimately show ?thesis\n    by (rule finite_subset)\nqed\n\nlemma finite_set_zmset[iff]: \"finite (set_zmset M)\"\n  unfolding set_zmset_def by transfer (auto intro: finite_count_ne)\n\nlemma zmultiset_nonemptyE[elim]:\n  assumes \"A \\<noteq> {#}\\<^sub>z\"\n  obtains x where \"x \\<in>#\\<^sub>z A\"\nproof -\n  have \"\\<exists>x. x \\<in>#\\<^sub>z A\"\n    by (rule ccontr) (insert assms, auto)\n  with that show ?thesis\n    by blast\nqed\n\n\nsubsubsection \\<open>Union\\<close>\n\nlemma zcount_union[simp]: \"zcount (M + N) a = zcount M a + zcount N a\"\n  by transfer auto\n\nlemma union_add_left_zmset[simp]: \"add_zmset a A + B = add_zmset a (A + B)\"\n  by (auto simp: zmultiset_eq_iff)\n\nlemma union_zmset_add_zmset_right[simp]: \"A + add_zmset a B = add_zmset a (A + B)\"\n  by (auto simp: zmultiset_eq_iff)\n\nlemma add_zmset_add_single: \\<open>add_zmset a A = A + {#a#}\\<^sub>z\\<close>\n  by (subst union_zmset_add_zmset_right, subst add.comm_neutral) (rule refl)\n\n\nsubsubsection \\<open>Difference\\<close>\n\nlemma zcount_diff[simp]: \"zcount (M - N) a = zcount M a - zcount N a\"\n  by transfer auto\n\nlemma add_zmset_diff_bothsides: \\<open>add_zmset a M - add_zmset a A = M - A\\<close>\n  by (auto simp: zmultiset_eq_iff)\n\nlemma in_diff_zcount: \"a \\<in>#\\<^sub>z M - N \\<longleftrightarrow> zcount N a \\<noteq> zcount M a\"\n  by (fastforce simp: set_zmset_def)\n\nlemma diff_add_zmset:\n  fixes M N Q :: \"'a zmultiset\"\n  shows \"M - (N + Q) = M - N - Q\"\n  by (rule sym) (fact diff_diff_add)\n\nlemma insert_Diff_zmset[simp]: \"add_zmset x (M - {#x#}\\<^sub>z) = M\"\n  by (clarsimp simp: zmultiset_eq_iff)\n\nlemma diff_union_swap_zmset: \"add_zmset b (M - {#a#}\\<^sub>z) = add_zmset b M - {#a#}\\<^sub>z\"\n  by (auto simp add: zmultiset_eq_iff)\n\nlemma diff_add_zmset_swap[simp]: \"add_zmset b M - A = add_zmset b (M - A)\"\n  by (auto simp add: zmultiset_eq_iff)\n\nlemma diff_diff_add_zmset[simp]: \"(M :: 'a zmultiset) - N - P = M - (N + P)\"\n  by (rule diff_diff_add)\n\nlemma zmset_add[elim?]:\n  obtains B where \"A = add_zmset a B\"\nproof -\n  have \"A = add_zmset a (A - {#a#}\\<^sub>z)\"\n    by simp\n  with that show thesis .\nqed\n\n\nsubsubsection \\<open>Equality of Signed Multisets\\<close>\n\nlemma single_eq_single_zmset[simp]: \"{#a#}\\<^sub>z = {#b#}\\<^sub>z \\<longleftrightarrow> a = b\"\n  by (auto simp add: zmultiset_eq_iff)\n\nlemma multi_self_add_other_not_self_zmset[simp]: \"M = add_zmset x M \\<longleftrightarrow> False\"\n  by (auto simp add: zmultiset_eq_iff)\n\nlemma add_zmset_remove_trivial: \\<open>add_zmset x M - {#x#}\\<^sub>z = M\\<close>\n  by simp\n\nlemma diff_single_eq_union_zmset: \"M - {#x#}\\<^sub>z = N \\<longleftrightarrow> M = add_zmset x N\"\n  by auto\n\nlemma union_single_eq_diff_zmset: \"add_zmset x M = N \\<Longrightarrow> M = N - {#x#}\\<^sub>z\"\n  unfolding add_zmset_add_single[of _ M] by (fact add_implies_diff)\n\nlemma add_zmset_eq_conv_diff:\n  \"add_zmset a M = add_zmset b N \\<longleftrightarrow>\n   M = N \\<and> a = b \\<or> M = add_zmset b (N - {#a#}\\<^sub>z) \\<and> N = add_zmset a (M - {#b#}\\<^sub>z)\"\n  by (simp add: zmultiset_eq_iff) fastforce\n\nlemma add_zmset_eq_conv_ex:\n  \"(add_zmset a M = add_zmset b N) =\n    (M = N \\<and> a = b \\<or> (\\<exists>K. M = add_zmset b K \\<and> N = add_zmset a K))\"\n  by (auto simp add: add_zmset_eq_conv_diff)\n\nlemma multi_member_split: \"\\<exists>A. M = add_zmset x A\"\n  by (rule exI[where x = \"M - {#x#}\\<^sub>z\"]) simp\n\n\nsubsection \\<open>Conversions from and to Multisets\\<close>\n\nlift_definition zmset_of :: \"'a multiset \\<Rightarrow> 'a zmultiset\" is \"\\<lambda>f. (Abs_multiset f, {#})\" .\n\nlemma zmset_of_inject[simp]: \"zmset_of M = zmset_of N \\<longleftrightarrow> M = N\"\n  by (simp add: zmset_of_def, transfer', auto simp: equiv_zmset_def)\n\nlemma zmset_of_empty[simp]: \"zmset_of {#} = {#}\\<^sub>z\"\n  by (simp add: zmset_of_def zero_zmultiset_def)\n\nlemma zmset_of_add_mset[simp]: \"zmset_of (add_mset x M) = add_zmset x (zmset_of M)\"\n  by transfer (auto simp: equiv_zmset_def add_mset_def cong: if_cong)\n\nlemma zcount_of_mset[simp]: \"zcount (zmset_of M) x = int (count M x)\"\n  by (induct M) auto\n\nlemma zmset_of_plus: \"zmset_of (M + N) = zmset_of M + zmset_of N\"\n  by (transfer, auto simp: equiv_zmset_def eq_onp_same_args plus_multiset.abs_eq)+\n\nlift_definition mset_pos :: \"'a zmultiset \\<Rightarrow> 'a multiset\" is \"\\<lambda>(Mp, Mn). count (Mp - Mn)\"\n  by (auto simp add: equiv_zmset_def simp flip: set_mset_diff)\n    (metis add.commute add_diff_cancel_right)\n\nlift_definition mset_neg :: \"'a zmultiset \\<Rightarrow> 'a multiset\" is \"\\<lambda>(Mp, Mn). count (Mn - Mp)\"\n  by (auto simp add: equiv_zmset_def simp flip: set_mset_diff)\n    (metis add.commute add_diff_cancel_right)\n\nlemma\n  zmset_of_inverse[simp]: \"mset_pos (zmset_of M) = M\" and\n  minus_zmset_of_inverse[simp]: \"mset_neg (- zmset_of M) = M\"\n  by (transfer, simp)+\n\nlemma neg_zmset_pos[simp]: \"mset_neg (zmset_of M) = {#}\"\n  by (rule zmset_of_inject[THEN iffD1], simp, transfer, auto simp: equiv_zmset_def)+\n\nlemma\n  count_mset_pos[simp]: \"count (mset_pos M) x = nat (zcount M x)\" and\n  count_mset_neg[simp]: \"count (mset_neg M) x = nat (- zcount M x)\"\n  by (transfer; auto)+\n\nlemma\n  mset_pos_empty[simp]: \"mset_pos {#}\\<^sub>z = {#}\" and\n  mset_neg_empty[simp]: \"mset_neg {#}\\<^sub>z = {#}\"\n  by (rule multiset_eqI, simp)+\n\nlemma\n  mset_pos_singleton[simp]: \"mset_pos {#x#}\\<^sub>z = {#x#}\" and\n  mset_neg_singleton[simp]: \"mset_neg {#x#}\\<^sub>z = {#}\"\n  by (rule multiset_eqI, simp)+\n\nlemma\n  mset_pos_neg_partition: \"M = zmset_of (mset_pos M) - zmset_of (mset_neg M)\" and\n  mset_pos_as_neg: \"zmset_of (mset_pos M) = zmset_of (mset_neg M) + M\" and\n  mset_neg_as_pos: \"zmset_of (mset_neg M) = zmset_of (mset_pos M) - M\"\n  by (rule zmultiset_eqI, simp)+\n\nlemma mset_pos_uminus[simp]: \"mset_pos (- A) = mset_neg A\"\n  by (rule multiset_eqI) simp\n\nlemma mset_neg_uminus[simp]: \"mset_neg (- A) = mset_pos A\"\n  by (rule multiset_eqI) simp\n\nlemma mset_pos_plus[simp]:\n  \"mset_pos (A + B) = (mset_pos A - mset_neg B) + (mset_pos B - mset_neg A)\"\n  by (rule multiset_eqI) simp\n\nlemma mset_neg_plus[simp]:\n  \"mset_neg (A + B) = (mset_neg A - mset_pos B) + (mset_neg B - mset_pos A)\"\n  by (rule multiset_eqI) simp\n\nlemma mset_pos_diff[simp]:\n  \"mset_pos (A - B) = (mset_pos A - mset_pos B) + (mset_neg B - mset_neg A)\"\n  by (rule mset_pos_plus[of A \"- B\", simplified])\n\nlemma mset_neg_diff[simp]:\n  \"mset_neg (A - B) = (mset_neg A - mset_neg B) + (mset_pos B - mset_pos A)\"\n  by (rule mset_neg_plus[of A \"- B\", simplified])\n\nlemma mset_pos_neg_dual:\n  \"mset_pos a + mset_pos b + (mset_neg a - mset_pos b) + (mset_neg b - mset_pos a) =\n   mset_neg a + mset_neg b + (mset_pos a - mset_neg b) + (mset_pos b - mset_neg a)\"\n  using [[linarith_split_limit = 20]] by (rule multiset_eqI) simp\n\nlemma decompose_zmset_of2:\n  obtains A B C where\n    \"M = zmset_of A + C\" and\n    \"N = zmset_of B + C\"\nproof\n  let ?A = \"zmset_of (mset_pos M + mset_neg N)\"\n  let ?B = \"zmset_of (mset_pos N + mset_neg M)\"\n  let ?C = \"- (zmset_of (mset_neg M) + zmset_of (mset_neg N))\"\n\n  show \"M = ?A + ?C\"\n    by (simp add: zmset_of_plus mset_pos_neg_partition)\n  show \"N = ?B + ?C\"\n    by (simp add: zmset_of_plus diff_add_zmset mset_pos_neg_partition)\nqed\n\n\nsubsubsection \\<open>Pointwise Ordering Induced by @{const zcount}\\<close>\n\ndefinition subseteq_zmset :: \"'a zmultiset \\<Rightarrow> 'a zmultiset \\<Rightarrow> bool\" (infix \"\\<subseteq>#\\<^sub>z\" 50) where\n  \"A \\<subseteq>#\\<^sub>z B \\<longleftrightarrow> (\\<forall>a. zcount A a \\<le> zcount B a)\"\n\ndefinition subset_zmset :: \"'a zmultiset \\<Rightarrow> 'a zmultiset \\<Rightarrow> bool\" (infix \"\\<subset>#\\<^sub>z\" 50) where\n  \"A \\<subset>#\\<^sub>z B \\<longleftrightarrow> A \\<subseteq>#\\<^sub>z B \\<and> A \\<noteq> B\"\n\nabbreviation (input)\n  supseteq_zmset :: \"'a zmultiset \\<Rightarrow> 'a zmultiset \\<Rightarrow> bool\" (infix \"\\<supseteq>#\\<^sub>z\" 50)\nwhere\n  \"supseteq_zmset A B \\<equiv> B \\<subseteq>#\\<^sub>z A\"\n\nabbreviation (input)\n  supset_zmset :: \"'a zmultiset \\<Rightarrow> 'a zmultiset \\<Rightarrow> bool\" (infix \"\\<supset>#\\<^sub>z\" 50)\nwhere\n  \"supset_zmset A B \\<equiv> B \\<subset>#\\<^sub>z A\"\n\nnotation (input)\n  subseteq_zmset (infix \"\\<subseteq>#\\<^sub>z\" 50) and\n  supseteq_zmset (infix \"\\<supseteq>#\\<^sub>z\" 50)\n\nnotation (ASCII)\n  subseteq_zmset (infix \"\\<subseteq>#\\<^sub>z\" 50) and\n  subset_zmset (infix \"\\<subset>#\\<^sub>z\" 50) and\n  supseteq_zmset (infix \"\\<supseteq>#\\<^sub>z\" 50) and\n  supset_zmset (infix \">#\\<^sub>z\" 50)\n\ninterpretation subset_zmset: ordered_ab_semigroup_add_imp_le \"(+)\" \"(-)\" \"(\\<subseteq>#\\<^sub>z)\" \"(\\<subset>#\\<^sub>z)\"\n  by unfold_locales (auto simp add: subset_zmset_def subseteq_zmset_def zmultiset_eq_iff\n    intro: order_trans antisym)\n\ninterpretation subset_zmset:\n  ordered_ab_semigroup_monoid_add_imp_le \"(+)\" 0 \"(-)\" \"(\\<subseteq>#\\<^sub>z)\" \"(\\<subset>#\\<^sub>z)\"\n  by unfold_locales\n\nlemma zmset_subset_eqI: \"(\\<And>a. zcount A a \\<le> zcount B a) \\<Longrightarrow> A \\<subseteq>#\\<^sub>z B\"\n  by (simp add: subseteq_zmset_def)\n\nlemma zmset_subset_eq_zcount: \"A \\<subseteq>#\\<^sub>z B \\<Longrightarrow> zcount A a \\<le> zcount B a\"\n  by (simp add: subseteq_zmset_def)\n\nlemma zmset_subset_eq_add_zmset_cancel: \\<open>add_zmset a A \\<subseteq>#\\<^sub>z add_zmset a B \\<longleftrightarrow> A \\<subseteq>#\\<^sub>z B\\<close>\n  unfolding add_zmset_add_single[of _ A] add_zmset_add_single[of _ B]\n  by (rule subset_zmset.add_le_cancel_right)\n\nlemma zmset_subset_eq_zmultiset_union_diff_commute:\n  \"A - B + C = A + C - B\" for A B C :: \"'a zmultiset\"\n  by (simp add: add.commute add_diff_eq)\n\nlemma zmset_subset_eq_insertD: \"add_zmset x A \\<subseteq>#\\<^sub>z B \\<Longrightarrow> A \\<subset>#\\<^sub>z B\"\n  unfolding subset_zmset_def subseteq_zmset_def\n  by (metis (no_types) add.commute add_le_same_cancel2 zcount_add_zmset dual_order.trans le_cases\n    le_numeral_extra(2))\n\nlemma zmset_subset_insertD: \"add_zmset x A \\<subset>#\\<^sub>z B \\<Longrightarrow> A \\<subset>#\\<^sub>z B\"\n  by (rule zmset_subset_eq_insertD) (rule subset_zmset.less_imp_le)\n\nlemma subset_eq_diff_conv_zmset: \"A - C \\<subseteq>#\\<^sub>z B \\<longleftrightarrow> A \\<subseteq>#\\<^sub>z B + C\"\n  by (simp add: subseteq_zmset_def ordered_ab_group_add_class.diff_le_eq)\n\nlemma multi_psub_of_add_self_zmset[simp]: \"A \\<subset>#\\<^sub>z add_zmset x A\"\n  by (auto simp: subset_zmset_def subseteq_zmset_def)\n\nlemma multi_psub_self_zmset: \"A \\<subset>#\\<^sub>z A = False\"\n  by simp\n\nlemma zmset_subset_add_zmset[simp]: \"add_zmset x N \\<subset>#\\<^sub>z add_zmset x M \\<longleftrightarrow> N \\<subset>#\\<^sub>z M\"\n  unfolding add_zmset_add_single[of _ N] add_zmset_add_single[of _ M]\n  by (fact subset_zmset.add_less_cancel_right)\n\nlemma zmset_of_subseteq_iff[simp]: \"zmset_of M \\<subseteq>#\\<^sub>z zmset_of N \\<longleftrightarrow> M \\<subseteq># N\"\n  by (simp add: subseteq_zmset_def subseteq_mset_def)\n\nlemma zmset_of_subset_iff[simp]: \"zmset_of M \\<subset>#\\<^sub>z zmset_of N \\<longleftrightarrow> M \\<subset># N\"\n  by (simp add: subset_zmset_def subset_mset_def)\n\nlemma\n  mset_pos_supset: \"A \\<subseteq>#\\<^sub>z zmset_of (mset_pos A)\" and\n  mset_neg_supset: \"- A \\<subseteq>#\\<^sub>z zmset_of (mset_neg A)\"\n  by (auto intro: zmset_subset_eqI)\n\nlemma subset_mset_zmsetE:\n  assumes \"M \\<subset>#\\<^sub>z N\"\n  obtains A B C where\n    \"M = zmset_of A + C\" and \"N = zmset_of B + C\" and \"A \\<subset># B\"\n  by (metis assms decompose_zmset_of2 subset_zmset.add_less_cancel_right zmset_of_subset_iff)\n\nlemma subseteq_mset_zmsetE:\n  assumes \"M \\<subseteq>#\\<^sub>z N\"\n  obtains A B C where\n    \"M = zmset_of A + C\" and \"N = zmset_of B + C\" and \"A \\<subseteq># B\"\n  by (metis assms add.commute add.right_neutral subset_mset.order_refl subset_mset_def\n    subset_mset_zmsetE subset_zmset_def zmset_of_empty)\n\n\nsubsubsection \\<open>Subset is an Order\\<close>\n\ninterpretation subset_zmset: order \"(\\<subseteq>#\\<^sub>z)\" \"(\\<subset>#\\<^sub>z)\"\n  by unfold_locales\n\n\nsubsection \\<open>Replicate and Repeat Operations\\<close>\n\ndefinition replicate_zmset :: \"nat \\<Rightarrow> 'a \\<Rightarrow> 'a zmultiset\" where\n  \"replicate_zmset n x = (add_zmset x ^^ n) {#}\\<^sub>z\"\n\nlemma replicate_zmset_0[simp]: \"replicate_zmset 0 x = {#}\\<^sub>z\"\n  unfolding replicate_zmset_def by simp\n\nlemma replicate_zmset_Suc[simp]: \"replicate_zmset (Suc n) x = add_zmset x (replicate_zmset n x)\"\n  unfolding replicate_zmset_def by (induct n) (auto intro: add.commute)\n\nlemma count_replicate_zmset[simp]:\n  \"zcount (replicate_zmset n x) y = (if y = x then of_nat n else 0)\"\n  unfolding replicate_zmset_def by (induct n) auto\n\nfun repeat_zmset :: \"nat \\<Rightarrow> 'a zmultiset \\<Rightarrow> 'a zmultiset\" where\n  \"repeat_zmset 0 _ = {#}\\<^sub>z\" |\n  \"repeat_zmset (Suc n) A = A + repeat_zmset n A\"\n\nlemma count_repeat_zmset[simp]: \"zcount (repeat_zmset i A) a = of_nat i * zcount A a\"\n  by (induct i) (auto simp: semiring_normalization_rules(3))\n\nlemma repeat_zmset_right[simp]: \"repeat_zmset a (repeat_zmset b A) = repeat_zmset (a * b) A\"\n  by (auto simp: zmultiset_eq_iff left_diff_distrib')\n\nlemma left_diff_repeat_zmset_distrib':\n  \\<open>i \\<ge> j \\<Longrightarrow> repeat_zmset (i - j) u = repeat_zmset i u - repeat_zmset j u\\<close>\n  by (auto simp: zmultiset_eq_iff int_distrib(3) of_nat_diff)\n\nlemma left_add_mult_distrib_zmset:\n  \"repeat_zmset i u + (repeat_zmset j u + k) = repeat_zmset (i+j) u + k\"\n  by (auto simp: zmultiset_eq_iff add_mult_distrib int_distrib(1))\n\nlemma repeat_zmset_distrib: \"repeat_zmset (m + n) A = repeat_zmset m A + repeat_zmset n A\"\n  by (auto simp: zmultiset_eq_iff Nat.add_mult_distrib int_distrib(1))\n\nlemma repeat_zmset_distrib2[simp]:\n  \"repeat_zmset n (A + B) = repeat_zmset n A + repeat_zmset n B\"\n  by (auto simp: zmultiset_eq_iff add_mult_distrib2 int_distrib(2))\n\nlemma repeat_zmset_replicate_zmset[simp]: \"repeat_zmset n {#a#}\\<^sub>z = replicate_zmset n a\"\n  by (auto simp: zmultiset_eq_iff)\n\nlemma repeat_zmset_distrib_add_zmset[simp]:\n  \"repeat_zmset n (add_zmset a A) = replicate_zmset n a + repeat_zmset n A\"\n  by (auto simp: zmultiset_eq_iff int_distrib(2))\n\nlemma repeat_zmset_empty[simp]: \"repeat_zmset n {#}\\<^sub>z = {#}\\<^sub>z\"\n  by (induct n) simp_all\n\n\nsubsubsection \\<open>Filter (with Comprehension Syntax)\\<close>\n\nlift_definition filter_zmset :: \"('a \\<Rightarrow> bool) \\<Rightarrow> 'a zmultiset \\<Rightarrow> 'a zmultiset\" is\n  \"\\<lambda>P (Mp, Mn). (filter_mset P Mp, filter_mset P Mn)\"\n  by (auto simp del: filter_union_mset simp: equiv_zmset_def filter_union_mset[symmetric])\n\nsyntax (ASCII)\n  \"_ZMCollect\" :: \"pttrn \\<Rightarrow> 'a zmultiset \\<Rightarrow> bool \\<Rightarrow> 'a zmultiset\" (\"(1{#_ :#z _./ _#})\")\nsyntax\n  \"_ZMCollect\" :: \"pttrn \\<Rightarrow> 'a zmultiset \\<Rightarrow> bool \\<Rightarrow> 'a zmultiset\" (\"(1{#_ \\<in>#\\<^sub>z _./ _#})\")\ntranslations\n  \"{#x \\<in>#\\<^sub>z M. P#}\" == \"CONST filter_zmset (\\<lambda>x. P) M\"\n\nlemma count_filter_zmset[simp]:\n  \"zcount (filter_zmset P M) a = (if P a then zcount M a else 0)\"\n  by transfer auto\n\nlemma filter_empty_zmset[simp]: \"filter_zmset P {#}\\<^sub>z = {#}\\<^sub>z\"\n  by (rule zmultiset_eqI) simp\n\nlemma filter_single_zmset: \"filter_zmset P {#x#}\\<^sub>z = (if P x then {#x#}\\<^sub>z else {#}\\<^sub>z)\"\n  by (rule zmultiset_eqI) simp\n\nlemma filter_union_zmset[simp]: \"filter_zmset P (M + N) = filter_zmset P M + filter_zmset P N\"\n  by (rule zmultiset_eqI) simp\n\nlemma filter_diff_zmset[simp]: \"filter_zmset P (M - N) = filter_zmset P M - filter_zmset P N\"\n  by (rule zmultiset_eqI) simp\n\nlemma filter_add_zmset[simp]:\n  \"filter_zmset P (add_zmset x A) =\n   (if P x then add_zmset x (filter_zmset P A) else filter_zmset P A)\"\n  by (auto simp: zmultiset_eq_iff)\n\nlemma zmultiset_filter_mono:\n  assumes \"A \\<subseteq>#\\<^sub>z B\"\n  shows \"filter_zmset f A \\<subseteq>#\\<^sub>z filter_zmset f B\"\n  using assms by (simp add: subseteq_zmset_def)\n\nlemma filter_filter_zmset: \"filter_zmset P (filter_zmset Q M) = {#x \\<in>#\\<^sub>z M. Q x \\<and> P x#}\"\n  by (auto simp: zmultiset_eq_iff)\n\nlemma\n  filter_zmset_True[simp]: \"{#y \\<in>#\\<^sub>z M. True#} = M\" and\n  filter_zmset_False[simp]: \"{#y \\<in>#\\<^sub>z M. False#} = {#}\\<^sub>z\"\n  by (auto simp: zmultiset_eq_iff)\n\n\nsubsection \\<open>Uncategorized\\<close>\n\nlemma multi_drop_mem_not_eq_zmset: \"B - {#c#}\\<^sub>z \\<noteq> B\"\n  by (simp add: diff_single_eq_union_zmset)\n\nlemma zmultiset_partition: \"M = {#x \\<in>#\\<^sub>z M. P x #} + {#x \\<in>#\\<^sub>z M. \\<not> P x#}\"\n  by (subst zmultiset_eq_iff) auto\n\n\nsubsection \\<open>Image\\<close>\n\ndefinition image_zmset :: \"('a \\<Rightarrow> 'b) \\<Rightarrow> 'a zmultiset \\<Rightarrow> 'b zmultiset\" where\n  \"image_zmset f M =\n   zmset_of (fold_mset (add_mset \\<circ> f) {#} (mset_pos M)) -\n   zmset_of (fold_mset (add_mset \\<circ> f) {#} (mset_neg M))\"\n\n\nsubsection \\<open>Multiset Order\\<close>\n\ninstantiation zmultiset :: (preorder) order\nbegin\n\nlift_definition less_zmultiset :: \"'a zmultiset \\<Rightarrow> 'a zmultiset \\<Rightarrow> bool\" is\n  \"\\<lambda>(Mp, Mn) (Np, Nn). Mp + Nn < Mn + Np\"\nproof (clarsimp simp: equiv_zmset_def)\n  fix A1 B2 B1 A2 C1 D2 D1 C2 :: \"'a multiset\"\n  assume\n    ab: \"A1 + A2 = B1 + B2\" and\n    cd: \"C1 + C2 = D1 + D2\"\n\n  have \"A1 + D2 < B2 + C1 \\<longleftrightarrow> A1 + A2 + D2 < A2 + B2 + C1\"\n    by simp\n  also have \"\\<dots> \\<longleftrightarrow> B1 + B2 + D2 < A2 + B2 + C1\"\n    unfolding ab by (rule refl)\n  also have \"\\<dots> \\<longleftrightarrow> B1 + D2 < A2 + C1\"\n    by simp\n  also have \"\\<dots> \\<longleftrightarrow> B1 + D1 + D2 < A2 + C1 + D1\"\n    by simp\n  also have \"\\<dots> \\<longleftrightarrow> B1 + C1 + C2 < A2 + C1 + D1\"\n    using cd by (simp add: add.assoc)\n  also have \"\\<dots> \\<longleftrightarrow> B1 + C2 < A2 + D1\"\n    by simp\n  finally show \"A1 + D2 < B2 + C1 \\<longleftrightarrow> B1 + C2 < A2 + D1\"\n    by assumption\nqed\n\ndefinition less_eq_zmultiset :: \"'a zmultiset \\<Rightarrow> 'a zmultiset \\<Rightarrow> bool\" where\n  \"less_eq_zmultiset M' M \\<longleftrightarrow> M' < M \\<or> M' = M\"\n\ninstance\nproof ((intro_classes; unfold less_eq_zmultiset_def; transfer),\n    auto simp: equiv_zmset_def union_commute)\n  fix A1 B1 D C B2 A2 :: \"'a multiset\"\n  assume ab: \"A1 + A2 \\<noteq> B1 + B2\"\n\n  {\n    assume ab1: \"A1 + C < B1 + D\"\n\n    {\n      assume ab2: \"D + A2 < C + B2\"\n      show \"A1 + A2 < B1 + B2\"\n      proof -\n        have f1: \"\\<And>m. D + A2 + m < C + B2 + m\"\n          using ab2 add_less_cancel_right by blast\n        have \"\\<And>m. C + (A1 + m) < D + (B1 + m)\"\n          by (simp add: ab1 add.commute)\n        then have \"D + (A2 + A1) < D + (B1 + B2)\"\n          using f1 by (metis add.assoc add.commute mset_le_trans)\n        then show ?thesis\n          by (simp add: add.commute)\n      qed\n    }\n    {\n      assume ab2: \"D + A2 = C + B2\"\n      show \"A1 + A2 < B1 + B2\"\n      proof -\n        have \"\\<And>m. C + A1 + m < D + B1 + m\"\n          by (simp add: ab1 add.commute)\n        then have \"D + (A2 + A1) < D + (B1 + B2)\"\n          by (metis (no_types) ab2 add.assoc add.commute)\n        then show ?thesis\n          by (simp add: add.commute)\n      qed\n    }\n  }\n\n  {\n    assume ab1: \"A1 + C = B1 + D\"\n\n    {\n      assume ab2: \"D + A2 < C + B2\"\n      show \"A1 + A2 < B1 + B2\"\n      proof -\n        have \"A1 + (D + A2) < B1 + (D + B2)\"\n          by (metis (no_types) ab1 ab2 add.assoc add_less_cancel_left)\n        then show ?thesis\n          by simp\n      qed\n    }\n    {\n      assume ab2: \"D + A2 = C + B2\"\n      have False\n        by (metis (no_types) ab ab1 ab2 add.assoc add.commute add_diff_cancel_right')\n      thus \"A1 + A2 < B1 + B2\"\n        by sat\n    }\n  }\nqed\n\nend\n\ninstance zmultiset :: (preorder) ordered_cancel_comm_monoid_add\n  by (intro_classes, unfold less_eq_zmultiset_def, transfer, auto simp: equiv_zmset_def)\n\ninstance zmultiset :: (preorder) ordered_ab_group_add\n  by (intro_classes; transfer; auto simp: equiv_zmset_def)\n\ninstantiation zmultiset :: (linorder) distrib_lattice\nbegin\n\ndefinition inf_zmultiset :: \"'a zmultiset \\<Rightarrow> 'a zmultiset \\<Rightarrow> 'a zmultiset\" where\n  \"inf_zmultiset A B = (if A < B then A else B)\"\n\ndefinition sup_zmultiset :: \"'a zmultiset \\<Rightarrow> 'a zmultiset \\<Rightarrow> 'a zmultiset\" where\n  \"sup_zmultiset A B = (if B > A then B else A)\"\n\nlemma not_lt_iff_ge_zmset: \"\\<not> x < y \\<longleftrightarrow> x \\<ge> y\" for x y :: \"'a zmultiset\"\n  by (unfold less_eq_zmultiset_def, transfer, auto simp: equiv_zmset_def algebra_simps)\n\ninstance\n  by intro_classes (auto simp: less_eq_zmultiset_def inf_zmultiset_def sup_zmultiset_def\n    dest!: not_lt_iff_ge_zmset[THEN iffD1])\n\nend\n\nlemma zmset_of_less: \"zmset_of M < zmset_of N \\<longleftrightarrow> M < N\"\n  by (clarsimp simp: zmset_of_def, transfer', simp)+\n\nlemma zmset_of_le: \"zmset_of M \\<le> zmset_of N \\<longleftrightarrow> M \\<le> N\"\n  by (simp_all add: less_eq_zmultiset_def zmset_of_def; transfer'; auto simp: equiv_zmset_def)\n\ninstance zmultiset :: (preorder) ordered_ab_semigroup_add\n  by (intro_classes, unfold less_eq_zmultiset_def, transfer, auto simp: equiv_zmset_def)\n\nlemma uminus_add_conv_diff_mset[cancelation_simproc_pre]: \\<open>-a + b = b - a\\<close> for a :: \\<open>'a zmultiset\\<close>\n  by (simp add: add.commute)\n\nlemma uminus_add_add_uminus[cancelation_simproc_pre]: \\<open>b -a + c = b + c - a\\<close> for a :: \\<open>'a zmultiset\\<close>\n  by (simp add: uminus_add_conv_diff_mset zmset_subset_eq_zmultiset_union_diff_commute)\n\nlemma add_zmset_eq_add_NO_MATCH[cancelation_simproc_pre]:\n  \\<open>NO_MATCH {#}\\<^sub>z H \\<Longrightarrow> add_zmset a H = {#a#}\\<^sub>z + H\\<close>\n  by auto\n\nlemma repeat_zmset_iterate_add: \\<open>repeat_zmset n M = iterate_add n M\\<close>\n  unfolding iterate_add_def by (induction n) auto\n\ndeclare repeat_zmset_iterate_add[cancelation_simproc_pre]\n\ndeclare repeat_zmset_iterate_add[symmetric, cancelation_simproc_post]\n\nsimproc_setup zmseteq_cancel_numerals\n  (\"(l::'a zmultiset) + m = n\" | \"(l::'a zmultiset) = m + n\" |\n   \"add_zmset a m = n\" | \"m = add_zmset a n\" |\n   \"replicate_zmset p a = n\" | \"m = replicate_zmset p a\" |\n   \"repeat_zmset p m = n\" | \"m = repeat_zmset p m\") =\n  \\<open>fn phi => Cancel_Simprocs.eq_cancel\\<close>\n\nlemma zmset_subseteq_add_iff1:\n  \\<open>j \\<le> i \\<Longrightarrow> (repeat_zmset i u + m \\<subseteq>#\\<^sub>z repeat_zmset j u + n) = (repeat_zmset (i - j) u + m \\<subseteq>#\\<^sub>z n)\\<close>\n  by (simp add: add.commute add_diff_eq left_diff_repeat_zmset_distrib' subset_eq_diff_conv_zmset)\n\nlemma zmset_subseteq_add_iff2:\n  \\<open>i \\<le> j \\<Longrightarrow> (repeat_zmset i u + m \\<subseteq>#\\<^sub>z repeat_zmset j u + n) = (m \\<subseteq>#\\<^sub>z repeat_zmset (j - i) u + n)\\<close>\nproof -\n  assume \"i \\<le> j\"\n  then have \"\\<And>z. repeat_zmset j (z::'a zmultiset) - repeat_zmset i z = repeat_zmset (j - i) z\"\n    by (simp add: left_diff_repeat_zmset_distrib')\n  then show ?thesis\n    by (metis add.commute diff_diff_eq2 subset_eq_diff_conv_zmset)\nqed\n\nlemma zmset_subset_add_iff1:\n  \\<open>j \\<le> i \\<Longrightarrow> (repeat_zmset i u + m \\<subset>#\\<^sub>z repeat_zmset j u + n) = (repeat_zmset (i - j) u + m \\<subset>#\\<^sub>z n)\\<close>\n  by (simp add: subset_zmset.less_le_not_le zmset_subseteq_add_iff1 zmset_subseteq_add_iff2)\n\nlemma zmset_subset_add_iff2:\n  \\<open>i \\<le> j \\<Longrightarrow> (repeat_zmset i u + m \\<subset>#\\<^sub>z repeat_zmset j u + n) = (m \\<subset>#\\<^sub>z repeat_zmset (j - i) u + n)\\<close>\n  by (simp add: subset_zmset.less_le_not_le zmset_subseteq_add_iff1 zmset_subseteq_add_iff2)\n\nML_file \\<open>zmultiset_simprocs.ML\\<close>\n\nsimproc_setup zmsetsubset_cancel\n  (\"(l::'a zmultiset) + m \\<subset>#\\<^sub>z n\" | \"(l::'a zmultiset) \\<subset>#\\<^sub>z m + n\" |\n   \"add_zmset a m \\<subset>#\\<^sub>z n\" | \"m \\<subset>#\\<^sub>z add_zmset a n\" |\n   \"replicate_zmset p a \\<subset>#\\<^sub>z n\" | \"m \\<subset>#\\<^sub>z replicate_zmset p a\" |\n   \"repeat_zmset p m \\<subset>#\\<^sub>z n\" | \"m \\<subset>#\\<^sub>z repeat_zmset p m\") =\n  \\<open>fn phi => ZMultiset_Simprocs.subset_cancel_zmsets\\<close>\n\nsimproc_setup zmsetsubseteq_cancel\n  (\"(l::'a zmultiset) + m \\<subseteq>#\\<^sub>z n\" | \"(l::'a zmultiset) \\<subseteq>#\\<^sub>z m + n\" |\n   \"add_zmset a m \\<subseteq>#\\<^sub>z n\" | \"m \\<subseteq>#\\<^sub>z add_zmset a n\" |\n   \"replicate_zmset p a \\<subseteq>#\\<^sub>z n\" | \"m \\<subseteq>#\\<^sub>z replicate_zmset p a\" |\n   \"repeat_zmset p m \\<subseteq>#\\<^sub>z n\" | \"m \\<subseteq>#\\<^sub>z repeat_zmset p m\") =\n  \\<open>fn phi => ZMultiset_Simprocs.subseteq_cancel_zmsets\\<close>\n\ninstance zmultiset :: (preorder) ordered_ab_semigroup_add_imp_le\n  by (intro_classes; unfold less_eq_zmultiset_def; transfer; auto)\n\nsimproc_setup zmsetless_cancel\n  (\"(l::'a::preorder zmultiset) + m < n\" | \"(l::'a zmultiset) < m + n\" |\n   \"add_zmset a m < n\" | \"m < add_zmset a n\" |\n   \"replicate_zmset p a < n\" | \"m < replicate_zmset p a\" |\n   \"repeat_zmset p m < n\" | \"m < repeat_zmset p m\") =\n  \\<open>fn phi => Cancel_Simprocs.less_cancel\\<close>\n\nsimproc_setup zmsetless_eq_cancel\n  (\"(l::'a::preorder zmultiset) + m \\<le> n\" | \"(l::'a zmultiset) \\<le> m + n\" |\n   \"add_zmset a m \\<le> n\" | \"m \\<le> add_zmset a n\" |\n   \"replicate_zmset p a \\<le> n\" | \"m \\<le> replicate_zmset p a\" |\n   \"repeat_zmset p m \\<le> n\" | \"m \\<le> repeat_zmset p m\") =\n  \\<open>fn phi => Cancel_Simprocs.less_eq_cancel\\<close>\n\nsimproc_setup zmsetdiff_cancel\n  (\"n + (l::'a zmultiset)\" | \"(l::'a zmultiset) - m\" |\n   \"add_zmset a m - n\" | \"m - add_zmset a n\" |\n   \"replicate_zmset p r - n\" | \"m - replicate_zmset p r\" |\n   \"repeat_zmset p m - n\" | \"m - repeat_zmset p m\") =\n  \\<open>fn phi => Cancel_Simprocs.diff_cancel\\<close>\n\ninstance zmultiset :: (linorder) linordered_cancel_ab_semigroup_add\n  by (intro_classes, unfold less_eq_zmultiset_def, transfer, auto simp: equiv_zmset_def add.commute)\n\nlemma less_mset_zmsetE:\n  assumes \"M < N\"\n  obtains A B C where\n    \"M = zmset_of A + C\" and \"N = zmset_of B + C\" and \"A < B\"\n  by (metis add_less_imp_less_right assms decompose_zmset_of2 zmset_of_less)\n\nlemma less_eq_mset_zmsetE:\n  assumes \"M \\<le> N\"\n  obtains A B C where\n    \"M = zmset_of A + C\" and \"N = zmset_of B + C\" and \"A \\<le> B\"\n  by (metis add.commute add.right_neutral assms le_neq_trans less_imp_le less_mset_zmsetE order_refl\n    zmset_of_empty)\n\nlemma subset_eq_imp_le_zmset: \"M \\<subseteq>#\\<^sub>z N \\<Longrightarrow> M \\<le> N\"\n  by (metis (no_types) add_mono_thms_linordered_semiring(3) subset_eq_imp_le_multiset\n    subseteq_mset_zmsetE zmset_of_le)\n\nlemma subset_imp_less_zmset: \"M \\<subset>#\\<^sub>z N \\<Longrightarrow> M < N\"\n  by (metis le_neq_trans subset_eq_imp_le_zmset subset_zmset_def)\n\nlemma lt_imp_ex_zcount_lt:\n  assumes m_lt_n: \"M < N\"\n  shows \"\\<exists>y. zcount M y < zcount N y\"\nproof (rule ccontr, clarsimp)\n  assume \"\\<forall>y. \\<not> zcount M y < zcount N y\"\n  hence \"\\<forall>y. zcount M y \\<ge> zcount N y\"\n    by (simp add: leI)\n  hence \"M \\<supseteq>#\\<^sub>z N\"\n    by (simp add: zmset_subset_eqI)\n  hence \"M \\<ge> N\"\n    by (simp add: subset_eq_imp_le_zmset)\n  thus False\n    using m_lt_n by simp\nqed\n\ninstance zmultiset :: (preorder) no_top\nproof\n  fix M :: \\<open>'a zmultiset\\<close>\n  obtain a :: 'a where True by fast\n  let ?M = \\<open>zmset_of (mset_pos M) + zmset_of (mset_neg M)\\<close>\n  have \\<open>M < add_zmset a ?M + ?M\\<close>\n    by (subst mset_pos_neg_partition)\n      (auto simp: subset_zmset_def subseteq_zmset_def zmultiset_eq_iff\n        intro!: subset_imp_less_zmset)\n  then show \\<open>\\<exists>N. M < N\\<close>\n    by blast\nqed\n\nlifting_update multiset.lifting\nlifting_forget multiset.lifting\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/Signed_Multiset.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314677809303, "lm_q2_score": 0.8333246035907933, "lm_q1q2_score": 0.7380184918160761}}
{"text": "theory ex3_06 imports Main \"~~/src/HOL/IMP/AExp\" begin\n\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 x) s = s x\" |\n\"lval (Plusl l r) s = lval l s + lval r s\" |\n\"lval (LET x a b) s = lval b (s(x := lval a s))\"\n\n(** let x = (let y = 1 in y+y) in 1+x == 3 **)\nvalue \"lval (LET ''x'' (LET ''y'' (Nl 1) (Plusl (Vl ''y'') (Vl ''y''))) (Plusl (Nl 1) (Vl ''x''))) <>\"\n\n(** see ex3.3 **)\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 x = v then a else (V v))\" |\n\"subst x a (Plus l r) = Plus (subst x a l) (subst x a r)\"\n\ntheorem[simp]: \"aval (subst x a e) s = aval e (s(x := aval a s))\"\nby (induction e, auto)\n\ntheorem[simp]: \"aval a_1 s = aval a_2 s \\<Longrightarrow> aval (subst x a_1 e) s = aval (subst x a_2 e) s\"\nby (induction e, auto)\n\nfun inline :: \"lexp \\<Rightarrow> aexp\" where\n\"inline (Nl n) = N n\" |\n\"inline (Vl x) = V x\" |\n\"inline (Plusl l r) = Plus (inline l) (inline r)\" |\n\"inline (LET x a b) = subst x (inline a) (inline b)\"\n\n(** let x = (let y = 1 in y+y) in 1+x **)\nvalue \"inline (LET ''x'' (LET ''y'' (Nl 1) (Plusl (Vl ''y'') (Vl ''y''))) (Plusl (Nl 1) (Vl ''x'')))\"\n\ntheorem \"aval (inline e) s = lval e s\"\napply(induction e arbitrary: s)\napply auto\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_06.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314677809303, "lm_q2_score": 0.8333245953120233, "lm_q1q2_score": 0.7380184844841369}}
{"text": "(* Authors: F. Maric, M. Spasic, R. Thiemann *)\nsection \\<open>Linear Polynomials and Constraints\\<close>\n\ntheory Abstract_Linear_Poly  \n  imports\n    Simplex_Algebra \nbegin\n\ntype_synonym var = nat\n\ntext\\<open>(Infinite) linear polynomials as functions from vars to coeffs\\<close>\n\ndefinition fun_zero :: \"var \\<Rightarrow> 'a::zero\" where\n  [simp]: \"fun_zero == \\<lambda> v. 0\"\ndefinition fun_plus :: \"(var \\<Rightarrow> 'a) \\<Rightarrow> (var \\<Rightarrow> 'a) \\<Rightarrow> var \\<Rightarrow> 'a::plus\" where\n  [simp]: \"fun_plus f1 f2 == \\<lambda> v. f1 v + f2 v\"\ndefinition fun_scale :: \"'a \\<Rightarrow> (var \\<Rightarrow> 'a) \\<Rightarrow> (var \\<Rightarrow> 'a::ring)\" where\n  [simp]: \"fun_scale c f == \\<lambda> v. c*(f v)\"\ndefinition fun_coeff :: \"(var \\<Rightarrow> 'a) \\<Rightarrow> var \\<Rightarrow> 'a\" where\n  [simp]: \"fun_coeff f var = f var\"\ndefinition fun_vars :: \"(var \\<Rightarrow> 'a::zero) \\<Rightarrow> var set\" where\n  [simp]: \"fun_vars f = {v. f v \\<noteq> 0}\"\ndefinition fun_vars_list :: \"(var \\<Rightarrow> 'a::zero) \\<Rightarrow> var list\" where\n  [simp]: \"fun_vars_list f = sorted_list_of_set {v. f v \\<noteq> 0}\"\ndefinition fun_var :: \"var \\<Rightarrow> (var \\<Rightarrow> 'a::{zero,one})\" where\n  [simp]: \"fun_var x = (\\<lambda> x'. if x' = x then 1 else 0)\"\ntype_synonym 'a valuation = \"var \\<Rightarrow> 'a\"\ndefinition fun_valuate :: \"(var \\<Rightarrow> rat) \\<Rightarrow> 'a valuation \\<Rightarrow> ('a::rational_vector)\" where\n  [simp]: \"fun_valuate lp val = (\\<Sum>x\\<in>{v. lp v \\<noteq> 0}. lp x *R val x)\"\n\ntext\\<open>Invariant -- only finitely many variables\\<close>\ndefinition inv where\n  [simp]: \"inv c == finite {v. c v \\<noteq> 0}\"\n\nlemma inv_fun_zero [simp]: \n  \"inv fun_zero\" by simp\n\nlemma inv_fun_plus [simp]: \n  \"\\<lbrakk>inv (f1 :: nat \\<Rightarrow> 'a::monoid_add); inv f2\\<rbrakk> \\<Longrightarrow> inv (fun_plus f1 f2)\"\nproof-\n  have *: \"{v. f1 v + f2 v \\<noteq> (0 :: 'a)} \\<subseteq> {v. f1 v \\<noteq> (0 :: 'a)} \\<union> {v. f2 v \\<noteq> (0 :: 'a)}\"\n    by auto\n  assume \"inv f1\" \"inv f2\"\n  then show ?thesis\n    using *\n    by (auto simp add: finite_subset)\nqed\n\nlemma inv_fun_scale [simp]: \n  \"inv (f :: nat \\<Rightarrow> 'a::ring) \\<Longrightarrow> inv (fun_scale r f)\"\nproof-\n  have *: \"{v. r * (f v) \\<noteq> 0} \\<subseteq> {v. f v \\<noteq> 0}\" \n    by auto\n  assume \"inv f\"\n  then show ?thesis\n    using *\n    by (auto simp add: finite_subset)\nqed\n\ntext\\<open>linear-poly type -- rat coeffs\\<close>\n  (* TODO: change rat to arbitrary ring *)\n\ntypedef  linear_poly = \"{c :: var \\<Rightarrow> rat. inv c}\"\n  by (rule_tac x=\"\\<lambda> v. 0\" in exI) auto\n\n\ntext\\<open>Linear polynomials are of the form $a_1 \\cdot x_1 + ... + a_n\n\\cdot x_n$. Their formalization follows the data-refinement approach\nof Isabelle/HOL \\cite{florian-refinement}. Abstract representation of\npolynomials are functions mapping variables to their coefficients,\nwhere only finitely many variables have non-zero\ncoefficients. Operations on polynomials are defined as operations on\nfunctions. For example, the sum of @{term \"p\\<^sub>1\"} and \\<open>p\\<^sub>2\\<close> is\ndefined by @{term \"\\<lambda> v. p\\<^sub>1 v + p\\<^sub>2 v\"} and the value of a polynomial\n@{term \"p\"} for a valuation @{term \"v\"} (denoted by \\<open>p\\<lbrace>v\\<rbrace>\\<close>),\nis defined by @{term \"\\<Sum>x\\<in>{x. p x \\<noteq> 0}. p x * v x\"}. Executable\nrepresentation of polynomials uses RBT mappings instead of functions.\n\\<close>\n\nsetup_lifting type_definition_linear_poly \n\ntext\\<open>Vector space operations on polynomials\\<close>\ninstantiation linear_poly :: rational_vector\nbegin\n\nlift_definition zero_linear_poly :: \"linear_poly\" is fun_zero by (rule inv_fun_zero)\n\nlift_definition plus_linear_poly :: \"linear_poly \\<Rightarrow> linear_poly \\<Rightarrow> linear_poly\" is fun_plus\n  by (rule inv_fun_plus)\n\nlift_definition scaleRat_linear_poly :: \"rat \\<Rightarrow> linear_poly \\<Rightarrow> linear_poly\" is fun_scale\n  by (rule inv_fun_scale)\n\ndefinition uminus_linear_poly :: \"linear_poly \\<Rightarrow> linear_poly\" where \n  \"uminus_linear_poly lp = -1 *R lp\"\n\ndefinition minus_linear_poly :: \"linear_poly \\<Rightarrow> linear_poly \\<Rightarrow> linear_poly\" where\n  \"minus_linear_poly lp1 lp2 = lp1 + (- lp2)\"\n\ninstance\nproof\n  fix a b c::linear_poly\n  show \"a + b + c = a + (b + c)\" by (transfer, auto)\n  show \"a + b = b + a\" by (transfer, auto)\n  show \"0 + a = a\" by (transfer, auto)\n  show \"-a + a = 0\" unfolding uminus_linear_poly_def by (transfer, auto)\n  show \"a - b = a + (- b)\" unfolding minus_linear_poly_def ..\nnext\n  fix a :: rat and x y :: linear_poly\n  show \"a *R (x + y) = a *R x + a *R y\" by (transfer, auto simp: field_simps)\nnext\n  fix a b::rat and x::linear_poly\n  show \"(a + b) *R x = a *R x + b *R x\" by (transfer, auto simp: field_simps)\n  show \"a *R b *R x = (a * b) *R x\" by (transfer, auto simp: field_simps)\nnext\n  fix x::linear_poly\n  show \"1 *R x = x\" by (transfer, auto)\nqed\n\nend\n\ntext\\<open>Coefficient\\<close>\nlift_definition coeff :: \"linear_poly \\<Rightarrow> var \\<Rightarrow> rat\" is fun_coeff .\n\nlemma coeff_plus [simp] : \"coeff (lp1 + lp2) var = coeff lp1 var + coeff lp2 var\"\n  by transfer auto\n\nlemma coeff_scaleRat [simp]: \"coeff (k *R lp1) var = k * coeff lp1 var\"\n  by transfer auto\n\nlemma coeff_uminus [simp]: \"coeff (-lp) var = - coeff lp var\"\n  unfolding uminus_linear_poly_def \n  by transfer auto\n\nlemma coeff_minus [simp]: \"coeff (lp1 - lp2) var = coeff lp1 var - coeff lp2 var\"\n  unfolding minus_linear_poly_def uminus_linear_poly_def\n  by transfer auto\n\ntext\\<open>Set of variables\\<close>\n\nlift_definition vars :: \"linear_poly \\<Rightarrow> var set\" is fun_vars .\n\nlemma coeff_zero: \"coeff p x \\<noteq> 0 \\<longleftrightarrow> x \\<in> vars p\" \n  by transfer auto\n\n\nlemma finite_vars: \"finite (vars p)\" \n  by transfer auto\n\n\ntext\\<open>List of variables\\<close>\nlift_definition vars_list :: \"linear_poly \\<Rightarrow> var list\" is fun_vars_list .\n\nlemma set_vars_list: \"set (vars_list lp) = vars lp\"\n  by transfer auto\n\ntext\\<open>Construct single variable polynomial\\<close>\nlift_definition Var :: \"var \\<Rightarrow> linear_poly\" is fun_var by auto\n\ntext\\<open>Value of a polynomial in a given valuation\\<close>\nlift_definition valuate :: \"linear_poly \\<Rightarrow> 'a valuation \\<Rightarrow> ('a::rational_vector)\" is fun_valuate .\n\nsyntax\n  \"_valuate\" :: \"linear_poly \\<Rightarrow> 'a valuation \\<Rightarrow> 'a\"    (\"_ \\<lbrace> _ \\<rbrace>\")\ntranslations\n  \"p\\<lbrace>v\\<rbrace> \" == \"CONST valuate p v\"\n\nlemma valuate_zero: \"(0 \\<lbrace>v\\<rbrace>) = 0\" \n  by transfer auto\n\nlemma \n  valuate_diff: \"(p \\<lbrace>v1\\<rbrace>) - (p \\<lbrace>v2\\<rbrace>) = (p \\<lbrace> \\<lambda> x. v1 x - v2 x \\<rbrace>)\"\n  by (transfer, simp add: sum_subtractf[THEN sym], auto simp: rational_vector.scale_right_diff_distrib)\n\n\nlemma valuate_opposite_val: \n  shows \"p \\<lbrace> \\<lambda> x. - v x \\<rbrace> = - (p \\<lbrace> v \\<rbrace>)\"\n  using valuate_diff[of p \"\\<lambda> x. 0\" v]\n  by (auto simp add: valuate_def)\n\nlemma valuate_nonneg:\n  fixes v :: \"'a::linordered_rational_vector valuation\"\n  assumes \"\\<forall> x \\<in> vars p. (coeff p x > 0 \\<longrightarrow> v x \\<ge> 0) \\<and> (coeff p x < 0 \\<longrightarrow> v x \\<le> 0)\"\n  shows \"p \\<lbrace> v \\<rbrace> \\<ge> 0\" \n  using assms\nproof (transfer, unfold fun_valuate_def, goal_cases)\n  case (1 p v)\n  from 1 have fin: \"finite {v. p v \\<noteq> 0}\" by auto\n  then show \"0 \\<le> (\\<Sum>x\\<in>{v. p v \\<noteq> 0}. p x *R v x)\" \n  proof (induct rule: finite_induct)\n    case empty show ?case by auto\n  next\n    case (insert x F)\n    show ?case unfolding sum.insert[OF insert(1-2)]\n    proof (rule order.trans[OF _ add_mono[OF _ insert(3)]])\n      show \"0 \\<le> p x *R v x\" using scaleRat_leq1[of 0 \"v x\" \"p x\"]\n        using scaleRat_leq2[of \"v x\" 0 \"p x\"] 1(2)\n        by (cases \"p x > 0\"; cases \"p x < 0\"; auto)\n    qed auto\n  qed\nqed\n\nlemma valuate_nonpos:\n  fixes v :: \"'a::linordered_rational_vector valuation\"\n  assumes \"\\<forall> x \\<in> vars p. (coeff p x > 0 \\<longrightarrow> v x \\<le> 0) \\<and> (coeff p x < 0 \\<longrightarrow> v x \\<ge> 0)\"\n  shows \"p \\<lbrace> v \\<rbrace> \\<le> 0\"\n  using assms\n  using valuate_opposite_val[of p v]\n  using valuate_nonneg[of p \"\\<lambda> x. - v x\"]\n  using scaleRat_leq2[of \"0::'a\" _ \"-1\"]\n  using scaleRat_leq2[of _ \"0::'a\" \"-1\"]\n  by force\n\nlemma valuate_uminus: \"(-p) \\<lbrace>v\\<rbrace> = - (p \\<lbrace>v\\<rbrace>)\"\n  unfolding uminus_linear_poly_def \n  by (transfer, auto simp: sum_negf)\n\nlemma valuate_add_lemma:\n  fixes v :: \"'a \\<Rightarrow> 'b::rational_vector\"\n  assumes \"finite {v. f1 v \\<noteq> 0}\" \"finite {v. f2 v \\<noteq> 0}\"\n  shows\n    \"(\\<Sum>x\\<in>{v. f1 v + f2 v \\<noteq> 0}. (f1 x + f2 x) *R v x) =\n   (\\<Sum>x\\<in>{v. f1 v \\<noteq> 0}. f1 x *R v x) +  (\\<Sum>x\\<in>{v. f2 v \\<noteq> 0}. f2 x *R v x)\"\nproof-\n  let ?A = \"{v. f1 v + f2 v \\<noteq> 0} \\<union> {v. f1 v + f2 v = 0 \\<and> (f1 v \\<noteq> 0 \\<or> f2 v \\<noteq> 0)}\"\n  have \"?A = {v. f1 v \\<noteq> 0 \\<or> f2 v \\<noteq> 0}\"\n    by auto\n  then have\n    \"finite ?A\"\n    using assms\n    by (subgoal_tac \"{v. f1 v \\<noteq> 0 \\<or> f2 v \\<noteq> 0} = {v. f1 v \\<noteq> 0} \\<union> {v. f2 v \\<noteq> 0}\") auto\n\n  then have \"(\\<Sum>x\\<in>{v. f1 v + f2 v \\<noteq> 0}. (f1 x + f2 x) *R v x) = \n    (\\<Sum>x\\<in>{v. f1 v + f2 v \\<noteq> 0} \\<union> {v. f1 v + f2 v = 0 \\<and> (f1 v \\<noteq> 0 \\<or> f2 v \\<noteq> 0)}. (f1 x + f2 x) *R v x)\"\n    by (rule sum.mono_neutral_left) auto\n  also have \"... = (\\<Sum>x \\<in> {v. f1 v \\<noteq> 0 \\<or> f2 v \\<noteq> 0}. (f1 x + f2 x) *R v x)\"\n    by (rule sum.cong) auto\n  also have \"... = (\\<Sum>x \\<in> {v. f1 v \\<noteq> 0 \\<or> f2 v \\<noteq> 0}. f1 x *R v x) + \n                   (\\<Sum>x \\<in> {v. f1 v \\<noteq> 0 \\<or> f2 v \\<noteq> 0}. f2 x *R v x)\"\n    by (simp add: scaleRat_left_distrib sum.distrib)\n  also have \"... = (\\<Sum>x\\<in>{v. f1 v \\<noteq> 0}. f1 x *R v x) +  (\\<Sum>x\\<in>{v. f2 v \\<noteq> 0}. f2 x *R v x)\"\n  proof-\n    {\n      fix f1 f2::\"'a \\<Rightarrow> rat\"\n      assume \"finite {v. f1 v \\<noteq> 0}\" \"finite {v. f2 v \\<noteq> 0}\"\n      then have \"finite {v. f1 v \\<noteq> 0 \\<or> f2 v \\<noteq> 0 \\<and> f1 v = 0}\"\n        by (subgoal_tac \"{v. f1 v \\<noteq> 0 \\<or> f2 v \\<noteq> 0} = {v. f1 v \\<noteq> 0} \\<union> {v. f2 v \\<noteq> 0}\") auto\n      have \"(\\<Sum>x\\<in>{v. f1 v \\<noteq> 0 \\<or> f2 v \\<noteq> 0}. f1 x *R v x) = \n        (\\<Sum>x\\<in>{v. f1 v \\<noteq> 0 \\<or> (f2 v \\<noteq> 0 \\<and> f1 v = 0)}. f1 x *R v x)\"\n        by auto\n      also have \"... = (\\<Sum>x\\<in>{v. f1 v \\<noteq> 0}. f1 x *R v x)\"\n        using \\<open>finite {v. f1 v \\<noteq> 0 \\<or> f2 v \\<noteq> 0 \\<and> f1 v = 0}\\<close>\n        by (rule sum.mono_neutral_left[THEN sym]) auto\n      ultimately have \"(\\<Sum>x\\<in>{v. f1 v \\<noteq> 0 \\<or> f2 v \\<noteq> 0}. f1 x *R v x) = \n        (\\<Sum>x\\<in>{v. f1 v \\<noteq> 0}. f1 x *R v x)\"\n        by simp\n    }\n    note * = this\n    show ?thesis\n      using assms\n      using *[of f1 f2]\n      using *[of f2 f1]\n      by (subgoal_tac \"{v. f2 v \\<noteq> 0 \\<or> f1 v \\<noteq> 0} = {v. f1 v \\<noteq> 0 \\<or> f2 v \\<noteq> 0}\") auto\n  qed\n  ultimately\n  show ?thesis by simp\nqed\n\nlemma valuate_add:  \"(p1 + p2) \\<lbrace>v\\<rbrace> = (p1 \\<lbrace>v\\<rbrace>) + (p2 \\<lbrace>v\\<rbrace>)\"\n  by (transfer, simp add: valuate_add_lemma)\n\nlemma valuate_minus: \"(p1 - p2) \\<lbrace>v\\<rbrace> = (p1 \\<lbrace>v\\<rbrace>) - (p2 \\<lbrace>v\\<rbrace>)\"\n  unfolding minus_linear_poly_def valuate_add \n  by (simp add: valuate_uminus)\n\n\nlemma valuate_scaleRat:\n  \"(c *R lp) \\<lbrace> v \\<rbrace> = c *R ( lp\\<lbrace>v\\<rbrace> )\"\nproof (cases \"c=0\")\n  case True\n  then show ?thesis\n    by (auto simp add: valuate_def zero_linear_poly_def Abs_linear_poly_inverse)\nnext\n  case False\n  then have \"\\<And> v. Rep_linear_poly (c *R lp) v = c * (Rep_linear_poly lp v)\"\n    unfolding scaleRat_linear_poly_def\n    using Abs_linear_poly_inverse[of \"\\<lambda>v. c * Rep_linear_poly lp v\"]\n    using Rep_linear_poly\n    by auto\n  then show ?thesis\n    unfolding valuate_def\n    using \\<open>c \\<noteq> 0\\<close>\n    by auto (subst rational_vector.scale_sum_right, auto)\nqed\n\nlemma valuate_Var: \"(Var x) \\<lbrace>v\\<rbrace> = v x\"\n  by transfer auto\n\nlemma valuate_sum: \"((\\<Sum>x\\<in>A. f x) \\<lbrace> v \\<rbrace>) = (\\<Sum>x\\<in>A. ((f x) \\<lbrace> v \\<rbrace>))\" \n  by (induct A rule: infinite_finite_induct, auto simp: valuate_zero valuate_add)\n\n\n\n\nlemma zero_coeff_zero: \"p = 0 \\<longleftrightarrow> (\\<forall> v. coeff p v = 0)\"\n  by transfer auto\n\nlemma all_val: \n  assumes \"\\<forall> (v::var \\<Rightarrow> 'a::lrv). \\<exists> v'. (\\<forall> x \\<in> vars p. v' x = v x) \\<and> (p \\<lbrace>v'\\<rbrace> = 0)\"\n  shows \"p = 0\"\nproof (subst zero_coeff_zero, rule allI)\n  fix x\n  show \"coeff p x = 0\"\n  proof (cases \"x \\<in> vars p\")\n    case False\n    then show ?thesis\n      using coeff_zero[of p x]\n      by simp\n  next\n    case True\n    have \"(0::'a::lrv) \\<noteq> (1::'a)\"\n      using zero_neq_one\n      by auto\n\n    let ?v = \"\\<lambda> x'. if x = x' then 1 else 0::'a\"\n    obtain v' where \"\\<forall> x \\<in> vars p. v' x = ?v x\" \"p \\<lbrace>v'\\<rbrace> = 0\"\n      using assms\n      by (erule_tac x=\"?v\" in allE) auto\n    then have \"\\<forall> x' \\<in> vars p. v' x' = (if x = x' then 1 else 0)\" \"p \\<lbrace>v'\\<rbrace> = 0\"\n      by auto\n\n    let ?fp = \"Rep_linear_poly p\"\n    have \"{x. ?fp x \\<noteq> 0 \\<and> v' x \\<noteq> (0 :: 'a)} = {x}\"\n      using \\<open>x \\<in> vars p\\<close> unfolding vars_def\n    proof (safe, simp_all)\n      fix x'\n      assume \"v' x' \\<noteq> 0\" \"Rep_linear_poly p x' \\<noteq> 0\"\n      then show \"x' = x\"\n        using \\<open>\\<forall> x' \\<in> vars p. v' x' = (if x = x' then 1 else 0)\\<close>\n        unfolding vars_def\n        by (erule_tac x=\"x'\" in ballE) (simp_all split: if_splits)\n    next\n      assume \"v' x = 0\" \"Rep_linear_poly p x \\<noteq> 0\"\n      then show False\n        using \\<open>\\<forall> x' \\<in> vars p. v' x' = (if x = x' then 1 else 0)\\<close>\n        using \\<open>0 \\<noteq> 1\\<close>\n        unfolding vars_def\n        by simp\n    qed\n\n    have \"p \\<lbrace>v'\\<rbrace> = (\\<Sum>x\\<in>{v. ?fp v \\<noteq> 0}. ?fp x *R v' x)\"\n      unfolding valuate_def\n      by auto\n    also have \"... = (\\<Sum>x\\<in>{v. ?fp v \\<noteq> 0 \\<and> v' v \\<noteq> 0}. ?fp x *R v' x)\"\n      apply (rule sum.mono_neutral_left[THEN sym])\n      using Rep_linear_poly[of p]\n      by auto\n    also have \"... = ?fp x *R v' x\"\n      using \\<open>{x. ?fp x \\<noteq> 0 \\<and> v' x \\<noteq> (0 :: 'a)} = {x}\\<close>\n      by simp\n    also have \"... = ?fp x *R 1\"\n      using \\<open>x \\<in> vars p\\<close>\n      using \\<open>\\<forall> x' \\<in> vars p. v' x' = (if x = x' then 1 else 0)\\<close>\n      by simp\n    ultimately\n    have \"p \\<lbrace>v'\\<rbrace> = ?fp x *R 1\"\n      by simp\n    then have \"coeff p x *R (1::'a)= 0\"\n      using \\<open>p \\<lbrace>v'\\<rbrace> = 0\\<close>\n      unfolding coeff_def\n      by simp\n    then show ?thesis\n      using rational_vector.scale_eq_0_iff\n      using \\<open>0 \\<noteq> 1\\<close>\n      by simp\n  qed\nqed\n\nlift_definition lp_monom :: \"rat \\<Rightarrow> var \\<Rightarrow> linear_poly\" is\n  \"\\<lambda> c x y. if x = y then c else 0\" by auto\n\nlemma valuate_lp_monom: \"((lp_monom c x) \\<lbrace>v\\<rbrace>) = c * (v x)\" \nproof (transfer, simp, goal_cases) \n  case (1 c x v)\n  have id: \"{v. x = v \\<and> (x = v \\<longrightarrow> c \\<noteq> 0)} = (if c = 0 then {} else {x})\" by auto\n  show ?case unfolding id\n    by (cases \"c = 0\", auto)\nqed\n\nlemma valuate_lp_monom_1[simp]: \"((lp_monom 1 x) \\<lbrace>v\\<rbrace>) = v x\"\n  by transfer simp \n\nlemma coeff_lp_monom [simp]:\n  shows \"coeff (lp_monom c v) v' = (if v = v' then c else 0)\"\n  by (transfer, auto)\n\nlemma vars_uminus [simp]: \"vars (-p) = vars p\"\n  unfolding uminus_linear_poly_def\n  by transfer auto\n\nlemma vars_plus [simp]: \"vars (p1 + p2) \\<subseteq> vars p1 \\<union> vars p2\"\n  by transfer auto\n\nlemma vars_minus [simp]: \"vars (p1 - p2) \\<subseteq> vars p1 \\<union> vars p2\"\n  unfolding minus_linear_poly_def\n  using vars_plus[of p1 \"-p2\"] vars_uminus[of p2]\n  by simp\n\nlemma vars_lp_monom: \"vars (lp_monom r x) = (if r = 0 then {} else {x})\" \n  by (transfer, auto)\n\nlemma vars_scaleRat1: \"vars (c *R p) \\<subseteq> vars p\"\n  by transfer auto\n\nlemma vars_scaleRat: \"c \\<noteq> 0 \\<Longrightarrow> vars(c *R p) = vars p\"\n  by transfer auto\n\nlemma vars_Var [simp]: \"vars (Var x) = {x}\"\n  by transfer auto\n\nlemma coeff_Var1 [simp]: \"coeff (Var x) x = 1\"\n  by transfer auto\n\nlemma coeff_Var2: \"x \\<noteq> y \\<Longrightarrow> coeff (Var x) y = 0\"\n  by transfer auto\n\nlemma valuate_depend:\n  assumes \"\\<forall> x \\<in> vars p. v x = v' x\"\n  shows \"(p \\<lbrace>v\\<rbrace>) = (p \\<lbrace>v'\\<rbrace>)\"\n  using assms\n  by transfer auto\n\nlemma valuate_update_x_lemma:\n  fixes v1 v2 :: \"'a::rational_vector valuation\"\n  assumes\n    \"\\<forall>y. f y \\<noteq> 0 \\<longrightarrow> y \\<noteq> x \\<longrightarrow> v1 y = v2 y\"\n    \"finite {v. f v \\<noteq> 0}\"\n  shows\n    \"(\\<Sum>x\\<in>{v. f v \\<noteq> 0}. f x *R v1 x) + f x *R (v2 x - v1 x) = (\\<Sum>x\\<in>{v. f v \\<noteq> 0}. f x *R v2 x)\"\nproof (cases \"f x = 0\")\n  case True\n  then have \"\\<forall>y. f y \\<noteq> 0 \\<longrightarrow> v1 y = v2 y\"\n    using assms(1) by auto\n  then show ?thesis using \\<open>f x = 0\\<close> by auto\nnext\n  case False\n  let ?A = \"{v. f v \\<noteq> 0}\" and ?Ax = \"{v. v \\<noteq> x \\<and> f v \\<noteq> 0}\"\n  have \"?A = ?Ax \\<union> {x}\"\n    using \\<open>f x \\<noteq> 0\\<close> by auto\n  then have \"(\\<Sum>x\\<in>?A. f x *R v1 x) = f x *R v1 x + (\\<Sum>x\\<in>?Ax. f x *R v1 x)\"\n    \"(\\<Sum>x\\<in>?A. f x *R v2 x) = f x *R v2 x + (\\<Sum>x\\<in>?Ax. f x *R v2 x)\"\n    using assms(2) by auto\n  moreover\n  have \"\\<forall> y \\<in> ?Ax. v1 y = v2 y\"\n    using assms by auto\n  moreover\n  have \"f x *R v1 x + f x *R (v2 x - v1 x) = f x *R v2 x\"\n    by (subst rational_vector.scale_right_diff_distrib) auto\n  ultimately\n  show ?thesis by simp\nqed\n\nlemma valuate_update_x:\n  fixes v1 v2 :: \"'a::rational_vector valuation\"\n  assumes \"\\<forall>y \\<in> vars lp. y\\<noteq>x \\<longrightarrow> v1 y = v2 y\"\n  shows \"lp \\<lbrace>v1\\<rbrace>  + coeff lp x *R (v2 x - v1 x) = (lp \\<lbrace>v2\\<rbrace>)\"\n  using assms \n  unfolding valuate_def vars_def coeff_def\n  using valuate_update_x_lemma[of \"Rep_linear_poly lp\" x v1 v2] Rep_linear_poly\n  by auto\n\nlemma vars_zero: \"vars 0 = {}\"\n  using zero_coeff_zero coeff_zero by auto\n\nlemma vars_empty_zero: \"vars lp = {} \\<longleftrightarrow> lp = 0\"\n  using zero_coeff_zero coeff_zero by auto\n\ndefinition max_var:: \"linear_poly \\<Rightarrow> var\" where\n  \"max_var lp \\<equiv> if lp = 0 then 0 else Max (vars lp)\"\n\nlemma max_var_max:\n  assumes \"a \\<in> vars lp\"\n  shows \"max_var lp \\<ge> a\"\n  using assms\n  by (auto simp add: finite_vars max_var_def vars_zero)\n\nlemma max_var_code[code]: \n  \"max_var lp = (let vl = vars_list lp \n                in if vl = [] then 0 else foldl max (hd vl) (tl vl))\"\nproof (cases \"lp = (0::linear_poly)\")\n  case True\n  then show ?thesis\n    using set_vars_list[of lp]\n    by (auto simp add: max_var_def vars_zero)\nnext\n  case False\n  then show ?thesis\n    using set_vars_list[of lp, THEN sym]\n    using vars_empty_zero[of lp]\n    unfolding max_var_def Let_def \n    using Max.set_eq_fold[of \"hd (vars_list lp)\" \"tl (vars_list lp)\"]\n    by (cases \"vars_list lp\", auto simp: foldl_conv_fold intro!: fold_cong)\nqed\n\ndefinition monom_var:: \"linear_poly \\<Rightarrow> var\" where\n  \"monom_var l = max_var l\"\n\ndefinition monom_coeff:: \"linear_poly \\<Rightarrow> rat\" where\n  \"monom_coeff l = coeff l (monom_var l)\"\n\ndefinition is_monom :: \"linear_poly \\<Rightarrow> bool\" where\n  \"is_monom l \\<longleftrightarrow> length (vars_list l) = 1\"\n\nlemma is_monom_vars_not_empty:\n  \"is_monom l \\<Longrightarrow> vars l \\<noteq> {}\"\n  by (auto simp add: is_monom_def vars_list_def) (auto simp add: vars_def)\n\nlemma monom_var_in_vars:\n  \"is_monom l \\<Longrightarrow> monom_var l \\<in> vars l\"\n  using vars_zero\n  by (auto simp add: monom_var_def max_var_def is_monom_vars_not_empty finite_vars is_monom_def)\n\nlemma zero_is_no_monom[simp]: \"\\<not> is_monom 0\"\n  using is_monom_vars_not_empty vars_zero by blast\n\nlemma is_monom_monom_coeff_not_zero:\n  \"is_monom l \\<Longrightarrow> monom_coeff l \\<noteq> 0\"\n  by (simp add: coeff_zero monom_var_in_vars monom_coeff_def)\n\nlemma list_two_elements:\n  \"\\<lbrakk>y \\<in> set l; x \\<in> set l; length l = Suc 0; y \\<noteq> x\\<rbrakk> \\<Longrightarrow> False\"\n  by (induct l) auto\n\nlemma is_monom_vars_monom_var:\n  assumes \"is_monom l\"\n  shows \"vars l = {monom_var l}\"\nproof-\n  have \"\\<And>x. \\<lbrakk>is_monom l; x \\<in> vars l\\<rbrakk> \\<Longrightarrow> monom_var l = x\"\n  proof-\n    fix x\n    assume \"is_monom l\" \"x \\<in> vars l\"\n    then have \"x \\<in> set (vars_list l)\"\n      using finite_vars\n      by (auto simp add: vars_list_def vars_def)\n    show \"monom_var l = x\"\n    proof(rule ccontr)\n      assume \"monom_var l \\<noteq> x\"\n      then have \"\\<exists>y. monom_var l = y \\<and> y \\<noteq> x\"\n        by simp\n      then obtain y where \"monom_var l = y\" \"y \\<noteq> x\"\n        by auto\n      then have \"Rep_linear_poly l y \\<noteq> 0\"\n        using monom_var_in_vars \\<open>is_monom l\\<close>\n        by (auto simp add: vars_def)\n      then have \"y \\<in> set (vars_list l)\"\n        using finite_vars\n        by (auto simp add: vars_def vars_list_def)\n      then show False\n        using \\<open>x \\<in> set (vars_list l)\\<close> \\<open>is_monom l\\<close> \\<open>y \\<noteq> x\\<close>\n        using list_two_elements\n        by (simp add: is_monom_def)\n    qed\n  qed\n  then show \"vars l = {monom_var l}\"\n    using assms\n    by (auto simp add: monom_var_in_vars)\nqed\n\nlemma monom_valuate:\n  assumes \"is_monom m\"\n  shows \"m\\<lbrace>v\\<rbrace> = (monom_coeff m) *R v (monom_var m)\"\n  using assms\n  using is_monom_vars_monom_var\n  by (simp add: vars_def coeff_def monom_coeff_def valuate_def)\n\nlemma coeff_zero_simp [simp]:\n  \"coeff 0 v = 0\"\n  using zero_coeff_zero by blast\n\nlemma poly_eq_iff: \"p = q \\<longleftrightarrow> (\\<forall> v. coeff p v = coeff q v)\"\n  by transfer auto\n\nlemma poly_eqI:\n  assumes \"\\<And>v. coeff p v = coeff q v\"\n  shows \"p = q\"\n  using assms poly_eq_iff by simp\n\nlemma coeff_sum_list:\n  assumes \"distinct xs\"\n  shows \"coeff (\\<Sum>x\\<leftarrow>xs. f x *R lp_monom 1 x) v = (if v \\<in> set xs then f v else 0)\"\n  using assms by (induction xs) auto\n\nlemma linear_poly_sum:\n  \"p \\<lbrace> v \\<rbrace> = (\\<Sum>x\\<in>vars p. coeff p x *R v x)\"\n  by transfer simp\n\nlemma all_valuate_zero: assumes \"\\<And>(v::'a::lrv valuation). p \\<lbrace>v\\<rbrace> = 0\"\n  shows \"p = 0\"\n  using all_val assms by blast\n\nlemma linear_poly_eqI: assumes \"\\<And>(v::'a::lrv valuation). (p \\<lbrace>v\\<rbrace>) = (q \\<lbrace>v\\<rbrace>)\"\n  shows \"p = q\"\n  using assms \nproof -\n  have \"(p - q) \\<lbrace> v \\<rbrace> = 0\" for v::\"'a::lrv valuation\"\n    using assms by (subst valuate_minus) auto\n  then have \"p - q = 0\"\n    by (intro all_valuate_zero) auto\n  then show ?thesis\n    by simp\nqed\n\nlemma monom_poly_assemble:\n  assumes \"is_monom p\"\n  shows \"monom_coeff p *R lp_monom 1 (monom_var p) = p\"\n  by (simp add: assms linear_poly_eqI monom_valuate valuate_scaleRat)\n\nlemma coeff_sum: \"coeff (sum (f :: _ \\<Rightarrow> linear_poly) is) x = sum (\\<lambda> i. coeff (f i) x) is\" \n  by (induct \"is\" rule: infinite_finite_induct, 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/Simplex/Abstract_Linear_Poly.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8856314677809304, "lm_q2_score": 0.8333245911726382, "lm_q1q2_score": 0.7380184808181673}}
{"text": "theory week08B_demo \nimports \"~~/src/HOL/Hoare/HeapSyntax\" \nbegin\n\n\nprimrec\n  fac :: \"nat \\<Rightarrow> nat\"\nwhere\n  \"fac 0 = 1\"\n| \"fac (Suc n) = (Suc n) * fac n\"\n\n\nlemma \"VARS B { True } B := x { B = x }\"\n  apply vcg\n  done\n  \nlemma \n  \" VARS (x::nat) y r \n    {True} \n    IF x>y THEN r:=x ELSE r:=y FI\n    {r \\<ge> x \\<and> r \\<ge>y \\<and> (r=x \\<or> r=y)}\"\n  apply vcg\n  apply simp\n  done\n  \nlemma\n  \"VARS (A::int) B \n   { A = 0 \\<and> B = 0 }\n    WHILE A \\<noteq> a\n    INV { B = A * b } DO\n      B := B + b; \n      A := A + 1\n    OD\n    {B = a * b }\"\n  apply vcg \n    apply simp\n   apply clarsimp\n   apply (simp add: semiring_normalization_rules(2))\n  apply simp\n  done\n  \nlemma factorial_sound:\n  \"VARS A B\n  { A = n}\n  B := 1;\n  WHILE A \\<noteq> 0 INV { fac n = B * fac A } DO\n    B := B * A;\n    A := A - 1\n  OD\n  { B = fac n }\"\n  apply (vcg; clarsimp)\n  apply (case_tac A; simp)\n  done\n\n\n\n-- ----------------------------------------------------------------------------------\n\n-- \"Arrays\"\n\n(* define a program that looks for a key in an array *)\n(*think about the loop invariant *)\n\nlemma\n \"VARS I L \n { True }\n  I := 0;\n  WHILE I < length L \\<and> L!I \\<noteq> key \n  INV { I \\<le> length L \\<and> (\\<forall>j < I. L!j \\<noteq> key)} DO\n    I := I+1 \n  OD\n  { (I < length L \\<longrightarrow> L!I = key) \\<and> (I=length L \\<longrightarrow> key \\<notin> set L)}\"\n  apply (vcg)\n    apply clarsimp\n   apply clarsimp\n   apply (case_tac \"I = j\"; simp?)\n   apply (metis linorder_neqE_nat not_less_eq)\n  apply clarsimp\n  apply (clarsimp simp: in_set_conv_nth)\n  apply auto\n  done\n\n\n-- \"Pointers\"\nthm List_def Path.simps\n\n(* \"List nxt p Ps\" represents a linked list, starting\n    at pointer p, with 'nxt' being the function to find\n    the next pointer, and Ps the list of all the content\n    of the linked list *)\n\n(* define a function that takes X, p and nxt function,\n   assuming that X is in the set of the linked list,\n   then it returns the pointer to that element *)\n\n(* think about its loop invariant *)\n\n\nlemma \"VARS nxt p\n  { List nxt p Ps \\<and> X \\<in> set Ps }\n  WHILE p \\<noteq> Null \\<and> p \\<noteq> Ref X  INV { \\<exists>xs. Path nxt p xs (Ref X) }\n  DO p := p^.nxt OD\n  { p = Ref X }\"\n  apply vcg\n    apply (clarsimp simp: List_def)\n    apply (clarsimp simp: in_set_conv_decomp)\n    apply auto\n  done\n\n\n\n(* define a function that \"splices\" 2 disjoint linked lists together *)\n\n(* think about its loop invariant *)\n\nlemma \"VARS tl p q pp qq\n  {List tl p Ps \\<and> List tl q Qs \\<and> set Ps \\<inter> set Qs = {} \\<and> size Qs \\<le> size Ps}\n  pp := p;\n  WHILE q \\<noteq> Null\n  INV { TODO }\n  DO qq := q^.tl; q^.tl := pp^.tl; pp^.tl := q; pp := q^.tl; q := qq OD\n  {List tl p (splice Ps Qs)}\"\n  sorry\n\nend", "meta": {"author": "z5146542", "repo": "TOR", "sha": "9a82d491288a6d013e0764f68e602a63e48f92cf", "save_path": "github-repos/isabelle/z5146542-TOR", "path": "github-repos/isabelle/z5146542-TOR/TOR-9a82d491288a6d013e0764f68e602a63e48f92cf/181206/week08B_demo.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942319436397, "lm_q2_score": 0.82893881677331, "lm_q1q2_score": 0.7379994472074635}}
{"text": "section \\<open>Isomorphisms of Free Groups\\<close>\n\ntheory \"Isomorphisms\"\nimports\n   UnitGroup\n   \"HOL-Algebra.IntRing\"\n   FreeGroups\n   C2\n   \"HOL-Cardinals.Cardinal_Order_Relation\"\nbegin\n\nsubsection \\<open>The Free Group over the empty set\\<close>\n\ntext \\<open>The Free Group over an empty set of generators is isomorphic to the trivial\ngroup.\\<close>\n\nlemma free_group_over_empty_set: \"\\<exists>h. h \\<in> iso \\<F>\\<^bsub>{}\\<^esub> unit_group\"\nproof(rule group.unit_group_unique)\n  show \"group \\<F>\\<^bsub>{}\\<^esub>\" by (rule free_group_is_group)\nnext\n  have \"carrier \\<F>\\<^bsub>{}::'a set\\<^esub> = {[]}\"\n    by (auto simp add:free_group_def)\n  thus \"card (carrier \\<F>\\<^bsub>{}::'a set\\<^esub>) = 1\"\n    by simp\nqed\n\nsubsection \\<open>The Free Group over one generator\\<close>\n\ntext \\<open>The Free Group over one generator is isomorphic to the free abelian group\nover one element, also known as the integers.\\<close>\n\nabbreviation \"int_group\"\n  where \"int_group \\<equiv> \\<lparr> carrier = carrier \\<Z>, monoid.mult = (+), one = 0::int \\<rparr>\"\n\nlemma replicate_set_eq[simp]: \"\\<forall>x \\<in> set xs. x = y \\<Longrightarrow> xs = replicate (length xs) y\"\n  by(induct xs)auto\n\nlemma int_group_gen_by_one: \"\\<langle>{1}\\<rangle>\\<^bsub>int_group\\<^esub> = carrier int_group\"\nproof\n  show \"\\<langle>{1}\\<rangle>\\<^bsub>int_group\\<^esub> \\<subseteq> carrier int_group\"\n    by auto\n  show \"carrier int_group \\<subseteq> \\<langle>{1}\\<rangle>\\<^bsub>int_group\\<^esub>\"\n  proof\n    interpret int: group int_group\n      using int.a_group by auto\n    fix x\n    have plus1: \"1 \\<in> \\<langle>{1}\\<rangle>\\<^bsub>int_group\\<^esub>\"\n      by (auto intro:gen_span.gen_gens)\n    hence \"inv\\<^bsub>int_group\\<^esub> 1 \\<in> \\<langle>{1}\\<rangle>\\<^bsub>int_group\\<^esub>\"\n      by (auto intro:gen_span.gen_inv)\n    moreover\n    have \"-1 = inv\\<^bsub>int_group\\<^esub> 1\" \n      by (rule sym, rule int.inv_equality) simp_all\n    ultimately\n    have minus1: \"-1 \\<in> \\<langle>{1}\\<rangle>\\<^bsub>int_group\\<^esub>\"\n      by (simp)\n\n    show \"x \\<in> \\<langle>{1::int}\\<rangle>\\<^bsub>int_group\\<^esub>\" (*\n    It does not work directly, unfortunately:\n    apply(induct x rule:int_induct[of _ \"0::int\"])\n    apply (auto simp add: int_arith_rules intro:gen_span.intros[of int_group])\n    *)\n    proof(induct x rule:int_induct[of _ \"0::int\"])\n    case base\n      have \"\\<one>\\<^bsub>int_group\\<^esub> \\<in> \\<langle>{1::int}\\<rangle>\\<^bsub>int_group\\<^esub>\"\n        by (rule gen_span.gen_one)\n      thus\"0 \\<in> \\<langle>{1}\\<rangle>\\<^bsub>int_group\\<^esub>\"\n        by simp\n    next\n    case (step1 i)\n      from \\<open>i \\<in> \\<langle>{1}\\<rangle>\\<^bsub>int_group\\<^esub>\\<close> and plus1\n      have \"i \\<otimes>\\<^bsub>int_group\\<^esub> 1 \\<in> \\<langle>{1}\\<rangle>\\<^bsub>int_group\\<^esub>\" \n        by (rule gen_span.gen_mult)\n      thus \"i + 1 \\<in> \\<langle>{1}\\<rangle>\\<^bsub>int_group\\<^esub>\" by simp\n    next\n    case (step2 i)\n      from \\<open>i \\<in> \\<langle>{1}\\<rangle>\\<^bsub>int_group\\<^esub>\\<close> and minus1\n      have \"i \\<otimes>\\<^bsub>int_group\\<^esub> -1 \\<in> \\<langle>{1}\\<rangle>\\<^bsub>int_group\\<^esub>\" \n        by (rule gen_span.gen_mult)\n      thus \"i - 1 \\<in> \\<langle>{1}\\<rangle>\\<^bsub>int_group\\<^esub>\"\n        by simp\n    qed\n  qed\nqed\n\nlemma free_group_over_one_gen: \"\\<exists>h. h \\<in> iso \\<F>\\<^bsub>{()}\\<^esub> int_group\"\nproof-\n  interpret int: group int_group \n    using int.a_group by auto\n  define f :: \"unit \\<Rightarrow> int\" where \"f x = 1\" for x\n  have \"f \\<in> {()} \\<rightarrow> carrier int_group\"\n    by auto\n  hence \"int.lift f \\<in> hom \\<F>\\<^bsub>{()}\\<^esub> int_group\"\n    by (rule int.lift_is_hom)\n  then\n  interpret hom: group_hom \"\\<F>\\<^bsub>{()}\\<^esub>\" int_group \"int.lift f\"\n    unfolding group_hom_def group_hom_axioms_def\n    using int.a_group by(auto intro: free_group_is_group)\n    \n  { (* This shows injectiveness of the given map *)\n    fix x\n    assume \"x \\<in> carrier \\<F>\\<^bsub>{()}\\<^esub>\"\n    hence \"canceled x\" by (auto simp add:free_group_def)\n    assume \"int.lift f x = (0::int)\"\n    have \"x = []\" \n    proof(rule ccontr)\n      assume \"x \\<noteq> []\"\n      then obtain a and xs where \"x = a # xs\" by (cases x, auto)\n      hence \"length (takeWhile (\\<lambda>y. y = a) x) > 0\" by auto\n      then obtain i where i: \"length (takeWhile (\\<lambda>y. y = a) x) = Suc i\" \n        by (cases \"length (takeWhile (\\<lambda>y. y = a) x)\", auto)\n      have \"Suc i \\<ge> length x\"\n      proof(rule ccontr)\n        assume \"\\<not> length x \\<le> Suc i\"\n        hence \"length (takeWhile (\\<lambda>y. y = a) x) < length x\" using i by simp\n        hence \"\\<not> (\\<lambda>y. y = a) (x ! length (takeWhile (\\<lambda>y. y = a) x))\"\n          by (rule nth_length_takeWhile)\n        hence \"\\<not> (\\<lambda>y. y = a) (x ! Suc i)\" using i by simp\n        hence \"fst (x ! Suc i) \\<noteq> fst a\" by (cases \"x ! Suc i\", cases \"a\", auto)\n        moreover\n        {\n          have \"takeWhile (\\<lambda>y. y = a) x ! i = x ! i\"\n            using i by (auto intro: takeWhile_nth)\n          moreover\n          have \"(takeWhile (\\<lambda>y. y = a) x) ! i \\<in> set (takeWhile (\\<lambda>y. y = a) x)\"\n            using i by auto\n          ultimately\n          have \"(\\<lambda>y. y = a) (x ! i)\"\n            by (auto dest:set_takeWhileD)\n        }\n        hence \"fst (x ! i) = fst a\" by auto\n        moreover\n        have \"snd (x ! i) = snd (x ! Suc i)\" by simp\n        ultimately\n        have \"canceling (x ! i) (x ! Suc i)\" unfolding canceling_def by auto\n        hence \"cancels_to_1_at i x (cancel_at i x)\"\n          using \\<open>\\<not> length x \\<le> Suc i\\<close> unfolding cancels_to_1_at_def \n          by (auto simp add:length_takeWhile_le)\n        hence \"cancels_to_1 x (cancel_at i x)\" unfolding cancels_to_1_def by auto\n        hence \"\\<not> canceled x\" unfolding canceled_def by auto\n        thus False using \\<open>canceled x\\<close> by contradiction\n      qed\n      hence \"length (takeWhile (\\<lambda>y. y = a) x) = length x\"\n        using i[THEN sym] by (auto dest:le_antisym simp add:length_takeWhile_le)\n      hence \"takeWhile (\\<lambda>y. y = a) x = x\"\n        by (subst takeWhile_eq_take, simp)\n      moreover\n      have \"\\<forall>y \\<in> set (takeWhile (\\<lambda>y. y = a) x). y = a\"\n        by (auto dest: set_takeWhileD)\n      ultimately\n      have \"\\<forall>y \\<in> set x. y = a\" by auto\n      hence \"x = replicate (length x) a\" by simp\n      hence \"int.lift f x = int.lift f (replicate (length x) a)\" by simp\n      also have \"... = pow int_group (int.lift_gi f a) (length x)\"\n        apply (induct x)\n        using local.int.nat_pow_Suc local.int.nat_pow_0\n         apply (auto simp: int.lift_def [simplified])\n        done\n      also have \"... = (int.lift_gi f a) * int (length x)\"\n        apply (induct x)\n        using local.int.nat_pow_Suc local.int.nat_pow_0\n        by (auto simp: int_distrib)\n      finally have \"\\<dots> = 0\" using \\<open>int.lift f x = 0\\<close> by simp\n      hence \"nat (abs (group.lift_gi int_group f a * int (length x))) = 0\" by simp\n      hence \"nat (abs (group.lift_gi int_group f a)) * length x = 0\" by simp\n      hence \"nat (abs (group.lift_gi int_group f a)) = 0\"\n        using \\<open>x \\<noteq> []\\<close> by auto\n      moreover\n      have \"inv\\<^bsub>int_group\\<^esub> 1 = -1\" \n        using int.inv_equality by auto\n      hence \"abs (group.lift_gi int_group f a) = 1\"\n      using int.is_group\n        by(auto simp add: group.lift_gi_def f_def)\n      ultimately\n      show False by simp\n    qed\n  }\n  hence \"\\<forall>x\\<in>carrier \\<F>\\<^bsub>{()}\\<^esub>. int.lift f x = \\<one>\\<^bsub>int_group\\<^esub> \\<longrightarrow> x = \\<one>\\<^bsub>\\<F>\\<^bsub>{()}\\<^esub>\\<^esub>\"\n    by (auto simp add:free_group_def)\n  moreover\n  {\n    have \"carrier \\<F>\\<^bsub>{()}\\<^esub> = \\<langle>insert`{()}\\<rangle>\\<^bsub>\\<F>\\<^bsub>{()}\\<^esub>\\<^esub>\"\n      by (rule gens_span_free_group[THEN sym])\n    moreover\n    have \"carrier int_group = \\<langle>{1}\\<rangle>\\<^bsub>int_group\\<^esub>\"\n      by (rule int_group_gen_by_one[THEN sym])\n    moreover\n    have \"int.lift f ` insert ` {()} = {1}\"\n      by (auto simp add: int.lift_def [simplified] insert_def f_def int.lift_gi_def [simplified])\n    moreover\n    have  \"int.lift f ` \\<langle>insert`{()}\\<rangle>\\<^bsub>\\<F>\\<^bsub>{()}\\<^esub>\\<^esub> = \\<langle>int.lift f ` (insert `{()})\\<rangle>\\<^bsub>int_group\\<^esub>\"\n      by (rule hom.hom_span, auto intro:insert_closed)\n    ultimately\n    have \"int.lift f ` carrier \\<F>\\<^bsub>{()}\\<^esub> = carrier int_group\"\n      by simp\n  }\n  ultimately\n  have \"int.lift f \\<in> iso \\<F>\\<^bsub>{()}\\<^esub> int_group\"\n    using \\<open>int.lift f \\<in> hom \\<F>\\<^bsub>{()}\\<^esub> int_group\\<close>\n    using hom.hom_mult int.is_group\n    by (auto intro:group_isoI simp add: free_group_is_group)\n  thus ?thesis by auto\nqed\n\nsubsection \\<open>Free Groups over isomorphic sets of generators\\<close>\n\ntext \\<open>Free Groups are isomorphic if their set of generators are isomorphic.\\<close>\n\ndefinition lift_generator_function :: \"('a \\<Rightarrow> 'b) \\<Rightarrow> (bool \\<times> 'a) list \\<Rightarrow> (bool \\<times> 'b) list\"\nwhere \"lift_generator_function f = map (map_prod id f)\"\n\ntheorem isomorphic_free_groups:\n  assumes \"bij_betw f gens1 gens2\"\n  shows \"lift_generator_function f \\<in> iso \\<F>\\<^bsub>gens1\\<^esub> \\<F>\\<^bsub>gens2\\<^esub>\"\nunfolding lift_generator_function_def\nproof(rule group_isoI)\n  show \"\\<forall>x\\<in>carrier \\<F>\\<^bsub>gens1\\<^esub>.\n       map (map_prod id f) x = \\<one>\\<^bsub>\\<F>\\<^bsub>gens2\\<^esub>\\<^esub> \\<longrightarrow> x = \\<one>\\<^bsub>\\<F>\\<^bsub>gens1\\<^esub>\\<^esub>\"\n    by(auto simp add:free_group_def)\nnext\n  from \\<open>bij_betw f gens1 gens2\\<close> have \"inj_on f gens1\" by (auto simp:bij_betw_def)\n  show \"map (map_prod id f) ` carrier \\<F>\\<^bsub>gens1\\<^esub> = carrier \\<F>\\<^bsub>gens2\\<^esub>\"\n  proof(rule Set.set_eqI,rule iffI)\n    from \\<open>bij_betw f gens1 gens2\\<close> have \"f ` gens1 = gens2\" by (auto simp:bij_betw_def)\n    fix x :: \"(bool \\<times> 'b) list\"\n    assume \"x \\<in> image (map (map_prod id f)) (carrier \\<F>\\<^bsub>gens1\\<^esub>)\"\n    then obtain y :: \"(bool \\<times> 'a) list\" where \"x = map (map_prod id f) y\"\n                    and \"y \\<in> carrier \\<F>\\<^bsub>gens1\\<^esub>\" by auto\n    from \\<open>y \\<in> carrier \\<F>\\<^bsub>gens1\\<^esub>\\<close>\n    have \"canceled y\" and \"y \\<in> lists(UNIV\\<times>gens1)\" by (auto simp add:free_group_def)\n\n    from \\<open>y \\<in> lists (UNIV\\<times>gens1)\\<close>\n      and \\<open>x = map (map_prod id f) y\\<close>\n      and \\<open>image f gens1 = gens2\\<close>\n    have \"x \\<in> lists (UNIV\\<times>gens2)\"\n      by (auto iff:lists_eq_set)\n    moreover\n\n    from \\<open>x = map (map_prod id f) y\\<close>\n     and \\<open>y \\<in> lists (UNIV\\<times>gens1)\\<close>\n     and \\<open>canceled y\\<close>\n     and \\<open>inj_on f gens1\\<close>\n    have \"canceled x\"\n      by (auto intro!:rename_gens_canceled subset_inj_on[OF \\<open>inj_on f gens1\\<close>] iff:lists_eq_set)\n    ultimately\n    show \"x \\<in> carrier \\<F>\\<^bsub>gens2\\<^esub>\" by (simp add:free_group_def)\n  next\n    fix x\n    assume \"x \\<in> carrier \\<F>\\<^bsub>gens2\\<^esub>\"\n    hence \"canceled x\" and \"x \\<in> lists (UNIV\\<times>gens2)\"\n      unfolding free_group_def by auto\n    define y where \"y = map (map_prod id (the_inv_into gens1 f)) x\"\n    have \"map (map_prod id f) y =\n          map (map_prod id f) (map (map_prod id (the_inv_into gens1 f)) x)\"\n      by (simp add:y_def)\n    also have \"\\<dots> = map (map_prod id f \\<circ> map_prod id (the_inv_into gens1 f)) x\"\n      by simp\n    also have \"\\<dots> = map (map_prod id (f \\<circ> the_inv_into gens1 f)) x\"\n      by auto\n    also have \"\\<dots> = map id x\"\n    proof(rule map_ext, rule impI)\n      fix xa :: \"bool \\<times> 'b\"\n      assume \"xa \\<in> set x\"\n      from \\<open>x \\<in> lists (UNIV\\<times>gens2)\\<close>\n      have \"set (map snd x) \\<subseteq> gens2\"  by auto\n      hence \"snd ` set x \\<subseteq> gens2\" by (simp add: set_map)\n      with \\<open>xa \\<in> set x\\<close> have \"snd xa \\<in> gens2\" by auto\n      with \\<open>bij_betw f gens1 gens2\\<close> have \"snd xa \\<in> f`gens1\"\n        by (auto simp add: bij_betw_def)\n\n      have \"map_prod id (f \\<circ> the_inv_into gens1 f) xa\n            = map_prod id (f \\<circ> the_inv_into gens1 f) (fst xa, snd xa)\" by simp\n      also have \"\\<dots> = (fst xa, f (the_inv_into gens1 f (snd xa)))\"\n        by (auto simp del:prod.collapse)\n      also\n      from \\<open>snd xa \\<in> image f gens1\\<close> and \\<open>inj_on f gens1\\<close>\n      have \"\\<dots> = (fst xa, snd xa)\"\n        by (auto elim:f_the_inv_into_f simp del:prod.collapse)\n      also have \"\\<dots> = id xa\" by simp\n      finally show \"map_prod id (f \\<circ> the_inv_into gens1 f) xa = id xa\".\n    qed\n    also have \"\\<dots> = x\" unfolding id_def by auto\n    finally have \"map (map_prod id f) y = x\".\n    moreover\n    {\n      from \\<open>bij_betw f gens1 gens2\\<close>\n      have \"bij_betw (the_inv_into gens1 f) gens2 gens1\" by (rule bij_betw_the_inv_into)\n      hence \"inj_on (the_inv_into gens1 f) gens2\" by (rule bij_betw_imp_inj_on)\n\n      with \\<open>canceled x\\<close>      \n       and \\<open>x \\<in> lists (UNIV\\<times>gens2)\\<close>\n      have \"canceled y\"\n        by (auto intro!:rename_gens_canceled[OF subset_inj_on] simp add:y_def)\n      moreover\n      {\n        from \\<open>bij_betw (the_inv_into gens1 f) gens2 gens1\\<close>\n         and \\<open>x\\<in>lists(UNIV\\<times>gens2)\\<close>\n        have \"y \\<in> lists(UNIV\\<times>gens1)\"\n          unfolding y_def and bij_betw_def\n          by (auto iff:lists_eq_set dest!:subsetD)\n      }\n      ultimately\n      have \"y \\<in> carrier \\<F>\\<^bsub>gens1\\<^esub>\" by (simp add:free_group_def)\n    }\n    ultimately\n    show \"x \\<in> map (map_prod id f) ` carrier \\<F>\\<^bsub>gens1\\<^esub>\" by auto\n  qed\nnext\n  from \\<open>bij_betw f gens1 gens2\\<close> have \"inj_on f gens1\" by (auto simp:bij_betw_def)\n  {\n  fix x\n  assume \"x \\<in> carrier \\<F>\\<^bsub>gens1\\<^esub>\"\n  fix y\n  assume \"y \\<in> carrier \\<F>\\<^bsub>gens1\\<^esub>\"\n\n  from \\<open>x \\<in> carrier \\<F>\\<^bsub>gens1\\<^esub>\\<close> and \\<open>y \\<in> carrier \\<F>\\<^bsub>gens1\\<^esub>\\<close>\n  have \"x \\<in> lists(UNIV\\<times>gens1)\" and \"y \\<in> lists(UNIV\\<times>gens1)\"\n    by (auto simp add:occuring_gens_in_element)\n(*  hence \"occuring_generators (x@y) \\<subseteq> gens1\"\n    by(auto simp add:occuring_generators_def)\n  with `inj_on f gens1` have \"inj_on f (occuring_generators (x@y))\"\n    by (rule subset_inj_on) *)\n\n  have \"map (map_prod id f) (x \\<otimes>\\<^bsub>\\<F>\\<^bsub>gens1\\<^esub>\\<^esub> y)\n       = map (map_prod id f) (normalize (x@y))\" by (simp add:free_group_def)\n  also (* from `inj_on f (occuring_generators (x@y))` *)\n       from \\<open>x \\<in> lists(UNIV\\<times>gens1)\\<close> and \\<open>y \\<in> lists(UNIV\\<times>gens1)\\<close>\n        and \\<open>inj_on f gens1\\<close>\n       have \"\\<dots> = normalize (map (map_prod id f) (x@y))\"\n         by -(rule rename_gens_normalize[THEN sym],\n              auto intro!: subset_inj_on[OF \\<open>inj_on f gens1\\<close>] iff:lists_eq_set)\n  also have \"\\<dots> = normalize (map (map_prod id f) x @ map (map_prod id f) y)\"\n       by (auto)\n  also have \"\\<dots> = map (map_prod id f) x \\<otimes>\\<^bsub>\\<F>\\<^bsub>gens2\\<^esub>\\<^esub> map (map_prod id f) y\"\n       by (simp add:free_group_def)\n  finally have \"map (map_prod id f) (x \\<otimes>\\<^bsub>\\<F>\\<^bsub>gens1\\<^esub>\\<^esub> y) =\n                map (map_prod id f) x \\<otimes>\\<^bsub>\\<F>\\<^bsub>gens2\\<^esub>\\<^esub> map (map_prod id f) y\".\n  }\n  thus \"\\<forall>x\\<in>carrier \\<F>\\<^bsub>gens1\\<^esub>.\n       \\<forall>y\\<in>carrier \\<F>\\<^bsub>gens1\\<^esub>.\n          map (map_prod id f) (x \\<otimes>\\<^bsub>\\<F>\\<^bsub>gens1\\<^esub>\\<^esub> y) =\n          map (map_prod id f) x \\<otimes>\\<^bsub>\\<F>\\<^bsub>gens2\\<^esub>\\<^esub> map (map_prod id f) y\"\n   by auto\nqed (auto intro: free_group_is_group)\n\nsubsection \\<open>Bases of isomorphic free groups\\<close>\n\ntext \\<open>\nIsomorphic free groups have bases of same cardinality. The proof is very different\nfor infinite bases and for finite bases.\n\nThe proof for the finite case uses the set of of homomorphisms from the free\ngroup to the group with two elements, as suggested by Christian Sievers. The\ndefinition of @{term hom} is not suitable for proofs about the cardinality of that\nset, as its definition does not require extensionality. This is amended by the\nfollowing definition:\n\\<close>\n\ndefinition homr\n  where \"homr G H = {h. h \\<in> hom G H \\<and> h \\<in> extensional (carrier G)}\"\n\nlemma (in group_hom) restrict_hom[intro!]:\n  shows \"restrict h (carrier G) \\<in> homr G H\"\n  unfolding homr_def and hom_def\n  by (auto)\n\nlemma hom_F_C2_Powerset:\n  \"\\<exists> f. bij_betw f (Pow X) (homr (\\<F>\\<^bsub>X\\<^esub>) C2)\"\nproof\n  interpret F: group \"\\<F>\\<^bsub>X\\<^esub>\" by (rule free_group_is_group)\n  interpret C2: group C2 by (rule C2_is_group)\n  let ?f = \"\\<lambda>S . restrict (C2.lift (\\<lambda>x. x \\<in> S)) (carrier \\<F>\\<^bsub>X\\<^esub>)\"\n  let ?f' = \"\\<lambda>h . X \\<inter> Collect(h \\<circ> insert)\"\n  show \"bij_betw ?f (Pow X) (homr (\\<F>\\<^bsub>X\\<^esub>) C2)\"\n  proof(induct rule: bij_betwI[of ?f _ _ ?f'])\n  case 1 show ?case\n    proof\n      fix S assume \"S \\<in> Pow X\"\n      interpret h: group_hom \"\\<F>\\<^bsub>X\\<^esub>\" C2 \"C2.lift (\\<lambda>x. x \\<in> S)\"\n        by unfold_locales (auto intro: C2.lift_is_hom)\n      show \"?f S \\<in> homr \\<F>\\<^bsub>X\\<^esub> C2\"\n        by (rule h.restrict_hom)\n     qed\n  next\n  case 2 show ?case by auto next\n  case (3 S) show ?case\n    proof (induct rule: Set.set_eqI)\n      case (1 x) show ?case\n      proof(cases \"x \\<in> X\")\n      case True thus ?thesis using insert_closed[of x X]\n         by (auto simp add:insert_def C2.lift_def C2.lift_gi_def)\n      next case False thus ?thesis using 3 by auto\n    qed\n  qed\n  next\n  case (4 h)\n    hence hom: \"h \\<in> hom \\<F>\\<^bsub>X\\<^esub> C2\"\n      and extn: \"h \\<in> extensional (carrier \\<F>\\<^bsub>X\\<^esub>)\"\n      unfolding homr_def by auto\n    have \"\\<forall>x \\<in> carrier \\<F>\\<^bsub>X\\<^esub> . h x = group.lift C2 (\\<lambda>z. z \\<in> X & (h \\<circ> FreeGroups.insert) z) x\"\n     by (rule C2.lift_is_unique[OF C2_is_group _ hom, of \"(\\<lambda>z. z \\<in> X & (h \\<circ> FreeGroups.insert) z)\"],\n             auto)\n    thus ?case\n    by -(rule extensionalityI[OF restrict_extensional extn], auto)\n  qed\nqed\n\nlemma group_iso_betw_hom:\n  assumes \"group G1\" and \"group G2\"\n      and iso: \"i \\<in> iso G1 G2\"\n  shows   \"\\<exists> f . bij_betw f (homr G2 H) (homr G1 H)\"\nproof-\n  interpret G2: group G2 by (rule \\<open>group G2\\<close>)\n  let ?i' = \"restrict (inv_into (carrier G1) i) (carrier G2)\"\n  have \"inv_into (carrier G1) i \\<in> iso G2 G1\"\n    by (simp add: \\<open>group G1\\<close> group.iso_set_sym iso)    \n  hence iso': \"?i' \\<in> iso G2 G1\"\n    by (auto simp add:Group.iso_def hom_def G2.m_closed)\n  show ?thesis\n  proof(rule, induct rule: bij_betwI[of \"(\\<lambda>h. compose (carrier G1) h i)\" _ _ \"(\\<lambda>h. compose (carrier G2) h ?i')\"])\n  case 1\n    show ?case\n    proof\n      fix h assume \"h \\<in> homr G2 H\"\n      hence \"compose (carrier G1) h i \\<in> hom G1 H\"\n        using iso\n        by (auto intro: group.hom_compose[OF \\<open>group G1\\<close>, of _ G2] simp add:Group.iso_def homr_def)\n      thus \"compose (carrier G1) h i \\<in> homr G1 H\"\n        unfolding homr_def by simp\n     qed\n  next\n  case 2\n    show ?case\n    proof\n      fix h assume \"h \\<in> homr G1 H\"\n      hence \"compose (carrier G2) h ?i' \\<in> hom G2 H\"\n        using iso'\n        by (auto intro: group.hom_compose[OF \\<open>group G2\\<close>, of _ G1] simp add:Group.iso_def homr_def)\n      thus \"compose (carrier G2) h ?i' \\<in> homr G2 H\"\n        unfolding homr_def by simp\n     qed\n  next\n  case (3 x)\n    hence \"compose (carrier G2) (compose (carrier G1) x i) ?i'\n          = compose (carrier G2) x (compose (carrier G2) i ?i')\"\n      using iso iso'\n      by (auto intro: compose_assoc[THEN sym]   simp add:Group.iso_def hom_def homr_def)\n    also have \"\\<dots> = compose (carrier G2) x (\\<lambda>y\\<in>carrier G2. y)\"\n      using iso\n      by (subst compose_id_inv_into, auto simp add:Group.iso_def hom_def bij_betw_def)\n    also have \"\\<dots> = x\"\n      using 3\n      by (auto intro:compose_Id simp add:homr_def)\n    finally\n    show ?case .\n  next\n  case (4 y)\n    hence \"compose (carrier G1) (compose (carrier G2) y ?i') i\n          = compose (carrier G1) y (compose (carrier G1) ?i' i)\"\n      using iso iso'\n      by (auto intro: compose_assoc[THEN sym] simp add:Group.iso_def hom_def homr_def)\n    also have \"\\<dots> = compose (carrier G1) y (\\<lambda>x\\<in>carrier G1. x)\"\n      using iso\n      by (subst compose_inv_into_id, auto simp add:Group.iso_def hom_def bij_betw_def)\n    also have \"\\<dots> = y\"\n      using 4\n      by (auto intro:compose_Id simp add:homr_def)\n    finally\n    show ?case .\n  qed\nqed\n\nlemma isomorphic_free_groups_bases_finite:\n  assumes iso: \"i \\<in> iso \\<F>\\<^bsub>X\\<^esub> \\<F>\\<^bsub>Y\\<^esub>\"\n      and finite: \"finite X\"\n  shows \"\\<exists>f. bij_betw f X Y\"\nproof-\n  obtain f\n    where \"bij_betw f (homr \\<F>\\<^bsub>Y\\<^esub> C2) (homr \\<F>\\<^bsub>X\\<^esub> C2)\"\n    using group_iso_betw_hom[OF free_group_is_group free_group_is_group iso]\n    by auto\n  moreover\n  obtain g'\n    where \"bij_betw g' (Pow X) (homr (\\<F>\\<^bsub>X\\<^esub>) C2)\"\n    using hom_F_C2_Powerset by auto\n  then obtain g\n    where \"bij_betw g (homr (\\<F>\\<^bsub>X\\<^esub>) C2) (Pow X)\"\n    by (auto intro: bij_betw_inv_into)\n  moreover\n  obtain h\n    where \"bij_betw h (Pow Y) (homr (\\<F>\\<^bsub>Y\\<^esub>) C2)\"\n    using hom_F_C2_Powerset by auto\n  ultimately\n  have \"bij_betw (g \\<circ> f \\<circ> h) (Pow Y) (Pow X)\"\n    by (auto intro: bij_betw_trans)\n  hence eq_card: \"card (Pow Y) = card (Pow X)\"\n    by (rule bij_betw_same_card)\n  with finite\n  have \"finite (Pow Y)\"\n   by -(rule card_ge_0_finite, auto simp add:card_Pow)\n  hence finite': \"finite Y\" by simp\n\n  with eq_card finite\n  have \"card X = card Y\"\n   by (auto simp add:card_Pow)\n  with finite finite'\n  show ?thesis\n   by (rule finite_same_card_bij)\nqed\n\ntext \\<open>\nThe proof for the infinite case is trivial once the fact that the free group\nover an infinite set has the same cardinality is established.\n\\<close>\n\nlemma free_group_card_infinite:\n  assumes \"\\<not> finite X\"\n  shows \"|X| =o |carrier \\<F>\\<^bsub>X\\<^esub>|\"\nproof-\n  have \"inj_on insert X\"\n    by (rule inj_onI) (auto simp add: insert_def)\n  moreover have \"insert ` X \\<subseteq> carrier \\<F>\\<^bsub>X\\<^esub>\"\n    by (auto intro: insert_closed)\n  ultimately have \"\\<exists>f. inj_on f X \\<and> f ` X \\<subseteq> carrier \\<F>\\<^bsub>X\\<^esub>\"\n    by auto\n  then have \"|X| \\<le>o |carrier \\<F>\\<^bsub>X\\<^esub>|\"\n    by (simp add: card_of_ordLeq)\n  moreover\n  have \"|carrier \\<F>\\<^bsub>X\\<^esub>| \\<le>o |lists ((UNIV::bool set)\\<times>X)|\"\n    by (auto intro!:card_of_mono1 simp add:free_group_def)\n  moreover\n  have \"|lists ((UNIV::bool set)\\<times>X)| =o |(UNIV::bool set)\\<times>X|\"\n    using \\<open>\\<not> finite X\\<close>\n    by (auto intro:card_of_lists_infinite dest!:finite_cartesian_productD2)\n  moreover\n  have  \"|(UNIV::bool set)\\<times>X| =o |X|\"\n    using \\<open>\\<not> finite X\\<close>\n    by (auto intro: card_of_Times_infinite[OF _ _ ordLess_imp_ordLeq[OF finite_ordLess_infinite2], THEN conjunct2])\n  ultimately\n  show \"|X| =o |carrier \\<F>\\<^bsub>X\\<^esub>|\"\n    by (subst ordIso_iff_ordLeq, auto intro: ord_trans)\nqed\n\ntheorem isomorphic_free_groups_bases:\n  assumes iso: \"i \\<in> iso \\<F>\\<^bsub>X\\<^esub> \\<F>\\<^bsub>Y\\<^esub>\"\n  shows \"\\<exists>f. bij_betw f X Y\"\nproof(cases \"finite X\")\ncase True\n  thus ?thesis using iso by -(rule isomorphic_free_groups_bases_finite)\nnext\ncase False show ?thesis\n  proof(cases \"finite Y\")\n  case True\n  from iso obtain i' where \"i' \\<in> iso \\<F>\\<^bsub>Y\\<^esub> \\<F>\\<^bsub>X\\<^esub>\"\n    using free_group_is_group group.iso_set_sym by blast\n  with \\<open>finite Y\\<close>\n  have \"\\<exists>f. bij_betw f Y X\" by -(rule isomorphic_free_groups_bases_finite)\n  thus \"\\<exists>f. bij_betw f X Y\" by (auto intro: bij_betw_the_inv_into) next\ncase False\n  from \\<open>\\<not> finite X\\<close> have \"|X| =o |carrier \\<F>\\<^bsub>X\\<^esub>|\" \n    by (rule free_group_card_infinite)\n  moreover\n  from \\<open>\\<not> finite Y\\<close> have \"|Y| =o |carrier \\<F>\\<^bsub>Y\\<^esub>|\" \n    by (rule free_group_card_infinite)\n  moreover\n  from iso have \"|carrier \\<F>\\<^bsub>X\\<^esub>| =o |carrier \\<F>\\<^bsub>Y\\<^esub>|\"\n    by (auto simp add:Group.iso_def iff:card_of_ordIso[THEN sym])\n  ultimately\n  have \"|X| =o |Y|\" by (auto intro: ordIso_equivalence)\n  thus ?thesis by (subst card_of_ordIso)\nqed\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/Free-Groups/Isomorphisms.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8902942319436397, "lm_q2_score": 0.8289388104343892, "lm_q1q2_score": 0.7379994415639589}}
{"text": "(*\n  File:   Master_Theorem.thy\n  Author: Manuel Eberl <manuel@pruvisto.org>\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_real_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": "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.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8723473846343393, "lm_q2_score": 0.8459424411924673, "lm_q1q2_score": 0.7379556761254372}}
{"text": "(*  Title:      HOL/Library/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": "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/Fraction_Field.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473779969194, "lm_q2_score": 0.8459424431344437, "lm_q1q2_score": 0.7379556722046401}}
{"text": "theory prog_prov_ch04 imports Main\nbegin\n\nlemma \"\\<not> surj(f::'a \\<Rightarrow> 'a set)\"\nproof\nassume \"surj f\"\nhence \"\\<forall> A. \\<exists> a. A = f a\" by(simp add:surj_def)\nhence \"\\<exists> a. {x. x \\<notin> f x} = f a\" by blast\nthus \"False\" by blast\nqed\n\nlemma\nfixes f:: \"'a \\<Rightarrow> 'a set\"\nassumes s: \"surj f\"\nshows \"False\"\nproof -\nhave \"\\<exists> a.  {x. x \\<notin> f x} = f a\" using s\n  by(auto simp: surj_def)\nthus \"False\" by blast\nqed\n\nlemma \"\\<not> surj(f:: 'a \\<Rightarrow> 'a set)\"\nproof\nassume \"surj f\"\nhence \"\\<exists> a. {x. x\\<notin>f x} = f a\" by (auto simp:surj_def)\nthen obtain a where \"{x. x \\<notin> f x} = f a\" by blast\nhence \"a \\<notin> f a \\<longleftrightarrow> a \\<in> f a\" by blast\nthus \"False\" by blast\nqed\n\n(*exercise 4.1 *)\nlemma assumes T: \"\\<forall> x y. T x y \\<or> T y x\"\n  and A: \"\\<forall> x y. A x y = A y x \\<longrightarrow> x = y\"\n  and TA: \"\\<forall> x y. T x y \\<longrightarrow> A x y\"\n  and Axy: \"A x y\"\nshows \"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 A and Axy by blast\n  thus \"T x y\" using T by blast\nqed\n  \n(* exercise 4.2 *)\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\n  next        \n  assume \"odd (length xs)\"\n    hence \"\\<exists> n. length xs = 2 * n + 1\" by (presburger)\n    then 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\n  qed\n    \nlemma \"length(tl xs) = length xs -1\"\nproof (cases xs)  \n  assume \"xs = []\"\n    thus ?thesis by simp\n  next\n    fix y ys\n    assume \"xs = y#ys\"\n    thus ?thesis by simp\n  qed\n\nlemma \"length (tl xs) = length xs -1\"\nproof (cases xs)\n  case Nil\n  thus ?thesis by simp\n  next      \n  case (Cons y ys)\n  thus ?thesis by simp\nqed\n  \nlemma \"\\<Sum> {0..n::nat} = n*(n+1) div 2\"\nproof (induction n)\n  show \"\\<Sum>{0..0::nat} = 0 * (0+1) div 2\" by simp    \nnext\n  fix n\n  assume \"\\<Sum>{0..n::nat} = n*(n+1) div 2\"\n  thus \"\\<Sum>{0..(Suc n)::nat} = (Suc n)*(Suc n + 1) div 2\" 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\n assume \"?P n\"\n thus \"?P (Suc n)\" by simp\nqed\n\nlemma \"\\<Sum> {0..n::nat} = n*(n+1) div 2\"\nproof (induction n)\n case 0\n show ?case by simp\nnext\n case (Suc n)\n thus ?case 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)\ncase ev0\nshow ?case by simp\nnext\ncase evSS\nthus ?case by simp\nqed\n\nlemma \"ev n \\<Longrightarrow> evn n\"\nproof (induction rule:ev.induct)\n case ev0 show ?case by simp\nnext\n case (evSS m)\n have \"evn (Suc (Suc m)) = evn m\" by simp\n thus ?case using `evn m` by blast\nqed\n\nlemma \"ev  n \\<Longrightarrow> ev (n - 2)\"\nproof -\nassume \"ev n\"\nhence \"ev (n-2)\"\nproof cases\n case ev0\n thus \"ev (n-2)\" by (simp add: ev.ev0)\n next\n case (evSS k)\n thus \"ev (n-2)\" by (simp add: ev.evSS)\nqed\nthus ?thesis by blast\nqed\n\nlemma \"\\<not> ev (Suc 0)\"\nproof\n assume \"ev (Suc 0)\"\n thus \"False\" 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)\"\n  hence \"False\" by cases\n  thus \"False\" by blast\n qed\nqed\n\nlemma \"ev (Suc m) \\<Longrightarrow> \\<not> (ev m)\"\nproof(induction \"Suc m\" arbitrary: m rule:ev.induct)\nfix n\nassume IH: \"\\<And>m. n = Suc m \\<Longrightarrow> \\<not> ev m\"\nshow \"\\<not> ev (Suc n)\"\nproof -- contradiction\nassume \"ev (Suc n)\"\nthus False\n proof (cases \"Suc n\" -- rule)\n  fix k\n  assume \"n = Suc k\" and \"ev k\"\n  thus False using IH by auto\n qed\nqed\nqed\n\n(* exercise 4.3 TODO *)\n\n(* exercise 4.4 TODO *)\n\n(* exercise 4.5 TODO *)\n\n(* exercise 4.6 TODO *)\n\n(* exercise 4.7 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_ch04.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424373085146, "lm_q2_score": 0.872347368040789, "lm_q1q2_score": 0.7379556587000929}}
{"text": "theory Permutation\nimports Main\nbegin\n\ntype_synonym 'a swp = \"'a \\<times> 'a\"\ntype_synonym 'a preprm = \"'a swp list\"\n\ndefinition preprm_id :: \"'a preprm\" where \"preprm_id = []\"\n\nfun swp_apply :: \"'a swp \\<Rightarrow> 'a \\<Rightarrow> 'a\" where\n  \"swp_apply (a, b) x = (if x = a then b else (if x = b then a else x))\"\n\nfun preprm_apply :: \"'a preprm \\<Rightarrow> 'a \\<Rightarrow> 'a\" where\n  \"preprm_apply [] x = x\"\n| \"preprm_apply (s # ss) x = swp_apply s (preprm_apply ss x)\"\n\ndefinition preprm_compose :: \"'a preprm \\<Rightarrow> 'a preprm \\<Rightarrow> 'a preprm\" where\n  \"preprm_compose f g \\<equiv> f @ g\"\n\ndefinition preprm_unit :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a preprm\" where\n  \"preprm_unit a b \\<equiv> [(a, b)]\"\n\ndefinition preprm_ext :: \"'a preprm \\<Rightarrow> 'a preprm \\<Rightarrow> bool\" (infix \"=p\" 100) where\n  \"\\<pi> =p \\<sigma> \\<equiv> \\<forall>x. preprm_apply \\<pi> x = preprm_apply \\<sigma> x\"\n\ndefinition preprm_inv :: \"'a preprm \\<Rightarrow> 'a preprm\" where\n  \"preprm_inv \\<pi> \\<equiv> rev \\<pi>\"\n\nlemma swp_apply_unequal:\n  assumes \"x \\<noteq> y\"\n  shows \"swp_apply s x \\<noteq> swp_apply s y\"\nproof(cases s)\n  case (Pair a b)\n    consider \"x = a\" | \"x = b\" | \"x \\<noteq> a \\<and> x \\<noteq> b\" by auto\n    thus ?thesis proof(cases)\n      case 1\n        have \"swp_apply s x = b\" using \\<open>s = (a, b)\\<close> \\<open>x = a\\<close> by simp\n        moreover have \"swp_apply s y \\<noteq> b\" using \\<open>s = (a, b)\\<close> \\<open>x = a\\<close> \\<open>x \\<noteq> y\\<close>\n          by(cases \"y = b\", simp_all)\n        ultimately show ?thesis by metis\n      next\n      case 2\n        have \"swp_apply s x = a\" using \\<open>s = (a, b)\\<close> \\<open>x = b\\<close> by simp\n        moreover have \"swp_apply s y \\<noteq> a\" using \\<open>s = (a, b)\\<close> \\<open>x = b\\<close> \\<open>x \\<noteq> y\\<close>\n          by(cases \"y = a\", simp_all)\n        ultimately show ?thesis by metis\n      next\n      case 3\n        have \"swp_apply s x = x\" using \\<open>s = (a, b)\\<close> \\<open>x \\<noteq> a \\<and> x \\<noteq> b\\<close> by simp\n        consider \"y = a\" | \"y = b\" | \"y \\<noteq> a \\<and> y \\<noteq> b\" by auto\n        hence \"swp_apply s y \\<noteq> x\" proof(cases)\n          case 1\n            hence \"swp_apply s y = b\" using \\<open>s = (a, b)\\<close> by simp\n            thus ?thesis using \\<open>x \\<noteq> a \\<and> x \\<noteq> b\\<close> by metis\n          next\n          case 2\n            hence \"swp_apply s y = a\" using \\<open>s = (a, b)\\<close> by simp\n            thus ?thesis using \\<open>x \\<noteq> a \\<and> x \\<noteq> b\\<close> by metis\n          next\n          case 3\n            hence \"swp_apply s y = y\" using \\<open>s = (a, b)\\<close> by simp\n            thus ?thesis using \\<open>x \\<noteq> y\\<close> by metis\n          next\n        qed\n        thus ?thesis using \\<open>swp_apply s x = x\\<close> \\<open>x \\<noteq> y\\<close> by metis\n      next\n    qed\n  next\nqed\n\nlemma preprm_ext_reflexive:\n  shows \"x =p x\"\nunfolding preprm_ext_def by auto\n\ncorollary preprm_ext_reflp:\n  shows \"reflp preprm_ext\"\nunfolding reflp_def using preprm_ext_reflexive by auto\n\nlemma preprm_ext_symmetric:\n  assumes \"x =p y\"\n  shows \"y =p x\"\nusing assms unfolding preprm_ext_def by auto\n\ncorollary preprm_ext_symp:\n  shows \"symp preprm_ext\"\nunfolding symp_def using preprm_ext_symmetric by auto\n\nlemma preprm_ext_transitive:\n  assumes \"x =p y\" and \"y =p z\"\n  shows \"x =p z\"\nusing assms unfolding preprm_ext_def by auto\n\ncorollary preprm_ext_transp:\n  shows \"transp preprm_ext\"\nunfolding transp_def using preprm_ext_transitive by auto\n\nlemma preprm_apply_composition:\n  shows \"preprm_apply (preprm_compose f g) x = preprm_apply f (preprm_apply g x)\"\nunfolding preprm_compose_def\nby(induction f, simp_all)\n\nlemma preprm_apply_unequal:\n  assumes \"x \\<noteq> y\"\n  shows \"preprm_apply \\<pi> x \\<noteq> preprm_apply \\<pi> y\"\nusing assms proof(induction \\<pi>, simp)\n  case (Cons s ss)\n    have  \"preprm_apply (s # ss) x = swp_apply s (preprm_apply ss x)\"\n      and \"preprm_apply (s # ss) y = swp_apply s (preprm_apply ss y)\" by auto\n    thus ?case using Cons.IH \\<open>x \\<noteq> y\\<close> swp_apply_unequal by metis\n  next\nqed\n\nlemma preprm_unit_equal_id:\n  shows \"preprm_unit a a =p preprm_id\"\nunfolding preprm_ext_def preprm_unit_def preprm_id_def\nby simp\n\nlemma preprm_unit_inaction:\n  assumes \"x \\<noteq> a\" and \"x \\<noteq> b\"\n  shows \"preprm_apply (preprm_unit a b) x = x\"\nunfolding preprm_unit_def using assms by simp\n\nlemma preprm_unit_action:\n  shows \"preprm_apply (preprm_unit a b) a = b\"\nunfolding preprm_unit_def by simp\n\nlemma preprm_unit_commutes:\n  shows \"preprm_unit a b =p preprm_unit b a\"\nunfolding preprm_ext_def preprm_unit_def\nby simp\n\nlemma preprm_singleton_involution:\n  shows \"preprm_compose [s] [s] =p preprm_id\"\nunfolding preprm_ext_def preprm_compose_def preprm_unit_def preprm_id_def\nproof -\n  obtain s1 s2 where \"s1 = fst s\" \"s2 = snd s\" by auto\n  hence \"s = (s1, s2)\" by simp\n  thus \"\\<forall>x. preprm_apply ([s] @ [s]) x = preprm_apply [] x\"\n    by simp\nqed\n\nlemma preprm_unit_involution:\n  shows \"preprm_compose (preprm_unit a b) (preprm_unit a b) =p preprm_id\"\nunfolding preprm_unit_def\nusing preprm_singleton_involution.\n\nlemma preprm_apply_id:\n  shows \"preprm_apply preprm_id x = x\"\nunfolding preprm_id_def\nby simp\n\nlemma preprm_apply_injective:\n  shows \"inj (preprm_apply \\<pi>)\"\nunfolding inj_on_def proof(rule+)\n  fix x y\n  assume \"preprm_apply \\<pi> x = preprm_apply \\<pi> y\"\n  thus \"x = y\" proof(induction \\<pi>)\n    case Nil\n      thus ?case by auto\n    next\n    case (Cons s ss)\n      hence \"swp_apply s (preprm_apply ss x) = swp_apply s (preprm_apply ss y)\" by auto\n      thus ?case using swp_apply_unequal Cons.IH by metis\n    next\n  qed\nqed\n\nlemma preprm_disagreement_composition:\n  assumes \"a \\<noteq> b\" \"b \\<noteq> c\" \"a \\<noteq> c\"\n  shows \"{x.\n    preprm_apply (preprm_compose (preprm_unit a b) (preprm_unit b c)) x \\<noteq>\n    preprm_apply (preprm_unit a c) x\n  } = {a, b}\"\nunfolding preprm_unit_def preprm_compose_def proof\n  show \"{x. preprm_apply ([(a, b)] @ [(b, c)]) x \\<noteq> preprm_apply [(a, c)] x} \\<subseteq> {a, b}\"\n  proof\n    fix x\n    have \"x \\<notin> {a, b} \\<Longrightarrow> x \\<notin> {x. preprm_apply ([(a, b)] @ [(b, c)]) x \\<noteq> preprm_apply [(a, c)] x}\"\n    proof -\n      assume \"x \\<notin> {a, b}\"\n      hence \"x \\<noteq> a \\<and> x \\<noteq> b\" by auto\n      hence \"preprm_apply ([(a, b)] @ [(b, c)]) x = preprm_apply [(a, c)] x\" by simp\n      thus \"x \\<notin> {x. preprm_apply ([(a, b)] @ [(b, c)]) x \\<noteq> preprm_apply [(a, c)] x}\" by auto\n    qed\n    thus \"x \\<in> {x. preprm_apply ([(a, b)] @ [(b, c)]) x \\<noteq> preprm_apply [(a, c)] x} \\<Longrightarrow> x \\<in> {a, b}\"\n      by blast\n  qed\n  show \"{a, b} \\<subseteq> {x. preprm_apply ([(a, b)] @ [(b, c)]) x \\<noteq> preprm_apply [(a, c)] x}\"\n  proof\n    fix x\n    assume \"x \\<in> {a, b}\"\n    from this consider \"x = a\" | \"x = b\" by auto\n    thus \"x \\<in> {x. preprm_apply ([(a, b)] @ [(b, c)]) x \\<noteq> preprm_apply [(a, c)] x}\"\n      using assms by(cases, simp_all)\n  qed\nqed\n\nlemma preprm_compose_push:\n  shows \"\n    preprm_compose \\<pi> (preprm_unit a b) =p\n    preprm_compose (preprm_unit (preprm_apply \\<pi> a) (preprm_apply \\<pi> b)) \\<pi>\n  \"\nunfolding preprm_ext_def preprm_unit_def\nby (simp add: inj_eq preprm_apply_composition preprm_apply_injective)\n\nlemma preprm_ext_compose_left:\n  assumes \"P =p S\"\n  shows \"preprm_compose \\<pi> P =p preprm_compose \\<pi> S\"\nusing assms unfolding preprm_ext_def\nusing preprm_apply_composition by metis\n\nlemma preprm_ext_compose_right:\n  assumes \"P =p S\"\n  shows \"preprm_compose P \\<pi> =p preprm_compose S \\<pi>\"\nusing assms unfolding preprm_ext_def\nusing preprm_apply_composition by metis\n\nlemma preprm_ext_uncompose:\n  assumes \"\\<pi> =p \\<sigma>\" \"preprm_compose \\<pi> P =p preprm_compose \\<sigma> S\"\n  shows \"P =p S\"\nusing assms unfolding preprm_ext_def\nproof -\n  assume *: \"\\<forall>x. preprm_apply \\<pi> x = preprm_apply \\<sigma> x\"\n\n  assume \"\\<forall>x. preprm_apply (preprm_compose \\<pi> P) x = preprm_apply (preprm_compose \\<sigma> S) x\"\n  hence \"\\<forall>x. preprm_apply \\<pi> (preprm_apply P x) = preprm_apply \\<sigma> (preprm_apply S x)\"\n    using preprm_apply_composition by metis\n  hence \"\\<forall>x. preprm_apply \\<pi> (preprm_apply P x) = preprm_apply \\<pi> (preprm_apply S x)\"\n    using * by metis\n  thus \"\\<forall>x. preprm_apply P x = preprm_apply S x\"\n    using preprm_apply_injective unfolding inj_on_def by fastforce\nqed\n\nlemma preprm_inv_compose:\n  shows \"preprm_compose (preprm_inv \\<pi>) \\<pi> =p preprm_id\"\nunfolding preprm_inv_def\nproof(induction \\<pi>, simp add: preprm_ext_def preprm_id_def preprm_compose_def)\n  case (Cons p ps)\n    hence IH: \"(preprm_compose (rev ps) ps) =p preprm_id\" by auto\n\n    have \"(preprm_compose (rev (p # ps)) (p # ps)) =p (preprm_compose (rev ps) (preprm_compose (preprm_compose [p] [p]) ps))\"\n      unfolding preprm_compose_def using preprm_ext_reflexive by simp\n    moreover have \"... =p (preprm_compose (rev ps) (preprm_compose preprm_id ps))\"\n      using preprm_singleton_involution preprm_ext_compose_left preprm_ext_compose_right by metis\n    moreover have \"... =p (preprm_compose (rev ps) ps)\"\n      unfolding preprm_compose_def preprm_id_def using preprm_ext_reflexive by simp\n    moreover have \"... =p preprm_id\" using IH.\n    ultimately show ?case using preprm_ext_transitive by metis\n  next\nqed\n\nlemma preprm_inv_involution:\n  shows \"preprm_inv (preprm_inv \\<pi>) = \\<pi>\"\nunfolding preprm_inv_def by simp\n\nlemma preprm_inv_ext:\n  assumes \"\\<pi> =p \\<sigma>\"\n  shows \"preprm_inv \\<pi> =p preprm_inv \\<sigma>\"\nproof -\n  have\n    \"(preprm_compose (preprm_inv (preprm_inv \\<pi>)) (preprm_inv \\<pi>)) =p preprm_id\"\n    \"(preprm_compose (preprm_inv (preprm_inv \\<sigma>)) (preprm_inv \\<sigma>)) =p preprm_id\"\n    using preprm_inv_compose by metis+\n  hence\n    \"(preprm_compose \\<pi> (preprm_inv \\<pi>)) =p preprm_id\"\n    \"(preprm_compose \\<sigma> (preprm_inv \\<sigma>)) =p preprm_id\"\n    using preprm_inv_involution by metis+\n  hence \"(preprm_compose \\<pi> (preprm_inv \\<pi>)) =p (preprm_compose \\<sigma> (preprm_inv \\<sigma>))\"\n    using preprm_ext_transitive preprm_ext_symmetric by metis\n  thus \"preprm_inv \\<pi> =p preprm_inv \\<sigma>\"\n    using preprm_ext_uncompose assms by metis\nqed\n\nquotient_type 'a prm = \"'a preprm\" / preprm_ext\nproof(rule equivpI)\n  show \"reflp preprm_ext\" using preprm_ext_reflp.\n  show \"symp preprm_ext\" using preprm_ext_symp.\n  show \"transp preprm_ext\" using preprm_ext_transp.\nqed\n\nlift_definition prm_id :: \"'a prm\" (\"\\<epsilon>\") is preprm_id.\n\nlift_definition prm_apply :: \"'a prm \\<Rightarrow> 'a \\<Rightarrow> 'a\" (infix \"$\" 140) is preprm_apply\nunfolding preprm_ext_def\nusing preprm_apply.simps by auto\n\nlift_definition prm_compose :: \"'a prm \\<Rightarrow> 'a prm \\<Rightarrow> 'a prm\" (infixr \"\\<diamondop>\" 145) is preprm_compose\nunfolding preprm_ext_def\nby(simp only: preprm_apply_composition, simp)\n\nlift_definition prm_unit :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a prm\" (\"[_ \\<leftrightarrow> _]\") is preprm_unit.\n\nlift_definition prm_inv :: \"'a prm \\<Rightarrow> 'a prm\" is preprm_inv\nusing preprm_inv_ext.\n\nlemma prm_apply_composition:\n  fixes f g :: \"'a prm\" and x :: 'a\n  shows \"f \\<diamondop> g $ x = f $ (g $ x)\"\nby(transfer, metis preprm_apply_composition)\n\nlemma prm_apply_unequal:\n  fixes \\<pi> :: \"'a prm\" and x y :: 'a\n  assumes \"x \\<noteq> y\"\n  shows \"\\<pi> $ x \\<noteq> \\<pi> $ y\"\nusing assms by (transfer, metis preprm_apply_unequal)\n\nlemma prm_unit_equal_id:\n  fixes a :: 'a\n  shows \"[a \\<leftrightarrow> a] = \\<epsilon>\"\nby (transfer, metis preprm_unit_equal_id)\n\nlemma prm_unit_inaction:\n  fixes a b x :: 'a\n  assumes \"x \\<noteq> a\" and \"x \\<noteq> b\"\n  shows \"[a \\<leftrightarrow> b] $ x = x\"\nusing assms\nby (transfer, metis preprm_unit_inaction)\n\nlemma prm_unit_action:\n  fixes a b :: 'a\n  shows \"[a \\<leftrightarrow> b] $ a = b\"\nby (transfer, metis preprm_unit_action)\n\nlemma prm_unit_commutes:\n  fixes a b :: 'a\n  shows \"[a \\<leftrightarrow> b] = [b \\<leftrightarrow> a]\"\nby (transfer, metis preprm_unit_commutes)\n\nlemma prm_unit_involution:\n  fixes a b :: 'a\n  shows \"[a \\<leftrightarrow> b] \\<diamondop> [a \\<leftrightarrow> b] = \\<epsilon>\"\nby (transfer, metis preprm_unit_involution)\n\nlemma prm_apply_id:\n  fixes x :: 'a\n  shows \"\\<epsilon> $ x = x\"\nby(transfer, metis preprm_apply_id)\n\nlemma prm_apply_injective:\n  shows \"inj (prm_apply \\<pi>)\"\nby(transfer, metis preprm_apply_injective)\n\nlemma prm_inv_compose:\n  shows \"(prm_inv \\<pi>) \\<diamondop> \\<pi> = \\<epsilon>\"\nby(transfer, metis preprm_inv_compose)\n\ninterpretation \"'a prm\": semigroup prm_compose\nunfolding semigroup_def by(transfer, simp add: preprm_compose_def preprm_ext_def)\n\ninterpretation \"'a prm\": group prm_compose prm_id prm_inv\nunfolding group_def group_axioms_def\nproof -\n  have \"semigroup (\\<diamondop>)\" using \"'a prm.semigroup_axioms\".\n  moreover have \"\\<forall>a. \\<epsilon> \\<diamondop> a = a\" by(transfer, simp add: preprm_id_def preprm_compose_def preprm_ext_def)\n  moreover have \"\\<forall>a. prm_inv a \\<diamondop> a = \\<epsilon>\" using prm_inv_compose by blast\n  ultimately show \"semigroup (\\<diamondop>) \\<and> (\\<forall>a. \\<epsilon> \\<diamondop> a = a) \\<and> (\\<forall>a. prm_inv a \\<diamondop> a = \\<epsilon>)\" by blast\nqed\n\ndefinition prm_set :: \"'a prm \\<Rightarrow> 'a set \\<Rightarrow> 'a set\" (infix \"{$}\" 140) where\n  \"prm_set \\<pi> S \\<equiv> image (prm_apply \\<pi>) S\"\n\nlemma prm_set_apply_compose:\n  shows \"\\<pi> {$} (\\<sigma> {$} S) = (\\<pi> \\<diamondop> \\<sigma>) {$} S\"\nunfolding prm_set_def proof -\n  have \"($) \\<pi> ` ($) \\<sigma> ` S = (\\<lambda>x. \\<pi> $ x) ` (\\<lambda>x. \\<sigma> $ x) ` S\" by simp\n  moreover have \"... = (\\<lambda>x. \\<pi> $ (\\<sigma> $ x)) ` S\" by auto\n  moreover have \"... = (\\<lambda>x. (\\<pi> \\<diamondop> \\<sigma>) $ x) ` S\" using prm_apply_composition by metis\n  moreover have \"... = (\\<pi> \\<diamondop> \\<sigma>) {$} S\" using prm_set_def by metis\n  ultimately show \"($) \\<pi> ` ($) \\<sigma> ` S = ($) (\\<pi> \\<diamondop> \\<sigma>) ` S\" by metis\nqed\n\nlemma prm_set_membership:\n  assumes \"x \\<in> S\"\n  shows \"\\<pi> $ x \\<in> \\<pi> {$} S\"\nusing assms unfolding prm_set_def by simp\n\nlemma prm_set_notmembership:\n  assumes \"x \\<notin> S\"\n  shows \"\\<pi> $ x \\<notin> \\<pi> {$} S\"\nusing assms unfolding prm_set_def \nby (simp add: inj_image_mem_iff prm_apply_injective)\n\nlemma prm_set_singleton:\n  shows \"\\<pi> {$} {x} = {\\<pi> $ x}\"\nunfolding prm_set_def by auto\n\nlemma prm_set_id:\n  shows \"\\<epsilon> {$} S = S\"\nunfolding prm_set_def\nproof -\n  have \"($) \\<epsilon> ` S = (\\<lambda>x. \\<epsilon> $ x) ` S\" by simp\n  moreover have \"... = (\\<lambda>x. x) ` S\" using prm_apply_id by metis\n  moreover have \"... = S\" by auto\n  ultimately show \"($) \\<epsilon> ` S = S\" by metis\nqed\n\nlemma prm_set_unit_inaction:\n  assumes \"a \\<notin> S\" and \"b \\<notin> S\"\n  shows \"[a \\<leftrightarrow> b] {$} S = S\"\nproof\n  show \"[a \\<leftrightarrow> b] {$} S \\<subseteq> S\" proof\n    fix x\n    assume H: \"x \\<in> [a \\<leftrightarrow> b] {$} S\"\n    from this obtain y where \"x = [a \\<leftrightarrow> b] $ y\" unfolding prm_set_def using imageE by metis\n    hence \"y \\<in> S\" using H inj_image_mem_iff prm_apply_injective prm_set_def by metis\n    hence \"y \\<noteq> a\" and \"y \\<noteq> b\" using assms by auto\n    hence \"x = y\" using prm_unit_inaction \\<open>x = [a \\<leftrightarrow> b] $ y\\<close> by metis\n    thus \"x \\<in> S\" using \\<open>y \\<in> S\\<close> by auto\n  qed\n  show \"S \\<subseteq> [a \\<leftrightarrow> b] {$} S\" proof\n    fix x\n    assume H: \"x \\<in> S\"\n    hence \"x \\<noteq> a\" and \"x \\<noteq> b\" using assms by auto\n    hence \"x = [a \\<leftrightarrow> b] $ x\" using prm_unit_inaction by metis\n    thus \"x \\<in> [a \\<leftrightarrow> b] {$} S\" unfolding prm_set_def using H by simp\n  qed\nqed\n\nlemma prm_set_unit_action:\n  assumes \"a \\<in> S\" and \"b \\<notin> S\"\n  shows \"[a \\<leftrightarrow> b] {$} S = S - {a} \\<union> {b}\"\nproof\n  show \"[a \\<leftrightarrow> b] {$} S \\<subseteq> S - {a} \\<union> {b}\" proof\n    fix x\n    assume H: \"x \\<in> [a \\<leftrightarrow> b] {$} S\"\n    from this obtain y where \"x = [a \\<leftrightarrow> b] $ y\" unfolding prm_set_def using imageE by metis\n    hence \"y \\<in> S\" using H inj_image_mem_iff prm_apply_injective prm_set_def by metis\n    hence \"y \\<noteq> b\" using assms by auto\n    consider \"y = a\" | \"y \\<noteq> a\" by auto\n    thus \"x \\<in> S - {a} \\<union> {b}\" proof(cases)\n      case 1\n        hence \"x = b\" using \\<open>x = [a \\<leftrightarrow> b] $ y\\<close> using prm_unit_action by metis\n        thus ?thesis by auto\n      next\n      case 2\n        hence \"x = y\" using \\<open>x = [a \\<leftrightarrow> b] $ y\\<close> using prm_unit_inaction \\<open>y \\<noteq> b\\<close> by metis\n        hence \"x \\<in> S\" and \"x \\<noteq> a\" using \\<open>y \\<in> S\\<close> \\<open>y \\<noteq> a\\<close> by auto\n        thus ?thesis by auto\n      next\n    qed\n  qed\n  show \"S - {a} \\<union> {b} \\<subseteq> [a \\<leftrightarrow> b] {$} S\" proof\n    fix x\n    assume H: \"x \\<in> S - {a} \\<union> {b}\"\n    hence \"x \\<noteq> a\" using assms by auto\n    consider \"x = b\" | \"x \\<noteq> b\" by auto\n    thus \"x \\<in> [a \\<leftrightarrow> b] {$} S\" proof(cases)\n      case 1\n        hence \"x = [a \\<leftrightarrow> b] $ a\" using prm_unit_action by metis\n        thus ?thesis using \\<open>a \\<in> S\\<close> prm_set_membership by metis\n      next\n      case 2\n        hence \"x \\<in> S\" using H by auto\n        moreover have \"x = [a \\<leftrightarrow> b] $ x\" using prm_unit_inaction \\<open>x \\<noteq> a\\<close> \\<open>x \\<noteq> b\\<close> by metis\n        ultimately show ?thesis using prm_set_membership by metis\n      next\n    qed\n  qed\nqed\n\nlemma prm_set_distributes_union:\n  shows \"\\<pi> {$} (S \\<union> T) = (\\<pi> {$} S) \\<union> (\\<pi> {$} T)\"\nunfolding prm_set_def by auto\n\nlemma prm_set_distributes_difference:\n  shows \"\\<pi> {$} (S - T) = (\\<pi> {$} S) - (\\<pi> {$} T)\"\nunfolding prm_set_def using prm_apply_injective image_set_diff by metis\n\ndefinition prm_disagreement :: \"'a prm \\<Rightarrow> 'a prm \\<Rightarrow> 'a set\" (\"ds\") where\n  \"prm_disagreement \\<pi> \\<sigma> \\<equiv> {x. \\<pi> $ x \\<noteq> \\<sigma> $ x}\"\n\nlemma prm_disagreement_ext:\n  shows \"x \\<in> ds \\<pi> \\<sigma> \\<equiv> \\<pi> $ x \\<noteq> \\<sigma> $ x\"\nunfolding prm_disagreement_def by simp\n\nlemma prm_disagreement_composition:\n  assumes \"a \\<noteq> b\" \"b \\<noteq> c\" \"a \\<noteq> c\"\n  shows \"ds ([a \\<leftrightarrow> b] \\<diamondop> [b \\<leftrightarrow> c]) [a \\<leftrightarrow> c] = {a, b}\"\nusing assms unfolding prm_disagreement_def by(transfer, metis preprm_disagreement_composition)\n\nlemma prm_compose_push:\n  shows \"\\<pi> \\<diamondop> [a \\<leftrightarrow> b] = [\\<pi> $ a \\<leftrightarrow> \\<pi> $ b] \\<diamondop> \\<pi>\"\nby(transfer, metis preprm_compose_push)\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/Name_Carrying_Type_Inference/Permutation.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473614033683, "lm_q2_score": 0.845942439250491, "lm_q1q2_score": 0.737955654779295}}
{"text": "theory Pascal_Property\n  imports Main Projective_Plane_Axioms Pappus_Property\nbegin\n\n(* Author: Anthony Bordg, University of Cambridge, apdb3@cam.ac.uk .*)\n\ntext \\<open>\nContents:\n\\<^item> A hexagon is pascal if its three opposite sides meet in collinear points @{term is_pascal}.\n\\<^item> A plane is pascal, or has Pascal's property, if for every hexagon of that plane\nPascal property is stable under any permutation of that hexagon. \n\\<close>\n\nsection \\<open>Pascal's Property\\<close>\n\ncontext projective_plane\nbegin \n\ndefinition inters :: \"'line \\<Rightarrow> 'line \\<Rightarrow> 'point set\" where\n\"inters l m \\<equiv> {P. incid P l \\<and> incid P m}\"\n\nlemma inters_is_singleton:\n  assumes \"l \\<noteq> m\" and \"P \\<in> inters l m\" and \"Q \\<in> inters l m\"\n  shows \"P = Q\"\n  using assms ax_uniqueness inters_def \n  by blast\n\ndefinition inter :: \"'line \\<Rightarrow> 'line \\<Rightarrow> 'point\" where\n\"inter l m \\<equiv> @P. P \\<in> inters l m\"\n\nlemma uniq_inter:\n  assumes \"l \\<noteq> m\" and \"incid P l\" and \"incid P m\"\n  shows \"inter l m = P\"\nproof -\n  have \"P \\<in> inters l m\"\n    by (simp add: assms(2) assms(3) inters_def)\n  have \"\\<forall>Q. Q \\<in> inters l m \\<longrightarrow> Q = P\"\n    using \\<open>P \\<in> inters l m\\<close> assms(1) inters_is_singleton \n    by blast\n  show \"inter l m = P\"\n    using \\<open>P \\<in> inters l m\\<close> assms(1) inter_def inters_is_singleton \n    by auto\nqed\n\n(* The configuration of a hexagon where the three pairs of opposite sides meet in \ncollinear points *)\ndefinition is_pascal :: \"['point, 'point, 'point, 'point, 'point, 'point] \\<Rightarrow> bool\" where\n\"is_pascal A B C D E F \\<equiv> distinct [A,B,C,D,E,F] \\<longrightarrow> line B C \\<noteq> line E F \\<longrightarrow> line C D \\<noteq> line A F\n\\<longrightarrow> line A B \\<noteq> line D E \\<longrightarrow> \n(let P = inter (line B C) (line E F) in\nlet Q = inter (line C D) (line A F) in\nlet R = inter (line A B) (line D E) in \ncol P Q R)\"\n\nlemma col_rot_CW:\n  assumes \"col P Q R\"\n  shows \"col R P Q\"\n  using assms col_def \n  by auto\n\nlemma col_2cycle: \n  assumes \"col P Q R\"\n  shows \"col P R Q\"\n  using assms col_def \n  by auto\n\nlemma distinct6_rot_CW:\n  assumes \"distinct [A,B,C,D,E,F]\"\n  shows \"distinct [F,A,B,C,D,E]\"\n  using assms distinct6_def \n  by auto\n\nlemma lines_comm: \"lines P Q = lines Q P\"\n  using lines_def \n  by auto\n\nlemma line_comm:\n  assumes \"P \\<noteq> Q\"\n  shows \"line P Q = line Q P\"\n  by (metis ax_uniqueness incidA_lAB incidB_lAB)\n  \nlemma inters_comm: \"inters l m = inters m l\"\n  using inters_def \n  by auto\n\nlemma inter_comm: \"inter l m = inter m l\"\n  by (simp add: inter_def inters_comm)\n\nlemma inter_line_line_comm:\n  assumes \"C \\<noteq> D\"\n  shows \"inter (line A B) (line C D) = inter (line A B) (line D C)\"\n  using assms line_comm \n  by auto\n\nlemma inter_line_comm_line:\n  assumes \"A \\<noteq> B\"\n  shows \"inter (line A B) (line C D) = inter (line B A) (line C D)\"\n  using assms line_comm \n  by auto\n\nlemma inter_comm_line_line_comm:\n  assumes \"C \\<noteq> D\" and \"line A B \\<noteq> line C D\"\n  shows \"inter (line A B) (line C D) = inter (line D C) (line A B)\"\n  by (metis inter_comm line_comm)\n\n(* Pascal's property is stable under the 6-cycle [A B C D E F] *)\nlemma is_pascal_rot_CW:\n  assumes \"is_pascal A B C D E F\"\n  shows \"is_pascal F A B C D E\"\nproof -\n  define P Q R where \"P = inter (line A B) (line D E)\" and \"Q = inter (line B C) (line E F)\" and\n    \"R = inter (line F A) (line C D)\"\n  have \"col P Q R\" if \"distinct [F,A,B,C,D,E]\" and \"line A B \\<noteq> line D E\" and \"line B C \\<noteq> line E F\" \n    and \"line F A \\<noteq> line C D\"\n    using P_def Q_def R_def assms col_rot_CW distinct6_def inter_comm is_pascal_def line_comm \n      that(1) that(2) that(3) that(4) \n    by auto\n  then show \"is_pascal F A B C D E\"\n    by (metis P_def Q_def R_def is_pascal_def line_comm)\nqed\n\n(* We recall that the group of permutations S_6 is generated by the 2-cycle [1 2]\nand the 6-cycle [1 2 3 4 5 6] *)\n\n(* Assuming Pappus's property, Pascal's property is stable under the 2-cycle [A B] *)\n\nlemma incid_C_AB: \n  assumes \"A \\<noteq> B\" and \"incid A l\" and \"incid B l\" and \"incid C l\"\n  shows \"incid C (line A B)\"\n  using assms ax_uniqueness incidA_lAB incidB_lAB \n  by blast\n\nlemma incid_inters_left: \n  assumes \"P \\<in> inters l m\"\n  shows \"incid P l\"\n  using assms inters_def \n  by auto\n\nlemma incid_inters_right:\n  assumes \"P \\<in> inters l m\"\n  shows \"incid P m\"\n  using assms incid_inters_left inters_comm \n  by blast\n\nlemma inter_in_inters: \"inter l m \\<in> inters l m\"\nproof -\n  have \"\\<exists>P. P \\<in> inters l m\"\n    using inters_def ax2 \n    by auto\n  show \"inter l m \\<in> inters l m\"\n    by (metis \\<open>\\<exists>P. P \\<in> inters l m\\<close> inter_def some_eq_ex)\nqed\n\nlemma incid_inter_left: \"incid (inter l m) l\"\n  using incid_inters_left inter_in_inters \n  by blast\n\nlemma incid_inter_right: \"incid (inter l m) m\"\n  using incid_inter_left inter_comm \n  by fastforce\n\nlemma col_A_B_ABl: \"col A B (inter (line A B) l)\"\n  using col_def incidA_lAB incidB_lAB incid_inter_left \n  by blast\n\nlemma col_A_B_lAB: \"col A B (inter l (line A B))\"\n  using col_A_B_ABl inter_comm \n  by auto\n\nlemma inter_is_a_intersec: \"is_a_intersec (inter (line A B) (line C D)) A B C D\"\n  by (simp add: col_A_B_ABl col_A_B_lAB col_rot_CW is_a_intersec_def)\n\ndefinition line_ext :: \"'line \\<Rightarrow> 'point set\" where\n\"line_ext l \\<equiv> {P. incid P l}\"\n\nlemma line_left_inter_1: \n  assumes \"P \\<in> line_ext l\" and \"P \\<notin> line_ext m\"\n  shows \"line (inter l m) P = l\"\n  by (metis CollectD CollectI assms(1) assms(2) incidA_lAB incidB_lAB incid_inter_left \n      incid_inter_right line_ext_def uniq_inter)\n\nlemma line_left_inter_2:\n  assumes \"P \\<in> line_ext m\" and \"P \\<notin> line_ext l\"\n  shows \"line (inter l m) P = m\"\n  using assms inter_comm line_left_inter_1 \n  by fastforce\n\nlemma line_right_inter_1:\n  assumes \"P \\<in> line_ext l\" and \"P \\<notin> line_ext m\"\n  shows \"line P (inter l m) = l\"\n  by (metis assms line_comm line_left_inter_1)\n\nlemma line_right_inter_2:\n  assumes \"P \\<in> line_ext m\" and \"P \\<notin> line_ext l\"\n  shows \"line P (inter l m) = m\"\n  by (metis assms inter_comm line_comm line_left_inter_1)\n\nlemma inter_ABC_1: \n  assumes \"line A B \\<noteq> line C A\"\n  shows \"inter (line A B) (line C A) = A\"\n  using assms ax_uniqueness incidA_lAB incidB_lAB incid_inter_left incid_inter_right \n  by blast\n\nlemma line_inter_2:\n  assumes \"inter l m \\<noteq> inter l' m\" \n  shows \"line (inter l m) (inter l' m) = m\"\n  using assms ax_uniqueness incidA_lAB incidB_lAB incid_inter_right \n  by blast\n\nlemma col_line_ext_1:\n  assumes \"col A B C\" and \"A \\<noteq> C\"\n  shows \"B \\<in> line_ext (line A C)\"\n  by (metis CollectI assms ax_uniqueness col_def incidA_lAB incidB_lAB line_ext_def)\n\nlemma inter_line_ext_1:\n  assumes \"inter l m \\<in> line_ext n\" and \"l \\<noteq> m\" and \"l \\<noteq> n\"\n  shows \"inter l m = inter l n\"\n  using assms(1) assms(3) ax_uniqueness incid_inter_left incid_inter_right line_ext_def \n  by blast\n\nlemma inter_line_ext_2:\n  assumes \"inter l m \\<in> line_ext n\" and \"l \\<noteq> m\" and \"m \\<noteq> n\"\n  shows \"inter l m = inter m n\"\n  by (metis assms inter_comm inter_line_ext_1)\n\ndefinition pascal_prop :: \"bool\" where\n\"pascal_prop \\<equiv> \\<forall>A B C D E F. is_pascal A B C D E F \\<longrightarrow> is_pascal B A C D E F\"\n\nlemma pappus_pascal:\n  assumes \"is_pappus\"\n  shows \"pascal_prop\"\nproof-\n  have \"is_pascal B A C D E F\" if \"is_pascal A B C D E F\" for A B C D E F\n  proof-\n    define X Y Z where \"X = inter (line A C) (line E F)\" and \"Y = inter (line C D) (line B F)\"\n      and \"Z = inter (line B A) (line D E)\" \n    have \"col X Y Z\" if \"distinct [B,A,C,D,E,F]\" and \"line A C \\<noteq> line E F\" and \"line C D \\<noteq> line B F\" \n      and \"line B A \\<noteq> line D E\" and \"line B C = line E F\"\n      by (smt X_def Y_def ax_uniqueness col_ABA col_rot_CW distinct6_def incidB_lAB incid_inter_left \n          incid_inter_right line_comm that(1) that(2) that(3) that(5))\n    have \"col X Y Z\" if \"distinct [B,A,C,D,E,F]\" and \"line A C \\<noteq> line E F\" and \"line C D \\<noteq> line B F\" \n      and \"line B A \\<noteq> line D E\" and \"line C D = line A F\"\n      by (metis X_def Y_def col_ABA col_rot_CW distinct6_def inter_ABC_1 line_comm that(1) that(2) \n          that(3) that(5))\n    have \"col X Y Z\" if \"distinct [B,A,C,D,E,F]\" and \"line A C \\<noteq> line E F\" and \"line C D \\<noteq> line B F\" \n      and \"line B A \\<noteq> line D E\" and \"line B C \\<noteq> line E F\" and \"line C D \\<noteq> line A F\"\n    proof-\n      define W where \"W = inter (line A C) (line E F)\"\n      have \"col A C W\"\n        by (simp add: col_A_B_ABl W_def)\n      define P Q R where \"P = inter (line B C) (line E F)\"\n        and \"Q = inter (line A B) (line D E)\"\n        and \"R = inter (line C D) (line A F)\"\n      have \"col P Q R\"\n        using P_def Q_def R_def \\<open>is_pascal A B C D E F\\<close> col_2cycle distinct6_def is_pascal_def \n          line_comm that(1) that(4) that(5) that(6) \n        by auto\n          (* Below we take care of a few degenerate cases *)\n      have \"col X Y Z\" if \"P = Q\"\n        by (smt P_def Q_def X_def Y_def Z_def \\<open>distinct [B,A,C,D,E,F]\\<close> ax_uniqueness col_ABA col_def \n            distinct6_def incidA_lAB incidB_lAB incid_inter_left inter_comm that)\n      have \"col X Y Z\" if \"P = R\"\n        by (smt P_def R_def X_def Y_def Z_def \\<open>distinct [B,A,C,D,E,F]\\<close> \\<open>line A C \\<noteq> line E F\\<close> \n            \\<open>line C D \\<noteq> line B F\\<close> col_2cycle col_A_B_ABl col_rot_CW distinct6_def incidA_lAB \n            incidB_lAB incid_inter_left incid_inter_right that uniq_inter)\n      have \"col X Y Z\" if \"P = A\"\n        by (smt P_def Q_def R_def X_def Y_def Z_def \\<open>P = Q \\<Longrightarrow> col X Y Z\\<close> \\<open>P = R \\<Longrightarrow> col X Y Z\\<close> \n            \\<open>col P Q R\\<close> \\<open>line B C \\<noteq> line E F\\<close> ax_uniqueness col_def incidA_lAB incid_inter_left \n            incid_inter_right line_comm that)\n      have \"col X Y Z\" if \"P = C\"\n        by (smt P_def Q_def R_def X_def Y_def Z_def \\<open>P = R \\<Longrightarrow> col X Y Z\\<close> \\<open>col P Q R\\<close> \n            \\<open>line A C \\<noteq> line E F\\<close> ax_uniqueness col_def incidA_lAB incid_inter_left \n            incid_inter_right line_comm that)\n      have \"col X Y Z\" if \"P = W\"\n        by (smt P_def Q_def R_def W_def X_def Y_def Z_def \\<open>P = C \\<Longrightarrow> col X Y Z\\<close> \\<open>P = Q \\<Longrightarrow> col X Y Z\\<close> \n            \\<open>col P Q R\\<close> \\<open>distinct [B,A,C,D,E,F]\\<close> ax_uniqueness col_def distinct6_def incidB_lAB \n            incid_inter_left incid_inter_right line_comm that) \n      have \"col X Y Z\" if \"Q = R\"\n        by (smt Q_def R_def X_def Y_def Z_def \\<open>distinct [B,A,C,D,E,F]\\<close> ax_uniqueness col_A_B_lAB \n            col_rot_CW distinct6_def incidB_lAB incid_inter_right inter_comm line_comm that)\n      have \"col X Y Z\" if \"Q = A\"\n        by (smt P_def Q_def R_def X_def Y_def Z_def \\<open>col P Q R\\<close> \\<open>distinct [B,A,C,D,E,F]\\<close> \n            \\<open>line C D \\<noteq> line B F\\<close> ax_uniqueness col_ABA col_def distinct6_def incidA_lAB incidB_lAB \n            incid_inter_left incid_inter_right that)\n      have \"col X Y Z\" if \"Q = C\"\n        by (metis P_def Q_def W_def \\<open>P = W \\<Longrightarrow> col X Y Z\\<close> \\<open>distinct [B,A,C,D,E,F]\\<close> ax_uniqueness \n            distinct6_def incidA_lAB incid_inter_left line_comm that)\n      have \"col X Y Z\" if \"Q = W\"\n        by (metis Q_def W_def X_def Z_def col_ABA line_comm that)\n      have \"col X Y Z\" if \"R = A\"\n        by (smt P_def Q_def R_def W_def X_def Y_def \\<open>P = W \\<Longrightarrow> col X Y Z\\<close> \\<open>Q = A \\<Longrightarrow> col X Y Z\\<close> \n            \\<open>col P Q R\\<close> \\<open>distinct [B,A,C,D,E,F]\\<close> ax_uniqueness col_ABA col_def col_rot_CW distinct6_def \n            incidA_lAB incidB_lAB incid_inter_right inter_comm that)\n      have \"col X Y Z\" if \"R = C\"\n        by (smt P_def Q_def R_def X_def Y_def Z_def \\<open>col P Q R\\<close> \\<open>distinct [B,A,C,D,E,F]\\<close> \n            \\<open>line A C \\<noteq> line E F\\<close> ax_uniqueness col_def distinct6_def incidA_lAB incidB_lAB \n            incid_inter_left inter_comm that)\n      have \"col X Y Z\" if \"R = W\"\n        by (metis R_def W_def \\<open>R = A \\<Longrightarrow> col X Y Z\\<close> \\<open>R = C \\<Longrightarrow> col X Y Z\\<close> \\<open>line C D \\<noteq> line A F\\<close> \n            ax_uniqueness incidA_lAB incidB_lAB incid_inter_left incid_inter_right that)\n      have \"col X Y Z\" if \"A = W\"\n        by (smt P_def Q_def R_def W_def X_def Y_def Z_def \\<open>P = R \\<Longrightarrow> col X Y Z\\<close> \\<open>Q = A \\<Longrightarrow> col X Y Z\\<close> \n            \\<open>col P Q R\\<close> \\<open>distinct [B,A,C,D,E,F]\\<close> ax_uniqueness col_def distinct6_def incidA_lAB \n            incidB_lAB incid_inter_left incid_inter_right that)\n      have \"col X Y Z\" if \"C = W\"\n        by (metis P_def W_def \\<open>P = C \\<Longrightarrow> col X Y Z\\<close> \\<open>line B C \\<noteq> line E F\\<close> ax_uniqueness incidB_lAB \n            incid_inter_left incid_inter_right that)\n      have f1:\"col (inter (line P C) (line A Q)) (inter (line Q W) (line C R)) \n      (inter (line P W) (line A R))\" if \"distinct [P,Q,R,A,C,W]\"\n        using assms(1) is_pappus_def is_pappus2_def \\<open>distinct [P,Q,R,A,C,W]\\<close> \\<open>col P Q R\\<close>\n          \\<open>col A C W\\<close> inter_is_a_intersec inter_line_line_comm \n        by presburger\n      have \"col X Y Z\" if \"C \\<in> line_ext (line E F)\"\n        using P_def \\<open>P = C \\<Longrightarrow> col X Y Z\\<close> \\<open>line B C \\<noteq> line E F\\<close> incidB_lAB line_ext_def that uniq_inter \n        by auto \n      have \"col X Y Z\" if \"A \\<in> line_ext (line D E)\"\n        by (metis Q_def \\<open>Q = A \\<Longrightarrow> col X Y Z\\<close> \\<open>line B A \\<noteq> line D E\\<close> ax_uniqueness incidA_lAB \n            incid_inter_left incid_inter_right line_comm line_ext_def mem_Collect_eq that)\n      have \"col X Y Z\" if \"line B C = line A B\"\n        by (metis P_def W_def \\<open>P = W \\<Longrightarrow> col X Y Z\\<close> \\<open>distinct [B,A,C,D,E,F]\\<close> ax_uniqueness \n            distinct6_def incidA_lAB incidB_lAB that)\n          (* We can resume our proof with the non-degenerate case *)\n      have f2:\"inter (line P C) (line A Q) = B\" if\n        \"C \\<notin> line_ext (line E F)\" and \"A \\<notin> line_ext (line D E)\" and \"line B C \\<noteq> line A B\"\n        by (smt CollectI P_def Q_def ax_uniqueness incidA_lAB incidB_lAB incid_inter_left \n            incid_inter_right line_ext_def that(1) that(2) that(3))\n          (* Again, we need to take care of a few particular cases *)\n      have \"col X Y Z\" if \"line E F = line A F\"\n        by (metis W_def \\<open>A = W \\<Longrightarrow> col X Y Z\\<close> \\<open>line A C \\<noteq> line E F\\<close> inter_ABC_1 inter_comm that)\n      have \"col X Y Z\" if \"A \\<in> line_ext (line C D)\"\n        using R_def \\<open>R = A \\<Longrightarrow> col X Y Z\\<close> \\<open>line C D \\<noteq> line A F\\<close> ax_uniqueness incidA_lAB \n          incid_inter_left incid_inter_right line_ext_def that \n        by blast \n      have \"col X Y Z\" if \"inter (line B C) (line E F) = inter (line A C) (line E F)\"\n        by (simp add: P_def W_def \\<open>P = W \\<Longrightarrow> col X Y Z\\<close> that)\n          (* We resume the general case *)\n      have f3:\"inter (line P W) (line A R) = F\" if \"line E F \\<noteq> line A F\" and \"A \\<notin> line_ext (line C D)\"\n        and \"inter (line B C) (line E F) \\<noteq> inter (line A C) (line E F)\"\n        by (smt CollectI P_def R_def W_def ax_uniqueness incidA_lAB incidB_lAB incid_inter_left \n            incid_inter_right line_ext_def that(1) that(2) that(3))\n          (* Once again, first we need to handle a particular case, namely C \\<in> AF, then \n            we resume the general case *)\n      have \"col X Y Z\" if \"C \\<in> line_ext (line A F)\"\n        using R_def \\<open>R = C \\<Longrightarrow> col X Y Z\\<close> \\<open>line C D \\<noteq> line A F\\<close> ax_uniqueness incidA_lAB \n          incid_inter_left incid_inter_right line_ext_def that \n        by blast\n      have f4:\"inter (line Q W) (line C R) = inter (line Q W) (line C D)\" if \"C \\<notin> line_ext (line A F)\"\n        using R_def incidA_lAB line_ext_def line_right_inter_1 that \n        by auto\n      then have \"inter (line Q W) (line C D) \\<in> line_ext (line B F)\" if \"distinct [P,Q,R,A,C,W]\"\n        and  \"C \\<notin> line_ext (line E F)\" and \"A \\<notin> line_ext (line D E)\" and \"line B C \\<noteq> line A B\"\n        and \"line E F \\<noteq> line A F\" and \"A \\<notin> line_ext (line C D)\"\n        and \"inter (line B C) (line E F) \\<noteq> inter (line A C) (line E F)\"\n        by (smt R_def \\<open>distinct [B,A,C,D,E,F]\\<close> ax_uniqueness col_line_ext_1 distinct6_def f1 f2 f3 \n            incidA_lAB incidB_lAB incid_inter_left that(1) that(2) that(3) that(5) that(6) that(7))\n      then have \"inter (line Q W) (line C D) = inter (line C D) (line B F)\" if \"distinct [P,Q,R,A,C,W]\"\n        and  \"C \\<notin> line_ext (line E F)\" and \"A \\<notin> line_ext (line D E)\" and \"line B C \\<noteq> line A B\"\n        and \"line E F \\<noteq> line A F\" and \"A \\<notin> line_ext (line C D)\"\n        and \"inter (line B C) (line E F) \\<noteq> inter (line A C) (line E F)\"\n        by (smt W_def \\<open>distinct [B,A,C,D,E,F]\\<close> \\<open>line C D \\<noteq> line B F\\<close> ax_uniqueness distinct6_def f2 \n            incidA_lAB incidB_lAB incid_inter_left incid_inter_right inter_line_ext_2 that(1) that(2) \n            that(3) that(5) that(6) that(7))\n      moreover have \"inter (line C D) (line B F) \\<in> line_ext (line Q W)\" if \"distinct [P,Q,R,A,C,W]\"\n        and  \"C \\<notin> line_ext (line E F)\" and \"A \\<notin> line_ext (line D E)\" and \"line B C \\<noteq> line A B\"\n        and \"line E F \\<noteq> line A F\" and \"A \\<notin> line_ext (line C D)\"\n        and \"inter (line B C) (line E F) \\<noteq> inter (line A C) (line E F)\"\n        by (metis calculation col_2cycle col_A_B_ABl col_line_ext_1 distinct6_def that(1) that(2) \n            that(3) that(4) that(5) that(6) that(7))\n      ultimately have \"col (inter (line A C) (line E F)) (inter (line C D) (line B F))\n      (inter (line A B) (line D E))\" if \"distinct [P,Q,R,A,C,W]\"\n        and  \"C \\<notin> line_ext (line E F)\" and \"A \\<notin> line_ext (line D E)\" and \"line B C \\<noteq> line A B\"\n        and \"line E F \\<noteq> line A F\" and \"A \\<notin> line_ext (line C D)\"\n        and \"inter (line B C) (line E F) \\<noteq> inter (line A C) (line E F)\"\n        by (metis Q_def W_def col_A_B_ABl col_rot_CW that(1) that(2) that(3) that(4) that(5) that(6) \n            that(7))\n      show \"col X Y Z\"\n        by (metis P_def W_def X_def Y_def Z_def \\<open>A = W \\<Longrightarrow> col X Y Z\\<close> \\<open>A \\<in> line_ext (line C D) \\<Longrightarrow> col X Y Z\\<close> \n            \\<open>A \\<in> line_ext (line D E) \\<Longrightarrow> col X Y Z\\<close> \\<open>C = W \\<Longrightarrow> col X Y Z\\<close> \\<open>C \\<in> line_ext (line E F) \\<Longrightarrow> col X Y Z\\<close> \n            \\<open>P = A \\<Longrightarrow> col X Y Z\\<close> \\<open>P = C \\<Longrightarrow> col X Y Z\\<close> \\<open>P = Q \\<Longrightarrow> col X Y Z\\<close> \\<open>P = R \\<Longrightarrow> col X Y Z\\<close> \n            \\<open>inter (line B C) (line E F) = inter (line A C) (line E F) \\<Longrightarrow> col X Y Z\\<close> \n            \\<open>Q = A \\<Longrightarrow> col X Y Z\\<close> \\<open>Q = C \\<Longrightarrow> col X Y Z\\<close> \\<open>Q = R \\<Longrightarrow> col X Y Z\\<close> \\<open>Q = W \\<Longrightarrow> col X Y Z\\<close> \\<open>R = A \\<Longrightarrow> col X Y Z\\<close> \n            \\<open>R = C \\<Longrightarrow> col X Y Z\\<close> \\<open>R = W \\<Longrightarrow> col X Y Z\\<close> \\<open>\\<lbrakk>distinct [P,Q,R,A,C,W]; C \\<notin> line_ext (line E F); A \\<notin> line_ext (line D E); line B C \\<noteq> line A B; line E F \\<noteq> line A F; A \\<notin> line_ext (line C D); inter (line B C) (line E F) \\<noteq> inter (line A C) (line E F)\\<rbrakk> \\<Longrightarrow> col (inter (line A C) (line E F)) (inter (line C D) (line B F)) (inter (line A B) (line D E))\\<close> \n            \\<open>line B C = line A B \\<Longrightarrow> col X Y Z\\<close> \\<open>line E F = line A F \\<Longrightarrow> col X Y Z\\<close> distinct6_def line_comm)\n     qed\n     show \"is_pascal B A C D E F\"\n       using X_def Y_def Z_def \\<open>\\<lbrakk>distinct [B,A,C,D,E,F]; line A C \\<noteq> line E F; line C D \\<noteq> line B F; line B A \\<noteq> line D E; line B C = line E F\\<rbrakk> \\<Longrightarrow> col X Y Z\\<close> \n         \\<open>\\<lbrakk>distinct [B,A,C,D,E,F]; line A C \\<noteq> line E F; line C D \\<noteq> line B F; line B A \\<noteq> line D E; line B C \\<noteq> line E F; line C D \\<noteq> line A F\\<rbrakk> \\<Longrightarrow> col X Y Z\\<close> \n         \\<open>\\<lbrakk>distinct [B,A,C,D,E,F]; line A C \\<noteq> line E F; line C D \\<noteq> line B F; line B A \\<noteq> line D E; line C D = line A F\\<rbrakk> \\<Longrightarrow> col X Y Z\\<close> \n         is_pascal_def \n       by force\n  qed\n  thus \"pascal_prop\" using pascal_prop_def \n    by auto\nqed\n\nlemma is_pascal_under_alternate_vertices:\n  assumes \"pascal_prop\" and \"is_pascal A B C A' B' C'\"\n  shows \"is_pascal A B' C A' B C'\"\n  using assms pascal_prop_def is_pascal_rot_CW \n  by presburger\n\nlemma col_inter:\n  assumes \"distinct [A,B,C,D,E,F]\" and \"col A B C\" and \"col D E F\"\n  shows \"inter (line B C) (line E F) = inter (line A B) (line D E)\"\n  by (smt assms ax_uniqueness col_def distinct6_def incidA_lAB incidB_lAB)\n\nlemma pascal_pappus1:\n  assumes \"pascal_prop\"\n  shows \"is_pappus1 A B C A' B' C' P Q R\"\nproof-\n  define a1 a2 a3 a4 a5 a6 where \"a1 = distinct [A,B,C,A',B',C']\"  and \"a2 = col A B C\" and \n\"a3 = col A' B' C'\" and \"a4 = is_a_proper_intersec P A B' A' B\" and \"a5 = is_a_proper_intersec Q B C' B' C\" \nand \"a6 = is_a_proper_intersec R A C' A' C\" \n  (* i.e. we have assumed a Pappus configuration *)\n  have \"inter (line B C) (line B' C') = inter (line A B) (line A' B')\" if a1 a2 a3 a4 a5 a6\n    using a1_def a2_def a3_def col_inter that(1) that(2) that(3) \n    by blast\n  then have \"is_pascal A B C A' B' C'\" if a1 a2 a3 a4 a5 a6\n    using a1_def col_ABA is_pascal_def that(1) that(2) that(3) that(4) that(5) that(6) \n    by auto\n  then have \"is_pascal A B' C A' B C'\" if a1 a2 a3 a4 a5 a6\n    using assms is_pascal_under_alternate_vertices that(1) that(2) that(3) that(4) that(5) that(6) \n    by blast\n  then have \"col P Q R\" if a1 a2 a3 a4 a5 a6\n    by (smt a1_def a4_def a5_def a6_def ax_uniqueness col_def distinct6_def incidB_lAB incid_inter_left \n        incid_inter_right is_a_proper_intersec_def is_pascal_def line_comm that(1) that(2) that(3) \n        that(4) that(5) that(6))\n  show \"is_pappus1 A B C A' B' C' P Q R\"\n    by (simp add: \\<open>\\<lbrakk>a1; a2; a3; a4; a5; a6\\<rbrakk> \\<Longrightarrow> col P Q R\\<close> a1_def a2_def a3_def a4_def a5_def a6_def \n        is_pappus1_def)\nqed\n\nlemma pascal_pappus:\n  assumes \"pascal_prop\"\n  shows \"is_pappus\"                           \n  by (simp add: assms is_pappus_def pappus12 pascal_pappus1)\n\ntheorem pappus_iff_pascal: \"is_pappus = pascal_prop\"\n  using pappus_pascal pascal_pappus \n  by blast\n\nend\n\nend\n\n\n\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/Projective_Geometry/Pascal_Property.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8807970842359877, "lm_q2_score": 0.837619959279793, "lm_q1q2_score": 0.7377732178315084}}
{"text": "theory Chap1_Lemma1\n  imports Main Chap1_Properties\nbegin\n\nsection \"commutative monoid\"\n\n\ntypedecl m\n\nconsts m_mult :: \"m \\<Rightarrow> m \\<Rightarrow> m\" (infixr \"\\<^bold>\\<sqdot>\\<^sub>m\" 55)\nconsts m_one :: \"m\" (\"\\<^bold>1\\<^sub>m\")\nconsts m_ord :: \"m \\<Rightarrow> m \\<Rightarrow> bool\" (infixr \"\\<^bold>\\<le>\\<^sub>m\" 50)\n\naxiomatization where\nm_assoc: \"assoc (\\<^bold>\\<sqdot>\\<^sub>m)\" and\nm_commu: \"commu (\\<^bold>\\<sqdot>\\<^sub>m)\" and\nm_idemp: \"unitE (\\<^bold>\\<sqdot>\\<^sub>m) \\<^bold>1\\<^sub>m\"\n\n\n(* definition even  \\<equiv>\\<forall>x. \\<exists> y:: m. Prod (Suc Suc Zero) y = x \\<longrightarrow>   *)\n\n(* \\<forall> x1 x2 x3. even x1 x2 x3 \\<longrightarrow> assoc x1 x2 x3 *)\n\n\nsection \"commutative residuated lattice\"\n\n\nsubsection \"Definitions\"\n\ntype_synonym p = \"m \\<Rightarrow> bool\"\ntype_synonym p_op = \"p \\<Rightarrow> p \\<Rightarrow> p\"\n\ndefinition p_meet :: p_op (infixr \"\\<^bold>\\<inter>\\<^sub>p\" 55) where\n\"X \\<^bold>\\<inter>\\<^sub>p Y \\<equiv> \\<lambda> m. X m \\<and> Y m\" \ndefinition p_join :: p_op (infixr \"\\<^bold>\\<union>\\<^sub>p\" 55) where\n\"X \\<^bold>\\<union>\\<^sub>p Y \\<equiv> \\<lambda> m. X m \\<or> Y m\"\ndefinition p_mult :: p_op (infixr \"\\<^bold>\\<star>\\<^sub>p\" 55) where\n\"X \\<^bold>\\<star>\\<^sub>p Y \\<equiv> \\<lambda> m. \\<exists> a b. X a \\<and> Y b \\<and> (a \\<^bold>\\<sqdot>\\<^sub>m b) = m\"\ndefinition p_impl :: p_op (infixr \"\\<^bold>\\<Rrightarrow>\\<^sub>p\" 55) where\n\"X \\<^bold>\\<Rrightarrow>\\<^sub>p Y \\<equiv> \\<lambda> m. \\<forall> c. X c \\<longrightarrow> Y (m \\<^bold>\\<sqdot>\\<^sub>m c)\"\nconsts p_zero :: \"p\" (\"\\<^bold>0\\<^sub>p\")\ndefinition p_one :: \"p\" (\"\\<^bold>1\\<^sub>p\") where\n\"\\<^bold>1\\<^sub>p \\<equiv> \\<lambda> m. m = (\\<^bold>1\\<^sub>m)\"\ndefinition p_bot :: \"p\" (\"\\<^bold>\\<bottom>\\<^sub>p\") where\n\"\\<^bold>\\<bottom>\\<^sub>p \\<equiv> \\<lambda> m. False\"\ndefinition p_top :: \"p\" (\"\\<^bold>\\<top>\\<^sub>p\") where\n\"\\<^bold>\\<top>\\<^sub>p \\<equiv> \\<lambda> m. True\"\ndefinition p_ord ::\"p \\<Rightarrow> p \\<Rightarrow> bool\" (infixr\"\\<^bold>\\<le>\\<^sub>p\"51) where \n(*\"p1 \\<^bold>\\<le>\\<^sub>p p2 \\<equiv> \\<forall> m. (p1 \\<^bold>\\<inter>\\<^sub>p p2) m \\<longleftrightarrow> p1 m\"*)\n(* this might be also contravariant *)\n\"p1 \\<^bold>\\<le>\\<^sub>p p2 \\<equiv> \\<forall> m. (p1 m \\<longrightarrow> p2 m)\"\n\n\n\nsubsection \"Properties Proof\"\n\nsubsubsection \"commutative monoid with the unit 1\"\n(*\ndefinition \"commu Op \\<equiv> \\<forall> a b. Op a b = Op b a\"\ndefinition \"unitE Op One \\<equiv> \\<forall> a. Op a One = a\"\ndefinition \"assoc Op \\<equiv> \\<forall> x y z. Op (Op x y) z = Op x (Op y z)\"\n*)\n\nlemma p_commu_mult: \"commu (\\<^bold>\\<star>\\<^sub>p)\"\n  apply (unfold commu_def p_mult_def)\nproof (rule, rule, rule)\n  fix a b m\n  show \"(\\<exists>aa ba. a aa \\<and> b ba \\<and> aa \\<^bold>\\<sqdot>\\<^sub>m ba = m) = (\\<exists>aa ba. b aa \\<and> a ba \\<and> aa \\<^bold>\\<sqdot>\\<^sub>m ba = m)\" proof\n    show \"\\<exists>aa ba. a aa \\<and> b ba \\<and> aa \\<^bold>\\<sqdot>\\<^sub>m ba = m \\<Longrightarrow> \\<exists>aa ba. b aa \\<and> a ba \\<and> aa \\<^bold>\\<sqdot>\\<^sub>m ba = m\" proof -\n      assume 1: \"\\<exists>aa ba. a aa \\<and> b ba \\<and> aa \\<^bold>\\<sqdot>\\<^sub>m ba = m\"\n      then obtain aa ba where \"a aa \\<and> b ba \\<and> aa \\<^bold>\\<sqdot>\\<^sub>m ba = m\" by auto\n      hence \"a aa \\<and> b ba \\<and> ba \\<^bold>\\<sqdot>\\<^sub>m aa = m\" using commu_def m_commu by metis\n      thus \"\\<exists>aa ba. b aa \\<and> a ba \\<and> aa \\<^bold>\\<sqdot>\\<^sub>m ba = m\" by auto\n    qed\n    show \" \\<exists>aa ba. b aa \\<and> a ba \\<and> aa \\<^bold>\\<sqdot>\\<^sub>m ba = m \\<Longrightarrow> \\<exists>aa ba. a aa \\<and> b ba \\<and> aa \\<^bold>\\<sqdot>\\<^sub>m ba = m\"\n      by (meson commu_def m_commu) qed qed\nlemma p_unitE_mult: \"unitE (\\<^bold>\\<star>\\<^sub>p) (\\<^bold>1\\<^sub>p)\"\n  apply (unfold unitE_def p_one_def p_mult_def)\nproof (rule, rule)\n  fix a m\n  show \"(\\<exists>aa b. a aa \\<and> b = \\<^bold>1\\<^sub>m \\<and> aa \\<^bold>\\<sqdot>\\<^sub>m b = m) = a m\" proof\n    show \"\\<exists>aa b. a aa \\<and> b = \\<^bold>1\\<^sub>m \\<and> aa \\<^bold>\\<sqdot>\\<^sub>m b = m \\<Longrightarrow> a m\" proof -\n      assume 1: \"\\<exists>aa b. a aa \\<and> b = \\<^bold>1\\<^sub>m \\<and> aa \\<^bold>\\<sqdot>\\<^sub>m b = m\"\n      then obtain aa b where 2: \"a aa \\<and> b = \\<^bold>1\\<^sub>m \\<and> aa \\<^bold>\\<sqdot>\\<^sub>m b = m\" by auto\n      then have \"a aa \\<and> (aa \\<^bold>\\<sqdot>\\<^sub>m \\<^bold>1\\<^sub>m = m)\" by auto\n      then have \"a aa \\<and> (aa = m)\" using m_idemp unitE_def by metis\n      thus \"a m\" by auto qed\n  next\n    show \"a m \\<Longrightarrow> \\<exists>aa b. a aa \\<and> b = \\<^bold>1\\<^sub>m \\<and> aa \\<^bold>\\<sqdot>\\<^sub>m b = m\" using m_idemp by (simp add: unitE_def)\n  qed qed\nlemma p_assoc_mult: \"assoc (\\<^bold>\\<star>\\<^sub>p)\"\n  apply (unfold assoc_def p_mult_def) \nproof (rule, rule, rule, rule)\n  fix x y z m\n  show \"(\\<exists>a b. (\\<exists>aa b. x aa \\<and> y b \\<and> aa \\<^bold>\\<sqdot>\\<^sub>m b = a) \\<and> z b \\<and> a \\<^bold>\\<sqdot>\\<^sub>m b = m) = (\\<exists>a b. x a \\<and> (\\<exists>a ba. y a \\<and> z ba \\<and> a \\<^bold>\\<sqdot>\\<^sub>m ba = b) \\<and> a \\<^bold>\\<sqdot>\\<^sub>m b = m)\"\n  proof\n    show \"\\<exists>a b. (\\<exists>aa b. x aa \\<and> y b \\<and> aa \\<^bold>\\<sqdot>\\<^sub>m b = a) \\<and> z b \\<and> a \\<^bold>\\<sqdot>\\<^sub>m b = m \\<Longrightarrow> \\<exists>a b. x a \\<and> (\\<exists>a ba. y a \\<and> z ba \\<and> a \\<^bold>\\<sqdot>\\<^sub>m ba = b) \\<and> a \\<^bold>\\<sqdot>\\<^sub>m b = m\"\n    proof -\n      assume 1: \"\\<exists>a b. (\\<exists>aa bb. x aa \\<and> y bb \\<and> aa \\<^bold>\\<sqdot>\\<^sub>m bb = a) \\<and> z b \\<and> a \\<^bold>\\<sqdot>\\<^sub>m b = m\"\n      then obtain a b aa bb where 3: \"x aa \\<and> y bb \\<and> aa \\<^bold>\\<sqdot>\\<^sub>m bb = a \\<and> z b \\<and> a \\<^bold>\\<sqdot>\\<^sub>m b = m\" by auto\n      hence \"x aa \\<and> y bb \\<and> z b \\<and> (aa \\<^bold>\\<sqdot>\\<^sub>m bb) \\<^bold>\\<sqdot>\\<^sub>m b = m\" by auto\n      hence \"x aa \\<and> y bb \\<and> z b \\<and> aa \\<^bold>\\<sqdot>\\<^sub>m (bb \\<^bold>\\<sqdot>\\<^sub>m b) = m\" using m_assoc assoc_def by metis\n      hence \"\\<exists> aa b' bb b. x aa \\<and> y bb \\<and> z b \\<and> bb \\<^bold>\\<sqdot>\\<^sub>m b = b' \\<and> z b \\<and> aa \\<^bold>\\<sqdot>\\<^sub>m b' = m\" by blast\n      thus \"\\<exists>aa b'. x aa \\<and> (\\<exists>bb b. y bb \\<and> z b \\<and> bb \\<^bold>\\<sqdot>\\<^sub>m b = b') \\<and> aa \\<^bold>\\<sqdot>\\<^sub>m b' = m\" by auto qed\n  next\n    show \"\\<exists>a b. x a \\<and> (\\<exists>a ba. y a \\<and> z ba \\<and> a \\<^bold>\\<sqdot>\\<^sub>m ba = b) \\<and> a \\<^bold>\\<sqdot>\\<^sub>m b = m \\<Longrightarrow> \\<exists>a b. (\\<exists>aa b. x aa \\<and> y b \\<and> aa \\<^bold>\\<sqdot>\\<^sub>m b = a) \\<and> z b \\<and> a \\<^bold>\\<sqdot>\\<^sub>m b = m\" \n      by (metis assoc_def m_assoc) qed qed\n\n\n\nsubsubsection \"bounded lattice for Meet\"\n\n(*\ndefinition \"commu Op \\<equiv> \\<forall> a b. Op a b = Op b a\"\ndefinition \"assoc Op \\<equiv> \\<forall> x y z. Op (Op x y) z = Op x (Op y z)\"\ndefinition \"idemp Op \\<equiv> \\<forall> a. Op a a = a\"\ndefinition \"great Op Top \\<equiv> extre Op Top\"\n*)\n\nlemma p_commu_meet: \"commu (\\<^bold>\\<inter>\\<^sub>p)\" \n  apply (unfold commu_def p_meet_def)\nproof (rule, rule, rule)\n  fix a b :: p fix  m :: m\n  show \"(a m \\<and> b m) = (b m \\<and> a m)\" by auto qed\nlemma p_assoc_meet: \"assoc (\\<^bold>\\<inter>\\<^sub>p)\" \n  apply (unfold assoc_def p_meet_def)\nproof (rule, rule, rule, rule)\n  fix x y z :: p fix m :: m\n  show \"((x m \\<and> y m) \\<and> z m) = (x m \\<and> y m \\<and> z m)\" by simp qed\nlemma p_idemp_meet: \"idemp (\\<^bold>\\<inter>\\<^sub>p)\" \n  apply (unfold idemp_def p_meet_def) proof (rule, rule)\n  fix a :: p fix m :: m\n  show \"(a m \\<and> a m) = a m\"  by simp qed\nlemma p_great_meet: \"great (\\<^bold>\\<inter>\\<^sub>p) (\\<^bold>\\<top>\\<^sub>p)\"\n  apply (unfold great_def extre_def p_meet_def p_top_def) proof (rule, rule)\n  fix a :: p fix m :: m\n  show \"(a m \\<and> True) = a m\" by simp qed\n\n\n\nsubsubsection \"bounded lattice for Join\"\n\n(*\ndefinition \"commu Op \\<equiv> \\<forall> a b. Op a b = Op b a\"\ndefinition \"assoc Op \\<equiv> \\<forall> x y z. Op (Op x y) z = Op x (Op y z)\"\ndefinition \"idemp Op \\<equiv> \\<forall> a. Op a a = a\"\ndefinition \"least Op Top \\<equiv> extre Op Top\"\n*)\n\nlemma p_commu_join: \"commu (\\<^bold>\\<union>\\<^sub>p)\" \n  apply (unfold commu_def p_join_def)\nproof (rule, rule, rule)\n  fix a b :: p fix  m :: m\n  show \"(a m \\<or> b m) = (b m \\<or> a m)\" by auto qed\nlemma p_assoc_join: \"assoc (\\<^bold>\\<union>\\<^sub>p)\" \n  apply (unfold assoc_def p_join_def)\nproof (rule, rule, rule, rule)\n  fix x y z :: p fix m :: m\n  show \"((x m \\<or> y m) \\<or> z m) = (x m \\<or> y m \\<or> z m)\" by simp qed\nlemma p_idemp_join: \"idemp (\\<^bold>\\<union>\\<^sub>p)\" \n  apply (unfold idemp_def p_join_def) proof (rule, rule)\n  fix a :: p fix m :: m\n  show \"(a m \\<or> a m) = a m\"  by simp qed\nlemma p_least_join: \"least (\\<^bold>\\<union>\\<^sub>p) (\\<^bold>\\<bottom>\\<^sub>p)\"\n  apply (unfold least_def extre_def p_join_def p_bot_def) proof (rule, rule)\n  fix a :: p fix m :: m\n  show \"(a m \\<or> False) = a m\" by simp qed\n\n\n\nsubsubsection \"bounded lattice for Join and Meet\"\n\n(*definition \"absor Op1 Op2 \\<equiv> \\<forall> a b. Op1 a (Op2 a b) = a\"*)\n\nlemma p_absorb_meetjoin: \"absorb (\\<^bold>\\<inter>\\<^sub>p) (\\<^bold>\\<union>\\<^sub>p)\"\n  apply (unfold absorb_def p_meet_def p_join_def) proof (rule, rule, rule)\n  fix a b :: p fix m :: m\n  show \"(a m \\<and> (a m \\<or> b m)) = a m\" by auto qed\nlemma p_absorb_joinmeet: \"absorb (\\<^bold>\\<union>\\<^sub>p) (\\<^bold>\\<inter>\\<^sub>p)\" \n  apply (unfold absorb_def p_meet_def p_join_def) proof (rule, rule, rule)\n  fix a b :: p fix m :: m\n  show \"(a m \\<or> a m \\<and> b m) = a m\" by auto qed\n\n\nsubsubsection \"residuated lattice\"\n\nlemma p_resid_law: \"resid (\\<^bold>\\<le>\\<^sub>p) (\\<^bold>\\<star>\\<^sub>p) (\\<^bold>\\<Rrightarrow>\\<^sub>p)\"\n  apply (unfold resid_def p_mult_def p_impl_def p_ord_def) \n(*  by (metis commu_def m_commu)*)\nproof (rule, rule, rule)\n  fix x y z :: p\n  show \"(\\<forall>m. (\\<exists>a b. x a \\<and> y b \\<and> a \\<^bold>\\<sqdot>\\<^sub>m b = m) \\<longrightarrow> z m) = (\\<forall>a. x a \\<longrightarrow> (\\<forall>b. y b \\<longrightarrow> z (a \\<^bold>\\<sqdot>\\<^sub>m b)))\" proof (rule)\n    show \" \\<forall>m. (\\<exists>a' b'. x a' \\<and> y b' \\<and> a' \\<^bold>\\<sqdot>\\<^sub>m b' = m) \\<longrightarrow> z m \\<Longrightarrow> \\<forall>a. x a \\<longrightarrow> (\\<forall>b. y b \\<longrightarrow> z (a \\<^bold>\\<sqdot>\\<^sub>m b))\" proof (rule, rule, rule, rule)\n      fix a b :: m\n      assume 1: \"\\<forall>m. (\\<exists>a' b'. x a' \\<and> y b' \\<and> a' \\<^bold>\\<sqdot>\\<^sub>m b' = m) \\<longrightarrow> z m\"\n      assume 2: \"x a\"\n      assume 3: \"y b\"\n      show \"z (a \\<^bold>\\<sqdot>\\<^sub>m b)\" proof -\n        let ?m' = \"a \\<^bold>\\<sqdot>\\<^sub>m b\"\n        from 2 3 have \"x a \\<and> y b \\<and> a \\<^bold>\\<sqdot>\\<^sub>m b = ?m'\" by simp\n        hence \"\\<exists>a' b'. x a' \\<and> y b' \\<and> a' \\<^bold>\\<sqdot>\\<^sub>m b' = ?m'\" by auto\n        hence \"z ?m'\" using 1 by simp\n        thus \"z (a \\<^bold>\\<sqdot>\\<^sub>m b)\" by simp\n      qed\n    qed\n  next\n    show \"\\<forall>a. x a \\<longrightarrow> (\\<forall>b. y b \\<longrightarrow> z (a \\<^bold>\\<sqdot>\\<^sub>m b)) \\<Longrightarrow> \\<forall>m. (\\<exists>a b. x a \\<and> y b \\<and> a \\<^bold>\\<sqdot>\\<^sub>m b = m) \\<longrightarrow> z m\"\n      by auto\n  qed qed\n\n\n\n\n  \n\n  \n  \n  subsubsection \"complete lattice\"\n\n(* how to state this ? *)\n\nabbreviation \"upper_bound U S \\<equiv> \\<forall>X. (S X) \\<longrightarrow> X \\<^bold>\\<preceq> U\"\n\nabbreviation \n\"is_supremum U S \\<equiv> upper_bound U S \\<and> (\\<forall>X. upper_bound X S \\<longrightarrow> U \\<^bold>\\<preceq> X)\"\n\nlemma sup_char: \"is_supremum \\<^bold>\\<Or>S S\"\n\nabbreviation \"upper_bound U \\<equiv> \\<forall> X.  X \\<^bold>\\<preceq> U\"\n\n\nend", "meta": {"author": "jhln", "repo": "Bamberg", "sha": "73c62c87b4c3a5f39c211d4162f9915390f4cd64", "save_path": "github-repos/isabelle/jhln-Bamberg", "path": "github-repos/isabelle/jhln-Bamberg/Bamberg-73c62c87b4c3a5f39c211d4162f9915390f4cd64/Chap1_Lemma1.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970811069351, "lm_q2_score": 0.837619961306541, "lm_q1q2_score": 0.7377732169957053}}
{"text": "(*\n  File: Graph.thy\n  Author: Bohua Zhan\n\n  Basics of graph of functions (as represented by a set of ordered pairs).\n*)\n\ntheory Graph\n  imports Set\nbegin\n\nsection \\<open>Graphs\\<close>\n\ndefinition is_graph :: \"i \\<Rightarrow> o\" where [rewrite]:\n  \"is_graph(G) \\<longleftrightarrow> (\\<forall>x\\<in>G. x = \\<langle>fst(x),snd(x)\\<rangle>)\"\n\nlemma is_graphE [forward]: \"is_graph(G) \\<Longrightarrow> x \\<in> G \\<Longrightarrow> x = \\<langle>fst(x),snd(x)\\<rangle>\" by auto2\nsetup {* del_prfstep_thm_eqforward @{thm is_graph_def} *}\n\ndefinition gr_source :: \"i \\<Rightarrow> i\" where [rewrite]:\n  \"gr_source(G) = {fst(p). p \\<in> G}\"\nlemma gr_sourceI [typing2]: \"\\<langle>a,b\\<rangle> \\<in> G \\<Longrightarrow> a \\<in> gr_source(G)\" by auto2\nlemma gr_sourceE [backward]: \"is_graph(G) \\<Longrightarrow> a \\<in> gr_source(G) \\<Longrightarrow> \\<exists>b. \\<langle>a,b\\<rangle>\\<in>G\" by auto2\nsetup {* del_prfstep_thm @{thm gr_source_def} *}\n\ndefinition gr_target :: \"i \\<Rightarrow> i\" where [rewrite]:\n  \"gr_target(G) = {snd(p). p \\<in> G}\"\nlemma gr_targetI [typing2]: \"\\<langle>a,b\\<rangle> \\<in> G \\<Longrightarrow> b \\<in> gr_target(G)\" by auto2\nlemma gr_targetE [backward]: \"is_graph(G) \\<Longrightarrow> b \\<in> gr_target(G) \\<Longrightarrow> \\<exists>a. \\<langle>a,b\\<rangle>\\<in>G\" by auto2\nsetup {* del_prfstep_thm @{thm gr_target_def} *}\n\ndefinition gr_field :: \"i \\<Rightarrow> i\" where [rewrite]:\n  \"gr_field(G) = gr_source(G) \\<union> gr_target(G)\"\nlemma gr_fieldI1 [typing2]: \"\\<langle>a,b\\<rangle> \\<in> G \\<Longrightarrow> a \\<in> gr_field(G)\" by auto2\nlemma gr_fieldI2 [typing2]: \"\\<langle>a,b\\<rangle> \\<in> G \\<Longrightarrow> b \\<in> gr_field(G)\" by auto2\n\ndefinition gr_id :: \"i \\<Rightarrow> i\" where [rewrite]:\n  \"gr_id(A) = {\\<langle>a,a\\<rangle>. a \\<in> A}\"\nlemma gr_id_is_graph [forward]: \"is_graph(gr_id(A))\" by auto2\nlemma gr_idI [typing2]: \"a \\<in> A \\<Longrightarrow> \\<langle>a,a\\<rangle> \\<in> gr_id(A)\" by auto2\nlemma gr_id_iff [rewrite]: \"p \\<in> gr_id(A) \\<longleftrightarrow> (p\\<in>A\\<times>A \\<and> fst(p) = snd(p))\" by auto2\nsetup {* del_prfstep_thm @{thm gr_id_def} *}\n\ndefinition gr_comp :: \"i \\<Rightarrow> i \\<Rightarrow> i\"  (infixr \"\\<circ>\\<^sub>g\" 60) where [rewrite]:\n  \"s \\<circ>\\<^sub>g r = {p\\<in>gr_source(r)\\<times>gr_target(s). \\<exists>z. \\<langle>fst(p),z\\<rangle>\\<in>r \\<and> \\<langle>z,snd(p)\\<rangle>\\<in>s}\"\n\nlemma gr_comp_is_graph [forward]: \"is_graph(s \\<circ>\\<^sub>g r)\" by auto2\nlemma gr_compI [backward2]:\n  \"\\<langle>x,y\\<rangle> \\<in> r \\<Longrightarrow> \\<langle>y,z\\<rangle> \\<in> s \\<Longrightarrow> \\<langle>x,z\\<rangle> \\<in> s \\<circ>\\<^sub>g r\" by auto2\nlemma gr_compE [forward]:\n  \"p \\<in> s \\<circ>\\<^sub>g r \\<Longrightarrow> \\<exists>y. \\<langle>fst(p),y\\<rangle> \\<in> r \\<and> \\<langle>y,snd(p)\\<rangle> \\<in> s\" by auto2\nsetup {* del_prfstep_thm @{thm gr_comp_def} *}\n\nsection \\<open>Evaluation on a graph\\<close>\n\ndefinition is_func_graph :: \"i \\<Rightarrow> i \\<Rightarrow> o\" where [rewrite]:\n  \"is_func_graph(G,X) \\<longleftrightarrow> is_graph(G) \\<and> gr_source(G) = X \\<and> (\\<forall>a\\<in>X. \\<exists>!y. \\<langle>a,y\\<rangle> \\<in> G)\"\n  \ndefinition func_graphs :: \"i \\<Rightarrow> i \\<Rightarrow> i\" where [rewrite]:\n  \"func_graphs(X,Y) = {G\\<in>Pow(X\\<times>Y). is_func_graph(G,X)}\"\n\ndefinition graph_eval :: \"i \\<Rightarrow> i \\<Rightarrow> i\" where [rewrite]:\n  \"graph_eval(G,x) = (THE y. \\<langle>x,y\\<rangle> \\<in> G)\"\n\nlemma is_func_graphD [forward]:\n  \"is_func_graph(G,X) \\<Longrightarrow> is_graph(G) \\<and> gr_source(G) = X\" by auto2\n\nlemma is_func_graphD2 [forward]:\n  \"is_func_graph(G,X) \\<Longrightarrow> x \\<in> X \\<Longrightarrow> \\<langle>x, graph_eval(G,x)\\<rangle> \\<in> G\" by auto2\n\nlemma is_func_graphD3 [forward]:\n  \"is_func_graph(G,X) \\<Longrightarrow> \\<langle>x,y\\<rangle> \\<in> G \\<Longrightarrow> x \\<in> X \\<Longrightarrow> graph_eval(G,x) = y\" by auto2\n\nlemma graph_eq [backward1]:\n  \"is_func_graph(G,X) \\<Longrightarrow> is_func_graph(H,X) \\<Longrightarrow>\n   \\<forall>x\\<in>X. graph_eval(G,x) = graph_eval(H,x) \\<Longrightarrow> G = H\" by auto2\n\nlemma is_func_graph_cons:\n  \"is_func_graph(G,X) \\<Longrightarrow> a \\<notin> X \\<Longrightarrow> is_func_graph(cons(\\<langle>a,b\\<rangle>,G),cons(a,X))\"\n@proof\n  @let \"H = cons(\\<langle>a,b\\<rangle>,G)\"\n  @have \"is_graph(H)\"\n  @have \"\\<forall>x\\<in>gr_source(H). x \\<in> cons(a,X)\" @with\n    @obtain y where \"\\<langle>x,y\\<rangle> \\<in> H\"\n  @end\n  @have \"\\<forall>c\\<in>cons(a,X). \\<exists>!y. \\<langle>c,y\\<rangle> \\<in> H\" @with\n    @case \"c = a\"\n  @end\n@qed\n\nlemma is_func_graph_empty: \"is_func_graph(\\<emptyset>,\\<emptyset>)\"\n@proof\n  @have \"is_graph(\\<emptyset>)\"\n  @have \"\\<forall>x\\<in>gr_source(\\<emptyset>). x \\<in> \\<emptyset>\" @with\n    @obtain y where \"\\<langle>x,y\\<rangle> \\<in> \\<emptyset>\"\n  @end\n@qed\n\nsetup {* del_prfstep_thm_eqforward @{thm is_func_graph_def} *}\nsetup {* del_prfstep_thm @{thm graph_eval_def} *}\n\nsection \\<open>Graphs from a relation\\<close>\n\ndefinition rel_graph :: \"i \\<Rightarrow> (i \\<Rightarrow> i \\<Rightarrow> o) \\<Rightarrow> i\" where [rewrite]:\n  \"rel_graph(S,R) = {p\\<in>S\\<times>S. R(fst(p),snd(p))}\"\n\nlemma rel_graph_mem [typing]: \"rel_graph(S,R) \\<in> Pow(S\\<times>S)\" by auto2\nlemma rel_graph_iff [rewrite]: \"\\<langle>x,y\\<rangle> \\<in> rel_graph(S,R) \\<longleftrightarrow> (x \\<in> S \\<and> y \\<in> S \\<and> R(x,y))\" by auto2\n\nsetup {* del_prfstep_thm @{thm rel_graph_def} *}\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/Graph.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8807970748488297, "lm_q2_score": 0.8376199633332891, "lm_q1q2_score": 0.7377732135389451}}
{"text": "theory Design_Basics imports Main Multisets_Extras \"HOL-Library.Disjoint_Sets\"\nbegin\n\nsection \\<open> Design Theory Basics\\<close>\ntext \\<open> All definitions in this section reference the handbook of combinatorial designs\n \\cite{colbournHandbookCombinatorialDesigns2007}\\<close>\n\nsubsection \\<open> Initial setup \\<close>\n\ntext \\<open> Enable coercion of nats to ints to aid with reasoning on design properties \\<close>\ndeclare [[coercion_enabled]]\ndeclare [[coercion \"of_nat :: nat \\<Rightarrow> int\"]]\n\nsubsection \\<open> Incidence System \\<close>\n\ntext \\<open>An incidence system is defined to be a wellformed set system. i.e. each block is a subset\nof the base point set. Alternatively, an incidence system can be looked at as the point set\nand an incidence relation which indicates if they are in the same block \\<close>\n\nlocale incidence_system = \n  fixes point_set :: \"'a set\" (\"\\<V>\")\n  fixes block_collection :: \"'a set multiset\" (\"\\<B>\")\n  assumes wellformed: \"b \\<in># \\<B> \\<Longrightarrow> b \\<subseteq> \\<V>\"\nbegin\n\ndefinition \"\\<I> \\<equiv> { (x, b) . b \\<in># \\<B> \\<and> x \\<in> b}\" (* incidence relation *)\n\ndefinition incident :: \"'a \\<Rightarrow> 'a set \\<Rightarrow> bool\" where\n\"incident p b \\<equiv> (p, b) \\<in> \\<I>\"\n\ntext \\<open>Defines common notation used to indicate number of points ($v$) and number of blocks ($b$) \\<close>\nabbreviation \"\\<v> \\<equiv> card \\<V>\"\n\nabbreviation \"\\<b> \\<equiv> size \\<B>\"\n\ntext \\<open>Basic incidence lemmas \\<close>\n\nlemma incidence_alt_def: \n  assumes \"p \\<in> \\<V>\"\n  assumes \"b \\<in># \\<B>\"\n  shows \"incident p b \\<longleftrightarrow> p \\<in> b\"\n  by (auto simp add: incident_def \\<I>_def assms)\n\nlemma wf_invalid_point: \"x \\<notin> \\<V> \\<Longrightarrow> b \\<in># \\<B> \\<Longrightarrow> x \\<notin> b\"\n  using wellformed by auto\n\nlemma block_set_nempty_imp_block_ex: \"\\<B> \\<noteq> {#} \\<Longrightarrow> \\<exists> bl . bl \\<in># \\<B>\"\n  by auto\n\ntext \\<open>Abbreviations for all incidence systems \\<close>\nabbreviation multiplicity :: \"'a set \\<Rightarrow> nat\" where\n\"multiplicity b \\<equiv> count \\<B> b\"\n\nabbreviation incomplete_block :: \"'a set \\<Rightarrow> bool\" where\n\"incomplete_block bl \\<equiv> card bl < card \\<V> \\<and> bl \\<in># \\<B>\"\n\nlemma incomplete_alt_size: \"incomplete_block bl \\<Longrightarrow> card bl < \\<v>\" \n  by simp\n\nlemma incomplete_alt_in: \"incomplete_block bl \\<Longrightarrow> bl \\<in># \\<B>\"\n  by simp\n\nlemma incomplete_alt_imp[intro]: \"card bl < \\<v> \\<Longrightarrow> bl \\<in># \\<B> \\<Longrightarrow> incomplete_block bl\"\n  by simp\n\ndefinition design_support :: \"'a set set\" where\n\"design_support \\<equiv> set_mset \\<B>\"\n\nend\n\nsubsection \\<open> Finite Incidence Systems \\<close>\n\ntext \\<open> These simply require the point set to be finite.\nAs multisets are only defined to be finite, it is implied that the block set must be finite already \\<close>\n\nlocale finite_incidence_system = incidence_system + \n  assumes finite_sets: \"finite \\<V>\"\nbegin\n\nlemma finite_blocks: \"b \\<in># \\<B> \\<Longrightarrow> finite b\"\n  using wellformed finite_sets finite_subset by blast \n\nlemma mset_points_distinct: \"distinct_mset (mset_set \\<V>)\"\n  using finite_sets by (simp add: distinct_mset_def)\n\nlemma mset_points_distinct_diff_one: \"distinct_mset (mset_set (\\<V> - {x}))\"\n  by (meson count_mset_set_le_one distinct_mset_count_less_1)\n\nlemma finite_design_support: \"finite (design_support)\"\n  using design_support_def by auto \n\nlemma block_size_lt_order: \"bl \\<in># \\<B> \\<Longrightarrow> card bl \\<le> card \\<V>\"\n  using wellformed by (simp add: card_mono finite_sets)  \n\nend\n\nsubsection \\<open> Designs \\<close>\n\ntext \\<open> There are many varied definitions of a design in literature. However, the most\ncommonly accepted definition is a finite point set, $V$ and collection of blocks $B$, where\nno block in $B$ can be empty \\<close>\nlocale design = finite_incidence_system +\n  assumes blocks_nempty: \"bl \\<in># \\<B> \\<Longrightarrow> bl \\<noteq> {}\"\nbegin\n\nlemma wf_design: \"design \\<V> \\<B>\"  by intro_locales\n\nlemma wf_design_iff: \"bl \\<in># \\<B> \\<Longrightarrow> design \\<V> \\<B> \\<longleftrightarrow> (bl \\<subseteq> \\<V> \\<and> finite \\<V> \\<and> bl \\<noteq> {})\"\n  using blocks_nempty wellformed finite_sets\n  by (simp add: wf_design) \n\ntext \\<open>Reasoning on non empty properties and non zero parameters\\<close>\nlemma blocks_nempty_alt: \"\\<forall> bl \\<in># \\<B>. bl \\<noteq> {}\"\n  using blocks_nempty by auto\n\nlemma block_set_nempty_imp_points: \"\\<B> \\<noteq> {#} \\<Longrightarrow> \\<V> \\<noteq> {}\"\n  using wf_design wf_design_iff by auto\n\nlemma b_non_zero_imp_v_non_zero: \"\\<b> > 0 \\<Longrightarrow> \\<v> > 0\"\n  using block_set_nempty_imp_points finite_sets by fastforce\n\nlemma v_eq0_imp_b_eq_0: \"\\<v> = 0 \\<Longrightarrow> \\<b> = 0\"\n  using b_non_zero_imp_v_non_zero by auto\n\ntext \\<open> Size lemmas \\<close>\nlemma block_size_lt_v: \"bl \\<in># \\<B> \\<Longrightarrow> card bl \\<le> \\<v>\"\n  by (simp add: card_mono finite_sets wellformed)\n\nlemma block_size_gt_0: \"bl \\<in># \\<B> \\<Longrightarrow> card bl > 0\"\n  using finite_sets blocks_nempty finite_blocks by fastforce\n\nlemma design_cart_product_size: \"size ((mset_set \\<V>) \\<times># \\<B>) = \\<v> * \\<b>\"\n  by (simp add: size_cartesian_product) \n\nend\n\ntext \\<open>Intro rules for design locale \\<close>\n\nlemma wf_design_implies: \n  assumes \"(\\<And> b . b \\<in># \\<B> \\<Longrightarrow> b \\<subseteq> V)\"\n  assumes \"\\<And> b . b \\<in># \\<B> \\<Longrightarrow> b \\<noteq> {}\"\n  assumes \"finite V\"\n  assumes \"\\<B> \\<noteq> {#}\"\n  assumes \"V \\<noteq> {}\"\n  shows \"design V \\<B>\"\n  using assms by (unfold_locales) simp_all\n\nlemma (in incidence_system) finite_sysI[intro]: \"finite \\<V> \\<Longrightarrow> finite_incidence_system \\<V> \\<B>\"\n  by (unfold_locales) simp_all\n\nlemma (in finite_incidence_system) designI[intro]: \"(\\<And> b. b \\<in># \\<B> \\<Longrightarrow> b \\<noteq> {}) \\<Longrightarrow> \\<B> \\<noteq> {#}\n     \\<Longrightarrow> \\<V> \\<noteq> {} \\<Longrightarrow> design \\<V> \\<B>\"\n  by (unfold_locales) simp_all\n\nsubsection \\<open> Core Property Definitions \\<close>\n\nsubsubsection \\<open> Replication Number\\<close>\n\ntext \\<open> The replication number for a point is the number of blocks that point is incident with \\<close>\n\ndefinition point_replication_number :: \"'a set multiset \\<Rightarrow> 'a \\<Rightarrow> nat\" (infix \"rep\" 75) where\n\"B rep x \\<equiv> size {#b \\<in># B . x \\<in> b#}\"\n\nlemma max_point_rep: \"B rep x \\<le> size B\"\n  using size_filter_mset_lesseq by (simp add: point_replication_number_def)\n\nlemma rep_number_g0_exists: \n  assumes \"B rep x > 0\" \n  obtains b where \"b \\<in># B\" and \"x \\<in> b\"\nproof -\n  have \"size {#b \\<in># B . x \\<in> b#} > 0\" using assms point_replication_number_def\n    by metis\n  thus ?thesis\n    by (metis filter_mset_empty_conv nonempty_has_size that) \nqed\n\nlemma rep_number_on_set_def: \"finite B \\<Longrightarrow> (mset_set B) rep x = card {b \\<in> B . x \\<in> b}\"\n  by (simp add: point_replication_number_def)\n\nlemma point_rep_number_split[simp]: \"(A + B) rep x = A rep x + B rep x\"\n  by (simp add: point_replication_number_def)\n\nlemma point_rep_singleton_val [simp]: \"x \\<in> b \\<Longrightarrow> {#b#} rep x = 1\"\n  by (simp add: point_replication_number_def)\n\nlemma point_rep_singleton_inval [simp]: \"x \\<notin> b \\<Longrightarrow> {#b#} rep x = 0\"\n  by (simp add: point_replication_number_def)\n\ncontext incidence_system\nbegin\n\nlemma point_rep_number_alt_def: \"\\<B> rep x = size {# b \\<in># \\<B> . x \\<in> b#}\"\n  by (simp add: point_replication_number_def)\n\nlemma rep_number_non_zero_system_point: \" \\<B> rep x > 0 \\<Longrightarrow> x \\<in> \\<V>\"\n  using rep_number_g0_exists wellformed\n  by (metis wf_invalid_point) \n\nlemma point_rep_non_existance [simp]: \"x \\<notin> \\<V> \\<Longrightarrow> \\<B> rep x = 0\"\n  using wf_invalid_point by (simp add:  point_replication_number_def filter_mset_empty_conv) \n\nlemma point_rep_number_inv: \"size {# b \\<in># \\<B> . x \\<notin> b #} = \\<b> - (\\<B> rep x)\"\nproof -\n  have \"\\<b> = size {# b \\<in># \\<B> . x \\<notin> b #} + size {# b \\<in># \\<B> . x \\<in> b #}\"\n    using multiset_partition by (metis add.commute size_union)  \n  thus ?thesis by (simp add: point_replication_number_def) \nqed\n\nlemma point_rep_num_inv_non_empty: \"(\\<B> rep x) < \\<b> \\<Longrightarrow> \\<B> \\<noteq> {#} \\<Longrightarrow> {# b \\<in># \\<B> . x \\<notin> b #} \\<noteq> {#}\"\n  by (metis diff_zero point_replication_number_def size_empty size_filter_neg verit_comp_simplify1(1))\n\nend\n\nsubsubsection \\<open>Point Index \\<close>\n\ntext \\<open>The point index of a subset of points in a design, is the number of times those points \noccur together in a block of the design\\<close>\ndefinition points_index :: \"'a set multiset \\<Rightarrow> 'a set \\<Rightarrow> nat\" (infix \"index\" 75) where\n\"B index ps \\<equiv> size {#b \\<in># B . ps \\<subseteq> b#}\"\n\nlemma points_index_empty [simp]: \"{#} index ps = 0\"\n  by (simp add: points_index_def)\n\nlemma point_index_distrib: \"(B1 + B2) index ps =  B1 index ps + B2 index ps\"\n  by (simp add: points_index_def)\n\nlemma point_index_diff: \"B1 index ps = (B1 + B2) index ps - B2 index ps\"\n  by (simp add: points_index_def)\n\nlemma points_index_singleton: \"{#b#} index ps = 1 \\<longleftrightarrow> ps \\<subseteq> b\"\n  by (simp add: points_index_def)\n\nlemma points_index_singleton_zero: \"\\<not> (ps \\<subseteq> b) \\<Longrightarrow> {#b#} index ps = 0\"\n  by (simp add: points_index_def)\n\nlemma points_index_sum: \"(\\<Sum>\\<^sub># B ) index ps = (\\<Sum>b \\<in># B . (b index ps))\"\n  using points_index_empty by (induction B) (auto simp add: point_index_distrib)\n\nlemma points_index_block_image_add_eq: \n  assumes \"x \\<notin> ps\"\n  assumes \"B index ps = l\"\n  shows \"{# insert x b . b \\<in># B#} index ps = l\"\n  using points_index_def by (metis (no_types, lifting) assms filter_mset_cong \n      image_mset_filter_swap2 points_index_def size_image_mset subset_insert)\n\nlemma points_index_on_set_def [simp]: \n  assumes \"finite B\"\n  shows \"(mset_set B) index ps = card {b \\<in> B. ps \\<subseteq> b}\"\n  by (simp add: points_index_def assms)\n\nlemma points_index_single_rep_num: \"B index {x} = B rep x\"\n  by (simp add: points_index_def point_replication_number_def)\n\nlemma points_index_pair_rep_num: \n  assumes \"\\<And> b. b \\<in># B \\<Longrightarrow> x \\<in> b\"\n  shows \"B index {x, y} = B rep y\"\n  using point_replication_number_def points_index_def\n  by (metis assms empty_subsetI filter_mset_cong insert_subset)\n\nlemma points_index_0_left_imp: \n  assumes \"B index ps = 0\"\n  assumes \"b \\<in># B\"\n  shows \"\\<not> (ps \\<subseteq> b)\"\nproof (rule ccontr)\n  assume \"\\<not> \\<not> ps \\<subseteq> b\"\n  then have a: \"ps \\<subseteq> b\" by auto\n  then have \"b \\<in># {#bl \\<in># B . ps \\<subseteq> bl#}\" by (simp add: assms(2)) \n  thus False by (metis assms(1) count_greater_eq_Suc_zero_iff count_size_set_repr not_less_eq_eq \n        points_index_def size_filter_mset_lesseq) \nqed\n\nlemma points_index_0_right_imp: \n  assumes \"\\<And> b . b \\<in># B \\<Longrightarrow> (\\<not> ps \\<subseteq> b)\"\n  shows \"B index ps = 0\"\n  using assms by (simp add: filter_mset_empty_conv points_index_def)\n\nlemma points_index_0_iff: \"B index ps = 0 \\<longleftrightarrow> (\\<forall> b. b \\<in># B \\<longrightarrow> (\\<not> ps \\<subseteq> b))\"\n  using points_index_0_left_imp points_index_0_right_imp by metis\n\nlemma points_index_gt0_impl_existance: \n  assumes \"B index ps > 0\"\n  shows \"(\\<exists> bl . (bl \\<in># B \\<and> ps \\<subseteq> bl))\"\nproof -\n  have \"size {#bl \\<in># B . ps \\<subseteq> bl#} > 0\"\n    by (metis assms points_index_def)\n  then obtain bl where \"bl \\<in># B\" and \"ps \\<subseteq> bl\"\n    by (metis filter_mset_empty_conv nonempty_has_size) \n  thus ?thesis by auto\nqed\n\nlemma points_index_one_unique: \n  assumes \"B index ps = 1\"\n  assumes \"bl \\<in># B\" and \"ps \\<subseteq> bl\" and \"bl' \\<in># B\" and \"ps \\<subseteq> bl'\"\n  shows \"bl = bl'\"\nproof (rule ccontr)\n  assume assm: \"bl \\<noteq> bl'\"\n  then have bl1: \"bl \\<in># {#bl \\<in># B . ps \\<subseteq> bl#}\" using assms by simp\n  then have bl2: \"bl'\\<in># {#bl \\<in># B . ps \\<subseteq> bl#}\" using assms by simp\n  then have \"{#bl, bl'#} \\<subseteq># {#bl \\<in># B . ps \\<subseteq> bl#}\" using assms by (metis bl1 bl2 points_index_def\n        add_mset_subseteq_single_iff assm mset_subset_eq_single size_single subseteq_mset_size_eql) \n  then have \"size {#bl \\<in># B . ps \\<subseteq> bl#} \\<ge> 2\" using size_mset_mono by fastforce \n  thus False using assms by (metis numeral_le_one_iff points_index_def semiring_norm(69))\nqed\n\nlemma points_index_one_unique_block: \n  assumes \"B index ps = 1\"\n  shows \"\\<exists>! bl . (bl \\<in># B \\<and> ps \\<subseteq> bl)\"\n  using assms points_index_gt0_impl_existance points_index_one_unique\n  by (metis zero_less_one) \n\nlemma points_index_one_not_unique_block: \n  assumes \"B index ps = 1\"\n  assumes \"ps \\<subseteq> bl\"\n  assumes \"bl \\<in># B\"\n  assumes \"bl' \\<in># B - {#bl#}\"\n  shows \"\\<not> ps \\<subseteq> bl'\"\nproof - \n  have \"B = (B - {#bl#}) + {#bl#}\" by (simp add: assms(3)) \n  then have \"(B - {#bl#}) index ps = B index ps - {#bl#} index ps\"\n    by (metis point_index_diff) \n  then have \"(B - {#bl#}) index ps = 0\" using assms points_index_singleton\n    by (metis diff_self_eq_0) \n  thus ?thesis using assms(4) points_index_0_left_imp by auto\nqed\n\nlemma (in incidence_system) points_index_alt_def: \"\\<B> index ps = size {#b \\<in># \\<B> . ps \\<subseteq> b#}\"\n  by (simp add: points_index_def)\n\nlemma (in incidence_system) points_index_ps_nin: \"\\<not> (ps \\<subseteq> \\<V>) \\<Longrightarrow> \\<B> index ps = 0\"\n  using points_index_alt_def filter_mset_empty_conv in_mono size_empty subsetI wf_invalid_point\n  by metis \n\nlemma (in incidence_system) points_index_count_bl: \n    \"multiplicity bl \\<ge> n \\<Longrightarrow> ps \\<subseteq> bl \\<Longrightarrow> count {#bl \\<in># \\<B> . ps \\<subseteq> bl#} bl \\<ge> n\"\n  by simp\n\nlemma (in finite_incidence_system) points_index_zero: \n  assumes \"card ps > card \\<V>\" \n  shows \"\\<B> index ps = 0\"\nproof -\n  have \"\\<And> b. b \\<in># \\<B> \\<Longrightarrow> card ps > card b\" \n    using block_size_lt_order card_subset_not_gt_card finite_sets assms by fastforce \n  then have \"{#b \\<in># \\<B> . ps \\<subseteq> b#} = {#}\"\n    by (simp add: card_subset_not_gt_card filter_mset_empty_conv finite_blocks)\n  thus ?thesis using points_index_alt_def by simp\nqed\n\nlemma (in design) points_index_subset: \n    \"x \\<subseteq># {#bl \\<in># \\<B> . ps \\<subseteq> bl#} \\<Longrightarrow> ps \\<subseteq> \\<V> \\<Longrightarrow> (\\<B> index ps) \\<ge> (size x)\"\n  by (simp add: points_index_def size_mset_mono)\n\nlemma (in design) points_index_count_min: \"multiplicity bl \\<ge> n \\<Longrightarrow> ps \\<subseteq> bl \\<Longrightarrow> \\<B> index ps \\<ge> n\"\n  using points_index_alt_def set_count_size_min by (metis filter_mset.rep_eq) \n\nsubsubsection \\<open>Intersection Number\\<close>\n\ntext \\<open> The intersection number of two blocks is the size of the intersection of those blocks. i.e. \nthe number of points which occur in both blocks \\<close>\ndefinition intersection_number :: \"'a set \\<Rightarrow> 'a set \\<Rightarrow> nat\" (infix \"|\\<inter>|\" 70) where\n\"b1 |\\<inter>| b2 \\<equiv> card (b1 \\<inter> b2)\"\n\nlemma intersection_num_non_neg: \"b1 |\\<inter>| b2 \\<ge> 0\"\n  by (simp add: intersection_number_def)\n\nlemma intersection_number_empty_iff: \n  assumes \"finite b1\"\n  shows \"b1 \\<inter> b2 = {} \\<longleftrightarrow> b1 |\\<inter>| b2 = 0\"\n  by (simp add: intersection_number_def assms)\n\nlemma intersect_num_commute: \"b1 |\\<inter>| b2 = b2 |\\<inter>| b1\"\n  by (simp add: inf_commute intersection_number_def) \n\ndefinition n_intersect_number :: \"'a set \\<Rightarrow> nat\\<Rightarrow> 'a set \\<Rightarrow> nat\" where\n\"n_intersect_number b1 n b2 \\<equiv> card { x \\<in> Pow (b1 \\<inter> b2) . card x = n}\"\n\nnotation n_intersect_number (\"(_ |\\<inter>|\\<^sub>_ _)\" [52, 51, 52] 50)\n\nlemma n_intersect_num_subset_def: \"b1 |\\<inter>|\\<^sub>n b2 = card {x . x \\<subseteq> b1 \\<inter> b2 \\<and> card x = n}\"\n  using n_intersect_number_def by auto\n\nlemma n_inter_num_one: \"finite b1 \\<Longrightarrow> finite b2 \\<Longrightarrow> b1 |\\<inter>|\\<^sub>1 b2 = b1 |\\<inter>| b2\"\n  using n_intersect_number_def intersection_number_def card_Pow_filter_one\n  by (metis (full_types) finite_Int)\n\nlemma n_inter_num_choose: \"finite b1 \\<Longrightarrow> finite b2 \\<Longrightarrow> b1 |\\<inter>|\\<^sub>n b2 = (card (b1 \\<inter> b2) choose n)\" \n  using n_subsets n_intersect_num_subset_def\n  by (metis (full_types) finite_Int) \n\nlemma set_filter_single: \"x \\<in> A \\<Longrightarrow> {a \\<in> A . a = x} = {x}\"\n  by auto \n\nlemma (in design) n_inter_num_zero: \n  assumes \"b1 \\<in># \\<B>\" and \"b2 \\<in># \\<B>\"\n  shows \"b1 |\\<inter>|\\<^sub>0 b2 = 1\"\nproof -\n  have empty: \"\\<And>x . finite x \\<Longrightarrow> card x = 0 \\<Longrightarrow> x = {}\"\n    by simp\n  have empt_in: \"{} \\<in> Pow (b1 \\<inter> b2)\" by simp\n  have \"finite (b1 \\<inter> b2)\" using finite_blocks assms by simp\n  then have \"\\<And> x . x \\<in> Pow (b1 \\<inter> b2) \\<Longrightarrow> finite x\" by (meson PowD finite_subset) \n  then have \"{x \\<in> Pow (b1 \\<inter> b2) . card x = 0} = {x \\<in> Pow (b1 \\<inter> b2) . x = {}}\" \n    using empty by (metis card.empty)\n  then have \"{x \\<in> Pow (b1 \\<inter> b2) . card x = 0} = {{}}\" \n    by (simp add: empt_in set_filter_single Collect_conv_if)\n  thus ?thesis by (simp add: n_intersect_number_def)\nqed\n\nlemma (in design) n_inter_num_choose_design: \"b1 \\<in># \\<B> \\<Longrightarrow> b2 \\<in># \\<B> \n    \\<Longrightarrow> b1 |\\<inter>|\\<^sub>n b2 = (card (b1 \\<inter> b2) choose n) \"\n  using finite_blocks by (simp add: n_inter_num_choose)\n\nlemma (in design) n_inter_num_choose_design_inter: \"b1 \\<in># \\<B> \\<Longrightarrow> b2 \\<in># \\<B> \n    \\<Longrightarrow> b1 |\\<inter>|\\<^sub>n b2 = (nat (b1 |\\<inter>| b2) choose n) \"\n  using finite_blocks by (simp add: n_inter_num_choose intersection_number_def)\n\nsubsection \\<open> Incidence System Set Property Definitions \\<close>\ncontext incidence_system\nbegin\n\ntext \\<open>The set of replication numbers for all points of design\\<close>\ndefinition replication_numbers :: \"int set\" where\n\"replication_numbers \\<equiv> {\\<B> rep x | x . x \\<in> \\<V>}\"\n\nlemma replication_numbers_non_empty: \n  assumes \"\\<V> \\<noteq> {}\"\n  shows \"replication_numbers \\<noteq> {}\"\n  by (simp add: assms replication_numbers_def) \n\nlemma obtain_point_with_rep: \"r \\<in> replication_numbers \\<Longrightarrow> \\<exists> x. x \\<in> \\<V> \\<and> \\<B> rep x = r\"\n  using replication_numbers_def by auto\n\nlemma point_rep_number_in_set: \"x \\<in> \\<V> \\<Longrightarrow> (\\<B> rep x) \\<in> replication_numbers\"\n  by (auto simp add: replication_numbers_def)\n\nlemma (in finite_incidence_system) replication_numbers_finite: \"finite replication_numbers\"\n  using finite_sets by (simp add: replication_numbers_def)\n\ntext \\<open>The set of all block sizes in a system\\<close>\n\ndefinition sys_block_sizes :: \"nat set\" where\n\"sys_block_sizes \\<equiv> { (int (card bl)) | bl. bl \\<in># \\<B>}\"\n\nlemma block_sizes_non_empty_set: \n  assumes \"\\<B> \\<noteq> {#}\"\n  shows \"sys_block_sizes \\<noteq> {}\"\nby (simp add: sys_block_sizes_def assms)\n\nlemma finite_block_sizes: \"finite (sys_block_sizes)\"\n  by (simp add: sys_block_sizes_def)\n\nlemma block_sizes_non_empty: \n  assumes \"\\<B> \\<noteq> {#}\"\n  shows \"card (sys_block_sizes) > 0\"\n  using finite_block_sizes block_sizes_non_empty_set\n  by (simp add: assms card_gt_0_iff) \n\nlemma sys_block_sizes_in: \"bl \\<in># \\<B> \\<Longrightarrow> card bl \\<in> sys_block_sizes\"\n  unfolding sys_block_sizes_def by auto \n\nlemma sys_block_sizes_obtain_bl: \"x \\<in> sys_block_sizes  \\<Longrightarrow> (\\<exists> bl \\<in># \\<B>. card bl = x)\"\n  by (auto simp add: sys_block_sizes_def)\n\ntext \\<open>The set of all possible intersection numbers in a system.\\<close>\n\ndefinition intersection_numbers :: \"nat set\" where\n\"intersection_numbers \\<equiv> { b1 |\\<inter>| b2 | b1 b2 . b1 \\<in># \\<B> \\<and> b2 \\<in># (\\<B> - {#b1#})}\"\n\nlemma obtain_blocks_intersect_num: \"n \\<in> intersection_numbers \\<Longrightarrow> \n  \\<exists> b1 b2. b1 \\<in># \\<B> \\<and> b2 \\<in># (\\<B> - {#b1#}) \\<and>  b1 |\\<inter>| b2 = n\"\n  by (auto simp add: intersection_numbers_def)\n\nlemma intersect_num_in_set: \"b1 \\<in># \\<B> \\<Longrightarrow> b2 \\<in># (\\<B> - {#b1#}) \\<Longrightarrow> b1 |\\<inter>| b2 \\<in> intersection_numbers\"\n  by (auto simp add: intersection_numbers_def)\n\ntext \\<open>The set of all possible point indices \\<close>\ndefinition point_indices :: \"nat \\<Rightarrow> nat set\" where\n\"point_indices t \\<equiv> {\\<B> index ps | ps. card ps = t \\<and> ps \\<subseteq> \\<V>}\"\n\nlemma point_indices_elem_in: \"ps \\<subseteq> \\<V> \\<Longrightarrow> card ps = t \\<Longrightarrow> \\<B> index ps \\<in> point_indices t\"\n  by (auto simp add: point_indices_def)\n\nlemma point_indices_alt_def: \"point_indices t = { \\<B> index ps | ps. card ps = t \\<and> ps \\<subseteq> \\<V>}\"\n  by (simp add: point_indices_def)\n\nend\n\nsubsection \\<open>Basic Constructions on designs\\<close>\n\ntext \\<open>This section defines some of the most common universal constructions found in design theory\ninvolving only a single design \\<close>\n\nsubsubsection \\<open>Design Complements \\<close>\n\ncontext incidence_system\nbegin\n\ntext \\<open> The complement of a block are all the points in the design not in that block. \nThe complement of a design is therefore the original point sets, and set of all block complements \\<close>\ndefinition block_complement:: \"'a set \\<Rightarrow> 'a set\" (\"_\\<^sup>c\" [56] 55) where\n\"block_complement b \\<equiv> \\<V> - b\"\n\ndefinition complement_blocks :: \"'a set multiset\" (\"(\\<B>\\<^sup>C)\")where\n\"complement_blocks \\<equiv> {# bl\\<^sup>c . bl \\<in># \\<B> #}\" \n\nlemma block_complement_elem_iff: \n  assumes \"ps \\<subseteq> \\<V>\"\n  shows \"ps \\<subseteq> bl\\<^sup>c \\<longleftrightarrow> (\\<forall> x \\<in> ps. x \\<notin> bl)\"\n  using assms block_complement_def by (auto)\n\nlemma block_complement_inter_empty: \"bl1\\<^sup>c = bl2 \\<Longrightarrow> bl1 \\<inter> bl2 = {}\"\n  using block_complement_def by auto\n\nlemma block_complement_inv: \n  assumes \"bl \\<in># \\<B>\"\n  assumes \"bl\\<^sup>c = bl2\"\n  shows \"bl2\\<^sup>c = bl\"\n  by (metis Diff_Diff_Int assms(1) assms(2) block_complement_def inf.absorb_iff2 wellformed)\n\nlemma block_complement_subset_points: \"ps \\<subseteq> (bl\\<^sup>c) \\<Longrightarrow> ps \\<subseteq> \\<V>\"\n  using block_complement_def by blast\n\nlemma obtain_comp_block_orig: \n  assumes \"bl1 \\<in># \\<B>\\<^sup>C\"\n  obtains bl2 where \"bl2 \\<in># \\<B>\" and \"bl1 = bl2\\<^sup>c\"\n  using wellformed assms by (auto simp add: complement_blocks_def)\n\nlemma complement_same_b [simp]: \"size \\<B>\\<^sup>C = size \\<B>\"\n  by (simp add: complement_blocks_def)\n\nlemma block_comp_elem_alt_left: \"x \\<in> bl \\<Longrightarrow> ps \\<subseteq> bl\\<^sup>c \\<Longrightarrow> x \\<notin> ps\"\n  by (auto simp add: block_complement_def block_complement_elem_iff)\n\nlemma block_comp_elem_alt_right: \"ps \\<subseteq> \\<V> \\<Longrightarrow> (\\<And> x . x \\<in> ps \\<Longrightarrow> x \\<notin> bl) \\<Longrightarrow> ps \\<subseteq> bl\\<^sup>c\"\n  by (auto simp add: block_complement_elem_iff)\n\nlemma complement_index:\n  assumes \"ps \\<subseteq> \\<V>\"\n  shows \"\\<B>\\<^sup>C index ps = size {# b \\<in># \\<B> . (\\<forall> x \\<in> ps . x \\<notin> b) #}\"\nproof -\n  have \"\\<B>\\<^sup>C index ps =  size {# b \\<in># {# bl\\<^sup>c . bl \\<in># \\<B>#}. ps \\<subseteq> b #}\"\n    by (simp add: complement_blocks_def points_index_def) \n  then have \"\\<B>\\<^sup>C index ps = size {# bl\\<^sup>c | bl \\<in># \\<B> . ps \\<subseteq> bl\\<^sup>c #}\"\n    by (metis image_mset_filter_swap)\n  thus ?thesis using assms by (simp add: block_complement_elem_iff)\nqed\n\nlemma complement_index_2:\n  assumes \"{x, y} \\<subseteq> \\<V>\"\n  shows \"\\<B>\\<^sup>C index {x, y} = size {# b \\<in># \\<B> . x \\<notin> b \\<and> y \\<notin> b #}\"\nproof -\n  have a: \"\\<And> b. b \\<in># \\<B> \\<Longrightarrow> \\<forall> x' \\<in> {x, y} . x' \\<notin> b \\<Longrightarrow> x \\<notin> b \\<and> y \\<notin> b\"\n    by simp \n  have \"\\<And> b. b \\<in># \\<B> \\<Longrightarrow> x \\<notin> b \\<and> y \\<notin> b \\<Longrightarrow> \\<forall> x' \\<in> {x, y} . x' \\<notin> b \"\n    by simp \n  thus ?thesis using assms a complement_index\n    by (smt (verit) filter_mset_cong) \nqed\n\nlemma complement_rep_number: \n  assumes \"x \\<in> \\<V>\" and \"\\<B> rep x = r\" \n  shows  \"\\<B>\\<^sup>C rep x = \\<b> - r\"\nproof - \n  have r: \"size {#b \\<in># \\<B> . x \\<in> b#} = r\" using assms by (simp add: point_replication_number_def)\n  then have a: \"\\<And> b . b \\<in># \\<B> \\<Longrightarrow> x \\<in> b \\<Longrightarrow> x \\<notin> b\\<^sup>c\"\n    by (simp add: block_complement_def)\n  have \"\\<And> b . b \\<in># \\<B> \\<Longrightarrow> x \\<notin> b \\<Longrightarrow> x \\<in> b\\<^sup>c\"\n    by (simp add: assms(1) block_complement_def) \n  then have alt: \"(image_mset block_complement \\<B>) rep x = size {#b \\<in># \\<B> . x \\<notin> b#}\" \n    using a filter_mset_cong image_mset_filter_swap2 point_replication_number_def\n    by (smt (verit, ccfv_SIG) size_image_mset) \n  have \"\\<b> = size {#b \\<in># \\<B> . x \\<in> b#} + size {#b \\<in># \\<B> . x \\<notin> b#}\"\n    by (metis multiset_partition size_union) \n  thus ?thesis using alt\n    by (simp add: r complement_blocks_def)\nqed\n\nlemma complement_blocks_wf: \"bl \\<in># \\<B>\\<^sup>C \\<Longrightarrow> bl \\<subseteq> \\<V>\"\n  by (auto simp add: complement_blocks_def block_complement_def)\n\nlemma complement_wf [intro]: \"incidence_system \\<V> \\<B>\\<^sup>C\"\n  using complement_blocks_wf by (unfold_locales)\n\ninterpretation sys_complement: incidence_system \"\\<V>\" \"\\<B>\\<^sup>C\"\n  using complement_wf by simp \nend\n\ncontext finite_incidence_system\nbegin\nlemma block_complement_size: \"b \\<subseteq> \\<V> \\<Longrightarrow> card (b\\<^sup>c) = card \\<V> - card b\"\n  by (simp add: block_complement_def card_Diff_subset finite_subset card_mono of_nat_diff finite_sets)  \n\nlemma block_comp_incomplete: \"incomplete_block bl \\<Longrightarrow> card (bl\\<^sup>c) > 0\"\n  using block_complement_size by (simp add: wellformed) \n\nlemma  block_comp_incomplete_nempty: \"incomplete_block bl \\<Longrightarrow> bl\\<^sup>c \\<noteq> {}\"\n  using wellformed block_complement_def finite_blocks\n  by (auto simp add: block_complement_size block_comp_incomplete card_subset_not_gt_card)\n\nlemma incomplete_block_proper_subset: \"incomplete_block bl \\<Longrightarrow> bl \\<subset> \\<V>\"\n  using wellformed by fastforce\n\nlemma complement_finite: \"finite_incidence_system \\<V> \\<B>\\<^sup>C\"\n  using complement_wf finite_sets by (simp add: incidence_system.finite_sysI) \n\ninterpretation comp_fin: finite_incidence_system \\<V> \"\\<B>\\<^sup>C\"\n  using complement_finite by simp \n\nend\n\ncontext design\nbegin\nlemma (in design) complement_design: \n  assumes \"\\<And> bl . bl \\<in># \\<B> \\<Longrightarrow> incomplete_block bl\" \n  shows \"design \\<V> (\\<B>\\<^sup>C)\"\nproof -\n  interpret fin: finite_incidence_system \\<V> \"\\<B>\\<^sup>C\" using complement_finite by simp\n  show ?thesis using assms block_comp_incomplete_nempty wellformed \n    by (unfold_locales) (auto simp add: complement_blocks_def)\nqed\n\nend\nsubsubsection \\<open>Multiples\\<close>\ntext \\<open>An easy way to construct new set systems is to simply multiply the block collection by some \nconstant \\<close>\n\ncontext incidence_system \nbegin\n\nabbreviation multiple_blocks :: \"nat \\<Rightarrow> 'a set multiset\" where\n\"multiple_blocks n \\<equiv> repeat_mset n \\<B>\"\n\nlemma multiple_block_in_original: \"b \\<in># multiple_blocks n \\<Longrightarrow> b \\<in># \\<B>\"\n  by (simp add: elem_in_repeat_in_original) \n\nlemma multiple_block_in: \"n > 0 \\<Longrightarrow> b \\<in># \\<B> \\<Longrightarrow>  b \\<in># multiple_blocks n\"\n  by (simp add: elem_in_original_in_repeat)\n\nlemma multiple_blocks_gt: \"n > 0 \\<Longrightarrow> size (multiple_blocks n) \\<ge> size \\<B>\" \n  by (simp)\n\nlemma block_original_count_le: \"n > 0 \\<Longrightarrow> count \\<B> b \\<le> count (multiple_blocks n) b\"\n  using count_repeat_mset by simp \n\nlemma multiple_blocks_sub: \"n > 0 \\<Longrightarrow> \\<B> \\<subseteq># (multiple_blocks n)\"\n  by (simp add: mset_subset_eqI block_original_count_le) \n\nlemma multiple_1_same: \"multiple_blocks 1 = \\<B>\"\n  by simp\n\nlemma multiple_unfold_1: \"multiple_blocks (Suc n) = (multiple_blocks n) + \\<B>\"\n  by simp\n\nlemma multiple_point_rep_num: \"(multiple_blocks n) rep x = (\\<B> rep x) * n\"\nproof (induction n)\n  case 0\n  then show ?case by (simp add: point_replication_number_def)\nnext\n  case (Suc n)\n  then have \"multiple_blocks (Suc n) rep x = \\<B> rep x * n + (\\<B> rep x)\"\n    using Suc.IH Suc.prems by (simp add: union_commute point_replication_number_def)\n  then show ?case by simp \nqed\n\nlemma multiple_point_index: \"(multiple_blocks n) index ps = (\\<B> index ps) * n\"\n  by (induction n) (auto simp add: points_index_def)\n\nlemma repeat_mset_block_point_rel: \"\\<And>b x. b \\<in># multiple_blocks  n \\<Longrightarrow> x \\<in> b \\<Longrightarrow> x \\<in> \\<V>\"\n  by (induction n) (auto, meson subset_iff wellformed)\n\nlemma multiple_is_wellformed: \"incidence_system \\<V> (multiple_blocks n)\"\n  using repeat_mset_subset_in wellformed repeat_mset_block_point_rel by (unfold_locales) (auto)\n\nlemma  multiple_blocks_num [simp]: \"size (multiple_blocks n) = n*\\<b>\"\n  by simp\n\ninterpretation mult_sys: incidence_system \\<V> \"(multiple_blocks n)\"\n  by (simp add: multiple_is_wellformed)\n\nlemma multiple_block_multiplicity [simp]: \"mult_sys.multiplicity n bl = (multiplicity bl) * n\"\n  by (simp)\n\nlemma multiple_block_sizes_same: \n  assumes \"n > 0\" \n  shows \"sys_block_sizes = mult_sys.sys_block_sizes n\"\nproof -\n  have def: \"mult_sys.sys_block_sizes n = {card bl | bl. bl \\<in># (multiple_blocks n)}\"\n    by (simp add: mult_sys.sys_block_sizes_def) \n  then have eq: \"\\<And> bl. bl \\<in># (multiple_blocks n) \\<longleftrightarrow> bl \\<in># \\<B>\"\n    using assms multiple_block_in multiple_block_in_original by blast \n  thus ?thesis using def by (simp add: sys_block_sizes_def eq)\nqed \n\nend\n\ncontext finite_incidence_system\nbegin\n\nlemma multiple_is_finite: \"finite_incidence_system \\<V> (multiple_blocks n)\"\n  using multiple_is_wellformed finite_sets by (unfold_locales) (auto simp add: incidence_system_def)\n\nend\n\ncontext design\nbegin\n\nlemma multiple_is_design: \"design \\<V> (multiple_blocks n)\"\nproof -\n  interpret fis: finite_incidence_system \\<V> \"multiple_blocks n\" using multiple_is_finite by simp\n  show ?thesis using blocks_nempty\n    by (unfold_locales) (auto simp add: elem_in_repeat_in_original repeat_mset_not_empty)\nqed\n\nend\n\nsubsection \\<open> Simple Designs \\<close>\n\ntext \\<open> Simple designs are those in which the multiplicity of each block is at most one. \nIn other words, the block collection is a set. This can significantly ease reasoning. \\<close>\n\nlocale simple_incidence_system = incidence_system + \n  assumes simple [simp]: \"bl \\<in># \\<B> \\<Longrightarrow> multiplicity bl = 1\"\n\nbegin \n\nlemma simple_alt_def_all: \"\\<forall> bl \\<in># \\<B> . multiplicity bl = 1\"\n  using simple by auto\n  \nlemma simple_blocks_eq_sup: \"mset_set (design_support) = \\<B>\"\n  using distinct_mset_def simple design_support_def by (metis distinct_mset_set_mset_ident) \n\nlemma simple_block_size_eq_card: \"\\<b> = card (design_support)\"\n  by (metis simple_blocks_eq_sup size_mset_set)\n\nlemma points_index_simple_def: \"\\<B> index ps = card {b \\<in> design_support . ps \\<subseteq> b}\"\n  using design_support_def points_index_def card_size_filter_eq simple_blocks_eq_sup\n  by (metis finite_set_mset) \n\nlemma replication_num_simple_def: \"\\<B> rep x = card {b \\<in> design_support . x \\<in> b}\"\n  using design_support_def point_replication_number_def card_size_filter_eq simple_blocks_eq_sup\n  by (metis finite_set_mset) \n\nend\n\nlocale simple_design = design + simple_incidence_system\n\ntext \\<open>Additional reasoning about when something is not simple \\<close>\ncontext incidence_system\nbegin\nlemma simple_not_multiplicity: \"b \\<in># \\<B> \\<Longrightarrow> multiplicity  b > 1 \\<Longrightarrow> \\<not> simple_incidence_system \\<V> \\<B>\"\n  using simple_incidence_system_def simple_incidence_system_axioms_def by (metis nat_neq_iff) \n\nlemma multiple_not_simple: \n  assumes \"n > 1\"\n  assumes \"\\<B> \\<noteq> {#}\"\n  shows \"\\<not> simple_incidence_system \\<V> (multiple_blocks n)\"\nproof (rule ccontr, simp)\n  assume \"simple_incidence_system \\<V> (multiple_blocks n)\"\n  then have \"\\<And> bl. bl \\<in># \\<B> \\<Longrightarrow> count (multiple_blocks n) bl = 1\"\n    using assms(1) elem_in_original_in_repeat\n    by (metis not_gr_zero not_less_zero simple_incidence_system.simple)\n  thus False using assms by auto \nqed\n\nend\n\nsubsection \\<open>Proper Designs\\<close>\ntext \\<open>Many types of designs rely on parameter conditions that only make sense for non-empty designs. \ni.e. designs with at least one block, and therefore given well-formed condition, at least one point. \nTo this end we define the notion of a \"proper\" design \\<close>\n\nlocale proper_design = design + \n  assumes b_non_zero: \"\\<b> \\<noteq> 0\"\nbegin\n\nlemma is_proper: \"proper_design \\<V> \\<B>\" by intro_locales\n\nlemma v_non_zero: \"\\<v> > 0\"\n  using b_non_zero v_eq0_imp_b_eq_0 by auto\n\nlemma b_positive: \"\\<b> > 0\" using b_non_zero\n  by (simp add: nonempty_has_size)\n\nlemma design_points_nempty: \"\\<V> \\<noteq> {}\"\n  using v_non_zero by auto \n\nlemma design_blocks_nempty: \"\\<B> \\<noteq> {#}\"\n  using b_non_zero by auto\n\nend\n\ntext \\<open> Intro rules for a proper design \\<close>\nlemma (in design) proper_designI[intro]: \"\\<b> \\<noteq> 0 \\<Longrightarrow> proper_design \\<V> \\<B>\"\n  by (unfold_locales) simp\n\nlemma proper_designII[intro]: \n  assumes \"design V B\" and \"B \\<noteq> {#}\" \n  shows \"proper_design V B\"\nproof -\n  interpret des: design V B using assms by simp\n  show ?thesis using assms by unfold_locales simp\nqed\n\ntext \\<open>Reasoning on construction closure for proper designs\\<close>\ncontext proper_design\nbegin\n\nlemma multiple_proper_design: \n  assumes \"n > 0\"\n  shows \"proper_design \\<V> (multiple_blocks n)\"\n  using multiple_is_design assms design_blocks_nempty multiple_block_in\n  by (metis block_set_nempty_imp_block_ex empty_iff proper_designII set_mset_empty) \n\nlemma complement_proper_design: \n  assumes \"\\<And> bl . bl \\<in># \\<B> \\<Longrightarrow> incomplete_block bl\"\n  shows \"proper_design \\<V> \\<B>\\<^sup>C\"\nproof -\n  interpret des: design \\<V> \"\\<B>\\<^sup>C\"\n    by (simp add: assms complement_design)  \n  show ?thesis using b_non_zero by (unfold_locales) auto\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/Design_Basics.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8807970748488297, "lm_q2_score": 0.8376199633332891, "lm_q1q2_score": 0.7377732135389451}}
{"text": "(*\n  File:    Eulerian_Polynomials.thy\n  Author:  Manuel Eberl, TU M\u00fcnchen\n*)\nsection \\<open>Eulerian polynomials\\<close>\ntheory Eulerian_Polynomials\nimports \n  Complex_Main \n  \"HOL-Computational_Algebra.Computational_Algebra\"\n  \"HOL-Library.Stirling\"\nbegin\n\ntext \\<open>\n  The Eulerian polynomials are a sequence of polynomials that is related to\n  the closed forms of the power series\n  \\[\\sum_{n=0}^\\infty n^k X^n\\]\n  for a fixed $k$.\n\\<close>\nprimrec eulerian_poly :: \"nat \\<Rightarrow> 'a :: idom poly\" where\n  \"eulerian_poly 0 = 1\"\n| \"eulerian_poly (Suc n) = (let p = eulerian_poly n in \n     [:0,1,-1:] * pderiv p + p * [:1, of_nat n:])\"\n\nlemmas eulerian_poly_Suc [simp del] = eulerian_poly.simps(2)\n\nlemma eulerian_poly:\n  \"fps_of_poly (eulerian_poly k :: 'a :: field poly) = \n     Abs_fps (\\<lambda>n. of_nat (n+1) ^ k) * (1 - fps_X) ^ (k + 1)\"\nproof (induction k)\n  case 0\n  have \"Abs_fps (\\<lambda>_. 1 :: 'a) = inverse (1 - fps_X)\"\n    by (rule fps_inverse_unique [symmetric])\n       (simp add: inverse_mult_eq_1 fps_inverse_gp' [symmetric])\n  thus ?case by (simp add: inverse_mult_eq_1)\nnext\n  case (Suc k)\n  define p :: \"'a fps\" where \"p = fps_of_poly (eulerian_poly k)\"\n  define F :: \"'a fps\" where \"F = Abs_fps (\\<lambda>n. of_nat (n+1) ^ k)\"\n\n  have p: \"p = F * (1 - fps_X) ^ (k+1)\" by (simp add: p_def Suc F_def)\n  have p': \"fps_deriv p = fps_deriv F * (1 - fps_X) ^ (k + 1) - F * (1 - fps_X) ^ k * of_nat (k + 1)\"\n    by (simp add: p fps_deriv_power algebra_simps fps_const_neg [symmetric] fps_of_nat \n             del: power_Suc of_nat_Suc fps_const_neg)\n  \n  have \"fps_of_poly (eulerian_poly (Suc k)) = (fps_X * fps_deriv F + F) * (1 - fps_X) ^ (Suc k + 1)\"\n    apply (simp add: Let_def p_def [symmetric] fps_of_poly_simps eulerian_poly_Suc del: power_Suc)\n    apply (simp add: p p' fps_deriv_power fps_const_neg [symmetric] fps_of_nat\n                del: power_Suc of_nat_Suc fps_const_neg)\n    apply (simp add: algebra_simps)\n    done\n  also have \"fps_X * fps_deriv F + F = Abs_fps (\\<lambda>n. of_nat (n + 1) ^ Suc k)\"\n    unfolding F_def by (intro fps_ext) (auto simp: algebra_simps)\n  finally show ?case .\nqed\n\nlemma eulerian_poly':\n  \"Abs_fps (\\<lambda>n. of_nat (n+1) ^ k) = \n     fps_of_poly (eulerian_poly k :: 'a :: field poly) / (1 - fps_X) ^ (k + 1)\"\n  by (subst eulerian_poly) simp\n  \nlemma eulerian_poly'':\n  assumes k: \"k > 0\"\n  shows \"Abs_fps (\\<lambda>n. of_nat n ^ k) = \n           fps_of_poly (pCons 0 (eulerian_poly k :: 'a :: field poly)) / (1 - fps_X) ^ (k + 1)\"\nproof -\n  from assms have \"Abs_fps (\\<lambda>n. of_nat n ^ k :: 'a) = fps_X * Abs_fps (\\<lambda>n. of_nat (n + 1) ^ k)\"\n    by (intro fps_ext) (auto simp: of_nat_diff)\n  also have \"Abs_fps (\\<lambda>n. of_nat (n + 1) ^ k :: 'a) = \n               fps_of_poly (eulerian_poly k) / (1 - fps_X) ^ (k + 1)\" by (rule eulerian_poly')\n  also have \"fps_X * \\<dots> = fps_of_poly (pCons 0 (eulerian_poly k)) / (1 - fps_X) ^ (k + 1)\"\n    by (simp add: fps_of_poly_pCons fps_divide_unit)\n  finally show ?thesis .\nqed\n\ndefinition fps_monom_poly :: \"'a :: field \\<Rightarrow> nat \\<Rightarrow> 'a poly\"\n  where \"fps_monom_poly c k = (if k = 0 then 1 else pcompose (pCons 0 (eulerian_poly k)) [:0,c:])\"\n\nprimrec fps_monom_poly_aux :: \"'a :: field \\<Rightarrow> nat \\<Rightarrow> 'a poly\" where\n  \"fps_monom_poly_aux c 0 = [:c:]\"\n| \"fps_monom_poly_aux c (Suc k) = \n      (let p = fps_monom_poly_aux c k\n       in  [:0,1,-c:] * pderiv p + [:1, of_nat k * c:] * p)\"\n\nlemma fps_monom_poly_aux:\n  \"fps_monom_poly_aux c k = smult c (pcompose (eulerian_poly k) [:0,c:])\"\n  by (induction k) \n     (simp_all add: eulerian_poly_Suc Let_def pderiv_pcompose pcompose_pCons\n                    pcompose_add pcompose_smult pcompose_uminus smult_add_right pderiv_pCons\n                    pderiv_smult algebra_simps one_pCons)\n\nlemma fps_monom_poly_code [code]:\n  \"fps_monom_poly c k = (if k = 0 then 1 else pCons 0 (fps_monom_poly_aux c k))\"\n  by (simp add: fps_monom_poly_def fps_monom_poly_aux pcompose_pCons)\n\nlemma fps_monom_aux: \n  \"Abs_fps (\\<lambda>n. of_nat n ^ k) = fps_of_poly (fps_monom_poly 1 k) / (1 - fps_X) ^ (k+1)\"\nproof (cases \"k = 0\")\n  assume [simp]: \"k = 0\"\n  hence \"Abs_fps (\\<lambda>n. of_nat n ^ k :: 'a) = Abs_fps (\\<lambda>_. 1)\" by simp\n  also have \"\\<dots> = 1 / (1 - fps_X)\" by (subst gp [symmetric]) simp_all\n  finally show ?thesis by (simp add: fps_monom_poly_def)\nqed (insert eulerian_poly''[of k, where ?'a = 'a], simp add: fps_monom_poly_def)\n\nlemma fps_monom:\n  \"Abs_fps (\\<lambda>n. of_nat n ^ k * c ^ n) = \n      fps_of_poly (fps_monom_poly c k) / (1 - fps_const c * fps_X) ^ (k+1)\"\nproof -\n  have \"Abs_fps (\\<lambda>n. of_nat n ^ k * c ^ n) = \n          fps_compose (Abs_fps (\\<lambda>n. of_nat n ^ k)) (fps_const c * fps_X)\"\n    by (subst fps_compose_linear) (simp add: mult_ac)\n  also have \"Abs_fps (\\<lambda>n. of_nat n ^ k) = fps_of_poly (fps_monom_poly 1 k) / (1 - fps_X) ^ (k+1)\"\n    by (rule fps_monom_aux)\n  also have \"fps_compose \\<dots> (fps_const c * fps_X) = \n                 (fps_of_poly (fps_monom_poly 1 k) oo fps_const c * fps_X) /\n                 ((1 - fps_X) ^ (k + 1) oo fps_const c * fps_X)\"\n    by (intro fps_compose_divide_distrib)\n       (simp_all add: fps_compose_power [symmetric] fps_compose_sub_distrib del: power_Suc)\n  also have \"fps_of_poly (fps_monom_poly 1 k) oo (fps_const c * fps_X) = \n                fps_of_poly (fps_monom_poly c k)\"\n    by (simp add: fps_monom_poly_def fps_of_poly_pcompose fps_of_poly_simps\n                  fps_of_poly_pCons mult_ac)\n  also have \"((1 - fps_X) ^ (k + 1) oo fps_const c * fps_X) = (1 - fps_const c * fps_X) ^ (k + 1)\"\n    by (simp add: fps_compose_power [symmetric] fps_compose_sub_distrib del: power_Suc)\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/Linear_Recurrences/Eulerian_Polynomials.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970654616711, "lm_q2_score": 0.8376199694135333, "lm_q1q2_score": 0.7377732110315349}}
{"text": "section {* Alternative list lexicographic order *}\n\ntheory List_lexord_alt\n  imports \"~~/src/HOL/Library/Char_ord\"\nbegin\n\ntext {* Since we can't instantiate the order class twice for lists, and we want prefix as\n  the default order for the UTP we here add syntax for the lexicographic order relation. *}\n\ndefinition list_lex_less :: \"'a::linorder list \\<Rightarrow> 'a list \\<Rightarrow> bool\" (infix \"<\\<^sub>l\" 50)\nwhere \"xs <\\<^sub>l ys \\<longleftrightarrow> (xs, ys) \\<in> lexord {(u, v). u < v}\"\n\nlemma list_lex_less_neq [simp]: \"x <\\<^sub>l y \\<Longrightarrow> x \\<noteq> y\"\n  apply (simp add: list_lex_less_def)\n  apply (meson case_prodD less_irrefl lexord_irreflexive mem_Collect_eq)\ndone\n\nlemma not_less_Nil [simp]: \"\\<not> x <\\<^sub>l []\"\n  by (simp add: list_lex_less_def)\n\nlemma Nil_less_Cons [simp]: \"[] <\\<^sub>l a # x\"\n  by (simp add: list_lex_less_def)\n\nlemma Cons_less_Cons [simp]: \"a # x <\\<^sub>l b # y \\<longleftrightarrow> a < b \\<or> a = b \\<and> x <\\<^sub>l y\"\n  by (simp add: list_lex_less_def)\nend", "meta": {"author": "git-vt", "repo": "orca", "sha": "92bda0f9cfe5cc680b9c405fc38f07a960087a36", "save_path": "github-repos/isabelle/git-vt-orca", "path": "github-repos/isabelle/git-vt-orca/orca-92bda0f9cfe5cc680b9c405fc38f07a960087a36/C-verifier/src/Midend-IVL/Isabelle-UTP/utils/List_lexord_alt.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8807970654616712, "lm_q2_score": 0.8376199592797929, "lm_q1q2_score": 0.7377732021057661}}
{"text": "theory Chapter16_1_Type\nimports DeBruijnEnvironment\nbegin\n\ndatatype type = \n  Tyvar var\n| Arrow type type\n| Unit\n| Prod type type\n| Void\n| Sum type type\n| Rec type\n\nprimrec type_insert :: \"var => type => type\"\nwhere \"type_insert n (Tyvar v) = Tyvar (incr n v)\"\n    | \"type_insert n (Arrow t1 t2) = Arrow (type_insert n t1) (type_insert n t2)\"\n    | \"type_insert n Unit = Unit\"\n    | \"type_insert n (Prod t1 t2) = Prod (type_insert n t1) (type_insert n t2)\"\n    | \"type_insert n Void = Void\"\n    | \"type_insert n (Sum t1 t2) = Sum (type_insert n t1) (type_insert n t2)\"\n    | \"type_insert n (Rec t) = Rec (type_insert (next n) t)\"\n\nprimrec type_subst :: \"type => var => type => type\"\nwhere \"type_subst e' n (Tyvar v) = (if v = n then e' else Tyvar (subr n v))\"\n    | \"type_subst e' n (Arrow t1 t2) = Arrow (type_subst e' n t1) (type_subst e' n t2)\"\n    | \"type_subst e' n Unit = Unit\"\n    | \"type_subst e' n (Prod t1 t2) = Prod (type_subst e' n t1) (type_subst e' n t2)\"\n    | \"type_subst e' n Void = Void\"\n    | \"type_subst e' n (Sum t1 t2) = Sum (type_subst e' n t1) (type_subst e' n t2)\"\n    | \"type_subst e' n (Rec t) = Rec (type_subst (type_insert first e') (next n) t)\"\n\n\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/Chapter16_1_Type.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802373309982, "lm_q2_score": 0.8031737963569014, "lm_q1q2_score": 0.7376992590959256}}
{"text": "theory AExp\nimports Main\nbegin\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\n\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\n\n\ndefinition null_state (\"<>\") where\n  \"null_state \\<equiv> \\<lambda>x. 0\"\nsyntax\n  \"_State\" :: \"updbinds => 'a\" (\"<_>\")\ntranslations\n  \"_State ms\" == \"_Update <> ms\"\n\nvalue \"aval (Plus (V ''x'') (N 5)) <''x'' := 7>\"\n\n\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 )\ndone\n\n\n\nfun times :: \"aexp \\<Rightarrow> aexp \\<Rightarrow> aexp\" where\n  \"times ( N n1 ) ( N n2 ) = N ( n1 * n2 )\" |\n  \"times ( N n ) a =\n    ( if\n        n = 0 then N 0 else ( if\n        n = 1 then a\n        else Times ( N n ) a ) )\" |\n  \"times a ( N n ) =\n    ( if\n        n = 0 then N 0 else ( if\n        n = 1 then a\n        else Times a ( N n ) ) )\" |\n  \"times a1 a2 = Times a1 a2\"\n\n\nlemma \"aval_times\" : \"aval ( times a1 a2 ) s = aval a1 s * aval a2 s\"\n  apply ( induction rule: times.induct )\n  apply ( auto )\ndone\n\n\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\nvalue \"asimp ( Times ( Times (N 3) (V x) ) (Plus (N (-1)) (N 21)) )\"\n\nlemma \"aval ( asimp a ) s = aval a s\"\n  apply ( induction a )\n  apply ( auto simp add: aval_plus aval_times)\ndone\n\n\n\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 \\<and> optimal a2 )\" |\n  \"optimal ( Times ( N i ) ( N j ) ) = False\" |\n  \"optimal ( Times ( N n ) _ ) = ( n \\<noteq> 0 \\<and> n \\<noteq> 1 )\" |\n  \"optimal ( Times _ ( N n ) ) = ( n \\<noteq> 0 \\<and> n \\<noteq> 1 )\" |\n  \"optimal ( Times a1 a2 ) = ( optimal a1 \\<and> optimal a2 )\"\n\n\nlemma \"optimal_plus\" : \"optimal a1 \\<Longrightarrow> optimal a2 \\<Longrightarrow> optimal (plus a1 a2)\"\n  apply ( induction a1 a2 rule: plus.induct )\n  apply ( auto )\ndone\n\nlemma \"optimal_times\" : \"optimal a1 \\<Longrightarrow> optimal a2 \\<Longrightarrow> optimal (times a1 a2)\"\n  apply ( induction a1 a2 rule: times.induct )\n  apply ( auto )\ndone\n\nlemma \"optimal ( asimp a )\"\n  apply ( induction a )\n  apply ( auto simp add: optimal_plus optimal_times )\ndone\n\nend\n", "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/AExp.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802350995702, "lm_q2_score": 0.8031737963569016, "lm_q1q2_score": 0.7376992573037012}}
{"text": "theory Exercise5p3\nimports Main\nbegin\n\ninductive ev :: \"nat \\<Rightarrow> bool\" where\n    ev0:  \"ev 0\" \n  | evSS: \"ev n \\<Longrightarrow> ev (Suc (Suc n))\"\n\n\n(* Exercise 5.3 *)  \nlemma \n  assumes a: \"ev (Suc (Suc n))\"\n  shows \"ev n\"\nproof -\n  show ?thesis using a \n  proof cases\n    case evSS\n    thus ?thesis by auto\n  qed\nqed  \n\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/Exercise5p3.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9241418262465169, "lm_q2_score": 0.7981867873410141, "lm_q1q2_score": 0.737637795339165}}
{"text": "theory Shortest_Path_Tree\n  imports \"Graph_Theory.Graph_Theory\" \"Graph_Definitions\" \"Graph_Theory_Batteries\" \"Misc\"\nbegin\n\ntext \\<open>\nThis theory defines the notion of a partial shortest path tree in the locale @{text psp_tree}.\nA partial shortest path tree contains the s nearest notes with respect to some weight function.\nSince, at the time of writing, the definition of @{const forest} only guarantees acyclicity\nand the definition of @{const tree} is also incorrect by extension, we develop our own definition\nof a directed tree in the locale @{text directed_tree}.\n\\<close>\n\nsection \\<open>Directed tree\\<close>\n\ntext \\<open>\nThe following locale defines the notion of a rooted directed tree. The tree property is\nestablished by asserting a unique walk from the root to each vertex. Note that we need\n@{const pre_digraph.awalk} and not @{const pre_digraph.apath} here since we want to have only one\nincoming arc for each vertex. In the locale all the usual properties of trees are established, e.g.\nnon-existence of @{const pre_digraph.cycle}, absence of loops with @{locale loopfree_digraph} and\nmulti-arcs with @{locale nomulti_digraph}.\nWe also prove the admissibility of an induction rule for finite trees which constructs any tree\ninductively by starting with a single node (the root) and consecutively adding leaves.\nFinally we define the depth of a tree.\n\\<close>\nlocale directed_tree =\n    wf_digraph T for T +\nfixes\n  root :: 'a\nassumes\n  root_in_T: \"root \\<in> verts T\" and\n  unique_awalk: \"v \\<in> verts T \\<Longrightarrow> \\<exists>!p. awalk root p v\"\nbegin\n\nsubsection \\<open>General properties of trees\\<close>\n\nlemma reachable_from_root: \"v \\<in> verts T \\<Longrightarrow> root \\<rightarrow>\\<^sup>*\\<^bsub>T\\<^esub> v\"\n  using unique_awalk reachable_awalkI by blast\n\nlemma non_empty: \"verts T \\<noteq> {}\"\n  using root_in_T by blast\n\ntheorem cycle_free: \"\\<nexists>c. cycle c\"\nproof\n  assume \"\\<exists>c. cycle c\"\n  then obtain c where c: \"cycle c\" by blast\n  from unique_awalk[of \"awhd root c\", OF awhd_in_verts[OF root_in_T, of c]]\n  obtain p where p: \"awalk root p (awhd root c)\"\n    using c[unfolded cycle_conv] unfolding awalk_conv by auto\n  from c p awalk_appendI have \"awalk root (p@c) (awhd root c)\"\n    by (metis awalkE' cycle_def awalk_verts_ne_eq)\n  with unique_awalk p c show \"False\"\n    using awalk_last_in_verts unfolding cycle_def by blast\nqed\n\nsublocale loopfree: loopfree_digraph T\nproof(standard, rule ccontr)\n  fix e assume arc: \"e \\<in> arcs T\" and loop: \"\\<not> tail T e \\<noteq> head T e\"\n  then have \"cycle [e]\"\n    unfolding cycle_conv\n    using arc_implies_awalk by force\n  with cycle_free show \"False\" by blast\nqed\n\nsublocale nomulti: nomulti_digraph T\nproof(standard, rule ccontr, goal_cases)\n  case (1 e1 e2)\n  let ?u = \"tail T e1\" and ?v = \"head T e1\"\n  from unique_awalk obtain p where \"awalk root p ?u\"\n    using 1 tail_in_verts by blast\n  with 1 have \"awalk root (p@[e1]) ?v\" and \"awalk root (p@[e2]) ?v\"\n    unfolding arc_to_ends_def\n    using arc_implies_awalk by (fastforce)+\n\n  with unique_awalk show \"False\"\n    using \\<open>e1 \\<noteq> e2\\<close> by blast\nqed\n\n\nlemma connected': \"\\<lbrakk> u \\<in> verts T; v \\<in> verts T \\<rbrakk> \\<Longrightarrow> u \\<rightarrow>\\<^sup>*\\<^bsub>mk_symmetric T\\<^esub> v\"\nproof -\n  let ?T' = \"mk_symmetric T\"\n  fix u v assume \"u \\<in> verts T\" and \"v \\<in> verts T\"\n  then have \"\\<exists>up. awalk root up u\" and \"\\<exists>vp. awalk root vp v\"\n    using unique_awalk by blast+\n  then obtain up vp where up: \"awalk root up u\" and vp: \"awalk root vp v\" by blast\n  then have \"u \\<rightarrow>\\<^sup>*\\<^bsub>mk_symmetric T\\<^esub> root\" and \"root \\<rightarrow>\\<^sup>*\\<^bsub>mk_symmetric T\\<^esub> v\"\n    by (meson reachable_awalkI reachable_mk_symmetricI\n        symmetric_mk_symmetric symmetric_reachable)+\n  then show \"u \\<rightarrow>\\<^sup>*\\<^bsub>mk_symmetric T\\<^esub> v\"\n    by (meson wellformed_mk_symmetric wf_digraph.reachable_trans wf_digraph_wp_iff)\nqed\n\ntheorem connected: \"connected T\"\n  unfolding connected_def strongly_connected_def\n  using connected' root_in_T by auto\n\nlemma unique_awalk_All: \"\\<exists>p. awalk u p v \\<Longrightarrow> \\<exists>!p. awalk u p v\"\nproof(rule ccontr, goal_cases)\n  case 1\n  then have \"\\<exists>p q. awalk u p v \\<and> awalk u q v \\<and> p \\<noteq> q\"\n    by blast\n  then obtain p q where\n    p: \"awalk u p v\" and q: \"awalk u q v\" and \"p \\<noteq> q\" by blast\n  from unique_awalk obtain w where w: \"awalk root w u\"\n    using \\<open>awalk u p v\\<close> by blast\n  then have \"awalk root (w@p) v\" and \"awalk root (w@q) v\" and \"(w@p) \\<noteq> (w@q)\"\n    using \\<open>awalk u p v\\<close> \\<open>awalk u q v\\<close> \\<open>p \\<noteq> q\\<close> awalk_appendI by auto\n  with unique_awalk show ?case by blast\nqed\n\nlemma unique_arc:\n  shows \"u \\<rightarrow>\\<^bsub>T\\<^esub> v \\<Longrightarrow> \\<exists>!e \\<in> arcs T. tail T e = u \\<and> head T e = v\"\n    and \"(\\<nexists>e. e \\<in> arcs T \\<and> tail T e = u \\<and> head T e = v) \\<Longrightarrow> \\<not> u \\<rightarrow>\\<^bsub>T\\<^esub> v\"\n  using unique_awalk_All nomulti.no_multi_arcs unfolding arc_to_ends_def\n  by auto\n\nlemma unique_arc_set:\n  fixes u v\n  defines \"A \\<equiv> {e \\<in> arcs T. tail T e = u \\<and> head T e = v}\"\n  shows \"A = {} \\<or> (\\<exists>e. A = {e})\"\nproof(cases \"u \\<rightarrow>\\<^bsub>T\\<^esub> v\")\n  case True\n  note unique_arc(1)[OF True]\n  then show ?thesis unfolding A_def by blast\nnext\n  case False\n  then have \"\\<nexists>e. e \\<in> arcs T \\<and> tail T e = u \\<and> head T e = v\"\n    using in_arcs_imp_in_arcs_ends arcs_ends_def by blast\n  then show ?thesis unfolding A_def by auto\nqed\n\n\nlemma sp_eq_awalk_cost: \"awalk a p b \\<Longrightarrow> awalk_cost w p = \\<mu> w a b\"\nproof -\n  assume \"awalk a p b\"\n  with unique_awalk_All have \"{p. awalk a p b} = {p}\"\n    by blast\n  then show ?thesis unfolding \\<mu>_def\n    by (metis cInf_singleton image_empty image_insert)\nqed\n\nlemma sp_cost_finite: \"awalk a p b \\<Longrightarrow> \\<mu> w a b > -\\<infinity> \\<and> \\<mu> w a b < \\<infinity>\"\n  using sp_eq_awalk_cost[symmetric] by simp\n\ntheorem sp_append:\n  \"\\<lbrakk> awalk a p b; awalk b q c \\<rbrakk> \\<Longrightarrow> \\<mu> w a c = \\<mu> w a b + \\<mu> w b c\"\nproof -\n  assume p: \"awalk a p b\" and q: \"awalk b q c\"\n  then have p_q: \"awalk a (p@q) c\" by auto\n  then have \"awalk_cost w (p@q) = awalk_cost w p + awalk_cost w q\"\n    using awalk_cost_append by blast\n\n  with p q p_q show ?thesis using sp_eq_awalk_cost\n    by (metis plus_ereal.simps(1))\nqed\n\ntext \\<open>Convenience lemma which reformulates @{thm sp_append} to use reachability as assumptions.\\<close>\nlemma sp_append2: \"\\<lbrakk> v1 \\<rightarrow>\\<^sup>*\\<^bsub>T\\<^esub> v2; v2 \\<rightarrow>\\<^sup>*\\<^bsub>T\\<^esub> v3 \\<rbrakk>\n  \\<Longrightarrow> \\<mu> w v1 v3 = \\<mu> w v1 v2 + \\<mu> w v2 v3\"\n  using reachable_awalk sp_append by auto\n\ntheorem connected_minimal: \"e \\<in> arcs T \\<Longrightarrow>  \\<not> (tail T e) \\<rightarrow>\\<^sup>*\\<^bsub>(del_arc e)\\<^esub> (head T e)\"\nproof\n  let ?T' = \"del_arc e\" and ?u = \"tail T e\" and ?v = \"head T e\"\n  assume \"e \\<in> arcs T\" and \"?u \\<rightarrow>\\<^sup>*\\<^bsub>?T'\\<^esub> ?v\"\n  note e = this\n  then have T'_wf: \"wf_digraph ?T'\" by blast\n\n  from e have \"awalk ?u [e] ?v\"\n    by (simp add: arc_implies_awalk)\n  moreover\n  note wf_digraph.reachable_awalk[OF T'_wf, of ?u ?v]\n  with e obtain p where p: \"pre_digraph.awalk ?T' ?u p ?v\" by blast\n\n  from e have \"e \\<notin> arcs ?T'\" by simp\n  with e p have \"e \\<notin> set p\" by (meson T'_wf subsetCE wf_digraph.awalkE')\n  with p have \"[e] \\<noteq> p\" and \"awalk ?u p ?v\"\n    by (auto simp: subgraph_awalk_imp_awalk subgraph_del_arc)\n\n  ultimately show False using unique_awalk_All by blast\nqed\n\nlemma All_arcs_in_path: \"e \\<in> arcs T \\<Longrightarrow> \\<exists>p u v. awalk u p v \\<and> e \\<in> set p\"\n  by (meson arc_implies_awalk list.set_intros(1))\n\nsubsection \\<open>An induction rule for finite trees\\<close>\ntext \\<open>\nIn this section we develop an induction rule for finite trees. Since this induction rule works by\ninductively adding trees we first need to define the notion of a leaf and prove numerous facts\nabout them.\n\\<close>\n\ndefinition (in pre_digraph) leaf :: \"'a \\<Rightarrow> bool\" where\n  \"leaf v \\<equiv> v \\<in> verts G \\<and> out_arcs G v = {}\"\n\nlemma in_degree_root_zero: \"in_degree T root = 0\"\nproof(rule ccontr)\n  assume \"in_degree T root \\<noteq> 0\"\n  then obtain e u where e: \"tail T e = u\" \"head T e = root\" \"u \\<in> verts T\" \"e \\<in> arcs T\"\n    by (metis tail_in_verts all_not_in_conv card.empty in_degree_def in_in_arcs_conv)\n  with unique_awalk obtain p where p: \"awalk root p u\" by blast\n  with e have \"awalk root (p@[e]) root\"\n    using awalk_appendI arc_implies_awalk by auto\n  moreover\n  have \"awalk root [] root\" by (simp add: awalk_Nil_iff root_in_T)\n  ultimately show \"False\" using unique_awalk by blast\nqed\n\nlemma leaf_out_degree_zero: \"leaf v \\<Longrightarrow> out_degree T v = 0\"\n  unfolding leaf_def out_degree_def by auto\n\nlemma two_in_arcs_contr:\n  assumes \"e1 \\<in> arcs T\" \"e2 \\<in> arcs T\" and \"e1 \\<noteq> e2\" and \"head T e1 = head T e2\"\n  shows \"False\"\nproof -\n  from unique_awalk assms obtain p1 p2\n    where \"awalk root p1 (tail T e1)\" and \"awalk root p2 (tail T e2)\"\n    by (meson tail_in_verts in_in_arcs_conv)\n  with assms have \"awalk root (p1@[e1]) (head T e1)\" and \"awalk root (p2@[e2]) (head T e1)\"\n    unfolding in_arcs_def\n    using arc_implies_awalk by force+\n  with unique_awalk \\<open>e1 \\<noteq> e2\\<close> show \"False\" by blast\nqed\n\nlemma in_arcs_finite: \"v \\<in> verts T \\<Longrightarrow> finite (in_arcs T v)\"\nproof(rule ccontr)\n  assume \"\\<not> finite (in_arcs T v)\"\n  then obtain e1 e2\n    where e1_e2: \"e1 \\<in> in_arcs T v\" \"e2 \\<in> in_arcs T v\" \"e1 \\<noteq> e2\"\n    by (metis finite.emptyI finite_insert finite_subset insertI1 subsetI)\n  with two_in_arcs_contr show \"False\" unfolding in_arcs_def by auto\nqed\n\nlemma not_root_imp_in_deg_one: \"\\<lbrakk> v \\<in> verts T; v \\<noteq> root \\<rbrakk>  \\<Longrightarrow> in_degree T v = 1\"\nproof(rule ccontr)\n  assume \"v \\<noteq> root\" and \"v \\<in> verts T\" and \"in_degree T v \\<noteq> 1\"\n  then have \"in_degree T v \\<noteq> 0\"\n  proof -\n    from unique_awalk \\<open>v \\<in> verts T\\<close> obtain p where \"awalk root p v\" by blast\n    with \\<open>v \\<noteq> root\\<close> have \"root \\<rightarrow>\\<^sup>+\\<^bsub>T\\<^esub> v\" using reachable_awalkI by blast\n    then have \"\\<exists>u. u \\<rightarrow>\\<^bsub>T\\<^esub> v\" by (meson tranclD2)\n    then show ?thesis\n      using in_arcs_finite[OF \\<open>v \\<in> verts T\\<close>] unfolding in_degree_def\n      using card_eq_0_iff by fastforce\n  qed\n  moreover\n  have \"\\<not> in_degree T v \\<ge> 2\"\n  proof\n    assume in_deg_ge_2: \"in_degree T v \\<ge> 2\"\n    have \"\\<exists>e1 e2. e1 \\<in> in_arcs T v \\<and> e2 \\<in> in_arcs T v \\<and> e1 \\<noteq> e2\"\n    proof(cases \"in_arcs T v = {}\")\n      case True\n      then show ?thesis using in_deg_ge_2[unfolded in_degree_def] by simp\n    next\n      case False\n      then obtain e1 where \"e1 \\<in> in_arcs T v\" by blast\n      then have \"card (in_arcs T v) = 1\" if \"\\<forall>e2 \\<in> in_arcs T v. e1 = e2\"\n        using that by(auto simp: card_Suc_eq[where ?A=\"(in_arcs T v)\"])\n      then show ?thesis\n        using in_deg_ge_2[unfolded in_degree_def] \\<open>e1 \\<in> in_arcs T v\\<close> by force\n    qed\n    with two_in_arcs_contr show \"False\" unfolding in_arcs_def by auto\n  qed\n  ultimately show \"False\" using \\<open>in_degree T v \\<noteq> 1\\<close> by linarith\nqed\n\nlemma in_deg_one_imp_not_root: \"\\<lbrakk> v \\<in> verts T; in_degree T v = 1 \\<rbrakk>  \\<Longrightarrow> v \\<noteq> root\"\n  using in_degree_root_zero by auto\n\ncorollary in_deg_one_iff: \"v \\<in> verts T \\<Longrightarrow> v \\<noteq> root \\<longleftrightarrow> in_degree T v = 1\"\n  using not_root_imp_in_deg_one in_deg_one_imp_not_root by blast\n\nlemma ex_in_arc: \"\\<lbrakk> v \\<noteq> root; v \\<in> verts T \\<rbrakk> \\<Longrightarrow> \\<exists>e. in_arcs T v = {e}\"\n  using not_root_imp_in_deg_one unfolding in_degree_def\n  by (auto simp: card_Suc_eq)\n\nlemma ex_leaf: \"finite (verts T) \\<Longrightarrow> \\<exists>v \\<in> verts T. leaf v\"\nproof(rule ccontr, simp)\n  assume verts_fin: \"finite (verts T)\" and  no_leaves: \"\\<forall>x\\<in>verts T. \\<not> leaf x\"\n  then have \"\\<forall>x \\<in> verts T. \\<exists>e. e \\<in> out_arcs T x\"\n    unfolding leaf_def by (simp add: out_arcs_def)\n  then have \"\\<forall>x \\<in> verts T. \\<exists>x' e. awalk x [e] x'\"\n    unfolding out_arcs_def using arc_implies_awalk by force\n  then have extend: \"\\<exists>p v'. awalk u (ps@[p]) v'\" if \"awalk u ps v\" for u ps v\n    using that by force\n  have \"\\<exists>u p v. awalk u p v \\<and> length p = n\" for n\n  proof(induction n)\n    case 0\n    from root_in_T have \"awalk root [] root\"\n      by (simp add: awalk_Nil_iff)\n    then show ?case by blast\n  next\n    case (Suc n)\n    then obtain u p v where \"awalk u p v\" and \"length p = n\" by blast\n    from extend[OF this(1)] obtain e v' where \"awalk u (p@[e]) v'\" and \"length (p@[e]) = Suc n\"\n      using length_append_singleton \\<open>length p = n\\<close> by auto\n    then show ?case by blast\n  qed\n  with awalk_not_distinct[OF verts_fin] have \"\\<exists>p. cycle p\"\n    using awalk_cyc_decompE' closed_w_imp_cycle by (metis order_refl)\n  with cycle_free show False by blast\nqed\n\nlemma verts_finite_imp_arcs_finite: \"finite (verts T) \\<Longrightarrow> finite (arcs T)\"\nproof -\n  assume \"finite (verts T)\"\n  then have \"finite (verts T \\<times> verts T)\" by simp\n  let ?a = \"\\<lambda>(u,v). {e \\<in> arcs T.  tail T e = u \\<and> head T e = v}\"\n  let ?A = \"\\<Union>{?a e |e. e \\<in> verts T \\<times> verts T}\"\n  have \"arcs T \\<subseteq> ?A\"\n  proof\n    fix e assume e: \"e \\<in> arcs T\"\n    then have \"tail T e \\<in> verts T\" and \"head T e \\<in> verts T\"\n      using wellformed by auto\n    with e show \"e \\<in> ?A\" by blast\n  qed\n  moreover\n  have \"finite (?a (u,v))\" for u v\n    using unique_arc_set[of u v] finite.simps by auto\n  with finite_Union[OF \\<open>finite (verts T \\<times> verts T)\\<close>] have \"finite ?A\"\n    by blast\n  ultimately show \"finite (arcs T)\" using finite_subset by blast\nqed\n\nlemma root_leaf_iff: \"leaf root \\<longleftrightarrow> verts T = {root}\"\nproof\n  from root_in_T show \"verts T = {root} \\<Longrightarrow> leaf root\"\n    using leaf_def ex_leaf by auto\n  show \"leaf root \\<Longrightarrow> (verts T = {root})\"\n  proof(rule ccontr)\n    assume \"leaf root\" and \"verts T \\<noteq> {root}\"\n    with non_empty obtain u where u: \"u \\<in> verts T\" \"u \\<noteq>root\"\n      by blast\n    with unique_awalk obtain p where p: \"awalk root p u\" by blast\n    with \\<open>u \\<noteq> root\\<close> obtain e where e: \"e = hd p\" \"tail T e = root\"\n      by (metis awalkE' awalk_ends pre_digraph.cas_simp)\n    with u p have \"e \\<in> out_arcs T root\" unfolding out_arcs_def\n      by (simp, metis awalkE awalk_ends hd_in_set subset_iff)\n    with \\<open>leaf root\\<close> show \"False\"\n      unfolding leaf_def out_degree_def by auto\n  qed\nqed\n\nlemma leaf_not_mem_awalk:\n  \"\\<lbrakk> leaf x; awalk u p v; v \\<noteq> x \\<rbrakk> \\<Longrightarrow> x \\<notin> set (awalk_verts u p)\"\nproof(induction p arbitrary: u)\n  case Nil\n  then have \"u = v\" unfolding awalk_conv by simp\n  with Nil show ?case by auto\nnext\n  case (Cons a p)\n  then have \"x \\<notin> set (awalk_verts (head T a) p)\" by (simp add: awalk_Cons_iff)\n  moreover\n  from Cons.prems have \"tail T a \\<noteq> x\"\n    unfolding leaf_def out_arcs_def by auto\n  ultimately show ?case by simp\nqed\n\nlemma tree_del_vert:\n  assumes \"v \\<noteq> root\" and \"leaf v\"\n  shows \"directed_tree (del_vert v) root\"\nproof(unfold_locales)\n  from \\<open>v \\<noteq> root\\<close> show \"root \\<in> verts (del_vert v)\" using verts_del_vert root_in_T by auto\n\n  have \"u\\<in>verts (del_vert v) \\<Longrightarrow> \\<exists>!p. pre_digraph.awalk (del_vert v) root p u\" for u\n  proof -\n    assume \"u \\<in> verts (del_vert v)\"\n    then have \"u \\<in> verts T\" \"u \\<noteq> v\" by (simp_all add: verts_del_vert)\n    then obtain p where p: \"awalk root p u\" \"\\<forall>p'. awalk root p' u \\<longrightarrow> p = p'\"\n    using unique_awalk[OF \\<open>u \\<in> verts T\\<close>] by auto\n    then have \"v \\<notin> set (awalk_verts root p)\"\n    using leaf_not_mem_awalk[OF \\<open>leaf v\\<close> _ \\<open>u \\<noteq> v\\<close>] by blast\n    with p have\n      \"pre_digraph.awalk (del_vert v) root p u\"\n      \"\\<forall>p'. pre_digraph.awalk (del_vert v) root p' u \\<longrightarrow> p = p'\"\n      using awalk_del_vert subgraph_awalk_imp_awalk subgraph_del_vert by blast+\n    then show ?thesis by blast\n  qed\n  then show \"\\<And>va. va \\<in> verts (del_vert v)\n  \\<Longrightarrow> \\<exists>!p. pre_digraph.awalk (del_vert v) root p va\" by blast\nqed (meson wf_digraph_del_vert wf_digraph_def)+\n\nlemma arcs_del_leaf:\n  assumes e: \"e \\<in> arcs T\" \"head T e = v\" and v: \"leaf v\"\n  shows \"arcs (del_vert v) = arcs T - {e}\"\nproof -\n  from v have \"out_arcs T v = {}\"\n    unfolding pre_digraph.leaf_def by simp\n  moreover\n  from e v have \"v \\<noteq> root\"\n    using loopfree.no_loops root_leaf_iff by fastforce\n  from ex_in_arc[OF this] v have \"in_arcs T v = {e}\"\n    unfolding pre_digraph.leaf_def using e e two_in_arcs_contr by fastforce\n  ultimately show ?thesis unfolding out_arcs_def in_arcs_def\n    using arcs_del_vert2 by auto\nqed\n\nlemma finite_directed_tree_induct[consumes 1, case_names single_vert add_leaf]:\n  assumes \"finite (verts T)\"\n  assumes base: \"\\<And>t h root. P \\<lparr> verts = {root}, arcs = {}, tail = t, head = h \\<rparr>\"\n      and add_leaf: \"\\<And>T' V A t h u root a v. \\<lbrakk>T' = \\<lparr> verts = V, arcs = A, tail = t, head = h \\<rparr>; finite (verts T');\n            directed_tree T' root; P T'; u \\<in> V; v \\<notin> V; a \\<notin> A\\<rbrakk>\n    \\<Longrightarrow> P \\<lparr> verts = V \\<union> {v}, arcs = A \\<union> {a}, tail = t(a := u), head = h(a := v) \\<rparr>\"\n    shows \"P T\"\n  using assms(1) directed_tree_axioms\nproof(induction \"card (verts T)\" arbitrary: T root)\n  case 0\n  then have \"verts T = {}\" using card_eq_0_iff by simp\n  with directed_tree.non_empty[OF \\<open>directed_tree T root\\<close>] show ?case by blast\nnext\n  case (Suc n)\n  then interpret tree_T: directed_tree T root by simp\n  show ?case\n  proof(cases \"n = 0\")\n    case True\n    with \\<open>Suc n = card (verts T)\\<close> have \"card (verts T) = 1\" by simp\n    from mem_card1_singleton[OF tree_T.root_in_T this] have \"verts T = {root}\" .\n    then have \"arcs T = {}\"\n      using tree_T.loopfree.no_loops tree_T.tail_in_verts by fastforce\n    with \\<open>verts T = {root}\\<close> have \"T = \\<lparr> verts = {root}, arcs = {}, tail = tail T, head = head T \\<rparr>\"\n      by simp\n    with base[of root \"tail T\" \"head T\"] show ?thesis by simp\n  next\n    case False\n\n    from Suc.prems(1) have \"finite (verts T)\"\n      using finite_insert by simp\n    from tree_T.ex_leaf[OF this]\n    obtain v where v: \"tree_T.leaf v\" by blast\n    with False have \"v \\<noteq> root\"\n      using tree_T.root_leaf_iff Suc.hyps(2) by fastforce\n    note v = \\<open>tree_T.leaf v\\<close> \\<open>v \\<noteq> root\\<close>\n\n    let ?T' = \"tree_T.del_vert v\"\n    have T': \"?T' = \\<lparr> verts = verts ?T', arcs = arcs ?T', tail = tail ?T', head = head ?T' \\<rparr>\"\n      by simp\n    note tree_T.tree_del_vert[OF v(2,1)]\n    moreover\n    have \"finite (verts ?T')\"\n      by (simp add: tree_T.verts_del_vert \\<open>finite (verts T)\\<close>)\n    moreover\n    from \\<open>finite (verts ?T')\\<close> Suc.hyps(2) Suc.prems(1) have \"card (verts ?T') = n\"\n      using tree_T.verts_del_vert v(1)[unfolded tree_T.leaf_def] by auto\n    moreover\n    from tree_T.ex_in_arc[OF v(2)]\n    obtain e where e: \"in_arcs T v = {e}\" \"tail T e \\<in> verts T\"\n      using v(1)[unfolded tree_T.leaf_def] by force\n    then have \"tail T e \\<in> verts ?T'\"\n      unfolding in_arcs_def using tree_T.arcs_del_vert[of v]\n      using tree_T.loopfree.no_loops tree_T.verts_del_vert[of v]\n      using v(1)[unfolded tree_T.leaf_def] by fastforce\n    moreover\n    from Suc.hyps(1) have \"P ?T'\" using calculation by blast\n    moreover\n    note tree_T.verts_del_vert[of v]\n    moreover\n    from e have \"head T e = v\" unfolding in_arcs_def by blast\n    then have \"e \\<notin> arcs ?T'\" unfolding tree_T.arcs_del_vert by simp\n\n    ultimately have \"P \\<lparr> verts = verts ?T' \\<union> {v}, arcs = arcs ?T' \\<union> {e},\n      tail = (tail ?T')(e := (tail T e)), head = (head ?T')(e := v) \\<rparr>\"\n      using add_leaf[OF T'] by blast\n    moreover\n    have \"T = \\<lparr> verts = verts ?T' \\<union> {v}, arcs = arcs ?T' \\<union> {e},\n      tail = (tail ?T')(e := (tail T e)), head = (head ?T')(e := v) \\<rparr>\"\n    proof -\n      have \"verts T = verts ?T' \\<union> {v}\"\n        using v(1)[unfolded tree_T.leaf_def] tree_T.verts_del_vert[of v] by fastforce\n      moreover\n      have \"arcs ?T' = arcs T - out_arcs T v - in_arcs T v\"\n        using tree_T.arcs_del_vert2 by fastforce\n      with e v(1)[unfolded pre_digraph.leaf_def] have \"arcs T = arcs ?T' \\<union> {e}\" by auto\n      moreover\n      have \"tail T = (tail ?T')(e := (tail T e))\"\n        by (simp add: tree_T.tail_del_vert)\n      moreover\n      from e[unfolded in_arcs_def] have \"head T = (head ?T')(e := v)\"\n        using tree_T.head_del_vert \\<open>head T e = v\\<close> by auto\n      ultimately show ?thesis by simp\n    qed\n    ultimately show ?thesis by simp\n  qed\nqed\n\ntext \\<open>A simple consequence of the induction rule is that a tree with n vertices has n-1 arcs.\\<close>\nlemma Suc_card_arcs_eq_card_verts:\n  assumes \"finite (verts T)\"\n  shows \"Suc (card (arcs T)) = card (verts T)\"\nusing assms\nproof(induction rule: finite_directed_tree_induct)\n  case (single_vert)\n  then show ?case by simp\nnext\n  case (add_leaf)\n  then show ?case\n    using directed_tree.verts_finite_imp_arcs_finite\n    by fastforce\nqed\n\nsubsection \\<open>Depth of a tree\\<close>\n\ndefinition depth where \"depth w \\<equiv> Sup {\\<mu> w root v|v. v \\<in> verts T}\"\n\ncontext\n  fixes w :: \"'b weight_fun\"\n  assumes \"\\<forall>e \\<in> arcs T. w e \\<ge> 0\"\nbegin\n\nlemma sp_from_root_le: \"u \\<rightarrow>\\<^sup>*\\<^bsub>T\\<^esub> v \\<Longrightarrow> \\<mu> w root v \\<ge> \\<mu> w u v\"\nproof -\n  assume \"u \\<rightarrow>\\<^sup>*\\<^bsub>T\\<^esub> v\"\n\n  have \"\\<mu> w root u \\<ge> 0\"\n    using \\<open>\\<forall>e\\<in>arcs T. 0 \\<le> w e\\<close> sp_non_neg_if_w_non_neg by simp\n  moreover\n  have \"root \\<rightarrow>\\<^sup>*\\<^bsub>T\\<^esub> u\"\n    using \\<open>u \\<rightarrow>\\<^sup>*\\<^bsub>T\\<^esub> v\\<close> reachable_from_root reachable_in_verts(1) by auto\n  ultimately show ?thesis\n    using \\<open>u \\<rightarrow>\\<^sup>*\\<^bsub>T\\<^esub> v\\<close> sp_append2 ereal_le_add_self2 by auto\nqed\n\nlemma depth_lowerB: \"v \\<in> verts T \\<Longrightarrow> depth w \\<ge> \\<mu> w root v\"\nproof -\n  assume \"v \\<in> verts T\"\n  then have \"\\<mu> w root v \\<in> {\\<mu> w root v|v. v \\<in> verts T}\" by auto\n  then show \"depth w \\<ge> \\<mu> w root v\"\n    unfolding depth_def by (simp add: Sup_upper)\nqed\n\nlemma depth_upperB: \"\\<forall>v \\<in> verts T. \\<mu> w root v \\<le> d \\<Longrightarrow> depth w \\<le> d\"\nproof -\n  assume \"\\<forall>v \\<in> verts T. \\<mu> w root v \\<le> d\"\n  then have \"\\<forall>x \\<in> {\\<mu> w root v |v. v \\<in> verts T}. x \\<le> d\"\n    by auto\n  then show ?thesis\n    unfolding depth_def using Sup_least by fast\nqed\n\ntext \\<open>\nThis relation between depth of a tree and its diameter is later used to establish the\ncorrectness of the diameter estimate.\n\\<close>\nlemma depth_eq_fin_dia: \"fin_digraph T \\<Longrightarrow> depth w = fin_diameter w\"\nproof -\n  assume \"fin_digraph T\"\n  have \"\\<forall>v \\<in> verts T. \\<mu> w root v < \\<infinity>\"\n    using \\<mu>_reach_conv reachable_from_root by blast\n  then have \"{\\<mu> w root v|v. v \\<in> verts T} \\<subseteq> fin_sp_costs w\"\n    unfolding fin_sp_costs_def using root_in_T by blast\n  then have \"depth w \\<le> fin_diameter w\"\n    unfolding depth_def fin_diameter_def by (simp add: Sup_subset_mono)\n  moreover\n  have \"\\<not> depth w < fin_diameter w\"\n  proof\n    assume \"depth w < fin_diameter w\"\n    obtain u v where \"\\<mu> w u v = fin_diameter w\" \"u \\<in> verts T\" \"v \\<in> verts T\"\n      using fin_digraph.ex_sp_eq_fin_dia[OF \\<open>fin_digraph T\\<close> non_empty] by blast\n    then have \"u \\<rightarrow>\\<^sup>*\\<^bsub>T\\<^esub> v\"\n      by (metis \\<mu>_reach_conv fin_digraph.fin_diameter_finite[OF \\<open>fin_digraph T\\<close>])\n    then have \"\\<mu> w u v \\<le> \\<mu> w root v\" using sp_from_root_le by blast\n    also have \"\\<dots> \\<le> depth w\" using depth_lowerB[OF \\<open>v \\<in> verts T\\<close>] by simp\n    finally have \"fin_diameter w \\<le> depth w\"\n      using \\<open>\\<mu> w u v = fin_diameter w\\<close> by simp\n    with \\<open>depth w < fin_diameter w\\<close> show False by simp\n  qed\n  ultimately show ?thesis by simp\nqed\n\nend\n\nend\n\nsection \\<open>Subgraph locale\\<close>\n\nlocale subgraph =\n    G: wf_digraph G for T G +\nassumes\n  sub_G: \"subgraph T G\"\nbegin\n\nsublocale wf_digraph T\n  using sub_G unfolding subgraph_def by blast\n\nlemma awalk_sub_imp_awalk:\n  \"awalk a p b \\<Longrightarrow> G.awalk a p b\"\n  using G.subgraph_awalk_imp_awalk sub_G by force\n\nend\n\nsection \\<open>Partial shortest path three\\<close>\n\nlocale psp_tree =\n  directed_tree T source + subgraph T G for G T w source n +\n  assumes\n    source_in_G: \"source \\<in> verts G\" and\n    partial: \"G.n_nearest_verts w source n (verts T)\" and\n    sp: \"u \\<in> verts T \\<Longrightarrow> \\<mu> w source u = G.\\<mu> w source u\"\nbegin\n\ntext \\<open>\nHere we formalize the notion of a partial shortest path tree. This is a shortest path tree where\nonly the @{term n} nearest nodes in the graph @{term G} are explored.\nConsequently, a partial shortest path tree is a subtree of the complete shortest path tree.\nWe can obtain the complete shortest path tree by choosing n to be larger than the cardinality\nof the graph @{term G}.\n\\<close>\n\nsublocale fin_digraph T\nproof(unfold_locales)\n  show \"finite (verts T)\" using G.nnvs_finite[OF partial] .\n  from verts_finite_imp_arcs_finite[OF this] show \"finite (arcs T)\" .\nqed\n\nlemma card_verts_le: \"card (verts T) \\<le> Suc n\"\n  using G.nnvs_card_le_n partial by auto\n\nlemma reachable_subs: \"{x. r \\<rightarrow>\\<^sup>*\\<^bsub>T\\<^esub> x} \\<subseteq> {x. r \\<rightarrow>\\<^sup>*\\<^bsub>G\\<^esub> x}\"\n  by (simp add: Collect_mono G.reachable_mono sub_G)\n\ntext \\<open>The following lemma proves that we explore all nodes if we set @{term n} large enough.\\<close>\nlemma sp_tree:\n  assumes \"fin_digraph G\"\n  assumes card_reachable: \"Suc n \\<ge> card {x. source \\<rightarrow>\\<^sup>*\\<^bsub>G\\<^esub> x}\"\n  shows \"verts T = {x. source \\<rightarrow>\\<^sup>*\\<^bsub>G\\<^esub> x}\"\n  using fin_digraph.nnvs_imp_all_reachable_Suc[OF \\<open>fin_digraph G\\<close> partial card_reachable] .\n\ncorollary sp_tree2:\n  assumes \"fin_digraph G\"\n  assumes \"Suc n \\<ge> card (verts G)\"\n  shows \"verts T = {x. source \\<rightarrow>\\<^sup>*\\<^bsub>G\\<^esub> x}\"\nproof -\n  have \"{x. source \\<rightarrow>\\<^sup>*\\<^bsub>G\\<^esub> x} \\<subseteq> verts G\"\n    using source_in_G G.reachable_in_verts(2) by blast\n  then have \"Suc n \\<ge> card {x. source \\<rightarrow>\\<^sup>*\\<^bsub>G\\<^esub> x}\"\n    using \\<open>Suc n \\<ge> card (verts G)\\<close> fin_digraph.finite_verts[OF \\<open>fin_digraph G\\<close>]\n    by (meson card_mono dual_order.trans)\n  from sp_tree[OF \\<open>fin_digraph G\\<close> this] show ?thesis .\nqed\n\nlemma strongly_con_imp_card_verts_eq:\n  assumes \"fin_digraph G\"\n  assumes \"strongly_connected G\"\n  assumes card_verts: \"Suc n \\<le> card (verts G)\"\n  shows \"card (verts T) = Suc n\"\nproof -\n  have verts_G: \"verts G = {x. source \\<rightarrow>\\<^sup>*\\<^bsub>G\\<^esub> x}\"\n    using G.strongly_con_imp_reachable_eq_verts\n      [OF source_in_G \\<open>strongly_connected G\\<close>, symmetric] .\n  with card_verts have \"Suc n \\<le> card {x. source \\<rightarrow>\\<^sup>*\\<^bsub>G\\<^esub> x}\" by simp\n\n  from fin_digraph.nnvs_imp_reachable[OF \\<open>fin_digraph G\\<close> partial this]\n  show ?thesis by blast\nqed\n\nlemma depth_fin_dia_lB:\n  assumes \"\\<forall>e \\<in> arcs G. w e \\<ge> 0\"\n  shows \"depth w \\<le> G.fin_diameter w\"\nproof(rule ccontr)\n  assume \"\\<not> depth w \\<le> G.fin_diameter w\"\n  then have \"depth w > G.fin_diameter w\"\n    by auto\n  then have \"\\<exists>v \\<in> verts T. \\<mu> w source v > G.fin_diameter w\"\n    unfolding depth_def by (auto simp: less_Sup_iff)\n  then obtain v where v: \"v \\<in> verts T\" \"v \\<in> verts G\" \"\\<mu> w source v > G.fin_diameter w\"\n    using sub_G by blast\n  moreover\n  have \"\\<mu> w source v < \\<infinity>\"\n    using reachable_from_root \\<mu>_reach_conv v(1) by blast\n  ultimately show \"False\"\n    using source_in_G G.fin_dia_lowerB[OF source_in_G \\<open>v \\<in> verts G\\<close>] sp v\n    by (simp add: leD)\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/Shortest_Path_Tree.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8740772417253255, "lm_q2_score": 0.8438951104066295, "lm_q1q2_score": 0.7376295104097157}}
{"text": "(*  Title:      HOL/Old_Number_Theory/IntPrimes.thy\n    Author:     Thomas M. Rasmussen\n    Copyright   2000  University of Cambridge\n*)\n\nsection {* Divisibility and prime numbers (on integers) *}\n\ntheory IntPrimes\nimports Primes\nbegin\n\ntext {*\n  The @{text dvd} relation, GCD, Euclid's extended algorithm, primes,\n  congruences (all on the Integers).  Comparable to theory @{text\n  Primes}, but @{text dvd} is included here as it is not present in\n  main HOL.  Also includes extended GCD and congruences not present in\n  @{text Primes}.\n*}\n\n\nsubsection {* Definitions *}\n\nfun xzgcda :: \"int \\<Rightarrow> int \\<Rightarrow> int \\<Rightarrow> int \\<Rightarrow> int \\<Rightarrow> int \\<Rightarrow> int \\<Rightarrow> int => (int * int * int)\"\nwhere\n  \"xzgcda m n r' r s' s t' t =\n        (if r \\<le> 0 then (r', s', t')\n         else xzgcda m n r (r' mod r) \n                      s (s' - (r' div r) * s) \n                      t (t' - (r' div r) * t))\"\n\ndefinition zprime :: \"int \\<Rightarrow> bool\"\n  where \"zprime p = (1 < p \\<and> (\\<forall>m. 0 <= m & m dvd p --> m = 1 \\<or> m = p))\"\n\ndefinition xzgcd :: \"int => int => int * int * int\"\n  where \"xzgcd m n = xzgcda m n m n 1 0 0 1\"\n\ndefinition zcong :: \"int => int => int => bool\"  (\"(1[_ = _] '(mod _'))\")\n  where \"[a = b] (mod m) = (m dvd (a - b))\"\n\n\nsubsection {* Euclid's Algorithm and GCD *}\n\n\nlemma zrelprime_zdvd_zmult_aux:\n     \"zgcd n k = 1 ==> k dvd m * n ==> 0 \\<le> m ==> k dvd m\"\n    by (metis abs_of_nonneg dvd_triv_right zgcd_greatest_iff zgcd_zmult_distrib2_abs mult_1_right)\n\nlemma zrelprime_zdvd_zmult: \"zgcd n k = 1 ==> k dvd m * n ==> k dvd m\"\n  apply (case_tac \"0 \\<le> m\")\n   apply (blast intro: zrelprime_zdvd_zmult_aux)\n  apply (subgoal_tac \"k dvd -m\")\n   apply (rule_tac [2] zrelprime_zdvd_zmult_aux, auto)\n  done\n\nlemma zgcd_geq_zero: \"0 <= zgcd x y\"\n  by (auto simp add: zgcd_def)\n\ntext{*This is merely a sanity check on zprime, since the previous version\n      denoted the empty set.*}\nlemma \"zprime 2\"\n  apply (auto simp add: zprime_def) \n  apply (frule zdvd_imp_le, simp) \n  apply (auto simp add: order_le_less dvd_def) \n  done\n\nlemma zprime_imp_zrelprime:\n    \"zprime p ==> \\<not> p dvd n ==> zgcd n p = 1\"\n  apply (auto simp add: zprime_def)\n  apply (metis zgcd_geq_zero zgcd_zdvd1 zgcd_zdvd2)\n  done\n\nlemma zless_zprime_imp_zrelprime:\n    \"zprime p ==> 0 < n ==> n < p ==> zgcd n p = 1\"\n  apply (erule zprime_imp_zrelprime)\n  apply (erule zdvd_not_zless, assumption)\n  done\n\nlemma zprime_zdvd_zmult:\n    \"0 \\<le> (m::int) ==> zprime p ==> p dvd m * n ==> p dvd m \\<or> p dvd n\"\n  by (metis zgcd_zdvd1 zgcd_zdvd2 zgcd_pos zprime_def zrelprime_dvd_mult)\n\nlemma zgcd_zadd_zmult [simp]: \"zgcd (m + n * k) n = zgcd m n\"\n  apply (rule zgcd_eq [THEN trans])\n  apply (simp add: mod_add_eq)\n  apply (rule zgcd_eq [symmetric])\n  done\n\nlemma zgcd_zdvd_zgcd_zmult: \"zgcd m n dvd zgcd (k * m) n\"\nby (simp add: zgcd_greatest_iff)\n\nlemma zgcd_zmult_zdvd_zgcd:\n    \"zgcd k n = 1 ==> zgcd (k * m) n dvd zgcd m n\"\n  apply (simp add: zgcd_greatest_iff)\n  apply (rule_tac n = k in zrelprime_zdvd_zmult)\n   prefer 2\n   apply (simp add: mult.commute)\n  apply (metis zgcd_1 zgcd_commute zgcd_left_commute)\n  done\n\nlemma zgcd_zmult_cancel: \"zgcd k n = 1 ==> zgcd (k * m) n = zgcd m n\"\n  by (simp add: zgcd_def nat_abs_mult_distrib gcd_mult_cancel)\n\nlemma zgcd_zgcd_zmult:\n    \"zgcd k m = 1 ==> zgcd n m = 1 ==> zgcd (k * n) m = 1\"\n  by (simp add: zgcd_zmult_cancel)\n\nlemma zdvd_iff_zgcd: \"0 < m ==> m dvd n \\<longleftrightarrow> zgcd n m = m\"\n  by (metis abs_of_pos dvd_mult_div_cancel zgcd_0 zgcd_commute zgcd_geq_zero zgcd_zdvd2 zgcd_zmult_eq_self)\n\n\n\nsubsection {* Congruences *}\n\nlemma zcong_1 [simp]: \"[a = b] (mod 1)\"\n  by (unfold zcong_def, auto)\n\nlemma zcong_refl [simp]: \"[k = k] (mod m)\"\n  by (unfold zcong_def, auto)\n\nlemma zcong_sym: \"[a = b] (mod m) = [b = a] (mod m)\"\n  unfolding zcong_def minus_diff_eq [of a, symmetric] dvd_minus_iff ..\n\nlemma zcong_zadd:\n    \"[a = b] (mod m) ==> [c = d] (mod m) ==> [a + c = b + d] (mod m)\"\n  apply (unfold zcong_def)\n  apply (rule_tac s = \"(a - b) + (c - d)\" in subst)\n   apply (rule_tac [2] dvd_add, auto)\n  done\n\nlemma zcong_zdiff:\n    \"[a = b] (mod m) ==> [c = d] (mod m) ==> [a - c = b - d] (mod m)\"\n  apply (unfold zcong_def)\n  apply (rule_tac s = \"(a - b) - (c - d)\" in subst)\n   apply (rule_tac [2] dvd_diff, auto)\n  done\n\nlemma zcong_trans:\n  \"[a = b] (mod m) ==> [b = c] (mod m) ==> [a = c] (mod m)\"\nunfolding zcong_def by (auto elim!: dvdE simp add: algebra_simps)\n\nlemma zcong_zmult:\n    \"[a = b] (mod m) ==> [c = d] (mod m) ==> [a * c = b * d] (mod m)\"\n  apply (rule_tac b = \"b * c\" in zcong_trans)\n   apply (unfold zcong_def)\n  apply (metis right_diff_distrib dvd_mult mult.commute)\n  apply (metis right_diff_distrib dvd_mult)\n  done\n\nlemma zcong_scalar: \"[a = b] (mod m) ==> [a * k = b * k] (mod m)\"\n  by (rule zcong_zmult, simp_all)\n\nlemma zcong_scalar2: \"[a = b] (mod m) ==> [k * a = k * b] (mod m)\"\n  by (rule zcong_zmult, simp_all)\n\nlemma zcong_zmult_self: \"[a * m = b * m] (mod m)\"\n  apply (unfold zcong_def)\n  apply (rule dvd_diff, simp_all)\n  done\n\nlemma zcong_square:\n   \"[| zprime p;  0 < a;  [a * a = 1] (mod p)|]\n    ==> [a = 1] (mod p) \\<or> [a = p - 1] (mod p)\"\n  apply (unfold zcong_def)\n  apply (rule zprime_zdvd_zmult)\n    apply (rule_tac [3] s = \"a * a - 1 + p * (1 - a)\" in subst)\n     prefer 4\n     apply (simp add: zdvd_reduce)\n    apply (simp_all add: left_diff_distrib mult.commute right_diff_distrib)\n  done\n\nlemma zcong_cancel:\n  \"0 \\<le> m ==>\n    zgcd k m = 1 ==> [a * k = b * k] (mod m) = [a = b] (mod m)\"\n  apply safe\n   prefer 2\n   apply (blast intro: zcong_scalar)\n  apply (case_tac \"b < a\")\n   prefer 2\n   apply (subst zcong_sym)\n   apply (unfold zcong_def)\n   apply (rule_tac [!] zrelprime_zdvd_zmult)\n     apply (simp_all add: left_diff_distrib)\n  apply (subgoal_tac \"m dvd (-(a * k - b * k))\")\n   apply simp\n  apply (subst dvd_minus_iff, assumption)\n  done\n\nlemma zcong_cancel2:\n  \"0 \\<le> m ==>\n    zgcd k m = 1 ==> [k * a = k * b] (mod m) = [a = b] (mod m)\"\n  by (simp add: mult.commute zcong_cancel)\n\nlemma zcong_zgcd_zmult_zmod:\n  \"[a = b] (mod m) ==> [a = b] (mod n) ==> zgcd m n = 1\n    ==> [a = b] (mod m * n)\"\n  apply (auto simp add: zcong_def dvd_def)\n  apply (subgoal_tac \"m dvd n * ka\")\n   apply (subgoal_tac \"m dvd ka\")\n    apply (case_tac [2] \"0 \\<le> ka\")\n  apply (metis dvd_mult_div_cancel dvd_refl dvd_mult_left mult.commute zrelprime_zdvd_zmult)\n  apply (metis abs_dvd_iff abs_of_nonneg add_0 zgcd_0_left zgcd_commute zgcd_zadd_zmult zgcd_zdvd_zgcd_zmult zgcd_zmult_distrib2_abs mult_1_right mult.commute)\n  apply (metis mult_le_0_iff  zdvd_mono zdvd_mult_cancel dvd_triv_left zero_le_mult_iff order_antisym linorder_linear order_refl mult.commute zrelprime_zdvd_zmult)\n  apply (metis dvd_triv_left)\n  done\n\nlemma zcong_zless_imp_eq:\n  \"0 \\<le> a ==>\n    a < m ==> 0 \\<le> b ==> b < m ==> [a = b] (mod m) ==> a = b\"\n  apply (unfold zcong_def dvd_def, auto)\n  apply (drule_tac f = \"\\<lambda>z. z mod m\" in arg_cong)\n  apply (metis diff_add_cancel mod_pos_pos_trivial add_0 add.commute zmod_eq_0_iff mod_add_right_eq)\n  done\n\nlemma zcong_square_zless:\n  \"zprime p ==> 0 < a ==> a < p ==>\n    [a * a = 1] (mod p) ==> a = 1 \\<or> a = p - 1\"\n  apply (cut_tac p = p and a = a in zcong_square)\n     apply (simp add: zprime_def)\n    apply (auto intro: zcong_zless_imp_eq)\n  done\n\nlemma zcong_not:\n    \"0 < a ==> a < m ==> 0 < b ==> b < a ==> \\<not> [a = b] (mod m)\"\n  apply (unfold zcong_def)\n  apply (rule zdvd_not_zless, auto)\n  done\n\nlemma zcong_zless_0:\n    \"0 \\<le> a ==> a < m ==> [a = 0] (mod m) ==> a = 0\"\n  apply (unfold zcong_def dvd_def, auto)\n  apply (metis div_pos_pos_trivial linorder_not_less div_mult_self1_is_id)\n  done\n\nlemma zcong_zless_unique:\n    \"0 < m ==> (\\<exists>!b. 0 \\<le> b \\<and> b < m \\<and> [a = b] (mod m))\"\n  apply auto\n   prefer 2 apply (metis zcong_sym zcong_trans zcong_zless_imp_eq)\n  apply (unfold zcong_def dvd_def)\n  apply (rule_tac x = \"a mod m\" in exI, auto)\n  apply (metis zmult_div_cancel)\n  done\n\nlemma zcong_iff_lin: \"([a = b] (mod m)) = (\\<exists>k. b = a + m * k)\"\n  unfolding zcong_def\n  apply (auto elim!: dvdE simp add: algebra_simps)\n  apply (rule_tac x = \"-k\" in exI) apply simp\n  done\n\nlemma zgcd_zcong_zgcd:\n  \"0 < m ==>\n    zgcd a m = 1 ==> [a = b] (mod m) ==> zgcd b m = 1\"\n  by (auto simp add: zcong_iff_lin)\n\nlemma zcong_zmod_aux:\n     \"a - b = (m::int) * (a div m - b div m) + (a mod m - b mod m)\"\n  by(simp add: right_diff_distrib add_diff_eq eq_diff_eq ac_simps)\n\nlemma zcong_zmod: \"[a = b] (mod m) = [a mod m = b mod m] (mod m)\"\n  apply (unfold zcong_def)\n  apply (rule_tac t = \"a - b\" in ssubst)\n  apply (rule_tac m = m in zcong_zmod_aux)\n  apply (rule trans)\n   apply (rule_tac [2] k = m and m = \"a div m - b div m\" in zdvd_reduce)\n  apply (simp add: add.commute)\n  done\n\nlemma zcong_zmod_eq: \"0 < m ==> [a = b] (mod m) = (a mod m = b mod m)\"\n  apply auto\n  apply (metis pos_mod_conj zcong_zless_imp_eq zcong_zmod)\n  apply (metis zcong_refl zcong_zmod)\n  done\n\nlemma zcong_zminus [iff]: \"[a = b] (mod -m) = [a = b] (mod m)\"\n  by (auto simp add: zcong_def)\n\nlemma zcong_zero [iff]: \"[a = b] (mod 0) = (a = b)\"\n  by (auto simp add: zcong_def)\n\nlemma \"[a = b] (mod m) = (a mod m = b mod m)\"\n  apply (cases \"m = 0\", simp)\n  apply (simp add: linorder_neq_iff)\n  apply (erule disjE)  \n   prefer 2 apply (simp add: zcong_zmod_eq)\n  txt{*Remainding case: @{term \"m<0\"}*}\n  apply (rule_tac t = m in minus_minus [THEN subst])\n  apply (subst zcong_zminus)\n  apply (subst zcong_zmod_eq, arith)\n  apply (frule neg_mod_bound [of _ a], frule neg_mod_bound [of _ b]) \n  apply (simp add: zmod_zminus2_eq_if del: neg_mod_bound)\n  done\n\nsubsection {* Modulo *}\n\nlemma zmod_zdvd_zmod:\n    \"0 < (m::int) ==> m dvd b ==> (a mod b mod m) = (a mod m)\"\n  by (rule mod_mod_cancel) \n\n\nsubsection {* Extended GCD *}\n\ndeclare xzgcda.simps [simp del]\n\nlemma xzgcd_correct_aux1:\n  \"zgcd r' r = k --> 0 < r -->\n    (\\<exists>sn tn. xzgcda m n r' r s' s t' t = (k, sn, tn))\"\n  apply (induct m n r' r s' s t' t rule: xzgcda.induct)\n  apply (subst zgcd_eq)\n  apply (subst xzgcda.simps, auto)\n  apply (case_tac \"r' mod r = 0\")\n   prefer 2\n   apply (frule_tac a = \"r'\" in pos_mod_sign, auto)\n  apply (rule exI)\n  apply (rule exI)\n  apply (subst xzgcda.simps, auto)\n  done\n\nlemma xzgcd_correct_aux2:\n  \"(\\<exists>sn tn. xzgcda m n r' r s' s t' t = (k, sn, tn)) --> 0 < r -->\n    zgcd r' r = k\"\n  apply (induct m n r' r s' s t' t rule: xzgcda.induct)\n  apply (subst zgcd_eq)\n  apply (subst xzgcda.simps)\n  apply (auto simp add: linorder_not_le)\n  apply (case_tac \"r' mod r = 0\")\n   prefer 2\n   apply (frule_tac a = \"r'\" in pos_mod_sign, auto)\n  apply (metis Pair_eq xzgcda.simps order_refl)\n  done\n\nlemma xzgcd_correct:\n    \"0 < n ==> (zgcd m n = k) = (\\<exists>s t. xzgcd m n = (k, s, t))\"\n  apply (unfold xzgcd_def)\n  apply (rule iffI)\n   apply (rule_tac [2] xzgcd_correct_aux2 [THEN mp, THEN mp])\n    apply (rule xzgcd_correct_aux1 [THEN mp, THEN mp], auto)\n  done\n\n\ntext {* \\medskip @{term xzgcd} linear *}\n\nlemma xzgcda_linear_aux1:\n  \"(a - r * b) * m + (c - r * d) * (n::int) =\n   (a * m + c * n) - r * (b * m + d * n)\"\n  by (simp add: left_diff_distrib distrib_left mult.assoc)\n\nlemma xzgcda_linear_aux2:\n  \"r' = s' * m + t' * n ==> r = s * m + t * n\n    ==> (r' mod r) = (s' - (r' div r) * s) * m + (t' - (r' div r) * t) * (n::int)\"\n  apply (rule trans)\n   apply (rule_tac [2] xzgcda_linear_aux1 [symmetric])\n  apply (simp add: eq_diff_eq mult.commute)\n  done\n\nlemma order_le_neq_implies_less: \"(x::'a::order) \\<le> y ==> x \\<noteq> y ==> x < y\"\n  by (rule iffD2 [OF order_less_le conjI])\n\nlemma xzgcda_linear [rule_format]:\n  \"0 < r --> xzgcda m n r' r s' s t' t = (rn, sn, tn) -->\n    r' = s' * m + t' * n -->  r = s * m + t * n --> rn = sn * m + tn * n\"\n  apply (induct m n r' r s' s t' t rule: xzgcda.induct)\n  apply (subst xzgcda.simps)\n  apply (simp (no_asm))\n  apply (rule impI)+\n  apply (case_tac \"r' mod r = 0\")\n   apply (simp add: xzgcda.simps, clarify)\n  apply (subgoal_tac \"0 < r' mod r\")\n   apply (rule_tac [2] order_le_neq_implies_less)\n   apply (rule_tac [2] pos_mod_sign)\n    apply (cut_tac m = m and n = n and r' = r' and r = r and s' = s' and\n      s = s and t' = t' and t = t in xzgcda_linear_aux2, auto)\n  done\n\nlemma xzgcd_linear:\n    \"0 < n ==> xzgcd m n = (r, s, t) ==> r = s * m + t * n\"\n  apply (unfold xzgcd_def)\n  apply (erule xzgcda_linear, assumption, auto)\n  done\n\nlemma zgcd_ex_linear:\n    \"0 < n ==> zgcd m n = k ==> (\\<exists>s t. k = s * m + t * n)\"\n  apply (simp add: xzgcd_correct, safe)\n  apply (rule exI)+\n  apply (erule xzgcd_linear, auto)\n  done\n\nlemma zcong_lineq_ex:\n    \"0 < n ==> zgcd a n = 1 ==> \\<exists>x. [a * x = 1] (mod n)\"\n  apply (cut_tac m = a and n = n and k = 1 in zgcd_ex_linear, safe)\n  apply (rule_tac x = s in exI)\n  apply (rule_tac b = \"s * a + t * n\" in zcong_trans)\n   prefer 2\n   apply simp\n  apply (unfold zcong_def)\n  apply (simp (no_asm) add: mult.commute)\n  done\n\nlemma zcong_lineq_unique:\n  \"0 < n ==>\n    zgcd a n = 1 ==> \\<exists>!x. 0 \\<le> x \\<and> x < n \\<and> [a * x = b] (mod n)\"\n  apply auto\n   apply (rule_tac [2] zcong_zless_imp_eq)\n       apply (tactic {* stac (@{thm zcong_cancel2} RS sym) 6 *})\n         apply (rule_tac [8] zcong_trans)\n          apply (simp_all (no_asm_simp))\n   prefer 2\n   apply (simp add: zcong_sym)\n  apply (cut_tac a = a and n = n in zcong_lineq_ex, auto)\n  apply (rule_tac x = \"x * b mod n\" in exI, safe)\n    apply (simp_all (no_asm_simp))\n  apply (metis zcong_scalar zcong_zmod mod_mult_right_eq mult_1 mult.assoc)\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/HOL/Old_Number_Theory/IntPrimes.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772482857833, "lm_q2_score": 0.8438951025545426, "lm_q1q2_score": 0.7376295090827234}}
{"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_MSortBU2Sorts\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 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 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\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_MSortBU2Sorts.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772417253256, "lm_q2_score": 0.8438951084436077, "lm_q1q2_score": 0.7376295086938832}}
{"text": "(* Author: Tobias Nipkow *)\n\nsection \\<open>Multiset of Elements of Binary Tree\\<close>\n\ntheory Tree_Multiset\nimports Multiset Tree\nbegin\n\ntext\\<open>Kept separate from theory @{theory Tree} to avoid importing all of\ntheory @{theory Multiset} into @{theory Tree}. Should be merged if\n@{theory Multiset} ever becomes part of @{theory Main}.\\<close>\n\nfun mset_tree :: \"'a tree \\<Rightarrow> 'a multiset\" where\n\"mset_tree Leaf = {#}\" |\n\"mset_tree (Node l a r) = {#a#} + mset_tree l + mset_tree r\"\n\nfun subtrees_mset :: \"'a tree \\<Rightarrow> 'a tree multiset\" where\n\"subtrees_mset Leaf = {#Leaf#}\" |\n\"subtrees_mset (Node l x r) = add_mset (Node l x r) (subtrees_mset l + subtrees_mset r)\"\n\n\nlemma set_mset_tree[simp]: \"set_mset (mset_tree t) = set_tree t\"\nby(induction t) auto\n\nlemma size_mset_tree[simp]: \"size(mset_tree t) = size t\"\nby(induction t) auto\n\nlemma mset_map_tree: \"mset_tree (map_tree f t) = image_mset f (mset_tree t)\"\nby (induction t) auto\n\nlemma mset_iff_set_tree: \"x \\<in># mset_tree t \\<longleftrightarrow> x \\<in> set_tree t\"\nby(induction t arbitrary: x) auto\n\nlemma mset_preorder[simp]: \"mset (preorder t) = mset_tree t\"\nby (induction t) (auto simp: ac_simps)\n\nlemma mset_inorder[simp]: \"mset (inorder t) = mset_tree t\"\nby (induction t) (auto simp: ac_simps)\n\nlemma map_mirror: \"mset_tree (mirror t) = mset_tree t\"\nby (induction t) (simp_all add: ac_simps)\n\n\nlemma in_subtrees_mset_iff[simp]: \"s \\<in># subtrees_mset t \\<longleftrightarrow> s \\<in> subtrees t\"\nby(induction t) auto\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/Tree_Multiset.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8740772482857833, "lm_q2_score": 0.8438950966654774, "lm_q1q2_score": 0.7376295039352255}}
{"text": "(*  Title:      HOL/Isar_Examples/Knaster_Tarski.thy\n    Author:     Markus Wenzel, TU Muenchen\n\nTypical textbook proof example.\n*)\n\nsection \\<open>Textbook-style reasoning: the Knaster-Tarski Theorem\\<close>\n\ntheory Knaster_Tarski\nimports Main \"~~/src/HOL/Library/Lattice_Syntax\"\nbegin\n\n\nsubsection \\<open>Prose version\\<close>\n\ntext \\<open>According to the textbook @{cite \\<open>pages 93--94\\<close> \"davey-priestley\"},\n  the Knaster-Tarski fixpoint theorem is as\n  follows.\\footnote{We have dualized the argument, and tuned the\n  notation a little bit.}\n\n  \\textbf{The Knaster-Tarski Fixpoint Theorem.}  Let @{text L} be a\n  complete lattice and @{text \"f: L \\<rightarrow> L\"} an order-preserving map.\n  Then @{text \"\\<Sqinter>{x \\<in> L | f(x) \\<le> x}\"} is a fixpoint of @{text f}.\n\n  \\textbf{Proof.} Let @{text \"H = {x \\<in> L | f(x) \\<le> x}\"} and @{text \"a =\n  \\<Sqinter>H\"}.  For all @{text \"x \\<in> H\"} we have @{text \"a \\<le> x\"}, so @{text\n  \"f(a) \\<le> f(x) \\<le> x\"}.  Thus @{text \"f(a)\"} is a lower bound of @{text\n  H}, whence @{text \"f(a) \\<le> a\"}.  We now use this inequality to prove\n  the reverse one (!) and thereby complete the proof that @{text a} is\n  a fixpoint.  Since @{text f} is order-preserving, @{text \"f(f(a)) \\<le>\n  f(a)\"}.  This says @{text \"f(a) \\<in> H\"}, so @{text \"a \\<le> f(a)\"}.\\<close>\n\n\nsubsection \\<open>Formal versions\\<close>\n\ntext \\<open>The Isar proof below closely follows the original\n  presentation.  Virtually all of the prose narration has been\n  rephrased in terms of formal Isar language elements.  Just as many\n  textbook-style proofs, there is a strong bias towards forward proof,\n  and several bends in the course of reasoning.\\<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>Above we have used several advanced Isar language elements,\n  such as explicit block structure and weak assumptions.  Thus we have\n  mimicked the particular way of reasoning of the original text.\n\n  In the subsequent version the order of reasoning is changed to\n  achieve structured top-down decomposition of the problem at the\n  outer level, while only the inner steps of reasoning are done in a\n  forward manner.  We are certainly more at ease here, requiring only\n  the most basic features of the Isar language.\\<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": "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/Knaster_Tarski.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951025545426, "lm_q2_score": 0.8740772400852111, "lm_q1q2_score": 0.7376295021623008}}
{"text": "(******************************************************************************)\n(* Submission: \"The Interchange Law: A Principle of Concurrent Programming\"   *)\n(* Authors: Tony Hoare, Bernard M\u00f6ller, Georg Struth, and Frank Zeyda         *)\n(* File: ICL_Examples.thy                                                     *)\n(******************************************************************************)\n(* LAST REVIEWED: TODO *)\n\nsection {* Example Applications *}\n\ntheory ICL_Examples\nimports ICL Strict_Operators Computer_Arith Partiality\nbegin\n\nhide_const Partiality.Value\n\ntext \\<open>We are going to use the `\\<open>|\\<close>' symbol for parallel composition.\\<close>\n\nno_notation (ASCII)\n  disj  (infixr \"|\" 30)\n\ntext \\<open>Example applications of the interchange law from the article.\\<close>\n\nsubsection \\<open>Arithmetic: addition (\\<open>+\\<close>) and subtraction (\\<open>-\\<close>) of numbers.\\<close>\n\ntext \\<open>\n  We prove the interchange laws for the HOL types @{type int}, @{type rat} and\n  @{type real}, as well as the corresponding @{type option} types of those. We\n  note that the law does not hold for type @{type nat}, although a weaker\n  version using \\<open>\\<le>\\<close> instead of equality is provable because Isabelle/HOL\n  interprets the minus operators as monus on natural numbers.\n\\<close>\n\ninterpretation icl_plus_minus_nat:\n  iclaw \"TYPE(nat)\" \"op =\" \"op -\" \"op +\"\napply (unfold_locales)\napply (linarith?)\noops\n\ninterpretation icl_plus_minus_nat:\n  iclaw \"TYPE(nat)\" \"op \\<le>\" \"op -\" \"op +\"\napply (unfold_locales)\napply (linarith)\noops\n\ninterpretation icl_plus_minus_nat_option:\n  iclaw \"TYPE(nat option)\" \"op \\<le>\\<^sub>?\" \"op -\\<^sub>?\" \"op +\\<^sub>?\"\napply (unfold_locales)\napply (option_tac)\ndone\n\ninterpretation icl_plus_minus_int:\n  iclaw \"TYPE(int)\" \"op =\" \"op -\" \"op +\"\napply (unfold_locales)\napply (linarith)\ndone\n\ninterpretation icl_plus_minus_rat:\n  iclaw \"TYPE(rat)\" \"op =\" \"op -\" \"op +\"\napply (unfold_locales)\napply (linarith)\ndone\n\ninterpretation icl_plus_minus_real:\n  iclaw \"TYPE(real)\" \"op =\" \"op -\" \"op +\"\napply (unfold_locales)\napply (linarith)\ndone\n\ntext \\<open>Corresponding proofs for option types and strict operators.\\<close>\n\ninterpretation icl_plus_minus_int_option:\n  iclaw \"TYPE(int option)\" \"op =\\<^sub>?\" \"op -\\<^sub>?\" \"op +\\<^sub>?\"\napply (unfold_locales)\napply (option_tac)\ndone\n\ninterpretation icl_plus_minus_rat_option:\n  iclaw \"TYPE(rat option)\" \"op =\\<^sub>?\" \"op -\\<^sub>?\" \"op +\\<^sub>?\"\napply (unfold_locales)\napply (option_tac)\ndone\n\ninterpretation icl_plus_minus_real_option:\n  iclaw \"TYPE(real option)\" \"op =\\<^sub>?\" \"op -\\<^sub>?\" \"op +\\<^sub>?\"\napply (unfold_locales)\napply (option_tac)\ndone\n\nsubsection \\<open>Positive arithmetic: with multiplication (\\<open>\\<times>\\<close>).\\<close>\n\ninterpretation icl_plus_times_nat:\n  iclaw \"TYPE(nat)\" \"op \\<le>\" \"op +\" \"op *\"\napply (unfold_locales)\napply (simp add: distrib_left distrib_right)\ndone\n\ninterpretation icl_plus_times_nat_option:\n  iclaw \"TYPE(nat option)\" \"op \\<le>\\<^sub>?\" \"op +\\<^sub>?\" \"op *\\<^sub>?\"\napply (unfold_locales)\napply (option_tac)\napply (simp add: distrib_left distrib_right)\ndone\n\ninterpretation icl_plus_times_nat_option:\n  iclaw \"TYPE(int)\" \"op \\<le>\" \"op +\" \"op *\"\napply (unfold_locales)\napply (subgoal_tac \"p \\<ge> 0 \\<and> r \\<ge> 0 \\<and> q \\<ge> 0 \\<and> s \\<ge> 0\")\n-- {* Subgoal 1 *}\napply (clarify)\napply (unfold ring_distribs)\napply (unfold sym [OF add.assoc])\napply (simp)\noops\n\ntext \\<open>\n  We note that the law can be proved more generally to hold in any (ordered)\n  @{class semiring} in which @{term 0} is the least element. To mechanically\n  verify this result, it is useful to introduce a type class that guarantees\n  that all elements of a type are positive.\n\\<close>\n\nclass positive = zero + ord +\n  assumes zero_least: \"0 \\<le> x\"\n\ninterpretation icl_positive_semiring:\n  iclaw \"TYPE('a::{positive,ordered_semiring})\" \"op \\<le>\" \"op +\" \"op *\"\napply (unfold_locales)\napply (simp add: distrib_left distrib_right)\napply (metis add.right_neutral add_increasing add_mono order_refl zero_least)\ndone\n\ntext \\<open>Clearly, all elements of the type @{type nat} are positive.\\<close>\n\ninstance nat :: positive\napply (intro_classes)\napply (simp)\ndone\n\ntext \\<open>\n  For other number types, such as @{type int}eger, @{type rat}ional and\n  @{type real} numbers, we introduce a subtype \\<open>'a pos\\<close> that includes only the\n  positive individuals of some type @{typ \"'a\"}. In order to establish the\n  non-emptiness caveat of the type definition, we require that the ordering be\n  a @{class preorder}.\n\\<close>\n\ntypedef (overloaded) 'a::\"{zero, preorder}\" pos = \"{x::'a. 0 \\<le> x}\"\napply (clarsimp)\napply (rule_tac x = \"0\" in exI)\napply (rule order_refl)\ndone\n\nsetup_lifting type_definition_pos\n\ntext \\<open>We next lift `\\<open>\\<le>\\<close>', `\\<open>0\\<close>', `\\<open>+\\<close>' and `\\<open>*\\<close>' into the new type @{type pos}.\\<close>\n\ninstantiation pos :: (\"{zero,preorder}\") preorder\nbegin\nlift_definition less_eq_pos :: \"'a pos \\<Rightarrow> 'a pos \\<Rightarrow> bool\"\nis \"op \\<le>\" .\nlift_definition less_pos :: \"'a pos \\<Rightarrow> 'a pos \\<Rightarrow> bool\"\nis \"op <\" .\ninstance\napply (intro_classes; transfer)\nusing less_le_not_le apply (blast)\nusing order_refl apply (blast)\nusing order_trans apply (blast)\ndone\nend\n\ninstantiation pos :: (\"{zero,preorder}\") zero\nbegin\nlift_definition zero_pos :: \"'a pos\"\nis \"0\" by (rule order_refl)\ninstance ..\nend\n\ntext \\<open>\n  We note that for the lifting of `\\<open>+\\<close>' and `\\<open>*\\<close>', we require closure of those\n  operators under positive numbers. Such is, however, provable within ordered\n  semi-rings, as we establish later on.\n\\<close>\n\nclass plus_pos_cl = zero + ord + plus +\n  assumes plus_pos_closure: \"0 \\<le> x \\<Longrightarrow> 0 \\<le> y \\<Longrightarrow> 0 \\<le> x + y\"\n\nclass times_pos_cl = zero + ord + times +\n  assumes times_pos_closure: \"0 \\<le> x \\<Longrightarrow> 0 \\<le> y \\<Longrightarrow> 0 \\<le> x * y\"\n\ninstantiation pos :: (\"{zero,preorder,plus_pos_cl}\") plus\nbegin\nlift_definition plus_pos :: \"'a pos \\<Rightarrow> 'a pos \\<Rightarrow> 'a pos\"\nis \"op +\" by (rule plus_pos_closure)\ninstance ..\nend\n\ninstantiation pos :: (\"{zero,preorder,times_pos_cl}\") times\nbegin\nlift_definition times_pos :: \"'a pos \\<Rightarrow> 'a pos \\<Rightarrow> 'a pos\"\nis \"op *\" by (rule times_pos_closure)\ninstance ..\nend\n\ntext \\<open>\n  We prove that the above closure property of `\\<open>+\\<close>' and `\\<open>*\\<close>' wrt the positive\n  individuals holds within any (ordered) semi-ring.\n\\<close>\n\nsubclass (in ordered_semiring) plus_pos_cl\napply (unfold class.plus_pos_cl_def)\nusing local.add_nonneg_nonneg by (blast)\n\nsubclass (in ordered_semiring_0) times_pos_cl\napply (unfold class.times_pos_cl_def)\nusing local.mult_nonneg_nonneg by (blast)\n\ntext \\<open>\n  Lastly, we prove that subtype @{typ \"'a pos\"} over some (ordered) semi-ring\n  is itself and ordered semi-ring, albeit comprising positive elements only.\n  With the earlier interpretation proof, namely for \\<open>icl_positive_semiring\\<close>,\n  this implies that the interchange law holds for positive arithmetic with\n  multiplication within any (ordered) semi-ring, including positive rational\n  and real numbers.\n\\<close>\n\ninstance pos :: (\"{zero, preorder}\") positive\napply (intro_classes)\napply (transfer)\napply (assumption)\ndone\n\ninstance pos :: (ordered_semiring_0) ordered_semiring\napply (intro_classes; transfer'; simp?)\napply (simp add: add.assoc)\napply (simp add: add.commute)\napply (simp add: add_left_mono)\napply (simp add: mult.assoc)\napply (simp add: distrib_right)\napply (simp add: distrib_left)\napply (simp add: mult_left_mono)\napply (simp add: mult_right_mono)\ndone\n\ninterpretation icl_plus_times_pos:\n  iclaw \"TYPE('a::ordered_semiring_0 pos)\" \"op \\<le>\" \"op +\" \"op *\"\napply (unfold_locales)\ndone\n\ninterpretation icl_plus_times_pos_option:\n  iclaw \"TYPE('a::ordered_semiring_0 pos option)\" \"op \\<le>\\<^sub>?\" \"op +\\<^sub>?\" \"op *\\<^sub>?\"\napply (unfold_locales)\napply (option_tac)\napply (rule icl_positive_semiring.interchange_law)\ndone\n\ninterpretation icl_plus_times_pos_int:\n  iclaw \"TYPE(int pos)\" \"op \\<le>\" \"op +\" \"op *\"\napply (unfold_locales)\ndone\n\ninterpretation icl_plus_times_pos_rat:\n  iclaw \"TYPE(rat pos)\" \"op \\<le>\" \"op +\" \"op *\"\napply (unfold_locales)\ndone\n\ninterpretation icl_plus_times_pos_real:\n  iclaw \"TYPE(real pos)\" \"op \\<le>\" \"op +\" \"op *\"\napply (unfold_locales)\ndone\n\ninterpretation icl_plus_times_pos_int_option:\n  iclaw \"TYPE(int pos option)\" \"op \\<le>\\<^sub>?\" \"op +\\<^sub>?\" \"op *\\<^sub>?\"\napply (unfold_locales)\ndone\n\ninterpretation icl_plus_times_pos_rat_option:\n  iclaw \"TYPE(rat pos option)\" \"op \\<le>\\<^sub>?\" \"op +\\<^sub>?\" \"op *\\<^sub>?\"\napply (unfold_locales)\ndone\n\ninterpretation icl_plus_times_pos_real_option:\n  iclaw \"TYPE(real pos option)\" \"op \\<le>\\<^sub>?\" \"op +\\<^sub>?\" \"op *\\<^sub>?\"\napply (unfold_locales)\ndone\n\nsubsection \\<open>Arithmetic: multiplication (\\<open>\\<times>\\<close>) and division (\\<open>/\\<close>) of numbers.\\<close>\n\ntext \\<open>This is proved for @{type rat}, @{type real}, and option types thereof.\\<close>\n\ninterpretation icl_mult_div_rat:\n  iclaw \"TYPE(rat)\" \"op =\" \"op *\" \"op /\"\napply (unfold_locales)\napply (simp)\ndone\n\ninterpretation icl_mult_div_real:\n  iclaw \"TYPE(real)\" \"op =\" \"op *\" \"op /\"\napply (unfold_locales)\napply (simp)\ndone\n\ninterpretation icl_mult_div_field:\n  iclaw \"TYPE('a::field)\" \"op =\" \"op *\" \"op /\"\napply (unfold_locales)\napply (simp)\ndone\n\ninterpretation icl_mult_div_rat_option:\n  iclaw \"TYPE(rat option)\" \"op =\\<^sub>?\" \"op *\\<^sub>?\" \"op /\\<^sub>?\"\napply (unfold_locales)\napply (option_tac)\ndone\n\ninterpretation icl_mult_div_real_option:\n  iclaw \"TYPE(real option)\" \"op =\\<^sub>?\" \"op *\\<^sub>?\" \"op /\\<^sub>?\"\napply (unfold_locales)\napply (option_tac)\ndone\n\ntext \\<open>\n  Theorem 1 likewise holds for @{type rat}ional and @{type real} numbers and\n  option types thereof.\n\\<close>\n\nlemma Theorem1_rat:\nfixes p :: \"rat\"\nfixes q :: \"rat\"\nshows \"(p / q) * q = (p * q) / q\"\napply (insert icl_mult_div_rat.interchange_law [of p q q 1])\napply (unfold div_by_1 mult_1_right)\napply (assumption)\ndone\n\nlemma Theorem1_real:\nfixes p :: \"real\"\nfixes q :: \"real\"\nshows \"(p / q) * q = (p * q) / q\"\napply (insert icl_mult_div_real.interchange_law [of p q q 1])\napply (unfold div_by_1 mult_1_right)\napply (assumption)\ndone\n\nlemma Theorem1_rat_option:\nfixes p :: \"rat option\"\nfixes q :: \"rat option\"\nshows \"(p /\\<^sub>? q) *\\<^sub>? q = (p *\\<^sub>? q) /\\<^sub>? q\"\napply (insert icl_mult_div_rat_option.interchange_law [of p q q 1])\napply (unfold div_by_1_option mult_1_right_option)\napply (case_tac p; case_tac q; option_tac)\ndone\n\nlemma Theorem1_real_option:\nfixes p :: \"real option\"\nfixes q :: \"real option\"\nshows \"(p /\\<^sub>? q) *\\<^sub>? q = (p *\\<^sub>? q) /\\<^sub>? q\"\napply (insert icl_mult_div_real_option.interchange_law [of p q q 1])\napply (unfold div_by_1_option mult_1_right_option)\napply (case_tac p; case_tac q; option_tac)\ndone\n\ntext \\<open>It also holds, more generally, in any division ring.\\<close>\n\ncontext division_ring\nbegin\nlemma div_mult_exchange:\nfixes p :: \"'a\"\nfixes q :: \"'a\"\nshows \"(p / q) * q = (p * q) / q\"\napply (metis eq_divide_eq mult_eq_0_iff)\ndone\nend\n\nsubsection \\<open>Positive integers: with truncated division (\\<open>\\<div>\\<close>).\\<close>\n\ntext \\<open>\n  By default, @{term \"x div y\"} is also used for truncated (integer) division\n  in Isabelle/HOL. Hence, we first introduce a neat syntax \\<open>x \\<div> y\\<close> consistent\n  with our notation in the paper. This is done via @{command abbreviation}.\n\\<close>\n\nabbreviation trunc_div :: \"nat binop\" (infixl \"\\<div>\" 70) where\n\"x \\<div> y \\<equiv> x div y\"\n\nabbreviation trunc_div_option :: \"nat option binop\" (infixl \"\\<div>\\<^sub>?\" 70) where\n\"x \\<div>\\<^sub>? y \\<equiv> x /\\<^sub>? y\"\n\ntext \\<open>\n  Since Isabelle/HOL defines \\<open>x div 0 = 0\\<close>, we can prove the interchange law\n  even in HOL's weak treatment of undefinedness, as well as in the strong one.\n\\<close>\n\ninterpretation icl_mult_trunc_div_nat:\n  iclaw \"TYPE(nat)\" \"op \\<le>\" \"op *\" \"op \\<div>\"\napply (unfold_locales)\napply (case_tac \"r = 0\"; simp_all)\napply (case_tac \"s = 0\"; simp_all)\napply (subgoal_tac \"(p div r) * (q div s) * (r * s) \\<le> p * q\")\napply (metis div_le_mono div_mult_self_is_m nat_0_less_mult_iff)\napply (unfold semiring_normalization_rules(13))\napply (metis mult.commute mult_le_mono split_div_lemma)\ndone\n\ninterpretation icl_mult_trunc_div_nat_option:\n  iclaw \"TYPE(nat option)\" \"op \\<le>\\<^sub>?\" \"op *\\<^sub>?\" \"op \\<div>\\<^sub>?\"\napply (unfold_locales)\napply (option_tac)\napply (rule icl_mult_trunc_div_nat.interchange_law)\ndone\n\ntext \\<open>\n  With the above, we prove Theorem 2 in the paper, both for natural numbers\n  and the option type over naturals.\n\\<close>\n\nlemma Theorem2:\nfixes p :: \"nat\"\nfixes q :: \"nat\"\nshows \"(p \\<div> q) * q \\<le> (p * q) \\<div> q\"\napply (insert icl_mult_trunc_div_nat.interchange_law [of p q q 1])\napply (unfold div_by_1 mult_1_right)\napply (assumption)\ndone\n\nlemma Theorem2_option:\nfixes p :: \"nat option\"\nfixes q :: \"nat option\"\nshows \"(p \\<div>\\<^sub>? q) *\\<^sub>? q \\<le> (p *\\<^sub>? q) \\<div>\\<^sub>? q\"\napply (insert icl_mult_trunc_div_nat_option.interchange_law [of p q q 1])\napply (unfold div_by_1_option mult_1_right_option)\napply (case_tac p; case_tac q; option_tac)\ndone\n\nsubsection \\<open>Propositional calculus: conjunction (\\<open>\\<and>\\<close>) and implication (\\<open>\\<Rightarrow>\\<close>).\\<close>\n\ntext \\<open>RE: Implication \\<open>p \\<Rightarrow> q\\<close> is defined in the usual way as \\<open>\\<not>p \\<or> q\\<close>.\\<close>\n\ntext \\<open>We can easily verify the above equivalence in HOL.\\<close>\n\nlemma \"(p \\<longrightarrow> q) \\<equiv> (\\<not> p \\<or> q)\"\napply (auto)\ndone\n\ntext \\<open>\n  This instance of the interchange law cannot be proved by way of interpreting\n  the @{locale iclaw} locale because rule implication is not an object-logic\n  operator. Nonetheless, we can prove the interchange law as an Isabelle/HOL\n  proof rule. We note that Isabelle uses \\<open>\\<longrightarrow>\\<close> for implication and \\<open>\\<Longrightarrow>\\<close> for\n  meta-level (rule) implication. To make the theorem look as in the paper, we\n  temporarily change the syntax of those operators.\n\\<close>\n\nnotation HOL.implies (infixr \"\\<Rightarrow>\" 25)\nnotation Pure.imp    (infixr \"\\<turnstile>\" 1)\n\nlemma icl_conj_imp_prop:\n\"(p \\<Rightarrow> q) \\<and> (r \\<Rightarrow> s) \\<turnstile> (p \\<and> r) \\<Rightarrow> (q \\<and> s)\"\napply (auto)\ndone\n\nsubsection \\<open>Boolean Algebra: conjunction (\\<open>\\<and>\\<close>) and disjunction (\\<open>\\<or>\\<close>).\\<close>\n\ntext \\<open>Numerical value of a @{type bool}ean.\\<close>\n\ndefinition valOfBool :: \"bool \\<Rightarrow> nat\" where\n\"valOfBool p = (if p then 1 else 0)\"\n\ntext \\<open>Order on boolean values induced by @{const valOfBool}.\\<close>\n\ndefinition numOrdBool :: \"bool \\<Rightarrow> bool \\<Rightarrow> bool\" where\n\"numOrdBool p q \\<longleftrightarrow> (valOfBool p) \\<le> (valOfBool q)\"\n\ntext \\<open>We show that the numerical order above is just implication.\\<close>\n\nlemma numOrdBool_is_imp [simp]:\n\"(numOrdBool p q) = (p \\<longrightarrow> q)\"\napply (unfold numOrdBool_def valOfBool_def)\napply (induct_tac p; induct_tac q)\napply (simp_all)\ndone\n\ninterpretation preorder_numOrdBool:\n  preorder \"TYPE(bool)\" \"numOrdBool\"\napply (unfold_locales)\napply (unfold numOrdBool_is_imp)\napply (auto)\ndone\n\ntext \\<open>Note that \\<open>;\\<close> is \\<open>\\<or>\\<close> and \\<open>|\\<close> is \\<open>\\<and>\\<close>.\\<close>\n\ninterpretation icl_boolean_algebra:\n  iclaw \"TYPE(bool)\" \"numOrdBool\" \"op \\<or>\" \"op \\<and>\"\napply (unfold_locales)\napply (unfold numOrdBool_is_imp)\napply (auto)\ndone\n\ntext \\<open>Theorem 3 once again needs to be formulated as an Isabelle proof rule.\\<close>\n\nlemma Theorem3:\n\"q \\<and> s \\<turnstile> q \\<or> s\"\napply (auto)\ndone\n\nno_notation HOL.implies (infixr \"\\<Rightarrow>\" 25)\nno_notation Pure.imp    (infixr \"\\<turnstile>\" 1)\n\nsubsection \\<open>Self-interchanging operators: \\<open>+\\<close>, \\<open>\\<times>\\<close>, \\<open>\\<or>\\<close>, \\<open>\\<and>\\<close>.\\<close>\n\ntext \\<open>For convenience, we define a locale for self-interchanging operators.\\<close>\n\nlocale self_iclaw =\n  iclaw \"type\" \"op =\" \"self_op\" \"self_op\"\n  for type :: \"'a itself\" and self_op :: \"'a binop\"\n\ntext \\<open>\n  We next introduce separate locales to capture associativity, commutativity\n  and existence of units for some binary operator. We use a bold circle (\\<open>\\<^bold>\\<circ>\\<close>)\n  to avoid clashes with Isabelle/HOL's symbol (\\<open>\\<circ>\\<close>) for functional composition.\n\\<close>\n\nlocale associative =\n  fixes operator :: \"'a binop\" (infix \"\\<^bold>\\<circ>\" 100)\n  assumes assoc: \"x \\<^bold>\\<circ> (y \\<^bold>\\<circ> z) = (x \\<^bold>\\<circ> y) \\<^bold>\\<circ> z\"\n\nlocale commutative =\n  fixes operator :: \"'a binop\" (infix \"\\<^bold>\\<circ>\" 100)\n  assumes comm: \"x \\<^bold>\\<circ> y = y \\<^bold>\\<circ> x\"\n\nlocale has_unit =\n  fixes operator :: \"'a binop\" (infix \"\\<^bold>\\<circ>\" 100)\n  fixes unit :: \"'a\" (\"\\<^bold>1\")\n  assumes left_unit [simp]: \"\\<^bold>1 \\<^bold>\\<circ> x = x\"\n  assumes right_unit [simp]: \"x \\<^bold>\\<circ> \\<^bold>1 = x\"\n\ntext \\<open>\n  We first show that any associative and commuting operator self-interchanges.\n\\<close>\n\nlemma assoc_comm_self_iclaw:\n\"(associative bop) \\<and> (commutative bop) \\<Longrightarrow> (self_iclaw bop)\"\napply (unfold_locales)\napply (unfold associative_def commutative_def)\napply (clarify)\napply (auto)\ndone\n\ntext \\<open>\n  We next show that self-interchanging operators with a unit are associative\n  and commute (Theorem 4).\n\\<close>\n\nlemma Theorem4_assoc:\n\"(self_iclaw bop) \\<and> (has_unit bop one) \\<Longrightarrow> associative bop\"\napply (unfold_locales)\napply (unfold self_iclaw_def iclaw_def iclaw_axioms_def)\napply (clarsimp)\napply (drule_tac x = \"x\" in spec)\napply (drule_tac x = \"one\" in spec)\napply (drule_tac x = \"y\" in spec)\napply (drule_tac x = \"z\" in spec)\napply (simp add: has_unit_def)\ndone\n\nlemma Theorem4_commute:\n\"(self_iclaw bop) \\<and> (has_unit bop one) \\<Longrightarrow> commutative bop\"\napply (unfold_locales)\napply (unfold self_iclaw_def iclaw_def iclaw_axioms_def)\napply (clarsimp)\napply (drule_tac x = \"one\" in spec)\napply (drule_tac x = \"x\" in spec)\napply (drule_tac x = \"y\" in spec)\napply (drule_tac x = \"one\" in spec)\napply (simp add: has_unit_def)\ndone\n\ntext \\<open>Lastly, we prove the self-interchange law for \\<open>+\\<close>, \\<open>*\\<close>, \\<open>\\<or>\\<close> and \\<open>\\<and>\\<close>.\\<close>\n\ninterpretation self_icl_plus:\n  self_iclaw \"TYPE('a::comm_monoid_add)\" \"op +\"\napply (rule assoc_comm_self_iclaw)\napply (rule conjI)\n-- {* Subgoal 1 *}\napply (unfold associative_def)\napply (simp add: add.assoc)\n-- {* Subgoal 2 *}\napply (unfold commutative_def)\napply (simp add: add.commute)\ndone\n\ninterpretation self_icl_mult:\n  self_iclaw \"TYPE('a::comm_monoid_mult)\" \"op *\"\napply (rule assoc_comm_self_iclaw)\napply (rule conjI)\n-- {* Subgoal 1 *}\napply (unfold associative_def)\napply (simp add: mult.assoc)\n-- {* Subgoal 2 *}\napply (unfold commutative_def)\napply (simp add: mult.commute)\ndone\n\ninterpretation self_icl_conj:\n  self_iclaw \"TYPE(bool)\" \"op \\<and>\"\napply (rule assoc_comm_self_iclaw)\napply (rule conjI)\n-- {* Subgoal 1 *}\napply (standard) [1]\napply (blast)\n-- {* Subgoal 2 *}\napply (standard) [1]\napply (blast)\ndone\n\ninterpretation self_icl_disj:\n  self_iclaw \"TYPE(bool)\" \"op \\<or>\"\napply (rule assoc_comm_self_iclaw)\napply (rule conjI)\n-- {* Subgoal 1 *}\napply (standard) [1]\napply (blast)\n-- {* Subgoal 2 *}\napply (standard) [1]\napply (blast)\ndone\n\ntext \\<open>In addition, we can also show self-interchanging of \\<open>+\\<^sub>?\\<close> and \\<open>*\\<^sub>?\\<close>.\\<close>\n\ninterpretation self_icl_plus_option:\n  self_iclaw \"TYPE('a::comm_monoid_add option)\" \"op +\\<^sub>?\"\napply (rule assoc_comm_self_iclaw)\napply (rule conjI)\n-- {* Subgoal 1 *}\napply (unfold associative_def)\napply (option_tac)\napply (simp add: add.assoc)\n-- {* Subgoal 2 *}\napply (option_tac)\napply (unfold commutative_def)\napply (option_tac)\napply (simp add: add.commute)\ndone\n\ninterpretation self_icl_mult_option:\n  self_iclaw \"TYPE('a::comm_monoid_mult option)\" \"op *\\<^sub>?\"\napply (rule assoc_comm_self_iclaw)\napply (rule conjI)\n-- {* Subgoal 1 *}\napply (unfold associative_def)\napply (option_tac)\napply (simp add: mult.assoc)\n-- {* Subgoal 2 *}\napply (unfold commutative_def)\napply (option_tac)\napply (simp add: mult.commute)\ndone\n\nsubsection \\<open>Note: Partial operators.\\<close>\n\ntext \\<open>TO: This validates the cancellation law in the algebra of Section 4.\\<close>\n\ntext \\<open>\n  Note that the below could even be proved if removing the assumption \\<open>0 < q\\<close>.\n  The reason for this is that in Isabelle/HOL, division by zero is defined to\n  be zero. Below we, however, conduct the prove not exploiting that fact.\n\\<close>\n\nlemma trunc_div_mult_cancel:\nfixes p :: \"nat\"\nfixes q :: \"nat\"\nassumes \"0 < q\"\nshows \"(p \\<div> q) * q \\<le> p\"\napply (insert Theorem2 [of p q])\napply (erule order_trans)\napply (simp)\ndone\n\nlemma trunc_div_mult_cancel_option:\nfixes p :: \"nat option\"\nfixes q :: \"nat option\"\nshows \"(p \\<div>\\<^sub>? q) *\\<^sub>? q \\<le> p\"\napply (induction p; induction q; option_tac)\napply (rename_tac q p)\napply (erule trunc_div_mult_cancel)\ndone\n\nsubsection \\<open>Computer arithmetic: Overflow (\\<open>\\<top>\\<close>).\\<close>\n\ntext \\<open>\n  We note that the various necessary types and operators to formalise machine\n  calculations are developed in the theories:\n  \\begin{itemize}\n    \\item @{theory Strict_Operators};\n    \\item @{theory Machine_Number};\n    \\item @{theory Overflow_Monad}; and\n    \\item @{theory Computer_Arith}.\n  \\end{itemize}\n\\<close>\n\nparagraph \\<open>Cancellation Laws\\<close>\n\nlemma Section_8_cancel_law_1a:\nfixes p :: \"nat machine_number_ext\"\nfixes q :: \"nat machine_number_ext\"\nshows \"q \\<noteq> 0 \\<Longrightarrow> p \\<le> (p *\\<^sub>\\<infinity> q) div\\<^sub>\\<infinity> q\"\napply (transfer) -- \\<open>Just to quantify free variables!\\<close>\napply (overflow_tac)\ndone\n\nlemma Section_8_cancel_law_1b:\nfixes p :: \"nat comparith\"\nfixes q :: \"nat comparith\"\nshows \"q \\<noteq> 0 \\<Longrightarrow> q \\<noteq> \\<bottom> \\<Longrightarrow> p \\<le> (p *\\<^sub>c q) /\\<^sub>c q\"\napply (transfer) -- \\<open>Just to quantify free variables!\\<close>\napply (comparith_tac)\ndone\n\nlemma Section_8_cancel_law_2a:\nfixes p :: \"nat option\"\nfixes q :: \"nat option\"\nshows \"(p /\\<^sub>? q) *\\<^sub>? q \\<le> p\"\napply (transfer) -- \\<open>Just to quantify free variables!\\<close>\napply (option_tac)\napply (metis mult.commute split_div_lemma)\ndone\n\nlemma Section_8_cancel_law_2b:\nfixes p :: \"nat comparith\"\nfixes q :: \"nat comparith\"\nshows \"q \\<noteq> \\<top> \\<Longrightarrow> (p /\\<^sub>c q) *\\<^sub>c q \\<le> p\"\napply (transfer) -- \\<open>Just to quantify free variables!\\<close>\napply (comparith_tac)\napply (transfer)\napply (clarsimp; safe)\n-- {* Subgoal 1 *}\napply (metis mult.commute split_div_lemma)\n-- {* Subgoal 2 *}\nusing div_le_dividend dual_order.trans apply (blast)\n-- {* Subgoal 3 *}\napply (metis dual_order.trans mult.commute split_div_lemma)\ndone\n\nparagraph \\<open>Interchange Law\\<close>\n\nlemma overflow_times_neq_Value_MN_0:\nfixes x :: \"nat machine_number_ext\"\nfixes y :: \"nat machine_number_ext\"\nshows\n\"x \\<noteq> Value MN(0) \\<Longrightarrow>\n y \\<noteq> Value MN(0) \\<Longrightarrow> x *\\<^sub>\\<infinity> y \\<noteq> Value MN(0)\"\napply (transfer) -- \\<open>Just to quantify free variables!\\<close>\napply (overflow_tac)\ndone\n\ninterpretation icl_mult_trunc_div_nat_overflow:\n  iclaw \"TYPE(nat comparith)\" \"op \\<le>\" \"op *\\<^sub>c\" \"op /\\<^sub>c\"\napply (unfold_locales)\napply (option_tac)\napply (simp add: overflow_times_neq_Value_MN_0)\napply (unfold times_overflow_def divide_overflow_def)\napply (thin_tac \"r \\<noteq> Value MN(0)\")\napply (thin_tac \"s \\<noteq> Value MN(0)\")\napply (overflow_tac)\napply (transfer)\napply (clarsimp)\napply (safe)\nusing icl_mult_trunc_div_nat.interchange_law apply (blast)\nusing div_le_dividend dual_order.trans apply (blast)\napply (meson dual_order.trans icl_mult_trunc_div_nat.interchange_law)\nusing div_le_dividend dual_order.trans apply (blast)\ndone\n\nsubsection \\<open>Sets: union (\\<open>\\<union>\\<close>) and disjoint union (\\<open>+\\<close>) of sets, ordered by inclusion \\<open>\\<subseteq>\\<close>.\\<close>\n\ntext \\<open>Proof of the below relies on @{term \"\\<bottom> \\<subseteq>\\<^sub>? A\"} for any \\<open>A\\<close>.\\<close>\n\ninterpretation preorder_option_subset:\n  iclaw \"TYPE('a set option)\" \"(op \\<subseteq>\\<^sub>?)\" \"op \\<oplus>\\<^sub>?\" \"op \\<union>\\<^sub>?\"\napply (unfold_locales)\napply (rename_tac p q r s)\napply (option_tac)\napply (auto)\noops\n\ntext \\<open>RE: Disjoint union has a unit \\<open>{}\\<close>, and so it interchanges with itself.\\<close>\n\ninterpretation disjoint_union_unit:\n  has_unit \"op \\<oplus>\\<^sub>?\" \"Some {}\"\napply (unfold_locales)\napply (option_tac)\napply (option_tac)\ndone\n\ninterpretation self_icl_disjoint_union:\n  self_iclaw \"TYPE('a set option)\" \"op \\<oplus>\\<^sub>?\"\napply (unfold_locales)\napply (option_tac)\napply (auto)\ndone\n\ntext \\<open>\n  RE: But it is clearly not idempotent: \\<open>p \\<oplus>\\<^sub>? p = p\\<close> only when \\<open>p = {}\\<close> or\n  \\<open>p = \\<bottom>\\<close> or \\<open>p = \\<top>\\<close>\n\\<close>\n\ntext \\<open>TODO: Use the type @{type partial} to prove this also for \\<open>\\<top>\\<close>.\\<close>\n\nlemma [rule_format]:\n\"\\<forall>p. p \\<oplus>\\<^sub>? p = p \\<longleftrightarrow> (p = \\<bottom> \\<or> p = Some {})\"\napply (option_tac)\ndone\n\nsubsection \\<open>Note: Variance of operators, covariant (\\<open>+\\<close>,\\<open>\\<and>\\<close>, \\<open>\\<or>\\<close>) and contravariant (\\<open>-\\<close>, \\<open>\\<and>\\<close>, \\<open>\\<Leftarrow>\\<close>)\\<close>\n\ntext \\<open>\n  We introduce the property of covariance and contravariance via locales.\n  For covariance, we have a single locale; and for contravariance, three\n  different locales to account for all possible combinations.\n\\<close>\n\nlocale covariant = preorder +\n  fixes cov_op :: \"'a binop\" (infixr \"cov\" 100)\n  assumes cov_rule: \"x \\<^bold>\\<le> x' \\<and> y \\<^bold>\\<le> y' \\<Longrightarrow> (x cov y) \\<^bold>\\<le> (x' cov y')\"\n\ntext \\<open>We consider contravariance in the first, second or both operators.\\<close>\n\nlocale contravariant = preorder +\n  fixes cot_op :: \"'a binop\" (infixr \"cot\" 100)\n  assumes cot_rule: \"x' \\<^bold>\\<le> x \\<and> y' \\<^bold>\\<le> y \\<Longrightarrow> (x cot y) \\<^bold>\\<le> (x' cot y')\"\n\nlocale contravariant1 = preorder +\n  fixes cot_op :: \"'a binop\" (infixr \"cot\" 100)\n  assumes cot_rule1: \"x' \\<^bold>\\<le> x \\<and> y \\<^bold>\\<le> y' \\<Longrightarrow> (x cot y) \\<^bold>\\<le> (x' cot y')\"\n\nlocale contravariant2 = preorder +\n  fixes cot_op :: \"'a binop\" (infixr \"cot\" 100)\n  assumes cot_rule2: \"x \\<^bold>\\<le> x' \\<and> y' \\<^bold>\\<le> y \\<Longrightarrow> (x cot y) \\<^bold>\\<le> (x' cot y')\"\n\ntext \\<open>Note that if the ordering is equality, all operators are covariant.\\<close>\n\ninterpretation covariant_equality:\n  covariant \"TYPE('a)\" \"op =\" \"f::'a binop\"\napply (intro_locales)\napply (unfold covariant_axioms_def)\napply (clarsimp)\ndone\n\ninterpretation contravariant_equality:\n  contravariant \"TYPE('a)\" \"op =\" \"f::'a binop\"\napply (intro_locales)\napply (unfold contravariant_axioms_def)\napply (clarsimp)\ndone\n\ninterpretation contravariant1_equality:\n  contravariant1 \"TYPE('a)\" \"op =\" \"f::'a binop\"\napply (intro_locales)\napply (unfold contravariant1_axioms_def)\napply (clarsimp)\ndone\n\ninterpretation contravariant2_equality:\n  contravariant2 \"TYPE('a)\" \"op =\" \"f::'a binop\"\napply (intro_locales)\napply (unfold contravariant2_axioms_def)\napply (clarsimp)\ndone\n\ntext \\<open>\n  Below, we prove covariance of \\<open>+\\<close> for @{type nat}ural, @{type int}eger,\n  @{type rat}ional and @{type real} numbers, as well as extensions of those\n  types with \\<open>\\<bottom>\\<close>.\n\\<close>\n\ninterpretation covariant_plus_nat:\n  covariant \"TYPE(nat)\" \"op \\<le>\" \"op +\"\napply (unfold_locales)\napply (linarith)\ndone\n\ninterpretation covariant_plus_int:\n  covariant \"TYPE(int)\" \"op \\<le>\" \"op +\"\napply (unfold_locales)\napply (linarith)\ndone\n\ninterpretation covariant_plus_rat:\n  covariant \"TYPE(rat)\" \"op \\<le>\" \"op +\"\napply (unfold_locales)\napply (linarith)\ndone\n\ninterpretation covariant_plus_real:\n  covariant \"TYPE(real)\" \"op \\<le>\" \"op +\"\napply (unfold_locales)\napply (linarith)\ndone\n\ninterpretation covariant_plus_nat_option:\n  covariant \"TYPE(nat option)\" \"op \\<le>\\<^sub>?\" \"op +\\<^sub>?\"\napply (unfold_locales)\napply (option_tac)\ndone\n\ninterpretation covariant_plus_int_option:\n  covariant \"TYPE(int option)\" \"op \\<le>\\<^sub>?\" \"op +\\<^sub>?\"\napply (unfold_locales)\napply (option_tac)\ndone\n\ninterpretation covariant_plus_rat_option:\n  covariant \"TYPE(rat option)\" \"op \\<le>\\<^sub>?\" \"op +\\<^sub>?\"\napply (unfold_locales)\napply (option_tac)\ndone\n\ninterpretation covariant_plus_real_option:\n  covariant \"TYPE(real option)\" \"op \\<le>\\<^sub>?\" \"op +\\<^sub>?\"\napply (unfold_locales)\napply (option_tac)\ndone\n\ntext \\<open>Covariance of conjunction and disjunction with respect to implication.\\<close>\n\ninterpretation covariant_conj:\n  covariant \"TYPE(bool)\" \"op \\<longrightarrow>\" \"op \\<and>\"\napply (unfold_locales)\napply (clarsimp)\ndone\n\ninterpretation covariant_disj:\n  covariant \"TYPE(bool)\" \"op \\<longrightarrow>\" \"op \\<or>\"\napply (unfold_locales)\napply (clarsimp)\ndone\n\ntext \\<open>\n  We prove contravariance in the right operator of \\<open>-\\<close> for @{type nat}ural,\n  @{type int}eger, @{type rat}ional and @{type real} numbers. We note that\n  contravariance does not hold for their respective @{type option} types. A\n  counter examples is where \\<open>y' = \\<bottom>\\<close> in \\<open>(x cov y) \\<^bold>\\<le> (x' cov y')\\<close> with all\n  other quantities defined.\n\\<close>\n\ninterpretation contravariant2_minus_nat:\n  contravariant2 \"TYPE(nat)\" \"op \\<le>\" \"op -\"\napply (unfold_locales)\napply (linarith)\ndone\n\ninterpretation contravariant2_minus_int:\n  contravariant2 \"TYPE(int)\" \"op \\<le>\" \"op -\"\napply (unfold_locales)\napply (linarith)\ndone\n\ninterpretation contravariant2_minus_rat:\n  contravariant2 \"TYPE(rat)\" \"op \\<le>\" \"op -\"\napply (unfold_locales)\napply (linarith)\ndone\n\ninterpretation contravariant2_minus_real:\n  contravariant2 \"TYPE(real)\" \"op \\<le>\" \"op -\"\napply (unfold_locales)\napply (linarith)\ndone\n\ntext \\<open>\n  Contravariance of division actually could not be proved. First of all it\n  does not hold for plain number types @{type nat} since the additional caveat\n  @{term \"y' > 0\"} is needed, see the proof below. For @{type int}, @{type rat}\n  and @{type real} it is even worse, since we also need to show that \\<open>y*y'\\<close> is\n  positive. Moving to @{type option} types does not help as we are facing the\n  same issue as for \\<open>-\\<close> above. Various instances of the contravariance law for\n  division may only be proved if we strengthen the assumptions on \\<open>y\\<close> and \\<open>y'\\<close>.\n\\<close>\n\ninterpretation contravariant2_nat:\n  contravariant2 \"TYPE(nat)\" \"op \\<le>\" \"op div\"\napply (unfold_locales)\napply (clarify)\napply (subgoal_tac \"x div y \\<le> x div y'\")\napply (erule order_trans)\napply (erule div_le_mono)\napply (rule div_le_mono2)\napply (simp_all)\noops\n\ninterpretation contravariant2_rat:\n  contravariant2 \"TYPE(rat)\" \"op \\<le>\" \"op /\"\napply (unfold_locales)\napply (clarify)\napply (subgoal_tac \"x / y \\<le> x / y'\")\napply (erule order_trans)\napply (erule divide_right_mono) defer\napply (erule divide_left_mono) defer\ndefer\noops\n\ninterpretation contravariant2_div_nat:\n  contravariant2 \"TYPE(nat option)\" \"op \\<le>\\<^sub>?\" \"op /\\<^sub>?\"\napply (unfold_locales)\napply (option_tac)\napply (safe; clarsimp?) defer\napply (subgoal_tac \"x div y \\<le> x div y'\")\napply (erule order_trans)\napply (erule div_le_mono)\napply (erule div_le_mono2)\napply (assumption)\noops\n\ntext \\<open>Contravariance in the second operators holds for reverse implication.\\<close>\n\ninterpretation contravariant_ref_implies:\n  contravariant2 \"TYPE(bool)\" \"op \\<longrightarrow>\" \"op \\<longleftarrow>\"\napply (unfold_locales)\napply (auto)\ndone\n\ntext \\<open>\n  Covariance and contravariance with respect to equality is trivial in HOL due\n  to Leibniz's law following from the axioms of the HOL kernel.\n\\<close>\n\nsubsection {* Note: Modularity, compositionality, locality, etc. *}\n\ntext \\<open>\n  This proof could  be more involved in requiring inductive reasoning about\n  arbitrary languages whose operators are covariant with respect to an order.\n  In a deep embedding of a specific language, this would not be difficult to\n  show. We will not dig deeper into mechanically proving this property in all\n  its generality, as it requires deep embedding of HOL functions, and giving\n  a semantics to this (in HOL) I stipulate is beyond expressivity of the type\n  system of HOL. An inductive proof would have to proceed at the meta-level.\n\\<close>\n\nsubsection \\<open>Strings of characters: catenation (\\<open>;\\<close>) interleaving (\\<open>|\\<close>) and empty string (\\<open>\\<epsilon>\\<close>).\\<close>\n\ntext \\<open>We first define a datatype to formalise the syntax of our string algebra.\\<close>\n\ntext \\<open>Note that we added a constructor for a single character (\\<open>atom\\<close>).\\<close>\n\ndatatype 'a str_calc =\n  empty_str (\"\\<epsilon>\") |\n  atom \"'a\" |\n  seq_str \"'a str_calc\" \"'a str_calc\" (infixr \";\" 110) |\n  par_str \"'a str_calc\" \"'a str_calc\" (infixr \"|\" 100)\n\ntext \\<open>The following function facilitates construction from HOL strings.\\<close>\n\nprimrec mk_str :: \"string \\<Rightarrow> char str_calc\" (*(\"\\<guillemotleft>_\\<guillemotright>\" )*) where\n\"mk_str [] = \\<epsilon>\" |\n\"mk_str (h # t) = seq_str (atom h) (mk_str t)\"\n\nsyntax \"_mk_str\" :: \"id \\<Rightarrow> char str_calc\" (\"\\<guillemotleft>_\\<guillemotright>\")\n\nparse_translation \\<open>\n  let\n    fun mk_str_tr [Free  (name, _)] = @{const mk_str} $ (HOLogic.mk_string name)\n      | mk_str_tr [Const (name, _)] = @{const mk_str} $ (HOLogic.mk_string name)\n      | mk_str_tr _ = raise Match;\n  in\n    [(@{syntax_const \"_mk_str\"}, K mk_str_tr)]\n  end\n\\<close>\n\ntranslations \"_mk_str s\" \\<leftharpoondown> \"(CONST mk_str) s\"\n\ntext \\<open>The function \\<open>ch\\<close> yields all characters in a @{type str_calc} term.\\<close>\n\nprimrec ch :: \"'a str_calc \\<Rightarrow> 'a set\" where\n\"ch \\<epsilon> = {}\" |\n\"ch (atom c) = {c}\" |\n\"ch (p ; q) = (ch p) \\<union> (ch q)\" |\n\"ch (p | q) = (ch p) \\<union> (ch q)\"\n\ntext \\<open>The function \\<open>sd\\<close> computes the sequential dependencies using \\<open>ch\\<close>.\\<close>\n\nprimrec sd :: \"'a str_calc \\<Rightarrow> ('a \\<times> 'a) set\" where\n\"sd \\<epsilon> = {}\" |\n\"sd (atom c) = {}\" |\n\"sd (p ; q) = {(c, d). c \\<in> (ch p) \\<and> d \\<in> (ch q)} \\<union> sd(p) \\<union> sd(q)\" |\n\"sd (p | q) = sd(p) \\<union> sd(q)\"\n\n(*<*)\nvalue \"ch \\<guillemotleft>frank\\<guillemotright>\"\nvalue \"sd \\<guillemotleft>frank\\<guillemotright>\"\n(*>*)\ntext \\<open>We are now able to define our ordering of @{type str_calc} objects.\\<close>\n\ninstantiation str_calc :: (type) ord\nbegin\ndefinition less_eq_str_calc :: \"'a str_calc \\<Rightarrow> 'a str_calc \\<Rightarrow> bool\" where\n\"less_eq_str_calc p q \\<longleftrightarrow> (*ch p = ch q \\<and>*)sd(q) \\<subseteq> sd(p)\"\ndefinition less_str_calc :: \"'a str_calc \\<Rightarrow> 'a str_calc \\<Rightarrow> bool\" where\n\"less_str_calc p q \\<longleftrightarrow> (*ch p = ch q \\<and>*)sd(q) \\<subset> sd(p)\"\ninstance ..\nend\n\ntext \\<open>Proof of the interchange law for the string calculus operators.\\<close>\n\ninstance str_calc :: (type) preorder\napply (intro_classes)\napply (unfold less_eq_str_calc_def less_str_calc_def)\napply (auto)\ndone\n\ninterpretation preorder_str_calc:\n  preorder \"TYPE('a str_calc)\" \"op \\<le>\"\napply (rule ICL.preorder_leq.preorder_axioms)\ndone\n\ninterpretation iclaw_str_calc:\n  iclaw \"TYPE('a str_calc)\" \"op \\<le>\" \"op ;\" \"op |\"\napply (unfold_locales)\napply (unfold less_eq_str_calc_def less_str_calc_def)\napply (clarsimp)\napply (simp add: subset_iff)\n(* apply (auto) *)\ndone\n\nsubsection \\<open>Note: Small interchange laws.\\<close>\n\nlemma equiv_str_calc:\n\"s \\<cong> t \\<longleftrightarrow> (*ch s = ch t \\<and>*) sd s = sd t\"\napply (clarsimp)\napply (unfold less_eq_str_calc_def)\napply (auto)\ndone\n\nlemma empty_str_seq_unit:\n\"\\<epsilon> ; s \\<cong> s\"\n\"s ; \\<epsilon> \\<cong> s\"\napply (unfold equiv_str_calc)\napply (auto)\ndone\n\nlemma empty_str_par_unit:\n\"\\<epsilon> | s \\<cong> s\"\n\"s | \\<epsilon> \\<cong> s\"\napply (unfold equiv_str_calc)\napply (auto)\ndone\n\nlemma small_interchange_laws:\n\"(p | q) ; s \\<le> p | (q ; s)\"\n\"p ; (r | s) \\<le> (p ; r) | s\"\n\"q ; (r | s) \\<le> r | (q ; s)\"\n\"(p | q) ; r \\<le> (p ; r) | q\"\n\"p ; s \\<le> p | s\"\n\"q ; s \\<le> s | q\"\napply (unfold less_eq_str_calc_def)\napply (auto)\ndone\n\nsubsection \\<open>Note: an example derivation\\<close>\n\ntext \\<open>We first prove several key lemmas.\\<close>\n\nlemma seq_str_assoc:\n\"(s ; t) ; u \\<ge> s ; t ; u\"\napply (unfold less_eq_str_calc_def)\napply (auto)\ndone\n\nlemma par_str_assoc:\n\"(s | t) | u \\<ge> s | t | u\"\napply (unfold less_eq_str_calc_def)\napply (auto)\ndone\n\ntext \\<open>\n  The following law does not hold but is needed to remove the \\<open>ch\\<close>-related\n  provisos in the law \\<open>seq_str_mono\\<close>. Alternatively, we could strengthen the\n  definition of the order by additionally requiring @{term \"ch p = ch q\"}.\n\\<close>\n\nlemma sd_imp_ch_subset:\n\"sd s \\<subseteq> sd t \\<Longrightarrow> ch s \\<subseteq> ch t\"\napply (induction s; induction t)\napply (simp)\napply (simp)\napply (simp)\napply (simp)\ndefer\ndefer\napply (simp)\napply (simp)\napply (simp)\napply (simp)\napply (simp)\napply (simp)\napply (simp)\napply (simp)\napply (simp)\napply (simp)\noops\n\nlemma seq_str_mono:\n\"ch s = ch s' \\<Longrightarrow>\n ch t = ch t' \\<Longrightarrow>\n s \\<ge> s' \\<Longrightarrow> t \\<ge> t' \\<Longrightarrow> (s ; t) \\<ge> (s' ; t')\"\napply (unfold less_eq_str_calc_def)\napply (auto)\ndone\n\nlemma par_str_mono:\n\"s \\<ge> s' \\<Longrightarrow> t \\<ge> t' \\<Longrightarrow> (s | t) \\<ge> (s' | t')\"\napply (unfold less_eq_str_calc_def)\napply (auto)\ndone\n\nlemma str_calc_step:\nfixes LHS :: \"'a::preorder\"\nfixes RHS :: \"'a::preorder\"\nfixes MID :: \"'a::preorder\"\nshows \"LHS \\<ge> MID \\<Longrightarrow> MID \\<ge> RHS \\<Longrightarrow> LHS \\<ge> RHS\"\nusing order_trans by (blast)\n\nlemma example_derivation:\nassumes lhs: \"LHS = \\<guillemotleft>abcd\\<guillemotright> | \\<guillemotleft>xyzw\\<guillemotright>\"\nassumes rhs: \"RHS = \\<guillemotleft>xaybzwcd\\<guillemotright>\"\nshows \"LHS \\<ge> RHS\"\napply (unfold lhs rhs)\n-- \\<open>Step 1\\<close>\napply (rule_tac MID = \"(\\<guillemotleft>a\\<guillemotright> ; \\<guillemotleft>bcd\\<guillemotright>) | (\\<guillemotleft>xy\\<guillemotright> ; \\<guillemotleft>zw\\<guillemotright>)\" in str_calc_step)\napply (unfold less_eq_str_calc_def; auto) [1]\n-- \\<open>Step 2\\<close>\napply (rule_tac MID = \"(\\<guillemotleft>a\\<guillemotright> | \\<guillemotleft>xy\\<guillemotright>) ; (\\<guillemotleft>bcd\\<guillemotright> | \\<guillemotleft>zw\\<guillemotright>)\" in str_calc_step)\napply (rule iclaw_str_calc.interchange_law)\n-- \\<open>Step 3\\<close>\napply (rule_tac MID = \"(\\<guillemotleft>a\\<guillemotright> | \\<guillemotleft>x\\<guillemotright> ; \\<guillemotleft>y\\<guillemotright>) ; (\\<guillemotleft>b\\<guillemotright> ; \\<guillemotleft>cd\\<guillemotright> | \\<guillemotleft>zw\\<guillemotright>)\" in str_calc_step)\napply (unfold less_eq_str_calc_def; auto) [1]\n-- \\<open>Step 4\\<close>\napply (rule_tac MID = \"(\\<guillemotleft>a\\<guillemotright> | \\<guillemotleft>x\\<guillemotright>) ; \\<guillemotleft>y\\<guillemotright> ; (\\<guillemotleft>b\\<guillemotright> | \\<guillemotleft>zw\\<guillemotright>) ; \\<guillemotleft>cd\\<guillemotright>\" in str_calc_step)\napply (unfold less_eq_str_calc_def; auto) [1]\n(* using seq_str_assoc seq_str_mono\n  small_interchange_laws(1)\n  small_interchange_laws(4) str_calc_step\napply (blast) *)\n-- \\<open>Remainder of the proof...\\<close>\napply (unfold less_eq_str_calc_def)\napply (auto)\ndone\n\nlemma example_derivation_auto:\nassumes lhs: \"LHS = \\<guillemotleft>abcd\\<guillemotright> | \\<guillemotleft>xyzw\\<guillemotright>\"\nassumes rhs: \"RHS = \\<guillemotleft>xaybzwcd\\<guillemotright>\"\nshows \"LHS \\<ge> RHS\"\napply (unfold lhs rhs)\napply (unfold less_eq_str_calc_def)\napply (auto)\ndone\nend", "meta": {"author": "cka-models", "repo": "ipl2017", "sha": "4552de80f3e07ba0e14c1bd13b3fcec37253246d", "save_path": "github-repos/isabelle/cka-models-ipl2017", "path": "github-repos/isabelle/cka-models-ipl2017/ipl2017-4552de80f3e07ba0e14c1bd13b3fcec37253246d/theories/ICL_Examples.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772450055545, "lm_q2_score": 0.8438950966654772, "lm_q1q2_score": 0.7376295011670565}}
{"text": "section \\<open>Combinatorics problems\\<close>\n\nsubsection \\<open>IMO 2017 SL - C1\\<close>\n\ntheory IMO_2017_SL_C1_sol\n  imports Complex_Main\nbegin\n\ntext \\<open>A rectangle with line coordinates [x1, x2) and [y1, y2) is given by a quadruple (x1, x2, y1, y2).\\<close>\ntype_synonym rect = \"nat \\<times> nat \\<times> nat \\<times> nat\"\n\nfun valid_rect :: \"rect \\<Rightarrow> bool\" where\n  \"valid_rect (x1, x2, y1, y2) \\<longleftrightarrow> x1 < x2 \\<and> y1 < y2\"\n\ntext \\<open>A square is given by the coordinates of its lower-left corner\\<close>\ntype_synonym square = \"nat \\<times> nat\"\n\ntext \\<open>All squares in a rectangle\\<close>\nfun squares :: \"rect \\<Rightarrow> square set\" where\n  \"squares (x1, x2, y1, y2) = {x1..<x2} \\<times> {y1..<y2}\"\n\ntext \\<open>One rectangle is inside another one\\<close>\ndefinition inside :: \"rect \\<Rightarrow> rect \\<Rightarrow> bool\" where\n  \"inside ri ro \\<longleftrightarrow> squares ri \\<subseteq> squares ro\"\n\ntext \\<open>Two rectangles overlap inside another one\\<close>\ndefinition overlap :: \"rect \\<Rightarrow> rect \\<Rightarrow> bool\" where\n  \"overlap r1 r2 \\<longleftrightarrow> squares r1 \\<inter> squares r2 \\<noteq> {}\"\n\ntext \\<open>There are no two overlapping rectangles in a set\\<close>\ndefinition non_overlapping :: \"rect set \\<Rightarrow> bool\" where\n  \"non_overlapping rs \\<longleftrightarrow> (\\<forall> r1 \\<in> rs. \\<forall> r2 \\<in> rs. r1 \\<noteq> r2 \\<longrightarrow> \\<not> overlap r1 r2)\"\n\ntext \\<open>A set of rectangles covers a given rectangle\\<close>\ndefinition cover :: \"rect set \\<Rightarrow> rect \\<Rightarrow> bool\" where\n  \"cover rs r \\<longleftrightarrow> (\\<Union> (squares ` rs)) = squares r\"\n\ntext \\<open>A rectangle is tiled by a set of non-overlapping, smaller rectangles\\<close>\ndefinition tiles :: \"rect set \\<Rightarrow> rect \\<Rightarrow> bool\" where\n  \"tiles rs r \\<longleftrightarrow> cover rs r \\<and> non_overlapping rs\"\n\n\ntext \\<open>Each square is colored either to green or yellow in a checkerboard pattern\\<close>\nfun green :: \"square \\<Rightarrow> bool\" where\n  \"green (x, y) \\<longleftrightarrow> (x + y) mod 2 = 0\"\n\nfun yellow :: \"square \\<Rightarrow> bool\" where\n  \"yellow (x, y) \\<longleftrightarrow> (x + y) mod 2 \\<noteq> 0\"\n\ntext \\<open>All green squares in a rectangle\\<close>\ndefinition green_squares :: \"rect \\<Rightarrow> square set\" where\n  \"green_squares r = {(x, y) \\<in> squares r. green (x, y)}\"\n\ntext \\<open>All yellow squares in a rectangle\\<close>\ndefinition yellow_squares :: \"rect \\<Rightarrow> square set\" where\n  \"yellow_squares r = {(x, y) \\<in> squares r. yellow (x, y)}\"\n\ntext \\<open>Corner squares of a rectangle\\<close>\nfun corners :: \"rect \\<Rightarrow> square set\" where\n  \"corners (x1, x2, y1, y2) = {(x1, y1), (x1, y2-1), (x2-1, y1), (x2-1, y2-1)}\"\n\ndefinition green_rect :: \"rect \\<Rightarrow> bool\" where\n  \"green_rect r \\<longleftrightarrow> (\\<forall> c \\<in> corners r. green c)\"\n\ndefinition yellow_rect :: \"rect \\<Rightarrow> bool\" where\n  \"yellow_rect r \\<longleftrightarrow> (\\<forall> c \\<in> corners r. yellow c)\"\n\ndefinition mixed_rect ::  \"rect \\<Rightarrow> bool\" where\n  \"mixed_rect r \\<longleftrightarrow> \\<not> green_rect r \\<and> \\<not> yellow_rect r\"\n\nlemma finite_squares [simp]:\n  shows \"finite (squares r)\"\n  by (cases r, auto)\n\nlemma finite_green_squares [simp]:\n  shows \"finite (green_squares r)\"\n  using finite_subset[of \"green_squares r\" \"squares r\"]\n  by (auto simp add: green_squares_def)\n\nlemma finite_yellow_squares [simp]:\n  shows \"finite (yellow_squares r)\"\n  using finite_subset[of \"yellow_squares r\" \"squares r\"]\n  by (auto simp add: yellow_squares_def)\n\nlemma card_green_squares_row:\n  assumes \"x1 < x2\"\n  shows \"card {(x, y). x1 \\<le> x \\<and> x < x2 \\<and> y = y0 \\<and> green (x, y)} = \n         (if yellow (x1, y0) then (x2 - x1) div 2 else (x2 - x1 + 1) div 2)\"\n  using assms\nproof (induction k \\<equiv> \"x2 - x1 - 1\" arbitrary: x2)\n  case 0\n  then have \"x2 = x1 + 1\"\n    by simp\n  then have \"{(x, y). x1 \\<le> x \\<and> x < x2 \\<and> y = y0 \\<and> green (x, y)} =\n         {(x, y). x = x1 \\<and> y = y0 \\<and> green (x, y)}\"\n    by auto\n  also have \"... = (if yellow (x1, y0) then {} else {(x1, y0)})\"\n    by auto\n  finally show ?case\n    using \\<open>x2 = x1 + 1\\<close>\n    by (smt One_nat_def Suc_1 Suc_eq_plus1 add_diff_cancel_left' card_empty card_insert_if div_self equals0D finite.intros(1) nat.simps(3) one_div_two_eq_zero)\nnext\n  case (Suc k)\n  let ?S = \"{(x, y). x1 \\<le> x \\<and> x < x2 \\<and> y = y0 \\<and> green (x, y)}\"\n  let ?S1 = \"{(x, y). x1 \\<le> x \\<and> x < x2 - 1 \\<and> y = y0 \\<and> green (x, y)}\"\n  let ?S2 = \"{(x, y). x = x2 - 1 \\<and> y = y0 \\<and> green (x, y)}\"\n  have \"card (?S1 \\<union> ?S2) = card ?S1 + card ?S2\"\n  proof (rule card_Un_disjoint)\n    show \"finite ?S1\"\n      using finite_subset[of ?S1 \"{x1..<x2} \\<times> {y0}\"]\n      by force\n  next\n    show \"finite ?S2\"\n      using finite_subset[of ?S2 \"{x2-1} \\<times> {y0}\"]\n      by auto\n  next\n    show \"?S1 \\<inter> ?S2 = {}\"\n      by auto\n  qed\n  moreover\n  have \"?S = ?S1 \\<union> ?S2\"\n    using \\<open>x1 < x2\\<close>\n    by auto\n  ultimately\n  have 1: \"card ?S = card ?S1 + card ?S2\"\n    by simp\n  have 2: \"card ?S1 = (if yellow (x1, y0) then (x2 - 1 - x1) div 2 else (x2 - x1) div 2)\"\n    using Suc(1)[of \"x2 - 1\"] Suc(2) Suc(3)\n    by auto\n  show ?case\n  proof (cases \"yellow (x1, y0)\")\n    case True\n    show ?thesis\n    proof (cases \"green (x2-1, y0)\")\n      case True\n      then have \"even (x2 - x1)\"\n        using \\<open>x1 < x2\\<close> \\<open>yellow (x1, y0)\\<close>\n        by simp presburger\n      then have \"(x2 - x1) div 2 = (x2 - x1 - 1) div 2 + 1\"\n        using \\<open>x1 < x2\\<close>\n        by presburger+\n      moreover\n      have \"?S2 = {(x2-1, y0)}\"\n        using \\<open>green (x2-1, y0)\\<close>\n        by auto\n      then have \"card ?S2 = 1\"\n        by simp\n      ultimately show ?thesis\n        using \\<open>yellow (x1, y0)\\<close> 1 2 True\n        by simp\n    next\n      case False\n      then have \"odd (x2 - x1)\"\n        using \\<open>yellow (x1, y0)\\<close> \\<open>x1 < x2\\<close>\n        by simp presburger\n      then have \"(x2 - x1) div 2 = (x2 - x1 - 1) div 2\"\n        using \\<open>x2 > x1\\<close>\n        by presburger\n      moreover\n      have \"?S2 = {}\"\n        using False\n        by auto\n      then have \"card ?S2 = 0\"\n        by (metis card_empty)\n      ultimately show ?thesis\n        using \\<open>yellow (x1, y0)\\<close> 1 2\n        by simp\n    qed\n  next\n    case False\n    then have \"green (x1, y0)\"\n      by simp\n    show ?thesis\n    proof (cases \"green (x2-1, y0)\")\n      case True\n      then have \"odd (x2 - x1)\"\n        using \\<open>green (x1, y0)\\<close> \\<open>x1 < x2\\<close>\n        by simp presburger\n      then have \"(x2 - x1) div 2 + 1 = (x2 - x1 + 1) div 2\"\n        using \\<open>x1 < x2\\<close>\n        by presburger\n      moreover\n      have \"?S2 = {(x2-1, y0)}\"\n        using True\n        by auto\n      then have \"card ?S2 = 1\"\n        by simp\n      ultimately show ?thesis\n        using 1 2 \\<open>green (x1, y0)\\<close>\n        by simp\n    next\n      case False\n      then have \"even (x2 - x1)\"\n        using \\<open>green (x1, y0)\\<close> \\<open>x1 < x2\\<close>\n        by simp presburger\n      then have \"(x2 - x1) div 2 = (x2 - x1 + 1) div 2\"\n        using \\<open>x2 > x1\\<close>\n        by presburger\n      moreover\n      have \"?S2 = {}\"\n        using False\n        by auto\n      then have \"card ?S2 = 0\"\n        by (metis card_empty)\n      ultimately show ?thesis\n        using 1 2 \\<open>green (x1, y0)\\<close>\n        by simp\n    qed\n  qed\nqed\n\nlemma card_squares:\n  shows \"card (squares (x1, x2, y1, y2)) = (x2 - x1) * (y2 - y1)\"\n  by simp\n\nlemma card_green_squares_start_yellow:\n  assumes \"yellow (x1, y1)\" \"valid_rect (x1, x2, y1, y2)\"\n  shows \"card (green_squares (x1, x2, y1, y2)) = (x2 - x1) * (y2 - y1) div 2\"\n  using assms\nproof (induction k \\<equiv> \"y2 - y1 - 1\" arbitrary: y2)\n  case 0\n  then have \"y2 = y1 + 1\"\n    by simp\n  then show ?case\n    using \\<open>yellow (x1, y1)\\<close> \\<open>valid_rect (x1, x2, y1, y2)\\<close> card_green_squares_row[of x1 x2 y1]\n    unfolding green_squares_def\n    by simp\nnext\n  case (Suc k)\n\n  have \"x1 < x2\" \"y1 < y2\" \n    using \\<open>valid_rect (x1, x2, y1, y2)\\<close>\n    by simp_all\n\n  let ?S = \"green_squares (x1, x2, y1, y2)\"\n  let ?S1 = \"green_squares (x1, x2, y1, y2-1)\"\n  let ?S2 = \"{(x, y). x1 \\<le> x \\<and> x < x2 \\<and> y = y2-1 \\<and> green (x, y)}\"\n\n  have 1: \"card ?S1 = (x2 - x1) * (y2 - 1 - y1) div 2\"\n    using Suc\n    by auto\n\n  have \"card (?S1 \\<union> ?S2) = card ?S1 + card ?S2\"\n  proof (rule card_Un_disjoint)\n    show \"finite ?S1\"\n      using finite_subset[of ?S1 \"{x1..<x2} \\<times> {y1..<y2}\"]\n      unfolding green_squares_def\n      by force\n  next\n    show \"finite ?S2\"\n      using finite_subset[of ?S2 \"{x1..<x2} \\<times> {y2 - 1}\"]\n      by force\n  next\n    show \"?S1 \\<inter> ?S2 = {}\"\n      unfolding green_squares_def\n      by auto\n  qed\n\n  moreover\n\n  have \"?S = ?S1 \\<union> ?S2\"\n    using \\<open>y1 < y2\\<close>\n    by (auto simp add: green_squares_def)\n\n  ultimately\n\n  have 2: \"card ?S = card ?S1 + card ?S2\"\n    by simp\n\n  show ?case\n  proof (cases \"odd (y2 - y1)\")\n    case True\n    then have \"yellow (x1, y2-1)\"\n      using \\<open>y1 < y2\\<close> \\<open>yellow (x1, y1)\\<close>\n      by simp presburger\n    then have \"card ?S2 = (x2 - x1) div 2\"\n      using card_green_squares_row[of x1 x2 \"y2-1\"] \\<open>x1 < x2\\<close>\n      by simp\n    then have \"card ?S = (x2 - x1) * (y2 - y1 - 1) div 2 + (x2 - x1) div 2\"\n      using 1 2\n      by simp\n    also have \"... = (x2 - x1) * (y2 - y1) div 2\"\n      using \\<open>odd (y2 - y1)\\<close> \\<open>x1 < x2\\<close> \\<open>y1 < y2\\<close>\n      by (metis add_mult_distrib2 div_plus_div_distrib_dvd_left dvdI dvd_mult nat_mult_1_right odd_two_times_div_two_nat odd_two_times_div_two_succ)\n    finally show ?thesis\n      .\n  next\n    case False\n    then have \"green (x1, y2-1)\"\n      using \\<open>y1 < y2\\<close> \\<open>yellow (x1, y1)\\<close>\n      by simp presburger\n    then have \"card ?S2 = (x2 - x1 + 1) div 2\"\n      using card_green_squares_row[of x1 x2 \"y2-1\"] \\<open>x1 < x2\\<close>\n      by simp\n    then have \"card ?S = (x2 - x1) * (y2 - y1 - 1) div 2 + (x2 - x1 + 1) div 2\"\n      using 1 2\n      by simp\n    also have \"... = (x2 - x1) * (y2 - y1) div 2\"\n      using \\<open>\\<not> odd (y2 - y1)\\<close> \\<open>x1 < x2\\<close> \\<open>y1 < y2\\<close>\n      apply (cases \"odd (x2 - x1)\")\n       apply (smt Suc_diff_Suc add.commute add_Suc_shift diff_diff_left div_mult_self2 even_add even_mult_iff mult_Suc_right odd_two_times_div_two_succ plus_1_eq_Suc zero_neq_numeral)\n      apply (metis Suc_diff_1 add.commute dvd_div_mult even_succ_div_two mult_Suc_right zero_less_diff)\n      done\n    finally show ?thesis\n      .\n  qed\nqed\n\nlemma card_yellow_squares_start_yellow:\n  assumes \"yellow (x1, y1)\" \"valid_rect (x1, x2, y1, y2)\"\n  shows \"card (yellow_squares (x1, x2, y1, y2)) = ((x2 - x1) * (y2 - y1) + 1) div 2\"\nproof-\n  let ?S = \"squares (x1, x2, y1, y2)\" and ?Y = \"yellow_squares (x1, x2, y1, y2)\" and ?G = \"green_squares (x1, x2, y1, y2)\"\n  have \"?S = ?Y \\<union> ?G\"\n    unfolding green_squares_def yellow_squares_def\n    by auto\n  moreover\n  have \"card (?Y \\<union> ?G) = card ?Y + card ?G\"\n  proof (rule card_Un_disjoint)\n    show \"finite ?Y\"\n      using finite_subset[of ?Y ?S]\n      by (force simp add: yellow_squares_def)\n  next\n    show \"finite ?G\"\n      using finite_subset[of ?G ?S]\n      by (force simp add: green_squares_def)\n  next\n    show \"?Y \\<inter> ?G = {}\"\n      by (auto simp add: yellow_squares_def green_squares_def)\n  qed\n  ultimately\n  have \"card ?S = card ?G + card ?Y\"\n    by simp\n  then have \"card ?Y = card ?S - card ?G\"\n    by auto\n  then have \"card ?Y = (x2 - x1)*(y2 - y1) - (x2 - x1)*(y2 - y1) div 2\"\n    using assms(1) assms(2) card_green_squares_start_yellow card_squares\n    by presburger\n  also have \"... = ((x2 - x1)*(y2 - y1) + 1) div 2\"\n    by presburger\n  finally show ?thesis\n    .\nqed\n\nlemma card_yellow_squares_start_green:\n  assumes \"green (x1, y1)\" \"valid_rect (x1, x2, y1, y2)\"\n  shows \"card (yellow_squares (x1, x2, y1, y2)) = (x2 - x1) * (y2 - y1) div 2\"\nproof-\n  let ?Y = \"yellow_squares (x1, x2, y1, y2)\" and ?G = \"green_squares (x1+1, x2+1, y1, y2)\"\n  have \"card ?Y = card ?G\"\n  proof (rule bij_betw_same_card)\n    let ?f = \"\\<lambda> (x, y). (x+1, y)\"\n    show \"bij_betw ?f ?Y ?G\"\n      unfolding bij_betw_def\n    proof safe\n      show \"inj_on ?f ?Y\"\n        by (auto simp add: inj_on_def)\n    next\n      fix x y\n      assume \"(x, y) \\<in> ?Y\"\n      then show \"(x+1, y) \\<in> ?G\"\n        unfolding green_squares_def yellow_squares_def\n        by (auto simp add: mod_Suc)\n    next\n      fix x y\n      assume \"(x, y) \\<in> ?G\"\n      then have \"(x-1, y) \\<in> ?Y\" \"x > 0\"\n        unfolding green_squares_def yellow_squares_def\n        apply auto\n        apply (metis Nat.add_diff_assoc2 Suc_eq_plus1 add_eq_if add_leD2 even_Suc even_iff_mod_2_eq_zero not_mod2_eq_Suc_0_eq_0 odd_add)\n        by (metis Suc_leI add_gr_0 even_iff_mod_2_eq_zero lessI mod_nat_eqI not_mod2_eq_Suc_0_eq_0 numeral_2_eq_2 odd_even_add odd_pos)\n      then show \"(x, y) \\<in> ?f ` ?Y\"\n        by (simp add: rev_image_eqI)\n    qed\n  qed\n  then show ?thesis\n    using card_green_squares_start_yellow[of \"x1+1\" y1 \"x2+1\" y2] \\<open>valid_rect (x1, x2, y1, y2)\\<close>\n    using \\<open>green (x1, y1)\\<close>\n    by auto\nqed\n\nlemma card_green_squares_start_green:\n  assumes \"green (x1, y1)\" \"valid_rect (x1, x2, y1, y2)\"\n  shows \"card (green_squares (x1, x2, y1, y2)) = ((x2 - x1) * (y2 - y1) + 1) div 2\"\nproof-\n  let ?G = \"green_squares (x1, x2, y1, y2)\" and ?Y = \"yellow_squares (x1+1, x2+1, y1, y2)\"\n  have \"card ?G = card ?Y\"\n  proof (rule bij_betw_same_card)\n    let ?f = \"\\<lambda> (x, y). (x+1, y)\"\n    show \"bij_betw ?f ?G ?Y\"\n      unfolding bij_betw_def\n    proof safe\n      show \"inj_on ?f ?G\"\n        by (auto simp add: inj_on_def)\n    next\n      fix x y\n      assume \"(x, y) \\<in> ?G\"\n      then show \"(x+1, y) \\<in> ?Y\"\n        unfolding green_squares_def yellow_squares_def\n        by auto\n    next\n      fix x y\n      assume \"(x, y) \\<in> ?Y\"\n      then have \"(x-1, y) \\<in> ?G\" \"x > 0\"\n        unfolding green_squares_def yellow_squares_def\n        apply auto\n        apply (metis Suc_eq_plus1 add_eq_if even_Suc even_iff_mod_2_eq_zero not_mod2_eq_Suc_0_eq_0 odd_add)\n        done\n      then show \"(x, y) \\<in> ?f ` ?G\"\n        by (simp add: rev_image_eqI)\n    qed\n  qed\n  then show ?thesis\n    using card_yellow_squares_start_yellow[of \"x1+1\" y1 \"x2+1\" y2] \\<open>valid_rect (x1, x2, y1, y2)\\<close>\n    using \\<open>green (x1, y1)\\<close>\n    by auto\nqed\n\nlemma mixed_rect: \n  assumes \"valid_rect (x1, x2, y1, y2)\" \"mixed_rect (x1, x2, y1, y2)\"\n  shows \"card (green_squares (x1, x2, y1, y2)) = card (yellow_squares (x1, x2, y1, y2))\"\nproof (cases \"green (x1, y1)\")\n  case True\n  then have \"even ((x2 - x1) * (y2 - y1))\"\n    using assms\n    unfolding mixed_rect_def green_rect_def yellow_rect_def\n    by auto presburger+\n  then show ?thesis\n    using True\n    using card_green_squares_start_green[of x1 y1 x2 y2] assms\n    using card_yellow_squares_start_green[of x1 y1 x2 y2]\n    by simp\nnext\n  case False\n  then have \"even ((x2 - x1) * (y2 - y1))\"\n    using assms\n    unfolding mixed_rect_def green_rect_def yellow_rect_def\n    by auto presburger+\n  then show ?thesis\n    using False\n    using card_green_squares_start_yellow[of x1 y1 x2 y2] assms\n    using card_yellow_squares_start_yellow[of x1 y1 x2 y2]\n    unfolding mixed_rect_def green_rect_def yellow_rect_def\n    by simp\nqed\n\nlemma green_rect: \n  assumes \"valid_rect (x1, x2, y1, y2)\"  \"green_rect (x1, x2, y1, y2)\"\n  shows \"card (green_squares (x1, x2, y1, y2)) = card (yellow_squares (x1, x2, y1, y2)) + 1\"\n  using assms\n  using card_green_squares_start_green[of x1 y1 x2 y2]\n  using card_yellow_squares_start_green[of x1 y1 x2 y2]\n  unfolding green_rect_def\n  by auto\n  \nlemma yellow_rect: \n  assumes \"valid_rect (x1, x2, y1, y2)\" \"yellow_rect (x1, x2, y1, y2)\"\n  shows \"card (green_squares (x1, x2, y1, y2)) + 1 = card (yellow_squares (x1, x2, y1, y2))\"\n  using assms\n  using card_green_squares_start_yellow[of x1 y1 x2 y2]\n  using card_yellow_squares_start_yellow[of x1 y1 x2 y2]\n  unfolding yellow_rect_def\n  by auto (metis dvd_imp_mod_0 even_Suc even_diff_nat even_mult_iff linorder_not_less nat_less_le odd_Suc_div_two odd_add)\n\nlemma tiles_inside:\n  assumes \"tiles rs (x1, x2, y1, y2)\" \"r \\<in> rs\"\n  shows \"inside r (x1, x2, y1, y2)\"\n  using assms\n  unfolding tiles_def inside_def cover_def\n  by auto\n\nlemma finite_tiles:\n  assumes \"tiles rs (x1, x2, y1, y2)\" \"\\<forall> r \\<in> rs. valid_rect r\"\n  shows \"finite rs\"\nproof (rule finite_subset)\n  show \"rs \\<subseteq> {x1..x2} \\<times> {x1..x2} \\<times> {y1..y2} \\<times> {y1..y2}\"\n  proof\n    fix r :: rect\n    obtain x1r x2r y1r y2r where r: \"r = (x1r, x2r, y1r, y2r)\"\n      by (cases r)\n    assume \"r \\<in> rs\"\n    then have \"inside r (x1, x2, y1, y2)\"\n      using tiles_inside[OF assms(1)]\n      by auto\n    moreover have \"x1r < x2r\" \"y1r < y2r\"\n      using assms(2) \\<open>r \\<in> rs\\<close> r\n      by auto\n    ultimately\n    show \"r \\<in> {x1..x2} \\<times> {x1..x2} \\<times> {y1..y2} \\<times> {y1..y2}\"\n      using r times_subset_iff[of \"{x1r..<x2r}\" \"{y1r..<y2r}\" \"{x1..<x2}\" \"{y1..<y2}\"]\n      by (auto simp add: inside_def)\n  qed\nnext\n  show \"finite ({x1..x2} \\<times> {x1..x2} \\<times> {y1..y2} \\<times> {y1..y2})\"\n    by simp\nqed\n\n\nlemma green_tile:\n  assumes \"green_rect (x1, x2, y1, y2)\" \"valid_rect (x1, x2, y1, y2)\"\n          \"tiles rs (x1, x2, y1, y2)\" \"\\<forall> r \\<in> rs. valid_rect r\"\n  shows \"\\<exists> r \\<in> rs. green_rect r\"\nproof (rule ccontr)\n  assume \"\\<not> ?thesis\"\n  then have *: \"\\<forall> r \\<in> rs. yellow_rect r \\<or> mixed_rect r\"\n    using mixed_rect_def by blast\n  then have **: \"\\<forall> r \\<in> rs. card (green_squares r) \\<le> card (yellow_squares r)\"\n    using yellow_rect mixed_rect \\<open>\\<forall> r \\<in> rs. valid_rect r\\<close>\n    by (metis le_add1 order_refl prod_cases4)\n\n  have \"card (green_squares (x1, x2, y1, y2)) \\<le> card (yellow_squares (x1, x2, y1, y2))\"\n  proof-\n    have \"card (green_squares (x1, x2, y1, y2)) = card (\\<Union> (green_squares ` rs))\"\n    proof-\n      have \"green_squares (x1, x2, y1, y2) = \\<Union> (green_squares ` rs)\"\n        using \\<open>tiles rs (x1, x2, y1, y2)\\<close>\n        unfolding tiles_def cover_def green_squares_def\n        by blast\n      then show ?thesis\n        by simp\n    qed                                 \n    also have \"... = (\\<Sum> r \\<in> rs. card (green_squares r))\"\n    proof (rule card_UN_disjoint)\n      show \"finite rs\"\n        using assms(3-4) finite_tiles\n        by auto\n    next\n      show \"\\<forall> r \\<in> rs. finite (green_squares r)\"\n        by auto\n    next\n      show \"\\<forall> r1 \\<in> rs. \\<forall> r2 \\<in> rs. r1 \\<noteq> r2 \\<longrightarrow> green_squares r1 \\<inter> green_squares r2 = {}\"\n      proof (rule, rule, rule)\n        fix r1 r2\n        assume \"r1 \\<in> rs\" \"r2 \\<in> rs\" \"r1 \\<noteq> r2\"\n        then have \"squares r1 \\<inter> squares r2 = {}\"\n          using \\<open>tiles rs (x1, x2, y1, y2)\\<close>\n          unfolding tiles_def non_overlapping_def overlap_def\n          by auto\n        then show \"green_squares r1 \\<inter> green_squares r2 = {}\"\n          unfolding green_squares_def\n          by auto\n      qed\n    qed\n    also have \"... \\<le> (\\<Sum> r \\<in> rs. card (yellow_squares r))\"\n      using **\n      by (simp add: sum_mono)\n    also have \"... = card (\\<Union> (yellow_squares ` rs))\"\n    proof (rule card_UN_disjoint[symmetric])\n      show \"finite rs\"\n        using assms(3-4) finite_tiles by auto\n    next\n      show \"\\<forall>r\\<in>rs. finite (yellow_squares r)\"\n        by auto\n    next\n      show \"\\<forall>r\\<in>rs. \\<forall>j\\<in>rs. r \\<noteq> j \\<longrightarrow> yellow_squares r \\<inter> yellow_squares j = {}\"\n      proof (rule, rule, rule)\n        fix r1 r2\n        assume \"r1 \\<in> rs\" \"r2 \\<in> rs\" \"r1 \\<noteq> r2\"\n        then have \"squares r1 \\<inter> squares r2 = {}\"\n          using \\<open>tiles rs (x1, x2, y1, y2)\\<close>\n          unfolding tiles_def non_overlapping_def overlap_def\n          by auto\n        then show \"yellow_squares r1 \\<inter> yellow_squares r2 = {}\"\n          unfolding yellow_squares_def\n          by auto\n      qed\n    qed\n    also have \"... = card (yellow_squares (x1, x2, y1, y2))\"\n    proof-\n      have \"yellow_squares (x1, x2, y1, y2) = \\<Union> (yellow_squares ` rs)\"\n        using \\<open>tiles rs (x1, x2, y1, y2)\\<close>\n        unfolding tiles_def cover_def yellow_squares_def\n        by blast\n      then show ?thesis\n        by simp\n    qed\n\n    finally\n    show ?thesis\n      .\n  qed\n\n  then show False\n    using \\<open>green_rect (x1, x2, y1, y2)\\<close> green_rect[of x1 x2 y1 y2] \\<open>valid_rect (x1, x2, y1, y2)\\<close>\n    by auto\nqed\n\nlemma green_inside_green_distances:\n  assumes \"green_rect (x1i, x2i, y1i, y2i)\" \"green_rect (x1o, x2o, y1o, y2o)\" \"valid_rect (x1i, x2i, y1i, y2i)\"\n          \"inside (x1i, x2i, y1i, y2i) (x1o, x2o, y1o, y2o)\"\n  shows   \"let ds = {x1i - x1o, x2o - x2i, y1i - y1o, y2o - y2i} \n            in (\\<forall> d \\<in> ds. even d) \\<or> (\\<forall> d \\<in> ds. odd d)\"\nproof-\n  have \"x1o \\<le> x1i\" \"x1i < x2i\" \"x2i \\<le> x2o\"\n       \"y1o \\<le> y1i\" \"y1i < y2i\" \"y2i \\<le> y2o\"\n    using assms times_subset_iff[of \"{x1i..<x2i}\" \"{y1i..<y2i}\" \"{x1o..<x2o}\" \"{y1o..<y2o}\"]\n    unfolding Let_def inside_def     \n    by auto\n  then show ?thesis\n    using assms\n    by (auto simp add: green_rect_def)\nqed\n  \n\ntheorem IMO_2017_SL_C1:\n  fixes a b :: nat                                          \n  assumes \"odd a\" \"odd b\" \"tiles rs (0, a, 0, b)\" \"\\<forall> r \\<in> rs. valid_rect r\"\n        shows \"\\<exists> (x1, x2, y1, y2) \\<in> rs. \n                  let ds = {x1 - 0, a - x2, y1 - 0, b - y2} \n                   in (\\<forall> d \\<in> ds. even d) \\<or> (\\<forall> d \\<in> ds. odd d)\"\nproof-\n  have \"green_rect (0, a, 0, b)\"\n    using \\<open>odd a\\<close> \\<open>odd b\\<close>\n    unfolding green_rect_def\n    by auto\n  then obtain x1 x2 y1 y2 where \n    \"(x1, x2, y1, y2) \\<in> rs\" \"valid_rect (x1, x2, y1, y2)\" \"green_rect (x1, x2, y1, y2)\"\n    \"inside (x1, x2, y1, y2) (0, a, 0, b)\"\n    using assms green_tile[of 0 a 0 b rs] tiles_inside[of rs 0 a 0 b]\n    by (auto simp add: odd_pos)\n  then show ?thesis\n    using \\<open>green_rect (0, a, 0, b)\\<close> green_inside_green_distances[of x1 x2 y1 y2 0 a 0 b]\n    by (rule_tac x=\"(x1, x2, y1, y2)\" in bexI, auto)\nqed\n\n\nend", "meta": {"author": "filipmaric", "repo": "IMO", "sha": "9fb602bf4fd5bcb5890361d194a4fb423ac266e2", "save_path": "github-repos/isabelle/filipmaric-IMO", "path": "github-repos/isabelle/filipmaric-IMO/IMO-9fb602bf4fd5bcb5890361d194a4fb423ac266e2/IMO_files/solutions/IMO_2017_SL_C1_sol.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8740772417253256, "lm_q2_score": 0.8438950966654772, "lm_q1q2_score": 0.7376294983988874}}
{"text": "theory Type\nimports Main\nbegin\n\ndatatype kind = Star\n\ndatatype type = \n  TyVar nat\n| Arrow type type\n| Record \"type list\"\n| Variant \"type list\"\n| Inductive kind type\n| Forall kind type\n\nprimrec incr\\<^sub>t\\<^sub>t :: \"nat \\<Rightarrow> type \\<Rightarrow> type\" where\n  \"incr\\<^sub>t\\<^sub>t x (TyVar y) = TyVar (if x \\<le> y then Suc y else y)\"\n| \"incr\\<^sub>t\\<^sub>t x (Arrow t\\<^sub>1 t\\<^sub>2) = Arrow (incr\\<^sub>t\\<^sub>t x t\\<^sub>1) (incr\\<^sub>t\\<^sub>t x t\\<^sub>2)\"\n| \"incr\\<^sub>t\\<^sub>t x (Record ts) = Record (map (incr\\<^sub>t\\<^sub>t x) ts)\"\n| \"incr\\<^sub>t\\<^sub>t x (Variant ts) = Variant (map (incr\\<^sub>t\\<^sub>t x) ts)\"\n| \"incr\\<^sub>t\\<^sub>t x (Inductive k t) = Inductive k (incr\\<^sub>t\\<^sub>t (Suc x) t)\"\n| \"incr\\<^sub>t\\<^sub>t x (Forall k t) = Forall k (incr\\<^sub>t\\<^sub>t (Suc x) t)\"\n\nprimrec subst\\<^sub>t\\<^sub>t :: \"nat \\<Rightarrow> type \\<Rightarrow> type \\<Rightarrow> type\" where\n  \"subst\\<^sub>t\\<^sub>t x t' (TyVar y) = (if x = y then t' else TyVar (if x < y then y - 1 else y))\"\n| \"subst\\<^sub>t\\<^sub>t x t' (Arrow t\\<^sub>1 t\\<^sub>2) = Arrow (subst\\<^sub>t\\<^sub>t x t' t\\<^sub>1) (subst\\<^sub>t\\<^sub>t x t' t\\<^sub>2)\"\n| \"subst\\<^sub>t\\<^sub>t x t' (Record ts) = Record (map (subst\\<^sub>t\\<^sub>t x t') ts)\"\n| \"subst\\<^sub>t\\<^sub>t x t' (Variant ts) = Variant (map (subst\\<^sub>t\\<^sub>t x t') ts)\"\n| \"subst\\<^sub>t\\<^sub>t x t' (Inductive k t) = Inductive k (subst\\<^sub>t\\<^sub>t (Suc x) (incr\\<^sub>t\\<^sub>t 0 t') t)\"\n| \"subst\\<^sub>t\\<^sub>t x t' (Forall k t) = Forall k (subst\\<^sub>t\\<^sub>t (Suc x) (incr\\<^sub>t\\<^sub>t 0 t') t)\"\n\n\n\nlemma [simp]: \"y \\<le> x \\<Longrightarrow> incr\\<^sub>t\\<^sub>t y o incr\\<^sub>t\\<^sub>t x = incr\\<^sub>t\\<^sub>t (Suc x) o incr\\<^sub>t\\<^sub>t y\"\n  by rule simp\n\nlemma subst_incr_swap [simp]: \"y \\<le> x \\<Longrightarrow> \n    subst\\<^sub>t\\<^sub>t y (incr\\<^sub>t\\<^sub>t x t') (incr\\<^sub>t\\<^sub>t (Suc x) t) = incr\\<^sub>t\\<^sub>t x (subst\\<^sub>t\\<^sub>t y t' t)\" \n  by (induction t arbitrary: x y t') auto\n\nlemma [simp]: \"y \\<le> x \\<Longrightarrow> subst\\<^sub>t\\<^sub>t y (incr\\<^sub>t\\<^sub>t x t') o incr\\<^sub>t\\<^sub>t (Suc x) = incr\\<^sub>t\\<^sub>t x o subst\\<^sub>t\\<^sub>t y t'\" \n  by rule simp\n\nlemma [simp]: \"subst\\<^sub>t\\<^sub>t x t' (incr\\<^sub>t\\<^sub>t x t) = t\"\n  proof (induction t arbitrary: x t')\n  case (Record ts)\n    thus ?case by (induction ts) simp_all\n  next case (Variant ts)\n    thus ?case by (induction ts) simp_all\n  qed simp_all\n\nlemma [simp]: \"subst\\<^sub>t\\<^sub>t x t' o incr\\<^sub>t\\<^sub>t x = id\"\n  by rule simp\n\nlemma [simp]: \"y \\<le> x \\<Longrightarrow> incr\\<^sub>t\\<^sub>t y (subst\\<^sub>t\\<^sub>t x t' t) = subst\\<^sub>t\\<^sub>t (Suc x) (incr\\<^sub>t\\<^sub>t y t') (incr\\<^sub>t\\<^sub>t y t)\"\n  by (induction t arbitrary: x y t') auto\n\nlemma [simp]: \"y \\<le> x \\<Longrightarrow> incr\\<^sub>t\\<^sub>t y \\<circ> subst\\<^sub>t\\<^sub>t x t' = subst\\<^sub>t\\<^sub>t (Suc x) (incr\\<^sub>t\\<^sub>t y t') \\<circ> incr\\<^sub>t\\<^sub>t y\"\n  by rule simp\n\nlemma [simp]: \"y \\<le> x \\<Longrightarrow> \n    subst\\<^sub>t\\<^sub>t x t\\<^sub>1' (subst\\<^sub>t\\<^sub>t y t\\<^sub>2' t) = subst\\<^sub>t\\<^sub>t y (subst\\<^sub>t\\<^sub>t x t\\<^sub>1' t\\<^sub>2') (subst\\<^sub>t\\<^sub>t (Suc x) (incr\\<^sub>t\\<^sub>t y t\\<^sub>1') t)\"\n  by (induction t arbitrary: x y t\\<^sub>1' t\\<^sub>2') auto\n\nlemma [simp]: \"y \\<le> x \\<Longrightarrow> \n    subst\\<^sub>t\\<^sub>t x t\\<^sub>1' o subst\\<^sub>t\\<^sub>t y t\\<^sub>2' = subst\\<^sub>t\\<^sub>t y (subst\\<^sub>t\\<^sub>t x t\\<^sub>1' t\\<^sub>2') o subst\\<^sub>t\\<^sub>t (Suc x) (incr\\<^sub>t\\<^sub>t y t\\<^sub>1')\"\n  by rule simp\n\nend", "meta": {"author": "xtreme-james-cooper", "repo": "LazyCompiler", "sha": "3b95c3550e0cce4966aaf45c7eb38f2cbc2bfbfa", "save_path": "github-repos/isabelle/xtreme-james-cooper-LazyCompiler", "path": "github-repos/isabelle/xtreme-james-cooper-LazyCompiler/LazyCompiler-3b95c3550e0cce4966aaf45c7eb38f2cbc2bfbfa/01Expression/Type.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070133672954, "lm_q2_score": 0.8104789086703225, "lm_q1q2_score": 0.737460443185398}}
{"text": "section \\<open>Solving the puzzle\\<close>\n\ntheory Puzzle_Bottom_Up\nimports Parity_Swap \"../lib/Lib\"\nbegin\n\nsubsubsection \\<open>Individual choice function\\<close>\n\ntext \\<open>Given a list of all hat numbers either @{text seen} or @{text heard}, we can reconstruct\n      the set of all hat numbers from the length of that list. Excluding the members from the\\<close>\n\ndefinition\n  \"candidates xs \\<equiv> {0 .. 1 + length xs} - set xs\"\n\ndefinition\n  choice :: \"nat list \\<Rightarrow> nat list \\<Rightarrow> nat\"\nwhere\n  \"choice heard seen \\<equiv>\n    case sorted_list_of_set (candidates (heard @ seen)) of\n      [a,b] \\<Rightarrow> if parity (a # heard @ b # seen) then b else a\"\n\nsubsubsection \\<open>Group choice function\\<close>\n\nprimrec\n  choices' :: \"nat list \\<Rightarrow> nat list \\<Rightarrow> nat list\"\nwhere\n  \"choices' heard [] = []\"\n| \"choices' heard (_ # seen)\n    = (let c = choice heard seen in c # choices' (heard @ [c]) seen)\"\n\ndefinition \"choices \\<equiv> choices' []\"\n\nsubsubsection \\<open>Examples\\<close>\n\ndefinition \"example_even \\<equiv> [4,2,3,6,0,5]\"\nlemma \"parity (1 # example_even)\" by eval\nlemma \"choices example_even = [4,2,3,6,0,5]\" by eval\n\ndefinition \"example_odd \\<equiv> [4,0,3,6,2,5]\"\nlemma \"\\<not> parity (1 # example_odd)\" by eval\nlemma \"choices example_odd = [1,0,3,6,2,5]\" by eval\n\nsubsubsection \\<open>Group choice does not cheat\\<close>\n\nlemma choices':\n  assumes \"i < length assigned\"\n  assumes \"spoken = choices' heard assigned\"\n  shows \"spoken ! i = choice (heard @ take i spoken) (drop (Suc i) assigned)\"\n  using assms proof (induct assigned arbitrary: i spoken heard)\n    case Cons thus ?case by (cases i) (auto simp: Let_def)\n  qed simp\n\nlemma choices:\n  assumes \"i < length assigned\"\n  assumes \"spoken = choices assigned\"\n  shows \"spoken ! i = choice (take i spoken) (drop (Suc i) assigned)\"\n  using assms by (simp add: choices_def choices')\n\nsubsubsection \\<open>Group choice has the correct length\\<close>\n\nlemma choices'_length: \"length (choices' heard assigned) = length assigned\"\n  by (induct assigned arbitrary: heard) (auto simp: Let_def)\n\nlemma choices_length: \"length (choices assigned) = length assigned\"\n  by (simp add: choices_def choices'_length)\n\nsubsection \\<open>Correctness of choice function\\<close>\n\ncontext\n  fixes spare :: \"nat\"\n  fixes assigned :: \"nat list\"\n  assumes assign: \"set (spare # assigned) = {0 .. length assigned}\"\nbegin\n\nlemma distinct: \"distinct (spare # assigned)\"\n  apply (rule card_distinct)\n  apply (subst assign)\n  by auto\n\nlemma distinct_pointwise:\n  assumes \"i < length assigned\"\n  shows \"spare \\<noteq> assigned ! i\n           \\<and> (\\<forall> j < length assigned. i \\<noteq> j \\<longrightarrow> assigned ! i \\<noteq> assigned ! j)\"\n  using assms distinct by (auto simp: nth_eq_iff_index_eq)\n\ncontext\n  fixes spoken :: \"nat list\"\n  assumes spoken: \"spoken = choices assigned\"\nbegin\n\nlemma spoken_length: \"length spoken = length assigned\"\n  using choices_length spoken by simp\n\nlemma spoken_choice:\n  \"i < length assigned \\<Longrightarrow> spoken ! i = choice (take i spoken) (drop (Suc i) assigned)\"\n  using choices spoken by simp\n\ncontext\n  assumes exists: \"0 < length assigned\"\n  notes parity.simps(2) [simp del]\nbegin\n\nlemmas assigned_0\n  = Cons_nth_drop_Suc[OF exists, simplified]\n\nlemma candidates_0:\n  \"candidates (drop (Suc 0) assigned) = {spare, assigned ! 0}\"\n  proof -\n    have len: \"1 + length (drop (Suc 0) assigned) = length assigned\"\n      using exists by simp\n    have set: \"set (drop (Suc 0) assigned) = {0..length assigned} - {spare, assigned ! 0}\"\n      using Diff_insert2 Diff_insert_absorb assign assigned_0 distinct\n            distinct.simps(2) list.simps(15)\n      by metis\n    show ?thesis\n      unfolding candidates_def len set\n      unfolding Diff_Diff_Int subset_absorb_r\n      unfolding assign[symmetric]\n      using exists by auto\n  qed\n\nlemma spoken_0:\n  \"spoken ! 0 = (if parity (spare # assigned) then assigned ! 0 else spare)\"\n  unfolding spoken_choice[OF exists] choice_def take_0 append_Nil candidates_0\n  using parity_swap_adj[where as=\"[]\"] assigned_0 distinct_pointwise[OF exists]\n  by (cases \"assigned ! 0 < spare\") auto\n\ncontext\n  fixes rejected :: \"nat\"\n  fixes initial_order :: \"nat list\"\n  assumes rejected: \"rejected = (if parity (spare # assigned) then spare else assigned ! 0)\"\n  assumes initial_order: \"initial_order = rejected # spoken ! 0 # drop (Suc 0) assigned\"\nbegin\n\nlemma parity_initial: \"parity initial_order\"\n  unfolding initial_order spoken_0 rejected\n  using parity_swap_adj[of \"assigned ! 0\" \"spare\" \"[]\"]\n        distinct_pointwise[OF exists] assigned_0\n  by auto\n\nlemma distinct_initial: \"distinct initial_order\"\n  unfolding initial_order rejected spoken_0\n  using assigned_0 distinct distinct_length_2_or_more\n  by (metis (full_types))\n\nlemma set_initial: \"set initial_order = {0..length assigned}\"\n  unfolding initial_order assign[symmetric] rejected spoken_0\n  using arg_cong[where f=set, OF assigned_0, symmetric]\n  by auto\n\nlemma spoken_correct:\n  \"i \\<in> {1 ..< length assigned} \\<Longrightarrow> spoken ! i = assigned ! i\"\n  proof (induction i rule: nat_less_induct)\n    case (1 i)\n\n    have\n      LB: \"0 < i\" and UB: \"i < length assigned\" and US: \"i < length spoken\" and\n      IH: \"\\<forall> j \\<in> {1 ..< i}. spoken ! j = assigned ! j\"\n      using 1 spoken_length by auto\n\n    let ?heard = \"take i spoken\"\n    let ?seen  = \"drop (Suc i) assigned\"\n\n    have heard: \"?heard = spoken ! 0 # map (op ! assigned) [Suc 0 ..< i]\"\n      using IH take_map_nth[OF less_imp_le, OF US] range_extract_head[OF LB] by auto\n\n    let ?my_order = \"rejected # ?heard @ assigned ! i # ?seen\"\n\n    have initial_order: \"?my_order = initial_order\"\n      unfolding initial_order heard\n      apply (simp add: UB Cons_nth_drop_Suc)\n      apply (subst drop_map_nth[OF less_imp_le_nat, OF UB])\n      apply (subst drop_map_nth[OF Suc_leI[OF exists]])\n      apply (subst map_append[symmetric])\n      apply (rule arg_cong[where f=\"map _\"])\n      apply (rule range_app)\n      using UB LB less_imp_le Suc_le_eq by auto\n\n    have distinct_my_order: \"distinct ?my_order\"\n      using distinct_initial initial_order by simp\n\n    have set_my_order: \"set ?my_order = {0..length assigned}\"\n      using set_initial initial_order by simp\n\n    have set: \"set (?heard @ ?seen) = {0..length assigned} - {rejected, assigned ! i}\"\n      apply (rule subset_minusI)\n      using distinct_my_order set_my_order by auto\n\n    have len: \"1 + length (?heard @ ?seen) = length assigned\"\n      using LB UB heard by simp\n\n    have candidates: \"candidates (?heard @ ?seen) = {rejected, assigned ! i}\"\n      unfolding candidates_def len set\n      unfolding Diff_Diff_Int subset_absorb_r\n      unfolding assign[symmetric]\n      unfolding rejected\n      using UB exists by auto\n\n    show ?case\n      apply (simp only: spoken_choice[OF UB] choice_def candidates)\n      apply (subst sorted_list_of_set_distinct_pair)\n       using distinct_my_order apply auto[1]\n      apply (cases \"assigned ! i < rejected\"; clarsimp)\n       apply (subst (asm) parity_swap[of _ _ _ \"[]\", simplified])\n        apply (simp add: distinct_my_order[simplified])\n       unfolding initial_order\n       using parity_initial\n       by auto\n  qed\n\nend\nend\nend\n\nlemma choices_correct:\n  \"i \\<in> {1 ..< length assigned} \\<Longrightarrow> choices assigned ! i = assigned ! i\"\n  apply (rule spoken_correct) by auto\n\nlemma choices_distinct: \"distinct (choices assigned)\"\n  proof (cases \"0 < length assigned\")\n    case True show ?thesis\n    apply (clarsimp simp: distinct_conv_nth_less choices_length)\n    apply (case_tac \"i = 0\")\n    using True choices_correct spoken_0[OF _ True] distinct_pointwise\n    by (auto split: if_splits)\n  next\n    case False thus ?thesis using choices_length[of assigned] by simp\n  qed\n\nend\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/Puzzle_Bottom_Up.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9099070011518829, "lm_q2_score": 0.8104788995148792, "lm_q1q2_score": 0.737460424954462}}
{"text": "(* Author: Alexander Bentkamp, Universit\u00e4t des Saarlandes\n*)\nsection \\<open>Concrete Matrices\\<close>\n\ntheory DL_Concrete_Matrices\nimports Jordan_Normal_Form.Matrix\nbegin\n\ntext \\<open>The following definition allows non-square-matrices, mat\\_one (mat\\_one n) only allows square matrices.\\<close>\n\ndefinition id_matrix::\"nat \\<Rightarrow> nat \\<Rightarrow> real mat\"\nwhere \"id_matrix nr nc = mat nr nc (\\<lambda>(r, c). if r=c then 1 else 0)\"\n\nlemma id_matrix_dim: \"dim_row (id_matrix nr nc) = nr\" \"dim_col (id_matrix nr nc) = nc\" by (simp_all add: id_matrix_def)\n\n\n\nlemma unit_eq_0[simp]:\n  assumes i: \"i \\<ge> n\"\n  shows \"unit_vec n i = 0\\<^sub>v n\"\n  by (rule eq_vecI, insert i, auto simp: unit_vec_def)\n\nlemma mult_id_matrix:\nassumes \"i < nr\"\nshows \"(id_matrix nr (dim_vec v) *\\<^sub>v v) $ i = (if i<dim_vec v then v $ i else 0)\" (is \"?a $ i = ?b\")\nproof -\n  have \"?a $ i = row (id_matrix nr (dim_vec v)) i \\<bullet> v\" using index_mult_mat_vec assms id_matrix_dim by auto\n  also have \"... = unit_vec (dim_vec v) i \\<bullet> v\" using row_id_matrix assms by auto\n  also have \"... = ?b\" using scalar_prod_left_unit carrier_vecI unit_eq_0 scalar_prod_left_zero by fastforce\n  finally show ?thesis by auto\nqed\n\n\ndefinition all1_vec::\"nat \\<Rightarrow> real vec\"\nwhere \"all1_vec n = vec n (\\<lambda>i. 1)\"\n\ndefinition all1_matrix::\"nat \\<Rightarrow> nat \\<Rightarrow> real mat\"\nwhere \"all1_matrix nr nc = mat nr nc (\\<lambda>(r, c). 1)\"\n\nlemma all1_matrix_dim: \"dim_row (all1_matrix nr nc) = nr\" \"dim_col (all1_matrix nr nc) = nc\"\n  by (simp_all add: all1_matrix_def)\n\nlemma row_all1_matrix:\nassumes \"i < nr\"\nshows \"row (all1_matrix nr nc) i = all1_vec nc\"\n  apply (rule eq_vecI)\n  apply (simp add: all1_matrix_def all1_vec_def assms)\n  by (simp add: all1_matrix_def all1_vec_def)\n\nlemma all1_vec_scalar_prod:\nshows \"all1_vec (length xs) \\<bullet> (vec_of_list xs) = sum_list xs\"\nproof -\n  have \"all1_vec (length xs) \\<bullet> (vec_of_list xs) = (\\<Sum>i = 0..<dim_vec (vec_of_list xs). vec_of_list xs $ i)\"\n    unfolding scalar_prod_def by (metis (no_types, lifting) all1_vec_def mult_cancel_right1 sum.ivl_cong\n    vec.abs_eq dim_vec index_vec vec_of_list.abs_eq)\n  also have \"... = (\\<Sum>i = 0..<length xs. xs ! i)\" using vec.abs_eq dim_vec vec_of_list.abs_eq\n    by (metis sum.ivl_cong index_vec)\n  also have \"... = sum_list xs\" by (simp add: sum_list_sum_nth)\n  finally show ?thesis by auto\nqed\n\n\nlemma mult_all1_matrix:\nassumes \"i < nr\"\nshows \"((all1_matrix nr (dim_vec v)) *\\<^sub>v v) $ i = sum_list (list_of_vec v)\" (is \"?a $ i = sum_list (list_of_vec v)\")\nproof -\n  have \"?a $ i = row (all1_matrix nr (dim_vec v)) i \\<bullet> v\" using index_mult_mat_vec assms all1_matrix_dim by auto\n  also have \"... = sum_list (list_of_vec v)\" unfolding row_all1_matrix[OF assms] using all1_vec_scalar_prod[of \"list_of_vec v\"]\n    by (metis vec.abs_eq dim_vec vec_list vec_of_list.abs_eq)\n  finally show ?thesis by auto\nqed\n\n\ndefinition copy_first_matrix::\"nat \\<Rightarrow> nat \\<Rightarrow> real mat\"\nwhere \"copy_first_matrix nr nc = mat nr nc (\\<lambda>(r, c). if c = 0 then 1 else 0)\"\n\nlemma copy_first_matrix_dim: \"dim_row (copy_first_matrix nr nc) = nr\" \"dim_col (copy_first_matrix nr nc) = nc\"\n  by (simp_all add: copy_first_matrix_def)\n\nlemma row_copy_first_matrix:\nassumes \"i < nr\"\nshows \"row (copy_first_matrix nr nc) i = unit_vec nc 0\"\n  apply (rule eq_vecI)\n  apply (auto simp add: copy_first_matrix_def assms)[1]\n  by (simp add: copy_first_matrix_def)\n\nlemma mult_copy_first_matrix:\nassumes \"i < nr\" and \"dim_vec v > 0\"\nshows \"(copy_first_matrix nr (dim_vec v) *\\<^sub>v v) $ i = v $ 0\" (is \"?a $ i = v $ 0\")\nproof -\n  have \"?a $ i = row (copy_first_matrix nr (dim_vec v)) i \\<bullet> v\" using index_mult_mat_vec assms copy_first_matrix_dim by auto\n  also have \"... = unit_vec (dim_vec v) 0 \\<bullet> v\" using row_copy_first_matrix assms by auto\n  also have \"... = v $ 0\" using assms(2) scalar_prod_left_unit carrier_dim_vec by blast\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/Deep_Learning/DL_Concrete_Matrices.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872046026642944, "lm_q2_score": 0.8311430478583169, "lm_q1q2_score": 0.7373939375323286}}
{"text": "(*  Title:      HOL/UNITY/ListOrder.thy\n    Author:     Lawrence C Paulson, Cambridge University Computer Laboratory\n    Copyright   1998  University of Cambridge\n\nLists are partially ordered by Charpentier's Generalized Prefix Relation\n   (xs,ys) : genPrefix(r)\n     if ys = xs' @ zs where length xs = length xs'\n     and corresponding elements of xs, xs' are pairwise related by r\n\nAlso overloads <= and < for lists!\n*)\n\nsection \\<open>The Prefix Ordering on Lists\\<close>\n\ntheory ListOrder\nimports MainRLT\nbegin\n\ninductive_set\n  genPrefix :: \"('a * 'a)set => ('a list * 'a list)set\"\n  for r :: \"('a * 'a)set\"\n where\n   Nil:     \"([],[]) \\<in> genPrefix(r)\"\n\n | prepend: \"[| (xs,ys) \\<in> genPrefix(r);  (x,y) \\<in> r |] ==>\n             (x#xs, y#ys) \\<in> genPrefix(r)\"\n\n | append:  \"(xs,ys) \\<in> genPrefix(r) ==> (xs, ys@zs) \\<in> genPrefix(r)\"\n\ninstantiation list :: (type) ord \nbegin\n\ndefinition\n  prefix_def:        \"xs <= zs \\<longleftrightarrow>  (xs, zs) \\<in> genPrefix Id\"\n\ndefinition\n  strict_prefix_def: \"xs < zs  \\<longleftrightarrow>  xs \\<le> zs \\<and> \\<not> zs \\<le> (xs :: 'a list)\"\n\ninstance ..  \n\n(*Constants for the <= and >= relations, used below in translations*)\n\nend\n\ndefinition Le :: \"(nat*nat) set\" where\n    \"Le == {(x,y). x <= y}\"\n\ndefinition  Ge :: \"(nat*nat) set\" where\n    \"Ge == {(x,y). y <= x}\"\n\nabbreviation\n  pfixLe :: \"[nat list, nat list] => bool\"  (infixl \"pfixLe\" 50)  where\n  \"xs pfixLe ys == (xs,ys) \\<in> genPrefix Le\"\n\nabbreviation\n  pfixGe :: \"[nat list, nat list] => bool\"  (infixl \"pfixGe\" 50)  where\n  \"xs pfixGe ys == (xs,ys) \\<in> genPrefix Ge\"\n\n\nsubsection\\<open>preliminary lemmas\\<close>\n\nlemma Nil_genPrefix [iff]: \"([], xs) \\<in> genPrefix r\"\nby (cut_tac genPrefix.Nil [THEN genPrefix.append], auto)\n\nlemma genPrefix_length_le: \"(xs,ys) \\<in> genPrefix r \\<Longrightarrow> length xs <= length ys\"\nby (erule genPrefix.induct, auto)\n\nlemma cdlemma:\n     \"[| (xs', ys') \\<in> genPrefix r |]  \n      ==> (\\<forall>x xs. xs' = x#xs \\<longrightarrow> (\\<exists>y ys. ys' = y#ys & (x,y) \\<in> r & (xs, ys) \\<in> genPrefix r))\"\napply (erule genPrefix.induct, blast, blast)\napply (force intro: genPrefix.append)\ndone\n\n(*As usual converting it to an elimination rule is tiresome*)\nlemma cons_genPrefixE [elim!]: \n     \"[| (x#xs, zs) \\<in> genPrefix r;   \n         !!y ys. [| zs = y#ys;  (x,y) \\<in> r;  (xs, ys) \\<in> genPrefix r |] ==> P  \n      |] ==> P\"\nby (drule cdlemma, simp, blast)\n\nlemma Cons_genPrefix_Cons [iff]:\n     \"((x#xs,y#ys) \\<in> genPrefix r) = ((x,y) \\<in> r \\<and> (xs,ys) \\<in> genPrefix r)\"\nby (blast intro: genPrefix.prepend)\n\n\nsubsection\\<open>genPrefix is a partial order\\<close>\n\nlemma refl_genPrefix: \"refl r ==> refl (genPrefix r)\"\napply (unfold refl_on_def, auto)\napply (induct_tac \"x\")\nprefer 2 apply (blast intro: genPrefix.prepend)\napply (blast intro: genPrefix.Nil)\ndone\n\nlemma genPrefix_refl [simp]: \"refl r \\<Longrightarrow> (l,l) \\<in> genPrefix r\"\nby (erule refl_onD [OF refl_genPrefix UNIV_I])\n\nlemma genPrefix_mono: \"r<=s ==> genPrefix r <= genPrefix s\"\napply clarify\napply (erule genPrefix.induct)\napply (auto intro: genPrefix.append)\ndone\n\n\n(** Transitivity **)\n\n(*A lemma for proving genPrefix_trans_O*)\nlemma append_genPrefix:\n     \"(xs @ ys, zs) \\<in> genPrefix r \\<Longrightarrow> (xs, zs) \\<in> genPrefix r\"\n  by (induct xs arbitrary: zs) auto\n\n(*Lemma proving transitivity and more*)\nlemma genPrefix_trans_O:\n  assumes \"(x, y) \\<in> genPrefix r\"\n  shows \"\\<And>z. (y, z) \\<in> genPrefix s \\<Longrightarrow> (x, z) \\<in> genPrefix (r O s)\"\n  apply (atomize (full))\n  using assms\n  apply induct\n    apply blast\n   apply (blast intro: genPrefix.prepend)\n  apply (blast dest: append_genPrefix)\n  done\n\nlemma genPrefix_trans:\n  \"(x, y) \\<in> genPrefix r \\<Longrightarrow> (y, z) \\<in> genPrefix r \\<Longrightarrow> trans r\n    \\<Longrightarrow> (x, z) \\<in> genPrefix r\"\n  apply (rule trans_O_subset [THEN genPrefix_mono, THEN subsetD])\n   apply assumption\n  apply (blast intro: genPrefix_trans_O)\n  done\n\nlemma prefix_genPrefix_trans:\n  \"[| x<=y;  (y,z) \\<in> genPrefix r |] ==> (x, z) \\<in> genPrefix r\"\napply (unfold prefix_def)\napply (drule genPrefix_trans_O, assumption)\napply simp\ndone\n\nlemma genPrefix_prefix_trans:\n  \"[| (x,y) \\<in> genPrefix r;  y<=z |] ==> (x,z) \\<in> genPrefix r\"\napply (unfold prefix_def)\napply (drule genPrefix_trans_O, assumption)\napply simp\ndone\n\nlemma trans_genPrefix: \"trans r ==> trans (genPrefix r)\"\nby (blast intro: transI genPrefix_trans)\n\n\n(** Antisymmetry **)\n\nlemma genPrefix_antisym:\n  assumes 1: \"(xs, ys) \\<in> genPrefix r\"\n    and 2: \"antisym r\"\n    and 3: \"(ys, xs) \\<in> genPrefix r\"\n  shows \"xs = ys\"\n  using 1 3\nproof induct\n  case Nil\n  then show ?case by blast\nnext\n  case prepend\n  then show ?case using 2 by (simp add: antisym_def)\nnext\n  case (append xs ys zs)\n  then show ?case\n    apply -\n    apply (subgoal_tac \"length zs = 0\", force)\n    apply (drule genPrefix_length_le)+\n    apply (simp del: length_0_conv)\n    done\nqed\n\nlemma antisym_genPrefix: \"antisym r ==> antisym (genPrefix r)\"\n  by (blast intro: antisymI genPrefix_antisym)\n\n\nsubsection\\<open>recursion equations\\<close>\n\nlemma genPrefix_Nil [simp]: \"((xs, []) \\<in> genPrefix r) = (xs = [])\"\n  by (induct xs) auto\n\nlemma same_genPrefix_genPrefix [simp]: \n    \"refl r \\<Longrightarrow> ((xs@ys, xs@zs) \\<in> genPrefix r) = ((ys,zs) \\<in> genPrefix r)\"\n  by (induct xs) (simp_all add: refl_on_def)\n\nlemma genPrefix_Cons:\n     \"((xs, y#ys) \\<in> genPrefix r) =  \n      (xs=[] | (\\<exists>z zs. xs=z#zs & (z,y) \\<in> r & (zs,ys) \\<in> genPrefix r))\"\n  by (cases xs) auto\n\nlemma genPrefix_take_append:\n     \"[| refl r;  (xs,ys) \\<in> genPrefix r |]  \n      ==>  (xs@zs, take (length xs) ys @ zs) \\<in> genPrefix r\"\napply (erule genPrefix.induct)\napply (frule_tac [3] genPrefix_length_le)\napply (simp_all (no_asm_simp) add: diff_is_0_eq [THEN iffD2])\ndone\n\nlemma genPrefix_append_both:\n     \"[| refl r;  (xs,ys) \\<in> genPrefix r;  length xs = length ys |]  \n      ==>  (xs@zs, ys @ zs) \\<in> genPrefix r\"\napply (drule genPrefix_take_append, assumption)\napply simp\ndone\n\n\n(*NOT suitable for rewriting since [y] has the form y#ys*)\nlemma append_cons_eq: \"xs @ y # ys = (xs @ [y]) @ ys\"\nby auto\n\nlemma aolemma:\n     \"[| (xs,ys) \\<in> genPrefix r;  refl r |]  \n      ==> length xs < length ys \\<longrightarrow> (xs @ [ys ! length xs], ys) \\<in> genPrefix r\"\napply (erule genPrefix.induct)\n  apply blast\n apply simp\ntxt\\<open>Append case is hardest\\<close>\napply simp\napply (frule genPrefix_length_le [THEN le_imp_less_or_eq])\napply (erule disjE)\napply (simp_all (no_asm_simp) add: neq_Nil_conv nth_append)\napply (blast intro: genPrefix.append, auto)\napply (subst append_cons_eq, fast intro: genPrefix_append_both genPrefix.append)\ndone\n\nlemma append_one_genPrefix:\n     \"[| (xs,ys) \\<in> genPrefix r;  length xs < length ys;  refl r |]  \n      ==> (xs @ [ys ! length xs], ys) \\<in> genPrefix r\"\nby (blast intro: aolemma [THEN mp])\n\n\n(** Proving the equivalence with Charpentier's definition **)\n\nlemma genPrefix_imp_nth:\n    \"i < length xs \\<Longrightarrow> (xs, ys) \\<in> genPrefix r \\<Longrightarrow> (xs ! i, ys ! i) \\<in> r\"\n  apply (induct xs arbitrary: i ys)\n   apply auto\n  apply (case_tac i)\n   apply auto\n  done\n\nlemma nth_imp_genPrefix:\n  \"length xs <= length ys \\<Longrightarrow>\n     (\\<forall>i. i < length xs \\<longrightarrow> (xs ! i, ys ! i) \\<in> r) \\<Longrightarrow>\n     (xs, ys) \\<in> genPrefix r\"\n  apply (induct xs arbitrary: ys)\n   apply (simp_all add: less_Suc_eq_0_disj all_conj_distrib)\n  apply (case_tac ys)\n   apply (force+)\n  done\n\nlemma genPrefix_iff_nth:\n     \"((xs,ys) \\<in> genPrefix r) =  \n      (length xs <= length ys & (\\<forall>i. i < length xs \\<longrightarrow> (xs!i, ys!i) \\<in> r))\"\napply (blast intro: genPrefix_length_le genPrefix_imp_nth nth_imp_genPrefix)\ndone\n\n\nsubsection\\<open>The type of lists is partially ordered\\<close>\n\ndeclare refl_Id [iff] \n        antisym_Id [iff] \n        trans_Id [iff]\n\nlemma prefix_refl [iff]: \"xs <= (xs::'a list)\"\nby (simp add: prefix_def)\n\nlemma prefix_trans: \"!!xs::'a list. [| xs <= ys; ys <= zs |] ==> xs <= zs\"\napply (unfold prefix_def)\napply (blast intro: genPrefix_trans)\ndone\n\nlemma prefix_antisym: \"!!xs::'a list. [| xs <= ys; ys <= xs |] ==> xs = ys\"\napply (unfold prefix_def)\napply (blast intro: genPrefix_antisym)\ndone\n\nlemma prefix_less_le_not_le: \"!!xs::'a list. (xs < zs) = (xs <= zs & \\<not> zs \\<le> xs)\"\nby (unfold strict_prefix_def, auto)\n\ninstance list :: (type) order\n  by (intro_classes,\n      (assumption | rule prefix_refl prefix_trans prefix_antisym\n                     prefix_less_le_not_le)+)\n\n(*Monotonicity of \"set\" operator WRT prefix*)\nlemma set_mono: \"xs <= ys ==> set xs <= set ys\"\napply (unfold prefix_def)\napply (erule genPrefix.induct, auto)\ndone\n\n\n(** recursion equations **)\n\nlemma Nil_prefix [iff]: \"[] <= xs\"\nby (simp add: prefix_def)\n\nlemma prefix_Nil [simp]: \"(xs <= []) = (xs = [])\"\nby (simp add: prefix_def)\n\nlemma Cons_prefix_Cons [simp]: \"(x#xs <= y#ys) = (x=y & xs<=ys)\"\nby (simp add: prefix_def)\n\nlemma same_prefix_prefix [simp]: \"(xs@ys <= xs@zs) = (ys <= zs)\"\nby (simp add: prefix_def)\n\nlemma append_prefix [iff]: \"(xs@ys <= xs) = (ys <= [])\"\nby (insert same_prefix_prefix [of xs ys \"[]\"], simp)\n\nlemma prefix_appendI [simp]: \"xs <= ys ==> xs <= ys@zs\"\napply (unfold prefix_def)\napply (erule genPrefix.append)\ndone\n\nlemma prefix_Cons: \n   \"(xs <= y#ys) = (xs=[] | (\\<exists>zs. xs=y#zs \\<and> zs <= ys))\"\nby (simp add: prefix_def genPrefix_Cons)\n\nlemma append_one_prefix: \n  \"[| xs <= ys; length xs < length ys |] ==> xs @ [ys ! length xs] <= ys\"\napply (unfold prefix_def)\napply (simp add: append_one_genPrefix)\ndone\n\nlemma prefix_length_le: \"xs <= ys ==> length xs <= length ys\"\napply (unfold prefix_def)\napply (erule genPrefix_length_le)\ndone\n\nlemma splemma: \"xs<=ys ==> xs~=ys --> length xs < length ys\"\napply (unfold prefix_def)\napply (erule genPrefix.induct, auto)\ndone\n\nlemma strict_prefix_length_less: \"xs < ys ==> length xs < length ys\"\napply (unfold strict_prefix_def)\napply (blast intro: splemma [THEN mp])\ndone\n\nlemma mono_length: \"mono length\"\nby (blast intro: monoI prefix_length_le)\n\n(*Equivalence to the definition used in Lex/Prefix.thy*)\nlemma prefix_iff: \"(xs <= zs) = (\\<exists>ys. zs = xs@ys)\"\napply (unfold prefix_def)\napply (auto simp add: genPrefix_iff_nth nth_append)\napply (rule_tac x = \"drop (length xs) zs\" in exI)\napply (rule nth_equalityI)\napply (simp_all (no_asm_simp) add: nth_append)\ndone\n\nlemma prefix_snoc [simp]: \"(xs <= ys@[y]) = (xs = ys@[y] | xs <= ys)\"\napply (simp add: prefix_iff)\napply (rule iffI)\n apply (erule exE)\n apply (rename_tac \"zs\")\n apply (rule_tac xs = zs in rev_exhaust)\n  apply simp\n apply clarify\n apply (simp del: append_assoc add: append_assoc [symmetric], force)\ndone\n\nlemma prefix_append_iff:\n     \"(xs <= ys@zs) = (xs <= ys | (\\<exists>us. xs = ys@us & us <= zs))\"\napply (rule_tac xs = zs in rev_induct)\n apply force\napply (simp del: append_assoc add: append_assoc [symmetric], force)\ndone\n\n(*Although the prefix ordering is not linear, the prefixes of a list\n  are linearly ordered.*)\nlemma common_prefix_linear:\n  fixes xs ys zs :: \"'a list\"\n  shows \"xs <= zs \\<Longrightarrow> ys <= zs \\<Longrightarrow> xs <= ys | ys <= xs\"\n  by (induct zs rule: rev_induct) auto\n\nsubsection\\<open>pfixLe, pfixGe: properties inherited from the translations\\<close>\n\n(** pfixLe **)\n\nlemma refl_Le [iff]: \"refl Le\"\nby (unfold refl_on_def Le_def, auto)\n\nlemma antisym_Le [iff]: \"antisym Le\"\nby (unfold antisym_def Le_def, auto)\n\nlemma trans_Le [iff]: \"trans Le\"\nby (unfold trans_def Le_def, auto)\n\nlemma pfixLe_refl [iff]: \"x pfixLe x\"\nby simp\n\nlemma pfixLe_trans: \"[| x pfixLe y; y pfixLe z |] ==> x pfixLe z\"\nby (blast intro: genPrefix_trans)\n\nlemma pfixLe_antisym: \"[| x pfixLe y; y pfixLe x |] ==> x = y\"\nby (blast intro: genPrefix_antisym)\n\nlemma prefix_imp_pfixLe: \"xs<=ys ==> xs pfixLe ys\"\napply (unfold prefix_def Le_def)\napply (blast intro: genPrefix_mono [THEN [2] rev_subsetD])\ndone\n\nlemma refl_Ge [iff]: \"refl Ge\"\nby (unfold refl_on_def Ge_def, auto)\n\nlemma antisym_Ge [iff]: \"antisym Ge\"\nby (unfold antisym_def Ge_def, auto)\n\nlemma trans_Ge [iff]: \"trans Ge\"\nby (unfold trans_def Ge_def, auto)\n\nlemma pfixGe_refl [iff]: \"x pfixGe x\"\nby simp\n\nlemma pfixGe_trans: \"[| x pfixGe y; y pfixGe z |] ==> x pfixGe z\"\nby (blast intro: genPrefix_trans)\n\nlemma pfixGe_antisym: \"[| x pfixGe y; y pfixGe x |] ==> x = y\"\nby (blast intro: genPrefix_antisym)\n\nlemma prefix_imp_pfixGe: \"xs<=ys ==> xs pfixGe ys\"\napply (unfold prefix_def Ge_def)\napply (blast intro: genPrefix_mono [THEN [2] rev_subsetD])\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/UNITY/ListOrder.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8872045877523147, "lm_q2_score": 0.8311430478583168, "lm_q1q2_score": 0.7373939251383403}}
{"text": "(*  Title:      HOL/ex/Set_Theory.thy\n    Author:     Tobias Nipkow and Lawrence C Paulson\n    Copyright   1991  University of Cambridge\n*)\n\nsection {* Set Theory examples: Cantor's Theorem, Schr\u00f6der-Bernstein Theorem, etc. *}\n\ntheory Set_Theory\nimports Main\nbegin\n\ntext{*\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*}\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 {*\n  Trivial example of term synthesis: apparently hard for some provers!\n*}\n\nschematic_lemma \"a \\<noteq> b \\<Longrightarrow> a \\<in> ?X \\<and> b \\<notin> ?X\"\n  by blast\n\n\nsubsection {* Examples for the @{text blast} paper *}\n\nlemma \"(\\<Union>x \\<in> C. f x \\<union> g x) = \\<Union>(f ` C)  \\<union>  \\<Union>(g ` C)\"\n  -- {* Union-image, called @{text Un_Union_image} in Main HOL *}\n  by blast\n\nlemma \"(\\<Inter>x \\<in> C. f x \\<inter> g x) = \\<Inter>(f ` C) \\<inter> \\<Inter>(g ` C)\"\n  -- {* Inter-image, called @{text Int_Inter_image} in Main HOL *}\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  -- {*Variant of the problem above. *}\n  by blast\n\nlemma \"\\<exists>!x. f (g x) = x \\<Longrightarrow> \\<exists>!y. g (f y) = y\"\n  -- {* A unique fixpoint theorem --- @{text fast}/@{text best}/@{text meson} all fail. *}\n  by metis\n\n\nsubsection {* Cantor's Theorem: There is no surjection from a set to its powerset *}\n\nlemma cantor1: \"\\<not> (\\<exists>f:: 'a \\<Rightarrow> 'a set. \\<forall>S. \\<exists>x. f x = S)\"\n  -- {* Requires best-first search because it is undirectional. *}\n  by best\n\nschematic_lemma \"\\<forall>f:: 'a \\<Rightarrow> 'a set. \\<forall>x. f x \\<noteq> ?S f\"\n  -- {*This form displays the diagonal term. *}\n  by best\n\nschematic_lemma \"?S \\<notin> range (f :: 'a \\<Rightarrow> 'a set)\"\n  -- {* This form exploits the set constructs. *}\n  by (rule notI, erule rangeE, best)\n\nschematic_lemma \"?S \\<notin> range (f :: 'a \\<Rightarrow> 'a set)\"\n  -- {* Or just this! *}\n  by best\n\n\nsubsection {* The Schr\u00f6der-Berstein Theorem *}\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    --{*The term above can be synthesized by a sufficiently detailed proof.*}\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 inv_image_comp [symmetric])\n  done\n\n\nsubsection {* A simple party theorem *}\n\ntext{* \\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.) *}\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 `card A \\<ge> 2` by(auto intro:ccontr)\n  have 0: \"R `` A <= A\" using `sym R` `Domain R <= A`\n    unfolding Domain_unfold sym_def by blast\n  have h: \"ALL a:A. R `` {a} <= A\" using 0 by blast\n  hence 1: \"ALL a:A. finite(R `` {a})\" using `finite A`\n    by(blast intro: finite_subset)\n  have sub: \"?N ` A <= {0..<?n}\"\n  proof -\n    have \"ALL a:A. R `` {a} - {a} < A\" using h by blast\n    thus ?thesis using psubset_card_mono[OF `finite A`] 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 `finite A` have 2[simp]: \"?N ` A = {0..<?n}\"\n      using subset_card_intvl_is_intvl[of _ 0] by(auto)\n    have \"0 : ?N ` A\" and \"?n - 1 : ?N ` A\"  using `card A \\<ge> 2` by simp+\n    then obtain a b where ab: \"a:A\" \"b: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 `card A \\<ge> 2` 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 `a\\<noteq>b` 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 `finite A` by simp\n    have \"?N b <= ?n - 2\" using ab `a\\<noteq>b` `finite A` card_mono[OF 4 3] by simp\n    then show False using Nb `card A \\<ge>  2` by arith\n  qed\nqed\n\ntext {*\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*}\n\nlemma \"\\<exists>A. (\\<forall>x \\<in> A. x \\<le> (0::int))\"\n  -- {* Example 1, page 295. *}\n  by force\n\nlemma \"D \\<in> F \\<Longrightarrow> \\<exists>G. \\<forall>A \\<in> G. \\<exists>B \\<in> F. A \\<subseteq> B\"\n  -- {* Example 2. *}\n  by force\n\nlemma \"P a \\<Longrightarrow> \\<exists>A. (\\<forall>x \\<in> A. P x) \\<and> (\\<exists>y. y \\<in> A)\"\n  -- {* Example 3. *}\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  -- {* Example 4. *}\n  by auto --{*slow*}\n\nlemma \"P (f b) \\<Longrightarrow> \\<exists>s A. (\\<forall>x \\<in> A. P x) \\<and> f s \\<in> A\"\n  -- {*Example 5, page 298. *}\n  by force\n\nlemma \"P (f b) \\<Longrightarrow> \\<exists>s A. (\\<forall>x \\<in> A. P x) \\<and> f s \\<in> A\"\n  -- {* Example 6. *}\n  by force\n\nlemma \"\\<exists>A. a \\<notin> A\"\n  -- {* Example 7. *}\n  by force\n\nlemma \"(\\<forall>u v. u < (0::int) \\<longrightarrow> u \\<noteq> abs v)\n    \\<longrightarrow> (\\<exists>A::int set. -2 \\<in> A & (\\<forall>y. abs y \\<notin> A))\"\n  -- {* Example 8 needs a small hint. *}\n  by force\n    -- {* not @{text blast}, which can't simplify @{text \"-2 < 0\"} *}\n\ntext {* Example 9 omitted (requires the reals). *}\n\ntext {* The paper has no Example 10! *}\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  -- {* Example 11: needs a hint. *}\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  -- {* Example 12. *}\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  -- {* Example EO1: typo in article, and with the obvious fix it seems\n      to require arithmetic reasoning. *}\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": "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/Set_Theory.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430353105599, "lm_q2_score": 0.8872045952083047, "lm_q1q2_score": 0.7373939202029071}}
{"text": "theory Lists\n  imports Basics\nbegin\n\nsection {* Lists *}\n\ndatatype natprod = pair \"nat * nat\"\n\nfun fst :: \"natprod \\<Rightarrow> nat\" where\n  \"fst (pair (x, y)) = x\"\n\nvalue \"fst (pair (3, 5))\"\n\nfun snd :: \"natprod \\<Rightarrow> nat\" where\n  \"snd (pair (x, y)) = y\"\n\nfun fst' :: \"nat * nat \\<Rightarrow> nat\" where\n  \"fst' (x, y) = x\"\n\nvalue \"fst' (3, 5)\"\n\nfun snd' :: \"nat * nat \\<Rightarrow> nat\" where\n  \"snd' (x, y) = y\"\n\nfun swap_pair :: \"natprod \\<Rightarrow> natprod\" where\n  \"swap_pair (pair (x, y)) = pair (y, x)\"\n\nfun swap_pair' :: \"nat * nat \\<Rightarrow> nat * nat\" where\n  \"swap_pair' (x, y) = (y, x)\"\n\ntheorem subjective_pairing': \"\\<forall> n m::nat. (n, m) = (fst'(n, m), snd'(n, m))\" by simp\n\n(* theorem subjective_pairing: \"\\<forall> p::natprod. p = pair (fst p, snd p)\" *)\ntheorem subjective_pairing: \"p = pair (fst p, snd p)\"\n  apply (induction p)\n  apply (auto)\n  done\n\ntheorem snd_fst_is_swap: \"(snd' p, fst' p) = swap_pair' p\"\n  apply (induction p)\n  apply (simp)\n  done\n\ntheorem fst_swap_is_snd: \"fst' (swap_pair' p) = snd' p\"\n  apply (induction p)\n  apply (simp)\n  done\n\nno_notation Nil (\"[]\") and Cons (infixr \"#\" 65) and append (infixr \"@\" 65)\n\ndatatype natlist = Nil (\"[]\")\n  | Cons nat \"natlist\" (infixr \"#\" 65)\nhide_type list\n\nfun repeat :: \"nat \\<Rightarrow> nat \\<Rightarrow> natlist\" where\n  \"repeat _ 0 = []\"\n| \"repeat n (Suc count') = n # (repeat n count')\"\n\nfun length :: \"natlist \\<Rightarrow> nat\" where\n  \"length [] = 0\"\n| \"length (x # xs) = Suc (length xs)\"\n\nprimrec app :: \"natlist \\<Rightarrow> natlist \\<Rightarrow> natlist\" (infixr \"@\" 65)\n  where\n  \"[] @ ys = ys\"\n| \"(x # xs) @ ys = x # (xs @ ys)\"\n\nlemma test_app1: \"(1 # (2 # (3 # []))) @ (4 # (5 # [])) = 1 # 2 # 3 # 4 # 5 # []\" by simp\n\nfun hd :: \"nat \\<Rightarrow> natlist \\<Rightarrow> nat\" where\n  \"hd init [] = init\"\n| \"hd _ (x # xs) = x\"\n\nfun tl :: \"natlist \\<Rightarrow> natlist\" where\n  \"tl [] = []\"\n| \"tl (x # xs) = xs\"\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\nfun nonzeros :: \"natlist \\<Rightarrow> natlist\" where\n  \"nonzeros [] = []\"\n| \"nonzeros (x # xs) = (if x = 0 then nonzeros xs else x # (nonzeros xs))\"\n\nlemma test_nonzeros: \"nonzeros (0 # 1 # 0 # 2 # 3 # 0 # 0 # []) = 1 # 2 # 3 # []\"\n  apply (simp)\n  done\n\nfun oddmembers :: \"natlist \\<Rightarrow> natlist\" where\n  \"oddmembers [] = []\"\n| \"oddmembers (x # xs) = (if odd x then x # oddmembers xs else oddmembers xs)\"\n\nlemma test_oddmembers: \"oddmembers (0 # 1 # 0 # 2 # 3 # 0 # 0 # []) = 1 # 3 # []\"\n  apply (simp)\n  done\n\ndefinition countoddmembers :: \"natlist \\<Rightarrow> nat\" where\n  \"countoddmembers xs = length (oddmembers xs)\"\n\nlemma test_countoddmembers1: \"countoddmembers (1 # 0 # 3 # 1 # 4 # 5 # []) = 4\"\n  unfolding countoddmembers_def\n  apply (simp)\n  done\n\nlemma test_countoddmembers2: \"countoddmembers (0 # 2 # 4 # []) = 0\"\n  unfolding countoddmembers_def\n  apply (simp)\n  done\n\nlemma test_countoddmembers3: \"countoddmembers [] = 0\"\n  unfolding countoddmembers_def\n  apply (simp)\n  done\n\nsubsection {* inferences *}\n\ntheorem nil_app: \"\\<forall> xs::natlist. [] @ xs = xs\" by simp\n\n(* theorem tl_length_pred: \"\\<forall> xs::natlist. pred (length xs) = length (tl xs)\" *)\ntheorem tl_length_pred: \"pred (length xs) = length (tl xs)\"\n  apply (induction xs)\n   apply (simp_all)\n  done\n\n(* theorem app_assoc: \"\\<forall> xs ys::natlist. (xs @ ys) @zs = xs @ (ys @ zs)\" *)\ntheorem app_assoc: \"(xs @ ys) @zs = xs @ (ys @ zs)\"\n  apply (induction xs)\n   apply (simp_all)\n  done\n\nfun rev :: \"natlist \\<Rightarrow> natlist\" where\n  \"rev [] = []\"\n| \"rev (x # xs) = (rev xs) @ (x # [])\"\n\nlemma test_rev1: \"rev (1 # 2 # 3 # []) = 3 # 2 # 1 # []\" by simp\nlemma test_rev2: \"rev [] = []\" by simp\n\n(* theorem app_length: \"\\<forall> xs ys::natlist. length (xs @ ys) = (length xs) + (length ys)\" *)\ntheorem app_length: \"length (xs @ ys) = (length xs) + (length ys)\"\n  apply (induct xs)\n   apply (simp_all)\n  done\n\n(* theorem rev_length: \"\\<forall> xs::natlist. length (rev xs) = length xs\" *)\ntheorem rev_length: \"length (rev xs) = length xs\"\n  apply (induct xs)\n   apply (simp)\n  apply (simp add: app_length)\n  done\n\n(* theorem app_nil_r: \"\\<forall> xs::natlist. xs @ [] = xs\" *)\ntheorem app_nil_r: \"xs @ [] = xs\"\n  apply (induction xs)\n   apply (simp_all)\n  done\n\ntheorem rev_app_distr: \"rev (xs @ ys) = rev ys @ rev xs\"\n  apply (induction xs)\n   apply (simp add: app_nil_r)\n  apply (simp add: app_assoc)\n  done\n\ntheorem rev_involutive: \"rev (rev xs) = xs\"\n  apply (induction xs)\n   apply (auto)\n  apply (simp add: rev_app_distr)\n  done\n\nend", "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/Lists.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511543206819, "lm_q2_score": 0.8615382147637196, "lm_q1q2_score": 0.737348475596909}}
{"text": "\ntheory ListLexorder\nimports Main\nbegin\n\nsection\\<open>Detour: Lexicographic ordering for lists\\<close>\ntext\\<open>Simplicial complexes are defined as sets of sets.\nTo conveniently run computations on them, we convert those sets to lists via @{const sorted_list_of_set}.\nThis requires providing an arbitrary linear order for lists.\nWe pick a lexicographic order.\\<close>\n\n(* There's probably an easier way to get a sorted list of lists from a set of lists. Some lexicographic ordering does have to exist. No idea... *)\n\ndatatype 'a :: linorder linorder_list = LinorderList \"'a list\"\n\ndefinition \"linorder_list_unwrap L \\<equiv> case L of LinorderList L \\<Rightarrow> L\" (* Meh, there is a way to get datatype to generate this. I forgot *)\n\nfun less_eq_linorder_list_pre where\n  \"less_eq_linorder_list_pre (LinorderList []) (LinorderList []) = True\" |\n  \"less_eq_linorder_list_pre (LinorderList []) _ = True\" |\n  \"less_eq_linorder_list_pre _ (LinorderList []) = False\" |\n  \"less_eq_linorder_list_pre (LinorderList (a # as)) (LinorderList (b # bs)) \n    = (if a = b then less_eq_linorder_list_pre (LinorderList as) (LinorderList bs) else a < b)\"\n\ninstantiation linorder_list :: (linorder) linorder\nbegin\ndefinition \"less_linorder_list x y \\<equiv> \n              (less_eq_linorder_list_pre x y \\<and> \\<not> less_eq_linorder_list_pre y x)\"\ndefinition \"less_eq_linorder_list x y \\<equiv> less_eq_linorder_list_pre x y\"\ninstance\nproof (standard; unfold less_eq_linorder_list_def less_linorder_list_def)\n  fix x y z\n  show \"less_eq_linorder_list_pre x x\"\n  proof(induction x)\n    case (LinorderList xa)\n    then show ?case by(induction xa; simp)\n  qed\n  show \"less_eq_linorder_list_pre x y \\<Longrightarrow> less_eq_linorder_list_pre y x \\<Longrightarrow> x = y\"\n    by(induction x y rule: less_eq_linorder_list_pre.induct; simp split: if_splits)\n  show \"less_eq_linorder_list_pre x y \\<or> less_eq_linorder_list_pre y x\"\n    by(induction x y rule: less_eq_linorder_list_pre.induct; auto)\n  show \"less_eq_linorder_list_pre x y \\<Longrightarrow> less_eq_linorder_list_pre y z \\<Longrightarrow> less_eq_linorder_list_pre x z\"\n  proof(induction x z arbitrary: y rule: less_eq_linorder_list_pre.induct)\n    case (3 va vb)\n    then show ?case \n      using less_eq_linorder_list_pre.elims(2) by blast\n  next\n    case (4 a1 as b1 bs)\n    obtain y1 ys where y: \"y = LinorderList (y1 # ys)\"\n      using \"4.prems\"(1) less_eq_linorder_list_pre.elims(2) by blast\n    then show ?case proof(cases \"a1 = b1\")\n      case True\n      have prems: \"less_eq_linorder_list_pre (LinorderList as) (LinorderList ys)\" \"less_eq_linorder_list_pre (LinorderList ys) (LinorderList bs)\"\n        by (metis \"4.prems\" True y less_eq_linorder_list_pre.simps(4) not_less_iff_gr_or_eq)+\n      note IH = \"4.IH\"[OF _ this]\n      then show ?thesis \n        using True by simp\n\n    next\n      case False\n        then show ?thesis using \"4.prems\" less_trans y by (simp  split: if_splits)\n      qed\n  qed simp_all\nqed simp\n\nend\n\ntext\\<open>The main product of this theory file:\\<close>\ndefinition \"sorted_list_of_list_set L \\<equiv> \n  map linorder_list_unwrap (sorted_list_of_set (LinorderList ` L))\"\n\nlemma set_sorted_list_of_list_set[simp]: \n  \"finite L \\<Longrightarrow> set (sorted_list_of_list_set L) = L\"\n  by(force simp add: sorted_list_of_list_set_def linorder_list_unwrap_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/ListLexorder.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382200964035, "lm_q2_score": 0.8558511451289037, "lm_q1q2_score": 0.7373484722418244}}
{"text": "theory \"Syntax\"\nimports\n  Complex_Main\n  \"Identifiers\"\nbegin \nsection \\<open>Syntax\\<close>\n\ntext \\<open>\n  Defines the syntax of Differential Game Logic as inductively defined data types.\n  \\<^url>\\<open>https://doi.org/10.1145/2817824\\<close> \\<^url>\\<open>https://doi.org/10.1007/978-3-319-94205-6_15\\<close>\n\\<close>\n\nsubsection \\<open>Terms\\<close>\n\ntext \\<open>Numeric literals\\<close>\ntype_synonym lit = real\n\ntext \\<open>the set of all real variables\\<close>\nabbreviation allidents:: \"ident set\"\n  where \"allidents \\<equiv> {x | x. True}\"\n\ntext \\<open>Variables and differential variables\\<close>\n\ndatatype variable =\n  RVar ident\n| DVar ident  \n\ndatatype trm =\n  Var variable\n| Number lit\n| Const ident\n| Func ident trm\n| Plus trm trm\n| Times trm trm\n| Differential trm\n\nsubsection \\<open>Formulas and Hybrid Games\\<close>\n\ndatatype fml =\n  Pred ident trm\n| Geq trm trm\n| Not fml                 (\"!\")\n| And fml fml             (infixr \"&&\" 8)\n| Exists variable fml\n| Diamond game fml        (\"(\\<langle> _ \\<rangle> _)\" 20)\nand game =\n  Game ident\n| Assign variable trm     (infixr \":=\" 20)\n| Test fml                (\"?\")\n| Choice game game        (infixr \"\\<union>\\<union>\" 10)\n| Compose game game       (infixr \";;\" 8)\n| Loop game               (\"_**\")\n| Dual game               (\"_^d\")\n| ODE ident trm\n\n\nparagraph \\<open>Derived operators\\<close>\ndefinition Neg ::\"trm \\<Rightarrow> trm\" \nwhere \"Neg \\<theta> = Times (Number (-1)) \\<theta>\"\n\ndefinition Minus ::\"trm \\<Rightarrow> trm \\<Rightarrow> trm\"\nwhere \"Minus \\<theta> \\<eta> = Plus \\<theta> (Neg \\<eta>)\"\n\ndefinition Or :: \"fml \\<Rightarrow> fml \\<Rightarrow> fml\" (infixr \"||\" 7)\nwhere \"Or P Q = Not (And (Not P) (Not Q))\"\n\ndefinition Implies :: \"fml \\<Rightarrow> fml \\<Rightarrow> fml\" (infixr \"\\<rightarrow>\" 10)\nwhere \"Implies P Q = Or Q (Not P)\"\n\ndefinition Equiv :: \"fml \\<Rightarrow> fml \\<Rightarrow> fml\" (infixr \"\\<leftrightarrow>\" 10)\nwhere \"Equiv P Q = Or (And P Q) (And (Not P) (Not Q))\"\n\ndefinition Forall :: \"variable \\<Rightarrow> fml \\<Rightarrow> fml\"\nwhere \"Forall x P = Not (Exists x (Not P))\"\n\ndefinition Equals :: \"trm \\<Rightarrow> trm \\<Rightarrow> fml\"\nwhere \"Equals \\<theta> \\<theta>' = ((Geq \\<theta> \\<theta>') && (Geq \\<theta>' \\<theta>))\"\n\ndefinition Greater :: \"trm \\<Rightarrow> trm \\<Rightarrow> fml\"\nwhere \"Greater \\<theta> \\<theta>' = ((Geq \\<theta> \\<theta>') && (Not (Geq \\<theta>' \\<theta>)))\"\n  \ntext \\<open>Justification: determinacy theorem justifies this equivalent syntactic abbreviation for box modalities from diamond modalities\n  Theorem 3.1 \\<^url>\\<open>https://doi.org/10.1145/2817824\\<close>\\<close>\ndefinition Box :: \"game \\<Rightarrow> fml \\<Rightarrow> fml\" (\"([[_]]_)\" 20)\nwhere \"Box \\<alpha> P = Not (Diamond \\<alpha> (Not P))\"\n  \ndefinition TT ::\"fml\" \nwhere \"TT = Geq (Number 0) (Number 0)\"\n\ndefinition FF ::\"fml\" \nwhere \"FF = Geq (Number 0) (Number 1)\"\n\ndefinition Skip ::\"game\" \nwhere \"Skip = Test TT\"\n\ntext \\<open>Inference: premises, then conclusion\\<close>\ntype_synonym inference = \"fml list * fml\"\n\ntype_synonym sequent = \"fml list * fml list\"\ntext \\<open>Rule: premises, then conclusion\\<close>\ntype_synonym rule = \"sequent list * sequent\"\n\n\nsubsection \\<open>Structural Induction\\<close>\n\ntext \\<open>Induction principles for hybrid games owing to their mutually recursive definition with formulas \\<close>\n\nlemma game_induct [case_names Game Assign ODE Test Choice Compose Loop Dual]:\n   \"(\\<And>a. P (Game a)) \n    \\<Longrightarrow> (\\<And>x \\<theta>. P (Assign x \\<theta>))\n    \\<Longrightarrow> (\\<And>x \\<theta>. P (ODE x \\<theta>))\n    \\<Longrightarrow> (\\<And>\\<phi>. P (? \\<phi>))\n    \\<Longrightarrow> (\\<And>\\<alpha> \\<beta>. P \\<alpha> \\<Longrightarrow> P \\<beta> \\<Longrightarrow> P (\\<alpha> \\<union>\\<union> \\<beta>))\n    \\<Longrightarrow> (\\<And>\\<alpha> \\<beta>. P \\<alpha> \\<Longrightarrow> P \\<beta> \\<Longrightarrow> P (\\<alpha> ;; \\<beta>))\n    \\<Longrightarrow> (\\<And>\\<alpha>. P \\<alpha> \\<Longrightarrow> P (\\<alpha>**))\n    \\<Longrightarrow> (\\<And>\\<alpha>. P \\<alpha> \\<Longrightarrow> P (\\<alpha>^d))\n    \\<Longrightarrow> P \\<alpha>\"\n  by(induction rule: game.induct) (auto)\n\nlemma fml_induct [case_names Pred Geq Not And Exists Diamond]:\n  \"(\\<And>x \\<theta>. P (Pred x \\<theta>))\n  \\<Longrightarrow> (\\<And>\\<theta> \\<eta>. P (Geq \\<theta> \\<eta>))\n  \\<Longrightarrow> (\\<And>\\<phi>. P \\<phi> \\<Longrightarrow> P (Not \\<phi>))\n  \\<Longrightarrow> (\\<And>\\<phi> \\<psi>. P \\<phi> \\<Longrightarrow> P \\<psi> \\<Longrightarrow> P (And \\<phi> \\<psi>))\n  \\<Longrightarrow> (\\<And>x \\<phi>. P \\<phi> \\<Longrightarrow> P (Exists x \\<phi>))\n  \\<Longrightarrow> (\\<And>\\<alpha> \\<phi>. P \\<phi> \\<Longrightarrow> P (Diamond \\<alpha> \\<phi>))\n  \\<Longrightarrow> P \\<phi>\"\n  by (induction rule: fml.induct) (auto)\n\ntext \\<open>the set of all variables\\<close>\nabbreviation allvars:: \"variable set\"\n  where \"allvars \\<equiv> {x::variable. True}\"\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/Differential_Game_Logic/Syntax.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8615382094310357, "lm_q2_score": 0.8558511524823263, "lm_q1q2_score": 0.7373484694491117}}
{"text": "(*  Title       : Fact.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    The integer version of factorial and other additions by Jeremy Avigad.\n*)\n\nsection{*Factorial Function*}\n\ntheory Fact\nimports Main\nbegin\n\nclass fact =\n  fixes fact :: \"'a \\<Rightarrow> 'a\"\n\ninstantiation nat :: fact\nbegin \n\nfun\n  fact_nat :: \"nat \\<Rightarrow> nat\"\nwhere\n  fact_0_nat: \"fact_nat 0 = Suc 0\"\n| fact_Suc: \"fact_nat (Suc x) = Suc x * fact x\"\n\ninstance ..\n\nend\n\n(* definitions for the integers *)\n\ninstantiation int :: fact\n\nbegin \n\ndefinition\n  fact_int :: \"int \\<Rightarrow> int\"\nwhere  \n  \"fact_int x = (if x >= 0 then int (fact (nat x)) else 0)\"\n\ninstance proof qed\n\nend\n\n\nsubsection {* Set up Transfer *}\n\nlemma transfer_nat_int_factorial:\n  \"(x::int) >= 0 \\<Longrightarrow> fact (nat x) = nat (fact x)\"\n  unfolding fact_int_def\n  by auto\n\n\nlemma transfer_nat_int_factorial_closure:\n  \"x >= (0::int) \\<Longrightarrow> fact x >= 0\"\n  by (auto simp add: fact_int_def)\n\ndeclare transfer_morphism_nat_int[transfer add return: \n    transfer_nat_int_factorial transfer_nat_int_factorial_closure]\n\nlemma transfer_int_nat_factorial:\n  \"fact (int x) = int (fact x)\"\n  unfolding fact_int_def by auto\n\nlemma transfer_int_nat_factorial_closure:\n  \"is_nat x \\<Longrightarrow> fact x >= 0\"\n  by (auto simp add: fact_int_def)\n\ndeclare transfer_morphism_int_nat[transfer add return: \n    transfer_int_nat_factorial transfer_int_nat_factorial_closure]\n\n\nsubsection {* Factorial *}\n\nlemma fact_0_int [simp]: \"fact (0::int) = 1\"\n  by (simp add: fact_int_def)\n\nlemma fact_1_nat [simp]: \"fact (1::nat) = 1\"\n  by simp\n\nlemma fact_Suc_0_nat [simp]: \"fact (Suc 0) = Suc 0\"\n  by simp\n\nlemma fact_1_int [simp]: \"fact (1::int) = 1\"\n  by (simp add: fact_int_def)\n\nlemma fact_plus_one_nat: \"fact ((n::nat) + 1) = (n + 1) * fact n\"\n  by simp\n\nlemma fact_plus_one_int: \n  assumes \"n >= 0\"\n  shows \"fact ((n::int) + 1) = (n + 1) * fact n\"\n  using assms unfolding fact_int_def \n  by (simp add: nat_add_distrib algebra_simps int_mult)\n\nlemma fact_reduce_nat: \"(n::nat) > 0 \\<Longrightarrow> fact n = n * fact (n - 1)\"\n  apply (subgoal_tac \"n = Suc (n - 1)\")\n  apply (erule ssubst)\n  apply (subst fact_Suc)\n  apply simp_all\n  done\n\nlemma fact_reduce_int: \"(n::int) > 0 \\<Longrightarrow> fact n = n * fact (n - 1)\"\n  apply (subgoal_tac \"n = (n - 1) + 1\")\n  apply (erule ssubst)\n  apply (subst fact_plus_one_int)\n  apply simp_all\n  done\n\nlemma fact_nonzero_nat [simp]: \"fact (n::nat) \\<noteq> 0\"\n  apply (induct n)\n  apply (auto simp add: fact_plus_one_nat)\n  done\n\nlemma fact_nonzero_int [simp]: \"n >= 0 \\<Longrightarrow> fact (n::int) ~= 0\"\n  by (simp add: fact_int_def)\n\nlemma fact_gt_zero_nat [simp]: \"fact (n :: nat) > 0\"\n  by (insert fact_nonzero_nat [of n], arith)\n\nlemma fact_gt_zero_int [simp]: \"n >= 0 \\<Longrightarrow> fact (n :: int) > 0\"\n  by (auto simp add: fact_int_def)\n\nlemma fact_ge_one_nat [simp]: \"fact (n :: nat) >= 1\"\n  by (insert fact_nonzero_nat [of n], arith)\n\nlemma fact_ge_Suc_0_nat [simp]: \"fact (n :: nat) >= Suc 0\"\n  by (insert fact_nonzero_nat [of n], arith)\n\nlemma fact_ge_one_int [simp]: \"n >= 0 \\<Longrightarrow> fact (n :: int) >= 1\"\n  apply (auto simp add: fact_int_def)\n  apply (subgoal_tac \"1 = int 1\")\n  apply (erule ssubst)\n  apply (subst zle_int)\n  apply auto\n  done\n\nlemma dvd_fact_nat [rule_format]: \"1 <= m \\<longrightarrow> m <= n \\<longrightarrow> m dvd fact (n::nat)\"\n  apply (induct n)\n  apply force\n  apply (auto simp only: fact_Suc)\n  apply (subgoal_tac \"m = Suc n\")\n  apply (erule ssubst)\n  apply (rule dvd_triv_left)\n  apply auto\n  done\n\nlemma dvd_fact_int [rule_format]: \"1 <= m \\<longrightarrow> m <= n \\<longrightarrow> m dvd fact (n::int)\"\n  apply (case_tac \"1 <= n\")\n  apply (induct n rule: int_ge_induct)\n  apply (auto simp add: fact_plus_one_int)\n  apply (subgoal_tac \"m = i + 1\")\n  apply auto\n  done\n\nlemma interval_plus_one_nat: \"(i::nat) <= j + 1 \\<Longrightarrow> \n  {i..j+1} = {i..j} Un {j+1}\"\n  by auto\n\nlemma interval_Suc: \"i <= Suc j \\<Longrightarrow> {i..Suc j} = {i..j} Un {Suc j}\"\n  by auto\n\nlemma interval_plus_one_int: \"(i::int) <= j + 1 \\<Longrightarrow> {i..j+1} = {i..j} Un {j+1}\"\n  by auto\n\nlemma fact_altdef_nat: \"fact (n::nat) = (PROD i:{1..n}. i)\"\n  apply (induct n)\n  apply force\n  apply (subst fact_Suc)\n  apply (subst interval_Suc)\n  apply auto\ndone\n\nlemma fact_altdef_int: \"n >= 0 \\<Longrightarrow> fact (n::int) = (PROD i:{1..n}. i)\"\n  apply (induct n rule: int_ge_induct)\n  apply force\n  apply (subst fact_plus_one_int, assumption)\n  apply (subst interval_plus_one_int)\n  apply auto\ndone\n\nlemma fact_dvd: \"n \\<le> m \\<Longrightarrow> fact n dvd fact (m::nat)\"\n  by (auto simp add: fact_altdef_nat intro!: setprod_dvd_setprod_subset)\n\nlemma fact_mod: \"m \\<le> (n::nat) \\<Longrightarrow> fact n mod fact m = 0\"\n  by (auto simp add: dvd_imp_mod_0 fact_dvd)\n\nlemma fact_div_fact:\n  assumes \"m \\<ge> (n :: nat)\"\n  shows \"(fact m) div (fact n) = \\<Prod>{n + 1..m}\"\nproof -\n  obtain d where \"d = m - n\" by auto\n  from assms this have \"m = n + d\" by auto\n  have \"fact (n + d) div (fact n) = \\<Prod>{n + 1..n + d}\"\n  proof (induct d)\n    case 0\n    show ?case by simp\n  next\n    case (Suc d')\n    have \"fact (n + Suc d') div fact n = Suc (n + d') * fact (n + d') div fact n\"\n      by simp\n    also from Suc.hyps have \"... = Suc (n + d') * \\<Prod>{n + 1..n + d'}\" \n      unfolding div_mult1_eq[of _ \"fact (n + d')\"] by (simp add: fact_mod)\n    also have \"... = \\<Prod>{n + 1..n + Suc d'}\"\n      by (simp add: atLeastAtMostSuc_conv setprod.insert)\n    finally show ?case .\n  qed\n  from this `m = n + d` show ?thesis by simp\nqed\n\nlemma fact_mono_nat: \"(m::nat) \\<le> n \\<Longrightarrow> fact m \\<le> fact n\"\napply (drule le_imp_less_or_eq)\napply (auto dest!: less_imp_Suc_add)\napply (induct_tac k, auto)\ndone\n\nlemma fact_neg_int [simp]: \"m < (0::int) \\<Longrightarrow> fact m = 0\"\n  unfolding fact_int_def by auto\n\nlemma fact_ge_zero_int [simp]: \"fact m >= (0::int)\"\n  apply (case_tac \"m >= 0\")\n  apply auto\n  apply (frule fact_gt_zero_int)\n  apply arith\ndone\n\nlemma fact_mono_int_aux [rule_format]: \"k >= (0::int) \\<Longrightarrow> \n    fact (m + k) >= fact m\"\n  apply (case_tac \"m < 0\")\n  apply auto\n  apply (induct k rule: int_ge_induct)\n  apply auto\n  apply (subst add.assoc [symmetric])\n  apply (subst fact_plus_one_int)\n  apply auto\n  apply (erule order_trans)\n  apply (subst mult_le_cancel_right1)\n  apply (subgoal_tac \"fact (m + i) >= 0\")\n  apply arith\n  apply auto\ndone\n\nlemma fact_mono_int: \"(m::int) <= n \\<Longrightarrow> fact m <= fact n\"\n  apply (insert fact_mono_int_aux [of \"n - m\" \"m\"])\n  apply auto\ndone\n\ntext{*Note that @{term \"fact 0 = fact 1\"}*}\nlemma fact_less_mono_nat: \"[| (0::nat) < m; m < n |] ==> fact m < fact n\"\napply (drule_tac m = m in less_imp_Suc_add, auto)\napply (induct_tac k, auto)\ndone\n\nlemma fact_less_mono_int_aux: \"k >= 0 \\<Longrightarrow> (0::int) < m \\<Longrightarrow>\n    fact m < fact ((m + 1) + k)\"\n  apply (induct k rule: int_ge_induct)\n  apply (simp add: fact_plus_one_int)\n  apply (subst (2) fact_reduce_int)\n  apply (auto simp add: ac_simps)\n  apply (erule order_less_le_trans)\n  apply auto\n  done\n\nlemma fact_less_mono_int: \"(0::int) < m \\<Longrightarrow> m < n \\<Longrightarrow> fact m < fact n\"\n  apply (insert fact_less_mono_int_aux [of \"n - (m + 1)\" \"m\"])\n  apply auto\ndone\n\nlemma fact_num_eq_if_nat: \"fact (m::nat) = \n  (if m=0 then 1 else m * fact (m - 1))\"\nby (cases m) auto\n\nlemma fact_add_num_eq_if_nat:\n  \"fact ((m::nat) + n) = (if m + n = 0 then 1 else (m + n) * fact (m + n - 1))\"\nby (cases \"m + n\") auto\n\nlemma fact_add_num_eq_if2_nat:\n  \"fact ((m::nat) + n) = \n    (if m = 0 then fact n else (m + n) * fact ((m - 1) + n))\"\nby (cases m) auto\n\nlemma fact_le_power: \"fact n \\<le> n^n\"\nproof (induct n)\n  case (Suc n)\n  then have \"fact n \\<le> Suc n ^ n\" by (rule le_trans) (simp add: power_mono)\n  then show ?case by (simp add: add_le_mono)\nqed simp\n\nsubsection {* @{term fact} and @{term of_nat} *}\n\nlemma of_nat_fact_not_zero [simp]: \"of_nat (fact n) \\<noteq> (0::'a::semiring_char_0)\"\nby auto\n\nlemma of_nat_fact_gt_zero [simp]: \"(0::'a::{linordered_semidom}) < of_nat(fact n)\" by auto\n\nlemma of_nat_fact_ge_zero [simp]: \"(0::'a::linordered_semidom) \\<le> of_nat(fact n)\"\nby simp\n\nlemma inv_of_nat_fact_gt_zero [simp]: \"(0::'a::linordered_field) < inverse (of_nat (fact n))\"\nby (auto simp add: positive_imp_inverse_positive)\n\nlemma inv_of_nat_fact_ge_zero [simp]: \"(0::'a::linordered_field) \\<le> inverse (of_nat (fact n))\"\nby (auto intro: order_less_imp_le)\n\nlemma fact_eq_rev_setprod_nat: \"fact (k::nat) = (\\<Prod>i<k. k - i)\"\n  unfolding fact_altdef_nat\n  by (rule setprod.reindex_bij_witness[where i=\"\\<lambda>i. k - i\" and j=\"\\<lambda>i. k - i\"]) auto\n\nlemma fact_div_fact_le_pow:\n  assumes \"r \\<le> n\" shows \"fact n div fact (n - r) \\<le> n ^ r\"\nproof -\n  have \"\\<And>r. r \\<le> n \\<Longrightarrow> \\<Prod>{n - r..n} = (n - r) * \\<Prod>{Suc (n - r)..n}\"\n    by (subst setprod.insert[symmetric]) (auto simp: atLeastAtMost_insertL)\n  with assms show ?thesis\n    by (induct r rule: nat.induct) (auto simp add: fact_div_fact Suc_diff_Suc mult_le_mono)\nqed\n\nlemma fact_numeral:  --{*Evaluation for specific numerals*}\n  \"fact (numeral k) = (numeral k) * (fact (pred_numeral k))\"\n  by (simp add: numeral_eq_Suc)\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/Fact.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382094310355, "lm_q2_score": 0.8558511524823263, "lm_q1q2_score": 0.7373484694491116}}
{"text": "section \\<open> Encoding real numbers as bit sequences \\<close>\n\ntheory Real_Bit\nimports\n  HOL.Transcendental\n  \"HOL-Library.Z2\"\n  \"HOL-Library.Sublist\"\n  Dyadic\nbegin\n\ntext \\<open> The objective of this theory is to show how every real number can be encoded as an infinite\n  sequences of bits. Whilst being an interesting property in its own right, this in particular\n  means that we can show that the real numbers can be encoded as a a set of natural numbers\n  (i.e. a function of type @{typ \"nat \\<Rightarrow> bool\"} -- a bit sequence), and thus have the same\n  cardinality. \\<close>\n\ndeclare [[linarith_split_limit=12]]\n\ndefinition bits_to_nats :: \"(nat \\<Rightarrow> bit) \\<Rightarrow> nat set\" where\n\"bits_to_nats f = {x. f x = 1}\"\n\nlemma bij_bits_to_nats: \"bij bits_to_nats\"\n  apply (rule bijI)\n   apply (rule injI)\n   apply (simp add: bits_to_nats_def set_eq_iff)\n  apply (rule ext)\n  apply (rename_tac x y i)\n  apply (case_tac \"x i\", auto)\n  apply (metis bit.exhaust)\n  apply (simp add: image_def bits_to_nats_def)\n  apply (rename_tac x)\n  apply (rule_tac x=\"\\<lambda> i. if (i \\<in> x) then 1 else 0\" in exI)\n  apply (auto)\n  done\n\nlemma card_of_bit_seq: \"|UNIV :: (nat \\<Rightarrow> bit) set| =o |UNIV :: nat set set|\"\n  using bij_bits_to_nats card_of_ordIsoI by blast\n\nlemma uncountable_UNIV_nat_set: \"uncountable (UNIV :: nat set set)\"\n  by (auto simp add: uncountable_def, metis Cantors_paradox Pow_UNIV)\n\nlemma card_rat_less_nat_set: \"|\\<rat> :: real set| <o |UNIV :: nat set set|\"\nproof -\n  have \"countable (\\<rat> :: real set)\"\n    by (simp add: countable_rat)\n  moreover have \"uncountable (UNIV :: nat set set)\"\n    by (simp add: uncountable_UNIV_nat_set)\n  ultimately show ?thesis\n    by (metis card_of_ordLess2 countable_empty countable_image)\nqed\n\ndefinition terminates_at :: \"(nat \\<Rightarrow> 'a::zero) \\<Rightarrow> nat \\<Rightarrow> bool\" where\n\"terminates_at x i = (\\<forall> j \\<ge> i. x(j) = 0)\"\n\ndefinition terminal :: \"(nat \\<Rightarrow> 'a::zero) \\<Rightarrow> bool\" where\n\"terminal x = (\\<exists> i. terminates_at x i)\"\n\nabbreviation \"BitSeqs \\<equiv> (UNIV :: (nat \\<Rightarrow> bit) set)\"\n\nabbreviation \"TermSeqs \\<equiv> {x. terminal x}\"\n\nabbreviation \"TermBitSeqs \\<equiv> TermSeqs :: (nat \\<Rightarrow> bit) set\"\n\nabbreviation \"nonterminal x \\<equiv> \\<not> terminal x\"\n\nabbreviation \"NonTermSeqs \\<equiv> {x. nonterminal x}\"\n\nabbreviation \"NonTermBitSeqs \\<equiv> NonTermSeqs :: (nat \\<Rightarrow> bit) set\"\n\ndefinition subsequence :: \"nat \\<Rightarrow> (nat \\<Rightarrow> 'a) \\<Rightarrow> (nat \\<Rightarrow> 'a)\" where\n\"subsequence n x = (\\<lambda> i. x (i + n))\"\n\ndefinition recur :: \"('a list) \\<Rightarrow> (nat \\<Rightarrow> 'a)\" where\n\"recur xs = (\\<lambda> i. xs ! (i mod (length xs)))\"\n\nlemma recur_example: \"recur [x,y] i = (if even i then x else y)\"\n  apply (auto simp add: recur_def)\n  apply (simp add: numeral_2_eq_2)\n  apply (metis One_nat_def even_iff_mod_2_eq_zero not_mod_2_eq_0_eq_1 nth_Cons_0 nth_Cons_Suc numeral_2_eq_2)\ndone\n\ndefinition recurrent :: \"(nat \\<Rightarrow> bit) \\<Rightarrow> bool\" where\n\"recurrent x = (\\<exists> n xs. subsequence n x = recur xs)\"\n\nlemma recurrent_recur: \"recurrent (recur xs)\"\n  apply (auto simp add: recurrent_def recur_def subsequence_def)\n  apply (rule_tac x=\"0\" in exI)\n  apply (rule_tac x=\"xs\" in exI)\n  apply (auto)\ndone\n\ntext \\<open> Convert a binary representation to a real number in [0..1] \\<close>\n\ndefinition binlist :: \"bit list \\<Rightarrow> real\" where\n\"binlist xs = (\\<Sum> i<length xs. of_bit(xs!i)/2^(i+1))\"\n\nlemma Ints_of_bit: \"of_bit x \\<in> \\<int>\"\n  by (cases \"x\", simp_all)\n\nlemma dyadic_bin_list: \"dyadic (binlist xs)\"\n  apply (unfold binlist_def)\n  apply (rule dyadic_sum)\n  apply (blast)\n  apply (blast intro: Ints_of_bit dyadic_div_pow_2)\ndone\n\n(*\nlemma \"bij_betw binlist {xs. length xs > 0 \\<longrightarrow> last xs = 1} \\<rat>\\<^sub>D\"\n  apply (rule bij_betwI')\n*)\n\ntext \\<open> For real number x, calculate the nth binary digit, given all the bits from 0..n-1 \\<close>\n\ndefinition rbit :: \"real \\<Rightarrow> nat \\<Rightarrow> bit list \\<Rightarrow> bit\" where\n  \"rbit x n xs = of_int \\<lfloor>(x - binlist xs) * 2^(n+2)\\<rfloor>\"\n\ntext \\<open> Convert a real number in the range [0..1) to a sequence of binary digits \\<close>\n\ntext \\<open> Extract the nth bit of a real number by shifting it to the left n+1 places (power multiplication),\n        chopping off the fractional part (flooring it), and removing all but the first bit of\n        the integer part (by takes modulus 2). \\<close>\n\ndefinition rbseq :: \"real \\<Rightarrow> (nat \\<Rightarrow> bit)\" where\n\"rbseq x = (\\<lambda> i.  of_int (\\<lfloor>(x * (2 ^ (i+1)))\\<rfloor> mod 2))\"\n\nlemma of_drat_DFract: \"coprime a (2^b) \\<Longrightarrow> of_drat (DFract a b) = a / 2^b\"\n  by (transfer, auto simp add: quotient_of_Fract of_int_power)\n\ndefinition real_bits2 :: \"real \\<Rightarrow> nat \\<Rightarrow> bit list\" where\n\"real_bits2 x n = map (rbseq x) [0..<n+1]\"\n\nfun real_bits :: \"real \\<Rightarrow> nat \\<Rightarrow> bit list\" where\n\"real_bits x 0 = [of_int \\<lfloor>x * 2\\<rfloor>]\" |\n\"real_bits x (Suc n) =\n   (real_bits x n @ [rbit x n (real_bits x n)])\"\n\ndefinition drat_bits :: \"drat \\<Rightarrow> bit list\" where\n\"drat_bits x = real_bits (of_drat x) (snd (dfrac_of x))\"\n\n(* Produce version that produces a non-terminating number for dyadics *)\n\ndefinition real_bin :: \"real \\<Rightarrow> (nat \\<Rightarrow> bit)\" where\n\"real_bin x = (\\<lambda> n. (real_bits x n) ! n)\"\n\ndefinition real_bin_seq :: \"real \\<Rightarrow> (nat \\<Rightarrow> bool)\" where\n\"real_bin_seq x n = (last (real_bits x n) = 1)\"\n\ndefinition binseq :: \"(nat \\<Rightarrow> bit) \\<Rightarrow> (nat \\<Rightarrow> real)\" where\n\"binseq x = (\\<lambda> i. of_bit (x(i)) / 2^(i+1))\"\n\ndefinition bin_real :: \"(nat \\<Rightarrow> bit) \\<Rightarrow> real\" where\n\"bin_real x = (\\<Sum> i. binseq x i)\"\n\nlemma binseq_le_bin_series: \"(\\<Sum> i<n. binseq x i) \\<le> (\\<Sum> i<n. 1/2^i)\"\n  apply (rule sum_mono)\n  apply (rename_tac i)\n  apply (simp add: binseq_def)\n  apply (case_tac \"x i\")\n  apply (auto simp add: frac_le)\ndone\n\nlemma bin_series_geometric:\n  \"((\\<Sum> i\\<le>n. 1/2^(i+1)) :: rat) = 1 - (1 / 2^(n + 1))\"\nproof -\n  have \"((\\<Sum> i\\<le>n. 1/2^(i+1)) :: rat) = (\\<Sum> i<n+2. (1/2)^i) - 1\"\n    by (induct n, simp_all add: power_one_over)\n  also have \"... = 1 - (1 / 2^(n + 1))\"\n    by (subst geometric_sum, simp_all add: power_one_over)\n  finally show ?thesis .\nqed\n\nlemma binseq_pos: \"binseq x i \\<ge> 0\"\n  by (case_tac \"x i\", simp_all add: binseq_def)\n\nlemma sum_minus_triv:\n  fixes f :: \"nat \\<Rightarrow> 'b::ab_group_add\"\n  assumes \"n \\<ge> m\"\n  shows \"(\\<Sum>i\\<le>n. f(i)) - (\\<Sum>i\\<le>m. f(i)) = (\\<Sum>i=m+1..n. f(i))\"\nproof -\n  have \"{..n} - {..m} = {m + 1..n}\"\n    by auto\n  with assms show ?thesis\n    by (simp add: sum_diff[THEN sym])\nqed\n\nlemma binary_ub:\n  assumes \"n \\<ge> m\"\n  shows \"((1 / 2 ^ m) :: real) > (\\<Sum>i=m+1..n. 1 / 2 ^ i)\"\nproof -\n  from assms have \"((\\<Sum>i=m+1..n. 1 / 2 ^ i) :: real) = (\\<Sum>i<n+1. 1/2^i) - (\\<Sum>i<m+1. 1/2^i)\"\n    by (subst sum_minus_triv[THEN sym], simp_all add: lessThan_Suc_atMost)\n  also have \"... = (\\<Sum>i<n+1. (1/2)^i) - (\\<Sum>i<m+1. (1/2)^i)\"\n    by (simp add: power_one_over)\n  also have \"... = 2 / 2 ^ (m + 1) - 2 / 2 ^ (n + 1)\"\n    by (simp only: geometric_sum, simp add: power_one_over)\n  moreover have \"(1/2^m :: real) > 2 / 2 ^ (m + 1) - 2 / 2 ^ (n + 1)\"\n    by (auto)\n  ultimately show ?thesis\n    by linarith\nqed\n\nlemma real_bin_ub:\n  assumes \"m > 0\"\n  shows \"\\<exists> n. 2^n > (m::real)\"\nproof -\n  have \"m \\<le> \\<lceil>m\\<rceil>\"\n    by (simp add: le_of_int_ceiling)\n  moreover from assms have \"2 powr \\<lceil>log 2 \\<lceil>m\\<rceil>\\<rceil> \\<ge> \\<lceil>m\\<rceil>\"\n    by (subst log_le_iff[THEN sym], simp_all)\n  moreover from assms have \"2 powr \\<lceil>log 2 \\<lceil>m\\<rceil>\\<rceil> = 2 powr (real (nat (\\<lceil>log 2 \\<lceil>m\\<rceil>\\<rceil> :: int)))\"\n  proof -\n    from assms have \"log 2 \\<lceil>m\\<rceil> \\<ge> 0\"\n      by simp\n    thus ?thesis\n      by simp\n  qed\n  ultimately have \"2 ^ nat \\<lceil>log 2 \\<lceil>m\\<rceil>\\<rceil> \\<ge> m\"\n    by (metis order_trans powr_realpow zero_less_numeral)\n  with assms have \"2 ^ (nat \\<lceil>log 2 \\<lceil>m\\<rceil>\\<rceil> + 1) > m\"\n    by simp\n  thus ?thesis\n    by blast\nqed\n\nlemma real_bin_lower_bound:\n  assumes \"(m::real) > 0\"\n  shows \"\\<exists> n::nat. 1 / 2^n < m\"\nproof -\n  from assms obtain n where \"2^n > (1/m)\"\n    using real_bin_ub[of \"1/m\"] by auto\n  with assms have \"1/2^n < 1/(1/m)\"\n    by (subst frac_less2, auto)\n  thus ?thesis\n    by (rule_tac x=\"n\" in exI, auto)\nqed\n\ntheorem binseq_summable: \"summable (binseq x)\"\nproof (simp add: summable_Cauchy, clarify)\n  fix r :: real\n  assume \"r > 0\"\n  then obtain j where wits: \"1/2^j < r\"\n    using real_bin_lower_bound[of \"r\"] by auto\n  then show \"\\<exists>k. \\<forall>m\\<ge>k. \\<forall>n. \\<bar>sum (binseq x) {m..<n}\\<bar> < r\"\n  proof (rule_tac x=\"j+1\" in exI, clarify)\n    fix m n :: nat\n    assume mnassm: \"j+1 \\<le> m\"\n    have \"(\\<Sum> i=m..<n. binseq x i) \\<le> 1/2^j\"\n    proof -\n      have \"(\\<Sum> i=m..<n. binseq x i) \\<le> (\\<Sum>i=m..<n. 1/2^i)\"\n        by (rule sum_mono)\n           (simp add: binseq_def frac_le)\n      also from mnassm have \"... \\<le> (\\<Sum>i=j+1..n-1. 1/2^i)\"\n        by (auto intro!: sum_mono2)\n      also have \"... < 1/2^j\"\n      proof (cases \"j \\<le> n - 1\")\n        case True thus ?thesis\n          by (rule binary_ub)\n      next\n        case False thus ?thesis\n          by auto\n      qed\n      finally show ?thesis by auto\n    qed\n    with mnassm wits show \"\\<bar>sum (binseq x) {m..<n}\\<bar> < r\"\n      by (auto simp add: sum_minus_triv binseq_pos sum_nonneg)\n  qed\nqed\n\nlemma binlist_nil [simp]:\n  \"binlist [] = 0\"\n  by (simp add: binlist_def)\n\nlemma binlist_append [simp]:\n  \"binlist (xs @ [x]) = binlist xs + (of_bit x*(1/2^(length xs + 1)))\"\n  by (simp add: binlist_def nth_append)\n\nlemma of_bit_pos: \"of_bit x \\<ge> (0::real)\"\n  by (cases x, auto)\n\nlemma bit_real_pos: \"of_bit x * (1/2^n) \\<ge> (0::real)\"\nproof -\n  have \"of_bit x \\<ge> (0::real)\"\n    by (cases x, auto)\n  moreover have \"1/2^n \\<ge> (0::real)\"\n    by auto\n  ultimately show ?thesis\n    by auto\nqed\n\nlemma binlist_pos [simp]:\n  \"binlist xs \\<ge> 0\"\n  by (induct xs rule: rev_induct, auto simp add: of_bit_pos)\n\nlemma real_bits_length [simp]:\n  \"length (real_bits x n) = n + 1\"\n  by (induct n, simp_all)\n\nlemma real_bits_first [simp]:\n  \"real_bits x m ! 0 = of_int \\<lfloor>x * 2\\<rfloor>\"\n  by (induct m, simp_all add: nth_append)\n\nlemma real_bits_plus:\n  assumes \"i \\<le> m\"\n  shows \"real_bits x (m + k) ! i = real_bits x m ! i\"\n  using assms\n  by (induct k, auto simp add: nth_append)\n\nlemma prefix_nth:\n  \"\\<lbrakk> length xs \\<le> length ys; \\<forall> i < length xs. xs!i = ys!i \\<rbrakk> \\<Longrightarrow> prefix xs ys\"\nproof (induct xs arbitrary: ys)\n  case Nil thus ?case by auto\nnext\n  case (Cons x xs') note hyp = this\n  then obtain ys' where \"ys = x # ys'\"\n    by (metis Cons_prefix_Cons in_set_takeD list.set_cases list.set_intros(1) nth_take_lemma order_refl take_all take_is_prefix)\n  with hyp show ?case\n    by (auto, metis le_trans not_less not_less_eq_eq not_less_iff_gr_or_eq nth_Cons_Suc)\nqed\n\nlemma real_bits_prefix:\n  assumes \"m \\<le> n\"\n  shows \"prefix (real_bits x m) (real_bits x n)\"\nproof -\n  obtain k where \"n = m + k\"\n    by (metis assms le_add_diff_inverse)\n  thus ?thesis\n    by (auto intro: prefix_nth simp add: real_bits_plus)\nqed\n\nlemma binseq_rbseq: \"binseq (rbseq x) i = (\\<lfloor>x * (2 ^ (i+1))\\<rfloor> mod 2) / (2 ^ (i+1))\"\n  by (simp add: binseq_def rbseq_def)\n     (metis not_mod_2_eq_1_eq_0 of_int_0 of_int_1)\n\ntext \\<open> The contribution of the nth bit to a real number \\<close>\n\ndefinition nth_cont :: \"real \\<Rightarrow> nat \\<Rightarrow> real\" where\n\"nth_cont x i = \\<lfloor>x * (2^(i+1))\\<rfloor> mod 2 / (2^(i+1))\"\n\ntext \\<open> Every bit contribution is less than the whole \\<close>\n\nlemma nth_cont_cases [case_names zero nzero]:\n  \"\\<lbrakk> nth_cont x i = 0 \\<Longrightarrow> P; nth_cont x i = 1/2^(i+1) \\<Longrightarrow> P \\<rbrakk> \\<Longrightarrow> P\"\n  apply (simp add: nth_cont_def)\n  apply (cases \"\\<lfloor>x * (2 * 2 ^ i)\\<rfloor>\" rule: parity_cases)\n  apply (simp_all)\ndone\n\nlemma nth_cont_le_geometric:\n  \"(\\<Sum> i\\<le>n. nth_cont x i) \\<le> 1 - (1 / 2^(n + 1))\"\nproof -\n  have \"(\\<Sum> i\\<le>n. nth_cont x i) \\<le> (\\<Sum> i\\<le>n. 1 / (2^(i+1)))\"\n    by (rule sum_mono, metis nth_cont_cases order_refl zero_le_divide_1_iff zero_le_numeral zero_le_power)\n  also have \"... = (\\<Sum> i<n+2. (1/2)^i) - 1\"\n    by (induct n, simp_all add: power_one_over)\n  also have \"... = 1 - (1 / 2^(n + 1))\"\n    by (subst geometric_sum, simp_all add: power_one_over)\n  finally show ?thesis .\nqed\n\nlemma nth_cont_bit_diff_ge_zero:\n  assumes \"0 \\<le> x\" \"x < 1\"\n  shows \"0 \\<le> x - nth_cont x i\"\nproof (cases \"\\<lfloor>x * (2 ^ (i+1))\\<rfloor>\" rule: parity_cases)\n  case even\n  with assms show ?thesis by (simp add: nth_cont_def)\nnext\n  case odd\n  have \"\\<lfloor>x * (2 ^ (i+1))\\<rfloor> \\<ge> 0\"\n    by (simp add: assms(1))\n  with odd have \"\\<lfloor>x * (2 ^ (i+1))\\<rfloor> \\<ge> (1::int)\"\n    by (metis zmod_le_nonneg_dividend)\n  with odd show ?thesis\n    by (simp add: nth_cont_def pos_divide_le_eq)\nqed\n\nlemma bin_series_geometric':\n  \"((\\<Sum> i\\<le>n. 1/2^(i+1)) :: real) = 1 - (1 / 2^(n + 1))\"\nproof -\n  have \"((\\<Sum> i\\<le>n. 1/2^(i+1)) :: real) = (\\<Sum> i<n+2. (1/2)^i) - 1\"\n    by (induct n, simp_all add: power_one_over)\n  also have \"... = 1 - (1 / 2^(n + 1))\"\n    by (subst geometric_sum, simp_all add: power_one_over)\n  finally show ?thesis .\nqed\n\ntext \\<open> The removal of the (contribution of) the ith bit from a real number does not affect\n        the jth bit. \\<close>\n\nlemma nth_cont_removed:\n  \"nth_cont (x - nth_cont x i) i = 0\"\nproof -\n  have \"(x - 1 / (2 * 2 ^ i)) * (2 * 2 ^ i) = x * (2 * 2 ^ i) - 1\"\n  proof -\n    have \"(x - 1 / (2 * 2 ^ i)) * (2 * 2 ^ i) = (x*(2 * 2 ^ i) - (1 / (2 * 2 ^ i))*(2 * 2 ^ i))\"\n      using left_diff_distrib by blast\n    also have \"... = x * (2 * 2 ^ i) - 1\"\n      by (simp)\n    finally show ?thesis .\n  qed\n  thus ?thesis\n    apply (simp add: nth_cont_def)\n    apply (cases \"\\<lfloor>x * (2 * 2 ^ i)\\<rfloor>\" rule: parity_cases)\n    apply (simp_all)\n  done\nqed\n\nlemma nth_cont_indep1:\n  assumes \"i < j\"\n  shows \"nth_cont (x - nth_cont x i) j = nth_cont x j\"\nproof -\n  have \"(x - (\\<lfloor>x * (2 ^ (i+1))\\<rfloor> mod 2) / (2 ^ (i+1))) * (2 ^ (j+1)) =\n        (x * 2 ^ (j+1)) - ((\\<lfloor>x * (2 ^ (i+1))\\<rfloor> mod 2) / (2 ^ (i+1)) * (2 ^ (j+1)))\"\n    using left_diff_distrib by blast\n  moreover have \"x * (2 * 2 ^ j) - 2 ^ j / 2 ^ i = x * (2 * 2 ^ j) - real ((2::nat) ^ (j - i))\"\n    by (simp add: assms order_less_imp_le power_diff power_one_over)\n       (metis assms le_less of_nat_numeral of_nat_power power_diff rel_simps(76))\n  moreover have \"\\<lfloor>x * (2 * 2 ^ j) - of_int ((2::nat) ^ (j - i))\\<rfloor> = \\<lfloor>x * (2 * 2 ^ j)\\<rfloor> - ((2::nat) ^ (j - i))\"\n    using floor_diff_of_int by blast\n  moreover have \"(2::int) ^ (j - i) mod 2 = 0\"\n    by (simp add: assms)\n(*\n  moreover have \"x * (2 * 2 ^ j) - 2 ^ j / 2 ^ i = 2^j * (2*x - 1/(2^i))\"\n    by (simp add: linordered_field_class.sign_simps(38))\n*)\n  ultimately show ?thesis\n  apply (simp add: nth_cont_def)\n  apply (cases \"\\<lfloor>x * (2 * 2 ^ i)\\<rfloor>\" rule: parity_cases)\n  apply (simp_all)\n    apply (metis minus_int_code(1) mod_diff_right_eq)\n  done\nqed\n\n(*\nlemma nth_cont_indep2:\n  assumes \"i > j\"\n  shows \"nth_cont (x - nth_cont x i) j = nth_cont x j\"\nproof -\n  have \"(x - (\\<lfloor>x * (2 ^ (i+1))\\<rfloor> mod 2) / (2 ^ (i+1))) * (2 ^ (j+1)) =\n        (x * 2 ^ (j+1)) - ((\\<lfloor>x * (2 ^ (i+1))\\<rfloor> mod 2) / (2 ^ (i+1)) * (2 ^ (j+1)))\"\n    using left_diff_distrib by blast\n\n  moreover have \"x * (2 * 2 ^ j) - 2 ^ j / 2 ^ i = 2^j * (2*x - 1/(2^i))\"\n    by (simp add: linordered_field_class.sign_simps(38))\n\n  moreover have \"i > 0\"\n    using assms by linarith\n\n  ultimately show ?thesis\n    apply (simp add: nth_cont_def)\n    apply (cases \"\\<lfloor>x * (2 * 2 ^ i)\\<rfloor>\" rule: parity_cases)\n    apply (simp_all)\n  sorry\nqed\n\nlemma nth_cont_indep:\n  assumes \"i \\<noteq> j\"\n  shows \"nth_cont (x - nth_cont x i) j = nth_cont x j\"\n  using assms nat_neq_iff nth_cont_indep1 nth_cont_indep2 by auto\n\nlemma sum_nth_cont_removed:\n  assumes \"finite A\" \"n \\<in> A\"\n  shows \"sum (nth_cont (x - nth_cont x n)) A = sum (nth_cont x) (A - {n})\"\nproof -\n  from assms have A: \"A = insert n (A - {n})\" by auto\n  moreover hence \"sum (nth_cont (x - nth_cont x n)) (insert n (A - {n})) = sum (nth_cont x) (A - {n})\"\n    apply (subst sum.insert)\n    apply (auto simp add: assms nth_cont_removed)\n    apply (rule sum.cong)\n    apply (auto simp add: nth_cont_indep)\n  done\n  ultimately show ?thesis\n    by simp\nqed\n*)\n\nlemma nth_cont_shift: \"nth_cont (2*x) n = (nth_cont x (n+1) * 2)\"\n  by (simp add: nth_cont_def mult.left_commute)\n\nlemma modulus_2_via_shift_lemma:\n  fixes x :: real\n  assumes \"0 \\<le> x\" \"x < 1\"\n  shows \"(\\<Sum> i < n. \\<lfloor>x * 2^(i+1)\\<rfloor> mod 2 * 2^(n-i)) = \\<lfloor>x * 2^(n+1)\\<rfloor> - \\<lfloor>x * 2^(n+1)\\<rfloor> mod 2\"\nproof (induct n)\n  case 0 with assms(1,2) show ?case\n    using mod_pos_pos_trivial by auto\nnext\n  case (Suc n) note hyp = this\n  have \"(\\<Sum>i<n. \\<lfloor>x * (2 ^ (i+1))\\<rfloor> mod 2 * 2 ^ (Suc n - i)) = (\\<Sum>i<n. \\<lfloor>x * (2 ^ (i+1))\\<rfloor> mod 2 * 2 ^ (n - i))*2\"\n    by (auto intro: sum.cong simp add: Suc_diff_le sum_distrib_right)\n  \\<comment> \\<open> This can be proven with reference to integer division and modulus \\<close>\n  moreover have \"\\<lfloor>x * (2 ^ (n+1))\\<rfloor> * 2 = \\<lfloor>x * (2 ^ (n+2))\\<rfloor> - \\<lfloor>x * (2 ^ (n+2))\\<rfloor> mod 2\"\n  proof -\n    have \"\\<lfloor>x * 2^(n+1)\\<rfloor> = \\<lfloor>x * 2^(n+2)\\<rfloor> div 2\"\n    proof -\n      \\<comment> \\<open> This result should maybe be extracted? It says how an integer division can\n           be expressed in binary more or less... \\<close>\n      have \"\\<lfloor>x * 2^(n+2)\\<rfloor> div 2 = \\<lfloor>(x * 2^(n+2)) / 2\\<rfloor>\"\n        by linarith\n      thus ?thesis\n        by (simp, subst mult.assoc[THEN sym], subst mult.commute, simp add: mult.assoc)\n    qed\n    hence \"(\\<lfloor>x * 2^(n+1)\\<rfloor> * 2) + \\<lfloor>x * (2 ^ (n+2))\\<rfloor> mod 2 = \\<lfloor>x * (2 ^ (n+2))\\<rfloor>\"\n      by simp\n    hence \"\\<lfloor>x * (2 ^ (n+1))\\<rfloor> * 2 = \\<lfloor>x * (2 ^ (n+2))\\<rfloor> - \\<lfloor>x * (2 ^ (n+2))\\<rfloor> mod 2\"\n      by simp\n    thus ?thesis\n      by (simp)\n  qed\n  ultimately show ?case\n    using hyp by simp\nqed\n\ntext \\<open> This theorem shows that the nth digit of a real number x in [0..1) can equivalently\n        be obtained either by shift;floor;modulus 2, or alternatively by subtracting the\n        approximation of the real number up to the nth digit, followed by a shift and floor.\n        It can be used to show that the recursive algorithm and functional specification\n        co-incide. \\<close>\n\ntheorem modulus_2_via_shift:\n  fixes x :: real\n  assumes \"0 \\<le> x\" \"x < 1\"\n  shows \"\\<lfloor>(x - (\\<Sum>i<n. nth_cont x i))*2^(n+1)\\<rfloor> = \\<lfloor>x * 2^(n+1)\\<rfloor> mod 2\"\nproof -\n  have \"\\<lfloor>(x - (\\<Sum>i<n. nth_cont x i))*2^(n+1)\\<rfloor> = \\<lfloor>(x*2^(n+1) - (\\<Sum>i<n. nth_cont x i)*2^(n+1))\\<rfloor>\"\n    by (simp add: left_diff_distrib)\n  moreover have \"(\\<Sum>i<n. nth_cont x i)*2^(n+1) = of_int (\\<Sum>i<n. (\\<lfloor>x * (2 ^ (i+1))\\<rfloor> mod 2) * (2 ^ (n-i)))\"\n  proof -\n    have \"(\\<Sum>i<n. nth_cont x i)*2^(n+1) = (\\<Sum>i<n. (\\<lfloor>x * (2 ^ (i+1))\\<rfloor> mod 2) / (2 ^ (i+1))) * (2 ^ (n+1))\"\n      by (simp add: nth_cont_def)\n    also have \"... = (\\<Sum>i<n. (\\<lfloor>x * (2 ^ (i+1))\\<rfloor> mod 2) / (2 ^ (i+1)) * (2 ^ (n+1)))\"\n      by (rule sum_distrib_right)\n    also have \"... = (\\<Sum>i<n. (of_int ((\\<lfloor>x * (2 ^ (i+1))\\<rfloor> mod 2) * (2 ^ (n-i)))))\"\n      by (rule sum.cong, auto simp add: power_diff)\n         (metis (no_types, opaque_lifting) le_less of_int_numeral of_int_power power_diff times_divide_eq_right zero_neq_numeral)\n    finally show ?thesis\n      by auto\n  qed\n  ultimately have \"\\<lfloor>(x - (\\<Sum>i<n. nth_cont x i))*2^(n+1)\\<rfloor> =\n                   \\<lfloor>x * 2^(n+1)\\<rfloor> - (\\<Sum>i<n. (\\<lfloor>x * (2 ^ (i+1))\\<rfloor> mod 2) * (2 ^ (n-i)))\"\n    by linarith\n  also from assms have \"... = \\<lfloor>x * 2 ^ (n + 1)\\<rfloor> - (\\<lfloor>x * 2 ^ (n + 1)\\<rfloor> - \\<lfloor>x * 2 ^ (n + 1)\\<rfloor> mod 2)\"\n    by (subst modulus_2_via_shift_lemma, simp_all)\n  finally show ?thesis\n    by linarith\nqed\n\nlemma binlist_as_nth_cont:\n  fixes x :: real\n  assumes \"0 \\<le> x\" \"x < 1\"\n  shows \"binlist (real_bits x n) = (\\<Sum>i<n+1. nth_cont x i)\"\nproof (induct n)\n  case 0 with assms show ?case\n  proof -\n    from assms have \"\\<lfloor>x * 2\\<rfloor> = 0 \\<or> \\<lfloor>x * 2\\<rfloor> = 1\"\n      by linarith\n    thus ?thesis\n      by (auto simp add: binlist_def nth_cont_def)\n  qed\nnext\n  case (Suc n) note hyp = this\n  thus ?case\n    using modulus_2_via_shift[of x \"Suc n\"] assms\n      by (simp add: rbit_def nth_cont_def)\n       (metis not_mod_2_eq_0_eq_1 of_int_0 of_int_1)\nqed\n\nlemma real_bits_rbseq:\n  assumes \"0 \\<le> x\" \"x < 1\" \"n \\<ge> i\"\n  shows \"real_bits x n ! i = rbseq x i\"\nusing assms proof (induct n arbitrary: i)\n  case 0 with assms show ?case\n    by (simp add: rbseq_def mod_pos_pos_trivial)\nnext\n  case (Suc n')\n  thus ?case\n    using modulus_2_via_shift[of x \"Suc n'\"] assms\n    by (auto simp add: nth_append rbit_def binlist_as_nth_cont rbseq_def)\nqed\n\nlemma real_bin_eq_rbseq:\n  \"\\<lbrakk> 0 \\<le> x; x < 1 \\<rbrakk> \\<Longrightarrow> real_bin x = rbseq x\"\n  by (auto simp add: real_bin_def real_bits_rbseq)\n\nlemma of_int_floor: \"\\<lbrakk> 0 \\<le> x; x < 1; of_int \\<lfloor>x\\<rfloor> = 0 \\<rbrakk> \\<Longrightarrow> \\<lfloor>x\\<rfloor> = 0\"\n  by (simp add: floor_unique)\n\nlemma binlist_approaching_range:\n  assumes \"0 \\<le> x\" \"x < 1\"\n  shows \"x - binlist (real_bits x n) \\<in> {0..<1/2^(n+1)}\"\nproof (induct n)\n  case 0\n  from assms have \"0 \\<le> x - binlist (real_bits x 0)\"\n  proof -\n    from assms have \"\\<lfloor>x * 2\\<rfloor> \\<in> {0,1}\"\n      by (auto, linarith)\n    with assms show ?thesis\n      by (auto simp add: binlist_def, linarith)\n  qed\n  moreover from assms have \"x - binlist (real_bits x 0) < 1/2^(0+1)\"\n    apply (simp add: binlist_def)\n    apply (case_tac \"of_int \\<lfloor>x * 2\\<rfloor> :: bit\")\n    apply (auto)\n    apply (metis bit.distinct(1) floor_less_iff linorder_neqE_linordered_idom mult.left_neutral not_le of_int_1 one_less_floor mult_le_cancel_iff1 zero_less_numeral)\n  done\n  ultimately show ?case\n    by auto\nnext\n  case (Suc n) note hyp = this\n  from hyp have blran: \"(x - binlist (real_bits x n)) * (4 * 2 ^ n) \\<in> {0..<2}\"\n    by (auto simp add: mult.commute mult.left_commute pos_less_divide_eq)\n  show ?case\n  proof (cases \"rbit x n (real_bits x n)\")\n    case zero\n    with hyp blran have \"(x - binlist (real_bits x n)) * (4 * 2 ^ n) < 1\"\n      apply (auto simp add: rbit_def pos_less_divide_eq)\n      apply (subgoal_tac \"\\<lfloor>(x - binlist (real_bits x n)) * (4 * 2 ^ n)\\<rfloor> = 0\")\n      apply linarith\n      apply (metis atLeastLessThan_iff bit.distinct(1) blran floor_less_one linorder_neqE_linordered_idom linorder_not_less of_int_1 of_int_floor one_less_floor)\n    done\n    with hyp zero show ?thesis\n      by (auto simp add: mult_imp_less_div_pos)\n  next\n    case one\n    with hyp blran have \"(x - binlist (real_bits x n)) * (4 * 2 ^ n) \\<ge> 1\"\n      by (auto simp add: rbit_def, metis atLeastLessThan_iff blran floor_less_iff linorder_neqE_linordered_idom not_le of_int_0 zero_less_floor zero_neq_one)\n    with hyp one show ?thesis\n      apply (auto)\n      apply (subst add.commute)\n      apply (simp add: le_diff_eq[THEN sym] pos_divide_le_eq)\n    done\n  qed\nqed\n\nlemma sum_binlist: \"sum (binseq (real_bin x)) {..n} = binlist (real_bits x n)\"\n  apply (unfold binlist_def binseq_def real_bits_length real_bin_def)\n  apply (rule sum.cong)\n  apply (auto)\n  apply (metis le_add_diff_inverse less_Suc_eq_le order_refl real_bits_plus)\n  apply (metis diff_Suc_1 less_imp_Suc_add less_or_eq_imp_le real_bits_plus)\ndone\n\nlemma sum_binseq_diff:\n  \"\\<lbrakk> 0 \\<le> x; x < 1 \\<rbrakk> \\<Longrightarrow> x - sum (binseq (real_bin x)) {..n} < 1/2^n\"\n  using binlist_approaching_range[of x n] sum_binlist by fastforce\n\nlemma sum_binseq_approx: \"\\<lbrakk> 0 \\<le> x; x < 1 \\<rbrakk> \\<Longrightarrow> sum (binseq (real_bin x)) {..n} \\<le> x\"\n  using binlist_approaching_range[of x n] by (simp add: sum_binlist)\n\nlemma sum_binseq_approx2:\n  assumes \"0 \\<le> x\" \"x < 1\"\n  shows \"sum (binseq (real_bin x)) {..<n} \\<le> x\"\nproof (cases n)\n  case 0 with assms show ?thesis by auto\nnext\n  case (Suc n')\n  with sum_binseq_approx[of x n'] assms\n  show ?thesis\n    by (simp add: lessThan_Suc_atMost)\nqed\n\nlemma binseq_approaches_real_bin:\n  assumes \"0 \\<le> x\" \"x < 1\"\n  shows \"(\\<lambda> n. \\<Sum> i<n. binseq (real_bin x) i) \\<longlonglongrightarrow> x\"\nproof (rule LIMSEQ_I, simp)\n  fix r :: real\n  assume \"0 < r\"\n  then obtain k where \"1/2^k < r\"\n    using real_bin_lower_bound[of r] by blast\n  moreover have \"x - sum (binseq (real_bin x)) {..k} < 1/2^k\"\n    by (simp add: assms(1) assms(2) sum_binseq_diff)\n  moreover have \"\\<And> m. m \\<ge> k+1 \\<Longrightarrow> sum (binseq (real_bin x)) {..<m} \\<ge> sum (binseq (real_bin x)) {..k}\"\n    by (auto intro: sum_mono2 simp add: binseq_pos)\n  ultimately have \"\\<And> m. m \\<ge> k+1 \\<Longrightarrow> x - sum (binseq (real_bin x)) {..<m} < r\"\n    by fastforce\n  thus \"\\<exists>no. \\<forall>n\\<ge>no. \\<bar>sum (binseq (real_bin x)) {..<n} - x\\<bar> < r\"\n    by (rule_tac x=\"k+1\" in exI, auto simp add: assms sum_binseq_approx2)\nqed\n\nlemma real_bin_inverse:\n  assumes \"0 \\<le> x\" \"x < 1\"\n  shows \"bin_real (real_bin x) = x\"\n  using assms\n  apply (simp add: bin_real_def)\n  apply (rule sym)\n  apply (rule sums_unique)\n  apply (simp add: sums_def binseq_approaches_real_bin)\ndone\n\nlemma real_bin_inj:\n  \"inj_on real_bin {0..<1}\"\n  by (metis atLeastLessThan_iff inj_onI real_bin_inverse)\n\nlemma sum_shift_plus_k:\n  fixes f :: \"nat \\<Rightarrow> real\"\n  shows \"(\\<Sum> i<n. f (i + k)) = (sum f {k..<n+k})\"\nproof -\n  have \"(\\<Sum> i<n. f (i + k)) = sum (\\<lambda> i . f (i + k)) {0..<n}\"\n    by (simp add: atLeast0LessThan)\n  thus ?thesis\n    by (simp, subst sum.shift_bounds_nat_ivl[THEN sym], auto)\nqed\n\nlemma binseq_upper: \"(\\<Sum> i. binseq x (i+k)) \\<le> 1/2^k\"\nproof (rule suminf_le_const)\n  show \"summable (\\<lambda>i. binseq x (i + k))\"\n    by (simp add: summable_iff_shift binseq_summable)\nnext\n  fix n\n  have \"(\\<Sum>i<n. binseq x (i + k)) \\<le> (\\<Sum>i<n. 1 / 2 ^ (i + (k + 1)))\"\n  proof (rule sum_mono, unfold binseq_def)\n    fix i\n    assume \"i \\<in> {..<n}\"\n    thus \"(of_bit (x (i + k)) / 2 ^ (i + k + 1) :: real) \\<le> 1 / 2 ^ (i + (k + 1))\"\n      by (cases \"x (i + k)\", auto)\n  qed\n  also have \"... \\<le> 1/2^k\"\n  proof -\n    have \"(\\<Sum>i<n. 1 / (2 :: real) ^ (i + (k + 1))) = ((\\<Sum>i<n+k+1. (1 / 2) ^ i) - (\\<Sum>i<k+1. (1 / 2) ^ i))\"\n      apply (subst sum_diff[THEN sym])\n      apply (simp)\n      apply (simp)\n      apply (subst sum_shift_plus_k)\n      apply (simp add: power_one_over)\n    done\n    also have \"... = 1 / 2 ^ k - 1 / 2 ^ (n + k)\"\n      apply (subst geometric_sum)\n      apply (simp)\n      apply (subst geometric_sum)\n      apply (simp)\n      apply (simp add: power_one_over)\n    done\n    finally show ?thesis\n      by (simp)\n  qed\n  finally show \"(\\<Sum>i<n. binseq x (i + k)) \\<le> 1 / 2 ^ k\" .\nqed\n\nlemma binseq_lower: \"(\\<Sum> i. binseq x (i+k)) \\<ge> 0\"\n  apply (rule suminf_nonneg)\n  apply (auto simp add: summable_iff_shift binseq_summable)\n  apply (simp add: binseq_def)\ndone\n\nlemma nonterminal_binseq_nonzero:\n  assumes \"nonterminal x\"\n  shows \"(\\<Sum> i. binseq x (i + k)) > 0\"\nproof -\n  from assms obtain i where i:\"x (i + k) = 1\"\n    by (auto simp add: terminal_def terminates_at_def, metis add.commute le_iff_add)\n  thus ?thesis\n  proof (rule_tac suminf_pos2[of _ i])\n    show \"summable (\\<lambda>i. binseq x (i + k))\"\n      by (simp add: summable_iff_shift binseq_summable)\n    show \"\\<And>n. 0 \\<le> binseq x (n + k)\"\n      by (simp add: binseq_pos)\n    from i show \"0 < binseq x (i + k)\"\n      by (simp add: binseq_def)\n  qed\nqed\n\nlemma list_neq_distinguish:\n  assumes \"xs \\<noteq> ys\" \"length xs = length ys\"\n  shows \"\\<exists> k<length xs. (\\<forall> i < k. xs!i = ys!i) \\<and> xs!k \\<noteq> ys!k\"\nusing assms proof (induct xs arbitrary: ys)\n  case Nil thus ?case by auto\nnext\n  case (Cons x xs')\n  note hyps = this\n  then obtain y ys' where ys: \"ys = y # ys'\"\n    by (metis length_0_conv neq_Nil_conv)\n  thus ?case\n  proof (cases \"x = y\")\n    case False with hyps ys show ?thesis\n      by (rule_tac x=\"0\" in exI, simp)\n  next\n    case True\n    with hyps ys have \"xs' \\<noteq> ys'\"\n      by (auto)\n    moreover from hyps ys have \"length xs' = length ys'\"\n      by (auto)\n      thm hyps\n    ultimately obtain k where \"k<length xs'\" \"\\<forall>i<k. xs' ! i = ys' ! i\" \"xs' ! k \\<noteq> ys' ! k\"\n      using hyps by auto\n    thus ?thesis\n      using True ys less_Suc_eq_0_disj by (rule_tac x=\"Suc k\" in exI, auto)\n  qed\nqed\n\nlemma seq_neq_distinguish:\n  fixes f :: \"nat \\<Rightarrow> 'b\"\n  assumes \"f \\<noteq> g\"\n  shows \"\\<exists> k. (\\<forall> i < k. f(i) = g(i)) \\<and> f(k) \\<noteq> g(k)\"\nproof -\n  from assms obtain k' where k': \"f(k') \\<noteq> g(k')\"\n    by auto\n  let ?xs = \"map f [0..<k'+1]\"\n  let ?ys = \"map g [0..<k'+1]\"\n  from k' obtain k where k: \"k < k'+1\" \"(\\<forall> i < k. ?xs!i = ?ys!i)\" \"?xs!k \\<noteq> ?ys!k\"\n    using list_neq_distinguish[of \"?xs\" \"?ys\"] by auto\n  have \"(\\<forall>i<k. f i = g i)\"\n    by (auto, metis (no_types, lifting) add.left_neutral add_lessD1 diff_zero k(1) k(2) less_imp_add_positive nth_map_upt)\n  moreover from k(3) have \"f k \\<noteq> g k\"\n    by (metis add.left_neutral diff_zero k(1) k(3) nth_map_upt)\n  ultimately show ?thesis\n    by (auto)\nqed\n\nlemma bin_real_nonterminal_inj_aux:\n  assumes \"nonterminal x\" \"nonterminal y\" \"x \\<noteq> y\"\n  shows \"bin_real x \\<noteq> bin_real y\"\nproof -\n  from assms(3) obtain k where k: \"\\<forall> i < k. x(i) = y(i)\" \"x(k) \\<noteq> y(k)\"\n    using seq_neq_distinguish by blast\n  have \"bin_real x =\n         (\\<Sum>i<k. binseq x i) + of_bit (x k) / 2 ^(k+1) + (\\<Sum>i. binseq x (i+(k+1)))\"\n    by (simp add: bin_real_def suminf_split_initial_segment[of _ \"k+1\"] binseq_summable)\n       (simp add: binseq_def)\n  moreover\n  have \"bin_real y =\n         (\\<Sum>i<k. binseq y i) + of_bit (y k) / 2 ^(k+1) + (\\<Sum>i. binseq y (i+(k+1)))\"\n    by (simp add: bin_real_def suminf_split_initial_segment[of _ \"k+1\"] binseq_summable)\n       (simp add: binseq_def)\n  moreover\n  from k(1) have \"(\\<Sum>i<k. binseq x i) = (\\<Sum>i<k. binseq y i)\"\n    by (auto simp add: binseq_def)\n  moreover\n  have \"of_bit (x k) / 2 ^(k+1) + (\\<Sum>i. binseq x (i+(k+1))) \\<noteq>\n        of_bit (y k) / 2 ^(k+1) + (\\<Sum>i. binseq y (i+(k+1)))\"\n  proof (cases \"x k\")\n    case one\n    moreover then have y:\"y k = 0\"\n      using k(2) by auto\n    moreover have \"(\\<Sum>i. binseq y (i + (k + 1))) \\<le> 1/2^(k+1)\"\n      by (rule binseq_upper)\n    moreover from assms(1) have \"(\\<Sum>i. binseq x (i + (k + 1))) > 0\"\n      by (rule nonterminal_binseq_nonzero)\n    ultimately have \"1 / 2^(k+1) + (\\<Sum>i. binseq x (i+(k+1))) > (\\<Sum>i. binseq y (i+(k+1)))\"\n      by simp\n    with one y show ?thesis\n      by simp\n  next\n    case zero\n    moreover then have y:\"y k = 1\"\n      using k(2) by auto\n    moreover have \"(\\<Sum>i. binseq x (i + (k + 1))) \\<le> 1/2^(k+1)\"\n      by (rule binseq_upper)\n    moreover from assms(2) have \"(\\<Sum>i. binseq y (i + (k + 1))) > 0\"\n      by (rule nonterminal_binseq_nonzero)\n    ultimately have \"1 / 2^(k+1) + (\\<Sum>i. binseq y (i+(k+1))) > (\\<Sum>i. binseq x (i+(k+1)))\"\n      by simp\n    with zero y show ?thesis\n      by simp\n  qed\n\n  ultimately show ?thesis\n    by auto\nqed\n\ntext \\<open> There is an injection from non-terminal infinite bit sequences to the real numbers \\<close>\n\nlemma bin_real_inj: \"inj_on bin_real NonTermBitSeqs\"\n  using bin_real_nonterminal_inj_aux by (blast intro: inj_onI)\n\nlemma bin_real_terminal_def:\n  assumes \"terminal x\"\n  obtains k where \"bin_real x = (\\<Sum>i<k. binseq x i)\"\nproof -\n  from assms obtain k where \"\\<forall>i\\<ge>k. x i = 0\"\n    by (auto simp add: terminal_def terminates_at_def)\n  hence \"bin_real x = (\\<Sum>i<k. binseq x i)\"\n    unfolding bin_real_def\n    by (subst suminf_finite[of \"{..<k}\"], auto simp add: binseq_def)\n  thus ?thesis\n    using that by blast\nqed\n\nlemma sum_int: \"\\<lbrakk> finite A; \\<forall> i. f i \\<in> \\<int> \\<rbrakk> \\<Longrightarrow> sum f A \\<in> \\<int>\"\n  by (induct rule: finite_induct, simp_all)\n\nlemma bin_real_terminal_dyadic:\n  assumes \"terminal x\"\n  shows \"dyadic (bin_real x)\"\nproof -\n  from assms obtain k where \"bin_real x = (\\<Sum>i<k. binseq x i)\"\n    using bin_real_terminal_def by blast\n  also have \"... = (\\<Sum>i<k. (binseq x i * 2^k)) / 2^k\"\n    by (simp add: sum_divide_distrib)\n  also have \"... = (\\<Sum>i<k. of_bit (x i) * 2 ^ (k - (i+1))) / 2 ^ k\"\n  proof -\n    have \"\\<And>i. i \\<in> {..<k} \\<Longrightarrow> (of_bit (x i) :: real) / 2^(i+1) * 2^k = of_bit (x i) * 2^(k-(i+1))\"\n      by (simp add: power_diff)\n    hence \"(\\<Sum>i<k. (binseq x i * 2^k)) = (\\<Sum>i<k. of_bit (x i) * 2 ^ (k - (i+1)))\"\n      by (auto intro: sum.cong simp add: binseq_def)\n    thus ?thesis by simp\n  qed\n  finally show ?thesis\n  proof (simp)\n    have \"(\\<Sum>i<k. of_bit (x i) * 2 ^ (k - (i + 1))) \\<in> \\<int>\"\n      by (auto intro!: sum_int)\n    thus \"dyadic ((\\<Sum>i\\<in>{..<k} \\<inter> {i. x i = 1}. 2 ^ (k - Suc i)) / 2 ^ k)\"\n      by (auto simp add: dyadic_def)\n  qed\nqed\n\nlemma terminal_rbseq_drat:\n  \"x \\<in> {0<..<1} \\<Longrightarrow> terminal (rbseq (of_drat x))\"\nproof (erule drat_0_1_induct, simp add: rbseq_def terminal_def terminates_at_def)\n  fix a :: int and b :: nat\n  assume coprime: \"even a \\<longrightarrow> b = 0\"\n  have \"\\<And> j. j \\<ge> b \\<Longrightarrow> of_int (\\<lfloor>real_of_int a * (2 * 2 ^ j) / 2 ^ b\\<rfloor> mod 2) = 0\"\n  proof -\n    fix j\n    assume \"j \\<ge> b\"\n    then have \"real_of_int a * (2 * 2 ^ j) / 2 ^ b = real_of_int a * (2 * 2 ^ (j-b))\"\n      by (simp add: power_diff)\n    moreover have \"real_of_int a * (2 * 2 ^ (j-b)) \\<in> \\<int>\"\n      by simp\n    moreover hence \"\\<lfloor>real_of_int a * (2 * 2 ^ (j-b))\\<rfloor> mod 2 = (2 * \\<lfloor>real_of_int a * 2 ^ (j - b)\\<rfloor>) mod 2\"\n      by (metis (no_types, opaque_lifting) floor_of_int mult.left_commute of_int_mult of_int_numeral of_int_power)\n    ultimately show \"of_int (\\<lfloor>real_of_int a * (2 * 2 ^ j) / 2 ^ b\\<rfloor> mod 2) = 0\"\n      by simp\n  qed\n  with coprime show \" \\<exists>i. \\<forall>j\\<ge>i. of_int (\\<lfloor>of_drat (DFract a b) * ((2::real) * 2 ^ j)\\<rfloor> mod 2) = 0\"\n    by (rule_tac x=\"b\" in exI, auto simp add:of_drat_DFract)\nqed\n\nlemma real_bin_dyadic_terminal:\n  assumes \"0 \\<le> x\" \"x < 1\" \"x \\<in> \\<rat>\\<^sub>D\"\n  shows \"terminal (real_bin x)\"\nproof (cases \"x = 0\")\n  case True thus ?thesis\n    by (simp add: real_bin_eq_rbseq terminal_def terminates_at_def rbseq_def)\nnext\n  case False\n  from assms obtain n where n:\"x = of_drat n\"\n     by (erule_tac drat_cases, auto)\n  with assms False have nr: \"n \\<in> {0<..<1}\"\n    using of_drat_0_1 by force\n  show ?thesis\n    apply (subst real_bin_eq_rbseq)\n    apply (simp_all add: assms)\n    apply (simp add: n nr)\n    apply (subst terminal_rbseq_drat)\n    apply (simp_all only: nr)\n  done\nqed\n\nlemma bin_real_terminates_binlist:\n  assumes \"terminates_at x k\"\n  shows \"bin_real x = binlist (map x [0..<k])\"\nproof -\n  from assms have \"(\\<Sum>n. binseq x (n + k)) = 0\"\n    by (simp add: suminf_eq_zero_iff binseq_summable summable_iff_shift binseq_def terminates_at_def)\n  thus ?thesis\n    apply (simp add: bin_real_def binlist_def)\n    apply (subst suminf_split_initial_segment[of _ k])\n    apply (simp add: binseq_summable)\n    apply (simp add: binseq_def)\n  done\nqed\n\ndefinition termseq_list :: \"(nat \\<Rightarrow> ('a::zero)) \\<Rightarrow> 'a list\" where\n\"termseq_list x = map x [0..<LEAST k. terminates_at x k]\"\n\ndefinition list_termseq :: \"'a list \\<Rightarrow> (nat \\<Rightarrow> ('a::zero))\" where\n\"list_termseq xs = (\\<lambda> i. if (i < length xs) then xs!i else 0)\"\n\ndefinition \"TermLists = {xs. xs = [] \\<or> (xs \\<noteq> [] \\<and> last xs \\<noteq> 0)}\"\n\nlemma TermLists_terminates_at:\n  \"xs \\<in> TermLists \\<Longrightarrow> terminates_at (list_termseq xs) k \\<longleftrightarrow> k \\<ge> length xs\"\n  apply (auto simp add: list_termseq_def terminates_at_def)\n  apply (auto simp add: TermLists_def)\n  using last_conv_nth not_less_eq_eq apply force\ndone\n\nlemma terminal_list_termseq: \"terminal (list_termseq xs)\"\n  apply (auto simp add: list_termseq_def terminal_def terminates_at_def)\n  using not_le apply blast\ndone\n\nlemma Least_terminates_at_list: \"xs \\<in> TermLists \\<Longrightarrow> (LEAST k. terminates_at (list_termseq xs) k) = length xs\"\n  by (auto simp add: TermLists_terminates_at simp add: Least_equality)\n\nlemma list_termseq_inverse:\n  assumes \"xs \\<in> TermLists\"\n  shows \"termseq_list (list_termseq xs) = xs\"\nproof -\n  have \"xs = map (\\<lambda> i. xs ! i) [0..<length xs]\"\n    by (simp add: map_nth)\n  also have \"... = map (list_termseq xs) [0..<LEAST k. terminates_at (list_termseq xs) k]\"\n  proof -\n    have \"\\<And>x. x < length xs \\<Longrightarrow> xs ! x = list_termseq xs x\"\n      by (simp add: list_termseq_def)\n    thus ?thesis\n      by (auto simp add: Least_terminates_at_list assms)\n  qed\n  finally show ?thesis\n    by (auto simp add: TermLists_def list_termseq_def termseq_list_def terminates_at_def)\nqed\n\nlemma termseq_list_inverse:\n  assumes \"x \\<in> TermSeqs\"\n  shows \"list_termseq (termseq_list x) = x\"\n  apply (rule ext)\n  apply (auto simp add: list_termseq_def termseq_list_def)\n  apply (metis (mono_tags, lifting) LeastI_ex assms le_less_linear mem_Collect_eq terminal_def terminates_at_def)\ndone\n\nlemma termseq_list_inj:\n  \"inj_on termseq_list TermSeqs\"\n  by (metis inj_onI termseq_list_inverse)\n\nlemma lenth_termseq_list:\n  \"length (termseq_list x) = (LEAST k. terminates_at x k)\"\n  by (simp add: termseq_list_def)\n\nlemma terminal_TermLists:\n  assumes \"terminal x\"\n  shows \"termseq_list x \\<in> TermLists\"\nproof -\n  let ?kx = \"LEAST k. terminates_at x k\"\n  have tx: \"terminates_at x ?kx\"\n    by (metis LeastI assms terminal_def)\n  moreover have mt: \"\\<And> k. terminates_at x k \\<Longrightarrow> ?kx \\<le> k\"\n    by (auto intro: wellorder_Least_lemma)\n  ultimately show ?thesis\n  proof (auto simp add: TermLists_def)\n    assume as: \"termseq_list x \\<noteq> []\" \"last (termseq_list x) = 0\"\n    hence kx_nz: \"?kx > 0\"\n      by (metis length_greater_0_conv lenth_termseq_list)\n    hence \"x (?kx - 1) \\<noteq> 0\"\n    proof -\n      from kx_nz mt have nt_kxs: \"\\<not> terminates_at x (?kx - 1)\"\n        by (metis One_nat_def Suc_n_not_le_n diff_Suc_1 gr0_implies_Suc)\n      show ?thesis\n      proof\n        assume \"x (?kx - 1) = 0\"\n        moreover from tx have \"\\<forall>j\\<ge>?kx. x j = 0\"\n          by (simp only: terminates_at_def)\n        ultimately have \"\\<forall>j\\<ge>?kx-1. x j = 0\"\n          by (auto, metis Suc_diff_Suc diff_zero kx_nz le_antisym not_less_eq_eq)\n        hence \"terminates_at x (?kx - 1)\"\n          by (simp only: terminates_at_def)\n        with nt_kxs show False by simp\n      qed\n    qed\n\n    with as show False\n      by (simp add: termseq_list_def last_map)\n  qed\nqed\n\nlemma termseq_list_surj:\n  \"termseq_list ` TermSeqs = TermLists\"\n  apply (auto simp add: terminal_TermLists)\n  apply (auto simp add: image_Collect)\n  apply (rule_tac x=\"list_termseq x\" in exI)\n  apply (simp add: list_termseq_inverse terminal_list_termseq)\ndone\n\nlemma termseq_list_bij:\n  \"bij_betw termseq_list TermSeqs TermLists\"\n  by (simp add: bij_betw_def termseq_list_inj termseq_list_surj)\n\nthm infinite_iff_countable_subset\n\nlemma infinite_TermBitLists:\n  \"infinite (TermLists :: bit list set)\"\nproof -\n  let ?f = \"(\\<lambda> i. replicate i 1) :: nat \\<Rightarrow> bit list\"\n  have \"inj ?f\"\n    by (meson injI replicate_eq_replicate)\n  moreover have \"range ?f \\<subseteq> TermLists\"\n    by (auto simp add: TermLists_def)\n  ultimately show ?thesis\n    by (auto simp add: infinite_iff_countable_subset)\nqed\n\ninstance bit :: countable\n  apply (intro_classes)\n  apply (rule_tac x=\"of_bit\" in exI)\n  apply (rule injI)\n  apply (rename_tac x y)\n  apply (case_tac x; case_tac y)\n  apply (simp_all)\ndone\n\nlemma countable_TermBitLists:\n  \"countable (TermLists :: bit list set)\"\n  by (fact countableI_type)\n\nlemma card_of_TermBitLists:\n  \"|TermLists :: bit list set| =o |UNIV :: nat set|\"\n  apply (subst card_of_ordIso[THEN sym])\n  using countable_TermBitLists infinite_TermBitLists to_nat_on_infinite apply blast\ndone\n\nlemma card_of_TermBitSeqs:\n  \"|TermBitSeqs| =o |TermLists :: bit list set|\"\n  apply (subst card_of_ordIso[THEN sym])\nusing termseq_list_bij by blast\n\nlemma card_less_TermBitSeqs_BitSeqs: \"|TermBitSeqs| <o |BitSeqs|\"\nproof -\n  have \"|TermBitSeqs| =o |UNIV :: nat set|\"\n    using card_of_TermBitLists card_of_TermBitSeqs ordIso_transitive by blast\n  moreover have \"|UNIV :: nat set set| =o |BitSeqs|\"\n    by (simp add: card_of_bit_seq ordIso_symmetric)\n  moreover have \"|UNIV :: nat set| <o |UNIV :: nat set set|\"\n    using card_of_set_type by blast\n  ultimately show ?thesis\n    apply (rule_tac ordLess_ordIso_trans)\n    apply (rule_tac ordIso_ordLess_trans)\n    apply (assumption)\n    apply (rule card_of_set_type)\n    apply auto\n  done\nqed\n\nlemma infinite_BitSeqs:\n  \"infinite BitSeqs\"\n  using bij_betw_finite bij_bits_to_nats infinite_UNIV by blast\n\nlemma card_eq_NonTermBitSeqs_BitSeqs: \"|NonTermBitSeqs| =o |BitSeqs|\"\nproof -\n  have \"|BitSeqs - TermBitSeqs| =o |BitSeqs|\"\n    apply (rule card_of_Un_diff_infinite)\n    apply (simp_all add: infinite_BitSeqs card_less_TermBitSeqs_BitSeqs)\n  done\n  moreover have \"BitSeqs - TermBitSeqs = NonTermBitSeqs\"\n    by (auto)\n  ultimately show ?thesis\n    by (simp)\nqed\n\nlemma card_le_NonTermBitSeqs_Reals: \"|NonTermBitSeqs| \\<le>o |UNIV :: real set|\"\n  using bin_real_inj card_of_ordLeqI by auto\n\nlemma card_le_BitSeqs_Reals: \"|BitSeqs| \\<le>o |UNIV :: real set|\"\n  using card_eq_NonTermBitSeqs_BitSeqs card_le_NonTermBitSeqs_Reals ordIso_ordLess_trans ordIso_symmetric ordIso_transitive ordLeq_iff_ordLess_or_ordIso by blast\n\nlemma card_le_PNats_Reals: \"|UNIV :: nat set set| \\<le>o |UNIV :: real set|\"\n  using card_le_BitSeqs_Reals card_of_bit_seq ordIso_iff_ordLeq ordLeq_transitive by blast\n\ndefinition dcut :: \"real \\<Rightarrow> rat set\" where\n\"dcut r = {q. real_of_rat q < r}\"\n\nlemma dedekind_cut_lemma:\n  assumes \"r1 < r2\"\n  shows \"dcut r1 \\<noteq> dcut r2\"\nproof -\n  from assms obtain q :: rat where \"r1 < of_rat q\" and \"of_rat q < r2\"\n    using of_rat_dense by auto\n  hence \"q \\<notin> dcut r1\" \"q \\<in> dcut r2\"\n    by (auto simp add: dcut_def)\n  thus ?thesis\n    by auto\nqed\n\nlemma dedekind_cut_inj:\n  \"inj dcut\"\n  by (simp add: dedekind_cut_lemma linorder_injI)\n\nlemma real_nat_set: \"\\<exists> f :: real \\<Rightarrow> nat set. inj f\"\n  apply (rule_tac x=\"\\<lambda> n. to_nat ` dcut n\" in exI)\n  apply (simp add: dedekind_cut_lemma inj_image_eq_iff linorder_injI)\ndone\n\nlemma card_le_Reals_PNats: \"|UNIV :: real set| \\<le>o |UNIV :: nat set set|\"\nproof -\n  obtain f :: \"real \\<Rightarrow> nat set\" where \"inj f\"\n    using real_nat_set by blast\n  thus ?thesis\n    by (rule card_of_ordLeqI, auto)\nqed\n\nlemma card_eq_Reals_PNats: \"|UNIV :: real set| =o |UNIV :: nat set set|\"\n  by (simp add: card_le_PNats_Reals card_le_Reals_PNats ordIso_iff_ordLeq)\n\ndefinition real_nats_bij :: \"real \\<Rightarrow> nat set\" where\n\"real_nats_bij = (SOME f. bij f)\"\n\nlemma real_nats_bij: \"bij real_nats_bij\"\nproof -\n  obtain f :: \"real \\<Rightarrow> nat set\" where \"bij f\"\n    using card_of_ordIso[of \"UNIV :: real set\" \"UNIV :: nat set set\"] card_eq_Reals_PNats\n    by (auto)\n  thus ?thesis\n    by (simp add: real_nats_bij_def, metis someI_ex)\nqed\n\nlemma \"|BitSeqs| =o |UNIV :: bit set| ^c |UNIV :: nat set|\"\n  by (simp add: card_of_Func_UNIV_UNIV cexp_def ordIso_symmetric)\n\ndeclare [[linarith_split_limit=10]]\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/Real_Bit.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.855851143290548, "lm_q2_score": 0.8615382094310357, "lm_q1q2_score": 0.7373484615300434}}
{"text": "(*\n  File:     Finite_Fourier_Series.thy\n  Authors:  Rodrigo Raya, EPFL; Manuel Eberl, TUM\n\n  Existence and uniqueness of finite Fourier series for periodic arithmetic functions\n*)\nsection \\<open>Finite Fourier series\\<close>\ntheory Finite_Fourier_Series\nimports \n  Polynomial_Interpolation.Lagrange_Interpolation\n  Complex_Roots_Of_Unity\nbegin\n\nsubsection \\<open>Auxiliary facts\\<close>\n\nlemma lagrange_exists:\n  assumes d: \"distinct (map fst zs_ws)\"\n  defines e: \"(p :: complex poly) \\<equiv> lagrange_interpolation_poly zs_ws\"\n  shows \"degree p \\<le> (length zs_ws)-1\"\n        \"(\\<forall>x y. (x,y) \\<in> set zs_ws \\<longrightarrow> poly p x = y)\" \nproof -\n  from e show \"degree p \\<le> (length zs_ws - 1)\"\n    using degree_lagrange_interpolation_poly by auto\n  from e d have \n    \"poly p x = y\" if \"(x,y) \\<in> set zs_ws\" for x y \n    using that lagrange_interpolation_poly by auto\n  then show \"(\\<forall>x y. (x,y) \\<in> set zs_ws \\<longrightarrow> poly p x = y)\" \n    by auto\nqed\n\nlemma lagrange_unique:\n  assumes o: \"length zs_ws > 0\" (* implicit in theorem *)\n  assumes d: \"distinct (map fst zs_ws)\"\n  assumes 1: \"degree (p1 :: complex poly) \\<le> (length zs_ws)-1 \\<and>\n               (\\<forall>x y. (x,y) \\<in> set zs_ws \\<longrightarrow> poly p1 x = y)\"\n  assumes 2: \"degree (p2 :: complex poly) \\<le> (length zs_ws)-1 \\<and>\n               (\\<forall>x y. (x,y) \\<in> set zs_ws \\<longrightarrow> poly p2 x = y)\"\n  shows \"p1 = p2\" \nproof (cases \"p1 - p2 = 0\")\n  case True then show ?thesis by simp\nnext\n  case False\n    have \"poly (p1-p2) x = 0\" if \"x \\<in> set (map fst zs_ws)\" for x\n      using 1 2 that by (auto simp add: field_simps)\n    from this d have 3: \"card {x. poly (p1-p2) x = 0} \\<ge> length zs_ws\"\n    proof (induction zs_ws)\n      case Nil then show ?case by simp\n    next\n      case (Cons z_w zs_ws)\n      from  False poly_roots_finite\n      have f: \"finite {x. poly (p1 - p2) x = 0}\" by blast\n      from Cons have \"set (map fst (z_w # zs_ws)) \\<subseteq> {x. poly (p1 - p2) x = 0}\"\n        by auto\n      then have i: \"card (set (map fst (z_w # zs_ws))) \\<le> card {x. poly (p1 - p2) x = 0}\" \n        using card_mono f by blast\n      have \"length (z_w # zs_ws) \\<le> card (set (map fst (z_w # zs_ws)))\"\n        using Cons.prems(2) distinct_card by fastforce \n      from this i show ?case by simp \n    qed\n    from 1 2 have 4: \"degree (p1 - p2) \\<le> (length zs_ws)-1\" \n      using degree_diff_le by blast\n \n    have \"p1 - p2 = 0\"  \n    proof (rule ccontr)\n      assume \"p1 - p2 \\<noteq> 0\"\n      then have \"card {x. poly (p1-p2) x = 0} \\<le> degree (p1-p2)\"\n        using poly_roots_degree by blast\n      then have \"card {x. poly (p1-p2) x = 0} \\<le> (length zs_ws)-1\"\n        using 4 by auto\n      then show \"False\" using 3 o by linarith\n    qed\n    then show ?thesis by simp \nqed\n\ntext \\<open>Theorem 8.2\\<close>\ncorollary lagrange:\n  assumes \"length zs_ws > 0\" \"distinct (map fst zs_ws)\"\n  shows \"(\\<exists>! (p :: complex poly).\n              degree p \\<le> length zs_ws - 1 \\<and>\n              (\\<forall>x y. (x, y) \\<in> set zs_ws \\<longrightarrow> poly p x = y))\"\n  using assms lagrange_exists lagrange_unique by blast\n\nlemma poly_altdef':\n assumes gr: \"k \\<ge> degree p\"  \n shows \"poly p (z::complex) = (\\<Sum>i\\<le>k. coeff p i * z ^ i)\"\nproof -\n  {fix z\n  have 1: \"poly p z = (\\<Sum>i\\<le>degree p. coeff p i * z ^ i)\"\n    using poly_altdef[of p z] by simp\n  have \"poly p z = (\\<Sum>i\\<le>k. coeff p i * z ^ i)\" \n    using gr\n  proof (induction k)\n    case 0 then show ?case by (simp add: poly_altdef) \n  next\n    case (Suc k) \n    then show ?case\n      using \"1\" le_degree not_less_eq_eq by fastforce\n  qed}  \n  then show ?thesis using gr by blast \nqed\n\n\nsubsection \\<open>Definition and uniqueness\\<close>\n\ndefinition finite_fourier_poly :: \"complex list \\<Rightarrow> complex poly\" where\n  \"finite_fourier_poly ws =\n    (let k = length ws\n      in  poly_of_list [1 / k * (\\<Sum>m<k. ws ! m * unity_root k (-n*m)). n \\<leftarrow> [0..<k]])\"\n\nlemma degree_poly_of_list_le: \"degree (poly_of_list ws) \\<le> length ws - 1\"\n  by (intro degree_le) (auto simp: nth_default_def)\n\nlemma degree_finite_fourier_poly: \"degree (finite_fourier_poly ws) \\<le> length ws - 1\"\n  unfolding finite_fourier_poly_def\nproof (subst Let_def)\n  let ?unrolled_list = \"\n       (map (\\<lambda>n. complex_of_real (1 / real (length ws)) *\n                  (\\<Sum>m<length ws.\n                      ws ! m *\n                      unity_root (length ws) (- int n * int m)))\n         [0..<length ws])\"\n  have \"degree (poly_of_list ?unrolled_list) \\<le> length ?unrolled_list - 1\"   \n    by (rule degree_poly_of_list_le)\n  also have \"\\<dots> = length [0..<length ws] - 1\"\n    using length_map by auto\n  also have \"\\<dots> = length ws - 1\" by auto\n  finally show \"degree (poly_of_list ?unrolled_list) \\<le> length ws - 1\" by blast\nqed\n\nlemma coeff_finite_fourier_poly:\n  assumes \"n < length ws\"\n  defines \"k \\<equiv> length ws\"\n  shows \"coeff (finite_fourier_poly ws) n = \n         (1/k) * (\\<Sum>m < k. ws ! m * unity_root k (-n*m))\"\n  using assms degree_finite_fourier_poly\n  by (auto simp: Let_def nth_default_def finite_fourier_poly_def)\n\nlemma poly_finite_fourier_poly:\n  fixes m :: int and ws\n  defines \"k \\<equiv> length ws\"\n  assumes \"m \\<in> {0..<k}\"\n  assumes \"m < length ws\"\n  shows \"poly (finite_fourier_poly ws) (unity_root k m) = ws ! (nat m)\"\nproof -\n  have \"k > 0\" using assms by auto\n\n  have distr: \"\n   (\\<Sum>j<length ws. ws ! j * unity_root k (-i*j))*(unity_root k (m*i)) = \n   (\\<Sum>j<length ws. ws ! j * unity_root k (-i*j)*(unity_root k (m*i)))\"\n   for i\n  using sum_distrib_right[of \"\\<lambda>j. ws ! j * unity_root k (-i*j)\" \n                            \"{..<k}\" \"(unity_root k (m*i))\"] \n  using k_def by blast\n\n  {fix j i :: nat\n   have \"unity_root k (-i*j)*(unity_root k (m*i)) = unity_root k (-i*j+m*i)\"\n     by (simp add: unity_root_diff unity_root_uminus field_simps)\n   also have \"\\<dots> = unity_root k (i*(m-j))\"\n     by (simp add: algebra_simps)\n   finally have \"unity_root k (-i*j)*(unity_root k (m*i)) = unity_root k (i*(m-j))\"\n     by simp\n   then have \"ws ! j * unity_root k (-i*j)*(unity_root k (m*i)) = \n              ws ! j * unity_root k (i*(m-j))\"\n     by auto\n } note prod = this\n\n have zeros: \n   \"(unity_root_sum k (m-j) \\<noteq> 0 \\<longleftrightarrow> m = j)\n     \" if \"j \\<ge> 0 \\<and> j < k\"  for j\n   using k_def that assms unity_root_sum_nonzero_iff[of _ \"m-j\"] by simp\n  then have sum_eq:\n    \"(\\<Sum>j\\<le>k-1. ws ! j * unity_root_sum k (m-j)) = \n          (\\<Sum>j\\<in>{nat m}.  ws ! j * unity_root_sum k (m-j))\"\n    using assms(2) by (intro sum.mono_neutral_right,auto)\n\n  have \"poly (finite_fourier_poly ws) (unity_root k m) = \n        (\\<Sum>i\\<le>k-1. coeff (finite_fourier_poly ws) i * (unity_root k m) ^ i)\"\n    using degree_finite_fourier_poly[of ws] k_def\n          poly_altdef'[of \"finite_fourier_poly ws\" \"k-1\" \"unity_root k m\"] by blast\n  also have \"\\<dots> = (\\<Sum>i<k. coeff (finite_fourier_poly ws) i * (unity_root k m) ^ i)\"\n    using assms(2) by (intro sum.cong) auto\n  also have \"\\<dots> = (\\<Sum>i<k. 1 / k *\n    (\\<Sum>j<k. ws ! j * unity_root k (-i*j)) * (unity_root k m) ^ i)\"\n    using coeff_finite_fourier_poly[of _ ws] k_def by auto\n  also have \"\\<dots> = (\\<Sum>i<k. 1 / k *\n    (\\<Sum>j<k. ws ! j * unity_root k (-i*j))*(unity_root k (m*i)))\"\n    using unity_root_pow by auto   \n  also have \"\\<dots> = (\\<Sum>i<k. 1 / k *\n    (\\<Sum>j<k. ws ! j * unity_root k (-i*j)*(unity_root k (m*i))))\"\n    using distr k_def by simp\n  also have \"\\<dots> = (\\<Sum>i<k. 1 / k * \n    (\\<Sum>j<k. ws ! j * unity_root k (i*(m-j))))\"\n    using prod by presburger\n  also have \"\\<dots> = 1 / k * (\\<Sum>i<k.  \n    (\\<Sum>j<k. ws ! j * unity_root k (i*(m-j))))\"\n    by (simp add: sum_distrib_left)\n  also have \"\\<dots> = 1 / k * (\\<Sum>j<k.  \n    (\\<Sum>i<k. ws ! j * unity_root k (i*(m-j))))\"\n    using sum.swap by fastforce\n  also have \"\\<dots> = 1 / k * (\\<Sum>j<k. ws ! j * (\\<Sum>i<k. unity_root k (i*(m-j))))\"\n    by (simp add: vector_space_over_itself.scale_sum_right)\n  also have \"\\<dots> = 1 / k * (\\<Sum>j<k. ws ! j * unity_root_sum k (m-j))\"\n    unfolding unity_root_sum_def by (simp add: algebra_simps)\n  also have \"(\\<Sum>j<k. ws ! j * unity_root_sum k (m-j)) = (\\<Sum>j\\<le>k-1. ws ! j * unity_root_sum k (m-j))\"\n    using \\<open>k > 0\\<close> by (intro sum.cong) auto\n  also have \"\\<dots> = (\\<Sum>j\\<in>{nat m}.  ws ! j * unity_root_sum k (m-j))\"\n    using sum_eq .\n  also have \"\\<dots> = ws ! (nat m) * k\"\n    using assms(2) by (auto simp: algebra_simps)\n  finally have \"poly (finite_fourier_poly ws) (unity_root k m) = ws ! (nat m)\"\n    using assms(2) by auto\n  then show ?thesis by simp\nqed\n\ntext \\<open>Theorem 8.3\\<close>\ntheorem finite_fourier_poly_unique:\n  assumes \"length ws > 0\"\n  defines \"k \\<equiv> length ws\"\n  assumes \"(degree p \\<le> k - 1)\"\n  assumes \"(\\<forall>m \\<le> k-1. (ws ! m) = poly p (unity_root k m))\"\n  shows \"p = finite_fourier_poly ws\"\nproof -  \n  let ?z = \"map (\\<lambda>m. unity_root k m) [0..<k]\" \n  have k: \"k > 0\" using assms by auto\n  from k have d1: \"distinct ?z\"\n    unfolding distinct_conv_nth using unity_root_eqD[OF k] by force  \n  let ?zs_ws = \"zip ?z ws\"\n  from d1 k_def have d2: \"distinct (map fst ?zs_ws)\" by simp\n  have l2: \"length ?zs_ws > 0\" using assms(1) k_def by auto\n  have l3: \"length ?zs_ws = k\" by (simp add: k_def)\n\n  from degree_finite_fourier_poly have degree: \"degree (finite_fourier_poly ws) \\<le> k - 1\" \n    using k_def by simp\n\n  have interp: \"poly (finite_fourier_poly ws) x = y\"\n    if \"(x, y) \\<in> set ?zs_ws\" for x y\n  proof -\n    from that obtain n where \"\n         x = map (unity_root k \\<circ> int) [0..<k] ! n \\<and>\n         y = ws ! n \\<and> \n         n < length ws\"\n      using in_set_zip[of \"(x,y)\" \"(map (unity_root k) (map int [0..<k]))\" ws]\n      by auto\n    then have \"\n         x = unity_root k (int n) \\<and>\n         y = ws ! n \\<and> \n         n < length ws\"\n      using nth_map[of n \"[0..<k]\" \"unity_root k \\<circ> int\" ] k_def by simp\n    thus \"poly (finite_fourier_poly ws) x = y\"\n      by (simp add: poly_finite_fourier_poly k_def)\n  qed\n\n  have interp_p: \"poly p x = y\" if \"(x,y) \\<in> set ?zs_ws\" for x y\n  proof -\n    from that obtain n where \"\n         x = map (unity_root k \\<circ> int) [0..<k] ! n \\<and>\n         y = ws ! n \\<and> \n         n < length ws\"\n      using in_set_zip[of \"(x,y)\" \"(map (unity_root k) (map int [0..<k]))\" ws]\n      by auto\n    then have rw: \"x = unity_root k (int n)\" \"y = ws ! n\" \"n < length ws\"\n      using nth_map[of n \"[0..<k]\" \"unity_root k \\<circ> int\" ] k_def by simp+\n    show \"poly p x = y\" \n      unfolding rw(1,2) using assms(4) rw(3) k_def by simp\n  qed\n\n  from lagrange_unique[of _ p \"finite_fourier_poly ws\"] d2 l2\n  have l: \"\n    degree p \\<le> k - 1 \\<and>\n    (\\<forall>x y. (x, y) \\<in> set ?zs_ws \\<longrightarrow> poly p x = y) \\<Longrightarrow>\n    degree (finite_fourier_poly ws) \\<le> k - 1 \\<and>\n    (\\<forall>x y. (x, y) \\<in> set ?zs_ws \\<longrightarrow> poly (finite_fourier_poly ws) x = y) \\<Longrightarrow>\n    p = (finite_fourier_poly ws)\"\n    using l3 by fastforce\n  from assms degree interp interp_p l3\n  show \"p = (finite_fourier_poly ws)\" using l by blast  \nqed\n\n\ntext \\<open>\n  The following alternative formulation returns a coefficient\n\\<close>\ndefinition finite_fourier_poly' :: \"(nat \\<Rightarrow> complex) \\<Rightarrow> nat \\<Rightarrow> complex poly\" where\n  \"finite_fourier_poly' ws k =\n     (poly_of_list [1 / k * (\\<Sum>m<k. (ws m) * unity_root k (-n*m)). n \\<leftarrow> [0..<k]])\"\n\nlemma finite_fourier_poly'_conv_finite_fourier_poly:\n  \"finite_fourier_poly' ws k = finite_fourier_poly [ws n. n \\<leftarrow> [0..<k]]\"\n  unfolding finite_fourier_poly_def finite_fourier_poly'_def by simp\n\n\n\nlemma degree_finite_fourier_poly': \"degree (finite_fourier_poly' ws k) \\<le> k - 1\"\n  using degree_finite_fourier_poly[of \"[ws n. n \\<leftarrow> [0..<k]]\"]\n  by (auto simp: finite_fourier_poly'_conv_finite_fourier_poly)\n\nlemma poly_finite_fourier_poly':\n  fixes m :: int and k\n  assumes \"m \\<in> {0..<k}\"\n  shows \"poly (finite_fourier_poly' ws k) (unity_root k m) = ws (nat m)\"\n  using assms poly_finite_fourier_poly[of m \"[ws n. n \\<leftarrow> [0..<k]]\"]\n  by (auto simp: finite_fourier_poly'_conv_finite_fourier_poly poly_finite_fourier_poly)\n\nlemma finite_fourier_poly'_unique:\n  assumes \"k > 0\"\n  assumes \"degree p \\<le> k - 1\"\n  assumes \"\\<forall>m\\<le>k-1. ws m = poly p (unity_root k m)\"\n  shows \"p = finite_fourier_poly' ws k\"\nproof -\n  let ?ws = \"[ws n. n \\<leftarrow> [0..<k]]\"\n  from finite_fourier_poly_unique have \"p = finite_fourier_poly ?ws\" using assms by simp\n  also have \"\\<dots> = finite_fourier_poly' ws k\"\n    using finite_fourier_poly'_conv_finite_fourier_poly ..\n  finally show \"p = finite_fourier_poly' ws k\" by blast\nqed\n\nlemma fourier_unity_root:\n  fixes k :: nat\n  assumes \"k > 0\" \n  shows \"poly (finite_fourier_poly' f k) (unity_root k m) = \n    (\\<Sum>n<k.1/k*(\\<Sum>m<k.(f m)*unity_root k (-n*m))*unity_root k (m*n))\"\nproof -\n  have \"poly (finite_fourier_poly' f k) (unity_root k m) = \n        (\\<Sum>n\\<le>k-1. coeff (finite_fourier_poly' f k) n *(unity_root k m)^n)\"\n    using poly_altdef'[of \"finite_fourier_poly' f k\" \"k-1\" \"unity_root k m\"]\n          degree_finite_fourier_poly'[of f k] by simp\n  also have \"\\<dots> = (\\<Sum>n\\<le>k-1. coeff (finite_fourier_poly' f k) n *(unity_root k (m*n)))\" \n    using unity_root_pow by simp\n  also have \"\\<dots> = (\\<Sum>n<k. coeff (finite_fourier_poly' f k) n *(unity_root k (m*n)))\" \n    using assms by (intro sum.cong) auto\n  also have \"\\<dots> = (\\<Sum>n<k.(1/k)*(\\<Sum>m<k.(f m)*unity_root k (-n*m))*(unity_root k (m*n)))\" \n    using coeff_finite_fourier_poly'[of _ k f] by simp\n  finally show\n   \"poly (finite_fourier_poly' f k) (unity_root k m) = \n    (\\<Sum>n<k.1/k*(\\<Sum>m<k.(f m)*unity_root k (-n*m))*unity_root k (m*n))\"\n    by blast\nqed\n  \nsubsection \\<open>Expansion of an arithmetical function\\<close>\n\ntext \\<open>Theorem 8.4\\<close>\ntheorem fourier_expansion_periodic_arithmetic:\n  assumes \"k > 0\"\n  assumes \"periodic_arithmetic f k\"\n  defines \"g \\<equiv> (\\<lambda>n. (1 / k) * (\\<Sum>m<k. f m * unity_root k (-n * m)))\"\n    shows \"periodic_arithmetic g k\" \n      and \"f m = (\\<Sum>n<k. g n * unity_root k (m * n))\"  \nproof -\n {fix l\n  from unity_periodic_arithmetic mult_period\n  have period: \"periodic_arithmetic (\\<lambda>x. unity_root k x) (k*l)\" by simp}\n  note period = this\n {fix n l\n  have \"unity_root k (-(n+k)*l) = cnj (unity_root k ((n+k)*l))\"\n    by (simp add: unity_root_uminus unity_root_diff ring_distribs unity_root_add)\n  also have \"unity_root k ((n+k)*l) = unity_root k (n*l)\"\n    by (intro unity_root_cong) (auto simp: cong_def algebra_simps)\n  also have \"cnj \\<dots> = unity_root k (-n*l)\"\n    using unity_root_uminus by simp \n  finally have \"unity_root k (-(n+k)*l) = unity_root k (-n*l)\" by simp}\n  note u_period = this\n  \n  show 1: \"periodic_arithmetic g k\"\n    unfolding periodic_arithmetic_def\n  proof \n    fix n \n   \n    have \"g(n+k) = (1 / k) * (\\<Sum>m<k. f(m) * unity_root k (-(n+k)*m))\"\n      using assms(3) by fastforce\n    also have \"\\<dots> = (1 / k) * (\\<Sum>m<k. f(m) * unity_root k (-n*m))\"\n    proof -\n      have \"(\\<Sum>m<k. f(m) * unity_root k (-(n+k)*m)) = \n            (\\<Sum>m<k. f(m) * unity_root k (-n*m))\" \n        by (intro sum.cong) (use u_period in auto)\n      then show ?thesis by argo\n    qed\n    also have \"\\<dots> = g(n)\"\n      using assms(3) by fastforce\n    finally show \"g(n+k) = g(n)\" by simp \n  qed\n\n  show \"f(m) = (\\<Sum>n<k. g(n)* unity_root k (m * int n))\"\n  proof -\n    { \n      fix m\n      assume range: \"m \\<in> {0..<k}\"\n      have \"f(m) = (\\<Sum>n<k. g(n)* unity_root k (m * int n))\"\n      proof -\n        have \"f m = poly (finite_fourier_poly' f k) (unity_root k m)\"\n          using range by (simp add: poly_finite_fourier_poly')\n        also have \"\\<dots> = (\\<Sum>n<k. (1 / k) * (\\<Sum>m<k. f(m) * unity_root k (-n*m))* unity_root k (m*n))\"\n          using fourier_unity_root assms(1) by blast\n        also have \"\\<dots> = (\\<Sum>n<k. g(n)* unity_root k (m*n))\"\n          using assms by simp\n        finally show ?thesis by auto\n    qed}\n  note concentrated = this\n\n  have \"periodic_arithmetic (\\<lambda>m. (\\<Sum>n<k. g(n)* unity_root k (m * int n))) k\"\n  proof - \n    have \"periodic_arithmetic (\\<lambda>n. g(n)* unity_root k (i * int n)) k\"  for i :: int\n      using 1 unity_periodic_arithmetic mult_periodic_arithmetic\n            unity_periodic_arithmetic_mult by auto\n    then have p_s: \"\\<forall>i<k. periodic_arithmetic (\\<lambda>n. g(n)* unity_root k (i * int n)) k\"\n      by simp\n    have \"periodic_arithmetic (\\<lambda>i. \\<Sum>n<k. g(n)* unity_root k (i * int n)) k\"\n      unfolding periodic_arithmetic_def\n    proof\n      fix n\n      show \"(\\<Sum>na<k. g na * unity_root k (int (n + k) * int na)) =\n            (\\<Sum>na<k. g na * unity_root k (int n * int na))\"      \n        by (intro sum.cong refl, simp add: distrib_right flip: of_nat_mult of_nat_add)\n           (insert period, unfold periodic_arithmetic_def, blast)\n    qed\n    then show ?thesis by simp\n  qed  \n  \n  from this assms(1-2) concentrated \n       unique_periodic_arithmetic_extension[of k f \"(\\<lambda>i. \\<Sum>n<k. g(n)* unity_root k (i * int n))\"  m]\n  show \"f m = (\\<Sum>n<k. g n * unity_root k (int m * int n))\" by simp        \n  qed\nqed\n\ntheorem fourier_expansion_periodic_arithmetic_unique:\n  fixes f g :: \"nat \\<Rightarrow> complex\" \n  assumes \"k > 0\"\n  assumes \"periodic_arithmetic f k\" and \"periodic_arithmetic g k\"\n  assumes \"\\<And>m. m < k \\<Longrightarrow> f m = (\\<Sum>n<k. g n * unity_root k (int (m * n)))\" \n  shows   \"g n = (1 / k) * (\\<Sum>m<k. f m * unity_root k (-n * m))\"\nproof -\n  let ?p = \"poly_of_list [g(n). n \\<leftarrow> [0..<k]]\"\n  have d: \"degree ?p \\<le> k-1\"\n  proof -\n    have \"degree ?p \\<le> length [g(n). n \\<leftarrow> [0..<k]] - 1\" \n      using degree_poly_of_list_le by blast\n    also have \"\\<dots> = length [0..<k] - 1\" \n      using length_map by auto\n    finally show ?thesis by simp\n  qed    \n  have c: \"coeff ?p i = (if i < k then g(i) else 0)\" for i\n    by (simp add: nth_default_def)\n  {fix z\n  have \"poly ?p z = (\\<Sum>n\\<le>k-1. coeff ?p n* z^n)\" \n    using poly_altdef'[of ?p \"k-1\"] d by blast\n  also have \"\\<dots> = (\\<Sum>n<k. coeff ?p n* z^n)\" \n    using \\<open>k > 0\\<close> by (intro sum.cong) auto\n  also have \"\\<dots> = (\\<Sum>n<k. (if n < k then g(n) else 0)* z^n)\"\n    using c by simp\n  also have \"\\<dots> = (\\<Sum>n<k. g(n)* z^n)\" \n    by (simp split: if_splits)\n  finally have \"poly ?p z = (\\<Sum>n<k. g n * z ^ n)\" .}\n  note eval = this\n  {fix i\n  have \"poly ?p (unity_root k i) = (\\<Sum>n<k. g(n)* (unity_root k i)^n)\"\n    using eval by blast\n  then have \"poly ?p (unity_root k i) = (\\<Sum>n<k. g(n)* (unity_root k (i*n)))\"\n    using unity_root_pow by auto}\n  note interpolation = this\n\n  {\n    fix m \n    assume b: \"m \\<le> k-1\"\n    from d assms(1)\n    have \"f m = (\\<Sum>n<k. g(n) * unity_root k (m*n))\" \n      using assms(4) b by auto \n    also have \"\\<dots> = poly ?p (unity_root k m)\"\n      using interpolation by simp\n    finally have \"f m = poly ?p (unity_root k m)\" by auto\n  }\n\n  from this finite_fourier_poly'_unique[of k _ f]\n  have p_is_fourier: \"?p = finite_fourier_poly' f k\"\n    using assms(1) d by blast\n\n  {\n    fix n \n    assume b: \"n \\<le> k-1\"\n    have f_1: \"coeff ?p n = (1 / k) * (\\<Sum>m<k. f(m) * unity_root k (-n*m))\"  \n      using p_is_fourier using assms(1) b by (auto simp: coeff_finite_fourier_poly')\n    then have \"g(n) = (1 / k) * (\\<Sum>m<k. f(m) * unity_root k (-n*m))\"\n      using c b assms(1) \n    proof -\n      have 1: \"coeff ?p n = (1 / k) * (\\<Sum>m<k. f(m) * unity_root k (-n*m))\"\n        using f_1 by blast\n      have 2: \"coeff ?p n =  g n\"\n        using c assms(1) b by simp\n      show ?thesis using 1 2 by argo\n    qed\n  }\n\n (* now show right hand side is periodic and use unique_periodic_extension *)\n  have \"periodic_arithmetic (\\<lambda>n. (1 / k) * (\\<Sum>m<k. f(m) * unity_root k (-n*m))) k\"\n  proof - \n    have \"periodic_arithmetic (\\<lambda>i. unity_root k (-int i*int m)) k\" for m\n      using unity_root_periodic_arithmetic_mult_minus by simp\n    then have \"periodic_arithmetic (\\<lambda>i. f(m) * unity_root k (-i*m)) k\" for m\n      by (simp add: periodic_arithmetic_def)\n    then show \"periodic_arithmetic (\\<lambda>i. (1 / k) * (\\<Sum>m<k. f m * unity_root k (-i*m))) k\"\n      by (intro scalar_mult_periodic_arithmetic fin_sum_periodic_arithmetic_set) auto\n  qed\n  note periodich = this\n  let ?h = \"(\\<lambda>i. (1 / k) *(\\<Sum>m<k. f m * unity_root k (-i*m)))\"\n  from unique_periodic_arithmetic_extension[of k g ?h n] \n        assms(3) assms(1) periodich\n  have \"g n = (1/k) * (\\<Sum>m<k. f m * unity_root k (-n*m))\" \n    by (simp add: \\<open>\\<And>na. na \\<le> k - 1 \\<Longrightarrow> g na = complex_of_real (1 / real k) * (\\<Sum>m<k. f m * unity_root k (- int na * int m))\\<close>)\n  then show ?thesis 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/Finite_Fourier_Series.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8918110511888302, "lm_q2_score": 0.8267117898012104, "lm_q1q2_score": 0.7372707102928167}}
{"text": "theory ExF015\n  imports Main \nbegin\n  \nlemma \"\\<not>(\\<forall>x. P x) \\<longleftrightarrow> (\\<exists>x. \\<not>P x)\" \nproof -\n  {\n    assume a:\"\\<not>(\\<forall>x. P x)\" \n    {\n      assume b:\"\\<not>(\\<exists>x. \\<not>P x)\"\n      {\n        fix aa \n        {\n          assume \"\\<not>P aa\"\n          hence \"\\<exists>x. \\<not>P x\" by (rule exI)\n          with b have False by contradiction\n        }\n        hence \"\\<not>\\<not>P aa\" by (rule notI)\n        hence \"P aa\" by (rule notnotD)\n      }\n      hence \"\\<forall>x. P x\" by (rule allI)\n      with a have False by contradiction\n    }\n    hence \"\\<not>\\<not>(\\<exists>x. \\<not>P x)\" by (rule notI)\n    hence \"\\<exists>x. \\<not>P x\" by (rule notnotD)\n  }\n  moreover\n  {\n    assume a:\"\\<exists>x. \\<not>P x\"\n    {\n      assume b:\"\\<forall>x. P x\" \n      {\n        fix aa\n        assume c:\"\\<not>P aa\"\n        from b have \"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. P x)\" by (rule notI)\n  }\n  ultimately show ?thesis by (rule iffI)\nqed\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/ExF015.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896780646392, "lm_q2_score": 0.8006920068519376, "lm_q1q2_score": 0.7372689352181255}}
{"text": "subsection \"Minimum Edit Distance\"\n\ntheory Min_Ed_Dist0\nimports\n  \"HOL-Library.IArray\"\n  \"HOL-Library.Code_Target_Numeral\"\n  \"HOL-Library.Product_Lexorder\"\n  \"HOL-Library.RBT_Mapping\"\n  \"../state_monad/State_Main\"\n  \"../heap_monad/Heap_Main\"\n  Example_Misc\n  \"../util/Tracing\"\n  \"../util/Ground_Function\"\nbegin\n\nsubsubsection \"Misc\"\n\ntext \"Executable argmin\"\n\nfun argmin :: \"('a \\<Rightarrow> 'b::order) \\<Rightarrow> 'a list \\<Rightarrow> 'a\" where\n\"argmin f [a] = a\" |\n\"argmin f (a#as) = (let m = argmin f as in if f a \\<le> f m then a else m)\"\n(* end rm *)\n\n(* Ex: Optimization of argmin *)\nfun argmin2 :: \"('a \\<Rightarrow> 'b::order) \\<Rightarrow> 'a list \\<Rightarrow> 'a * 'b\" where\n\"argmin2 f [a] = (a, f a)\" |\n\"argmin2 f (a#as) = (let fa = f a; (am,m) = argmin2 f as in if fa \\<le> m then (a, fa) else (am,m))\"\n\n\nsubsubsection \"Edit Distance\"\n\ndatatype 'a ed = Copy | Repl 'a | Ins 'a | Del\n\nfun edit :: \"'a ed list \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where\n\"edit (Copy # es) (x # xs) = x # edit es xs\" |\n\"edit (Repl a # es) (x # xs) = a # edit es xs\" |\n\"edit (Ins a # es) xs = a # edit es xs\" |\n\"edit (Del # es) (x # xs) = edit es xs\" |\n\"edit (Copy # es) [] = edit es []\" |\n\"edit (Repl a # es) [] = edit es []\" |\n\"edit (Del # es) [] = edit es []\" |\n\"edit [] xs = xs\"\n\nabbreviation cost where\n\"cost es \\<equiv> length [e <- es. e \\<noteq> Copy]\"\n\n\nsubsubsection \"Minimum Edit Sequence\"\n\nfun min_eds :: \"'a list \\<Rightarrow> 'a list \\<Rightarrow> 'a ed list\" where\n\"min_eds [] [] = []\" |\n\"min_eds [] (y#ys) = Ins y # min_eds [] ys\" |\n\"min_eds (x#xs) [] = Del # min_eds xs []\" |\n\"min_eds (x#xs) (y#ys) =\n  argmin cost [Ins y # min_eds (x#xs) ys, Del # min_eds xs (y#ys),\n     (if x=y then Copy else Repl y) # min_eds xs ys]\"\n\nlemma \"min_eds ''vintner'' ''writers'' =\n  [Ins CHR ''w'', Repl CHR ''r'', Copy, Del, Copy, Del, Copy, Copy, Ins CHR ''s'']\"\nby eval\n(*\nvalue \"min_eds ''madagascar'' ''bananas''\"\n\nvalue \"min_eds ''madagascaram'' ''banananas''\"\n*)\nlemma min_eds_correct: \"edit (min_eds xs ys) xs = ys\"\nby (induction xs ys rule: min_eds.induct) auto\n\nlemma min_eds_same: \"min_eds xs xs = replicate (length xs) Copy\"\nby (induction xs) auto\n\nlemma min_eds_eq_Nil_iff: \"min_eds xs ys = [] \\<longleftrightarrow> xs = [] \\<and> ys = []\"\nby (induction xs ys rule: min_eds.induct) auto\n\nlemma min_eds_Nil: \"min_eds [] ys = map Ins ys\"\nby (induction ys) auto\n\nlemma min_eds_Nil2: \"min_eds xs [] = replicate (length xs) Del\"\nby (induction xs) auto\n\nlemma if_edit_Nil2: \"edit es ([]::'a list) = ys \\<Longrightarrow> length ys \\<le> cost es\"\napply(induction es \"[]::'a list\" arbitrary: ys rule: edit.induct)\napply auto\n apply fastforce\napply fastforce\ndone\n\nlemma if_edit_eq_Nil: \"edit es xs = [] \\<Longrightarrow> length xs \\<le> cost es\"\nby (induction es xs rule: edit.induct) auto\n\nlemma min_eds_minimal: \"edit es xs = ys \\<Longrightarrow> cost(min_eds xs ys) \\<le> cost es\"\nproof(induction xs ys arbitrary: es rule: min_eds.induct)\n  case 1 thus ?case by simp\nnext\n  case 2 thus ?case by (auto simp add: min_eds_Nil dest: if_edit_Nil2)\nnext\n  case 3\n  thus ?case by(auto simp add: min_eds_Nil2 dest: if_edit_eq_Nil)\nnext\n  case 4\n  show ?case\n  proof (cases \"es\")\n    case Nil then show ?thesis using \"4.prems\" by (auto simp: min_eds_same)\n  next\n    case [simp]: (Cons e es')\n    show ?thesis\n    proof (cases e)\n      case Copy\n      thus ?thesis using \"4.prems\" \"4.IH\"(3)[of es'] by simp\n    next\n      case (Repl a)\n      thus ?thesis using \"4.prems\" \"4.IH\"(3)[of es']\n        using [[simp_depth_limit=1]] by simp\n    next\n      case (Ins a)\n      thus ?thesis using \"4.prems\" \"4.IH\"(1)[of es']\n        using [[simp_depth_limit=1]] by auto\n    next\n      case Del\n      thus ?thesis using \"4.prems\" \"4.IH\"(2)[of es']\n        using [[simp_depth_limit=1]] by auto\n    qed\n  qed\nqed\n\n\nsubsubsection \"Computing the Minimum Edit Distance\"\n\nfun min_ed :: \"'a list \\<Rightarrow> 'a list \\<Rightarrow> nat\" where\n\"min_ed [] [] = 0\" |\n\"min_ed [] (y#ys) = 1 + min_ed [] ys\" |\n\"min_ed (x#xs) [] = 1 + min_ed xs []\" |\n\"min_ed (x#xs) (y#ys) =\n  Min {1 + min_ed (x#xs) ys, 1 + min_ed xs (y#ys), (if x=y then 0 else 1) + min_ed xs ys}\"\n\nlemma min_ed_min_eds: \"min_ed xs ys = cost(min_eds xs ys)\"\napply(induction xs ys rule: min_ed.induct)\napply (auto split!: if_splits)\ndone\n\nlemma \"min_ed ''madagascar'' ''bananas'' = 6\"\nby eval\n(*\nvalue \"min_ed ''madagascaram'' ''banananas''\"\n*)\n\ntext \"Exercise: Optimization of the Copy case\"\n\nfun min_eds2 :: \"'a list \\<Rightarrow> 'a list \\<Rightarrow> 'a ed list\" where\n\"min_eds2 [] [] = []\" |\n\"min_eds2 [] (y#ys) = Ins y # min_eds2 [] ys\" |\n\"min_eds2 (x#xs) [] = Del # min_eds2 xs []\" |\n\"min_eds2 (x#xs) (y#ys) =\n  (if x=y then Copy # min_eds2 xs ys\n   else argmin cost\n     [Ins y # min_eds2 (x#xs) ys, Del # min_eds2 xs (y#ys), Repl y # min_eds2 xs ys])\"\n\nvalue \"min_eds2 ''madagascar'' ''bananas''\"\n\nlemma cost_Copy_Del: \"cost(min_eds xs ys) \\<le> cost (min_eds xs (x#ys)) + 1\"\napply(induction xs ys rule: min_eds.induct)\napply(auto simp del: filter_True filter_False split!: if_splits)\ndone\n\nlemma cost_Copy_Ins: \"cost(min_eds xs ys) \\<le> cost (min_eds (x#xs) ys) + 1\"\napply(induction xs ys rule: min_eds.induct)\napply(auto simp del: filter_True filter_False split!: if_splits)\ndone\n\nlemma \"cost(min_eds2 xs ys) = cost(min_eds xs ys)\"\nproof(induction xs ys rule: min_eds2.induct)\n  case (4 x xs y ys) thus ?case\n    apply (auto split!: if_split)\n      apply (metis (mono_tags, lifting) Suc_eq_plus1 Suc_leI cost_Copy_Del cost_Copy_Ins le_imp_less_Suc le_neq_implies_less not_less)\n     apply (metis Suc_eq_plus1 cost_Copy_Del le_antisym)\n    by (metis Suc_eq_plus1 cost_Copy_Ins le_antisym)\nqed simp_all\n\nlemma \"min_eds2 xs ys = min_eds xs ys\"\noops\n(* Not proveable because Copy comes last in min_eds but first in min_eds2.\n   Can reorder, but the proof still requires the same two lemmas cost_*_* above.\n*)\n\n\nsubsubsection \"Indexing\"\n\ntext \"Indexing lists\"\n\ncontext\nfixes xs ys :: \"'a list\"\nfixes m n :: nat\nbegin\n\nfunction (sequential)\n  min_ed_ix' :: \"nat * nat \\<Rightarrow> nat\" where\n\"min_ed_ix' (i,j) =\n  (if i \\<ge> m then\n     if j \\<ge> n then 0 else 1 + min_ed_ix' (i,j+1) else\n   if j \\<ge> n then 1 + min_ed_ix' (i+1, j)\n   else\n   Min {1 + min_ed_ix' (i,j+1), 1 + min_ed_ix' (i+1, j),\n       (if xs!i = ys!j then 0 else 1) + min_ed_ix' (i+1,j+1)})\"\nby pat_completeness auto\ntermination by(relation \"measure(\\<lambda>(i,j). (m - i) + (n - j))\") auto\n\n\ndeclare min_ed_ix'.simps[simp del]\n\nend\n\nlemma min_ed_ix'_min_ed:\n  \"min_ed_ix' xs ys (length xs) (length ys) (i, j) = min_ed (drop i xs) (drop j ys)\"\napply(induction \"(i,j)\" arbitrary: i j rule: min_ed_ix'.induct[of \"length xs\" \"length ys\"])\napply(subst min_ed_ix'.simps)\napply(simp add: Cons_nth_drop_Suc[symmetric])\ndone\n\n\ntext \"Indexing functions\"\n\ncontext\nfixes xs ys :: \"nat \\<Rightarrow> 'a\"\nfixes m n :: nat\nbegin\n\nfunction (sequential)\n  min_ed_ix :: \"nat \\<times> nat \\<Rightarrow> nat\" where\n\"min_ed_ix (i, j) =\n  (if i \\<ge> m then\n     if j \\<ge> n then 0 else n-j else\n   if j \\<ge> n then m-i\n   else\n   min_list [1 + min_ed_ix (i, j+1), 1 + min_ed_ix (i+1, j),\n       (if xs i = ys j then 0 else 1) + min_ed_ix (i+1, j+1)])\"\nby pat_completeness auto\ntermination by(relation \"measure(\\<lambda>(i,j). (m - i) + (n - j))\") auto\n\n\nsubsubsection \\<open>Functional Memoization\\<close>\n\nmemoize_fun min_ed_ix\\<^sub>m: min_ed_ix with_memory dp_consistency_mapping monadifies (state) min_ed_ix.simps\nthm min_ed_ix\\<^sub>m'.simps\n\nmemoize_correct\n  by memoize_prover\nprint_theorems\n\nlemmas [code] = min_ed_ix\\<^sub>m.memoized_correct\n\ndeclare min_ed_ix.simps[simp del]\n\n\nsubsubsection \\<open>Imperative Memoization\\<close>\n\ncontext\n  fixes mem :: \"nat ref \\<times> nat ref \\<times> nat option array ref \\<times> nat option array ref\"\n  assumes mem_is_init: \"mem = result_of (init_state (n + 1) m (m + 1)) Heap.empty\"\nbegin\n\ninterpretation iterator\n  \"\\<lambda> (x, y). x \\<le> m \\<and> y \\<le> n \\<and> x > 0\"\n  \"\\<lambda> (x, y). if y > 0 then (x, y - 1) else (x - 1, n)\"\n  \"\\<lambda> (x, y). (m - x) * (n + 1) + (n - y)\"\n  by (rule table_iterator_down)\n\nlemma [intro]:\n  \"dp_consistency_heap_array_pair' (n + 1) fst snd id m (m + 1) mem\"\n  by (standard; simp add: mem_is_init injective_def)\n\nlemma [intro]:\n  \"dp_consistency_heap_array_pair_iterator (n + 1) fst snd id m (m + 1) mem\n   (\\<lambda> (x, y). if y > 0 then (x, y - 1) else (x - 1, n))\n   (\\<lambda> (x, y). (m - x) * (n + 1) + (n - y))\n   (\\<lambda> (x, y). x \\<le> m \\<and> y \\<le> n \\<and> x > 0)\n  \"\n  by (standard; simp add: mem_is_init injective_def)\n\nmemoize_fun min_ed_ix\\<^sub>h: min_ed_ix\n  with_memory (default_proof) dp_consistency_heap_array_pair_iterator\n  where size = \"n + 1\"\n    and key1=\"fst :: nat \\<times> nat \\<Rightarrow> nat\" and key2=\"snd :: nat \\<times> nat \\<Rightarrow> nat\"\n    and k1=\"m :: nat\" and k2=\"m + 1 :: nat\"\n    and to_index = \"id :: nat \\<Rightarrow> nat\"\n    and mem = mem\n    and cnt = \"\\<lambda> (x, y). x \\<le> m \\<and> y \\<le> n \\<and> x > 0\"\n    and nxt = \"\\<lambda> (x::nat, y). if y > 0 then (x, y - 1) else (x - 1, n)\"\n    and sizef = \"\\<lambda> (x, y). (m - x) * (n + 1) + (n - y)\"\nmonadifies (heap) min_ed_ix.simps\n\nmemoize_correct\n  by memoize_prover\n\nlemmas memoized_empty =\n  min_ed_ix\\<^sub>h.memoized_empty[OF min_ed_ix\\<^sub>h.consistent_DP_iter_and_compute[OF min_ed_ix\\<^sub>h.crel]]\nlemmas iter_heap_unfold = iter_heap_unfold\n\nend (* Fixed Memory *)\n\nend\n\n\nsubsubsection \\<open>Test Cases\\<close>\n\nabbreviation \"slice xs i j \\<equiv> map xs [i..<j]\"\n\nlemma min_ed_Nil1: \"min_ed [] ys = length ys\"\nby (induction ys) auto\n\nlemma min_ed_Nil2: \"min_ed xs [] = length xs\"\nby (induction xs) auto\n\n(* prove correctness of min_ed_ix directly ? *)\nlemma min_ed_ix_min_ed: \"min_ed_ix xs ys m n (i,j) = min_ed (slice xs i m) (slice ys j n)\"\napply(induction \"(i,j)\" arbitrary: i j rule: min_ed_ix.induct[of m n])\napply(simp add: min_ed_ix.simps upt_conv_Cons min_ed_Nil1 min_ed_Nil2 Suc_diff_Suc)\ndone\n\n\ntext \\<open>Functional Test Cases\\<close>\n\ndefinition \"min_ed_list xs ys = min_ed_ix (\\<lambda>i. xs!i) (\\<lambda>i. ys!i) (length xs) (length ys) (0,0)\"\n\nlemma \"min_ed_list ''madagascar'' ''bananas'' = 6\"\nby eval\n\ndefinition \"min_ed_ia xs ys = (let a = IArray xs; b = IArray ys\n  in min_ed_ix (\\<lambda>i. a!!i) (\\<lambda>i. b!!i) (length xs) (length ys) (0,0))\"\n\nlemma \"min_ed_ia ''madagascar'' ''bananas'' = 6\"\nby eval\n\n\n\ntext \\<open>Extracting an Executable Constant for the Imperative Implementation\\<close>\n\nground_function min_ed_ix\\<^sub>h'_impl: min_ed_ix\\<^sub>h'.simps\ntermination\n  by(relation \"measure(\\<lambda>(xs, ys, m, n, mem, i, j). (m - i) + (n - j))\") auto\n\nlemmas [simp del] = min_ed_ix\\<^sub>h'_impl.simps min_ed_ix\\<^sub>h'.simps\n\nlemma min_ed_ix\\<^sub>h'_impl_def:\n  includes heap_monad_syntax\n  fixes m n :: nat\n  fixes mem :: \"nat ref \\<times> nat ref \\<times> nat option array ref \\<times> nat option array ref\"\n  assumes mem_is_init: \"mem = result_of (init_state (n + 1) m (m + 1)) Heap.empty\"\n  shows \"min_ed_ix\\<^sub>h'_impl xs ys m n mem = min_ed_ix\\<^sub>h' xs ys m n mem\"\nproof -\n  have \"min_ed_ix\\<^sub>h'_impl xs ys m n mem (i, j) = min_ed_ix\\<^sub>h' xs ys m n mem (i, j)\" for i j\n    apply (induction rule: min_ed_ix\\<^sub>h'.induct[OF mem_is_init])\n    apply (subst min_ed_ix\\<^sub>h'_impl.simps)\n    apply (subst min_ed_ix\\<^sub>h'.simps[OF mem_is_init])\n    apply (solve_cong simp)\n    done\n  then show ?thesis\n    by auto\nqed\n\ndefinition\n  \"iter_min_ed_ix xs ys m n mem = iterator_defs.iter_heap\n    (\\<lambda> (x, y). x \\<le> m \\<and> y \\<le> n \\<and> x > 0)\n    (\\<lambda> (x, y). if y > 0 then (x, y - 1) else (x - 1, n))\n    (min_ed_ix\\<^sub>h'_impl xs ys m n mem)\n  \"\n\nlemma iter_min_ed_ix_unfold[code]:\n  \"iter_min_ed_ix xs ys m n mem = (\\<lambda> (i, j).\n    (if i > 0 \\<and> i \\<le> m \\<and> j \\<le> n\n     then do {\n            min_ed_ix\\<^sub>h'_impl xs ys m n mem (i, j);\n            iter_min_ed_ix xs ys m n mem (if j > 0 then (i, j - 1) else (i - 1, n))\n          }\n     else Heap_Monad.return ()))\"\n  unfolding iter_min_ed_ix_def by (rule ext) (safe, simp add: iter_heap_unfold)\n\ndefinition\n  \"min_ed_ix_impl xs ys m n i j = do {\n    mem \\<leftarrow> (init_state (n + 1) (m::nat) (m + 1) ::\n      (nat ref \\<times> nat ref \\<times> nat option array ref \\<times> nat option array ref) Heap);\n    iter_min_ed_ix xs ys m n mem (m, n);\n    min_ed_ix\\<^sub>h'_impl xs ys m n mem (i, j)\n  }\"\n\nlemma bf_impl_correct:\n  \"min_ed_ix xs ys m n (i, j) = result_of (min_ed_ix_impl xs ys m n i j) Heap.empty\"\n  using memoized_empty[OF HOL.refl, of xs ys m n \"(i, j)\" \"\\<lambda> _. (m, n)\"]\n  by (simp add:\n      execute_bind_success[OF succes_init_state] min_ed_ix_impl_def min_ed_ix\\<^sub>h'_impl_def\n      iter_min_ed_ix_def\n     )\n\n\ntext \\<open>Imperative Test Case\\<close>\n\ndefinition\n  \"min_ed_ia\\<^sub>h xs ys = (let a = IArray xs; b = IArray ys\n  in min_ed_ix_impl (\\<lambda>i. a!!i) (\\<lambda>i. b!!i) (length xs) (length ys) 0 0)\"\n\ndefinition\n  \"test_case = min_ed_ia\\<^sub>h ''madagascar'' ''bananas''\"\n\nexport_code min_ed_ix in SML module_name Test\n\ncode_reflect Test functions test_case\n\ntext \\<open>One can see a trace of the calls to the memory in the output\\<close>\nML \\<open>Test.test_case ()\\<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/Monad_Memo_DP/example/Min_Ed_Dist0.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127678225575, "lm_q2_score": 0.8633916064586998, "lm_q1q2_score": 0.7372611163859127}}
{"text": "section \\<open>Counterclockwise\\<close>\ntheory Counterclockwise\nimports \"HOL-Analysis.Multivariate_Analysis\"\nbegin\ntext \\<open>\\label{sec:counterclockwise}\\<close>\n\nsubsection \\<open>Auxiliary Lemmas\\<close>\n\nlemma convex3_alt:\n  fixes x y z::\"'a::real_vector\"\n  assumes \"0 \\<le> a\" \"0 \\<le> b\" \"0 \\<le> c\" \"a + b + c = 1\"\n  obtains u v  where \"a *\\<^sub>R x + b *\\<^sub>R y + c *\\<^sub>R z = x + u *\\<^sub>R (y - x) + v *\\<^sub>R (z - x)\"\n    and \"0 \\<le> u\" \"0 \\<le> v\" \"u + v \\<le> 1\"\nproof -\n  from convex_hull_3[of x y z] have \"a *\\<^sub>R x + b *\\<^sub>R y + c *\\<^sub>R z \\<in> convex hull {x, y, z}\"\n    using assms by auto\n  also note convex_hull_3_alt\n  finally obtain u v where \"a *\\<^sub>R x + b *\\<^sub>R y + c *\\<^sub>R z = x + u *\\<^sub>R (y - x) + v *\\<^sub>R (z - x)\"\n    and uv: \"0 \\<le> u\" \"0 \\<le> v\" \"u + v \\<le> 1\"\n    by auto\n  thus ?thesis ..\nqed\n\nlemma (in ordered_ab_group_add) add_nonpos_eq_0_iff:\n  assumes x: \"0 \\<ge> x\" and y: \"0 \\<ge> y\"\n  shows \"x + y = 0 \\<longleftrightarrow> x = 0 \\<and> y = 0\"\nproof -\n  from add_nonneg_eq_0_iff[of \"-x\" \"-y\"] assms\n  have \"- (x + y) = 0 \\<longleftrightarrow> - x = 0 \\<and> - y = 0\"\n    by simp\n  also have \"(- (x + y) = 0) = (x + y = 0)\" unfolding neg_equal_0_iff_equal ..\n  finally show ?thesis by simp\nqed\n\nlemma sum_nonpos_eq_0_iff:\n  fixes f :: \"'a \\<Rightarrow> 'b::ordered_ab_group_add\"\n  shows \"\\<lbrakk>finite A; \\<forall>x\\<in>A. f x \\<le> 0\\<rbrakk> \\<Longrightarrow> sum f A = 0 \\<longleftrightarrow> (\\<forall>x\\<in>A. f x = 0)\"\n  by (induct set: finite) (simp_all add: add_nonpos_eq_0_iff sum_nonpos)\n\nlemma fold_if_in_set:\n  \"fold (\\<lambda>x m. if P x m then x else m) xs x \\<in> set (x#xs)\"\n  by (induct xs arbitrary: x) auto\n\nsubsection \\<open>Sort Elements of a List\\<close>\n\nlocale linorder_list0 = fixes le::\"'a \\<Rightarrow> 'a \\<Rightarrow> bool\"\nbegin\n\ndefinition \"min_for a b = (if le a b then a else b)\"\n\nlemma min_for_in[simp]: \"x \\<in> S \\<Longrightarrow> y \\<in> S \\<Longrightarrow> min_for x y \\<in> S\"\n  by (auto simp: min_for_def)\n\nlemma fold_min_eqI1: \"fold min_for ys y \\<notin> set ys \\<Longrightarrow> fold min_for ys y = y\"\n  using fold_if_in_set[of _ ys y]\n  by (auto simp: min_for_def[abs_def])\n\nfunction selsort where\n  \"selsort [] = []\"\n| \"selsort (y#ys) = (let\n      xm = fold min_for ys y;\n      xs' = List.remove1 xm (y#ys)\n    in (xm#selsort xs'))\"\n  by pat_completeness auto\ntermination\n  by (relation \"Wellfounded.measure length\")\n    (auto simp: length_remove1 intro!: fold_min_eqI1 dest!: length_pos_if_in_set)\n\nlemma in_set_selsort_eq: \"x \\<in> set (selsort xs) \\<longleftrightarrow> x \\<in> (set xs)\"\n  by (induct rule: selsort.induct) (auto simp: Let_def intro!: fold_min_eqI1)\n\nlemma set_selsort[simp]: \"set (selsort xs) = set xs\"\n  using in_set_selsort_eq by blast\n\nlemma length_selsort[simp]: \"length (selsort xs) = length xs\"\nproof (induct xs rule: selsort.induct)\n  case (2 x xs)\n  from 2[OF refl refl]\n  show ?case\n    unfolding selsort.simps\n    by (auto simp: Let_def length_remove1\n      simp del: selsort.simps split: if_split_asm\n      intro!: Suc_pred\n      dest!: fold_min_eqI1)\nqed simp\n\nlemma distinct_selsort[simp]: \"distinct (selsort xs) = distinct xs\"\n  by (auto intro!: card_distinct dest!: distinct_card)\n\nlemma selsort_eq_empty_iff[simp]: \"selsort xs = [] \\<longleftrightarrow> xs = []\"\n  by (cases xs) (auto simp: Let_def)\n\n\ninductive sortedP :: \"'a list \\<Rightarrow> bool\" where\n  Nil: \"sortedP []\"\n| Cons: \"\\<forall>y\\<in>set ys. le x y \\<Longrightarrow> sortedP ys \\<Longrightarrow> sortedP (x # ys)\"\n\ninductive_cases\n  sortedP_Nil: \"sortedP []\" and\n  sortedP_Cons: \"sortedP (x#xs)\"\ninductive_simps\n  sortedP_Nil_iff: \"sortedP Nil\" and\n  sortedP_Cons_iff: \"sortedP (Cons x xs)\"\n\nlemma sortedP_append_iff:\n  \"sortedP (xs @ ys) = (sortedP xs & sortedP ys & (\\<forall>x \\<in> set xs. \\<forall>y \\<in> set ys. le x y))\"\n  by (induct xs) (auto intro!: Nil Cons elim!: sortedP_Cons)\n\nlemma sortedP_appendI:\n  \"sortedP xs \\<Longrightarrow> sortedP ys \\<Longrightarrow> (\\<And>x y. x \\<in> set xs \\<Longrightarrow> y \\<in> set ys \\<Longrightarrow> le x y) \\<Longrightarrow> sortedP (xs @ ys)\"\n  by (induct xs) (auto intro!: Nil Cons elim!: sortedP_Cons)\n\nlemma sorted_nth_less: \"sortedP xs \\<Longrightarrow> i < j \\<Longrightarrow> j < length xs \\<Longrightarrow> le (xs ! i) (xs ! j)\"\n  by (induct xs arbitrary: i j) (auto simp: nth_Cons split: nat.split elim!: sortedP_Cons)\n\nlemma sorted_butlastI[intro, simp]: \"sortedP xs \\<Longrightarrow> sortedP (butlast xs)\"\n  by (induct xs) (auto simp: elim!: sortedP_Cons intro!: sortedP.Cons dest!: in_set_butlastD)\n\nlemma sortedP_right_of_append1:\n  assumes \"sortedP (zs@[z])\"\n  assumes \"y \\<in> set zs\"\n  shows \"le y z\"\n  using assms\n  by (induct zs arbitrary: y z) (auto elim!: sortedP_Cons)\n\nlemma sortedP_right_of_last:\n  assumes \"sortedP zs\"\n  assumes \"y \\<in> set zs\" \"y \\<noteq> last zs\"\n  shows \"le y (last zs)\"\n  using assms\n  apply (intro sortedP_right_of_append1[of \"butlast zs\" \"last zs\" y])\n  subgoal by (metis append_is_Nil_conv list.distinct(1) snoc_eq_iff_butlast split_list)\n  subgoal by (metis List.insert_def append_butlast_last_id insert_Nil list.distinct(1) rotate1.simps(2)\n    set_ConsD set_rotate1)\n  done\n\nlemma selsort_singleton_iff: \"selsort xs = [x] \\<longleftrightarrow> xs = [x]\"\n  by (induct xs) (auto simp: Let_def)\n\nlemma hd_last_sorted:\n  assumes \"sortedP xs\" \"length xs > 1\"\n  shows \"le (hd xs) (last xs)\"\nproof (cases xs)\n  case (Cons y ys)\n  note ys = this\n  thus ?thesis\n    using ys assms\n    by (auto elim!: sortedP_Cons)\nqed (insert assms, simp)\n\nend\n\nlemma (in comm_monoid_add) sum_list_distinct_selsort:\n  assumes \"distinct xs\"\n  shows \"sum_list (linorder_list0.selsort le xs) = sum_list xs\"\n  using assms\n  apply (simp add: distinct_sum_list_conv_Sum linorder_list0.distinct_selsort)\n  apply (rule sum.cong)\n  subgoal by (simp add: linorder_list0.set_selsort)\n  subgoal by simp\n  done\n\ndeclare linorder_list0.sortedP_Nil_iff[code]\n  linorder_list0.sortedP_Cons_iff[code]\n  linorder_list0.selsort.simps[code]\n  linorder_list0.min_for_def[code]\n\nlocale linorder_list = linorder_list0 le for le::\"'a::ab_group_add \\<Rightarrow> _\" +\n  fixes S\n  assumes order_refl: \"a \\<in> S \\<Longrightarrow> le a a\"\n  assumes trans': \"a \\<in> S \\<Longrightarrow> b \\<in> S \\<Longrightarrow> c \\<in> S \\<Longrightarrow> a \\<noteq> b \\<Longrightarrow> b \\<noteq> c \\<Longrightarrow> a \\<noteq> c \\<Longrightarrow>\n    le a b \\<Longrightarrow> le b c \\<Longrightarrow> le a c\"\n  assumes antisym: \"a \\<in> S \\<Longrightarrow> b \\<in> S \\<Longrightarrow> le a b \\<Longrightarrow> le b a \\<Longrightarrow> a = b\"\n  assumes linear': \"a \\<in> S \\<Longrightarrow> b \\<in> S \\<Longrightarrow> a \\<noteq> b \\<Longrightarrow> le a b \\<or> le b a\"\nbegin\n\nlemma trans: \"a \\<in> S \\<Longrightarrow> b \\<in> S \\<Longrightarrow> c \\<in> S \\<Longrightarrow> le a b \\<Longrightarrow> le b c \\<Longrightarrow> le a c\"\n  by (cases \"a = b\" \"b = c\" \"a = c\"\n    rule: bool.exhaust[case_product bool.exhaust[case_product bool.exhaust]])\n    (auto simp: order_refl intro: trans')\n\nlemma linear: \"a \\<in> S \\<Longrightarrow> b \\<in> S \\<Longrightarrow> le a b \\<or> le b a\"\n  by (cases \"a = b\") (auto simp: linear' order_refl)\n\nlemma min_le1: \"w \\<in> S \\<Longrightarrow> y \\<in> S \\<Longrightarrow> le (min_for w y) y\"\n  and min_le2: \"w \\<in> S \\<Longrightarrow> y \\<in> S \\<Longrightarrow> le (min_for w y) w\"\n  using linear\n  by (auto simp: min_for_def refl)\n\nlemma fold_min:\n  assumes \"set xs \\<subseteq> S\"\n  shows \"list_all (\\<lambda>y. le (fold min_for (tl xs) (hd xs)) y) xs\"\nproof (cases xs)\n  case (Cons y ys)\n  hence subset: \"set (y#ys) \\<subseteq> S\" using assms\n    by auto\n  show ?thesis\n    unfolding Cons list.sel\n    using subset\n  proof (induct ys arbitrary: y)\n    case (Cons z zs)\n    hence IH: \"\\<And>y. y \\<in> S \\<Longrightarrow> list_all (le (fold min_for zs y)) (y # zs)\"\n      by simp\n    let ?f = \"fold min_for zs (min_for z y)\"\n    have \"?f \\<in> set ((min_for z y)#zs)\"\n      unfolding min_for_def[abs_def]\n      by (rule fold_if_in_set)\n    also have \"\\<dots> \\<subseteq> S\" using Cons.prems by auto\n    finally have \"?f \\<in> S\" .\n\n    have \"le ?f (min_for z y)\"\n      using IH[of \"min_for z y\"] Cons.prems\n      by auto\n    moreover have \"le (min_for z y) y\" \"le (min_for z y) z\" using Cons.prems\n      by (auto intro!: min_le1 min_le2)\n    ultimately have \"le ?f y\" \"le ?f z\" using Cons.prems \\<open>?f \\<in> S\\<close>\n      by (auto intro!: trans[of ?f \"min_for z y\"])\n    thus ?case\n      using IH[of \"min_for z y\"]\n      using Cons.prems\n      by auto\n  qed (simp add: order_refl)\nqed simp\n\nlemma\n  sortedP_selsort:\n  assumes \"set xs \\<subseteq> S\"\n  shows \"sortedP (selsort xs)\"\n  using assms\nproof (induction xs rule: selsort.induct)\n  case (2 z zs)\n  from this fold_min[of \"z#zs\"]\n  show ?case\n    by (fastforce simp: list_all_iff Let_def\n        simp del: remove1.simps\n        intro: Cons intro!: 2(1)[OF refl refl]\n        dest!: rev_subsetD[OF _ set_remove1_subset])+\nqed (auto intro!: Nil)\n\nend\n\n\nsubsection \\<open>Abstract CCW Systems\\<close>\n\nlocale ccw_system0 =\n  fixes ccw::\"'a \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> bool\"\n    and S::\"'a set\"\nbegin\n\nabbreviation \"indelta t p q r \\<equiv> ccw t q r \\<and> ccw p t r \\<and> ccw p q t\"\nabbreviation \"insquare p q r s \\<equiv> ccw p q r \\<and> ccw q r s \\<and> ccw r s p \\<and> ccw s p q\"\n\nend\n\nabbreviation \"distinct3 p q r \\<equiv> \\<not>(p = q \\<or> p = r \\<or> q = r)\"\nabbreviation \"distinct4 p q r s \\<equiv> \\<not>(p = q \\<or> p = r \\<or> p = s \\<or> \\<not> distinct3 q r s)\"\nabbreviation \"distinct5 p q r s t \\<equiv> \\<not>(p = q \\<or> p = r \\<or> p = s \\<or> p = t \\<or> \\<not> distinct4 q r s t)\"\n\nabbreviation \"in3 S p q r \\<equiv> p \\<in> S \\<and> q \\<in> S \\<and> r \\<in> S\"\nabbreviation \"in4 S p q r s \\<equiv> in3 S p q r \\<and> s \\<in> S\"\nabbreviation \"in5 S p q r s t \\<equiv> in4 S p q r s \\<and> t \\<in> S\"\n\nlocale ccw_system12 = ccw_system0 +\n  assumes cyclic: \"ccw p q r \\<Longrightarrow> ccw q r p\"\n  assumes ccw_antisym: \"distinct3 p q r \\<Longrightarrow> in3 S p q r \\<Longrightarrow> ccw p q r \\<Longrightarrow> \\<not> ccw p r q\"\n\nlocale ccw_system123 = ccw_system12 +\n  assumes nondegenerate: \"distinct3 p q r \\<Longrightarrow> in3 S p q r \\<Longrightarrow> ccw p q r \\<or> ccw p r q\"\nbegin\n\nlemma not_ccw_eq: \"distinct3 p q r \\<Longrightarrow> in3 S p q r \\<Longrightarrow> \\<not> ccw p q r \\<longleftrightarrow> ccw p r q\"\n  using ccw_antisym nondegenerate by blast\n\nend\n\nlocale ccw_system4 = ccw_system123 +\n  assumes interior:\n    \"distinct4 p q r t \\<Longrightarrow> in4 S p q r t \\<Longrightarrow> ccw t q r \\<Longrightarrow> ccw p t r \\<Longrightarrow> ccw p q t \\<Longrightarrow> ccw p q r\"\nbegin\n\nlemma interior':\n  \"distinct4 p q r t \\<Longrightarrow> in4 S p q r t \\<Longrightarrow> ccw p q t \\<Longrightarrow> ccw q r t \\<Longrightarrow> ccw r p t \\<Longrightarrow> ccw p q r\"\n  by (metis ccw_antisym cyclic interior nondegenerate)\n\nend\n\nlocale ccw_system1235' = ccw_system123 +\n  assumes dual_transitive:\n    \"distinct5 p q r s t \\<Longrightarrow> in5 S p q r s t \\<Longrightarrow>\n      ccw s t p \\<Longrightarrow> ccw s t q \\<Longrightarrow> ccw s t r \\<Longrightarrow> ccw t p q \\<Longrightarrow> ccw t q r \\<Longrightarrow> ccw t p r\"\n\nlocale ccw_system1235 = ccw_system123 +\n  assumes transitive: \"distinct5 p q r s t \\<Longrightarrow> in5 S p q r s t \\<Longrightarrow>\n    ccw t s p \\<Longrightarrow> ccw t s q \\<Longrightarrow> ccw t s r \\<Longrightarrow> ccw t p q \\<Longrightarrow> ccw t q r \\<Longrightarrow> ccw t p r\"\nbegin\n\nlemmas ccw_axioms = cyclic nondegenerate ccw_antisym transitive\n\nsublocale ccw_system1235'\nproof (unfold_locales, rule ccontr, goal_cases)\n  case prems: (1 p q r s t)\n  hence \"ccw s p q \\<Longrightarrow> ccw s r p\"\n    by (metis ccw_axioms prems)\n  moreover\n  have \"ccw s r p \\<Longrightarrow> ccw s q r\"\n    by (metis ccw_axioms prems)\n  moreover\n  have \"ccw s q r \\<Longrightarrow> ccw s p q\"\n    by (metis ccw_axioms prems)\n  ultimately\n  have \"ccw s p q \\<and> ccw s r p \\<and> ccw s q r \\<or> ccw s q p \\<and> ccw s p r \\<and> ccw s r q\"\n    by (metis ccw_axioms prems)\n  thus False\n    by (metis ccw_axioms prems)\nqed\n\nend\n\nlocale ccw_system = ccw_system1235 + ccw_system4\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/Affine_Arithmetic/Counterclockwise.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8539127455162773, "lm_q2_score": 0.8633916134888614, "lm_q1q2_score": 0.7372611031300021}}
{"text": "(*  Title:      HOL/Library/Permutations.thy\n    Author:     Amine Chaieb, University of Cambridge\n*)\n\nsection {* Permutations, both general and specifically on finite sets.*}\n\ntheory Permutations\nimports Fact\nbegin\n\nsubsection {* Transpositions *}\n\nlemma swap_id_idempotent [simp]:\n  \"Fun.swap a b id \\<circ> Fun.swap a b id = id\"\n  by (rule ext, auto simp add: Fun.swap_def)\n\nlemma inv_swap_id:\n  \"inv (Fun.swap a b id) = Fun.swap a b id\"\n  by (rule inv_unique_comp) simp_all\n\nlemma swap_id_eq:\n  \"Fun.swap a b id x = (if x = a then b else if x = b then a else x)\"\n  by (simp add: Fun.swap_def)\n\n\nsubsection {* Basic consequences of the definition *}\n\ndefinition permutes  (infixr \"permutes\" 41)\n  where \"(p permutes S) \\<longleftrightarrow> (\\<forall>x. x \\<notin> S \\<longrightarrow> p x = x) \\<and> (\\<forall>y. \\<exists>!x. p x = y)\"\n\nlemma permutes_in_image: \"p permutes S \\<Longrightarrow> p x \\<in> S \\<longleftrightarrow> x \\<in> S\"\n  unfolding permutes_def by metis\n\nlemma permutes_image: \"p permutes S \\<Longrightarrow> p ` S = S\"\n  unfolding permutes_def\n  apply (rule set_eqI)\n  apply (simp add: image_iff)\n  apply metis\n  done\n\nlemma permutes_inj: \"p permutes S \\<Longrightarrow> inj p\"\n  unfolding permutes_def inj_on_def by blast\n\nlemma permutes_surj: \"p permutes s \\<Longrightarrow> surj p\"\n  unfolding permutes_def surj_def by metis\n\nlemma permutes_inv_o:\n  assumes pS: \"p permutes S\"\n  shows \"p \\<circ> inv p = id\"\n    and \"inv p \\<circ> p = id\"\n  using permutes_inj[OF pS] permutes_surj[OF pS]\n  unfolding inj_iff[symmetric] surj_iff[symmetric] by blast+\n\nlemma permutes_inverses:\n  fixes p :: \"'a \\<Rightarrow> 'a\"\n  assumes pS: \"p permutes S\"\n  shows \"p (inv p x) = x\"\n    and \"inv p (p x) = x\"\n  using permutes_inv_o[OF pS, unfolded fun_eq_iff o_def] by auto\n\nlemma permutes_subset: \"p permutes S \\<Longrightarrow> S \\<subseteq> T \\<Longrightarrow> p permutes T\"\n  unfolding permutes_def by blast\n\nlemma permutes_empty[simp]: \"p permutes {} \\<longleftrightarrow> p = id\"\n  unfolding fun_eq_iff permutes_def by simp metis\n\nlemma permutes_sing[simp]: \"p permutes {a} \\<longleftrightarrow> p = id\"\n  unfolding fun_eq_iff permutes_def by simp metis\n\nlemma permutes_univ: \"p permutes UNIV \\<longleftrightarrow> (\\<forall>y. \\<exists>!x. p x = y)\"\n  unfolding permutes_def by simp\n\nlemma permutes_inv_eq: \"p permutes S \\<Longrightarrow> inv p y = x \\<longleftrightarrow> p x = y\"\n  unfolding permutes_def inv_def\n  apply auto\n  apply (erule allE[where x=y])\n  apply (erule allE[where x=y])\n  apply (rule someI_ex)\n  apply blast\n  apply (rule some1_equality)\n  apply blast\n  apply blast\n  done\n\nlemma permutes_swap_id: \"a \\<in> S \\<Longrightarrow> b \\<in> S \\<Longrightarrow> Fun.swap a b id permutes S\"\n  unfolding permutes_def Fun.swap_def fun_upd_def by auto metis\n\nlemma permutes_superset: \"p permutes S \\<Longrightarrow> (\\<forall>x \\<in> S - T. p x = x) \\<Longrightarrow> p permutes T\"\n  by (simp add: Ball_def permutes_def) metis\n\n\nsubsection {* Group properties *}\n\nlemma permutes_id: \"id permutes S\"\n  unfolding permutes_def by simp\n\nlemma permutes_compose: \"p permutes S \\<Longrightarrow> q permutes S \\<Longrightarrow> q \\<circ> p permutes S\"\n  unfolding permutes_def o_def by metis\n\nlemma permutes_inv:\n  assumes pS: \"p permutes S\"\n  shows \"inv p permutes S\"\n  using pS unfolding permutes_def permutes_inv_eq[OF pS] by metis\n\nlemma permutes_inv_inv:\n  assumes pS: \"p permutes S\"\n  shows \"inv (inv p) = p\"\n  unfolding fun_eq_iff permutes_inv_eq[OF pS] permutes_inv_eq[OF permutes_inv[OF pS]]\n  by blast\n\n\nsubsection {* The number of permutations on a finite set *}\n\nlemma permutes_insert_lemma:\n  assumes pS: \"p permutes (insert a S)\"\n  shows \"Fun.swap a (p a) id \\<circ> p permutes S\"\n  apply (rule permutes_superset[where S = \"insert a S\"])\n  apply (rule permutes_compose[OF pS])\n  apply (rule permutes_swap_id, simp)\n  using permutes_in_image[OF pS, of a]\n  apply simp\n  apply (auto simp add: Ball_def Fun.swap_def)\n  done\n\nlemma permutes_insert: \"{p. p permutes (insert a S)} =\n  (\\<lambda>(b,p). Fun.swap a b id \\<circ> p) ` {(b,p). b \\<in> insert a S \\<and> p \\<in> {p. p permutes S}}\"\nproof -\n  {\n    fix p\n    {\n      assume pS: \"p permutes insert a S\"\n      let ?b = \"p a\"\n      let ?q = \"Fun.swap a (p a) id \\<circ> p\"\n      have th0: \"p = Fun.swap a ?b id \\<circ> ?q\"\n        unfolding fun_eq_iff o_assoc by simp\n      have th1: \"?b \\<in> insert a S\"\n        unfolding permutes_in_image[OF pS] by simp\n      from permutes_insert_lemma[OF pS] th0 th1\n      have \"\\<exists>b q. p = Fun.swap a b id \\<circ> q \\<and> b \\<in> insert a S \\<and> q permutes S\" by blast\n    }\n    moreover\n    {\n      fix b q\n      assume bq: \"p = Fun.swap a b id \\<circ> q\" \"b \\<in> insert a S\" \"q permutes S\"\n      from permutes_subset[OF bq(3), of \"insert a S\"]\n      have qS: \"q permutes insert a S\"\n        by auto\n      have aS: \"a \\<in> insert a S\"\n        by simp\n      from bq(1) permutes_compose[OF qS permutes_swap_id[OF aS bq(2)]]\n      have \"p permutes insert a S\"\n        by simp\n    }\n    ultimately have \"p permutes insert a S \\<longleftrightarrow>\n        (\\<exists>b q. p = Fun.swap a b id \\<circ> q \\<and> b \\<in> insert a S \\<and> q permutes S)\"\n      by blast\n  }\n  then show ?thesis\n    by auto\nqed\n\nlemma card_permutations:\n  assumes Sn: \"card S = n\"\n    and fS: \"finite S\"\n  shows \"card {p. p permutes S} = fact n\"\n  using fS Sn\nproof (induct arbitrary: n)\n  case empty\n  then show ?case by simp\nnext\n  case (insert x F)\n  {\n    fix n\n    assume H0: \"card (insert x F) = n\"\n    let ?xF = \"{p. p permutes insert x F}\"\n    let ?pF = \"{p. p permutes F}\"\n    let ?pF' = \"{(b, p). b \\<in> insert x F \\<and> p \\<in> ?pF}\"\n    let ?g = \"(\\<lambda>(b, p). Fun.swap x b id \\<circ> p)\"\n    from permutes_insert[of x F]\n    have xfgpF': \"?xF = ?g ` ?pF'\" .\n    have Fs: \"card F = n - 1\"\n      using `x \\<notin> F` H0 `finite F` by auto\n    from insert.hyps Fs have pFs: \"card ?pF = fact (n - 1)\"\n      using `finite F` by auto\n    then have \"finite ?pF\"\n      using fact_gt_zero_nat by (auto intro: card_ge_0_finite)\n    then have pF'f: \"finite ?pF'\"\n      using H0 `finite F`\n      apply (simp only: Collect_split Collect_mem_eq)\n      apply (rule finite_cartesian_product)\n      apply simp_all\n      done\n\n    have ginj: \"inj_on ?g ?pF'\"\n    proof -\n      {\n        fix b p c q\n        assume bp: \"(b,p) \\<in> ?pF'\"\n        assume cq: \"(c,q) \\<in> ?pF'\"\n        assume eq: \"?g (b,p) = ?g (c,q)\"\n        from bp cq have ths: \"b \\<in> insert x F\" \"c \\<in> insert x F\" \"x \\<in> insert x F\"\n          \"p permutes F\" \"q permutes F\"\n          by auto\n        from ths(4) `x \\<notin> F` eq have \"b = ?g (b,p) x\"\n          unfolding permutes_def\n          by (auto simp add: Fun.swap_def fun_upd_def fun_eq_iff)\n        also have \"\\<dots> = ?g (c,q) x\"\n          using ths(5) `x \\<notin> F` eq\n          by (auto simp add: swap_def fun_upd_def fun_eq_iff)\n        also have \"\\<dots> = c\"\n          using ths(5) `x \\<notin> F`\n          unfolding permutes_def\n          by (auto simp add: Fun.swap_def fun_upd_def fun_eq_iff)\n        finally have bc: \"b = c\" .\n        then have \"Fun.swap x b id = Fun.swap x c id\"\n          by simp\n        with eq have \"Fun.swap x b id \\<circ> p = Fun.swap x b id \\<circ> q\"\n          by simp\n        then have \"Fun.swap x b id \\<circ> (Fun.swap x b id \\<circ> p) =\n          Fun.swap x b id \\<circ> (Fun.swap x b id \\<circ> q)\"\n          by simp\n        then have \"p = q\"\n          by (simp add: o_assoc)\n        with bc have \"(b, p) = (c, q)\"\n          by simp\n      }\n      then show ?thesis\n        unfolding inj_on_def by blast\n    qed\n    from `x \\<notin> F` H0 have n0: \"n \\<noteq> 0\"\n      using `finite F` by auto\n    then have \"\\<exists>m. n = Suc m\"\n      by presburger\n    then obtain m where n[simp]: \"n = Suc m\"\n      by blast\n    from pFs H0 have xFc: \"card ?xF = fact n\"\n      unfolding xfgpF' card_image[OF ginj]\n      using `finite F` `finite ?pF`\n      apply (simp only: Collect_split Collect_mem_eq card_cartesian_product)\n      apply simp\n      done\n    from finite_imageI[OF pF'f, of ?g] have xFf: \"finite ?xF\"\n      unfolding xfgpF' by simp\n    have \"card ?xF = fact n\"\n      using xFf xFc unfolding xFf by blast\n  }\n  then show ?case\n    using insert by simp\nqed\n\nlemma finite_permutations:\n  assumes fS: \"finite S\"\n  shows \"finite {p. p permutes S}\"\n  using card_permutations[OF refl fS] fact_gt_zero_nat\n  by (auto intro: card_ge_0_finite)\n\n\nsubsection {* Permutations of index set for iterated operations *}\n\nlemma (in comm_monoid_set) permute:\n  assumes \"p permutes S\"\n  shows \"F g S = F (g \\<circ> p) S\"\nproof -\n  from `p permutes S` have \"inj p\"\n    by (rule permutes_inj)\n  then have \"inj_on p S\"\n    by (auto intro: subset_inj_on)\n  then have \"F g (p ` S) = F (g \\<circ> p) S\"\n    by (rule reindex)\n  moreover from `p permutes S` have \"p ` S = S\"\n    by (rule permutes_image)\n  ultimately show ?thesis\n    by simp\nqed\n\nlemma setsum_permute:\n  assumes \"p permutes S\"\n  shows \"setsum f S = setsum (f \\<circ> p) S\"\n  using assms by (fact setsum.permute)\n\nlemma setsum_permute_natseg:\n  assumes pS: \"p permutes {m .. n}\"\n  shows \"setsum f {m .. n} = setsum (f \\<circ> p) {m .. n}\"\n  using setsum_permute [OF pS, of f ] pS by blast\n\nlemma setprod_permute:\n  assumes \"p permutes S\"\n  shows \"setprod f S = setprod (f \\<circ> p) S\"\n  using assms by (fact setprod.permute)\n\nlemma setprod_permute_natseg:\n  assumes pS: \"p permutes {m .. n}\"\n  shows \"setprod f {m .. n} = setprod (f \\<circ> p) {m .. n}\"\n  using setprod_permute [OF pS, of f ] pS by blast\n\n\nsubsection {* Various combinations of transpositions with 2, 1 and 0 common elements *}\n\nlemma swap_id_common:\" a \\<noteq> c \\<Longrightarrow> b \\<noteq> c \\<Longrightarrow>\n  Fun.swap a b id \\<circ> Fun.swap a c id = Fun.swap b c id \\<circ> Fun.swap a b id\"\n  by (simp add: fun_eq_iff Fun.swap_def)\n\nlemma swap_id_common': \"a \\<noteq> b \\<Longrightarrow> a \\<noteq> c \\<Longrightarrow>\n  Fun.swap a c id \\<circ> Fun.swap b c id = Fun.swap b c id \\<circ> Fun.swap a b id\"\n  by (simp add: fun_eq_iff Fun.swap_def)\n\nlemma swap_id_independent: \"a \\<noteq> c \\<Longrightarrow> a \\<noteq> d \\<Longrightarrow> b \\<noteq> c \\<Longrightarrow> b \\<noteq> d \\<Longrightarrow>\n  Fun.swap a b id \\<circ> Fun.swap c d id = Fun.swap c d id \\<circ> Fun.swap a b id\"\n  by (simp add: fun_eq_iff Fun.swap_def)\n\n\nsubsection {* Permutations as transposition sequences *}\n\ninductive swapidseq :: \"nat \\<Rightarrow> ('a \\<Rightarrow> 'a) \\<Rightarrow> bool\"\nwhere\n  id[simp]: \"swapidseq 0 id\"\n| comp_Suc: \"swapidseq n p \\<Longrightarrow> a \\<noteq> b \\<Longrightarrow> swapidseq (Suc n) (Fun.swap a b id \\<circ> p)\"\n\ndeclare id[unfolded id_def, simp]\n\ndefinition \"permutation p \\<longleftrightarrow> (\\<exists>n. swapidseq n p)\"\n\n\nsubsection {* Some closure properties of the set of permutations, with lengths *}\n\nlemma permutation_id[simp]: \"permutation id\"\n  unfolding permutation_def by (rule exI[where x=0]) simp\n\ndeclare permutation_id[unfolded id_def, simp]\n\nlemma swapidseq_swap: \"swapidseq (if a = b then 0 else 1) (Fun.swap a b id)\"\n  apply clarsimp\n  using comp_Suc[of 0 id a b]\n  apply simp\n  done\n\nlemma permutation_swap_id: \"permutation (Fun.swap a b id)\"\n  apply (cases \"a = b\")\n  apply simp_all\n  unfolding permutation_def\n  using swapidseq_swap[of a b]\n  apply blast\n  done\n\nlemma swapidseq_comp_add: \"swapidseq n p \\<Longrightarrow> swapidseq m q \\<Longrightarrow> swapidseq (n + m) (p \\<circ> q)\"\nproof (induct n p arbitrary: m q rule: swapidseq.induct)\n  case (id m q)\n  then show ?case by simp\nnext\n  case (comp_Suc n p a b m q)\n  have th: \"Suc n + m = Suc (n + m)\"\n    by arith\n  show ?case\n    unfolding th comp_assoc\n    apply (rule swapidseq.comp_Suc)\n    using comp_Suc.hyps(2)[OF comp_Suc.prems] comp_Suc.hyps(3)\n    apply blast+\n    done\nqed\n\nlemma permutation_compose: \"permutation p \\<Longrightarrow> permutation q \\<Longrightarrow> permutation (p \\<circ> q)\"\n  unfolding permutation_def using swapidseq_comp_add[of _ p _ q] by metis\n\nlemma swapidseq_endswap: \"swapidseq n p \\<Longrightarrow> a \\<noteq> b \\<Longrightarrow> swapidseq (Suc n) (p \\<circ> Fun.swap a b id)\"\n  apply (induct n p rule: swapidseq.induct)\n  using swapidseq_swap[of a b]\n  apply (auto simp add: comp_assoc intro: swapidseq.comp_Suc)\n  done\n\nlemma swapidseq_inverse_exists: \"swapidseq n p \\<Longrightarrow> \\<exists>q. swapidseq n q \\<and> p \\<circ> q = id \\<and> q \\<circ> p = id\"\nproof (induct n p rule: swapidseq.induct)\n  case id\n  then show ?case\n    by (rule exI[where x=id]) simp\nnext\n  case (comp_Suc n p a b)\n  from comp_Suc.hyps obtain q where q: \"swapidseq n q\" \"p \\<circ> q = id\" \"q \\<circ> p = id\"\n    by blast\n  let ?q = \"q \\<circ> Fun.swap a b id\"\n  note H = comp_Suc.hyps\n  from swapidseq_swap[of a b] H(3) have th0: \"swapidseq 1 (Fun.swap a b id)\"\n    by simp\n  from swapidseq_comp_add[OF q(1) th0] have th1: \"swapidseq (Suc n) ?q\"\n    by simp\n  have \"Fun.swap a b id \\<circ> p \\<circ> ?q = Fun.swap a b id \\<circ> (p \\<circ> q) \\<circ> Fun.swap a b id\"\n    by (simp add: o_assoc)\n  also have \"\\<dots> = id\"\n    by (simp add: q(2))\n  finally have th2: \"Fun.swap a b id \\<circ> p \\<circ> ?q = id\" .\n  have \"?q \\<circ> (Fun.swap a b id \\<circ> p) = q \\<circ> (Fun.swap a b id \\<circ> Fun.swap a b id) \\<circ> p\"\n    by (simp only: o_assoc)\n  then have \"?q \\<circ> (Fun.swap a b id \\<circ> p) = id\"\n    by (simp add: q(3))\n  with th1 th2 show ?case\n    by blast\nqed\n\nlemma swapidseq_inverse:\n  assumes H: \"swapidseq n p\"\n  shows \"swapidseq n (inv p)\"\n  using swapidseq_inverse_exists[OF H] inv_unique_comp[of p] by auto\n\nlemma permutation_inverse: \"permutation p \\<Longrightarrow> permutation (inv p)\"\n  using permutation_def swapidseq_inverse by blast\n\n\nsubsection {* The identity map only has even transposition sequences *}\n\nlemma symmetry_lemma:\n  assumes \"\\<And>a b c d. P a b c d \\<Longrightarrow> P a b d c\"\n    and \"\\<And>a b c d. a \\<noteq> b \\<Longrightarrow> c \\<noteq> d \\<Longrightarrow>\n      a = c \\<and> b = d \\<or> a = c \\<and> b \\<noteq> d \\<or> a \\<noteq> c \\<and> b = d \\<or> a \\<noteq> c \\<and> a \\<noteq> d \\<and> b \\<noteq> c \\<and> b \\<noteq> d \\<Longrightarrow>\n      P a b c d\"\n  shows \"\\<And>a b c d. a \\<noteq> b \\<longrightarrow> c \\<noteq> d \\<longrightarrow>  P a b c d\"\n  using assms by metis\n\nlemma swap_general: \"a \\<noteq> b \\<Longrightarrow> c \\<noteq> d \\<Longrightarrow>\n  Fun.swap a b id \\<circ> Fun.swap c d id = id \\<or>\n  (\\<exists>x y z. x \\<noteq> a \\<and> y \\<noteq> a \\<and> z \\<noteq> a \\<and> x \\<noteq> y \\<and>\n    Fun.swap a b id \\<circ> Fun.swap c d id = Fun.swap x y id \\<circ> Fun.swap a z id)\"\nproof -\n  assume H: \"a \\<noteq> b\" \"c \\<noteq> d\"\n  have \"a \\<noteq> b \\<longrightarrow> c \\<noteq> d \\<longrightarrow>\n    (Fun.swap a b id \\<circ> Fun.swap c d id = id \\<or>\n      (\\<exists>x y z. x \\<noteq> a \\<and> y \\<noteq> a \\<and> z \\<noteq> a \\<and> x \\<noteq> y \\<and>\n        Fun.swap a b id \\<circ> Fun.swap c d id = Fun.swap x y id \\<circ> Fun.swap a z id))\"\n    apply (rule symmetry_lemma[where a=a and b=b and c=c and d=d])\n    apply (simp_all only: swap_commute)\n    apply (case_tac \"a = c \\<and> b = d\")\n    apply (clarsimp simp only: swap_commute swap_id_idempotent)\n    apply (case_tac \"a = c \\<and> b \\<noteq> d\")\n    apply (rule disjI2)\n    apply (rule_tac x=\"b\" in exI)\n    apply (rule_tac x=\"d\" in exI)\n    apply (rule_tac x=\"b\" in exI)\n    apply (clarsimp simp add: fun_eq_iff Fun.swap_def)\n    apply (case_tac \"a \\<noteq> c \\<and> b = d\")\n    apply (rule disjI2)\n    apply (rule_tac x=\"c\" in exI)\n    apply (rule_tac x=\"d\" in exI)\n    apply (rule_tac x=\"c\" in exI)\n    apply (clarsimp simp add: fun_eq_iff Fun.swap_def)\n    apply (rule disjI2)\n    apply (rule_tac x=\"c\" in exI)\n    apply (rule_tac x=\"d\" in exI)\n    apply (rule_tac x=\"b\" in exI)\n    apply (clarsimp simp add: fun_eq_iff Fun.swap_def)\n    done\n  with H show ?thesis by metis\nqed\n\nlemma swapidseq_id_iff[simp]: \"swapidseq 0 p \\<longleftrightarrow> p = id\"\n  using swapidseq.cases[of 0 p \"p = id\"]\n  by auto\n\nlemma swapidseq_cases: \"swapidseq n p \\<longleftrightarrow>\n  n = 0 \\<and> p = id \\<or> (\\<exists>a b q m. n = Suc m \\<and> p = Fun.swap a b id \\<circ> q \\<and> swapidseq m q \\<and> a \\<noteq> b)\"\n  apply (rule iffI)\n  apply (erule swapidseq.cases[of n p])\n  apply simp\n  apply (rule disjI2)\n  apply (rule_tac x= \"a\" in exI)\n  apply (rule_tac x= \"b\" in exI)\n  apply (rule_tac x= \"pa\" in exI)\n  apply (rule_tac x= \"na\" in exI)\n  apply simp\n  apply auto\n  apply (rule comp_Suc, simp_all)\n  done\n\nlemma fixing_swapidseq_decrease:\n  assumes spn: \"swapidseq n p\"\n    and ab: \"a \\<noteq> b\"\n    and pa: \"(Fun.swap a b id \\<circ> p) a = a\"\n  shows \"n \\<noteq> 0 \\<and> swapidseq (n - 1) (Fun.swap a b id \\<circ> p)\"\n  using spn ab pa\nproof (induct n arbitrary: p a b)\n  case 0\n  then show ?case\n    by (auto simp add: Fun.swap_def fun_upd_def)\nnext\n  case (Suc n p a b)\n  from Suc.prems(1) swapidseq_cases[of \"Suc n\" p]\n  obtain c d q m where\n    cdqm: \"Suc n = Suc m\" \"p = Fun.swap c d id \\<circ> q\" \"swapidseq m q\" \"c \\<noteq> d\" \"n = m\"\n    by auto\n  {\n    assume H: \"Fun.swap a b id \\<circ> Fun.swap c d id = id\"\n    have ?case by (simp only: cdqm o_assoc H) (simp add: cdqm)\n  }\n  moreover\n  {\n    fix x y z\n    assume H: \"x \\<noteq> a\" \"y \\<noteq> a\" \"z \\<noteq> a\" \"x \\<noteq> y\"\n      \"Fun.swap a b id \\<circ> Fun.swap c d id = Fun.swap x y id \\<circ> Fun.swap a z id\"\n    from H have az: \"a \\<noteq> z\"\n      by simp\n\n    {\n      fix h\n      have \"(Fun.swap x y id \\<circ> h) a = a \\<longleftrightarrow> h a = a\"\n        using H by (simp add: Fun.swap_def)\n    }\n    note th3 = this\n    from cdqm(2) have \"Fun.swap a b id \\<circ> p = Fun.swap a b id \\<circ> (Fun.swap c d id \\<circ> q)\"\n      by simp\n    then have \"Fun.swap a b id \\<circ> p = Fun.swap x y id \\<circ> (Fun.swap a z id \\<circ> q)\"\n      by (simp add: o_assoc H)\n    then have \"(Fun.swap a b id \\<circ> p) a = (Fun.swap x y id \\<circ> (Fun.swap a z id \\<circ> q)) a\"\n      by simp\n    then have \"(Fun.swap x y id \\<circ> (Fun.swap a z id \\<circ> q)) a = a\"\n      unfolding Suc by metis\n    then have th1: \"(Fun.swap a z id \\<circ> q) a = a\"\n      unfolding th3 .\n    from Suc.hyps[OF cdqm(3)[ unfolded cdqm(5)[symmetric]] az th1]\n    have th2: \"swapidseq (n - 1) (Fun.swap a z id \\<circ> q)\" \"n \\<noteq> 0\"\n      by blast+\n    have th: \"Suc n - 1 = Suc (n - 1)\"\n      using th2(2) by auto\n    have ?case\n      unfolding cdqm(2) H o_assoc th\n      apply (simp only: Suc_not_Zero simp_thms comp_assoc)\n      apply (rule comp_Suc)\n      using th2 H\n      apply blast+\n      done\n  }\n  ultimately show ?case\n    using swap_general[OF Suc.prems(2) cdqm(4)] by metis\nqed\n\nlemma swapidseq_identity_even:\n  assumes \"swapidseq n (id :: 'a \\<Rightarrow> 'a)\"\n  shows \"even n\"\n  using `swapidseq n id`\nproof (induct n rule: nat_less_induct)\n  fix n\n  assume H: \"\\<forall>m<n. swapidseq m (id::'a \\<Rightarrow> 'a) \\<longrightarrow> even m\" \"swapidseq n (id :: 'a \\<Rightarrow> 'a)\"\n  {\n    assume \"n = 0\"\n    then have \"even n\" by presburger\n  }\n  moreover\n  {\n    fix a b :: 'a and q m\n    assume h: \"n = Suc m\" \"(id :: 'a \\<Rightarrow> 'a) = Fun.swap a b id \\<circ> q\" \"swapidseq m q\" \"a \\<noteq> b\"\n    from fixing_swapidseq_decrease[OF h(3,4), unfolded h(2)[symmetric]]\n    have m: \"m \\<noteq> 0\" \"swapidseq (m - 1) (id :: 'a \\<Rightarrow> 'a)\"\n      by auto\n    from h m have mn: \"m - 1 < n\"\n      by arith\n    from H(1)[rule_format, OF mn m(2)] h(1) m(1) have \"even n\"\n      by presburger\n  }\n  ultimately show \"even n\"\n    using H(2)[unfolded swapidseq_cases[of n id]] by auto\nqed\n\n\nsubsection {* Therefore we have a welldefined notion of parity *}\n\ndefinition \"evenperm p = even (SOME n. swapidseq n p)\"\n\nlemma swapidseq_even_even:\n  assumes m: \"swapidseq m p\"\n    and n: \"swapidseq n p\"\n  shows \"even m \\<longleftrightarrow> even n\"\nproof -\n  from swapidseq_inverse_exists[OF n]\n  obtain q where q: \"swapidseq n q\" \"p \\<circ> q = id\" \"q \\<circ> p = id\"\n    by blast\n  from swapidseq_identity_even[OF swapidseq_comp_add[OF m q(1), unfolded q]]\n  show ?thesis\n    by arith\nqed\n\nlemma evenperm_unique:\n  assumes p: \"swapidseq n p\"\n    and n:\"even n = b\"\n  shows \"evenperm p = b\"\n  unfolding n[symmetric] evenperm_def\n  apply (rule swapidseq_even_even[where p = p])\n  apply (rule someI[where x = n])\n  using p\n  apply blast+\n  done\n\n\nsubsection {* And it has the expected composition properties *}\n\nlemma evenperm_id[simp]: \"evenperm id = True\"\n  by (rule evenperm_unique[where n = 0]) simp_all\n\nlemma evenperm_swap: \"evenperm (Fun.swap a b id) = (a = b)\"\n  by (rule evenperm_unique[where n=\"if a = b then 0 else 1\"]) (simp_all add: swapidseq_swap)\n\nlemma evenperm_comp:\n  assumes p: \"permutation p\"\n    and q:\"permutation q\"\n  shows \"evenperm (p \\<circ> q) = (evenperm p = evenperm q)\"\nproof -\n  from p q obtain n m where n: \"swapidseq n p\" and m: \"swapidseq m q\"\n    unfolding permutation_def by blast\n  note nm =  swapidseq_comp_add[OF n m]\n  have th: \"even (n + m) = (even n \\<longleftrightarrow> even m)\"\n    by arith\n  from evenperm_unique[OF n refl] evenperm_unique[OF m refl]\n    evenperm_unique[OF nm th]\n  show ?thesis\n    by blast\nqed\n\nlemma evenperm_inv:\n  assumes p: \"permutation p\"\n  shows \"evenperm (inv p) = evenperm p\"\nproof -\n  from p obtain n where n: \"swapidseq n p\"\n    unfolding permutation_def by blast\n  from evenperm_unique[OF swapidseq_inverse[OF n] evenperm_unique[OF n refl, symmetric]]\n  show ?thesis .\nqed\n\n\nsubsection {* A more abstract characterization of permutations *}\n\nlemma bij_iff: \"bij f \\<longleftrightarrow> (\\<forall>x. \\<exists>!y. f y = x)\"\n  unfolding bij_def inj_on_def surj_def\n  apply auto\n  apply metis\n  apply metis\n  done\n\nlemma permutation_bijective:\n  assumes p: \"permutation p\"\n  shows \"bij p\"\nproof -\n  from p obtain n where n: \"swapidseq n p\"\n    unfolding permutation_def by blast\n  from swapidseq_inverse_exists[OF n]\n  obtain q where q: \"swapidseq n q\" \"p \\<circ> q = id\" \"q \\<circ> p = id\"\n    by blast\n  then show ?thesis unfolding bij_iff\n    apply (auto simp add: fun_eq_iff)\n    apply metis\n    done\nqed\n\nlemma permutation_finite_support:\n  assumes p: \"permutation p\"\n  shows \"finite {x. p x \\<noteq> x}\"\nproof -\n  from p obtain n where n: \"swapidseq n p\"\n    unfolding permutation_def by blast\n  from n show ?thesis\n  proof (induct n p rule: swapidseq.induct)\n    case id\n    then show ?case by simp\n  next\n    case (comp_Suc n p a b)\n    let ?S = \"insert a (insert b {x. p x \\<noteq> x})\"\n    from comp_Suc.hyps(2) have fS: \"finite ?S\"\n      by simp\n    from `a \\<noteq> b` have th: \"{x. (Fun.swap a b id \\<circ> p) x \\<noteq> x} \\<subseteq> ?S\"\n      by (auto simp add: Fun.swap_def)\n    from finite_subset[OF th fS] show ?case  .\n  qed\nqed\n\nlemma bij_inv_eq_iff: \"bij p \\<Longrightarrow> x = inv p y \\<longleftrightarrow> p x = y\"\n  using surj_f_inv_f[of p] by (auto simp add: bij_def)\n\nlemma bij_swap_comp:\n  assumes bp: \"bij p\"\n  shows \"Fun.swap a b id \\<circ> p = Fun.swap (inv p a) (inv p b) p\"\n  using surj_f_inv_f[OF bij_is_surj[OF bp]]\n  by (simp add: fun_eq_iff Fun.swap_def bij_inv_eq_iff[OF bp])\n\nlemma bij_swap_ompose_bij: \"bij p \\<Longrightarrow> bij (Fun.swap a b id \\<circ> p)\"\nproof -\n  assume H: \"bij p\"\n  show ?thesis\n    unfolding bij_swap_comp[OF H] bij_swap_iff\n    using H .\nqed\n\nlemma permutation_lemma:\n  assumes fS: \"finite S\"\n    and p: \"bij p\"\n    and pS: \"\\<forall>x. x\\<notin> S \\<longrightarrow> p x = x\"\n  shows \"permutation p\"\n  using fS p pS\nproof (induct S arbitrary: p rule: finite_induct)\n  case (empty p)\n  then show ?case by simp\nnext\n  case (insert a F p)\n  let ?r = \"Fun.swap a (p a) id \\<circ> p\"\n  let ?q = \"Fun.swap a (p a) id \\<circ> ?r\"\n  have raa: \"?r a = a\"\n    by (simp add: Fun.swap_def)\n  from bij_swap_ompose_bij[OF insert(4)]\n  have br: \"bij ?r\"  .\n\n  from insert raa have th: \"\\<forall>x. x \\<notin> F \\<longrightarrow> ?r x = x\"\n    apply (clarsimp simp add: Fun.swap_def)\n    apply (erule_tac x=\"x\" in allE)\n    apply auto\n    unfolding bij_iff\n    apply metis\n    done\n  from insert(3)[OF br th]\n  have rp: \"permutation ?r\" .\n  have \"permutation ?q\"\n    by (simp add: permutation_compose permutation_swap_id rp)\n  then show ?case\n    by (simp add: o_assoc)\nqed\n\nlemma permutation: \"permutation p \\<longleftrightarrow> bij p \\<and> finite {x. p x \\<noteq> x}\"\n  (is \"?lhs \\<longleftrightarrow> ?b \\<and> ?f\")\nproof\n  assume p: ?lhs\n  from p permutation_bijective permutation_finite_support show \"?b \\<and> ?f\"\n    by auto\nnext\n  assume \"?b \\<and> ?f\"\n  then have \"?f\" \"?b\" by blast+\n  from permutation_lemma[OF this] show ?lhs\n    by blast\nqed\n\nlemma permutation_inverse_works:\n  assumes p: \"permutation p\"\n  shows \"inv p \\<circ> p = id\"\n    and \"p \\<circ> inv p = id\"\n  using permutation_bijective [OF p]\n  unfolding bij_def inj_iff surj_iff by auto\n\nlemma permutation_inverse_compose:\n  assumes p: \"permutation p\"\n    and q: \"permutation q\"\n  shows \"inv (p \\<circ> q) = inv q \\<circ> inv p\"\nproof -\n  note ps = permutation_inverse_works[OF p]\n  note qs = permutation_inverse_works[OF q]\n  have \"p \\<circ> q \\<circ> (inv q \\<circ> inv p) = p \\<circ> (q \\<circ> inv q) \\<circ> inv p\"\n    by (simp add: o_assoc)\n  also have \"\\<dots> = id\"\n    by (simp add: ps qs)\n  finally have th0: \"p \\<circ> q \\<circ> (inv q \\<circ> inv p) = id\" .\n  have \"inv q \\<circ> inv p \\<circ> (p \\<circ> q) = inv q \\<circ> (inv p \\<circ> p) \\<circ> q\"\n    by (simp add: o_assoc)\n  also have \"\\<dots> = id\"\n    by (simp add: ps qs)\n  finally have th1: \"inv q \\<circ> inv p \\<circ> (p \\<circ> q) = id\" .\n  from inv_unique_comp[OF th0 th1] show ?thesis .\nqed\n\n\nsubsection {* Relation to \"permutes\" *}\n\nlemma permutation_permutes: \"permutation p \\<longleftrightarrow> (\\<exists>S. finite S \\<and> p permutes S)\"\n  unfolding permutation permutes_def bij_iff[symmetric]\n  apply (rule iffI, clarify)\n  apply (rule exI[where x=\"{x. p x \\<noteq> x}\"])\n  apply simp\n  apply clarsimp\n  apply (rule_tac B=\"S\" in finite_subset)\n  apply auto\n  done\n\n\nsubsection {* Hence a sort of induction principle composing by swaps *}\n\nlemma permutes_induct: \"finite S \\<Longrightarrow> P id \\<Longrightarrow>\n  (\\<And> a b p. a \\<in> S \\<Longrightarrow> b \\<in> S \\<Longrightarrow> P p \\<Longrightarrow> P p \\<Longrightarrow> permutation p \\<Longrightarrow> P (Fun.swap a b id \\<circ> p)) \\<Longrightarrow>\n  (\\<And>p. p permutes S \\<Longrightarrow> P p)\"\nproof (induct S rule: finite_induct)\n  case empty\n  then show ?case by auto\nnext\n  case (insert x F p)\n  let ?r = \"Fun.swap x (p x) id \\<circ> p\"\n  let ?q = \"Fun.swap x (p x) id \\<circ> ?r\"\n  have qp: \"?q = p\"\n    by (simp add: o_assoc)\n  from permutes_insert_lemma[OF insert.prems(3)] insert have Pr: \"P ?r\"\n    by blast\n  from permutes_in_image[OF insert.prems(3), of x]\n  have pxF: \"p x \\<in> insert x F\"\n    by simp\n  have xF: \"x \\<in> insert x F\"\n    by simp\n  have rp: \"permutation ?r\"\n    unfolding permutation_permutes using insert.hyps(1)\n      permutes_insert_lemma[OF insert.prems(3)]\n    by blast\n  from insert.prems(2)[OF xF pxF Pr Pr rp]\n  show ?case\n    unfolding qp .\nqed\n\n\nsubsection {* Sign of a permutation as a real number *}\n\ndefinition \"sign p = (if evenperm p then (1::int) else -1)\"\n\nlemma sign_nz: \"sign p \\<noteq> 0\"\n  by (simp add: sign_def)\n\nlemma sign_id: \"sign id = 1\"\n  by (simp add: sign_def)\n\nlemma sign_inverse: \"permutation p \\<Longrightarrow> sign (inv p) = sign p\"\n  by (simp add: sign_def evenperm_inv)\n\nlemma sign_compose: \"permutation p \\<Longrightarrow> permutation q \\<Longrightarrow> sign (p \\<circ> q) = sign p * sign q\"\n  by (simp add: sign_def evenperm_comp)\n\nlemma sign_swap_id: \"sign (Fun.swap a b id) = (if a = b then 1 else -1)\"\n  by (simp add: sign_def evenperm_swap)\n\nlemma sign_idempotent: \"sign p * sign p = 1\"\n  by (simp add: sign_def)\n\n\nsubsection {* More lemmas about permutations *}\n\nlemma permutes_natset_le:\n  fixes S :: \"'a::wellorder set\"\n  assumes p: \"p permutes S\"\n    and le: \"\\<forall>i \\<in> S. p i \\<le> i\"\n  shows \"p = id\"\nproof -\n  {\n    fix n\n    have \"p n = n\"\n      using p le\n    proof (induct n arbitrary: S rule: less_induct)\n      fix n S\n      assume H:\n        \"\\<And>m S. m < n \\<Longrightarrow> p permutes S \\<Longrightarrow> \\<forall>i\\<in>S. p i \\<le> i \\<Longrightarrow> p m = m\"\n        \"p permutes S\" \"\\<forall>i \\<in>S. p i \\<le> i\"\n      {\n        assume \"n \\<notin> S\"\n        with H(2) have \"p n = n\"\n          unfolding permutes_def by metis\n      }\n      moreover\n      {\n        assume ns: \"n \\<in> S\"\n        from H(3)  ns have \"p n < n \\<or> p n = n\"\n          by auto\n        moreover {\n          assume h: \"p n < n\"\n          from H h have \"p (p n) = p n\"\n            by metis\n          with permutes_inj[OF H(2)] have \"p n = n\"\n            unfolding inj_on_def by blast\n          with h have False\n            by simp\n        }\n        ultimately have \"p n = n\"\n          by blast\n      }\n      ultimately show \"p n = n\"\n        by blast\n    qed\n  }\n  then show ?thesis\n    by (auto simp add: fun_eq_iff)\nqed\n\nlemma permutes_natset_ge:\n  fixes S :: \"'a::wellorder set\"\n  assumes p: \"p permutes S\"\n    and le: \"\\<forall>i \\<in> S. p i \\<ge> i\"\n  shows \"p = id\"\nproof -\n  {\n    fix i\n    assume i: \"i \\<in> S\"\n    from i permutes_in_image[OF permutes_inv[OF p]] have \"inv p i \\<in> S\"\n      by simp\n    with le have \"p (inv p i) \\<ge> inv p i\"\n      by blast\n    with permutes_inverses[OF p] have \"i \\<ge> inv p i\"\n      by simp\n  }\n  then have th: \"\\<forall>i\\<in>S. inv p i \\<le> i\"\n    by blast\n  from permutes_natset_le[OF permutes_inv[OF p] th]\n  have \"inv p = inv id\"\n    by simp\n  then show ?thesis\n    apply (subst permutes_inv_inv[OF p, symmetric])\n    apply (rule inv_unique_comp)\n    apply simp_all\n    done\nqed\n\nlemma image_inverse_permutations: \"{inv p |p. p permutes S} = {p. p permutes S}\"\n  apply (rule set_eqI)\n  apply auto\n  using permutes_inv_inv permutes_inv\n  apply auto\n  apply (rule_tac x=\"inv x\" in exI)\n  apply auto\n  done\n\nlemma image_compose_permutations_left:\n  assumes q: \"q permutes S\"\n  shows \"{q \\<circ> p | p. p permutes S} = {p . p permutes S}\"\n  apply (rule set_eqI)\n  apply auto\n  apply (rule permutes_compose)\n  using q\n  apply auto\n  apply (rule_tac x = \"inv q \\<circ> x\" in exI)\n  apply (simp add: o_assoc permutes_inv permutes_compose permutes_inv_o)\n  done\n\nlemma image_compose_permutations_right:\n  assumes q: \"q permutes S\"\n  shows \"{p \\<circ> q | p. p permutes S} = {p . p permutes S}\"\n  apply (rule set_eqI)\n  apply auto\n  apply (rule permutes_compose)\n  using q\n  apply auto\n  apply (rule_tac x = \"x \\<circ> inv q\" in exI)\n  apply (simp add: o_assoc permutes_inv permutes_compose permutes_inv_o comp_assoc)\n  done\n\nlemma permutes_in_seg: \"p permutes {1 ..n} \\<Longrightarrow> i \\<in> {1..n} \\<Longrightarrow> 1 \\<le> p i \\<and> p i \\<le> n\"\n  by (simp add: permutes_def) metis\n\nlemma setsum_permutations_inverse:\n  \"setsum f {p. p permutes S} = setsum (\\<lambda>p. f(inv p)) {p. p permutes S}\"\n  (is \"?lhs = ?rhs\")\nproof -\n  let ?S = \"{p . p permutes S}\"\n  have th0: \"inj_on inv ?S\"\n  proof (auto simp add: inj_on_def)\n    fix q r\n    assume q: \"q permutes S\"\n      and r: \"r permutes S\"\n      and qr: \"inv q = inv r\"\n    then have \"inv (inv q) = inv (inv r)\"\n      by simp\n    with permutes_inv_inv[OF q] permutes_inv_inv[OF r] show \"q = r\"\n      by metis\n  qed\n  have th1: \"inv ` ?S = ?S\"\n    using image_inverse_permutations by blast\n  have th2: \"?rhs = setsum (f \\<circ> inv) ?S\"\n    by (simp add: o_def)\n  from setsum.reindex[OF th0, of f] show ?thesis unfolding th1 th2 .\nqed\n\nlemma setum_permutations_compose_left:\n  assumes q: \"q permutes S\"\n  shows \"setsum f {p. p permutes S} = setsum (\\<lambda>p. f(q \\<circ> p)) {p. p permutes S}\"\n  (is \"?lhs = ?rhs\")\nproof -\n  let ?S = \"{p. p permutes S}\"\n  have th0: \"?rhs = setsum (f \\<circ> (op \\<circ> q)) ?S\"\n    by (simp add: o_def)\n  have th1: \"inj_on (op \\<circ> q) ?S\"\n  proof (auto simp add: inj_on_def)\n    fix p r\n    assume \"p permutes S\"\n      and r: \"r permutes S\"\n      and rp: \"q \\<circ> p = q \\<circ> r\"\n    then have \"inv q \\<circ> q \\<circ> p = inv q \\<circ> q \\<circ> r\"\n      by (simp add: comp_assoc)\n    with permutes_inj[OF q, unfolded inj_iff] show \"p = r\"\n      by simp\n  qed\n  have th3: \"(op \\<circ> q) ` ?S = ?S\"\n    using image_compose_permutations_left[OF q] by auto\n  from setsum.reindex[OF th1, of f] show ?thesis unfolding th0 th1 th3 .\nqed\n\nlemma sum_permutations_compose_right:\n  assumes q: \"q permutes S\"\n  shows \"setsum f {p. p permutes S} = setsum (\\<lambda>p. f(p \\<circ> q)) {p. p permutes S}\"\n  (is \"?lhs = ?rhs\")\nproof -\n  let ?S = \"{p. p permutes S}\"\n  have th0: \"?rhs = setsum (f \\<circ> (\\<lambda>p. p \\<circ> q)) ?S\"\n    by (simp add: o_def)\n  have th1: \"inj_on (\\<lambda>p. p \\<circ> q) ?S\"\n  proof (auto simp add: inj_on_def)\n    fix p r\n    assume \"p permutes S\"\n      and r: \"r permutes S\"\n      and rp: \"p \\<circ> q = r \\<circ> q\"\n    then have \"p \\<circ> (q \\<circ> inv q) = r \\<circ> (q \\<circ> inv q)\"\n      by (simp add: o_assoc)\n    with permutes_surj[OF q, unfolded surj_iff] show \"p = r\"\n      by simp\n  qed\n  have th3: \"(\\<lambda>p. p \\<circ> q) ` ?S = ?S\"\n    using image_compose_permutations_right[OF q] by auto\n  from setsum.reindex[OF th1, of f]\n  show ?thesis unfolding th0 th1 th3 .\nqed\n\n\nsubsection {* Sum over a set of permutations (could generalize to iteration) *}\n\nlemma setsum_over_permutations_insert:\n  assumes fS: \"finite S\"\n    and aS: \"a \\<notin> S\"\n  shows \"setsum f {p. p permutes (insert a S)} =\n    setsum (\\<lambda>b. setsum (\\<lambda>q. f (Fun.swap a b id \\<circ> q)) {p. p permutes S}) (insert a S)\"\nproof -\n  have th0: \"\\<And>f a b. (\\<lambda>(b,p). f (Fun.swap a b id \\<circ> p)) = f \\<circ> (\\<lambda>(b,p). Fun.swap a b id \\<circ> p)\"\n    by (simp add: fun_eq_iff)\n  have th1: \"\\<And>P Q. P \\<times> Q = {(a,b). a \\<in> P \\<and> b \\<in> Q}\"\n    by blast\n  have th2: \"\\<And>P Q. P \\<Longrightarrow> (P \\<Longrightarrow> Q) \\<Longrightarrow> P \\<and> Q\"\n    by blast\n  show ?thesis\n    unfolding permutes_insert\n    unfolding setsum.cartesian_product\n    unfolding th1[symmetric]\n    unfolding th0\n  proof (rule setsum.reindex)\n    let ?f = \"(\\<lambda>(b, y). Fun.swap a b id \\<circ> y)\"\n    let ?P = \"{p. p permutes S}\"\n    {\n      fix b c p q\n      assume b: \"b \\<in> insert a S\"\n      assume c: \"c \\<in> insert a S\"\n      assume p: \"p permutes S\"\n      assume q: \"q permutes S\"\n      assume eq: \"Fun.swap a b id \\<circ> p = Fun.swap a c id \\<circ> q\"\n      from p q aS have pa: \"p a = a\" and qa: \"q a = a\"\n        unfolding permutes_def by metis+\n      from eq have \"(Fun.swap a b id \\<circ> p) a  = (Fun.swap a c id \\<circ> q) a\"\n        by simp\n      then have bc: \"b = c\"\n        by (simp add: permutes_def pa qa o_def fun_upd_def Fun.swap_def id_def\n            cong del: if_weak_cong split: split_if_asm)\n      from eq[unfolded bc] have \"(\\<lambda>p. Fun.swap a c id \\<circ> p) (Fun.swap a c id \\<circ> p) =\n        (\\<lambda>p. Fun.swap a c id \\<circ> p) (Fun.swap a c id \\<circ> q)\" by simp\n      then have \"p = q\"\n        unfolding o_assoc swap_id_idempotent\n        by (simp add: o_def)\n      with bc have \"b = c \\<and> p = q\"\n        by blast\n    }\n    then show \"inj_on ?f (insert a S \\<times> ?P)\"\n      unfolding inj_on_def by clarify metis\n  qed\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/Permutations.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8539127492339909, "lm_q2_score": 0.8633916047011594, "lm_q1q2_score": 0.7372610988359141}}
{"text": "section \"Topological Sorting\"\n\ntheory topological_sort\n  imports Main \"HOL-Library.Multiset\"\n    \"fuzzyrule.fuzzyrule\"\nbegin\n\n\ntext \"A list is sorted by a partial order, if no element in the list is followed by a smaller\nelement with respect to the relation.\"\n\ndefinition sorted_by where\n\"sorted_by rel xs \\<equiv> \\<forall>i j. i<j \\<longrightarrow> j<length xs \\<longrightarrow> (xs!j,xs!i)\\<notin>rel\"\n\nlemma sorted_by_empty:\n\"sorted_by R []\"\n  by (auto simp add: sorted_by_def)\n\nlemma sorted_by_single:\n\"sorted_by R [x]\"\n  by (auto simp add: sorted_by_def)\n\nlemma sorted_by_prepend_smallest:\n  assumes \"\\<forall>y\\<in>set xs. (y,x)\\<notin>R\"\n    and \"sorted_by R xs\"\n  shows \"sorted_by R (x#xs)\"\n  using assms by (auto simp add: sorted_by_def nth_Cons split: nat.splits)\n\nlemma sorted_by_sublist_left:\n  assumes a: \"sorted_by R (xs@ys)\"\n  shows \"sorted_by R xs\"\n  using a by (auto simp add: sorted_by_def nth_append split: if_splits)\n\nlemma sorted_by_sublist_right:\n  assumes a: \"sorted_by R (xs@ys)\"\n  shows \"sorted_by R ys\"\n  using a by (auto simp add: sorted_by_def nth_append split: if_splits,\n      metis add.commute add_diff_cancel_left' add_less_cancel_right add_less_same_cancel1 not_less_zero)\n\nlemma sorted_by_append:\n  assumes \"sorted_by R (xs @ ys)\"\n      and c1: \"x \\<in> set xs\"\n      and c2: \"y \\<in> set ys\"\n    shows \"(y, x) \\<notin> R\"\n  using assms apply (auto simp add: sorted_by_def nth_append in_set_conv_nth split: if_splits)\n  by (smt add_diff_cancel_left' add_diff_cancel_right' diff_le_self less_diff_conv less_le_trans not_add_less2)\n\n\nlemma sorted_by_append_iff:\n  shows \"sorted_by R (xs@ys) \\<longleftrightarrow> (sorted_by R xs \\<and> sorted_by R ys \\<and> (\\<forall>x\\<in>set xs. \\<forall>y\\<in>set ys. (y,x)\\<notin>R))\"\nproof auto\n  show \"sorted_by R (xs @ ys) \\<Longrightarrow> sorted_by R xs\"\n    using sorted_by_sublist_left by blast\n  show \"sorted_by R (xs @ ys) \\<Longrightarrow> sorted_by R ys\"\n    using sorted_by_sublist_right by blast\n\n  show \"False\"\n    if c0: \"sorted_by R (xs @ ys)\"\n      and c1: \"x \\<in> set xs\"\n      and c2: \"y \\<in> set ys\"\n      and c3: \"(y, x) \\<in> R\"\n    for  x y\n    by (meson c0 c1 c2 c3 sorted_by_append)\n\n\n  show \"sorted_by R (xs @ ys)\"\n    if c0: \"sorted_by R xs\"\n      and c1: \"sorted_by R ys\"\n      and c2: \"\\<forall>x\\<in>set xs. \\<forall>y\\<in>set ys. (y, x) \\<notin> R\"\n    apply (auto simp add: sorted_by_def nth_append)\n    using c0 sorted_by_def apply blast\n    apply (simp add: c2)\n    by (metis add_diff_inverse_nat c1 dual_order.strict_trans nat_add_left_cancel_less sorted_by_def)\nqed\n\nlemma sorted_by_cons_iff:\n  shows \"sorted_by R (x#xs) \\<longleftrightarrow> (sorted_by R xs \\<and> (\\<forall>y\\<in>set xs. (y,x)\\<notin>R))\"\n  using sorted_by_append_iff[where R=R and xs=\"[x]\" and ys=\"xs\"]\n  by (auto simp add: sorted_by_single)\n\n\ntext \"For strict linear orders, @{term sorted_by} is the same as @{term sorted}:\"\n\nlemma sorted_by_eq_sorted:\n\"sorted_by {(x::'a::linorder,y). x < y} xs = sorted xs\"\n  by (induct xs, auto simp add: sorted_by_empty sorted_by_cons_iff)\n\n\n\nfun top_sort where\n  \"top_sort R [] = []\"\n| \"top_sort R (x#xs) = (\n    let (greater, not_greater) = partition (\\<lambda>y. R x y) xs in\n    top_sort R not_greater @ x # top_sort R greater)\"\n\nvalue \"top_sort (\\<subset>) [{1,2,3}, {1}, {1}, {2,3,4}, {2}, {1,3::int}, {}]\"\n\nlemma top_sort_mset[simp]:\n\"mset (top_sort R xs) = mset xs\"\nproof (induct R xs rule: top_sort.induct)\n  case (1 R)\n  show \"mset (top_sort R []) = mset [] \"\n    by simp\nnext\n  case (2 R x xs)\n  show \" mset (top_sort R (x # xs)) = mset (x # xs)\"\n    using 2 by auto\nqed\n\nlemma top_sort_set[simp]:\n\"set (top_sort R xs) = set xs\"\n  by (metis set_mset_mset top_sort_mset)\n\n\nlemma top_sort_sorts_irrefl:\n  assumes trans: \"trans {(x,y). R x y}\"\n    and irrefl: \"irrefl {(x,y). R x y}\"\n  shows \"sorted_by {(x,y). R x y} (top_sort R xs)\"\nusing trans irrefl proof (induct R xs rule: top_sort.induct)\ncase (1 R)\n  then show ?case \n    by (auto simp add: sorted_by_empty)\nnext\n  case (2 R x xs)\n  show ?case \n  proof (auto simp add: sorted_by_append_iff sorted_by_cons_iff)\n    show \"sorted_by {(x, y). R x y} (top_sort R (filter (Not \\<circ> R x) xs))\"\n      by (simp add: 2)\n    show \"sorted_by {(x, y). R x y} (top_sort R (filter (R x) xs))\"\n      by (simp add: 2)\n    show \"\\<And>y. \\<lbrakk>y \\<in> set xs; R x y; R y x\\<rbrakk> \\<Longrightarrow> False\"\n      by (metis \"2.prems\"(1) \"2.prems\"(2) case_prodI irrefl_def mem_Collect_eq trans_def)\n    show \"\\<And>xa y. \\<lbrakk>xa \\<in> set xs; \\<not> R x xa; y \\<in> set xs; R x y; R y xa\\<rbrakk> \\<Longrightarrow> False\"\n      by (smt \"2.prems\"(1) case_prodD case_prodI mem_Collect_eq transE)\n  qed\nqed\n\nlemma top_sort_sorts_distinct:\n  assumes trans: \"trans {(x,y). R x y}\"\n    and irrefl: \"\\<And>x y. x\\<in>set xs \\<Longrightarrow> y\\<in>set xs \\<Longrightarrow> R x y \\<Longrightarrow> x\\<noteq>y \\<Longrightarrow> \\<not>R y x\"\n    and distinct: \"distinct xs\"\n  shows \"sorted_by {(x,y). R x y} (top_sort R xs)\"\nusing trans irrefl distinct proof (induct R xs rule: top_sort.induct)\ncase (1 R)\n  then show ?case \n    by (auto simp add: sorted_by_empty)\nnext\n  case (2 R x xs)\n  have irrefl: \"\\<And>x y. x\\<in>set xs \\<Longrightarrow> y\\<in>set xs \\<Longrightarrow> R x y \\<Longrightarrow> x\\<noteq>y \\<Longrightarrow> \\<not>R y x\"\n    by (simp add: \"2.prems\"(2))\n\n  show ?case \n  proof (auto simp add: sorted_by_append_iff sorted_by_cons_iff)\n    show \"sorted_by {(x, y). R x y} (top_sort R (filter (Not \\<circ> R x) xs))\"\n      by (rule 2, insert \"2.prems\"(3) irrefl, auto simp add: \"2.prems\"(1))\n    show \"sorted_by {(x, y). R x y} (top_sort R (filter (R x) xs))\"\n      by (rule 2, insert \"2.prems\"(3) irrefl, auto simp add: \"2.prems\"(1))\n    show \"\\<And>y. \\<lbrakk>y \\<in> set xs; R x y; R y x\\<rbrakk> \\<Longrightarrow> False\"\n      using \"2.prems\"(2) \"2.prems\"(3) by auto\n    show \"\\<And>xa y. \\<lbrakk>xa \\<in> set xs; \\<not> R x xa; y \\<in> set xs; R x y; R y xa\\<rbrakk> \\<Longrightarrow> False\"\n      by (smt \"2.prems\"(1) case_prodD case_prodI mem_Collect_eq transE)\n  qed\nqed\n\nlemma exists_sorted_by:\n  assumes fin: \"finite S\"\n    and trans: \"trans R\"\n    and irrefl2: \"\\<And>x y. x\\<in>S \\<Longrightarrow> y\\<in>S \\<Longrightarrow> (x,y)\\<in>R \\<Longrightarrow> x\\<noteq>y \\<Longrightarrow> (y,x)\\<notin>R\"\nshows \"\\<exists>l. set l = S \\<and> sorted_by R l\"\nproof -\n  obtain ul where \"set ul = S\" and \"distinct ul\"\n    using fin finite_distinct_list by auto\n\n  have \"sorted_by R (top_sort (\\<lambda>x y. (x,y)\\<in>R) ul)\"\n    by (fuzzy_rule top_sort_sorts_distinct; (simp add: trans `distinct ul`  \\<open>set ul = S\\<close> irrefl2)?)\n\n  thus ?thesis\n    by (metis \\<open>set ul = S\\<close> top_sort_set)\nqed\n\nlemma exists_sorted_by_irrefl:\n  assumes fin: \"finite S\"\n    and trans: \"trans R\"\n    and irrefl: \"irrefl R\"\n  shows \"\\<exists>l. set l = S \\<and> sorted_by R l\"\n  by (meson exists_sorted_by fin irrefl irrefl_def local.trans transE)\n\nlemma exists_sorted_by_antisym:\n  assumes fin: \"finite S\"\n    and trans: \"trans R\"\n    and irrefl: \"antisym R\"\n  shows \"\\<exists>l. set l = S \\<and> sorted_by R l\"\n  by (meson antisym_def exists_sorted_by fin irrefl local.trans)\n\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/topological_sort.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869916479466, "lm_q2_score": 0.8418256512199033, "lm_q1q2_score": 0.7372599545739527}}
{"text": "theory Van_der_Waerden\n  imports Main \"HOL-Library.FuncSet\" Digits\nbegin\n\nsection \\<open>Van der Waerden's Theorem\\<close>\n\ntext \\<open>In combinatorics, Van der Waerden's Theorem is about arithmetic progressions of a certain\nlength of the same colour in a colouring of an interval. In order to state the theorem and to\nprove it, we need to formally introduce arithmetic progressions. We will express $k$-colourings as\nfunctions mapping an integer interval to the set $\\{0,\\dots , k-1 \\}$ of colours.\\<close>\n\nsubsection \\<open>Arithmetic progressions\\<close>\n\ntext \\<open>A sequence of integer numbers with the same step size is called an arithmetic progression.\n We say an  $m$-fold arithmetic progression is an arithmetic progression with multiple step \nlengths.\\<close>\n\ntext \\<open> Arithmetic progressions are defined in the following using the variables:\n\n\\begin{tabular}{lcp{8cm}}\n$start$:& \\<open>int\\<close>& starting value\\\\\n$step$:&  \\<open>nat\\<close>& positive integer for step length\\\\\n$i$:&     \\<open>nat\\<close>& $i$-th value in the arithmetic progression \\\\\n\\end{tabular}\\<close>\n\ndefinition arith_prog :: \"int \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> int\"\n  where \"arith_prog start step i = start + int (i * step)\"\n\ntext \\<open> An $m$-fold arithmetic progression (which we will also call a multi-arithmetic progression)\nis defined in the following using the variables:\n\n\\begin{tabular}{lcp{8cm}}\n$dims$:&   \\<open>nat\\<close>& number of dimensions/step directions of $m$-fold arithmetic progression\\\\\n$start$:&  \\<open>int\\<close>& starting value\\\\\n$steps$:&  \\<open>nat \\<Rightarrow> nat\\<close>& function of steps, returns step in $i$-th dimension for $i\\in[0..<dims]$\\\\\n$c$:&      \\<open>nat \\<Rightarrow> nat\\<close>& function of coefficients, returns coefficient in $i$-th dimension for \n           $i\\in[0..<dims]$ \\\\\n\\end{tabular}\\<close>\n\ndefinition multi_arith_prog :: \n    \"nat \\<Rightarrow> int \\<Rightarrow> (nat \\<Rightarrow> nat) \\<Rightarrow> (nat \\<Rightarrow> nat) \\<Rightarrow> int\"\n  where \"multi_arith_prog dims start steps c = \n           start + int (\\<Sum>i<dims. c i * steps i)\"\n\ntext \\<open>An $m$-fold arithmetic progression of dimension $1$ is also an arithmetic progression and \n  vice versa. This is shown in the following lemmas.\\<close>\nlemma multi_to_arith_prog: \n  \"multi_arith_prog 1 start steps c = \n    arith_prog start (steps 0) (c 0)\"\n  unfolding multi_arith_prog_def arith_prog_def by auto\n\nlemma arith_prog_to_multi: \n  \"arith_prog start step c = \n    multi_arith_prog 1 start (\\<lambda>_. step) (\\<lambda>_. c)\"\n  unfolding multi_arith_prog_def arith_prog_def by auto\n\ntext \\<open>To show that an arithmetic progression is well-defined, we introduce the following predicate.\nIt assures that \\<open>arith_prog start step ` [0..<l]\\<close> is contained in the integer interval $[a..b]$.\\<close>\ndefinition is_arith_prog_on :: \n    \"nat \\<Rightarrow> int \\<Rightarrow> nat \\<Rightarrow> int \\<Rightarrow> int \\<Rightarrow> bool\" \n  where \"is_arith_prog_on l start step a b \\<longleftrightarrow>\n    (start \\<ge> a \\<and> arith_prog start step (l-1) \\<le> b)\"\n\ntext \\<open>Furthermore, we have monotonicity for arithmetic progressions.\\<close>\nlemma arith_prog_mono: \n  assumes \"c \\<le> c'\"\n  shows   \"arith_prog start step c \\<le> arith_prog start step c'\"\n  using assms unfolding arith_prog_def by (auto intro: mult_mono)\n\ntext \\<open>Now, we state the well-definedness of an arithmetic progression of length $l$ in an integer\ninterval $[a..b]$. \nIndeed, \\<open>is_arith_prog_on\\<close> guarantees that every element of \\<open>arith_prog start step\\<close> of length $l$ \n  lies in $[a..b]$.\\<close>\nlemma is_arith_prog_onD:\n  assumes \"is_arith_prog_on l start step a b\"\n  assumes \"c \\<in> {0..<l}\"\n  shows   \"arith_prog start step c \\<in> {a..b}\"\nproof -\n  have \"arith_prog start step 0 \\<le> arith_prog start step c\"\n    by (rule arith_prog_mono) auto\n  hence \"arith_prog start step c \\<ge> a\"\n    using assms by (simp add: arith_prog_def is_arith_prog_on_def \n                      add_increasing2)\n  moreover have \"arith_prog start step (l-1) \\<ge> \n                   arith_prog start step c\"\n    by (rule arith_prog_mono) (use assms(2) in auto)\n  hence \"arith_prog start step c \\<le> b\"\n    using assms unfolding arith_prog_def is_arith_prog_on_def \n    by linarith\n  ultimately show ?thesis\n    by auto\nqed\n\ntext \\<open>We also need a predicate for an $m$-fold arithmetic progression to be well-defined. \nIt assures that \\<open>multi_arith_prog start step ` [0..<l]^m\\<close> is contained in $[a..b]$.\\<close>\ndefinition is_multi_arith_prog_on :: \n    \"nat \\<Rightarrow> nat \\<Rightarrow> int \\<Rightarrow> (nat \\<Rightarrow> nat) \\<Rightarrow> int \\<Rightarrow> int \\<Rightarrow> bool\" \n  where \"is_multi_arith_prog_on l m start steps a b \\<longleftrightarrow>\n     (start \\<ge> a \\<and> multi_arith_prog m start steps (\\<lambda>_. l-1) \\<le> b)\"\n\ntext \\<open>Moreover, we have monotonicity for $m$-fold arithmetic progressions as well.\\<close>\nlemma multi_arith_prog_mono:\n  assumes \"\\<And>i. i < m \\<Longrightarrow> c i \\<le> c' i\"\n  shows   \"multi_arith_prog m start steps c \\<le> \n            multi_arith_prog m start steps c'\"\n  using assms unfolding multi_arith_prog_def \n  by (auto intro!: sum_mono intro: mult_right_mono)\n\ntext \\<open>Finally, we get the well-definedness for $m$-fold arithmetic progressions of length $l$.\nHere, \\<open>is_multi_arith_prog_on\\<close> guarantees that every element of \\<open>multi_arith_prog start step\\<close> \n  of length $l$ lies in $[a..b]$.\\<close>\nlemma is_multi_arith_prog_onD:\n  assumes \"is_multi_arith_prog_on l m start steps a b\"\n  assumes \"c \\<in> {0..<m} \\<rightarrow> {0..<l}\"\n  shows   \"multi_arith_prog m start steps c \\<in> {a..b}\"\nproof -\n  have \"multi_arith_prog m start steps (\\<lambda>_. 0) \\<le> \n          multi_arith_prog m start steps c\"\n    by (rule multi_arith_prog_mono) auto\n  hence \"multi_arith_prog m start steps c \\<ge> a\"\n    using assms by (simp add: multi_arith_prog_def \n       is_multi_arith_prog_on_def)\n  moreover have \"multi_arith_prog m start steps (\\<lambda>_. l-1) \\<ge> \n                   multi_arith_prog m start steps c\"\n    by (rule multi_arith_prog_mono) (use assms in force)\n  hence \"multi_arith_prog m start steps c \\<le> b\"\n    using assms by (simp add: multi_arith_prog_def \n        is_multi_arith_prog_on_def)\n  ultimately show ?thesis\n    by auto\nqed\n\n\nsubsection \\<open>Van der Waerden's Theorem\\<close>\n\ntext \\<open>The property for a number $n$ to fulfill Van der Waerden's theorem is the following:\\\\\nFor a $k$-colouring col of $[a..b]$ there exist\n\\begin{itemize}\n\\item $start$: starting value of an arithmetic progression\n\\item $step$:  step length of an arithmetic progression\n\\item $j$: colour \n\\end{itemize}\nsuch that \\<open>arith_prog start step\\<close> is a valid arithmetic progression of length $l$ lying \nin $[a..b]$ of the same colour $j$.\n\nThe following variables will be used:\\\\\n\\begin{tabular}{lcp{8cm}}\n$k$:& \\<open>nat\\<close>& number of colours in segment colouring on $[a..b]$\\\\\n$l$:& \\<open>nat\\<close>& length of arithmetic progression\\\\\n$n$:& \\<open>nat\\<close>& number fulfilling Van der Waerden's Theorem\\\\\n\\end{tabular}\n\\<close>\ndefinition vdw :: \n    \"nat \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> bool\" \n  where \"vdw k l n \\<longleftrightarrow>\n     (\\<forall>a b col. b + 1 \\<ge> a + int n \\<and> col \\<in> {a..b} \\<rightarrow> {..<k} \\<longrightarrow>\n       (\\<exists>j start step. j < k \\<and> step > 0 \\<and> \n        is_arith_prog_on l start step a b \\<and>\n        arith_prog start step ` {..<l} \\<subseteq> col -` {j} \\<inter> {a..b}))\"\n\ntext \\<open>To better work with the property of Van der Waerden's theorem, we introduce an \n  elimination rule.\\<close>\nlemma vdwE:\n  assumes \"vdw k l n\"\n          \"b + 1 \\<ge> a + int n\" \n          \"col \\<in> {a..b} \\<rightarrow> {..<k}\"\n  obtains j start step where\n    \"j < k\" \"step > 0\" \n    \"is_arith_prog_on l start step a b\"\n    \"arith_prog start step ` {..<l} \\<subseteq> col -` {j} \\<inter> {a..b}\"\n  using assms that unfolding vdw_def by metis\n\ntext \\<open>Van der Waerden's theorem implies that the number fulfilling it is positive. This is show \nin the following lemma.\\<close>\nlemma vdw_imp_pos:\n  assumes \"vdw k l n\" \n          \"l > 0\"\n  shows \"n > 0\"\nproof (rule Nat.gr0I)\n  assume [simp]: \"n = 0\"\n  show False\n    using assms \n    by (elim vdwE[where a = 1 and b = 0 and col = \"\\<lambda>_. 0\"]) \n       (auto simp: lessThan_empty_iff)\nqed\n\ntext \\<open>Van der Waerden's Theorem is trivial for a non-existent colouring. \nIt also makes no sense for arithmetic progressions of length 0.\\<close>\nlemma vdw_0_left [simp, intro]: \"n>0 \\<Longrightarrow> vdw 0 l n\"\n  by (auto simp: vdw_def)\n\ntext \\<open>In the case of $k=1$, Van der Waerden's Theorem holds. Then every number has the same colour,\nhence also the arithmetic progression. A possible choice for the number fulfilling Van der \nWaerden Theorem is $l$.\\<close>\nlemma vdw_1_left: \n  assumes \"l>0\" \n  shows \"vdw 1 l l\"\nunfolding vdw_def\nproof (safe, goal_cases)\n  case (1 a b col)\n  have \"arith_prog a 1 ` {..<l} \\<subseteq> {a..b}\"\n    using 1(1) by (auto simp: arith_prog_def)\n  also have \"{a..b} = col -` {0} \\<inter> {a..b}\"\n    using 1(2) by auto\n  finally have \"arith_prog a 1 ` {..<l} \\<subseteq> col -` {0} \\<inter> {a..b}\"\n    by auto\n  moreover have \"is_arith_prog_on l a 1 a b\" \n    unfolding is_arith_prog_on_def arith_prog_def using 1 assms \n    by auto\n  ultimately show \"\\<exists>j start step. j < 1 \\<and> 0 < step \\<and> \n        is_arith_prog_on l start step a b \\<and>\n        arith_prog start step ` {..<l} \\<subseteq> col -` {j} \\<inter> {a..b}\"\n    by auto\nqed\n\ntext \\<open>In the case $l=1$, Van der Waerden's Theorem holds. As the length of the arithmetic \nprogression is $1$, it consists of just one element. Thus every nonempty integer interval fulfills \nthe Van der Waerden property. We can prove $N_{k,1}$ to be $1$.\\<close>\nlemma vdw_1_right: \"vdw k 1 1\"\nunfolding vdw_def \nproof safe\n  fix a b :: int and col :: \"int \\<Rightarrow> nat\"\n  assume *: \"a + int 1 \\<le> b + 1\" \"col \\<in> {a..b} \\<rightarrow> {..<k}\"\n  have \"col a < k\" using * by auto\n  have \"arith_prog a 1 ` {..<1} = {a}\"\n    using *(1) by (auto simp: arith_prog_def)\n  also have \"{a} \\<subseteq> col -` {col a} \\<inter> {a..b}\"\n    using * by auto\n  finally have \"arith_prog a 1 ` {..<1} \\<subseteq> col -` {col a} \\<inter> {a..b}\"\n    by auto\n  moreover have \"is_arith_prog_on 1 a 1 a b\" \n    unfolding is_arith_prog_on_def arith_prog_def\n    using * by auto\n  ultimately show  \"\\<exists>j start step.\n          j < k \\<and> 0 < step \\<and> is_arith_prog_on 1 start step a b \\<and>\n          arith_prog start step ` {..<1} \\<subseteq> col -` {j} \\<inter> {a..b}\"\n    using \\<open>col a <k\\<close> by blast\nqed\n\ntext \\<open>In the case $l=2$, Van der Waerden's Theorem holds as well. Here, any two distinct numbers \nform an arithmetic progression of length $2$. Thus we only have to find two numbers with the same \ncolour.\nUsing the pigeonhole principle on $k+1$ values, we can find two integers with the same colour.\\<close>\nlemma vdw_2_right: \"vdw k 2 (k+1)\"\nunfolding vdw_def \nproof safe\n  fix a b :: int and col :: \"int \\<Rightarrow> nat\"\n  assume *: \"a + int (k + 1) \\<le> b + 1\" \"col \\<in> {a..b} \\<rightarrow> {..<k}\"\n\n  have \"col ` {a..b} \\<subseteq> {..<k}\" using *(2) by auto\n  moreover have \"k+1 \\<le> card {a..b}\" using *(1) by auto\n  ultimately have \"card (col ` {a..b}) < card {a..b}\" using * \n    by (metis card_lessThan card_mono finite_lessThan le_less_trans \n        less_add_one not_le)\n  then have \"\\<not> inj_on col {a..b}\" using pigeonhole[of col \"{a..b}\"]\n    by auto\n  then obtain start start_step \n    where pigeon: \"col start = col start_step\" \n      \"start < start_step\"\n      \"start \\<in> {a..b}\" \n      \"start_step \\<in> {a..b}\" \n    using inj_onI[of \"{a..b}\" col] \n    by (metis not_less_iff_gr_or_eq)\n\n  define step where \"step = nat (start_step - start)\"\n  define j where \"j = col start\"\n\n  have \"j < k\" unfolding j_def using *(2) pigeon(3) by auto \n  moreover have \"0 < step\" unfolding step_def using pigeon(2) by auto\n  moreover have \"is_arith_prog_on 2 start step a b\" \n    unfolding is_arith_prog_on_def arith_prog_def step_def \n    using pigeon by auto\n  moreover {\n  have \"arith_prog start step i \\<in> {start, start_step}\" if \"i<2\" for i\n    using that arith_prog_def step_def by (auto simp: less_2_cases_iff)\n  also have \"\\<dots> \\<subseteq> col -` {j} \\<inter> {a..b}\" \n    using pigeon unfolding j_def by auto\n  finally have \"arith_prog start step ` {..<2} \\<subseteq> col -` {j} \\<inter> {a..b}\" \n    by auto\n  }\n  ultimately show \"\\<exists>j start step.\n          j < k \\<and>\n          0 < step \\<and>\n          is_arith_prog_on 2 start step a b \\<and>\n          arith_prog start step ` {..<2} \\<subseteq> col -` {j} \\<inter> {a..b}\" by blast\nqed\n\ntext \\<open>In order to prove Van der Waerden's Theorem, we first prove a slightly different lemma.\nThe statement goes as follows:\\\\\nFor a $k$-colouring $col$ on $[a..b]$ there exist\n\\begin{itemize}\n\\item  $start$: starting value of an arithmetic progression\n\\item  $steps$: step length of an arithmetic progression\n\\end{itemize}\nsuch that \\<open>f = multi_arith_prog m start step\\<close> is a valid $m$-fold arithmetic progression of \nlength $l$ lying in $[a..b]$ such that for every $s<m$ have: if $c j < l$ for all $j\\leq s$ then\n$f(c_0, c_1, \\dots, c_{m-1})$ and $f(0,\\dots,0, c_{s+1},\\dots, c_{m-1})$ have the same colour.\n\nThe property of the lemma uses the following variables:\\\\\n\\begin{tabular}{lcp{8cm}}\n$k$:& \\<open>nat\\<close>& number of colours in segment colouring of $[a..b]$\\\\\n$m$:& \\<open>nat\\<close>& dimension of $m$-fold arithmetic progression\\\\\n$l$:& \\<open>nat\\<close>& $l+1$ is length of $m$-fold arithmetic progression\\\\\n$n$:& \\<open>nat\\<close>& number fulfilling \\<open>vdw_lemma\\<close>\\\\\n\\end{tabular}\n\\<close>\ndefinition vdw_lemma :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> bool\" where\n  \"vdw_lemma k m l n \\<longleftrightarrow>\n     (\\<forall>a b col. b + 1 \\<ge> a + int n \\<and> col \\<in> {a..b} \\<rightarrow> {..<k} \\<longrightarrow>\n       (\\<exists>start steps. (\\<forall>i<m. steps i > 0) \\<and> \n        is_multi_arith_prog_on (l+1) m start steps a b \\<and> (\n           let f = multi_arith_prog m start steps\n           in  (\\<forall>c \\<in> {0..<m} \\<rightarrow> {0..l}. \\<forall>s<m. (\\<forall> j \\<le> s. c j < l) \\<longrightarrow>\n                  col (f c) = col (f (\\<lambda>i. if i \\<le> s then 0 else c i))))))\"\n\ntext \\<open>To better work with this property, we introduce an elimination rule for \\<open>vdw_lemma\\<close>.\\<close>\nlemma vdw_lemmaE:\n  fixes a b :: int\n  assumes \"vdw_lemma k m l n\"\n    \"b + 1 \\<ge> a + int n\" \"col \\<in> {a..b} \\<rightarrow> {..<k}\"\n  obtains start steps where\n    \"\\<And>i. i < m \\<Longrightarrow> steps i > 0\"\n    \"is_multi_arith_prog_on (l+1) m start steps a b\"\n    \"let f = multi_arith_prog m start steps\n     in  \\<forall>c \\<in> {0..<m} \\<rightarrow> {0..l}. \\<forall>s<m. (\\<forall> j \\<le> s. c j < l) \\<longrightarrow>\n            col (f c) = col (f (\\<lambda>i. if i \\<le> s then 0 else c i))\"\n  using assms that unfolding vdw_lemma_def by blast\n\ntext \\<open>To simplify the following proof, we show the following formula.\\<close>\nlemma sum_mod_poly: \n  assumes \"(k::nat)>0\" \n  shows \"(k - 1) * (\\<Sum> n\\<in>{..<q}. k^n) < k^q \"\nproof -\n  have \"int ((k - 1) * (\\<Sum>n<q. k ^ n)) = \n        (int k - 1) * (\\<Sum>n<q. int k ^ n)\"\n    using assms by (simp add: of_nat_diff)\n  also have \"\\<dots> = int k ^ q - 1\"\n    by (induction q) (auto simp: algebra_simps)\n  also have \"\\<dots> < int (k ^ q)\"\n    by simp\n  finally show ?thesis by linarith\nqed\n\ntext \\<open>The proof of Van der Waerden's Theorem now proceeds in three steps:\\\\\n\\begin{itemize}\n\\item Firstly, we show that the \\<open>vdw\\<close> property for all $k$ proves the \\<open>vdw_lemma\\<close> for fixed $l$ but \narbitrary $k$ and $m$. This is done by induction over $m$.\n\\item Secondly, we show that \\<open>vdw_lemma\\<close> implies the induction step of \\<open>vdw\\<close> using the pigeonhole \nprinciple.\n\\item Lastly, we combine the previous steps in an induction over $l$ to show Van der Waerden's \nTheorem in the general setting.\n\\end{itemize}\\<close>\n\ntext \\<open>Firstly, we need to show that \\<open>vdw\\<close> for arbitrary $k$ implies \\<open>vdw_lemma\\<close> for fixed $l$.\nAs mentioned earlier, we use induction over $m$.\\<close>\nlemma vdw_imp_vdw_lemma:\n  fixes l\n  assumes vdw_assms: \"\\<And>k'. k'>0 \\<Longrightarrow> \\<exists>n_k'. vdw k' l n_k'\"\n    and \"l \\<ge> 2\"\n    and \"m > 0\"\n    and \"k > 0\"\n  shows   \"\\<exists>N. vdw_lemma k m l N\"\nusing \\<open>m>0\\<close> \\<open>k>0\\<close> proof (induction m rule: less_induct)\n  case (less m)\n  consider  \"m=1\" | \"m>1\" using less.prems by linarith\n  then show ?case \n  proof cases\n    text \\<open> Case $m=1$: Show \\<open>vdw_lemma\\<close> for arithmetic progression, Induction start. \\<close>\n    assume \"m = 1\"\n\n    obtain n where vdw: \"vdw k l n\" using vdw_assms \\<open>k>0\\<close> by blast\n    define N where \"N = 2*n\"\n    have \"l>0\" and \"l>1\" using \\<open>l\\<ge>2\\<close> by auto\n\n    have \"vdw_lemma k m l N\"\n      unfolding vdw_lemma_def\n    proof (safe, goal_cases)\n      case (1 a b col)\n      text \\<open> Divide $[a..b]$ in two intervals $I_1$, $I_2$ of same length and obtain arithmetic \n        progression of length $l$ in $I_1$. \\<close>\n      have col_restr: \"col \\<in> {a..a + int n - 1} \\<rightarrow> {..<k}\"\n        using 1 by (auto simp: N_def)\n      then obtain j start step where prog:\n        \"j < k\" \"step > 0\" \n        \"is_arith_prog_on l start step a (a + int n -1)\"\n        \"arith_prog start step ` {..<l} \\<subseteq> \n          col -` {j} \\<inter> {a..a + int n - 1}\"\n        using vdw 1 unfolding N_def by (elim vdwE)(auto simp:is_arith_prog_on_def)\n      have range_prog_lessThan_l: \n        \"arith_prog start step i \\<in> {a..a + int n -1}\" if \"i < l\" for i\n        using that prog by auto\n\n      have \"{a..a + int n-1}\\<subseteq>{a..b}\" using N_def \"1\"(1) by auto \n      then have \"a + 2* int n - 1 \\<le> b\" using 1(1) unfolding N_def \n        by auto\n\n      text \\<open> Show that \\<open>arith_prog start step\\<close> is an arithmetic progression of length $l+1$\n         in $[a..b]$. \\<close>\n      have prog_in_ivl: \"arith_prog start step i \\<in> {a..b}\" \n        if \"i \\<le> l\" for i\n      proof (cases \"i=l\")\n        case False\n        have \"i<l\" using that False by auto\n        then show ?thesis \n          using range_prog_lessThan_l \\<open>{a..a + int n-1}\\<subseteq>{a..b}\\<close> by force\n      next\n        case True\n        text \\<open> Show $\\<open>step\\<close>\\leq |I_1|$ then have \\<open>arith_prog start step (l+1)\\<in>[a..b]\\<close> as \n           \\<open>arith_prog start step (l+1) = arith_prog start step l + step\\<close> \\<close>\n        have \"start \\<in> {a..a + int n -1}\" \n          using range_prog_lessThan_l[of 0] \n          unfolding arith_prog_def by (simp add: \\<open>0 < l\\<close>)\n        moreover have \"start + int step \\<in> {a..a + int n -1}\" \n          using range_prog_lessThan_l[of 1] \n          unfolding arith_prog_def by (metis \\<open>1 < l\\<close> mult.left_neutral)\n        ultimately have \"step \\<le> n\" by auto\n        have \"arith_prog start step (l-1) \\<in> {a..a + int n -1}\" \n          using range_prog_lessThan_l[of \"l-1\"] unfolding arith_prog_def\n          using \\<open>0 < l\\<close> diff_less less_numeral_extra(1) by blast\n        moreover have \"arith_prog start step l = \n                        arith_prog start step (l-1) + int step\"\n          unfolding arith_prog_def using \\<open>0 < l\\<close> mult_eq_if by force\n        ultimately have \"arith_prog start step l \\<in> {a..b}\" \n          using \\<open>step\\<le>n\\<close> N_def \\<open>a + 2* int n -1 \\<le> b\\<close> by auto\n        then show ?thesis using range_prog_lessThan_l using True \n          by force\n      qed\n\n      have col_prog_eq: \"col (arith_prog start step k) = j\" \n        if \"k < l\" for k\n        using prog that by blast\n      \n      define steps :: \"nat \\<Rightarrow> nat\" where steps_def: \"steps = (\\<lambda>i. step)\"\n      define f where \"f = multi_arith_prog 1 start steps\"\n      \n      have rel_prop_1: \n        \"col (f c) = col (f (\\<lambda>i. if i < s then 0 else c i))\"\n        if \"c \\<in> {0..<1} \\<rightarrow> {0..l}\" \"s<1\" \"\\<forall>j\\<le>s. c j < l\" for c s \n        using that by auto\n\n      have arith_prog_on: \n        \"is_multi_arith_prog_on (l+1) m start steps a b\"\n        using prog(3) unfolding is_arith_prog_on_def is_multi_arith_prog_on_def\n        using \\<open>m=1\\<close> arith_prog_to_multi steps_def prog_in_ivl by auto\n      \n      show ?case\n        by (rule exI[of _ start], rule exI[of _ steps])\n           (use rel_prop_1 \\<open>step > 0\\<close> \\<open>m = 1\\<close> arith_prog_on col_prog_eq\n             multi_to_arith_prog in \\<open>auto simp: f_def Let_def steps_def\\<close>)\n    qed\n    then show ?case ..\n\n  next\n    text \\<open> Case $m>1$: Show \\<open>vdw_lemma\\<close> for $m$-fold arithmetic progression, \n          Induction step $(m-1) \\longrightarrow m$. \\<close>\n    assume \"m>1\"\n\n    obtain q where vdw_lemma_IH:\"vdw_lemma k (m-1) l q\" \n      using \\<open>1 < m\\<close> less by force\n    have \"k^q>0\" using \\<open>k>0\\<close> by auto\n    obtain n_kq where vdw: \"vdw (k^q) l n_kq\" \n      using vdw_assms \\<open>k^q>0\\<close> by blast\n    define N where \"N = q + 2 * n_kq\"\n\n    text \\<open>Idea: $[a..b] = I_1 \\cup I_2$ where $|I_1| = 2*n_{k,q}$ and $|I_2| = q$.\n                Divide $I_1$ into blocks of length $q$ and define a new colouring on the set of \n                $q$-blocks where the colour of the block is the $k$-basis representation where \n                the $i$-th digit corresponds to the colour of the $i$-th element in the block. \n                Get an arithmetic progression of $q$-blocks of length $l+1$ in $I_1$, such that\n                the first $l$ $q$-blocks have the same colour. \n                The step of the block-arithmetic progression is going to be the additional \n                step in the induction over $m$. \\<close>\n\n    have \"vdw_lemma k m l N\"\n      unfolding vdw_lemma_def\n    proof (safe, goal_cases)\n      case (1 a b col)\n      have \"n_kq>0\" using vdw_imp_pos vdw \\<open>l\\<ge>2\\<close> by auto\n      then have \"N>0\" by (simp add:N_def)\n      then have \"a\\<le>b\" using 1 by auto\n      then have \"k>0\" using 1 by (intro Nat.gr0I) force\n      have \"l>0\" and \"l>1\" using \\<open>l\\<ge>2\\<close> by auto\n      interpret digits k by (simp add: \\<open>0 < k\\<close> digits_def)\n      define col1 where \"col1 = (\\<lambda> x. from_digits q (\\<lambda>y. col (x + y)))\" \n      have range_col1: \"col1\\<in>{a..a + int n_kq - 1} \\<rightarrow> {..<k^q}\" \n      unfolding Pi_def\n      proof safe\n        fix x assume \"x\\<in>{a..a + int n_kq - 1}\"\n        then have col_xn:\"col (x + int n)\\<in>{..<k}\" if \"n<q\" for n :: nat\n          using that 1 PiE N_def by auto\n        have col_xn_upper_bound:\"col (x + int n) \\<le> k - 1\" \n          if \"n<q\" for n ::nat\n          using that col_xn[of n] \\<open>k>0\\<close> by (auto)\n        have \"(\\<Sum>n<q. col (x + int n) * k ^ n)\\<le> \n               (\\<Sum>n<q. (k-1) *  k ^ n)\"\n          using col_xn_upper_bound by (intro sum_mono mult_right_mono) \n            auto\n        also have \"\\<dots> = (k-1) * (\\<Sum>n<q. k ^ n)\"\n          by (rule sum_distrib_left[symmetric])\n        also have \"\\<dots> < k^q\" using sum_mod_poly \\<open>k>0\\<close> by auto        \n        finally show \"col1 x <k^q\" unfolding col1_def from_digits_altdef \n          by auto \n      qed\n\n      obtain j start step where prog:\n        \"j < k^q\" \"step > 0\" \n        \"is_arith_prog_on l start step a (a + int n_kq - 1)\"\n        \"arith_prog start step ` {..<l} \\<subseteq> \n          col1 -` {j} \\<inter> {a..a + int n_kq -1}\"\n        using vdw range_col1 by (elim vdwE) (auto simp: \\<open>k>0\\<close>) \n\n      have range_prog_lessThan_l: \n        \"arith_prog start step i \\<in> {a..a + int n_kq -1}\" \n        if \"i < l\" for i\n        using that prog by auto\n\n      have prog_in_ivl: \n        \"arith_prog start step i \\<in> {a..a + 2 * int n_kq -1}\" \n        if \"i \\<le> l\" for i\n      proof (cases \"i=l\")\n        case False\n        then have \"i<l\" using that by auto\n        then show ?thesis using prog by auto\n      next\n        case True\n        have \"start \\<in> {a..a + int n_kq -1}\" \n          using range_prog_lessThan_l[of 0] unfolding arith_prog_def \n          by (simp add: \\<open>0 < l\\<close>)\n        moreover have \"start + step \\<in> {a..a + int n_kq -1}\" \n          using range_prog_lessThan_l[of 1] unfolding arith_prog_def \n          by (metis \\<open>1 < l\\<close> mult.left_neutral)\n        ultimately have \"step \\<le> n_kq\" by auto\n        have \"arith_prog start step (l-1) \\<in> {a..a + int n_kq -1}\" \n          using range_prog_lessThan_l[of \"l-1\"] unfolding arith_prog_def\n          using \\<open>0 < l\\<close> diff_less less_numeral_extra(1) by blast\n        moreover have \"arith_prog start step l = \n            arith_prog start step (l-1) + step\"\n          unfolding arith_prog_def using \\<open>0 < l\\<close> mult_eq_if by force\n        ultimately have \"arith_prog start step l \\<in> \n            {a..a + 2 * int n_kq - 1}\" \n          using \\<open>step\\<le>n_kq\\<close> by auto\n        then show ?thesis using range_prog_lessThan_l using True \n          by force\n      qed\n\n      have col_prog_eq: \"col1 (arith_prog start step k) = j\" \n        if \"k < l\" for k\n        using prog that by blast\n\n      have digit_col1:\"digit (col1 x) y = col (x+int y)\" \n        if \"x\\<in>{a..<a + 2*int n_kq}\" \"y\\<in>{..<q}\" \n        for x::int and y::nat unfolding col1_def using that\n      proof -\n        have \"\\<And>j'. j'<q \\<Longrightarrow> x+j'\\<in>{a..b}\" \n          using \"1\"(1) N_def that(1) by force\n        then have \"\\<And>j'. j'<q \\<Longrightarrow> (\\<lambda>y. col (x+int y)) j' < k\" \n          using 1 that by auto\n        then show \"digit (from_digits q (\\<lambda>xa. col (x + int xa))) y = \n                    col (x + int y)\" \n          using digit_from_digits that 1 by auto\n      qed\n\n      text \\<open> Impact on the colour when taking the block-step. \\<close>\n      have one_step_more:\n        \"col (arith_prog start' step i) = digit j (nat (start'-start))\" \n        if \"start'\\<in>{start..<start+q}\" \"i\\<in>{..<l}\" for start' i\n      proof -\n        have \"start \\<le> start'\" using that by simp\n        have shift_arith_prog:\n          \"arith_prog start step i + (start' - start) = \n            arith_prog start' step i\" \n          unfolding arith_prog_def by simp\n        define diff where \"diff = nat (start'-start)\"\n        have \"diff \\<in>{..<q}\" using that unfolding diff_def by auto\n        have \"col (arith_prog start step i + int diff) = digit j diff\"\n        proof -\n          have \"col1 (arith_prog start step i) = j\" \n            using col1_def prog that by blast\n          moreover have \" arith_prog start step i\\<in>{a..a + 2 * int n_kq-1}\"\n            using prog(4) that by auto\n          ultimately show ?thesis \n            using digit_col1[where x = \"arith_prog start step i\" \n                and y = \"diff\"] \n              prog 1 \\<open>diff \\<in>{..<q}\\<close> by auto\n        qed\n        then show ?thesis unfolding diff_def 1\n          by (auto simp: \\<open>start\\<le>start'\\<close> shift_arith_prog) \n      qed\n\n      have one_step_more': \"col (arith_prog start' step i) =\n        col (arith_prog start' step 0)\"\n        if \"start'\\<in>{start..<start+q}\" \"i\\<in>{..<l}\" for start' i\n        using that one_step_more[of start' 0] \n          one_step_more[of start' i] by auto\n\n      have start_q: \"start + int q \\<le> start + int q - 1 + 1\" by linarith\n      have \"{start..start + int q-1} \\<subseteq> {a..b}\"\n        using prog N_def 1(1) by (force simp: arith_prog_def is_arith_prog_on_def)  \n      then have col': \"col \\<in> {start..start + int q-1} \\<rightarrow> {..<k}\"\n        using 1 prog(4) by auto\n\n      text \\<open> Obtain an $(m-1)$-fold arithmetic progression in the starting $q$-bolck of the \n             block arithmetic progression. \\<close>\n      obtain start_m steps_m where\n        step_m_pos: \"\\<And>i. i < m - 1 \\<Longrightarrow> 0 < steps_m i\" and\n        is_multi_arith_prog: \"is_multi_arith_prog_on (l+1) (m - 1) \n          start_m steps_m start (start + int q - 1)\" and\n        g_aux: \"let g = multi_arith_prog (m - 1) start_m steps_m\n          in  \\<forall>c\\<in>{0..<m - 1} \\<rightarrow> {0..l}. \\<forall>s<m - 1. (\\<forall>j\\<le>s. c j < l) \\<longrightarrow>\n          col (g c) = col (g (\\<lambda>i. if i \\<le> s then 0 else c i))\"\n        by (rule vdw_lemmaE[OF vdw_lemma_IH start_q col']) blast\n        \n      define g where \"g = multi_arith_prog (m-1) start_m steps_m\"\n      have g: \"col (g c) = col (g (\\<lambda>i. if i \\<le> s then 0 else c i))\"\n        if \"c \\<in> {0..<(m-1)} \\<rightarrow> {0..l}\" \"s < m - 1\" \"\\<forall>j \\<le> s. c j < l\"\n        for c s using g_aux that unfolding g_def Let_def by blast\n\n      have range_g: \"g c \\<in> {start..start + int q - 1}\"\n        if \"c \\<in> {0..<m - 1} \\<rightarrow> {0..<(l+1)}\" for c\n        using is_multi_arith_prog_onD[OF is_multi_arith_prog that] \n        by (auto simp: g_def)\n\n      text \\<open>Obtain an $m$-fold arithmetic progression by adding the block-step.\\<close>\n      define steps :: \"nat \\<Rightarrow> nat\" where steps_def: \n        \"steps = (\\<lambda>i.  (if i=0 then step else steps_m (i-1)))\"\n      define f where \"f = multi_arith_prog m start_m steps\"\n      have f_step_g: \"f c = int (c 0*step) + g (c \\<circ> Suc)\" for c\n      proof -\n        have \"f c = start_m + int (\\<Sum>i<Suc (m-1). c i * steps i)\"\n          using f_def unfolding multi_arith_prog_def \n          using less.prems by auto \n        also have \"\\<dots> = start_m + int (c 0 * steps 0) + \n                       int (\\<Sum>i<m-1. c (Suc i) * steps (Suc i))\"\n          using sum.lessThan_Suc_shift[where n = \"m-1\"] by auto\n        also have \"\\<dots> = start_m + int (c 0 * step) + \n                       int (\\<Sum>i<m-1. c (Suc i) * steps_m i)\"\n          using steps_def by (auto split:if_splits)\n        finally show ?thesis unfolding multi_arith_prog_def g_def \n          by simp\n      qed\n\n      text \\<open> Show that this $m$-fold arithmetic progression fulfills all needed properties. \\<close>\n      have steps_gr_0: \"\\<forall>i<m. 0 < steps i\" \n        unfolding steps_def using step_m_pos prog by auto\n\n      have is_multi_on_f: \n        \"is_multi_arith_prog_on (l+1) m start_m steps a b\"\n      proof -\n        have \"a \\<le> start_m\" using is_multi_arith_prog \n          unfolding is_multi_arith_prog_on_def\n          using is_arith_prog_on_def prog(3) by force\n        moreover {\n          have \"f (\\<lambda>_. l) = arith_prog (g ((\\<lambda>_. l) \\<circ> Suc)) step l\" \n            using f_step_g unfolding arith_prog_def by auto\n          also have \"g ((\\<lambda>_. l) \\<circ> Suc) \\<le> start + q\" \n            using range_g[of \"(\\<lambda>_. l) \\<circ> Suc\"] by auto\n          then have \"arith_prog (g ((\\<lambda>_. l) \\<circ> Suc)) step l \\<le> \n            arith_prog start step l + q\"\n            unfolding arith_prog_def by auto\n          also have \"\\<dots>\\<le> b\" using prog_in_ivl[of l]\n            using is_multi_arith_prog unfolding is_multi_arith_prog_on_def\n            using \"1\"(1) N_def by auto\n          finally have \"f (\\<lambda>_. l) \\<le> b\" by auto\n         }\n         ultimately show ?thesis \n           unfolding is_multi_arith_prog_on_def f_def by auto\n      qed\n\n      text \\<open> Show the relational property for all $s$. \\<close>\n      have rel_prop_1: \n        \"col (f c) = col (f (\\<lambda>i. if i \\<le> s then 0 else c i))\"\n        if \"c \\<in> {0..<m} \\<rightarrow> {0..l}\" \"s<m\" \"\\<forall>j\\<le>s. c j < l\" for c s \n      proof (cases \"s = 0\")\n        case True\n        have \"c 0 < l\" using that(3) True by auto\n        have range_c_Suc: \"c \\<circ> Suc \\<in> {0..<m-1} \\<rightarrow> {0..l}\" \n          using that(1) by auto\n        have \"f c = arith_prog (g (c \\<circ> Suc)) step (c 0)\" \n          using f_step_g unfolding arith_prog_def by auto\n        then have \"col (f c) = col (arith_prog (g (c \\<circ> Suc)) step 0)\"\n          using one_step_more'[of \"g (c \\<circ> Suc)\" \"c 0\"] \\<open>c 0 < l\\<close>\n            range_g[of \"c \\<circ> Suc\"] range_c_Suc \n            atLeastLessThanSuc_atLeastAtMost by auto\n        also {\n          have \"(\\<Sum>x<m - 1. int (c (Suc x)) * int (steps_m x)) =\n                   (\\<Sum>x=1..<m. int(c x) * int (steps x))\"\n            by(rule sum.reindex_bij_witness[of _ \"(\\<lambda>x. x-1)\" \"Suc\"]) \n              (auto simp: steps_def split:if_splits) \n          also have \"\\<dots> = (\\<Sum>x<m. int (if x = 0 then 0 else c x) * \n            int (steps x))\" \n            by (rule sum.mono_neutral_cong_left) auto\n          finally have \"arith_prog (g (c \\<circ> Suc)) step 0 = \n            f (\\<lambda>i. if i \\<le> s then 0 else c i)\" \n            unfolding f_def g_def multi_arith_prog_def arith_prog_def\n            using True by auto\n      }\n        finally show ?thesis by auto\n      next \n        case False\n        hence s_greater_0: \"s > 0\" by auto\n        have range_c_Suc: \"c \\<circ> Suc \\<in> {0..<m-1} \\<rightarrow> {0..l}\" \n          using that(1) by auto\n        have \"c 0 < l\" using \\<open>s>0\\<close> that by auto\n        have g_IH:\n          \"col (g c') = col (g (\\<lambda>i. if i \\<le> s' then 0 else c' i))\" \n          if \"c' \\<in> {0..<m-1} \\<rightarrow> {0..l}\" \"s'<m-1\" \"\\<forall>j\\<le>s'. c' j < l\" \n          for c' s' \n          using g_aux that unfolding multi_arith_prog_def g_def\n          by (auto simp: Let_def)\n        have g_shift_IH: \"col (g (c \\<circ> Suc)) = \n          col (g ((\\<lambda>i. if i\\<in>{1..t} then 0 else c i) \\<circ> Suc))\" \n          if \"c \\<in> {1..<m} \\<rightarrow> {0..l}\" \"t\\<in>{1..<m}\" \"\\<forall>j\\<in>{1..t}. c j < l\"\n          for c t\n        proof -\n          have \"(\\<lambda>i. (if i \\<le> t - 1 then 0 else (c \\<circ> Suc) i)) =\n                (\\<lambda>i. (if i \\<in> {1..t} then 0 else c i)) \\<circ> Suc\"\n            using that by (auto split: if_splits simp:fun_eq_iff)\n          then have right: \n            \"g (\\<lambda>i. if i \\<le> (t-1) then 0 else (c \\<circ> Suc) i) = \n             g ((\\<lambda>i. if i\\<in>{1..t} then 0 else c i) \\<circ> Suc)\" by auto\n          have \"(c \\<circ> Suc)\\<in> {0..<m-1} \\<rightarrow> {0..l}\" using that(1) by auto\n          moreover have \"t-1<m-1\" using that(2) by auto\n          moreover have\"\\<forall>j\\<le>t-1. (c \\<circ> Suc) j < l\" using that by auto\n          ultimately have \"col (g (c \\<circ> Suc)) = \n            col (g (\\<lambda>i. (if i \\<le> t-1 then 0 else (c \\<circ> Suc) i)))\"\n            using g_IH[of \"(c \\<circ> Suc)\" \"t-1\"] by auto\n          with right show ?thesis by auto\n        qed\n\n        have \"col (f c) = col (int (c 0 * step) + g (c \\<circ> Suc))\" \n          using f_step_g by simp\n        also have \"int (c 0 * step) + g (c \\<circ> Suc) = \n          arith_prog (g (c \\<circ> Suc)) step (c 0)\"\n          by (simp add: arith_prog_def)\n        also have \"col \\<dots> = col (arith_prog (g (c \\<circ> Suc)) step 0)\" \n          using one_step_more'[of \"g (c \\<circ> Suc)\" \"c 0\"] \\<open>c 0 < l\\<close> \n            range_g[of \"c \\<circ> Suc\"] range_c_Suc \n            atLeastLessThanSuc_atLeastAtMost by auto\n        also have \"\\<dots> = col (g (c \\<circ> Suc))\"\n          unfolding arith_prog_def by auto\n        also have \"\\<dots> = col (g ((\\<lambda>i. if  i\\<in>{1..s} then 0 else c i) \\<circ>\n          Suc))\" using g_shift_IH[of \"c\" s] \\<open>s>0\\<close> that by force\n        also have \"\\<dots> = col ((\\<lambda>c. int (c 0 * step) + \n          g (c \\<circ> Suc))(\\<lambda>i. if i\\<le>s then 0 else c i))\" \n          by (auto simp: g_def multi_arith_prog_def)\n        also have \"\\<dots> = col (f (\\<lambda>i. if i \\<le> s then 0 else c i))\" \n          unfolding f_step_g by auto\n        finally show ?thesis by simp\n      qed\n\n      show ?case\n        by (rule exI[of _ start_m], rule exI[of _ steps])\n           (use steps_gr_0 is_multi_on_f rel_prop_1 in \n             \\<open>auto simp: f_def Let_def steps_def\\<close>)\n    qed\n    then show ?case ..\n  qed\nqed\n\n\n\n\ntext \\<open> Secondly, we show that \\<open>vdw_lemma\\<close> implies the induction step of Van der Waerden's Theorem\nusing the pigeonhole principle. \\<close>\nlemma vdw_lemma_imp_vdw:\n  assumes \"vdw_lemma k k l N\"\n  shows   \"vdw k (Suc l) N\"\nunfolding vdw_def proof (safe, goal_cases)\ntext \\<open>Idea: Proof uses pigeonhole principle to guarantee the existence of an arithmetic \n            progression of length $l+1$ with the same colour. \\<close>\n  case (1 a b col)\n  obtain start steps where prog:\n    \"\\<And>i. i < k \\<Longrightarrow> steps i > 0\"\n    \"is_multi_arith_prog_on (l+1) k start steps a b\"\n    \"let f = multi_arith_prog k start steps\n     in  \\<forall>c \\<in> {0..<k} \\<rightarrow> {0..l}. \\<forall>s<k. (\\<forall> j \\<le> s. c j < l) \\<longrightarrow>\n            col (f c) = col (f (\\<lambda>i. if i \\<le> s then 0 else c i))\"\n    using assms 1 \n    by (elim vdw_lemmaE[where a=a and b=b and col=col and m=k \n          and k=k and l=l and n=N]) auto\n\n  text \\<open> Obtain a $k$-fold arithmetic progression $f$ of length $l$ from assumptions. \\<close>\n  define f where \"f = multi_arith_prog k start steps\" \n  have rel_propE: \"col (f c) = col (f (\\<lambda>i. if i \\<le> s then 0 else c i))\"\n    if \"c \\<in> {0..<k} \\<rightarrow> {0..l}\" \"s<k\" \"\\<forall> j \\<le> s. c j < l\"\n    for c s\n    using prog(3) that unfolding f_def Let_def by auto\n\n  text \\<open>There are $k+1$ values $a_r = f(0,\\dots,0,l,\\dots,l)$ with $0\\leq r\\leq k$ zeros.\\<close>\n  define a_r where \"a_r = (\\<lambda>r. f (\\<lambda>i. (if i<r then 0 else l)))\"\n  have range_col_a_r: \"col (a_r x) < k\" if \"x < k+1\" for x \n  proof -\n    have \"a_r x \\<in> {a..b}\" unfolding a_r_def f_def \n      by (intro is_multi_arith_prog_onD[OF prog(2)]) auto\n    thus ?thesis using 1 by blast\n  qed\n  then have \"(col \\<circ> a_r) ` {..<k + 1} \\<subseteq> {..<k}\" using 1(2) by auto\n  then have \"card ((col \\<circ> a_r) ` {..<k + 1}) \\<le> card {..<k}\"\n    by (intro card_mono) auto\n  then have \"\\<not> inj_on (col \\<circ> a_r) {..<k+1}\" \n    using pigeonhole[of \"col \\<circ> a_r\" \"{..<k+1}\"] by auto\n  text \\<open>Using the pigeonhole principle get $r_1$ and $r_2$ where $a_{r_1}$ and $a_{r_2}$ have the \n    same colour.\\<close>\n  then obtain r1 r2 where pigeon_cols:\n      \"r1\\<in>{..<k+1}\" \n      \"r2\\<in>{..<k+1}\" \n      \"r1 < r2\" \n      \"(col \\<circ> a_r) r1 = (col \\<circ> a_r) r2\"\n    by (metis (mono_tags, lifting) linear linorder_inj_onI)\n  text \\<open> Show that the following function $h$ is an arithmetic progression which fulfills all\n         properties for Van der Waerden's Theorem. \\<close>\n  define h where \n    \"h = (\\<lambda>x. f (\\<lambda>i. (if i<r1 then 0 else (if i<r2 then x else l))))\"\n  have \"h 0 = a_r r2\" unfolding h_def a_r_def using \\<open>r1<r2\\<close> \n    by (intro arg_cong[where f = f]) auto\n  moreover have \"h l = a_r r1\"  unfolding h_def a_r_def using \\<open>r1<r2\\<close>\n    by (metis le_eq_less_or_eq less_le_trans)\n  ultimately have \"col (h 0) = col (h l)\" using pigeon_cols(4) by auto\n  have h_col: \"col (h 0) = col (h i)\" if \"i\\<in>{..<l+1}\" for i\n  proof (cases \"i=l\")\n    case True\n    then show ?thesis using \\<open>col (h 0) = col (h l)\\<close> by auto\n  next\n    case False\n    then have \"i<l\" using that by auto\n    let ?c = \"(\\<lambda>idx. if idx < r1 then 0 else if idx < r2 then i else l)\"\n    have \"?c\\<in>{0..<k} \\<rightarrow> {0..l}\" \n      using that by auto\n    moreover have \"(\\<forall>j\\<le>r2-1. ?c j < l)\" \n      using \\<open>i<l\\<close> pigeon_cols(3) by force\n    ultimately have \"col (f ?c) = \n      col (f (\\<lambda>i. if i \\<le> r2-1 then 0 else ?c i))\"\n      using rel_propE[of ?c \"r2-1\"] pigeon_cols by simp\n    then show ?thesis unfolding h_def f_def \n      by (smt (z3) Nat.lessE One_nat_def add_diff_cancel_left' \n          le_less less_Suc_eq_le multi_arith_prog_mono plus_1_eq_Suc)\n  qed\n\n  define h_start where \"h_start = start + l*(\\<Sum>i\\<in>{r2..<k}. steps i)\"\n  define h_step where \"h_step = (\\<Sum>i\\<in>{r1..<r2}. steps i)\"\n  have h_arith_prog: \"h = arith_prog h_start h_step\" \n  proof -\n    have \"(\\<Sum>x<k. int (if x < r1 then 0 else if x < r2 then y else l)\n        * int (steps x)) =\n      int l * (\\<Sum>x = r2..<k. int (steps x)) + \n        int y * (\\<Sum>x = r1..<r2. int (steps x))\"\n      for y \n    proof (cases \"r2 = k\")\n      case True\n      then have \"r1<k\" using pigeon_cols by auto\n      with True have \n        \"(\\<Sum>x<k. int (if x < r1 then 0 else if x < r2 then y else l)\n           * int (steps x)) =\n         (\\<Sum>x<k. int (if x < r1 then 0 else y) * int (steps x))\"\n        by (intro sum.cong) auto\n      also have \"\\<dots> = (\\<Sum>x<r1. int (if x < r1 then 0 else y) *\n          int (steps x)) + (\\<Sum>x=r1..<k. int (if x < r1 then 0 else y)\n          * int (steps x))\"\n        using split_sum_mid_less[of r1 k \n            \"(\\<lambda>x. int (if x < r1 then 0 else y) * int (steps x))\"] \n            \\<open>r1<k\\<close> by auto\n      also have \"\\<dots> = (\\<Sum>x=r1..<k. int y * int (steps x))\" by auto\n      also have \"\\<dots> = int y * (\\<Sum>x=r1..<k. int (steps x))\" \n        by (auto simp: sum_distrib_left[of \"int y\"])\n      finally show ?thesis using True by auto\n    next\n      case False\n      then have \"r2<k\" using pigeon_cols by auto\n      define aux_left where \"aux_left = \n        (\\<lambda>x. int (if x < r1 then 0 else if x < r2 then y else l)\n          * int (steps x))\"\n      have \"(\\<Sum>x<k. aux_left x) = (\\<Sum>x=r1..<k. aux_left x)\"\n        by (intro sum.mono_neutral_right) (auto simp: aux_left_def)\n      also have \"{r1..<k} = {r1..<r2} \\<union> {r2..<k}\"\n        using \\<open>r1 < r2\\<close> \\<open>r2 < k\\<close> by auto\n      also have \"(\\<Sum>x\\<in>\\<dots>. aux_left x) = (\\<Sum>x=r1..<r2. aux_left x) + \n        (\\<Sum>x=r2..<k. aux_left x)\"\n        by (intro sum.union_disjoint) auto\n      also have \"(\\<Sum>x=r1..<r2. aux_left x) =\n        (\\<Sum>x=r1..<r2. int y * int (steps x))\"\n        by (intro sum.cong) (auto simp: aux_left_def)\n      also have \"(\\<Sum>x=r2..<k. aux_left x) = \n        (\\<Sum>x=r2..<k. int l * int (steps x))\"\n        using \\<open>r1 < r2\\<close> by (intro sum.cong) (auto simp: aux_left_def)\n      finally show ?thesis\n        by (simp add: aux_left_def sum_distrib_left)\n    qed\n    then show ?thesis\n      unfolding arith_prog_def h_start_def h_step_def h_def f_def\n        multi_arith_prog_def by (auto split:if_splits)\n  qed\n\n  define j where \"j = col (h 0)\"\n  have case_j: \"j<k\" using 1 range_col_a_r \\<open>col (h 0) = col (h l)\\<close> \n      \\<open>h l = a_r r1\\<close> j_def pigeon_cols(1) by auto\n  have case_step: \"h_step > 0\" unfolding h_step_def\n    using pigeon_cols by (intro sum_pos prog(1)) auto\n\n  have range_h: \"h i \\<in> {a..b}\" if \"i < l + 1\" for i\n    unfolding h_def f_def by (rule is_multi_arith_prog_onD[OF prog(2)])\n      (use that in auto)\n\n  have case_on: \"is_arith_prog_on (l+1) h_start h_step a b\"\n    unfolding is_arith_prog_on_def h_arith_prog \n    using range_h[of 0] range_h[of l]\n    by (auto simp: Max_ge[of \"{a..b}\"] Min_le[of \"{a..b}\"] \n        h_arith_prog arith_prog_def)\n\n  have case_col: \"h ` {..<Suc l} \\<subseteq> col -` {j} \\<inter> {a..b}\" \n    using h_col range_h unfolding j_def by auto\n\n  show ?case using case_j case_step case_on case_col \n    by (auto simp: h_arith_prog) \nqed\n\ntext \\<open> Lastly, we assemble all lemmas to finally prove Van der Waerden's Theorem by induction on \n$l$. The cases $l=1$ and the induction start $l=2$ are treated separately and have been shown \nearlier.\\<close>\ntheorem van_der_Waerden: assumes \"l>0\" \"k>0\" shows \"\\<exists>n. vdw k l n\"\nusing assms proof (induction l arbitrary: k rule: less_induct)\n  case (less l)\n  consider  \"l=1\" | \"l=2\" | \"l>2\" using less.prems by linarith\n  then show ?case\n  proof (cases)\n    assume \"l=1\"\n    then show ?thesis using vdw_1_right by auto\n  next\n    assume \"l=2\"\n    then show ?thesis using vdw_2_right by auto\n  next\n    assume \"l > 2\"\n    then have \"2\\<le>l-1\" by auto\n    from less.IH[of \"l-1\"] \\<open>l>2\\<close> \n    have \"\\<And>k'. k'>0 \\<Longrightarrow> \\<exists>n. vdw k' (l-1) n\" by auto\n    with vdw_imp_vdw_lemma[of \"l-1\" k k] \\<open>l-1\\<ge>2\\<close> \\<open>k>0\\<close> \n      obtain N where \"vdw_lemma k k (l-1) N\" by auto\n    then have \"vdw k l N\" using vdw_lemma_imp_vdw[of k \"l-1\" N]\n      by (simp add: less.prems(1))\n    then show ?thesis by auto\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/Van_der_Waerden/Van_der_Waerden.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8757869884059266, "lm_q2_score": 0.8418256512199033, "lm_q1q2_score": 0.737259951844737}}
{"text": "(* \nAuthors: \n  Anthony Bordg, University of Cambridge, apdb3@cam.ac.uk \n  Hanna Lachnitt, TU Wien, lachnitt@student.tuwien.ac.at\n*)\n\ntheory Binary_Nat\nimports\n  HOL.Nat\n  HOL.List\n  Basics\nbegin \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": "AnthonyBordg", "repo": "Isabelle_marries_Dirac", "sha": "ab313fb4028c99bd5d97f8e30aaf1644e200d57b", "save_path": "github-repos/isabelle/AnthonyBordg-Isabelle_marries_Dirac", "path": "github-repos/isabelle/AnthonyBordg-Isabelle_marries_Dirac/Isabelle_marries_Dirac-ab313fb4028c99bd5d97f8e30aaf1644e200d57b/Binary_Nat.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278664544911, "lm_q2_score": 0.8354835432479661, "lm_q1q2_score": 0.7372539605261413}}
{"text": "theory Isar\n  imports Main\nbegin\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\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 (metis Cantors_paradox Pow_UNIV)\n  thus \"False\" by blast\nqed\n\n\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/Isar.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.882427860270573, "lm_q2_score": 0.8354835309589074, "lm_q1q2_score": 0.7372539445153716}}
{"text": "header{* Lemmas about undirected graphs *}\n\ntheory Ugraph_Lemmas\nimports\n  Prob_Lemmas\n  \"../Girth_Chromatic/Girth_Chromatic\"\n  Lattices_Big\nbegin\n\ntext{* The complete graph is a graph where all possible edges are present. It is wellformed by\ndefinition. *}\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{* If the set of vertices is finite, the set of edges in the complete graph is finite. *}\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{* The sets of possible edges of disjoint sets of vertices are disjoint. *}\n\nlemma all_edges_disjoint: \"S \\<inter> T = {} \\<Longrightarrow> all_edges S \\<inter> all_edges T = {}\"\nunfolding all_edges_def\nby force\n\ntext{* A graph is called `finite' if its set of edges and its set of vertices are finite. *}\n\ndefinition \"finite_graph G \\<equiv> finite (uverts G) \\<and> finite (uedges G)\"\n\ntext{* The complete graph is finite. *}\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{* A graph is called `nonempty' if it contains at least one vertex and at least one edge. *}\n\ndefinition \"nonempty_graph G \\<equiv> uverts G \\<noteq> {} \\<and> uedges G \\<noteq> {}\"\n\ntext{* A random graph is both wellformed and finite. *}\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{* The probability for a random graph to have $e$ edges is $p ^ e$. *}\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{* Subgraphs *}\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 `u \\<noteq> v` 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{* Induced subgraphs *}\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{* Graph isomorphism *}\n\ntext{* 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. *}\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)\"\nunfolding fun_eq_iff\nby auto (metis imageI image_comp)+\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 pair_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{* Isomorphic subgraphs *}\n\ntext{* 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. *}\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) `subgraph G\\<^sub>2' G\\<^sub>3` 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{* Density *}\n\ntext{* The density of a graph is the quotient of the number of edges and the number of vertices of\na graph. *}\n\ndefinition density :: \"ugraph \\<Rightarrow> real\" where\n\"density G = card (uedges G) / card (uverts G)\"\n\ntext{* The maximum density of a graph is the density of its densest nonempty subgraph. *}\n\ndefinition max_density :: \"ugraph \\<Rightarrow> real\" where\n\"max_density G = Lattices_Big.Max (density ` nonempty_subgraphs G)\"\n\ntext{* 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. *}\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  --{* 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.} *}\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    --{* We observe that the set of densities of the subgraphs does not change if we map the\n         subgraphs first. *}\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 `uwellformed G`)\n        thus \"density G = density (map_ugraph f G)\"\n          by (fact isomorphic_density)\n      qed\n    --{* 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. *}\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{* Fixed selectors *}\n\ntext{* \\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.} *}\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{* 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. *}\n\nlemma ex_fixed_selector:\n  assumes \"uwellformed H\" and \"finite_graph H\"\n  obtains f where \"is_fixed_selector H f\"\nproof\n  --{* 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. *}\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": "Josh-Tilles", "repo": "AFP", "sha": "f4bf1d502bde2a3469d482b62c531f1c3af3e881", "save_path": "github-repos/isabelle/Josh-Tilles-AFP", "path": "github-repos/isabelle/Josh-Tilles-AFP/AFP-f4bf1d502bde2a3469d482b62c531f1c3af3e881/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.8991213826762114, "lm_q2_score": 0.819893340314393, "lm_q1q2_score": 0.7371836337904946}}
{"text": "(*  Title:      HOL/Algebra/Lattice.thy\n    Author:     Clemens Ballarin, started 7 November 2003\n    Copyright:  Clemens Ballarin\n\nMost congruence rules by Stephan Hohe.\nWith additional contributions from Alasdair Armstrong and Simon Foster.\n*)\n\ntheory Lattice\nimports Order\nbegin\n\nsection \\<open>Lattices\\<close>\n  \nsubsection \\<open>Supremum and infimum\\<close>\n\ndefinition\n  sup :: \"[_, 'a set] => 'a\" (\"\\<Squnion>\\<index>_\" [90] 90)\n  where \"\\<Squnion>\\<^bsub>L\\<^esub>A = (SOME x. least L x (Upper L A))\"\n\ndefinition\n  inf :: \"[_, 'a set] => 'a\" (\"\\<Sqinter>\\<index>_\" [90] 90)\n  where \"\\<Sqinter>\\<^bsub>L\\<^esub>A = (SOME x. greatest L x (Lower L A))\"\n\ndefinition supr :: \n  \"('a, 'b) gorder_scheme \\<Rightarrow> 'c set \\<Rightarrow> ('c \\<Rightarrow> 'a) \\<Rightarrow> 'a \"\n  where \"supr L A f = \\<Squnion>\\<^bsub>L\\<^esub>(f ` A)\"\n\ndefinition infi :: \n  \"('a, 'b) gorder_scheme \\<Rightarrow> 'c set \\<Rightarrow> ('c \\<Rightarrow> 'a) \\<Rightarrow> 'a \"\n  where \"infi L A f = \\<Sqinter>\\<^bsub>L\\<^esub>(f ` A)\"\n\nsyntax\n  \"_inf1\"     :: \"('a, 'b) gorder_scheme \\<Rightarrow> pttrns \\<Rightarrow> 'a \\<Rightarrow> 'a\" (\"(3IINF\\<index> _./ _)\" [0, 10] 10)\n  \"_inf\"      :: \"('a, 'b) gorder_scheme \\<Rightarrow> pttrn \\<Rightarrow> 'c set \\<Rightarrow> 'a \\<Rightarrow> 'a\"  (\"(3IINF\\<index> _:_./ _)\" [0, 0, 10] 10)\n  \"_sup1\"     :: \"('a, 'b) gorder_scheme \\<Rightarrow> pttrns \\<Rightarrow> 'a \\<Rightarrow> 'a\" (\"(3SSUP\\<index> _./ _)\" [0, 10] 10)\n  \"_sup\"      :: \"('a, 'b) gorder_scheme \\<Rightarrow> pttrn \\<Rightarrow> 'c set \\<Rightarrow> 'a \\<Rightarrow> 'a\"  (\"(3SSUP\\<index> _:_./ _)\" [0, 0, 10] 10)\n\ntranslations\n  \"IINF\\<^bsub>L\\<^esub> x. B\"     == \"CONST infi L CONST UNIV (%x. B)\"\n  \"IINF\\<^bsub>L\\<^esub> x:A. B\"   == \"CONST infi L A (%x. B)\"\n  \"SSUP\\<^bsub>L\\<^esub> x. B\"     == \"CONST supr L CONST UNIV (%x. B)\"\n  \"SSUP\\<^bsub>L\\<^esub> x:A. B\"   == \"CONST supr L A (%x. B)\"\n\ndefinition\n  join :: \"[_, 'a, 'a] => 'a\" (infixl \"\\<squnion>\\<index>\" 65)\n  where \"x \\<squnion>\\<^bsub>L\\<^esub> y = \\<Squnion>\\<^bsub>L\\<^esub>{x, y}\"\n\ndefinition\n  meet :: \"[_, 'a, 'a] => 'a\" (infixl \"\\<sqinter>\\<index>\" 70)\n  where \"x \\<sqinter>\\<^bsub>L\\<^esub> y = \\<Sqinter>\\<^bsub>L\\<^esub>{x, y}\"\n\ndefinition\n  LEAST_FP :: \"('a, 'b) gorder_scheme \\<Rightarrow> ('a \\<Rightarrow> 'a) \\<Rightarrow> 'a\" (\"LFP\\<index>\") where\n  \"LEAST_FP L f = \\<Sqinter>\\<^bsub>L\\<^esub> {u \\<in> carrier L. f u \\<sqsubseteq>\\<^bsub>L\\<^esub> u}\"    \\<comment> \\<open>least fixed point\\<close>\n\ndefinition\n  GREATEST_FP:: \"('a, 'b) gorder_scheme \\<Rightarrow> ('a \\<Rightarrow> 'a) \\<Rightarrow> 'a\" (\"GFP\\<index>\") where\n  \"GREATEST_FP L f = \\<Squnion>\\<^bsub>L\\<^esub> {u \\<in> carrier L. u \\<sqsubseteq>\\<^bsub>L\\<^esub> f u}\"    \\<comment> \\<open>greatest fixed point\\<close>\n\n\nsubsection \\<open>Dual operators\\<close>\n\nlemma sup_dual [simp]: \n  \"\\<Squnion>\\<^bsub>inv_gorder L\\<^esub>A = \\<Sqinter>\\<^bsub>L\\<^esub>A\"\n  by (simp add: sup_def inf_def)\n\nlemma inf_dual [simp]: \n  \"\\<Sqinter>\\<^bsub>inv_gorder L\\<^esub>A = \\<Squnion>\\<^bsub>L\\<^esub>A\"\n  by (simp add: sup_def inf_def)\n\nlemma join_dual [simp]:\n  \"p \\<squnion>\\<^bsub>inv_gorder L\\<^esub> q = p \\<sqinter>\\<^bsub>L\\<^esub> q\"\n  by (simp add:join_def meet_def)\n\nlemma meet_dual [simp]:\n  \"p \\<sqinter>\\<^bsub>inv_gorder L\\<^esub> q = p \\<squnion>\\<^bsub>L\\<^esub> q\"\n  by (simp add:join_def meet_def)\n\nlemma top_dual [simp]:\n  \"\\<top>\\<^bsub>inv_gorder L\\<^esub> = \\<bottom>\\<^bsub>L\\<^esub>\"\n  by (simp add: top_def bottom_def)\n\nlemma bottom_dual [simp]:\n  \"\\<bottom>\\<^bsub>inv_gorder L\\<^esub> = \\<top>\\<^bsub>L\\<^esub>\"\n  by (simp add: top_def bottom_def)\n\nlemma LFP_dual [simp]:\n  \"LEAST_FP (inv_gorder L) f = GREATEST_FP L f\"\n  by (simp add:LEAST_FP_def GREATEST_FP_def)\n\nlemma GFP_dual [simp]:\n  \"GREATEST_FP (inv_gorder L) f = LEAST_FP L f\"\n  by (simp add:LEAST_FP_def GREATEST_FP_def)\n\n\nsubsection \\<open>Lattices\\<close>\n\nlocale weak_upper_semilattice = weak_partial_order +\n  assumes sup_of_two_exists:\n    \"[| x \\<in> carrier L; y \\<in> carrier L |] ==> \\<exists>s. least L s (Upper L {x, y})\"\n\nlocale weak_lower_semilattice = weak_partial_order +\n  assumes inf_of_two_exists:\n    \"[| x \\<in> carrier L; y \\<in> carrier L |] ==> \\<exists>s. greatest L s (Lower L {x, y})\"\n\nlocale weak_lattice = weak_upper_semilattice + weak_lower_semilattice\n\nlemma (in weak_lattice) dual_weak_lattice:\n  \"weak_lattice (inv_gorder L)\"\nproof -\n  interpret dual: weak_partial_order \"inv_gorder L\"\n    by (metis dual_weak_order)\n  show ?thesis\n  proof qed (simp_all add: inf_of_two_exists sup_of_two_exists)\nqed\n\n\nsubsubsection \\<open>Supremum\\<close>\n\nlemma (in weak_upper_semilattice) joinI:\n  \"[| !!l. least L l (Upper L {x, y}) ==> P l; x \\<in> carrier L; y \\<in> carrier L |]\n  ==> P (x \\<squnion> y)\"\nproof (unfold join_def sup_def)\n  assume L: \"x \\<in> carrier L\"  \"y \\<in> carrier L\"\n    and P: \"!!l. least L l (Upper L {x, y}) ==> P l\"\n  with sup_of_two_exists obtain s where \"least L s (Upper L {x, y})\" by fast\n  with L show \"P (SOME l. least L l (Upper L {x, y}))\"\n    by (fast intro: someI2 P)\nqed\n\nlemma (in weak_upper_semilattice) join_closed [simp]:\n  \"[| x \\<in> carrier L; y \\<in> carrier L |] ==> x \\<squnion> y \\<in> carrier L\"\n  by (rule joinI) (rule least_closed)\n\nlemma (in weak_upper_semilattice) join_cong_l:\n  assumes carr: \"x \\<in> carrier L\" \"x' \\<in> carrier L\" \"y \\<in> carrier L\"\n    and xx': \"x .= x'\"\n  shows \"x \\<squnion> y .= x' \\<squnion> y\"\nproof (rule joinI, rule joinI)\n  fix a b\n  from xx' carr\n      have seq: \"{x, y} {.=} {x', y}\" by (rule set_eq_pairI)\n\n  assume leasta: \"least L a (Upper L {x, y})\"\n  assume \"least L b (Upper L {x', y})\"\n  with carr\n      have leastb: \"least L b (Upper L {x, y})\"\n      by (simp add: least_Upper_cong_r[OF _ _ seq])\n\n  from leasta leastb\n      show \"a .= b\" by (rule weak_least_unique)\nqed (rule carr)+\n\nlemma (in weak_upper_semilattice) join_cong_r:\n  assumes carr: \"x \\<in> carrier L\" \"y \\<in> carrier L\" \"y' \\<in> carrier L\"\n    and yy': \"y .= y'\"\n  shows \"x \\<squnion> y .= x \\<squnion> y'\"\nproof (rule joinI, rule joinI)\n  fix a b\n  have \"{x, y} = {y, x}\" by fast\n  also from carr yy'\n      have \"{y, x} {.=} {y', x}\" by (intro set_eq_pairI)\n  also have \"{y', x} = {x, y'}\" by fast\n  finally\n      have seq: \"{x, y} {.=} {x, y'}\" .\n\n  assume leasta: \"least L a (Upper L {x, y})\"\n  assume \"least L b (Upper L {x, y'})\"\n  with carr\n      have leastb: \"least L b (Upper L {x, y})\"\n      by (simp add: least_Upper_cong_r[OF _ _ seq])\n\n  from leasta leastb\n      show \"a .= b\" by (rule weak_least_unique)\nqed (rule carr)+\n\nlemma (in weak_partial_order) sup_of_singletonI:      (* only reflexivity needed ? *)\n  \"x \\<in> carrier L ==> least L x (Upper L {x})\"\n  by (rule least_UpperI) auto\n\nlemma (in weak_partial_order) weak_sup_of_singleton [simp]:\n  \"x \\<in> carrier L ==> \\<Squnion>{x} .= x\"\n  unfolding sup_def\n  by (rule someI2) (auto intro: weak_least_unique sup_of_singletonI)\n\nlemma (in weak_partial_order) sup_of_singleton_closed [simp]:\n  \"x \\<in> carrier L \\<Longrightarrow> \\<Squnion>{x} \\<in> carrier L\"\n  unfolding sup_def\n  by (rule someI2) (auto intro: sup_of_singletonI)\n\ntext \\<open>Condition on \\<open>A\\<close>: supremum exists.\\<close>\n\nlemma (in weak_upper_semilattice) sup_insertI:\n  \"[| !!s. least L s (Upper L (insert x A)) ==> P s;\n  least L a (Upper L A); x \\<in> carrier L; A \\<subseteq> carrier L |]\n  ==> P (\\<Squnion>(insert x A))\"\nproof (unfold sup_def)\n  assume L: \"x \\<in> carrier L\"  \"A \\<subseteq> carrier L\"\n    and P: \"!!l. least L l (Upper L (insert x A)) ==> P l\"\n    and least_a: \"least L a (Upper L A)\"\n  from L least_a have La: \"a \\<in> carrier L\" by simp\n  from L sup_of_two_exists least_a\n  obtain s where least_s: \"least L s (Upper L {a, x})\" by blast\n  show \"P (SOME l. least L l (Upper L (insert x A)))\"\n  proof (rule someI2)\n    show \"least L s (Upper L (insert x A))\"\n    proof (rule least_UpperI)\n      fix z\n      assume \"z \\<in> insert x A\"\n      then show \"z \\<sqsubseteq> s\"\n      proof\n        assume \"z = x\" then show ?thesis\n          by (simp add: least_Upper_above [OF least_s] L La)\n      next\n        assume \"z \\<in> A\"\n        with L least_s least_a show ?thesis\n          by (rule_tac le_trans [where y = a]) (auto dest: least_Upper_above)\n      qed\n    next\n      fix y\n      assume y: \"y \\<in> Upper L (insert x A)\"\n      show \"s \\<sqsubseteq> y\"\n      proof (rule least_le [OF least_s], rule Upper_memI)\n        fix z\n        assume z: \"z \\<in> {a, x}\"\n        then show \"z \\<sqsubseteq> y\"\n        proof\n          have y': \"y \\<in> Upper L A\"\n            by (meson Upper_antimono in_mono subset_insertI y)\n          assume \"z = a\"\n          with y' least_a show ?thesis by (fast dest: least_le)\n        next\n          assume \"z \\<in> {x}\"\n          with y L show ?thesis by blast\n        qed\n      qed (rule Upper_closed [THEN subsetD, OF y])\n    next\n      from L show \"insert x A \\<subseteq> carrier L\" by simp\n      from least_s show \"s \\<in> carrier L\" by simp\n    qed\n  qed (rule P)\nqed\n\nlemma (in weak_upper_semilattice) finite_sup_least:\n  \"[| finite A; A \\<subseteq> carrier L; A \\<noteq> {} |] ==> least L (\\<Squnion>A) (Upper L A)\"\nproof (induct set: finite)\n  case empty\n  then show ?case by simp\nnext\n  case (insert x A)\n  show ?case\n  proof (cases \"A = {}\")\n    case True\n    with insert show ?thesis\n      by simp (simp add: least_cong [OF weak_sup_of_singleton] sup_of_singletonI)\n        (* The above step is hairy; least_cong can make simp loop.\n        Would want special version of simp to apply least_cong. *)\n  next\n    case False\n    with insert have \"least L (\\<Squnion>A) (Upper L A)\" by simp\n    with _ show ?thesis\n      by (rule sup_insertI) (simp_all add: insert [simplified])\n  qed\nqed\n\nlemma (in weak_upper_semilattice) finite_sup_insertI:\n  assumes P: \"!!l. least L l (Upper L (insert x A)) ==> P l\"\n    and xA: \"finite A\"  \"x \\<in> carrier L\"  \"A \\<subseteq> carrier L\"\n  shows \"P (\\<Squnion> (insert x A))\"\nproof (cases \"A = {}\")\n  case True with P and xA show ?thesis\n    by (simp add: finite_sup_least)\nnext\n  case False with P and xA show ?thesis\n    by (simp add: sup_insertI finite_sup_least)\nqed\n\nlemma (in weak_upper_semilattice) finite_sup_closed [simp]:\n  \"[| finite A; A \\<subseteq> carrier L; A \\<noteq> {} |] ==> \\<Squnion>A \\<in> carrier L\"\nproof (induct set: finite)\n  case empty then show ?case by simp\nnext\n  case insert then show ?case\n    by - (rule finite_sup_insertI, simp_all)\nqed\n\nlemma (in weak_upper_semilattice) join_left:\n  \"[| x \\<in> carrier L; y \\<in> carrier L |] ==> x \\<sqsubseteq> x \\<squnion> y\"\n  by (rule joinI [folded join_def]) (blast dest: least_mem)\n\nlemma (in weak_upper_semilattice) join_right:\n  \"[| x \\<in> carrier L; y \\<in> carrier L |] ==> y \\<sqsubseteq> x \\<squnion> y\"\n  by (rule joinI [folded join_def]) (blast dest: least_mem)\n\nlemma (in weak_upper_semilattice) sup_of_two_least:\n  \"[| x \\<in> carrier L; y \\<in> carrier L |] ==> least L (\\<Squnion>{x, y}) (Upper L {x, y})\"\nproof (unfold sup_def)\n  assume L: \"x \\<in> carrier L\"  \"y \\<in> carrier L\"\n  with sup_of_two_exists obtain s where \"least L s (Upper L {x, y})\" by fast\n  with L show \"least L (SOME z. least L z (Upper L {x, y})) (Upper L {x, y})\"\n  by (fast intro: someI2 weak_least_unique)  (* blast fails *)\nqed\n\nlemma (in weak_upper_semilattice) join_le:\n  assumes sub: \"x \\<sqsubseteq> z\"  \"y \\<sqsubseteq> z\"\n    and x: \"x \\<in> carrier L\" and y: \"y \\<in> carrier L\" and z: \"z \\<in> carrier L\"\n  shows \"x \\<squnion> y \\<sqsubseteq> z\"\nproof (rule joinI [OF _ x y])\n  fix s\n  assume \"least L s (Upper L {x, y})\"\n  with sub z show \"s \\<sqsubseteq> z\" by (fast elim: least_le intro: Upper_memI)\nqed\n\nlemma (in weak_lattice) weak_le_iff_meet:\n  assumes \"x \\<in> carrier L\" \"y \\<in> carrier L\"\n  shows \"x \\<sqsubseteq> y \\<longleftrightarrow> (x \\<squnion> y) .= y\"\n  by (meson assms(1) assms(2) join_closed join_le join_left join_right le_cong_r local.le_refl weak_le_antisym)\n  \nlemma (in weak_upper_semilattice) weak_join_assoc_lemma:\n  assumes L: \"x \\<in> carrier L\"  \"y \\<in> carrier L\"  \"z \\<in> carrier L\"\n  shows \"x \\<squnion> (y \\<squnion> z) .= \\<Squnion>{x, y, z}\"\nproof (rule finite_sup_insertI)\n  \\<comment> \\<open>The textbook argument in Jacobson I, p 457\\<close>\n  fix s\n  assume sup: \"least L s (Upper L {x, y, z})\"\n  show \"x \\<squnion> (y \\<squnion> z) .= s\"\n  proof (rule weak_le_antisym)\n    from sup L show \"x \\<squnion> (y \\<squnion> z) \\<sqsubseteq> s\"\n      by (fastforce intro!: join_le elim: least_Upper_above)\n  next\n    from sup L show \"s \\<sqsubseteq> x \\<squnion> (y \\<squnion> z)\"\n    by (erule_tac least_le)\n      (blast intro!: Upper_memI intro: le_trans join_left join_right join_closed)\n  qed (simp_all add: L least_closed [OF sup])\nqed (simp_all add: L)\n\ntext \\<open>Commutativity holds for \\<open>=\\<close>.\\<close>\n\nlemma join_comm:\n  fixes L (structure)\n  shows \"x \\<squnion> y = y \\<squnion> x\"\n  by (unfold join_def) (simp add: insert_commute)\n\nlemma (in weak_upper_semilattice) weak_join_assoc:\n  assumes L: \"x \\<in> carrier L\"  \"y \\<in> carrier L\"  \"z \\<in> carrier L\"\n  shows \"(x \\<squnion> y) \\<squnion> z .= x \\<squnion> (y \\<squnion> z)\"\nproof -\n  (* FIXME: could be simplified by improved simp: uniform use of .=,\n     omit [symmetric] in last step. *)\n  have \"(x \\<squnion> y) \\<squnion> z = z \\<squnion> (x \\<squnion> y)\" by (simp only: join_comm)\n  also from L have \"... .= \\<Squnion>{z, x, y}\" by (simp add: weak_join_assoc_lemma)\n  also from L have \"... = \\<Squnion>{x, y, z}\" by (simp add: insert_commute)\n  also from L have \"... .= x \\<squnion> (y \\<squnion> z)\" by (simp add: weak_join_assoc_lemma [symmetric])\n  finally show ?thesis by (simp add: L)\nqed\n\n\nsubsubsection \\<open>Infimum\\<close>\n\nlemma (in weak_lower_semilattice) meetI:\n  \"[| !!i. greatest L i (Lower L {x, y}) ==> P i;\n  x \\<in> carrier L; y \\<in> carrier L |]\n  ==> P (x \\<sqinter> y)\"\nproof (unfold meet_def inf_def)\n  assume L: \"x \\<in> carrier L\"  \"y \\<in> carrier L\"\n    and P: \"!!g. greatest L g (Lower L {x, y}) ==> P g\"\n  with inf_of_two_exists obtain i where \"greatest L i (Lower L {x, y})\" by fast\n  with L show \"P (SOME g. greatest L g (Lower L {x, y}))\"\n  by (fast intro: someI2 weak_greatest_unique P)\nqed\n\nlemma (in weak_lower_semilattice) meet_closed [simp]:\n  \"[| x \\<in> carrier L; y \\<in> carrier L |] ==> x \\<sqinter> y \\<in> carrier L\"\n  by (rule meetI) (rule greatest_closed)\n\nlemma (in weak_lower_semilattice) meet_cong_l:\n  assumes carr: \"x \\<in> carrier L\" \"x' \\<in> carrier L\" \"y \\<in> carrier L\"\n    and xx': \"x .= x'\"\n  shows \"x \\<sqinter> y .= x' \\<sqinter> y\"\nproof (rule meetI, rule meetI)\n  fix a b\n  from xx' carr\n      have seq: \"{x, y} {.=} {x', y}\" by (rule set_eq_pairI)\n\n  assume greatesta: \"greatest L a (Lower L {x, y})\"\n  assume \"greatest L b (Lower L {x', y})\"\n  with carr\n      have greatestb: \"greatest L b (Lower L {x, y})\"\n      by (simp add: greatest_Lower_cong_r[OF _ _ seq])\n\n  from greatesta greatestb\n      show \"a .= b\" by (rule weak_greatest_unique)\nqed (rule carr)+\n\nlemma (in weak_lower_semilattice) meet_cong_r:\n  assumes carr: \"x \\<in> carrier L\" \"y \\<in> carrier L\" \"y' \\<in> carrier L\"\n    and yy': \"y .= y'\"\n  shows \"x \\<sqinter> y .= x \\<sqinter> y'\"\nproof (rule meetI, rule meetI)\n  fix a b\n  have \"{x, y} = {y, x}\" by fast\n  also from carr yy'\n      have \"{y, x} {.=} {y', x}\" by (intro set_eq_pairI)\n  also have \"{y', x} = {x, y'}\" by fast\n  finally\n      have seq: \"{x, y} {.=} {x, y'}\" .\n\n  assume greatesta: \"greatest L a (Lower L {x, y})\"\n  assume \"greatest L b (Lower L {x, y'})\"\n  with carr\n      have greatestb: \"greatest L b (Lower L {x, y})\"\n      by (simp add: greatest_Lower_cong_r[OF _ _ seq])\n\n  from greatesta greatestb\n      show \"a .= b\" by (rule weak_greatest_unique)\nqed (rule carr)+\n\nlemma (in weak_partial_order) inf_of_singletonI:      (* only reflexivity needed ? *)\n  \"x \\<in> carrier L ==> greatest L x (Lower L {x})\"\n  by (rule greatest_LowerI) auto\n\nlemma (in weak_partial_order) weak_inf_of_singleton [simp]:\n  \"x \\<in> carrier L ==> \\<Sqinter>{x} .= x\"\n  unfolding inf_def\n  by (rule someI2) (auto intro: weak_greatest_unique inf_of_singletonI)\n\nlemma (in weak_partial_order) inf_of_singleton_closed:\n  \"x \\<in> carrier L ==> \\<Sqinter>{x} \\<in> carrier L\"\n  unfolding inf_def\n  by (rule someI2) (auto intro: inf_of_singletonI)\n\ntext \\<open>Condition on \\<open>A\\<close>: infimum exists.\\<close>\n\nlemma (in weak_lower_semilattice) inf_insertI:\n  \"[| !!i. greatest L i (Lower L (insert x A)) ==> P i;\n  greatest L a (Lower L A); x \\<in> carrier L; A \\<subseteq> carrier L |]\n  ==> P (\\<Sqinter>(insert x A))\"\nproof (unfold inf_def)\n  assume L: \"x \\<in> carrier L\"  \"A \\<subseteq> carrier L\"\n    and P: \"!!g. greatest L g (Lower L (insert x A)) ==> P g\"\n    and greatest_a: \"greatest L a (Lower L A)\"\n  from L greatest_a have La: \"a \\<in> carrier L\" by simp\n  from L inf_of_two_exists greatest_a\n  obtain i where greatest_i: \"greatest L i (Lower L {a, x})\" by blast\n  show \"P (SOME g. greatest L g (Lower L (insert x A)))\"\n  proof (rule someI2)\n    show \"greatest L i (Lower L (insert x A))\"\n    proof (rule greatest_LowerI)\n      fix z\n      assume \"z \\<in> insert x A\"\n      then show \"i \\<sqsubseteq> z\"\n      proof\n        assume \"z = x\" then show ?thesis\n          by (simp add: greatest_Lower_below [OF greatest_i] L La)\n      next\n        assume \"z \\<in> A\"\n        with L greatest_i greatest_a show ?thesis\n          by (rule_tac le_trans [where y = a]) (auto dest: greatest_Lower_below)\n      qed\n    next\n      fix y\n      assume y: \"y \\<in> Lower L (insert x A)\"\n      show \"y \\<sqsubseteq> i\"\n      proof (rule greatest_le [OF greatest_i], rule Lower_memI)\n        fix z\n        assume z: \"z \\<in> {a, x}\"\n        then show \"y \\<sqsubseteq> z\"\n        proof\n          have y': \"y \\<in> Lower L A\"\n            by (meson Lower_antimono in_mono subset_insertI y)\n          assume \"z = a\"\n          with y' greatest_a show ?thesis by (fast dest: greatest_le)\n        next\n          assume \"z \\<in> {x}\"\n          with y L show ?thesis by blast\n        qed\n      qed (rule Lower_closed [THEN subsetD, OF y])\n    next\n      from L show \"insert x A \\<subseteq> carrier L\" by simp\n      from greatest_i show \"i \\<in> carrier L\" by simp\n    qed\n  qed (rule P)\nqed\n\nlemma (in weak_lower_semilattice) finite_inf_greatest:\n  \"[| finite A; A \\<subseteq> carrier L; A \\<noteq> {} |] ==> greatest L (\\<Sqinter>A) (Lower L A)\"\nproof (induct set: finite)\n  case empty then show ?case by simp\nnext\n  case (insert x A)\n  show ?case\n  proof (cases \"A = {}\")\n    case True\n    with insert show ?thesis\n      by simp (simp add: greatest_cong [OF weak_inf_of_singleton]\n        inf_of_singleton_closed inf_of_singletonI)\n  next\n    case False\n    from insert show ?thesis\n    proof (rule_tac inf_insertI)\n      from False insert show \"greatest L (\\<Sqinter>A) (Lower L A)\" by simp\n    qed simp_all\n  qed\nqed\n\nlemma (in weak_lower_semilattice) finite_inf_insertI:\n  assumes P: \"!!i. greatest L i (Lower L (insert x A)) ==> P i\"\n    and xA: \"finite A\"  \"x \\<in> carrier L\"  \"A \\<subseteq> carrier L\"\n  shows \"P (\\<Sqinter> (insert x A))\"\nproof (cases \"A = {}\")\n  case True with P and xA show ?thesis\n    by (simp add: finite_inf_greatest)\nnext\n  case False with P and xA show ?thesis\n    by (simp add: inf_insertI finite_inf_greatest)\nqed\n\nlemma (in weak_lower_semilattice) finite_inf_closed [simp]:\n  \"[| finite A; A \\<subseteq> carrier L; A \\<noteq> {} |] ==> \\<Sqinter>A \\<in> carrier L\"\nproof (induct set: finite)\n  case empty then show ?case by simp\nnext\n  case insert then show ?case\n    by (rule_tac finite_inf_insertI) (simp_all)\nqed\n\nlemma (in weak_lower_semilattice) meet_left:\n  \"[| x \\<in> carrier L; y \\<in> carrier L |] ==> x \\<sqinter> y \\<sqsubseteq> x\"\n  by (rule meetI [folded meet_def]) (blast dest: greatest_mem)\n\nlemma (in weak_lower_semilattice) meet_right:\n  \"[| x \\<in> carrier L; y \\<in> carrier L |] ==> x \\<sqinter> y \\<sqsubseteq> y\"\n  by (rule meetI [folded meet_def]) (blast dest: greatest_mem)\n\nlemma (in weak_lower_semilattice) inf_of_two_greatest:\n  \"[| x \\<in> carrier L; y \\<in> carrier L |] ==>\n  greatest L (\\<Sqinter>{x, y}) (Lower L {x, y})\"\nproof (unfold inf_def)\n  assume L: \"x \\<in> carrier L\"  \"y \\<in> carrier L\"\n  with inf_of_two_exists obtain s where \"greatest L s (Lower L {x, y})\" by fast\n  with L\n  show \"greatest L (SOME z. greatest L z (Lower L {x, y})) (Lower L {x, y})\"\n  by (fast intro: someI2 weak_greatest_unique)  (* blast fails *)\nqed\n\nlemma (in weak_lower_semilattice) meet_le:\n  assumes sub: \"z \\<sqsubseteq> x\"  \"z \\<sqsubseteq> y\"\n    and x: \"x \\<in> carrier L\" and y: \"y \\<in> carrier L\" and z: \"z \\<in> carrier L\"\n  shows \"z \\<sqsubseteq> x \\<sqinter> y\"\nproof (rule meetI [OF _ x y])\n  fix i\n  assume \"greatest L i (Lower L {x, y})\"\n  with sub z show \"z \\<sqsubseteq> i\" by (fast elim: greatest_le intro: Lower_memI)\nqed\n\nlemma (in weak_lattice) weak_le_iff_join:\n  assumes \"x \\<in> carrier L\" \"y \\<in> carrier L\"\n  shows \"x \\<sqsubseteq> y \\<longleftrightarrow> x .= (x \\<sqinter> y)\"\n  by (meson assms(1) assms(2) local.le_refl local.le_trans meet_closed meet_le meet_left meet_right weak_le_antisym weak_refl)\n  \nlemma (in weak_lower_semilattice) weak_meet_assoc_lemma:\n  assumes L: \"x \\<in> carrier L\"  \"y \\<in> carrier L\"  \"z \\<in> carrier L\"\n  shows \"x \\<sqinter> (y \\<sqinter> z) .= \\<Sqinter>{x, y, z}\"\nproof (rule finite_inf_insertI)\n  txt \\<open>The textbook argument in Jacobson I, p 457\\<close>\n  fix i\n  assume inf: \"greatest L i (Lower L {x, y, z})\"\n  show \"x \\<sqinter> (y \\<sqinter> z) .= i\"\n  proof (rule weak_le_antisym)\n    from inf L show \"i \\<sqsubseteq> x \\<sqinter> (y \\<sqinter> z)\"\n      by (fastforce intro!: meet_le elim: greatest_Lower_below)\n  next\n    from inf L show \"x \\<sqinter> (y \\<sqinter> z) \\<sqsubseteq> i\"\n    by (erule_tac greatest_le)\n      (blast intro!: Lower_memI intro: le_trans meet_left meet_right meet_closed)\n  qed (simp_all add: L greatest_closed [OF inf])\nqed (simp_all add: L)\n\n\n\nlemma (in weak_lower_semilattice) weak_meet_assoc:\n  assumes L: \"x \\<in> carrier L\"  \"y \\<in> carrier L\"  \"z \\<in> carrier L\"\n  shows \"(x \\<sqinter> y) \\<sqinter> z .= x \\<sqinter> (y \\<sqinter> z)\"\nproof -\n  (* FIXME: improved simp, see weak_join_assoc above *)\n  have \"(x \\<sqinter> y) \\<sqinter> z = z \\<sqinter> (x \\<sqinter> y)\" by (simp only: meet_comm)\n  also from L have \"... .= \\<Sqinter> {z, x, y}\" by (simp add: weak_meet_assoc_lemma)\n  also from L have \"... = \\<Sqinter> {x, y, z}\" by (simp add: insert_commute)\n  also from L have \"... .= x \\<sqinter> (y \\<sqinter> z)\" by (simp add: weak_meet_assoc_lemma [symmetric])\n  finally show ?thesis by (simp add: L)\nqed\n\ntext \\<open>Total orders are lattices.\\<close>\n\nsublocale weak_total_order \\<subseteq> weak?: weak_lattice\nproof\n  fix x y\n  assume L: \"x \\<in> carrier L\"  \"y \\<in> carrier L\"\n  show \"\\<exists>s. least L s (Upper L {x, y})\"\n  proof -\n    note total L\n    moreover\n    {\n      assume \"x \\<sqsubseteq> y\"\n      with L have \"least L y (Upper L {x, y})\"\n        by (rule_tac least_UpperI) auto\n    }\n    moreover\n    {\n      assume \"y \\<sqsubseteq> x\"\n      with L have \"least L x (Upper L {x, y})\"\n        by (rule_tac least_UpperI) auto\n    }\n    ultimately show ?thesis by blast\n  qed\nnext\n  fix x y\n  assume L: \"x \\<in> carrier L\"  \"y \\<in> carrier L\"\n  show \"\\<exists>i. greatest L i (Lower L {x, y})\"\n  proof -\n    note total L\n    moreover\n    {\n      assume \"y \\<sqsubseteq> x\"\n      with L have \"greatest L y (Lower L {x, y})\"\n        by (rule_tac greatest_LowerI) auto\n    }\n    moreover\n    {\n      assume \"x \\<sqsubseteq> y\"\n      with L have \"greatest L x (Lower L {x, y})\"\n        by (rule_tac greatest_LowerI) auto\n    }\n    ultimately show ?thesis by blast\n  qed\nqed\n\n\nsubsection \\<open>Weak Bounded Lattices\\<close>\n\nlocale weak_bounded_lattice = \n  weak_lattice + \n  weak_partial_order_bottom + \n  weak_partial_order_top\nbegin\n\nlemma bottom_meet: \"x \\<in> carrier L \\<Longrightarrow> \\<bottom> \\<sqinter> x .= \\<bottom>\"\n  by (metis bottom_least least_def meet_closed meet_left weak_le_antisym)\n\nlemma bottom_join: \"x \\<in> carrier L \\<Longrightarrow> \\<bottom> \\<squnion> x .= x\"\n  by (metis bottom_least join_closed join_le join_right le_refl least_def weak_le_antisym)\n\nlemma bottom_weak_eq:\n  \"\\<lbrakk> b \\<in> carrier L; \\<And> x. x \\<in> carrier L \\<Longrightarrow> b \\<sqsubseteq> x \\<rbrakk> \\<Longrightarrow> b .= \\<bottom>\"\n  by (metis bottom_closed bottom_lower weak_le_antisym)\n\nlemma top_join: \"x \\<in> carrier L \\<Longrightarrow> \\<top> \\<squnion> x .= \\<top>\"\n  by (metis join_closed join_left top_closed top_higher weak_le_antisym)\n\nlemma top_meet: \"x \\<in> carrier L \\<Longrightarrow> \\<top> \\<sqinter> x .= x\"\n  by (metis le_refl meet_closed meet_le meet_right top_closed top_higher weak_le_antisym)\n\nlemma top_weak_eq:  \"\\<lbrakk> t \\<in> carrier L; \\<And> x. x \\<in> carrier L \\<Longrightarrow> x \\<sqsubseteq> t \\<rbrakk> \\<Longrightarrow> t .= \\<top>\"\n  by (metis top_closed top_higher weak_le_antisym)\n\nend\n\nsublocale weak_bounded_lattice \\<subseteq> weak_partial_order ..\n\n\nsubsection \\<open>Lattices where \\<open>eq\\<close> is the Equality\\<close>\n\nlocale upper_semilattice = partial_order +\n  assumes sup_of_two_exists:\n    \"[| x \\<in> carrier L; y \\<in> carrier L |] ==> \\<exists>s. least L s (Upper L {x, y})\"\n\nsublocale upper_semilattice \\<subseteq> weak?: weak_upper_semilattice\n  by unfold_locales (rule sup_of_two_exists)\n\nlocale lower_semilattice = partial_order +\n  assumes inf_of_two_exists:\n    \"[| x \\<in> carrier L; y \\<in> carrier L |] ==> \\<exists>s. greatest L s (Lower L {x, y})\"\n\nsublocale lower_semilattice \\<subseteq> weak?: weak_lower_semilattice\n  by unfold_locales (rule inf_of_two_exists)\n\nlocale lattice = upper_semilattice + lower_semilattice\n\nsublocale lattice \\<subseteq> weak_lattice ..\n\nlemma (in lattice) dual_lattice:\n  \"lattice (inv_gorder L)\"\nproof -\n  interpret dual: weak_lattice \"inv_gorder L\"\n    by (metis dual_weak_lattice)\n\n  show ?thesis\n    apply (unfold_locales)\n    apply (simp_all add: inf_of_two_exists sup_of_two_exists)\n    apply (rule eq_is_equal)\n  done\nqed\n  \nlemma (in lattice) le_iff_join:\n  assumes \"x \\<in> carrier L\" \"y \\<in> carrier L\"\n  shows \"x \\<sqsubseteq> y \\<longleftrightarrow> x = (x \\<sqinter> y)\"\n  by (simp add: assms(1) assms(2) eq_is_equal weak_le_iff_join)\n\nlemma (in lattice) le_iff_meet:\n  assumes \"x \\<in> carrier L\" \"y \\<in> carrier L\"\n  shows \"x \\<sqsubseteq> y \\<longleftrightarrow> (x \\<squnion> y) = y\"\n  by (simp add: assms eq_is_equal weak_le_iff_meet)\n\ntext \\<open> Total orders are lattices. \\<close>\n\nsublocale total_order \\<subseteq> weak?: lattice\n  by standard (auto intro: weak.weak.sup_of_two_exists weak.weak.inf_of_two_exists)\n    \ntext \\<open>Functions that preserve joins and meets\\<close>\n  \ndefinition join_pres :: \"('a, 'c) gorder_scheme \\<Rightarrow> ('b, 'd) gorder_scheme \\<Rightarrow> ('a \\<Rightarrow> 'b) \\<Rightarrow> bool\" where\n\"join_pres X Y f \\<equiv> lattice X \\<and> lattice Y \\<and> (\\<forall> x \\<in> carrier X. \\<forall> y \\<in> carrier X. f (x \\<squnion>\\<^bsub>X\\<^esub> y) = f x \\<squnion>\\<^bsub>Y\\<^esub> f y)\"\n\ndefinition meet_pres :: \"('a, 'c) gorder_scheme \\<Rightarrow> ('b, 'd) gorder_scheme \\<Rightarrow> ('a \\<Rightarrow> 'b) \\<Rightarrow> bool\" where\n\"meet_pres X Y f \\<equiv> lattice X \\<and> lattice Y \\<and> (\\<forall> x \\<in> carrier X. \\<forall> y \\<in> carrier X. f (x \\<sqinter>\\<^bsub>X\\<^esub> y) = f x \\<sqinter>\\<^bsub>Y\\<^esub> f y)\"\n\nlemma join_pres_isotone:\n  assumes \"f \\<in> carrier X \\<rightarrow> carrier Y\" \"join_pres X Y f\"\n  shows \"isotone X Y f\"\nproof (rule isotoneI)\n  show \"weak_partial_order X\" \"weak_partial_order Y\"\n    using assms unfolding join_pres_def lattice_def upper_semilattice_def lower_semilattice_def\n    by (meson partial_order.axioms(1))+\n  show \"\\<And>x y. \\<lbrakk>x \\<in> carrier X; y \\<in> carrier X; x \\<sqsubseteq>\\<^bsub>X\\<^esub> y\\<rbrakk> \\<Longrightarrow> f x \\<sqsubseteq>\\<^bsub>Y\\<^esub> f y\"\n    by (metis (no_types, lifting) PiE assms join_pres_def lattice.le_iff_meet)\nqed\n\nlemma meet_pres_isotone:\n  assumes \"f \\<in> carrier X \\<rightarrow> carrier Y\" \"meet_pres X Y f\"\n  shows \"isotone X Y f\"\nproof (rule isotoneI)\n  show \"weak_partial_order X\" \"weak_partial_order Y\"\n    using assms unfolding meet_pres_def lattice_def upper_semilattice_def lower_semilattice_def\n    by (meson partial_order.axioms(1))+\n  show \"\\<And>x y. \\<lbrakk>x \\<in> carrier X; y \\<in> carrier X; x \\<sqsubseteq>\\<^bsub>X\\<^esub> y\\<rbrakk> \\<Longrightarrow> f x \\<sqsubseteq>\\<^bsub>Y\\<^esub> f y\"\n    by (metis (no_types, lifting) PiE assms lattice.le_iff_join meet_pres_def)\nqed\n\n\nsubsection \\<open>Bounded Lattices\\<close>\n\nlocale bounded_lattice = \n  lattice + \n  weak_partial_order_bottom + \n  weak_partial_order_top\n\nsublocale bounded_lattice \\<subseteq> weak_bounded_lattice ..\n\ncontext bounded_lattice\nbegin\n\nlemma bottom_eq:  \n  \"\\<lbrakk> b \\<in> carrier L; \\<And> x. x \\<in> carrier L \\<Longrightarrow> b \\<sqsubseteq> x \\<rbrakk> \\<Longrightarrow> b = \\<bottom>\"\n  by (metis bottom_closed bottom_lower le_antisym)\n\nlemma top_eq:  \"\\<lbrakk> t \\<in> carrier L; \\<And> x. x \\<in> carrier L \\<Longrightarrow> x \\<sqsubseteq> t \\<rbrakk> \\<Longrightarrow> t = \\<top>\"\n  by (metis le_antisym top_closed top_higher)\n\nend\n\nhide_const (open) Lattice.inf\nhide_const (open) Lattice.sup\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/Lattice.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8652240791017535, "lm_q2_score": 0.8519528038477825, "lm_q1q2_score": 0.7371300801473544}}
{"text": "(*<*)\ntheory Trie imports Main begin\n(*>*)\ntext\\<open>\nTo minimize running time, each node of a trie should contain an array that maps\nletters to subtries. We have chosen a\nrepresentation where the subtries are held in an association list, i.e.\\ a\nlist of (letter,trie) pairs.  Abstracting over the alphabet \\<^typ>\\<open>'a\\<close> and the\nvalues \\<^typ>\\<open>'v\\<close> we define a trie as follows:\n\\<close>\n\ndatatype ('a,'v)trie = Trie  \"'v option\"  \"('a * ('a,'v)trie)list\"\n\ntext\\<open>\\noindent\n\\index{datatypes!and nested recursion}%\nThe first component is the optional value, the second component the\nassociation list of subtries.  This is an example of nested recursion involving products,\nwhich is fine because products are datatypes as well.\nWe define two selector functions:\n\\<close>\n\nprimrec \"value\" :: \"('a,'v)trie \\<Rightarrow> 'v option\" where\n\"value(Trie ov al) = ov\"\nprimrec alist :: \"('a,'v)trie \\<Rightarrow> ('a * ('a,'v)trie)list\" where\n\"alist(Trie ov al) = al\"\n\ntext\\<open>\\noindent\nAssociation lists come with a generic lookup function.  Its result\ninvolves type \\<open>option\\<close> because a lookup can fail:\n\\<close>\n\nprimrec assoc :: \"('key * 'val)list \\<Rightarrow> 'key \\<Rightarrow> 'val option\" where\n\"assoc [] x = None\" |\n\"assoc (p#ps) x =\n   (let (a,b) = p in if a=x then Some b else assoc ps x)\"\n\ntext\\<open>\nNow we can define the lookup function for tries. It descends into the trie\nexamining the letters of the search string one by one. As\nrecursion on lists is simpler than on tries, let us express this as primitive\nrecursion on the search string argument:\n\\<close>\n\nprimrec lookup :: \"('a,'v)trie \\<Rightarrow> 'a list \\<Rightarrow> 'v option\" where\n\"lookup t [] = value t\" |\n\"lookup t (a#as) = (case assoc (alist t) a of\n                      None \\<Rightarrow> None\n                    | Some at \\<Rightarrow> lookup at as)\"\n\ntext\\<open>\nAs a first simple property we prove that looking up a string in the empty\ntrie \\<^term>\\<open>Trie None []\\<close> always returns \\<^const>\\<open>None\\<close>. The proof merely\ndistinguishes the two cases whether the search string is empty or not:\n\\<close>\n\n\n\ntext\\<open>\nThings begin to get interesting with the definition of an update function\nthat adds a new (string, value) pair to a trie, overwriting the old value\nassociated with that string:\n\\<close>\n\nprimrec update:: \"('a,'v)trie \\<Rightarrow> 'a list \\<Rightarrow> 'v \\<Rightarrow> ('a,'v)trie\" where\n\"update t []     v = Trie (Some v) (alist t)\" |\n\"update t (a#as) v =\n   (let tt = (case assoc (alist t) a of\n                None \\<Rightarrow> Trie None [] | Some at \\<Rightarrow> at)\n    in Trie (value t) ((a,update tt as v) # alist t))\"\n\ntext\\<open>\\noindent\nThe base case is obvious. In the recursive case the subtrie\n\\<^term>\\<open>tt\\<close> associated with the first letter \\<^term>\\<open>a\\<close> is extracted,\nrecursively updated, and then placed in front of the association list.\nThe old subtrie associated with \\<^term>\\<open>a\\<close> is still in the association list\nbut no longer accessible via \\<^const>\\<open>assoc\\<close>. Clearly, there is room here for\noptimizations!\n\nBefore we start on any proofs about \\<^const>\\<open>update\\<close> we tell the simplifier to\nexpand all \\<open>let\\<close>s and to split all \\<open>case\\<close>-constructs over\noptions:\n\\<close>\n\ndeclare Let_def[simp] option.split[split]\n\ntext\\<open>\\noindent\nThe reason becomes clear when looking (probably after a failed proof\nattempt) at the body of \\<^const>\\<open>update\\<close>: it contains both\n\\<open>let\\<close> and a case distinction over type \\<open>option\\<close>.\n\nOur main goal is to prove the correct interaction of \\<^const>\\<open>update\\<close> and\n\\<^const>\\<open>lookup\\<close>:\n\\<close>\n\ntheorem \"\\<forall>t v bs. lookup (update t as v) bs =\n                    (if as=bs then Some v else lookup t bs)\"\n\ntxt\\<open>\\noindent\nOur plan is to induct on \\<^term>\\<open>as\\<close>; hence the remaining variables are\nquantified. From the definitions it is clear that induction on either\n\\<^term>\\<open>as\\<close> or \\<^term>\\<open>bs\\<close> is required. The choice of \\<^term>\\<open>as\\<close> is \nguided by the intuition that simplification of \\<^const>\\<open>lookup\\<close> might be easier\nif \\<^const>\\<open>update\\<close> has already been simplified, which can only happen if\n\\<^term>\\<open>as\\<close> is instantiated.\nThe start of the proof is conventional:\n\\<close>\napply(induct_tac as, auto)\n\ntxt\\<open>\\noindent\nUnfortunately, this time we are left with three intimidating looking subgoals:\n\\begin{isabelle}\n~1.~\\dots~{\\isasymLongrightarrow}~lookup~\\dots~bs~=~lookup~t~bs\\isanewline\n~2.~\\dots~{\\isasymLongrightarrow}~lookup~\\dots~bs~=~lookup~t~bs\\isanewline\n~3.~\\dots~{\\isasymLongrightarrow}~lookup~\\dots~bs~=~lookup~t~bs\n\\end{isabelle}\nClearly, if we want to make headway we have to instantiate \\<^term>\\<open>bs\\<close> as\nwell now. It turns out that instead of induction, case distinction\nsuffices:\n\\<close>\napply(case_tac[!] bs, auto)\ndone\n\ntext\\<open>\\noindent\n\\index{subgoal numbering}%\nAll methods ending in \\<open>tac\\<close> take an optional first argument that\nspecifies the range of subgoals they are applied to, where \\<open>[!]\\<close> means\nall subgoals, i.e.\\ \\<open>[1-3]\\<close> in our case. Individual subgoal numbers,\ne.g. \\<open>[2]\\<close> are also allowed.\n\nThis proof may look surprisingly straightforward. However, note that this\ncomes at a cost: the proof script is unreadable because the intermediate\nproof states are invisible, and we rely on the (possibly brittle) magic of\n\\<open>auto\\<close> (\\<open>simp_all\\<close> will not do --- try it) to split the subgoals\nof the induction up in such a way that case distinction on \\<^term>\\<open>bs\\<close> makes\nsense and solves the proof. \n\n\\begin{exercise}\n  Modify \\<^const>\\<open>update\\<close> (and its type) such that it allows both insertion and\n  deletion of entries with a single function.  Prove the corresponding version \n  of the main theorem above.\n  Optimize your function such that it shrinks tries after\n  deletion if possible.\n\\end{exercise}\n\n\\begin{exercise}\n  Write an improved version of \\<^const>\\<open>update\\<close> that does not suffer from the\n  space leak (pointed out above) caused by not deleting overwritten entries\n  from the association list. Prove the main theorem for your improved\n  \\<^const>\\<open>update\\<close>.\n\\end{exercise}\n\n\\begin{exercise}\n  Conceptually, each node contains a mapping from letters to optional\n  subtries. Above we have implemented this by means of an association\n  list. Replay the development replacing \\<^typ>\\<open>('a * ('a,'v)trie)list\\<close>\n  with \\<^typ>\\<open>'a \\<Rightarrow> ('a,'v)trie option\\<close>.\n\\end{exercise}\n\n\\<close>\n\n(*<*)\n\n(* Exercise 1. Solution by Getrud Bauer *)\n\nprimrec update1 :: \"('a, 'v) trie \\<Rightarrow> 'a list \\<Rightarrow> 'v option \\<Rightarrow> ('a, 'v) trie\"\nwhere\n  \"update1 t []     vo = Trie vo (alist t)\" |\n  \"update1 t (a#as) vo =\n     (let tt = (case assoc (alist t) a of\n                  None \\<Rightarrow> Trie None [] \n                | Some at \\<Rightarrow> at)\n      in Trie (value t) ((a, update1 tt as vo) # alist t))\"\n\ntheorem [simp]: \"\\<forall>t v bs. lookup (update1 t as v) bs =\n                    (if as = bs then v else lookup t bs)\"\napply (induct_tac as, auto)\napply (case_tac[!] bs, auto)\ndone\n\n\n(* Exercise 2. Solution by Getrud Bauer *)\n\nprimrec overwrite :: \"'a \\<Rightarrow> 'b \\<Rightarrow> ('a * 'b) list \\<Rightarrow> ('a * 'b) list\" where\n\"overwrite a v [] = [(a,v)]\" |\n\"overwrite a v (p#ps) = (if a = fst p then (a,v)#ps else p # overwrite a v ps)\"\n\nlemma [simp]: \"\\<forall> a v b. assoc (overwrite a v ps) b = assoc ((a,v)#ps) b\"\napply (induct_tac ps, auto)\napply (case_tac[!] a)\ndone\n\nprimrec update2 :: \"('a, 'v) trie \\<Rightarrow> 'a list \\<Rightarrow> 'v option \\<Rightarrow> ('a, 'v) trie\"\nwhere\n  \"update2 t []     vo = Trie vo (alist t)\" |\n  \"update2 t (a#as) vo =\n     (let tt = (case assoc (alist t) a of \n                  None \\<Rightarrow> Trie None []  \n                | Some at \\<Rightarrow> at) \n      in Trie (value t) (overwrite a (update2 tt as vo) (alist t)))\" \n\ntheorem \"\\<forall>t v bs. lookup (update2 t as vo) bs =\n                    (if as = bs then vo else lookup t bs)\"\napply (induct_tac as, auto)\napply (case_tac[!] bs, auto)\ndone\n\n\n(* Exercise 3. Solution by Getrud Bauer *)\ndatatype ('a,dead 'v) triem = Triem  \"'v option\" \"'a \\<Rightarrow> ('a,'v) triem option\"\n\nprimrec valuem :: \"('a, 'v) triem \\<Rightarrow> 'v option\" where\n\"valuem (Triem ov m) = ov\"\n\nprimrec mapping :: \"('a,'v) triem \\<Rightarrow> 'a \\<Rightarrow> ('a, 'v) triem option\" where\n\"mapping (Triem ov m) = m\"\n\nprimrec lookupm :: \"('a,'v) triem \\<Rightarrow> 'a list \\<Rightarrow> 'v option\" where\n  \"lookupm t [] = valuem t\" |\n  \"lookupm t (a#as) = (case mapping t a of\n                        None \\<Rightarrow> None\n                      | Some at \\<Rightarrow> lookupm at as)\"\n\nlemma [simp]: \"lookupm (Triem None  (\\<lambda>c. None)) as = None\"\napply (case_tac as, simp_all)\ndone\n\nprimrec updatem :: \"('a,'v)triem \\<Rightarrow> 'a list \\<Rightarrow> 'v \\<Rightarrow> ('a,'v)triem\" where\n  \"updatem t []     v = Triem (Some v) (mapping t)\" |\n  \"updatem t (a#as) v =\n     (let tt = (case mapping t a of\n                  None \\<Rightarrow> Triem None (\\<lambda>c. None) \n                | Some at \\<Rightarrow> at)\n      in Triem (valuem t) \n              (\\<lambda>c. if c = a then Some (updatem tt as v) else mapping t c))\"\n\ntheorem \"\\<forall>t v bs. lookupm (updatem t as v) bs = \n                    (if as = bs then Some v else lookupm t bs)\"\napply (induct_tac as, auto)\napply (case_tac[!] bs, auto)\ndone\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/Trie/Trie.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8519527982093666, "lm_q2_score": 0.8652240721511739, "lm_q1q2_score": 0.7371300693472955}}
{"text": "theory P10 imports Main begin\n\nfun sq :: \"nat \\<Rightarrow> nat\" where\n\"sq 0 = 0\" | \"sq (Suc n) = (sq n) + n + (Suc n)\"\n\ntheorem [simp]: \"sq n = n * n\"\n  apply (induct n)\n   apply auto\n  done\n\n\n\nlemma aux[rule_format]: \"\\<forall>m. m <= n \\<longrightarrow> sq n = ((n + (n-m))* m) + sq (n-m)\"\n  apply (induct_tac n, auto)\n  apply (case_tac m, auto)\n  done\n\ntheorem MM2: \"100 \\<le> n \\<Longrightarrow> sq n = ((n + (n - 100))* 100) + sq (n - 100)\"\n  by (rule aux)\n\nlemma binomial [simp]: \"sq (a+b) = (sq a + sq b + 2 * a * b)\"\n  apply (induct a)\n   apply auto\n  done\n\ntheorem MM3: \"sq((10 * n) + 5) = ((n * (Suc n)) * 100) + 25\"\nproof (induct n)\ncase 0\n  then show ?case by simp\nnext\n  case (Suc n)\n  assume \"sq (10 * n + 5) = n * Suc n * 100 + 25\"\n  have \"sq (10 * Suc n + 5) = sq (10 * n + 10 + 5)\" by simp\n  also have \"\\<dots> = sq (10 * n + 15)\" by (simp add: add.assoc)\n  also have \"\\<dots> = (sq (10 * n) + sq 15 + (2 * (10 * n) * 15))\" using P10.binomial by blast\n  also have \"\\<dots> = ((10 * n * 10 * n) + sq 15 + (2 * (10 * n) * 15))\" by simp\n  also have \"\\<dots> = ((100 * n * n) + sq 15 + (2 * (10 * n) * 15))\" by simp\n  also have \"\\<dots> = ((100 * n * n) + 225 + (30 * (10 * n)))\" by simp\n  finally have \"\\<dots> = ((100 * n * n) + (300 * n) + 225)\" by (simp add: add.assoc)\n  hence 1: \"sq (10 * Suc n + 5) = ((100 * n * n) + (300 * n) + 225)\"\n    using \\<open>sq (10 * n + 10 + 5) = sq (10 * n + 15)\\<close>\n          \\<open>sq (10 * n + 15) = sq (10 * n) + sq 15 + 2 * (10 * n) * 15\\<close> by auto\n  have \"Suc n * Suc (Suc n) * 100 + 25 = (n+1) * (n+1+1) * 100 + 25\" by simp\n  also have \"\\<dots> = (n+1) * (n+2) * 100 + 25\" by simp\n  also have \"\\<dots> = (n*n + 3 * n + 2) * 100 + 25\" by simp\n  also have \"\\<dots> = (100 * n * n) + (300 * n) + 25 + 200\" by simp\n  finally have \"\\<dots> = ((100 * n * n) + 225 + (30 * (10 * n)))\" by simp\n  hence 2: \"Suc n * Suc (Suc n) * 100 + 25 = ((100 * n * n) + 225 + (30 * (10 * n)))\"\n    by simp\n  then show ?case using 1 2 by simp\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/P10.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.926303724190573, "lm_q2_score": 0.7956580952177051, "lm_q1q2_score": 0.7370210567825378}}
{"text": "(*  Title:      HOL/Algebra/Group.thy\n    Author:     Clemens Ballarin, started 4 February 2003\n\nBased on work by Florian Kammueller, L C Paulson and Markus Wenzel.\nWith additional contributions from Martin Baillon and Paulo Em\u00edlio de Vilhena.\n*)\n\ntheory Group\nimports Complete_Lattice \"HOL-Library.FuncSet\"\nbegin\n\nsection \\<open>Monoids and Groups\\<close>\n\nsubsection \\<open>Definitions\\<close>\n\ntext \\<open>\n  Definitions follow @{cite \"Jacobson:1985\"}.\n\\<close>\n\nrecord 'a monoid =  \"'a partial_object\" +\n  mult    :: \"['a, 'a] \\<Rightarrow> 'a\" (infixl \"\\<otimes>\\<index>\" 70)\n  one     :: 'a (\"\\<one>\\<index>\")\n\ndefinition\n  m_inv :: \"('a, 'b) monoid_scheme => 'a => 'a\" (\"inv\\<index> _\" [81] 80)\n  where \"inv\\<^bsub>G\\<^esub> x = (THE y. y \\<in> carrier G \\<and> x \\<otimes>\\<^bsub>G\\<^esub> y = \\<one>\\<^bsub>G\\<^esub> \\<and> y \\<otimes>\\<^bsub>G\\<^esub> x = \\<one>\\<^bsub>G\\<^esub>)\"\n\ndefinition\n  Units :: \"_ => 'a set\"\n  \\<comment> \\<open>The set of invertible elements\\<close>\n  where \"Units G = {y. y \\<in> carrier G \\<and> (\\<exists>x \\<in> carrier G. x \\<otimes>\\<^bsub>G\\<^esub> y = \\<one>\\<^bsub>G\\<^esub> \\<and> y \\<otimes>\\<^bsub>G\\<^esub> x = \\<one>\\<^bsub>G\\<^esub>)}\"\n\nlocale monoid =\n  fixes G (structure)\n  assumes m_closed [intro, simp]:\n         \"\\<lbrakk>x \\<in> carrier G; y \\<in> carrier G\\<rbrakk> \\<Longrightarrow> x \\<otimes> y \\<in> carrier G\"\n      and m_assoc:\n         \"\\<lbrakk>x \\<in> carrier G; y \\<in> carrier G; z \\<in> carrier G\\<rbrakk>\n          \\<Longrightarrow> (x \\<otimes> y) \\<otimes> z = x \\<otimes> (y \\<otimes> z)\"\n      and one_closed [intro, simp]: \"\\<one> \\<in> carrier G\"\n      and l_one [simp]: \"x \\<in> carrier G \\<Longrightarrow> \\<one> \\<otimes> x = x\"\n      and r_one [simp]: \"x \\<in> carrier G \\<Longrightarrow> x \\<otimes> \\<one> = x\"\n\nlemma monoidI:\n  fixes G (structure)\n  assumes m_closed:\n      \"!!x y. [| x \\<in> carrier G; y \\<in> carrier G |] ==> x \\<otimes> y \\<in> carrier G\"\n    and one_closed: \"\\<one> \\<in> carrier G\"\n    and m_assoc:\n      \"!!x y z. [| x \\<in> carrier G; y \\<in> carrier G; z \\<in> carrier G |] ==>\n      (x \\<otimes> y) \\<otimes> z = x \\<otimes> (y \\<otimes> z)\"\n    and l_one: \"!!x. x \\<in> carrier G ==> \\<one> \\<otimes> x = x\"\n    and r_one: \"!!x. x \\<in> carrier G ==> x \\<otimes> \\<one> = x\"\n  shows \"monoid G\"\n  by (fast intro!: monoid.intro intro: assms)\n\nlemma (in monoid) Units_closed [dest]:\n  \"x \\<in> Units G ==> x \\<in> carrier G\"\n  by (unfold Units_def) fast\n\nlemma (in monoid) one_unique:\n  assumes \"u \\<in> carrier G\"\n    and \"\\<And>x. x \\<in> carrier G \\<Longrightarrow> u \\<otimes> x = x\"\n  shows \"u = \\<one>\"\n  using assms(2)[OF one_closed] r_one[OF assms(1)] by simp\n\nlemma (in monoid) inv_unique:\n  assumes eq: \"y \\<otimes> x = \\<one>\"  \"x \\<otimes> y' = \\<one>\"\n    and G: \"x \\<in> carrier G\"  \"y \\<in> carrier G\"  \"y' \\<in> carrier G\"\n  shows \"y = y'\"\nproof -\n  from G eq have \"y = y \\<otimes> (x \\<otimes> y')\" by simp\n  also from G have \"... = (y \\<otimes> x) \\<otimes> y'\" by (simp add: m_assoc)\n  also from G eq have \"... = y'\" by simp\n  finally show ?thesis .\nqed\n\nlemma (in monoid) Units_m_closed [simp, intro]:\n  assumes x: \"x \\<in> Units G\" and y: \"y \\<in> Units G\"\n  shows \"x \\<otimes> y \\<in> Units G\"\nproof -\n  from x obtain x' where x: \"x \\<in> carrier G\" \"x' \\<in> carrier G\" and xinv: \"x \\<otimes> x' = \\<one>\" \"x' \\<otimes> x = \\<one>\"\n    unfolding Units_def by fast\n  from y obtain y' where y: \"y \\<in> carrier G\" \"y' \\<in> carrier G\" and yinv: \"y \\<otimes> y' = \\<one>\" \"y' \\<otimes> y = \\<one>\"\n    unfolding Units_def by fast\n  from x y xinv yinv have \"y' \\<otimes> (x' \\<otimes> x) \\<otimes> y = \\<one>\" by simp\n  moreover from x y xinv yinv have \"x \\<otimes> (y \\<otimes> y') \\<otimes> x' = \\<one>\" by simp\n  moreover note x y\n  ultimately show ?thesis unfolding Units_def\n    by simp (metis m_assoc m_closed)\nqed\n\nlemma (in monoid) Units_one_closed [intro, simp]:\n  \"\\<one> \\<in> Units G\"\n  by (unfold Units_def) auto\n\nlemma (in monoid) Units_inv_closed [intro, simp]:\n  \"x \\<in> Units G ==> inv x \\<in> carrier G\"\n  apply (simp add: Units_def m_inv_def)\n  by (metis (mono_tags, lifting) inv_unique the_equality)\n\nlemma (in monoid) Units_l_inv_ex:\n  \"x \\<in> Units G ==> \\<exists>y \\<in> carrier G. y \\<otimes> x = \\<one>\"\n  by (unfold Units_def) auto\n\nlemma (in monoid) Units_r_inv_ex:\n  \"x \\<in> Units G ==> \\<exists>y \\<in> carrier G. x \\<otimes> y = \\<one>\"\n  by (unfold Units_def) auto\n\nlemma (in monoid) Units_l_inv [simp]:\n  \"x \\<in> Units G ==> inv x \\<otimes> x = \\<one>\"\n  apply (unfold Units_def m_inv_def, simp)\n  by (metis (mono_tags, lifting) inv_unique the_equality)\n\nlemma (in monoid) Units_r_inv [simp]:\n  \"x \\<in> Units G ==> x \\<otimes> inv x = \\<one>\"\n  by (metis (full_types) Units_closed Units_inv_closed Units_l_inv Units_r_inv_ex inv_unique)\n\nlemma (in monoid) inv_one [simp]:\n  \"inv \\<one> = \\<one>\"\n  by (metis Units_one_closed Units_r_inv l_one monoid.Units_inv_closed monoid_axioms)\n\nlemma (in monoid) Units_inv_Units [intro, simp]:\n  \"x \\<in> Units G ==> inv x \\<in> Units G\"\nproof -\n  assume x: \"x \\<in> Units G\"\n  show \"inv x \\<in> Units G\"\n    by (auto simp add: Units_def\n      intro: Units_l_inv Units_r_inv x Units_closed [OF x])\nqed\n\nlemma (in monoid) Units_l_cancel [simp]:\n  \"[| x \\<in> Units G; y \\<in> carrier G; z \\<in> carrier G |] ==>\n   (x \\<otimes> y = x \\<otimes> z) = (y = z)\"\nproof\n  assume eq: \"x \\<otimes> y = x \\<otimes> z\"\n    and G: \"x \\<in> Units G\"  \"y \\<in> carrier G\"  \"z \\<in> carrier G\"\n  then have \"(inv x \\<otimes> x) \\<otimes> y = (inv x \\<otimes> x) \\<otimes> z\"\n    by (simp add: m_assoc Units_closed del: Units_l_inv)\n  with G show \"y = z\" by simp\nnext\n  assume eq: \"y = z\"\n    and G: \"x \\<in> Units G\"  \"y \\<in> carrier G\"  \"z \\<in> carrier G\"\n  then show \"x \\<otimes> y = x \\<otimes> z\" by simp\nqed\n\nlemma (in monoid) Units_inv_inv [simp]:\n  \"x \\<in> Units G ==> inv (inv x) = x\"\nproof -\n  assume x: \"x \\<in> Units G\"\n  then have \"inv x \\<otimes> inv (inv x) = inv x \\<otimes> x\" by simp\n  with x show ?thesis by (simp add: Units_closed del: Units_l_inv Units_r_inv)\nqed\n\nlemma (in monoid) inv_inj_on_Units:\n  \"inj_on (m_inv G) (Units G)\"\nproof (rule inj_onI)\n  fix x y\n  assume G: \"x \\<in> Units G\"  \"y \\<in> Units G\" and eq: \"inv x = inv y\"\n  then have \"inv (inv x) = inv (inv y)\" by simp\n  with G show \"x = y\" by simp\nqed\n\nlemma (in monoid) Units_inv_comm:\n  assumes inv: \"x \\<otimes> y = \\<one>\"\n    and G: \"x \\<in> Units G\"  \"y \\<in> Units G\"\n  shows \"y \\<otimes> x = \\<one>\"\nproof -\n  from G have \"x \\<otimes> y \\<otimes> x = x \\<otimes> \\<one>\" by (auto simp add: inv Units_closed)\n  with G show ?thesis by (simp del: r_one add: m_assoc Units_closed)\nqed\n\nlemma (in monoid) carrier_not_empty: \"carrier G \\<noteq> {}\"\nby auto\n\n(* Jacobson defines submonoid here. *)\n(* Jacobson defines the order of a monoid here. *)\n\n\nsubsection \\<open>Groups\\<close>\n\ntext \\<open>\n  A group is a monoid all of whose elements are invertible.\n\\<close>\n\nlocale group = monoid +\n  assumes Units: \"carrier G <= Units G\"\n\nlemma (in group) is_group [iff]: \"group G\" by (rule group_axioms)\n\nlemma (in group) is_monoid [iff]: \"monoid G\"\n  by (rule monoid_axioms)\n\ntheorem groupI:\n  fixes G (structure)\n  assumes m_closed [simp]:\n      \"!!x y. [| x \\<in> carrier G; y \\<in> carrier G |] ==> x \\<otimes> y \\<in> carrier G\"\n    and one_closed [simp]: \"\\<one> \\<in> carrier G\"\n    and m_assoc:\n      \"!!x y z. [| x \\<in> carrier G; y \\<in> carrier G; z \\<in> carrier G |] ==>\n      (x \\<otimes> y) \\<otimes> z = x \\<otimes> (y \\<otimes> z)\"\n    and l_one [simp]: \"!!x. x \\<in> carrier G ==> \\<one> \\<otimes> x = x\"\n    and l_inv_ex: \"!!x. x \\<in> carrier G ==> \\<exists>y \\<in> carrier G. y \\<otimes> x = \\<one>\"\n  shows \"group G\"\nproof -\n  have l_cancel [simp]:\n    \"!!x y z. [| x \\<in> carrier G; y \\<in> carrier G; z \\<in> carrier G |] ==>\n    (x \\<otimes> y = x \\<otimes> z) = (y = z)\"\n  proof\n    fix x y z\n    assume eq: \"x \\<otimes> y = x \\<otimes> z\"\n      and G: \"x \\<in> carrier G\"  \"y \\<in> carrier G\"  \"z \\<in> carrier G\"\n    with l_inv_ex obtain x_inv where xG: \"x_inv \\<in> carrier G\"\n      and l_inv: \"x_inv \\<otimes> x = \\<one>\" by fast\n    from G eq xG have \"(x_inv \\<otimes> x) \\<otimes> y = (x_inv \\<otimes> x) \\<otimes> z\"\n      by (simp add: m_assoc)\n    with G show \"y = z\" by (simp add: l_inv)\n  next\n    fix x y z\n    assume eq: \"y = z\"\n      and G: \"x \\<in> carrier G\"  \"y \\<in> carrier G\"  \"z \\<in> carrier G\"\n    then show \"x \\<otimes> y = x \\<otimes> z\" by simp\n  qed\n  have r_one:\n    \"!!x. x \\<in> carrier G ==> x \\<otimes> \\<one> = x\"\n  proof -\n    fix x\n    assume x: \"x \\<in> carrier G\"\n    with l_inv_ex obtain x_inv where xG: \"x_inv \\<in> carrier G\"\n      and l_inv: \"x_inv \\<otimes> x = \\<one>\" by fast\n    from x xG have \"x_inv \\<otimes> (x \\<otimes> \\<one>) = x_inv \\<otimes> x\"\n      by (simp add: m_assoc [symmetric] l_inv)\n    with x xG show \"x \\<otimes> \\<one> = x\" by simp\n  qed\n  have inv_ex:\n    \"\\<And>x. x \\<in> carrier G \\<Longrightarrow> \\<exists>y \\<in> carrier G. y \\<otimes> x = \\<one> \\<and> x \\<otimes> y = \\<one>\"\n  proof -\n    fix x\n    assume x: \"x \\<in> carrier G\"\n    with l_inv_ex obtain y where y: \"y \\<in> carrier G\"\n      and l_inv: \"y \\<otimes> x = \\<one>\" by fast\n    from x y have \"y \\<otimes> (x \\<otimes> y) = y \\<otimes> \\<one>\"\n      by (simp add: m_assoc [symmetric] l_inv r_one)\n    with x y have r_inv: \"x \\<otimes> y = \\<one>\"\n      by simp\n    from x y show \"\\<exists>y \\<in> carrier G. y \\<otimes> x = \\<one> \\<and> x \\<otimes> y = \\<one>\"\n      by (fast intro: l_inv r_inv)\n  qed\n  then have carrier_subset_Units: \"carrier G \\<subseteq> Units G\"\n    by (unfold Units_def) fast\n  show ?thesis\n    by standard (auto simp: r_one m_assoc carrier_subset_Units)\nqed\n\nlemma (in monoid) group_l_invI:\n  assumes l_inv_ex:\n    \"!!x. x \\<in> carrier G ==> \\<exists>y \\<in> carrier G. y \\<otimes> x = \\<one>\"\n  shows \"group G\"\n  by (rule groupI) (auto intro: m_assoc l_inv_ex)\n\nlemma (in group) Units_eq [simp]:\n  \"Units G = carrier G\"\nproof\n  show \"Units G \\<subseteq> carrier G\" by fast\nnext\n  show \"carrier G \\<subseteq> Units G\" by (rule Units)\nqed\n\nlemma (in group) inv_closed [intro, simp]:\n  \"x \\<in> carrier G ==> inv x \\<in> carrier G\"\n  using Units_inv_closed by simp\n\nlemma (in group) l_inv_ex [simp]:\n  \"x \\<in> carrier G ==> \\<exists>y \\<in> carrier G. y \\<otimes> x = \\<one>\"\n  using Units_l_inv_ex by simp\n\nlemma (in group) r_inv_ex [simp]:\n  \"x \\<in> carrier G ==> \\<exists>y \\<in> carrier G. x \\<otimes> y = \\<one>\"\n  using Units_r_inv_ex by simp\n\nlemma (in group) l_inv [simp]:\n  \"x \\<in> carrier G ==> inv x \\<otimes> x = \\<one>\"\n  by simp\n\n\nsubsection \\<open>Cancellation Laws and Basic Properties\\<close>\n\nlemma (in group) inv_eq_1_iff [simp]:\n  assumes \"x \\<in> carrier G\" shows \"inv\\<^bsub>G\\<^esub> x = \\<one>\\<^bsub>G\\<^esub> \\<longleftrightarrow> x = \\<one>\\<^bsub>G\\<^esub>\"\nproof -\n  have \"x = \\<one>\" if \"inv x = \\<one>\"\n  proof -\n    have \"inv x \\<otimes> x = \\<one>\"\n      using assms l_inv by blast\n    then show \"x = \\<one>\"\n      using that assms by simp\n  qed\n  then show ?thesis\n    by auto\nqed\n\nlemma (in group) r_inv [simp]:\n  \"x \\<in> carrier G ==> x \\<otimes> inv x = \\<one>\"\n  by simp\n\nlemma (in group) right_cancel [simp]:\n  \"[| x \\<in> carrier G; y \\<in> carrier G; z \\<in> carrier G |] ==>\n   (y \\<otimes> x = z \\<otimes> x) = (y = z)\"\n  by (metis inv_closed m_assoc r_inv r_one)\n\nlemma (in group) inv_inv [simp]:\n  \"x \\<in> carrier G ==> inv (inv x) = x\"\n  using Units_inv_inv by simp\n\nlemma (in group) inv_inj:\n  \"inj_on (m_inv G) (carrier G)\"\n  using inv_inj_on_Units by simp\n\nlemma (in group) inv_mult_group:\n  \"[| x \\<in> carrier G; y \\<in> carrier G |] ==> inv (x \\<otimes> y) = inv y \\<otimes> inv x\"\nproof -\n  assume G: \"x \\<in> carrier G\"  \"y \\<in> carrier G\"\n  then have \"inv (x \\<otimes> y) \\<otimes> (x \\<otimes> y) = (inv y \\<otimes> inv x) \\<otimes> (x \\<otimes> y)\"\n    by (simp add: m_assoc) (simp add: m_assoc [symmetric])\n  with G show ?thesis by (simp del: l_inv Units_l_inv)\nqed\n\nlemma (in group) inv_comm:\n  \"[| x \\<otimes> y = \\<one>; x \\<in> carrier G; y \\<in> carrier G |] ==> y \\<otimes> x = \\<one>\"\n  by (rule Units_inv_comm) auto\n\nlemma (in group) inv_equality:\n     \"[|y \\<otimes> x = \\<one>; x \\<in> carrier G; y \\<in> carrier G|] ==> inv x = y\"\n  using inv_unique r_inv by blast\n\nlemma (in group) inv_solve_left:\n  \"\\<lbrakk> a \\<in> carrier G; b \\<in> carrier G; c \\<in> carrier G \\<rbrakk> \\<Longrightarrow> a = inv b \\<otimes> c \\<longleftrightarrow> c = b \\<otimes> a\"\n  by (metis inv_equality l_inv_ex l_one m_assoc r_inv)\n\nlemma (in group) inv_solve_left':\n  \"\\<lbrakk> a \\<in> carrier G; b \\<in> carrier G; c \\<in> carrier G \\<rbrakk> \\<Longrightarrow> inv b \\<otimes> c = a \\<longleftrightarrow> c = b \\<otimes> a\"\n  by (metis inv_equality l_inv_ex l_one m_assoc r_inv)\n\nlemma (in group) inv_solve_right:\n  \"\\<lbrakk> a \\<in> carrier G; b \\<in> carrier G; c \\<in> carrier G \\<rbrakk> \\<Longrightarrow> a = b \\<otimes> inv c \\<longleftrightarrow> b = a \\<otimes> c\"\n  by (metis inv_equality l_inv_ex l_one m_assoc r_inv)\n\nlemma (in group) inv_solve_right':\n  \"\\<lbrakk>a \\<in> carrier G; b \\<in> carrier G; c \\<in> carrier G\\<rbrakk> \\<Longrightarrow> b \\<otimes> inv c = a \\<longleftrightarrow> b = a \\<otimes> c\"\n  by (auto simp: m_assoc)\n  \n\nsubsection \\<open>Power\\<close>\n\nconsts\n  pow :: \"[('a, 'm) monoid_scheme, 'a, 'b::semiring_1] => 'a\"  (infixr \"[^]\\<index>\" 75)\n\noverloading nat_pow == \"pow :: [_, 'a, nat] => 'a\"\nbegin\n  definition \"nat_pow G a n = rec_nat \\<one>\\<^bsub>G\\<^esub> (%u b. b \\<otimes>\\<^bsub>G\\<^esub> a) n\"\nend\n\nlemma (in monoid) nat_pow_closed [intro, simp]:\n  \"x \\<in> carrier G ==> x [^] (n::nat) \\<in> carrier G\"\n  by (induct n) (simp_all add: nat_pow_def)\n\nlemma (in monoid) nat_pow_0 [simp]:\n  \"x [^] (0::nat) = \\<one>\"\n  by (simp add: nat_pow_def)\n\nlemma (in monoid) nat_pow_Suc [simp]:\n  \"x [^] (Suc n) = x [^] n \\<otimes> x\"\n  by (simp add: nat_pow_def)\n\nlemma (in monoid) nat_pow_one [simp]:\n  \"\\<one> [^] (n::nat) = \\<one>\"\n  by (induct n) simp_all\n\nlemma (in monoid) nat_pow_mult:\n  \"x \\<in> carrier G ==> x [^] (n::nat) \\<otimes> x [^] m = x [^] (n + m)\"\n  by (induct m) (simp_all add: m_assoc [THEN sym])\n\nlemma (in monoid) nat_pow_comm:\n  \"x \\<in> carrier G \\<Longrightarrow> (x [^] (n::nat)) \\<otimes> (x [^] (m :: nat)) = (x [^] m) \\<otimes> (x [^] n)\"\n  using nat_pow_mult[of x n m] nat_pow_mult[of x m n] by (simp add: add.commute)\n\nlemma (in monoid) nat_pow_Suc2:\n  \"x \\<in> carrier G \\<Longrightarrow> x [^] (Suc n) = x \\<otimes> (x [^] n)\"\n  using nat_pow_mult[of x 1 n] Suc_eq_plus1[of n]\n  by (metis One_nat_def Suc_eq_plus1_left l_one nat.rec(1) nat_pow_Suc nat_pow_def)\n\nlemma (in monoid) nat_pow_pow:\n  \"x \\<in> carrier G ==> (x [^] n) [^] m = x [^] (n * m::nat)\"\n  by (induct m) (simp, simp add: nat_pow_mult add.commute)\n\nlemma (in monoid) nat_pow_consistent:\n  \"x [^] (n :: nat) = x [^]\\<^bsub>(G \\<lparr> carrier := H \\<rparr>)\\<^esub> n\"\n  unfolding nat_pow_def by simp\n\nlemma nat_pow_0 [simp]: \"x [^]\\<^bsub>G\\<^esub> (0::nat) = \\<one>\\<^bsub>G\\<^esub>\"\n  by (simp add: nat_pow_def)\n\nlemma nat_pow_Suc [simp]: \"x [^]\\<^bsub>G\\<^esub> (Suc n) = (x [^]\\<^bsub>G\\<^esub> n)\\<otimes>\\<^bsub>G\\<^esub> x\"\n  by (simp add: nat_pow_def)\n\nlemma (in group) nat_pow_inv:\n  assumes \"x \\<in> carrier G\" shows \"(inv x) [^] (i :: nat) = inv (x [^] i)\"\nproof (induction i)\n  case 0 thus ?case by simp\nnext\n  case (Suc i)\n  have \"(inv x) [^] Suc i = ((inv x) [^] i) \\<otimes> inv x\"\n    by simp\n  also have \" ... = (inv (x [^] i)) \\<otimes> inv x\"\n    by (simp add: Suc.IH Suc.prems)\n  also have \" ... = inv (x \\<otimes> (x [^] i))\"\n    by (simp add: assms inv_mult_group)\n  also have \" ... = inv (x [^] (Suc i))\"\n    using assms nat_pow_Suc2 by auto\n  finally show ?case .\nqed\n\noverloading int_pow == \"pow :: [_, 'a, int] => 'a\"\nbegin\n  definition \"int_pow G a z =\n   (let p = rec_nat \\<one>\\<^bsub>G\\<^esub> (%u b. b \\<otimes>\\<^bsub>G\\<^esub> a)\n    in if z < 0 then inv\\<^bsub>G\\<^esub> (p (nat (-z))) else p (nat z))\"\nend\n\nlemma int_pow_int: \"x [^]\\<^bsub>G\\<^esub> (int n) = x [^]\\<^bsub>G\\<^esub> n\"\n  by(simp add: int_pow_def nat_pow_def)\n\nlemma pow_nat:\n  assumes \"i\\<ge>0\"\n  shows \"x [^]\\<^bsub>G\\<^esub> nat i = x [^]\\<^bsub>G\\<^esub> i\"\nproof (cases i rule: int_cases)\n  case (nonneg n)\n  then show ?thesis\n    by (simp add: int_pow_int)\nnext\n  case (neg n)\n  then show ?thesis\n    using assms by linarith\nqed\n\nlemma int_pow_0 [simp]: \"x [^]\\<^bsub>G\\<^esub> (0::int) = \\<one>\\<^bsub>G\\<^esub>\"\n  by (simp add: int_pow_def)\n\nlemma int_pow_def2: \"a [^]\\<^bsub>G\\<^esub> z =\n   (if z < 0 then inv\\<^bsub>G\\<^esub> (a [^]\\<^bsub>G\\<^esub> (nat (-z))) else a [^]\\<^bsub>G\\<^esub> (nat z))\"\n  by (simp add: int_pow_def nat_pow_def)\n\nlemma (in group) int_pow_one [simp]:\n  \"\\<one> [^] (z::int) = \\<one>\"\n  by (simp add: int_pow_def2)\n\nlemma (in group) int_pow_closed [intro, simp]:\n  \"x \\<in> carrier G ==> x [^] (i::int) \\<in> carrier G\"\n  by (simp add: int_pow_def2)\n\nlemma (in group) int_pow_1 [simp]:\n  \"x \\<in> carrier G \\<Longrightarrow> x [^] (1::int) = x\"\n  by (simp add: int_pow_def2)\n\nlemma (in group) int_pow_neg:\n  \"x \\<in> carrier G \\<Longrightarrow> x [^] (-i::int) = inv (x [^] i)\"\n  by (simp add: int_pow_def2)\n\nlemma (in group) int_pow_neg_int: \"x \\<in> carrier G \\<Longrightarrow> x [^] -(int n) = inv (x [^] n)\"\n  by (simp add: int_pow_neg int_pow_int)\n\nlemma (in group) int_pow_mult:\n  assumes \"x \\<in> carrier G\" shows \"x [^] (i + j::int) = x [^] i \\<otimes> x [^] j\"\nproof -\n  have [simp]: \"-i - j = -j - i\" by simp\n  show ?thesis\n    by (auto simp: assms int_pow_def2 inv_solve_left inv_solve_right nat_add_distrib [symmetric] nat_pow_mult)\nqed\n\nlemma (in group) int_pow_inv:\n  \"x \\<in> carrier G \\<Longrightarrow> (inv x) [^] (i :: int) = inv (x [^] i)\"\n  by (metis int_pow_def2 nat_pow_inv)\n\nlemma (in group) int_pow_pow:\n  assumes \"x \\<in> carrier G\"\n  shows \"(x [^] (n :: int)) [^] (m :: int) = x [^] (n * m :: int)\"\nproof (cases)\n  assume n_ge: \"n \\<ge> 0\" thus ?thesis\n  proof (cases)\n    assume m_ge: \"m \\<ge> 0\" thus ?thesis\n      using n_ge nat_pow_pow[OF assms, of \"nat n\" \"nat m\"] int_pow_def2 [where G=G]\n      by (simp add: mult_less_0_iff nat_mult_distrib)\n  next\n    assume m_lt: \"\\<not> m \\<ge> 0\" \n    with n_ge show ?thesis\n      apply (simp add: int_pow_def2 mult_less_0_iff)\n      by (metis assms mult_minus_right n_ge nat_mult_distrib nat_pow_pow)\n  qed\nnext\n  assume n_lt: \"\\<not> n \\<ge> 0\" thus ?thesis\n  proof (cases)\n    assume m_ge: \"m \\<ge> 0\" \n    have \"inv x [^] (nat m * nat (- n)) = inv x [^] nat (- (m * n))\"\n      by (metis (full_types) m_ge mult_minus_right nat_mult_distrib)\n    with m_ge n_lt show ?thesis\n      by (simp add: int_pow_def2 mult_less_0_iff assms mult.commute nat_pow_inv nat_pow_pow)\n  next\n    assume m_lt: \"\\<not> m \\<ge> 0\" thus ?thesis\n      using n_lt by (auto simp: int_pow_def2 mult_less_0_iff assms nat_mult_distrib_neg nat_pow_inv nat_pow_pow)\n  qed\nqed\n\nlemma (in group) int_pow_diff:\n  \"x \\<in> carrier G \\<Longrightarrow> x [^] (n - m :: int) = x [^] n \\<otimes> inv (x [^] m)\"\n  by(simp only: diff_conv_add_uminus int_pow_mult int_pow_neg)\n\nlemma (in group) inj_on_multc: \"c \\<in> carrier G \\<Longrightarrow> inj_on (\\<lambda>x. x \\<otimes> c) (carrier G)\"\n  by(simp add: inj_on_def)\n\nlemma (in group) inj_on_cmult: \"c \\<in> carrier G \\<Longrightarrow> inj_on (\\<lambda>x. c \\<otimes> x) (carrier G)\"\n  by(simp add: inj_on_def)\n\n\nlemma (in monoid) group_commutes_pow:\n  fixes n::nat\n  shows \"\\<lbrakk>x \\<otimes> y = y \\<otimes> x; x \\<in> carrier G; y \\<in> carrier G\\<rbrakk> \\<Longrightarrow> x [^] n \\<otimes> y = y \\<otimes> x [^] n\"\n  apply (induction n, auto)\n  by (metis m_assoc nat_pow_closed)\n\nlemma (in monoid) pow_mult_distrib:\n  assumes eq: \"x \\<otimes> y = y \\<otimes> x\" and xy: \"x \\<in> carrier G\" \"y \\<in> carrier G\"\n  shows \"(x \\<otimes> y) [^] (n::nat) = x [^] n \\<otimes> y [^] n\"\nproof (induct n)\n  case (Suc n)\n  have \"x \\<otimes> (y [^] n \\<otimes> y) = y [^] n \\<otimes> x \\<otimes> y\"\n    by (simp add: eq group_commutes_pow m_assoc xy)\n  then show ?case\n    using assms Suc.hyps m_assoc by auto\nqed auto\n\nlemma (in group) int_pow_mult_distrib:\n  assumes eq: \"x \\<otimes> y = y \\<otimes> x\" and xy: \"x \\<in> carrier G\" \"y \\<in> carrier G\"\n  shows \"(x \\<otimes> y) [^] (i::int) = x [^] i \\<otimes> y [^] i\"\nproof (cases i rule: int_cases)\n  case (nonneg n)\n  then show ?thesis\n    by (metis eq int_pow_int pow_mult_distrib xy)\nnext\n  case (neg n)\n  then show ?thesis\n    unfolding neg\n    apply (simp add: xy int_pow_neg_int del: of_nat_Suc)\n    by (metis eq inv_mult_group local.nat_pow_Suc nat_pow_closed pow_mult_distrib xy)\nqed\n\nlemma (in group) pow_eq_div2:\n  fixes m n :: nat\n  assumes x_car: \"x \\<in> carrier G\"\n  assumes pow_eq: \"x [^] m = x [^] n\"\n  shows \"x [^] (m - n) = \\<one>\"\nproof (cases \"m < n\")\n  case False\n  have \"\\<one> \\<otimes> x [^] m = x [^] m\" by (simp add: x_car)\n  also have \"\\<dots> = x [^] (m - n) \\<otimes> x [^] n\"\n    using False by (simp add: nat_pow_mult x_car)\n  also have \"\\<dots> = x [^] (m - n) \\<otimes> x [^] m\"\n    by (simp add: pow_eq)\n  finally show ?thesis\n    by (metis nat_pow_closed one_closed right_cancel x_car)\nqed simp\n\nsubsection \\<open>Submonoids\\<close>\n\nlocale submonoid = \\<^marker>\\<open>contributor \\<open>Martin Baillon\\<close>\\<close>\n  fixes H and G (structure)\n  assumes subset: \"H \\<subseteq> carrier G\"\n    and m_closed [intro, simp]: \"\\<lbrakk>x \\<in> H; y \\<in> H\\<rbrakk> \\<Longrightarrow> x \\<otimes> y \\<in> H\"\n    and one_closed [simp]: \"\\<one> \\<in> H\"\n\nlemma (in submonoid) is_submonoid: \\<^marker>\\<open>contributor \\<open>Martin Baillon\\<close>\\<close>\n  \"submonoid H G\" by (rule submonoid_axioms)\n\nlemma (in submonoid) mem_carrier [simp]: \\<^marker>\\<open>contributor \\<open>Martin Baillon\\<close>\\<close>\n  \"x \\<in> H \\<Longrightarrow> x \\<in> carrier G\"\n  using subset by blast\n\nlemma (in submonoid) submonoid_is_monoid [intro]: \\<^marker>\\<open>contributor \\<open>Martin Baillon\\<close>\\<close>\n  assumes \"monoid G\"\n  shows \"monoid (G\\<lparr>carrier := H\\<rparr>)\"\nproof -\n  interpret monoid G by fact\n  show ?thesis\n    by (simp add: monoid_def m_assoc)\nqed\n\nlemma submonoid_nonempty: \\<^marker>\\<open>contributor \\<open>Martin Baillon\\<close>\\<close>\n  \"~ submonoid {} G\"\n  by (blast dest: submonoid.one_closed)\n\nlemma (in submonoid) finite_monoid_imp_card_positive: \\<^marker>\\<open>contributor \\<open>Martin Baillon\\<close>\\<close>\n  \"finite (carrier G) ==> 0 < card H\"\nproof (rule classical)\n  assume \"finite (carrier G)\" and a: \"~ 0 < card H\"\n  then have \"finite H\" by (blast intro: finite_subset [OF subset])\n  with is_submonoid a have \"submonoid {} G\" by simp\n  with submonoid_nonempty show ?thesis by contradiction\nqed\n\n\nlemma (in monoid) monoid_incl_imp_submonoid : \\<^marker>\\<open>contributor \\<open>Martin Baillon\\<close>\\<close>\n  assumes \"H \\<subseteq> carrier G\"\nand \"monoid (G\\<lparr>carrier := H\\<rparr>)\"\nshows \"submonoid H G\"\nproof (intro submonoid.intro[OF assms(1)])\n  have ab_eq : \"\\<And> a b. a \\<in> H \\<Longrightarrow> b \\<in> H \\<Longrightarrow> a \\<otimes>\\<^bsub>G\\<lparr>carrier := H\\<rparr>\\<^esub> b = a \\<otimes> b\" using assms by simp\n  have \"\\<And>a b. a \\<in> H \\<Longrightarrow> b \\<in> H \\<Longrightarrow> a \\<otimes> b \\<in> carrier (G\\<lparr>carrier := H\\<rparr>) \"\n    using assms ab_eq unfolding group_def using monoid.m_closed by fastforce\n  thus \"\\<And>a b. a \\<in> H \\<Longrightarrow> b \\<in> H \\<Longrightarrow> a \\<otimes> b \\<in> H\" by simp\n  show \"\\<one> \\<in> H \" using monoid.one_closed[OF assms(2)] assms by simp\nqed\n\nlemma (in monoid) inv_unique': \\<^marker>\\<open>contributor \\<open>Martin Baillon\\<close>\\<close>\n  assumes \"x \\<in> carrier G\" \"y \\<in> carrier G\"\n  shows \"\\<lbrakk> x \\<otimes> y = \\<one>; y \\<otimes> x = \\<one> \\<rbrakk> \\<Longrightarrow> y = inv x\"\nproof -\n  assume \"x \\<otimes> y = \\<one>\" and l_inv: \"y \\<otimes> x = \\<one>\"\n  hence unit: \"x \\<in> Units G\"\n    using assms unfolding Units_def by auto\n  show \"y = inv x\"\n    using inv_unique[OF l_inv Units_r_inv[OF unit] assms Units_inv_closed[OF unit]] .\nqed\n\nlemma (in monoid) m_inv_monoid_consistent: \\<^marker>\\<open>contributor \\<open>Paulo Em\u00edlio de Vilhena\\<close>\\<close>\n  assumes \"x \\<in> Units (G \\<lparr> carrier := H \\<rparr>)\" and \"submonoid H G\"\n  shows \"inv\\<^bsub>(G \\<lparr> carrier := H \\<rparr>)\\<^esub> x = inv x\"\nproof -\n  have monoid: \"monoid (G \\<lparr> carrier := H \\<rparr>)\"\n    using submonoid.submonoid_is_monoid[OF assms(2) monoid_axioms] .\n  obtain y where y: \"y \\<in> H\" \"x \\<otimes> y = \\<one>\" \"y \\<otimes> x = \\<one>\"\n    using assms(1) unfolding Units_def by auto\n  have x: \"x \\<in> H\" and in_carrier: \"x \\<in> carrier G\" \"y \\<in> carrier G\"\n    using y(1) submonoid.subset[OF assms(2)] assms(1) unfolding Units_def by auto\n  show ?thesis\n    using monoid.inv_unique'[OF monoid, of x y] x y\n    using inv_unique'[OF in_carrier y(2-3)] by auto\nqed\n\nsubsection \\<open>Subgroups\\<close>\n\nlocale subgroup =\n  fixes H and G (structure)\n  assumes subset: \"H \\<subseteq> carrier G\"\n    and m_closed [intro, simp]: \"\\<lbrakk>x \\<in> H; y \\<in> H\\<rbrakk> \\<Longrightarrow> x \\<otimes> y \\<in> H\"\n    and one_closed [simp]: \"\\<one> \\<in> H\"\n    and m_inv_closed [intro,simp]: \"x \\<in> H \\<Longrightarrow> inv x \\<in> H\"\n\nlemma (in subgroup) is_subgroup:\n  \"subgroup H G\" by (rule subgroup_axioms)\n\ndeclare (in subgroup) group.intro [intro]\n\nlemma (in subgroup) mem_carrier [simp]:\n  \"x \\<in> H \\<Longrightarrow> x \\<in> carrier G\"\n  using subset by blast\n\nlemma (in subgroup) subgroup_is_group [intro]:\n  assumes \"group G\"\n  shows \"group (G\\<lparr>carrier := H\\<rparr>)\"\nproof -\n  interpret group G by fact\n  have \"Group.monoid (G\\<lparr>carrier := H\\<rparr>)\"\n    by (simp add: monoid_axioms submonoid.intro submonoid.submonoid_is_monoid subset)\n  then show ?thesis\n    by (rule monoid.group_l_invI) (auto intro: l_inv mem_carrier)\nqed\n\nlemma subgroup_is_submonoid:\n  assumes \"subgroup H G\" shows \"submonoid H G\"\n  using assms by (auto intro: submonoid.intro simp add: subgroup_def)\n\nlemma (in group) subgroup_Units:\n  assumes \"subgroup H G\" shows \"H \\<subseteq> Units (G \\<lparr> carrier := H \\<rparr>)\"\n  using group.Units[OF subgroup.subgroup_is_group[OF assms group_axioms]] by simp\n\nlemma (in group) m_inv_consistent [simp]:\n  assumes \"subgroup H G\" \"x \\<in> H\"\n  shows \"inv\\<^bsub>(G \\<lparr> carrier := H \\<rparr>)\\<^esub> x = inv x\"\n  using assms m_inv_monoid_consistent[OF _ subgroup_is_submonoid] subgroup_Units[of H] by auto\n\nlemma (in group) int_pow_consistent: \\<^marker>\\<open>contributor \\<open>Paulo Em\u00edlio de Vilhena\\<close>\\<close>\n  assumes \"subgroup H G\" \"x \\<in> H\"\n  shows \"x [^] (n :: int) = x [^]\\<^bsub>(G \\<lparr> carrier := H \\<rparr>)\\<^esub> n\"\nproof (cases)\n  assume ge: \"n \\<ge> 0\"\n  hence \"x [^] n = x [^] (nat n)\"\n    using int_pow_def2 [of G] by auto\n  also have \" ... = x [^]\\<^bsub>(G \\<lparr> carrier := H \\<rparr>)\\<^esub> (nat n)\"\n    using nat_pow_consistent by simp\n  also have \" ... = x [^]\\<^bsub>(G \\<lparr> carrier := H \\<rparr>)\\<^esub> n\"\n    by (metis ge int_nat_eq int_pow_int)\n  finally show ?thesis .\nnext\n  assume \"\\<not> n \\<ge> 0\" hence lt: \"n < 0\" by simp\n  hence \"x [^] n = inv (x [^] (nat (- n)))\"\n    using int_pow_def2 [of G] by auto\n  also have \" ... = (inv x) [^] (nat (- n))\"\n    by (metis assms nat_pow_inv subgroup.mem_carrier)\n  also have \" ... = (inv\\<^bsub>(G \\<lparr> carrier := H \\<rparr>)\\<^esub> x) [^]\\<^bsub>(G \\<lparr> carrier := H \\<rparr>)\\<^esub> (nat (- n))\"\n    using m_inv_consistent[OF assms] nat_pow_consistent by auto\n  also have \" ... = inv\\<^bsub>(G \\<lparr> carrier := H \\<rparr>)\\<^esub> (x [^]\\<^bsub>(G \\<lparr> carrier := H \\<rparr>)\\<^esub> (nat (- n)))\"\n    using group.nat_pow_inv[OF subgroup.subgroup_is_group[OF assms(1) is_group]] assms(2) by auto\n  also have \" ... = x [^]\\<^bsub>(G \\<lparr> carrier := H \\<rparr>)\\<^esub> n\"\n    by (simp add: int_pow_def2 lt)\n  finally show ?thesis .\nqed\n\ntext \\<open>\n  Since \\<^term>\\<open>H\\<close> is nonempty, it contains some element \\<^term>\\<open>x\\<close>.  Since\n  it is closed under inverse, it contains \\<open>inv x\\<close>.  Since\n  it is closed under product, it contains \\<open>x \\<otimes> inv x = \\<one>\\<close>.\n\\<close>\n\nlemma (in group) one_in_subset:\n  \"[| H \\<subseteq> carrier G; H \\<noteq> {}; \\<forall>a \\<in> H. inv a \\<in> H; \\<forall>a\\<in>H. \\<forall>b\\<in>H. a \\<otimes> b \\<in> H |]\n   ==> \\<one> \\<in> H\"\nby force\n\ntext \\<open>A characterization of subgroups: closed, non-empty subset.\\<close>\n\nlemma (in group) subgroupI:\n  assumes subset: \"H \\<subseteq> carrier G\" and non_empty: \"H \\<noteq> {}\"\n    and inv: \"!!a. a \\<in> H \\<Longrightarrow> inv a \\<in> H\"\n    and mult: \"!!a b. \\<lbrakk>a \\<in> H; b \\<in> H\\<rbrakk> \\<Longrightarrow> a \\<otimes> b \\<in> H\"\n  shows \"subgroup H G\"\nproof (simp add: subgroup_def assms)\n  show \"\\<one> \\<in> H\" by (rule one_in_subset) (auto simp only: assms)\nqed\n\nlemma (in group) subgroupE:\n  assumes \"subgroup H G\"\n  shows \"H \\<subseteq> carrier G\"\n    and \"H \\<noteq> {}\"\n    and \"\\<And>a. a \\<in> H \\<Longrightarrow> inv a \\<in> H\"\n    and \"\\<And>a b. \\<lbrakk> a \\<in> H; b \\<in> H \\<rbrakk> \\<Longrightarrow> a \\<otimes> b \\<in> H\"\n  using assms unfolding subgroup_def[of H G] by auto\n\ndeclare monoid.one_closed [iff] group.inv_closed [simp]\n  monoid.l_one [simp] monoid.r_one [simp] group.inv_inv [simp]\n\nlemma subgroup_nonempty:\n  \"\\<not> subgroup {} G\"\n  by (blast dest: subgroup.one_closed)\n\nlemma (in subgroup) finite_imp_card_positive: \"finite (carrier G) \\<Longrightarrow> 0 < card H\"\n  using subset one_closed card_gt_0_iff finite_subset by blast\n\nlemma (in subgroup) subgroup_is_submonoid : \\<^marker>\\<open>contributor \\<open>Martin Baillon\\<close>\\<close>\n  \"submonoid H G\"\n  by (simp add: submonoid.intro subset)\n\nlemma (in group) submonoid_subgroupI : \\<^marker>\\<open>contributor \\<open>Martin Baillon\\<close>\\<close>\n  assumes \"submonoid H G\"\n    and \"\\<And>a. a \\<in> H \\<Longrightarrow> inv a \\<in> H\"\n  shows \"subgroup H G\"\n  by (metis assms subgroup_def submonoid_def)\n\nlemma (in group) group_incl_imp_subgroup: \\<^marker>\\<open>contributor \\<open>Martin Baillon\\<close>\\<close>\n  assumes \"H \\<subseteq> carrier G\"\n    and \"group (G\\<lparr>carrier := H\\<rparr>)\"\n  shows \"subgroup H G\"\nproof (intro submonoid_subgroupI[OF monoid_incl_imp_submonoid[OF assms(1)]])\n  show \"monoid (G\\<lparr>carrier := H\\<rparr>)\" using group_def assms by blast\n  have ab_eq : \"\\<And> a b. a \\<in> H \\<Longrightarrow> b \\<in> H \\<Longrightarrow> a \\<otimes>\\<^bsub>G\\<lparr>carrier := H\\<rparr>\\<^esub> b = a \\<otimes> b\" using assms by simp\n  fix a  assume aH : \"a \\<in> H\"\n  have \" inv\\<^bsub>G\\<lparr>carrier := H\\<rparr>\\<^esub> a \\<in> carrier G\"\n    using assms aH group.inv_closed[OF assms(2)] by auto\n  moreover have \"\\<one>\\<^bsub>G\\<lparr>carrier := H\\<rparr>\\<^esub> = \\<one>\" using assms monoid.one_closed ab_eq one_def by simp\n  hence \"a \\<otimes>\\<^bsub>G\\<lparr>carrier := H\\<rparr>\\<^esub> inv\\<^bsub>G\\<lparr>carrier := H\\<rparr>\\<^esub> a= \\<one>\"\n    using assms ab_eq aH  group.r_inv[OF assms(2)] by simp\n  hence \"a \\<otimes> inv\\<^bsub>G\\<lparr>carrier := H\\<rparr>\\<^esub> a= \\<one>\"\n    using aH assms group.inv_closed[OF assms(2)] ab_eq by simp\n  ultimately have \"inv\\<^bsub>G\\<lparr>carrier := H\\<rparr>\\<^esub> a = inv a\"\n    by (metis aH assms(1) contra_subsetD group.inv_inv is_group local.inv_equality)\n  moreover have \"inv\\<^bsub>G\\<lparr>carrier := H\\<rparr>\\<^esub> a \\<in> H\" \n    using aH group.inv_closed[OF assms(2)] by auto\n  ultimately show \"inv a \\<in> H\" by auto\nqed\n\n\nsubsection \\<open>Direct Products\\<close>\n\ndefinition\n  DirProd :: \"_ \\<Rightarrow> _ \\<Rightarrow> ('a \\<times> 'b) monoid\" (infixr \"\\<times>\\<times>\" 80) where\n  \"G \\<times>\\<times> H =\n    \\<lparr>carrier = carrier G \\<times> carrier H,\n     mult = (\\<lambda>(g, h) (g', h'). (g \\<otimes>\\<^bsub>G\\<^esub> g', h \\<otimes>\\<^bsub>H\\<^esub> h')),\n     one = (\\<one>\\<^bsub>G\\<^esub>, \\<one>\\<^bsub>H\\<^esub>)\\<rparr>\"\n\nlemma DirProd_monoid:\n  assumes \"monoid G\" and \"monoid H\"\n  shows \"monoid (G \\<times>\\<times> H)\"\nproof -\n  interpret G: monoid G by fact\n  interpret H: monoid H by fact\n  from assms\n  show ?thesis by (unfold monoid_def DirProd_def, auto)\nqed\n\n\ntext\\<open>Does not use the previous result because it's easier just to use auto.\\<close>\nlemma DirProd_group:\n  assumes \"group G\" and \"group H\"\n  shows \"group (G \\<times>\\<times> H)\"\nproof -\n  interpret G: group G by fact\n  interpret H: group H by fact\n  show ?thesis by (rule groupI)\n     (auto intro: G.m_assoc H.m_assoc G.l_inv H.l_inv\n           simp add: DirProd_def)\nqed\n\nlemma carrier_DirProd [simp]: \"carrier (G \\<times>\\<times> H) = carrier G \\<times> carrier H\"\n  by (simp add: DirProd_def)\n\nlemma one_DirProd [simp]: \"\\<one>\\<^bsub>G \\<times>\\<times> H\\<^esub> = (\\<one>\\<^bsub>G\\<^esub>, \\<one>\\<^bsub>H\\<^esub>)\"\n  by (simp add: DirProd_def)\n\nlemma mult_DirProd [simp]: \"(g, h) \\<otimes>\\<^bsub>(G \\<times>\\<times> H)\\<^esub> (g', h') = (g \\<otimes>\\<^bsub>G\\<^esub> g', h \\<otimes>\\<^bsub>H\\<^esub> h')\"\n  by (simp add: DirProd_def)\n\nlemma mult_DirProd': \"x \\<otimes>\\<^bsub>(G \\<times>\\<times> H)\\<^esub> y = (fst x \\<otimes>\\<^bsub>G\\<^esub> fst y, snd x \\<otimes>\\<^bsub>H\\<^esub> snd y)\"\n  by (subst mult_DirProd [symmetric]) simp\n\nlemma DirProd_assoc: \"(G \\<times>\\<times> H \\<times>\\<times> I) = (G \\<times>\\<times> (H \\<times>\\<times> I))\"\n  by auto\n\nlemma inv_DirProd [simp]:\n  assumes \"group G\" and \"group H\"\n  assumes g: \"g \\<in> carrier G\"\n      and h: \"h \\<in> carrier H\"\n  shows \"m_inv (G \\<times>\\<times> H) (g, h) = (inv\\<^bsub>G\\<^esub> g, inv\\<^bsub>H\\<^esub> h)\"\nproof -\n  interpret G: group G by fact\n  interpret H: group H by fact\n  interpret Prod: group \"G \\<times>\\<times> H\"\n    by (auto intro: DirProd_group group.intro group.axioms assms)\n  show ?thesis by (simp add: Prod.inv_equality g h)\nqed\n\nlemma DirProd_subgroups :\n  assumes \"group G\"\n    and \"subgroup H G\"\n    and \"group K\"\n    and \"subgroup I K\"\n  shows \"subgroup (H \\<times> I) (G \\<times>\\<times> K)\"\nproof (intro group.group_incl_imp_subgroup[OF DirProd_group[OF assms(1)assms(3)]])\n  have \"H \\<subseteq> carrier G\" \"I \\<subseteq> carrier K\" using subgroup.subset assms by blast+\n  thus \"(H \\<times> I) \\<subseteq> carrier (G \\<times>\\<times> K)\" unfolding DirProd_def by auto\n  have \"Group.group ((G\\<lparr>carrier := H\\<rparr>) \\<times>\\<times> (K\\<lparr>carrier := I\\<rparr>))\"\n    using DirProd_group[OF subgroup.subgroup_is_group[OF assms(2)assms(1)]\n        subgroup.subgroup_is_group[OF assms(4)assms(3)]].\n  moreover have \"((G\\<lparr>carrier := H\\<rparr>) \\<times>\\<times> (K\\<lparr>carrier := I\\<rparr>)) = ((G \\<times>\\<times> K)\\<lparr>carrier := H \\<times> I\\<rparr>)\"\n    unfolding DirProd_def using assms by simp\n  ultimately show \"Group.group ((G \\<times>\\<times> K)\\<lparr>carrier := H \\<times> I\\<rparr>)\" by simp\nqed\n\nsubsection \\<open>Homomorphisms (mono and epi) and Isomorphisms\\<close>\n\ndefinition\n  hom :: \"_ => _ => ('a => 'b) set\" where\n  \"hom G H =\n    {h. h \\<in> carrier G \\<rightarrow> carrier H \\<and>\n      (\\<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\nlemma homI:\n  \"\\<lbrakk>\\<And>x. x \\<in> carrier G \\<Longrightarrow> h x \\<in> carrier H;\n    \\<And>x y. \\<lbrakk>x \\<in> carrier G; y \\<in> carrier G\\<rbrakk> \\<Longrightarrow> h (x \\<otimes>\\<^bsub>G\\<^esub> y) = h x \\<otimes>\\<^bsub>H\\<^esub> h y\\<rbrakk> \\<Longrightarrow> h \\<in> hom G H\"\n  by (auto simp: hom_def)\n\nlemma hom_carrier: \"h \\<in> hom G H \\<Longrightarrow> h ` carrier G \\<subseteq> carrier H\"\n  by (auto simp: hom_def)\n\nlemma hom_in_carrier: \"\\<lbrakk>h \\<in> hom G H; x \\<in> carrier G\\<rbrakk> \\<Longrightarrow> h x \\<in> carrier H\"\n  by (auto simp: hom_def)\n\nlemma hom_compose:\n  \"\\<lbrakk> f \\<in> hom G H; g \\<in> hom H I \\<rbrakk> \\<Longrightarrow> g \\<circ> f \\<in> hom G I\"\n  unfolding hom_def by (auto simp add: Pi_iff)\n\nlemma (in group) hom_restrict:\n  assumes \"h \\<in> hom G H\" and \"\\<And>g. g \\<in> carrier G \\<Longrightarrow> h g = t g\" shows \"t \\<in> hom G H\"\n  using assms unfolding hom_def by (auto simp add: Pi_iff)\n\nlemma (in group) hom_compose:\n  \"[|h \\<in> hom G H; i \\<in> hom H I|] ==> compose (carrier G) i h \\<in> hom G I\"\nby (fastforce simp add: hom_def compose_def)\n\nlemma (in group) restrict_hom_iff [simp]:\n  \"(\\<lambda>x. if x \\<in> carrier G then f x else g x) \\<in> hom G H \\<longleftrightarrow> f \\<in> hom G H\"\n  by (simp add: hom_def Pi_iff)\n\ndefinition iso :: \"_ => _ => ('a => 'b) set\"\n  where \"iso G H = {h. h \\<in> hom G H \\<and> bij_betw h (carrier G) (carrier H)}\"\n\ndefinition is_iso :: \"_ \\<Rightarrow> _ \\<Rightarrow> bool\" (infixr \"\\<cong>\" 60)\n  where \"G \\<cong> H = (iso G H  \\<noteq> {})\"\n\ndefinition mon where \"mon G H = {f \\<in> hom G H. inj_on f (carrier G)}\"\n\ndefinition epi where \"epi G H = {f \\<in> hom G H. f ` (carrier G) = carrier H}\"\n\nlemma isoI:\n  \"\\<lbrakk>h \\<in> hom G H; bij_betw h (carrier G) (carrier H)\\<rbrakk> \\<Longrightarrow> h \\<in> iso G H\"\n  by (auto simp: iso_def)\n\nlemma is_isoI: \"h \\<in> iso G H \\<Longrightarrow> G \\<cong> H\"\n  using is_iso_def by auto\n\nlemma epi_iff_subset:\n   \"f \\<in> epi G G' \\<longleftrightarrow> f \\<in> hom G G' \\<and> carrier G' \\<subseteq> f ` carrier G\"\n  by (auto simp: epi_def hom_def)\n\nlemma iso_iff_mon_epi: \"f \\<in> iso G H \\<longleftrightarrow> f \\<in> mon G H \\<and> f \\<in> epi G H\"\n  by (auto simp: iso_def mon_def epi_def bij_betw_def)\n\nlemma iso_set_refl: \"(\\<lambda>x. x) \\<in> iso G G\"\n  by (simp add: iso_def hom_def inj_on_def bij_betw_def Pi_def)\n\nlemma id_iso: \"id \\<in> iso G G\"\n  by (simp add: iso_def hom_def inj_on_def bij_betw_def Pi_def)\n\ncorollary iso_refl [simp]: \"G \\<cong> G\"\n  using iso_set_refl unfolding is_iso_def by auto\n\nlemma iso_iff:\n   \"h \\<in> iso G H \\<longleftrightarrow> h \\<in> hom G H \\<and> h ` (carrier G) = carrier H \\<and> inj_on h (carrier G)\"\n  by (auto simp: iso_def hom_def bij_betw_def)\n\nlemma iso_imp_homomorphism:\n   \"h \\<in> iso G H \\<Longrightarrow> h \\<in> hom G H\"\n  by (simp add: iso_iff)\n\nlemma trivial_hom:\n   \"group H \\<Longrightarrow> (\\<lambda>x. one H) \\<in> hom G H\"\n  by (auto simp: hom_def Group.group_def)\n\nlemma (in group) hom_eq:\n  assumes \"f \\<in> hom G H\" \"\\<And>x. x \\<in> carrier G \\<Longrightarrow> f' x = f x\"\n  shows \"f' \\<in> hom G H\"\n  using assms by (auto simp: hom_def)\n\nlemma (in group) iso_eq:\n  assumes \"f \\<in> iso G H\" \"\\<And>x. x \\<in> carrier G \\<Longrightarrow> f' x = f x\"\n  shows \"f' \\<in> iso G H\"\n  using assms  by (fastforce simp: iso_def inj_on_def bij_betw_def hom_eq image_iff)\n\nlemma (in group) iso_set_sym:\n  assumes \"h \\<in> iso G H\"\n  shows \"inv_into (carrier G) h \\<in> iso H G\"\nproof -\n  have h: \"h \\<in> hom G H\" \"bij_betw h (carrier G) (carrier H)\"\n    using assms by (auto simp add: iso_def bij_betw_inv_into)\n  then have HG: \"bij_betw (inv_into (carrier G) h) (carrier H) (carrier G)\"\n    by (simp add: bij_betw_inv_into)\n  have \"inv_into (carrier G) h \\<in> hom H G\"\n    unfolding hom_def\n  proof safe\n    show *: \"\\<And>x. x \\<in> carrier H \\<Longrightarrow> inv_into (carrier G) h x \\<in> carrier G\"\n      by (meson HG bij_betwE)\n    show \"inv_into (carrier G) h (x \\<otimes>\\<^bsub>H\\<^esub> y) = inv_into (carrier G) h x \\<otimes> inv_into (carrier G) h y\"\n      if \"x \\<in> carrier H\" \"y \\<in> carrier H\" for x y\n    proof (rule inv_into_f_eq)\n      show \"inj_on h (carrier G)\"\n        using bij_betw_def h(2) by blast\n      show \"inv_into (carrier G) h x \\<otimes> inv_into (carrier G) h y \\<in> carrier G\"\n        by (simp add: * that)\n      show \"h (inv_into (carrier G) h x \\<otimes> inv_into (carrier G) h y) = x \\<otimes>\\<^bsub>H\\<^esub> y\"\n        using h bij_betw_inv_into_right [of h] unfolding hom_def by (simp add: \"*\" that)\n    qed\n  qed\n  then show ?thesis\n    by (simp add: Group.iso_def bij_betw_inv_into h)\nqed\n\ncorollary (in group) iso_sym: \"G \\<cong> H \\<Longrightarrow> H \\<cong> G\"\n  using iso_set_sym unfolding is_iso_def by auto\n\nlemma iso_set_trans:\n  \"\\<lbrakk>h \\<in> Group.iso G H; i \\<in> Group.iso H I\\<rbrakk> \\<Longrightarrow> i \\<circ> h \\<in> Group.iso G I\"\n  by (force simp: iso_def hom_compose intro: bij_betw_trans)\n\ncorollary iso_trans [trans]: \"\\<lbrakk>G \\<cong> H ; H \\<cong> I\\<rbrakk> \\<Longrightarrow> G \\<cong> I\"\n  using iso_set_trans unfolding is_iso_def by blast\n\nlemma iso_same_card: \"G \\<cong> H \\<Longrightarrow> card (carrier G) = card (carrier H)\"\n  using bij_betw_same_card  unfolding is_iso_def iso_def by auto\n\nlemma iso_finite: \"G \\<cong> H \\<Longrightarrow> finite(carrier G) \\<longleftrightarrow> finite(carrier H)\"\n  by (auto simp: is_iso_def iso_def bij_betw_finite)\n\nlemma mon_compose:\n   \"\\<lbrakk>f \\<in> mon G H; g \\<in> mon H K\\<rbrakk> \\<Longrightarrow> (g \\<circ> f) \\<in> mon G K\"\n  by (auto simp: mon_def intro: hom_compose comp_inj_on inj_on_subset [OF _ hom_carrier])\n\nlemma mon_compose_rev:\n   \"\\<lbrakk>f \\<in> hom G H; g \\<in> hom H K; (g \\<circ> f) \\<in> mon G K\\<rbrakk> \\<Longrightarrow> f \\<in> mon G H\"\n  using inj_on_imageI2 by (auto simp: mon_def)\n\nlemma epi_compose:\n   \"\\<lbrakk>f \\<in> epi G H; g \\<in> epi H K\\<rbrakk> \\<Longrightarrow> (g \\<circ> f) \\<in> epi G K\"\n  using hom_compose by (force simp: epi_def hom_compose simp flip: image_image)\n\nlemma epi_compose_rev:\n   \"\\<lbrakk>f \\<in> hom G H; g \\<in> hom H K; (g \\<circ> f) \\<in> epi G K\\<rbrakk> \\<Longrightarrow> g \\<in> epi H K\"\n  by (fastforce simp: epi_def hom_def Pi_iff image_def set_eq_iff)\n\nlemma iso_compose_rev:\n   \"\\<lbrakk>f \\<in> hom G H; g \\<in> hom H K; (g \\<circ> f) \\<in> iso G K\\<rbrakk> \\<Longrightarrow> f \\<in> mon G H \\<and> g \\<in> epi H K\"\n  unfolding iso_iff_mon_epi using mon_compose_rev epi_compose_rev by blast\n\nlemma epi_iso_compose_rev:\n  assumes \"f \\<in> epi G H\" \"g \\<in> hom H K\" \"(g \\<circ> f) \\<in> iso G K\"\n  shows \"f \\<in> iso G H \\<and> g \\<in> iso H K\"\nproof\n  show \"f \\<in> iso G H\"\n    by (metis (no_types, lifting) assms epi_def iso_compose_rev iso_iff_mon_epi mem_Collect_eq)\n  then have \"f \\<in> hom G H \\<and> bij_betw f (carrier G) (carrier H)\"\n    using Group.iso_def \\<open>f \\<in> Group.iso G H\\<close> by blast\n  then have \"bij_betw g (carrier H) (carrier K)\"\n    using Group.iso_def assms(3) bij_betw_comp_iff by blast\n  then show \"g \\<in> iso H K\"\n    using Group.iso_def assms(2) by blast\nqed\n\nlemma mon_left_invertible:\n   \"\\<lbrakk>f \\<in> hom G H; \\<And>x. x \\<in> carrier G \\<Longrightarrow> g(f x) = x\\<rbrakk> \\<Longrightarrow> f \\<in> mon G H\"\n  by (simp add: mon_def inj_on_def) metis\n\nlemma epi_right_invertible:\n   \"\\<lbrakk>g \\<in> hom H G; f \\<in> carrier G \\<rightarrow> carrier H; \\<And>x. x \\<in> carrier G \\<Longrightarrow> g(f x) = x\\<rbrakk> \\<Longrightarrow> g \\<in> epi H G\"\n  by (force simp: Pi_iff epi_iff_subset image_subset_iff_funcset subset_iff)\n\nlemma (in monoid) hom_imp_img_monoid: \\<^marker>\\<open>contributor \\<open>Paulo Em\u00edlio de Vilhena\\<close>\\<close>\n  assumes \"h \\<in> hom G H\"\n  shows \"monoid (H \\<lparr> carrier := h ` (carrier G), one := h \\<one>\\<^bsub>G\\<^esub> \\<rparr>)\" (is \"monoid ?h_img\")\nproof (rule monoidI)\n  show \"\\<one>\\<^bsub>?h_img\\<^esub> \\<in> carrier ?h_img\"\n    by auto\nnext\n  fix x y z assume \"x \\<in> carrier ?h_img\" \"y \\<in> carrier ?h_img\" \"z \\<in> carrier ?h_img\"\n  then obtain g1 g2 g3\n    where g1: \"g1 \\<in> carrier G\" \"x = h g1\"\n      and g2: \"g2 \\<in> carrier G\" \"y = h g2\"\n      and g3: \"g3 \\<in> carrier G\" \"z = h g3\"\n    using image_iff[where ?f = h and ?A = \"carrier G\"] by auto\n  have aux_lemma:\n    \"\\<And>a b. \\<lbrakk> a \\<in> carrier G; b \\<in> carrier G \\<rbrakk> \\<Longrightarrow> h a \\<otimes>\\<^bsub>(?h_img)\\<^esub> h b = h (a \\<otimes> b)\"\n    using assms unfolding hom_def by auto\n\n  show \"x \\<otimes>\\<^bsub>(?h_img)\\<^esub> \\<one>\\<^bsub>(?h_img)\\<^esub> = x\"\n    using aux_lemma[OF g1(1) one_closed] g1(2) r_one[OF g1(1)] by simp\n\n  show \"\\<one>\\<^bsub>(?h_img)\\<^esub> \\<otimes>\\<^bsub>(?h_img)\\<^esub> x = x\"\n    using aux_lemma[OF one_closed g1(1)] g1(2) l_one[OF g1(1)] by simp\n\n  have \"x \\<otimes>\\<^bsub>(?h_img)\\<^esub> y = h (g1 \\<otimes> g2)\"\n    using aux_lemma g1 g2 by auto\n  thus \"x \\<otimes>\\<^bsub>(?h_img)\\<^esub> y \\<in> carrier ?h_img\"\n    using g1(1) g2(1) by simp\n\n  have \"(x \\<otimes>\\<^bsub>(?h_img)\\<^esub> y) \\<otimes>\\<^bsub>(?h_img)\\<^esub> z = h ((g1 \\<otimes> g2) \\<otimes> g3)\"\n    using aux_lemma g1 g2 g3 by auto\n  also have \" ... = h (g1 \\<otimes> (g2 \\<otimes> g3))\"\n    using m_assoc[OF g1(1) g2(1) g3(1)] by simp\n  also have \" ... = x \\<otimes>\\<^bsub>(?h_img)\\<^esub> (y \\<otimes>\\<^bsub>(?h_img)\\<^esub> z)\"\n    using aux_lemma g1 g2 g3 by auto\n  finally show \"(x \\<otimes>\\<^bsub>(?h_img)\\<^esub> y) \\<otimes>\\<^bsub>(?h_img)\\<^esub> z = x \\<otimes>\\<^bsub>(?h_img)\\<^esub> (y \\<otimes>\\<^bsub>(?h_img)\\<^esub> z)\" .\nqed\n\nlemma (in group) hom_imp_img_group: \\<^marker>\\<open>contributor \\<open>Paulo Em\u00edlio de Vilhena\\<close>\\<close>\n  assumes \"h \\<in> hom G H\"\n  shows \"group (H \\<lparr> carrier := h ` (carrier G), one := h \\<one>\\<^bsub>G\\<^esub> \\<rparr>)\" (is \"group ?h_img\")\nproof -\n  interpret monoid ?h_img\n    using hom_imp_img_monoid[OF assms] .\n\n  show ?thesis\n  proof (unfold_locales)\n    show \"carrier ?h_img \\<subseteq> Units ?h_img\"\n    proof (auto simp add: Units_def)\n      have aux_lemma:\n        \"\\<And>g1 g2. \\<lbrakk> g1 \\<in> carrier G; g2 \\<in> carrier G \\<rbrakk> \\<Longrightarrow> h g1 \\<otimes>\\<^bsub>H\\<^esub> h g2 = h (g1 \\<otimes> g2)\"\n        using assms unfolding hom_def by auto\n\n      fix g1 assume g1: \"g1 \\<in> carrier G\"\n      thus \"\\<exists>g2 \\<in> carrier G. (h g2) \\<otimes>\\<^bsub>H\\<^esub> (h g1) = h \\<one> \\<and> (h g1) \\<otimes>\\<^bsub>H\\<^esub> (h g2) = h \\<one>\"\n        using aux_lemma[OF g1 inv_closed[OF g1]]\n              aux_lemma[OF inv_closed[OF g1] g1]\n              inv_closed by auto\n    qed\n  qed\nqed\n\nlemma (in group) iso_imp_group: \\<^marker>\\<open>contributor \\<open>Paulo Em\u00edlio de Vilhena\\<close>\\<close>\n  assumes \"G \\<cong> H\" and \"monoid H\"\n  shows \"group H\"\nproof -\n  obtain \\<phi> where phi: \"\\<phi> \\<in> iso G H\" \"inv_into (carrier G) \\<phi> \\<in> iso H G\"\n    using iso_set_sym assms unfolding is_iso_def by blast\n  define \\<psi> where psi_def: \"\\<psi> = inv_into (carrier G) \\<phi>\"\n\n  have surj: \"\\<phi> ` (carrier G) = (carrier H)\" \"\\<psi> ` (carrier H) = (carrier G)\"\n   and inj: \"inj_on \\<phi> (carrier G)\" \"inj_on \\<psi> (carrier H)\"\n   and phi_hom: \"\\<And>g1 g2. \\<lbrakk> g1 \\<in> carrier G; g2 \\<in> carrier G \\<rbrakk> \\<Longrightarrow> \\<phi> (g1 \\<otimes> g2) = (\\<phi> g1) \\<otimes>\\<^bsub>H\\<^esub> (\\<phi> g2)\"\n   and psi_hom: \"\\<And>h1 h2. \\<lbrakk> h1 \\<in> carrier H; h2 \\<in> carrier H \\<rbrakk> \\<Longrightarrow> \\<psi> (h1 \\<otimes>\\<^bsub>H\\<^esub> h2) = (\\<psi> h1) \\<otimes> (\\<psi> h2)\"\n   using phi psi_def unfolding iso_def bij_betw_def hom_def by auto\n\n  have phi_one: \"\\<phi> \\<one> = \\<one>\\<^bsub>H\\<^esub>\"\n  proof -\n    have \"(\\<phi> \\<one>) \\<otimes>\\<^bsub>H\\<^esub> \\<one>\\<^bsub>H\\<^esub> = (\\<phi> \\<one>) \\<otimes>\\<^bsub>H\\<^esub> (\\<phi> \\<one>)\"\n      by (metis assms(2) image_eqI monoid.r_one one_closed phi_hom r_one surj(1))\n    thus ?thesis\n      by (metis (no_types, opaque_lifting) Units_eq Units_one_closed assms(2) f_inv_into_f imageI\n          monoid.l_one monoid.one_closed phi_hom psi_def r_one surj)\n  qed\n\n  have \"carrier H \\<subseteq> Units H\"\n  proof\n    fix h assume h: \"h \\<in> carrier H\"\n    let ?inv_h = \"\\<phi> (inv (\\<psi> h))\"\n    have \"h \\<otimes>\\<^bsub>H\\<^esub> ?inv_h = \\<phi> (\\<psi> h) \\<otimes>\\<^bsub>H\\<^esub> ?inv_h\"\n      by (simp add: f_inv_into_f h psi_def surj(1))\n    also have \" ... = \\<phi> ((\\<psi> h) \\<otimes> inv (\\<psi> h))\"\n      by (metis h imageI inv_closed phi_hom surj(2))\n    also have \" ... = \\<phi> \\<one>\"\n      by (simp add: h inv_into_into psi_def surj(1))\n    finally have 1: \"h \\<otimes>\\<^bsub>H\\<^esub> ?inv_h = \\<one>\\<^bsub>H\\<^esub>\"\n      using phi_one by simp\n\n    have \"?inv_h \\<otimes>\\<^bsub>H\\<^esub> h = ?inv_h \\<otimes>\\<^bsub>H\\<^esub> \\<phi> (\\<psi> h)\"\n      by (simp add: f_inv_into_f h psi_def surj(1))\n    also have \" ... = \\<phi> (inv (\\<psi> h) \\<otimes> (\\<psi> h))\"\n      by (metis h imageI inv_closed phi_hom surj(2))\n    also have \" ... = \\<phi> \\<one>\"\n      by (simp add: h inv_into_into psi_def surj(1))\n    finally have 2: \"?inv_h \\<otimes>\\<^bsub>H\\<^esub> h = \\<one>\\<^bsub>H\\<^esub>\"\n      using phi_one by simp\n\n    thus \"h \\<in> Units H\" unfolding Units_def using 1 2 h surj by fastforce\n  qed\n  thus ?thesis unfolding group_def group_axioms_def using assms(2) by simp\nqed\n\ncorollary (in group) iso_imp_img_group: \\<^marker>\\<open>contributor \\<open>Paulo Em\u00edlio de Vilhena\\<close>\\<close>\n  assumes \"h \\<in> iso G H\"\n  shows \"group (H \\<lparr> one := h \\<one> \\<rparr>)\"\nproof -\n  let ?h_img = \"H \\<lparr> carrier := h ` (carrier G), one := h \\<one> \\<rparr>\"\n  have \"h \\<in> iso G ?h_img\"\n    using assms unfolding iso_def hom_def bij_betw_def by auto\n  hence \"G \\<cong> ?h_img\"\n    unfolding is_iso_def by auto\n  hence \"group ?h_img\"\n    using iso_imp_group[of ?h_img] hom_imp_img_monoid[of h H] assms unfolding iso_def by simp\n  moreover have \"carrier H = carrier ?h_img\"\n    using assms unfolding iso_def bij_betw_def by simp\n  hence \"H \\<lparr> one := h \\<one> \\<rparr> = ?h_img\"\n    by simp\n  ultimately show ?thesis by simp\nqed\n\nsubsubsection \\<open>HOL Light's concept of an isomorphism pair\\<close>\n\ndefinition group_isomorphisms\n  where\n \"group_isomorphisms G H f g \\<equiv>\n        f \\<in> hom G H \\<and> g \\<in> hom H G \\<and>\n        (\\<forall>x \\<in> carrier G. g(f x) = x) \\<and>\n        (\\<forall>y \\<in> carrier H. f(g y) = y)\"\n\nlemma group_isomorphisms_sym: \"group_isomorphisms G H f g \\<Longrightarrow> group_isomorphisms H G g f\"\n  by (auto simp: group_isomorphisms_def)\n\nlemma group_isomorphisms_imp_iso: \"group_isomorphisms G H f g \\<Longrightarrow> f \\<in> iso G H\"\nby (auto simp: iso_def inj_on_def image_def group_isomorphisms_def hom_def bij_betw_def Pi_iff, metis+)\n\nlemma (in group) iso_iff_group_isomorphisms:\n  \"f \\<in> iso G H \\<longleftrightarrow> (\\<exists>g. group_isomorphisms G H f g)\"\nproof safe\n  show \"\\<exists>g. group_isomorphisms G H f g\" if \"f \\<in> Group.iso G H\"\n    unfolding group_isomorphisms_def\n  proof (intro exI conjI)\n    let ?g = \"inv_into (carrier G) f\"\n    show \"\\<forall>x\\<in>carrier G. ?g (f x) = x\"\n      by (metis (no_types, lifting) Group.iso_def bij_betw_inv_into_left mem_Collect_eq that)\n    show \"\\<forall>y\\<in>carrier H. f (?g y) = y\"\n      by (metis (no_types, lifting) Group.iso_def bij_betw_inv_into_right mem_Collect_eq that)\n  qed (use Group.iso_def iso_set_sym that in \\<open>blast+\\<close>)\nnext\n  fix g\n  assume \"group_isomorphisms G H f g\"\n  then show \"f \\<in> Group.iso G H\"\n    by (auto simp: iso_def group_isomorphisms_def hom_in_carrier intro: bij_betw_byWitness)\nqed\n\n\nsubsubsection \\<open>Involving direct products\\<close>\n\nlemma DirProd_commute_iso_set:\n  shows \"(\\<lambda>(x,y). (y,x)) \\<in> iso (G \\<times>\\<times> H) (H \\<times>\\<times> G)\"\n  by (auto simp add: iso_def hom_def inj_on_def bij_betw_def)\n\ncorollary DirProd_commute_iso :\n\"(G \\<times>\\<times> H) \\<cong> (H \\<times>\\<times> G)\"\n  using DirProd_commute_iso_set unfolding is_iso_def by blast\n\nlemma DirProd_assoc_iso_set:\n  shows \"(\\<lambda>(x,y,z). (x,(y,z))) \\<in> iso (G \\<times>\\<times> H \\<times>\\<times> I) (G \\<times>\\<times> (H \\<times>\\<times> I))\"\nby (auto simp add: iso_def hom_def inj_on_def bij_betw_def)\n\nlemma (in group) DirProd_iso_set_trans:\n  assumes \"g \\<in> iso G G2\"\n    and \"h \\<in> iso H I\"\n  shows \"(\\<lambda>(x,y). (g x, h y)) \\<in> iso (G \\<times>\\<times> H) (G2 \\<times>\\<times> I)\"\nproof-\n  have \"(\\<lambda>(x,y). (g x, h y)) \\<in> hom (G \\<times>\\<times> H) (G2 \\<times>\\<times> I)\"\n    using assms unfolding iso_def hom_def by auto\n  moreover have \" inj_on (\\<lambda>(x,y). (g x, h y)) (carrier (G \\<times>\\<times> H))\"\n    using assms unfolding iso_def DirProd_def bij_betw_def inj_on_def by auto\n  moreover have \"(\\<lambda>(x, y). (g x, h y)) ` carrier (G \\<times>\\<times> H) = carrier (G2 \\<times>\\<times> I)\"\n    using assms unfolding iso_def bij_betw_def image_def DirProd_def by fastforce\n  ultimately show \"(\\<lambda>(x,y). (g x, h y)) \\<in> iso (G \\<times>\\<times> H) (G2 \\<times>\\<times> I)\"\n    unfolding iso_def bij_betw_def by auto\nqed\n\ncorollary (in group) DirProd_iso_trans :\n  assumes \"G \\<cong> G2\" and \"H \\<cong> I\"\n  shows \"G \\<times>\\<times> H \\<cong> G2 \\<times>\\<times> I\"\n  using DirProd_iso_set_trans assms unfolding is_iso_def by blast\n\nlemma hom_pairwise: \"f \\<in> hom G (DirProd H K) \\<longleftrightarrow> (fst \\<circ> f) \\<in> hom G H \\<and> (snd \\<circ> f) \\<in> hom G K\"\n  apply (auto simp: hom_def mult_DirProd' dest: Pi_mem)\n   apply (metis Product_Type.mem_Times_iff comp_eq_dest_lhs funcset_mem)\n  by (metis mult_DirProd prod.collapse)\n\nlemma hom_paired:\n   \"(\\<lambda>x. (f x,g x)) \\<in> hom G (DirProd H K) \\<longleftrightarrow> f \\<in> hom G H \\<and> g \\<in> hom G K\"\n  by (simp add: hom_pairwise o_def)\n\nlemma hom_paired2:\n  assumes \"group G\" \"group H\"\n  shows \"(\\<lambda>(x,y). (f x,g y)) \\<in> hom (DirProd G H) (DirProd G' H') \\<longleftrightarrow> f \\<in> hom G G' \\<and> g \\<in> hom H H'\"\n  using assms\n  by (fastforce simp: hom_def Pi_def dest!: group.is_monoid)\n\nlemma iso_paired2:\n  assumes \"group G\" \"group H\"\n  shows \"(\\<lambda>(x,y). (f x,g y)) \\<in> iso (DirProd G H) (DirProd G' H') \\<longleftrightarrow> f \\<in> iso G G' \\<and> g \\<in> iso H H'\"\n  using assms\n  by (fastforce simp add: iso_def inj_on_def bij_betw_def hom_paired2 image_paired_Times\n      times_eq_iff group_def monoid.carrier_not_empty)\n\nlemma hom_of_fst:\n  assumes \"group H\"\n  shows \"(f \\<circ> fst) \\<in> hom (DirProd G H) K \\<longleftrightarrow> f \\<in> hom G K\"\nproof -\n  interpret group H\n    by (rule assms)\n  show ?thesis\n    using one_closed by (auto simp: hom_def Pi_def)\nqed\n\nlemma hom_of_snd:\n  assumes \"group G\"\n  shows \"(f \\<circ> snd) \\<in> hom (DirProd G H) K \\<longleftrightarrow> f \\<in> hom H K\"\nproof -\n  interpret group G\n    by (rule assms)\n  show ?thesis\n    using one_closed by (auto simp: hom_def Pi_def)\nqed\n\n\nsubsection\\<open>The locale for a homomorphism between two groups\\<close>\n\ntext\\<open>Basis for homomorphism proofs: we assume two groups \\<^term>\\<open>G\\<close> and\n  \\<^term>\\<open>H\\<close>, with a homomorphism \\<^term>\\<open>h\\<close> between them\\<close>\nlocale group_hom = G?: group G + H?: group H for G (structure) and H (structure) +\n  fixes h\n  assumes homh [simp]: \"h \\<in> hom G H\"\n\ndeclare group_hom.homh [simp]\n\nlemma (in group_hom) hom_mult [simp]:\n  \"[| x \\<in> carrier G; y \\<in> carrier G |] ==> h (x \\<otimes>\\<^bsub>G\\<^esub> y) = h x \\<otimes>\\<^bsub>H\\<^esub> h y\"\nproof -\n  assume \"x \\<in> carrier G\" \"y \\<in> carrier G\"\n  with homh [unfolded hom_def] show ?thesis by simp\nqed\n\nlemma (in group_hom) hom_closed [simp]:\n  \"x \\<in> carrier G ==> h x \\<in> carrier H\"\nproof -\n  assume \"x \\<in> carrier G\"\n  with homh [unfolded hom_def] show ?thesis by auto\nqed\n\nlemma (in group_hom) one_closed: \"h \\<one> \\<in> carrier H\"\n  by simp\n\nlemma (in group_hom) hom_one [simp]: \"h \\<one> = \\<one>\\<^bsub>H\\<^esub>\"\nproof -\n  have \"h \\<one> \\<otimes>\\<^bsub>H\\<^esub> \\<one>\\<^bsub>H\\<^esub> = h \\<one> \\<otimes>\\<^bsub>H\\<^esub> h \\<one>\"\n    by (simp add: hom_mult [symmetric] del: hom_mult)\n  then show ?thesis\n    by (metis H.Units_eq H.Units_l_cancel H.one_closed local.one_closed)\nqed\n\nlemma hom_one:\n  assumes \"h \\<in> hom G H\" \"group G\" \"group H\"\n  shows \"h (one G) = one H\"\n  apply (rule group_hom.hom_one)\n  by (simp add: assms group_hom_axioms_def group_hom_def)\n\nlemma hom_mult:\n  \"\\<lbrakk>h \\<in> hom G H; x \\<in> carrier G; y \\<in> carrier G\\<rbrakk> \\<Longrightarrow> h (x \\<otimes>\\<^bsub>G\\<^esub> y) = h x \\<otimes>\\<^bsub>H\\<^esub> h y\"\n  by (auto simp: hom_def)\n\nlemma (in group_hom) inv_closed [simp]:\n  \"x \\<in> carrier G ==> h (inv x) \\<in> carrier H\"\n  by simp\n\nlemma (in group_hom) hom_inv [simp]:\n  assumes \"x \\<in> carrier G\" shows \"h (inv x) = inv\\<^bsub>H\\<^esub> (h x)\"\nproof -\n  have \"h x \\<otimes>\\<^bsub>H\\<^esub> h (inv x) = h x \\<otimes>\\<^bsub>H\\<^esub> inv\\<^bsub>H\\<^esub> (h x)\" \n    using assms by (simp flip: hom_mult)\n  with assms show ?thesis by (simp del: H.r_inv H.Units_r_inv)\nqed\n\nlemma (in group) int_pow_is_hom: \\<^marker>\\<open>contributor \\<open>Joachim Breitner\\<close>\\<close>\n  \"x \\<in> carrier G \\<Longrightarrow> (([^]) x) \\<in> hom \\<lparr> carrier = UNIV, mult = (+), one = 0::int \\<rparr> G \"\n  unfolding hom_def by (simp add: int_pow_mult)\n\nlemma (in group_hom) img_is_subgroup: \"subgroup (h ` (carrier G)) H\" \\<^marker>\\<open>contributor \\<open>Paulo Em\u00edlio de Vilhena\\<close>\\<close>\n  apply (rule subgroupI)\n  apply (auto simp add: image_subsetI)\n  apply (metis G.inv_closed hom_inv image_iff)\n  by (metis G.monoid_axioms hom_mult image_eqI monoid.m_closed)\n\nlemma (in group_hom) subgroup_img_is_subgroup: \\<^marker>\\<open>contributor \\<open>Paulo Em\u00edlio de Vilhena\\<close>\\<close>\n  assumes \"subgroup I G\"\n  shows \"subgroup (h ` I) H\"\nproof -\n  have \"h \\<in> hom (G \\<lparr> carrier := I \\<rparr>) H\"\n    using G.subgroupE[OF assms] subgroup.mem_carrier[OF assms] homh\n    unfolding hom_def by auto\n  hence \"group_hom (G \\<lparr> carrier := I \\<rparr>) H h\"\n    using subgroup.subgroup_is_group[OF assms G.is_group] is_group\n    unfolding group_hom_def group_hom_axioms_def by simp\n  thus ?thesis\n    using group_hom.img_is_subgroup[of \"G \\<lparr> carrier := I \\<rparr>\" H h] by simp\nqed\n\nlemma (in group_hom) induced_group_hom: \\<^marker>\\<open>contributor \\<open>Paulo Em\u00edlio de Vilhena\\<close>\\<close>\n  assumes \"subgroup I G\"\n  shows \"group_hom (G \\<lparr> carrier := I \\<rparr>) (H \\<lparr> carrier := h ` I \\<rparr>) h\"\nproof -\n  have \"h \\<in> hom (G \\<lparr> carrier := I \\<rparr>) (H \\<lparr> carrier := h ` I \\<rparr>)\"\n    using homh subgroup.mem_carrier[OF assms] unfolding hom_def by auto\n  thus ?thesis\n    unfolding group_hom_def group_hom_axioms_def\n    using subgroup.subgroup_is_group[OF assms G.is_group]\n          subgroup.subgroup_is_group[OF subgroup_img_is_subgroup[OF assms] is_group] by simp\nqed\n\nlemma (in group) canonical_inj_is_hom: \\<^marker>\\<open>contributor \\<open>Paulo Em\u00edlio de Vilhena\\<close>\\<close>\n  assumes \"subgroup H G\"\n  shows \"group_hom (G \\<lparr> carrier := H \\<rparr>) G id\"\n  unfolding group_hom_def group_hom_axioms_def hom_def\n  using subgroup.subgroup_is_group[OF assms is_group]\n        is_group subgroup.subset[OF assms] by auto\n\nlemma (in group_hom) hom_nat_pow: \\<^marker>\\<open>contributor \\<open>Paulo Em\u00edlio de Vilhena\\<close>\\<close>\n  \"x \\<in> carrier G \\<Longrightarrow> h (x [^] (n :: nat)) = (h x) [^]\\<^bsub>H\\<^esub> n\"\n  by (induction n) auto\n\nlemma (in group_hom) hom_int_pow: \\<^marker>\\<open>contributor \\<open>Paulo Em\u00edlio de Vilhena\\<close>\\<close>\n  \"x \\<in> carrier G \\<Longrightarrow> h (x [^] (n :: int)) = (h x) [^]\\<^bsub>H\\<^esub> n\"\n  using hom_nat_pow by (simp add: int_pow_def2)\n\nlemma hom_nat_pow:\n  \"\\<lbrakk>h \\<in> hom G H; x \\<in> carrier G; group G; group H\\<rbrakk> \\<Longrightarrow> h (x [^]\\<^bsub>G\\<^esub> (n :: nat)) = (h x) [^]\\<^bsub>H\\<^esub> n\"\n  by (simp add: group_hom.hom_nat_pow group_hom_axioms_def group_hom_def)\n\nlemma hom_int_pow:\n  \"\\<lbrakk>h \\<in> hom G H; x \\<in> carrier G; group G; group H\\<rbrakk> \\<Longrightarrow> h (x [^]\\<^bsub>G\\<^esub> (n :: int)) = (h x) [^]\\<^bsub>H\\<^esub> n\"\n  by (simp add: group_hom.hom_int_pow group_hom_axioms.intro group_hom_def)\n\nsubsection \\<open>Commutative Structures\\<close>\n\ntext \\<open>\n  Naming convention: multiplicative structures that are commutative\n  are called \\emph{commutative}, additive structures are called\n  \\emph{Abelian}.\n\\<close>\n\nlocale comm_monoid = monoid +\n  assumes m_comm: \"\\<lbrakk>x \\<in> carrier G; y \\<in> carrier G\\<rbrakk> \\<Longrightarrow> x \\<otimes> y = y \\<otimes> x\"\n\nlemma (in comm_monoid) m_lcomm:\n  \"\\<lbrakk>x \\<in> carrier G; y \\<in> carrier G; z \\<in> carrier G\\<rbrakk> \\<Longrightarrow>\n   x \\<otimes> (y \\<otimes> z) = y \\<otimes> (x \\<otimes> z)\"\nproof -\n  assume xyz: \"x \\<in> carrier G\"  \"y \\<in> carrier G\"  \"z \\<in> carrier G\"\n  from xyz have \"x \\<otimes> (y \\<otimes> z) = (x \\<otimes> y) \\<otimes> z\" by (simp add: m_assoc)\n  also from xyz have \"... = (y \\<otimes> x) \\<otimes> z\" by (simp add: m_comm)\n  also from xyz have \"... = y \\<otimes> (x \\<otimes> z)\" by (simp add: m_assoc)\n  finally show ?thesis .\nqed\n\nlemmas (in comm_monoid) m_ac = m_assoc m_comm m_lcomm\n\nlemma comm_monoidI:\n  fixes G (structure)\n  assumes m_closed:\n      \"!!x y. [| x \\<in> carrier G; y \\<in> carrier G |] ==> x \\<otimes> y \\<in> carrier G\"\n    and one_closed: \"\\<one> \\<in> carrier G\"\n    and m_assoc:\n      \"!!x y z. [| x \\<in> carrier G; y \\<in> carrier G; z \\<in> carrier G |] ==>\n      (x \\<otimes> y) \\<otimes> z = x \\<otimes> (y \\<otimes> z)\"\n    and l_one: \"!!x. x \\<in> carrier G ==> \\<one> \\<otimes> x = x\"\n    and m_comm:\n      \"!!x y. [| x \\<in> carrier G; y \\<in> carrier G |] ==> x \\<otimes> y = y \\<otimes> x\"\n  shows \"comm_monoid G\"\n  using l_one\n    by (auto intro!: comm_monoid.intro comm_monoid_axioms.intro monoid.intro\n             intro: assms simp: m_closed one_closed m_comm)\n\nlemma (in monoid) monoid_comm_monoidI:\n  assumes m_comm:\n      \"!!x y. [| x \\<in> carrier G; y \\<in> carrier G |] ==> x \\<otimes> y = y \\<otimes> x\"\n  shows \"comm_monoid G\"\n  by (rule comm_monoidI) (auto intro: m_assoc m_comm)\n\nlemma (in comm_monoid) submonoid_is_comm_monoid :\n  assumes \"submonoid H G\"\n  shows \"comm_monoid (G\\<lparr>carrier := H\\<rparr>)\"\nproof (intro monoid.monoid_comm_monoidI)\n  show \"monoid (G\\<lparr>carrier := H\\<rparr>)\"\n    using submonoid.submonoid_is_monoid assms comm_monoid_axioms comm_monoid_def by blast\n  show \"\\<And>x y. x \\<in> carrier (G\\<lparr>carrier := H\\<rparr>) \\<Longrightarrow> y \\<in> carrier (G\\<lparr>carrier := H\\<rparr>)\n        \\<Longrightarrow> x \\<otimes>\\<^bsub>G\\<lparr>carrier := H\\<rparr>\\<^esub> y = y \\<otimes>\\<^bsub>G\\<lparr>carrier := H\\<rparr>\\<^esub> x\" \n    by simp (meson assms m_comm submonoid.mem_carrier)\nqed\n\nlocale comm_group = comm_monoid + group\n\nlemma (in group) group_comm_groupI:\n  assumes m_comm: \"!!x y. [| x \\<in> carrier G; y \\<in> carrier G |] ==> x \\<otimes> y = y \\<otimes> x\"\n  shows \"comm_group G\"\n  by standard (simp_all add: m_comm)\n\nlemma comm_groupI:\n  fixes G (structure)\n  assumes m_closed:\n      \"!!x y. [| x \\<in> carrier G; y \\<in> carrier G |] ==> x \\<otimes> y \\<in> carrier G\"\n    and one_closed: \"\\<one> \\<in> carrier G\"\n    and m_assoc:\n      \"!!x y z. [| x \\<in> carrier G; y \\<in> carrier G; z \\<in> carrier G |] ==>\n      (x \\<otimes> y) \\<otimes> z = x \\<otimes> (y \\<otimes> z)\"\n    and m_comm:\n      \"!!x y. [| x \\<in> carrier G; y \\<in> carrier G |] ==> x \\<otimes> y = y \\<otimes> x\"\n    and l_one: \"!!x. x \\<in> carrier G ==> \\<one> \\<otimes> x = x\"\n    and l_inv_ex: \"!!x. x \\<in> carrier G ==> \\<exists>y \\<in> carrier G. y \\<otimes> x = \\<one>\"\n  shows \"comm_group G\"\n  by (fast intro: group.group_comm_groupI groupI assms)\n\nlemma comm_groupE:\n  fixes G (structure)\n  assumes \"comm_group G\"\n  shows \"\\<And>x y. \\<lbrakk> x \\<in> carrier G; y \\<in> carrier G \\<rbrakk> \\<Longrightarrow> x \\<otimes> y \\<in> carrier G\"\n    and \"\\<one> \\<in> carrier G\"\n    and \"\\<And>x y z. \\<lbrakk> x \\<in> carrier G; y \\<in> carrier G; z \\<in> carrier G \\<rbrakk> \\<Longrightarrow> (x \\<otimes> y) \\<otimes> z = x \\<otimes> (y \\<otimes> z)\"\n    and \"\\<And>x y. \\<lbrakk> x \\<in> carrier G; y \\<in> carrier G \\<rbrakk> \\<Longrightarrow> x \\<otimes> y = y \\<otimes> x\"\n    and \"\\<And>x. x \\<in> carrier G \\<Longrightarrow> \\<one> \\<otimes> x = x\"\n    and \"\\<And>x. x \\<in> carrier G \\<Longrightarrow> \\<exists>y \\<in> carrier G. y \\<otimes> x = \\<one>\"\n  apply (simp_all add: group.axioms assms comm_group.axioms comm_monoid.m_comm comm_monoid.m_ac(1))\n  by (simp_all add: Group.group.axioms(1) assms comm_group.axioms(2) monoid.m_closed group.r_inv_ex)\n\nlemma (in comm_group) inv_mult:\n  \"[| x \\<in> carrier G; y \\<in> carrier G |] ==> inv (x \\<otimes> y) = inv x \\<otimes> inv y\"\n  by (simp add: m_ac inv_mult_group)\n\nlemma (in comm_monoid) nat_pow_distrib:\n  fixes n::nat\n  assumes \"x \\<in> carrier G\" \"y \\<in> carrier G\"\n  shows \"(x \\<otimes> y) [^] n = x [^] n \\<otimes> y [^] n\"\n  by (simp add: assms pow_mult_distrib m_comm)\n\nlemma (in comm_group) int_pow_distrib:\n  assumes \"x \\<in> carrier G\" \"y \\<in> carrier G\"\n  shows \"(x \\<otimes> y) [^] (i::int) = x [^] i \\<otimes> y [^] i\"\n  by (simp add: assms int_pow_mult_distrib m_comm)\n\nlemma (in comm_monoid) hom_imp_img_comm_monoid: \\<^marker>\\<open>contributor \\<open>Paulo Em\u00edlio de Vilhena\\<close>\\<close>\n  assumes \"h \\<in> hom G H\"\n  shows \"comm_monoid (H \\<lparr> carrier := h ` (carrier G), one := h \\<one>\\<^bsub>G\\<^esub> \\<rparr>)\" (is \"comm_monoid ?h_img\")\nproof (rule monoid.monoid_comm_monoidI)\n  show \"monoid ?h_img\"\n    using hom_imp_img_monoid[OF assms] .\nnext\n  fix x y assume \"x \\<in> carrier ?h_img\" \"y \\<in> carrier ?h_img\"\n  then obtain g1 g2\n    where g1: \"g1 \\<in> carrier G\" \"x = h g1\"\n      and g2: \"g2 \\<in> carrier G\" \"y = h g2\"\n    by auto\n  have \"x \\<otimes>\\<^bsub>(?h_img)\\<^esub> y = h (g1 \\<otimes> g2)\"\n    using g1 g2 assms unfolding hom_def by auto\n  also have \" ... = h (g2 \\<otimes> g1)\"\n    using m_comm[OF g1(1) g2(1)] by simp\n  also have \" ... = y \\<otimes>\\<^bsub>(?h_img)\\<^esub> x\"\n    using g1 g2 assms unfolding hom_def by auto\n  finally show \"x \\<otimes>\\<^bsub>(?h_img)\\<^esub> y = y \\<otimes>\\<^bsub>(?h_img)\\<^esub> x\" .\nqed\n\nlemma (in comm_group) hom_group_mult:\n  assumes \"f \\<in> hom H G\" \"g \\<in> hom H G\"\n shows \"(\\<lambda>x. f x \\<otimes>\\<^bsub>G\\<^esub> g x) \\<in> hom H G\"\n    using assms by (auto simp: hom_def Pi_def m_ac)\n\nlemma (in comm_group) hom_imp_img_comm_group: \\<^marker>\\<open>contributor \\<open>Paulo Em\u00edlio de Vilhena\\<close>\\<close>\n  assumes \"h \\<in> hom G H\"\n  shows \"comm_group (H \\<lparr> carrier := h ` (carrier G), one := h \\<one>\\<^bsub>G\\<^esub> \\<rparr>)\"\n  unfolding comm_group_def\n  using hom_imp_img_group[OF assms] hom_imp_img_comm_monoid[OF assms] by simp\n\nlemma (in comm_group) iso_imp_img_comm_group: \\<^marker>\\<open>contributor \\<open>Paulo Em\u00edlio de Vilhena\\<close>\\<close>\n  assumes \"h \\<in> iso G H\"\n  shows \"comm_group (H \\<lparr> one := h \\<one>\\<^bsub>G\\<^esub> \\<rparr>)\"\nproof -\n  let ?h_img = \"H \\<lparr> carrier := h ` (carrier G), one := h \\<one> \\<rparr>\"\n  have \"comm_group ?h_img\"\n    using hom_imp_img_comm_group[of h H] assms unfolding iso_def by auto\n  moreover have \"carrier H = carrier ?h_img\"\n    using assms unfolding iso_def bij_betw_def by simp\n  hence \"H \\<lparr> one := h \\<one> \\<rparr> = ?h_img\"\n    by simp\n  ultimately show ?thesis by simp\nqed\n\nlemma (in comm_group) iso_imp_comm_group: \\<^marker>\\<open>contributor \\<open>Paulo Em\u00edlio de Vilhena\\<close>\\<close>\n  assumes \"G \\<cong> H\" \"monoid H\"\n  shows \"comm_group H\"\nproof -\n  obtain h where h: \"h \\<in> iso G H\"\n    using assms(1) unfolding is_iso_def by auto\n  hence comm_gr: \"comm_group (H \\<lparr> one := h \\<one> \\<rparr>)\"\n    using iso_imp_img_comm_group[of h H] by simp\n  hence \"\\<And>x. x \\<in> carrier H \\<Longrightarrow> h \\<one> \\<otimes>\\<^bsub>H\\<^esub> x = x\"\n    using monoid.l_one[of \"H \\<lparr> one := h \\<one> \\<rparr>\"] unfolding comm_group_def comm_monoid_def by simp\n  moreover have \"h \\<one> \\<in> carrier H\"\n    using h one_closed unfolding iso_def hom_def by auto\n  ultimately have \"h \\<one> = \\<one>\\<^bsub>H\\<^esub>\"\n    using monoid.one_unique[OF assms(2), of \"h \\<one>\"] by simp\n  hence \"H = H \\<lparr> one := h \\<one> \\<rparr>\"\n    by simp\n  thus ?thesis\n    using comm_gr by simp\nqed\n\n(*A subgroup of a subgroup is a subgroup of the group*)\nlemma (in group) incl_subgroup:\n  assumes \"subgroup J G\"\n    and \"subgroup I (G\\<lparr>carrier:=J\\<rparr>)\"\n  shows \"subgroup I G\" unfolding subgroup_def\nproof\n  have H1: \"I \\<subseteq> carrier (G\\<lparr>carrier:=J\\<rparr>)\" using assms(2) subgroup.subset by blast\n  also have H2: \"...\\<subseteq>J\" by simp\n  also  have \"...\\<subseteq>(carrier G)\"  by (simp add: assms(1) subgroup.subset)\n  finally have H: \"I \\<subseteq> carrier G\" by simp\n  have \"(\\<And>x y. \\<lbrakk>x \\<in> I ; y \\<in> I\\<rbrakk> \\<Longrightarrow> x \\<otimes> y \\<in> I)\" using assms(2) by (auto simp add: subgroup_def)\n  thus  \"I \\<subseteq> carrier G \\<and> (\\<forall>x y. x \\<in> I \\<longrightarrow> y \\<in> I \\<longrightarrow> x \\<otimes> y \\<in> I)\"  using H by blast\n  have K: \"\\<one> \\<in> I\" using assms(2) by (auto simp add: subgroup_def)\n  have \"(\\<And>x. x \\<in> I \\<Longrightarrow> inv x \\<in> I)\" using assms  subgroup.m_inv_closed H\n    by (metis H1 H2 m_inv_consistent subsetCE)\n  thus \"\\<one> \\<in> I \\<and> (\\<forall>x. x \\<in> I \\<longrightarrow> inv x \\<in> I)\" using K by blast\nqed\n\n(*A subgroup included in another subgroup is a subgroup of the subgroup*)\nlemma (in group) subgroup_incl:\n  assumes \"subgroup I G\" and \"subgroup J G\" and \"I \\<subseteq> J\"\n  shows \"subgroup I (G \\<lparr> carrier := J \\<rparr>)\"\n  using group.group_incl_imp_subgroup[of \"G \\<lparr> carrier := J \\<rparr>\" I]\n        assms(1-2)[THEN subgroup.subgroup_is_group[OF _ group_axioms]] assms(3) by auto\n\n\nsubsection \\<open>The Lattice of Subgroups of a Group\\<close>\n\ntext_raw \\<open>\\label{sec:subgroup-lattice}\\<close>\n\ntheorem (in group) subgroups_partial_order:\n  \"partial_order \\<lparr>carrier = {H. subgroup H G}, eq = (=), le = (\\<subseteq>)\\<rparr>\"\n  by standard simp_all\n\nlemma (in group) subgroup_self:\n  \"subgroup (carrier G) G\"\n  by (rule subgroupI) auto\n\nlemma (in group) subgroup_imp_group:\n  \"subgroup H G ==> group (G\\<lparr>carrier := H\\<rparr>)\"\n  by (erule subgroup.subgroup_is_group) (rule group_axioms)\n\nlemma (in group) subgroup_mult_equality:\n  \"\\<lbrakk> subgroup H G; h1 \\<in> H; h2 \\<in> H \\<rbrakk> \\<Longrightarrow>  h1 \\<otimes>\\<^bsub>G \\<lparr> carrier := H \\<rparr>\\<^esub> h2 = h1 \\<otimes> h2\"\n  unfolding subgroup_def by simp\n\ntheorem (in group) subgroups_Inter:\n  assumes subgr: \"(\\<And>H. H \\<in> A \\<Longrightarrow> subgroup H G)\"\n    and not_empty: \"A \\<noteq> {}\"\n  shows \"subgroup (\\<Inter>A) G\"\nproof (rule subgroupI)\n  from subgr [THEN subgroup.subset] and not_empty\n  show \"\\<Inter>A \\<subseteq> carrier G\" by blast\nnext\n  from subgr [THEN subgroup.one_closed]\n  show \"\\<Inter>A \\<noteq> {}\" by blast\nnext\n  fix x assume \"x \\<in> \\<Inter>A\"\n  with subgr [THEN subgroup.m_inv_closed]\n  show \"inv x \\<in> \\<Inter>A\" by blast\nnext\n  fix x y assume \"x \\<in> \\<Inter>A\" \"y \\<in> \\<Inter>A\"\n  with subgr [THEN subgroup.m_closed]\n  show \"x \\<otimes> y \\<in> \\<Inter>A\" by blast\nqed\n\nlemma (in group) subgroups_Inter_pair :\n  assumes  \"subgroup I G\"\n    and  \"subgroup J G\"\n  shows \"subgroup (I\\<inter>J) G\" using subgroups_Inter[ where ?A = \"{I,J}\"] assms by auto\n\ntheorem (in group) subgroups_complete_lattice:\n  \"complete_lattice \\<lparr>carrier = {H. subgroup H G}, eq = (=), le = (\\<subseteq>)\\<rparr>\"\n    (is \"complete_lattice ?L\")\nproof (rule partial_order.complete_lattice_criterion1)\n  show \"partial_order ?L\" by (rule subgroups_partial_order)\nnext\n  have \"greatest ?L (carrier G) (carrier ?L)\"\n    by (unfold greatest_def) (simp add: subgroup.subset subgroup_self)\n  then show \"\\<exists>G. greatest ?L G (carrier ?L)\" ..\nnext\n  fix A\n  assume L: \"A \\<subseteq> carrier ?L\" and non_empty: \"A \\<noteq> {}\"\n  then have Int_subgroup: \"subgroup (\\<Inter>A) G\"\n    by (fastforce intro: subgroups_Inter)\n  have \"greatest ?L (\\<Inter>A) (Lower ?L A)\" (is \"greatest _ ?Int _\")\n  proof (rule greatest_LowerI)\n    fix H\n    assume H: \"H \\<in> A\"\n    with L have subgroupH: \"subgroup H G\" by auto\n    from subgroupH have groupH: \"group (G \\<lparr>carrier := H\\<rparr>)\" (is \"group ?H\")\n      by (rule subgroup_imp_group)\n    from groupH have monoidH: \"monoid ?H\"\n      by (rule group.is_monoid)\n    from H have Int_subset: \"?Int \\<subseteq> H\" by fastforce\n    then show \"le ?L ?Int H\" by simp\n  next\n    fix H\n    assume H: \"H \\<in> Lower ?L A\"\n    with L Int_subgroup show \"le ?L H ?Int\"\n      by (fastforce simp: Lower_def intro: Inter_greatest)\n  next\n    show \"A \\<subseteq> carrier ?L\" by (rule L)\n  next\n    show \"?Int \\<in> carrier ?L\" by simp (rule Int_subgroup)\n  qed\n  then show \"\\<exists>I. greatest ?L I (Lower ?L A)\" ..\nqed\n\nsubsection\\<open>The units in any monoid give rise to a group\\<close>\n\ntext \\<open>Thanks to Jeremy Avigad. The file Residues.thy provides some infrastructure to use\n  facts about the unit group within the ring locale.\n\\<close>\n\ndefinition units_of :: \"('a, 'b) monoid_scheme \\<Rightarrow> 'a monoid\"\n  where \"units_of G =\n    \\<lparr>carrier = Units G, Group.monoid.mult = Group.monoid.mult G, one  = one G\\<rparr>\"\n\nlemma (in monoid) units_group: \"group (units_of G)\"\nproof -\n  have \"\\<And>x y z. \\<lbrakk>x \\<in> Units G; y \\<in> Units G; z \\<in> Units G\\<rbrakk> \\<Longrightarrow> x \\<otimes> y \\<otimes> z = x \\<otimes> (y \\<otimes> z)\"\n    by (simp add: Units_closed m_assoc)\n  moreover have \"\\<And>x. x \\<in> Units G \\<Longrightarrow> \\<exists>y\\<in>Units G. y \\<otimes> x = \\<one>\"\n    using Units_l_inv by blast\n  ultimately show ?thesis\n    unfolding units_of_def\n    by (force intro!: groupI)\nqed\n\nlemma (in comm_monoid) units_comm_group: \"comm_group (units_of G)\"\nproof -\n  have \"\\<And>x y. \\<lbrakk>x \\<in> carrier (units_of G); y \\<in> carrier (units_of G)\\<rbrakk>\n              \\<Longrightarrow> x \\<otimes>\\<^bsub>units_of G\\<^esub> y = y \\<otimes>\\<^bsub>units_of G\\<^esub> x\"\n    by (simp add: Units_closed m_comm units_of_def)\n  then show ?thesis\n    by (rule group.group_comm_groupI [OF units_group]) auto\nqed\n\nlemma units_of_carrier: \"carrier (units_of G) = Units G\"\n  by (auto simp: units_of_def)\n\nlemma units_of_mult: \"mult (units_of G) = mult G\"\n  by (auto simp: units_of_def)\n\nlemma units_of_one: \"one (units_of G) = one G\"\n  by (auto simp: units_of_def)\n\nlemma (in monoid) units_of_inv:\n  assumes \"x \\<in> Units G\"\n  shows \"m_inv (units_of G) x = m_inv G x\"\n  by (simp add: assms group.inv_equality units_group units_of_carrier units_of_mult units_of_one)\n\nlemma units_of_units [simp] : \"Units (units_of G) = Units G\"\n  unfolding units_of_def Units_def by force\n\nlemma (in group) surj_const_mult: \"a \\<in> carrier G \\<Longrightarrow> (\\<lambda>x. a \\<otimes> x) ` carrier G = carrier G\"\n  apply (auto simp add: image_def)\n  by (metis inv_closed inv_solve_left m_closed)\n\nlemma (in group) l_cancel_one [simp]: \"x \\<in> carrier G \\<Longrightarrow> a \\<in> carrier G \\<Longrightarrow> x \\<otimes> a = x \\<longleftrightarrow> a = one G\"\n  by (metis Units_eq Units_l_cancel monoid.r_one monoid_axioms one_closed)\n\nlemma (in group) r_cancel_one [simp]: \"x \\<in> carrier G \\<Longrightarrow> a \\<in> carrier G \\<Longrightarrow> a \\<otimes> x = x \\<longleftrightarrow> a = one G\"\n  by (metis monoid.l_one monoid_axioms one_closed right_cancel)\n\nlemma (in group) l_cancel_one' [simp]: \"x \\<in> carrier G \\<Longrightarrow> a \\<in> carrier G \\<Longrightarrow> x = x \\<otimes> a \\<longleftrightarrow> a = one G\"\n  using l_cancel_one by fastforce\n\nlemma (in group) r_cancel_one' [simp]: \"x \\<in> carrier G \\<Longrightarrow> a \\<in> carrier G \\<Longrightarrow> x = a \\<otimes> x \\<longleftrightarrow> a = one G\"\n  using r_cancel_one by fastforce\n\ndeclare pow_nat [simp] (*causes looping if added above, especially with int_pow_def2*)\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/Algebra/Group.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8670357735451835, "lm_q2_score": 0.849971181358171, "lm_q1q2_score": 0.7369554207199952}}
{"text": "(*  Title:      RealPower/RatPower.thy\n    Authors:    Jacques D. Fleuriot\n                University of Edinburgh, 2021          \n*)\n\ntheory RatPower\nimports HOL.NthRoot\nbegin\n\nsection \\<open>Rational Exponents\\<close>\n\ntext\\<open>A few lemmas about nth-root.\\<close>\n\nlemma real_root_mult_exp_cancel:\n  \"\\<lbrakk> 0 < x; 0 < m; 0 < n \\<rbrakk> \n   \\<Longrightarrow> root (m * n) (x ^ (k * n)) = root m (x ^ k)\"\n  by (simp add: power_mult real_root_pos_unique) \n\nlemma real_root_mult_exp_cancel1:\n  \"\\<lbrakk> 0 < x; 0 < n \\<rbrakk> \\<Longrightarrow> root n (x ^ (k * n)) = x ^ k\"\nby (auto dest: real_root_mult_exp_cancel [of _ 1])\n\nlemma real_root_mult_exp_cancel2:\n  \"\\<lbrakk> 0 < x; 0 < m; 0 < n \\<rbrakk> \n   \\<Longrightarrow> root (n * m) (x ^ (n * k)) = root m (x ^ k)\"\nby (simp add: mult.commute real_root_mult_exp_cancel) \n\nlemma real_root_mult_exp_cancel3:\n  \"\\<lbrakk> 0 < x; 0 < n \\<rbrakk> \\<Longrightarrow> root n (x ^ (n * k)) = x ^ k\" \nby (auto dest: real_root_mult_exp_cancel2 [of _ 1])\n\ntext\\<open>Definition of rational exponents,\\<close>\n\ndefinition\n  powrat  :: \"[real,rat] => real\"     (infixr \"pow\\<^sub>\\<rat>\" 80) where\n  \"x pow\\<^sub>\\<rat> r = (if r > 0 \n               then root (nat (snd(quotient_of r))) \n                          (x ^ (nat (fst(quotient_of r))))\n               else root (nat (snd(quotient_of r))) \n                          (1/x ^ (nat (- fst(quotient_of r)))))\"\n\n(* Why isn't this a default simp rule?  *)\ndeclare quotient_of_denom_pos' [simp]\n\nlemma powrat_one_eq_one [simp]: \"1 pow\\<^sub>\\<rat> a = 1\"\n  by (simp add: powrat_def)\n\nlemma powrat_zero_eq_one [simp]: \"x pow\\<^sub>\\<rat> 0 = 1\"\nby (simp add: powrat_def)\n\nlemma powrat_one [simp]: \"x pow\\<^sub>\\<rat> 1 = x\"\nby (simp add: powrat_def)\n\nlemma powrat_mult_base: \n      \"(x * y) pow\\<^sub>\\<rat> r = (x pow\\<^sub>\\<rat> r) * (y pow\\<^sub>\\<rat> r)\"\nproof (cases r)\n  case (Fract a b)\n  then show ?thesis \n    using powrat_def quotient_of_Fract real_root_mult [symmetric] \n          power_mult_distrib by fastforce\nqed\n\nlemma powrat_divide:\n     \"(x / y) pow\\<^sub>\\<rat> r = (x pow\\<^sub>\\<rat> r)/(y pow\\<^sub>\\<rat> r)\"\nproof (cases r)\n  case (Fract a b)\n  then show ?thesis \n    using powrat_def quotient_of_Fract real_root_divide [symmetric] \n          power_divide by fastforce\nqed\n\nlemma powrat_zero_base [simp]: \n  assumes \"r \\<noteq> 0\" shows \"0 pow\\<^sub>\\<rat> r = 0\"\nproof (cases r)\n  case (Fract a b)\n  then show ?thesis\n  proof (cases \"a > 0\")\n    case True\n    then show ?thesis \n      using Fract powrat_def quotient_of_Fract zero_less_Fract_iff \n      by simp\n  next\n    case False\n    then  have \"a \\<noteq> 0\"\n    using Fract(1) assms rat_number_collapse(1) by blast \n  then \n    show ?thesis\n      using Fract powrat_def quotient_of_Fract zero_less_Fract_iff \n      by auto\n  qed\nqed\n\n\n(* That's the one we want *)\nlemma powrat_inverse:\n      \"(inverse y) pow\\<^sub>\\<rat> r = inverse(y pow\\<^sub>\\<rat> r)\"\nproof (cases \"r=0\")\n  case True \n  then show ?thesis by simp\nnext\n  case False\n  then show ?thesis\n    by (simp add: inverse_eq_divide powrat_divide)  \nqed\n\nlemma powrat_minus:\n   \"x pow\\<^sub>\\<rat> (-r) = inverse (x pow\\<^sub>\\<rat> r)\"\nproof (cases r)\n  case (Fract a b)\n  then show ?thesis \n    by (auto simp add: powrat_def divide_inverse real_root_inverse \n                       quotient_of_Fract zero_less_Fract_iff)\nqed\n\nlemma powrat_gt_zero: \n  assumes \"x > 0\" shows \"x pow\\<^sub>\\<rat> r > 0\"\nproof (cases r)\n  case (Fract a b)\n  then show ?thesis\n    by (simp add: assms powrat_def) \nqed\n\nlemma powrat_not_zero: \n  assumes \"x \\<noteq> 0\" shows \"x pow\\<^sub>\\<rat> r \\<noteq> 0\"\nproof (cases r)\n  case (Fract a b)\n  then show ?thesis\n    by (simp add: assms powrat_def) \nqed\n\n(* Not in GCD.thy *)\nlemma gcd_add_mult_commute: \"gcd (m::'a::semiring_gcd) (n + k * m) = gcd m n\"\n  by (metis add.commute gcd_add_mult)\n\nlemma coprime_add_mult_iff1 [simp]: \n     \"coprime (n + k * m) (m::'a::semiring_gcd) = coprime n m\"\n  by (simp add: coprime_iff_gcd_eq_1 gcd.commute gcd_add_mult_commute)\n\nlemma coprime_add_mult_iff2 [simp]: \n     \"coprime (k * m + n) (m::'a::semiring_gcd) = coprime n m\"\n  by (simp add: add.commute)\n\n(* Not proved before?? *)\nlemma gcd_mult_div_cancel_left1 [simp]: \n  \"gcd a b * (a div gcd a b)  = (a::'a::semiring_gcd)\"\n  by simp\n\nlemma gcd_mult_div_cancel_left2 [simp]: \n  \"gcd b a * (a div gcd b a)  = (a::'a::semiring_gcd)\"\n  by simp\n\nlemma gcd_mult_div_cancel_right1 [simp]: \n  \"(a div gcd a b) * gcd a b  = (a::'a::semiring_gcd)\"\n  by simp\n\nlemma gcd_mult_div_cancel_right2 [simp]:\n  \"(a div gcd b a) * gcd b a = (a::'a::semiring_gcd)\"\n  by simp\n(* END: Not in GCD.thy *)\n\nlemma real_root_normalize_cancel:\n  assumes \"0 < x\" and \"a \\<noteq> 0\" and \"b > 0\"\n  shows \"root (nat(snd(Rat.normalize(a,b)))) \n               (x ^ nat(fst(Rat.normalize(a,b)))) = \n         root (nat b) (x ^ (nat a))\"\nproof -\n  have \"root (nat (b div gcd a b)) (x ^ nat (a div gcd a b)) = \n        root (nat b) (x ^ nat a)\"\n  proof (cases \"coprime a b\")\n    case True\n      then show ?thesis by simp\n  next\n    case False\n      have \"0 < gcd a b\"\n        using assms(2) gcd_pos_int by blast\n      then have \"nat (gcd a b) > 0\"\n        by linarith \n      moreover have \"nat (b div gcd a b) > 0\" \n        using nonneg1_imp_zdiv_pos_iff assms(3) by auto\n      moreover\n       have \"root (nat b) (x ^ nat a) = \n             root (nat (gcd a b * (b div gcd a b))) \n                   (x ^ nat (gcd a b * (a div gcd a b)))\"\n         by simp \n       ultimately show ?thesis\n         using assms(1) gcd_ge_0_int nat_mult_distrib real_root_mult_exp_cancel2 \n         by presburger\n     qed\n     then show ?thesis\n       by (metis assms(3) fst_conv normalize_def snd_conv) \n  qed\n\nlemma powrat_add_pos: \n  assumes \"0 < x\" and \"0 < r\" and \"0 < s\" \n  shows \"x pow\\<^sub>\\<rat> (r + s) = (x pow\\<^sub>\\<rat> r) * (x pow\\<^sub>\\<rat> s)\"\nproof (cases r)\n  case (Fract a b)\n  assume b0: \"b > 0\" and rf: \"r = Fract a b\"\n  then have a0: \"a > 0\"\n    using Fract(1) assms(2) zero_less_Fract_iff by blast \n  then show ?thesis\n    proof (cases s)\n      case (Fract c d) \n      assume d0: \"d > 0\" and sf: \"s = Fract c d\" \n      then have c0: \"c > 0\"\n        using assms(3) zero_less_Fract_iff by blast \n      then have bd0: \"b * d > 0\"  \n          using b0 zero_less_mult_iff Fract(2) by blast \n          then show ?thesis \n          proof (cases \"a * d > 0 \\<and> c * b > 0\")\n            case True\n            assume abcd: \"a * d > 0 \\<and> c * b > 0\"\n            then have adcb0: \"a * d + c * b > 0\" by simp\n            have \"x ^ nat (a * d + c * b) = \n                  ((x ^ (nat a)) ^ nat d) * (x ^ (nat c)) ^ nat b\"\n              using abcd nat_mult_distrib nat_add_distrib \n                    zero_less_Fract_iff Fract(3) a0 c0 \n              by (simp add: power_mult power_add)\n            then have \"root (nat b) \n                        (root (nat d) \n                           (x ^ nat (a * d + c * b))) =\n                       root (nat b) \n                        (root (nat d) \n                          (((x ^ (nat a)) ^ nat d) * (x ^ (nat c)) ^ nat b))\"\n              by simp   \n            also have \"... = root (nat b) \n                              (root (nat d) ((x ^ (nat a)) ^ nat d) * \n                               root (nat d) ((x ^ (nat c)) ^ nat b))\"\n              by (simp add: Fract(2) real_root_mult)\n            also have \"... = root (nat b) \n                              (root (nat d) ((x ^ (nat a)) ^ nat d)) *\n                             root (nat b) \n                              (root (nat d) ((x ^ (nat c)) ^ nat b))\"\n              using real_root_mult by blast\n            also have \"... = root (nat b) (x ^ (nat a)) * \n                             root (nat b) \n                              (root (nat d) ((x ^ (nat c)) ^ nat b))\"\n              using real_root_power_cancel Fract(2) zero_less_nat_eq assms(1) \n                    less_imp_le by simp\n            also have \"... = \n                       root (nat b) (x ^ nat a) *  root (nat d) (x ^ nat c)\"\n              using  real_root_power [of \"nat d\"] real_root_power_cancel \n                     real_root_pos_pos_le zero_less_nat_eq\n                     Fract(2) zero_less_nat_eq b0 assms(1) by auto \n            finally have \"root (nat b) (root (nat d) (x ^ nat (a * d + c * b))) = \n                          root (nat b) (x ^ nat a) *  root (nat d) (x ^ nat c)\" \n              by assumption        \n            then show ?thesis using a0 b0 c0 d0 bd0 abcd adcb0 assms(1) sf rf \n              by (auto simp add:  powrat_def quotient_of_Fract \n                      real_root_mult_exp nat_mult_distrib \n                      zero_less_Fract_iff real_root_normalize_cancel)\n          next\n            case False\n            then show ?thesis\n              by (simp add: a0 b0 c0 d0) \n          qed\n    qed\nqed\n\nlemma powrat_add_neg: \n  assumes \"0 < x\" and \"r < 0\" and \"s < 0\" \n  shows \"x pow\\<^sub>\\<rat> (r + s) = (x pow\\<^sub>\\<rat> r) * (x pow\\<^sub>\\<rat> s)\"\nproof - \n  have \"x pow\\<^sub>\\<rat> (- r + - s) = x pow\\<^sub>\\<rat> - r * x pow\\<^sub>\\<rat> - s\" \n    using assms powrat_add_pos neg_0_less_iff_less by blast \n  then show ?thesis\n    by (metis inverse_eq_imp_eq inverse_mult_distrib \n         minus_add_distrib powrat_minus) \nqed\n\nlemma powrat_add_neg_pos: \n    assumes pos_x: \"0 < x\" and  \n            neg_r: \"r < 0\" and \n            pos_s: \"0 < s\" \n    shows \"x pow\\<^sub>\\<rat> (r + s) = (x pow\\<^sub>\\<rat> r) * (x pow\\<^sub>\\<rat> s)\"\nproof (cases \"r + s > 0\")\n  assume exp_pos: \"r + s > 0\"\n  have \"-r > 0\" using neg_r by simp \n  then have \"x pow\\<^sub>\\<rat> (r + s) * (x pow\\<^sub>\\<rat> -r) =  (x pow\\<^sub>\\<rat> s)\" \n    using exp_pos pos_x powrat_add_pos by fastforce \n  then have \"x pow\\<^sub>\\<rat> (r + s) * inverse (x pow\\<^sub>\\<rat> r) =  (x pow\\<^sub>\\<rat> s)\" \n    by (simp add: powrat_minus) \n  then show \"x pow\\<^sub>\\<rat> (r + s) = (x pow\\<^sub>\\<rat> r) * (x pow\\<^sub>\\<rat> s)\"\n    by (metis Groups.mult_ac(3) assms(1) mult.right_neutral \n          order_less_irrefl powrat_gt_zero right_inverse)  \nnext\n  assume exp_pos: \"\\<not> r + s > 0\"   \n  then have \"r + s = 0 \\<or> r + s < 0\" using neq_iff by blast   \n  then show \"x pow\\<^sub>\\<rat> (r + s) = (x pow\\<^sub>\\<rat> r) * (x pow\\<^sub>\\<rat> s)\" \n  proof \n    assume exp_zero: \"r + s = 0\" \n    then have \"x pow\\<^sub>\\<rat> (r + s) = 1\" by simp\n    also have \"... = (x pow\\<^sub>\\<rat> r) * inverse (x pow\\<^sub>\\<rat> r)\" \n      using pos_x powrat_not_zero by simp\n    also have \"... = (x pow\\<^sub>\\<rat> r) * (x pow\\<^sub>\\<rat> - r)\" \n      by (simp add: powrat_minus) \n    finally show \"x pow\\<^sub>\\<rat> (r + s) = (x pow\\<^sub>\\<rat> r) * (x pow\\<^sub>\\<rat> s)\"  \n      using exp_zero minus_unique by blast \n   next \n    assume \"r + s < 0\" \n    have \"-s < 0\" using pos_s by simp \n    then have \"x pow\\<^sub>\\<rat> (r + s) * (x pow\\<^sub>\\<rat> -s) =  (x pow\\<^sub>\\<rat> r)\" \n      using \\<open>r + s < 0\\<close> pos_x powrat_add_neg by fastforce \n    then have \"x pow\\<^sub>\\<rat> (r + s) * inverse (x pow\\<^sub>\\<rat> s) =  (x pow\\<^sub>\\<rat> r)\" \n      by (simp add: powrat_minus) \n    then show \"x pow\\<^sub>\\<rat> (r + s) = (x pow\\<^sub>\\<rat> r) * (x pow\\<^sub>\\<rat> s)\"\n      by (metis divide_eq_eq divide_real_def \n            less_irrefl pos_x powrat_not_zero) \n    qed\nqed\n\nlemma powrat_add_pos_neg: \n \"\\<lbrakk> 0 < x; 0 < r; s < 0 \\<rbrakk> \n  \\<Longrightarrow> x pow\\<^sub>\\<rat> (r + s) = (x pow\\<^sub>\\<rat> r) * (x pow\\<^sub>\\<rat> s)\"\nby (metis add.commute mult.commute powrat_add_neg_pos)\n\nlemma powrat_add: \n  assumes \"0 < x\" \n  shows \"x pow\\<^sub>\\<rat> (r + s) = (x pow\\<^sub>\\<rat> r) * (x pow\\<^sub>\\<rat> s)\"\n  proof (cases \"(r > 0 \\<or> r \\<le> 0) \\<and> (s > 0 \\<or> s \\<le> 0)\")\n    case True\n    then show ?thesis using assms \n      by (auto dest: powrat_add_pos powrat_add_neg powrat_add_neg_pos \n           powrat_add_pos_neg simp add: le_less)\nnext\n  case False\n  then show ?thesis  by auto\nqed\n\nlemma powrat_diff: \n     \"0 < x \\<Longrightarrow>  x pow\\<^sub>\\<rat> (a - b) = x pow\\<^sub>\\<rat> a / x pow\\<^sub>\\<rat> b\"\nby (metis add_uminus_conv_diff divide_inverse powrat_add powrat_minus)\n\nlemma powrat_mult_pos:\n  assumes \"0 < x\" and \"0 < r\" and \"0 < s\" \n  shows \"x pow\\<^sub>\\<rat> (r * s) = (x pow\\<^sub>\\<rat> r) pow\\<^sub>\\<rat> s\" \nproof (cases r)\n  case (Fract a b)\n  assume b0: \"b > 0\" and rf: \"r = Fract a b\" and coab: \"coprime a b\"\n  have a0: \"a > 0\"\n    using assms(2) b0 rf zero_less_Fract_iff by blast \n  then show ?thesis \n  proof (cases s)\n    case (Fract c d)\n    assume d0: \"d > 0\" and sf: \"s = Fract c d\" and coad: \"coprime c d\"\n      then have c0: \"c > 0\"\n        using assms(3) zero_less_Fract_iff by blast \n      then have  \"b * d > 0\" \n        using b0 d0 by simp\n      then show ?thesis using a0 c0 b0 d0 rf sf coab coad assms\n        by (auto intro: mult_pos_pos simp add: powrat_def quotient_of_Fract\n            zero_less_Fract_iff real_root_normalize_cancel real_root_power\n            real_root_mult_exp [symmetric] nat_mult_distrib power_mult \n            mult.commute)\n  qed\nqed\n\nlemma powrat_mult_neg:\n  assumes \"0 < x\" \"r < 0\" and \"s < 0\" \n  shows \"x pow\\<^sub>\\<rat> (r * s) = (x pow\\<^sub>\\<rat> r) pow\\<^sub>\\<rat> s\"\nproof - \n  have \" x pow\\<^sub>\\<rat> (- r * - s) = (x pow\\<^sub>\\<rat> - r) pow\\<^sub>\\<rat> - s\" \n    using powrat_mult_pos assms neg_0_less_iff_less by blast \n  then show ?thesis\n    by (simp add: powrat_inverse powrat_minus) \nqed \n\n\nlemma powrat_mult_neg_pos:\n  assumes \"0 < x\" and \"r < 0\" and \"0 < s\" \n  shows \"x pow\\<^sub>\\<rat> (r * s) = (x pow\\<^sub>\\<rat> r) pow\\<^sub>\\<rat> s\"\nproof -\n  have \"x pow\\<^sub>\\<rat> (- r * s) = (x pow\\<^sub>\\<rat> - r) pow\\<^sub>\\<rat> s\" \n    using powrat_mult_pos assms neg_0_less_iff_less by blast \n  then show ?thesis\n    by (simp add: powrat_inverse powrat_minus) \nqed\n\nlemma powrat_mult_pos_neg:\n  assumes \"0 < x\" and \"0 < r\" and \"s < 0\"\n  shows \"x pow\\<^sub>\\<rat> (r * s) = (x pow\\<^sub>\\<rat> r) pow\\<^sub>\\<rat> s\"\nproof -\n  have \"x pow\\<^sub>\\<rat> (r * - s) = (x pow\\<^sub>\\<rat> r) pow\\<^sub>\\<rat> - s\" \n    using powrat_mult_pos assms neg_0_less_iff_less by blast \n  then show ?thesis\n    by (simp add: powrat_minus) \nqed\n\nlemma powrat_mult:\n  assumes \"0 < x\" shows \"x pow\\<^sub>\\<rat> (r * s) = (x pow\\<^sub>\\<rat> r) pow\\<^sub>\\<rat> s\"\nproof -\n  {fix q::rat\n    assume \"q = 0\" then have \"x pow\\<^sub>\\<rat> (q * s) = (x pow\\<^sub>\\<rat> q) pow\\<^sub>\\<rat> s\"\n      by simp\n  }\n  then show ?thesis\n    by (metis assms linorder_neqE_linordered_idom mult_zero_right \n         powrat_mult_neg powrat_mult_neg_pos powrat_mult_pos \n         powrat_mult_pos_neg powrat_zero_eq_one)\nqed\n\nlemma powrat_less_mono: \n  assumes \"r < s\" and \"1 < x\" \n  shows \"x  pow\\<^sub>\\<rat> r < x pow\\<^sub>\\<rat> s\"\n  proof (cases r)\n    case (Fract a b)\n    assume r_assms: \"r = Fract a b\" \"0 < b\" \"coprime a b\"\n    then show ?thesis\n  proof (cases s)\n    case (Fract c d)\n    assume s_assms: \"s = Fract c d\" \"0 < d\" \"coprime c d\"\n    have adcb: \"a * d < c * b\" \n      using assms r_assms s_assms by auto\n    have b_ba: \"0 < nat (b * d)\"\n      by (simp add: r_assms(2) s_assms(2))\n    have root0: \"0 \\<le> root (nat d) (x ^ nat c)\" \n                \"0 \\<le> root (nat d) (1 / x ^ nat (- c))\"\n      using assms(2) real_root_pos_pos_le by auto \n    then show ?thesis\n    proof (auto simp add: powrat_def quotient_of_Fract zero_less_Fract_iff \n                          s_assms r_assms)\n      assume ac0: \"0 < a\" \"0 < c\"\n      then have \"(x ^ nat a) ^ nat d < (x ^ nat c) ^ nat b\"\n        using adcb assms(2) r_assms(2) less_imp_le mult_pos_pos \n              nat_mono_iff nat_mult_distrib power_mult \n              power_strict_increasing \n        by metis\n      then have \"root (nat b) (x ^ nat a) ^ nat (b * d) <\n                  root (nat d) (x ^ nat c) ^ nat (b * d)\" \n        using assms r_assms s_assms ac0 real_root_power \n              [symmetric] nat_mult_distrib\n        by (auto simp add:  power_mult)\n      then show \"root (nat b) (x ^ nat a) < root (nat d) (x ^ nat c)\"\n        using power_less_imp_less_base root0(1) by blast\n    next\n      assume \"0 < a\" \"\\<not> 0 < c\"\n      then show \"root (nat b) (x ^ nat a) < \n                  root (nat d) (1 / x ^ nat (- c))\"\n        using assms(1) less_trans r_assms(1) r_assms(2) s_assms(1) \n              s_assms(2) zero_less_Fract_iff by blast\n    next \n      assume ac0: \"\\<not> 0 < a\" \"0 < c\"\n      then have \"a = 0 \\<or> a < 0\" by auto\n      then show \"root (nat b) (1 / x ^ nat (- a)) <\n                  root (nat d) (x ^ nat c)\"\n      proof \n        assume \"a = 0\" then show ?thesis\n          by (simp add: ac0(2) assms(2) r_assms(2) s_assms(2))\n      next\n        assume a0: \"a < 0\"  \n        have \"(1 / x ^ nat (- a)) ^ nat d < 1\" \n          using a0 s_assms(2) assms(2) adcb power_mult [symmetric] \n                power_one_over nat_mult_distrib [symmetric]\n          by (metis (no_types) eq_divide_eq_1 inverse_eq_divide inverse_le_1_iff\n              le_less neg_0_less_iff_less one_less_power power_one_over\n              zero_less_nat_eq)\n        moreover have \"1 < (x ^ nat c) ^ nat b\"\n          by (simp add: ac0(2) assms(2) r_assms(2)) \n        ultimately have \"(1 / x ^ nat (- a)) ^ nat d < (x ^ nat c) ^ nat b\"\n          by linarith \n        then have \"root (nat b) (1 / x ^ nat (- a)) ^ nat (b * d)\n                    < root (nat d) (x ^ nat c) ^ nat (b * d)\"\n        using  assms r_assms s_assms ac0 real_root_power [symmetric] nat_mult_distrib\n        by (auto simp add:  power_mult)\n        then show ?thesis\n          using power_less_imp_less_base root0(1) by blast \n      qed\n    next\n      assume ac0: \"\\<not> 0 < a\" \"\\<not> 0 < c\"   \n      then show \"root (nat b) (1 / x ^ nat (- a)) < \n                  root (nat d) (1 / x ^ nat (- c))\"\n      proof (cases \"a = 0 \\<or> c = 0\")\n        assume \"a = 0 \\<or> c = 0\" then show ?thesis\n          using assms r_assms s_assms adcb ac0  \n          by (auto simp add: not_less le_less)\n      next\n        assume \"\\<not> (a = 0 \\<or> c = 0)\" \n        then have ac00: \"a < 0\" \"c < 0\" using ac0 by auto\n        then have \"1 / x ^ nat (- (a * d)) < \n                    1 / x ^ nat (- (c * b))\" \n          using ac00 r_assms s_assms assms \n          by (simp add: divide_inverse mult_pos_neg2) \n        then have \"(1 / x ^ nat (- a)) ^ nat d < \n                    (1 / x ^ nat (- c)) ^ nat b\" \n          using s_assms r_assms  ac00\n          by (auto simp add: power_mult [symmetric] \n                power_one_over nat_mult_distrib [symmetric])\n        then have \"root (nat b) (1 / x ^ nat (- a)) ^ nat (b * d)\n                   < root (nat d) (1 / x ^ nat (- c)) ^ nat (b * d)\"\n          using assms r_assms s_assms ac0 real_root_power [symmetric] \n                nat_mult_distrib\n        by (auto simp add:  power_mult)\n      then show \"root (nat b) (1 / x ^ nat (- a)) < \n                  root (nat d) (1 / x ^ nat (- c))\"\n          using power_less_imp_less_base root0(2) by blast\n      qed\n    qed\n  qed\nqed\n\nlemma power_le_imp_le_base2: \n  \"\\<lbrakk> (a::'a::linordered_semidom) ^ n \\<le> b ^ n; 0 \\<le> b; 0 < n \\<rbrakk> \n   \\<Longrightarrow> a \\<le> b\"\nby (auto intro: power_le_imp_le_base [of _ \"n - 1\"])\n\nlemma powrat_le_mono: \n  assumes \"r \\<le> s\" and \"1 \\<le> x\" \n  shows \"x  pow\\<^sub>\\<rat> r \\<le> x pow\\<^sub>\\<rat> s\"\n  by (metis (full_types) assms le_less powrat_less_mono powrat_one_eq_one)\n\nlemma powrat_less_cancel: \n  \"\\<lbrakk> x  pow\\<^sub>\\<rat> r < x  pow\\<^sub>\\<rat> s; 1 < x \\<rbrakk> \\<Longrightarrow> r < s\"\n  by (metis not_less_iff_gr_or_eq powrat_less_mono)\n\n(* Monotonically increasing *)\nlemma powrat_less_cancel_iff [simp]: \n  \"1 < x \\<Longrightarrow> (x pow\\<^sub>\\<rat> r < x pow\\<^sub>\\<rat> s) = (r < s)\"\nby (blast intro: powrat_less_cancel powrat_less_mono)\n\nlemma powrat_le_cancel_iff [simp]: \n  \"1 < x \\<Longrightarrow> (x  pow\\<^sub>\\<rat> r \\<le> x  pow\\<^sub>\\<rat> s) = (r \\<le> s)\"\nby (simp add: linorder_not_less [symmetric])\n\n(* Next 2 theorems should be in Power.thy *)\nlemma power_inject_exp_less_one [simp]:\n  \"\\<lbrakk>0 < a; (a::'a::{linordered_field}) < 1 \\<rbrakk> \n   \\<Longrightarrow> a ^ m = a ^ n \\<longleftrightarrow> m = n\"\nby (metis less_irrefl nat_neq_iff power_strict_decreasing)\n\nlemma power_inject_exp_strong [simp]:\n  \"\\<lbrakk>0 < a; (a::'a::{linordered_field}) \\<noteq> 1 \\<rbrakk> \n   \\<Longrightarrow> a ^ m = a ^ n \\<longleftrightarrow> m = n\"\nby (case_tac \"a < 1\") (auto simp add: not_less)\n\n(* Not proved elsewhere? *)\nlemma nat_eq_cancel: \"0 < a \\<Longrightarrow> 0 < b \\<Longrightarrow> (nat a = nat b) = (a = b)\"\nby auto\n\nlemma powrat_inject_exp [simp]: \n  \"1 < x  \\<Longrightarrow> (x pow\\<^sub>\\<rat> r = x pow\\<^sub>\\<rat> s) = (s = r)\"\n  by (metis neq_iff powrat_less_cancel_iff)\n\nlemma powrat_inject_exp_less_one [simp]: \n  assumes \"0 < x\" and \"x < 1\" \n  shows \"(x pow\\<^sub>\\<rat> r = x pow\\<^sub>\\<rat> s) = (s = r)\"\nproof -\n  have \"1 < inverse x\"\n    using assms one_less_inverse by blast \n  then show ?thesis\n    using powrat_inject_exp powrat_inverse by fastforce \nqed\n\nlemma powrat_inject_exp_strong [simp]:\n   \"\\<lbrakk> 0 < x; x \\<noteq> 1 \\<rbrakk>  \\<Longrightarrow> (x pow\\<^sub>\\<rat> r = x pow\\<^sub>\\<rat> s) = (s = r)\"\n  using powrat_inject_exp_less_one by fastforce\n\n(* Monotonically decreasing *)\nlemma powrat_less_1_cancel_iff [simp]: \n  assumes x0: \"0 < x\" and x1: \"x < 1\" \n  shows \"(x pow\\<^sub>\\<rat> r < x pow\\<^sub>\\<rat> s) = (s < r)\"\nproof \n  assume xrs: \"x pow\\<^sub>\\<rat> r < x pow\\<^sub>\\<rat> s\" \n  have invx: \"1 < 1/x\" using assms by simp\n  have  \"r < s \\<or> r \\<ge> s\" using leI by blast \n  then show \"s < r\" \n  proof\n    assume \"r < s\"\n    then have \" inverse x pow\\<^sub>\\<rat> r < inverse x pow\\<^sub>\\<rat> s\" using invx\n      by (simp add: inverse_eq_divide)\n    then have \" x pow\\<^sub>\\<rat> s < x pow\\<^sub>\\<rat> r\"\n      by (simp add: powrat_gt_zero powrat_inverse x0) \n    then show ?thesis using xrs by linarith \n  next\n    assume \"r \\<ge> s\"   \n    then show ?thesis\n      using less_eq_rat_def xrs by blast \n  qed\nnext \n  assume sr: \"s < r\" \n  have invx: \"1 < 1/x\" using assms by simp\n  then have \" inverse x pow\\<^sub>\\<rat> s < inverse x pow\\<^sub>\\<rat> r\" using invx sr\n    by (simp add: inverse_eq_divide) \n  then  show \"x pow\\<^sub>\\<rat> r < x pow\\<^sub>\\<rat> s\"\n    by (simp add: powrat_gt_zero powrat_inverse x0)\nqed\n \nlemma powrat_le_1_cancel_iff [simp]: \n   \"\\<lbrakk>0 < x; x < 1\\<rbrakk> \\<Longrightarrow> (x pow\\<^sub>\\<rat> r \\<le> x pow\\<^sub>\\<rat> s) = (s \\<le> r)\"\nby (auto simp add: le_less)\n\nlemma powrat_ge_one: \"x \\<ge> 1 \\<Longrightarrow> r \\<ge> 0 \\<Longrightarrow> x pow\\<^sub>\\<rat> r \\<ge> 1\"\nby (metis powrat_le_mono powrat_zero_eq_one)\n\nlemma isCont_powrat:\n  assumes \"0 < x\" shows \"isCont (\\<lambda>x. x pow\\<^sub>\\<rat> r) x\"\nproof (cases r)\n  case (Fract a b)\n    assume fract_assms: \"r = Fract a b\" \"0 < b\" \"coprime a b\"\n    then show ?thesis\n    proof (cases \"0 < a\")\n      case True\n      then show ?thesis \n        using fract_assms isCont_o2 [OF isCont_power [OF continuous_ident]]\n        by (auto intro: isCont_real_root simp add: powrat_def zero_less_Fract_iff)\n      next\n        case False\n        then show ?thesis \n          using fract_assms assms isCont_real_root  real_root_gt_zero\n                continuous_at_within_inverse [intro!]\n          by (auto intro!: isCont_o2 [OF isCont_power [OF continuous_ident]]\n                   simp add: powrat_def zero_less_Fract_iff divide_inverse \n                      real_root_inverse)\n      qed\nqed\n\nlemma LIMSEQ_powrat_base: \n  \"\\<lbrakk> X \\<longlonglongrightarrow> a; a > 0 \\<rbrakk> \\<Longrightarrow> (\\<lambda>n. (X n) pow\\<^sub>\\<rat> q) \\<longlonglongrightarrow> a pow\\<^sub>\\<rat> q\"\nby (metis isCont_tendsto_compose [where g=\"\\<lambda>x. x pow\\<^sub>\\<rat> q\"] isCont_powrat)\n\nlemma powrat_inverse_of_nat_ge_one [simp]: \n      \"a \\<ge> 1 \\<Longrightarrow> a pow\\<^sub>\\<rat> (inverse (of_nat n)) \\<ge> 1\"\n  by (simp add: powrat_ge_one)\n\nlemma powrat_inverse_of_nat_le_self [simp]: \n  assumes \"1 \\<le> a\" shows \"a pow\\<^sub>\\<rat> inverse (rat_of_nat n) \\<le> a\"\nproof - \n  have \"inverse (rat_of_nat n) \\<le> 1\"  \n    by (auto simp add: inverse_le_1_iff)\n  also have \"a pow\\<^sub>\\<rat> 1 \\<le> a\" by simp\n  ultimately show ?thesis\n    using assms powrat_le_mono by fastforce \nqed\n\n(* This lemma used to be in Limits.thy *)\nlemma BseqI2': \"\\<forall>n\\<ge>N. norm (X n) \\<le> K \\<Longrightarrow> Bseq X\"\n  using BfunI eventually_sequentially by blast\n\nlemma Bseq_powrat_inverse_of_nat_ge_one:\n      \"a \\<ge> 1 \\<Longrightarrow> Bseq (\\<lambda>n. a pow\\<^sub>\\<rat> (inverse (of_nat n)))\"\nby (auto intro: BseqI2' [of 1 _ a] simp add: less_imp_le powrat_gt_zero)\n\nlemma decseq_powrat_inverse_of_nat_ge_one:\n      \"a \\<ge> 1 \\<Longrightarrow> decseq (\\<lambda>n. a pow\\<^sub>\\<rat> (inverse (of_nat (Suc n))))\"\nunfolding decseq_def by (auto intro: powrat_le_mono)\n\nlemma convergent_powrat_inverse_Suc_of_nat_ge_one:\n  assumes \"a \\<ge> 1\" \n  shows \"convergent (\\<lambda>n. a pow\\<^sub>\\<rat> (inverse (of_nat (Suc n))))\"\nproof -\n  have \"Bseq (\\<lambda>n. a pow\\<^sub>\\<rat> inverse (rat_of_nat n))\" \n    using Bseq_powrat_inverse_of_nat_ge_one assms by blast\n  then have \"Bseq (\\<lambda>n. a pow\\<^sub>\\<rat> inverse (rat_of_nat (Suc n)))\"\n    using Bseq_ignore_initial_segment [of _ 1] by fastforce \n  also have \"monoseq (\\<lambda>n. a pow\\<^sub>\\<rat> inverse (rat_of_nat (Suc n)))\"\n    using assms decseq_imp_monoseq decseq_powrat_inverse_of_nat_ge_one by blast\n  ultimately show ?thesis\n    using Bseq_monoseq_convergent by blast\nqed\n\nlemma convergent_powrat_inverse_of_nat_ge_one:\n  assumes \"a \\<ge> 1\" shows \"convergent (\\<lambda>n. a pow\\<^sub>\\<rat> (inverse (of_nat n)))\"\nproof -\n  have \"convergent (\\<lambda>n. a pow\\<^sub>\\<rat> inverse (rat_of_nat (Suc n)))\"\n    using convergent_powrat_inverse_Suc_of_nat_ge_one assms by blast\n  then obtain L where \"(\\<lambda>n. a pow\\<^sub>\\<rat> inverse (1 + rat_of_nat n)) \\<longlonglongrightarrow> L\" \n    using convergent_def by auto\n  then have \"(\\<lambda>n. a pow\\<^sub>\\<rat> inverse (rat_of_nat (n + 1))) \\<longlonglongrightarrow> L\" \n    by simp\n  then have \"(\\<lambda>n. a pow\\<^sub>\\<rat> inverse (rat_of_nat n)) \\<longlonglongrightarrow> L\" \n    by (rule LIMSEQ_offset  [of _ 1])\n  then show ?thesis using convergent_def by auto\nqed\n\nlemma LIMSEQ_powrat_inverse_of_nat_ge_one: \n  assumes \"a \\<ge> 1\" shows \"(\\<lambda>n. a pow\\<^sub>\\<rat> (inverse (of_nat n))) \\<longlonglongrightarrow> 1\"\nproof -\n  have \"convergent(\\<lambda>n. a pow\\<^sub>\\<rat> inverse (rat_of_nat n))\"  \n    using convergent_powrat_inverse_of_nat_ge_one assms by blast\n  then have \"\\<exists>L. L \\<noteq> 0 \\<and> (\\<lambda>n. a pow\\<^sub>\\<rat> (inverse (of_nat n))) \\<longlonglongrightarrow> L\"\n    using assms convergent_def powrat_inverse_of_nat_ge_one \n          LIMSEQ_le_const not_one_le_zero\n    by metis \n  then obtain L \n       where l0: \"L \\<noteq> 0\" \n       and liml: \"(\\<lambda>n. a pow\\<^sub>\\<rat> (inverse (of_nat n))) \\<longlonglongrightarrow> L\" \n    by blast\n  then have \"(\\<lambda>n. a pow\\<^sub>\\<rat> (inverse (of_nat n)) * \n                   a pow\\<^sub>\\<rat> (inverse (of_nat n))) \\<longlonglongrightarrow> L * L\"\n    by (simp add:  tendsto_mult)\n  then have \"(\\<lambda>n. a pow\\<^sub>\\<rat> (2 * inverse (of_nat n))) \\<longlonglongrightarrow>  L * L\"\n    using powrat_add [symmetric] assms by simp\n  also have \"(2::nat) > 0\" by simp\n  ultimately \n  have \"(\\<lambda>n. a pow\\<^sub>\\<rat> (2 * inverse (of_nat (n * 2)))) \\<longlonglongrightarrow>  L * L\" \n    using LIMSEQ_linear [of _ \"L * L\" 2] by blast\n  then have \"(\\<lambda>n. a pow\\<^sub>\\<rat> (inverse (of_nat n))) \\<longlonglongrightarrow>  L * L\" \n    by simp\n  then show ?thesis using liml using LIMSEQ_unique l0 \n    by fastforce\nqed\n\nlemma LIMSEQ_powrat_inverse_of_nat_pos_less_one: \n  assumes a0: \"0 < a\" and a1: \"a < 1\" \n  shows \"(\\<lambda>n. a pow\\<^sub>\\<rat> (inverse (of_nat n))) \\<longlonglongrightarrow> 1\"\nproof - \n  have \"inverse a > 1\" using a0 a1\n    using one_less_inverse by blast \n  then have \"(\\<lambda>n. inverse a pow\\<^sub>\\<rat> inverse (rat_of_nat n)) \\<longlonglongrightarrow> 1\"\n    using LIMSEQ_powrat_inverse_of_nat_ge_one by simp \n  then have \"(\\<lambda>n. inverse (a pow\\<^sub>\\<rat> inverse (rat_of_nat n))) \\<longlonglongrightarrow> 1\"\n    using powrat_inverse by simp\n  then have \"(\\<lambda>x. 1 / inverse (a pow\\<^sub>\\<rat> inverse (rat_of_nat x))) \\<longlonglongrightarrow> 1/1\"\n    by (auto intro: tendsto_divide simp only:)\n  then show ?thesis  by (auto simp add: divide_inverse)\nqed\n\nlemma LIMSEQ_powrat_inverse_of_nat: \n   \"a > 0 \\<Longrightarrow> (\\<lambda>n. a pow\\<^sub>\\<rat> (inverse (of_nat n))) \\<longlonglongrightarrow> 1\"\n  by (metis LIMSEQ_powrat_inverse_of_nat_ge_one \n       LIMSEQ_powrat_inverse_of_nat_pos_less_one leI)\n\n\nlemma real_root_eq_powrat_inverse:\n  assumes \"n > 0\" shows \"root n x = x pow\\<^sub>\\<rat> (inverse (of_nat n))\"\nproof (cases n)\n  case 0\n  then show ?thesis\n    using assms by blast \nnext\n  case (Suc m)\n  assume nSuc: \"n = Suc m\"\n  then have \"root (Suc m) x = root (nat (1 + int m)) x\"\n    by (metis nat_int of_nat_Suc)    \n  then show ?thesis \n    by (auto simp add: nSuc powrat_def of_nat_rat \n          zero_less_Fract_iff quotient_of_Fract)\nqed\n\nlemma powrat_power_eq: \n   \"0 < a \\<Longrightarrow> a pow\\<^sub>\\<rat> rat_of_nat n = a ^ n\"\nproof (induction n)\ncase 0\n  then show ?case by simp\nnext\n  case (Suc n)\n  then show ?case using powrat_add by simp\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/Real_Power/RatPower.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357701094304, "lm_q2_score": 0.8499711737573762, "lm_q1q2_score": 0.7369554112095432}}
{"text": "(*  Title:      HOL/Euclidean_Rgins.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_Rings\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 (induction 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 (induction 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 (induction 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 (induction 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 (induction 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>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 (induction 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 (induction 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 (induction 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>\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 m div n = m div n + Suc (m mod n) div n\\<close>\n    using div_add1_eq [of m 1 n] by simp\n  also have \\<open>Suc (m mod n) div n = of_bool (n dvd Suc m)\\<close>\n  proof (cases \\<open>n dvd Suc m\\<close>)\n    case False\n    moreover 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 - Suc 0\\<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 show ?thesis\n      by (simp add: div_eq_0_iff)\n  next\n    case True\n    then obtain q where q: \\<open>Suc m = n * q\\<close> ..\n    moreover have \\<open>q > 0\\<close> by (rule ccontr)\n      (use q in simp)\n    ultimately have \\<open>m mod n = n - Suc 0\\<close>\n      using \\<open>n > 1\\<close> mult_le_cancel1 [of n \\<open>Suc 0\\<close> q]\n      by (auto intro: mod_nat_eqI)\n    with True \\<open>n > 1\\<close> show ?thesis\n      by simp\n  qed\n  finally show ?thesis\n    by (simp add: mod_greater_zero_iff_not_dvd)\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>\nproof (cases \\<open>n = 0\\<close>)\n  case True\n  then show ?thesis\n    by simp\nnext\n  case False\n  moreover have \\<open>Suc m mod n = Suc (m mod n) mod n\\<close>\n    by (simp add: mod_simps)\n  ultimately show ?thesis\n    by (auto intro!: mod_nat_eqI intro: neq_le_trans simp add: Suc_le_eq)\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>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 (induction 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\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 (induction 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  have \\<open>(a div b, a mod b) = (q, r)\\<close>\n    by (induction rule: euclidean_relation_intI)\n      (use assms in \\<open>auto simp add: ac_simps dvd_add_left_iff sgn_1_pos le_less dest: zdvd_imp_le\\<close>)\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: \\<open>a div (b * c) = (a div b) div c\\<close>  (is ?Q)\n  and zmod_zmult2_eq: \\<open>a mod (b * c) = b * (a div b mod c) + a mod b\\<close>  (is ?P)\n  if \\<open>c \\<ge> 0\\<close> for a b c :: int\nproof -\n  have *: \\<open>(a div (b * c), a mod (b * c)) = ((a div b) div c, b * (a div b mod c) + a mod b)\\<close>\n    if \\<open>b > 0\\<close> for a b\n  proof (induction rule: euclidean_relationI)\n    case by0\n    then show ?case by auto\n  next\n    case divides\n    then obtain d where \\<open>a = b * c * d\\<close>\n      by blast\n    with divides that show ?case\n      by (simp add: ac_simps)\n  next\n    case euclidean_relation\n    with \\<open>b > 0\\<close> \\<open>c \\<ge> 0\\<close> have \\<open>0 < c\\<close> \\<open>b > 0\\<close>\n      by simp_all\n    then have \\<open>a mod b < b\\<close>\n      by simp\n    moreover have \\<open>1 \\<le> c - a div b mod c\\<close>\n      using \\<open>c > 0\\<close> by (simp add: int_one_le_iff_zero_less)\n    ultimately have \\<open>a mod b * 1 < b * (c - a div b mod c)\\<close>\n      by (rule mult_less_le_imp_less) (use \\<open>b > 0\\<close> in simp_all)\n    with \\<open>0 < b\\<close> \\<open>0 < c\\<close> show ?case\n      by (simp add: division_segment_int_def algebra_simps flip: minus_mod_eq_mult_div)\n  qed\n  show ?Q\n  proof (cases \\<open>b \\<ge> 0\\<close>)\n    case True\n    with * [of b a] show ?thesis\n      by (cases \\<open>b = 0\\<close>) simp_all\n  next\n    case False\n    with * [of \\<open>- b\\<close> \\<open>- a\\<close>] show ?thesis\n      by simp\n  qed\n  show ?P\n  proof (cases \\<open>b \\<ge> 0\\<close>)\n    case True\n    with * [of b a] show ?thesis\n      by (cases \\<open>b = 0\\<close>) simp_all\n  next\n    case False\n    with * [of \\<open>- b\\<close> \\<open>- a\\<close>] show ?thesis\n      by simp\n  qed\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 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  \\<open>int (m div n) = int m div int n\\<close>\n  by (cases \\<open>m = 0\\<close>) (auto simp add: divide_int_def)\n\nlemma zmod_int:\n  \\<open>int (m mod n) = int m mod int n\\<close>\n  by (cases \\<open>m = 0\\<close>) (auto simp add: modulo_int_def)\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 (induction 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 (induction 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>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 \n\nend\n\ncode_identifier\n  code_module Euclidean_Rings \\<rightharpoonup> (SML) Arith and (OCaml) Arith and (Haskell) Arith\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/Euclidean_Rings.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8670357598021707, "lm_q2_score": 0.849971181358171, "lm_q1q2_score": 0.7369554090388304}}
{"text": "theory Ex04\nimports Main\nbegin\n\n(* Exercise 4.1 *)\n\n(* Podemos definir esto de dos maneras, como un conjunto o como una relacion *)\ninductive star :: \"('a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> bool\" for step where\n  \"star step x x\" |\n  \"\\<lbrakk> star step x y; step y z \\<rbrakk> \\<Longrightarrow> star step x z\"\n\ninductive_set starp' :: \"('a \\<times> 'a) set \\<Rightarrow> ('a \\<times> 'a) set\" for R where\n  \"(x,x) \\<in> starp' R\" |\n  \"\\<lbrakk>(x,y) \\<in> starp' R; (y, z) \\<in> R \\<rbrakk> \\<Longrightarrow> (x,z) \\<in> starp' R\"\n\n(* La primera definicion que hicimos le pega un paso al final, pero tambien podemos agregar pasos\n   al inicio, como sigue: *)\ninductive star' :: \"('a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> bool\" for step where\n  \"star' step x x\" |\n  \"\\<lbrakk>step x y; star' step y z\\<rbrakk> \\<Longrightarrow> star' step x z\"\n\nlemma star_prepend: (* \\<lbrakk> step x y; star step y z \\<rbrakk> \\<Longrightarrow> star step x z *)\n  assumes 1: \"step x y\"\n  assumes 2: \"star step y z\"\n  shows \"star step x z\"\n    using 2 1\n    apply (induction)\n    apply (auto intro: star.intros) (* usamos las reglas de intro de star porque en C tenemos star *)\n  done\n\nlemma star'_append: (* \\<lbrakk> star step x y; step y z \\<rbrakk> \\<Longrightarrow> star step x z *)\n  assumes 1: \"star' step x y\"\n  assumes 2: \"step y z\"\n  shows \"star' step x z\"\n    using 1 2\n    apply (induction)\n    apply (auto intro: star'.intros) (* usamos las reglas de la definicion inductiva de star porque en la conclusion tenemos star *)\n  done\n\nlemma \"star = star'\"\nproof (intro ext iffI) (* agregamos iffI porque tenemos una igualdad y necesitamos probar ambas direcciones *)\n  fix R :: \"'a \\<Rightarrow> 'a \\<Rightarrow> bool\" and x y :: 'a\n  assume \"star R x y\"\n  then show \"star' R x y\"\n    apply induction\n    apply (auto intro: star'.intros star'_append)\n  done\nnext\n  fix R :: \"'a \\<Rightarrow> 'a \\<Rightarrow> bool\" and x y :: 'a\n  assume \"star' R x y\"\n  then show \"star R x y\"\n    apply induction\n    apply (auto intro: star.intros star_prepend)\n  done\nqed\n\n(* Exercise 4.2 *)\nfun elems :: \"'a list \\<Rightarrow> 'a set\" where\n  \"elems [] = {}\"\n| \"elems (x#xs) = insert x (elems xs)\"\n\nvalue \"elems [1,2,3,4::nat]\"\n\nlemma \"elems [1,2,3,4::nat] = {1,2,3,4}\"\nsorry\n\nlemma (* \"x \\<in> elems xs \\<Longrightarrow> \\<exists> ys zs. xs = ys @ x # zs \\<and> x \\<notin> elems ys\" *)\n  assumes \"x \\<in> elems xs\"\n  shows \"\\<exists> ys zs. xs = ys @ x # zs \\<and> x \\<notin> elems ys\"\n  using assms\nproof (induction xs)\n  case Nil hence False by simp thus ?case ..\nnext\n  case (Cons y xs')\n  (* note `x \\<in> elems (y#xs')` esto ya lo sabemos, es para documentar, es como decir: ya se esto *)\n  assume A: \"x \\<in> elems (y#xs')\"\n  assume IH: \"x \\<in> elems xs' \\<Longrightarrow> \\<exists> ys zs. xs' = ys @ x # zs \\<and> x \\<notin> elems ys\"\n  term ?case\n  show \"\\<exists> ys zs. xs' = ys @ x # zs \\<and> x \\<notin> elems ys\"\n  proof (cases)\n    assume \"x = y\"\n    hence \"y#xs' = [] @ x # xs' \\<and> x \\<notin> elems []\"\n      by simp\n    thus ?case by blast\n    show ?thesis sorry\n  next\n    assume \"x \\<noteq> y\"\n    show ?thesis sorry\n  qed\nqed\n\n\n(* Exercise 4.3 *)\ninductive ev :: \"nat \\<Rightarrow> bool\" where\n  ev0: \"ev 0\" |\n  evSS: \"ev n \\<Longrightarrow> ev (Suc (Suc n))\"\n\nlemma \"ev (Suc (Suc n)) \\<Longrightarrow> ev n\"\nsorry\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/Exercise4/Ex04.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357598021707, "lm_q2_score": 0.8499711794579723, "lm_q1q2_score": 0.7369554073912902}}
{"text": "(*\n  File:     Regexp_Constructions.thy\n  Author:   Manuel Eberl <eberlm@in.tum.de>\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": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Evaluation/Regular-Sets/Regexp_Constructions.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8670357666736772, "lm_q2_score": 0.8499711718571774, "lm_q1q2_score": 0.7369554066417117}}
{"text": "(*<*)\ntheory tmpl0arun7\n  imports Main \"HOL-Data_Structures.Sorting\"\nbegin\n(*>*)\n\nhide_const (open) inv (*inv is used as a constant in isabelle, renaming it pretty prints the const \nwith the long name if the const is not hidden*)\n\ntext {* \\ExerciseSheet{7}{25.~5.~2018} *}\n\n\ntext {* \\Exercise{Interval Lists}\n\n Sets of natural numbers can be implemented as lists of intervals, where\nan interval is simply a pair of numbers.  For example the set @{term \"{2, 3, 5,\n7, 8, 9::nat}\"} can be represented by the list @{term \"[(2, 3), (5, 5),\n(7::nat, 9::nat)]\"}.  A typical application is the list of free blocks of\ndynamically allocated memory. *}\n\ntext {* We introduce the type *}\n\ntype_synonym intervals = \"(nat*nat) list\"\n\ntext {* Next, define an \\emph{invariant}\nthat characterizes valid interval lists:\nFor efficiency reasons intervals should be sorted in ascending order, the lower\nbound of each interval should be less than or equal to the upper bound, and the\nintervals should be chosen as large as possible, i.e.\\ no two adjacent\nintervals should overlap or even touch each other.  It turns out to be\nconvenient to define @{term inv} in terms of a more general function\nsuch that the additional argument is a lower bound for the intervals in\nthe list:*}\n\nfun inv' :: \"nat \\<Rightarrow> intervals \\<Rightarrow> bool\" where\n  \"inv' n [] \\<longleftrightarrow> True\"|\n  \"inv' n ((a,b)#ivs) \\<longleftrightarrow> n\\<le>a \\<and> a\\<le>b \\<and> inv' (b+2) ivs\"\n\ndefinition inv where \"inv = inv' 0\"\n\n\n\ntext {* To relate intervals back to sets define an \\emph{abstraction function}*}\n\nfun set_of :: \"intervals => nat set\"\nwhere\n  \"set_of [] = {}\"|\n  \"set_of ((a,b)#ivs) = {a..b} \\<union> set_of ivs\"\n(*{a..<b} for non inclusive bound*)\n\ntext \\<open>Define a function to add a single element to the interval list,\n  and show its correctness\\<close>\n\nfun merge_aux where\n  \"merge_aux a b [] = [(a,b)]\"|\n  \"merge_aux a b ((c,d)#ivs) = (if b+1 = c then (a,d)#ivs else (a,b)#(c,d)#ivs)\"\n\nfun add :: \"nat \\<Rightarrow> intervals \\<Rightarrow> intervals\"\n  where\n  \"add i [] = [(i,i)]\"|\n(*i can be less than a, a-1, between a and b, b+1, greater than b. if b+1 might need to merge with next element too*)\n  \"add i ((a,b)#ivs) = (\n    if i+1 < a then (i,i)#(a,b)#ivs\n    else if i+1 = a then (i,b)#ivs\n    else if i\\<le>b then (a,b)#ivs\n    else if i = b+1 then merge_aux a i ivs\n    else (a,b)#add i ivs\n)\"\n\n(* the (a,b)#add i ivs uses ivs which might cause infinite case splits on ivs when originally \nthe case split on ivs is done in the add function itself, therefore we write a different function for \nthe case splitting\n else if i = b+1 then case ivs of \n      [] \\<Rightarrow> [(a,i)]|\n      (c,d)#ivs' \\<Rightarrow> if i+1 = c then (a,d)#ivs' else (a,i)#ivs*)\n\nlemma add_pres_inv': \"n\\<le>x \\<Longrightarrow> inv' n itl \\<Longrightarrow> inv' n (add x itl)\"\n  apply(induction itl arbitrary: n) (*arbitrary n as the value of n changes in the inv' function definition*)\n   apply simp (*simp here keeps induction step as (add x (a #itl)) instead of (a,b) *)\n  apply auto (*after this sledgehammer can solve this, auto case splits on products not on anything else,\n              hence we need to case split on merge_aux*)\n  apply (case_tac itl) (*case split by apply (case_tac itl) but it is unstable so don't use except to verify*)\n  apply auto\n  done\n\nlemma add_pres_inv: \"n\\<le>x \\<Longrightarrow> inv' n itl \\<Longrightarrow> inv' n (add x itl)\"\nproof (induction itl arbitrary:n)\n  case Nil\n  then show ?case by auto\nnext\n  case (Cons a itl)\n  then show ?case\n    apply (cases a)\n    apply (cases itl)\n    apply auto\n    done\nqed\n  \nlemma set_of_add:\n  assumes \"n\\<le>x\"\n  assumes \"inv' n itl\"\n  shows \"set_of (add x itl) = {x} \\<union> set_of itl\"\n  using assms\nproof (induction itl arbitrary:n)\ncase Nil\n  then show ?case by auto\nnext\n  case (Cons a itl)\n  then show ?case \n    apply (cases a)\n    apply (cases itl)\n     apply (auto split: if_splits)  (*the apply auto without splitting on ifs shows 10 subcases where it shows all\n                                      the if cases in each subcase split: if_splits/if_split_asm where asm is \n                                      assumptions*)\n    done\nqed\n(*not in ex but done in class*)\nconsts\n  a :: \"nat\"\n  b :: \"nat set\"\n  c :: \"nat set\"\n\nlemma A: \"{a} \\<union> b = c\" sorry\n\nlemma B: \"{a} \\<union> b \\<union> d = c \\<union> d\"\n  using A apply simp (*doing apply (simp add: A) will simplify it to insert a (b \\<union> d) = c \\<union> d *)\n  done\n(*not in ex*)\nlemma add_correct:\n  assumes \"inv itl\"\n  shows \"inv (add x itl)\" \"set_of (add x itl) = insert x (set_of itl)\"\n  using add_pres_inv' assms tmpl0arun7.inv_def apply fastforce\n  using assms set_of_add tmpl0arun7.inv_def by fastforce\n\ntext \\<open>Hints:\n  \\<^item> Sketch the different cases (position of element relative to the first interval of the list)\n    on paper first\n  \\<^item> In one case, you will also need information about the second interval of the list.\n    Do this case split via an auxiliary function! Otherwise, you may end up with a recursion equation of the form\n      \\<open>f (x#xs) = \\<dots> case xs of x'#xs' \\<Rightarrow> \\<dots> f (x'#xs') \\<dots>\\<close>\n    combined with \\<open>split: list.splits\\<close> this will make the simplifier loop!\n\n\\<close>\n\n\ntext \\<open>\\Exercise{Optimized Mergesort}\n\n  Import @{theory \"Sorting\"} for this exercise.\n  The @{const msort} function recomputes the length of the list in each iteration.\n  Implement an optimized version that has an additional parameter keeping track\n  of the length, and show that it is equal to the original @{const msort}.\n\\<close>\n\n(* Optimized mergesort *)\n\nfun msort2 :: \"nat \\<Rightarrow> 'a::linorder list \\<Rightarrow> 'a list\" where\n  \"msort2 n xs = (\n    if n \\<le> 1 then xs\n    else merge (msort2 (n div 2) (take (n div 2) xs)) (msort2 (n - n div 2) (drop (n div 2) xs)))\"\n\ndeclare msort2.simps [simp del]\n\nlemma \"n = length xs \\<Longrightarrow> msort2 n xs = msort xs\"\nproof (induction n xs rule:msort2.induct)\n  case (1 n xs)\n  then show ?case \n    apply (auto simp: msort.simps[of xs] msort2.simps[of _ xs]) (*simplifier works innermost to out and  using\n                                                                  substitutes instead*)\n    done\nqed\n \n\ntext \\<open>Hint:\n  Use @{thm [source] msort.simps} only when instantiated to a particular \\<open>xs\\<close>\n  (@{thm [source] msort.simps[of xs]}),\n  otherwise the simplifier will loop!\n\\<close>\n\n\n\ntext \\<open> \\NumHomework{Deletion from Interval Lists}{June 1}\n\n  Implement and prove correct a delete function.\n\n  Hints:\n    \\<^item> The correctness lemma is analogous to the one for add.\n    \\<^item> A monotonicity property on \\<open>inv'\\<close> may be useful, i.e.,\n      @{prop \\<open>inv' m is \\<Longrightarrow> inv' m' is\\<close>} if @{prop \\<open>m'\\<le>m\\<close>}\n    \\<^item> A bounding lemma, relating \\<open>m\\<close> and the elements of @{term \\<open>set_of is\\<close>}\n      if @{prop \\<open>inv' m is\\<close>}, may be useful.\n\\<close>\n\n\n\nfun del :: \"nat \\<Rightarrow> intervals \\<Rightarrow> intervals\"\nwhere\n  \"del _ _ = undefined\"\n\nlemma del_correct: \"Come up with a meaningful spec yourself\" oops\n\n\n\ntext \\<open> \\NumHomework{Addition of Interval to Interval List}{June 1}\n  For 3 \\<^bold>\\<open>bonus points\\<close>, implement and prove correct a function\n  to add a whole interval to an interval list. The runtime must\n  not depend on the size of the interval, e.g., iterating over the\n  interval and adding the elements separately is not allowed!\n\\<close>\n\nfun addi :: \"nat \\<Rightarrow> nat \\<Rightarrow> intervals \\<Rightarrow> intervals\"\nwhere\n  \"addi i j is = undefined\"\n\nlemma addi_correct:\n  assumes \"inv is\" \"i\\<le>j\"\n  shows \"inv (addi i j is)\" \"set_of (addi i j is) = {i..j} \\<union> (set_of is)\"\n  sorry\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/07/tmpl0arun7.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8670357529306639, "lm_q2_score": 0.8499711794579723, "lm_q1q2_score": 0.7369554015507075}}
{"text": "(*  Title:      ZF/Fixedpt.thy\n    Author:     Lawrence C Paulson, Cambridge University Computer Laboratory\n    Copyright   1992  University of Cambridge\n*)\n\nsection\\<open>Least and Greatest Fixed Points; the Knaster-Tarski Theorem\\<close>\n\ntheory Fixedpt imports equalities begin\n\ndefinition \n  (*monotone operator from Pow(D) to itself*)\n  bnd_mono :: \"[i,i\\<Rightarrow>i]\\<Rightarrow>o\"  where\n     \"bnd_mono(D,h) \\<equiv> h(D)<=D \\<and> (\\<forall>W X. W<=X \\<longrightarrow> X<=D \\<longrightarrow> h(W) \\<subseteq> h(X))\"\n\ndefinition \n  lfp      :: \"[i,i\\<Rightarrow>i]\\<Rightarrow>i\"  where\n     \"lfp(D,h) \\<equiv> \\<Inter>({X: Pow(D). h(X) \\<subseteq> X})\"\n\ndefinition \n  gfp      :: \"[i,i\\<Rightarrow>i]\\<Rightarrow>i\"  where\n     \"gfp(D,h) \\<equiv> \\<Union>({X: Pow(D). X \\<subseteq> h(X)})\"\n\ntext\\<open>The theorem is proved in the lattice of subsets of \\<^term>\\<open>D\\<close>, \n      namely \\<^term>\\<open>Pow(D)\\<close>, with Inter as the greatest lower bound.\\<close>\n\nsubsection\\<open>Monotone Operators\\<close>\n\nlemma bnd_monoI:\n    \"\\<lbrakk>h(D)<=D;   \n        \\<And>W X. \\<lbrakk>W<=D;  X<=D;  W<=X\\<rbrakk> \\<Longrightarrow> h(W) \\<subseteq> h(X)   \n\\<rbrakk> \\<Longrightarrow> bnd_mono(D,h)\"\nby (unfold bnd_mono_def, clarify, blast)  \n\nlemma bnd_monoD1: \"bnd_mono(D,h) \\<Longrightarrow> h(D) \\<subseteq> D\"\n  unfolding bnd_mono_def\napply (erule conjunct1)\ndone\n\nlemma bnd_monoD2: \"\\<lbrakk>bnd_mono(D,h);  W<=X;  X<=D\\<rbrakk> \\<Longrightarrow> h(W) \\<subseteq> h(X)\"\nby (unfold bnd_mono_def, blast)\n\nlemma bnd_mono_subset:\n    \"\\<lbrakk>bnd_mono(D,h);  X<=D\\<rbrakk> \\<Longrightarrow> h(X) \\<subseteq> D\"\nby (unfold bnd_mono_def, clarify, blast) \n\nlemma bnd_mono_Un:\n     \"\\<lbrakk>bnd_mono(D,h);  A \\<subseteq> D;  B \\<subseteq> D\\<rbrakk> \\<Longrightarrow> h(A) \\<union> h(B) \\<subseteq> h(A \\<union> B)\"\n  unfolding bnd_mono_def\napply (rule Un_least, blast+)\ndone\n\n(*unused*)\nlemma bnd_mono_UN:\n     \"\\<lbrakk>bnd_mono(D,h);  \\<forall>i\\<in>I. A(i) \\<subseteq> D\\<rbrakk> \n      \\<Longrightarrow> (\\<Union>i\\<in>I. h(A(i))) \\<subseteq> h((\\<Union>i\\<in>I. A(i)))\"\n  unfolding bnd_mono_def \napply (rule UN_least)\napply (elim conjE) \napply (drule_tac x=\"A(i)\" in spec)\napply (drule_tac x=\"(\\<Union>i\\<in>I. A(i))\" in spec) \napply blast \ndone\n\n(*Useful??*)\nlemma bnd_mono_Int:\n     \"\\<lbrakk>bnd_mono(D,h);  A \\<subseteq> D;  B \\<subseteq> D\\<rbrakk> \\<Longrightarrow> h(A \\<inter> B) \\<subseteq> h(A) \\<inter> h(B)\"\napply (rule Int_greatest) \napply (erule bnd_monoD2, rule Int_lower1, assumption) \napply (erule bnd_monoD2, rule Int_lower2, assumption) \ndone\n\nsubsection\\<open>Proof of Knaster-Tarski Theorem using \\<^term>\\<open>lfp\\<close>\\<close>\n\n(*lfp is contained in each pre-fixedpoint*)\nlemma lfp_lowerbound: \n    \"\\<lbrakk>h(A) \\<subseteq> A;  A<=D\\<rbrakk> \\<Longrightarrow> lfp(D,h) \\<subseteq> A\"\nby (unfold lfp_def, blast)\n\n(*Unfolding the defn of Inter dispenses with the premise bnd_mono(D,h)!*)\nlemma lfp_subset: \"lfp(D,h) \\<subseteq> D\"\nby (unfold lfp_def Inter_def, blast)\n\n(*Used in datatype package*)\nlemma def_lfp_subset:  \"A \\<equiv> lfp(D,h) \\<Longrightarrow> A \\<subseteq> D\"\napply simp\napply (rule lfp_subset)\ndone\n\nlemma lfp_greatest:  \n    \"\\<lbrakk>h(D) \\<subseteq> D;  \\<And>X. \\<lbrakk>h(X) \\<subseteq> X;  X<=D\\<rbrakk> \\<Longrightarrow> A<=X\\<rbrakk> \\<Longrightarrow> A \\<subseteq> lfp(D,h)\"\nby (unfold lfp_def, blast) \n\nlemma lfp_lemma1:  \n    \"\\<lbrakk>bnd_mono(D,h);  h(A)<=A;  A<=D\\<rbrakk> \\<Longrightarrow> h(lfp(D,h)) \\<subseteq> A\"\napply (erule bnd_monoD2 [THEN subset_trans])\napply (rule lfp_lowerbound, assumption+)\ndone\n\nlemma lfp_lemma2: \"bnd_mono(D,h) \\<Longrightarrow> h(lfp(D,h)) \\<subseteq> lfp(D,h)\"\napply (rule bnd_monoD1 [THEN lfp_greatest])\napply (rule_tac [2] lfp_lemma1)\napply (assumption+)\ndone\n\nlemma lfp_lemma3: \n    \"bnd_mono(D,h) \\<Longrightarrow> lfp(D,h) \\<subseteq> h(lfp(D,h))\"\napply (rule lfp_lowerbound)\napply (rule bnd_monoD2, assumption)\napply (rule lfp_lemma2, assumption)\napply (erule_tac [2] bnd_mono_subset)\napply (rule lfp_subset)+\ndone\n\n\n\n(*Definition form, to control unfolding*)\nlemma def_lfp_unfold:\n    \"\\<lbrakk>A\\<equiv>lfp(D,h);  bnd_mono(D,h)\\<rbrakk> \\<Longrightarrow> A = h(A)\"\napply simp\napply (erule lfp_unfold)\ndone\n\nsubsection\\<open>General Induction Rule for Least Fixedpoints\\<close>\n\nlemma Collect_is_pre_fixedpt:\n    \"\\<lbrakk>bnd_mono(D,h);  \\<And>x. x \\<in> h(Collect(lfp(D,h),P)) \\<Longrightarrow> P(x)\\<rbrakk>\n     \\<Longrightarrow> h(Collect(lfp(D,h),P)) \\<subseteq> Collect(lfp(D,h),P)\"\nby (blast intro: lfp_lemma2 [THEN subsetD] bnd_monoD2 [THEN subsetD] \n                 lfp_subset [THEN subsetD]) \n\n(*This rule yields an induction hypothesis in which the components of a\n  data structure may be assumed to be elements of lfp(D,h)*)\nlemma induct:\n    \"\\<lbrakk>bnd_mono(D,h);  a \\<in> lfp(D,h);                    \n        \\<And>x. x \\<in> h(Collect(lfp(D,h),P)) \\<Longrightarrow> P(x)         \n\\<rbrakk> \\<Longrightarrow> P(a)\"\napply (rule Collect_is_pre_fixedpt\n              [THEN lfp_lowerbound, THEN subsetD, THEN CollectD2])\napply (rule_tac [3] lfp_subset [THEN Collect_subset [THEN subset_trans]], \n       blast+)\ndone\n\n(*Definition form, to control unfolding*)\nlemma def_induct:\n    \"\\<lbrakk>A \\<equiv> lfp(D,h);  bnd_mono(D,h);  a:A;    \n        \\<And>x. x \\<in> h(Collect(A,P)) \\<Longrightarrow> P(x)  \n\\<rbrakk> \\<Longrightarrow> P(a)\"\nby (rule induct, blast+)\n\n(*This version is useful when \"A\" is not a subset of D\n  second premise could simply be h(D \\<inter> A) \\<subseteq> D or \\<And>X. X<=D \\<Longrightarrow> h(X)<=D *)\nlemma lfp_Int_lowerbound:\n    \"\\<lbrakk>h(D \\<inter> A) \\<subseteq> A;  bnd_mono(D,h)\\<rbrakk> \\<Longrightarrow> lfp(D,h) \\<subseteq> A\" \napply (rule lfp_lowerbound [THEN subset_trans])\napply (erule bnd_mono_subset [THEN Int_greatest], blast+)\ndone\n\n(*Monotonicity of lfp, where h precedes i under a domain-like partial order\n  monotonicity of h is not strictly necessary; h must be bounded by D*)\nlemma lfp_mono:\n  assumes hmono: \"bnd_mono(D,h)\"\n      and imono: \"bnd_mono(E,i)\"\n      and subhi: \"\\<And>X. X<=D \\<Longrightarrow> h(X) \\<subseteq> i(X)\"\n    shows \"lfp(D,h) \\<subseteq> lfp(E,i)\"\napply (rule bnd_monoD1 [THEN lfp_greatest])\napply (rule imono)\napply (rule hmono [THEN [2] lfp_Int_lowerbound])\napply (rule Int_lower1 [THEN subhi, THEN subset_trans])\napply (rule imono [THEN bnd_monoD2, THEN subset_trans], auto) \ndone\n\n(*This (unused) version illustrates that monotonicity is not really needed,\n  but both lfp's must be over the SAME set D;  Inter is anti-monotonic!*)\nlemma lfp_mono2:\n    \"\\<lbrakk>i(D) \\<subseteq> D;  \\<And>X. X<=D \\<Longrightarrow> h(X) \\<subseteq> i(X)\\<rbrakk> \\<Longrightarrow> lfp(D,h) \\<subseteq> lfp(D,i)\"\napply (rule lfp_greatest, assumption)\napply (rule lfp_lowerbound, blast, assumption)\ndone\n\nlemma lfp_cong:\n     \"\\<lbrakk>D=D'; \\<And>X. X \\<subseteq> D' \\<Longrightarrow> h(X) = h'(X)\\<rbrakk> \\<Longrightarrow> lfp(D,h) = lfp(D',h')\"\napply (simp add: lfp_def)\napply (rule_tac t=Inter in subst_context)\napply (rule Collect_cong, simp_all) \ndone \n\n\nsubsection\\<open>Proof of Knaster-Tarski Theorem using \\<^term>\\<open>gfp\\<close>\\<close>\n\n(*gfp contains each post-fixedpoint that is contained in D*)\nlemma gfp_upperbound: \"\\<lbrakk>A \\<subseteq> h(A);  A<=D\\<rbrakk> \\<Longrightarrow> A \\<subseteq> gfp(D,h)\"\n  unfolding gfp_def\napply (rule PowI [THEN CollectI, THEN Union_upper])\napply (assumption+)\ndone\n\nlemma gfp_subset: \"gfp(D,h) \\<subseteq> D\"\nby (unfold gfp_def, blast)\n\n(*Used in datatype package*)\nlemma def_gfp_subset: \"A\\<equiv>gfp(D,h) \\<Longrightarrow> A \\<subseteq> D\"\napply simp\napply (rule gfp_subset)\ndone\n\nlemma gfp_least: \n    \"\\<lbrakk>bnd_mono(D,h);  \\<And>X. \\<lbrakk>X \\<subseteq> h(X);  X<=D\\<rbrakk> \\<Longrightarrow> X<=A\\<rbrakk> \\<Longrightarrow>  \n     gfp(D,h) \\<subseteq> A\"\n  unfolding gfp_def\napply (blast dest: bnd_monoD1) \ndone\n\nlemma gfp_lemma1: \n    \"\\<lbrakk>bnd_mono(D,h);  A<=h(A);  A<=D\\<rbrakk> \\<Longrightarrow> A \\<subseteq> h(gfp(D,h))\"\napply (rule subset_trans, assumption)\napply (erule bnd_monoD2)\napply (rule_tac [2] gfp_subset)\napply (simp add: gfp_upperbound)\ndone\n\nlemma gfp_lemma2: \"bnd_mono(D,h) \\<Longrightarrow> gfp(D,h) \\<subseteq> h(gfp(D,h))\"\napply (rule gfp_least)\napply (rule_tac [2] gfp_lemma1)\napply (assumption+)\ndone\n\nlemma gfp_lemma3: \n    \"bnd_mono(D,h) \\<Longrightarrow> h(gfp(D,h)) \\<subseteq> gfp(D,h)\"\napply (rule gfp_upperbound)\napply (rule bnd_monoD2, assumption)\napply (rule gfp_lemma2, assumption)\napply (erule bnd_mono_subset, rule gfp_subset)+\ndone\n\nlemma gfp_unfold: \"bnd_mono(D,h) \\<Longrightarrow> gfp(D,h) = h(gfp(D,h))\"\napply (rule equalityI) \napply (erule gfp_lemma2) \napply (erule gfp_lemma3) \ndone\n\n(*Definition form, to control unfolding*)\nlemma def_gfp_unfold:\n    \"\\<lbrakk>A\\<equiv>gfp(D,h);  bnd_mono(D,h)\\<rbrakk> \\<Longrightarrow> A = h(A)\"\napply simp\napply (erule gfp_unfold)\ndone\n\n\nsubsection\\<open>Coinduction Rules for Greatest Fixed Points\\<close>\n\n(*weak version*)\nlemma weak_coinduct: \"\\<lbrakk>a: X;  X \\<subseteq> h(X);  X \\<subseteq> D\\<rbrakk> \\<Longrightarrow> a \\<in> gfp(D,h)\"\nby (blast intro: gfp_upperbound [THEN subsetD])\n\nlemma coinduct_lemma:\n    \"\\<lbrakk>X \\<subseteq> h(X \\<union> gfp(D,h));  X \\<subseteq> D;  bnd_mono(D,h)\\<rbrakk> \\<Longrightarrow>   \n     X \\<union> gfp(D,h) \\<subseteq> h(X \\<union> gfp(D,h))\"\napply (erule Un_least)\napply (rule gfp_lemma2 [THEN subset_trans], assumption)\napply (rule Un_upper2 [THEN subset_trans])\napply (rule bnd_mono_Un, assumption+) \napply (rule gfp_subset)\ndone\n\n(*strong version*)\nlemma coinduct:\n     \"\\<lbrakk>bnd_mono(D,h);  a: X;  X \\<subseteq> h(X \\<union> gfp(D,h));  X \\<subseteq> D\\<rbrakk>\n      \\<Longrightarrow> a \\<in> gfp(D,h)\"\napply (rule weak_coinduct)\napply (erule_tac [2] coinduct_lemma)\napply (simp_all add: gfp_subset Un_subset_iff) \ndone\n\n(*Definition form, to control unfolding*)\nlemma def_coinduct:\n    \"\\<lbrakk>A \\<equiv> gfp(D,h);  bnd_mono(D,h);  a: X;  X \\<subseteq> h(X \\<union> A);  X \\<subseteq> D\\<rbrakk> \\<Longrightarrow>  \n     a \\<in> A\"\napply simp\napply (rule coinduct, assumption+)\ndone\n\n(*The version used in the induction/coinduction package*)\nlemma def_Collect_coinduct:\n    \"\\<lbrakk>A \\<equiv> gfp(D, \\<lambda>w. Collect(D,P(w)));  bnd_mono(D, \\<lambda>w. Collect(D,P(w)));   \n        a: X;  X \\<subseteq> D;  \\<And>z. z: X \\<Longrightarrow> P(X \\<union> A, z)\\<rbrakk> \\<Longrightarrow>  \n     a \\<in> A\"\napply (rule def_coinduct, assumption+, blast+)\ndone\n\n(*Monotonicity of gfp!*)\nlemma gfp_mono:\n    \"\\<lbrakk>bnd_mono(D,h);  D \\<subseteq> E;                  \n        \\<And>X. X<=D \\<Longrightarrow> h(X) \\<subseteq> i(X)\\<rbrakk> \\<Longrightarrow> gfp(D,h) \\<subseteq> gfp(E,i)\"\napply (rule gfp_upperbound)\napply (rule gfp_lemma2 [THEN subset_trans], assumption)\napply (blast del: subsetI intro: gfp_subset) \napply (blast del: subsetI intro: subset_trans gfp_subset) \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/Fixedpt.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8499711756575749, "lm_q2_score": 0.8670357563664174, "lm_q1q2_score": 0.7369554011759184}}
{"text": "section \\<open>Function \\textit{isin} for Search_Tree2\\<close>\n\ntheory Isin2\nimports\n  Search_Tree2\n  Cmp\n  Set_Specs\nbegin\n\nfun isin :: \"('a::linorder*'b) search_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: search_tree2_induct) (auto simp: isin_simps)\n\nlemma isin_set_tree: \"bst t \\<Longrightarrow> isin t x \\<longleftrightarrow> x \\<in> set_search_tree t\"\nby(induction t rule: search_tree2_induct) auto\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/Isin2.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8962513731336202, "lm_q2_score": 0.8221891370573388, "lm_q1q2_score": 0.7368881430631862}}
{"text": "theory Counting_Tiles\n  imports\n    \"HOL-Library.Code_Target_Numeral\"\n    \"HOL-Library.Product_Lexorder\"\n    \"HOL-Library.RBT_Mapping\"\n    \"../state_monad/State_Main\" \n    Example_Misc\nbegin\n\nsubsection \\<open>A Counting Problem\\<close>\n\ntext \\<open>\n  This formalization contains verified solutions for Project Euler problems\n    \\<^item> \\<open>#\\<close>114 (\\<^url>\\<open>https://projecteuler.net/problem=114\\<close>) and\n    \\<^item> \\<open>#\\<close>115 (\\<^url>\\<open>https://projecteuler.net/problem=115\\<close>).\n\n  This is the problem description for \\<open>#\\<close>115:\n  \\begin{quote}\n  A row measuring n units in length has red blocks with a minimum length of m units placed on it,\n  such that any two red blocks (which are allowed to be different lengths) are separated\n  by at least one black square.\n  Let the fill-count function, F(m, n), represent the number of ways that a row can be filled.\n\n  For example, F(3, 29) = 673135 and F(3, 30) = 1089155.\n\n  That is, for m = 3, it can be seen that n = 30 is the smallest value for which the fill-count\n  function first exceeds one million.\n  In the same way, for m = 10, it can be verified that F(10, 56) = 880711 and F(10, 57) = 1148904,\n  so n = 57 is the least value for which the fill-count function first exceeds one million.\n\n  For m = 50, find the least value of n for which the fill-count function first exceeds one million.\n  \\end{quote}\n\\<close>\n\nsubsubsection \\<open>Misc\\<close>\n\n(* Duplicate from Refine_Misc with slightly nicer proof *)\n\n\n(* Duplicate from Refine_Misc *)\nlemma disjE1:\n  \"A \\<or> B \\<Longrightarrow> (A \\<Longrightarrow> P) \\<Longrightarrow> (\\<not> A \\<Longrightarrow> B \\<Longrightarrow> P) \\<Longrightarrow> P\"\n  by metis\n\n\nsubsubsection \\<open>Problem Specification\\<close>\n\ntext \\<open>Colors\\<close>\n\ndatatype color = R | B\n\ntext \\<open>Direct natural definition of a valid line\\<close>\n\ncontext\n  fixes m :: nat\nbegin\n\ninductive valid where\n  \"valid []\" |\n  \"valid xs \\<Longrightarrow> valid (B # xs)\" |\n  \"valid xs \\<Longrightarrow> n \\<ge> m \\<Longrightarrow> valid (replicate n R @ xs)\"\n\ntext \\<open>Definition of the fill-count function\\<close>\n\ndefinition \"F n = card {l. length l = n \\<and> valid l}\"\n\n\nsubsubsection \\<open>Combinatorial Identities\\<close>\n\ntext \\<open>This alternative variant helps us to prove the split lemma below.\\<close>\ninductive valid' where\n  \"valid' []\" |\n  \"n \\<ge> m \\<Longrightarrow> valid' (replicate n R)\" |\n  \"valid' xs \\<Longrightarrow> valid' (B # xs)\" |\n  \"valid' xs \\<Longrightarrow> n \\<ge> m \\<Longrightarrow> valid' (replicate n R @ B # xs)\"\n\nlemma 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\nlemmas valid_red = valid.intros(3)[OF valid.intros(1), simplified]\n\nlemma valid'_valid:\n  \"valid' l \\<Longrightarrow> valid l\"\n  by (induction rule: valid'.induct) (auto intro: valid.intros valid_red)\n\nlemma valid_eq_valid':\n  \"valid' l = valid l\"\n  using valid_valid' valid'_valid by metis\n\n\ntext \\<open>Additional Facts on Replicate\\<close>\n\nlemma 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\nlemma 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\nlemma 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\ntext \\<open>Main Case Analysis on \\<open>@term valid\\<close>\\<close>\n\nlemma valid_split:\n  \"valid l \\<longleftrightarrow>\n    l = [] \\<or>\n    (l!0 = B \\<and> valid (tl l)) \\<or>\n    length l \\<ge> m \\<and> (\\<forall> i < length l. l ! i = R) \\<or>\n    (\\<exists> j < length l. j \\<ge> m \\<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    apply (auto intro: valid'.intros simp: replicate_iff elim!: disjE1)\n      apply (fastforce intro: valid'.intros simp: neq_Nil_conv)\n     apply (subst (asm) replicate_iff2; fastforce intro: valid'.intros simp: neq_Nil_conv nth_append)+\n    done\n  done\n\n\ntext \\<open>Base cases\\<close>\n\nlemma valid_line_just_B:\n  \"valid (replicate n B)\"\n  by (induction n) (auto intro: valid.intros)\n\nlemma F_base_0_aux:\n  \"{l. l = [] \\<and> valid l} = {[]}\"\n  by (auto intro: valid.intros)\n\nlemma F_base_0: \"F 0 = 1\"\n  by (auto simp: F_base_0_aux F_def)\n\nlemma F_base_aux: \"{l. length l=n \\<and> valid l} = {replicate n B}\" if \"n > 0\" \"n < m\"\n  using that\nproof (induction n)\n  case 0\n  then show ?case\n    by simp\nnext\n  case (Suc n)\n  show ?case\n  proof (cases \"n = 0\")\n    case True\n    with Suc.prems show ?thesis\n      by (auto intro: valid.intros elim: valid.cases)\n  next\n    case False\n    with Suc.prems show ?thesis\n      apply safe\n      using Suc.IH\n        apply -\n        apply (erule valid.cases)\n          apply (auto intro: valid.intros elim: valid.cases)\n      done\n  qed\nqed\n\nlemma F_base_1:\n  \"F n = 1\" if \"n > 0\" \"n < m\"\n  using that unfolding F_def by (simp add: F_base_aux)\n\nlemma valid_m_Rs [simp]:\n  \"valid (replicate m R)\"\n  using valid_red[of m, simplified] by simp\n\nlemma F_base_aux_2: \"{l. length l=m \\<and> valid l} = {replicate m R, replicate m B}\"\n  apply (auto simp: valid_line_just_B)\n  apply (erule Counting_Tiles.valid.cases)\n    apply auto\n  subgoal for xs\n    using F_base_aux[of \"length xs\"] by (cases \"xs = []\") auto\n  done\n\nlemma F_base_2:\n  \"F m = 2\" if \"0 < m\"\n  using that unfolding F_def by (simp add: F_base_aux_2)\n\n\ntext \\<open>The recursion case\\<close>\n\nlemma finite_valid_length:\n  \"finite {l. length l = n \\<and> valid l}\" (is \"finite ?S\")\nproof -\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)\nqed\n\nlemma 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\nlemma 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'\nproof -\n  have \"?l ! x = B\" \"?r ! x = R\"\n    using that by (auto simp: nth_append)\n  then show ?thesis\n    by auto\nqed\n\nlemma valid_prepend_B_iff:\n  \"valid (B # xs) \\<longleftrightarrow> valid xs\" if \"m > 0\"\n  using that\n  by (auto 4 3 intro: valid.intros elim: valid.cases simp: Cons_replicate_eq Cons_eq_append_conv)\n\nlemma F_rec: \"F n = F (n-1) + 1 + (\\<Sum>i=m..<n. F (n-i-1))\" if \\<open>n>m\\<close> \"m > 0\"\nproof -\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> m \\<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 > m\\<close> by (subst valid_split) auto\n\n  let ?B1 = \"((#) B) ` {l. length l = n - Suc 0 \\<and> valid l}\"\n  from \\<open>n > m\\<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 = F (n-1)\"\n    unfolding F_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> {m..<n}. (\\<lambda> l. replicate i R @ B # l)` {l. length l = n - i - 1 \\<and> valid l})\"\n  have \"?D =\n        (\\<Union>i \\<in> {m..<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\" 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 \"m \\<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=m..<n. F (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: F_def card_image[OF inj])\n    qed\n  qed (auto intro: finite_subset[OF _ finite_valid_length])\n\n  show ?thesis\n    apply (subst F_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 using \\<open>m > 0\\<close> by (auto simp: Cons_replicate_eq Cons_eq_append_conv)\nqed\n\n\nsubsubsection \\<open>Computing the Fill-Count Function\\<close>\n\nfun lcount :: \"nat \\<Rightarrow> nat\" where\n  \"lcount n = (\n    if n < m then 1\n    else if n = m then 2\n    else lcount (n - 1) + 1 + (\\<Sum>i \\<leftarrow> [m..<n]. lcount (n - i - 1))\n  )\"\n\nlemmas [simp del] = lcount.simps\n\nlemma lcount_correct:\n  \"lcount n = F n\" if \"m > 0\"\nproof (induction n rule: less_induct)\n  case (less n)\n  from \\<open>m > 0\\<close> show ?case\n    apply (cases \"n = 0\")\n    subgoal\n      by (simp add: lcount.simps F_base_0)\n    by (subst lcount.simps)\n      (simp add: less.IH F_base_1 F_base_2 F_rec interv_sum_list_conv_sum_set_nat)\nqed\n\n\nsubsubsection \\<open>Memoization\\<close>\n\nmemoize_fun lcount\\<^sub>m: lcount with_memory dp_consistency_mapping monadifies (state) lcount.simps\n\nmemoize_correct\n  by memoize_prover\n\nlemmas [code] = lcount\\<^sub>m.memoized_correct\n\nend (* Fixed block size *)\n\n\nsubsubsection \\<open>Problem solutions\\<close>\n\ntext \\<open>Example and solution for problem \\<open>#\\<close>114\\<close>\nvalue \"lcount 3 7\"\nvalue \"lcount 3 50\"\n\ntext \\<open>Examples for problem \\<open>#\\<close>115\\<close>\nvalue \"lcount 3 29\"\nvalue \"lcount 3 30\"\nvalue \"lcount 10 56\"\nvalue \"lcount 10 57\"\n\ntext \\<open>Binary search for the solution of problem \\<open>#\\<close>115\\<close>\nvalue \"lcount 50 100\"\nvalue \"lcount 50 150\"\nvalue \"lcount 50 163\"\nvalue \"lcount 50 166\"\nvalue \"lcount 50 167\"\nvalue \"lcount 50 168\" \\<comment> \\<open>The solution\\<close>\nvalue \"lcount 50 169\"\nvalue \"lcount 50 175\"\nvalue \"lcount 50 200\"\nvalue \"lcount 50 300\"\nvalue \"lcount 50 500\"\nvalue \"lcount 50 1000\"\n\ntext \\<open>We prove that 168 is the solution for problem \\<open>#\\<close>115\\<close>\ntheorem\n  \"(LEAST n. F 50 n > 1000000) = 168\"\nproof -\n  have \"lcount 50 168 > 1000000\"\n    by eval\n  moreover have \"\\<forall> n \\<in> {0..<168}. lcount 50 n < 1000000\"\n    by eval\n  ultimately show ?thesis\n    by - (rule Least_equality; rule ccontr; force simp: not_le lcount_correct)\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/Monad_Memo_DP/example/Counting_Tiles.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8962513842182775, "lm_q2_score": 0.8221891261650247, "lm_q1q2_score": 0.7368881424146194}}
{"text": "theory Ch2\nimports Complex_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 a (add b c) = add (add a b) c\"\n  apply(induction a)\n  apply(auto)\ndone\n\nlemma add_n_0 [simp]: \"add n 0 = n\"\n  apply(induction n)\n  apply(auto)\ndone\n\nlemma add_n_suc [simp]: \"add n (Suc m) = Suc (add n m)\"\n  apply(induction n)\n  apply(auto)\ndone\n\ntheorem add_comm [simp]: \"add a b = add b a\"\n  apply(induction a)\n  apply(auto)\ndone\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 n = n + n\"\n  apply(induction n)\n  apply(auto)\ndone\n\n(* 2.3 *)\nfun count :: \"'a \\<Rightarrow> 'a list \\<Rightarrow> nat\" where\n  \"count x [] = 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)\ndone\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 (x # xs) = snoc (reverse xs) x\"\n\nlemma reverse_snoc [simp]: \"reverse (snoc xs a) = a # 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(* 2.5 *)\nfun sum_upto :: \"nat \\<Rightarrow> nat\" where\n  \"sum_upto 0 = 0\" |\n  \"sum_upto n = n + sum_upto (n - 1)\"\n\ntheorem sum_upto_nn1d2 [simp]: \"sum_upto n = n * (n + 1) div 2\"\n  apply(induction n)\n  apply(auto)\ndone\n\n(* 2.6 *)\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\nfun contents :: \"'a tree \\<Rightarrow> 'a list\" where\n  \"contents Tip = []\" |\n  \"contents (Node l x r) = x # contents l @ contents r\"\n\nfun sum_tree :: \"nat tree \\<Rightarrow> nat\" where\n  \"sum_tree Tip = 0\" |\n  \"sum_tree (Node l x r) = x + sum_tree l + sum_tree r\"\n\ntheorem sum_tree_sum_list_contents [simp]: \"sum_tree t = sum_list (contents t)\"\n  apply(induction t)\n  apply(auto)\ndone\n\n(* 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\ntheorem pre_order_rev_post_order [simp]: \"pre_order (mirror t) = rev (post_order t)\"\n  apply(induction t)\n  apply(auto)\ndone\n\n(* 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 # intersperse a (x2 # xs)\"\n\ntheorem map_intersperse_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)\ndone\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\ntheorem itadd_add [simp]: \"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 nodes_explode [simp]: \"nodes (explode n t) = (nodes t + 1) * 2 ^ n - 1\"\n  apply(induction n arbitrary: t)\n  apply(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 v = v\" |\n  \"eval (Const c) _ = c\" |\n  \"eval (Add e1 e2) v = eval e1 v + eval e2 v\" |\n  \"eval (Mult e1 e2) v = eval e1 v * eval e2 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 addp :: \"int list \\<Rightarrow> int list \\<Rightarrow> int list\" where\n  \"addp [] ys = ys\" |\n  \"addp xs [] = xs\" |\n  \"addp (x # xs) (y # ys) = (x + y) # addp xs ys\"\n\nfun mults :: \"int \\<Rightarrow> int list \\<Rightarrow> int list\" where\n  \"mults s [] = []\" |\n  \"mults s (x # xs) = s * x # mults s xs\"\n\nfun multp :: \"int list \\<Rightarrow> int list \\<Rightarrow> int list\" where\n  \"multp [] _ = []\" |\n  \"multp _ [] = []\" |\n  \"multp (x # xs) ys = addp (mults x ys) (0 # multp 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) = addp (coeffs e1) (coeffs e2)\" |\n  \"coeffs (Mult e1 e2) = multp (coeffs e1) (coeffs e2)\"\n\nlemma evalp_addp [simp]: \"evalp (addp xs ys) v = evalp xs v + evalp ys v\"\n  apply(induction xs ys rule: addp.induct)\n  apply(auto simp add: algebra_simps)\ndone\n\nlemma addp_nil [simp]: \"addp xs [] = xs\"\n  apply(induction xs)\n  apply(auto)\ndone\n\nlemma multp_mults [simp]: \"multp [x] ys = mults x ys\"\n  apply(induction ys)\n  apply(auto simp add: algebra_simps)\ndone\n\nlemma evalp_mults [simp]: \"evalp (mults x ys) v = x * evalp ys v\"\n  apply(induction ys)\n  apply(auto simp add: algebra_simps)\ndone\n\nlemma evalp_multp_cons [simp]: \"evalp (multp (x # xs) ys) v = x * evalp ys v + v * evalp (multp xs ys) v\"\n  apply(induction xs ys rule: multp.induct)\n  apply(auto simp add: algebra_simps)\ndone\n\nlemma evalp_multp [simp]: \"evalp (multp xs ys) v = evalp xs v * evalp ys v\"\n  apply(induction xs arbitrary: ys)\n  apply(auto simp add: algebra_simps)\ndone\n\ntheorem evalp_coeffs [simp]: \"evalp (coeffs e) x = eval e x\"\n  apply(induction e rule: coeffs.induct)\n  apply(auto simp add: algebra_simps)\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/Ch2.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513842182777, "lm_q2_score": 0.822189121808099, "lm_q1q2_score": 0.7368881385097188}}
{"text": "theory General_Operations \n  imports \"HOL-Analysis.Sigma_Algebra\"\nbegin\n\nsection \"Basics from Measure Theory\"\n\nsubsection \"Sets\"\n\nsubsubsection \"Set Operations\"\n\ndefinition disjoint :: \"'a set \\<Rightarrow> 'a set \\<Rightarrow> bool\"\n  where \"disjoint A B \\<equiv> \\<not>(\\<exists>x. x\\<in>A \\<and> x\\<in>B)\"\n\nlemma disj_iff_empty_inter: \"(disjoint A B) = (A \\<inter> B = {})\"\n  by (simp add: disjoint_def disjoint_iff)\n\n(* Power set is Pow. *)\n\ndefinition non_decreasing :: \"(nat \\<Rightarrow> 'a set) \\<Rightarrow> bool\"\n  where \"non_decreasing A\\<^sub>n \\<equiv> \\<forall>n. A\\<^sub>n n \\<subseteq> A\\<^sub>n (n + 1)\"\n\nlemma non_decreasing_multistep: \n  assumes non_dec: \"non_decreasing A\\<^sub>n\"\n      and leq: \"n \\<le> m\"\n    shows \"A\\<^sub>n n \\<subseteq> A\\<^sub>n m\"\nproof - \n  have \"\\<forall>n y. y \\<in> A\\<^sub>n n \\<longrightarrow> y \\<in> A\\<^sub>n (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\\<^sub>n n \\<subseteq> A\\<^sub>n (n+d))\" \n      using add.commute le_add2 lift_Suc_mono_le subset_iff by metis\n  thus \"A\\<^sub>n n \\<subseteq> A\\<^sub>n m\"\n    by (metis bot_nat_0.extremum le_iff_add leq)\nqed \n\nlemma non_decreasing_stay_in: \n  assumes non_dec: \"non_decreasing A\\<^sub>n\"\n      and base: \"x \\<in> A\\<^sub>n n\"\n    shows \"\\<forall>m\\<ge>n. x \\<in> A\\<^sub>n m\"\n  using base non_dec non_decreasing_multistep by auto\n\ndefinition non_increasing :: \"(nat \\<Rightarrow> 'a set) \\<Rightarrow> bool\"\n  where \"non_increasing A\\<^sub>n \\<equiv> \\<forall>n. A\\<^sub>n (n + 1) \\<subseteq> A\\<^sub>n n\"\n\nlemma non_increasing_multistep: \n  assumes non_inc: \"non_increasing A\\<^sub>n\"\n      and leq: \"n \\<le> m\"\n    shows \"A\\<^sub>n m \\<subseteq> A\\<^sub>n n\"\nproof - \n  have \"\\<forall>n y. y \\<in> A\\<^sub>n (Suc n) \\<longrightarrow> y \\<in> A\\<^sub>n n\"\n    using non_inc non_increasing_def Suc_eq_plus1 subset_iff by metis\n  hence \"\\<forall>n. \\<forall>d\\<ge>0. (A\\<^sub>n (n+d) \\<subseteq> A\\<^sub>n n)\" \n      using add.commute le_add2 subset_iff lift_Suc_antimono_le by metis \n  thus \"A\\<^sub>n m \\<subseteq> A\\<^sub>n n\"\n    by (metis bot_nat_0.extremum le_iff_add leq)\nqed \n\nlemma non_increasing_stay_out: \n  assumes non_inc: \"non_increasing A\\<^sub>n\"\n      and base: \"x \\<notin> A\\<^sub>n n\"\n    shows \"\\<forall>m\\<ge>n. x \\<notin> A\\<^sub>n m\"\n  using base non_inc non_increasing_multistep by auto\n\n\ndefinition general_union :: \"'a set set \\<Rightarrow> 'a set\"\n  where \"general_union A = {x. \\<exists>S. S \\<in> A \\<and> x \\<in> S}\"\n\nlemma notin_general_union:\n  assumes x_notin: \"x \\<notin> general_union A\"\n  shows \"\\<forall>S\\<in>A. x \\<notin> S\"\n  using x_notin general_union_def by fastforce\n\nlemma general_union_empty: \"general_union {} = {}\"\nproof - \n  have \"\\<not>(\\<exists>x. x \\<in> {y. \\<exists>A. A \\<in> {} \\<and> y \\<in> A})\"\n    by simp\n  hence \"\\<not>(\\<exists>x. x \\<in> general_union {})\"\n    using general_union_def by metis \n  thus ?thesis\n    by simp \nqed \n\nlemma general_union_singleton: \"general_union {A} = A\"\n  by (simp add: general_union_def)\n\nlemma general_union_binary: \n  \"general_union {A, B} = A \\<union> B\"\nproof - \n  have \"general_union {A, B} = {x. \\<exists>S. S \\<in> {A, B} \\<and> x \\<in> S}\"\n    by (simp add: general_union_def)\n  hence \"general_union {A, B} = {x. x \\<in> A \\<or> x \\<in> B}\"\n    by fast \n  thus ?thesis\n    by auto \nqed\n\nlemma general_union_UNIV: \"general_union UNIV = UNIV\"\n  using general_union_def by fast \n\nlemma general_union_sequence: \"general_union {A. \\<exists>n. A = A\\<^sub>n n} =\n                                      {x. \\<exists>n. x \\<in> A\\<^sub>n n}\"\nproof \n  show \"general_union {A. \\<exists>n. A = A\\<^sub>n n} \\<subseteq> {x. \\<exists>n. x \\<in> A\\<^sub>n n}\"\n  proof \n    fix x \n    assume \"x \\<in> general_union {A. \\<exists>n. A = A\\<^sub>n n}\"\n    hence \"\\<exists>S. S \\<in> {A. \\<exists>n. A = A\\<^sub>n n} \\<and> x \\<in> S\"\n      by (simp add: general_union_def)\n    thus \"x \\<in> {x. \\<exists>n. x \\<in> A\\<^sub>n n}\"  \n      by auto \n  qed\nnext \n  show \"{x. \\<exists>n. x \\<in> A\\<^sub>n n} \\<subseteq> general_union {A. \\<exists>n. A = A\\<^sub>n n}\"\n  proof \n    fix x \n    assume \"x \\<in> {x. \\<exists>n. x \\<in> A\\<^sub>n n}\"\n    hence \"\\<exists>S. S \\<in> {A. \\<exists>n. A = A\\<^sub>n n} \\<and> x \\<in> S\"\n      by auto \n    thus \"x \\<in> general_union {A. \\<exists>n. A = A\\<^sub>n n}\"\n      by (simp add: general_union_def)\n  qed\nqed \n\n\ndefinition general_intersection :: \"'a set set \\<Rightarrow> 'a set\"\n  where \"general_intersection A = {x. \\<forall>S. S \\<in> A \\<longrightarrow> x \\<in> S}\"\n\nlemma general_intersection_binary: \n  \"general_intersection {A, B} = A \\<inter> B\"\nproof - \n  have \"general_intersection {A, B} = {x. \\<forall>S. S \\<in> {A, B} \\<longrightarrow> x \\<in> S}\"\n    by (simp add: general_intersection_def)\n  hence \"general_intersection {A, B} = {x. x \\<in> A \\<and> x \\<in> B}\"\n    by fast \n  thus ?thesis\n    by auto \nqed\n\nlemma notin_general_intersection:\n  shows \"(x \\<notin> general_intersection A) = (\\<exists>S\\<in>A. x \\<notin> S)\"\n  using general_intersection_def by fast \n\nlemma general_intersection_empty: \"general_intersection {} = UNIV\"\nproof - \n  have \"\\<not>(\\<exists>x. x \\<notin> {y. \\<forall>A. A \\<in> {} \\<longrightarrow> y \\<in> A})\"\n    by simp\n  hence \"\\<not>(\\<exists>x. x \\<notin> general_intersection {})\"\n    using general_intersection_def by metis \n  thus ?thesis\n    by auto  \nqed \n\nlemma general_intersection_singleton: \"general_intersection {A} = A\"\n  by (simp add: general_intersection_def)\n\nlemma general_intersection_UNIV: \"general_intersection UNIV = {}\"\nproof -  \n  have \"\\<forall>x. x \\<notin> {y. \\<forall>A. A \\<in> UNIV \\<longrightarrow> y \\<in> A}\" \n    by auto \n  hence \"\\<forall>x. x \\<notin> general_intersection UNIV\"\n    using general_intersection_def by metis\n  thus ?thesis\n    by simp \nqed\n\nlemma general_intersection_sequence: \"general_intersection {A. \\<exists>n. A = A\\<^sub>n n} =\n                                      {x. \\<forall>n. x \\<in> A\\<^sub>n n}\"\nproof \n  show \"general_intersection {A. \\<exists>n. A = A\\<^sub>n n} \\<subseteq> {x. \\<forall>n. x \\<in> A\\<^sub>n n}\"\n  proof \n    fix x \n    assume \"x \\<in> general_intersection {A. \\<exists>n. A = A\\<^sub>n n}\"\n    hence \"\\<forall>S. S \\<in> {A. \\<exists>n. A = A\\<^sub>n n} \\<longrightarrow> x \\<in> S\"\n      by (simp add: general_intersection_def)\n    thus \"x \\<in> {x. \\<forall>n. x \\<in> A\\<^sub>n n}\"  \n      by auto \n  qed\nnext \n  show \"{x. \\<forall>n. x \\<in> A\\<^sub>n n} \\<subseteq> general_intersection {A. \\<exists>n. A = A\\<^sub>n n}\"\n  proof \n    fix x \n    assume \"x \\<in> {x. \\<forall>n. x \\<in> A\\<^sub>n n}\"\n    hence \"\\<forall>S. S \\<in> {A. \\<exists>n. A = A\\<^sub>n n} \\<longrightarrow> x \\<in> S\"\n      by auto \n    thus \"x \\<in> general_intersection {A. \\<exists>n. A = A\\<^sub>n n}\"\n      by (simp add: general_intersection_def)\n  qed\nqed \n\n\n(* The union/intersection of a set collection is a subset of any set that all members belong to.*)\nlemma collection_union_subseq: \n  assumes subseq: \"\\<forall>A\\<in>\\<A>. A \\<subseteq> \\<Omega>\" \n  shows \"general_union \\<A> \\<subseteq> \\<Omega>\"\nproof \n  fix x \n  assume \"x \\<in> general_union \\<A>\"\n  hence \"\\<exists>S. S \\<in> \\<A> \\<and> x \\<in> S\"\n    by (simp add: general_union_def)\n  then obtain S where \"S \\<in> \\<A> \\<and> x \\<in> S\"\n    by fast \n  moreover have \"S \\<subseteq> \\<Omega>\"\n    by (simp add: calculation subseq)\n  ultimately show \"x \\<in> \\<Omega>\"\n    by auto \nqed \n\nlemma collection_inter_subseq: \n  assumes subseq: \"\\<forall>A\\<in>\\<A>. A \\<subseteq> \\<Omega>\"\n      and non_empty: \"\\<A> \\<noteq> {}\"\n  shows \"general_intersection \\<A> \\<subseteq> \\<Omega>\"\nproof \n  fix x \n  assume x_in_inter: \"x \\<in> general_intersection \\<A>\"\n  hence \"\\<forall>S. S \\<in> \\<A> \\<longrightarrow> x \\<in> S\"\n    by (simp add: general_intersection_def)\n  then obtain S where \"S \\<in> \\<A> \\<and> x \\<in> S\"\n    using non_empty by fast\n  moreover have \"S \\<subseteq> \\<Omega>\"\n    by (simp add: calculation subseq)\n  ultimately show \"x \\<in> \\<Omega>\"\n    by auto\nqed \n\n\ndefinition set_complement :: \"'a set \\<Rightarrow> 'a set \\<Rightarrow> 'a set\"\n  where \"set_complement A \\<Omega> = (THE B. B = {x\\<in>\\<Omega>. x \\<notin> A} \\<and> A \\<subseteq> \\<Omega>)\"\n\nlemma set_complement_meaning: \n  assumes subseq: \"A \\<subseteq> B\"\n  shows \"set_complement A B = {x\\<in>B. x \\<notin> A}\"\n  by (simp add: set_complement_def subseq)\n\nlemma set_complement_diff: \n  assumes subseq: \"A \\<subseteq> B\"\n  shows \"set_complement A B = B - A\"\n  using Diff_iff subseq set_complement_meaning by auto \n\nlemma set_complement_self_inverse: \n  assumes subseq: \"A \\<subseteq> B\"\n    shows \"set_complement (set_complement A B) B = A\"\n  by (simp add: double_diff set_complement_diff subseq)\n\nlemma de_morgan_general_1: \n  assumes subseq: \"\\<forall>A\\<in>\\<A>. A \\<subseteq> \\<Omega>\" \n      and non_empty_collection: \"\\<A> \\<noteq> {}\"\n  shows \"set_complement (general_union \\<A>) \\<Omega> = \n         general_intersection {C. \\<exists>S\\<in>\\<A>. C = set_complement S \\<Omega>}\"\nproof\n  show \"set_complement (general_union \\<A>) \\<Omega> \\<subseteq> general_intersection {C. \\<exists>S\\<in>\\<A>. C = set_complement S \\<Omega>}\" \n  proof \n    fix x \n    assume \"x \\<in> set_complement (general_union \\<A>) \\<Omega>\"\n    moreover have \"(general_union \\<A>) \\<subseteq> \\<Omega>\"\n      using subseq collection_union_subseq by auto \n    hence \"set_complement (general_union \\<A>) \\<Omega> = {x\\<in>\\<Omega>. x \\<notin> (general_union \\<A>)}\"\n      using set_complement_meaning by auto \n    ultimately have \"x \\<in> \\<Omega> \\<and> x \\<notin> general_union \\<A>\" \n      by simp \n    hence \"x \\<in> \\<Omega> \\<and> \\<not>(\\<exists>S. S \\<in> \\<A> \\<and> x \\<in> S)\"\n      using general_union_def by fast\n    hence \"x \\<in> \\<Omega> \\<and> (\\<forall>S. S \\<notin> \\<A> \\<or> x \\<notin> S)\"\n      by auto \n    hence \"\\<forall>S\\<in>\\<A>. x \\<in> set_complement S \\<Omega>\"\n      by (simp add: set_complement_meaning subseq) \n    thus \"x \\<in> general_intersection {C. \\<exists>S\\<in>\\<A>. C = set_complement S \\<Omega>}\"\n      using general_intersection_def by fastforce \n  qed \nnext \n  show \"general_intersection {C. \\<exists>S\\<in>\\<A>. C = set_complement S \\<Omega>} \\<subseteq> set_complement (general_union \\<A>) \\<Omega>\"\n  proof \n    fix x \n    assume \"x \\<in> general_intersection {C. \\<exists>S\\<in>\\<A>. C = set_complement S \\<Omega>}\"\n    hence \"\\<forall>C. (\\<exists>S\\<in>\\<A>. C = set_complement S \\<Omega>) \\<longrightarrow> x \\<in> C\"\n      by (simp add: general_intersection_def)\n    hence \"\\<forall>S\\<in>\\<A>. x \\<in> set_complement S \\<Omega>\"\n      by auto \n    moreover have \"\\<forall>S\\<in>\\<A>. set_complement S \\<Omega> = {x\\<in>\\<Omega>. x \\<notin> S}\"\n      using set_complement_meaning subseq by auto \n    ultimately have \"\\<forall>S\\<in>\\<A>. (x \\<in> \\<Omega> \\<and> x \\<notin> S)\" \n      by simp\n    hence \"x \\<in> \\<Omega> \\<and> (\\<forall>S\\<in>\\<A>. x \\<notin> S)\"\n      using non_empty_collection by auto \n    hence \"x \\<in> \\<Omega> \\<and> x \\<notin> general_union \\<A>\"\n      by (simp add: general_union_def)\n    thus \"x \\<in> set_complement (general_union \\<A>) \\<Omega>\"\n      by (simp add: collection_union_subseq set_complement_meaning subseq) \n  qed \nqed\n\nlemma de_morgan_general_2: \n  assumes subseq: \"\\<forall>A\\<in>\\<A>. A \\<subseteq> \\<Omega>\" \n      and non_empty_collection: \"\\<A> \\<noteq> {}\"\n    shows \"set_complement (general_intersection \\<A>) \\<Omega> = \n           general_union {C. \\<exists>S\\<in>\\<A>. C = set_complement S \\<Omega>}\"\nproof \n  show \"set_complement (general_intersection \\<A>) \\<Omega> \\<subseteq> general_union {C. \\<exists>S\\<in>\\<A>. C = set_complement S \\<Omega>}\"\n  proof \n    fix x \n    assume \"x \\<in> set_complement (general_intersection \\<A>) \\<Omega>\"\n    moreover have \"(general_intersection \\<A>) \\<subseteq> \\<Omega>\"\n      using subseq non_empty_collection collection_inter_subseq by auto \n    hence \"set_complement (general_intersection \\<A>) \\<Omega> = {x\\<in>\\<Omega>. x \\<notin> (general_intersection \\<A>)}\"\n      using set_complement_meaning by auto \n    ultimately have \"x \\<in> \\<Omega> \\<and> x \\<notin> general_intersection \\<A>\" \n      by simp \n    hence \"\\<exists>S\\<in>\\<A>. x \\<notin> S \\<and> x \\<in> \\<Omega>\"\n      by (metis notin_general_intersection)\n    hence \"\\<exists>S\\<in>\\<A>. x \\<in> set_complement S \\<Omega>\"\n      by (simp add: set_complement_meaning subseq)\n    thus \"x \\<in> general_union {C. \\<exists>S\\<in>\\<A>. C = set_complement S \\<Omega>}\"\n      using general_union_def by fast\n  qed \nnext \n  show \"general_union {C. \\<exists>S\\<in>\\<A>. C = set_complement S \\<Omega>} \\<subseteq> set_complement (general_intersection \\<A>) \\<Omega>\"\n  proof\n    fix x \n    assume \"x \\<in> general_union {C. \\<exists>S\\<in>\\<A>. C = set_complement S \\<Omega>}\"\n    hence \"\\<exists>C. \\<exists>S\\<in>\\<A>. C = set_complement S \\<Omega> \\<and> x \\<in> C\"\n      by (simp add: general_union_def)\n    hence \"\\<exists>S\\<in>\\<A>. x \\<in> set_complement S \\<Omega>\"\n      by auto \n    hence \"x \\<in> \\<Omega> \\<and> (\\<exists>S\\<in>\\<A>. x \\<notin> S)\"\n      by (simp add: subseq set_complement_meaning)\n    hence \"x \\<in> \\<Omega> \\<and> x \\<notin> general_intersection \\<A>\"\n      by (simp add: notin_general_intersection)\n    thus \"x \\<in> set_complement (general_intersection \\<A>) \\<Omega>\"\n      by (simp add: collection_inter_subseq non_empty_collection set_complement_diff subseq) \n  qed\nqed\n\nlemma de_morgan_binary_1: \nassumes A_subseq: \"A \\<subseteq> \\<Omega>\" \n    and B_subseq: \"B \\<subseteq> \\<Omega>\" \n  shows \"set_complement (A \\<union> B) \\<Omega> = (set_complement A \\<Omega>) \\<inter> (set_complement B \\<Omega>)\"\nproof - \n  have \"A \\<union> B = general_union {A, B}\"\n    by (simp add: general_union_binary)\n  moreover have \"(set_complement A \\<Omega>) \\<inter> (set_complement B \\<Omega>) = \n                 general_intersection {set_complement A \\<Omega>, set_complement B \\<Omega>}\"\n    by (simp add: general_intersection_binary)\n  moreover have \"{set_complement A \\<Omega>, set_complement B \\<Omega>} = {C. \\<exists>S\\<in>{A, B}. C = set_complement S \\<Omega>}\"\n    by auto \n  moreover have \"set_complement (general_union {A, B}) \\<Omega> = \n                 general_intersection {C. \\<exists>S\\<in>{A, B}. C = set_complement S \\<Omega>}\"\n    by (simp add: A_subseq B_subseq de_morgan_general_1)\n  ultimately show ?thesis \n    by simp \nqed\n\nlemma de_morgan_binary_2: \nassumes A_subseq: \"A \\<subseteq> \\<Omega>\" \n    and B_subseq: \"B \\<subseteq> \\<Omega>\" \n  shows \"set_complement (A \\<inter> B) \\<Omega> = (set_complement A \\<Omega>) \\<union> (set_complement B \\<Omega>)\"\nproof - \n  have \"A \\<inter> B = general_intersection {A, B}\"\n    by (simp add: general_intersection_binary)\n  moreover have \"(set_complement A \\<Omega>) \\<union> (set_complement B \\<Omega>) = \n                 general_union {set_complement A \\<Omega>, set_complement B \\<Omega>}\"\n    by (simp add: general_union_binary)\n  moreover have \"{set_complement A \\<Omega>, set_complement B \\<Omega>} = {C. \\<exists>S\\<in>{A, B}. C = set_complement S \\<Omega>}\"\n    by auto \n  moreover have \"set_complement (general_intersection {A, B}) \\<Omega> = \n                 general_union {C. \\<exists>S\\<in>{A, B}. C = set_complement S \\<Omega>}\"\n    by (simp add: A_subseq B_subseq de_morgan_general_2)\n  ultimately show ?thesis \n    by simp \nqed\n\nsubsubsection \"Limits of Sets\"\n\ndefinition liminf :: \"(nat \\<Rightarrow> 'a set) \\<Rightarrow> 'a set\"\n  where \"liminf A = \n         general_union {B. \\<exists>n. B = general_intersection {C. \\<exists>k. k \\<ge> n \\<and> C = A k}}\"\n\nlemma liminf_greater_n: \"(x \\<in> liminf A) = (\\<exists>n. \\<forall>k. (k \\<ge> n \\<longrightarrow> x \\<in> A k))\"\nproof - \n  have \"(x \\<in> liminf A) = \n         (\\<exists>S. \\<exists>n. S = general_intersection {C. \\<exists>k. k \\<ge> n \\<and> C = A k} \\<and> x \\<in> S)\"\n    by (simp add: liminf_def general_union_def)\n  hence \"(x \\<in> liminf A) = (\\<exists>n. x \\<in> general_intersection {C. \\<exists>k. k \\<ge> n \\<and> C = A k})\"\n    by auto\n  hence \"(x \\<in> liminf A) = (\\<exists>n. \\<forall>S. (S \\<in> {C. \\<exists>k. k \\<ge> n \\<and> C = A k} \\<longrightarrow> x \\<in> S))\"\n    by (simp add: general_intersection_def)\n  thus ?thesis\n    by auto\nqed\n\nlemma liminf_greater_n_set: \"liminf A = {x. \\<exists>n. \\<forall>k. k \\<ge> n \\<longrightarrow> x \\<in> A k}\"\nproof \n  show \"liminf A \\<subseteq> {x. \\<exists>n. \\<forall>k\\<ge>n. x \\<in> A k}\"\n  proof \n    fix x \n    assume \"x \\<in> liminf A\"\n    hence \"\\<exists>n. \\<forall>k. (k \\<ge> n \\<longrightarrow> x \\<in> A k)\"\n      by (simp add: liminf_greater_n) \n    thus \"x \\<in> {x. \\<exists>n. \\<forall>k. k \\<ge> n \\<longrightarrow> x \\<in> A k}\" \n      by auto \n  qed \nnext \n  show \"{x. \\<exists>n. \\<forall>k\\<ge>n. x \\<in> A k} \\<subseteq> liminf A\"\n  proof \n    fix x \n    assume \"x \\<in> {x. \\<exists>n. \\<forall>k\\<ge>n. x \\<in> A k}\"\n    hence \"\\<exists>n. \\<forall>k. (k \\<ge> n \\<longrightarrow> x \\<in> A k)\"\n      by auto \n    thus \"x \\<in> liminf A\" \n      by (simp add: liminf_greater_n) \n  qed\nqed\n   \n\ndefinition limsup :: \"(nat \\<Rightarrow> 'a set) \\<Rightarrow> 'a set\"\n  where \"limsup A = general_intersection {B. \\<exists>n. B = general_union {C. \\<exists>m. m \\<ge> n \\<and> C = A m}}\"\n\nlemma limsup_greater_n: \"(x \\<in> limsup A) = (\\<forall>n. \\<exists>m. m \\<ge> n \\<and> x \\<in> A m)\"\nproof - \n  have \"(x \\<in> limsup A) = \n        (x \\<in> general_intersection {B. \\<exists>n. B = general_union {C. \\<exists>m. m \\<ge> n \\<and> C = A m}})\"\n    using limsup_def by fast \n  hence \"(x \\<in> limsup A) = (\\<forall>S. (\\<exists>n. S = {x. \\<exists>S'. S' \\<in> {C. \\<exists>m. m \\<ge> n \\<and> C = A m} \\<and> x \\<in> S'}) \\<longrightarrow> x \\<in> S)\"\n    by (simp add: general_union_def general_intersection_def) \n  hence \"(x \\<in> limsup A) = (\\<forall>n. \\<exists>S'. (\\<exists>m. m \\<ge> n \\<and> S' = A m) \\<and> x \\<in> S')\"\n    by auto \n  thus ?thesis \n    by fast \nqed\n\nlemma limsup_greater_n_set: \"limsup A = {x. \\<forall>n. \\<exists>m. m \\<ge> n \\<and> x \\<in> A m}\"\nproof \n  show \"limsup A \\<subseteq> {x. \\<forall>n. \\<exists>m. m \\<ge> n \\<and> x \\<in> A m}\"\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 (simp add: limsup_greater_n) \n    thus \"x \\<in> {x. \\<forall>n. \\<exists>m. m \\<ge> n \\<and> x \\<in> A m}\" \n      by auto \n  qed \nnext \n  show \"{x. \\<forall>n. \\<exists>m. m \\<ge> n \\<and> x \\<in> A m} \\<subseteq> limsup A\"\n  proof \n    fix x \n    assume \"x \\<in> {x. \\<forall>n. \\<exists>m. m \\<ge> n \\<and> x \\<in> A m}\"\n    hence \"\\<forall>n. \\<exists>m. m \\<ge> n \\<and> x \\<in> A m\"\n      by auto \n    thus \"x \\<in> limsup A\" \n      by (simp add: limsup_greater_n) \n  qed\nqed\n\nlemma liminf_sub_limsup: \"liminf A \\<subseteq> limsup A\"\nproof \n  fix x \n  assume \"x \\<in> liminf A\"\n  hence \"\\<exists>n. \\<forall>m. (m \\<ge> n \\<longrightarrow> x \\<in> A m)\"\n    by (simp add: liminf_greater_n)\n  hence \"\\<forall>n. \\<exists>m. m \\<ge> n \\<and> x \\<in> A m\"\n    by (meson nat_le_linear)  \n  thus \"x \\<in> limsup A\" \n    by (simp add: limsup_greater_n) \nqed\n\nlemma liminf_limsup_eq_cond: \n  assumes limsup_sub_liminf: \"limsup A \\<subseteq> liminf A\" \n  shows \"liminf A = limsup A\"\n  by (simp add: limsup_sub_liminf liminf_sub_limsup subset_antisym)\n\n\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\nlemma set_limit_eq_liminf: \n  assumes lim_defined: \"liminf A = limsup A\"\n  shows \"set_limit A = liminf A\"\n  by (simp add: lim_defined set_limit_def)\n\nlemma set_limit_eq_limsup: \n  assumes lim_defined: \"liminf A = limsup A\"\n  shows \"set_limit A = limsup A\"\n  by (simp add: lim_defined set_limit_def)\n\nlemma non_decreasing_set_limit: \n  assumes non_decreasing: \"non_decreasing A\\<^sub>n\"\n  shows \"set_limit A\\<^sub>n = general_union {A. \\<exists>n. A = A\\<^sub>n n}\"\nproof - \n  have \"limsup A\\<^sub>n = general_union {A. \\<exists>n. A = A\\<^sub>n n}\" \n  proof \n    show \"limsup A\\<^sub>n \\<subseteq> general_union {A. \\<exists>n. A = A\\<^sub>n n}\"\n    proof \n      fix x \n      assume \"x \\<in> limsup A\\<^sub>n\"\n      hence \"(\\<exists>m. m \\<ge> 1 \\<and> x \\<in> A\\<^sub>n m)\"\n        by (simp add: limsup_greater_n) \n      hence \"(\\<exists>m. x \\<in> A\\<^sub>n m)\"\n        by auto \n      thus \"x \\<in> general_union {A. \\<exists>n. A = A\\<^sub>n n}\" \n        using general_union_sequence by fast  \n    qed\n  next \n    show \"general_union {A. \\<exists>n. A = A\\<^sub>n n} \\<subseteq> limsup A\\<^sub>n\"\n    proof \n      fix x \n      assume \"x \\<in> general_union {A. \\<exists>n. A = A\\<^sub>n n}\" \n      hence \"x \\<in> {x. \\<exists>n. x \\<in> A\\<^sub>n n}\"\n        using general_union_sequence by metis \n      hence \"\\<exists>n. x \\<in> A\\<^sub>n n\"\n        by auto \n      then obtain n where \"x \\<in> A\\<^sub>n n\" \n        by auto \n      hence \"\\<forall>m\\<ge>n. x \\<in> A\\<^sub>n m\"\n        by (meson non_decreasing non_decreasing_stay_in)\n      thus \"x \\<in> limsup A\\<^sub>n\"\n        by (meson limsup_greater_n nat_le_linear) \n    qed\n  qed\n\n  moreover have \"limsup A\\<^sub>n = liminf A\\<^sub>n\" \n  proof - \n    have \"limsup A\\<^sub>n \\<subseteq> liminf A\\<^sub>n\"\n    proof \n      fix x \n      assume \"x \\<in> limsup A\\<^sub>n\"\n      hence \"\\<forall>n. \\<exists>m. m \\<ge> n \\<and> x \\<in> A\\<^sub>n m\"\n        by (simp add: limsup_greater_n)\n      hence \"\\<exists>n. \\<forall>k. (k \\<ge> n \\<longrightarrow> x \\<in> A\\<^sub>n k)\"\n        by (meson non_decreasing non_decreasing_stay_in)\n      thus \"x \\<in> liminf A\\<^sub>n\"\n        by (simp add: liminf_greater_n)\n    qed\n    thus ?thesis\n      using liminf_limsup_eq_cond by auto \n  qed\n\n  ultimately show ?thesis\n    by (simp add: set_limit_eq_limsup) \nqed\n\nlemma non_increasing_set_limit: \n  assumes non_increasing: \"non_increasing A\\<^sub>n\"\n  shows \"set_limit A\\<^sub>n = general_intersection {A. \\<exists>n. A = A\\<^sub>n n}\"\nproof - \n  have \"limsup A\\<^sub>n = general_intersection {A. \\<exists>n. A = A\\<^sub>n n}\" \n  proof \n    show \"limsup A\\<^sub>n \\<subseteq> general_intersection {A. \\<exists>n. A = A\\<^sub>n n}\"\n    proof \n      fix x \n      assume \"x \\<in> limsup A\\<^sub>n\"\n      hence \"\\<forall>n. \\<exists>m. m \\<ge> n \\<and> x \\<in> A\\<^sub>n m\"\n        by (simp add: limsup_greater_n) \n      hence \"\\<forall>m. x \\<in> A\\<^sub>n m\"\n        using non_increasing non_increasing_stay_out by metis \n      thus \"x \\<in> general_intersection {A. \\<exists>n. A = A\\<^sub>n n}\"\n        using general_intersection_sequence by fast \n    qed\n  next \n    show \"general_intersection {A. \\<exists>n. A = A\\<^sub>n n} \\<subseteq> limsup A\\<^sub>n\"\n    proof \n      fix x \n      assume \"x \\<in> general_intersection {A. \\<exists>n. A = A\\<^sub>n n}\" \n      hence \"\\<forall>n. x \\<in> A\\<^sub>n n\"\n        using general_intersection_sequence by fast \n      thus \"x \\<in> limsup A\\<^sub>n\"\n        by (meson limsup_greater_n order_refl)\n    qed\n  qed\n\n  moreover have \"limsup A\\<^sub>n = liminf A\\<^sub>n\" \n  proof - \n    have \"limsup A\\<^sub>n \\<subseteq> liminf A\\<^sub>n\"\n    proof \n      fix x \n      assume \"x \\<in> limsup A\\<^sub>n\"\n      hence \"\\<forall>n. \\<exists>m. m \\<ge> n \\<and> x \\<in> A\\<^sub>n m\"\n        by (simp add: limsup_greater_n)\n      hence \"\\<exists>n. \\<forall>k\\<ge>n. x \\<in> A\\<^sub>n k\"\n        by (meson non_increasing non_increasing_stay_out)\n      thus \"x \\<in> liminf A\\<^sub>n\"\n        by (simp add: liminf_greater_n) \n    qed\n    thus ?thesis\n      using liminf_limsup_eq_cond by auto \n  qed\n\n  ultimately show ?thesis\n    by (simp add: set_limit_eq_limsup) \nqed\n\nsubsection \"Collections of Sets\"\n\ndefinition complement_stable :: \"'a set set \\<Rightarrow> 'a set \\<Rightarrow> bool\"\n  where \"complement_stable \\<A> \\<Omega> \\<equiv> \\<A> \\<noteq> {} \\<and> (\\<forall>A\\<in>\\<A>. set_complement A \\<Omega> \\<in> \\<A>)\"\n\ndefinition finite_union_stable :: \"'a set set \\<Rightarrow> bool\"\n  where \"finite_union_stable \\<A> \\<equiv> \\<A> \\<noteq> {} \\<and> (\\<forall>A\\<in>\\<A>. \\<forall>B\\<in>\\<A>. A\\<union>B \\<in> \\<A>)\"\n\ndefinition finite_inter_stable :: \"'a set set \\<Rightarrow> bool\"\n  where \"finite_inter_stable \\<A> \\<equiv> \\<A> \\<noteq> {} \\<and> (\\<forall>A\\<in>\\<A>. \\<forall>B\\<in>\\<A>. A\\<inter>B \\<in> \\<A>)\"\n\nlemma c_fu_imp_fi_stable: \n  assumes c_stable: \"complement_stable \\<A> \\<Omega>\"\n      and fu_stable: \"finite_union_stable \\<A>\" \n      and subseq: \"\\<forall>S\\<in>\\<A>. S \\<subseteq> \\<Omega>\"\n    shows \"finite_inter_stable \\<A>\"\nproof - \n  have \"\\<A> \\<noteq> {}\"\n    using fu_stable finite_union_stable_def by auto \n\n  moreover have \"\\<forall>A\\<in>\\<A>. \\<forall>B\\<in>\\<A>. A\\<inter>B \\<in> \\<A>\"\n  proof \n    fix A\n    assume A_in: \"A \\<in> \\<A>\"\n    show \"\\<forall>B\\<in>\\<A>. A \\<inter> B \\<in> \\<A>\"\n    proof \n      fix B\n      assume B_in: \"B \\<in> \\<A>\"\n      have \"set_complement A \\<Omega> \\<in> \\<A>\"\n        using A_in c_stable complement_stable_def by auto\n      moreover have \"set_complement B \\<Omega> \\<in> \\<A>\"\n        using B_in c_stable complement_stable_def by auto \n      ultimately have \"(set_complement A \\<Omega>) \\<union> (set_complement B \\<Omega>) \\<in> \\<A>\"\n        using finite_union_stable_def fu_stable by fast\n      moreover have \"(set_complement A \\<Omega>) \\<union> (set_complement B \\<Omega>) = set_complement (A \\<inter> B) \\<Omega>\"\n        by (simp add: A_in B_in de_morgan_binary_2 subseq)\n      ultimately have \"set_complement (set_complement (A \\<inter> B) \\<Omega>) \\<Omega> \\<in> \\<A>\"\n        using c_stable complement_stable_def by auto\n      thus \"A \\<inter> B \\<in> \\<A>\"\n        by (metis A_in le_sup_iff set_complement_self_inverse subseq sup_inf_absorb) \n    qed\n  qed\n\n  ultimately show \"finite_inter_stable \\<A>\"\n    by (simp add: finite_inter_stable_def) \nqed\n\n(* TODO: c_fi_imp_fu_stable*)\n\ndefinition set_diff_stable :: \"'a set set \\<Rightarrow> bool\"\n  where \"set_diff_stable \\<A> \\<equiv> \\<A> \\<noteq> {} \\<and> (\\<forall>A\\<in>\\<A>. \\<forall>B\\<in>\\<A>. B \\<subseteq> A \\<longrightarrow> A-B \\<in> \\<A>)\"\n\ndefinition countable_union_stable :: \"'a set set \\<Rightarrow> bool\"\n  where \"countable_union_stable \\<A> \\<equiv> \\<A> \\<noteq> {} \\<and> (\\<forall>A\\<^sub>n. (\\<forall>n::nat. A\\<^sub>n n \\<in> \\<A>) \\<longrightarrow> \n  (general_union {S. \\<exists>n. S = A\\<^sub>n n} \\<in> \\<A>))\"\n\n(* TODO - disjoint_countable_union_stable *) \n\ndefinition countable_inter_stable :: \"'a set set \\<Rightarrow> bool\"\n  where \"countable_inter_stable \\<A> \\<equiv> \\<A> \\<noteq> {} \\<and> (\\<forall>A\\<^sub>n. (\\<forall>n::nat. A\\<^sub>n n \\<in> \\<A>) \\<longrightarrow> \n  (general_intersection {S. \\<exists>n. S = A\\<^sub>n n} \\<in> \\<A>))\"\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/RETIRED/General_Operations.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.877476793890012, "lm_q2_score": 0.839733963661418, "lm_q1q2_score": 0.7368470661541728}}
{"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>\\<open>\"schwerdtfeger\"\\<close>) 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\u00f6bius 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>\\<open>\"needham\"\\<close>.\\<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\u00f6bius transforms preserve angles and perpendicularity\\<close>\n(* ----------------------------------------------------------------- *)\n\ntext \\<open>M\u00f6bius 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": "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/Circlines_Angle.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8397339596505965, "lm_q2_score": 0.8774767858797979, "lm_q1q2_score": 0.7368470559083213}}
{"text": "(*  Title:      HOL/Isar_Examples/Group_Context.thy\n    Author:     Makarius\n*)\n\nsection \\<open>Some algebraic identities derived from group axioms -- theory context version\\<close>\n\ntheory Group_Context\n  imports Main\nbegin\n\ntext \\<open>hypothetical group axiomatization\\<close>\n\ncontext\n  fixes prod :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a\"  (infixl \"\\<odot>\" 70)\n    and one :: \"'a\"\n    and inverse :: \"'a \\<Rightarrow> 'a\"\n  assumes assoc: \"(x \\<odot> y) \\<odot> z = x \\<odot> (y \\<odot> z)\"\n    and left_one: \"one \\<odot> x = x\"\n    and left_inverse: \"inverse x \\<odot> x = one\"\nbegin\n\ntext \\<open>some consequences\\<close>\n\nlemma right_inverse: \"x \\<odot> inverse x = one\"\nproof -\n  have \"x \\<odot> inverse x = one \\<odot> (x \\<odot> inverse x)\"\n    by (simp only: left_one)\n  also have \"\\<dots> = one \\<odot> x \\<odot> inverse x\"\n    by (simp only: assoc)\n  also have \"\\<dots> = inverse (inverse x) \\<odot> inverse x \\<odot> x \\<odot> inverse x\"\n    by (simp only: left_inverse)\n  also have \"\\<dots> = inverse (inverse x) \\<odot> (inverse x \\<odot> x) \\<odot> inverse x\"\n    by (simp only: assoc)\n  also have \"\\<dots> = inverse (inverse x) \\<odot> one \\<odot> inverse x\"\n    by (simp only: left_inverse)\n  also have \"\\<dots> = inverse (inverse x) \\<odot> (one \\<odot> inverse x)\"\n    by (simp only: assoc)\n  also have \"\\<dots> = inverse (inverse x) \\<odot> inverse x\"\n    by (simp only: left_one)\n  also have \"\\<dots> = one\"\n    by (simp only: left_inverse)\n  finally show ?thesis .\nqed\n\nlemma right_one: \"x \\<odot> one = x\"\nproof -\n  have \"x \\<odot> one = x \\<odot> (inverse x \\<odot> x)\"\n    by (simp only: left_inverse)\n  also have \"\\<dots> = x \\<odot> inverse x \\<odot> x\"\n    by (simp only: assoc)\n  also have \"\\<dots> = one \\<odot> x\"\n    by (simp only: right_inverse)\n  also have \"\\<dots> = x\"\n    by (simp only: left_one)\n  finally show ?thesis .\nqed\n\nlemma one_equality:\n  assumes eq: \"e \\<odot> x = x\"\n  shows \"one = e\"\nproof -\n  have \"one = x \\<odot> inverse x\"\n    by (simp only: right_inverse)\n  also have \"\\<dots> = (e \\<odot> x) \\<odot> inverse x\"\n    by (simp only: eq)\n  also have \"\\<dots> = e \\<odot> (x \\<odot> inverse x)\"\n    by (simp only: assoc)\n  also have \"\\<dots> = e \\<odot> one\"\n    by (simp only: right_inverse)\n  also have \"\\<dots> = e\"\n    by (simp only: right_one)\n  finally show ?thesis .\nqed\n\nlemma inverse_equality:\n  assumes eq: \"x' \\<odot> x = one\"\n  shows \"inverse x = x'\"\nproof -\n  have \"inverse x = one \\<odot> inverse x\"\n    by (simp only: left_one)\n  also have \"\\<dots> = (x' \\<odot> x) \\<odot> inverse x\"\n    by (simp only: eq)\n  also have \"\\<dots> = x' \\<odot> (x \\<odot> inverse x)\"\n    by (simp only: assoc)\n  also have \"\\<dots> = x' \\<odot> one\"\n    by (simp only: right_inverse)\n  also have \"\\<dots> = x'\"\n    by (simp only: right_one)\n  finally show ?thesis .\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/Isar_Examples/Group_Context.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267762381844, "lm_q2_score": 0.8479677602988601, "lm_q1q2_score": 0.7367370955343722}}
{"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\"\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 \\<open>Derived properties of 0 and oSuc\\<close>\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 \\<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:\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 \\<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 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 \\<open>Making strict monotonic sequences\\<close>\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 \\<open>Induction principle for ordinals\\<close>\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": "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/OrdinalInduct.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8887587993853655, "lm_q2_score": 0.8289388167733099, "lm_q1q2_score": 0.7367266675593724}}
{"text": "theory Homework7\nimports \n  \"../IMP/Small_Step\" \n  \"~~/src/HOL/Library/Code_Target_Nat\"   (* Makes value-command compute with ML-integers rather than unary Suc (Suc ...) objects. *)\nbegin\n\n\n  (*\n    ISSUED: Wednesday, Nov 1\n    DUE: Wednesday, Nov 8, 11:59pm\n    POINTS: 10   (5 per part)\n  *)\n\n\n  (********** PART 1 ***************)\n\n  (*\n    In this homework, we will develop a faster way to interpret programs.\n  \n    First, we want to define a functional version of a small step,\n    that is, a function \n      small_stepf :: com * state \\<Rightarrow> (com * state) option\n    that returns the next configuration, after performing one small step.\n    If the configuration was final, it shall return None.\n    The equations of this function correspond to the rules of SmallStep.\n    \n    Complete the function!\n  *)\n\n\n\n  (* Hint: Ignore *warnings* about ambiguous inputs ... the \\<Rightarrow> in case and big-step causes them.\n    If you get type *errors*, though, DO NOT IGNORE THEM!\n  *)\n\n  fun small_stepf :: \"com * state \\<Rightarrow> (com * state) option\" where\n    \"small_stepf (x ::= a, s) = Some (SKIP, s(x := aval a s))\"\n  | \"small_stepf (SKIP;;c\\<^sub>2,s) = Some (c\\<^sub>2,s)\"\n  | \"small_stepf (c\\<^sub>1;;c\\<^sub>2,s) = undefined\"\n  | \"small_stepf (IF b THEN c\\<^sub>1 ELSE c\\<^sub>2,s) = undefined\"\n        (* Note: Although there are two If-rules in SmallStep, you only need a single equation here!  *)\n  | \"small_stepf (WHILE b DO c,s) = undefined\"\n  | \"small_stepf _ = None\" (* Catch-all case*)\n\n  (* Show that small_stepf indeed computes a single small step! *)\n  lemma small_stepf_eq: \"cs\\<rightarrow>cs'\\<longleftrightarrow> small_stepf cs = Some cs'\" sorry\n\n  (* Show that None is returned only for final configurations.\n    Hint: Already implied by thm small_stepf_eq, no separate induction required!\n  *)\n  lemma final_eq: \"final cs \\<longleftrightarrow> small_stepf cs = None\"\n    sorry\n    \n\n  (* \n    Write a function iterate that iterates small_stepf, until a final \n    configuration is reached, but for at most n iterations.\n    \n    If no final configuration is reached after n iterations, the function \n    shall return None. \n    \n    Hint: For n=0, it is OK to always return None, even if the configuration should be final.\n      This will simplify the equation for 0.\n  \n    n is also called fuel: Each iteration uses one unit of fuel, \n      and when running out of fuel the computation stops.\n      \n    Do not use \\<rightarrow> or final in your function, but \n    use small_stepsf instead (cf. thms small_stepf_eq and final_eq)!\n      \n  *)  \n  fun iterate :: \"nat \\<Rightarrow> com * state \\<Rightarrow> (com * state) option\" where\n    \"iterate 0 cs = undefined\"\n  | \"iterate (Suc n) cs = undefined\"\n  \n  (* Show that iterate behaves as expected! \n    There is a terminating execution if, and only if, there is an \n    initial fuel value such that iterate returns Some.\n    \n    Hint: Prove both directions separately.\n  *)\n  lemma iterate_eq: \"(cs \\<rightarrow>* cs' \\<and> final cs') \\<longleftrightarrow> (\\<exists>n. iterate n cs = Some cs')\"\n    sorry\n    \n  (*\n    The iterate function gives you another way to execute programs, which \n    is considerably faster than constructing derivation trees.\n    \n    Notes: \n      * the extracts the value cs from Some cs, and the None is undefined.\n      * snd extracts the second component of a pair\n      * If you do not specify enough initial fuel, the command will just return \n        \\<open>snd (the None) ''a''\\<close>, otherwise it returns teh correct result, e.g., 225.\n        Specifying too much fuel, on the other hand, is no problem, as the iteration \n        stops once it reaches a final result, not necessarily using up all its fuel.\n  \n  *)\n\n  value \"(snd (the (iterate 100000000000 (DerTreeExample.square,<''x'':=15>)))) ''a''\"\n\n  \n  (********** PART 2 ***************)\n  \n  (*\n    In this part, you are supposed to write some programs, \n    satisfying a given specification. Test your programs!\n    \n    Try to find short and simple programs that only use the \n    available operations of IMP!\n  *)\n  \n  \n  (* Write a program power2 that returns 2^c (2 to the power of c) in variable a.\n    You may assume c being non-negative.\n  \n    Specification: { c=i\\<^sub>c \\<and> i\\<^sub>c\\<ge>0 } power2 { a=2^i\\<^sub>c }, i\\<^sub>c does not occur in power2!\n  *)\n\n  definition power2 where \"power2 \\<equiv> undefined\"\n    \n  (* Template for testing \\<dots> *)\n  value \"(snd (the (iterate 100000000000 (power2,<''c'':=10>)))) ''a''\"\n    \n  (* If you did not succeed with the iterate function, use the standard big-step\n    derivation to test your programs ... will be much slower, though!\n  *)\n  schematic_goal \"(power2,<''c'':=10>) \\<Rightarrow> ?s\"\n    unfolding power2_def\n    by BigSteps\n  \n  \n    \n  (* Write a program that replaces variable a by a*b, and does not change b!\n    You may assume that a and b are positive!\n  \n    Specification: { a=i\\<^sub>a \\<and> b=i\\<^sub>b \\<and> i\\<^sub>a>0 \\<and> i\\<^sub>b>0 } mult { a=i\\<^sub>a*i\\<^sub>b \\<and> b=i\\<^sub>b }, i\\<^sub>a,i\\<^sub>b do not occur in mult!\n  *)\n\n  definition mult where \"mult \\<equiv> undefined\n  \"\n  \n  value \"(snd (the (iterate 100000000000 (mult,<''a'':=10, ''b'':=7>)))) ''a''\"\n\n  (* Write a program that returns b^c in variable a. \n    You may assume that b is positive and c is non-negative\n  \n    Specification: { b=i\\<^sub>b \\<and> c=i\\<^sub>c \\<and> i\\<^sub>b>0 \\<and> i\\<^sub>c\\<ge>0 } power { a=i\\<^sub>b^i\\<^sub>c }, i\\<^sub>b,i\\<^sub>c do not occur in power\n    \n    Hint: Combine the ideas from the two above programs, you'll need two nested while loops.\n      If your multiplication program uses auxiliary variables, keep care that they do not\n      conflict with the variables used in your main program!\n    \n  *)\n  \n  definition power where \"power \\<equiv> undefined\"\n  \n  value \"(snd (the (iterate 100000000000 (power,<''b'':=5, ''c'':=4>)))) ''a''\"\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/Homework7.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8333245953120233, "lm_q2_score": 0.8840392893839085, "lm_q1q2_score": 0.7366916830657743}}
{"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_TSortIsSort\nimports \"../../Test_Base\"\nbegin\n\ndatatype 'a list = nil2 | cons2 \"'a\" \"'a list\"\n\ndatatype Tree = TNode \"Tree\" \"int\" \"Tree\" | TNil\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\nfun flatten :: \"Tree => int list => int list\" where\n\"flatten (TNode p z q) y = flatten p (cons2 z (flatten q y))\"\n| \"flatten (TNil) y = y\"\n\nfun add :: \"int => Tree => Tree\" where\n\"add x (TNode p z q) =\n   (if x <= z then TNode (add x p) z q else TNode p z (add x q))\"\n| \"add x (TNil) = TNode TNil x TNil\"\n\nfun toTree :: \"int list => Tree\" where\n\"toTree (nil2) = TNil\"\n| \"toTree (cons2 y xs) = add y (toTree xs)\"\n\nfun tsort :: \"int list => int 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_TSortIsSort.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392756357327, "lm_q2_score": 0.8333245870332531, "lm_q1q2_score": 0.7366916642903232}}
{"text": "theory EjT2B\nimports Main\nbegin\n\nsection \"Ejercicio 2.6: Suma de elementos de un \u00e1rbol\"\n\ntext {*\n  ----------------------------------------------------------------------\n  Ejercicio 2.6.1. En este ejercicio se usa el tipo de los \u00e1rboles\n  definido por \n     datatype 'a arbol = Hoja | Nodo \"'a arbol\" 'a \"'a arbol\"\n  Por ejemplo, el \u00e1rbol\n      9\n     / \\\n   .    4\n        /\\\n       .   .\n  se define por\n     abbreviation ejArbol1 :: \"int arbol\" where\n       \"ejArbol1 \\<equiv> Nodo Hoja (9::int) (Nodo Hoja 4 Hoja)\"\n  Definir la funci\u00f3n\n     elementos :: \"'a arbol \\<Rightarrow> 'a list\"\n  tal que (elementos t) es la lista de los elementos del \u00e1rbol t. Por\n  ejemplo, \n     elementos ejArbol1                   = [9,4]\n     elementos (Nodo ejArbol1 7 ejArbol1) = [9,4,7,9,4]\n  ------------------------------------------------------------------- *}\n\ndatatype 'a arbol = Hoja | Nodo \"'a arbol\" 'a \"'a arbol\"\n\nabbreviation ejArbol1 :: \"int arbol\" where\n  \"ejArbol1 \\<equiv> Nodo Hoja (9::int) (Nodo Hoja 4 Hoja)\"\n\nfun elementos :: \"'a arbol \\<Rightarrow> 'a list\" where\n  \"elementos Hoja = []\"\n| \"elementos (Nodo i x d) = elementos i @ [x] @ elementos d\"\n\nvalue \"elementos ejArbol1\"\nlemma \"elementos ejArbol1 = [9,4]\" by simp\nvalue \"elementos (Nodo ejArbol1 7 ejArbol1) = [9, 4, 7, 9, 4]\"\n\ntext {*\n  ----------------------------------------------------------------------\n  Ejercicio 2.6.2. Definir la funci\u00f3n\n     suma_arbol :: \"int arbol \\<Rightarrow> int\" \n  tal que (suma_arbol t) es la suma de los elementos del \u00e1rbol t. Por\n  ejemplo, \n     suma_arbol ejArbol1 = 13 \n     suma_arbol (Nodo ejArbol1 7 ejArbol1) = 33\n  ------------------------------------------------------------------- *}\n\nfun suma_arbol :: \"int arbol \\<Rightarrow> int\" where\n  \"suma_arbol Hoja = 0\"\n| \"suma_arbol (Nodo i x d) = suma_arbol i + x + suma_arbol d\"  \n\nvalue \"suma_arbol ejArbol1 = 13\" \nvalue \"suma_arbol (Nodo ejArbol1 7 ejArbol1) = 33\"\n\ntext {*\n  ----------------------------------------------------------------------\n  Ejercicio 2.6.3. Demostrar que\n     suma_arbol t = listsum (elementos t)\n  ------------------------------------------------------------------- *}\n\nlemma \"suma_arbol t = listsum (elementos t)\"\napply (induction t)\napply simp_all\ndone\n\nsection \"Ejercicio 2.7: Recorrido de \u00e1rboles e imagen especular\"\n\ntext {*\n  ----------------------------------------------------------------------\n  Ejercicio 2.7.1. Definir el tipo arbol2 para representar los \u00e1rboles\n  con valores en las hojas. Por ejemplo, el \u00e1rbol\n       /\\\n      /\\ 1\n     3  5\n  se define por   \n     abbreviation ejArbol2 :: \"int arbol2\" where\n       \"ejArbol2 \\<equiv> N (N (H 3) (H 5)) (H (1::int))\"\n  ------------------------------------------------------------------- *}\n\ndatatype 'a arbol2 = H \"'a\" \n                   | N \"'a arbol2\" \"'a arbol2\"\n\nabbreviation ejArbol2 :: \"int arbol2\" where\n  \"ejArbol2 \\<equiv> N (N (H 3) (H 5)) (H (1::int))\"\n \ntext {*\n  ----------------------------------------------------------------------\n  Ejercicio 2.7.2. Definir la funci\u00f3n\n     espejo :: \"'a arbol2 \\<Rightarrow> 'a arbol2\" where\n  tal que (espejo t) es la imagen especular de t. Por ejemplo,\n     espejo ejArbol2 = N (H 1) (N (H 5) (H 3))\n  ------------------------------------------------------------------- *}\n  \nfun espejo :: \"'a arbol2 \\<Rightarrow> 'a arbol2\" where\n  \"espejo (H x)   = H x\"\n| \"espejo (N i d) = N (espejo d) (espejo i)\"  \n\nvalue \"espejo ejArbol2 = N (H 1) (N (H 5) (H 3))\"\n\ntext {*\n  ----------------------------------------------------------------------\n  Ejercicio 2.7.3. Definir la funci\u00f3n\n     pre_orden :: \"'a arbol2 \\<Rightarrow> 'a list\"\n  tal que (pre_orden t) es el recorrido pre orden de t. Por ejemplo,\n     pre_orden ejArbol2 = [3, 5, 1]\n  ------------------------------------------------------------------- *}\n\nfun pre_orden :: \"'a arbol2 \\<Rightarrow> 'a list\" where\n  \"pre_orden (H x) = [x]\"\n| \"pre_orden (N i d) = pre_orden i @ pre_orden d\"  \n\nvalue \"pre_orden ejArbol2 = [3, 5, 1]\"\n\ntext {*\n  ----------------------------------------------------------------------\n  Ejercicio 2.7.4. Definir la funci\u00f3n\n     post_orden :: \"'a arbol2 \\<Rightarrow> 'a list\"\n  tal que (post_orden t) es el recorrido post orden de t. Por ejemplo,\n     post_orden ejArbol2 = [1, 5, 3]\n  ------------------------------------------------------------------- *}\n\nfun post_orden :: \"'a arbol2 \\<Rightarrow> 'a list\" where\n  \"post_orden (H x)   = [x]\"\n| \"post_orden (N i d) = post_orden d @ post_orden i\"  \n\nvalue \"post_orden ejArbol2 = [1, 5, 3]\"\n\ntext {*\n  ----------------------------------------------------------------------\n  Ejercicio 2.7.5. Demostrar que\n     pre_orden (espejo t) = post_orden t\n  ------------------------------------------------------------------- *}\n\nlemma \"pre_orden (espejo t) = post_orden t\"\napply (induction t)\napply simp_all\ndone\n\nsection \"Ejercicio 2.8: Intercalado de un elemento\"\n\ntext {*\n  ----------------------------------------------------------------------\n  Ejercicio 2.8.1. Definir la funci\u00f3n\n     intercala :: \"'a \\<Rightarrow> 'a list \\<Rightarrow> 'a list\n  tal que (intercala x ys) es la lista obtenida intercalando x entre los\n  elementos consecutivos de ys. Por ejemplo,\n     intercala x [a,b,c] = [a,x,b,x,c]\n  ------------------------------------------------------------------- *}\n\nfun intercala :: \"'a \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where\n  \"intercala x []     = []\"\n| \"intercala x [y]    = [y]\"  \n| \"intercala x (y#ys) = y # x # intercala x ys\"  \n\nvalue \"intercala x [a,b,c] = [a,x,b,x,c]\"\n\ntext {*\n  ----------------------------------------------------------------------\n  Ejercicio 2.8.2. Demostrar que\n     map f (intercala a xs) = intercala (f a) (map f xs)\n  ------------------------------------------------------------------- *}\n\nlemma \"map f (intercala a xs) = intercala (f a) (map f xs)\"\napply (induction xs rule: intercala.induct)\napply simp_all\ndone\n\nsection \"Ejercicio 2.9: Definici\u00f3n iterativa de suma de naturales\"\n\ntext {*\n  ----------------------------------------------------------------------\n  Ejercicio 2.9.1. Definir, como recursiva final, la funci\u00f3n\n     sumaIt :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\n  tal que (sumaIt n m) es la suma de n y m. Por ejemplo,\n     sumaIt 3 2 = 5\n  Nota: Que sumaIt es recursiva final significa que en la llamada\n  recursiva, la aplicaci\u00f3n de sumaIt es la \u00faltima; es decir,\n     sumaIt (Suc n) m = sumaIt ...\n  ------------------------------------------------------------------- *}\n\nfun sumaIt :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\" where\n  \"sumaIt 0 m = m\"\n| \"sumaIt (Suc n) m = sumaIt n (Suc m)\"  \n\nvalue \"sumaIt 3 2 = 5\" \n\ntext {*\n  ----------------------------------------------------------------------\n  Ejercicio 2.9.2. Demostrar que la funci\u00f3n suma It es equivalente a\n  suma definida por\n     fun suma :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\" where\n       \"suma 0 m      = m\"\n     | \"suma (Suc n) m = Suc (suma n m)\"  \n  ------------------------------------------------------------------- *}\n\nfun suma :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\" where\n  \"suma 0 m      = m\"\n| \"suma (Suc n) m = Suc (suma n m)\"  \n\ntext {* 1\\<ordmasculine> intento *}\nlemma \"sumaIt n m = suma n m\"\napply (induction n)\napply simp_all\noops\n\ntext {* Queda pendiente\n     sumaIt n m = suma n m \\<Longrightarrow> sumaIt n (Suc m) = Suc (suma n m)\n  Para probarlo se introduce el siguiente lema. *}\n\nlemma sumaIt1:\n  \"sumaIt n (Suc m) = Suc (sumaIt n m)\"\nsorry\n\ntext {* 2\\<ordmasculine> intento *}\nlemma \"sumaIt n m = suma n m\"\napply (induction n)\napply (simp_all add: sumaIt1)\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/Ejercicios/EjT2B.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619393159451, "lm_q2_score": 0.8933094145755219, "lm_q1q2_score": 0.7364996123501264}}
{"text": "theory Concrete_Semantics_3_3\n  imports Main\nbegin\n\n(* from 3.1 and 3.2 *) \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 a b) s = aval a s + aval b s\" \n\n(* ----- *)\n\ndatatype instr = LOADI val | LOAD vname | ADD\n\ntype_synonym stack = \"val list\"\n\n(* we argue about the case of stack, so the following warning is dismissed:\nMissing patterns in function definition:\n\\<And>b. exec1 ADD b [] = undefined\n\\<And>b v. exec1 ADD b [v] = undefined\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\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 a) s stk = aval a s # stk\"\n  apply(induction a arbitrary:stk)\n    apply(auto simp add: exec_division)\n  done\n\nfun mexec1 :: \"instr \\<Rightarrow> state \\<Rightarrow> stack \\<Rightarrow> stack option\" where\n\"mexec1 (LOADI n) _ stk = Some (n # stk)\" |\n\"mexec1 (LOAD x) s stk = Some(s(x) # stk)\" |\n\"mexec1 ADD _ (j # i # stk) = Some((i + j) # stk)\" |\n\"mexec1 ADD _ _ = None\"\n\n(* case stk is None or Some *)\nfun mexec :: \"instr list \\<Rightarrow> state \\<Rightarrow> stack \\<Rightarrow> stack option\" where\n\"mexec [] _ stk = Some(stk)\" |\n\"mexec (i#is) s stk = (case (mexec1 i s stk) of Some stk' \\<Rightarrow> mexec is s stk' | \nNone \\<Rightarrow> None)\"\n\nfun mcomp:: \"aexp \\<Rightarrow> instr list\" where\n\"mcomp (N n) = [LOADI n]\" |\n\"mcomp (V x) = [LOAD x]\" |\n\"mcomp (Plus e1 e2) = mcomp e1 @ mcomp e2 @ [ADD]\"\n\n(* add condition to exec_division \n *)\nlemma mexec_division:\"mexec a1 s stk = Some stk' \\<Longrightarrow> mexec (a1 @ a2) s stk = mexec a2 s stk'\"\n  apply(induction a1 arbitrary:stk)\n  apply(auto)\n  by (metis option.case_eq_if option.simps(3))\n\nlemma \"mexec (mcomp a) s stk = Some(aval a s # stk)\"\n  apply(induction a arbitrary:stk)\n    apply(auto simp add: mexec_division)\n  done\n\n(* ex 3.11 *)\n\ntype_synonym reg = nat\n\ndatatype r_instr = LDI int reg | LD vname reg | ADD reg reg\n\nfun rexec1 :: \"r_instr \\<Rightarrow> state \\<Rightarrow> (reg \\<Rightarrow> int) \\<Rightarrow> reg \\<Rightarrow> int\" where\n\"rexec1 (LDI i r1) _ f  = f(r1 := i)\" |\n\"rexec1 (LD x r1) s f = f(r1 := s(x))\" |\n\"rexec1 (ADD r1 r2) s f = f(r1:= (f r1) + (f r2))\"\n\nfun rexec :: \"r_instr list \\<Rightarrow> state \\<Rightarrow> (reg \\<Rightarrow> int) \\<Rightarrow> reg \\<Rightarrow> int\" where\n\"rexec [] _ f = f\" |\n\"rexec (r#rs) s f = rexec rs s (rexec1 r s f)\"\n\n(* I don't undestand about register machine enough.\nWhy (r + 1) is needed? \\<rightarrow> the answer might be that each register machines is different?\n *)\nfun rcomp:: \"aexp \\<Rightarrow> reg \\<Rightarrow> r_instr list\" where\n\"rcomp (N n) r = [LDI n r]\" |\n\"rcomp (V x) r = [LD x r]\" |\n\"rcomp (Plus e1 e2) r = rcomp e1 r @ rcomp e2 (r + 1) @ [ADD r (r + 1)]\"\n\n\nlemma rexec_division:\"rexec (a1 @ a2) s e = rexec a2 s (rexec a1 s e)\"\n  apply(induction a1 arbitrary: s e)\n  apply(auto)\n  done\n\n(* \nThe following lemma is not needed. And in this proof I found the above lemma.\nlemma \"rexec (rcomp a1 r @ rcomp a2 (Suc r) @ [ADD r (Suc r)]) s e r \n= aval a1 s + aval a2 s\"\n  apply(induction a1 arbitrary:s r e)\n  done\n*)\n\n\n(* Do not misunderstand to use which of r and q*)\nlemma min_number_of_reg_is_prior:\"r < q \\<Longrightarrow> rexec (rcomp a q) s f r = f r\"\n  apply(induction a arbitrary: q f)\n    apply(auto simp add:rexec_division)\n  done\n\n(* NOTE: \"The registers > r should be used in a stack-like fashion for intermediate results,\n the ones < r should be left alone.\"*)\nlemma min_number_of_reg_is_aval: \"rexec (rcomp a2 (Suc r)) s (rexec (rcomp a1 r) s e) r = aval a1 s\"\n  apply(induction a1 arbitrary: s e r)\n    apply(auto simp add: rexec_division min_number_of_reg_is_prior)\n  done\n\n(* counter examples occurs at\n- \"(rexec (rcomp a r1) s e) r2 = aval a s\"\n*)\nlemma \"(rexec (rcomp a r) s e) r = aval a s\"\n  apply(induction a arbitrary:s r e)\n    apply(auto simp add: rexec_division min_number_of_reg_is_aval)\n  done\n\n\n(* Exercise 3.12 *)\n\ndatatype instr0 = LDI0 val | LD0 vname | MV0 reg | ADD0 reg\n\nfun lexec1 :: \"instr0 \\<Rightarrow> state \\<Rightarrow> (reg \\<Rightarrow> int) \\<Rightarrow> reg \\<Rightarrow> int\" where\n\"lexec1 (LDI0 i) _ f  = f(0 := i)\" |\n\"lexec1 (LD0 x) s f = f(0 := s(x))\" |\n\"lexec1 (MV0 r1) s f = f(r1 := f(0))\" |\n\"lexec1 (ADD0 r1 ) s f = f(0:= (f 0) + (f r1))\"\n\nfun lexec :: \"instr0 list \\<Rightarrow> state \\<Rightarrow> (reg \\<Rightarrow> int) \\<Rightarrow> reg \\<Rightarrow> int\" where\n\"lexec [] _ f = f\" |\n\"lexec (r#rs) s f = lexec rs s (lexec1 r s f)\"\n\n(* I don't undestand about register machine enough.\nWhy (r + 1) is needed? \\<rightarrow> the answer might be that each register machines is different?\n *)\nfun lcomp:: \"aexp \\<Rightarrow> reg \\<Rightarrow> instr0 list\" where\n\"lcomp (N n) r = [LDI0 n]\" |\n\"lcomp (V x) r = [LD0 x]\" |\n\"lcomp (Plus e1 e2) r = (lcomp e1 (r + 1)@ [MV0 (r + 1)]  @ lcomp e2 (r + 2) @ [ADD0 (r + 1)])\"\n\nlemma lexec_division:\"lexec (a1 @ a2) s e = lexec a2 s (lexec a1 s e)\"\n  apply(induction a1 arbitrary: s e)\n  apply(auto)\n  done\n\nlemma min_number_of_reg0_is_prior:\"0 < r \\<Longrightarrow> r < q \\<Longrightarrow> lexec (lcomp a q) s f r = f r\"\n  apply(induction a arbitrary: q f)\n    apply(auto simp add:lexec_division)\n  done\n\nlemma \"lexec (lcomp a r) s rs 0 = aval a s\"\n  apply(induction a arbitrary: r s rs)\n  apply(auto simp add:lexec_division min_number_of_reg0_is_prior)\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/Concrete_Semantics_3_3.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619263765707, "lm_q2_score": 0.8933094152856196, "lm_q1q2_score": 0.7364996013767099}}
{"text": "theory Calculus\n  imports Complex_Main\nbegin\n\ntheorem mvt:\n  fixes \\<phi> :: \"real \\<Rightarrow> real\"\n  assumes \"a < b\"\n    and contf: \"continuous_on {a..b} \\<phi>\"\n    and derf: \"\\<And>x. \\<lbrakk>a < x; x < b\\<rbrakk> \\<Longrightarrow> (\\<phi> has_derivative \\<phi>' x) (at x)\"\n  obtains \\<xi> where \"a < \\<xi>\" \"\\<xi> < b\" \"\\<phi> b - \\<phi> a = (\\<phi>' \\<xi>) (b-a)\"\nproof -\n  define f where \"f \\<equiv> \\<lambda>x. \\<phi> x - (\\<phi> b - \\<phi> a) / (b-a) * x\"\n  have \"\\<exists>\\<xi>. a < \\<xi> \\<and> \\<xi> < b \\<and> (\\<lambda>y. \\<phi>' \\<xi> y - (\\<phi> b - \\<phi> a) / (b-a) * y) = (\\<lambda>v. 0)\"\n  proof (intro Rolle_deriv[OF \\<open>a < b\\<close>])\n    fix x\n    assume x: \"a < x\" \"x < b\"\n    show \"(f has_derivative (\\<lambda>y. \\<phi>' x y - (\\<phi> b - \\<phi> a) / (b-a) * y)) (at x)\"\n      unfolding f_def by (intro derivative_intros derf x)\n  next\n    show \"f a = f b\"\n      using assms by (simp add: f_def field_simps)\n  next\n    show \"continuous_on {a..b} f\"\n      unfolding f_def by (intro continuous_intros assms)\n  qed\n  then show ?thesis\n    by (smt (verit, ccfv_SIG) pos_le_divide_eq pos_less_divide_eq that)\nqed\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/Calculus.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8933094174159127, "lm_q2_score": 0.8244619220634456, "lm_q1q2_score": 0.7364995992801002}}
{"text": "(*  Title:      HOL/Transcendental.thy\n    Author:     Jacques D. Fleuriot, University of Cambridge, University of Edinburgh\n    Author:     Lawrence C Paulson\n    Author:     Jeremy Avigad\n*)\n\nsection \\<open>Power Series, Transcendental Functions etc.\\<close>\n\ntheory Transcendental\nimports Binomial Series Deriv NthRoot\nbegin\n\ntext \\<open>A fact theorem on reals.\\<close>\n\nlemma square_fact_le_2_fact: \"fact n * fact n \\<le> (fact (2 * n) :: real)\"\nproof (induct n)\n  case 0\n  then show ?case by simp\nnext\n  case (Suc n)\n  have \"(fact (Suc n)) * (fact (Suc n)) = of_nat (Suc n) * of_nat (Suc n) * (fact n * fact n :: real)\"\n    by (simp add: field_simps)\n  also have \"\\<dots> \\<le> of_nat (Suc n) * of_nat (Suc n) * fact (2 * n)\"\n    by (rule mult_left_mono [OF Suc]) simp\n  also have \"\\<dots> \\<le> of_nat (Suc (Suc (2 * n))) * of_nat (Suc (2 * n)) * fact (2 * n)\"\n    by (rule mult_right_mono)+ (auto simp: field_simps)\n  also have \"\\<dots> = fact (2 * Suc n)\" by (simp add: field_simps)\n  finally show ?case .\nqed\n\nlemma fact_in_Reals: \"fact n \\<in> \\<real>\"\n  by (induction n) auto\n\nlemma of_real_fact [simp]: \"of_real (fact n) = fact n\"\n  by (metis of_nat_fact of_real_of_nat_eq)\n\nlemma pochhammer_of_real: \"pochhammer (of_real x) n = of_real (pochhammer x n)\"\n  by (simp add: pochhammer_prod)\n\nlemma norm_fact [simp]: \"norm (fact n :: 'a::real_normed_algebra_1) = fact n\"\nproof -\n  have \"(fact n :: 'a) = of_real (fact n)\"\n    by simp\n  also have \"norm \\<dots> = fact n\"\n    by (subst norm_of_real) simp\n  finally show ?thesis .\nqed\n\nlemma root_test_convergence:\n  fixes f :: \"nat \\<Rightarrow> 'a::banach\"\n  assumes f: \"(\\<lambda>n. root n (norm (f n))) \\<longlonglongrightarrow> x\" \\<comment> \"could be weakened to lim sup\"\n    and \"x < 1\"\n  shows \"summable f\"\nproof -\n  have \"0 \\<le> x\"\n    by (rule LIMSEQ_le[OF tendsto_const f]) (auto intro!: exI[of _ 1])\n  from \\<open>x < 1\\<close> obtain z where z: \"x < z\" \"z < 1\"\n    by (metis dense)\n  from f \\<open>x < z\\<close> have \"eventually (\\<lambda>n. root n (norm (f n)) < z) sequentially\"\n    by (rule order_tendstoD)\n  then have \"eventually (\\<lambda>n. norm (f n) \\<le> z^n) sequentially\"\n    using eventually_ge_at_top\n  proof eventually_elim\n    fix n\n    assume less: \"root n (norm (f n)) < z\" and n: \"1 \\<le> n\"\n    from power_strict_mono[OF less, of n] n show \"norm (f n) \\<le> z ^ n\"\n      by simp\n  qed\n  then show \"summable f\"\n    unfolding eventually_sequentially\n    using z \\<open>0 \\<le> x\\<close> by (auto intro!: summable_comparison_test[OF _  summable_geometric])\nqed\n\nsubsection \\<open>More facts about binomial coefficients\\<close>\n\ntext \\<open>\n  These facts could have been proven before, but having real numbers \n  makes the proofs a lot easier.\n\\<close>\n\nlemma central_binomial_odd:\n  \"odd n \\<Longrightarrow> n choose (Suc (n div 2)) = n choose (n div 2)\"\nproof -\n  assume \"odd n\"\n  hence \"Suc (n div 2) \\<le> n\" by presburger\n  hence \"n choose (Suc (n div 2)) = n choose (n - Suc (n div 2))\"\n    by (rule binomial_symmetric)\n  also from \\<open>odd n\\<close> have \"n - Suc (n div 2) = n div 2\" by presburger\n  finally show ?thesis .\nqed\n\nlemma binomial_less_binomial_Suc:\n  assumes k: \"k < n div 2\"\n  shows   \"n choose k < n choose (Suc k)\"\nproof -\n  from k have k': \"k \\<le> n\" \"Suc k \\<le> n\" by simp_all\n  from k' have \"real (n choose k) = fact n / (fact k * fact (n - k))\"\n    by (simp add: binomial_fact)\n  also from k' have \"n - k = Suc (n - Suc k)\" by simp\n  also from k' have \"fact \\<dots> = (real n - real k) * fact (n - Suc k)\"\n    by (subst fact_Suc) (simp_all add: of_nat_diff)\n  also from k have \"fact k = fact (Suc k) / (real k + 1)\" by (simp add: field_simps)\n  also have \"fact n / (fact (Suc k) / (real k + 1) * ((real n - real k) * fact (n - Suc k))) =\n               (n choose (Suc k)) * ((real k + 1) / (real n - real k))\"\n    using k by (simp add: divide_simps binomial_fact)\n  also from assms have \"(real k + 1) / (real n - real k) < 1\" by simp\n  finally show ?thesis using k by (simp add: mult_less_cancel_left)\nqed\n\nlemma binomial_strict_mono:\n  assumes \"k < k'\" \"2*k' \\<le> n\"\n  shows   \"n choose k < n choose k'\"\nproof -\n  from assms have \"k \\<le> k' - 1\" by simp\n  thus ?thesis\n  proof (induction rule: inc_induct)\n    case base\n    with assms binomial_less_binomial_Suc[of \"k' - 1\" n] \n      show ?case by simp\n  next\n    case (step k)\n    from step.prems step.hyps assms have \"n choose k < n choose (Suc k)\" \n      by (intro binomial_less_binomial_Suc) simp_all\n    also have \"\\<dots> < n choose k'\" by (rule step.IH)\n    finally show ?case .\n  qed\nqed\n\nlemma binomial_mono:\n  assumes \"k \\<le> k'\" \"2*k' \\<le> n\"\n  shows   \"n choose k \\<le> n choose k'\"\n  using assms binomial_strict_mono[of k k' n] by (cases \"k = k'\") simp_all\n\nlemma binomial_strict_antimono:\n  assumes \"k < k'\" \"2 * k \\<ge> n\" \"k' \\<le> n\"\n  shows   \"n choose k > n choose k'\"\nproof -\n  from assms have \"n choose (n - k) > n choose (n - k')\"\n    by (intro binomial_strict_mono) (simp_all add: algebra_simps)\n  with assms show ?thesis by (simp add: binomial_symmetric [symmetric])\nqed\n\nlemma binomial_antimono:\n  assumes \"k \\<le> k'\" \"k \\<ge> n div 2\" \"k' \\<le> n\"\n  shows   \"n choose k \\<ge> n choose k'\"\nproof (cases \"k = k'\")\n  case False\n  note not_eq = False\n  show ?thesis\n  proof (cases \"k = n div 2 \\<and> odd n\")\n    case False\n    with assms(2) have \"2*k \\<ge> n\" by presburger\n    with not_eq assms binomial_strict_antimono[of k k' n] \n      show ?thesis by simp\n  next\n    case True\n    have \"n choose k' \\<le> n choose (Suc (n div 2))\"\n    proof (cases \"k' = Suc (n div 2)\") \n      case False\n      with assms True not_eq have \"Suc (n div 2) < k'\" by simp\n      with assms binomial_strict_antimono[of \"Suc (n div 2)\" k' n] True\n        show ?thesis by auto\n    qed simp_all\n    also from True have \"\\<dots> = n choose k\" by (simp add: central_binomial_odd)\n    finally show ?thesis .\n  qed\nqed simp_all\n\nlemma binomial_maximum: \"n choose k \\<le> n choose (n div 2)\"\nproof -\n  have \"k \\<le> n div 2 \\<longleftrightarrow> 2*k \\<le> n\" by linarith\n  consider \"2*k \\<le> n\" | \"2*k \\<ge> n\" \"k \\<le> n\" | \"k > n\" by linarith\n  thus ?thesis\n  proof cases\n    case 1\n    thus ?thesis by (intro binomial_mono) linarith+\n  next\n    case 2\n    thus ?thesis by (intro binomial_antimono) simp_all\n  qed (simp_all add: binomial_eq_0)\nqed\n\nlemma binomial_maximum': \"(2*n) choose k \\<le> (2*n) choose n\"\n  using binomial_maximum[of \"2*n\"] by simp\n\nlemma central_binomial_lower_bound:\n  assumes \"n > 0\"\n  shows   \"4^n / (2*real n) \\<le> real ((2*n) choose n)\"\nproof -\n  from binomial[of 1 1 \"2*n\"]\n    have \"4 ^ n = (\\<Sum>k=0..2*n. (2*n) choose k)\"\n    by (simp add: power_mult power2_eq_square One_nat_def [symmetric] del: One_nat_def)\n  also have \"{0..2*n} = {0<..<2*n} \\<union> {0,2*n}\" by auto\n  also have \"(\\<Sum>k\\<in>\\<dots>. (2*n) choose k) = \n               (\\<Sum>k\\<in>{0<..<2*n}. (2*n) choose k) + (\\<Sum>k\\<in>{0,2*n}. (2*n) choose k)\"\n    by (subst sum.union_disjoint) auto\n  also have \"(\\<Sum>k\\<in>{0,2*n}. (2*n) choose k) \\<le> (\\<Sum>k\\<le>1. (n choose k)\\<^sup>2)\" \n    by (cases n) simp_all\n  also from assms have \"\\<dots> \\<le> (\\<Sum>k\\<le>n. (n choose k)\\<^sup>2)\"\n    by (intro sum_mono3) auto\n  also have \"\\<dots> = (2*n) choose n\" by (rule choose_square_sum)\n  also have \"(\\<Sum>k\\<in>{0<..<2*n}. (2*n) choose k) \\<le> (\\<Sum>k\\<in>{0<..<2*n}. (2*n) choose n)\"\n    by (intro sum_mono binomial_maximum')\n  also have \"\\<dots> = card {0<..<2*n} * ((2*n) choose n)\" by simp\n  also have \"card {0<..<2*n} \\<le> 2*n - 1\" by (cases n) simp_all\n  also have \"(2 * n - 1) * (2 * n choose n) + (2 * n choose n) = ((2*n) choose n) * (2*n)\"\n    using assms by (simp add: algebra_simps)\n  finally have \"4 ^ n \\<le> (2 * n choose n) * (2 * n)\" by simp_all\n  hence \"real (4 ^ n) \\<le> real ((2 * n choose n) * (2 * n))\"\n    by (subst of_nat_le_iff)\n  with assms show ?thesis by (simp add: field_simps)\nqed\n\n\nsubsection \\<open>Properties of Power Series\\<close>\n\nlemma powser_zero [simp]: \"(\\<Sum>n. f n * 0 ^ n) = f 0\"\n  for f :: \"nat \\<Rightarrow> 'a::real_normed_algebra_1\"\nproof -\n  have \"(\\<Sum>n<1. f n * 0 ^ n) = (\\<Sum>n. f n * 0 ^ n)\"\n    by (subst suminf_finite[where N=\"{0}\"]) (auto simp: power_0_left)\n  then show ?thesis by simp\nqed\n\nlemma powser_sums_zero: \"(\\<lambda>n. a n * 0^n) sums a 0\"\n  for a :: \"nat \\<Rightarrow> 'a::real_normed_div_algebra\"\n  using sums_finite [of \"{0}\" \"\\<lambda>n. a n * 0 ^ n\"]\n  by simp\n\nlemma powser_sums_zero_iff [simp]: \"(\\<lambda>n. a n * 0^n) sums x \\<longleftrightarrow> a 0 = x\"\n  for a :: \"nat \\<Rightarrow> 'a::real_normed_div_algebra\"\n  using powser_sums_zero sums_unique2 by blast\n\ntext \\<open>\n  Power series has a circle or radius of convergence: if it sums for \\<open>x\\<close>,\n  then it sums absolutely for \\<open>z\\<close> with @{term \"\\<bar>z\\<bar> < \\<bar>x\\<bar>\"}.\\<close>\n\nlemma powser_insidea:\n  fixes x z :: \"'a::real_normed_div_algebra\"\n  assumes 1: \"summable (\\<lambda>n. f n * x^n)\"\n    and 2: \"norm z < norm x\"\n  shows \"summable (\\<lambda>n. norm (f n * z ^ n))\"\nproof -\n  from 2 have x_neq_0: \"x \\<noteq> 0\" by clarsimp\n  from 1 have \"(\\<lambda>n. f n * x^n) \\<longlonglongrightarrow> 0\"\n    by (rule summable_LIMSEQ_zero)\n  then have \"convergent (\\<lambda>n. f n * x^n)\"\n    by (rule convergentI)\n  then have \"Cauchy (\\<lambda>n. f n * x^n)\"\n    by (rule convergent_Cauchy)\n  then have \"Bseq (\\<lambda>n. f n * x^n)\"\n    by (rule Cauchy_Bseq)\n  then obtain K where 3: \"0 < K\" and 4: \"\\<forall>n. norm (f n * x^n) \\<le> K\"\n    by (auto simp add: Bseq_def)\n  have \"\\<exists>N. \\<forall>n\\<ge>N. norm (norm (f n * z ^ n)) \\<le> K * norm (z ^ n) * inverse (norm (x^n))\"\n  proof (intro exI allI impI)\n    fix n :: nat\n    assume \"0 \\<le> n\"\n    have \"norm (norm (f n * z ^ n)) * norm (x^n) =\n          norm (f n * x^n) * norm (z ^ n)\"\n      by (simp add: norm_mult abs_mult)\n    also have \"\\<dots> \\<le> K * norm (z ^ n)\"\n      by (simp only: mult_right_mono 4 norm_ge_zero)\n    also have \"\\<dots> = K * norm (z ^ n) * (inverse (norm (x^n)) * norm (x^n))\"\n      by (simp add: x_neq_0)\n    also have \"\\<dots> = K * norm (z ^ n) * inverse (norm (x^n)) * norm (x^n)\"\n      by (simp only: mult.assoc)\n    finally show \"norm (norm (f n * z ^ n)) \\<le> K * norm (z ^ n) * inverse (norm (x^n))\"\n      by (simp add: mult_le_cancel_right x_neq_0)\n  qed\n  moreover have \"summable (\\<lambda>n. K * norm (z ^ n) * inverse (norm (x^n)))\"\n  proof -\n    from 2 have \"norm (norm (z * inverse x)) < 1\"\n      using x_neq_0\n      by (simp add: norm_mult nonzero_norm_inverse divide_inverse [where 'a=real, symmetric])\n    then have \"summable (\\<lambda>n. norm (z * inverse x) ^ n)\"\n      by (rule summable_geometric)\n    then have \"summable (\\<lambda>n. K * norm (z * inverse x) ^ n)\"\n      by (rule summable_mult)\n    then show \"summable (\\<lambda>n. K * norm (z ^ n) * inverse (norm (x^n)))\"\n      using x_neq_0\n      by (simp add: norm_mult nonzero_norm_inverse power_mult_distrib\n          power_inverse norm_power mult.assoc)\n  qed\n  ultimately show \"summable (\\<lambda>n. norm (f n * z ^ n))\"\n    by (rule summable_comparison_test)\nqed\n\nlemma powser_inside:\n  fixes f :: \"nat \\<Rightarrow> 'a::{real_normed_div_algebra,banach}\"\n  shows\n    \"summable (\\<lambda>n. f n * (x^n)) \\<Longrightarrow> norm z < norm x \\<Longrightarrow>\n      summable (\\<lambda>n. f n * (z ^ n))\"\n  by (rule powser_insidea [THEN summable_norm_cancel])\n\nlemma powser_times_n_limit_0:\n  fixes x :: \"'a::{real_normed_div_algebra,banach}\"\n  assumes \"norm x < 1\"\n    shows \"(\\<lambda>n. of_nat n * x ^ n) \\<longlonglongrightarrow> 0\"\nproof -\n  have \"norm x / (1 - norm x) \\<ge> 0\"\n    using assms by (auto simp: divide_simps)\n  moreover obtain N where N: \"norm x / (1 - norm x) < of_int N\"\n    using ex_le_of_int by (meson ex_less_of_int)\n  ultimately have N0: \"N>0\"\n    by auto\n  then have *: \"real_of_int (N + 1) * norm x / real_of_int N < 1\"\n    using N assms by (auto simp: field_simps)\n  have **: \"real_of_int N * (norm x * (real_of_nat (Suc n) * norm (x ^ n))) \\<le>\n      real_of_nat n * (norm x * ((1 + N) * norm (x ^ n)))\" if \"N \\<le> int n\" for n :: nat\n  proof -\n    from that have \"real_of_int N * real_of_nat (Suc n) \\<le> real_of_nat n * real_of_int (1 + N)\"\n      by (simp add: algebra_simps)\n    then have \"(real_of_int N * real_of_nat (Suc n)) * (norm x * norm (x ^ n)) \\<le>\n        (real_of_nat n *  (1 + N)) * (norm x * norm (x ^ n))\"\n      using N0 mult_mono by fastforce\n    then show ?thesis\n      by (simp add: algebra_simps)\n  qed\n  show ?thesis using *\n    by (rule summable_LIMSEQ_zero [OF summable_ratio_test, where N1=\"nat N\"])\n      (simp add: N0 norm_mult field_simps ** del: of_nat_Suc of_int_add)\nqed\n\ncorollary lim_n_over_pown:\n  fixes x :: \"'a::{real_normed_field,banach}\"\n  shows \"1 < norm x \\<Longrightarrow> ((\\<lambda>n. of_nat n / x^n) \\<longlongrightarrow> 0) sequentially\"\n  using powser_times_n_limit_0 [of \"inverse x\"]\n  by (simp add: norm_divide divide_simps)\n\nlemma sum_split_even_odd:\n  fixes f :: \"nat \\<Rightarrow> real\"\n  shows \"(\\<Sum>i<2 * n. if even i then f i else g i) = (\\<Sum>i<n. f (2 * i)) + (\\<Sum>i<n. g (2 * i + 1))\"\nproof (induct n)\n  case 0\n  then show ?case by simp\nnext\n  case (Suc n)\n  have \"(\\<Sum>i<2 * Suc n. if even i then f i else g i) =\n    (\\<Sum>i<n. f (2 * i)) + (\\<Sum>i<n. g (2 * i + 1)) + (f (2 * n) + g (2 * n + 1))\"\n    using Suc.hyps unfolding One_nat_def by auto\n  also have \"\\<dots> = (\\<Sum>i<Suc n. f (2 * i)) + (\\<Sum>i<Suc n. g (2 * i + 1))\"\n    by auto\n  finally show ?case .\nqed\n\nlemma sums_if':\n  fixes g :: \"nat \\<Rightarrow> real\"\n  assumes \"g sums x\"\n  shows \"(\\<lambda> n. if even n then 0 else g ((n - 1) div 2)) sums x\"\n  unfolding sums_def\nproof (rule LIMSEQ_I)\n  fix r :: real\n  assume \"0 < r\"\n  from \\<open>g sums x\\<close>[unfolded sums_def, THEN LIMSEQ_D, OF this]\n  obtain no where no_eq: \"\\<And>n. n \\<ge> no \\<Longrightarrow> (norm (sum g {..<n} - x) < r)\"\n    by blast\n\n  let ?SUM = \"\\<lambda> m. \\<Sum>i<m. if even i then 0 else g ((i - 1) div 2)\"\n  have \"(norm (?SUM m - x) < r)\" if \"m \\<ge> 2 * no\" for m\n  proof -\n    from that have \"m div 2 \\<ge> no\" by auto\n    have sum_eq: \"?SUM (2 * (m div 2)) = sum g {..< m div 2}\"\n      using sum_split_even_odd by auto\n    then have \"(norm (?SUM (2 * (m div 2)) - x) < r)\"\n      using no_eq unfolding sum_eq using \\<open>m div 2 \\<ge> no\\<close> by auto\n    moreover\n    have \"?SUM (2 * (m div 2)) = ?SUM m\"\n    proof (cases \"even m\")\n      case True\n      then show ?thesis\n        by (auto simp add: even_two_times_div_two)\n    next\n      case False\n      then have eq: \"Suc (2 * (m div 2)) = m\" by simp\n      then have \"even (2 * (m div 2))\" using \\<open>odd m\\<close> by auto\n      have \"?SUM m = ?SUM (Suc (2 * (m div 2)))\" unfolding eq ..\n      also have \"\\<dots> = ?SUM (2 * (m div 2))\" using \\<open>even (2 * (m div 2))\\<close> by auto\n      finally show ?thesis by auto\n    qed\n    ultimately show ?thesis by auto\n  qed\n  then show \"\\<exists>no. \\<forall> m \\<ge> no. norm (?SUM m - x) < r\"\n    by blast\nqed\n\nlemma sums_if:\n  fixes g :: \"nat \\<Rightarrow> real\"\n  assumes \"g sums x\" and \"f sums y\"\n  shows \"(\\<lambda> n. if even n then f (n div 2) else g ((n - 1) div 2)) sums (x + y)\"\nproof -\n  let ?s = \"\\<lambda> n. if even n then 0 else f ((n - 1) div 2)\"\n  have if_sum: \"(if B then (0 :: real) else E) + (if B then T else 0) = (if B then T else E)\"\n    for B T E\n    by (cases B) auto\n  have g_sums: \"(\\<lambda> n. if even n then 0 else g ((n - 1) div 2)) sums x\"\n    using sums_if'[OF \\<open>g sums x\\<close>] .\n  have if_eq: \"\\<And>B T E. (if \\<not> B then T else E) = (if B then E else T)\"\n    by auto\n  have \"?s sums y\" using sums_if'[OF \\<open>f sums y\\<close>] .\n  from this[unfolded sums_def, THEN LIMSEQ_Suc]\n  have \"(\\<lambda>n. if even n then f (n div 2) else 0) sums y\"\n    by (simp add: lessThan_Suc_eq_insert_0 sum_atLeast1_atMost_eq image_Suc_lessThan\n        if_eq sums_def cong del: if_weak_cong)\n  from sums_add[OF g_sums this] show ?thesis\n    by (simp only: if_sum)\nqed\n\nsubsection \\<open>Alternating series test / Leibniz formula\\<close>\n(* FIXME: generalise these results from the reals via type classes? *)\n\nlemma sums_alternating_upper_lower:\n  fixes a :: \"nat \\<Rightarrow> real\"\n  assumes mono: \"\\<And>n. a (Suc n) \\<le> a n\"\n    and a_pos: \"\\<And>n. 0 \\<le> a n\"\n    and \"a \\<longlonglongrightarrow> 0\"\n  shows \"\\<exists>l. ((\\<forall>n. (\\<Sum>i<2*n. (- 1)^i*a i) \\<le> l) \\<and> (\\<lambda> n. \\<Sum>i<2*n. (- 1)^i*a i) \\<longlonglongrightarrow> l) \\<and>\n             ((\\<forall>n. l \\<le> (\\<Sum>i<2*n + 1. (- 1)^i*a i)) \\<and> (\\<lambda> n. \\<Sum>i<2*n + 1. (- 1)^i*a i) \\<longlonglongrightarrow> l)\"\n  (is \"\\<exists>l. ((\\<forall>n. ?f n \\<le> l) \\<and> _) \\<and> ((\\<forall>n. l \\<le> ?g n) \\<and> _)\")\nproof (rule nested_sequence_unique)\n  have fg_diff: \"\\<And>n. ?f n - ?g n = - a (2 * n)\" by auto\n\n  show \"\\<forall>n. ?f n \\<le> ?f (Suc n)\"\n  proof\n    show \"?f n \\<le> ?f (Suc n)\" for n\n      using mono[of \"2*n\"] by auto\n  qed\n  show \"\\<forall>n. ?g (Suc n) \\<le> ?g n\"\n  proof\n    show \"?g (Suc n) \\<le> ?g n\" for n\n      using mono[of \"Suc (2*n)\"] by auto\n  qed\n  show \"\\<forall>n. ?f n \\<le> ?g n\"\n  proof\n    show \"?f n \\<le> ?g n\" for n\n      using fg_diff a_pos by auto\n  qed\n  show \"(\\<lambda>n. ?f n - ?g n) \\<longlonglongrightarrow> 0\"\n    unfolding fg_diff\n  proof (rule LIMSEQ_I)\n    fix r :: real\n    assume \"0 < r\"\n    with \\<open>a \\<longlonglongrightarrow> 0\\<close>[THEN LIMSEQ_D] obtain N where \"\\<And> n. n \\<ge> N \\<Longrightarrow> norm (a n - 0) < r\"\n      by auto\n    then have \"\\<forall>n \\<ge> N. norm (- a (2 * n) - 0) < r\"\n      by auto\n    then show \"\\<exists>N. \\<forall>n \\<ge> N. norm (- a (2 * n) - 0) < r\"\n      by auto\n  qed\nqed\n\nlemma summable_Leibniz':\n  fixes a :: \"nat \\<Rightarrow> real\"\n  assumes a_zero: \"a \\<longlonglongrightarrow> 0\"\n    and a_pos: \"\\<And>n. 0 \\<le> a n\"\n    and a_monotone: \"\\<And>n. a (Suc n) \\<le> a n\"\n  shows summable: \"summable (\\<lambda> n. (-1)^n * a n)\"\n    and \"\\<And>n. (\\<Sum>i<2*n. (-1)^i*a i) \\<le> (\\<Sum>i. (-1)^i*a i)\"\n    and \"(\\<lambda>n. \\<Sum>i<2*n. (-1)^i*a i) \\<longlonglongrightarrow> (\\<Sum>i. (-1)^i*a i)\"\n    and \"\\<And>n. (\\<Sum>i. (-1)^i*a i) \\<le> (\\<Sum>i<2*n+1. (-1)^i*a i)\"\n    and \"(\\<lambda>n. \\<Sum>i<2*n+1. (-1)^i*a i) \\<longlonglongrightarrow> (\\<Sum>i. (-1)^i*a i)\"\nproof -\n  let ?S = \"\\<lambda>n. (-1)^n * a n\"\n  let ?P = \"\\<lambda>n. \\<Sum>i<n. ?S i\"\n  let ?f = \"\\<lambda>n. ?P (2 * n)\"\n  let ?g = \"\\<lambda>n. ?P (2 * n + 1)\"\n  obtain l :: real\n    where below_l: \"\\<forall> n. ?f n \\<le> l\"\n      and \"?f \\<longlonglongrightarrow> l\"\n      and above_l: \"\\<forall> n. l \\<le> ?g n\"\n      and \"?g \\<longlonglongrightarrow> l\"\n    using sums_alternating_upper_lower[OF a_monotone a_pos a_zero] by blast\n\n  let ?Sa = \"\\<lambda>m. \\<Sum>n<m. ?S n\"\n  have \"?Sa \\<longlonglongrightarrow> l\"\n  proof (rule LIMSEQ_I)\n    fix r :: real\n    assume \"0 < r\"\n    with \\<open>?f \\<longlonglongrightarrow> l\\<close>[THEN LIMSEQ_D]\n    obtain f_no where f: \"\\<And>n. n \\<ge> f_no \\<Longrightarrow> norm (?f n - l) < r\"\n      by auto\n    from \\<open>0 < r\\<close> \\<open>?g \\<longlonglongrightarrow> l\\<close>[THEN LIMSEQ_D]\n    obtain g_no where g: \"\\<And>n. n \\<ge> g_no \\<Longrightarrow> norm (?g n - l) < r\"\n      by auto\n    have \"norm (?Sa n - l) < r\" if \"n \\<ge> (max (2 * f_no) (2 * g_no))\" for n\n    proof -\n      from that have \"n \\<ge> 2 * f_no\" and \"n \\<ge> 2 * g_no\" by auto\n      show ?thesis\n      proof (cases \"even n\")\n        case True\n        then have n_eq: \"2 * (n div 2) = n\"\n          by (simp add: even_two_times_div_two)\n        with \\<open>n \\<ge> 2 * f_no\\<close> have \"n div 2 \\<ge> f_no\"\n          by auto\n        from f[OF this] show ?thesis\n          unfolding n_eq atLeastLessThanSuc_atLeastAtMost .\n      next\n        case False\n        then have \"even (n - 1)\" by simp\n        then have n_eq: \"2 * ((n - 1) div 2) = n - 1\"\n          by (simp add: even_two_times_div_two)\n        then have range_eq: \"n - 1 + 1 = n\"\n          using odd_pos[OF False] by auto\n        from n_eq \\<open>n \\<ge> 2 * g_no\\<close> have \"(n - 1) div 2 \\<ge> g_no\"\n          by auto\n        from g[OF this] show ?thesis\n          by (simp only: n_eq range_eq)\n      qed\n    qed\n    then show \"\\<exists>no. \\<forall>n \\<ge> no. norm (?Sa n - l) < r\" by blast\n  qed\n  then have sums_l: \"(\\<lambda>i. (-1)^i * a i) sums l\"\n    by (simp only: sums_def)\n  then show \"summable ?S\"\n    by (auto simp: summable_def)\n\n  have \"l = suminf ?S\" by (rule sums_unique[OF sums_l])\n\n  fix n\n  show \"suminf ?S \\<le> ?g n\"\n    unfolding sums_unique[OF sums_l, symmetric] using above_l by auto\n  show \"?f n \\<le> suminf ?S\"\n    unfolding sums_unique[OF sums_l, symmetric] using below_l by auto\n  show \"?g \\<longlonglongrightarrow> suminf ?S\"\n    using \\<open>?g \\<longlonglongrightarrow> l\\<close> \\<open>l = suminf ?S\\<close> by auto\n  show \"?f \\<longlonglongrightarrow> suminf ?S\"\n    using \\<open>?f \\<longlonglongrightarrow> l\\<close> \\<open>l = suminf ?S\\<close> by auto\nqed\n\ntheorem summable_Leibniz:\n  fixes a :: \"nat \\<Rightarrow> real\"\n  assumes a_zero: \"a \\<longlonglongrightarrow> 0\"\n    and \"monoseq a\"\n  shows \"summable (\\<lambda> n. (-1)^n * a n)\" (is \"?summable\")\n    and \"0 < a 0 \\<longrightarrow>\n      (\\<forall>n. (\\<Sum>i. (- 1)^i*a i) \\<in> { \\<Sum>i<2*n. (- 1)^i * a i .. \\<Sum>i<2*n+1. (- 1)^i * a i})\" (is \"?pos\")\n    and \"a 0 < 0 \\<longrightarrow>\n      (\\<forall>n. (\\<Sum>i. (- 1)^i*a i) \\<in> { \\<Sum>i<2*n+1. (- 1)^i * a i .. \\<Sum>i<2*n. (- 1)^i * a i})\" (is \"?neg\")\n    and \"(\\<lambda>n. \\<Sum>i<2*n. (- 1)^i*a i) \\<longlonglongrightarrow> (\\<Sum>i. (- 1)^i*a i)\" (is \"?f\")\n    and \"(\\<lambda>n. \\<Sum>i<2*n+1. (- 1)^i*a i) \\<longlonglongrightarrow> (\\<Sum>i. (- 1)^i*a i)\" (is \"?g\")\nproof -\n  have \"?summable \\<and> ?pos \\<and> ?neg \\<and> ?f \\<and> ?g\"\n  proof (cases \"(\\<forall>n. 0 \\<le> a n) \\<and> (\\<forall>m. \\<forall>n\\<ge>m. a n \\<le> a m)\")\n    case True\n    then have ord: \"\\<And>n m. m \\<le> n \\<Longrightarrow> a n \\<le> a m\"\n      and ge0: \"\\<And>n. 0 \\<le> a n\"\n      by auto\n    have mono: \"a (Suc n) \\<le> a n\" for n\n      using ord[where n=\"Suc n\" and m=n] by auto\n    note leibniz = summable_Leibniz'[OF \\<open>a \\<longlonglongrightarrow> 0\\<close> ge0]\n    from leibniz[OF mono]\n    show ?thesis using \\<open>0 \\<le> a 0\\<close> by auto\n  next\n    let ?a = \"\\<lambda>n. - a n\"\n    case False\n    with monoseq_le[OF \\<open>monoseq a\\<close> \\<open>a \\<longlonglongrightarrow> 0\\<close>]\n    have \"(\\<forall> n. a n \\<le> 0) \\<and> (\\<forall>m. \\<forall>n\\<ge>m. a m \\<le> a n)\" by auto\n    then have ord: \"\\<And>n m. m \\<le> n \\<Longrightarrow> ?a n \\<le> ?a m\" and ge0: \"\\<And> n. 0 \\<le> ?a n\"\n      by auto\n    have monotone: \"?a (Suc n) \\<le> ?a n\" for n\n      using ord[where n=\"Suc n\" and m=n] by auto\n    note leibniz =\n      summable_Leibniz'[OF _ ge0, of \"\\<lambda>x. x\",\n        OF tendsto_minus[OF \\<open>a \\<longlonglongrightarrow> 0\\<close>, unfolded minus_zero] monotone]\n    have \"summable (\\<lambda> n. (-1)^n * ?a n)\"\n      using leibniz(1) by auto\n    then obtain l where \"(\\<lambda> n. (-1)^n * ?a n) sums l\"\n      unfolding summable_def by auto\n    from this[THEN sums_minus] have \"(\\<lambda> n. (-1)^n * a n) sums -l\"\n      by auto\n    then have ?summable by (auto simp: summable_def)\n    moreover\n    have \"\\<bar>- a - - b\\<bar> = \\<bar>a - b\\<bar>\" for a b :: real\n      unfolding minus_diff_minus by auto\n\n    from suminf_minus[OF leibniz(1), unfolded mult_minus_right minus_minus]\n    have move_minus: \"(\\<Sum>n. - ((- 1) ^ n * a n)) = - (\\<Sum>n. (- 1) ^ n * a n)\"\n      by auto\n\n    have ?pos using \\<open>0 \\<le> ?a 0\\<close> by auto\n    moreover have ?neg\n      using leibniz(2,4)\n      unfolding mult_minus_right sum_negf move_minus neg_le_iff_le\n      by auto\n    moreover have ?f and ?g\n      using leibniz(3,5)[unfolded mult_minus_right sum_negf move_minus, THEN tendsto_minus_cancel]\n      by auto\n    ultimately show ?thesis by auto\n  qed\n  then show ?summable and ?pos and ?neg and ?f and ?g\n    by safe\nqed\n\n\nsubsection \\<open>Term-by-Term Differentiability of Power Series\\<close>\n\ndefinition diffs :: \"(nat \\<Rightarrow> 'a::ring_1) \\<Rightarrow> nat \\<Rightarrow> 'a\"\n  where \"diffs c = (\\<lambda>n. of_nat (Suc n) * c (Suc n))\"\n\ntext \\<open>Lemma about distributing negation over it.\\<close>\nlemma diffs_minus: \"diffs (\\<lambda>n. - c n) = (\\<lambda>n. - diffs c n)\"\n  by (simp add: diffs_def)\n\nlemma diffs_equiv:\n  fixes x :: \"'a::{real_normed_vector,ring_1}\"\n  shows \"summable (\\<lambda>n. diffs c n * x^n) \\<Longrightarrow>\n    (\\<lambda>n. of_nat n * c n * x^(n - Suc 0)) sums (\\<Sum>n. diffs c n * x^n)\"\n  unfolding diffs_def\n  by (simp add: summable_sums sums_Suc_imp)\n\nlemma lemma_termdiff1:\n  fixes z :: \"'a :: {monoid_mult,comm_ring}\"\n  shows \"(\\<Sum>p<m. (((z + h) ^ (m - p)) * (z ^ p)) - (z ^ m)) =\n    (\\<Sum>p<m. (z ^ p) * (((z + h) ^ (m - p)) - (z ^ (m - p))))\"\n  by (auto simp add: algebra_simps power_add [symmetric])\n\nlemma sumr_diff_mult_const2: \"sum f {..<n} - of_nat n * r = (\\<Sum>i<n. f i - r)\"\n  for r :: \"'a::ring_1\"\n  by (simp add: sum_subtractf)\n\nlemma lemma_realpow_rev_sumr:\n  \"(\\<Sum>p<Suc n. (x ^ p) * (y ^ (n - p))) = (\\<Sum>p<Suc n. (x ^ (n - p)) * (y ^ p))\"\n  by (subst nat_diff_sum_reindex[symmetric]) simp\n\nlemma lemma_termdiff2:\n  fixes h :: \"'a::field\"\n  assumes h: \"h \\<noteq> 0\"\n  shows \"((z + h) ^ n - z ^ n) / h - of_nat n * z ^ (n - Suc 0) =\n    h * (\\<Sum>p< n - Suc 0. \\<Sum>q< n - Suc 0 - p. (z + h) ^ q * z ^ (n - 2 - q))\"\n    (is \"?lhs = ?rhs\")\n  apply (subgoal_tac \"h * ?lhs = h * ?rhs\")\n   apply (simp add: h)\n  apply (simp add: right_diff_distrib diff_divide_distrib h)\n  apply (simp add: mult.assoc [symmetric])\n  apply (cases n)\n  apply simp\n  apply (simp add: diff_power_eq_sum h right_diff_distrib [symmetric] mult.assoc\n      del: power_Suc sum_lessThan_Suc of_nat_Suc)\n  apply (subst lemma_realpow_rev_sumr)\n  apply (subst sumr_diff_mult_const2)\n  apply simp\n  apply (simp only: lemma_termdiff1 sum_distrib_left)\n  apply (rule sum.cong [OF refl])\n  apply (simp add: less_iff_Suc_add)\n  apply clarify\n  apply (simp add: sum_distrib_left diff_power_eq_sum ac_simps\n      del: sum_lessThan_Suc power_Suc)\n  apply (subst mult.assoc [symmetric], subst power_add [symmetric])\n  apply (simp add: ac_simps)\n  done\n\nlemma real_sum_nat_ivl_bounded2:\n  fixes K :: \"'a::linordered_semidom\"\n  assumes f: \"\\<And>p::nat. p < n \\<Longrightarrow> f p \\<le> K\"\n    and K: \"0 \\<le> K\"\n  shows \"sum f {..<n-k} \\<le> of_nat n * K\"\n  apply (rule order_trans [OF sum_mono])\n   apply (rule f)\n   apply simp\n  apply (simp add: mult_right_mono K)\n  done\n\nlemma lemma_termdiff3:\n  fixes h z :: \"'a::real_normed_field\"\n  assumes 1: \"h \\<noteq> 0\"\n    and 2: \"norm z \\<le> K\"\n    and 3: \"norm (z + h) \\<le> K\"\n  shows \"norm (((z + h) ^ n - z ^ n) / h - of_nat n * z ^ (n - Suc 0)) \\<le>\n    of_nat n * of_nat (n - Suc 0) * K ^ (n - 2) * norm h\"\nproof -\n  have \"norm (((z + h) ^ n - z ^ n) / h - of_nat n * z ^ (n - Suc 0)) =\n    norm (\\<Sum>p<n - Suc 0. \\<Sum>q<n - Suc 0 - p. (z + h) ^ q * z ^ (n - 2 - q)) * norm h\"\n    by (metis (lifting, no_types) lemma_termdiff2 [OF 1] mult.commute norm_mult)\n  also have \"\\<dots> \\<le> of_nat n * (of_nat (n - Suc 0) * K ^ (n - 2)) * norm h\"\n  proof (rule mult_right_mono [OF _ norm_ge_zero])\n    from norm_ge_zero 2 have K: \"0 \\<le> K\"\n      by (rule order_trans)\n    have le_Kn: \"\\<And>i j n. i + j = n \\<Longrightarrow> norm ((z + h) ^ i * z ^ j) \\<le> K ^ n\"\n      apply (erule subst)\n      apply (simp only: norm_mult norm_power power_add)\n      apply (intro mult_mono power_mono 2 3 norm_ge_zero zero_le_power K)\n      done\n    show \"norm (\\<Sum>p<n - Suc 0. \\<Sum>q<n - Suc 0 - p. (z + h) ^ q * z ^ (n - 2 - q)) \\<le>\n        of_nat n * (of_nat (n - Suc 0) * K ^ (n - 2))\"\n      apply (intro\n          order_trans [OF norm_sum]\n          real_sum_nat_ivl_bounded2\n          mult_nonneg_nonneg\n          of_nat_0_le_iff\n          zero_le_power K)\n      apply (rule le_Kn)\n      apply simp\n      done\n  qed\n  also have \"\\<dots> = of_nat n * of_nat (n - Suc 0) * K ^ (n - 2) * norm h\"\n    by (simp only: mult.assoc)\n  finally show ?thesis .\nqed\n\nlemma lemma_termdiff4:\n  fixes f :: \"'a::real_normed_vector \\<Rightarrow> 'b::real_normed_vector\"\n    and k :: real\n  assumes k: \"0 < k\"\n    and le: \"\\<And>h. h \\<noteq> 0 \\<Longrightarrow> norm h < k \\<Longrightarrow> norm (f h) \\<le> K * norm h\"\n  shows \"f \\<midarrow>0\\<rightarrow> 0\"\nproof (rule tendsto_norm_zero_cancel)\n  show \"(\\<lambda>h. norm (f h)) \\<midarrow>0\\<rightarrow> 0\"\n  proof (rule real_tendsto_sandwich)\n    show \"eventually (\\<lambda>h. 0 \\<le> norm (f h)) (at 0)\"\n      by simp\n    show \"eventually (\\<lambda>h. norm (f h) \\<le> K * norm h) (at 0)\"\n      using k by (auto simp add: eventually_at dist_norm le)\n    show \"(\\<lambda>h. 0) \\<midarrow>(0::'a)\\<rightarrow> (0::real)\"\n      by (rule tendsto_const)\n    have \"(\\<lambda>h. K * norm h) \\<midarrow>(0::'a)\\<rightarrow> K * norm (0::'a)\"\n      by (intro tendsto_intros)\n    then show \"(\\<lambda>h. K * norm h) \\<midarrow>(0::'a)\\<rightarrow> 0\"\n      by simp\n  qed\nqed\n\nlemma lemma_termdiff5:\n  fixes g :: \"'a::real_normed_vector \\<Rightarrow> nat \\<Rightarrow> 'b::banach\"\n    and k :: real\n  assumes k: \"0 < k\"\n    and f: \"summable f\"\n    and le: \"\\<And>h n. h \\<noteq> 0 \\<Longrightarrow> norm h < k \\<Longrightarrow> norm (g h n) \\<le> f n * norm h\"\n  shows \"(\\<lambda>h. suminf (g h)) \\<midarrow>0\\<rightarrow> 0\"\nproof (rule lemma_termdiff4 [OF k])\n  fix h :: 'a\n  assume \"h \\<noteq> 0\" and \"norm h < k\"\n  then have 1: \"\\<forall>n. norm (g h n) \\<le> f n * norm h\"\n    by (simp add: le)\n  then have \"\\<exists>N. \\<forall>n\\<ge>N. norm (norm (g h n)) \\<le> f n * norm h\"\n    by simp\n  moreover from f have 2: \"summable (\\<lambda>n. f n * norm h)\"\n    by (rule summable_mult2)\n  ultimately have 3: \"summable (\\<lambda>n. norm (g h n))\"\n    by (rule summable_comparison_test)\n  then have \"norm (suminf (g h)) \\<le> (\\<Sum>n. norm (g h n))\"\n    by (rule summable_norm)\n  also from 1 3 2 have \"(\\<Sum>n. norm (g h n)) \\<le> (\\<Sum>n. f n * norm h)\"\n    by (rule suminf_le)\n  also from f have \"(\\<Sum>n. f n * norm h) = suminf f * norm h\"\n    by (rule suminf_mult2 [symmetric])\n  finally show \"norm (suminf (g h)) \\<le> suminf f * norm h\" .\nqed\n\n\n(* FIXME: Long proofs *)\n\nlemma termdiffs_aux:\n  fixes x :: \"'a::{real_normed_field,banach}\"\n  assumes 1: \"summable (\\<lambda>n. diffs (diffs c) n * K ^ n)\"\n    and 2: \"norm x < norm K\"\n  shows \"(\\<lambda>h. \\<Sum>n. c n * (((x + h) ^ n - x^n) / h - of_nat n * x ^ (n - Suc 0))) \\<midarrow>0\\<rightarrow> 0\"\nproof -\n  from dense [OF 2] obtain r where r1: \"norm x < r\" and r2: \"r < norm K\"\n    by fast\n  from norm_ge_zero r1 have r: \"0 < r\"\n    by (rule order_le_less_trans)\n  then have r_neq_0: \"r \\<noteq> 0\" by simp\n  show ?thesis\n  proof (rule lemma_termdiff5)\n    show \"0 < r - norm x\"\n      using r1 by simp\n    from r r2 have \"norm (of_real r::'a) < norm K\"\n      by simp\n    with 1 have \"summable (\\<lambda>n. norm (diffs (diffs c) n * (of_real r ^ n)))\"\n      by (rule powser_insidea)\n    then have \"summable (\\<lambda>n. diffs (diffs (\\<lambda>n. norm (c n))) n * r ^ n)\"\n      using r by (simp add: diffs_def norm_mult norm_power del: of_nat_Suc)\n    then have \"summable (\\<lambda>n. of_nat n * diffs (\\<lambda>n. norm (c n)) n * r ^ (n - Suc 0))\"\n      by (rule diffs_equiv [THEN sums_summable])\n    also have \"(\\<lambda>n. of_nat n * diffs (\\<lambda>n. norm (c n)) n * r ^ (n - Suc 0)) =\n      (\\<lambda>n. diffs (\\<lambda>m. of_nat (m - Suc 0) * norm (c m) * inverse r) n * (r ^ n))\"\n      apply (rule ext)\n      apply (simp add: diffs_def)\n      apply (case_tac n)\n       apply (simp_all add: r_neq_0)\n      done\n    finally have \"summable\n      (\\<lambda>n. of_nat n * (of_nat (n - Suc 0) * norm (c n) * inverse r) * r ^ (n - Suc 0))\"\n      by (rule diffs_equiv [THEN sums_summable])\n    also have\n      \"(\\<lambda>n. of_nat n * (of_nat (n - Suc 0) * norm (c n) * inverse r) * r ^ (n - Suc 0)) =\n       (\\<lambda>n. norm (c n) * of_nat n * of_nat (n - Suc 0) * r ^ (n - 2))\"\n      apply (rule ext)\n      apply (case_tac n)\n       apply simp\n      apply (rename_tac nat)\n      apply (case_tac nat)\n       apply simp\n      apply (simp add: r_neq_0)\n      done\n    finally show \"summable (\\<lambda>n. norm (c n) * of_nat n * of_nat (n - Suc 0) * r ^ (n - 2))\" .\n  next\n    fix h :: 'a\n    fix n :: nat\n    assume h: \"h \\<noteq> 0\"\n    assume \"norm h < r - norm x\"\n    then have \"norm x + norm h < r\" by simp\n    with norm_triangle_ineq have xh: \"norm (x + h) < r\"\n      by (rule order_le_less_trans)\n    show \"norm (c n * (((x + h) ^ n - x^n) / h - of_nat n * x ^ (n - Suc 0))) \\<le>\n      norm (c n) * of_nat n * of_nat (n - Suc 0) * r ^ (n - 2) * norm h\"\n      apply (simp only: norm_mult mult.assoc)\n      apply (rule mult_left_mono [OF _ norm_ge_zero])\n      apply (simp add: mult.assoc [symmetric])\n      apply (metis h lemma_termdiff3 less_eq_real_def r1 xh)\n      done\n  qed\nqed\n\nlemma termdiffs:\n  fixes K x :: \"'a::{real_normed_field,banach}\"\n  assumes 1: \"summable (\\<lambda>n. c n * K ^ n)\"\n    and 2: \"summable (\\<lambda>n. (diffs c) n * K ^ n)\"\n    and 3: \"summable (\\<lambda>n. (diffs (diffs c)) n * K ^ n)\"\n    and 4: \"norm x < norm K\"\n  shows \"DERIV (\\<lambda>x. \\<Sum>n. c n * x^n) x :> (\\<Sum>n. (diffs c) n * x^n)\"\n  unfolding DERIV_def\nproof (rule LIM_zero_cancel)\n  show \"(\\<lambda>h. (suminf (\\<lambda>n. c n * (x + h) ^ n) - suminf (\\<lambda>n. c n * x^n)) / h\n            - suminf (\\<lambda>n. diffs c n * x^n)) \\<midarrow>0\\<rightarrow> 0\"\n  proof (rule LIM_equal2)\n    show \"0 < norm K - norm x\"\n      using 4 by (simp add: less_diff_eq)\n  next\n    fix h :: 'a\n    assume \"norm (h - 0) < norm K - norm x\"\n    then have \"norm x + norm h < norm K\" by simp\n    then have 5: \"norm (x + h) < norm K\"\n      by (rule norm_triangle_ineq [THEN order_le_less_trans])\n    have \"summable (\\<lambda>n. c n * x^n)\"\n      and \"summable (\\<lambda>n. c n * (x + h) ^ n)\"\n      and \"summable (\\<lambda>n. diffs c n * x^n)\"\n      using 1 2 4 5 by (auto elim: powser_inside)\n    then have \"((\\<Sum>n. c n * (x + h) ^ n) - (\\<Sum>n. c n * x^n)) / h - (\\<Sum>n. diffs c n * x^n) =\n          (\\<Sum>n. (c n * (x + h) ^ n - c n * x^n) / h - of_nat n * c n * x ^ (n - Suc 0))\"\n      by (intro sums_unique sums_diff sums_divide diffs_equiv summable_sums)\n    then show \"((\\<Sum>n. c n * (x + h) ^ n) - (\\<Sum>n. c n * x^n)) / h - (\\<Sum>n. diffs c n * x^n) =\n          (\\<Sum>n. c n * (((x + h) ^ n - x^n) / h - of_nat n * x ^ (n - Suc 0)))\"\n      by (simp add: algebra_simps)\n  next\n    show \"(\\<lambda>h. \\<Sum>n. c n * (((x + h) ^ n - x^n) / h - of_nat n * x ^ (n - Suc 0))) \\<midarrow>0\\<rightarrow> 0\"\n      by (rule termdiffs_aux [OF 3 4])\n  qed\nqed\n\nsubsection \\<open>The Derivative of a Power Series Has the Same Radius of Convergence\\<close>\n\nlemma termdiff_converges:\n  fixes x :: \"'a::{real_normed_field,banach}\"\n  assumes K: \"norm x < K\"\n    and sm: \"\\<And>x. norm x < K \\<Longrightarrow> summable(\\<lambda>n. c n * x ^ n)\"\n  shows \"summable (\\<lambda>n. diffs c n * x ^ n)\"\nproof (cases \"x = 0\")\n  case True\n  then show ?thesis\n    using powser_sums_zero sums_summable by auto\nnext\n  case False\n  then have \"K > 0\"\n    using K less_trans zero_less_norm_iff by blast\n  then obtain r :: real where r: \"norm x < norm r\" \"norm r < K\" \"r > 0\"\n    using K False\n    by (auto simp: field_simps abs_less_iff add_pos_pos intro: that [of \"(norm x + K) / 2\"])\n  have \"(\\<lambda>n. of_nat n * (x / of_real r) ^ n) \\<longlonglongrightarrow> 0\"\n    using r by (simp add: norm_divide powser_times_n_limit_0 [of \"x / of_real r\"])\n  then obtain N where N: \"\\<And>n. n\\<ge>N \\<Longrightarrow> real_of_nat n * norm x ^ n < r ^ n\"\n    using r unfolding LIMSEQ_iff\n    apply (drule_tac x=1 in spec)\n    apply (auto simp: norm_divide norm_mult norm_power field_simps)\n    done\n  have \"summable (\\<lambda>n. (of_nat n * c n) * x ^ n)\"\n    apply (rule summable_comparison_test' [of \"\\<lambda>n. norm(c n * (of_real r) ^ n)\" N])\n     apply (rule powser_insidea [OF sm [of \"of_real ((r+K)/2)\"]])\n    using N r norm_of_real [of \"r + K\", where 'a = 'a]\n      apply (auto simp add: norm_divide norm_mult norm_power field_simps)\n    apply (fastforce simp: less_eq_real_def)\n    done\n  then have \"summable (\\<lambda>n. (of_nat (Suc n) * c(Suc n)) * x ^ Suc n)\"\n    using summable_iff_shift [of \"\\<lambda>n. of_nat n * c n * x ^ n\" 1]\n    by simp\n  then have \"summable (\\<lambda>n. (of_nat (Suc n) * c(Suc n)) * x ^ n)\"\n    using False summable_mult2 [of \"\\<lambda>n. (of_nat (Suc n) * c(Suc n) * x ^ n) * x\" \"inverse x\"]\n    by (simp add: mult.assoc) (auto simp: ac_simps)\n  then show ?thesis\n    by (simp add: diffs_def)\nqed\n\nlemma termdiff_converges_all:\n  fixes x :: \"'a::{real_normed_field,banach}\"\n  assumes \"\\<And>x. summable (\\<lambda>n. c n * x^n)\"\n  shows \"summable (\\<lambda>n. diffs c n * x^n)\"\n  apply (rule termdiff_converges [where K = \"1 + norm x\"])\n  using assms\n   apply auto\n  done\n\nlemma termdiffs_strong:\n  fixes K x :: \"'a::{real_normed_field,banach}\"\n  assumes sm: \"summable (\\<lambda>n. c n * K ^ n)\"\n    and K: \"norm x < norm K\"\n  shows \"DERIV (\\<lambda>x. \\<Sum>n. c n * x^n) x :> (\\<Sum>n. diffs c n * x^n)\"\nproof -\n  have K2: \"norm ((of_real (norm K) + of_real (norm x)) / 2 :: 'a) < norm K\"\n    using K\n    apply (auto simp: norm_divide field_simps)\n    apply (rule le_less_trans [of _ \"of_real (norm K) + of_real (norm x)\"])\n     apply (auto simp: mult_2_right norm_triangle_mono)\n    done\n  then have [simp]: \"norm ((of_real (norm K) + of_real (norm x)) :: 'a) < norm K * 2\"\n    by simp\n  have \"summable (\\<lambda>n. c n * (of_real (norm x + norm K) / 2) ^ n)\"\n    by (metis K2 summable_norm_cancel [OF powser_insidea [OF sm]] add.commute of_real_add)\n  moreover have \"\\<And>x. norm x < norm K \\<Longrightarrow> summable (\\<lambda>n. diffs c n * x ^ n)\"\n    by (blast intro: sm termdiff_converges powser_inside)\n  moreover have \"\\<And>x. norm x < norm K \\<Longrightarrow> summable (\\<lambda>n. diffs(diffs c) n * x ^ n)\"\n    by (blast intro: sm termdiff_converges powser_inside)\n  ultimately show ?thesis\n    apply (rule termdiffs [where K = \"of_real (norm x + norm K) / 2\"])\n      apply (auto simp: field_simps)\n    using K\n    apply (simp_all add: of_real_add [symmetric] del: of_real_add)\n    done\nqed\n\nlemma termdiffs_strong_converges_everywhere:\n  fixes K x :: \"'a::{real_normed_field,banach}\"\n  assumes \"\\<And>y. summable (\\<lambda>n. c n * y ^ n)\"\n  shows \"((\\<lambda>x. \\<Sum>n. c n * x^n) has_field_derivative (\\<Sum>n. diffs c n * x^n)) (at x)\"\n  using termdiffs_strong[OF assms[of \"of_real (norm x + 1)\"], of x]\n  by (force simp del: of_real_add)\n\nlemma termdiffs_strong':\n  fixes z :: \"'a :: {real_normed_field,banach}\"\n  assumes \"\\<And>z. norm z < K \\<Longrightarrow> summable (\\<lambda>n. c n * z ^ n)\"\n  assumes \"norm z < K\"\n  shows   \"((\\<lambda>z. \\<Sum>n. c n * z^n) has_field_derivative (\\<Sum>n. diffs c n * z^n)) (at z)\"\nproof (rule termdiffs_strong)\n  define L :: real where \"L =  (norm z + K) / 2\"\n  have \"0 \\<le> norm z\" by simp\n  also note \\<open>norm z < K\\<close>\n  finally have K: \"K \\<ge> 0\" by simp\n  from assms K have L: \"L \\<ge> 0\" \"norm z < L\" \"L < K\" by (simp_all add: L_def)\n  from L show \"norm z < norm (of_real L :: 'a)\" by simp\n  from L show \"summable (\\<lambda>n. c n * of_real L ^ n)\" by (intro assms(1)) simp_all\nqed\n\nlemma termdiffs_sums_strong:\n  fixes z :: \"'a :: {banach,real_normed_field}\"\n  assumes sums: \"\\<And>z. norm z < K \\<Longrightarrow> (\\<lambda>n. c n * z ^ n) sums f z\"\n  assumes deriv: \"(f has_field_derivative f') (at z)\"\n  assumes norm: \"norm z < K\"\n  shows   \"(\\<lambda>n. diffs c n * z ^ n) sums f'\"\nproof -\n  have summable: \"summable (\\<lambda>n. diffs c n * z^n)\"\n    by (intro termdiff_converges[OF norm] sums_summable[OF sums])\n  from norm have \"eventually (\\<lambda>z. z \\<in> norm -` {..<K}) (nhds z)\"\n    by (intro eventually_nhds_in_open open_vimage) \n       (simp_all add: continuous_on_norm continuous_on_id)\n  hence eq: \"eventually (\\<lambda>z. (\\<Sum>n. c n * z^n) = f z) (nhds z)\"\n    by eventually_elim (insert sums, simp add: sums_iff)\n\n  have \"((\\<lambda>z. \\<Sum>n. c n * z^n) has_field_derivative (\\<Sum>n. diffs c n * z^n)) (at z)\"\n    by (intro termdiffs_strong'[OF _ norm] sums_summable[OF sums])\n  hence \"(f has_field_derivative (\\<Sum>n. diffs c n * z^n)) (at z)\"\n    by (subst (asm) DERIV_cong_ev[OF refl eq refl])\n  from this and deriv have \"(\\<Sum>n. diffs c n * z^n) = f'\" by (rule DERIV_unique)\n  with summable show ?thesis by (simp add: sums_iff)\nqed\n\nlemma isCont_powser:\n  fixes K x :: \"'a::{real_normed_field,banach}\"\n  assumes \"summable (\\<lambda>n. c n * K ^ n)\"\n  assumes \"norm x < norm K\"\n  shows \"isCont (\\<lambda>x. \\<Sum>n. c n * x^n) x\"\n  using termdiffs_strong[OF assms] by (blast intro!: DERIV_isCont)\n\nlemmas isCont_powser' = isCont_o2[OF _ isCont_powser]\n\nlemma isCont_powser_converges_everywhere:\n  fixes K x :: \"'a::{real_normed_field,banach}\"\n  assumes \"\\<And>y. summable (\\<lambda>n. c n * y ^ n)\"\n  shows \"isCont (\\<lambda>x. \\<Sum>n. c n * x^n) x\"\n  using termdiffs_strong[OF assms[of \"of_real (norm x + 1)\"], of x]\n  by (force intro!: DERIV_isCont simp del: of_real_add)\n\nlemma powser_limit_0:\n  fixes a :: \"nat \\<Rightarrow> 'a::{real_normed_field,banach}\"\n  assumes s: \"0 < s\"\n    and sm: \"\\<And>x. norm x < s \\<Longrightarrow> (\\<lambda>n. a n * x ^ n) sums (f x)\"\n  shows \"(f \\<longlongrightarrow> a 0) (at 0)\"\nproof -\n  have \"summable (\\<lambda>n. a n * (of_real s / 2) ^ n)\"\n    apply (rule sums_summable [where l = \"f (of_real s / 2)\", OF sm])\n    using s\n    apply (auto simp: norm_divide)\n    done\n  then have \"((\\<lambda>x. \\<Sum>n. a n * x ^ n) has_field_derivative (\\<Sum>n. diffs a n * 0 ^ n)) (at 0)\"\n    apply (rule termdiffs_strong)\n    using s\n    apply (auto simp: norm_divide)\n    done\n  then have \"isCont (\\<lambda>x. \\<Sum>n. a n * x ^ n) 0\"\n    by (blast intro: DERIV_continuous)\n  then have \"((\\<lambda>x. \\<Sum>n. a n * x ^ n) \\<longlongrightarrow> a 0) (at 0)\"\n    by (simp add: continuous_within)\n  then show ?thesis\n    apply (rule Lim_transform)\n    apply (auto simp add: LIM_eq)\n    apply (rule_tac x=\"s\" in exI)\n    using s\n    apply (auto simp: sm [THEN sums_unique])\n    done\nqed\n\nlemma powser_limit_0_strong:\n  fixes a :: \"nat \\<Rightarrow> 'a::{real_normed_field,banach}\"\n  assumes s: \"0 < s\"\n    and sm: \"\\<And>x. x \\<noteq> 0 \\<Longrightarrow> norm x < s \\<Longrightarrow> (\\<lambda>n. a n * x ^ n) sums (f x)\"\n  shows \"(f \\<longlongrightarrow> a 0) (at 0)\"\nproof -\n  have *: \"((\\<lambda>x. if x = 0 then a 0 else f x) \\<longlongrightarrow> a 0) (at 0)\"\n    apply (rule powser_limit_0 [OF s])\n    apply (case_tac \"x = 0\")\n     apply (auto simp add: powser_sums_zero sm)\n    done\n  show ?thesis\n    apply (subst LIM_equal [where g = \"(\\<lambda>x. if x = 0 then a 0 else f x)\"])\n     apply (simp_all add: *)\n    done\nqed\n\n\nsubsection \\<open>Derivability of power series\\<close>\n\nlemma DERIV_series':\n  fixes f :: \"real \\<Rightarrow> nat \\<Rightarrow> real\"\n  assumes DERIV_f: \"\\<And> n. DERIV (\\<lambda> x. f x n) x0 :> (f' x0 n)\"\n    and allf_summable: \"\\<And> x. x \\<in> {a <..< b} \\<Longrightarrow> summable (f x)\"\n    and x0_in_I: \"x0 \\<in> {a <..< b}\"\n    and \"summable (f' x0)\"\n    and \"summable L\"\n    and L_def: \"\\<And>n x y. x \\<in> {a <..< b} \\<Longrightarrow> y \\<in> {a <..< b} \\<Longrightarrow> \\<bar>f x n - f y n\\<bar> \\<le> L n * \\<bar>x - y\\<bar>\"\n  shows \"DERIV (\\<lambda> x. suminf (f x)) x0 :> (suminf (f' x0))\"\n  unfolding DERIV_def\nproof (rule LIM_I)\n  fix r :: real\n  assume \"0 < r\" then have \"0 < r/3\" by auto\n\n  obtain N_L where N_L: \"\\<And> n. N_L \\<le> n \\<Longrightarrow> \\<bar> \\<Sum> i. L (i + n) \\<bar> < r/3\"\n    using suminf_exist_split[OF \\<open>0 < r/3\\<close> \\<open>summable L\\<close>] by auto\n\n  obtain N_f' where N_f': \"\\<And> n. N_f' \\<le> n \\<Longrightarrow> \\<bar> \\<Sum> i. f' x0 (i + n) \\<bar> < r/3\"\n    using suminf_exist_split[OF \\<open>0 < r/3\\<close> \\<open>summable (f' x0)\\<close>] by auto\n\n  let ?N = \"Suc (max N_L N_f')\"\n  have \"\\<bar> \\<Sum> i. f' x0 (i + ?N) \\<bar> < r/3\" (is \"?f'_part < r/3\")\n    and L_estimate: \"\\<bar> \\<Sum> i. L (i + ?N) \\<bar> < r/3\"\n    using N_L[of \"?N\"] and N_f' [of \"?N\"] by auto\n\n  let ?diff = \"\\<lambda>i x. (f (x0 + x) i - f x0 i) / x\"\n\n  let ?r = \"r / (3 * real ?N)\"\n  from \\<open>0 < r\\<close> have \"0 < ?r\" by simp\n\n  let ?s = \"\\<lambda>n. SOME s. 0 < s \\<and> (\\<forall> x. x \\<noteq> 0 \\<and> \\<bar> x \\<bar> < s \\<longrightarrow> \\<bar> ?diff n x - f' x0 n \\<bar> < ?r)\"\n  define S' where \"S' = Min (?s ` {..< ?N })\"\n\n  have \"0 < S'\"\n    unfolding S'_def\n  proof (rule iffD2[OF Min_gr_iff])\n    show \"\\<forall>x \\<in> (?s ` {..< ?N }). 0 < x\"\n    proof\n      fix x\n      assume \"x \\<in> ?s ` {..<?N}\"\n      then obtain n where \"x = ?s n\" and \"n \\<in> {..<?N}\"\n        using image_iff[THEN iffD1] by blast\n      from DERIV_D[OF DERIV_f[where n=n], THEN LIM_D, OF \\<open>0 < ?r\\<close>, unfolded real_norm_def]\n      obtain s where s_bound: \"0 < s \\<and> (\\<forall>x. x \\<noteq> 0 \\<and> \\<bar>x\\<bar> < s \\<longrightarrow> \\<bar>?diff n x - f' x0 n\\<bar> < ?r)\"\n        by auto\n      have \"0 < ?s n\"\n        by (rule someI2[where a=s]) (auto simp add: s_bound simp del: of_nat_Suc)\n      then show \"0 < x\" by (simp only: \\<open>x = ?s n\\<close>)\n    qed\n  qed auto\n\n  define S where \"S = min (min (x0 - a) (b - x0)) S'\"\n  then have \"0 < S\" and S_a: \"S \\<le> x0 - a\" and S_b: \"S \\<le> b - x0\"\n    and \"S \\<le> S'\" using x0_in_I and \\<open>0 < S'\\<close>\n    by auto\n\n  have \"\\<bar>(suminf (f (x0 + x)) - suminf (f x0)) / x - suminf (f' x0)\\<bar> < r\"\n    if \"x \\<noteq> 0\" and \"\\<bar>x\\<bar> < S\" for x\n  proof -\n    from that have x_in_I: \"x0 + x \\<in> {a <..< b}\"\n      using S_a S_b by auto\n\n    note diff_smbl = summable_diff[OF allf_summable[OF x_in_I] allf_summable[OF x0_in_I]]\n    note div_smbl = summable_divide[OF diff_smbl]\n    note all_smbl = summable_diff[OF div_smbl \\<open>summable (f' x0)\\<close>]\n    note ign = summable_ignore_initial_segment[where k=\"?N\"]\n    note diff_shft_smbl = summable_diff[OF ign[OF allf_summable[OF x_in_I]] ign[OF allf_summable[OF x0_in_I]]]\n    note div_shft_smbl = summable_divide[OF diff_shft_smbl]\n    note all_shft_smbl = summable_diff[OF div_smbl ign[OF \\<open>summable (f' x0)\\<close>]]\n\n    have 1: \"\\<bar>(\\<bar>?diff (n + ?N) x\\<bar>)\\<bar> \\<le> L (n + ?N)\" for n\n    proof -\n      have \"\\<bar>?diff (n + ?N) x\\<bar> \\<le> L (n + ?N) * \\<bar>(x0 + x) - x0\\<bar> / \\<bar>x\\<bar>\"\n        using divide_right_mono[OF L_def[OF x_in_I x0_in_I] abs_ge_zero]\n        by (simp only: abs_divide)\n      with \\<open>x \\<noteq> 0\\<close> show ?thesis by auto\n    qed\n    note 2 = summable_rabs_comparison_test[OF _ ign[OF \\<open>summable L\\<close>]]\n    from 1 have \"\\<bar> \\<Sum> i. ?diff (i + ?N) x \\<bar> \\<le> (\\<Sum> i. L (i + ?N))\"\n      by (metis (lifting) abs_idempotent\n          order_trans[OF summable_rabs[OF 2] suminf_le[OF _ 2 ign[OF \\<open>summable L\\<close>]]])\n    then have \"\\<bar>\\<Sum>i. ?diff (i + ?N) x\\<bar> \\<le> r / 3\" (is \"?L_part \\<le> r/3\")\n      using L_estimate by auto\n\n    have \"\\<bar>\\<Sum>n<?N. ?diff n x - f' x0 n\\<bar> \\<le> (\\<Sum>n<?N. \\<bar>?diff n x - f' x0 n\\<bar>)\" ..\n    also have \"\\<dots> < (\\<Sum>n<?N. ?r)\"\n    proof (rule sum_strict_mono)\n      fix n\n      assume \"n \\<in> {..< ?N}\"\n      have \"\\<bar>x\\<bar> < S\" using \\<open>\\<bar>x\\<bar> < S\\<close> .\n      also have \"S \\<le> S'\" using \\<open>S \\<le> S'\\<close> .\n      also have \"S' \\<le> ?s n\"\n        unfolding S'_def\n      proof (rule Min_le_iff[THEN iffD2])\n        have \"?s n \\<in> (?s ` {..<?N}) \\<and> ?s n \\<le> ?s n\"\n          using \\<open>n \\<in> {..< ?N}\\<close> by auto\n        then show \"\\<exists> a \\<in> (?s ` {..<?N}). a \\<le> ?s n\"\n          by blast\n      qed auto\n      finally have \"\\<bar>x\\<bar> < ?s n\" .\n\n      from DERIV_D[OF DERIV_f[where n=n], THEN LIM_D, OF \\<open>0 < ?r\\<close>,\n          unfolded real_norm_def diff_0_right, unfolded some_eq_ex[symmetric], THEN conjunct2]\n      have \"\\<forall>x. x \\<noteq> 0 \\<and> \\<bar>x\\<bar> < ?s n \\<longrightarrow> \\<bar>?diff n x - f' x0 n\\<bar> < ?r\" .\n      with \\<open>x \\<noteq> 0\\<close> and \\<open>\\<bar>x\\<bar> < ?s n\\<close> show \"\\<bar>?diff n x - f' x0 n\\<bar> < ?r\"\n        by blast\n    qed auto\n    also have \"\\<dots> = of_nat (card {..<?N}) * ?r\"\n      by (rule sum_constant)\n    also have \"\\<dots> = real ?N * ?r\"\n      by simp\n    also have \"\\<dots> = r/3\"\n      by (auto simp del: of_nat_Suc)\n    finally have \"\\<bar>\\<Sum>n<?N. ?diff n x - f' x0 n \\<bar> < r / 3\" (is \"?diff_part < r / 3\") .\n\n    from suminf_diff[OF allf_summable[OF x_in_I] allf_summable[OF x0_in_I]]\n    have \"\\<bar>(suminf (f (x0 + x)) - (suminf (f x0))) / x - suminf (f' x0)\\<bar> =\n        \\<bar>\\<Sum>n. ?diff n x - f' x0 n\\<bar>\"\n      unfolding suminf_diff[OF div_smbl \\<open>summable (f' x0)\\<close>, symmetric]\n      using suminf_divide[OF diff_smbl, symmetric] by auto\n    also have \"\\<dots> \\<le> ?diff_part + \\<bar>(\\<Sum>n. ?diff (n + ?N) x) - (\\<Sum> n. f' x0 (n + ?N))\\<bar>\"\n      unfolding suminf_split_initial_segment[OF all_smbl, where k=\"?N\"]\n      unfolding suminf_diff[OF div_shft_smbl ign[OF \\<open>summable (f' x0)\\<close>]]\n      apply (subst (5) add.commute)\n      apply (rule abs_triangle_ineq)\n      done\n    also have \"\\<dots> \\<le> ?diff_part + ?L_part + ?f'_part\"\n      using abs_triangle_ineq4 by auto\n    also have \"\\<dots> < r /3 + r/3 + r/3\"\n      using \\<open>?diff_part < r/3\\<close> \\<open>?L_part \\<le> r/3\\<close> and \\<open>?f'_part < r/3\\<close>\n      by (rule add_strict_mono [OF add_less_le_mono])\n    finally show ?thesis\n      by auto\n  qed\n  then show \"\\<exists>s > 0. \\<forall> x. x \\<noteq> 0 \\<and> norm (x - 0) < s \\<longrightarrow>\n      norm (((\\<Sum>n. f (x0 + x) n) - (\\<Sum>n. f x0 n)) / x - (\\<Sum>n. f' x0 n)) < r\"\n    using \\<open>0 < S\\<close> by auto\nqed\n\nlemma DERIV_power_series':\n  fixes f :: \"nat \\<Rightarrow> real\"\n  assumes converges: \"\\<And>x. x \\<in> {-R <..< R} \\<Longrightarrow> summable (\\<lambda>n. f n * real (Suc n) * x^n)\"\n    and x0_in_I: \"x0 \\<in> {-R <..< R}\"\n    and \"0 < R\"\n  shows \"DERIV (\\<lambda>x. (\\<Sum>n. f n * x^(Suc n))) x0 :> (\\<Sum>n. f n * real (Suc n) * x0^n)\"\n    (is \"DERIV (\\<lambda>x. suminf (?f x)) x0 :> suminf (?f' x0)\")\nproof -\n  have for_subinterval: \"DERIV (\\<lambda>x. suminf (?f x)) x0 :> suminf (?f' x0)\"\n    if \"0 < R'\" and \"R' < R\" and \"-R' < x0\" and \"x0 < R'\" for R'\n  proof -\n    from that have \"x0 \\<in> {-R' <..< R'}\" and \"R' \\<in> {-R <..< R}\" and \"x0 \\<in> {-R <..< R}\"\n      by auto\n    show ?thesis\n    proof (rule DERIV_series')\n      show \"summable (\\<lambda> n. \\<bar>f n * real (Suc n) * R'^n\\<bar>)\"\n      proof -\n        have \"(R' + R) / 2 < R\" and \"0 < (R' + R) / 2\"\n          using \\<open>0 < R'\\<close> \\<open>0 < R\\<close> \\<open>R' < R\\<close> by (auto simp: field_simps)\n        then have in_Rball: \"(R' + R) / 2 \\<in> {-R <..< R}\"\n          using \\<open>R' < R\\<close> by auto\n        have \"norm R' < norm ((R' + R) / 2)\"\n          using \\<open>0 < R'\\<close> \\<open>0 < R\\<close> \\<open>R' < R\\<close> by (auto simp: field_simps)\n        from powser_insidea[OF converges[OF in_Rball] this] show ?thesis\n          by auto\n      qed\n    next\n      fix n x y\n      assume \"x \\<in> {-R' <..< R'}\" and \"y \\<in> {-R' <..< R'}\"\n      show \"\\<bar>?f x n - ?f y n\\<bar> \\<le> \\<bar>f n * real (Suc n) * R'^n\\<bar> * \\<bar>x-y\\<bar>\"\n      proof -\n        have \"\\<bar>f n * x ^ (Suc n) - f n * y ^ (Suc n)\\<bar> =\n          (\\<bar>f n\\<bar> * \\<bar>x-y\\<bar>) * \\<bar>\\<Sum>p<Suc n. x ^ p * y ^ (n - p)\\<bar>\"\n          unfolding right_diff_distrib[symmetric] diff_power_eq_sum abs_mult\n          by auto\n        also have \"\\<dots> \\<le> (\\<bar>f n\\<bar> * \\<bar>x-y\\<bar>) * (\\<bar>real (Suc n)\\<bar> * \\<bar>R' ^ n\\<bar>)\"\n        proof (rule mult_left_mono)\n          have \"\\<bar>\\<Sum>p<Suc n. x ^ p * y ^ (n - p)\\<bar> \\<le> (\\<Sum>p<Suc n. \\<bar>x ^ p * y ^ (n - p)\\<bar>)\"\n            by (rule sum_abs)\n          also have \"\\<dots> \\<le> (\\<Sum>p<Suc n. R' ^ n)\"\n          proof (rule sum_mono)\n            fix p\n            assume \"p \\<in> {..<Suc n}\"\n            then have \"p \\<le> n\" by auto\n            have \"\\<bar>x^n\\<bar> \\<le> R'^n\" if  \"x \\<in> {-R'<..<R'}\" for n and x :: real\n            proof -\n              from that have \"\\<bar>x\\<bar> \\<le> R'\" by auto\n              then show ?thesis\n                unfolding power_abs by (rule power_mono) auto\n            qed\n            from mult_mono[OF this[OF \\<open>x \\<in> {-R'<..<R'}\\<close>, of p] this[OF \\<open>y \\<in> {-R'<..<R'}\\<close>, of \"n-p\"]]\n              and \\<open>0 < R'\\<close>\n            have \"\\<bar>x^p * y^(n - p)\\<bar> \\<le> R'^p * R'^(n - p)\"\n              unfolding abs_mult by auto\n            then show \"\\<bar>x^p * y^(n - p)\\<bar> \\<le> R'^n\"\n              unfolding power_add[symmetric] using \\<open>p \\<le> n\\<close> by auto\n          qed\n          also have \"\\<dots> = real (Suc n) * R' ^ n\"\n            unfolding sum_constant card_atLeastLessThan by auto\n          finally show \"\\<bar>\\<Sum>p<Suc n. x ^ p * y ^ (n - p)\\<bar> \\<le> \\<bar>real (Suc n)\\<bar> * \\<bar>R' ^ n\\<bar>\"\n            unfolding abs_of_nonneg[OF zero_le_power[OF less_imp_le[OF \\<open>0 < R'\\<close>]]]\n            by linarith\n          show \"0 \\<le> \\<bar>f n\\<bar> * \\<bar>x - y\\<bar>\"\n            unfolding abs_mult[symmetric] by auto\n        qed\n        also have \"\\<dots> = \\<bar>f n * real (Suc n) * R' ^ n\\<bar> * \\<bar>x - y\\<bar>\"\n          unfolding abs_mult mult.assoc[symmetric] by algebra\n        finally show ?thesis .\n      qed\n    next\n      show \"DERIV (\\<lambda>x. ?f x n) x0 :> ?f' x0 n\" for n\n        by (auto intro!: derivative_eq_intros simp del: power_Suc)\n    next\n      fix x\n      assume \"x \\<in> {-R' <..< R'}\"\n      then have \"R' \\<in> {-R <..< R}\" and \"norm x < norm R'\"\n        using assms \\<open>R' < R\\<close> by auto\n      have \"summable (\\<lambda>n. f n * x^n)\"\n      proof (rule summable_comparison_test, intro exI allI impI)\n        fix n\n        have le: \"\\<bar>f n\\<bar> * 1 \\<le> \\<bar>f n\\<bar> * real (Suc n)\"\n          by (rule mult_left_mono) auto\n        show \"norm (f n * x^n) \\<le> norm (f n * real (Suc n) * x^n)\"\n          unfolding real_norm_def abs_mult\n          using le mult_right_mono by fastforce\n      qed (rule powser_insidea[OF converges[OF \\<open>R' \\<in> {-R <..< R}\\<close>] \\<open>norm x < norm R'\\<close>])\n      from this[THEN summable_mult2[where c=x], simplified mult.assoc, simplified mult.commute]\n      show \"summable (?f x)\" by auto\n    next\n      show \"summable (?f' x0)\"\n        using converges[OF \\<open>x0 \\<in> {-R <..< R}\\<close>] .\n      show \"x0 \\<in> {-R' <..< R'}\"\n        using \\<open>x0 \\<in> {-R' <..< R'}\\<close> .\n    qed\n  qed\n  let ?R = \"(R + \\<bar>x0\\<bar>) / 2\"\n  have \"\\<bar>x0\\<bar> < ?R\"\n    using assms by (auto simp: field_simps)\n  then have \"- ?R < x0\"\n  proof (cases \"x0 < 0\")\n    case True\n    then have \"- x0 < ?R\"\n      using \\<open>\\<bar>x0\\<bar> < ?R\\<close> by auto\n    then show ?thesis\n      unfolding neg_less_iff_less[symmetric, of \"- x0\"] by auto\n  next\n    case False\n    have \"- ?R < 0\" using assms by auto\n    also have \"\\<dots> \\<le> x0\" using False by auto\n    finally show ?thesis .\n  qed\n  then have \"0 < ?R\" \"?R < R\" \"- ?R < x0\" and \"x0 < ?R\"\n    using assms by (auto simp: field_simps)\n  from for_subinterval[OF this] show ?thesis .\nqed\n\nlemma geometric_deriv_sums:\n  fixes z :: \"'a :: {real_normed_field,banach}\"\n  assumes \"norm z < 1\"\n  shows   \"(\\<lambda>n. of_nat (Suc n) * z ^ n) sums (1 / (1 - z)^2)\"\nproof -\n  have \"(\\<lambda>n. diffs (\\<lambda>n. 1) n * z^n) sums (1 / (1 - z)^2)\"\n  proof (rule termdiffs_sums_strong)\n    fix z :: 'a assume \"norm z < 1\"\n    thus \"(\\<lambda>n. 1 * z^n) sums (1 / (1 - z))\" by (simp add: geometric_sums)\n  qed (insert assms, auto intro!: derivative_eq_intros simp: power2_eq_square)\n  thus ?thesis unfolding diffs_def by simp\nqed\n\nlemma isCont_pochhammer [continuous_intros]: \"isCont (\\<lambda>z. pochhammer z n) z\"\n  for z :: \"'a::real_normed_field\"\n  by (induct n) (auto simp: pochhammer_rec')\n\nlemma continuous_on_pochhammer [continuous_intros]: \"continuous_on A (\\<lambda>z. pochhammer z n)\"\n  for A :: \"'a::real_normed_field set\"\n  by (intro continuous_at_imp_continuous_on ballI isCont_pochhammer)\n\n\nsubsection \\<open>Exponential Function\\<close>\n\ndefinition exp :: \"'a \\<Rightarrow> 'a::{real_normed_algebra_1,banach}\"\n  where \"exp = (\\<lambda>x. \\<Sum>n. x^n /\\<^sub>R fact n)\"\n\nlemma summable_exp_generic:\n  fixes x :: \"'a::{real_normed_algebra_1,banach}\"\n  defines S_def: \"S \\<equiv> \\<lambda>n. x^n /\\<^sub>R fact n\"\n  shows \"summable S\"\nproof -\n  have S_Suc: \"\\<And>n. S (Suc n) = (x * S n) /\\<^sub>R (Suc n)\"\n    unfolding S_def by (simp del: mult_Suc)\n  obtain r :: real where r0: \"0 < r\" and r1: \"r < 1\"\n    using dense [OF zero_less_one] by fast\n  obtain N :: nat where N: \"norm x < real N * r\"\n    using ex_less_of_nat_mult r0 by auto\n  from r1 show ?thesis\n  proof (rule summable_ratio_test [rule_format])\n    fix n :: nat\n    assume n: \"N \\<le> n\"\n    have \"norm x \\<le> real N * r\"\n      using N by (rule order_less_imp_le)\n    also have \"real N * r \\<le> real (Suc n) * r\"\n      using r0 n by (simp add: mult_right_mono)\n    finally have \"norm x * norm (S n) \\<le> real (Suc n) * r * norm (S n)\"\n      using norm_ge_zero by (rule mult_right_mono)\n    then have \"norm (x * S n) \\<le> real (Suc n) * r * norm (S n)\"\n      by (rule order_trans [OF norm_mult_ineq])\n    then have \"norm (x * S n) / real (Suc n) \\<le> r * norm (S n)\"\n      by (simp add: pos_divide_le_eq ac_simps)\n    then show \"norm (S (Suc n)) \\<le> r * norm (S n)\"\n      by (simp add: S_Suc inverse_eq_divide)\n  qed\nqed\n\nlemma summable_norm_exp: \"summable (\\<lambda>n. norm (x^n /\\<^sub>R fact n))\"\n  for x :: \"'a::{real_normed_algebra_1,banach}\"\nproof (rule summable_norm_comparison_test [OF exI, rule_format])\n  show \"summable (\\<lambda>n. norm x^n /\\<^sub>R fact n)\"\n    by (rule summable_exp_generic)\n  show \"norm (x^n /\\<^sub>R fact n) \\<le> norm x^n /\\<^sub>R fact n\" for n\n    by (simp add: norm_power_ineq)\nqed\n\nlemma summable_exp: \"summable (\\<lambda>n. inverse (fact n) * x^n)\"\n  for x :: \"'a::{real_normed_field,banach}\"\n  using summable_exp_generic [where x=x]\n  by (simp add: scaleR_conv_of_real nonzero_of_real_inverse)\n\nlemma exp_converges: \"(\\<lambda>n. x^n /\\<^sub>R fact n) sums exp x\"\n  unfolding exp_def by (rule summable_exp_generic [THEN summable_sums])\n\nlemma exp_fdiffs:\n  \"diffs (\\<lambda>n. inverse (fact n)) = (\\<lambda>n. inverse (fact n :: 'a::{real_normed_field,banach}))\"\n  by (simp add: diffs_def mult_ac nonzero_inverse_mult_distrib nonzero_of_real_inverse\n      del: mult_Suc of_nat_Suc)\n\nlemma diffs_of_real: \"diffs (\\<lambda>n. of_real (f n)) = (\\<lambda>n. of_real (diffs f n))\"\n  by (simp add: diffs_def)\n\nlemma DERIV_exp [simp]: \"DERIV exp x :> exp x\"\n  unfolding exp_def scaleR_conv_of_real\n  apply (rule DERIV_cong)\n   apply (rule termdiffs [where K=\"of_real (1 + norm x)\"])\n      apply (simp_all only: diffs_of_real scaleR_conv_of_real exp_fdiffs)\n     apply (rule exp_converges [THEN sums_summable, unfolded scaleR_conv_of_real])+\n  apply (simp del: of_real_add)\n  done\n\ndeclare DERIV_exp[THEN DERIV_chain2, derivative_intros]\n  and DERIV_exp[THEN DERIV_chain2, unfolded has_field_derivative_def, derivative_intros]\n\nlemma norm_exp: \"norm (exp x) \\<le> exp (norm x)\"\nproof -\n  from summable_norm[OF summable_norm_exp, of x]\n  have \"norm (exp x) \\<le> (\\<Sum>n. inverse (fact n) * norm (x^n))\"\n    by (simp add: exp_def)\n  also have \"\\<dots> \\<le> exp (norm x)\"\n    using summable_exp_generic[of \"norm x\"] summable_norm_exp[of x]\n    by (auto simp: exp_def intro!: suminf_le norm_power_ineq)\n  finally show ?thesis .\nqed\n\nlemma isCont_exp: \"isCont exp x\"\n  for x :: \"'a::{real_normed_field,banach}\"\n  by (rule DERIV_exp [THEN DERIV_isCont])\n\nlemma isCont_exp' [simp]: \"isCont f a \\<Longrightarrow> isCont (\\<lambda>x. exp (f x)) a\"\n  for f :: \"_ \\<Rightarrow>'a::{real_normed_field,banach}\"\n  by (rule isCont_o2 [OF _ isCont_exp])\n\nlemma tendsto_exp [tendsto_intros]: \"(f \\<longlongrightarrow> a) F \\<Longrightarrow> ((\\<lambda>x. exp (f x)) \\<longlongrightarrow> exp a) F\"\n  for f:: \"_ \\<Rightarrow>'a::{real_normed_field,banach}\"\n  by (rule isCont_tendsto_compose [OF isCont_exp])\n\nlemma continuous_exp [continuous_intros]: \"continuous F f \\<Longrightarrow> continuous F (\\<lambda>x. exp (f x))\"\n  for f :: \"_ \\<Rightarrow>'a::{real_normed_field,banach}\"\n  unfolding continuous_def by (rule tendsto_exp)\n\nlemma continuous_on_exp [continuous_intros]: \"continuous_on s f \\<Longrightarrow> continuous_on s (\\<lambda>x. exp (f x))\"\n  for f :: \"_ \\<Rightarrow>'a::{real_normed_field,banach}\"\n  unfolding continuous_on_def by (auto intro: tendsto_exp)\n\n\nsubsubsection \\<open>Properties of the Exponential Function\\<close>\n\nlemma exp_zero [simp]: \"exp 0 = 1\"\n  unfolding exp_def by (simp add: scaleR_conv_of_real)\n\nlemma exp_series_add_commuting:\n  fixes x y :: \"'a::{real_normed_algebra_1,banach}\"\n  defines S_def: \"S \\<equiv> \\<lambda>x n. x^n /\\<^sub>R fact n\"\n  assumes comm: \"x * y = y * x\"\n  shows \"S (x + y) n = (\\<Sum>i\\<le>n. S x i * S y (n - i))\"\nproof (induct n)\n  case 0\n  show ?case\n    unfolding S_def by simp\nnext\n  case (Suc n)\n  have S_Suc: \"\\<And>x n. S x (Suc n) = (x * S x n) /\\<^sub>R real (Suc n)\"\n    unfolding S_def by (simp del: mult_Suc)\n  then have times_S: \"\\<And>x n. x * S x n = real (Suc n) *\\<^sub>R S x (Suc n)\"\n    by simp\n  have S_comm: \"\\<And>n. S x n * y = y * S x n\"\n    by (simp add: power_commuting_commutes comm S_def)\n\n  have \"real (Suc n) *\\<^sub>R S (x + y) (Suc n) = (x + y) * S (x + y) n\"\n    by (simp only: times_S)\n  also have \"\\<dots> = (x + y) * (\\<Sum>i\\<le>n. S x i * S y (n - i))\"\n    by (simp only: Suc)\n  also have \"\\<dots> = x * (\\<Sum>i\\<le>n. S x i * S y (n - i)) + y * (\\<Sum>i\\<le>n. S x i * S y (n - i))\"\n    by (rule distrib_right)\n  also have \"\\<dots> = (\\<Sum>i\\<le>n. x * S x i * S y (n - i)) + (\\<Sum>i\\<le>n. S x i * y * S y (n - i))\"\n    by (simp add: sum_distrib_left ac_simps S_comm)\n  also have \"\\<dots> = (\\<Sum>i\\<le>n. x * S x i * S y (n - i)) + (\\<Sum>i\\<le>n. S x i * (y * S y (n - i)))\"\n    by (simp add: ac_simps)\n  also have \"\\<dots> = (\\<Sum>i\\<le>n. real (Suc i) *\\<^sub>R (S x (Suc i) * S y (n - i))) +\n      (\\<Sum>i\\<le>n. real (Suc n - i) *\\<^sub>R (S x i * S y (Suc n - i)))\"\n    by (simp add: times_S Suc_diff_le)\n  also have \"(\\<Sum>i\\<le>n. real (Suc i) *\\<^sub>R (S x (Suc i) * S y (n - i))) =\n      (\\<Sum>i\\<le>Suc n. real i *\\<^sub>R (S x i * S y (Suc n - i)))\"\n    by (subst sum_atMost_Suc_shift) simp\n  also have \"(\\<Sum>i\\<le>n. real (Suc n - i) *\\<^sub>R (S x i * S y (Suc n - i))) =\n      (\\<Sum>i\\<le>Suc n. real (Suc n - i) *\\<^sub>R (S x i * S y (Suc n - i)))\"\n    by simp\n  also have \"(\\<Sum>i\\<le>Suc n. real i *\\<^sub>R (S x i * S y (Suc n - i))) +\n        (\\<Sum>i\\<le>Suc n. real (Suc n - i) *\\<^sub>R (S x i * S y (Suc n - i))) =\n      (\\<Sum>i\\<le>Suc n. real (Suc n) *\\<^sub>R (S x i * S y (Suc n - i)))\"\n    by (simp only: sum.distrib [symmetric] scaleR_left_distrib [symmetric]\n        of_nat_add [symmetric]) simp\n  also have \"\\<dots> = real (Suc n) *\\<^sub>R (\\<Sum>i\\<le>Suc n. S x i * S y (Suc n - i))\"\n    by (simp only: scaleR_right.sum)\n  finally show \"S (x + y) (Suc n) = (\\<Sum>i\\<le>Suc n. S x i * S y (Suc n - i))\"\n    by (simp del: sum_cl_ivl_Suc)\nqed\n\nlemma exp_add_commuting: \"x * y = y * x \\<Longrightarrow> exp (x + y) = exp x * exp y\"\n  by (simp only: exp_def Cauchy_product summable_norm_exp exp_series_add_commuting)\n\nlemma exp_times_arg_commute: \"exp A * A = A * exp A\"\n  by (simp add: exp_def suminf_mult[symmetric] summable_exp_generic power_commutes suminf_mult2)\n\nlemma exp_add: \"exp (x + y) = exp x * exp y\"\n  for x y :: \"'a::{real_normed_field,banach}\"\n  by (rule exp_add_commuting) (simp add: ac_simps)\n\nlemma exp_double: \"exp(2 * z) = exp z ^ 2\"\n  by (simp add: exp_add_commuting mult_2 power2_eq_square)\n\nlemmas mult_exp_exp = exp_add [symmetric]\n\nlemma exp_of_real: \"exp (of_real x) = of_real (exp x)\"\n  unfolding exp_def\n  apply (subst suminf_of_real)\n   apply (rule summable_exp_generic)\n  apply (simp add: scaleR_conv_of_real)\n  done\n\ncorollary exp_in_Reals [simp]: \"z \\<in> \\<real> \\<Longrightarrow> exp z \\<in> \\<real>\"\n  by (metis Reals_cases Reals_of_real exp_of_real)\n\nlemma exp_not_eq_zero [simp]: \"exp x \\<noteq> 0\"\nproof\n  have \"exp x * exp (- x) = 1\"\n    by (simp add: exp_add_commuting[symmetric])\n  also assume \"exp x = 0\"\n  finally show False by simp\nqed\n\nlemma exp_minus_inverse: \"exp x * exp (- x) = 1\"\n  by (simp add: exp_add_commuting[symmetric])\n\nlemma exp_minus: \"exp (- x) = inverse (exp x)\"\n  for x :: \"'a::{real_normed_field,banach}\"\n  by (intro inverse_unique [symmetric] exp_minus_inverse)\n\nlemma exp_diff: \"exp (x - y) = exp x / exp y\"\n  for x :: \"'a::{real_normed_field,banach}\"\n  using exp_add [of x \"- y\"] by (simp add: exp_minus divide_inverse)\n\nlemma exp_of_nat_mult: \"exp (of_nat n * x) = exp x ^ n\"\n  for x :: \"'a::{real_normed_field,banach}\"\n  by (induct n) (auto simp add: distrib_left exp_add mult.commute)\n\ncorollary exp_real_of_nat_mult: \"exp (real n * x) = exp x ^ n\"\n  by (simp add: exp_of_nat_mult)\n\nlemma exp_sum: \"finite I \\<Longrightarrow> exp (sum f I) = prod (\\<lambda>x. exp (f x)) I\"\n  by (induct I rule: finite_induct) (auto simp: exp_add_commuting mult.commute)\n\nlemma exp_divide_power_eq:\n  fixes x :: \"'a::{real_normed_field,banach}\"\n  assumes \"n > 0\"\n  shows \"exp (x / of_nat n) ^ n = exp x\"\n  using assms\nproof (induction n arbitrary: x)\n  case 0\n  then show ?case by simp\nnext\n  case (Suc n)\n  show ?case\n  proof (cases \"n = 0\")\n    case True\n    then show ?thesis by simp\n  next\n    case False\n    then have [simp]: \"x * of_nat n / (1 + of_nat n) / of_nat n = x / (1 + of_nat n)\"\n      by simp\n    have [simp]: \"x / (1 + of_nat n) + x * of_nat n / (1 + of_nat n) = x\"\n      apply (simp add: divide_simps)\n      using of_nat_eq_0_iff apply (fastforce simp: distrib_left)\n      done\n    show ?thesis\n      using Suc.IH [of \"x * of_nat n / (1 + of_nat n)\"] False\n      by (simp add: exp_add [symmetric])\n  qed\nqed\n\n\nsubsubsection \\<open>Properties of the Exponential Function on Reals\\<close>\n\ntext \\<open>Comparisons of @{term \"exp x\"} with zero.\\<close>\n\ntext \\<open>Proof: because every exponential can be seen as a square.\\<close>\nlemma exp_ge_zero [simp]: \"0 \\<le> exp x\"\n  for x :: real\nproof -\n  have \"0 \\<le> exp (x/2) * exp (x/2)\"\n    by simp\n  then show ?thesis\n    by (simp add: exp_add [symmetric])\nqed\n\nlemma exp_gt_zero [simp]: \"0 < exp x\"\n  for x :: real\n  by (simp add: order_less_le)\n\nlemma not_exp_less_zero [simp]: \"\\<not> exp x < 0\"\n  for x :: real\n  by (simp add: not_less)\n\nlemma not_exp_le_zero [simp]: \"\\<not> exp x \\<le> 0\"\n  for x :: real\n  by (simp add: not_le)\n\nlemma abs_exp_cancel [simp]: \"\\<bar>exp x\\<bar> = exp x\"\n  for x :: real\n  by simp\n\ntext \\<open>Strict monotonicity of exponential.\\<close>\n\nlemma exp_ge_add_one_self_aux:\n  fixes x :: real\n  assumes \"0 \\<le> x\"\n  shows \"1 + x \\<le> exp x\"\n  using order_le_imp_less_or_eq [OF assms]\nproof\n  assume \"0 < x\"\n  have \"1 + x \\<le> (\\<Sum>n<2. inverse (fact n) * x^n)\"\n    by (auto simp add: numeral_2_eq_2)\n  also have \"\\<dots> \\<le> (\\<Sum>n. inverse (fact n) * x^n)\"\n    apply (rule sum_le_suminf [OF summable_exp])\n    using \\<open>0 < x\\<close>\n    apply (auto  simp add:  zero_le_mult_iff)\n    done\n  finally show \"1 + x \\<le> exp x\"\n    by (simp add: exp_def)\nnext\n  assume \"0 = x\"\n  then show \"1 + x \\<le> exp x\"\n    by auto\nqed\n\nlemma exp_gt_one: \"0 < x \\<Longrightarrow> 1 < exp x\"\n  for x :: real\nproof -\n  assume x: \"0 < x\"\n  then have \"1 < 1 + x\" by simp\n  also from x have \"1 + x \\<le> exp x\"\n    by (simp add: exp_ge_add_one_self_aux)\n  finally show ?thesis .\nqed\n\nlemma exp_less_mono:\n  fixes x y :: real\n  assumes \"x < y\"\n  shows \"exp x < exp y\"\nproof -\n  from \\<open>x < y\\<close> have \"0 < y - x\" by simp\n  then have \"1 < exp (y - x)\" by (rule exp_gt_one)\n  then have \"1 < exp y / exp x\" by (simp only: exp_diff)\n  then show \"exp x < exp y\" by simp\nqed\n\nlemma exp_less_cancel: \"exp x < exp y \\<Longrightarrow> x < y\"\n  for x y :: real\n  unfolding linorder_not_le [symmetric]\n  by (auto simp add: order_le_less exp_less_mono)\n\nlemma exp_less_cancel_iff [iff]: \"exp x < exp y \\<longleftrightarrow> x < y\"\n  for x y :: real\n  by (auto intro: exp_less_mono exp_less_cancel)\n\nlemma exp_le_cancel_iff [iff]: \"exp x \\<le> exp y \\<longleftrightarrow> x \\<le> y\"\n  for x y :: real\n  by (auto simp add: linorder_not_less [symmetric])\n\nlemma exp_inj_iff [iff]: \"exp x = exp y \\<longleftrightarrow> x = y\"\n  for x y :: real\n  by (simp add: order_eq_iff)\n\ntext \\<open>Comparisons of @{term \"exp x\"} with one.\\<close>\n\nlemma one_less_exp_iff [simp]: \"1 < exp x \\<longleftrightarrow> 0 < x\"\n  for x :: real\n  using exp_less_cancel_iff [where x = 0 and y = x] by simp\n\nlemma exp_less_one_iff [simp]: \"exp x < 1 \\<longleftrightarrow> x < 0\"\n  for x :: real\n  using exp_less_cancel_iff [where x = x and y = 0] by simp\n\nlemma one_le_exp_iff [simp]: \"1 \\<le> exp x \\<longleftrightarrow> 0 \\<le> x\"\n  for x :: real\n  using exp_le_cancel_iff [where x = 0 and y = x] by simp\n\nlemma exp_le_one_iff [simp]: \"exp x \\<le> 1 \\<longleftrightarrow> x \\<le> 0\"\n  for x :: real\n  using exp_le_cancel_iff [where x = x and y = 0] by simp\n\nlemma exp_eq_one_iff [simp]: \"exp x = 1 \\<longleftrightarrow> x = 0\"\n  for x :: real\n  using exp_inj_iff [where x = x and y = 0] by simp\n\nlemma lemma_exp_total: \"1 \\<le> y \\<Longrightarrow> \\<exists>x. 0 \\<le> x \\<and> x \\<le> y - 1 \\<and> exp x = y\"\n  for y :: real\nproof (rule IVT)\n  assume \"1 \\<le> y\"\n  then have \"0 \\<le> y - 1\" by simp\n  then have \"1 + (y - 1) \\<le> exp (y - 1)\"\n    by (rule exp_ge_add_one_self_aux)\n  then show \"y \\<le> exp (y - 1)\" by simp\nqed (simp_all add: le_diff_eq)\n\nlemma exp_total: \"0 < y \\<Longrightarrow> \\<exists>x. exp x = y\"\n  for y :: real\nproof (rule linorder_le_cases [of 1 y])\n  assume \"1 \\<le> y\"\n  then show \"\\<exists>x. exp x = y\"\n    by (fast dest: lemma_exp_total)\nnext\n  assume \"0 < y\" and \"y \\<le> 1\"\n  then have \"1 \\<le> inverse y\"\n    by (simp add: one_le_inverse_iff)\n  then obtain x where \"exp x = inverse y\"\n    by (fast dest: lemma_exp_total)\n  then have \"exp (- x) = y\"\n    by (simp add: exp_minus)\n  then show \"\\<exists>x. exp x = y\" ..\nqed\n\n\nsubsection \\<open>Natural Logarithm\\<close>\n\nclass ln = real_normed_algebra_1 + banach +\n  fixes ln :: \"'a \\<Rightarrow> 'a\"\n  assumes ln_one [simp]: \"ln 1 = 0\"\n\ndefinition powr :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a::ln\"  (infixr \"powr\" 80)\n  \\<comment> \\<open>exponentation via ln and exp\\<close>\n  where  [code del]: \"x powr a \\<equiv> if x = 0 then 0 else exp (a * ln x)\"\n\nlemma powr_0 [simp]: \"0 powr z = 0\"\n  by (simp add: powr_def)\n\n\ninstantiation real :: ln\nbegin\n\ndefinition ln_real :: \"real \\<Rightarrow> real\"\n  where \"ln_real x = (THE u. exp u = x)\"\n\ninstance\n  by intro_classes (simp add: ln_real_def)\n\nend\n\nlemma powr_eq_0_iff [simp]: \"w powr z = 0 \\<longleftrightarrow> w = 0\"\n  by (simp add: powr_def)\n\nlemma ln_exp [simp]: \"ln (exp x) = x\"\n  for x :: real\n  by (simp add: ln_real_def)\n\nlemma exp_ln [simp]: \"0 < x \\<Longrightarrow> exp (ln x) = x\"\n  for x :: real\n  by (auto dest: exp_total)\n\nlemma exp_ln_iff [simp]: \"exp (ln x) = x \\<longleftrightarrow> 0 < x\"\n  for x :: real\n  by (metis exp_gt_zero exp_ln)\n\nlemma ln_unique: \"exp y = x \\<Longrightarrow> ln x = y\"\n  for x :: real\n  by (erule subst) (rule ln_exp)\n\nlemma ln_mult: \"0 < x \\<Longrightarrow> 0 < y \\<Longrightarrow> ln (x * y) = ln x + ln y\"\n  for x :: real\n  by (rule ln_unique) (simp add: exp_add)\n\nlemma ln_prod: \"finite I \\<Longrightarrow> (\\<And>i. i \\<in> I \\<Longrightarrow> f i > 0) \\<Longrightarrow> ln (prod f I) = sum (\\<lambda>x. ln(f x)) I\"\n  for f :: \"'a \\<Rightarrow> real\"\n  by (induct I rule: finite_induct) (auto simp: ln_mult prod_pos)\n\nlemma ln_inverse: \"0 < x \\<Longrightarrow> ln (inverse x) = - ln x\"\n  for x :: real\n  by (rule ln_unique) (simp add: exp_minus)\n\nlemma ln_div: \"0 < x \\<Longrightarrow> 0 < y \\<Longrightarrow> ln (x / y) = ln x - ln y\"\n  for x :: real\n  by (rule ln_unique) (simp add: exp_diff)\n\nlemma ln_realpow: \"0 < x \\<Longrightarrow> ln (x^n) = real n * ln x\"\n  by (rule ln_unique) (simp add: exp_real_of_nat_mult)\n\nlemma ln_less_cancel_iff [simp]: \"0 < x \\<Longrightarrow> 0 < y \\<Longrightarrow> ln x < ln y \\<longleftrightarrow> x < y\"\n  for x :: real\n  by (subst exp_less_cancel_iff [symmetric]) simp\n\nlemma ln_le_cancel_iff [simp]: \"0 < x \\<Longrightarrow> 0 < y \\<Longrightarrow> ln x \\<le> ln y \\<longleftrightarrow> x \\<le> y\"\n  for x :: real\n  by (simp add: linorder_not_less [symmetric])\n\nlemma ln_inj_iff [simp]: \"0 < x \\<Longrightarrow> 0 < y \\<Longrightarrow> ln x = ln y \\<longleftrightarrow> x = y\"\n  for x :: real\n  by (simp add: order_eq_iff)\n\nlemma ln_add_one_self_le_self [simp]: \"0 \\<le> x \\<Longrightarrow> ln (1 + x) \\<le> x\"\n  for x :: real\n  by (rule exp_le_cancel_iff [THEN iffD1]) (simp add: exp_ge_add_one_self_aux)\n\nlemma ln_less_self [simp]: \"0 < x \\<Longrightarrow> ln x < x\"\n  for x :: real\n  by (rule order_less_le_trans [where y = \"ln (1 + x)\"]) simp_all\n\nlemma ln_ge_zero [simp]: \"1 \\<le> x \\<Longrightarrow> 0 \\<le> ln x\"\n  for x :: real\n  using ln_le_cancel_iff [of 1 x] by simp\n\nlemma ln_ge_zero_imp_ge_one: \"0 \\<le> ln x \\<Longrightarrow> 0 < x \\<Longrightarrow> 1 \\<le> x\"\n  for x :: real\n  using ln_le_cancel_iff [of 1 x] by simp\n\nlemma ln_ge_zero_iff [simp]: \"0 < x \\<Longrightarrow> 0 \\<le> ln x \\<longleftrightarrow> 1 \\<le> x\"\n  for x :: real\n  using ln_le_cancel_iff [of 1 x] by simp\n\nlemma ln_less_zero_iff [simp]: \"0 < x \\<Longrightarrow> ln x < 0 \\<longleftrightarrow> x < 1\"\n  for x :: real\n  using ln_less_cancel_iff [of x 1] by simp\n\nlemma ln_gt_zero: \"1 < x \\<Longrightarrow> 0 < ln x\"\n  for x :: real\n  using ln_less_cancel_iff [of 1 x] by simp\n\nlemma ln_gt_zero_imp_gt_one: \"0 < ln x \\<Longrightarrow> 0 < x \\<Longrightarrow> 1 < x\"\n  for x :: real\n  using ln_less_cancel_iff [of 1 x] by simp\n\nlemma ln_gt_zero_iff [simp]: \"0 < x \\<Longrightarrow> 0 < ln x \\<longleftrightarrow> 1 < x\"\n  for x :: real\n  using ln_less_cancel_iff [of 1 x] by simp\n\nlemma ln_eq_zero_iff [simp]: \"0 < x \\<Longrightarrow> ln x = 0 \\<longleftrightarrow> x = 1\"\n  for x :: real\n  using ln_inj_iff [of x 1] by simp\n\nlemma ln_less_zero: \"0 < x \\<Longrightarrow> x < 1 \\<Longrightarrow> ln x < 0\"\n  for x :: real\n  by simp\n\nlemma ln_neg_is_const: \"x \\<le> 0 \\<Longrightarrow> ln x = (THE x. False)\"\n  for x :: real\n  by (auto simp: ln_real_def intro!: arg_cong[where f = The])\n\nlemma isCont_ln:\n  fixes x :: real\n  assumes \"x \\<noteq> 0\"\n  shows \"isCont ln x\"\nproof (cases \"0 < x\")\n  case True\n  then have \"isCont ln (exp (ln x))\"\n    by (intro isCont_inv_fun[where d = \"\\<bar>x\\<bar>\" and f = exp]) auto\n  with True show ?thesis\n    by simp\nnext\n  case False\n  with \\<open>x \\<noteq> 0\\<close> show \"isCont ln x\"\n    unfolding isCont_def\n    by (subst filterlim_cong[OF _ refl, of _ \"nhds (ln 0)\" _ \"\\<lambda>_. ln 0\"])\n       (auto simp: ln_neg_is_const not_less eventually_at dist_real_def\n         intro!: exI[of _ \"\\<bar>x\\<bar>\"])\nqed\n\nlemma tendsto_ln [tendsto_intros]: \"(f \\<longlongrightarrow> a) F \\<Longrightarrow> a \\<noteq> 0 \\<Longrightarrow> ((\\<lambda>x. ln (f x)) \\<longlongrightarrow> ln a) F\"\n  for a :: real\n  by (rule isCont_tendsto_compose [OF isCont_ln])\n\nlemma continuous_ln:\n  \"continuous F f \\<Longrightarrow> f (Lim F (\\<lambda>x. x)) \\<noteq> 0 \\<Longrightarrow> continuous F (\\<lambda>x. ln (f x :: real))\"\n  unfolding continuous_def by (rule tendsto_ln)\n\nlemma isCont_ln' [continuous_intros]:\n  \"continuous (at x) f \\<Longrightarrow> f x \\<noteq> 0 \\<Longrightarrow> continuous (at x) (\\<lambda>x. ln (f x :: real))\"\n  unfolding continuous_at by (rule tendsto_ln)\n\nlemma continuous_within_ln [continuous_intros]:\n  \"continuous (at x within s) f \\<Longrightarrow> f x \\<noteq> 0 \\<Longrightarrow> continuous (at x within s) (\\<lambda>x. ln (f x :: real))\"\n  unfolding continuous_within by (rule tendsto_ln)\n\nlemma continuous_on_ln [continuous_intros]:\n  \"continuous_on s f \\<Longrightarrow> (\\<forall>x\\<in>s. f x \\<noteq> 0) \\<Longrightarrow> continuous_on s (\\<lambda>x. ln (f x :: real))\"\n  unfolding continuous_on_def by (auto intro: tendsto_ln)\n\nlemma DERIV_ln: \"0 < x \\<Longrightarrow> DERIV ln x :> inverse x\"\n  for x :: real\n  by (rule DERIV_inverse_function [where f=exp and a=0 and b=\"x+1\"])\n    (auto intro: DERIV_cong [OF DERIV_exp exp_ln] isCont_ln)\n\nlemma DERIV_ln_divide: \"0 < x \\<Longrightarrow> DERIV ln x :> 1 / x\"\n  for x :: real\n  by (rule DERIV_ln[THEN DERIV_cong]) (simp_all add: divide_inverse)\n\ndeclare DERIV_ln_divide[THEN DERIV_chain2, derivative_intros]\n  and DERIV_ln_divide[THEN DERIV_chain2, unfolded has_field_derivative_def, derivative_intros]\n\nlemma ln_series:\n  assumes \"0 < x\" and \"x < 2\"\n  shows \"ln x = (\\<Sum> n. (-1)^n * (1 / real (n + 1)) * (x - 1)^(Suc n))\"\n    (is \"ln x = suminf (?f (x - 1))\")\nproof -\n  let ?f' = \"\\<lambda>x n. (-1)^n * (x - 1)^n\"\n\n  have \"ln x - suminf (?f (x - 1)) = ln 1 - suminf (?f (1 - 1))\"\n  proof (rule DERIV_isconst3 [where x = x])\n    fix x :: real\n    assume \"x \\<in> {0 <..< 2}\"\n    then have \"0 < x\" and \"x < 2\" by auto\n    have \"norm (1 - x) < 1\"\n      using \\<open>0 < x\\<close> and \\<open>x < 2\\<close> by auto\n    have \"1 / x = 1 / (1 - (1 - x))\" by auto\n    also have \"\\<dots> = (\\<Sum> n. (1 - x)^n)\"\n      using geometric_sums[OF \\<open>norm (1 - x) < 1\\<close>] by (rule sums_unique)\n    also have \"\\<dots> = suminf (?f' x)\"\n      unfolding power_mult_distrib[symmetric]\n      by (rule arg_cong[where f=suminf], rule arg_cong[where f=\"op ^\"], auto)\n    finally have \"DERIV ln x :> suminf (?f' x)\"\n      using DERIV_ln[OF \\<open>0 < x\\<close>] unfolding divide_inverse by auto\n    moreover\n    have repos: \"\\<And> h x :: real. h - 1 + x = h + x - 1\" by auto\n    have \"DERIV (\\<lambda>x. suminf (?f x)) (x - 1) :>\n      (\\<Sum>n. (-1)^n * (1 / real (n + 1)) * real (Suc n) * (x - 1) ^ n)\"\n    proof (rule DERIV_power_series')\n      show \"x - 1 \\<in> {- 1<..<1}\" and \"(0 :: real) < 1\"\n        using \\<open>0 < x\\<close> \\<open>x < 2\\<close> by auto\n    next\n      fix x :: real\n      assume \"x \\<in> {- 1<..<1}\"\n      then have \"norm (-x) < 1\" by auto\n      show \"summable (\\<lambda>n. (- 1) ^ n * (1 / real (n + 1)) * real (Suc n) * x^n)\"\n        unfolding One_nat_def\n        by (auto simp add: power_mult_distrib[symmetric] summable_geometric[OF \\<open>norm (-x) < 1\\<close>])\n    qed\n    then have \"DERIV (\\<lambda>x. suminf (?f x)) (x - 1) :> suminf (?f' x)\"\n      unfolding One_nat_def by auto\n    then have \"DERIV (\\<lambda>x. suminf (?f (x - 1))) x :> suminf (?f' x)\"\n      unfolding DERIV_def repos .\n    ultimately have \"DERIV (\\<lambda>x. ln x - suminf (?f (x - 1))) x :> suminf (?f' x) - suminf (?f' x)\"\n      by (rule DERIV_diff)\n    then show \"DERIV (\\<lambda>x. ln x - suminf (?f (x - 1))) x :> 0\" by auto\n  qed (auto simp add: assms)\n  then show ?thesis by auto\nqed\n\nlemma exp_first_terms:\n  fixes x :: \"'a::{real_normed_algebra_1,banach}\"\n  shows \"exp x = (\\<Sum>n<k. inverse(fact n) *\\<^sub>R (x ^ n)) + (\\<Sum>n. inverse(fact (n + k)) *\\<^sub>R (x ^ (n + k)))\"\nproof -\n  have \"exp x = suminf (\\<lambda>n. inverse(fact n) *\\<^sub>R (x^n))\"\n    by (simp add: exp_def)\n  also from summable_exp_generic have \"\\<dots> = (\\<Sum> n. inverse(fact(n+k)) *\\<^sub>R (x ^ (n + k))) +\n    (\\<Sum> n::nat<k. inverse(fact n) *\\<^sub>R (x^n))\" (is \"_ = _ + ?a\")\n    by (rule suminf_split_initial_segment)\n  finally show ?thesis by simp\nqed\n\nlemma exp_first_term: \"exp x = 1 + (\\<Sum>n. inverse (fact (Suc n)) *\\<^sub>R (x ^ Suc n))\"\n  for x :: \"'a::{real_normed_algebra_1,banach}\"\n  using exp_first_terms[of x 1] by simp\n\nlemma exp_first_two_terms: \"exp x = 1 + x + (\\<Sum>n. inverse (fact (n + 2)) *\\<^sub>R (x ^ (n + 2)))\"\n  for x :: \"'a::{real_normed_algebra_1,banach}\"\n  using exp_first_terms[of x 2] by (simp add: eval_nat_numeral)\n\nlemma exp_bound:\n  fixes x :: real\n  assumes a: \"0 \\<le> x\"\n    and b: \"x \\<le> 1\"\n  shows \"exp x \\<le> 1 + x + x\\<^sup>2\"\nproof -\n  have aux1: \"inverse (fact (n + 2)) * x ^ (n + 2) \\<le> (x\\<^sup>2/2) * ((1/2)^n)\" for n :: nat\n  proof -\n    have \"(2::nat) * 2 ^ n \\<le> fact (n + 2)\"\n      by (induct n) simp_all\n    then have \"real ((2::nat) * 2 ^ n) \\<le> real_of_nat (fact (n + 2))\"\n      by (simp only: of_nat_le_iff)\n    then have \"((2::real) * 2 ^ n) \\<le> fact (n + 2)\"\n      unfolding of_nat_fact by simp\n    then have \"inverse (fact (n + 2)) \\<le> inverse ((2::real) * 2 ^ n)\"\n      by (rule le_imp_inverse_le) simp\n    then have \"inverse (fact (n + 2)) \\<le> 1/(2::real) * (1/2)^n\"\n      by (simp add: power_inverse [symmetric])\n    then have \"inverse (fact (n + 2)) * (x^n * x\\<^sup>2) \\<le> 1/2 * (1/2)^n * (1 * x\\<^sup>2)\"\n      by (rule mult_mono) (rule mult_mono, simp_all add: power_le_one a b)\n    then show ?thesis\n      unfolding power_add by (simp add: ac_simps del: fact_Suc)\n  qed\n  have \"(\\<lambda>n. x\\<^sup>2 / 2 * (1 / 2) ^ n) sums (x\\<^sup>2 / 2 * (1 / (1 - 1 / 2)))\"\n    by (intro sums_mult geometric_sums) simp\n  then have aux2: \"(\\<lambda>n. x\\<^sup>2 / 2 * (1 / 2) ^ n) sums x\\<^sup>2\"\n    by simp\n  have \"suminf (\\<lambda>n. inverse(fact (n+2)) * (x ^ (n + 2))) \\<le> x\\<^sup>2\"\n  proof -\n    have \"suminf (\\<lambda>n. inverse(fact (n+2)) * (x ^ (n + 2))) \\<le> suminf (\\<lambda>n. (x\\<^sup>2/2) * ((1/2)^n))\"\n      apply (rule suminf_le)\n        apply (rule allI)\n        apply (rule aux1)\n       apply (rule summable_exp [THEN summable_ignore_initial_segment])\n      apply (rule sums_summable)\n      apply (rule aux2)\n      done\n    also have \"\\<dots> = x\\<^sup>2\"\n      by (rule sums_unique [THEN sym]) (rule aux2)\n    finally show ?thesis .\n  qed\n  then show ?thesis\n    unfolding exp_first_two_terms by auto\nqed\n\ncorollary exp_half_le2: \"exp(1/2) \\<le> (2::real)\"\n  using exp_bound [of \"1/2\"]\n  by (simp add: field_simps)\n\ncorollary exp_le: \"exp 1 \\<le> (3::real)\"\n  using exp_bound [of 1]\n  by (simp add: field_simps)\n\nlemma exp_bound_half: \"norm z \\<le> 1/2 \\<Longrightarrow> norm (exp z) \\<le> 2\"\n  by (blast intro: order_trans intro!: exp_half_le2 norm_exp)\n\nlemma exp_bound_lemma:\n  assumes \"norm z \\<le> 1/2\"\n  shows \"norm (exp z) \\<le> 1 + 2 * norm z\"\nproof -\n  have *: \"(norm z)\\<^sup>2 \\<le> norm z * 1\"\n    unfolding power2_eq_square\n    apply (rule mult_left_mono)\n    using assms\n     apply auto\n    done\n  show ?thesis\n    apply (rule order_trans [OF norm_exp])\n    apply (rule order_trans [OF exp_bound])\n    using assms *\n      apply auto\n    done\nqed\n\nlemma real_exp_bound_lemma: \"0 \\<le> x \\<Longrightarrow> x \\<le> 1/2 \\<Longrightarrow> exp x \\<le> 1 + 2 * x\"\n  for x :: real\n  using exp_bound_lemma [of x] by simp\n\nlemma ln_one_minus_pos_upper_bound:\n  fixes x :: real\n  assumes a: \"0 \\<le> x\" and b: \"x < 1\"\n  shows \"ln (1 - x) \\<le> - x\"\nproof -\n  have \"(1 - x) * (1 + x + x\\<^sup>2) = 1 - x^3\"\n    by (simp add: algebra_simps power2_eq_square power3_eq_cube)\n  also have \"\\<dots> \\<le> 1\"\n    by (auto simp add: a)\n  finally have \"(1 - x) * (1 + x + x\\<^sup>2) \\<le> 1\" .\n  moreover have c: \"0 < 1 + x + x\\<^sup>2\"\n    by (simp add: add_pos_nonneg a)\n  ultimately have \"1 - x \\<le> 1 / (1 + x + x\\<^sup>2)\"\n    by (elim mult_imp_le_div_pos)\n  also have \"\\<dots> \\<le> 1 / exp x\"\n    by (metis a abs_one b exp_bound exp_gt_zero frac_le less_eq_real_def real_sqrt_abs\n        real_sqrt_pow2_iff real_sqrt_power)\n  also have \"\\<dots> = exp (- x)\"\n    by (auto simp add: exp_minus divide_inverse)\n  finally have \"1 - x \\<le> exp (- x)\" .\n  also have \"1 - x = exp (ln (1 - x))\"\n    by (metis b diff_0 exp_ln_iff less_iff_diff_less_0 minus_diff_eq)\n  finally have \"exp (ln (1 - x)) \\<le> exp (- x)\" .\n  then show ?thesis\n    by (auto simp only: exp_le_cancel_iff)\nqed\n\nlemma exp_ge_add_one_self [simp]: \"1 + x \\<le> exp x\"\n  for x :: real\n  apply (cases \"0 \\<le> x\")\n   apply (erule exp_ge_add_one_self_aux)\n  apply (cases \"x \\<le> -1\")\n   apply (subgoal_tac \"1 + x \\<le> 0\")\n    apply (erule order_trans)\n    apply simp\n   apply simp\n  apply (subgoal_tac \"1 + x = exp (ln (1 + x))\")\n   apply (erule ssubst)\n   apply (subst exp_le_cancel_iff)\n   apply (subgoal_tac \"ln (1 - (- x)) \\<le> - (- x)\")\n    apply simp\n   apply (rule ln_one_minus_pos_upper_bound)\n    apply auto\n  done\n\nlemma ln_one_plus_pos_lower_bound:\n  fixes x :: real\n  assumes a: \"0 \\<le> x\" and b: \"x \\<le> 1\"\n  shows \"x - x\\<^sup>2 \\<le> ln (1 + x)\"\nproof -\n  have \"exp (x - x\\<^sup>2) = exp x / exp (x\\<^sup>2)\"\n    by (rule exp_diff)\n  also have \"\\<dots> \\<le> (1 + x + x\\<^sup>2) / exp (x \\<^sup>2)\"\n    by (metis a b divide_right_mono exp_bound exp_ge_zero)\n  also have \"\\<dots> \\<le> (1 + x + x\\<^sup>2) / (1 + x\\<^sup>2)\"\n    by (simp add: a divide_left_mono add_pos_nonneg)\n  also from a have \"\\<dots> \\<le> 1 + x\"\n    by (simp add: field_simps add_strict_increasing zero_le_mult_iff)\n  finally have \"exp (x - x\\<^sup>2) \\<le> 1 + x\" .\n  also have \"\\<dots> = exp (ln (1 + x))\"\n  proof -\n    from a have \"0 < 1 + x\" by auto\n    then show ?thesis\n      by (auto simp only: exp_ln_iff [THEN sym])\n  qed\n  finally have \"exp (x - x\\<^sup>2) \\<le> exp (ln (1 + x))\" .\n  then show ?thesis\n    by (metis exp_le_cancel_iff)\nqed\n\nlemma ln_one_minus_pos_lower_bound:\n  fixes x :: real\n  assumes a: \"0 \\<le> x\" and b: \"x \\<le> 1 / 2\"\n  shows \"- x - 2 * x\\<^sup>2 \\<le> ln (1 - x)\"\nproof -\n  from b have c: \"x < 1\" by auto\n  then have \"ln (1 - x) = - ln (1 + x / (1 - x))\"\n    apply (subst ln_inverse [symmetric])\n     apply (simp add: field_simps)\n    apply (rule arg_cong [where f=ln])\n    apply (simp add: field_simps)\n    done\n  also have \"- (x / (1 - x)) \\<le> \\<dots>\"\n  proof -\n    have \"ln (1 + x / (1 - x)) \\<le> x / (1 - x)\"\n      using a c by (intro ln_add_one_self_le_self) auto\n    then show ?thesis\n      by auto\n  qed\n  also have \"- (x / (1 - x)) = - x / (1 - x)\"\n    by auto\n  finally have d: \"- x / (1 - x) \\<le> ln (1 - x)\" .\n  have \"0 < 1 - x\" using a b by simp\n  then have e: \"- x - 2 * x\\<^sup>2 \\<le> - x / (1 - x)\"\n    using mult_right_le_one_le[of \"x * x\" \"2 * x\"] a b\n    by (simp add: field_simps power2_eq_square)\n  from e d show \"- x - 2 * x\\<^sup>2 \\<le> ln (1 - x)\"\n    by (rule order_trans)\nqed\n\nlemma ln_add_one_self_le_self2:\n  fixes x :: real\n  shows \"-1 < x \\<Longrightarrow> ln (1 + x) \\<le> x\"\n  apply (subgoal_tac \"ln (1 + x) \\<le> ln (exp x)\")\n   apply simp\n  apply (subst ln_le_cancel_iff)\n    apply auto\n  done\n\nlemma abs_ln_one_plus_x_minus_x_bound_nonneg:\n  fixes x :: real\n  assumes x: \"0 \\<le> x\" and x1: \"x \\<le> 1\"\n  shows \"\\<bar>ln (1 + x) - x\\<bar> \\<le> x\\<^sup>2\"\nproof -\n  from x have \"ln (1 + x) \\<le> x\"\n    by (rule ln_add_one_self_le_self)\n  then have \"ln (1 + x) - x \\<le> 0\"\n    by simp\n  then have \"\\<bar>ln(1 + x) - x\\<bar> = - (ln(1 + x) - x)\"\n    by (rule abs_of_nonpos)\n  also have \"\\<dots> = x - ln (1 + x)\"\n    by simp\n  also have \"\\<dots> \\<le> x\\<^sup>2\"\n  proof -\n    from x x1 have \"x - x\\<^sup>2 \\<le> ln (1 + x)\"\n      by (intro ln_one_plus_pos_lower_bound)\n    then show ?thesis\n      by simp\n  qed\n  finally show ?thesis .\nqed\n\nlemma abs_ln_one_plus_x_minus_x_bound_nonpos:\n  fixes x :: real\n  assumes a: \"-(1 / 2) \\<le> x\" and b: \"x \\<le> 0\"\n  shows \"\\<bar>ln (1 + x) - x\\<bar> \\<le> 2 * x\\<^sup>2\"\nproof -\n  have \"\\<bar>ln (1 + x) - x\\<bar> = x - ln (1 - (- x))\"\n    apply (subst abs_of_nonpos)\n     apply simp\n     apply (rule ln_add_one_self_le_self2)\n    using a apply auto\n    done\n  also have \"\\<dots> \\<le> 2 * x\\<^sup>2\"\n    apply (subgoal_tac \"- (-x) - 2 * (-x)\\<^sup>2 \\<le> ln (1 - (- x))\")\n     apply (simp add: algebra_simps)\n    apply (rule ln_one_minus_pos_lower_bound)\n    using a b apply auto\n    done\n  finally show ?thesis .\nqed\n\nlemma abs_ln_one_plus_x_minus_x_bound:\n  fixes x :: real\n  shows \"\\<bar>x\\<bar> \\<le> 1 / 2 \\<Longrightarrow> \\<bar>ln (1 + x) - x\\<bar> \\<le> 2 * x\\<^sup>2\"\n  apply (cases \"0 \\<le> x\")\n   apply (rule order_trans)\n    apply (rule abs_ln_one_plus_x_minus_x_bound_nonneg)\n     apply auto\n  apply (rule abs_ln_one_plus_x_minus_x_bound_nonpos)\n   apply auto\n  done\n\nlemma ln_x_over_x_mono:\n  fixes x :: real\n  assumes x: \"exp 1 \\<le> x\" \"x \\<le> y\"\n  shows \"ln y / y \\<le> ln x / x\"\nproof -\n  note x\n  moreover have \"0 < exp (1::real)\" by simp\n  ultimately have a: \"0 < x\" and b: \"0 < y\"\n    by (fast intro: less_le_trans order_trans)+\n  have \"x * ln y - x * ln x = x * (ln y - ln x)\"\n    by (simp add: algebra_simps)\n  also have \"\\<dots> = x * ln (y / x)\"\n    by (simp only: ln_div a b)\n  also have \"y / x = (x + (y - x)) / x\"\n    by simp\n  also have \"\\<dots> = 1 + (y - x) / x\"\n    using x a by (simp add: field_simps)\n  also have \"x * ln (1 + (y - x) / x) \\<le> x * ((y - x) / x)\"\n    using x a\n    by (intro mult_left_mono ln_add_one_self_le_self) simp_all\n  also have \"\\<dots> = y - x\"\n    using a by simp\n  also have \"\\<dots> = (y - x) * ln (exp 1)\" by simp\n  also have \"\\<dots> \\<le> (y - x) * ln x\"\n    apply (rule mult_left_mono)\n     apply (subst ln_le_cancel_iff)\n       apply fact\n      apply (rule a)\n     apply (rule x)\n    using x apply simp\n    done\n  also have \"\\<dots> = y * ln x - x * ln x\"\n    by (rule left_diff_distrib)\n  finally have \"x * ln y \\<le> y * ln x\"\n    by arith\n  then have \"ln y \\<le> (y * ln x) / x\"\n    using a by (simp add: field_simps)\n  also have \"\\<dots> = y * (ln x / x)\" by simp\n  finally show ?thesis\n    using b by (simp add: field_simps)\nqed\n\nlemma ln_le_minus_one: \"0 < x \\<Longrightarrow> ln x \\<le> x - 1\"\n  for x :: real\n  using exp_ge_add_one_self[of \"ln x\"] by simp\n\ncorollary ln_diff_le: \"0 < x \\<Longrightarrow> 0 < y \\<Longrightarrow> ln x - ln y \\<le> (x - y) / y\"\n  for x :: real\n  by (simp add: ln_div [symmetric] diff_divide_distrib ln_le_minus_one)\n\nlemma ln_eq_minus_one:\n  fixes x :: real\n  assumes \"0 < x\" \"ln x = x - 1\"\n  shows \"x = 1\"\nproof -\n  let ?l = \"\\<lambda>y. ln y - y + 1\"\n  have D: \"\\<And>x::real. 0 < x \\<Longrightarrow> DERIV ?l x :> (1 / x - 1)\"\n    by (auto intro!: derivative_eq_intros)\n\n  show ?thesis\n  proof (cases rule: linorder_cases)\n    assume \"x < 1\"\n    from dense[OF \\<open>x < 1\\<close>] obtain a where \"x < a\" \"a < 1\" by blast\n    from \\<open>x < a\\<close> have \"?l x < ?l a\"\n    proof (rule DERIV_pos_imp_increasing, safe)\n      fix y\n      assume \"x \\<le> y\" \"y \\<le> a\"\n      with \\<open>0 < x\\<close> \\<open>a < 1\\<close> have \"0 < 1 / y - 1\" \"0 < y\"\n        by (auto simp: field_simps)\n      with D show \"\\<exists>z. DERIV ?l y :> z \\<and> 0 < z\" by blast\n    qed\n    also have \"\\<dots> \\<le> 0\"\n      using ln_le_minus_one \\<open>0 < x\\<close> \\<open>x < a\\<close> by (auto simp: field_simps)\n    finally show \"x = 1\" using assms by auto\n  next\n    assume \"1 < x\"\n    from dense[OF this] obtain a where \"1 < a\" \"a < x\" by blast\n    from \\<open>a < x\\<close> have \"?l x < ?l a\"\n    proof (rule DERIV_neg_imp_decreasing, safe)\n      fix y\n      assume \"a \\<le> y\" \"y \\<le> x\"\n      with \\<open>1 < a\\<close> have \"1 / y - 1 < 0\" \"0 < y\"\n        by (auto simp: field_simps)\n      with D show \"\\<exists>z. DERIV ?l y :> z \\<and> z < 0\"\n        by blast\n    qed\n    also have \"\\<dots> \\<le> 0\"\n      using ln_le_minus_one \\<open>1 < a\\<close> by (auto simp: field_simps)\n    finally show \"x = 1\" using assms by auto\n  next\n    assume \"x = 1\"\n    then show ?thesis by simp\n  qed\nqed\n\nlemma ln_x_over_x_tendsto_0: \"((\\<lambda>x::real. ln x / x) \\<longlongrightarrow> 0) at_top\"\nproof (rule lhospital_at_top_at_top[where f' = inverse and g' = \"\\<lambda>_. 1\"])\n  from eventually_gt_at_top[of \"0::real\"]\n  show \"\\<forall>\\<^sub>F x in at_top. (ln has_real_derivative inverse x) (at x)\"\n    by eventually_elim (auto intro!: derivative_eq_intros simp: field_simps)\nqed (use tendsto_inverse_0 in\n      \\<open>auto simp: filterlim_ident dest!: tendsto_mono[OF at_top_le_at_infinity]\\<close>)\n\nlemma exp_ge_one_plus_x_over_n_power_n:\n  assumes \"x \\<ge> - real n\" \"n > 0\"\n  shows \"(1 + x / of_nat n) ^ n \\<le> exp x\"\nproof (cases \"x = - of_nat n\")\n  case False\n  from assms False have \"(1 + x / of_nat n) ^ n = exp (of_nat n * ln (1 + x / of_nat n))\"\n    by (subst exp_of_nat_mult, subst exp_ln) (simp_all add: field_simps)\n  also from assms False have \"ln (1 + x / real n) \\<le> x / real n\"\n    by (intro ln_add_one_self_le_self2) (simp_all add: field_simps)\n  with assms have \"exp (of_nat n * ln (1 + x / of_nat n)) \\<le> exp x\"\n    by (simp add: field_simps)\n  finally show ?thesis .\nnext\n  case True\n  then show ?thesis by (simp add: zero_power)\nqed\n\nlemma exp_ge_one_minus_x_over_n_power_n:\n  assumes \"x \\<le> real n\" \"n > 0\"\n  shows \"(1 - x / of_nat n) ^ n \\<le> exp (-x)\"\n  using exp_ge_one_plus_x_over_n_power_n[of n \"-x\"] assms by simp\n\nlemma exp_at_bot: \"(exp \\<longlongrightarrow> (0::real)) at_bot\"\n  unfolding tendsto_Zfun_iff\nproof (rule ZfunI, simp add: eventually_at_bot_dense)\n  fix r :: real\n  assume \"0 < r\"\n  have \"exp x < r\" if \"x < ln r\" for x\n  proof -\n    from that have \"exp x < exp (ln r)\"\n      by simp\n    with \\<open>0 < r\\<close> show ?thesis\n      by simp\n  qed\n  then show \"\\<exists>k. \\<forall>n<k. exp n < r\" by auto\nqed\n\nlemma exp_at_top: \"LIM x at_top. exp 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=\"ln\"])\n    (auto intro: eventually_gt_at_top)\n\nlemma lim_exp_minus_1: \"((\\<lambda>z::'a. (exp(z) - 1) / z) \\<longlongrightarrow> 1) (at 0)\"\n  for x :: \"'a::{real_normed_field,banach}\"\nproof -\n  have \"((\\<lambda>z::'a. exp(z) - 1) has_field_derivative 1) (at 0)\"\n    by (intro derivative_eq_intros | simp)+\n  then show ?thesis\n    by (simp add: Deriv.DERIV_iff2)\nqed\n\nlemma ln_at_0: \"LIM x at_right 0. ln (x::real) :> at_bot\"\n  by (rule filterlim_at_bot_at_right[where Q=\"\\<lambda>x. 0 < x\" and P=\"\\<lambda>x. True\" and g=\"exp\"])\n     (auto simp: eventually_at_filter)\n\nlemma ln_at_top: \"LIM x at_top. ln (x::real) :> at_top\"\n  by (rule filterlim_at_top_at_top[where Q=\"\\<lambda>x. 0 < x\" and P=\"\\<lambda>x. True\" and g=\"exp\"])\n     (auto intro: eventually_gt_at_top)\n\nlemma filtermap_ln_at_top: \"filtermap (ln::real \\<Rightarrow> real) at_top = at_top\"\n  by (intro filtermap_fun_inverse[of exp] exp_at_top ln_at_top) auto\n\nlemma filtermap_exp_at_top: \"filtermap (exp::real \\<Rightarrow> real) at_top = at_top\"\n  by (intro filtermap_fun_inverse[of ln] exp_at_top ln_at_top)\n     (auto simp: eventually_at_top_dense)\n\nlemma tendsto_power_div_exp_0: \"((\\<lambda>x. x ^ k / exp x) \\<longlongrightarrow> (0::real)) at_top\"\nproof (induct k)\n  case 0\n  show \"((\\<lambda>x. x ^ 0 / exp x) \\<longlongrightarrow> (0::real)) at_top\"\n    by (simp add: inverse_eq_divide[symmetric])\n       (metis filterlim_compose[OF tendsto_inverse_0] exp_at_top filterlim_mono\n         at_top_le_at_infinity order_refl)\nnext\n  case (Suc k)\n  show ?case\n  proof (rule lhospital_at_top_at_top)\n    show \"eventually (\\<lambda>x. DERIV (\\<lambda>x. x ^ Suc k) x :> (real (Suc k) * x^k)) at_top\"\n      by eventually_elim (intro derivative_eq_intros, auto)\n    show \"eventually (\\<lambda>x. DERIV exp x :> exp x) at_top\"\n      by eventually_elim auto\n    show \"eventually (\\<lambda>x. exp x \\<noteq> 0) at_top\"\n      by auto\n    from tendsto_mult[OF tendsto_const Suc, of \"real (Suc k)\"]\n    show \"((\\<lambda>x. real (Suc k) * x ^ k / exp x) \\<longlongrightarrow> 0) at_top\"\n      by simp\n  qed (rule exp_at_top)\nqed\n\ndefinition log :: \"real \\<Rightarrow> real \\<Rightarrow> real\"\n  \\<comment> \\<open>logarithm of @{term x} to base @{term a}\\<close>\n  where \"log a x = ln x / ln a\"\n\nlemma tendsto_log [tendsto_intros]:\n  \"(f \\<longlongrightarrow> a) F \\<Longrightarrow> (g \\<longlongrightarrow> b) F \\<Longrightarrow> 0 < a \\<Longrightarrow> a \\<noteq> 1 \\<Longrightarrow> 0 < b \\<Longrightarrow>\n    ((\\<lambda>x. log (f x) (g x)) \\<longlongrightarrow> log a b) F\"\n  unfolding log_def by (intro tendsto_intros) auto\n\nlemma continuous_log:\n  assumes \"continuous F f\"\n    and \"continuous F g\"\n    and \"0 < f (Lim F (\\<lambda>x. x))\"\n    and \"f (Lim F (\\<lambda>x. x)) \\<noteq> 1\"\n    and \"0 < g (Lim F (\\<lambda>x. x))\"\n  shows \"continuous F (\\<lambda>x. log (f x) (g x))\"\n  using assms unfolding continuous_def by (rule tendsto_log)\n\nlemma continuous_at_within_log[continuous_intros]:\n  assumes \"continuous (at a within s) f\"\n    and \"continuous (at a within s) g\"\n    and \"0 < f a\"\n    and \"f a \\<noteq> 1\"\n    and \"0 < g a\"\n  shows \"continuous (at a within s) (\\<lambda>x. log (f x) (g x))\"\n  using assms unfolding continuous_within by (rule tendsto_log)\n\nlemma isCont_log[continuous_intros, simp]:\n  assumes \"isCont f a\" \"isCont g a\" \"0 < f a\" \"f a \\<noteq> 1\" \"0 < g a\"\n  shows \"isCont (\\<lambda>x. log (f x) (g x)) a\"\n  using assms unfolding continuous_at by (rule tendsto_log)\n\nlemma continuous_on_log[continuous_intros]:\n  assumes \"continuous_on s f\" \"continuous_on s g\"\n    and \"\\<forall>x\\<in>s. 0 < f x\" \"\\<forall>x\\<in>s. f x \\<noteq> 1\" \"\\<forall>x\\<in>s. 0 < g x\"\n  shows \"continuous_on s (\\<lambda>x. log (f x) (g x))\"\n  using assms unfolding continuous_on_def by (fast intro: tendsto_log)\n\nlemma powr_one_eq_one [simp]: \"1 powr a = 1\"\n  by (simp add: powr_def)\n\nlemma powr_zero_eq_one [simp]: \"x powr 0 = (if x = 0 then 0 else 1)\"\n  by (simp add: powr_def)\n\nlemma powr_one_gt_zero_iff [simp]: \"x powr 1 = x \\<longleftrightarrow> 0 \\<le> x\"\n  for x :: real\n  by (auto simp: powr_def)\ndeclare powr_one_gt_zero_iff [THEN iffD2, simp]\n\nlemma powr_mult: \"0 \\<le> x \\<Longrightarrow> 0 \\<le> y \\<Longrightarrow> (x * y) powr a = (x powr a) * (y powr a)\"\n  for a x y :: real\n  by (simp add: powr_def exp_add [symmetric] ln_mult distrib_left)\n\nlemma powr_ge_pzero [simp]: \"0 \\<le> x powr y\"\n  for x y :: real\n  by (simp add: powr_def)\n\nlemma powr_divide: \"0 < x \\<Longrightarrow> 0 < y \\<Longrightarrow> (x / y) powr a = (x powr a) / (y powr a)\"\n  for a b x :: real\n  apply (simp add: divide_inverse positive_imp_inverse_positive powr_mult)\n  apply (simp add: powr_def exp_minus [symmetric] exp_add [symmetric] ln_inverse)\n  done\n\nlemma powr_divide2: \"x powr a / x powr b = x powr (a - b)\"\n  for a b x :: real\n  apply (simp add: powr_def)\n  apply (subst exp_diff [THEN sym])\n  apply (simp add: left_diff_distrib)\n  done\n\nlemma powr_add: \"x powr (a + b) = (x powr a) * (x powr b)\"\n  for a b x :: real\n  by (simp add: powr_def exp_add [symmetric] distrib_right)\n\nlemma powr_mult_base: \"0 < x \\<Longrightarrow>x * x powr y = x powr (1 + y)\"\n  for x :: real\n  by (auto simp: powr_add)\n\nlemma powr_powr: \"(x powr a) powr b = x powr (a * b)\"\n  for a b x :: real\n  by (simp add: powr_def)\n\nlemma powr_powr_swap: \"(x powr a) powr b = (x powr b) powr a\"\n  for a b x :: real\n  by (simp add: powr_powr mult.commute)\n\nlemma powr_minus: \"x powr (- a) = inverse (x powr a)\"\n  for x a :: real\n  by (simp add: powr_def exp_minus [symmetric])\n\nlemma powr_minus_divide: \"x powr (- a) = 1/(x powr a)\"\n  for x a :: real\n  by (simp add: divide_inverse powr_minus)\n\nlemma divide_powr_uminus: \"a / b powr c = a * b powr (- c)\"\n  for a b c :: real\n  by (simp add: powr_minus_divide)\n\nlemma powr_less_mono: \"a < b \\<Longrightarrow> 1 < x \\<Longrightarrow> x powr a < x powr b\"\n  for a b x :: real\n  by (simp add: powr_def)\n\nlemma powr_less_cancel: \"x powr a < x powr b \\<Longrightarrow> 1 < x \\<Longrightarrow> a < b\"\n  for a b x :: real\n  by (simp add: powr_def)\n\nlemma powr_less_cancel_iff [simp]: \"1 < x \\<Longrightarrow> x powr a < x powr b \\<longleftrightarrow> a < b\"\n  for a b x :: real\n  by (blast intro: powr_less_cancel powr_less_mono)\n\nlemma powr_le_cancel_iff [simp]: \"1 < x \\<Longrightarrow> x powr a \\<le> x powr b \\<longleftrightarrow> a \\<le> b\"\n  for a b x :: real\n  by (simp add: linorder_not_less [symmetric])\n\nlemma log_ln: \"ln x = log (exp(1)) x\"\n  by (simp add: log_def)\n\nlemma DERIV_log:\n  assumes \"x > 0\"\n  shows \"DERIV (\\<lambda>y. log b y) x :> 1 / (ln b * x)\"\nproof -\n  define lb where \"lb = 1 / ln b\"\n  moreover have \"DERIV (\\<lambda>y. lb * ln y) x :> lb / x\"\n    using \\<open>x > 0\\<close> by (auto intro!: derivative_eq_intros)\n  ultimately show ?thesis\n    by (simp add: log_def)\nqed\n\nlemmas DERIV_log[THEN DERIV_chain2, derivative_intros]\n  and DERIV_log[THEN DERIV_chain2, unfolded has_field_derivative_def, derivative_intros]\n\nlemma powr_log_cancel [simp]: \"0 < a \\<Longrightarrow> a \\<noteq> 1 \\<Longrightarrow> 0 < x \\<Longrightarrow> a powr (log a x) = x\"\n  by (simp add: powr_def log_def)\n\nlemma log_powr_cancel [simp]: \"0 < a \\<Longrightarrow> a \\<noteq> 1 \\<Longrightarrow> log a (a powr y) = y\"\n  by (simp add: log_def powr_def)\n\nlemma log_mult:\n  \"0 < a \\<Longrightarrow> a \\<noteq> 1 \\<Longrightarrow> 0 < x \\<Longrightarrow> 0 < y \\<Longrightarrow>\n    log a (x * y) = log a x + log a y\"\n  by (simp add: log_def ln_mult divide_inverse distrib_right)\n\nlemma log_eq_div_ln_mult_log:\n  \"0 < a \\<Longrightarrow> a \\<noteq> 1 \\<Longrightarrow> 0 < b \\<Longrightarrow> b \\<noteq> 1 \\<Longrightarrow> 0 < x \\<Longrightarrow>\n    log a x = (ln b/ln a) * log b x\"\n  by (simp add: log_def divide_inverse)\n\ntext\\<open>Base 10 logarithms\\<close>\nlemma log_base_10_eq1: \"0 < x \\<Longrightarrow> log 10 x = (ln (exp 1) / ln 10) * ln x\"\n  by (simp add: log_def)\n\nlemma log_base_10_eq2: \"0 < x \\<Longrightarrow> log 10 x = (log 10 (exp 1)) * ln x\"\n  by (simp add: log_def)\n\nlemma log_one [simp]: \"log a 1 = 0\"\n  by (simp add: log_def)\n\nlemma log_eq_one [simp]: \"0 < a \\<Longrightarrow> a \\<noteq> 1 \\<Longrightarrow> log a a = 1\"\n  by (simp add: log_def)\n\nlemma log_inverse: \"0 < a \\<Longrightarrow> a \\<noteq> 1 \\<Longrightarrow> 0 < x \\<Longrightarrow> log a (inverse x) = - log a x\"\n  apply (rule add_left_cancel [THEN iffD1, where a1 = \"log a x\"])\n  apply (simp add: log_mult [symmetric])\n  done\n\nlemma log_divide: \"0 < a \\<Longrightarrow> a \\<noteq> 1 \\<Longrightarrow> 0 < x \\<Longrightarrow> 0 < y \\<Longrightarrow> log a (x/y) = log a x - log a y\"\n  by (simp add: log_mult divide_inverse log_inverse)\n\nlemma powr_gt_zero [simp]: \"0 < x powr a \\<longleftrightarrow> x \\<noteq> 0\"\n  for a x :: real\n  by (simp add: powr_def)\n\nlemma log_add_eq_powr: \"0 < b \\<Longrightarrow> b \\<noteq> 1 \\<Longrightarrow> 0 < x \\<Longrightarrow> log b x + y = log b (x * b powr y)\"\n  and add_log_eq_powr: \"0 < b \\<Longrightarrow> b \\<noteq> 1 \\<Longrightarrow> 0 < x \\<Longrightarrow> y + log b x = log b (b powr y * x)\"\n  and log_minus_eq_powr: \"0 < b \\<Longrightarrow> b \\<noteq> 1 \\<Longrightarrow> 0 < x \\<Longrightarrow> log b x - y = log b (x * b powr -y)\"\n  and minus_log_eq_powr: \"0 < b \\<Longrightarrow> b \\<noteq> 1 \\<Longrightarrow> 0 < x \\<Longrightarrow> y - log b x = log b (b powr y / x)\"\n  by (simp_all add: log_mult log_divide)\n\nlemma log_less_cancel_iff [simp]: \"1 < a \\<Longrightarrow> 0 < x \\<Longrightarrow> 0 < y \\<Longrightarrow> log a x < log a y \\<longleftrightarrow> x < y\"\n  apply safe\n   apply (rule_tac [2] powr_less_cancel)\n    apply (drule_tac a = \"log a x\" in powr_less_mono)\n     apply auto\n  done\n\nlemma log_inj:\n  assumes \"1 < b\"\n  shows \"inj_on (log b) {0 <..}\"\nproof (rule inj_onI, simp)\n  fix x y\n  assume pos: \"0 < x\" \"0 < y\" and *: \"log b x = log b y\"\n  show \"x = y\"\n  proof (cases rule: linorder_cases)\n    assume \"x = y\"\n    then show ?thesis by simp\n  next\n    assume \"x < y\"\n    then have \"log b x < log b y\"\n      using log_less_cancel_iff[OF \\<open>1 < b\\<close>] pos by simp\n    then show ?thesis using * by simp\n  next\n    assume \"y < x\"\n    then have \"log b y < log b x\"\n      using log_less_cancel_iff[OF \\<open>1 < b\\<close>] pos by simp\n    then show ?thesis using * by simp\n  qed\nqed\n\nlemma log_le_cancel_iff [simp]: \"1 < a \\<Longrightarrow> 0 < x \\<Longrightarrow> 0 < y \\<Longrightarrow> log a x \\<le> log a y \\<longleftrightarrow> x \\<le> y\"\n  by (simp add: linorder_not_less [symmetric])\n\nlemma zero_less_log_cancel_iff[simp]: \"1 < a \\<Longrightarrow> 0 < x \\<Longrightarrow> 0 < log a x \\<longleftrightarrow> 1 < x\"\n  using log_less_cancel_iff[of a 1 x] by simp\n\nlemma zero_le_log_cancel_iff[simp]: \"1 < a \\<Longrightarrow> 0 < x \\<Longrightarrow> 0 \\<le> log a x \\<longleftrightarrow> 1 \\<le> x\"\n  using log_le_cancel_iff[of a 1 x] by simp\n\nlemma log_less_zero_cancel_iff[simp]: \"1 < a \\<Longrightarrow> 0 < x \\<Longrightarrow> log a x < 0 \\<longleftrightarrow> x < 1\"\n  using log_less_cancel_iff[of a x 1] by simp\n\nlemma log_le_zero_cancel_iff[simp]: \"1 < a \\<Longrightarrow> 0 < x \\<Longrightarrow> log a x \\<le> 0 \\<longleftrightarrow> x \\<le> 1\"\n  using log_le_cancel_iff[of a x 1] by simp\n\nlemma one_less_log_cancel_iff[simp]: \"1 < a \\<Longrightarrow> 0 < x \\<Longrightarrow> 1 < log a x \\<longleftrightarrow> a < x\"\n  using log_less_cancel_iff[of a a x] by simp\n\nlemma one_le_log_cancel_iff[simp]: \"1 < a \\<Longrightarrow> 0 < x \\<Longrightarrow> 1 \\<le> log a x \\<longleftrightarrow> a \\<le> x\"\n  using log_le_cancel_iff[of a a x] by simp\n\nlemma log_less_one_cancel_iff[simp]: \"1 < a \\<Longrightarrow> 0 < x \\<Longrightarrow> log a x < 1 \\<longleftrightarrow> x < a\"\n  using log_less_cancel_iff[of a x a] by simp\n\nlemma log_le_one_cancel_iff[simp]: \"1 < a \\<Longrightarrow> 0 < x \\<Longrightarrow> log a x \\<le> 1 \\<longleftrightarrow> x \\<le> a\"\n  using log_le_cancel_iff[of a x a] by simp\n\nlemma le_log_iff:\n  fixes b x y :: real\n  assumes \"1 < b\" \"x > 0\"\n  shows \"y \\<le> log b x \\<longleftrightarrow> b powr y \\<le> x\"\n  using assms\n  apply auto\n   apply (metis (no_types, hide_lams) less_irrefl less_le_trans linear powr_le_cancel_iff\n      powr_log_cancel zero_less_one)\n  apply (metis not_less order.trans order_refl powr_le_cancel_iff powr_log_cancel zero_le_one)\n  done\n\nlemma less_log_iff:\n  assumes \"1 < b\" \"x > 0\"\n  shows \"y < log b x \\<longleftrightarrow> b powr y < x\"\n  by (metis assms dual_order.strict_trans less_irrefl powr_less_cancel_iff\n    powr_log_cancel zero_less_one)\n\nlemma\n  assumes \"1 < b\" \"x > 0\"\n  shows log_less_iff: \"log b x < y \\<longleftrightarrow> x < b powr y\"\n    and log_le_iff: \"log b x \\<le> y \\<longleftrightarrow> x \\<le> b powr y\"\n  using le_log_iff[OF assms, of y] less_log_iff[OF assms, of y]\n  by auto\n\nlemmas powr_le_iff = le_log_iff[symmetric]\n  and powr_less_iff = le_log_iff[symmetric]\n  and less_powr_iff = log_less_iff[symmetric]\n  and le_powr_iff = log_le_iff[symmetric]\n\nlemma floor_log_eq_powr_iff: \"x > 0 \\<Longrightarrow> b > 1 \\<Longrightarrow> \\<lfloor>log b x\\<rfloor> = k \\<longleftrightarrow> b powr k \\<le> x \\<and> x < b powr (k + 1)\"\n  by (auto simp add: floor_eq_iff powr_le_iff less_powr_iff)\n\nlemma powr_realpow: \"0 < x \\<Longrightarrow> x powr (real n) = x^n\"\n  by (induct n) (simp_all add: ac_simps powr_add)\n\nlemma powr_numeral: \"0 < x \\<Longrightarrow> x powr (numeral n :: real) = x ^ (numeral n)\"\n  by (metis of_nat_numeral powr_realpow)\n\nlemma powr_real_of_int:\n  \"x > 0 \\<Longrightarrow> x powr real_of_int n = (if n \\<ge> 0 then x ^ nat n else inverse (x ^ nat (- n)))\"\n  using powr_realpow[of x \"nat n\"] powr_realpow[of x \"nat (-n)\"]\n  by (auto simp: field_simps powr_minus)\n\nlemma powr2_sqrt[simp]: \"0 < x \\<Longrightarrow> sqrt x powr 2 = x\"\n  by (simp add: powr_numeral)\n\nlemma powr_realpow2: \"0 \\<le> x \\<Longrightarrow> 0 < n \\<Longrightarrow> x^n = (if (x = 0) then 0 else x powr (real n))\"\n  apply (cases \"x = 0\")\n   apply simp_all\n  apply (rule powr_realpow [THEN sym])\n  apply simp\n  done\n\nlemma powr_int:\n  assumes \"x > 0\"\n  shows \"x powr i = (if i \\<ge> 0 then x ^ nat i else 1 / x ^ nat (-i))\"\nproof (cases \"i < 0\")\n  case True\n  have r: \"x powr i = 1 / x powr (- i)\"\n    by (simp add: powr_minus field_simps)\n  show ?thesis using \\<open>i < 0\\<close> \\<open>x > 0\\<close>\n    by (simp add: r field_simps powr_realpow[symmetric])\nnext\n  case False\n  then show ?thesis\n    by (simp add: assms powr_realpow[symmetric])\nqed\n\nlemma compute_powr[code]:\n  fixes i :: real\n  shows \"b powr i =\n    (if b \\<le> 0 then Code.abort (STR ''op powr with nonpositive base'') (\\<lambda>_. b powr i)\n     else if \\<lfloor>i\\<rfloor> = i then (if 0 \\<le> i then b ^ nat \\<lfloor>i\\<rfloor> else 1 / b ^ nat \\<lfloor>- i\\<rfloor>)\n     else Code.abort (STR ''op powr with non-integer exponent'') (\\<lambda>_. b powr i))\"\n  by (auto simp: powr_int)\n\nlemma powr_one: \"0 \\<le> x \\<Longrightarrow> x powr 1 = x\"\n  for x :: real\n  using powr_realpow [of x 1] by simp\n\nlemma powr_neg_one: \"0 < x \\<Longrightarrow> x powr - 1 = 1 / x\"\n  for x :: real\n  using powr_int [of x \"- 1\"] by simp\n\nlemma powr_neg_numeral: \"0 < x \\<Longrightarrow> x powr - numeral n = 1 / x ^ numeral n\"\n  for x :: real\n  using powr_int [of x \"- numeral n\"] by simp\n\nlemma root_powr_inverse: \"0 < n \\<Longrightarrow> 0 < x \\<Longrightarrow> root n x = x powr (1/n)\"\n  by (rule real_root_pos_unique) (auto simp: powr_realpow[symmetric] powr_powr)\n\nlemma ln_powr: \"x \\<noteq> 0 \\<Longrightarrow> ln (x powr y) = y * ln x\"\n  for x :: real\n  by (simp add: powr_def)\n\nlemma ln_root: \"n > 0 \\<Longrightarrow> b > 0 \\<Longrightarrow> ln (root n b) =  ln b / n\"\n  by (simp add: root_powr_inverse ln_powr)\n\nlemma ln_sqrt: \"0 < x \\<Longrightarrow> ln (sqrt x) = ln x / 2\"\n  by (simp add: ln_powr powr_numeral ln_powr[symmetric] mult.commute)\n\nlemma log_root: \"n > 0 \\<Longrightarrow> a > 0 \\<Longrightarrow> log b (root n a) =  log b a / n\"\n  by (simp add: log_def ln_root)\n\nlemma log_powr: \"x \\<noteq> 0 \\<Longrightarrow> log b (x powr y) = y * log b x\"\n  by (simp add: log_def ln_powr)\n\nlemma log_nat_power: \"0 < x \\<Longrightarrow> log b (x^n) = real n * log b x\"\n  by (simp add: log_powr powr_realpow [symmetric])\n\nlemma le_log_of_power:\n  assumes \"1 < b\" \"b ^ n \\<le> m\"\n  shows \"n \\<le> log b m\"\nproof -\n   from assms have \"0 < m\"\n     by (metis less_trans zero_less_power less_le_trans zero_less_one)\n   have \"n = log b (b ^ n)\"\n     using assms(1) by (simp add: log_nat_power)\n   also have \"\\<dots> \\<le> log b m\"\n     using assms \\<open>0 < m\\<close> by simp\n   finally show ?thesis .\nqed\n\nlemma le_log2_of_power: \"2 ^ n \\<le> m \\<Longrightarrow> n \\<le> log 2 m\"\n  for m n :: nat\n  using le_log_of_power[of 2] by simp\n\nlemma log_base_change: \"0 < a \\<Longrightarrow> a \\<noteq> 1 \\<Longrightarrow> log b x = log a x / log a b\"\n  by (simp add: log_def)\n\nlemma log_base_pow: \"0 < a \\<Longrightarrow> log (a ^ n) x = log a x / n\"\n  by (simp add: log_def ln_realpow)\n\nlemma log_base_powr: \"a \\<noteq> 0 \\<Longrightarrow> log (a powr b) x = log a x / b\"\n  by (simp add: log_def ln_powr)\n\nlemma log_base_root: \"n > 0 \\<Longrightarrow> b > 0 \\<Longrightarrow> log (root n b) x = n * (log b x)\"\n  by (simp add: log_def ln_root)\n\nlemma ln_bound: \"1 \\<le> x \\<Longrightarrow> ln x \\<le> x\"\n  for x :: real\n  apply (subgoal_tac \"ln (1 + (x - 1)) \\<le> x - 1\")\n   apply simp\n  apply (rule ln_add_one_self_le_self)\n  apply simp\n  done\n\nlemma powr_mono: \"a \\<le> b \\<Longrightarrow> 1 \\<le> x \\<Longrightarrow> x powr a \\<le> x powr b\"\n  for x :: real\n  apply (cases \"x = 1\")\n   apply simp\n  apply (cases \"a = b\")\n   apply simp\n  apply (rule order_less_imp_le)\n  apply (rule powr_less_mono)\n   apply auto\n  done\n\nlemma ge_one_powr_ge_zero: \"1 \\<le> x \\<Longrightarrow> 0 \\<le> a \\<Longrightarrow> 1 \\<le> x powr a\"\n  for x :: real\n  using powr_mono by fastforce\n\nlemma powr_less_mono2: \"0 < a \\<Longrightarrow> 0 \\<le> x \\<Longrightarrow> x < y \\<Longrightarrow> x powr a < y powr a\"\n  for x :: real\n  by (simp add: powr_def)\n\nlemma powr_less_mono2_neg: \"a < 0 \\<Longrightarrow> 0 < x \\<Longrightarrow> x < y \\<Longrightarrow> y powr a < x powr a\"\n  for x :: real\n  by (simp add: powr_def)\n\nlemma powr_mono2: \"0 \\<le> a \\<Longrightarrow> 0 \\<le> x \\<Longrightarrow> x \\<le> y \\<Longrightarrow> x powr a \\<le> y powr a\"\n  for x :: real\n  apply (case_tac \"a = 0\")\n   apply simp\n  apply (case_tac \"x = y\")\n   apply simp\n  apply (metis dual_order.strict_iff_order powr_less_mono2)\n  done\n\nlemma powr_mono2':\n  fixes a x y :: real\n  assumes \"a \\<le> 0\" \"x > 0\" \"x \\<le> y\"\n  shows \"x powr a \\<ge> y powr a\"\nproof -\n  from assms have \"x powr - a \\<le> y powr - a\"\n    by (intro powr_mono2) simp_all\n  with assms show ?thesis\n    by (auto simp add: powr_minus field_simps)\nqed\n\nlemma powr_inj: \"0 < a \\<Longrightarrow> a \\<noteq> 1 \\<Longrightarrow> a powr x = a powr y \\<longleftrightarrow> x = y\"\n  for x :: real\n  unfolding powr_def exp_inj_iff by simp\n\nlemma powr_half_sqrt: \"0 \\<le> x \\<Longrightarrow> x powr (1/2) = sqrt x\"\n  by (simp add: powr_def root_powr_inverse sqrt_def)\n\nlemma ln_powr_bound: \"1 \\<le> x \\<Longrightarrow> 0 < a \\<Longrightarrow> ln x \\<le> (x powr a) / a\"\n  for x :: real\n  by (metis exp_gt_zero linear ln_eq_zero_iff ln_exp ln_less_self ln_powr mult.commute\n      mult_imp_le_div_pos not_less powr_gt_zero)\n\nlemma ln_powr_bound2:\n  fixes x :: real\n  assumes \"1 < x\" and \"0 < a\"\n  shows \"(ln x) powr a \\<le> (a powr a) * x\"\nproof -\n  from assms have \"ln x \\<le> (x powr (1 / a)) / (1 / a)\"\n    by (metis less_eq_real_def ln_powr_bound zero_less_divide_1_iff)\n  also have \"\\<dots> = a * (x powr (1 / a))\"\n    by simp\n  finally have \"(ln x) powr a \\<le> (a * (x powr (1 / a))) powr a\"\n    by (metis assms less_imp_le ln_gt_zero powr_mono2)\n  also have \"\\<dots> = (a powr a) * ((x powr (1 / a)) powr a)\"\n    using assms powr_mult by auto\n  also have \"(x powr (1 / a)) powr a = x powr ((1 / a) * a)\"\n    by (rule powr_powr)\n  also have \"\\<dots> = x\" using assms\n    by auto\n  finally show ?thesis .\nqed\n\nlemma tendsto_powr:\n  fixes a b :: real\n  assumes f: \"(f \\<longlongrightarrow> a) F\"\n    and g: \"(g \\<longlongrightarrow> b) F\"\n    and a: \"a \\<noteq> 0\"\n  shows \"((\\<lambda>x. f x powr g x) \\<longlongrightarrow> a powr b) F\"\n  unfolding powr_def\nproof (rule filterlim_If)\n  from f show \"((\\<lambda>x. 0) \\<longlongrightarrow> (if a = 0 then 0 else exp (b * ln a))) (inf F (principal {x. f x = 0}))\"\n    by simp (auto simp: filterlim_iff eventually_inf_principal elim: eventually_mono dest: t1_space_nhds)\n  from f g a show \"((\\<lambda>x. exp (g x * ln (f x))) \\<longlongrightarrow> (if a = 0 then 0 else exp (b * ln a)))\n      (inf F (principal {x. f x \\<noteq> 0}))\"\n    by (auto intro!: tendsto_intros intro: tendsto_mono inf_le1)\nqed\n\nlemma tendsto_powr'[tendsto_intros]:\n  fixes a :: real\n  assumes f: \"(f \\<longlongrightarrow> a) F\"\n    and g: \"(g \\<longlongrightarrow> b) F\"\n    and a: \"a \\<noteq> 0 \\<or> (b > 0 \\<and> eventually (\\<lambda>x. f x \\<ge> 0) F)\"\n  shows \"((\\<lambda>x. f x powr g x) \\<longlongrightarrow> a powr b) F\"\nproof -\n  from a consider \"a \\<noteq> 0\" | \"a = 0\" \"b > 0\" \"eventually (\\<lambda>x. f x \\<ge> 0) F\"\n    by auto\n  then show ?thesis\n  proof cases\n    case 1\n    with f g show ?thesis by (rule tendsto_powr)\n  next\n    case 2\n    have \"((\\<lambda>x. if f x = 0 then 0 else exp (g x * ln (f x))) \\<longlongrightarrow> 0) F\"\n    proof (intro filterlim_If)\n      have \"filterlim f (principal {0<..}) (inf F (principal {z. f z \\<noteq> 0}))\"\n        using \\<open>eventually (\\<lambda>x. f x \\<ge> 0) F\\<close>\n        by (auto simp add: filterlim_iff eventually_inf_principal\n            eventually_principal elim: eventually_mono)\n      moreover have \"filterlim f (nhds a) (inf F (principal {z. f z \\<noteq> 0}))\"\n        by (rule tendsto_mono[OF _ f]) simp_all\n      ultimately have f: \"filterlim f (at_right 0) (inf F (principal {x. f x \\<noteq> 0}))\"\n        by (simp add: at_within_def filterlim_inf \\<open>a = 0\\<close>)\n      have g: \"(g \\<longlongrightarrow> b) (inf F (principal {z. f z \\<noteq> 0}))\"\n        by (rule tendsto_mono[OF _ g]) simp_all\n      show \"((\\<lambda>x. exp (g x * ln (f x))) \\<longlongrightarrow> 0) (inf F (principal {x. f x \\<noteq> 0}))\"\n        by (rule filterlim_compose[OF exp_at_bot] filterlim_tendsto_pos_mult_at_bot\n                 filterlim_compose[OF ln_at_0] f g \\<open>b > 0\\<close>)+\n    qed simp_all\n    with \\<open>a = 0\\<close> show ?thesis\n      by (simp add: powr_def)\n  qed\nqed\n\nlemma continuous_powr:\n  assumes \"continuous F f\"\n    and \"continuous F g\"\n    and \"f (Lim F (\\<lambda>x. x)) \\<noteq> 0\"\n  shows \"continuous F (\\<lambda>x. (f x) powr (g x :: real))\"\n  using assms unfolding continuous_def by (rule tendsto_powr)\n\nlemma continuous_at_within_powr[continuous_intros]:\n  fixes f g :: \"_ \\<Rightarrow> real\"\n  assumes \"continuous (at a within s) f\"\n    and \"continuous (at a within s) g\"\n    and \"f a \\<noteq> 0\"\n  shows \"continuous (at a within s) (\\<lambda>x. (f x) powr (g x))\"\n  using assms unfolding continuous_within by (rule tendsto_powr)\n\nlemma isCont_powr[continuous_intros, simp]:\n  fixes f g :: \"_ \\<Rightarrow> real\"\n  assumes \"isCont f a\" \"isCont g a\" \"f a \\<noteq> 0\"\n  shows \"isCont (\\<lambda>x. (f x) powr g x) a\"\n  using assms unfolding continuous_at by (rule tendsto_powr)\n\nlemma continuous_on_powr[continuous_intros]:\n  fixes f g :: \"_ \\<Rightarrow> real\"\n  assumes \"continuous_on s f\" \"continuous_on s g\" and \"\\<forall>x\\<in>s. f x \\<noteq> 0\"\n  shows \"continuous_on s (\\<lambda>x. (f x) powr (g x))\"\n  using assms unfolding continuous_on_def by (fast intro: tendsto_powr)\n\nlemma tendsto_powr2:\n  fixes a :: real\n  assumes f: \"(f \\<longlongrightarrow> a) F\"\n    and g: \"(g \\<longlongrightarrow> b) F\"\n    and \"\\<forall>\\<^sub>F x in F. 0 \\<le> f x\"\n    and b: \"0 < b\"\n  shows \"((\\<lambda>x. f x powr g x) \\<longlongrightarrow> a powr b) F\"\n  using tendsto_powr'[of f a F g b] assms by auto\n\nlemma DERIV_powr:\n  fixes r :: real\n  assumes g: \"DERIV g x :> m\"\n    and pos: \"g x > 0\"\n    and f: \"DERIV f x :> r\"\n  shows \"DERIV (\\<lambda>x. g x powr f x) x :> (g x powr f x) * (r * ln (g x) + m * f x / g x)\"\nproof -\n  have \"DERIV (\\<lambda>x. exp (f x * ln (g x))) x :> (g x powr f x) * (r * ln (g x) + m * f x / g x)\"\n    using pos\n    by (auto intro!: derivative_eq_intros g pos f simp: powr_def field_simps exp_diff)\n  then show ?thesis\n  proof (rule DERIV_cong_ev[OF refl _ refl, THEN iffD1, rotated])\n    from DERIV_isCont[OF g] pos have \"\\<forall>\\<^sub>F x in at x. 0 < g x\"\n      unfolding isCont_def by (rule order_tendstoD(1))\n    with pos show \"\\<forall>\\<^sub>F x in nhds x. exp (f x * ln (g x)) = g x powr f x\"\n      by (auto simp: eventually_at_filter powr_def elim: eventually_mono)\n  qed\nqed\n\nlemma DERIV_fun_powr:\n  fixes r :: real\n  assumes g: \"DERIV g x :> m\"\n    and pos: \"g x > 0\"\n  shows \"DERIV (\\<lambda>x. (g x) powr r) x :> r * (g x) powr (r - of_nat 1) * m\"\n  using DERIV_powr[OF g pos DERIV_const, of r] pos\n  by (simp add: powr_divide2[symmetric] field_simps)\n\nlemma has_real_derivative_powr:\n  assumes \"z > 0\"\n  shows \"((\\<lambda>z. z powr r) has_real_derivative r * z powr (r - 1)) (at z)\"\nproof (subst DERIV_cong_ev[OF refl _ refl])\n  from assms have \"eventually (\\<lambda>z. z \\<noteq> 0) (nhds z)\"\n    by (intro t1_space_nhds) auto\n  then show \"eventually (\\<lambda>z. z powr r = exp (r * ln z)) (nhds z)\"\n    unfolding powr_def by eventually_elim simp\n  from assms show \"((\\<lambda>z. exp (r * ln z)) has_real_derivative r * z powr (r - 1)) (at z)\"\n    by (auto intro!: derivative_eq_intros simp: powr_def field_simps exp_diff)\nqed\n\ndeclare has_real_derivative_powr[THEN DERIV_chain2, derivative_intros]\n\nlemma tendsto_zero_powrI:\n  assumes \"(f \\<longlongrightarrow> (0::real)) F\" \"(g \\<longlongrightarrow> b) F\" \"\\<forall>\\<^sub>F x in F. 0 \\<le> f x\" \"0 < b\"\n  shows \"((\\<lambda>x. f x powr g x) \\<longlongrightarrow> 0) F\"\n  using tendsto_powr2[OF assms] by simp\n\nlemma continuous_on_powr':\n  fixes f g :: \"_ \\<Rightarrow> real\"\n  assumes \"continuous_on s f\" \"continuous_on s g\"\n    and \"\\<forall>x\\<in>s. f x \\<ge> 0 \\<and> (f x = 0 \\<longrightarrow> g x > 0)\"\n  shows \"continuous_on s (\\<lambda>x. (f x) powr (g x))\"\n  unfolding continuous_on_def\nproof\n  fix x\n  assume x: \"x \\<in> s\"\n  from assms x show \"((\\<lambda>x. f x powr g x) \\<longlongrightarrow> f x powr g x) (at x within s)\"\n  proof (cases \"f x = 0\")\n    case True\n    from assms(3) have \"eventually (\\<lambda>x. f x \\<ge> 0) (at x within s)\"\n      by (auto simp: at_within_def eventually_inf_principal)\n    with True x assms show ?thesis\n      by (auto intro!: tendsto_zero_powrI[of f _ g \"g x\"] simp: continuous_on_def)\n  next\n    case False\n    with assms x show ?thesis\n      by (auto intro!: tendsto_powr' simp: continuous_on_def)\n  qed\nqed\n\nlemma tendsto_neg_powr:\n  assumes \"s < 0\"\n    and f: \"LIM x F. f x :> at_top\"\n  shows \"((\\<lambda>x. f x powr s) \\<longlongrightarrow> (0::real)) F\"\nproof -\n  have \"((\\<lambda>x. exp (s * ln (f x))) \\<longlongrightarrow> (0::real)) F\" (is \"?X\")\n    by (auto intro!: filterlim_compose[OF exp_at_bot] filterlim_compose[OF ln_at_top]\n        filterlim_tendsto_neg_mult_at_bot assms)\n  also have \"?X \\<longleftrightarrow> ((\\<lambda>x. f x powr s) \\<longlongrightarrow> (0::real)) F\"\n    using f filterlim_at_top_dense[of f F]\n    by (intro filterlim_cong[OF refl refl]) (auto simp: neq_iff powr_def elim: eventually_mono)\n  finally show ?thesis .\nqed\n\nlemma tendsto_exp_limit_at_right: \"((\\<lambda>y. (1 + x * y) powr (1 / y)) \\<longlongrightarrow> exp x) (at_right 0)\"\n  for x :: real\nproof (cases \"x = 0\")\n  case True\n  then show ?thesis by simp\nnext\n  case False\n  have \"((\\<lambda>y. ln (1 + x * y)::real) has_real_derivative 1 * x) (at 0)\"\n    by (auto intro!: derivative_eq_intros)\n  then have \"((\\<lambda>y. ln (1 + x * y) / y) \\<longlongrightarrow> x) (at 0)\"\n    by (auto simp add: has_field_derivative_def field_has_derivative_at)\n  then have *: \"((\\<lambda>y. exp (ln (1 + x * y) / y)) \\<longlongrightarrow> exp x) (at 0)\"\n    by (rule tendsto_intros)\n  then show ?thesis\n  proof (rule filterlim_mono_eventually)\n    show \"eventually (\\<lambda>xa. exp (ln (1 + x * xa) / xa) = (1 + x * xa) powr (1 / xa)) (at_right 0)\"\n      unfolding eventually_at_right[OF zero_less_one]\n      using False\n      apply (intro exI[of _ \"1 / \\<bar>x\\<bar>\"])\n      apply (auto simp: field_simps powr_def abs_if)\n      apply (metis add_less_same_cancel1 mult_less_0_iff not_less_iff_gr_or_eq zero_less_one)\n      done\n  qed (simp_all add: at_eq_sup_left_right)\nqed\n\nlemma tendsto_exp_limit_at_top: \"((\\<lambda>y. (1 + x / y) powr y) \\<longlongrightarrow> exp x) at_top\"\n  for x :: real\n  apply (subst filterlim_at_top_to_right)\n  apply (simp add: inverse_eq_divide)\n  apply (rule tendsto_exp_limit_at_right)\n  done\n\nlemma tendsto_exp_limit_sequentially: \"(\\<lambda>n. (1 + x / n) ^ n) \\<longlonglongrightarrow> exp x\"\n  for x :: real\nproof (rule filterlim_mono_eventually)\n  from reals_Archimedean2 [of \"\\<bar>x\\<bar>\"] obtain n :: nat where *: \"real n > \\<bar>x\\<bar>\" ..\n  then have \"eventually (\\<lambda>n :: nat. 0 < 1 + x / real n) at_top\"\n    apply (intro eventually_sequentiallyI [of n])\n    apply (cases \"x \\<ge> 0\")\n     apply (rule add_pos_nonneg)\n      apply (auto intro: divide_nonneg_nonneg)\n    apply (subgoal_tac \"x / real xa > - 1\")\n     apply (auto simp add: field_simps)\n    done\n  then show \"eventually (\\<lambda>n. (1 + x / n) powr n = (1 + x / n) ^ n) at_top\"\n    by (rule eventually_mono) (erule powr_realpow)\n  show \"(\\<lambda>n. (1 + x / real n) powr real n) \\<longlonglongrightarrow> exp x\"\n    by (rule filterlim_compose [OF tendsto_exp_limit_at_top filterlim_real_sequentially])\nqed auto\n\n\nsubsection \\<open>Sine and Cosine\\<close>\n\ndefinition sin_coeff :: \"nat \\<Rightarrow> real\"\n  where \"sin_coeff = (\\<lambda>n. if even n then 0 else (- 1) ^ ((n - Suc 0) div 2) / (fact n))\"\n\ndefinition cos_coeff :: \"nat \\<Rightarrow> real\"\n  where \"cos_coeff = (\\<lambda>n. if even n then ((- 1) ^ (n div 2)) / (fact n) else 0)\"\n\ndefinition sin :: \"'a \\<Rightarrow> 'a::{real_normed_algebra_1,banach}\"\n  where \"sin = (\\<lambda>x. \\<Sum>n. sin_coeff n *\\<^sub>R x^n)\"\n\ndefinition cos :: \"'a \\<Rightarrow> 'a::{real_normed_algebra_1,banach}\"\n  where \"cos = (\\<lambda>x. \\<Sum>n. cos_coeff n *\\<^sub>R x^n)\"\n\nlemma sin_coeff_0 [simp]: \"sin_coeff 0 = 0\"\n  unfolding sin_coeff_def by simp\n\nlemma cos_coeff_0 [simp]: \"cos_coeff 0 = 1\"\n  unfolding cos_coeff_def by simp\n\nlemma sin_coeff_Suc: \"sin_coeff (Suc n) = cos_coeff n / real (Suc n)\"\n  unfolding cos_coeff_def sin_coeff_def\n  by (simp del: mult_Suc)\n\nlemma cos_coeff_Suc: \"cos_coeff (Suc n) = - sin_coeff n / real (Suc n)\"\n  unfolding cos_coeff_def sin_coeff_def\n  by (simp del: mult_Suc) (auto elim: oddE)\n\nlemma summable_norm_sin: \"summable (\\<lambda>n. norm (sin_coeff n *\\<^sub>R x^n))\"\n  for x :: \"'a::{real_normed_algebra_1,banach}\"\n  unfolding sin_coeff_def\n  apply (rule summable_comparison_test [OF _ summable_norm_exp [where x=x]])\n  apply (auto simp: divide_inverse abs_mult power_abs [symmetric] zero_le_mult_iff)\n  done\n\nlemma summable_norm_cos: \"summable (\\<lambda>n. norm (cos_coeff n *\\<^sub>R x^n))\"\n  for x :: \"'a::{real_normed_algebra_1,banach}\"\n  unfolding cos_coeff_def\n  apply (rule summable_comparison_test [OF _ summable_norm_exp [where x=x]])\n  apply (auto simp: divide_inverse abs_mult power_abs [symmetric] zero_le_mult_iff)\n  done\n\nlemma sin_converges: \"(\\<lambda>n. sin_coeff n *\\<^sub>R x^n) sums sin x\"\n  unfolding sin_def\n  by (metis (full_types) summable_norm_cancel summable_norm_sin summable_sums)\n\nlemma cos_converges: \"(\\<lambda>n. cos_coeff n *\\<^sub>R x^n) sums cos x\"\n  unfolding cos_def\n  by (metis (full_types) summable_norm_cancel summable_norm_cos summable_sums)\n\nlemma sin_of_real: \"sin (of_real x) = of_real (sin x)\"\n  for x :: real\nproof -\n  have \"(\\<lambda>n. of_real (sin_coeff n *\\<^sub>R  x^n)) = (\\<lambda>n. sin_coeff n *\\<^sub>R  (of_real x)^n)\"\n  proof\n    show \"of_real (sin_coeff n *\\<^sub>R  x^n) = sin_coeff n *\\<^sub>R of_real x^n\" for n\n      by (simp add: scaleR_conv_of_real)\n  qed\n  also have \"\\<dots> sums (sin (of_real x))\"\n    by (rule sin_converges)\n  finally have \"(\\<lambda>n. of_real (sin_coeff n *\\<^sub>R x^n)) sums (sin (of_real x))\" .\n  then show ?thesis\n    using sums_unique2 sums_of_real [OF sin_converges]\n    by blast\nqed\n\ncorollary sin_in_Reals [simp]: \"z \\<in> \\<real> \\<Longrightarrow> sin z \\<in> \\<real>\"\n  by (metis Reals_cases Reals_of_real sin_of_real)\n\nlemma cos_of_real: \"cos (of_real x) = of_real (cos x)\"\n  for x :: real\nproof -\n  have \"(\\<lambda>n. of_real (cos_coeff n *\\<^sub>R  x^n)) = (\\<lambda>n. cos_coeff n *\\<^sub>R  (of_real x)^n)\"\n  proof\n    show \"of_real (cos_coeff n *\\<^sub>R  x^n) = cos_coeff n *\\<^sub>R of_real x^n\" for n\n      by (simp add: scaleR_conv_of_real)\n  qed\n  also have \"\\<dots> sums (cos (of_real x))\"\n    by (rule cos_converges)\n  finally have \"(\\<lambda>n. of_real (cos_coeff n *\\<^sub>R x^n)) sums (cos (of_real x))\" .\n  then show ?thesis\n    using sums_unique2 sums_of_real [OF cos_converges]\n    by blast\nqed\n\ncorollary cos_in_Reals [simp]: \"z \\<in> \\<real> \\<Longrightarrow> cos z \\<in> \\<real>\"\n  by (metis Reals_cases Reals_of_real cos_of_real)\n\nlemma diffs_sin_coeff: \"diffs sin_coeff = cos_coeff\"\n  by (simp add: diffs_def sin_coeff_Suc del: of_nat_Suc)\n\nlemma diffs_cos_coeff: \"diffs cos_coeff = (\\<lambda>n. - sin_coeff n)\"\n  by (simp add: diffs_def cos_coeff_Suc del: of_nat_Suc)\n\ntext \\<open>Now at last we can get the derivatives of exp, sin and cos.\\<close>\n\nlemma DERIV_sin [simp]: \"DERIV sin x :> cos x\"\n  for x :: \"'a::{real_normed_field,banach}\"\n  unfolding sin_def cos_def scaleR_conv_of_real\n  apply (rule DERIV_cong)\n   apply (rule termdiffs [where K=\"of_real (norm x) + 1 :: 'a\"])\n      apply (simp_all add: norm_less_p1 diffs_of_real diffs_sin_coeff diffs_cos_coeff\n              summable_minus_iff scaleR_conv_of_real [symmetric]\n              summable_norm_sin [THEN summable_norm_cancel]\n              summable_norm_cos [THEN summable_norm_cancel])\n  done\n\ndeclare DERIV_sin[THEN DERIV_chain2, derivative_intros]\n  and DERIV_sin[THEN DERIV_chain2, unfolded has_field_derivative_def, derivative_intros]\n\nlemma DERIV_cos [simp]: \"DERIV cos x :> - sin x\"\n  for x :: \"'a::{real_normed_field,banach}\"\n  unfolding sin_def cos_def scaleR_conv_of_real\n  apply (rule DERIV_cong)\n   apply (rule termdiffs [where K=\"of_real (norm x) + 1 :: 'a\"])\n      apply (simp_all add: norm_less_p1 diffs_of_real diffs_minus suminf_minus\n              diffs_sin_coeff diffs_cos_coeff\n              summable_minus_iff scaleR_conv_of_real [symmetric]\n              summable_norm_sin [THEN summable_norm_cancel]\n              summable_norm_cos [THEN summable_norm_cancel])\n  done\n\ndeclare DERIV_cos[THEN DERIV_chain2, derivative_intros]\n  and DERIV_cos[THEN DERIV_chain2, unfolded has_field_derivative_def, derivative_intros]\n\nlemma isCont_sin: \"isCont sin x\"\n  for x :: \"'a::{real_normed_field,banach}\"\n  by (rule DERIV_sin [THEN DERIV_isCont])\n\nlemma isCont_cos: \"isCont cos x\"\n  for x :: \"'a::{real_normed_field,banach}\"\n  by (rule DERIV_cos [THEN DERIV_isCont])\n\nlemma isCont_sin' [simp]: \"isCont f a \\<Longrightarrow> isCont (\\<lambda>x. sin (f x)) a\"\n  for f :: \"_ \\<Rightarrow> 'a::{real_normed_field,banach}\"\n  by (rule isCont_o2 [OF _ isCont_sin])\n\n(* FIXME a context for f would be better *)\n\nlemma isCont_cos' [simp]: \"isCont f a \\<Longrightarrow> isCont (\\<lambda>x. cos (f x)) a\"\n  for f :: \"_ \\<Rightarrow> 'a::{real_normed_field,banach}\"\n  by (rule isCont_o2 [OF _ isCont_cos])\n\nlemma tendsto_sin [tendsto_intros]: \"(f \\<longlongrightarrow> a) F \\<Longrightarrow> ((\\<lambda>x. sin (f x)) \\<longlongrightarrow> sin a) F\"\n  for f :: \"_ \\<Rightarrow> 'a::{real_normed_field,banach}\"\n  by (rule isCont_tendsto_compose [OF isCont_sin])\n\nlemma tendsto_cos [tendsto_intros]: \"(f \\<longlongrightarrow> a) F \\<Longrightarrow> ((\\<lambda>x. cos (f x)) \\<longlongrightarrow> cos a) F\"\n  for f :: \"_ \\<Rightarrow> 'a::{real_normed_field,banach}\"\n  by (rule isCont_tendsto_compose [OF isCont_cos])\n\nlemma continuous_sin [continuous_intros]: \"continuous F f \\<Longrightarrow> continuous F (\\<lambda>x. sin (f x))\"\n  for f :: \"_ \\<Rightarrow> 'a::{real_normed_field,banach}\"\n  unfolding continuous_def by (rule tendsto_sin)\n\nlemma continuous_on_sin [continuous_intros]: \"continuous_on s f \\<Longrightarrow> continuous_on s (\\<lambda>x. sin (f x))\"\n  for f :: \"_ \\<Rightarrow> 'a::{real_normed_field,banach}\"\n  unfolding continuous_on_def by (auto intro: tendsto_sin)\n\nlemma continuous_within_sin: \"continuous (at z within s) sin\"\n  for z :: \"'a::{real_normed_field,banach}\"\n  by (simp add: continuous_within tendsto_sin)\n\nlemma continuous_cos [continuous_intros]: \"continuous F f \\<Longrightarrow> continuous F (\\<lambda>x. cos (f x))\"\n  for f :: \"_ \\<Rightarrow> 'a::{real_normed_field,banach}\"\n  unfolding continuous_def by (rule tendsto_cos)\n\nlemma continuous_on_cos [continuous_intros]: \"continuous_on s f \\<Longrightarrow> continuous_on s (\\<lambda>x. cos (f x))\"\n  for f :: \"_ \\<Rightarrow> 'a::{real_normed_field,banach}\"\n  unfolding continuous_on_def by (auto intro: tendsto_cos)\n\nlemma continuous_within_cos: \"continuous (at z within s) cos\"\n  for z :: \"'a::{real_normed_field,banach}\"\n  by (simp add: continuous_within tendsto_cos)\n\n\nsubsection \\<open>Properties of Sine and Cosine\\<close>\n\nlemma sin_zero [simp]: \"sin 0 = 0\"\n  by (simp add: sin_def sin_coeff_def scaleR_conv_of_real)\n\nlemma cos_zero [simp]: \"cos 0 = 1\"\n  by (simp add: cos_def cos_coeff_def scaleR_conv_of_real)\n\nlemma DERIV_fun_sin: \"DERIV g x :> m \\<Longrightarrow> DERIV (\\<lambda>x. sin (g x)) x :> cos (g x) * m\"\n  by (auto intro!: derivative_intros)\n\nlemma DERIV_fun_cos: \"DERIV g x :> m \\<Longrightarrow> DERIV (\\<lambda>x. cos(g x)) x :> - sin (g x) * m\"\n  by (auto intro!: derivative_eq_intros)\n\n\nsubsection \\<open>Deriving the Addition Formulas\\<close>\n\ntext \\<open>The product of two cosine series.\\<close>\nlemma cos_x_cos_y:\n  fixes x :: \"'a::{real_normed_field,banach}\"\n  shows\n    \"(\\<lambda>p. \\<Sum>n\\<le>p.\n        if even p \\<and> even n\n        then ((-1) ^ (p div 2) * (p choose n) / (fact p)) *\\<^sub>R (x^n) * y^(p-n) else 0)\n      sums (cos x * cos y)\"\nproof -\n  have \"(cos_coeff n * cos_coeff (p - n)) *\\<^sub>R (x^n * y^(p - n)) =\n    (if even p \\<and> even n then ((-1) ^ (p div 2) * (p choose n) / (fact p)) *\\<^sub>R (x^n) * y^(p - n)\n     else 0)\"\n    if \"n \\<le> p\" for n p :: nat\n  proof -\n    from that have *: \"even n \\<Longrightarrow> even p \\<Longrightarrow>\n        (-1) ^ (n div 2) * (-1) ^ ((p - n) div 2) = (-1 :: real) ^ (p div 2)\"\n      by (metis div_add power_add le_add_diff_inverse odd_add)\n    with that show ?thesis\n      by (auto simp: algebra_simps cos_coeff_def binomial_fact)\n  qed\n  then have \"(\\<lambda>p. \\<Sum>n\\<le>p. if even p \\<and> even n\n                  then ((-1) ^ (p div 2) * (p choose n) / (fact p)) *\\<^sub>R (x^n) * y^(p-n) else 0) =\n             (\\<lambda>p. \\<Sum>n\\<le>p. (cos_coeff n * cos_coeff (p - n)) *\\<^sub>R (x^n * y^(p-n)))\"\n    by simp\n  also have \"\\<dots> = (\\<lambda>p. \\<Sum>n\\<le>p. (cos_coeff n *\\<^sub>R x^n) * (cos_coeff (p - n) *\\<^sub>R y^(p-n)))\"\n    by (simp add: algebra_simps)\n  also have \"\\<dots> sums (cos x * cos y)\"\n    using summable_norm_cos\n    by (auto simp: cos_def scaleR_conv_of_real intro!: Cauchy_product_sums)\n  finally show ?thesis .\nqed\n\ntext \\<open>The product of two sine series.\\<close>\nlemma sin_x_sin_y:\n  fixes x :: \"'a::{real_normed_field,banach}\"\n  shows\n    \"(\\<lambda>p. \\<Sum>n\\<le>p.\n        if even p \\<and> odd n\n        then - ((-1) ^ (p div 2) * (p choose n) / (fact p)) *\\<^sub>R (x^n) * y^(p-n)\n        else 0)\n      sums (sin x * sin y)\"\nproof -\n  have \"(sin_coeff n * sin_coeff (p - n)) *\\<^sub>R (x^n * y^(p-n)) =\n    (if even p \\<and> odd n\n     then -((-1) ^ (p div 2) * (p choose n) / (fact p)) *\\<^sub>R (x^n) * y^(p-n)\n     else 0)\"\n    if \"n \\<le> p\" for n p :: nat\n  proof -\n    have \"(-1) ^ ((n - Suc 0) div 2) * (-1) ^ ((p - Suc n) div 2) = - ((-1 :: real) ^ (p div 2))\"\n      if np: \"odd n\" \"even p\"\n    proof -\n      from \\<open>n \\<le> p\\<close> np have *: \"n - Suc 0 + (p - Suc n) = p - Suc (Suc 0)\" \"Suc (Suc 0) \\<le> p\"\n        by arith+\n      have \"(p - Suc (Suc 0)) div 2 = p div 2 - Suc 0\"\n        by simp\n      with \\<open>n \\<le> p\\<close> np * show ?thesis\n        apply (simp add: power_add [symmetric] div_add [symmetric] del: div_add)\n        apply (metis (no_types) One_nat_def Suc_1 le_div_geq minus_minus\n            mult.left_neutral mult_minus_left power.simps(2) zero_less_Suc)\n        done\n    qed\n    then show ?thesis\n      using \\<open>n\\<le>p\\<close> by (auto simp: algebra_simps sin_coeff_def binomial_fact)\n  qed\n  then have \"(\\<lambda>p. \\<Sum>n\\<le>p. if even p \\<and> odd n\n               then - ((-1) ^ (p div 2) * (p choose n) / (fact p)) *\\<^sub>R (x^n) * y^(p-n) else 0) =\n             (\\<lambda>p. \\<Sum>n\\<le>p. (sin_coeff n * sin_coeff (p - n)) *\\<^sub>R (x^n * y^(p-n)))\"\n    by simp\n  also have \"\\<dots> = (\\<lambda>p. \\<Sum>n\\<le>p. (sin_coeff n *\\<^sub>R x^n) * (sin_coeff (p - n) *\\<^sub>R y^(p-n)))\"\n    by (simp add: algebra_simps)\n  also have \"\\<dots> sums (sin x * sin y)\"\n    using summable_norm_sin\n    by (auto simp: sin_def scaleR_conv_of_real intro!: Cauchy_product_sums)\n  finally show ?thesis .\nqed\n\nlemma sums_cos_x_plus_y:\n  fixes x :: \"'a::{real_normed_field,banach}\"\n  shows\n    \"(\\<lambda>p. \\<Sum>n\\<le>p.\n        if even p\n        then ((-1) ^ (p div 2) * (p choose n) / (fact p)) *\\<^sub>R (x^n) * y^(p-n)\n        else 0)\n      sums cos (x + y)\"\nproof -\n  have\n    \"(\\<Sum>n\\<le>p.\n      if even p then ((-1) ^ (p div 2) * (p choose n) / (fact p)) *\\<^sub>R (x^n) * y^(p-n)\n      else 0) = cos_coeff p *\\<^sub>R ((x + y) ^ p)\"\n    for p :: nat\n  proof -\n    have\n      \"(\\<Sum>n\\<le>p. if even p then ((-1) ^ (p div 2) * (p choose n) / (fact p)) *\\<^sub>R (x^n) * y^(p-n) else 0) =\n       (if even p then \\<Sum>n\\<le>p. ((-1) ^ (p div 2) * (p choose n) / (fact p)) *\\<^sub>R (x^n) * y^(p-n) else 0)\"\n      by simp\n    also have \"\\<dots> =\n       (if even p\n        then of_real ((-1) ^ (p div 2) / (fact p)) * (\\<Sum>n\\<le>p. (p choose n) *\\<^sub>R (x^n) * y^(p-n))\n        else 0)\"\n      by (auto simp: sum_distrib_left field_simps scaleR_conv_of_real nonzero_of_real_divide)\n    also have \"\\<dots> = cos_coeff p *\\<^sub>R ((x + y) ^ p)\"\n      by (simp add: cos_coeff_def binomial_ring [of x y]  scaleR_conv_of_real atLeast0AtMost)\n    finally show ?thesis .\n  qed\n  then have\n    \"(\\<lambda>p. \\<Sum>n\\<le>p.\n        if even p\n        then ((-1) ^ (p div 2) * (p choose n) / (fact p)) *\\<^sub>R (x^n) * y^(p-n)\n        else 0) = (\\<lambda>p. cos_coeff p *\\<^sub>R ((x+y)^p))\"\n    by simp\n   also have \"\\<dots> sums cos (x + y)\"\n    by (rule cos_converges)\n   finally show ?thesis .\nqed\n\ntheorem cos_add:\n  fixes x :: \"'a::{real_normed_field,banach}\"\n  shows \"cos (x + y) = cos x * cos y - sin x * sin y\"\nproof -\n  have\n    \"(if even p \\<and> even n\n      then ((- 1) ^ (p div 2) * int (p choose n) / (fact p)) *\\<^sub>R (x^n) * y^(p-n) else 0) -\n     (if even p \\<and> odd n\n      then - ((- 1) ^ (p div 2) * int (p choose n) / (fact p)) *\\<^sub>R (x^n) * y^(p-n) else 0) =\n     (if even p then ((-1) ^ (p div 2) * (p choose n) / (fact p)) *\\<^sub>R (x^n) * y^(p-n) else 0)\"\n    if \"n \\<le> p\" for n p :: nat\n    by simp\n  then have\n    \"(\\<lambda>p. \\<Sum>n\\<le>p. (if even p then ((-1) ^ (p div 2) * (p choose n) / (fact p)) *\\<^sub>R (x^n) * y^(p-n) else 0))\n      sums (cos x * cos y - sin x * sin y)\"\n    using sums_diff [OF cos_x_cos_y [of x y] sin_x_sin_y [of x y]]\n    by (simp add: sum_subtractf [symmetric])\n  then show ?thesis\n    by (blast intro: sums_cos_x_plus_y sums_unique2)\nqed\n\nlemma sin_minus_converges: \"(\\<lambda>n. - (sin_coeff n *\\<^sub>R (-x)^n)) sums sin x\"\nproof -\n  have [simp]: \"\\<And>n. - (sin_coeff n *\\<^sub>R (-x)^n) = (sin_coeff n *\\<^sub>R x^n)\"\n    by (auto simp: sin_coeff_def elim!: oddE)\n  show ?thesis\n    by (simp add: sin_def summable_norm_sin [THEN summable_norm_cancel, THEN summable_sums])\nqed\n\nlemma sin_minus [simp]: \"sin (- x) = - sin x\"\n  for x :: \"'a::{real_normed_algebra_1,banach}\"\n  using sin_minus_converges [of x]\n  by (auto simp: sin_def summable_norm_sin [THEN summable_norm_cancel]\n      suminf_minus sums_iff equation_minus_iff)\n\nlemma cos_minus_converges: \"(\\<lambda>n. (cos_coeff n *\\<^sub>R (-x)^n)) sums cos x\"\nproof -\n  have [simp]: \"\\<And>n. (cos_coeff n *\\<^sub>R (-x)^n) = (cos_coeff n *\\<^sub>R x^n)\"\n    by (auto simp: Transcendental.cos_coeff_def elim!: evenE)\n  show ?thesis\n    by (simp add: cos_def summable_norm_cos [THEN summable_norm_cancel, THEN summable_sums])\nqed\n\nlemma cos_minus [simp]: \"cos (-x) = cos x\"\n  for x :: \"'a::{real_normed_algebra_1,banach}\"\n  using cos_minus_converges [of x]\n  by (simp add: cos_def summable_norm_cos [THEN summable_norm_cancel]\n      suminf_minus sums_iff equation_minus_iff)\n\nlemma sin_cos_squared_add [simp]: \"(sin x)\\<^sup>2 + (cos x)\\<^sup>2 = 1\"\n  for x :: \"'a::{real_normed_field,banach}\"\n  using cos_add [of x \"-x\"]\n  by (simp add: power2_eq_square algebra_simps)\n\nlemma sin_cos_squared_add2 [simp]: \"(cos x)\\<^sup>2 + (sin x)\\<^sup>2 = 1\"\n  for x :: \"'a::{real_normed_field,banach}\"\n  by (subst add.commute, rule sin_cos_squared_add)\n\nlemma sin_cos_squared_add3 [simp]: \"cos x * cos x + sin x * sin x = 1\"\n  for x :: \"'a::{real_normed_field,banach}\"\n  using sin_cos_squared_add2 [unfolded power2_eq_square] .\n\nlemma sin_squared_eq: \"(sin x)\\<^sup>2 = 1 - (cos x)\\<^sup>2\"\n  for x :: \"'a::{real_normed_field,banach}\"\n  unfolding eq_diff_eq by (rule sin_cos_squared_add)\n\nlemma cos_squared_eq: \"(cos x)\\<^sup>2 = 1 - (sin x)\\<^sup>2\"\n  for x :: \"'a::{real_normed_field,banach}\"\n  unfolding eq_diff_eq by (rule sin_cos_squared_add2)\n\nlemma abs_sin_le_one [simp]: \"\\<bar>sin x\\<bar> \\<le> 1\"\n  for x :: real\n  by (rule power2_le_imp_le) (simp_all add: sin_squared_eq)\n\nlemma sin_ge_minus_one [simp]: \"- 1 \\<le> sin x\"\n  for x :: real\n  using abs_sin_le_one [of x] by (simp add: abs_le_iff)\n\nlemma sin_le_one [simp]: \"sin x \\<le> 1\"\n  for x :: real\n  using abs_sin_le_one [of x] by (simp add: abs_le_iff)\n\nlemma abs_cos_le_one [simp]: \"\\<bar>cos x\\<bar> \\<le> 1\"\n  for x :: real\n  by (rule power2_le_imp_le) (simp_all add: cos_squared_eq)\n\nlemma cos_ge_minus_one [simp]: \"- 1 \\<le> cos x\"\n  for x :: real\n  using abs_cos_le_one [of x] by (simp add: abs_le_iff)\n\nlemma cos_le_one [simp]: \"cos x \\<le> 1\"\n  for x :: real\n  using abs_cos_le_one [of x] by (simp add: abs_le_iff)\n\nlemma cos_diff: \"cos (x - y) = cos x * cos y + sin x * sin y\"\n  for x :: \"'a::{real_normed_field,banach}\"\n  using cos_add [of x \"- y\"] by simp\n\nlemma cos_double: \"cos(2*x) = (cos x)\\<^sup>2 - (sin x)\\<^sup>2\"\n  for x :: \"'a::{real_normed_field,banach}\"\n  using cos_add [where x=x and y=x] by (simp add: power2_eq_square)\n\nlemma sin_cos_le1: \"\\<bar>sin x * sin y + cos x * cos y\\<bar> \\<le> 1\"\n  for x :: real\n  using cos_diff [of x y] by (metis abs_cos_le_one add.commute)\n\nlemma DERIV_fun_pow: \"DERIV g x :> m \\<Longrightarrow> DERIV (\\<lambda>x. (g x) ^ n) x :> real n * (g x) ^ (n - 1) * m\"\n  by (auto intro!: derivative_eq_intros simp:)\n\nlemma DERIV_fun_exp: \"DERIV g x :> m \\<Longrightarrow> DERIV (\\<lambda>x. exp (g x)) x :> exp (g x) * m\"\n  by (auto intro!: derivative_intros)\n\n\nsubsection \\<open>The Constant Pi\\<close>\n\ndefinition pi :: real\n  where \"pi = 2 * (THE x. 0 \\<le> x \\<and> x \\<le> 2 \\<and> cos x = 0)\"\n\ntext \\<open>Show that there's a least positive @{term x} with @{term \"cos x = 0\"};\n   hence define pi.\\<close>\n\nlemma sin_paired: \"(\\<lambda>n. (- 1) ^ n / (fact (2 * n + 1)) * x ^ (2 * n + 1)) sums  sin x\"\n  for x :: real\nproof -\n  have \"(\\<lambda>n. \\<Sum>k = n*2..<n * 2 + 2. sin_coeff k * x ^ k) sums sin x\"\n    by (rule sums_group) (use sin_converges [of x, unfolded scaleR_conv_of_real] in auto)\n  then show ?thesis\n    by (simp add: sin_coeff_def ac_simps)\nqed\n\nlemma sin_gt_zero_02:\n  fixes x :: real\n  assumes \"0 < x\" and \"x < 2\"\n  shows \"0 < sin x\"\nproof -\n  let ?f = \"\\<lambda>n::nat. \\<Sum>k = n*2..<n*2+2. (- 1) ^ k / (fact (2*k+1)) * x^(2*k+1)\"\n  have pos: \"\\<forall>n. 0 < ?f n\"\n  proof\n    fix n :: nat\n    let ?k2 = \"real (Suc (Suc (4 * n)))\"\n    let ?k3 = \"real (Suc (Suc (Suc (4 * n))))\"\n    have \"x * x < ?k2 * ?k3\"\n      using assms by (intro mult_strict_mono', simp_all)\n    then have \"x * x * x * x ^ (n * 4) < ?k2 * ?k3 * x * x ^ (n * 4)\"\n      by (intro mult_strict_right_mono zero_less_power \\<open>0 < x\\<close>)\n    then show \"0 < ?f n\"\n      by (simp add: divide_simps mult_ac del: mult_Suc)\nqed\n  have sums: \"?f sums sin x\"\n    by (rule sin_paired [THEN sums_group]) simp\n  show \"0 < sin x\"\n    unfolding sums_unique [OF sums]\n    using sums_summable [OF sums] pos\n    by (rule suminf_pos)\nqed\n\nlemma cos_double_less_one: \"0 < x \\<Longrightarrow> x < 2 \\<Longrightarrow> cos (2 * x) < 1\"\n  for x :: real\n  using sin_gt_zero_02 [where x = x] by (auto simp: cos_squared_eq cos_double)\n\nlemma cos_paired: \"(\\<lambda>n. (- 1) ^ n / (fact (2 * n)) * x ^ (2 * n)) sums cos x\"\n  for x :: real\nproof -\n  have \"(\\<lambda>n. \\<Sum>k = n * 2..<n * 2 + 2. cos_coeff k * x ^ k) sums cos x\"\n    by (rule sums_group) (use cos_converges [of x, unfolded scaleR_conv_of_real] in auto)\n  then show ?thesis\n    by (simp add: cos_coeff_def ac_simps)\nqed\n\nlemmas realpow_num_eq_if = power_eq_if\n\nlemma sumr_pos_lt_pair:\n  fixes f :: \"nat \\<Rightarrow> real\"\n  shows \"summable f \\<Longrightarrow>\n    (\\<And>d. 0 < f (k + (Suc(Suc 0) * d)) + f (k + ((Suc (Suc 0) * d) + 1))) \\<Longrightarrow>\n    sum f {..<k} < suminf f\"\n  apply (simp only: One_nat_def)\n  apply (subst suminf_split_initial_segment [where k=k])\n   apply assumption\n  apply simp\n  apply (drule_tac k=k in summable_ignore_initial_segment)\n  apply (drule_tac k=\"Suc (Suc 0)\" in sums_group [OF summable_sums])\n   apply simp\n  apply simp\n  apply (metis (no_types, lifting) add.commute suminf_pos summable_def sums_unique)\n  done\n\nlemma cos_two_less_zero [simp]: \"cos 2 < (0::real)\"\nproof -\n  note fact_Suc [simp del]\n  from sums_minus [OF cos_paired]\n  have *: \"(\\<lambda>n. - ((- 1) ^ n * 2 ^ (2 * n) / fact (2 * n))) sums - cos (2::real)\"\n    by simp\n  then have sm: \"summable (\\<lambda>n. - ((- 1::real) ^ n * 2 ^ (2 * n) / (fact (2 * n))))\"\n    by (rule sums_summable)\n  have \"0 < (\\<Sum>n<Suc (Suc (Suc 0)). - ((- 1::real) ^ n * 2 ^ (2 * n) / (fact (2 * n))))\"\n    by (simp add: fact_num_eq_if realpow_num_eq_if)\n  moreover have \"(\\<Sum>n<Suc (Suc (Suc 0)). - ((- 1::real) ^ n  * 2 ^ (2 * n) / (fact (2 * n)))) <\n    (\\<Sum>n. - ((- 1) ^ n * 2 ^ (2 * n) / (fact (2 * n))))\"\n  proof -\n    {\n      fix d\n      let ?six4d = \"Suc (Suc (Suc (Suc (Suc (Suc (4 * d))))))\"\n      have \"(4::real) * (fact (?six4d)) < (Suc (Suc (?six4d)) * fact (Suc (?six4d)))\"\n        unfolding of_nat_mult by (rule mult_strict_mono) (simp_all add: fact_less_mono)\n      then have \"(4::real) * (fact (?six4d)) < (fact (Suc (Suc (?six4d))))\"\n        by (simp only: fact_Suc [of \"Suc (?six4d)\"] of_nat_mult of_nat_fact)\n      then have \"(4::real) * inverse (fact (Suc (Suc (?six4d)))) < inverse (fact (?six4d))\"\n        by (simp add: inverse_eq_divide less_divide_eq)\n    }\n    then show ?thesis\n      by (force intro!: sumr_pos_lt_pair [OF sm] simp add: divide_inverse algebra_simps)\n  qed\n  ultimately have \"0 < (\\<Sum>n. - ((- 1::real) ^ n * 2 ^ (2 * n) / (fact (2 * n))))\"\n    by (rule order_less_trans)\n  moreover from * have \"- cos 2 = (\\<Sum>n. - ((- 1::real) ^ n * 2 ^ (2 * n) / (fact (2 * n))))\"\n    by (rule sums_unique)\n  ultimately have \"(0::real) < - cos 2\" by simp\n  then show ?thesis by simp\nqed\n\nlemmas cos_two_neq_zero [simp] = cos_two_less_zero [THEN less_imp_neq]\nlemmas cos_two_le_zero [simp] = cos_two_less_zero [THEN order_less_imp_le]\n\nlemma cos_is_zero: \"\\<exists>!x::real. 0 \\<le> x \\<and> x \\<le> 2 \\<and> cos x = 0\"\nproof (rule ex_ex1I)\n  show \"\\<exists>x::real. 0 \\<le> x \\<and> x \\<le> 2 \\<and> cos x = 0\"\n    by (rule IVT2) simp_all\nnext\n  fix x y :: real\n  assume x: \"0 \\<le> x \\<and> x \\<le> 2 \\<and> cos x = 0\"\n  assume y: \"0 \\<le> y \\<and> y \\<le> 2 \\<and> cos y = 0\"\n  have [simp]: \"\\<forall>x::real. cos differentiable (at x)\"\n    unfolding real_differentiable_def by (auto intro: DERIV_cos)\n  from x y less_linear [of x y] show \"x = y\"\n    apply auto\n     apply (drule_tac f = cos in Rolle)\n        apply (drule_tac [5] f = cos in Rolle)\n           apply (auto dest!: DERIV_cos [THEN DERIV_unique])\n     apply (metis order_less_le_trans less_le sin_gt_zero_02)\n    apply (metis order_less_le_trans less_le sin_gt_zero_02)\n    done\nqed\n\nlemma pi_half: \"pi/2 = (THE x. 0 \\<le> x \\<and> x \\<le> 2 \\<and> cos x = 0)\"\n  by (simp add: pi_def)\n\nlemma cos_pi_half [simp]: \"cos (pi / 2) = 0\"\n  by (simp add: pi_half cos_is_zero [THEN theI'])\n\nlemma cos_of_real_pi_half [simp]: \"cos ((of_real pi / 2) :: 'a) = 0\"\n  if \"SORT_CONSTRAINT('a::{real_field,banach,real_normed_algebra_1})\"\n  by (metis cos_pi_half cos_of_real eq_numeral_simps(4)\n      nonzero_of_real_divide of_real_0 of_real_numeral)\n\nlemma pi_half_gt_zero [simp]: \"0 < pi / 2\"\n  apply (rule order_le_neq_trans)\n   apply (simp add: pi_half cos_is_zero [THEN theI'])\n  apply (metis cos_pi_half cos_zero zero_neq_one)\n  done\n\nlemmas pi_half_neq_zero [simp] = pi_half_gt_zero [THEN less_imp_neq, symmetric]\nlemmas pi_half_ge_zero [simp] = pi_half_gt_zero [THEN order_less_imp_le]\n\nlemma pi_half_less_two [simp]: \"pi / 2 < 2\"\n  apply (rule order_le_neq_trans)\n   apply (simp add: pi_half cos_is_zero [THEN theI'])\n  apply (metis cos_pi_half cos_two_neq_zero)\n  done\n\nlemmas pi_half_neq_two [simp] = pi_half_less_two [THEN less_imp_neq]\nlemmas pi_half_le_two [simp] =  pi_half_less_two [THEN order_less_imp_le]\n\nlemma pi_gt_zero [simp]: \"0 < pi\"\n  using pi_half_gt_zero by simp\n\nlemma pi_ge_zero [simp]: \"0 \\<le> pi\"\n  by (rule pi_gt_zero [THEN order_less_imp_le])\n\nlemma pi_neq_zero [simp]: \"pi \\<noteq> 0\"\n  by (rule pi_gt_zero [THEN less_imp_neq, symmetric])\n\nlemma pi_not_less_zero [simp]: \"\\<not> pi < 0\"\n  by (simp add: linorder_not_less)\n\nlemma minus_pi_half_less_zero: \"-(pi/2) < 0\"\n  by simp\n\nlemma m2pi_less_pi: \"- (2*pi) < pi\"\n  by simp\n\nlemma sin_pi_half [simp]: \"sin(pi/2) = 1\"\n  using sin_cos_squared_add2 [where x = \"pi/2\"]\n  using sin_gt_zero_02 [OF pi_half_gt_zero pi_half_less_two]\n  by (simp add: power2_eq_1_iff)\n\nlemma sin_of_real_pi_half [simp]: \"sin ((of_real pi / 2) :: 'a) = 1\"\n  if \"SORT_CONSTRAINT('a::{real_field,banach,real_normed_algebra_1})\"\n  using sin_pi_half\n  by (metis sin_pi_half eq_numeral_simps(4) nonzero_of_real_divide of_real_1 of_real_numeral sin_of_real)\n\nlemma sin_cos_eq: \"sin x = cos (of_real pi / 2 - x)\"\n  for x :: \"'a::{real_normed_field,banach}\"\n  by (simp add: cos_diff)\n\nlemma minus_sin_cos_eq: \"- sin x = cos (x + of_real pi / 2)\"\n  for x :: \"'a::{real_normed_field,banach}\"\n  by (simp add: cos_add nonzero_of_real_divide)\n\nlemma cos_sin_eq: \"cos x = sin (of_real pi / 2 - x)\"\n  for x :: \"'a::{real_normed_field,banach}\"\n  using sin_cos_eq [of \"of_real pi / 2 - x\"] by simp\n\nlemma sin_add: \"sin (x + y) = sin x * cos y + cos x * sin y\"\n  for x :: \"'a::{real_normed_field,banach}\"\n  using cos_add [of \"of_real pi / 2 - x\" \"-y\"]\n  by (simp add: cos_sin_eq) (simp add: sin_cos_eq)\n\nlemma sin_diff: \"sin (x - y) = sin x * cos y - cos x * sin y\"\n  for x :: \"'a::{real_normed_field,banach}\"\n  using sin_add [of x \"- y\"] by simp\n\nlemma sin_double: \"sin(2 * x) = 2 * sin x * cos x\"\n  for x :: \"'a::{real_normed_field,banach}\"\n  using sin_add [where x=x and y=x] by simp\n\nlemma cos_of_real_pi [simp]: \"cos (of_real pi) = -1\"\n  using cos_add [where x = \"pi/2\" and y = \"pi/2\"]\n  by (simp add: cos_of_real)\n\nlemma sin_of_real_pi [simp]: \"sin (of_real pi) = 0\"\n  using sin_add [where x = \"pi/2\" and y = \"pi/2\"]\n  by (simp add: sin_of_real)\n\nlemma cos_pi [simp]: \"cos pi = -1\"\n  using cos_add [where x = \"pi/2\" and y = \"pi/2\"] by simp\n\nlemma sin_pi [simp]: \"sin pi = 0\"\n  using sin_add [where x = \"pi/2\" and y = \"pi/2\"] by simp\n\nlemma sin_periodic_pi [simp]: \"sin (x + pi) = - sin x\"\n  by (simp add: sin_add)\n\nlemma sin_periodic_pi2 [simp]: \"sin (pi + x) = - sin x\"\n  by (simp add: sin_add)\n\nlemma cos_periodic_pi [simp]: \"cos (x + pi) = - cos x\"\n  by (simp add: cos_add)\n\nlemma cos_periodic_pi2 [simp]: \"cos (pi + x) = - cos x\"\n  by (simp add: cos_add)\n\nlemma sin_periodic [simp]: \"sin (x + 2 * pi) = sin x\"\n  by (simp add: sin_add sin_double cos_double)\n\nlemma cos_periodic [simp]: \"cos (x + 2 * pi) = cos x\"\n  by (simp add: cos_add sin_double cos_double)\n\nlemma cos_npi [simp]: \"cos (real n * pi) = (- 1) ^ n\"\n  by (induct n) (auto simp: distrib_right)\n\nlemma cos_npi2 [simp]: \"cos (pi * real n) = (- 1) ^ n\"\n  by (metis cos_npi mult.commute)\n\nlemma sin_npi [simp]: \"sin (real n * pi) = 0\"\n  for n :: nat\n  by (induct n) (auto simp: distrib_right)\n\nlemma sin_npi2 [simp]: \"sin (pi * real n) = 0\"\n  for n :: nat\n  by (simp add: mult.commute [of pi])\n\nlemma cos_two_pi [simp]: \"cos (2 * pi) = 1\"\n  by (simp add: cos_double)\n\nlemma sin_two_pi [simp]: \"sin (2 * pi) = 0\"\n  by (simp add: sin_double)\n\nlemma sin_times_sin: \"sin w * sin z = (cos (w - z) - cos (w + z)) / 2\"\n  for w :: \"'a::{real_normed_field,banach}\"\n  by (simp add: cos_diff cos_add)\n\nlemma sin_times_cos: \"sin w * cos z = (sin (w + z) + sin (w - z)) / 2\"\n  for w :: \"'a::{real_normed_field,banach}\"\n  by (simp add: sin_diff sin_add)\n\nlemma cos_times_sin: \"cos w * sin z = (sin (w + z) - sin (w - z)) / 2\"\n  for w :: \"'a::{real_normed_field,banach}\"\n  by (simp add: sin_diff sin_add)\n\nlemma cos_times_cos: \"cos w * cos z = (cos (w - z) + cos (w + z)) / 2\"\n  for w :: \"'a::{real_normed_field,banach}\"\n  by (simp add: cos_diff cos_add)\n\nlemma sin_plus_sin: \"sin w + sin z = 2 * sin ((w + z) / 2) * cos ((w - z) / 2)\"\n  for w :: \"'a::{real_normed_field,banach,field}\"  (* FIXME field should not be necessary *)\n  apply (simp add: mult.assoc sin_times_cos)\n  apply (simp add: field_simps)\n  done\n\nlemma sin_diff_sin: \"sin w - sin z = 2 * sin ((w - z) / 2) * cos ((w + z) / 2)\"\n  for w :: \"'a::{real_normed_field,banach,field}\"\n  apply (simp add: mult.assoc sin_times_cos)\n  apply (simp add: field_simps)\n  done\n\nlemma cos_plus_cos: \"cos w + cos z = 2 * cos ((w + z) / 2) * cos ((w - z) / 2)\"\n  for w :: \"'a::{real_normed_field,banach,field}\"\n  apply (simp add: mult.assoc cos_times_cos)\n  apply (simp add: field_simps)\n  done\n\nlemma cos_diff_cos: \"cos w - cos z = 2 * sin ((w + z) / 2) * sin ((z - w) / 2)\"\n  for w :: \"'a::{real_normed_field,banach,field}\"\n  apply (simp add: mult.assoc sin_times_sin)\n  apply (simp add: field_simps)\n  done\n\nlemma cos_double_cos: \"cos (2 * z) = 2 * cos z ^ 2 - 1\"\n  for z :: \"'a::{real_normed_field,banach}\"\n  by (simp add: cos_double sin_squared_eq)\n\nlemma cos_double_sin: \"cos (2 * z) = 1 - 2 * sin z ^ 2\"\n  for z :: \"'a::{real_normed_field,banach}\"\n  by (simp add: cos_double sin_squared_eq)\n\nlemma sin_pi_minus [simp]: \"sin (pi - x) = sin x\"\n  by (metis sin_minus sin_periodic_pi minus_minus uminus_add_conv_diff)\n\nlemma cos_pi_minus [simp]: \"cos (pi - x) = - (cos x)\"\n  by (metis cos_minus cos_periodic_pi uminus_add_conv_diff)\n\nlemma sin_minus_pi [simp]: \"sin (x - pi) = - (sin x)\"\n  by (simp add: sin_diff)\n\nlemma cos_minus_pi [simp]: \"cos (x - pi) = - (cos x)\"\n  by (simp add: cos_diff)\n\nlemma sin_2pi_minus [simp]: \"sin (2 * pi - x) = - (sin x)\"\n  by (metis sin_periodic_pi2 add_diff_eq mult_2 sin_pi_minus)\n\nlemma cos_2pi_minus [simp]: \"cos (2 * pi - x) = cos x\"\n  by (metis (no_types, hide_lams) cos_add cos_minus cos_two_pi sin_minus sin_two_pi\n      diff_0_right minus_diff_eq mult_1 mult_zero_left uminus_add_conv_diff)\n\nlemma sin_gt_zero2: \"0 < x \\<Longrightarrow> x < pi/2 \\<Longrightarrow> 0 < sin x\"\n  by (metis sin_gt_zero_02 order_less_trans pi_half_less_two)\n\nlemma sin_less_zero:\n  assumes \"- pi/2 < x\" and \"x < 0\"\n  shows \"sin x < 0\"\nproof -\n  have \"0 < sin (- x)\"\n    using assms by (simp only: sin_gt_zero2)\n  then show ?thesis by simp\nqed\n\nlemma pi_less_4: \"pi < 4\"\n  using pi_half_less_two by auto\n\nlemma cos_gt_zero: \"0 < x \\<Longrightarrow> x < pi/2 \\<Longrightarrow> 0 < cos x\"\n  by (simp add: cos_sin_eq sin_gt_zero2)\n\nlemma cos_gt_zero_pi: \"-(pi/2) < x \\<Longrightarrow> x < pi/2 \\<Longrightarrow> 0 < cos x\"\n  using cos_gt_zero [of x] cos_gt_zero [of \"-x\"]\n  by (cases rule: linorder_cases [of x 0]) auto\n\nlemma cos_ge_zero: \"-(pi/2) \\<le> x \\<Longrightarrow> x \\<le> pi/2 \\<Longrightarrow> 0 \\<le> cos x\"\n  by (auto simp: order_le_less cos_gt_zero_pi)\n    (metis cos_pi_half eq_divide_eq eq_numeral_simps(4))\n\nlemma sin_gt_zero: \"0 < x \\<Longrightarrow> x < pi \\<Longrightarrow> 0 < sin x\"\n  by (simp add: sin_cos_eq cos_gt_zero_pi)\n\nlemma sin_lt_zero: \"pi < x \\<Longrightarrow> x < 2 * pi \\<Longrightarrow> sin x < 0\"\n  using sin_gt_zero [of \"x - pi\"]\n  by (simp add: sin_diff)\n\nlemma pi_ge_two: \"2 \\<le> pi\"\nproof (rule ccontr)\n  assume \"\\<not> ?thesis\"\n  then have \"pi < 2\" by auto\n  have \"\\<exists>y > pi. y < 2 \\<and> y < 2 * pi\"\n  proof (cases \"2 < 2 * pi\")\n    case True\n    with dense[OF \\<open>pi < 2\\<close>] show ?thesis by auto\n  next\n    case False\n    have \"pi < 2 * pi\" by auto\n    from dense[OF this] and False show ?thesis by auto\n  qed\n  then obtain y where \"pi < y\" and \"y < 2\" and \"y < 2 * pi\"\n    by blast\n  then have \"0 < sin y\"\n    using sin_gt_zero_02 by auto\n  moreover have \"sin y < 0\"\n    using sin_gt_zero[of \"y - pi\"] \\<open>pi < y\\<close> and \\<open>y < 2 * pi\\<close> sin_periodic_pi[of \"y - pi\"]\n    by auto\n  ultimately show False by auto\nqed\n\nlemma sin_ge_zero: \"0 \\<le> x \\<Longrightarrow> x \\<le> pi \\<Longrightarrow> 0 \\<le> sin x\"\n  by (auto simp: order_le_less sin_gt_zero)\n\nlemma sin_le_zero: \"pi \\<le> x \\<Longrightarrow> x < 2 * pi \\<Longrightarrow> sin x \\<le> 0\"\n  using sin_ge_zero [of \"x - pi\"] by (simp add: sin_diff)\n\nlemma sin_pi_divide_n_ge_0 [simp]:\n  assumes \"n \\<noteq> 0\"\n  shows \"0 \\<le> sin (pi / real n)\"\n  by (rule sin_ge_zero) (use assms in \\<open>simp_all add: divide_simps\\<close>)\n\nlemma sin_pi_divide_n_gt_0:\n  assumes \"2 \\<le> n\"\n  shows \"0 < sin (pi / real n)\"\n  by (rule sin_gt_zero) (use assms in \\<open>simp_all add: divide_simps\\<close>)\n\n(* FIXME: This proof is almost identical to lemma \\<open>cos_is_zero\\<close>.\n   It should be possible to factor out some of the common parts. *)\nlemma cos_total:\n  assumes y: \"- 1 \\<le> y\" \"y \\<le> 1\"\n  shows \"\\<exists>!x. 0 \\<le> x \\<and> x \\<le> pi \\<and> cos x = y\"\nproof (rule ex_ex1I)\n  show \"\\<exists>x. 0 \\<le> x \\<and> x \\<le> pi \\<and> cos x = y\"\n    by (rule IVT2) (simp_all add: y)\nnext\n  fix a b\n  assume a: \"0 \\<le> a \\<and> a \\<le> pi \\<and> cos a = y\"\n  assume b: \"0 \\<le> b \\<and> b \\<le> pi \\<and> cos b = y\"\n  have [simp]: \"\\<forall>x::real. cos differentiable (at x)\"\n    unfolding real_differentiable_def by (auto intro: DERIV_cos)\n  from a b less_linear [of a b] show \"a = b\"\n    apply auto\n     apply (drule_tac f = cos in Rolle)\n        apply (drule_tac [5] f = cos in Rolle)\n           apply (auto dest!: DERIV_cos [THEN DERIV_unique])\n     apply (metis order_less_le_trans less_le sin_gt_zero)\n    apply (metis order_less_le_trans less_le sin_gt_zero)\n    done\nqed\n\nlemma sin_total:\n  assumes y: \"-1 \\<le> y\" \"y \\<le> 1\"\n  shows \"\\<exists>!x. - (pi/2) \\<le> x \\<and> x \\<le> pi/2 \\<and> sin x = y\"\nproof -\n  from cos_total [OF y]\n  obtain x where x: \"0 \\<le> x\" \"x \\<le> pi\" \"cos x = y\"\n    and uniq: \"\\<And>x'. 0 \\<le> x' \\<Longrightarrow> x' \\<le> pi \\<Longrightarrow> cos x' = y \\<Longrightarrow> x' = x \"\n    by blast\n  show ?thesis\n    apply (simp add: sin_cos_eq)\n    apply (rule ex1I [where a=\"pi/2 - x\"])\n     apply (cut_tac [2] x'=\"pi/2 - xa\" in uniq)\n    using x\n        apply auto\n    done\nqed\n\nlemma cos_zero_lemma:\n  assumes \"0 \\<le> x\" \"cos x = 0\"\n  shows \"\\<exists>n. odd n \\<and> x = of_nat n * (pi/2) \\<and> n > 0\"\nproof -\n  have xle: \"x < (1 + real_of_int \\<lfloor>x/pi\\<rfloor>) * pi\"\n    using floor_correct [of \"x/pi\"]\n    by (simp add: add.commute divide_less_eq)\n  obtain n where \"real n * pi \\<le> x\" \"x < real (Suc n) * pi\"\n    apply (rule that [of \"nat \\<lfloor>x/pi\\<rfloor>\"])\n    using assms\n     apply (simp_all add: xle)\n    apply (metis floor_less_iff less_irrefl mult_imp_div_pos_less not_le pi_gt_zero)\n    done\n  then have x: \"0 \\<le> x - n * pi\" \"(x - n * pi) \\<le> pi\" \"cos (x - n * pi) = 0\"\n    by (auto simp: algebra_simps cos_diff assms)\n  then have \"\\<exists>!x. 0 \\<le> x \\<and> x \\<le> pi \\<and> cos x = 0\"\n    by (auto simp: intro!: cos_total)\n  then obtain \\<theta> where \\<theta>: \"0 \\<le> \\<theta>\" \"\\<theta> \\<le> pi\" \"cos \\<theta> = 0\"\n    and uniq: \"\\<And>\\<phi>. 0 \\<le> \\<phi> \\<Longrightarrow> \\<phi> \\<le> pi \\<Longrightarrow> cos \\<phi> = 0 \\<Longrightarrow> \\<phi> = \\<theta>\"\n    by blast\n  then have \"x - real n * pi = \\<theta>\"\n    using x by blast\n  moreover have \"pi/2 = \\<theta>\"\n    using pi_half_ge_zero uniq by fastforce\n  ultimately show ?thesis\n    by (rule_tac x = \"Suc (2 * n)\" in exI) (simp add: algebra_simps)\nqed\n\nlemma sin_zero_lemma: \"0 \\<le> x \\<Longrightarrow> sin x = 0 \\<Longrightarrow> \\<exists>n::nat. even n \\<and> x = real n * (pi/2)\"\n  using cos_zero_lemma [of \"x + pi/2\"]\n  apply (clarsimp simp add: cos_add)\n  apply (rule_tac x = \"n - 1\" in exI)\n  apply (simp add: algebra_simps of_nat_diff)\n  done\n\nlemma cos_zero_iff:\n  \"cos x = 0 \\<longleftrightarrow> ((\\<exists>n. odd n \\<and> x = real n * (pi/2)) \\<or> (\\<exists>n. odd n \\<and> x = - (real n * (pi/2))))\"\n  (is \"?lhs = ?rhs\")\nproof -\n  have *: \"cos (real n * pi / 2) = 0\" if \"odd n\" for n :: nat\n  proof -\n    from that obtain m where \"n = 2 * m + 1\" ..\n    then show ?thesis\n      by (simp add: field_simps) (simp add: cos_add add_divide_distrib)\n  qed\n  show ?thesis\n  proof\n    show ?rhs if ?lhs\n      using that cos_zero_lemma [of x] cos_zero_lemma [of \"-x\"] by force\n    show ?lhs if ?rhs\n      using that by (auto dest: * simp del: eq_divide_eq_numeral1)\n  qed\nqed\n\nlemma sin_zero_iff:\n  \"sin x = 0 \\<longleftrightarrow> ((\\<exists>n. even n \\<and> x = real n * (pi/2)) \\<or> (\\<exists>n. even n \\<and> x = - (real n * (pi/2))))\"\n  (is \"?lhs = ?rhs\")\nproof\n  show ?rhs if ?lhs\n    using that sin_zero_lemma [of x] sin_zero_lemma [of \"-x\"] by force\n  show ?lhs if ?rhs\n    using that by (auto elim: evenE)\nqed\n\nlemma cos_zero_iff_int: \"cos x = 0 \\<longleftrightarrow> (\\<exists>n. odd n \\<and> x = of_int n * (pi/2))\"\nproof safe\n  assume \"cos x = 0\"\n  then show \"\\<exists>n. odd n \\<and> x = of_int n * (pi/2)\"\n    apply (simp add: cos_zero_iff)\n    apply safe\n     apply (metis even_int_iff of_int_of_nat_eq)\n    apply (rule_tac x=\"- (int n)\" in exI)\n    apply simp\n    done\nnext\n  fix n :: int\n  assume \"odd n\"\n  then show \"cos (of_int n * (pi / 2)) = 0\"\n    apply (simp add: cos_zero_iff)\n    apply (cases n rule: int_cases2)\n     apply simp_all\n    done\nqed\n\nlemma sin_zero_iff_int: \"sin x = 0 \\<longleftrightarrow> (\\<exists>n. even n \\<and> x = of_int n * (pi/2))\"\nproof safe\n  assume \"sin x = 0\"\n  then show \"\\<exists>n. even n \\<and> x = of_int n * (pi / 2)\"\n    apply (simp add: sin_zero_iff)\n    apply safe\n     apply (metis even_int_iff of_int_of_nat_eq)\n    apply (rule_tac x=\"- (int n)\" in exI)\n    apply simp\n    done\nnext\n  fix n :: int\n  assume \"even n\"\n  then show \"sin (of_int n * (pi / 2)) = 0\"\n    apply (simp add: sin_zero_iff)\n    apply (cases n rule: int_cases2)\n     apply simp_all\n    done\nqed\n\nlemma sin_zero_iff_int2: \"sin x = 0 \\<longleftrightarrow> (\\<exists>n::int. x = of_int n * pi)\"\n  apply (simp only: sin_zero_iff_int)\n  apply (safe elim!: evenE)\n   apply (simp_all add: field_simps)\n  using dvd_triv_left apply fastforce\n  done\n\nlemma cos_monotone_0_pi:\n  assumes \"0 \\<le> y\" and \"y < x\" and \"x \\<le> pi\"\n  shows \"cos x < cos y\"\nproof -\n  have \"- (x - y) < 0\" using assms by auto\n  from MVT2[OF \\<open>y < x\\<close> DERIV_cos[THEN impI, THEN allI]]\n  obtain z where \"y < z\" and \"z < x\" and cos_diff: \"cos x - cos y = (x - y) * - sin z\"\n    by auto\n  then have \"0 < z\" and \"z < pi\"\n    using assms by auto\n  then have \"0 < sin z\"\n    using sin_gt_zero by auto\n  then have \"cos x - cos y < 0\"\n    unfolding cos_diff minus_mult_commute[symmetric]\n    using \\<open>- (x - y) < 0\\<close> by (rule mult_pos_neg2)\n  then show ?thesis by auto\nqed\n\nlemma cos_monotone_0_pi_le:\n  assumes \"0 \\<le> y\" and \"y \\<le> x\" and \"x \\<le> pi\"\n  shows \"cos x \\<le> cos y\"\nproof (cases \"y < x\")\n  case True\n  show ?thesis\n    using cos_monotone_0_pi[OF \\<open>0 \\<le> y\\<close> True \\<open>x \\<le> pi\\<close>] by auto\nnext\n  case False\n  then have \"y = x\" using \\<open>y \\<le> x\\<close> by auto\n  then show ?thesis by auto\nqed\n\nlemma cos_monotone_minus_pi_0:\n  assumes \"- pi \\<le> y\" and \"y < x\" and \"x \\<le> 0\"\n  shows \"cos y < cos x\"\nproof -\n  have \"0 \\<le> - x\" and \"- x < - y\" and \"- y \\<le> pi\"\n    using assms by auto\n  from cos_monotone_0_pi[OF this] show ?thesis\n    unfolding cos_minus .\nqed\n\nlemma cos_monotone_minus_pi_0':\n  assumes \"- pi \\<le> y\" and \"y \\<le> x\" and \"x \\<le> 0\"\n  shows \"cos y \\<le> cos x\"\nproof (cases \"y < x\")\n  case True\n  show ?thesis using cos_monotone_minus_pi_0[OF \\<open>-pi \\<le> y\\<close> True \\<open>x \\<le> 0\\<close>]\n    by auto\nnext\n  case False\n  then have \"y = x\" using \\<open>y \\<le> x\\<close> by auto\n  then show ?thesis by auto\nqed\n\nlemma sin_monotone_2pi:\n  assumes \"- (pi/2) \\<le> y\" and \"y < x\" and \"x \\<le> pi/2\"\n  shows \"sin y < sin x\"\n  apply (simp add: sin_cos_eq)\n  apply (rule cos_monotone_0_pi)\n  using assms\n    apply auto\n  done\n\nlemma sin_monotone_2pi_le:\n  assumes \"- (pi / 2) \\<le> y\" and \"y \\<le> x\" and \"x \\<le> pi / 2\"\n  shows \"sin y \\<le> sin x\"\n  by (metis assms le_less sin_monotone_2pi)\n\nlemma sin_x_le_x:\n  fixes x :: real\n  assumes x: \"x \\<ge> 0\"\n  shows \"sin x \\<le> x\"\nproof -\n  let ?f = \"\\<lambda>x. x - sin x\"\n  from x have \"?f x \\<ge> ?f 0\"\n    apply (rule DERIV_nonneg_imp_nondecreasing)\n    apply (intro allI impI exI[of _ \"1 - cos x\" for x])\n    apply (auto intro!: derivative_eq_intros simp: field_simps)\n    done\n  then show \"sin x \\<le> x\" by simp\nqed\n\nlemma sin_x_ge_neg_x:\n  fixes x :: real\n  assumes x: \"x \\<ge> 0\"\n  shows \"sin x \\<ge> - x\"\nproof -\n  let ?f = \"\\<lambda>x. x + sin x\"\n  from x have \"?f x \\<ge> ?f 0\"\n    apply (rule DERIV_nonneg_imp_nondecreasing)\n    apply (intro allI impI exI[of _ \"1 + cos x\" for x])\n    apply (auto intro!: derivative_eq_intros simp: field_simps real_0_le_add_iff)\n    done\n  then show \"sin x \\<ge> -x\" by simp\nqed\n\nlemma abs_sin_x_le_abs_x: \"\\<bar>sin x\\<bar> \\<le> \\<bar>x\\<bar>\"\n  for x :: real\n  using sin_x_ge_neg_x [of x] sin_x_le_x [of x] sin_x_ge_neg_x [of \"-x\"] sin_x_le_x [of \"-x\"]\n  by (auto simp: abs_real_def)\n\n\nsubsection \\<open>More Corollaries about Sine and Cosine\\<close>\n\nlemma sin_cos_npi [simp]: \"sin (real (Suc (2 * n)) * pi / 2) = (-1) ^ n\"\nproof -\n  have \"sin ((real n + 1/2) * pi) = cos (real n * pi)\"\n    by (auto simp: algebra_simps sin_add)\n  then show ?thesis\n    by (simp add: distrib_right add_divide_distrib add.commute mult.commute [of pi])\nqed\n\nlemma cos_2npi [simp]: \"cos (2 * real n * pi) = 1\"\n  for n :: nat\n  by (cases \"even n\") (simp_all add: cos_double mult.assoc)\n\nlemma cos_3over2_pi [simp]: \"cos (3/2*pi) = 0\"\n  apply (subgoal_tac \"cos (pi + pi/2) = 0\")\n   apply simp\n  apply (subst cos_add)\n  apply simp\n  done\n\nlemma sin_2npi [simp]: \"sin (2 * real n * pi) = 0\"\n  for n :: nat\n  by (auto simp: mult.assoc sin_double)\n\nlemma sin_3over2_pi [simp]: \"sin (3/2*pi) = - 1\"\n  apply (subgoal_tac \"sin (pi + pi/2) = - 1\")\n   apply simp\n  apply (subst sin_add)\n  apply simp\n  done\n\nlemma cos_pi_eq_zero [simp]: \"cos (pi * real (Suc (2 * m)) / 2) = 0\"\n  by (simp only: cos_add sin_add of_nat_Suc distrib_right distrib_left add_divide_distrib, auto)\n\nlemma DERIV_cos_add [simp]: \"DERIV (\\<lambda>x. cos (x + k)) xa :> - sin (xa + k)\"\n  by (auto intro!: derivative_eq_intros)\n\nlemma sin_zero_norm_cos_one:\n  fixes x :: \"'a::{real_normed_field,banach}\"\n  assumes \"sin x = 0\"\n  shows \"norm (cos x) = 1\"\n  using sin_cos_squared_add [of x, unfolded assms]\n  by (simp add: square_norm_one)\n\nlemma sin_zero_abs_cos_one: \"sin x = 0 \\<Longrightarrow> \\<bar>cos x\\<bar> = (1::real)\"\n  using sin_zero_norm_cos_one by fastforce\n\nlemma cos_one_sin_zero:\n  fixes x :: \"'a::{real_normed_field,banach}\"\n  assumes \"cos x = 1\"\n  shows \"sin x = 0\"\n  using sin_cos_squared_add [of x, unfolded assms]\n  by simp\n\nlemma sin_times_pi_eq_0: \"sin (x * pi) = 0 \\<longleftrightarrow> x \\<in> \\<int>\"\n  by (simp add: sin_zero_iff_int2) (metis Ints_cases Ints_of_int)\n\nlemma cos_one_2pi: \"cos x = 1 \\<longleftrightarrow> (\\<exists>n::nat. x = n * 2 * pi) | (\\<exists>n::nat. x = - (n * 2 * pi))\"\n  (is \"?lhs = ?rhs\")\nproof\n  assume ?lhs\n  then have \"sin x = 0\"\n    by (simp add: cos_one_sin_zero)\n  then show ?rhs\n  proof (simp only: sin_zero_iff, elim exE disjE conjE)\n    fix n :: nat\n    assume n: \"even n\" \"x = real n * (pi/2)\"\n    then obtain m where m: \"n = 2 * m\"\n      using dvdE by blast\n    then have me: \"even m\" using \\<open>?lhs\\<close> n\n      by (auto simp: field_simps) (metis one_neq_neg_one  power_minus_odd power_one)\n    show ?rhs\n      using m me n\n      by (auto simp: field_simps elim!: evenE)\n  next\n    fix n :: nat\n    assume n: \"even n\" \"x = - (real n * (pi/2))\"\n    then obtain m where m: \"n = 2 * m\"\n      using dvdE by blast\n    then have me: \"even m\" using \\<open>?lhs\\<close> n\n      by (auto simp: field_simps) (metis one_neq_neg_one  power_minus_odd power_one)\n    show ?rhs\n      using m me n\n      by (auto simp: field_simps elim!: evenE)\n  qed\nnext\n  assume ?rhs\n  then show \"cos x = 1\"\n    by (metis cos_2npi cos_minus mult.assoc mult.left_commute)\nqed\n\nlemma cos_one_2pi_int: \"cos x = 1 \\<longleftrightarrow> (\\<exists>n::int. x = n * 2 * pi)\"\n  apply auto  (* FIXME simproc bug? *)\n   apply (auto simp: cos_one_2pi)\n    apply (metis of_int_of_nat_eq)\n   apply (metis mult_minus_right of_int_minus of_int_of_nat_eq)\n  apply (metis mult_minus_right of_int_of_nat)\n  done\n\nlemma sin_cos_sqrt: \"0 \\<le> sin x \\<Longrightarrow> sin x = sqrt (1 - (cos(x) ^ 2))\"\n  using sin_squared_eq real_sqrt_unique by fastforce\n\nlemma sin_eq_0_pi: \"- pi < x \\<Longrightarrow> x < pi \\<Longrightarrow> sin x = 0 \\<Longrightarrow> x = 0\"\n  by (metis sin_gt_zero sin_minus minus_less_iff neg_0_less_iff_less not_less_iff_gr_or_eq)\n\nlemma cos_treble_cos: \"cos (3 * x) = 4 * cos x ^ 3 - 3 * cos x\"\n  for x :: \"'a::{real_normed_field,banach}\"\nproof -\n  have *: \"(sin x * (sin x * 3)) = 3 - (cos x * (cos x * 3))\"\n    by (simp add: mult.assoc [symmetric] sin_squared_eq [unfolded power2_eq_square])\n  have \"cos(3 * x) = cos(2*x + x)\"\n    by simp\n  also have \"\\<dots> = 4 * cos x ^ 3 - 3 * cos x\"\n    apply (simp only: cos_add cos_double sin_double)\n    apply (simp add: * field_simps power2_eq_square power3_eq_cube)\n    done\n  finally show ?thesis .\nqed\n\nlemma cos_45: \"cos (pi / 4) = sqrt 2 / 2\"\nproof -\n  let ?c = \"cos (pi / 4)\"\n  let ?s = \"sin (pi / 4)\"\n  have nonneg: \"0 \\<le> ?c\"\n    by (simp add: cos_ge_zero)\n  have \"0 = cos (pi / 4 + pi / 4)\"\n    by simp\n  also have \"cos (pi / 4 + pi / 4) = ?c\\<^sup>2 - ?s\\<^sup>2\"\n    by (simp only: cos_add power2_eq_square)\n  also have \"\\<dots> = 2 * ?c\\<^sup>2 - 1\"\n    by (simp add: sin_squared_eq)\n  finally have \"?c\\<^sup>2 = (sqrt 2 / 2)\\<^sup>2\"\n    by (simp add: power_divide)\n  then show ?thesis\n    using nonneg by (rule power2_eq_imp_eq) simp\nqed\n\nlemma cos_30: \"cos (pi / 6) = sqrt 3/2\"\nproof -\n  let ?c = \"cos (pi / 6)\"\n  let ?s = \"sin (pi / 6)\"\n  have pos_c: \"0 < ?c\"\n    by (rule cos_gt_zero) simp_all\n  have \"0 = cos (pi / 6 + pi / 6 + pi / 6)\"\n    by simp\n  also have \"\\<dots> = (?c * ?c - ?s * ?s) * ?c - (?s * ?c + ?c * ?s) * ?s\"\n    by (simp only: cos_add sin_add)\n  also have \"\\<dots> = ?c * (?c\\<^sup>2 - 3 * ?s\\<^sup>2)\"\n    by (simp add: algebra_simps power2_eq_square)\n  finally have \"?c\\<^sup>2 = (sqrt 3/2)\\<^sup>2\"\n    using pos_c by (simp add: sin_squared_eq power_divide)\n  then show ?thesis\n    using pos_c [THEN order_less_imp_le]\n    by (rule power2_eq_imp_eq) simp\nqed\n\nlemma sin_45: \"sin (pi / 4) = sqrt 2 / 2\"\n  by (simp add: sin_cos_eq cos_45)\n\nlemma sin_60: \"sin (pi / 3) = sqrt 3/2\"\n  by (simp add: sin_cos_eq cos_30)\n\nlemma cos_60: \"cos (pi / 3) = 1 / 2\"\n  apply (rule power2_eq_imp_eq)\n    apply (simp add: cos_squared_eq sin_60 power_divide)\n   apply (rule cos_ge_zero)\n    apply (rule order_trans [where y=0])\n     apply simp_all\n  done\n\nlemma sin_30: \"sin (pi / 6) = 1 / 2\"\n  by (simp add: sin_cos_eq cos_60)\n\nlemma cos_integer_2pi: \"n \\<in> \\<int> \\<Longrightarrow> cos(2 * pi * n) = 1\"\n  by (metis Ints_cases cos_one_2pi_int mult.assoc mult.commute)\n\nlemma sin_integer_2pi: \"n \\<in> \\<int> \\<Longrightarrow> sin(2 * pi * n) = 0\"\n  by (metis sin_two_pi Ints_mult mult.assoc mult.commute sin_times_pi_eq_0)\n\nlemma cos_int_2npi [simp]: \"cos (2 * of_int n * pi) = 1\"\n  for n :: int\n  by (simp add: cos_one_2pi_int)\n\nlemma sin_int_2npi [simp]: \"sin (2 * of_int n * pi) = 0\"\n  for n :: int\n  by (metis Ints_of_int mult.assoc mult.commute sin_integer_2pi)\n\nlemma sincos_principal_value: \"\\<exists>y. (- pi < y \\<and> y \\<le> pi) \\<and> (sin y = sin x \\<and> cos y = cos x)\"\n  apply (rule exI [where x=\"pi - (2 * pi) * frac ((pi - x) / (2 * pi))\"])\n  apply (auto simp: field_simps frac_lt_1)\n   apply (simp_all add: frac_def divide_simps)\n   apply (simp_all add: add_divide_distrib diff_divide_distrib)\n   apply (simp_all add: sin_diff cos_diff mult.assoc [symmetric] cos_integer_2pi sin_integer_2pi)\n  done\n\n\nsubsection \\<open>Tangent\\<close>\n\ndefinition tan :: \"'a \\<Rightarrow> 'a::{real_normed_field,banach}\"\n  where \"tan = (\\<lambda>x. sin x / cos x)\"\n\nlemma tan_of_real: \"of_real (tan x) = (tan (of_real x) :: 'a::{real_normed_field,banach})\"\n  by (simp add: tan_def sin_of_real cos_of_real)\n\nlemma tan_in_Reals [simp]: \"z \\<in> \\<real> \\<Longrightarrow> tan z \\<in> \\<real>\"\n  for z :: \"'a::{real_normed_field,banach}\"\n  by (simp add: tan_def)\n\nlemma tan_zero [simp]: \"tan 0 = 0\"\n  by (simp add: tan_def)\n\nlemma tan_pi [simp]: \"tan pi = 0\"\n  by (simp add: tan_def)\n\nlemma tan_npi [simp]: \"tan (real n * pi) = 0\"\n  for n :: nat\n  by (simp add: tan_def)\n\nlemma tan_minus [simp]: \"tan (- x) = - tan x\"\n  by (simp add: tan_def)\n\nlemma tan_periodic [simp]: \"tan (x + 2 * pi) = tan x\"\n  by (simp add: tan_def)\n\nlemma lemma_tan_add1: \"cos x \\<noteq> 0 \\<Longrightarrow> cos y \\<noteq> 0 \\<Longrightarrow> 1 - tan x * tan y = cos (x + y)/(cos x * cos y)\"\n  by (simp add: tan_def cos_add field_simps)\n\nlemma add_tan_eq: \"cos x \\<noteq> 0 \\<Longrightarrow> cos y \\<noteq> 0 \\<Longrightarrow> tan x + tan y = sin(x + y)/(cos x * cos y)\"\n  for x :: \"'a::{real_normed_field,banach}\"\n  by (simp add: tan_def sin_add field_simps)\n\nlemma tan_add:\n  \"cos x \\<noteq> 0 \\<Longrightarrow> cos y \\<noteq> 0 \\<Longrightarrow> cos (x + y) \\<noteq> 0 \\<Longrightarrow> tan (x + y) = (tan x + tan y)/(1 - tan x * tan y)\"\n  for x :: \"'a::{real_normed_field,banach}\"\n  by (simp add: add_tan_eq lemma_tan_add1 field_simps) (simp add: tan_def)\n\nlemma tan_double: \"cos x \\<noteq> 0 \\<Longrightarrow> cos (2 * x) \\<noteq> 0 \\<Longrightarrow> tan (2 * x) = (2 * tan x) / (1 - (tan x)\\<^sup>2)\"\n  for x :: \"'a::{real_normed_field,banach}\"\n  using tan_add [of x x] by (simp add: power2_eq_square)\n\nlemma tan_gt_zero: \"0 < x \\<Longrightarrow> x < pi/2 \\<Longrightarrow> 0 < tan x\"\n  by (simp add: tan_def zero_less_divide_iff sin_gt_zero2 cos_gt_zero_pi)\n\nlemma tan_less_zero:\n  assumes \"- pi/2 < x\" and \"x < 0\"\n  shows \"tan x < 0\"\nproof -\n  have \"0 < tan (- x)\"\n    using assms by (simp only: tan_gt_zero)\n  then show ?thesis by simp\nqed\n\nlemma tan_half: \"tan x = sin (2 * x) / (cos (2 * x) + 1)\"\n  for x :: \"'a::{real_normed_field,banach,field}\"\n  unfolding tan_def sin_double cos_double sin_squared_eq\n  by (simp add: power2_eq_square)\n\nlemma tan_30: \"tan (pi / 6) = 1 / sqrt 3\"\n  unfolding tan_def by (simp add: sin_30 cos_30)\n\nlemma tan_45: \"tan (pi / 4) = 1\"\n  unfolding tan_def by (simp add: sin_45 cos_45)\n\nlemma tan_60: \"tan (pi / 3) = sqrt 3\"\n  unfolding tan_def by (simp add: sin_60 cos_60)\n\nlemma DERIV_tan [simp]: \"cos x \\<noteq> 0 \\<Longrightarrow> DERIV tan x :> inverse ((cos x)\\<^sup>2)\"\n  for x :: \"'a::{real_normed_field,banach}\"\n  unfolding tan_def\n  by (auto intro!: derivative_eq_intros, simp add: divide_inverse power2_eq_square)\n\nlemma isCont_tan: \"cos x \\<noteq> 0 \\<Longrightarrow> isCont tan x\"\n  for x :: \"'a::{real_normed_field,banach}\"\n  by (rule DERIV_tan [THEN DERIV_isCont])\n\nlemma isCont_tan' [simp,continuous_intros]:\n  fixes a :: \"'a::{real_normed_field,banach}\" and f :: \"'a \\<Rightarrow> 'a\"\n  shows \"isCont f a \\<Longrightarrow> cos (f a) \\<noteq> 0 \\<Longrightarrow> isCont (\\<lambda>x. tan (f x)) a\"\n  by (rule isCont_o2 [OF _ isCont_tan])\n\nlemma tendsto_tan [tendsto_intros]:\n  fixes f :: \"'a \\<Rightarrow> 'a::{real_normed_field,banach}\"\n  shows \"(f \\<longlongrightarrow> a) F \\<Longrightarrow> cos a \\<noteq> 0 \\<Longrightarrow> ((\\<lambda>x. tan (f x)) \\<longlongrightarrow> tan a) F\"\n  by (rule isCont_tendsto_compose [OF isCont_tan])\n\nlemma continuous_tan:\n  fixes f :: \"'a \\<Rightarrow> 'a::{real_normed_field,banach}\"\n  shows \"continuous F f \\<Longrightarrow> cos (f (Lim F (\\<lambda>x. x))) \\<noteq> 0 \\<Longrightarrow> continuous F (\\<lambda>x. tan (f x))\"\n  unfolding continuous_def by (rule tendsto_tan)\n\nlemma continuous_on_tan [continuous_intros]:\n  fixes f :: \"'a \\<Rightarrow> 'a::{real_normed_field,banach}\"\n  shows \"continuous_on s f \\<Longrightarrow> (\\<forall>x\\<in>s. cos (f x) \\<noteq> 0) \\<Longrightarrow> continuous_on s (\\<lambda>x. tan (f x))\"\n  unfolding continuous_on_def by (auto intro: tendsto_tan)\n\nlemma continuous_within_tan [continuous_intros]:\n  fixes f :: \"'a \\<Rightarrow> 'a::{real_normed_field,banach}\"\n  shows \"continuous (at x within s) f \\<Longrightarrow>\n    cos (f x) \\<noteq> 0 \\<Longrightarrow> continuous (at x within s) (\\<lambda>x. tan (f x))\"\n  unfolding continuous_within by (rule tendsto_tan)\n\nlemma LIM_cos_div_sin: \"(\\<lambda>x. cos(x)/sin(x)) \\<midarrow>pi/2\\<rightarrow> 0\"\n  by (rule LIM_cong_limit, (rule tendsto_intros)+, simp_all)\n\nlemma lemma_tan_total: \"0 < y \\<Longrightarrow> \\<exists>x. 0 < x \\<and> x < pi/2 \\<and> y < tan x\"\n  apply (insert LIM_cos_div_sin)\n  apply (simp only: LIM_eq)\n  apply (drule_tac x = \"inverse y\" in spec)\n  apply safe\n   apply force\n  apply (drule_tac ?d1.0 = s in pi_half_gt_zero [THEN [2] real_lbound_gt_zero])\n  apply safe\n  apply (rule_tac x = \"(pi/2) - e\" in exI)\n  apply (simp (no_asm_simp))\n  apply (drule_tac x = \"(pi/2) - e\" in spec)\n  apply (auto simp add: tan_def sin_diff cos_diff)\n  apply (rule inverse_less_iff_less [THEN iffD1])\n    apply (auto simp add: divide_inverse)\n   apply (rule mult_pos_pos)\n    apply (subgoal_tac [3] \"0 < sin e \\<and> 0 < cos e\")\n     apply (auto intro: cos_gt_zero sin_gt_zero2 simp: mult.commute)\n  done\n\nlemma tan_total_pos: \"0 \\<le> y \\<Longrightarrow> \\<exists>x. 0 \\<le> x \\<and> x < pi/2 \\<and> tan x = y\"\n  apply (frule order_le_imp_less_or_eq)\n  apply safe\n   prefer 2 apply force\n  apply (drule lemma_tan_total)\n  apply safe\n  apply (cut_tac f = tan and a = 0 and b = x and y = y in IVT_objl)\n  apply (auto intro!: DERIV_tan [THEN DERIV_isCont])\n  apply (drule_tac y = xa in order_le_imp_less_or_eq)\n  apply (auto dest: cos_gt_zero)\n  done\n\nlemma lemma_tan_total1: \"\\<exists>x. -(pi/2) < x \\<and> x < (pi/2) \\<and> tan x = y\"\n  apply (insert linorder_linear [of 0 y])\n  apply safe\n   apply (drule tan_total_pos)\n   apply (cut_tac [2] y=\"-y\" in tan_total_pos)\n    apply safe\n    apply (rule_tac [3] x = \"-x\" in exI)\n    apply (auto del: exI intro!: exI)\n  done\n\nlemma tan_total: \"\\<exists>! x. -(pi/2) < x \\<and> x < (pi/2) \\<and> tan x = y\"\n  apply (insert lemma_tan_total1 [where y = y])\n  apply auto\n  apply hypsubst_thin\n  apply (cut_tac x = xa and y = y in linorder_less_linear)\n  apply auto\n   apply (subgoal_tac [2] \"\\<exists>z. y < z \\<and> z < xa \\<and> DERIV tan z :> 0\")\n    apply (subgoal_tac \"\\<exists>z. xa < z \\<and> z < y \\<and> DERIV tan z :> 0\")\n     apply (rule_tac [4] Rolle)\n        apply (rule_tac [2] Rolle)\n           apply (auto del: exI intro!: DERIV_tan DERIV_isCont exI\n            simp add: real_differentiable_def)\n       apply (rule_tac [!] DERIV_tan asm_rl)\n       apply (auto dest!: DERIV_unique [OF _ DERIV_tan]\n        simp add: cos_gt_zero_pi [THEN less_imp_neq, THEN not_sym])\n  done\n\nlemma tan_monotone:\n  assumes \"- (pi / 2) < y\" and \"y < x\" and \"x < pi / 2\"\n  shows \"tan y < tan x\"\nproof -\n  have \"\\<forall>x'. y \\<le> x' \\<and> x' \\<le> x \\<longrightarrow> DERIV tan x' :> inverse ((cos x')\\<^sup>2)\"\n  proof (rule allI, rule impI)\n    fix x' :: real\n    assume \"y \\<le> x' \\<and> x' \\<le> x\"\n    then have \"-(pi/2) < x'\" and \"x' < pi/2\"\n      using assms by auto\n    from cos_gt_zero_pi[OF this]\n    have \"cos x' \\<noteq> 0\" by auto\n    then show \"DERIV tan x' :> inverse ((cos x')\\<^sup>2)\"\n      by (rule DERIV_tan)\n  qed\n  from MVT2[OF \\<open>y < x\\<close> this]\n  obtain z where \"y < z\" and \"z < x\"\n    and tan_diff: \"tan x - tan y = (x - y) * inverse ((cos z)\\<^sup>2)\" by auto\n  then have \"- (pi / 2) < z\" and \"z < pi / 2\"\n    using assms by auto\n  then have \"0 < cos z\"\n    using cos_gt_zero_pi by auto\n  then have inv_pos: \"0 < inverse ((cos z)\\<^sup>2)\"\n    by auto\n  have \"0 < x - y\" using \\<open>y < x\\<close> by auto\n  with inv_pos have \"0 < tan x - tan y\"\n    unfolding tan_diff by auto\n  then show ?thesis by auto\nqed\n\nlemma tan_monotone':\n  assumes \"- (pi / 2) < y\"\n    and \"y < pi / 2\"\n    and \"- (pi / 2) < x\"\n    and \"x < pi / 2\"\n  shows \"y < x \\<longleftrightarrow> tan y < tan x\"\nproof\n  assume \"y < x\"\n  then show \"tan y < tan x\"\n    using tan_monotone and \\<open>- (pi / 2) < y\\<close> and \\<open>x < pi / 2\\<close> by auto\nnext\n  assume \"tan y < tan x\"\n  show \"y < x\"\n  proof (rule ccontr)\n    assume \"\\<not> ?thesis\"\n    then have \"x \\<le> y\" by auto\n    then have \"tan x \\<le> tan y\"\n    proof (cases \"x = y\")\n      case True\n      then show ?thesis by auto\n    next\n      case False\n      then have \"x < y\" using \\<open>x \\<le> y\\<close> by auto\n      from tan_monotone[OF \\<open>- (pi/2) < x\\<close> this \\<open>y < pi / 2\\<close>] show ?thesis\n        by auto\n    qed\n    then show False\n      using \\<open>tan y < tan x\\<close> by auto\n  qed\nqed\n\nlemma tan_inverse: \"1 / (tan y) = tan (pi / 2 - y)\"\n  unfolding tan_def sin_cos_eq[of y] cos_sin_eq[of y] by auto\n\nlemma tan_periodic_pi[simp]: \"tan (x + pi) = tan x\"\n  by (simp add: tan_def)\n\nlemma tan_periodic_nat[simp]: \"tan (x + real n * pi) = tan x\"\n  for n :: nat\nproof (induct n arbitrary: x)\n  case 0\n  then show ?case by simp\nnext\n  case (Suc n)\n  have split_pi_off: \"x + real (Suc n) * pi = (x + real n * pi) + pi\"\n    unfolding Suc_eq_plus1 of_nat_add  distrib_right by auto\n  show ?case\n    unfolding split_pi_off using Suc by auto\nqed\n\nlemma tan_periodic_int[simp]: \"tan (x + of_int i * pi) = tan x\"\nproof (cases \"0 \\<le> i\")\n  case True\n  then have i_nat: \"of_int i = of_int (nat i)\" by auto\n  show ?thesis unfolding i_nat\n    by (metis of_int_of_nat_eq tan_periodic_nat)\nnext\n  case False\n  then have i_nat: \"of_int i = - of_int (nat (- i))\" by auto\n  have \"tan x = tan (x + of_int i * pi - of_int i * pi)\"\n    by auto\n  also have \"\\<dots> = tan (x + of_int i * pi)\"\n    unfolding i_nat mult_minus_left diff_minus_eq_add\n    by (metis of_int_of_nat_eq tan_periodic_nat)\n  finally show ?thesis by auto\nqed\n\nlemma tan_periodic_n[simp]: \"tan (x + numeral n * pi) = tan x\"\n  using tan_periodic_int[of _ \"numeral n\" ] by simp\n\nlemma tan_minus_45: \"tan (-(pi/4)) = -1\"\n  unfolding tan_def by (simp add: sin_45 cos_45)\n\nlemma tan_diff:\n  \"cos x \\<noteq> 0 \\<Longrightarrow> cos y \\<noteq> 0 \\<Longrightarrow> cos (x - y) \\<noteq> 0 \\<Longrightarrow> tan (x - y) = (tan x - tan y)/(1 + tan x * tan y)\"\n  for x :: \"'a::{real_normed_field,banach}\"\n  using tan_add [of x \"-y\"] by simp\n\nlemma tan_pos_pi2_le: \"0 \\<le> x \\<Longrightarrow> x < pi/2 \\<Longrightarrow> 0 \\<le> tan x\"\n  using less_eq_real_def tan_gt_zero by auto\n\nlemma cos_tan: \"\\<bar>x\\<bar> < pi/2 \\<Longrightarrow> cos x = 1 / sqrt (1 + tan x ^ 2)\"\n  using cos_gt_zero_pi [of x]\n  by (simp add: divide_simps tan_def real_sqrt_divide abs_if split: if_split_asm)\n\nlemma sin_tan: \"\\<bar>x\\<bar> < pi/2 \\<Longrightarrow> sin x = tan x / sqrt (1 + tan x ^ 2)\"\n  using cos_gt_zero [of \"x\"] cos_gt_zero [of \"-x\"]\n  by (force simp add: divide_simps tan_def real_sqrt_divide abs_if split: if_split_asm)\n\nlemma tan_mono_le: \"-(pi/2) < x \\<Longrightarrow> x \\<le> y \\<Longrightarrow> y < pi/2 \\<Longrightarrow> tan x \\<le> tan y\"\n  using less_eq_real_def tan_monotone by auto\n\nlemma tan_mono_lt_eq:\n  \"-(pi/2) < x \\<Longrightarrow> x < pi/2 \\<Longrightarrow> -(pi/2) < y \\<Longrightarrow> y < pi/2 \\<Longrightarrow> tan x < tan y \\<longleftrightarrow> x < y\"\n  using tan_monotone' by blast\n\nlemma tan_mono_le_eq:\n  \"-(pi/2) < x \\<Longrightarrow> x < pi/2 \\<Longrightarrow> -(pi/2) < y \\<Longrightarrow> y < pi/2 \\<Longrightarrow> tan x \\<le> tan y \\<longleftrightarrow> x \\<le> y\"\n  by (meson tan_mono_le not_le tan_monotone)\n\nlemma tan_bound_pi2: \"\\<bar>x\\<bar> < pi/4 \\<Longrightarrow> \\<bar>tan x\\<bar> < 1\"\n  using tan_45 tan_monotone [of x \"pi/4\"] tan_monotone [of \"-x\" \"pi/4\"]\n  by (auto simp: abs_if split: if_split_asm)\n\nlemma tan_cot: \"tan(pi/2 - x) = inverse(tan x)\"\n  by (simp add: tan_def sin_diff cos_diff)\n\n\nsubsection \\<open>Cotangent\\<close>\n\ndefinition cot :: \"'a \\<Rightarrow> 'a::{real_normed_field,banach}\"\n  where \"cot = (\\<lambda>x. cos x / sin x)\"\n\nlemma cot_of_real: \"of_real (cot x) = (cot (of_real x) :: 'a::{real_normed_field,banach})\"\n  by (simp add: cot_def sin_of_real cos_of_real)\n\nlemma cot_in_Reals [simp]: \"z \\<in> \\<real> \\<Longrightarrow> cot z \\<in> \\<real>\"\n  for z :: \"'a::{real_normed_field,banach}\"\n  by (simp add: cot_def)\n\nlemma cot_zero [simp]: \"cot 0 = 0\"\n  by (simp add: cot_def)\n\nlemma cot_pi [simp]: \"cot pi = 0\"\n  by (simp add: cot_def)\n\nlemma cot_npi [simp]: \"cot (real n * pi) = 0\"\n  for n :: nat\n  by (simp add: cot_def)\n\nlemma cot_minus [simp]: \"cot (- x) = - cot x\"\n  by (simp add: cot_def)\n\nlemma cot_periodic [simp]: \"cot (x + 2 * pi) = cot x\"\n  by (simp add: cot_def)\n\nlemma cot_altdef: \"cot x = inverse (tan x)\"\n  by (simp add: cot_def tan_def)\n\nlemma tan_altdef: \"tan x = inverse (cot x)\"\n  by (simp add: cot_def tan_def)\n\nlemma tan_cot': \"tan (pi/2 - x) = cot x\"\n  by (simp add: tan_cot cot_altdef)\n\nlemma cot_gt_zero: \"0 < x \\<Longrightarrow> x < pi/2 \\<Longrightarrow> 0 < cot x\"\n  by (simp add: cot_def zero_less_divide_iff sin_gt_zero2 cos_gt_zero_pi)\n\nlemma cot_less_zero:\n  assumes lb: \"- pi/2 < x\" and \"x < 0\"\n  shows \"cot x < 0\"\nproof -\n  have \"0 < cot (- x)\"\n    using assms by (simp only: cot_gt_zero)\n  then show ?thesis by simp\nqed\n\nlemma DERIV_cot [simp]: \"sin x \\<noteq> 0 \\<Longrightarrow> DERIV cot x :> -inverse ((sin x)\\<^sup>2)\"\n  for x :: \"'a::{real_normed_field,banach}\"\n  unfolding cot_def using cos_squared_eq[of x]\n  by (auto intro!: derivative_eq_intros) (simp add: divide_inverse power2_eq_square)\n\nlemma isCont_cot: \"sin x \\<noteq> 0 \\<Longrightarrow> isCont cot x\"\n  for x :: \"'a::{real_normed_field,banach}\"\n  by (rule DERIV_cot [THEN DERIV_isCont])\n\nlemma isCont_cot' [simp,continuous_intros]:\n  \"isCont f a \\<Longrightarrow> sin (f a) \\<noteq> 0 \\<Longrightarrow> isCont (\\<lambda>x. cot (f x)) a\"\n  for a :: \"'a::{real_normed_field,banach}\" and f :: \"'a \\<Rightarrow> 'a\"\n  by (rule isCont_o2 [OF _ isCont_cot])\n\nlemma tendsto_cot [tendsto_intros]: \"(f \\<longlongrightarrow> a) F \\<Longrightarrow> sin a \\<noteq> 0 \\<Longrightarrow> ((\\<lambda>x. cot (f x)) \\<longlongrightarrow> cot a) F\"\n  for f :: \"'a \\<Rightarrow> 'a::{real_normed_field,banach}\"\n  by (rule isCont_tendsto_compose [OF isCont_cot])\n\nlemma continuous_cot:\n  \"continuous F f \\<Longrightarrow> sin (f (Lim F (\\<lambda>x. x))) \\<noteq> 0 \\<Longrightarrow> continuous F (\\<lambda>x. cot (f x))\"\n  for f :: \"'a \\<Rightarrow> 'a::{real_normed_field,banach}\"\n  unfolding continuous_def by (rule tendsto_cot)\n\nlemma continuous_on_cot [continuous_intros]:\n  fixes f :: \"'a \\<Rightarrow> 'a::{real_normed_field,banach}\"\n  shows \"continuous_on s f \\<Longrightarrow> (\\<forall>x\\<in>s. sin (f x) \\<noteq> 0) \\<Longrightarrow> continuous_on s (\\<lambda>x. cot (f x))\"\n  unfolding continuous_on_def by (auto intro: tendsto_cot)\n\nlemma continuous_within_cot [continuous_intros]:\n  fixes f :: \"'a \\<Rightarrow> 'a::{real_normed_field,banach}\"\n  shows \"continuous (at x within s) f \\<Longrightarrow> sin (f x) \\<noteq> 0 \\<Longrightarrow> continuous (at x within s) (\\<lambda>x. cot (f x))\"\n  unfolding continuous_within by (rule tendsto_cot)\n\n\nsubsection \\<open>Inverse Trigonometric Functions\\<close>\n\ndefinition arcsin :: \"real \\<Rightarrow> real\"\n  where \"arcsin y = (THE x. -(pi/2) \\<le> x \\<and> x \\<le> pi/2 \\<and> sin x = y)\"\n\ndefinition arccos :: \"real \\<Rightarrow> real\"\n  where \"arccos y = (THE x. 0 \\<le> x \\<and> x \\<le> pi \\<and> cos x = y)\"\n\ndefinition arctan :: \"real \\<Rightarrow> real\"\n  where \"arctan y = (THE x. -(pi/2) < x \\<and> x < pi/2 \\<and> tan x = y)\"\n\nlemma arcsin: \"- 1 \\<le> y \\<Longrightarrow> y \\<le> 1 \\<Longrightarrow> - (pi/2) \\<le> arcsin y \\<and> arcsin y \\<le> pi/2 \\<and> sin (arcsin y) = y\"\n  unfolding arcsin_def by (rule theI' [OF sin_total])\n\nlemma arcsin_pi: \"- 1 \\<le> y \\<Longrightarrow> y \\<le> 1 \\<Longrightarrow> - (pi/2) \\<le> arcsin y \\<and> arcsin y \\<le> pi \\<and> sin (arcsin y) = y\"\n  by (drule (1) arcsin) (force intro: order_trans)\n\nlemma sin_arcsin [simp]: \"- 1 \\<le> y \\<Longrightarrow> y \\<le> 1 \\<Longrightarrow> sin (arcsin y) = y\"\n  by (blast dest: arcsin)\n\nlemma arcsin_bounded: \"- 1 \\<le> y \\<Longrightarrow> y \\<le> 1 \\<Longrightarrow> - (pi/2) \\<le> arcsin y \\<and> arcsin y \\<le> pi/2\"\n  by (blast dest: arcsin)\n\nlemma arcsin_lbound: \"- 1 \\<le> y \\<Longrightarrow> y \\<le> 1 \\<Longrightarrow> - (pi/2) \\<le> arcsin y\"\n  by (blast dest: arcsin)\n\nlemma arcsin_ubound: \"- 1 \\<le> y \\<Longrightarrow> y \\<le> 1 \\<Longrightarrow> arcsin y \\<le> pi/2\"\n  by (blast dest: arcsin)\n\nlemma arcsin_lt_bounded: \"- 1 < y \\<Longrightarrow> y < 1 \\<Longrightarrow> - (pi/2) < arcsin y \\<and> arcsin y < pi/2\"\n  apply (frule order_less_imp_le)\n  apply (frule_tac y = y in order_less_imp_le)\n  apply (frule arcsin_bounded)\n   apply safe\n    apply simp\n   apply (drule_tac y = \"arcsin y\" in order_le_imp_less_or_eq)\n   apply (drule_tac [2] y = \"pi/2\" in order_le_imp_less_or_eq)\n   apply safe\n   apply (drule_tac [!] f = sin in arg_cong)\n   apply auto\n  done\n\nlemma arcsin_sin: \"- (pi/2) \\<le> x \\<Longrightarrow> x \\<le> pi/2 \\<Longrightarrow> arcsin (sin x) = x\"\n  apply (unfold arcsin_def)\n  apply (rule the1_equality)\n   apply (rule sin_total)\n    apply auto\n  done\n\nlemma arcsin_0 [simp]: \"arcsin 0 = 0\"\n  using arcsin_sin [of 0] by simp\n\nlemma arcsin_1 [simp]: \"arcsin 1 = pi/2\"\n  using arcsin_sin [of \"pi/2\"] by simp\n\nlemma arcsin_minus_1 [simp]: \"arcsin (- 1) = - (pi/2)\"\n  using arcsin_sin [of \"- pi/2\"] by simp\n\nlemma arcsin_minus: \"- 1 \\<le> x \\<Longrightarrow> x \\<le> 1 \\<Longrightarrow> arcsin (- x) = - arcsin x\"\n  by (metis (no_types, hide_lams) arcsin arcsin_sin minus_minus neg_le_iff_le sin_minus)\n\nlemma arcsin_eq_iff: \"\\<bar>x\\<bar> \\<le> 1 \\<Longrightarrow> \\<bar>y\\<bar> \\<le> 1 \\<Longrightarrow> arcsin x = arcsin y \\<longleftrightarrow> x = y\"\n  by (metis abs_le_iff arcsin minus_le_iff)\n\nlemma cos_arcsin_nonzero: \"- 1 < x \\<Longrightarrow> x < 1 \\<Longrightarrow> cos (arcsin x) \\<noteq> 0\"\n  using arcsin_lt_bounded cos_gt_zero_pi by force\n\nlemma arccos: \"- 1 \\<le> y \\<Longrightarrow> y \\<le> 1 \\<Longrightarrow> 0 \\<le> arccos y \\<and> arccos y \\<le> pi \\<and> cos (arccos y) = y\"\n  unfolding arccos_def by (rule theI' [OF cos_total])\n\nlemma cos_arccos [simp]: \"- 1 \\<le> y \\<Longrightarrow> y \\<le> 1 \\<Longrightarrow> cos (arccos y) = y\"\n  by (blast dest: arccos)\n\nlemma arccos_bounded: \"- 1 \\<le> y \\<Longrightarrow> y \\<le> 1 \\<Longrightarrow> 0 \\<le> arccos y \\<and> arccos y \\<le> pi\"\n  by (blast dest: arccos)\n\nlemma arccos_lbound: \"- 1 \\<le> y \\<Longrightarrow> y \\<le> 1 \\<Longrightarrow> 0 \\<le> arccos y\"\n  by (blast dest: arccos)\n\nlemma arccos_ubound: \"- 1 \\<le> y \\<Longrightarrow> y \\<le> 1 \\<Longrightarrow> arccos y \\<le> pi\"\n  by (blast dest: arccos)\n\nlemma arccos_lt_bounded: \"- 1 < y \\<Longrightarrow> y < 1 \\<Longrightarrow> 0 < arccos y \\<and> arccos y < pi\"\n  apply (frule order_less_imp_le)\n  apply (frule_tac y = y in order_less_imp_le)\n  apply (frule arccos_bounded)\n   apply auto\n   apply (drule_tac y = \"arccos y\" in order_le_imp_less_or_eq)\n   apply (drule_tac [2] y = pi in order_le_imp_less_or_eq)\n   apply auto\n   apply (drule_tac [!] f = cos in arg_cong)\n   apply auto\n  done\n\nlemma arccos_cos: \"0 \\<le> x \\<Longrightarrow> x \\<le> pi \\<Longrightarrow> arccos (cos x) = x\"\n  by (auto simp: arccos_def intro!: the1_equality cos_total)\n\nlemma arccos_cos2: \"x \\<le> 0 \\<Longrightarrow> - pi \\<le> x \\<Longrightarrow> arccos (cos x) = -x\"\n  by (auto simp: arccos_def intro!: the1_equality cos_total)\n\nlemma cos_arcsin: \"- 1 \\<le> x \\<Longrightarrow> x \\<le> 1 \\<Longrightarrow> cos (arcsin x) = sqrt (1 - x\\<^sup>2)\"\n  apply (subgoal_tac \"x\\<^sup>2 \\<le> 1\")\n   apply (rule power2_eq_imp_eq)\n     apply (simp add: cos_squared_eq)\n    apply (rule cos_ge_zero)\n     apply (erule (1) arcsin_lbound)\n    apply (erule (1) arcsin_ubound)\n   apply simp\n  apply (subgoal_tac \"\\<bar>x\\<bar>\\<^sup>2 \\<le> 1\\<^sup>2\")\n   apply simp\n  apply (rule power_mono)\n   apply simp\n  apply simp\n  done\n\nlemma sin_arccos: \"- 1 \\<le> x \\<Longrightarrow> x \\<le> 1 \\<Longrightarrow> sin (arccos x) = sqrt (1 - x\\<^sup>2)\"\n  apply (subgoal_tac \"x\\<^sup>2 \\<le> 1\")\n   apply (rule power2_eq_imp_eq)\n     apply (simp add: sin_squared_eq)\n    apply (rule sin_ge_zero)\n     apply (erule (1) arccos_lbound)\n    apply (erule (1) arccos_ubound)\n   apply simp\n  apply (subgoal_tac \"\\<bar>x\\<bar>\\<^sup>2 \\<le> 1\\<^sup>2\")\n   apply simp\n  apply (rule power_mono)\n   apply simp\n  apply simp\n  done\n\nlemma arccos_0 [simp]: \"arccos 0 = pi/2\"\n  by (metis arccos_cos cos_gt_zero cos_pi cos_pi_half pi_gt_zero\n      pi_half_ge_zero not_le not_zero_less_neg_numeral numeral_One)\n\nlemma arccos_1 [simp]: \"arccos 1 = 0\"\n  using arccos_cos by force\n\nlemma arccos_minus_1 [simp]: \"arccos (- 1) = pi\"\n  by (metis arccos_cos cos_pi order_refl pi_ge_zero)\n\nlemma arccos_minus: \"-1 \\<le> x \\<Longrightarrow> x \\<le> 1 \\<Longrightarrow> arccos (- x) = pi - arccos x\"\n  by (metis arccos_cos arccos_cos2 cos_minus_pi cos_total diff_le_0_iff_le le_add_same_cancel1\n      minus_diff_eq uminus_add_conv_diff)\n\nlemma sin_arccos_nonzero: \"- 1 < x \\<Longrightarrow> x < 1 \\<Longrightarrow> \\<not> sin (arccos x) = 0\"\n  using arccos_lt_bounded sin_gt_zero by force\n\nlemma arctan: \"- (pi/2) < arctan y \\<and> arctan y < pi/2 \\<and> tan (arctan y) = y\"\n  unfolding arctan_def by (rule theI' [OF tan_total])\n\nlemma tan_arctan: \"tan (arctan y) = y\"\n  by (simp add: arctan)\n\nlemma arctan_bounded: \"- (pi/2) < arctan y \\<and> arctan y < pi/2\"\n  by (auto simp only: arctan)\n\nlemma arctan_lbound: \"- (pi/2) < arctan y\"\n  by (simp add: arctan)\n\nlemma arctan_ubound: \"arctan y < pi/2\"\n  by (auto simp only: arctan)\n\nlemma arctan_unique:\n  assumes \"-(pi/2) < x\"\n    and \"x < pi/2\"\n    and \"tan x = y\"\n  shows \"arctan y = x\"\n  using assms arctan [of y] tan_total [of y] by (fast elim: ex1E)\n\nlemma arctan_tan: \"-(pi/2) < x \\<Longrightarrow> x < pi/2 \\<Longrightarrow> arctan (tan x) = x\"\n  by (rule arctan_unique) simp_all\n\nlemma arctan_zero_zero [simp]: \"arctan 0 = 0\"\n  by (rule arctan_unique) simp_all\n\nlemma arctan_minus: \"arctan (- x) = - arctan x\"\n  apply (rule arctan_unique)\n    apply (simp only: neg_less_iff_less arctan_ubound)\n   apply (metis minus_less_iff arctan_lbound)\n  apply (simp add: arctan)\n  done\n\nlemma cos_arctan_not_zero [simp]: \"cos (arctan x) \\<noteq> 0\"\n  by (intro less_imp_neq [symmetric] cos_gt_zero_pi arctan_lbound arctan_ubound)\n\nlemma cos_arctan: \"cos (arctan x) = 1 / sqrt (1 + x\\<^sup>2)\"\nproof (rule power2_eq_imp_eq)\n  have \"0 < 1 + x\\<^sup>2\" by (simp add: add_pos_nonneg)\n  show \"0 \\<le> 1 / sqrt (1 + x\\<^sup>2)\" by simp\n  show \"0 \\<le> cos (arctan x)\"\n    by (intro less_imp_le cos_gt_zero_pi arctan_lbound arctan_ubound)\n  have \"(cos (arctan x))\\<^sup>2 * (1 + (tan (arctan x))\\<^sup>2) = 1\"\n    unfolding tan_def by (simp add: distrib_left power_divide)\n  then show \"(cos (arctan x))\\<^sup>2 = (1 / sqrt (1 + x\\<^sup>2))\\<^sup>2\"\n    using \\<open>0 < 1 + x\\<^sup>2\\<close> by (simp add: arctan power_divide eq_divide_eq)\nqed\n\nlemma sin_arctan: \"sin (arctan x) = x / sqrt (1 + x\\<^sup>2)\"\n  using add_pos_nonneg [OF zero_less_one zero_le_power2 [of x]]\n  using tan_arctan [of x] unfolding tan_def cos_arctan\n  by (simp add: eq_divide_eq)\n\nlemma tan_sec: \"cos x \\<noteq> 0 \\<Longrightarrow> 1 + (tan x)\\<^sup>2 = (inverse (cos x))\\<^sup>2\"\n  for x :: \"'a::{real_normed_field,banach,field}\"\n  apply (rule power_inverse [THEN subst])\n  apply (rule_tac c1 = \"(cos x)\\<^sup>2\" in mult_right_cancel [THEN iffD1])\n   apply (auto simp add: tan_def field_simps)\n  done\n\nlemma arctan_less_iff: \"arctan x < arctan y \\<longleftrightarrow> x < y\"\n  by (metis tan_monotone' arctan_lbound arctan_ubound tan_arctan)\n\nlemma arctan_le_iff: \"arctan x \\<le> arctan y \\<longleftrightarrow> x \\<le> y\"\n  by (simp only: not_less [symmetric] arctan_less_iff)\n\nlemma arctan_eq_iff: \"arctan x = arctan y \\<longleftrightarrow> x = y\"\n  by (simp only: eq_iff [where 'a=real] arctan_le_iff)\n\nlemma zero_less_arctan_iff [simp]: \"0 < arctan x \\<longleftrightarrow> 0 < x\"\n  using arctan_less_iff [of 0 x] by simp\n\nlemma arctan_less_zero_iff [simp]: \"arctan x < 0 \\<longleftrightarrow> x < 0\"\n  using arctan_less_iff [of x 0] by simp\n\nlemma zero_le_arctan_iff [simp]: \"0 \\<le> arctan x \\<longleftrightarrow> 0 \\<le> x\"\n  using arctan_le_iff [of 0 x] by simp\n\nlemma arctan_le_zero_iff [simp]: \"arctan x \\<le> 0 \\<longleftrightarrow> x \\<le> 0\"\n  using arctan_le_iff [of x 0] by simp\n\nlemma arctan_eq_zero_iff [simp]: \"arctan x = 0 \\<longleftrightarrow> x = 0\"\n  using arctan_eq_iff [of x 0] by simp\n\nlemma continuous_on_arcsin': \"continuous_on {-1 .. 1} arcsin\"\nproof -\n  have \"continuous_on (sin ` {- pi / 2 .. pi / 2}) arcsin\"\n    by (rule continuous_on_inv) (auto intro: continuous_intros simp: arcsin_sin)\n  also have \"sin ` {- pi / 2 .. pi / 2} = {-1 .. 1}\"\n  proof safe\n    fix x :: real\n    assume \"x \\<in> {-1..1}\"\n    then show \"x \\<in> sin ` {- pi / 2..pi / 2}\"\n      using arcsin_lbound arcsin_ubound\n      by (intro image_eqI[where x=\"arcsin x\"]) auto\n  qed simp\n  finally show ?thesis .\nqed\n\nlemma continuous_on_arcsin [continuous_intros]:\n  \"continuous_on s f \\<Longrightarrow> (\\<forall>x\\<in>s. -1 \\<le> f x \\<and> f x \\<le> 1) \\<Longrightarrow> continuous_on s (\\<lambda>x. arcsin (f x))\"\n  using continuous_on_compose[of s f, OF _ continuous_on_subset[OF  continuous_on_arcsin']]\n  by (auto simp: comp_def subset_eq)\n\nlemma isCont_arcsin: \"-1 < x \\<Longrightarrow> x < 1 \\<Longrightarrow> isCont arcsin x\"\n  using continuous_on_arcsin'[THEN continuous_on_subset, of \"{ -1 <..< 1 }\"]\n  by (auto simp: continuous_on_eq_continuous_at subset_eq)\n\nlemma continuous_on_arccos': \"continuous_on {-1 .. 1} arccos\"\nproof -\n  have \"continuous_on (cos ` {0 .. pi}) arccos\"\n    by (rule continuous_on_inv) (auto intro: continuous_intros simp: arccos_cos)\n  also have \"cos ` {0 .. pi} = {-1 .. 1}\"\n  proof safe\n    fix x :: real\n    assume \"x \\<in> {-1..1}\"\n    then show \"x \\<in> cos ` {0..pi}\"\n      using arccos_lbound arccos_ubound\n      by (intro image_eqI[where x=\"arccos x\"]) auto\n  qed simp\n  finally show ?thesis .\nqed\n\nlemma continuous_on_arccos [continuous_intros]:\n  \"continuous_on s f \\<Longrightarrow> (\\<forall>x\\<in>s. -1 \\<le> f x \\<and> f x \\<le> 1) \\<Longrightarrow> continuous_on s (\\<lambda>x. arccos (f x))\"\n  using continuous_on_compose[of s f, OF _ continuous_on_subset[OF  continuous_on_arccos']]\n  by (auto simp: comp_def subset_eq)\n\nlemma isCont_arccos: \"-1 < x \\<Longrightarrow> x < 1 \\<Longrightarrow> isCont arccos x\"\n  using continuous_on_arccos'[THEN continuous_on_subset, of \"{ -1 <..< 1 }\"]\n  by (auto simp: continuous_on_eq_continuous_at subset_eq)\n\nlemma isCont_arctan: \"isCont arctan x\"\n  apply (rule arctan_lbound [of x, THEN dense, THEN exE])\n  apply clarify\n  apply (rule arctan_ubound [of x, THEN dense, THEN exE])\n  apply clarify\n  apply (subgoal_tac \"isCont arctan (tan (arctan x))\")\n   apply (simp add: arctan)\n  apply (erule (1) isCont_inverse_function2 [where f=tan])\n   apply (metis arctan_tan order_le_less_trans order_less_le_trans)\n  apply (metis cos_gt_zero_pi isCont_tan order_less_le_trans less_le)\n  done\n\nlemma tendsto_arctan [tendsto_intros]: \"(f \\<longlongrightarrow> x) F \\<Longrightarrow> ((\\<lambda>x. arctan (f x)) \\<longlongrightarrow> arctan x) F\"\n  by (rule isCont_tendsto_compose [OF isCont_arctan])\n\nlemma continuous_arctan [continuous_intros]: \"continuous F f \\<Longrightarrow> continuous F (\\<lambda>x. arctan (f x))\"\n  unfolding continuous_def by (rule tendsto_arctan)\n\nlemma continuous_on_arctan [continuous_intros]:\n  \"continuous_on s f \\<Longrightarrow> continuous_on s (\\<lambda>x. arctan (f x))\"\n  unfolding continuous_on_def by (auto intro: tendsto_arctan)\n\nlemma DERIV_arcsin: \"- 1 < x \\<Longrightarrow> x < 1 \\<Longrightarrow> DERIV arcsin x :> inverse (sqrt (1 - x\\<^sup>2))\"\n  apply (rule DERIV_inverse_function [where f=sin and a=\"-1\" and b=1])\n       apply (rule DERIV_cong [OF DERIV_sin])\n       apply (simp add: cos_arcsin)\n      apply (subgoal_tac \"\\<bar>x\\<bar>\\<^sup>2 < 1\\<^sup>2\")\n       apply simp\n      apply (rule power_strict_mono)\n        apply simp\n       apply simp\n      apply simp\n     apply assumption\n    apply assumption\n   apply simp\n  apply (erule (1) isCont_arcsin)\n  done\n\nlemma DERIV_arccos: \"- 1 < x \\<Longrightarrow> x < 1 \\<Longrightarrow> DERIV arccos x :> inverse (- sqrt (1 - x\\<^sup>2))\"\n  apply (rule DERIV_inverse_function [where f=cos and a=\"-1\" and b=1])\n       apply (rule DERIV_cong [OF DERIV_cos])\n       apply (simp add: sin_arccos)\n      apply (subgoal_tac \"\\<bar>x\\<bar>\\<^sup>2 < 1\\<^sup>2\")\n       apply simp\n      apply (rule power_strict_mono)\n        apply simp\n       apply simp\n      apply simp\n     apply assumption\n    apply assumption\n   apply simp\n  apply (erule (1) isCont_arccos)\n  done\n\nlemma DERIV_arctan: \"DERIV arctan x :> inverse (1 + x\\<^sup>2)\"\n  apply (rule DERIV_inverse_function [where f=tan and a=\"x - 1\" and b=\"x + 1\"])\n       apply (rule DERIV_cong [OF DERIV_tan])\n        apply (rule cos_arctan_not_zero)\n       apply (simp_all add: add_pos_nonneg arctan isCont_arctan)\n   apply (simp add: arctan power_inverse [symmetric] tan_sec [symmetric])\n  apply (subgoal_tac \"0 < 1 + x\\<^sup>2\")\n   apply simp\n  apply (simp_all add: add_pos_nonneg arctan isCont_arctan)\n  done\n\ndeclare\n  DERIV_arcsin[THEN DERIV_chain2, derivative_intros]\n  DERIV_arcsin[THEN DERIV_chain2, unfolded has_field_derivative_def, derivative_intros]\n  DERIV_arccos[THEN DERIV_chain2, derivative_intros]\n  DERIV_arccos[THEN DERIV_chain2, unfolded has_field_derivative_def, derivative_intros]\n  DERIV_arctan[THEN DERIV_chain2, derivative_intros]\n  DERIV_arctan[THEN DERIV_chain2, unfolded has_field_derivative_def, derivative_intros]\n\nlemma filterlim_tan_at_right: \"filterlim tan at_bot (at_right (- (pi/2)))\"\n  by (rule filterlim_at_bot_at_right[where Q=\"\\<lambda>x. - pi/2 < x \\<and> x < pi/2\" and P=\"\\<lambda>x. True\" and g=arctan])\n     (auto simp: arctan le_less eventually_at dist_real_def simp del: less_divide_eq_numeral1\n           intro!: tan_monotone exI[of _ \"pi/2\"])\n\nlemma filterlim_tan_at_left: \"filterlim tan at_top (at_left (pi/2))\"\n  by (rule filterlim_at_top_at_left[where Q=\"\\<lambda>x. - pi/2 < x \\<and> x < pi/2\" and P=\"\\<lambda>x. True\" and g=arctan])\n     (auto simp: arctan le_less eventually_at dist_real_def simp del: less_divide_eq_numeral1\n           intro!: tan_monotone exI[of _ \"pi/2\"])\n\nlemma tendsto_arctan_at_top: \"(arctan \\<longlongrightarrow> (pi/2)) at_top\"\nproof (rule tendstoI)\n  fix e :: real\n  assume \"0 < e\"\n  define y where \"y = pi/2 - min (pi/2) e\"\n  then have y: \"0 \\<le> y\" \"y < pi/2\" \"pi/2 \\<le> e + y\"\n    using \\<open>0 < e\\<close> by auto\n  show \"eventually (\\<lambda>x. dist (arctan x) (pi / 2) < e) at_top\"\n  proof (intro eventually_at_top_dense[THEN iffD2] exI allI impI)\n    fix x\n    assume \"tan y < x\"\n    then have \"arctan (tan y) < arctan x\"\n      by (simp add: arctan_less_iff)\n    with y have \"y < arctan x\"\n      by (subst (asm) arctan_tan) simp_all\n    with arctan_ubound[of x, arith] y \\<open>0 < e\\<close>\n    show \"dist (arctan x) (pi / 2) < e\"\n      by (simp add: dist_real_def)\n  qed\nqed\n\nlemma tendsto_arctan_at_bot: \"(arctan \\<longlongrightarrow> - (pi/2)) at_bot\"\n  unfolding filterlim_at_bot_mirror arctan_minus\n  by (intro tendsto_minus tendsto_arctan_at_top)\n\n\nsubsection \\<open>Prove Totality of the Trigonometric Functions\\<close>\n\nlemma cos_arccos_abs: \"\\<bar>y\\<bar> \\<le> 1 \\<Longrightarrow> cos (arccos y) = y\"\n  by (simp add: abs_le_iff)\n\nlemma sin_arccos_abs: \"\\<bar>y\\<bar> \\<le> 1 \\<Longrightarrow> sin (arccos y) = sqrt (1 - y\\<^sup>2)\"\n  by (simp add: sin_arccos abs_le_iff)\n\nlemma sin_mono_less_eq:\n  \"- (pi/2) \\<le> x \\<Longrightarrow> x \\<le> pi/2 \\<Longrightarrow> - (pi/2) \\<le> y \\<Longrightarrow> y \\<le> pi/2 \\<Longrightarrow> sin x < sin y \\<longleftrightarrow> x < y\"\n  by (metis not_less_iff_gr_or_eq sin_monotone_2pi)\n\nlemma sin_mono_le_eq:\n  \"- (pi/2) \\<le> x \\<Longrightarrow> x \\<le> pi/2 \\<Longrightarrow> - (pi/2) \\<le> y \\<Longrightarrow> y \\<le> pi/2 \\<Longrightarrow> sin x \\<le> sin y \\<longleftrightarrow> x \\<le> y\"\n  by (meson leD le_less_linear sin_monotone_2pi sin_monotone_2pi_le)\n\nlemma sin_inj_pi:\n  \"- (pi/2) \\<le> x \\<Longrightarrow> x \\<le> pi/2 \\<Longrightarrow> - (pi/2) \\<le> y \\<Longrightarrow> y \\<le> pi/2 \\<Longrightarrow> sin x = sin y \\<Longrightarrow> x = y\"\n  by (metis arcsin_sin)\n\nlemma cos_mono_less_eq: \"0 \\<le> x \\<Longrightarrow> x \\<le> pi \\<Longrightarrow> 0 \\<le> y \\<Longrightarrow> y \\<le> pi \\<Longrightarrow> cos x < cos y \\<longleftrightarrow> y < x\"\n  by (meson cos_monotone_0_pi cos_monotone_0_pi_le leD le_less_linear)\n\nlemma cos_mono_le_eq: \"0 \\<le> x \\<Longrightarrow> x \\<le> pi \\<Longrightarrow> 0 \\<le> y \\<Longrightarrow> y \\<le> pi \\<Longrightarrow> cos x \\<le> cos y \\<longleftrightarrow> y \\<le> x\"\n  by (metis arccos_cos cos_monotone_0_pi_le eq_iff linear)\n\nlemma cos_inj_pi: \"0 \\<le> x \\<Longrightarrow> x \\<le> pi \\<Longrightarrow> 0 \\<le> y \\<Longrightarrow> y \\<le> pi \\<Longrightarrow> cos x = cos y \\<Longrightarrow> x = y\"\n  by (metis arccos_cos)\n\nlemma arccos_le_pi2: \"\\<lbrakk>0 \\<le> y; y \\<le> 1\\<rbrakk> \\<Longrightarrow> arccos y \\<le> pi/2\"\n  by (metis (mono_tags) arccos_0 arccos cos_le_one cos_monotone_0_pi_le\n      cos_pi cos_pi_half pi_half_ge_zero antisym_conv less_eq_neg_nonpos linear minus_minus order.trans order_refl)\n\nlemma sincos_total_pi_half:\n  assumes \"0 \\<le> x\" \"0 \\<le> y\" \"x\\<^sup>2 + y\\<^sup>2 = 1\"\n  shows \"\\<exists>t. 0 \\<le> t \\<and> t \\<le> pi/2 \\<and> x = cos t \\<and> y = sin t\"\nproof -\n  have x1: \"x \\<le> 1\"\n    using assms by (metis le_add_same_cancel1 power2_le_imp_le power_one zero_le_power2)\n  with assms have *: \"0 \\<le> arccos x\" \"cos (arccos x) = x\"\n    by (auto simp: arccos)\n  from assms have \"y = sqrt (1 - x\\<^sup>2)\"\n    by (metis abs_of_nonneg add.commute add_diff_cancel real_sqrt_abs)\n  with x1 * assms arccos_le_pi2 [of x] show ?thesis\n    by (rule_tac x=\"arccos x\" in exI) (auto simp: sin_arccos)\nqed\n\nlemma sincos_total_pi:\n  assumes \"0 \\<le> y\" \"x\\<^sup>2 + y\\<^sup>2 = 1\"\n  shows \"\\<exists>t. 0 \\<le> t \\<and> t \\<le> pi \\<and> x = cos t \\<and> y = sin t\"\nproof (cases rule: le_cases [of 0 x])\n  case le\n  from sincos_total_pi_half [OF le] show ?thesis\n    by (metis pi_ge_two pi_half_le_two add.commute add_le_cancel_left add_mono assms)\nnext\n  case ge\n  then have \"0 \\<le> -x\"\n    by simp\n  then obtain t where t: \"t\\<ge>0\" \"t \\<le> pi/2\" \"-x = cos t\" \"y = sin t\"\n    using sincos_total_pi_half assms\n    by auto (metis \\<open>0 \\<le> - x\\<close> power2_minus)\n  show ?thesis\n    by (rule exI [where x = \"pi -t\"]) (use t in auto)\nqed\n\nlemma sincos_total_2pi_le:\n  assumes \"x\\<^sup>2 + y\\<^sup>2 = 1\"\n  shows \"\\<exists>t. 0 \\<le> t \\<and> t \\<le> 2 * pi \\<and> x = cos t \\<and> y = sin t\"\nproof (cases rule: le_cases [of 0 y])\n  case le\n  from sincos_total_pi [OF le] show ?thesis\n    by (metis assms le_add_same_cancel1 mult.commute mult_2_right order.trans)\nnext\n  case ge\n  then have \"0 \\<le> -y\"\n    by simp\n  then obtain t where t: \"t\\<ge>0\" \"t \\<le> pi\" \"x = cos t\" \"-y = sin t\"\n    using sincos_total_pi assms\n    by auto (metis \\<open>0 \\<le> - y\\<close> power2_minus)\n  show ?thesis\n    by (rule exI [where x = \"2 * pi - t\"]) (use t in auto)\nqed\n\nlemma sincos_total_2pi:\n  assumes \"x\\<^sup>2 + y\\<^sup>2 = 1\"\n  obtains t where \"0 \\<le> t\" \"t < 2*pi\" \"x = cos t\" \"y = sin t\"\nproof -\n  from sincos_total_2pi_le [OF assms]\n  obtain t where t: \"0 \\<le> t\" \"t \\<le> 2*pi\" \"x = cos t\" \"y = sin t\"\n    by blast\n  show ?thesis\n    by (cases \"t = 2 * pi\") (use t that in \\<open>force+\\<close>)\nqed\n\nlemma arcsin_less_mono: \"\\<bar>x\\<bar> \\<le> 1 \\<Longrightarrow> \\<bar>y\\<bar> \\<le> 1 \\<Longrightarrow> arcsin x < arcsin y \\<longleftrightarrow> x < y\"\n  by (rule trans [OF sin_mono_less_eq [symmetric]]) (use arcsin_ubound arcsin_lbound in auto)\n\nlemma arcsin_le_mono: \"\\<bar>x\\<bar> \\<le> 1 \\<Longrightarrow> \\<bar>y\\<bar> \\<le> 1 \\<Longrightarrow> arcsin x \\<le> arcsin y \\<longleftrightarrow> x \\<le> y\"\n  using arcsin_less_mono not_le by blast\n\nlemma arcsin_less_arcsin: \"- 1 \\<le> x \\<Longrightarrow> x < y \\<Longrightarrow> y \\<le> 1 \\<Longrightarrow> arcsin x < arcsin y\"\n  using arcsin_less_mono by auto\n\nlemma arcsin_le_arcsin: \"- 1 \\<le> x \\<Longrightarrow> x \\<le> y \\<Longrightarrow> y \\<le> 1 \\<Longrightarrow> arcsin x \\<le> arcsin y\"\n  using arcsin_le_mono by auto\n\nlemma arccos_less_mono: \"\\<bar>x\\<bar> \\<le> 1 \\<Longrightarrow> \\<bar>y\\<bar> \\<le> 1 \\<Longrightarrow> arccos x < arccos y \\<longleftrightarrow> y < x\"\n  by (rule trans [OF cos_mono_less_eq [symmetric]]) (use arccos_ubound arccos_lbound in auto)\n\nlemma arccos_le_mono: \"\\<bar>x\\<bar> \\<le> 1 \\<Longrightarrow> \\<bar>y\\<bar> \\<le> 1 \\<Longrightarrow> arccos x \\<le> arccos y \\<longleftrightarrow> y \\<le> x\"\n  using arccos_less_mono [of y x] by (simp add: not_le [symmetric])\n\nlemma arccos_less_arccos: \"- 1 \\<le> x \\<Longrightarrow> x < y \\<Longrightarrow> y \\<le> 1 \\<Longrightarrow> arccos y < arccos x\"\n  using arccos_less_mono by auto\n\nlemma arccos_le_arccos: \"- 1 \\<le> x \\<Longrightarrow> x \\<le> y \\<Longrightarrow> y \\<le> 1 \\<Longrightarrow> arccos y \\<le> arccos x\"\n  using arccos_le_mono by auto\n\nlemma arccos_eq_iff: \"\\<bar>x\\<bar> \\<le> 1 \\<and> \\<bar>y\\<bar> \\<le> 1 \\<Longrightarrow> arccos x = arccos y \\<longleftrightarrow> x = y\"\n  using cos_arccos_abs by fastforce\n\n\nsubsection \\<open>Machin's formula\\<close>\n\nlemma arctan_one: \"arctan 1 = pi / 4\"\n  by (rule arctan_unique) (simp_all add: tan_45 m2pi_less_pi)\n\nlemma tan_total_pi4:\n  assumes \"\\<bar>x\\<bar> < 1\"\n  shows \"\\<exists>z. - (pi / 4) < z \\<and> z < pi / 4 \\<and> tan z = x\"\nproof\n  show \"- (pi / 4) < arctan x \\<and> arctan x < pi / 4 \\<and> tan (arctan x) = x\"\n    unfolding arctan_one [symmetric] arctan_minus [symmetric]\n    unfolding arctan_less_iff\n    using assms by (auto simp add: arctan)\nqed\n\nlemma arctan_add:\n  assumes \"\\<bar>x\\<bar> \\<le> 1\" \"\\<bar>y\\<bar> < 1\"\n  shows \"arctan x + arctan y = arctan ((x + y) / (1 - x * y))\"\nproof (rule arctan_unique [symmetric])\n  have \"- (pi / 4) \\<le> arctan x\" \"- (pi / 4) < arctan y\"\n    unfolding arctan_one [symmetric] arctan_minus [symmetric]\n    unfolding arctan_le_iff arctan_less_iff\n    using assms by auto\n  from add_le_less_mono [OF this] show 1: \"- (pi / 2) < arctan x + arctan y\"\n    by simp\n  have \"arctan x \\<le> pi / 4\" \"arctan y < pi / 4\"\n    unfolding arctan_one [symmetric]\n    unfolding arctan_le_iff arctan_less_iff\n    using assms by auto\n  from add_le_less_mono [OF this] show 2: \"arctan x + arctan y < pi / 2\"\n    by simp\n  show \"tan (arctan x + arctan y) = (x + y) / (1 - x * y)\"\n    using cos_gt_zero_pi [OF 1 2] by (simp add: arctan tan_add)\nqed\n\nlemma arctan_double: \"\\<bar>x\\<bar> < 1 \\<Longrightarrow> 2 * arctan x = arctan ((2 * x) / (1 - x\\<^sup>2))\"\n  by (metis arctan_add linear mult_2 not_less power2_eq_square)\n\ntheorem machin: \"pi / 4 = 4 * arctan (1 / 5) - arctan (1 / 239)\"\nproof -\n  have \"\\<bar>1 / 5\\<bar> < (1 :: real)\"\n    by auto\n  from arctan_add[OF less_imp_le[OF this] this] have \"2 * arctan (1 / 5) = arctan (5 / 12)\"\n    by auto\n  moreover\n  have \"\\<bar>5 / 12\\<bar> < (1 :: real)\"\n    by auto\n  from arctan_add[OF less_imp_le[OF this] this] have \"2 * arctan (5 / 12) = arctan (120 / 119)\"\n    by auto\n  moreover\n  have \"\\<bar>1\\<bar> \\<le> (1::real)\" and \"\\<bar>1 / 239\\<bar> < (1::real)\"\n    by auto\n  from arctan_add[OF this] have \"arctan 1 + arctan (1 / 239) = arctan (120 / 119)\"\n    by auto\n  ultimately have \"arctan 1 + arctan (1 / 239) = 4 * arctan (1 / 5)\"\n    by auto\n  then show ?thesis\n    unfolding arctan_one by algebra\nqed\n\nlemma machin_Euler: \"5 * arctan (1 / 7) + 2 * arctan (3 / 79) = pi / 4\"\nproof -\n  have 17: \"\\<bar>1 / 7\\<bar> < (1 :: real)\" by auto\n  with arctan_double have \"2 * arctan (1 / 7) = arctan (7 / 24)\"\n    by simp (simp add: field_simps)\n  moreover\n  have \"\\<bar>7 / 24\\<bar> < (1 :: real)\" by auto\n  with arctan_double have \"2 * arctan (7 / 24) = arctan (336 / 527)\"\n    by simp (simp add: field_simps)\n  moreover\n  have \"\\<bar>336 / 527\\<bar> < (1 :: real)\" by auto\n  from arctan_add[OF less_imp_le[OF 17] this]\n  have \"arctan(1/7) + arctan (336 / 527) = arctan (2879 / 3353)\"\n    by auto\n  ultimately have I: \"5 * arctan (1 / 7) = arctan (2879 / 3353)\" by auto\n  have 379: \"\\<bar>3 / 79\\<bar> < (1 :: real)\" by auto\n  with arctan_double have II: \"2 * arctan (3 / 79) = arctan (237 / 3116)\"\n    by simp (simp add: field_simps)\n  have *: \"\\<bar>2879 / 3353\\<bar> < (1 :: real)\" by auto\n  have \"\\<bar>237 / 3116\\<bar> < (1 :: real)\" by auto\n  from arctan_add[OF less_imp_le[OF *] this] have \"arctan (2879/3353) + arctan (237/3116) = pi/4\"\n    by (simp add: arctan_one)\n  with I II show ?thesis by auto\nqed\n\n(*But could also prove MACHIN_GAUSS:\n  12 * arctan(1/18) + 8 * arctan(1/57) - 5 * arctan(1/239) = pi/4*)\n\n\nsubsection \\<open>Introducing the inverse tangent power series\\<close>\n\nlemma monoseq_arctan_series:\n  fixes x :: real\n  assumes \"\\<bar>x\\<bar> \\<le> 1\"\n  shows \"monoseq (\\<lambda>n. 1 / real (n * 2 + 1) * x^(n * 2 + 1))\"\n    (is \"monoseq ?a\")\nproof (cases \"x = 0\")\n  case True\n  then show ?thesis by (auto simp: monoseq_def)\nnext\n  case False\n  have \"norm x \\<le> 1\" and \"x \\<le> 1\" and \"-1 \\<le> x\"\n    using assms by auto\n  show \"monoseq ?a\"\n  proof -\n    have mono: \"1 / real (Suc (Suc n * 2)) * x ^ Suc (Suc n * 2) \\<le>\n        1 / real (Suc (n * 2)) * x ^ Suc (n * 2)\"\n      if \"0 \\<le> x\" and \"x \\<le> 1\" for n and x :: real\n    proof (rule mult_mono)\n      show \"1 / real (Suc (Suc n * 2)) \\<le> 1 / real (Suc (n * 2))\"\n        by (rule frac_le) simp_all\n      show \"0 \\<le> 1 / real (Suc (n * 2))\"\n        by auto\n      show \"x ^ Suc (Suc n * 2) \\<le> x ^ Suc (n * 2)\"\n        by (rule power_decreasing) (simp_all add: \\<open>0 \\<le> x\\<close> \\<open>x \\<le> 1\\<close>)\n      show \"0 \\<le> x ^ Suc (Suc n * 2)\"\n        by (rule zero_le_power) (simp add: \\<open>0 \\<le> x\\<close>)\n    qed\n    show ?thesis\n    proof (cases \"0 \\<le> x\")\n      case True\n      from mono[OF this \\<open>x \\<le> 1\\<close>, THEN allI]\n      show ?thesis\n        unfolding Suc_eq_plus1[symmetric] by (rule mono_SucI2)\n    next\n      case False\n      then have \"0 \\<le> - x\" and \"- x \\<le> 1\"\n        using \\<open>-1 \\<le> x\\<close> by auto\n      from mono[OF this]\n      have \"1 / real (Suc (Suc n * 2)) * x ^ Suc (Suc n * 2) \\<ge>\n          1 / real (Suc (n * 2)) * x ^ Suc (n * 2)\" for n\n        using \\<open>0 \\<le> -x\\<close> by auto\n      then show ?thesis\n        unfolding Suc_eq_plus1[symmetric] by (rule mono_SucI1[OF allI])\n    qed\n  qed\nqed\n\nlemma zeroseq_arctan_series:\n  fixes x :: real\n  assumes \"\\<bar>x\\<bar> \\<le> 1\"\n  shows \"(\\<lambda>n. 1 / real (n * 2 + 1) * x^(n * 2 + 1)) \\<longlonglongrightarrow> 0\"\n    (is \"?a \\<longlonglongrightarrow> 0\")\nproof (cases \"x = 0\")\n  case True\n  then show ?thesis by simp\nnext\n  case False\n  have \"norm x \\<le> 1\" and \"x \\<le> 1\" and \"-1 \\<le> x\"\n    using assms by auto\n  show \"?a \\<longlonglongrightarrow> 0\"\n  proof (cases \"\\<bar>x\\<bar> < 1\")\n    case True\n    then have \"norm x < 1\" by auto\n    from tendsto_mult[OF LIMSEQ_inverse_real_of_nat LIMSEQ_power_zero[OF \\<open>norm x < 1\\<close>, THEN LIMSEQ_Suc]]\n    have \"(\\<lambda>n. 1 / real (n + 1) * x ^ (n + 1)) \\<longlonglongrightarrow> 0\"\n      unfolding inverse_eq_divide Suc_eq_plus1 by simp\n    then show ?thesis\n      using pos2 by (rule LIMSEQ_linear)\n  next\n    case False\n    then have \"x = -1 \\<or> x = 1\"\n      using \\<open>\\<bar>x\\<bar> \\<le> 1\\<close> by auto\n    then have n_eq: \"\\<And> n. x ^ (n * 2 + 1) = x\"\n      unfolding One_nat_def by auto\n    from tendsto_mult[OF LIMSEQ_inverse_real_of_nat[THEN LIMSEQ_linear, OF pos2, unfolded inverse_eq_divide] tendsto_const[of x]]\n    show ?thesis\n      unfolding n_eq Suc_eq_plus1 by auto\n  qed\nqed\n\nlemma summable_arctan_series:\n  fixes n :: nat\n  assumes \"\\<bar>x\\<bar> \\<le> 1\"\n  shows \"summable (\\<lambda> k. (-1)^k * (1 / real (k*2+1) * x ^ (k*2+1)))\"\n    (is \"summable (?c x)\")\n  by (rule summable_Leibniz(1),\n      rule zeroseq_arctan_series[OF assms],\n      rule monoseq_arctan_series[OF assms])\n\nlemma DERIV_arctan_series:\n  assumes \"\\<bar>x\\<bar> < 1\"\n  shows \"DERIV (\\<lambda>x'. \\<Sum>k. (-1)^k * (1 / real (k * 2 + 1) * x' ^ (k * 2 + 1))) x :>\n      (\\<Sum>k. (-1)^k * x^(k * 2))\"\n    (is \"DERIV ?arctan _ :> ?Int\")\nproof -\n  let ?f = \"\\<lambda>n. if even n then (-1)^(n div 2) * 1 / real (Suc n) else 0\"\n\n  have n_even: \"even n \\<Longrightarrow> 2 * (n div 2) = n\" for n :: nat\n    by presburger\n  then have if_eq: \"?f n * real (Suc n) * x'^n =\n      (if even n then (-1)^(n div 2) * x'^(2 * (n div 2)) else 0)\"\n    for n x'\n    by auto\n\n  have summable_Integral: \"summable (\\<lambda> n. (- 1) ^ n * x^(2 * n))\" if \"\\<bar>x\\<bar> < 1\" for x :: real\n  proof -\n    from that have \"x\\<^sup>2 < 1\"\n      by (simp add: abs_square_less_1)\n    have \"summable (\\<lambda> n. (- 1) ^ n * (x\\<^sup>2) ^n)\"\n      by (rule summable_Leibniz(1))\n        (auto intro!: LIMSEQ_realpow_zero monoseq_realpow \\<open>x\\<^sup>2 < 1\\<close> order_less_imp_le[OF \\<open>x\\<^sup>2 < 1\\<close>])\n    then show ?thesis\n      by (simp only: power_mult)\n  qed\n\n  have sums_even: \"op sums f = op sums (\\<lambda> n. if even n then f (n div 2) else 0)\"\n    for f :: \"nat \\<Rightarrow> real\"\n  proof -\n    have \"f sums x = (\\<lambda> n. if even n then f (n div 2) else 0) sums x\" for x :: real\n    proof\n      assume \"f sums x\"\n      from sums_if[OF sums_zero this] show \"(\\<lambda>n. if even n then f (n div 2) else 0) sums x\"\n        by auto\n    next\n      assume \"(\\<lambda> n. if even n then f (n div 2) else 0) sums x\"\n      from LIMSEQ_linear[OF this[simplified sums_def] pos2, simplified sum_split_even_odd[simplified mult.commute]]\n      show \"f sums x\"\n        unfolding sums_def by auto\n    qed\n    then show ?thesis ..\n  qed\n\n  have Int_eq: \"(\\<Sum>n. ?f n * real (Suc n) * x^n) = ?Int\"\n    unfolding if_eq mult.commute[of _ 2]\n      suminf_def sums_even[of \"\\<lambda> n. (- 1) ^ n * x ^ (2 * n)\", symmetric]\n    by auto\n\n  have arctan_eq: \"(\\<Sum>n. ?f n * x^(Suc n)) = ?arctan x\" for x\n  proof -\n    have if_eq': \"\\<And>n. (if even n then (- 1) ^ (n div 2) * 1 / real (Suc n) else 0) * x ^ Suc n =\n      (if even n then (- 1) ^ (n div 2) * (1 / real (Suc (2 * (n div 2))) * x ^ Suc (2 * (n div 2))) else 0)\"\n      using n_even by auto\n    have idx_eq: \"\\<And>n. n * 2 + 1 = Suc (2 * n)\"\n      by auto\n    then show ?thesis\n      unfolding if_eq' idx_eq suminf_def\n        sums_even[of \"\\<lambda> n. (- 1) ^ n * (1 / real (Suc (2 * n)) * x ^ Suc (2 * n))\", symmetric]\n      by auto\n  qed\n\n  have \"DERIV (\\<lambda> x. \\<Sum> n. ?f n * x^(Suc n)) x :> (\\<Sum>n. ?f n * real (Suc n) * x^n)\"\n  proof (rule DERIV_power_series')\n    show \"x \\<in> {- 1 <..< 1}\"\n      using \\<open>\\<bar> x \\<bar> < 1\\<close> by auto\n    show \"summable (\\<lambda> n. ?f n * real (Suc n) * x'^n)\"\n      if x'_bounds: \"x' \\<in> {- 1 <..< 1}\" for x' :: real\n    proof -\n      from that have \"\\<bar>x'\\<bar> < 1\" by auto\n      then have *: \"summable (\\<lambda>n. (- 1) ^ n * x' ^ (2 * n))\"\n        by (rule summable_Integral)\n      show ?thesis\n        unfolding if_eq\n        apply (rule sums_summable [where l=\"0 + (\\<Sum>n. (-1)^n * x'^(2 * n))\"])\n        apply (rule sums_if)\n         apply (rule sums_zero)\n        apply (rule summable_sums)\n        apply (rule *)\n        done\n    qed\n  qed auto\n  then show ?thesis\n    by (simp only: Int_eq arctan_eq)\nqed\n\nlemma arctan_series:\n  assumes \"\\<bar>x\\<bar> \\<le> 1\"\n  shows \"arctan x = (\\<Sum>k. (-1)^k * (1 / real (k * 2 + 1) * x ^ (k * 2 + 1)))\"\n    (is \"_ = suminf (\\<lambda> n. ?c x n)\")\nproof -\n  let ?c' = \"\\<lambda>x n. (-1)^n * x^(n*2)\"\n\n  have DERIV_arctan_suminf: \"DERIV (\\<lambda> x. suminf (?c x)) x :> (suminf (?c' x))\"\n    if \"0 < r\" and \"r < 1\" and \"\\<bar>x\\<bar> < r\" for r x :: real\n  proof (rule DERIV_arctan_series)\n    from that show \"\\<bar>x\\<bar> < 1\"\n      using \\<open>r < 1\\<close> and \\<open>\\<bar>x\\<bar> < r\\<close> by auto\n  qed\n\n  {\n    fix x :: real\n    assume \"\\<bar>x\\<bar> \\<le> 1\"\n    note summable_Leibniz[OF zeroseq_arctan_series[OF this] monoseq_arctan_series[OF this]]\n  } note arctan_series_borders = this\n\n  have when_less_one: \"arctan x = (\\<Sum>k. ?c x k)\" if \"\\<bar>x\\<bar> < 1\" for x :: real\n  proof -\n    obtain r where \"\\<bar>x\\<bar> < r\" and \"r < 1\"\n      using dense[OF \\<open>\\<bar>x\\<bar> < 1\\<close>] by blast\n    then have \"0 < r\" and \"- r < x\" and \"x < r\" by auto\n\n    have suminf_eq_arctan_bounded: \"suminf (?c x) - arctan x = suminf (?c a) - arctan a\"\n      if \"-r < a\" and \"b < r\" and \"a < b\" and \"a \\<le> x\" and \"x \\<le> b\" for x a b\n    proof -\n      from that have \"\\<bar>x\\<bar> < r\" by auto\n      show \"suminf (?c x) - arctan x = suminf (?c a) - arctan a\"\n      proof (rule DERIV_isconst2[of \"a\" \"b\"])\n        show \"a < b\" and \"a \\<le> x\" and \"x \\<le> b\"\n          using \\<open>a < b\\<close> \\<open>a \\<le> x\\<close> \\<open>x \\<le> b\\<close> by auto\n        have \"\\<forall>x. - r < x \\<and> x < r \\<longrightarrow> DERIV (\\<lambda> x. suminf (?c x) - arctan x) x :> 0\"\n        proof (rule allI, rule impI)\n          fix x\n          assume \"-r < x \\<and> x < r\"\n          then have \"\\<bar>x\\<bar> < r\" by auto\n          with \\<open>r < 1\\<close> have \"\\<bar>x\\<bar> < 1\" by auto\n          have \"\\<bar>- (x\\<^sup>2)\\<bar> < 1\" using abs_square_less_1 \\<open>\\<bar>x\\<bar> < 1\\<close> by auto\n          then have \"(\\<lambda>n. (- (x\\<^sup>2)) ^ n) sums (1 / (1 - (- (x\\<^sup>2))))\"\n            unfolding real_norm_def[symmetric] by (rule geometric_sums)\n          then have \"(?c' x) sums (1 / (1 - (- (x\\<^sup>2))))\"\n            unfolding power_mult_distrib[symmetric] power_mult mult.commute[of _ 2] by auto\n          then have suminf_c'_eq_geom: \"inverse (1 + x\\<^sup>2) = suminf (?c' x)\"\n            using sums_unique unfolding inverse_eq_divide by auto\n          have \"DERIV (\\<lambda> x. suminf (?c x)) x :> (inverse (1 + x\\<^sup>2))\"\n            unfolding suminf_c'_eq_geom\n            by (rule DERIV_arctan_suminf[OF \\<open>0 < r\\<close> \\<open>r < 1\\<close> \\<open>\\<bar>x\\<bar> < r\\<close>])\n          from DERIV_diff [OF this DERIV_arctan] show \"DERIV (\\<lambda>x. suminf (?c x) - arctan x) x :> 0\"\n            by auto\n        qed\n        then have DERIV_in_rball: \"\\<forall>y. a \\<le> y \\<and> y \\<le> b \\<longrightarrow> DERIV (\\<lambda>x. suminf (?c x) - arctan x) y :> 0\"\n          using \\<open>-r < a\\<close> \\<open>b < r\\<close> by auto\n        then show \"\\<forall>y. a < y \\<and> y < b \\<longrightarrow> DERIV (\\<lambda>x. suminf (?c x) - arctan x) y :> 0\"\n          using \\<open>\\<bar>x\\<bar> < r\\<close> by auto\n        show \"\\<forall>y. a \\<le> y \\<and> y \\<le> b \\<longrightarrow> isCont (\\<lambda>x. suminf (?c x) - arctan x) y\"\n          using DERIV_in_rball DERIV_isCont by auto\n      qed\n    qed\n\n    have suminf_arctan_zero: \"suminf (?c 0) - arctan 0 = 0\"\n      unfolding Suc_eq_plus1[symmetric] power_Suc2 mult_zero_right arctan_zero_zero suminf_zero\n      by auto\n\n    have \"suminf (?c x) - arctan x = 0\"\n    proof (cases \"x = 0\")\n      case True\n      then show ?thesis\n        using suminf_arctan_zero by auto\n    next\n      case False\n      then have \"0 < \\<bar>x\\<bar>\" and \"- \\<bar>x\\<bar> < \\<bar>x\\<bar>\"\n        by auto\n      have \"suminf (?c (- \\<bar>x\\<bar>)) - arctan (- \\<bar>x\\<bar>) = suminf (?c 0) - arctan 0\"\n        by (rule suminf_eq_arctan_bounded[where x1=\"0\" and a1=\"-\\<bar>x\\<bar>\" and b1=\"\\<bar>x\\<bar>\", symmetric])\n          (simp_all only: \\<open>\\<bar>x\\<bar> < r\\<close> \\<open>-\\<bar>x\\<bar> < \\<bar>x\\<bar>\\<close> neg_less_iff_less)\n      moreover\n      have \"suminf (?c x) - arctan x = suminf (?c (- \\<bar>x\\<bar>)) - arctan (- \\<bar>x\\<bar>)\"\n        by (rule suminf_eq_arctan_bounded[where x1=\"x\" and a1=\"- \\<bar>x\\<bar>\" and b1=\"\\<bar>x\\<bar>\"])\n           (simp_all only: \\<open>\\<bar>x\\<bar> < r\\<close> \\<open>- \\<bar>x\\<bar> < \\<bar>x\\<bar>\\<close> neg_less_iff_less)\n      ultimately show ?thesis\n        using suminf_arctan_zero by auto\n    qed\n    then show ?thesis by auto\n  qed\n\n  show \"arctan x = suminf (\\<lambda>n. ?c x n)\"\n  proof (cases \"\\<bar>x\\<bar> < 1\")\n    case True\n    then show ?thesis by (rule when_less_one)\n  next\n    case False\n    then have \"\\<bar>x\\<bar> = 1\" using \\<open>\\<bar>x\\<bar> \\<le> 1\\<close> by auto\n    let ?a = \"\\<lambda>x n. \\<bar>1 / real (n * 2 + 1) * x^(n * 2 + 1)\\<bar>\"\n    let ?diff = \"\\<lambda>x n. \\<bar>arctan x - (\\<Sum>i<n. ?c x i)\\<bar>\"\n    have \"?diff 1 n \\<le> ?a 1 n\" for n :: nat\n    proof -\n      have \"0 < (1 :: real)\" by auto\n      moreover\n      have \"?diff x n \\<le> ?a x n\" if \"0 < x\" and \"x < 1\" for x :: real\n      proof -\n        from that have \"\\<bar>x\\<bar> \\<le> 1\" and \"\\<bar>x\\<bar> < 1\"\n          by auto\n        from \\<open>0 < x\\<close> have \"0 < 1 / real (0 * 2 + (1::nat)) * x ^ (0 * 2 + 1)\"\n          by auto\n        note bounds = mp[OF arctan_series_borders(2)[OF \\<open>\\<bar>x\\<bar> \\<le> 1\\<close>] this, unfolded when_less_one[OF \\<open>\\<bar>x\\<bar> < 1\\<close>, symmetric], THEN spec]\n        have \"0 < 1 / real (n*2+1) * x^(n*2+1)\"\n          by (rule mult_pos_pos) (simp_all only: zero_less_power[OF \\<open>0 < x\\<close>], auto)\n        then have a_pos: \"?a x n = 1 / real (n*2+1) * x^(n*2+1)\"\n          by (rule abs_of_pos)\n        show ?thesis\n        proof (cases \"even n\")\n          case True\n          then have sgn_pos: \"(-1)^n = (1::real)\" by auto\n          from \\<open>even n\\<close> obtain m where \"n = 2 * m\" ..\n          then have \"2 * m = n\" ..\n          from bounds[of m, unfolded this atLeastAtMost_iff]\n          have \"\\<bar>arctan x - (\\<Sum>i<n. (?c x i))\\<bar> \\<le> (\\<Sum>i<n + 1. (?c x i)) - (\\<Sum>i<n. (?c x i))\"\n            by auto\n          also have \"\\<dots> = ?c x n\" by auto\n          also have \"\\<dots> = ?a x n\" unfolding sgn_pos a_pos by auto\n          finally show ?thesis .\n        next\n          case False\n          then have sgn_neg: \"(-1)^n = (-1::real)\" by auto\n          from \\<open>odd n\\<close> obtain m where \"n = 2 * m + 1\" ..\n          then have m_def: \"2 * m + 1 = n\" ..\n          then have m_plus: \"2 * (m + 1) = n + 1\" by auto\n          from bounds[of \"m + 1\", unfolded this atLeastAtMost_iff, THEN conjunct1] bounds[of m, unfolded m_def atLeastAtMost_iff, THEN conjunct2]\n          have \"\\<bar>arctan x - (\\<Sum>i<n. (?c x i))\\<bar> \\<le> (\\<Sum>i<n. (?c x i)) - (\\<Sum>i<n+1. (?c x i))\" by auto\n          also have \"\\<dots> = - ?c x n\" by auto\n          also have \"\\<dots> = ?a x n\" unfolding sgn_neg a_pos by auto\n          finally show ?thesis .\n        qed\n      qed\n      hence \"\\<forall>x \\<in> { 0 <..< 1 }. 0 \\<le> ?a x n - ?diff x n\" by auto\n      moreover have \"isCont (\\<lambda> x. ?a x n - ?diff x n) x\" for x\n        unfolding diff_conv_add_uminus divide_inverse\n        by (auto intro!: isCont_add isCont_rabs continuous_ident isCont_minus isCont_arctan\n          isCont_inverse isCont_mult isCont_power continuous_const isCont_sum\n          simp del: add_uminus_conv_diff)\n      ultimately have \"0 \\<le> ?a 1 n - ?diff 1 n\"\n        by (rule LIM_less_bound)\n      then show ?thesis by auto\n    qed\n    have \"?a 1 \\<longlonglongrightarrow> 0\"\n      unfolding tendsto_rabs_zero_iff power_one divide_inverse One_nat_def\n      by (auto intro!: tendsto_mult LIMSEQ_linear LIMSEQ_inverse_real_of_nat simp del: of_nat_Suc)\n    have \"?diff 1 \\<longlonglongrightarrow> 0\"\n    proof (rule LIMSEQ_I)\n      fix r :: real\n      assume \"0 < r\"\n      obtain N :: nat where N_I: \"N \\<le> n \\<Longrightarrow> ?a 1 n < r\" for n\n        using LIMSEQ_D[OF \\<open>?a 1 \\<longlonglongrightarrow> 0\\<close> \\<open>0 < r\\<close>] by auto\n      have \"norm (?diff 1 n - 0) < r\" if \"N \\<le> n\" for n\n        using \\<open>?diff 1 n \\<le> ?a 1 n\\<close> N_I[OF that] by auto\n      then show \"\\<exists>N. \\<forall> n \\<ge> N. norm (?diff 1 n - 0) < r\" by blast\n    qed\n    from this [unfolded tendsto_rabs_zero_iff, THEN tendsto_add [OF _ tendsto_const], of \"- arctan 1\", THEN tendsto_minus]\n    have \"(?c 1) sums (arctan 1)\" unfolding sums_def by auto\n    then have \"arctan 1 = (\\<Sum>i. ?c 1 i)\" by (rule sums_unique)\n\n    show ?thesis\n    proof (cases \"x = 1\")\n      case True\n      then show ?thesis by (simp add: \\<open>arctan 1 = (\\<Sum> i. ?c 1 i)\\<close>)\n    next\n      case False\n      then have \"x = -1\" using \\<open>\\<bar>x\\<bar> = 1\\<close> by auto\n\n      have \"- (pi / 2) < 0\" using pi_gt_zero by auto\n      have \"- (2 * pi) < 0\" using pi_gt_zero by auto\n\n      have c_minus_minus: \"?c (- 1) i = - ?c 1 i\" for i by auto\n\n      have \"arctan (- 1) = arctan (tan (-(pi / 4)))\"\n        unfolding tan_45 tan_minus ..\n      also have \"\\<dots> = - (pi / 4)\"\n        by (rule arctan_tan) (auto simp: order_less_trans[OF \\<open>- (pi / 2) < 0\\<close> pi_gt_zero])\n      also have \"\\<dots> = - (arctan (tan (pi / 4)))\"\n        unfolding neg_equal_iff_equal\n        by (rule arctan_tan[symmetric]) (auto simp: order_less_trans[OF \\<open>- (2 * pi) < 0\\<close> pi_gt_zero])\n      also have \"\\<dots> = - (arctan 1)\"\n        unfolding tan_45 ..\n      also have \"\\<dots> = - (\\<Sum> i. ?c 1 i)\"\n        using \\<open>arctan 1 = (\\<Sum> i. ?c 1 i)\\<close> by auto\n      also have \"\\<dots> = (\\<Sum> i. ?c (- 1) i)\"\n        using suminf_minus[OF sums_summable[OF \\<open>(?c 1) sums (arctan 1)\\<close>]]\n        unfolding c_minus_minus by auto\n      finally show ?thesis using \\<open>x = -1\\<close> by auto\n    qed\n  qed\nqed\n\nlemma arctan_half: \"arctan x = 2 * arctan (x / (1 + sqrt(1 + x\\<^sup>2)))\"\n  for x :: real\nproof -\n  obtain y where low: \"- (pi / 2) < y\" and high: \"y < pi / 2\" and y_eq: \"tan y = x\"\n    using tan_total by blast\n  then have low2: \"- (pi / 2) < y / 2\" and high2: \"y / 2 < pi / 2\"\n    by auto\n\n  have \"0 < cos y\" by (rule cos_gt_zero_pi[OF low high])\n  then have \"cos y \\<noteq> 0\" and cos_sqrt: \"sqrt ((cos y)\\<^sup>2) = cos y\"\n    by auto\n\n  have \"1 + (tan y)\\<^sup>2 = 1 + (sin y)\\<^sup>2 / (cos y)\\<^sup>2\"\n    unfolding tan_def power_divide ..\n  also have \"\\<dots> = (cos y)\\<^sup>2 / (cos y)\\<^sup>2 + (sin y)\\<^sup>2 / (cos y)\\<^sup>2\"\n    using \\<open>cos y \\<noteq> 0\\<close> by auto\n  also have \"\\<dots> = 1 / (cos y)\\<^sup>2\"\n    unfolding add_divide_distrib[symmetric] sin_cos_squared_add2 ..\n  finally have \"1 + (tan y)\\<^sup>2 = 1 / (cos y)\\<^sup>2\" .\n\n  have \"sin y / (cos y + 1) = tan y / ((cos y + 1) / cos y)\"\n    unfolding tan_def using \\<open>cos y \\<noteq> 0\\<close> by (simp add: field_simps)\n  also have \"\\<dots> = tan y / (1 + 1 / cos y)\"\n    using \\<open>cos y \\<noteq> 0\\<close> unfolding add_divide_distrib by auto\n  also have \"\\<dots> = tan y / (1 + 1 / sqrt ((cos y)\\<^sup>2))\"\n    unfolding cos_sqrt ..\n  also have \"\\<dots> = tan y / (1 + sqrt (1 / (cos y)\\<^sup>2))\"\n    unfolding real_sqrt_divide by auto\n  finally have eq: \"sin y / (cos y + 1) = tan y / (1 + sqrt(1 + (tan y)\\<^sup>2))\"\n    unfolding \\<open>1 + (tan y)\\<^sup>2 = 1 / (cos y)\\<^sup>2\\<close> .\n\n  have \"arctan x = y\"\n    using arctan_tan low high y_eq by auto\n  also have \"\\<dots> = 2 * (arctan (tan (y/2)))\"\n    using arctan_tan[OF low2 high2] by auto\n  also have \"\\<dots> = 2 * (arctan (sin y / (cos y + 1)))\"\n    unfolding tan_half by auto\n  finally show ?thesis\n    unfolding eq \\<open>tan y = x\\<close> .\nqed\n\nlemma arctan_monotone: \"x < y \\<Longrightarrow> arctan x < arctan y\"\n  by (simp only: arctan_less_iff)\n\nlemma arctan_monotone': \"x \\<le> y \\<Longrightarrow> arctan x \\<le> arctan y\"\n  by (simp only: arctan_le_iff)\n\nlemma arctan_inverse:\n  assumes \"x \\<noteq> 0\"\n  shows \"arctan (1 / x) = sgn x * pi / 2 - arctan x\"\nproof (rule arctan_unique)\n  show \"- (pi / 2) < sgn x * pi / 2 - arctan x\"\n    using arctan_bounded [of x] assms\n    unfolding sgn_real_def\n    apply (auto simp add: arctan algebra_simps)\n    apply (drule zero_less_arctan_iff [THEN iffD2])\n    apply arith\n    done\n  show \"sgn x * pi / 2 - arctan x < pi / 2\"\n    using arctan_bounded [of \"- x\"] assms\n    unfolding sgn_real_def arctan_minus\n    by (auto simp add: algebra_simps)\n  show \"tan (sgn x * pi / 2 - arctan x) = 1 / x\"\n    unfolding tan_inverse [of \"arctan x\", unfolded tan_arctan]\n    unfolding sgn_real_def\n    by (simp add: tan_def cos_arctan sin_arctan sin_diff cos_diff)\nqed\n\ntheorem pi_series: \"pi / 4 = (\\<Sum>k. (-1)^k * 1 / real (k * 2 + 1))\"\n  (is \"_ = ?SUM\")\nproof -\n  have \"pi / 4 = arctan 1\"\n    using arctan_one by auto\n  also have \"\\<dots> = ?SUM\"\n    using arctan_series[of 1] by auto\n  finally show ?thesis by auto\nqed\n\n\nsubsection \\<open>Existence of Polar Coordinates\\<close>\n\nlemma cos_x_y_le_one: \"\\<bar>x / sqrt (x\\<^sup>2 + y\\<^sup>2)\\<bar> \\<le> 1\"\n  by (rule power2_le_imp_le [OF _ zero_le_one])\n    (simp add: power_divide divide_le_eq not_sum_power2_lt_zero)\n\nlemmas cos_arccos_lemma1 = cos_arccos_abs [OF cos_x_y_le_one]\n\nlemmas sin_arccos_lemma1 = sin_arccos_abs [OF cos_x_y_le_one]\n\nlemma polar_Ex: \"\\<exists>r::real. \\<exists>a. x = r * cos a \\<and> y = r * sin a\"\nproof -\n  have polar_ex1: \"0 < y \\<Longrightarrow> \\<exists>r a. x = r * cos a \\<and> y = r * sin a\" for y\n    apply (rule exI [where x = \"sqrt (x\\<^sup>2 + y\\<^sup>2)\"])\n    apply (rule exI [where x = \"arccos (x / sqrt (x\\<^sup>2 + y\\<^sup>2))\"])\n    apply (simp add: cos_arccos_lemma1 sin_arccos_lemma1 power_divide\n        real_sqrt_mult [symmetric] right_diff_distrib)\n    done\n  show ?thesis\n  proof (cases \"0::real\" y rule: linorder_cases)\n    case less\n    then show ?thesis\n      by (rule polar_ex1)\n  next\n    case equal\n    then show ?thesis\n      by (force simp add: intro!: cos_zero sin_zero)\n  next\n    case greater\n    with polar_ex1 [where y=\"-y\"] show ?thesis\n      by auto (metis cos_minus minus_minus minus_mult_right sin_minus)\n  qed\nqed\n\n\nsubsection \\<open>Basics about polynomial functions: products, extremal behaviour and root counts\\<close>\n\nlemma pairs_le_eq_Sigma: \"{(i, j). i + j \\<le> m} = Sigma (atMost m) (\\<lambda>r. atMost (m - r))\"\n  for m :: nat\n  by auto\n\nlemma sum_up_index_split: \"(\\<Sum>k\\<le>m + n. f k) = (\\<Sum>k\\<le>m. f k) + (\\<Sum>k = Suc m..m + n. f k)\"\n  by (metis atLeast0AtMost Suc_eq_plus1 le0 sum_ub_add_nat)\n\nlemma Sigma_interval_disjoint: \"(SIGMA i:A. {..v i}) \\<inter> (SIGMA i:A.{v i<..w}) = {}\"\n  for w :: \"'a::order\"\n  by auto\n\nlemma product_atMost_eq_Un: \"A \\<times> {..m} = (SIGMA i:A.{..m - i}) \\<union> (SIGMA i:A.{m - i<..m})\"\n  for m :: nat\n  by auto\n\nlemma polynomial_product: (*with thanks to Chaitanya Mangla*)\n  fixes x :: \"'a::idom\"\n  assumes m: \"\\<And>i. i > m \\<Longrightarrow> a i = 0\"\n    and n: \"\\<And>j. j > n \\<Longrightarrow> b j = 0\"\n  shows \"(\\<Sum>i\\<le>m. (a i) * x ^ i) * (\\<Sum>j\\<le>n. (b j) * x ^ j) =\n    (\\<Sum>r\\<le>m + n. (\\<Sum>k\\<le>r. (a k) * (b (r - k))) * x ^ r)\"\nproof -\n  have \"(\\<Sum>i\\<le>m. (a i) * x ^ i) * (\\<Sum>j\\<le>n. (b j) * x ^ j) = (\\<Sum>i\\<le>m. \\<Sum>j\\<le>n. (a i * x ^ i) * (b j * x ^ j))\"\n    by (rule sum_product)\n  also have \"\\<dots> = (\\<Sum>i\\<le>m + n. \\<Sum>j\\<le>n + m. a i * x ^ i * (b j * x ^ j))\"\n    using assms by (auto simp: sum_up_index_split)\n  also have \"\\<dots> = (\\<Sum>r\\<le>m + n. \\<Sum>j\\<le>m + n - r. a r * x ^ r * (b j * x ^ j))\"\n    apply (simp add: add_ac sum.Sigma product_atMost_eq_Un)\n    apply (clarsimp simp add: sum_Un Sigma_interval_disjoint intro!: sum.neutral)\n    apply (metis add_diff_assoc2 add.commute add_lessD1 leD m n nat_le_linear neqE)\n    done\n  also have \"\\<dots> = (\\<Sum>(i,j)\\<in>{(i,j). i+j \\<le> m+n}. (a i * x ^ i) * (b j * x ^ j))\"\n    by (auto simp: pairs_le_eq_Sigma sum.Sigma)\n  also have \"\\<dots> = (\\<Sum>r\\<le>m + n. (\\<Sum>k\\<le>r. (a k) * (b (r - k))) * x ^ r)\"\n    apply (subst sum_triangle_reindex_eq)\n    apply (auto simp: algebra_simps sum_distrib_left intro!: sum.cong)\n    apply (metis le_add_diff_inverse power_add)\n    done\n  finally show ?thesis .\nqed\n\nlemma polynomial_product_nat:\n  fixes x :: nat\n  assumes m: \"\\<And>i. i > m \\<Longrightarrow> a i = 0\"\n    and n: \"\\<And>j. j > n \\<Longrightarrow> b j = 0\"\n  shows \"(\\<Sum>i\\<le>m. (a i) * x ^ i) * (\\<Sum>j\\<le>n. (b j) * x ^ j) =\n    (\\<Sum>r\\<le>m + n. (\\<Sum>k\\<le>r. (a k) * (b (r - k))) * x ^ r)\"\n  using polynomial_product [of m a n b x] assms\n  by (simp only: of_nat_mult [symmetric] of_nat_power [symmetric]\n      of_nat_eq_iff Int.int_sum [symmetric])\n\nlemma polyfun_diff: (*COMPLEX_SUB_POLYFUN in HOL Light*)\n  fixes x :: \"'a::idom\"\n  assumes \"1 \\<le> n\"\n  shows \"(\\<Sum>i\\<le>n. a i * x^i) - (\\<Sum>i\\<le>n. a i * y^i) =\n    (x - y) * (\\<Sum>j<n. (\\<Sum>i=Suc j..n. a i * y^(i - j - 1)) * x^j)\"\nproof -\n  have h: \"bij_betw (\\<lambda>(i,j). (j,i)) ((SIGMA i : atMost n. lessThan i)) (SIGMA j : lessThan n. {Suc j..n})\"\n    by (auto simp: bij_betw_def inj_on_def)\n  have \"(\\<Sum>i\\<le>n. a i * x^i) - (\\<Sum>i\\<le>n. a i * y^i) = (\\<Sum>i\\<le>n. a i * (x^i - y^i))\"\n    by (simp add: right_diff_distrib sum_subtractf)\n  also have \"\\<dots> = (\\<Sum>i\\<le>n. a i * (x - y) * (\\<Sum>j<i. y^(i - Suc j) * x^j))\"\n    by (simp add: power_diff_sumr2 mult.assoc)\n  also have \"\\<dots> = (\\<Sum>i\\<le>n. \\<Sum>j<i. a i * (x - y) * (y^(i - Suc j) * x^j))\"\n    by (simp add: sum_distrib_left)\n  also have \"\\<dots> = (\\<Sum>(i,j) \\<in> (SIGMA i : atMost n. lessThan i). a i * (x - y) * (y^(i - Suc j) * x^j))\"\n    by (simp add: sum.Sigma)\n  also have \"\\<dots> = (\\<Sum>(j,i) \\<in> (SIGMA j : lessThan n. {Suc j..n}). a i * (x - y) * (y^(i - Suc j) * x^j))\"\n    by (auto simp add: sum.reindex_bij_betw [OF h, symmetric] intro: sum.strong_cong)\n  also have \"\\<dots> = (\\<Sum>j<n. \\<Sum>i=Suc j..n. a i * (x - y) * (y^(i - Suc j) * x^j))\"\n    by (simp add: sum.Sigma)\n  also have \"\\<dots> = (x - y) * (\\<Sum>j<n. (\\<Sum>i=Suc j..n. a i * y^(i - j - 1)) * x^j)\"\n    by (simp add: sum_distrib_left mult_ac)\n  finally show ?thesis .\nqed\n\nlemma polyfun_diff_alt: (*COMPLEX_SUB_POLYFUN_ALT in HOL Light*)\n  fixes x :: \"'a::idom\"\n  assumes \"1 \\<le> n\"\n  shows \"(\\<Sum>i\\<le>n. a i * x^i) - (\\<Sum>i\\<le>n. a i * y^i) =\n    (x - y) * ((\\<Sum>j<n. \\<Sum>k<n-j. a(j + k + 1) * y^k * x^j))\"\nproof -\n  have \"(\\<Sum>i=Suc j..n. a i * y^(i - j - 1)) = (\\<Sum>k<n-j. a(j+k+1) * y^k)\"\n    if \"j < n\" for j :: nat\n  proof -\n    have h: \"bij_betw (\\<lambda>i. i - (j + 1)) {Suc j..n} (lessThan (n-j))\"\n      apply (auto simp: bij_betw_def inj_on_def)\n      apply (rule_tac x=\"x + Suc j\" in image_eqI)\n       apply (auto simp: )\n      done\n    then show ?thesis\n      by (auto simp add: sum.reindex_bij_betw [OF h, symmetric] intro: sum.strong_cong)\n  qed\n  then show ?thesis\n    by (simp add: polyfun_diff [OF assms] sum_distrib_right)\nqed\n\nlemma polyfun_linear_factor:  (*COMPLEX_POLYFUN_LINEAR_FACTOR in HOL Light*)\n  fixes a :: \"'a::idom\"\n  shows \"\\<exists>b. \\<forall>z. (\\<Sum>i\\<le>n. c(i) * z^i) = (z - a) * (\\<Sum>i<n. b(i) * z^i) + (\\<Sum>i\\<le>n. c(i) * a^i)\"\nproof (cases \"n = 0\")\n  case True then show ?thesis\n    by simp\nnext\n  case False\n  have \"(\\<exists>b. \\<forall>z. (\\<Sum>i\\<le>n. c i * z^i) = (z - a) * (\\<Sum>i<n. b i * z^i) + (\\<Sum>i\\<le>n. c i * a^i)) \\<longleftrightarrow>\n        (\\<exists>b. \\<forall>z. (\\<Sum>i\\<le>n. c i * z^i) - (\\<Sum>i\\<le>n. c i * a^i) = (z - a) * (\\<Sum>i<n. b i * z^i))\"\n    by (simp add: algebra_simps)\n  also have \"\\<dots> \\<longleftrightarrow>\n    (\\<exists>b. \\<forall>z. (z - a) * (\\<Sum>j<n. (\\<Sum>i = Suc j..n. c i * a^(i - Suc j)) * z^j) =\n      (z - a) * (\\<Sum>i<n. b i * z^i))\"\n    using False by (simp add: polyfun_diff)\n  also have \"\\<dots> = True\" by auto\n  finally show ?thesis\n    by simp\nqed\n\nlemma polyfun_linear_factor_root:  (*COMPLEX_POLYFUN_LINEAR_FACTOR_ROOT in HOL Light*)\n  fixes a :: \"'a::idom\"\n  assumes \"(\\<Sum>i\\<le>n. c(i) * a^i) = 0\"\n  obtains b where \"\\<And>z. (\\<Sum>i\\<le>n. c i * z^i) = (z - a) * (\\<Sum>i<n. b i * z^i)\"\n  using polyfun_linear_factor [of c n a] assms by auto\n\n(*The material of this section, up until this point, could go into a new theory of polynomials\n  based on Main alone. The remaining material involves limits, continuity, series, etc.*)\n\nlemma isCont_polynom: \"isCont (\\<lambda>w. \\<Sum>i\\<le>n. c i * w^i) a\"\n  for c :: \"nat \\<Rightarrow> 'a::real_normed_div_algebra\"\n  by simp\n\nlemma zero_polynom_imp_zero_coeffs:\n  fixes c :: \"nat \\<Rightarrow> 'a::{ab_semigroup_mult,real_normed_div_algebra}\"\n  assumes \"\\<And>w. (\\<Sum>i\\<le>n. c i * w^i) = 0\"  \"k \\<le> n\"\n  shows \"c k = 0\"\n  using assms\nproof (induction n arbitrary: c k)\n  case 0\n  then show ?case\n    by simp\nnext\n  case (Suc n c k)\n  have [simp]: \"c 0 = 0\" using Suc.prems(1) [of 0]\n    by simp\n  have \"(\\<Sum>i\\<le>Suc n. c i * w^i) = w * (\\<Sum>i\\<le>n. c (Suc i) * w^i)\" for w\n  proof -\n    have \"(\\<Sum>i\\<le>Suc n. c i * w^i) = (\\<Sum>i\\<le>n. c (Suc i) * w ^ Suc i)\"\n      unfolding Set_Interval.sum_atMost_Suc_shift\n      by simp\n    also have \"\\<dots> = w * (\\<Sum>i\\<le>n. c (Suc i) * w^i)\"\n      by (simp add: sum_distrib_left ac_simps)\n    finally show ?thesis .\n  qed\n  then have w: \"\\<And>w. w \\<noteq> 0 \\<Longrightarrow> (\\<Sum>i\\<le>n. c (Suc i) * w^i) = 0\"\n    using Suc  by auto\n  then have \"(\\<lambda>h. \\<Sum>i\\<le>n. c (Suc i) * h^i) \\<midarrow>0\\<rightarrow> 0\"\n    by (simp cong: LIM_cong)  \\<comment> \\<open>the case \\<open>w = 0\\<close> by continuity\\<close>\n  then have \"(\\<Sum>i\\<le>n. c (Suc i) * 0^i) = 0\"\n    using isCont_polynom [of 0 \"\\<lambda>i. c (Suc i)\" n] LIM_unique\n    by (force simp add: Limits.isCont_iff)\n  then have \"\\<And>w. (\\<Sum>i\\<le>n. c (Suc i) * w^i) = 0\"\n    using w by metis\n  then have \"\\<And>i. i \\<le> n \\<Longrightarrow> c (Suc i) = 0\"\n    using Suc.IH [of \"\\<lambda>i. c (Suc i)\"] by blast\n  then show ?case using \\<open>k \\<le> Suc n\\<close>\n    by (cases k) auto\nqed\n\nlemma polyfun_rootbound: (*COMPLEX_POLYFUN_ROOTBOUND in HOL Light*)\n  fixes c :: \"nat \\<Rightarrow> 'a::{idom,real_normed_div_algebra}\"\n  assumes \"c k \\<noteq> 0\" \"k\\<le>n\"\n  shows \"finite {z. (\\<Sum>i\\<le>n. c(i) * z^i) = 0} \\<and> card {z. (\\<Sum>i\\<le>n. c(i) * z^i) = 0} \\<le> n\"\n  using assms\nproof (induction n arbitrary: c k)\n  case 0\n  then show ?case\n    by simp\nnext\n  case (Suc m c k)\n  let ?succase = ?case\n  show ?case\n  proof (cases \"{z. (\\<Sum>i\\<le>Suc m. c(i) * z^i) = 0} = {}\")\n    case True\n    then show ?succase\n      by simp\n  next\n    case False\n    then obtain z0 where z0: \"(\\<Sum>i\\<le>Suc m. c(i) * z0^i) = 0\"\n      by blast\n    then obtain b where b: \"\\<And>w. (\\<Sum>i\\<le>Suc m. c i * w^i) = (w - z0) * (\\<Sum>i\\<le>m. b i * w^i)\"\n      using polyfun_linear_factor_root [OF z0, unfolded lessThan_Suc_atMost]\n      by blast\n    then have eq: \"{z. (\\<Sum>i\\<le>Suc m. c i * z^i) = 0} = insert z0 {z. (\\<Sum>i\\<le>m. b i * z^i) = 0}\"\n      by auto\n    have \"\\<not> (\\<forall>k\\<le>m. b k = 0)\"\n    proof\n      assume [simp]: \"\\<forall>k\\<le>m. b k = 0\"\n      then have \"\\<And>w. (\\<Sum>i\\<le>m. b i * w^i) = 0\"\n        by simp\n      then have \"\\<And>w. (\\<Sum>i\\<le>Suc m. c i * w^i) = 0\"\n        using b by simp\n      then have \"\\<And>k. k \\<le> Suc m \\<Longrightarrow> c k = 0\"\n        using zero_polynom_imp_zero_coeffs by blast\n      then show False using Suc.prems by blast\n    qed\n    then obtain k' where bk': \"b k' \\<noteq> 0\" \"k' \\<le> m\"\n      by blast\n    show ?succase\n      using Suc.IH [of b k'] bk'\n      by (simp add: eq card_insert_if del: sum_atMost_Suc)\n    qed\nqed\n\nlemma\n  fixes c :: \"nat \\<Rightarrow> 'a::{idom,real_normed_div_algebra}\"\n  assumes \"c k \\<noteq> 0\" \"k\\<le>n\"\n  shows polyfun_roots_finite: \"finite {z. (\\<Sum>i\\<le>n. c(i) * z^i) = 0}\"\n    and polyfun_roots_card: \"card {z. (\\<Sum>i\\<le>n. c(i) * z^i) = 0} \\<le> n\"\n  using polyfun_rootbound assms by auto\n\nlemma polyfun_finite_roots: (*COMPLEX_POLYFUN_FINITE_ROOTS in HOL Light*)\n  fixes c :: \"nat \\<Rightarrow> 'a::{idom,real_normed_div_algebra}\"\n  shows \"finite {x. (\\<Sum>i\\<le>n. c i * x^i) = 0} \\<longleftrightarrow> (\\<exists>i\\<le>n. c i \\<noteq> 0)\"\n    (is \"?lhs = ?rhs\")\nproof\n  assume ?lhs\n  moreover have \"\\<not> finite {x. (\\<Sum>i\\<le>n. c i * x^i) = 0}\" if \"\\<forall>i\\<le>n. c i = 0\"\n  proof -\n    from that have \"\\<And>x. (\\<Sum>i\\<le>n. c i * x^i) = 0\"\n      by simp\n    then show ?thesis\n      using ex_new_if_finite [OF infinite_UNIV_char_0 [where 'a='a]]\n      by auto\n  qed\n  ultimately show ?rhs by metis\nnext\n  assume ?rhs\n  with polyfun_rootbound show ?lhs by blast\nqed\n\nlemma polyfun_eq_0: \"(\\<forall>x. (\\<Sum>i\\<le>n. c i * x^i) = 0) \\<longleftrightarrow> (\\<forall>i\\<le>n. c i = 0)\"\n  for c :: \"nat \\<Rightarrow> 'a::{idom,real_normed_div_algebra}\"\n  (*COMPLEX_POLYFUN_EQ_0 in HOL Light*)\n  using zero_polynom_imp_zero_coeffs by auto\n\nlemma polyfun_eq_coeffs: \"(\\<forall>x. (\\<Sum>i\\<le>n. c i * x^i) = (\\<Sum>i\\<le>n. d i * x^i)) \\<longleftrightarrow> (\\<forall>i\\<le>n. c i = d i)\"\n  for c :: \"nat \\<Rightarrow> 'a::{idom,real_normed_div_algebra}\"\nproof -\n  have \"(\\<forall>x. (\\<Sum>i\\<le>n. c i * x^i) = (\\<Sum>i\\<le>n. d i * x^i)) \\<longleftrightarrow> (\\<forall>x. (\\<Sum>i\\<le>n. (c i - d i) * x^i) = 0)\"\n    by (simp add: left_diff_distrib Groups_Big.sum_subtractf)\n  also have \"\\<dots> \\<longleftrightarrow> (\\<forall>i\\<le>n. c i - d i = 0)\"\n    by (rule polyfun_eq_0)\n  finally show ?thesis\n    by simp\nqed\n\nlemma polyfun_eq_const: (*COMPLEX_POLYFUN_EQ_CONST in HOL Light*)\n  fixes c :: \"nat \\<Rightarrow> 'a::{idom,real_normed_div_algebra}\"\n  shows \"(\\<forall>x. (\\<Sum>i\\<le>n. c i * x^i) = k) \\<longleftrightarrow> c 0 = k \\<and> (\\<forall>i \\<in> {1..n}. c i = 0)\"\n    (is \"?lhs = ?rhs\")\nproof -\n  have *: \"\\<forall>x. (\\<Sum>i\\<le>n. (if i=0 then k else 0) * x^i) = k\"\n    by (induct n) auto\n  show ?thesis\n  proof\n    assume ?lhs\n    with * have \"(\\<forall>i\\<le>n. c i = (if i=0 then k else 0))\"\n      by (simp add: polyfun_eq_coeffs [symmetric])\n    then show ?rhs by simp\n  next\n    assume ?rhs\n    then show ?lhs by (induct n) auto\n  qed\nqed\n\nlemma root_polyfun:\n  fixes z :: \"'a::idom\"\n  assumes \"1 \\<le> n\"\n  shows \"z^n = a \\<longleftrightarrow> (\\<Sum>i\\<le>n. (if i = 0 then -a else if i=n then 1 else 0) * z^i) = 0\"\n  using assms by (cases n) (simp_all add: sum_head_Suc atLeast0AtMost [symmetric])\n\nlemma\n  assumes \"SORT_CONSTRAINT('a::{idom,real_normed_div_algebra})\"\n    and \"1 \\<le> n\"\n  shows finite_roots_unity: \"finite {z::'a. z^n = 1}\"\n    and card_roots_unity: \"card {z::'a. z^n = 1} \\<le> n\"\n  using polyfun_rootbound [of \"\\<lambda>i. if i = 0 then -1 else if i=n then 1 else 0\" n n] assms(2)\n  by (auto simp add: root_polyfun [OF assms(2)])\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/Transcendental.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094145755218, "lm_q2_score": 0.8244619242200082, "lm_q1q2_score": 0.7364995988647838}}
{"text": "theory predicate_logic_examples_isar\nimports Main\nbegin\n\n(* lemma ex1: \"A \\<Rightarrow>(B \\<Rightarrow> (A \\<and> B)))\" *)\n\nthm conjI (* \\<lbrakk>?P; ?Q\\<rbrakk> \\<Longrightarrow> ?P \\<and> ?Q *)\nlemma \n  shows \"\\<lbrakk>A;B\\<rbrakk> \\<Longrightarrow> (A \\<and> B)\"\nproof -\n  assume A: A\n  assume B: B\n  from A B show \"A \\<and> B\" by (rule conjI)\nqed\n\n(* Your turn 1 *)\n\nlemma \n  shows \"A \\<longrightarrow> (A \\<or> B)\"\nproof (rule impI)\n  show \"A \\<Longrightarrow> (A \\<or> B)\" by (rule disjI1)\nqed\n\nlemma \n  shows \"A \\<longrightarrow> (A \\<or> B)\"\nproof (rule impI)\n  assume A: A\n  from A show \"(A \\<or> B)\" by (rule disjI1)\nqed\n\n(* Example 4: (A \\<Rightarrow> B) \\<Rightarrow> ((B \\<Rightarrow> C) \\<Rightarrow> (A \\<Rightarrow> C)) *)\n\nthm impI (* (?P \\<Longrightarrow> ?Q) \\<Longrightarrow> ?P \\<longrightarrow> ?Q *)\nthm impE (* \\<lbrakk>?P \\<longrightarrow> ?Q; ?P; ?Q \\<Longrightarrow> ?R\\<rbrakk> \\<Longrightarrow> ?R *)\nlemma\n  shows \"(A \\<Longrightarrow> B) \\<Longrightarrow> ((B \\<Longrightarrow> C) \\<Longrightarrow> (A \\<Longrightarrow> C))\"\nproof -\n  assume A2B: \"A\\<Longrightarrow>B\"\n  assume B2C: \"B\\<Longrightarrow>C\"\n  assume A: \"A\"\n  from A2B have A22B: \"A\\<longrightarrow>B\" by (rule impI)\n  from B2C have A22C: \"B\\<longrightarrow>C\" by (rule impI)\n  have B: \"B\" proof -\n    from A22B A show \"B\" by (rule impE) qed\n  show \"C\" proof -\n    from A22C B show \"C\" by (rule impE) qed\nqed\n\n(* Your turn 2:  (A \\<and> B) \\<Rightarrow> (A \\<or> B) *)\n\nthm conjE (* \\<lbrakk>?P \\<and> ?Q; \\<lbrakk>?P; ?Q\\<rbrakk> \\<Longrightarrow> ?R\\<rbrakk> \\<Longrightarrow> ?R *)\nlemma\n  shows \"A \\<and> B \\<longrightarrow> A \\<or> B\"\nproof (rule impI)\n  assume AnB: \"A \\<and> B\"\n  have AB2ArB: \"A \\<Longrightarrow> B \\<Longrightarrow> A \\<or> B\" by (rule disjI1)\n  from AnB AB2ArB show \"A \\<or> B\" by (rule conjE)\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/predicate_logic_examples_isar.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094174159127, "lm_q2_score": 0.8244619177503205, "lm_q1q2_score": 0.7364995954271449}}
{"text": "theory \"Set-Cpo\"\nimports \"~~/src/HOL/HOLCF/HOLCF\"\nbegin\n\ndefault_sort type\n\ninstantiation set :: (type) below\nbegin\n  definition below_set where \"op \\<sqsubseteq> = op \\<subseteq>\"\ninstance..  \nend\n\ninstance set :: (type) po\n  by standard (auto simp add: below_set_def)\n\nlemma is_lub_set:\n  \"S <<| \\<Union>S\"\n  by(auto simp add: is_lub_def below_set_def is_ub_def)\n\nlemma lub_set: \"lub S = \\<Union>S\"\n  by (metis is_lub_set lub_eqI)\n  \ninstance set  :: (type) cpo\n  by standard (rule exI, rule is_lub_set)\n\nlemma minimal_set: \"{} \\<sqsubseteq> S\"\n  unfolding below_set_def by simp\n\ninstance set  :: (type) pcpo\n  by standard (rule+, rule minimal_set)\n\nlemma set_contI:\n  assumes  \"\\<And> Y. chain Y \\<Longrightarrow> f (\\<Squnion> i. Y i) = \\<Union> (f ` range Y)\"\n  shows \"cont f\"\nproof(rule contI)\n  fix Y :: \"nat \\<Rightarrow> 'a\"\n  assume \"chain Y\"\n  hence \"f (\\<Squnion> i. Y i) = \\<Union> (f ` range Y)\" by (rule assms)\n  also have \"\\<dots> = \\<Union> (range (\\<lambda>i. f (Y i)))\" by simp\n  finally\n  show \"range (\\<lambda>i. f (Y i)) <<| f (\\<Squnion> i. Y i)\" using is_lub_set by metis\nqed\n\nlemma set_set_contI:\n  assumes  \"\\<And> S. f (\\<Union>S) = \\<Union> (f ` S)\"\n  shows \"cont f\"\n  by (metis set_contI assms is_lub_set  lub_eqI)\n\nlemma adm_subseteq[simp]:\n  assumes \"cont f\"\n  shows \"adm (\\<lambda>a. f a \\<subseteq> S)\"\nby (rule admI)(auto simp add: cont2contlubE[OF assms] lub_set)\n\nlemma adm_Ball[simp]: \"adm (\\<lambda>S. \\<forall>x\\<in>S. P x)\"\n  by (auto intro!: admI  simp add: lub_set)\n\nlemma finite_subset_chain:\n  fixes Y :: \"nat \\<Rightarrow> 'a set\"\n  assumes \"chain Y\"\n  assumes \"S \\<subseteq> UNION UNIV Y\"\n  assumes \"finite S\"\n  shows \"\\<exists>i. S \\<subseteq> Y i\"\nproof-\n  from assms(2)\n  have \"\\<forall>x \\<in> S. \\<exists> i. x \\<in> Y i\" by auto\n  then obtain f where f: \"\\<forall> x\\<in> S. x \\<in> Y (f x)\" by metis\n\n  def i \\<equiv> \"Max (f ` S)\"\n  from `finite S`\n  have \"finite (f ` S)\" by simp\n  hence \"\\<forall> x\\<in>S. f x \\<le> i\" unfolding i_def by auto\n  with chain_mono[OF `chain Y`]\n  have \"\\<forall> x\\<in>S. Y (f x) \\<subseteq> Y i\" by (auto simp add: below_set_def)\n  with f\n  have \"S \\<subseteq> Y i\" by auto\n  thus ?thesis..\nqed\n\nlemma diff_cont[THEN cont_compose, simp, cont2cont]:\n  fixes S' :: \"'a set\"\n  shows  \"cont (\\<lambda>S. S - S')\"\nby (rule set_set_contI) simp\n\n\nend\n", "meta": {"author": "nomeata", "repo": "isa-launchbury", "sha": "2caa8d7d588e218aef1c49f2f327597af06d116e", "save_path": "github-repos/isabelle/nomeata-isa-launchbury", "path": "github-repos/isabelle/nomeata-isa-launchbury/isa-launchbury-2caa8d7d588e218aef1c49f2f327597af06d116e/Call_Arity/Set-Cpo.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094032139577, "lm_q2_score": 0.8244619306896955, "lm_q1q2_score": 0.7364995952770392}}
{"text": "(*<*)\ntheory Nested imports ABexpr begin\n(*>*)\n\ntext{*\n\\index{datatypes!and nested recursion}%\nSo far, all datatypes had the property that on the right-hand side of their\ndefinition they occurred only at the top-level: directly below a\nconstructor. Now we consider \\emph{nested recursion}, where the recursive\ndatatype occurs nested in some other datatype (but not inside itself!).\nConsider the following model of terms\nwhere function symbols can be applied to a list of arguments:\n*}\n(*<*)hide_const Var(*>*)\ndatatype ('v,'f)\"term\" = Var 'v | App 'f \"('v,'f)term list\"\n\ntext{*\\noindent\nNote that we need to quote @{text term} on the left to avoid confusion with\nthe Isabelle command \\isacommand{term}.\nParameter @{typ\"'v\"} is the type of variables and @{typ\"'f\"} the type of\nfunction symbols.\nA mathematical term like $f(x,g(y))$ becomes @{term\"App f [Var x, App g\n  [Var y]]\"}, where @{term f}, @{term g}, @{term x}, @{term y} are\nsuitable values, e.g.\\ numbers or strings.\n\nWhat complicates the definition of @{text term} is the nested occurrence of\n@{text term} inside @{text list} on the right-hand side. In principle,\nnested recursion can be eliminated in favour of mutual recursion by unfolding\nthe offending datatypes, here @{text list}. The result for @{text term}\nwould be something like\n\\medskip\n\n\\input{unfoldnested.tex}\n\\medskip\n\n\\noindent\nAlthough we do not recommend this unfolding to the user, it shows how to\nsimulate nested recursion by mutual recursion.\nNow we return to the initial definition of @{text term} using\nnested recursion.\n\nLet us define a substitution function on terms. Because terms involve term\nlists, we need to define two substitution functions simultaneously:\n*}\n\nprimrec\nsubst :: \"('v\\<Rightarrow>('v,'f)term) \\<Rightarrow> ('v,'f)term      \\<Rightarrow> ('v,'f)term\" and\nsubsts:: \"('v\\<Rightarrow>('v,'f)term) \\<Rightarrow> ('v,'f)term list \\<Rightarrow> ('v,'f)term list\"\nwhere\n\"subst s (Var x) = s x\" |\n  subst_App:\n\"subst s (App f ts) = App f (substs s ts)\" |\n\n\"substs s [] = []\" |\n\"substs s (t # ts) = subst s t # substs s ts\"\n\ntext{*\\noindent\nIndividual equations in a \\commdx{primrec} definition may be\nnamed as shown for @{thm[source]subst_App}.\nThe significance of this device will become apparent below.\n\nSimilarly, when proving a statement about terms inductively, we need\nto prove a related statement about term lists simultaneously. For example,\nthe fact that the identity substitution does not change a term needs to be\nstrengthened and proved as follows:\n*}\n\nlemma subst_id(*<*)(*referred to from ABexpr*)(*>*): \"subst  Var t  = (t ::('v,'f)term)  \\<and>\n                  substs Var ts = (ts::('v,'f)term list)\"\napply(induct_tac t and ts rule: subst.induct substs.induct, simp_all)\ndone\n\ntext{*\\noindent\nNote that @{term Var} is the identity substitution because by definition it\nleaves variables unchanged: @{prop\"subst Var (Var x) = Var x\"}. Note also\nthat the type annotations are necessary because otherwise there is nothing in\nthe goal to enforce that both halves of the goal talk about the same type\nparameters @{text\"('v,'f)\"}. As a result, induction would fail\nbecause the two halves of the goal would be unrelated.\n\n\\begin{exercise}\nThe fact that substitution distributes over composition can be expressed\nroughly as follows:\n@{text[display]\"subst (f \\<circ> g) t = subst f (subst g t)\"}\nCorrect this statement (you will find that it does not type-check),\nstrengthen it, and prove it. (Note: @{text\"\\<circ>\"} is function composition;\nits definition is found in theorem @{thm[source]o_def}).\n\\end{exercise}\n\\begin{exercise}\\label{ex:trev-trev}\n  Define a function @{term trev} of type @{typ\"('v,'f)term => ('v,'f)term\"}\nthat recursively reverses the order of arguments of all function symbols in a\n  term. Prove that @{prop\"trev(trev t) = t\"}.\n\\end{exercise}\n\nThe experienced functional programmer may feel that our definition of\n@{term subst} is too complicated in that @{const substs} is\nunnecessary. The @{term App}-case can be defined directly as\n@{term[display]\"subst s (App f ts) = App f (map (subst s) ts)\"}\nwhere @{term\"map\"} is the standard list function such that\n@{text\"map f [x1,...,xn] = [f x1,...,f xn]\"}. This is true, but Isabelle\ninsists on the conjunctive format. Fortunately, we can easily \\emph{prove}\nthat the suggested equation holds:\n*}\n(*<*)\n(* Exercise 1: *)\nlemma \"subst  ((subst f) \\<circ> g) t  = subst  f (subst g t) \\<and>\n       substs ((subst f) \\<circ> g) ts = substs f (substs g ts)\"\napply (induct_tac t and ts rule: subst.induct substs.induct)\napply (simp_all)\ndone\n\n(* Exercise 2: *)\n\nprimrec trev :: \"('v,'f) term \\<Rightarrow> ('v,'f) term\"\n  and trevs:: \"('v,'f) term list \\<Rightarrow> ('v,'f) term list\"\nwhere\n  \"trev (Var v)    = Var v\"\n| \"trev (App f ts) = App f (trevs ts)\"\n| \"trevs [] = []\"\n| \"trevs (t#ts) = (trevs ts) @ [(trev t)]\" \n\n\n\nlemma \"trev (trev t) = (t::('v,'f)term) \\<and> \n       trevs (trevs ts) = (ts::('v,'f)term list)\"\napply (induct_tac t and ts rule: trev.induct trevs.induct, simp_all)\ndone\n(*>*)\n\nlemma [simp]: \"subst s (App f ts) = App f (map (subst s) ts)\"\napply(induct_tac ts, simp_all)\ndone\n\ntext{*\\noindent\nWhat is more, we can now disable the old defining equation as a\nsimplification rule:\n*}\n\ndeclare subst_App [simp del]\n\ntext{*\\noindent The advantage is that now we have replaced @{const\nsubsts} by @{const map}, we can profit from the large number of\npre-proved lemmas about @{const map}.  Unfortunately, inductive proofs\nabout type @{text term} are still awkward because they expect a\nconjunction. One could derive a new induction principle as well (see\n\\S\\ref{sec:derive-ind}), but simpler is to stop using\n\\isacommand{primrec} and to define functions with \\isacommand{fun}\ninstead.  Simple uses of \\isacommand{fun} are described in\n\\S\\ref{sec:fun} below.  Advanced applications, including functions\nover nested datatypes like @{text term}, are discussed in a\nseparate tutorial~@{cite \"isabelle-function\"}.\n\nOf course, you may also combine mutual and nested recursion of datatypes. For example,\nconstructor @{text Sum} in \\S\\ref{sec:datatype-mut-rec} could take a list of\nexpressions as its argument: @{text Sum}~@{typ[quotes]\"'a aexp list\"}.\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/Datatype/Nested.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8459424373085146, "lm_q2_score": 0.8705972650509008, "lm_q1q2_score": 0.736475172311286}}
{"text": "(*  Title:      HOL/Statespace/DistinctTreeProver.thy\n    Author:     Norbert Schirmer, TU Muenchen\n*)\n\nsection \\<open>Distinctness of Names in a Binary Tree \\label{sec:DistinctTreeProver}\\<close>\n\ntheory DistinctTreeProver \nimports Main\nbegin\n\ntext \\<open>A state space manages a set of (abstract) names and assumes\nthat the names are distinct. The names are stored as parameters of a\nlocale and distinctness as an assumption. The most common request is\nto proof distinctness of two given names. We maintain the names in a\nbalanced binary tree and formulate a predicate that all nodes in the\ntree have distinct names. This setup leads to logarithmic certificates.\n\\<close>\n\nsubsection \\<open>The Binary Tree\\<close>\n\ndatatype 'a tree = Node \"'a tree\" 'a bool \"'a tree\" | Tip\n\n\ntext \\<open>The boolean flag in the node marks the content of the node as\ndeleted, without having to build a new tree. We prefer the boolean\nflag to an option type, so that the ML-layer can still use the node\ncontent to facilitate binary search in the tree. The ML code keeps the\nnodes sorted using the term order. We do not have to push ordering to\nthe HOL level.\\<close>\n\nsubsection \\<open>Distinctness of Nodes\\<close>\n\n\nprimrec set_of :: \"'a tree \\<Rightarrow> 'a set\"\nwhere\n  \"set_of Tip = {}\"\n| \"set_of (Node l x d r) = (if d then {} else {x}) \\<union> set_of l \\<union> set_of r\"\n\nprimrec all_distinct :: \"'a tree \\<Rightarrow> bool\"\nwhere\n  \"all_distinct Tip = True\"\n| \"all_distinct (Node l x d r) =\n    ((d \\<or> (x \\<notin> set_of l \\<and> x \\<notin> set_of r)) \\<and> \n      set_of l \\<inter> set_of r = {} \\<and>\n      all_distinct l \\<and> all_distinct r)\"\n\ntext \\<open>Given a binary tree @{term \"t\"} for which \n@{const all_distinct} holds, given two different nodes contained in the tree,\nwe want to write a ML function that generates a logarithmic\ncertificate that the content of the nodes is distinct. We use the\nfollowing lemmas to achieve this.\\<close> \n\nlemma all_distinct_left: \"all_distinct (Node l x b r) \\<Longrightarrow> all_distinct l\"\n  by simp\n\nlemma all_distinct_right: \"all_distinct (Node l x b r) \\<Longrightarrow> all_distinct r\"\n  by simp\n\nlemma distinct_left: \"all_distinct (Node l x False r) \\<Longrightarrow> y \\<in> set_of l \\<Longrightarrow> x \\<noteq> y\"\n  by auto\n\nlemma distinct_right: \"all_distinct (Node l x False r) \\<Longrightarrow> y \\<in> set_of r \\<Longrightarrow> x \\<noteq> y\"\n  by auto\n\nlemma distinct_left_right:\n    \"all_distinct (Node l z b r) \\<Longrightarrow> x \\<in> set_of l \\<Longrightarrow> y \\<in> set_of r \\<Longrightarrow> x \\<noteq> y\"\n  by auto\n\nlemma in_set_root: \"x \\<in> set_of (Node l x False r)\"\n  by simp\n\nlemma in_set_left: \"y \\<in> set_of l \\<Longrightarrow>  y \\<in> set_of (Node l x False r)\"\n  by simp\n\nlemma in_set_right: \"y \\<in> set_of r \\<Longrightarrow>  y \\<in> set_of (Node l x False r)\"\n  by simp\n\nlemma swap_neq: \"x \\<noteq> y \\<Longrightarrow> y \\<noteq> x\"\n  by blast\n\nlemma neq_to_eq_False: \"x\\<noteq>y \\<Longrightarrow> (x=y)\\<equiv>False\"\n  by simp\n\nsubsection \\<open>Containment of Trees\\<close>\n\ntext \\<open>When deriving a state space from other ones, we create a new\nname tree which contains all the names of the parent state spaces and\nassume the predicate @{const all_distinct}. We then prove that the new\nlocale interprets all parent locales. Hence we have to show that the\nnew distinctness assumption on all names implies the distinctness\nassumptions of the parent locales. This proof is implemented in ML. We\ndo this efficiently by defining a kind of containment check of trees\nby ``subtraction''.  We subtract the parent tree from the new tree. If\nthis succeeds we know that @{const all_distinct} of the new tree\nimplies @{const all_distinct} of the parent tree.  The resulting\ncertificate is of the order @{term \"n * log(m)\"} where @{term \"n\"} is\nthe size of the (smaller) parent tree and @{term \"m\"} the size of the\n(bigger) new tree.\\<close>\n\n\nprimrec delete :: \"'a \\<Rightarrow> 'a tree \\<Rightarrow> 'a tree option\"\nwhere\n  \"delete x Tip = None\"\n| \"delete x (Node l y d r) = (case delete x l of\n                                Some l' \\<Rightarrow>\n                                 (case delete x r of \n                                    Some r' \\<Rightarrow> Some (Node l' y (d \\<or> (x=y)) r')\n                                  | None \\<Rightarrow> Some (Node l' y (d \\<or> (x=y)) r))\n                               | None \\<Rightarrow>\n                                  (case delete x r of \n                                     Some r' \\<Rightarrow> Some (Node l y (d \\<or> (x=y)) r')\n                                   | None \\<Rightarrow> if x=y \\<and> \\<not>d then Some (Node l y True r)\n                                             else None))\"\n\n\nlemma delete_Some_set_of: \"delete x t = Some t' \\<Longrightarrow> set_of t' \\<subseteq> set_of t\"\nproof (induct t arbitrary: t')\n  case Tip thus ?case by simp\nnext\n  case (Node l y d r)\n  have del: \"delete x (Node l y d r) = Some t'\" by fact\n  show ?case\n  proof (cases \"delete x l\")\n    case (Some l')\n    note x_l_Some = this\n    with Node.hyps\n    have l'_l: \"set_of l' \\<subseteq> set_of l\"\n      by simp\n    show ?thesis\n    proof (cases \"delete x r\")\n      case (Some r')\n      with Node.hyps\n      have \"set_of r' \\<subseteq> set_of r\"\n        by simp\n      with l'_l Some x_l_Some del\n      show ?thesis\n        by (auto split: if_split_asm)\n    next\n      case None\n      with l'_l Some x_l_Some del\n      show ?thesis\n        by (fastforce split: if_split_asm)\n    qed\n  next\n    case None\n    note x_l_None = this\n    show ?thesis\n    proof (cases \"delete x r\")\n      case (Some r')\n      with Node.hyps\n      have \"set_of r' \\<subseteq> set_of r\"\n        by simp\n      with Some x_l_None del\n      show ?thesis\n        by (fastforce split: if_split_asm)\n    next\n      case None\n      with x_l_None del\n      show ?thesis\n        by (fastforce split: if_split_asm)\n    qed\n  qed\nqed\n\nlemma delete_Some_all_distinct:\n  \"delete x t = Some t' \\<Longrightarrow> all_distinct t \\<Longrightarrow> all_distinct t'\"\nproof (induct t arbitrary: t')\n  case Tip thus ?case by simp\nnext\n  case (Node l y d r)\n  have del: \"delete x (Node l y d r) = Some t'\" by fact\n  have \"all_distinct (Node l y d r)\" by fact\n  then obtain\n    dist_l: \"all_distinct l\" and\n    dist_r: \"all_distinct r\" and\n    d: \"d \\<or> (y \\<notin> set_of l \\<and> y \\<notin> set_of r)\" and\n    dist_l_r: \"set_of l \\<inter> set_of r = {}\"\n    by auto\n  show ?case\n  proof (cases \"delete x l\")\n    case (Some l')\n    note x_l_Some = this\n    from Node.hyps (1) [OF Some dist_l]\n    have dist_l': \"all_distinct l'\"\n      by simp\n    from delete_Some_set_of [OF x_l_Some]\n    have l'_l: \"set_of l' \\<subseteq> set_of l\".\n    show ?thesis\n    proof (cases \"delete x r\")\n      case (Some r')\n      from Node.hyps (2) [OF Some dist_r]\n      have dist_r': \"all_distinct r'\"\n        by simp\n      from delete_Some_set_of [OF Some]\n      have \"set_of r' \\<subseteq> set_of r\".\n      \n      with dist_l' dist_r' l'_l Some x_l_Some del d dist_l_r\n      show ?thesis\n        by fastforce\n    next\n      case None\n      with l'_l dist_l'  x_l_Some del d dist_l_r dist_r\n      show ?thesis\n        by fastforce\n    qed\n  next\n    case None\n    note x_l_None = this\n    show ?thesis\n    proof (cases \"delete x r\")\n      case (Some r')\n      with Node.hyps (2) [OF Some dist_r]\n      have dist_r': \"all_distinct r'\"\n        by simp\n      from delete_Some_set_of [OF Some]\n      have \"set_of r' \\<subseteq> set_of r\".\n      with Some dist_r' x_l_None del dist_l d dist_l_r\n      show ?thesis\n        by fastforce\n    next\n      case None\n      with x_l_None del dist_l dist_r d dist_l_r\n      show ?thesis\n        by (fastforce split: if_split_asm)\n    qed\n  qed\nqed\n\nlemma delete_None_set_of_conv: \"delete x t = None = (x \\<notin> set_of t)\"\nproof (induct t)\n  case Tip thus ?case by simp\nnext\n  case (Node l y d r)\n  thus ?case\n    by (auto split: option.splits)\nqed\n\nlemma delete_Some_x_set_of:\n  \"delete x t = Some t' \\<Longrightarrow> x \\<in> set_of t \\<and> x \\<notin> set_of t'\"\nproof (induct t arbitrary: t')\n  case Tip thus ?case by simp\nnext\n  case (Node l y d r)\n  have del: \"delete x (Node l y d r) = Some t'\" by fact\n  show ?case\n  proof (cases \"delete x l\")\n    case (Some l')\n    note x_l_Some = this\n    from Node.hyps (1) [OF Some]\n    obtain x_l: \"x \\<in> set_of l\" \"x \\<notin> set_of l'\"\n      by simp\n    show ?thesis\n    proof (cases \"delete x r\")\n      case (Some r')\n      from Node.hyps (2) [OF Some]\n      obtain x_r: \"x \\<in> set_of r\" \"x \\<notin> set_of r'\"\n        by simp\n      from x_r x_l Some x_l_Some del \n      show ?thesis\n        by (clarsimp split: if_split_asm)\n    next\n      case None\n      then have \"x \\<notin> set_of r\"\n        by (simp add: delete_None_set_of_conv)\n      with x_l None x_l_Some del\n      show ?thesis\n        by (clarsimp split: if_split_asm)\n    qed\n  next\n    case None\n    note x_l_None = this\n    then have x_notin_l: \"x \\<notin> set_of l\"\n      by (simp add: delete_None_set_of_conv)\n    show ?thesis\n    proof (cases \"delete x r\")\n      case (Some r')\n      from Node.hyps (2) [OF Some]\n      obtain x_r: \"x \\<in> set_of r\" \"x \\<notin> set_of r'\"\n        by simp\n      from x_r x_notin_l Some x_l_None del \n      show ?thesis\n        by (clarsimp split: if_split_asm)\n    next\n      case None\n      then have \"x \\<notin> set_of r\"\n        by (simp add: delete_None_set_of_conv)\n      with None x_l_None x_notin_l del\n      show ?thesis\n        by (clarsimp split: if_split_asm)\n    qed\n  qed\nqed\n\n\nprimrec subtract :: \"'a tree \\<Rightarrow> 'a tree \\<Rightarrow> 'a tree option\"\nwhere\n  \"subtract Tip t = Some t\"\n| \"subtract (Node l x b r) t =\n     (case delete x t of\n        Some t' \\<Rightarrow> (case subtract l t' of \n                     Some t'' \\<Rightarrow> subtract r t''\n                    | None \\<Rightarrow> None)\n       | None \\<Rightarrow> None)\"\n\nlemma subtract_Some_set_of_res: \n  \"subtract t\\<^sub>1 t\\<^sub>2 = Some t \\<Longrightarrow> set_of t \\<subseteq> set_of t\\<^sub>2\"\nproof (induct t\\<^sub>1 arbitrary: t\\<^sub>2 t)\n  case Tip thus ?case by simp\nnext\n  case (Node l x b r)\n  have sub: \"subtract (Node l x b r) t\\<^sub>2 = Some t\" by fact\n  show ?case\n  proof (cases \"delete x t\\<^sub>2\")\n    case (Some t\\<^sub>2')\n    note del_x_Some = this\n    from delete_Some_set_of [OF Some] \n    have t2'_t2: \"set_of t\\<^sub>2' \\<subseteq> set_of t\\<^sub>2\" .\n    show ?thesis\n    proof (cases \"subtract l t\\<^sub>2'\")\n      case (Some t\\<^sub>2'')\n      note sub_l_Some = this\n      from Node.hyps (1) [OF Some] \n      have t2''_t2': \"set_of t\\<^sub>2'' \\<subseteq> set_of t\\<^sub>2'\" .\n      show ?thesis\n      proof (cases \"subtract r t\\<^sub>2''\")\n        case (Some t\\<^sub>2''')\n        from Node.hyps (2) [OF Some ] \n        have \"set_of t\\<^sub>2''' \\<subseteq> set_of t\\<^sub>2''\" .\n        with Some sub_l_Some del_x_Some sub t2''_t2' t2'_t2\n        show ?thesis\n          by simp\n      next\n        case None\n        with del_x_Some sub_l_Some sub\n        show ?thesis\n          by simp\n      qed\n    next\n      case None\n      with del_x_Some sub \n      show ?thesis\n        by simp\n    qed\n  next\n    case None\n    with sub show ?thesis by simp\n  qed\nqed\n\nlemma subtract_Some_set_of: \n  \"subtract t\\<^sub>1 t\\<^sub>2 = Some t \\<Longrightarrow> set_of t\\<^sub>1 \\<subseteq> set_of t\\<^sub>2\"\nproof (induct t\\<^sub>1 arbitrary: t\\<^sub>2 t)\n  case Tip thus ?case by simp\nnext\n  case (Node l x d r)\n  have sub: \"subtract (Node l x d r) t\\<^sub>2 = Some t\" by fact\n  show ?case\n  proof (cases \"delete x t\\<^sub>2\")\n    case (Some t\\<^sub>2')\n    note del_x_Some = this\n    from delete_Some_set_of [OF Some] \n    have t2'_t2: \"set_of t\\<^sub>2' \\<subseteq> set_of t\\<^sub>2\" .\n    from delete_None_set_of_conv [of x t\\<^sub>2] Some\n    have x_t2: \"x \\<in> set_of t\\<^sub>2\"\n      by simp\n    show ?thesis\n    proof (cases \"subtract l t\\<^sub>2'\")\n      case (Some t\\<^sub>2'')\n      note sub_l_Some = this\n      from Node.hyps (1) [OF Some] \n      have l_t2': \"set_of l \\<subseteq> set_of t\\<^sub>2'\" .\n      from subtract_Some_set_of_res [OF Some]\n      have t2''_t2': \"set_of t\\<^sub>2'' \\<subseteq> set_of t\\<^sub>2'\" .\n      show ?thesis\n      proof (cases \"subtract r t\\<^sub>2''\")\n        case (Some t\\<^sub>2''')\n        from Node.hyps (2) [OF Some ] \n        have r_t\\<^sub>2'': \"set_of r \\<subseteq> set_of t\\<^sub>2''\" .\n        from Some sub_l_Some del_x_Some sub r_t\\<^sub>2'' l_t2' t2'_t2 t2''_t2' x_t2\n        show ?thesis\n          by auto\n      next\n        case None\n        with del_x_Some sub_l_Some sub\n        show ?thesis\n          by simp\n      qed\n    next\n      case None\n      with del_x_Some sub \n      show ?thesis\n        by simp\n    qed\n  next\n    case None\n    with sub show ?thesis by simp\n  qed\nqed\n\nlemma subtract_Some_all_distinct_res: \n  \"subtract t\\<^sub>1 t\\<^sub>2 = Some t \\<Longrightarrow> all_distinct t\\<^sub>2 \\<Longrightarrow> all_distinct t\"\nproof (induct t\\<^sub>1 arbitrary: t\\<^sub>2 t)\n  case Tip thus ?case by simp\nnext\n  case (Node l x d r)\n  have sub: \"subtract (Node l x d r) t\\<^sub>2 = Some t\" by fact\n  have dist_t2: \"all_distinct t\\<^sub>2\" by fact\n  show ?case\n  proof (cases \"delete x t\\<^sub>2\")\n    case (Some t\\<^sub>2')\n    note del_x_Some = this\n    from delete_Some_all_distinct [OF Some dist_t2] \n    have dist_t2': \"all_distinct t\\<^sub>2'\" .\n    show ?thesis\n    proof (cases \"subtract l t\\<^sub>2'\")\n      case (Some t\\<^sub>2'')\n      note sub_l_Some = this\n      from Node.hyps (1) [OF Some dist_t2'] \n      have dist_t2'': \"all_distinct t\\<^sub>2''\" .\n      show ?thesis\n      proof (cases \"subtract r t\\<^sub>2''\")\n        case (Some t\\<^sub>2''')\n        from Node.hyps (2) [OF Some dist_t2''] \n        have dist_t2''': \"all_distinct t\\<^sub>2'''\" .\n        from Some sub_l_Some del_x_Some sub \n             dist_t2'''\n        show ?thesis\n          by simp\n      next\n        case None\n        with del_x_Some sub_l_Some sub\n        show ?thesis\n          by simp\n      qed\n    next\n      case None\n      with del_x_Some sub \n      show ?thesis\n        by simp\n    qed\n  next\n    case None\n    with sub show ?thesis by simp\n  qed\nqed\n\n\nlemma subtract_Some_dist_res: \n  \"subtract t\\<^sub>1 t\\<^sub>2 = Some t \\<Longrightarrow> set_of t\\<^sub>1 \\<inter> set_of t = {}\"\nproof (induct t\\<^sub>1 arbitrary: t\\<^sub>2 t)\n  case Tip thus ?case by simp\nnext\n  case (Node l x d r)\n  have sub: \"subtract (Node l x d r) t\\<^sub>2 = Some t\" by fact\n  show ?case\n  proof (cases \"delete x t\\<^sub>2\")\n    case (Some t\\<^sub>2')\n    note del_x_Some = this\n    from delete_Some_x_set_of [OF Some]\n    obtain x_t2: \"x \\<in> set_of t\\<^sub>2\" and x_not_t2': \"x \\<notin> set_of t\\<^sub>2'\"\n      by simp\n    from delete_Some_set_of [OF Some]\n    have t2'_t2: \"set_of t\\<^sub>2' \\<subseteq> set_of t\\<^sub>2\" .\n    show ?thesis\n    proof (cases \"subtract l t\\<^sub>2'\")\n      case (Some t\\<^sub>2'')\n      note sub_l_Some = this\n      from Node.hyps (1) [OF Some ] \n      have dist_l_t2'': \"set_of l \\<inter> set_of t\\<^sub>2'' = {}\".\n      from subtract_Some_set_of_res [OF Some]\n      have t2''_t2': \"set_of t\\<^sub>2'' \\<subseteq> set_of t\\<^sub>2'\" .\n      show ?thesis\n      proof (cases \"subtract r t\\<^sub>2''\")\n        case (Some t\\<^sub>2''')\n        from Node.hyps (2) [OF Some] \n        have dist_r_t2''': \"set_of r \\<inter> set_of t\\<^sub>2''' = {}\" .\n        from subtract_Some_set_of_res [OF Some]\n        have t2'''_t2'': \"set_of t\\<^sub>2''' \\<subseteq> set_of t\\<^sub>2''\".\n        \n        from Some sub_l_Some del_x_Some sub t2'''_t2'' dist_l_t2'' dist_r_t2'''\n             t2''_t2' t2'_t2 x_not_t2'\n        show ?thesis\n          by auto\n      next\n        case None\n        with del_x_Some sub_l_Some sub\n        show ?thesis\n          by simp\n      qed\n    next\n      case None\n      with del_x_Some sub \n      show ?thesis\n        by simp\n    qed\n  next\n    case None\n    with sub show ?thesis by simp\n  qed\nqed\n        \nlemma subtract_Some_all_distinct:\n  \"subtract t\\<^sub>1 t\\<^sub>2 = Some t \\<Longrightarrow> all_distinct t\\<^sub>2 \\<Longrightarrow> all_distinct t\\<^sub>1\"\nproof (induct t\\<^sub>1 arbitrary: t\\<^sub>2 t)\n  case Tip thus ?case by simp\nnext\n  case (Node l x d r)\n  have sub: \"subtract (Node l x d r) t\\<^sub>2 = Some t\" by fact\n  have dist_t2: \"all_distinct t\\<^sub>2\" by fact\n  show ?case\n  proof (cases \"delete x t\\<^sub>2\")\n    case (Some t\\<^sub>2')\n    note del_x_Some = this\n    from delete_Some_all_distinct [OF Some dist_t2 ] \n    have dist_t2': \"all_distinct t\\<^sub>2'\" .\n    from delete_Some_set_of [OF Some]\n    have t2'_t2: \"set_of t\\<^sub>2' \\<subseteq> set_of t\\<^sub>2\" .\n    from delete_Some_x_set_of [OF Some]\n    obtain x_t2: \"x \\<in> set_of t\\<^sub>2\" and x_not_t2': \"x \\<notin> set_of t\\<^sub>2'\"\n      by simp\n\n    show ?thesis\n    proof (cases \"subtract l t\\<^sub>2'\")\n      case (Some t\\<^sub>2'')\n      note sub_l_Some = this\n      from Node.hyps (1) [OF Some dist_t2' ] \n      have dist_l: \"all_distinct l\" .\n      from subtract_Some_all_distinct_res [OF Some dist_t2'] \n      have dist_t2'': \"all_distinct t\\<^sub>2''\" .\n      from subtract_Some_set_of [OF Some]\n      have l_t2': \"set_of l \\<subseteq> set_of t\\<^sub>2'\" .\n      from subtract_Some_set_of_res [OF Some]\n      have t2''_t2': \"set_of t\\<^sub>2'' \\<subseteq> set_of t\\<^sub>2'\" .\n      from subtract_Some_dist_res [OF Some]\n      have dist_l_t2'': \"set_of l \\<inter> set_of t\\<^sub>2'' = {}\".\n      show ?thesis\n      proof (cases \"subtract r t\\<^sub>2''\")\n        case (Some t\\<^sub>2''')\n        from Node.hyps (2) [OF Some dist_t2''] \n        have dist_r: \"all_distinct r\" .\n        from subtract_Some_set_of [OF Some]\n        have r_t2'': \"set_of r \\<subseteq> set_of t\\<^sub>2''\" .\n        from subtract_Some_dist_res [OF Some]\n        have dist_r_t2''': \"set_of r \\<inter> set_of t\\<^sub>2''' = {}\".\n\n        from dist_l dist_r Some sub_l_Some del_x_Some r_t2'' l_t2' x_t2 x_not_t2' \n             t2''_t2' dist_l_t2'' dist_r_t2'''\n        show ?thesis\n          by auto\n      next\n        case None\n        with del_x_Some sub_l_Some sub\n        show ?thesis\n          by simp\n      qed\n    next\n      case None\n      with del_x_Some sub \n      show ?thesis\n        by simp\n    qed\n  next\n    case None\n    with sub show ?thesis by simp\n  qed\nqed\n\n\nlemma delete_left:\n  assumes dist: \"all_distinct (Node l y d r)\" \n  assumes del_l: \"delete x l = Some l'\"\n  shows \"delete x (Node l y d r) = Some (Node l' y d r)\"\nproof -\n  from delete_Some_x_set_of [OF del_l]\n  obtain x: \"x \\<in> set_of l\"\n    by simp\n  with dist \n  have \"delete x r = None\"\n    by (cases \"delete x r\") (auto dest:delete_Some_x_set_of)\n\n  with x \n  show ?thesis\n    using del_l dist\n    by (auto split: option.splits)\nqed\n\nlemma delete_right:\n  assumes dist: \"all_distinct (Node l y d r)\" \n  assumes del_r: \"delete x r = Some r'\"\n  shows \"delete x (Node l y d r) = Some (Node l y d r')\"\nproof -\n  from delete_Some_x_set_of [OF del_r]\n  obtain x: \"x \\<in> set_of r\"\n    by simp\n  with dist \n  have \"delete x l = None\"\n    by (cases \"delete x l\") (auto dest:delete_Some_x_set_of)\n\n  with x \n  show ?thesis\n    using del_r dist\n    by (auto split: option.splits)\nqed\n\nlemma delete_root: \n  assumes dist: \"all_distinct (Node l x False r)\" \n  shows \"delete x (Node l x False r) = Some (Node l x True r)\"\nproof -\n  from dist have \"delete x r = None\"\n    by (cases \"delete x r\") (auto dest:delete_Some_x_set_of)\n  moreover\n  from dist have \"delete x l = None\"\n    by (cases \"delete x l\") (auto dest:delete_Some_x_set_of)\n  ultimately show ?thesis\n    using dist\n       by (auto split: option.splits)\nqed               \n\nlemma subtract_Node:\n assumes del: \"delete x t = Some t'\"                                \n assumes sub_l: \"subtract l t' = Some t''\"\n assumes sub_r: \"subtract r t'' = Some t'''\"\n shows \"subtract (Node l x False r) t = Some t'''\"\nusing del sub_l sub_r\nby simp\n\nlemma subtract_Tip: \"subtract Tip t = Some t\"\n  by simp\n \ntext \\<open>Now we have all the theorems in place that are needed for the\ncertificate generating ML functions.\\<close>\n\nML_file \"distinct_tree_prover.ML\"\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/Statespace/DistinctTreeProver.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.905989815306765, "lm_q2_score": 0.8128673201042492, "lm_q1q2_score": 0.7364495132101538}}
{"text": "header{*Sum of divisors function*}\n\ntheory Sigma\nimports PerfectBasics \"~~/src/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) <-> divisors p = {1,p} & p>1\"\nby (auto simp add: divisors_def prime_nat_def)\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: setsum_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 setsum_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)\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 = setsum (%x. x) {(op ^ p) m |m . m<= n}\" by auto\n  also have \"... = setsum (%x. x) ((op ^ p)`{m . m<= n})\"\n    by(rule seteq_imp_setsumeq) auto\n  moreover with p have \"inj_on (op ^p) {m . m<=n}\"\n    by (simp add: inj_on_def)\n  ultimately have \"?l = setsum (op ^ p) {m . m<=n}\"\n    by (simp add: setsum.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_def)\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\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 `prime p` show \"x : {a * b |a b. a dvd p ^ n & b dvd m}\"\n      by (auto simp add: divides_primepow)\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 `prime p` by auto (metis assms divides_primepow)\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_nat 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 (auto simp add: coprime_exp_nat gcd_commute_nat)\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_def)\n  also have \"... = (\\<Sum> {a*b| a b . a dvd (p^n) & b dvd m})\"\n    by(rule seteq_imp_setsumeq,rule rewrite_for_sigma_semimultiplicative[OF p])\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", "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/Sigma.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178919837706, "lm_q2_score": 0.8104788995148792, "lm_q1q2_score": 0.7364156291745357}}
{"text": "(**        Algebra7  \n                            author Hidetsune Kobayashi\n                            Group You Santo\n                            Department of Mathematics\n                            Nihon University\n                            h_koba@math.cst.nihon-u.ac.jp\n                            May 3, 2004.\n                            April 6, 2007 (revised)\n\n   chapter 5. Modules\n    section 3.   a module over two rings \n    section 4.   eSum and Generators\n     subsection 4-1. sum up coefficients\n     subsection 4-2. free generators \n   **)\n\ntheory Algebra7 imports Algebra6 begin\n\nchapter \"Modules\"\n\nsection \"Basic properties of Modules\"\n\nrecord ('a, 'b) Module = \"'a aGroup\" +\n  sprod  :: \"'b \\<Rightarrow> 'a \\<Rightarrow> 'a\" (infixl \"\\<cdot>\\<^sub>s\\<index>\" 76)\n\nlocale Module = aGroup M for M (structure) +\n  fixes R (structure)\n  assumes  sc_Ring: \"Ring R\" \n  and  sprod_closed :\n      \"\\<lbrakk> a \\<in> carrier R; m \\<in> carrier M\\<rbrakk> \\<Longrightarrow> a \\<cdot>\\<^sub>s m \\<in> carrier M\" \n    and sprod_l_distr:\n      \"\\<lbrakk>a \\<in> carrier R; b \\<in> carrier R; m \\<in> carrier M\\<rbrakk> \\<Longrightarrow>\n       (a \\<plusminus>\\<^bsub>R\\<^esub> b) \\<cdot>\\<^sub>s m = a \\<cdot>\\<^sub>s m \\<plusminus>\\<^bsub>M\\<^esub> b \\<cdot>\\<^sub>s m\" \n    and sprod_r_distr:\n      \"\\<lbrakk> a \\<in> carrier R; m \\<in> carrier M; n \\<in> carrier M \\<rbrakk> \\<Longrightarrow>\n      a \\<cdot>\\<^sub>s (m \\<plusminus>\\<^bsub>M\\<^esub> n) = a \\<cdot>\\<^sub>s m \\<plusminus>\\<^bsub>M\\<^esub> a \\<cdot>\\<^sub>s n\"\n    and sprod_assoc:\n      \"\\<lbrakk> a \\<in> carrier R; b \\<in> carrier R; m \\<in> carrier M \\<rbrakk> \\<Longrightarrow>\n      (a \\<cdot>\\<^sub>r\\<^bsub>R\\<^esub> b) \\<cdot>\\<^sub>s m = a \\<cdot>\\<^sub>s (b \\<cdot>\\<^sub>s m)\"  \n    and sprod_one:\n      \"m \\<in> carrier M \\<Longrightarrow> (1\\<^sub>r\\<^bsub>R\\<^esub>) \\<cdot>\\<^sub>s m = m\" \n\ndefinition \n  submodule :: \"[('b, 'm) Ring_scheme, ('a, 'b, 'c) Module_scheme, 'a set] \\<Rightarrow>\n            bool\" where\n  \"submodule R A H \\<longleftrightarrow> H \\<subseteq> carrier A \\<and> A +> H \\<and> (\\<forall>a. \\<forall>m. \n                     (a \\<in> carrier R \\<and> m \\<in> H) \\<longrightarrow> (sprod A a m) \\<in> H)\"\n\ndefinition\n  mdl :: \"[('a, 'b, 'm) Module_scheme, 'a set] \\<Rightarrow> ('a, 'b) Module\" where\n  \"mdl M H = \\<lparr>carrier = H, pop = pop M, mop = mop M, zero = zero M,\n    sprod = \\<lambda>a. \\<lambda>x\\<in>H. sprod M a x\\<rparr>\" \n\nabbreviation\n  MODULE  (infixl \"module\" 58) where\n \"R module M == Module M R\"\n \n\nlemma (in Module) module_is_ag: \"aGroup M\" ..\n\nlemma (in Module) module_inc_zero:\" \\<zero>\\<^bsub>M\\<^esub> \\<in> carrier M\"\napply (simp add:ag_inc_zero) (** type of M is ('c, 'a, 'd) Module_scheme **)\ndone                         (** type of M is (?'b, ?'b, ?'z) Module_scheme **)\n\nlemma (in Module) submodule_subset:\"submodule R M H \\<Longrightarrow> H \\<subseteq> carrier M\"\napply (simp add:submodule_def)\ndone\n\nlemma (in Module) submodule_asubg:\"submodule R M H \\<Longrightarrow> M +> H\"\nby (simp add:submodule_def)\n\nlemma (in Module) submodule_subset1:\"\\<lbrakk>submodule R M H; h \\<in> H\\<rbrakk> \\<Longrightarrow>\n                            h \\<in> carrier M\"\napply (simp add:submodule_def)\napply (erule conjE)+\napply (simp add:subsetD)\ndone\n\nlemma (in Module) submodule_inc_0:\"submodule R M H \\<Longrightarrow>\n                                           \\<zero>\\<^bsub>M\\<^esub> \\<in> H\" \napply (simp add:submodule_def, (erule conjE)+)\napply (rule asubg_inc_zero, assumption+)\ndone\n\nlemma (in Module) sc_un:\" m \\<in> carrier M \\<Longrightarrow> 1\\<^sub>r\\<^bsub>R\\<^esub> \\<cdot>\\<^sub>s m = m\"\napply (simp add:sprod_one)\ndone\n\nlemma (in Module) sc_mem:\"\\<lbrakk>a \\<in> carrier R; m \\<in> carrier M\\<rbrakk> \\<Longrightarrow>\n           a \\<cdot>\\<^sub>s m \\<in> carrier M\"\napply (simp add:sprod_closed)\ndone\n\nlemma (in Module) submodule_sc_closed:\"\\<lbrakk>submodule R M H; \n a \\<in> carrier R; h \\<in> H\\<rbrakk> \\<Longrightarrow>  a \\<cdot>\\<^sub>s h \\<in> H\"\napply (simp add:submodule_def)\ndone\n\nlemma (in Module) sc_assoc:\"\\<lbrakk>a \\<in> carrier R; b \\<in> carrier R; \n m \\<in> carrier M\\<rbrakk> \\<Longrightarrow> (a \\<cdot>\\<^sub>r\\<^bsub>R\\<^esub> b) \\<cdot>\\<^sub>s m =  a \\<cdot>\\<^sub>s ( b \\<cdot>\\<^sub>s m)\"\napply (simp add:sprod_assoc)\ndone\n\nlemma (in Module) sc_l_distr:\"\\<lbrakk>a \\<in> carrier R; b \\<in> carrier R; \n m \\<in> carrier M\\<rbrakk> \\<Longrightarrow> (a \\<plusminus>\\<^bsub>R\\<^esub> b)\\<cdot>\\<^sub>s m = a \\<cdot>\\<^sub>s m \\<plusminus>  b \\<cdot>\\<^sub>s m\"\napply (simp add:sprod_l_distr)\ndone\n\nlemma (in Module) sc_r_distr:\"\\<lbrakk>a \\<in> carrier R; m \\<in> carrier M; n \\<in> carrier M\\<rbrakk> \\<Longrightarrow>\n                 a \\<cdot>\\<^sub>s (m \\<plusminus> n) = a \\<cdot>\\<^sub>s m \\<plusminus>  a \\<cdot>\\<^sub>s n\"\napply (simp add:sprod_r_distr)\ndone\n\n\n\nlemma (in Module) sc_a_0:\"a \\<in> carrier R \\<Longrightarrow> a \\<cdot>\\<^sub>s \\<zero>  = \\<zero>\"\napply (cut_tac ag_inc_zero,\n       frule sc_r_distr[of a \\<zero> \\<zero>], assumption+,\n       frule sc_mem [of a \\<zero>], assumption+)\napply (simp add:ag_l_zero, frule sym,\n       thin_tac \"a \\<cdot>\\<^sub>s \\<zero> = a \\<cdot>\\<^sub>s \\<zero> \\<plusminus> a \\<cdot>\\<^sub>s \\<zero>\")\napply (frule ag_eq_sol1 [of \"a \\<cdot>\\<^sub>s \\<zero>\" \"a \\<cdot>\\<^sub>s \\<zero>\" \"a \\<cdot>\\<^sub>s \\<zero>\"], assumption+,   \n       simp add:ag_l_inv1)\ndone\n\nlemma (in Module) sc_minus_am:\"\\<lbrakk>a \\<in> carrier R; m \\<in> carrier M\\<rbrakk>\n                     \\<Longrightarrow> -\\<^sub>a (a \\<cdot>\\<^sub>s m) = a \\<cdot>\\<^sub>s (-\\<^sub>a m)\"\napply (frule ag_mOp_closed [of m],\n       frule sc_r_distr[of a m \"-\\<^sub>a m\"], assumption+,\n       simp add:ag_r_inv1,\n       simp add:sc_a_0, frule sym,\n       thin_tac \"\\<zero> = a \\<cdot>\\<^sub>s m \\<plusminus> a \\<cdot>\\<^sub>s (-\\<^sub>a m)\")\n apply (frule sc_mem [of a m], assumption+,\n        frule sc_mem [of a \"-\\<^sub>a m\"], assumption+,\n        frule ag_eq_sol1 [of \"a \\<cdot>\\<^sub>s m\" \"a \\<cdot>\\<^sub>s (-\\<^sub>a m)\" \"\\<zero>\"], assumption+,\n        simp add:ag_inc_zero, assumption)\n apply (frule ag_mOp_closed [of \"a \\<cdot>\\<^sub>s m\"],\n        simp add:ag_r_zero)\ndone\n\nlemma (in Module) sc_minus_am1:\"\\<lbrakk>a \\<in> carrier R; m \\<in> carrier M\\<rbrakk>\n            \\<Longrightarrow> -\\<^sub>a (a \\<cdot>\\<^sub>s m) = (-\\<^sub>a\\<^bsub>R\\<^esub> a) \\<cdot>\\<^sub>s m\"\napply (cut_tac sc_Ring, frule Ring.ring_is_ag,\n       frule aGroup.ag_mOp_closed [of R a], assumption+,\n       frule sc_l_distr[of a \"-\\<^sub>a\\<^bsub>R\\<^esub> a\" m], assumption+,\n       simp add:aGroup.ag_r_inv1 [of \"R\"],\n       simp add:sc_0_m, frule sym) apply (\n       thin_tac \"\\<zero> = a \\<cdot>\\<^sub>s m \\<plusminus> (-\\<^sub>a\\<^bsub>R\\<^esub> a) \\<cdot>\\<^sub>s m\")\n apply (frule sc_mem [of a m], assumption+,\n        frule sc_mem [of \"-\\<^sub>a\\<^bsub>R\\<^esub> a\" m], assumption+)\n apply (frule ag_eq_sol1 [of \"a \\<cdot>\\<^sub>s m\" \"(-\\<^sub>a\\<^bsub>R\\<^esub> a) \\<cdot>\\<^sub>s m\" \\<zero>], assumption+,\n        simp add:ag_inc_zero, assumption)\n apply (frule ag_mOp_closed [of \"a \\<cdot>\\<^sub>s m\"])\n apply (thin_tac \"a \\<cdot>\\<^sub>s m \\<plusminus> (-\\<^sub>a\\<^bsub>R\\<^esub> a) \\<cdot>\\<^sub>s m = \\<zero>\",\n        simp add:ag_r_zero)\ndone\n\nlemma (in Module) submodule_0:\"submodule R M {\\<zero>}\" \napply (simp add:submodule_def)\napply (simp add:ag_inc_zero)\napply (simp add:asubg_zero)\napply (rule allI, rule impI)\napply (simp add:sc_a_0)\ndone   \n\nlemma (in Module) submodule_whole:\"submodule R M (carrier M)\" \napply (simp add:submodule_def)\napply (simp add:asubg_whole)\napply ((rule allI)+, rule impI, erule conjE)\napply (simp add:sc_mem)\ndone\n\n\n\nlemma (in Module) submodule_mOp_closed:\"\\<lbrakk>submodule R M H; h \\<in> H\\<rbrakk>\n                 \\<Longrightarrow> -\\<^sub>a h \\<in> H\"\napply (simp add:submodule_def,\n       (erule conjE)+,\n       thin_tac \"\\<forall>a m. a \\<in> carrier R \\<and> m \\<in> H \\<longrightarrow> a \\<cdot>\\<^sub>s m \\<in> H\")\napply (rule asubg_mOp_closed, assumption+)\ndone \n\ndefinition\n  mHom :: \"[('b, 'm) Ring_scheme, ('a, 'b, 'm1) Module_scheme, \n                    ('c, 'b, 'm2) Module_scheme] \\<Rightarrow>  ('a \\<Rightarrow> 'c) set\"\n        (*  (\"(3HOM\\<^sub>_/ _/ _)\" [90, 90, 91]90 ) *) where\n  \"mHom R M N = {f. f \\<in> aHom M N \\<and> \n             (\\<forall>a\\<in>carrier R. \\<forall>m\\<in>carrier M. f (a \\<cdot>\\<^sub>s\\<^bsub>M\\<^esub> m) = a \\<cdot>\\<^sub>s\\<^bsub>N\\<^esub> (f m))}\"\n\ndefinition\n  mimg :: \"[('b, 'm) Ring_scheme, ('a, 'b, 'm1) Module_scheme, \n           ('c, 'b, 'm2) Module_scheme, 'a \\<Rightarrow> 'c] \\<Rightarrow>  ('c, 'b) Module\" \n                 (\"(4mimg\\<^bsub>_ _,_\\<^esub>/ _)\" [88,88,88,89]88) where\n  \"mimg\\<^bsub>R M,N\\<^esub> f = mdl N (f ` (carrier M))\"\n\ndefinition\n  mzeromap :: \"[('a, 'b, 'm1) Module_scheme, ('c, 'b, 'm2) Module_scheme]\n                              \\<Rightarrow> ('a \\<Rightarrow> 'c)\" where\n  \"mzeromap M N = (\\<lambda>x\\<in>carrier M. \\<zero>\\<^bsub>N\\<^esub>)\"\n\nlemma (in Ring) mHom_func:\"f \\<in> mHom R M N \\<Longrightarrow> f \\<in> carrier M \\<rightarrow> carrier N\"\nby (simp add:mHom_def aHom_def)\n\nlemma (in Module) mHom_test:\"\\<lbrakk>R module N; f \\<in> carrier M \\<rightarrow> carrier N \\<and> \n      f \\<in> extensional (carrier M) \\<and> \n     (\\<forall>m\\<in>carrier M. \\<forall>n\\<in>carrier M. f (m \\<plusminus>\\<^bsub>M\\<^esub> n) = f m \\<plusminus>\\<^bsub>N\\<^esub> (f n)) \\<and> \n     (\\<forall>a\\<in>carrier R. \\<forall>m\\<in>carrier M. f (a \\<cdot>\\<^sub>s\\<^bsub>M\\<^esub> m) = a \\<cdot>\\<^sub>s\\<^bsub>N\\<^esub> (f m))\\<rbrakk> \\<Longrightarrow>\n     f \\<in> mHom R M N\"  \napply (simp add:mHom_def)\napply (simp add:aHom_def)\ndone\n\nlemma (in Module) mHom_mem:\"\\<lbrakk>R module N; f \\<in> mHom R M N; m \\<in> carrier M\\<rbrakk>\n \\<Longrightarrow> f m \\<in> carrier N\"\napply (simp add:mHom_def aHom_def) apply (erule conjE)+\napply (simp add:Pi_def)\ndone\n\nlemma (in Module) mHom_add:\"\\<lbrakk>R module N; f \\<in> mHom R M N; m \\<in> carrier M; \n             n \\<in> carrier M\\<rbrakk> \\<Longrightarrow> f (m \\<plusminus> n) = f m \\<plusminus>\\<^bsub>N\\<^esub> (f n)\"\napply (simp add:mHom_def) apply (erule conjE)+\napply (frule Module.module_is_ag [of N R],\n       cut_tac module_is_ag)\napply (simp add:aHom_add)\ndone \n \nlemma (in Module) mHom_0:\"\\<lbrakk>R module N; f \\<in> mHom R M N\\<rbrakk> \\<Longrightarrow> f (\\<zero>) = \\<zero>\\<^bsub>N\\<^esub>\"\napply (simp add:mHom_def, (erule conjE)+,\n       frule Module.module_is_ag [of N],\n       cut_tac module_is_ag)\napply (simp add:aHom_0_0)\ndone\n\nlemma (in Module) mHom_inv:\"\\<lbrakk>R module N; m \\<in> carrier M; f \\<in> mHom R M N\\<rbrakk> \\<Longrightarrow> \n                 f (-\\<^sub>a m) = -\\<^sub>a\\<^bsub>N\\<^esub> (f m)\"\napply (cut_tac module_is_ag,\n       frule Module.module_is_ag [of N])\napply (simp add:mHom_def, (erule conjE)+)\napply (rule aHom_inv_inv, assumption+)\ndone\n\nlemma (in Module) mHom_lin:\"\\<lbrakk>R module N; m \\<in> carrier M; f \\<in> mHom R M N;\n                    a \\<in> carrier R\\<rbrakk> \\<Longrightarrow> f (a \\<cdot>\\<^sub>s m) = a \\<cdot>\\<^sub>s\\<^bsub>N\\<^esub> (f m)\"\napply (simp add:mHom_def)\ndone\n\nlemma (in Module) mker_inc_zero:\n           \"\\<lbrakk>R module N; f \\<in> mHom R M N \\<rbrakk> \\<Longrightarrow> \\<zero> \\<in> (ker\\<^bsub>M,N\\<^esub> f)\" \napply (simp add:ker_def) \napply (simp add:module_inc_zero)\napply (simp add:mHom_0)\ndone\n\nlemma (in Module) mHom_eq_ker:\"\\<lbrakk>R module N; f \\<in> mHom R M N; a \\<in> carrier M; \n      b\\<in> carrier M; a \\<plusminus> (-\\<^sub>a b) \\<in> ker\\<^bsub>M,N\\<^esub> f\\<rbrakk> \\<Longrightarrow> f a = f b\"\napply (simp add:ker_def, erule conjE)\napply (cut_tac module_is_ag,\n       frule aGroup.ag_mOp_closed [of \"M\" \"b\"], assumption+,\n       simp add:mHom_add, simp add:mHom_inv,\n       thin_tac \"aGroup M\")\napply (frule mHom_mem [of N f a], assumption+,\n       frule mHom_mem [of N f b], assumption+,\n       frule Module.module_is_ag[of N]) \napply (subst aGroup.ag_eq_diffzero[of N], assumption+)\ndone  \n\nlemma (in Module) mHom_ker_eq:\"\\<lbrakk>R module N; f \\<in> mHom R M N; a \\<in> carrier M; \n      b\\<in> carrier M; f a = f b\\<rbrakk> \\<Longrightarrow> a \\<plusminus> (-\\<^sub>a b) \\<in> ker\\<^bsub>M,N\\<^esub> f\"\napply (simp add:ker_def)\n apply (frule ag_mOp_closed[of b])\n apply (simp add:ag_pOp_closed)\n apply (simp add:mHom_add mHom_inv)\n apply (frule mHom_mem [of N f b], assumption+)\n apply (frule_tac R = R and M = N in Module.module_is_ag,\n        simp add:aGroup.ag_r_inv1)\ndone\n \nlemma (in Module) mker_submodule:\"\\<lbrakk>R module N; f \\<in> mHom R M N\\<rbrakk> \\<Longrightarrow>\n                                    submodule R M (ker\\<^bsub>M,N\\<^esub> f)\"\napply (cut_tac module_is_ag,\n       frule Module.module_is_ag [of N])\napply (simp add:submodule_def)\napply (rule conjI)\n apply (rule subsetI, simp add:ker_def)\n\napply (rule conjI)\n apply (simp add:mHom_def, (erule conjE)+, simp add:ker_subg)\n\napply ((rule allI)+, rule impI, erule conjE)\n apply (simp add:ker_def, erule conjE)\n apply (simp add:sc_mem)\n apply (subst mHom_lin [of N _ f], assumption+, simp) (* key *)\napply (simp add:Module.sc_a_0[of N])\ndone\n\nlemma (in Module) mker_mzeromap:\"R module N \\<Longrightarrow>\n                         ker\\<^bsub>M,N\\<^esub> (mzeromap M N) = carrier M\"\napply (simp add:ker_def mzeromap_def)\ndone\n\nlemma (in Module) mdl_carrier:\"submodule R M H \\<Longrightarrow> carrier (mdl M H) = H\"\napply (simp add:mdl_def)\ndone \n\nlemma (in Module) mdl_is_ag:\"submodule R M H \\<Longrightarrow> aGroup (mdl M H)\"\napply (cut_tac module_is_ag)\napply (rule aGroup.intro)\n apply (simp add:mdl_def)\n apply (clarsimp simp: submodule_def asubg_pOp_closed)\n\n apply (simp add:mdl_def)\n apply (simp add:submodule_def, (erule conjE)+,\n        frule_tac c = a in subsetD[of H \"carrier M\"], assumption+,\n        frule_tac c = b in subsetD[of H \"carrier M\"], assumption+,\n        frule_tac c = c in subsetD[of H \"carrier M\"], assumption+,\n        simp add:aGroup.ag_pOp_assoc)\n\n apply (simp add:submodule_def, (erule conjE)+,\n        simp add:mdl_def,\n        frule_tac c = a in subsetD[of H \"carrier M\"], assumption+,\n        frule_tac c = b in subsetD[of H \"carrier M\"], assumption+,\n        simp add:aGroup.ag_pOp_commute)\n\n apply (simp add:mdl_def)\n apply (simp add:submodule_def aGroup.asubg_mOp_closed)\n\n apply (simp add:mdl_def,\n        simp add:submodule_def, (erule conjE)+,\n        frule_tac c = a in subsetD[of H \"carrier M\"], assumption+,\n        rule aGroup.ag_l_inv1, assumption+)         \n\n apply (simp add:mdl_def,\n        simp add:submodule_def, (erule conjE)+,\n        simp add:asubg_inc_zero)\n\n apply (simp add:mdl_def, simp add:submodule_def, (erule conjE)+,\n        frule_tac c = a in subsetD[of H \"carrier M\"], assumption+)\n apply (simp add:ag_l_zero)\ndone\n\nlemma (in Module) mdl_is_module:\"submodule R M H \\<Longrightarrow> R module (mdl M H)\" \napply (rule Module.intro)\napply (simp add:mdl_is_ag)\n\napply (rule Module_axioms.intro)\napply (simp add:sc_Ring)\n\napply (simp add:mdl_def)\n apply (simp add:submodule_def) \n\napply (simp add:mdl_def)\n apply (simp add:submodule_def, (erule conjE)+,\n        frule_tac c = m in subsetD[of H \"carrier M\"], assumption+,\n        simp add:sc_l_distr)\n\napply (simp add:mdl_def submodule_def, (erule conjE)+,\n       simp add:asubg_pOp_closed,\n       frule_tac c = m in subsetD[of H \"carrier M\"], assumption+,\n       frule_tac c = n in subsetD[of H \"carrier M\"], assumption+,\n       simp add:sc_r_distr)\napply (simp add:mdl_def submodule_def, (erule conjE)+,\n       frule_tac c = m in subsetD[of H \"carrier M\"], assumption+,\n       simp add:sc_assoc)\napply (simp add:mdl_def submodule_def, (erule conjE)+,\n       frule_tac c = m in subsetD[of H \"carrier M\"], assumption+,\n       simp add:sprod_one)\ndone   \n\nlemma (in Module) submodule_of_mdl:\"\\<lbrakk>submodule R M H; submodule R M N; H \\<subseteq> N\\<rbrakk>\n                   \\<Longrightarrow> submodule R (mdl M N) H\"\napply (subst submodule_def)\n apply (rule conjI, simp add:mdl_def)\n apply (rule conjI)\n apply (rule aGroup.asubg_test[of \"mdl M N\" H])\n apply (frule mdl_is_module[of N],\n        simp add:Module.module_is_ag, simp add:mdl_def)\n apply (simp add:submodule_def[of R M H], (erule conjE)+)\n apply (frule asubg_inc_zero[of H], simp add:nonempty)\n\n apply ((rule ballI)+, simp add:mdl_def)\n apply (simp add:submodule_def[of R M H], (erule conjE)+)\n apply (frule_tac x = b in asubg_mOp_closed[of H], assumption+)\n apply (rule asubg_pOp_closed[of H], assumption+)\n\napply ((rule allI)+, rule impI, erule conjE)\n apply (simp add:mdl_def subsetD)\n apply (simp add:submodule_def[of R M H])\ndone\n\nlemma (in Module) img_set_submodule:\"\\<lbrakk>R module N; f \\<in> mHom R M N\\<rbrakk> \\<Longrightarrow>\n         submodule R N (f ` (carrier M))\"\napply (simp add:submodule_def)\napply (rule conjI)\n apply (rule subsetI)\n apply (simp add:image_def)\n apply (erule bexE, simp, thin_tac \"x = f xa\")\n  apply (simp add:mHom_mem)\napply (rule conjI)\n apply (frule Module.module_is_ag [of N])\n apply (rule aGroup.asubg_test, assumption+)\n apply (rule subsetI) apply (simp add:image_def)\n apply (erule bexE) apply (simp add:mHom_mem)\n apply (cut_tac ag_inc_zero,\n        simp add:mHom_mem,  simp add:nonempty)\n apply ((rule ballI)+, simp add:image_def)\n apply ((erule bexE)+, simp)\n apply (simp add:mHom_inv[THEN sym],\n        frule_tac x = xa in ag_mOp_closed,\n        simp add:mHom_add[THEN sym, of N f],\n        frule_tac x = \"x\" and y = \"-\\<^sub>a xa\" in ag_pOp_closed, assumption+)\n apply blast\n\napply ((rule allI)+, rule impI, erule conjE)\n apply (simp add:image_def, erule bexE, simp)\n apply (simp add:mHom_lin[THEN sym, of N _ f])\n apply (frule_tac a = a and m = x in sc_mem, assumption) \n apply blast \ndone\n\nlemma (in Module) mimg_module:\"\\<lbrakk>R module N; f \\<in> mHom R M N\\<rbrakk> \\<Longrightarrow>\n                                              R module (mimg R M N f)\"\napply (simp add:mimg_def)\napply (rule Module.mdl_is_module[of N R \"f ` (carrier M)\"], assumption)\napply (simp add:img_set_submodule)\ndone\n   \nlemma (in Module) surjec_to_mimg:\"\\<lbrakk>R module N; f \\<in> mHom R M N\\<rbrakk> \\<Longrightarrow>\n                                       surjec\\<^bsub>M, (mimg R M N f)\\<^esub> f\"\napply (simp add:surjec_def)\napply (rule conjI)\n apply (simp add:aHom_def)\n apply (rule conjI)\n apply (simp add:mimg_def mdl_def)\n apply (rule conjI)\n apply (simp add:mHom_def aHom_def restrict_def extensional_def)\n apply ((rule ballI)+, simp add:mimg_def mdl_def, simp add:mHom_add)\napply (simp add:mimg_def mdl_def)\n apply (simp add:surj_to_def image_def)\ndone\n \ndefinition\n  tOp_mHom :: \"[('b, 'm) Ring_scheme, ('a, 'b, 'm1) Module_scheme, \n    ('c, 'b, 'm2) Module_scheme] \\<Rightarrow>  ('a \\<Rightarrow> 'c) \\<Rightarrow> ('a \\<Rightarrow> 'c) \\<Rightarrow> ('a \\<Rightarrow> 'c)\" where\n  \"tOp_mHom R M N f g = (\\<lambda>x \\<in> carrier M. (f x \\<plusminus>\\<^bsub>N\\<^esub> (g x)))\"\n\ndefinition\n  iOp_mHom :: \"[('b, 'm) Ring_scheme, ('a, 'b, 'm1) Module_scheme, \n    ('c, 'b, 'm2) Module_scheme] \\<Rightarrow>  ('a \\<Rightarrow> 'c) \\<Rightarrow> ('a \\<Rightarrow> 'c)\" where\n  \"iOp_mHom R M N f = (\\<lambda>x \\<in> carrier M. (-\\<^sub>a\\<^bsub>N\\<^esub> (f x)))\" \n\ndefinition\n  sprod_mHom ::\"[('b, 'm) Ring_scheme, ('a, 'b, 'm1) Module_scheme, \n    ('c, 'b, 'm2) Module_scheme] \\<Rightarrow> 'b \\<Rightarrow> ('a \\<Rightarrow> 'c) \\<Rightarrow> ('a \\<Rightarrow> 'c)\" where\n  \"sprod_mHom R M N a f = (\\<lambda>x \\<in> carrier M. a \\<cdot>\\<^sub>s\\<^bsub>N\\<^esub> (f x))\"\n\ndefinition\n  HOM :: \"[('b, 'more) Ring_scheme, ('a, 'b, 'more1) Module_scheme, \n    ('c, 'b, 'more2) Module_scheme] \\<Rightarrow> ('a \\<Rightarrow> 'c, 'b) Module\"   \n    (\"(3HOM\\<^bsub>_\\<^esub> _/ _)\" [90, 90, 91] 90) where\n \"HOM\\<^bsub>R\\<^esub> M N = \\<lparr>carrier = mHom R M N, pop = tOp_mHom R M N, \n  mop = iOp_mHom R M N, zero = mzeromap M N,  sprod =sprod_mHom R M N \\<rparr>\"\n\nlemma (in Module) zero_HOM:\"R module N \\<Longrightarrow>\n         mzeromap M N = \\<zero>\\<^bsub>HOM\\<^bsub>R\\<^esub> M N\\<^esub>\"\napply (simp add:HOM_def)\ndone\n\nlemma (in Module) tOp_mHom_closed:\"\\<lbrakk>R module N; f \\<in> mHom R M N; g \\<in> mHom R M N\\<rbrakk>\n      \\<Longrightarrow> tOp_mHom R M N f g \\<in> mHom R M N\"\napply (rule mHom_test, assumption+)\napply (rule conjI)\n apply (rule Pi_I)\n apply (simp add:tOp_mHom_def)\n apply (frule_tac f = f and m = x in mHom_mem [of N], assumption+,\n        frule_tac f = g and m = x in mHom_mem [of N], assumption+,\n        frule Module.module_is_ag [of N], \n        simp add:aGroup.ag_pOp_closed[of N])\napply (rule conjI)\n apply (simp add:tOp_mHom_def restrict_def extensional_def)\napply (rule conjI)\n apply (rule ballI)+\n apply (simp add:tOp_mHom_def)\n apply (simp add:ag_pOp_closed)\n            \napply (frule_tac f = f and m = m in mHom_mem [of N], assumption+,\n       frule_tac f = f and m = n in mHom_mem [of N], assumption+,\n       frule_tac f = g and m = m in mHom_mem [of N], assumption+,\n       frule_tac f = g and m = n in mHom_mem [of N], assumption+,\n       simp add:mHom_add,\n       frule Module.module_is_ag [of N],\n       subst aGroup.pOp_assocTr43[of \"N\"], assumption+,\n       frule_tac x = \"f n\" and y = \"g m\" in aGroup.ag_pOp_commute [of \"N\"],\n                                                              assumption+)\napply simp\napply (subst aGroup.pOp_assocTr43[of \"N\"], assumption+, simp) \n\napply (rule ballI)+\napply (simp add:tOp_mHom_def) \napply (frule_tac a = a and m = m in sc_mem, assumption, simp) \napply (frule_tac f = f and m = m in mHom_mem [of N], assumption+,\n       frule_tac f = g and m = m in mHom_mem [of N], assumption+,\n       frule_tac a = a and m = \"f m\" and n = \"g m\" in \n                                  Module.sc_r_distr[of N R], assumption+,\n      simp)\napply (simp add:mHom_lin)\ndone\n\nlemma (in Module) iOp_mHom_closed:\"\\<lbrakk>R module N; f \\<in> mHom R M N\\<rbrakk>\n                                     \\<Longrightarrow> iOp_mHom R M N f \\<in> mHom R M N\"\napply (rule mHom_test, assumption+)\napply (rule conjI)\n apply (rule Pi_I)\n apply (simp add:iOp_mHom_def)\n apply (frule_tac f = f and m = x in mHom_mem [of N], assumption+)\n apply (frule Module.module_is_ag [of N])\n apply (simp add:aGroup.ag_mOp_closed)\napply (rule conjI)\n apply (simp add:iOp_mHom_def restrict_def extensional_def)\napply (rule conjI) apply (rule ballI)+\n apply (simp add:iOp_mHom_def)\n apply (simp add:ag_pOp_closed)\n apply (simp add:mHom_add)\n  apply (frule_tac f = f and m = m in mHom_mem [of N], assumption+,\n         frule_tac f = f and m = n in mHom_mem [of N], assumption+)\n apply (frule Module.module_is_ag [of N])\n apply (simp add:aGroup.ag_p_inv)\n\napply (rule ballI)+\napply (simp add:iOp_mHom_def)\napply (simp add:sc_mem)\n apply (simp add:mHom_lin)\n apply (frule_tac f = f and m = m in mHom_mem [of N], assumption+)\n apply (simp add:Module.sc_minus_am[of N])\ndone\n\nlemma (in Module) mHom_ex_zero:\"R module N \\<Longrightarrow>  mzeromap M N \\<in> mHom R M N\"\napply (simp add:mHom_def)\napply (rule conjI)\n apply (simp add:aHom_def,\n        rule conjI,\n        simp add:mzeromap_def, simp add:Module.module_inc_zero)\n\n apply (simp add:mzeromap_def extensional_def)\n\n apply ((rule ballI)+,\n         simp add:ag_pOp_closed,\n         frule Module.module_is_ag [of N],\n         frule aGroup.ag_inc_zero [of \"N\"],\n         simp add:aGroup.ag_l_zero)\napply ((rule ballI)+,\n       simp add:mzeromap_def,\n       simp add:sc_mem)\n apply (simp add:Module.sc_a_0)\ndone\n\nlemma (in Module) mHom_eq:\"\\<lbrakk>R module N; f \\<in> mHom R M N; g \\<in> mHom R M N; \n                            \\<forall>m\\<in>carrier M. f m = g m\\<rbrakk> \\<Longrightarrow> f = g\"  \napply (simp add:mHom_def aHom_def)\n apply (erule conjE)+\n apply (rule funcset_eq, assumption+)\ndone\n\nlemma (in Module) mHom_l_zero:\"\\<lbrakk>R module N; f \\<in> mHom R M N\\<rbrakk>\n              \\<Longrightarrow> tOp_mHom R M N (mzeromap M N) f = f\"\napply (frule mHom_ex_zero [of N])\napply (frule tOp_mHom_closed [of N \"mzeromap M N\" f], assumption+)\napply (rule mHom_eq, assumption+)\n apply (rule ballI)\n apply (simp add:tOp_mHom_def, simp add:mzeromap_def)\n apply (frule_tac f = f and m = m in mHom_mem [of N], assumption+)\n apply (frule Module.module_is_ag [of N])\n apply (simp add:aGroup.ag_l_zero[of N])\ndone\n\nlemma  (in Module) mHom_l_inv:\"\\<lbrakk>R module N; f \\<in> mHom R M N\\<rbrakk>\n       \\<Longrightarrow> tOp_mHom R M N (iOp_mHom R M N f) f = mzeromap M N\"\napply (frule mHom_ex_zero [of N])\napply (frule_tac f = f in iOp_mHom_closed [of N], assumption,\n       frule_tac f = \"iOp_mHom R M N f\" and g = f in tOp_mHom_closed [of N],\n        assumption+,\n       frule mHom_ex_zero [of N])\napply (rule mHom_eq, assumption+, rule ballI)\n apply (simp add:tOp_mHom_def iOp_mHom_def, simp add:mzeromap_def)\n apply (frule_tac f = f and m = m in mHom_mem [of N], assumption+)\n apply (frule Module.module_is_ag [of N])\n apply (simp add:aGroup.ag_l_inv1)\ndone\n\nlemma  (in Module) mHom_tOp_assoc:\"\\<lbrakk>R module N; f \\<in> mHom R M N; g \\<in> mHom R M N;\n        h \\<in> mHom R M N\\<rbrakk> \\<Longrightarrow> tOp_mHom R M N (tOp_mHom R M N f g) h =\n          tOp_mHom R M N f (tOp_mHom R M N g h)\"\napply (frule_tac f = f and g = g in tOp_mHom_closed [of N], assumption+,\n       frule_tac f = \"tOp_mHom R M N f g\" and g = h in \n                      tOp_mHom_closed [of N], assumption+,\n       frule_tac f = g and g = h in tOp_mHom_closed [of N], assumption+,\n       frule_tac f = f and g = \"tOp_mHom R M N g h\" in \n                      tOp_mHom_closed [of N], assumption+) \n apply (rule mHom_eq, assumption+, rule ballI,\n        thin_tac \"tOp_mHom R M N f g \\<in> mHom R M N\",\n        thin_tac \"tOp_mHom R M N (tOp_mHom R M N f g) h \\<in> mHom R M N\",\n        thin_tac \"tOp_mHom R M N g h \\<in> mHom R M N\",\n        thin_tac \"tOp_mHom R M N f (tOp_mHom R M N g h) \\<in> mHom R M N\")\n apply (simp add:tOp_mHom_def)\n apply (frule_tac f = f and m = m in mHom_mem [of N], assumption+,\n        frule_tac f = g and m = m in mHom_mem [of N], assumption+,\n        frule_tac f = h and m = m in mHom_mem [of N], assumption+)\napply (frule Module.module_is_ag [of N])\n apply (simp add:aGroup.ag_pOp_assoc)\ndone\n\nlemma (in Module) mHom_tOp_commute:\"\\<lbrakk>R module N; f \\<in> mHom R M N; \n        g \\<in> mHom R M N\\<rbrakk> \\<Longrightarrow> tOp_mHom R M N f g = tOp_mHom R M N g f\"\napply (frule_tac f = f and g = g in tOp_mHom_closed [of N], assumption+,\n       frule_tac f = g and g = f in tOp_mHom_closed [of N], assumption+)\napply (rule mHom_eq, assumption+)\n apply (rule ballI)\n apply (thin_tac \"tOp_mHom R M N f g \\<in> mHom R M N\",\n        thin_tac \"tOp_mHom R M N g f \\<in> mHom R M N\")\n apply (simp add:tOp_mHom_def)\n apply (frule_tac f = f and m = m in mHom_mem [of N], assumption+,\n        frule_tac f = g and m = m in mHom_mem [of N], assumption+,\n        frule Module.module_is_ag [of N])\n apply (simp add:aGroup.ag_pOp_commute)\ndone\n\nlemma  (in Module) HOM_is_ag:\"R module N \\<Longrightarrow> aGroup (HOM\\<^bsub>R\\<^esub> M N)\"\napply (rule aGroup.intro)\n apply (simp add:HOM_def)\n apply (simp add:tOp_mHom_closed)\n\napply (simp add:HOM_def)\n apply (simp add:mHom_tOp_assoc)\n\napply (simp add:HOM_def)\n apply (simp add:mHom_tOp_commute)\n\napply (simp add:HOM_def)\n apply (simp add:iOp_mHom_closed)\n\napply (simp add:HOM_def,\n       simp add:mHom_l_inv)\n\napply (simp add:HOM_def)\n apply (simp add:mHom_ex_zero)\n\napply (simp add:HOM_def,\n       simp add:mHom_l_zero)\ndone\n\nlemma (in Module) sprod_mHom_closed:\"\\<lbrakk>R module N; a \\<in> carrier R; \n       f \\<in> mHom R M N\\<rbrakk> \\<Longrightarrow> sprod_mHom R M N a f \\<in> mHom R M N\"\napply (rule mHom_test, assumption+)\napply (rule conjI)\n apply (simp add:Pi_def)\n apply (rule allI, rule impI, simp add:sprod_mHom_def,\n        frule_tac f = f and m = x in mHom_mem [of N], assumption+,\n        simp add:Module.sc_mem [of N R a])\napply (rule conjI)\n apply (simp add:sprod_mHom_def restrict_def extensional_def)\napply (rule conjI)\n apply (rule ballI)+\n apply (frule_tac x = m and y = n in ag_pOp_closed, assumption+)\n apply (simp add:sprod_mHom_def)\napply (subst mHom_add [of N f], assumption+)\n apply (frule_tac f = f and m = m in mHom_mem [of N], assumption+, \n        frule_tac f = f and m = n in mHom_mem [of N], assumption+)\n apply (simp add:Module.sc_r_distr)\n\napply (rule ballI)+\n apply (simp add:sprod_mHom_def)\n apply (frule_tac a = aa and m = m in sc_mem, assumption+, simp)\n apply (simp add:mHom_lin) \n apply (frule_tac f = f and m = m in mHom_mem [of N], assumption+)\napply (simp add:Module.sc_assoc[THEN sym, of N R]) \napply (cut_tac sc_Ring, simp add:Ring.ring_tOp_commute)\ndone\n\nlemma (in Module) HOM_is_module:\"R module N \\<Longrightarrow> R module (HOM\\<^bsub>R\\<^esub> M N)\"\napply (rule Module.intro)\napply (simp add:HOM_is_ag)\napply (rule Module_axioms.intro)\n apply (simp add:sc_Ring)\n\n apply (simp add:HOM_def)\n apply (simp add:sprod_mHom_closed)\n\n apply (simp add:HOM_def)\n apply (cut_tac sc_Ring,\n        frule Ring.ring_is_ag[of R],\n        frule_tac x = a and y = b in aGroup.ag_pOp_closed[of R], assumption+,\n        frule_tac a = \"a \\<plusminus>\\<^bsub>R\\<^esub> b\" and f = m in sprod_mHom_closed[of N], \n        assumption+)\n  apply(frule_tac a = a and f = m in sprod_mHom_closed[of N], assumption+,\n        frule_tac a = b and f = m in sprod_mHom_closed[of N], assumption+,\n        frule_tac f = \"sprod_mHom R M N a m\" and g = \"sprod_mHom R M N b m\" in\n        tOp_mHom_closed[of N], assumption+)\n  apply (rule mHom_eq[of N], assumption+, rule ballI,\n         simp add:sprod_mHom_def tOp_mHom_def)\n  apply (rename_tac a b f m)\n  apply (frule_tac f = f and m = m in mHom_mem[of N], assumption+)\n  apply (simp add:Module.sc_l_distr[of N])\n\napply (simp add:HOM_def)\n apply (rename_tac a f g,\n        frule_tac f = f and g = g in tOp_mHom_closed[of N], assumption+,\n        frule_tac a = a and f = \"tOp_mHom R M N f g\" in \n                                     sprod_mHom_closed[of N], assumption+,\n        frule_tac a = a and f = f in sprod_mHom_closed[of N], assumption+,\n        frule_tac a = a and f = g in sprod_mHom_closed[of N], assumption+,\n        frule_tac f = \"sprod_mHom R M N a f\" and g = \"sprod_mHom R M N a g\" \n        in tOp_mHom_closed[of N], assumption+)   \n apply (rule mHom_eq[of N], assumption+, rule ballI,\n        simp add:sprod_mHom_def tOp_mHom_def,\n        frule_tac f = f and m = m in mHom_mem[of N], assumption+,\n        frule_tac f = g and m = m in mHom_mem[of N], assumption+)\n apply (simp add:Module.sc_r_distr)\n\napply (simp add:HOM_def)\n apply (rename_tac a b f)\n apply (cut_tac sc_Ring,\n        frule_tac x = a and y = b in Ring.ring_tOp_closed, assumption+,\n        frule_tac a = \"a \\<cdot>\\<^sub>r\\<^bsub>R\\<^esub> b\" and f = f in sprod_mHom_closed[of N], \n                                                            assumption+,\n        frule_tac a = b and f = f in sprod_mHom_closed[of N], assumption+,\n        frule_tac a = a and f = \"sprod_mHom R M N b f\" in \n                                     sprod_mHom_closed[of N], assumption+) \n apply (rule mHom_eq[of N], assumption+, rule ballI,\n        simp add:sprod_mHom_def,\n        frule_tac f = f and m = m in mHom_mem[of N], assumption+,\n        simp add:Module.sc_assoc)\n\napply (simp add:HOM_def)\n apply (cut_tac sc_Ring,\n        frule Ring.ring_one,\n        frule_tac a = \"1\\<^sub>r\\<^bsub>R\\<^esub>\" and f = m in sprod_mHom_closed[of N], assumption+)\n apply (rule mHom_eq, assumption+, rule ballI, rename_tac f m,\n        simp add:sprod_mHom_def,\n        frule_tac f = f and m = m in mHom_mem[of N], assumption+,\n        simp add:Module.sprod_one)\ndone\n\nsection \"Injective hom, surjective hom, bijective hom and inverse hom\"\n\ndefinition\n  invmfun :: \"[('b, 'm) Ring_scheme, ('a, 'b, 'm1) Module_scheme, \n              ('c, 'b, 'm2) Module_scheme, 'a \\<Rightarrow> 'c] \\<Rightarrow> 'c \\<Rightarrow> 'a\" where\n  \"invmfun R M N (f :: 'a \\<Rightarrow> 'c) =\n                    (\\<lambda>y\\<in>(carrier N). SOME x. (x \\<in> (carrier M) \\<and> f x = y))\"\n\ndefinition\n  misomorphic :: \"[('b, 'm) Ring_scheme, ('a, 'b, 'm1) Module_scheme, \n              ('c, 'b, 'm2) Module_scheme] \\<Rightarrow> bool\" where\n  \"misomorphic R M N \\<longleftrightarrow> (\\<exists>f. f \\<in> mHom R M N \\<and> bijec\\<^bsub>M,N\\<^esub> f)\"\n\ndefinition\n  mId :: \"('a, 'b, 'm1) Module_scheme \\<Rightarrow> 'a \\<Rightarrow> 'a\"   (\"(mId\\<^bsub>_\\<^esub>/ )\" [89]88) where\n  \"mId\\<^bsub>M\\<^esub> = (\\<lambda>m\\<in>carrier M. m)\"\n\ndefinition\n  mcompose :: \"[('a, 'r, 'm1) Module_scheme, 'b \\<Rightarrow> 'c, 'a \\<Rightarrow> 'b] \\<Rightarrow> 'a \\<Rightarrow> 'c\" where\n  \"mcompose M g f = compose (carrier M) g f\"\n\nabbreviation\n  MISOM  (\"(3_ \\<cong>\\<^bsub>_\\<^esub> _)\" [82,82,83]82) where\n  \"M \\<cong>\\<^bsub>R\\<^esub> N == misomorphic R M N\"\n\nlemma (in Module) minjec_inj:\"\\<lbrakk>R module N; injec\\<^bsub>M,N\\<^esub> f\\<rbrakk> \\<Longrightarrow>\n                            inj_on f (carrier M)\" \napply (simp add:inj_on_def, (rule ballI)+, rule impI)\n apply (simp add:injec_def, erule conjE)\n apply (frule Module.module_is_ag[of N])\n apply (cut_tac module_is_ag) \n apply (frule_tac a = x in aHom_mem[of M N f], assumption+,\n        frule_tac a = y in aHom_mem[of M N f], assumption+)\n apply (simp add:aGroup.ag_eq_diffzero[of N])\n apply (simp add:aHom_inv_inv[THEN sym, of M N f],\n       frule_tac x = y in aGroup.ag_mOp_closed, assumption+,\n       simp add:aHom_add[THEN sym, of M N f])\n apply (simp add:ker_def)\n apply (frule_tac x = x and y = \"-\\<^sub>a y\" in ag_pOp_closed, assumption+)\n apply (subgoal_tac \"(x \\<plusminus> -\\<^sub>a y) \\<in> {a \\<in> carrier M. f a = \\<zero>\\<^bsub>N\\<^esub>}\", simp)\n apply (simp add:ag_eq_diffzero)\n apply blast\ndone \n\nlemma (in Module) invmfun_l_inv:\"\\<lbrakk>R module N; bijec\\<^bsub>M,N\\<^esub> f; m \\<in> carrier M\\<rbrakk> \\<Longrightarrow>\n                            (invmfun R M N f) (f m) = m\"\napply (simp add:bijec_def, erule conjE)\napply (frule minjec_inj [of N f], assumption+)\napply (simp add:surjec_def, erule conjE, simp add:aHom_def)\napply (frule conjunct1) \napply (thin_tac \"f \\<in> carrier M \\<rightarrow> carrier N \\<and>\n     f \\<in> extensional (carrier M) \\<and>\n     (\\<forall>a\\<in>carrier M. \\<forall>b\\<in>carrier M. f (a \\<plusminus> b) = f a \\<plusminus>\\<^bsub>N\\<^esub> f b)\")\napply (frule invfun_l [of \"f\" \"carrier M\" \"carrier N\" \"m\"], assumption+)\n apply (simp add:surj_to_def) \napply (simp add:invfun_def invmfun_def)\ndone\n \nlemma (in Module) invmfun_mHom:\"\\<lbrakk>R module N; bijec\\<^bsub>M,N\\<^esub> f; f \\<in> mHom R M N \\<rbrakk> \\<Longrightarrow>\n                 invmfun R M N f \\<in> mHom R N M\"\napply (frule minjec_inj [of N f])\n apply (simp add:bijec_def)\n apply (subgoal_tac \"surjec\\<^bsub>M,N\\<^esub> f\") prefer 2 apply (simp add:bijec_def)\n apply (rule Module.mHom_test) apply assumption apply (rule Module_axioms)\n\napply (rule conjI) \n apply (simp add:surjec_def, erule conjE)\n apply (simp add:aHom_def, frule conjunct1)\n apply (thin_tac \"f \\<in> carrier M \\<rightarrow> carrier N \\<and>\n     f \\<in> extensional (carrier M) \\<and>\n     (\\<forall>a\\<in>carrier M. \\<forall>b\\<in>carrier M. f (a \\<plusminus> b) = f a \\<plusminus>\\<^bsub>N\\<^esub> f b)\")\n apply (frule inv_func [of \"f\" \"carrier M\" \"carrier N\"], assumption+)\n apply (simp add:invmfun_def invfun_def)\n\napply (rule conjI)\n apply (simp add:invmfun_def restrict_def extensional_def)\n\napply (rule conjI)\n apply (rule ballI)+\n apply (simp add:surjec_def)\n apply (erule conjE, simp add:surj_to_def)\n apply (frule sym, thin_tac \"f ` carrier M = carrier N\", simp,\n        thin_tac \"carrier N = f ` carrier M\")\n apply (simp add:image_def, (erule bexE)+, simp)\n apply (simp add:mHom_add[THEN sym])\n apply (frule_tac x = x and y = xa in ag_pOp_closed, assumption+)\n apply (simp add:invmfun_l_inv)\n\napply (rule ballI)+\n apply (simp add:surjec_def, erule conjE)\n apply (simp add:surj_to_def, frule sym, thin_tac \"f ` carrier M = carrier N\") \n apply (simp add:image_def, (erule bexE)+, simp)\n apply (simp add:mHom_lin[THEN sym])\n apply (frule_tac a = a and m = x in sc_mem, assumption+)\n apply (simp add:invmfun_l_inv)\ndone\n\nlemma (in Module) invmfun_r_inv:\"\\<lbrakk>R module N; bijec\\<^bsub>M,N\\<^esub> f; n \\<in> carrier N\\<rbrakk> \\<Longrightarrow>\n                           f ((invmfun R M N f) n) = n\"\napply (frule minjec_inj[of N f])\n apply (simp add:bijec_def)\n apply (unfold bijec_def, frule conjunct2, fold bijec_def)\n apply (simp add:surjec_def, erule conjE, simp add:surj_to_def)\n apply (frule sym, thin_tac \"f ` carrier M = carrier N\", simp,\n        thin_tac \"carrier N = f ` carrier M\")\n apply (simp add:image_def, erule bexE, simp)\n apply (simp add:invmfun_l_inv)\ndone\n\nlemma (in Module) mHom_compos:\"\\<lbrakk>R module L; R module N; f \\<in> mHom R L M; \n       g \\<in> mHom R M N \\<rbrakk> \\<Longrightarrow> compos L g f \\<in> mHom R L N\" \napply (simp add:mHom_def [of \"R\" \"L\" \"N\"])\n apply (frule Module.module_is_ag [of L],\n        frule Module.module_is_ag [of N])\n\napply (rule conjI) \n apply (simp add:mHom_def, (erule conjE)+)\n   apply (rule aHom_compos[of L M N f], assumption+)\n   apply (cut_tac module_is_ag, assumption+)\n\napply (rule ballI)+\napply (simp add:compos_def compose_def)\n apply (simp add:Module.sc_mem)\n apply (subst Module.mHom_lin[of L R M _ f], assumption, rule Module_axioms, assumption+) (*apply (\n        simp add:Module_def, rule conjI, assumption+) *)\n apply (subst Module.mHom_lin[of M R N _ g], rule Module_axioms, assumption) (*apply (\n        simp add:Module_def, rule conjI)*)  (** ordering **)\n apply (rule Module.mHom_mem[of L R M f], assumption, rule Module_axioms, assumption+) \n apply simp\ndone\n\nlemma (in Module) mcompos_inj_inj:\"\\<lbrakk>R module L; R module N; f \\<in> mHom R L M; \n       g \\<in> mHom R M N; injec\\<^bsub>L,M\\<^esub> f; injec\\<^bsub>M,N\\<^esub> g \\<rbrakk> \\<Longrightarrow> injec\\<^bsub>L,N\\<^esub> (compos L g f)\"\napply (frule Module.module_is_ag [of L],\n       frule Module.module_is_ag [of N])\napply (simp add:injec_def [of \"L\" \"N\"])\napply (rule conjI)\n apply (simp add:injec_def, (erule conjE)+,\n        rule_tac aHom_compos[of L M N], assumption+,\n        rule module_is_ag)\n apply assumption+\n apply (simp add:compos_def compose_def)\n apply (rule equalityI)\n apply (rule subsetI, simp) \n apply (simp add:injec_def [of _ _ \"g\"], erule conjE, simp add:ker_def)\n apply (subgoal_tac \"f x \\<in> {a. a \\<in> carrier M \\<and> g a = \\<zero>\\<^bsub>N\\<^esub>}\")\n apply simp\n apply (simp add:injec_def [of _ _ \"f\"], erule conjE)\n apply (subgoal_tac \"x \\<in> ker\\<^bsub>L,M\\<^esub> f\", simp, thin_tac \"ker\\<^bsub>L,M\\<^esub> f = {\\<zero>\\<^bsub>L\\<^esub>}\")\n apply (simp add:ker_def)\n apply (thin_tac \"{a \\<in> carrier M. g a = \\<zero>\\<^bsub>N\\<^esub>} = {\\<zero>}\")\n apply (simp, erule conjE, simp)\n apply (rule Module.mHom_mem[of L R M f], assumption, rule Module_axioms, assumption+) \n\napply (rule subsetI, simp)\n apply (frule Module.module_inc_zero [of L R])\n apply (frule Module.mHom_0[of L R M f], rule Module_axioms, assumption+) \n apply (simp add:ker_def)\n apply (subst mHom_0[of N], assumption+, simp)\ndone\n\nlemma (in Module) mcompos_surj_surj:\"\\<lbrakk>R module L; R module N; surjec\\<^bsub>L,M\\<^esub> f;\n        surjec\\<^bsub>M,N\\<^esub> g; f \\<in> mHom R L M; g \\<in> mHom R M N \\<rbrakk> \\<Longrightarrow> \n                                        surjec\\<^bsub>L,N\\<^esub> (compos L g f)\"\napply (frule Module.module_is_ag [of L],\n       frule Module.module_is_ag [of N],\n       cut_tac module_is_ag)\napply (simp add:surjec_def [of \"L\" \"N\"])\napply (rule conjI)\n apply (simp add:mHom_def, (erule conjE)+)\n apply (rule aHom_compos[of L M N f g], assumption+)\n\napply (rule surj_to_test)\n apply (cut_tac Module.mHom_compos [of M R L N f g]) \n apply (simp add:mHom_def aHom_def) \n apply (rule Module_axioms, assumption+)\n\napply (rule ballI)\n apply (simp add: compos_def compose_def)\n apply (simp add:surjec_def [of _ _ \"g\"])\n apply (erule conjE) apply (simp add:surj_to_def)\n apply (frule sym, thin_tac \"g ` carrier M = carrier N\", simp add:image_def,\n        thin_tac \"carrier N = {y. \\<exists>x\\<in>carrier M. y = g x}\",\n        erule bexE, simp)\n  apply (simp add:surjec_def [of _ _ \"f\"], erule conjE, simp add:surj_to_def,\n         rotate_tac -1, frule sym, thin_tac \"f ` carrier L = carrier M\",\n          simp add:image_def, erule bexE, simp)\n apply blast\ndone\n\nlemma (in Module) mId_mHom:\"mId\\<^bsub>M\\<^esub> \\<in> mHom R M M\"\napply (simp add:mHom_def)\napply (rule conjI)\n apply (simp add:aHom_def)\n apply (rule conjI)\n apply (simp add:mId_def)\napply (simp add:mId_def extensional_def)\napply (rule ballI)+\n apply (simp add:ag_pOp_closed)\napply (rule ballI)+\n apply (simp add:mId_def)\n apply (simp add:sc_mem)\ndone\n\nlemma (in Module) mHom_mId_bijec:\"\\<lbrakk>R module N; f \\<in> mHom R M N; g \\<in> mHom R N M;\n      compose (carrier M) g f = mId\\<^bsub>M\\<^esub>; compose (carrier N) f g = mId\\<^bsub>N\\<^esub>\\<rbrakk> \\<Longrightarrow>\n      bijec\\<^bsub>M,N\\<^esub> f\"\napply (simp add:bijec_def)\napply (rule conjI)\napply (simp add:injec_def)\n apply (rule conjI)\n apply (simp add:mHom_def)\n apply (simp add:ker_def)\n apply (rule equalityI)\n apply (rule subsetI, simp, erule conjE)\n apply (frule_tac x = \"f x\" and y = \"\\<zero>\\<^bsub>N\\<^esub>\" and f = g in eq_elems_eq_val)\n apply (frule_tac f = \"compose (carrier M) g f\" and g = \"mId\\<^bsub>M\\<^esub>\" and x = x in\n        eq_fun_eq_val, thin_tac \"compose (carrier M) g f = mId\\<^bsub>M\\<^esub>\", \n        simp add:compose_def)\n apply (cut_tac Module.mHom_0[of N R M g], simp add:mId_def, assumption,\n   rule Module_axioms, assumption) \napply (rule subsetI, simp,\n       simp add:ag_inc_zero, simp add:mHom_0)\n\napply (simp add:surjec_def)\n apply (rule conjI, simp add:mHom_def)\n apply (rule surj_to_test)\n apply (simp add:mHom_def aHom_def)\n apply (rule ballI)\n  apply (frule_tac f = \"compose (carrier N) f g\" and g = \"mId\\<^bsub>N\\<^esub>\" and x = b in\n        eq_fun_eq_val, thin_tac \"compose (carrier M) g f = mId\\<^bsub>M\\<^esub>\",\n        thin_tac \"compose (carrier N) f g = mId\\<^bsub>N\\<^esub>\", \n        simp add:compose_def)\n apply (simp add:mId_def)\n apply (frule_tac m = b in Module.mHom_mem [of N R M g], rule Module_axioms, assumption+)\n apply blast\ndone\n\ndefinition\n  sup_sharp :: \"[('r, 'n) Ring_scheme, ('b, 'r, 'm1) Module_scheme, \n    ('c, 'r, 'm2) Module_scheme, ('a, 'r, 'm) Module_scheme, 'b \\<Rightarrow> 'c] \n     \\<Rightarrow> ('c \\<Rightarrow> 'a) \\<Rightarrow> ('b \\<Rightarrow> 'a)\" where\n  \"sup_sharp R M N L u = (\\<lambda>f\\<in>mHom R N L. compos M f u)\"\n\ndefinition\n  sub_sharp :: \"[('r, 'n) Ring_scheme, ('a, 'r, 'm) Module_scheme, \n    ('b, 'r, 'm1) Module_scheme, ('c, 'r, 'm2) Module_scheme, 'b \\<Rightarrow> 'c] \n     \\<Rightarrow> ('a \\<Rightarrow> 'b) \\<Rightarrow> ('a \\<Rightarrow> 'c)\" where\n  \"sub_sharp R L M N u = (\\<lambda>f\\<in>mHom R L M. compos L u f)\"\n\n       (*  L\n          f| u\n           M \\<rightarrow> N,  f \\<rightarrow> u o f   *)\n\nlemma (in Module) sup_sharp_homTr:\"\\<lbrakk>R module N; R module L; u \\<in> mHom R M N; \n      f \\<in> mHom R N L \\<rbrakk> \\<Longrightarrow> sup_sharp R M N L u f \\<in> mHom R M L\"\napply (simp add:sup_sharp_def)\napply (rule Module.mHom_compos, assumption, rule Module_axioms, assumption+) \ndone\n\nlemma (in Module) sup_sharp_hom:\"\\<lbrakk>R module N; R module L; u \\<in> mHom R M N\\<rbrakk> \\<Longrightarrow> \n           sup_sharp R M N L u \\<in> mHom R (HOM\\<^bsub>R\\<^esub> N L) (HOM\\<^bsub>R\\<^esub> M L)\"\napply (simp add:mHom_def [of \"R\" \"HOM\\<^bsub>R\\<^esub> N L\"])\napply (rule conjI) \n apply (simp add:aHom_def) \n apply (rule conjI)\n apply (simp add:HOM_def sup_sharp_homTr)\n\n apply (rule conjI)\n apply (simp add:sup_sharp_def extensional_def,\n        rule allI, rule impI, simp add:HOM_def)\n\n apply (rule ballI)+\n apply (simp add:HOM_def)\n apply (frule_tac f = a and g = b in Module.tOp_mHom_closed, assumption+)\n apply (subgoal_tac \"R module M\")        \n apply (frule_tac f = a in Module.sup_sharp_homTr [of M R N L u], assumption+)\n apply (frule_tac f = b in Module.sup_sharp_homTr [of M R N L u], assumption+)\n apply (frule_tac f = \"tOp_mHom R N L a b\" in \n                            Module.sup_sharp_homTr[of M R N L u], assumption+) \n apply (rule Module.mHom_eq, assumption+)\n apply (rule Module.tOp_mHom_closed, assumption+)\n\n apply (rule ballI)\n apply (simp add:sup_sharp_def tOp_mHom_def compose_def compos_def)\n apply (simp add:mHom_mem, rule Module_axioms)\n\napply (rule ballI)+\n apply (simp add:HOM_def)\n apply (frule_tac a = a and f = m in Module.sprod_mHom_closed [of N R L],\n                                                                assumption+)\n apply (subgoal_tac \"R module M\",\n        frule_tac f = \"sprod_mHom R N L a m\" in \n                 Module.sup_sharp_homTr [of M R N L u], assumption+)\n apply (frule_tac f = m in Module.sup_sharp_homTr [of M R N L u], assumption+)\n apply (frule_tac a = a and f = \"sup_sharp R M N L u m\" in \n           Module.sprod_mHom_closed [of M R L], assumption+)\n apply (rule mHom_eq, assumption+)\n apply (rule ballI)\n apply (simp add:sprod_mHom_def sup_sharp_def compose_def compos_def)\napply (simp add:Module.mHom_mem, rule Module_axioms)\ndone\n\nlemma (in Module) sub_sharp_homTr:\"\\<lbrakk>R module N; R module L; u \\<in> mHom R M N; \n       f \\<in> mHom R L M\\<rbrakk> \\<Longrightarrow> sub_sharp R L M N u f \\<in> mHom R L N\"\napply (simp add:sub_sharp_def)\napply (simp add:mHom_compos)\ndone\n\nlemma (in Module) sub_sharp_hom:\"\\<lbrakk>R module N; R module L; u \\<in> mHom R M N\\<rbrakk> \\<Longrightarrow> \n          sub_sharp R L M N u \\<in> mHom R (HOM\\<^bsub>R\\<^esub> L M) (HOM\\<^bsub>R\\<^esub> L N)\"\napply (simp add:mHom_def [of _ \"HOM\\<^bsub>R\\<^esub> L M\"])\napply (rule conjI)\n apply (simp add:aHom_def)\n apply (rule conjI)\n apply (simp add:HOM_def)\n apply (simp add:sub_sharp_homTr)\n\napply (rule conjI)\n apply (simp add:sub_sharp_def extensional_def)\n apply (simp add:HOM_def)\n\napply (rule ballI)+\n apply (simp add:HOM_def)\n apply (frule_tac f = a and g = b in Module.tOp_mHom_closed [of L R M],\n   rule Module_axioms, assumption+)\n apply (subgoal_tac \"R module M\")\n apply (frule_tac f = \"tOp_mHom R L M a b\" in Module.sub_sharp_homTr \n                                 [of M R N L u], assumption+)\n apply (frule_tac f = b in Module.sub_sharp_homTr[of M R N L u],\n                                                  assumption+,\n        frule_tac f = a in Module.sub_sharp_homTr[of M R N L u], assumption+) \n apply (frule_tac f = \"sub_sharp R L M N u a\" and \n  g = \"sub_sharp R L M N u b\" in Module.tOp_mHom_closed [of L R N],assumption+)\napply (rule Module.mHom_eq, assumption+)\n apply (rule ballI)\n apply (simp add:tOp_mHom_def sub_sharp_def mcompose_def compose_def,\n        simp add:compos_def compose_def)\n apply (rule Module.mHom_add [of M R], assumption+)\n apply (simp add:Module.mHom_mem, simp add:Module.mHom_mem)\n apply (rule Module_axioms)\n\napply (rule ballI)+\n apply (simp add:HOM_def)\n apply (subgoal_tac \"R module M\")\n apply (frule_tac a = a and f = m in Module.sprod_mHom_closed [of L R M],\n                                          assumption+)\n apply (frule_tac f = \"sprod_mHom R L M a m\" in Module.sub_sharp_homTr \n                                 [of M R N L u], assumption+) \n apply (frule_tac f = m in Module.sub_sharp_homTr \n                                 [of M R N L u], assumption+) \n apply (frule_tac a = a and f = \"sub_sharp R L M N u m\" in \n                       Module.sprod_mHom_closed [of L R N], assumption+)\napply (rule Module.mHom_eq, assumption+)\n apply (rule ballI)\n apply (simp add:sprod_mHom_def sub_sharp_def mcompose_def compose_def)\n apply (frule_tac  f = m and m = ma in Module.mHom_mem [of L R M], assumption+)\napply (simp add:compos_def compose_def) \napply (simp add:mHom_lin)\napply (rule Module_axioms)\ndone   \n\nlemma (in Module) mId_bijec:\"bijec\\<^bsub>M,M\\<^esub> (mId\\<^bsub>M\\<^esub>)\" \napply (simp add:bijec_def)\napply (cut_tac mId_mHom)\napply (rule conjI)\n apply (simp add:injec_def)\n apply (rule conjI) apply (simp add:mHom_def)\n apply (simp add:ker_def) apply (simp add:mId_def)\n apply (rule equalityI) apply (rule subsetI, simp) \n apply (rule subsetI, simp, simp add:ag_inc_zero) \n\napply (simp add:surjec_def)\n apply (rule conjI, simp add:mHom_def)\n apply (rule surj_to_test)\n apply (simp add:mHom_def aHom_def)\n apply (rule ballI)\n apply (simp add:mId_def)\ndone\n\nlemma (in Module) invmfun_bijec:\"\\<lbrakk>R module N; f \\<in> mHom R M N; bijec\\<^bsub>M,N\\<^esub> f\\<rbrakk> \\<Longrightarrow>\n                  bijec\\<^bsub>N,M\\<^esub> (invmfun R M N f)\"\napply (frule invmfun_mHom [of N f], assumption+)\napply (simp add:bijec_def [of N M])\napply (rule conjI)\napply (simp add:injec_def)\n apply (simp add:mHom_def [of \"R\" \"N\" \"M\"]) apply (erule conjE)+\n apply (thin_tac \"\\<forall>a\\<in>carrier R.\n        \\<forall>m\\<in>carrier N. invmfun R M N f (a \\<cdot>\\<^sub>s\\<^bsub>N\\<^esub> m) = a \\<cdot>\\<^sub>s invmfun R M N f m\")\n apply (rule equalityI) apply (rule subsetI) apply (simp add:ker_def CollectI)\n apply (erule conjE)\n apply (frule_tac x = \"invmfun R M N f x\" and y = \"\\<zero>\" and f = f in \n       eq_elems_eq_val,\n       thin_tac \"invmfun R M N f x = \\<zero>\")\n apply (simp add:invmfun_r_inv)\n  apply (simp add:mHom_0)\n\napply (rule subsetI, simp)\n apply (simp add:ker_def)\n apply (simp add:Module.module_inc_zero)\n apply (cut_tac ag_inc_zero,\n        frule invmfun_l_inv[of N f \\<zero>], assumption+)\n apply (simp add:mHom_0)\n\napply (simp add:surjec_def,\n       frule invmfun_mHom[of N f], assumption+)\n apply (rule conjI, simp add:mHom_def)\n apply (simp add:surj_to_def)\n apply (rule equalityI, rule subsetI, simp add:image_def, erule bexE,\n        simp) thm Module.mHom_mem[of N R M \"invmfun R M N f\"]\n apply (rule Module.mHom_mem[of N R M \"invmfun R M N f\"], assumption,\n   rule Module_axioms, assumption+) \n apply (rule subsetI, simp add:image_def)\n apply (frule_tac m = x in invmfun_l_inv[of N f], assumption+)\n apply (frule_tac m = x in mHom_mem[of N f], assumption+)\n apply (frule sym, thin_tac \"invmfun R M N f (f x) = x\", blast)\ndone\n  \nlemma (in Module) misom_self:\"M \\<cong>\\<^bsub>R\\<^esub> M\"\napply (cut_tac mId_bijec)\napply (cut_tac mId_mHom)\napply (simp add:misomorphic_def)\napply blast\ndone\n\nlemma (in Module) misom_sym:\"\\<lbrakk>R module N; M \\<cong>\\<^bsub>R\\<^esub> N\\<rbrakk> \\<Longrightarrow> N \\<cong>\\<^bsub>R\\<^esub> M\"\napply (simp add:misomorphic_def [of \"R\" \"M\" \"N\"])\napply (erule exE, erule conjE)\napply (frule_tac f = f in invmfun_mHom [of N], assumption+)\napply (frule_tac f = f in invmfun_bijec [of N], assumption+)\napply (simp add:misomorphic_def)\napply blast\ndone\n\nlemma (in Module) misom_trans:\"\\<lbrakk>R module L; R module N; L \\<cong>\\<^bsub>R\\<^esub> M; M \\<cong>\\<^bsub>R\\<^esub> N\\<rbrakk> \\<Longrightarrow> \n                               L \\<cong>\\<^bsub>R\\<^esub> N\"\napply (simp add:misomorphic_def)\n apply ((erule exE)+, (erule conjE)+)\n apply (subgoal_tac  \"bijec\\<^bsub>L,N\\<^esub> (compos L fa f)\")\n apply (subgoal_tac \"(compos L fa f) \\<in> mHom R L N\")\n apply blast\n apply (rule Module.mHom_compos[of M R L N], rule Module_axioms, assumption+) \n\napply (simp add:bijec_def) apply (erule conjE)+\napply (simp add:mcompos_inj_inj)                                \napply (simp add:mcompos_surj_surj)\ndone\n\ndefinition\n  mr_coset :: \"['a, ('a, 'b, 'more) Module_scheme, 'a set] \\<Rightarrow> 'a set\" where\n  \"mr_coset a M H = a \\<uplus>\\<^bsub>M\\<^esub> H\"\n\ndefinition\n  set_mr_cos :: \"[('a, 'b, 'more) Module_scheme, 'a set] \\<Rightarrow> 'a set set\" where\n  \"set_mr_cos M H = {X. \\<exists>a\\<in>carrier M. X = a \\<uplus>\\<^bsub>M\\<^esub> H}\"\n\ndefinition\n  mr_cos_sprod :: \"[('a, 'b, 'more) Module_scheme, 'a set] \\<Rightarrow> \n                                              'b \\<Rightarrow> 'a set \\<Rightarrow> 'a set\" where\n  \"mr_cos_sprod M H a X = {z. \\<exists>x\\<in>X. \\<exists>h\\<in>H. z = h \\<plusminus>\\<^bsub>M\\<^esub> (a \\<cdot>\\<^sub>s\\<^bsub>M\\<^esub> x)}\"\n\ndefinition\n  mr_cospOp :: \"[('a, 'b, 'more) Module_scheme, 'a set] \\<Rightarrow> \n                                               'a set \\<Rightarrow> 'a set \\<Rightarrow> 'a set\" where\n  \"mr_cospOp M H = (\\<lambda>X. \\<lambda>Y. c_top (b_ag M) H X Y)\"  \n\ndefinition\n  mr_cosmOp :: \"[('a, 'b, 'more) Module_scheme, 'a set] \\<Rightarrow> \n                                                  'a set \\<Rightarrow> 'a set\" where\n  \"mr_cosmOp M H = (\\<lambda>X. c_iop (b_ag M) H X)\"\n\ndefinition\n  qmodule :: \"[('a, 'r, 'more) Module_scheme, 'a set] \\<Rightarrow>\n                 ('a set, 'r) Module\" where\n  \"qmodule M H = \\<lparr> carrier = set_mr_cos M H, pop = mr_cospOp M H, \n    mop = mr_cosmOp M H, zero = H, sprod = mr_cos_sprod M H\\<rparr>\"\n\ndefinition\n  sub_mr_set_cos :: \"[('a, 'r, 'more) Module_scheme, 'a set, 'a set] \\<Rightarrow>\n                            'a set set\" where\n \"sub_mr_set_cos M H N = {X. \\<exists>n\\<in>N. X = n \\<uplus>\\<^bsub>M\\<^esub> H}\" \n (* N/H, where N is a submodule *)\n\nabbreviation\n  QMODULE  (infixl \"'/'\\<^sub>m\" 200) where\n  \"M /\\<^sub>m H == qmodule M H\"\n\nabbreviation\n  SUBMRSET  (\"(3_/ \\<^sub>s'/'\\<^sub>_/ _)\" [82,82,83]82) where\n  \"N \\<^sub>s/\\<^sub>M H == sub_mr_set_cos M H N\"\n\nlemma (in Module) qmodule_carr:\"submodule R M H \\<Longrightarrow>\n            carrier (qmodule M H) = set_mr_cos M H\"\napply (simp add:qmodule_def)\ndone\n\nlemma (in Module) set_mr_cos_mem:\"\\<lbrakk>submodule R M H; m \\<in> carrier M\\<rbrakk> \\<Longrightarrow>\n                        m \\<uplus>\\<^bsub>M\\<^esub> H \\<in> set_mr_cos M H\"\napply (simp add:set_mr_cos_def) \napply blast\ndone\n\nlemma (in Module) mem_set_mr_cos:\"\\<lbrakk>submodule R M N; x \\<in> set_mr_cos M N\\<rbrakk> \\<Longrightarrow>\n                          \\<exists>m \\<in> carrier M. x = m  \\<uplus>\\<^bsub>M\\<^esub> N\"\nby (simp add:set_mr_cos_def)\n\nlemma (in Module) m_in_mr_coset:\"\\<lbrakk>submodule R M H; m \\<in> carrier M\\<rbrakk> \\<Longrightarrow>\n                                   m \\<in> m \\<uplus>\\<^bsub>M\\<^esub> H\"\napply (cut_tac module_is_ag)\napply (frule aGroup.b_ag_group)\napply (simp add:ar_coset_def)\napply (simp add:aGroup.ag_carrier_carrier [THEN sym])\napply (simp add:submodule_def) apply (erule conjE)+ \napply (simp add:asubGroup_def)\napply (rule Group.a_in_rcs [of \"b_ag M\" \"H\" \"m\"], assumption+)\ndone\n\nlemma (in Module) mr_cos_h_stable:\"\\<lbrakk>submodule R M H; h \\<in> H\\<rbrakk> \\<Longrightarrow>\n                                                       H = h \\<uplus>\\<^bsub>M\\<^esub> H\"\napply (cut_tac module_is_ag)\napply (frule aGroup.b_ag_group [of \"M\"])\napply (simp add:ar_coset_def) \napply (rule Group.rcs_Unit2[THEN sym], assumption+,\n        simp add:submodule_def, (erule conjE)+, \n        simp add:asubGroup_def) \napply assumption\ndone\n\nlemma (in Module) mr_cos_h_stable1:\"\\<lbrakk>submodule R M H; m \\<in> carrier M; h \\<in> H\\<rbrakk>\n             \\<Longrightarrow> (m \\<plusminus> h) \\<uplus>\\<^bsub>M\\<^esub> H = m \\<uplus>\\<^bsub>M\\<^esub> H\"\napply (cut_tac module_is_ag)\napply (subst aGroup.ag_pOp_commute, assumption+)\n apply (simp add:submodule_def, (erule conjE)+, simp add:subsetD)\napply (frule aGroup.b_ag_group [of \"M\"])\napply (simp add:ar_coset_def)\napply (simp add:aGroup.agop_gop [THEN sym])\napply (simp add:aGroup.ag_carrier_carrier [THEN sym])\napply (simp add:submodule_def, (erule conjE)+, simp add:asubGroup_def)\napply (rule Group.rcs_fixed1 [THEN sym, of \"b_ag M\" \"H\" \"m\" \"h\"], assumption+)\ndone\n\nlemma (in Module) x_in_mr_coset:\"\\<lbrakk>submodule R M H; m \\<in> carrier M; x \\<in> m \\<uplus>\\<^bsub>M\\<^esub> H\\<rbrakk>\n                 \\<Longrightarrow> \\<exists>h\\<in>H. m \\<plusminus> h = x\"\napply (cut_tac module_is_ag)\n apply (frule aGroup.b_ag_group [of \"M\"])\n apply (simp add:submodule_def, (erule conjE)+,\n        simp add:asubGroup_def)\n apply (simp add:aGroup.ag_carrier_carrier [THEN sym])\n apply (simp add:aGroup.agop_gop [THEN sym])\n apply (simp add:ar_coset_def)\n apply (frule Group.rcs_tool2[of \"b_ag M\" H m x], assumption+,\n        erule bexE)\n apply (frule sym, thin_tac \"h \\<cdot>\\<^bsub>b_ag M\\<^esub> m = x\", simp)\n apply (simp add:aGroup.agop_gop)\n apply (simp add:aGroup.ag_carrier_carrier)\n apply (frule_tac c = h in subsetD[of H \"carrier M\"], assumption+)\n apply (subst ag_pOp_commute[of _ m], assumption+)\n apply blast\ndone\n\nlemma (in Module) mr_cos_sprodTr:\"\\<lbrakk>submodule R M H; a \\<in> carrier R; \n       m \\<in> carrier M\\<rbrakk> \\<Longrightarrow> mr_cos_sprod M H a (m \\<uplus>\\<^bsub>M\\<^esub> H) = (a \\<cdot>\\<^sub>s m) \\<uplus>\\<^bsub>M\\<^esub> H\"\napply (cut_tac module_is_ag,\n       frule aGroup.b_ag_group,\n       frule sc_mem[of a m], assumption)\n apply (simp add:ar_coset_def,\n        simp add:mr_cos_sprod_def)\n apply (simp add:submodule_def, (erule conjE)+)\n apply (simp add:aGroup.ag_carrier_carrier [THEN sym],\n        simp add:aGroup.agop_gop [THEN sym])\n apply (simp add:asubGroup_def)\napply (rule equalityI)\n apply (rule subsetI, simp) \n apply (erule bexE)+\n apply (frule_tac x = xa in Group.rcs_tool2[of \"b_ag M\" H m], assumption+)\n apply (erule bexE, rotate_tac -1, frule sym, thin_tac \"ha \\<cdot>\\<^bsub>b_ag M\\<^esub> m = xa\",\n        simp)\n apply (simp add:aGroup.agop_gop, simp add:aGroup.ag_carrier_carrier)\n apply (frule_tac c = ha in subsetD[of H \"carrier M\"], assumption+,\n        simp add:sc_r_distr,\n        drule_tac x = a in spec,\n        drule_tac a = ha in forall_spec, simp,\n        frule_tac c = \"a \\<cdot>\\<^sub>s ha\" in subsetD[of H \"carrier M\"], assumption+,\n        frule_tac c = h in subsetD[of H \"carrier M\"], assumption+,\n        subst ag_pOp_assoc[THEN sym], assumption+)\n apply (simp add:aGroup.agop_gop[THEN sym], \n        simp add:aGroup.ag_carrier_carrier[THEN sym]) \n apply (frule_tac x = h and y = \"a \\<cdot>\\<^sub>s ha\" in \n                  Group.sg_mult_closed[of \"b_ag M\" H], assumption+)\n apply (frule_tac a = \"a \\<cdot>\\<^sub>s m\" and h = \"h \\<cdot>\\<^bsub>b_ag M\\<^esub> (a \\<cdot>\\<^sub>s ha)\" in \n                  Group.rcs_fixed1[of \"b_ag M\" H], assumption+)\n apply simp\n apply (rule Group.a_in_rcs [of \"b_ag M\" \"H\"], assumption+)\n apply (simp add:aGroup.agop_gop, simp add:aGroup.ag_carrier_carrier)  \n apply (rule ag_pOp_closed, simp add:subsetD, assumption)\n\napply (rule subsetI, simp,\n       frule_tac x = x in Group.rcs_tool2[of \"b_ag M\" H \"a \\<cdot>\\<^sub>s m\"], assumption+,\n       erule bexE,\n       rotate_tac -1, frule sym, thin_tac \"h \\<cdot>\\<^bsub>b_ag M\\<^esub> (a \\<cdot>\\<^sub>s m) = x\",\n       frule Group.a_in_rcs[of \"b_ag M\" H m], assumption+)\n apply blast\ndone\n\nlemma (in Module) mr_cos_sprod_mem:\"\\<lbrakk>submodule R M H; a \\<in> carrier R; \n       X \\<in> set_mr_cos M H\\<rbrakk> \\<Longrightarrow> mr_cos_sprod M H a X \\<in> set_mr_cos M H\"\napply (simp add:set_mr_cos_def)\n apply (erule bexE, rename_tac m, simp) \n apply (subst mr_cos_sprodTr, assumption+)\n apply (frule_tac m = m in sc_mem [of a], assumption)\napply blast\ndone  \n\nlemma (in Module) mr_cos_sprod_assoc:\"\\<lbrakk>submodule R M H; a \\<in> carrier R;\n b \\<in> carrier R; X \\<in> set_mr_cos M H\\<rbrakk> \\<Longrightarrow> mr_cos_sprod  M H (a \\<cdot>\\<^sub>r\\<^bsub>R\\<^esub> b) X = \n                           mr_cos_sprod M H a (mr_cos_sprod M H b X)\"\napply (simp add:set_mr_cos_def, erule bexE, simp)\n apply (frule_tac m = aa in sc_mem [of b], assumption)\n apply (cut_tac sc_Ring,\n        frule Ring.ring_tOp_closed [of \"R\" \"a\" \"b\"], assumption+)\n apply (subst mr_cos_sprodTr, assumption+)+\n apply (simp add: sc_assoc)\ndone\n\nlemma (in Module) mr_cos_sprod_one:\"\\<lbrakk>submodule R M H; X \\<in> set_mr_cos M H\\<rbrakk> \\<Longrightarrow>\n                   mr_cos_sprod M H (1\\<^sub>r\\<^bsub>R\\<^esub>) X = X\"\napply (simp add:set_mr_cos_def, erule bexE, simp,\n       thin_tac \"X = a \\<uplus>\\<^bsub>M\\<^esub> H\")\n apply (cut_tac sc_Ring,\n        frule Ring.ring_one[of \"R\"])\n apply (subst mr_cos_sprodTr, assumption+) \n apply (simp add:sprod_one)\ndone\n\n\n\napply (simp add:submodule_def, (erule conjE)+,\n       frule aGroup.asubg_nsubg, assumption+, simp add:ar_coset_def)\napply (simp add:Group.c_top_welldef[THEN sym, of \"b_ag M\" H m n])\ndone\n\nlemma(in Module) mr_cos_sprod_distrib1:\"\\<lbrakk>submodule R M H; a \\<in> carrier R; \n                b \\<in> carrier R;  X \\<in> set_mr_cos M H\\<rbrakk> \\<Longrightarrow> \n                mr_cos_sprod M H (a \\<plusminus>\\<^bsub>R\\<^esub> b) X =  \n                 mr_cospOp M H (mr_cos_sprod M H a X) (mr_cos_sprod M H b X)\"\napply (simp add:set_mr_cos_def, erule bexE, rename_tac m)\n apply simp\n apply (cut_tac sc_Ring,\n        frule Ring.ring_is_ag[of R])\n apply (frule aGroup.ag_pOp_closed [of R a b], assumption+)\napply (subst mr_cos_sprodTr [of H], assumption+)+\napply (subst mr_cospOpTr, assumption+)\n apply (simp add:sc_mem, simp add:sc_mem)\n apply (simp add:sc_l_distr)\ndone\n\nlemma (in Module) mr_cos_sprod_distrib2:\"\\<lbrakk>submodule R M H; \n a \\<in> carrier R; X \\<in> set_mr_cos M H; Y \\<in> set_mr_cos M H\\<rbrakk> \\<Longrightarrow> \n mr_cos_sprod M H a (mr_cospOp M H X Y) =  \n           mr_cospOp M H (mr_cos_sprod M H a X) (mr_cos_sprod M H a Y)\"\napply (simp add:set_mr_cos_def, (erule bexE)+, rename_tac m n, simp,\n       thin_tac \"X = m \\<uplus>\\<^bsub>M\\<^esub> H\", thin_tac \"Y = n \\<uplus>\\<^bsub>M\\<^esub> H\")\napply (subst mr_cos_sprodTr [of H], assumption+)+\n apply (subst mr_cospOpTr, assumption+)\n apply (subst mr_cospOpTr, assumption+)\n apply (simp add:sc_mem)+\napply (subst mr_cos_sprodTr [of H], assumption+)\n apply (rule ag_pOp_closed, assumption+)\napply (simp add:sc_r_distr)\ndone\n\nlemma (in Module) mr_cosmOpTr:\"\\<lbrakk>submodule R M H; m \\<in> carrier M\\<rbrakk> \\<Longrightarrow> \n                mr_cosmOp M H (m \\<uplus>\\<^bsub>M\\<^esub> H) = (-\\<^sub>a m) \\<uplus>\\<^bsub>M\\<^esub> H\"\napply (simp add:ar_coset_def) \napply (cut_tac module_is_ag)\napply (frule aGroup.b_ag_group)\napply (simp add:ag_carrier_carrier [THEN sym])\napply (simp add:agiop_giop [THEN sym])\napply (simp add:mr_cosmOp_def)\n apply (simp add:submodule_def, (erule conjE)+,\n        frule aGroup.asubg_nsubg[of M H], assumption)\n apply (simp add:Group.c_iop_welldef[of \"b_ag M\" H m])\ndone\n\nlemma (in Module) mr_cos_oneTr:\"submodule R M H \\<Longrightarrow> H =  \\<zero> \\<uplus>\\<^bsub>M\\<^esub> H\"\napply (cut_tac module_is_ag,\n       cut_tac ag_inc_zero)\n apply (simp add:ar_coset_def)\n apply (frule aGroup.b_ag_group)\n apply (simp add:ag_carrier_carrier [THEN sym])\n apply (subst aGroup.agunit_gone[THEN sym, of M], assumption)\n apply (subst Group.rcs_Unit1, assumption)\n apply (simp add:submodule_def, (erule conjE)+, simp add:asubGroup_def)\n apply simp\ndone\n\nlemma (in Module) mr_cos_oneTr1:\"\\<lbrakk>submodule R M H; m \\<in> carrier M\\<rbrakk> \\<Longrightarrow>\n                            mr_cospOp M H H (m \\<uplus>\\<^bsub>M\\<^esub> H) = m \\<uplus>\\<^bsub>M\\<^esub> H\"\napply (subgoal_tac \"mr_cospOp M H (\\<zero> \\<uplus>\\<^bsub>M\\<^esub> H) (m \\<uplus>\\<^bsub>M\\<^esub> H) = m \\<uplus>\\<^bsub>M\\<^esub> H\")\napply (simp add:mr_cos_oneTr [THEN sym, of H])\napply (subst mr_cospOpTr, assumption+)\n apply (simp add:ag_inc_zero)\n apply assumption\n apply (simp add:ag_l_zero)\ndone\n\nlemma (in Module) qmodule_is_ag:\"submodule R M H \\<Longrightarrow> aGroup (M /\\<^sub>m H)\"\napply (cut_tac sc_Ring)\napply (rule aGroup.intro) \n apply (simp add:qmodule_def)\n apply (rule Pi_I)+\n apply (rename_tac X Y)\n apply (simp add:set_mr_cos_def, (erule bexE)+, rename_tac n m, simp)\n apply (subst mr_cospOpTr, assumption+,\n        frule_tac x = n and y = m in ag_pOp_closed, assumption+, blast)\n\n apply (simp add:qmodule_def)\n apply (simp add:set_mr_cos_def, (erule bexE)+, rename_tac a b c m n n')\n apply (simp add:mr_cospOpTr,\n        frule_tac x = m and y = n in ag_pOp_closed, assumption+,\n        frule_tac x = n and y = n' in ag_pOp_closed, assumption+,\n       simp add:mr_cospOpTr, simp add:ag_pOp_assoc)\n\n apply (simp add:qmodule_def) \n  apply (simp add:set_mr_cos_def, (erule bexE)+, rename_tac a b m n, simp)\n  apply (simp add:mr_cospOpTr,\n         simp add:ag_pOp_commute)\n\n apply (simp add:qmodule_def,\n        rule Pi_I,\n        simp add:set_mr_cos_def, erule bexE, simp)\n apply (subst mr_cosmOpTr, assumption+,\n         frule_tac x = a in ag_mOp_closed, blast)\n\n apply (simp add:qmodule_def,\n        simp add:set_mr_cos_def, erule bexE, simp,\n        simp add:mr_cosmOpTr,\n        frule_tac x = aa in ag_mOp_closed)  \n apply (simp add:mr_cospOpTr,\n        frule_tac x = \"-\\<^sub>a aa\" and y = aa in ag_pOp_closed, assumption+,\n        simp add:ag_l_inv1, simp add:mr_cos_oneTr[THEN sym])\n apply (simp add:qmodule_def,\n        simp add:set_mr_cos_def,\n        cut_tac mr_cos_oneTr[of H],\n        cut_tac ag_inc_zero, blast, assumption)\n\n apply (simp add:qmodule_def)\n  apply (simp add:set_mr_cos_def, erule bexE, simp)\n apply (subgoal_tac \"mr_cospOp M H (\\<zero> \\<uplus>\\<^bsub>M\\<^esub> H) (aa \\<uplus>\\<^bsub>M\\<^esub> H) = aa \\<uplus>\\<^bsub>M\\<^esub> H\")\n  apply (simp add:mr_cos_oneTr[THEN sym, of H])\n apply (subst mr_cospOpTr, assumption+,\n        simp add:ag_inc_zero, assumption, simp add:ag_l_zero)\ndone\n\nlemma (in Module) qmodule_module:\"submodule R M H \\<Longrightarrow> R module (M /\\<^sub>m H)\"\napply (rule Module.intro)\napply (simp add:qmodule_is_ag)\napply (rule Module_axioms.intro)\n apply (cut_tac sc_Ring, simp)\n\napply (simp add:qmodule_def)\n apply (simp add:mr_cos_sprod_mem)\n\napply (simp add:qmodule_def)\n apply (simp add:mr_cos_sprod_distrib1[of H])\n\napply (simp add:qmodule_def)\n apply (simp add:mr_cos_sprod_distrib2[of H])\n\napply (simp add:qmodule_def)\n apply (simp add:mr_cos_sprod_assoc)\n\napply (simp add:qmodule_def)\n apply (simp add:mr_cos_sprod_one)\ndone\n\ndefinition\n  indmhom :: \"[('b, 'm) Ring_scheme, ('a, 'b, 'm1) Module_scheme, \n    ('c, 'b, 'm2) Module_scheme, 'a \\<Rightarrow> 'c] \\<Rightarrow>  'a set \\<Rightarrow> 'c\" where\n  \"indmhom R M N f = (\\<lambda>X\\<in> (set_mr_cos M (ker\\<^bsub>M,N\\<^esub> f)). f ( SOME x. x \\<in> X))\"\n\nabbreviation\n  INDMHOM  (\"(4_\\<^sup>\\<flat>\\<^bsub>_ _, _\\<^esub>)\" [92,92,92,93]92) where\n  \"f\\<^sup>\\<flat>\\<^bsub>R M,N\\<^esub> == indmhom R M N f\"\n\n\nlemma (in Module) indmhom_someTr:\"\\<lbrakk>R module N; f \\<in> mHom R M N; \n      X \\<in> set_mr_cos M (ker\\<^bsub>M,N\\<^esub> f)\\<rbrakk> \\<Longrightarrow> f (SOME xa. xa \\<in> X) \\<in> f `(carrier M)\"\napply (simp add:set_mr_cos_def)\n apply (erule bexE, simp) \napply (frule mker_submodule [of N f], assumption+)\napply (simp add:submodule_def) apply (erule conjE)+\napply (simp add:asubGroup_def)\n apply (thin_tac \"\\<forall>a m. a \\<in> carrier R \\<and> m \\<in> ker\\<^bsub>M,N\\<^esub> f \\<longrightarrow> a \\<cdot>\\<^sub>s m \\<in> ker\\<^bsub>M,N\\<^esub> f\")\n apply (cut_tac module_is_ag)\n apply (frule aGroup.b_ag_group)\napply (rule someI2_ex)\n apply (simp add:ar_coset_def)\n apply (frule_tac a = a in Group.a_in_rcs[of \"b_ag M\" \"ker\\<^bsub>M,N\\<^esub> f\"], \n        assumption+, simp add:ag_carrier_carrier [THEN sym], blast)\napply (simp add:ar_coset_def)\n apply (frule_tac a = a and x = x in \n                  Group.rcs_subset_elem[of \"b_ag M\" \"ker\\<^bsub>M,N\\<^esub> f\"], assumption+)\n apply (simp add:ag_carrier_carrier, assumption+)\n\napply (simp add:image_def,\n       simp add:ag_carrier_carrier, blast)\ndone\n\nlemma (in Module) indmhom_someTr1:\"\\<lbrakk>R module N; f \\<in> mHom R M N; m \\<in> carrier M\\<rbrakk>\n        \\<Longrightarrow>  f (SOME xa. xa \\<in> (ar_coset m M (ker\\<^bsub>M,N\\<^esub> f))) = f m\"\napply (rule someI2_ex)\n apply (frule mker_submodule[of N f], assumption)\n apply (frule_tac m_in_mr_coset[of \"ker\\<^bsub>M,N\\<^esub> f\" m], assumption+,\n        blast)\n\n apply (frule mker_submodule [of N f], assumption+) \n apply (frule_tac x = x in x_in_mr_coset [of  \"ker\\<^bsub>M,N\\<^esub> f\" \"m\"], \n                                         assumption+, erule bexE,\n        frule sym , thin_tac \"m \\<plusminus> h = x\", simp)\n apply (simp add:ker_def, erule conjE)\n apply (subst mHom_add[of N f ], assumption+, simp)\napply (frule Module.module_is_ag [of N R])\n apply (frule mHom_mem [of \"N\" \"f\" \"m\"], assumption+)\napply (simp add:aGroup.ag_r_zero)\ndone\n\nlemma (in Module) indmhom_someTr2:\"\\<lbrakk>R module N; f \\<in> mHom R M N; \n       submodule R M H; m \\<in> carrier M; H \\<subseteq> ker\\<^bsub>M,N\\<^esub> f\\<rbrakk> \\<Longrightarrow> \n                       f (SOME xa. xa \\<in> m \\<uplus>\\<^bsub>M\\<^esub> H) = f m\"\napply (rule someI2_ex)\n  apply (frule_tac m_in_mr_coset[of \"H\" m], assumption+, blast) \n   apply (frule_tac x = x in x_in_mr_coset [of  H m], \n                                         assumption+, erule bexE,\n        frule sym , thin_tac \"m \\<plusminus> h = x\", simp)\n apply (frule_tac c = h in subsetD[of H \"ker\\<^bsub>M,N\\<^esub> f\"], assumption+)\n apply (frule mker_submodule [of N f], assumption+, \n         simp add:submodule_def[of R M \"ker\\<^bsub>M,N\\<^esub> f\"], (erule conjE)+,\n        frule_tac c = h in subsetD[of \"ker\\<^bsub>M,N\\<^esub> f\" \"carrier M\"], assumption+)\n apply (simp add:ker_def mHom_add,\n        frule_tac m = m in mHom_mem[of \"N\" \"f\"], assumption+)\n apply (frule Module.module_is_ag[of N R])\n apply (simp add:aGroup.ag_r_zero)\ndone\n\nlemma (in Module) indmhomTr1:\"\\<lbrakk>R module N; f \\<in> mHom R M N; m \\<in> carrier M\\<rbrakk> \\<Longrightarrow>\n               (f\\<^sup>\\<flat>\\<^bsub>R M,N\\<^esub>) (m \\<uplus>\\<^bsub>M\\<^esub> (ker\\<^bsub>M,N\\<^esub> f)) = f m\" \napply (simp add:indmhom_def)\napply (subgoal_tac \"m \\<uplus>\\<^bsub>M\\<^esub> ker\\<^bsub>M,N\\<^esub> f \\<in> set_mr_cos M (ker\\<^bsub>M,N\\<^esub> f)\", simp)\n apply (rule indmhom_someTr1, assumption+)\n apply (rule set_mr_cos_mem)\napply (rule mker_submodule, assumption+)\ndone\n\nlemma (in Module) indmhomTr2:\"\\<lbrakk>R module N; f \\<in> mHom R M N\\<rbrakk> \n      \\<Longrightarrow> (f\\<^sup>\\<flat>\\<^bsub>R M,N\\<^esub>) \\<in> set_mr_cos M (ker\\<^bsub>M,N\\<^esub> f) \\<rightarrow> carrier N\" \n apply (rule Pi_I)\n apply (simp add:set_mr_cos_def)\n apply (erule bexE)\n apply (frule_tac m = a in indmhomTr1 [of N f], assumption+)\n apply (simp add:mHom_mem)\ndone\n\nlemma (in Module) indmhom:\"\\<lbrakk>R module N; f \\<in> mHom R M N\\<rbrakk> \n                           \\<Longrightarrow> (f\\<^sup>\\<flat>\\<^bsub>R M,N\\<^esub>) \\<in> mHom R (M /\\<^sub>m (ker\\<^bsub>M,N\\<^esub> f)) N\"\napply (simp add:mHom_def [of R \"M /\\<^sub>m (ker\\<^bsub>M,N\\<^esub> f)\" N])\napply (rule conjI)\n apply (simp add:aHom_def)\n apply (rule conjI)\n apply (simp add:qmodule_def)\n apply (simp add:indmhomTr2)\n\napply (rule conjI)\n apply (simp add:qmodule_def indmhom_def extensional_def) \n\napply (rule ballI)+\n apply (simp add:qmodule_def)\n apply (simp add:set_mr_cos_def, (erule bexE)+, simp, rename_tac  m n)\n apply (frule mker_submodule [of N f], assumption+,\n        simp add:mr_cospOpTr,\n        frule_tac x = m and y = n in ag_pOp_closed, assumption+)\n apply (simp add:indmhomTr1, simp add:mHom_add)\n\n apply (rule ballI)+ \n apply (simp add:qmodule_def)\n apply (simp add:set_mr_cos_def, (erule bexE)+, simp)\n apply (frule mker_submodule [of N f], assumption+,\n        subst mr_cos_sprodTr [of \"ker\\<^bsub>M,N\\<^esub> f\"], assumption+,\n        frule_tac a = a and m = aa in sc_mem, assumption)\n apply (simp add:indmhomTr1)\n apply (simp add:mHom_lin)\ndone\n\nlemma (in Module) indmhom_injec:\"\\<lbrakk>R module N; f \\<in> mHom R M N\\<rbrakk> \\<Longrightarrow>\n       injec\\<^bsub>(M /\\<^sub>m (ker\\<^bsub>M,N\\<^esub> f)),N\\<^esub> (f\\<^sup>\\<flat>\\<^bsub>R M,N\\<^esub>)\"\napply (simp add:injec_def)\napply (frule indmhom [of N f], assumption+)\napply (rule conjI)\napply (simp add:mHom_def)\napply (simp add:ker_def [of  _ _ \"f\\<^sup>\\<flat>\\<^bsub>R M, N\\<^esub>\"])\napply (simp add:qmodule_def) apply (fold qmodule_def)\napply (rule equalityI)\n apply (rule subsetI) apply (simp add:CollectI) apply (erule conjE)\n apply (simp add:set_mr_cos_def, erule bexE, simp)\n apply (simp add:indmhomTr1)\napply (frule mker_submodule [of N f], assumption+)\n apply (rule_tac h1 = a in mr_cos_h_stable [THEN sym, of \"ker\\<^bsub>M,N\\<^esub> f\"], \n         assumption+)\n apply (simp add:ker_def)\n\napply (rule subsetI) apply (simp add:CollectI)\n apply (rule conjI)\n apply (simp add:set_mr_cos_def)\n apply (frule mker_submodule [of N f], assumption+)\n apply (frule mr_cos_oneTr [of \"ker\\<^bsub>M,N\\<^esub> f\"])\n apply (cut_tac  ag_inc_zero)\n apply blast\n apply (frule mker_submodule [of N f], assumption+) \napply (subst mr_cos_oneTr [of \"ker\\<^bsub>M,N\\<^esub> f\"], assumption)\n apply (cut_tac  ag_inc_zero)        \n apply (subst indmhomTr1, assumption+)\n apply (simp add:mHom_0)\ndone\n\nlemma (in Module) indmhom_surjec1:\"\\<lbrakk>R module N; surjec\\<^bsub>M,N\\<^esub> f;\n f \\<in> mHom R M N\\<rbrakk> \\<Longrightarrow> surjec\\<^bsub>(M /\\<^sub>m (ker\\<^bsub>M,N\\<^esub> f)),N\\<^esub> (f\\<^sup>\\<flat>\\<^bsub>R M,N\\<^esub>)\"\napply (simp add:surjec_def)\n apply (frule indmhom [of N f], assumption+)\n apply (rule conjI)\n apply (simp add:mHom_def)\napply (rule surj_to_test)\n apply (simp add:mHom_def aHom_def)\napply (rule ballI)\n apply (erule conjE) \n apply (simp add:surj_to_def, frule sym , thin_tac \"f ` carrier M = carrier N\",\n        simp,\n        thin_tac \"carrier N = f ` carrier M\")\n apply (simp add:image_def, erule bexE, simp)\n apply (frule_tac m = x in indmhomTr1 [of N f], assumption+)\n apply (frule mker_submodule [of N f], assumption+)\n apply (simp add:qmodule_carr)\n apply (frule_tac m = x in set_mr_cos_mem [of \"ker\\<^bsub>M,N\\<^esub> f\"], assumption+)\napply blast\ndone\n\nlemma (in Module) module_homTr:\"\\<lbrakk>R module N; f \\<in> mHom R M N\\<rbrakk> \\<Longrightarrow>\n                           f \\<in> mHom R M (mimg\\<^bsub>R M,N\\<^esub> f)\"\napply (subst mHom_def, simp add:CollectI)\n apply (rule conjI)\n apply (simp add:aHom_def)\n apply (rule conjI)\n apply (simp add:mimg_def mdl_def)\napply (rule conjI)\n apply (simp add:mHom_def aHom_def extensional_def)\napply (rule ballI)+\n apply (simp add:mimg_def mdl_def)\n apply (simp add:mHom_add)\napply (rule ballI)+\n apply (simp add:mimg_def mdl_def)\n apply (simp add:mHom_lin)\ndone\n\nlemma (in Module) ker_to_mimg:\"\\<lbrakk>R module N; f \\<in> mHom R M N\\<rbrakk> \\<Longrightarrow>\n                ker\\<^bsub>M,mimg\\<^bsub>R M,N\\<^esub> f\\<^esub> f = ker\\<^bsub>M,N\\<^esub> f\"\napply (rule equalityI)\n apply (rule subsetI)\n apply (simp add:ker_def mimg_def mdl_def)\n apply (rule subsetI)\n apply (simp add:ker_def mimg_def mdl_def) \ndone\n\nlemma (in Module) module_homTr1:\"\\<lbrakk>R module N; f \\<in> mHom R M N\\<rbrakk> \\<Longrightarrow>\n   (mimg\\<^bsub>R (M /\\<^sub>m (ker\\<^bsub>M,N\\<^esub> f)),N\\<^esub> (f\\<^sup>\\<flat>\\<^bsub>R M,N\\<^esub>)) = mimg\\<^bsub>R M,N\\<^esub> f\"    apply (simp add:mimg_def)\napply (subgoal_tac \"f\\<^sup>\\<flat>\\<^bsub>R M, N\\<^esub> ` carrier (M /\\<^sub>m (ker\\<^bsub>M,N\\<^esub> f))  = f ` carrier M \",\n       simp)\napply (simp add:qmodule_def)\napply (rule equalityI)\n apply (rule subsetI)\n apply (simp add:image_def set_mr_cos_def)\n apply (erule exE, erule conjE, erule bexE, simp)\n apply (simp add:indmhomTr1, blast)\napply (rule subsetI,\n       simp add:image_def set_mr_cos_def, erule bexE, simp)\n apply (frule_tac m1 = xa in indmhomTr1 [THEN sym, of N f], \n                                                     assumption+)\n apply blast\ndone\n\nlemma (in Module) module_Homth_1:\"\\<lbrakk>R module N; f \\<in> mHom R M N\\<rbrakk> \\<Longrightarrow>\n                     M /\\<^sub>m (ker\\<^bsub>M,N\\<^esub> f) \\<cong>\\<^bsub>R\\<^esub> mimg\\<^bsub>R M,N\\<^esub> f\"\napply (frule surjec_to_mimg[of N f], assumption,\n       frule module_homTr[of N f], assumption,\n       frule mimg_module[of N f], assumption,\n       frule indmhom_surjec1[of \"mimg\\<^bsub>R M,N\\<^esub> f\" f], assumption+,\n       frule indmhom_injec[of \"mimg\\<^bsub>R M,N\\<^esub> f\" f], assumption+,\n       frule indmhom[of \"mimg\\<^bsub>R M,N\\<^esub> f\" f], assumption+)\napply (simp add:misomorphic_def,\n       simp add:bijec_def)\napply (simp add:ker_to_mimg)\napply blast\ndone\n\ndefinition\n  mpj :: \"[('a, 'r, 'm) Module_scheme, 'a set] \\<Rightarrow>  ('a => 'a set)\" where\n  \"mpj M H = (\\<lambda>x\\<in>carrier M. x \\<uplus>\\<^bsub>M\\<^esub> H)\" \n\nlemma (in Module) elem_mpj:\"\\<lbrakk>m \\<in> carrier M; submodule R M H\\<rbrakk> \\<Longrightarrow>\n                                                 mpj M H m = m \\<uplus>\\<^bsub>M\\<^esub> H\"\nby (simp add:mpj_def)\n\nlemma (in Module) mpj_mHom:\"submodule R M H \\<Longrightarrow> mpj M H \\<in> mHom R M (M /\\<^sub>m H)\"\napply (simp add:mHom_def)\napply (rule conjI)\n apply (simp add:aHom_def)\n apply (rule conjI)\n apply (simp add:mpj_def qmodule_carr set_mr_cos_mem)\napply (rule conjI)\n apply (simp add:mpj_def extensional_def)\napply (rule ballI)+\n apply (simp add:qmodule_def)\n apply (simp add:mpj_def, simp add:ag_pOp_closed)\n apply (simp add:mr_cospOpTr)\napply (rule ballI)+\n apply (simp add:mpj_def sc_mem)\n apply (simp add:qmodule_def)\n apply (simp add:mr_cos_sprodTr)\ndone\n \nlemma (in Module) mpj_mem:\"\\<lbrakk>submodule R M H; m \\<in> carrier M\\<rbrakk> \\<Longrightarrow>\n                                mpj M H m \\<in> carrier (M /\\<^sub>m H)\"\napply (frule mpj_mHom[of H])\napply (rule mHom_mem [of \"M /\\<^sub>m H\" \"mpj M H\" \"m\"])\n apply (simp add:qmodule_module) apply assumption+\ndone\n\nlemma (in Module) mpj_surjec:\"submodule R M H \\<Longrightarrow>\n                             surjec\\<^bsub>M,(M /\\<^sub>m H)\\<^esub> (mpj M H)\" \napply (simp add:surjec_def)\napply (frule mpj_mHom [of H])\napply (rule conjI, simp add:mHom_def)\napply (rule surj_to_test,\n       simp add:mHom_def aHom_def)\napply (rule ballI)\n apply (thin_tac \"mpj M H \\<in> mHom R M (M /\\<^sub>m H)\")\n\n apply (simp add:qmodule_def)\napply (simp add:set_mr_cos_def, erule bexE, simp)\n apply (frule_tac m = a in elem_mpj[of _ H], assumption, blast)\ndone\n\nlemma (in Module) mpj_0:\"\\<lbrakk>submodule R M H; h \\<in> H\\<rbrakk> \\<Longrightarrow>\n                                 mpj M H h  = \\<zero>\\<^bsub>(M /\\<^sub>m H)\\<^esub>\"\napply (simp add:submodule_def, (erule conjE)+)\n apply (frule_tac c = h in subsetD[of H \"carrier M\"], assumption+)\n apply (subst elem_mpj[of _ H], assumption+,\n        simp add:submodule_def)\n apply (simp add:qmodule_def)\n apply (rule mr_cos_h_stable[THEN sym],\n        simp add:submodule_def, assumption)\ndone\n\nlemma (in Module) mker_of_mpj:\"submodule R M H \\<Longrightarrow>\n                                 ker\\<^bsub>M,(M /\\<^sub>m H)\\<^esub> (mpj M H) = H\"\napply (simp add:ker_def)\napply (rule equalityI)\napply (rule subsetI, simp, erule conjE)\n apply (simp add:elem_mpj, simp add:qmodule_def)\n apply (frule_tac m = x in m_in_mr_coset [of H], assumption+)\n apply simp\napply (rule subsetI)\n apply simp\n apply (simp add:submodule_def, (erule conjE)+)\n apply (simp add:subsetD)\n apply (subst elem_mpj,\n        simp add:subsetD, simp add:submodule_def) \n apply (simp add:qmodule_def)\n apply (rule mr_cos_h_stable[THEN sym],\n        simp add:submodule_def, assumption)\ndone\n\nlemma (in Module) indmhom1:\"\\<lbrakk>submodule R M H; R module N; f \\<in> mHom R M N;  H \\<subseteq> ker\\<^bsub>M,N\\<^esub> f\\<rbrakk> \\<Longrightarrow> \\<exists>!g. g \\<in> (mHom R (M /\\<^sub>m H) N) \\<and> (compos M g (mpj M H)) = f\" \napply (rule ex_ex1I)\napply (subgoal_tac \"(\\<lambda>X\\<in>set_mr_cos M H. f (SOME x. x \\<in> X)) \\<in> mHom R  (M /\\<^sub>m H) N \\<and> compos M (\\<lambda>X\\<in>set_mr_cos M H. f (SOME x. x \\<in> X)) (mpj M H) = f\")\napply blast\n apply (rule conjI)\n apply (rule Module.mHom_test)\n apply (simp add:qmodule_module, assumption+)\n apply (rule conjI)\n apply (rule Pi_I)\n apply (simp add:qmodule_def, simp add:set_mr_cos_def, erule bexE, simp)\n apply (simp add:indmhom_someTr2, simp add:mHom_mem)\n\n apply (rule conjI)\n apply (simp add:qmodule_def)\n\n apply (rule conjI, (rule ballI)+)\n apply (simp add:qmodule_def, simp add:set_mr_cos_def, (erule bexE)+, simp)\n apply (simp add:mr_cospOpTr,\n        frule_tac x = a and y = aa in ag_pOp_closed, assumption+)\n  apply (simp add:indmhom_someTr2, simp add:mHom_add)\n  apply (rule impI) \n  apply (frule_tac x = \"a \\<plusminus> aa\" in bspec, assumption+, simp)\n\n apply ((rule ballI)+,\n        simp add:qmodule_def, simp add:set_mr_cos_def, erule bexE, simp,\n        simp add:mr_cos_sprodTr,\n        frule_tac a = a and m = aa in sc_mem, assumption)\n apply (simp add:indmhom_someTr2, simp add:mHom_lin,\n        rule impI,\n        frule_tac x = \"a \\<cdot>\\<^sub>s aa\" in bspec, assumption, simp)\n apply (rule mHom_eq[of N _ f], assumption)\n apply (rule Module.mHom_compos[of \"M /\\<^sub>m H\" R M N \"mpj M H\" \n         \"\\<lambda>X\\<in>set_mr_cos M H. f (SOME x. x \\<in> X)\"]) apply (\n        simp add:qmodule_module, rule Module_axioms, assumption,\n        simp add:mpj_mHom)\n apply (rule Module.mHom_test,\n        simp add:qmodule_module, assumption)\n apply (rule conjI,\n        rule Pi_I,\n        clarsimp simp: qmodule_def set_mr_cos_def indmhom_someTr2 mHom_mem)\n apply (rule conjI,\n       simp add:qmodule_def)\n apply (rule conjI,\n        (rule ballI)+, simp add:qmodule_def, simp add:set_mr_cos_def,\n        (erule bexE)+, simp add:mr_cospOpTr,\n        frule_tac x = a and y = aa in ag_pOp_closed, assumption+,\n        simp add:indmhom_someTr2 mHom_add,\n        rule impI, \n        frule_tac x = \"a \\<plusminus> aa\" in bspec, assumption, simp) \n apply ((rule ballI)+, simp add:qmodule_def set_mr_cos_def, erule bexE, simp,\n        simp add:mr_cos_sprodTr,\n        frule_tac a = a and m = aa in sc_mem, assumption,\n        simp add:indmhom_someTr2 mHom_lin,\n        rule impI,\n        frule_tac x = \"a \\<cdot>\\<^sub>s aa\" in bspec, assumption, simp, \n        assumption+) \n apply (rule ballI, simp add:compos_def compose_def elem_mpj,\n        simp add:indmhom_someTr2,\n        rule impI, simp add:set_mr_cos_def,\n        frule_tac x = m in bspec, assumption, simp)\n \n apply (erule conjE)+ \n apply (rule_tac f = g and g = y in Module.mHom_eq[of \"M /\\<^sub>m H\" R N],\n        simp add:qmodule_module, assumption+) \n apply (rule ballI, simp add:qmodule_def, fold qmodule_def,\n        simp add:set_mr_cos_def, erule bexE, simp)\n apply (rotate_tac -3, frule sym, thin_tac \"compos M y (mpj M H) = f\", \n        simp)\n apply (frule_tac f = \"compos M g (mpj M H)\" and g = \"compos M y (mpj M H)\"\n        and x = a in eq_fun_eq_val,\n        thin_tac \"compos M g (mpj M H) = compos M y (mpj M H)\")\n apply (simp add:compos_def compose_def elem_mpj)\ndone\n\ndefinition\n  mQmp :: \"[('a, 'r, 'm) Module_scheme, 'a set, 'a set] \\<Rightarrow> \n                                                   ('a set \\<Rightarrow> 'a set)\" where\n  \"mQmp M H N = (\\<lambda>X\\<in> set_mr_cos M H. {z. \\<exists> x \\<in> X. \\<exists> y \\<in> N. (y \\<plusminus>\\<^bsub>M\\<^esub> x = z)})\"\n             (* H \\<subseteq> N *)\n\nabbreviation\n  MQP  (\"(3Mp\\<^bsub>_  _,_\\<^esub>)\" [82,82,83]82) where\n  \"Mp\\<^bsub>M H,N\\<^esub> == mQmp M H N\"\n\n (* \"\\<lbrakk> R Module M; H \\<subseteq> N \\<rbrakk> \\<Longrightarrow> Mp\\<^bsub>M H,N\\<^esub> \\<in> rHom (M /\\<^sub> m H) (M /\\<^sub>m N)\"  *)\n\nlemma (in Module) mQmpTr0:\"\\<lbrakk>submodule R M H; submodule R M N; H \\<subseteq> N;\n m \\<in> carrier M\\<rbrakk> \\<Longrightarrow>  mQmp M H N (m \\<uplus>\\<^bsub>M\\<^esub> H) = m \\<uplus>\\<^bsub>M\\<^esub> N\"\napply (frule set_mr_cos_mem [of H m], assumption+)\napply (simp add:mQmp_def)\napply (rule equalityI)\n apply (rule subsetI, simp, (erule bexE)+, rotate_tac -1, frule sym,\n        thin_tac \"y \\<plusminus> xa = x\", simp)\n apply (frule_tac x = xa in x_in_mr_coset[of H m], assumption+, erule bexE,\n        rotate_tac -1, frule sym, thin_tac \"m \\<plusminus> h = xa\", simp)\n apply (unfold submodule_def, frule conjunct1, rotate_tac 1, frule conjunct1,\n        fold submodule_def,\n        frule_tac c = y in subsetD[of N \"carrier M\"], assumption+,\n        frule_tac c = h in subsetD[of H \"carrier M\"], assumption+,\n        simp add:ag_pOp_assoc[THEN sym],\n        simp add:ag_pOp_commute[of _ m], simp add:ag_pOp_assoc,\n        frule_tac c = h in subsetD[of H N], assumption+,\n        frule_tac h = y and k = h in submodule_pOp_closed[of N], assumption+,\n        frule_tac h1 = \"y \\<plusminus> h\" in mr_cos_h_stable1[THEN sym, of N m], \n        assumption+, simp)\n apply (rule m_in_mr_coset, assumption+,\n        rule ag_pOp_closed, assumption+, simp add:subsetD)\n\n apply (rule subsetI, simp,\n        frule_tac x = x in x_in_mr_coset[of N m], assumption+,\n        erule bexE, frule sym, thin_tac \"m \\<plusminus> h = x\", simp,\n        simp add:submodule_def[of R M N], frule conjunct1, fold submodule_def,\n        frule_tac c = h in subsetD[of N \"carrier M\"], assumption+)\napply (frule_tac m_in_mr_coset[of H m], assumption+,\n        subst ag_pOp_commute[of m], assumption+)\n apply blast\ndone\n\n  (* show mQmp M H N is a welldefined map from M/H to M/N. step2 *)\nlemma (in Module) mQmpTr1:\"\\<lbrakk>submodule R M H; submodule R M N; H \\<subseteq> N;\n m \\<in> carrier M; n \\<in> carrier M; m \\<uplus>\\<^bsub>M\\<^esub> H = n \\<uplus>\\<^bsub>M\\<^esub> H\\<rbrakk> \\<Longrightarrow>  m \\<uplus>\\<^bsub>M\\<^esub> N = n \\<uplus>\\<^bsub>M\\<^esub> N\"\napply (frule_tac m_in_mr_coset [of H m], assumption+)\napply simp\napply (frule_tac x_in_mr_coset [of H n m], assumption+) \napply (erule bexE, rotate_tac -1, frule sym, thin_tac \"n \\<plusminus> h = m\", simp)\napply (frule_tac c = h in subsetD [of \"H\" \"N\"], assumption+)\napply (rule mr_cos_h_stable1[of N n], assumption+)\ndone\n   \nlemma (in Module) mQmpTr2:\"\\<lbrakk>submodule R M H; submodule R M N; H \\<subseteq> N ; \n        X \\<in> carrier (M /\\<^sub>m H)\\<rbrakk> \\<Longrightarrow> (mQmp M H N) X \\<in> carrier (M /\\<^sub>m N)\" \napply (simp add:qmodule_def)\napply (simp add:set_mr_cos_def)\napply (erule bexE, simp)\n apply (frule_tac m = a in mQmpTr0 [of H N], assumption+)\napply blast\ndone\n\nlemma (in Module) mQmpTr2_1:\"\\<lbrakk>submodule R M H; submodule R M N; H \\<subseteq> N \\<rbrakk>\n \\<Longrightarrow> mQmp M H N \\<in> carrier (M /\\<^sub>m H) \\<rightarrow> carrier (M /\\<^sub>m N)\"\nby (simp add:mQmpTr2)\n\nlemma (in Module) mQmpTr3:\"\\<lbrakk>submodule R M H; submodule R M N; H \\<subseteq> N ; \nX \\<in> carrier (M /\\<^sub>m H); Y \\<in> carrier (M /\\<^sub>m H)\\<rbrakk> \\<Longrightarrow> (mQmp M H N) (mr_cospOp M H X Y) = mr_cospOp M N ((mQmp M H N) X) ((mQmp M H N) Y)\" \napply (simp add:qmodule_def)\napply (simp add:set_mr_cos_def)\napply ((erule bexE)+, simp)\napply (simp add:mr_cospOpTr)\napply (frule_tac x = a and y = aa in ag_pOp_closed, assumption+)\napply (subst mQmpTr0, assumption+)+\napply (subst mr_cospOpTr, assumption+) \napply simp\ndone\n     \nlemma (in Module) mQmpTr4:\"\\<lbrakk>submodule R M H; submodule R M N; H \\<subseteq> N;\n                            a \\<in> N\\<rbrakk> \\<Longrightarrow> mr_coset a (mdl M N) H = mr_coset a M H\"\napply (simp add:mr_coset_def)\n apply (unfold submodule_def[of R M N], frule conjunct1, fold submodule_def,\n        frule subsetD[of N \"carrier M\" a], assumption+)\napply (rule equalityI)\n apply (rule subsetI)\n apply (frule mdl_is_module[of N])\n apply (frule_tac x = x in Module.x_in_mr_coset[of \"mdl M N\" R H a])\n apply (simp add:submodule_of_mdl)\n apply (simp add:mdl_carrier)\n apply assumption+\n apply (erule bexE)\n apply (unfold submodule_def[of R M H], frule conjunct1, fold submodule_def)\n apply (frule_tac c = h in subsetD[of H \"carrier M\"], assumption+)\n apply (thin_tac \"x \\<in> a \\<uplus>\\<^bsub>mdl M N\\<^esub> H\", thin_tac \"R module mdl M N\",\n        simp add:mdl_def)\n apply (frule sym, thin_tac \"a \\<plusminus> h = x\", simp)\n apply (subst mr_cos_h_stable1[THEN sym, of H a], assumption+)\n apply (frule_tac x = a and y = h in ag_pOp_closed, assumption+)\n apply (rule m_in_mr_coset, assumption+)\n\napply (rule subsetI)\n apply (frule_tac x = x in x_in_mr_coset[of H a], assumption+)\n apply (erule bexE, frule sym, thin_tac \"a \\<plusminus> h = x\", simp)\n apply (frule mdl_is_module[of N])\n apply (frule submodule_of_mdl[of H N], assumption+)\n apply (subst Module.mr_cos_h_stable1[THEN sym, of \"mdl M N\" R H a],\n         assumption+, simp add:mdl_carrier, simp)\n apply (subgoal_tac \"a \\<plusminus> h = a \\<plusminus>\\<^bsub>mdl M N\\<^esub> h\", simp)\n apply (rule Module.m_in_mr_coset[of \"mdl M N\" R H], assumption+)\n apply (frule Module.module_is_ag[of \"mdl M N\" R])\n apply (rule aGroup.ag_pOp_closed, assumption,\n        simp add:mdl_carrier, simp add:mdl_carrier subsetD)\n apply (subst mdl_def, simp)\ndone\n\nlemma (in Module) mQmp_mHom:\"\\<lbrakk>submodule R M H; submodule R M N; H \\<subseteq> N\\<rbrakk> \\<Longrightarrow>\n                  (Mp\\<^bsub>M H,N\\<^esub>) \\<in> mHom R (M /\\<^sub>m H) (M /\\<^sub>m N)\"\napply (simp add:mHom_def)\napply (rule conjI)  \n apply (simp add:aHom_def)\n apply (simp add:mQmpTr2_1)\napply (rule conjI)\n apply (simp add:mQmp_def extensional_def qmodule_def)\n apply (rule ballI)+\n apply (frule_tac X1 = a and Y1 = b in mQmpTr3 [THEN sym, of H N],\n                                               assumption+) \n apply (simp add:qmodule_def)\n\napply (rule ballI)+\n apply (simp add:qmodule_def)\n apply (simp add:set_mr_cos_def)\n apply (erule bexE, simp)\n apply (subst mr_cos_sprodTr, assumption+)\n apply (frule_tac a = a and m = aa in sc_mem, assumption)\n apply (simp add:mQmpTr0)\n apply (subst mr_cos_sprodTr, assumption+)\napply simp\ndone\n    \nlemma (in Module) Mp_surjec:\"\\<lbrakk>submodule R M H; submodule R M N; H \\<subseteq> N\\<rbrakk> \\<Longrightarrow> \n                surjec\\<^bsub>(M /\\<^sub>m H),(M /\\<^sub>m N)\\<^esub> (Mp\\<^bsub>M H,N\\<^esub>)\" \napply (simp add:surjec_def)\n apply (frule mQmp_mHom [of H N], assumption+)\n apply (rule conjI)\n apply (simp add:mHom_def)\napply (rule surj_to_test)\n apply (simp add:mHom_def aHom_def)\n apply (rule ballI)\n apply (thin_tac \"Mp\\<^bsub>M  H,N\\<^esub> \\<in> mHom R (M /\\<^sub>m H) (M /\\<^sub>m N)\")\n apply (simp add:qmodule_def)\n apply (simp add:set_mr_cos_def, erule bexE, simp)\n apply (frule_tac m = a in mQmpTr0 [of H N], assumption+)\n apply blast\ndone\n\nlemma (in Module) kerQmp:\"\\<lbrakk>submodule R M H; submodule R M N; H \\<subseteq> N\\<rbrakk> \n \\<Longrightarrow> ker\\<^bsub>(M /\\<^sub>m H),(M /\\<^sub>m N)\\<^esub> (Mp\\<^bsub>M H,N\\<^esub>) = carrier ((mdl M N) /\\<^sub>m H)\"   \napply (simp add:ker_def)\napply (rule equalityI)\n apply (rule subsetI)\n apply (simp add:CollectI, erule conjE)\n apply (simp add:qmodule_def)\n apply (simp add:set_mr_cos_def [of \"mdl M N\" \"H\"])\n apply (simp add:set_mr_cos_def)\n apply (erule bexE, simp)\n apply (simp add:mQmpTr0)\n apply (frule_tac m = a in m_in_mr_coset[of N], assumption+, simp)\n apply (frule_tac a = a in mQmpTr4[of H N], assumption+,\n        simp add:mr_coset_def,\n        rotate_tac -1, frule sym,thin_tac \"a \\<uplus>\\<^bsub>mdl M N\\<^esub> H = a \\<uplus>\\<^bsub>M\\<^esub> H\",\n        simp only:mdl_carrier, blast)\n\n apply (rule subsetI)\n apply (simp add:qmodule_def)\n apply (simp add:set_mr_cos_def [of \"mdl M N\" \"H\"])\n apply (erule bexE, simp)\n apply (simp add:mdl_carrier)\n  apply (frule_tac a = a in mQmpTr4[of H N], assumption+,\n         simp add:mr_coset_def)\n apply (thin_tac \"a \\<uplus>\\<^bsub>mdl M N\\<^esub> H = a \\<uplus>\\<^bsub>M\\<^esub> H\")\n apply (unfold submodule_def[of R M N], frule conjunct1, fold submodule_def,\n        frule_tac c = a in subsetD[of N \"carrier M\"], assumption+)\n apply (rule conjI) \n apply (simp add:set_mr_cos_def, blast)\n apply (simp add:mQmpTr0)\n  apply (simp add:mr_cos_h_stable [THEN sym])\ndone\n\nlemma (in Module) misom2Tr:\"\\<lbrakk>submodule R M H; submodule R M N; H \\<subseteq> N\\<rbrakk> \\<Longrightarrow> \n            (M /\\<^sub>m H) /\\<^sub>m (carrier ((mdl M N) /\\<^sub>m H)) \\<cong>\\<^bsub>R\\<^esub> (M /\\<^sub>m N)\"\napply (frule mQmp_mHom [of H N], assumption+)\napply (frule qmodule_module [of H])\napply (frule qmodule_module [of N]) thm Module.indmhom\napply (frule Module.indmhom [of \"M /\\<^sub>m H\" R \"M /\\<^sub>m N\" \"Mp\\<^bsub>M H,N\\<^esub>\"], assumption+)\napply (simp add:kerQmp)\napply (subgoal_tac \"bijec\\<^bsub>((M /\\<^sub>m H) /\\<^sub>m (carrier((mdl M N) /\\<^sub>m H))),(M /\\<^sub>m N)\n\\<^esub> (indmhom R (M /\\<^sub>m H) (M /\\<^sub>m N) (mQmp M H N))\")\napply (simp add:misomorphic_def) apply blast\napply (simp add:bijec_def)\napply (rule conjI)\n apply (simp add:kerQmp [THEN sym])\n apply (rule Module.indmhom_injec [of \"M /\\<^sub>m H\" R \"M /\\<^sub>m N\" \"Mp\\<^bsub>M H,N\\<^esub>\"], assumption+)\napply (frule Mp_surjec [of H N], assumption+)\n apply (simp add:kerQmp [THEN sym])\n apply (rule Module.indmhom_surjec1, assumption+)\ndone\n\nlemma (in Module) eq_class_of_Submodule:\"\\<lbrakk>submodule R M H; submodule R M N; \n         H \\<subseteq> N\\<rbrakk> \\<Longrightarrow> carrier ((mdl M N) /\\<^sub>m H) = N \\<^sub>s/\\<^sub>M H\"\napply (rule equalityI)\n apply (rule subsetI) apply (simp add:qmodule_def)\n apply (simp add:set_mr_cos_def) apply (erule bexE, simp)\n apply (frule_tac a = a in mQmpTr4 [of H N], assumption+)\n apply (simp add:mdl_def) apply (simp add:mr_coset_def)\n apply (simp add:sub_mr_set_cos_def)\n apply (simp add:mdl_carrier, blast)\n\napply (rule subsetI)\napply (simp add:qmodule_def)\n apply (simp add:set_mr_cos_def)\n apply (simp add:sub_mr_set_cos_def)\n apply (erule bexE, simp add:mdl_carrier)\n apply (frule_tac a1 = n in mQmpTr4[THEN sym, of H N], assumption+)\n apply (simp add:mr_coset_def)\n apply blast\ndone\n\ntheorem (in Module) misom2:\"\\<lbrakk>submodule R M H; submodule R M N; H \\<subseteq> N\\<rbrakk> \\<Longrightarrow> \n                           (M /\\<^sub>m H) /\\<^sub>m (N \\<^sub>s/\\<^sub>M H) \\<cong>\\<^bsub>R\\<^esub> (M /\\<^sub>m N)\"\napply (frule misom2Tr [of H N], assumption+)\napply (simp add:eq_class_of_Submodule)\ndone\n\nprimrec natm :: \"('a, 'm) aGroup_scheme  => nat \\<Rightarrow> 'a  => 'a\"\nwhere\n  natm_0:  \"natm M 0 x = \\<zero>\\<^bsub>M\\<^esub>\"\n| natm_Suc:  \"natm M (Suc n) x = (natm M n x) \\<plusminus>\\<^bsub>M\\<^esub> x\"\n\ndefinition\n  finitesum_base :: \"[('a, 'r, 'm) Module_scheme, 'b set, 'b \\<Rightarrow> 'a set]\n                      \\<Rightarrow> 'a set \" where\n  \"finitesum_base M I f = \\<Union>{f i | i. i \\<in> I}\" \n\ndefinition\n  finitesum :: \"[('a, 'r, 'm) Module_scheme, 'b set, 'b \\<Rightarrow> 'a set]\n                      \\<Rightarrow> 'a set \" where\n  \"finitesum M I f = {x. \\<exists>n. \\<exists>g. g \\<in> {j. j \\<le> (n::nat)} \\<rightarrow> finitesum_base M I f\n                                           \\<and> x =  nsum M g n}\"\n\n\nlemma (in Module) finitesumbase_sub_carrier:\"f \\<in> I \\<rightarrow> {X. submodule R M X} \\<Longrightarrow>\n             finitesum_base M I f \\<subseteq> carrier M\"\napply (simp add:finitesum_base_def)\napply (rule subsetI)\n apply (simp add:CollectI)\n apply (erule exE, erule conjE, erule exE, erule conjE)\n apply (frule_tac x = i in funcset_mem[of f I \"{X. submodule R M X}\"], \n         assumption+, simp)\n apply (thin_tac \"f \\<in> I \\<rightarrow> {X. submodule R M X}\", unfold submodule_def,\n        frule conjunct1, fold submodule_def, simp add:subsetD)\ndone\n\nlemma (in Module) finitesum_sub_carrier:\"f \\<in> I \\<rightarrow> {X. submodule R M X} \\<Longrightarrow>\n                       finitesum M I f \\<subseteq> carrier M\"\napply (rule subsetI, simp add:finitesum_def)\napply ((erule exE)+, erule conjE, simp)\napply (frule finitesumbase_sub_carrier)\napply (rule nsum_mem, rule allI, rule impI)\napply (frule_tac x = j and f = g and A = \"{j. j \\<le> n}\" and\n        B = \"finitesum_base M I f\" in funcset_mem, simp)\napply (simp add:subsetD)\ndone\n\nlemma (in Module) finitesum_inc_zero:\"\\<lbrakk>f \\<in> I \\<rightarrow> {X. submodule R M X}; I \\<noteq> {}\\<rbrakk>\n      \\<Longrightarrow>   \\<zero> \\<in> finitesum M I f\"\napply (simp add:finitesum_def)\napply (frule nonempty_ex)\napply (subgoal_tac \"\\<forall>i. i\\<in>I \\<longrightarrow> (\\<exists>n g. g \\<in> {j. j \\<le> (n::nat)} \\<rightarrow> \n                    finitesum_base M I f \\<and> \\<zero>\\<^bsub>M\\<^esub> = \\<Sigma>\\<^sub>e M g n)\")\napply blast \napply (rule allI, rule impI)\napply (subgoal_tac \"(\\<lambda>x\\<in>{j. j \\<le> (0::nat)}. \\<zero>) \\<in> \n                    {j. j \\<le> (0::nat)} \\<rightarrow> finitesum_base M I f \\<and>\n                    \\<zero>\\<^bsub>M\\<^esub> = \\<Sigma>\\<^sub>e M (\\<lambda>x\\<in>{j. j \\<le> (0::nat)}. \\<zero>) 0\")\napply blast\napply (rule conjI)\napply (rule Pi_I) \n apply (simp add:finitesum_base_def, thin_tac \"\\<exists>x. x \\<in> I\")\n apply (frule_tac x = i in funcset_mem[of f I \"{X. submodule R M X}\"], \n        assumption+)\n apply (frule_tac x = i in funcset_mem [of \"f\" \"I\" \"{X. submodule R M X}\"],\n                                              assumption+, simp)\n apply (frule_tac H = \"f i\" in submodule_inc_0)\n apply blast\n\n apply simp\ndone\n\nlemma (in Module) finitesum_mOp_closed:\n     \"\\<lbrakk>f \\<in> I \\<rightarrow> {X. submodule R M X}; I \\<noteq> {}; a \\<in> finitesum M I f\\<rbrakk> \\<Longrightarrow>\n                  -\\<^sub>a a \\<in> finitesum M I f\"\napply (simp add:finitesum_def)\napply ((erule exE)+, erule conjE)\n  apply (frule finitesumbase_sub_carrier [of f I])\n  apply (frule_tac f = g and A = \"{j. j \\<le> n}\" and B = \"finitesum_base M I f\"\n          and ?B1.0 = \"carrier M\" in extend_fun, assumption+)\n  apply (frule sym, thin_tac \"a = \\<Sigma>\\<^sub>e M g n\")\n  apply (cut_tac n = n and f = g in nsum_minus,\n         rule allI, simp add:Pi_def, simp)\n\n apply (subgoal_tac \"(\\<lambda>x\\<in>{j. j \\<le> n}. -\\<^sub>a (g x)) \\<in> {j. j \\<le> n} \\<rightarrow> \n                                                 finitesum_base M I f\")\n apply blast\n apply (rule Pi_I, simp)\n apply (frule_tac f = g and A = \"{j. j \\<le> n}\" and B = \"finitesum_base M I f\" \n        and  x = x in funcset_mem, simp)\n apply (simp add:finitesum_base_def)\n apply (erule exE, erule conjE, erule exE, erule conjE)\n apply (frule_tac f = f and A = I and B = \"{X. submodule R M X}\" and\n  x = i in funcset_mem, assumption+, simp add:CollectI)\n apply (thin_tac \"f \\<in> I \\<rightarrow> {X. submodule R M X}\")\n apply (simp add:submodule_def, (erule conjE)+,\n        frule_tac H = \"f i\" and x = \"g x\" in asubg_mOp_closed, assumption+) \n apply blast\ndone\n\nlemma (in Module) finitesum_pOp_closed:\n \"\\<lbrakk>f \\<in> I \\<rightarrow> {X. submodule R M X}; a \\<in> finitesum M I f;  b \\<in> finitesum M I f\\<rbrakk>\n           \\<Longrightarrow>  a \\<plusminus> b \\<in> finitesum M I f\"\napply (simp add:finitesum_def) \napply ((erule exE)+, (erule conjE)+)\napply (frule_tac f = g and n = n and A = \"finitesum_base M I f\" and\n       g = ga and m = na and B = \"finitesum_base M I f\" in jointfun_hom0,\n       assumption+, simp)\napply (cut_tac finitesumbase_sub_carrier[of f I],\n       cut_tac n1 = n and f1 = g and m1 = na and g1 = ga in \n                 nsum_add_nm[THEN sym], rule allI, rule impI,\n       frule_tac x = j and f = g and A = \"{j. j \\<le> n}\" and\n        B = \"finitesum_base M I f\" in funcset_mem, simp,\n       simp add:subsetD,\n       rule allI, rule impI,\n       frule_tac x = j and f = ga and A = \"{j. j \\<le> na}\" and\n        B = \"finitesum_base M I f\" in funcset_mem, simp,\n       simp add:subsetD)\napply blast\napply assumption\ndone\n\nlemma (in Module) finitesum_sprodTr:\"\\<lbrakk>f \\<in> I \\<rightarrow> {X. submodule R M X}; I \\<noteq> {};\n       r \\<in> carrier R\\<rbrakk>  \\<Longrightarrow> g \\<in>{j. j \\<le> (n::nat)} \\<rightarrow> (finitesum_base M I f)\n              \\<longrightarrow> r \\<cdot>\\<^sub>s (nsum M g n) =  nsum M (\\<lambda>x. r \\<cdot>\\<^sub>s (g x)) n\"\napply (induct_tac n)\n apply (rule impI)\n apply simp\napply (rule impI)\napply (frule func_pre) apply simp\napply (frule finitesumbase_sub_carrier [of f I])\n apply (frule_tac f = g and A = \"{j. j \\<le> Suc n}\" in extend_fun [of _ _ \"finitesum_base M I f\" \"carrier M\"], assumption+)\n apply (thin_tac \"g \\<in> {j. j \\<le> Suc n} \\<rightarrow> finitesum_base M I f\",\n        thin_tac \"g \\<in> {j. j \\<le> n} \\<rightarrow> finitesum_base M I f\",\n        frule func_pre)\n apply (cut_tac n = n in nsum_mem [of _ g])\n apply (rule allI, simp add:Pi_def)\n apply (frule_tac x = \"Suc n\" in funcset_mem [of \"g\" _ \"carrier M\"], simp)\n apply (subst sc_r_distr, assumption+)\n apply simp\ndone\n\nlemma (in Module) finitesum_sprod:\"\\<lbrakk>f \\<in> I \\<rightarrow> {X. submodule R M X}; I \\<noteq> {}; \n      r \\<in> carrier R; g \\<in>{j. j \\<le> (n::nat)} \\<rightarrow> (finitesum_base M I f) \\<rbrakk> \\<Longrightarrow>\n                       r \\<cdot>\\<^sub>s (nsum M g n) =  nsum M (\\<lambda>x. r \\<cdot>\\<^sub>s (g x)) n\"\napply (simp add:finitesum_sprodTr)\ndone\n\nlemma (in Module) finitesum_subModule:\"\\<lbrakk>f \\<in> I \\<rightarrow> {X. submodule R M X}; I \\<noteq> {}\\<rbrakk>\n                   \\<Longrightarrow> submodule R M (finitesum M I f)\"\napply (simp add:submodule_def [of _ _ \"(finitesum M I f)\"])\napply (simp add:finitesum_sub_carrier)\napply (rule conjI)\n apply (rule asubg_test)\n apply (simp add:finitesum_sub_carrier)\n apply (frule finitesum_inc_zero, assumption, blast) \n\n apply (rule ballI)+\n apply (rule finitesum_pOp_closed, assumption+,\n        rule finitesum_mOp_closed, assumption+)\n\n apply ((rule allI)+, rule impI, erule conjE)\n apply (simp add:finitesum_def, (erule exE)+, erule conjE, simp)\n apply (simp add:finitesum_sprod)\n apply (subgoal_tac \"(\\<lambda>x. a \\<cdot>\\<^sub>s g x) \\<in> {j. j \\<le> n} \\<rightarrow> finitesum_base M I f\",\n        blast)\n apply (rule Pi_I)\n apply (frule_tac x = x and f = g and A = \"{j. j \\<le> n}\" in \n                  funcset_mem[of _ _ \"finitesum_base M I f\"], assumption+,\n        thin_tac \"g \\<in> {j. j \\<le> n} \\<rightarrow> finitesum_base M I f\",\n        simp add:finitesum_base_def, erule exE, erule conjE, erule exE,\n        erule conjE, simp)\n apply (frule_tac x = i and f = f and A = I in \n        funcset_mem[of _ _ \"{X. submodule R M X}\"], assumption+, simp,\n        frule_tac H = \"f i\" and a = a and h = \"g x\" in submodule_sc_closed,\n        assumption+)\napply blast\ndone\n\nlemma (in Module) sSum_cont_H:\"\\<lbrakk>submodule R M H; submodule R M K\\<rbrakk> \\<Longrightarrow>\n                     H \\<subseteq>  H \\<minusplus> K\"\napply (rule subsetI)\napply (unfold submodule_def[of R M H], frule conjunct1, fold submodule_def,\n       unfold submodule_def[of R M K], frule conjunct1, fold submodule_def)\napply (simp add:set_sum) \napply (frule submodule_inc_0 [of K])\napply (cut_tac t = x in ag_r_zero [THEN sym],\n       rule submodule_subset1, assumption+)\napply blast\ndone\n\nlemma (in Module) sSum_commute:\"\\<lbrakk>submodule R M H; submodule R M K\\<rbrakk> \\<Longrightarrow>\n                       H \\<minusplus> K =  K \\<minusplus> H\"\napply (unfold submodule_def[of R M H], frule conjunct1, fold submodule_def,\n       unfold submodule_def[of R M K], frule conjunct1, fold submodule_def)   \napply (rule equalityI)\napply (rule subsetI) \napply (simp add:set_sum)\napply ((erule bexE)+, simp)\napply (frule_tac c = h in subsetD[of H \"carrier M\"], assumption+,\n       frule_tac c = k in subsetD[of K \"carrier M\"], assumption+)\napply (subst ag_pOp_commute, assumption+)\napply blast\n\napply (rule subsetI)\napply (simp add:set_sum)\napply ((erule bexE)+, simp)\napply (frule_tac h = h in submodule_subset1[of K ], assumption+,\n       frule_tac h = k in submodule_subset1[of H ], assumption+)\napply (subst ag_pOp_commute, assumption+)\napply blast\ndone\n\nlemma (in Module) Sum_of_SubmodulesTr:\"\\<lbrakk>submodule R M H; submodule R M K\\<rbrakk> \\<Longrightarrow>\n      g \\<in> {j. j \\<le> (n::nat)} \\<rightarrow> H \\<union> K \\<longrightarrow> \\<Sigma>\\<^sub>e M g n \\<in> H \\<minusplus> K\"\napply (induct_tac n)\n apply (rule impI)\n apply simp\n apply (frule submodule_subset[of H],\n        frule submodule_subset[of K])\n apply (simp add:set_sum)\n apply (erule disjE)\n apply (frule_tac c = \"g 0\" in subsetD[of H \"carrier M\"], assumption+,\n        frule_tac t = \"g 0\" in ag_r_zero[THEN sym]) apply (\n        frule submodule_inc_0[of K], blast)\n apply (frule_tac c = \"g 0\" in subsetD[of K \"carrier M\"], assumption+,\n        frule_tac t = \"g 0\" in ag_l_zero[THEN sym]) apply (\n        frule submodule_inc_0[of H], blast)\napply simp\n\napply (rule impI, frule func_pre, simp)\n apply (frule submodule_subset[of H],\n        frule submodule_subset[of K])\n apply (simp add:set_sum[of H K], (erule bexE)+, simp)\n apply (frule_tac x = \"Suc n\" and f = g and A = \"{j. j \\<le> Suc n}\" and\n        B = \"H \\<union> K\" in funcset_mem, simp,\n        thin_tac \"g \\<in> {j. j \\<le> n} \\<rightarrow> H \\<union> K\",\n        thin_tac \"g \\<in> {j. j \\<le> Suc n} \\<rightarrow> H \\<union> K\",\n        thin_tac \"\\<Sigma>\\<^sub>e M g n = h \\<plusminus> k\", simp)\n apply (erule disjE)\n apply (frule_tac h = h in submodule_subset1[of H], assumption,\n        frule_tac h = \"g (Suc n)\" in submodule_subset1[of H], assumption,\n        frule_tac h = k in submodule_subset1[of K], assumption) \n apply (subst ag_pOp_assoc, assumption+)\n  apply (frule_tac x = k and y = \"g (Suc n)\" in ag_pOp_commute, assumption+,\n         simp, subst ag_pOp_assoc[THEN sym], assumption+)\n  apply (frule_tac h = h and k = \"g (Suc n)\" in submodule_pOp_closed[of H],\n         assumption+, blast)\n apply (frule_tac h = h in submodule_subset1[of H], assumption,\n        frule_tac h = \"g (Suc n)\" in submodule_subset1[of K], assumption,\n        frule_tac h = k in submodule_subset1[of K], assumption) \n apply (subst ag_pOp_assoc, assumption+,\n        frule_tac h = k and k = \"g (Suc n)\" in submodule_pOp_closed[of K],\n         assumption+, blast)\ndone\n\nlemma (in Module) sSum_two_Submodules:\"\\<lbrakk>submodule R M H; submodule R M K\\<rbrakk> \\<Longrightarrow>\n                       submodule R M (H \\<minusplus> K)\"\napply (subst submodule_def) \n apply (frule submodule_asubg[of H],\n        frule submodule_asubg[of K])\n apply (frule plus_subgs[of H K], assumption, simp add:asubg_subset)\n\napply (rule allI)+\napply (rule impI, erule conjE, frule asubg_subset[of H], \n       frule asubg_subset[of K])\n apply (simp add:set_sum[of H K], (erule bexE)+, simp)\n apply (frule_tac H = H and a = a and h = h in submodule_sc_closed, \n                  assumption+,\n        frule_tac H = K and a = a and h = k in submodule_sc_closed, \n                  assumption+)\n apply (frule_tac c = h in subsetD[of H \"carrier M\"], assumption+,\n        frule_tac c = k in subsetD[of K \"carrier M\"], assumption+,\n        simp add:sc_r_distr)\n apply blast\ndone\n\ndefinition\n  iotam :: \"[('a, 'r, 'm) Module_scheme, 'a set, 'a set] \\<Rightarrow> ('a \\<Rightarrow> 'a)\"\n      (\"(3\\<iota>m\\<^bsub>_ _,_\\<^esub>)\" [82, 82, 83]82) where\n  \"\\<iota>m\\<^bsub>M H,K\\<^esub> = (\\<lambda>x\\<in>H. (x \\<plusminus>\\<^bsub>M\\<^esub> \\<zero>\\<^bsub>M\\<^esub>))\"  (** later we define miota. This is not \n equal to iotam **) \n\nlemma (in Module) iotam_mHom:\"\\<lbrakk>submodule R M H; submodule R M K\\<rbrakk>\n                           \\<Longrightarrow> \\<iota>m\\<^bsub>M H,K\\<^esub> \\<in> mHom R (mdl M H) (mdl M (H \\<minusplus> K))\"\napply (simp add:mHom_def)\napply (rule conjI)\n apply (simp add:aHom_def)\n apply (simp add:mdl_def)\n apply (rule conjI)\n apply (rule Pi_I)\n apply (simp add:iotam_def)\n apply (frule submodule_subset[of H], frule submodule_subset[of K],\n        simp add:set_sum)\n apply (frule submodule_inc_0 [of K])\n apply blast\napply (rule conjI)\n apply (simp add:iotam_def extensional_def mdl_def)\napply (rule ballI)+\n apply (simp add:mdl_def iotam_def)\n apply (frule_tac h = a and k = b in submodule_pOp_closed [of H],\n                                     assumption+, simp)\n apply (frule submodule_subset[of H], \n        frule_tac c = a in subsetD[of H \"carrier M\"], assumption) apply (\n        simp add:ag_r_zero) \n apply ( frule_tac c = b in subsetD[of H \"carrier M\"], assumption,\n        subst ag_pOp_assoc, assumption+,\n        simp add:ag_inc_zero, simp)\n\napply (rule ballI)+\n apply (simp add:iotam_def mdl_def)\n apply (simp add:submodule_sc_closed)\n apply (frule submodule_inc_0[of K]) \n apply (frule submodule_asubg[of H], frule submodule_asubg[of K],\n        simp add:mem_sum_subgs)\n\n apply (frule_tac a = a and h = m in submodule_sc_closed, assumption+,\n        frule submodule_subset[of H],\n        frule_tac c = m in subsetD[of H \"carrier M\"], assumption+,\n        frule_tac c = \"a \\<cdot>\\<^sub>s m\" in subsetD[of H \"carrier M\"], assumption+)\n apply (simp add:ag_r_zero)\ndone\n\nlemma (in Module) mhomom3Tr:\"\\<lbrakk>submodule R M H; submodule R M K\\<rbrakk> \\<Longrightarrow>\n                         submodule R (mdl M (H \\<minusplus> K)) K\"\napply (subst submodule_def) \napply (rule conjI)\n apply (simp add:mdl_def)\n apply (subst sSum_commute, assumption+) \n apply (simp add:sSum_cont_H)\napply (rule conjI)\n apply (rule aGroup.asubg_test)\n apply (frule sSum_two_Submodules [of H K], assumption+)\n apply (frule mdl_is_module [of  \"(H \\<minusplus> K)\"])\n apply (rule Module.module_is_ag, assumption+)\napply (simp add:mdl_def)\n apply (subst sSum_commute, assumption+)   \n  apply (simp add:sSum_cont_H)\n apply (frule submodule_inc_0 [of K])\n apply (simp add:nonempty)\napply (rule ballI)+\n apply (simp add:mdl_def)\n apply (rule submodule_pOp_closed, assumption+)\n apply (rule submodule_mOp_closed, assumption+)\napply ((rule allI)+, rule impI)\n apply (simp add:mdl_def, erule conjE)\n apply (frule sSum_cont_H[of K H], assumption,\n        simp add:sSum_commute[of K H])\n apply (simp add:subsetD submodule_sc_closed)\ndone\n\nlemma (in Module) mhomom3Tr0:\"\\<lbrakk>submodule R M H; submodule R M K\\<rbrakk>\n     \\<Longrightarrow> compos (mdl M H) (mpj (mdl M (H \\<minusplus> K)) K) (\\<iota>m\\<^bsub>M H,K\\<^esub>)\n        \\<in> mHom R (mdl M H) (mdl M (H \\<minusplus> K) /\\<^sub>m K)\"\napply (frule mdl_is_module [of H])\napply (frule mhomom3Tr[of H K], assumption+)\napply (frule sSum_two_Submodules [of H K], assumption+)\napply (frule mdl_is_module [of  \"H \\<minusplus> K\"])\napply (frule iotam_mHom [of H K], assumption+) thm Module.mpj_mHom\napply (frule Module.mpj_mHom [of \"mdl M (H \\<minusplus> K)\" R \"K\"], assumption+)\napply (rule  Module.mHom_compos[of \"mdl M (H \\<minusplus> K)\" R \"mdl M H\"], assumption+)\napply (simp add:Module.qmodule_module, assumption)\napply (simp add:mpj_mHom)\ndone\n\nlemma (in Module) mhomom3Tr1:\"\\<lbrakk>submodule R M H; submodule R M K\\<rbrakk> \\<Longrightarrow>\n  surjec\\<^bsub>(mdl M H),((mdl M (H \\<minusplus> K))/\\<^sub>m K)\\<^esub> \n    (compos (mdl M H) (mpj (mdl M (H \\<minusplus> K)) K) (\\<iota>m\\<^bsub>M H,K\\<^esub>))\"\napply (simp add:surjec_def)\napply (frule mhomom3Tr0 [of H K], assumption+)\napply (rule conjI)\napply (simp add:mHom_def)\napply (rule surj_to_test)\n apply (simp add:mHom_def aHom_def)\napply (rule ballI)\n apply (simp add:compos_def compose_def)\n apply (thin_tac \"(\\<lambda>x\\<in>carrier (mdl M H). mpj (mdl M (H \\<minusplus> K)) K ((\\<iota>m\\<^bsub>M H,K\\<^esub>) x))\n         \\<in> mHom R (mdl M H) (mdl M (H \\<minusplus> K) /\\<^sub>m K)\")\n apply (simp add:qmodule_def)\n apply (simp add:set_mr_cos_def)\n apply (erule bexE, simp)\n apply (simp add:mdl_carrier)\n apply (simp add:iotam_def)\n apply (simp add:mpj_def)\n apply (frule sSum_two_Submodules[of H K], assumption+)\n apply (simp add:mdl_carrier)\n apply (subgoal_tac \"\\<forall>aa\\<in>H. aa \\<plusminus> \\<zero> \\<in> H \\<minusplus> K\", simp)\n apply (frule submodule_subset[of H], frule submodule_subset[of K],\n        thin_tac \"\\<forall>aa\\<in>H. aa \\<plusminus> \\<zero> \\<in> H \\<minusplus> K\",\n        simp add:set_sum, (erule bexE)+) \n        apply (simp add:set_sum[THEN sym])\n apply (frule mdl_is_module[of \"H \\<minusplus> K\"],\n        frule mhomom3Tr[of H K], assumption+)\n apply (frule_tac m = h and h = k in Module.mr_cos_h_stable1[of \"mdl M (H \\<minusplus> K)\"\n        R K], assumption+)\n apply (simp add:mdl_carrier)\n apply (frule sSum_cont_H[of H K], assumption+, simp add:subsetD, assumption)\n apply (simp add:mdl_def, fold mdl_def)\n apply (subgoal_tac \"\\<forall>a\\<in>H. a \\<plusminus> \\<zero> = a\", simp, blast)\n apply (rule ballI)\n apply (frule_tac c = aa in subsetD[of H \"carrier M\"], assumption+,\n        simp add:ag_r_zero)\n apply (rule ballI)\n apply (frule submodule_inc_0[of K])\n apply (rule mem_sum_subgs,\n       simp add:submodule_def, simp add:submodule_def, assumption+)\ndone\n \nlemma (in Module) mhomom3Tr2:\"\\<lbrakk>submodule R M H; submodule R M K\\<rbrakk> \\<Longrightarrow>\n  ker\\<^bsub>(mdl M H),((mdl M (H \\<minusplus> K)) /\\<^sub>m K)\\<^esub> \n    (compos (mdl M H) (mpj (mdl M (H \\<minusplus> K)) K) (\\<iota>m\\<^bsub>M H,K\\<^esub>)) = H \\<inter> K\"\napply (rule equalityI)\n apply (rule subsetI)\n apply (simp add:ker_def, erule conjE)\n apply (simp add:qmodule_def)\n apply (simp add:mdl_carrier) \n apply (simp add:compos_def compose_def mdl_def iotam_def)\n apply (fold mdl_def)\napply (simp add:iotam_def mpj_def) \n apply (frule  sSum_two_Submodules[of H K], assumption+, simp add:mdl_carrier)\n apply (frule submodule_asubg[of H], frule submodule_asubg[of K])\n apply (frule_tac h = x and k = \\<zero> in mem_sum_subgs[of H K], assumption+)\n apply (simp add:submodule_inc_0)\n apply simp apply (frule mhomom3Tr[of H K], assumption+)\n (*thm Module.m_in_mr_coset[of \"mdl M (H \\<minusplus> K)\" R K]\n apply (frule_tac m = \"x \\<plusminus> \\<zero>\" in Module.m_in_mr_coset[of \"mdl M (H \\<minusplus> K)\" R K])*)\napply (frule sSum_two_Submodules[of H K], assumption,\n       frule mdl_is_module [of  \"H \\<minusplus> K\"])\napply (frule_tac m = \"x \\<plusminus> \\<zero>\" in Module.m_in_mr_coset[of \"mdl M (H \\<minusplus> K)\" R K],\n                          assumption+)\n apply (simp add:mdl_carrier, simp)\n apply (frule submodule_subset[of H], \n        frule_tac c = x in subsetD[of H \"carrier M\"], assumption+) \n apply (simp add:ag_r_zero)\n\napply (rule subsetI)\n apply (simp add:ker_def)\n apply (simp add:mdl_carrier)\n apply (simp add:qmodule_def)\n apply (simp add:compos_def compose_def)\n apply (simp add:mdl_carrier)\n apply (simp add:iotam_def mpj_def)\n apply (frule sSum_two_Submodules[of H K], assumption+)\n apply (simp add:mdl_carrier)\n apply (erule conjE,\n        frule submodule_inc_0[of K],\n        frule submodule_asubg[of H], frule submodule_asubg[of K],\n       simp add:mem_sum_subgs)\n apply (frule submodule_subset[of K]) apply (\n        frule_tac c = x in subsetD[of K \"carrier M\"], assumption+)\n apply (simp add:ag_r_zero,\n        frule mdl_is_module [of  \"H \\<minusplus> K\"],\n        frule mhomom3Tr[of H K], assumption+)\n apply (frule_tac h1 = x in Module.mr_cos_h_stable[THEN sym, of \"mdl M (H \\<minusplus> K)\"\n         R K], assumption+)\ndone\n\nlemma (in Module) mhomom_3:\"\\<lbrakk>submodule R M H; submodule R M K\\<rbrakk> \\<Longrightarrow>\n                 (mdl M H) /\\<^sub>m (H \\<inter> K) \\<cong>\\<^bsub>R\\<^esub> (mdl M (H \\<minusplus> K)) /\\<^sub>m K\" \napply (frule sSum_two_Submodules [of H K], assumption+)\n apply (frule mdl_is_module [of H])\n apply (frule mdl_is_module [of K])\n apply (frule mdl_is_module [of \"H \\<minusplus> K\"])\n apply (frule mhomom3Tr [of H K], assumption+)\n apply (frule Module.qmodule_module [of \"mdl M (H \\<minusplus> K)\" R K], assumption+)\napply (simp add:misomorphic_def)\napply (frule mhomom3Tr0[of H K], assumption+)\napply (frule mhomom3Tr1[of H K], assumption+)\napply (frule Module.indmhom [of \"mdl M H\" R \"mdl M (H \\<minusplus> K) /\\<^sub>m K\" \"compos (mdl M H) (mpj (mdl M (H \\<minusplus> K)) K) (\\<iota>m\\<^bsub>M H,K\\<^esub>)\"], assumption+)\napply (frule Module.indmhom_injec[of \"mdl M H\" R \"mdl M (H \\<minusplus> K) /\\<^sub>m K\"\n     \"compos (mdl M H) (mpj (mdl M (H \\<minusplus> K)) K) (\\<iota>m\\<^bsub>M H,K\\<^esub>)\"], assumption+)\napply (frule Module.indmhom_surjec1[of  \"mdl M H\" R \"mdl M (H \\<minusplus> K) /\\<^sub>m K\" \"compos (mdl M H) (mpj (mdl M (H \\<minusplus> K)) K) (\\<iota>m\\<^bsub>M H,K\\<^esub>)\"], assumption+)\napply (simp add:bijec_def)\napply (simp add:mhomom3Tr2[of H K])\napply blast\ndone\n\ndefinition\n  l_comb :: \"[('r, 'm) Ring_scheme, ('a, 'r, 'm1) Module_scheme, nat] \\<Rightarrow>\n    (nat \\<Rightarrow> 'r) \\<Rightarrow> (nat \\<Rightarrow> 'a) \\<Rightarrow> 'a\" where\n  \"l_comb R M n s m = nsum M (\\<lambda>j. (s j) \\<cdot>\\<^sub>s\\<^bsub>M\\<^esub> (m j)) n\" \n\ndefinition\n  linear_span :: \"[('r, 'm) Ring_scheme, ('a, 'r, 'm1) Module_scheme, 'r set,\n              'a set] \\<Rightarrow> 'a set\" where\n  \"linear_span R M A H = (if H = {} then {\\<zero>\\<^bsub>M\\<^esub>} else \n                           {x. \\<exists>n. \\<exists>f \\<in> {j. j \\<le> (n::nat)} \\<rightarrow> H.\n         \\<exists>s\\<in>{j. j \\<le> (n::nat)} \\<rightarrow> A.  x = l_comb R M n s f})\"\n\ndefinition\n  coefficient :: \"[('r, 'm) Ring_scheme, ('a, 'r, 'm1) Module_scheme,\n               nat, nat \\<Rightarrow> 'r, nat \\<Rightarrow> 'a] \\<Rightarrow> nat \\<Rightarrow> 'r\" where\n  \"coefficient R M n s m j = s j\"\n\ndefinition\n  body :: \"[('r, 'm) Ring_scheme, ('a, 'r, 'm1) Module_scheme, nat, nat \\<Rightarrow> 'r, \n         nat \\<Rightarrow> 'a] \\<Rightarrow> nat \\<Rightarrow> 'a\" where\n  \"body R M n s m j = m j\"\n\nlemma (in Module) l_comb_mem_linear_span:\"\\<lbrakk>ideal R A; H \\<subseteq> carrier M; \n       s \\<in> {j. j \\<le> (n::nat)} \\<rightarrow> A; f \\<in> {j. j \\<le> n} \\<rightarrow> H\\<rbrakk> \\<Longrightarrow>\n                    l_comb R M n s f \\<in> linear_span R M A H\"\napply (frule_tac x = 0 in funcset_mem[of f \"{j. j \\<le> n}\" H], simp)\n apply (frule nonempty[of \"f 0\" H])\n apply (simp add:linear_span_def)\n apply blast\ndone\n\nlemma (in Module) linear_comb_eqTr:\"H \\<subseteq> carrier M \\<Longrightarrow> \n      s \\<in> {j. j \\<le> (n::nat)} \\<rightarrow> carrier R \\<and> \n      f \\<in> {j. j \\<le> n} \\<rightarrow> H \\<and> \n      g \\<in> {j. j \\<le> n} \\<rightarrow> H \\<and> \n      (\\<forall>j\\<in>{j. j \\<le> n}. f j = g j) \\<longrightarrow> \n      l_comb R M n s f = l_comb R M n s g\" \napply (induct_tac n)\n apply (rule impI) apply (erule conjE)+ apply (simp add:l_comb_def)\n \napply (rule impI) apply (erule conjE)+ \n apply (frule_tac f = s in func_pre)\n apply (frule_tac f = f in func_pre)\n apply (frule_tac f = g in func_pre)\n apply (cut_tac n = n in Nsetn_sub_mem1, simp)\n apply (thin_tac \"s \\<in> {j. j \\<le> n} \\<rightarrow> carrier R\",\n        thin_tac \"f \\<in> {j. j \\<le> n} \\<rightarrow> H\",\n        thin_tac \"g \\<in> {j. j \\<le> n} \\<rightarrow> H\")\n apply (simp add:l_comb_def)\ndone\n           \nlemma (in Module) linear_comb_eq:\"\\<lbrakk>H \\<subseteq> carrier M; \n       s \\<in> {j. j \\<le> (n::nat)} \\<rightarrow> carrier R; f \\<in> {j. j \\<le> n} \\<rightarrow> H; \n       g \\<in> {j. j \\<le> n} \\<rightarrow> H; \\<forall>j\\<in>{j. j \\<le> n}. f j = g j\\<rbrakk>  \\<Longrightarrow>\n  l_comb R M n s f = l_comb R M n s g\" \napply (simp add:linear_comb_eqTr)\ndone\n\nlemma (in Module) l_comb_Suc:\"\\<lbrakk>H \\<subseteq> carrier M; ideal R A; \n       s \\<in> {j. j \\<le> (Suc n)} \\<rightarrow> carrier R; f \\<in> {j. j \\<le> (Suc n)} \\<rightarrow> H\\<rbrakk>  \\<Longrightarrow>\n       l_comb R M (Suc n) s f = l_comb R M n s f \\<plusminus> s (Suc n) \\<cdot>\\<^sub>s f (Suc n)\" \napply (simp add:l_comb_def)\ndone\n\nlemma (in Module) l_comb_jointfun_jj:\"\\<lbrakk>H \\<subseteq> carrier M; ideal R A;\n        s \\<in> {j. j \\<le> (n::nat)} \\<rightarrow> A; f \\<in> {j. j \\<le> (n::nat)} \\<rightarrow> H;\n        t \\<in> {j. j \\<le> (m::nat)} \\<rightarrow> A; g \\<in> {j. j \\<le> (m::nat)} \\<rightarrow> H\\<rbrakk> \\<Longrightarrow>\n        nsum M (\\<lambda>j. (jointfun n s m t) j \\<cdot>\\<^sub>s (jointfun n f m g) j) n =\n        nsum M (\\<lambda>j. s j \\<cdot>\\<^sub>s f j) n\"\napply (cut_tac sc_Ring)\napply (rule nsum_eq)\n apply (rule allI, rule impI, simp add:jointfun_def,\n        rule sc_mem,\n        simp add:Pi_def Ring.ideal_subset,\n        simp add:Pi_def subsetD)\n apply (rule allI, rule impI, \n        rule sc_mem,\n        simp add:Pi_def Ring.ideal_subset,\n        simp add:Pi_def subsetD)\n apply (rule allI, simp add:jointfun_def)\ndone\n\nlemma (in Module) l_comb_jointfun_jj1:\"\\<lbrakk>H \\<subseteq> carrier M; ideal R A;\n        s \\<in> {j. j \\<le> (n::nat)} \\<rightarrow> A; f \\<in> {j. j \\<le> (n::nat)} \\<rightarrow> H;\n        t \\<in> {j. j \\<le> (m::nat)} \\<rightarrow> A; g \\<in> {j. j \\<le> (m::nat)} \\<rightarrow> H\\<rbrakk> \\<Longrightarrow>\n        l_comb R M n (jointfun n s m t) (jointfun n f m g) =\n        l_comb R M n s f\"\nby (simp add:l_comb_def, simp add:l_comb_jointfun_jj)\n\nlemma (in Module) l_comb_jointfun_jf:\"\\<lbrakk>H \\<subseteq> carrier M; ideal R A;\n        s \\<in> {j. j \\<le> (n::nat)} \\<rightarrow> A; f \\<in> {j. j \\<le> Suc (n + m)} \\<rightarrow> H;\n        t \\<in> {j. j \\<le> (m::nat)} \\<rightarrow> A\\<rbrakk> \\<Longrightarrow>\n        nsum M (\\<lambda>j. (jointfun n s m t) j \\<cdot>\\<^sub>s f j) n =\n        nsum M (\\<lambda>j. s j \\<cdot>\\<^sub>s f j) n\"\napply (cut_tac sc_Ring)\napply (rule nsum_eq)\n apply (rule allI, rule impI, simp add:jointfun_def,\n        rule sc_mem,\n        simp add:Pi_def Ring.ideal_subset,\n        simp add:Pi_def subsetD)\n  apply (rule allI, rule impI, \n        rule sc_mem,\n        simp add:Pi_def Ring.ideal_subset,\n        simp add:Pi_def subsetD)\n  apply (rule allI, simp add:jointfun_def)\ndone\n\nlemma (in Module) l_comb_jointfun_jf1:\"\\<lbrakk>H \\<subseteq> carrier M; ideal R A;\n        s \\<in> {j. j \\<le> (n::nat)} \\<rightarrow> A; f \\<in> {j. j \\<le> Suc (n + m)} \\<rightarrow> H;\n        t \\<in> {j. j \\<le> (m::nat)} \\<rightarrow> A\\<rbrakk> \\<Longrightarrow>\n        l_comb R M n (jointfun n s m t) f = l_comb R M n s f\"\nby (simp add:l_comb_def l_comb_jointfun_jf)\n\nlemma (in Module) l_comb_jointfun_fj:\"\\<lbrakk>H \\<subseteq> carrier M; ideal R A;\n        s \\<in> {j. j \\<le> Suc (n + m)} \\<rightarrow> A; f \\<in> {j. j \\<le> (n::nat)} \\<rightarrow> H;\n        g \\<in> {j. j \\<le> (m::nat)} \\<rightarrow> H\\<rbrakk> \\<Longrightarrow>\n        nsum M (\\<lambda>j. s j \\<cdot>\\<^sub>s (jointfun n f m g) j) n =\n        nsum M (\\<lambda>j. s j \\<cdot>\\<^sub>s f j) n\"\napply (cut_tac sc_Ring)\napply (rule nsum_eq)\n apply (rule allI, rule impI, simp add:jointfun_def,\n        rule sc_mem,\n        simp add:Pi_def Ring.ideal_subset,\n        simp add:Pi_def subsetD)\n  apply (rule allI, rule impI, \n        rule sc_mem,\n        simp add:Pi_def Ring.ideal_subset,\n        simp add:Pi_def subsetD)\n    apply (rule allI, simp add:jointfun_def)\ndone\n\nlemma (in Module) l_comb_jointfun_fj1:\"\\<lbrakk>H \\<subseteq> carrier M; ideal R A;\n        s \\<in> {j. j \\<le> Suc (n + m)} \\<rightarrow> A; f \\<in> {j. j \\<le> (n::nat)} \\<rightarrow> H;\n        g \\<in> {j. j \\<le> (m::nat)} \\<rightarrow> H\\<rbrakk> \\<Longrightarrow>\n        l_comb R M n s (jointfun n f m g) = l_comb R M n s f\"\nby (simp add:l_comb_def l_comb_jointfun_fj)\n\nlemma (in Module) linear_comb0_1Tr:\"H \\<subseteq> carrier M \\<Longrightarrow> \n      s \\<in> {j. j \\<le> (n::nat)} \\<rightarrow> {\\<zero>\\<^bsub>R\\<^esub>} \\<and>  \n      m \\<in> {j. j \\<le> n} \\<rightarrow> H \\<longrightarrow> l_comb R M n s m = \\<zero>\\<^bsub>M\\<^esub>\"\napply (induct_tac n)\n apply (rule impI) apply (erule conjE)\n apply (simp add:l_comb_def subsetD sc_0_m)\n\napply (rule impI) apply (erule conjE)\n apply (frule func_pre [of _ _ \"{\\<zero>\\<^bsub>R\\<^esub>}\"])\n apply (frule func_pre [of _ _ \"H\"])\n apply simp\n apply (thin_tac \"s \\<in> {j. j \\<le> n} \\<rightarrow> {\\<zero>\\<^bsub>R\\<^esub>}\",\n        thin_tac \"m \\<in> {j. j \\<le> n} \\<rightarrow> H\")\n apply (simp add:l_comb_def)\n apply (frule_tac x = \"Suc n\" and f = s and A = \"{j. j \\<le> Suc n}\" in \n        funcset_mem[of _ _ \"{\\<zero>\\<^bsub>R\\<^esub>}\"], simp, simp,\n        frule_tac x = \"Suc n\" and f = m and A = \"{j. j \\<le> Suc n}\" in \n        funcset_mem[of _ _ H], simp,\n        frule_tac c = \"m (Suc n)\" in subsetD[of H \"carrier M\"], assumption+,\n        simp add:sc_0_m)\n apply (cut_tac ag_inc_zero)\n apply (simp add:ag_l_zero)\ndone\n\nlemma (in Module) linear_comb0_1:\"\\<lbrakk>H \\<subseteq> carrier M; \n      s \\<in> {j. j \\<le> (n::nat)} \\<rightarrow> {\\<zero>\\<^bsub>R\\<^esub>}; m \\<in> {j. j \\<le> n} \\<rightarrow> H \\<rbrakk> \\<Longrightarrow> \n      l_comb R M n s m = \\<zero>\\<^bsub>M\\<^esub>\"\napply (simp add:linear_comb0_1Tr)\ndone\n\nlemma (in Module) linear_comb0_2Tr:\"ideal R A \\<Longrightarrow> s \\<in> {j. j \\<le> (n::nat)} \\<rightarrow> A \n      \\<and>  m \\<in> {j. j \\<le> n} \\<rightarrow> {\\<zero>\\<^bsub>M\\<^esub>} \\<longrightarrow> l_comb R M n s m = \\<zero>\\<^bsub>M\\<^esub>\"\napply (induct_tac n )\n apply (rule impI) apply (erule conjE)\n apply (simp add:l_comb_def sc_a_0 sc_Ring Ring.ideal_subset)\n\napply (rule impI)\n apply (erule conjE)+\n apply (frule func_pre [of \"s\"],\n        frule func_pre [of \"m\"], simp)\n  apply (thin_tac \"s \\<in> {j. j \\<le> n} \\<rightarrow> A\",\n         thin_tac \"m \\<in> {j. j \\<le> n} \\<rightarrow> {\\<zero>}\")\n apply (simp add:l_comb_def)\n  apply (frule_tac A = \"{j. j \\<le> Suc n}\" and x = \"Suc n\" in \n         funcset_mem [of \"m\" _ \"{\\<zero>}\"], simp+,\n         frule_tac A = \"{j. j \\<le> Suc n}\" and x = \"Suc n\" in \n         funcset_mem[of s _ A], simp+,\n         cut_tac sc_Ring,\n         frule_tac h = \"s (Suc n)\" in Ring.ideal_subset[of R A], assumption+)\n  apply (cut_tac ag_inc_zero, simp add:sc_a_0)\n apply (simp add:ag_l_zero)\ndone\n\nlemma (in Module) linear_comb0_2:\"\\<lbrakk>ideal R A;  s \\<in> {j. j \\<le> (n::nat)} \\<rightarrow> A;\n       m \\<in> {j. j \\<le> n} \\<rightarrow> {\\<zero>\\<^bsub>M\\<^esub>} \\<rbrakk> \\<Longrightarrow>  l_comb R M n s m = \\<zero>\\<^bsub>M\\<^esub>\"\napply (simp add:linear_comb0_2Tr)\ndone\n\nlemma (in Module) liear_comb_memTr:\"\\<lbrakk>ideal R A; H \\<subseteq> carrier M\\<rbrakk> \\<Longrightarrow>\n \\<forall>s. \\<forall>m. s \\<in> {j. j \\<le> (n::nat)} \\<rightarrow> A \\<and> \n          m \\<in> {j. j \\<le> n} \\<rightarrow> H \\<longrightarrow> l_comb R M n s m \\<in> carrier M\"\napply (induct_tac n)\n apply (rule allI)+ apply (rule impI) apply (erule conjE)\n apply (simp add: l_comb_def sc_mem Ring.ideal_subset[of R A] subsetD sc_Ring) \n\napply (rule allI)+ apply (rule impI) apply (erule conjE)\n apply (frule func_pre [of _ _ \"A\"],\n        frule func_pre [of _ _ \"H\"],\n        drule_tac x = s in spec,\n        drule_tac x = m in spec)\n\napply (simp add:l_comb_def)\n apply (rule ag_pOp_closed, assumption+)\n apply (rule sc_mem)\n apply (cut_tac sc_Ring,\n        simp add:Pi_def Ring.ideal_subset subsetD)\n apply (simp add:Pi_def subsetD)\ndone\n\nlemma (in Module) l_comb_mem:\"\\<lbrakk>ideal R A; H \\<subseteq> carrier M; \n       s \\<in> {j. j \\<le> (n::nat)} \\<rightarrow> A; m \\<in> {j. j \\<le> n} \\<rightarrow> H\\<rbrakk> \\<Longrightarrow> \n      l_comb R M n s m \\<in> carrier M\"\napply (simp add:liear_comb_memTr)\ndone\n\nlemma (in Module) l_comb_transpos:\" \\<lbrakk>ideal R A; H \\<subseteq> carrier M;\n      s \\<in> {l. l \\<le> Suc n} \\<rightarrow> A; f \\<in> {l. l \\<le> Suc n} \\<rightarrow> H;\n      j < Suc n \\<rbrakk> \\<Longrightarrow> \n     \\<Sigma>\\<^sub>e M (cmp (\\<lambda>k. s k \\<cdot>\\<^sub>s f k) (transpos j (Suc n))) (Suc n) =\n       \\<Sigma>\\<^sub>e M (\\<lambda>k. (cmp s (transpos j (Suc n))) k \\<cdot>\\<^sub>s\n                  (cmp f (transpos j (Suc n))) k) (Suc n)\"\napply (cut_tac sc_Ring)\napply (rule nsum_eq) \n apply (rule allI, rule impI, simp add:cmp_def)\n apply (cut_tac l = ja in transpos_mem[of j \"Suc n\" \"Suc n\"],\n        simp add:less_imp_le, simp, simp, assumption)\n apply (rule sc_mem,\n        simp add:Pi_def Ring.ideal_subset,\n        simp add:Pi_def subsetD)\n apply (rule allI, rule impI, simp add:cmp_def)\n apply (frule less_imp_le[of j \"Suc n\"],\n        frule_tac l = ja in transpos_mem[of j \"Suc n\" \"Suc n\"], simp,\n        simp, assumption+)\n apply (rule sc_mem,\n        simp add:Pi_def Ring.ideal_subset,\n        simp add:Pi_def subsetD)\n apply (rule allI, rule impI,\n        simp add:cmp_def)\ndone\n\nlemma (in Module) l_comb_transpos1:\" \\<lbrakk>ideal R A; H \\<subseteq> carrier M;\n      s \\<in> {l. l \\<le> Suc n} \\<rightarrow> A; f \\<in> {l. l \\<le> Suc n} \\<rightarrow> H; j < Suc n \\<rbrakk> \\<Longrightarrow> \n l_comb R M (Suc n) s f = \n  l_comb R M (Suc n) (cmp s (transpos j (Suc n))) (cmp f (transpos j (Suc n)))\"\napply (cut_tac sc_Ring)\napply (frule l_comb_transpos[THEN sym, of A H s n f j], assumption+)\n apply (simp del:nsum_suc add:l_comb_def,\n        thin_tac \"\\<Sigma>\\<^sub>e M (\\<lambda>k. (cmp s (transpos j (Suc n))) k \\<cdot>\\<^sub>s\n               (cmp f (transpos j (Suc n))) k) (Suc n) =\n     \\<Sigma>\\<^sub>e M (cmp (\\<lambda>k. s k \\<cdot>\\<^sub>s f k) (transpos j (Suc n))) (Suc n)\")\n apply (cut_tac addition2[of \"\\<lambda>j. s j \\<cdot>\\<^sub>s f j\" n \"transpos j (Suc n)\"],\n         simp)\n apply (rule Pi_I, rule sc_mem,\n          simp add:Pi_def Ring.ideal_subset,\n          simp add:Pi_def subsetD)\n apply (rule_tac i = j and n = \"Suc n\" and j = \"Suc n\" in transpos_hom,\n        simp add:less_imp_le, simp, simp)\n apply (rule_tac i = j and n = \"Suc n\" and j = \"Suc n\" in transpos_inj,\n         simp add:less_imp_le, simp, simp)\ndone\n\nlemma (in Module) sc_linear_span:\"\\<lbrakk>ideal R A; H \\<subseteq> carrier M; a \\<in> A;\n h \\<in> H\\<rbrakk> \\<Longrightarrow> a \\<cdot>\\<^sub>s h \\<in> linear_span R M A H\"\napply (simp add:linear_span_def)\n apply (simp add:nonempty)\n apply (simp add:l_comb_def)\n apply (subgoal_tac \"(\\<lambda>k\\<in>{j. j \\<le> (0::nat)}. a) \\<in>{j. j \\<le> 0} \\<rightarrow> A\")\n apply (subgoal_tac \"(\\<lambda>k\\<in>{j. j \\<le> 0}. h) \\<in> {j. j \\<le> (0::nat)} \\<rightarrow> H\")\n apply (subgoal_tac \"a \\<cdot>\\<^sub>s h = \n \\<Sigma>\\<^sub>e M (\\<lambda>j. (\\<lambda>k\\<in>{j. j \\<le> (0::nat)}. a) j \\<cdot>\\<^sub>s (\\<lambda>k\\<in>{j. j \\<le> (0::nat)}. h) j) 0\")\n apply blast\n apply simp+\ndone\n\nlemma (in Module) l_span_cont_H:\"H \\<subseteq> carrier M \\<Longrightarrow> \n                      H \\<subseteq> linear_span R M (carrier R) H\"            \napply (rule subsetI)\napply (cut_tac sc_Ring,\n       cut_tac Ring.whole_ideal[of R])\napply (frule_tac A = \"carrier R\" and H = H and a = \"1\\<^sub>r\\<^bsub>R\\<^esub>\" \n       and h = x in sc_linear_span, assumption+)\n apply (simp add:Ring.ring_one, assumption+)\n apply (frule_tac c = x in subsetD[of H \"carrier M\"], assumption+,\n        simp add:sprod_one, assumption)\ndone\n\nlemma (in Module) linear_span_inc_0:\"\\<lbrakk>ideal R A; H \\<subseteq> carrier M\\<rbrakk>  \\<Longrightarrow> \n                   \\<zero> \\<in> linear_span R M A H\" \napply (case_tac \"H = {}\")\n apply (simp add:linear_span_def)\n\napply (frule nonempty_ex[of H], erule exE)\n apply (frule_tac h = x in sc_linear_span[of A H \"\\<zero>\\<^bsub>R\\<^esub>\"], assumption)\n apply (cut_tac sc_Ring, simp add:Ring.ideal_zero, assumption)\n apply (frule_tac c = x in subsetD[of H \"carrier M\"], assumption,\n        simp add:sc_0_m)\ndone\n\nlemma (in Module) linear_span_iOp_closedTr1:\"\\<lbrakk>ideal R A;\n       s \\<in> {j. j \\<le> (n::nat)} \\<rightarrow> A\\<rbrakk> \\<Longrightarrow>\n               (\\<lambda>x\\<in>{j. j \\<le> n}. -\\<^sub>a\\<^bsub>R\\<^esub> (s x)) \\<in> {j. j \\<le> n} \\<rightarrow> A\"\napply (rule Pi_I)\n apply simp\n apply (cut_tac sc_Ring,\n        rule Ring.ideal_inv1_closed, assumption+)\n apply (simp add:Pi_def)\ndone\n\nlemma (in Module) l_span_gen_mono:\"\\<lbrakk>K \\<subseteq> H; H \\<subseteq> carrier M; ideal R A\\<rbrakk> \\<Longrightarrow>\n        linear_span R M A K \\<subseteq> linear_span R M A H\"\napply (rule subsetI)\napply (case_tac \"K = {}\", simp add:linear_span_def[of _ _ _ \"{}\"],\n       simp add:linear_span_inc_0)\napply (frule nonempty_ex[of K], erule exE,\n       frule_tac c = xa in subsetD[of K H], assumption+,\n       frule nonempty[of _ H])\napply (simp add:linear_span_def[of _ _ _ K],\n       erule exE, (erule bexE)+, simp,\n       frule extend_fun[of _ _ K H], assumption+)\napply (simp add: l_comb_mem_linear_span)\ndone\n\nlemma (in Module) l_comb_add:\"\\<lbrakk>ideal R A; H \\<subseteq> carrier M;\n        s \\<in> {j. j \\<le> (n::nat)} \\<rightarrow> A; f \\<in> {j. j \\<le> n} \\<rightarrow> H;\n        t \\<in> {j. j \\<le> (m::nat)} \\<rightarrow> A; g \\<in> {j. j \\<le> m} \\<rightarrow> H\\<rbrakk> \\<Longrightarrow>\n  l_comb R M (Suc (n + m)) (jointfun n s m t) (jointfun n f m g) =\n                                  l_comb R M n s f \\<plusminus> l_comb R M m t g\"\napply (cut_tac sc_Ring)       \napply (simp del:nsum_suc add:l_comb_def)\n apply (subst nsum_split)\n apply (rule allI, rule impI)\n apply (case_tac \"j \\<le> n\", simp add:jointfun_def,\n        rule sc_mem, simp add:Pi_def Ring.ideal_subset,\n       simp add:Pi_def subsetD)\n apply (simp add:jointfun_def sliden_def) \n apply (frule_tac m = j and n = \"Suc (n + m)\" and l = \"Suc n\" in diff_le_mono,\n        thin_tac \"j \\<le> Suc (n + m)\", simp,\n        rule sc_mem, simp add:Pi_def Ring.ideal_subset,\n        simp add:Pi_def subsetD) \n apply (simp add:l_comb_jointfun_jj[of H A s n f t m g])\n apply (cut_tac nsum_eq[of m \"cmp (\\<lambda>j. jointfun n s m t j \\<cdot>\\<^sub>s \n        jointfun n f m g j) (slide (Suc n))\" \"\\<lambda>j. t j \\<cdot>\\<^sub>s g j\"], simp)\n apply (rule allI, rule impI, simp add:cmp_def,\n        simp add:jointfun_def sliden_def slide_def,\n        rule sc_mem, simp add:Pi_def Ring.ideal_subset,\n       simp add:Pi_def subsetD)\n apply (rule allI, rule impI,\n        rule sc_mem, simp add:Pi_def Ring.ideal_subset,\n       simp add:Pi_def subsetD)\n apply (simp add:cmp_def jointfun_def sliden_def slide_def)\ndone\n       \nlemma (in Module) l_comb_add1Tr:\"\\<lbrakk>ideal R A; H \\<subseteq> carrier M\\<rbrakk> \\<Longrightarrow>\n  f \\<in> {j. j \\<le> (n::nat)} \\<rightarrow> H \\<and> s \\<in> {j. j \\<le> n} \\<rightarrow> A \\<and> t \\<in> {j. j \\<le> n} \\<rightarrow> A \\<longrightarrow>\n    l_comb R M n (\\<lambda>x\\<in>{j. j \\<le> n}. (s x) \\<plusminus>\\<^bsub>R\\<^esub> (t x)) f =\n      l_comb R M n s f \\<plusminus> l_comb R M n t f\"\napply (induct_tac n)\n apply (simp add:l_comb_def sc_Ring Ring.ideal_subset subsetD sc_l_distr)\n\n apply (rule impI, (erule conjE)+)\n apply (frule func_pre[of f], frule func_pre[of s], frule func_pre[of t],\n        simp)\n apply (simp add:l_comb_def, cut_tac sc_Ring)\n apply (cut_tac n = n and f = \"\\<lambda>j. (if j \\<le> n then s j \\<plusminus>\\<^bsub>R\\<^esub> t j else undefined) \\<cdot>\\<^sub>s f j\" and g = \"\\<lambda>j. (if j \\<le> Suc n then s j \\<plusminus>\\<^bsub>R\\<^esub> t j else undefined) \\<cdot>\\<^sub>s\n                     f j\" in nsum_eq)\n apply (rule allI, rule impI, simp,\n         rule sc_mem, frule Ring.ring_is_ag,\n         rule aGroup.ag_pOp_closed[of R], assumption,\n         simp add:Pi_def Ring.ideal_subset,\n         simp add:Pi_def Ring.ideal_subset,\n         simp add:Pi_def subsetD)\n apply (rule allI, rule impI, simp,\n         rule sc_mem, frule Ring.ring_is_ag,\n         rule aGroup.ag_pOp_closed[of R], assumption,\n         simp add:Pi_def Ring.ideal_subset,\n         simp add:Pi_def Ring.ideal_subset,\n         simp add:Pi_def subsetD)\n apply (simp)\n apply simp\n apply (thin_tac \"\\<Sigma>\\<^sub>e M (\\<lambda>j. (if j \\<le> n then s j \\<plusminus>\\<^bsub>R\\<^esub> t j else undefined) \\<cdot>\\<^sub>s f j)\n        n =  \\<Sigma>\\<^sub>e M (\\<lambda>j. s j \\<cdot>\\<^sub>s f j) n \\<plusminus> \\<Sigma>\\<^sub>e M (\\<lambda>j. t j \\<cdot>\\<^sub>s f j) n\",\n        thin_tac \"\\<Sigma>\\<^sub>e M (\\<lambda>j. (if j \\<le> Suc n then s j \\<plusminus>\\<^bsub>R\\<^esub> t j else undefined) \\<cdot>\\<^sub>s \n        f j) n = \\<Sigma>\\<^sub>e M (\\<lambda>j. s j \\<cdot>\\<^sub>s f j) n \\<plusminus> \\<Sigma>\\<^sub>e M (\\<lambda>j. t j \\<cdot>\\<^sub>s f j) n\")\n apply (frule_tac x = \"Suc n\" and A = \"{j. j \\<le> Suc n}\" in \n        funcset_mem[of s _ A], simp,\n        frule_tac x = \"Suc n\" and A = \"{j. j \\<le> Suc n}\" in \n        funcset_mem[of t _ A], simp,\n        frule_tac x = \"Suc n\" and A = \"{j. j \\<le> Suc n}\" in\n        funcset_mem[of f _ H], simp,\n        cut_tac sc_Ring,\n        frule_tac h = \"s (Suc n)\" in Ring.ideal_subset, assumption+,\n        frule_tac h = \"t (Suc n)\" in Ring.ideal_subset, assumption+,\n        frule_tac c = \"f (Suc n)\" in subsetD[of H \"carrier M\"], assumption+)\n apply (simp add:sc_l_distr)\n apply (cut_tac n = n and f = \"\\<lambda>j. s j \\<cdot>\\<^sub>s f j\" in nsum_mem,\n        rule allI, rule impI,  rule sc_mem,\n        simp add:Pi_def Ring.ideal_subset,\n        simp add:Pi_def subsetD)\n apply (cut_tac n = n and f = \"\\<lambda>j. t j \\<cdot>\\<^sub>s f j\" in nsum_mem,\n        rule allI, rule impI,  rule sc_mem,\n        simp add:Pi_def Ring.ideal_subset,\n        simp add:Pi_def subsetD)\n apply (cut_tac a = \"s (Suc n)\" and m = \"f (Suc n)\" in sc_mem,\n        simp add:Pi_def Ring.ideal_subset,\n        simp add:Pi_def subsetD)\n apply (cut_tac a = \"t (Suc n)\" and m = \"f (Suc n)\" in sc_mem,\n        simp add:Pi_def Ring.ideal_subset,\n        simp add:Pi_def subsetD)\n apply (subst pOp_assocTr41[THEN sym], assumption+,\n        subst pOp_assocTr42, assumption+)\n apply (frule_tac x = \"\\<Sigma>\\<^sub>e M (\\<lambda>j. t j \\<cdot>\\<^sub>s f j) n\" and \n         y = \"s (Suc n) \\<cdot>\\<^sub>s f (Suc n)\" in ag_pOp_commute, assumption+, simp)\n  apply (subst pOp_assocTr42[THEN sym], assumption+,\n         subst pOp_assocTr41, assumption+, simp)\ndone\n\nlemma (in Module) l_comb_add1:\"\\<lbrakk>ideal R A; H \\<subseteq> carrier M; \n f \\<in> {j. j \\<le> (n::nat)} \\<rightarrow> H; s \\<in> {j. j \\<le> n} \\<rightarrow> A; t \\<in> {j. j \\<le> n} \\<rightarrow> A \\<rbrakk> \\<Longrightarrow> \n   l_comb R M n (\\<lambda>x\\<in>{j. j \\<le> n}. (s x) \\<plusminus>\\<^bsub>R\\<^esub> (t x)) f =\n                                l_comb R M n s f \\<plusminus> l_comb R M n t f\"\napply (simp add:l_comb_add1Tr)\ndone\n\nlemma (in Module) linear_span_iOp_closedTr2:\"\\<lbrakk>ideal R A; H \\<subseteq> carrier M; \n       f \\<in> {j. j \\<le> (n::nat)} \\<rightarrow> H; s \\<in> {j. j \\<le> n} \\<rightarrow> A\\<rbrakk>  \\<Longrightarrow>\n       -\\<^sub>a (l_comb R M n s f) = \n           l_comb R M n (\\<lambda>x\\<in>{j. j \\<le> n}. -\\<^sub>a\\<^bsub>R\\<^esub> (s x)) f\"\napply (frule_tac f = f and A = \"{j. j \\<le> n}\" and B = H and x = 0 in \n       funcset_mem, simp)\napply (frule_tac A = A and s = s in linear_span_iOp_closedTr1, assumption+)\napply (frule l_comb_add1[of A H f n s \"\\<lambda>x\\<in>{j. j \\<le> n}. -\\<^sub>a\\<^bsub>R\\<^esub> (s x)\"], \n        assumption+)\napply (cut_tac linear_comb0_1[of H \"\\<lambda>x\\<in>{j. j \\<le> n}. s x \\<plusminus>\\<^bsub>R\\<^esub> \n                  (\\<lambda>x\\<in>{j. j \\<le> n}. -\\<^sub>a\\<^bsub>R\\<^esub> (s x)) x\" n f])\n apply (simp,\n       thin_tac \"l_comb R M n\n (\\<lambda>x\\<in>{j. j \\<le> n}. s x \\<plusminus>\\<^bsub>R\\<^esub> (if x \\<le> n then -\\<^sub>a\\<^bsub>R\\<^esub> (s x) else undefined)) f = \\<zero>\")\n apply (frule l_comb_mem[of A H s n f], assumption+,\n        frule l_comb_mem[of A H \"\\<lambda>x\\<in>{j. j \\<le> n}. -\\<^sub>a\\<^bsub>R\\<^esub> (s x)\" n f], assumption+)\n apply (frule ag_mOp_closed[of \"l_comb R M n s f\"])\n apply (frule ag_pOp_assoc[of \"-\\<^sub>a (l_comb R M n s f)\" \"l_comb R M n s f\" \"l_comb R M n (\\<lambda>x\\<in>{j. j \\<le> n}. -\\<^sub>a\\<^bsub>R\\<^esub> (s x)) f\"], assumption+)\n apply (simp, simp add:ag_l_inv1, simp add:ag_l_zero, simp add:ag_r_zero)\n apply assumption+\n apply (rule Pi_I, simp)\n apply (frule_tac x = x in funcset_mem[of s \"{j. j \\<le> n}\" A], simp,\n        cut_tac sc_Ring,\n        frule_tac h = \"s x\" in Ring.ideal_subset[of R A], assumption+)\n apply (frule Ring.ring_is_ag[of R],\n        simp add:aGroup.ag_r_inv1[of R])\n apply assumption\ndone\n\nlemma (in Module) linear_span_iOp_closed:\"\\<lbrakk>ideal R A; H \\<subseteq> carrier M; \n a \\<in> linear_span R M A H\\<rbrakk> \\<Longrightarrow> -\\<^sub>a a \\<in> linear_span R M A H\"\napply (case_tac \"H = {}\")\napply (simp add:linear_span_def)\napply (simp add:ag_inv_zero)\napply (simp add:linear_span_def, erule exE, (erule bexE)+)\napply simp\napply (frule_tac f = f and n = n and s = s in \n                 linear_span_iOp_closedTr2[of A H], assumption+)\napply (subgoal_tac \"(\\<lambda>x\\<in>{j. j \\<le> n}. -\\<^sub>a\\<^bsub>R\\<^esub> (s x)) \\<in> {j. j \\<le> n} \\<rightarrow> A\")\napply blast\napply (rule Pi_I, simp)\napply(cut_tac sc_Ring,\n      rule Ring.ideal_inv1_closed, assumption+,\n      simp add:Pi_def)\ndone\n\nlemma (in Module) linear_span_pOp_closed:\n \"\\<lbrakk>ideal R A; H \\<subseteq> carrier M; a \\<in> linear_span R M A H; b \\<in> linear_span R M A H\\<rbrakk>\n  \\<Longrightarrow> a \\<plusminus> b \\<in> linear_span R M A H\"\napply (case_tac \"H = {}\")\n apply (simp add:linear_span_def)\n apply (cut_tac ag_inc_zero, simp add:ag_r_zero)\napply (simp add:linear_span_def) \n apply ((erule exE)+, (erule bexE)+)\n apply (rename_tac n m f g s t)\n apply (simp add:l_comb_def)\n apply (cut_tac n = n and f = \"\\<lambda>j. s j \\<cdot>\\<^sub>s f j\" and m = m and \n                g = \"\\<lambda>j. t j \\<cdot>\\<^sub>s g j\" in nsum_add_nm)\n apply (rule allI, rule impI, rule sc_mem,\n        cut_tac sc_Ring,\n        simp add:Pi_def Ring.ideal_subset,\n        simp add:Pi_def subsetD)\n apply (rule allI, rule impI, rule sc_mem,\n        cut_tac sc_Ring,\n        simp add:Pi_def Ring.ideal_subset,\n        simp add:Pi_def subsetD)\n apply (rotate_tac -1, frule sym, \n        thin_tac \"\\<Sigma>\\<^sub>e M (jointfun n (\\<lambda>j. s j \\<cdot>\\<^sub>s f j) m (\\<lambda>j. t j \\<cdot>\\<^sub>s g j)) \n                     (Suc (n + m)) =\n                  \\<Sigma>\\<^sub>e M (\\<lambda>j. s j \\<cdot>\\<^sub>s f j) n \\<plusminus> \\<Sigma>\\<^sub>e M (\\<lambda>j. t j \\<cdot>\\<^sub>s g j) m\",\n         simp del:nsum_suc)\n apply (cut_tac n = \"Suc (n + m)\" and f = \"jointfun n (\\<lambda>j. s j \\<cdot>\\<^sub>s f j) m \n  (\\<lambda>j. t j \\<cdot>\\<^sub>s g j)\" and g = \"\\<lambda>j. (jointfun n s m t) j \\<cdot>\\<^sub>s (jointfun n f m g) j\"\n   in nsum_eq)\n apply (rule allI, rule impI)\n  apply (simp add:jointfun_def)\n  apply (case_tac \"j \\<le> n\", simp)\n  apply (rule sc_mem,\n         cut_tac sc_Ring,\n         simp add:Pi_def Ring.ideal_subset,\n         simp add:Pi_def subsetD)  \n  apply (simp, rule sc_mem)\n  apply (simp add:sliden_def,\n         frule_tac m = j and n = \"Suc (n + m)\" and l = \"Suc n\" in diff_le_mono,\n         thin_tac \"j \\<le> Suc (n + m)\", simp,\n         cut_tac sc_Ring,\n         simp add:Pi_def Ring.ideal_subset) \n  apply (simp add:sliden_def,\n         frule_tac m = j and n = \"Suc (n + m)\" and l = \"Suc n\" in diff_le_mono,\n         thin_tac \"j \\<le> Suc (n + m)\", simp,\n         cut_tac sc_Ring,\n         simp add:Pi_def subsetD) \n apply (rule allI, rule impI)\n  apply (simp add:jointfun_def)\n  apply (case_tac \"j \\<le> n\", simp)\n  apply (rule sc_mem,\n         cut_tac sc_Ring,\n         simp add:Pi_def Ring.ideal_subset,\n         simp add:Pi_def subsetD)  \n  apply (simp, simp add:sliden_def,\n         rule sc_mem,\n         frule_tac m = j and n = \"Suc (n + m)\" and l = \"Suc n\" in diff_le_mono,\n         thin_tac \"j \\<le> Suc (n + m)\", simp,\n         cut_tac sc_Ring,\n         simp add:Pi_def Ring.ideal_subset) \n  apply (frule_tac m = j and n = \"Suc (n + m)\" and l = \"Suc n\" in diff_le_mono,\n         thin_tac \"j \\<le> Suc (n + m)\", simp,\n         cut_tac sc_Ring,\n         simp add:Pi_def subsetD)\n  apply (rule allI, rule impI,\n         simp add:jointfun_def)\napply (simp del:nsum_suc,\n       thin_tac \"\\<Sigma>\\<^sub>e M (\\<lambda>j. s j \\<cdot>\\<^sub>s f j) n \\<plusminus> \\<Sigma>\\<^sub>e M (\\<lambda>j. t j \\<cdot>\\<^sub>s g j) m =\n        \\<Sigma>\\<^sub>e M (\\<lambda>j. jointfun n s m t j \\<cdot>\\<^sub>s jointfun n f m g j) (Suc (n + m))\",\n       thin_tac \"\\<Sigma>\\<^sub>e M (jointfun n (\\<lambda>j. s j \\<cdot>\\<^sub>s f j) m (\\<lambda>j. t j \\<cdot>\\<^sub>s g j))\n                        (Suc (n + m)) =\n        \\<Sigma>\\<^sub>e M (\\<lambda>j. jointfun n s m t j \\<cdot>\\<^sub>s jointfun n f m g j) (Suc (n + m))\")\n apply (frule_tac f = s and n = n and A = A and g = t and m = m and B = A in\n                  jointfun_hom0, assumption+, simp del:nsum_suc,\n        frule_tac f = f and n = n and A = H and g = g and m = m and B = H in\n                  jointfun_hom0, assumption+, simp del:nsum_suc)\n apply blast\ndone\n\nlemma (in Module) l_comb_scTr:\"\\<lbrakk>ideal R A; H \\<subseteq> carrier M;\n r \\<in> carrier R; H \\<noteq> {}\\<rbrakk>  \\<Longrightarrow> s \\<in> {j. j \\<le> (n::nat)} \\<rightarrow> A \\<and> \n g \\<in> {j. j \\<le> n} \\<rightarrow>  H  \\<longrightarrow> r \\<cdot>\\<^sub>s (nsum M (\\<lambda>k. (s k) \\<cdot>\\<^sub>s (g k))  n) =  \n                             nsum M (\\<lambda>k. r \\<cdot>\\<^sub>s ((s k) \\<cdot>\\<^sub>s (g k))) n\" \napply (induct_tac n)\n apply (rule impI, (erule conjE)+, simp)\n\napply (rule impI) apply (erule conjE)\n apply (frule func_pre [of _ _ \"A\"]) apply (frule func_pre [of _ _ \"H\"])\n apply (simp)\n apply (cut_tac n = n and f = \"\\<lambda>k. s k \\<cdot>\\<^sub>s g k\" in nsum_mem,\n        rule allI, rule impI,\n        cut_tac sc_Ring, rule sc_mem,\n        simp add:Pi_def Ring.ideal_subset,\n        simp add:Pi_def subsetD)  \n apply (cut_tac a = \"s (Suc n)\" and m = \"g (Suc n)\" in sc_mem,\n        cut_tac sc_Ring,\n        simp add:Pi_def Ring.ideal_subset,\n        simp add:Pi_def subsetD)  \n apply (simp add:sc_r_distr)\ndone\n\nlemma (in Module) l_comb_sc1Tr:\"\\<lbrakk>ideal R A; H \\<subseteq> carrier M;\n r \\<in> carrier R; H \\<noteq> {}\\<rbrakk>  \\<Longrightarrow> s \\<in> {j. j \\<le> (n::nat)} \\<rightarrow> A \\<and> \n g \\<in> {j. j \\<le> n} \\<rightarrow>  H  \\<longrightarrow> r \\<cdot>\\<^sub>s (nsum M (\\<lambda>k. (s k) \\<cdot>\\<^sub>s (g k))  n) =  \n                             nsum M (\\<lambda>k. (r \\<cdot>\\<^sub>r\\<^bsub>R\\<^esub> (s k)) \\<cdot>\\<^sub>s (g k)) n\"\napply (cut_tac sc_Ring) \napply (induct_tac n)\n apply (rule impI, (erule conjE)+, simp)\n apply (subst sc_assoc, assumption+,\n        simp add:Pi_def Ring.ideal_subset,\n        simp add:Pi_def subsetD, simp)\n\napply (rule impI) apply (erule conjE)\n apply (frule func_pre [of _ _ \"A\"], frule func_pre [of _ _ \"H\"])\n apply simp\n apply (cut_tac n = n and f = \"\\<lambda>k. s k \\<cdot>\\<^sub>s g k\" in nsum_mem,\n        rule allI, rule impI,\n        cut_tac sc_Ring, rule sc_mem,\n        simp add:Pi_def Ring.ideal_subset,\n        simp add:Pi_def subsetD)  \n apply (cut_tac a = \"s (Suc n)\" and m = \"g (Suc n)\" in sc_mem,\n        cut_tac sc_Ring,\n        simp add:Pi_def Ring.ideal_subset,\n        simp add:Pi_def subsetD)  \n apply (simp add:sc_r_distr)\n apply (subst  sc_assoc, assumption+,\n        simp add:Pi_def Ring.ideal_subset,\n        simp add:Pi_def subsetD, simp)\ndone\n\nlemma (in Module) l_comb_sc:\"\\<lbrakk>ideal R A; H \\<subseteq> carrier M; r \\<in> carrier R; \n      s \\<in> {j. j \\<le> (n::nat)} \\<rightarrow> A;  g \\<in> {j. j \\<le> n} \\<rightarrow>  H\\<rbrakk> \\<Longrightarrow>\nr \\<cdot>\\<^sub>s (nsum M (\\<lambda>k. (s k) \\<cdot>\\<^sub>s (g k)) n) = nsum M (\\<lambda>k. r \\<cdot>\\<^sub>s ((s k) \\<cdot>\\<^sub>s (g k))) n\" \napply (case_tac \"H \\<noteq> {}\")\n apply (simp add:l_comb_scTr)\n apply simp\n apply (frule_tac x = 0 in funcset_mem[of g \" {j. j \\<le> n}\" \"{}\"], simp)\n apply blast\ndone\n\nlemma (in Module) l_comb_sc1:\"\\<lbrakk>ideal R A; H \\<subseteq> carrier M; r \\<in> carrier R; \n      s \\<in> {j. j \\<le> (n::nat)} \\<rightarrow> A;  g \\<in> {j. j \\<le> n} \\<rightarrow>  H\\<rbrakk> \\<Longrightarrow>\nr \\<cdot>\\<^sub>s (nsum M (\\<lambda>k. (s k) \\<cdot>\\<^sub>s (g k)) n) = nsum M (\\<lambda>k. (r \\<cdot>\\<^sub>r\\<^bsub>R\\<^esub> (s k)) \\<cdot>\\<^sub>s (g k)) n\" \napply (case_tac \"H \\<noteq> {}\")\n apply (simp add:l_comb_sc1Tr)\n apply simp\n apply (frule_tac x = 0 in funcset_mem[of g \" {j. j \\<le> n}\" \"{}\"], simp)\n apply blast\ndone\n\nlemma (in Module) linear_span_sc_closed:\"\\<lbrakk>ideal R A; H \\<subseteq> carrier M;\n r \\<in> carrier R; x \\<in> linear_span R M A H\\<rbrakk> \\<Longrightarrow> r \\<cdot>\\<^sub>s x \\<in> linear_span R M A H\"\napply (case_tac \"H = {}\")\n apply (simp add:linear_span_def)\n apply (simp add:sc_a_0)\napply (simp add:linear_span_def)\n apply (erule exE, (erule bexE)+)\n apply (simp add:l_comb_def) \n apply (simp add:l_comb_sc)\n \napply (cut_tac n = n and f = \"\\<lambda>j. r \\<cdot>\\<^sub>s (s j \\<cdot>\\<^sub>s f j)\" and \n       g = \"\\<lambda>j. (r \\<cdot>\\<^sub>r\\<^bsub>R\\<^esub> (s j)) \\<cdot>\\<^sub>s f j\" in nsum_eq)\n apply (rule allI, rule impI,\n        rule sc_mem, assumption, rule sc_mem,\n        cut_tac sc_Ring,\n        simp add:Pi_def Ring.ideal_subset,\n        simp add:Pi_def subsetD)\n apply (rule allI, rule impI,\n        rule sc_mem,\n        cut_tac sc_Ring,\n        rule Ring.ring_tOp_closed, assumption+,\n        simp add:Pi_def Ring.ideal_subset,\n        simp add:Pi_def subsetD)\n apply (rule allI, rule impI,\n        subst sc_assoc, assumption,\n        cut_tac sc_Ring, \n        simp add:Pi_def Ring.ideal_subset,\n        simp add:Pi_def subsetD, simp,\n        simp,\n    thin_tac \"\\<Sigma>\\<^sub>e M (\\<lambda>j. r \\<cdot>\\<^sub>s (s j \\<cdot>\\<^sub>s f j)) n = \n                                \\<Sigma>\\<^sub>e M (\\<lambda>j. (r \\<cdot>\\<^sub>r\\<^bsub>R\\<^esub> s j) \\<cdot>\\<^sub>s f j) n\",\n    thin_tac \"x = \\<Sigma>\\<^sub>e M (\\<lambda>j. s j \\<cdot>\\<^sub>s f j) n\")\n\n apply (cut_tac n = n and f = \"\\<lambda>j. (r \\<cdot>\\<^sub>r\\<^bsub>R\\<^esub> s j) \\<cdot>\\<^sub>s f j\" and \n       g = \"\\<lambda>j. (\\<lambda>x\\<in>{j. j \\<le> n}. r \\<cdot>\\<^sub>r\\<^bsub>R\\<^esub> (s x)) j \\<cdot>\\<^sub>s f j\" in nsum_eq)\n  apply (rule allI, rule impI,\n        rule sc_mem,\n        cut_tac sc_Ring,\n        rule Ring.ring_tOp_closed, assumption+,\n        simp add:Pi_def Ring.ideal_subset,\n        simp add:Pi_def subsetD)\n   apply (rule allI, rule impI,\n         rule sc_mem, simp) apply (\n          cut_tac sc_Ring,\n        rule Ring.ring_tOp_closed, assumption+,\n        simp add:Pi_def Ring.ideal_subset,\n        simp add:Pi_def subsetD)\n  apply (rule allI, rule impI)\n         apply simp\n  apply (subgoal_tac \"(\\<lambda>x\\<in>{j. j \\<le> n}. r \\<cdot>\\<^sub>r\\<^bsub>R\\<^esub> s x) \\<in> {j. j \\<le> n} \\<rightarrow> A\",\n         blast)\n  apply (rule Pi_I, simp)\napply (thin_tac \"\\<Sigma>\\<^sub>e M (\\<lambda>j. (r \\<cdot>\\<^sub>r\\<^bsub>R\\<^esub> s j) \\<cdot>\\<^sub>s f j) n =\n        \\<Sigma>\\<^sub>e M (\\<lambda>j. (if j \\<le> n then r \\<cdot>\\<^sub>r\\<^bsub>R\\<^esub> s j else undefined) \\<cdot>\\<^sub>s f j) n\",\n        cut_tac sc_Ring,\n        rule Ring.ideal_ring_multiple, assumption+, simp add:Pi_def,\n        assumption)\ndone\n    \nlemma (in Module) mem_single_l_spanTr:\"\\<lbrakk>ideal R A; h \\<in> carrier M\\<rbrakk> \\<Longrightarrow>\n      s \\<in> {j. j \\<le> (n::nat)} \\<rightarrow> A \\<and>\n      f \\<in> {j. j \\<le> n} \\<rightarrow> {h} \\<and> l_comb R M n s f \\<in> linear_span R M A {h}\n      \\<longrightarrow> (\\<exists>a \\<in> A. l_comb R M n s f = a \\<cdot>\\<^sub>s h)\"\napply (cut_tac sc_Ring)  \napply (induct_tac n)\n apply (rule impI, (erule conjE)+)\n apply (simp add:l_comb_def Ring.ideal_subset[of R A] bexI[of _ \"s 0\"])\napply (rule impI, (erule conjE)+,\n       frule func_pre[of _ _ A], frule func_pre[of _ _ \"{h}\"],\n       frule_tac n = n in l_comb_mem_linear_span[of A \"{h}\" s _ f],\n       rule subsetI, simp, assumption+, simp,\n       erule bexE)\napply (frule singleton_sub[of h \"carrier M\"])\n apply (frule Ring.ideal_subset1[of R A], assumption)\n apply (frule extend_fun[of s _ A \"carrier R\"], assumption)\n apply (frule_tac n = n in l_comb_Suc[of \"{h}\" A s _ f], assumption+,\n        simp)\n apply (frule_tac A = \"{j. j \\<le> Suc n}\" and x = \"Suc n\" in \n        funcset_mem[of f _ \"{h}\"], simp, simp,\n        frule_tac A = \"{j. j \\<le> Suc n}\" and x = \"Suc n\" in \n        funcset_mem[of s _ A], simp,\n        frule_tac h = \"s (Suc n)\" in Ring.ideal_subset[of R A], assumption+)\n apply (frule_tac h = a in Ring.ideal_subset[of R A], assumption+,\n        frule_tac h = \"s (Suc n)\" in Ring.ideal_subset[of R A], assumption+,\n        simp add:sc_l_distr[THEN sym],\n        frule_tac x = a and y = \"s (Suc n)\" in Ring.ideal_pOp_closed[of R A],\n        assumption+, blast)\ndone\n\nlemma (in Module) mem_single_l_span:\"\\<lbrakk>ideal R A; h \\<in> carrier M; \n       s \\<in> {j. j \\<le> (n::nat)} \\<rightarrow> A; f \\<in> {j. j \\<le> n} \\<rightarrow> {h}; \n       l_comb R M n s f \\<in> linear_span R M A {h}\\<rbrakk> \\<Longrightarrow>\n       \\<exists>a \\<in> A. l_comb R M n s f = a \\<cdot>\\<^sub>s h\"\napply (simp add:mem_single_l_spanTr)\ndone\n\nlemma (in Module) mem_single_l_span1:\"\\<lbrakk>ideal R A; h \\<in> carrier M; \n       x \\<in> linear_span R M A {h}\\<rbrakk> \\<Longrightarrow> \\<exists>a \\<in> A. x = a \\<cdot>\\<^sub>s h\"\napply (simp add:linear_span_def, erule exE, (erule bexE)+, simp)\napply (frule_tac s = s and n = n and f = f in mem_single_l_span[of A h],\n       assumption+)\napply (frule singleton_sub[of h \"carrier M\"],\n      rule_tac s = s and f = f in l_comb_mem_linear_span[of A \"{h}\"],\n      assumption+)\ndone\n\nlemma (in Module) linear_span_subModule:\"\\<lbrakk>ideal R A; H \\<subseteq> carrier M\\<rbrakk>  \\<Longrightarrow> \n                  submodule R M (linear_span R M A H)\"\napply (case_tac \"H = {}\")\n apply (simp add:linear_span_def)\n apply (simp add:submodule_0)\n\napply (simp add:submodule_def)\napply (rule conjI)\n apply (simp add:linear_span_def)\n apply (rule subsetI)\n apply (simp add:CollectI)\n apply (erule exE, (erule bexE)+)\n apply simp\n apply (simp add:l_comb_mem)\napply (rule conjI)\n apply (rule asubg_test) \n apply (rule subsetI) apply (simp add:linear_span_def)\n apply (erule exE, (erule bexE)+)\n apply (simp add:l_comb_mem)\n apply (frule linear_span_inc_0[of A H], assumption, blast)\n apply (rule ballI)+\n apply (rule linear_span_pOp_closed, assumption+)\n apply (rule linear_span_iOp_closed, assumption+)\napply (rule allI)+\n apply (simp add:linear_span_sc_closed)\ndone\n\nlemma (in Module) l_comb_mem_submoduleTr:\"\\<lbrakk>ideal R A; submodule R M N\\<rbrakk> \\<Longrightarrow>\n (s \\<in> {j. j \\<le> (n::nat)} \\<rightarrow> A \\<and> f \\<in> {j. j \\<le> n} \\<rightarrow> carrier M \\<and>\n (\\<forall>j \\<le> n.(s j) \\<cdot>\\<^sub>s (f j) \\<in> N)) \\<longrightarrow> l_comb R M n s f \\<in> N\"\napply (induct_tac n)\n apply (simp add:l_comb_def, rule impI, (erule conjE)+)\napply (frule func_pre[of _ _ A], frule func_pre[of _ _ \"carrier M\"], simp)\napply (simp add:l_comb_def)\napply (frule_tac a = \"Suc n\" in forall_spec, simp) \napply (rule submodule_pOp_closed, assumption+)\ndone\n\nlemma (in Module) l_span_sub_submodule:\"\\<lbrakk>ideal R A; submodule R M N; H \\<subseteq> N\\<rbrakk> \\<Longrightarrow>\n       linear_span R M A H \\<subseteq> N\"\napply (cut_tac sc_Ring)\n apply (rule subsetI, simp add:linear_span_def)\n apply (case_tac \"H = {}\", simp)\n apply (simp add:submodule_inc_0)\n\n apply simp\n apply (erule exE, (erule bexE)+)\n apply (cut_tac s = s and A = A and f = f and N = N and n = n in \n        l_comb_mem_submoduleTr, assumption+,\n        frule submodule_subset[of N],\n        frule subset_trans[of H N \"carrier M\"], assumption+,\n        frule_tac f = f and A = \"{j. j \\<le> n}\" and B = H and ?B1.0 = \"carrier M\"\n        in extend_fun, assumption+)\n apply (subgoal_tac \"\\<forall>j\\<le>n. s j \\<cdot>\\<^sub>s f j \\<in> N\", simp)\n apply (rule allI, rule impI)\n apply (rule submodule_sc_closed[of N], assumption,\n        simp add:Pi_def Ring.ideal_subset,\n        simp add:Pi_def subsetD)\ndone\n\nlemma (in Module) linear_span_sub:\"\\<lbrakk>ideal R A; H \\<subseteq> carrier M\\<rbrakk>  \\<Longrightarrow> \n                  (linear_span R M A H) \\<subseteq> carrier M\"\napply (frule linear_span_subModule[of A H], assumption+)\napply (simp add:submodule_subset)\ndone\n\ndefinition\n  smodule_ideal_coeff :: \"[('r, 'm) Ring_scheme, ('a, 'r, 'm1) Module_scheme,\n       'r set] \\<Rightarrow> 'a set\" where\n  \"smodule_ideal_coeff R M A = linear_span R M A (carrier M)\"\n\nabbreviation\n  SMLIDEALCOEFF  (\"(3_/ \\<odot>\\<^bsub>_\\<^esub> _)\" [64,64,65]64) where\n  \"A \\<odot>\\<^bsub>R\\<^esub> M == smodule_ideal_coeff R M A\"\n\nlemma (in Module) smodule_ideal_coeff_is_Submodule:\"ideal R A  \\<Longrightarrow>\n            submodule R M (A \\<odot>\\<^bsub>R\\<^esub> M)\"\napply (simp add:smodule_ideal_coeff_def)\napply (simp add:linear_span_subModule)\ndone\n\nlemma (in Module) mem_smodule_ideal_coeff:\"\\<lbrakk>ideal R A; x \\<in> A \\<odot>\\<^bsub>R\\<^esub> M\\<rbrakk> \\<Longrightarrow>\n             \\<exists>n. \\<exists>s \\<in> {j. j \\<le> n} \\<rightarrow> A. \\<exists>g \\<in> {j. j \\<le> n} \\<rightarrow> carrier M.\n              x = l_comb R M n s g\" \napply (cut_tac ag_inc_zero,\n       frule nonempty[of \"\\<zero>\" \"carrier M\"])\napply (simp add:smodule_ideal_coeff_def linear_span_def,\n       erule exE, (erule bexE)+, blast)\ndone\n\ndefinition\n  quotient_of_submodules :: \"[('r, 'm) Ring_scheme, ('a, 'r, 'm1) Module_scheme,\n            'a set, 'a set] \\<Rightarrow> 'r set\" where\n  \"quotient_of_submodules R M N P = {x | x. x\\<in>carrier R \\<and> \n                                    (linear_span R M (Rxa R x)  P) \\<subseteq> N}\"\n\ndefinition\n  Annihilator :: \"[('r, 'm) Ring_scheme, ('a, 'r, 'm1) Module_scheme]\n    \\<Rightarrow> 'r set\" (\"(Ann\\<^bsub>_\\<^esub> _)\" [82,83]82) where\n  \"Ann\\<^bsub>R\\<^esub> M = quotient_of_submodules R M {\\<zero>\\<^bsub>M\\<^esub>} (carrier M)\"\n\nabbreviation\n  QOFSUBMDS  (\"(4_ \\<^bsub>_\\<ddagger>_\\<^esub> _)\" [82,82,82,83]82) where\n  \"N \\<^bsub>R\\<ddagger>M\\<^esub> P == quotient_of_submodules R M N P\"\n\nlemma (in Module) quotient_of_submodules_inc_0:\n     \"\\<lbrakk>submodule R M P; submodule R M Q\\<rbrakk> \\<Longrightarrow> \\<zero>\\<^bsub>R\\<^esub> \\<in> (P \\<^bsub>R\\<ddagger>M\\<^esub> Q)\"\napply (simp add:quotient_of_submodules_def)\napply (cut_tac sc_Ring, simp add:Ring.ring_zero)\napply (simp add:linear_span_def)\n apply (frule submodule_inc_0[of Q], simp add:nonempty)\napply (rule subsetI)\n apply (simp, erule exE, (erule bexE)+)\n apply (simp, thin_tac \"x = l_comb R M n s f\", simp add:l_comb_def)\n apply (cut_tac n = n and f = \"\\<lambda>j. s j \\<cdot>\\<^sub>s f j\" in nsum_zeroA)\n apply (rule allI, rule impI,\n       frule_tac x = j and f = s and A = \"{j. j \\<le> n}\" in \n       funcset_mem[of _ _ \"R \\<diamondsuit>\\<^sub>p \\<zero>\\<^bsub>R\\<^esub>\"], simp)\n apply (simp add:Rxa_def, erule bexE, simp) apply (\n        simp add:Ring.ring_times_x_0,\n        rule sc_0_m) apply (\n        frule submodule_subset[of Q],\n        simp add:Pi_def subsetD)\n apply (simp add:submodule_inc_0)\ndone\n \nlemma (in Module) quotient_of_submodules_is_ideal:\n      \"\\<lbrakk>submodule R M P; submodule R M Q\\<rbrakk> \\<Longrightarrow> ideal R (P \\<^bsub>R\\<ddagger>M\\<^esub> Q)\"\napply (frule quotient_of_submodules_inc_0 [of P Q], assumption+)\napply (cut_tac sc_Ring,\n       rule Ring.ideal_condition[of R], assumption+)\napply (simp add:quotient_of_submodules_def)\napply (simp add:nonempty) apply (thin_tac \"\\<zero>\\<^bsub>R\\<^esub> \\<in> P \\<^bsub>R\\<ddagger>M\\<^esub> Q\")\n apply (rule ballI)+\n apply (simp add:quotient_of_submodules_def) \napply (erule conjE)+\n apply (rule conjI)\n apply (frule Ring.ring_is_ag,\n        rule aGroup.ag_pOp_closed[of R], assumption+)\n apply (rule aGroup.ag_mOp_closed, assumption+)\napply (subst linear_span_def)\n apply (frule submodule_inc_0 [of Q], simp add:nonempty)\n apply (rule subsetI, simp,\n        erule exE, (erule bexE)+, simp add:l_comb_def,\n        thin_tac \"xa = \\<Sigma>\\<^sub>e M (\\<lambda>j. s j \\<cdot>\\<^sub>s f j) n\")\n apply (cut_tac s = s and n = n and f = f in \n           l_comb_mem_submoduleTr[of \"carrier R\" P])\n apply (simp add:Ring.whole_ideal, assumption+)\n apply (frule Ring.ring_is_ag[of R],\n        frule_tac x = y in aGroup.ag_mOp_closed[of R], assumption+,\n        frule_tac x = x and y = \"-\\<^sub>a\\<^bsub>R\\<^esub> y\" in aGroup.ag_pOp_closed, assumption+,\n        frule_tac a = \"x \\<plusminus>\\<^bsub>R\\<^esub> -\\<^sub>a\\<^bsub>R\\<^esub> y\" in Ring.principal_ideal[of R], assumption+,\n        frule_tac I = \"R \\<diamondsuit>\\<^sub>p (x \\<plusminus>\\<^bsub>R\\<^esub> -\\<^sub>a\\<^bsub>R\\<^esub> y)\" in Ring.ideal_subset1, assumption+)\n  apply (frule_tac f = s and A = \"{j. j \\<le> n}\" and B = \"R \\<diamondsuit>\\<^sub>p (x \\<plusminus>\\<^bsub>R\\<^esub> -\\<^sub>a\\<^bsub>R\\<^esub> y)\" \n         and ?B1.0 = \"carrier R\" in extend_fun, assumption+,\n         frule_tac submodule_subset[of Q],\n         frule_tac f = f and A = \"{j. j \\<le> n}\" and B = Q  \n         and ?B1.0 = \"carrier M\" in extend_fun, assumption+)        \n  apply (subgoal_tac \"\\<forall>j\\<le>n. s j \\<cdot>\\<^sub>s f j \\<in> P\", simp add:l_comb_def,\n         thin_tac \"s \\<in> {j. j \\<le> n} \\<rightarrow> carrier R \\<and>\n        f \\<in> {j. j \\<le> n} \\<rightarrow> carrier M \\<and> (\\<forall>j\\<le>n. s j \\<cdot>\\<^sub>s f j \\<in> P) \\<longrightarrow>\n        l_comb R M n s f \\<in> P\",\n         thin_tac \"s \\<in> {j. j \\<le> n} \\<rightarrow> carrier R\",\n         thin_tac \"f \\<in> {j. j \\<le> n} \\<rightarrow> carrier M\")\n  apply (rule allI, rule impI,\n         frule_tac x = j and f = s and A = \"{j. j \\<le> n}\" and \n         B = \"R \\<diamondsuit>\\<^sub>p (x \\<plusminus>\\<^bsub>R\\<^esub> -\\<^sub>a\\<^bsub>R\\<^esub> y)\" in funcset_mem, simp, \n         thin_tac \"s \\<in> {j. j \\<le> n} \\<rightarrow> R \\<diamondsuit>\\<^sub>p (x \\<plusminus>\\<^bsub>R\\<^esub> -\\<^sub>a\\<^bsub>R\\<^esub> y)\",\n         thin_tac \"ideal R (R \\<diamondsuit>\\<^sub>p (x \\<plusminus>\\<^bsub>R\\<^esub> -\\<^sub>a\\<^bsub>R\\<^esub> y))\")\n  apply (simp add:Rxa_def, fold Rxa_def, erule bexE, simp,\n         thin_tac \"s j = r \\<cdot>\\<^sub>r\\<^bsub>R\\<^esub> (x \\<plusminus>\\<^bsub>R\\<^esub> -\\<^sub>a\\<^bsub>R\\<^esub> y)\")\n  apply (simp add:Ring.ring_distrib1,\n         frule_tac x = r and y = x in Ring.ring_tOp_closed, assumption+, \n         frule_tac x = r and y = \"-\\<^sub>a\\<^bsub>R\\<^esub> y\" in Ring.ring_tOp_closed, assumption+,\n         frule_tac x = j and A = \"{j. j \\<le> n}\" and B = Q in funcset_mem,\n         simp,\n         frule_tac c = \"f j\" in subsetD[of Q \"carrier M\"], assumption+,\n         simp add:sc_l_distr)\n  apply (subst Ring.ring_inv1_2[THEN sym], assumption+,\n         subst Ring.ring_inv1_1, assumption+)\n  apply (frule_tac a = x in Ring.principal_ideal[of R], assumption+,\n         frule_tac a = x in Ring.principal_ideal[of R], assumption+,\n         frule_tac A = \"R \\<diamondsuit>\\<^sub>p x\" and H = Q and a = \"r \\<cdot>\\<^sub>r\\<^bsub>R\\<^esub> x\" and h = \"f j\" in\n         sc_linear_span, assumption+, simp add:Rxa_def, blast,\n         simp add:Pi_def)\n  apply (frule_tac x = r in aGroup.ag_mOp_closed[of R], assumption+,\n         frule_tac a = y in Ring.principal_ideal[of R], assumption+,\n         frule_tac a = y in Ring.principal_ideal[of R], assumption+,\n         frule_tac A = \"R \\<diamondsuit>\\<^sub>p y\" and H = Q and a = \"(-\\<^sub>a\\<^bsub>R\\<^esub> r) \\<cdot>\\<^sub>r\\<^bsub>R\\<^esub> y\" and\n         h = \"f j\" in sc_linear_span, assumption+, simp add:Rxa_def,\n         blast,\n         simp add:Pi_def)\n  apply (frule_tac c = \"(r \\<cdot>\\<^sub>r\\<^bsub>R\\<^esub> x) \\<cdot>\\<^sub>s f j\" and A = \"linear_span R M (R \\<diamondsuit>\\<^sub>p x) Q\" \n         and B = P in subsetD, assumption+) apply (\n         frule_tac c = \"((-\\<^sub>a\\<^bsub>R\\<^esub> r) \\<cdot>\\<^sub>r\\<^bsub>R\\<^esub> y) \\<cdot>\\<^sub>s f j\" and \n         A = \"linear_span R M (R \\<diamondsuit>\\<^sub>p y) Q\" and B = P in subsetD, assumption+)\n  apply (rule submodule_pOp_closed, assumption+)\n\n  apply ((rule ballI)+,\n         thin_tac \"\\<zero>\\<^bsub>R\\<^esub> \\<in> P \\<^bsub>R\\<ddagger>M\\<^esub> Q\",\n         simp add:quotient_of_submodules_def, erule conjE)\n  apply (simp add:Ring.ring_tOp_closed)\n  apply (rule subsetI)\n  apply (frule submodule_inc_0[of Q],\n         simp add:linear_span_def nonempty)\n  apply (erule exE, (erule bexE)+)\n  apply (rule_tac c = xa and A = \"{xa. \\<exists>n. \\<exists>f\\<in>{j. j \\<le> n} \\<rightarrow> Q.\n                \\<exists>s\\<in>{j. j \\<le> n} \\<rightarrow> R \\<diamondsuit>\\<^sub>p x. xa = l_comb R M n s f}\" in\n          subsetD[of _ P], assumption+,\n          thin_tac \"{xa. \\<exists>n. \\<exists>f\\<in>{j. j \\<le> n} \\<rightarrow> Q.\n                \\<exists>s\\<in>{j. j \\<le> n} \\<rightarrow> R \\<diamondsuit>\\<^sub>p x. xa = l_comb R M n s f} \\<subseteq> P\")\n  apply simp\n  apply (frule_tac a = r and b = x in Ring.Rxa_mult_smaller[of R], assumption+)\n  apply (frule_tac f = s and A = \"{j. j \\<le> n}\" and B = \"R \\<diamondsuit>\\<^sub>p (r \\<cdot>\\<^sub>r\\<^bsub>R\\<^esub> x)\" and\n          ?B1.0 = \"R \\<diamondsuit>\\<^sub>p x\" in extend_fun, assumption+)\n  apply blast\ndone\n \nlemma (in Module) Ann_is_ideal:\"ideal R (Ann\\<^bsub>R\\<^esub> M)\"\napply (simp add:Annihilator_def)\napply (rule quotient_of_submodules_is_ideal)\napply (simp add:submodule_0)\napply (simp add:submodule_whole)\ndone\n\nlemma (in Module) linmap_im_of_lincombTr:\"\\<lbrakk>ideal R A; R module N; \n      f \\<in> mHom R M N; H \\<subseteq> carrier M\\<rbrakk> \\<Longrightarrow>  \n      s \\<in> {j. j \\<le> (n::nat)} \\<rightarrow> A \\<and> g \\<in> {j. j \\<le> n} \\<rightarrow> H \\<longrightarrow>\n      f (l_comb R M n s g) = l_comb R N n s (cmp f g)\"\napply (induct_tac n)\n apply (rule impI) apply (erule conjE)\n apply (simp add:l_comb_def)\n apply (cut_tac m = \"g 0\" and f = f and a = \"s 0\" in mHom_lin [of N],\n        assumption+,\n        simp add:Pi_def subsetD, assumption,\n        cut_tac sc_Ring,\n        simp add:Pi_def Ring.ideal_subset, simp add:cmp_def)\n\napply (rule impI, erule conjE)\n apply (frule_tac f = s in func_pre,\n        frule_tac f = g in func_pre, simp)\n apply (simp add:l_comb_def)\n apply (subst mHom_add[of N f], assumption+)\n apply (rule nsum_mem,\n        rule allI, rule impI, rule sc_mem,\n        cut_tac sc_Ring,\n        simp add:Pi_def Ring.ideal_subset,\n        simp add:Pi_def subsetD)\n apply (rule sc_mem,\n         cut_tac sc_Ring,\n        simp add:Pi_def Ring.ideal_subset,\n        simp add:Pi_def subsetD, simp,\n        frule_tac x = \"Suc n\" and A = \"{j. j \\<le> Suc n}\" and f = s and \n                  B = A in funcset_mem, simp,\n        cut_tac sc_Ring,\n        frule_tac h = \"s (Suc n)\" in Ring.ideal_subset[of R A], assumption+,\n        frule_tac x = \"Suc n\" and A = \"{j. j \\<le> Suc n}\" and f = g and \n                  B = H in funcset_mem, simp,\n        frule_tac c = \"g (Suc n)\" in subsetD[of H \"carrier M\"], assumption+)\n apply (simp add:mHom_lin cmp_def)\ndone\n \nlemma (in Module) linmap_im_lincomb:\"\\<lbrakk>ideal R A; R module N; f \\<in> mHom R M N; \n      H \\<subseteq> carrier M; s \\<in> {j. j \\<le> (n::nat)} \\<rightarrow> A; g \\<in> {j. j \\<le> n} \\<rightarrow> H \\<rbrakk> \\<Longrightarrow> \n      f (l_comb R M n s g) = l_comb R N n s (cmp f g)\"\napply (simp add:linmap_im_of_lincombTr)\ndone\n\nlemma (in Module) linmap_im_linspan:\"\\<lbrakk>ideal R A; R module N; f \\<in> mHom R M N; \n       H \\<subseteq> carrier M; s \\<in> {j. j \\<le> (n::nat)} \\<rightarrow> A; g \\<in> {j. j \\<le> n} \\<rightarrow> H \\<rbrakk> \\<Longrightarrow> \n            f (l_comb R M n s g) \\<in> linear_span R N A (f ` H)\"\napply (frule l_comb_mem_linear_span[of A H s n g], assumption+) \n apply (simp add:linmap_im_lincomb)\n apply (rule Module.l_comb_mem_linear_span[of N R A \"f ` H\" s n \"cmp f g\"],\n        assumption+,\n        rule subsetI,\n        simp add:image_def, erule bexE, simp,\n        frule_tac c = xa in subsetD[of H \"carrier M\"], assumption+,\n        simp add:mHom_mem[of N f], assumption+)\n apply (rule Pi_I, simp add:cmp_def)\n apply (frule_tac f = g and A = \"{j. j \\<le> n}\" and B = H and x = x in \n        funcset_mem, simp, simp add:image_def) \n apply blast\ndone\n\nlemma (in Module) linmap_im_linspan1:\"\\<lbrakk>ideal R A; R module N; f \\<in> mHom R M N; \n      H \\<subseteq> carrier M; h \\<in> linear_span R M A H\\<rbrakk> \\<Longrightarrow> \n                              f h \\<in> linear_span R N A (f ` H)\"\napply (simp add:linear_span_def [of \"R\" \"M\"])\n apply (case_tac \"H = {}\", simp add:linear_span_def)\n apply (simp add:mHom_0, simp)\napply (erule exE, (erule bexE)+)\n apply (simp add:linmap_im_linspan)\ndone\n\n(*\nsection \"A module over two rings\"\n\nrecord ('a, 'r, 's) bModule = \"'a aGroup\" +\n  sc_l  :: \"'r \\<Rightarrow> 'a \\<Rightarrow> 'a\"    (infixl \"\\<cdot>\\<^bsub>sl\\<^esub>\\<index>\" 70)\n  sc_r  :: \"'a \\<Rightarrow> 's \\<Rightarrow> 'a\"    (infixl \"\\<cdot>\\<^bsub>sr\\<^esub>\\<index>\" 70)\n\nlocale bModule = aGroup M +\n  fixes R (structure)\n  fixes S (structure)\n  assumes  scl_Ring: \"Ring R\"\n  and      scr_Ring: \"Ring S\" \n  and  scl_closed :\n      \"\\<lbrakk> a \\<in> carrier R; m \\<in> carrier M\\<rbrakk> \\<Longrightarrow> a \\<cdot>\\<^bsub>sl\\<^esub> m \\<in> carrier M\"\n  and scr_closed :\n      \"\\<lbrakk> b \\<in> carrier S; m \\<in> carrier M\\<rbrakk> \\<Longrightarrow> m \\<cdot>\\<^bsub>sr\\<^esub> b \\<in> carrier M\" \n  and scl_l_distr:\n      \"\\<lbrakk>a \\<in> carrier R; b \\<in> carrier R; m \\<in> carrier M\\<rbrakk> \\<Longrightarrow>\n       (a \\<plusminus>\\<^bsub>R\\<^esub> b) \\<cdot>\\<^bsub>sl\\<^esub> m = a \\<cdot>\\<^bsub>sl\\<^esub> m \\<plusminus> b \\<cdot>\\<^bsub>sl\\<^esub> m\"\n  and scr_l_distr:\n      \"\\<lbrakk>a \\<in> carrier S; m \\<in> carrier M; n \\<in> carrier M \\<rbrakk> \\<Longrightarrow>\n        (m \\<plusminus> n) \\<cdot>\\<^bsub>sr\\<^esub> a = m \\<cdot>\\<^bsub>sr\\<^esub> a \\<plusminus>  n \\<cdot>\\<^bsub>sr\\<^esub> a\"\n  and scl_r_distr:\n      \"\\<lbrakk> a \\<in> carrier R; m \\<in> carrier M; n \\<in> carrier M \\<rbrakk> \\<Longrightarrow>\n      a \\<cdot>\\<^bsub>sl\\<^esub> (m \\<plusminus> n) = a \\<cdot>\\<^bsub>sl\\<^esub> m \\<plusminus> a \\<cdot>\\<^bsub>sl\\<^esub> n\"\n  and scr_r_distr:\n        \"\\<lbrakk>a \\<in> carrier S; b \\<in> carrier S; m \\<in> carrier M\\<rbrakk> \\<Longrightarrow>\n          m \\<cdot>\\<^bsub>sr\\<^esub> (a \\<plusminus>\\<^bsub>S\\<^esub> b) = m \\<cdot>\\<^bsub>sr\\<^esub> a \\<plusminus>  m \\<cdot>\\<^bsub>sr\\<^esub> b\"\n  and scl_assoc:\n      \"\\<lbrakk> a \\<in> carrier R; b \\<in> carrier R; m \\<in> carrier M \\<rbrakk> \\<Longrightarrow>\n      (a \\<cdot>\\<^sub>r\\<^bsub>R\\<^esub> b) \\<cdot>\\<^bsub>sl\\<^esub> m = a \\<cdot>\\<^bsub>sl\\<^esub> (b \\<cdot>\\<^bsub>sl\\<^esub> m)\"\n  and scr_assoc:\n      \"\\<lbrakk>a \\<in> carrier S; b \\<in> carrier S; m \\<in> carrier M \\<rbrakk> \\<Longrightarrow>\n       m \\<cdot>\\<^bsub>sr\\<^esub> (a \\<cdot>\\<^sub>r\\<^bsub>S\\<^esub> b)  =  (m \\<cdot>\\<^bsub>sr\\<^esub> a) \\<cdot>\\<^bsub>sr\\<^esub> b\"\n  and scl_one:\n      \"m \\<in> carrier M \\<Longrightarrow> (1\\<^sub>r\\<^bsub>R\\<^esub>) \\<cdot>\\<^bsub>sl\\<^esub> m = m\" \n  and scr_one:\n       \"m \\<in> carrier M \\<Longrightarrow> m \\<cdot>\\<^bsub>sr\\<^esub> (1\\<^sub>r\\<^bsub>S\\<^esub>) = m\" \n\ndefinition lModule :: \"('a, 'r, 's, 'more) bModule_scheme \\<Rightarrow> ('a, 'r) Module\" where\n       (\"(_\\<^sub>l)\" [1000]999)\n  \"M\\<^sub>l == \\<lparr>carrier = carrier M, pop = pop M, mop = mop M, \n    zero = zero M, sprod = sc_l M \\<rparr>\"\n\ndefinition scr_re :: \"('a, 'b, 'c, 'more) bModule_scheme \\<Rightarrow> 'c \\<Rightarrow> 'a \\<Rightarrow> 'a\" where \n                  \n \"scr_re M r m == sc_r M m r\"\n\ndefinition rModule :: \"('a, 'r, 's, 'more) bModule_scheme \\<Rightarrow> ('a, 's) Module\" where\n        (\"(_\\<^sub>r)\" [1000]999) \n  \"M\\<^sub>r == \\<lparr>carrier = carrier M, pop = pop M, mop = mop M, \n    zero = zero M, sprod = scr_re M \\<rparr>\"\n\nlemma (in bModule) bmodule_is_ag:\"aGroup M\"  \napply assumption\ndone\n\nlemma (in bModule) lModule_is_Module:\"R module M\\<^sub>l\"\napply (subgoal_tac \"aGroup M\")\napply (rule Module.intro)\n apply (rule aGroup.intro)\n apply (simp add:lModule_def, simp add:aGroup.pop_closed[of M])\n apply (simp add:lModule_def, simp add:aGroup.ag_pOp_assoc)\n apply (simp add:lModule_def, simp add:aGroup.ag_pOp_commute)\n apply (simp add:lModule_def, rule mop_closed)\n apply (simp add:lModule_def, rule l_m, assumption+)\n apply (simp add:lModule_def, rule ex_zero)\n apply (simp add:lModule_def, rule l_zero, assumption)\napply (rule Module_axioms.intro)\n apply (simp add:scl_Ring)\n apply (simp add:lModule_def, rule  scl_closed, assumption+)\n apply (simp add:lModule_def, rule  scl_l_distr, assumption+)\n apply (simp add:lModule_def, rule  scl_r_distr, assumption+)\n apply (simp add:lModule_def, rule  scl_assoc, assumption+)\n apply (simp add:lModule_def, rule scl_one, assumption+)\ndone\n\n\nlemma (in bModule) rModule_is_Module:\"S module M\\<^sub>r\"\napply (subgoal_tac \"aGroup M\")\napply (rule Module.intro)\n apply (rule aGroup.intro)\n apply (simp add:rModule_def, simp add:aGroup.pop_closed[of M])\n apply (simp add:rModule_def, simp add:aGroup.ag_pOp_assoc)\n apply (simp add:rModule_def, simp add:aGroup.ag_pOp_commute)\n apply (simp add:rModule_def, rule mop_closed)\n apply (simp add:rModule_def, rule l_m, assumption+)\n apply (simp add:rModule_def, rule ex_zero)\n apply (simp add:rModule_def, rule l_zero, assumption)\napply (rule Module_axioms.intro,\n       simp add:scr_Ring)\napply (simp add:rModule_def, simp add:scr_re_def scr_closed)\napply (simp add:rModule_def, simp add:scr_re_def, simp add:scr_r_distr)\napply (simp add:rModule_def, simp add:scr_re_def, rule scr_l_distr, \n        assumption+)\napply (simp add:rModule_def scr_re_def,\n       subst scr_assoc[THEN sym], assumption+,\n       cut_tac scr_Ring,\n       simp add:Ring.ring_tOp_commute)\napply (simp add:rModule_def scr_re_def) \napply (cut_tac m = m in scr_one, simp)\napply assumption+\ndone\n\nlemma (in Module) sprodr_welldefTr1:\"\\<lbrakk>ideal R A; A \\<subseteq> Ann\\<^bsub>R\\<^esub> M; a \\<in> A;\n       m \\<in> carrier M\\<rbrakk>  \\<Longrightarrow> a \\<cdot>\\<^sub>s m = \\<zero>\" \napply (simp add:Annihilator_def quotient_of_submodules_def)\napply (frule subsetD, assumption+)\n apply (simp add:CollectI, erule conjE, \n        thin_tac \"A \\<subseteq> {u \\<in> carrier R.\n                   linear_span R M (R \\<diamondsuit>\\<^sub>p u) (carrier M) \\<subseteq> {\\<zero>}}\")\n apply (cut_tac sc_Ring,\n        cut_tac a = a and A = \"Rxa R a\" in \n                         sc_linear_span[of  _ \"carrier M\" _ \"m\"],\n                simp add:Ring.principal_ideal, simp, \n                simp add:Ring.a_in_principal, assumption)\n apply (frule subsetD[of \"linear_span R M (R \\<diamondsuit>\\<^sub>p a) (carrier M)\" \"{\\<zero>}\"\n                             \"a \\<cdot>\\<^sub>s m\"], assumption)\n apply simp\ndone\n\nlemma (in Module) sprodr_welldefTr2:\"\\<lbrakk>ideal R A; A \\<subseteq> Ann\\<^bsub>R\\<^esub> M; a \\<in> carrier R; \n      x \\<in> a \\<uplus>\\<^bsub>R\\<^esub> A; m \\<in> carrier M\\<rbrakk>  \\<Longrightarrow> a \\<cdot>\\<^sub>s m = x \\<cdot>\\<^sub>s m\"\napply (cut_tac sc_Ring,\n       frule Ring.mem_ar_coset1 [of R A a x], assumption+, erule bexE,\n       rotate_tac -1, frule sym, thin_tac \"h \\<plusminus>\\<^bsub>R\\<^esub> a = x\", simp)\napply (subst sc_l_distr)\n apply (simp add:Ring.ideal_subset, assumption+)\napply (simp add:sprodr_welldefTr1)\napply (frule sc_mem [of a m], assumption+)\napply (simp add:ag_l_zero)\ndone\n\ndefinition cos_scr :: \"[('r, 'm) Ring_scheme, 'r set, ('a, 'r, 'm1) Module_scheme] \\<Rightarrow>\n               'a \\<Rightarrow> 'r set \\<Rightarrow> 'a\" where\n  \"cos_scr R A M == \\<lambda>m. \\<lambda>X. (SOME x. x \\<in> X) \\<cdot>\\<^sub>s\\<^bsub>M\\<^esub> m\"\n\nlemma (in Module) cos_scr_welldef:\"\\<lbrakk>ideal R A; A \\<subseteq> Ann\\<^bsub>R\\<^esub> M; a \\<in> carrier R; \n       X = a \\<uplus>\\<^bsub>R\\<^esub> A; m \\<in> carrier M\\<rbrakk>  \\<Longrightarrow> cos_scr R A M m X = a \\<cdot>\\<^sub>s m\" \napply (cut_tac sc_Ring,\n       frule Ring.a_in_ar_coset [of R A a], assumption+)\n apply (simp add:cos_scr_def,\n        rule sprodr_welldefTr2[THEN sym], assumption+) \n prefer 2 apply simp\napply (rule someI2_ex, blast, assumption)\ndone\n\ndefinition r_qr_bmod :: \"[('r, 'm) Ring_scheme, 'r set, ('a, 'r, 'm1) Module_scheme] \\<Rightarrow> \n    ('a, 'r, 'r set) bModule\" where \n \"r_qr_bmod R A M == \\<lparr>carrier = carrier M, pop = pop M, mop = mop M, \n  zero = zero M, sc_l = sprod M, sc_r = cos_scr R A M \\<rparr>\" *)\n (* Remark. A should be an ideal contained in Ann\\<^sub>R M. *)\n\ndefinition\n  faithful :: \"[('r, 'm) Ring_scheme, ('a, 'r, 'm1) Module_scheme]\n                             \\<Rightarrow> bool\" where\n  \"faithful R M \\<longleftrightarrow> Ann\\<^bsub>R\\<^esub> M = {\\<zero>\\<^bsub>R\\<^esub>}\"\n\nsection \"nsum and Generators\"\n\ndefinition\n  generator :: \"[('r, 'm) Ring_scheme, ('a, 'r, 'm1) Module_scheme,\n               'a set] \\<Rightarrow> bool\" where\n \"generator R M H == H \\<subseteq> carrier M \\<and> \n                      linear_span R M (carrier R) H = carrier M\"\n\ndefinition\n  finite_generator :: \"[('r, 'm) Ring_scheme, ('a, 'r, 'm1) Module_scheme,\n               'a set] \\<Rightarrow> bool\" where\n  \"finite_generator R M H \\<longleftrightarrow> finite H \\<and> generator R M H\"\n\ndefinition\n  fGOver :: \"[('a, 'r, 'm1) Module_scheme, ('r, 'm) Ring_scheme]  \\<Rightarrow>  bool\"\n              (*(infixl 70)*)  where\n  \"fGOver M R \\<longleftrightarrow> (\\<exists>H. finite_generator R M H)\"\n\nabbreviation\n  FGENOVER  (infixl \"fgover\" 70) where\n  \"M fgover R == fGOver M R\"\n\nlemma (in Module) h_in_linear_span:\"\\<lbrakk>H \\<subseteq> carrier M; h \\<in> H\\<rbrakk> \\<Longrightarrow>\n                                   h \\<in> linear_span R M (carrier R) H\"\napply (subst sprod_one [THEN sym, of h])\n apply (simp add:subsetD)\n apply (cut_tac sc_Ring)\n apply (frule Ring.ring_one)\n apply (rule sc_linear_span [of \"carrier R\" \"H\" \"1\\<^sub>r\\<^bsub>R\\<^esub>\" \"h\"])\n apply (simp add:Ring.whole_ideal) apply assumption+\ndone                                                   \n\nlemma (in Module) generator_sub_carrier:\"generator R M H \\<Longrightarrow>\n                                              H \\<subseteq> carrier M\" \napply (simp add:generator_def)\ndone \n\nlemma (in Module) lin_span_sub_carrier:\"\\<lbrakk>ideal R A; \n       H \\<subseteq> carrier M\\<rbrakk> \\<Longrightarrow> linear_span R M A H \\<subseteq> carrier M\"\napply (cut_tac sc_Ring)\napply (rule subsetI)\n apply (simp add:linear_span_def)\n apply (case_tac \"H = {}\") apply simp\n apply (simp add:module_inc_zero) \napply simp\napply (erule exE, (erule bexE)+, simp,\n       thin_tac \"x = l_comb R M n s f\")\napply (simp add:l_comb_def) \napply (rule_tac n = n in nsum_mem) \n apply (rule allI, rule impI)\n apply (rule sc_mem)\n apply (simp add:Pi_def Ring.ideal_subset)\n apply (simp add:Pi_def subsetD)\ndone\n\nlemma (in Module) lin_span_coeff_mono:\"\\<lbrakk>ideal R A; H \\<subseteq> carrier M\\<rbrakk>\\<Longrightarrow>  \n                        linear_span R M A H \\<subseteq> linear_span R M (carrier R) H\"\napply (cut_tac sc_Ring)\napply (rule subsetI)\n apply (simp add:linear_span_def)\n apply (case_tac \"H = {}\") apply simp apply simp\n apply (erule exE, (erule bexE)+)\n apply (frule Ring.ideal_subset1 [of R A], assumption+)\napply (frule_tac  f = s in extend_fun, assumption+) \n apply blast\ndone\n\nlemma (in Module) l_span_sum_closedTr:\"\\<lbrakk>ideal R A; H \\<subseteq> carrier M\\<rbrakk>\\<Longrightarrow> \n   \\<forall>s. \\<forall>f. s\\<in>{j. j \\<le> (n::nat)} \\<rightarrow> A \\<and> \n   f \\<in> {j. j \\<le> n} \\<rightarrow> linear_span R M A H \\<longrightarrow>\n   (nsum M (\\<lambda>j. s j \\<cdot>\\<^sub>s (f j)) n \\<in> linear_span R M A H)\"\napply (cut_tac sc_Ring)\napply (induct_tac n)\n apply ((rule allI)+, rule impI, simp) \n apply (erule conjE)\n apply (rule linear_span_sc_closed, assumption+)\n apply (simp add:Pi_def Ring.ideal_subset,\n        simp add:Pi_def)\n\napply ((rule allI)+, rule impI, erule conjE)\n apply (frule func_pre [of _ _ \"A\"],\n        frule func_pre [of _ _ \"linear_span R M A H\"])\n apply (drule_tac x = s in spec,\n        drule_tac x = f in spec)\n\n apply simp\n apply (rule linear_span_pOp_closed, assumption+)\n apply (rule linear_span_sc_closed, assumption+,\n        simp add:Pi_def Ring.ideal_subset,\n        simp add:Pi_def subsetD)\ndone\n\nlemma (in Module) l_span_closed:\"\\<lbrakk>ideal R A; H \\<subseteq> carrier M; \n s \\<in> {j. j \\<le> (n::nat)} \\<rightarrow> A;  f \\<in> {j. j \\<le> n} \\<rightarrow> linear_span R M A H \\<rbrakk> \\<Longrightarrow>\n l_comb R M n s f \\<in> linear_span R M A H\"\napply (simp add:l_comb_def)\napply (simp add: l_span_sum_closedTr)\ndone \n\nlemma (in Module) l_span_closed1:\"\\<lbrakk>H \\<subseteq> carrier M; \n      s \\<in> {j. j \\<le> (n::nat)} \\<rightarrow> carrier R;  \n      f \\<in> {j. j \\<le> n} \\<rightarrow> linear_span R M (carrier R) H \\<rbrakk> \\<Longrightarrow>\n      \\<Sigma>\\<^sub>e M (\\<lambda>j.  s j \\<cdot>\\<^sub>s (f j)) n \\<in> linear_span R M (carrier R) H\"\napply (cut_tac sc_Ring,\n       frule Ring.whole_ideal [of \"R\"])\napply (frule l_span_sum_closedTr[of \"carrier R\" H n], assumption+)\napply (drule_tac x = s in spec,\n       drule_tac x = f in spec,\n       simp)\ndone\n\nlemma (in Module) l_span_closed2Tr0:\"\\<lbrakk>ideal R A; H \\<subseteq> carrier M; Ring R; s \\<in> A;\n     f \\<in> linear_span R M (carrier R) H \\<rbrakk> \\<Longrightarrow> s \\<cdot>\\<^sub>s f \\<in> linear_span R M A H\"\napply (cut_tac sc_Ring)\napply (case_tac \"H = {}\")\n apply (simp add:linear_span_def)\n apply (rule sc_a_0,\n        cut_tac sc_Ring,\n        simp add:Pi_def Ring.ideal_subset) \n\n apply (simp add:linear_span_def) \n apply (erule exE, (erule bexE)+, simp,\n        thin_tac \"f = l_comb R M n sa fa\")\n apply (frule Ring.whole_ideal[of R])\n apply (frule_tac h = s in Ring.ideal_subset[of R A], assumption+)\n apply (frule_tac s = sa and g = f in l_comb_sc1[of \"carrier R\" H s],\n        assumption+, simp add:l_comb_def,\n        thin_tac \"s \\<cdot>\\<^sub>s \\<Sigma>\\<^sub>e M (\\<lambda>k. sa k \\<cdot>\\<^sub>s f k) n = \n                                    \\<Sigma>\\<^sub>e M (\\<lambda>k. (s \\<cdot>\\<^sub>r\\<^bsub>R\\<^esub> sa k) \\<cdot>\\<^sub>s f k) n\")\n apply (cut_tac n = n and f = \"\\<lambda>j. (s \\<cdot>\\<^sub>r\\<^bsub>R\\<^esub> sa j) \\<cdot>\\<^sub>s f j\" and \n        g = \"\\<lambda>j. ((\\<lambda>x\\<in>{j. j \\<le> n}. (s \\<cdot>\\<^sub>r\\<^bsub>R\\<^esub> sa x)) j) \\<cdot>\\<^sub>s f j\" in nsum_eq)\n        apply (rule allI, rule impI, rule sc_mem,\n               rule Ring.ring_tOp_closed, assumption+,\n               simp add:Pi_def,\n               simp add:Pi_def subsetD)\n        apply (rule allI, rule impI, simp,\n                rule sc_mem,\n               rule Ring.ring_tOp_closed, assumption+,\n               simp add:Pi_def,\n               simp add:Pi_def subsetD)\n        apply (rule allI, rule impI, simp)\n apply (subgoal_tac \"(\\<lambda>x\\<in>{j. j \\<le> n}. (s \\<cdot>\\<^sub>r\\<^bsub>R\\<^esub> sa x)) \\<in> {j. j \\<le> n} \\<rightarrow> A\",\n        blast,\n        thin_tac \"\\<Sigma>\\<^sub>e M (\\<lambda>j. (s \\<cdot>\\<^sub>r\\<^bsub>R\\<^esub> sa j) \\<cdot>\\<^sub>s f j) n =\n        \\<Sigma>\\<^sub>e M (\\<lambda>j. (\\<lambda>x\\<in>{j. j \\<le> n}. s \\<cdot>\\<^sub>r\\<^bsub>R\\<^esub> sa x) j \\<cdot>\\<^sub>s f j) n\")\n        apply (rule Pi_I, simp,\n               rule_tac x = s and r = \"sa x\" in \n               Ring.ideal_ring_multiple1[of R A], assumption+)\n               apply (simp add:Pi_def)\ndone\n\nlemma (in Module) l_span_closed2Tr:\"\\<lbrakk>ideal R A; H \\<subseteq> carrier M\\<rbrakk> \\<Longrightarrow> \n       s \\<in> {j. j \\<le> (n::nat)} \\<rightarrow> A \\<and> \n       f \\<in> {j. j \\<le> n} \\<rightarrow> linear_span R M (carrier R) H \\<longrightarrow>\n            l_comb R M n s f \\<in> linear_span R M A H\"\napply (cut_tac sc_Ring)\napply (induct_tac n)\napply (rule impI, (erule conjE)+)\napply (case_tac \"H = {}\")\n apply (simp add:linear_span_def)\n apply (simp add:l_comb_def)\n apply (rule sc_a_0,\n        cut_tac sc_Ring,\n        simp add:Pi_def Ring.ideal_subset) \n apply (simp add:l_comb_def l_span_closed2Tr0)\n\napply (rule impI, erule conjE,\n       frule func_pre[of s], frule func_pre[of f], simp)\n apply (simp add:l_comb_def) \n apply (rule linear_span_pOp_closed, assumption+) \n apply (rule_tac s = \"s (Suc n)\" and f = \"f (Suc n)\" in \n                 l_span_closed2Tr0[of A H], assumption+,\n       (simp add:Pi_def)+)\ndone\n\nlemma (in Module) l_span_closed2:\"\\<lbrakk>ideal R A; H \\<subseteq> carrier M;\n       s \\<in> {j. j \\<le> (n::nat)} \\<rightarrow> A ; \n       f \\<in> {j. j \\<le> n} \\<rightarrow> linear_span R M (carrier R) H\\<rbrakk> \\<Longrightarrow>\n       l_comb R M n s f \\<in> linear_span R M A H\"\napply (simp add:l_span_closed2Tr)\ndone\n\nlemma (in Module) l_span_l_span:\"H \\<subseteq> carrier M \\<Longrightarrow>\n       linear_span R M (carrier R) (linear_span R M (carrier R) H) =\n                                          linear_span R M (carrier R) H\"\napply (cut_tac sc_Ring, frule Ring.whole_ideal[of R])\napply (rule equalityI)\n apply (rule subsetI)\n apply (frule linear_span_inc_0[of \"carrier R\" H], assumption+,\n        frule nonempty[of _ \"linear_span R M (carrier R) H\"],\n        simp add:linear_span_def[of R M \"carrier R\" \n                            \"linear_span R M (carrier R) H\"],\n        erule exE, (erule bexE)+, simp)\n apply (frule_tac s = s and n = n and f = f in l_span_closed2[of \"carrier R\"],\n        assumption+,\n        frule lin_span_sub_carrier[of \"carrier R\" \"H\"], assumption+,\n        rule subsetI)\n apply (rule_tac h = x in h_in_linear_span[of \"linear_span R M (carrier R) H\"],\n        assumption+)\ndone\n\nlemma (in Module) l_spanA_l_span:\"\\<lbrakk>ideal R A; H \\<subseteq> carrier M\\<rbrakk> \\<Longrightarrow>\n       linear_span R M A (linear_span R M (carrier R) H) =\n                                          linear_span R M A H\"\napply (cut_tac sc_Ring, frule Ring.whole_ideal[of R])\napply (rule equalityI)\n apply (rule subsetI)\n apply (frule linear_span_inc_0[of \"carrier R\" H], assumption+,\n        frule nonempty[of _ \"linear_span R M (carrier R) H\"],\n        simp add:linear_span_def[of R M A \n                            \"linear_span R M (carrier R) H\"],\n        erule exE, (erule bexE)+, simp)\n apply (frule_tac s = s and n = n and f = f in l_span_closed2[of A],\n        assumption+)\n apply (frule l_span_cont_H[of H])\n apply (frule l_span_gen_mono[of \"H\" \"linear_span R M (carrier R) H\" A],\n        simp add:lin_span_sub_carrier[of \"carrier R\" H], assumption)\n apply assumption\ndone \n\nlemma (in Module) l_span_zero:\"ideal R A \\<Longrightarrow> linear_span R M A {\\<zero>} = {\\<zero>}\"\napply (cut_tac sc_Ring)\napply (rule equalityI)\n apply (rule subsetI,\n        frule_tac x = x in mem_single_l_span1[of A \\<zero>],\n        simp add:ag_inc_zero, assumption,\n        erule bexE, frule_tac h = a in Ring.ideal_subset[of R A], assumption+,\n        simp add:sc_a_0)\n apply (rule subsetI, simp, rule linear_span_inc_0, assumption,\n        rule subsetI, simp add:ag_inc_zero)\ndone\n\nlemma (in Module) l_span_closed3:\"\\<lbrakk>ideal R A; generator R M H;\n       A \\<odot>\\<^bsub>R\\<^esub> M = carrier M\\<rbrakk> \\<Longrightarrow> linear_span R M A H = carrier M\"\napply (cut_tac sc_Ring)\n\napply (rule equalityI) \n apply (cut_tac linear_span_subModule[of A H],\n        simp add:submodule_subset, assumption,\n        simp add:generator_def)\n\napply (rule subsetI) \n apply (simp add:generator_def)\n apply (erule conjE) \n apply (case_tac \"H = {}\", simp, simp add:linear_span_def)\napply (simp add:smodule_ideal_coeff_def)\n apply (rotate_tac -2, frule sym,\n        thin_tac \"linear_span R M (carrier R) H = carrier M\")\n apply simp \n apply (frule sym, \n        thin_tac \"linear_span R M A (linear_span R M (carrier R) H) =\n                  linear_span R M (carrier R) H\")\n apply (frule_tac a = x in eq_set_inc[of _ \"linear_span R M (carrier R) H\"\n        \"linear_span R M A (linear_span R M (carrier R) H)\"], assumption+,\n        thin_tac \"x \\<in> linear_span R M (carrier R) H\",\n        thin_tac \"linear_span R M (carrier R) H =\n         linear_span R M A (linear_span R M (carrier R) H)\")\n apply (frule sym, \n        thin_tac \"carrier M = linear_span R M (carrier R) H\",\n        frule subset_trans[of H \"linear_span R M (carrier R) H\" \"carrier M\"],\n        simp,\n        thin_tac \"linear_span R M (carrier R) H = carrier M\")\n apply (frule Ring.whole_ideal,\n        frule linear_span_inc_0 [of \"carrier R\" \"H\"], assumption+,\n        frule nonempty [of \"\\<zero>\" \"linear_span R M (carrier R) H\"])\napply (simp add:linear_span_def [of _ _ _ \"linear_span R M (carrier R) H\"])\n apply (erule exE, (erule bexE)+)\napply (simp add:l_span_closed2) \ndone\n\nlemma (in Module) generator_generator:\"\\<lbrakk>generator R M H; H1 \\<subseteq> carrier M; \n           H \\<subseteq> linear_span R M (carrier R) H1\\<rbrakk>  \\<Longrightarrow>  generator R M H1\"\napply (cut_tac sc_Ring,\n       frule Ring.whole_ideal[of R],\n       frule linear_span_subModule[of \"carrier R\" H1], assumption,\n       frule l_span_sub_submodule[of \"carrier R\" \n            \"linear_span R M (carrier R) H1\" H], assumption+)\napply (simp add:generator_def)\napply (rule equalityI,\n       simp add:submodule_subset, assumption)\ndone\n\nlemma (in Module) generator_elimTr:\n\"f \\<in> {j. j \\<le> (n::nat)} \\<rightarrow> carrier M \\<and> generator R M (f ` {j. j \\<le> n}) \\<and> \n(\\<forall>i\\<in>nset (Suc 0) n. f i \\<in> \n   linear_span R M (carrier R) (f ` {j. j \\<le> (i - Suc 0)})) \\<longrightarrow> \n linear_span R M (carrier R) {f 0} = carrier M\"\napply (induct_tac n)\n apply (rule impI, (erule conjE)+)\n apply (simp add:nset_def generator_def)\n\napply (rule impI)\n apply (erule conjE)+\n apply (frule func_pre [of _ _ \"carrier M\"], simp)\n apply (subgoal_tac \"generator R M (f ` {j. j \\<le> n})\")\n apply (subgoal_tac \"\\<forall>i\\<in>nset (Suc 0) n.\n         f i \\<in> linear_span R M (carrier R) (f ` {j. j \\<le> (i - Suc 0)})\")\n apply simp\n apply (thin_tac \"generator R M (f ` {j. j \\<le> n}) \\<and>\n     (\\<forall>i\\<in>nset (Suc 0) n. f i \\<in> linear_span R M (carrier R) \n              (f ` {j. j \\<le> i - Suc 0})) \\<longrightarrow>\n         linear_span R M (carrier R) {f 0} = carrier M\")\n apply (rule ballI)\n apply (frule_tac x = i in bspec, simp add:nset_def, assumption)\n apply (thin_tac \"generator R M (f ` {j. j \\<le> n}) \\<and>\n         (\\<forall>i\\<in>nset (Suc 0) n.\n         f i \\<in> linear_span R M (carrier R) (f ` {j. j \\<le> i - Suc 0})) \\<longrightarrow>\n         linear_span R M (carrier R) {f 0} = carrier M\")\n apply (frule_tac x = \"Suc n\" in bspec, simp add:nset_def,\n        thin_tac \"\\<forall>i\\<in>nset (Suc 0) (Suc n).\n            f i \\<in> linear_span R M (carrier R) (f ` {j. j \\<le> i - Suc 0})\",\n        simp)\n apply (subgoal_tac \"f ` {j. j \\<le> Suc n} \\<subseteq> linear_span R M (carrier R) (f ` {j. j \\<le> n})\")\n apply (frule_tac H = \"f ` {j. j \\<le> Suc n}\" and ?H1.0 = \"f ` {j. j \\<le> n}\"\n        in generator_generator,\n        rule subsetI, simp add:image_def, erule exE, erule conjE, simp,\n        simp add:Pi_def)\n apply assumption+\n apply (rule subsetI, simp add:image_def, erule exE, erule conjE)\n apply (case_tac \"xa = Suc n\", simp)\n apply (frule_tac m = xa and n = \"Suc n\" in noteq_le_less, assumption,\n        thin_tac \"xa \\<le> Suc n\",\n        frule_tac x = xa and n = \"Suc n\" in less_le_diff, \n        thin_tac \"xa < Suc n\", simp)\n apply (rule_tac H = \"{y. \\<exists>x\\<le>n. y = f x}\" and h = \"f xa\" in \n                       h_in_linear_span,\n        rule subsetI, simp add:image_def, erule exE, erule conjE,\n        simp add:Pi_def)\n apply (simp, blast)\ndone\n\nlemma (in Module) generator_generator_elim:\n \"\\<lbrakk>f \\<in> {j. j \\<le> (n::nat)} \\<rightarrow> carrier M; generator R M (f ` {j. j \\<le> n}); \n  (\\<forall>i\\<in>nset (Suc 0) n. f i \\<in> linear_span R M (carrier R) \n     (f ` {j. j \\<le> (i - Suc 0)}))\\<rbrakk> \\<Longrightarrow> \n   linear_span R M (carrier R) {f 0} = carrier M\"\napply (simp add:generator_elimTr [of f n])\ndone\n\nlemma (in Module) surjec_generator:\"\\<lbrakk>R module N; f \\<in> mHom R M N;\n surjec\\<^bsub>M,N\\<^esub> f; generator R M H\\<rbrakk> \\<Longrightarrow> generator R N (f ` H)\"\napply (cut_tac sc_Ring, frule Ring.whole_ideal)\napply (simp add:generator_def, erule conjE)\n apply (simp add:surjec_def, (erule conjE)+)\n apply (simp add:aHom_def, (erule conjE)+)\n apply (simp add:image_sub [of \"f\" \"carrier M\" \"carrier N\" \"H\"])\n\napply (frule Module.lin_span_sub_carrier[of N R \"carrier R\" \"f ` H\"],\n       assumption,\n       simp add:image_sub [of \"f\" \"carrier M\" \"carrier N\" \"H\"])\napply (rule equalityI, assumption+)\n apply (rule subsetI)\n apply (simp add:surj_to_def,\n        thin_tac \"f \\<in> extensional (carrier M)\",\n        thin_tac \"\\<forall>a\\<in>carrier M. \\<forall>b\\<in>carrier M. f (a \\<plusminus> b) = f a \\<plusminus>\\<^bsub>N\\<^esub> f b\")\n apply (frule sym, rotate_tac 6, frule sym,\n        thin_tac \"f ` carrier M = carrier N\",\n        frule_tac a = x and A = \"carrier N\" and B = \"f ` carrier M\" in\n        eq_set_inc, assumption,\n        thin_tac \"carrier N = f ` carrier M\", \n        thin_tac \"carrier M = linear_span R M (carrier R) H\")\n apply (simp add:image_def[of f \"carrier M\"], erule bexE)\n apply (frule sym, thin_tac \"linear_span R M (carrier R) H = carrier M\",\n        frule_tac a = xa in eq_set_inc[of _ \"carrier M\" \n        \"linear_span R M (carrier R) H\"], assumption,\n        thin_tac \"carrier M = linear_span R M (carrier R) H\",\n        thin_tac \"linear_span R N (carrier R) (f ` H) \\<subseteq> carrier N\")\n\n apply (simp add:linear_span_def)\napply (case_tac \"H = {}\", simp) \n apply (simp add:mHom_0, simp,\n        erule exE, (erule bexE)+)\n apply (cut_tac sc_Ring, frule Ring.whole_ideal[of R],\n       frule_tac s = s and n = n and g = fa in \n       linmap_im_linspan[of \"carrier R\" N f H], assumption+,\n       rotate_tac -5, frule sym,\n       thin_tac \"xa = l_comb R M n s fa\", simp,\n       thin_tac \"l_comb R M n s fa = xa\")\n apply (simp add:linear_span_def)\ndone   \n\n\n\nlemma (in Module) similar_termTr:\"\\<lbrakk>ideal R A; a \\<in> A\\<rbrakk> \\<Longrightarrow>\n \\<forall>s. \\<forall>f. s \\<in> {j. j \\<le> (n::nat)} \\<rightarrow> A \\<and> \n         f \\<in> {j. j \\<le> n} \\<rightarrow> carrier M \\<and> \n         m \\<in> f ` {j. j \\<le> n} \\<longrightarrow>\n       (\\<exists>t\\<in>{j. j \\<le> n} \\<rightarrow> A. nsum M (\\<lambda>j. s j \\<cdot>\\<^sub>s (f j)) n \\<plusminus> a \\<cdot>\\<^sub>s m = \n           nsum M (\\<lambda>j. t j \\<cdot>\\<^sub>s (f j)) n )\"\napply (cut_tac sc_Ring)   \napply (induct_tac n)\n apply (rule allI)+ apply (rule impI) apply (erule conjE)+\n apply simp\n apply (rule_tac x = \"\\<lambda>k\\<in>{0::nat}. (s 0 \\<plusminus>\\<^bsub>R\\<^esub> a)\" in bexI)\n apply (simp add: Ring.ideal_subset sc_l_distr)\n apply simp\n   apply (simp add:Ring.ideal_pOp_closed)\n\n(** n **)\napply ((rule allI)+, rule impI, (erule conjE)+)\n apply (simp del:nsum_suc add:image_def)\n apply (cut_tac n = n and f = \"\\<lambda>j. s j \\<cdot>\\<^sub>s f j\" in nsum_mem,\n        rule allI, rule impI, rule sc_mem,\n        simp add:funcset_mem Ring.ideal_subset,\n        simp add:funcset_mem,\n        frule_tac x = \"Suc n\" and f = s and A = \"{j. j \\<le> Suc n}\" and\n        B = A in funcset_mem, simp,\n        frule_tac h = \"s (Suc n)\" in Ring.ideal_subset, assumption+,\n        frule_tac x = \"Suc n\" and f = f and A = \"{j. j \\<le> Suc n}\" and\n        B = \"carrier M\" in funcset_mem, simp,\n        frule_tac a = \"s (Suc n)\" and m = \"f (Suc n)\" in sc_mem, assumption+,\n        cut_tac a = a and m = m in sc_mem,\n        simp add:Ring.ideal_subset, erule exE, simp add:Pi_def,\n        erule exE, erule conjE)\n apply (case_tac \"x = Suc n\", simp)  (***** case x = Suc n ********)\n apply (subst ag_pOp_assoc, assumption+)\n apply (thin_tac \"\\<Sigma>\\<^sub>e M (\\<lambda>j. s j \\<cdot>\\<^sub>s f j) n \\<in> carrier M\",\n        thin_tac \"s (Suc n) \\<cdot>\\<^sub>s f (Suc n) \\<in> carrier M\",\n        thin_tac \"a \\<cdot>\\<^sub>s f (Suc n) \\<in> carrier M\",\n        thin_tac \"\\<forall>s fa.\n           s \\<in> {j. j \\<le> n} \\<rightarrow> A \\<and>\n           fa \\<in> {j. j \\<le> n} \\<rightarrow> carrier M \\<and> (\\<exists>x\\<le>n. f (Suc n) = fa x) \\<longrightarrow>\n           (\\<exists>t\\<in>{j. j \\<le> n} \\<rightarrow> A.\n               \\<Sigma>\\<^sub>e M (\\<lambda>j. s j \\<cdot>\\<^sub>s fa j) n \\<plusminus> a \\<cdot>\\<^sub>s f (Suc n) =\n               \\<Sigma>\\<^sub>e M (\\<lambda>j. t j \\<cdot>\\<^sub>s fa j) n)\")\n apply (subst sc_l_distr[THEN sym], assumption+,\n        simp add:Ring.ideal_subset, assumption+)\n apply (frule func_pre[of _ _ A],\n        frule_tac f = s and n = n and g = \"\\<lambda>k\\<in>{0::nat}. (s (Suc n) \\<plusminus>\\<^bsub>R\\<^esub> a)\" and\n        m = 0 and A = A and B = A in jointfun_hom0,\n        simp add: Ring.ideal_pOp_closed)\n apply (subgoal_tac \"\\<Sigma>\\<^sub>e M (\\<lambda>j. s j \\<cdot>\\<^sub>s f j) n \\<plusminus> (s (Suc n) \\<plusminus>\\<^bsub>R\\<^esub> a) \\<cdot>\\<^sub>s f (Suc n) =\n      \\<Sigma>\\<^sub>e M (\\<lambda>j. (jointfun n s 0 (\\<lambda>k\\<in>{0}. s (Suc n) \\<plusminus>\\<^bsub>R\\<^esub> a)) j \\<cdot>\\<^sub>s f j) (Suc n)\",\n      simp,\n      thin_tac \"\\<Sigma>\\<^sub>e M (\\<lambda>j. s j \\<cdot>\\<^sub>s f j) n \\<plusminus> (s (Suc n) \\<plusminus>\\<^bsub>R\\<^esub> a) \\<cdot>\\<^sub>s f (Suc n) =\n      \\<Sigma>\\<^sub>e M (\\<lambda>j. jointfun n s 0 (\\<lambda>k\\<in>{0}. s (Suc n) \\<plusminus>\\<^bsub>R\\<^esub> a) j \\<cdot>\\<^sub>s f j) n \\<plusminus>\n      jointfun n s 0 (\\<lambda>k\\<in>{0}. s (Suc n) \\<plusminus>\\<^bsub>R\\<^esub> a) (Suc n) \\<cdot>\\<^sub>s f (Suc n)\")\n apply blast\n apply simp\n apply (simp add:jointfun_def sliden_def)\n apply (cut_tac n = n and f = \"\\<lambda>j. s j \\<cdot>\\<^sub>s f j\" and g = \"\\<lambda>j. (if j \\<le> n then s j\n        else (\\<lambda>k\\<in>{0}. s (Suc n) \\<plusminus>\\<^bsub>R\\<^esub> a) (sliden (Suc n) j)) \\<cdot>\\<^sub>s f j\" in\n        nsum_eq)\n        apply (rule allI, rule impI, rule sc_mem,\n               simp add:Pi_def Ring.ideal_subset,\n               simp add:Pi_def)\n        apply (rule allI, rule impI, simp, rule sc_mem,\n               simp add:Pi_def Ring.ideal_subset,\n               simp add:Pi_def)\n        apply (rule allI, rule impI, simp)\n  apply simp\n  \n  apply (frule_tac m = x and n = \"Suc n\" in noteq_le_less, assumption,\n         thin_tac \"x \\<le> Suc n\",\n         frule_tac x = x and n = \"Suc n\" in less_le_diff,\n         thin_tac \"x < Suc n\", simp)\n  apply (frule func_pre[of _ _ A], frule func_pre[of _ _ \"carrier M\"])\n  apply (drule_tac x = s in spec,\n         drule_tac x = f in spec)\n   apply (subgoal_tac \"\\<exists>xa\\<le>n. f x = f xa\", simp,\n          thin_tac \"\\<exists>xa\\<le>n. f x = f xa\", erule bexE)\n   apply (subst ag_pOp_assoc, assumption+,\n          frule_tac x = \"s (Suc n) \\<cdot>\\<^sub>s f (Suc n)\" and y = \"a \\<cdot>\\<^sub>s f x\" in \n          ag_pOp_commute, assumption+, simp,\n          thin_tac \"s (Suc n) \\<cdot>\\<^sub>s f (Suc n) \\<plusminus> a \\<cdot>\\<^sub>s f x =\n          a \\<cdot>\\<^sub>s f x \\<plusminus> s (Suc n) \\<cdot>\\<^sub>s f (Suc n)\",\n          subst ag_pOp_assoc[THEN sym], assumption+, simp,\n    thin_tac \"\\<Sigma>\\<^sub>e M (\\<lambda>j. s j \\<cdot>\\<^sub>s f j) n \\<plusminus> a \\<cdot>\\<^sub>s f x = \\<Sigma>\\<^sub>e M (\\<lambda>j. t j \\<cdot>\\<^sub>s f j) n\")\n  apply (frule_tac f = t and n = n and g = \"\\<lambda>k\\<in>{0::nat}. s (Suc n)\" and\n         m = 0 and A = A and B = A in jointfun_hom0,\n         simp, simp)\n  apply (subgoal_tac \"\\<Sigma>\\<^sub>e M (\\<lambda>j. t j \\<cdot>\\<^sub>s f j) n \\<plusminus> s (Suc n) \\<cdot>\\<^sub>s f (Suc n) =\n         \\<Sigma>\\<^sub>e M (\\<lambda>j. (jointfun n t 0 (\\<lambda>k\\<in>{0}. s (Suc n))) j \\<cdot>\\<^sub>s f j) (Suc n)\",\n         simp,\n         thin_tac \"\\<Sigma>\\<^sub>e M (\\<lambda>j. t j \\<cdot>\\<^sub>s f j) n \\<plusminus> s (Suc n) \\<cdot>\\<^sub>s f (Suc n) =\n        \\<Sigma>\\<^sub>e M (\\<lambda>j. jointfun n t 0 (\\<lambda>k\\<in>{0}. s (Suc n)) j \\<cdot>\\<^sub>s f j) n \\<plusminus>\n        jointfun n t 0 (\\<lambda>k\\<in>{0}. s (Suc n)) (Suc n) \\<cdot>\\<^sub>s f (Suc n)\")\n  apply blast\n   apply (simp add:jointfun_def sliden_def)\n   apply (cut_tac n = n and f = \"\\<lambda>j. t j \\<cdot>\\<^sub>s f j\" and \n          g = \"\\<lambda>j. (if j \\<le> n then t j  else (\\<lambda>k\\<in>{0}. s (Suc n)) \n                (sliden (Suc n) j)) \\<cdot>\\<^sub>s f j\" in nsum_eq)\n   apply (rule allI, rule impI, rule sc_mem,\n          simp add:Pi_def Ring.ideal_subset,\n          simp add:Pi_def)\n   apply (rule allI, rule impI, simp, rule sc_mem,\n          simp add:Pi_def Ring.ideal_subset,\n          simp add:Pi_def)   \n   apply (rule allI, rule impI, simp, simp)\n   apply blast\ndone\n\nlemma (in Module) similar_term1:\"\\<lbrakk>ideal R A; a \\<in> A; s \\<in> {j. j\\<le>(n::nat)} \\<rightarrow> A;\n       f \\<in> {j. j \\<le> n} \\<rightarrow> carrier M; m \\<in> f ` {j. j \\<le> n}\\<rbrakk> \\<Longrightarrow> \n      \\<exists>t\\<in>{j. j \\<le> n} \\<rightarrow> A. \\<Sigma>\\<^sub>e M (\\<lambda>j. s j \\<cdot>\\<^sub>s (f j)) n \\<plusminus> a \\<cdot>\\<^sub>s m =\n             \\<Sigma>\\<^sub>e M (\\<lambda>j.  t j \\<cdot>\\<^sub>s (f j)) n\" \napply (simp add:similar_termTr)\ndone\n\n\nlemma (in Module) same_togetherTr:\"\\<lbrakk>ideal R A; H \\<subseteq> carrier M \\<rbrakk> \\<Longrightarrow> \n \\<forall>s. \\<forall>f. s\\<in>{j. j \\<le> (n::nat)} \\<rightarrow> A  \\<and> f \\<in> {j. j \\<le> n} \\<rightarrow> H \\<longrightarrow> \n (\\<exists>t \\<in> {j. j \\<le> (card (f ` {j. j \\<le> n}) - Suc 0)} \\<rightarrow> A. \n  \\<exists>g \\<in> {j. j \\<le> (card (f ` {j. j \\<le> n}) - Suc 0)} \\<rightarrow> f ` {j. j \\<le> n}. \n   surj_to g {j. j \\<le> (card (f ` {j. j \\<le> n}) - Suc 0)} (f ` {j. j \\<le> n}) \\<and> \n  nsum M (\\<lambda>j. s j \\<cdot>\\<^sub>s (f j)) n = nsum M (\\<lambda>k. t k \\<cdot>\\<^sub>s (g k)) \n       (card (f ` {j. j \\<le> n}) - Suc 0))\"  \napply (induct_tac n)\n apply ((rule allI)+, rule impI, erule conjE)\n apply (simp del: Pi_split_insert_domain)\n apply (frule_tac f = f and A = \"{0}\" and B= H in func_to_img,\n        frule_tac f = f and A = \"{0}\" and B= H in surj_to_image,\n        fastforce simp add:image_def)\n\napply ((rule allI)+, rule impI, erule conjE)\n apply (frule func_pre [of _ _ \"A\"], frule func_pre [of _ _ \"H\"])\n apply (drule_tac x = s in spec,\n        drule_tac x = f in spec,\n        simp, (erule bexE)+ , (erule conjE)+, simp,\n        thin_tac \"\\<Sigma>\\<^sub>e M (\\<lambda>j. s j \\<cdot>\\<^sub>s f j) n =\n        \\<Sigma>\\<^sub>e M (\\<lambda>k. t k \\<cdot>\\<^sub>s g k) (card (f ` {j. j \\<le> n}) - Suc 0)\")\n\napply (case_tac \"f (Suc n) \\<in> f ` {j. j \\<le> n}\")\n apply (frule_tac a = \"s (Suc n)\" and s = t and \n        n = \"card (f ` {j. j \\<le> n}) - Suc 0\" and f = g and m = \"f (Suc n)\" in \n        similar_term1[of A],\n        simp add:Pi_def,\n        assumption,\n        frule_tac f = f and A = \"{j. j \\<le> n}\" and B = H in image_sub0,\n        frule_tac A = \"f ` {j. j \\<le> n}\" and B = H and C = \"carrier M\" \n         in subset_trans, assumption,\n        rule_tac f = g and A = \"{j. j \\<le> card (f ` {j. j \\<le> n}) - Suc 0}\" and \n                 B = \"f ` {j. j \\<le> n}\" and ?B1.0 = \"carrier M\" in extend_fun, \n        assumption+)\n        apply (simp add:surj_to_def)\n  apply (erule bexE, simp,\n         thin_tac \"\\<Sigma>\\<^sub>e M (\\<lambda>j. t j \\<cdot>\\<^sub>s g j) (card (f ` {j. j \\<le> n}) - Suc 0) \\<plusminus>\n        s (Suc n) \\<cdot>\\<^sub>s f (Suc n) =\n        \\<Sigma>\\<^sub>e M (\\<lambda>j. ta j \\<cdot>\\<^sub>s g j) (card (f ` {j. j \\<le> n}) - Suc 0)\") \n  apply (simp add:Nset_img0)\n  apply blast\n  \n  apply (frule_tac f = t and n = \"card (f ` {j. j \\<le> n}) - Suc 0\" and A = A and\n        g = \"\\<lambda>k\\<in>{0::nat}. s (Suc n)\" and m = 0 and B = A in jointfun_hom0)\n        apply (simp add:Pi_def,\n               simp)\n  apply (frule_tac f = g and n = \"card (f ` {j. j \\<le> n}) - Suc 0\" and \n         A = \"f ` {j. j \\<le> n}\" and g = \"\\<lambda>k\\<in>{0::nat}. f (Suc n)\" and m = 0 and \n         B = \"{f (Suc n)}\" in jointfun_hom0)\n        apply (simp add:Pi_def,\n               simp)\n  apply (subgoal_tac \"\\<Sigma>\\<^sub>e M (\\<lambda>k. t k \\<cdot>\\<^sub>s g k) (card (f ` {j. j \\<le> n}) - Suc 0) \\<plusminus>\n                s (Suc n) \\<cdot>\\<^sub>s f (Suc n) =\n        \\<Sigma>\\<^sub>e M (\\<lambda>j. (jointfun (card (f ` {j. j \\<le> n}) - Suc 0) t 0 (\\<lambda>k\\<in>{0}. \n            s (Suc n))) j \\<cdot>\\<^sub>s (jointfun (card (f ` {j. j \\<le> n}) - Suc 0) g 0 \n        (\\<lambda>k\\<in>{0}. f (Suc n))) j) (card (f ` {j. j \\<le> (Suc n)}) - Suc 0)\", simp, \n        thin_tac \"\\<Sigma>\\<^sub>e M (\\<lambda>k. t k \\<cdot>\\<^sub>s g k) (card (f ` {j. j \\<le> n}) - Suc 0) \\<plusminus>\n        s (Suc n) \\<cdot>\\<^sub>s f (Suc n) =\n        \\<Sigma>\\<^sub>e M (\\<lambda>j. jointfun (card (f ` {j. j \\<le> n}) - Suc 0) t 0\n                   (\\<lambda>k\\<in>{0}. s (Suc n)) j \\<cdot>\\<^sub>s\n                  jointfun (card (f ` {j. j \\<le> n}) - Suc 0) g 0\n                   (\\<lambda>k\\<in>{0}. f (Suc n))\n                   j) (card (f ` {j. j \\<le> Suc n}) - Suc 0)\")\n  apply (simp del:nsum_suc add:card_image_Nsetn_Suc)\n  apply (simp del:nsum_suc add:image_Nset_Suc[THEN sym])\n apply (subgoal_tac \"surj_to (jointfun (card (f ` {j. j \\<le> n}) - Suc 0) g 0 \n       (\\<lambda>k\\<in>{0}. f (Suc n))) {l. l \\<le> Suc (card (f ` {j. j \\<le> n}) - Suc 0)} \n       (f ` {j. j \\<le> Suc n})\", blast)\n\n   apply (simp add:surj_to_def)\n   apply (frule_tac f = g and n = \"card (f ` {j. j \\<le> n}) - Suc 0\" and A = \"f ` {j. j \\<le> n}\" and g = \"\\<lambda>k\\<in>{0}. f (Suc n)\" and m = 0 and B = \"{f (Suc n)}\" in\n  im_jointfun)\n   apply (simp add:Pi_def)\n   apply simp\n   apply (simp add:image_Nset_Suc[THEN sym])\n   apply (simp add:card_image_Nsetn_Suc)\n   apply (simp add:Nset_img)\n\n   apply (frule_tac f = f and A = \"{j. j \\<le> Suc n}\" and B = H in image_sub0)\n   apply (frule_tac A = \"f ` {j. j \\<le> Suc n}\" and B = H and C = \"carrier M\" in\n          subset_trans, assumption+)\n   apply (cut_tac H = H and s = t and n = \"card (f ` {j. j \\<le> n}) - Suc 0\" \n         and f = g and t = \"\\<lambda>k\\<in>{0}. s (Suc n)\" and m = 0 and \n         g = \"\\<lambda>k\\<in>{0}. f (Suc n)\" in \n         l_comb_jointfun_jj[of _ A], assumption+) \n   apply (frule_tac f = f and A = \"{j. j \\<le> n}\" and B = H in image_sub0)\n   apply (rule_tac f = g and A = \"{j. j \\<le> card (f ` {j. j \\<le> n}) - Suc 0}\" and\n          B = \"f ` {j. j \\<le> n}\" in extend_fun[of _ _ _ H], assumption+,\n          simp add:Pi_def, simp add:Pi_def)\n   apply simp\n   apply (simp add:jointfun_def sliden_def)\ndone\n\n (* H shall a generator *)\nlemma (in Module) same_together:\"\\<lbrakk>ideal R A; H \\<subseteq> carrier M; \n       s \\<in> {j. j \\<le> (n::nat)} \\<rightarrow> A; f \\<in> {j. j \\<le> n} \\<rightarrow> H\\<rbrakk> \\<Longrightarrow> \n \\<exists>t \\<in> {j. j \\<le> (card (f ` {j. j \\<le> (n::nat)}) - Suc 0)} \\<rightarrow> A. \n \\<exists>g \\<in> {j. j \\<le> (card (f ` {j. j \\<le> n}) - Suc 0)} \\<rightarrow> f ` {j. j \\<le> n}. \n       surj_to g {j. j \\<le> (card (f ` {j. j \\<le> n}) - Suc 0)} (f ` {j. j \\<le> n}) \\<and> \n  \\<Sigma>\\<^sub>e M (\\<lambda>j. s j \\<cdot>\\<^sub>s (f j)) n = \n                  \\<Sigma>\\<^sub>e M (\\<lambda>k. t k \\<cdot>\\<^sub>s (g k)) (card (f ` {j. j \\<le> n}) - Suc 0)\"  \napply (simp add:same_togetherTr[of A H])\ndone\n\nlemma (in Module) one_last:\"\\<lbrakk>ideal R A; H \\<subseteq> carrier M; \n      s \\<in> {j. j \\<le> (Suc n)} \\<rightarrow> A; f \\<in> {j. j \\<le> (Suc n)} \\<rightarrow> H; \n      bij_to f {j. j \\<le> (Suc n)} H; j \\<le> (Suc n); j \\<noteq> (Suc n)\\<rbrakk> \\<Longrightarrow> \n \\<exists>t \\<in> {j. j \\<le> (Suc n)} \\<rightarrow> A. \\<exists>g \\<in> {j. j \\<le> (Suc n)} \\<rightarrow> H.  \n  \\<Sigma>\\<^sub>e M (\\<lambda>k. s k  \\<cdot>\\<^sub>s (f k)) (Suc n) =  \\<Sigma>\\<^sub>e M (\\<lambda>k. t k  \\<cdot>\\<^sub>s (g k)) (Suc n) \\<and>\n  g (Suc n) = f j \\<and> t (Suc n) = s j \\<and> bij_to g {j. j \\<le> (Suc n)} H\"  \napply (cut_tac sc_Ring)\napply (subgoal_tac \"(\\<lambda>k. s k \\<cdot>\\<^sub>s (f k)) \\<in> {j. j \\<le> Suc n} \\<rightarrow> carrier M\")\napply (frule transpos_hom[of j \"Suc n\" \"Suc n\"], simp, assumption,\n       frule transpos_inj[of j \"Suc n\" \"Suc n\"], simp, assumption,\n       frule_tac f1 = \"\\<lambda>k.  s k \\<cdot>\\<^sub>s (f k)\" and n1 = n and h1 = \n         \"transpos j (Suc n)\" in addition2 [THEN sym], assumption+,\n       simp del:nsum_suc)\nprefer 2  \n    apply (rule Pi_I, rule sc_mem,\n           simp add:Pi_def Ring.ideal_subset,\n           simp add:Pi_def subsetD)\n apply (frule cmp_fun[of \"transpos j (Suc n)\" \"{j. j \\<le> Suc n}\" \n                         \"{j. j \\<le> Suc n}\" s A], assumption+,\n        frule cmp_fun[of \"transpos j (Suc n)\" \"{j. j \\<le> Suc n}\" \n                         \"{j. j \\<le> Suc n}\" f H], assumption+)\n apply (simp del:nsum_suc add:l_comb_transpos[of A H])\n apply (subgoal_tac \"bij_to (cmp f (transpos j (Suc n))) {j. j \\<le> (Suc n)} H\") \n apply (subgoal_tac \"(cmp f (transpos j (Suc n))) (Suc n) = f j\")\n apply (subgoal_tac \"(cmp s (transpos j (Suc n))) (Suc n) = s j\")\n apply blast\n apply (simp add:cmp_def, simp add:transpos_ij_2,\n        simp add:cmp_def, simp add:transpos_ij_2)\n apply (simp add:bij_to_def, rule conjI,\n        rule cmp_surj[of \"transpos j (Suc n)\" \"{j. j \\<le> Suc n}\" \n          \"{j. j \\<le> Suc n}\" f H], assumption+,\n        simp add:transpos_surjec, assumption+, simp)\n apply (rule cmp_inj[of \"transpos j (Suc n)\" \"{j. j \\<le> Suc n}\" \n          \"{j. j \\<le> Suc n}\" f H], assumption+, simp)\ndone\n \nlemma (in Module) finite_lin_spanTr1:\"\\<lbrakk>ideal R A; z \\<in> carrier M\\<rbrakk> \\<Longrightarrow>\n      h \\<in> {j. j \\<le> (n::nat)} \\<rightarrow> {z} \\<and> t \\<in> {j. j \\<le> n} \\<rightarrow> A  \\<longrightarrow> \n      (\\<exists>s\\<in>{0::nat} \\<rightarrow> A. \\<Sigma>\\<^sub>e M (\\<lambda>j. t j \\<cdot>\\<^sub>s (h j)) n =  s 0 \\<cdot>\\<^sub>s z)\"\napply (induct_tac n)\n apply (rule impI)\n apply ((erule conjE)+, simp)\n apply blast \n\napply (rule impI) apply (erule conjE)+\n apply (frule func_pre [of _ _ \"{z}\"], frule func_pre [of _ _ \"A\"])\napply (simp del:nsum_suc, erule bexE, simp,\n       frule_tac f = h and A = \"{j. j \\<le> Suc n}\" and B = \"{z}\" and x = \"Suc n\"\n       in funcset_mem, simp, simp,\n       frule_tac f = t and A = \"{j. j \\<le> Suc n}\" and B = A and x = \"Suc n\" in\n        funcset_mem, simp, cut_tac sc_Ring,\n       frule_tac h = \"s 0\" in Ring.ideal_subset[of R A], assumption+,\n       frule_tac h = \"t (Suc n)\" in Ring.ideal_subset[of R A], assumption+)\n apply (simp add:sc_l_distr[THEN sym])\n apply (subgoal_tac \"(\\<lambda>l\\<in>{0::nat}. (s 0 \\<plusminus>\\<^bsub>R\\<^esub> (t (Suc n)))) \\<in> {0} \\<rightarrow> A\")\napply (subgoal_tac \"(s 0 \\<plusminus>\\<^bsub>R\\<^esub> t (Suc n)) \\<cdot>\\<^sub>s z = (\\<lambda>l\\<in>{0::nat}. (s 0 \\<plusminus>\\<^bsub>R\\<^esub> (t (Suc n)))) 0 \\<cdot>\\<^sub>s z \") apply blast\n apply simp \n apply (rule Pi_I) apply simp\n apply (rule Ring.ideal_pOp_closed, assumption+)\ndone\n\nlemma (in Module) single_span:\"\\<lbrakk>ideal R A; z \\<in> carrier M;\n    h \\<in> {j. j \\<le> (n::nat)} \\<rightarrow> {z}; t \\<in> {j. j \\<le> n} \\<rightarrow> A\\<rbrakk> \\<Longrightarrow> \n     \\<exists>s\\<in>{0::nat} \\<rightarrow> A. \\<Sigma>\\<^sub>e M (\\<lambda>j. t j \\<cdot>\\<^sub>s (h j)) n =  s 0 \\<cdot>\\<^sub>s z\"\napply (simp add:finite_lin_spanTr1)\ndone\n(*\nlemma (in Module) finite_lin_spanTr2:\"\\<lbrakk>ideal R A; \\<forall>m. \n(\\<exists>n1. \\<exists>f\\<in>{j. j \\<le> n1} \\<rightarrow> h ` {j. j \\<le> n}. \\<exists>s\\<in>{j. j \\<le> n1} \\<rightarrow> A. \n  m = \\<Sigma>\\<^sub>e M (\\<lambda>j. s j \\<cdot>\\<^sub>s (f j)) n1) \\<longrightarrow> \n     (\\<exists>s\\<in>{j. j \\<le> n} \\<rightarrow> A. m = \\<Sigma>\\<^sub>e M (\\<lambda>j. s j \\<cdot>\\<^sub>s (h j)) n); \n  h \\<in> {j. j \\<le> (Suc n)} \\<rightarrow> carrier M; f \\<in> {j. j \\<le> n1} \\<rightarrow> h ` {j. j \\<le> n}; \n  s \\<in> {j. j \\<le> n1} \\<rightarrow> A; m = \\<Sigma>\\<^sub>e M (\\<lambda>j. s j \\<cdot>\\<^sub>s (f j)) n1\\<rbrakk> \\<Longrightarrow> \n  \\<exists>sa\\<in>{j. j \\<le> (Suc n)} \\<rightarrow> A. \\<Sigma>\\<^sub>e M (\\<lambda>j. s j \\<cdot>\\<^sub>s (f j)) n1 = \n    \\<Sigma>\\<^sub>e M (\\<lambda>j. sa j \\<cdot>\\<^sub>s (h j)) n \\<plusminus> (sa (Suc n) \\<cdot>\\<^sub>s (h (Suc n)))\"\n apply (frule_tac \n apply (subgoal_tac \"\\<exists>l\\<in>{j. j \\<le> n} \\<rightarrow> A. m = \\<Sigma>\\<^sub>e M (\\<lambda>j. l j \\<cdot>\\<^sub>s (h j)) n\")\n prefer 2 \n apply (thin_tac \"h \\<in> {j. j \\<le> (Suc n)} \\<rightarrow> carrier M\")\n apply blast\n apply (thin_tac \" \\<forall>m. (\\<exists>n1. \\<exists>f\\<in>Nset n1 \\<rightarrow> h ` Nset n.\n  \\<exists>s\\<in>Nset n1 \\<rightarrow> A. m = e\\<Sigma> M (\\<lambda>j. s j \\<star>\\<^sub>M (f j)) n1) \\<longrightarrow>\n              (\\<exists>s\\<in>Nset n \\<rightarrow> A. m = e\\<Sigma> M (\\<lambda>j.  s j \\<star>\\<^sub>M (h j)) n)\")\n apply (subgoal_tac \"\\<forall>l\\<in>Nset n \\<rightarrow> A. m = e\\<Sigma> M (\\<lambda>j. l j \\<star>\\<^sub>M (h j)) n \\<longrightarrow> (\\<exists>sa\\<in>Nset (Suc n) \\<rightarrow> A. e\\<Sigma> M (\\<lambda>j. s j \\<star>\\<^sub>M (f j)) n1 = e\\<Sigma> M (\\<lambda>j. sa j \\<star>\\<^sub>M (h j)) n +\\<^sub>M  (sa (Suc n) \\<star>\\<^sub>M (h (Suc n))))\")\n apply blast\n apply (thin_tac \"\\<exists>l\\<in>Nset n \\<rightarrow> A. m = e\\<Sigma> M (\\<lambda>j. l j \\<star>\\<^sub>M (h j)) n\")\n apply (rule ballI) apply (rule impI)\n apply (frule sym) apply (thin_tac \"m = e\\<Sigma> M (\\<lambda>j. s j \\<star>\\<^sub>M (f j)) n1\")\n apply simp\n apply (thin_tac \"m = e\\<Sigma> M (\\<lambda>j. l j \\<star>\\<^sub>M (h j)) n\")\n apply (thin_tac \"e\\<Sigma> M (\\<lambda>j. s j \\<star>\\<^sub>M (f j)) n1 = e\\<Sigma> M (\\<lambda>j. l j \\<star>\\<^sub>M (h j)) n\")\n apply (subgoal_tac \"jointfun n l 0 (\\<lambda>x\\<in>Nset 0. (0\\<^sub>R)) \\<in> Nset (Suc n) \\<rightarrow> A\")\n apply (subgoal_tac \" e\\<Sigma> M (\\<lambda>j. l j \\<star>\\<^sub>M (h j)) n =\n  e\\<Sigma> M (\\<lambda>j. (jointfun n l 0 (\\<lambda>x\\<in>Nset 0. (0\\<^sub>R))) j \\<star>\\<^sub>M (h j)) n +\\<^sub>M  ((jointfun n l 0 (\\<lambda>x\\<in>Nset 0. (0\\<^sub>R))) (Suc n)) \\<star>\\<^sub>M (h (Suc n))\")\n apply blast\n apply (subgoal_tac \"jointfun n l 0 (\\<lambda>x\\<in>Nset 0. 0\\<^sub>R) (Suc n) \\<star>\\<^sub>M (h (Suc n)) =\n  0\\<^sub>M\") apply simp\n apply (subgoal_tac \"e\\<Sigma> M (\\<lambda>j. jointfun n l 0 (\\<lambda>x\\<in>Nset 0. 0\\<^sub>R) j \\<star>\\<^sub>M (h j)) n =\n e\\<Sigma> M (\\<lambda>j. l j \\<star>\\<^sub>M (h j)) n \") apply simp\n apply (frule module_is_ag [of \"R\" \"M\"], assumption+)\n apply (subst ag_r_zero, assumption+)\n apply (subgoal_tac \"(\\<lambda>j. l j \\<star>\\<^sub>M (h j)) \\<in> Nset n \\<rightarrow> carrier M\")\n apply (rule eSum_mem, assumption+) apply (simp add:n_in_Nsetn)\n apply (rule univar_func_test) apply (rule ballI) \n apply (rule sprod_mem, assumption+)\n apply (simp add:funcset_mem ideal_subset)\n apply (frule func_pre [of \"h\" _ \"carrier M\"])\n apply (simp add:funcset_mem) apply simp\n apply (rule eSum_eq)\n apply (rule module_is_ag [of \"R\" \"M\"], assumption+)\n apply (rule univar_func_test)\n apply (rule ballI)\n apply (frule_tac x = x and n = n in Nset_le)\n apply (insert Nset_nonempty[of \"0\"]) \n apply (simp add:jointfun_def)\n apply (rule sprod_mem, assumption+)\n apply (simp add:funcset_mem ideal_subset)\n apply (frule func_pre [of \"h\" _ \"carrier M\"]) \n apply (simp add:funcset_mem)\n apply (rule univar_func_test) apply (rule ballI)\n apply (rule sprod_mem, assumption+)\n apply (simp add:funcset_mem ideal_subset)\n apply (frule func_pre [of \"h\" _ \"carrier M\"])\n apply (simp add:funcset_mem)\napply (rule ballI)\n apply (frule_tac x = la and n = n in Nset_le)\n apply (simp add:jointfun_def)\n apply (subgoal_tac \"0 \\<in> Nset 0\")\n apply (simp add:jointfun_def sliden_def slide_def)\n apply (rule sprod_0_m, assumption+) \n apply (subgoal_tac \"Suc n \\<in> Nset (Suc n)\")\n apply (simp add:funcset_mem) apply (simp add:n_in_Nsetn)+ \napply (frule_tac f = l and n = n and A = A and g = \"\\<lambda>x\\<in>Nset 0. 0\\<^sub>R\" and m = 0\n      and B = A in jointfun_hom0)\n apply (rule univar_func_test) apply (rule ballI) apply (simp add:Nset_def)\n apply (simp add:ideal_zero) apply simp\ndone *) \n\ndefinition\n  coeff_at_k :: \"[('r, 'm) Ring_scheme, 'r, nat] \\<Rightarrow> (nat \\<Rightarrow> 'r)\" where\n  \"coeff_at_k R a k = (\\<lambda>j. if j = k then a else (\\<zero>\\<^bsub>R\\<^esub>))\" \n\nlemma card_Nset_im:\"f \\<in> {j. j \\<le> (n::nat)} \\<rightarrow> A \\<Longrightarrow> \n                      (Suc 0) \\<le> card (f `{j. j \\<le> n})\"\napply (cut_tac image_Nsetn_card_pos[of f n])\napply (frule_tac m = 0 and n = \"card (f ` {i. i \\<le> n})\" in Suc_leI,\n        assumption+)\ndone \n\nlemma (in Module) eSum_changeTr1:\"\\<lbrakk>ideal R A; \n  t \\<in> {k. k \\<le> (card (f ` {j. j \\<le> (n1::nat)}) - Suc 0)} \\<rightarrow> A; \n  g \\<in> {k. k \\<le> (card (f ` {j. j \\<le> n1}) - Suc 0)} \\<rightarrow> f `{j. j \\<le> n1}; \n  Suc 0 < card (f `{j. j \\<le> n1}); g x = h (Suc n); x = Suc n; \ncard (f `{j. j \\<le> n1}) - Suc 0 =  Suc (card (f ` {j. j \\<le> n1}) - Suc 0 - Suc 0)\\<rbrakk>\n  \\<Longrightarrow> \n \\<Sigma>\\<^sub>e M (\\<lambda>k. t k  \\<cdot>\\<^sub>s (g k)) (card (f ` {j. j \\<le> n1}) - Suc 0) =  \n \\<Sigma>\\<^sub>e M (\\<lambda>k. t k  \\<cdot>\\<^sub>s (g k)) (card (f ` {j. j \\<le> n1}) - Suc 0 - Suc 0) \\<plusminus>  \n    (t (Suc (card (f ` {j. j \\<le> n1}) - Suc 0 - Suc 0))  \\<cdot>\\<^sub>s \n                (g ( Suc (card (f ` {j. j \\<le> n1}) - Suc 0 - Suc 0))))\"  \napply simp\ndone\n\ndefinition\n  zeroi :: \"[('r, 'm) Ring_scheme] \\<Rightarrow> nat \\<Rightarrow> 'r\" where\n  \"zeroi R = (\\<lambda>j. \\<zero>\\<^bsub>R\\<^esub>)\" \n\nlemma zeroi_func:\"\\<lbrakk>Ring R; ideal R A\\<rbrakk> \\<Longrightarrow>  zeroi R \\<in> {j. j \\<le> 0} \\<rightarrow> A\"\nby (simp add:zeroi_def Ring.ideal_zero)\n\nlemma (in Module) prep_arrTr1:\"\\<lbrakk>ideal R A; h \\<in> {j. j \\<le> (Suc n)} \\<rightarrow> carrier M;\n f \\<in> {j. j \\<le> (n1::nat)} \\<rightarrow> h ` {j. j \\<le> (Suc n)}; s \\<in> {j. j \\<le> n1}\\<rightarrow> A; \n m = l_comb R M n1 s f\\<rbrakk> \\<Longrightarrow> \n \\<exists>l\\<in>{j. j \\<le> (Suc n)}. (\\<exists>s\\<in>{j. j \\<le> (l::nat)} \\<rightarrow> A. \n \\<exists>g\\<in> {j. j \\<le> l} \\<rightarrow> h `{j. j \\<le> (Suc n)}. m = l_comb R M l s g \\<and> \n                      bij_to g {j. j \\<le> l} (f ` {j. j \\<le> n1}))\"\napply (cut_tac sc_Ring)\napply (frule_tac s = s and n = n1 and f = f in  same_together[of A \n      \"h ` {j. j \\<le> (Suc n)}\"]) \n apply (simp add:image_sub0, assumption+)\n apply (erule bexE)+ \n apply (simp add:l_comb_def, erule conjE)\n apply (thin_tac \"\\<Sigma>\\<^sub>e M (\\<lambda>j. s j \\<cdot>\\<^sub>s f j) n1 =\n           \\<Sigma>\\<^sub>e M (\\<lambda>k. t k \\<cdot>\\<^sub>s g k) (card (f ` {j. j \\<le> n1}) - Suc 0)\")\n apply (subgoal_tac \"(card (f ` {j. j \\<le> n1}) - Suc 0) \\<in> {j. j \\<le> Suc n}\")\n apply (subgoal_tac \"g \\<in> {k. k \\<le> (card (f `{j. j \\<le> n1}) - Suc 0)} \\<rightarrow>\n                         h ` {j. j \\<le> Suc n}\")\n apply (subgoal_tac \"bij_to g {k. k \\<le> (card (f ` {j. j \\<le> n1}) - Suc 0)} (f ` {j. j \\<le> n1})\")\n apply blast\n prefer 2 \n  apply (frule_tac f = f and A = \"{j. j \\<le> n1}\" and B = \"h ` {j. j \\<le> Suc n}\" \n          in image_sub0, simp)\n  apply (rule extend_fun, assumption+)\n apply (simp add:bij_to_def)\napply (rule_tac A = \"f ` {j. j \\<le> n1}\" and n = \"card (f `{j. j \\<le> n1}) - Suc 0\" and f = g in Nset2finite_inj)\n apply (rule finite_imageI, simp)\n apply (frule_tac f = f and n = n1 and A = \"h ` {j. j \\<le> (Suc n)}\" in card_Nset_im)\n apply (simp, assumption)\napply (subgoal_tac \"finite (h ` {j. j \\<le> (Suc n)})\")\napply (frule_tac f = f and A = \"{j. j \\<le> n1}\" and B = \"h ` {j. j \\<le> (Suc n)}\" \n       in image_sub0, simp)\n apply (cut_tac B = \"h ` {j. j \\<le> (Suc n)}\" and A = \"f ` {j. j \\<le> n1}\" in \n        card_mono, simp,  assumption+,\n        insert finite_Collect_le_nat [of \"Suc n\"],\n        frule card_image_le [of \"{j. j \\<le> (Suc n)}\" \"h\"],\n        frule_tac i = \"card (f ` {j. j \\<le> n1})\" and \n         j = \"card (h ` {j. j \\<le> (Suc n)})\" and k = \"card {j. j \\<le> (Suc n)}\" in\n        le_trans, assumption+)\n apply simp\n apply (rule finite_imageI, simp)\ndone\n\nlemma two_func_imageTr:\"\\<lbrakk> h \\<in> {j. j \\<le> Suc n} \\<rightarrow> B; \n   f \\<in> {j. j \\<le> (m::nat)} \\<rightarrow> h ` {j. j \\<le> Suc n};  h (Suc n) \\<notin> f ` {j. j \\<le> m}\\<rbrakk>\n       \\<Longrightarrow> f \\<in> {j. j \\<le> m} \\<rightarrow> h ` {j. j \\<le> n}\" \napply (rule Pi_I)\n    apply (frule_tac x = x and f = f and A = \"{j. j \\<le> m}\" and \n           B = \"h ` {j. j \\<le> Suc n}\" in funcset_mem, assumption)\n   apply (thin_tac \"h \\<in> {j. j \\<le> Suc n} \\<rightarrow> B\")\n   apply (rule contrapos_pp, simp+)\n     apply (simp add:image_def[of h])\n     apply (erule exE, erule conjE)\n     apply (case_tac \"xa \\<noteq> Suc n\",\n            frule_tac m = xa and n = \"Suc n\" in noteq_le_less, assumption)\n          apply (\n            thin_tac \"xa \\<le> Suc n\",\n            frule_tac x = xa and n = \"Suc n\" in less_le_diff,\n            thin_tac \"xa < Suc n\", simp) apply blast\n     apply simp\n     apply (subgoal_tac \"(f x) \\<in> f ` {j. j \\<le> m}\", simp)\n       apply (thin_tac \"h (Suc n) \\<notin> f ` {j. j \\<le> m}\",\n                 thin_tac \"\\<forall>x\\<le>n. h (Suc n) \\<noteq> h x\",\n                 thin_tac \"f x = h (Suc n)\",\n                 thin_tac \"xa = Suc n\")\n     apply (simp add:image_def, blast)\ndone\n\nlemma (in Module) finite_lin_spanTr3_0:\"\\<lbrakk>bij_to g {j. j \\<le> l} (g `{j. j \\<le> l});\n      ideal R A; \n     \\<forall>na. \\<forall>s\\<in>{j. j \\<le> na} \\<rightarrow> A.\n                \\<forall>f\\<in>{j. j \\<le> na} \\<rightarrow> h ` {j. j \\<le> n}.\n                   \\<exists>t\\<in>{j. j \\<le> n} \\<rightarrow> A. l_comb R M na s f = l_comb R M n t h;\n     h \\<in> {j. j \\<le> Suc n} \\<rightarrow> carrier M; s \\<in> {j. j \\<le> m} \\<rightarrow> A;\n     f \\<in> {j. j \\<le> m} \\<rightarrow> h ` {j. j \\<le> Suc n}; \n     l \\<le> Suc n; sa \\<in> {j. j \\<le> l} \\<rightarrow> A; g \\<in> {j. j \\<le> l} \\<rightarrow> h ` {j. j \\<le> Suc n};\n     0 < l; f ` {j. j \\<le> m} = g ` {j. j \\<le> l}; h (Suc n) = g l\\<rbrakk>\n \\<Longrightarrow> \\<exists>t\\<in>{j. j \\<le> Suc n} \\<rightarrow> A. l_comb R M l sa g = l_comb R M (Suc n) t h\"\n  apply (cut_tac sc_Ring)\n  apply (subgoal_tac \"l_comb R M l sa g = l_comb R M (Suc (l - Suc 0)) sa g\",\n         simp del:Suc_pred,\n         thin_tac \"l_comb R M l sa g = l_comb R M (Suc (l - Suc 0)) sa g\",\n         simp del:Suc_pred add:l_comb_def)\n  apply (drule_tac x = \"l - Suc 0\" in spec,\n         drule_tac x = sa in bspec)\n        \n  apply (rule Pi_I, simp)\n        apply (rule_tac x = x and f = sa and A = \"{j. j \\<le> l}\"and B = A\n               in funcset_mem, assumption, simp) (*\n        apply (rule_tac i = x and j = \"l - Suc 0\" and k = l in le_trans)\napply (\n               assumption, subst Suc_le_mono[THEN sym], simp) *)\n  apply (drule_tac x = g in bspec,\n         thin_tac \"f \\<in> {j. j \\<le> m} \\<rightarrow> h ` {j. j \\<le> Suc n}\",\n         thin_tac \"sa \\<in> {j. j \\<le> l} \\<rightarrow> A\",\n         thin_tac \"f ` {j. j \\<le> m} = g ` {j. j \\<le> l}\")\n      apply (rule Pi_I, simp)\n      apply (frule_tac x = x and f = g and A = \"{j. j \\<le> l}\" and \n         B = \"h ` {j. j \\<le> Suc n}\" in funcset_mem)\n      apply simp (*\n      apply (rule_tac i = x and j = \"l - Suc 0\" and k = l in Nat.le_trans,\n             assumption, subst Suc_le_mono[THEN sym], simp) *)\n      apply (unfold bij_to_def, frule conjunct2, fold bij_to_def,\n             thin_tac \"bij_to g {j. j \\<le> l} (g ` {j. j \\<le> l})\",\n             thin_tac \"g \\<in> {j. j \\<le> l} \\<rightarrow> h ` {j. j \\<le> Suc n}\")\n      apply (simp add:image_def, erule exE, erule conjE)\n      apply (case_tac \"xa = Suc n\", simp add:inj_on_def,\n             drule_tac a = x in forall_spec) apply simp\n(*\n      apply (frule_tac i = x and j = \"l - Suc 0\" and k = l in Nat.le_trans,\n              subst Suc_le_mono[THEN sym], simp, assumption) *)\n      apply(drule_tac a = l in forall_spec, simp) \n      apply (cut_tac n1 = l and m1 = \"l - Suc 0\" in Suc_le_mono[THEN sym])\n             apply simp\n     apply (frule_tac m = xa and n = \"Suc n\" in noteq_le_less, assumption,\n            thin_tac \"xa \\<le> Suc n\",\n            frule_tac x = xa and n = \"Suc n\" in less_le_diff,\n            thin_tac \"xa < Suc n\", simp)\n      apply blast\n      apply (erule bexE, simp)\n      apply (rotate_tac -4, frule sym, thin_tac \"h (Suc n) = g l\", simp)\n   apply (frule_tac f = t and n = n and A = A and g = \"\\<lambda>k\\<in>{0::nat}. sa l\"\n          and m = 0 and B = A in jointfun_hom0,\n          simp add:Pi_def, simp)\n   apply (subgoal_tac \" \\<Sigma>\\<^sub>e M (\\<lambda>j. t j \\<cdot>\\<^sub>s h j) n \\<plusminus> sa l \\<cdot>\\<^sub>s h (Suc n) =\n           \\<Sigma>\\<^sub>e M (\\<lambda>j. (jointfun n t 0 (\\<lambda>k\\<in>{0}. sa l)) j \\<cdot>\\<^sub>s h j) (Suc n)\",\n          simp, blast) \n   apply (cut_tac H = \"carrier M\" and A = A and s = t and f = h and n = n and\n          m = 0 and t = \"\\<lambda>k\\<in>{0}. sa l\" in l_comb_jointfun_jf)\n          apply simp+ \n          apply (simp add:Pi_def)\n          apply simp\n   apply (simp add:jointfun_def sliden_def, simp)\ndone\n \nlemma (in Module) finite_lin_spanTr3:\"ideal R A \\<Longrightarrow> \n       h \\<in> {j. j \\<le> (n::nat)} \\<rightarrow> carrier M \\<longrightarrow> \n      (\\<forall>na. \\<forall>s \\<in> {j. j \\<le> (na::nat)} \\<rightarrow> A. \n       \\<forall>f\\<in> {j. j \\<le> na} \\<rightarrow> (h ` {j. j \\<le> n}). (\\<exists>t \\<in> {j. j \\<le> n} \\<rightarrow> A. \n       l_comb R M na s f = l_comb R M n t h))\"\napply (cut_tac sc_Ring)\napply (induct_tac n)\n apply (rule impI, rule allI, (rule ballI)+) \n apply (insert Nset_nonempty [of \"0\"]) \n apply (simp add:l_comb_def)\n apply (frule_tac z = \"h 0\" and h = f and t = s and n = na in \n          single_span [of A])\n apply (simp add:Pi_def)\n apply assumption+\n(********** n = 0 done ***********)\napply (rule impI, rule allI, (rule ballI)+) \n apply (frule func_pre, simp)\n apply (case_tac \"h (Suc n) \\<notin>  f ` {j. j \\<le> na}\")\n  apply (frule_tac h = h and n = n and B = \"carrier M\" and f = f and\n         m = na in two_func_imageTr, assumption+)\n  apply (drule_tac x = na in spec,\n         drule_tac x = s in bspec, assumption,\n         drule_tac x = f in bspec, assumption)\n        \n  apply (erule bexE, simp )\n  apply (thin_tac \"l_comb R M na s f = l_comb R M n t h\") \napply (simp add:l_comb_def)\n apply (subgoal_tac \"\\<Sigma>\\<^sub>e M (\\<lambda>j. t j  \\<cdot>\\<^sub>s (h j)) n =\n        \\<Sigma>\\<^sub>e M (\\<lambda>j. (jointfun n t 0 (zeroi R)) j \\<cdot>\\<^sub>s (h j)) (Suc n)\", simp,\n        thin_tac \"\\<Sigma>\\<^sub>e M (\\<lambda>j. t j \\<cdot>\\<^sub>s h j) n =\n        \\<Sigma>\\<^sub>e M (\\<lambda>j. jointfun n t 0 (zeroi R) j \\<cdot>\\<^sub>s h j) n \\<plusminus>\n        jointfun n t 0 (zeroi R) (Suc n) \\<cdot>\\<^sub>s h (Suc n)\")\n apply (frule_tac f = t and n = n and g = \"zeroi R\" and m = 0 and A = A and \n        B = A in jointfun_hom)\n        apply (rule zeroi_func, assumption+, simp, blast)\n apply (cut_tac H = \"carrier M\" and s = t and n = n and f = h and m = 0 and \n        t = \"zeroi R\" in l_comb_jointfun_jf[of _ A],\n        simp, assumption+, simp,\n        rule zeroi_func, assumption+)\n apply (simp,\n       thin_tac \"\\<Sigma>\\<^sub>e M (\\<lambda>j. jointfun n t 0 (zeroi R) j \\<cdot>\\<^sub>s h j) n =\n        \\<Sigma>\\<^sub>e M (\\<lambda>j. t j \\<cdot>\\<^sub>s h j) n\",\n        simp add:jointfun_def sliden_def zeroi_def,\n        subst sc_0_m, simp add:Pi_def,\n        subst ag_r_zero,\n        rule nsum_mem, rule allI, rule impI, rule sc_mem,\n               simp add:Pi_def Ring.ideal_subset,\n               simp add:Pi_def,\n         simp)\n\n(*** case h (Suc n) \\<notin>  f ` (Nset na) done ***)\n\napply simp\napply (frule_tac h = h and n = n and m = \"l_comb R M na s f\" in \n               prep_arrTr1 [of \"A\"], assumption+, simp)\napply (erule bexE)+\n apply (simp, (erule conjE)+)\n apply (case_tac \"l = 0\", simp)\n apply (unfold bij_to_def, frule conjunct1, frule conjunct2, fold bij_to_def)\n apply (thin_tac \"l_comb R M na s f = l_comb R M 0 sa g\")\n apply (simp add:l_comb_def)\n apply (simp add:surj_to_def, rotate_tac -1, frule sym, \n        thin_tac \"{g 0} = f ` {j. j \\<le> na}\", simp,\n        rotate_tac -6, frule sym, thin_tac \"h (Suc n) = g 0\", simp)\n apply (cut_tac f = \"zeroi R\" and n = n and g = \"\\<lambda>j. sa 0\" and m = 0 and \n         A = A and B = A in jointfun_hom0)\n        apply (simp add:zeroi_def Ring.ideal_zero)\n        apply (simp add:Pi_def)\n        apply simp\n apply (subgoal_tac \"sa 0 \\<cdot>\\<^sub>s h (Suc n) = nsum M (\\<lambda>j. (jointfun n (zeroi R) 0 \n         (\\<lambda>j. sa 0) j \\<cdot>\\<^sub>s h j)) (Suc n)\", simp,\n        thin_tac \"sa 0 \\<cdot>\\<^sub>s h (Suc n) =\n        \\<Sigma>\\<^sub>e M (\\<lambda>j. jointfun n (zeroi R) 0 (\\<lambda>j. sa 0) j \\<cdot>\\<^sub>s h j) n \\<plusminus>\n        jointfun n (zeroi R) 0 (\\<lambda>j. sa 0) (Suc n) \\<cdot>\\<^sub>s h (Suc n)\",\n        blast)\n apply simp\n apply (cut_tac n = n and f = \"\\<lambda>j. jointfun n (zeroi R) 0 (\\<lambda>j. sa 0) j \\<cdot>\\<^sub>s h j\"\n        in nsum_zeroA)\n apply (rule allI, rule impI,\n        simp add:jointfun_def zeroi_def,\n        rule sc_0_m, simp add:Pi_def, simp,\n       thin_tac \"\\<Sigma>\\<^sub>e M (\\<lambda>j. jointfun n (zeroi R) 0 (\\<lambda>j. sa 0) j \\<cdot>\\<^sub>s h j) n = \\<zero>\")\n apply (simp add:jointfun_def sliden_def,\n        subst ag_l_zero,\n        rule sc_mem, simp add:Pi_def Ring.ideal_subset,\n        simp add:Pi_def, simp)\n (**** l = 0 done ***)\napply (simp)\n apply (thin_tac \"l_comb R M na s f = l_comb R M l sa g\")\n apply (unfold bij_to_def, frule conjunct1, frule conjunct2, fold bij_to_def)\n apply (simp add:surj_to_def, rotate_tac -2, frule sym,\n        thin_tac \"g ` {j. j \\<le> l} = f ` {j. j \\<le> na}\", simp)\n  apply (subgoal_tac \"\\<exists>x\\<in>{j. j \\<le> l}. h (Suc n) = g x\")  \n  prefer 2  apply (simp add:image_def) \napply (erule bexE)\n  apply (case_tac \"x = l\", simp)\napply (frule_tac g = g and l = l and A = A and h = h and n = n and s = s and\n       m = na and f = f and l = l and sa = sa in finite_lin_spanTr3_0,\n       assumption+)\n\napply (subgoal_tac \"l_comb R M l sa g = l_comb R M (Suc (l - Suc 0)) sa g\")\n   prefer 2 apply simp\n  apply (simp del:nsum_suc Suc_pred,\n          thin_tac \"l_comb R M l sa g = l_comb R M (Suc (l - Suc 0)) sa g\",\n          simp del:nsum_suc Suc_pred add:l_comb_def)\n   apply (cut_tac f1 = \"\\<lambda>j. sa j \\<cdot>\\<^sub>s g j\" and n1 = \"l - Suc 0\" and\n          h1 = \"transpos x (Suc (l - Suc 0))\" in addition2[THEN sym],\n          thin_tac \"\\<forall>na. \\<forall>s\\<in>{j. j \\<le> na} \\<rightarrow> A.\n                \\<forall>f\\<in>{j. j \\<le> na} \\<rightarrow> h ` {j. j \\<le> n}.\n                   \\<exists>t\\<in>{j. j \\<le> n} \\<rightarrow> A.\n                      \\<Sigma>\\<^sub>e M (\\<lambda>j. s j \\<cdot>\\<^sub>s f j) na = \\<Sigma>\\<^sub>e M (\\<lambda>j. t j \\<cdot>\\<^sub>s h j) n\",\n              rule Pi_I, simp)\n       apply (rule sc_mem, \n              simp add:Pi_def Ring.ideal_subset,\n              frule_tac f = h and A = \"{j. j \\<le> Suc n}\" and B = \"carrier M\" in\n              image_sub0,\n              frule_tac x = xa and f = g and A = \"{j. j \\<le> l}\" and \n              B = \"h ` {j. j \\<le> Suc n}\" in funcset_mem, simp, simp add:subsetD)\n       apply (simp,\n             rule_tac i = x and n = l and j = l in transpos_hom,\n             assumption+, simp, assumption+)\n       apply (simp,\n              rule_tac i = x and n = l and j = l in transpos_inj,\n              assumption+, simp, assumption+)\n    apply (simp del:Suc_pred nsum_suc)\n    apply (subst l_comb_transpos[of A \"carrier M\"], assumption, simp,\n           simp, simp,\n           rule Pi_I,\n           frule_tac f = h and A = \"{j. j \\<le> Suc n}\" and B = \"carrier M\" in\n              image_sub0,\n              frule_tac x = xa and f = g and A = \"{j. j \\<le> l}\" and \n              B = \"h ` {j. j \\<le> Suc n}\" in funcset_mem, simp, simp add:subsetD,\n            simp)  \n     apply (simp del:Suc_pred, simp,\n            thin_tac \"\\<Sigma>\\<^sub>e M (\\<lambda>j. sa j \\<cdot>\\<^sub>s g j) (l - Suc 0) \\<plusminus> sa l \\<cdot>\\<^sub>s g l =\n        \\<Sigma>\\<^sub>e M (cmp (\\<lambda>j. sa j \\<cdot>\\<^sub>s g j) (transpos x l)) (l - Suc 0) \\<plusminus>\n        cmp (\\<lambda>j. sa j \\<cdot>\\<^sub>s g j) (transpos x l) l\")\n\napply (cut_tac g = \"cmp g (transpos x l)\" and l = l and A = A and\n      h = h and n = n and s = s and m = na and f = f and l = l and\n      sa = \"cmp sa (transpos x l)\" in finite_lin_spanTr3_0)\n\n   apply (frule_tac i = x and n = l and j = l in transpos_hom,\n          simp, assumption)\n   apply (cut_tac n = l in Nat.le_refl)\n   apply (frule_tac i = x and n = l and j = l in transpos_surjec, assumption+)\n   apply (frule_tac f = \"transpos x l\" and A = \"{j. j \\<le> l}\" and \n         B = \"{j. j \\<le> l}\" and g = g and C = \"g ` {j. j \\<le> l}\" in cmp_surj,\n         assumption+)\n   apply (rule_tac f = g and A = \"{j. j \\<le> l}\" and B = \"h ` {j. j \\<le> Suc n}\"\n          in func_to_img, assumption)\n   apply (simp add:bij_to_def)\n   apply (subst bij_to_def, simp)\n   apply (subgoal_tac \"cmp g (transpos x l) ` {j. j \\<le> l} = g ` {j. j \\<le> l}\",\n          simp) \n   apply (frule_tac f = \"transpos x l\" and A = \"{j. j \\<le> l}\" and \n         B = \"{j. j \\<le> l}\" and g = g and C = \"h ` {j. j \\<le> Suc n}\" in cmp_inj,\n         assumption+)\n   apply (rule_tac i = x and n = l and j = l in transpos_inj, assumption,\n          simp, assumption, simp add:bij_to_def,\n          assumption)\n   apply (simp add:cmp_fun_image, simp add:surj_to_def)\n\n   apply assumption+ \n   apply (simp add:l_comb_def)\n   apply assumption+\n   \n   apply (rule Pi_I)\n   apply (simp add:cmp_def)\n   apply (cut_tac n = l in Nat.le_refl,\n          frule_tac i = x and n = l and j = l and l = xa in transpos_mem,\n          assumption+,\n          simp add:Pi_def)\n   apply (rule Pi_I,\n          simp add:cmp_def,\n          cut_tac n = l in Nat.le_refl,\n          frule_tac i = x and n = l and j = l and l = xa in transpos_mem,\n          assumption+,\n          simp add:Pi_def)\n   apply simp\n   \n   apply (cut_tac n = l in Nat.le_refl,\n          frule_tac i = x and n = l and j = l in transpos_surjec, assumption+)\n     apply (frule_tac i = x and n = l and j = l in transpos_hom,\n           simp, assumption)\n   apply (frule_tac f = \"transpos x l\" and A = \"{i. i \\<le> l}\" and \n          B = \"{i. i \\<le> l}\" and g = g and C = \"h ` {j. j \\<le> Suc n}\" in\n          cmp_fun_image, assumption+)\n   apply (simp add:surj_to_def)\n   apply (simp add:cmp_def)\n   apply (simp add:transpos_ij_2)\n   apply (erule bexE)\n   apply (thin_tac \"\\<forall>na. \\<forall>s\\<in>{j. j \\<le> na} \\<rightarrow> A.\n                \\<forall>f\\<in>{j. j \\<le> na} \\<rightarrow> h ` {j. j \\<le> n}.\n                   \\<exists>t\\<in>{j. j \\<le> n} \\<rightarrow> A.\n                      \\<Sigma>\\<^sub>e M (\\<lambda>j. s j \\<cdot>\\<^sub>s f j) na = \\<Sigma>\\<^sub>e M (\\<lambda>j. t j \\<cdot>\\<^sub>s h j) n\")\n   apply (rename_tac n na s f l sa g x sb)\n  apply (subgoal_tac \"l_comb R M l (cmp sa (transpos x l)) \n   (cmp g (transpos x l)) = l_comb R M (Suc (l - Suc 0)) \n    (cmp sa (transpos x l)) (cmp g (transpos x l)) \",\n     simp del:Suc_pred,\n     thin_tac \"l_comb R M l (cmp sa (transpos x l)) (cmp g (transpos x l)) =\n        l_comb R M (Suc n) sb h\")\n  apply (simp del:Suc_pred add:l_comb_def, simp,\n         thin_tac \" \\<Sigma>\\<^sub>e M (\\<lambda>j. cmp sa (transpos x l) j \\<cdot>\\<^sub>s\n                  cmp g (transpos x l) j) (l - Suc 0) \\<plusminus>\n         cmp sa (transpos x l) l \\<cdot>\\<^sub>s cmp g (transpos x l) l =\n         \\<Sigma>\\<^sub>e M (\\<lambda>j. sb j \\<cdot>\\<^sub>s h j) n \\<plusminus> sb (Suc n) \\<cdot>\\<^sub>s g x\")\n   apply (rotate_tac -3, frule sym, thin_tac \"h (Suc n) = g x\", simp)\n   apply blast\n\n   apply simp\ndone\n     \nlemma (in Module) finite_lin_span:\n\"\\<lbrakk>ideal R A;  h \\<in> {j. j \\<le> (n::nat)} \\<rightarrow> carrier M; s \\<in> {j. j \\<le> (n1::nat)} \\<rightarrow> A;\n f \\<in> {j. j \\<le> n1} \\<rightarrow> h ` {j. j \\<le> n}\\<rbrakk> \\<Longrightarrow> \\<exists>t\\<in>{j. j \\<le> n} \\<rightarrow> A.\n              l_comb R M n1 s f = l_comb R M n t h\"\napply (simp add:finite_lin_spanTr3)\ndone\n\nsubsection \"Free generators\"\n\ndefinition\n  free_generator :: \"[('r, 'm) Ring_scheme, ('a, 'r, 'm1) Module_scheme, 'a set]\n        \\<Rightarrow> bool\" where\n \"free_generator R M H \\<longleftrightarrow> generator R M H \\<and>\n      (\\<forall>n. (\\<forall>s f. (s \\<in> {j. j \\<le> (n::nat)} \\<rightarrow> carrier R \\<and>\n                   f \\<in> {j. j \\<le> n} \\<rightarrow> H \\<and> inj_on f {j. j \\<le> n} \\<and> \n         l_comb R M n s f = \\<zero>\\<^bsub>M\\<^esub>) \\<longrightarrow> s \\<in> {j. j \\<le> n} \\<rightarrow> {\\<zero>\\<^bsub>R\\<^esub>}))\"\n\nlemma (in Module) free_generator_generator:\"free_generator R M H \\<Longrightarrow>\n                  generator R M H\"\nby (simp add:free_generator_def)\n\nlemma (in Module) free_generator_sub:\"free_generator R M H \\<Longrightarrow> \n                    H \\<subseteq> carrier M\"\nby (simp add:free_generator_def generator_def)\n\nlemma (in Module) free_generator_nonzero:\"\\<lbrakk>\\<not> (zeroring R); \n                free_generator R M H; h \\<in> H\\<rbrakk> \\<Longrightarrow> h \\<noteq> \\<zero>\"\napply (cut_tac sc_Ring)\napply (rule contrapos_pp, simp+)\n apply (simp add:free_generator_def, (erule conjE)+)\n apply (subgoal_tac \"(\\<lambda>t. 1\\<^sub>r\\<^bsub>R\\<^esub>) \\<in> {j. j \\<le> (0::nat)} \\<rightarrow> carrier R\")\n apply (subgoal_tac \"(\\<lambda>t. \\<zero>) \\<in> {j. j \\<le> (0::nat)} \\<rightarrow> H \\<and> \n                     inj_on (\\<lambda>t. \\<zero>) {j. j \\<le> (0::nat)} \\<and>\n        l_comb R M 0 (\\<lambda>t.  1\\<^sub>r\\<^bsub>R\\<^esub>) (\\<lambda>t.  \\<zero>) =  \\<zero>\")\n apply (subgoal_tac \"(\\<lambda>t.  1\\<^sub>r\\<^bsub>R\\<^esub>) \\<in> {j. j \\<le> (0::nat)} \\<rightarrow> {\\<zero>\\<^bsub>R\\<^esub>}\") \n prefer 2 apply blast\n apply (frule_tac f = \"\\<lambda>t. 1\\<^sub>r\\<^bsub>R\\<^esub>\" and A = \"{j. j \\<le> (0::nat)}\" and B = \"{\\<zero>\\<^bsub>R\\<^esub>}\" \n        and x = 0 in funcset_mem, simp, simp)\n apply (frule Ring.Zero_ring1 [of \"R\"], assumption+, simp)\napply simp\n apply (thin_tac \"\\<forall>n s. s \\<in> {j. j \\<le> n} \\<rightarrow> carrier R \\<and>\n           (\\<exists>f. f \\<in> {j. j \\<le> n} \\<rightarrow> H \\<and>\n                inj_on f {j. j \\<le> n} \\<and> l_comb R M n s f = \\<zero>) \\<longrightarrow>\n           s \\<in> {j. j \\<le> n} \\<rightarrow> {\\<zero>\\<^bsub>R\\<^esub>}\")\n apply (simp add:l_comb_def)\n apply (rule sc_a_0)\n apply (simp add:Ring.ring_one)\n apply (simp add:Ring.ring_one)\ndone\n\nlemma (in Module) has_free_generator_nonzeroring:\" \\<lbrakk>free_generator R M H; \n      \\<exists>p \\<in> linear_span R M (carrier R) H. p \\<noteq> \\<zero> \\<rbrakk>  \\<Longrightarrow> \\<not> zeroring R\"\napply (erule bexE, simp add:linear_span_def)\n apply (case_tac \"H = {}\", simp, simp)\n apply (erule exE, (erule bexE)+, simp,\n        thin_tac \"p = l_comb R M n s f\")\napply (rule contrapos_pp, simp+)\n apply (simp add:zeroring_def, erule conjE)\n apply (frule Ring.ring_one[of \"R\"], simp)\n apply (simp add:l_comb_def)\n apply (cut_tac n = n and f = \"\\<lambda>j. s j \\<cdot>\\<^sub>s f j\" in nsum_zeroA)\n apply (rule allI, rule impI)\n apply (simp add:free_generator_def generator_def, frule conjunct1,\n        frule_tac x = j and f = f and A = \"{j. j \\<le> n}\" and B = H in\n        funcset_mem, simp,\n        frule_tac c = \"f j\" in subsetD[of H \"carrier M\"], assumption+,\n       frule_tac x = j and f = s and A = \"{j. j \\<le> n}\" and B = \"{\\<zero>\\<^bsub>R\\<^esub>}\" in\n       funcset_mem, simp, simp add:sc_0_m)\n apply simp\ndone\n\nlemma (in Module) unique_expression1:\"\\<lbrakk>H \\<subseteq> carrier M; free_generator R M H;\n      s \\<in> {j. j \\<le> (n::nat)} \\<rightarrow> carrier R; m \\<in> {j. j \\<le> n} \\<rightarrow> H; \n      inj_on m {j. j \\<le> n}; l_comb R M n s m = \\<zero>\\<rbrakk> \\<Longrightarrow> \n                                 \\<forall>j\\<in>{j. j \\<le> n}. s j = \\<zero>\\<^bsub>R\\<^esub>\" \napply (rule ballI)\napply (simp add:free_generator_def, (erule conjE)+)\napply (subgoal_tac \"s \\<in> {j. j \\<le> n} \\<rightarrow> {\\<zero>\\<^bsub>R\\<^esub>}\")\n apply (frule_tac f = s and A = \"{j. j \\<le> n}\" and B = \"{\\<zero>\\<^bsub>R\\<^esub>}\" and x = j in \n        funcset_mem, simp, simp)\napply blast\ndone\n\nlemma (in Module) free_gen_coeff_zero:\"\\<lbrakk>H \\<subseteq> carrier M; free_generator R M H;\n       h \\<in> H; a \\<in> carrier R; a \\<cdot>\\<^sub>s h = \\<zero>\\<rbrakk> \\<Longrightarrow> a = \\<zero>\\<^bsub>R\\<^esub>\"\napply (frule unique_expression1[of H \"\\<lambda>x\\<in>{0::nat}. a\" 0 \"\\<lambda>x\\<in>{0::nat}. h\"],\n        assumption+,\n       simp,\n       simp,\n       simp add:inj_on_def,\n       simp add:l_comb_def,\n       simp)\ndone\n\nlemma (in Module) unique_expression2:\"\\<lbrakk>H \\<subseteq> carrier M; \n      f \\<in> {j. j \\<le> (n::nat)} \\<rightarrow> H; s \\<in> {j. j \\<le> n} \\<rightarrow> carrier R\\<rbrakk> \\<Longrightarrow>\n    \\<exists>m g t. g \\<in> ({j. j \\<le> (m::nat)} \\<rightarrow> H) \\<and> \n            bij_to g {j. j \\<le> (m::nat)} (f ` {j. j \\<le> n}) \\<and> \n            t \\<in> {j. j \\<le> m} \\<rightarrow> carrier R \\<and> \n            l_comb R M n s f = l_comb R M m t g\" \napply (cut_tac sc_Ring)\napply (frule Ring.whole_ideal [of \"R\"])\napply (frule_tac  A = \"carrier R\" and H = H and s = s and f = f in \n       same_together, assumption+)\napply ((erule bexE)+, erule conjE)\napply (frule_tac f = f and A = \"{j. j \\<le> n}\" in image_sub0,\n       frule_tac f = g and A = \"{j. j \\<le> card (f ` {j. j \\<le> n}) - Suc 0}\" \n       and B = \"f ` {j. j \\<le> n}\" in extend_fun[of _ _ _ \"H\"], assumption)\napply (subgoal_tac \"bij_to g {j. j \\<le> (card (f ` {j. j \\<le> n}) - Suc 0)} \n                                  (f ` {j. j \\<le> n})\")\n apply (simp add:l_comb_def, blast)\napply (simp add:bij_to_def)\napply (cut_tac finite_Collect_le_nat[of n],\n        frule finite_imageI[of \"{j. j \\<le> n}\" f])\napply (rule_tac A = \"f ` {j. j \\<le> n}\" and n = \"card (f ` {j. j \\<le> n}) - \n        Suc 0\" and f = g in Nset2finite_inj, assumption)\n using image_Nsetn_card_pos[of f n] apply simp\napply assumption\ndone\n\nlemma (in Module) unique_expression3_1:\"\\<lbrakk>H \\<subseteq> carrier M; \n      f \\<in> {l. l \\<le> (Suc n)} \\<rightarrow> H; s \\<in> {l. l \\<le> (Suc n)} \\<rightarrow> carrier R; \n      (f (Suc n)) \\<notin> f `({l. l \\<le> (Suc n)} - {Suc n})\\<rbrakk> \\<Longrightarrow> \n     \\<exists>g m t. g \\<in> {l. l \\<le> (m::nat)} \\<rightarrow> H \\<and> \n             inj_on g {l. l \\<le> (m::nat)} \\<and> \n             t \\<in> {l. l \\<le> (m::nat)} \\<rightarrow> carrier R \\<and> \n             l_comb R M (Suc n) s f = \n                 l_comb R M m t g \\<and> t m = s (Suc n) \\<and> g m = f (Suc n)\"\napply (cut_tac sc_Ring,\n       frule Ring.whole_ideal)\napply (simp add:Nset_pre1)\n apply (subst l_comb_Suc[of H \"carrier R\" s n f], assumption+)\n apply (frule func_pre[of _ _ H], frule func_pre[of _ _ \"carrier R\"])\n apply (frule unique_expression2[of H f n s], assumption+)\n apply ((erule exE)+, (erule conjE)+, simp,\n        thin_tac \"l_comb R M n s f = l_comb R M m t g\")\n apply (frule_tac f = g and n = m and A = H and g = \"\\<lambda>k\\<in>{0::nat}. f (Suc n)\"\n         and m = 0 and B = H in jointfun_hom0,\n        simp add:Pi_def, simp)\n apply (frule_tac f = t and n = m and A = \"carrier R\" and \n        g = \"\\<lambda>k\\<in>{0::nat}. s (Suc n)\"  and m = 0 and B = \"carrier R\" in \n        jointfun_hom0,\n        simp add:Pi_def, simp)\n apply (subgoal_tac \"inj_on (jointfun m g 0 (\\<lambda>k\\<in>{0}. f (Suc n))) \n                       {l. l \\<le> Suc m}\",\n    subgoal_tac \"l_comb R M m t g \\<plusminus> s (Suc n) \\<cdot>\\<^sub>s f (Suc n) =\n        l_comb R M (Suc m) (jointfun m t 0 (\\<lambda>k\\<in>{0}. s (Suc n))) \n                             (jointfun m g 0 (\\<lambda>k\\<in>{0}. f (Suc n)))\",\n    subgoal_tac \"(jointfun m t 0 (\\<lambda>k\\<in>{0}. s (Suc n))) (Suc m) = s (Suc n) \\<and>\n                 (jointfun m g 0 (\\<lambda>k\\<in>{0}. f (Suc n))) (Suc m) = f (Suc n)\",\n    simp, blast)\n apply (simp add:jointfun_def sliden_def)\n  apply (frule_tac s = t and n = m and f = g and t = \"\\<lambda>k\\<in>{0}. s (Suc n)\" and\n         m = 0 and g = \"\\<lambda>k\\<in>{0}. f (Suc n)\" in l_comb_jointfun_jj[of H \n        \"carrier R\"], assumption+,\n         simp add:Pi_def, simp,\n         simp add:Pi_def)\n  apply (simp add:l_comb_def, simp add:jointfun_def sliden_def)\n  apply (thin_tac \"jointfun m g 0 (\\<lambda>k\\<in>{0}. f (Suc n)) \\<in> {l. l \\<le> Suc m} \\<rightarrow> H\",\n  thin_tac \"jointfun m t 0 (\\<lambda>k\\<in>{0}. s (Suc n)) \\<in> {l. l \\<le> Suc m} \\<rightarrow> carrier R\",\n  thin_tac \"t \\<in> {j. j \\<le> m} \\<rightarrow> carrier R\", \n  thin_tac \"s \\<in> {j. j \\<le> n} \\<rightarrow> carrier R\")\n apply (rule_tac f = g and n = m and b = \"f (Suc n)\" and B = H in jointfun_inj,\n        assumption+)\n  apply (simp add:bij_to_def)\n  apply (unfold bij_to_def, frule conjunct1, fold bij_to_def,\n         simp add:surj_to_def)\ndone\n(*\nlemma (in Module) unique_expression3_1:\"\\<lbrakk>H \\<subseteq> carrier M; \n      f \\<in> {l. l \\<le> (Suc n)} \\<rightarrow> H; s \\<in> {l. l \\<le> (Suc n)} \\<rightarrow> carrier R; \n      (f (Suc n)) \\<notin> f `({l. l \\<le> (Suc n)} - {Suc n})\\<rbrakk> \\<Longrightarrow> \n     \\<exists>g m t. g \\<in> {l. l \\<le> (m::nat)} \\<rightarrow> H \\<and> \n             inj_on g {l. l \\<le> (m::nat)} \\<and> \n             t \\<in> {l. l \\<le> (m::nat)} \\<rightarrow> carrier R \\<and> \n             l_comb R M (Suc n) s f = l_comb R M m t g \\<and> \n              t m = s (Suc n)\"\napply (cut_tac sc_Ring,\n       frule Ring.whole_ideal)\napply (simp add:Nset_pre1)\n apply (subst l_comb_Suc[of H \"carrier R\" s n f], assumption+)\n apply (frule func_pre[of _ _ H], frule func_pre[of _ _ \"carrier R\"])\n apply (frule unique_expression2[of H f n s], assumption+)\n apply ((erule exE)+, (erule conjE)+, simp,\n        thin_tac \"l_comb R M n s f = l_comb R M m t g\")\n apply (frule_tac f = g and n = m and A = H and g = \"\\<lambda>k\\<in>{0::nat}. f (Suc n)\"\n         and m = 0 and B = H in jointfun_hom0,\n        rule univar_func_test, rule ballI, simp add:funcset_mem, simp)\n apply (frule_tac f = t and n = m and A = \"carrier R\" and \n        g = \"\\<lambda>k\\<in>{0::nat}. s (Suc n)\"  and m = 0 and B = \"carrier R\" in \n        jointfun_hom0,\n        rule univar_func_test, rule ballI, simp add:funcset_mem, simp)\n apply (subgoal_tac \"inj_on (jointfun m g 0 (\\<lambda>k\\<in>{0}. f (Suc n))) \n                       {l. l \\<le> Suc m}\",\n    subgoal_tac \"l_comb R M m t g \\<plusminus> s (Suc n) \\<cdot>\\<^sub>s f (Suc n) =\n        l_comb R M (Suc m) (jointfun m t 0 (\\<lambda>k\\<in>{0}. s (Suc n))) \n                             (jointfun m g 0 (\\<lambda>k\\<in>{0}. f (Suc n)))\",\n    subgoal_tac \"(jointfun m t 0 (\\<lambda>k\\<in>{0}. s (Suc n))) (Suc m) = s (Suc n)\",\n    simp, blast)\n apply (simp add:jointfun_def sliden_def)\n  apply (frule_tac s = t and n = m and f = g and t = \"\\<lambda>k\\<in>{0}. s (Suc n)\" and\n         m = 0 and g = \"\\<lambda>k\\<in>{0}. f (Suc n)\" in l_comb_jointfun_jj[of H \n        \"carrier R\"], assumption+,\n         rule univar_func_test, rule ballI, simp add:funcset_mem, simp,\n         rule univar_func_test, rule ballI, simp add:funcset_mem)\n  apply (simp add:l_comb_def, simp add:jointfun_def sliden_def)\n  apply (thin_tac \"jointfun m g 0 (\\<lambda>k\\<in>{0}. f (Suc n)) \\<in> {l. l \\<le> Suc m} \\<rightarrow> H\",\n  thin_tac \"jointfun m t 0 (\\<lambda>k\\<in>{0}. s (Suc n)) \\<in> {l. l \\<le> Suc m} \\<rightarrow> carrier R\",\n  thin_tac \"t \\<in> {j. j \\<le> m} \\<rightarrow> carrier R\", \n  thin_tac \"s \\<in> {j. j \\<le> n} \\<rightarrow> carrier R\")\n apply (rule_tac f = g and n = m and b = \"f (Suc n)\" and B = H in jointfun_inj,\n        assumption+)\n  apply (simp add:bij_to_def)\n  apply (unfold bij_to_def, frule conjunct1, fold bij_to_def,\n         simp add:surj_to_def)\ndone     *)\n\nlemma (in Module) unique_expression3_2:\"\\<lbrakk>H \\<subseteq> carrier M; \n      f \\<in> {k. k \\<le> (Suc n)} \\<rightarrow> H; s \\<in> {k. k \\<le> (Suc n)} \\<rightarrow> carrier R; \n      l \\<le> (Suc n); (f l) \\<notin> f ` ({k. k \\<le> (Suc n)} - {l}); l \\<noteq> Suc n\\<rbrakk> \\<Longrightarrow> \n    \\<exists>g m t. g \\<in> {l. l \\<le> (m::nat)} \\<rightarrow> H \\<and> inj_on g {l. l \\<le> (m::nat)} \\<and> \n            t \\<in> {l. l \\<le> m} \\<rightarrow> carrier R \\<and> \n            l_comb R M (Suc n) s f = l_comb R M m t g \\<and> \n             t m = s l \\<and> g m = f l\"\napply (cut_tac sc_Ring,\n       frule Ring.whole_ideal)\n apply (subst l_comb_transpos1[of \"carrier R\" H s n f l], assumption+,\n        rule noteq_le_less[of l \"Suc n\"], assumption+) \n apply (cut_tac unique_expression3_1[of H \"cmp f (transpos l (Suc n))\" n \n        \"cmp s (transpos l (Suc n))\"])\n apply ((erule exE)+, (erule conjE)+, simp)\n apply (subgoal_tac \"t m = s l \\<and> g m = f l\", blast)\n apply (thin_tac \"l_comb R M (Suc n) (cmp s (transpos l (Suc n)))\n         (cmp f (transpos l (Suc n))) = l_comb R M m t g\")\n apply (simp add:cmp_def)\n apply (subst transpos_ij_2[of l \"Suc n\" \"Suc n\"], simp+,\n        subst transpos_ij_2[of l \"Suc n\" \"Suc n\"], simp+) \n apply (rule Pi_I, simp add:cmp_def,\n        frule_tac l = x in transpos_mem[of l \"Suc n\" \"Suc n\"], simp,\n         assumption+, simp add:Pi_def)\n apply (rule Pi_I, simp add:cmp_def,\n        frule_tac l = x in transpos_mem[of l \"Suc n\" \"Suc n\"], simp,\n         assumption+, simp add:Pi_def)\n apply (frule_tac i = l and n = \"Suc n\" and j = \"Suc n\" in transpos_hom,\n           simp, assumption)\n apply (frule cmp_fun_sub_image[of \"transpos l (Suc n)\" \"{i. i \\<le> Suc n}\" \n       \"{i. i \\<le> Suc n}\" f H \"{l. l \\<le> Suc n} - {Suc n}\"], assumption+)\n       apply (rule subsetI, simp)\n       apply simp\n       apply (frule_tac i = l and n = \"Suc n\" and j = \"Suc n\" in transpos_inj,\n              simp, assumption+)\n       apply (subst injfun_elim_image[of \"transpos l (Suc n)\" \"{i. i \\<le> Suc n}\"\n        \"{i. i \\<le> Suc n}\" \"Suc n\"], assumption+, simp)\n       apply (thin_tac \"cmp f (transpos l (Suc n)) ` ({l. l \\<le> Suc n} - \n            {Suc n}) = f ` transpos l (Suc n) ` ({l. l \\<le> Suc n} - {Suc n})\")\n       apply (frule_tac i = l and n = \"Suc n\" and j = \"Suc n\" in \n              transpos_surjec, simp, assumption+)\n       apply (simp add:surj_to_def cmp_def)\n    apply (simp add:transpos_ij_2)\ndone\n\n(*\nlemma (in Module) unique_expression3_2:\"\\<lbrakk>H \\<subseteq> carrier M; \n      f \\<in> {k. k \\<le> (Suc n)} \\<rightarrow> H; s \\<in> {k. k \\<le> (Suc n)} \\<rightarrow> carrier R; \n      l \\<le> (Suc n); (f l) \\<notin> f ` ({k. k \\<le> (Suc n)} - {l}); l \\<noteq> Suc n\\<rbrakk> \\<Longrightarrow> \n    \\<exists>g m t. g \\<in> {l. l \\<le> (m::nat)} \\<rightarrow> H \\<and> inj_on g {l. l \\<le> (m::nat)} \\<and> \n            t \\<in> {l. l \\<le> m} \\<rightarrow> carrier R \\<and> \n            l_comb R M (Suc n) s f = l_comb R M m t g \\<and> t m = s l\"\napply (cut_tac sc_Ring,\n       frule Ring.whole_ideal)\n apply (subst l_comb_transpos1[of \"carrier R\" H s n f l], assumption+,\n        rule noteq_le_less[of l \"Suc n\"], assumption+) \n apply (cut_tac unique_expression3_1[of H \"cmp f (transpos l (Suc n))\" n \n        \"cmp s (transpos l (Suc n))\"])\n apply ((erule exE)+, (erule conjE)+, simp)\n apply (subgoal_tac \"t m = s l\", blast)\n apply (thin_tac \"l_comb R M (Suc n) (cmp s (transpos l (Suc n)))\n         (cmp f (transpos l (Suc n))) = l_comb R M m t g\")\n apply (simp add:cmp_def)\n apply (subst transpos_ij_2[of l \"Suc n\" \"Suc n\"], assumption+,\n        simp, assumption, simp, assumption)\n apply (rule univar_func_test, rule ballI, simp add:cmp_def,\n        frule_tac l = x in transpos_mem[of l \"Suc n\" \"Suc n\"], simp,\n         assumption+, simp add:funcset_mem)\n apply (rule univar_func_test, rule ballI, simp add:cmp_def,\n        frule_tac l = x in transpos_mem[of l \"Suc n\" \"Suc n\"], simp,\n         assumption+, simp add:funcset_mem)\n apply (frule_tac i = l and n = \"Suc n\" and j = \"Suc n\" in transpos_hom,\n           simp, assumption)\n apply (frule cmp_fun_sub_image[of \"transpos l (Suc n)\" \"{i. i \\<le> Suc n}\" \n       \"{i. i \\<le> Suc n}\" f H \"{l. l \\<le> Suc n} - {Suc n}\"], assumption+)\n       apply (rule subsetI, simp)\n       apply simp\n       apply (frule_tac i = l and n = \"Suc n\" and j = \"Suc n\" in transpos_inj,\n              simp, assumption+)\n       apply (subst injfun_elim_image[of \"transpos l (Suc n)\" \"{i. i \\<le> Suc n}\"\n        \"{i. i \\<le> Suc n}\" \"Suc n\"], assumption+, simp)\n       apply (thin_tac \"cmp f (transpos l (Suc n)) ` ({l. l \\<le> Suc n} - \n            {Suc n}) = f ` transpos l (Suc n) ` ({l. l \\<le> Suc n} - {Suc n})\")\n       apply (frule_tac i = l and n = \"Suc n\" and j = \"Suc n\" in \n              transpos_surjec, simp, assumption+)\n       apply (simp add:surj_to_def cmp_def)\n    apply (simp add:transpos_ij_2)\ndone  *)\n\nlemma (in Module) unique_expression3:\n   \"\\<lbrakk>H \\<subseteq> carrier M; f \\<in> {k. k \\<le> (Suc n)} \\<rightarrow> H;\n     s \\<in> {k. k \\<le> (Suc n)} \\<rightarrow> carrier R; l \\<le> (Suc n);\n    (f l) \\<notin> f ` ({k. k \\<le> (Suc n)} - {l})\\<rbrakk> \\<Longrightarrow> \n   \\<exists>g m t. g \\<in> {k. k \\<le> (m::nat)} \\<rightarrow> H \\<and> \n        inj_on g {k. k \\<le> m} \\<and> \n        t \\<in> {k. k \\<le> m} \\<rightarrow> carrier R \\<and> \n        l_comb R M (Suc n) s f = l_comb R M m t g \\<and> t m = s l \\<and> g m = f l\"\napply (case_tac \"l = Suc n\", simp)\n apply (cut_tac unique_expression3_1[of H f n s], blast,\n        assumption+)\n apply (rule unique_expression3_2[of H f n s l], assumption+)\ndone\n\nlemma (in Module) unique_expression4:\"free_generator R M H \\<Longrightarrow>\n     f \\<in> {k. k \\<le> (n::nat)} \\<rightarrow> H \\<and> inj_on f {k. k \\<le> n} \\<and> \n     s \\<in> {k. k \\<le> n} \\<rightarrow> carrier R \\<and> l_comb R M n s f \\<noteq> \\<zero>  \\<longrightarrow> \n(\\<exists>m g t. (g \\<in> {k. k \\<le> m} \\<rightarrow> H) \\<and> inj_on g {k. k \\<le> m} \\<and> \n        (g ` {k. k \\<le> m} \\<subseteq> f ` {k. k \\<le> n}) \\<and> (t \\<in> {k. k \\<le> m} \\<rightarrow> carrier R) \\<and>\n        (\\<forall>l \\<in> {k. k \\<le> m}. t l \\<noteq> \\<zero>\\<^bsub>R\\<^esub>) \\<and> l_comb R M n s f = l_comb R M m t g)\"\napply (cut_tac sc_Ring)\napply (frule free_generator_sub[of H])\napply (induct_tac n)\n apply (rule impI, (erule conjE)+)\n apply (frule has_free_generator_nonzeroring[of H])\n   apply (frule Ring.whole_ideal,\n         frule_tac s = s and n = 0 and f = f in \n             l_comb_mem_linear_span[of \"carrier R\" H], assumption+)\n   apply blast\n apply (simp add:l_comb_def)\n apply (subgoal_tac \"f \\<in> {j. j \\<le> (0::nat)} \\<rightarrow> H \\<and> \n        inj_on f {j. j \\<le> 0} \\<and> f ` {j. j \\<le> 0} \\<subseteq> f ` {0} \\<and> \n        s \\<in> {j. j \\<le> 0} \\<rightarrow> carrier R \\<and> (\\<forall>l \\<le> 0. s l \\<noteq> \\<zero>\\<^bsub>R\\<^esub>) \\<and>  \n        s 0 \\<cdot>\\<^sub>s (f 0) = \\<Sigma>\\<^sub>e M (\\<lambda>j. s j \\<cdot>\\<^sub>s (f j)) 0\",\n        (erule conjE)+, blast)\n apply simp\n apply (rule contrapos_pp, simp+)\n apply (cut_tac m = \"f 0\" in sc_0_m,\n           simp add:Pi_def subsetD, simp)\n\napply (rule impI) apply (erule conjE)+\n apply (frule func_pre[of _ _ H],\n        frule_tac f = f and A = \"{k. k \\<le> Suc n}\" and ?A1.0 = \"{k. k \\<le> n}\" in\n        restrict_inj, rule subsetI, simp,\n        frule func_pre[of _ _ \"carrier R\"], simp)\n apply (frule Ring.whole_ideal)\n apply (frule free_generator_sub[of H], \n         simp add:l_comb_Suc[of H \"carrier R\" s _ f])\n\n apply (case_tac \"s (Suc n) = \\<zero>\\<^bsub>R\\<^esub>\", simp)\n       apply (frule_tac x = \"Suc n\" and f = f and A = \"{k. k \\<le> Suc n}\" and\n              B = H in funcset_mem, simp,\n             frule_tac c = \"f (Suc n)\" in subsetD[of H \"carrier M\"], simp)\n       apply (frule_tac m = \"f (Suc n)\" in sc_0_m, simp)\n       apply (frule_tac n = n in l_comb_mem[of \"carrier R\" H s _ f],\n               assumption+, simp add:ag_r_zero)\n   apply ((erule exE)+, (erule conjE)+)\n   apply (frule_tac f = f and A = \"{k. k \\<le> Suc n}\" and B = H and \n          ?A1.0 = \"{k. k \\<le> n}\" and ?A2.0 = \"{k. k \\<le> Suc n}\" in im_set_mono,\n          rule subsetI, simp, simp,\n          frule_tac A = \"g ` {k. k \\<le> m}\" and B = \"f ` {k. k \\<le> n}\" and \n          C = \"f ` {k. k \\<le> Suc n}\" in subset_trans, assumption+)\n   apply blast\n\n  apply (case_tac \"l_comb R M n s f = \\<zero>\\<^bsub>M\\<^esub>\", simp,\n         frule_tac x = \"Suc n\" and f = s and A = \"{k. k \\<le> Suc n}\" and \n            B = \"carrier R\" in funcset_mem, simp,\n         frule_tac x = \"Suc n\" and f = f and A = \"{k. k \\<le> Suc n}\" and \n         B = H in funcset_mem, simp,\n         frule_tac c = \"f (Suc n)\" in subsetD[of H \"carrier M\"], assumption+,\n         frule_tac a = \"s (Suc n)\" and m = \"f (Suc n)\" in sc_mem, assumption+,\n         simp add:ag_l_zero)\n  apply (subgoal_tac \"(\\<lambda>j\\<in>{0::nat}. f (Suc n)) \\<in> {j. j \\<le> (0::nat)} \\<rightarrow> H \\<and> \n     inj_on (\\<lambda>j\\<in>{0::nat}. f (Suc n)) {j. j \\<le> (0::nat)} \\<and> \n     (\\<lambda>j\\<in>{0::nat}. f (Suc n)) ` {j. j \\<le> (0::nat)} \\<subseteq>  f  ` {k. k \\<le> (Suc n)} \\<and> \n      (\\<lambda>j\\<in>{0::nat}. s (Suc n))\\<in> {k. k \\<le> 0} \\<rightarrow> carrier R \\<and> \n      (\\<forall>l\\<le>0. (\\<lambda>j\\<in>{0::nat}. s (Suc n)) l \\<noteq> \\<zero>\\<^bsub>R\\<^esub>) \\<and>\n        s (Suc n) \\<cdot>\\<^sub>s f (Suc n) = \n           l_comb R M 0 (\\<lambda>j\\<in>{0::nat}. s (Suc n)) (\\<lambda>j\\<in>{0::nat}. f (Suc n))\")\n apply ((erule conjE)+, blast) \n apply simp\n apply (simp add:l_comb_def)\n \n apply simp\n apply ((erule exE)+, (erule conjE)+, erule exE, (erule conjE)+, simp)\n apply (thin_tac \"l_comb R M m t g \\<noteq> \\<zero>\",\n        thin_tac \"l_comb R M m t g \\<plusminus> s (Suc n) \\<cdot>\\<^sub>s f (Suc n) \\<noteq> \\<zero>\",\n        thin_tac \"l_comb R M n s f = l_comb R M m t g\")\n apply (frule_tac f = g and n = m and A = H and g = \"\\<lambda>j\\<in>{0::nat}. f (Suc n)\"\n        and m = 0 and B = H in jointfun_hom,\n        rule Pi_I, simp add:Pi_def,\n        frule_tac f = t and n = m and A = \"carrier R\" and \n         g = \"\\<lambda>j\\<in>{0::nat}. s (Suc n)\" and m = 0 and B = \"carrier R\" in \n         jointfun_hom, simp add:Pi_def, simp)\n apply (subgoal_tac \"inj_on (jointfun m g 0 (\\<lambda>j\\<in>{0}. f (Suc n)))\n    {k. k \\<le> Suc m} \\<and> \n (jointfun m g 0 (\\<lambda>j\\<in>{0}. f (Suc n))) ` {k. k \\<le> Suc m} \\<subseteq> f ` {k. k \\<le> Suc n} \\<and>\n (\\<forall>l \\<le> (Suc m). (jointfun m t 0 (\\<lambda>j\\<in>{0}. s (Suc n))) l \\<noteq> \\<zero>\\<^bsub>R\\<^esub>) \\<and>\n l_comb R M m t g \\<plusminus> s (Suc n) \\<cdot>\\<^sub>s f (Suc n) =\n    l_comb R M (Suc m) (jointfun m t 0 (\\<lambda>j\\<in>{0}. s (Suc n)))\n                            (jointfun m g 0 (\\<lambda>j\\<in>{0}. f (Suc n)))\") \n apply (erule conjE)+ apply blast\n\n apply (rule conjI) \n  apply (rule_tac f = g and n = m and b = \"f (Suc n)\" and B = H in \n         jointfun_inj, assumption+)\n  apply (rule contrapos_pp, simp+)   \n  apply (frule_tac c = \"f (Suc n)\" and A = \"g ` {k. k \\<le> m}\" and \n       B = \"f ` {k. k \\<le> n}\" in subsetD, assumption+)\n\n  apply (thin_tac \"inj_on f {k. k \\<le> n}\",\n         thin_tac \"g ` {k. k \\<le> m} \\<subseteq> f ` {k. k \\<le> n}\",\n         thin_tac \"f (Suc n) \\<in> g ` {j. j \\<le> m}\", simp add:image_def,\n         erule exE, erule conjE)\n  apply (simp add:inj_on_def,\n         drule_tac a = \"Suc n\" in forall_spec, simp,\n         thin_tac \"\\<forall>x\\<le>m. \\<forall>y\\<le>m. g x = g y \\<longrightarrow> x = y\",\n         thin_tac \"\\<forall>l\\<le>m. t l \\<noteq> \\<zero>\\<^bsub>R\\<^esub>\",\n         drule_tac a = x in forall_spec, simp, simp)\n\n  apply (rule conjI, rule subsetI)\n  apply (simp add:image_def, erule exE, erule conjE) \n   apply (case_tac \"xa = Suc m\", simp add:jointfun_def sliden_def)\n   apply (cut_tac n = \"Suc n\" in Nat.le_refl, blast)\n   apply (frule_tac m = xa and n = \"Suc m\" in noteq_le_less, assumption,\n            thin_tac \"xa \\<le> Suc m\",\n            frule_tac x = xa and n = \"Suc m\" in less_le_diff,\n            thin_tac \"xa < Suc m\", simp,\n      thin_tac \"jointfun m g 0 (\\<lambda>j\\<in>{0}. f (Suc n)) \\<in> {j. j \\<le> Suc m} \\<rightarrow> H\",\n  thin_tac \"jointfun m t 0 (\\<lambda>j\\<in>{0}. s (Suc n)) \\<in> {j. j \\<le> Suc m} \\<rightarrow> carrier R\",\n  simp add:jointfun_def)\n  apply (subgoal_tac \"g xa \\<in> {y. \\<exists>x\\<le>n. y = f x}\", simp, erule exE)\n  apply (erule conjE, frule_tac i = xb and j = n and k = \"Suc n\" in\n         le_trans, simp, blast)\n  apply (rule_tac c = \"g xa\" and A = \"{y. \\<exists>x\\<le>m. y = g x}\" and \n         B = \"{y. \\<exists>x\\<le>n. y = f x}\" in subsetD, assumption+,\n         simp, blast)\n  apply (rule conjI, rule allI, rule impI)\n  apply (case_tac \"l = Suc m\", simp add:jointfun_def sliden_def)\n    apply (frule_tac m = l and n = \"Suc m\" in noteq_le_less, assumption,\n            thin_tac \"l \\<le> Suc m\",\n            frule_tac x = l and n = \"Suc m\" in less_le_diff,\n            thin_tac \"l < Suc m\", simp,\n  thin_tac \"jointfun m g 0 (\\<lambda>j\\<in>{0}. f (Suc n)) \\<in> {j. j \\<le> Suc m} \\<rightarrow> H\",\n  thin_tac \"jointfun m t 0 (\\<lambda>j\\<in>{0}. s (Suc n)) \\<in> {j. j \\<le> Suc m} \\<rightarrow> carrier R\",\n   simp add:jointfun_def)  \n  apply (simp add:l_comb_def,\n        subst l_comb_jointfun_jj[of H \"carrier R\"], assumption+,\n        simp add:Pi_def,\n        simp add:Pi_def)\n  apply (simp add:jointfun_def sliden_def)\ndone\n\nlemma (in Module) unique_prepression5_0:\"\\<lbrakk>free_generator R M H; \n       f \\<in> {j. j \\<le> n} \\<rightarrow> H; inj_on f {j. j \\<le> n};\n       s \\<in> {j. j \\<le> n} \\<rightarrow> carrier R; g \\<in> {j. j \\<le> m} \\<rightarrow> H; \n       inj_on g {j. j \\<le> m}; t \\<in> {j. j \\<le> m} \\<rightarrow> carrier R; \n       l_comb R M n s f = l_comb R M m t g;\\<forall>j\\<le>n. s j \\<noteq> \\<zero>\\<^bsub>R\\<^esub>; \\<forall>k\\<le>m. t k \\<noteq> \\<zero>\\<^bsub>R\\<^esub>;\n       f n \\<notin> g ` {j. j \\<le> m}; 0 < n\\<rbrakk>  \\<Longrightarrow> False\" \napply (cut_tac sc_Ring,\n       frule Ring.ring_is_ag,\n       frule Ring.whole_ideal,\n       frule free_generator_sub[of H])\n apply (cut_tac l_comb_Suc[of H \"carrier R\" s \"n - Suc 0\" f],\n         simp,\n         thin_tac \"l_comb R M n s f = l_comb R M (n - Suc 0) s f \\<plusminus> s n \\<cdot>\\<^sub>s f n\")\n  apply (frule free_generator_sub[of H],\n         frule l_comb_mem[of \"carrier R\" H t m g], assumption+,\n         frule l_comb_mem[of \"carrier R\" H s \"n - Suc 0\" f], assumption+,\n         rule func_pre, simp, rule func_pre, simp,\n         cut_tac sc_mem[of \"s n\" \"f n\"])\n  apply (frule ag_pOp_closed[of \"l_comb R M (n - Suc 0) s f\" \"s n \\<cdot>\\<^sub>s f n\"],\n          assumption+,\n         frule ag_mOp_closed[of \"l_comb R M (n - Suc 0) s f\"])\n  apply (frule ag_pOp_add_l[of \"l_comb R M m t g\" \"l_comb R M (n - Suc 0) s f \\<plusminus> s n \\<cdot>\\<^sub>s f n\" \"-\\<^sub>a (l_comb R M (n - Suc 0) s f)\"], assumption+,\n        thin_tac \"l_comb R M m t g = l_comb R M (n - Suc 0) s f \\<plusminus> s n \\<cdot>\\<^sub>s f n\")\n  apply (simp add:ag_pOp_assoc[THEN sym, of \"-\\<^sub>a (l_comb R M (n - Suc 0) s f)\"\n         \"l_comb R M (n - Suc 0) s f\" \"s n \\<cdot>\\<^sub>s f n\"],\n         simp add:ag_l_inv1 ag_l_zero)\n  apply (cut_tac func_pre[of f \"n - Suc 0\" H],\n         cut_tac func_pre[of s \"n - Suc 0\" \"carrier R\"])\n  apply (frule linear_span_iOp_closedTr2[of \"carrier R\" \"H\" f \"n - Suc 0\" s],\n         assumption+)\n  apply (simp, \n          thin_tac \"-\\<^sub>a (l_comb R M (n - Suc 0) s f) =\n         l_comb R M (n - Suc 0) (\\<lambda>x\\<in>{j. j \\<le> n - Suc 0}. -\\<^sub>a\\<^bsub>R\\<^esub> (s x)) f\")\n  apply (subgoal_tac \"(\\<lambda>x\\<in>{j. j \\<le> n - Suc 0}. -\\<^sub>a\\<^bsub>R\\<^esub> (s x)) \n         \\<in> {j. j \\<le> n - Suc 0} \\<rightarrow> carrier R\")\n  apply (simp add:l_comb_add[THEN sym, of \"carrier R\" H\n          \"\\<lambda>x\\<in>{j. j \\<le> n - Suc 0}. -\\<^sub>a\\<^bsub>R\\<^esub> (s x)\" \"n - Suc 0\" f t m g],\n        thin_tac \"l_comb R M m t g \\<in> carrier M\",\n        thin_tac \"l_comb R M (n - Suc 0) s f \\<in> carrier M\",\n        thin_tac \"l_comb R M (n - Suc 0) s f \\<plusminus> s n \\<cdot>\\<^sub>s f n \\<in> carrier M\",\n        thin_tac \"l_comb R M (n - Suc 0) (\\<lambda>x\\<in>{j. j \\<le> n - Suc 0}. -\\<^sub>a\\<^bsub>R\\<^esub> (s x)) f\n         \\<in> carrier M\")\n  apply (frule jointfun_hom[of f \"n - Suc 0\" H g m H], assumption+,\n         frule jointfun_hom[of \"\\<lambda>x\\<in>{j. j \\<le> n - Suc 0}. -\\<^sub>a\\<^bsub>R\\<^esub> (s x)\" \"n - Suc 0\"\n          \"carrier R\" t m \"carrier R\"], assumption+, simp)\n (* to apply unique_expression3_1, we show\n     f n \\<notin> (jointfun (n - Suc 0) f m g) ` {j. j \\<le> n + m} *)\n apply (frule im_jointfun[of f \"n - Suc 0\" H g m H], assumption+)\n apply (frule unique_expression3_1[of H \n  \"jointfun (n + m) (jointfun (n - Suc 0) f m g) 0 (\\<lambda>x\\<in>{0::nat}. (f n))\"\n  \"n + m\"\n  \"jointfun (n + m) (jointfun (n - Suc 0) (\\<lambda>x\\<in>{j. j \\<le> n - Suc 0}. -\\<^sub>a\\<^bsub>R\\<^esub> (s x)) \n  m t) 0 (\\<lambda>x\\<in>{0::nat}. -\\<^sub>a\\<^bsub>R\\<^esub> (s n))\"])\n apply (rule Pi_I,\n        case_tac \"x \\<le> (n + m)\", simp,\n        simp add:jointfun_def[of \"n+m\"], simp add:Pi_def,\n        simp add:jointfun_def[of \"n+m\"] sliden_def, simp add:Pi_def)\n  apply (rule Pi_I,\n        case_tac \"x \\<le> (n + m)\", simp,\n        simp add:jointfun_def[of \"n+m\"], simp add:Pi_def)\n  apply (simp add:jointfun_def[of \"n+m\"] sliden_def,\n         frule Ring.ring_is_ag[of R], rule aGroup.ag_mOp_closed, assumption,\n         simp add:Pi_def)\n  apply (thin_tac \"s \\<in> {j. j \\<le> n} \\<rightarrow> carrier R\",\n         thin_tac \"t \\<in> {j. j \\<le> m} \\<rightarrow> carrier R\",\n         thin_tac \"\\<forall>j\\<le>n. s j \\<noteq> \\<zero>\\<^bsub>R\\<^esub>\",\n         thin_tac \"\\<forall>k\\<le>m. t k \\<noteq> \\<zero>\\<^bsub>R\\<^esub>\",\n         thin_tac \"l_comb R M (n + m)\n          (jointfun (n - Suc 0) (\\<lambda>x\\<in>{j. j \\<le> n - Suc 0}. -\\<^sub>a\\<^bsub>R\\<^esub> (s x)) m t)\n          (jointfun (n - Suc 0) f m g) =\n         s n \\<cdot>\\<^sub>s f n\",\n         thin_tac \"s \\<in> {j. j \\<le> n - Suc 0} \\<rightarrow> carrier R\")\n apply (thin_tac \"(\\<lambda>x\\<in>{j. j \\<le> n - Suc 0}. -\\<^sub>a\\<^bsub>R\\<^esub> (s x))\n         \\<in> {j. j \\<le> n - Suc 0} \\<rightarrow> carrier R\",\n        thin_tac \"jointfun (n - Suc 0) (\\<lambda>x\\<in>{j. j \\<le> n - Suc 0}. -\\<^sub>a\\<^bsub>R\\<^esub> (s x)) m t\n         \\<in> {j. j \\<le> n + m} \\<rightarrow> carrier R\")\n apply (simp add:Nset_pre1,\n        simp add:im_jointfunTr1[of \"n + m\" \"jointfun (n - Suc 0) f m g\" 0 \n        \"\\<lambda>x\\<in>{0}. f n\"],\n        thin_tac \"jointfun (n - Suc 0) f m g \\<in> {j. j \\<le> n + m} \\<rightarrow> H\",\n        thin_tac \"jointfun (n - Suc 0) f m g ` {j. j \\<le> n + m} =\n         f ` {j. j \\<le> n - Suc 0} \\<union> g ` {j. j \\<le> m}\",\n        simp add:jointfun_def[of \"n+m\"] sliden_def)\n apply (rule contrapos_pp, simp+, simp add:image_def, erule exE,erule conjE,\n        simp add:inj_on_def[of f],\n        drule_tac a = n in forall_spec, simp,\n        thin_tac \"\\<forall>xa\\<le>m. f x \\<noteq> g xa\",\n        drule_tac a = x in forall_spec,\n        rule_tac i = x and j = \"n - Suc 0\" and k = n in Nat.le_trans,\n        assumption+, subst Suc_le_mono[THEN sym], simp,\n        simp,\n        cut_tac n1 = x and m1 = \"x - Suc 0\" in \n               Suc_le_mono[THEN sym], simp)\n\ndefer\n apply (rule Pi_I, simp,\n        rule aGroup.ag_mOp_closed, assumption,\n        cut_tac  i = x and j = \"n - Suc 0\" and k = n in Nat.le_trans,\n        assumption, subst Suc_le_mono[THEN sym], simp,\n        simp add:Pi_def, simp, simp, simp add:Pi_def,\n        simp add:Pi_def,\n        simp add:Pi_def subsetD, assumption+, simp, simp)\n apply ((erule exE)+, (erule conjE)+, erule exE, (erule conjE)+) \n apply (cut_tac l_comb_Suc[of H \"carrier R\" \"jointfun (n + m)\n           (jointfun (n - Suc 0) (\\<lambda>x\\<in>{j. j \\<le> n - Suc 0}. -\\<^sub>a\\<^bsub>R\\<^esub> (s x)) m t) 0\n           (\\<lambda>x\\<in>{0}. -\\<^sub>a\\<^bsub>R\\<^esub> (s n))\" \"n + m\"\n           \"jointfun (n + m) (jointfun (n - Suc 0) f m g) 0 (\\<lambda>x\\<in>{0}. f n)\"],\n        simp) apply (\n       thin_tac \"l_comb R M (Suc (n + m))\n         (jointfun (n + m)\n           (jointfun (n - Suc 0) (\\<lambda>x\\<in>{j. j \\<le> n - Suc 0}. -\\<^sub>a\\<^bsub>R\\<^esub> (s x)) m t) 0\n           (\\<lambda>x\\<in>{0}. -\\<^sub>a\\<^bsub>R\\<^esub> (s n)))\n         (jointfun (n + m) (jointfun (n - Suc 0) f m g) 0 (\\<lambda>x\\<in>{0}. f n)) =\n        l_comb R M ma ta ga\")\n apply (subgoal_tac \"l_comb R M (n + m)\n         (jointfun (n + m)\n           (jointfun (n - Suc 0) (\\<lambda>x\\<in>{j. j \\<le> n - Suc 0}. -\\<^sub>a\\<^bsub>R\\<^esub> (s x)) m t) 0\n           (\\<lambda>x\\<in>{0}. -\\<^sub>a\\<^bsub>R\\<^esub> (s n)))\n         (jointfun (n + m) (jointfun (n - Suc 0) f m g) 0 (\\<lambda>x\\<in>{0}. f n)) \\<plusminus>\n        jointfun (n + m)\n         (jointfun (n - Suc 0) (\\<lambda>x\\<in>{j. j \\<le> n - Suc 0}. -\\<^sub>a\\<^bsub>R\\<^esub> (s x)) m t) 0\n         (\\<lambda>x\\<in>{0}. -\\<^sub>a\\<^bsub>R\\<^esub> (s n)) (Suc (n + m)) \\<cdot>\\<^sub>s\n        jointfun (n + m) (jointfun (n - Suc 0) f m g) 0 (\\<lambda>x\\<in>{0}. f n)\n         (Suc (n + m)) = \\<zero>\\<^bsub>M\\<^esub>\", simp,\n       thin_tac \"l_comb R M (n + m)\n         (jointfun (n + m)\n           (jointfun (n - Suc 0) (\\<lambda>x\\<in>{j. j \\<le> n - Suc 0}. -\\<^sub>a\\<^bsub>R\\<^esub> (s x)) m t) 0\n           (\\<lambda>x\\<in>{0}. -\\<^sub>a\\<^bsub>R\\<^esub> (s n)))\n         (jointfun (n + m) (jointfun (n - Suc 0) f m g) 0 (\\<lambda>x\\<in>{0}. f n)) \\<plusminus>\n        jointfun (n + m)\n         (jointfun (n - Suc 0) (\\<lambda>x\\<in>{j. j \\<le> n - Suc 0}. -\\<^sub>a\\<^bsub>R\\<^esub> (s x)) m t) 0\n         (\\<lambda>x\\<in>{0}. -\\<^sub>a\\<^bsub>R\\<^esub> (s n)) (Suc (n + m)) \\<cdot>\\<^sub>s\n        jointfun (n + m) (jointfun (n - Suc 0) f m g) 0 (\\<lambda>x\\<in>{0}. f n)\n         (Suc (n + m)) =\n        l_comb R M ma ta ga\",\n       thin_tac \"l_comb R M (n + m)\n         (jointfun (n - Suc 0) (\\<lambda>x\\<in>{j. j \\<le> n - Suc 0}. -\\<^sub>a\\<^bsub>R\\<^esub> (s x)) m t)\n         (jointfun (n - Suc 0) f m g) =\n        s n \\<cdot>\\<^sub>s f n\",\n       thin_tac \"jointfun (n - Suc 0) f m g \\<in> {j. j \\<le> n + m} \\<rightarrow> H\",\n       thin_tac \"jointfun (n - Suc 0) (\\<lambda>x\\<in>{j. j \\<le> n - Suc 0}. -\\<^sub>a\\<^bsub>R\\<^esub> (s x)) m t\n        \\<in> {j. j \\<le> n + m} \\<rightarrow> carrier R\",\n       thin_tac \"jointfun (n - Suc 0) f m g ` {j. j \\<le> n + m} =\n        f ` {j. j \\<le> n - Suc 0} \\<union> g ` {j. j \\<le> m}\")\n    apply (simp add:jointfun_def[of \"n+m\"] sliden_def)\n    apply (rotate_tac -3, frule sym, thin_tac \"\\<zero> = l_comb R M ma ta ga\")\n    apply (frule_tac s = ta and n = ma and m = ga in unique_expression1[of H],\n           assumption+)\n    apply (rotate_tac -1, \n           drule_tac x = ma in bspec, simp)\n    apply (frule_tac funcset_mem[of s \"{j. j \\<le> n}\" \"carrier R\" n], simp,\n           frule sym, thin_tac \"ta ma = -\\<^sub>a\\<^bsub>R\\<^esub> (s n)\",\n           frule aGroup.ag_inv_inv[of R \"s n\"], assumption+, simp,\n           thin_tac \" -\\<^sub>a\\<^bsub>R\\<^esub> (s n) = \\<zero>\\<^bsub>R\\<^esub>\",\n           rotate_tac -1, frule sym, thin_tac \" -\\<^sub>a\\<^bsub>R\\<^esub> \\<zero>\\<^bsub>R\\<^esub> = s n\",\n           simp add:aGroup.ag_inv_zero[of R])\n\n   apply (thin_tac \"l_comb R M (n + m)\n         (jointfun (n + m)\n           (jointfun (n - Suc 0) (\\<lambda>x\\<in>{j. j \\<le> n - Suc 0}. -\\<^sub>a\\<^bsub>R\\<^esub> (s x)) m t) 0\n           (\\<lambda>x\\<in>{0}. -\\<^sub>a\\<^bsub>R\\<^esub> (s n)))\n         (jointfun (n + m) (jointfun (n - Suc 0) f m g) 0 (\\<lambda>x\\<in>{0}. f n)) \\<plusminus>\n        jointfun (n + m)\n         (jointfun (n - Suc 0) (\\<lambda>x\\<in>{j. j \\<le> n - Suc 0}. -\\<^sub>a\\<^bsub>R\\<^esub> (s x)) m t) 0\n         (\\<lambda>x\\<in>{0}. -\\<^sub>a\\<^bsub>R\\<^esub> (s n)) (Suc (n + m)) \\<cdot>\\<^sub>s\n        jointfun (n + m) (jointfun (n - Suc 0) f m g) 0 (\\<lambda>x\\<in>{0}. f n)\n         (Suc (n + m)) =\n        l_comb R M ma ta ga\",\n        thin_tac \"ta ma =\n        jointfun (n + m)\n         (jointfun (n - Suc 0) (\\<lambda>x\\<in>{j. j \\<le> n - Suc 0}. -\\<^sub>a\\<^bsub>R\\<^esub> (s x)) m t) 0\n         (\\<lambda>x\\<in>{0}. -\\<^sub>a\\<^bsub>R\\<^esub> (s n)) (Suc (n + m))\")\n  apply (subst l_comb_jointfun_jj1[of H \"carrier R\"], assumption+,\n         rule Pi_I, simp,\n         rule aGroup.ag_mOp_closed, assumption, simp add:Pi_def,\n         simp add:Pi_def)\n  apply (simp,\n        thin_tac \"l_comb R M (n + m) (jointfun (n - Suc 0) \n       (\\<lambda>x\\<in>{j. j \\<le> n - Suc 0}. -\\<^sub>a\\<^bsub>R\\<^esub> (s x)) m t) (jointfun (n - Suc 0) f m g) =\n        s n \\<cdot>\\<^sub>s f n\",\n       thin_tac \"jointfun (n - Suc 0) f m g \\<in> {j. j \\<le> n + m} \\<rightarrow> H\",\n       thin_tac \"jointfun (n - Suc 0) (\\<lambda>x\\<in>{j. j \\<le> n - Suc 0}. -\\<^sub>a\\<^bsub>R\\<^esub> (s x)) m t\n        \\<in> {j. j \\<le> n + m} \\<rightarrow> carrier R\",\n       thin_tac \"jointfun (n - Suc 0) f m g ` {j. j \\<le> n + m} =\n        f ` {j. j \\<le> n - Suc 0} \\<union> g ` {j. j \\<le> m}\")\n  apply (simp add:jointfun_def[of \"n+m\"] sliden_def,\n         subst sc_minus_am1[THEN sym],\n         simp add:Pi_def, simp add:Pi_def subsetD,\n         simp add:ag_r_inv1,  simp add:free_generator_sub) \n  apply (assumption+,\n         rule Pi_I,\n         case_tac \"x \\<le> n + m\", simp add:jointfun_def[of \"n+m\"],\n         simp add:Pi_def,\n         simp add:jointfun_def[of \"n+m\"] sliden_def,\n         rule aGroup.ag_mOp_closed, assumption, simp add:Pi_def,\n         rule Pi_I, simp,\n          case_tac \"x \\<le> n+m\", simp add:jointfun_def[of \"n+m\"],\n          simp add:Pi_def, \n          simp add:jointfun_def[of \"n+m\"] sliden_def,\n          simp add:Pi_def)\ndone\n   \nlemma (in Module) unique_expression5:\"\\<lbrakk>free_generator R M H; \n      f \\<in> {j. j \\<le> (n::nat)} \\<rightarrow> H; inj_on f {j. j \\<le> n}; \n      s \\<in> {j. j \\<le> n} \\<rightarrow> carrier R; g \\<in> {j. j \\<le> (m::nat)} \\<rightarrow> H; \n      inj_on g {j. j \\<le> m}; t \\<in> {j. j \\<le> m} \\<rightarrow> carrier R; \n      l_comb R M n s f = l_comb R M m t g; \n     \\<forall>j \\<in> {j. j \\<le> n}. s j \\<noteq> \\<zero>\\<^bsub>R\\<^esub>; \\<forall>k \\<in> {j. j \\<le> m}. t k \\<noteq> \\<zero>\\<^bsub>R\\<^esub>\\<rbrakk> \\<Longrightarrow>\n      f ` {j. j \\<le> n} \\<subseteq> g ` {j. j \\<le> m}\"\napply (cut_tac sc_Ring, frule Ring.ring_is_ag[of R],\n       frule Ring.whole_ideal, \n       frule free_generator_sub[of H]) \napply (rule contrapos_pp, simp+, simp add:subset_eq)\n apply (erule exE, erule conjE) \n apply (case_tac \"n = 0\", simp)\n  apply (frule_tac f = t and n = m and A = \"carrier R\" and \n        g = \"\\<lambda>k\\<in>{0::nat}. -\\<^sub>a\\<^bsub>R\\<^esub> (s 0)\"  and m = 0 and B = \"carrier R\" in \n        jointfun_hom0,\n        simp add:Pi_def,\n        rule aGroup.ag_mOp_closed, assumption, simp add:Pi_def,\n        frule_tac f = g and n = m and A = H and \n        g = \"\\<lambda>k\\<in>{0::nat}. (f 0)\" and m = 0 and B = H in \n        jointfun_hom0,\n        simp add:Pi_def subsetD,\n        simp)\n  apply (frule sym, thin_tac \"l_comb R M 0 s f = l_comb R M m t g\")\n  apply (frule_tac n = 0 in l_comb_mem[of \"carrier R\" H s _ f],\n         simp add:free_generator_sub, simp+,\n         frule_tac n = m in l_comb_mem[of \"carrier R\" H t _ g],\n         simp add:free_generator_sub, assumption+)\n  apply (simp add:ag_eq_diffzero[of \"l_comb R M m t g\" \"l_comb R M 0 s f\"],\n         simp add:l_comb_def[of R M 0 s f],\n         frule free_generator_sub[of H],\n          frule_tac c = \"f 0\" in subsetD[of H \"carrier M\"], assumption+,\n          simp add:sc_minus_am1)\n  apply (subgoal_tac \"l_comb R M m t g \\<plusminus> (-\\<^sub>a\\<^bsub>R\\<^esub> (s 0)) \\<cdot>\\<^sub>s f 0 = \n          l_comb R M (Suc m) (jointfun m t 0 (\\<lambda>k\\<in>{0}. (-\\<^sub>a\\<^bsub>R\\<^esub> (s 0))))\n          (jointfun m g 0 (\\<lambda>k\\<in>{0}. f 0))\", simp)\n  apply (frule_tac f = g and n = m and B = H and b = \"f 0\" in jointfun_inj,\n          assumption+)\n  apply (frule unique_expression1[of H \"jointfun m t 0 (\\<lambda>k\\<in>{0}. (-\\<^sub>a\\<^bsub>R\\<^esub> (s 0)))\" \n        \"Suc m\" \"jointfun m g 0 (\\<lambda>k\\<in>{0}. f 0)\"], assumption+)\n apply (frule_tac x = \"Suc m\" in bspec, simp,\n        thin_tac \"\\<forall>j\\<in>{j. j \\<le> Suc m}. jointfun m t 0 (\\<lambda>k\\<in>{0}. -\\<^sub>a\\<^bsub>R\\<^esub> (s 0)) j \n          = \\<zero>\\<^bsub>R\\<^esub>\")\n  apply (simp add:jointfun_def sliden_def)\n  apply (frule aGroup.ag_inv_inv[THEN sym, of R \"s 0\"], assumption,\n         simp add:aGroup.ag_inv_zero)\n        \n  apply (thin_tac \"l_comb R M m t g \\<plusminus> (-\\<^sub>a\\<^bsub>R\\<^esub> (s 0)) \\<cdot>\\<^sub>s f 0 = \\<zero>\",\n         simp del:nsum_suc add:l_comb_def)\n  apply (cut_tac l_comb_jointfun_jj[of H \"carrier R\" t m g \"\\<lambda>k\\<in>{0}. -\\<^sub>a\\<^bsub>R\\<^esub> (s 0)\"\n               0 \"\\<lambda>k\\<in>{0}. f 0\"], simp,\n         thin_tac \"\\<Sigma>\\<^sub>e M (\\<lambda>j. jointfun m t 0 (\\<lambda>k\\<in>{0}. -\\<^sub>a\\<^bsub>R\\<^esub> (s 0)) j \\<cdot>\\<^sub>s\n                   jointfun m g 0 (\\<lambda>k\\<in>{0}. f 0) j) m =\n         \\<Sigma>\\<^sub>e M (\\<lambda>j. t j \\<cdot>\\<^sub>s g j) m\",\n         simp add:jointfun_def sliden_def, simp add:free_generator_sub,\n         assumption+,\n         rule Pi_I, simp,\n         rule aGroup.ag_mOp_closed, assumption+,\n         simp)\n apply (case_tac \"x = n\", simp,\n        rule unique_prepression5_0[of H f n s g m t], assumption+)\n apply (frule_tac j = x in l_comb_transpos1[of \"carrier R\" H s \"n - Suc 0\" f],\n        rule subsetI, simp,\n        simp+,\n        rotate_tac -1, frule sym,\n        thin_tac \"l_comb R M m t g = \n        l_comb R M n (cmp s (transpos x n)) (cmp f (transpos x n))\",\n        frule_tac i = x and n = n and j = n in transpos_hom, simp,\n           assumption,\n        frule_tac i = x and n = n and j = n in transpos_inj, simp,\n           assumption+,\n        rule_tac f = \"cmp f (transpos x n)\" and s = \"cmp s (transpos x n)\" in \n        unique_prepression5_0[of H _ n _ g m t], assumption+,\n        simp add:cmp_fun, simp add:cmp_fun, simp add:cmp_inj,\n        simp add:cmp_fun, assumption+,\n        rule allI, rule impI, simp add:cmp_def,\n        frule_tac i = x and n = n and j = n and l = j in transpos_mem,\n        simp, assumption+, blast, assumption)\n  apply (simp add:cmp_def transpos_ij_2) \n  apply simp\ndone\n \nlemma (in Module) unique_expression6:\"\\<lbrakk>free_generator R M H;\n      f \\<in> {j. j \\<le> (n::nat)} \\<rightarrow> H; inj_on f {j. j \\<le> n}; \n      s \\<in> {j. j \\<le> n} \\<rightarrow> carrier R; \n      g \\<in> {j. j \\<le> (m::nat)} \\<rightarrow> H; inj_on g {j. j \\<le> m}; \n      t \\<in> {j. j \\<le> m} \\<rightarrow> carrier R;\n      l_comb R M n s f = l_comb R M m t g;\n      \\<forall>j\\<in>{j. j \\<le> n}. s j \\<noteq> \\<zero>\\<^bsub>R\\<^esub>; \\<forall>k\\<in> {j. j \\<le> m}. t k \\<noteq> \\<zero>\\<^bsub>R\\<^esub>\\<rbrakk> \\<Longrightarrow> \n      f `{j. j \\<le> n} = g `  {j. j \\<le> m}\"\napply (rule equalityI)\napply (rule_tac  H = H and f = f and n = n and s = s and g = g and m = m and \n       t = t in unique_expression5, assumption+)\napply (rule_tac  H = H and f = g and n = m and s = t and g = f and m = n and \n       t = s in unique_expression5, assumption+)\napply (rule sym, assumption, blast, blast)\ndone\n\nlemma (in Module) unique_expression7_1:\"\\<lbrakk>free_generator R M H; \n    f \\<in> {j. j \\<le> (n::nat)} \\<rightarrow> H; inj_on f {j. j \\<le> n}; \n    s \\<in> {j. j \\<le> n} \\<rightarrow> carrier R; \n    g \\<in> {j. j \\<le> (m::nat)} \\<rightarrow> H; inj_on g {j. j \\<le> m}; \n    t \\<in> {j. j \\<le> m} \\<rightarrow> carrier R; \n    l_comb R M n s f = l_comb R M m t g; \n   \\<forall>j \\<in> {j. j \\<le> n}. s j \\<noteq> \\<zero>\\<^bsub>R\\<^esub>; \\<forall>k\\<in>{j. j \\<le> m}. t k \\<noteq> \\<zero>\\<^bsub>R\\<^esub>\\<rbrakk> \\<Longrightarrow> n = m\"\napply (frule_tac A = \"{j. j \\<le> n}\" and f = f in card_image,\n       frule_tac A = \"{j. j \\<le> m}\" and f = g in card_image)\napply (frule_tac H = H and f = f and n = n and s = s and g = g and t = t and \n       m = m in unique_expression6, assumption+)\napply (rotate_tac -3, frule sym, \n       thin_tac \"card (f ` {j. j \\<le> n}) = card ({j. j \\<le> n})\")\napply simp\ndone\n\nlemma (in Module) unique_expression7_2:\"\\<lbrakk>free_generator R M H;\n      f \\<in> {j. j \\<le> (n::nat)} \\<rightarrow> H;  inj_on f {j. j \\<le> n};\n      s \\<in> {j. j \\<le> n} \\<rightarrow> carrier R; t \\<in> {j. j \\<le> n} \\<rightarrow> carrier R; \n      l_comb R M n s f = l_comb R M n t f\\<rbrakk> \\<Longrightarrow> (\\<forall>l \\<in> {j. j \\<le> n}. s l = t l)\"\napply (cut_tac sc_Ring, frule Ring.whole_ideal)\n apply (frule free_generator_sub[of H])\n apply (frule l_comb_mem[of \"carrier R\" H s n f], assumption+,\n        frule l_comb_mem[of \"carrier R\" H t n f], assumption+)\n apply (simp add:ag_eq_diffzero[of \"l_comb R M n s f\" \"l_comb R M n t f\"])\n apply (simp add:linear_span_iOp_closedTr2[of \"carrier R\" H f n t])\n apply (frule l_comb_add1[THEN sym, of \"carrier R\" H f n s \"\\<lambda>j\\<in>{k. k \\<le> n}. -\\<^sub>a\\<^bsub>R\\<^esub> (t j)\"],\n            assumption+)\n       apply (rule Pi_I)\n       apply (simp, frule Ring.ring_is_ag[of R],\n              rule aGroup.ag_mOp_closed[of R], simp add:Pi_def)\n       apply (simp add:Pi_def)\n       apply simp\n apply (frule_tac s = \"\\<lambda>x\\<in>{x. x \\<le> n}. s x \\<plusminus>\\<^bsub>R\\<^esub> (if x \\<le> n then -\\<^sub>a\\<^bsub>R\\<^esub> (t x) else \n        undefined)\" in unique_expression1[of H _ n f], assumption+)\n  apply (rule Pi_I, simp)\n  apply (frule Ring.ring_is_ag[of R], rule aGroup.ag_pOp_closed, assumption,\n         simp add:Pi_def,\n         rule aGroup.ag_mOp_closed, assumption,\n         simp add:Pi_def, assumption+)\n  apply (rule allI, rule impI)\n  apply (subst aGroup.ag_eq_diffzero[of R],\n         simp add:Ring.ring_is_ag,\n         simp add:Pi_def, simp add:Pi_def)\n apply (drule_tac x = l in bspec, simp)\n  apply simp\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/Group-Ring-Module/Algebra7.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9032942145139149, "lm_q2_score": 0.8152324983301568, "lm_q1q2_score": 0.7363947992253553}}
{"text": "subsection\\<open>Chaum-Pedersen \\<open>\\<Sigma>\\<close>-protocol\\<close>\n\ntext\\<open>The Chaum-Pedersen \\<open>\\<Sigma>\\<close>-protocol \\<^cite>\\<open>\"DBLP:conf/crypto/ChaumP92\"\\<close> considers a relation of equality of discrete logs.\\<close>\n\ntheory Chaum_Pedersen_Sigma_Commit imports\n  Commitment_Schemes\n  Sigma_Protocols\n  Cyclic_Group_Ext\n  Discrete_Log\n  Number_Theory_Aux\n  Uniform_Sampling \nbegin \n\nlocale chaum_ped_\\<Sigma>_base = \n  fixes \\<G> :: \"'grp cyclic_group\" (structure)\n    and x :: nat\n  assumes  prime_order: \"prime (order \\<G>)\"\nbegin\n\ndefinition \"g' = \\<^bold>g [^] x\"\n\nlemma or_gt_1: \"order \\<G> > 1\" \n  using prime_order \n  using prime_gt_1_nat by blast\n\nlemma or_gt_0 [simp]:\"order \\<G> > 0\" \n  using or_gt_1 by simp\n\ntype_synonym witness = \"nat\"\ntype_synonym rand = nat \ntype_synonym 'grp' msg = \"'grp' \\<times> 'grp'\"\ntype_synonym response = nat\ntype_synonym challenge = nat\ntype_synonym 'grp' pub_in = \"'grp' \\<times> 'grp'\"\n\ndefinition \"G = do {\n    w \\<leftarrow> sample_uniform (order \\<G>);\n    return_spmf ((\\<^bold>g [^] w, g' [^] w), w)}\"\n\nlemma lossless_G: \"lossless_spmf G\"\n  by(simp add: G_def)\n\ndefinition \"challenge_space = {..< order \\<G>}\" \n\ndefinition init :: \"'grp pub_in \\<Rightarrow> witness \\<Rightarrow> (rand \\<times> 'grp msg) spmf\"\n  where \"init h w = do {\n    let (h, h') = h;  \n    r \\<leftarrow> sample_uniform (order \\<G>);\n    return_spmf (r, \\<^bold>g [^] r, g' [^] r)}\"\n\nlemma lossless_init: \"lossless_spmf (init h w)\" \n  by(simp add:  init_def)\n\ndefinition \"response r w e = return_spmf ((w*e + r) mod (order \\<G>))\"\n\nlemma lossless_response: \"lossless_spmf (response r w  e)\"\n  by(simp add: response_def)\n\ndefinition check :: \"'grp pub_in \\<Rightarrow> 'grp msg \\<Rightarrow> challenge \\<Rightarrow> response \\<Rightarrow> bool\"\n  where \"check h a e z =  (fst a \\<otimes> (fst h [^] e) = \\<^bold>g [^] z \\<and> snd a \\<otimes> (snd h [^] e) = g' [^] z \\<and> fst a \\<in> carrier \\<G> \\<and> snd a \\<in> carrier \\<G>)\"\n\ndefinition R :: \"('grp pub_in \\<times> witness) set\"\n  where \"R = {(h, w). (fst h = \\<^bold>g [^] w \\<and> snd h = g' [^] w)}\"\n\ndefinition S2 :: \"'grp pub_in \\<Rightarrow> challenge \\<Rightarrow> ('grp msg, response) sim_out spmf\"\n  where \"S2 H c = do {\n  let (h, h') = H;\n  z \\<leftarrow> (sample_uniform (order \\<G>));\n  let a = \\<^bold>g [^] z \\<otimes> inv (h [^] c); \n  let a' =  g' [^] z \\<otimes> inv (h' [^] c);\n  return_spmf ((a,a'), z)}\"\n\ndefinition ss_adversary :: \"'grp pub_in \\<Rightarrow> ('grp msg, challenge, response) conv_tuple \\<Rightarrow> ('grp msg, challenge, response) conv_tuple \\<Rightarrow> nat spmf\"\n  where \"ss_adversary x' c1 c2 = do {\n    let ((a,a'), e, z) = c1;\n    let ((b,b'), e', z') = c2;\n    return_spmf (if (e mod order \\<G> > e' mod order \\<G>) then (nat ((int z - int z') * (fst (bezw ((e mod order \\<G> - e' mod order \\<G>) mod order \\<G>) (order \\<G>))) mod order \\<G>)) else \n(nat ((int z' - int z) * (fst (bezw ((e' mod order \\<G> - e mod order \\<G>) mod order \\<G>) (order \\<G>))) mod order \\<G>)))}\"\n\ndefinition \"valid_pub = carrier \\<G> \\<times> carrier \\<G>\"\n\nend \n\nlocale chaum_ped_\\<Sigma> = chaum_ped_\\<Sigma>_base + cyclic_group \\<G>\nbegin\n\nlemma g'_in_carrier [simp]: \"g' \\<in> carrier \\<G>\"\n  by(simp add: g'_def) \n\nsublocale chaum_ped_sigma: \\<Sigma>_protocols_base init response check R S2 ss_adversary challenge_space valid_pub \n  by unfold_locales (auto simp add: R_def valid_pub_def)\n\nlemma completeness: \n  shows \"chaum_ped_sigma.completeness\"\nproof-\n  have \"g' [^] y \\<otimes> (g' [^] w') [^] e = g' [^] ((w' * e + y) mod order \\<G>)\" for y e w'\n    by (simp add: Groups.add_ac(2) pow_carrier_mod nat_pow_pow nat_pow_mult)\n  moreover have \"\\<^bold>g [^] y \\<otimes> (\\<^bold>g [^] w') [^] e = \\<^bold>g [^] ((w' * e + y) mod order \\<G>)\" for y e w'\n    by (metis add.commute nat_pow_pow nat_pow_mult pow_generator_mod generator_closed mod_mult_right_eq)  \n  ultimately show ?thesis\n    unfolding chaum_ped_sigma.completeness_def chaum_ped_sigma.completeness_game_def\n    by(auto simp add: R_def challenge_space_def init_def check_def response_def split_def bind_spmf_const)\nqed\n\nlemma hvzk_xr'_rewrite:\n  assumes r: \"r < order \\<G>\"\n  shows \"((w*c + r) mod (order \\<G>) mod (order \\<G>) + (order \\<G>) * w*c - w*c) mod (order \\<G>) = r\"\n(is \"?lhs = ?rhs\")\nproof-\n  have \"?lhs = (w*c + r  + (order \\<G>) * w*c- w*c) mod (order \\<G>)\" \n    by (metis Nat.add_diff_assoc Num.of_nat_simps(1) One_nat_def add_less_same_cancel2 less_imp_le_nat \n        mod_add_left_eq mult.assoc mult_0_right n_less_m_mult_n nat_neq_iff not_add_less2 of_nat_0_le_iff prime_gt_1_nat prime_order) \n  thus ?thesis using r \n    by (metis ab_semigroup_add_class.add_ac(1) ab_semigroup_mult_class.mult_ac(1) diff_add_inverse mod_if mod_mult_self2)\nqed\n\nlemma hvzk_h_sub_rewrite:\n  assumes \"h = \\<^bold>g [^] w\"  \n    and z: \"z < order \\<G>\" \n  shows \"\\<^bold>g [^] ((z + (order \\<G>)* w * c - w*c)) = \\<^bold>g [^] z \\<otimes> inv (h [^] c)\" \n    (is \"?lhs = ?rhs\")\nproof(cases \"w = 0\")\n  case True\n  then show ?thesis using assms by simp\nnext\n  case w_gt_0: False\n  then show ?thesis \n  proof-\n    have \"(z + order \\<G> * w * c - w * c) = (z + (order \\<G> * w * c- w * c))\"\n      using z by (simp add: less_imp_le_nat mult_le_mono) \n    then have lhs: \"?lhs = \\<^bold>g [^] z \\<otimes> \\<^bold>g [^] ((order \\<G>) * w *c - w*c)\" \n      by(simp add: nat_pow_mult)\n    have \" \\<^bold>g [^] ((order \\<G>) * w *c - w*c) =  inv (h [^] c)\"  \n    proof(cases \"c = 0\")\n      case True\n      then show ?thesis using lhs by simp\n    next\n      case False\n      hence *: \"((order \\<G>)*w *c - w*c) > 0\" using assms w_gt_0 \n        using gr0I mult_less_cancel2 n_less_m_mult_n numeral_nat(7) prime_gt_1_nat prime_order zero_less_diff by presburger\n      then have \" \\<^bold>g [^] ((order \\<G>)*w*c - w*c) =  \\<^bold>g [^] int ((order \\<G>)*w*c - w*c)\"\n        by (simp add: int_pow_int) \n      also have \"... = \\<^bold>g [^] int ((order \\<G>)*w*c) \\<otimes> inv (\\<^bold>g [^] (w*c))\" \n        using int_pow_diff[of \"\\<^bold>g\" \"order \\<G> * w * c\" \"w * c\"] * generator_closed int_ops(6) int_pow_neg int_pow_neg_int by presburger\n\n      also have \"... = \\<^bold>g [^] ((order \\<G>)*w*c) \\<otimes> inv (\\<^bold>g [^] (w*c))\"\n        by (metis int_pow_int) \n      also have \"... = \\<^bold>g [^] ((order \\<G>)*w*c) \\<otimes> inv ((\\<^bold>g [^] w) [^] c)\"\n        by(simp add: nat_pow_pow)\n      also have \"... = \\<^bold>g [^] ((order \\<G>)*w*c) \\<otimes> inv (h [^] c)\"\n        using assms by simp\n      also have \"... = \\<one> \\<otimes> inv (h [^] c)\"\n        using generator_pow_order\n        by (metis generator_closed mult_is_0 nat_pow_0 nat_pow_pow)\n      ultimately show ?thesis\n        by (simp add: assms(1)) \n    qed\n    then show ?thesis using lhs by simp\n  qed\nqed\n\nlemma hvzk_h_sub2_rewrite:\n  assumes  \"h' = g' [^] w\" \n    and z: \"z < order \\<G>\" \n  shows \"g' [^] ((z + (order \\<G>)*w*c - w*c))  = g' [^] z \\<otimes> inv (h' [^] c)\" \n    (is \"?lhs = ?rhs\")\nproof(cases \"w = 0\")\n  case True\n  then show ?thesis \n    using assms by (simp add: g'_def)\nnext\n  case w_gt_0: False\n  then show ?thesis \n  proof-\n    have \"g' = \\<^bold>g [^] x\" using g'_def by simp\n    have g'_carrier: \"g' \\<in> carrier \\<G>\" using g'_def by simp\n    have 1: \"g' [^] ((order \\<G>)*w*c- w*c) = inv (h' [^] c)\"\n    proof(cases \"c = 0\")\n      case True\n      then show ?thesis by simp\n    next\n      case False\n      hence *: \"((order \\<G>)*w*c - w*c) > 0\" \n        using assms mult_strict_mono w_gt_0 prime_gt_1_nat prime_order by auto \n      then have \" g' [^] ((order \\<G>)*w*c - w*c) = g' [^] (int (order \\<G> * w * c) - int (w * c))\"\n        by (metis int_ops(6) int_pow_int of_nat_0_less_iff order.irrefl)\n      also have \"... = g' [^] ((order \\<G>)*w*c) \\<otimes> inv (g' [^] (w*c))\" \n        by (metis g'_carrier int_pow_diff int_pow_int) \n      also have \"... = g' [^] ((order \\<G>)*w*c) \\<otimes> inv (h' [^] c)\"\n        by(simp add: nat_pow_pow assms)\n      also have \"... = \\<one> \\<otimes> inv (h' [^] c)\" \n        by (metis g'_carrier nat_pow_one nat_pow_pow pow_order_eq_1)\n      ultimately show ?thesis\n        by (simp add: assms(1)) \n    qed\n    have \"(z + order \\<G> * w * c - w * c) = (z + (order \\<G> * w * c - w * c))\"\n      using z by (simp add: less_imp_le_nat mult_le_mono) \n    then have lhs: \"?lhs = g' [^] z \\<otimes> g' [^] ((order \\<G>)*w*c - w*c)\" \n      by(auto simp add: nat_pow_mult)\n    then show ?thesis using 1 by simp\n  qed\nqed\n\nlemma hv_zk2:\n  assumes \"(H, w) \\<in> R\" \n  shows \"chaum_ped_sigma.R H w c = chaum_ped_sigma.S H c\"\n  including monad_normalisation\nproof-\n  have H: \"H = (\\<^bold>g [^] (w::nat), g' [^] w)\" \n    using assms R_def  by(simp add: prod.expand)\n  have g'_carrier: \"g' \\<in> carrier \\<G>\" using g'_def by simp\n  have \"chaum_ped_sigma.R H w c  = do {\n    let (h, h') = H;\n    r \\<leftarrow> sample_uniform (order \\<G>);\n    let z = (w*c + r) mod (order \\<G>);\n    let a = \\<^bold>g [^] ((z + (order \\<G>) * w*c - w*c) mod (order \\<G>)); \n    let a' = g' [^] ((z + (order \\<G>) * w*c - w*c) mod (order \\<G>));\n    return_spmf ((a,a'),c, z)}\"\n    apply(simp add: chaum_ped_sigma.R_def Let_def response_def split_def init_def)\n    using assms hvzk_xr'_rewrite \n    by(simp cong: bind_spmf_cong_simp)\n  also have \"... = do {\n    let (h, h') = H;\n    z \\<leftarrow> map_spmf (\\<lambda> r. (w*c + r) mod (order \\<G>)) (sample_uniform (order \\<G>));\n    let a = \\<^bold>g [^] ((z + (order \\<G>) * w*c - w*c) mod (order \\<G>)); \n    let a' = g' [^] ((z + (order \\<G>) * w*c - w*c) mod (order \\<G>));\n    return_spmf ((a,a'),c, z)}\"\n    by(simp add: bind_map_spmf Let_def o_def)\n  also have \"... = do {\n    let (h, h') = H;\n    z \\<leftarrow> (sample_uniform (order \\<G>));\n    let a = \\<^bold>g [^] ((z + (order \\<G>) * w*c - w*c) mod (order \\<G>)); \n    let a' = g' [^] ((z + (order \\<G>) * w*c - w*c) mod (order \\<G>));\n    return_spmf ((a,a'),c, z)}\"\n    by(simp add: samp_uni_plus_one_time_pad)\n  also have \"... = do {\n    let (h, h') = H;\n    z \\<leftarrow> (sample_uniform (order \\<G>));\n    let a = \\<^bold>g [^] z \\<otimes> inv (h [^] c); \n    let a' = g' [^] ((z + (order \\<G>) * w*c - w*c) mod (order \\<G>));\n    return_spmf ((a,a'),c, z)}\"\n    using hvzk_h_sub_rewrite assms\n    apply(simp add: Let_def H)\n    apply(intro bind_spmf_cong[OF refl]; clarsimp?)\n    by (simp add: pow_generator_mod)\n  also have \"... = do {\n    let (h, h') = H;\n    z \\<leftarrow> (sample_uniform (order \\<G>));\n    let a = \\<^bold>g [^] z \\<otimes> inv (h [^] c); \n    let a' = g' [^] ((z + (order \\<G>)*w*c - w*c));\n    return_spmf ((a,a'),c, z)}\"\n     using g'_carrier pow_carrier_mod[of \"g'\"] by simp\n   also have \"... = do {\n    let (h, h') = H;\n    z \\<leftarrow> (sample_uniform (order \\<G>));\n    let a = \\<^bold>g [^] z \\<otimes> inv (h [^] c); \n    let a' =  g' [^] z \\<otimes> inv (h' [^] c);\n    return_spmf ((a,a'),c, z)}\"\n     using hvzk_h_sub2_rewrite assms H\n     by(simp cong: bind_spmf_cong_simp)\n   ultimately show ?thesis \n     unfolding chaum_ped_sigma.S_def chaum_ped_sigma.R_def\n     by(simp add: init_def S2_def split_def Let_def \\<Sigma>_protocols_base.S_def bind_map_spmf map_spmf_conv_bind_spmf)\nqed\n\nlemma HVZK: \n  shows \"chaum_ped_sigma.HVZK\"\n    unfolding chaum_ped_sigma.HVZK_def \n    by(auto simp add: hv_zk2 R_def valid_pub_def   S2_def check_def cyclic_group_assoc)\n\nlemma ss_rewrite1:\n  assumes \"fst h \\<in> carrier \\<G>\"\n    and \"a \\<in> carrier \\<G>\" \n    and e: \"e < order \\<G>\" \n    and \"a \\<otimes> fst h [^] e = \\<^bold>g [^] z\"  \n    and e': \"e' < e\"\n    and \"a \\<otimes> fst h [^] e' = \\<^bold>g [^] z'\"\n  shows \"fst h = \\<^bold>g [^] ((int z - int z') * inverse (e - e') (order \\<G>) mod int (order \\<G>))\"\nproof-\n  have gcd: \"gcd (e - e') (order \\<G>) = 1\" \n    using e e' prime_field prime_order by simp\n  have \"a = \\<^bold>g [^] z \\<otimes> inv (fst h [^] e)\" \n    using assms\n    by (simp add: assms inv_solve_right)\n  moreover have \"a = \\<^bold>g [^] z' \\<otimes> inv (fst h [^] e')\" \n    using assms\n    by (simp add: assms inv_solve_right)\n  ultimately have \"\\<^bold>g [^] z \\<otimes> fst h [^] e' = \\<^bold>g [^] z' \\<otimes> fst h [^] e\"\n    by (metis (no_types, lifting) assms cyclic_group_assoc cyclic_group_commute nat_pow_closed)\n  moreover obtain t :: nat where t: \"fst h = \\<^bold>g [^] t\"\n    using assms generatorE by blast\n  ultimately have \"\\<^bold>g [^] (z + t * e') = \\<^bold>g [^] (z' + t * e)\" \n    using nat_pow_pow \n    by (simp add: nat_pow_mult)\n  hence \"[z + t * e' = z' + t * e] (mod order \\<G>)\"\n    using group_eq_pow_eq_mod or_gt_0 by blast\n  hence \"[int z + int t * int e' = int z' + int t * int e] (mod order \\<G>)\"\n    using cong_int_iff by force\n  hence \"[int z - int z' = int t * int e - int t * int e'] (mod order \\<G>)\"\n    by (smt cong_diff_iff_cong_0)\n  hence \"[int z - int z' = int t * (int e - int e')] (mod order \\<G>)\"\n    by (simp add: right_diff_distrib)\n  hence \"[int z - int z' = int t * (e - e')] (mod order \\<G>)\" \n    using assms by (simp add: of_nat_diff)\n  hence \"[(int z - int z') * fst (bezw (e - e') (order \\<G>))  = int t * (e - e') * fst (bezw (e - e') (order \\<G>))] (mod order \\<G>)\"\n    using cong_scalar_right by blast\n  hence \"[(int z - int z') * fst (bezw (e - e') (order \\<G>))  = int t * ((e - e') * fst (bezw (e - e') (order \\<G>)))] (mod order \\<G>)\" \n    by (simp add: more_arith_simps(11))\n  hence \"[(int z - int z') * fst (bezw (e - e') (order \\<G>))  = int t * 1] (mod order \\<G>)\" \n    by (metis (no_types, opaque_lifting) cong_scalar_left cong_trans inverse gcd)\n  hence \"[(int z - int z') * fst (bezw (e - e') (order \\<G>)) mod order \\<G>  = t] (mod order \\<G>)\" \n    by simp\n  hence \"[nat ((int z - int z') * fst (bezw (e - e') (order \\<G>)) mod order \\<G>)  = t] (mod order \\<G>)\" \n    by (metis cong_def int_ops(9) mod_mod_trivial nat_int)\n  hence \"\\<^bold>g [^] (nat ((int z - int z') * fst (bezw (e - e') (order \\<G>)) mod order \\<G>))  = \\<^bold>g [^] t\" \n    using order_gt_0 order_gt_0_iff_finite pow_generator_eq_iff_cong by blast\n  thus ?thesis using t by simp\nqed\n\nlemma ss_rewrite2:\n  assumes \"fst h \\<in> carrier \\<G>\"\n    and \"snd h \\<in> carrier \\<G>\" \n    and \"a \\<in> carrier \\<G>\" \n    and \"b \\<in> carrier \\<G>\"\n    and \"e < order \\<G>\" \n    and \"a \\<otimes> fst h [^] e = \\<^bold>g [^] z\" \n    and \"b \\<otimes> snd h [^] e = g' [^] z\"\n    and \"e' < e\" \n    and \"a \\<otimes> fst h [^] e' = \\<^bold>g [^] z'\"\n    and \"b \\<otimes> snd h [^] e' = g' [^] z'\"\n  shows \"snd h = g' [^] ((int z - int z') * inverse (e - e') (order \\<G>) mod int (order \\<G>))\"\nproof-\n  have gcd: \"gcd (e - e') (order \\<G>) = 1\" \n    using prime_field assms prime_order by simp\n  have \"b = g' [^] z \\<otimes> inv (snd h [^] e)\"\n    by (simp add: assms inv_solve_right)\n  moreover have \"b = g' [^] z' \\<otimes> inv (snd h [^] e')\"\n    by (metis assms(2) assms(4) assms(10) g'_def generator_closed group.inv_solve_right' group_l_invI l_inv_ex nat_pow_closed)\n  ultimately have \"g' [^] z \\<otimes> snd h [^] e' = g' [^] z' \\<otimes> snd h [^] e\" \n    by (metis (no_types, lifting) assms cyclic_group_assoc cyclic_group_commute nat_pow_closed)\n  moreover obtain t :: nat where t: \"snd h = \\<^bold>g [^] t\"\n    using assms(2) generatorE by blast\n  ultimately have \"\\<^bold>g [^] (x * z + t * e') = \\<^bold>g [^] (x * z' + t * e)\"\n    using g'_def nat_pow_pow\n    by (simp add: nat_pow_mult) \n  hence \"[x * z + t * e' = x * z' + t * e] (mod order \\<G>)\"\n    using group_eq_pow_eq_mod order_gt_0 by blast\n  hence \"[int x * int z + int t * int e' = int x * int z' + int t * int e] (mod order \\<G>)\"\n    by (metis Groups.add_ac(2) Groups.mult_ac(2) cong_int_iff int_ops(7) int_plus)\n  hence \"[int x * int z - int x * int z' = int t * int e - int t * int e'] (mod order \\<G>)\"\n    by (smt cong_diff_iff_cong_0)\n  hence \"[int x * (int z - int z') = int t * (int e - int e')] (mod order \\<G>)\"\n    by (simp add: int_distrib(4))\n  hence \"[int x * (int z - int z') = int t * (e - e')] (mod order \\<G>)\"\n    using assms by (simp add: of_nat_diff)\n  hence \"[(int x * (int z - int z')) * fst (bezw (e - e') (order \\<G>)) = int t * (e - e') * fst (bezw (e - e') (order \\<G>))] (mod order \\<G>)\"\n    using cong_scalar_right by blast\n  hence \"[(int x * (int z - int z')) * fst (bezw (e - e') (order \\<G>)) = int t * ((e - e') * fst (bezw (e - e') (order \\<G>)))] (mod order \\<G>)\"\n    by (simp add: more_arith_simps(11))\n  hence *: \"[(int x * (int z - int z')) * fst (bezw (e - e') (order \\<G>)) = int t * 1] (mod order \\<G>)\"\n    by (metis (no_types, opaque_lifting) cong_scalar_left cong_trans gcd inverse)\n  hence \"[nat ((int x * (int z - int z')) * fst (bezw (e - e') (order \\<G>)) mod order \\<G>) = t] (mod order \\<G>)\"\n    by (metis cong_def cong_mod_right more_arith_simps(6) nat_int zmod_int)\n  hence \"\\<^bold>g [^] (nat ((int x * (int z - int z')) * fst (bezw (e - e') (order \\<G>)) mod order \\<G>)) = \\<^bold>g [^] t\"\n    using order_gt_0 order_gt_0_iff_finite pow_generator_eq_iff_cong by blast\n  thus ?thesis using t \n    by (metis (mono_tags, opaque_lifting) * cong_def g'_def generator_closed int_pow_int int_pow_pow mod_mult_right_eq more_arith_simps(11) more_arith_simps(6) pow_generator_mod_int)\nqed\n\nlemma ss_rewrite_snd_h:\n  assumes e_e'_mod: \"e' mod order \\<G> < e mod order \\<G>\"\n    and h_mem: \"snd h \\<in> carrier \\<G>\"\n    and a_mem: \"snd a \\<in> carrier \\<G>\"\n    and a1: \"snd a \\<otimes> snd h [^] e = g' [^] z\" \n    and a2: \"snd a \\<otimes> snd h [^] e' = g' [^] z'\" \n  shows \"snd h = g' [^] ((int z - int z') * fst (bezw ((e mod order \\<G> - e' mod order \\<G>) mod order \\<G>) (order \\<G>)) mod int (order \\<G>))\"\nproof-\n  have gcd: \"gcd ((e mod order \\<G> - e' mod order \\<G>) mod order \\<G>) (order \\<G>) = 1\"\n    using prime_field \n    by (simp add: assms less_imp_diff_less linorder_not_le prime_order)\n  have \"snd a = g' [^] z \\<otimes> inv (snd h [^] e)\"\n    using a1 \n    by (metis (no_types, lifting) Group.group.axioms(1) h_mem a_mem group.inv_closed group_l_invI l_inv_ex monoid.m_assoc nat_pow_closed r_inv r_one)\n  moreover have \"snd a = g' [^] z' \\<otimes> inv (snd h [^] e')\"\n    by (metis a2 h_mem a_mem g'_def generator_closed group.inv_solve_right' group_l_invI l_inv_ex nat_pow_closed)\n  ultimately have \"g' [^] z \\<otimes> snd h [^] e' = g' [^] z' \\<otimes> snd h [^] e\" \n    by (metis (no_types, lifting) a2 h_mem a_mem a1 cyclic_group_assoc cyclic_group_commute nat_pow_closed)\n  moreover obtain t :: nat where t: \"snd h = \\<^bold>g [^] t\"\n    using assms(2) generatorE by blast\n  ultimately have \"\\<^bold>g [^] (x * z + t * e') = \\<^bold>g [^] (x * z' + t * e)\"\n    using g'_def nat_pow_pow\n    by (simp add: nat_pow_mult) \n  hence \"[x * z + t * e' = x * z' + t * e] (mod order \\<G>)\"\n    using group_eq_pow_eq_mod order_gt_0 by blast\n  hence \"[int x * int z + int t * int e' = int x * int z' + int t * int e] (mod order \\<G>)\"\n    by (metis Groups.add_ac(2) Groups.mult_ac(2) cong_int_iff int_ops(7) int_plus)\n  hence \"[int x * int z - int x * int z' = int t * int e - int t * int e'] (mod order \\<G>)\"\n    by (smt cong_diff_iff_cong_0)\n  hence \"[int x * (int z - int z') = int t * (int e - int e')] (mod order \\<G>)\"\n    by (simp add: int_distrib(4))\n  hence \"[int x * (int z - int z') = int t * (int e mod order \\<G> - int e' mod order \\<G>) mod order \\<G>] (mod order \\<G>)\"\n    by (metis (no_types, lifting) cong_def mod_diff_eq mod_mod_trivial mod_mult_right_eq)\n  hence *: \"[int x * (int z - int z') = int t * (e mod order \\<G> - e' mod order \\<G>) mod order \\<G>] (mod order \\<G>)\"\n    by (simp add: assms(1) int_ops(9) less_imp_le_nat of_nat_diff)\n  hence \"[int x * (int z - int z') * fst (bezw ((e mod order \\<G> - e' mod order \\<G>) mod order \\<G>) (order \\<G>)) \n               = int t * ((e mod order \\<G> - e' mod order \\<G>) mod order \\<G> \n                  * fst (bezw ((e mod order \\<G> - e' mod order \\<G>) mod order \\<G>) (order \\<G>)))] (mod order \\<G>)\"\n    by (metis (no_types, lifting) cong_mod_right cong_scalar_right less_imp_diff_less mod_if more_arith_simps(11) or_gt_0 unique_euclidean_semiring_numeral_class.pos_mod_bound)\n  hence \"[int x * (int z - int z') * fst (bezw ((e mod order \\<G> - e' mod order \\<G>) mod order \\<G>) (order \\<G>)) \n               = int t * 1] (mod order \\<G>)\"\n    by (meson Number_Theory_Aux.inverse * gcd cong_scalar_left cong_trans)\n  hence \"\\<^bold>g [^] (int x * (int z - int z') * fst (bezw ((e mod order \\<G> - e' mod order \\<G>) mod order \\<G>) (order \\<G>))) = \\<^bold>g [^] t\"\n    by (metis cong_def int_pow_int more_arith_simps(6) pow_generator_mod_int)\n  thus ?thesis using t \n    by (metis (mono_tags, opaque_lifting) g'_def generator_closed int_pow_int int_pow_pow mod_mult_right_eq more_arith_simps(11) pow_generator_mod_int)\nqed\n\nlemma special_soundness:\n  shows \"chaum_ped_sigma.special_soundness\"\n  unfolding chaum_ped_sigma.special_soundness_def \n  apply(auto simp add: challenge_space_def check_def ss_adversary_def R_def valid_pub_def)\n  using ss_rewrite2 ss_rewrite1 by auto\n\ntheorem \\<Sigma>_protocol:  \"chaum_ped_sigma.\\<Sigma>_protocol\"\n  by(simp add: chaum_ped_sigma.\\<Sigma>_protocol_def completeness HVZK special_soundness)\n\nsublocale chaum_ped_\\<Sigma>_commit: \\<Sigma>_protocols_to_commitments init response check R S2 ss_adversary challenge_space valid_pub G\n  apply unfold_locales\n      apply(auto simp add: \\<Sigma>_protocol lossless_init lossless_response lossless_G)\n  by(simp add: R_def G_def)\n\nsublocale dis_log: dis_log \\<G> \n  unfolding dis_log_def by simp\n\nsublocale dis_log_alt: dis_log_alt \\<G> x \n  unfolding dis_log_alt_def by simp\n\nlemma reduction_to_dis_log: \n  shows \"chaum_ped_\\<Sigma>_commit.rel_advantage \\<A> = dis_log.advantage (dis_log_alt.adversary3 \\<A>)\"\nproof-\n  have \"chaum_ped_\\<Sigma>_commit.rel_game \\<A> = TRY do {\n    w \\<leftarrow> sample_uniform (order \\<G>);\n    let (h,w) = ((\\<^bold>g [^] w, g' [^] w), w);\n    w' \\<leftarrow> \\<A> h;\n    return_spmf ((fst h = \\<^bold>g [^] w' \\<and> snd h = g' [^] w'))} ELSE return_spmf False\"\n    unfolding chaum_ped_\\<Sigma>_commit.rel_game_def \n    by(simp add:  G_def R_def)\n  also have \"... = TRY do {    \n    w \\<leftarrow> sample_uniform (order \\<G>);\n    let (h,w) = ((\\<^bold>g [^] w, g' [^] w), w);\n    w' \\<leftarrow> \\<A> h;\n    return_spmf ([w = w'] (mod (order \\<G>)) \\<and> [x*w = x*w'] (mod order \\<G>))} ELSE return_spmf False\"\n    apply(intro try_spmf_cong bind_spmf_cong[OF refl]; simp add: dis_log_alt.dis_log3_def dis_log_alt.g'_def g'_def)\n    by (simp add: finite_carrier nat_pow_pow pow_generator_eq_iff_cong)\n  also have \"... = dis_log_alt.dis_log3 \\<A>\"\n    apply(auto simp add:  dis_log_alt.dis_log3_def dis_log_alt.g'_def g'_def)\n    by(intro try_spmf_cong  bind_spmf_cong[OF refl]; clarsimp?; auto simp add: cong_scalar_left)\n  ultimately have \"chaum_ped_\\<Sigma>_commit.rel_advantage \\<A> = dis_log_alt.advantage3 \\<A>\"\n    by(simp add: chaum_ped_\\<Sigma>_commit.rel_advantage_def dis_log_alt.advantage3_def)\n  thus ?thesis\n    by (simp add: dis_log_alt_reductions.dis_log_adv3 cyclic_group_axioms dis_log_alt.dis_log_alt_axioms dis_log_alt_reductions.intro)\nqed\n\nlemma commitment_correct: \"chaum_ped_\\<Sigma>_commit.abstract_com.correct\"\n  by(simp add: chaum_ped_\\<Sigma>_commit.commit_correct)\n\nlemma  \"chaum_ped_\\<Sigma>_commit.abstract_com.perfect_hiding_ind_cpa \\<A>\"\n  using chaum_ped_\\<Sigma>_commit.perfect_hiding by blast\n\n\n\nend\n\nlocale chaum_ped_asymp = \n  fixes \\<G> :: \"nat \\<Rightarrow> 'grp cyclic_group\"\n    and x :: nat\n  assumes cp_\\<Sigma>: \"\\<And>\\<eta>. chaum_ped_\\<Sigma> (\\<G> \\<eta>)\"\nbegin\n\nsublocale chaum_ped_\\<Sigma> \"\\<G> \\<eta>\" for \\<eta> \n  by(simp add: cp_\\<Sigma>)\n\ntext\\<open>The \\<open>\\<Sigma>\\<close>-protocol statement comes easily in the asympotic setting.\\<close>\n\ntheorem sigma_protocol:\n  shows \"chaum_ped_sigma.\\<Sigma>_protocol n\"\n  by(simp add: \\<Sigma>_protocol)\n\ntext\\<open>We now show the statements of security for the commitment scheme in the asymptotic setting, the main difference is that\nwe are able to show the binding advantage is negligible in the security parameter.\\<close>\n\nlemma asymp_correct: \"chaum_ped_\\<Sigma>_commit.abstract_com.correct n\" \n  using  chaum_ped_\\<Sigma>_commit.commit_correct by simp\n\nlemma asymp_perfect_hiding: \"chaum_ped_\\<Sigma>_commit.abstract_com.perfect_hiding_ind_cpa n (\\<A> n)\"\n  using chaum_ped_\\<Sigma>_commit.perfect_hiding by blast\n\n\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/Sigma_Commit_Crypto/Chaum_Pedersen_Sigma_Commit.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9032942067038784, "lm_q2_score": 0.8152324848629215, "lm_q1q2_score": 0.7363947806934843}}
{"text": "(*\n    Author:   Benedikt Seidl\n    Author:   Salomon Sickert\n    License:  BSD\n*)\n\nsection \\<open>Disjunctive Normal Form of LTL formulas\\<close>\n\ntheory Disjunctive_Normal_Form\nimports\n  LTL Equivalence_Relations \"HOL-Library.FSet\"\nbegin\n\ntext \\<open>\n  We use the propositional representation of LTL formulas to define\n  the minimal disjunctive normal form of our formulas. For this purpose\n  we define the minimal product \\<open>\\<otimes>\\<^sub>m\\<close> and union \\<open>\\<union>\\<^sub>m\\<close>.\n  In the end we show that for a set \\<open>\\<A>\\<close> of literals,\n  @{term \"\\<A> \\<Turnstile>\\<^sub>P \\<phi>\"} if, and only if, there exists a subset\n  of \\<open>\\<A>\\<close> in the minimal DNF of \\<open>\\<phi>\\<close>.\n\\<close>\n\nsubsection \\<open>Definition of Minimum Sets\\<close>\n\ndefinition (in ord) min_set :: \"'a set \\<Rightarrow> 'a set\" where\n  \"min_set X = {y \\<in> X. \\<forall>x \\<in> X. x \\<le> y \\<longrightarrow> x = y}\"\n\nlemma min_set_iff:\n  \"x \\<in> min_set X \\<longleftrightarrow> x \\<in> X \\<and> (\\<forall>y \\<in> X. y \\<le> x \\<longrightarrow> y = x)\"\n  unfolding min_set_def by blast\n\nlemma min_set_subset:\n  \"min_set X \\<subseteq> X\"\n  by (auto simp: min_set_def)\n\nlemma min_set_idem[simp]:\n  \"min_set (min_set X) = min_set X\"\n  by (auto simp: min_set_def)\n\nlemma min_set_empty[simp]:\n  \"min_set {} = {}\"\n  using min_set_subset by blast\n\nlemma min_set_singleton[simp]:\n  \"min_set {x} = {x}\"\n  by (auto simp: min_set_def)\n\n\n\nlemma min_set_obtains_helper:\n  \"A \\<in> B \\<Longrightarrow> \\<exists>C. C |\\<subseteq>| A \\<and> C \\<in> min_set B\"\nproof (induction \"fcard A\" arbitrary: A rule: less_induct)\n  case less\n\n  then have \"(\\<forall>A'. A' \\<notin> B \\<or> \\<not> A' |\\<subseteq>| A \\<or> A' = A) \\<or> (\\<exists>A'. A' |\\<subseteq>| A \\<and> A' \\<in> min_set B)\"\n    by (metis (no_types) dual_order.trans order.not_eq_order_implies_strict pfsubset_fcard_mono)\n\n  then show ?case\n    using less.prems min_set_def by auto\nqed\n\nlemma min_set_obtains:\n  assumes \"A \\<in> B\"\n  obtains C where \"C |\\<subseteq>| A\" and \"C \\<in> min_set B\"\n  using min_set_obtains_helper assms by metis\n\n\n\nsubsection \\<open>Minimal operators on sets\\<close>\n\ndefinition product :: \"'a fset set \\<Rightarrow> 'a fset set \\<Rightarrow> 'a fset set\" (infixr \"\\<otimes>\" 65)\n  where \"A \\<otimes> B = {a |\\<union>| b | a b. a \\<in> A \\<and> b \\<in> B}\"\n\ndefinition min_product :: \"'a fset set \\<Rightarrow> 'a fset set \\<Rightarrow> 'a fset set\" (infixr \"\\<otimes>\\<^sub>m\" 65)\n  where \"A \\<otimes>\\<^sub>m B = min_set (A \\<otimes> B)\"\n\ndefinition min_union :: \"'a fset set \\<Rightarrow> 'a fset set \\<Rightarrow> 'a fset set\" (infixr \"\\<union>\\<^sub>m\" 65)\n  where \"A \\<union>\\<^sub>m B = min_set (A \\<union> B)\"\n\ndefinition product_set :: \"'a fset set set \\<Rightarrow> 'a fset set\" (\"\\<Otimes>\")\n  where \"\\<Otimes> X = Finite_Set.fold product {{||}} X\"\n\ndefinition min_product_set :: \"'a fset set set \\<Rightarrow> 'a fset set\" (\"\\<Otimes>\\<^sub>m\")\n  where \"\\<Otimes>\\<^sub>m X = Finite_Set.fold min_product {{||}} X\"\n\n\nlemma min_product_idem[simp]:\n  \"A \\<otimes>\\<^sub>m A = min_set A\"\n  by (auto simp: min_product_def product_def min_set_def) fastforce\n\nlemma min_union_idem[simp]:\n  \"A \\<union>\\<^sub>m A = min_set A\"\n  by (simp add: min_union_def)\n\n\nlemma product_empty[simp]:\n  \"A \\<otimes> {} = {}\"\n  \"{} \\<otimes> A = {}\"\n  by (simp_all add: product_def)\n\nlemma min_product_empty[simp]:\n  \"A \\<otimes>\\<^sub>m {} = {}\"\n  \"{} \\<otimes>\\<^sub>m A = {}\"\n  by (simp_all add: min_product_def)\n\nlemma min_union_empty[simp]:\n  \"A \\<union>\\<^sub>m {} = min_set A\"\n  \"{} \\<union>\\<^sub>m A = min_set A\"\n  by (simp_all add: min_union_def)\n\nlemma product_empty_singleton[simp]:\n  \"A \\<otimes> {{||}} = A\"\n  \"{{||}} \\<otimes> A = A\"\n  by (simp_all add: product_def)\n\nlemma min_product_empty_singleton[simp]:\n  \"A \\<otimes>\\<^sub>m {{||}} = min_set A\"\n  \"{{||}} \\<otimes>\\<^sub>m A = min_set A\"\n  by (simp_all add: min_product_def)\n\nlemma product_singleton_singleton:\n  \"A \\<otimes> {{|x|}} = finsert x ` A\"\n  \"{{|x|}} \\<otimes> A = finsert x ` A\"\n  unfolding product_def by blast+\n\nlemma product_mono:\n  \"A \\<subseteq> B \\<Longrightarrow> A \\<otimes> C \\<subseteq> B \\<otimes> C\"\n  \"B \\<subseteq> C \\<Longrightarrow> A \\<otimes> B \\<subseteq> A \\<otimes> C\"\n  unfolding product_def by auto\n\n\n\nlemma product_finite:\n  \"finite A \\<Longrightarrow> finite B \\<Longrightarrow> finite (A \\<otimes> B)\"\n  by (simp add: product_def finite_image_set2)\n\nlemma min_product_finite:\n  \"finite A \\<Longrightarrow> finite B \\<Longrightarrow> finite (A \\<otimes>\\<^sub>m B)\"\n  by (metis min_product_def product_finite min_set_finite)\n\nlemma min_union_finite:\n  \"finite A \\<Longrightarrow> finite B \\<Longrightarrow> finite (A \\<union>\\<^sub>m B)\"\n  by (simp add: min_union_def min_set_finite)\n\n\nlemma product_set_infinite[simp]:\n  \"infinite X \\<Longrightarrow> \\<Otimes> X = {{||}}\"\n  by (simp add: product_set_def)\n\nlemma min_product_set_infinite[simp]:\n  \"infinite X \\<Longrightarrow> \\<Otimes>\\<^sub>m X = {{||}}\"\n  by (simp add: min_product_set_def)\n\n\nlemma product_comm:\n  \"A \\<otimes> B = B \\<otimes> A\"\n  unfolding product_def by blast\n\n\n\nlemma min_union_comm:\n  \"A \\<union>\\<^sub>m B = B \\<union>\\<^sub>m A\"\n  unfolding min_union_def\n  by (simp add: sup.commute)\n\n\nlemma product_iff:\n  \"x \\<in> A \\<otimes> B \\<longleftrightarrow> (\\<exists>a \\<in> A. \\<exists>b \\<in> B. x = a |\\<union>| b)\"\n  unfolding product_def by blast\n\nlemma min_product_iff:\n  \"x \\<in> A \\<otimes>\\<^sub>m B \\<longleftrightarrow> (\\<exists>a \\<in> A. \\<exists>b \\<in> B. x = a |\\<union>| b) \\<and> (\\<forall>a \\<in> A. \\<forall>b \\<in> B. a |\\<union>| b |\\<subseteq>| x \\<longrightarrow> a |\\<union>| b = x)\"\n  unfolding min_product_def min_set_iff product_iff product_def by blast\n\nlemma min_union_iff:\n  \"x \\<in> A \\<union>\\<^sub>m B \\<longleftrightarrow> x \\<in> A \\<union> B \\<and> (\\<forall>a \\<in> A. a |\\<subseteq>| x \\<longrightarrow> a = x) \\<and> (\\<forall>b \\<in> B. b |\\<subseteq>| x \\<longrightarrow> b = x)\"\n  unfolding min_union_def min_set_iff by blast\n\n\n\n\n  then obtain a b where \"a \\<in> min_set A\" and \"b \\<in> B\" and \"x = a |\\<union>| b\" and 1: \"\\<forall>a \\<in> min_set A. \\<forall>b \\<in> B. a |\\<union>| b |\\<subseteq>| x \\<longrightarrow> a |\\<union>| b = x\"\n    unfolding min_product_iff by blast\n\n  moreover\n\n  {\n    fix a' b'\n    assume \"a' \\<in> A\" and \"b' \\<in> B\" and \"a' |\\<union>| b' |\\<subseteq>| x\"\n\n    then obtain a'' where \"a'' |\\<subseteq>| a'\" and \"a'' \\<in> min_set A\"\n      using min_set_obtains by metis\n\n    then have \"a'' |\\<union>| b' = x\"\n      by (metis (full_types) 1 \\<open>b' \\<in> B\\<close> \\<open>a' |\\<union>| b' |\\<subseteq>| x\\<close> dual_order.trans le_sup_iff)\n\n    then have \"a' |\\<union>| b' = x\"\n      using \\<open>a' |\\<union>| b' |\\<subseteq>| x\\<close> \\<open>a'' |\\<subseteq>| a'\\<close> by blast\n  }\n\n  ultimately show \"x \\<in> A \\<otimes>\\<^sub>m B\"\n    by (metis min_product_iff min_set_iff)\nnext\n  fix x\n  assume \"x \\<in> A \\<otimes>\\<^sub>m B\"\n\n  then have 1: \"x \\<in> A \\<otimes> B\" and \"\\<forall>y \\<in> A \\<otimes> B. y |\\<subseteq>| x \\<longrightarrow> y = x\"\n    unfolding min_product_def min_set_iff by simp+\n\n  then have 2: \"\\<forall>y\\<in>min_set A \\<otimes> B. y |\\<subseteq>| x \\<longrightarrow> y = x\"\n    by (metis product_iff min_set_iff)\n\n  then have \"x \\<in> min_set A \\<otimes> B\"\n    by (metis 1 funion_mono min_set_obtains order_refl product_iff)\n\n  then show \"x \\<in> min_set A \\<otimes>\\<^sub>m B\"\n    by (simp add: 2 min_product_def min_set_iff)\nqed\n\nlemma min_set_min_product[simp]:\n  \"(min_set A) \\<otimes>\\<^sub>m B = A \\<otimes>\\<^sub>m B\"\n  \"A \\<otimes>\\<^sub>m (min_set B) = A \\<otimes>\\<^sub>m B\"\n  using min_product_comm min_set_min_product_helper by blast+\n\nlemma min_set_min_union[simp]:\n  \"(min_set A) \\<union>\\<^sub>m B = A \\<union>\\<^sub>m B\"\n  \"A \\<union>\\<^sub>m (min_set B) = A \\<union>\\<^sub>m B\"\nproof (unfold min_union_def min_set_def, safe)\n  show \"\\<And>x xa xb. \\<lbrakk>\\<forall>xa\\<in>{y \\<in> A. \\<forall>x\\<in>A. x |\\<subseteq>| y \\<longrightarrow> x = y} \\<union> B. xa |\\<subseteq>| x \\<longrightarrow> xa = x; x \\<in> B; xa |\\<subseteq>| x; xb |\\<in>| x; xa \\<in> A\\<rbrakk> \\<Longrightarrow> xb |\\<in>| xa\"\n    by (metis (mono_tags) UnCI dual_order.trans fequalityI min_set_def min_set_obtains)\nnext\n  show \"\\<And>x xa xb. \\<lbrakk>\\<forall>xa\\<in>A \\<union> {y \\<in> B. \\<forall>x\\<in>B. x |\\<subseteq>| y \\<longrightarrow> x = y}. xa |\\<subseteq>| x \\<longrightarrow> xa = x; x \\<in> A; xa |\\<subseteq>| x; xb |\\<in>| x; xa \\<in> B\\<rbrakk> \\<Longrightarrow> xb |\\<in>| xa\"\n    by (metis (mono_tags) UnCI dual_order.trans fequalityI min_set_def min_set_obtains)\nqed blast+\n\n\nlemma product_assoc[simp]:\n  \"(A \\<otimes> B) \\<otimes> C = A \\<otimes> (B \\<otimes> C)\"\nproof (unfold product_def, safe)\n  fix a b c\n  assume \"a \\<in> A\" and \"c \\<in> C\" and \"b \\<in> B\"\n  then have \"b |\\<union>| c \\<in> {b |\\<union>| c |b c. b \\<in> B \\<and> c \\<in> C}\"\n    by blast\n  then show \"\\<exists>a' bc. a |\\<union>| b |\\<union>| c = a' |\\<union>| bc \\<and> a' \\<in> A \\<and> bc \\<in> {b |\\<union>| c |b c. b \\<in> B \\<and> c \\<in> C}\"\n    using `a \\<in> A` by (metis (no_types) inf_sup_aci(5) sup_left_commute)\nqed (metis (mono_tags, lifting) mem_Collect_eq sup_assoc)\n\nlemma min_product_assoc[simp]:\n  \"(A \\<otimes>\\<^sub>m B) \\<otimes>\\<^sub>m C = A \\<otimes>\\<^sub>m (B \\<otimes>\\<^sub>m C)\"\n  unfolding min_product_def[of A B] min_product_def[of B C]\n  by simp (simp add: min_product_def)\n\nlemma min_union_assoc[simp]:\n  \"(A \\<union>\\<^sub>m B) \\<union>\\<^sub>m C = A \\<union>\\<^sub>m (B \\<union>\\<^sub>m C)\"\n  unfolding min_union_def[of A B] min_union_def[of B C]\n  by simp (simp add: min_union_def sup_assoc)\n\n\nlemma min_product_comp:\n  \"a \\<in> A \\<Longrightarrow> b \\<in> B \\<Longrightarrow> \\<exists>c. c |\\<subseteq>| (a |\\<union>| b) \\<and> c \\<in> A \\<otimes>\\<^sub>m B\"\n  by (metis (mono_tags, lifting) mem_Collect_eq min_product_def product_def min_set_obtains)\n\nlemma min_union_comp:\n  \"a \\<in> A \\<Longrightarrow> \\<exists>c. c |\\<subseteq>| a \\<and> c \\<in> A \\<union>\\<^sub>m B\"\n  by (metis Un_iff min_set_obtains min_union_def)\n\n\ninterpretation product_set_thms: Finite_Set.comp_fun_commute product\nproof unfold_locales\n  have \"\\<And>x y z. x \\<otimes> (y \\<otimes> z) = y \\<otimes> (x \\<otimes> z)\"\n    by (simp only: product_assoc[symmetric]) (simp only: product_comm)\n\n  then show \"\\<And>x y. (\\<otimes>) y \\<circ> (\\<otimes>) x = (\\<otimes>) x \\<circ> (\\<otimes>) y\"\n    by fastforce\nqed\n\ninterpretation min_product_set_thms: Finite_Set.comp_fun_idem min_product\nproof unfold_locales\n  have \"\\<And>x y z. x \\<otimes>\\<^sub>m (y \\<otimes>\\<^sub>m z) = y \\<otimes>\\<^sub>m (x \\<otimes>\\<^sub>m z)\"\n    by (simp only: min_product_assoc[symmetric]) (simp only: min_product_comm)\n\n  then show \"\\<And>x y. (\\<otimes>\\<^sub>m) y \\<circ> (\\<otimes>\\<^sub>m) x = (\\<otimes>\\<^sub>m) x \\<circ> (\\<otimes>\\<^sub>m) y\"\n    by fastforce\nnext\n  have \"\\<And>x y. x \\<otimes>\\<^sub>m (x \\<otimes>\\<^sub>m y) = x \\<otimes>\\<^sub>m y\"\n    by (simp add: min_product_assoc[symmetric])\n\n  then show \"\\<And>x. (\\<otimes>\\<^sub>m) x \\<circ> (\\<otimes>\\<^sub>m) x = (\\<otimes>\\<^sub>m) x\"\n    by fastforce\nqed\n\n\ninterpretation min_union_set_thms: Finite_Set.comp_fun_idem min_union\nproof unfold_locales\n  have \"\\<And>x y z. x \\<union>\\<^sub>m (y \\<union>\\<^sub>m z) = y \\<union>\\<^sub>m (x \\<union>\\<^sub>m z)\"\n    by (simp only: min_union_assoc[symmetric]) (simp only: min_union_comm)\n\n  then show \"\\<And>x y. (\\<union>\\<^sub>m) y \\<circ> (\\<union>\\<^sub>m) x = (\\<union>\\<^sub>m) x \\<circ> (\\<union>\\<^sub>m) y\"\n    by fastforce\nnext\n  have \"\\<And>x y. x \\<union>\\<^sub>m (x \\<union>\\<^sub>m y) = x \\<union>\\<^sub>m y\"\n    by (simp add: min_union_assoc[symmetric])\n\n  then show \"\\<And>x. (\\<union>\\<^sub>m) x \\<circ> (\\<union>\\<^sub>m) x = (\\<union>\\<^sub>m) x\"\n    by fastforce\nqed\n\n\nlemma product_set_empty[simp]:\n  \"\\<Otimes> {} = {{||}}\"\n  \"\\<Otimes> {{}} = {}\"\n  \"\\<Otimes> {{{||}}} = {{||}}\"\n  by (simp_all add: product_set_def)\n\nlemma min_product_set_empty[simp]:\n  \"\\<Otimes>\\<^sub>m {} = {{||}}\"\n  \"\\<Otimes>\\<^sub>m {{}} = {}\"\n  \"\\<Otimes>\\<^sub>m {{{||}}} = {{||}}\"\n  by (simp_all add: min_product_set_def)\n\nlemma product_set_code[code]:\n  \"\\<Otimes> (set xs) = fold product (remdups xs) {{||}}\"\n  by (simp add: product_set_def product_set_thms.fold_set_fold_remdups)\n\nlemma min_product_set_code[code]:\n  \"\\<Otimes>\\<^sub>m (set xs) = fold min_product (remdups xs) {{||}}\"\n  by (simp add: min_product_set_def min_product_set_thms.fold_set_fold_remdups)\n\nlemma product_set_insert[simp]:\n  \"finite X \\<Longrightarrow> \\<Otimes> (insert x X) = x \\<otimes> (\\<Otimes> (X - {x}))\"\n  unfolding product_set_def product_set_thms.fold_insert_remove ..\n\nlemma min_product_set_insert[simp]:\n  \"finite X \\<Longrightarrow> \\<Otimes>\\<^sub>m (insert x X) = x \\<otimes>\\<^sub>m (\\<Otimes>\\<^sub>m X)\"\n  unfolding min_product_set_def min_product_set_thms.fold_insert_idem ..\n\nlemma min_product_subseteq:\n  \"x \\<in> A \\<otimes>\\<^sub>m B \\<Longrightarrow> \\<exists>a. a |\\<subseteq>| x \\<and> a \\<in> A\"\n  by (metis funion_upper1 min_product_iff)\n\nlemma min_product_set_subseteq:\n  \"finite X \\<Longrightarrow> x \\<in> \\<Otimes>\\<^sub>m X \\<Longrightarrow> A \\<in> X \\<Longrightarrow> \\<exists>a \\<in> A. a |\\<subseteq>| x\"\n  by (induction X rule: finite_induct) (blast, metis finite_insert insert_absorb min_product_set_insert min_product_subseteq)\n\n\n\n\nlemma min_product_min_set[simp]:\n  \"min_set (A \\<otimes>\\<^sub>m B) = A \\<otimes>\\<^sub>m B\"\n  by (simp add: min_product_def)\n\nlemma min_union_min_set[simp]:\n  \"min_set (A \\<union>\\<^sub>m B) = A \\<union>\\<^sub>m B\"\n  by (simp add: min_union_def)\n\nlemma min_product_set_min_set[simp]:\n  \"finite X \\<Longrightarrow> min_set (\\<Otimes>\\<^sub>m X) = \\<Otimes>\\<^sub>m X\"\n  by (induction X rule: finite_induct, auto simp add: min_product_set_def min_set_iff)\n\nlemma min_set_min_product_set[simp]:\n  \"finite X \\<Longrightarrow> \\<Otimes>\\<^sub>m (min_set ` X) = \\<Otimes>\\<^sub>m X\"\n  by (induction X rule: finite_induct) simp_all\n\nlemma min_product_set_union[simp]:\n  \"finite X \\<Longrightarrow> finite Y \\<Longrightarrow> \\<Otimes>\\<^sub>m (X \\<union> Y) = (\\<Otimes>\\<^sub>m X) \\<otimes>\\<^sub>m (\\<Otimes>\\<^sub>m Y)\"\n  by (induction X rule: finite_induct) simp_all\n\n\nlemma product_set_finite:\n  \"(\\<And>x. x \\<in> X \\<Longrightarrow> finite x) \\<Longrightarrow> finite (\\<Otimes> X)\"\n  by (cases \"finite X\", rotate_tac, induction X rule: finite_induct) (simp_all add: product_set_def, insert product_finite, blast)\n\nlemma min_product_set_finite:\n  \"(\\<And>x. x \\<in> X \\<Longrightarrow> finite x) \\<Longrightarrow> finite (\\<Otimes>\\<^sub>m X)\"\n  by (cases \"finite X\", rotate_tac, induction X rule: finite_induct) (simp_all add: min_product_set_def, insert min_product_finite, blast)\n\n\n\nsubsection \\<open>Disjunctive Normal Form\\<close>\n\nfun dnf :: \"'a ltln \\<Rightarrow> 'a ltln fset set\"\nwhere\n  \"dnf true\\<^sub>n = {{||}}\"\n| \"dnf false\\<^sub>n = {}\"\n| \"dnf (\\<phi> and\\<^sub>n \\<psi>) = (dnf \\<phi>) \\<otimes> (dnf \\<psi>)\"\n| \"dnf (\\<phi> or\\<^sub>n \\<psi>) = (dnf \\<phi>) \\<union> (dnf \\<psi>)\"\n| \"dnf \\<phi> = {{|\\<phi>|}}\"\n\nfun min_dnf :: \"'a ltln \\<Rightarrow> 'a ltln fset set\"\nwhere\n  \"min_dnf true\\<^sub>n = {{||}}\"\n| \"min_dnf false\\<^sub>n = {}\"\n| \"min_dnf (\\<phi> and\\<^sub>n \\<psi>) = (min_dnf \\<phi>) \\<otimes>\\<^sub>m (min_dnf \\<psi>)\"\n| \"min_dnf (\\<phi> or\\<^sub>n \\<psi>) = (min_dnf \\<phi>) \\<union>\\<^sub>m (min_dnf \\<psi>)\"\n| \"min_dnf \\<phi> = {{|\\<phi>|}}\"\n\nlemma dnf_min_set:\n  \"min_dnf \\<phi> = min_set (dnf \\<phi>)\"\n  by (induction \\<phi>) (simp_all, simp_all only: min_product_def min_union_def)\n\nlemma dnf_finite:\n  \"finite (dnf \\<phi>)\"\n  by (induction \\<phi>) (auto simp: product_finite)\n\nlemma min_dnf_finite:\n  \"finite (min_dnf \\<phi>)\"\n  by (induction \\<phi>) (auto simp: min_product_finite min_union_finite)\n\nlemma dnf_Abs_fset[simp]:\n  \"fset (Abs_fset (dnf \\<phi>)) = dnf \\<phi>\"\n  by (simp add: dnf_finite Abs_fset_inverse)\n\nlemma min_dnf_Abs_fset[simp]:\n  \"fset (Abs_fset (min_dnf \\<phi>)) = min_dnf \\<phi>\"\n  by (simp add: min_dnf_finite Abs_fset_inverse)\n\nlemma dnf_prop_atoms:\n  \"\\<Phi> \\<in> dnf \\<phi> \\<Longrightarrow> fset \\<Phi> \\<subseteq> prop_atoms \\<phi>\"\n  by (induction \\<phi> arbitrary: \\<Phi>) (auto simp: product_def, blast+)\n\nlemma min_dnf_prop_atoms:\n  \"\\<Phi> \\<in> min_dnf \\<phi> \\<Longrightarrow> fset \\<Phi> \\<subseteq> prop_atoms \\<phi>\"\n  using dnf_min_set dnf_prop_atoms min_set_subset by blast\n\nlemma min_dnf_atoms_dnf:\n  \"\\<Phi> \\<in> min_dnf \\<psi> \\<Longrightarrow> \\<phi> \\<in> fset \\<Phi> \\<Longrightarrow> dnf \\<phi> = {{|\\<phi>|}}\"\nproof (induction \\<phi>)\n  case True_ltln\n  then show ?case\n    using min_dnf_prop_atoms prop_atoms_notin(1) by blast\nnext\n  case False_ltln\n  then show ?case\n    using min_dnf_prop_atoms prop_atoms_notin(2) by blast\nnext\n  case (And_ltln \\<phi>1 \\<phi>2)\n  then show ?case\n    using min_dnf_prop_atoms prop_atoms_notin(3) by force\nnext\n  case (Or_ltln \\<phi>1 \\<phi>2)\n  then show ?case\n    using min_dnf_prop_atoms prop_atoms_notin(4) by force\nqed auto\n\nlemma min_dnf_min_set[simp]:\n  \"min_set (min_dnf \\<phi>) = min_dnf \\<phi>\"\n  by (induction \\<phi>) (simp_all add: min_set_def min_product_def min_union_def, blast+)\n\n\nlemma min_dnf_iff_prop_assignment_subset:\n  \"\\<A> \\<Turnstile>\\<^sub>P \\<phi> \\<longleftrightarrow> (\\<exists>B. fset B \\<subseteq> \\<A> \\<and> B \\<in> min_dnf \\<phi>)\"\nproof\n  assume \"\\<A> \\<Turnstile>\\<^sub>P \\<phi>\"\n\n  then show \"\\<exists>B. fset B \\<subseteq> \\<A> \\<and> B \\<in> min_dnf \\<phi>\"\n  proof (induction \\<phi> arbitrary: \\<A>)\n    case (And_ltln \\<phi>\\<^sub>1 \\<phi>\\<^sub>2)\n\n    then obtain B\\<^sub>1 B\\<^sub>2 where 1: \"fset B\\<^sub>1 \\<subseteq> \\<A> \\<and> B\\<^sub>1 \\<in> min_dnf \\<phi>\\<^sub>1\" and 2: \"fset B\\<^sub>2 \\<subseteq> \\<A> \\<and> B\\<^sub>2 \\<in> min_dnf \\<phi>\\<^sub>2\"\n      by fastforce\n\n    then obtain C where \"C |\\<subseteq>| B\\<^sub>1 |\\<union>| B\\<^sub>2\" and \"C \\<in> min_dnf \\<phi>\\<^sub>1 \\<otimes>\\<^sub>m min_dnf \\<phi>\\<^sub>2\"\n      using min_product_comp by metis\n\n    then show ?case\n      by (metis 1 2 le_sup_iff min_dnf.simps(3) sup.absorb_iff1 sup_fset.rep_eq)\n  next\n    case (Or_ltln \\<phi>\\<^sub>1 \\<phi>\\<^sub>2)\n\n    {\n      assume \"\\<A> \\<Turnstile>\\<^sub>P \\<phi>\\<^sub>1\"\n\n      then obtain B where 1: \"fset B \\<subseteq> \\<A> \\<and> B \\<in> min_dnf \\<phi>\\<^sub>1\"\n        using Or_ltln by fastforce\n\n      then obtain C where \"C |\\<subseteq>| B\" and \"C \\<in> min_dnf \\<phi>\\<^sub>1 \\<union>\\<^sub>m min_dnf \\<phi>\\<^sub>2\"\n        using min_union_comp by metis\n\n      then have ?case\n        by (metis 1 dual_order.trans less_eq_fset.rep_eq min_dnf.simps(4))\n    }\n\n    moreover\n\n    {\n      assume \"\\<A> \\<Turnstile>\\<^sub>P \\<phi>\\<^sub>2\"\n\n      then obtain B where 2: \"fset B \\<subseteq> \\<A> \\<and> B \\<in> min_dnf \\<phi>\\<^sub>2\"\n        using Or_ltln by fastforce\n\n      then obtain C where \"C |\\<subseteq>| B\" and \"C \\<in> min_dnf \\<phi>\\<^sub>1 \\<union>\\<^sub>m min_dnf \\<phi>\\<^sub>2\"\n        using min_union_comp min_union_comm by metis\n\n      then have ?case\n        by (metis 2 dual_order.trans less_eq_fset.rep_eq min_dnf.simps(4))\n    }\n\n    ultimately show ?case\n      using Or_ltln.prems by auto\n  qed simp_all\nnext\n  assume \"\\<exists>B. fset B \\<subseteq> \\<A> \\<and> B \\<in> min_dnf \\<phi>\"\n\n  then obtain B where \"fset B \\<subseteq> \\<A>\" and \"B \\<in> min_dnf \\<phi>\"\n    by auto\n\n  then have \"fset B \\<Turnstile>\\<^sub>P \\<phi>\"\n    by (induction \\<phi> arbitrary: B) (auto simp: min_set_def min_product_def product_def min_union_def, blast+)\n\n  then show \"\\<A> \\<Turnstile>\\<^sub>P \\<phi>\"\n    using \\<open>fset B \\<subseteq> \\<A>\\<close> by blast\nqed\n\n\nlemma ltl_prop_implies_min_dnf:\n  \"\\<phi> \\<longrightarrow>\\<^sub>P \\<psi> = (\\<forall>A \\<in> min_dnf \\<phi>. \\<exists>B \\<in> min_dnf \\<psi>. B |\\<subseteq>| A)\"\n  by (meson less_eq_fset.rep_eq ltl_prop_implies_def min_dnf_iff_prop_assignment_subset order_refl dual_order.trans)\n\nlemma ltl_prop_equiv_min_dnf:\n  \"\\<phi> \\<sim>\\<^sub>P \\<psi> = (min_dnf \\<phi> = min_dnf \\<psi>)\"\nproof\n  assume \"\\<phi> \\<sim>\\<^sub>P \\<psi>\"\n\n  then have \"\\<And>x. x \\<in> min_set (min_dnf \\<phi>) \\<longleftrightarrow> x \\<in> min_set (min_dnf \\<psi>)\"\n    unfolding ltl_prop_implies_equiv ltl_prop_implies_min_dnf min_set_iff\n    by fastforce\n\n  then show \"min_dnf \\<phi> = min_dnf \\<psi>\"\n    by auto\nqed (simp add: ltl_prop_equiv_def min_dnf_iff_prop_assignment_subset)\n\n\n\n\nsubsection \\<open>Folding of \\<open>and\\<^sub>n\\<close> and \\<open>or\\<^sub>n\\<close> over Finite Sets\\<close>\n\ndefinition And\\<^sub>n :: \"'a ltln set \\<Rightarrow> 'a ltln\"\nwhere\n  \"And\\<^sub>n \\<Phi> \\<equiv> SOME \\<phi>. fold_graph And_ltln True_ltln \\<Phi> \\<phi>\"\n\ndefinition Or\\<^sub>n :: \"'a ltln set \\<Rightarrow> 'a ltln\"\nwhere\n  \"Or\\<^sub>n \\<Phi> \\<equiv> SOME \\<phi>. fold_graph Or_ltln False_ltln \\<Phi> \\<phi>\"\n\nlemma fold_graph_And\\<^sub>n:\n  \"finite \\<Phi> \\<Longrightarrow> fold_graph And_ltln True_ltln \\<Phi> (And\\<^sub>n \\<Phi>)\"\n  unfolding And\\<^sub>n_def by (rule someI2_ex[OF finite_imp_fold_graph])\n\nlemma fold_graph_Or\\<^sub>n:\n  \"finite \\<Phi> \\<Longrightarrow> fold_graph Or_ltln False_ltln \\<Phi> (Or\\<^sub>n \\<Phi>)\"\n  unfolding Or\\<^sub>n_def by (rule someI2_ex[OF finite_imp_fold_graph])\n\nlemma Or\\<^sub>n_empty[simp]:\n  \"Or\\<^sub>n {} = False_ltln\"\n  by (metis empty_fold_graphE finite.emptyI fold_graph_Or\\<^sub>n)\n\nlemma And\\<^sub>n_empty[simp]:\n  \"And\\<^sub>n {} = True_ltln\"\n  by (metis empty_fold_graphE finite.emptyI fold_graph_And\\<^sub>n)\n\ninterpretation dnf_union_thms: Finite_Set.comp_fun_commute \"\\<lambda>\\<phi>. (\\<union>) (f \\<phi>)\"\n  by unfold_locales fastforce\n\ninterpretation dnf_product_thms: Finite_Set.comp_fun_commute \"\\<lambda>\\<phi>. (\\<otimes>) (f \\<phi>)\"\n  by unfold_locales (simp add: product_set_thms.comp_fun_commute)\n\n\\<comment> \\<open>Copied from locale @{locale comp_fun_commute}\\<close>\n\n\n\ntext \\<open>Taking the DNF of @{const And\\<^sub>n} and @{const Or\\<^sub>n} is the same as folding over the individual DNFs.\\<close>\n\nlemma And\\<^sub>n_dnf:\n  \"finite \\<Phi> \\<Longrightarrow> dnf (And\\<^sub>n \\<Phi>) = Finite_Set.fold (\\<lambda>\\<phi>. (\\<otimes>) (dnf \\<phi>)) {{||}} \\<Phi>\"\nproof (drule fold_graph_And\\<^sub>n, induction rule: fold_graph.induct)\n  case (insertI x A y)\n\n  then have \"finite A\"\n    using fold_graph_finite by fast\n\n  then show ?case\n    using insertI by auto\nqed simp\n\nlemma Or\\<^sub>n_dnf:\n  \"finite \\<Phi> \\<Longrightarrow> dnf (Or\\<^sub>n \\<Phi>) = Finite_Set.fold (\\<lambda>\\<phi>. (\\<union>) (dnf \\<phi>)) {} \\<Phi>\"\nproof (drule fold_graph_Or\\<^sub>n, induction rule: fold_graph.induct)\n  case (insertI x A y)\n\n  then have \"finite A\"\n    using fold_graph_finite by fast\n\n  then show ?case\n    using insertI by auto\nqed simp\n\n\ntext \\<open>@{const And\\<^sub>n} and @{const Or\\<^sub>n} are injective on finite sets.\\<close>\n\nlemma And\\<^sub>n_inj:\n  \"inj_on And\\<^sub>n {s. finite s}\"\nproof (standard, simp)\n  fix x y :: \"'a ltln set\"\n  assume \"finite x\" and \"finite y\"\n\n  then have 1: \"fold_graph And_ltln True_ltln x (And\\<^sub>n x)\" and 2: \"fold_graph And_ltln True_ltln y (And\\<^sub>n y)\"\n    using fold_graph_And\\<^sub>n by blast+\n\n  assume \"And\\<^sub>n x = And\\<^sub>n y\"\n\n  with 1 show \"x = y\"\n  proof (induction rule: fold_graph.induct)\n    case emptyI\n    then show ?case\n      using 2 fold_graph.cases by force\n  next\n    case (insertI x A y)\n    with 2 show ?case\n    proof (induction arbitrary: x A y rule: fold_graph.induct)\n      case (insertI x A y)\n      then show ?case\n        by (metis fold_graph.cases insertI1 ltln.distinct(7) ltln.inject(3))\n    qed blast\n  qed\nqed\n\nlemma Or\\<^sub>n_inj:\n  \"inj_on Or\\<^sub>n {s. finite s}\"\nproof (standard, simp)\n  fix x y :: \"'a ltln set\"\n  assume \"finite x\" and \"finite y\"\n\n  then have 1: \"fold_graph Or_ltln False_ltln x (Or\\<^sub>n x)\" and 2: \"fold_graph Or_ltln False_ltln y (Or\\<^sub>n y)\"\n    using fold_graph_Or\\<^sub>n by blast+\n\n  assume \"Or\\<^sub>n x = Or\\<^sub>n y\"\n\n  with 1 show \"x = y\"\n  proof (induction rule: fold_graph.induct)\n    case emptyI\n    then show ?case\n      using 2 fold_graph.cases by force\n  next\n    case (insertI x A y)\n    with 2 show ?case\n    proof (induction arbitrary: x A y rule: fold_graph.induct)\n      case (insertI x A y)\n      then show ?case\n        by (metis fold_graph.cases insertI1 ltln.distinct(27) ltln.inject(4))\n    qed blast\n  qed\nqed\n\n\ntext \\<open>The semantics of @{const And\\<^sub>n} and @{const Or\\<^sub>n} can be expressed using quantifiers.\\<close>\n\nlemma And\\<^sub>n_semantics:\n  \"finite \\<Phi> \\<Longrightarrow> w \\<Turnstile>\\<^sub>n And\\<^sub>n \\<Phi> \\<longleftrightarrow> (\\<forall>\\<phi> \\<in> \\<Phi>. w \\<Turnstile>\\<^sub>n \\<phi>)\"\nproof -\n  assume \"finite \\<Phi>\"\n  have \"\\<And>\\<psi>. fold_graph And_ltln True_ltln \\<Phi> \\<psi> \\<Longrightarrow> w \\<Turnstile>\\<^sub>n \\<psi> \\<longleftrightarrow> (\\<forall>\\<phi> \\<in> \\<Phi>. w \\<Turnstile>\\<^sub>n \\<phi>)\"\n    by (rule fold_graph.induct) auto\n  then show ?thesis\n    using fold_graph_And\\<^sub>n[OF \\<open>finite \\<Phi>\\<close>] by simp\nqed\n\nlemma Or\\<^sub>n_semantics:\n  \"finite \\<Phi> \\<Longrightarrow> w \\<Turnstile>\\<^sub>n Or\\<^sub>n \\<Phi> \\<longleftrightarrow> (\\<exists>\\<phi> \\<in> \\<Phi>. w \\<Turnstile>\\<^sub>n \\<phi>)\"\nproof -\n  assume \"finite \\<Phi>\"\n  have \"\\<And>\\<psi>. fold_graph Or_ltln False_ltln \\<Phi> \\<psi> \\<Longrightarrow> w \\<Turnstile>\\<^sub>n \\<psi> \\<longleftrightarrow> (\\<exists>\\<phi> \\<in> \\<Phi>. w \\<Turnstile>\\<^sub>n \\<phi>)\"\n    by (rule fold_graph.induct) auto\n  then show ?thesis\n    using fold_graph_Or\\<^sub>n[OF \\<open>finite \\<Phi>\\<close>] by simp\nqed\n\nlemma And\\<^sub>n_prop_semantics:\n  \"finite \\<Phi> \\<Longrightarrow> \\<A> \\<Turnstile>\\<^sub>P And\\<^sub>n \\<Phi> \\<longleftrightarrow> (\\<forall>\\<phi> \\<in> \\<Phi>. \\<A> \\<Turnstile>\\<^sub>P \\<phi>)\"\nproof -\n  assume \"finite \\<Phi>\"\n  have \"\\<And>\\<psi>. fold_graph And_ltln True_ltln \\<Phi> \\<psi> \\<Longrightarrow> \\<A> \\<Turnstile>\\<^sub>P \\<psi> \\<longleftrightarrow> (\\<forall>\\<phi> \\<in> \\<Phi>. \\<A> \\<Turnstile>\\<^sub>P \\<phi>)\"\n    by (rule fold_graph.induct) auto\n  then show ?thesis\n    using fold_graph_And\\<^sub>n[OF \\<open>finite \\<Phi>\\<close>] by simp\nqed\n\nlemma Or\\<^sub>n_prop_semantics:\n  \"finite \\<Phi> \\<Longrightarrow> \\<A> \\<Turnstile>\\<^sub>P Or\\<^sub>n \\<Phi> \\<longleftrightarrow> (\\<exists>\\<phi> \\<in> \\<Phi>. \\<A> \\<Turnstile>\\<^sub>P \\<phi>)\"\nproof -\n  assume \"finite \\<Phi>\"\n  have \"\\<And>\\<psi>. fold_graph Or_ltln False_ltln \\<Phi> \\<psi> \\<Longrightarrow> \\<A> \\<Turnstile>\\<^sub>P \\<psi> \\<longleftrightarrow> (\\<exists>\\<phi> \\<in> \\<Phi>. \\<A> \\<Turnstile>\\<^sub>P \\<phi>)\"\n    by (rule fold_graph.induct) auto\n  then show ?thesis\n    using fold_graph_Or\\<^sub>n[OF \\<open>finite \\<Phi>\\<close>] by simp\nqed\n\nlemma Or\\<^sub>n_And\\<^sub>n_image_semantics:\n  assumes \"finite \\<A>\" and \"\\<And>\\<Phi>. \\<Phi> \\<in> \\<A> \\<Longrightarrow> finite \\<Phi>\"\n  shows \"w \\<Turnstile>\\<^sub>n Or\\<^sub>n (And\\<^sub>n ` \\<A>) \\<longleftrightarrow> (\\<exists>\\<Phi> \\<in> \\<A>. \\<forall>\\<phi> \\<in> \\<Phi>. w \\<Turnstile>\\<^sub>n \\<phi>)\"\nproof -\n  have \"w \\<Turnstile>\\<^sub>n Or\\<^sub>n (And\\<^sub>n ` \\<A>) \\<longleftrightarrow> (\\<exists>\\<Phi> \\<in> \\<A>. w \\<Turnstile>\\<^sub>n And\\<^sub>n \\<Phi>)\"\n    using Or\\<^sub>n_semantics assms by auto\n  then show ?thesis\n    using And\\<^sub>n_semantics assms by fast\nqed\n\nlemma Or\\<^sub>n_And\\<^sub>n_image_prop_semantics:\n  assumes \"finite \\<A>\" and \"\\<And>\\<Phi>. \\<Phi> \\<in> \\<A> \\<Longrightarrow> finite \\<Phi>\"\n  shows \"\\<I> \\<Turnstile>\\<^sub>P Or\\<^sub>n (And\\<^sub>n ` \\<A>) \\<longleftrightarrow> (\\<exists>\\<Phi> \\<in> \\<A>. \\<forall>\\<phi> \\<in> \\<Phi>. \\<I> \\<Turnstile>\\<^sub>P \\<phi>)\"\nproof -\n  have \"\\<I> \\<Turnstile>\\<^sub>P Or\\<^sub>n (And\\<^sub>n ` \\<A>) \\<longleftrightarrow> (\\<exists>\\<Phi> \\<in> \\<A>. \\<I> \\<Turnstile>\\<^sub>P And\\<^sub>n \\<Phi>)\"\n    using Or\\<^sub>n_prop_semantics assms by blast\n  then show ?thesis\n    using And\\<^sub>n_prop_semantics assms by metis\nqed\n\n\nsubsection \\<open>DNF to LTL conversion\\<close>\n\ndefinition ltln_of_dnf :: \"'a ltln fset set \\<Rightarrow> 'a ltln\"\nwhere\n  \"ltln_of_dnf \\<A> = Or\\<^sub>n (And\\<^sub>n ` fset ` \\<A>)\"\n\nlemma ltln_of_dnf_semantics:\n  assumes \"finite \\<A>\"\n  shows \"w \\<Turnstile>\\<^sub>n ltln_of_dnf \\<A> \\<longleftrightarrow> (\\<exists>\\<Phi> \\<in> \\<A>. \\<forall>\\<phi>. \\<phi> |\\<in>| \\<Phi> \\<longrightarrow> w \\<Turnstile>\\<^sub>n \\<phi>)\"\nproof -\n  have \"finite (fset ` \\<A>)\"\n    using assms by blast\n\n  then have \"w \\<Turnstile>\\<^sub>n ltln_of_dnf \\<A> \\<longleftrightarrow> (\\<exists>\\<Phi> \\<in> fset ` \\<A>. \\<forall>\\<phi> \\<in> \\<Phi>. w \\<Turnstile>\\<^sub>n \\<phi>)\"\n    unfolding ltln_of_dnf_def using Or\\<^sub>n_And\\<^sub>n_image_semantics by fastforce\n\n  then show ?thesis\n    by (metis image_iff notin_fset)\nqed\n\nlemma ltln_of_dnf_prop_semantics:\n  assumes \"finite \\<A>\"\n  shows \"\\<I> \\<Turnstile>\\<^sub>P ltln_of_dnf \\<A> \\<longleftrightarrow> (\\<exists>\\<Phi> \\<in> \\<A>. \\<forall>\\<phi>. \\<phi> |\\<in>| \\<Phi> \\<longrightarrow> \\<I> \\<Turnstile>\\<^sub>P \\<phi>)\"\nproof -\n  have \"finite (fset ` \\<A>)\"\n    using assms by blast\n\n  then have \"\\<I> \\<Turnstile>\\<^sub>P ltln_of_dnf \\<A> \\<longleftrightarrow> (\\<exists>\\<Phi> \\<in> fset ` \\<A>. \\<forall>\\<phi> \\<in> \\<Phi>. \\<I> \\<Turnstile>\\<^sub>P \\<phi>)\"\n    unfolding ltln_of_dnf_def using Or\\<^sub>n_And\\<^sub>n_image_prop_semantics by fastforce\n\n  then show ?thesis\n    by (metis image_iff notin_fset)\nqed\n\nlemma ltln_of_dnf_prop_equiv:\n  \"ltln_of_dnf (min_dnf \\<phi>) \\<sim>\\<^sub>P \\<phi>\"\n  unfolding ltl_prop_equiv_def\nproof\n  fix \\<A>\n  have \"\\<A> \\<Turnstile>\\<^sub>P ltln_of_dnf (min_dnf \\<phi>) \\<longleftrightarrow> (\\<exists>\\<Phi> \\<in> min_dnf \\<phi>. \\<forall>\\<phi>. \\<phi> |\\<in>| \\<Phi> \\<longrightarrow> \\<A> \\<Turnstile>\\<^sub>P \\<phi>)\"\n    using ltln_of_dnf_prop_semantics min_dnf_finite by metis\n  also have \"\\<dots> \\<longleftrightarrow> (\\<exists>\\<Phi> \\<in> min_dnf \\<phi>. fset \\<Phi> \\<subseteq> \\<A>)\"\n    by (metis min_dnf_prop_atoms prop_atoms_entailment_iff notin_fset subset_eq)\n  also have \"\\<dots> \\<longleftrightarrow> \\<A> \\<Turnstile>\\<^sub>P \\<phi>\"\n    using min_dnf_iff_prop_assignment_subset by blast\n  finally show \"\\<A> \\<Turnstile>\\<^sub>P ltln_of_dnf (min_dnf \\<phi>) = \\<A> \\<Turnstile>\\<^sub>P \\<phi>\" .\nqed\n\nlemma min_dnf_ltln_of_dnf[simp]:\n  \"min_dnf (ltln_of_dnf (min_dnf \\<phi>)) = min_dnf \\<phi>\"\n  using ltl_prop_equiv_min_dnf ltln_of_dnf_prop_equiv by blast\n\n\nsubsection \\<open>Substitution in DNF formulas\\<close>\n\ndefinition subst_clause :: \"'a ltln fset \\<Rightarrow> ('a ltln \\<rightharpoonup> 'a ltln) \\<Rightarrow> 'a ltln fset set\"\nwhere\n  \"subst_clause \\<Phi> m = \\<Otimes>\\<^sub>m {min_dnf (subst \\<phi> m) | \\<phi>. \\<phi> \\<in> fset \\<Phi>}\"\n\ndefinition subst_dnf :: \"'a ltln fset set \\<Rightarrow> ('a ltln \\<rightharpoonup> 'a ltln) \\<Rightarrow> 'a ltln fset set\"\nwhere\n  \"subst_dnf \\<A> m = (\\<Union>\\<Phi> \\<in> \\<A>. subst_clause \\<Phi> m)\"\n\nlemma subst_clause_empty[simp]:\n  \"subst_clause {||} m = {{||}}\"\n  by (simp add: subst_clause_def)\n\nlemma subst_dnf_empty[simp]:\n  \"subst_dnf {} m = {}\"\n  by (simp add: subst_dnf_def)\n\nlemma subst_clause_inner_finite:\n  \"finite {min_dnf (subst \\<phi> m) | \\<phi>. \\<phi> \\<in> \\<Phi>}\" if \"finite \\<Phi>\"\n  using that by simp\n\nlemma subst_clause_finite:\n  \"finite (subst_clause \\<Phi> m)\"\n  unfolding subst_clause_def\n  by (auto intro: min_dnf_finite min_product_set_finite)\n\nlemma subst_dnf_finite:\n  \"finite \\<A> \\<Longrightarrow> finite (subst_dnf \\<A> m)\"\n  unfolding subst_dnf_def using subst_clause_finite by blast\n\nlemma subst_dnf_mono:\n  \"\\<A> \\<subseteq> \\<B> \\<Longrightarrow> subst_dnf \\<A> m \\<subseteq> subst_dnf \\<B> m\"\n  unfolding subst_dnf_def by blast\n\nlemma subst_clause_min_set[simp]:\n  \"min_set (subst_clause \\<Phi> m) = subst_clause \\<Phi> m\"\n  unfolding subst_clause_def by simp\n\nlemma subst_clause_finsert[simp]:\n  \"subst_clause (finsert \\<phi> \\<Phi>) m = (min_dnf (subst \\<phi> m)) \\<otimes>\\<^sub>m (subst_clause \\<Phi> m)\"\nproof -\n  have \"{min_dnf (subst \\<psi> m) | \\<psi>. \\<psi> \\<in> fset (finsert \\<phi> \\<Phi>)}\n    = insert (min_dnf (subst \\<phi> m)) {min_dnf (subst \\<psi> m) | \\<psi>. \\<psi> \\<in> fset \\<Phi>}\"\n    by auto\n\n  then show ?thesis\n    by (simp add: subst_clause_def)\nqed\n\nlemma subst_clause_funion[simp]:\n  \"subst_clause (\\<Phi> |\\<union>| \\<Psi>) m = (subst_clause \\<Phi> m) \\<otimes>\\<^sub>m (subst_clause \\<Psi> m)\"\nproof (induction \\<Psi>)\n  case (insert x F)\n  then show ?case\n    using min_product_set_thms.fun_left_comm by fastforce\nqed simp\n\n\ntext \\<open>For the proof of correctness, we redefine the @{const product} operator on lists.\\<close>\n\ndefinition list_product :: \"'a list set \\<Rightarrow> 'a list set \\<Rightarrow> 'a list set\" (infixl \"\\<otimes>\\<^sub>l\" 65)\nwhere\n  \"A \\<otimes>\\<^sub>l B = {a @ b | a b. a \\<in> A \\<and> b \\<in> B}\"\n\nlemma list_product_fset_of_list[simp]:\n  \"fset_of_list ` (A \\<otimes>\\<^sub>l B) = (fset_of_list ` A) \\<otimes> (fset_of_list ` B)\"\n  unfolding list_product_def product_def image_def by fastforce\n\nlemma list_product_finite:\n  \"finite A \\<Longrightarrow> finite B \\<Longrightarrow> finite (A \\<otimes>\\<^sub>l B)\"\n  unfolding list_product_def by (simp add: finite_image_set2)\n\nlemma list_product_iff:\n  \"x \\<in> A \\<otimes>\\<^sub>l B \\<longleftrightarrow> (\\<exists>a b. a \\<in> A \\<and> b \\<in> B \\<and> x = a @ b)\"\n  unfolding list_product_def by blast\n\nlemma list_product_assoc[simp]:\n  \"A \\<otimes>\\<^sub>l (B \\<otimes>\\<^sub>l C) = A \\<otimes>\\<^sub>l B \\<otimes>\\<^sub>l C\"\n  unfolding set_eq_iff list_product_iff by fastforce\n\n\ntext \\<open>Furthermore, we introduct DNFs where the clauses are represented as lists.\\<close>\n\nfun list_dnf :: \"'a ltln \\<Rightarrow> 'a ltln list set\"\nwhere\n  \"list_dnf true\\<^sub>n = {[]}\"\n| \"list_dnf false\\<^sub>n = {}\"\n| \"list_dnf (\\<phi> and\\<^sub>n \\<psi>) = (list_dnf \\<phi>) \\<otimes>\\<^sub>l (list_dnf \\<psi>)\"\n| \"list_dnf (\\<phi> or\\<^sub>n \\<psi>) = (list_dnf \\<phi>) \\<union> (list_dnf \\<psi>)\"\n| \"list_dnf \\<phi> = {[\\<phi>]}\"\n\ndefinition list_dnf_to_dnf :: \"'a list set \\<Rightarrow> 'a fset set\"\nwhere\n  \"list_dnf_to_dnf X = fset_of_list ` X\"\n\nlemma list_dnf_to_dnf_list_dnf[simp]:\n  \"list_dnf_to_dnf (list_dnf \\<phi>) = dnf \\<phi>\"\n  by (induction \\<phi>) (simp_all add: list_dnf_to_dnf_def image_Un)\n\nlemma list_dnf_finite:\n  \"finite (list_dnf \\<phi>)\"\n  by (induction \\<phi>) (simp_all add: list_product_finite)\n\n\ntext \\<open>We use this to redefine @{const subst_clause} and @{const subst_dnf} on list DNFs.\\<close>\n\ndefinition subst_clause' :: \"'a ltln list \\<Rightarrow> ('a ltln \\<rightharpoonup> 'a ltln) \\<Rightarrow> 'a ltln list set\"\nwhere\n  \"subst_clause' \\<Phi> m = fold (\\<lambda>\\<phi> acc. acc \\<otimes>\\<^sub>l list_dnf (subst \\<phi> m)) \\<Phi> {[]}\"\n\ndefinition subst_dnf' :: \"'a ltln list set \\<Rightarrow> ('a ltln \\<rightharpoonup> 'a ltln) \\<Rightarrow> 'a ltln list set\"\nwhere\n  \"subst_dnf' \\<A> m = (\\<Union>\\<Phi> \\<in> \\<A>. subst_clause' \\<Phi> m)\"\n\nlemma subst_clause'_finite:\n  \"finite (subst_clause' \\<Phi> m)\"\n  by (induction \\<Phi> rule: rev_induct) (simp_all add: subst_clause'_def list_dnf_finite list_product_finite)\n\nlemma subst_clause'_nil[simp]:\n  \"subst_clause' [] m = {[]}\"\n  by (simp add: subst_clause'_def)\n\nlemma subst_clause'_cons[simp]:\n  \"subst_clause' (xs @ [x]) m = subst_clause' xs m \\<otimes>\\<^sub>l list_dnf (subst x m)\"\n  by (simp add: subst_clause'_def)\n\nlemma subst_clause'_append[simp]:\n  \"subst_clause' (A @ B) m = subst_clause' A m \\<otimes>\\<^sub>l subst_clause' B m\"\nproof (induction B rule: rev_induct)\n  case (snoc x xs)\n  then show ?case\n    by simp (metis append_assoc subst_clause'_cons)\nqed(simp add: list_product_def)\n\n\nlemma subst_dnf'_iff:\n  \"x \\<in> subst_dnf' A m \\<longleftrightarrow> (\\<exists>\\<Phi> \\<in> A. x \\<in> subst_clause' \\<Phi> m)\"\n  by (simp add: subst_dnf'_def)\n\nlemma subst_dnf'_product:\n  \"subst_dnf' (A \\<otimes>\\<^sub>l B) m = (subst_dnf' A m) \\<otimes>\\<^sub>l (subst_dnf' B m)\" (is \"?lhs = ?rhs\")\nproof (unfold set_eq_iff, safe)\n  fix x\n  assume \"x \\<in> ?lhs\"\n\n  then obtain \\<Phi> where \"\\<Phi> \\<in> A \\<otimes>\\<^sub>l B\" and \"x \\<in> subst_clause' \\<Phi> m\"\n    unfolding subst_dnf'_iff by blast\n\n  then obtain a b where \"a \\<in> A\" and \"b \\<in> B\" and \"\\<Phi> = a @ b\"\n    unfolding list_product_def by blast\n\n  then have \"x \\<in> (subst_clause' a m) \\<otimes>\\<^sub>l (subst_clause' b m)\"\n    using \\<open>x \\<in> subst_clause' \\<Phi> m\\<close> by simp\n\n  then obtain a' b' where \"a' \\<in> subst_clause' a m\" and \"b' \\<in> subst_clause' b m\" and \"x = a' @ b'\"\n    unfolding list_product_iff by blast\n\n  then have \"a' \\<in> subst_dnf' A m\" and \"b' \\<in> subst_dnf' B m\"\n    unfolding subst_dnf'_iff using \\<open>a \\<in> A\\<close> \\<open>b \\<in> B\\<close> by auto\n\n  then have \"\\<exists>a\\<in>subst_dnf' A m. \\<exists>b\\<in>subst_dnf' B m. x = a @ b\"\n    using \\<open>x = a' @ b'\\<close> by blast\n\n  then show \"x \\<in> ?rhs\"\n    unfolding list_product_iff by blast\nnext\n  fix x\n  assume \"x \\<in> ?rhs\"\n\n  then obtain a b where \"a \\<in> subst_dnf' A m\" and \"b \\<in> subst_dnf' B m\" and \"x = a @ b\"\n    unfolding list_product_iff by blast\n\n  then obtain a' b' where \"a' \\<in> A\" and \"b' \\<in> B\" and a: \"a \\<in> subst_clause' a' m\" and b: \"b \\<in> subst_clause' b' m\"\n    unfolding subst_dnf'_iff by blast\n\n  then have \"x \\<in> (subst_clause' a' m) \\<otimes>\\<^sub>l (subst_clause' b' m)\"\n    unfolding list_product_iff using \\<open>x = a @ b\\<close> by blast\n\n  moreover\n\n  have \"a' @ b' \\<in> A \\<otimes>\\<^sub>l B\"\n    unfolding list_product_iff using \\<open>a' \\<in> A\\<close> \\<open>b' \\<in> B\\<close> by blast\n\n  ultimately show \"x \\<in> ?lhs\"\n    unfolding subst_dnf'_iff by force\nqed\n\nlemma subst_dnf'_list_dnf:\n  \"subst_dnf' (list_dnf \\<phi>) m = list_dnf (subst \\<phi> m)\"\nproof (induction \\<phi>)\n  case (And_ltln \\<phi>1 \\<phi>2)\n  then show ?case\n    by (simp add: subst_dnf'_product)\nqed (simp_all add: subst_dnf'_def subst_clause'_def list_product_def)\n\n\nlemma min_set_Union:\n  \"finite X \\<Longrightarrow> min_set (\\<Union> (min_set ` X)) = min_set (\\<Union> X)\" for X :: \"'a fset set set\"\n  by (induction X rule: finite_induct) (force, metis Sup_insert image_insert min_set_min_union min_union_def)\n\nlemma min_set_Union_image:\n  \"finite X \\<Longrightarrow> min_set (\\<Union>x \\<in> X. min_set (f x)) = min_set (\\<Union>x \\<in> X. f x)\" for f :: \"'b \\<Rightarrow> 'a fset set\"\nproof -\n  assume \"finite X\"\n\n  then have *: \"finite (f ` X)\" by auto\n\n  with min_set_Union show ?thesis\n    unfolding image_image by fastforce\nqed\n\nlemma subst_clause_fset_of_list:\n  \"subst_clause (fset_of_list \\<Phi>) m = min_set (list_dnf_to_dnf (subst_clause' \\<Phi> m))\"\n  unfolding list_dnf_to_dnf_def subst_clause'_def\nproof (induction \\<Phi> rule: rev_induct)\n  case (snoc x xs)\n  then show ?case\n    by simp (metis (no_types, lifting) dnf_min_set list_dnf_to_dnf_def list_dnf_to_dnf_list_dnf min_product_comm min_product_def min_set_min_product(1))\nqed simp\n\nlemma min_set_list_dnf_to_dnf_subst_dnf':\n  \"finite X \\<Longrightarrow> min_set (list_dnf_to_dnf (subst_dnf' X m)) = min_set (subst_dnf (list_dnf_to_dnf X) m)\"\n  by (simp add: subst_dnf'_def subst_dnf_def subst_clause_fset_of_list list_dnf_to_dnf_def min_set_Union_image image_Union)\n\nlemma subst_dnf_dnf:\n  \"min_set (subst_dnf (dnf \\<phi>) m) = min_dnf (subst \\<phi> m)\"\n  unfolding dnf_min_set\n  unfolding list_dnf_to_dnf_list_dnf[symmetric]\n  unfolding subst_dnf'_list_dnf[symmetric]\n  unfolding min_set_list_dnf_to_dnf_subst_dnf'[OF list_dnf_finite]\n  by simp\n\n\ntext \\<open>This is almost the lemma we need. However, we need to show that the same holds for @{term \"min_dnf \\<phi>\"}, too.\\<close>\n\nlemma fold_product:\n  \"Finite_Set.fold (\\<lambda>x. (\\<otimes>) {{|x|}}) {{||}} (fset x) = {x}\"\n  by (induction x) (simp_all add: notin_fset, simp add: product_singleton_singleton)\n\nlemma fold_union:\n  \"Finite_Set.fold (\\<lambda>x. (\\<union>) {x}) {} (fset x) = fset x\"\n  by (induction x) (simp_all add: notin_fset comp_fun_idem.fold_insert_idem comp_fun_idem_insert)\n\nlemma fold_union_fold_product:\n  assumes \"finite X\" and \"\\<And>\\<Psi> \\<psi>. \\<Psi> \\<in> X \\<Longrightarrow> \\<psi> \\<in> fset \\<Psi> \\<Longrightarrow> dnf \\<psi> = {{|\\<psi>|}}\"\n  shows \"Finite_Set.fold (\\<lambda>x. (\\<union>) (Finite_Set.fold (\\<lambda>\\<phi>. (\\<otimes>) (dnf \\<phi>)) {{||}} (fset x))) {} X = X\" (is \"?lhs = X\")\nproof -\n  from assms have \"?lhs = Finite_Set.fold (\\<lambda>x. (\\<union>) (Finite_Set.fold (\\<lambda>\\<phi>. (\\<otimes>) {{|\\<phi>|}}) {{||}} (fset x))) {} X\"\n  proof (induction X rule: finite_induct)\n    case (insert \\<Phi> X)\n\n    from insert.prems have 1: \"\\<And>\\<Psi> \\<psi>. \\<lbrakk>\\<Psi> \\<in> X; \\<psi> \\<in> fset \\<Psi>\\<rbrakk> \\<Longrightarrow> dnf \\<psi> = {{|\\<psi>|}}\"\n      by force\n\n    from insert.prems have \"Finite_Set.fold (\\<lambda>\\<phi>. (\\<otimes>) (dnf \\<phi>)) {{||}} (fset \\<Phi>) = Finite_Set.fold (\\<lambda>\\<phi>. (\\<otimes>) {{|\\<phi>|}}) {{||}} (fset \\<Phi>)\"\n      by (induction \\<Phi>) (force simp: notin_fset)+\n\n    with insert 1 show ?case\n      by simp\n  qed simp\n\n  with \\<open>finite X\\<close> show ?thesis\n    unfolding fold_product by (metis fset_to_fset fold_union)\nqed\n\nlemma dnf_ltln_of_dnf_min_dnf:\n  \"dnf (ltln_of_dnf (min_dnf \\<phi>)) = min_dnf \\<phi>\"\nproof -\n  have 1: \"finite (And\\<^sub>n ` fset ` min_dnf \\<phi>)\"\n    using min_dnf_finite by blast\n\n  have 2: \"inj_on And\\<^sub>n (fset ` min_dnf \\<phi>)\"\n    by (metis (mono_tags, lifting) And\\<^sub>n_inj f_inv_into_f fset inj_onI inj_on_contraD)\n\n  have 3: \"inj_on fset (min_dnf \\<phi>)\"\n    by (meson fset_inject inj_onI)\n\n  show ?thesis\n    unfolding ltln_of_dnf_def\n    unfolding Or\\<^sub>n_dnf[OF 1]\n    unfolding fold_image[OF 2]\n    unfolding fold_image[OF 3]\n    unfolding comp_def\n    unfolding And\\<^sub>n_dnf[OF finite_fset]\n    by (metis fold_union_fold_product min_dnf_finite min_dnf_atoms_dnf)\nqed\n\nlemma min_dnf_subst:\n  \"min_set (subst_dnf (min_dnf \\<phi>) m) = min_dnf (subst \\<phi> m)\" (is \"?lhs = ?rhs\")\nproof -\n  let ?\\<phi>' = \"ltln_of_dnf (min_dnf \\<phi>)\"\n\n  have \"?lhs = min_set (subst_dnf (dnf ?\\<phi>') m)\"\n    unfolding dnf_ltln_of_dnf_min_dnf ..\n\n  also have \"\\<dots> = min_dnf (subst ?\\<phi>' m)\"\n    unfolding subst_dnf_dnf ..\n\n  also have \"\\<dots> = min_dnf (subst \\<phi> m)\"\n    using ltl_prop_equiv_min_dnf ltln_of_dnf_prop_equiv subst_respects_ltl_prop_entailment(2) by blast\n\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/LTL/Disjunctive_Normal_Form.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.879146780175245, "lm_q2_score": 0.8376199633332891, "lm_q1q2_score": 0.7363908937749679}}
{"text": "theory heap_SortPermutes\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 equal2 :: \"Nat => Nat => bool\" where\n\"equal2 (Z) (Z) = True\"\n| \"equal2 (Z) (S z) = False\"\n| \"equal2 (S x2) (Z) = False\"\n| \"equal2 (S x2) (S y2) = equal2 x2 y2\"\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 count :: \"Nat => Nat list => Nat\" where\n\"count x (Nil2) = Z\"\n| \"count x (Cons2 z xs) =\n     (if equal2 x z then S (count x xs) else count x xs)\"\n\n(*hipster plus\n          le\n          merge\n          toList\n          insert2\n          toHeap\n          heapSize\n          toList2\n          equal2\n          dot\n          hsort\n          count *)\n\ntheorem x0 :\n  \"!! (x :: Nat) (y :: Nat list) . (count x (hsort y)) = (count x y)\"\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_SortPermutes.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9407897509188344, "lm_q2_score": 0.7826624789529375, "lm_q1q2_score": 0.7363208386276515}}
{"text": "(*  Title:      HOL/Multivariate_Analysis/Path_Connected.thy\n    Author:     Robert Himmelmann, TU Muenchen\n*)\n\nsection {* Continuous paths and path-connected sets *}\n\ntheory Path_Connected\nimports Convex_Euclidean_Space\nbegin\n\nsubsection {* Paths. *}\n\ndefinition path :: \"(real \\<Rightarrow> 'a::topological_space) \\<Rightarrow> bool\"\n  where \"path g \\<longleftrightarrow> continuous_on {0..1} g\"\n\ndefinition pathstart :: \"(real \\<Rightarrow> 'a::topological_space) \\<Rightarrow> 'a\"\n  where \"pathstart g = g 0\"\n\ndefinition pathfinish :: \"(real \\<Rightarrow> 'a::topological_space) \\<Rightarrow> 'a\"\n  where \"pathfinish g = g 1\"\n\ndefinition path_image :: \"(real \\<Rightarrow> 'a::topological_space) \\<Rightarrow> 'a set\"\n  where \"path_image g = g ` {0 .. 1}\"\n\ndefinition reversepath :: \"(real \\<Rightarrow> 'a::topological_space) \\<Rightarrow> real \\<Rightarrow> 'a\"\n  where \"reversepath g = (\\<lambda>x. g(1 - x))\"\n\ndefinition joinpaths :: \"(real \\<Rightarrow> 'a::topological_space) \\<Rightarrow> (real \\<Rightarrow> 'a) \\<Rightarrow> real \\<Rightarrow> 'a\"\n    (infixr \"+++\" 75)\n  where \"g1 +++ g2 = (\\<lambda>x. if x \\<le> 1/2 then g1 (2 * x) else g2 (2 * x - 1))\"\n\ndefinition simple_path :: \"(real \\<Rightarrow> 'a::topological_space) \\<Rightarrow> bool\"\n  where \"simple_path g \\<longleftrightarrow>\n    (\\<forall>x\\<in>{0..1}. \\<forall>y\\<in>{0..1}. g x = g y \\<longrightarrow> x = y \\<or> x = 0 \\<and> y = 1 \\<or> x = 1 \\<and> y = 0)\"\n\ndefinition injective_path :: \"(real \\<Rightarrow> 'a::topological_space) \\<Rightarrow> bool\"\n  where \"injective_path g \\<longleftrightarrow> (\\<forall>x\\<in>{0..1}. \\<forall>y\\<in>{0..1}. g x = g y \\<longrightarrow> x = y)\"\n\n\nsubsection {* Some lemmas about these concepts. *}\n\nlemma injective_imp_simple_path: \"injective_path g \\<Longrightarrow> simple_path g\"\n  unfolding injective_path_def simple_path_def\n  by auto\n\nlemma path_image_nonempty: \"path_image g \\<noteq> {}\"\n  unfolding path_image_def image_is_empty box_eq_empty\n  by auto\n\nlemma pathstart_in_path_image[intro]: \"pathstart g \\<in> path_image g\"\n  unfolding pathstart_def path_image_def\n  by auto\n\nlemma pathfinish_in_path_image[intro]: \"pathfinish g \\<in> path_image g\"\n  unfolding pathfinish_def path_image_def\n  by auto\n\nlemma connected_path_image[intro]: \"path g \\<Longrightarrow> connected (path_image g)\"\n  unfolding path_def path_image_def\n  apply (erule connected_continuous_image)\n  apply (rule convex_connected, rule convex_real_interval)\n  done\n\nlemma compact_path_image[intro]: \"path g \\<Longrightarrow> compact (path_image g)\"\n  unfolding path_def path_image_def\n  apply (erule compact_continuous_image)\n  apply (rule compact_Icc)\n  done\n\nlemma reversepath_reversepath[simp]: \"reversepath (reversepath g) = g\"\n  unfolding reversepath_def\n  by auto\n\nlemma pathstart_reversepath[simp]: \"pathstart (reversepath g) = pathfinish g\"\n  unfolding pathstart_def reversepath_def pathfinish_def\n  by auto\n\nlemma pathfinish_reversepath[simp]: \"pathfinish (reversepath g) = pathstart g\"\n  unfolding pathstart_def reversepath_def pathfinish_def\n  by auto\n\nlemma pathstart_join[simp]: \"pathstart (g1 +++ g2) = pathstart g1\"\n  unfolding pathstart_def joinpaths_def pathfinish_def\n  by auto\n\nlemma pathfinish_join[simp]: \"pathfinish (g1 +++ g2) = pathfinish g2\"\n  unfolding pathstart_def joinpaths_def pathfinish_def\n  by auto\n\nlemma path_image_reversepath[simp]: \"path_image (reversepath g) = path_image g\"\nproof -\n  have *: \"\\<And>g. path_image (reversepath g) \\<subseteq> path_image g\"\n    unfolding path_image_def subset_eq reversepath_def Ball_def image_iff\n    apply rule\n    apply rule\n    apply (erule bexE)\n    apply (rule_tac x=\"1 - xa\" in bexI)\n    apply auto\n    done\n  show ?thesis\n    using *[of g] *[of \"reversepath g\"]\n    unfolding reversepath_reversepath\n    by auto\nqed\n\nlemma path_reversepath [simp]: \"path (reversepath g) \\<longleftrightarrow> path g\"\nproof -\n  have *: \"\\<And>g. path g \\<Longrightarrow> path (reversepath g)\"\n    unfolding path_def reversepath_def\n    apply (rule continuous_on_compose[unfolded o_def, of _ \"\\<lambda>x. 1 - x\"])\n    apply (intro continuous_intros)\n    apply (rule continuous_on_subset[of \"{0..1}\"])\n    apply assumption\n    apply auto\n    done\n  show ?thesis\n    using *[of \"reversepath g\"] *[of g]\n    unfolding reversepath_reversepath\n    by (rule iffI)\nqed\n\nlemmas reversepath_simps =\n  path_reversepath path_image_reversepath pathstart_reversepath pathfinish_reversepath\n\nlemma path_join[simp]:\n  assumes \"pathfinish g1 = pathstart g2\"\n  shows \"path (g1 +++ g2) \\<longleftrightarrow> path g1 \\<and> path g2\"\n  unfolding path_def pathfinish_def pathstart_def\nproof safe\n  assume cont: \"continuous_on {0..1} (g1 +++ g2)\"\n  have g1: \"continuous_on {0..1} g1 \\<longleftrightarrow> continuous_on {0..1} ((g1 +++ g2) \\<circ> (\\<lambda>x. x / 2))\"\n    by (intro continuous_on_cong refl) (auto simp: joinpaths_def)\n  have g2: \"continuous_on {0..1} g2 \\<longleftrightarrow> continuous_on {0..1} ((g1 +++ g2) \\<circ> (\\<lambda>x. x / 2 + 1/2))\"\n    using assms\n    by (intro continuous_on_cong refl) (auto simp: joinpaths_def pathfinish_def pathstart_def)\n  show \"continuous_on {0..1} g1\" and \"continuous_on {0..1} g2\"\n    unfolding g1 g2\n    by (auto intro!: continuous_intros continuous_on_subset[OF cont] simp del: o_apply)\nnext\n  assume g1g2: \"continuous_on {0..1} g1\" \"continuous_on {0..1} g2\"\n  have 01: \"{0 .. 1} = {0..1/2} \\<union> {1/2 .. 1::real}\"\n    by auto\n  {\n    fix x :: real\n    assume \"0 \\<le> x\" and \"x \\<le> 1\"\n    then have \"x \\<in> (\\<lambda>x. x * 2) ` {0..1 / 2}\"\n      by (intro image_eqI[where x=\"x/2\"]) auto\n  }\n  note 1 = this\n  {\n    fix x :: real\n    assume \"0 \\<le> x\" and \"x \\<le> 1\"\n    then have \"x \\<in> (\\<lambda>x. x * 2 - 1) ` {1 / 2..1}\"\n      by (intro image_eqI[where x=\"x/2 + 1/2\"]) auto\n  }\n  note 2 = this\n  show \"continuous_on {0..1} (g1 +++ g2)\"\n    using assms\n    unfolding joinpaths_def 01\n    apply (intro continuous_on_cases closed_atLeastAtMost g1g2[THEN continuous_on_compose2] continuous_intros)\n    apply (auto simp: field_simps pathfinish_def pathstart_def intro!: 1 2)\n    done\nqed\n\nlemma path_image_join_subset: \"path_image (g1 +++ g2) \\<subseteq> path_image g1 \\<union> path_image g2\"\n  unfolding path_image_def joinpaths_def\n  by auto\n\nlemma subset_path_image_join:\n  assumes \"path_image g1 \\<subseteq> s\"\n    and \"path_image g2 \\<subseteq> s\"\n  shows \"path_image (g1 +++ g2) \\<subseteq> s\"\n  using path_image_join_subset[of g1 g2] and assms\n  by auto\n\nlemma path_image_join:\n  assumes \"pathfinish g1 = pathstart g2\"\n  shows \"path_image (g1 +++ g2) = path_image g1 \\<union> path_image g2\"\n  apply rule\n  apply (rule path_image_join_subset)\n  apply rule\n  unfolding Un_iff\nproof (erule disjE)\n  fix x\n  assume \"x \\<in> path_image g1\"\n  then obtain y where y: \"y \\<in> {0..1}\" \"x = g1 y\"\n    unfolding path_image_def image_iff by auto\n  then show \"x \\<in> path_image (g1 +++ g2)\"\n    unfolding joinpaths_def path_image_def image_iff\n    apply (rule_tac x=\"(1/2) *\\<^sub>R y\" in bexI)\n    apply auto\n    done\nnext\n  fix x\n  assume \"x \\<in> path_image g2\"\n  then obtain y where y: \"y \\<in> {0..1}\" \"x = g2 y\"\n    unfolding path_image_def image_iff by auto\n  then show \"x \\<in> path_image (g1 +++ g2)\"\n    unfolding joinpaths_def path_image_def image_iff\n    apply (rule_tac x=\"(1/2) *\\<^sub>R (y + 1)\" in bexI)\n    using assms(1)[unfolded pathfinish_def pathstart_def]\n    apply (auto simp add: add_divide_distrib)\n    done\nqed\n\nlemma not_in_path_image_join:\n  assumes \"x \\<notin> path_image g1\"\n    and \"x \\<notin> path_image g2\"\n  shows \"x \\<notin> path_image (g1 +++ g2)\"\n  using assms and path_image_join_subset[of g1 g2]\n  by auto\n\nlemma simple_path_reversepath:\n  assumes \"simple_path g\"\n  shows \"simple_path (reversepath g)\"\n  using assms\n  unfolding simple_path_def reversepath_def\n  apply -\n  apply (rule ballI)+\n  apply (erule_tac x=\"1-x\" in ballE)\n  apply (erule_tac x=\"1-y\" in ballE)\n  apply auto\n  done\n\nlemma simple_path_join_loop:\n  assumes \"injective_path g1\"\n    and \"injective_path g2\"\n    and \"pathfinish g2 = pathstart g1\"\n    and \"path_image g1 \\<inter> path_image g2 \\<subseteq> {pathstart g1, pathstart g2}\"\n  shows \"simple_path (g1 +++ g2)\"\n  unfolding simple_path_def\nproof (intro ballI impI)\n  let ?g = \"g1 +++ g2\"\n  note inj = assms(1,2)[unfolded injective_path_def, rule_format]\n  fix x y :: real\n  assume xy: \"x \\<in> {0..1}\" \"y \\<in> {0..1}\" \"?g x = ?g y\"\n  show \"x = y \\<or> x = 0 \\<and> y = 1 \\<or> x = 1 \\<and> y = 0\"\n  proof (cases \"x \\<le> 1/2\", case_tac[!] \"y \\<le> 1/2\", unfold not_le)\n    assume as: \"x \\<le> 1 / 2\" \"y \\<le> 1 / 2\"\n    then have \"g1 (2 *\\<^sub>R x) = g1 (2 *\\<^sub>R y)\"\n      using xy(3)\n      unfolding joinpaths_def\n      by auto\n    moreover have \"2 *\\<^sub>R x \\<in> {0..1}\" \"2 *\\<^sub>R y \\<in> {0..1}\"\n      using xy(1,2) as\n      by auto\n    ultimately show ?thesis\n      using inj(1)[of \"2*\\<^sub>R x\" \"2*\\<^sub>R y\"]\n      by auto\n  next\n    assume as: \"x > 1 / 2\" \"y > 1 / 2\"\n    then have \"g2 (2 *\\<^sub>R x - 1) = g2 (2 *\\<^sub>R y - 1)\"\n      using xy(3)\n      unfolding joinpaths_def\n      by auto\n    moreover have \"2 *\\<^sub>R x - 1 \\<in> {0..1}\" \"2 *\\<^sub>R y - 1 \\<in> {0..1}\"\n      using xy(1,2) as\n      by auto\n    ultimately show ?thesis\n      using inj(2)[of \"2*\\<^sub>R x - 1\" \"2*\\<^sub>R y - 1\"] by auto\n  next\n    assume as: \"x \\<le> 1 / 2\" \"y > 1 / 2\"\n    then have \"?g x \\<in> path_image g1\" \"?g y \\<in> path_image g2\"\n      unfolding path_image_def joinpaths_def\n      using xy(1,2) by auto\n    moreover have \"?g y \\<noteq> pathstart g2\"\n      using as(2)\n      unfolding pathstart_def joinpaths_def\n      using inj(2)[of \"2 *\\<^sub>R y - 1\" 0] and xy(2)\n      by (auto simp add: field_simps)\n    ultimately have *: \"?g x = pathstart g1\"\n      using assms(4)\n      unfolding xy(3)\n      by auto\n    then have \"x = 0\"\n      unfolding pathstart_def joinpaths_def\n      using as(1) and xy(1)\n      using inj(1)[of \"2 *\\<^sub>R x\" 0]\n      by auto\n    moreover have \"y = 1\"\n      using *\n      unfolding xy(3) assms(3)[symmetric]\n      unfolding joinpaths_def pathfinish_def\n      using as(2) and xy(2)\n      using inj(2)[of \"2 *\\<^sub>R y - 1\" 1]\n      by auto\n    ultimately show ?thesis\n      by auto\n  next\n    assume as: \"x > 1 / 2\" \"y \\<le> 1 / 2\"\n    then have \"?g x \\<in> path_image g2\" and \"?g y \\<in> path_image g1\"\n      unfolding path_image_def joinpaths_def\n      using xy(1,2) by auto\n    moreover have \"?g x \\<noteq> pathstart g2\"\n      using as(1)\n      unfolding pathstart_def joinpaths_def\n      using inj(2)[of \"2 *\\<^sub>R x - 1\" 0] and xy(1)\n      by (auto simp add: field_simps)\n    ultimately have *: \"?g y = pathstart g1\"\n      using assms(4)\n      unfolding xy(3)\n      by auto\n    then have \"y = 0\"\n      unfolding pathstart_def joinpaths_def\n      using as(2) and xy(2)\n      using inj(1)[of \"2 *\\<^sub>R y\" 0]\n      by auto\n    moreover have \"x = 1\"\n      using *\n      unfolding xy(3)[symmetric] assms(3)[symmetric]\n      unfolding joinpaths_def pathfinish_def using as(1) and xy(1)\n      using inj(2)[of \"2 *\\<^sub>R x - 1\" 1]\n      by auto\n    ultimately show ?thesis\n      by auto\n  qed\nqed\n\nlemma injective_path_join:\n  assumes \"injective_path g1\"\n    and \"injective_path g2\"\n    and \"pathfinish g1 = pathstart g2\"\n    and \"path_image g1 \\<inter> path_image g2 \\<subseteq> {pathstart g2}\"\n  shows \"injective_path (g1 +++ g2)\"\n  unfolding injective_path_def\nproof (rule, rule, rule)\n  let ?g = \"g1 +++ g2\"\n  note inj = assms(1,2)[unfolded injective_path_def, rule_format]\n  fix x y\n  assume xy: \"x \\<in> {0..1}\" \"y \\<in> {0..1}\" \"(g1 +++ g2) x = (g1 +++ g2) y\"\n  show \"x = y\"\n  proof (cases \"x \\<le> 1/2\", case_tac[!] \"y \\<le> 1/2\", unfold not_le)\n    assume \"x \\<le> 1 / 2\" and \"y \\<le> 1 / 2\"\n    then show ?thesis\n      using inj(1)[of \"2*\\<^sub>R x\" \"2*\\<^sub>R y\"] and xy\n      unfolding joinpaths_def by auto\n  next\n    assume \"x > 1 / 2\" and \"y > 1 / 2\"\n    then show ?thesis\n      using inj(2)[of \"2*\\<^sub>R x - 1\" \"2*\\<^sub>R y - 1\"] and xy\n      unfolding joinpaths_def by auto\n  next\n    assume as: \"x \\<le> 1 / 2\" \"y > 1 / 2\"\n    then have \"?g x \\<in> path_image g1\" and \"?g y \\<in> path_image g2\"\n      unfolding path_image_def joinpaths_def\n      using xy(1,2)\n      by auto\n    then have \"?g x = pathfinish g1\" and \"?g y = pathstart g2\"\n      using assms(4)\n      unfolding assms(3) xy(3)\n      by auto\n    then show ?thesis\n      using as and inj(1)[of \"2 *\\<^sub>R x\" 1] inj(2)[of \"2 *\\<^sub>R y - 1\" 0] and xy(1,2)\n      unfolding pathstart_def pathfinish_def joinpaths_def\n      by auto\n  next\n    assume as:\"x > 1 / 2\" \"y \\<le> 1 / 2\"\n    then have \"?g x \\<in> path_image g2\" and \"?g y \\<in> path_image g1\"\n      unfolding path_image_def joinpaths_def\n      using xy(1,2)\n      by auto\n    then have \"?g x = pathstart g2\" and \"?g y = pathfinish g1\"\n      using assms(4)\n      unfolding assms(3) xy(3)\n      by auto\n    then show ?thesis using as and inj(2)[of \"2 *\\<^sub>R x - 1\" 0] inj(1)[of \"2 *\\<^sub>R y\" 1] and xy(1,2)\n      unfolding pathstart_def pathfinish_def joinpaths_def\n      by auto\n  qed\nqed\n\nlemmas join_paths_simps = path_join path_image_join pathstart_join pathfinish_join\n\n\nsubsection {* Reparametrizing a closed curve to start at some chosen point *}\n\ndefinition shiftpath :: \"real \\<Rightarrow> (real \\<Rightarrow> 'a::topological_space) \\<Rightarrow> real \\<Rightarrow> 'a\"\n  where \"shiftpath a f = (\\<lambda>x. if (a + x) \\<le> 1 then f (a + x) else f (a + x - 1))\"\n\nlemma pathstart_shiftpath: \"a \\<le> 1 \\<Longrightarrow> pathstart (shiftpath a g) = g a\"\n  unfolding pathstart_def shiftpath_def by auto\n\nlemma pathfinish_shiftpath:\n  assumes \"0 \\<le> a\"\n    and \"pathfinish g = pathstart g\"\n  shows \"pathfinish (shiftpath a g) = g a\"\n  using assms\n  unfolding pathstart_def pathfinish_def shiftpath_def\n  by auto\n\nlemma endpoints_shiftpath:\n  assumes \"pathfinish g = pathstart g\"\n    and \"a \\<in> {0 .. 1}\"\n  shows \"pathfinish (shiftpath a g) = g a\"\n    and \"pathstart (shiftpath a g) = g a\"\n  using assms\n  by (auto intro!: pathfinish_shiftpath pathstart_shiftpath)\n\nlemma closed_shiftpath:\n  assumes \"pathfinish g = pathstart g\"\n    and \"a \\<in> {0..1}\"\n  shows \"pathfinish (shiftpath a g) = pathstart (shiftpath a g)\"\n  using endpoints_shiftpath[OF assms]\n  by auto\n\nlemma path_shiftpath:\n  assumes \"path g\"\n    and \"pathfinish g = pathstart g\"\n    and \"a \\<in> {0..1}\"\n  shows \"path (shiftpath a g)\"\nproof -\n  have *: \"{0 .. 1} = {0 .. 1-a} \\<union> {1-a .. 1}\"\n    using assms(3) by auto\n  have **: \"\\<And>x. x + a = 1 \\<Longrightarrow> g (x + a - 1) = g (x + a)\"\n    using assms(2)[unfolded pathfinish_def pathstart_def]\n    by auto\n  show ?thesis\n    unfolding path_def shiftpath_def *\n    apply (rule continuous_on_union)\n    apply (rule closed_real_atLeastAtMost)+\n    apply (rule continuous_on_eq[of _ \"g \\<circ> (\\<lambda>x. a + x)\"])\n    prefer 3\n    apply (rule continuous_on_eq[of _ \"g \\<circ> (\\<lambda>x. a - 1 + x)\"])\n    defer\n    prefer 3\n    apply (rule continuous_intros)+\n    prefer 2\n    apply (rule continuous_intros)+\n    apply (rule_tac[1-2] continuous_on_subset[OF assms(1)[unfolded path_def]])\n    using assms(3) and **\n    apply auto\n    apply (auto simp add: field_simps)\n    done\nqed\n\nlemma shiftpath_shiftpath:\n  assumes \"pathfinish g = pathstart g\"\n    and \"a \\<in> {0..1}\"\n    and \"x \\<in> {0..1}\"\n  shows \"shiftpath (1 - a) (shiftpath a g) x = g x\"\n  using assms\n  unfolding pathfinish_def pathstart_def shiftpath_def\n  by auto\n\nlemma path_image_shiftpath:\n  assumes \"a \\<in> {0..1}\"\n    and \"pathfinish g = pathstart g\"\n  shows \"path_image (shiftpath a g) = path_image g\"\nproof -\n  { fix x\n    assume as: \"g 1 = g 0\" \"x \\<in> {0..1::real}\" \" \\<forall>y\\<in>{0..1} \\<inter> {x. \\<not> a + x \\<le> 1}. g x \\<noteq> g (a + y - 1)\"\n    then have \"\\<exists>y\\<in>{0..1} \\<inter> {x. a + x \\<le> 1}. g x = g (a + y)\"\n    proof (cases \"a \\<le> x\")\n      case False\n      then show ?thesis\n        apply (rule_tac x=\"1 + x - a\" in bexI)\n        using as(1,2) and as(3)[THEN bspec[where x=\"1 + x - a\"]] and assms(1)\n        apply (auto simp add: field_simps atomize_not)\n        done\n    next\n      case True\n      then show ?thesis\n        using as(1-2) and assms(1)\n        apply (rule_tac x=\"x - a\" in bexI)\n        apply (auto simp add: field_simps)\n        done\n    qed\n  }\n  then show ?thesis\n    using assms\n    unfolding shiftpath_def path_image_def pathfinish_def pathstart_def\n    by (auto simp add: image_iff)\nqed\n\n\nsubsection {* Special case of straight-line paths *}\n\ndefinition linepath :: \"'a::real_normed_vector \\<Rightarrow> 'a \\<Rightarrow> real \\<Rightarrow> 'a\"\n  where \"linepath a b = (\\<lambda>x. (1 - x) *\\<^sub>R a + x *\\<^sub>R b)\"\n\nlemma pathstart_linepath[simp]: \"pathstart (linepath a b) = a\"\n  unfolding pathstart_def linepath_def\n  by auto\n\nlemma pathfinish_linepath[simp]: \"pathfinish (linepath a b) = b\"\n  unfolding pathfinish_def linepath_def\n  by auto\n\nlemma continuous_linepath_at[intro]: \"continuous (at x) (linepath a b)\"\n  unfolding linepath_def\n  by (intro continuous_intros)\n\nlemma continuous_on_linepath[intro]: \"continuous_on s (linepath a b)\"\n  using continuous_linepath_at\n  by (auto intro!: continuous_at_imp_continuous_on)\n\nlemma path_linepath[intro]: \"path (linepath a b)\"\n  unfolding path_def\n  by (rule continuous_on_linepath)\n\nlemma path_image_linepath[simp]: \"path_image (linepath a b) = closed_segment a b\"\n  unfolding path_image_def segment linepath_def\n  apply (rule set_eqI)\n  apply rule\n  defer\n  unfolding mem_Collect_eq image_iff\n  apply (erule exE)\n  apply (rule_tac x=\"u *\\<^sub>R 1\" in bexI)\n  apply auto\n  done\n\nlemma reversepath_linepath[simp]: \"reversepath (linepath a b) = linepath b a\"\n  unfolding reversepath_def linepath_def\n  by auto\n\nlemma injective_path_linepath:\n  assumes \"a \\<noteq> b\"\n  shows \"injective_path (linepath a b)\"\nproof -\n  {\n    fix x y :: \"real\"\n    assume \"x *\\<^sub>R b + y *\\<^sub>R a = x *\\<^sub>R a + y *\\<^sub>R b\"\n    then have \"(x - y) *\\<^sub>R a = (x - y) *\\<^sub>R b\"\n      by (simp add: algebra_simps)\n    with assms have \"x = y\"\n      by simp\n  }\n  then show ?thesis\n    unfolding injective_path_def linepath_def\n    by (auto simp add: algebra_simps)\nqed\n\nlemma simple_path_linepath[intro]: \"a \\<noteq> b \\<Longrightarrow> simple_path (linepath a b)\"\n  by (auto intro!: injective_imp_simple_path injective_path_linepath)\n\n\nsubsection {* Bounding a point away from a path *}\n\nlemma not_on_path_ball:\n  fixes g :: \"real \\<Rightarrow> 'a::heine_borel\"\n  assumes \"path g\"\n    and \"z \\<notin> path_image g\"\n  shows \"\\<exists>e > 0. ball z e \\<inter> path_image g = {}\"\nproof -\n  obtain a where \"a \\<in> path_image g\" \"\\<forall>y \\<in> path_image g. dist z a \\<le> dist z y\"\n    using distance_attains_inf[OF _ path_image_nonempty, of g z]\n    using compact_path_image[THEN compact_imp_closed, OF assms(1)] by auto\n  then show ?thesis\n    apply (rule_tac x=\"dist z a\" in exI)\n    using assms(2)\n    apply (auto intro!: dist_pos_lt)\n    done\nqed\n\nlemma not_on_path_cball:\n  fixes g :: \"real \\<Rightarrow> 'a::heine_borel\"\n  assumes \"path g\"\n    and \"z \\<notin> path_image g\"\n  shows \"\\<exists>e>0. cball z e \\<inter> (path_image g) = {}\"\nproof -\n  obtain e where \"ball z e \\<inter> path_image g = {}\" \"e > 0\"\n    using not_on_path_ball[OF assms] by auto\n  moreover have \"cball z (e/2) \\<subseteq> ball z e\"\n    using `e > 0` by auto\n  ultimately show ?thesis\n    apply (rule_tac x=\"e/2\" in exI)\n    apply auto\n    done\nqed\n\n\nsubsection {* Path component, considered as a \"joinability\" relation (from Tom Hales) *}\n\ndefinition \"path_component s x y \\<longleftrightarrow>\n  (\\<exists>g. path g \\<and> path_image g \\<subseteq> s \\<and> pathstart g = x \\<and> pathfinish g = y)\"\n\nlemmas path_defs = path_def pathstart_def pathfinish_def path_image_def path_component_def\n\nlemma path_component_mem:\n  assumes \"path_component s x y\"\n  shows \"x \\<in> s\" and \"y \\<in> s\"\n  using assms\n  unfolding path_defs\n  by auto\n\nlemma path_component_refl:\n  assumes \"x \\<in> s\"\n  shows \"path_component s x x\"\n  unfolding path_defs\n  apply (rule_tac x=\"\\<lambda>u. x\" in exI)\n  using assms\n  apply (auto intro!: continuous_intros)\n  done\n\nlemma path_component_refl_eq: \"path_component s x x \\<longleftrightarrow> x \\<in> s\"\n  by (auto intro!: path_component_mem path_component_refl)\n\nlemma path_component_sym: \"path_component s x y \\<Longrightarrow> path_component s y x\"\n  using assms\n  unfolding path_component_def\n  apply (erule exE)\n  apply (rule_tac x=\"reversepath g\" in exI)\n  apply auto\n  done\n\nlemma path_component_trans:\n  assumes \"path_component s x y\"\n    and \"path_component s y z\"\n  shows \"path_component s x z\"\n  using assms\n  unfolding path_component_def\n  apply (elim exE)\n  apply (rule_tac x=\"g +++ ga\" in exI)\n  apply (auto simp add: path_image_join)\n  done\n\nlemma path_component_of_subset: \"s \\<subseteq> t \\<Longrightarrow> path_component s x y \\<Longrightarrow> path_component t x y\"\n  unfolding path_component_def by auto\n\n\ntext {* Can also consider it as a set, as the name suggests. *}\n\nlemma path_component_set:\n  \"{y. path_component s x y} =\n    {y. (\\<exists>g. path g \\<and> path_image g \\<subseteq> s \\<and> pathstart g = x \\<and> pathfinish g = y)}\"\n  apply (rule set_eqI)\n  unfolding mem_Collect_eq\n  unfolding path_component_def\n  apply auto\n  done\n\nlemma path_component_subset: \"{y. path_component s x y} \\<subseteq> s\"\n  apply rule\n  apply (rule path_component_mem(2))\n  apply auto\n  done\n\nlemma path_component_eq_empty: \"{y. path_component s x y} = {} \\<longleftrightarrow> x \\<notin> s\"\n  apply rule\n  apply (drule equals0D[of _ x])\n  defer\n  apply (rule equals0I)\n  unfolding mem_Collect_eq\n  apply (drule path_component_mem(1))\n  using path_component_refl\n  apply auto\n  done\n\n\nsubsection {* Path connectedness of a space *}\n\ndefinition \"path_connected s \\<longleftrightarrow>\n  (\\<forall>x\\<in>s. \\<forall>y\\<in>s. \\<exists>g. path g \\<and> path_image g \\<subseteq> s \\<and> pathstart g = x \\<and> pathfinish g = y)\"\n\nlemma path_connected_component: \"path_connected s \\<longleftrightarrow> (\\<forall>x\\<in>s. \\<forall>y\\<in>s. path_component s x y)\"\n  unfolding path_connected_def path_component_def by auto\n\nlemma path_connected_component_set: \"path_connected s \\<longleftrightarrow> (\\<forall>x\\<in>s. {y. path_component s x y} = s)\"\n  unfolding path_connected_component\n  apply rule\n  apply rule\n  apply rule\n  apply (rule path_component_subset)\n  unfolding subset_eq mem_Collect_eq Ball_def\n  apply auto\n  done\n\n\nsubsection {* Some useful lemmas about path-connectedness *}\n\nlemma convex_imp_path_connected:\n  fixes s :: \"'a::real_normed_vector set\"\n  assumes \"convex s\"\n  shows \"path_connected s\"\n  unfolding path_connected_def\n  apply rule\n  apply rule\n  apply (rule_tac x = \"linepath x y\" in exI)\n  unfolding path_image_linepath\n  using assms [unfolded convex_contains_segment]\n  apply auto\n  done\n\nlemma path_connected_imp_connected:\n  assumes \"path_connected s\"\n  shows \"connected s\"\n  unfolding connected_def not_ex\n  apply rule\n  apply rule\n  apply (rule ccontr)\n  unfolding not_not\n  apply (elim conjE)\nproof -\n  fix e1 e2\n  assume as: \"open e1\" \"open e2\" \"s \\<subseteq> e1 \\<union> e2\" \"e1 \\<inter> e2 \\<inter> s = {}\" \"e1 \\<inter> s \\<noteq> {}\" \"e2 \\<inter> s \\<noteq> {}\"\n  then obtain x1 x2 where obt:\"x1 \\<in> e1 \\<inter> s\" \"x2 \\<in> e2 \\<inter> s\"\n    by auto\n  then obtain g where g: \"path g\" \"path_image g \\<subseteq> s\" \"pathstart g = x1\" \"pathfinish g = x2\"\n    using assms[unfolded path_connected_def,rule_format,of x1 x2] by auto\n  have *: \"connected {0..1::real}\"\n    by (auto intro!: convex_connected convex_real_interval)\n  have \"{0..1} \\<subseteq> {x \\<in> {0..1}. g x \\<in> e1} \\<union> {x \\<in> {0..1}. g x \\<in> e2}\"\n    using as(3) g(2)[unfolded path_defs] by blast\n  moreover have \"{x \\<in> {0..1}. g x \\<in> e1} \\<inter> {x \\<in> {0..1}. g x \\<in> e2} = {}\"\n    using as(4) g(2)[unfolded path_defs]\n    unfolding subset_eq\n    by auto\n  moreover have \"{x \\<in> {0..1}. g x \\<in> e1} \\<noteq> {} \\<and> {x \\<in> {0..1}. g x \\<in> e2} \\<noteq> {}\"\n    using g(3,4)[unfolded path_defs]\n    using obt\n    by (simp add: ex_in_conv [symmetric], metis zero_le_one order_refl)\n  ultimately show False\n    using *[unfolded connected_local not_ex, rule_format,\n      of \"{x\\<in>{0..1}. g x \\<in> e1}\" \"{x\\<in>{0..1}. g x \\<in> e2}\"]\n    using continuous_open_in_preimage[OF g(1)[unfolded path_def] as(1)]\n    using continuous_open_in_preimage[OF g(1)[unfolded path_def] as(2)]\n    by auto\nqed\n\nlemma open_path_component:\n  fixes s :: \"'a::real_normed_vector set\"\n  assumes \"open s\"\n  shows \"open {y. path_component s x y}\"\n  unfolding open_contains_ball\nproof\n  fix y\n  assume as: \"y \\<in> {y. path_component s x y}\"\n  then have \"y \\<in> s\"\n    apply -\n    apply (rule path_component_mem(2))\n    unfolding mem_Collect_eq\n    apply auto\n    done\n  then obtain e where e: \"e > 0\" \"ball y e \\<subseteq> s\"\n    using assms[unfolded open_contains_ball]\n    by auto\n  show \"\\<exists>e > 0. ball y e \\<subseteq> {y. path_component s x y}\"\n    apply (rule_tac x=e in exI)\n    apply (rule,rule `e>0`)\n    apply rule\n    unfolding mem_ball mem_Collect_eq\n  proof -\n    fix z\n    assume \"dist y z < e\"\n    then show \"path_component s x z\"\n      apply (rule_tac path_component_trans[of _ _ y])\n      defer\n      apply (rule path_component_of_subset[OF e(2)])\n      apply (rule convex_imp_path_connected[OF convex_ball, unfolded path_connected_component, rule_format])\n      using `e > 0` as\n      apply auto\n      done\n  qed\nqed\n\nlemma open_non_path_component:\n  fixes s :: \"'a::real_normed_vector set\"\n  assumes \"open s\"\n  shows \"open (s - {y. path_component s x y})\"\n  unfolding open_contains_ball\nproof\n  fix y\n  assume as: \"y \\<in> s - {y. path_component s x y}\"\n  then obtain e where e: \"e > 0\" \"ball y e \\<subseteq> s\"\n    using assms [unfolded open_contains_ball]\n    by auto\n  show \"\\<exists>e>0. ball y e \\<subseteq> s - {y. path_component s x y}\"\n    apply (rule_tac x=e in exI)\n    apply rule\n    apply (rule `e>0`)\n    apply rule\n    apply rule\n    defer\n  proof (rule ccontr)\n    fix z\n    assume \"z \\<in> ball y e\" \"\\<not> z \\<notin> {y. path_component s x y}\"\n    then have \"y \\<in> {y. path_component s x y}\"\n      unfolding not_not mem_Collect_eq using `e>0`\n      apply -\n      apply (rule path_component_trans, assumption)\n      apply (rule path_component_of_subset[OF e(2)])\n      apply (rule convex_imp_path_connected[OF convex_ball, unfolded path_connected_component, rule_format])\n      apply auto\n      done\n    then show False\n      using as by auto\n  qed (insert e(2), auto)\nqed\n\nlemma connected_open_path_connected:\n  fixes s :: \"'a::real_normed_vector set\"\n  assumes \"open s\"\n    and \"connected s\"\n  shows \"path_connected s\"\n  unfolding path_connected_component_set\nproof (rule, rule, rule path_component_subset, rule)\n  fix x y\n  assume \"x \\<in> s\" and \"y \\<in> s\"\n  show \"y \\<in> {y. path_component s x y}\"\n  proof (rule ccontr)\n    assume \"\\<not> ?thesis\"\n    moreover have \"{y. path_component s x y} \\<inter> s \\<noteq> {}\"\n      using `x \\<in> s` path_component_eq_empty path_component_subset[of s x]\n      by auto\n    ultimately\n    show False\n      using `y \\<in> s` open_non_path_component[OF assms(1)] open_path_component[OF assms(1)]\n      using assms(2)[unfolded connected_def not_ex, rule_format,\n        of\"{y. path_component s x y}\" \"s - {y. path_component s x y}\"]\n      by auto\n  qed\nqed\n\nlemma path_connected_continuous_image:\n  assumes \"continuous_on s f\"\n    and \"path_connected s\"\n  shows \"path_connected (f ` s)\"\n  unfolding path_connected_def\nproof (rule, rule)\n  fix x' y'\n  assume \"x' \\<in> f ` s\" \"y' \\<in> f ` s\"\n  then obtain x y where x: \"x \\<in> s\" and y: \"y \\<in> s\" and x': \"x' = f x\" and y': \"y' = f y\"\n    by auto\n  from x y obtain g where \"path g \\<and> path_image g \\<subseteq> s \\<and> pathstart g = x \\<and> pathfinish g = y\"\n    using assms(2)[unfolded path_connected_def] by fast\n  then show \"\\<exists>g. path g \\<and> path_image g \\<subseteq> f ` s \\<and> pathstart g = x' \\<and> pathfinish g = y'\"\n    unfolding x' y'\n    apply (rule_tac x=\"f \\<circ> g\" in exI)\n    unfolding path_defs\n    apply (intro conjI continuous_on_compose continuous_on_subset[OF assms(1)])\n    apply auto\n    done\nqed\n\nlemma homeomorphic_path_connectedness:\n  \"s homeomorphic t \\<Longrightarrow> path_connected s \\<longleftrightarrow> path_connected t\"\n  unfolding homeomorphic_def homeomorphism_def\n  apply (erule exE|erule conjE)+\n  apply rule\n  apply (drule_tac f=f in path_connected_continuous_image)\n  prefer 3\n  apply (drule_tac f=g in path_connected_continuous_image)\n  apply auto\n  done\n\nlemma path_connected_empty: \"path_connected {}\"\n  unfolding path_connected_def by auto\n\nlemma path_connected_singleton: \"path_connected {a}\"\n  unfolding path_connected_def pathstart_def pathfinish_def path_image_def\n  apply clarify\n  apply (rule_tac x=\"\\<lambda>x. a\" in exI)\n  apply (simp add: image_constant_conv)\n  apply (simp add: path_def continuous_on_const)\n  done\n\nlemma path_connected_Un:\n  assumes \"path_connected s\"\n    and \"path_connected t\"\n    and \"s \\<inter> t \\<noteq> {}\"\n  shows \"path_connected (s \\<union> t)\"\n  unfolding path_connected_component\nproof (rule, rule)\n  fix x y\n  assume as: \"x \\<in> s \\<union> t\" \"y \\<in> s \\<union> t\"\n  from assms(3) obtain z where \"z \\<in> s \\<inter> t\"\n    by auto\n  then show \"path_component (s \\<union> t) x y\"\n    using as and assms(1-2)[unfolded path_connected_component]\n    apply -\n    apply (erule_tac[!] UnE)+\n    apply (rule_tac[2-3] path_component_trans[of _ _ z])\n    apply (auto simp add:path_component_of_subset [OF Un_upper1] path_component_of_subset[OF Un_upper2])\n    done\nqed\n\nlemma path_connected_UNION:\n  assumes \"\\<And>i. i \\<in> A \\<Longrightarrow> path_connected (S i)\"\n    and \"\\<And>i. i \\<in> A \\<Longrightarrow> z \\<in> S i\"\n  shows \"path_connected (\\<Union>i\\<in>A. S i)\"\n  unfolding path_connected_component\nproof clarify\n  fix x i y j\n  assume *: \"i \\<in> A\" \"x \\<in> S i\" \"j \\<in> A\" \"y \\<in> S j\"\n  then have \"path_component (S i) x z\" and \"path_component (S j) z y\"\n    using assms by (simp_all add: path_connected_component)\n  then have \"path_component (\\<Union>i\\<in>A. S i) x z\" and \"path_component (\\<Union>i\\<in>A. S i) z y\"\n    using *(1,3) by (auto elim!: path_component_of_subset [rotated])\n  then show \"path_component (\\<Union>i\\<in>A. S i) x y\"\n    by (rule path_component_trans)\nqed\n\n\nsubsection {* Sphere is path-connected *}\n\nlemma path_connected_punctured_universe:\n  assumes \"2 \\<le> DIM('a::euclidean_space)\"\n  shows \"path_connected ((UNIV::'a set) - {a})\"\nproof -\n  let ?A = \"{x::'a. \\<exists>i\\<in>Basis. x \\<bullet> i < a \\<bullet> i}\"\n  let ?B = \"{x::'a. \\<exists>i\\<in>Basis. a \\<bullet> i < x \\<bullet> i}\"\n\n  have A: \"path_connected ?A\"\n    unfolding Collect_bex_eq\n  proof (rule path_connected_UNION)\n    fix i :: 'a\n    assume \"i \\<in> Basis\"\n    then show \"(\\<Sum>i\\<in>Basis. (a \\<bullet> i - 1)*\\<^sub>R i) \\<in> {x::'a. x \\<bullet> i < a \\<bullet> i}\"\n      by simp\n    show \"path_connected {x. x \\<bullet> i < a \\<bullet> i}\"\n      using convex_imp_path_connected [OF convex_halfspace_lt, of i \"a \\<bullet> i\"]\n      by (simp add: inner_commute)\n  qed\n  have B: \"path_connected ?B\"\n    unfolding Collect_bex_eq\n  proof (rule path_connected_UNION)\n    fix i :: 'a\n    assume \"i \\<in> Basis\"\n    then show \"(\\<Sum>i\\<in>Basis. (a \\<bullet> i + 1) *\\<^sub>R i) \\<in> {x::'a. a \\<bullet> i < x \\<bullet> i}\"\n      by simp\n    show \"path_connected {x. a \\<bullet> i < x \\<bullet> i}\"\n      using convex_imp_path_connected [OF convex_halfspace_gt, of \"a \\<bullet> i\" i]\n      by (simp add: inner_commute)\n  qed\n  obtain S :: \"'a set\" where \"S \\<subseteq> Basis\" and \"card S = Suc (Suc 0)\"\n    using ex_card[OF assms]\n    by auto\n  then obtain b0 b1 :: 'a where \"b0 \\<in> Basis\" and \"b1 \\<in> Basis\" and \"b0 \\<noteq> b1\"\n    unfolding card_Suc_eq by auto\n  then have \"a + b0 - b1 \\<in> ?A \\<inter> ?B\"\n    by (auto simp: inner_simps inner_Basis)\n  then have \"?A \\<inter> ?B \\<noteq> {}\"\n    by fast\n  with A B have \"path_connected (?A \\<union> ?B)\"\n    by (rule path_connected_Un)\n  also have \"?A \\<union> ?B = {x. \\<exists>i\\<in>Basis. x \\<bullet> i \\<noteq> a \\<bullet> i}\"\n    unfolding neq_iff bex_disj_distrib Collect_disj_eq ..\n  also have \"\\<dots> = {x. x \\<noteq> a}\"\n    unfolding euclidean_eq_iff [where 'a='a]\n    by (simp add: Bex_def)\n  also have \"\\<dots> = UNIV - {a}\"\n    by auto\n  finally show ?thesis .\nqed\n\nlemma path_connected_sphere:\n  assumes \"2 \\<le> DIM('a::euclidean_space)\"\n  shows \"path_connected {x::'a. norm (x - a) = r}\"\nproof (rule linorder_cases [of r 0])\n  assume \"r < 0\"\n  then have \"{x::'a. norm(x - a) = r} = {}\"\n    by auto\n  then show ?thesis\n    using path_connected_empty by simp\nnext\n  assume \"r = 0\"\n  then show ?thesis\n    using path_connected_singleton by simp\nnext\n  assume r: \"0 < r\"\n  have *: \"{x::'a. norm(x - a) = r} = (\\<lambda>x. a + r *\\<^sub>R x) ` {x. norm x = 1}\"\n    apply (rule set_eqI)\n    apply rule\n    unfolding image_iff\n    apply (rule_tac x=\"(1/r) *\\<^sub>R (x - a)\" in bexI)\n    unfolding mem_Collect_eq norm_scaleR\n    using r\n    apply (auto simp add: scaleR_right_diff_distrib)\n    done\n  have **: \"{x::'a. norm x = 1} = (\\<lambda>x. (1/norm x) *\\<^sub>R x) ` (UNIV - {0})\"\n    apply (rule set_eqI)\n    apply rule\n    unfolding image_iff\n    apply (rule_tac x=x in bexI)\n    unfolding mem_Collect_eq\n    apply (auto split: split_if_asm)\n    done\n  have \"continuous_on (UNIV - {0}) (\\<lambda>x::'a. 1 / norm x)\"\n    unfolding field_divide_inverse\n    by (simp add: continuous_intros)\n  then show ?thesis\n    unfolding * **\n    using path_connected_punctured_universe[OF assms]\n    by (auto intro!: path_connected_continuous_image continuous_intros)\nqed\n\nlemma connected_sphere: \"2 \\<le> DIM('a::euclidean_space) \\<Longrightarrow> connected {x::'a. norm (x - a) = r}\"\n  using path_connected_sphere path_connected_imp_connected\n  by 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/Multivariate_Analysis/Path_Connected.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297754396142, "lm_q2_score": 0.8175744828610095, "lm_q1q2_score": 0.7362501654559837}}
{"text": "(*<*)\ntheory Bool_nat_list\nimports Main\nbegin\n(*>*)\n\ntext{*\n\\vspace{-4ex}\n\\section{\\texorpdfstring{Types @{typ bool}, @{typ nat} and @{text list}}{Types bool, nat and list}}\n\nThese are the most important predefined types. We go through them one by one.\nBased on examples we learn how to define (possibly recursive) functions and\nprove theorems about them by induction and simplification.\n\n\\subsection{Type \\indexed{@{typ bool}}{bool}}\n\nThe type of boolean values is a predefined datatype\n@{datatype[display] bool}\nwith the two values \\indexed{@{const True}}{True} and \\indexed{@{const False}}{False} and\nwith many predefined functions:  @{text \"\\<not>\"}, @{text \"\\<and>\"}, @{text \"\\<or>\"}, @{text\n\"\\<longrightarrow>\"}, etc. Here is how conjunction could be defined by pattern matching:\n*}\n\nfun conj :: \"bool \\<Rightarrow> bool \\<Rightarrow> bool\" where\n\"conj True True = True\" |\n\"conj _ _ = False\"\n\ntext{* Both the datatype and function definitions roughly follow the syntax\nof functional programming languages.\n\n\\subsection{Type \\indexed{@{typ nat}}{nat}}\n\nNatural numbers are another predefined datatype:\n@{datatype[display] nat}\\index{Suc@@{const Suc}}\nAll values of type @{typ nat} are generated by the constructors\n@{text 0} and @{const Suc}. Thus the values of type @{typ nat} are\n@{text 0}, @{term\"Suc 0\"}, @{term\"Suc(Suc 0)\"}, etc.\nThere are many predefined functions: @{text \"+\"}, @{text \"*\"}, @{text\n\"\\<le>\"}, etc. Here is how you could define your own addition:\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{* And here is a proof of the fact that @{prop\"add m 0 = m\"}: *}\n\nlemma add_02: \"add m 0 = m\"\napply(induction m)\napply(auto)\ndone\n(*<*)\nlemma \"add m 0 = m\"\napply(induction m)\n(*>*)\ntxt{* The \\isacom{lemma} command starts the proof and gives the lemma\na name, @{text add_02}. Properties of recursively defined functions\nneed to be established by induction in most cases.\nCommand \\isacom{apply}@{text\"(induction m)\"} instructs Isabelle to\nstart a proof by induction on @{text m}. In response, it will show the\nfollowing proof state\\ifsem\\footnote{See page \\pageref{proof-state} for how to\ndisplay the proof state.}\\fi:\n@{subgoals[display,indent=0]}\nThe numbered lines are known as \\emph{subgoals}.\nThe first subgoal is the base case, the second one the induction step.\nThe prefix @{text\"\\<And>m.\"} is Isabelle's way of saying ``for an arbitrary but fixed @{text m}''. The @{text\"\\<Longrightarrow>\"} separates assumptions from the conclusion.\nThe command \\isacom{apply}@{text\"(auto)\"} instructs Isabelle to try\nand prove all subgoals automatically, essentially by simplifying them.\nBecause both subgoals are easy, Isabelle can do it.\nThe base case @{prop\"add 0 0 = 0\"} holds by definition of @{const add},\nand the induction step is almost as simple:\n@{text\"add\\<^latex>\\<open>~\\<close>(Suc m) 0 = Suc(add m 0) = Suc m\"}\nusing first the definition of @{const add} and then the induction hypothesis.\nIn summary, both subproofs rely on simplification with function definitions and\nthe induction hypothesis.\nAs a result of that final \\isacom{done}, Isabelle associates the lemma\njust proved with its name. You can now inspect the lemma with the command\n*}\n\nthm add_02\n\ntxt{* which displays @{thm[show_question_marks,display] add_02} The free\nvariable @{text m} has been replaced by the \\concept{unknown}\n@{text\"?m\"}. There is no logical difference between the two but there is an\noperational one: unknowns can be instantiated, which is what you want after\nsome lemma has been proved.\n\nNote that there is also a proof method @{text induct}, which behaves almost\nlike @{text induction}; the difference is explained in \\autoref{ch:Isar}.\n\n\\begin{warn}\nTerminology: We use \\concept{lemma}, \\concept{theorem} and \\concept{rule}\ninterchangeably for propositions that have been proved.\n\\end{warn}\n\\begin{warn}\n  Numerals (@{text 0}, @{text 1}, @{text 2}, \\dots) and most of the standard\n  arithmetic operations (@{text \"+\"}, @{text \"-\"}, @{text \"*\"}, @{text\"\\<le>\"},\n  @{text\"<\"}, etc.) are overloaded: they are available\n  not just for natural numbers but for other types as well.\n  For example, given the goal @{text\"x + 0 = x\"}, there is nothing to indicate\n  that you are talking about natural numbers. Hence Isabelle can only infer\n  that @{term x} is of some arbitrary type where @{text 0} and @{text\"+\"}\n  exist. As a consequence, you will be unable to prove the goal.\n%  To alert you to such pitfalls, Isabelle flags numerals without a\n%  fixed type in its output: @ {prop\"x+0 = x\"}.\n  In this particular example, you need to include\n  an explicit type constraint, for example @{text\"x+0 = (x::nat)\"}. If there\n  is enough contextual information this may not be necessary: @{prop\"Suc x =\n  x\"} automatically implies @{text\"x::nat\"} because @{term Suc} is not\n  overloaded.\n\\end{warn}\n\n\\subsubsection{An Informal Proof}\n\nAbove we gave some terse informal explanation of the proof of\n@{prop\"add m 0 = m\"}. A more detailed informal exposition of the lemma\nmight look like this:\n\\bigskip\n\n\\noindent\n\\textbf{Lemma} @{prop\"add m 0 = m\"}\n\n\\noindent\n\\textbf{Proof} by induction on @{text m}.\n\\begin{itemize}\n\\item Case @{text 0} (the base case): @{prop\"add 0 0 = 0\"}\n  holds by definition of @{const add}.\n\\item Case @{term\"Suc m\"} (the induction step):\n  We assume @{prop\"add m 0 = m\"}, the induction hypothesis (IH),\n  and we need to show @{text\"add (Suc m) 0 = Suc m\"}.\n  The proof is as follows:\\smallskip\n\n  \\begin{tabular}{@ {}rcl@ {\\quad}l@ {}}\n  @{term \"add (Suc m) 0\"} &@{text\"=\"}& @{term\"Suc(add m 0)\"}\n  & by definition of @{text add}\\\\\n              &@{text\"=\"}& @{term \"Suc m\"} & by IH\n  \\end{tabular}\n\\end{itemize}\nThroughout this book, \\concept{IH} will stand for ``induction hypothesis''.\n\nWe have now seen three proofs of @{prop\"add m 0 = 0\"}: the Isabelle one, the\nterse four lines explaining the base case and the induction step, and just now a\nmodel of a traditional inductive proof. The three proofs differ in the level\nof detail given and the intended reader: the Isabelle proof is for the\nmachine, the informal proofs are for humans. Although this book concentrates\non Isabelle proofs, it is important to be able to rephrase those proofs\nas informal text comprehensible to a reader familiar with traditional\nmathematical proofs. Later on we will introduce an Isabelle proof language\nthat is closer to traditional informal mathematical language and is often\ndirectly readable.\n\n\\subsection{Type \\indexed{@{text list}}{list}}\n\nAlthough lists are already predefined, we define our own copy for\ndemonstration purposes:\n*}\n(*<*)\napply(auto)\ndone \ndeclare [[names_short]]\n(*>*)\ndatatype 'a list = Nil | Cons 'a \"'a list\"\n(*<*)\nfor map: map\n(*>*)\n\ntext{*\n\\begin{itemize}\n\\item Type @{typ \"'a list\"} is the type of lists over elements of type @{typ 'a}. Because @{typ 'a} is a type variable, lists are in fact \\concept{polymorphic}: the elements of a list can be of arbitrary type (but must all be of the same type).\n\\item Lists have two constructors: @{const Nil}, the empty list, and @{const Cons}, which puts an element (of type @{typ 'a}) in front of a list (of type @{typ \"'a list\"}).\nHence all lists are of the form @{const Nil}, or @{term\"Cons x Nil\"},\nor @{term\"Cons x (Cons y Nil)\"}, etc.\n\\item \\isacom{datatype} requires no quotation marks on the\nleft-hand side, but on the right-hand side each of the argument\ntypes of a constructor needs to be enclosed in quotation marks, unless\nit is just an identifier (e.g., @{typ nat} or @{typ 'a}).\n\\end{itemize}\nWe also define two standard functions, append and reverse: *}\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\ntext{* By default, variables @{text xs}, @{text ys} and @{text zs} are of\n@{text list} type.\n\nCommand \\indexed{\\isacommand{value}}{value} evaluates a term. For example, *}\n\nvalue \"rev(Cons True (Cons False Nil))\"\n\ntext{* yields the result @{value \"rev(Cons True (Cons False Nil))\"}. This works symbolically, too: *}\n\nvalue \"rev(Cons a (Cons b Nil))\"\n\ntext{* yields @{value \"rev(Cons a (Cons b Nil))\"}.\n\\medskip\n\nFigure~\\ref{fig:MyList} shows the theory created so far.\nBecause @{text list}, @{const Nil}, @{const Cons}, etc.\\ are already predefined,\n Isabelle prints qualified (long) names when executing this theory, for example, @{text MyList.Nil}\n instead of @{const Nil}.\n To suppress the qualified names you can insert the command\n \\texttt{declare [[names\\_short]]}.\n This is not recommended in general but is convenient for this unusual example.\n% Notice where the\n%quotations marks are needed that we mostly sweep under the carpet.  In\n%particular, notice that \\isacom{datatype} requires no quotation marks on the\n%left-hand side, but that on the right-hand side each of the argument\n%types of a constructor needs to be enclosed in quotation marks.\n\n\\begin{figure}[htbp]\n\\begin{alltt}\n\\input{MyList.thy}\\end{alltt}\n\\caption{A theory of lists}\n\\label{fig:MyList}\n\\index{comment}\n\\end{figure}\n\n\\subsubsection{Structural Induction for Lists}\n\nJust as for natural numbers, there is a proof principle of induction for\nlists. Induction over a list is essentially induction over the length of\nthe list, although the length remains implicit. To prove that some property\n@{text P} holds for all lists @{text xs}, i.e., \\mbox{@{prop\"P(xs)\"}},\nyou need to prove\n\\begin{enumerate}\n\\item the base case @{prop\"P(Nil)\"} and\n\\item the inductive case @{prop\"P(Cons x xs)\"} under the assumption @{prop\"P(xs)\"}, for some arbitrary but fixed @{text x} and @{text xs}.\n\\end{enumerate}\nThis is often called \\concept{structural induction} for lists.\n\n\\subsection{The Proof Process}\n\nWe will now demonstrate the typical proof process, which involves\nthe formulation and proof of auxiliary lemmas.\nOur goal is to show that reversing a list twice produces the original\nlist. *}\n\ntheorem rev_rev [simp]: \"rev(rev xs) = xs\"\n\ntxt{* Commands \\isacom{theorem} and \\isacom{lemma} are\ninterchangeable and merely indicate the importance we attach to a\nproposition. Via the bracketed attribute @{text simp} we also tell Isabelle\nto make the eventual theorem a \\conceptnoidx{simplification rule}: future proofs\ninvolving simplification will replace occurrences of @{term\"rev(rev xs)\"} by\n@{term\"xs\"}. The proof is by induction: *}\n\napply(induction xs)\n\ntxt{*\nAs explained above, we obtain two subgoals, namely the base case (@{const Nil}) and the induction step (@{const Cons}):\n@{subgoals[display,indent=0,margin=65]}\nLet us try to solve both goals automatically:\n*}\n\napply(auto)\n\ntxt{*Subgoal~1 is proved, and disappears; the simplified version\nof subgoal~2 becomes the new subgoal~1:\n@{subgoals[display,indent=0,margin=70]}\nIn order to simplify this subgoal further, a lemma suggests itself.\n\n\\subsubsection{A First Lemma}\n\nWe insert the following lemma in front of the main theorem:\n*}\n(*<*)\noops\n(*>*)\nlemma rev_app [simp]: \"rev(app xs ys) = app (rev ys) (rev xs)\"\n\ntxt{* There are two variables that we could induct on: @{text xs} and\n@{text ys}. Because @{const app} is defined by recursion on\nthe first argument, @{text xs} is the correct one:\n*}\n\napply(induction xs)\n\ntxt{* This time not even the base case is solved automatically: *}\napply(auto)\ntxt{*\n\\vspace{-5ex}\n@{subgoals[display,goals_limit=1]}\nAgain, we need to abandon this proof attempt and prove another simple lemma\nfirst.\n\n\\subsubsection{A Second Lemma}\n\nWe again try the canonical proof procedure:\n*}\n(*<*)\noops\n(*>*)\nlemma app_Nil2 [simp]: \"app xs Nil = xs\"\napply(induction xs)\napply(auto)\ndone\n\ntext{*\nThankfully, this worked.\nNow we can continue with our stuck proof attempt of the first lemma:\n*}\n\nlemma rev_app [simp]: \"rev(app xs ys) = app (rev ys) (rev xs)\"\napply(induction xs)\napply(auto)\n\ntxt{*\nWe find that this time @{text\"auto\"} solves the base case, but the\ninduction step merely simplifies to\n@{subgoals[display,indent=0,goals_limit=1]}\nThe missing lemma is associativity of @{const app},\nwhich we insert in front of the failed lemma @{text rev_app}.\n\n\\subsubsection{Associativity of @{const app}}\n\nThe canonical proof procedure succeeds without further ado:\n*}\n(*<*)oops(*>*)\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(*>*)\ntext{*\nFinally the proofs of @{thm[source] rev_app} and @{thm[source] rev_rev}\nsucceed, too.\n\n\\subsubsection{Another Informal Proof}\n\nHere is the informal proof of associativity of @{const app}\ncorresponding to the Isabelle proof above.\n\\bigskip\n\n\\noindent\n\\textbf{Lemma} @{prop\"app (app xs ys) zs = app xs (app ys zs)\"}\n\n\\noindent\n\\textbf{Proof} by induction on @{text xs}.\n\\begin{itemize}\n\\item Case @{text Nil}: \\ @{prop\"app (app Nil ys) zs = app ys zs\"} @{text\"=\"}\n  \\mbox{@{term\"app Nil (app ys zs)\"}} \\ holds by definition of @{text app}.\n\\item Case @{text\"Cons x xs\"}: We assume\n  \\begin{center} \\hfill @{term\"app (app xs ys) zs\"} @{text\"=\"}\n  @{term\"app xs (app ys zs)\"} \\hfill (IH) \\end{center}\n  and we need to show\n  \\begin{center} @{prop\"app (app (Cons x xs) ys) zs = app (Cons x xs) (app ys zs)\"}.\\end{center}\n  The proof is as follows:\\smallskip\n\n  \\begin{tabular}{@ {}l@ {\\quad}l@ {}}\n  @{term\"app (app (Cons x xs) ys) zs\"}\\\\\n  @{text\"= app (Cons x (app xs ys)) zs\"} & by definition of @{text app}\\\\\n  @{text\"= Cons x (app (app xs ys) zs)\"} & by definition of @{text app}\\\\\n  @{text\"= Cons x (app xs (app ys zs))\"} & by IH\\\\\n  @{text\"= app (Cons x xs) (app ys zs)\"} & by definition of @{text app}\n  \\end{tabular}\n\\end{itemize}\n\\medskip\n\n\\noindent Didn't we say earlier that all proofs are by simplification? But\nin both cases, going from left to right, the last equality step is not a\nsimplification at all! In the base case it is @{prop\"app ys zs = app Nil (app\nys zs)\"}. It appears almost mysterious because we suddenly complicate the\nterm by appending @{text Nil} on the left. What is really going on is this:\nwhen proving some equality \\mbox{@{prop\"s = t\"}}, both @{text s} and @{text t} are\nsimplified until they ``meet in the middle''. This heuristic for equality proofs\nworks well for a functional programming context like ours. In the base case\nboth @{term\"app (app Nil ys) zs\"} and @{term\"app Nil (app\nys zs)\"} are simplified to @{term\"app ys zs\"}, the term in the middle.\n\n\\subsection{Predefined Lists}\n\\label{sec:predeflists}\n\nIsabelle's predefined lists are the same as the ones above, but with\nmore syntactic sugar:\n\\begin{itemize}\n\\item @{text \"[]\"} is \\indexed{@{const Nil}}{Nil},\n\\item @{term\"x # xs\"} is @{term\"Cons x xs\"}\\index{Cons@@{const Cons}},\n\\item @{text\"[x\\<^sub>1, \\<dots>, x\\<^sub>n]\"} is @{text\"x\\<^sub>1 # \\<dots> # x\\<^sub>n # []\"}, and\n\\item @{term \"xs @ ys\"} is @{term\"app xs ys\"}.\n\\end{itemize}\nThere is also a large library of predefined functions.\nThe most important ones are the length function\n@{text\"length :: 'a list \\<Rightarrow> nat\"}\\index{length@@{const length}} (with the obvious definition),\nand the \\indexed{@{const map}}{map} function that applies a function to all elements of a list:\n\\begin{isabelle}\n\\isacom{fun} @{const map} @{text\"::\"} @{typ[source] \"('a \\<Rightarrow> 'b) \\<Rightarrow> 'a list \\<Rightarrow> 'b list\"} \\isacom{where}\\\\\n@{text\"\\\"\"}@{thm list.map(1) [of f]}@{text\"\\\" |\"}\\\\\n@{text\"\\\"\"}@{thm list.map(2) [of f x xs]}@{text\"\\\"\"}\n\\end{isabelle}\n\n\\ifsem\nAlso useful are the \\concept{head} of a list, its first element,\nand the \\concept{tail}, the rest of the list:\n\\begin{isabelle}\\index{hd@@{const hd}}\n\\isacom{fun} @{text\"hd :: 'a list \\<Rightarrow> 'a\"}\\\\\n@{prop\"hd(x#xs) = x\"}\n\\end{isabelle}\n\\begin{isabelle}\\index{tl@@{const tl}}\n\\isacom{fun} @{text\"tl :: 'a list \\<Rightarrow> 'a list\"}\\\\\n@{prop\"tl [] = []\"} @{text\"|\"}\\\\\n@{prop\"tl(x#xs) = xs\"}\n\\end{isabelle}\nNote that since HOL is a logic of total functions, @{term\"hd []\"} is defined,\nbut we do now know what the result is. That is, @{term\"hd []\"} is not undefined\nbut underdefined.\n\\fi\n%\n\nFrom now on lists are always the predefined lists.\n\n\n\\subsection*{Exercises}\n\n\\begin{exercise}\nUse the \\isacom{value} command to evaluate the following expressions:\n@{term[source] \"1 + (2::nat)\"}, @{term[source] \"1 + (2::int)\"},\n@{term[source] \"1 - (2::nat)\"} and @{term[source] \"1 - (2::int)\"}.\n\\end{exercise}\n\n\\begin{exercise}\nStart from the definition of @{const add} given above.\nProve that @{const add} is associative and commutative.\nDefine a recursive function @{text double} @{text\"::\"} @{typ\"nat \\<Rightarrow> nat\"}\nand prove @{prop\"double m = add m m\"}.\n\\end{exercise}\n\n\\begin{exercise}\nDefine a function @{text\"count ::\"} @{typ\"'a \\<Rightarrow> 'a list \\<Rightarrow> nat\"}\nthat counts the number of occurrences of an element in a list. Prove\n@{prop\"count x xs \\<le> length xs\"}.\n\\end{exercise}\n\n\\begin{exercise}\nDefine a recursive function @{text \"snoc ::\"} @{typ\"'a list \\<Rightarrow> 'a \\<Rightarrow> 'a list\"}\nthat appends an element to the end of a list. With the help of @{text snoc}\ndefine a recursive function @{text \"reverse ::\"} @{typ\"'a list \\<Rightarrow> 'a list\"}\nthat reverses a list. Prove @{prop\"reverse(reverse xs) = xs\"}.\n\\end{exercise}\n\n\\begin{exercise}\nDefine a recursive function @{text \"sum_upto ::\"} @{typ\"nat \\<Rightarrow> nat\"} such that\n\\mbox{@{text\"sum_upto n\"}} @{text\"=\"} @{text\"0 + ... + n\"} and prove\n@{prop\" sum_upto (n::nat) = n * (n+1) div 2\"}.\n\\end{exercise}\n*}\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/Prog_Prove/Bool_nat_list.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8723473713594992, "lm_q2_score": 0.8438950966654772, "lm_q1q2_score": 0.7361696692792996}}
{"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 Main\nbegin\n\ntext \\<open>\n  This library lifts operations like addition and multiplication to sets. It\n  was designed to support asymptotic calculations for the now-obsolete BigO theory,\n  but has other uses.\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 sumset_empty [simp]: \"A + {} = {}\" \"{} + A = {}\"\n  by (auto simp: set_plus_def)\n\nlemma Un_set_plus: \"(A \\<union> B) + C = (A+C) \\<union> (B+C)\" and set_plus_Un: \"C + (A \\<union> B) = (C+A) \\<union> (C+B)\"\n  by (auto simp: set_plus_def)\n\nlemma \n  fixes A :: \"'a::comm_monoid_add set\"\n  shows insert_set_plus: \"(insert a A) + B = (A+B) \\<union> (((+)a) ` B)\" and set_plus_insert: \"B + (insert a A) = (B+A) \\<union> (((+)a) ` B)\"\n  using add.commute by (auto simp: set_plus_def)\n\nlemma set_add_0 [simp]:\n  fixes A :: \"'a::comm_monoid_add set\"\n  shows \"{0} + A = A\"\n  by (metis comm_monoid_add_class.add_0 set_zero)\n\nlemma set_add_0_right [simp]:\n  fixes A :: \"'a::comm_monoid_add set\"\n  shows \"A + {0} = A\"\n  by (metis add.comm_neutral set_zero)\n\nlemma card_plus_sing:\n  fixes A :: \"'a::ab_group_add set\"\n  shows \"card (A + {a}) = card A\"\nproof (rule bij_betw_same_card)\n  show \"bij_betw ((+) (-a)) (A + {a}) A\"\n    by (fastforce simp: set_plus_def bij_betw_def image_iff)\nqed\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    by (auto simp: elt_set_plus_def set_plus_def; metis group_cancel.add1 group_cancel.add2)\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  by (auto simp add: elt_set_plus_def set_plus_def; metis add.assoc)\n\ntheorem set_plus_rearrange4: \"C + (a +o D) = a +o (C + D)\"\n  for a :: \"'a::comm_monoid_add\"\n  by (metis add.commute set_plus_rearrange3)\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  using order_subst2 by blast\n\nlemma set_plus_mono_b: \"C \\<subseteq> D \\<Longrightarrow> x \\<in> a +o C \\<Longrightarrow> x \\<in> a +o D\"\n  using set_plus_mono by blast\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  using set_plus_intro by fastforce\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  by (metis add.commute diff_add_cancel set_plus_intro2)\n\nlemma set_minus_plus: \"a - b \\<in> C \\<longleftrightarrow> a \\<in> b +o C\"\n  for a b :: \"'a::ab_group_add\"\n  by (meson set_minus_imp_plus set_plus_imp_minus)\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  by (auto simp add: elt_set_times_def set_times_def; metis mult.assoc mult.left_commute)\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  by (auto simp add: elt_set_times_def set_times_def; metis mult.assoc)\n\ntheorem set_times_rearrange4: \"C * (a *o D) = a *o (C * D)\"\n  for a :: \"'a::comm_monoid_mult\"\n  by (metis mult.commute set_times_rearrange3)\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  by (meson dual_order.trans set_times_mono set_times_mono3)\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  by (auto simp: set_plus_def elt_set_times_def; metis distrib_left)\n\nlemma set_times_plus_distrib3: \"(a +o C) * D \\<subseteq> a *o D + C * D\"\n  for a :: \"'a::semiring\"\n  using distrib_right \n  by (fastforce simp add: elt_set_plus_def elt_set_times_def set_times_def set_plus_def)\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": "seL4", "repo": "isabelle", "sha": "e1ab32a3bb41728cd19541063283e37919978a4c", "save_path": "github-repos/isabelle/seL4-isabelle", "path": "github-repos/isabelle/seL4-isabelle/isabelle-e1ab32a3bb41728cd19541063283e37919978a4c/src/HOL/Library/Set_Algebras.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473680407889, "lm_q2_score": 0.8438950966654774, "lm_q1q2_score": 0.7361696664786563}}
{"text": "(*  Title:      HOL/Number_Theory/Pocklington.thy\n    Author:     Amine Chaieb\n*)\n\nsection {* Pocklington's Theorem for Primes *}\n\ntheory Pocklington\nimports Residues\nbegin\n\nsubsection{*Lemmas about previously defined terms*}\n\nlemma prime: \n  \"prime p \\<longleftrightarrow> p \\<noteq> 0 \\<and> p\\<noteq>1 \\<and> (\\<forall>m. 0 < m \\<and> m < p \\<longrightarrow> coprime p m)\"\n  (is \"?lhs \\<longleftrightarrow> ?rhs\")\nproof-\n  {assume \"p=0 \\<or> p=1\" hence ?thesis\n    by (metis one_not_prime_nat zero_not_prime_nat)}\n  moreover\n  {assume p0: \"p\\<noteq>0\" \"p\\<noteq>1\"\n    {assume H: \"?lhs\"\n      {fix m assume m: \"m > 0\" \"m < p\"\n        {assume \"m=1\" hence \"coprime p m\" by simp}\n        moreover\n        {assume \"p dvd m\" hence \"p \\<le> m\" using dvd_imp_le m by blast with m(2)\n          have \"coprime p m\" by simp}\n        ultimately have \"coprime p m\" \n          by (metis H prime_imp_coprime_nat)}\n      hence ?rhs using p0 by auto}\n    moreover\n    { assume H: \"\\<forall>m. 0 < m \\<and> m < p \\<longrightarrow> coprime p m\"\n      obtain q where q: \"prime q\" \"q dvd p\"\n        by (metis p0(2) prime_factor_nat) \n      have q0: \"q > 0\"\n        by (metis prime_gt_0_nat q(1))\n      from dvd_imp_le[OF q(2)] p0 have qp: \"q \\<le> p\" by arith\n      {assume \"q = p\" hence ?lhs using q(1) by blast}\n      moreover\n      {assume \"q\\<noteq>p\" with qp have qplt: \"q < p\" by arith\n        from H qplt q0 have \"coprime p q\" by arith\n       hence ?lhs using q\n         by (metis gcd_semilattice_nat.inf_absorb2 one_not_prime_nat)}\n      ultimately have ?lhs by blast}\n    ultimately have ?thesis by blast}\n  ultimately show ?thesis  by (cases\"p=0 \\<or> p=1\", auto)\nqed\n\nlemma finite_number_segment: \"card { m. 0 < m \\<and> m < n } = n - 1\"\nproof-\n  have \"{ m. 0 < m \\<and> m < n } = {1..<n}\" by auto\n  thus ?thesis by simp\nqed\n\n\nsubsection{*Some basic theorems about solving congruences*}\n\nlemma cong_solve: \n  fixes n::nat assumes an: \"coprime a n\" shows \"\\<exists>x. [a * x = b] (mod n)\"\nproof-\n  {assume \"a=0\" hence ?thesis using an by (simp add: cong_nat_def)}\n  moreover\n  {assume az: \"a\\<noteq>0\"\n  from bezout_add_strong_nat[OF az, of n]\n  obtain d x y where dxy: \"d dvd a\" \"d dvd n\" \"a*x = n*y + d\" by blast\n  from dxy(1,2) have d1: \"d = 1\"\n    by (metis assms coprime_nat) \n  hence \"a*x*b = (n*y + 1)*b\" using dxy(3) by simp\n  hence \"a*(x*b) = n*(y*b) + b\" \n    by (auto simp add: algebra_simps)\n  hence \"a*(x*b) mod n = (n*(y*b) + b) mod n\" by simp\n  hence \"a*(x*b) mod n = b mod n\" by (simp add: mod_add_left_eq)\n  hence \"[a*(x*b) = b] (mod n)\" unfolding cong_nat_def .\n  hence ?thesis by blast}\nultimately  show ?thesis by blast\nqed\n\nlemma cong_solve_unique: \n  fixes n::nat assumes an: \"coprime a n\" and nz: \"n \\<noteq> 0\"\n  shows \"\\<exists>!x. x < n \\<and> [a * x = b] (mod n)\"\nproof-\n  let ?P = \"\\<lambda>x. x < n \\<and> [a * x = b] (mod n)\"\n  from cong_solve[OF an] obtain x where x: \"[a*x = b] (mod n)\" by blast\n  let ?x = \"x mod n\"\n  from x have th: \"[a * ?x = b] (mod n)\"\n    by (simp add: cong_nat_def mod_mult_right_eq[of a x n])\n  from mod_less_divisor[ of n x] nz th have Px: \"?P ?x\" by simp\n  {fix y assume Py: \"y < n\" \"[a * y = b] (mod n)\"\n    from Py(2) th have \"[a * y = a*?x] (mod n)\" by (simp add: cong_nat_def)\n    hence \"[y = ?x] (mod n)\"\n      by (metis an cong_mult_lcancel_nat) \n    with mod_less[OF Py(1)] mod_less_divisor[ of n x] nz\n    have \"y = ?x\" by (simp add: cong_nat_def)}\n  with Px show ?thesis by blast\nqed\n\nlemma cong_solve_unique_nontrivial:\n  assumes p: \"prime p\" and pa: \"coprime p a\" and x0: \"0 < x\" and xp: \"x < p\"\n  shows \"\\<exists>!y. 0 < y \\<and> y < p \\<and> [x * y = a] (mod p)\"\nproof-\n  from pa have ap: \"coprime a p\"\n    by (metis gcd_nat.commute) \n  have px:\"coprime x p\"\n    by (metis gcd_nat.commute p prime x0 xp)\n  obtain y where y: \"y < p\" \"[x * y = a] (mod p)\" \"\\<forall>z. z < p \\<and> [x * z = a] (mod p) \\<longrightarrow> z = y\"\n    by (metis cong_solve_unique neq0_conv p prime_gt_0_nat px)\n  {assume y0: \"y = 0\"\n    with y(2) have th: \"p dvd a\"\n      by (metis cong_dvd_eq_nat gcd_lcm_complete_lattice_nat.top_greatest mult_0_right) \n    have False\n      by (metis gcd_nat.absorb1 one_not_prime_nat p pa th)}\n  with y show ?thesis unfolding Ex1_def using neq0_conv by blast\nqed\n\nlemma cong_unique_inverse_prime:\n  assumes p: \"prime p\" and x0: \"0 < x\" and xp: \"x < p\"\n  shows \"\\<exists>!y. 0 < y \\<and> y < p \\<and> [x * y = 1] (mod p)\"\nby (metis cong_solve_unique_nontrivial gcd_lcm_complete_lattice_nat.inf_bot_left gcd_nat.commute assms) \n\nlemma chinese_remainder_coprime_unique:\n  fixes a::nat \n  assumes ab: \"coprime a b\" and az: \"a \\<noteq> 0\" and bz: \"b \\<noteq> 0\"\n  and ma: \"coprime m a\" and nb: \"coprime n b\"\n  shows \"\\<exists>!x. coprime x (a * b) \\<and> x < a * b \\<and> [x = m] (mod a) \\<and> [x = n] (mod b)\"\nproof-\n  let ?P = \"\\<lambda>x. x < a * b \\<and> [x = m] (mod a) \\<and> [x = n] (mod b)\"\n  from binary_chinese_remainder_unique_nat[OF ab az bz]\n  obtain x where x: \"x < a * b\" \"[x = m] (mod a)\" \"[x = n] (mod b)\"\n    \"\\<forall>y. ?P y \\<longrightarrow> y = x\" by blast\n  from ma nb x\n  have \"coprime x a\" \"coprime x b\"\n    by (metis cong_gcd_eq_nat)+\n  then have \"coprime x (a*b)\"\n    by (metis coprime_mul_eq_nat)\n  with x show ?thesis by blast\nqed\n\n\nsubsection{*Lucas's theorem*}\n\nlemma phi_limit_strong: \"phi(n) \\<le> n - 1\"\nproof -\n  have \"phi n = card {x. 0 < x \\<and> x < int n \\<and> coprime x (int n)}\"\n    by (simp add: phi_def)\n  also have \"... \\<le> card {0 <..< int n}\"\n    by (rule card_mono) auto\n  also have \"... = card {0 <..< n}\"\n    by (simp add: transfer_nat_int_set_functions)\n  also have \"... \\<le> n - 1\"\n    by (metis card_greaterThanLessThan le_refl One_nat_def)\n  finally show ?thesis .\nqed\n\nlemma phi_lowerbound_1: assumes n: \"n \\<ge> 2\"\n  shows \"phi n \\<ge> 1\"\nproof -\n  have \"1 \\<le> card {0::int <.. 1}\"\n    by auto\n  also have \"... \\<le> card {x. 0 < x \\<and> x < n \\<and> coprime x n}\"\n    apply (rule card_mono) using assms\n    by auto (metis dual_order.antisym gcd_1_int gcd_int.commute int_one_le_iff_zero_less)\n  also have \"... = phi n\"\n    by (simp add: phi_def)\n  finally show ?thesis .\nqed\n\nlemma phi_lowerbound_1_nat: assumes n: \"n \\<ge> 2\"\n  shows \"phi(int n) \\<ge> 1\"\nby (metis n nat_le_iff nat_numeral phi_lowerbound_1)\n\nlemma euler_theorem_nat:\n  fixes m::nat \n  assumes \"coprime a m\"\n  shows \"[a ^ phi m = 1] (mod m)\"\nby (metis assms le0 euler_theorem [transferred])\n\nlemma lucas_coprime_lemma:\n  fixes n::nat \n  assumes m: \"m\\<noteq>0\" and am: \"[a^m = 1] (mod n)\"\n  shows \"coprime a n\"\nproof-\n  {assume \"n=1\" hence ?thesis by simp}\n  moreover\n  {assume \"n = 0\" hence ?thesis using am m \n     by (metis am cong_0_nat gcd_nat.right_neutral power_eq_one_eq_nat)}\n  moreover\n  {assume n: \"n\\<noteq>0\" \"n\\<noteq>1\"\n    from m obtain m' where m': \"m = Suc m'\" by (cases m, blast+)\n    {fix d\n      assume d: \"d dvd a\" \"d dvd n\"\n      from n have n1: \"1 < n\" by arith\n      from am mod_less[OF n1] have am1: \"a^m mod n = 1\" unfolding cong_nat_def by simp\n      from dvd_mult2[OF d(1), of \"a^m'\"] have dam:\"d dvd a^m\" by (simp add: m')\n      from dvd_mod_iff[OF d(2), of \"a^m\"] dam am1\n      have \"d = 1\" by simp }\n    hence ?thesis by auto\n  }\n  ultimately show ?thesis by blast\nqed\n\nlemma lucas_weak:\n  fixes n::nat \n  assumes n: \"n \\<ge> 2\" and an:\"[a^(n - 1) = 1] (mod n)\"\n  and nm: \"\\<forall>m. 0 <m \\<and> m < n - 1 \\<longrightarrow> \\<not> [a^m = 1] (mod n)\"\n  shows \"prime n\"\nproof-\n  from n have n1: \"n \\<noteq> 1\" \"n\\<noteq>0\" \"n - 1 \\<noteq> 0\" \"n - 1 > 0\" \"n - 1 < n\" by arith+\n  from lucas_coprime_lemma[OF n1(3) an] have can: \"coprime a n\" .\n  from euler_theorem_nat[OF can] have afn: \"[a ^ phi n = 1] (mod n)\"\n    by auto \n  {assume \"phi n \\<noteq> n - 1\"\n    with phi_limit_strong phi_lowerbound_1_nat [OF n]\n    have c:\"phi n > 0 \\<and> phi n < n - 1\"\n      by (metis gr0I leD less_linear not_one_le_zero)\n    from nm[rule_format, OF c] afn have False ..}\n  hence \"phi n = n - 1\" by blast\n  with prime_phi phi_prime n1(1,2) show ?thesis\n    by auto\nqed\n\nlemma nat_exists_least_iff: \"(\\<exists>(n::nat). P n) \\<longleftrightarrow> (\\<exists>n. P n \\<and> (\\<forall>m < n. \\<not> P m))\"\n  by (metis ex_least_nat_le not_less0)\n\nlemma nat_exists_least_iff': \"(\\<exists>(n::nat). P n) \\<longleftrightarrow> (P (Least P) \\<and> (\\<forall>m < (Least P). \\<not> P m))\"\n  (is \"?lhs \\<longleftrightarrow> ?rhs\")\nproof-\n  {assume ?rhs hence ?lhs by blast}\n  moreover\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] have ?rhs by blast}\n  ultimately show ?thesis by blast\nqed\n\ntheorem lucas:\n  assumes n2: \"n \\<ge> 2\" and an1: \"[a^(n - 1) = 1] (mod n)\"\n  and pn: \"\\<forall>p. prime p \\<and> p dvd n - 1 \\<longrightarrow> [a^((n - 1) div p) \\<noteq> 1] (mod n)\"\n  shows \"prime n\"\nproof-\n  from n2 have n01: \"n\\<noteq>0\" \"n\\<noteq>1\" \"n - 1 \\<noteq> 0\" by arith+\n  from mod_less_divisor[of n 1] n01 have onen: \"1 mod n = 1\" by simp\n  from lucas_coprime_lemma[OF n01(3) an1] cong_imp_coprime_nat an1\n  have an: \"coprime a n\" \"coprime (a^(n - 1)) n\"\n    by (auto simp add: coprime_exp_nat gcd_nat.commute)\n  {assume H0: \"\\<exists>m. 0 < m \\<and> m < n - 1 \\<and> [a ^ m = 1] (mod n)\" (is \"EX m. ?P m\")\n    from H0[unfolded nat_exists_least_iff[of ?P]] obtain m where\n      m: \"0 < m\" \"m < n - 1\" \"[a ^ m = 1] (mod n)\" \"\\<forall>k <m. \\<not>?P k\" by blast\n    {assume nm1: \"(n - 1) mod m > 0\"\n      from mod_less_divisor[OF m(1)] have th0:\"(n - 1) mod m < m\" by blast\n      let ?y = \"a^ ((n - 1) div m * m)\"\n      note mdeq = mod_div_equality[of \"(n - 1)\" m]\n      have yn: \"coprime ?y n\"\n        by (metis an(1) coprime_exp_nat gcd_nat.commute)\n      have \"?y mod n = (a^m)^((n - 1) div m) mod n\"\n        by (simp add: algebra_simps power_mult)\n      also have \"\\<dots> = (a^m mod n)^((n - 1) div m) mod n\"\n        using power_mod[of \"a^m\" n \"(n - 1) div m\"] by simp\n      also have \"\\<dots> = 1\" using m(3)[unfolded cong_nat_def onen] onen\n        by (metis power_one)\n      finally have th3: \"?y mod n = 1\"  .\n      have th2: \"[?y * a ^ ((n - 1) mod m) = ?y* 1] (mod n)\"\n        using an1[unfolded cong_nat_def onen] onen\n          mod_div_equality[of \"(n - 1)\" m, symmetric]\n        by (simp add:power_add[symmetric] cong_nat_def th3 del: One_nat_def)\n      have th1: \"[a ^ ((n - 1) mod m) = 1] (mod n)\"\n        by (metis cong_mult_rcancel_nat mult.commute th2 yn)\n      from m(4)[rule_format, OF th0] nm1\n        less_trans[OF mod_less_divisor[OF m(1), of \"n - 1\"] m(2)] th1\n      have False by blast }\n    hence \"(n - 1) mod m = 0\" by auto\n    then have mn: \"m dvd n - 1\" by presburger\n    then obtain r where r: \"n - 1 = m*r\" unfolding dvd_def by blast\n    from n01 r m(2) have r01: \"r\\<noteq>0\" \"r\\<noteq>1\" by - (rule ccontr, simp)+\n    obtain p where p: \"prime p\" \"p dvd r\"\n      by (metis prime_factor_nat r01(2))\n    hence th: \"prime p \\<and> p dvd n - 1\" unfolding r by (auto intro: dvd_mult)\n    have \"(a ^ ((n - 1) div p)) mod n = (a^(m*r div p)) mod n\" using r\n      by (simp add: power_mult)\n    also have \"\\<dots> = (a^(m*(r div p))) mod n\" \n      using div_mult1_eq[of m r p] p(2)[unfolded dvd_eq_mod_eq_0] \n      by simp\n    also have \"\\<dots> = ((a^m)^(r div p)) mod n\" by (simp add: power_mult)\n    also have \"\\<dots> = ((a^m mod n)^(r div p)) mod n\" using power_mod ..\n    also have \"\\<dots> = 1\" using m(3) onen by (simp add: cong_nat_def)\n    finally have \"[(a ^ ((n - 1) div p))= 1] (mod n)\"\n      using onen by (simp add: cong_nat_def)\n    with pn th have False by blast}\n  hence th: \"\\<forall>m. 0 < m \\<and> m < n - 1 \\<longrightarrow> \\<not> [a ^ m = 1] (mod n)\" by blast\n  from lucas_weak[OF n2 an1 th] show ?thesis .\nqed\n\n\nsubsection{*Definition of the order of a number mod n (0 in non-coprime case)*}\n\ndefinition \"ord n a = (if coprime n a then Least (\\<lambda>d. d > 0 \\<and> [a ^d = 1] (mod n)) else 0)\"\n\n(* This has the expected properties.                                         *)\n\nlemma coprime_ord:\n  fixes n::nat \n  assumes \"coprime n a\"\n  shows \"ord n a > 0 \\<and> [a ^(ord n a) = 1] (mod n) \\<and> (\\<forall>m. 0 < m \\<and> m < ord n a \\<longrightarrow> [a^ m \\<noteq> 1] (mod n))\"\nproof-\n  let ?P = \"\\<lambda>d. 0 < d \\<and> [a ^ d = 1] (mod n)\"\n  from bigger_prime[of a] obtain p where p: \"prime p\" \"a < p\" by blast\n  from assms have o: \"ord n a = Least ?P\" by (simp add: ord_def)\n  {assume \"n=0 \\<or> n=1\" with assms have \"\\<exists>m>0. ?P m\" \n      by auto}\n  moreover\n  {assume \"n\\<noteq>0 \\<and> n\\<noteq>1\" hence n2:\"n \\<ge> 2\" by arith\n    from assms have na': \"coprime a n\"\n      by (metis gcd_nat.commute)\n    from phi_lowerbound_1_nat[OF n2] euler_theorem_nat [OF na']\n    have ex: \"\\<exists>m>0. ?P m\" by - (rule exI[where x=\"phi n\"], auto) }\n  ultimately have ex: \"\\<exists>m>0. ?P m\" by blast\n  from nat_exists_least_iff'[of ?P] ex assms show ?thesis\n    unfolding o[symmetric] by auto\nqed\n\n(* With the special value 0 for non-coprime case, it's more convenient.      *)\nlemma ord_works:\n  fixes n::nat\n  shows \"[a ^ (ord n a) = 1] (mod n) \\<and> (\\<forall>m. 0 < m \\<and> m < ord n a \\<longrightarrow> ~[a^ m = 1] (mod n))\"\napply (cases \"coprime n a\")\nusing coprime_ord[of n a]\nby (auto simp add: ord_def cong_nat_def)\n\nlemma ord:\n  fixes n::nat\n  shows \"[a^(ord n a) = 1] (mod n)\" using ord_works by blast\n\nlemma ord_minimal:\n  fixes n::nat\n  shows \"0 < m \\<Longrightarrow> m < ord n a \\<Longrightarrow> ~[a^m = 1] (mod n)\"\n  using ord_works by blast\n\nlemma ord_eq_0:\n  fixes n::nat\n  shows \"ord n a = 0 \\<longleftrightarrow> ~coprime n a\"\nby (cases \"coprime n a\", simp add: coprime_ord, simp add: ord_def)\n\nlemma divides_rexp: \n  \"x dvd y \\<Longrightarrow> (x::nat) dvd (y^(Suc n))\" \n  by (simp add: dvd_mult2[of x y])\n\nlemma ord_divides:\n  fixes n::nat\n  shows \"[a ^ d = 1] (mod n) \\<longleftrightarrow> ord n a dvd d\" (is \"?lhs \\<longleftrightarrow> ?rhs\")\nproof\n  assume rh: ?rhs\n  then obtain k where \"d = ord n a * k\" unfolding dvd_def by blast\n  hence \"[a ^ d = (a ^ (ord n a) mod n)^k] (mod n)\"\n    by (simp add : cong_nat_def power_mult power_mod)\n  also have \"[(a ^ (ord n a) mod n)^k = 1] (mod n)\"\n    using ord[of a n, unfolded cong_nat_def]\n    by (simp add: cong_nat_def power_mod)\n  finally  show ?lhs .\nnext\n  assume lh: ?lhs\n  { assume H: \"\\<not> coprime n a\"\n    hence o: \"ord n a = 0\" by (simp add: ord_def)\n    {assume d: \"d=0\" with o H have ?rhs by (simp add: cong_nat_def)}\n    moreover\n    {assume d0: \"d\\<noteq>0\" then obtain d' where d': \"d = Suc d'\" by (cases d, auto)\n      from H\n      obtain p where p: \"p dvd n\" \"p dvd a\" \"p \\<noteq> 1\" by auto\n      from lh\n      obtain q1 q2 where q12:\"a ^ d + n * q1 = 1 + n * q2\"\n        by (metis H d0 gcd_nat.commute lucas_coprime_lemma) \n      hence \"a ^ d + n * q1 - n * q2 = 1\" by simp\n      with dvd_diff_nat [OF dvd_add [OF divides_rexp]]  dvd_mult2  d' p\n      have \"p dvd 1\"\n        by metis\n      with p(3) have False by simp\n      hence ?rhs ..}\n    ultimately have ?rhs by blast}\n  moreover\n  {assume H: \"coprime n a\"\n    let ?o = \"ord n a\"\n    let ?q = \"d div ord n a\"\n    let ?r = \"d mod ord n a\"\n    have eqo: \"[(a^?o)^?q = 1] (mod n)\"\n      by (metis cong_exp_nat ord power_one)\n    from H have onz: \"?o \\<noteq> 0\" by (simp add: ord_eq_0)\n    hence op: \"?o > 0\" by simp\n    from mod_div_equality[of d \"ord n a\"] lh\n    have \"[a^(?o*?q + ?r) = 1] (mod n)\" by (simp add: cong_nat_def mult.commute)\n    hence \"[(a^?o)^?q * (a^?r) = 1] (mod n)\"\n      by (simp add: cong_nat_def power_mult[symmetric] power_add[symmetric])\n    hence th: \"[a^?r = 1] (mod n)\"\n      using eqo mod_mult_left_eq[of \"(a^?o)^?q\" \"a^?r\" n]\n      apply (simp add: cong_nat_def del: One_nat_def)\n      by (simp add: mod_mult_left_eq[symmetric])\n    {assume r: \"?r = 0\" hence ?rhs by (simp add: dvd_eq_mod_eq_0)}\n    moreover\n    {assume r: \"?r \\<noteq> 0\"\n      with mod_less_divisor[OF op, of d] have r0o:\"?r >0 \\<and> ?r < ?o\" by simp\n      from conjunct2[OF ord_works[of a n], rule_format, OF r0o] th\n      have ?rhs by blast}\n    ultimately have ?rhs by blast}\n  ultimately  show ?rhs by blast\nqed\n\nlemma order_divides_phi: \n  fixes n::nat shows \"coprime n a \\<Longrightarrow> ord n a dvd phi n\"\n  by (metis ord_divides euler_theorem_nat gcd_nat.commute)\n\nlemma order_divides_expdiff:\n  fixes n::nat and a::nat assumes na: \"coprime n a\"\n  shows \"[a^d = a^e] (mod n) \\<longleftrightarrow> [d = e] (mod (ord n a))\"\nproof-\n  {fix n::nat and a::nat and d::nat and e::nat\n    assume na: \"coprime n a\" and ed: \"(e::nat) \\<le> d\"\n    hence \"\\<exists>c. d = e + c\" by presburger\n    then obtain c where c: \"d = e + c\" by presburger\n    from na have an: \"coprime a n\"\n      by (metis gcd_nat.commute)\n    have aen: \"coprime (a^e) n\"\n      by (metis coprime_exp_nat gcd_nat.commute na)      \n    have acn: \"coprime (a^c) n\"\n      by (metis coprime_exp_nat gcd_nat.commute na) \n    have \"[a^d = a^e] (mod n) \\<longleftrightarrow> [a^(e + c) = a^(e + 0)] (mod n)\"\n      using c by simp\n    also have \"\\<dots> \\<longleftrightarrow> [a^e* a^c = a^e *a^0] (mod n)\" by (simp add: power_add)\n    also have  \"\\<dots> \\<longleftrightarrow> [a ^ c = 1] (mod n)\"\n      using cong_mult_lcancel_nat [OF aen, of \"a^c\" \"a^0\"] by simp\n    also  have \"\\<dots> \\<longleftrightarrow> ord n a dvd c\" by (simp only: ord_divides)\n    also have \"\\<dots> \\<longleftrightarrow> [e + c = e + 0] (mod ord n a)\"\n      using cong_add_lcancel_nat \n      by (metis cong_dvd_eq_nat dvd_0_right cong_dvd_modulus_nat cong_mult_self_nat nat_mult_1)\n    finally have \"[a^d = a^e] (mod n) \\<longleftrightarrow> [d = e] (mod (ord n a))\"\n      using c by simp }\n  note th = this\n  have \"e \\<le> d \\<or> d \\<le> e\" by arith\n  moreover\n  {assume ed: \"e \\<le> d\" from th[OF na ed] have ?thesis .}\n  moreover\n  {assume de: \"d \\<le> e\"\n    from th[OF na de] have ?thesis\n    by (metis cong_sym_nat)}\n  ultimately show ?thesis by blast\nqed\n\nsubsection{*Another trivial primality characterization*}\n\nlemma prime_prime_factor:\n  \"prime n \\<longleftrightarrow> n \\<noteq> 1 \\<and> (\\<forall>p. prime p \\<and> p dvd n \\<longrightarrow> p = n)\" \n  (is \"?lhs \\<longleftrightarrow> ?rhs\")\nproof (cases \"n=0 \\<or> n=1\")\n  case True\n  then show ?thesis\n     by (metis bigger_prime dvd_0_right one_not_prime_nat zero_not_prime_nat)\nnext\n  case False\n  show ?thesis\n  proof\n    assume \"prime n\"\n    then show ?rhs\n      by (metis one_not_prime_nat prime_nat_def)\n  next\n    assume ?rhs\n    with False show \"prime n\"\n      by (auto simp: prime_def) (metis One_nat_def prime_factor_nat prime_nat_def)\n  qed\nqed\n\nlemma prime_divisor_sqrt:\n  \"prime n \\<longleftrightarrow> n \\<noteq> 1 \\<and> (\\<forall>d. d dvd n \\<and> d\\<^sup>2 \\<le> n \\<longrightarrow> d = 1)\"\nproof -\n  {assume \"n=0 \\<or> n=1\" hence ?thesis\n    by (metis dvd.order_refl le_refl one_not_prime_nat power_zero_numeral zero_not_prime_nat)}\n  moreover\n  {assume n: \"n\\<noteq>0\" \"n\\<noteq>1\"\n    hence np: \"n > 1\" by arith\n    {fix d assume d: \"d dvd n\" \"d\\<^sup>2 \\<le> n\" and H: \"\\<forall>m. m dvd n \\<longrightarrow> m=1 \\<or> m=n\"\n      from H d have d1n: \"d = 1 \\<or> d=n\" by blast\n      {assume dn: \"d=n\"\n        have \"n\\<^sup>2 > n*1\" using n by (simp add: power2_eq_square)\n        with dn d(2) have \"d=1\" by simp}\n      with d1n have \"d = 1\" by blast  }\n    moreover\n    {fix d assume d: \"d dvd n\" and H: \"\\<forall>d'. d' dvd n \\<and> d'\\<^sup>2 \\<le> n \\<longrightarrow> d' = 1\"\n      from d n have \"d \\<noteq> 0\"\n        by (metis dvd_0_left_iff)\n      hence dp: \"d > 0\" by simp\n      from d[unfolded dvd_def] obtain e where e: \"n= d*e\" by blast\n      from n dp e have ep:\"e > 0\" by simp\n      have \"d\\<^sup>2 \\<le> n \\<or> e\\<^sup>2 \\<le> n\" using dp ep\n        by (auto simp add: e power2_eq_square mult_le_cancel_left)\n      moreover\n      {assume h: \"d\\<^sup>2 \\<le> n\"\n        from H[rule_format, of d] h d have \"d = 1\" by blast}\n      moreover\n      {assume h: \"e\\<^sup>2 \\<le> n\"\n        from e have \"e dvd n\" unfolding dvd_def by (simp add: mult.commute)\n        with H[rule_format, of e] h have \"e=1\" by simp\n        with e have \"d = n\" by simp}\n      ultimately have \"d=1 \\<or> d=n\"  by blast}\n    ultimately have ?thesis unfolding prime_def using np n(2) by blast}\n  ultimately show ?thesis by auto\nqed\n\nlemma prime_prime_factor_sqrt:\n  \"prime n \\<longleftrightarrow> n \\<noteq> 0 \\<and> n \\<noteq> 1 \\<and> \\<not> (\\<exists>p. prime p \\<and> p dvd n \\<and> p\\<^sup>2 \\<le> n)\"\n  (is \"?lhs \\<longleftrightarrow>?rhs\")\nproof-\n  {assume \"n=0 \\<or> n=1\" \n   hence ?thesis\n     by (metis one_not_prime_nat zero_not_prime_nat)}\n  moreover\n  {assume n: \"n\\<noteq>0\" \"n\\<noteq>1\"\n    {assume H: ?lhs\n      from H[unfolded prime_divisor_sqrt] n\n      have ?rhs\n        by (metis prime_prime_factor) }\n    moreover\n    {assume H: ?rhs\n      {fix d assume d: \"d dvd n\" \"d\\<^sup>2 \\<le> n\" \"d\\<noteq>1\"\n        then obtain p where p: \"prime p\" \"p dvd d\"\n          by (metis prime_factor_nat) \n        from d(1) n have dp: \"d > 0\"\n          by (metis dvd_0_left neq0_conv) \n        from mult_mono[OF dvd_imp_le[OF p(2) dp] dvd_imp_le[OF p(2) dp]] d(2)\n        have \"p\\<^sup>2 \\<le> n\" unfolding power2_eq_square by arith\n        with H n p(1) dvd_trans[OF p(2) d(1)] have False  by blast}\n      with n prime_divisor_sqrt  have ?lhs by auto}\n    ultimately have ?thesis by blast }\n  ultimately show ?thesis by (cases \"n=0 \\<or> n=1\", auto)\nqed\n\n\nsubsection{*Pocklington theorem*}\n\nlemma pocklington_lemma:\n  assumes n: \"n \\<ge> 2\" and nqr: \"n - 1 = q*r\" and an: \"[a^ (n - 1) = 1] (mod n)\"\n  and aq:\"\\<forall>p. prime p \\<and> p dvd q \\<longrightarrow> coprime (a^ ((n - 1) div p) - 1) n\"\n  and pp: \"prime p\" and pn: \"p dvd n\"\n  shows \"[p = 1] (mod q)\"\nproof -\n  have p01: \"p \\<noteq> 0\" \"p \\<noteq> 1\" using pp one_not_prime_nat zero_not_prime_nat by auto\n  obtain k where k: \"a ^ (q * r) - 1 = n*k\"\n    by (metis an cong_to_1_nat dvd_def nqr)\n  from pn[unfolded dvd_def] obtain l where l: \"n = p*l\" by blast\n  {assume a0: \"a = 0\"\n    hence \"a^ (n - 1) = 0\" using n by (simp add: power_0_left)\n    with n an mod_less[of 1 n]  have False by (simp add: power_0_left cong_nat_def)}\n  hence a0: \"a\\<noteq>0\" ..\n  from n nqr have aqr0: \"a ^ (q * r) \\<noteq> 0\" using a0 by simp\n  hence \"(a ^ (q * r) - 1) + 1  = a ^ (q * r)\" by simp\n  with k l have \"a ^ (q * r) = p*l*k + 1\" by simp\n  hence \"a ^ (r * q) + p * 0 = 1 + p * (l*k)\" by (simp add: ac_simps)\n  hence odq: \"ord p (a^r) dvd q\"\n    unfolding ord_divides[symmetric] power_mult[symmetric]\n    by (metis an cong_dvd_modulus_nat mult.commute nqr pn) \n  from odq[unfolded dvd_def] obtain d where d: \"q = ord p (a^r) * d\" by blast\n  {assume d1: \"d \\<noteq> 1\"\n    obtain P where P: \"prime P\" \"P dvd d\"\n      by (metis d1 prime_factor_nat) \n    from d dvd_mult[OF P(2), of \"ord p (a^r)\"] have Pq: \"P dvd q\" by simp\n    from aq P(1) Pq have caP:\"coprime (a^ ((n - 1) div P) - 1) n\" by blast\n    from Pq obtain s where s: \"q = P*s\" unfolding dvd_def by blast\n    have P0: \"P \\<noteq> 0\" using P(1)\n      by (metis zero_not_prime_nat) \n    from P(2) obtain t where t: \"d = P*t\" unfolding dvd_def by blast\n    from d s t P0  have s': \"ord p (a^r) * t = s\"\n      by (metis mult.commute mult_cancel1 mult.assoc) \n    have \"ord p (a^r) * t*r = r * ord p (a^r) * t\"\n      by (metis mult.assoc mult.commute)\n    hence exps: \"a^(ord p (a^r) * t*r) = ((a ^ r) ^ ord p (a^r)) ^ t\"\n      by (simp only: power_mult)\n    then have th: \"[((a ^ r) ^ ord p (a^r)) ^ t= 1] (mod p)\"\n      by (metis cong_exp_nat ord power_one)\n    have pd0: \"p dvd a^(ord p (a^r) * t*r) - 1\"\n      by (metis cong_to_1_nat exps th)\n    from nqr s s' have \"(n - 1) div P = ord p (a^r) * t*r\" using P0 by simp\n    with caP have \"coprime (a^(ord p (a^r) * t*r) - 1) n\" by simp\n    with p01 pn pd0 coprime_common_divisor_nat have False \n      by auto}\n  hence d1: \"d = 1\" by blast\n  hence o: \"ord p (a^r) = q\" using d by simp\n  from pp phi_prime[of p] have phip: \"phi p = p - 1\" by simp\n  {fix d assume d: \"d dvd p\" \"d dvd a\" \"d \\<noteq> 1\"\n    from pp[unfolded prime_def] d have dp: \"d = p\" by blast\n    from n have \"n \\<noteq> 0\" by simp\n    then have False using d\n      by (metis coprime_minus_one_nat dp lucas_coprime_lemma an coprime_nat \n           gcd_lcm_complete_lattice_nat.top_greatest pn)} \n  hence cpa: \"coprime p a\" by auto\n  have arp: \"coprime (a^r) p\"\n    by (metis coprime_exp_nat cpa gcd_nat.commute) \n  from euler_theorem_nat[OF arp, simplified ord_divides] o phip\n  have \"q dvd (p - 1)\" by simp\n  then obtain d where d:\"p - 1 = q * d\" \n    unfolding dvd_def by blast\n  have p0:\"p \\<noteq> 0\"\n    by (metis p01(1)) \n  from p0 d have \"p + q * 0 = 1 + q * d\" by simp\n  then show ?thesis\n    by (metis cong_iff_lin_nat mult.commute)\nqed\n\ntheorem pocklington:\n  assumes n: \"n \\<ge> 2\" and nqr: \"n - 1 = q*r\" and sqr: \"n \\<le> q\\<^sup>2\"\n  and an: \"[a^ (n - 1) = 1] (mod n)\"\n  and aq: \"\\<forall>p. prime p \\<and> p dvd q \\<longrightarrow> coprime (a^ ((n - 1) div p) - 1) n\"\n  shows \"prime n\"\nunfolding prime_prime_factor_sqrt[of n]\nproof-\n  let ?ths = \"n \\<noteq> 0 \\<and> n \\<noteq> 1 \\<and> \\<not> (\\<exists>p. prime p \\<and> p dvd n \\<and> p\\<^sup>2 \\<le> n)\"\n  from n have n01: \"n\\<noteq>0\" \"n\\<noteq>1\" by arith+\n  {fix p assume p: \"prime p\" \"p dvd n\" \"p\\<^sup>2 \\<le> n\"\n    from p(3) sqr have \"p^(Suc 1) \\<le> q^(Suc 1)\" by (simp add: power2_eq_square)\n    hence pq: \"p \\<le> q\"\n      by (metis le0 power_le_imp_le_base) \n    from pocklington_lemma[OF n nqr an aq p(1,2)] \n    have th: \"q dvd p - 1\"\n      by (metis cong_to_1_nat) \n    have \"p - 1 \\<noteq> 0\" using prime_ge_2_nat [OF p(1)] by arith\n    with pq p have False\n      by (metis Suc_diff_1 gcd_le2_nat gcd_semilattice_nat.inf_absorb1 not_less_eq_eq\n            prime_gt_0_nat th) }\n  with n01 show ?ths by blast\nqed\n\n(* Variant for application, to separate the exponentiation.                  *)\nlemma pocklington_alt:\n  assumes n: \"n \\<ge> 2\" and nqr: \"n - 1 = q*r\" and sqr: \"n \\<le> q\\<^sup>2\"\n  and an: \"[a^ (n - 1) = 1] (mod n)\"\n  and aq:\"\\<forall>p. prime p \\<and> p dvd q \\<longrightarrow> (\\<exists>b. [a^((n - 1) div p) = b] (mod n) \\<and> coprime (b - 1) n)\"\n  shows \"prime n\"\nproof-\n  {fix p assume p: \"prime p\" \"p dvd q\"\n    from aq[rule_format] p obtain b where\n      b: \"[a^((n - 1) div p) = b] (mod n)\" \"coprime (b - 1) n\" by blast\n    {assume a0: \"a=0\"\n      from n an have \"[0 = 1] (mod n)\" unfolding a0 power_0_left by auto\n      hence False using n by (simp add: cong_nat_def dvd_eq_mod_eq_0[symmetric])}\n    hence a0: \"a\\<noteq> 0\" ..\n    hence a1: \"a \\<ge> 1\" by arith\n    from one_le_power[OF a1] have ath: \"1 \\<le> a ^ ((n - 1) div p)\" .\n    {assume b0: \"b = 0\"\n      from p(2) nqr have \"(n - 1) mod p = 0\"\n        by (metis mod_0 mod_mod_cancel mod_mult_self1_is_0)\n      with mod_div_equality[of \"n - 1\" p]\n      have \"(n - 1) div p * p= n - 1\" by auto\n      hence eq: \"(a^((n - 1) div p))^p = a^(n - 1)\"\n        by (simp only: power_mult[symmetric])\n      have \"p - 1 \\<noteq> 0\" using prime_ge_2_nat [OF p(1)] by arith\n      then have pS: \"Suc (p - 1) = p\" by arith\n      from b have d: \"n dvd a^((n - 1) div p)\" unfolding b0\n        by (metis b0 diff_0_eq_0 gcd_dvd2_nat gcd_lcm_complete_lattice_nat.inf_bot_left \n                   gcd_lcm_complete_lattice_nat.inf_top_left) \n      from divides_rexp[OF d, of \"p - 1\"] pS eq cong_dvd_eq_nat [OF an] n\n      have False\n        by simp}\n    then have b0: \"b \\<noteq> 0\" ..\n    hence b1: \"b \\<ge> 1\" by arith \n    from cong_imp_coprime_nat[OF Cong.cong_diff_nat[OF cong_sym_nat [OF b(1)] cong_refl_nat[of 1] b1]] \n         ath b1 b nqr\n    have \"coprime (a ^ ((n - 1) div p) - 1) n\"\n      by simp}\n  hence th: \"\\<forall>p. prime p \\<and> p dvd q \\<longrightarrow> coprime (a ^ ((n - 1) div p) - 1) n \"\n    by blast\n  from pocklington[OF n nqr sqr an th] show ?thesis .\nqed\n\n\nsubsection{*Prime factorizations*}\n\n(* FIXME some overlap with material in UniqueFactorization, class unique_factorization *)\n\ndefinition \"primefact ps n = (foldr op * ps  1 = n \\<and> (\\<forall>p\\<in> set ps. prime p))\"\n\nlemma primefact: assumes n: \"n \\<noteq> 0\"\n  shows \"\\<exists>ps. primefact ps n\"\nusing n\nproof(induct n rule: nat_less_induct)\n  fix n assume H: \"\\<forall>m<n. m \\<noteq> 0 \\<longrightarrow> (\\<exists>ps. primefact ps m)\" and n: \"n\\<noteq>0\"\n  let ?ths = \"\\<exists>ps. primefact ps n\"\n  {assume \"n = 1\"\n    hence \"primefact [] n\" by (simp add: primefact_def)\n    hence ?ths by blast }\n  moreover\n  {assume n1: \"n \\<noteq> 1\"\n    with n have n2: \"n \\<ge> 2\" by arith\n    obtain p where p: \"prime p\" \"p dvd n\"\n      by (metis n1 prime_factor_nat) \n    from p(2) obtain m where m: \"n = p*m\" unfolding dvd_def by blast\n    from n m have m0: \"m > 0\" \"m\\<noteq>0\" by auto\n    have \"1 < p\"\n      by (metis p(1) prime_nat_def)\n    with m0 m have mn: \"m < n\" by auto\n    from H[rule_format, OF mn m0(2)] obtain ps where ps: \"primefact ps m\" ..\n    from ps m p(1) have \"primefact (p#ps) n\" by (simp add: primefact_def)\n    hence ?ths by blast}\n  ultimately show ?ths by blast\nqed\n\nlemma primefact_contains:\n  assumes pf: \"primefact ps n\" and p: \"prime p\" and pn: \"p dvd n\"\n  shows \"p \\<in> set ps\"\n  using pf p pn\nproof(induct ps arbitrary: p n)\n  case Nil thus ?case by (auto simp add: primefact_def)\nnext\n  case (Cons q qs p n)\n  from Cons.prems[unfolded primefact_def]\n  have q: \"prime q\" \"q * foldr op * qs 1 = n\" \"\\<forall>p \\<in>set qs. prime p\"  and p: \"prime p\" \"p dvd q * foldr op * qs 1\" by simp_all\n  {assume \"p dvd q\"\n    with p(1) q(1) have \"p = q\" unfolding prime_def by auto\n    hence ?case by simp}\n  moreover\n  { assume h: \"p dvd foldr op * qs 1\"\n    from q(3) have pqs: \"primefact qs (foldr op * qs 1)\"\n      by (simp add: primefact_def)\n    from Cons.hyps[OF pqs p(1) h] have ?case by simp}\n  ultimately show ?case\n    by (metis p prime_dvd_mult_eq_nat) \nqed\n\nlemma primefact_variant: \"primefact ps n \\<longleftrightarrow> foldr op * ps 1 = n \\<and> list_all prime ps\"\n  by (auto simp add: primefact_def list_all_iff)\n\n(* Variant of Lucas theorem.                                                 *)\n\nlemma lucas_primefact:\n  assumes n: \"n \\<ge> 2\" and an: \"[a^(n - 1) = 1] (mod n)\"\n  and psn: \"foldr op * ps 1 = n - 1\"\n  and psp: \"list_all (\\<lambda>p. prime p \\<and> \\<not> [a^((n - 1) div p) = 1] (mod n)) ps\"\n  shows \"prime n\"\nproof-\n  {fix p assume p: \"prime p\" \"p dvd n - 1\" \"[a ^ ((n - 1) div p) = 1] (mod n)\"\n    from psn psp have psn1: \"primefact ps (n - 1)\"\n      by (auto simp add: list_all_iff primefact_variant)\n    from p(3) primefact_contains[OF psn1 p(1,2)] psp\n    have False by (induct ps, auto)}\n  with lucas[OF n an] show ?thesis by blast\nqed\n\n(* Variant of Pocklington theorem.                                           *)\n\nlemma pocklington_primefact:\n  assumes n: \"n \\<ge> 2\" and qrn: \"q*r = n - 1\" and nq2: \"n \\<le> q\\<^sup>2\"\n  and arnb: \"(a^r) mod n = b\" and psq: \"foldr op * ps 1 = q\"\n  and bqn: \"(b^q) mod n = 1\"\n  and psp: \"list_all (\\<lambda>p. prime p \\<and> coprime ((b^(q div p)) mod n - 1) n) ps\"\n  shows \"prime n\"\nproof-\n  from bqn psp qrn\n  have bqn: \"a ^ (n - 1) mod n = 1\"\n    and psp: \"list_all (\\<lambda>p. prime p \\<and> coprime (a^(r *(q div p)) mod n - 1) n) ps\"  \n    unfolding arnb[symmetric] power_mod \n    by (simp_all add: power_mult[symmetric] algebra_simps)\n  from n  have n0: \"n > 0\" by arith\n  from mod_div_equality[of \"a^(n - 1)\" n]\n    mod_less_divisor[OF n0, of \"a^(n - 1)\"]\n  have an1: \"[a ^ (n - 1) = 1] (mod n)\"\n    by (metis bqn cong_nat_def mod_mod_trivial)\n  {fix p assume p: \"prime p\" \"p dvd q\"\n    from psp psq have pfpsq: \"primefact ps q\"\n      by (auto simp add: primefact_variant list_all_iff)\n    from psp primefact_contains[OF pfpsq p]\n    have p': \"coprime (a ^ (r * (q div p)) mod n - 1) n\"\n      by (simp add: list_all_iff)\n    from p prime_def have p01: \"p \\<noteq> 0\" \"p \\<noteq> 1\" \"p =Suc(p - 1)\" \n      by auto\n    from div_mult1_eq[of r q p] p(2)\n    have eq1: \"r* (q div p) = (n - 1) div p\"\n      unfolding qrn[symmetric] dvd_eq_mod_eq_0 by (simp add: mult.commute)\n    have ath: \"\\<And>a (b::nat). a <= b \\<Longrightarrow> a \\<noteq> 0 ==> 1 <= a \\<and> 1 <= b\" by arith\n    {assume \"a ^ ((n - 1) div p) mod n = 0\"\n      then obtain s where s: \"a ^ ((n - 1) div p) = n*s\"\n        unfolding mod_eq_0_iff by blast\n      hence eq0: \"(a^((n - 1) div p))^p = (n*s)^p\" by simp\n      from qrn[symmetric] have qn1: \"q dvd n - 1\" unfolding dvd_def by auto\n      from dvd_trans[OF p(2) qn1]\n      have npp: \"(n - 1) div p * p = n - 1\" by simp\n      with eq0 have \"a^ (n - 1) = (n*s)^p\"\n        by (simp add: power_mult[symmetric])\n      hence \"1 = (n*s)^(Suc (p - 1)) mod n\" using bqn p01 by simp\n      also have \"\\<dots> = 0\" by (simp add: mult.assoc)\n      finally have False by simp }\n      then have th11: \"a ^ ((n - 1) div p) mod n \\<noteq> 0\" by auto\n    have th1: \"[a ^ ((n - 1) div p) mod n = a ^ ((n - 1) div p)] (mod n)\"\n      unfolding cong_nat_def by simp\n    from  th1   ath[OF mod_less_eq_dividend th11]\n    have th: \"[a ^ ((n - 1) div p) mod n - 1 = a ^ ((n - 1) div p) - 1] (mod n)\"\n      by (metis cong_diff_nat cong_refl_nat)\n    have \"coprime (a ^ ((n - 1) div p) - 1) n\"\n      by (metis cong_imp_coprime_nat eq1 p' th) }\n  with pocklington[OF n qrn[symmetric] nq2 an1]\n  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/Pocklington.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314858927011, "lm_q2_score": 0.8311430562234877, "lm_q1q2_score": 0.7360864598726082}}
{"text": "(*  Title:      HOL/Old_Number_Theory/Residues.thy\n    Authors:    Jeremy Avigad, David Gray, and Adam Kramer\n*)\n\nsection {* Residue Sets *}\n\ntheory Residues\nimports Int2\nbegin\n\ntext {*\n  \\medskip Define the residue of a set, the standard residue,\n  quadratic residues, and prove some basic properties. *}\n\ndefinition ResSet :: \"int => int set => bool\"\n  where \"ResSet m X = (\\<forall>y1 y2. (y1 \\<in> X & y2 \\<in> X & [y1 = y2] (mod m) --> y1 = y2))\"\n\ndefinition StandardRes :: \"int => int => int\"\n  where \"StandardRes m x = x mod m\"\n\ndefinition QuadRes :: \"int => int => bool\"\n  where \"QuadRes m x = (\\<exists>y. ([y\\<^sup>2 = x] (mod m)))\"\n\ndefinition Legendre :: \"int => int => int\" where\n  \"Legendre a p = (if ([a = 0] (mod p)) then 0\n                     else if (QuadRes p a) then 1\n                     else -1)\"\n\ndefinition SR :: \"int => int set\"\n  where \"SR p = {x. (0 \\<le> x) & (x < p)}\"\n\ndefinition SRStar :: \"int => int set\"\n  where \"SRStar p = {x. (0 < x) & (x < p)}\"\n\n\nsubsection {* Some useful properties of StandardRes *}\n\nlemma StandardRes_prop1: \"[x = StandardRes m x] (mod m)\"\n  by (auto simp add: StandardRes_def zcong_zmod)\n\nlemma StandardRes_prop2: \"0 < m ==> (StandardRes m x1 = StandardRes m x2)\n      = ([x1 = x2] (mod m))\"\n  by (auto simp add: StandardRes_def zcong_zmod_eq)\n\nlemma StandardRes_prop3: \"(~[x = 0] (mod p)) = (~(StandardRes p x = 0))\"\n  by (auto simp add: StandardRes_def zcong_def dvd_eq_mod_eq_0)\n\nlemma StandardRes_prop4: \"2 < m \n     ==> [StandardRes m x * StandardRes m y = (x * y)] (mod m)\"\n  by (auto simp add: StandardRes_def zcong_zmod_eq \n                     mod_mult_eq [of x y m])\n\nlemma StandardRes_lbound: \"0 < p ==> 0 \\<le> StandardRes p x\"\n  by (auto simp add: StandardRes_def)\n\nlemma StandardRes_ubound: \"0 < p ==> StandardRes p x < p\"\n  by (auto simp add: StandardRes_def)\n\nlemma StandardRes_eq_zcong: \n   \"(StandardRes m x = 0) = ([x = 0](mod m))\"\n  by (auto simp add: StandardRes_def zcong_eq_zdvd_prop dvd_def) \n\n\nsubsection {* Relations between StandardRes, SRStar, and SR *}\n\nlemma SRStar_SR_prop: \"x \\<in> SRStar p ==> x \\<in> SR p\"\n  by (auto simp add: SRStar_def SR_def)\n\nlemma StandardRes_SR_prop: \"x \\<in> SR p ==> StandardRes p x = x\"\n  by (auto simp add: SR_def StandardRes_def mod_pos_pos_trivial)\n\nlemma StandardRes_SRStar_prop1: \"2 < p ==> (StandardRes p x \\<in> SRStar p) \n     = (~[x = 0] (mod p))\"\n  apply (auto simp add: StandardRes_prop3 StandardRes_def SRStar_def)\n  apply (subgoal_tac \"0 < p\")\n  apply (drule_tac a = x in pos_mod_sign, arith, simp)\n  done\n\nlemma StandardRes_SRStar_prop1a: \"x \\<in> SRStar p ==> ~([x = 0] (mod p))\"\n  by (auto simp add: SRStar_def zcong_def zdvd_not_zless)\n\nlemma StandardRes_SRStar_prop2: \"[| 2 < p; zprime p; x \\<in> SRStar p |] \n     ==> StandardRes p (MultInv p x) \\<in> SRStar p\"\n  apply (frule_tac x = \"(MultInv p x)\" in StandardRes_SRStar_prop1, simp)\n  apply (rule MultInv_prop3)\n  apply (auto simp add: SRStar_def zcong_def zdvd_not_zless)\n  done\n\nlemma StandardRes_SRStar_prop3: \"x \\<in> SRStar p ==> StandardRes p x = x\"\n  by (auto simp add: SRStar_SR_prop StandardRes_SR_prop)\n\nlemma StandardRes_SRStar_prop4: \"[| zprime p; 2 < p; x \\<in> SRStar p |] \n     ==> StandardRes p x \\<in> SRStar p\"\n  by (frule StandardRes_SRStar_prop3, auto)\n\nlemma SRStar_mult_prop1: \"[| zprime p; 2 < p; x \\<in> SRStar p; y \\<in> SRStar p|] \n     ==> (StandardRes p (x * y)):SRStar p\"\n  apply (frule_tac x = x in StandardRes_SRStar_prop4, auto)\n  apply (frule_tac x = y in StandardRes_SRStar_prop4, auto)\n  apply (auto simp add: StandardRes_SRStar_prop1 zcong_zmult_prop3)\n  done\n\nlemma SRStar_mult_prop2: \"[| zprime p; 2 < p; ~([a = 0](mod p)); \n     x \\<in> SRStar p |] \n     ==> StandardRes p (a * MultInv p x) \\<in> SRStar p\"\n  apply (frule_tac x = x in StandardRes_SRStar_prop2, auto)\n  apply (frule_tac x = \"MultInv p x\" in StandardRes_SRStar_prop1)\n  apply (auto simp add: StandardRes_SRStar_prop1 zcong_zmult_prop3)\n  done\n\nlemma SRStar_card: \"2 < p ==> int(card(SRStar p)) = p - 1\"\n  by (auto simp add: SRStar_def int_card_bdd_int_set_l_l)\n\nlemma SRStar_finite: \"2 < p ==> finite( SRStar p)\"\n  by (auto simp add: SRStar_def bdd_int_set_l_l_finite)\n\n\nsubsection {* Properties relating ResSets with StandardRes *}\n\nlemma aux: \"x mod m = y mod m ==> [x = y] (mod m)\"\n  apply (subgoal_tac \"x = y ==> [x = y](mod m)\")\n  apply (subgoal_tac \"[x mod m = y mod m] (mod m) ==> [x = y] (mod m)\")\n  apply (auto simp add: zcong_zmod [of x y m])\n  done\n\nlemma StandardRes_inj_on_ResSet: \"ResSet m X ==> (inj_on (StandardRes m) X)\"\n  apply (auto simp add: ResSet_def StandardRes_def inj_on_def)\n  apply (drule_tac m = m in aux, auto)\n  done\n\nlemma StandardRes_Sum: \"[| finite X; 0 < m |] \n     ==> [setsum f X = setsum (StandardRes m o f) X](mod m)\" \n  apply (rule_tac F = X in finite_induct)\n  apply (auto intro!: zcong_zadd simp add: StandardRes_prop1)\n  done\n\nlemma SR_pos: \"0 < m ==> (StandardRes m ` X) \\<subseteq> {x. 0 \\<le> x & x < m}\"\n  by (auto simp add: StandardRes_ubound StandardRes_lbound)\n\nlemma ResSet_finite: \"0 < m ==> ResSet m X ==> finite X\"\n  apply (rule_tac f = \"StandardRes m\" in finite_imageD) \n  apply (rule_tac B = \"{x. (0 :: int) \\<le> x & x < m}\" in finite_subset)\n  apply (auto simp add: StandardRes_inj_on_ResSet bdd_int_set_l_finite SR_pos)\n  done\n\nlemma mod_mod_is_mod: \"[x = x mod m](mod m)\"\n  by (auto simp add: zcong_zmod)\n\nlemma StandardRes_prod: \"[| finite X; 0 < m |] \n     ==> [setprod f X = setprod (StandardRes m o f) X] (mod m)\"\n  apply (rule_tac F = X in finite_induct)\n  apply (auto intro!: zcong_zmult simp add: StandardRes_prop1)\n  done\n\nlemma ResSet_image:\n  \"[| 0 < m; ResSet m A; \\<forall>x \\<in> A. \\<forall>y \\<in> A. ([f x = f y](mod m) --> x = y) |] ==>\n    ResSet m (f ` A)\"\n  by (auto simp add: ResSet_def)\n\n\nsubsection {* Property for SRStar *}\n\nlemma ResSet_SRStar_prop: \"ResSet p (SRStar p)\"\n  by (auto simp add: SRStar_def ResSet_def zcong_zless_imp_eq)\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/Old_Number_Theory/Residues.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314828740728, "lm_q2_score": 0.8311430499496096, "lm_q1q2_score": 0.7360864518073523}}
{"text": "(*  Title:      HOL/Nonstandard_Analysis/HSEQ.thy\n    Author:     Jacques D. Fleuriot\n    Copyright:  1998  University of Cambridge\n\nConvergence of sequences and series.\n\nConversion to Isar and new proofs by Lawrence C Paulson, 2004\nAdditional contributions by Jeremy Avigad and Brian Huffman.\n*)\n\nsection \\<open>Sequences and Convergence (Nonstandard)\\<close>\n\ntheory HSEQ\n  imports Complex_Main NatStar\n  abbrevs \"--->\" = \"\\<longlonglongrightarrow>\\<^sub>N\\<^sub>S\"\nbegin\n\ndefinition NSLIMSEQ :: \"(nat \\<Rightarrow> 'a::real_normed_vector) \\<Rightarrow> 'a \\<Rightarrow> bool\"\n    (\"((_)/ \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S (_))\" [60, 60] 60) where\n    \\<comment> \\<open>Nonstandard definition of convergence of sequence\\<close>\n  \"X \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S L \\<longleftrightarrow> (\\<forall>N \\<in> HNatInfinite. ( *f* X) N \\<approx> star_of L)\"\n\ndefinition nslim :: \"(nat \\<Rightarrow> 'a::real_normed_vector) \\<Rightarrow> 'a\"\n  where \"nslim X = (THE L. X \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S L)\"\n  \\<comment> \\<open>Nonstandard definition of limit using choice operator\\<close>\n\n\ndefinition NSconvergent :: \"(nat \\<Rightarrow> 'a::real_normed_vector) \\<Rightarrow> bool\"\n  where \"NSconvergent X \\<longleftrightarrow> (\\<exists>L. X \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S L)\"\n  \\<comment> \\<open>Nonstandard definition of convergence\\<close>\n\ndefinition NSBseq :: \"(nat \\<Rightarrow> 'a::real_normed_vector) \\<Rightarrow> bool\"\n  where \"NSBseq X \\<longleftrightarrow> (\\<forall>N \\<in> HNatInfinite. ( *f* X) N \\<in> HFinite)\"\n  \\<comment> \\<open>Nonstandard definition for bounded sequence\\<close>\n\n\ndefinition NSCauchy :: \"(nat \\<Rightarrow> 'a::real_normed_vector) \\<Rightarrow> bool\"\n  where \"NSCauchy X \\<longleftrightarrow> (\\<forall>M \\<in> HNatInfinite. \\<forall>N \\<in> HNatInfinite. ( *f* X) M \\<approx> ( *f* X) N)\"\n  \\<comment> \\<open>Nonstandard definition\\<close>\n\n\nsubsection \\<open>Limits of Sequences\\<close>\n\nlemma NSLIMSEQ_I: \"(\\<And>N. N \\<in> HNatInfinite \\<Longrightarrow> starfun X N \\<approx> star_of L) \\<Longrightarrow> X \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S L\"\n  by (simp add: NSLIMSEQ_def)\n\nlemma NSLIMSEQ_D: \"X \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S L \\<Longrightarrow> N \\<in> HNatInfinite \\<Longrightarrow> starfun X N \\<approx> star_of L\"\n  by (simp add: NSLIMSEQ_def)\n\nlemma NSLIMSEQ_const: \"(\\<lambda>n. k) \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S k\"\n  by (simp add: NSLIMSEQ_def)\n\nlemma NSLIMSEQ_add: \"X \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S a \\<Longrightarrow> Y \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S b \\<Longrightarrow> (\\<lambda>n. X n + Y n) \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S a + b\"\n  by (auto intro: approx_add simp add: NSLIMSEQ_def)\n\nlemma NSLIMSEQ_add_const: \"f \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S a \\<Longrightarrow> (\\<lambda>n. f n + b) \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S a + b\"\n  by (simp only: NSLIMSEQ_add NSLIMSEQ_const)\n\nlemma NSLIMSEQ_mult: \"X \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S a \\<Longrightarrow> Y \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S b \\<Longrightarrow> (\\<lambda>n. X n * Y n) \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S a * b\"\n  for a b :: \"'a::real_normed_algebra\"\n  by (auto intro!: approx_mult_HFinite simp add: NSLIMSEQ_def)\n\nlemma NSLIMSEQ_minus: \"X \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S a \\<Longrightarrow> (\\<lambda>n. - X n) \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S - a\"\n  by (auto simp add: NSLIMSEQ_def)\n\nlemma NSLIMSEQ_minus_cancel: \"(\\<lambda>n. - X n) \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S -a \\<Longrightarrow> X \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S a\"\n  by (drule NSLIMSEQ_minus) simp\n\nlemma NSLIMSEQ_diff: \"X \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S a \\<Longrightarrow> Y \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S b \\<Longrightarrow> (\\<lambda>n. X n - Y n) \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S a - b\"\n  using NSLIMSEQ_add [of X a \"- Y\" \"- b\"] by (simp add: NSLIMSEQ_minus fun_Compl_def)\n\nlemma NSLIMSEQ_diff_const: \"f \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S a \\<Longrightarrow> (\\<lambda>n. f n - b) \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S a - b\"\n  by (simp add: NSLIMSEQ_diff NSLIMSEQ_const)\n\nlemma NSLIMSEQ_inverse: \"X \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S a \\<Longrightarrow> a \\<noteq> 0 \\<Longrightarrow> (\\<lambda>n. inverse (X n)) \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S inverse a\"\n  for a :: \"'a::real_normed_div_algebra\"\n  by (simp add: NSLIMSEQ_def star_of_approx_inverse)\n\nlemma NSLIMSEQ_mult_inverse: \"X \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S a \\<Longrightarrow> Y \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S b \\<Longrightarrow> b \\<noteq> 0 \\<Longrightarrow> (\\<lambda>n. X n / Y n) \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S a / b\"\n  for a b :: \"'a::real_normed_field\"\n  by (simp add: NSLIMSEQ_mult NSLIMSEQ_inverse divide_inverse)\n\nlemma starfun_hnorm: \"\\<And>x. hnorm (( *f* f) x) = ( *f* (\\<lambda>x. norm (f x))) x\"\n  by transfer simp\n\nlemma NSLIMSEQ_norm: \"X \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S a \\<Longrightarrow> (\\<lambda>n. norm (X n)) \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S norm a\"\n  by (simp add: NSLIMSEQ_def starfun_hnorm [symmetric] approx_hnorm)\n\ntext \\<open>Uniqueness of limit.\\<close>\nlemma NSLIMSEQ_unique: \"X \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S a \\<Longrightarrow> X \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S b \\<Longrightarrow> a = b\"\n  unfolding NSLIMSEQ_def\n  using HNatInfinite_whn approx_trans3 star_of_approx_iff by blast\n\nlemma NSLIMSEQ_pow [rule_format]: \"(X \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S a) \\<longrightarrow> ((\\<lambda>n. (X n) ^ m) \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S a ^ m)\"\n  for a :: \"'a::{real_normed_algebra,power}\"\n  by (induct m) (auto intro: NSLIMSEQ_mult NSLIMSEQ_const)\n\ntext \\<open>We can now try and derive a few properties of sequences,\n  starting with the limit comparison property for sequences.\\<close>\n\nlemma NSLIMSEQ_le: \"f \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S l \\<Longrightarrow> g \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S m \\<Longrightarrow> \\<exists>N. \\<forall>n \\<ge> N. f n \\<le> g n \\<Longrightarrow> l \\<le> m\"\n  for l m :: real\n  unfolding NSLIMSEQ_def\n  by (metis HNatInfinite_whn bex_Infinitesimal_iff2 hypnat_of_nat_le_whn hypreal_of_real_le_add_Infininitesimal_cancel2 starfun_le_mono)\n \nlemma NSLIMSEQ_le_const: \"X \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S r \\<Longrightarrow> \\<forall>n. a \\<le> X n \\<Longrightarrow> a \\<le> r\"\n  for a r :: real\n  by (erule NSLIMSEQ_le [OF NSLIMSEQ_const]) auto\n\nlemma NSLIMSEQ_le_const2: \"X \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S r \\<Longrightarrow> \\<forall>n. X n \\<le> a \\<Longrightarrow> r \\<le> a\"\n  for a r :: real\n  by (erule NSLIMSEQ_le [OF _ NSLIMSEQ_const]) auto\n\ntext \\<open>Shift a convergent series by 1:\n  By the equivalence between Cauchiness and convergence and because\n  the successor of an infinite hypernatural is also infinite.\\<close>\n\nlemma NSLIMSEQ_Suc_iff: \"((\\<lambda>n. f (Suc n)) \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S l) \\<longleftrightarrow> (f \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S l)\"\nproof\n  assume *: \"f \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S l\"\n  show \"(\\<lambda>n. f(Suc n)) \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S l\"\n  proof (rule NSLIMSEQ_I)\n    fix N\n    assume \"N \\<in> HNatInfinite\"\n    then have \"(*f* f) (N + 1) \\<approx> star_of l\"\n      by (simp add: HNatInfinite_add NSLIMSEQ_D *)\n    then show \"(*f* (\\<lambda>n. f (Suc n))) N \\<approx> star_of l\"\n      by (simp add: starfun_shift_one)\n  qed\nnext\n  assume *: \"(\\<lambda>n. f(Suc n)) \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S l\"\n  show \"f \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S l\"\n  proof (rule NSLIMSEQ_I)\n    fix N\n    assume \"N \\<in> HNatInfinite\"\n    then have \"(*f* (\\<lambda>n. f (Suc n))) (N - 1) \\<approx> star_of l\"\n      using * by (simp add: HNatInfinite_diff NSLIMSEQ_D)\n    then show \"(*f* f) N \\<approx> star_of l\"\n      by (simp add: \\<open>N \\<in> HNatInfinite\\<close> one_le_HNatInfinite starfun_shift_one)\n  qed\nqed\n\n\nsubsubsection \\<open>Equivalence of \\<^term>\\<open>LIMSEQ\\<close> and \\<^term>\\<open>NSLIMSEQ\\<close>\\<close>\n\nlemma LIMSEQ_NSLIMSEQ:\n  assumes X: \"X \\<longlonglongrightarrow> L\"\n  shows \"X \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S L\"\nproof (rule NSLIMSEQ_I)\n  fix N\n  assume N: \"N \\<in> HNatInfinite\"\n  have \"starfun X N - star_of L \\<in> Infinitesimal\"\n  proof (rule InfinitesimalI2)\n    fix r :: real\n    assume r: \"0 < r\"\n    from LIMSEQ_D [OF X r] obtain no where \"\\<forall>n\\<ge>no. norm (X n - L) < r\" ..\n    then have \"\\<forall>n\\<ge>star_of no. hnorm (starfun X n - star_of L) < star_of r\"\n      by transfer\n    then show \"hnorm (starfun X N - star_of L) < star_of r\"\n      using N by (simp add: star_of_le_HNatInfinite)\n  qed\n  then show \"starfun X N \\<approx> star_of L\"\n    by (simp only: approx_def)\nqed\n\nlemma NSLIMSEQ_LIMSEQ:\n  assumes X: \"X \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S L\"\n  shows \"X \\<longlonglongrightarrow> L\"\nproof (rule LIMSEQ_I)\n  fix r :: real\n  assume r: \"0 < r\"\n  have \"\\<exists>no. \\<forall>n\\<ge>no. hnorm (starfun X n - star_of L) < star_of r\"\n  proof (intro exI allI impI)\n    fix n\n    assume \"whn \\<le> n\"\n    with HNatInfinite_whn have \"n \\<in> HNatInfinite\"\n      by (rule HNatInfinite_upward_closed)\n    with X have \"starfun X n \\<approx> star_of L\"\n      by (rule NSLIMSEQ_D)\n    then have \"starfun X n - star_of L \\<in> Infinitesimal\"\n      by (simp only: approx_def)\n    then show \"hnorm (starfun X n - star_of L) < star_of r\"\n      using r by (rule InfinitesimalD2)\n  qed\n  then show \"\\<exists>no. \\<forall>n\\<ge>no. norm (X n - L) < r\"\n    by transfer\nqed\n\ntheorem LIMSEQ_NSLIMSEQ_iff: \"f \\<longlonglongrightarrow> L \\<longleftrightarrow> f \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S L\"\n  by (blast intro: LIMSEQ_NSLIMSEQ NSLIMSEQ_LIMSEQ)\n\n\nsubsubsection \\<open>Derived theorems about \\<^term>\\<open>NSLIMSEQ\\<close>\\<close>\n\ntext \\<open>We prove the NS version from the standard one, since the NS proof\n  seems more complicated than the standard one above!\\<close>\nlemma NSLIMSEQ_norm_zero: \"(\\<lambda>n. norm (X n)) \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S 0 \\<longleftrightarrow> X \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S 0\"\n  by (simp add: LIMSEQ_NSLIMSEQ_iff [symmetric] tendsto_norm_zero_iff)\n\nlemma NSLIMSEQ_rabs_zero: \"(\\<lambda>n. \\<bar>f n\\<bar>) \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S 0 \\<longleftrightarrow> f \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S (0::real)\"\n  by (simp add: LIMSEQ_NSLIMSEQ_iff [symmetric] tendsto_rabs_zero_iff)\n\ntext \\<open>Generalization to other limits.\\<close>\nlemma NSLIMSEQ_imp_rabs: \"f \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S l \\<Longrightarrow> (\\<lambda>n. \\<bar>f n\\<bar>) \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S \\<bar>l\\<bar>\"\n  for l :: real\n  by (simp add: NSLIMSEQ_def) (auto intro: approx_hrabs simp add: starfun_abs)\n\nlemma NSLIMSEQ_inverse_zero: \"\\<forall>y::real. \\<exists>N. \\<forall>n \\<ge> N. y < f n \\<Longrightarrow> (\\<lambda>n. inverse (f n)) \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S 0\"\n  by (simp add: LIMSEQ_NSLIMSEQ_iff [symmetric] LIMSEQ_inverse_zero)\n\nlemma NSLIMSEQ_inverse_real_of_nat: \"(\\<lambda>n. inverse (real (Suc n))) \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S 0\"\n  by (simp add: LIMSEQ_NSLIMSEQ_iff [symmetric] LIMSEQ_inverse_real_of_nat del: of_nat_Suc)\n\nlemma NSLIMSEQ_inverse_real_of_nat_add: \"(\\<lambda>n. r + inverse (real (Suc n))) \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S r\"\n  by (simp add: LIMSEQ_NSLIMSEQ_iff [symmetric] LIMSEQ_inverse_real_of_nat_add del: of_nat_Suc)\n\nlemma NSLIMSEQ_inverse_real_of_nat_add_minus: \"(\\<lambda>n. r + - inverse (real (Suc n))) \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S r\"\n  using LIMSEQ_inverse_real_of_nat_add_minus by (simp add: LIMSEQ_NSLIMSEQ_iff [symmetric])\n\nlemma NSLIMSEQ_inverse_real_of_nat_add_minus_mult:\n  \"(\\<lambda>n. r * (1 + - inverse (real (Suc n)))) \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S r\"\n  using LIMSEQ_inverse_real_of_nat_add_minus_mult\n  by (simp add: LIMSEQ_NSLIMSEQ_iff [symmetric])\n\n\nsubsection \\<open>Convergence\\<close>\n\nlemma nslimI: \"X \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S L \\<Longrightarrow> nslim X = L\"\n  by (simp add: nslim_def) (blast intro: NSLIMSEQ_unique)\n\nlemma lim_nslim_iff: \"lim X = nslim X\"\n  by (simp add: lim_def nslim_def LIMSEQ_NSLIMSEQ_iff)\n\nlemma NSconvergentD: \"NSconvergent X \\<Longrightarrow> \\<exists>L. X \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S L\"\n  by (simp add: NSconvergent_def)\n\nlemma NSconvergentI: \"X \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S L \\<Longrightarrow> NSconvergent X\"\n  by (auto simp add: NSconvergent_def)\n\nlemma convergent_NSconvergent_iff: \"convergent X = NSconvergent X\"\n  by (simp add: convergent_def NSconvergent_def LIMSEQ_NSLIMSEQ_iff)\n\nlemma NSconvergent_NSLIMSEQ_iff: \"NSconvergent X \\<longleftrightarrow> X \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S nslim X\"\n  by (auto intro: theI NSLIMSEQ_unique simp add: NSconvergent_def nslim_def)\n\n\nsubsection \\<open>Bounded Monotonic Sequences\\<close>\n\nlemma NSBseqD: \"NSBseq X \\<Longrightarrow> N \\<in> HNatInfinite \\<Longrightarrow> ( *f* X) N \\<in> HFinite\"\n  by (simp add: NSBseq_def)\n\nlemma Standard_subset_HFinite: \"Standard \\<subseteq> HFinite\"\n  by (auto simp: Standard_def)\n\nlemma NSBseqD2: \"NSBseq X \\<Longrightarrow> ( *f* X) N \\<in> HFinite\"\n  using HNatInfinite_def NSBseq_def Nats_eq_Standard Standard_starfun Standard_subset_HFinite by blast\n\nlemma NSBseqI: \"\\<forall>N \\<in> HNatInfinite. ( *f* X) N \\<in> HFinite \\<Longrightarrow> NSBseq X\"\n  by (simp add: NSBseq_def)\n\ntext \\<open>The standard definition implies the nonstandard definition.\\<close>\nlemma Bseq_NSBseq: \"Bseq X \\<Longrightarrow> NSBseq X\"\n  unfolding NSBseq_def\nproof safe\n  assume X: \"Bseq X\"\n  fix N\n  assume N: \"N \\<in> HNatInfinite\"\n  from BseqD [OF X] obtain K where \"\\<forall>n. norm (X n) \\<le> K\"\n    by fast\n  then have \"\\<forall>N. hnorm (starfun X N) \\<le> star_of K\"\n    by transfer\n  then have \"hnorm (starfun X N) \\<le> star_of K\"\n    by simp\n  also have \"star_of K < star_of (K + 1)\"\n    by simp\n  finally have \"\\<exists>x\\<in>Reals. hnorm (starfun X N) < x\"\n    by (rule bexI) simp\n  then show \"starfun X N \\<in> HFinite\"\n    by (simp add: HFinite_def)\nqed\n\ntext \\<open>The nonstandard definition implies the standard definition.\\<close>\nlemma SReal_less_omega: \"r \\<in> \\<real> \\<Longrightarrow> r < \\<omega>\"\n  using HInfinite_omega\n  by (simp add: HInfinite_def) (simp add: order_less_imp_le)\n\nlemma NSBseq_Bseq: \"NSBseq X \\<Longrightarrow> Bseq X\"\nproof (rule ccontr)\n  let ?n = \"\\<lambda>K. LEAST n. K < norm (X n)\"\n  assume \"NSBseq X\"\n  then have finite: \"( *f* X) (( *f* ?n) \\<omega>) \\<in> HFinite\"\n    by (rule NSBseqD2)\n  assume \"\\<not> Bseq X\"\n  then have \"\\<forall>K>0. \\<exists>n. K < norm (X n)\"\n    by (simp add: Bseq_def linorder_not_le)\n  then have \"\\<forall>K>0. K < norm (X (?n K))\"\n    by (auto intro: LeastI_ex)\n  then have \"\\<forall>K>0. K < hnorm (( *f* X) (( *f* ?n) K))\"\n    by transfer\n  then have \"\\<omega> < hnorm (( *f* X) (( *f* ?n) \\<omega>))\"\n    by simp\n  then have \"\\<forall>r\\<in>\\<real>. r < hnorm (( *f* X) (( *f* ?n) \\<omega>))\"\n    by (simp add: order_less_trans [OF SReal_less_omega])\n  then have \"( *f* X) (( *f* ?n) \\<omega>) \\<in> HInfinite\"\n    by (simp add: HInfinite_def)\n  with finite show \"False\"\n    by (simp add: HFinite_HInfinite_iff)\nqed\n\ntext \\<open>Equivalence of nonstandard and standard definitions for a bounded sequence.\\<close>\nlemma Bseq_NSBseq_iff: \"Bseq X = NSBseq X\"\n  by (blast intro!: NSBseq_Bseq Bseq_NSBseq)\n\ntext \\<open>A convergent sequence is bounded:\n  Boundedness as a necessary condition for convergence.\n  The nonstandard version has no existential, as usual.\\<close>\nlemma NSconvergent_NSBseq: \"NSconvergent X \\<Longrightarrow> NSBseq X\"\n  by (simp add: NSconvergent_def NSBseq_def NSLIMSEQ_def)\n    (blast intro: HFinite_star_of approx_sym approx_HFinite)\n\ntext \\<open>Standard Version: easily now proved using equivalence of NS and\n standard definitions.\\<close>\n\nlemma convergent_Bseq: \"convergent X \\<Longrightarrow> Bseq X\"\n  for X :: \"nat \\<Rightarrow> 'b::real_normed_vector\"\n  by (simp add: NSconvergent_NSBseq convergent_NSconvergent_iff Bseq_NSBseq_iff)\n\n\nsubsubsection \\<open>Upper Bounds and Lubs of Bounded Sequences\\<close>\n\nlemma NSBseq_isUb: \"NSBseq X \\<Longrightarrow> \\<exists>U::real. isUb UNIV {x. \\<exists>n. X n = x} U\"\n  by (simp add: Bseq_NSBseq_iff [symmetric] Bseq_isUb)\n\nlemma NSBseq_isLub: \"NSBseq X \\<Longrightarrow> \\<exists>U::real. isLub UNIV {x. \\<exists>n. X n = x} U\"\n  by (simp add: Bseq_NSBseq_iff [symmetric] Bseq_isLub)\n\n\nsubsubsection \\<open>A Bounded and Monotonic Sequence Converges\\<close>\n\ntext \\<open>The best of both worlds: Easier to prove this result as a standard\n   theorem and then use equivalence to \"transfer\" it into the\n   equivalent nonstandard form if needed!\\<close>\n\nlemma Bmonoseq_NSLIMSEQ: \"\\<forall>\\<^sub>F k in sequentially. X k = X m \\<Longrightarrow> X \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S X m\"\n  unfolding LIMSEQ_NSLIMSEQ_iff[symmetric]\n  by (simp add: eventually_mono eventually_nhds_x_imp_x filterlim_iff)\n\nlemma NSBseq_mono_NSconvergent: \"NSBseq X \\<Longrightarrow> \\<forall>m. \\<forall>n \\<ge> m. X m \\<le> X n \\<Longrightarrow> NSconvergent X\"\n  for X :: \"nat \\<Rightarrow> real\"\n  by (auto intro: Bseq_mono_convergent\n      simp: convergent_NSconvergent_iff [symmetric] Bseq_NSBseq_iff [symmetric])\n\n\nsubsection \\<open>Cauchy Sequences\\<close>\n\nlemma NSCauchyI:\n  \"(\\<And>M N. M \\<in> HNatInfinite \\<Longrightarrow> N \\<in> HNatInfinite \\<Longrightarrow> starfun X M \\<approx> starfun X N) \\<Longrightarrow> NSCauchy X\"\n  by (simp add: NSCauchy_def)\n\nlemma NSCauchyD:\n  \"NSCauchy X \\<Longrightarrow> M \\<in> HNatInfinite \\<Longrightarrow> N \\<in> HNatInfinite \\<Longrightarrow> starfun X M \\<approx> starfun X N\"\n  by (simp add: NSCauchy_def)\n\n\nsubsubsection \\<open>Equivalence Between NS and Standard\\<close>\n\nlemma Cauchy_NSCauchy:\n  assumes X: \"Cauchy X\"\n  shows \"NSCauchy X\"\nproof (rule NSCauchyI)\n  fix M\n  assume M: \"M \\<in> HNatInfinite\"\n  fix N\n  assume N: \"N \\<in> HNatInfinite\"\n  have \"starfun X M - starfun X N \\<in> Infinitesimal\"\n  proof (rule InfinitesimalI2)\n    fix r :: real\n    assume r: \"0 < r\"\n    from CauchyD [OF X r] obtain k where \"\\<forall>m\\<ge>k. \\<forall>n\\<ge>k. norm (X m - X n) < r\" ..\n    then have \"\\<forall>m\\<ge>star_of k. \\<forall>n\\<ge>star_of k. hnorm (starfun X m - starfun X n) < star_of r\"\n      by transfer\n    then show \"hnorm (starfun X M - starfun X N) < star_of r\"\n      using M N by (simp add: star_of_le_HNatInfinite)\n  qed\n  then show \"starfun X M \\<approx> starfun X N\"\n    by (simp only: approx_def)\nqed\n\nlemma NSCauchy_Cauchy:\n  assumes X: \"NSCauchy X\"\n  shows \"Cauchy X\"\nproof (rule CauchyI)\n  fix r :: real\n  assume r: \"0 < r\"\n  have \"\\<exists>k. \\<forall>m\\<ge>k. \\<forall>n\\<ge>k. hnorm (starfun X m - starfun X n) < star_of r\"\n  proof (intro exI allI impI)\n    fix M\n    assume \"whn \\<le> M\"\n    with HNatInfinite_whn have M: \"M \\<in> HNatInfinite\"\n      by (rule HNatInfinite_upward_closed)\n    fix N\n    assume \"whn \\<le> N\"\n    with HNatInfinite_whn have N: \"N \\<in> HNatInfinite\"\n      by (rule HNatInfinite_upward_closed)\n    from X M N have \"starfun X M \\<approx> starfun X N\"\n      by (rule NSCauchyD)\n    then have \"starfun X M - starfun X N \\<in> Infinitesimal\"\n      by (simp only: approx_def)\n    then show \"hnorm (starfun X M - starfun X N) < star_of r\"\n      using r by (rule InfinitesimalD2)\n  qed\n  then show \"\\<exists>k. \\<forall>m\\<ge>k. \\<forall>n\\<ge>k. norm (X m - X n) < r\"\n    by transfer\nqed\n\ntheorem NSCauchy_Cauchy_iff: \"NSCauchy X = Cauchy X\"\n  by (blast intro!: NSCauchy_Cauchy Cauchy_NSCauchy)\n\n\nsubsubsection \\<open>Cauchy Sequences are Bounded\\<close>\n\ntext \\<open>A Cauchy sequence is bounded -- nonstandard version.\\<close>\n\nlemma NSCauchy_NSBseq: \"NSCauchy X \\<Longrightarrow> NSBseq X\"\n  by (simp add: Cauchy_Bseq Bseq_NSBseq_iff [symmetric] NSCauchy_Cauchy_iff)\n\n\nsubsubsection \\<open>Cauchy Sequences are Convergent\\<close>\n\ntext \\<open>Equivalence of Cauchy criterion and convergence:\n  We will prove this using our NS formulation which provides a\n  much easier proof than using the standard definition. We do not\n  need to use properties of subsequences such as boundedness,\n  monotonicity etc... Compare with Harrison's corresponding proof\n  in HOL which is much longer and more complicated. Of course, we do\n  not have problems which he encountered with guessing the right\n  instantiations for his 'espsilon-delta' proof(s) in this case\n  since the NS formulations do not involve existential quantifiers.\\<close>\n\nlemma NSconvergent_NSCauchy: \"NSconvergent X \\<Longrightarrow> NSCauchy X\"\n  by (simp add: NSconvergent_def NSLIMSEQ_def NSCauchy_def) (auto intro: approx_trans2)\n\nlemma real_NSCauchy_NSconvergent: \n  fixes X :: \"nat \\<Rightarrow> real\"\n  assumes \"NSCauchy X\" shows \"NSconvergent X\"\n  unfolding NSconvergent_def NSLIMSEQ_def\nproof -\n  have \"( *f* X) whn \\<in> HFinite\"\n    by (simp add: NSBseqD2 NSCauchy_NSBseq assms)\n  moreover have \"\\<forall>N\\<in>HNatInfinite. ( *f* X) whn \\<approx> ( *f* X) N\"\n    using HNatInfinite_whn NSCauchy_def assms by blast\n  ultimately show \"\\<exists>L. \\<forall>N\\<in>HNatInfinite. ( *f* X) N \\<approx> hypreal_of_real L\"\n    by (force dest!: st_part_Ex simp add: SReal_iff intro: approx_trans3)\nqed\n\nlemma NSCauchy_NSconvergent: \"NSCauchy X \\<Longrightarrow> NSconvergent X\"\n  for X :: \"nat \\<Rightarrow> 'a::banach\"\n  using Cauchy_convergent NSCauchy_Cauchy convergent_NSconvergent_iff by auto\n\nlemma NSCauchy_NSconvergent_iff: \"NSCauchy X = NSconvergent X\"\n  for X :: \"nat \\<Rightarrow> 'a::banach\"\n  by (fast intro: NSCauchy_NSconvergent NSconvergent_NSCauchy)\n\n\nsubsection \\<open>Power Sequences\\<close>\n\ntext \\<open>The sequence \\<^term>\\<open>x^n\\<close> tends to 0 if \\<^term>\\<open>0\\<le>x\\<close> and \\<^term>\\<open>x<1\\<close>.  Proof will use (NS) Cauchy equivalence for convergence and\n  also fact that bounded and monotonic sequence converges.\\<close>\n\ntext \\<open>We now use NS criterion to bring proof of theorem through.\\<close>\nlemma NSLIMSEQ_realpow_zero:\n  fixes x :: real\n  assumes \"0 \\<le> x\" \"x < 1\" shows \"(\\<lambda>n. x ^ n) \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S 0\"\nproof -\n  have \"( *f* (^) x) N \\<approx> 0\"\n    if N: \"N \\<in> HNatInfinite\" and x: \"NSconvergent ((^) x)\" for N\n  proof -\n    have \"hypreal_of_real x pow N \\<approx> hypreal_of_real x pow (N + 1)\"\n      by (metis HNatInfinite_add N NSCauchy_NSconvergent_iff NSCauchy_def starfun_pow x)\n    moreover obtain L where L: \"hypreal_of_real x pow N \\<approx> hypreal_of_real L\"\n      using NSconvergentD [OF x] N by (auto simp add: NSLIMSEQ_def starfun_pow)\n    ultimately have \"hypreal_of_real x pow N \\<approx> hypreal_of_real L * hypreal_of_real x\"\n      by (simp add: approx_mult_subst_star_of hyperpow_add)\n    then have \"hypreal_of_real L \\<approx> hypreal_of_real L * hypreal_of_real x\"\n      using L approx_trans3 by blast\n    then show ?thesis\n      by (metis L \\<open>x < 1\\<close> hyperpow_def less_irrefl mult.right_neutral mult_left_cancel star_of_approx_iff star_of_mult star_of_simps(9) starfun2_star_of)\n  qed\n  with assms show ?thesis\n    by (force dest!: convergent_realpow simp add: NSLIMSEQ_def convergent_NSconvergent_iff)\nqed\n\nlemma NSLIMSEQ_abs_realpow_zero: \"\\<bar>c\\<bar> < 1 \\<Longrightarrow> (\\<lambda>n. \\<bar>c\\<bar> ^ n) \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S 0\"\n  for c :: real\n  by (simp add: LIMSEQ_abs_realpow_zero LIMSEQ_NSLIMSEQ_iff [symmetric])\n\nlemma NSLIMSEQ_abs_realpow_zero2: \"\\<bar>c\\<bar> < 1 \\<Longrightarrow> (\\<lambda>n. c ^ n) \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S 0\"\n  for c :: real\n  by (simp add: LIMSEQ_abs_realpow_zero2 LIMSEQ_NSLIMSEQ_iff [symmetric])\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/Nonstandard_Analysis/HSEQ.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8902942290328345, "lm_q2_score": 0.8267117898012104, "lm_q1q2_score": 0.7360167355334234}}
{"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_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/TIP15/TIP15/TIP_sort_BubSortSorts.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942203004186, "lm_q2_score": 0.8267117940706734, "lm_q1q2_score": 0.7360167321153104}}
{"text": "theory Short_Theory_AExp\n  imports Main\nbegin\n\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) _ = 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\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 = 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\\<^sub>1 a\\<^sub>2 = Times a\\<^sub>1 a\\<^sub>2\"\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  \"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)\"\n\nlemma \"aval (asimp_const a) s = aval a s\"\n  apply (induction a)\n    apply (auto split: aexp.split)\n  done\n\nlemma aval_plus: \"aval (plus a\\<^sub>1 a\\<^sub>2) s = aval a\\<^sub>1 s + aval a\\<^sub>2 s\"\n  apply (induction a\\<^sub>1 a\\<^sub>2 rule: plus.induct)\n              apply auto\n  done\n\nlemma aval_times: \"aval (times a\\<^sub>1 a\\<^sub>2) s = aval a\\<^sub>1 s * aval a\\<^sub>2 s\"\n  apply (induction a\\<^sub>1 a\\<^sub>2 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 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\nlemma aval_asimp [simp]: \"aval (asimp a) s = aval a s\"\n  apply (induction a)\n    apply (auto simp add: aval_plus aval_times)\n  done\n\nend", "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/Short_Theory_AExp.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942261220292, "lm_q2_score": 0.8267117855317474, "lm_q1q2_score": 0.7360167293259481}}
{"text": "  (*\n    Title: Generalizations.thy\n    Author: Jose Divas\u00f3n <jose.divasonm at unirioja.es>\n    Author: Jes\u00fas Aransay <jesus-maria.aransay at unirioja.es>\n  *)\n\nheader{*Generalizations*}\n\ntheory Generalizations\nimports\n  \"~~/src/HOL/Multivariate_Analysis/Multivariate_Analysis\"\nbegin\n\nsubsection{*Generalization of parts of the HMA library*}\n\ntext{*In this file, some parts of the Multivariate Analysis library required for our\nformalizations of both the Rank Nullity Theorem and the Gauss-Jordan algorithm are generalized.\n\nMainly, we have carried out four kinds of generalizations:\n\\begin{enumerate}\n\\item Lemmas involving real vector spaces (that is, lemmas that used the @{text \"real_vector\"} \n  class) are now generalized to vector spaces over any field.\n\\item Some lemmas involving euclidean spaces (the @{text \"euclidean_space\"} class) have been \n  generalized to finite dimensional vector spaces.\n\\item Lemmas involving real matrices have been generalized to matrices over any field.\n\\item Lemmas about determinants involving the class @{text \"linordered_idom\"}, such as the lemma \n  @{text \"det_identical_columns\"}, are now proven using the class @{text \"comm_ring_1\"}.\n\\end{enumerate}\n*}\n\nhide_const (open) span\nhide_const (open) dependent\nhide_const (open) independent\nhide_const (open) dim\n\ninterpretation vec: vector_space \"op *s :: 'a::field => 'a^'b => 'a^'b\"\n  by (unfold_locales, simp_all)\n\n(*A linear map is a mapping between the elements of two vector spaces over same field*)\n(*A linear form is a mapping between a vector space and the field of its scalars*)\n\n(******************* Generalized parts of the file Real_Vector_Space.thy *******************)\n\nlocale linear = B: vector_space scaleB + C: vector_space scaleC\n  for scaleB :: \"('a::field => 'b::ab_group_add => 'b)\" (infixr \"*b\" 75)\n  and scaleC :: \"('a => 'c::ab_group_add => 'c)\" (infixr \"*c\" 75) +\n  fixes f :: \"('b=>'c)\"\n  assumes cmult: \"f (r *b x) = r *c (f x)\"\n  and add: \"f (a + b) = f a + f b\"\nbegin\n(***************** Here ends the generalization of Real_Vector_Space.thy *****************)\n\n(******************* Generalized parts of the file Linear_Algebra.thy *******************)\n\nlemma linear_0: \"f 0 = 0\"\n  by (metis add eq_add_iff)\n\nlemma linear_cmul: \"f (c *b x) = c *c (f x)\" \n  by (metis cmult)\n  \nlemma linear_neg: \"f (- x) = - f x\"\n  using linear_cmul [where c=\"-1\"]\n    by (metis add add_eq_0_iff linear_0)\n\nlemma linear_add: \"f (x + y) = f x + f y\"\n  by (metis add)\n\nlemma linear_sub: \"f (x - y) = f x - f y\"\n  by (metis ab_add_uminus_conv_diff linear_add linear_neg)  \n\nlemma linear_setsum:\n  assumes fin: \"finite S\"\n  shows \"f (setsum g S) = setsum (f \\<circ> g) S\"\n  using fin\nproof induct\n  case empty\n  then show ?case\n    by (simp add: linear_0)\nnext\n  case (insert x F)\n  have \"f (setsum g (insert x F)) = f (g x + setsum g F)\"\n    using insert.hyps by simp\n  also have \"\\<dots> = f (g x) + f (setsum g F)\"\n    using linear_add by simp\n  also have \"\\<dots> = setsum (f \\<circ> g) (insert x F)\"\n    using insert.hyps by simp\n  finally show ?case .\nqed\n\n\nlemma linear_setsum_mul:\n  assumes fin: \"finite S\"\n  shows \"f (setsum (\\<lambda>i. c i *b v i) S) = setsum (\\<lambda>i. c i *c f (v i)) S\"\n  using linear_setsum[OF fin] linear_cmul\n  by simp\n\n\nlemma linear_injective_0:\n  shows \"inj f \\<longleftrightarrow> (\\<forall>x. f x = 0 \\<longrightarrow> x = 0)\"\nproof -\n  have \"inj f \\<longleftrightarrow> (\\<forall> x y. f x = f y \\<longrightarrow> x = y)\"\n    by (simp add: inj_on_def)\n  also have \"\\<dots> \\<longleftrightarrow> (\\<forall> x y. f x - f y = 0 \\<longrightarrow> x - y = 0)\"\n    by simp\n  also have \"\\<dots> \\<longleftrightarrow> (\\<forall> x y. f (x - y) = 0 \\<longrightarrow> x - y = 0)\"\n    by (simp add: linear_sub)\n  also have \"\\<dots> \\<longleftrightarrow> (\\<forall> x. f x = 0 \\<longrightarrow> x = 0)\"\n    by auto\n  finally show ?thesis .\nqed\n\nend\n\nlemma linear_iff:\n  \"linear scaleB scaleC  f \\<longleftrightarrow> (vector_space scaleB) \\<and> (vector_space scaleC) \n    \\<and> (\\<forall>x y. f (x + y) = f x + f y) \\<and> (\\<forall>c x. f (scaleB c x) = scaleC c (f x))\"\n  (is \"linear scaleB scaleC  f \\<longleftrightarrow> ?rhs\")\nproof\n  assume lf: \"linear scaleB scaleC f\" then interpret f: linear  scaleB scaleC  f .\n  have B: \"vector_space scaleB\" using lf unfolding linear_def by simp\n  moreover have C: \"vector_space scaleC\" using lf unfolding linear_def by simp\n  ultimately show \"?rhs\" using f.linear_add f.linear_cmul by simp\nnext\n  assume \"?rhs\" then show \"linear scaleB scaleC  f\" \n    by (unfold_locales, auto simp add: vector_space.scale_right_distrib\n    vector_space.scale_left_distrib vector_space.scale_scale vector_space.scale_one)\nqed\n\n(*This lemma doesn't appear in the file Linear_Algebra.thy, but it's useful in my case.*)\nlemma linear_iff2:\n  \"linear (op *s) (op *s)  f \\<longleftrightarrow> (\\<forall>x y. f (x + y) = f x + f y) \\<and> (\\<forall>c x. f (c *s x) = c *s (f x))\"\n  (is \"linear (op *s) (op *s)  f \\<longleftrightarrow> ?rhs\")\nproof\n  assume \"linear  (op *s) (op *s) f\" then interpret f: linear  \"(op *s)\" \"(op *s)\" f .\n  show \"?rhs\" by (metis f.linear_add f.linear_cmul)\nnext\n  assume \"?rhs\" then show \"linear (op *s) (op *s) f\" by (unfold_locales,auto)\nqed\n\nlemma linear_compose_sub: \"linear scale scaleC f \\<Longrightarrow> linear scale scaleC g \\<Longrightarrow> linear scale scaleC (\\<lambda>x. f x - g x)\"\n  unfolding linear_iff\n  by (simp add: vector_space.scale_right_diff_distrib)\n    \nlemma linear_compose: \"linear scale scaleC f \\<Longrightarrow> linear scaleC scaleT  g \\<Longrightarrow> linear scale scaleT  (g o f)\"\n  unfolding linear_iff by auto\n    \ncontext vector_space\nbegin\n\nlemma linear_id: \"linear scale scale id\"\n by (simp add: linear_iff, unfold_locales)\n\n(*This lemma doesn't appear in the file Linear_Algebra.thy, but it's useful for my formalization.*)\nlemma scale_minus1_left[simp]:\n  shows \"scale (-1) x = - x\"\n  using scale_minus_left [of 1 x] by simp\n\ndefinition subspace :: \"'b set \\<Rightarrow> bool\"\n  where \"subspace S \\<longleftrightarrow> 0 \\<in> S \\<and> (\\<forall>x\\<in> S. \\<forall>y \\<in>S. x + y \\<in> S) \\<and> (\\<forall>c. \\<forall>x \\<in>S. scale c x \\<in>S )\"  \ndefinition \"span (S::'b set) = (subspace hull S)\"\ndefinition \"dependent S \\<longleftrightarrow> (\\<exists>a \\<in> S. a \\<in> span (S - {a}))\"\nabbreviation\"independent s \\<equiv> \\<not> dependent s\"\n\ntext {* Closure properties of subspaces.*}\n\nlemma subspace_UNIV[simp]: \"subspace UNIV\"\n  by (simp add: subspace_def)\n\nlemma subspace_0: \"subspace S \\<Longrightarrow> 0 \\<in> S\"\n  by (metis subspace_def)\n\nlemma subspace_add: \"subspace S \\<Longrightarrow> x \\<in> S \\<Longrightarrow> y \\<in> S \\<Longrightarrow> x + y \\<in> S\"\n  by (metis subspace_def)\n\nlemma  subspace_mul: \"subspace S \\<Longrightarrow> x \\<in> S \\<Longrightarrow> scale c x \\<in> S\"\n  by (metis subspace_def)\n\nlemma subspace_neg: \"subspace S \\<Longrightarrow> x \\<in> S \\<Longrightarrow> - x \\<in> S\" \nby (metis scale_minus_left scale_one subspace_mul)\n\nlemma subspace_sub: \"subspace S \\<Longrightarrow> x \\<in> S \\<Longrightarrow> y \\<in> S \\<Longrightarrow> x - y \\<in> S\"\n  by (metis ab_add_uminus_conv_diff subspace_add subspace_neg)\n  \nlemma subspace_setsum:\n  assumes sA: \"subspace A\"\n    and fB: \"finite B\"\n    and f: \"\\<forall>x\\<in> B. f x \\<in> A\"\n  shows \"setsum f B \\<in> A\"\n  using  fB f sA\n  by (induct rule: finite_induct[OF fB])\n    (simp add: subspace_def sA, auto simp add: sA subspace_add)\n      \nlemma subspace_linear_image:\n  assumes lf: \"linear scale scaleC f\"\n    and sS: \"subspace S\"\n  shows \"vector_space.subspace scaleC (f ` S)\"\nproof -\ninterpret lf: linear scale scaleC f using lf by simp\nhave C: \"vector_space scaleC\"  using lf unfolding linear_def by simp\nshow ?thesis\n  proof (unfold vector_space.subspace_def[OF C], auto)\n    show \" 0 \\<in> f ` S\"\n      by (metis (full_types) image_eqI lf.linear_0 sS subspace_0)\n   fix x y assume x: \"x \\<in> S\" and y: \"y \\<in> S\"\n   show \"f x + f y \\<in> f ` S\"  unfolding image_iff\n    apply (rule_tac x=\"x + y\" in bexI) using lf.add subspace_add[OF sS x y] by auto\n   fix c\n   show \"scaleC c (f x) \\<in> f ` S\" by (metis imageI subspace_mul lf.linear_cmul sS x)\n  qed\nqed\n\nlemma subspace_linear_vimage: \n  assumes lf: \"linear scale scaleC (f::'b::ab_group_add=>'c::ab_group_add)\"\n  and s: \"vector_space.subspace scaleC S\"\n  shows \"subspace (f -` S)\"\n  proof -\n  interpret lf: linear scale scaleC f using lf by simp\n  have C: \"vector_space scaleC\" using lf by (unfold_locales)\n  show ?thesis\n    unfolding subspace_def\n      apply (auto)\n      apply (metis lf.C.subspace_0 lf.linear_0 s)\n      apply (metis (full_types) lf.C.subspace_def lf.linear_add s)\n      by (metis lf.C.subspace_mul lf.linear_cmul s)\nqed\n\nlemma subspace_Times:\nassumes A: \"subspace A\" and B: \"subspace B\"\nshows \"vector_space.subspace (\\<lambda>x (a,b). (scale x a, scale x b)) (A \\<times> B)\"\nproof -\nhave v: \"vector_space (\\<lambda>x (a,b). (scale x a, scale x b))\"\n  unfolding vector_space_def\n  by (simp add: scale_left_distrib scale_right_distrib)\nshow ?thesis\n  using A B unfolding subspace_def\n  unfolding vector_space.subspace_def[OF v] zero_prod_def by auto\nqed\n\n(*This lemma doesn't appear in the file Linear_Algebra.thy, but it's useful for my formalization.*)\nlemma vector_space_product: \"vector_space (\\<lambda>x (a, b). (scale x a, scale x b))\"\n  by (unfold_locales, auto simp: scale_right_distrib scale_left_distrib)\n\ntext {* Properties of span. *}  \n  \nlemma  span_mono: \"A \\<subseteq> B \\<Longrightarrow> span A \\<subseteq> span B\"\n  by (metis span_def hull_mono)  \n  \nlemma subspace_span: \"subspace (span S)\"\n  unfolding span_def\n  apply (rule hull_in)\n  apply (simp only: subspace_def Inter_iff Int_iff subset_eq)\n  apply auto\n  done\n  \n  \nlemma span_clauses:\n  \"a \\<in> S ==> a \\<in> span S\"\n  \"0 \\<in> span S\"\n  \"x\\<in> span S ==> y \\<in> span S ==> x + y \\<in> span S\"\n  \"x \\<in> span S ==> scale c x \\<in> span S\"\n  by (metis span_def hull_subset subset_eq) (metis subspace_span subspace_def)+\n  \nlemma span_unique:\n  \"S \\<subseteq> T ==> subspace T ==> (!!T'. S \\<subseteq> T' ==> subspace T' ==> T \\<subseteq> T') ==> span S = T\"\n  unfolding span_def by (rule hull_unique)\n  \n  \nlemma span_minimal: \"S \\<subseteq> T ==> subspace T ==> span S \\<subseteq> T\"\n  unfolding span_def by (rule hull_minimal)\n\nlemma span_induct:\n  assumes x: \"x \\<in> span S\"\n    and P: \"subspace P\"\n    and SP: \"!!x. x \\<in> S ==> x \\<in> P\"\n  shows \"x \\<in> P\"\nproof -\n  from SP have SP': \"S \\<subseteq> P\"\n    by (simp add: subset_eq)\n  from x hull_minimal[where S=subspace, OF SP' P, unfolded span_def[symmetric]]\n  show \"x \\<in> P\"\n    by (metis subset_eq)\nqed\n\nlemma span_empty[simp]: \"span {} = {0}\"\n  apply (simp add: span_def)\n  apply (rule hull_unique)\n  apply (auto simp add: subspace_def)\n  done\n\n  \nlemma  independent_empty[intro]: \"independent {}\"\n  by (simp add: dependent_def)\n\nlemma dependent_single[simp]: \"dependent {x} <-> x = 0\"\n  unfolding dependent_def by auto\n\nlemma  independent_mono: \"independent A ==> B \\<subseteq> A ==> independent B\"\n  apply (clarsimp simp add: dependent_def span_mono)\n  apply (subgoal_tac \"span (B - {a}) \\<le> span (A - {a})\")\n  apply force\n  apply (rule span_mono)\n  apply auto\n  done\n\nlemma span_subspace: \"A \\<subseteq> B ==> B \\<le> span A ==>  subspace B ==> span A = B\"\n  by (metis order_antisym span_def hull_minimal) \n  \n  \nlemma span_induct':\n  assumes SP: \"\\<forall>x \\<in> S. P x\"\n    and P: \"subspace {x. P x}\"\n  shows \"\\<forall>x \\<in> span S. P x\"\n  using span_induct SP P by blast\n\ninductive_set  span_induct_alt_help for S:: \"'b set\"\nwhere\n  span_induct_alt_help_0: \"0 \\<in> span_induct_alt_help S\"\n| span_induct_alt_help_S:\n    \"x \\<in> S ==> z \\<in> span_induct_alt_help S ==>\n      (scale c x + z) \\<in> span_induct_alt_help S\"\n\nlemma span_induct_alt':\n  assumes h0: \"h 0\"\n    and hS: \"!!c x y. x \\<in> S ==> h y ==> h (scale c x + y)\"\n  shows \"\\<forall>x \\<in> span S. h x\"\nproof -\n  {\n    fix x :: 'b\n    assume x: \"x \\<in> span_induct_alt_help S\"\n    have \"h x\"\n      apply (rule span_induct_alt_help.induct[OF x])\n      apply (rule h0)\n      apply (rule hS)\n      apply assumption\n      apply assumption\n      done\n  }\n  note th0 = this\n  {\n    fix x\n    assume x: \"x \\<in> span S\"\n    have \"x \\<in> span_induct_alt_help S\"\n    proof (rule span_induct[where x=x and S=S])\n      show \"x \\<in> span S\" by (rule x)\n    next\n      fix x\n      assume xS: \"x \\<in> S\"\n      from span_induct_alt_help_S[OF xS span_induct_alt_help_0, of 1]\n      show \"x \\<in> span_induct_alt_help S\"\n        by simp\n    next\n      have \"0 \\<in> span_induct_alt_help S\" by (rule span_induct_alt_help_0)\n      moreover\n      {\n        fix x y\n        assume h: \"x \\<in> span_induct_alt_help S\" \"y \\<in> span_induct_alt_help S\"\n        from h have \"(x + y) \\<in> span_induct_alt_help S\"\n          apply (induct rule: span_induct_alt_help.induct)\n          apply simp\n          unfolding add.assoc\n          apply (rule span_induct_alt_help_S)\n          apply assumption\n          apply simp\n          done\n      }\n      moreover\n      {\n        fix c x\n        assume xt: \"x \\<in> span_induct_alt_help S\"\n        then have \"(scale c x) \\<in> span_induct_alt_help S\"\n          apply (induct rule: span_induct_alt_help.induct)\n          apply (simp add: span_induct_alt_help_0)\n          apply (simp add: scale_right_distrib)\n          apply (rule span_induct_alt_help_S)\n          apply assumption\n          apply simp\n          done }\n      ultimately show \"subspace (span_induct_alt_help S)\"\n        unfolding subspace_def Ball_def by blast\n    qed\n  }\n  with th0 show ?thesis by blast\nqed\n\nlemma span_induct_alt:\n  assumes h0: \"h 0\"\n    and hS: \"!!c x y. x \\<in> S ==> h y ==> h (scale c x + y)\"\n    and x: \"x \\<in> span S\"\n  shows \"h x\"\n  using span_induct_alt'[of h S] h0 hS x by blast\n  \ntext {* Individual closure properties. *}\n\nlemma span_span: \"span (span A) = span A\"\n  unfolding span_def hull_hull ..\n\nlemma span_superset: \"x \\<in> S ==> x \\<in> span S\"\n  by (metis span_clauses(1))\n\nlemma  span_0: \"0 \\<in> span S\"\n  by (metis span_clauses(2))\n\nlemma span_inc: \"S \\<subseteq> span S\"\n  by (metis subset_eq span_superset)\n\nlemma dependent_0:\n  assumes \"0 \\<in> A\"\n  shows \"dependent A\"\n  unfolding dependent_def\n  apply (rule_tac x=0 in bexI)\n  using assms span_0\n  apply auto\n  done\n\nlemma span_add: \"x \\<in> span S ==> y \\<in> span S ==> x + y \\<in> span S\"\n  by (metis subspace_add subspace_span)\n\nlemma span_mul: \"x \\<in> span S ==> scale c x \\<in> span S\"\n  by (metis span_clauses(4))\n\nlemma span_neg: \"x \\<in> span S ==> - x \\<in> span S\"\n  by (metis subspace_neg subspace_span)\n\nlemma span_sub: \"x \\<in> span S ==> y \\<in> span S ==> x - y \\<in> span S\"\n  by (metis subspace_span subspace_sub)\n\nlemma span_setsum: \"finite A ==> \\<forall>x \\<in> A. f x \\<in> span S ==> setsum f A \\<in> span S\"\n  by (rule subspace_setsum, rule subspace_span)\n\nlemma span_add_eq: \"x \\<in> span S ==> x + y \\<in> span S <-> y \\<in> span S\"\n  apply (auto simp only: span_add span_sub)\n  apply (subgoal_tac \"(x + y) - x \\<in> span S\")\n  apply simp\n  apply (simp only: span_add span_sub)\n  done\n  \n\nlemma span_linear_image:\n  assumes lf: \"linear scale scaleC (f::'b::ab_group_add=>'c::ab_group_add)\"\n  shows \"vector_space.span scaleC (f ` S) = f ` (span S)\" \nproof -\ninterpret B: vector_space scale using lf by (metis linear_iff)\ninterpret C: vector_space scaleC using lf by (metis linear_iff)\ninterpret lf: linear scale scaleC f using lf by simp\nshow ?thesis\nproof (rule C.span_unique)\n  show \"f ` S \\<subseteq> f ` span S\" \n    by (rule image_mono, rule span_inc)\n  show \"vector_space.subspace scaleC (f ` span S)\"\n    using lf subspace_span by (rule subspace_linear_image)\nnext\n  fix T\n  assume \"f ` S \\<subseteq> T\" and \"vector_space.subspace scaleC T\"\n  then show \"f ` span S \\<subseteq> T\"\n    unfolding image_subset_iff_subset_vimage\n    by (metis subspace_linear_vimage lf span_minimal)\nqed\nqed\n\nlemma span_union: \"span (A \\<union> B) = (\\<lambda>(a, b). a + b) ` (span A \\<times> span B)\"\nproof (rule span_unique)\n  show \"A \\<union> B \\<subseteq> (\\<lambda>(a, b). a + b) ` (span A \\<times> span B)\"\n    by safe (force intro: span_clauses)+\nnext   \n  have \"linear (\\<lambda>x (a,b). (scale x a, scale x b)) scale (\\<lambda>(a, b). a + b)\"\n    proof (unfold linear_def linear_axioms_def, auto)\n        show \"vector_space (\\<lambda>x (a, b). (scale x a, scale x b))\" using vector_space_product .\n        show \"vector_space scale\" by (unfold_locales)\n        show \"\\<And>r a b. scale r a + scale r b = scale r (a + b)\" by (metis scale_right_distrib)\n    qed\n  moreover have \"vector_space.subspace (\\<lambda>x (a,b). (scale x a, scale x b))  (span A \\<times> span B)\"\n    by (intro subspace_Times subspace_span)\n  ultimately show \"subspace ((\\<lambda>(a, b). a + b) ` (span A \\<times> span B))\"\n    by (metis (lifting) linear_iff vector_space.subspace_linear_image)\nnext\n  fix T\n  assume \"A \\<union> B \\<subseteq> T\" and \"subspace T\"\n  then show \"(\\<lambda>(a, b). a + b) ` (span A \\<times> span B) \\<subseteq> T\"\n    by (auto intro!: subspace_add elim: span_induct)\nqed\n\n\nlemma span_singleton: \"span {x} = range (\\<lambda>k. scale k x)\"\nproof (rule span_unique)\n  show \"{x} \\<subseteq> range (\\<lambda>k. scale k x)\"\n    by (fast intro: scale_one [symmetric])\n  show \"subspace (range (\\<lambda>k. scale k x))\"\n    unfolding subspace_def\n    by (auto intro: scale_left_distrib [symmetric])\nnext\n  fix T\n  assume \"{x} \\<subseteq> T\" and \"subspace T\"\n  then show \"range (\\<lambda>k. scale k x) \\<subseteq> T\"\n    unfolding subspace_def by auto\nqed\n\nlemma span_insert: \"span (insert a S) = {x. \\<exists>k. (x - scale k a) \\<in> span S}\"\nproof -\n  have \"span ({a} \\<union> S) = {x. \\<exists>k. (x - scale k a) \\<in> span S}\"\n    unfolding span_union span_singleton\n    apply safe\n    apply (rule_tac x=k in exI, simp)\n    apply (erule rev_image_eqI [OF SigmaI [OF rangeI]])\n    apply auto\n    done\n  then show ?thesis by simp\nqed\n\n\nlemma span_breakdown:\n  assumes bS: \"b \\<in> S\"\n    and aS: \"a \\<in> span S\"\n  shows \"\\<exists>k. a - scale k b \\<in> span (S - {b})\"\n  using assms span_insert [of b \"S - {b}\"]\n  by (simp add: insert_absorb)\n\nlemma span_breakdown_eq: \"x \\<in> span (insert a S) \\<longleftrightarrow> (\\<exists>k. x - scale k a \\<in> span S)\"\n  by (simp add: span_insert)\n  \nlemma in_span_insert:\n  assumes a: \"a \\<in> span (insert b S)\"\n    and na: \"a \\<notin> span S\"\n  shows \"b \\<in> span (insert a S)\"\nproof -\n  from span_breakdown[of b \"insert b S\" a, OF insertI1 a]\n  obtain k where k: \"a - scale k b \\<in> span (S - {b})\" by auto\n  show ?thesis\n  proof (cases \"k = 0\")\n    case True\n    with k have \"a \\<in> span S\"\n      apply (simp)\n      apply (rule set_rev_mp)\n      apply assumption\n      apply (rule span_mono)\n      apply blast\n      done\n    with na show ?thesis by blast\n  next\n    case False\n    have eq: \"b = scale (1/k) a - (scale (1/k) a - b)\" by simp\n    from False have eq': \"scale (1/k) (a - scale k b) = scale (1/k) a - b\"\n      by (simp add: algebra_simps)\n    from k have \"scale (1/k) (a - scale k b) \\<in> span (S - {b})\"\n      by (rule span_mul)\n    then have th: \"scale (1/k) a - b \\<in> span (S - {b})\"\n      unfolding eq' .\n    from k show ?thesis\n      apply (subst eq)\n      apply (rule span_sub)\n      apply (rule span_mul)\n      apply (rule span_superset)\n      apply blast\n      apply (rule set_rev_mp)\n      apply (rule th)\n      apply (rule span_mono)\n      using na\n      apply blast\n      done\n  qed\nqed\n\n\n\nlemma in_span_delete:\n  assumes a: \"a \\<in> span S\"\n    and na: \"a \\<notin> span (S - {b})\"\n  shows \"b \\<in> span (insert a (S - {b}))\"\n  apply (rule in_span_insert)\n  apply (rule set_rev_mp)\n  apply (rule a)\n  apply (rule span_mono)\n  apply blast\n  apply (rule na)\n  done\n  \n  \nlemma span_redundant: \"x \\<in> span S \\<Longrightarrow> span (insert x S) = span S\"\n  unfolding span_def by (rule hull_redundant)\n\nlemma span_trans:\n  assumes x: \"x \\<in> span S\"\n    and y: \"y \\<in> span (insert x S)\"\n  shows \"y \\<in> span S\"\n  using assms by (simp only: span_redundant)\n  \nlemma span_insert_0[simp]: \"span (insert 0 S) = span S\"\n  by (metis span_0 span_redundant)\n\nlemma span_explicit:\n  \"span  P = {y. \\<exists>S u. finite S \\<and> S \\<subseteq> P \\<and> setsum (\\<lambda>v. scale (u v) v) S = y}\"\n  (is \"_ = ?E\" is \"_ = {y. ?h y}\" is \"_ = {y. \\<exists>S u. ?Q S u y}\")\n  proof -\n  {\n    fix x\n    assume x: \"x \\<in> ?E\"\n    then obtain S u where fS: \"finite S\" and SP: \"S\\<subseteq>P\" and u: \"setsum (\\<lambda>v. scale (u v) v) S = x\"\n      by blast\n    have \"x \\<in> span P\"\n      unfolding u[symmetric]\n      apply (rule span_setsum[OF fS])\n      using span_mono[OF SP]\n      apply (auto intro: span_superset span_mul)\n      done\n  }\n  moreover\n  have \"\\<forall>x \\<in> span P. x \\<in> ?E\"\n  proof (rule span_induct_alt')\n    show \"0 \\<in> Collect ?h\"\n      unfolding mem_Collect_eq\n      apply (rule exI[where x=\"{}\"])\n      apply simp\n      done\n  next\n    fix c x y\n    assume x: \"x \\<in> P\"\n    assume hy: \"y \\<in> Collect ?h\"\n    from hy obtain S u where fS: \"finite S\" and SP: \"S\\<subseteq>P\"\n      and u: \"setsum (\\<lambda>v. scale (u v) v) S = y\" by blast\n    let ?S = \"insert x S\"\n    let ?u = \"\\<lambda>y. if y = x then (if x \\<in> S then u y + c else c) else u y\"\n    from fS SP x have th0: \"finite (insert x S)\" \"insert x S \\<subseteq> P\"\n      by blast+\n    have \"?Q ?S ?u (scale c x + y)\"\n    proof cases\n      assume xS: \"x \\<in> S\"\n      have S1: \"S = (S - {x}) \\<union> {x}\"\n        and Sss:\"finite (S - {x})\" \"finite {x}\" \"(S - {x}) \\<inter> {x} = {}\"\n        using xS fS by auto\n      have \"setsum (\\<lambda>v. scale (?u v) v) ?S =(\\<Sum>v\\<in>S - {x}.  scale (?u v) v) + scale (u x + c) x\"\n        using xS by (simp add: setsum.remove [OF fS xS] insert_absorb)\n      also have \"\\<dots> = (\\<Sum>v\\<in>S. scale (u v) v) + scale c x\"\n        by (simp add: setsum.remove [OF fS xS] algebra_simps)\n      also have \"\\<dots> = scale c x + y\"\n        by (simp add: add.commute u)\n      finally have \"setsum (\\<lambda>v. scale (?u v) v) ?S = scale c x + y\" .\n      then show ?thesis using th0 by blast\n    next\n      assume xS: \"x \\<notin> S\"\n      have th00: \"(\\<Sum>v\\<in>S. scale (if v = x then c else u v) v) = y\"\n        unfolding u[symmetric]\n        apply (rule setsum.cong)\n        using xS\n        apply auto\n        done\n      show ?thesis using fS xS th0\n        by (simp add: th00 setsum_clauses add.commute cong del: if_weak_cong)\n    qed\n    then show \"(scale c x + y) \\<in> Collect ?h\"\n      unfolding mem_Collect_eq\n      apply -\n      apply (rule exI[where x=\"?S\"])\n      apply (rule exI[where x=\"?u\"])\n      apply metis\n      done\n  qed\n  ultimately show ?thesis by blast\nqed\n\n\nlemma dependent_explicit:\n  \"dependent P \\<longleftrightarrow> (\\<exists>S u. finite S \\<and> S \\<subseteq> P \\<and> (\\<exists>v\\<in>S. u v \\<noteq> 0 \\<and> setsum (\\<lambda>v. scale (u v) v) S = 0))\"\n  (is \"?lhs = ?rhs\")\n  proof -\n  {\n    assume dP: \"dependent P\"\n    then obtain a S u where aP: \"a \\<in> P\" and fS: \"finite S\"\n      and SP: \"S \\<subseteq> P - {a}\" and ua: \"setsum (\\<lambda>v. scale (u v) v) S = a\"\n      unfolding dependent_def span_explicit by blast\n    let ?S = \"insert a S\"\n    let ?u = \"\\<lambda>y. if y = a then - 1 else u y\"\n    let ?v = a\n    from aP SP have aS: \"a \\<notin> S\"\n      by blast\n    from fS SP aP have th0: \"finite ?S\" \"?S \\<subseteq> P\" \"?v \\<in> ?S\" \"?u ?v \\<noteq> 0\" by auto\n    have s0: \"setsum (\\<lambda>v. scale (?u v) v) ?S = 0\"\n      using fS aS\n      apply (simp add: setsum_clauses field_simps)\n      apply (subst (2) ua[symmetric])\n      apply (rule setsum.cong)\n      apply auto\n      done\n    with th0 have ?rhs by fast\n  }\n  moreover\n  {\n    fix S u v\n    assume fS: \"finite S\"\n      and SP: \"S \\<subseteq> P\"\n      and vS: \"v \\<in> S\"\n      and uv: \"u v \\<noteq> 0\"\n      and u: \"setsum (\\<lambda>v. scale (u v) v) S = 0\"\n    let ?a = v\n    let ?S = \"S - {v}\"\n    let ?u = \"\\<lambda>i. (- u i) / u v\"\n    have th0: \"?a \\<in> P\" \"finite ?S\" \"?S \\<subseteq> P\"\n      using fS SP vS by auto\n    have \"setsum (\\<lambda>v. scale (?u v) v) ?S =\n      setsum (\\<lambda>v. scale (- (inverse (u ?a))) (scale (u v) v)) S - scale (?u v) v\" \n      using fS vS uv by (simp add: setsum_diff1 field_simps)   \n    also have \"\\<dots> = ?a\" \n      unfolding scale_setsum_right[symmetric] u using uv by simp\n    finally have \"setsum (\\<lambda>v. scale (?u v) v) ?S = ?a\" .\n    with th0 have ?lhs\n      unfolding dependent_def span_explicit\n      apply -\n      apply (rule bexI[where x= \"?a\"])\n      apply (simp_all del: scale_minus_left)\n      apply (rule exI[where x= \"?S\"])\n      apply (auto simp del: scale_minus_left)\n      done\n  }\n  ultimately show ?thesis by blast\nqed\n\n\n\nlemma span_finite:\n  assumes fS: \"finite S\"\n  shows \"span S = {y. \\<exists>u. setsum (\\<lambda>v. scale (u v)  v) S = y}\"\n  (is \"_ = ?rhs\")\nproof -\n  {\n    fix y\n    assume y: \"y \\<in> span S\"\n    from y obtain S' u where fS': \"finite S'\"\n      and SS': \"S' \\<subseteq> S\"\n      and u: \"setsum (\\<lambda>v. scale (u v)v) S' = y\"\n      unfolding span_explicit by blast\n    let ?u = \"\\<lambda>x. if x \\<in> S' then u x else 0\"\n    have \"setsum (\\<lambda>v. scale (?u v) v) S = setsum (\\<lambda>v. scale (u v) v) S'\"\n      using SS' fS by (auto intro!: setsum.mono_neutral_cong_right)\n    then have \"setsum (\\<lambda>v. scale (?u v) v) S = y\" by (metis u)\n    then have \"y \\<in> ?rhs\" by auto\n  }\n  moreover\n  {\n    fix y u\n    assume u: \"setsum (\\<lambda>v. scale (u v) v) S = y\"\n    then have \"y \\<in> span S\" using fS unfolding span_explicit by auto\n  }\n  ultimately show ?thesis by blast\nqed\n\n\nlemma independent_insert:\n  \"independent (insert a S) \\<longleftrightarrow>\n    (if a \\<in> S then independent S else independent S \\<and> a \\<notin> span S)\"\n  (is \"?lhs \\<longleftrightarrow> ?rhs\")\nproof (cases \"a \\<in> S\")\n  case True\n  then show ?thesis\n    using insert_absorb[OF True] by simp\nnext\n  case False\n  show ?thesis\n  proof\n    assume i: ?lhs\n    then show ?rhs\n      using False\n      apply simp\n      apply (rule conjI)\n      apply (rule independent_mono)\n      apply assumption\n      apply blast\n      apply (simp add: dependent_def)\n      done\n  next\n    assume i: ?rhs\n    show ?lhs\n      using i False\n      apply simp\n      apply (auto simp add: dependent_def)\n      apply (case_tac \"aa = a\")\n      apply auto\n      apply (subgoal_tac \"insert a S - {aa} = insert a (S - {aa})\")\n      apply simp\n      apply (subgoal_tac \"a \\<in> span (insert aa (S - {aa}))\")\n      apply (subgoal_tac \"insert aa (S - {aa}) = S\")\n      apply simp\n      apply blast\n      apply (rule in_span_insert)\n      apply assumption\n      apply blast\n      apply blast\n      done\n  qed\nqed\n\n\nlemma spanning_subset_independent:\n  assumes BA: \"B \\<subseteq> A\"\n    and iA: \"independent A\"\n    and AsB: \"A \\<subseteq> span B\"\n  shows \"A = B\"\nproof\n  show \"B \\<subseteq> A\" by (rule BA)\n\n  from span_mono[OF BA] span_mono[OF AsB]\n  have sAB: \"span A = span B\" unfolding span_span by blast\n\n  {\n    fix x\n    assume x: \"x \\<in> A\"\n    from iA have th0: \"x \\<notin> span (A - {x})\"\n      unfolding dependent_def using x by blast\n    from x have xsA: \"x \\<in> span A\"\n      by (blast intro: span_superset)\n    have \"A - {x} \\<subseteq> A\" by blast\n    then have th1: \"span (A - {x}) \\<subseteq> span A\"\n      by (metis span_mono)\n    {\n      assume xB: \"x \\<notin> B\"\n      from xB BA have \"B \\<subseteq> A - {x}\"\n        by blast\n      then have \"span B \\<subseteq> span (A - {x})\"\n        by (metis span_mono)\n      with th1 th0 sAB have \"x \\<notin> span A\"\n        by blast\n      with x have False\n        by (metis span_superset)\n    }\n    then have \"x \\<in> B\" by blast\n  }\n  then show \"A \\<subseteq> B\" by blast\nqed\n\nlemma exchange_lemma:\n  assumes f:\"finite t\"\n  and i: \"independent s\"\n  and sp: \"s \\<subseteq> span t\"\n  shows \"\\<exists>t'. card t' = card t \\<and> finite t' \\<and> s \\<subseteq> t' \\<and> t' \\<subseteq> s \\<union> t \\<and> s \\<subseteq> span t'\"\n  using f i sp\nproof (induct \"card (t - s)\" arbitrary: s t rule: less_induct)\n  case less\n  note ft = `finite t` and s = `independent s` and sp = `s \\<subseteq> span t`\n  let ?P = \"\\<lambda>t'. card t' = card t \\<and> finite t' \\<and> s \\<subseteq> t' \\<and> t' \\<subseteq> s \\<union> t \\<and> s \\<subseteq> span t'\"\n  let ?ths = \"\\<exists>t'. ?P t'\"\n  {\n    assume st: \"s \\<subseteq> t\"\n    from st ft span_mono[OF st]\n    have ?ths\n      apply -\n      apply (rule exI[where x=t])\n      apply (auto intro: span_superset)\n      done\n  }\n  moreover\n  {\n    assume st: \"t \\<subseteq> s\"\n    from spanning_subset_independent[OF st s sp] st ft span_mono[OF st]\n    have ?ths\n      apply -\n      apply (rule exI[where x=t])\n      apply (auto intro: span_superset)\n      done\n  }\n  moreover\n  {\n    assume st: \"\\<not> s \\<subseteq> t\" \"\\<not> t \\<subseteq> s\"\n    from st(2) obtain b where b: \"b \\<in> t\" \"b \\<notin> s\"\n      by blast\n    from b have \"t - {b} - s \\<subset> t - s\"\n      by blast\n    then have cardlt: \"card (t - {b} - s) < card (t - s)\"\n      using ft by (auto intro: psubset_card_mono)\n    from b ft have ct0: \"card t \\<noteq> 0\"\n      by auto\n    have ?ths\n    proof cases\n      assume stb: \"s \\<subseteq> span (t - {b})\"\n      from ft have ftb: \"finite (t - {b})\"\n        by auto\n      from less(1)[OF cardlt ftb s stb]\n      obtain u where u: \"card u = card (t - {b})\" \"s \\<subseteq> u\" \"u \\<subseteq> s \\<union> (t - {b})\" \"s \\<subseteq> span u\"\n        and fu: \"finite u\" by blast\n      let ?w = \"insert b u\"\n      have th0: \"s \\<subseteq> insert b u\"\n        using u by blast\n      from u(3) b have \"u \\<subseteq> s \\<union> t\"\n        by blast\n      then have th1: \"insert b u \\<subseteq> s \\<union> t\"\n        using u b by blast\n      have bu: \"b \\<notin> u\"\n        using b u by blast\n      from u(1) ft b have \"card u = (card t - 1)\"\n        by auto\n      then have th2: \"card (insert b u) = card t\"\n        using card_insert_disjoint[OF fu bu] ct0 by auto\n      from u(4) have \"s \\<subseteq> span u\" .\n      also have \"\\<dots> \\<subseteq> span (insert b u)\"\n        by (rule span_mono) blast\n      finally have th3: \"s \\<subseteq> span (insert b u)\" .\n      from th0 th1 th2 th3 fu have th: \"?P ?w\"\n        by blast\n      from th show ?thesis by blast\n    next\n      assume stb: \"\\<not> s \\<subseteq> span (t - {b})\"\n      from stb obtain a where a: \"a \\<in> s\" \"a \\<notin> span (t - {b})\"\n        by blast\n      have ab: \"a \\<noteq> b\"\n        using a b by blast\n      have at: \"a \\<notin> t\"\n        using a ab span_superset[of a \"t- {b}\"] by auto\n      have mlt: \"card ((insert a (t - {b})) - s) < card (t - s)\"\n        using cardlt ft a b by auto\n      have ft': \"finite (insert a (t - {b}))\"\n        using ft by auto\n      {\n        fix x\n        assume xs: \"x \\<in> s\"\n        have t: \"t \\<subseteq> insert b (insert a (t - {b}))\"\n          using b by auto\n        from b(1) have \"b \\<in> span t\"\n          by (simp add: span_superset)\n        have bs: \"b \\<in> span (insert a (t - {b}))\"\n          apply (rule in_span_delete)\n          using a sp unfolding subset_eq\n          apply auto\n          done\n        from xs sp have \"x \\<in> span t\"\n          by blast\n        with span_mono[OF t] have x: \"x \\<in> span (insert b (insert a (t - {b})))\" ..\n        from span_trans[OF bs x] have \"x \\<in> span (insert a (t - {b}))\" .\n      }\n      then have sp': \"s \\<subseteq> span (insert a (t - {b}))\"\n        by blast\n      from less(1)[OF mlt ft' s sp'] obtain u where u:\n        \"card u = card (insert a (t - {b}))\"\n        \"finite u\" \"s \\<subseteq> u\" \"u \\<subseteq> s \\<union> insert a (t - {b})\"\n        \"s \\<subseteq> span u\" by blast\n      from u a b ft at ct0 have \"?P u\"\n        by auto\n      then show ?thesis by blast\n    qed\n  }\n  ultimately show ?ths by blast\nqed\n\nlemma independent_span_bound:\n  assumes f: \"finite t\"\n    and i: \"independent s\"\n    and sp: \"s \\<subseteq> span t\"\n  shows \"finite s \\<and> card s \\<le> card t\"\n  by (metis exchange_lemma[OF f i sp] finite_subset card_mono)\n\n\n(*The following lemmas don't appear in the library, but they are useful in my development.*)\nlemma independent_explicit:\n  \"independent A = \n  (\\<forall>S \\<subseteq> A. finite S \\<longrightarrow> (\\<forall>u. (\\<Sum>v\\<in>S. scale (u v) v) = 0 \\<longrightarrow> (\\<forall>v\\<in>S. u v = 0)))\" \n  unfolding dependent_explicit [of A] by (simp add: disj_not2)\n\ntext{*A finite set @{term \"A::'a set\"} for which\n  every of its linear combinations equal to zero \n  requires every coefficient being zero, is independent:*}  \n  \nlemma independent_if_scalars_zero:\n  assumes fin_A: \"finite A\"\n  and sum: \"\\<forall>f. (\\<Sum>x\\<in>A. scale (f x) x) = 0 \\<longrightarrow> (\\<forall>x \\<in> A. f x = 0)\"\n  shows \"independent A\"\nproof (unfold independent_explicit, clarify)\n  fix S v and u :: \"'b \\<Rightarrow> 'a\"\n  assume S: \"S \\<subseteq> A\" and v: \"v \\<in> S\" \n  let ?g = \"\\<lambda>x. if x \\<in> S then u x else 0\"\n  have \"(\\<Sum>v\\<in>A. scale (?g v) v) = (\\<Sum>v\\<in>S. scale (u v) v)\"\n    using S fin_A by (auto intro!: setsum.mono_neutral_cong_right) \n  also assume \"(\\<Sum>v\\<in>S. scale (u v) v) = 0\"\n  finally have \"?g v = 0\" using v S sum by force\n  thus \"u v = 0\"  unfolding if_P[OF v] .\nqed\nend\n\ndefinition \"cart_basis = {axis i 1 | i. i\\<in>UNIV}\"\n\nlemma finite_cart_basis: \"finite (cart_basis)\" unfolding cart_basis_def\n  using finite_Atleast_Atmost_nat by fastforce\n\nlemma independent_cart_basis:\n  \"vec.independent (cart_basis)\"\n  proof (rule vec.independent_if_scalars_zero, auto)\n  show \"finite (cart_basis)\" using finite_cart_basis .\n  fix f::\"('a, 'b) vec \\<Rightarrow> 'a\" and x::\"('a, 'b) vec\"\n  assume eq_0: \"(\\<Sum>x\\<in>cart_basis. f x *s x) = 0\" and x_in: \"x \\<in> cart_basis\"\n  obtain i where x: \"x = axis i 1\" using x_in unfolding cart_basis_def by auto\n  have setsum_eq_0: \"(\\<Sum>x\\<in>(cart_basis) - {x}. f x * (x $ i)) = 0\"\n    proof (rule setsum.neutral, rule ballI)\n      fix xa assume xa: \"xa \\<in> cart_basis - {x}\"\n      obtain a where a: \"xa = axis a 1\" and a_not_i: \"a \\<noteq> i\"\n        using xa x unfolding cart_basis_def by auto\n      have \"xa $ i = 0\" unfolding a axis_def using a_not_i by auto\n      thus \"f xa * xa $ i = 0\" by simp\n   qed    \n  have \"0 = (\\<Sum>x\\<in>cart_basis. f x *s x) $ i\" using eq_0 by simp\n  also have \"... = (\\<Sum>x\\<in>cart_basis. (f x *s x) $ i)\" unfolding setsum_component ..\n  also have \"... = (\\<Sum>x\\<in>cart_basis. f x * (x $ i))\" unfolding vector_smult_component ..\n  also have \"... = f x * (x $ i) + (\\<Sum>x\\<in>(cart_basis) - {x}. f x * (x $ i))\"\n    by (rule setsum.remove[OF finite_cart_basis x_in])\n  also have \"... =  f x * (x $ i)\" unfolding setsum_eq_0 by simp\n  also have \"... = f x\" unfolding x axis_def by auto\n  finally show \"f x = 0\" .. \nqed\n\nlemma span_cart_basis:\n  \"vec.span (cart_basis) = UNIV\"\nproof (auto)\nfix x::\"('a, 'b) vec\"\nlet ?f=\"\\<lambda>v. x $ (THE i. v = axis i 1)\"\nshow \"x \\<in> vec.span (cart_basis)\"\nproof (unfold vec.span_finite[OF finite_cart_basis], auto, rule exI[of _ ?f] , subst (2) vec_eq_iff, clarify)\nfix i::'b\nlet ?w = \"axis i (1::'a)\"\nhave the_eq_i: \"(THE a. ?w = axis a 1) = i\" \n  by (rule the_equality, auto simp: axis_eq_axis)\nhave setsum_eq_0: \"(\\<Sum>v\\<in>(cart_basis) - {?w}. x $ (THE i. v = axis i 1) * v $ i) = 0\"\n  proof (rule setsum.neutral, rule ballI)\n     fix xa::\"('a, 'b) vec\"\n     assume xa: \"xa \\<in> cart_basis - {?w}\"\n     obtain j where j: \"xa = axis j 1\" and i_not_j: \"i \\<noteq> j\" using xa unfolding cart_basis_def by auto\n     have the_eq_j: \"(THE i. xa = axis i 1) = j\"\n      proof (rule the_equality)\n         show \"xa = axis j 1\" using j .\n         show \"\\<And>i. xa = axis i 1 \\<Longrightarrow> i = j\" by (metis axis_eq_axis j zero_neq_one)\n      qed\n     show \"x $ (THE i. xa = axis i 1) * xa $ i = 0\" \n      apply (subst (2) j) \n      unfolding the_eq_j unfolding axis_def using i_not_j by simp\n   qed\nhave \"(\\<Sum>v\\<in>cart_basis. x $ (THE i. v = axis i 1) *s v) $ i = \n  (\\<Sum>v\\<in>cart_basis. (x $ (THE i. v = axis i 1) *s v) $ i)\" unfolding setsum_component ..\nalso have \"... = (\\<Sum>v\\<in>cart_basis. x $ (THE i. v = axis i 1) * v $ i)\" \n  unfolding vector_smult_component ..\nalso have \"... = x $ (THE a. ?w = axis a 1) * ?w $ i + (\\<Sum>v\\<in>(cart_basis) - {?w}. x $ (THE i. v = axis i 1) * v $ i)\"\n by (rule setsum.remove[OF finite_cart_basis], auto simp add: cart_basis_def)\nalso have \"... = x $ (THE a. ?w = axis a 1) * ?w $ i\" unfolding setsum_eq_0 by simp\nalso have \"... = x $ i\" unfolding the_eq_i unfolding axis_def by auto\nfinally show \"(\\<Sum>v\\<in>cart_basis. x $ (THE i. v = axis i 1) *s v) $ i = x $ i\" .\nqed\nqed\n\n(*Locale of a finite dimensional vector space. From here on, some theorems that were based on\nthe euclidean_space class will be proven over this new locale.*)\nlocale finite_dimensional_vector_space = vector_space +\n  fixes Basis :: \"'b set\"\n  assumes finite_Basis: \"finite (Basis)\"\n  and independent_Basis: \"independent (Basis)\"\n  and span_Basis: \"span (Basis) = UNIV\"  \nbegin\n\n(*In the library, this is an abbreviation and it appears in the file Euclidean_Space.thy*)\ndefinition dimension :: \"nat\" where\n  \"dimension \\<equiv> card (Basis :: 'b set)\"\n\nlemma independent_bound:\n  shows \"independent S \\<Longrightarrow> finite S \\<and> card S \\<le> dimension\"\n  using independent_span_bound[OF finite_Basis, of S]\n  unfolding dimension_def span_Basis by auto\n  \n  \n  lemma maximal_independent_subset_extend:\n  assumes sv: \"S \\<subseteq> V\"\n    and iS: \"independent S\"\n  shows \"\\<exists>B. S \\<subseteq> B \\<and> B \\<subseteq> V \\<and> independent B \\<and> V \\<subseteq> span B\"\n  using sv iS\nproof (induct \"dimension - card S\" arbitrary: S rule: less_induct)\n  case less\n  note sv = `S \\<subseteq> V` and i = `independent S`\n  let ?P = \"\\<lambda>B. S \\<subseteq> B \\<and> B \\<subseteq> V \\<and> independent B \\<and> V \\<subseteq> span B\"\n  let ?ths = \"\\<exists>x. ?P x\"\n  let ?d = \"dimension\"\n  show ?ths\n  proof (cases \"V \\<subseteq> span S\")\n    case True\n    then show ?thesis\n      using sv i by blast\n  next\n    case False\n    then obtain a where a: \"a \\<in> V\" \"a \\<notin> span S\"\n      by blast\n    from a have aS: \"a \\<notin> S\"\n      by (auto simp add: span_superset)\n    have th0: \"insert a S \\<subseteq> V\"\n      using a sv by blast\n    from independent_insert[of a S]  i a\n    have th1: \"independent (insert a S)\"\n      by auto\n    have mlt: \"?d - card (insert a S) < ?d - card S\"\n      using aS a independent_bound[OF th1] by auto\n\n    from less(1)[OF mlt th0 th1]\n    obtain B where B: \"insert a S \\<subseteq> B\" \"B \\<subseteq> V\" \"independent B\" \" V \\<subseteq> span B\"\n      by blast\n    from B have \"?P B\" by auto\n    then show ?thesis by blast\n  qed\nqed\n\nlemma maximal_independent_subset:\n  \"\\<exists>B. B\\<subseteq> V \\<and> independent B \\<and> V \\<subseteq> span B\"\n  by (metis maximal_independent_subset_extend[of \"{}\"]\n    empty_subsetI independent_empty)\nend\n\ncontext vector_space\nbegin  \ndefinition \"dim V = (SOME n. \\<exists>B. B \\<subseteq> V \\<and> independent B \\<and> V \\<subseteq> span B \\<and> card B = n)\"\nend\n\ncontext finite_dimensional_vector_space\nbegin\nlemma basis_exists:\n  \"\\<exists>B. B \\<subseteq> V \\<and> independent B \\<and> V \\<subseteq> span B \\<and> (card B = dim V)\"\n  unfolding dim_def some_eq_ex[of \"\\<lambda>n. \\<exists>B. B \\<subseteq> V \\<and> independent B \\<and> V \\<subseteq> span B \\<and> (card B = n)\"]\n  using maximal_independent_subset[of V] independent_bound\n  by auto\n  \n  lemma independent_card_le_dim:\n  assumes \"B \\<subseteq> V\"\n    and \"independent B\"\n  shows \"card B \\<le> dim V\"\nproof -\n  from basis_exists[of V] `B \\<subseteq> V`\n  obtain B' where \"independent B'\"\n    and \"B \\<subseteq> span B'\"\n    and \"card B' = dim V\"\n    by blast\n  with independent_span_bound[OF _ `independent B` `B \\<subseteq> span B'`] independent_bound[of B']\n  show ?thesis by auto\nqed\n\nlemma span_card_ge_dim:\n  shows \"B \\<subseteq> V \\<Longrightarrow> V \\<subseteq> span B \\<Longrightarrow> finite B \\<Longrightarrow> dim V \\<le> card B\"\n  by (metis basis_exists[of V] independent_span_bound subset_trans)\n\nlemma basis_card_eq_dim:\n  shows \"B \\<subseteq> V \\<Longrightarrow> V \\<subseteq> span B \\<Longrightarrow> independent B \\<Longrightarrow> finite B \\<and> card B = dim V\"\n  by (metis order_eq_iff independent_card_le_dim span_card_ge_dim independent_bound)\n\nlemma dim_unique:\n  shows \"B \\<subseteq> V \\<Longrightarrow> V \\<subseteq> span B \\<Longrightarrow> independent B \\<Longrightarrow> card B = n \\<Longrightarrow> dim V = n\"\n  by (metis basis_card_eq_dim)\n  \nlemma dim_UNIV:\n  shows \"dim UNIV = card (Basis)\"\n  by (metis basis_card_eq_dim independent_Basis span_Basis top_greatest)\n\nlemma dim_subset:\n  shows \"S \\<subseteq> T \\<Longrightarrow> dim S \\<le> dim T\"\n  using basis_exists[of T] basis_exists[of S]\n  by (metis independent_card_le_dim subset_trans)  \n\n(*This lemma doesn't appear in the library, but it's useful in my development*)  \nlemma dim_univ_eq_dimension:\n  shows \"dim UNIV = dimension\"\n  by (metis basis_card_eq_dim dimension_def independent_Basis span_Basis top_greatest)\n\nlemma dim_subset_UNIV:\n  shows \"dim S \\<le> dimension\"\n  by (metis dimension_def dim_subset subset_UNIV dim_UNIV)\n\nlemma card_ge_dim_independent:\n  assumes BV: \"B \\<subseteq> V\"\n    and iB: \"independent B\"\n    and dVB: \"dim V \\<le> card B\"\n  shows \"V \\<subseteq> span B\"\nproof\n  fix a\n  assume aV: \"a \\<in> V\"\n  {\n    assume aB: \"a \\<notin> span B\"\n    then have iaB: \"independent (insert a B)\"\n      using iB aV BV by (simp add: independent_insert)\n    from aV BV have th0: \"insert a B \\<subseteq> V\"\n      by blast\n    from aB have \"a \\<notin>B\"\n      by (auto simp add: span_superset)\n    with independent_card_le_dim[OF th0 iaB] dVB independent_bound[OF iB]\n    have False by auto\n  }\n  then show \"a \\<in> span B\" by blast\nqed\n\nlemma card_le_dim_spanning:\n  assumes BV: \"B \\<subseteq> V\"\n    and VB: \"V \\<subseteq> span B\"\n    and fB: \"finite B\"\n    and dVB: \"dim V \\<ge> card B\"\n  shows \"independent B\"\nproof -\n  {\n    fix a\n    assume a: \"a \\<in> B\" \"a \\<in> span (B - {a})\"\n    from a fB have c0: \"card B \\<noteq> 0\"\n      by auto\n    from a fB have cb: \"card (B - {a}) = card B - 1\"\n      by auto\n    from BV a have th0: \"B - {a} \\<subseteq> V\"\n      by blast\n    {\n      fix x\n      assume x: \"x \\<in> V\"\n      from a have eq: \"insert a (B - {a}) = B\"\n        by blast\n      from x VB have x': \"x \\<in> span B\"\n        by blast\n      from span_trans[OF a(2), unfolded eq, OF x']\n      have \"x \\<in> span (B - {a})\" .\n    }\n    then have th1: \"V \\<subseteq> span (B - {a})\"\n      by blast\n    have th2: \"finite (B - {a})\"\n      using fB by auto\n    from span_card_ge_dim[OF th0 th1 th2]\n    have c: \"dim V \\<le> card (B - {a})\" .\n    from c c0 dVB cb have False by simp\n  }\n  then show ?thesis\n    unfolding dependent_def by blast\nqed\n\nlemma card_eq_dim:\n  shows \"B \\<subseteq> V \\<Longrightarrow> card B = dim V \\<Longrightarrow> finite B \\<Longrightarrow> independent B \\<longleftrightarrow> V \\<subseteq> span B\"\n  by (metis order_eq_iff card_le_dim_spanning card_ge_dim_independent)\n  \nlemma independent_bound_general:\n  shows \"independent S ==> finite S \\<and> card S \\<le> dim S\"\n  by (metis independent_card_le_dim independent_bound subset_refl)\n\nlemma dim_span:\n  shows \"dim (span S) = dim S\"\nproof -\n  have th0: \"dim S \\<le> dim (span S)\"\n    by (auto simp add: subset_eq intro: dim_subset span_superset)\n  from basis_exists[of S]\n  obtain B where B: \"B \\<subseteq> S\" \"independent B\" \"S \\<subseteq> span B\" \"card B = dim S\"\n    by blast\n  from B have fB: \"finite B\" \"card B = dim S\"\n    using independent_bound by blast+\n  have bSS: \"B \\<subseteq> span S\"\n    using B(1) by (metis subset_eq span_inc)\n  have sssB: \"span S \\<subseteq> span B\"\n    using span_mono[OF B(3)] by (simp add: span_span)\n  from span_card_ge_dim[OF bSS sssB fB(1)] th0 show ?thesis\n    using fB(2) by arith\nqed\n\nlemma subset_le_dim:\n  shows \"S \\<subseteq> span T ==> dim S \\<le> dim T\"\n  by (metis dim_span dim_subset)\n\nlemma span_eq_dim:\n  shows \"span S = span T ==> dim S = dim T\"\n  by (metis dim_span)\nend\n\ncontext linear\nbegin\n\nlemma independent_injective_image:\n  assumes iS: \"B.independent S\"\n    and fi: \"inj f\"\n  shows \"C.independent (f ` S)\"\nproof -\n  have l: \"linear scaleB scaleC f\" by unfold_locales\n  {\n    fix a\n    assume a: \"a \\<in> S\" \"f a \\<in> C.span (f ` S - {f a})\"\n    have eq: \"f ` S - {f a} = f ` (S - {a})\"\n      using fi by (auto simp add: inj_on_def)\n    from a have \"f a \\<in> f ` B.span (S - {a})\"\n      unfolding eq B.span_linear_image[OF l, of \"S - {a}\"] by blast\n    then have \"a \\<in> B.span (S - {a})\"\n      using fi by (auto simp add: inj_on_def)\n    with a(1) iS have False\n      by (simp add: B.dependent_def)\n  }\n  then show ?thesis\n    unfolding dependent_def by blast\nqed\nend\n\n\n(*This is a new locale to make easier some proofs.*)\nlocale two_vector_spaces_over_same_field = B: vector_space scaleB + C: vector_space scaleC\n  for scaleB :: \"('a::field => 'b::ab_group_add => 'b)\" (infixr \"*b\" 75)\n  and scaleC :: \"('a => 'c::ab_group_add => 'c)\" (infixr \"*c\" 75)\n  \ncontext two_vector_spaces_over_same_field\nbegin\n\nlemma linear_indep_image_lemma:\n  assumes lf: \"linear (op *b) (op *c) f\"\n    and fB: \"finite B\"\n    and ifB: \"C.independent (f ` B)\"\n    and fi: \"inj_on f B\"\n    and xsB: \"x \\<in> B.span B\"\n    and fx: \"f x = 0\"\n  shows \"x = 0\"\n  using fB ifB fi xsB fx\nproof (induct arbitrary: x rule: finite_induct[OF fB])\n  case 1\n  then show ?case by auto\nnext\n  case (2 a b x)\n  have fb: \"finite b\" using \"2.prems\" by simp\n  have th0: \"f ` b \\<subseteq> f ` (insert a b)\"\n    apply (rule image_mono)\n    apply blast\n    done\n  from independent_mono[ OF \"2.prems\"(2) th0]\n  have ifb: \"independent (f ` b)\"  .\n  have fib: \"inj_on f b\"\n    apply (rule subset_inj_on [OF \"2.prems\"(3)])\n    apply blast\n    done\n  from B.span_breakdown[of a \"insert a b\", simplified, OF \"2.prems\"(4)]\n  obtain k where k: \"x - k *b a \\<in> B.span (b - {a})\"\n    by blast\n  have \"f (x - k *b a) \\<in> C.span (f ` b)\"\n    unfolding B.span_linear_image[OF lf]\n    apply (rule imageI)\n    using k B.span_mono[of \"b - {a}\" b]\n    apply blast\n    done\n  then have \"f x - k *c f a \\<in> C.span (f ` b)\"\n    by (metis (full_types) lf linear.linear_cmul linear.linear_sub)\n  then have th: \"-k *c f a \\<in> C.span (f ` b)\"\n    using \"2.prems\"(5) by simp\n  have xsb: \"x \\<in> B.span b\"\n  proof (cases \"k = 0\")\n    case True\n    with k have \"x \\<in> B.span (b - {a})\" by simp\n    then show ?thesis using B.span_mono[of \"b - {a}\" b]\n      by blast\n  next\n    case False\n    with span_mul[OF th, of \"- 1/ k\"]\n    have th1: \"f a \\<in> span (f ` b)\"\n      by auto\n    from inj_on_image_set_diff[OF \"2.prems\"(3), of \"insert a b \" \"{a}\", symmetric]\n    have tha: \"f ` insert a b - f ` {a} = f ` (insert a b - {a})\" by blast\n    from \"2.prems\"(2) [unfolded dependent_def bex_simps(8), rule_format, of \"f a\"]\n    have \"f a \\<notin> span (f ` b)\" using tha\n      using \"2.hyps\"(2)\n      \"2.prems\"(3) by auto\n    with th1 have False by blast\n    then show ?thesis by blast\n  qed\n  from \"2.hyps\"(3)[OF fb ifb fib xsb \"2.prems\"(5)] show \"x = 0\" .\nqed\n\nlemma linear_independent_extend_lemma:\n  fixes f :: \"'b \\<Rightarrow> 'c\"\n  assumes fi: \"finite B\"\n    and ib: \"B.independent B\"\n  shows \"\\<exists>g.\n    (\\<forall>x\\<in> B.span B. \\<forall>y\\<in> B.span B. g (x + y) = g x + g y) \\<and>\n    (\\<forall>x\\<in> B.span B. \\<forall>c. g (c *b x) = c *c (g x)) \\<and>\n    (\\<forall>x\\<in> B. g x = f x)\"\n  using ib fi\nproof (induct rule: finite_induct[OF fi])\n  case 1\n  then show ?case by auto\nnext\n  case (2 a b)\n  from \"2.prems\" \"2.hyps\" have ibf: \"B.independent b\" \"finite b\"\n    by (simp_all add: B.independent_insert)\n  from \"2.hyps\"(3)[OF ibf] obtain g where\n    g: \"\\<forall>x\\<in>B.span b. \\<forall>y\\<in>B.span b. g (x + y) = g x + g y\"\n    \"\\<forall>x\\<in>B.span b. \\<forall>c. g (c *b x) = c *c g x\" \"\\<forall>x\\<in>b. g x = f x\" by blast\n  let ?h = \"\\<lambda>z. SOME k. (z - k *b a) \\<in> B.span b\"\n  {\n    fix z\n    assume z: \"z \\<in> B.span (insert a b)\"\n    have th0: \"z - ?h z *b a \\<in> B.span b\"\n      apply (rule someI_ex)\n      unfolding B.span_breakdown_eq[symmetric]\n      apply (rule z)\n      done\n    {\n      fix k\n      assume k: \"z - k *b a \\<in> B.span b\"\n      have eq: \"z - ?h z *b a - (z - k *b a) = (k - ?h z) *b a\"\n        by (simp add: field_simps B.scale_left_distrib [symmetric])\n      from B.span_sub[OF th0 k] have khz: \"(k - ?h z) *b a \\<in> B.span b\"\n        by (simp add: eq)\n      {\n        assume \"k \\<noteq> ?h z\"\n        then have k0: \"k - ?h z \\<noteq> 0\" by simp\n        from k0 B.span_mul[OF khz, of \"1 /(k - ?h z)\"]\n        have \"a \\<in> B.span b\" by simp\n        with \"2.prems\"(1) \"2.hyps\"(2) have False\n          by (auto simp add: B.dependent_def)\n      }\n      then have \"k = ?h z\" by blast\n    }\n    with th0 have \"z - ?h z *b a \\<in> B.span b \\<and> (\\<forall>k. z - k *b a \\<in> B.span b \\<longrightarrow> k = ?h z)\"\n      by blast\n  }\n  note h = this\n  let ?g = \"\\<lambda>z. (?h z) *c (f a) + g (z - (?h z) *b a)\"\n  {\n    fix x y\n    assume x: \"x \\<in> B.span (insert a b)\"\n      and y: \"y \\<in> B.span (insert a b)\"\n    have tha: \"\\<And>(x::'b) y a k l. (x + y) - (k + l) *b a = (x - k *b a) + (y - l *b a)\"\n      by (simp add: algebra_simps)\n    have addh: \"?h (x + y) = ?h x + ?h y\"\n      apply (rule conjunct2[OF h, rule_format, symmetric])\n      apply (rule B.span_add[OF x y])\n      unfolding tha\n      apply (metis B.span_add x y conjunct1[OF h, rule_format])\n      done\n    have \"?g (x + y) = ?g x + ?g y\"\n      unfolding addh tha\n      g(1)[rule_format,OF conjunct1[OF h, OF x] conjunct1[OF h, OF y]]\n      by (simp add: C.scale_left_distrib)}\n  moreover\n  {\n    fix x :: \"'b\"\n    fix c :: 'a\n    assume x: \"x \\<in> B.span (insert a b)\"\n    have tha: \"\\<And>(x::'b) c k a. c *b x - (c * k) *b a = c *b (x - k *b a)\"\n      by (simp add: algebra_simps)\n    have hc: \"?h (c *b x) = c * ?h x\"\n      apply (rule conjunct2[OF h, rule_format, symmetric])\n      apply (metis B.span_mul x)\n      apply (metis tha B.span_mul x conjunct1[OF h])\n      done\n    have \"?g (c *b x) = c *c ?g x\"\n      unfolding hc tha g(2)[rule_format, OF conjunct1[OF h, OF x]]\n      by (simp add: algebra_simps)\n  }\n  moreover\n  {\n    fix x\n    assume x: \"x \\<in> insert a b\"\n    {\n      assume xa: \"x = a\"\n      have ha1: \"1 = ?h a\"\n        apply (rule conjunct2[OF h, rule_format])\n        apply (metis B.span_superset insertI1)\n        using conjunct1[OF h, OF B.span_superset, OF insertI1]\n        apply (auto simp add: B.span_0)\n        done\n      from xa ha1[symmetric] have \"?g x = f x\"\n        apply simp\n        using g(2)[rule_format, OF B.span_0, of 0]\n        apply simp\n        done\n    }\n    moreover\n    {\n      assume xb: \"x \\<in> b\"\n      have h0: \"0 = ?h x\"\n        apply (rule conjunct2[OF h, rule_format])\n        apply (metis B.span_superset x)\n        apply simp\n        apply (metis B.span_superset xb)\n        done\n      have \"?g x = f x\"\n        by (simp add: h0[symmetric] g(3)[rule_format, OF xb])\n    }\n    ultimately have \"?g x = f x\"\n      using x by blast\n  }\n  ultimately show ?case\n    apply -\n    apply (rule exI[where x=\"?g\"])\n    apply blast\n    done\nqed\nend\n\n(*This is a new locale, similar to the previous one, to make easier some proofs.*)\nlocale two_finite_dimensional_vector_spaces_over_same_field = B: finite_dimensional_vector_space scaleB BasisB + \n  C: finite_dimensional_vector_space scaleC BasisC\n  for scaleB :: \"('a::field => 'b::ab_group_add => 'b)\" (infixr \"*b\" 75)\n  and scaleC :: \"('a => 'c::ab_group_add => 'c)\" (infixr \"*c\" 75)\n  and BasisB :: \"('b set)\"\n  and BasisC :: \"('c set)\"\n\ncontext two_finite_dimensional_vector_spaces_over_same_field\nbegin\n\nsublocale two_vector_spaces: two_vector_spaces_over_same_field by unfold_locales\n\nlemma linear_independent_extend:\n  assumes iB: \"B.independent B\"\n  shows \"\\<exists>g. linear (op *b) (op *c) g \\<and> (\\<forall>x\\<in>B. g x = f x)\"\nproof -\n  have 1: \"vector_space (op *b)\" and 2: \"vector_space (op *c)\" by unfold_locales\n  from B.maximal_independent_subset_extend[of B UNIV] iB\n  obtain C where C: \"B \\<subseteq> C\" \"B.independent C\" \"\\<And>x. x \\<in> B.span C\"\n    by auto\n  from C(2) B.independent_bound[of C] two_vector_spaces.linear_independent_extend_lemma[of C]\n  obtain g where g:\n    \"(\\<forall>x\\<in> B.span C. \\<forall>y\\<in> B.span C. g (x + y) = g x + g y) \\<and>\n     (\\<forall>x\\<in> B.span C. \\<forall>c. g (c *b x) = c *c g x) \\<and>\n     (\\<forall>x\\<in> C. g x = f x)\" by blast\n  from g show ?thesis\n    unfolding linear_iff\n    using C 1 2\n    apply clarsimp\n    apply blast\n    done\nqed\nend\n\ncontext vector_space\nbegin\n  \nlemma spans_image:\n  assumes lf: \"linear scale scaleC (f::'b=>'c::ab_group_add)\"\n  and VB: \"V \\<subseteq> span B\"\n  shows \"f ` V \\<subseteq> vector_space.span scaleC (f ` B)\"\n  unfolding span_linear_image[OF lf] by (metis VB image_mono) \n\nlemma subspace_kernel:\n  assumes lf: \"linear scale scaleC f\"\n  shows \"subspace {x. f x = 0}\"\n  proof (unfold subspace_def, auto)\n  interpret lf: linear scale scaleC f using lf by simp\n  show \"f 0 = 0\" using lf.linear_0 .\n  fix x y assume fx: \"f x = 0\" and fy: \"f y = 0\"\n  show \"f (x + y) = 0\" unfolding lf.linear_add fx fy by simp\n  fix c::'a show \"f (scale c x) = 0\" unfolding fx lf.linear_cmul lf.scale_zero_right ..\nqed\n\nlemma linear_eq_0_span:\n  assumes lf: \"linear scale scaleC f\" and f0: \"\\<forall>x\\<in>B. f x = 0\"\n  shows \"\\<forall>x \\<in> span B. f x = 0\"\n  using f0 subspace_kernel[OF lf]\n  by (rule span_induct')\n\nlemma linear_eq_0:\n  assumes lf: \"linear scale scaleB f\"\n    and SB: \"S \\<subseteq> span B\"\n    and f0: \"\\<forall>x\\<in>B. f x = 0\"\n  shows \"\\<forall>x \\<in> S. f x = 0\"\n  by (metis linear_eq_0_span[OF lf] subset_eq SB f0)\n\nlemma linear_eq:\n  assumes lf: \"linear scale scaleC f\"\n    and lg: \"linear scale scaleC g\"\n    and S: \"S \\<subseteq> span  B\"\n    and fg: \"\\<forall> x\\<in> B. f x = g x\"\n  shows \"\\<forall>x\\<in> S. f x = g x\"\nproof -\n  let ?h = \"\\<lambda>x. f x - g x\"\n  from fg have fg': \"\\<forall>x\\<in> B. ?h x = 0\" by simp\n  from linear_eq_0[OF linear_compose_sub[OF lf lg] S fg']\n  show ?thesis by simp\nqed\nend\n\n(*A new locale to make easier some proofs.*)\n\nlocale linear_between_finite_dimensional_vector_spaces =\n  l: linear scaleB scaleC f +\n  B: finite_dimensional_vector_space scaleB BasisB + \n  C: finite_dimensional_vector_space scaleC BasisC\n  for scaleB :: \"('a::field => 'b::ab_group_add => 'b)\" (infixr \"*b\" 75)\n  and scaleC :: \"('a => 'c::ab_group_add => 'c)\" (infixr \"*c\" 75) \n  and BasisB :: \"('b set)\"\n  and BasisC :: \"('c set)\"\n  and f :: \"('b=>'c)\"\n  \ncontext linear_between_finite_dimensional_vector_spaces\nbegin\n\nlemma linear_eq_stdbasis:\n  assumes lg: \"linear (op *b) (op *c) g\"\n  and fg: \"\\<forall>b\\<in>BasisB. f b = g b\"\n  shows \"f = g\" \nproof -\n  have l: \"linear (op *b) (op *c) f\" by unfold_locales\n  show ?thesis \n  using B.linear_eq[OF l lg, of UNIV BasisB] fg using B.span_Basis by auto\nqed\n  \nlemma linear_injective_left_inverse:\n  assumes fi: \"inj f\"\n  shows \"\\<exists>g. linear (op *c) (op *b) g \\<and> g o f = id\"\nproof -\n  interpret fd: two_finite_dimensional_vector_spaces_over_same_field \"(op *c)\" \"(op *b)\" BasisC BasisB\n    by unfold_locales  \n have lf: \"linear op *b op *c f\" by unfold_locales\n  from fd.linear_independent_extend[OF independent_injective_image, OF B.independent_Basis, OF fi]\n  obtain h:: \"'c \\<Rightarrow> 'b\" where h: \"linear (op *c) (op *b) h\" \"\\<forall>x \\<in> f ` BasisB. h x = inv f x\"\n    by blast\n  from h(2) have th: \"\\<forall>i\\<in>BasisB. (h \\<circ> f) i = id i\"\n    using inv_o_cancel[OF fi, unfolded fun_eq_iff id_def o_def]\n    by auto\n  interpret l_hg: linear_between_finite_dimensional_vector_spaces \"op *b\" \"op *b\" BasisB BasisB \"(h \\<circ> f)\" \n  apply (unfold_locales) using linear_compose[OF lf h(1)] unfolding linear_iff by fast+\n  show ?thesis\n    using h(1)  l_hg.linear_eq_stdbasis[OF B.linear_id th] by blast\nqed\n\nsublocale two_finite_dimensional_vector_spaces: two_finite_dimensional_vector_spaces_over_same_field \nby unfold_locales\n\nlemma linear_surjective_right_inverse:\n  assumes sf: \"surj f\"\n  shows \"\\<exists>g. linear (op *c) (op *b) g \\<and> f o g = id\"\nproof -\n  interpret lh: two_finite_dimensional_vector_spaces_over_same_field \"op *c\" \"op *b\" BasisC BasisB \n    by unfold_locales\n  have lf: \"linear (op *b) (op *c) f\" by unfold_locales\n  from lh.linear_independent_extend[OF independent_Basis]\n  obtain h:: \"'c \\<Rightarrow> 'b\" where h: \"linear (op *c) (op *b) h\" \"\\<forall>x\\<in>BasisC. h x = inv f x\"\n    by blast\n  interpret l_fg: linear_between_finite_dimensional_vector_spaces  \"op *c\" \"op *c\" BasisC BasisC \"(f \\<circ> h)\"\n     using linear_compose[OF h(1) lf] by (unfold_locales, auto simp add: linear_def linear_axioms_def)\n  from h(2) have th: \"\\<forall>i\\<in>BasisC. (f o h) i = id i\"\n    using sf by (metis comp_apply surj_iff)\n  from l_fg.linear_eq_stdbasis[OF linear_id th]\n  have \"f o h = id\" .\n  then show ?thesis\n    using h(1) by blast\nqed\n\nend\n\n\ncontext finite_dimensional_vector_space\nbegin\n\nlemma linear_injective_imp_surjective:\n  assumes lf: \"linear scale scale f\"\n    and fi: \"inj f\"\n  shows \"surj f\"\nproof -\n  interpret lf: linear scale scale f using lf by auto\n  let ?U = \"UNIV :: 'b set\"\n  from basis_exists[of ?U] obtain B\n    where B: \"B \\<subseteq> ?U\" \"independent B\" \"?U \\<subseteq> span B\" \"card B = dim ?U\"\n    by blast\n  from B(4) have d: \"dim ?U = card B\"\n    by simp\n  have th: \"?U \\<subseteq> span (f ` B)\"\n    apply (rule card_ge_dim_independent)\n    apply blast\n    apply (rule lf.independent_injective_image[OF B(2) fi])\n    apply (rule order_eq_refl)\n    apply (rule sym)\n    unfolding d\n    apply (rule card_image)\n    apply (rule subset_inj_on[OF fi])\n    apply blast\n    done\n  from th show ?thesis\n    unfolding span_linear_image[OF lf] surj_def\n    using B(3) by auto \nqed\n\n\nlemma linear_surjective_imp_injective:\n  assumes lf: \"linear scale scale f\"\n    and sf: \"surj f\"\n  shows \"inj f\"\nproof -\n  interpret t: two_vector_spaces_over_same_field scale scale by unfold_locales\n  let ?U = \"UNIV :: 'b set\"\n  from basis_exists[of ?U] obtain B\n    where B: \"B \\<subseteq> ?U\" \"independent B\" \"?U \\<subseteq> span B\" and d: \"card B = dim ?U\"\n    by blast\n  {\n    fix x\n    assume x: \"x \\<in> span B\"\n    assume fx: \"f x = 0\"\n    from B(2) have fB: \"finite B\"\n      using independent_bound by auto\n    have fBi: \"independent (f ` B)\"\n      apply (rule card_le_dim_spanning[of \"f ` B\" ?U])\n      apply blast\n      using sf B(3)\n      unfolding span_linear_image[OF lf] surj_def subset_eq image_iff\n      apply blast\n      using fB apply blast\n      unfolding d[symmetric]\n      apply (rule card_image_le)\n      apply (rule fB)\n      done\n    have th0: \"dim ?U \\<le> card (f ` B)\"\n      apply (rule span_card_ge_dim)\n      apply blast\n      unfolding span_linear_image[OF lf]\n      apply (rule subset_trans[where B = \"f ` UNIV\"])\n      using sf unfolding surj_def\n      apply blast\n      apply (rule image_mono)\n      apply (rule B(3))\n      apply (metis finite_imageI fB)\n      done\n    moreover have \"card (f ` B) \\<le> card B\"\n      by (rule card_image_le, rule fB)\n    ultimately have th1: \"card B = card (f ` B)\"\n      unfolding d by arith\n    have fiB: \"inj_on f B\"\n      unfolding surjective_iff_injective_gen[OF fB finite_imageI[OF fB] th1 subset_refl, symmetric]\n      by blast\n    from t.linear_indep_image_lemma[OF lf fB fBi fiB x] fx\n    have \"x = 0\" by blast\n  }\n  then show ?thesis\n    unfolding linear.linear_injective_0[OF lf]\n    using B(3)\n    by blast\nqed\n\n\nlemma linear_injective_isomorphism:\n  assumes lf: \"linear scale scale f\"\n    and fi: \"inj f\"\n  shows \"\\<exists>f'. linear scale scale f' \\<and> (\\<forall>x. f' (f x) = x) \\<and> (\\<forall>x. f (f' x) = x)\"\nproof -\n  interpret lbfdvs: linear_between_finite_dimensional_vector_spaces scale scale Basis Basis f\n    by (unfold_locales, simp add: lf linear.linear_cmul linear.linear_add, metis lf linear.linear_add)\n  show ?thesis\n  unfolding isomorphism_expand[symmetric]\n  using lbfdvs.linear_surjective_right_inverse\n  using linear_injective_imp_surjective \n  by (metis comp_assoc comp_id fi lbfdvs.linear_injective_left_inverse lf)\nqed\n\n\nlemma linear_surjective_isomorphism:\n  assumes lf: \"linear scale scale f\"\n    and sf: \"surj f\"\n  shows \"\\<exists>f'. linear scale scale f' \\<and> (\\<forall>x. f' (f x) = x) \\<and> (\\<forall>x. f (f' x) = x)\"\n  proof -\n  interpret lbfdvs: linear_between_finite_dimensional_vector_spaces scale scale Basis Basis f\n    apply (unfold_locales) apply (simp add:  lf linear.linear_cmul linear.linear_add)\n    by (metis lf linear.linear_add)\n  show ?thesis  \n  unfolding isomorphism_expand[symmetric]\n    using lbfdvs.linear_surjective_right_inverse[OF sf]\n   using lbfdvs.linear_injective_left_inverse[OF linear_surjective_imp_injective[OF lf sf]]\n  by (metis left_right_inverse_eq)\nqed\n\n\nlemma left_inverse_linear:\n  assumes lf: \"linear scale scale f\"\n    and gf: \"g \\<circ> f = id\"\n  shows \"linear scale scale g\"\nproof -\n  from gf have fi: \"inj f\"\n    by (metis inj_on_id inj_on_imageI2)\n  from linear_injective_isomorphism[OF lf fi]\n  obtain h :: \"'b \\<Rightarrow> 'b\" where h: \"linear scale scale h\" \"\\<forall>x. h (f x) = x\" \"\\<forall>x. f (h x) = x\"\n    by blast\n  have \"h = g\"\n    apply (rule ext) using gf h(2,3)\n    by (metis comp_apply id_apply)\n  with h(1) show ?thesis by blast\nqed\nend\n\n(********************** Here ends the generalization of Linear_Algebra.thy **********************)\n\n(*Some interpretations:*)\ninterpretation vec: finite_dimensional_vector_space \"op *s\" \"(cart_basis)\"\n  by (unfold_locales, auto simp add: finite_cart_basis independent_cart_basis span_cart_basis) \n  \nlemma matrix_vector_mul_linear_between_finite_dimensional_vector_spaces: \n  \"linear_between_finite_dimensional_vector_spaces (op *s) (op *s) \n    (cart_basis) (cart_basis) (\\<lambda>x. A *v (x::'a::{field} ^ _))\"\n  by (unfold_locales) \n    (auto simp add: linear_iff2 matrix_vector_mult_def vec_eq_iff\n      field_simps setsum_right_distrib setsum.distrib)\n\ninterpretation euclidean_space: \n  finite_dimensional_vector_space \"scaleR :: real => 'a => 'a::{euclidean_space}\" \"Basis\"\nproof\n  have v: \"vector_space (scaleR :: real => 'a => 'a::{euclidean_space})\" by (unfold_locales)\n  show \"finite (Basis::'a set)\" by (metis finite_Basis)\n  show \"vector_space.independent op *\\<^sub>R (Basis::'a set)\"\n    unfolding vector_space.dependent_def[OF v]\n    apply (subst vector_space.span_finite[OF v])\n    apply simp\n    apply clarify\n    apply (drule_tac f=\"inner a\" in arg_cong)\n    apply (simp add: inner_Basis inner_setsum_right eq_commute)\n    done\n  show \"vector_space.span op *\\<^sub>R (Basis::'a set) = UNIV\"\n    unfolding vector_space.span_finite [OF v finite_Basis]\n    by (fast intro: euclidean_representation)\nqed\n\n(****************** Generalized parts of the file Cartesian_Euclidean_Space.thy ******************)\n\nlemma vector_mul_lcancel[simp]: \"a *s x = a *s y \\<longleftrightarrow> a = (0::'a::{field}) \\<or> x = y\"\n  by (metis eq_iff_diff_eq_0 vector_mul_eq_0 vector_ssub_ldistrib)\n  \nlemma vector_mul_lcancel_imp: \"a \\<noteq> (0::'a::{field}) ==>  a *s x = a *s y ==> (x = y)\"\n  by (metis vector_mul_lcancel)\n  \nlemma linear_componentwise:\n  fixes f:: \"'a::field ^'m \\<Rightarrow> 'a ^ 'n\"\n  assumes lf: \"linear (op *s) (op *s) f\"\n  shows \"(f x)$j = setsum (\\<lambda>i. (x$i) * (f (axis i 1)$j)) (UNIV :: 'm set)\" (is \"?lhs = ?rhs\")\nproof -\n  interpret lf: linear \"(op *s)\" \"(op *s)\" f\n    using lf .   \n  let ?M = \"(UNIV :: 'm set)\"\n  let ?N = \"(UNIV :: 'n set)\"\n  have fM: \"finite ?M\" by simp\n  have \"?rhs = (setsum (\\<lambda>i. (x$i) *s (f (axis i 1))) ?M)$j\"\n    unfolding setsum_component by simp\n  then show ?thesis\n    unfolding lf.linear_setsum_mul[OF fM, symmetric]\n    unfolding basis_expansion by auto\nqed\n\n\nlemma matrix_vector_mul_linear: \"linear (op *s) (op *s) (\\<lambda>x. A *v (x::'a::{field} ^ _))\"\n  by (simp add: linear_iff2 matrix_vector_mult_def vec_eq_iff\n      field_simps setsum_right_distrib setsum.distrib)\n  \n(*Two new interpretations*)\ninterpretation vec: linear \"op *s\" \"op *s\" \"(\\<lambda>x. A *v (x::'a::{field} ^ _))\" \n  using matrix_vector_mul_linear .\n  \ninterpretation vec: linear_between_finite_dimensional_vector_spaces \"op *s\" \"op *s\" \n  \"(cart_basis)\" \"(cart_basis)\" \"(op *v A)\"\n  by unfold_locales\n  \nlemma matrix_works:\n  assumes lf: \"linear (op *s) (op *s) f\"\n  shows \"matrix f *v x = f (x::'a::field ^ 'n)\"\n  apply (simp add: matrix_def matrix_vector_mult_def vec_eq_iff mult.commute)\n  apply clarify\n  apply (rule linear_componentwise[OF lf, symmetric])\n  done\n      \nlemma matrix_vector_mul: \"linear (op *s) (op *s) f ==> f = (\\<lambda>x. matrix f *v (x::'a::{field}^ 'n))\"\n  by (simp add: ext matrix_works)\n  \nlemma matrix_of_matrix_vector_mul: \"matrix(\\<lambda>x. A *v (x :: 'a::{field} ^ 'n)) = A\"\n  by (simp add: matrix_eq matrix_vector_mul_linear matrix_works)\n  \nlemma matrix_compose:\n  assumes lf: \"linear (op *s) (op *s) (f::'a::{field}^'n \\<Rightarrow> 'a^'m)\"\n    and lg: \"linear (op *s) (op *s) (g::'a^'m \\<Rightarrow> 'a^_)\"\n  shows \"matrix (g o f) = matrix g ** matrix f\"\n  using lf lg linear_compose[OF lf lg] matrix_works[OF linear_compose[OF lf lg]]\n  by (simp add: matrix_eq matrix_works matrix_vector_mul_assoc[symmetric] o_def)\n  \nlemma matrix_left_invertible_injective:\n  \"(\\<exists>B. (B::'a::{field}^'m^'n) ** (A::'a::{field}^'n^'m) = mat 1) \n    \\<longleftrightarrow> (\\<forall>x y. A *v x = A *v y \\<longrightarrow> x = y)\"\nproof -\n  { fix B:: \"'a^'m^'n\" and x y assume B: \"B ** A = mat 1\" and xy: \"A *v x = A*v y\"\n    from xy have \"B*v (A *v x) = B *v (A*v y)\" by simp\n    hence \"x = y\"\n      unfolding matrix_vector_mul_assoc B matrix_vector_mul_lid . }\n  moreover\n  { assume A: \"\\<forall>x y. A *v x = A *v y \\<longrightarrow> x = y\"\n    hence i: \"inj (op *v A)\" unfolding inj_on_def by auto\n    from vec.linear_injective_left_inverse[OF i]\n    obtain g where g: \"linear (op *s)  (op *s) g\" \"g o op *v A = id\" by blast\n    have \"matrix g ** A = mat 1\"\n      unfolding matrix_eq matrix_vector_mul_lid matrix_vector_mul_assoc[symmetric] matrix_works[OF g(1)]\n      using g(2) by (metis comp_apply id_apply)\n    then have \"\\<exists>B. (B::'a::{field}^'m^'n) ** A = mat 1\" by blast }\n  ultimately show ?thesis by blast\nqed\n\n\nlemma matrix_left_invertible_ker:\n  \"(\\<exists>B. (B::'a::{field} ^'m^'n) ** (A::'a::{field}^'n^'m) = mat 1) \\<longleftrightarrow> (\\<forall>x. A *v x = 0 \\<longrightarrow> x = 0)\"\n  unfolding matrix_left_invertible_injective\n  using vec.linear_injective_0[of A]\n  by (simp add: inj_on_def)\n  \n  lemma matrix_left_invertible_independent_columns:\n  fixes A :: \"'a::{field}^'n^'m\"\n  shows \"(\\<exists>(B::'a ^'m^'n). B ** A = mat 1) \\<longleftrightarrow>\n      (\\<forall>c. setsum (\\<lambda>i. c i *s column i A) (UNIV :: 'n set) = 0 \\<longrightarrow> (\\<forall>i. c i = 0))\"\n    (is \"?lhs \\<longleftrightarrow> ?rhs\")\nproof -\n  let ?U = \"UNIV :: 'n set\"\n  { assume k: \"\\<forall>x. A *v x = 0 \\<longrightarrow> x = 0\"\n    { fix c i\n      assume c: \"setsum (\\<lambda>i. c i *s column i A) ?U = 0\" and i: \"i \\<in> ?U\"\n      let ?x = \"\\<chi> i. c i\"\n      have th0:\"A *v ?x = 0\"\n        using c\n        unfolding matrix_mult_vsum vec_eq_iff\n        by auto\n      from k[rule_format, OF th0] i\n      have \"c i = 0\" by (vector vec_eq_iff)}\n    hence ?rhs by blast }\n  moreover\n  { assume H: ?rhs\n    { fix x assume x: \"A *v x = 0\"\n      let ?c = \"\\<lambda>i. ((x$i ):: 'a)\"\n      from H[rule_format, of ?c, unfolded matrix_mult_vsum[symmetric], OF x]\n      have \"x = 0\" by vector }\n  }\n  ultimately show ?thesis unfolding matrix_left_invertible_ker by blast\nqed\n\n  \nlemma matrix_right_invertible_independent_rows:\n  fixes A :: \"'a::{field}^'n^'m\"\n  shows \"(\\<exists>(B::'a^'m^'n). A ** B = mat 1) \\<longleftrightarrow>\n    (\\<forall>c. setsum (\\<lambda>i. c i *s row i A) (UNIV :: 'm set) = 0 \\<longrightarrow> (\\<forall>i. c i = 0))\"\n  unfolding left_invertible_transpose[symmetric]\n    matrix_left_invertible_independent_columns\n  by (simp add: column_transpose)\n\n\nlemma matrix_left_right_inverse:\n  fixes A A' :: \"'a::{field}^'n^'n\"\n  shows \"A ** A' = mat 1 \\<longleftrightarrow> A' ** A = mat 1\"\nproof -\n  { fix A A' :: \"'a ^'n^'n\"\n    assume AA': \"A ** A' = mat 1\"\n    have sA: \"surj (op *v A)\"\n      unfolding surj_def\n      apply clarify\n      apply (rule_tac x=\"(A' *v y)\" in exI)\n      apply (simp add: matrix_vector_mul_assoc AA' matrix_vector_mul_lid)\n      done\n    from vec.linear_surjective_isomorphism[OF matrix_vector_mul_linear sA]\n    obtain f' :: \"'a ^'n \\<Rightarrow> 'a ^'n\"\n      where f': \"linear (op *s) (op *s) f'\" \"\\<forall>x. f' (A *v x) = x\" \"\\<forall>x. A *v f' x = x\" by blast\n    have th: \"matrix f' ** A = mat 1\"\n      by (simp add: matrix_eq matrix_works[OF f'(1)]\n          matrix_vector_mul_assoc[symmetric] matrix_vector_mul_lid f'(2)[rule_format])\n    hence \"(matrix f' ** A) ** A' = mat 1 ** A'\" by simp\n    hence \"matrix f' = A'\"\n      by (simp add: matrix_mul_assoc[symmetric] AA' matrix_mul_rid matrix_mul_lid)\n    hence \"matrix f' ** A = A' ** A\" by simp\n    hence \"A' ** A = mat 1\" by (simp add: th)\n  }\n  then show ?thesis by blast\nqed\n\n(***************** Here ends the generalization of Cartesian_Euclidean_Space.thy *****************)\n\n(****************** Generalized parts of the file Convex_Euclidean_Space.thy ******************)\n\ncontext vector_space\nbegin\n\nlemma linear_injective_on_subspace_0:\n  assumes lf: \"linear scale scale f\"\n    and \"subspace S\"\n  shows \"inj_on f S \\<longleftrightarrow> (\\<forall>x \\<in> S. f x = 0 \\<longrightarrow> x = 0)\"\nproof -\n  have \"inj_on f S \\<longleftrightarrow> (\\<forall>x \\<in> S. \\<forall>y \\<in> S. f x = f y \\<longrightarrow> x = y)\"\n    by (simp add: inj_on_def)\n  also have \"\\<dots> \\<longleftrightarrow> (\\<forall>x \\<in> S. \\<forall>y \\<in> S. f x - f y = 0 \\<longrightarrow> x - y = 0)\"\n    by simp\n  also have \"\\<dots> \\<longleftrightarrow> (\\<forall>x \\<in> S. \\<forall>y \\<in> S. f (x - y) = 0 \\<longrightarrow> x - y = 0)\"\n    by (simp add: linear.linear_sub[OF lf])\n  also have \"\\<dots> \\<longleftrightarrow> (\\<forall>x \\<in> S. f x = 0 \\<longrightarrow> x = 0)\"\n    using `subspace S` subspace_def[of S] subspace_sub[of S] by auto\n  finally show ?thesis .\nqed\n\nend\n\n(*Maybe change de name*)\nlemma setsum_constant_scaleR:\n  shows \"(\\<Sum>x\\<in>A. y) = of_nat (card A) *s y\"\n  apply (cases \"finite A\")\n  apply (induct set: finite)\n  apply (simp_all add: algebra_simps)\n  done\n\ncontext finite_dimensional_vector_space\nbegin\n  \nlemma indep_card_eq_dim_span:\n  assumes \"independent B\"\n  shows \"finite B \\<and> card B = dim (span B)\"\n  using assms basis_card_eq_dim[of B \"span B\"] span_inc by auto\nend\n\ncontext linear\nbegin\n\nlemma independent_injective_on_span_image:\n  assumes iS: \"B.independent S\"\n    and fi: \"inj_on f (B.span S)\"\n  shows \"C.independent (f ` S)\"\nproof -\n  have l: \"linear (op *b) (op *c) f\"\n    by unfold_locales\n  {\n    fix a\n    assume a: \"a \\<in> S\" \"f a \\<in> C.span (f ` S - {f a})\"\n    have eq: \"f ` S - {f a} = f ` (S - {a})\"\n      using fi a B.span_inc by (auto simp add: inj_on_def)\n    from a have \"f a \\<in> f ` B.span (S -{a})\"\n      unfolding eq using B.span_linear_image[OF l] by auto\n    moreover have \"B.span (S - {a}) \\<subseteq> B.span S\"\n      using B.span_mono[of \"S - {a}\" S] by auto\n    ultimately have \"a \\<in> B.span (S - {a})\"\n      using fi a B.span_inc by (auto simp add: inj_on_def)\n    with a(1) iS have False\n      by (simp add: B.dependent_def)\n  }\n  then show ?thesis\n    unfolding dependent_def by blast\nqed\nend\n\ncontext vector_space\nbegin\nlemma subspace_Inter: \"\\<forall>s \\<in> f. subspace s \\<Longrightarrow> subspace (Inter f)\"\n  unfolding subspace_def by auto\n  \nlemma span_eq[simp]: \"span s = s \\<longleftrightarrow> subspace s\"\n  unfolding span_def by (rule hull_eq) (rule subspace_Inter)\nend\n\ncontext finite_dimensional_vector_space\nbegin  \nlemma subspace_dim_equal:\n  assumes \"subspace S\"\n    and \"subspace T\"\n    and \"S \\<subseteq> T\"\n    and \"dim S \\<ge> dim T\"\n  shows \"S = T\"\nproof -\n  obtain B where B: \"B \\<le> S\" \"independent B \\<and> S \\<subseteq> span B\" \"card B = dim S\"\n    using basis_exists[of S] by auto\n  then have \"span B \\<subseteq> S\"\n    using span_mono[of B S] span_eq[of S] assms by metis\n  then have \"span B = S\"\n    using B by auto\n  have \"dim S = dim T\"\n    using assms dim_subset[of S T] by auto\n  then have \"T \\<subseteq> span B\"\n    using card_eq_dim[of B T] B  assms \n    by (metis independent_bound_general subset_trans)\n  then show ?thesis\n    using assms `span B = S` by auto\nqed\nend\n(***************** Here ends the generalization of Convex_Euclidean_Space.thy *****************)\n\n(*********************** Generalized parts of the file Determinants.thy ***********************)\n\n(*Here I generalize some lemmas, from the class linordered_idom to a comm_ring_1.\n  Next proof follows the one presented in: http://hobbes.la.asu.edu/courses/site/442-f09/dets.pdf*)\nlemma det_identical_columns:\n  fixes A :: \"'a::{comm_ring_1}^'n^'n\"\n  assumes jk: \"j \\<noteq> k\"\n  and r: \"column j A = column k A\"\n  shows \"det A = 0\"\nproof -\nlet ?U=\"UNIV::'n set\"\nlet ?t_jk=\"Fun.swap j k id\"\nlet ?PU=\"{p. p permutes ?U}\"\nlet ?S1=\"{p. p\\<in>?PU \\<and> evenperm p}\"\nlet ?S2=\"{(?t_jk \\<circ> p) |p. p \\<in>?S1}\"\nlet ?f=\"\\<lambda>p. of_int (sign p) * (\\<Prod>i\\<in>UNIV. A $ i $ p i)\"\nlet ?g=\"\\<lambda>p. ?t_jk \\<circ> p\"\nhave g_S1: \"?S2 = ?g` ?S1\" by auto\nhave inj_g: \"inj_on ?g ?S1\" \n  proof (unfold inj_on_def, auto)\n      fix x y assume x: \"x permutes ?U\" and even_x: \"evenperm x\"\n        and y: \"y permutes ?U\" and even_y: \"evenperm y\" and eq: \"?t_jk \\<circ> x = ?t_jk \\<circ> y\"\n      show \"x = y\" by (metis (hide_lams, no_types) comp_assoc eq id_comp swap_id_idempotent)\n  qed\nhave tjk_permutes: \"?t_jk permutes ?U\" unfolding permutes_def swap_id_eq by (auto,metis)\nhave tjk_eq: \"\\<forall>i l. A $ i $ ?t_jk l  =  A $ i $ l\" \n  using r jk \n  unfolding column_def vec_eq_iff swap_id_eq by fastforce\nhave sign_tjk: \"sign ?t_jk = -1\" using sign_swap_id[of j k] jk by auto\n  {fix x\n   assume x: \"x\\<in> ?S1\"\n   have \"sign (?t_jk \\<circ> x) = sign (?t_jk) * sign x\"\n    by (metis (lifting) finite_class.finite_UNIV mem_Collect_eq \n        permutation_permutes permutation_swap_id sign_compose x)\n   also have \"... = - sign x\" using sign_tjk by simp\n   also have \"... \\<noteq> sign x\" unfolding sign_def by simp\n   finally have \"sign (?t_jk \\<circ> x) \\<noteq> sign x\" and \"(?t_jk \\<circ> x) \\<in> ?S2\"\n   by (auto, metis (lifting, full_types) mem_Collect_eq x)\n  }\nhence disjoint: \"?S1 \\<inter> ?S2 = {}\" by (auto, metis sign_def)\nhave PU_decomposition: \"?PU = ?S1 \\<union> ?S2\" \n  proof (auto)\n    fix x\n    assume x: \"x permutes ?U\" and \"\\<forall>p. p permutes ?U \\<longrightarrow> x = Fun.swap j k id \\<circ> p \\<longrightarrow> \\<not> evenperm p\"    \n    from this obtain p where p: \"p permutes UNIV\" and x_eq: \"x = Fun.swap j k id \\<circ> p\" \n      and odd_p: \"\\<not> evenperm p\"\n      by (metis (no_types) comp_assoc id_comp inv_swap_id permutes_compose \n          permutes_inv_o(1) tjk_permutes)\n    thus \"evenperm x\"\n      by (metis evenperm_comp evenperm_swap finite_class.finite_UNIV \n        jk permutation_permutes permutation_swap_id)\n   next\n   fix p assume p: \"p permutes ?U\"\n   show \"Fun.swap j k id \\<circ> p permutes UNIV\" by (metis p permutes_compose tjk_permutes)\nqed\nhave \"setsum ?f ?S2 = setsum ((\\<lambda>p. of_int (sign p) * (\\<Prod>i\\<in>UNIV. A $ i $ p i)) \n  \\<circ> op \\<circ> (Fun.swap j k id)) {p \\<in> {p. p permutes UNIV}. evenperm p}\"\n    unfolding g_S1 by (rule setsum.reindex[OF inj_g])\nalso have \"... = setsum (\\<lambda>p. of_int (sign (?t_jk \\<circ> p)) * (\\<Prod>i\\<in>UNIV. A $ i $ p i)) ?S1\"\n  unfolding o_def by (rule setsum.cong, auto simp add: tjk_eq)\nalso have \"... = setsum (\\<lambda>p. - ?f p) ?S1\"\n  proof (rule setsum.cong, auto)\n     fix x assume x: \"x permutes ?U\"\n     and even_x: \"evenperm x\"\n     hence perm_x: \"permutation x\" and perm_tjk: \"permutation ?t_jk\" \n      using permutation_permutes[of x] permutation_permutes[of ?t_jk] permutation_swap_id\n      by (metis finite_code)+\n     have \"(sign (?t_jk \\<circ> x)) = - (sign x)\" \n      unfolding sign_compose[OF perm_tjk perm_x] sign_tjk by auto\n     thus \"of_int (sign (?t_jk \\<circ> x)) * (\\<Prod>i\\<in>UNIV. A $ i $ x i) \n      = - (of_int (sign x) * (\\<Prod>i\\<in>UNIV. A $ i $ x i))\"\n      by auto\n  qed\nalso have \"...= - setsum ?f ?S1\" unfolding setsum_negf ..\nfinally have *: \"setsum ?f ?S2 = - setsum ?f ?S1\" .\nhave \"det A = (\\<Sum>p | p permutes UNIV. of_int (sign p) * (\\<Prod>i\\<in>UNIV. A $ i $ p i))\" \n  unfolding det_def ..\nalso have \"...= setsum ?f ?S1 + setsum ?f ?S2\"\n  by (subst PU_decomposition, rule setsum.union_disjoint[OF _ _ disjoint], auto)\nalso have \"...= setsum ?f ?S1 - setsum ?f ?S1 \" unfolding * by auto\nalso have \"...= 0\" by simp\nfinally show \"det A = 0\" by simp\nqed\n\n\nlemma det_identical_rows:\n  fixes A :: \"'a::{comm_ring_1}^'n^'n\"\n  assumes ij: \"i \\<noteq> j\"\n  and r: \"row i A = row j A\"\n  shows \"det A = 0\"\n  apply (subst det_transpose[symmetric])\n  apply (rule det_identical_columns[OF ij])\n  apply (metis column_transpose r)\n  done\n  \n(*The following two lemmas appear in the library with the restriction:\n\n  lemma 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\nNow I will do the proof over a field in general. But that is not a generalization, since integers\nare not a field, although they satisfy {idom, ring_char_0}. Nevertheless, in my case I'll work with\nZ/Z2 (the field of integers modulo 2), which are a field but not a {idom, ring_char_0}.*)  \n  \nlemma det_zero_row:\n  fixes A :: \"'a::{field}^'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 setsum.neutral)\n  apply (auto)\n  done\n  \n  \nlemma det_zero_column:\n  fixes A :: \"'a::{field}^'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_operation:\n  fixes A :: \"'a::{comm_ring_1}^'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 :: \"'a::{field}^'n^'n\"\n  assumes x: \"x \\<in> vec.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 vec.span_induct_alt[of ?P ?S, OF P0, folded scalar_mult_eq_scaleR])\n    apply blast\n    apply (rule x)\n    done\nqed\n\nlemma det_dependent_rows:\n  fixes A:: \"'a::{field}^'n^'n\"\n  assumes d: \"vec.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> vec.span (rows A - {row i A})\"\n    unfolding vec.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> vec.span {row j A|j. j \\<noteq> i}\"\n      apply (rule vec.span_neg)\n      apply (rule set_rev_mp)\n      apply (rule i)\n      apply (rule vec.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::'a\" \"\\<lambda>i. 1\"]\n    have \"det A = 0\" by simp\n  }\n  ultimately show ?thesis by blast\nqed\n\nlemma det_mul:\n  fixes A B :: \"'a::{comm_ring_1}^'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 \"(setsum (\\<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      (setsum (\\<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 setsum.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: \"setprod (\\<lambda>i. B$i$ q (inv p i)) ?U = setprod ((\\<lambda>i. B$i$ q (inv p i)) \\<circ> p) ?U\"\n        by (rule setprod_permute[OF p])\n      have thp: \"setprod (\\<lambda>i. (\\<chi> i. A$i$p i *s B$p i :: 'a^'n^'n) $i $ q i) ?U =\n        setprod (\\<lambda>i. A$i$p i) ?U * setprod (\\<lambda>i. B$i$ q (inv p i)) ?U\"\n          unfolding th001 setprod.distrib[symmetric] o_def permutes_inverses[OF p]\n          apply (rule setprod.cong[OF refl])\n          using permutes_in_image[OF q]\n          apply vector\n          done\n      show \"?s q * setprod (\\<lambda>i. (((\\<chi> i. A$i$p i *s B$p i) :: 'a^'n^'n)$i$q i)) ?U =\n        ?s p * (setprod (\\<lambda>i. A$i$p i) ?U) * (?s (q \\<circ> inv p) * setprod (\\<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: \"setsum (\\<lambda>f. det (\\<chi> i. A$i$f i *s B$f i)) ?PU = det A * det B\"\n    unfolding det_def setsum_product\n    by (rule setsum.cong[OF refl])\n  have \"det (A**B) = setsum (\\<lambda>f.  det (\\<chi> i. A $ i $ f i *s B $ f i)) ?F\"\n    unfolding matrix_mul_setsum_alt det_linear_rows_setsum[OF fU]\n    by simp\n  also have \"\\<dots> = setsum (\\<lambda>f. det (\\<chi> i. A$i$f i *s B$f i)) ?PU\"\n    using setsum.mono_neutral_cong_left[OF fF PUF zth, symmetric]\n    unfolding det_rows_mul by auto\n  finally show ?thesis unfolding th2 .\nqed\n\nlemma invertible_left_inverse:\n  fixes A :: \"'a::{field}^'n^'n\"\n  shows \"invertible A \\<longleftrightarrow> (\\<exists>(B::'a^'n^'n). B ** A = mat 1)\"\n  by (metis invertible_def matrix_left_right_inverse)\n\n  lemma invertible_righ_inverse:\n  fixes A :: \"'a::{field}^'n^'n\"\n  shows \"invertible A \\<longleftrightarrow> (\\<exists>(B::'a^'n^'n). A** B = mat 1)\"\n  by (metis invertible_def matrix_left_right_inverse)\n  \n  lemma invertible_det_nz:\n  fixes A::\"'a::{field}^'n^'n\"\n  shows \"invertible A \\<longleftrightarrow> det A \\<noteq> 0\"\nproof -\n  {\n    assume \"invertible A\"\n    then obtain B :: \"'a^'n^'n\" where B: \"A ** B = mat 1\"\n      unfolding invertible_righ_inverse by blast\n    then have \"det (A ** B) = det (mat 1 :: 'a^'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: \"setsum (\\<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::'a^'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 = setsum (\\<lambda>j. (1/ c i) *s (c j *s row j A)) (?U - {i})\"\n      unfolding setsum.remove[OF fU iU] setsum_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> vec.span {row j A| j. j \\<noteq> i}\"\n      unfolding thr0\n      apply (rule vec.span_setsum)\n      apply simp\n      apply (rule ballI)\n      apply (rule vec.span_mul [folded scalar_mult_eq_scaleR])+\n      apply (rule vec.span_superset)\n      apply auto\n      done\n    let ?B = \"(\\<chi> k. if k = i then 0 else row k A) :: 'a^'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(********************** Here ends the generalization of Determinants.thy **********************)\n\n(*Finally, some interesting theorems and interpretations that don't appear in any file of the \n  library.*)\n\nlocale linear_first_finite_dimensional_vector_space =\n  l: linear scaleB scaleC f +\n  B: finite_dimensional_vector_space scaleB BasisB + \n  C: vector_space scaleC \n  for scaleB :: \"('a::field => 'b::ab_group_add => 'b)\" (infixr \"*b\" 75)\n  and scaleC :: \"('a => 'c::ab_group_add => 'c)\" (infixr \"*c\" 75) \n  and BasisB :: \"('b set)\"\n  and f :: \"('b=>'c)\"  \n\ncontext linear_between_finite_dimensional_vector_spaces\nbegin\n  sublocale lblf: linear_first_finite_dimensional_vector_space by unfold_locales\nend\n  \nlemma vec_dim_card: \"vec.dim (UNIV::('a::{field}^'n) set) = CARD ('n)\"\nproof -\n  let ?f=\"\\<lambda>i::'n. axis i (1::'a)\"\n  have \"vec.dim (UNIV::('a::{field}^'n) set) = card (cart_basis::('a^'n) set)\" \n    unfolding vec.dim_UNIV ..\n  also have \"... = card ({i. i\\<in> UNIV}::('n) set)\"\n    proof (rule bij_betw_same_card[of ?f, symmetric], unfold bij_betw_def, auto)\n      show \"inj (\\<lambda>i::'n. axis i (1::'a))\"  by (simp add: inj_on_def axis_eq_axis)\n      fix i::'n\n      show \"axis i 1 \\<in> cart_basis\" unfolding cart_basis_def by auto\n      fix x::\"'a^'n\"\n      assume \"x \\<in> cart_basis\"\n      thus \"x \\<in> range (\\<lambda>i. axis i 1)\" unfolding cart_basis_def by auto\n    qed\n  also have \"... = CARD('n)\" by auto\n  finally show ?thesis .\nqed                   \n\ninterpretation vector_space_over_itself: vector_space \"op * :: 'a::field => 'a => 'a\" \n  by (unfold_locales, \n      auto intro: comm_semiring_1_class.normalizing_semiring_rules comm_semiring_class.distrib)\n\ninterpretation vector_space_over_itself: finite_dimensional_vector_space \n  \"op * :: 'a::field => 'a => 'a\" \"{1}\"  \nproof (unfold_locales, auto)\n (* interpret v: vector_space \"op * :: 'a::field => 'a => 'a\" by unfold_locales*) \n  have v: \"vector_space (op * :: 'a::field => 'a => 'a)\" by unfold_locales \n  fix x::'a\n  show \"x \\<in> vector_space.span (op *) {1::'a}\" unfolding vector_space.span_singleton[OF v] by auto  \nqed\n\nlemma dimension_eq_1[code_unfold]: \"vector_space_over_itself.dimension TYPE('a::field)= 1\"\n  unfolding vector_space_over_itself.dimension_def by simp\n\ninterpretation complex_over_reals: finite_dimensional_vector_space \"(op *\\<^sub>R)::real=>complex=>complex\" \n  \"{1, \\<i>}\"\nproof unfold_locales\nshow \"finite {1, \\<i>}\" by auto\nshow \"vector_space.independent (op *\\<^sub>R) {1, \\<i>}\"\n  by (metis Basis_complex_def euclidean_space.independent_Basis)\nshow \"vector_space.span (op *\\<^sub>R) {1, \\<i>} = UNIV\" \n  by (metis Basis_complex_def euclidean_space.span_Basis)\nqed\n\nlemma complex_over_reals_dimension[code_unfold]:\n  \"complex_over_reals.dimension = 2\" unfolding complex_over_reals.dimension_def by auto\n\nterm \"op *s\"\nterm \"op *\\<^sub>R\"\n\n(* The following definition will be very useful in our formalization. The problem was that \n  (op *\\<^sub>R) has type real=>'a=>'a but (op *s) has type 'a \\<Rightarrow> ('a, 'b) vec \\<Rightarrow> ('a, 'b) vec, \n  so we can't use (op *s) to multiply a matrix by a scalar.*) \n(*\n  definition 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*)\n\n(*One example of the use of *\\<^sub>R, *s and *k appears in the following theorem (obtained from AFP entry \n  about Tarski's Geometry, \n  see http://afp.sourceforge.net/browser_info/devel/AFP/Tarskis_Geometry/Linear_Algebra2.html)*)\n(*\n  lemma scalar_matrix_vector_assoc:\n  fixes A :: \"real^('m::finite)^('n::finite)\"\n  shows \"k *\\<^sub>R (A *v v) = k *\\<^sub>R A *v v\"*)\n  \n(*Now, the generalization of the statement would be: *)\n\n(*\n  lemma scalar_matrix_vector_assoc:\n  fixes A :: \"'a::{field}^'m^'n\"\n  shows \"k *s (A *v v) = k *k A *v v\"\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/Generalizations.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970904940926, "lm_q2_score": 0.8354835350552603, "lm_q1q2_score": 0.7358914668323925}}
{"text": "theory quantifiers\n  imports \"../boolean_algebra/boolean_algebra_infinitary\"\nbegin\n\nsubsection \\<open>Encoding quantifiers (restricted and unrestricted)\\<close>\n\n(*Introduce pedagogically convenient notation*)\nnotation HOL.All (\"\\<Pi>\") notation HOL.Ex (\"\\<Sigma>\")\n\n(**Let us recall that in HOL we have: *)\nlemma \"(\\<forall>x. P) = \\<Pi>(\\<lambda>x. P)\" by simp\nlemma \"(\\<exists>x. P) = \\<Sigma>(\\<lambda>x. P)\" by simp\nlemma \"\\<Sigma> = (\\<lambda>P. \\<not>\\<Pi>(\\<lambda>x. \\<not>P x))\" by simp\n\n(**We can introduce their respective 'w-type-lifted variants as follows: *)\ndefinition mforall::\"('i\\<Rightarrow>'w \\<sigma>)\\<Rightarrow>'w \\<sigma>\" (\"\\<^bold>\\<Pi>_\")\n  where \"\\<^bold>\\<Pi>\\<phi> \\<equiv> \\<lambda>w. \\<forall>X. \\<phi> X w\"\ndefinition mexists::\"('i\\<Rightarrow>'w \\<sigma>)\\<Rightarrow>'w \\<sigma>\" (\"\\<^bold>\\<Sigma>_\") \n  where \"\\<^bold>\\<Sigma>\\<phi> \\<equiv> \\<lambda>w. \\<exists>X. \\<phi> X w\"\n\n(**To improve readability, we introduce for them standard binder notation.*)\nnotation mforall (binder \"\\<^bold>\\<forall>\" [48]49)  notation mexists (binder \"\\<^bold>\\<exists>\" [48]49) \n\n(**And thus we obtain the 'w-type-lifted variant of the standard (variable-binding) quantifiers*)\nlemma \"(\\<^bold>\\<forall>X. \\<phi>) = \\<^bold>\\<Pi>(\\<lambda>X. \\<phi>)\" by (simp add: mforall_def)\nlemma \"(\\<^bold>\\<exists>X. \\<phi>) = \\<^bold>\\<Sigma>(\\<lambda>X. \\<phi>)\" by (simp add: mexists_def)\n\n(**Quantifiers are dual to each other in the expected way*)\nlemma \"\\<^bold>\\<Pi>\\<phi> = \\<^bold>\\<midarrow>(\\<^bold>\\<Sigma>\\<phi>\\<^sup>c)\" by (simp add: compl_def mexists_def mforall_def svfun_compl_def)\nlemma \"(\\<^bold>\\<forall>X. \\<phi> X) = \\<^bold>\\<midarrow>(\\<^bold>\\<exists>X. \\<^bold>\\<midarrow>(\\<phi> X))\" by (simp add: compl_def mexists_def mforall_def)\n\n(**Relationship between quantifiers and the infinitary supremum and infimum operations*)\nlemma mforall_char: \"\\<^bold>\\<Pi>\\<phi> = \\<^bold>\\<And>\\<lbrakk>\\<phi> _\\<rbrakk>\" unfolding infimum_def mforall_def range_def by metis\nlemma mexists_char:  \"\\<^bold>\\<Sigma>\\<phi> = \\<^bold>\\<Or>\\<lbrakk>\\<phi> _\\<rbrakk>\" unfolding supremum_def mexists_def range_def by metis\n\n(*or, in other words*)\nlemma mforallb_char: \"(\\<^bold>\\<forall>X. \\<phi>) = \\<^bold>\\<And>\\<lbrakk>(\\<lambda>X. \\<phi>) _\\<rbrakk>\" unfolding infimum_def mforall_def range_def by simp\nlemma mexistsb_char: \"(\\<^bold>\\<exists>X. \\<phi>) = \\<^bold>\\<Or>\\<lbrakk>(\\<lambda>X. \\<phi>) _\\<rbrakk>\" unfolding supremum_def mexists_def range_def by simp\n\n\n(**Restricted quantification*)\n\n(**Constant domains: first generalization of quantifiers above (e.g. free logic)*)\ndefinition mforall_const::\"'i \\<sigma> \\<Rightarrow> ('i \\<Rightarrow> 'w \\<sigma>) \\<Rightarrow> 'w \\<sigma>\" (\"\\<^bold>\\<Pi>[_]_\") \n  where \"\\<^bold>\\<Pi>[D]\\<phi> \\<equiv> \\<lambda>w. \\<forall>X. (D X) \\<longrightarrow> (\\<phi> X) w\" \ndefinition mexists_const::\"'i \\<sigma> \\<Rightarrow> ('i \\<Rightarrow> 'w \\<sigma>) \\<Rightarrow> 'w \\<sigma>\" (\"\\<^bold>\\<Sigma>[_]_\") \n  where \"\\<^bold>\\<Sigma>[D]\\<phi> \\<equiv> \\<lambda>w. \\<exists>X. (D X)  \\<and>  (\\<phi> X) w\"\n\n(**Alas! the convenient binder notation cannot be easily introduced for restricted quantifiers*)\n\n(**Constant-domain quantification generalises its unrestricted counterpart*)\nlemma \"\\<^bold>\\<Pi>\\<phi> = \\<^bold>\\<Pi>[\\<^bold>\\<top>]\\<phi>\" by (simp add: mforall_const_def mforall_def top_def)\nlemma \"\\<^bold>\\<Sigma>\\<phi> = \\<^bold>\\<Sigma>[\\<^bold>\\<top>]\\<phi>\" by (simp add: mexists_const_def mexists_def top_def)\n\n(**Constant-domain quantification can also be characterised using infimum and supremum*)\nlemma mforall_const_char: \"\\<^bold>\\<Pi>[D]\\<phi> = \\<^bold>\\<And>\\<lbrakk>\\<phi> D\\<rbrakk>\" unfolding image_def infimum_def mforall_const_def by metis\nlemma mexists_const_char: \"\\<^bold>\\<Sigma>[D]\\<phi> = \\<^bold>\\<Or>\\<lbrakk>\\<phi> D\\<rbrakk>\" unfolding image_def supremum_def mexists_const_def by metis\n\n(**Constant-domain quantifiers also  allow us to nicely characterize the interaction between\n function composition and (restricted) quantification:*)\nlemma mforall_comp: \"\\<^bold>\\<Pi>(\\<phi>\\<circ>\\<psi>) = \\<^bold>\\<Pi>[\\<lbrakk>\\<psi> _\\<rbrakk>] \\<phi>\" unfolding fun_comp_def mforall_const_def mforall_def range_def by metis\nlemma mexists_comp: \"\\<^bold>\\<Sigma>(\\<phi>\\<circ>\\<psi>) = \\<^bold>\\<Sigma>[\\<lbrakk>\\<psi> _\\<rbrakk>] \\<phi>\" unfolding fun_comp_def mexists_const_def mexists_def range_def by metis\n\n\n(**Varying domains: we can also restrict quantifiers by taking a 'functional domain' as additional parameter.\nThe latter is a set-valued mapping each element 'i to a set of points (e.g. where it 'exists').*)\ndefinition mforall_var::\"('i \\<Rightarrow> 'w \\<sigma>) \\<Rightarrow> ('i \\<Rightarrow> 'w \\<sigma>) \\<Rightarrow> 'w \\<sigma>\" (\"\\<^bold>\\<Pi>{_}_\") \n  where \"\\<^bold>\\<Pi>{\\<psi>}\\<phi> \\<equiv> \\<lambda>w. \\<forall>X. (\\<psi> X) w \\<longrightarrow> (\\<phi> X) w\" \ndefinition mexists_var::\"('i \\<Rightarrow> 'w \\<sigma>) \\<Rightarrow> ('i \\<Rightarrow> 'w \\<sigma>) \\<Rightarrow> 'w \\<sigma>\" (\"\\<^bold>\\<Sigma>{_}_\") \n  where \"\\<^bold>\\<Sigma>{\\<psi>}\\<phi> \\<equiv> \\<lambda>w. \\<exists>X. (\\<psi> X) w  \\<and>  (\\<phi> X) w\"\n\n(**Varying-domain quantification generalises its constant-domain counterpart*)\n\nlemma \"\\<^bold>\\<Pi>[D]\\<phi> = \\<^bold>\\<Pi>{D\\<up>}\\<phi>\" by (simp add: mforall_const_def mforall_var_def)\nlemma \"\\<^bold>\\<Sigma>[D]\\<phi> = \\<^bold>\\<Sigma>{D\\<up>}\\<phi>\" by (simp add: mexists_const_def mexists_var_def)\n\n(**Restricted quantifiers are dual to each other in the expected way*)\nlemma \"\\<^bold>\\<Pi>[D]\\<phi> = \\<^bold>\\<midarrow>(\\<^bold>\\<Sigma>[D]\\<phi>\\<^sup>c)\" by (metis iDM_b im_prop2 mexists_const_char mforall_const_char setequ_ext)\nlemma \"\\<^bold>\\<Pi>{\\<psi>}\\<phi> = \\<^bold>\\<midarrow>(\\<^bold>\\<Sigma>{\\<psi>}\\<phi>\\<^sup>c)\" by (simp add: compl_def mexists_var_def mforall_var_def svfun_compl_def)\n\n\n(**We can use 2nd-order connectives on set-valued functions to encode restricted quantifiers as unrestricted*)\nlemma \"\\<^bold>\\<Pi>{\\<psi>}\\<phi> = \\<^bold>\\<Pi>(\\<psi> \\<^bold>\\<sqsupset> \\<phi>)\" by (simp add: impl_def mforall_def mforall_var_def svfun_impl_def)\nlemma \"\\<^bold>\\<Sigma>{\\<psi>}\\<phi> = \\<^bold>\\<Sigma>(\\<psi> \\<^bold>\\<sqinter> \\<phi>)\" by (simp add: meet_def mexists_def mexists_var_def svfun_meet_def)\n\n(**Observe that using these operators has the advantage of allowing for binder notation,*)\nlemma \"\\<^bold>\\<Pi>{\\<psi>}\\<phi> = (\\<^bold>\\<forall>X. (\\<psi> \\<^bold>\\<sqsupset> \\<phi>) X)\" by (simp add: impl_def mforall_def mforall_var_def svfun_impl_def)\nlemma \"\\<^bold>\\<Sigma>{\\<psi>}\\<phi> = (\\<^bold>\\<exists>X. (\\<psi> \\<^bold>\\<sqinter> \\<phi>) X)\" by (simp add: meet_def mexists_def mexists_var_def svfun_meet_def)\n\n(**So to sumarize: different sorts of restricted quantification can be emulated \n  by employing 2nd-order operations to adequately relativise predicates: *)\n\nlemma \"\\<^bold>\\<Pi>[D]\\<phi> = (\\<^bold>\\<forall>X. (D\\<up> \\<^bold>\\<sqsupset> \\<phi>) X)\" by (simp add: impl_def mforall_const_def mforall_def svfun_impl_def)\nlemma \"\\<^bold>\\<Pi>{\\<^bold>\\<top>'}\\<phi> = (\\<^bold>\\<forall>X. (\\<^bold>\\<top>' \\<^bold>\\<sqsupset> \\<phi>) X)\" by (simp add: impl_def mforall_def mforall_var_def svfun_impl_def)\nlemma \"\\<^bold>\\<Pi>\\<phi> = \\<^bold>\\<Pi>{\\<^bold>\\<top>'}\\<phi>\" by (simp add: mforall_def mforall_var_def svfun_top_def top_def)\nlemma \"(\\<^bold>\\<forall>X. \\<phi> X) = \\<^bold>\\<Pi>{\\<^bold>\\<top>'}\\<phi>\" by (simp add: mforall_def mforall_var_def svfun_top_def top_def)\n\nnamed_theorems quant (*to group together definitions related to quantification*)\ndeclare mforall_def[quant] mexists_def[quant]\n        mforall_const_def[quant] mexists_const_def[quant]\n        mforall_var_def[quant] mexists_var_def[quant]\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/logics/quantifiers.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8807970779778824, "lm_q2_score": 0.8354835330070838, "lm_q1q2_score": 0.735891454571277}}
{"text": "(*  Title:      HOL/Hahn_Banach/Subspace.thy\n    Author:     Gertrud Bauer, TU Munich\n*)\n\nsection \\<open>Subspaces\\<close>\n\ntheory Subspace\nimports Vector_Space \"HOL-Library.Set_Algebras\"\nbegin\n\nsubsection \\<open>Definition\\<close>\n\ntext \\<open>\n  A non-empty subset \\<open>U\\<close> of a vector space \\<open>V\\<close> is a \\<^emph>\\<open>subspace\\<close> of \\<open>V\\<close>, iff\n  \\<open>U\\<close> is closed under addition and scalar multiplication.\n\\<close>\n\nlocale subspace =\n  fixes U :: \"'a::{minus, plus, zero, uminus} set\" and V\n  assumes non_empty [iff, intro]: \"U \\<noteq> {}\"\n    and subset [iff]: \"U \\<subseteq> V\"\n    and add_closed [iff]: \"x \\<in> U \\<Longrightarrow> y \\<in> U \\<Longrightarrow> x + y \\<in> U\"\n    and mult_closed [iff]: \"x \\<in> U \\<Longrightarrow> a \\<cdot> x \\<in> U\"\n\nnotation (symbols)\n  subspace  (infix \"\\<unlhd>\" 50)\n\ndeclare vectorspace.intro [intro?] subspace.intro [intro?]\n\nlemma subspace_subset [elim]: \"U \\<unlhd> V \\<Longrightarrow> U \\<subseteq> V\"\n  by (rule subspace.subset)\n\nlemma (in subspace) subsetD [iff]: \"x \\<in> U \\<Longrightarrow> x \\<in> V\"\n  using subset by blast\n\nlemma subspaceD [elim]: \"U \\<unlhd> V \\<Longrightarrow> x \\<in> U \\<Longrightarrow> x \\<in> V\"\n  by (rule subspace.subsetD)\n\nlemma rev_subspaceD [elim?]: \"x \\<in> U \\<Longrightarrow> U \\<unlhd> V \\<Longrightarrow> x \\<in> V\"\n  by (rule subspace.subsetD)\n\nlemma (in subspace) diff_closed [iff]:\n  assumes \"vectorspace V\"\n  assumes x: \"x \\<in> U\" and y: \"y \\<in> U\"\n  shows \"x - y \\<in> U\"\nproof -\n  interpret vectorspace V by fact\n  from x y show ?thesis by (simp add: diff_eq1 negate_eq1)\nqed\n\ntext \\<open>\n  \\<^medskip>\n  Similar as for linear spaces, the existence of the zero element in every\n  subspace follows from the non-emptiness of the carrier set and by vector\n  space laws.\n\\<close>\n\nlemma (in subspace) zero [intro]:\n  assumes \"vectorspace V\"\n  shows \"0 \\<in> U\"\nproof -\n  interpret V: vectorspace V by fact\n  have \"U \\<noteq> {}\" by (rule non_empty)\n  then obtain x where x: \"x \\<in> U\" by blast\n  then have \"x \\<in> V\" .. then have \"0 = x - x\" by simp\n  also from \\<open>vectorspace V\\<close> x x have \"\\<dots> \\<in> U\" by (rule diff_closed)\n  finally show ?thesis .\nqed\n\nlemma (in subspace) neg_closed [iff]:\n  assumes \"vectorspace V\"\n  assumes x: \"x \\<in> U\"\n  shows \"- x \\<in> U\"\nproof -\n  interpret vectorspace V by fact\n  from x show ?thesis by (simp add: negate_eq1)\nqed\n\ntext \\<open>\\<^medskip> Further derived laws: every subspace is a vector space.\\<close>\n\nlemma (in subspace) vectorspace [iff]:\n  assumes \"vectorspace V\"\n  shows \"vectorspace U\"\nproof -\n  interpret vectorspace V by fact\n  show ?thesis\n  proof\n    show \"U \\<noteq> {}\" ..\n    fix x y z assume x: \"x \\<in> U\" and y: \"y \\<in> U\" and z: \"z \\<in> U\"\n    fix a b :: real\n    from x y show \"x + y \\<in> U\" by simp\n    from x show \"a \\<cdot> x \\<in> U\" by simp\n    from x y z show \"(x + y) + z = x + (y + z)\" by (simp add: add_ac)\n    from x y show \"x + y = y + x\" by (simp add: add_ac)\n    from x show \"x - x = 0\" by simp\n    from x show \"0 + x = x\" by simp\n    from x y show \"a \\<cdot> (x + y) = a \\<cdot> x + a \\<cdot> y\" by (simp add: distrib)\n    from x show \"(a + b) \\<cdot> x = a \\<cdot> x + b \\<cdot> x\" by (simp add: distrib)\n    from x show \"(a * b) \\<cdot> x = a \\<cdot> b \\<cdot> x\" by (simp add: mult_assoc)\n    from x show \"1 \\<cdot> x = x\" by simp\n    from x show \"- x = - 1 \\<cdot> x\" by (simp add: negate_eq1)\n    from x y show \"x - y = x + - y\" by (simp add: diff_eq1)\n  qed\nqed\n\n\ntext \\<open>The subspace relation is reflexive.\\<close>\n\nlemma (in vectorspace) subspace_refl [intro]: \"V \\<unlhd> V\"\nproof\n  show \"V \\<noteq> {}\" ..\n  show \"V \\<subseteq> V\" ..\nnext\n  fix x y assume x: \"x \\<in> V\" and y: \"y \\<in> V\"\n  fix a :: real\n  from x y show \"x + y \\<in> V\" by simp\n  from x show \"a \\<cdot> x \\<in> V\" by simp\nqed\n\ntext \\<open>The subspace relation is transitive.\\<close>\n\nlemma (in vectorspace) subspace_trans [trans]:\n  \"U \\<unlhd> V \\<Longrightarrow> V \\<unlhd> W \\<Longrightarrow> U \\<unlhd> W\"\nproof\n  assume uv: \"U \\<unlhd> V\" and vw: \"V \\<unlhd> W\"\n  from uv show \"U \\<noteq> {}\" by (rule subspace.non_empty)\n  show \"U \\<subseteq> W\"\n  proof -\n    from uv have \"U \\<subseteq> V\" by (rule subspace.subset)\n    also from vw have \"V \\<subseteq> W\" by (rule subspace.subset)\n    finally show ?thesis .\n  qed\n  fix x y assume x: \"x \\<in> U\" and y: \"y \\<in> U\"\n  from uv and x y show \"x + y \\<in> U\" by (rule subspace.add_closed)\n  from uv and x show \"a \\<cdot> x \\<in> U\" for a by (rule subspace.mult_closed)\nqed\n\n\nsubsection \\<open>Linear closure\\<close>\n\ntext \\<open>\n  The \\<^emph>\\<open>linear closure\\<close> of a vector \\<open>x\\<close> is the set of all scalar multiples of\n  \\<open>x\\<close>.\n\\<close>\n\ndefinition lin :: \"('a::{minus,plus,zero}) \\<Rightarrow> 'a set\"\n  where \"lin x = {a \\<cdot> x | a. True}\"\n\nlemma linI [intro]: \"y = a \\<cdot> x \\<Longrightarrow> y \\<in> lin x\"\n  unfolding lin_def by blast\n\nlemma linI' [iff]: \"a \\<cdot> x \\<in> lin x\"\n  unfolding lin_def by blast\n\nlemma linE [elim]:\n  assumes \"x \\<in> lin v\"\n  obtains a :: real where \"x = a \\<cdot> v\"\n  using assms unfolding lin_def by blast\n\n\ntext \\<open>Every vector is contained in its linear closure.\\<close>\n\nlemma (in vectorspace) x_lin_x [iff]: \"x \\<in> V \\<Longrightarrow> x \\<in> lin x\"\nproof -\n  assume \"x \\<in> V\"\n  then have \"x = 1 \\<cdot> x\" by simp\n  also have \"\\<dots> \\<in> lin x\" ..\n  finally show ?thesis .\nqed\n\nlemma (in vectorspace) \"0_lin_x\" [iff]: \"x \\<in> V \\<Longrightarrow> 0 \\<in> lin x\"\nproof\n  assume \"x \\<in> V\"\n  then show \"0 = 0 \\<cdot> x\" by simp\nqed\n\ntext \\<open>Any linear closure is a subspace.\\<close>\n\nlemma (in vectorspace) lin_subspace [intro]:\n  assumes x: \"x \\<in> V\"\n  shows \"lin x \\<unlhd> V\"\nproof\n  from x show \"lin x \\<noteq> {}\" by auto\nnext\n  show \"lin x \\<subseteq> V\"\n  proof\n    fix x' assume \"x' \\<in> lin x\"\n    then obtain a where \"x' = a \\<cdot> x\" ..\n    with x show \"x' \\<in> V\" by simp\n  qed\nnext\n  fix x' x'' assume x': \"x' \\<in> lin x\" and x'': \"x'' \\<in> lin x\"\n  show \"x' + x'' \\<in> lin x\"\n  proof -\n    from x' obtain a' where \"x' = a' \\<cdot> x\" ..\n    moreover from x'' obtain a'' where \"x'' = a'' \\<cdot> x\" ..\n    ultimately have \"x' + x'' = (a' + a'') \\<cdot> x\"\n      using x by (simp add: distrib)\n    also have \"\\<dots> \\<in> lin x\" ..\n    finally show ?thesis .\n  qed\n  fix a :: real\n  show \"a \\<cdot> x' \\<in> lin x\"\n  proof -\n    from x' obtain a' where \"x' = a' \\<cdot> x\" ..\n    with x have \"a \\<cdot> x' = (a * a') \\<cdot> x\" by (simp add: mult_assoc)\n    also have \"\\<dots> \\<in> lin x\" ..\n    finally show ?thesis .\n  qed\nqed\n\n\ntext \\<open>Any linear closure is a vector space.\\<close>\n\nlemma (in vectorspace) lin_vectorspace [intro]:\n  assumes \"x \\<in> V\"\n  shows \"vectorspace (lin x)\"\nproof -\n  from \\<open>x \\<in> V\\<close> have \"subspace (lin x) V\"\n    by (rule lin_subspace)\n  from this and vectorspace_axioms show ?thesis\n    by (rule subspace.vectorspace)\nqed\n\n\nsubsection \\<open>Sum of two vectorspaces\\<close>\n\ntext \\<open>\n  The \\<^emph>\\<open>sum\\<close> of two vectorspaces \\<open>U\\<close> and \\<open>V\\<close> is the set of all sums of\n  elements from \\<open>U\\<close> and \\<open>V\\<close>.\n\\<close>\n\nlemma sum_def: \"U + V = {u + v | u v. u \\<in> U \\<and> v \\<in> V}\"\n  unfolding set_plus_def by auto\n\nlemma sumE [elim]:\n    \"x \\<in> U + V \\<Longrightarrow> (\\<And>u v. x = u + v \\<Longrightarrow> u \\<in> U \\<Longrightarrow> v \\<in> V \\<Longrightarrow> C) \\<Longrightarrow> C\"\n  unfolding sum_def by blast\n\nlemma sumI [intro]:\n    \"u \\<in> U \\<Longrightarrow> v \\<in> V \\<Longrightarrow> x = u + v \\<Longrightarrow> x \\<in> U + V\"\n  unfolding sum_def by blast\n\nlemma sumI' [intro]:\n    \"u \\<in> U \\<Longrightarrow> v \\<in> V \\<Longrightarrow> u + v \\<in> U + V\"\n  unfolding sum_def by blast\n\ntext \\<open>\\<open>U\\<close> is a subspace of \\<open>U + V\\<close>.\\<close>\n\nlemma subspace_sum1 [iff]:\n  assumes \"vectorspace U\" \"vectorspace V\"\n  shows \"U \\<unlhd> U + V\"\nproof -\n  interpret vectorspace U by fact\n  interpret vectorspace V by fact\n  show ?thesis\n  proof\n    show \"U \\<noteq> {}\" ..\n    show \"U \\<subseteq> U + V\"\n    proof\n      fix x assume x: \"x \\<in> U\"\n      moreover have \"0 \\<in> V\" ..\n      ultimately have \"x + 0 \\<in> U + V\" ..\n      with x show \"x \\<in> U + V\" by simp\n    qed\n    fix x y assume x: \"x \\<in> U\" and \"y \\<in> U\"\n    then show \"x + y \\<in> U\" by simp\n    from x show \"a \\<cdot> x \\<in> U\" for a by simp\n  qed\nqed\n\ntext \\<open>The sum of two subspaces is again a subspace.\\<close>\n\nlemma sum_subspace [intro?]:\n  assumes \"subspace U E\" \"vectorspace E\" \"subspace V E\"\n  shows \"U + V \\<unlhd> E\"\nproof -\n  interpret subspace U E by fact\n  interpret vectorspace E by fact\n  interpret subspace V E by fact\n  show ?thesis\n  proof\n    have \"0 \\<in> U + V\"\n    proof\n      show \"0 \\<in> U\" using \\<open>vectorspace E\\<close> ..\n      show \"0 \\<in> V\" using \\<open>vectorspace E\\<close> ..\n      show \"(0::'a) = 0 + 0\" by simp\n    qed\n    then show \"U + V \\<noteq> {}\" by blast\n    show \"U + V \\<subseteq> E\"\n    proof\n      fix x assume \"x \\<in> U + V\"\n      then obtain u v where \"x = u + v\" and\n        \"u \\<in> U\" and \"v \\<in> V\" ..\n      then show \"x \\<in> E\" by simp\n    qed\n  next\n    fix x y assume x: \"x \\<in> U + V\" and y: \"y \\<in> U + V\"\n    show \"x + y \\<in> U + V\"\n    proof -\n      from x obtain ux vx where \"x = ux + vx\" and \"ux \\<in> U\" and \"vx \\<in> V\" ..\n      moreover\n      from y obtain uy vy where \"y = uy + vy\" and \"uy \\<in> U\" and \"vy \\<in> V\" ..\n      ultimately\n      have \"ux + uy \\<in> U\"\n        and \"vx + vy \\<in> V\"\n        and \"x + y = (ux + uy) + (vx + vy)\"\n        using x y by (simp_all add: add_ac)\n      then show ?thesis ..\n    qed\n    fix a show \"a \\<cdot> x \\<in> U + V\"\n    proof -\n      from x obtain u v where \"x = u + v\" and \"u \\<in> U\" and \"v \\<in> V\" ..\n      then have \"a \\<cdot> u \\<in> U\" and \"a \\<cdot> v \\<in> V\"\n        and \"a \\<cdot> x = (a \\<cdot> u) + (a \\<cdot> v)\" by (simp_all add: distrib)\n      then show ?thesis ..\n    qed\n  qed\nqed\n\ntext \\<open>The sum of two subspaces is a vectorspace.\\<close>\n\nlemma sum_vs [intro?]:\n    \"U \\<unlhd> E \\<Longrightarrow> V \\<unlhd> E \\<Longrightarrow> vectorspace E \\<Longrightarrow> vectorspace (U + V)\"\n  by (rule subspace.vectorspace) (rule sum_subspace)\n\n\nsubsection \\<open>Direct sums\\<close>\n\ntext \\<open>\n  The sum of \\<open>U\\<close> and \\<open>V\\<close> is called \\<^emph>\\<open>direct\\<close>, iff the zero element is the only\n  common element of \\<open>U\\<close> and \\<open>V\\<close>. For every element \\<open>x\\<close> of the direct sum of\n  \\<open>U\\<close> and \\<open>V\\<close> the decomposition in \\<open>x = u + v\\<close> with \\<open>u \\<in> U\\<close> and \\<open>v \\<in> V\\<close> is\n  unique.\n\\<close>\n\nlemma decomp:\n  assumes \"vectorspace E\" \"subspace U E\" \"subspace V E\"\n  assumes direct: \"U \\<inter> V = {0}\"\n    and u1: \"u1 \\<in> U\" and u2: \"u2 \\<in> U\"\n    and v1: \"v1 \\<in> V\" and v2: \"v2 \\<in> V\"\n    and sum: \"u1 + v1 = u2 + v2\"\n  shows \"u1 = u2 \\<and> v1 = v2\"\nproof -\n  interpret vectorspace E by fact\n  interpret subspace U E by fact\n  interpret subspace V E by fact\n  show ?thesis\n  proof\n    have U: \"vectorspace U\"  (* FIXME: use interpret *)\n      using \\<open>subspace U E\\<close> \\<open>vectorspace E\\<close> by (rule subspace.vectorspace)\n    have V: \"vectorspace V\"\n      using \\<open>subspace V E\\<close> \\<open>vectorspace E\\<close> by (rule subspace.vectorspace)\n    from u1 u2 v1 v2 and sum have eq: \"u1 - u2 = v2 - v1\"\n      by (simp add: add_diff_swap)\n    from u1 u2 have u: \"u1 - u2 \\<in> U\"\n      by (rule vectorspace.diff_closed [OF U])\n    with eq have v': \"v2 - v1 \\<in> U\" by (simp only:)\n    from v2 v1 have v: \"v2 - v1 \\<in> V\"\n      by (rule vectorspace.diff_closed [OF V])\n    with eq have u': \" u1 - u2 \\<in> V\" by (simp only:)\n    \n    show \"u1 = u2\"\n    proof (rule add_minus_eq)\n      from u1 show \"u1 \\<in> E\" ..\n      from u2 show \"u2 \\<in> E\" ..\n      from u u' and direct show \"u1 - u2 = 0\" by blast\n    qed\n    show \"v1 = v2\"\n    proof (rule add_minus_eq [symmetric])\n      from v1 show \"v1 \\<in> E\" ..\n      from v2 show \"v2 \\<in> E\" ..\n      from v v' and direct show \"v2 - v1 = 0\" by blast\n    qed\n  qed\nqed\n\ntext \\<open>\n  An application of the previous lemma will be used in the proof of the\n  Hahn-Banach Theorem (see page \\pageref{decomp-H-use}): for any element\n  \\<open>y + a \\<cdot> x\\<^sub>0\\<close> of the direct sum of a vectorspace \\<open>H\\<close> and the linear closure\n  of \\<open>x\\<^sub>0\\<close> the components \\<open>y \\<in> H\\<close> and \\<open>a\\<close> are uniquely determined.\n\\<close>\n\nlemma decomp_H':\n  assumes \"vectorspace E\" \"subspace H E\"\n  assumes y1: \"y1 \\<in> H\" and y2: \"y2 \\<in> H\"\n    and x': \"x' \\<notin> H\"  \"x' \\<in> E\"  \"x' \\<noteq> 0\"\n    and eq: \"y1 + a1 \\<cdot> x' = y2 + a2 \\<cdot> x'\"\n  shows \"y1 = y2 \\<and> a1 = a2\"\nproof -\n  interpret vectorspace E by fact\n  interpret subspace H E by fact\n  show ?thesis\n  proof\n    have c: \"y1 = y2 \\<and> a1 \\<cdot> x' = a2 \\<cdot> x'\"\n    proof (rule decomp)\n      show \"a1 \\<cdot> x' \\<in> lin x'\" ..\n      show \"a2 \\<cdot> x' \\<in> lin x'\" ..\n      show \"H \\<inter> lin x' = {0}\"\n      proof\n        show \"H \\<inter> lin x' \\<subseteq> {0}\"\n        proof\n          fix x assume x: \"x \\<in> H \\<inter> lin x'\"\n          then obtain a where xx': \"x = a \\<cdot> x'\"\n            by blast\n          have \"x = 0\"\n          proof cases\n            assume \"a = 0\"\n            with xx' and x' show ?thesis by simp\n          next\n            assume a: \"a \\<noteq> 0\"\n            from x have \"x \\<in> H\" ..\n            with xx' have \"inverse a \\<cdot> a \\<cdot> x' \\<in> H\" by simp\n            with a and x' have \"x' \\<in> H\" by (simp add: mult_assoc2)\n            with \\<open>x' \\<notin> H\\<close> show ?thesis by contradiction\n          qed\n          then show \"x \\<in> {0}\" ..\n        qed\n        show \"{0} \\<subseteq> H \\<inter> lin x'\"\n        proof -\n          have \"0 \\<in> H\" using \\<open>vectorspace E\\<close> ..\n          moreover have \"0 \\<in> lin x'\" using \\<open>x' \\<in> E\\<close> ..\n          ultimately show ?thesis by blast\n        qed\n      qed\n      show \"lin x' \\<unlhd> E\" using \\<open>x' \\<in> E\\<close> ..\n    qed (rule \\<open>vectorspace E\\<close>, rule \\<open>subspace H E\\<close>, rule y1, rule y2, rule eq)\n    then show \"y1 = y2\" ..\n    from c have \"a1 \\<cdot> x' = a2 \\<cdot> x'\" ..\n    with x' show \"a1 = a2\" by (simp add: mult_right_cancel)\n  qed\nqed\n\ntext \\<open>\n  Since for any element \\<open>y + a \\<cdot> x'\\<close> of the direct sum of a vectorspace \\<open>H\\<close>\n  and the linear closure of \\<open>x'\\<close> the components \\<open>y \\<in> H\\<close> and \\<open>a\\<close> are unique, it\n  follows from \\<open>y \\<in> H\\<close> that \\<open>a = 0\\<close>.\n\\<close>\n\nlemma decomp_H'_H:\n  assumes \"vectorspace E\" \"subspace H E\"\n  assumes t: \"t \\<in> H\"\n    and x': \"x' \\<notin> H\"  \"x' \\<in> E\"  \"x' \\<noteq> 0\"\n  shows \"(SOME (y, a). t = y + a \\<cdot> x' \\<and> y \\<in> H) = (t, 0)\"\nproof -\n  interpret vectorspace E by fact\n  interpret subspace H E by fact\n  show ?thesis\n  proof (rule, simp_all only: split_paired_all split_conv)\n    from t x' show \"t = t + 0 \\<cdot> x' \\<and> t \\<in> H\" by simp\n    fix y and a assume ya: \"t = y + a \\<cdot> x' \\<and> y \\<in> H\"\n    have \"y = t \\<and> a = 0\"\n    proof (rule decomp_H')\n      from ya x' show \"y + a \\<cdot> x' = t + 0 \\<cdot> x'\" by simp\n      from ya show \"y \\<in> H\" ..\n    qed (rule \\<open>vectorspace E\\<close>, rule \\<open>subspace H E\\<close>, rule t, (rule x')+)\n    with t x' show \"(y, a) = (y + a \\<cdot> x', 0)\" by simp\n  qed\nqed\n\ntext \\<open>\n  The components \\<open>y \\<in> H\\<close> and \\<open>a\\<close> in \\<open>y + a \\<cdot> x'\\<close> are unique, so the function\n  \\<open>h'\\<close> defined by \\<open>h' (y + a \\<cdot> x') = h y + a \\<cdot> \\<xi>\\<close> is definite.\n\\<close>\n\nlemma h'_definite:\n  fixes H\n  assumes h'_def:\n    \"\\<And>x. h' x =\n      (let (y, a) = SOME (y, a). (x = y + a \\<cdot> x' \\<and> y \\<in> H)\n       in (h y) + a * xi)\"\n    and x: \"x = y + a \\<cdot> x'\"\n  assumes \"vectorspace E\" \"subspace H E\"\n  assumes y: \"y \\<in> H\"\n    and x': \"x' \\<notin> H\"  \"x' \\<in> E\"  \"x' \\<noteq> 0\"\n  shows \"h' x = h y + a * xi\"\nproof -\n  interpret vectorspace E by fact\n  interpret subspace H E by fact\n  from x y x' have \"x \\<in> H + lin x'\" by auto\n  have \"\\<exists>!(y, a). x = y + a \\<cdot> x' \\<and> y \\<in> H\" (is \"\\<exists>!p. ?P p\")\n  proof (rule ex_ex1I)\n    from x y show \"\\<exists>p. ?P p\" by blast\n    fix p q assume p: \"?P p\" and q: \"?P q\"\n    show \"p = q\"\n    proof -\n      from p have xp: \"x = fst p + snd p \\<cdot> x' \\<and> fst p \\<in> H\"\n        by (cases p) simp\n      from q have xq: \"x = fst q + snd q \\<cdot> x' \\<and> fst q \\<in> H\"\n        by (cases q) simp\n      have \"fst p = fst q \\<and> snd p = snd q\"\n      proof (rule decomp_H')\n        from xp show \"fst p \\<in> H\" ..\n        from xq show \"fst q \\<in> H\" ..\n        from xp and xq show \"fst p + snd p \\<cdot> x' = fst q + snd q \\<cdot> x'\"\n          by simp\n      qed (rule \\<open>vectorspace E\\<close>, rule \\<open>subspace H E\\<close>, (rule x')+)\n      then show ?thesis by (cases p, cases q) simp\n    qed\n  qed\n  then have eq: \"(SOME (y, a). x = y + a \\<cdot> x' \\<and> y \\<in> H) = (y, a)\"\n    by (rule some1_equality) (simp add: x y)\n  with h'_def show \"h' x = h y + a * xi\" by (simp add: Let_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/Hahn_Banach/Subspace.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835289107307, "lm_q2_score": 0.880797071719777, "lm_q1q2_score": 0.7358914457346772}}
{"text": "section \\<open>Calculating parity efficiently using merge sort\\<close>\n\ntheory Parity_Merge_Sort\nimports Parity_Extras\nbegin\n\ntype_synonym 'a counter = \"nat \\<times> 'a\"\n\nabbreviation bind :: \"'a counter \\<Rightarrow> ('a \\<Rightarrow> 'b counter) \\<Rightarrow> 'b counter\"\n  where \"bind m f \\<equiv> case m of (c, r) \\<Rightarrow> case f r of (c', r') \\<Rightarrow> (c + c', r')\"\n\nfun\n  merge_sorted :: \"nat list \\<Rightarrow> nat list \\<Rightarrow> nat list counter\"\nwhere\n  \"merge_sorted [] ys = (0, ys)\"\n| \"merge_sorted xs [] = (0, xs)\"\n| \"merge_sorted (x # xs) (y # ys)\n    = (if x \\<le> y\n        then bind (merge_sorted xs (y # ys)) (Pair 0               \\<circ> op # x)\n        else bind (merge_sorted (x # xs) ys) (Pair (1 + length xs) \\<circ> op # y))\"\n\nlemma merge_sorted_occ:\n  \"occ (snd (merge_sorted xs ys)) = occ (xs @ ys)\"\n  by (induct xs ys rule: merge_sorted.induct) (auto simp: append_occ split: prod.splits)\n\nlemma merge_sorted_set:\n  \"set (snd (merge_sorted xs ys)) = set xs \\<union> set ys\"\n  by (rule equalityI; rule subsetI) (auto simp: occ_member merge_sorted_occ append_occ)\n\nlemma prod_split_case: \"P (case p of (x,y) \\<Rightarrow> f x y) = P (f (fst p) (snd p))\"\n  by (auto split: prod.splits)\n\nlemma merge_sorted_sorted_parity:\n  \"sorted xs \\<Longrightarrow> sorted ys\n    \\<Longrightarrow> sorted (snd (merge_sorted xs ys))\n        \\<and> parity (xs @ ys) = even (fst (merge_sorted xs ys))\"\n  proof (induct xs ys rule: merge_sorted.induct)\n    case (3 x xs y ys)\n      have sorted: \"sorted xs\" \"sorted ys\" \"\\<forall> x' \\<in> set xs. x \\<le> x'\" \"\\<forall> y' \\<in> set ys. y \\<le> y'\"\n        using 3(3,4) by (auto simp: sorted_Cons)\n      show ?case\n      proof cases\n        assume le: \"x \\<le> y\"\n        have\n          hd: \"\\<forall> y' \\<in> set ys. x \\<le> y'\" and\n          so: \"sorted (snd (merge_sorted xs (y # ys)))\" and\n          pa: \"parity (xs @ y # ys) = even (fst (merge_sorted xs (y # ys)))\"\n          using le sorted 3 by auto\n        have \"parity (x # xs @ y # ys) = even (fst (merge_sorted (x # xs) (y # ys)))\"\n          by auto (auto simp: le pa sorted hd prod_split_case filter_le_empty)\n        thus ?thesis\n          by (auto simp: le prod_split_case merge_sorted_set sorted hd\n                 intro!: sorted.Cons[OF _ so])\n      next\n        assume gt: \"\\<not> x \\<le> y\"\n        have\n          le: \"y \\<le> x\"\n              \"\\<forall> x' \\<in> set xs. y \\<le> x'\" and\n          lt: \"y < x\"\n              \"\\<forall> x' \\<in> set xs. y < x'\" and\n          ts: \"sorted (snd (merge_sorted (x # xs) ys))\" and\n          tp: \"parity (x # xs @ ys) = even (fst (merge_sorted (x # xs) ys))\"\n          using gt sorted 3 by auto\n        have sh: \"parity (xs @ y # ys) = (parity (xs @ ys) = even (length xs))\"\n          using lt(2) proof (induct xs)\n            case Nil show ?case by (simp add: sorted filter_le_empty)\n          qed (simp; blast)\n        have \"parity (x # xs @ y # ys) = even (fst (merge_sorted (x # xs) (y # ys)))\"\n          by auto (auto simp: sh gt prod_split_case tp[symmetric])\n        thus ?thesis\n          by (auto simp: gt le prod_split_case merge_sorted_set sorted\n                 intro!: sorted.Cons[OF _ ts])\n      qed\n  qed (auto dest!: sorted_parity)\n\nlemmas merge_sorted_sorted = conjunct1[OF merge_sorted_sorted_parity]\nlemmas merge_sorted_parity = conjunct2[OF merge_sorted_sorted_parity]\n\nlemmas merge_sorted_simps =\n  merge_sorted_sorted\n  sorted_parity[OF merge_sorted_sorted]\n  merge_sorted_parity\n\nfun\n  merge_pairs :: \"nat list list \\<Rightarrow> nat list list counter\"\nwhere\n  \"merge_pairs (xs # ys # zss) =\n    bind (merge_sorted xs ys) (\\<lambda>zs. bind (merge_pairs zss) (Pair 0 \\<circ> op # zs))\"\n| \"merge_pairs xss = (0, xss)\"\n\nlemma merge_pairs_occ:\n  \"occ (concat (snd (merge_pairs zss))) = occ (concat zss)\"\n  proof (induct zss rule: merge_pairs.induct)\n    case (1 xs ys zss) show ?case using 1[OF prod.collapse]\n      by (auto simp: merge_sorted_occ append_occ prod_split_case)\n  qed auto\n\nlemma sum_list_merge_pairs:\n  \"(\\<Sum> x \\<leftarrow> snd (merge_sorted xs ys). length [y \\<leftarrow> concat (snd (merge_pairs zss)) . y < x])\n    = (\\<Sum> x \\<leftarrow> xs @ ys. length [y \\<leftarrow> concat zss . y < x])\"\n  by (intro sum_list_cong merge_sorted_occ length_filter_cong merge_pairs_occ refl)\n\nlemma merge_pairs_sorted_parity:\n  assumes \"\\<forall> xs \\<in> set xss. sorted xs\"\n  shows \"(\\<forall> xs \\<in> set (snd (merge_pairs xss)). sorted xs)\n            \\<and> parity (concat xss) =\n                (even (fst (merge_pairs xss)) = parity (concat (snd (merge_pairs xss))))\"\n        (is \"?sorted xss \\<and> ?parity xss\")\n  using assms proof (induct xss rule: merge_pairs.induct)\n    case (1 xs ys zss)\n    have hyp: \"sorted xs\" \"sorted ys\" \"\\<forall> zs \\<in> set zss. sorted zs\"\n      using 1(2) by auto\n    have IH: \"?sorted zss\" \"?parity zss\"\n      by (auto simp: 1(1)[OF prod.collapse hyp(3)])\n    show ?case\n      apply (subst concat_cons_cons)\n      by (auto simp add: prod_split_case IH merge_sorted_simps[OF hyp(1,2)]\n                         parity_app[where xs=\"xs@ys\"]\n                         parity_app[where xs=\"snd (merge_sorted xs ys)\"]\n                         sum_list_merge_pairs\n               simp del: append_assoc map_append)\n  qed auto\n\nlemmas merge_pairs_sorted = conjunct1[OF merge_pairs_sorted_parity]\nlemmas merge_pairs_parity = conjunct2[OF merge_pairs_sorted_parity]\n\nfunction (sequential)\n  merge_lists :: \"nat list list \\<Rightarrow> nat list counter\"\nwhere\n  \"merge_lists []   = (0, [])\"\n| \"merge_lists [xs] = (0, xs)\"\n| \"merge_lists xss  = bind (merge_pairs xss) merge_lists\"\n  by pat_completeness auto\n\nlemma merge_pairs_length_bound: \"length (snd (merge_pairs xss)) < Suc (length xss)\"\n  proof (induct xss rule: merge_pairs.induct)\n    case (1 xs ys zss) show ?case\n      using 1[OF prod.collapse] by (auto simp: prod_split_case)\n  qed auto\n\ntermination merge_lists\n  by (relation \"measure length\") (auto simp: prod_split_case merge_pairs_length_bound)\n\nlemma merge_lists_occ:\n  \"occ (snd (merge_lists xss)) = occ (concat xss)\"\n  proof (induct xss rule: merge_lists.induct)\n    case (3 xs ys zss)\n    show ?case using 3[OF prod.collapse]\n      by (simp add: add.assoc prod_split_case append_occ merge_sorted_occ merge_pairs_occ)\n  qed auto\n\nlemma merge_lists_sorted_parity:\n  \"\\<forall> xs \\<in> set xss. sorted xs\n    \\<Longrightarrow> sorted (snd (merge_lists xss))\n        \\<and> parity (concat xss) = even (fst (merge_lists xss))\"\n  proof (induct xss rule: merge_lists.induct)\n    case (3 xs ys zss)\n    have hyp: \"sorted xs\" \"sorted ys\" \"\\<forall> zs \\<in> set zss. sorted zs\"\n      using 3(2) by auto\n    show ?case\n      apply (subst concat_cons_cons)\n      using 3(1)[OF prod.collapse merge_pairs_sorted, OF 3(2)]\n      by (auto simp add: prod_split_case\n                         parity_app[where xs=\"xs@ys\"]\n                         parity_app[where xs=\"snd (merge_sorted xs ys)\"]\n                         merge_sorted_simps[OF hyp(1,2)]\n                         merge_pairs_parity[OF hyp(3)]\n                         sum_list_merge_pairs\n               simp del: append_assoc map_append)\n  qed (auto elim: sorted_parity)\n\nlemmas merge_lists_sorted = conjunct1[OF merge_lists_sorted_parity]\nlemmas merge_lists_parity = conjunct2[OF merge_lists_sorted_parity]\n\ndefinition \"merge_pre \\<equiv> merge_lists \\<circ> map (\\<lambda>x. [x])\"\n\ndefinition \"sort_merge \\<equiv> snd \\<circ> merge_pre\"\ndefinition \"parity_merge \\<equiv> even \\<circ> fst \\<circ> merge_pre\"\n\nlemma sort_merge_occ: \"occ (sort_merge xs) = occ xs\"\n  by (simp add: sort_merge_def merge_pre_def merge_lists_occ)\n\nlemma sort_merge: \"sorted (sort_merge xs)\"\n  by (simp add: sort_merge_def merge_pre_def merge_lists_sorted)\n\nlemma parity_merge: \"parity_merge = parity\"\n  by (auto simp: parity_merge_def merge_pre_def merge_lists_parity[symmetric])\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_Merge_Sort.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772417253255, "lm_q2_score": 0.8418256551882382, "lm_q1q2_score": 0.7358206467005501}}
{"text": "(*<*)theory Star imports Main begin(*>*)\n\nsection\\<open>The Reflexive Transitive Closure\\<close>\n\ntext\\<open>\\label{sec:rtc}\n\\index{reflexive transitive closure!defining inductively|(}%\nAn inductive definition may accept parameters, so it can express \nfunctions that yield sets.\nRelations too can be defined inductively, since they are just sets of pairs.\nA perfect example is the function that maps a relation to its\nreflexive transitive closure.  This concept was already\nintroduced in \\S\\ref{sec:Relations}, where the operator \\<open>\\<^sup>*\\<close> was\ndefined as a least fixed point because inductive definitions were not yet\navailable. But now they are:\n\\<close>\n\ninductive_set\n  rtc :: \"('a \\<times> 'a)set \\<Rightarrow> ('a \\<times> 'a)set\"   (\"_*\" [1000] 999)\n  for r :: \"('a \\<times> 'a)set\"\nwhere\n  rtc_refl[iff]:  \"(x,x) \\<in> r*\"\n| rtc_step:       \"\\<lbrakk> (x,y) \\<in> r; (y,z) \\<in> r* \\<rbrakk> \\<Longrightarrow> (x,z) \\<in> r*\"\n\ntext\\<open>\\noindent\nThe function \\<^term>\\<open>rtc\\<close> is annotated with concrete syntax: instead of\n\\<open>rtc r\\<close> we can write \\<^term>\\<open>r*\\<close>. The actual definition\nconsists of two rules. Reflexivity is obvious and is immediately given the\n\\<open>iff\\<close> attribute to increase automation. The\nsecond rule, @{thm[source]rtc_step}, says that we can always add one more\n\\<^term>\\<open>r\\<close>-step to the left. Although we could make @{thm[source]rtc_step} an\nintroduction rule, this is dangerous: the recursion in the second premise\nslows down and may even kill the automatic tactics.\n\nThe above definition of the concept of reflexive transitive closure may\nbe sufficiently intuitive but it is certainly not the only possible one:\nfor a start, it does not even mention transitivity.\nThe rest of this section is devoted to proving that it is equivalent to\nthe standard definition. We start with a simple lemma:\n\\<close>\n\nlemma [intro]: \"(x,y) \\<in> r \\<Longrightarrow> (x,y) \\<in> r*\"\nby(blast intro: rtc_step)\n\ntext\\<open>\\noindent\nAlthough the lemma itself is an unremarkable consequence of the basic rules,\nit has the advantage that it can be declared an introduction rule without the\ndanger of killing the automatic tactics because \\<^term>\\<open>r*\\<close> occurs only in\nthe conclusion and not in the premise. Thus some proofs that would otherwise\nneed @{thm[source]rtc_step} can now be found automatically. The proof also\nshows that \\<open>blast\\<close> is able to handle @{thm[source]rtc_step}. But\nsome of the other automatic tactics are more sensitive, and even \\<open>blast\\<close> can be lead astray in the presence of large numbers of rules.\n\nTo prove transitivity, we need rule induction, i.e.\\ theorem\n@{thm[source]rtc.induct}:\n@{thm[display]rtc.induct}\nIt says that \\<open>?P\\<close> holds for an arbitrary pair @{thm (prem 1) rtc.induct}\nif \\<open>?P\\<close> is preserved by all rules of the inductive definition,\ni.e.\\ if \\<open>?P\\<close> holds for the conclusion provided it holds for the\npremises. In general, rule induction for an $n$-ary inductive relation $R$\nexpects a premise of the form $(x@1,\\dots,x@n) \\in R$.\n\nNow we turn to the inductive proof of transitivity:\n\\<close>\n\nlemma rtc_trans: \"\\<lbrakk> (x,y) \\<in> r*; (y,z) \\<in> r* \\<rbrakk> \\<Longrightarrow> (x,z) \\<in> r*\"\napply(erule rtc.induct)\n\ntxt\\<open>\\noindent\nUnfortunately, even the base case is a problem:\n@{subgoals[display,indent=0,goals_limit=1]}\nWe have to abandon this proof attempt.\nTo understand what is going on, let us look again at @{thm[source]rtc.induct}.\nIn the above application of \\<open>erule\\<close>, the first premise of\n@{thm[source]rtc.induct} is unified with the first suitable assumption, which\nis \\<^term>\\<open>(x,y) \\<in> r*\\<close> rather than \\<^term>\\<open>(y,z) \\<in> r*\\<close>. Although that\nis what we want, it is merely due to the order in which the assumptions occur\nin the subgoal, which it is not good practice to rely on. As a result,\n\\<open>?xb\\<close> becomes \\<^term>\\<open>x\\<close>, \\<open>?xa\\<close> becomes\n\\<^term>\\<open>y\\<close> and \\<open>?P\\<close> becomes \\<^term>\\<open>\\<lambda>u v. (u,z) \\<in> r*\\<close>, thus\nyielding the above subgoal. So what went wrong?\n\nWhen looking at the instantiation of \\<open>?P\\<close> we see that it does not\ndepend on its second parameter at all. The reason is that in our original\ngoal, of the pair \\<^term>\\<open>(x,y)\\<close> only \\<^term>\\<open>x\\<close> appears also in the\nconclusion, but not \\<^term>\\<open>y\\<close>. Thus our induction statement is too\ngeneral. Fortunately, it can easily be specialized:\ntransfer the additional premise \\<^prop>\\<open>(y,z)\\<in>r*\\<close> into the conclusion:\\<close>\n(*<*)oops(*>*)\nlemma rtc_trans[rule_format]:\n  \"(x,y) \\<in> r* \\<Longrightarrow> (y,z) \\<in> r* \\<longrightarrow> (x,z) \\<in> r*\"\n\ntxt\\<open>\\noindent\nThis is not an obscure trick but a generally applicable heuristic:\n\\begin{quote}\\em\nWhen proving a statement by rule induction on $(x@1,\\dots,x@n) \\in R$,\npull all other premises containing any of the $x@i$ into the conclusion\nusing $\\longrightarrow$.\n\\end{quote}\nA similar heuristic for other kinds of inductions is formulated in\n\\S\\ref{sec:ind-var-in-prems}. The \\<open>rule_format\\<close> directive turns\n\\<open>\\<longrightarrow>\\<close> back into \\<open>\\<Longrightarrow>\\<close>: in the end we obtain the original\nstatement of our lemma.\n\\<close>\n\napply(erule rtc.induct)\n\ntxt\\<open>\\noindent\nNow induction produces two subgoals which are both proved automatically:\n@{subgoals[display,indent=0]}\n\\<close>\n\n apply(blast)\napply(blast intro: rtc_step)\ndone\n\ntext\\<open>\nLet us now prove that \\<^term>\\<open>r*\\<close> is really the reflexive transitive closure\nof \\<^term>\\<open>r\\<close>, i.e.\\ the least reflexive and transitive\nrelation containing \\<^term>\\<open>r\\<close>. The latter is easily formalized\n\\<close>\n\ninductive_set\n  rtc2 :: \"('a \\<times> 'a)set \\<Rightarrow> ('a \\<times> 'a)set\"\n  for r :: \"('a \\<times> 'a)set\"\nwhere\n  \"(x,y) \\<in> r \\<Longrightarrow> (x,y) \\<in> rtc2 r\"\n| \"(x,x) \\<in> rtc2 r\"\n| \"\\<lbrakk> (x,y) \\<in> rtc2 r; (y,z) \\<in> rtc2 r \\<rbrakk> \\<Longrightarrow> (x,z) \\<in> rtc2 r\"\n\ntext\\<open>\\noindent\nand the equivalence of the two definitions is easily shown by the obvious rule\ninductions:\n\\<close>\n\nlemma \"(x,y) \\<in> rtc2 r \\<Longrightarrow> (x,y) \\<in> r*\"\napply(erule rtc2.induct)\n  apply(blast)\n apply(blast)\napply(blast intro: rtc_trans)\ndone\n\nlemma \"(x,y) \\<in> r* \\<Longrightarrow> (x,y) \\<in> rtc2 r\"\napply(erule rtc.induct)\n apply(blast intro: rtc2.intros)\napply(blast intro: rtc2.intros)\ndone\n\ntext\\<open>\nSo why did we start with the first definition? Because it is simpler. It\ncontains only two rules, and the single step rule is simpler than\ntransitivity.  As a consequence, @{thm[source]rtc.induct} is simpler than\n@{thm[source]rtc2.induct}. Since inductive proofs are hard enough\nanyway, we should always pick the simplest induction schema available.\nHence \\<^term>\\<open>rtc\\<close> is the definition of choice.\n\\index{reflexive transitive closure!defining inductively|)}\n\n\\begin{exercise}\\label{ex:converse-rtc-step}\nShow that the converse of @{thm[source]rtc_step} also holds:\n@{prop[display]\"[| (x,y) \\<in> r*; (y,z) \\<in> r |] ==> (x,z) \\<in> r*\"}\n\\end{exercise}\n\\begin{exercise}\nRepeat the development of this section, but starting with a definition of\n\\<^term>\\<open>rtc\\<close> where @{thm[source]rtc_step} is replaced by its converse as shown\nin exercise~\\ref{ex:converse-rtc-step}.\n\\end{exercise}\n\\<close>\n(*<*)\nlemma rtc_step2[rule_format]: \"(x,y) \\<in> r* \\<Longrightarrow> (y,z) \\<in> r \\<longrightarrow> (x,z) \\<in> r*\"\napply(erule rtc.induct)\n apply blast\napply(blast intro: rtc_step)\ndone\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/Star.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8740772417253255, "lm_q2_score": 0.8418256551882382, "lm_q1q2_score": 0.7358206467005501}}
{"text": "theory Permutations_2\nimports\n  \"HOL-Library.Permutations\"\n  Executable_Permutations\n  Graph_Theory.Funpow\nbegin\n\nsection \\<open>Modifying Permutations\\<close>\n\nabbreviation funswapid :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> 'a\" (infix \"\\<rightleftharpoons>\\<^sub>F\" 90) where\n  \"x \\<rightleftharpoons>\\<^sub>F y \\<equiv> Fun.swap x y id\"\n\ndefinition perm_swap :: \"'a \\<Rightarrow> 'a \\<Rightarrow> ('a \\<Rightarrow> 'a) \\<Rightarrow> ('a \\<Rightarrow> 'a)\" where\n  \"perm_swap x y f \\<equiv> x \\<rightleftharpoons>\\<^sub>F y o f o x \\<rightleftharpoons>\\<^sub>F y\"\n\ndefinition perm_rem :: \"'a \\<Rightarrow> ('a \\<Rightarrow> 'a) \\<Rightarrow> ('a \\<Rightarrow> 'a)\" where\n  \"perm_rem x f \\<equiv> if f x \\<noteq> x then x \\<rightleftharpoons>\\<^sub>F f x o f else f\"\n\n\ntext \\<open>\n  An example:\n\n  @{lemma \"perm_rem (2 :: nat) (list_succ [1,2,3,4]) x = list_succ [1,3,4] x\"\n      by (auto simp: perm_rem_def Fun.swap_def list_succ_def)}\n\\<close>\n\nlemma perm_swap_id[simp]: \"perm_swap a b id = id\"\n  by (auto simp: perm_swap_def)\n  \nlemma perm_rem_permutes:\n  assumes \"f permutes S \\<union> {x}\"\n  shows \"perm_rem x f permutes S\"\n  using assms by (auto simp: permutes_def perm_rem_def) (metis swap_id_eq)+\n\nlemma perm_rem_same:\n  assumes \"bij f\" \"f y = y\" shows \"perm_rem x f y = f y\"\n  using assms by (auto simp: perm_rem_def swap_id_eq bij_iff)\n\nlemma perm_rem_simps:\n  assumes \"bij f\"\n  shows\n  \"x = y \\<Longrightarrow> perm_rem x f y = x\"\n  \"f y = x \\<Longrightarrow> perm_rem x f y = f x\"\n  \"y \\<noteq> x \\<Longrightarrow> f y \\<noteq> x \\<Longrightarrow> perm_rem x f y = f y\"\n  using assms\n  apply (auto simp: perm_rem_def )\n  by (metis bij_iff id_apply swap_apply(3))\n\nlemma bij_swap_compose: \"bij (x \\<rightleftharpoons>\\<^sub>F y o f) \\<longleftrightarrow> bij f\"\n  by (metis UNIV_I bij_betw_comp_iff2 bij_betw_id bij_swap_iff subsetI)\n\nlemma bij_perm_rem[simp]: \"bij (perm_rem x f) \\<longleftrightarrow> bij f\"\n  by (simp add: perm_rem_def bij_swap_compose)\n\nlemma perm_rem_conv: \"\\<And>f x y. bij f \\<Longrightarrow> perm_rem x f y = (\n    if x = y then x\n    else if f y = x then f (f y)\n    else f y)\"\n  by (auto simp: perm_rem_simps)\n\nlemma perm_rem_commutes:\n  assumes \"bij f\" shows \"perm_rem a (perm_rem b f) = perm_rem b (perm_rem a f)\"\nproof -\n  have bij_simp: \"\\<And>x y. f x = f y \\<longleftrightarrow> x = y\"\n    using assms by (auto simp: bij_iff)\n  show ?thesis using assms by (auto simp: perm_rem_conv bij_simp fun_eq_iff)\nqed\n\nlemma perm_rem_id[simp]: \"perm_rem a id = id\"\n  by (simp add: perm_rem_def)\n\nlemma bij_eq_iff:\n  assumes \"bij f\" shows \"f x = f y \\<longleftrightarrow> x = y\"\n  using assms by (metis bij_iff) \n\nlemma swap_swap_id[simp]: \"(x \\<rightleftharpoons>\\<^sub>F y) ((x \\<rightleftharpoons>\\<^sub>F y) z) = z\"\n  by (simp add: swap_id_eq)\n\nlemma in_funswapid_image_iff: \"\\<And>a b x S. x \\<in> (a \\<rightleftharpoons>\\<^sub>F b) ` S \\<longleftrightarrow> (a \\<rightleftharpoons>\\<^sub>F b) x \\<in> S\"\n  by (metis bij_def bij_id bij_swap_iff inj_image_mem_iff swap_swap_id)\n\nlemma perm_swap_comp: \"perm_swap a b (f \\<circ> g) x = perm_swap a b f (perm_swap a b g x)\"\n  by (auto simp: perm_swap_def)\n\nlemma bij_perm_swap_iff[simp]: \"bij (perm_swap a b f) \\<longleftrightarrow> bij f\"\n  by (auto simp: perm_swap_def bij_swap_compose bij_comp comp_swap)\n\nlemma funpow_perm_swap: \"perm_swap a b f ^^ n = perm_swap a b (f ^^ n)\"\n  by (induct n) (auto simp: perm_swap_def fun_eq_iff)\n\nlemma orbit_perm_swap: \"orbit (perm_swap a b f) x = (a \\<rightleftharpoons>\\<^sub>F b) ` orbit f ((a \\<rightleftharpoons>\\<^sub>F b) x)\"\n  by (auto simp: orbit_altdef funpow_perm_swap) (auto simp: perm_swap_def)\n\nlemma has_dom_perm_swap: \"has_dom (perm_swap a b f) S = has_dom f ((a \\<rightleftharpoons>\\<^sub>F b) ` S)\"\n  by (auto simp: has_dom_def perm_swap_def inj_image_mem_iff) (metis image_iff swap_swap_id)\n\nlemma perm_restrict_dom_subset:\n  assumes \"has_dom f A\" shows \"perm_restrict f A = f\"\nproof -\n  from assms have \"\\<And>x. x \\<notin> A \\<Longrightarrow> f x = x\" by (auto simp: has_dom_def)\n  then show ?thesis by (auto simp: perm_restrict_def fun_eq_iff)\nqed\n\nlemma has_domD: \"has_dom f S \\<Longrightarrow> x \\<notin> S \\<Longrightarrow> f x = x\"\n  by (auto simp: has_dom_def)\n\nlemma has_domI: \"(\\<And>x. x \\<notin> S \\<Longrightarrow> f x = x) \\<Longrightarrow> has_dom f S\"\n  by (auto simp: has_dom_def)\n\nlemma perm_swap_permutes2:\n  assumes \"f permutes ((x \\<rightleftharpoons>\\<^sub>F y) ` S)\"\n  shows \"perm_swap x y f permutes S\"\n  using assms\n  by (auto simp: perm_swap_def permutes_conv_has_dom has_dom_perm_swap[unfolded perm_swap_def])\n    (metis bij_swap_iff bij_swap_compose_bij comp_id comp_swap)\n\nsection \\<open>Cyclic Permutations\\<close>\n\nlemma cyclic_on_perm_swap:\n  assumes \"cyclic_on f S\" shows \"cyclic_on (perm_swap x y f) ((x \\<rightleftharpoons>\\<^sub>F y) ` S)\"\n  using assms by (rule cyclic_on_FOO) (auto simp: perm_swap_def swap_swap_id)\n\nlemma orbit_perm_rem:\n  assumes \"bij f\" \"x \\<noteq> y\" shows \"orbit (perm_rem y f) x = orbit f x - {y}\" (is \"?L = ?R\")\nproof (intro set_eqI iffI)\n  fix z assume \"z \\<in> ?L\"\n  then show \"z \\<in> ?R\"\n    using assms by induct (auto simp: perm_rem_conv bij_iff intro: orbit.intros)\nnext\n  fix z assume A: \"z \\<in> ?R\"\n\n  { assume \"z \\<in> orbit f x\"\n    then have \"(z \\<noteq> y \\<longrightarrow> z \\<in> ?L) \\<and> (z = y \\<longrightarrow> f z \\<in> ?L)\"\n    proof induct\n      case base with assms show ?case by (auto intro: orbit_eqI(1) simp: perm_rem_conv)\n    next\n      case (step z) then show ?case\n        using assms by (cases \"y = z\") (auto intro: orbit_eqI simp: perm_rem_conv)\n    qed\n  } with A show \"z \\<in> ?L\" by auto\nqed\n\nlemma orbit_perm_rem_eq:\n  assumes \"bij f\" shows \"orbit (perm_rem y f) x = (if x = y then {y} else orbit f x - {y})\"\n  using assms by (simp add: orbit_eq_singleton_iff orbit_perm_rem perm_rem_simps)\n\nlemma cyclic_on_perm_rem:\n  assumes \"cyclic_on f S\" \"bij f\" \"S \\<noteq> {x}\" shows \"cyclic_on (perm_rem x f) (S - {x})\"\n  using assms[unfolded cyclic_on_alldef] by (simp add: cyclic_on_def orbit_perm_rem_eq) auto\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/Planarity_Certificates/Planarity/Permutations_2.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8740772417253256, "lm_q2_score": 0.8418256393148981, "lm_q1q2_score": 0.735820632826025}}
{"text": "header {*Monotone Convergence*}\n\ntheory MonConv\nimports Complex_Main\nbegin\n\ntext {* A sensible requirement for an integral operator is that it be\n  ``well-behaved'' with respect to limit functions. To become just a\n  little more\n  precise, it is expected that the limit operator may be interchanged\n  with the integral operator under conditions that are as weak as\n  possible. To this\n  end, the notion of monotone convergence is introduced and later\n  applied in the definition of the integral. \n\n  In fact, we distinguish three types of monotone convergence here:\n  There are converging sequences of real numbers, real functions and\n  sets. Monotone convergence could even be defined more generally for\n  any type in the axiomatic type class\\footnote{For the concept of axiomatic type\n  classes, see \\cite{Nipkow93,wenzelax}} @{text ord} of ordered\n  types like this.\n\n  @{prop \"mon_conv u f \\<equiv> (\\<forall>n. u n \\<le> u (Suc n)) \\<and> Sup (range u) = f\"}\n\n  However, this employs the general concept of a least upper bound.\n  For the special types we have in mind, the more specific\n  limit --- respective union --- operators are available, combined with many theorems\n  about their properties. For the type of real- (or rather ordered-) valued functions,\n  the less-or-equal relation is defined pointwise.\n\n  @{thm le_fun_def [no_vars]}\n  *}\n\n(*monotone convergence*)\n \ntext {*Now the foundations are laid for the definition of monotone\n  convergence. To express the similarity of the different types of\n  convergence, a single overloaded operator is used.*}\n\nconsts\n  mon_conv:: \"(nat \\<Rightarrow> 'a) \\<Rightarrow> 'a::ord \\<Rightarrow> bool\" (\"_\\<up>_\" [60,61] 60) \n\ndefs (overloaded)\n  real_mon_conv: \"x\\<up>(y::real) \\<equiv> (\\<forall>n. x n \\<le> x (Suc n)) \\<and> x ----> y\"\n  realfun_mon_conv: \n  \"u\\<up>(f::'a \\<Rightarrow> real) \\<equiv> (\\<forall>n. u n \\<le> u (Suc n)) \\<and>  (\\<forall>w. (\\<lambda>n. u n w) ----> f w)\"\n  set_mon_conv: \"A\\<up>(B::'a set) \\<equiv> (\\<forall>n. A n \\<le> A (Suc n)) \\<and> B = (\\<Union>n. A n)\"\n\ntheorem realfun_mon_conv_iff: \"(u\\<up>f) = (\\<forall>w. (\\<lambda>n. u n w)\\<up>((f w)::real))\"\n  by (auto simp add: real_mon_conv realfun_mon_conv le_fun_def)\n\ntext {* The long arrow signifies convergence of real sequences as\n  defined in the theory @{text SEQ} \\cite{Fleuriot:2000:MNR}. Monotone convergence\n  for real functions is simply pointwise monotone convergence.\n\n  Quite a few properties of these definitions will be necessary later,\n  and they are listed now, giving only few select proofs. *} \n\n    (*This theorem, too, could be proved just the same for any ord\n  Type!*)\n\n\nlemma assumes mon_conv: \"x\\<up>(y::real)\"\n  shows mon_conv_mon: \"(x i) \\<le> (x (m+i))\"\n(*<*)proof (induct m)\n  case 0 \n  show ?case by simp\n  \nnext\n  case (Suc n)\n  also \n  from mon_conv have \"x (n+i) \\<le> x (Suc n+i)\" \n    by (simp add: real_mon_conv)              \n  finally show ?case .\nqed(*>*)\n\n\nlemma limseq_shift_iff: \"(\\<lambda>m. x (m+i)) ----> y = x ----> y\"\n(*<*)proof (induct i)\n  case 0 show ?case by simp\nnext \n  case (Suc n)\n  also have \"(\\<lambda>m. x (m + n)) ----> y = (\\<lambda>m. x (Suc m + n)) ----> y\"\n    by (rule LIMSEQ_Suc_iff[THEN sym])  \n  also have \"\\<dots> = (\\<lambda>m. x (m + Suc n)) ----> y\"\n    by simp\n  finally show ?case .\nqed(*>*)\n\n    (*This, too, could be established in general*)\ntheorem assumes mon_conv: \"x\\<up>(y::real)\"\n  shows real_mon_conv_le: \"x i \\<le> y\"\nproof -\n  from mon_conv have \"(\\<lambda>m. x (m+i)) ----> y\" \n    by (simp add: real_mon_conv limseq_shift_iff)\n  also from mon_conv have \"\\<forall>m\\<ge>0. x i \\<le> x (m+i)\" by (simp add: mon_conv_mon)\n  ultimately show ?thesis by (rule LIMSEQ_le_const[OF _ exI[where x=0]])\nqed\n\ntheorem assumes mon_conv: \"x\\<up>(y::('a \\<Rightarrow> real))\"\n  shows realfun_mon_conv_le: \"x i \\<le> y\"\nproof -\n  {fix w\n    from mon_conv have \"(\\<lambda>i. x i w)\\<up>(y w)\" \n      by (simp add: realfun_mon_conv_iff)    \n    hence \"x i w \\<le> y w\" \n      by (rule real_mon_conv_le)\n  }\n  thus ?thesis by (simp add: le_fun_def)\nqed\n\nlemma assumes mon_conv: \"x\\<up>(y::real)\"\n  and less: \"z < y\"\n  shows real_mon_conv_outgrow: \"\\<exists>n. \\<forall>m. n \\<le> m \\<longrightarrow> z < x m\"\nproof -\n  from less have less': \"0 < y-z\" \n    by simp                \n  have \"\\<exists>n.\\<forall>m. n \\<le> m \\<longrightarrow> \\<bar>x m - y\\<bar> < y - z\"\n  proof -\n    from mon_conv have aux: \"\\<And>r. r > 0 \\<Longrightarrow> \\<exists>n. \\<forall>m. n \\<le> m \\<longrightarrow> \\<bar>x m - y\\<bar> < r\"\n    unfolding real_mon_conv LIMSEQ_def dist_real_def by auto\n    with less' show \"\\<exists>n. \\<forall>m. n \\<le> m \\<longrightarrow> \\<bar>x m - y\\<bar> < y - z\" by auto\n  qed\n  also\n  { fix m \n    from mon_conv have \"x m \\<le> y\" \n      by (rule real_mon_conv_le)  \n    hence \"\\<bar>x m - y\\<bar> = y - x m\" \n      by arith                    \n    also assume \"\\<bar>x m - y\\<bar> < y - z\"\n    ultimately have \"z < x m\" \n      by arith                \n  }\n  ultimately show ?thesis \n    by blast\nqed\n\n\ntheorem real_mon_conv_times: \n  assumes xy: \"x\\<up>(y::real)\" and nn: \"0\\<le>z\"\n  shows \"(\\<lambda>m. z*x m)\\<up>(z*y)\"\n(*<*)proof -\n  from assms have \"\\<And>n. z*x n \\<le> z*x (Suc n)\"\n    by (simp add: real_mon_conv mult_left_mono)\n  also from xy have \"(\\<lambda>m. z*x m)---->(z*y)\"\n    by (simp add: real_mon_conv tendsto_const tendsto_mult)\n  ultimately show ?thesis by (simp add: real_mon_conv)\nqed(*>*)\n\n\ntheorem realfun_mon_conv_times: \n  assumes xy: \"x\\<up>(y::'a\\<Rightarrow>real)\" and nn: \"0\\<le>z\"\n  shows \"(\\<lambda>m w. z*x m w)\\<up>(\\<lambda>w. z*y w)\"\n(*<*)proof -\n  from assms have \"\\<And>w. (\\<lambda>m. z*x m w)\\<up>(z*y w)\"\n    by (simp add: realfun_mon_conv_iff real_mon_conv_times)\n  thus ?thesis by (auto simp add: realfun_mon_conv_iff)\nqed(*>*)\n\n\ntheorem real_mon_conv_add: \n  assumes xy: \"x\\<up>(y::real)\" and ab: \"a\\<up>(b::real)\"\n  shows \"(\\<lambda>m. x m + a m)\\<up>(y + b)\" \n(*<*)proof - \n  { fix n\n    from assms have \"x n \\<le> x (Suc n)\" and \"a n \\<le> a (Suc n)\"\n      by (simp_all add: real_mon_conv)\n    hence \"x n + a n \\<le> x (Suc n) + a (Suc n)\"\n      by simp\n  }\n  also from assms have \"(\\<lambda>m. x m + a m)---->(y + b)\" by (simp add: real_mon_conv tendsto_add)\n  ultimately show ?thesis by (simp add: real_mon_conv)\nqed(*>*)\n\ntheorem realfun_mon_conv_add:\n  assumes xy: \"x\\<up>(y::'a\\<Rightarrow>real)\" and ab: \"a\\<up>(b::'a \\<Rightarrow> real)\"\n  shows \"(\\<lambda>m w. x m w + a m w)\\<up>(\\<lambda>w. y w + b w)\"\n(*<*)proof -\n  from assms have \"\\<And>w. (\\<lambda>m. x m w + a m w)\\<up>(y w + b w)\"\n    by (simp add: realfun_mon_conv_iff real_mon_conv_add)\n  thus ?thesis by (auto simp add: realfun_mon_conv_iff)\nqed(*>*)\n\n\ntheorem real_mon_conv_bound:\n  assumes mon: \"\\<And>n. c n \\<le> c (Suc n)\"\n  and bound: \"\\<And>n. c n \\<le> (x::real)\"\n  shows \"\\<exists>l. c\\<up>l \\<and> l\\<le>x\"\nproof -\n  from incseq_convergent[of c x] mon bound\n  obtain l where \"c ----> l\" \"\\<forall>i. c i \\<le> l\"\n    by (auto simp: incseq_Suc_iff)\n  moreover -- {*This is like $\\isacommand{also}$ but lacks the transitivity step.*}\n  with bound have \"l \\<le> x\"\n    by (intro LIMSEQ_le_const2) auto\n  ultimately show ?thesis\n    by (auto simp: real_mon_conv mon)\nqed\n\ntheorem real_mon_conv_dom:\n  assumes xy: \"x\\<up>(y::real)\" and mon: \"\\<And>n. c n \\<le> c (Suc n)\"\n  and dom: \"c \\<le> x\"\n  shows \"\\<exists>l. c\\<up>l \\<and> l\\<le>y\"\nproof -\n  from dom have \"\\<And>n. c n \\<le> x n\" by (simp add: le_fun_def)\n  also from xy have \"\\<And>n. x n \\<le> y\" by (simp add: real_mon_conv_le)\n  also note mon \n  ultimately show ?thesis by (simp add: real_mon_conv_bound) \nqed\n\ntext{*\\newpage*}\ntheorem realfun_mon_conv_bound:\n  assumes mon: \"\\<And>n. c n \\<le> c (Suc n)\"\n  and bound: \"\\<And>n. c n \\<le> (x::'a \\<Rightarrow> real)\"\n  shows \"\\<exists>l. c\\<up>l \\<and> l\\<le>x\"\n(*<*)proof \n  def r \\<equiv> \"\\<lambda>t. SOME l. (\\<lambda>n. c n t)\\<up>l \\<and> l\\<le>x t\"\n  { fix t\n    from mon have m2: \"\\<And>n. c n t \\<le> c (Suc n) t\" by (simp add: le_fun_def)\n    also \n    from bound have \"\\<And>n. c n t \\<le> x t\" by (simp add: le_fun_def)\n    \n    ultimately have \"\\<exists>l. (\\<lambda>n. c n t)\\<up>l \\<and> l\\<le>x t\" (is \"\\<exists>l. ?P l\") \n      by (rule real_mon_conv_bound) \n    hence \"?P (SOME l. ?P l)\" by (rule someI_ex)\n    hence \"(\\<lambda>n. c n t)\\<up>r t \\<and> r t\\<le>x t\" by (simp add: r_def)\n  }  \n  thus \"c\\<up>r \\<and> r \\<le> x\" by (simp add: realfun_mon_conv_iff le_fun_def)\nqed (*>*)  \n\ntext {*This brings the theory to an end. Notice how the definition of the limit of a\n  real sequence is visible in the proof to @{text\n  real_mon_conv_outgrow}, a lemma that will be used for a\n  monotonicity proof of the integral of simple functions later on.*}(*<*)\n  (*Another set construction. Needed in ImportPredSet, but Set is shadowed beyond \n  reconstruction there.\n  Before making disjoint, we first need an ascending series of sets*)\n\nprimrec mk_mon::\"(nat \\<Rightarrow> 'a set) \\<Rightarrow> nat \\<Rightarrow> 'a set\"\nwhere\n  \"mk_mon A 0 = A 0\"\n| \"mk_mon A (Suc n) = A (Suc n) \\<union> mk_mon A n\"\n\nlemma \"mk_mon A \\<up> (\\<Union>i. A i)\"\nproof (unfold set_mon_conv)\n  { fix n\n    have \"mk_mon A n \\<subseteq> mk_mon A (Suc n)\"\n      by auto\n  }\n  also\n  have \"(\\<Union>i. mk_mon A i) = (\\<Union>i. A i)\"\n  proof \n    { fix i x\n      assume \"x \\<in> mk_mon A i\"\n      hence \"\\<exists>j. x \\<in> A j\"\n        by (induct i) auto\n      hence \"x \\<in> (\\<Union>i. A i)\"\n        by simp\n    }\n    thus \"(\\<Union>i. mk_mon A i) \\<subseteq> (\\<Union>i. A i)\"\n      by auto\n    \n    { fix i \n      have \"A i \\<subseteq> mk_mon A i\"\n        by (induct i) auto\n    }\n    thus \"(\\<Union>i. A i) \\<subseteq> (\\<Union>i. mk_mon A i)\"\n      by auto\n  qed\n  ultimately show \"(\\<forall>n. mk_mon A n \\<subseteq> mk_mon A (Suc n)) \\<and> UNION UNIV A = (\\<Union>n. mk_mon A n)\"\n    by simp\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/MonConv.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256393148982, "lm_q2_score": 0.8740772286044095, "lm_q1q2_score": 0.7358206217805014}}
{"text": "theory Gronwall\nimports Vector_Derivative_On\nbegin\n\nsubsection \\<open>Gronwall\\<close>\n\nlemma derivative_quotient_bound:\n  assumes g_deriv_on: \"(g has_vderiv_on g') {a .. b}\"\n  assumes frac_le: \"\\<And>t. t \\<in> {a .. b} \\<Longrightarrow> g' t / g t \\<le> K\"\n  assumes g'_cont: \"continuous_on {a .. b} g'\"\n  assumes g_pos: \"\\<And>t. t \\<in> {a .. b} \\<Longrightarrow> g t > 0\"\n  assumes t_in: \"t \\<in> {a .. b}\"\n  shows \"g t \\<le> g a * exp (K * (t - a))\"\nproof -\n  have g_deriv: \"\\<And>t. t \\<in> {a .. b} \\<Longrightarrow> (g has_real_derivative g' t) (at t within {a .. b})\"\n    using g_deriv_on\n    by (auto simp: has_vderiv_on_def has_real_derivative_iff_has_vector_derivative[symmetric])\n  from assms have g_nonzero: \"\\<And>t. t \\<in> {a .. b} \\<Longrightarrow> g t \\<noteq> 0\"\n    by fastforce\n  have frac_integrable: \"\\<And>t. t \\<in> {a .. b} \\<Longrightarrow> (\\<lambda>t. g' t / g t) integrable_on {a..t}\"\n    by (force simp: g_nonzero intro: assms has_field_derivative_subset[OF g_deriv]\n      continuous_on_subset[OF g'_cont] continuous_intros integrable_continuous_real\n      continuous_on_subset[OF vderiv_on_continuous_on[OF g_deriv_on]])\n  have \"\\<And>t. t \\<in> {a..b} \\<Longrightarrow> ((\\<lambda>t. g' t / g t) has_integral ln (g t) - ln (g a)) {a .. t}\"\n    by (rule fundamental_theorem_of_calculus)\n      (auto intro!: derivative_eq_intros assms has_field_derivative_subset[OF g_deriv]\n        simp: has_real_derivative_iff_has_vector_derivative[symmetric])\n  hence *: \"\\<And>t. t \\<in> {a .. b} \\<Longrightarrow> ln (g t) - ln (g a) = integral {a .. t} (\\<lambda>t. g' t / g t)\"\n    using integrable_integral[OF frac_integrable]\n    by (rule has_integral_unique[where f = \"\\<lambda>t. g' t / g t\"])\n  from * t_in have \"ln (g t) - ln (g a) = integral {a .. t} (\\<lambda>t. g' t / g t)\" .\n  also have \"\\<dots> \\<le> integral {a .. t} (\\<lambda>_. K)\"\n    using \\<open>t \\<in> {a .. b}\\<close>\n    by (intro integral_le) (auto intro!: frac_integrable frac_le integral_le)\n  also have \"\\<dots> = K * (t - a)\" using \\<open>t \\<in> {a .. b}\\<close>\n    by simp\n  finally have \"ln (g t) \\<le> K * (t - a) + ln (g a)\" (is \"?lhs \\<le> ?rhs\")\n    by simp\n  hence \"exp ?lhs \\<le> exp ?rhs\"\n    by simp\n  thus ?thesis\n    using \\<open>t \\<in> {a .. b}\\<close> g_pos\n    by (simp add: ac_simps exp_add del: exp_le_cancel_iff)\nqed\n\nlemma derivative_quotient_bound_left:\n  assumes g_deriv_on: \"(g has_vderiv_on g') {a .. b}\"\n  assumes frac_ge: \"\\<And>t. t \\<in> {a .. b} \\<Longrightarrow> K \\<le> g' t / g t\"\n  assumes g'_cont: \"continuous_on {a .. b} g'\"\n  assumes g_pos: \"\\<And>t. t \\<in> {a .. b} \\<Longrightarrow> g t > 0\"\n  assumes t_in: \"t \\<in> {a..b}\"\n  shows \"g t \\<le> g b * exp (K * (t - b))\"\nproof -\n  have g_deriv: \"\\<And>t. t \\<in> {a .. b} \\<Longrightarrow> (g has_real_derivative g' t) (at t within {a .. b})\"\n    using g_deriv_on\n    by (auto simp: has_vderiv_on_def has_real_derivative_iff_has_vector_derivative[symmetric])\n  from assms have g_nonzero: \"\\<And>t. t \\<in> {a..b} \\<Longrightarrow> g t \\<noteq> 0\"\n    by fastforce\n  have frac_integrable: \"\\<And>t. t \\<in> {a .. b} \\<Longrightarrow> (\\<lambda>t. g' t / g t) integrable_on {t..b}\"\n    by (force simp: g_nonzero intro: assms has_field_derivative_subset[OF g_deriv]\n      continuous_on_subset[OF g'_cont] continuous_intros integrable_continuous_real\n      continuous_on_subset[OF vderiv_on_continuous_on[OF g_deriv_on]])\n  have \"\\<And>t. t \\<in> {a..b} \\<Longrightarrow> ((\\<lambda>t. g' t / g t) has_integral ln (g b) - ln (g t)) {t..b}\"\n    by (rule fundamental_theorem_of_calculus)\n      (auto intro!: derivative_eq_intros assms has_field_derivative_subset[OF g_deriv]\n        simp: has_real_derivative_iff_has_vector_derivative[symmetric])\n  hence *: \"\\<And>t. t \\<in> {a..b} \\<Longrightarrow> ln (g b) - ln (g t) = integral {t..b} (\\<lambda>t. g' t / g t)\"\n    using integrable_integral[OF frac_integrable]\n    by (rule has_integral_unique[where f = \"\\<lambda>t. g' t / g t\"])\n  have \"K * (b - t) = integral {t..b} (\\<lambda>_. K)\"\n    using \\<open>t \\<in> {a..b}\\<close>\n    by simp\n  also have \"... \\<le> integral {t..b} (\\<lambda>t. g' t / g t)\"\n    using \\<open>t \\<in> {a..b}\\<close>\n    by (intro integral_le) (auto intro!: frac_integrable frac_ge integral_le)\n  also have \"... = ln (g b) - ln (g t)\"\n    using * t_in by simp\n  finally have \"K * (b - t) + ln (g t) \\<le> ln (g b)\" (is \"?lhs \\<le> ?rhs\")\n    by simp\n  hence \"exp ?lhs \\<le> exp ?rhs\"\n    by simp\n  hence \"g t * exp (K * (b - t)) \\<le> g b\"\n    using \\<open>t \\<in> {a..b}\\<close> g_pos\n    by (simp add: ac_simps exp_add del: exp_le_cancel_iff)\n  hence \"g t / exp (K * (t - b)) \\<le> g b\"\n    by (simp add: algebra_simps exp_diff)\n  thus ?thesis\n    by (simp add: field_simps)\nqed\n\nlemma gronwall_general:\n  fixes g K C a b and t::real\n  defines \"G \\<equiv> \\<lambda>t. C + K * integral {a..t} (\\<lambda>s. g s)\"\n  assumes g_le_G: \"\\<And>t. t \\<in> {a..b} \\<Longrightarrow> g t \\<le> G t\"\n  assumes g_cont: \"continuous_on {a..b} g\"\n  assumes g_nonneg: \"\\<And>t. t \\<in> {a..b} \\<Longrightarrow> 0 \\<le> g t\"\n  assumes pos: \"0 < C\" \"K > 0\"\n  assumes \"t \\<in> {a..b}\"\n  shows \"g t \\<le> C * exp (K * (t - a))\"\nproof -\n  have G_pos: \"\\<And>t. t \\<in> {a..b} \\<Longrightarrow> 0 < G t\"\n    by (auto simp: G_def intro!: add_pos_nonneg mult_nonneg_nonneg Henstock_Kurzweil_Integration.integral_nonneg\n      integrable_continuous_real assms intro: less_imp_le continuous_on_subset)\n  have \"g t \\<le> G t\" using assms by auto\n  also\n  {\n    have \"(G has_vderiv_on (\\<lambda>t. K * g t)) {a..b}\"\n      by (auto intro!: derivative_eq_intros integral_has_vector_derivative g_cont\n        simp add: G_def has_vderiv_on_def)\n    moreover\n    {\n      fix t assume \"t \\<in> {a..b}\"\n      hence \"K * g t / G t \\<le> K * G t / G t\"\n        using pos g_le_G G_pos\n        by (intro divide_right_mono mult_left_mono) (auto intro!: less_imp_le)\n      also have \"\\<dots> = K\"\n        using G_pos[of t] \\<open>t \\<in> {a .. b}\\<close> by simp\n      finally have \"K * g t / G t \\<le> K\" .\n    }\n    ultimately have \"G t \\<le> G a * exp (K * (t - a))\"\n      apply (rule derivative_quotient_bound)\n      using \\<open>t \\<in> {a..b}\\<close>\n      by (auto intro!: continuous_intros g_cont G_pos simp: field_simps pos)\n  }\n  also have \"G a = C\"\n    by (simp add: G_def)\n  finally show ?thesis\n    by simp\nqed\n\nlemma gronwall_general_left:\n  fixes g K C a b and t::real\n  defines \"G \\<equiv> \\<lambda>t. C + K * integral {t..b} (\\<lambda>s. g s)\"\n  assumes g_le_G: \"\\<And>t. t \\<in> {a..b} \\<Longrightarrow> g t \\<le> G t\"\n  assumes g_cont: \"continuous_on {a..b} g\"\n  assumes g_nonneg: \"\\<And>t. t \\<in> {a..b} \\<Longrightarrow> 0 \\<le> g t\"\n  assumes pos: \"0 < C\" \"K > 0\"\n  assumes \"t \\<in> {a..b}\"\n  shows \"g t \\<le> C * exp (-K * (t - b))\"\nproof -\n  have G_pos: \"\\<And>t. t \\<in> {a..b} \\<Longrightarrow> 0 < G t\"\n    by (auto simp: G_def intro!: add_pos_nonneg mult_nonneg_nonneg Henstock_Kurzweil_Integration.integral_nonneg\n      integrable_continuous_real assms intro: less_imp_le continuous_on_subset)\n  have \"g t \\<le> G t\" using assms by auto\n  also\n  {\n    have \"(G has_vderiv_on (\\<lambda>t. -K * g t)) {a..b}\"\n      by (auto intro!: derivative_eq_intros g_cont integral_has_vector_derivative'\n          simp add: G_def has_vderiv_on_def)\n    moreover\n    {\n      fix t assume \"t \\<in> {a..b}\"\n      hence \"K * g t / G t \\<le> K * G t / G t\"\n        using pos g_le_G G_pos\n        by (intro divide_right_mono mult_left_mono) (auto intro!: less_imp_le)\n      also have \"\\<dots> = K\"\n        using G_pos[of t] \\<open>t \\<in> {a .. b}\\<close> by simp\n      finally have \"K * g t / G t \\<le> K\" .\n      hence \"-K \\<le> -K * g t / G t\"\n        by simp\n    }\n    ultimately\n    have \"G t \\<le> G b * exp (-K * (t - b))\"\n      apply (rule derivative_quotient_bound_left)\n      using \\<open>t \\<in> {a..b}\\<close>\n      by (auto intro!: continuous_intros g_cont G_pos simp: field_simps pos)\n  }\n  also have \"G b = C\"\n    by (simp add: G_def)\n  finally show ?thesis\n    by simp\nqed\n\nlemma gronwall_general_segment:\n  fixes a b::real\n  assumes \"\\<And>t. t \\<in> closed_segment a b \\<Longrightarrow> g t \\<le> C + K * integral (closed_segment a t) g\"\n    and \"continuous_on (closed_segment a b) g\"\n    and \"\\<And>t. t \\<in> closed_segment a b \\<Longrightarrow> 0 \\<le> g t\"\n    and \"0 < C\"\n    and \"0 < K\"\n    and \"t \\<in> closed_segment a b\"\n  shows \"g t \\<le> C * exp (K * abs (t - a))\"\nproof cases\n  assume \"a \\<le> b\"\n  then have *: \"abs (t - a) = t -a\" using assms by (auto simp: closed_segment_eq_real_ivl)\n  show ?thesis\n    unfolding *\n    using assms\n    by (intro gronwall_general[where b=b]) (auto intro!: simp: closed_segment_eq_real_ivl \\<open>a \\<le> b\\<close>)\nnext\n  assume \"\\<not>a \\<le> b\"\n  then have *: \"K * abs (t - a) = - K * (t - a)\" using assms by (auto simp: closed_segment_eq_real_ivl algebra_simps)\n  {\n    fix s :: real\n    assume a1: \"b \\<le> s\"\n    assume a2: \"s \\<le> a\"\n    assume a3: \"\\<And>t. b \\<le> t \\<and> t \\<le> a \\<Longrightarrow> g t \\<le> C + K * integral (if a \\<le> t then {a..t} else {t..a}) g\"\n    have \"s = a \\<or> s < a\"\n      using a2 by (meson less_eq_real_def)\n    then have \"g s \\<le> C + K * integral {s..a} g\"\n      using a3 a1 by fastforce\n  } then show ?thesis\n    unfolding *\n    using assms  \\<open>\\<not>a \\<le> b\\<close>\n    by (intro gronwall_general_left)\n      (auto intro!: simp: closed_segment_eq_real_ivl)\nqed\n\nlemma gronwall_more_general_segment:\n  fixes a b c::real\n  assumes \"\\<And>t. t \\<in> closed_segment a b \\<Longrightarrow> g t \\<le> C + K * integral (closed_segment c t) g\"\n    and cont: \"continuous_on (closed_segment a b) g\"\n    and \"\\<And>t. t \\<in> closed_segment a b \\<Longrightarrow> 0 \\<le> g t\"\n    and \"0 < C\"\n    and \"0 < K\"\n    and t: \"t \\<in> closed_segment a b\"\n    and c: \"c \\<in> closed_segment a b\"\n  shows \"g t \\<le> C * exp (K * abs (t - c))\"\nproof -\n  from t c have \"t \\<in> closed_segment c a \\<or> t \\<in> closed_segment c b\"\n    by (auto simp: closed_segment_eq_real_ivl split_ifs)\n  then show ?thesis\n  proof\n    assume \"t \\<in> closed_segment c a\"\n    moreover\n    have subs: \"closed_segment c a \\<subseteq> closed_segment a b\" using t c\n      by (auto simp: closed_segment_eq_real_ivl split_ifs)\n    ultimately show ?thesis\n      by (intro gronwall_general_segment[where b=a])\n        (auto intro!: assms intro: continuous_on_subset)\n  next\n    assume \"t \\<in> closed_segment c b\"\n    moreover\n    have subs: \"closed_segment c b \\<subseteq> closed_segment a b\" using t c\n      by (auto simp: closed_segment_eq_real_ivl)\n    ultimately show ?thesis\n      by (intro gronwall_general_segment[where b=b])\n        (auto intro!: assms intro: continuous_on_subset)\n  qed\nqed\n\nlemma gronwall:\n  fixes g K C and t::real\n  defines \"G \\<equiv> \\<lambda>t. C + K * integral {0..t} (\\<lambda>s. g s)\"\n  assumes g_le_G: \"\\<And>t. 0 \\<le> t \\<Longrightarrow> t \\<le> a \\<Longrightarrow> g t \\<le> G t\"\n  assumes g_cont: \"continuous_on {0..a} g\"\n  assumes g_nonneg: \"\\<And>t. 0 \\<le> t \\<Longrightarrow> t \\<le> a \\<Longrightarrow> 0 \\<le> g t\"\n  assumes pos: \"0 < C\" \"0 < K\"\n  assumes \"0 \\<le> t\" \"t \\<le> a\"\n  shows \"g t \\<le> C * exp (K * t)\"\n  apply(rule gronwall_general[where a=0, simplified, OF assms(2-6)[unfolded G_def]])\n  using assms(7,8)\n  by simp_all\n\nlemma gronwall_left:\n  fixes g K C and t::real\n  defines \"G \\<equiv> \\<lambda>t. C + K * integral {t..0} (\\<lambda>s. g s)\"\n  assumes g_le_G: \"\\<And>t. a \\<le> t \\<Longrightarrow> t \\<le> 0 \\<Longrightarrow> g t \\<le> G t\"\n  assumes g_cont: \"continuous_on {a..0} g\"\n  assumes g_nonneg: \"\\<And>t. a \\<le> t \\<Longrightarrow> t \\<le> 0 \\<Longrightarrow> 0 \\<le> g t\"\n  assumes pos: \"0 < C\" \"0 < K\"\n  assumes \"a \\<le> t\" \"t \\<le> 0\"\n  shows \"g t \\<le> C * exp (-K * t)\"\n  apply(simp, rule gronwall_general_left[where b=0, simplified, OF assms(2-6)[unfolded G_def]])\n  using assms(7,8)\n  by simp_all\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/Ordinary_Differential_Equations/Library/Gronwall.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511543206819, "lm_q2_score": 0.8596637433190939, "lm_q1q2_score": 0.7357442070472849}}
{"text": "(*\n    $Id: sol.thy,v 1.5 2012/01/04 13:40:21 webertj Exp $\n    Author: Tobias Nipkow\n*)\n\nheader {* Context-Free Grammars *}\n\n(*<*) theory sol imports Main begin (*>*)\n\ntext {* This exercise is concerned with context-free grammars (CFGs).\nPlease read Section~7.4 in the tutorial which explains how to model\nCFGs as inductive definitions.  Our particular example is about\ndefining valid sequences of parentheses. *}\n\nsubsection {* Two grammars *}\n\ntext {* The most natural definition of valid sequences of parentheses is this:\n\\[ S \\quad\\to\\quad \\varepsilon \\quad\\mid\\quad '('~S~')' \\quad\\mid\\quad S~S \\]\nwhere $\\varepsilon$ is the empty word.\n\nA second, somewhat unusual grammar is the following one:\n\\[ T \\quad\\to\\quad \\varepsilon \\quad\\mid\\quad T~'('~T~')' \\]\n\nModel both grammars as inductive sets $S$ and $T$ and prove $S = T$. *}\n\ntext {* The alphabet: *}\n\ndatatype alpha = A | B\n\ntext {* Standard grammar: *}\n\ninductive_set S :: \"alpha list set\" where\nS1: \"[] : S\" |\nS2: \"w : S \\<Longrightarrow> A#w@[B] : S\" |\nS3: \"v : S \\<Longrightarrow> w : S \\<Longrightarrow> v @ w : S\"\n\ndeclare S1 [iff] S2[intro!,simp]\n\ntext {* Nonstandard grammar: *}\n\ninductive_set T :: \"alpha list set\" where\nT1: \"[] : T\" |\nT23: \"v : T \\<Longrightarrow> w : T \\<Longrightarrow> v @ A # w @ [B]: T\"\n\ndeclare T1 [iff]\n\ntext {* @{text T} is a subset of @{text S}: *}\n\nlemma T2S: \"w : T \\<Longrightarrow> w : S\"\n  apply (erule T.induct)\n    apply simp\n  apply (blast intro: S3)\ndone\n\ntext {* @{text S} is a subset of @{text T}: *}\n\nlemma T2: \"w : T \\<Longrightarrow> A#w@[B] : T\"\n  using T23[where v = \"[]\"] by simp\n\nlemma T3: \"v : T \\<Longrightarrow> u : T \\<Longrightarrow> u@v : T\"\n  apply (erule T.induct)\n    apply fastforce\n  apply (simp add: append_assoc[symmetric] del:append_assoc)\n  apply (blast intro: T23)\ndone\n\nlemma S2T: \"w : S \\<Longrightarrow> w : T\"\n  apply (erule S.induct)\n      apply simp\n    apply (blast intro: T2)\n  apply (blast intro: T3)\ndone\n\ntext {* @{text \"S = T\"}: *}\n\nlemma \"S = T\"\n  by (blast intro: S2T T2S)\n\n\nsubsection {* A recursive function *}\n\ntext {* Instead of a grammar, we can also define valid sequences of\nparentheses via a test function:  traverse the word from left to right\nwhile counting how many closing parentheses are still needed.  If the\ncounter is 0 at the end, the sequence is valid.\n\nDefine this recursive function and prove that a word is in $S$ iff it\nis accepted by your function.  The $\\Longrightarrow$ direction is easy,\nthe other direction more complicated. *}\n\nfun balanced :: \"alpha list \\<Rightarrow> nat \\<Rightarrow> bool\" where\n  \"balanced []    0       = True\"\n| \"balanced (A#w) n       = balanced w (Suc n)\"\n| \"balanced (B#w) (Suc n) = balanced w n\"\n| \"balanced w     n       = False\"\n\ntext {* Correctness of the recognizer w.r.t.\\ @{text S}: *}\n\n\n\nlemma [simp]: \"\\<lbrakk>balanced v n; balanced w 0\\<rbrakk> \\<Longrightarrow> balanced (v @ w) n\"\n  apply (induct v n rule: balanced.induct)\n  apply simp_all\ndone\n\nlemma \"w : S \\<Longrightarrow> balanced w 0\"\n  apply (erule S.induct)\n  apply simp_all\ndone\n\ntext {* Completeness of the recognizer w.r.t.\\ @{text S}: *}\n\n\n\nlemma AB: assumes u: \"u \\<in> S\" shows \"\\<And>v w. u = v@w \\<Longrightarrow> v @ A # B # w \\<in> S\"\nusing u\nproof(induct)\n  case S1 thus ?case by simp\nnext\n  case (S2 u)\n  have uS: \"u \\<in> S\" and\n       IH: \"\\<And>v w. u = v @ w \\<Longrightarrow> v @ A # B # w \\<in> S\" and\n       asm: \"A # u @ [B] = v @ w\" by fact+\n  show \"v @ A # B # w \\<in> S\"\n  proof (cases v)\n    case Nil\n    hence \"w = A # u @ [B]\" using asm by simp\n    hence \"w \\<in> S\" using uS by simp\n    hence \"[A,B] @ w \\<in> S\" by(blast intro:S3)\n    thus ?thesis using Nil by simp\n  next\n    case (Cons x v')\n    show ?thesis\n    proof (cases w rule:rev_cases)\n      case Nil\n      from uS have \"(A # u @ [B]) @ [A,B] \\<in> S\" by(blast intro:S3)\n      thus ?thesis using Nil Cons asm by auto\n    next\n      case (snoc w' y)\n      hence u: \"u = v' @ w'\" and [simp]: \"x = A & y = B\"\n\tusing Cons asm by auto\n      from u have \"v' @ A # B # w' \\<in> S\" by(rule IH)\n      hence \"A # (v' @ A # B # w') @ [B] \\<in> S\" by(rule S.S2)\n      thus ?thesis using Cons snoc by auto\n    qed\n  qed\nnext\n  case (S3 v' w')\n  have v'S: \"v' \\<in> S\" and w'S: \"w' \\<in> S\"\n   and IHv: \"\\<And>v w. v' = v @ w \\<Longrightarrow> v @ A # B # w \\<in> S\"\n   and IHw: \"\\<And>v w. w' = v @ w \\<Longrightarrow> v @ A # B # w \\<in> S\"\n   and asm: \"v' @ w' = v @ w\" by fact+\n  then obtain r where \"v' = v @ r \\<and> r @ w' = w \\<or> v' @ r = v \\<and> w' = r @ w\"\n    (is \"?A \\<or> ?B\")\n    by (auto simp:append_eq_append_conv2)\n  thus \"v @ A # B # w \\<in> S\"\n  proof\n    assume A: ?A\n    hence \"v @ A # B # r \\<in> S\" using IHv by blast\n    hence \"(v @ A # B # r) @ w' \\<in> S\" using w'S by(rule S.S3)\n    thus ?thesis using A by auto\n  next\n    assume B: ?B\n    hence \"r @ A # B # w \\<in> S\" using IHw by blast\n    with v'S have \"v' @ (r @ A # B # w) \\<in> S\" by(rule S.S3)\n    thus ?thesis using B by auto\n  qed\nqed\n\ntext {* The same lemma for friends of the apply style: *}\n\nlemma \"u \\<in> S \\<Longrightarrow> ALL v w. u = v@w \\<longrightarrow> v @ A # B # w \\<in> S\"\napply(erule S.induct)\n  apply simp\n apply(rename_tac u)\n apply (clarsimp simp:Cons_eq_append_conv)\n apply(rule conjI)\n  apply (clarsimp)\n  apply(subgoal_tac \"[A,B] @ (A # u @ [B]) : S\")\n   apply(simp)\n  apply(blast intro:S3)\n apply(clarsimp simp:append_eq_append_conv2 Cons_eq_append_conv)\n apply(rename_tac w w1 w2)\n apply(erule disjE)\n  apply clarsimp\n  apply(subgoal_tac \"A # (w1 @ A # B # w2) @ [B] : S\")\n   apply simp\n  apply(blast intro:S3)\n apply clarsimp\n apply(erule disjE)\n  apply clarsimp\n  apply(subgoal_tac \"A # (u @ [A,B]) @ [B] : S\")\n   apply(simp)\n  apply(blast intro:S3)\n apply clarsimp\n apply(subgoal_tac \"(A # u @ [B]) @ [A,B] : S\")\n  apply(simp)\n apply(blast intro:S3)\napply(clarsimp simp:append_eq_append_conv2)\napply(rename_tac u v w x y)\napply(erule disjE)\n apply clarsimp\n apply(subgoal_tac \"(w @ A # B # y) @ v : S\")\n  apply(simp)\n apply(blast intro:S3)\napply clarsimp\napply(blast intro:S3)\ndone\n\nlemma \"balanced w n \\<Longrightarrow> replicate n A @ w : S\"\n  apply (induct w n rule: balanced.induct)\n  apply simp_all\n    apply (simp add: replicate_app_Cons_same)\n  apply (simp add: AB replicate_app_Cons_same[symmetric])\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/logic/parentheses/sol.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8558511469672595, "lm_q2_score": 0.8596637469145054, "lm_q1q2_score": 0.7357442038029514}}
{"text": "theory Section4\nimports Main \"~~/src/HOL/Library/Order_Relation\" \"~~/src/HOL/Library/Zorn\"\n\nbegin\n\n(* Section 4.1 *)\n\ntypedecl p\n\ndatatype Lit = P p (\"_.\" 500) | Not p (\"_`\")\n\nfun complement :: \"Lit \\<Rightarrow> Lit\" (\"_\\<acute>\" 300) where\n  \"(p`)\\<acute> = (p.)\"\n| \"(p.)\\<acute> = (p`)\"\n\ndatatype formula = All Lit Lit (\"All _ are _ \") | Some Lit Lit (\"Some _ are _\") \n\nlemma \"(p.)\\<acute> = (p`)\" by (rule complement.simps(2))\n\nlemma complement_involutive[simp] : \"x\\<acute>\\<acute> = x\"\n  by (metis Lit.exhaust complement.simps(1) complement.simps(2))\n(*declare [[show_types]]*)\n\n\ntype_synonym 'a model = \"p \\<Rightarrow>'a set\"\n\nfun modelOnLit :: \"'a model \\<Rightarrow> Lit \\<Rightarrow>'a set\" where\n  \"modelOnLit M (x`) = (UNIV::'a set) - M (x)\"\n |\"modelOnLit M (x.) = M (x)\"\n\n\nfun M_satisfies :: \"'a model \\<Rightarrow> formula \\<Rightarrow> bool\" (\"_ \\<Turnstile> _\")\nwhere\n  \"M_satisfies M (All x are y) = (modelOnLit M x \\<subseteq> modelOnLit M y)\"\n| \"M_satisfies M (Some x are y) = (\\<exists>e. e \\<in> modelOnLit M x \\<inter> modelOnLit M y)\"\n\n\n\nlemma \n assumes \"M \\<Turnstile> All (p.) are (q`)\"\n shows \"M p \\<inter> M q = {}\" (* eqivalent to saying M \\<Turnstile> No p are q *)\nproof -\n  from assms have \"M p \\<subseteq> modelOnLit M (q`)\"\n    by simp\n  then have \"M p \\<subseteq> ( UNIV - M q )\"\n    by simp\n  then show ?thesis by auto\nqed\n\ninductive derarg :: \"formula set \\<Rightarrow> formula \\<Rightarrow> bool\" (\"_ \\<turnstile> _\")\n  for hs\n  where\n  axiom: \"hs \\<turnstile> All X are X\"\n| some1: \"hs \\<turnstile> Some X are Y \\<Longrightarrow> hs \\<turnstile> Some X are X\"\n| some2: \"hs \\<turnstile> Some X are Y \\<Longrightarrow> hs \\<turnstile> Some Y are X\"\n| barbara: \"\\<lbrakk>hs \\<turnstile> All X are Y; hs \\<turnstile> All Y are Z\\<rbrakk> \\<Longrightarrow> hs \\<turnstile> All X are Z\"\n| darii: \"\\<lbrakk>hs \\<turnstile> All Y are Z; hs \\<turnstile> Some X are Y\\<rbrakk> \\<Longrightarrow> hs \\<turnstile> Some X are Z\"\n| zero: \"hs \\<turnstile> All X  are (X\\<acute>) \\<Longrightarrow> hs \\<turnstile> All X are Y\"\n| one: \"hs \\<turnstile> All (Y\\<acute>) are Y \\<Longrightarrow> hs \\<turnstile> All X are Y\"\n| antitone: \"hs \\<turnstile> All Y are (X\\<acute>) \\<Longrightarrow> hs \\<turnstile> All X are (Y\\<acute>)\"\n| x: \"\\<lbrakk>hs \\<turnstile> All X are Y; hs \\<turnstile> Some X are (Y\\<acute>)\\<rbrakk> \\<Longrightarrow> hs \\<turnstile> _\"\n| ass: \"f \\<in> hs \\<Longrightarrow> hs \\<turnstile> f\"\n\nlemma \"{Some (p`) are (q.)} \\<turnstile> Some (q.) are (q.)\"\nproof -\n  have \"{Some (p`) are (q.)} \\<turnstile> Some (q.) are (p`)\" by (simp add: ass derarg.some2)\n  then show ?thesis by (simp add: derarg.some1)\nqed\n\n\n\n(* section 4.2 *)  \n\n\n(* preorder on Lit induced by set of formulas G *)\nfun less_equal_Lit :: \"Lit \\<Rightarrow> formula set \\<Rightarrow> Lit \\<Rightarrow> bool\" (\"_ \\<lesssim> _ _\")  where\n  \"less_equal_Lit x G y = (G \\<turnstile> All x are y)\"\n\n\n(* TT: export the theorems for trans and refl, since they are useful in the following *)\nlemma less_equal_Lit_refl [simp]:\n  \"\\<And>x G. x \\<lesssim>G x\"\n  by (metis axiom less_equal_Lit.elims(3))\n\nlemma less_equal_Lit_trans:\n  \"\\<And>x G y z. x \\<lesssim>G y \\<Longrightarrow> y \\<lesssim>G z \\<Longrightarrow> x \\<lesssim>G z\"\n  by (metis barbara less_equal_Lit.simps(1))\n\nlemma less_equal_Lit_ass [simp] :\n  \"(All x are y) \\<in> G \\<Longrightarrow> less_equal_Lit x G y\"\n  by (metis ass less_equal_Lit.simps(1))\n\nlemma less_equal_Lit_antitone :\n  \"\\<And>G x y. (x \\<lesssim>G y) \\<longleftrightarrow> ((y\\<acute>) \\<lesssim>G (x\\<acute>))\"\nby (metis antitone complement_involutive less_equal_Lit.simps)\n\n\nlemma prop_2_1:\n  fixes G \n  defines R_def: \"R \\<equiv> { (x, y). less_equal_Lit x G y }\"\n  shows \"preorder_on UNIV R\"\nproof -\n  have \"refl R\"\n    by (simp add: refl_on_def R_def) (metis axiom)\n  have \"trans R\"\n    by (metis assms less_equal_Lit_trans mem_Collect_eq old.prod.case transI)\n  with `refl R` show ?thesis by (simp add: preorder_on_def)\nqed\n\n(* equivalence relation induced by the preorder *)\n(* should we rename equiv_Lit to equal_Lit? - cant there is an automatically generated definition called equal_Lit *)\ndefinition equiv_Lit :: \"Lit \\<Rightarrow> formula set \\<Rightarrow> Lit \\<Rightarrow> bool\" (\"_ \\<approx>_ _\")  where\n  \"equiv_Lit x G y \\<equiv> less_equal_Lit x G y \\<and> less_equal_Lit y G x\"\n  \n\nlemma equiv_Lit_refl [simp]:\n  \"\\<And>G x. x \\<approx>G x\"\nunfolding equiv_Lit_def by (metis less_equal_Lit_refl)\n\nlemma equiv_Lit_antitone:\n  \"\\<And>G x y. (x \\<approx>G y) \\<longleftrightarrow> ((x\\<acute>) \\<approx>G (y\\<acute>))\"\nby (metis antitone complement_involutive equiv_Lit_def less_equal_Lit.simps)\n\n\n\ndefinition Lit_poset_eqclass :: \"Lit \\<Rightarrow> formula set \\<Rightarrow> Lit set\" (\"[[_]]_\") where\n  \"Lit_poset_eqclass x G \\<equiv> {y. x \\<approx>G y}\"\n\nlemma Lit_poset_eqclass_membership : \"\\<And>x G. x \\<in> [[x]]G\"\n  unfolding Lit_poset_eqclass_def by (metis equiv_Lit_refl mem_Collect_eq)\n\nlemma Lit_poset_eqclass_equivalence [simp]: \"\\<And>x G y. x \\<approx>G y \\<Longrightarrow> ([[x]]G) = ([[y]]G)\"\n  unfolding Lit_poset_eqclass_def equiv_Lit_def\n  by (metis less_equal_Lit_trans)\n\n\ndatatype lit_mod_elt = Zero_rep | One_rep | Equiv \"Lit set\"\n\ndefinition Lit_mod :: \"formula set \\<Rightarrow> lit_mod_elt set\" where\n   \"Lit_mod G = { Equiv ([[x]]G) | x. x \\<in> UNIV }\"\n\ndefinition Lit_mod_plus_cond :: \"formula set => bool\" where\n  \"Lit_mod_plus_cond G \\<equiv> \\<exists> p. (p \\<lesssim>G (p\\<acute>))\"\n\ndefinition Lit_mod_plus :: \"formula set \\<Rightarrow> lit_mod_elt set\" where\n  \"Lit_mod_plus G \\<equiv> if Lit_mod_plus_cond G then Lit_mod G else\n  ((Lit_mod G) \\<union> {Zero_rep, One_rep})\"\n\ndefinition zero :: \"formula set \\<Rightarrow> lit_mod_elt\" where\n  \"zero G \\<equiv> if Lit_mod_plus_cond G then Equiv([[SOME p. (p \\<lesssim>G (p\\<acute>))]]G) else Zero_rep\"\n\n\nlemma Lit_mod_intro[simp] : \"\\<And>x. ( Equiv [[x]]G) \\<in> Lit_mod G\"\nunfolding Lit_mod_def\nby (metis (lifting, mono_tags) UNIV_I mem_Collect_eq)\n\n\nlemma Lit_mod_plus_intro[simp] : \"\\<And>x. ( Equiv [[x]]G) \\<in> Lit_mod_plus G\"\nunfolding Lit_mod_plus_def by fastforce\n\n\nlemma Lit_mod_intro2[simp] : \"\\<And>x. x \\<in> Lit_mod G \\<Longrightarrow> \\<exists>y. x = (Equiv [[y]]G)\"\nunfolding Lit_mod_def\nproof -\n  fix x\n  assume \"x \\<in> {(Equiv [[x]]G) |x. x \\<in> UNIV}\"\n  hence \"\\<exists>xa. x = (Equiv [[xa]]G) \\<and> xa \\<in> UNIV\"\n    by fastforce\n  thus \"\\<exists>y. x = (Equiv [[y]]G)\"\n    by simp\nqed\n\nfun less_equal_Lit_poset_eqclass :: \"lit_mod_elt \\<Rightarrow> formula set \\<Rightarrow> lit_mod_elt \\<Rightarrow> bool\" (\"_ \\<lesssim>._ _\" 400) where\n  \"less_equal_Lit_poset_eqclass (Equiv a) G (Equiv b) = (\\<exists>aa \\<in> a. \\<exists>bb \\<in> b. (aa \\<lesssim>G bb))\"\n  | \"less_equal_Lit_poset_eqclass Zero_rep G _ = True\"\n  | \"less_equal_Lit_poset_eqclass _ G One_rep = True\"\n  | \"less_equal_Lit_poset_eqclass One_rep G _ = False\"\n  | \"less_equal_Lit_poset_eqclass _ G Zero_rep = False\"\n\nlemma less_equal_Lit_poset_eqclass_simp[simp] : \n  \"(a \\<lesssim>G b) \\<longleftrightarrow> (Equiv ([[a]]G) \\<lesssim>.G (Equiv [[b]]G))\"\nproof -\n  {\n    assume \"a \\<lesssim>G b\"\n    have \"Equiv ([[a]]G) \\<lesssim>.G (Equiv [[b]]G)\"\n      by (metis Lit_poset_eqclass_membership `a \\<lesssim> G b` less_equal_Lit_poset_eqclass.simps(1))\n  }\n  {\n    assume \"Equiv ([[a]]G) \\<lesssim>.G (Equiv [[b]]G)\"\n    have 1: \"\\<exists>aa \\<in> ([[a]]G). \\<exists>bb \\<in> ([[b]]G). (aa \\<lesssim>G bb)\"\n      by (metis `(Equiv [[a]]G) \\<lesssim>.G (Equiv [[b]]G)` less_equal_Lit_poset_eqclass.simps(1))\n    have \"\\<forall>x \\<in> ([[a]]G). (a \\<lesssim>G x)\" \"\\<forall>y \\<in> ([[b]]G). (b \\<lesssim>G y)\"\n      by (metis Lit_poset_eqclass_def equiv_Lit_def mem_Collect_eq)+\n    with 1 have \"a \\<lesssim>G b\"\n      by (metis Lit_poset_eqclass_def equiv_Lit_def less_equal_Lit_trans mem_Collect_eq)\n  }\n  thus ?thesis\n    by (metis `a \\<lesssim> G b \\<Longrightarrow> (Equiv [[a]]G) \\<lesssim>.G (Equiv [[b]]G)`)\nqed\n\n\nlemma less_equal_Lit_poset_eqclass_simp2[simp] : \n  \"\\<And>x G. (Equiv [[x]]G) \\<lesssim>.G (Equiv [[x]]G)\"\nunfolding Lit_poset_eqclass_def\nby (metis equiv_Lit_def equiv_Lit_refl less_equal_Lit_poset_eqclass.simps(1) mem_Collect_eq)\n\nlemma zero_less_equal_Lit_poset_eqclass:\n  fixes G p\n  assumes \"p \\<lesssim>G (p\\<acute>)\"\n  shows \"\\<forall>q. ((Equiv [[p]]G) \\<lesssim>.G (Equiv [[q]]G))\"\nproof -\n  from assms have \"\\<forall>q. (p \\<lesssim>G q)\"\n    by (metis less_equal_Lit.simps zero)\n  then show ?thesis by (metis less_equal_Lit_poset_eqclass_simp)\nqed\n\nlemma 10[simp]:\n  fixes G x a\n  assumes \"(Equiv x) \\<in> Lit_mod_plus G\"\n  and \"a \\<in> x\"\n  shows \"(Equiv [[a]]G) = (Equiv x)\"\nproof -\n  from assms(1) have \"\\<exists>a. (Equiv x) = (Equiv [[a]]G)\"\n    by (metis Lit_mod_intro2 Lit_mod_plus_def UnE insertE lit_mod_elt.distinct(3) lit_mod_elt.distinct(5) singleton_iff)\n  {\n    fix l\n    assume \"x \\<equiv> [[l]]G\"\n    have \"a \\<approx>G l\"\n      by (metis Lit_poset_eqclass_def `x \\<equiv> [[l]]G` assms(2) equiv_Lit_def mem_Collect_eq)\n    have ?thesis\n      by (metis Lit_poset_eqclass_equivalence `a \\<approx> G l` `x \\<equiv> [[l]]G`)\n  }\n  thus ?thesis\n    by (metis `\\<exists>a. Equiv x = Equiv [[a]]G` lit_mod_elt.inject)\nqed\n\n(*lemma 11:\n  fixes G l\n  defines \"a \\<equiv> ([[l]]G)\"\n  shows \"a = \\<Union>{ ([[y]]G) | y. y \\<in> a }\"\nproof -\n  have 1: \"\\<forall>x \\<in> a. ([[x]]G) = a\"\n    by (metis Lit_poset_eqclass_def Lit_poset_eqclass_equivalence assms mem_Collect_eq)\n  then have \"\\<Union>{ ([[y]]G) | y. y \\<in> a } \\<subseteq> a\" by fast\n  with 1 assms show ?thesis \n    by (metis (lifting, mono_tags) Union_upper mem_Collect_eq subsetI subset_antisym)\nqed\n*)\n(*lemma\n  fixes G l x\n  defines \"a \\<equiv> (Lit_poset_eqclass G l)\"\n  assumes \"x \\<in> a\"\n  shows \"(Lit_poset_eqclass x G) = \\<Union>{ (Lit_poset_eqclass G y) | y. y \\<in> a }\"\nusing 10[of x G l]\nusing 11[of G l]\nby (metis assms)*)\n\nfun complement_Lit_poset_eqclass :: \"lit_mod_elt \\<Rightarrow> formula set \\<Rightarrow> lit_mod_elt\" (infix \".\\<acute>\" 400)  where \n  \"(Equiv a).\\<acute>G = Equiv([[(SOME p. (p \\<in> a))\\<acute>]]G)\"\n  | \"Zero_rep.\\<acute>G = One_rep\"\n  | \"One_rep.\\<acute>G = Zero_rep\"\n\ndefinition one :: \"formula set \\<Rightarrow> lit_mod_elt\" where\n  \"one G \\<equiv> zero G .\\<acute>G\"\n\nlemma complement_Lit_poset_eqclass_equivalence:\n  fixes G x a b\n  assumes \"(Equiv x) \\<in> Lit_mod_plus G\"\n  and \"a \\<in> x\"\n  and \"b \\<in> x\"\n  shows \"(Equiv [[a\\<acute>]]G) = (Equiv [[b\\<acute>]]G)\"\nproof -\n  have \"a \\<approx>G b\"\n    by (metis \"10\" Lit_poset_eqclass_def assms(1) assms(2) assms(3) lit_mod_elt.inject mem_Collect_eq)\n  then have \"(a\\<acute>) \\<approx>G (b\\<acute>)\" by (metis equiv_Lit_antitone)\n  thus ?thesis by force\nqed\n\nlemma complement_Lit_poset_eqclass_simp: \n  fixes G x a\n  assumes \"(Equiv x) \\<in> Lit_mod_plus G\"\n  and \"a \\<in> x\"\n  shows \"(Equiv [[a\\<acute>]]G) = (Equiv x).\\<acute>G\"\nby (metis (lifting) assms(1) assms(2) complement_Lit_poset_eqclass.simps(1) complement_Lit_poset_eqclass_equivalence someI)  \n\n\nlemma complement_Lit_poset_eqclass_simp2 [simp]: \"\\<And>x G. Equiv [[x\\<acute>]]G \\<equiv> (Equiv [[x]]G).\\<acute>G\"\nproof -\n  fix x :: Lit and G :: \"formula set\"\n  have \"(Equiv [[x]]G).\\<acute>G = Equiv [[(x\\<acute>)]]G\"\n    by (metis Lit_mod_intro Lit_mod_plus_def Lit_poset_eqclass_def UnI1 complement_Lit_poset_eqclass_simp equiv_Lit_refl mem_Collect_eq)\n  thus \"(Equiv [[x\\<acute>]]G) \\<equiv> (Equiv [[x]]G).\\<acute>G\"\n    using Lit_poset_eqclass_def by simp\nqed\n\nlemma Lit_poset_eqclass_reflexive:\n  fixes G x\n  assumes \"x \\<in> Lit_mod_plus G\"\n  shows \"x \\<lesssim>.G x\"\nproof (cases x)\n  case Zero_rep\n  thus ?thesis by simp\nnext\n  case One_rep\n  thus ?thesis by simp\nnext\n  case Equiv\n  obtain y where \"x \\<equiv> Equiv y\" by (metis Equiv)\n  have 1: \"\\<forall>a \\<in> y. (Equiv [[a]]G) = x\" by (metis \"10\" `x \\<equiv> Equiv y` assms)\n  have \"\\<forall>a \\<in> y. (a \\<lesssim>G a)\" by (metis less_equal_Lit_refl)\n  then have \"\\<forall>a \\<in> y. ((Equiv [[a]]G) \\<lesssim>.G (Equiv [[a]]G))\" by (metis less_equal_Lit_poset_eqclass_simp2)\n  obtain a where \"(Equiv [[a]]G) = x\" \"((Equiv [[a]]G) \\<lesssim>.G (Equiv [[a]]G))\"\n    by (metis Equiv Lit_mod_intro2 Lit_mod_plus_def Un_insert_right assms insert_iff less_equal_Lit_poset_eqclass_simp2 lit_mod_elt.distinct(3) lit_mod_elt.distinct(5) sup_bot_right)\n  thus ?thesis by fast\nqed\n\nlemma Lit_poset_eqclass_trans:\n  fixes G x y z\n  assumes \"x \\<in> Lit_mod_plus G\"\n  and \"y \\<in> Lit_mod_plus G\"\n  and \"z \\<in> Lit_mod_plus G\"\n  and \"(x \\<lesssim>.G y)\"\n  and \"(y \\<lesssim>.G z)\"\n  shows \"(x \\<lesssim>.G z)\"\nproof (cases x)\n  case Zero_rep\n  thus ?thesis by simp\nnext\n  case One_rep\n  thus ?thesis\n    by (metis assms(4) assms(5) less_equal_Lit_poset_eqclass.elims(2) lit_mod_elt.distinct(1) lit_mod_elt.distinct(5))\nnext\n  case Equiv\n  note Equiv_x = Equiv\n  thus ?thesis\n  proof (cases y)\n    case Zero_rep\n    have False by (metis Equiv Zero_rep assms(4) less_equal_Lit_poset_eqclass.simps(7))\n    thus ?thesis ..\n  next\n    case One_rep\n    thus ?thesis\n      by (metis Equiv assms(5) less_equal_Lit_poset_eqclass.simps(4) less_equal_Lit_poset_eqclass.simps(5) less_equal_Lit_poset_eqclass.simps(6) lit_mod_elt.exhaust)\n  next\n    case Equiv\n    note Equiv_y = Equiv\n    thus ?thesis\n    proof (cases z)\n      case Zero_rep\n      have False by (metis Equiv_y Zero_rep assms(5) less_equal_Lit_poset_eqclass.simps(7))\n      thus ?thesis ..\n    next\n      case One_rep\n      thus ?thesis by (metis Equiv_x less_equal_Lit_poset_eqclass.simps(4))\n    next\n      case Equiv\n      note Equiv_z = Equiv\n      obtain e f g where \"x \\<equiv> Equiv e\" \"y \\<equiv> Equiv f\" \"z \\<equiv> Equiv g\"\n        by (metis Equiv_x Equiv_y Equiv_z)\n      then have 1 : \"\\<forall>a \\<in> e. \\<forall>b \\<in> f. (a \\<lesssim>G b)\"\n      proof -\n        obtain a b where \"a \\<in> e\" \"b \\<in> f\"\n          by (metis `x \\<equiv> Equiv e` `y \\<equiv> Equiv f` assms(4) less_equal_Lit_poset_eqclass.simps(1))\n        then have \"Equiv ([[a]]G) = x\" \"Equiv ([[b]]G) = y\"\n          using \"10\" \\<open>x \\<equiv> Equiv e\\<close> assms(1) apply blast\n          using \\<open>b \\<in> f\\<close> \\<open>y \\<equiv> Equiv f\\<close> assms(2) by auto\n        then have \"(Equiv ([[a]]G)) \\<lesssim>.G (Equiv ([[b]]G))\" by (metis assms(4))\n        then have  \"a \\<lesssim>G b\" by (metis less_equal_Lit_poset_eqclass_simp)\n        thus ?thesis by (metis Lit_poset_eqclass_def Lit_poset_eqclass_equivalence `x \\<equiv> Equiv e` `y \\<equiv> Equiv f` `(Equiv [[a]]G) = x` `(Equiv [[b]]G) = y` less_equal_Lit_poset_eqclass_simp lit_mod_elt.inject mem_Collect_eq)\n      qed\n      have 2 : \"\\<forall>a \\<in> f. \\<forall>b \\<in> g. (a \\<lesssim>G b)\"\n      proof -\n        obtain b c where \"b \\<in> f\" \"c \\<in> g\"\n          by (metis `z \\<equiv> Equiv g` `y \\<equiv> Equiv f` assms(5) less_equal_Lit_poset_eqclass.simps(1))\n        then have \"Equiv ([[b]]G) = y\" \"Equiv ([[c]]G) = z\" \n          by (metis \"10\" `y \\<equiv> Equiv f` assms(2)) (metis \"10\" `c \\<in> g` `z \\<equiv> Equiv g` assms(3))\n        then have \"(Equiv ([[b]]G)) \\<lesssim>.G (Equiv ([[c]]G))\" by (metis assms(5))\n        then have  \"b \\<lesssim>G c\" by (metis less_equal_Lit_poset_eqclass_simp)\n        thus ?thesis by (metis Lit_poset_eqclass_def Lit_poset_eqclass_equivalence `y \\<equiv> Equiv f` `z \\<equiv> Equiv g` `(Equiv [[b]]G) = y` `(Equiv [[c]]G) = z` assms(5) less_equal_Lit_poset_eqclass_simp lit_mod_elt.inject mem_Collect_eq)\n      qed\n\n      from 1 2 have \"\\<forall>a \\<in> e. \\<forall>b \\<in> g. (a \\<lesssim>G b)\" \n        by (metis `x \\<equiv> Equiv e` `y \\<equiv> Equiv f` assms(4) ex_in_conv less_equal_Lit_poset_eqclass.simps(1) less_equal_Lit_trans)\n      thus ?thesis\n        by (metis `x \\<equiv> Equiv e` `y \\<equiv> Equiv f` `z \\<equiv> Equiv g` assms(4) assms(5) less_equal_Lit_poset_eqclass.simps(1))\n    qed\n  qed\nqed\n\nlemma Lit_poset_eqclass_antisym:\n  fixes G x y\n  assumes \"x \\<in> Lit_mod_plus G\"\n  and \"y \\<in> Lit_mod_plus G\"\n  and \"(x \\<lesssim>.G y)\"\n  and \"(y \\<lesssim>.G x)\"\n  shows \"x = y\"\nproof (cases x)\n  case Zero_rep\n  thus ?thesis by (metis assms(4) less_equal_Lit_poset_eqclass.simps(5) less_equal_Lit_poset_eqclass.simps(7) lit_mod_elt.exhaust)\nnext\n  case One_rep\n  thus ?thesis by (metis assms(3) less_equal_Lit_poset_eqclass.simps(5) less_equal_Lit_poset_eqclass.simps(6) lit_mod_elt.exhaust)\nnext\n  case Equiv\n  note Equiv_x = Equiv\n  thus ?thesis\n  proof (cases y)\n    case Zero_rep\n    thus ?thesis by (metis Equiv_x assms(3) less_equal_Lit_poset_eqclass.simps(7))\n  next\n    case One_rep\n    thus ?thesis by (metis Equiv_x assms(4) less_equal_Lit_poset_eqclass.simps(6))\n  next\n    case Equiv\n    note Equiv_y = Equiv\n    obtain e f where \"x \\<equiv> Equiv e\" \"y \\<equiv> Equiv f\" by (metis Equiv_x Equiv_y)\n    have 1 : \"\\<forall>a \\<in> e. \\<forall>b \\<in> f. (a \\<lesssim>G b)\"\n      by (metis \"10\" `x \\<equiv> Equiv e` `y \\<equiv> Equiv f` assms(1) assms(2) assms(3) less_equal_Lit_poset_eqclass_simp lit_mod_elt.inject)\n\n    have 2 : \"\\<forall>a \\<in> f. \\<forall>b \\<in> e. (a \\<lesssim>G b)\"\n      by (metis \"10\" `x \\<equiv> Equiv e` `y \\<equiv> Equiv f` assms(1) assms(2) assms(4) less_equal_Lit_poset_eqclass_simp lit_mod_elt.inject)\n  \n    from 1 2 have \"\\<forall>a \\<in> e. \\<forall>b \\<in> f. (a \\<approx>G b)\" by (metis equiv_Lit_def)\n    then have \"\\<forall>a \\<in> e. \\<forall>b \\<in> f. (Equiv [[a]]G) = (Equiv [[b]]G)\" by force\n    thus ?thesis \n      by (metis \"10\" `x \\<equiv> Equiv e` `y \\<equiv> Equiv f` assms(1) assms(2) assms(3) less_equal_Lit_poset_eqclass.elims(2) lit_mod_elt.distinct(3) lit_mod_elt.distinct(5) lit_mod_elt.inject)\n  qed\nqed\n\n\nlemma Lit_eqclass_partial_order:\n  fixes G \n  defines R_def: \"R \\<equiv> { (x, y). x \\<in> Lit_mod_plus G \\<and> y \\<in> Lit_mod_plus G \\<and> (x \\<lesssim>.G y) }\"\n  shows \"partial_order_on (Lit_mod_plus G) R\"\nproof -\n  have \"refl_on (Lit_mod_plus G) R\"\n    unfolding refl_on_def\n    by (metis (lifting) Lit_poset_eqclass_reflexive SigmaI assms mem_Collect_eq split_conv subrelI)\n\n  have \"trans R\"\n    unfolding trans_def\n    using Lit_poset_eqclass_trans assms by blast\n\n  have \"antisym R\"\n    unfolding antisym_def\n      by (metis (lifting) Lit_poset_eqclass_antisym assms mem_Collect_eq split_conv)\n  \n  with `refl_on (Lit_mod_plus G) R` `trans R` show ?thesis by (metis partial_order_on_def preorder_on_def)\nqed\n\n\nlemma Lit_eqclass_antitone :\n  fixes G x y\n  assumes \"x \\<in> Lit_mod_plus G\"\n  and \"y \\<in> Lit_mod_plus G\"\n  shows \"(x \\<lesssim>.G y) \\<longleftrightarrow> ((y.\\<acute>G) \\<lesssim>.G (x.\\<acute>G))\"\nproof (cases x)\n  case Zero_rep\n  thus ?thesis by (metis complement_Lit_poset_eqclass.simps(2) less_equal_Lit_poset_eqclass.elims(3) less_equal_Lit_poset_eqclass.simps(2) less_equal_Lit_poset_eqclass.simps(3) less_equal_Lit_poset_eqclass.simps(4) lit_mod_elt.distinct(1))\nnext\n  case One_rep\n  thus ?thesis by (metis complement_Lit_poset_eqclass.simps(1) complement_Lit_poset_eqclass.simps(2) complement_Lit_poset_eqclass.simps(3) less_equal_Lit_poset_eqclass.elims(2) less_equal_Lit_poset_eqclass.elims(3) lit_mod_elt.distinct(1) lit_mod_elt.distinct(5))\nnext\n  case Equiv\n  note Equiv_x = Equiv\n  thus ?thesis\n  proof (cases y)\n    case Zero_rep\n    thus ?thesis by (metis Equiv_x complement_Lit_poset_eqclass.simps(1) complement_Lit_poset_eqclass.simps(2) less_equal_Lit_poset_eqclass.elims(2) less_equal_Lit_poset_eqclass.simps(7) lit_mod_elt.distinct(1) lit_mod_elt.distinct(5))\n  next\n    case One_rep\n    thus ?thesis by (metis Equiv_x complement_Lit_poset_eqclass.simps(3) less_equal_Lit_poset_eqclass.simps(2) less_equal_Lit_poset_eqclass.simps(4))\n  next\n    case Equiv\n    note Equiv_y = Equiv\n\n    obtain e f where \"x \\<equiv> Equiv e\" \"y \\<equiv> Equiv f\" \n      by (metis Equiv_x Equiv_y)\n    have 1: \"\\<forall>a \\<in> e. (Equiv [[a]]G) = x\" by (metis \"10\" `x \\<equiv> Equiv e` assms(1))\n    have 2: \"\\<forall>a \\<in> f. (Equiv [[a]]G) = y\" by (metis \"10\" `y \\<equiv> Equiv f` assms(2))\n    have \"\\<forall>a \\<in> e. \\<forall>b \\<in> f. (a \\<lesssim>G b) \\<longleftrightarrow> ((b\\<acute>) \\<lesssim>G (a\\<acute>))\" by (metis less_equal_Lit_antitone)\n    then have \"\\<forall>a \\<in> e. \\<forall>b \\<in> f. ((Equiv [[a]]G) \\<lesssim>.G (Equiv [[b]]G)) \\<longleftrightarrow> ((Equiv [[(b\\<acute>)]]G) \\<lesssim>.G (Equiv [[(a\\<acute>)]]G))\" by (metis less_equal_Lit_poset_eqclass_simp)\n    then have 3: \"\\<forall>a \\<in> e. \\<forall>b \\<in> f. ((Equiv [[a]]G) \\<lesssim>.G (Equiv [[b]]G)) \\<longleftrightarrow> (((Equiv [[b]]G).\\<acute>G) \\<lesssim>.G ((Equiv [[a]]G).\\<acute>G))\" by (metis complement_Lit_poset_eqclass_simp2)\n    then obtain a b where \"((Equiv [[a]]G) \\<lesssim>.G (Equiv [[b]]G)) \\<longleftrightarrow> (((Equiv [[b]]G).\\<acute>G) \\<lesssim>.G ((Equiv [[a]]G).\\<acute>G))\" \"(Equiv [[a]]G) = x\" \"(Equiv [[b]]G) = y\"\n      by (metis \"1\" \"2\" Lit_poset_eqclass_reflexive `x \\<equiv> Equiv e` `y \\<equiv> Equiv f` all_not_in_conv assms(1) assms(2) complement_Lit_poset_eqclass_simp2 equals0I less_equal_Lit_poset_eqclass.simps(1))\n    thus ?thesis by fast\n  qed\nqed\n\nlemma Lit_eqclass_involutive :\n  fixes G x\n  assumes \"x \\<in> Lit_mod_plus G\"\n  shows \"((x.\\<acute>G).\\<acute>G) = x\"\nproof (cases x)\n  case Zero_rep\n  thus ?thesis by simp  \nnext\n  case One_rep\n  thus ?thesis by simp\nnext\n  case Equiv\n  then have \"x \\<in> Lit_mod G\"\n    by (metis \"10\" Lit_mod_intro Lit_poset_eqclass_reflexive assms less_equal_Lit_poset_eqclass.simps(1))\n  thus ?thesis by (metis Lit_mod_intro2 complement_Lit_poset_eqclass_simp2 complement_involutive)\nqed\n\n\nlemma Lit_eqclass_complement_in_Lit_mod:\n  fixes G x\n  assumes \"x \\<in> Lit_mod G\"\n  shows \"(x.\\<acute>G) \\<in> Lit_mod G\"\nby (metis Lit_mod_intro Lit_mod_intro2 assms complement_Lit_poset_eqclass_simp2)\n\n\nlemma zero_less_than_all:\n  fixes G x\n  assumes \"x \\<in> Lit_mod_plus G\"\n  shows \"(zero G \\<lesssim>.G x)\"\nproof -\n  {\n    assume \"\\<not>Lit_mod_plus_cond G\"\n    have ?thesis by (metis `\\<not> Lit_mod_plus_cond G` less_equal_Lit_poset_eqclass.simps(2) zero_def)\n  }\n  {\n    assume \"Lit_mod_plus_cond G\"\n    obtain p where \"zero G = p\" by simp\n    then obtain q where \"(Equiv [[q]]G) = p\" by (metis `Lit_mod_plus_cond G` zero_def)\n    then have \"(Equiv [[q]]G) = (Equiv [[SOME p. (p \\<lesssim> G (p\\<acute>))]]G)\" by (metis `Lit_mod_plus_cond G` `zero G = p` zero_def)\n    then have \"q \\<lesssim>G (q\\<acute>)\"\n      by (metis (lifting, no_types) Lit_mod_plus_cond_def Lit_poset_eqclass_def Lit_poset_eqclass_membership `(Equiv [[q]]G) = p` `Lit_mod_plus_cond G` complement_involutive empty_Collect_eq equiv_Lit_antitone equiv_Lit_def less_equal_Lit.elims(2) less_equal_Lit.elims(3) less_equal_Lit_trans lit_mod_elt.inject mem_Collect_eq one someI_ex)\n    then have ?thesis\n      by (metis Lit_mod_intro2 Lit_mod_plus_def `zero G = p` `(Equiv [[q]]G) = p` `Lit_mod_plus_cond G` assms zero_less_equal_Lit_poset_eqclass)\n  }\n  thus ?thesis by (metis `\\<not> Lit_mod_plus_cond G \\<Longrightarrow> zero G \\<lesssim>.G x`)\nqed\n\nlemma all_zero_Eqclasses:\n  fixes G a\n  assumes \"Lit_mod_plus_cond G\"\n  and \"a \\<lesssim>G (a\\<acute>)\"\n  shows \"(Equiv [[a]]G) = zero G\"\nproof (rule ccontr)\n  assume \"(Equiv [[a]]G) \\<noteq> zero G\"\n  then show False\n    by (metis Lit_mod_intro Lit_mod_plus_def Lit_poset_eqclass_antisym assms(1) assms(2) zero_def zero_less_equal_Lit_poset_eqclass zero_less_than_all)\nqed\n\nlemma Lit_eqiv_class_complement_inconsistency :\n  fixes G x y\n  assumes \"x \\<in> Lit_mod_plus G\"\n  and \"y \\<in> Lit_mod_plus G\"\n  and \"(x \\<lesssim>.G y)\"\n  and \"(x \\<lesssim>.G (y.\\<acute>G))\"\n  shows \"x = zero G\"\nproof (cases x)\n  case Zero_rep\n  thus ?thesis by (metis Lit_eqclass_complement_in_Lit_mod Lit_mod_intro2 Lit_mod_plus_def assms(1) complement_Lit_poset_eqclass.simps(2) lit_mod_elt.distinct(5) zero_def)\nnext\n  case One_rep\n  thus ?thesis by (metis assms(3) assms(4) complement_Lit_poset_eqclass.simps(3) less_equal_Lit_poset_eqclass.elims(2) lit_mod_elt.distinct(1) lit_mod_elt.distinct(5))\nnext\n  case Equiv\n  note Equiv_x = Equiv\n  thus ?thesis\n  proof (cases y)\n    case Zero_rep\n    thus ?thesis by (metis Equiv_x assms(3) less_equal_Lit_poset_eqclass.simps(7))\n  next\n    case One_rep\n    thus ?thesis by (metis Equiv_x assms(4) complement_Lit_poset_eqclass.simps(3) less_equal_Lit_poset_eqclass.simps(7))\n  next\n    case Equiv\n    note Equiv_y = Equiv\n    obtain e f where \"x \\<equiv> Equiv e\" \"y \\<equiv> Equiv f\" by (metis Equiv_x Equiv_y)\n    have \"\\<forall>a \\<in> e. \\<forall>b \\<in> f. (a \\<lesssim>G b)\"\n      by (metis \"10\" `x \\<equiv> Equiv e` `y \\<equiv> Equiv f` assms(1) assms(2) assms(3) less_equal_Lit_poset_eqclass_simp lit_mod_elt.inject)\n    have \"\\<forall>a \\<in> e. \\<forall>b \\<in> f. (a \\<lesssim>G (b\\<acute>))\"\n      by (metis \"10\" `x \\<equiv> Equiv e` `y \\<equiv> Equiv f` assms(1) assms(2) assms(4) complement_Lit_poset_eqclass_simp less_equal_Lit_poset_eqclass_simp lit_mod_elt.inject)\n    then obtain a b where \"(a \\<lesssim>G b)\" \"(a \\<lesssim>G (b\\<acute>))\" \"a \\<in> e\" \"b \\<in> f\"\n      by (metis `x \\<equiv> Equiv e` `y \\<equiv> Equiv f` assms(3) less_equal_Lit_poset_eqclass.simps(1))\n    have \"b \\<lesssim>G (a\\<acute>)\" by (metis `a \\<lesssim> G (b\\<acute>)` antitone less_equal_Lit.simps)\n    have \"a \\<lesssim>G (a\\<acute>)\" by (metis `a \\<lesssim> G b` `b \\<lesssim> G (a\\<acute>)` less_equal_Lit_trans)\n    have \"Lit_mod_plus_cond G\"\n      unfolding Lit_mod_plus_cond_def by (metis `a \\<lesssim> G (a\\<acute>)`)\n    then have \"zero G = (Equiv [[a]]G)\" by (metis `a \\<lesssim> G (a\\<acute>)` all_zero_Eqclasses)\n    thus ?thesis by (metis \"10\" `a \\<in> e` `x \\<equiv> Equiv e` assms(1))\n  qed\nqed\n\nlemma Lit_eqclass_in_Lit_mod_plus:\n  fixes G x\n  assumes \"x \\<in> Lit_mod_plus G\"\n  shows \"x.\\<acute>G \\<in> Lit_mod_plus G\"\nproof (cases x)\n  case Zero_rep\n  thus ?thesis by (metis (mono_tags) Lit_eqclass_complement_in_Lit_mod Lit_mod_plus_def Un_insert_right assms complement_Lit_poset_eqclass.simps(2) insertI1 insert_commute)\nnext\n  case One_rep\n  thus ?thesis by (metis Lit_eqclass_complement_in_Lit_mod Lit_mod_plus_def Un_absorb assms complement_Lit_poset_eqclass.simps(3) insert_subset le_iff_sup sup.boundedE)\nnext\n  case Equiv\n  thus ?thesis by (metis Lit_mod_plus_intro complement_Lit_poset_eqclass.simps(1))\nqed\n\nlemma zero_in_Lit_mod_plus[simp]:\n  fixes G\n  shows \"zero G \\<in> Lit_mod_plus G\"\nproof -\n{\n  assume \"\\<not>Lit_mod_plus_cond G\"\n  then have \"zero G = Zero_rep\" by (metis zero_def)\n  have ?thesis by (metis Lit_mod_plus_def Un_upper2 `\\<not> Lit_mod_plus_cond G` `zero G = Zero_rep` insert_subset)\n}\n{\n  assume \"Lit_mod_plus_cond G\"\n  then have \"zero G = Equiv [[SOME p. (p \\<lesssim> G (p\\<acute>))]]G\" by (metis zero_def)\n  have ?thesis by (metis Lit_mod_plus_intro `zero G = Equiv [[SOME p. (p \\<lesssim> G (p\\<acute>))]]G`)\n}\n  thus ?thesis by (metis `\\<not> Lit_mod_plus_cond G \\<Longrightarrow> zero G \\<in> Lit_mod_plus G`)\nqed\n\nlemma one_in_Lit_mod_plus[simp]:\n  fixes G\n  shows \"one G \\<in> Lit_mod_plus G\"\nunfolding one_def by (metis Lit_eqclass_in_Lit_mod_plus zero_in_Lit_mod_plus)\n\ndefinition up_closed :: \"lit_mod_elt set \\<Rightarrow> formula set \\<Rightarrow> bool\" where\n  \"up_closed A G \\<equiv> \\<forall>v \\<in> A. (\\<forall>w \\<in> Lit_mod_plus G. (v \\<lesssim>.G w) \\<longrightarrow> w \\<in> A)\"\n\ndefinition complete :: \"lit_mod_elt set \\<Rightarrow> formula set \\<Rightarrow> bool\" where\n  \"complete A G \\<equiv> \\<forall>v \\<in> Lit_mod_plus G. v \\<in> A \\<or> (v.\\<acute>G) \\<in> A\"\n\ndefinition consistent :: \"lit_mod_elt set \\<Rightarrow> formula set \\<Rightarrow> bool\" where\n  \"consistent A G \\<equiv> \\<forall>v \\<in> A. \\<not>(v \\<in> A \\<and> (v.\\<acute>G) \\<in> A)\"\n\n\ndefinition \"points G \\<equiv> {S. S \\<subseteq> Lit_mod_plus G \\<and> up_closed S G \\<and> complete S G \\<and> consistent S G}\"\n\nlemma zeroisone:\n    assumes \"G \\<equiv> {Some (q.) are (q`)}\"\n    shows \" zero G = one G\"\nproof - \n  have \"G\\<turnstile> All (q.) are (q`)\" \n    by (metis (mono_tags) ass assms axiom complement.simps(1) insert_compr mem_Collect_eq some2 the_elem_eq x)\n  have \"G\\<turnstile> All (q`) are (q.)\"\n    by (metis (full_types) ass assms axiom complement.simps(1) complement_involutive insertI1 x)\n  have \"zero G = Equiv [[q.]] G\" \n    by (metis Lit_mod_plus_cond_def `G \\<turnstile> All q. are (q\\`)` all_zero_Eqclasses complement.simps(1) complement_involutive less_equal_Lit.elims(3))\n  have \"zero G = Equiv [[q`]] G\" \n    by (metis Lit_mod_plus_cond_def `G \\<turnstile> All (q\\`) are (q.)` all_zero_Eqclasses complement.simps(1) less_equal_Lit.elims(3))\n  thus ?thesis \n    by (metis `zero G = Equiv [[q.]]G` complement.simps(2) complement_Lit_poset_eqclass_simp2 one_def)\nqed\n\nlemma falseiszero:\n  assumes \"G \\<equiv> {All (q.) are (q`)}\"\n  shows \"(case (zero G) of (Equiv z) \\<Rightarrow> (q.)\\<in> z)\"\n(*ak nitpick finds a false counterexample *)\nproof -\n  have \"Lit_mod_plus_cond G\"\n    unfolding Lit_mod_plus_cond_def\n      by (metis (mono_tags) ass assms complement.simps(1) complement_involutive insertI1 less_equal_Lit.elims(3) the_elem_eq)\n  have \"(q.) \\<lesssim>G ((q.)\\<acute>)\" \n    by (metis assms complement.simps(2) insertI1 less_equal_Lit_ass)\n  then have \"zero G = Equiv [[q.]]G\" \n    unfolding zero_def by (metis (lifting) Lit_mod_plus_cond_def all_zero_Eqclasses someI)\n  have \"(q.) \\<in> [[q.]]G\" by (metis Lit_poset_eqclass_membership)\n  thus ?thesis\nby (metis `zero G = Equiv [[q.]]G` lit_mod_elt.simps(10))\nqed\n\n\ndefinition consistent2 :: \"lit_mod_elt set \\<Rightarrow> formula set \\<Rightarrow> bool\" where\n  \"consistent2 S G \\<equiv> ( \\<forall>x \\<in> S. \\<forall>y \\<in> S. \\<not>(x \\<lesssim>.G (y.\\<acute>G)) )\"\n\nlemma l4_1_aux : \n  fixes G S\n  assumes \"S \\<subseteq> Lit_mod_plus G\"\n  shows \"consistent2 S G \\<Longrightarrow> consistent S G\"\nproof -\n  assume \"consistent2 S G\"\n\n  have \"consistent S G\" \n    unfolding consistent_def\n    proof (rule ccontr)\n      assume \"\\<not> (\\<forall>x \\<in> S. \\<not> (x \\<in> S \\<and> x.\\<acute>G \\<in> S))\"\n      then have \"\\<exists>x \\<in> S. x \\<in> S  \\<and> x.\\<acute>G \\<in> S\" by blast\n      then obtain x where \"x \\<in> S  \\<and> x.\\<acute>G \\<in> S\" by fast\n      then have \"\\<not> (x \\<lesssim>.G x)\" \n        by (metis Lit_eqclass_antitone `consistent2 S G` assms consistent2_def set_rev_mp)\n      have \"(x \\<lesssim>.G x)\"\n        by (metis Lit_poset_eqclass_reflexive `x \\<in> S \\<and> x .\\<acute> G \\<in> S` assms in_mono)\n      then show False by (metis `\\<not> (x \\<lesssim>.G x)`)\n    qed\n  thus ?thesis by simp\nqed\n\n\n\n\nlemma l4_1 :\n  fixes G S_0\n  assumes \"S_0 \\<subseteq> Lit_mod_plus G\"\n  and \"points G \\<noteq> {}\"\n  shows \"( \\<exists>S \\<in> points G. S_0 \\<subseteq> S ) \\<longleftrightarrow> (consistent2 S_0 G)\"\nproof -\n  {\n    assume \"\\<exists>S \\<in> points G. S_0 \\<subseteq> S\"\n    have \"\\<forall>x \\<in> S_0. \\<forall>y \\<in> S_0. \\<not>(x \\<lesssim>.G (y.\\<acute>G))\"\n    proof (rule ccontr)\n      assume \"\\<not> (\\<forall>x \\<in> S_0. \\<forall>y \\<in> S_0. \\<not>(x \\<lesssim>.G (y.\\<acute>G)))\"\n      then have \"\\<exists>x \\<in> S_0. \\<exists>y \\<in> S_0. (x \\<lesssim>.G (y.\\<acute>G))\" by fast\n      then obtain x y where \"(x \\<lesssim>.G (y.\\<acute>G))\" \"x \\<in> S_0\" \"y \\<in> S_0\" by force\n      \n      obtain S where S_0_sub_S: \"S_0 \\<subseteq> S\" \"S \\<in> points G\" by (metis `\\<exists>S\\<in>points G. S_0 \\<subseteq> S`)\n      {\n        have \"S \\<notin> points G\"\n        proof (rule ccontr)\n          assume \"\\<not>(S \\<notin> points G)\"\n          have \"(y.\\<acute>G) \\<in> S\"\n          proof -\n            have f1: \"\\<And>v. S_0 \\<subseteq> v \\<longrightarrow> y \\<in> v\"\n              by (metis (lifting) `y \\<in> S_0` in_mono)\n            have \"\\<And>v. S_0 \\<subseteq> v \\<longrightarrow> x \\<in> v\"\n              by (metis (lifting) `x \\<in> S_0` in_mono)\n            hence \"x \\<in> S\"\n              using S_0_sub_S(1) subset_trans by simp\n            hence \"x \\<in> S \\<and> y .\\<acute> G \\<in> Lit_mod_plus G \\<and> up_closed S G\"\n              using f1 Lit_eqclass_in_Lit_mod_plus S_0_sub_S(2) assms(1) points_def by simp\n            hence \"\\<exists>w u. w \\<in> S \\<and> y.\\<acute>G \\<in> Lit_mod_plus u \\<and> (w \\<lesssim>.u y.\\<acute>G) \\<and> up_closed S u\"\n              by (metis (lifting) `x \\<lesssim>.G y .\\<acute> G`)\n            thus \"y .\\<acute> G \\<in> S\"\n              using up_closed_def by auto\n          qed\n\n          have \"y \\<in> S\" by (metis S_0_sub_S(1) `y \\<in> S_0` in_mono)\n          then show False by (metis (lifting) S_0_sub_S(2) `y .\\<acute> G \\<in> S` consistent_def mem_Collect_eq points_def)\n        qed \n      }\n      then show False by (metis S_0_sub_S(2))\n    qed\n  }\n  {\n    assume \"consistent2 S_0 G\"\n    then have \"\\<forall>x \\<in> S_0. \\<forall>y \\<in> S_0. \\<not>(x \\<lesssim>.G (y.\\<acute>G))\" by (metis consistent2_def)\n    {\n      assume \"S_0 = {}\"\n      have \"( \\<exists>S \\<in> points G. S_0 \\<subseteq> S )\" by (metis Collect_mem_eq `S_0 = {}` assms(2) empty_Collect_eq empty_subsetI)\n    }\n    {\n      assume \"S_0 \\<noteq> {}\" \n      define A where \"A = {x. S_0 \\<subseteq> x \\<and> x \\<subseteq> Lit_mod_plus G \\<and> consistent2 x G}\"\n  \n      have \"\\<forall>C \\<in> chains A. \\<exists>U\\<in>A. \\<forall>X\\<in>C. X \\<subseteq> U\"\n      proof rule\n        fix C \n        assume \"C \\<in> chains A\"\n        show  \"\\<exists>U\\<in>A. \\<forall>X\\<in>C. X \\<subseteq> U\"\n        proof (simp add: A_def)\n        {\n          assume \"C \\<noteq> {}\"\n          define U where \"U = \\<Union>C\"\n          obtain x where \"x \\<in> C\" by (metis Collect_mem_eq `C \\<noteq> {}` empty_Collect_eq)\n          then have \"S_0 \\<subseteq> x\" by (metis (mono_tags) A_def `C \\<in> chains A` chainsD2 mem_Collect_eq set_rev_mp)\n          then have \"S_0 \\<subseteq> U\" by (metis (full_types) U_def Union_upper `x \\<in> C` subset_trans)\n  \n          have \"\\<Union>C \\<subseteq> Lit_mod_plus G\" \n            by (metis (lifting) A_def Sup_le_iff `C \\<in> chains A` chainsD2 mem_Collect_eq set_rev_mp)\n          \n          have \"consistent2 (\\<Union>C) G\"\n            unfolding consistent2_def\n            proof auto\n              fix y and x and ya and yb\n              assume a1: \"y \\<in> C\"\n              assume a2: \"x \\<in> y\"\n              assume a3: \"ya \\<in> C\"\n              assume a4: \"yb \\<in> ya\"\n              assume a5: \"x \\<lesssim>.G yb .\\<acute> G\" \n              show False by (metis (lifting, mono_tags) A_def `C \\<in> chains A` a1 a2 a3 a4 a5 chainsD chainsD2 consistent2_def mem_Collect_eq subsetD)\n            qed\n  \n          have \"\\<exists>U\\<in>A. \\<forall>X\\<in>C. X \\<subseteq> U\" by (metis (lifting) A_def U_def Union_upper `S_0 \\<subseteq> U` `\\<Union>C \\<subseteq> Lit_mod_plus G` `consistent2 (\\<Union>C) G` mem_Collect_eq)\n        }\n        {\n          assume \"C = {}\"\n          define U where \"U = S_0\"\n          have \"\\<exists>U\\<in>A. \\<forall>X\\<in>C. X \\<subseteq> U\" by (metis (lifting) A_def `C = {}` `consistent2 S_0 G` all_not_in_conv assms(1) empty_Collect_eq eq_iff)\n        }\n          thus \"\\<exists>U. S_0 \\<subseteq> U \\<and> U \\<subseteq> Lit_mod_plus G \\<and> consistent2 U G \\<and> (\\<forall>X\\<in>C. X \\<subseteq> U)\" \n            by (metis (lifting) A_def `C \\<noteq> {} \\<Longrightarrow> \\<exists>U\\<in>A. \\<forall>X\\<in>C. X \\<subseteq> U` mem_Collect_eq)\n        qed\n      qed\n      then have \"\\<exists>M \\<in> A. \\<forall>X \\<in> A. M \\<subseteq> X \\<longrightarrow> X = M\" by (metis Zorn_Lemma2)\n      then obtain S_1 where \"S_1 \\<in> A\" \"\\<forall>X \\<in> A. S_1 \\<subseteq> X \\<longrightarrow> X = S_1\" by force\n  \n      then have \"consistent2 S_1 G\"\n        by (metis (lifting, no_types) A_def mem_Collect_eq)\n      have S_1_in_Lit_mod : \"S_1 \\<subseteq> Lit_mod_plus G\" by (metis (lifting, no_types) A_def `S_1 \\<in> A` mem_Collect_eq)\n      define S where \"S = { (q::lit_mod_elt). q \\<in> Lit_mod_plus G \\<and> (\\<exists>p \\<in> S_1. (p \\<lesssim>.G q))}\"\n  \n      have \"\\<forall>x \\<in> S. (\\<exists>y \\<in> S_1. (y \\<lesssim>.G x))\" \n        proof -\n          { fix sk\\<^sub>0 :: lit_mod_elt\n            have ff1: \"sk\\<^sub>0 \\<in> {uu. \\<exists>x. x \\<in> S_1 \\<and> (x \\<lesssim>.G uu)} \\<or> sk\\<^sub>0 \\<notin> S \\<or> (\\<exists>x\\<^sub>1. x\\<^sub>1 \\<in> S_1 \\<and> (x\\<^sub>1 \\<lesssim>.G sk\\<^sub>0))\"\n              using S_def by blast\n            have \"sk\\<^sub>0 \\<notin> S \\<or> (\\<exists>x\\<^sub>1. x\\<^sub>1 \\<in> S_1 \\<and> (x\\<^sub>1 \\<lesssim>.G sk\\<^sub>0))\"\n              using ff1 by fastforce }\n          thus \"\\<forall>x\\<in>S. \\<exists>y\\<in>S_1. (y \\<lesssim>.G x)\"\n            by blast\n        qed\n   \n      have S_in_Lit_mod_plus : \"S \\<subseteq> Lit_mod_plus G\"\n        by (metis (lifting, no_types) S_def mem_Collect_eq subsetI)\n      \n      have \"S_0 \\<subseteq> S_1\" by (metis (lifting, no_types) A_def `S_1 \\<in> A` mem_Collect_eq)\n      have \"S_1 \\<subseteq> S\"\n        unfolding S_def by (metis (lifting, mono_tags) Lit_poset_eqclass_reflexive S_1_in_Lit_mod S_def in_mono mem_Collect_eq subsetI)\n      then have \"S_0 \\<subseteq> S\" by (metis `S_0 \\<subseteq> S_1` dual_order.trans)\n      \n      have \"S_1 \\<noteq> {}\" by (metis `S_0 \\<noteq> {}` `S_0 \\<subseteq> S_1` subset_empty)\n  \n      have \"one G \\<in> S\" \n        proof -\n          obtain x where \"x \\<in> S_1\" by (metis `S_1 \\<noteq> {}` ex_in_conv)\n  \n          then have \"x \\<in> Lit_mod_plus G\" by (metis (full_types) S_1_in_Lit_mod in_mono)\n          have \"x \\<lesssim>.G (one G)\"\n            proof -\n            {\n              assume \"\\<not>Lit_mod_plus_cond G\"\n              then have \"one G = One_rep\" by (metis Lit_eqiv_class_complement_inconsistency Lit_mod_plus_def Un_insert_right complement_Lit_poset_eqclass.simps(2) insertCI less_equal_Lit_poset_eqclass.simps(2) one_def)\n              then have ?thesis by (metis (full_types) Lit_eqclass_antitone `x \\<in> Lit_mod_plus G` complement_Lit_poset_eqclass.simps(3) less_equal_Lit_poset_eqclass.simps(2) one_in_Lit_mod_plus)\n            }\n            {\n              assume \"Lit_mod_plus_cond G\"\n              then have \"zero G = Equiv [[SOME p. (p \\<lesssim> G (p\\<acute>))]]G\" by (metis zero_def)\n              then have \"(zero G) \\<lesssim>.G x.\\<acute>G\" by (metis (full_types) Lit_eqclass_in_Lit_mod_plus `x \\<in> Lit_mod_plus G` zero_less_than_all)\n              then have ?thesis by (metis Lit_eqclass_antitone Lit_eqclass_in_Lit_mod_plus Lit_eqclass_involutive `x \\<in> Lit_mod_plus G` one_def zero_in_Lit_mod_plus)\n            }\n              thus ?thesis by (metis `\\<not> Lit_mod_plus_cond G \\<Longrightarrow> x \\<lesssim>.G (one G)`)\n            qed\n            then have \"\\<exists>p\\<in>S_1. (p \\<lesssim>.G (one G))\" by (metis `x \\<in> S_1`)\n            show ?thesis by (metis (lifting, no_types) S_def `\\<exists>p\\<in>S_1. (p \\<lesssim>.G (one G))` mem_Collect_eq one_in_Lit_mod_plus)\n          qed\n  \n      have \"up_closed S G\"\n        unfolding up_closed_def \n        proof auto\n          fix x y\n          assume \"x \\<in> S\" and \"y \\<in> Lit_mod_plus G\" and \"x \\<lesssim>.G y\"\n  \n          { assume \"x \\<in> S_1\"\n          have \"y \\<in> S\" \n            unfolding S_def by (metis (lifting, no_types) `x \\<in> S_1` `x \\<lesssim>.G y` `y \\<in> Lit_mod_plus G` mem_Collect_eq) }\n          { assume \"x \\<notin> S_1\"\n          then have \"\\<exists>a \\<in> S_1. (a \\<lesssim>.G x)\" by (metis `x \\<in> S` `\\<forall>x\\<in>S. \\<exists>y\\<in>S_1. (y \\<lesssim>.G x)`)\n          then have \"y \\<in> S\"\n            unfolding S_def \n            using Lit_poset_eqclass_trans S_1_in_Lit_mod S_in_Lit_mod_plus \\<open>x \\<in> S\\<close> \\<open>x \\<lesssim>.G y\\<close> \\<open>y \\<in> Lit_mod_plus G\\<close> by blast }\n          thus \"y \\<in> S\" by (metis `x \\<in> S_1 \\<Longrightarrow> y \\<in> S`)\n        qed\n  \n  \n      have \"consistent S G\"\n      proof (rule ccontr)\n        assume \"\\<not> consistent S G\"\n        then obtain r where \"r \\<in> S\" \"r.\\<acute>G \\<in> S\" by (metis (full_types) consistent_def)\n        then obtain q_1 q_2 where \"q_1 \\<in> S_1\" \"q_1 \\<lesssim>.G r\" \"q_2 \\<in> S_1\" \"q_2 \\<lesssim>.G r.\\<acute>G\" by (metis `\\<forall>x\\<in>S. \\<exists>y\\<in>S_1. (y \\<lesssim>.G x)`)\n        then have 1: \"r \\<lesssim>.G q_2.\\<acute>G\" by (metis (full_types) Lit_eqclass_antitone Lit_eqclass_involutive S_1_in_Lit_mod S_in_Lit_mod_plus `r.\\<acute>G \\<in> S` `r \\<in> S` in_mono)\n        have 2: \"r \\<in> Lit_mod_plus G\" by (metis S_in_Lit_mod_plus `r \\<in> S` in_mono)\n        have \"q_1 \\<in> Lit_mod_plus G\" \"q_2 \\<in> Lit_mod_plus G\" by (metis S_1_in_Lit_mod `q_1 \\<in> S_1` set_rev_mp) (metis S_1_in_Lit_mod `q_2 \\<in> S_1` set_rev_mp)\n        then have \"q_2.\\<acute>G \\<in> Lit_mod_plus G\" by (metis Lit_eqclass_in_Lit_mod_plus)\n        with 1 2 `q_1 \\<lesssim>.G r` have \"q_1 \\<lesssim>.G q_2.\\<acute>G\" by (metis Lit_poset_eqclass_trans `q_1 \\<in> Lit_mod_plus G`)\n        then have \"q_2.\\<acute>G \\<in> S_1\" by (metis `q_1 \\<in> S_1` `q_2 \\<in> S_1` `consistent2 S_1 G` consistent2_def)\n        then show False by (metis S_1_in_Lit_mod `q_2 \\<in> S_1` `consistent2 S_1 G` consistent_def l4_1_aux)\n      qed\n  \n      have \"complete S G\"\n        unfolding complete_def\n      proof (rule ccontr)\n        assume \"\\<not> (\\<forall>x\\<in>Lit_mod_plus G. x \\<in> S \\<or> x.\\<acute>G \\<in> S)\"\n        then have \"\\<exists>x \\<in> Lit_mod_plus G. x \\<notin> S \\<and> x.\\<acute>G \\<notin> S\" by blast\n        then obtain r where \"r \\<in> Lit_mod_plus G\" \"r \\<notin> S \\<and> r.\\<acute>G \\<notin> S\" by force\n  \n        have \"consistent2 (S_1 \\<union> {r}) G\"\n          proof (rule ccontr)\n            assume \"\\<not> consistent2 (S_1 \\<union> {r}) G\"\n            then have \"\\<exists>x \\<in> (S_1 \\<union> {r}). \\<exists>y \\<in> (S_1 \\<union> {r}). (x \\<lesssim>.G y.\\<acute>G)\" \n              by (metis (mono_tags) consistent2_def)\n            then obtain x y where \"x \\<in> (S_1 \\<union> {r})\" \"y \\<in> (S_1 \\<union> {r})\" \"(x \\<lesssim>.G y.\\<acute>G)\" by blast\n            have \"x \\<in> Lit_mod_plus G\" \"y \\<in> Lit_mod_plus G\"\n              by (metis (full_types) S_1_in_Lit_mod Un_iff `r \\<in> Lit_mod_plus G` `x \\<in> S_1 \\<union> {r}` empty_iff in_mono insert_iff)\n                 (metis (full_types) S_1_in_Lit_mod Un_iff `r \\<in> Lit_mod_plus G` `y \\<in> S_1 \\<union> {r}` empty_iff in_mono insert_iff)\n            {\n              assume \"x = r\" \"y \\<noteq> r\"\n              then have \"r \\<lesssim>.G y.\\<acute>G\" by (metis `x \\<lesssim>.G y .\\<acute> G`)\n              then have \"y \\<lesssim>.G r.\\<acute>G\" by (metis (mono_tags) Lit_eqclass_antitone Lit_eqclass_in_Lit_mod_plus Lit_eqclass_involutive `r \\<in> Lit_mod_plus G` `x = r` `x \\<lesssim>.G y .\\<acute> G` `y \\<in> Lit_mod_plus G`)\n              have \"y \\<in> S_1\" by (metis Un_iff `y \\<in> S_1 \\<union> {r}` `y \\<noteq> r` singleton_iff)\n              then have \"r.\\<acute>G \\<in> S\" by (metis (lifting, no_types) Lit_eqclass_in_Lit_mod_plus S_def `r \\<in> Lit_mod_plus G` `y \\<lesssim>.G r .\\<acute> G` mem_Collect_eq)\n              then have False by (metis `r \\<notin> S \\<and> r .\\<acute> G \\<notin> S`)\n            }\n            {\n              assume \"x \\<noteq> r\" \"y = r\"\n              then have \"x \\<lesssim>.G r.\\<acute>G\" by (metis `x \\<lesssim>.G y .\\<acute> G`)\n              have \"x \\<in> S_1\" by (metis Un_iff `x \\<in> S_1 \\<union> {r}` `x \\<noteq> r` singleton_iff)\n              then have \"r.\\<acute>G \\<in> S\" by (metis (lifting, no_types) Lit_eqclass_in_Lit_mod_plus S_def `r \\<in> Lit_mod_plus G` `x \\<lesssim>.G r .\\<acute> G` mem_Collect_eq)\n              then have False by (metis `r \\<notin> S \\<and> r .\\<acute> G \\<notin> S`)\n            }\n            {\n              assume \"x = r\" \"y = r\"\n              then have \"r \\<lesssim>.G r.\\<acute>G\" by (metis `x \\<lesssim>.G y.\\<acute>G`)\n              then have \"r = zero G\" by (metis Lit_eqiv_class_complement_inconsistency Lit_poset_eqclass_reflexive `r \\<in> Lit_mod_plus G`)\n              then have False by (metis `r \\<notin> S \\<and> r .\\<acute> G \\<notin> S` `one G \\<in> S` one_def)\n            }   \n            {\n              assume \"x \\<noteq> r\" \"y \\<noteq> r\"\n              then have \"x \\<in> S_1\" \"y \\<in> S_1\" \n                by (metis Un_iff `x \\<in> S_1 \\<union> {r}` singleton_iff)\n                   (metis Un_iff `y \\<in> S_1 \\<union> {r}` `y \\<noteq> r` singleton_iff)\n              then have \"x \\<lesssim>.G y.\\<acute>G\" by (metis `x \\<lesssim>.G y .\\<acute> G`)\n              then have False by (metis `x \\<in> S_1` `y \\<in> S_1` `consistent2 S_1 G` consistent2_def)\n            }\n            then show False by (metis `\\<lbrakk>x = r; y = r\\<rbrakk> \\<Longrightarrow> False` `\\<lbrakk>x = r; y \\<noteq> r\\<rbrakk> \\<Longrightarrow> False` `\\<lbrakk>x \\<noteq> r; y = r\\<rbrakk> \\<Longrightarrow> False`)\n          qed\n  \n        have \"S_0 \\<subseteq> (S_1 \\<union> {r})\" by (metis `S_0 \\<subseteq> S_1` sup.coboundedI1)\n        have \"(S_1 \\<union> {r}) \\<subseteq> Lit_mod_plus G\" by (metis S_1_in_Lit_mod Un_empty_right Un_insert_right `r \\<in> Lit_mod_plus G` insert_subset)\n        then have \"(S_1 \\<union> {r}) \\<in> A\"\n          unfolding A_def by (metis (lifting) `S_0 \\<subseteq> S_1 \\<union> {r}` `consistent2 (S_1 \\<union> {r}) G` mem_Collect_eq)\n        then show False\n          by (metis Un_absorb Un_empty_right Un_insert_right `r \\<notin> S \\<and> r .\\<acute> G \\<notin> S` `S_1 \\<subseteq> S` `\\<forall>X\\<in>A. S_1 \\<subseteq> X \\<longrightarrow> X = S_1` insert_subset subset_Un_eq)\n      qed\n  \n      have \"S \\<in> points G\" \n        unfolding points_def \n        by (metis (lifting, no_types) S_in_Lit_mod_plus `complete S G` `consistent S G` `up_closed S G` mem_Collect_eq)\n      have \"( \\<exists>S \\<in> points G. S_0 \\<subseteq> S )\" by (metis `S \\<in> points G` `S_0 \\<subseteq> S`)\n    }\n    then have \"\\<exists>S\\<in>points G. S_0 \\<subseteq> S\" by (metis `S_0 = {} \\<Longrightarrow> \\<exists>S\\<in>points G. S_0 \\<subseteq> S`)\n  }\n  thus ?thesis by (metis `\\<exists>S\\<in>points G. S_0 \\<subseteq> S \\<Longrightarrow> \\<forall>x\\<in>S_0. \\<forall>y\\<in>S_0. \\<not> (x \\<lesssim>.G y.\\<acute>G)` consistent2_def)\nqed\n(*declare [[show_types]]*)\n\nend", "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/Section4.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8558511396138365, "lm_q2_score": 0.8596637487122111, "lm_q1q2_score": 0.7357441990200486}}
{"text": "(* Author: Tobias Nipkow *)\n\nsection \\<open>Function \\textit{isin} for Tree2\\<close>\n\ntheory Isin2\nimports\n  Tree2\n  Cmp\n  Set_by_Ordered\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 \"sorted(inorder t) \\<Longrightarrow> isin t x = (x \\<in> elems(inorder t))\"\nby (induction t) (auto simp: elems_simps1)\n\nlemma isin_set: \"sorted(inorder t) \\<Longrightarrow> isin t x = (x \\<in> elems(inorder t))\"\nby (induction t) (auto simp: elems_simps2)\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/Isin2.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.894789454880027, "lm_q2_score": 0.8221891305219504, "lm_q1q2_score": 0.7356861639080194}}
{"text": "(*  Title:     HOL/Inequalities.thy\n    Author:    Tobias Nipkow\n    Author:    Johannes H\u00f6lzl\n*)\n\ntheory Inequalities\n  imports Real_Vector_Spaces\nbegin\n\nlemma Sum_Icc_int: \"(m::int) \\<le> n \\<Longrightarrow> \\<Sum> {m..n} = (n*(n+1) - m*(m-1)) div 2\"\nproof(induct i == \"nat(n-m)\" arbitrary: m n)\n  case 0\n  hence \"m = n\" by arith\n  thus ?case by (simp add: algebra_simps)\nnext\n  case (Suc i)\n  have 0: \"i = nat((n-1) - m)\" \"m \\<le> n-1\" using Suc(2,3) by arith+\n  have \"\\<Sum> {m..n} = \\<Sum> {m..1+(n-1)}\" by simp\n  also have \"\\<dots> = \\<Sum> {m..n-1} + n\" using \\<open>m \\<le> n\\<close>\n    by(subst atLeastAtMostPlus1_int_conv) simp_all\n  also have \"\\<dots> = ((n-1)*(n-1+1) - m*(m-1)) div 2 + n\"\n    by(simp add: Suc(1)[OF 0])\n  also have \"\\<dots> = ((n-1)*(n-1+1) - m*(m-1) + 2*n) div 2\" by simp\n  also have \"\\<dots> = (n*(n+1) - m*(m-1)) div 2\" by(simp add: algebra_simps)\n  finally show ?case .\nqed\n\nlemma Sum_Icc_nat: assumes \"(m::nat) \\<le> n\"\nshows \"\\<Sum> {m..n} = (n*(n+1) - m*(m-1)) div 2\"\nproof -\n  have \"m*(m-1) \\<le> n*(n + 1)\"\n   using assms by (meson diff_le_self order_trans le_add1 mult_le_mono)\n  hence \"int(\\<Sum> {m..n}) = int((n*(n+1) - m*(m-1)) div 2)\" using assms\n    by (auto simp: Sum_Icc_int[transferred, OF assms] zdiv_int of_nat_mult simp del: of_nat_sum\n          split: zdiff_int_split)\n  thus ?thesis\n    using of_nat_eq_iff by blast\nqed\n\nlemma Sum_Ico_nat: assumes \"(m::nat) \\<le> n\"\nshows \"\\<Sum> {m..<n} = (n*(n-1) - m*(m-1)) div 2\"\nproof cases\n  assume \"m < n\"\n  hence \"{m..<n} = {m..n-1}\" by auto\n  hence \"\\<Sum>{m..<n} = \\<Sum>{m..n-1}\" by simp\n  also have \"\\<dots> = (n*(n-1) - m*(m-1)) div 2\"\n    using assms \\<open>m < n\\<close> by (simp add: Sum_Icc_nat mult.commute)\n  finally show ?thesis .\nnext\n  assume \"\\<not> m < n\" with assms show ?thesis by simp\nqed\n\nlemma Chebyshev_sum_upper:\n  fixes a b::\"nat \\<Rightarrow> 'a::linordered_idom\"\n  assumes \"\\<And>i j. i \\<le> j \\<Longrightarrow> j < n \\<Longrightarrow> a i \\<le> a j\"\n  assumes \"\\<And>i j. i \\<le> j \\<Longrightarrow> j < n \\<Longrightarrow> b i \\<ge> b j\"\n  shows \"of_nat n * (\\<Sum>k=0..<n. a k * b k) \\<le> (\\<Sum>k=0..<n. a k) * (\\<Sum>k=0..<n. b k)\"\nproof -\n  let ?S = \"(\\<Sum>j=0..<n. (\\<Sum>k=0..<n. (a j - a k) * (b j - b k)))\"\n  have \"2 * (of_nat n * (\\<Sum>j=0..<n. (a j * b j)) - (\\<Sum>j=0..<n. b j) * (\\<Sum>k=0..<n. a k)) = ?S\"\n    by (simp only: one_add_one[symmetric] algebra_simps)\n      (simp add: algebra_simps sum_subtractf sum.distrib sum.commute[of \"\\<lambda>i j. a i * b j\"] sum_distrib_left)\n  also\n  { fix i j::nat assume \"i<n\" \"j<n\"\n    hence \"a i - a j \\<le> 0 \\<and> b i - b j \\<ge> 0 \\<or> a i - a j \\<ge> 0 \\<and> b i - b j \\<le> 0\"\n      using assms by (cases \"i \\<le> j\") (auto simp: algebra_simps)\n  } then have \"?S \\<le> 0\"\n    by (auto intro!: sum_nonpos simp: mult_le_0_iff)\n  finally show ?thesis by (simp add: algebra_simps)\nqed\n\nlemma Chebyshev_sum_upper_nat:\n  fixes a b :: \"nat \\<Rightarrow> nat\"\n  shows \"(\\<And>i j. \\<lbrakk> i\\<le>j; j<n \\<rbrakk> \\<Longrightarrow> a i \\<le> a j) \\<Longrightarrow>\n         (\\<And>i j. \\<lbrakk> i\\<le>j; j<n \\<rbrakk> \\<Longrightarrow> b i \\<ge> b j) \\<Longrightarrow>\n    n * (\\<Sum>i=0..<n. a i * b i) \\<le> (\\<Sum>i=0..<n. a i) * (\\<Sum>i=0..<n. b i)\"\nusing Chebyshev_sum_upper[where 'a=real, of n a b]\nby (simp del: of_nat_mult of_nat_sum  add: of_nat_mult[symmetric] of_nat_sum[symmetric])\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/Inequalities.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382236515259, "lm_q2_score": 0.8539127492339909, "lm_q1q2_score": 0.7356784731284434}}
{"text": "(*  Title:    HOL/Analysis/Harmonic_Numbers.thy\n    Author:   Manuel Eberl, TU M\u00fcnchen\n*)\n\nsection \\<open>Harmonic Numbers\\<close>\n\ntheory Harmonic_Numbers\nimports\n  Complex_Transcendental\n  Summation_Tests\nbegin\n\ntext \\<open>\n  The definition of the Harmonic Numbers and the Euler-Mascheroni constant.\n  Also provides a reasonably accurate approximation of \\<^term>\\<open>ln 2 :: real\\<close>\n  and the Euler-Mascheroni constant.\n\\<close>\n\nsubsection \\<open>The Harmonic numbers\\<close>\n\ndefinition\\<^marker>\\<open>tag important\\<close> 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 sum_nonneg) simp_all\n\nlemma harm_pos: \"n > 0 \\<Longrightarrow> harm n > (0 :: 'a :: {real_normed_field,linordered_field})\"\n  unfolding harm_def by (intro sum_pos) simp_all\n\nlemma of_real_harm: \"of_real (harm n) = harm n\"\n  unfolding harm_def by simp\n\nlemma abs_harm [simp]: \"(abs (harm n) :: real) = harm n\"\n  using harm_nonneg[of n] by (rule abs_of_nonneg)\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 0 = 0\"\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_all add: harm_def)\n\ntheorem 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 sum.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\nlemma harm_pos_iff [simp]: \"harm n > (0 :: 'a :: {real_normed_field,linordered_field}) \\<longleftrightarrow> n > 0\"\n  by (rule iffI, cases n, simp add: harm_expand, simp, rule harm_pos)\n\nlemma ln_diff_le_inverse:\n  assumes \"x \\<ge> (1::real)\"\n  shows   \"ln (x + 1) - ln x < 1 / x\"\nproof -\n  from assms have \"\\<exists>z>x. z < x + 1 \\<and> ln (x + 1) - ln x = (x + 1 - x) * inverse z\"\n    by (intro MVT2) (auto intro!: derivative_eq_intros simp: field_simps)\n  then obtain z where z: \"z > x\" \"z < x + 1\" \"ln (x + 1) - ln x = inverse z\" by auto\n  have \"ln (x + 1) - ln x = inverse z\" by fact\n  also from z(1,2) assms have \"\\<dots> < 1 / x\" by (simp add: field_simps)\n  finally show ?thesis .\nqed\n\nlemma ln_le_harm: \"ln (real n + 1) \\<le> (harm n :: real)\"\nproof (induction n)\n  fix n assume IH: \"ln (real n + 1) \\<le> harm n\"\n  have \"ln (real (Suc n) + 1) = ln (real n + 1) + (ln (real n + 2) - ln (real n + 1))\" by simp\n  also have \"(ln (real n + 2) - ln (real n + 1)) \\<le> 1 / real (Suc n)\"\n    using ln_diff_le_inverse[of \"real n + 1\"] by (simp add: add_ac)\n  also note IH\n  also have \"harm n + 1 / real (Suc n) = harm (Suc n)\" by (simp add: harm_Suc field_simps)\n  finally show \"ln (real (Suc n) + 1) \\<le> harm (Suc n)\" by - simp\nqed (simp_all add: harm_def)\n\nlemma harm_at_top: \"filterlim (harm :: nat \\<Rightarrow> real) at_top sequentially\"\nproof (rule filterlim_at_top_mono)\n  show \"eventually (\\<lambda>n. harm n \\<ge> ln (real (Suc n))) at_top\"\n    using ln_le_harm by (intro always_eventually allI) (simp_all add: add_ac)\n  show \"filterlim (\\<lambda>n. ln (real (Suc n))) at_top sequentially\"\n    by (intro filterlim_compose[OF ln_at_top] filterlim_compose[OF filterlim_real_sequentially]\n              filterlim_Suc)\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\nlemma harm_ge_ln: \"harm n \\<ge> ln (real n + 1)\"\nproof -\n  have \"ln (n + 1) = (\\<Sum>j<n. ln (real (Suc j + 1)) - ln (real (j + 1)))\"\n    by (subst sum_lessThan_telescope) auto\n  also have \"\\<dots> \\<le> (\\<Sum>j<n. 1 / (Suc j))\"\n  proof (intro sum_mono, clarify)\n    fix j assume j: \"j < n\"\n    have \"\\<exists>\\<xi>. \\<xi> > real j + 1 \\<and> \\<xi> < real j + 2 \\<and>\n            ln (real j + 2) - ln (real j + 1) = (real j + 2 - (real j + 1)) * (1 / \\<xi>)\"\n      by (intro MVT2) (auto intro!: derivative_eq_intros)\n    then obtain \\<xi> :: real\n      where \\<xi>: \"\\<xi> \\<in> {real j + 1..real j + 2}\" \"ln (real j + 2) - ln (real j + 1) = 1 / \\<xi>\"\n      by auto\n    note \\<xi>(2)\n    also have \"1 / \\<xi> \\<le> 1 / (Suc j)\"\n      using \\<xi>(1) by (auto simp: field_simps)\n    finally show \"ln (real (Suc j + 1)) - ln (real (j + 1)) \\<le> 1 / (Suc j)\"\n      by (simp add: add_ac)\n  qed\n  also have \"\\<dots> = harm n\"\n    by (simp add: harm_altdef field_simps)\n  finally show ?thesis by (simp add: add_ac)\nqed\n\nlemma decseq_harm_diff_ln: \"decseq (\\<lambda>n. harm (Suc n) - ln (Suc n))\"\nproof (rule decseq_SucI)\n  fix m :: nat\n  define n where \"n = Suc m\"\n  have \"n > 0\" by (simp add: n_def)\n  have \"convex_on {0<..} (\\<lambda>x :: real. -ln x)\"\n    by (rule convex_on_realI[where f' = \"\\<lambda>x. -1/x\"])\n       (auto intro!: derivative_eq_intros simp: field_simps)\n  hence \"(-1 / (n + 1)) * (real n - real (n + 1)) \\<le> (- ln (real n)) - (-ln (real (n + 1)))\"\n    using \\<open>n > 0\\<close> by (intro convex_on_imp_above_tangent[where A = \"{0<..}\"])\n                     (auto intro!: derivative_eq_intros simp: interior_open)\n  thus \"harm (Suc n) - ln (Suc n) \\<le> harm n - ln n\"\n    by (auto simp: harm_Suc field_simps)\nqed\n\nlemma euler_mascheroni_sequence_nonneg:\n  assumes \"n > 0\"\n  shows   \"harm n - ln (real n) \\<ge> (0 :: real)\"\nproof -\n  have \"ln (real n) \\<le> ln (real n + 1)\"\n    using assms by simp\n  also have \"\\<dots> \\<le> harm n\"\n    by (rule harm_ge_ln)\n  finally show ?thesis by simp\nqed\n\nlemma euler_mascheroni_convergent: \"convergent (\\<lambda>n. harm n - ln n)\"\nproof -\n  have \"harm (Suc n) - ln (real (Suc n)) \\<ge> 0\" for n :: nat\n    using euler_mascheroni_sequence_nonneg[of \"Suc n\"] by simp\n  hence \"convergent (\\<lambda>n. harm (Suc n) - ln (Suc n))\"\n    by (intro Bseq_monoseq_convergent decseq_bounded[of _ 0] decseq_harm_diff_ln decseq_imp_monoseq)\n       auto\n  thus ?thesis\n    by (subst (asm) convergent_Suc_iff)\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  using decseqD[OF decseq_harm_diff_ln, of \"m - 1\" \"n - 1\"] by simp\n  \nlemma\\<^marker>\\<open>tag important\\<close> euler_mascheroni_LIMSEQ:\n  \"(\\<lambda>n. harm n - ln (of_nat n) :: real) \\<longlonglongrightarrow> 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))) \\<longlonglongrightarrow>\n      (euler_mascheroni :: 'a :: {real_normed_algebra_1, topological_space})\"\nproof -\n  have \"(\\<lambda>n. of_real (harm n - ln (of_nat n))) \\<longlonglongrightarrow> (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_real:\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 euler_mascheroni_sum:\n  \"(\\<lambda>n. inverse (of_nat (n+1)) + of_real (ln (of_nat (n+1))) - of_real (ln (of_nat (n+2))))\n       sums (euler_mascheroni :: 'a :: {banach, real_normed_field})\"\nproof -\n  have \"(\\<lambda>n. of_real (inverse (of_nat (n+1)) + ln (of_nat (n+1)) - ln (of_nat (n+2))))\n       sums (of_real euler_mascheroni :: 'a :: {banach, real_normed_field})\"\n    by (subst sums_of_real_iff) (rule euler_mascheroni_sum_real)\n  thus ?thesis by simp\nqed\n\ntheorem 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: sum.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 sum.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 sum.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 sum.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 sum.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                     \\<longlonglongrightarrow> 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: strict_mono_def)\n  hence \"(\\<lambda>n. ?em (2*n) - ?em n + ln (2::real)) \\<longlonglongrightarrow> ln 2\" by simp\n  ultimately have \"(\\<lambda>n. (\\<Sum>k<2*n. (-1)^k / real_of_nat (Suc k))) \\<longlonglongrightarrow> ln 2\"\n    by (blast intro: 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)) \\<longlonglongrightarrow> (\\<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 \"(*) (2::nat)\"]]\n    have \"(\\<lambda>n. \\<Sum>k<2*n. (-1)^k / real_of_nat (Suc k)) \\<longlonglongrightarrow> (\\<Sum>k. (-1)^k / real_of_nat (Suc k))\"\n    by (simp add: strict_mono_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))) \\<longlonglongrightarrow> 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\n\nsubsection\\<^marker>\\<open>tag unimportant\\<close> \\<open>Bounds on the Euler-Mascheroni constant\\<close>\n(* TODO: perhaps move this section away to remove unnecessary dependency on integration *)\n\n(* TODO: Move? *)\nlemma ln_inverse_approx_le:\n  assumes \"(x::real) > 0\" \"a > 0\"\n  shows   \"ln (x + a) - ln x \\<le> a * (inverse x + inverse (x + a))/2\" (is \"_ \\<le> ?A\")\nproof -\n  define f' where \"f' = (inverse (x + a) - inverse x)/a\"\n  let ?f = \"\\<lambda>t. (t - x) * f' + inverse x\"\n  let ?F = \"\\<lambda>t. (t - x)^2 * f' / 2 + t * inverse x\"\n\n  have deriv: \"\\<exists>D. ((\\<lambda>x. ?F x - ln x) has_field_derivative D) (at \\<xi>) \\<and> D \\<ge> 0\"\n    if \"\\<xi> \\<ge> x\" \"\\<xi> \\<le> x + a\" for \\<xi>\n  proof -\n    from that assms have t: \"0 \\<le> (\\<xi> - x) / a\" \"(\\<xi> - x) / a \\<le> 1\" by simp_all\n    have \"inverse \\<xi> = inverse ((1 - (\\<xi> - x) / a) *\\<^sub>R x + ((\\<xi> - x) / a) *\\<^sub>R (x + a))\" (is \"_ = ?A\")\n      using assms by (simp add: field_simps)\n    also from assms have \"convex_on {x..x+a} inverse\" by (intro convex_on_inverse) auto\n    from convex_onD_Icc[OF this _ t] assms\n      have \"?A \\<le> (1 - (\\<xi> - x) / a) * inverse x + (\\<xi> - x) / a * inverse (x + a)\" by simp\n    also have \"\\<dots> = (\\<xi> - x) * f' + inverse x\" using assms\n      by (simp add: f'_def divide_simps) (simp add: field_simps)\n    finally have \"?f \\<xi> - 1 / \\<xi> \\<ge> 0\" by (simp add: field_simps)\n    moreover have \"((\\<lambda>x. ?F x - ln x) has_field_derivative ?f \\<xi> - 1 / \\<xi>) (at \\<xi>)\"\n      using that assms by (auto intro!: derivative_eq_intros simp: field_simps)\n    ultimately show ?thesis by blast\n  qed\n  have \"?F x - ln x \\<le> ?F (x + a) - ln (x + a)\"\n    by (rule DERIV_nonneg_imp_nondecreasing[of x \"x + a\", OF _ deriv]) (use assms in auto)\n  thus ?thesis\n    using assms by (simp add: f'_def divide_simps) (simp add: algebra_simps power2_eq_square)?\nqed\n\nlemma ln_inverse_approx_ge:\n  assumes \"(x::real) > 0\" \"x < y\"\n  shows   \"ln y - ln x \\<ge> 2 * (y - x) / (x + y)\" (is \"_ \\<ge> ?A\")\nproof -\n  define m where \"m = (x+y)/2\"\n  define f' where \"f' = -inverse (m^2)\"\n  from assms have m: \"m > 0\" by (simp add: m_def)\n  let ?F = \"\\<lambda>t. (t - m)^2 * f' / 2 + t / m\"\n  let ?f = \"\\<lambda>t. (t - m) * f' + inverse m\"\n  \n  have deriv: \"\\<exists>D. ((\\<lambda>x. ln x - ?F x) has_field_derivative D) (at \\<xi>) \\<and> D \\<ge> 0\"\n    if \"\\<xi> \\<ge> x\" \"\\<xi> \\<le> y\" for \\<xi>\n  proof -\n    from that assms have \"inverse \\<xi> - inverse m \\<ge> f' * (\\<xi> - m)\"\n      by (intro convex_on_imp_above_tangent[of \"{0<..}\"] convex_on_inverse)\n         (auto simp: m_def interior_open f'_def power2_eq_square intro!: derivative_eq_intros)\n    hence \"1 / \\<xi> - ?f \\<xi> \\<ge> 0\" by (simp add: field_simps f'_def)\n    moreover have \"((\\<lambda>x. ln x - ?F x) has_field_derivative 1 / \\<xi> - ?f \\<xi>) (at \\<xi>)\"\n      using that assms m by (auto intro!: derivative_eq_intros simp: field_simps)\n    ultimately show ?thesis by blast\n  qed\n  have \"ln x - ?F x \\<le> ln y - ?F y\"\n    by (rule DERIV_nonneg_imp_nondecreasing[of x y, OF _ deriv]) (use assms in auto)\n  hence \"ln y - ln x \\<ge> ?F y - ?F x\"\n    by (simp add: algebra_simps)\n  also have \"?F y - ?F x = ?A\"\n    using assms by (simp add: f'_def m_def divide_simps) (simp add: algebra_simps power2_eq_square)\n  finally show ?thesis .\nqed\n\nlemma euler_mascheroni_lower:\n          \"euler_mascheroni \\<ge> harm (Suc n) - ln (real_of_nat (n + 2)) + 1/real_of_nat (2 * (n + 2))\"\n    and euler_mascheroni_upper:\n          \"euler_mascheroni \\<le> harm (Suc n) - ln (real_of_nat (n + 2)) + 1/real_of_nat (2 * (n + 1))\"\nproof -\n  define D :: \"_ \\<Rightarrow> real\"\n    where \"D n = inverse (of_nat (n+1)) + ln (of_nat (n+1)) - ln (of_nat (n+2))\" for n\n  let ?g = \"\\<lambda>n. ln (of_nat (n+2)) - ln (of_nat (n+1)) - inverse (of_nat (n+1)) :: real\"\n  define inv where [abs_def]: \"inv n = inverse (real_of_nat n)\" for n\n  fix n :: nat\n  note summable = sums_summable[OF euler_mascheroni_sum_real, folded D_def]\n  have sums: \"(\\<lambda>k. (inv (Suc (k + (n+1))) - inv (Suc (Suc k + (n+1))))/2) sums ((inv (Suc (0 + (n+1))) - 0)/2)\"\n    unfolding inv_def\n    by (intro sums_divide telescope_sums' LIMSEQ_ignore_initial_segment LIMSEQ_inverse_real_of_nat)\n  have sums': \"(\\<lambda>k. (inv (Suc (k + n)) - inv (Suc (Suc k + n)))/2) sums ((inv (Suc (0 + n)) - 0)/2)\"\n    unfolding inv_def\n    by (intro sums_divide telescope_sums' LIMSEQ_ignore_initial_segment LIMSEQ_inverse_real_of_nat)\n  from euler_mascheroni_sum_real have \"euler_mascheroni = (\\<Sum>k. D k)\"\n    by (simp add: sums_iff D_def)\n  also have \"\\<dots> = (\\<Sum>k. D (k + Suc n)) + (\\<Sum>k\\<le>n. D k)\"\n    by (subst suminf_split_initial_segment[OF summable, of \"Suc n\"],\n        subst lessThan_Suc_atMost) simp\n  finally have sum: \"(\\<Sum>k\\<le>n. D k) - euler_mascheroni = -(\\<Sum>k. D (k + Suc n))\" by simp\n\n  note sum\n  also have \"\\<dots> \\<le> -(\\<Sum>k. (inv (k + Suc n + 1) - inv (k + Suc n + 2)) / 2)\"\n  proof (intro le_imp_neg_le suminf_le allI summable_ignore_initial_segment[OF summable])\n    fix k' :: nat\n    define k where \"k = k' + Suc n\"\n    hence k: \"k > 0\" by (simp add: k_def)\n    have \"real_of_nat (k+1) > 0\" by (simp add: k_def)\n    with ln_inverse_approx_le[OF this zero_less_one]\n      have \"ln (of_nat k + 2) - ln (of_nat k + 1) \\<le> (inv (k+1) + inv (k+2))/2\"\n      by (simp add: inv_def add_ac)\n    hence \"(inv (k+1) - inv (k+2))/2 \\<le> inv (k+1) + ln (of_nat (k+1)) - ln (of_nat (k+2))\"\n      by (simp add: field_simps)\n    also have \"\\<dots> = D k\" unfolding D_def inv_def ..\n    finally show \"D (k' + Suc n) \\<ge> (inv (k' + Suc n + 1) - inv (k' + Suc n + 2)) / 2\"\n      by (simp add: k_def)\n    from sums_summable[OF sums]\n      show \"summable (\\<lambda>k. (inv (k + Suc n + 1) - inv (k + Suc n + 2))/2)\" by simp\n  qed\n  also from sums have \"\\<dots> = -inv (n+2) / 2\" by (simp add: sums_iff)\n  finally have \"euler_mascheroni \\<ge> (\\<Sum>k\\<le>n. D k) + 1 / (of_nat (2 * (n+2)))\"\n    by (simp add: inv_def field_simps)\n  also have \"(\\<Sum>k\\<le>n. D k) = harm (Suc n) - (\\<Sum>k\\<le>n. ln (real_of_nat (Suc k+1)) - ln (of_nat (k+1)))\"\n    unfolding harm_altdef D_def by (subst lessThan_Suc_atMost) (simp add:  sum.distrib sum_subtractf)\n  also have \"(\\<Sum>k\\<le>n. ln (real_of_nat (Suc k+1)) - ln (of_nat (k+1))) = ln (of_nat (n+2))\"\n    by (subst atLeast0AtMost [symmetric], subst sum_Suc_diff) simp_all\n  finally show \"euler_mascheroni \\<ge> harm (Suc n) - ln (real_of_nat (n + 2)) + 1/real_of_nat (2 * (n + 2))\"\n    by simp\n\n  note sum\n  also have \"-(\\<Sum>k. D (k + Suc n)) \\<ge> -(\\<Sum>k. (inv (Suc (k + n)) - inv (Suc (Suc k + n)))/2)\"\n  proof (intro le_imp_neg_le suminf_le allI summable_ignore_initial_segment[OF summable])\n    fix k' :: nat\n    define k where \"k = k' + Suc n\"\n    hence k: \"k > 0\" by (simp add: k_def)\n    have \"real_of_nat (k+1) > 0\" by (simp add: k_def)\n    from ln_inverse_approx_ge[of \"of_nat k + 1\" \"of_nat k + 2\"]\n      have \"2 / (2 * real_of_nat k + 3) \\<le> ln (of_nat (k+2)) - ln (real_of_nat (k+1))\"\n      by (simp add: add_ac)\n    hence \"D k \\<le> 1 / real_of_nat (k+1) - 2 / (2 * real_of_nat k + 3)\"\n      by (simp add: D_def inverse_eq_divide inv_def)\n    also have \"\\<dots> = inv ((k+1)*(2*k+3))\" unfolding inv_def by (simp add: field_simps)\n    also have \"\\<dots> \\<le> inv (2*k*(k+1))\" unfolding inv_def using k\n      by (intro le_imp_inverse_le)\n         (simp add: algebra_simps, simp del: of_nat_add)\n    also have \"\\<dots> = (inv k - inv (k+1))/2\" unfolding inv_def using k\n      by (simp add: divide_simps del: of_nat_mult) (simp add: algebra_simps)\n    finally show \"D k \\<le> (inv (Suc (k' + n)) - inv (Suc (Suc k' + n)))/2\" unfolding k_def by simp\n  next\n    from sums_summable[OF sums']\n      show \"summable (\\<lambda>k. (inv (Suc (k + n)) - inv (Suc (Suc k + n)))/2)\" by simp\n  qed\n  also from sums' have \"(\\<Sum>k. (inv (Suc (k + n)) - inv (Suc (Suc k + n)))/2) = inv (n+1)/2\"\n    by (simp add: sums_iff)\n  finally have \"euler_mascheroni \\<le> (\\<Sum>k\\<le>n. D k) + 1 / of_nat (2 * (n+1))\"\n    by (simp add: inv_def field_simps)\n  also have \"(\\<Sum>k\\<le>n. D k) = harm (Suc n) - (\\<Sum>k\\<le>n. ln (real_of_nat (Suc k+1)) - ln (of_nat (k+1)))\"\n    unfolding harm_altdef D_def by (subst lessThan_Suc_atMost) (simp add:  sum.distrib sum_subtractf)\n  also have \"(\\<Sum>k\\<le>n. ln (real_of_nat (Suc k+1)) - ln (of_nat (k+1))) = ln (of_nat (n+2))\"\n    by (subst atLeast0AtMost [symmetric], subst sum_Suc_diff) simp_all\n  finally show \"euler_mascheroni \\<le> harm (Suc n) - ln (real_of_nat (n + 2)) + 1/real_of_nat (2 * (n + 1))\"\n    by simp\nqed\n\nlemma euler_mascheroni_pos: \"euler_mascheroni > (0::real)\"\n  using euler_mascheroni_lower[of 0] ln_2_less_1 by (simp add: harm_def)\n\ncontext\nbegin\n\nprivate lemma ln_approx_aux:\n  fixes n :: nat and x :: real\n  defines \"y \\<equiv> (x-1)/(x+1)\"\n  assumes x: \"x > 0\" \"x \\<noteq> 1\"\n  shows \"inverse (2*y^(2*n+1)) * (ln x - (\\<Sum>k<n. 2*y^(2*k+1) / of_nat (2*k+1))) \\<in>\n            {0..(1 / (1 - y^2) / of_nat (2*n+1))}\"\nproof -\n  from x have norm_y: \"norm y < 1\" unfolding y_def by simp\n  from power_strict_mono[OF this, of 2] have norm_y': \"norm y^2 < 1\" by simp\n\n  let ?f = \"\\<lambda>k. 2 * y ^ (2*k+1) / of_nat (2*k+1)\"\n  note sums = ln_series_quadratic[OF x(1)]\n  define c where \"c = inverse (2*y^(2*n+1))\"\n  let ?d = \"c * (ln x - (\\<Sum>k<n. ?f k))\"\n  have \"\\<forall>k. y\\<^sup>2^k / of_nat (2*(k+n)+1) \\<le> y\\<^sup>2 ^ k / of_nat (2*n+1)\"\n    by (intro allI divide_left_mono mult_right_mono mult_pos_pos zero_le_power[of \"y^2\"]) simp_all\n  moreover {\n    have \"(\\<lambda>k. ?f (k + n)) sums (ln x - (\\<Sum>k<n. ?f k))\"\n      using sums_split_initial_segment[OF sums] by (simp add: y_def)\n    hence \"(\\<lambda>k. c * ?f (k + n)) sums ?d\" by (rule sums_mult)\n    also have \"(\\<lambda>k. c * (2*y^(2*(k+n)+1) / of_nat (2*(k+n)+1))) =\n                   (\\<lambda>k. (c * (2*y^(2*n+1))) * ((y^2)^k / of_nat (2*(k+n)+1)))\"\n      by (simp only: ring_distribs power_add power_mult) (simp add: mult_ac)\n    also from x have \"c * (2*y^(2*n+1)) = 1\" by (simp add: c_def y_def)\n    finally have \"(\\<lambda>k. (y^2)^k / of_nat (2*(k+n)+1)) sums ?d\" by simp\n  } note sums' = this\n  moreover from norm_y' have \"(\\<lambda>k. (y^2)^k / of_nat (2*n+1)) sums (1 / (1 - y^2) / of_nat (2*n+1))\"\n    by (intro sums_divide geometric_sums) (simp_all add: norm_power)\n  ultimately have \"?d \\<le> (1 / (1 - y^2) / of_nat (2*n+1))\" by (rule sums_le)\n  moreover have \"c * (ln x - (\\<Sum>k<n. 2 * y ^ (2 * k + 1) / real_of_nat (2 * k + 1))) \\<ge> 0\"\n    by (intro sums_le[OF _ sums_zero sums']) simp_all\n  ultimately show ?thesis unfolding c_def by simp\nqed\n\nlemma\n  fixes n :: nat and x :: real\n  defines \"y \\<equiv> (x-1)/(x+1)\"\n  defines \"approx \\<equiv> (\\<Sum>k<n. 2*y^(2*k+1) / of_nat (2*k+1))\"\n  defines \"d \\<equiv> y^(2*n+1) / (1 - y^2) / of_nat (2*n+1)\"\n  assumes x: \"x > 1\"\n  shows   ln_approx_bounds: \"ln x \\<in> {approx..approx + 2*d}\"\n  and     ln_approx_abs:    \"abs (ln x - (approx + d)) \\<le> d\"\nproof -\n  define c where \"c = 2*y^(2*n+1)\"\n  from x have c_pos: \"c > 0\" unfolding c_def y_def\n    by (intro mult_pos_pos zero_less_power) simp_all\n  have A: \"inverse c * (ln x - (\\<Sum>k<n. 2*y^(2*k+1) / of_nat (2*k+1))) \\<in>\n              {0.. (1 / (1 - y^2) / of_nat (2*n+1))}\" using assms unfolding y_def c_def\n    by (intro ln_approx_aux) simp_all\n  hence \"inverse c * (ln x - (\\<Sum>k<n. 2*y^(2*k+1)/of_nat (2*k+1))) \\<le> (1 / (1-y^2) / of_nat (2*n+1))\"\n    by simp\n  hence \"(ln x - (\\<Sum>k<n. 2*y^(2*k+1) / of_nat (2*k+1))) / c \\<le> (1 / (1 - y^2) / of_nat (2*n+1))\"\n    by (auto simp add: field_split_simps)\n  with c_pos have \"ln x \\<le> c / (1 - y^2) / of_nat (2*n+1) + approx\"\n    by (subst (asm) pos_divide_le_eq) (simp_all add: mult_ac approx_def)\n  moreover {\n    from A c_pos have \"0 \\<le> c * (inverse c * (ln x - (\\<Sum>k<n. 2*y^(2*k+1) / of_nat (2*k+1))))\"\n      by (intro mult_nonneg_nonneg[of c]) simp_all\n    also have \"\\<dots> = (c * inverse c) * (ln x - (\\<Sum>k<n. 2*y^(2*k+1) / of_nat (2*k+1)))\"\n      by (simp add: mult_ac)\n    also from c_pos have \"c * inverse c = 1\" by simp\n    finally have \"ln x \\<ge> approx\" by (simp add: approx_def)\n  }\n  ultimately show \"ln x \\<in> {approx..approx + 2*d}\" by (simp add: c_def d_def)\n  thus \"abs (ln x - (approx + d)) \\<le> d\" by auto\nqed\n\nend\n\nlemma euler_mascheroni_bounds:\n  fixes n :: nat assumes \"n \\<ge> 1\" defines \"t \\<equiv> harm n - ln (of_nat (Suc n)) :: real\"\n  shows \"euler_mascheroni \\<in> {t + inverse (of_nat (2*(n+1)))..t + inverse (of_nat (2*n))}\"\n  using assms euler_mascheroni_upper[of \"n-1\"] euler_mascheroni_lower[of \"n-1\"]\n  unfolding t_def by (cases n) (simp_all add: harm_Suc t_def inverse_eq_divide)\n\nlemma euler_mascheroni_bounds':\n  fixes n :: nat assumes \"n \\<ge> 1\" \"ln (real_of_nat (Suc n)) \\<in> {l<..<u}\"\n  shows \"euler_mascheroni \\<in>\n           {harm n - u + inverse (of_nat (2*(n+1)))<..<harm n - l + inverse (of_nat (2*n))}\"\n  using euler_mascheroni_bounds[OF assms(1)] assms(2) by auto\n\n\ntext \\<open>\n  Approximation of \\<^term>\\<open>ln 2\\<close>. The lower bound is accurate to about 0.03; the upper\n  bound is accurate to about 0.0015.\n\\<close>\nlemma ln2_ge_two_thirds: \"2/3 \\<le> ln (2::real)\"\n  and ln2_le_25_over_36: \"ln (2::real) \\<le> 25/36\"\n  using ln_approx_bounds[of 2 1, simplified, simplified eval_nat_numeral, simplified] by simp_all\n\n\ntext \\<open>\n  Approximation of the Euler-Mascheroni constant. The lower bound is accurate to about 0.0015;\n  the upper bound is accurate to about 0.015.\n\\<close>\nlemma euler_mascheroni_gt_19_over_33: \"(euler_mascheroni :: real) > 19/33\" (is ?th1)\n  and euler_mascheroni_less_13_over_22: \"(euler_mascheroni :: real) < 13/22\" (is ?th2)\nproof -\n  have \"ln (real (Suc 7)) = 3 * ln 2\" by (simp add: ln_powr [symmetric])\n  also from ln_approx_bounds[of 2 3] have \"\\<dots> \\<in> {3*307/443<..<3*4615/6658}\"\n    by (simp add: eval_nat_numeral)\n  finally have \"ln (real (Suc 7)) \\<in> \\<dots>\" .\n  from euler_mascheroni_bounds'[OF _ this] have \"?th1 \\<and> ?th2\" by (simp_all add: harm_expand)\n  thus ?th1 ?th2 by blast+\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/Analysis/Harmonic_Numbers.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8615381952105442, "lm_q2_score": 0.853912760387131, "lm_q1q2_score": 0.7356784584511827}}
{"text": "(*  Title:      HOL/Hull.thy\n    Author:     Amine Chaieb, University of Cambridge\n    Author:     Jose Divas\u00f3n <jose.divasonm at unirioja.es>\n    Author:     Jes\u00fas Aransay <jesus-maria.aransay at unirioja.es>\n    Author:     Johannes H\u00f6lzl, VU Amsterdam\n*)\n\ntheory Hull\n  imports Main\nbegin\n\nsubsection \\<open>A generic notion of the convex, affine, conic hull, or closed \"hull\".\\<close>\n\ndefinition hull :: \"('a set \\<Rightarrow> bool) \\<Rightarrow> 'a set \\<Rightarrow> 'a set\"  (infixl \"hull\" 75)\n  where \"S hull s = \\<Inter>{t. S t \\<and> s \\<subseteq> t}\"\n\nlemma hull_same: \"S s \\<Longrightarrow> S hull s = s\"\n  unfolding hull_def by auto\n\nlemma hull_in: \"(\\<And>T. Ball T S \\<Longrightarrow> S (\\<Inter>T)) \\<Longrightarrow> S (S hull s)\"\n  unfolding hull_def Ball_def by auto\n\nlemma hull_eq: \"(\\<And>T. Ball T S \\<Longrightarrow> S (\\<Inter>T)) \\<Longrightarrow> (S hull s) = s \\<longleftrightarrow> S s\"\n  using hull_same[of S s] hull_in[of S s] by metis\n\nlemma hull_hull [simp]: \"S hull (S hull s) = S hull s\"\n  unfolding hull_def by blast\n\nlemma hull_subset[intro]: \"s \\<subseteq> (S hull s)\"\n  unfolding hull_def by blast\n\nlemma hull_mono: \"s \\<subseteq> t \\<Longrightarrow> (S hull s) \\<subseteq> (S hull t)\"\n  unfolding hull_def by blast\n\nlemma hull_antimono: \"\\<forall>x. S x \\<longrightarrow> T x \\<Longrightarrow> (T hull s) \\<subseteq> (S hull s)\"\n  unfolding hull_def by blast\n\nlemma hull_minimal: \"s \\<subseteq> t \\<Longrightarrow> S t \\<Longrightarrow> (S hull s) \\<subseteq> t\"\n  unfolding hull_def by blast\n\nlemma subset_hull: \"S t \\<Longrightarrow> S hull s \\<subseteq> t \\<longleftrightarrow> s \\<subseteq> t\"\n  unfolding hull_def by blast\n\nlemma hull_UNIV [simp]: \"S hull UNIV = UNIV\"\n  unfolding hull_def by auto\n\nlemma hull_unique: \"s \\<subseteq> t \\<Longrightarrow> S t \\<Longrightarrow> (\\<And>t'. s \\<subseteq> t' \\<Longrightarrow> S t' \\<Longrightarrow> t \\<subseteq> t') \\<Longrightarrow> (S hull s = t)\"\n  unfolding hull_def by auto\n\nlemma hull_induct: \"\\<lbrakk>a \\<in> Q hull S; \\<And>x. x\\<in> S \\<Longrightarrow> P x; Q {x. P x}\\<rbrakk> \\<Longrightarrow> P a\"\n  using hull_minimal[of S \"{x. P x}\" Q]\n  by (auto simp add: subset_eq)\n\nlemma hull_inc: \"x \\<in> S \\<Longrightarrow> x \\<in> P hull S\"\n  by (metis hull_subset subset_eq)\n\nlemma hull_Un_subset: \"(S hull s) \\<union> (S hull t) \\<subseteq> (S hull (s \\<union> t))\"\n  unfolding Un_subset_iff by (metis hull_mono Un_upper1 Un_upper2)\n\nlemma hull_Un:\n  assumes T: \"\\<And>T. Ball T S \\<Longrightarrow> S (\\<Inter>T)\"\n  shows \"S hull (s \\<union> t) = S hull (S hull s \\<union> S hull t)\"\n  apply (rule equalityI)\n  apply (meson hull_mono hull_subset sup.mono)\n  by (metis hull_Un_subset hull_hull hull_mono)\n\nlemma hull_Un_left: \"P hull (S \\<union> T) = P hull (P hull S \\<union> T)\"\n  apply (rule equalityI)\n   apply (simp add: Un_commute hull_mono hull_subset sup.coboundedI2)\n  by (metis Un_subset_iff hull_hull hull_mono hull_subset)\n\nlemma hull_Un_right: \"P hull (S \\<union> T) = P hull (S \\<union> P hull T)\"\n  by (metis hull_Un_left sup.commute)\n\nlemma hull_insert:\n   \"P hull (insert a S) = P hull (insert a (P hull S))\"\n  by (metis hull_Un_right insert_is_Un)\n\nlemma hull_redundant_eq: \"a \\<in> (S hull s) \\<longleftrightarrow> S hull (insert a s) = S hull s\"\n  unfolding hull_def by blast\n\nlemma hull_redundant: \"a \\<in> (S hull s) \\<Longrightarrow> S hull (insert a s) = S hull s\"\n  by (metis hull_redundant_eq)\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/Hull.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916029436189, "lm_q2_score": 0.8519528019683106, "lm_q1q2_score": 0.7355688953237273}}
{"text": "section \\<open> Unrestriction \\<close>\n\ntheory utp_unrest\n  imports utp_expr_insts\nbegin\n\nsubsection \\<open> Definitions and Core Syntax \\<close>\n  \ntext \\<open> Unrestriction is an encoding of semantic freshness that allows us to reason about the\n  presence of variables in predicates without being concerned with abstract syntax trees.\n  An expression $p$ is unrestricted by lens $x$, written $x \\mathop{\\sharp} p$, if\n  altering the value of $x$ has no effect on the valuation of $p$. This is a sufficient\n  notion to prove many laws that would ordinarily rely on an \\emph{fv} function. \n\n  Unrestriction was first defined in the work of Marcel Oliveira~\\cite{Oliveira2005-PHD,Oliveira07} in his\n  UTP mechanisation in \\emph{ProofPowerZ}. Our definition modifies his in that our variables\n  are semantically characterised as lenses, and supported by the lens laws, rather than named \n  syntactic entities. We effectively fuse the ideas from both Feliachi~\\cite{Feliachi2010} and \n  Oliveira's~\\cite{Oliveira07} mechanisations of the UTP, the former being also purely semantic\n  in nature.\n\n  We first set up overloaded syntax for unrestriction, as several concepts will have this\n  defined. \\<close>\n\nconsts\n  unrest :: \"'a \\<Rightarrow> 'b \\<Rightarrow> bool\"\n\nsyntax\n  \"_unrest\" :: \"salpha \\<Rightarrow> logic \\<Rightarrow> logic \\<Rightarrow> logic\" (infix \"\\<sharp>\" 20)\n  \ntranslations\n  \"_unrest x p\" == \"CONST unrest x p\"                                           \n  \"_unrest (_salphaset (_salphamk (x +\\<^sub>L y))) P\"  <= \"_unrest (x +\\<^sub>L y) P\"\n\ntext \\<open> Our syntax translations support both variables and variable sets such that we can write down \n  predicates like @{term \"&x \\<sharp> P\"} and also @{term \"{&x,&y,&z} \\<sharp> P\"}. \n\n  We set up a simple tactic for discharging unrestriction conjectures using a simplification set. \\<close>\n  \nnamed_theorems unrest\nmethod unrest_tac = (simp add: unrest)?\n\ntext \\<open> Unrestriction for expressions is defined as a lifted construct using the underlying lens\n  operations. It states that lens $x$ is unrestricted by expression $e$ provided that, for any\n  state-space binding $b$ and variable valuation $v$, the value which the expression evaluates\n  to is unaltered if we set $x$ to $v$ in $b$. In other words, we cannot effect the behaviour\n  of $e$ by changing $x$. Thus $e$ does not observe the portion of state-space characterised\n  by $x$. We add this definition to our overloaded constant. \\<close>\n  \nlift_definition unrest_uexpr :: \"('a \\<Longrightarrow> '\\<alpha>) \\<Rightarrow> ('b, '\\<alpha>) uexpr \\<Rightarrow> bool\"\nis \"\\<lambda> x e. \\<forall> b v. e (put\\<^bsub>x\\<^esub> b v) = e b\" .\n\nadhoc_overloading\n  unrest unrest_uexpr\n\nlemma unrest_expr_alt_def:\n  \"weak_lens x \\<Longrightarrow> (x \\<sharp> P) = (\\<forall> b b'. \\<lbrakk>P\\<rbrakk>\\<^sub>e (b \\<oplus>\\<^sub>L b' on x) = \\<lbrakk>P\\<rbrakk>\\<^sub>e b)\"\n  by (transfer, metis lens_override_def weak_lens.put_get)\n  \nsubsection \\<open> Unrestriction laws \\<close>\n  \ntext \\<open> We now prove unrestriction laws for the key constructs of our expression model. Many\n  of these depend on lens properties and so variously employ the assumptions @{term mwb_lens} and\n  @{term vwb_lens}, depending on the number of assumptions from the lenses theory is required.\n\n  Firstly, we prove a general property -- if $x$ and $y$ are both unrestricted in $P$, then their composition\n  is also unrestricted in $P$. One can interpret the composition here as a union -- if the two sets\n  of variables $x$ and $y$ are unrestricted, then so is their union. \\<close>\n  \nlemma unrest_var_comp [unrest]:\n  \"\\<lbrakk> x \\<sharp> P; y \\<sharp> P \\<rbrakk> \\<Longrightarrow> x;y \\<sharp> P\"\n  by (transfer, simp add: lens_defs)\n\nlemma unrest_svar [unrest]: \"(&x \\<sharp> P) \\<longleftrightarrow> (x \\<sharp> P)\"\n  by (transfer, simp add: lens_defs)\n\ntext \\<open> No lens is restricted by a literal, since it returns the same value for any state binding. \\<close>\n    \nlemma unrest_lit [unrest]: \"x \\<sharp> \\<guillemotleft>v\\<guillemotright>\"\n  by (transfer, simp)\n\ntext \\<open> If one lens is smaller than another, then any unrestriction on the larger lens implies\n  unrestriction on the smaller. \\<close>\n    \nlemma unrest_sublens:\n  fixes P :: \"('a, '\\<alpha>) uexpr\"\n  assumes \"x \\<sharp> P\" \"y \\<subseteq>\\<^sub>L x\"\n  shows \"y \\<sharp> P\" \n  using assms\n  by (transfer, metis (no_types, lifting) lens.select_convs(2) lens_comp_def sublens_def)\n    \ntext \\<open> If two lenses are equivalent, and thus they characterise the same state-space regions,\n  then clearly unrestrictions over them are equivalent. \\<close>\n    \nlemma unrest_equiv:\n  fixes P :: \"('a, '\\<alpha>) uexpr\"\n  assumes \"mwb_lens y\" \"x \\<approx>\\<^sub>L y\" \"x \\<sharp> P\"\n  shows \"y \\<sharp> P\"\n  by (metis assms lens_equiv_def sublens_pres_mwb sublens_put_put unrest_uexpr.rep_eq)\n\ntext \\<open> If we can show that an expression is unrestricted on a bijective lens, then is unrestricted\n  on the entire state-space. \\<close>\n\nlemma bij_lens_unrest_all:\n  fixes P :: \"('a, '\\<alpha>) uexpr\"\n  assumes \"bij_lens X\" \"X \\<sharp> P\"\n  shows \"\\<Sigma> \\<sharp> P\"\n  using assms bij_lens_equiv_id lens_equiv_def unrest_sublens by blast\n\nlemma bij_lens_unrest_all_eq:\n  fixes P :: \"('a, '\\<alpha>) uexpr\"\n  assumes \"bij_lens X\"\n  shows \"(\\<Sigma> \\<sharp> P) \\<longleftrightarrow> (X \\<sharp> P)\"\n  by (meson assms bij_lens_equiv_id lens_equiv_def unrest_sublens)\n\ntext \\<open> If an expression is unrestricted by all variables, then it is unrestricted by any variable \\<close>\n\nlemma unrest_all_var:\n  fixes e :: \"('a, '\\<alpha>) uexpr\"\n  assumes \"\\<Sigma> \\<sharp> e\"\n  shows \"x \\<sharp> e\"\n  by (metis assms id_lens_def lens.simps(2) unrest_uexpr.rep_eq)\n\ntext \\<open> We can split an unrestriction composed by lens plus \\<close>\n\nlemma unrest_plus_split:\n  fixes P :: \"('a, '\\<alpha>) uexpr\"\n  assumes \"x \\<bowtie> y\" \"vwb_lens x\" \"vwb_lens y\"\n  shows \"unrest (x +\\<^sub>L y) P \\<longleftrightarrow> (x \\<sharp> P) \\<and> (y \\<sharp> P)\"\n  using assms\n  by (meson lens_plus_right_sublens lens_plus_ub sublens_refl unrest_sublens unrest_var_comp vwb_lens_wb)\n\ntext \\<open> The following laws demonstrate the primary motivation for lens independence: a variable\n  expression is unrestricted by another variable only when the two variables are independent. \n  Lens independence thus effectively allows us to semantically characterise when two variables,\n  or sets of variables, are different. \\<close>\n\nlemma unrest_var [unrest]: \"\\<lbrakk> mwb_lens x; x \\<bowtie> y \\<rbrakk> \\<Longrightarrow> y \\<sharp> var x\"\n  by (transfer, auto)\n    \nlemma unrest_iuvar [unrest]: \"\\<lbrakk> mwb_lens x; x \\<bowtie> y \\<rbrakk> \\<Longrightarrow> $y \\<sharp> $x\"\n  by (simp add: unrest_var)\n\nlemma unrest_ouvar [unrest]: \"\\<lbrakk> mwb_lens x; x \\<bowtie> y \\<rbrakk> \\<Longrightarrow> $y\\<acute> \\<sharp> $x\\<acute>\"\n  by (simp add: unrest_var)\n\ntext \\<open> The following laws follow automatically from independence of input and output variables. \\<close>\n    \nlemma unrest_iuvar_ouvar [unrest]:\n  fixes x :: \"('a \\<Longrightarrow> '\\<alpha>)\"\n  assumes \"mwb_lens y\"\n  shows \"$x \\<sharp> $y\\<acute>\"\n  by (metis prod.collapse unrest_uexpr.rep_eq var.rep_eq var_lookup_out var_update_in)\n\nlemma unrest_ouvar_iuvar [unrest]:\n  fixes x :: \"('a \\<Longrightarrow> '\\<alpha>)\"\n  assumes \"mwb_lens y\"\n  shows \"$x\\<acute> \\<sharp> $y\"\n  by (metis prod.collapse unrest_uexpr.rep_eq var.rep_eq var_lookup_in var_update_out)\n\ntext \\<open> Unrestriction distributes through the various function lifting expression constructs;\n  this allows us to prove unrestrictions for the majority of the expression language. \\<close>\n    \nlemma unrest_uop [unrest]: \"x \\<sharp> e \\<Longrightarrow> x \\<sharp> uop f e\"\n  by (transfer, simp)\n\nlemma unrest_bop [unrest]: \"\\<lbrakk> x \\<sharp> u; x \\<sharp> v \\<rbrakk> \\<Longrightarrow> x \\<sharp> bop f u v\"\n  by (transfer, simp)\n\nlemma unrest_trop [unrest]: \"\\<lbrakk> x \\<sharp> u; x \\<sharp> v; x \\<sharp> w \\<rbrakk> \\<Longrightarrow> x \\<sharp> trop f u v w\"\n  by (transfer, simp)\n\nlemma unrest_qtop [unrest]: \"\\<lbrakk> x \\<sharp> u; x \\<sharp> v; x \\<sharp> w; x \\<sharp> y \\<rbrakk> \\<Longrightarrow> x \\<sharp> qtop f u v w y\"\n  by (transfer, simp)\n\ntext \\<open> For convenience, we also prove unrestriction rules for the bespoke operators on equality,\n  numbers, arithmetic etc. \\<close>\n    \nlemma unrest_eq [unrest]: \"\\<lbrakk> x \\<sharp> u; x \\<sharp> v \\<rbrakk> \\<Longrightarrow> x \\<sharp> u =\\<^sub>u v\"\n  by (simp add: eq_upred_def, transfer, simp)\n\nlemma unrest_zero [unrest]: \"x \\<sharp> 0\"\n  by (simp add: unrest_lit zero_uexpr_def)\n\nlemma unrest_one [unrest]: \"x \\<sharp> 1\"\n  by (simp add: one_uexpr_def unrest_lit)\n\nlemma unrest_numeral [unrest]: \"x \\<sharp> (numeral n)\"\n  by (simp add: numeral_uexpr_simp unrest_lit)\n\nlemma unrest_sgn [unrest]: \"x \\<sharp> u \\<Longrightarrow> x \\<sharp> sgn u\"\n  by (simp add: sgn_uexpr_def unrest_uop)\n\nlemma unrest_abs [unrest]: \"x \\<sharp> u \\<Longrightarrow> x \\<sharp> abs u\"\n  by (simp add: abs_uexpr_def unrest_uop)\n\nlemma unrest_plus [unrest]: \"\\<lbrakk> x \\<sharp> u; x \\<sharp> v \\<rbrakk> \\<Longrightarrow> x \\<sharp> u + v\"\n  by (simp add: plus_uexpr_def unrest)\n\nlemma unrest_uminus [unrest]: \"x \\<sharp> u \\<Longrightarrow> x \\<sharp> - u\"\n  by (simp add: uminus_uexpr_def unrest)\n\nlemma unrest_minus [unrest]: \"\\<lbrakk> x \\<sharp> u; x \\<sharp> v \\<rbrakk> \\<Longrightarrow> x \\<sharp> u - v\"\n  by (simp add: minus_uexpr_def unrest)\n\nlemma unrest_times [unrest]: \"\\<lbrakk> x \\<sharp> u; x \\<sharp> v \\<rbrakk> \\<Longrightarrow> x \\<sharp> u * v\"\n  by (simp add: times_uexpr_def unrest)\n\nlemma unrest_divide [unrest]: \"\\<lbrakk> x \\<sharp> u; x \\<sharp> v \\<rbrakk> \\<Longrightarrow> x \\<sharp> u / v\"\n  by (simp add: divide_uexpr_def unrest)\n\nlemma unrest_case_prod [unrest]: \"\\<lbrakk> \\<And> i j. x \\<sharp> P i j \\<rbrakk> \\<Longrightarrow> x \\<sharp> case_prod P v\"\n  by (simp add: prod.split_sel_asm)\n\ntext \\<open> For a $\\lambda$-term we need to show that the characteristic function expression does\n  not restrict $v$ for any input value $x$. \\<close>\n    \nlemma unrest_ulambda [unrest]:\n  \"\\<lbrakk> \\<And> x. v \\<sharp> F x \\<rbrakk> \\<Longrightarrow> v \\<sharp> (\\<lambda> x \\<bullet> F x)\"\n  by (transfer, simp)\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/utp/utp_unrest.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8872046026642945, "lm_q2_score": 0.8289388125473629, "lm_q1q2_score": 0.7354383298190952}}
{"text": "theory Namespace_String\n  imports \n    Main\n    Ecore.Model_Namespace\n    List_Join_Split\n    Namespace_List\nbegin\n\nsection \"Namespace to string mapping for string based namespaces\"\n\ntext \"Maps a namespace consisting of strings to a single string, entirely lossless.\"\n\ndefinition ns_to_string :: \"'t \\<Rightarrow> 't list Namespace \\<Rightarrow> 't list\" where\n  \"ns_to_string d n \\<equiv> join d ([[]] @ (ns_to_list n))\"\n\ndefinition string_to_ns :: \"'t \\<Rightarrow> 't list \\<Rightarrow> 't list Namespace\" where\n  \"string_to_ns d s \\<equiv> list_to_ns (tl (split d s))\"\n\n\nsubsection \"Lemma's on the definition\"\n\nlemma ns_to_string_root: \"ns_to_string d \\<bottom> = []\"\n  by (simp add: ns_to_string_def)\n\nlemma ns_to_string_identifier: \"ns_to_string d (Identifier \\<bottom>\\<^enum>x) = [d] @ x\"\n  by (simp add: ns_to_string_def)\n\nlemma ns_to_string_append: \"ns_to_string d (Identifier (x, y)) = ns_to_string d x @ [d] @ y\"\n  unfolding ns_to_string_def\n  using join_append by fastforce\n\nlemma string_to_ns_root: \"string_to_ns d [] = \\<bottom>\"\n  by (simp add: split_def list_to_ns_def string_to_ns_def)\n\nlemma string_to_ns_identifier: \"d \\<notin> set x \\<Longrightarrow> string_to_ns d ([d] @ x) = Identifier \\<bottom>\\<^enum>x\"\n  unfolding string_to_ns_def\nproof-\n  fix x\n  assume \"d \\<notin> set x\"\n  then have \"list_to_ns (tl (split d ([d] @ x))) = list_to_ns (tl ([[], x]))\"\n    by (simp add: split_def split_rec_singleton_left)\n  then have \"list_to_ns (tl (split d ([d] @ x))) = list_to_ns [x]\"\n    by simp\n  then show \"list_to_ns (tl (split d ([d] @ x))) = Identifier \\<bottom>\\<^enum>x\"\n    by (simp add: list_to_ns_def)\nqed\n\nlemma string_to_ns_append: \"d \\<notin> set y \\<Longrightarrow> string_to_ns d (x @ [d] @ y) = Identifier (string_to_ns d x, y)\"\n  unfolding string_to_ns_def\nproof-\n  fix x y\n  assume no_delimiter: \"d \\<notin> set y\"\n  then have \"list_to_ns (tl (split d (x @ [d] @ y))) = list_to_ns (tl (split d x) @ [y])\"\n    using split_def list.distinct(1) split_append split_empty split_rec_not_empty tl_append2\n    by metis\n  then show \"list_to_ns (tl (split d (x @ [d] @ y))) = Identifier (list_to_ns (tl (split d x)), y)\"\n    using list_to_ns_inverse ns_to_list.simps(2) ns_to_list_inverse\n    by metis\nqed\n\nlemma string_to_ns_delim_impl_identifier: \"d \\<in> set x \\<Longrightarrow> \\<exists>y. string_to_ns d x = Identifier y\"\n  using split_list_last string_to_ns_append by fastforce\n\n\nsubsection \"Domain & Range\"\n\ninductive_set string_namespace_domain :: \"'t \\<Rightarrow> 't list Namespace set\"\n  for d :: \"'t\"\n  where\n    rule_root: \"\\<bottom> \\<in> string_namespace_domain d\" |\n    rule_nested: \"namespace \\<in> string_namespace_domain d \\<Longrightarrow> d \\<notin> set name \\<Longrightarrow> Identifier (namespace, name) \\<in> string_namespace_domain d\"\n\nlemma string_namespace_domain_subset: \"string_namespace_domain d \\<subseteq> namespace_domain\"\n  using namespace_domainI\n  by blast\n\ninductive_set string_namespace_range :: \"'t \\<Rightarrow> 't list set\"\n  for d :: \"'t\"\n  where\n    rule_root: \"[] \\<in> string_namespace_range d\" |\n    rule_nested: \"str \\<in> string_namespace_range d \\<Longrightarrow> d \\<notin> set name \\<Longrightarrow> str @ [d] @ name \\<in> string_namespace_range d\"\n\nlemma string_namespace_range_subset: \"string_namespace_range d \\<subseteq> split_bij_domain d\"\nproof\n  fix x\n  assume \"x \\<in> string_namespace_range d\"\n  then show \"x \\<in> split_bij_domain d\"\n  proof (induct)\n    case rule_root\n    then show ?case\n      by (simp add: split_bij_domain.rule_no_delim)\n  next\n    case (rule_nested str name)\n    then show ?case\n      using split_bij_domain.rule_append\n      by simp\n  qed\nqed\n\n\nsubsection \"Inverse function\"\n\nlemma ns_to_string_inverse: \"x \\<in> string_namespace_domain d \\<Longrightarrow> string_to_ns d (ns_to_string d x) = x\"\nproof (induct x rule: string_namespace_domain.induct)\n  case rule_root\n  then show ?case\n    by (simp add: ns_to_string_root string_to_ns_root)\nnext\n  case (rule_nested namespace name)\n  then show ?case\n    using ns_to_string_append string_to_ns_append\n    by metis\nqed\n\nlemma string_to_ns_inverse: \"x \\<in> string_namespace_range d \\<Longrightarrow> ns_to_string d (string_to_ns d x) = x\"\nproof (induct x rule: string_namespace_range.induct)\n  case rule_root\n  then show ?case\n    by (simp add: ns_to_string_root string_to_ns_root)\nnext\n  case (rule_nested str name)\n  then show ?case\n    using ns_to_string_append string_to_ns_append\n    by metis\nqed\n\n\nsubsection \"Range of mapping functions\"\n\nlemma ns_to_string_range: \"ns_to_string d ` string_namespace_domain d = string_namespace_range d\"\nproof\n  show \"ns_to_string d ` string_namespace_domain d \\<subseteq> string_namespace_range d\"\n  proof\n    fix x\n    assume \"x \\<in> ns_to_string d ` string_namespace_domain d\"\n    then show \"x \\<in> string_namespace_range d\"\n    proof\n      fix xa\n      assume x_is_xa: \"x = ns_to_string d xa\"\n      assume \"xa \\<in> string_namespace_domain d\"\n      then have \"ns_to_string d xa \\<in> string_namespace_range d\"\n      proof (induct xa)\n        case rule_root\n        then show ?case\n          by (simp add: ns_to_string_root string_namespace_range.rule_root)\n      next\n        case (rule_nested namespace name)\n        then show ?case\n          using ns_to_string_append string_namespace_range.rule_nested\n          by metis\n      qed\n      then show \"x \\<in> string_namespace_range d\"\n        using x_is_xa\n        by simp\n    qed\n  qed\nnext\n  show \"string_namespace_range d \\<subseteq> ns_to_string d ` string_namespace_domain d\"\n  proof\n    fix x\n    assume \"x \\<in> string_namespace_range d\"\n    then show \"x \\<in> ns_to_string d ` string_namespace_domain d\"\n    proof (induct x)\n      case rule_root\n      then show ?case\n        unfolding ns_to_string_def\n        using image_iff string_namespace_domain.intros(1) \n        by fastforce\n    next\n      case (rule_nested str name)\n      then have namespace_existance: \"\\<exists>namespace. namespace \\<in> string_namespace_domain d \\<and> str = ns_to_string d namespace\"\n        by blast\n      have \"\\<And>namespace. namespace \\<in> string_namespace_domain d \\<Longrightarrow> Identifier (namespace, name) \\<in> string_namespace_domain d\"\n        by (simp add: rule_nested.hyps(3) string_namespace_domain.rule_nested)\n      then have \"\\<And>namespace. namespace \\<in> string_namespace_domain d \\<Longrightarrow> ns_to_string d (Identifier (namespace, name)) \\<in> ns_to_string d ` string_namespace_domain d\"\n        by simp\n      then have \"\\<And>namespace. namespace \\<in> string_namespace_domain d \\<Longrightarrow> ns_to_string d (namespace) @ [d] @ name \\<in> ns_to_string d ` string_namespace_domain d\"\n        by (simp add: ns_to_string_append)\n      then show ?case\n        using namespace_existance\n        by blast\n    qed\n  qed\nqed\n\nlemma string_to_ns_range: \"string_to_ns d ` string_namespace_range d = string_namespace_domain d\"\nproof\n  show \"string_to_ns d ` string_namespace_range d \\<subseteq> string_namespace_domain d\"\n  proof\n    fix x\n    assume \"x \\<in> string_to_ns d ` string_namespace_range d\"\n    then show \"x \\<in> string_namespace_domain d\"\n    proof\n      fix xa\n      assume x_is_xa: \"x = string_to_ns d xa\"\n      assume \"xa \\<in> string_namespace_range d\"\n      then have \"string_to_ns d xa \\<in> string_namespace_domain d\"\n      proof (induct xa)\n        case rule_root\n        then show ?case\n          by (simp add: string_namespace_domain.rule_root string_to_ns_root)\n      next\n        case (rule_nested str name)\n        then show ?case\n          using string_namespace_domain.simps string_to_ns_append\n          by metis\n      qed\n      then show \"x \\<in> string_namespace_domain d\"\n        using x_is_xa\n        by simp\n    qed\n  qed\nnext\n  show \"string_namespace_domain d \\<subseteq> string_to_ns d ` string_namespace_range d\"\n  proof\n    fix x\n    assume \"x \\<in> string_namespace_domain d\"\n    then show \"x \\<in> string_to_ns d ` string_namespace_range d\"\n    proof (induct x)\n      case rule_root\n      then show ?case\n        using image_iff string_namespace_range.rule_root string_to_ns_root \n        by metis\n    next\n      case (rule_nested namespace name)\n      then have str_existance: \"\\<exists>str. str \\<in> string_namespace_range d \\<and> namespace = string_to_ns d str\"\n        by blast\n      have \"\\<And>str. str \\<in> string_namespace_range d \\<Longrightarrow> str @ [d] @ name \\<in> string_namespace_range d\"\n        using rule_nested.hyps(3) string_namespace_range.rule_nested\n        by metis\n      then have \"\\<And>str. str \\<in> string_namespace_range d \\<Longrightarrow> string_to_ns d (str @ [d] @ name) \\<in> string_to_ns d ` string_namespace_range d\"\n        by simp\n      then have \"\\<And>str. str \\<in> string_namespace_range d \\<Longrightarrow> Identifier ((string_to_ns d str), name) \\<in> string_to_ns d ` string_namespace_range d\"\n        using rule_nested.hyps(3) string_to_ns_append \n        by metis\n      then show ?case\n        using str_existance\n        by blast\n    qed\n  qed\nqed\n\n\nsubsection \"Injectivity\"\n\nlemma ns_to_string_inj[simp]: \"inj_on (ns_to_string d) (string_namespace_domain d)\"\nproof\n  fix x y\n  assume x_in_domain: \"x \\<in> string_namespace_domain d\"\n  assume y_in_domain: \"y \\<in> string_namespace_domain d\"\n  assume mapping_eq: \"ns_to_string d x = ns_to_string d y\"\n  then show \"x = y\"\n    using x_in_domain y_in_domain ns_to_string_inverse\n    by metis\nqed\n\nlemma string_to_ns_inj[simp]: \"inj_on (string_to_ns d) (string_namespace_range d)\"\nproof\n  fix x y\n  assume x_in_range: \"x \\<in> string_namespace_range d\"\n  assume y_in_range: \"y \\<in> string_namespace_range d\"\n  assume mapping_eq: \"string_to_ns d x = string_to_ns d y\"\n  then show \"x = y\"\n    using x_in_range y_in_range string_to_ns_inverse\n    by metis\nqed\n\n\nsubsection \"Bijectivity\"\n\nlemma ns_to_string_bij[simp]: \"bij_betw (ns_to_string d) (string_namespace_domain d) (string_namespace_range d)\"\n  unfolding bij_betw_def\n  using ns_to_string_inj ns_to_string_range\n  by simp\n\nlemma string_to_ns_bij[simp]: \"bij_betw (string_to_ns d) (string_namespace_range d) (string_namespace_domain d)\"\n  unfolding bij_betw_def\n  using string_to_ns_inj string_to_ns_range\n  by simp\n\n\nsubsection \"Subnamespaces\"\n\ndefinition ns_string_in_ns_string :: \"char \\<Rightarrow> string \\<Rightarrow> string \\<Rightarrow> bool\" where\n  \"ns_string_in_ns_string d xs ys \\<equiv> ns_list_in_ns_list (tl (split d xs)) (tl (split d ys))\"\n\nlemma ns_to_string_in_ns_to_string: \"\\<And>x y. x \\<in> string_namespace_domain d \\<Longrightarrow> y \\<in> string_namespace_domain d \\<Longrightarrow> ns_in_ns x y \\<longleftrightarrow> ns_string_in_ns_string d (ns_to_string d x) (ns_to_string d y)\"\nproof-\n  fix x y\n  assume x_in_domain: \"x \\<in> string_namespace_domain d\"\n  assume y_in_domain: \"y \\<in> string_namespace_domain d\"\n  show \"ns_in_ns x y \\<longleftrightarrow> ns_string_in_ns_string d (ns_to_string d x) (ns_to_string d y)\"\n    using list_to_ns_in_list_to_ns ns_string_in_ns_string_def ns_to_string_inverse string_to_ns_def x_in_domain y_in_domain\n    by metis\nqed\n\nlemma string_to_ns_in_string_to_ns: \"\\<And>x y. x \\<in> string_namespace_range d \\<Longrightarrow> y \\<in> string_namespace_range d \\<Longrightarrow> ns_in_ns (string_to_ns d x) (string_to_ns d y) \\<longleftrightarrow> ns_string_in_ns_string d x y\"\n  by (simp add: list_to_ns_in_list_to_ns ns_string_in_ns_string_def string_to_ns_def)\n\nend", "meta": {"author": "RemcodM", "repo": "thesis-ecore-groove-formalisation", "sha": "a0e860c4b60deb2f3798ae2ffc09f18a98cf42ca", "save_path": "github-repos/isabelle/RemcodM-thesis-ecore-groove-formalisation", "path": "github-repos/isabelle/RemcodM-thesis-ecore-groove-formalisation/thesis-ecore-groove-formalisation-a0e860c4b60deb2f3798ae2ffc09f18a98cf42ca/isabelle/Ecore-GROOVE-Mapping/Namespace_String.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045966995027, "lm_q2_score": 0.82893881677331, "lm_q1q2_score": 0.7354383286239276}}
{"text": "(*  Title:      HOL/Nonstandard_Analysis/HTranscendental.thy\n    Author:     Jacques D. Fleuriot\n    Copyright:  2001 University of Edinburgh\n\nConverted to Isar and polished by lcp\n*)\n\nsection\\<open>Nonstandard Extensions of Transcendental Functions\\<close>\n\ntheory HTranscendental\nimports Transcendental HSeries HDeriv\nbegin\n\ndefinition\n  exphr :: \"real => hypreal\" where\n    \\<comment>\\<open>define exponential function using standard part\\<close>\n  \"exphr x =  st(sumhr (0, whn, %n. inverse (fact n) * (x ^ n)))\"\n\ndefinition\n  sinhr :: \"real => hypreal\" where\n  \"sinhr x = st(sumhr (0, whn, %n. sin_coeff n * x ^ n))\"\n  \ndefinition\n  coshr :: \"real => hypreal\" where\n  \"coshr x = st(sumhr (0, whn, %n. cos_coeff n * x ^ n))\"\n\n\nsubsection\\<open>Nonstandard Extension of Square Root Function\\<close>\n\nlemma STAR_sqrt_zero [simp]: \"( *f* sqrt) 0 = 0\"\nby (simp add: starfun star_n_zero_num)\n\nlemma STAR_sqrt_one [simp]: \"( *f* sqrt) 1 = 1\"\nby (simp add: starfun star_n_one_num)\n\nlemma hypreal_sqrt_pow2_iff: \"(( *f* sqrt)(x) ^ 2 = x) = (0 \\<le> x)\"\napply (cases x)\napply (auto simp add: star_n_le star_n_zero_num starfun hrealpow star_n_eq_iff\n            simp del: hpowr_Suc power_Suc)\ndone\n\nlemma hypreal_sqrt_gt_zero_pow2: \"!!x. 0 < x ==> ( *f* sqrt) (x) ^ 2 = x\"\nby (transfer, simp)\n\nlemma hypreal_sqrt_pow2_gt_zero: \"0 < x ==> 0 < ( *f* sqrt) (x) ^ 2\"\nby (frule hypreal_sqrt_gt_zero_pow2, auto)\n\nlemma hypreal_sqrt_not_zero: \"0 < x ==> ( *f* sqrt) (x) \\<noteq> 0\"\napply (frule hypreal_sqrt_pow2_gt_zero)\napply (auto simp add: numeral_2_eq_2)\ndone\n\nlemma hypreal_inverse_sqrt_pow2:\n     \"0 < x ==> inverse (( *f* sqrt)(x)) ^ 2 = inverse x\"\napply (cut_tac n = 2 and a = \"( *f* sqrt) x\" in power_inverse [symmetric])\napply (auto dest: hypreal_sqrt_gt_zero_pow2)\ndone\n\nlemma hypreal_sqrt_mult_distrib: \n    \"!!x y. [|0 < x; 0 <y |] ==>\n      ( *f* sqrt)(x*y) = ( *f* sqrt)(x) * ( *f* sqrt)(y)\"\napply transfer\napply (auto intro: real_sqrt_mult_distrib) \ndone\n\nlemma hypreal_sqrt_mult_distrib2:\n     \"[|0\\<le>x; 0\\<le>y |] ==>  \n     ( *f* sqrt)(x*y) =  ( *f* sqrt)(x) * ( *f* sqrt)(y)\"\nby (auto intro: hypreal_sqrt_mult_distrib simp add: order_le_less)\n\nlemma hypreal_sqrt_approx_zero [simp]:\n     \"0 < x ==> (( *f* sqrt)(x) \\<approx> 0) = (x \\<approx> 0)\"\napply (auto simp add: mem_infmal_iff [symmetric])\napply (rule hypreal_sqrt_gt_zero_pow2 [THEN subst])\napply (auto intro: Infinitesimal_mult \n            dest!: hypreal_sqrt_gt_zero_pow2 [THEN ssubst] \n            simp add: numeral_2_eq_2)\ndone\n\nlemma hypreal_sqrt_approx_zero2 [simp]:\n     \"0 \\<le> x ==> (( *f* sqrt)(x) \\<approx> 0) = (x \\<approx> 0)\"\nby (auto simp add: order_le_less)\n\nlemma hypreal_sqrt_sum_squares [simp]:\n     \"(( *f* sqrt)(x*x + y*y + z*z) \\<approx> 0) = (x*x + y*y + z*z \\<approx> 0)\"\napply (rule hypreal_sqrt_approx_zero2)\napply (rule add_nonneg_nonneg)+\napply (auto)\ndone\n\nlemma hypreal_sqrt_sum_squares2 [simp]:\n     \"(( *f* sqrt)(x*x + y*y) \\<approx> 0) = (x*x + y*y \\<approx> 0)\"\napply (rule hypreal_sqrt_approx_zero2)\napply (rule add_nonneg_nonneg)\napply (auto)\ndone\n\nlemma hypreal_sqrt_gt_zero: \"!!x. 0 < x ==> 0 < ( *f* sqrt)(x)\"\napply transfer\napply (auto intro: real_sqrt_gt_zero)\ndone\n\nlemma hypreal_sqrt_ge_zero: \"0 \\<le> x ==> 0 \\<le> ( *f* sqrt)(x)\"\nby (auto intro: hypreal_sqrt_gt_zero simp add: order_le_less)\n\nlemma hypreal_sqrt_hrabs [simp]: \"!!x. ( *f* sqrt)(x\\<^sup>2) = \\<bar>x\\<bar>\"\nby (transfer, simp)\n\nlemma hypreal_sqrt_hrabs2 [simp]: \"!!x. ( *f* sqrt)(x*x) = \\<bar>x\\<bar>\"\nby (transfer, simp)\n\nlemma hypreal_sqrt_hyperpow_hrabs [simp]:\n     \"!!x. ( *f* sqrt)(x pow (hypnat_of_nat 2)) = \\<bar>x\\<bar>\"\nby (transfer, simp)\n\nlemma star_sqrt_HFinite: \"\\<lbrakk>x \\<in> HFinite; 0 \\<le> x\\<rbrakk> \\<Longrightarrow> ( *f* sqrt) x \\<in> HFinite\"\napply (rule HFinite_square_iff [THEN iffD1])\napply (simp only: hypreal_sqrt_mult_distrib2 [symmetric], simp) \ndone\n\nlemma st_hypreal_sqrt:\n     \"[| x \\<in> HFinite; 0 \\<le> x |] ==> st(( *f* sqrt) x) = ( *f* sqrt)(st x)\"\napply (rule power_inject_base [where n=1])\napply (auto intro!: st_zero_le hypreal_sqrt_ge_zero)\napply (rule st_mult [THEN subst])\napply (rule_tac [3] hypreal_sqrt_mult_distrib2 [THEN subst])\napply (rule_tac [5] hypreal_sqrt_mult_distrib2 [THEN subst])\napply (auto simp add: st_hrabs st_zero_le star_sqrt_HFinite)\ndone\n\nlemma hypreal_sqrt_sum_squares_ge1 [simp]: \"!!x y. x \\<le> ( *f* sqrt)(x\\<^sup>2 + y\\<^sup>2)\"\nby transfer (rule real_sqrt_sum_squares_ge1)\n\nlemma HFinite_hypreal_sqrt:\n     \"[| 0 \\<le> x; x \\<in> HFinite |] ==> ( *f* sqrt) x \\<in> HFinite\"\napply (auto simp add: order_le_less)\napply (rule HFinite_square_iff [THEN iffD1])\napply (drule hypreal_sqrt_gt_zero_pow2)\napply (simp add: numeral_2_eq_2)\ndone\n\nlemma HFinite_hypreal_sqrt_imp_HFinite:\n     \"[| 0 \\<le> x; ( *f* sqrt) x \\<in> HFinite |] ==> x \\<in> HFinite\"\napply (auto simp add: order_le_less)\napply (drule HFinite_square_iff [THEN iffD2])\napply (drule hypreal_sqrt_gt_zero_pow2)\napply (simp add: numeral_2_eq_2 del: HFinite_square_iff)\ndone\n\nlemma HFinite_hypreal_sqrt_iff [simp]:\n     \"0 \\<le> x ==> (( *f* sqrt) x \\<in> HFinite) = (x \\<in> HFinite)\"\nby (blast intro: HFinite_hypreal_sqrt HFinite_hypreal_sqrt_imp_HFinite)\n\nlemma HFinite_sqrt_sum_squares [simp]:\n     \"(( *f* sqrt)(x*x + y*y) \\<in> HFinite) = (x*x + y*y \\<in> HFinite)\"\napply (rule HFinite_hypreal_sqrt_iff)\napply (rule add_nonneg_nonneg)\napply (auto)\ndone\n\nlemma Infinitesimal_hypreal_sqrt:\n     \"[| 0 \\<le> x; x \\<in> Infinitesimal |] ==> ( *f* sqrt) x \\<in> Infinitesimal\"\napply (auto simp add: order_le_less)\napply (rule Infinitesimal_square_iff [THEN iffD2])\napply (drule hypreal_sqrt_gt_zero_pow2)\napply (simp add: numeral_2_eq_2)\ndone\n\nlemma Infinitesimal_hypreal_sqrt_imp_Infinitesimal:\n     \"[| 0 \\<le> x; ( *f* sqrt) x \\<in> Infinitesimal |] ==> x \\<in> Infinitesimal\"\napply (auto simp add: order_le_less)\napply (drule Infinitesimal_square_iff [THEN iffD1])\napply (drule hypreal_sqrt_gt_zero_pow2)\napply (simp add: numeral_2_eq_2 del: Infinitesimal_square_iff [symmetric])\ndone\n\nlemma Infinitesimal_hypreal_sqrt_iff [simp]:\n     \"0 \\<le> x ==> (( *f* sqrt) x \\<in> Infinitesimal) = (x \\<in> Infinitesimal)\"\nby (blast intro: Infinitesimal_hypreal_sqrt_imp_Infinitesimal Infinitesimal_hypreal_sqrt)\n\nlemma Infinitesimal_sqrt_sum_squares [simp]:\n     \"(( *f* sqrt)(x*x + y*y) \\<in> Infinitesimal) = (x*x + y*y \\<in> Infinitesimal)\"\napply (rule Infinitesimal_hypreal_sqrt_iff)\napply (rule add_nonneg_nonneg)\napply (auto)\ndone\n\nlemma HInfinite_hypreal_sqrt:\n     \"[| 0 \\<le> x; x \\<in> HInfinite |] ==> ( *f* sqrt) x \\<in> HInfinite\"\napply (auto simp add: order_le_less)\napply (rule HInfinite_square_iff [THEN iffD1])\napply (drule hypreal_sqrt_gt_zero_pow2)\napply (simp add: numeral_2_eq_2)\ndone\n\nlemma HInfinite_hypreal_sqrt_imp_HInfinite:\n     \"[| 0 \\<le> x; ( *f* sqrt) x \\<in> HInfinite |] ==> x \\<in> HInfinite\"\napply (auto simp add: order_le_less)\napply (drule HInfinite_square_iff [THEN iffD2])\napply (drule hypreal_sqrt_gt_zero_pow2)\napply (simp add: numeral_2_eq_2 del: HInfinite_square_iff)\ndone\n\nlemma HInfinite_hypreal_sqrt_iff [simp]:\n     \"0 \\<le> x ==> (( *f* sqrt) x \\<in> HInfinite) = (x \\<in> HInfinite)\"\nby (blast intro: HInfinite_hypreal_sqrt HInfinite_hypreal_sqrt_imp_HInfinite)\n\nlemma HInfinite_sqrt_sum_squares [simp]:\n     \"(( *f* sqrt)(x*x + y*y) \\<in> HInfinite) = (x*x + y*y \\<in> HInfinite)\"\napply (rule HInfinite_hypreal_sqrt_iff)\napply (rule add_nonneg_nonneg)\napply (auto)\ndone\n\nlemma HFinite_exp [simp]:\n     \"sumhr (0, whn, %n. inverse (fact n) * x ^ n) \\<in> HFinite\"\nunfolding sumhr_app\napply (simp only: star_zero_def starfun2_star_of atLeast0LessThan)\napply (rule NSBseqD2)\napply (rule NSconvergent_NSBseq)\napply (rule convergent_NSconvergent_iff [THEN iffD1])\napply (rule summable_iff_convergent [THEN iffD1])\napply (rule summable_exp)\ndone\n\nlemma exphr_zero [simp]: \"exphr 0 = 1\"\napply (simp add: exphr_def sumhr_split_add [OF hypnat_one_less_hypnat_omega, symmetric])\napply (rule st_unique, simp)\napply (rule subst [where P=\"\\<lambda>x. 1 \\<approx> x\", OF _ approx_refl])\napply (rule rev_mp [OF hypnat_one_less_hypnat_omega])\napply (rule_tac x=\"whn\" in spec)\napply (unfold sumhr_app, transfer, simp add: power_0_left)\ndone\n\nlemma coshr_zero [simp]: \"coshr 0 = 1\"\napply (simp add: coshr_def sumhr_split_add\n                   [OF hypnat_one_less_hypnat_omega, symmetric]) \napply (rule st_unique, simp)\napply (rule subst [where P=\"\\<lambda>x. 1 \\<approx> x\", OF _ approx_refl])\napply (rule rev_mp [OF hypnat_one_less_hypnat_omega])\napply (rule_tac x=\"whn\" in spec)\napply (unfold sumhr_app, transfer, simp add: cos_coeff_def power_0_left)\ndone\n\nlemma STAR_exp_zero_approx_one [simp]: \"( *f* exp) (0::hypreal) \\<approx> 1\"\napply (subgoal_tac \"( *f* exp) (0::hypreal) = 1\", simp)\napply (transfer, simp)\ndone\n\nlemma STAR_exp_Infinitesimal: \"x \\<in> Infinitesimal ==> ( *f* exp) (x::hypreal) \\<approx> 1\"\napply (case_tac \"x = 0\")\napply (cut_tac [2] x = 0 in DERIV_exp)\napply (auto simp add: NSDERIV_DERIV_iff [symmetric] nsderiv_def)\napply (drule_tac x = x in bspec, auto)\napply (drule_tac c = x in approx_mult1)\napply (auto intro: Infinitesimal_subset_HFinite [THEN subsetD] \n            simp add: mult.assoc)\napply (rule approx_add_right_cancel [where d=\"-1\"])\napply (rule approx_sym [THEN [2] approx_trans2])\napply (auto simp add: mem_infmal_iff)\ndone\n\nlemma STAR_exp_epsilon [simp]: \"( *f* exp) \\<epsilon> \\<approx> 1\"\nby (auto intro: STAR_exp_Infinitesimal)\n\nlemma STAR_exp_add:\n  \"!!(x::'a:: {banach,real_normed_field} star) y. ( *f* exp)(x + y) = ( *f* exp) x * ( *f* exp) y\"\nby transfer (rule exp_add)\n\nlemma exphr_hypreal_of_real_exp_eq: \"exphr x = hypreal_of_real (exp x)\"\napply (simp add: exphr_def)\napply (rule st_unique, simp)\napply (subst starfunNat_sumr [symmetric])\nunfolding atLeast0LessThan\napply (rule NSLIMSEQ_D [THEN approx_sym])\napply (rule LIMSEQ_NSLIMSEQ)\napply (subst sums_def [symmetric])\napply (cut_tac exp_converges [where x=x], simp)\napply (rule HNatInfinite_whn)\ndone\n\nlemma starfun_exp_ge_add_one_self [simp]: \"!!x::hypreal. 0 \\<le> x ==> (1 + x) \\<le> ( *f* exp) x\"\nby transfer (rule exp_ge_add_one_self_aux)\n\n(* exp (oo) is infinite *)\nlemma starfun_exp_HInfinite:\n     \"[| x \\<in> HInfinite; 0 \\<le> x |] ==> ( *f* exp) (x::hypreal) \\<in> HInfinite\"\napply (frule starfun_exp_ge_add_one_self)\napply (rule HInfinite_ge_HInfinite, assumption)\napply (rule order_trans [of _ \"1+x\"], auto) \ndone\n\nlemma starfun_exp_minus:\n  \"!!x::'a:: {banach,real_normed_field} star. ( *f* exp) (-x) = inverse(( *f* exp) x)\"\nby transfer (rule exp_minus)\n\n(* exp (-oo) is infinitesimal *)\nlemma starfun_exp_Infinitesimal:\n     \"[| x \\<in> HInfinite; x \\<le> 0 |] ==> ( *f* exp) (x::hypreal) \\<in> Infinitesimal\"\napply (subgoal_tac \"\\<exists>y. x = - y\")\napply (rule_tac [2] x = \"- x\" in exI)\napply (auto intro!: HInfinite_inverse_Infinitesimal starfun_exp_HInfinite\n            simp add: starfun_exp_minus HInfinite_minus_iff)\ndone\n\nlemma starfun_exp_gt_one [simp]: \"!!x::hypreal. 0 < x ==> 1 < ( *f* exp) x\"\nby transfer (rule exp_gt_one)\n\nabbreviation real_ln :: \"real \\<Rightarrow> real\" where \n  \"real_ln \\<equiv> ln\"\n\nlemma starfun_ln_exp [simp]: \"!!x. ( *f* real_ln) (( *f* exp) x) = x\"\nby transfer (rule ln_exp)\n\nlemma starfun_exp_ln_iff [simp]: \"!!x. (( *f* exp)(( *f* real_ln) x) = x) = (0 < x)\"\nby transfer (rule exp_ln_iff)\n\nlemma starfun_exp_ln_eq: \"!!u x. ( *f* exp) u = x ==> ( *f* real_ln) x = u\"\nby transfer (rule ln_unique)\n\nlemma starfun_ln_less_self [simp]: \"!!x. 0 < x ==> ( *f* real_ln) x < x\"\nby transfer (rule ln_less_self)\n\nlemma starfun_ln_ge_zero [simp]: \"!!x. 1 \\<le> x ==> 0 \\<le> ( *f* real_ln) x\"\nby transfer (rule ln_ge_zero)\n\nlemma starfun_ln_gt_zero [simp]: \"!!x .1 < x ==> 0 < ( *f* real_ln) x\"\nby transfer (rule ln_gt_zero)\n\nlemma starfun_ln_not_eq_zero [simp]: \"!!x. [| 0 < x; x \\<noteq> 1 |] ==> ( *f* real_ln) x \\<noteq> 0\"\nby transfer simp\n\nlemma starfun_ln_HFinite: \"[| x \\<in> HFinite; 1 \\<le> x |] ==> ( *f* real_ln) x \\<in> HFinite\"\napply (rule HFinite_bounded)\napply assumption \napply (simp_all add: starfun_ln_less_self order_less_imp_le)\ndone\n\nlemma starfun_ln_inverse: \"!!x. 0 < x ==> ( *f* real_ln) (inverse x) = -( *f* ln) x\"\nby transfer (rule ln_inverse)\n\nlemma starfun_abs_exp_cancel: \"\\<And>x. \\<bar>( *f* exp) (x::hypreal)\\<bar> = ( *f* exp) x\"\nby transfer (rule abs_exp_cancel)\n\nlemma starfun_exp_less_mono: \"\\<And>x y::hypreal. x < y \\<Longrightarrow> ( *f* exp) x < ( *f* exp) y\"\nby transfer (rule exp_less_mono)\n\nlemma starfun_exp_HFinite: \"x \\<in> HFinite ==> ( *f* exp) (x::hypreal) \\<in> HFinite\"\napply (auto simp add: HFinite_def, rename_tac u)\napply (rule_tac x=\"( *f* exp) u\" in rev_bexI)\napply (simp add: Reals_eq_Standard)\napply (simp add: starfun_abs_exp_cancel)\napply (simp add: starfun_exp_less_mono)\ndone\n\nlemma starfun_exp_add_HFinite_Infinitesimal_approx:\n     \"[|x \\<in> Infinitesimal; z \\<in> HFinite |] ==> ( *f* exp) (z + x::hypreal) \\<approx> ( *f* exp) z\"\napply (simp add: STAR_exp_add)\napply (frule STAR_exp_Infinitesimal)\napply (drule approx_mult2)\napply (auto intro: starfun_exp_HFinite)\ndone\n\n(* using previous result to get to result *)\nlemma starfun_ln_HInfinite:\n     \"[| x \\<in> HInfinite; 0 < x |] ==> ( *f* real_ln) x \\<in> HInfinite\"\napply (rule ccontr, drule HFinite_HInfinite_iff [THEN iffD2])\napply (drule starfun_exp_HFinite)\napply (simp add: starfun_exp_ln_iff [THEN iffD2] HFinite_HInfinite_iff)\ndone\n\nlemma starfun_exp_HInfinite_Infinitesimal_disj:\n \"x \\<in> HInfinite ==> ( *f* exp) x \\<in> HInfinite | ( *f* exp) (x::hypreal) \\<in> Infinitesimal\"\napply (insert linorder_linear [of x 0]) \napply (auto intro: starfun_exp_HInfinite starfun_exp_Infinitesimal)\ndone\n\n(* check out this proof!!! *)\nlemma starfun_ln_HFinite_not_Infinitesimal:\n     \"[| x \\<in> HFinite - Infinitesimal; 0 < x |] ==> ( *f* real_ln) x \\<in> HFinite\"\napply (rule ccontr, drule HInfinite_HFinite_iff [THEN iffD2])\napply (drule starfun_exp_HInfinite_Infinitesimal_disj)\napply (simp add: starfun_exp_ln_iff [symmetric] HInfinite_HFinite_iff\n            del: starfun_exp_ln_iff)\ndone\n\n(* we do proof by considering ln of 1/x *)\nlemma starfun_ln_Infinitesimal_HInfinite:\n     \"[| x \\<in> Infinitesimal; 0 < x |] ==> ( *f* real_ln) x \\<in> HInfinite\"\napply (drule Infinitesimal_inverse_HInfinite)\napply (frule positive_imp_inverse_positive)\napply (drule_tac [2] starfun_ln_HInfinite)\napply (auto simp add: starfun_ln_inverse HInfinite_minus_iff)\ndone\n\nlemma starfun_ln_less_zero: \"!!x. [| 0 < x; x < 1 |] ==> ( *f* real_ln) x < 0\"\nby transfer (rule ln_less_zero)\n\nlemma starfun_ln_Infinitesimal_less_zero:\n     \"[| x \\<in> Infinitesimal; 0 < x |] ==> ( *f* real_ln) x < 0\"\nby (auto intro!: starfun_ln_less_zero simp add: Infinitesimal_def)\n\nlemma starfun_ln_HInfinite_gt_zero:\n     \"[| x \\<in> HInfinite; 0 < x |] ==> 0 < ( *f* real_ln) x\"\nby (auto intro!: starfun_ln_gt_zero simp add: HInfinite_def)\n\n\n(*\nGoalw [NSLIM_def] \"(%h. ((x powr h) - 1) / h) \\<midarrow>0\\<rightarrow>\\<^sub>N\\<^sub>S ln x\"\n*)\n\nlemma HFinite_sin [simp]: \"sumhr (0, whn, %n. sin_coeff n * x ^ n) \\<in> HFinite\"\nunfolding sumhr_app\napply (simp only: star_zero_def starfun2_star_of atLeast0LessThan)\napply (rule NSBseqD2)\napply (rule NSconvergent_NSBseq)\napply (rule convergent_NSconvergent_iff [THEN iffD1])\napply (rule summable_iff_convergent [THEN iffD1])\nusing summable_norm_sin [of x]\napply (simp add: summable_rabs_cancel)\ndone\n\nlemma STAR_sin_zero [simp]: \"( *f* sin) 0 = 0\"\nby transfer (rule sin_zero)\n\nlemma STAR_sin_Infinitesimal [simp]:\n  fixes x :: \"'a::{real_normed_field,banach} star\"\n  shows \"x \\<in> Infinitesimal ==> ( *f* sin) x \\<approx> x\"\napply (case_tac \"x = 0\")\napply (cut_tac [2] x = 0 in DERIV_sin)\napply (auto simp add: NSDERIV_DERIV_iff [symmetric] nsderiv_def)\napply (drule bspec [where x = x], auto)\napply (drule approx_mult1 [where c = x])\napply (auto intro: Infinitesimal_subset_HFinite [THEN subsetD]\n           simp add: mult.assoc)\ndone\n\nlemma HFinite_cos [simp]: \"sumhr (0, whn, %n. cos_coeff n * x ^ n) \\<in> HFinite\"\nunfolding sumhr_app\napply (simp only: star_zero_def starfun2_star_of atLeast0LessThan)\napply (rule NSBseqD2)\napply (rule NSconvergent_NSBseq)\napply (rule convergent_NSconvergent_iff [THEN iffD1])\napply (rule summable_iff_convergent [THEN iffD1])\nusing summable_norm_cos [of x]\napply (simp add: summable_rabs_cancel)\ndone\n\nlemma STAR_cos_zero [simp]: \"( *f* cos) 0 = 1\"\nby transfer (rule cos_zero)\n\nlemma STAR_cos_Infinitesimal [simp]:\n  fixes x :: \"'a::{real_normed_field,banach} star\"\n  shows \"x \\<in> Infinitesimal ==> ( *f* cos) x \\<approx> 1\"\napply (case_tac \"x = 0\")\napply (cut_tac [2] x = 0 in DERIV_cos)\napply (auto simp add: NSDERIV_DERIV_iff [symmetric] nsderiv_def)\napply (drule bspec [where x = x])\napply auto\napply (drule approx_mult1 [where c = x])\napply (auto intro: Infinitesimal_subset_HFinite [THEN subsetD]\n            simp add: mult.assoc)\napply (rule approx_add_right_cancel [where d = \"-1\"])\napply simp\ndone\n\nlemma STAR_tan_zero [simp]: \"( *f* tan) 0 = 0\"\nby transfer (rule tan_zero)\n\nlemma STAR_tan_Infinitesimal: \"x \\<in> Infinitesimal ==> ( *f* tan) x \\<approx> x\"\napply (case_tac \"x = 0\")\napply (cut_tac [2] x = 0 in DERIV_tan)\napply (auto simp add: NSDERIV_DERIV_iff [symmetric] nsderiv_def)\napply (drule bspec [where x = x], auto)\napply (drule approx_mult1 [where c = x])\napply (auto intro: Infinitesimal_subset_HFinite [THEN subsetD]\n             simp add: mult.assoc)\ndone\n\nlemma STAR_sin_cos_Infinitesimal_mult:\n  fixes x :: \"'a::{real_normed_field,banach} star\"\n  shows \"x \\<in> Infinitesimal ==> ( *f* sin) x * ( *f* cos) x \\<approx> x\"\nusing approx_mult_HFinite [of \"( *f* sin) x\" _ \"( *f* cos) x\" 1] \nby (simp add: Infinitesimal_subset_HFinite [THEN subsetD])\n\nlemma HFinite_pi: \"hypreal_of_real pi \\<in> HFinite\"\nby simp\n\n(* lemmas *)\n\nlemma lemma_split_hypreal_of_real:\n     \"N \\<in> HNatInfinite  \n      ==> hypreal_of_real a =  \n          hypreal_of_hypnat N * (inverse(hypreal_of_hypnat N) * hypreal_of_real a)\"\nby (simp add: mult.assoc [symmetric] zero_less_HNatInfinite)\n\nlemma STAR_sin_Infinitesimal_divide:\n  fixes x :: \"'a::{real_normed_field,banach} star\"\n  shows \"[|x \\<in> Infinitesimal; x \\<noteq> 0 |] ==> ( *f* sin) x/x \\<approx> 1\"\nusing DERIV_sin [of \"0::'a\"]\nby (simp add: NSDERIV_DERIV_iff [symmetric] nsderiv_def)\n\n(*------------------------------------------------------------------------*) \n(* sin* (1/n) * 1/(1/n) \\<approx> 1 for n = oo                                   *)\n(*------------------------------------------------------------------------*)\n\nlemma lemma_sin_pi:\n     \"n \\<in> HNatInfinite  \n      ==> ( *f* sin) (inverse (hypreal_of_hypnat n))/(inverse (hypreal_of_hypnat n)) \\<approx> 1\"\napply (rule STAR_sin_Infinitesimal_divide)\napply (auto simp add: zero_less_HNatInfinite)\ndone\n\nlemma STAR_sin_inverse_HNatInfinite:\n     \"n \\<in> HNatInfinite  \n      ==> ( *f* sin) (inverse (hypreal_of_hypnat n)) * hypreal_of_hypnat n \\<approx> 1\"\napply (frule lemma_sin_pi)\napply (simp add: divide_inverse)\ndone\n\nlemma Infinitesimal_pi_divide_HNatInfinite: \n     \"N \\<in> HNatInfinite  \n      ==> hypreal_of_real pi/(hypreal_of_hypnat N) \\<in> Infinitesimal\"\napply (simp add: divide_inverse)\napply (auto intro: Infinitesimal_HFinite_mult2)\ndone\n\nlemma pi_divide_HNatInfinite_not_zero [simp]:\n     \"N \\<in> HNatInfinite ==> hypreal_of_real pi/(hypreal_of_hypnat N) \\<noteq> 0\"\nby (simp add: zero_less_HNatInfinite)\n\nlemma STAR_sin_pi_divide_HNatInfinite_approx_pi:\n     \"n \\<in> HNatInfinite  \n      ==> ( *f* sin) (hypreal_of_real pi/(hypreal_of_hypnat n)) * hypreal_of_hypnat n  \n          \\<approx> hypreal_of_real pi\"\napply (frule STAR_sin_Infinitesimal_divide\n               [OF Infinitesimal_pi_divide_HNatInfinite \n                   pi_divide_HNatInfinite_not_zero])\napply (auto)\napply (rule approx_SReal_mult_cancel [of \"inverse (hypreal_of_real pi)\"])\napply (auto intro: Reals_inverse simp add: divide_inverse ac_simps)\ndone\n\nlemma STAR_sin_pi_divide_HNatInfinite_approx_pi2:\n     \"n \\<in> HNatInfinite  \n      ==> hypreal_of_hypnat n *  \n          ( *f* sin) (hypreal_of_real pi/(hypreal_of_hypnat n))  \n          \\<approx> hypreal_of_real pi\"\napply (rule mult.commute [THEN subst])\napply (erule STAR_sin_pi_divide_HNatInfinite_approx_pi)\ndone\n\nlemma starfunNat_pi_divide_n_Infinitesimal: \n     \"N \\<in> HNatInfinite ==> ( *f* (%x. pi / real x)) N \\<in> Infinitesimal\"\nby (auto intro!: Infinitesimal_HFinite_mult2 \n         simp add: starfun_mult [symmetric] divide_inverse\n                   starfun_inverse [symmetric] starfunNat_real_of_nat)\n\nlemma STAR_sin_pi_divide_n_approx:\n     \"N \\<in> HNatInfinite ==>  \n      ( *f* sin) (( *f* (%x. pi / real x)) N) \\<approx>  \n      hypreal_of_real pi/(hypreal_of_hypnat N)\"\napply (simp add: starfunNat_real_of_nat [symmetric])\napply (rule STAR_sin_Infinitesimal)\napply (simp add: divide_inverse)\napply (rule Infinitesimal_HFinite_mult2)\napply (subst starfun_inverse)\napply (erule starfunNat_inverse_real_of_nat_Infinitesimal)\napply simp\ndone\n\nlemma NSLIMSEQ_sin_pi: \"(%n. real n * sin (pi / real n)) \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S pi\"\napply (auto simp add: NSLIMSEQ_def starfun_mult [symmetric] starfunNat_real_of_nat)\napply (rule_tac f1 = sin in starfun_o2 [THEN subst])\napply (auto simp add: starfun_mult [symmetric] starfunNat_real_of_nat divide_inverse)\napply (rule_tac f1 = inverse in starfun_o2 [THEN subst])\napply (auto dest: STAR_sin_pi_divide_HNatInfinite_approx_pi \n            simp add: starfunNat_real_of_nat mult.commute divide_inverse)\ndone\n\nlemma NSLIMSEQ_cos_one: \"(%n. cos (pi / real n))\\<longlonglongrightarrow>\\<^sub>N\\<^sub>S 1\"\napply (simp add: NSLIMSEQ_def, auto)\napply (rule_tac f1 = cos in starfun_o2 [THEN subst])\napply (rule STAR_cos_Infinitesimal)\napply (auto intro!: Infinitesimal_HFinite_mult2 \n            simp add: starfun_mult [symmetric] divide_inverse\n                      starfun_inverse [symmetric] starfunNat_real_of_nat)\ndone\n\nlemma NSLIMSEQ_sin_cos_pi:\n     \"(%n. real n * sin (pi / real n) * cos (pi / real n)) \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S pi\"\nby (insert NSLIMSEQ_mult [OF NSLIMSEQ_sin_pi NSLIMSEQ_cos_one], simp)\n\n\ntext\\<open>A familiar approximation to @{term \"cos x\"} when @{term x} is small\\<close>\n\nlemma STAR_cos_Infinitesimal_approx:\n  fixes x :: \"'a::{real_normed_field,banach} star\"\n  shows \"x \\<in> Infinitesimal ==> ( *f* cos) x \\<approx> 1 - x\\<^sup>2\"\napply (rule STAR_cos_Infinitesimal [THEN approx_trans])\napply (auto simp add: Infinitesimal_approx_minus [symmetric] \n            add.assoc [symmetric] numeral_2_eq_2)\ndone\n\nlemma STAR_cos_Infinitesimal_approx2:\n  fixes x :: hypreal  \\<comment>\\<open>perhaps could be generalised, like many other hypreal results\\<close>\n  shows \"x \\<in> Infinitesimal ==> ( *f* cos) x \\<approx> 1 - (x\\<^sup>2)/2\"\napply (rule STAR_cos_Infinitesimal [THEN approx_trans])\napply (auto intro: Infinitesimal_SReal_divide Infinitesimal_mult\n            simp add: Infinitesimal_approx_minus [symmetric] numeral_2_eq_2)\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/Nonstandard_Analysis/HTranscendental.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045877523147, "lm_q2_score": 0.8289388125473629, "lm_q1q2_score": 0.7354383174579764}}
{"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          Pi_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": "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/Skip_List.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8652240756264638, "lm_q2_score": 0.8499711775577736, "lm_q1q2_score": 0.7354155264115616}}
{"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 RelationFoundation\nimports Main HOL.Real\n\nbegin\n\ndeclare [[smt_timeout = 60]]\n\nchapter {* chapter 6. Relation *}\n\nsection {* section 6.1: relation and its properties *}\n\nsubsection {* definition 6.1 *}\n\ntype_synonym ('a, 'b) Relation = \"('a \\<times> 'b) set\"\n\ntype_synonym Nat_Relation = \"(nat \\<times> nat) set\"\n\nconsts Rel_A :: \"('a, 'b) Relation\"\n\nlemma \"{x::'a. True} = UNIV\" by auto\nlemma \"{x::'b. True} = UNIV\" by auto\nlemma \"Rel_A \\<subseteq> UNIV \\<times> UNIV\" by auto\n\nlemma \"\\<forall>x y. (x,y) \\<in> Rel_A \\<or> (x,y) \\<notin> Rel_A\" \n  by auto\n\nsubsection {* example 6.1 *}\n\ndatatype Teacher = x1 | y1 | z1\ndatatype Student = a1 | b1 | c1 | d1\n\ndefinition \"T_S \\<equiv> {(x1,a1), (x1,b1), (y1,b1), (z1,b1), (z1,d1)}\"\n  \ndefinition real_lg :: \"(real,real) Relation\"\n  where \"real_lg \\<equiv> {(x,y). x > y}\"\n\ndefinition real_S :: \"(real,real) Relation\"\n  where \"real_S \\<equiv> {(x,y). y = x\\<^sup>2}\"\n\nsubsection {* predicate representation of relation *}\n\ndefinition Rel :: \"('a \\<Rightarrow> 'b \\<Rightarrow> bool) \\<Rightarrow> ('a, 'b) Relation\"\n  where \"Rel P \\<equiv> {(x,y). P x y}\"\n\nlemma \"\\<forall>x y. P x y \\<longleftrightarrow> (x,y)\\<in>Rel P\" \n  by (simp add:Rel_def)\n\nsubsection {* definition 6.2 *}\n\nthm DomainI\nlemma \"Domain R = {x. \\<exists>y. (x,y)\\<in>R}\"\n  unfolding Domain_def by auto\n\nthm RangeI \nlemma \"Range R = {y. \\<exists>x. (x,y)\\<in>R}\"\n  unfolding Range_def by auto\n\nlemma \"Domain Rel_A \\<subseteq> {x::'a. True}\" by auto\nlemma \"Range Rel_A \\<subseteq> {x::'b. True}\" by auto\n\ndefinition \"U_x X \\<equiv> {(x, y). x\\<in>X \\<and> y\\<in>X}\"\n\ndefinition \"I_x X \\<equiv> {(x, y). x\\<in>X \\<and> y\\<in>X \\<and> x = y}\"\n\nsubsection {* example 6.2 *}\n\nvalue \"U_x {0::int,1,2}\" \n\n(* value \"I_x {0::int,1,2}\" *)\nlemma \"I_x {0::int,1,2} = {(0,0),(1,1),(2,2)}\"\n  unfolding I_x_def by force\n\nsubsection {* definition 6.3 *}\n\nthm reflp_def\n\nthm irreflp_def\n\nthm symp_def\n\nthm antisym_def\n\nthm transp_def\n\nthm Id_def\n\nsubsection {* example 6.5 *}\n\nthm Relation.refl_Id\n\nlemma \"\\<not> (irrefl Id)\"\n  by (simp add: irrefl_def)  \n\nthm Relation.sym_Id\n\nthm Relation.antisym_Id\n\nthm Relation.trans_Id\n\ndefinition int_less_eq :: \"(int,int) Relation\"\n  where \"int_less_eq \\<equiv> {(x,y). x \\<le> y}\"\n\nlemma \"refl int_less_eq\" \n  by (simp add:int_less_eq_def refl_on_def)\n\nlemma \"\\<not>(irrefl int_less_eq)\"\n  by (simp add:int_less_eq_def irrefl_def)\n\nlemma \"antisym int_less_eq\"\n  by (simp add:int_less_eq_def antisym_def)\n\nlemma \"\\<not> (sym int_less_eq)\" \n  unfolding int_less_eq_def sym_def \n    proof -\n      have \"(0::int) < (1::int)\" by auto \n      have \"(0::int, 1::int) \\<in> {(x, y). x \\<le> y}\" by auto\n      moreover\n      have \"(1::int, 0::int) \\<notin> {(x, y). x \\<le> y}\" by auto\n      ultimately have \"\\<exists>(x::int) (y::int). (x, y) \\<in> {(x, y). x \\<le> y} \\<and> (y, x) \\<notin> {(x, y). x \\<le> y}\" \n        by blast\n      then show \"\\<not> (\\<forall>(x::int) (y::int). (x, y) \\<in> {(x, y). x \\<le> y} \\<longrightarrow> (y, x) \\<in> {(x, y). x \\<le> y})\" \n        by auto\n    qed\n\nlemma \"trans int_less_eq\" \n  by (simp add:int_less_eq_def trans_def)\n\ndefinition int_less :: \"(int,int) Relation\"\n  where \"int_less \\<equiv> {(x,y). x < y}\"\n\nlemma \"irrefl int_less\" \n  by (simp add:int_less_def irrefl_def)\n\nlemma \"\\<not> (refl int_less)\"\n  by (simp add:int_less_def refl_on_def)\n\nlemma \"antisym int_less\"\n  by (simp add:int_less_def antisym_def)\n\nlemma \"\\<not> (sym int_less)\" \n  unfolding int_less_def sym_def \n    proof -\n      have \"(0::int) < (1::int)\" by auto \n      have \"(0::int, 1::int) \\<in> {(x, y). x < y}\" by auto\n      moreover\n      have \"(1::int, 0::int) \\<notin> {(x, y). x < y}\" by auto\n      ultimately have \"\\<exists>(x::int) (y::int). (x, y) \\<in> {(x, y). x < y} \\<and> (y, x) \\<notin> {(x, y). x < y}\" \n        by blast\n      then show \"\\<not> (\\<forall>(x::int) (y::int). (x, y) \\<in> {(x, y). x < y} \\<longrightarrow> (y, x) \\<in> {(x, y). x < y})\" \n        by auto\n    qed\n\nlemma \"trans int_less\" \n  by (simp add:int_less_def trans_def)\n\nsection {* section 6.2: relation operation*}\n\nsubsection {* definition 6.4 *}\n\nlemma \"(x,y)\\<in>(R \\<inter> S) = ((x,y)\\<in>R \\<and> (x,y)\\<in>S)\"\n  by auto\n\nlemma \"(x,y)\\<in>(R \\<union> S) = ((x,y)\\<in>R \\<or> (x,y)\\<in>S)\"\n  by auto\n\nlemma \"(x,y)\\<in>(R - S) = ((x,y)\\<in>R \\<and> \\<not> (x,y)\\<in>S)\"\n  by auto\n\nlemma \"(x,y)\\<in>(- R) = (\\<not> (x,y)\\<in>R)\"\n  by auto\n\nsubsection {* example 6.6 *}\n\ndefinition R1 :: \"(int,int) Relation\"\n  where \"R1 \\<equiv> {(1,3),(3,1),(2,4),(4,2)}\"\n\ndefinition S1 :: \"(int,int) Relation\"\n  where \"S1 \\<equiv> {(1,4),(4,1)}\"\n\nvalue \"R1 \\<union> S1\"\n\nvalue \"R1 \\<inter> S1\"\n\nvalue \"R1 - S1\"\n\nvalue \"{1,2,3,4}\\<times>{1,2,3,4} - R1\"\n\nsubsection {* definition 6.5 *}\n\nthm Relation.relcomp_unfold\n\nsubsection {* theorem 6.1 *}\n\nthm Relation.O_assoc\n\nlemma \"(R O S) O P = R O (S O P)\"\n  proof -\n    have \"\\<forall>x w. (x,w)\\<in>(R O S) O P \\<longleftrightarrow> (\\<exists>z. (x,z)\\<in> R O S \\<and> (z,w)\\<in>P)\" by auto\n    then have \"\\<forall>x w. (x,w)\\<in>(R O S) O P \\<longleftrightarrow> (\\<exists>z y. (x,y)\\<in> R \\<and> (y,z)\\<in>S \\<and> (z,w)\\<in>P)\" by auto\n    then have \"\\<forall>x w. (x,w)\\<in>(R O S) O P \\<longleftrightarrow> (\\<exists>y. (x,y)\\<in> R \\<and> (\\<exists>z. (y,z)\\<in>S \\<and> (z,w)\\<in>P))\" by auto\n    then have \"\\<forall>x w. (x,w)\\<in>(R O S) O P \\<longleftrightarrow> (\\<exists>y. (x,y)\\<in> R \\<and> (y,w)\\<in>S O P)\" by auto\n    then have \"\\<forall>x w. (x,w)\\<in>(R O S) O P \\<longleftrightarrow> (x,w)\\<in>R O (S O P)\" by auto\n    then show ?thesis by auto\n  qed\n\nsubsection {* example 6.7 *}\n\ndefinition R2 :: \"(int,int) Relation\"\n  where \"R2 \\<equiv> {(1,2),(3,4),(2,2)}\"\n\ndefinition S2 :: \"(int,int) Relation\"\n  where \"S2 \\<equiv> {(4,2),(2,5),(3,1),(1,3)}\"\n\nvalue \"R2 O S2\"\nvalue \"S2 O R2\"\nvalue \"(R2 O S2) O R2\"\nvalue \"R2 O ( S2 O R2)\"\nvalue \"R2 O R2\"\nvalue \"S2 O S2\"\nvalue \"R2 O R2 O R2\"\n\nsubsection {* example 6.8 *}\n\ndefinition R3 :: \"(int,int) Relation\"\n  where \"R3 \\<equiv> {(x, y). y = 2 * x}\"\n\ndefinition S3 :: \"(int,int) Relation\"\n  where \"S3 \\<equiv> {(x, y). y = 7 * x}\"\n\nlemma \"R3 O S3 = {(x,y). y = 14 * x}\" \n  proof -\n    have \"\\<forall>x y. (x,y)\\<in>R3 O S3 \\<longleftrightarrow> (\\<exists>z. (x,z)\\<in>R3 \\<and> (z,y)\\<in>S3)\" by auto\n    then have \"\\<forall>x y. (x,y)\\<in>R3 O S3 \\<longleftrightarrow> (x,2*x)\\<in>R3 \\<and> (2*x,y)\\<in>S3\" \n      by (simp add: R3_def S3_def) \n    then have \"\\<forall>x y. (x,y)\\<in>R3 O S3 \\<longleftrightarrow> y = 14 * x\" \n      by (simp add: R3_def S3_def) \n    then show ?thesis by auto\n  qed\n\nlemma R3_lm1: \"R3 O R3 = {(x,y). y = 4 * x}\" apply(simp add:R3_def) by auto\n(* please prove it by youself *)\n\nlemma \"R3 O R3 O R3 = {(x,y). y = 8 * x}\" using R3_lm1 by(simp add:R3_def, auto)\n\nlemma \"R3 O S3 O R3 = {(x,y). y = 28 * x}\" \napply(rule subst[where t=\"S3 O R3\" and s = \"{(x,y). y = 14 * x}\"]) \napply(simp add:R3_def S3_def) apply auto[1]\nby(simp add:R3_def,auto)\n\nsubsection {* definition 6.6 *}\n\nprimrec R_n :: \"('a, 'a) Relation \\<Rightarrow> nat \\<Rightarrow> ('a, 'a) Relation\" (\"_\\<^sup>_\" [81] 80)\n  where R_n_zero: \"R\\<^sup>0 = Id\" |\n        R_n_suc: \"R_n R (Suc n) = R O (R\\<^sup>n)\"\n\nlemma R_m_n : \"\\<forall>R m n. R\\<^sup>m O R\\<^sup>n = R_n R (m+n)\"\n  proof -\n  {\n    fix R m\n    have \"\\<forall>n. R\\<^sup>m O R\\<^sup>n = R_n R (m+n)\"\n      proof(induct m)\n        case 0\n        show ?case by simp\n      next\n        case (Suc k)\n        assume p: \"\\<forall>n. R\\<^sup>k O R\\<^sup>n = R_n R (k + n)\"\n        show ?case \n          proof\n            fix n\n            have \"R_n R (Suc k) O R\\<^sup>n = R O (R_n R k) O R\\<^sup>n\" \n              using R_n_suc by auto\n            with p have \"R_n R (Suc k) O R\\<^sup>n = R O (R_n R (k+n))\" by auto\n            then show \"R_n R (Suc k) O R\\<^sup>n = R_n R (Suc k + n)\" using R_n_suc by auto\n          qed\n      qed\n  }\n  then show ?thesis by blast\n  qed\n\nlemma \"(R\\<^sup>m)\\<^sup>n = R_n R (m*n)\" sorry\n(* please prove it by youself *)\n\nsubsection {* definition 6.7 *}\n\nthm Relation.converse_unfold\n\nlemma \"(R\\<inverse>)\\<inverse> = R\"\n  using Relation.converse_converse by simp\n\nsubsection {* theorem 6.2 *}\n\nthm Relation.converse_relcomp\n\nlemma \"(R O S)\\<inverse> = S\\<inverse> O R\\<inverse>\" \n  proof -\n    have \"\\<forall>x y. (x,y)\\<in>(R O S)\\<inverse> \\<longleftrightarrow> (y,x)\\<in>(R O S)\" by auto\n    then have \"\\<forall>x y. (x,y)\\<in>(R O S)\\<inverse> \\<longleftrightarrow> (\\<exists>z. (y,z)\\<in>R \\<and> (z,x)\\<in>S)\" by auto\n    then have \"\\<forall>x y. (x,y)\\<in>(R O S)\\<inverse> \\<longleftrightarrow> (\\<exists>z. (z,y)\\<in>R\\<inverse> \\<and> (x,z)\\<in>S\\<inverse>)\" by auto\n    then have \"\\<forall>x y. (x,y)\\<in>(R O S)\\<inverse> \\<longleftrightarrow> (x,y)\\<in>S\\<inverse> O R\\<inverse>\" by auto\n    then show ?thesis by auto\n  qed\n\nsubsection {* definition 6.8 *}\n\n(* reflexive closure*)\ninductive_set reflcl :: \"('a \\<times> 'a) set \\<Rightarrow> ('a \\<times> 'a) set\"  (\"(r(_))\" [1000] 999)\n  for R :: \"('a \\<times> 'a) set\"\nwhere\n  R_reflcl:      \"(a, b) \\<in> R \\<Longrightarrow> (a, b) \\<in> r(R)\"\n| R_into_reflcl: \"(a, a) \\<in> r(R)\"\n\n(* transitive closure*)\ninductive_set trancl :: \"('a \\<times> 'a) set \\<Rightarrow> ('a \\<times> 'a) set\"  (\"(t(_))\" [1000] 999)\n  for R :: \"('a \\<times> 'a) set\"\nwhere\n  R_into_trancl: \"(a, b) \\<in> R \\<Longrightarrow> (a, b) \\<in> t(R)\"\n| R_trancl:      \"(a, b) \\<in> t(R) \\<Longrightarrow> (b, c) \\<in> R \\<Longrightarrow> (a, c) \\<in> t(R)\" \n  (* R_trancl: \"(a, b) \\<in> R \\<Longrightarrow> (b, c) \\<in> t(R) \\<Longrightarrow> (a, c) \\<in> t(R)\" *)\n\n(* symmetric closure*)\ninductive_set symcl :: \"('a \\<times> 'a) set \\<Rightarrow> ('a \\<times> 'a) set\"  (\"(s(_))\" [1000] 999)\n  for R :: \"('a \\<times> 'a) set\"\nwhere\n  R_symcl:      \"(a, b) \\<in> R \\<Longrightarrow> (a, b) \\<in> s(R)\"\n| R_into_symcl: \"(a, b) \\<in> R \\<Longrightarrow> (b, a) \\<in> s(R)\"\n\n(* the set R is contained in r(R) *)\nlemma reflcl_cl: \"R \\<subseteq> r(R)\" \n  using R_reflcl subrelI by fastforce \n\n(* the set R is contained in t(R) *)\nlemma trancl_cl: \"R \\<subseteq> t(R)\" \n  using R_trancl by (simp add: subrelI trancl.R_into_trancl)  \n\n(* the set R is contained in s(R) *)\nlemma symcl_cl: \"R \\<subseteq> s(R)\"\n   using R_symcl subrelI by fastforce \n\n(* reflexive closure is reflexive*)\nlemma \"refl (r(R))\"\n  using R_into_reflcl reflp_def reflp_refl_eq by force \n\n(* symmetric closure is symmetric*)\nlemma \"sym (s(R))\"\n  using R_into_symcl R_symcl\n    by (simp add: sym_def symcl.simps)  \n\n(* transitive closure is transitive*)\nlemma \"trans (t(R))\"\n   sorry\n(* please prove it on paper by youself *)\n\nlemma \"refl R \\<Longrightarrow> r(R) = R\"\n  proof -\n    assume p: \"refl R\"\n    have \"R \\<subseteq> r(R)\" using reflcl_cl by auto\n    moreover\n    have \"r(R) \\<subseteq> R\"\n      proof -\n        {\n          fix a b\n          assume a0: \"(a, b)\\<in>r(R)\"\n          then have \"(a, b)\\<in>R\" \n            apply(rule reflcl.cases) \n            apply simp\n            by (meson UNIV_I p refl_onD)\n        }\n        then have \"\\<forall>z. z\\<in>r(R) \\<longrightarrow> z\\<in>R\" by auto\n        then show ?thesis by auto\n      qed\n    ultimately show ?thesis by auto\n  qed\n   \n\nlemma \"sym R \\<Longrightarrow> s(R) = R\"\n  proof -\n    assume p: \"sym R\"\n    have \"R \\<subseteq> s(R)\" using symcl_cl by auto\n    moreover\n    have \"s(R) \\<subseteq> R\"\n      proof -\n        {\n          fix a b\n          assume a0: \"(a, b)\\<in>s(R)\"\n          then have \"(a, b)\\<in>R\" \n            apply(rule symcl.cases)\n            apply simp\n            by (meson p symE)\n        }\n        then have \"\\<forall>z. z\\<in>s(R) \\<longrightarrow> z\\<in>R\" by auto\n        then show ?thesis by auto\n      qed\n    ultimately show ?thesis by auto\n  qed\n\nlemma \"trans R \\<Longrightarrow> t(R) = R\" sorry\n(* please prove it on paper by youself *)\n\n\nlemma \"\\<lbrakk>R \\<subseteq> S; refl S\\<rbrakk> \\<Longrightarrow> r(R) \\<subseteq> S\"\n  (* by (metis UNIV_I refl_on_def reflcl.simps subrelI subsetCE) *)\n  proof -\n    assume p1: \"R \\<subseteq> S\"\n      and  p2: \"refl S\"\n    {\n      fix a b\n      assume \"(a,b)\\<in>r(R)\"\n      then have \"(a,b)\\<in>S\"\n        apply(rule reflcl.cases)\n        using p1 apply blast\n        using p2 by (meson UNIV_I refl_onD)       \n        \n    }\n    then show \"r(R) \\<subseteq> S\" by auto\n  qed\n\nlemma \"\\<lbrakk>R \\<subseteq> S; sym S\\<rbrakk> \\<Longrightarrow> s(R) \\<subseteq> S\"\n  (* by (meson subrelI subsetCE symE symcl.cases) *)\n  proof -\n    assume p1: \"R \\<subseteq> S\"\n      and  p2: \"sym S\"\n    {\n      fix a b\n      assume \"(a,b)\\<in>s(R)\"\n      then have \"(a,b)\\<in>S\"\n        apply(rule symcl.cases)\n        using p1 apply auto[1]\n        using p1 p2 by (meson subsetCE symE)\n    }\n    then show \"s(R) \\<subseteq> S\" by auto\n  qed\n\nlemma tR_trans_S: \"\\<lbrakk>R \\<subseteq> S; trans S\\<rbrakk> \\<Longrightarrow> t(R) \\<subseteq> S\" sorry\n(* please prove it on paper by youself *)\n(*\n  proof -\n    assume p1: \"R \\<subseteq> S\"\n      and  p2: \"trans S\"\n    {\n      fix a b\n      assume \"(a,b)\\<in>t(R)\"\n      then have \"(a,b)\\<in>S\"\n        apply(rule trancl.cases)\n        using p1 apply auto[1]\n        \n        using p1 p2 apply (meson subsetCE symE)\n        using p1 by auto\n    }\n    then show \"s(R) \\<subseteq> S\" by auto\n  qed\n*)\n\nsubsection {* theorem 6.3 *}\n\nlemma \"r(R) = R \\<union> Id\" \n  proof -\n    have \"\\<forall>x. x\\<in>r(R) \\<longrightarrow> x\\<in>(R \\<union> Id)\"\n      proof -\n      {\n        fix x\n        assume p0: \"x\\<in>r(R)\"\n        then obtain a and b where a1: \"x = (a,b)\"\n          by fastforce \n        have \"x\\<in>(R \\<union> Id)\"\n          apply(rule reflcl.cases)\n          using p0 a1 by simp+\n      }\n      then show ?thesis by auto\n      qed\n    moreover\n    have \"\\<forall>x. x\\<in>(R \\<union> Id) \\<longrightarrow> x\\<in>r(R)\"\n      proof -\n      {\n        fix x\n        assume p0: \"x\\<in>(R \\<union> Id)\"\n        then obtain a and b where a1: \"x = (a,b)\"\n          by fastforce \n        from p0 have \"x\\<in>r(R)\"\n          proof \n            assume \"x\\<in>R\"\n            then show \"x\\<in>r(R)\" using R_reflcl a1 by auto\n          next\n            assume \"x:Id\"\n            then show \"x\\<in>r(R)\" using R_into_reflcl a1 by auto\n          qed\n       }\n      then show ?thesis by auto\n      qed\n    ultimately show ?thesis by auto\n  qed\n\nthm sym_conv_converse_eq\n\nlemma \"sym R = (R = R\\<inverse>)\"\n  proof - \n    {\n      assume p: \"sym R\"\n      then have \"\\<forall>x y. (x,y)\\<in>R \\<longleftrightarrow> (y,x)\\<in>R\"\n        by (meson symE)\n      then have \"\\<forall>x y. (x,y)\\<in>R \\<longleftrightarrow> (x,y)\\<in>R\\<inverse>\" by simp\n      then have \"R = R\\<inverse>\" by auto\n    }\n    moreover\n    {\n      assume \"R = R\\<inverse>\"\n      then have \"\\<forall>x y. (x,y)\\<in>R \\<longleftrightarrow> (x,y)\\<in>R\\<inverse>\" by auto\n      then have \"\\<forall>x y. (x,y)\\<in>R \\<longrightarrow> (y,x)\\<in>R\" by simp\n      then have \"sym R\" by (simp add:sym_def)\n    }\n    ultimately show ?thesis by auto\n  qed\n\nsubsubsection {* theorem 6.4 *}\n\nlemma \"s(R) = R \\<union> R\\<inverse>\" \n  proof -\n    have \"\\<forall>x\\<in>s(R). x\\<in>R \\<union> R\\<inverse>\"\n      proof\n        fix x\n        assume p: \"x\\<in>s(R)\"\n        then obtain a and b where a1: \"x=(a,b)\" by fastforce\n        show \"x\\<in>R \\<union> R\\<inverse>\"\n          apply(rule symcl.cases)\n          using p a1 by simp+\n      qed\n    moreover\n    have \"\\<forall>x\\<in>R \\<union> R\\<inverse>. x\\<in>s(R)\"\n      proof\n        fix x\n        assume p: \"x\\<in>R \\<union> R\\<inverse>\"\n        then obtain a and b where a1: \"x=(a,b)\" by fastforce\n        from p show \"x\\<in>s(R)\"\n          proof\n            assume \"x\\<in>R\"\n            then show \"x\\<in>s(R)\" using R_symcl a1 by auto\n          next\n            assume \"x\\<in>R\\<inverse>\"\n            then show \"x\\<in>s(R)\" using R_into_symcl a1 by auto\n          qed\n      qed\n    ultimately show ?thesis by auto\n  qed\n\nsubsubsection {* theorem 6.5 *}\n\n(* declare [[ show_types = true ]] *)\n\nlemma U_R_trans: \"trans (\\<Union>n\\<in>{0<..}. R\\<^sup>n)\"\n  proof -\n  {\n    fix x y z\n    let ?U = \"\\<Union>n\\<in>{0<..}. R\\<^sup>n\"\n    assume a1: \"(x,y)\\<in>?U\"\n      and  a2: \"(y,z)\\<in>?U\"\n    from a1 have \"\\<exists>m>0. (x,y)\\<in>R\\<^sup>m\"\n      by blast\n    then obtain m where a3: \"m > 0 \\<and> (x,y)\\<in>R\\<^sup>m\" by auto\n    \n    from a2 have \"\\<exists>k>0. ((y,z)\\<in>R\\<^sup>k)\" by blast\n    then obtain k where a4: \"k > 0 \\<and> (y,z)\\<in>R\\<^sup>k\" by auto\n\n    from a3 a4 have \"(x,z)\\<in>R_n R (m+k)\" \n      using R_m_n relcomp.relcompI by fastforce \n    with a3 a4 have \"(x,z)\\<in>?U\" by blast\n  }\n  then show ?thesis by (meson transI)\n  qed\n\nlemma \"\\<forall>(R::('d,'d) Relation). t(R) = (\\<Union>n\\<in>{0<..}. R\\<^sup>n)\"\n  proof -\n    have \"\\<forall>n>0. \\<forall>(R::('d,'d) Relation). (R\\<^sup>n) \\<subseteq> t(R)\"\n      proof -\n      {\n        fix n\n        assume p: \"(n::nat) > 0\"\n        then have \"\\<forall>(R::('d,'d) Relation). (R\\<^sup>n) \\<subseteq> t(R)\" \n          proof(induct n)\n            case 0 show ?case using \"0.prems\" by auto  \n          next\n            case (Suc m)\n            assume a0: \"0 < (m::nat) \\<Longrightarrow> \\<forall>(R::('d,'d) Relation). (R\\<^sup>m) \\<subseteq> t(R)\"\n              and  a1: \"0 < Suc m\"\n            show ?case\n              proof(cases \"m = 0\")\n                assume b0: \"m = 0\"\n                have \"\\<forall>R. R\\<subseteq>t(R)\" using R_into_trancl by auto\n                with b0 show ?thesis by auto\n              next\n                assume b0: \"m \\<noteq> 0\"\n                then have b1: \"m > 0\" by auto\n                with a0 have b2: \"\\<forall>(R::('d,'d) Relation). (R\\<^sup>m) \\<subseteq> t(R)\" by simp\n                have \"\\<forall>(R::('d,'d) Relation). (R\\<^sup>m) O R \\<subseteq> t(R)\"\n                  proof -\n                  {\n                    fix R\n                    from b2 have \"(R\\<^sup>m) \\<subseteq> t(R::('d,'d) Relation)\" by simp \n                    then have \"(R\\<^sup>m) O R \\<subseteq> t(R)\" using R_trancl\n                      by (smt relcomp.cases set_mp subrelI)\n                  }\n                  then show ?thesis by auto\n                  qed\n                then show ?thesis \n                  using R_n_suc R_m_n b1 by (metis Nat.add_0_right R_O_Id R_n.simps(1) add_Suc_right) \n              qed\n          qed              \n      }\n      then show ?thesis by auto\n      qed\n    then have \"\\<forall>(R::('d,'d) Relation). (\\<Union>n\\<in>{0<..}. R\\<^sup>n) \\<subseteq> t(R)\" by blast\n    moreover\n    {\n      fix R\n      have \"(R::('d,'d) Relation) = R\\<^sup>1\" \n        using R_n_zero R_n_suc by simp\n      then have \"(R::('d,'d) Relation) \\<subseteq> (\\<Union>n\\<in>{0<..}. R\\<^sup>n)\" by blast\n      then have \"t((R::('d,'d) Relation)) \\<subseteq> (\\<Union>n\\<in>{0<..}. R\\<^sup>n)\"\n        using U_R_trans[of R] tR_trans_S[of R \"\\<Union>n\\<in>{0<..}. R\\<^sup>n\"] by blast\n    }        \n    ultimately show ?thesis by fast\n  qed\n\nlemma \"\\<lbrakk>card X = n; R \\<subseteq> X \\<times> X\\<rbrakk> \\<Longrightarrow> t(R) = (\\<Union>i\\<in>{1..n}. R\\<^sup>i)\" sorry\n\n\nsubsection {* example 6.9 *}\n\ndefinition \"R4 \\<equiv> {(''a'', ''b''), (''b'', ''c''), (''c'', ''a'')}\"\n\nlemma \"R_n (R4) 2 = R4 O R4\" \n  using R_n_suc R_n_zero by (simp add: numeral_2_eq_2) \n\nvalue \"R4 O R4\" \nvalue \"R4 O R4 O R4\" \nvalue \"R4 O R4 O R4 O R4\"\n\nsection {* Order relation *}\n\nsubsection {* definition 6.9*}\n\ndefinition Partial_Order_Set :: \"'d set \\<Rightarrow> ('d,'d) Relation \\<Rightarrow> bool\" (\"\\<langle>_, \\<le> _\\<rangle>\")\n  where \"Partial_Order_Set P R \\<equiv> refl_on P R \\<and> trans R \\<and> antisym R\"\n\nlemma \"\\<langle>P, \\<le> R\\<rangle> \\<Longrightarrow> Domain R = P\"\n  unfolding Partial_Order_Set_def refl_on_def using DomainI by blast\n\nlemma \"\\<langle>P, \\<le> R\\<rangle> \\<Longrightarrow> \\<langle>P, \\<le> R\\<inverse>\\<rangle> \" \n  unfolding Partial_Order_Set_def by force\n\nsubsection {* definition 6.10 *} \n\ndefinition Total_Order_Set :: \"'d set \\<Rightarrow> ('d,'d) Relation \\<Rightarrow> bool\" (\"\\<langle>_, \\<le>* _\\<rangle>\")\n  where \"Total_Order_Set P R \\<equiv> \\<langle>P, \\<le> R\\<rangle> \\<and> (\\<forall>x y. x\\<in>P \\<and> y\\<in>P \\<longrightarrow> (x, y)\\<in>R \\<or> (y, x)\\<in>R)\"\n\nlemma \"\\<langle>P, \\<le>* R\\<rangle> \\<Longrightarrow> \\<langle>P, \\<le> R\\<rangle> \" \n  unfolding Partial_Order_Set_def Total_Order_Set_def\n    by blast\n\nsubsection {* definition 6.11 *}\n\ndefinition Strict_Partial_Order_Set :: \"'d set \\<Rightarrow> ('d, 'd) Relation \\<Rightarrow> bool\" (\"\\<langle>_, < _\\<rangle>\")\n  where \"Strict_Partial_Order_Set P R \\<equiv> R \\<subseteq> P \\<times> P \\<and> trans R \\<and> irrefl R\"\n\n(* \nwhy we did not define antisym in Strict_Partial_Order_Set? \nbecause antisym is implied by trans and irrefl\n*)\nlemma \"trans R \\<and> irrefl R \\<Longrightarrow> antisym R\"\n  unfolding trans_def irrefl_def antisym_def by blast\n\n(*\nlemma \"Domain R = P \\<Longrightarrow> R \\<in> \\<langle>-, <\\<rangle> \\<Longrightarrow> (R \\<union> Id) \\<in> \\<langle>P, \\<le>\\<rangle>\"\n*)\n\n(*\nlemma \"R \\<in> \\<langle>-, <\\<rangle> \\<and> S\\<in>\\<langle>P, \\<le>\\<rangle> \\<Longrightarrow> R = S - Id\"  \n*)\n\nsubsection {* examples of definition 6.11 *}\n\ndefinition \"less_eq_real \\<equiv> {(x::real,y). x \\<le> y}\"\ndefinition \"greater_eq_real \\<equiv> {(x::real,y). x \\<ge> y} \"\ndefinition \"less_real \\<equiv> {(x::real,y). x < y}\"\ndefinition \"greater_real \\<equiv> {(x::real,y). x > y} \"\n\nlemma less_eq_real_partial_order: \"\\<langle>UNIV, \\<le> less_eq_real\\<rangle> \"\n  proof -\n    have \"trans less_eq_real\" using less_eq_real_def trans_def\n      by (smt case_prodD case_prodI mem_Collect_eq)  \n    moreover\n    have \"antisym less_eq_real\" using less_eq_real_def antisym_def\n      by (smt case_prod_conv mem_Collect_eq)\n    moreover\n    have \"refl_on UNIV less_eq_real\" using less_eq_real_def refl_on_def\n      UNIV_I case_prodI mem_Collect_eq mem_Sigma_iff subrelI by fastforce\n    ultimately show ?thesis by (simp add:Partial_Order_Set_def)\n  qed\n\nlemma \"\\<langle>UNIV, \\<le>* less_eq_real\\<rangle>\"\n  proof - \n    have \"\\<forall>x y. (x, y)\\<in>less_eq_real \\<or> (y, x)\\<in>less_eq_real\"\n      by (smt less_eq_real_def mem_Collect_eq old.prod.case) \n    with less_eq_real_partial_order show ?thesis by (simp add:Total_Order_Set_def)\n  qed\n\nlemma greater_eq_real_partial_order: \"\\<langle>UNIV, \\<le> greater_eq_real\\<rangle>\"\n  proof -\n    have \"trans greater_eq_real\" using greater_eq_real_def trans_def\n      by (smt case_prodD case_prodI mem_Collect_eq)  \n    moreover\n    have \"antisym greater_eq_real\" using greater_eq_real_def antisym_def\n      by (smt case_prod_conv mem_Collect_eq)\n    moreover\n    have \"refl_on UNIV greater_eq_real\" using greater_eq_real_def refl_on_def\n      UNIV_I case_prodI mem_Collect_eq mem_Sigma_iff subrelI by fastforce\n    ultimately show ?thesis by (simp add:Partial_Order_Set_def)\n  qed\n\nlemma \"\\<langle>UNIV, \\<le>* greater_eq_real\\<rangle>\"\n  proof - \n    have \"\\<forall>x y. (x, y)\\<in>greater_eq_real \\<or> (y, x)\\<in>greater_eq_real\"\n      by (smt greater_eq_real_def mem_Collect_eq old.prod.case) \n    with greater_eq_real_partial_order show ?thesis by (simp add:Total_Order_Set_def)\n  qed\n\nlemma \"\\<langle>UNIV, < less_real\\<rangle>\"\n  proof -\n    have \"trans less_real\" using less_real_def trans_def\n      by (smt case_prodD case_prodI mem_Collect_eq)  \n    moreover\n    have \"irrefl less_real\" using less_real_def irrefl_def\n      by (smt case_prod_conv mem_Collect_eq)\n    ultimately show ?thesis by (simp add:Strict_Partial_Order_Set_def)\n  qed\n\nlemma \"\\<langle>UNIV, < greater_real\\<rangle>\"\n  proof -\n    have \"trans greater_real\" using greater_real_def trans_def[of greater_real]\n      by (smt case_prodD case_prodI mem_Collect_eq)  \n    moreover\n    have \"irrefl greater_real\" using greater_real_def irrefl_def\n      by (smt case_prod_conv mem_Collect_eq)\n    ultimately show ?thesis by (simp add:Strict_Partial_Order_Set_def)\n  qed\n\ndefinition \"subset_eq_rel \\<equiv> {(x,y). x \\<subseteq> y} \"\n\n(* it is not correct. Domain of subset_eq_rel is UNIV, not P *)\nlemma \"\\<langle>P, \\<le> subset_eq_rel\\<rangle>\" sorry\n\ndefinition \"subset_eq_powp_rel P \\<equiv> {(x,y). x\\<in>Pow P \\<and> y\\<in>Pow P \\<and> x \\<subseteq> y}\"\ndefinition \"subset_powp_rel P \\<equiv> {(x,y). x\\<in>Pow P \\<and> y\\<in>Pow P \\<and> x \\<subset> y} \"\n\nlemma \"\\<langle>Pow P, \\<le> (subset_eq_powp_rel P)\\<rangle>\"\n  proof -\n    have \"trans (subset_eq_powp_rel P)\" \n      using subset_eq_powp_rel_def[of P] trans_def[of \"(subset_eq_powp_rel P)\"] by fastforce\n    moreover\n    have \"antisym (subset_eq_powp_rel P)\" \n      using subset_eq_powp_rel_def[of P] antisym_def[of \"(subset_eq_powp_rel P)\"] by fastforce\n    moreover\n    have \"refl_on (Pow P) (subset_eq_powp_rel P)\" \n      using subset_eq_powp_rel_def[of P] refl_on_def[of \"Pow P\" \"(subset_eq_powp_rel P)\"] by force\n    ultimately show ?thesis by (simp add:Partial_Order_Set_def)\n  qed\n\nlemma \"\\<langle>Pow P, < (subset_powp_rel P)\\<rangle>\"\n  proof -\n    have \"trans (subset_powp_rel P)\" \n      using subset_powp_rel_def[of P] trans_def[of \"subset_powp_rel P\"] by fastforce \n    moreover\n    have \"irrefl (subset_powp_rel P)\" \n      using subset_powp_rel_def[of P] irrefl_def[of \"subset_powp_rel P\"] by fastforce\n    ultimately show ?thesis \n      unfolding Strict_Partial_Order_Set_def subset_powp_rel_def by auto\n  qed\n\nsubsection {* definition 6.12, 6.13 *}\n(* maximal, minimal, least and greatest elements *)\n(*  supremum: least upper bound  or join *)\n(*  infimum: greatest lower bound or meet *) \n\ndefinition greatest :: \"('a, 'a) Relation \\<Rightarrow> 'a set \\<Rightarrow> 'a set\"\n  where \"greatest R B \\<equiv> {b. b \\<in> B \\<and> (\\<forall>b' \\<in> B. (b', b) \\<in> R)}\" \n\ndefinition least :: \"('a, 'a) Relation \\<Rightarrow> 'a set \\<Rightarrow> 'a set\"\n  where \"least R B \\<equiv> {b. b \\<in> B \\<and> (\\<forall>b' \\<in> B. (b, b') \\<in> R)}\" \n\ndefinition maximal :: \"('a, 'a) Relation \\<Rightarrow> 'a set \\<Rightarrow> 'a set\"\n  where \"maximal R B \\<equiv> {b. b \\<in> B \\<and> \\<not>(\\<exists>b' \\<in> B. b \\<noteq> b' \\<and> (b, b') \\<in> R)}\" \n\ndefinition minimal :: \"('a, 'a) Relation \\<Rightarrow> 'a set \\<Rightarrow> 'a set\"\n  where \"minimal R B \\<equiv> {b. b \\<in> B \\<and> \\<not>(\\<exists>b' \\<in> B. b \\<noteq> b' \\<and> (b', b) \\<in> R)}\" \n\ndefinition upperbound :: \"('a, 'a) Relation \\<Rightarrow> 'a set \\<Rightarrow> 'a set\"\n  where \"upperbound R B \\<equiv> {b. (\\<forall>b' \\<in> B. (b', b) \\<in> R)}\" \n\ndefinition lowerbound :: \"('a, 'a) Relation \\<Rightarrow> 'a set \\<Rightarrow> 'a set\"\n  where \"lowerbound R B \\<equiv> {b. (\\<forall>b' \\<in> B. (b, b') \\<in> R)}\"\n\n(*  supremum: least upper bound  or join *)\ndefinition supremum :: \"('a, 'a) Relation \\<Rightarrow> 'a set \\<Rightarrow> 'a set\"\n  where \"supremum R B \\<equiv> {b. \\<forall>b'\\<in>upperbound R B. (b,b') \\<in> R}\"\n\n(*  infimum: greatest lower bound or meet *) \ndefinition infimum :: \"('a, 'a) Relation \\<Rightarrow> 'a set \\<Rightarrow> 'a set\"\n  where \"infimum R B \\<equiv> {b. \\<forall>b'\\<in>lowerbound R B. (b',b) \\<in> R}\"\n\n\n(* at most one greatest element *)\nlemma grtst_one_most: \"\\<langle>A, \\<le> R\\<rangle> \\<Longrightarrow> \\<forall>x y. x \\<in> greatest R B \\<and> y \\<in> greatest R B \\<longrightarrow> x = y\"\n  proof -\n    assume p0: \"\\<langle>A, \\<le> R\\<rangle>\"\n    {\n      fix x y\n      assume p2: \"x \\<in> greatest R B \\<and> y \\<in> greatest R B\"\n      from p2 have \"x \\<in> B \\<and> (\\<forall>b' \\<in> B. (b', x) \\<in> R)\" by (simp add:greatest_def)\n      moreover\n      from p2 have \"y \\<in> B \\<and> (\\<forall>b' \\<in> B. (b', y) \\<in> R)\" by (simp add:greatest_def)\n      ultimately have \"(x,y)\\<in>R \\<and> (y,x)\\<in>R\"  by auto\n      moreover\n      from p0 have \"antisym R\" by (simp add:Partial_Order_Set_def)\n      ultimately have \"x = y\" by (simp add:antisym_def)\n    }\n    then show ?thesis by auto\n  qed\n\n(* at most one least element *)\nlemma least_one_most: \"\\<langle>A, \\<le> R\\<rangle> \\<Longrightarrow> \\<forall>x y. x \\<in> least R B \\<and> y \\<in> least R B \\<longrightarrow> x = y\"\n  proof -\n    assume p0: \"\\<langle>A, \\<le> R\\<rangle>\"\n    {\n      fix x y\n      assume p2: \"x \\<in> least R B \\<and> y \\<in> least R B\"\n      from p2 have \"x \\<in> B \\<and> (\\<forall>b' \\<in> B. (x, b') \\<in> R)\" by (simp add:least_def)\n      moreover\n      from p2 have \"y \\<in> B \\<and> (\\<forall>b' \\<in> B. (y, b') \\<in> R)\" by (simp add:least_def)\n      ultimately have \"(x,y)\\<in>R \\<and> (y,x)\\<in>R\" by auto\n      moreover\n      from p0 have \"antisym R\" by (simp add:Partial_Order_Set_def)\n      ultimately have \"x = y\" by (simp add:antisym_def)\n    }\n    then show ?thesis by auto\n  qed\n\n(* greatest implies maximal *)\nlemma poset_grst_eq_max: \"\\<langle>A, \\<le> R\\<rangle> \\<and> greatest R B \\<noteq> {} \\<Longrightarrow> greatest R B = maximal R B\"\n  proof -\n    assume p0: \"\\<langle>A, \\<le> R\\<rangle> \\<and> greatest R B \\<noteq> {}\"\n    then obtain b where \"b \\<in> greatest R B\" by blast\n    with grtst_one_most p0 have a0: \"{b} = greatest R B\"\n      using singleton_iff subsetI subset_singletonD by blast \n    then have a1: \"b \\<in> B \\<and> (\\<forall>b' \\<in> B. (b', b) \\<in> R)\" unfolding greatest_def by blast\n\n    from p0 have a2: \"antisym R\" by (simp add:Partial_Order_Set_def)\n    \n    with a1 have \"b \\<in> maximal R B\" unfolding maximal_def antisym_def by blast\n    \n    with a1 a2 have \"{b} = maximal R B\" unfolding maximal_def antisym_def by blast\n    with a0 show \"greatest R B = maximal R B\" by simp\n  qed\n  \n(* least implies minimal *)\nlemma poset_least_eq_min: \"\\<langle>A, \\<le> R\\<rangle> \\<and> least R B \\<noteq> {} \\<Longrightarrow> least R B = minimal R B\"\n  proof -\n    assume p0: \"\\<langle>A, \\<le> R\\<rangle> \\<and> least R B \\<noteq> {}\"\n    then obtain b where \"b \\<in> least R B\" by blast\n    with least_one_most p0 have a0: \"{b} = least R B\"\n      using singleton_iff subsetI subset_singletonD by blast \n    then have a1: \"b \\<in> B \\<and> (\\<forall>b' \\<in> B. (b, b') \\<in> R)\" unfolding least_def by blast\n\n    from p0 have a2: \"antisym R\" by (simp add:Partial_Order_Set_def)\n    \n    with a1 have \"b \\<in> minimal R B\" unfolding minimal_def antisym_def by blast\n    \n    with a1 a2 have \"{b} = minimal R B\" unfolding minimal_def antisym_def by blast\n    with a0 show \"least R B = minimal R B\" by simp\n  qed\n\n\nsubsection {* definition 6.14 *}\n\ndefinition Well_Order_Set :: \"'d set \\<Rightarrow> ('d,'d) Relation \\<Rightarrow> bool\" (\"\\<langle>_, \\<lessapprox> _\\<rangle>\")\n  where \"Well_Order_Set P R \\<equiv> \\<langle>P,\\<le> R\\<rangle> \\<and> (\\<forall>A. A\\<subseteq>P \\<and> A \\<noteq> {}  \\<longrightarrow> least R A \\<noteq> {})\"\n\n(* *)\nlemma A_wo_has_least: \"\\<langle>P, \\<lessapprox> R\\<rangle> \\<Longrightarrow> (\\<forall>A. A \\<subseteq> P \\<and> A \\<noteq> {} \\<longrightarrow> (\\<exists>y\\<in>A. \\<forall>x\\<in>A. (y,x)\\<in>R))\"\n  proof -\n    assume p0: \"\\<langle>P, \\<lessapprox> R\\<rangle>\"\n    then have p1: \"\\<langle>P,\\<le> R\\<rangle> \\<and> (\\<forall>A. A \\<subseteq> P \\<and> A \\<noteq> {} \\<longrightarrow> least R A \\<noteq> {})\" \n      by (simp add: Well_Order_Set_def)\n    \n    {\n      fix A\n      assume a0: \"A\\<subseteq>P \\<and> A \\<noteq> {}\"\n      with p1 have a1: \"least R A \\<noteq> {}\" by auto\n\n      from p1 have \"\\<forall>x y. x \\<in> least R A \\<and> y \\<in> least R A \\<longrightarrow> x = y\"\n        using least_one_most by metis\n\n      with a1 have \"\\<exists>y. least R A = {y}\" by fastforce\n\n      then obtain y where \"least R A = {y}\" by auto\n      then have \"y \\<in> A \\<and> (\\<forall>b' \\<in> A. (y, b') \\<in> R)\" unfolding least_def by blast\n      then have \"\\<exists>y\\<in>A. \\<forall>x\\<in>A. (y,x)\\<in>R\" by auto\n    }\n    then show ?thesis by auto\n  qed\n\n(* well order set is total order set*)\nlemma \"\\<langle>P, \\<lessapprox> R\\<rangle> \\<Longrightarrow> \\<langle>P, \\<le>* R\\<rangle>\"\n  proof -\n    assume \"\\<langle>P, \\<lessapprox> R\\<rangle>\"\n    then have p1: \"\\<langle>P,\\<le> R\\<rangle> \\<and> (\\<forall>A. A\\<subseteq>P \\<and> A \\<noteq> {}  \\<longrightarrow> least R A \\<noteq> {})\" \n      by (simp add: Well_Order_Set_def)\n      \n    {\n      fix x y\n      assume a0: \"x\\<in>P \\<and> y\\<in>P\"\n      let ?A = \"{x,y}\"\n      from a0 have \"?A\\<subseteq>P\" by auto\n      with p1 have a1: \"least R ?A \\<noteq> {}\" by blast\n      from p1 have \"\\<forall>x y. x \\<in> least R ?A \\<and> y \\<in> least R ?A \\<longrightarrow> x = y\"\n        using least_one_most by metis\n      with a1 have \"\\<exists>y. least R ?A = {y}\" by fastforce\n      then obtain y1 where \"least R ?A = {y1}\" by auto\n      then have a2: \"y1 \\<in> ?A \\<and> (\\<forall>b' \\<in> ?A. (y1, b') \\<in> R)\" unfolding least_def by blast\n      then have \"x = y1 \\<or> y = y1\" by blast\n      then have \"(x, y)\\<in>R \\<or> (y, x)\\<in>R\" \n        proof\n          assume \"x = y1\"\n          with a2 show \"(x, y) \\<in> R \\<or> (y, x) \\<in> R\" by blast\n        next\n          assume \"y = y1\"\n          with a2 show \"(x, y) \\<in> R \\<or> (y, x) \\<in> R\" by blast\n        qed\n    }\n    then have \"\\<forall>x y. x\\<in>P \\<and> y\\<in>P \\<longrightarrow> (x, y)\\<in>R \\<or> (y, x)\\<in>R\" by auto\n    with p1 show ?thesis by (simp add:Total_Order_Set_def)\n  qed\n\n\nsection {* section 6.4 equivalent relation, partition, and others *}\n\nsubsection {* definition 6.15 *}\n\ndefinition \"Set_Cover S A \\<equiv> ((\\<forall>B\\<in>A. B \\<noteq> {}) \\<and> Union A = S)\"\n\nsubsection {* definition 6.16 *}\n\ndefinition \"Set_Partition S A \\<equiv> Set_Cover S A \\<and> (\\<forall>x y. x\\<in>A \\<and> y\\<in>A \\<and> x \\<noteq> y \\<longrightarrow> x \\<inter> y = {})\"\n\nsubsection {* example 6.16 *}\n\nlemma lmaa:  \"Set_Cover {1::int,2,3} {{1,2},{2,3}}\"\n  unfolding Set_Cover_def by blast\n\nlemma lmcc: \"Set_Partition {1::int,2,3} {{1},{2,3}}\"\n  unfolding Set_Partition_def Set_Cover_def by force\n\nlemma lmdd: \"Set_Partition {1::int,2,3} {{1,2,3}}\"\n  unfolding Set_Partition_def Set_Cover_def by force\n\nlemma lmee: \"Set_Partition {1::int,2,3} {{1},{2},{3}}\"\n  unfolding Set_Partition_def Set_Cover_def by force\n\nlemma lmff:  \"Set_Cover {1::int,2,3} {{1}, {1,2},{2,3}}\"\n  unfolding Set_Cover_def by blast\n\nsubsection {* example 6.17 *}\n\ndefinition \"NatSet = {x::int. x \\<ge> 0}\"\n\ndefinition \"E1 = {x::int. x \\<ge> 0 \\<and> x mod 2 = 0}\"\n\ndefinition \"O1 = {x::int. x \\<ge> 0 \\<and> x mod 2 \\<noteq> 0}\"\n\nlemma exm617_lm1: \"Union {E1, O1} = NatSet\"\n  proof -\n    have \"Union {E1, O1} = {x::int. x \\<ge> 0}\"\n      unfolding E1_def O1_def by force\n    then show ?thesis unfolding NatSet_def by simp\n  qed\n\nlemma exm617_lm2: \"Set_Cover NatSet {E1, O1}\"\n    apply(simp add: Set_Cover_def)\n    apply(rule conjI)\n    apply(simp add: E1_def) apply fastforce\n    apply(rule conjI)\n    apply(simp add: O1_def) apply presburger \n    using exm617_lm1 by simp\n\nlemma \"Set_Partition NatSet {E1, O1}\" \n  apply(simp add: Set_Partition_def)\n  apply(rule conjI)\n  using exm617_lm2 apply simp\n  apply(rule allI)+\n  apply(rule impI)\n  unfolding NatSet_def E1_def O1_def \n  by fastforce\n\nsubsection {* definition 6.17 *}\n\nthm equiv_def\n\nlemma \"equiv A R \\<Longrightarrow> Domain R = A\"\n  unfolding equiv_def refl_on_def by force\n\nsubsection {* equiv with mod *}\n\ndefinition \"ModR X m \\<equiv> {(x::int,y::int). x\\<in>X \\<and> y\\<in>X \\<and> x mod m = y mod m}\"\n\nlemma \"equiv X (ModR X m)\" \n  proof -\n    have \"refl_on X (ModR X m)\"\n      unfolding refl_on_def ModR_def by fastforce\n    moreover\n    have \"sym (ModR X m)\"\n      unfolding sym_def ModR_def by fastforce\n    moreover\n    have \"trans (ModR X m)\" \n      unfolding trans_def ModR_def by fastforce\n    ultimately show ?thesis by (simp add:equiv_def)\n  qed\n\nsubsection {* definition 6.18 *}\n\ndefinition \"Set_x X R x \\<equiv> {y. y\\<in>X \\<and> (x,y)\\<in>R}\"\n\nlemma def618_lm11: \"equiv X R \\<and> x\\<in>X \\<Longrightarrow> x\\<in>Set_x X R x\"\n  unfolding equiv_def refl_on_def Set_x_def by fastforce\n\nlemma def618_lm12: \"equiv X R \\<and> x\\<in>X \\<Longrightarrow> Set_x X R x \\<noteq> {}\"  \n  using def618_lm11 by fastforce\n\nlemma def618_lm2: \"equiv X R \\<and> x\\<in>X \\<and> y\\<in>X \\<Longrightarrow> (Set_x X R x = Set_x X R y) \\<longleftrightarrow> (x,y)\\<in>R\"\n  proof -\n    assume p0: \"equiv X R \\<and> x\\<in>X \\<and> y\\<in>X\"\n\n    {\n      assume a0: \"Set_x X R x = Set_x X R y\"\n      from p0 have \"x\\<in>Set_x X R x\" using def618_lm11 by fastforce\n      moreover\n      from p0 have \"y\\<in>Set_x X R y\" using def618_lm11 by fastforce\n      ultimately have \"(x,y)\\<in>R\"  using a0 unfolding Set_x_def by fastforce\n    }\n    moreover\n    {\n      assume a0: \"(x,y)\\<in>R\"\n      with p0 have a1: \"(y,x)\\<in>R\" \n        unfolding equiv_def sym_def by fastforce\n\n      {\n        fix a\n        assume \"a\\<in>Set_x X R  x\"\n        with p0 a1 have \"a\\<in>Set_x X R y\"\n          unfolding Set_x_def equiv_def trans_def\n            using mem_Collect_eq by blast \n      }\n      moreover\n      {\n        fix a\n        assume \"a\\<in>Set_x X R y\"\n        then have \"(y,a)\\<in>R\"\n          unfolding Set_x_def by auto\n        with p0 a0 have \"a\\<in>Set_x X R x\"\n          unfolding Set_x_def equiv_def trans_def\n            by (metis (no_types, lifting) CollectI refl_onD2) \n      }\n      ultimately have \"Set_x X R x = Set_x X R y\" by auto\n    }\n    ultimately show ?thesis by auto\n  qed\n\nlemma def618_lm3: \"equiv X R \\<and> x\\<in>X \\<and> y\\<in>X \\<and> (x,y)\\<notin>R \\<Longrightarrow> Set_x X R x \\<inter> Set_x X R y = {}\"\n  proof -\n    assume p0: \"equiv X R \\<and> x\\<in>X \\<and> y\\<in>X \\<and> (x,y)\\<notin>R\"\n\n    {\n      assume a0: \"Set_x X R x \\<inter> Set_x X R y \\<noteq> {}\"\n      then obtain tt where \"tt \\<in> Set_x X R x \\<and> tt \\<in> Set_x X R y\" by auto\n      then have \"(x,tt)\\<in>R \\<and> (y,tt)\\<in>R\"\n        unfolding Set_x_def by auto\n      moreover\n      with p0 have \"(tt,y)\\<in>R\" unfolding equiv_def sym_def by fastforce\n      ultimately have \"(x,y)\\<in>R\" using p0\n        unfolding equiv_def sym_def refl_on_def trans_def by meson\n   \n      with p0 have False by simp\n    }\n    then show ?thesis by auto\n qed\n\nlemma def618_lm4: \"equiv X R \\<Longrightarrow> (\\<Union>x\\<in>X. Set_x X R x) = X\" \n  proof -\n    assume p0: \"equiv X R\"\n    have \"\\<forall>x. x\\<in>X \\<longrightarrow> Set_x X R x \\<subseteq> X\"\n      apply(rule allI)\n      apply(rule impI)\n      unfolding Set_x_def by auto\n    then have g1: \"(\\<Union>x\\<in>X. Set_x X R x) \\<subseteq> X\" by auto\n\n    from p0 have \"\\<forall>x. x\\<in>X \\<longrightarrow> x\\<in>Set_x X R x\" \n      using def618_lm11 by fastforce\n    then have g2: \"X \\<subseteq> (\\<Union>x\\<in>X. Set_x X R x)\" by auto\n\n    from g1 g2 show ?thesis by auto\n  qed\n\nsubsection {* theorem 6.8 *}\n\n(* the set of equiv class *)\ndefinition \"Equiv_Set X R \\<equiv> {S. \\<exists>x\\<in>X. S = Set_x X R x}\"\n\nlemma thm6_8: \"equiv X R \\<Longrightarrow> Set_Partition X (Equiv_Set X R)\" \n  proof -\n    assume p0: \"equiv X R\"\n    let ?A = \"{S. \\<exists>x\\<in>X. S = Set_x X R x}\"\n    from p0 have \"(\\<Union>x\\<in>X. Set_x X R x) = X\" using def618_lm4 by auto\n    moreover\n    have \"(\\<Union>x\\<in>X. Set_x X R x) = Union ?A\" by fastforce\n    ultimately have \"Union ?A = X\" by simp\n    moreover from p0 have \"\\<forall>B\\<in>{S. \\<exists>x\\<in>X. S = Set_x X R x}. B \\<noteq> {}\" using def618_lm12 by fastforce\n    ultimately have g1: \"Set_Cover X ?A\" unfolding Set_Cover_def by auto\n\n    {\n      fix A B\n      assume a0: \"A\\<in>?A \\<and> B\\<in>?A \\<and> A \\<noteq> B\"\n      moreover\n      then obtain x where a1: \"x\\<in>X \\<and> Set_x X R x = A\" by auto\n      moreover\n      from a0 obtain y where a2: \"y\\<in>X \\<and> Set_x X R y = B\" by auto\n      ultimately have \"(x,y)\\<notin>R\" \n        using p0 def618_lm2 by (metis (no_types, lifting)) \n\n      with p0 a1 a2 have \"A \\<inter> B = {}\" using def618_lm3 by fastforce\n    }\n    then have g2: \"\\<forall>A B. A\\<in>?A \\<and> B\\<in>?A \\<and> A \\<noteq> B \\<longrightarrow> A \\<inter> B = {}\" by auto\n   \n    from g1 g2 show ?thesis unfolding Set_Partition_def Equiv_Set_def by simp\n  qed\n\n\nsubsection {* example 6.20 *}\n\ndefinition \"ID X \\<equiv> {p. \\<exists>x. x\\<in>X \\<and> p = (x, x)}\"\ndefinition \"U X \\<equiv> {p. \\<exists>x y. x\\<in>X \\<and> y\\<in>X \\<and> p = (x,y)}\"\n\nlemma equiv_id_lm: \"equiv X (ID X)\"\n  unfolding equiv_def ID_def\n  apply(rule conjI)\n  unfolding refl_on_def apply force\n  apply(rule conjI)\n  unfolding sym_def apply force\n  unfolding trans_def by force\n\nlemma equiv_u_lm: \"equiv X (U X)\"\n  unfolding equiv_def U_def\n  apply(rule conjI)\n  unfolding refl_on_def apply force\n  apply(rule conjI)\n  unfolding sym_def apply force\n  unfolding trans_def by force\n\nlemma \"X \\<noteq> {} \\<Longrightarrow> Equiv_Set X (U X) = {X}\" \n  proof -\n    assume p0: \"X \\<noteq> {}\"\n    let ?R = \"U X\"\n    have a1: \"equiv X ?R\" using equiv_u_lm by auto\n\n    {\n      fix x y\n      assume b0: \"x\\<in>X \\<and> y\\<in>X\"\n      then have \"(x,y)\\<in> ?R\" unfolding U_def by fastforce\n      with b0 a1 have \"Set_x X ?R x = Set_x X ?R y\" \n        using def618_lm2 by fastforce\n    }\n    then have a2: \"\\<forall>x y. x\\<in>X \\<and> y\\<in>X \\<longrightarrow> Set_x X ?R x = Set_x X ?R y\"  by auto\n    from p0 obtain x1 where a3: \"x1\\<in>X\" by auto\n    with a2 have a4: \"\\<forall>x\\<in>X. Set_x X ?R x = Set_x X ?R x1\" by blast\n\n    {\n      fix a\n      assume \"a\\<in>(\\<Union>x\\<in>X. Set_x X ?R x)\"\n      then obtain y1 where \"y1\\<in>X \\<and> a\\<in>Set_x X ?R y1\" by auto\n      with a4 have \"a\\<in>Set_x X ?R x1\" by blast\n    }\n    moreover\n    {\n      fix a\n      assume \"a\\<in>Set_x X ?R x1\"\n      with a3 have \"a\\<in>(\\<Union>x\\<in>X. Set_x X ?R x)\"\n          using UN_I \\<open>\\<And>thesis. (\\<And>x1. x1 \\<in> X \\<Longrightarrow> thesis) \\<Longrightarrow> thesis\\<close> by force\n    }\n    ultimately have \"(\\<Union>x\\<in>X. Set_x X ?R x) = Set_x X ?R x1\" by blast\n\n    with a1 a4 have a5: \"\\<forall>x\\<in>X. Set_x X ?R x = X\" using def618_lm4 by fastforce\n\n    {\n      fix a\n      assume \"a\\<in>Equiv_Set X (U X)\"\n      then obtain x2 where \"x2\\<in>X \\<and> a = Set_x X ?R x2\" unfolding Equiv_Set_def by auto\n      with a5 have \"a\\<in>{X}\" by auto\n    }\n    moreover\n    {\n      fix a\n      assume \"a\\<in>{X}\"\n      with a3 a5 a4 have \"a\\<in>Equiv_Set X (U X)\" \n        unfolding Equiv_Set_def by blast\n    }\n    ultimately show ?thesis by auto\n  qed\n\nlemma \"X \\<noteq> {} \\<Longrightarrow> Equiv_Set X (ID X) = {p. \\<exists>x\\<in>X. p = {x}}\" sorry\n(* please prove it by youself *)\n\nsubsection {* theorem 6.9 *} \n    \nlemma \"Set_Partition X C \\<and> (\\<forall>x y. (x,y)\\<in>R \\<longleftrightarrow> (\\<exists>c\\<in>C. x\\<in>c \\<and> y\\<in>c)) \\<Longrightarrow> equiv X R\" \n  proof -\n    assume p0: \"Set_Partition X C \\<and> (\\<forall>x y. (x,y)\\<in>R \\<longleftrightarrow> (\\<exists>c\\<in>C. x\\<in>c \\<and> y\\<in>c))\"\n    \n    have g1: \"refl_on X R\" \n      unfolding refl_on_def apply(rule conjI)\n      proof -\n        {\n          fix x y\n          assume \"(x,y)\\<in>R\"\n          with p0 have \"\\<exists>c\\<in>C. x\\<in>c \\<and> y\\<in>c\" by auto\n          then obtain c where \"c\\<in>C \\<and> x\\<in>c \\<and> y\\<in>c\" by auto\n          with p0 have \"(x,y)\\<in>X \\<times> X\" \n            unfolding Set_Partition_def Set_Cover_def by fastforce\n        }\n        then show \"R \\<subseteq> X \\<times> X\" by auto\n      next\n        {\n          fix x\n          assume \"x\\<in>X\"\n          with p0 have \"\\<exists>c\\<in>C. x\\<in>c\" \n            unfolding Set_Partition_def Set_Cover_def by fastforce\n          with p0 have \"(x, x) \\<in> R\" by auto\n        }\n        then show \"\\<forall>x\\<in>X. (x, x) \\<in> R\"  by auto\n      qed\n\n    {\n      fix x y\n      assume \"(x, y) \\<in> R\"\n      with p0 have \"\\<exists>c\\<in>C. x \\<in> c \\<and> y \\<in> c\" by auto\n      with p0 have \"(y, x) \\<in> R\" by auto\n    }\n    then have g2: \"sym R\"\n      unfolding sym_def by auto\n          \n    {\n      fix x y z\n      assume a1: \"(x, y) \\<in> R\"\n        and  a2: \"(y, z) \\<in> R\"\n      from p0 a1 have \"\\<exists>c\\<in>C. x \\<in> c \\<and> y \\<in> c\" by auto\n      then obtain c1 where a3: \"c1\\<in>C \\<and> x \\<in> c1 \\<and> y \\<in> c1\" by auto\n\n      from p0 a2 have \"\\<exists>c\\<in>C. y \\<in> c \\<and> z \\<in> c\" by auto\n      then obtain c2 where a4: \"c2\\<in>C \\<and> y \\<in> c2 \\<and> z \\<in> c2\" by auto\n      \n      from a3 a4 have \"c1 \\<inter> c2 \\<noteq> {}\" by auto\n      with p0 a3 a4 have \"c1 = c2\" \n        unfolding Set_Partition_def Set_Cover_def by auto\n      with p0 a3 a4 have \"(x, z) \\<in> R\" by auto\n    }\n    then have g3: \"trans R\"\n      unfolding trans_def by blast\n\n    from g1 g2 g3 show ?thesis unfolding equiv_def by auto\n  qed\n\nlemma \"Set_Partition X C \\<and> R = (\\<Union>c\\<in>C. (c \\<times> c)) \\<Longrightarrow> (\\<forall>x y. (x,y)\\<in>R \\<longleftrightarrow> (\\<exists>c\\<in>C. x\\<in>c \\<and> y\\<in>c))\"\n  proof -\n    assume p0: \"Set_Partition X C \\<and> R = (\\<Union>c\\<in>C. (c \\<times> c))\"\n    \n    {\n      fix x y\n      {\n        assume \"(x,y)\\<in>R\"\n        with p0 have \"\\<exists>c\\<in>C. x\\<in>c \\<and> y\\<in>c\" by auto\n      }\n      moreover\n      {\n        assume \"\\<exists>c\\<in>C. x\\<in>c \\<and> y\\<in>c\"\n        then obtain c where \"c\\<in>C \\<and> x\\<in>c \\<and> y\\<in>c\" by auto\n        with p0 have \"(x,y)\\<in>R\" by auto\n      }\n      ultimately have \"(x,y)\\<in>R \\<longleftrightarrow> (\\<exists>c\\<in>C. x\\<in>c \\<and> y\\<in>c)\" by auto\n    }\n    then show ?thesis by auto\n  qed\n\nlemma \"Set_Partition X C \\<and> (\\<forall>x y. (x,y)\\<in>R \\<longleftrightarrow> (\\<exists>c\\<in>C. x\\<in>c \\<and> y\\<in>c)) \\<Longrightarrow> R = (\\<Union>c\\<in>C. (c \\<times> c))\"\n  proof -\n    assume p0: \"Set_Partition X C \\<and> (\\<forall>x y. (x,y)\\<in>R \\<longleftrightarrow> (\\<exists>c\\<in>C. x\\<in>c \\<and> y\\<in>c))\"\n    \n    {\n      fix x y\n      assume \"(x,y)\\<in>R\"\n      with p0 have \"\\<exists>c\\<in>C. x\\<in>c \\<and> y\\<in>c\" by auto\n      then have \"(x,y)\\<in>(\\<Union>c\\<in>C. (c \\<times> c))\" by auto\n    }\n    then have g1: \"\\<forall>x y. (x,y)\\<in>R \\<longrightarrow> (x,y)\\<in>(\\<Union>c\\<in>C. (c \\<times> c))\" by auto\n    \n    {\n      fix x y\n      assume \"(x,y)\\<in>(\\<Union>c\\<in>C. (c \\<times> c))\"\n      then have \"\\<exists>c\\<in>C. (x,y)\\<in>c\\<times>c\" by auto\n      with p0 have \"(x,y)\\<in>R\" by auto\n    }\n    then have g2: \"\\<forall>x y. (x,y)\\<in>(\\<Union>c\\<in>C. (c \\<times> c)) \\<longrightarrow> (x,y)\\<in>R\" by auto\n\n    from g1 g2 show ?thesis by fastforce\n  qed\n  \n\nend", "meta": {"author": "LVPGroup", "repo": "FLAT", "sha": "674c932d9a2f178cb870e28bd63407ad797199e8", "save_path": "github-repos/isabelle/LVPGroup-FLAT", "path": "github-repos/isabelle/LVPGroup-FLAT/FLAT-674c932d9a2f178cb870e28bd63407ad797199e8/Section1_Foundation/RelationFoundation.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711642563823, "lm_q2_score": 0.8652240808393984, "lm_q1q2_score": 0.7354155193337217}}
{"text": "section \\<open>Faces, Extreme Points, Polytopes, Polyhedra etc\\<close>\n\ntext\\<open>Refactoring of HOL-Analysis.Polytope, originally ported from HOL Light by L C Paulson\\<close>\n\ntheory Polytope\n  imports \"HOL-Analysis.Cartesian_Euclidean_Space\"\nbegin\n\nsubsection\\<open>Faces of a (usually convex) set\\<close>\n\ndeclare[[show_consts=true,show_brackets=true]]\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    \"((+) a ` T face_of (+) a ` S) \\<longleftrightarrow> T face_of S\"\nproof -\n  have *: \"\\<And>a T S. T face_of S \\<Longrightarrow> ((+) a ` T face_of (+) 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\"  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      by (simp add: divide_simps) (simp add: algebra_simps)\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\nlemma subset_of_face_of_affine_hull:\n    fixes S :: \"'a::euclidean_space set\"\n  assumes T: \"T face_of S\" and \"convex S\" \"U \\<subseteq> S\" and dis: \"~disjnt (affine hull T) (rel_interior U)\"\n  shows \"U \\<subseteq> T\"\n  apply (rule subset_of_face_of [OF T \\<open>U \\<subseteq> S\\<close>])\n  using face_of_imp_eq_affine_Int [OF \\<open>convex S\\<close> T]\n  using rel_interior_subset [of U] dis\n  using \\<open>U \\<subseteq> S\\<close> disjnt_def by fastforce\n\nlemma affine_hull_face_of_disjoint_rel_interior:\n    fixes S :: \"'a::euclidean_space set\"\n  assumes \"convex S\" \"F face_of S\" \"F \\<noteq> S\"\n  shows \"affine hull F \\<inter> rel_interior S = {}\"\n  by (metis assms disjnt_def face_of_imp_subset order_refl subset_antisym subset_of_face_of_affine_hull)\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 fin(2) sum_nonneg_eq_0_iff by auto\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 IntQ Inter_UNIV_conv(2) assms(1) assms(2) ex_in_conv)\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\nlemma exposed_face_of_parallel:\n   \"T exposed_face_of S \\<longleftrightarrow>\n         T face_of S \\<and>\n         (\\<exists>a b. S \\<subseteq> {x. a \\<bullet> x \\<le> b} \\<and> T = S \\<inter> {x. a \\<bullet> x = b} \\<and>\n                (T \\<noteq> {} \\<longrightarrow> T \\<noteq> S \\<longrightarrow> a \\<noteq> 0) \\<and>\n                (T \\<noteq> S \\<longrightarrow> (\\<forall>w \\<in> affine hull S. (w + a) \\<in> affine hull S)))\"\n  (is \"?lhs = ?rhs\")\nproof\n  assume ?lhs then show ?rhs\n  proof (clarsimp simp: exposed_face_of_def)\n    fix a b\n    assume faceS: \"S \\<inter> {x. a \\<bullet> x = b} face_of S\" and Ssub: \"S \\<subseteq> {x. a \\<bullet> x \\<le> b}\" \n    show \"\\<exists>c d. S \\<subseteq> {x. c \\<bullet> x \\<le> d} \\<and>\n                S \\<inter> {x. a \\<bullet> x = b} = S \\<inter> {x. c \\<bullet> x = d} \\<and>\n                (S \\<inter> {x. a \\<bullet> x = b} \\<noteq> {} \\<longrightarrow> S \\<inter> {x. a \\<bullet> x = b} \\<noteq> S \\<longrightarrow> c \\<noteq> 0) \\<and>\n                (S \\<inter> {x. a \\<bullet> x = b} \\<noteq> S \\<longrightarrow> (\\<forall>w \\<in> affine hull S. w + c \\<in> affine hull S))\"\n    proof (cases \"affine hull S \\<inter> {x. -a \\<bullet> x \\<le> -b} = {} \\<or> affine hull S \\<subseteq> {x. - a \\<bullet> x \\<le> - b}\")\n      case True\n      then show ?thesis\n      proof\n        assume \"affine hull S \\<inter> {x. - a \\<bullet> x \\<le> - b} = {}\"\n       then show ?thesis\n         apply (rule_tac x=\"0\" in exI)\n         apply (rule_tac x=\"1\" in exI)\n         using hull_subset by fastforce\n    next\n      assume \"affine hull S \\<subseteq> {x. - a \\<bullet> x \\<le> - b}\"\n      then show ?thesis\n         apply (rule_tac x=\"0\" in exI)\n         apply (rule_tac x=\"0\" in exI)\n        using Ssub hull_subset by fastforce\n    qed\n  next\n    case False\n    then obtain a' b' where \"a' \\<noteq> 0\" \n      and le: \"affine hull S \\<inter> {x. a' \\<bullet> x \\<le> b'} = affine hull S \\<inter> {x. - a \\<bullet> x \\<le> - b}\" \n      and eq: \"affine hull S \\<inter> {x. a' \\<bullet> x = b'} = affine hull S \\<inter> {x. - a \\<bullet> x = - b}\" \n      and mem: \"\\<And>w. w \\<in> affine hull S \\<Longrightarrow> w + a' \\<in> affine hull S\"\n      using affine_parallel_slice affine_affine_hull by metis \n    show ?thesis\n    proof (intro conjI impI allI ballI exI)\n      have *: \"S \\<subseteq> - (affine hull S \\<inter> {x. P x}) \\<union> affine hull S \\<inter> {x. Q x} \\<Longrightarrow> S \\<subseteq> {x. ~P x \\<or> Q x}\" \n        for P Q \n        using hull_subset by fastforce  \n      have \"S \\<subseteq> {x. ~ (a' \\<bullet> x \\<le> b') \\<or> a' \\<bullet> x = b'}\"\n        apply (rule *)\n        apply (simp only: le eq)\n        using Ssub by auto\n      then show \"S \\<subseteq> {x. - a' \\<bullet> x \\<le> - b'}\"\n        by auto \n      show \"S \\<inter> {x. a \\<bullet> x = b} = S \\<inter> {x. - a' \\<bullet> x = - b'}\"\n        using eq hull_subset [of S affine] by force\n      show \"\\<lbrakk>S \\<inter> {x. a \\<bullet> x = b} \\<noteq> {}; S \\<inter> {x. a \\<bullet> x = b} \\<noteq> S\\<rbrakk> \\<Longrightarrow> - a' \\<noteq> 0\"\n        using \\<open>a' \\<noteq> 0\\<close> by auto\n      show \"w + - a' \\<in> affine hull S\"\n        if \"S \\<inter> {x. a \\<bullet> x = b} \\<noteq> S\" \"w \\<in> affine hull S\" for w\n      proof -\n        have \"w + 1 *\\<^sub>R (w - (w + a')) \\<in> affine hull S\"\n          using affine_affine_hull mem mem_affine_3_minus that(2) by blast\n        then show ?thesis  by simp\n      qed\n    qed\n  qed\nqed\nnext\n  assume ?rhs then show ?lhs\n    unfolding exposed_face_of_def by blast\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           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            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 ((\\<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_base)\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 ((+) (- a) ` S)\"\n      by (simp add: \\<open>compact S\\<close> compact_translation)\n    have 2: \"convex ((+) (- 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\nlemma face_of_convex_hull_aux:\n  assumes eq: \"x *\\<^sub>R p = u *\\<^sub>R a + v *\\<^sub>R b + w *\\<^sub>R c\"\n    and x: \"u + v + w = x\" \"x \\<noteq> 0\" and S: \"affine S\" \"a \\<in> S\" \"b \\<in> S\" \"c \\<in> S\"\n  shows \"p \\<in> S\"\nproof -\n  have \"p = (u *\\<^sub>R a + v *\\<^sub>R b + w *\\<^sub>R c) /\\<^sub>R x\"\n    by (metis \\<open>x \\<noteq> 0\\<close> eq mult.commute right_inverse scaleR_one scaleR_scaleR)\n  moreover have \"affine hull {a,b,c} \\<subseteq> S\"\n    by (simp add: S hull_minimal)\n  moreover have \"(u *\\<^sub>R a + v *\\<^sub>R b + w *\\<^sub>R c) /\\<^sub>R x \\<in> affine hull {a,b,c}\"\n    apply (simp add: affine_hull_3)\n    apply (rule_tac x=\"u/x\" in exI)\n    apply (rule_tac x=\"v/x\" in exI)\n    apply (rule_tac x=\"w/x\" in exI)\n    using x apply (auto simp: algebra_simps divide_simps)\n    done\n  ultimately show ?thesis by force\nqed\n\nproposition face_of_convex_hull_insert_eq:\n  fixes a :: \"'a :: euclidean_space\"\n  assumes \"finite S\" and a: \"a \\<notin> affine hull S\"\n  shows \"(F face_of (convex hull (insert a S)) \\<longleftrightarrow>\n          F face_of (convex hull S) \\<or>\n          (\\<exists>F'. F' face_of (convex hull S) \\<and> F = convex hull (insert a F')))\"\n         (is \"F face_of ?CAS \\<longleftrightarrow> _\")\nproof safe\n  assume F: \"F face_of ?CAS\"\n    and *: \"\\<nexists>F'. F' face_of convex hull S \\<and> F = convex hull insert a F'\"\n  obtain T where T: \"T \\<subseteq> insert a S\" and FeqT: \"F = convex hull T\"\n    by (metis F \\<open>finite S\\<close> compact_insert finite_imp_compact face_of_convex_hull_subset)\n  show \"F face_of convex hull S\"\n  proof (cases \"a \\<in> T\")\n    case True\n    have \"F = convex hull insert a (convex hull T \\<inter> convex hull S)\"\n    proof\n      have \"T \\<subseteq> insert a (convex hull T \\<inter> convex hull S)\"\n        using T hull_subset by fastforce\n      then show \"F \\<subseteq> convex hull insert a (convex hull T \\<inter> convex hull S)\"\n        by (simp add: FeqT hull_mono)\n      show \"convex hull insert a (convex hull T \\<inter> convex hull S) \\<subseteq> F\"\n        apply (rule hull_minimal)\n        using True by (auto simp: \\<open>F = convex hull T\\<close> hull_inc)\n    qed\n    moreover have \"convex hull T \\<inter> convex hull S face_of convex hull S\"\n      by (metis F FeqT convex_convex_hull face_of_slice hull_mono inf.absorb_iff2 subset_insertI)\n    ultimately show ?thesis\n      using * by force\n  next\n    case False\n    then show ?thesis\n      by (metis FeqT F T face_of_subset hull_mono subset_insert subset_insertI)\n  qed\nnext\n  assume \"F face_of convex hull S\"\n  show \"F face_of ?CAS\"\n    by (simp add: \\<open>F face_of convex hull S\\<close> a face_of_convex_hull_insert \\<open>finite S\\<close>)\nnext\n  fix F\n  assume F: \"F face_of convex hull S\"\n  show \"convex hull insert a F face_of ?CAS\"\n  proof (cases \"S = {}\")\n    case True\n    then show ?thesis\n      using F face_of_affine_eq by auto\n  next\n    case False\n    have anotc: \"a \\<notin> convex hull S\"\n      by (metis (no_types) a affine_hull_convex_hull hull_inc)\n    show ?thesis\n    proof (cases \"F = {}\")\n      case True show ?thesis\n        using anotc by (simp add: \\<open>F = {}\\<close> \\<open>finite S\\<close> extreme_point_of_convex_hull_insert face_of_singleton)\n    next\n      case False\n      have \"convex hull insert a F \\<subseteq> ?CAS\"\n        by (simp add: F a \\<open>finite S\\<close> convex_hull_subset face_of_convex_hull_insert face_of_imp_subset hull_inc)\n      moreover\n      have \"(\\<exists>y v. (1 - ub) *\\<^sub>R a + ub *\\<^sub>R b = (1 - v) *\\<^sub>R a + v *\\<^sub>R y \\<and>\n                   0 \\<le> v \\<and> v \\<le> 1 \\<and> y \\<in> F) \\<and>\n            (\\<exists>x u. (1 - uc) *\\<^sub>R a + uc *\\<^sub>R c = (1 - u) *\\<^sub>R a + u *\\<^sub>R x \\<and>\n                   0 \\<le> u \\<and> u \\<le> 1 \\<and> x \\<in> F)\"\n        if *: \"(1 - ux) *\\<^sub>R a + ux *\\<^sub>R x\n               \\<in> open_segment ((1 - ub) *\\<^sub>R a + ub *\\<^sub>R b) ((1 - uc) *\\<^sub>R a + uc *\\<^sub>R c)\"\n          and \"0 \\<le> ub\" \"ub \\<le> 1\" \"0 \\<le> uc\" \"uc \\<le> 1\" \"0 \\<le> ux\" \"ux \\<le> 1\"\n          and b: \"b \\<in> convex hull S\" and c: \"c \\<in> convex hull S\" and \"x \\<in> F\"\n        for b c ub uc ux x\n      proof -\n        obtain v where ne: \"(1 - ub) *\\<^sub>R a + ub *\\<^sub>R b \\<noteq> (1 - uc) *\\<^sub>R a + uc *\\<^sub>R c\"\n          and eq: \"(1 - ux) *\\<^sub>R a + ux *\\<^sub>R x =\n                    (1 - v) *\\<^sub>R ((1 - ub) *\\<^sub>R a + ub *\\<^sub>R b) + v *\\<^sub>R ((1 - uc) *\\<^sub>R a + uc *\\<^sub>R c)\"\n          and \"0 < v\" \"v < 1\"\n          using * by (auto simp: in_segment)\n        then have 0: \"((1 - ux) - ((1 - v) * (1 - ub) + v * (1 - uc))) *\\<^sub>R a +\n                      (ux *\\<^sub>R x - (((1 - v) * ub) *\\<^sub>R b + (v * uc) *\\<^sub>R c)) = 0\"\n          by (auto simp: algebra_simps)\n        then have \"((1 - ux) - ((1 - v) * (1 - ub) + v * (1 - uc))) *\\<^sub>R a =\n                   ((1 - v) * ub) *\\<^sub>R b + (v * uc) *\\<^sub>R c + (-ux) *\\<^sub>R x\"\n          by (auto simp: algebra_simps)\n        then have \"a \\<in> affine hull S\" if \"1 - ux - ((1 - v) * (1 - ub) + v * (1 - uc)) \\<noteq> 0\"\n          apply (rule face_of_convex_hull_aux)\n          using b c that apply (auto simp: algebra_simps)\n          using F convex_hull_subset_affine_hull face_of_imp_subset \\<open>x \\<in> F\\<close> apply blast+\n          done\n        then have \"1 - ux - ((1 - v) * (1 - ub) + v * (1 - uc)) = 0\"\n          using a by blast\n        with 0 have equx: \"(1 - v) * ub + v * uc = ux\"\n          and uxx: \"ux *\\<^sub>R x = (((1 - v) * ub) *\\<^sub>R b + (v * uc) *\\<^sub>R c)\"\n          by auto (auto simp: algebra_simps)\n        show ?thesis\n        proof (cases \"uc = 0\")\n          case True\n          then show ?thesis\n            using equx 0 \\<open>0 \\<le> ub\\<close> \\<open>ub \\<le> 1\\<close> \\<open>v < 1\\<close> \\<open>x \\<in> F\\<close>\n            apply (auto simp: algebra_simps)\n             apply (rule_tac x=x in exI, simp)\n             apply (rule_tac x=ub in exI, auto)\n             apply (metis add.left_neutral diff_eq_eq less_irrefl mult.commute mult_cancel_right1 real_vector.scale_cancel_left real_vector.scale_left_diff_distrib)\n            using \\<open>x \\<in> F\\<close> \\<open>uc \\<le> 1\\<close> apply blast\n            done\n        next\n          case False\n          show ?thesis\n          proof (cases \"ub = 0\")\n            case True\n            then show ?thesis\n              using equx 0 \\<open>0 \\<le> uc\\<close> \\<open>uc \\<le> 1\\<close> \\<open>0 < v\\<close> \\<open>x \\<in> F\\<close> \\<open>uc \\<noteq> 0\\<close> by (force simp: algebra_simps)\n          next\n            case False\n            then have \"0 < ub\" \"0 < uc\"\n              using \\<open>uc \\<noteq> 0\\<close> \\<open>0 \\<le> ub\\<close> \\<open>0 \\<le> uc\\<close> by auto\n            then have \"ux \\<noteq> 0\"\n              by (metis \\<open>0 < v\\<close> \\<open>v < 1\\<close> diff_ge_0_iff_ge dual_order.strict_implies_order equx leD le_add_same_cancel2 zero_le_mult_iff zero_less_mult_iff)\n            have \"b \\<in> F \\<and> c \\<in> F\"\n            proof (cases \"b = c\")\n              case True\n              then show ?thesis\n                by (metis \\<open>ux \\<noteq> 0\\<close> equx real_vector.scale_cancel_left scaleR_add_left uxx \\<open>x \\<in> F\\<close>)\n            next\n              case False\n              have \"x = (((1 - v) * ub) *\\<^sub>R b + (v * uc) *\\<^sub>R c) /\\<^sub>R ux\"\n                by (metis \\<open>ux \\<noteq> 0\\<close> uxx mult.commute right_inverse scaleR_one scaleR_scaleR)\n              also have \"... = (1 - v * uc / ux) *\\<^sub>R b + (v * uc / ux) *\\<^sub>R c\"\n                using \\<open>ux \\<noteq> 0\\<close> equx apply (auto simp: algebra_simps divide_simps)\n                by (metis add.commute add_diff_eq add_divide_distrib diff_add_cancel scaleR_add_left)\n              finally have \"x = (1 - v * uc / ux) *\\<^sub>R b + (v * uc / ux) *\\<^sub>R c\" .\n              then have \"x \\<in> open_segment b c\"\n                apply (simp add: in_segment \\<open>b \\<noteq> c\\<close>)\n                apply (rule_tac x=\"(v * uc) / ux\" in exI)\n                using \\<open>0 \\<le> ux\\<close> \\<open>ux \\<noteq> 0\\<close> \\<open>0 < uc\\<close> \\<open>0 < v\\<close> \\<open>0 < ub\\<close> \\<open>v < 1\\<close> equx\n                apply (force simp: algebra_simps divide_simps)\n                done\n              then show ?thesis\n                by (rule face_ofD [OF F _ b c \\<open>x \\<in> F\\<close>])\n            qed\n            with \\<open>0 \\<le> ub\\<close> \\<open>ub \\<le> 1\\<close> \\<open>0 \\<le> uc\\<close> \\<open>uc \\<le> 1\\<close> show ?thesis by blast\n          qed\n        qed\n      qed\n      moreover have \"convex hull F = F\"\n        by (meson F convex_hull_eq face_of_imp_convex)\n      ultimately show ?thesis\n        unfolding face_of_def by (fastforce simp: convex_hull_insert_alt \\<open>S \\<noteq> {}\\<close> \\<open>F \\<noteq> {}\\<close>)\n    qed\n  qed\nqed\n\nlemma face_of_convex_hull_insert2:\n  fixes a :: \"'a :: euclidean_space\"\n  assumes S: \"finite S\" and a: \"a \\<notin> affine hull S\" and F: \"F face_of convex hull S\"\n  shows \"convex hull (insert a F) face_of convex hull (insert a S)\"\n  by (metis F face_of_convex_hull_insert_eq [OF S a])\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 ((hull) convex ` {T. T \\<subseteq> v})\"\n    by (simp add: \\<open>finite v\\<close>)\n  moreover have \"{F. F face_of S} \\<subseteq> ((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\nlemma face_of_polytope_insert:\n     \"\\<lbrakk>polytope S; a \\<notin> affine hull S; F face_of S\\<rbrakk> \\<Longrightarrow> F face_of convex hull (insert a S)\"\n  by (metis (no_types, lifting) affine_hull_convex_hull face_of_convex_hull_insert hull_insert polytope_def)\n\nlemma face_of_polytope_insert2:\n  fixes a :: \"'a :: euclidean_space\"\n  assumes \"polytope S\" \"a \\<notin> affine hull S\" \"F face_of S\"\n  shows \"convex hull (insert a F) face_of convex hull (insert a S)\"\nproof -\n  obtain V where \"finite V\" \"S = convex hull V\"\n    using assms by (auto simp: polytope_def)\n  then have \"convex hull (insert a F) face_of convex hull (insert a V)\"\n    using affine_hull_convex_hull assms face_of_convex_hull_insert2 by blast\n  then show ?thesis\n    by (metis \\<open>S = convex hull V\\<close> hull_insert)\nqed\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\" shows \"polyhedron c\"\nby (metis assms face_of_imp_eq_affine_Int polyhedron_Int polyhedron_affine_hull 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 ((\\<in>) x) \\<notin> Collect ((\\<in>) (\\<Union>{A. A facet_of S}))\"\n        using xnot by fastforce\n      then have \"F \\<notin> Collect ((\\<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 ((`) 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)\"\n  by (subst polyhedron_linear_image_eq)\n    (auto simp: bij_uminus intro!: linear_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_eq_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_eq_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\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>\\<G>. \\<Union>\\<G> = \\<Union>\\<F> \\<and>\n                 finite \\<G> \\<and>\n                 (\\<forall>C \\<in> \\<G>. \\<exists>D. D \\<in> \\<F> \\<and> C \\<subseteq> D) \\<and>\n                 (\\<forall>C \\<in> \\<F>. \\<forall>x \\<in> C. \\<exists>D. D \\<in> \\<G> \\<and> x \\<in> D \\<and> D \\<subseteq> C) \\<and>\n                 (\\<forall>X \\<in> \\<G>. polytope X) \\<and>\n                 (\\<forall>X \\<in> \\<G>. aff_dim X \\<le> d) \\<and>\n                 (\\<forall>X \\<in> \\<G>. \\<forall>Y \\<in> \\<G>. X \\<inter> Y face_of X \\<and> X \\<inter> Y face_of Y) \\<and>\n                 (\\<forall>X \\<in> \\<G>. \\<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) (auto simp: assms)\nnext\n  case (insert ab I)\n  then obtain \\<G> where eq: \"\\<Union>\\<G> = \\<Union>\\<F>\" and \"finite \\<G>\"\n                   and sub1: \"\\<And>C. C \\<in> \\<G> \\<Longrightarrow> \\<exists>D. D \\<in> \\<F> \\<and> C \\<subseteq> D\"\n                   and sub2: \"\\<And>C x. C \\<in> \\<F> \\<and> x \\<in> C \\<Longrightarrow> \\<exists>D. D \\<in> \\<G> \\<and> x \\<in> D \\<and> D \\<subseteq> C\"\n                   and poly: \"\\<And>X. X \\<in> \\<G> \\<Longrightarrow> polytope X\"\n                   and aff: \"\\<And>X. X \\<in> \\<G> \\<Longrightarrow> aff_dim X \\<le> d\"\n                   and face: \"\\<And>X Y. \\<lbrakk>X \\<in> \\<G>; Y \\<in> \\<G>\\<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> \\<G>; 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}) ` \\<G> \\<union> (\\<lambda>X. X \\<inter> {x. a \\<bullet> x \\<ge> b}) ` \\<G>\"\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 \\<G>\\<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    show \"\\<forall>C \\<in> ?\\<G>. \\<exists>D. D \\<in> \\<F> \\<and> C \\<subseteq> D\"\n      using sub1 by force\n    show \"\\<forall>C\\<in>\\<F>. \\<forall>x\\<in>C. \\<exists>D. D \\<in> ?\\<G> \\<and> x \\<in> D \\<and> D \\<subseteq> C\"\n    proof (intro ballI)\n      fix C z\n      assume \"C \\<in> \\<F>\" \"z \\<in> C\"\n      with sub2 obtain D where D: \"D \\<in> \\<G>\" \"z \\<in> D\" \"D \\<subseteq> C\" by blast\n      have \"D \\<in> \\<G> \\<and> z \\<in> D \\<inter> {x. a \\<bullet> x \\<le> b} \\<and> D \\<inter> {x. a \\<bullet> x \\<le> b} \\<subseteq> C \\<or>\n            D \\<in> \\<G> \\<and> z \\<in> D \\<inter> {x. a \\<bullet> x \\<ge> b} \\<and> D \\<inter> {x. a \\<bullet> x \\<ge> b} \\<subseteq> C\"\n        using linorder_class.linear [of \"a \\<bullet> z\" b] D by blast\n      then show \"\\<exists>D. D \\<in> ?\\<G> \\<and> z \\<in> D \\<and> D \\<subseteq> C\"\n        by blast\n    qed\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\"\n                \"\\<And>C. C \\<in> \\<F>' \\<Longrightarrow> \\<exists>D. D \\<in> \\<F> \\<and> C \\<subseteq> D\"\n                \"\\<And>C x. C \\<in> \\<F> \\<and> x \\<in> C \\<Longrightarrow> \\<exists>D. D \\<in> \\<F>' \\<and> x \\<in> D \\<and> D \\<subseteq> C\"\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              and sub1: \"\\<And>C. C \\<in> \\<F>' \\<Longrightarrow> \\<exists>D. D \\<in> \\<F> \\<and> C \\<subseteq> D\"\n              and sub2: \"\\<And>C x. C \\<in> \\<F> \\<and> x \\<in> C \\<Longrightarrow> \\<exists>D. D \\<in> \\<F>' \\<and> x \\<in> D \\<and> D \\<subseteq> C\"\n    apply (rule exE [OF cell_subdivision_lemma])\n    using assms \\<open>finite I\\<close> apply auto\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 sub1 sub2 \\<open>finite \\<F>'\\<close>)\nqed\n\n\nsubsection\\<open>Simplexes\\<close>\n\ntext\\<open>The notion of n-simplex for integer @{term\"n \\<ge> -1\"}\\<close>\ndefinition simplex :: \"int \\<Rightarrow> 'a::euclidean_space set \\<Rightarrow> bool\" (infix \"simplex\" 50)\n  where \"n simplex S \\<equiv> \\<exists>C. ~(affine_dependent C) \\<and> int(card C) = n + 1 \\<and> S = convex hull C\"\n\nlemma simplex:\n    \"n simplex S \\<longleftrightarrow> (\\<exists>C. finite C \\<and>\n                       ~(affine_dependent C) \\<and>\n                       int(card C) = n + 1 \\<and>\n                       S = convex hull C)\"\n  by (auto simp add: simplex_def intro: aff_independent_finite)\n\nlemma simplex_convex_hull:\n   \"~affine_dependent C \\<and> int(card C) = n + 1 \\<Longrightarrow> n simplex (convex hull C)\"\n  by (auto simp add: simplex_def)\n\nlemma convex_simplex: \"n simplex S \\<Longrightarrow> convex S\"\n  by (metis convex_convex_hull simplex_def)\n\nlemma compact_simplex: \"n simplex S \\<Longrightarrow> compact S\"\n  unfolding simplex\n  using finite_imp_compact_convex_hull by blast\n\nlemma closed_simplex: \"n simplex S \\<Longrightarrow> closed S\"\n  by (simp add: compact_imp_closed compact_simplex)\n\nlemma simplex_imp_polytope:\n   \"n simplex S \\<Longrightarrow> polytope S\"\n  unfolding simplex_def polytope_def\n  using aff_independent_finite by blast\n\nlemma simplex_imp_polyhedron:\n   \"n simplex S \\<Longrightarrow> polyhedron S\"\n  by (simp add: polytope_imp_polyhedron simplex_imp_polytope)\n\nlemma simplex_dim_ge: \"n simplex S \\<Longrightarrow> -1 \\<le> n\"\n  by (metis (no_types, hide_lams) aff_dim_geq affine_independent_iff_card diff_add_cancel diff_diff_eq2 simplex_def)\n\nlemma simplex_empty [simp]: \"n simplex {} \\<longleftrightarrow> n = -1\"\nproof\n  assume \"n simplex {}\"\n  then show \"n = -1\"\n    unfolding simplex by (metis card_empty convex_hull_eq_empty diff_0 diff_eq_eq of_nat_0)\nnext\n  assume \"n = -1\" then show \"n simplex {}\"\n    by (fastforce simp: simplex)\nqed\n\nlemma simplex_minus_1 [simp]: \"-1 simplex S \\<longleftrightarrow> S = {}\"\n  by (metis simplex cancel_comm_monoid_add_class.diff_cancel card_0_eq diff_minus_eq_add of_nat_eq_0_iff simplex_empty)\n\n\nlemma aff_dim_simplex:\n   \"n simplex S \\<Longrightarrow> aff_dim S = n\"\n  by (metis simplex add.commute add_diff_cancel_left' aff_dim_convex_hull affine_independent_iff_card)\n\nlemma zero_simplex_sing: \"0 simplex {a}\"\n  apply (simp add: simplex_def)\n  by (metis affine_independent_1 card_empty card_insert_disjoint convex_hull_singleton empty_iff finite.emptyI)\n\nlemma simplex_sing [simp]: \"n simplex {a} \\<longleftrightarrow> n = 0\"\n  using aff_dim_simplex aff_dim_sing zero_simplex_sing by blast\n\nlemma simplex_zero: \"0 simplex S \\<longleftrightarrow> (\\<exists>a. S = {a})\"\napply (auto simp: )\n  using aff_dim_eq_0 aff_dim_simplex by blast\n\nlemma one_simplex_segment: \"a \\<noteq> b \\<Longrightarrow> 1 simplex closed_segment a b\"\n  apply (simp add: simplex_def)\n  apply (rule_tac x=\"{a,b}\" in exI)\n  apply (auto simp: segment_convex_hull)\n  done\n\nlemma simplex_segment_cases:\n   \"(if a = b then 0 else 1) simplex closed_segment a b\"\n  by (auto simp: one_simplex_segment)\n\nlemma simplex_segment:\n   \"\\<exists>n. n simplex closed_segment a b\"\n  using simplex_segment_cases by metis\n\nlemma polytope_lowdim_imp_simplex:\n  assumes \"polytope P\" \"aff_dim P \\<le> 1\"\n  obtains n where \"n simplex P\"\nproof (cases \"P = {}\")\n  case True\n  then show ?thesis\n    by (simp add: that)\nnext\n  case False\n  then show ?thesis\n    by (metis assms compact_convex_collinear_segment collinear_aff_dim polytope_imp_compact polytope_imp_convex simplex_segment_cases that)\nqed\n\nlemma simplex_insert_dimplus1:\n  fixes n::int\n  assumes \"n simplex S\" and a: \"a \\<notin> affine hull S\"\n  shows \"(n+1) simplex (convex hull (insert a S))\"\nproof -\n  obtain C where C: \"finite C\" \"~(affine_dependent C)\" \"int(card C) = n+1\" and S: \"S = convex hull C\"\n    using assms unfolding simplex by force\n  show ?thesis\n    unfolding simplex\n  proof (intro exI conjI)\n      have \"aff_dim S = n\"\n        using aff_dim_simplex assms(1) by blast\n      moreover have \"a \\<notin> affine hull C\"\n        using S a affine_hull_convex_hull by blast\n      moreover have \"a \\<notin> C\"\n          using S a hull_inc by fastforce\n      ultimately show \"\\<not> affine_dependent (insert a C)\"\n        by (simp add: C S aff_dim_convex_hull aff_dim_insert affine_independent_iff_card)\n  next\n    have \"a \\<notin> C\"\n      using S a hull_inc by fastforce\n    then show \"int (card (insert a C)) = n + 1 + 1\"\n      by (simp add: C)\n  next\n    show \"convex hull insert a S = convex hull (insert a C)\"\n      by (simp add: S convex_hull_insert_segments)\n  qed (use C in auto)\nqed\n\nsubsection\\<open>Simplicial complexes and triangulations\\<close>\n\ndefinition triangulation where\n \"triangulation \\<T> \\<equiv>\n        finite \\<T> \\<and>\n        (\\<forall>T \\<in> \\<T>. \\<exists>n. n simplex T) \\<and>\n        (\\<forall>T T'. T \\<in> \\<T> \\<and> T' \\<in> \\<T>\n                \\<longrightarrow> (T \\<inter> T') face_of T \\<and> (T \\<inter> T') face_of T')\"\n\ndefinition simplicial_complex where\n \"simplicial_complex \\<C> \\<equiv>\n        finite \\<C> \\<and>\n        (\\<forall>S \\<in> \\<C>. \\<exists>n. n simplex S) \\<and>\n        (\\<forall>S S'. S \\<in> \\<C> \\<and> S' \\<in> \\<C>\n                \\<longrightarrow> (S \\<inter> S') face_of S \\<and> (S \\<inter> S') face_of S') \\<and>\n        (\\<forall>F S. S \\<in> \\<C> \\<and> F face_of S \\<longrightarrow> F \\<in> \\<C>)\"\n\ntext\\<open>A simplicial complex is equivalent to a triangulation that also includes all sub-faces.\\<close>\n\nlemma simplicial_complex_is_triangulation:\n  \"simplicial_complex \\<C> \\<equiv> triangulation \\<C> \\<and> (\\<forall>F S. S \\<in> \\<C> \\<and> F face_of S \\<longrightarrow> F \\<in> \\<C>)\"\n  unfolding triangulation_def simplicial_complex_def by simp\n\n\nsubsection\\<open>Refining a cell complex to a simplicial complex\\<close>\n\nlemma convex_hull_insert_Int_eq:\n  fixes z :: \"'a :: euclidean_space\"\n  assumes z: \"z \\<in> rel_interior S\"\n      and T: \"T \\<subseteq> rel_frontier S\"\n      and U: \"U \\<subseteq> rel_frontier S\"\n      and \"convex S\" \"convex T\" \"convex U\"\n  shows \"convex hull (insert z T) \\<inter> convex hull (insert z U) = convex hull (insert z (T \\<inter> U))\"\n    (is \"?lhs = ?rhs\")\nproof\n  show \"?lhs \\<subseteq> ?rhs\"\n  proof (cases \"T={} \\<or> U={}\")\n    case True then show ?thesis by auto\n  next\n    case False\n    then have \"T \\<noteq> {}\" \"U \\<noteq> {}\" by auto\n    have TU: \"convex (T \\<inter> U)\"\n      by (simp add: \\<open>convex T\\<close> \\<open>convex U\\<close> convex_Int)\n    have \"(\\<Union>x\\<in>T. closed_segment z x) \\<inter> (\\<Union>x\\<in>U. closed_segment z x)\n          \\<subseteq> (if T \\<inter> U = {} then {z} else UNION (T \\<inter> U) (closed_segment z))\" (is \"_ \\<subseteq> ?IF\")\n    proof clarify\n      fix x t u\n      assume xt: \"x \\<in> closed_segment z t\"\n        and xu: \"x \\<in> closed_segment z u\"\n        and \"t \\<in> T\" \"u \\<in> U\"\n      then have ne: \"t \\<noteq> z\" \"u \\<noteq> z\"\n        using T U z unfolding rel_frontier_def by blast+\n      show \"x \\<in> ?IF\"\n      proof (cases \"x = z\")\n        case True then show ?thesis by auto\n      next\n        case False\n        have t: \"t \\<in> closure S\"\n          using T \\<open>t \\<in> T\\<close> rel_frontier_def by auto\n        have u: \"u \\<in> closure S\"\n          using U \\<open>u \\<in> U\\<close> rel_frontier_def by auto\n        show ?thesis\n        proof (cases \"t = u\")\n          case True\n          then show ?thesis\n            using \\<open>t \\<in> T\\<close> \\<open>u \\<in> U\\<close> xt by auto\n        next\n          case False\n          have tnot: \"t \\<notin> closed_segment u z\"\n          proof -\n            have \"t \\<in> closure S - rel_interior S\"\n              using T \\<open>t \\<in> T\\<close> rel_frontier_def by blast\n            then have \"t \\<notin> open_segment z u\"\n              by (meson DiffD2 rel_interior_closure_convex_segment [OF \\<open>convex S\\<close> z u] subsetD)\n            then show ?thesis\n              by (simp add: \\<open>t \\<noteq> u\\<close> \\<open>t \\<noteq> z\\<close> open_segment_commute open_segment_def)\n          qed\n          moreover have \"u \\<notin> closed_segment z t\"\n            using rel_interior_closure_convex_segment [OF \\<open>convex S\\<close> z t] \\<open>u \\<in> U\\<close> \\<open>u \\<noteq> z\\<close>\n              U [unfolded rel_frontier_def] tnot\n            by (auto simp: closed_segment_eq_open)\n          ultimately\n          have \"~(between (t,u) z | between (u,z) t | between (z,t) u)\" if \"x \\<noteq> z\"\n            using that xt xu\n            apply (simp add: between_mem_segment [symmetric])\n            by (metis between_commute between_trans_2 between_antisym)\n          then have \"~ collinear {t, z, u}\" if \"x \\<noteq> z\"\n            by (auto simp: that collinear_between_cases between_commute)\n          moreover have \"collinear {t, z, x}\"\n            by (metis closed_segment_commute collinear_2 collinear_closed_segment collinear_triples ends_in_segment(1) insert_absorb insert_absorb2 xt)\n          moreover have \"collinear {z, x, u}\"\n            by (metis closed_segment_commute collinear_2 collinear_closed_segment collinear_triples ends_in_segment(1) insert_absorb insert_absorb2 xu)\n          ultimately have False\n            using collinear_3_trans [of t z x u] \\<open>x \\<noteq> z\\<close> by blast\n          then show ?thesis by metis\n        qed\n      qed\n    qed\n    then show ?thesis\n      using False \\<open>convex T\\<close> \\<open>convex U\\<close> TU\n      by (simp add: convex_hull_insert_segments hull_same split: if_split_asm)\n  qed\n  show \"?rhs \\<subseteq> ?lhs\"\n    by (metis inf_greatest hull_mono inf.cobounded1 inf.cobounded2 insert_mono)\nqed\n\nlemma simplicial_subdivision_aux:\n  assumes \"finite \\<M>\"\n      and \"\\<And>C. C \\<in> \\<M> \\<Longrightarrow> polytope C\"\n      and \"\\<And>C. C \\<in> \\<M> \\<Longrightarrow> aff_dim C \\<le> of_nat n\"\n      and \"\\<And>C F. \\<lbrakk>C \\<in> \\<M>; F face_of C\\<rbrakk> \\<Longrightarrow> F \\<in> \\<M>\"\n      and \"\\<And>C1 C2. \\<lbrakk>C1 \\<in> \\<M>; C2 \\<in> \\<M>\\<rbrakk> \\<Longrightarrow> C1 \\<inter> C2 face_of C1 \\<and> C1 \\<inter> C2 face_of C2\"\n    shows \"\\<exists>\\<T>. simplicial_complex \\<T> \\<and>\n                (\\<forall>K \\<in> \\<T>. aff_dim K \\<le> of_nat n) \\<and>\n                \\<Union>\\<T> = \\<Union>\\<M> \\<and>\n                (\\<forall>C \\<in> \\<M>. \\<exists>F. finite F \\<and> F \\<subseteq> \\<T> \\<and> C = \\<Union>F) \\<and>\n                (\\<forall>K \\<in> \\<T>. \\<exists>C. C \\<in> \\<M> \\<and> K \\<subseteq> C)\"\n  using assms\nproof (induction n arbitrary: \\<M> rule: less_induct)\n  case (less n)\n  then have poly\\<M>: \"\\<And>C. C \\<in> \\<M> \\<Longrightarrow> polytope C\"\n      and aff\\<M>:    \"\\<And>C. C \\<in> \\<M> \\<Longrightarrow> aff_dim C \\<le> of_nat n\"\n      and face\\<M>:   \"\\<And>C F. \\<lbrakk>C \\<in> \\<M>; F face_of C\\<rbrakk> \\<Longrightarrow> F \\<in> \\<M>\"\n      and intface\\<M>: \"\\<And>C1 C2. \\<lbrakk>C1 \\<in> \\<M>; C2 \\<in> \\<M>\\<rbrakk> \\<Longrightarrow> C1 \\<inter> C2 face_of C1 \\<and> C1 \\<inter> C2 face_of C2\"\n    by simp+\n  show ?case\n  proof (cases \"n \\<le> 1\")\n    case True\n    have \"\\<And>s. \\<lbrakk>n \\<le> 1; s \\<in> \\<M>\\<rbrakk> \\<Longrightarrow> \\<exists>m. m simplex s\"\n      using poly\\<M> aff\\<M> by (force intro: polytope_lowdim_imp_simplex)\n    then show ?thesis\n      unfolding simplicial_complex_def\n      apply (rule_tac x=\"\\<M>\" in exI)\n      using True by (auto simp: less.prems)\n  next\n    case False\n    define \\<S> where \"\\<S> \\<equiv> {C \\<in> \\<M>. aff_dim C < n}\"\n    have \"finite \\<S>\" \"\\<And>C. C \\<in> \\<S> \\<Longrightarrow> polytope C\" \"\\<And>C. C \\<in> \\<S> \\<Longrightarrow> aff_dim C \\<le> int (n - 1)\"\n         \"\\<And>C F. \\<lbrakk>C \\<in> \\<S>; F face_of C\\<rbrakk> \\<Longrightarrow> F \\<in> \\<S>\"\n         \"\\<And>C1 C2. \\<lbrakk>C1 \\<in> \\<S>; C2 \\<in> \\<S>\\<rbrakk>  \\<Longrightarrow> C1 \\<inter> C2 face_of C1 \\<and> C1 \\<inter> C2 face_of C2\"\n      using less.prems\n      apply (auto simp: \\<S>_def)\n      by (metis aff_dim_subset face_of_imp_subset less_le not_le)\n    with less.IH [of \"n-1\" \\<S>] False\n    obtain \\<U> where \"simplicial_complex \\<U>\"\n           and aff_dim\\<U>: \"\\<And>K. K \\<in> \\<U> \\<Longrightarrow> aff_dim K \\<le> int (n - 1)\"\n           and        \"\\<Union>\\<U> = \\<Union>\\<S>\"\n           and fin\\<U>:  \"\\<And>C. C \\<in> \\<S> \\<Longrightarrow> \\<exists>F. finite F \\<and> F \\<subseteq> \\<U> \\<and> C = \\<Union>F\"\n           and C\\<U>:    \"\\<And>K. K \\<in> \\<U> \\<Longrightarrow> \\<exists>C. C \\<in> \\<S> \\<and> K \\<subseteq> C\"\n      by auto\n    then have \"finite \\<U>\"\n         and simpl\\<U>: \"\\<And>S. S \\<in> \\<U> \\<Longrightarrow> \\<exists>n. n simplex S\"\n         and face\\<U>:  \"\\<And>F S. \\<lbrakk>S \\<in> \\<U>; F face_of S\\<rbrakk> \\<Longrightarrow> F \\<in> \\<U>\"\n         and faceI\\<U>: \"\\<And>S S'. \\<lbrakk>S \\<in> \\<U>; S' \\<in> \\<U>\\<rbrakk> \\<Longrightarrow> (S \\<inter> S') face_of S \\<and> (S \\<inter> S') face_of S'\"\n      by (auto simp: simplicial_complex_def)\n    define \\<N> where \"\\<N> \\<equiv> {C \\<in> \\<M>. aff_dim C = n}\"\n    have \"finite \\<N>\"\n      by (simp add: \\<N>_def less.prems(1))\n    have poly\\<N>: \"\\<And>C. C \\<in> \\<N> \\<Longrightarrow> polytope C\"\n      and convex\\<N>: \"\\<And>C. C \\<in> \\<N> \\<Longrightarrow> convex C\"\n      and closed\\<N>: \"\\<And>C. C \\<in> \\<N> \\<Longrightarrow> closed C\"\n      by (auto simp: \\<N>_def poly\\<M> polytope_imp_convex polytope_imp_closed)\n    have in_rel_interior: \"(SOME z. z \\<in> rel_interior C) \\<in> rel_interior C\" if \"C \\<in> \\<N>\" for C\n        using that poly\\<M> polytope_imp_convex rel_interior_aff_dim some_in_eq by (fastforce simp: \\<N>_def)\n    have *: \"\\<exists>T. ~affine_dependent T \\<and> card T \\<le> n \\<and> aff_dim K < n \\<and> K = convex hull T\"\n      if \"K \\<in> \\<U>\" for K\n    proof -\n      obtain r where r: \"r simplex K\"\n        using \\<open>K \\<in> \\<U>\\<close> simpl\\<U> by blast\n      have \"r = aff_dim K\"\n        using \\<open>r simplex K\\<close> aff_dim_simplex by blast\n      with r\n      show ?thesis\n        unfolding simplex_def\n        using False \\<open>\\<And>K. K \\<in> \\<U> \\<Longrightarrow> aff_dim K \\<le> int (n - 1)\\<close> that by fastforce\n    qed\n    have ahK_C_disjoint: \"affine hull K \\<inter> rel_interior C = {}\"\n      if \"C \\<in> \\<N>\" \"K \\<in> \\<U>\" \"K \\<subseteq> rel_frontier C\" for C K\n    proof -\n      have \"convex C\" \"closed C\"\n        by (auto simp: convex\\<N> closed\\<N> \\<open>C \\<in> \\<N>\\<close>)\n      obtain F where F: \"F face_of C\" and \"F \\<noteq> C\" \"K \\<subseteq> F\"\n      proof -\n        obtain L where \"L \\<in> \\<S>\" \"K \\<subseteq> L\"\n          using \\<open>K \\<in> \\<U>\\<close> C\\<U> by blast\n        have \"K \\<le> rel_frontier C\"\n          by (simp add: \\<open>K \\<subseteq> rel_frontier C\\<close>)\n        also have \"... \\<le> C\"\n          by (simp add: \\<open>closed C\\<close> rel_frontier_def subset_iff)\n        finally have \"K \\<subseteq> C\" .\n        have \"L \\<inter> C face_of C\"\n          using \\<N>_def \\<S>_def \\<open>C \\<in> \\<N>\\<close> \\<open>L \\<in> \\<S>\\<close> intface\\<M> by auto\n        moreover have \"L \\<inter> C \\<noteq> C\"\n          using \\<open>C \\<in> \\<N>\\<close> \\<open>L \\<in> \\<S>\\<close>\n          apply (clarsimp simp: \\<N>_def \\<S>_def)\n          by (metis aff_dim_subset inf_le1 not_le)\n        moreover have \"K \\<subseteq> L \\<inter> C\"\n          using \\<open>C \\<in> \\<N>\\<close> \\<open>L \\<in> \\<S>\\<close> \\<open>K \\<subseteq> C\\<close> \\<open>K \\<subseteq> L\\<close>\n          by (auto simp: \\<N>_def \\<S>_def)\n        ultimately show ?thesis using that by metis\n      qed\n      have \"affine hull F \\<inter> rel_interior C = {}\"\n        by (rule affine_hull_face_of_disjoint_rel_interior [OF \\<open>convex C\\<close> F \\<open>F \\<noteq> C\\<close>])\n      with hull_mono [OF \\<open>K \\<subseteq> F\\<close>]\n      show \"affine hull K \\<inter> rel_interior C = {}\"\n        by fastforce\n    qed\n    let ?\\<T> = \"(\\<Union>C \\<in> \\<N>. \\<Union>K \\<in> \\<U> \\<inter> Pow (rel_frontier C).\n                     {convex hull (insert (SOME z. z \\<in> rel_interior C) K)})\"\n    have \"\\<exists>\\<T>. simplicial_complex \\<T> \\<and>\n              (\\<forall>K \\<in> \\<T>. aff_dim K \\<le> of_nat n) \\<and>\n              (\\<forall>C \\<in> \\<M>. \\<exists>F. F \\<subseteq> \\<T> \\<and> C = \\<Union>F) \\<and>\n              (\\<forall>K \\<in> \\<T>. \\<exists>C. C \\<in> \\<M> \\<and> K \\<subseteq> C)\"\n    proof (rule exI, intro conjI ballI)\n      show \"simplicial_complex (\\<U> \\<union> ?\\<T>)\"\n        unfolding simplicial_complex_def\n      proof (intro conjI impI ballI allI)\n        show \"finite (\\<U> \\<union> ?\\<T>)\"\n          using \\<open>finite \\<U>\\<close> \\<open>finite \\<N>\\<close> by simp\n        show \"\\<exists>n. n simplex S\" if \"S \\<in> \\<U> \\<union> ?\\<T>\" for S\n          using that ahK_C_disjoint in_rel_interior simpl\\<U> simplex_insert_dimplus1 by fastforce\n        show \"F \\<in> \\<U> \\<union> ?\\<T>\" if S: \"S \\<in> \\<U> \\<union> ?\\<T> \\<and> F face_of S\" for F S\n        proof -\n          have \"F \\<in> \\<U>\" if \"S \\<in> \\<U>\"\n            using S face\\<U> that by blast\n          moreover have \"F \\<in> \\<U> \\<union> ?\\<T>\"\n            if \"F face_of S\" \"C \\<in> \\<N>\" \"K \\<in> \\<U>\" and \"K \\<subseteq> rel_frontier C\"\n              and S: \"S = convex hull insert (SOME z. z \\<in> rel_interior C) K\" for C K\n          proof -\n            let ?z = \"SOME z. z \\<in> rel_interior C\"\n            have \"?z \\<in> rel_interior C\"\n              by (simp add: in_rel_interior \\<open>C \\<in> \\<N>\\<close>)\n            moreover\n            obtain I where \"\\<not> affine_dependent I\" \"card I \\<le> n\" \"aff_dim K < int n\" \"K = convex hull I\"\n              using * [OF \\<open>K \\<in> \\<U>\\<close>] by auto\n            ultimately have \"?z \\<notin> affine hull I\"\n              using ahK_C_disjoint affine_hull_convex_hull that by blast\n            have \"compact I\" \"finite I\"\n              by (auto simp: \\<open>\\<not> affine_dependent I\\<close> aff_independent_finite finite_imp_compact)\n            moreover have \"F face_of convex hull insert ?z I\"\n              by (metis S \\<open>F face_of S\\<close> \\<open>K = convex hull I\\<close> convex_hull_eq_empty convex_hull_insert_segments hull_hull)\n            ultimately obtain J where \"J \\<subseteq> insert ?z I\" \"F = convex hull J\"\n              using face_of_convex_hull_subset [of \"insert ?z I\" F] by auto\n            show ?thesis\n            proof (cases \"?z \\<in> J\")\n              case True\n              have \"F \\<in> (\\<Union>K\\<in>\\<U> \\<inter> Pow (rel_frontier C). {convex hull insert ?z K})\"\n              proof\n                have \"convex hull (J - {?z}) face_of K\"\n                  by (metis True \\<open>J \\<subseteq> insert ?z I\\<close> \\<open>K = convex hull I\\<close> \\<open>\\<not> affine_dependent I\\<close> face_of_convex_hull_affine_independent subset_insert_iff)\n                then have \"convex hull (J - {?z}) \\<in> \\<U>\"\n                  by (rule face\\<U> [OF \\<open>K \\<in> \\<U>\\<close>])\n                moreover\n                have \"\\<And>x. x \\<in> convex hull (J - {?z}) \\<Longrightarrow> x \\<in> rel_frontier C\"\n                  by (metis True \\<open>J \\<subseteq> insert ?z I\\<close> \\<open>K = convex hull I\\<close> subsetD hull_mono subset_insert_iff that(4))\n                ultimately show \"convex hull (J - {?z}) \\<in> \\<U> \\<inter> Pow (rel_frontier C)\" by auto\n                let ?F = \"convex hull insert ?z (convex hull (J - {?z}))\"\n                have \"F \\<subseteq> ?F\"\n                  apply (clarsimp simp: \\<open>F = convex hull J\\<close>)\n                  by (metis True subsetD hull_mono hull_subset subset_insert_iff)\n                moreover have \"?F \\<subseteq> F\"\n                  apply (clarsimp simp: \\<open>F = convex hull J\\<close>)\n                  by (metis (no_types, lifting) True convex_hull_eq_empty convex_hull_insert_segments hull_hull insert_Diff)\n                ultimately\n                show \"F \\<in> {?F}\" by auto\n              qed\n              with \\<open>C\\<in>\\<N>\\<close> show ?thesis by auto\n            next\n              case False\n              then have \"F \\<in> \\<U>\"\n                using face_of_convex_hull_affine_independent [OF \\<open>\\<not> affine_dependent I\\<close>]\n                by (metis Int_absorb2 Int_insert_right_if0 \\<open>F = convex hull J\\<close> \\<open>J \\<subseteq> insert ?z I\\<close> \\<open>K = convex hull I\\<close> face\\<U> inf_le2 \\<open>K \\<in> \\<U>\\<close>)\n              then show \"F \\<in> \\<U> \\<union> ?\\<T>\"\n                by blast\n            qed\n          qed\n          ultimately show ?thesis\n            using that by auto\n        qed\n        have \"(S \\<inter> S' face_of S) \\<and> (S \\<inter> S' face_of S')\"\n          if \"S \\<in> \\<U> \\<union> ?\\<T>\" \"S' \\<in> \\<U> \\<union> ?\\<T>\" for S S'\n        proof -\n          have symmy: \"\\<lbrakk>\\<And>X Y. R X Y \\<Longrightarrow> R Y X;\n                        \\<And>X Y. \\<lbrakk>X \\<in> \\<U>; Y \\<in> \\<U>\\<rbrakk> \\<Longrightarrow> R X Y;\n                        \\<And>X Y. \\<lbrakk>X \\<in> \\<U>; Y \\<in> ?\\<T>\\<rbrakk> \\<Longrightarrow> R X Y;\n                        \\<And>X Y. \\<lbrakk>X \\<in> ?\\<T>; Y \\<in> ?\\<T>\\<rbrakk> \\<Longrightarrow> R X Y\\<rbrakk> \\<Longrightarrow> R S S'\" for R\n            using that by (metis (no_types, lifting) Un_iff)\n          show ?thesis\n          proof (rule symmy)\n            show \"Y \\<inter> X face_of Y \\<and> Y \\<inter> X face_of X\"\n              if \"X \\<inter> Y face_of X \\<and> X \\<inter> Y face_of Y\" for X Y :: \"'a set\"\n              by (simp add: inf_commute that)\n          next\n            show \"X \\<inter> Y face_of X \\<and> X \\<inter> Y face_of Y\"\n              if \"X \\<in> \\<U>\" and \"Y \\<in> \\<U>\" for X Y\n              by (simp add: faceI\\<U> that)\n          next\n            show \"X \\<inter> Y face_of X \\<and> X \\<inter> Y face_of Y\"\n              if XY: \"X \\<in> \\<U>\" \"Y \\<in> ?\\<T>\" for X Y\n            proof -\n              obtain C K\n                where \"C \\<in> \\<N>\" \"K \\<in> \\<U>\" \"K \\<subseteq> rel_frontier C\"\n                and Y: \"Y = convex hull insert (SOME z. z \\<in> rel_interior C) K\"\n                using XY by blast\n              have \"convex C\"\n                by (simp add: \\<open>C \\<in> \\<N>\\<close> convex\\<N>)\n              have \"K \\<subseteq> C\"\n                by (metis DiffE \\<open>C \\<in> \\<N>\\<close> \\<open>K \\<subseteq> rel_frontier C\\<close> closed\\<N> closure_closed rel_frontier_def subset_iff)\n              let ?z = \"(SOME z. z \\<in> rel_interior C)\"\n              have z: \"?z \\<in> rel_interior C\"\n                using \\<open>C \\<in> \\<N>\\<close> in_rel_interior by blast\n              obtain D where \"D \\<in> \\<S>\" \"X \\<subseteq> D\"\n                using C\\<U> \\<open>X \\<in> \\<U>\\<close> by blast\n              have \"D \\<inter> rel_interior C = (C \\<inter> D) \\<inter> rel_interior C\"\n                using rel_interior_subset by blast\n              also have \"(C \\<inter> D) \\<inter> rel_interior C = {}\"\n              proof (rule face_of_disjoint_rel_interior)\n                show \"C \\<inter> D face_of C\"\n                  using \\<N>_def \\<S>_def \\<open>C \\<in> \\<N>\\<close> \\<open>D \\<in> \\<S>\\<close> intface\\<M> by blast\n                show \"C \\<inter> D \\<noteq> C\"\n                  by (metis (mono_tags, lifting) Int_lower2 \\<N>_def \\<S>_def \\<open>C \\<in> \\<N>\\<close> \\<open>D \\<in> \\<S>\\<close> aff_dim_subset mem_Collect_eq not_le)\n              qed\n              finally have DC: \"D \\<inter> rel_interior C = {}\" .\n              have eq: \"X \\<inter> convex hull (insert ?z K) = X \\<inter> convex hull K\"\n                apply (rule Int_convex_hull_insert_rel_exterior [OF \\<open>convex C\\<close> \\<open>K \\<subseteq> C\\<close> z])\n                using DC by (meson \\<open>X \\<subseteq> D\\<close> disjnt_def disjnt_subset1)\n              obtain I where I: \"\\<not> affine_dependent I\"\n                         and Keq: \"K = convex hull I\" and [simp]: \"convex hull K = K\"\n                using \"*\" \\<open>K \\<in> \\<U>\\<close> by force\n              then have \"?z \\<notin> affine hull I\"\n                using ahK_C_disjoint \\<open>C \\<in> \\<N>\\<close> \\<open>K \\<in> \\<U>\\<close> \\<open>K \\<subseteq> rel_frontier C\\<close> affine_hull_convex_hull z by blast\n              have \"X \\<inter> K face_of K\"\n                by (simp add: \\<open>K \\<in> \\<U>\\<close> faceI\\<U> \\<open>X \\<in> \\<U>\\<close>)\n              also have \"... face_of convex hull insert ?z K\"\n                by (metis I Keq \\<open>?z \\<notin> affine hull I\\<close> aff_independent_finite convex_convex_hull face_of_convex_hull_insert face_of_refl hull_insert)\n              finally have \"X \\<inter> K face_of convex hull insert ?z K\" .\n              then show ?thesis\n                using \"*\" \\<open>K \\<in> \\<U>\\<close> faceI\\<U> that(1) by (fastforce simp add: Y eq)\n            qed\n          next\n            show \"X \\<inter> Y face_of X \\<and> X \\<inter> Y face_of Y\"\n              if XY: \"X \\<in> ?\\<T>\" \"Y \\<in> ?\\<T>\" for X Y\n            proof -\n              obtain C K D L\n                where \"C \\<in> \\<N>\" \"K \\<in> \\<U>\" \"K \\<subseteq> rel_frontier C\"\n                and X: \"X = convex hull insert (SOME z. z \\<in> rel_interior C) K\"\n                and \"D \\<in> \\<N>\" \"L \\<in> \\<U>\" \"L \\<subseteq> rel_frontier D\"\n                and Y: \"Y = convex hull insert (SOME z. z \\<in> rel_interior D) L\"\n                using XY by blast\n              let ?z = \"(SOME z. z \\<in> rel_interior C)\"\n              have z: \"?z \\<in> rel_interior C\"\n                using \\<open>C \\<in> \\<N>\\<close> in_rel_interior by blast\n              have \"convex C\"\n                by (simp add: \\<open>C \\<in> \\<N>\\<close> convex\\<N>)\n              have \"convex K\"\n                using \"*\" \\<open>K \\<in> \\<U>\\<close> by blast\n              have \"convex L\"\n                by (meson \\<open>L \\<in> \\<U>\\<close> convex_simplex simpl\\<U>)\n              show ?thesis\n              proof (cases \"D=C\")\n                case True\n                then have \"L \\<subseteq> rel_frontier C\"\n                  using \\<open>L \\<subseteq> rel_frontier D\\<close> by auto\n                show ?thesis\n                  apply (simp add: X Y True)\n                  apply (simp add: convex_hull_insert_Int_eq [OF z] \\<open>K \\<subseteq> rel_frontier C\\<close> \\<open>L \\<subseteq> rel_frontier C\\<close> \\<open>convex C\\<close> \\<open>convex K\\<close> \\<open>convex L\\<close>)\n                  using face_of_polytope_insert2\n                  by (metis \"*\" IntI \\<open>C \\<in> \\<N>\\<close> \\<open>K \\<in> \\<U>\\<close> \\<open>L \\<in> \\<U>\\<close>\\<open>K \\<subseteq> rel_frontier C\\<close> \\<open>L \\<subseteq> rel_frontier C\\<close> aff_independent_finite ahK_C_disjoint empty_iff faceI\\<U> polytope_convex_hull z)\n              next\n                case False\n                have \"convex D\"\n                  by (simp add: \\<open>D \\<in> \\<N>\\<close> convex\\<N>)\n                have \"K \\<subseteq> C\"\n                  by (metis DiffE \\<open>C \\<in> \\<N>\\<close> \\<open>K \\<subseteq> rel_frontier C\\<close> closed\\<N> closure_closed rel_frontier_def subset_eq)\n                have \"L \\<subseteq> D\"\n                  by (metis DiffE \\<open>D \\<in> \\<N>\\<close> \\<open>L \\<subseteq> rel_frontier D\\<close> closed\\<N> closure_closed rel_frontier_def subset_eq)\n                let ?w = \"(SOME w. w \\<in> rel_interior D)\"\n                have w: \"?w \\<in> rel_interior D\"\n                  using \\<open>D \\<in> \\<N>\\<close> in_rel_interior by blast\n                have \"C \\<inter> rel_interior D = (D \\<inter> C) \\<inter> rel_interior D\"\n                  using rel_interior_subset by blast\n                also have \"(D \\<inter> C) \\<inter> rel_interior D = {}\"\n                proof (rule face_of_disjoint_rel_interior)\n                  show \"D \\<inter> C face_of D\"\n                    using \\<N>_def \\<open>C \\<in> \\<N>\\<close> \\<open>D \\<in> \\<N>\\<close> intface\\<M> by blast\n                  have \"D \\<in> \\<M> \\<and> aff_dim D = int n\"\n                    using \\<N>_def \\<open>D \\<in> \\<N>\\<close> by blast\n                  moreover have \"C \\<in> \\<M> \\<and> aff_dim C = int n\"\n                    using \\<N>_def \\<open>C \\<in> \\<N>\\<close> by blast\n                  ultimately show \"D \\<inter> C \\<noteq> D\"\n                    by (metis False face_of_aff_dim_lt inf.idem inf_le1 intface\\<M> not_le poly\\<M> polytope_imp_convex)\n                qed\n                finally have CD: \"C \\<inter> (rel_interior D) = {}\" .\n                have zKC: \"(convex hull insert ?z K) \\<subseteq> C\"\n                  by (metis DiffE \\<open>C \\<in> \\<N>\\<close> \\<open>K \\<subseteq> rel_frontier C\\<close> closed\\<N> closure_closed convex\\<N> hull_minimal insert_subset rel_frontier_def rel_interior_subset subset_iff z)\n                have eq: \"convex hull (insert ?z K) \\<inter> convex hull (insert ?w L) =\n                          convex hull (insert ?z K) \\<inter> convex hull L\"\n                  apply (rule Int_convex_hull_insert_rel_exterior [OF \\<open>convex D\\<close> \\<open>L \\<subseteq> D\\<close> w])\n                  using zKC CD apply (force simp: disjnt_def)\n                  done\n                have ch_id: \"convex hull K = K\" \"convex hull L = L\"\n                  using \"*\" \\<open>K \\<in> \\<U>\\<close> \\<open>L \\<in> \\<U>\\<close> hull_same by auto\n                have \"convex C\"\n                  by (simp add: \\<open>C \\<in> \\<N>\\<close> convex\\<N>)\n                have \"convex hull (insert ?z K) \\<inter> L = L \\<inter> convex hull (insert ?z K)\"\n                  by blast\n                also have \"... = convex hull K \\<inter> L\"\n                proof (subst Int_convex_hull_insert_rel_exterior [OF \\<open>convex C\\<close> \\<open>K \\<subseteq> C\\<close> z])\n                  have \"(C \\<inter> D) \\<inter> rel_interior C = {}\"\n                  proof (rule face_of_disjoint_rel_interior)\n                    show \"C \\<inter> D face_of C\"\n                      using \\<N>_def \\<open>C \\<in> \\<N>\\<close> \\<open>D \\<in> \\<N>\\<close> intface\\<M> by blast\n                    have \"D \\<in> \\<M>\" \"aff_dim D = int n\"\n                      using \\<N>_def \\<open>D \\<in> \\<N>\\<close> by fastforce+\n                    moreover have \"C \\<in> \\<M>\" \"aff_dim C = int n\"\n                      using \\<N>_def \\<open>C \\<in> \\<N>\\<close> by fastforce+\n                    ultimately have \"aff_dim D + - 1 * aff_dim C \\<le> 0\"\n                      by fastforce\n                    then have \"\\<not> C face_of D\"\n                      using False \\<open>convex D\\<close> face_of_aff_dim_lt by fastforce\n                    show \"C \\<inter> D \\<noteq> C\"\n                      using \\<open>C \\<in> \\<M>\\<close> \\<open>D \\<in> \\<M>\\<close> \\<open>\\<not> C face_of D\\<close> intface\\<M> by fastforce\n                  qed\n                  then have \"D \\<inter> rel_interior C = {}\"\n                    by (metis inf.absorb_iff2 inf_assoc inf_sup_aci(1) rel_interior_subset)\n                  then show \"disjnt L (rel_interior C)\"\n                    by (meson \\<open>L \\<subseteq> D\\<close> disjnt_def disjnt_subset1)\n                next\n                  show \"L \\<inter> convex hull K = convex hull K \\<inter> L\"\n                    by force\n                qed\n                finally have chKL: \"convex hull (insert ?z K) \\<inter> L = convex hull K \\<inter> L\" .\n                have \"convex hull insert ?z K \\<inter> convex hull L face_of K\"\n                  by (simp add: \\<open>K \\<in> \\<U>\\<close> \\<open>L \\<in> \\<U>\\<close> ch_id chKL faceI\\<U>)\n                also have \"... face_of convex hull insert ?z K\"\n                proof -\n                  obtain I where I: \"\\<not> affine_dependent I\" \"K = convex hull I\"\n                    using * [OF \\<open>K \\<in> \\<U>\\<close>] by auto\n                  then have \"\\<And>a. a \\<notin> rel_interior C \\<or> a \\<notin> affine hull I\"\n                    using ahK_C_disjoint \\<open>C \\<in> \\<N>\\<close> \\<open>K \\<in> \\<U>\\<close> \\<open>K \\<subseteq> rel_frontier C\\<close> affine_hull_convex_hull by blast\n                  then show ?thesis\n                    by (metis I affine_independent_insert face_of_convex_hull_affine_independent hull_insert subset_insertI z)\n                qed\n                finally have 1: \"convex hull insert ?z K \\<inter> convex hull L face_of convex hull insert ?z K\" .\n                have \"convex hull insert ?z K \\<inter> convex hull L face_of L\"\n                  by (simp add: \\<open>K \\<in> \\<U>\\<close> \\<open>L \\<in> \\<U>\\<close> ch_id chKL faceI\\<U>)\n                also have \"... face_of convex hull insert ?w L\"\n                proof -\n                  obtain I where I: \"\\<not> affine_dependent I\" \"L = convex hull I\"\n                    using * [OF \\<open>L \\<in> \\<U>\\<close>] by auto\n                  then have \"\\<And>a. a \\<notin> rel_interior D \\<or> a \\<notin> affine hull I\"\n                    using \\<open>D \\<in> \\<N>\\<close> \\<open>L \\<in> \\<U>\\<close> \\<open>L \\<subseteq> rel_frontier D\\<close> affine_hull_convex_hull ahK_C_disjoint by blast\n                  then show ?thesis\n                    by (metis I aff_independent_finite convex_convex_hull face_of_convex_hull_insert face_of_refl hull_insert w)\n                qed\n                finally have 2: \"convex hull insert ?z K \\<inter> convex hull L face_of convex hull insert ?w L\" .\n                show ?thesis\n                  by (simp add: X Y eq 1 2)\n              qed\n            qed\n          qed\n        qed\n        then\n        show \"S \\<inter> S' face_of S\" \"S \\<inter> S' face_of S'\" if \"S \\<in> \\<U> \\<union> ?\\<T> \\<and> S' \\<in> \\<U> \\<union> ?\\<T>\" for S S'\n          using that by auto\n      qed\n      show \"\\<exists>F \\<subseteq> \\<U> \\<union> ?\\<T>. C = \\<Union>F\" if \"C \\<in> \\<M>\" for C\n      proof (cases \"C \\<in> \\<S>\")\n        case True\n        then show ?thesis\n          by (meson UnCI fin\\<U> subsetD subsetI)\n      next\n        case False\n        then have \"C \\<in> \\<N>\"\n          by (simp add: \\<N>_def \\<S>_def aff\\<M> less_le that)\n        let ?z = \"SOME z. z \\<in> rel_interior C\"\n        have z: \"?z \\<in> rel_interior C\"\n          using \\<open>C \\<in> \\<N>\\<close> in_rel_interior by blast\n        let ?F = \"\\<Union>K \\<in> \\<U> \\<inter> Pow (rel_frontier C). {convex hull (insert ?z K)}\"\n        have \"?F \\<subseteq> ?\\<T>\"\n          using \\<open>C \\<in> \\<N>\\<close> by blast\n        moreover have \"C \\<subseteq> \\<Union>?F\"\n        proof\n          fix x\n          assume \"x \\<in> C\"\n          have \"convex C\"\n            using \\<open>C \\<in> \\<N>\\<close> convex\\<N> by blast\n          have \"bounded C\"\n            using \\<open>C \\<in> \\<N>\\<close> by (simp add: poly\\<M> polytope_imp_bounded that)\n          have \"polytope C\"\n            using \\<open>C \\<in> \\<N>\\<close> poly\\<N> by auto\n          have \"\\<not> (?z = x \\<and> C = {?z})\"\n            using \\<open>C \\<in> \\<N>\\<close> aff_dim_sing [of ?z] \\<open>\\<not> n \\<le> 1\\<close> by (force simp: \\<N>_def)\n          then obtain y where y: \"y \\<in> rel_frontier C\" and xzy: \"x \\<in> closed_segment ?z y\"\n            and sub: \"open_segment ?z y \\<subseteq> rel_interior C\"\n            by (blast intro: segment_to_rel_frontier [OF \\<open>convex C\\<close> \\<open>bounded C\\<close> z \\<open>x \\<in> C\\<close>])\n          then obtain F where \"y \\<in> F\" \"F face_of C\" \"F \\<noteq> C\"\n            by (auto simp: rel_frontier_of_polyhedron_alt [OF polytope_imp_polyhedron [OF \\<open>polytope C\\<close>]])\n          then obtain \\<G> where \"finite \\<G>\" \"\\<G> \\<subseteq> \\<U>\" \"F = \\<Union>\\<G>\"\n            by (metis (mono_tags, lifting) \\<S>_def \\<open>C \\<in> \\<M>\\<close> \\<open>convex C\\<close> aff\\<M> face\\<M> face_of_aff_dim_lt fin\\<U> le_less_trans mem_Collect_eq not_less)\n          then obtain K where \"y \\<in> K\" \"K \\<in> \\<G>\"\n            using \\<open>y \\<in> F\\<close> by blast\n          moreover have x: \"x \\<in> convex hull {?z,y}\"\n            using segment_convex_hull xzy by auto\n          moreover have \"convex hull {?z,y} \\<subseteq> convex hull insert ?z K\"\n            by (metis (full_types) \\<open>y \\<in> K\\<close> hull_mono empty_subsetI insertCI insert_subset)\n          moreover have \"K \\<in> \\<U>\"\n            using \\<open>K \\<in> \\<G>\\<close> \\<open>\\<G> \\<subseteq> \\<U>\\<close> by blast\n          moreover have \"K \\<subseteq> rel_frontier C\"\n            using \\<open>F = \\<Union>\\<G>\\<close> \\<open>F \\<noteq> C\\<close> \\<open>F face_of C\\<close> \\<open>K \\<in> \\<G>\\<close> face_of_subset_rel_frontier by fastforce\n          ultimately show \"x \\<in> \\<Union>?F\"\n            by force\n        qed\n        moreover\n        have \"convex hull insert (SOME z. z \\<in> rel_interior C) K \\<subseteq> C\"\n          if \"K \\<in> \\<U>\" \"K \\<subseteq> rel_frontier C\" for K\n        proof (rule hull_minimal)\n          show \"insert (SOME z. z \\<in> rel_interior C) K \\<subseteq> C\"\n            using that \\<open>C \\<in> \\<N>\\<close> in_rel_interior rel_interior_subset\n            by (force simp: closure_eq rel_frontier_def closed\\<N>)\n          show \"convex C\"\n            by (simp add: \\<open>C \\<in> \\<N>\\<close> convex\\<N>)\n        qed\n        then have \"\\<Union>?F \\<subseteq> C\"\n          by auto\n        ultimately show ?thesis\n          by blast\n      qed\n\n      have \"(\\<exists>C. C \\<in> \\<M> \\<and> L \\<subseteq> C) \\<and> aff_dim L \\<le> int n\"  if \"L \\<in> \\<U> \\<union> ?\\<T>\" for L\n        using that\n      proof\n        assume \"L \\<in> \\<U>\"\n        then show ?thesis using C\\<U> \\<S>_def * by fastforce\n      next\n        assume \"L \\<in> ?\\<T>\"\n        then obtain C K where \"C \\<in> \\<N>\"\n          and L: \"L = convex hull insert (SOME z. z \\<in> rel_interior C) K\"\n          and K: \"K \\<in> \\<U>\" \"K \\<subseteq> rel_frontier C\"\n          by auto\n        hence \"convex hull C = C\" by (meson convex\\<N> convex_hull_eq)\n        hence \"convex C\" using convex_convex_hull[of C] by simp\n        have \"rel_frontier C \\<subseteq> C\"\n          by (metis DiffE closed\\<N> \\<open>C \\<in> \\<N>\\<close> closure_closed rel_frontier_def subsetI)\n        have \"K \\<subseteq> C\"\n          using K \\<open>rel_frontier C \\<subseteq> C\\<close> by blast\n        have \"C \\<in> \\<M>\"\n          using \\<N>_def \\<open>C \\<in> \\<N>\\<close> by auto\n        moreover have \"L \\<subseteq> C\" using K L \\<open>C \\<in> \\<N>\\<close>\n          by (metis \\<open>K \\<subseteq> C\\<close> \\<open>convex hull C = C\\<close> contra_subsetD hull_mono in_rel_interior insert_subset rel_interior_subset)\n        ultimately show ?thesis\n          using \\<open>rel_frontier C \\<subseteq> C\\<close> \\<open>L \\<subseteq> C\\<close> aff\\<M> aff_dim_subset \\<open>C \\<in> \\<M>\\<close> dual_order.trans by blast\n      qed\n      then show \"\\<exists>C. C \\<in> \\<M> \\<and> L \\<subseteq> C\" \"aff_dim L \\<le> int n\" if \"L \\<in> \\<U> \\<union> ?\\<T>\" for L\n        using that by auto\n    qed\n    then show ?thesis\n      apply (rule ex_forward, safe)\n      apply (meson Union_iff subsetCE, fastforce)\n      by (meson infinite_super simplicial_complex_def)\n  qed\nqed\n\n\nlemma simplicial_subdivision_of_cell_complex_lowdim:\n  assumes \"finite \\<M>\"\n      and poly: \"\\<And>C. C \\<in> \\<M> \\<Longrightarrow> polytope C\"\n      and face: \"\\<And>C1 C2. \\<lbrakk>C1 \\<in> \\<M>; C2 \\<in> \\<M>\\<rbrakk> \\<Longrightarrow> C1 \\<inter> C2 face_of C1 \\<and> C1 \\<inter> C2 face_of C2\"\n      and aff: \"\\<And>C. C \\<in> \\<M> \\<Longrightarrow> aff_dim C \\<le> d\"\n  obtains \\<T> where \"simplicial_complex \\<T>\" \"\\<And>K. K \\<in> \\<T> \\<Longrightarrow> aff_dim K \\<le> d\"\n                  \"\\<Union>\\<T> = \\<Union>\\<M>\"\n                  \"\\<And>C. C \\<in> \\<M> \\<Longrightarrow> \\<exists>F. finite F \\<and> F \\<subseteq> \\<T> \\<and> C = \\<Union>F\"\n                  \"\\<And>K. K \\<in> \\<T> \\<Longrightarrow> \\<exists>C. C \\<in> \\<M> \\<and> K \\<subseteq> C\"\nproof (cases \"d \\<ge> 0\")\n  case True\n  then obtain n where n: \"d = of_nat n\"\n    using zero_le_imp_eq_int by blast\n  have \"\\<exists>\\<T>. simplicial_complex \\<T> \\<and>\n            (\\<forall>K\\<in>\\<T>. aff_dim K \\<le> int n) \\<and>\n            \\<Union>\\<T> = \\<Union>(\\<Union>C\\<in>\\<M>. {F. F face_of C}) \\<and>\n            (\\<forall>C\\<in>\\<Union>C\\<in>\\<M>. {F. F face_of C}.\n                \\<exists>F. finite F \\<and> F \\<subseteq> \\<T> \\<and> C = \\<Union>F) \\<and>\n            (\\<forall>K\\<in>\\<T>. \\<exists>C. C \\<in> (\\<Union>C\\<in>\\<M>. {F. F face_of C}) \\<and> K \\<subseteq> C)\"\n  proof (rule simplicial_subdivision_aux)\n    show \"finite (\\<Union>C\\<in>\\<M>. {F. F face_of C})\"\n      using \\<open>finite \\<M>\\<close> poly polyhedron_eq_finite_faces polytope_imp_polyhedron by fastforce\n    show \"polytope F\" if \"F \\<in> (\\<Union>C\\<in>\\<M>. {F. F face_of C})\" for F\n      using poly that face_of_polytope_polytope by blast\n    show \"aff_dim F \\<le> int n\" if \"F \\<in> (\\<Union>C\\<in>\\<M>. {F. F face_of C})\" for F\n      using that\n      by clarify (metis n aff_dim_subset aff face_of_imp_subset order_trans)\n    show \"F \\<in> (\\<Union>C\\<in>\\<M>. {F. F face_of C})\"\n      if \"G \\<in> (\\<Union>C\\<in>\\<M>. {F. F face_of C})\" and \"F face_of G\" for F G\n      using that face_of_trans by blast\n  next\n    show \"F1 \\<inter> F2 face_of F1 \\<and> F1 \\<inter> F2 face_of F2\"\n      if \"F1 \\<in> (\\<Union>C\\<in>\\<M>. {F. F face_of C})\" and \"F2 \\<in> (\\<Union>C\\<in>\\<M>. {F. F face_of C})\" for F1 F2\n      using that\n      by safe (meson face face_of_Int_subface)+\n  qed\n  moreover\n  have \"\\<Union>(\\<Union>C\\<in>\\<M>. {F. F face_of C}) = \\<Union>\\<M>\"\n    using face_of_imp_subset face by blast\n  ultimately show ?thesis\n    apply clarify\n    apply (rule that, assumption+)\n       using n apply blast\n      apply (simp_all add: poly face_of_refl polytope_imp_convex)\n    using face_of_imp_subset by fastforce\nnext\n  case False\n  then have m1: \"\\<And>C. C \\<in> \\<M> \\<Longrightarrow> aff_dim C = -1\"\n    by (metis aff aff_dim_empty_eq aff_dim_negative_iff dual_order.trans not_less)\n  then have face\\<M>: \"\\<And>F S. \\<lbrakk>S \\<in> \\<M>; F face_of S\\<rbrakk> \\<Longrightarrow> F \\<in> \\<M>\"\n    by (metis aff_dim_empty face_of_empty)\n  show ?thesis\n  proof\n    have \"\\<And>S. S \\<in> \\<M> \\<Longrightarrow> \\<exists>n. n simplex S\"\n      by (metis (no_types) m1 aff_dim_empty simplex_minus_1)\n    then show \"simplicial_complex \\<M>\"\n      by (auto simp: simplicial_complex_def \\<open>finite \\<M>\\<close> face intro: face\\<M>)\n    show \"aff_dim K \\<le> d\" if \"K \\<in> \\<M>\" for K\n      by (simp add: that aff)\n    show \"\\<exists>F. finite F \\<and> F \\<subseteq> \\<M> \\<and> C = \\<Union>F\" if \"C \\<in> \\<M>\" for C\n      using \\<open>C \\<in> \\<M>\\<close> equals0I by auto\n    show \"\\<exists>C. C \\<in> \\<M> \\<and> K \\<subseteq> C\" if \"K \\<in> \\<M>\" for K\n      using \\<open>K \\<in> \\<M>\\<close> by blast\n  qed auto\nqed\n\nproposition simplicial_subdivision_of_cell_complex:\n  assumes \"finite \\<M>\"\n      and poly: \"\\<And>C. C \\<in> \\<M> \\<Longrightarrow> polytope C\"\n      and face: \"\\<And>C1 C2. \\<lbrakk>C1 \\<in> \\<M>; C2 \\<in> \\<M>\\<rbrakk> \\<Longrightarrow> C1 \\<inter> C2 face_of C1 \\<and> C1 \\<inter> C2 face_of C2\"\n  obtains \\<T> where \"simplicial_complex \\<T>\"\n                  \"\\<Union>\\<T> = \\<Union>\\<M>\"\n                  \"\\<And>C. C \\<in> \\<M> \\<Longrightarrow> \\<exists>F. finite F \\<and> F \\<subseteq> \\<T> \\<and> C = \\<Union>F\"\n                  \"\\<And>K. K \\<in> \\<T> \\<Longrightarrow> \\<exists>C. C \\<in> \\<M> \\<and> K \\<subseteq> C\"\n  by (blast intro: simplicial_subdivision_of_cell_complex_lowdim [OF assms aff_dim_le_DIM])\n\ncorollary fine_simplicial_subdivision_of_cell_complex:\n  assumes \"0 < e\" \"finite \\<M>\"\n      and poly: \"\\<And>C. C \\<in> \\<M> \\<Longrightarrow> polytope C\"\n      and face: \"\\<And>C1 C2. \\<lbrakk>C1 \\<in> \\<M>; C2 \\<in> \\<M>\\<rbrakk> \\<Longrightarrow> C1 \\<inter> C2 face_of C1 \\<and> C1 \\<inter> C2 face_of C2\"\n  obtains \\<T> where \"simplicial_complex \\<T>\"\n                  \"\\<And>K. K \\<in> \\<T> \\<Longrightarrow> diameter K < e\"\n                  \"\\<Union>\\<T> = \\<Union>\\<M>\"\n                  \"\\<And>C. C \\<in> \\<M> \\<Longrightarrow> \\<exists>F. finite F \\<and> F \\<subseteq> \\<T> \\<and> C = \\<Union>F\"\n                  \"\\<And>K. K \\<in> \\<T> \\<Longrightarrow> \\<exists>C. C \\<in> \\<M> \\<and> K \\<subseteq> C\"\nproof -\n  obtain \\<N> where \\<N>: \"finite \\<N>\" \"\\<Union>\\<N> = \\<Union>\\<M>\" \n              and diapoly: \"\\<And>X. X \\<in> \\<N> \\<Longrightarrow> diameter X < e\" \"\\<And>X. X \\<in> \\<N> \\<Longrightarrow> polytope X\"\n               and      \"\\<And>X Y. \\<lbrakk>X \\<in> \\<N>; Y \\<in> \\<N>\\<rbrakk> \\<Longrightarrow> X \\<inter> Y face_of X \\<and> X \\<inter> Y face_of Y\"\n               and \\<N>covers: \"\\<And>C x. C \\<in> \\<M> \\<and> x \\<in> C \\<Longrightarrow> \\<exists>D. D \\<in> \\<N> \\<and> x \\<in> D \\<and> D \\<subseteq> C\"\n               and \\<N>covered: \"\\<And>C. C \\<in> \\<N> \\<Longrightarrow> \\<exists>D. D \\<in> \\<M> \\<and> C \\<subseteq> D\"\n    by (blast intro: cell_complex_subdivision_exists [OF \\<open>0 < e\\<close> \\<open>finite \\<M>\\<close> poly aff_dim_le_DIM face])\n  then obtain \\<T> where \\<T>: \"simplicial_complex \\<T>\" \"\\<Union>\\<T> = \\<Union>\\<N>\"\n                   and \\<T>covers: \"\\<And>C. C \\<in> \\<N> \\<Longrightarrow> \\<exists>F. finite F \\<and> F \\<subseteq> \\<T> \\<and> C = \\<Union>F\"\n                   and \\<T>covered: \"\\<And>K. K \\<in> \\<T> \\<Longrightarrow> \\<exists>C. C \\<in> \\<N> \\<and> K \\<subseteq> C\"\n    using simplicial_subdivision_of_cell_complex [OF \\<open>finite \\<N>\\<close>] by metis\n  show ?thesis\n  proof\n    show \"simplicial_complex \\<T>\"\n      by (rule \\<T>)\n    show \"diameter K < e\" if \"K \\<in> \\<T>\" for K\n      by (metis le_less_trans diapoly \\<T>covered diameter_subset polytope_imp_bounded that)\n    show \"\\<Union>\\<T> = \\<Union>\\<M>\"\n      by (simp add: \\<N>(2) \\<open>\\<Union>\\<T> = \\<Union>\\<N>\\<close>)\n    show \"\\<exists>F. finite F \\<and> F \\<subseteq> \\<T> \\<and> C = \\<Union>F\" if \"C \\<in> \\<M>\" for C\n    proof -\n      { fix x\n        assume \"x \\<in> C\"\n        then obtain D where \"D \\<in> \\<T>\" \"x \\<in> D\" \"D \\<subseteq> C\"\n          using \\<N>covers \\<open>C \\<in> \\<M>\\<close> \\<T>covers by force\n        then have \"\\<exists>X\\<in>\\<T> \\<inter> Pow C. x \\<in> X\"\n          using \\<open>D \\<in> \\<T>\\<close> \\<open>D \\<subseteq> C\\<close> \\<open>x \\<in> D\\<close> by blast\n      }\n      moreover\n      have \"finite (\\<T> \\<inter> Pow C)\"\n        using \\<open>simplicial_complex \\<T>\\<close> simplicial_complex_def by auto\n      ultimately show ?thesis\n        by (rule_tac x=\"(\\<T> \\<inter> Pow C)\" in exI) auto\n    qed\n    show \"\\<exists>C. C \\<in> \\<M> \\<and> K \\<subseteq> C\" if \"K \\<in> \\<T>\" for K\n      by (meson \\<N>covered \\<T>covered order_trans that)\n  qed\nqed\n\nsubsection\\<open>Some results on cell division with full-dimensional cells only\\<close>\n\nlemma convex_Union_fulldim_cells:\n  assumes \"finite \\<S>\" and clo: \"\\<And>C. C \\<in> \\<S> \\<Longrightarrow> closed C\" and con: \"\\<And>C. C \\<in> \\<S> \\<Longrightarrow> convex C\"\n      and eq: \"\\<Union>\\<S> = U\"and  \"convex U\"\n shows \"\\<Union>{C \\<in> \\<S>. aff_dim C = aff_dim U} = U\"  (is \"?lhs = U\")\nproof -\n  have \"closed U\"\n    using \\<open>finite \\<S>\\<close> clo eq by blast\n  have \"?lhs \\<subseteq> U\"\n    using eq by blast\n  moreover have \"U \\<subseteq> ?lhs\"\n  proof (cases \"\\<forall>C \\<in> \\<S>. aff_dim C = aff_dim U\")\n    case True\n    then show ?thesis\n      using eq by blast\n  next\n    case False\n    have \"closed ?lhs\"\n      by (simp add: \\<open>finite \\<S>\\<close> clo closed_Union)\n    moreover have \"U \\<subseteq> closure ?lhs\"\n    proof -\n      have \"U \\<subseteq> closure(\\<Inter>{U - C |C. C \\<in> \\<S> \\<and> aff_dim C < aff_dim U})\"\n      proof (rule Baire [OF \\<open>closed U\\<close>])\n        show \"countable {U - C |C. C \\<in> \\<S> \\<and> aff_dim C < aff_dim U}\"\n          using \\<open>finite \\<S>\\<close> uncountable_infinite by fastforce\n        have \"\\<And>C. C \\<in> \\<S> \\<Longrightarrow> openin (subtopology euclidean U) (U-C)\"\n          by (metis Sup_upper clo closed_limpt closedin_limpt eq openin_diff openin_subtopology_self)\n        then show \"openin (subtopology euclidean U) T \\<and> U \\<subseteq> closure T\"\n          if \"T \\<in> {U - C |C. C \\<in> \\<S> \\<and> aff_dim C < aff_dim U}\" for T\n          using that dense_complement_convex_closed \\<open>closed U\\<close> \\<open>convex U\\<close> by auto\n      qed\n      also have \"... \\<subseteq> closure ?lhs\"\n      proof -\n        obtain C where \"C \\<in> \\<S>\" \"aff_dim C < aff_dim U\"\n          by (metis False Sup_upper aff_dim_subset eq eq_iff not_le)\n        have \"\\<exists>X. X \\<in> \\<S> \\<and> aff_dim X = aff_dim U \\<and> x \\<in> X\"\n          if \"\\<And>V. (\\<exists>C. V = U - C \\<and> C \\<in> \\<S> \\<and> aff_dim C < aff_dim U) \\<Longrightarrow> x \\<in> V\" for x\n        proof -\n          have \"x \\<in> U \\<and> x \\<in> \\<Union>\\<S>\"\n            using \\<open>C \\<in> \\<S>\\<close> \\<open>aff_dim C < aff_dim U\\<close> eq that by blast\n          then show ?thesis\n            by (metis Diff_iff Sup_upper Union_iff aff_dim_subset dual_order.order_iff_strict eq that)\n        qed\n        then show ?thesis\n          by (auto intro!: closure_mono)\n      qed\n      finally show ?thesis .\n    qed\n    ultimately show ?thesis\n      using closure_subset_eq by blast\n  qed\n  ultimately show ?thesis by blast\nqed\n\nproposition fine_triangular_subdivision_of_cell_complex:\n  assumes \"0 < e\" \"finite \\<M>\"\n      and poly: \"\\<And>C. C \\<in> \\<M> \\<Longrightarrow> polytope C\"\n      and aff: \"\\<And>C. C \\<in> \\<M> \\<Longrightarrow> aff_dim C = d\"\n      and face: \"\\<And>C1 C2. \\<lbrakk>C1 \\<in> \\<M>; C2 \\<in> \\<M>\\<rbrakk> \\<Longrightarrow> C1 \\<inter> C2 face_of C1 \\<and> C1 \\<inter> C2 face_of C2\"\n  obtains \\<T> where \"triangulation \\<T>\" \"\\<And>k. k \\<in> \\<T> \\<Longrightarrow> diameter k < e\"\n                 \"\\<And>k. k \\<in> \\<T> \\<Longrightarrow> aff_dim k = d\" \"\\<Union>\\<T> = \\<Union>\\<M>\"\n                 \"\\<And>C. C \\<in> \\<M> \\<Longrightarrow> \\<exists>f. finite f \\<and> f \\<subseteq> \\<T> \\<and> C = \\<Union>f\"\n                 \"\\<And>k. k \\<in> \\<T> \\<Longrightarrow> \\<exists>C. C \\<in> \\<M> \\<and> k \\<subseteq> C\"\nproof -\n  obtain \\<T> where \"simplicial_complex \\<T>\"\n             and dia\\<T>: \"\\<And>K. K \\<in> \\<T> \\<Longrightarrow> diameter K < e\"\n             and \"\\<Union>\\<T> = \\<Union>\\<M>\"\n             and in\\<M>: \"\\<And>C. C \\<in> \\<M> \\<Longrightarrow> \\<exists>F. finite F \\<and> F \\<subseteq> \\<T> \\<and> C = \\<Union>F\"\n             and in\\<T>: \"\\<And>K. K \\<in> \\<T> \\<Longrightarrow> \\<exists>C. C \\<in> \\<M> \\<and> K \\<subseteq> C\"\n    by (blast intro: fine_simplicial_subdivision_of_cell_complex [OF \\<open>e > 0\\<close> \\<open>finite \\<M>\\<close> poly face])\n  let ?\\<T> = \"{K \\<in> \\<T>. aff_dim K = d}\"\n  show thesis\n  proof\n    show \"triangulation ?\\<T>\"\n      using \\<open>simplicial_complex \\<T>\\<close> by (auto simp: triangulation_def simplicial_complex_def)\n    show \"diameter L < e\" if \"L \\<in> {K \\<in> \\<T>. aff_dim K = d}\" for L\n      using that by (auto simp: dia\\<T>)\n    show \"aff_dim L = d\" if \"L \\<in> {K \\<in> \\<T>. aff_dim K = d}\" for L\n      using that by auto\n    show \"\\<exists>F. finite F \\<and> F \\<subseteq> {K \\<in> \\<T>. aff_dim K = d} \\<and> C = \\<Union>F\" if \"C \\<in> \\<M>\" for C\n    proof -\n      obtain F where \"finite F\" \"F \\<subseteq> \\<T>\" \"C = \\<Union>F\"\n        using in\\<M> [OF \\<open>C \\<in> \\<M>\\<close>] by auto\n      show ?thesis\n      proof (intro exI conjI)\n        show \"finite {K \\<in> F. aff_dim K = d}\"\n          by (simp add: \\<open>finite F\\<close>)\n        show \"{K \\<in> F. aff_dim K = d} \\<subseteq> {K \\<in> \\<T>. aff_dim K = d}\"\n          using \\<open>F \\<subseteq> \\<T>\\<close> by blast\n        have \"d = aff_dim C\"\n          by (simp add: aff that)\n        moreover have \"\\<And>K. K \\<in> F \\<Longrightarrow> closed K \\<and> convex K\"\n          using \\<open>simplicial_complex \\<T>\\<close> \\<open>F \\<subseteq> \\<T>\\<close>\n          unfolding simplicial_complex_def by (metis subsetCE \\<open>F \\<subseteq> \\<T>\\<close> closed_simplex convex_simplex)\n        moreover have \"convex (\\<Union>F)\"\n          using \\<open>C = \\<Union>F\\<close> poly polytope_imp_convex that by blast\n        ultimately show \"C = \\<Union>{K \\<in> F. aff_dim K = d}\"\n          by (simp add: convex_Union_fulldim_cells \\<open>C = \\<Union>F\\<close> \\<open>finite F\\<close>)\n      qed\n    qed\n    then show \"\\<Union>{K \\<in> \\<T>. aff_dim K = d} = \\<Union>\\<M>\"\n      by auto (meson in\\<T> subsetCE)\n    show \"\\<exists>C. C \\<in> \\<M> \\<and> L \\<subseteq> C\"\n      if \"L \\<in> {K \\<in> \\<T>. aff_dim K = d}\" for L\n      using that by (auto simp: in\\<T>)\n  qed\nqed\n\nend\n", "meta": {"author": "tangentstorm", "repo": "tangentlabs", "sha": "49d7a335221e1ae67e8de0203a3f056bc4ab1d00", "save_path": "github-repos/isabelle/tangentstorm-tangentlabs", "path": "github-repos/isabelle/tangentstorm-tangentlabs/tangentlabs-49d7a335221e1ae67e8de0203a3f056bc4ab1d00/isar/Polytope.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8652240686758841, "lm_q2_score": 0.849971175657575, "lm_q1q2_score": 0.7354155188596716}}
{"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  \"a \\<noteq> 0 \\<Longrightarrow> a * x\\<^sup>2 + b * x + c = 0 \\<longleftrightarrow> (2 * a * x + b)\\<^sup>2 = discrim a b c\"\nby (simp add: discrim_def) algebra\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\nlemma Rats_solution_QE:\n  assumes \"a \\<in> \\<rat>\" \"b \\<in> \\<rat>\" \"a \\<noteq> 0\"\n  and \"a*x^2 + b*x + c = 0\"\n  and \"sqrt (discrim a b c) \\<in> \\<rat>\"\n  shows \"x \\<in> \\<rat>\" \nusing assms(1,2,5) discriminant_iff[THEN iffD1, OF assms(3,4)] by auto\n\nlemma Rats_solution_QE_converse:\n  assumes \"a \\<in> \\<rat>\" \"b \\<in> \\<rat>\"\n  and \"a*x^2 + b*x + c = 0\"\n  and \"x \\<in> \\<rat>\"\n  shows \"sqrt (discrim a b c) \\<in> \\<rat>\"\nproof -\n  from assms(3) have \"discrim a b c = (2*a*x+b)^2\" unfolding discrim_def by algebra\n  hence \"sqrt (discrim a b c) = \\<bar>2*a*x+b\\<bar>\" by (simp)\n  thus ?thesis using \\<open>a \\<in> \\<rat>\\<close> \\<open>b \\<in> \\<rat>\\<close> \\<open>x \\<in> \\<rat>\\<close> 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/Library/Quadratic_Discriminant.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505351008906, "lm_q2_score": 0.8128673246376009, "lm_q1q2_score": 0.735360860199435}}
{"text": "(*  Title:       Projective geometry\n    Author:      Tim Makarios <tjm1983 at gmail.com>, 2012\n    Maintainer:  Tim Makarios <tjm1983 at gmail.com>\n*)\n\nheader \"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 non_zero_vectors proportionality\"\n  proof -\n    have \"proportionality \\<subseteq> non_zero_vectors \\<times> non_zero_vectors\"\n      unfolding proportionality_def non_zero_vectors_def\n      by auto\n    moreover have \"\\<forall>x\\<in>non_zero_vectors. (x, x) \\<in> proportionality\"\n    proof\n      fix x\n      assume \"x \\<in> 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> proportionality\"\n        unfolding proportionality_def\n        by blast\n    qed\n    ultimately show \"refl_on non_zero_vectors proportionality\"\n      unfolding refl_on_def ..\n  qed\n\n  lemma proportionality_sym: \"sym proportionality\"\n  proof -\n    { fix x y\n      assume \"(x, y) \\<in> 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 `\\<exists>k. x = scale k y` obtain k where \"x = scale k y\" by auto\n      with `x \\<noteq> 0` have \"k \\<noteq> 0\" by simp\n      with `x = scale k y` have \"y = scale (1/k) x\" by simp\n      with `x \\<noteq> 0` and `y \\<noteq> 0` have \"(y, x) \\<in> proportionality\"\n        unfolding proportionality_def\n        by auto\n    }\n    thus \"sym proportionality\"\n      unfolding sym_def\n      by blast\n  qed\n\n  lemma proportionality_trans: \"trans proportionality\"\n  proof -\n    { fix x y z\n      assume \"(x, y) \\<in> proportionality\" and \"(y, z) \\<in> 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 `\\<exists>j. x = scale j y` and `\\<exists>k. y = scale k z`\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 `x \\<noteq> 0` and `z \\<noteq> 0` have \"(x, z) \\<in> proportionality\"\n        unfolding proportionality_def\n        by auto\n    }\n    thus \"trans proportionality\"\n      unfolding trans_def\n      by blast\n  qed\n\n  theorem proportionality_equiv: \"equiv non_zero_vectors 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 `real_vector.non_zero_vectors \\<inter> ?invs = ?invs`\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 `v \\<in> real_vector.non_zero_vectors`\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 `c \\<noteq> 0`\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 `v \\<noteq> 0`\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 `v \\<noteq> 0` have \"c \\<noteq> 0\" by auto\n  hence \"1/c \\<noteq> 0\" by simp\n\n  from `v = c *\\<^sub>R proj2_rep (proj2_abs v)`\n  have \"(1/c) *\\<^sub>R v = (1/c) *\\<^sub>R c *\\<^sub>R proj2_rep (proj2_abs v)\"\n    by simp\n  with `c \\<noteq> 0` have \"proj2_rep (proj2_abs v) = (1/c) *\\<^sub>R v\" by simp\n\n  with `1/c \\<noteq> 0` 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 `proj2_abs v = proj2_abs w`\n  have \"proj2_rep (proj2_abs v) = proj2_rep (proj2_abs w)\" by simp\n  with proj2_rep_abs2 and `w \\<noteq> 0`\n  obtain k where \"proj2_rep (proj2_abs v) = k *\\<^sub>R w\" by auto\n  with proj2_rep_abs2 [of v] and `v \\<noteq> 0`\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 `j \\<noteq> 0` 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 `i \\<noteq> 0 \\<or> j \\<noteq> 0` have \"j \\<noteq> 0\" by simp\n    with `i *\\<^sub>R p + j *\\<^sub>R q = 0` and `q \\<noteq> 0` have \"i *\\<^sub>R p \\<noteq> 0\" by auto\n    with `i = 0` show False by simp\n  qed\n  with `p \\<noteq> 0` and `i *\\<^sub>R p + j *\\<^sub>R q = 0` have \"j \\<noteq> 0\" by auto\n\n  from `i \\<noteq> 0`\n  have \"proj2_abs p = proj2_abs (i *\\<^sub>R p)\" by (rule proj2_abs_mult [symmetric])\n  also from `i *\\<^sub>R p + j *\\<^sub>R q = 0` 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 `j \\<noteq> 0` 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 `i \\<noteq> 0 \\<or> j \\<noteq> 0` and `i *\\<^sub>R ?p + j *\\<^sub>R ?q = 0`\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 `p \\<noteq> q` have \"?p' \\<noteq> ?q'\"\n    unfolding inj_on_def\n    by auto\n  with dependent_explicit_2 [of ?p' ?q'] and `dependent ?S`\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 `p \\<noteq> q` 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 `p \\<noteq> 0` 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 `q \\<noteq> 0` 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 `r \\<noteq> 0` 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 `i *\\<^sub>R p + j *\\<^sub>R q + k *\\<^sub>R r = 0`\n    and `i' \\<noteq> 0` and `proj2_rep ?pp = i' *\\<^sub>R p`\n    and `j' \\<noteq> 0` and `proj2_rep ?pq = j' *\\<^sub>R q`\n  have \"(i/i') *\\<^sub>R ?rp + (j/j') *\\<^sub>R ?rq + (k/k') *\\<^sub>R ?rr = 0\" by simp\n\n  from `i' \\<noteq> 0` and `j' \\<noteq> 0` and `k' \\<noteq> 0` and `i \\<noteq> 0 \\<or> j \\<noteq> 0 \\<or> k \\<noteq> 0`\n  have \"i/i' \\<noteq> 0 \\<or> j/j' \\<noteq> 0 \\<or> k/k' \\<noteq> 0\" by simp\n  with `(i/i') *\\<^sub>R ?rp + (j/j') *\\<^sub>R ?rq + (k/k') *\\<^sub>R ?rr = 0`\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 `proj2_Col a b c`\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 `i *\\<^sub>R ?a' + j *\\<^sub>R ?b' + k *\\<^sub>R ?c' = 0`\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 `i \\<noteq> 0 \\<or> j \\<noteq> 0 \\<or> k \\<noteq> 0`\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 `h \\<noteq> 0 \\<or> j \\<noteq> 0 \\<or> k \\<noteq> 0` have \"h \\<noteq> 0 \\<or> k \\<noteq> 0\" by simp\n      with proj2_rep_dependent\n        and `h *\\<^sub>R ?a' + j *\\<^sub>R ?r' + k *\\<^sub>R ?t' = 0`\n        and `j = 0`\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 `h *\\<^sub>R ?a' + j *\\<^sub>R ?r' + k *\\<^sub>R ?t' = 0`\n          and `j \\<noteq> 0`\n        have \"a = r\" by simp\n        with `a \\<noteq> r` show False ..\n      qed\n      \n      from `h *\\<^sub>R ?a' + j *\\<^sub>R ?r' + k *\\<^sub>R ?t' = 0`\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 `k \\<noteq> 0`\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 `j \\<noteq> 0`\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 `t = a \\<or> (\\<exists> i. t = proj2_abs (i *\\<^sub>R ?a' + ?r'))`\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 `a \\<noteq> r`\n      have \"i *\\<^sub>R ?a' + ?r' \\<noteq> 0\" by auto\n      with proj2_rep_abs2 and `t = proj2_abs (i *\\<^sub>R ?a' + ?r')`\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 default+\n        from `(j * i) *\\<^sub>R ?a' + j *\\<^sub>R ?r' + (-1) *\\<^sub>R ?t' = 0`\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 `a \\<noteq> r` and `proj2_Col a r t` and `t \\<noteq> a` 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 `a \\<noteq> 0` and `r \\<noteq> 0` and `proj2_abs a \\<noteq> proj2_abs r`\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 `proj2_abs (i *\\<^sub>R a + r) = proj2_abs (j *\\<^sub>R a + r)`\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 `a \\<noteq> 0` and `r \\<noteq> 0` and `proj2_abs a \\<noteq> proj2_abs r`\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 `k - l = 0` have \"k = l\" by simp\n  with `k * i - l * j = 0` have \"k * i = k * j\" by simp\n  with `k \\<noteq> 0` 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 `a \\<noteq> r` have \"proj2_abs ?a' \\<noteq> proj2_abs ?r'\" by (simp add: proj2_abs_rep)\n  with `?a' \\<noteq> 0` and `?r' \\<noteq> 0`\n    and `proj2_abs (i *\\<^sub>R ?a' + ?r') = proj2_abs (j *\\<^sub>R ?a' + ?r')`\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 `v \\<noteq> 0`\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 `k \\<noteq> 0`\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 card_ge_dim [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 `l' \\<noteq> 0`\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_inc [of ?B] and `span ?B \\<subseteq> {x. l' \\<bullet> x = 0}`\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 `?l'' = k *\\<^sub>R l'`\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 `proj2_incident p l` and `proj2_incident q l`\n  have \"\\<forall> w\\<in>?A. orthogonal ?m' w\" and \"\\<forall> w\\<in>?A. orthogonal ?l' w\"\n    unfolding proj2_incident_def and orthogonal_def\n    by (simp_all add: inner_commute)\n  from proj2_rep_independent and `p \\<noteq> q` have \"independent ?A\" by simp\n  from proj2_line_rep_non_zero have \"?m' \\<noteq> 0\" by simp\n  with orthogonal_independent\n    and `independent ?A` and `\\<forall> w\\<in>?A. orthogonal ?m' w`\n  have \"independent ?B\" by auto\n\n  from proj2_rep_inj and `p \\<noteq> q` 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  proof\n    assume \"?m' \\<in> ?A\"\n    with span_inc [of ?A] have \"?m' \\<in> span ?A\" by auto\n    with orthogonal_in_span_eq_0 and `\\<forall> w\\<in>?A. orthogonal ?m' w`\n    have \"?m' = 0\" by auto\n    with `?m' \\<noteq> 0` show False ..\n  qed\n  ultimately have \"card ?B = 3\" by simp\n  with independent_is_basis [of ?B] and `independent ?B`\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 `?l' = (\\<Sum> v\\<in>?B. c v *\\<^sub>R v)` and `?m' \\<notin> ?A`\n  have \"?l'' = (\\<Sum> v\\<in>?A. c v *\\<^sub>R v)\" by simp\n  with orthogonal_setsum [of ?A]\n    and `\\<forall> w\\<in>?A. orthogonal ?l' w` and `\\<forall> w\\<in>?A. orthogonal ?m' w`\n  have \"orthogonal ?l' ?l''\" and \"orthogonal ?m' ?l''\"\n    by (simp_all add: scalar_equiv)\n  from `orthogonal ?m' ?l''`\n  have \"orthogonal (c ?m' *\\<^sub>R ?m') ?l''\" by (simp add: orthogonal_clauses)\n  with `orthogonal ?l' ?l''`\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 `proj2_incident p l` and `proj2_incident q l`\n    and proj2_line_through_unique\n  have \"l = proj2_line_through p q\" by simp\n  moreover from `p \\<noteq> q` and `proj2_incident p m` and `proj2_incident q m`\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 `l \\<noteq> m` have \"L2P l \\<noteq> L2P m\" by auto\n  from `proj2_incident p l` and `proj2_incident p m`\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 `L2P l \\<noteq> L2P m` 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 `proj2_incident ?q ?m` and proj2_not_self_incident have \"?q \\<noteq> p\" by auto\n  with `proj2_incident ?q l` 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 `v \\<noteq> 0` 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 `w \\<noteq> 0` 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 `j \\<noteq> 0` and `proj2_rep (proj2_abs v) = j *\\<^sub>R v`\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 `v \\<noteq> 0` 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 `v \\<noteq> 0` 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 `T \\<subseteq> S` and `proj2_set_Col S`\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 `i \\<noteq> 0 \\<or> j \\<noteq> 0 \\<or> k \\<noteq> 0`\n    have \"?x \\<noteq> 0\"\n      unfolding vector_def\n      by (simp add: vec_eq_iff forall_3)\n    moreover {\n      from `i *\\<^sub>R ?u + j *\\<^sub>R ?v + k *\\<^sub>R ?w = 0`\n      have \"?x v* ?M = 0\"\n        unfolding vector_def and vector_matrix_mult_def\n        by (simp add: setsum_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 `x \\<noteq> 0` have \"?i \\<noteq> 0 \\<or> ?j \\<noteq> 0 \\<or> ?k \\<noteq> 0\" by (simp add: vec_eq_iff forall_3)\n    moreover {\n      from `x v* ?M = 0`\n      have \"?i *\\<^sub>R ?u + ?j *\\<^sub>R ?v + ?k *\\<^sub>R ?w = 0\"\n        unfolding vector_matrix_mult_def and setsum_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 `?M *v y = 0`\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 setsum_3\n      by (simp add: vec_eq_iff forall_3)\n    with `y \\<noteq> 0` 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 `\\<forall> s\\<in>{p,q,r}. proj2_incident s l`\n      have \"?M *v ?y = 0\"\n        unfolding vector_def\n          and matrix_vector_mult_def\n          and inner_vec_def\n          and setsum_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 `proj2_incident p l` and `proj2_incident q l` and `proj2_incident r l`\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 `proj2_incident p l` and `proj2_incident q l`\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 `p \\<noteq> q` and `proj2_incident p l` and `proj2_incident q l`\n    and `proj2_incident p m` and `proj2_incident q m`\n    and proj2_incident_unique\n  have \"m = l\" by auto\n  with `proj2_incident r m` 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 `p \\<noteq> q` and `proj2_incident p l` and `proj2_incident q l`\n  have \"proj2_incident r l \\<longleftrightarrow> proj2_Col p q r\" by (rule proj2_incident_iff_Col)\n  with `p \\<noteq> q` 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 `card S = 3` 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 `S = {p,q,r}` 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 and row_def\n        by (auto simp add: vec_lambda_eta) }\n    thus \"{?u, ?v, ?w} \\<subseteq> rows ?M\" ..\n  qed\n  with `S = {p,q,r}`\n  have \"rows ?M = proj2_rep ` S\"\n    unfolding image_def\n    by auto\n  with `\\<not> proj2_set_Col S \\<longleftrightarrow> span (rows ?M) = UNIV`\n  show \"\\<not> proj2_set_Col S \\<longleftrightarrow> span (proj2_rep ` S) = UNIV\" by simp\nqed\n\n\n\n  from `proj2_no_3_Col S` and `p \\<in> S`\n  have \"\\<not> proj2_set_Col (S - {p})\"\n    unfolding proj2_no_3_Col_def\n    by simp\n  with `card (S - {p}) = 3` 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 `\\<not> proj2_Col p q r` and proj2_Col_coincide have \"p \\<noteq> q\" by auto\n  hence \"card {p,q} = 2\" by simp\n\n  from `\\<not> proj2_Col p q r` and proj2_Col_coincide and proj2_Col_permute\n  have \"r \\<notin> {p,q}\" by fast\n  with `card {p,q} = 2` 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 `p \\<noteq> q` 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 `r \\<notin> {p,q}` and `p \\<noteq> q`\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: setsum.insert [of _ _ \"\\<lambda> t. ?c t *\\<^sub>R proj2_rep t\"])\n    also from `finite {r,p,q}` and `?s \\<in> {r,p,q}`\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        setsum.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 `finite {r,p,q}` and `?s \\<in> {r,p,q}`\n    have \"\\<dots> = -j *\\<^sub>R proj2_rep ?s + (\\<Sum> t\\<in>{r,p,q}. proj2_rep t)\"\n      by (simp only:\n        setsum.remove [of \"{r,p,q}\" ?s \"\\<lambda> t. proj2_rep t\",symmetric])\n    also from `(\\<Sum> t\\<in>{r,p,q}. proj2_rep t) = j *\\<^sub>R proj2_rep ?s`\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 `?c p \\<noteq> 0 \\<or> ?c q \\<noteq> 0`\n    have \"proj2_Col p q r\"\n      by (unfold proj2_Col_def) (auto simp add: algebra_simps)\n    with `\\<not> proj2_Col p q r` show False ..\n  qed\n  with `card {r,p,q} = 3` have \"card ?S = 4\" by simp\n\n  from `\\<not> proj2_Col p q r` 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 `card ?S = 4` have \"card (?S - {u}) = 3\" by simp\n    show \"\\<not> proj2_set_Col (?S - {u})\"\n    proof cases\n      assume \"u = ?s\"\n      with `?s \\<notin> {r,p,q}` have \"?S - {u} = {r,p,q}\" by simp\n      with `\\<not> proj2_set_Col {r,p,q}` 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 `finite {r,p,q}` have \"finite ({r,p,q} - {u})\" by simp\n\n      from `?s \\<notin> {r,p,q}` 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 `u \\<noteq> ?s` and  `u \\<in> ?S` 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: setsum.remove)\n      with `(\\<Sum> t\\<in>{r,p,q}. proj2_rep t) = j *\\<^sub>R proj2_rep ?s`\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 `\\<forall> t\\<in>{r,p,q}-{u}. ?d t = -1`\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: setsum_negf)\n      also from `finite ({r,p,q} - {u})`  and `?s \\<notin> {r,p,q} - {u}`\n      have \"\\<dots> = (\\<Sum> t\\<in>insert ?s ({r,p,q}-{u}). ?d t *\\<^sub>R proj2_rep t)\"\n        by (simp add: setsum.insert)\n      also from `insert ?s ({r,p,q} - {u}) = ?S - {u}`\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 (simp add: span_setsum)\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 `proj2_rep u \\<in> span (image proj2_rep (?S - {u}))`\n          show \"proj2_rep t \\<in> span (proj2_rep ` (?S - {u}))\"\n            by (subst `t = u`)\n        next\n          assume \"t \\<noteq> u\"\n          with `t \\<in> {r,p,q}`\n          have \"proj2_rep t \\<in> proj2_rep ` (?S - {u})\" by simp\n          with span_inc [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 `\\<not> proj2_set_Col {r,p,q}`\n        and `card {r,p,q} = 3`\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 `card (?S - {u}) = 3` and not_proj2_set_Col_iff_span\n      show \"\\<not> proj2_set_Col (?S - {u})\" by simp\n    qed\n  qed\n  with `card ?S = 4`\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 `proj2_set_Col S`\n  obtain l where \"\\<forall> t\\<in>S. proj2_incident t l\" unfolding proj2_set_Col_def ..\n  with `{p,q,r} \\<subseteq> S` and `p \\<noteq> q` and `r \\<noteq> p` 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 `invertible A`\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 `invertible A` 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 `invertible A` 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 `A = c *\\<^sub>R cltn2_rep (cltn2_abs A)`\n  have \"?k *\\<^sub>R A = ?k *\\<^sub>R c *\\<^sub>R cltn2_rep (cltn2_abs A)\" by simp\n  with `c \\<noteq> 0` have \"cltn2_rep (cltn2_abs A) = ?k *\\<^sub>R A\" by simp\n  with `?k \\<noteq> 0`\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 `k \\<noteq> 0` and `invertible A` and scalar_invertible\n  have \"invertible (k *\\<^sub>R A)\" by auto\n  with `invertible A`\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 `invertible A` and `invertible (k *\\<^sub>R A)`\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 `x \\<noteq> 0`\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 `invertible A`\n  obtain c where \"c \\<noteq> 0\" and \"cltn2_rep (cltn2_abs A) = c *\\<^sub>R A\" by auto\n\n  from `k \\<noteq> 0` and `c \\<noteq> 0` have \"k * c \\<noteq> 0\" by simp\n\n  from `proj2_rep (proj2_abs x) = k *\\<^sub>R x` and `cltn2_rep (cltn2_abs A) = c *\\<^sub>R A`\n  have \"proj2_rep (proj2_abs x) v* cltn2_rep (cltn2_abs A) = (k*c) *\\<^sub>R (x v* A)\"\n    by (simp add: scalar_vector_matrix_assoc vector_scalar_matrix_ac)\n  with `k * c \\<noteq> 0` \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 `v \\<noteq> 0` 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 `invertible M` 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 `v \\<noteq> 0` 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 `invertible M` and `invertible N` and invertible_mult\n  have \"invertible (M ** N)\" by auto\n\n  from `invertible M` and `invertible N` 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 `j \\<noteq> 0` and `k \\<noteq> 0` have \"j * k \\<noteq> 0\" by simp\n\n  from `cltn2_rep (cltn2_abs M) = j *\\<^sub>R M` and `cltn2_rep (cltn2_abs N) = k *\\<^sub>R N`\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 `j * k \\<noteq> 0` and `invertible (M ** N)`\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 `invertible M` 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 `invertible M` 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 `invertible M` and `invertible N`\n  have \"invertible (M ** N)\" by (simp add: invertible_mult)\n\n  from `invertible M` 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 `cltn2_rep (cltn2_abs M) = k *\\<^sub>R M`\n  have \"cltn2_rep (cltn2_abs M) ** N = k *\\<^sub>R M ** N\" by simp\n  with `k \\<noteq> 0` and `invertible (M ** N)` 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 `invertible (?A' ** ?B')` and `invertible ?C'` 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 `invertible (?B' ** ?C')` 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 `cltn2_rep (cltn2_abs (?B' ** ?C')) = k *\\<^sub>R (?B' ** ?C')`\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 `k \\<noteq> 0` and `invertible (?A' ** ?B' ** ?C')`\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 `cltn2_abs (cltn2_rep (cltn2_abs (?A' ** ?B')) ** ?C')\n    = cltn2_abs (?A' ** ?B' ** ?C')`\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 `invertible ?M` 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 `invertible ?M`\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\n    by auto\n  thus \"apply_cltn2 p cltn2_id = p\"\n    by (simp add: vector_matrix_mul_rid 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 `apply_cltn2 (apply_cltn2 p A) B\n    = proj2_abs (proj2_rep p v* (cltn2_rep A ** cltn2_rep B))`\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 `invertible M` and transpose_invertible have \"invertible (transpose M)\" by auto\n\n  from `invertible M` 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 `cltn2_rep (cltn2_abs M) = k *\\<^sub>R M`\n  have \"transpose (cltn2_rep (cltn2_abs M)) = k *\\<^sub>R transpose M\"\n    by (simp add: transpose_scalar)\n  with `k \\<noteq> 0` and `invertible (transpose M)`\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 `invertible (cltn2_rep A)` and `invertible (cltn2_rep B)`\n    and invertible_mult\n  have \"invertible (cltn2_rep A ** cltn2_rep B)\" by auto\n  with `invertible (cltn2_rep A ** cltn2_rep B)` 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 `invertible (transpose (cltn2_rep B))`\n    and `invertible (transpose (cltn2_rep A))`\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 `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  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 `proj2_set_Col S`\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 `apply_cltn2_line l C = apply_cltn2_line m C`\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 `proj2_incident p l`\n  have \"proj2_incident (apply_cltn2 p C) (apply_cltn2_line l C)\" by simp\n\n  from `proj2_incident q l`\n  have \"proj2_incident (apply_cltn2 q C) (apply_cltn2_line l C)\" by simp\n\n  from `p \\<noteq> q` and apply_cltn2_injective [of p C q]\n  have \"apply_cltn2 p C \\<noteq> apply_cltn2 q C\" by auto\n  with `proj2_incident (apply_cltn2 p C) (apply_cltn2_line l C)`\n    and `proj2_incident (apply_cltn2 q C) (apply_cltn2_line l C)`\n    and `proj2_incident (apply_cltn2 p C) m`\n    and `proj2_incident (apply_cltn2 q C) m`\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 `proj2_incident p l`\n  have \"proj2_incident (apply_cltn2 p C) (apply_cltn2_line l C)\" by simp\n\n  from `proj2_incident p m`\n  have \"proj2_incident (apply_cltn2 p C) (apply_cltn2_line m C)\" by simp\n\n  from `l \\<noteq> m` 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 `proj2_incident (apply_cltn2 p C) (apply_cltn2_line l C)`\n    and `proj2_incident (apply_cltn2 p C) (apply_cltn2_line m C)`\n    and `proj2_incident q (apply_cltn2_line l C)`\n    and `proj2_incident q (apply_cltn2_line m C)`\n    and proj2_incident_unique\n  show \"apply_cltn2 p C = q\" by fast\nqed\n\nsubsubsection {* Parts of some Statements from \\cite{borsuk} *}\ntext {* All theorems with names beginning with \\emph{statement} are based\n  on corresponding theorems in \\cite{borsuk}. *}\n\nlemma statement52_existence:\n  fixes a :: \"proj2^3\" and a3 :: \"proj2\"\n  assumes \"proj2_no_3_Col (insert a3 (range (op $ 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 (op $ a)\"\n\n  from `proj2_no_3_Col (insert a3 (range (op $ a)))`\n  have \"card (insert a3 (range (op $ a))) = 4\" unfolding proj2_no_3_Col_def ..\n\n  from card_image_le [of UNIV \"op $ a\"]\n  have \"card (range (op $ a)) \\<le> 3\" by simp\n  with card_insert_if [of \"range (op $ a)\" a3]\n    and `card (insert a3 (range (op $ a))) = 4`\n  have \"a3 \\<notin> range (op $ a)\" by auto\n  hence \"(insert a3 (range (op $ a))) - {a3} = range (op $ a)\" by simp\n  with `proj2_no_3_Col (insert a3 (range (op $ a)))`\n    and proj2_no_3_Col_span [of \"insert a3 (range (op $ a))\" a3]\n  have \"span ?B = UNIV\" by simp\n\n  from card_suc_ge_insert [of a3 \"range (op $ a)\"]\n    and `card (insert a3 (range (op $ a))) = 4`\n    and `card (range (op $ a)) \\<le> 3`\n  have \"card (range (op $ a)) = 3\" by simp\n  with card_image [of proj2_rep \"range (op $ 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 `span ?B = UNIV` and span_finite [of ?B]\n  obtain c where \"(\\<Sum> w \\<in> ?B. (c w) *\\<^sub>R w) = ?v\" by (auto simp add: scalar_equiv)\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 `a3 \\<notin> range (op $ a)` 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 (op $ a) - {a$i})\"\n\n    have \"a$i \\<in> insert a3 (range (op $ 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 setsum_diff1 [of ?B \"\\<lambda> w. (c w) *\\<^sub>R w\"]\n      and `finite ?B`\n      and `proj2_rep (a$i) \\<in> ?B`\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 `a3 \\<notin> range (op $ a)` have \"a3 \\<noteq> a$i\" by auto\n    hence \"insert a3 (range (op $ a)) - {a$i} =\n      insert a3 (range (op $ a) - {a$i})\" by auto\n    hence \"proj2_rep ` (insert a3 (range (op $ a)) - {a$i}) = insert ?v ?Bi\"\n      by simp\n    moreover from `proj2_no_3_Col (insert a3 (range (op $ a)))`\n      and `a$i \\<in> insert a3 (range (op $ a))`\n    have \"span (proj2_rep ` (insert a3 (range (op $ 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 `?Bi = ?B - {proj2_rep (a$i)}`\n      and `proj2_rep (a$i) \\<in> ?B`\n      and `card ?B = 3`\n    have \"card ?Bi = 2\" by (simp add: card_gt_0_diff_singleton)\n    hence \"finite ?Bi\" by simp\n    with `card ?Bi = 2` and card_ge_dim [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\" by (auto simp: dim_UNIV)\n    with `span (insert ?v ?Bi) = UNIV` and in_span_eq\n    have \"?v \\<notin> span ?Bi\" by auto\n\n    { assume \"c (proj2_rep (a$i)) = 0\"\n      with `(\\<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        and `(\\<Sum> w \\<in> ?B. (c w) *\\<^sub>R w) = ?v`\n      have \"?v = (\\<Sum> w \\<in> ?Bi. (c w) *\\<^sub>R w)\"\n        by simp\n      with span_finite [of ?Bi] and `finite ?Bi`\n      have \"?v \\<in> span ?Bi\" by (simp add: scalar_equiv) auto\n      with `?v \\<notin> span ?Bi` 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 `finite ?B` and span_finite [of ?B] and `span ?B = UNIV`\n    obtain ub where \"(\\<Sum> w\\<in>?B. (ub w) *\\<^sub>R w) = x\" by (auto simp add: scalar_equiv)\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_inc [of \"rows ?C\"] and `rows ?C = image (\\<lambda> w. (c w) *\\<^sub>R w) ?B`\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 `\\<forall> w\\<in>?B. c w \\<noteq> 0` and `w \\<in> ?B`\n      show \"(ub w) *\\<^sub>R w \\<in> span (rows ?C)\" by auto\n    qed\n    with span_setsum [of ?B \"\\<lambda> w. (ub w) *\\<^sub>R w\"] and `finite ?B`\n    have \"(\\<Sum> w\\<in>?B. (ub w) *\\<^sub>R w) \\<in> span (rows ?C)\" by simp\n    with `(\\<Sum> w\\<in>?B. (ub w) *\\<^sub>R w) = x` 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 `invertible ?C`\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 \"op $ a\"] and `card (range (op $ a)) = 3`\n  have \"inj (op $ 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 setsum.reindex\n  [of \"op $ a\" UNIV \"\\<lambda> x. (c (proj2_rep x)) *\\<^sub>R (proj2_rep x)\"]\n    and `inj (op $ a)`\n  have \"\\<dots> = (\\<Sum> x\\<in>(range (op $ a)). (c (proj2_rep x)) *\\<^sub>R (proj2_rep x))\"\n    by simp\n  also from setsum.reindex\n  [of proj2_rep \"range (op $ a)\" \"\\<lambda> w. (c w) *\\<^sub>R w\"]\n    and proj2_rep_inj and subset_inj_on [of proj2_rep UNIV \"range (op $ a)\"]\n  have \"\\<dots> = (\\<Sum> w\\<in>?B. (c w) *\\<^sub>R w)\" by simp\n  also from `(\\<Sum> w \\<in> ?B. (c w) *\\<^sub>R w) = ?v` have \"\\<dots> = ?v\" by simp\n  finally have \"(vector [1,1,1]) v* ?C = ?v\" .\n  with `apply_cltn2 (proj2_abs (vector [1,1,1])) ?A =\n    proj2_abs (vector [1,1,1] v* ?C)`\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 `invertible ?C`\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 setsum.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 `\\<forall> i. c (proj2_rep (a$i)) \\<noteq> 0`\n      and `apply_cltn2 (proj2_abs (axis j 1)) ?A = proj2_abs (axis j 1 v* ?C)`\n    show \"apply_cltn2 (proj2_abs (axis j 1)) ?A = a$j\"\n      by simp\n  qed\n  with `apply_cltn2 (proj2_abs (vector [1,1,1])) ?A = a3`\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 (op $ (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 (op $ (p$i)) = insert (p$i$3) (range (op $ (?q$i)))\"\n    proof    \n      show \"range (op $ (p$i)) \\<supseteq> insert (p$i$3) (range (op $ (?q$i)))\" by auto\n      show \"range (op $ (p$i)) \\<subseteq> insert (p$i$3) (range (op $ (?q$i)))\"\n      proof\n        fix r\n        assume \"r \\<in> range (op $ (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 (op $ (?q$i)))\" by auto\n      qed\n    qed\n    moreover from `\\<forall> i. proj2_no_3_Col (range (op $ (p$i)))`\n    have \"proj2_no_3_Col (range (op $ (p$i)))\" ..\n    ultimately have \"proj2_no_3_Col (insert (p$i$3) (range (op $ (?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 `apply_cltn2 (proj2_abs (vector [1,1,1])) (?D$0) = p$0$3`\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 `apply_cltn2 (proj2_abs (vector [1,1,1])) (?D$1) = p$1$3`\n        and `j = 3`\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')\" by auto\n      with `\\<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      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 `p$0$j = apply_cltn2 (proj2_abs (axis j' 1)) (?D$0)`\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 `p$1$j = apply_cltn2 (proj2_abs (axis j' 1)) (?D$1)`\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 scalar_vector_matrix_assoc)\n  with `j *\\<^sub>R v + k *\\<^sub>R w \\<noteq> 0` and non_zero_mult_rep_non_zero\n  show \"?u \\<noteq> 0\" by simp\n\n  from `?u = (j *\\<^sub>R v + k *\\<^sub>R w) v* cltn2_rep C`\n    and `j *\\<^sub>R v + k *\\<^sub>R w \\<noteq> 0`\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 `apply_cltn2 p C = q`\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 `proj2_rep p v* cltn2_rep C \\<noteq> 0` 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 `j \\<noteq> 0`\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 `apply_cltn2 p C = q` and `apply_cltn2 q C = p`\n  show \"apply_cltn2 (apply_cltn2 r C) C = r\" by simp\nnext\n  assume \"r \\<noteq> p\"\n\n  from `apply_cltn2 p C = q` 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 `apply_cltn2 q C = p` 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 `p \\<noteq> q`\n    and `proj2_incident p l`\n    and `proj2_incident q l`\n    and `proj2_incident r l`\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 `r \\<noteq> p`\n  obtain k where \"r = proj2_abs (k *\\<^sub>R proj2_rep p + proj2_rep q)\" by auto\n\n  from `p \\<noteq> q` 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 `r = proj2_abs (k *\\<^sub>R proj2_rep p + proj2_rep q)`\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 `proj2_rep p v* cltn2_rep C = i *\\<^sub>R proj2_rep q`\n    and `proj2_rep q v* cltn2_rep C = j *\\<^sub>R proj2_rep p`\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 `proj2_rep p v* cltn2_rep C = i *\\<^sub>R proj2_rep q`\n    and `proj2_rep q v* cltn2_rep C = j *\\<^sub>R proj2_rep p`\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 `i \\<noteq> 0` and `j \\<noteq> 0` and proj2_abs_mult\n  have \"\\<dots> = proj2_abs (k *\\<^sub>R proj2_rep p + proj2_rep q)\" by simp\n  also from `r = proj2_abs (k *\\<^sub>R proj2_rep p + proj2_rep q)`\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 `j \\<noteq> 0`\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 `p \\<noteq> q` 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 `?r = proj2_abs ((i/j) *\\<^sub>R proj2_rep p + proj2_rep q)`\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 `(k*i/j) *\\<^sub>R proj2_rep p + k *\\<^sub>R proj2_rep q - proj2_rep ?r = 0`\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 `k \\<noteq> 0` and proj2_rep_dependent have \"p = q\" by simp\n    with `p \\<noteq> q` show False ..\n  qed\n  with `proj2_Col p q ?r` and `p \\<noteq> q`\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 `p \\<noteq> q` and `?r = proj2_abs ((i/j) *\\<^sub>R proj2_rep p + proj2_rep q)`\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 `{p,q,r} \\<subseteq> S` and `proj2_set_Col S`\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 `p \\<noteq> q` and `r \\<noteq> p` 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 `u \\<noteq> 0` and proj2_rep_abs2\n  obtain g where \"g \\<noteq> 0\" and \"proj2_rep ?p = g *\\<^sub>R u\" by auto\n\n  from `v \\<noteq> 0` and proj2_rep_abs2\n  obtain h where \"h \\<noteq> 0\" and \"proj2_rep ?q = h *\\<^sub>R v\" by auto\n  with `g \\<noteq> 0` and `proj2_rep ?p = g *\\<^sub>R u`\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 `?p \\<noteq> ?q` and `h \\<noteq> 0` and `j \\<noteq> 0` and `l \\<noteq> 0` 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 `g \\<noteq> 0` and `h \\<noteq> 0`\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 `?u \\<noteq> 0` and `?v \\<noteq> 0` and `p \\<noteq> q` 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 `cross_ratio_correct p q r s`\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 `proj2_set_Col {p,q,r,s}`\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 `p \\<noteq> q` and `r \\<noteq> p` and `s \\<noteq> p` and `r \\<noteq> q` 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 `proj2_set_Col {?pC,?qC,?rC,?sC}`\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 `proj2_set_Col {p,q,r,s}` and `p \\<noteq> q` and `r \\<noteq> p` and `s \\<noteq> p`\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 `p \\<noteq> q` and apply_cltn2_injective have \"?pC \\<noteq> ?qC\" by fast\n\n  from `p \\<noteq> q` 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 `r = proj2_abs (?i *\\<^sub>R ?u + ?v)` and `s = proj2_abs (?j *\\<^sub>R ?u + ?v)`\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 `?uC \\<noteq> 0` and `?vC \\<noteq> 0` and `proj2_abs ?uC = ?pC`\n    and `proj2_abs ?vC = ?qC` and `?pC \\<noteq> ?qC`\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 `cross_ratio_correct p q r s` and `cross_ratio_correct p q r t`\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 `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 `s \\<noteq> p` and `t \\<noteq> p` 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 `r \\<noteq> q` and `r = proj2_abs (?i *\\<^sub>R ?u + ?v)`\n  have \"?i \\<noteq> 0\" by (auto simp add: proj2_abs_rep)\n  with `cross_ratio p q r s = cross_ratio p q r t`\n  have \"?j = ?k\" by (unfold cross_ratio_def) simp\n  with `s = proj2_abs (?j *\\<^sub>R ?u + ?v)` and `t = proj2_abs (?k *\\<^sub>R ?u + ?v)`\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 `apply_cltn2 p C = p` 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 `proj2_incident p l` and `proj2_incident q l` and `proj2_incident r l`\n    and `proj2_incident s l`\n  have \"proj2_set_Col {p,q,r,s}\" by (unfold proj2_set_Col_def) auto\n  with `p \\<noteq> q` and `r \\<noteq> p` and `s \\<noteq> p` and `r \\<noteq> q`\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 `?pC = p` and `?qC = q` and `?rC = r`\n  have \"cross_ratio_correct p q r ?sC\" by simp\n\n  from `proj2_set_Col {p,q,r,s}` and `p \\<noteq> q` and `r \\<noteq> p` and `s \\<noteq> p`\n  have \"cross_ratio ?pC ?qC ?rC ?sC = cross_ratio p q r s\"\n    by (rule cross_ratio_cltn2)\n  with `?pC = p` and `?qC = q` and `?rC = r`\n  have \"cross_ratio p q r ?sC = cross_ratio p q r s\" by simp\n  with `cross_ratio_correct p q r ?sC` and `cross_ratio_correct p q r s`\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 `cross_ratio_correct p q r s`\n  have \"cross_ratio_correct ?pC ?qC ?rC ?sC\" by (rule cross_ratio_correct_cltn2)\n\n  from `cross_ratio_correct p q r s`\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 `cross_ratio ?pC ?qC ?rC t = cross_ratio p q r s`\n  have \"cross_ratio ?pC ?qC ?rC t = cross_ratio ?pC ?qC ?rC ?sC\" by simp\n  with `cross_ratio_correct ?pC ?qC ?rC t`\n    and `cross_ratio_correct ?pC ?qC ?rC ?sC`\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 `proj2_Col p q r` and `p \\<noteq> q` and `r \\<noteq> p`\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 `proj2_Col_coeff p q r = 0` have \"r = q\" by (simp add: proj2_abs_rep)\n  with `r \\<noteq> q` 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 `proj2_Col p q s` and `p \\<noteq> q` and `s \\<noteq> p` and `s \\<noteq> q`\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 `proj2_Col p q r` and `p \\<noteq> q` and `r \\<noteq> p` and `r \\<noteq> q`\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 `cross_ratio_correct p q r s`\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 `proj2_set_Col {p,q,r,s}`\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 `p \\<noteq> q` and `r \\<noteq> p` and `r \\<noteq> q`\n  have \"cross_ratio_correct p q r r\" by (unfold cross_ratio_correct_def) simp\n\n  from `proj2_set_Col {p,q,r}`\n  have \"proj2_Col p q r\" by (subst proj2_Col_iff_set_Col)\n  with `p \\<noteq> q` and `r \\<noteq> p` and `r \\<noteq> q`\n  have \"cross_ratio p q r r = 1\" by (simp add: cross_ratio_equal_1)\n  with `cross_ratio p q r s = 1`\n  have \"cross_ratio p q r r = cross_ratio p q r s\" by simp\n  with `cross_ratio_correct p q r r` and `cross_ratio_correct p q r s`\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 `cross_ratio_correct p q r s`\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 `p \\<noteq> q` 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 `proj2_set_Col {p,q,r,s}` and `p \\<noteq> q` and `r \\<noteq> p` and `s \\<noteq> p`\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 `r \\<noteq> s` have \"?i \\<noteq> ?j\" by auto\n\n  from `?u \\<noteq> 0` and `?v \\<noteq> 0` and `proj2_abs ?u \\<noteq> proj2_abs ?v`\n    and dependent_proj2_abs [of ?u ?v _ 1]\n  have \"?w \\<noteq> 0\" and \"?x \\<noteq> 0\" by auto\n\n  from `r = proj2_abs (?i *\\<^sub>R ?u + ?v)` and `r \\<noteq> q`\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 `?i \\<noteq> ?j`\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 `?i \\<noteq> ?j`\n  have \"q = proj2_abs (?j *\\<^sub>R ?w - ?i *\\<^sub>R ?x)\" by (simp add: proj2_abs_mult_rep)\n  with `?w \\<noteq> 0` and `?x \\<noteq> 0` and `r \\<noteq> s` and `?i \\<noteq> 0` and `r = proj2_abs ?w`\n    and `s = proj2_abs ?x` and `p = proj2_abs (?w - ?x)`\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 `cross_ratio_correct p q r s`\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 `proj2_set_Col {p,q,r,s}` and `r = s`\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 `proj2_Col p q r` and `p \\<noteq> q` and `r \\<noteq> p` and `r \\<noteq> q` and `r = s`\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 `cross_ratio_correct q p r s`\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 `cross_ratio_correct p q r s` and `r \\<noteq> s`\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 `z_non_zero p`\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 `z_non_zero p` 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 `z_non_zero p`\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 `z_non_zero p`\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 `z_non_zero p` have \"(cart2_append1 p)$3 = 1\" by (rule cart2_append1_z)\n  with `cart2_append1 p = cart2_append1 q`\n  have \"(cart2_append1 q)$3 = 1\" by simp\n  hence \"z_non_zero q\" by (unfold cart2_append1_def) auto\n\n  from `cart2_append1 p = cart2_append1 q`\n  have \"proj2_abs (cart2_append1 p) = proj2_abs (cart2_append1 q)\" by simp\n  with `z_non_zero p` and `z_non_zero q`\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 `z_non_zero p`\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 `proj2_rep (proj2_pt v) = c *\\<^sub>R (vector2_append1 v)`\n  have \"(proj2_rep (proj2_pt v))$3 = c\"\n    unfolding vector2_append1_def and vector_def\n    by simp\n  with `c \\<noteq> 0` 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 `z_non_zero p`\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 `z_non_zero p`\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 `z_non_zero p` and `z_non_zero q`\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 `proj2_pt (cart2_pt p) = p` and `cart2_pt p = cart2_pt q`\n  have \"proj2_pt (cart2_pt q) = p\" by simp\n  with `proj2_pt (cart2_pt q) = q` 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 `i\\<noteq>0` and `j\\<noteq>0` and `k\\<noteq>0` and `i'\\<noteq>0 \\<or> j'\\<noteq>0 \\<or> k'\\<noteq>0`\n    have \"?i''\\<noteq>0 \\<or> ?j''\\<noteq>0 \\<or> ?k''\\<noteq>0\" by simp\n\n    from `i' *\\<^sub>R ?a'' + j' *\\<^sub>R ?b'' + k' *\\<^sub>R ?c'' = 0`\n      and `?a'' = i *\\<^sub>R ?a'`\n      and `?b'' = j *\\<^sub>R ?b'`\n      and `?c'' = k *\\<^sub>R ?c'`\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 `?i'' *\\<^sub>R ?a' + ?j'' *\\<^sub>R ?b' + ?k'' *\\<^sub>R ?c' = 0`\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 `?i'' + ?j'' + ?k'' = 0` have \"?j'' = -?i''\" by simp\n      with `?i''\\<noteq>0 \\<or> ?j''\\<noteq>0 \\<or> ?k''\\<noteq>0` and `?k'' = 0` have \"?i'' \\<noteq> 0\" by simp\n      \n      from `?i'' *\\<^sub>R a + ?j'' *\\<^sub>R b + ?k'' *\\<^sub>R c = 0`\n        and `?k'' = 0` and `?j'' = -?i''`\n      have \"?i'' *\\<^sub>R a + (-?i'' *\\<^sub>R b) = 0\" by simp\n      with `?i'' \\<noteq> 0` 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 `?i'' + ?j'' + ?k'' = 0` have \"?i'' = -(?j'' + ?k'')\" by simp\n      with `?i'' *\\<^sub>R a + ?j'' *\\<^sub>R b + ?k'' *\\<^sub>R c = 0`\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 `?k'' \\<noteq> 0` 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 `b - a = t *\\<^sub>R x` 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 `b - a = t *\\<^sub>R x` and `c - a = s *\\<^sub>R x`\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 `?a' = (1/i) *\\<^sub>R ?a''`\n        and `?b' = (1/j) *\\<^sub>R ?b''`\n        and `?c' = (1/k) *\\<^sub>R ?c''`\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 `t \\<noteq> 0` and `k \\<noteq> 0` 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 `z_non_zero p` and `z_non_zero q` and `z_non_zero r`\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 `z_non_zero p` and `z_non_zero q` and `z_non_zero r`\n    and `real_euclid.Col ?cp ?cq ?cr`\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 `p \\<noteq> q` and `proj2_incident p l` and `proj2_incident q l`\n    and `proj2_incident p m` and `proj2_incident q m` and proj2_incident_unique\n  have \"l = m\" by auto\n  with `proj2_incident r m` 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 `z_non_zero p` and `z_non_zero q` and `z_non_zero r`\n    and `B\\<^sub>\\<real> ?cp ?cq ?cr` 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 `z_non_zero p` and `z_non_zero q` and `z_non_zero r`\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 `?cp1 = cart2_append1 p`\n    and `?cq1 = cart2_append1 q`\n    and `?cr1 = cart2_append1 r`\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 `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 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 `cart2_append1 q = k *\\<^sub>R cart2_append1 r + (1 - k) *\\<^sub>R cart2_append1 p`\n    have \"cart2_append1 q = cart2_append1 r\" by simp\n    with `z_non_zero q` have \"q = r\" by (rule cart2_append1_inj)\n    with `q \\<noteq> r` show False ..\n  qed\n  with `k \\<le> 1` have \"k < 1\" by simp\n  with `k \\<ge> 0`\n    and `cart2_append1 q = k *\\<^sub>R cart2_append1 r + (1 - k) *\\<^sub>R cart2_append1 p`\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 `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    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 `cart2_append1 q = k *\\<^sub>R cart2_append1 r + (1 - k) *\\<^sub>R cart2_append1 p`\n    have \"cart2_append1 q = cart2_append1 p\" by simp\n    with `z_non_zero q` have \"q = p\" by (rule cart2_append1_inj)\n    with `q \\<noteq> p` show False ..\n  qed\n  with `k \\<ge> 0` have \"k > 0\" by simp\n  with `k < 1`\n    and `cart2_append1 q = k *\\<^sub>R cart2_append1 r + (1 - k) *\\<^sub>R cart2_append1 p`\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": "Josh-Tilles", "repo": "AFP", "sha": "f4bf1d502bde2a3469d482b62c531f1c3af3e881", "save_path": "github-repos/isabelle/Josh-Tilles-AFP", "path": "github-repos/isabelle/Josh-Tilles-AFP/AFP-f4bf1d502bde2a3469d482b62c531f1c3af3e881/thys/Tarskis_Geometry/Projective.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312213841788, "lm_q2_score": 0.8104789086703224, "lm_q1q2_score": 0.7353574128977465}}
{"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>\\<open>A\\<close> produces \\<^term>\\<open>Trueprop A\\<close> internally. From the Pure\n  perspective this means ``\\<^prop>\\<open>A\\<close> 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>\\<open>equal\\<close> 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>\\<open>\"Gentzen:1935\"\\<close>.\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>\\<open>A \\<and> B\\<close> involves an immediate decision which component should be projected.\n  The more convenient simultaneous elimination \\<^prop>\\<open>A \\<and> B \\<Longrightarrow> (A \\<Longrightarrow> B \\<Longrightarrow> C) \\<Longrightarrow>\n  C\\<close> 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>\\<open>(\\<not> C \\<Longrightarrow> C)\n  \\<Longrightarrow> C\\<close> 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>\\<open>\"church40\"\\<close>, quantifiers are operators on predicates, which\n  are syntactically represented as \\<open>\\<lambda>\\<close>-terms of type \\<^typ>\\<open>i \\<Rightarrow> o\\<close>. 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": "seL4", "repo": "isabelle", "sha": "e1ab32a3bb41728cd19541063283e37919978a4c", "save_path": "github-repos/isabelle/seL4-isabelle", "path": "github-repos/isabelle/seL4-isabelle/isabelle-e1ab32a3bb41728cd19541063283e37919978a4c/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.8824278788223264, "lm_q2_score": 0.8333246015211008, "lm_q1q2_score": 0.7353488604907253}}
{"text": "(*\nTitle:KoenigsbergBridge.thy\nAuthor:Wenda Li\n*)\n\ntheory KoenigsbergBridge imports MoreGraph\nbegin\n\nsection\\<open>Definition of Eulerian trails and circuits\\<close>\n\ndefinition (in valid_unMultigraph) is_Eulerian_trail:: \"'v\\<Rightarrow>('v,'w) path\\<Rightarrow>'v\\<Rightarrow> bool\" where\n  \"is_Eulerian_trail v ps v'\\<equiv> is_trail v ps v' \\<and> edges (rem_unPath ps G) = {}\"\n\ndefinition (in valid_unMultigraph) is_Eulerian_circuit:: \"'v \\<Rightarrow> ('v,'w) path \\<Rightarrow> 'v \\<Rightarrow> bool\" where\n  \"is_Eulerian_circuit v ps v'\\<equiv> (v=v') \\<and> (is_Eulerian_trail v ps v')\"\n\nsection\\<open>Necessary conditions for Eulerian trails and circuits\\<close>\n\nlemma (in valid_unMultigraph) euclerian_rev:\n  \"is_Eulerian_trail v' (rev_path ps) v=is_Eulerian_trail v ps v' \"\nproof -\n  have \"is_trail v' (rev_path ps) v=is_trail v ps v'\"\n    by (metis is_trail_rev)\n  moreover have \"edges (rem_unPath (rev_path ps) G)=edges (rem_unPath ps G)\"\n    by (metis rem_unPath_graph)\n  ultimately show ?thesis unfolding is_Eulerian_trail_def by auto\nqed\n\n(*Necessary conditions for Eulerian circuits*)\ntheorem (in valid_unMultigraph) euclerian_cycle_ex:\n  assumes \"is_Eulerian_circuit v ps v'\" \"finite V\" \"finite E\"\n  shows \"\\<forall>v\\<in>V. even (degree v G)\"\nproof -\n  obtain v ps v' where cycle:\"is_Eulerian_circuit v ps v'\" using assms by auto\n  hence \"edges (rem_unPath ps G) = {}\"\n    unfolding is_Eulerian_circuit_def is_Eulerian_trail_def\n    by simp\n  moreover have \"nodes (rem_unPath ps G)=nodes G\" by auto\n  ultimately have \"rem_unPath ps G = G \\<lparr>edges:={}\\<rparr>\" by auto\n  hence \"num_of_odd_nodes (rem_unPath ps G) = 0\" by (metis assms(2) odd_nodes_no_edge)\n  moreover have \"v=v'\"\n    by (metis \\<open>is_Eulerian_circuit v ps v'\\<close> is_Eulerian_circuit_def)\n  hence \"num_of_odd_nodes (rem_unPath ps G)=num_of_odd_nodes G\"\n    by (metis assms(2) assms(3) cycle is_Eulerian_circuit_def\n        is_Eulerian_trail_def rem_UnPath_cycle)\n  ultimately have \"num_of_odd_nodes G=0\" by auto\n  moreover have \"finite(odd_nodes_set G)\"\n    using \\<open>finite V\\<close> unfolding odd_nodes_set_def by auto\n  ultimately have \"odd_nodes_set G = {}\" unfolding num_of_odd_nodes_def by auto\n  thus ?thesis unfolding odd_nodes_set_def by auto\nqed\n\n(*Necessary conditions for Eulerian trails*)\ntheorem (in valid_unMultigraph) euclerian_path_ex:\n  assumes \"is_Eulerian_trail v ps v'\" \"finite V\" \"finite E\"\n  shows \"(\\<forall>v\\<in>V. even (degree v G)) \\<or> (num_of_odd_nodes G =2)\"\nproof -\n  obtain v ps v' where path:\"is_Eulerian_trail v ps v'\" using assms by auto\n  hence \"edges (rem_unPath ps G) = {}\"\n    unfolding  is_Eulerian_trail_def\n    by simp\n  moreover have \"nodes (rem_unPath ps G)=nodes G\" by auto\n  ultimately have \"rem_unPath ps G = G \\<lparr>edges:={}\\<rparr>\" by auto\n  hence odd_nodes: \"num_of_odd_nodes (rem_unPath ps G) = 0\"\n    by (metis assms(2) odd_nodes_no_edge)\n  have \"v\\<noteq>v' \\<Longrightarrow> ?thesis\"\n    proof (cases \"even(degree v' G)\")\n      case True\n      assume \"v\\<noteq>v'\"\n      have \"is_trail v ps v'\" by (metis is_Eulerian_trail_def path)\n      hence \"num_of_odd_nodes (rem_unPath ps G) = num_of_odd_nodes G\n          + (if even (degree v G) then 2 else 0)\"\n        using rem_UnPath_even True \\<open>finite V\\<close> \\<open>finite E\\<close> \\<open>v\\<noteq>v'\\<close> by auto\n      hence \"num_of_odd_nodes G + (if even (degree v G) then 2 else 0)=0\"\n        using odd_nodes by auto\n      hence \"num_of_odd_nodes G = 0\" by auto\n      moreover have \"finite(odd_nodes_set G)\"\n        using \\<open>finite V\\<close> unfolding odd_nodes_set_def by auto\n      ultimately have \"odd_nodes_set G = {}\" unfolding num_of_odd_nodes_def by auto\n      thus ?thesis unfolding odd_nodes_set_def by auto\n    next\n      case False\n      assume \"v\\<noteq>v'\"\n      have \"is_trail v ps v'\" by (metis is_Eulerian_trail_def path)\n      hence \"num_of_odd_nodes (rem_unPath ps G) = num_of_odd_nodes G\n          + (if odd (degree v G) then -2 else 0)\"\n        using rem_UnPath_odd False \\<open>finite V\\<close> \\<open>finite E\\<close> \\<open>v\\<noteq>v'\\<close> by auto\n      hence odd_nodes_if: \"num_of_odd_nodes G + (if odd (degree v G) then -2 else 0)=0\"\n        using odd_nodes by auto\n      have \"odd (degree v G) \\<Longrightarrow> ?thesis\"\n        proof -\n          assume \"odd (degree v G)\"\n          hence \"num_of_odd_nodes G = 2\" using odd_nodes_if by auto\n          thus ?thesis by simp\n        qed\n      moreover have \"even(degree v G) \\<Longrightarrow> ?thesis\"\n        proof -\n          assume \"even (degree v G)\"\n          hence \"num_of_odd_nodes G = 0\" using odd_nodes_if by auto\n          moreover have \"finite(odd_nodes_set G)\"\n            using \\<open>finite V\\<close> unfolding odd_nodes_set_def by auto\n          ultimately have \"odd_nodes_set G = {}\" unfolding num_of_odd_nodes_def by auto\n          thus ?thesis unfolding odd_nodes_set_def by auto\n        qed\n      ultimately show ?thesis by auto\n    qed\n  moreover have \"v=v'\\<Longrightarrow> ?thesis\"\n    by (metis assms(2) assms(3) euclerian_cycle_ex is_Eulerian_circuit_def path)\n  ultimately show ?thesis by auto\nqed\n\nsection\\<open>Specific case of the Konigsberg Bridge Problem\\<close>\n\n(*to denote the four landmasses*)\ndatatype kon_node = a | b | c | d\n\n(*to denote the seven bridges*)\ndatatype kon_bridge = ab1 | ab2 | ac1 | ac2 | ad1 | bd1 | cd1\n\ndefinition kon_graph :: \"(kon_node,kon_bridge) graph\" where\n  \"kon_graph\\<equiv>\\<lparr>nodes={a,b,c,d},\n              edges={(a,ab1,b), (b,ab1,a),\n                     (a,ab2,b), (b,ab2,a),\n                     (a,ac1,c), (c,ac1,a),\n                     (a,ac2,c), (c,ac2,a),\n                     (a,ad1,d), (d,ad1,a),\n                     (b,bd1,d), (d,bd1,b),\n                     (c,cd1,d), (d,cd1,c)} \\<rparr>\"\n\ninstantiation kon_node :: enum\nbegin\ndefinition [simp]:  \"enum_class.enum =[a,b,c,d]\"\ndefinition  [simp]: \"enum_class.enum_all P \\<longleftrightarrow> P a \\<and> P b \\<and> P c \\<and> P d\"\ndefinition   [simp]:\"enum_class.enum_ex P \\<longleftrightarrow> P a \\<or> P b \\<or> P c \\<or> P d\"\ninstance proof qed (auto,(case_tac x,auto)+)\nend\n\ninstantiation kon_bridge :: enum\nbegin\ndefinition [simp]:\"enum_class.enum =[ab1,ab2,ac1,ac2,ad1,cd1,bd1]\"\ndefinition  [simp]:\"enum_class.enum_all P \\<longleftrightarrow> P ab1 \\<and> P ab2 \\<and> P ac1 \\<and> P ac2 \\<and> P ad1  \\<and> P bd1\n    \\<and> P cd1\"\ndefinition   [simp]:\"enum_class.enum_ex P \\<longleftrightarrow>  P ab1 \\<or> P ab2 \\<or> P ac1 \\<or> P ac2 \\<or> P ad1  \\<or> P bd1\n    \\<or> P cd1\"\ninstance proof qed (auto,(case_tac x,auto)+)\nend\n\ninterpretation   kon_graph: valid_unMultigraph kon_graph\nproof (unfold_locales)\n  show \"fst ` edges kon_graph \\<subseteq> nodes kon_graph\" by eval\nnext\n  show \"snd ` snd ` edges kon_graph \\<subseteq> nodes kon_graph\"  by eval\nnext\n  have \" \\<forall>v w u'. ((v, w, u') \\<in> edges kon_graph) = ((u', w, v) \\<in> edges kon_graph)\"\n    by eval\n  thus \"\\<And>v w u'. ((v, w, u') \\<in> edges kon_graph) = ((u', w, v) \\<in> edges kon_graph)\" by simp\nnext\n  have \"\\<forall>v w. (v, w, v) \\<notin> edges kon_graph\"  by eval\n  thus \"\\<And>v w. (v, w, v) \\<notin> edges kon_graph\" by simp\nqed\n\n(*The specific case of the Konigsberg Bridge Problem does not have a solution*)\ntheorem \"\\<not>kon_graph.is_Eulerian_trail v1 p v2\"\nproof\n  assume \"kon_graph.is_Eulerian_trail  v1 p v2\"\n  moreover have \"finite (nodes kon_graph)\" by (metis finite_code)\n  moreover have \"finite (edges kon_graph)\" by (metis finite_code)\n  ultimately have contra:\n    \"(\\<forall>v\\<in>nodes kon_graph. even (degree v kon_graph)) \\<or>(num_of_odd_nodes kon_graph =2)\"\n    by (metis kon_graph.euclerian_path_ex)\n  have \"odd(degree a kon_graph)\" by eval\n  moreover have \"odd(degree b kon_graph)\" by eval\n  moreover have \"odd(degree c kon_graph)\" by eval\n  moreover have \"odd(degree d kon_graph)\" by eval\n  ultimately have \"\\<not>(num_of_odd_nodes kon_graph =2)\" by eval\n  moreover have \"\\<not>(\\<forall>v\\<in>nodes kon_graph. even (degree v kon_graph))\" by eval\n  ultimately show False using contra by auto\nqed\n\nsection\\<open>Sufficient conditions for Eulerian trails and circuits\\<close>\n\nlemma (in valid_unMultigraph) eulerian_cons:\n  assumes\n    \"valid_unMultigraph.is_Eulerian_trail (del_unEdge v0 w v1 G) v1 ps v2\"\n    \"(v0,w,v1)\\<in> E\"\n  shows \"is_Eulerian_trail v0 ((v0,w,v1)#ps) v2\"\nproof -\n  have valid:\"valid_unMultigraph (del_unEdge v0 w v1 G)\"\n    using  valid_unMultigraph_axioms by auto\n  hence distinct:\"valid_unMultigraph.is_trail (del_unEdge v0 w v1 G) v1 ps v2\"\n    using assms unfolding valid_unMultigraph.is_Eulerian_trail_def[OF valid]\n    by auto\n  hence \"set ps \\<subseteq> edges (del_unEdge v0 w v1 G)\"\n    using valid_unMultigraph.path_in_edges[OF valid] by auto\n  moreover have \"(v0,w,v1)\\<notin>edges (del_unEdge v0 w v1 G)\"\n    unfolding del_unEdge_def by auto\n  moreover have \"(v1,w,v0)\\<notin>edges (del_unEdge v0 w v1 G)\"\n    unfolding del_unEdge_def by auto\n  ultimately have \"(v0,w,v1)\\<notin>set ps\" \"(v1,w,v0)\\<notin>set ps\"  by auto\n  moreover have \"is_trail v1 ps v2\"\n    using distinct_path_intro[OF distinct] .\n  ultimately have \"is_trail v0 ((v0,w,v1)#ps) v2\"\n    using \\<open>(v0,w,v1)\\<in> E\\<close> by auto\n  moreover have \"edges (rem_unPath ps (del_unEdge v0 w v1 G)) ={}\"\n    using assms unfolding valid_unMultigraph.is_Eulerian_trail_def[OF valid]\n    by auto\n  hence \"edges (rem_unPath ((v0,w,v1)#ps) G)={}\"\n    by (metis rem_unPath.simps(2))\n  ultimately show ?thesis unfolding is_Eulerian_trail_def by auto\nqed\n\nlemma (in valid_unMultigraph) eulerian_cons':\n  assumes\n    \"valid_unMultigraph.is_Eulerian_trail (del_unEdge v2 w v3 G) v1 ps v2\"\n    \"(v2,w,v3)\\<in> E\"\n  shows \"is_Eulerian_trail v1 (ps@[(v2,w,v3)]) v3\"\nproof -\n  have valid:\"valid_unMultigraph (del_unEdge v3 w v2 G)\"\n    using valid_unMultigraph_axioms del_unEdge_valid by auto\n  have \"del_unEdge v2 w v3 G=del_unEdge v3 w v2 G\"\n    by (metis delete_edge_sym)\n  hence \"valid_unMultigraph.is_Eulerian_trail (del_unEdge v3 w v2 G) v2\n        (rev_path ps) v1\" using assms valid_unMultigraph.euclerian_rev[OF valid]\n    by auto\n  hence \"is_Eulerian_trail v3 ((v3,w,v2)#(rev_path ps)) v1\"\n    using eulerian_cons by (metis assms(2) corres)\n  hence \"is_Eulerian_trail v1 (rev_path((v3,w,v2)#(rev_path ps))) v3\"\n    using euclerian_rev by auto\n  moreover have \"rev_path((v3,w,v2)#(rev_path ps)) = rev_path(rev_path ps)@[(v2,w,v3)]\"\n    unfolding rev_path_def by auto\n  hence \"rev_path((v3,w,v2)#(rev_path ps))=ps@[(v2,w,v3)]\" by auto\n  ultimately show ?thesis by auto\nqed\n\nlemma eulerian_split:\n  assumes \"nodes G1 \\<inter> nodes G2 = {}\" \"edges G1 \\<inter> edges G2={}\"\n    \"valid_unMultigraph G1\" \"valid_unMultigraph G2\"\n    \"valid_unMultigraph.is_Eulerian_trail  G1 v1 ps1 v1'\"\n    \"valid_unMultigraph.is_Eulerian_trail  G2 v2 ps2 v2'\"\n  shows \"valid_unMultigraph.is_Eulerian_trail \\<lparr>nodes=nodes G1 \\<union> nodes G2,\n          edges=edges G1 \\<union> edges G2 \\<union> {(v1',w,v2),(v2,w,v1')}\\<rparr> v1 (ps1@(v1',w,v2)#ps2) v2'\"\nproof -\n  have \"valid_graph G1\" using \\<open>valid_unMultigraph G1\\<close> valid_unMultigraph_def by auto\n  have \"valid_graph G2\" using \\<open>valid_unMultigraph G2\\<close> valid_unMultigraph_def by auto\n  obtain G where G:\"G=\\<lparr>nodes=nodes G1 \\<union> nodes G2, edges=edges G1 \\<union> edges G2\n      \\<union> {(v1',w,v2),(v2,w,v1')}\\<rparr>\"\n    by metis\n  have \"v1'\\<in>nodes G1\"\n    by (metis (full_types) \\<open>valid_graph G1\\<close> assms(3) assms(5) valid_graph.is_path_memb\n        valid_unMultigraph.is_trail_intro valid_unMultigraph.is_Eulerian_trail_def)\n  moreover have \"v2\\<in>nodes G2\"\n    by (metis (full_types) \\<open>valid_graph G2\\<close> assms(4) assms(6) valid_graph.is_path_memb\n        valid_unMultigraph.is_trail_intro valid_unMultigraph.is_Eulerian_trail_def)\n  ultimately have \"valid_unMultigraph \\<lparr>nodes=nodes G1 \\<union> nodes G2, edges=edges G1 \\<union> edges G2 \\<union>\n                   {(v1',w,v2),(v2,w,v1')}\\<rparr>\"\n    using\n      valid_unMultigraph.corres[OF \\<open>valid_unMultigraph G1\\<close>]\n      valid_unMultigraph.no_id[OF \\<open>valid_unMultigraph G1\\<close>]\n      valid_unMultigraph.corres[OF \\<open>valid_unMultigraph G2\\<close>]\n      valid_unMultigraph.no_id[OF \\<open>valid_unMultigraph G2\\<close>]\n      valid_graph.E_validD[OF \\<open>valid_graph G1\\<close>]\n      valid_graph.E_validD[OF \\<open>valid_graph G2\\<close>]\n      \\<open>nodes G1 \\<inter> nodes G2 = {}\\<close>\n    proof (unfold_locales,auto)\n      fix aa ab ba\n      assume  \"(aa, ab, ba) \\<in> edges G1\"\n      thus \"ba \\<in> nodes G1\" by (metis \\<open>\\<And>v' v e. (v, e, v') \\<in> edges G1 \\<Longrightarrow> v' \\<in> nodes G1\\<close>)\n    next\n      fix aa ab ba\n      assume \"ba \\<notin> nodes G2\"  \"(aa, ab, ba) \\<in> edges G2\"\n      thus \"ba \\<in> nodes G1\" by (metis \\<open>valid_graph G2\\<close> valid_graph.E_validD(2))\n    qed\n  hence valid: \"valid_unMultigraph G\" using G by auto\n  hence valid':\"valid_graph G\" using valid_unMultigraph_def by auto\n  moreover have \"valid_unMultigraph.is_trail G v1 (ps1@((v1',w,v2)#ps2)) v2'\"\n    proof -\n      have ps1_G:\"valid_unMultigraph.is_trail G v1 ps1 v1'\"\n        proof -\n          have \"valid_unMultigraph.is_trail G1 v1 ps1 v1'\" using assms\n            by (metis valid_unMultigraph.is_Eulerian_trail_def)\n          moreover have \"edges G1 \\<subseteq> edges G\" by (metis G UnI1 Un_assoc select_convs(2) subrelI)\n          moreover have \"nodes G1 \\<subseteq> nodes G\" by (metis G inf_sup_absorb le_iff_inf select_convs(1))\n          ultimately show ?thesis\n            using distinct_path_subset[of G1 G,OF \\<open>valid_unMultigraph G1\\<close> valid] by auto\n        qed\n      have ps2_G:\"valid_unMultigraph.is_trail G v2 ps2 v2'\"\n        proof -\n          have \"valid_unMultigraph.is_trail G2 v2 ps2 v2'\" using assms\n            by (metis valid_unMultigraph.is_Eulerian_trail_def)\n          moreover have \"edges G2 \\<subseteq> edges G\" by (metis G inf_sup_ord(3) le_supE select_convs(2))\n          moreover have \"nodes G2 \\<subseteq> nodes G\" by (metis G inf_sup_ord(4) select_convs(1))\n          ultimately show ?thesis\n            using distinct_path_subset[of G2 G,OF \\<open>valid_unMultigraph G2\\<close> valid] by auto\n        qed\n      have \"valid_graph.is_path G v1 (ps1@((v1',w,v2)#ps2)) v2'\"\n        proof -\n          have \"valid_graph.is_path  G v1 ps1 v1'\"\n            by (metis ps1_G valid valid_unMultigraph.is_trail_intro)\n          moreover have \"valid_graph.is_path G v2 ps2 v2'\"\n            by (metis ps2_G valid valid_unMultigraph.is_trail_intro)\n          moreover have \"(v1',w,v2) \\<in> edges G\"\n            using G by auto\n          ultimately show ?thesis\n            using valid_graph.is_path_split'[OF valid',of v1 ps1 v1' w v2 ps2 v2'] by auto\n        qed\n      moreover have \"distinct (ps1@((v1',w,v2)#ps2))\"\n        proof -\n          have \"distinct ps1\" by (metis ps1_G valid valid_unMultigraph.is_trail_path)\n          moreover have \"distinct ps2\"\n            by (metis ps2_G valid valid_unMultigraph.is_trail_path)\n          moreover have \"set ps1 \\<inter> set ps2 = {}\"\n            proof -\n              have \"set ps1 \\<subseteq>edges G1\"\n                by (metis assms(3) assms(5) valid_unMultigraph.is_Eulerian_trail_def\n                    valid_unMultigraph.path_in_edges)\n              moreover have \"set ps2 \\<subseteq> edges G2\"\n                by (metis assms(4) assms(6) valid_unMultigraph.is_Eulerian_trail_def\n                    valid_unMultigraph.path_in_edges)\n              ultimately show ?thesis using \\<open>edges G1 \\<inter> edges G2={}\\<close> by auto\n            qed\n          moreover have \"(v1',w,v2)\\<notin>edges G1\"\n            using \\<open>v2 \\<in> nodes G2\\<close> \\<open>valid_graph G1\\<close>\n            by (metis Int_iff  all_not_in_conv assms(1) valid_graph.E_validD(2))\n          hence \"(v1',w,v2)\\<notin>set ps1\"\n            by (metis (full_types) assms(3) assms(5) subsetD valid_unMultigraph.path_in_edges\n                valid_unMultigraph.is_Eulerian_trail_def )\n          moreover have \"(v1',w,v2)\\<notin>edges G2\"\n            using \\<open>v1' \\<in> nodes G1\\<close> \\<open>valid_graph G2\\<close>\n            by (metis  assms(1) disjoint_iff_not_equal valid_graph.E_validD(1))\n          hence  \"(v1',w,v2)\\<notin>set ps2\"\n            by (metis (full_types)  assms(4) assms(6) in_mono valid_unMultigraph.path_in_edges\n                valid_unMultigraph.is_Eulerian_trail_def )\n          ultimately show ?thesis using distinct_append by auto\n        qed\n      moreover have \"set (ps1@((v1',w,v2)#ps2)) \\<inter> set (rev_path (ps1@((v1',w,v2)#ps2))) = {}\"\n        proof -\n          have \"set ps1 \\<inter> set (rev_path ps1) = {}\"\n            by (metis ps1_G valid valid_unMultigraph.is_trail_path)\n          moreover have \"set (rev_path ps2) \\<subseteq> edges G2\"\n            by (metis assms(4) assms(6) valid_unMultigraph.is_trail_rev\n                valid_unMultigraph.is_Eulerian_trail_def valid_unMultigraph.path_in_edges)\n          hence \"set ps1 \\<inter> set (rev_path ps2) = {}\"\n            using assms\n              valid_unMultigraph.path_in_edges[OF \\<open>valid_unMultigraph G1\\<close>, of v1 ps1 v1']\n              valid_unMultigraph.path_in_edges[OF \\<open>valid_unMultigraph G2\\<close>, of v2 ps2 v2']\n            unfolding valid_unMultigraph.is_Eulerian_trail_def[OF \\<open>valid_unMultigraph G1\\<close>]\n              valid_unMultigraph.is_Eulerian_trail_def[OF \\<open>valid_unMultigraph G2\\<close>]\n            by auto\n          moreover have \"set ps2 \\<inter> set (rev_path ps2) = {}\"\n            by (metis ps2_G valid valid_unMultigraph.is_trail_path)\n          moreover have \"set (rev_path ps1) \\<subseteq>edges G1\"\n            by (metis assms(3) assms(5) valid_unMultigraph.is_Eulerian_trail_def\n                valid_unMultigraph.path_in_edges valid_unMultigraph.euclerian_rev)\n          hence \"set ps2 \\<inter> set (rev_path ps1) = {}\"\n            by (metis calculation(2) distinct_append distinct_rev_path ps1_G ps2_G rev_path_append\n              rev_path_double valid valid_unMultigraph.is_trail_path)\n          moreover have \"(v2,w,v1')\\<notin>set (ps1@((v1',w,v2)#ps2))\"\n            proof -\n              have \"(v2,w,v1')\\<notin>edges G1\"\n                using \\<open>v2 \\<in> nodes G2\\<close> \\<open>valid_graph G1\\<close>\n                by (metis Int_iff  all_not_in_conv assms(1) valid_graph.E_validD(1))\n              hence \"(v2,w,v1')\\<notin>set ps1\"\n                by (metis assms(3) assms(5) split_list valid_unMultigraph.is_trail_split'\n                    valid_unMultigraph.is_Eulerian_trail_def)\n              moreover have \"(v2,w,v1')\\<notin>edges G2\"\n                using \\<open>v1' \\<in> nodes G1\\<close> \\<open>valid_graph G2\\<close>\n                by (metis IntI assms(1) empty_iff valid_graph.E_validD(2))\n              hence \"(v2,w,v1')\\<notin>set ps2\"\n                by (metis (full_types) assms(4) assms(6) in_mono  valid_unMultigraph.path_in_edges\n                    valid_unMultigraph.is_Eulerian_trail_def)\n              moreover have \"(v2,w,v1')\\<noteq>(v1',w,v2)\"\n                using \\<open>v1' \\<in> nodes G1\\<close> \\<open>v2 \\<in> nodes G2\\<close>\n                by (metis IntI Pair_inject  assms(1) assms(5) bex_empty)\n              ultimately show ?thesis by auto\n            qed\n          ultimately show ?thesis using rev_path_append by auto\n        qed\n      ultimately show ?thesis using valid_unMultigraph.is_trail_path[OF valid]\n        by auto\n    qed\n  moreover have \"edges (rem_unPath (ps1@((v1',w,v2)#ps2)) G)= {}\"\n    proof -\n      have \"edges (rem_unPath (ps1@((v1',w,v2)#ps2)) G)=edges G -\n           (set (ps1@((v1',w,v2)#ps2)) \\<union> set (rev_path (ps1@((v1',w,v2)#ps2))))\"\n        by (metis rem_unPath_edges)\n      also have \"...=edges G - (set ps1 \\<union> set ps2 \\<union> set (rev_path ps1) \\<union> set (rev_path ps2)\n                 \\<union> {(v1',w,v2),(v2,w,v1')})\" using rev_path_append by auto\n      finally have \"edges (rem_unPath (ps1@((v1',w,v2)#ps2)) G) = edges G - (set ps1 \\<union>\n                    set ps2 \\<union> set (rev_path ps1) \\<union> set (rev_path ps2) \\<union> {(v1',w,v2),(v2,w,v1')})\" .\n      moreover have \"edges (rem_unPath ps1 G1)={}\"\n        by (metis assms(3) assms(5) valid_unMultigraph.is_Eulerian_trail_def)\n      hence \"edges G1 - (set ps1 \\<union> set (rev_path ps1))={}\"\n        by (metis rem_unPath_edges)\n      moreover have \"edges (rem_unPath ps2 G2)={}\"\n        by (metis assms(4) assms(6) valid_unMultigraph.is_Eulerian_trail_def)\n      hence \"edges G2 - (set ps2 \\<union> set (rev_path ps2))={}\"\n        by (metis rem_unPath_edges)\n      ultimately show ?thesis using G by auto\n    qed\n  ultimately show ?thesis by (metis G valid valid_unMultigraph.is_Eulerian_trail_def)\nqed\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/Koenigsberg_Friendship/KoenigsbergBridge.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.89181104831338, "lm_q2_score": 0.8244619350028204, "lm_q1q2_score": 0.735264262549343}}
{"text": "section \\<open>CCW for Nonaligned Points in the Plane\\<close>\ntheory Counterclockwise_2D_Strict\n  imports\n    Counterclockwise_Vector\n    Affine_Arithmetic_Auxiliarities\nbegin\ntext \\<open>\\label{sec:counterclockwise2d}\\<close>\n\nsubsection \\<open>Determinant\\<close>\n\ntype_synonym point = \"real*real\"\n\nfun det3::\"point \\<Rightarrow> point \\<Rightarrow> point \\<Rightarrow> real\" where \"det3 (xp, yp) (xq, yq) (xr, yr) =\n  xp * yq + yp * xr + xq * yr - yq * xr - yp * xq - xp * yr\"\n\nlemma det3_def':\n  \"det3 p q r = fst p * snd q + snd p * fst r + fst q * snd r -\n    snd q * fst r - snd p * fst q - fst p * snd r\"\n  by (cases p q r rule: prod.exhaust[case_product prod.exhaust[case_product prod.exhaust]]) auto\n\nlemma det3_eq_det: \"det3 (xa, ya) (xb, yb) (xc, yc) =\n  det (vector [vector [xa, ya, 1], vector [xb, yb, 1], vector [xc, yc, 1]]::real^3^3)\"\n  unfolding Determinants.det_def UNIV_3\n  by (auto simp: sum_over_permutations_insert\n    vector_3 sign_swap_id permutation_swap_id sign_compose)\n\ndeclare det3.simps[simp del]\n\nlemma det3_self23[simp]: \"det3 a b b = 0\"\n  and det3_self12[simp]: \"det3 b b a = 0\"\n  by (auto simp: det3_def')\n\nlemma\n  coll_ex_scaling:\n  assumes \"b \\<noteq> c\"\n  assumes d: \"det3 a b c = 0\"\n  shows \"\\<exists>r. a = b + r *\\<^sub>R (c - b)\"\nproof -\n  from assms have \"fst b \\<noteq> fst c \\<or> snd b \\<noteq> snd c\" by (auto simp: prod_eq_iff)\n  thus ?thesis\n  proof\n    assume neq: \"fst b \\<noteq> fst c\"\n    with d have \"snd a = ((fst a - fst b) * snd c + (fst c - fst a) * snd b) / (fst c - fst b)\"\n      by (auto simp: det3_def' field_simps)\n    hence \"snd a = ((fst a - fst b)/ (fst c - fst b)) * snd c +\n      ((fst c - fst a)/ (fst c - fst b)) * snd b\"\n      by (simp add: add_divide_distrib)\n    hence \"snd a = snd b + (fst a - fst b) * snd c / (fst c - fst b) +\n      ((fst c - fst a) - (fst c - fst b)) * snd b / (fst c - fst b)\"\n      using neq\n      by (simp add: field_simps)\n    hence \"snd a = snd b + ((fst a - fst b) * snd c + (- fst a + fst b) * snd b) / (fst c - fst b)\"\n      unfolding add_divide_distrib\n      by (simp add: algebra_simps)\n    also\n    have \"(fst a - fst b) * snd c + (- fst a + fst b) * snd b = (fst a - fst b) * (snd c - snd b)\"\n      by (simp add: algebra_simps)\n    finally have \"snd a = snd b + (fst a - fst b) / (fst c - fst b) * (snd c - snd b)\"\n      by simp\n    moreover\n    hence \"fst a = fst b + (fst a - fst b) / (fst c - fst b) * (fst c - fst b)\"\n      using neq by simp\n    ultimately have \"a = b + ((fst a - fst b) / (fst c - fst b)) *\\<^sub>R (c - b)\"\n      by (auto simp: prod_eq_iff)\n    thus ?thesis by blast\n  next\n    assume neq: \"snd b \\<noteq> snd c\"\n    with d have \"fst a = ((snd a - snd b) * fst c + (snd c - snd a) * fst b) / (snd c - snd b)\"\n      by (auto simp: det3_def' field_simps)\n    hence \"fst a = ((snd a - snd b)/ (snd c - snd b)) * fst c +\n      ((snd c - snd a)/ (snd c - snd b)) * fst b\"\n      by (simp add: add_divide_distrib)\n    hence \"fst a = fst b + (snd a - snd b) * fst c / (snd c - snd b) +\n      ((snd c - snd a) - (snd c - snd b)) * fst b / (snd c - snd b)\"\n      using neq\n      by (simp add: field_simps)\n    hence \"fst a = fst b + ((snd a - snd b) * fst c + (- snd a + snd b) * fst b) / (snd c - snd b)\"\n      unfolding add_divide_distrib\n      by (simp add: algebra_simps)\n    also\n    have \"(snd a - snd b) * fst c + (- snd a + snd b) * fst b = (snd a - snd b) * (fst c - fst b)\"\n      by (simp add: algebra_simps)\n    finally have \"fst a = fst b + (snd a - snd b) / (snd c - snd b) * (fst c - fst b)\"\n      by simp\n    moreover\n    hence \"snd a = snd b + (snd a - snd b) / (snd c - snd b) * (snd c - snd b)\"\n      using neq by simp\n    ultimately have \"a = b + ((snd a - snd b) / (snd c - snd b)) *\\<^sub>R (c - b)\"\n      by (auto simp: prod_eq_iff)\n    thus ?thesis by blast\n  qed\nqed\n\nlemma cramer: \"\\<not>det3 s t q = 0 \\<Longrightarrow>\n  (det3 t p r) = ((det3 t q r) * (det3 s t p) + (det3 t p q) * (det3 s t r))/(det3 s t q)\"\n  by (auto simp: det3_def' field_simps)\n\nlemma convex_comb_dets:\n  assumes \"det3 p q r > 0\"\n  shows \"s = (det3 s q r / det3 p q r) *\\<^sub>R p + (det3 p s r /  det3 p q r) *\\<^sub>R q +\n      (det3 p q s / det3 p q r) *\\<^sub>R r\"\n    (is \"?lhs = ?rhs\")\nproof -\n  from assms have \"det3 p q r *\\<^sub>R ?lhs = det3 p q r *\\<^sub>R ?rhs\"\n    by (simp add: field_simps prod_eq_iff scaleR_add_right) (simp add: algebra_simps det3_def')\n  thus ?thesis using assms by simp\nqed\n\nlemma four_points_aligned:\n  assumes c: \"det3 t p q = 0\" \"det3 t q r = 0\"\n  assumes distinct: \"distinct5 t s p q r\"\n  shows \"det3 t r p = 0\" \"det3 p q r = 0\"\nproof -\n  from distinct have d: \"p \\<noteq> q\" \"q \\<noteq> r\" by (auto)\n  from coll_ex_scaling[OF d(1) c(1)] obtain s1 where s1: \"t = p + s1 *\\<^sub>R (q - p)\" by auto\n  from coll_ex_scaling[OF d(2) c(2)] obtain s2 where s2: \"t = q + s2 *\\<^sub>R (r - q)\" by auto\n  from distinct s1 have ne: \"1 - s1 \\<noteq> 0\" by auto\n  from s1 s2 have \"(1 - s1) *\\<^sub>R p = (1 - s1 - s2) *\\<^sub>R q + s2 *\\<^sub>R r\"\n    by (simp add: algebra_simps)\n  hence \"(1 - s1) *\\<^sub>R p /\\<^sub>R (1 - s1)= ((1 - s1 - s2) *\\<^sub>R q + s2 *\\<^sub>R r) /\\<^sub>R (1 - s1)\"\n    by simp\n  with ne have p: \"p = ((1 - s1 - s2) / (1 - s1)) *\\<^sub>R q + (s2 / (1 - s1)) *\\<^sub>R r\"\n    using ne\n    by (simp add: prod_eq_iff inverse_eq_divide add_divide_distrib)\n  define k1 where \"k1 = (1 - s1 - s2) / (1 - s1)\"\n  define k2 where \"k2 = s2 / (1 - s1)\"\n  have \"det3 t r p = det3 0 (k1 *\\<^sub>R q + (k2 - 1) *\\<^sub>R r)\n    (k1 *\\<^sub>R q + (k2 - 1) *\\<^sub>R r + (- s1 * (k1 - 1)) *\\<^sub>R q - (s1 * k2) *\\<^sub>R r)\"\n    unfolding s1 p k1_def[symmetric] k2_def[symmetric]\n    by (simp add: algebra_simps det3_def')\n  also have \"- s1 * (k1 - 1) = s1 * k2\"\n    using ne by (auto simp: k1_def field_simps k2_def)\n  also\n  have \"1 - k1 = k2\"\n    using ne\n    by (auto simp: k2_def k1_def field_simps)\n  have k21: \"k2 - 1 = -k1\"\n    using ne\n    by (auto simp: k2_def k1_def field_simps)\n  finally have \"det3 t r p = det3 0 (k1 *\\<^sub>R (q - r)) ((k1 + (s1 * k2)) *\\<^sub>R (q - r))\"\n    by (auto simp: algebra_simps)\n  also have \"\\<dots> = 0\"\n    by (simp add: algebra_simps det3_def')\n  finally show \"det3 t r p = 0\" .\n  have \"det3 p q r = det3 (k1 *\\<^sub>R q + k2 *\\<^sub>R r) q r\"\n    unfolding p k1_def[symmetric] k2_def[symmetric] ..\n  also have \"\\<dots> = det3 0 (r - q) (k1 *\\<^sub>R q + (-k1) *\\<^sub>R r)\"\n    unfolding k21[symmetric]\n    by (auto simp: algebra_simps det3_def')\n  also have \"\\<dots> = det3 0 (r - q) (-k1 *\\<^sub>R (r - q))\"\n    by (auto simp: det3_def' algebra_simps)\n  also have \"\\<dots> = 0\"\n    by (auto simp: det3_def')\n  finally show \"det3 p q r = 0\" .\nqed\n\nlemma det_identity:\n  \"det3 t p q * det3 t s r + det3 t q r * det3 t s p + det3 t r p * det3 t s q = 0\"\n  by (auto simp: det3_def' algebra_simps)\n\nlemma det3_eq_zeroI:\n  assumes \"p = q + x *\\<^sub>R (t - q)\"\n  shows \"det3 q t p = 0\"\n  unfolding assms\n  by (auto simp: det3_def' algebra_simps)\n\nlemma det3_rotate: \"det3 a b c = det3 c a b\"\n  by (auto simp: det3_def')\n\nlemma det3_switch: \"det3 a b c = - det3 a c b\"\n  by (auto simp: det3_def')\n\nlemma det3_switch': \"det3 a b c = - det3 b a c\"\n  by (auto simp: det3_def')\n\nlemma det3_pos_transitive_coll:\n  \"det3 t s p > 0 \\<Longrightarrow> det3 t s r \\<ge> 0 \\<Longrightarrow> det3 t p q \\<ge> 0 \\<Longrightarrow>\n  det3 t q r > 0 \\<Longrightarrow> det3 t s q = 0 \\<Longrightarrow> det3 t p r > 0\"\n  using det_identity[of t p q s r]\n  by (metis add.commute add_less_same_cancel1 det3_switch det3_switch' less_eq_real_def\n    less_not_sym monoid_add_class.add.left_neutral mult_pos_pos mult_zero_left mult_zero_right)\n\nlemma det3_pos_transitive:\n  \"det3 t s p > 0 \\<Longrightarrow> det3 t s q \\<ge> 0 \\<Longrightarrow> det3 t s r \\<ge> 0 \\<Longrightarrow> det3 t p q \\<ge> 0 \\<Longrightarrow>\n  det3 t q r > 0 \\<Longrightarrow> det3 t p r > 0\"\n  apply (cases \"det3 t s q \\<noteq> 0\")\n   using cramer[of q t s p r]\n   apply (force simp: det3_rotate[of q t p] det3_rotate[of p q t] det3_switch[of t p s]\n     det3_switch'[of q t r] det3_rotate[of q t s] det3_rotate[of s q t]\n     intro!: divide_pos_pos add_nonneg_pos)\n  apply (metis det3_pos_transitive_coll)\n  done\n\nlemma det3_zero_translate_plus[simp]: \"det3 (a + x) (b + x) (c + x) = 0 \\<longleftrightarrow> det3 a b c = 0\"\n  by (auto simp: algebra_simps det3_def')\n\nlemma det3_zero_translate_plus'[simp]: \"det3 (a) (a + b) (a + c) = 0 \\<longleftrightarrow> det3 0 b c = 0\"\n  by (auto simp: algebra_simps det3_def')\n\nlemma\n  det30_zero_scaleR1:\n  \"0 < e \\<Longrightarrow> det3 0 xr P = 0 \\<Longrightarrow> det3 0 (e *\\<^sub>R xr) P = 0\"\n  by (auto simp: zero_prod_def algebra_simps det3_def')\n\nlemma det3_same[simp]: \"det3 a x x = 0\"\n  by (auto simp: det3_def')\n\nlemma\n  det30_zero_scaleR2:\n  \"0 < e \\<Longrightarrow> det3 0 P xr = 0 \\<Longrightarrow> det3 0 P (e *\\<^sub>R xr) = 0\"\n  by (auto simp: zero_prod_def algebra_simps det3_def')\n\n\n\nlemma det30_plus_scaled3[simp]: \"det3 0 a (b + x *\\<^sub>R a) = 0 \\<longleftrightarrow> det3 0 a b = 0\"\n  by (auto simp: det3_def' algebra_simps)\n\nlemma det30_plus_scaled2[simp]:\n  shows \"det3 0 (a + x *\\<^sub>R a) b = 0 \\<longleftrightarrow> (if x = -1 then True else det3 0 a b = 0)\"\n    (is \"?lhs = ?rhs\")\nproof\n  assume \"det3 0 (a + x *\\<^sub>R a) b = 0\"\n  hence \"fst a * snd b * (1 + x) = fst b * snd a * (1 + x)\"\n    by (simp add: algebra_simps det3_def')\n  thus ?rhs\n    by (auto simp add: det3_def')\nqed (auto simp: det3_def' algebra_simps split: if_split_asm)\n\nlemma det30_uminus2[simp]: \"det3 0 (-a) (b) = 0 \\<longleftrightarrow> det3 0 a b = 0\"\n  and det30_uminus3[simp]: \"det3 0 a (-b) = 0 \\<longleftrightarrow> det3 0 a b = 0\"\n  by (auto simp: det3_def' algebra_simps)\n\nlemma det30_minus_scaled3[simp]: \"det3 0 a (b - x *\\<^sub>R a) = 0 \\<longleftrightarrow> det3 0 a b = 0\"\n  using det30_plus_scaled3[of a b \"-x\"] by simp\n\nlemma det30_scaled_minus3[simp]: \"det3 0 a (e *\\<^sub>R a - b) = 0 \\<longleftrightarrow> det3 0 a b = 0\"\n  using det30_plus_scaled3[of a \"-b\" e]\n  by (simp add: algebra_simps)\n\nlemma det30_minus_scaled2[simp]:\n  \"det3 0 (a - x *\\<^sub>R a) b = 0 \\<longleftrightarrow> (if x = 1 then True else det3 0 a b = 0)\"\n  using det30_plus_scaled2[of a  \"-x\" b] by simp\n\nlemma det3_nonneg_scaleR1:\n  \"0 < e \\<Longrightarrow> det3 0 xr P \\<ge> 0 \\<Longrightarrow> det3 0 (e*\\<^sub>Rxr) P \\<ge> 0\"\n  by (auto simp add: det3_def' algebra_simps)\n\nlemma det3_nonneg_scaleR1_eq:\n  \"0 < e \\<Longrightarrow> det3 0 (e*\\<^sub>Rxr) P \\<ge> 0 \\<longleftrightarrow> det3 0 xr P \\<ge> 0\"\n  by (auto simp add: det3_def' algebra_simps)\n\nlemma det3_translate_origin: \"NO_MATCH 0 p \\<Longrightarrow> det3 p q r = det3 0 (q - p) (r - p)\"\n  by (auto simp: det3_def' algebra_simps)\n\nlemma det3_nonneg_scaleR_segment2:\n  assumes \"det3 x y z \\<ge> 0\"\n  assumes \"a > 0\"\n  shows \"det3 x ((1 - a) *\\<^sub>R x + a *\\<^sub>R y) z \\<ge> 0\"\nproof -\n  from assms have \"0 \\<le> det3 0 (a *\\<^sub>R (y - x)) (z - x)\"\n    by (intro det3_nonneg_scaleR1) (simp_all add: det3_translate_origin)\n  thus ?thesis\n    by (simp add: algebra_simps det3_translate_origin)\nqed\n\nlemma det3_nonneg_scaleR_segment1:\n  assumes \"det3 x y z \\<ge> 0\"\n  assumes \"0 \\<le> a\" \"a < 1\"\n  shows \"det3 ((1 - a) *\\<^sub>R x + a *\\<^sub>R y) y z \\<ge> 0\"\nproof -\n  from assms have \"det3 0 ((1 - a) *\\<^sub>R (y - x)) (z - x + (- a) *\\<^sub>R (y - x)) \\<ge> 0\"\n    by (subst det3_nonneg_scaleR1_eq) (auto simp add: det3_def' algebra_simps)\n  thus ?thesis\n    by (auto simp: algebra_simps det3_translate_origin)\nqed\n\n\nsubsection \\<open>Strict CCW Predicate\\<close>\n\ndefinition \"ccw' p q r \\<longleftrightarrow> 0 < det3 p q r\"\n\ninterpretation ccw': ccw_vector_space ccw'\n  by unfold_locales (auto simp: ccw'_def det3_def' algebra_simps)\n\ninterpretation ccw': linorder_list0 \"ccw' x\" for x .\n\nlemma ccw'_contra: \"ccw' t r q \\<Longrightarrow> ccw' t q r = False\"\n  by (auto simp: ccw'_def det3_def' algebra_simps)\n\nlemma not_ccw'_eq: \"\\<not> ccw' t p s \\<longleftrightarrow> ccw' t s p \\<or> det3 t s p = 0\"\n  by (auto simp: ccw'_def det3_def' algebra_simps)\n\nlemma neq_left_right_of: \"ccw' a b c \\<Longrightarrow> ccw' a c d \\<Longrightarrow> b \\<noteq> d\"\n  by (auto simp: ccw'_def det3_def' algebra_simps)\n\nlemma ccw'_subst_collinear:\n  assumes \"det3 t r s = 0\"\n  assumes \"s \\<noteq> t\"\n  assumes \"ccw' t r p\"\n  shows \"ccw' t s p \\<or> ccw' t p s\"\nproof cases\n  assume \"r \\<noteq> s\"\n  from assms have \"det3 r s t = 0\"\n    by (auto simp: algebra_simps det3_def')\n  from coll_ex_scaling[OF assms(2) this]\n  obtain x where s: \"r = s + x *\\<^sub>R (t - s)\" by auto\n  from assms(3)[simplified ccw'_def s]\n  have \"0 < det3 0 (s + x *\\<^sub>R (t - s) - t) (p - t)\"\n    by (auto simp: algebra_simps det3_def')\n  also have \"s + x *\\<^sub>R (t - s) - t = (1 - x) *\\<^sub>R (s - t)\"\n    by (simp add: algebra_simps)\n  finally have ccw': \"ccw' 0 ((1 - x) *\\<^sub>R (s - t)) (p - t)\"\n    by (simp add: ccw'_def)\n  hence \"x \\<noteq> 1\" by (auto simp add: det3_def' ccw'_def)\n  {\n    assume \"x < 1\"\n    hence ?thesis using ccw'\n      by (auto simp: not_ccw'_eq ccw'.translate_origin)\n  } moreover {\n    assume \"x > 1\"\n    hence ?thesis using ccw'\n      by (auto simp: not_ccw'_eq ccw'.translate_origin)\n  } ultimately show ?thesis using \\<open>x \\<noteq> 1\\<close> by arith\nqed (insert assms, simp)\n\nlemma ccw'_sorted_scaleR: \"ccw'.sortedP 0 xs \\<Longrightarrow> r > 0 \\<Longrightarrow> ccw'.sortedP 0 (map ((*\\<^sub>R) r) xs)\"\n  by (induct xs) (auto intro!: ccw'.sortedP.Cons  elim!: ccw'.sortedP_Cons simp del: scaleR_Pair)\n\n\nsubsection \\<open>Collinearity\\<close>\n\nabbreviation \"coll a b c \\<equiv> det3 a b c = 0\"\n\nlemma coll_zero[intro, simp]: \"coll 0 z 0\"\n  by (auto simp: det3_def')\n\nlemma coll_zero1[intro, simp]: \"coll 0 0 z\"\n  by (auto simp: det3_def')\n\nlemma coll_self[intro, simp]: \"coll 0 z z\"\n  by (auto simp: )\n\nlemma ccw'_not_coll:\n  \"ccw' a b c \\<Longrightarrow> \\<not>coll a b c\"\n  \"ccw' a b c \\<Longrightarrow> \\<not>coll a c b\"\n  \"ccw' a b c \\<Longrightarrow> \\<not>coll b a c\"\n  \"ccw' a b c \\<Longrightarrow> \\<not>coll b c a\"\n  \"ccw' a b c \\<Longrightarrow> \\<not>coll c a b\"\n  \"ccw' a b c \\<Longrightarrow> \\<not>coll c b a\"\n  by (auto simp: det3_def' ccw'_def algebra_simps)\n\nlemma coll_add: \"coll 0 x y \\<Longrightarrow> coll 0 x z \\<Longrightarrow> coll 0 x (y + z)\"\n  by (auto simp: det3_def' algebra_simps)\n\nlemma coll_scaleR_left_eq[simp]: \"coll 0 (r *\\<^sub>R x) y \\<longleftrightarrow> r = 0 \\<or> coll 0 x y\"\n  by (auto simp: det3_def' algebra_simps)\n\nlemma coll_scaleR_right_eq[simp]: \"coll 0 y (r *\\<^sub>R x) \\<longleftrightarrow> r = 0 \\<or> coll 0 y x\"\n  by (auto simp: det3_def' algebra_simps)\n\nlemma coll_scaleR: \"coll 0 x y \\<Longrightarrow> coll 0 (r *\\<^sub>R x) y\"\n  by (auto simp: det3_def' algebra_simps)\n\nlemma coll_sum_list: \"(\\<And>y. y \\<in> set ys \\<Longrightarrow> coll 0 x y) \\<Longrightarrow> coll 0 x (sum_list ys)\"\n  by (induct ys) (auto intro!: coll_add)\n\nlemma scaleR_left_normalize:\n  fixes a ::real and b c::\"'a::real_vector\"\n  shows \"a *\\<^sub>R b = c \\<longleftrightarrow> (if a = 0 then c = 0 else b = c /\\<^sub>R a)\"\n  by (auto simp: field_simps)\n\n\n\nlemma coll_scale: \"coll 0 r q \\<Longrightarrow> r \\<noteq> 0 \\<Longrightarrow> (\\<exists>x. q = x *\\<^sub>R r)\"\n  using coll_scale_pair[of \"fst r\" \"snd r\" \"fst q\" \"snd q\"]\n  by simp\n\nlemma coll_add_trans:\n  assumes \"coll 0 x (y + z)\"\n  assumes \"coll 0 y z\"\n  assumes \"x \\<noteq> 0\"\n  assumes \"y \\<noteq> 0\"\n  assumes \"z \\<noteq> 0\"\n  assumes \"y + z \\<noteq> 0\"\n  shows \"coll 0 x z\"\nproof (cases \"snd z = 0\")\n  case True\n  hence \"snd y = 0\"\n    using assms\n    by (cases z) (auto simp add: zero_prod_def det3_def')\n  with True assms have \"snd x = 0\"\n    by (cases y, cases z) (auto simp add: zero_prod_def det3_def')\n  from \\<open>snd x = 0\\<close> \\<open>snd y = 0\\<close> \\<open>snd z = 0\\<close>\n  show ?thesis\n    by (auto simp add: zero_prod_def det3_def')\nnext\n  case False\n  note z = False\n  hence \"snd y \\<noteq> 0\"\n    using assms\n    by (cases y) (auto simp add: zero_prod_def det3_def')\n  with False assms have \"snd x \\<noteq> 0\"\n    apply (cases x)\n    apply (cases y)\n    apply (cases z)\n    apply (auto simp add: zero_prod_def det3_def')\n    apply (metis mult.commute mult_eq_0_iff ring_class.ring_distribs(1))\n    done\n  with False assms \\<open>snd y \\<noteq> 0\\<close> have yz: \"snd (y + z) \\<noteq> 0\"\n    by (cases x; cases y; cases z) (auto simp add: det3_def' zero_prod_def)\n  from coll_scale[OF assms(1) assms(3)] coll_scale[OF assms(2) assms(4)]\n  obtain r s where rs: \"y + z = r *\\<^sub>R x\" \"z = s *\\<^sub>R y\"\n    by auto\n  with z have \"s \\<noteq> 0\"\n    by (cases x; cases y; cases z) (auto simp: zero_prod_def)\n  with rs z yz have \"r \\<noteq> 0\"\n    by (cases x; cases y; cases z) (auto simp: zero_prod_def)\n  from \\<open>s \\<noteq> 0\\<close> rs have \"y = r *\\<^sub>R x - z\" \"y = z /\\<^sub>R s\"\n    by (auto simp: inverse_eq_divide algebra_simps)\n  hence \"r *\\<^sub>R x - z = z /\\<^sub>R s\" by simp\n  hence \"r *\\<^sub>R x = (1 + inverse s) *\\<^sub>R z\"\n    by (auto simp: inverse_eq_divide algebra_simps)\n  hence \"x = (inverse r * (1 + inverse s)) *\\<^sub>R z\"\n    using \\<open>r \\<noteq> 0\\<close> \\<open>s \\<noteq> 0\\<close>\n    by (auto simp: field_simps scaleR_left_normalize)\n  from this\n  show ?thesis\n    by (auto intro: coll_scaleR)\nqed\n\nlemma coll_commute: \"coll 0 a b \\<longleftrightarrow> coll 0 b a\"\n  by (metis det3_rotate det3_switch' diff_0 diff_self)\n\nlemma coll_add_cancel: \"coll 0 a (a + b) \\<Longrightarrow> coll 0 a b\"\n  by (cases a, cases b) (auto simp: det3_def' algebra_simps)\n\nlemma coll_trans:\n  \"coll 0 a b \\<Longrightarrow> coll 0 a c \\<Longrightarrow> a \\<noteq> 0 \\<Longrightarrow> coll 0 b c\"\n  by (metis coll_scale coll_scaleR)\n\nlemma sum_list_posI:\n  fixes xs::\"'a::ordered_comm_monoid_add list\"\n  shows \"(\\<And>x. x \\<in> set xs \\<Longrightarrow> x > 0) \\<Longrightarrow> xs \\<noteq> [] \\<Longrightarrow> sum_list xs > 0\"\nproof (induct xs)\n  case (Cons x xs)\n  thus ?case\n    by (cases \"xs = []\") (auto intro!: add_pos_pos)\nqed simp\n\nlemma nonzero_fstI[intro, simp]: \"fst x \\<noteq> 0 \\<Longrightarrow> x \\<noteq> 0\"\n  and nonzero_sndI[intro, simp]: \"snd x \\<noteq> 0 \\<Longrightarrow> x \\<noteq> 0\"\n  by auto\n\nlemma coll_sum_list_trans:\n  \"xs \\<noteq> [] \\<Longrightarrow> coll 0 a (sum_list xs) \\<Longrightarrow> (\\<And>x. x \\<in> set xs \\<Longrightarrow> coll 0 x y) \\<Longrightarrow>\n    (\\<And>x. x \\<in> set xs \\<Longrightarrow> coll 0 x (sum_list xs)) \\<Longrightarrow>\n    (\\<And>x. x \\<in> set xs \\<Longrightarrow> snd x > 0) \\<Longrightarrow> a \\<noteq> 0 \\<Longrightarrow> coll 0 a y\"\nproof (induct xs rule: list_nonempty_induct)\n  case (single x)\n  from single(1) single(2)[of x] single(4)[of x] have \"coll 0 x a\" \"coll 0 x y\" \"x \\<noteq> 0\"\n    by (auto simp: coll_commute)\n  thus ?case by (rule coll_trans)\nnext\n  case (cons x xs)\n  from cons(5)[of x] \\<open>a \\<noteq> 0\\<close> cons(6)[of x]\n  have *: \"coll 0 x (sum_list xs)\" \"a \\<noteq> 0\" \"x \\<noteq> 0\" by (force simp add: coll_add_cancel)+\n  have \"0 < snd (sum_list (x#xs))\"\n    unfolding snd_sum_list\n    by (rule sum_list_posI) (auto intro!: add_pos_pos cons simp: snd_sum_list)\n  hence \"x + sum_list xs \\<noteq> 0\" by simp\n  from coll_add_trans[OF cons(3)[simplified] * _ this]\n  have cH: \"coll 0 a (sum_list xs)\"\n    by (cases \"sum_list xs = 0\") auto\n  from cons(4) have cy: \"(\\<And>x. x \\<in> set xs \\<Longrightarrow> coll 0 x y)\" by simp\n  {\n    fix y assume \"y \\<in> set xs\"\n    hence \"snd (sum_list xs) > 0\"\n      unfolding snd_sum_list\n      by (intro sum_list_posI) (auto intro!: add_pos_pos cons simp: snd_sum_list)\n    hence \"sum_list xs \\<noteq> 0\" by simp\n    from cons(5)[of x] have \"coll 0 x (sum_list xs)\"\n      by (simp add: coll_add_cancel)\n    from cons(5)[of y]\n    have \"coll 0 y (sum_list xs)\"\n      using \\<open>y \\<in> set xs\\<close> cons(6)[of y] \\<open>x + sum_list xs \\<noteq> 0\\<close>\n      apply (cases \"y = x\")\n      subgoal by (force simp add: coll_add_cancel)\n      subgoal by (force simp: dest!: coll_add_trans[OF _ *(1) _ *(3)])\n      done\n  } note cl = this\n  show ?case\n    by (rule cons(2)[OF cH cy cl cons(6) \\<open>a \\<noteq> 0\\<close>]) auto\nqed\n\nlemma sum_list_coll_ex_scale:\n  assumes coll: \"\\<And>x. x \\<in> set xs \\<Longrightarrow> coll 0 z x\"\n  assumes nz: \"z \\<noteq> 0\"\n  shows \"\\<exists>r. sum_list xs = r *\\<^sub>R z\"\nproof -\n  {\n    fix i assume i: \"i < length xs\"\n    hence nth: \"xs ! i \\<in> set xs\" by simp\n    note coll_scale[OF coll[OF nth] \\<open>z \\<noteq> 0\\<close>]\n  } then obtain r where r: \"\\<And>i. i < length xs \\<Longrightarrow> r i *\\<^sub>R z = xs ! i\"\n    by metis\n  have \"xs = map ((!) xs) [0..<length xs]\" by (simp add: map_nth)\n  also have \"\\<dots> = map (\\<lambda>i. r i *\\<^sub>R z) [0..<length xs]\"\n    by (auto simp: r)\n  also have \"sum_list \\<dots> = (\\<Sum>i\\<leftarrow>[0..<length xs]. r i) *\\<^sub>R z\"\n    by (simp add: sum_list_sum_nth scaleR_sum_left)\n  finally show ?thesis ..\nqed\n\nlemma sum_list_filter_coll_ex_scale: \"z \\<noteq> 0 \\<Longrightarrow> \\<exists>r. sum_list (filter (coll 0 z) zs) = r *\\<^sub>R z\"\n  by (rule sum_list_coll_ex_scale) 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/Affine_Arithmetic/Counterclockwise_2D_Strict.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8918110396870287, "lm_q2_score": 0.8244619350028204, "lm_q1q2_score": 0.7352642554372447}}
{"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 Main\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 sumset_empty [simp]: \"A + {} = {}\" \"{} + A = {}\"\n  by (auto simp: set_plus_def)\n\nlemma Un_set_plus: \"(A \\<union> B) + C = (A+C) \\<union> (B+C)\" and set_plus_Un: \"C + (A \\<union> B) = (C+A) \\<union> (C+B)\"\n  by (auto simp: set_plus_def)\n\nlemma \n  fixes A :: \"'a::comm_monoid_add set\"\n  shows insert_set_plus: \"(insert a A) + B = (A+B) \\<union> (((+)a) ` B)\" and set_plus_insert: \"B + (insert a A) = (B+A) \\<union> (((+)a) ` B)\"\n  using add.commute by (auto simp: set_plus_def)\n\nlemma set_add_0 [simp]:\n  fixes A :: \"'a::comm_monoid_add set\"\n  shows \"{0} + A = A\"\n  by (metis comm_monoid_add_class.add_0 set_zero)\n\nlemma set_add_0_right [simp]:\n  fixes A :: \"'a::comm_monoid_add set\"\n  shows \"A + {0} = A\"\n  by (metis add.comm_neutral set_zero)\n\nlemma card_plus_sing:\n  fixes A :: \"'a::ab_group_add set\"\n  shows \"card (A + {a}) = card A\"\nproof (rule bij_betw_same_card)\n  show \"bij_betw ((+) (-a)) (A + {a}) A\"\n    by (fastforce simp: set_plus_def bij_betw_def image_iff)\nqed\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    by (auto simp: elt_set_plus_def set_plus_def; metis group_cancel.add1 group_cancel.add2)\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  by (auto simp add: elt_set_plus_def set_plus_def; metis add.assoc)\n\ntheorem set_plus_rearrange4: \"C + (a +o D) = a +o (C + D)\"\n  for a :: \"'a::comm_monoid_add\"\n  by (metis add.commute set_plus_rearrange3)\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  using order_subst2 by blast\n\nlemma set_plus_mono_b: \"C \\<subseteq> D \\<Longrightarrow> x \\<in> a +o C \\<Longrightarrow> x \\<in> a +o D\"\n  using set_plus_mono by blast\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  using set_plus_intro by fastforce\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  by (metis add.commute diff_add_cancel set_plus_intro2)\n\nlemma set_minus_plus: \"a - b \\<in> C \\<longleftrightarrow> a \\<in> b +o C\"\n  for a b :: \"'a::ab_group_add\"\n  by (meson set_minus_imp_plus set_plus_imp_minus)\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  by (auto simp add: elt_set_times_def set_times_def; metis mult.assoc mult.left_commute)\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  by (auto simp add: elt_set_times_def set_times_def; metis mult.assoc)\n\ntheorem set_times_rearrange4: \"C * (a *o D) = a *o (C * D)\"\n  for a :: \"'a::comm_monoid_mult\"\n  by (metis mult.commute set_times_rearrange3)\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  by (meson dual_order.trans set_times_mono set_times_mono3)\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  by (auto simp: set_plus_def elt_set_times_def; metis distrib_left)\n\nlemma set_times_plus_distrib3: \"(a +o C) * D \\<subseteq> a *o D + C * D\"\n  for a :: \"'a::semiring\"\n  using distrib_right \n  by (fastforce simp add: elt_set_plus_def elt_set_times_def set_times_def set_plus_def)\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": "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/Library/Set_Algebras.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8918110425624791, "lm_q2_score": 0.8244619199068831, "lm_q1q2_score": 0.7352642443452205}}
{"text": "section\"Derangements\"\ntheory Derangements_Enum\n  imports\n    \"HOL-Combinatorics.Multiset_Permutations\"\n    \"Common_Lemmas\"\n   (* \"Derangements.Derangements\" *)\nbegin\n\nsubsection\"Definition\"\n\nfun no_overlap :: \"'a list \\<Rightarrow> 'a list \\<Rightarrow> bool\" where\n  \"no_overlap _ [] = True\"\n| \"no_overlap [] _ = True\"\n| \"no_overlap (x#xs) (y#ys) = (x \\<noteq> y \\<and> no_overlap xs ys)\"\n\nlemma no_overlap_nth: \"length xs = length ys \\<Longrightarrow> i < length xs \\<Longrightarrow> no_overlap xs ys \\<Longrightarrow> xs ! i \\<noteq> ys ! i\" \n  by(induct xs ys arbitrary: i rule: list_induct2) (auto simp: less_Suc_eq_0_disj)\n\nlemma nth_no_overlap: \"length xs = length ys \\<Longrightarrow> \\<forall> i < length xs. xs ! i \\<noteq> ys ! i \\<Longrightarrow> no_overlap xs ys\"\nproof (induct xs ys rule: list_induct2)\n  case (Cons x xs y ys)\n  then show ?case using Suc_less_eq nth_Cons_Suc by fastforce\nqed simp \n  \ndefinition derangements :: \"'a list \\<Rightarrow> 'a list set\" where\n  \"derangements xs = {ys. distinct ys \\<and> length xs = length ys \\<and> set xs = set ys \\<and> no_overlap xs ys }\"\ntext \"A derangement of a list is a permutation where every element changes its position,\n  assuming all elements are distinguishable.\"\ntext \\<open>An alternative definition exists in \\<open>Derangements.Derangements\\<close> \\cite{AFPderan}.\\<close>\ntext \"Cardinality: \\<open>count_derangements (length xs)\\<close> (from \\<open>Derangements.Derangements\\<close>)\"\ntext \"Example: \\<open>derangements [0,1,2] = {[1,2,0], [2,0,1]}\\<close>\"\n\nsubsection\"Algorithm\"\nfun derangement_enum_aux :: \"'a list \\<Rightarrow> 'a list \\<Rightarrow> 'a list list\" where\n  \"derangement_enum_aux [] ys = [[]]\"\n| \"derangement_enum_aux (x#xs) ys = [y#r . y \\<leftarrow> ys, r \\<leftarrow> derangement_enum_aux xs (remove1 y ys), y \\<noteq> x]\"\n\nfun derangement_enum :: \"'a list  \\<Rightarrow> 'a list list\" where\n \"derangement_enum xs = derangement_enum_aux xs xs\"\n\nsubsection\"Verification\"\n\nsubsubsection\"Correctness\"\n\nlemma derangement_enum_aux_elem_length: \"zs \\<in> set (derangement_enum_aux xs ys) \\<Longrightarrow> length xs = length zs\"\n  by(induct xs arbitrary: ys zs) auto\n\nlemma derangement_enum_aux_not_in: \"y \\<notin> set ys \\<Longrightarrow> zs \\<in> set (derangement_enum_aux xs ys) \\<Longrightarrow> y \\<notin> set zs\"\nproof(induct xs arbitrary: ys zs)\n  case Nil\n  then show ?case by simp\nnext\n  case (Cons x xs)\n  then obtain z zs2 where ob: \"zs = z#zs2\"\n    by auto\n  have \"zs2 \\<in> set (derangement_enum_aux xs (remove1 z ys)) \\<Longrightarrow> y \\<notin> set zs2\"\n    using Cons notin_set_remove1 by fast\n  then show ?case using Cons ob\n    by auto\nqed\n\nlemma derangement_enum_aux_in: \"y \\<in> set zs \\<Longrightarrow> zs \\<in> set (derangement_enum_aux xs ys) \\<Longrightarrow> y \\<in> set ys\"\n  using derangement_enum_aux_not_in by fast\n  \nlemma derangement_enum_aux_distinct_elem: \"distinct ys \\<Longrightarrow> zs \\<in> set (derangement_enum_aux xs ys) \\<Longrightarrow> distinct zs\"\nproof(induct xs arbitrary: ys zs)\n  case Nil\n  then show ?case by simp\nnext\n  case (Cons x xs)\n  obtain z zs2 where ob: \"zs = z#zs2\"\n    using Cons by auto\n  then have ev: \"zs2 \\<in> set (derangement_enum_aux xs (remove1 z ys))\"\n    using Cons ob by auto\n\n  have \"distinct zs2\"\n    using ev Cons distinct_remove1 by fast\n  moreover have \"z \\<notin> set zs2\"\n    using ev Cons(2) derangement_enum_aux_in by fastforce\n  ultimately show ?case using ob by simp\nqed\n\nlemma derangement_enum_aux_no_overlap: \"zs \\<in> set (derangement_enum_aux xs ys) \\<Longrightarrow> no_overlap xs zs\"\n  by(induct xs arbitrary: zs ys) auto\n\nlemma derangement_enum_aux_set:\n  \"length xs = length ys \\<Longrightarrow> zs \\<in> set (derangement_enum_aux xs ys) \\<Longrightarrow> set zs = set ys\"\nproof(induct xs ys arbitrary: zs rule: derangement_enum_aux.induct)\n  case (1 ys)\n  then show ?case by simp\nnext\n  case (2 x xs ys)\n  obtain z zs2 where ob: \"zs = z#zs2\"\n    using 2 by auto\n  have ev1: \"zs2 \\<in> set (derangement_enum_aux xs (remove1 z ys))\"\n    using 2 ob  by simp\n  have ev2:\"z \\<in> set ys\"\n    using 2 ob by simp\n\n  have \"length xs = length (remove1 z ys)\"\n    using ev2 Suc_length_remove1 \"2.prems\"(1) by force\n  then have \"set zs2 = set (remove1 z ys)\"\n    using \"2.hyps\"[of z zs2] ev1 ev2  by simp\n\n  then show ?case\n    using ob notin_set_remove1 ev2 in_set_remove1 by fastforce\nqed\n\nlemma derangement_enum_correct_aux1:\n  \"\\<lbrakk>distinct zs;length ys = length zs; length ys = length xs; set ys = set zs; no_overlap xs zs\\<rbrakk>\n   \\<Longrightarrow> zs \\<in> set (derangement_enum_aux xs ys)\"\nproof(induct xs arbitrary: zs ys)\n  case Nil\n  then show ?case by simp\nnext\n  case (Cons x xs)\n  obtain z zs2 where ob: \"zs = z#zs2\"\n    using Cons length_0_conv neq_Nil_conv by metis\n\n  have e1: \"z \\<noteq> x\"\n    using Cons.prems(5) ob  by auto\n\n  have \"distinct zs2\"\n    using Cons.prems(1) ob by auto \n  moreover have \"length (remove1 z ys) = length zs2\" using Cons.prems ob\n    by (simp add: length_remove1) \n  moreover have \"length (remove1 z ys) = length xs\"\n    by (simp add: Cons.prems(3) Cons.prems(4) length_remove1 ob) \n  moreover have \"set (remove1 z ys) = set zs2\"\n    using Cons ob by (metis distinct_card distinct_remdups length_remdups_eq remove1.simps(2) set_remdups set_remove1_eq)\n  moreover have \"no_overlap xs zs2\"\n    using Cons.prems(5) ob by fastforce \n\n  ultimately have \"zs2 \\<in> set (derangement_enum_aux xs (remove1 z ys))\"\n    using Cons.hyps[of zs2 \"(remove1 z ys)\"] by simp\n  then show ?case\n    using ob e1 Cons by simp \nqed\n\ntheorem derangement_enum_correct: \"distinct xs \\<Longrightarrow> derangements xs = set (derangement_enum xs)\"\nproof(standard)\n  show \"distinct xs \\<Longrightarrow> derangements xs \\<subseteq> set (derangement_enum xs)\"\n    unfolding derangements_def using derangement_enum_correct_aux1 by auto \nnext\n  show \"distinct xs \\<Longrightarrow> set (derangement_enum xs) \\<subseteq> derangements xs\"\n    unfolding derangements_def\n    using derangement_enum_aux_set derangement_enum_aux_distinct_elem derangement_enum_aux_elem_length derangement_enum_aux_no_overlap\n    by auto\nqed\n\nsubsubsection\"Distinctness\"\n\nlemma derangement_enum_aux_distinct: \"distinct ys \\<Longrightarrow> distinct (derangement_enum_aux xs ys)\"\nproof(induct xs arbitrary: ys)\n  case Nil\n  then show ?case by simp\nnext\n  case (Cons x xs)\n  show ?case\n    using inj2_distinct_concat_map_function_filter[of\n        \"Cons\"\n         ys\n         \"\\<lambda>y. derangement_enum_aux xs (remove1 y ys)\"\n        \"\\<lambda>y. y \\<noteq> x\"\n      ]\n    using Cons Cons_inj2\n    by (simp)\nqed\n\ntheorem derangement_enum_distinct: \"distinct xs \\<Longrightarrow> distinct (derangement_enum xs)\"\n  using derangement_enum_aux_distinct by auto\n\n(*\nsubsubsection\"Cardinality\"\nshould be provable with Derangements.Derangements\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/Derangements_Enum.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8479677737461007, "lm_q2_score": 0.8670357477770337, "lm_q1q2_score": 0.735218372800777}}
{"text": "(*\n  File:    Pochhammer_Polynomials.thy\n  Author:  Manuel Eberl, TU M\u00fcnchen\n*)\nsection \\<open>Falling factorial as a polynomial\\<close>\ntheory Pochhammer_Polynomials\nimports\n  Complex_Main\n  \"HOL-Combinatorics.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": "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/Linear_Recurrences/Pochhammer_Polynomials.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357563664174, "lm_q2_score": 0.847967764140929, "lm_q1q2_score": 0.7352183717562703}}
{"text": "(*  Title:      HOL/SMT_Examples/SMT_Tests.thy\n    Author:     Sascha Boehme, TU Muenchen\n*)\n\nsection \\<open>Tests for the SMT binding\\<close>\n\ntheory SMT_Tests\nimports Complex_Main\nbegin\n\nsmt_status\n\ntext \\<open>Most examples are taken from various Isabelle theories and from HOL4.\\<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 \\<longrightarrow> (\\<exists>y. P x \\<and> P 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. (\\<exists>y. P y) \\<longrightarrow> P x\"\n  \"(\\<exists>x. Q \\<longrightarrow> P x) \\<longleftrightarrow> (Q \\<longrightarrow> (\\<exists>x. P x))\"\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>z. P z \\<longrightarrow> (\\<forall>x. P x)\"\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 using [[smt_trace]] 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  \"(0::nat) div 0 = 0\"\n  \"(x::nat) div 0 = 0\"\n  \"(0::nat) div 1 = 0\"\n  \"(1::nat) div 1 = 1\"\n  \"(3::nat) div 1 = 3\"\n  \"(x::nat) div 1 = x\"\n  \"(0::nat) div 3 = 0\"\n  \"(1::nat) div 3 = 0\"\n  \"(3::nat) div 3 = 1\"\n  \"(x::nat) div 3 \\<le> x\"\n  \"(x div 3 = x) = (x = 0)\"\n  using [[z3_extensions]]\n  by smt+\n\nlemma\n  \"(0::nat) mod 0 = 0\"\n  \"(x::nat) mod 0 = x\"\n  \"(0::nat) mod 1 = 0\"\n  \"(1::nat) mod 1 = 0\"\n  \"(3::nat) mod 1 = 0\"\n  \"(x::nat) mod 1 = 0\"\n  \"(0::nat) mod 3 = 0\"\n  \"(1::nat) mod 3 = 1\"\n  \"(3::nat) mod 3 = 0\"\n  \"x mod 3 < 3\"\n  \"(x mod 3 = x) = (x < 3)\"\n  using [[z3_extensions]]\n  by smt+\n\nlemma\n  \"(x::nat) = x div 1 * 1 + x mod 1\"\n  \"x = x div 3 * 3 + x mod 3\"\n  using [[z3_extensions]]\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  \"(0::int) div 0 = 0\"\n  \"(x::int) div 0 = 0\"\n  \"(0::int) div 1 = 0\"\n  \"(1::int) div 1 = 1\"\n  \"(3::int) div 1 = 3\"\n  \"(x::int) div 1 = x\"\n  \"(0::int) div -1 = 0\"\n  \"(1::int) div -1 = -1\"\n  \"(3::int) div -1 = -3\"\n  \"(x::int) div -1 = -x\"\n  \"(0::int) div 3 = 0\"\n  \"(0::int) div -3 = 0\"\n  \"(1::int) div 3 = 0\"\n  \"(3::int) div 3 = 1\"\n  \"(5::int) div 3 = 1\"\n  \"(1::int) div -3 = -1\"\n  \"(3::int) div -3 = -1\"\n  \"(5::int) div -3 = -2\"\n  \"(-1::int) div 3 = -1\"\n  \"(-3::int) div 3 = -1\"\n  \"(-5::int) div 3 = -2\"\n  \"(-1::int) div -3 = 0\"\n  \"(-3::int) div -3 = 1\"\n  \"(-5::int) div -3 = 1\"\n  using [[z3_extensions]]\n  by smt+\n\nlemma\n  \"(0::int) mod 0 = 0\"\n  \"(x::int) mod 0 = x\"\n  \"(0::int) mod 1 = 0\"\n  \"(1::int) mod 1 = 0\"\n  \"(3::int) mod 1 = 0\"\n  \"(x::int) mod 1 = 0\"\n  \"(0::int) mod -1 = 0\"\n  \"(1::int) mod -1 = 0\"\n  \"(3::int) mod -1 = 0\"\n  \"(x::int) mod -1 = 0\"\n  \"(0::int) mod 3 = 0\"\n  \"(0::int) mod -3 = 0\"\n  \"(1::int) mod 3 = 1\"\n  \"(3::int) mod 3 = 0\"\n  \"(5::int) mod 3 = 2\"\n  \"(1::int) mod -3 = -2\"\n  \"(3::int) mod -3 = 0\"\n  \"(5::int) mod -3 = -1\"\n  \"(-1::int) mod 3 = 2\"\n  \"(-3::int) mod 3 = 0\"\n  \"(-5::int) mod 3 = 1\"\n  \"(-1::int) mod -3 = -1\"\n  \"(-3::int) mod -3 = 0\"\n  \"(-5::int) mod -3 = -2\"\n  \"x mod 3 < 3\"\n  \"(x mod 3 = x) \\<longrightarrow> (x < 3)\"\n  using [[z3_extensions]]\n  by smt+\n\nlemma\n  \"(x::int) = x div 1 * 1 + x mod 1\"\n  \"x = x div 3 * 3 + x mod 3\"\n  using [[z3_extensions]]\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  \"(1/2 :: real) < 1\"\n  \"(1::real) / 3 = 1 / 3\"\n  \"(1::real) / -3 = - 1 / 3\"\n  \"(-1::real) / 3 = - 1 / 3\"\n  \"(-1::real) / -3 = 1 / 3\"\n  \"(x::real) / 1 = x\"\n  \"x > 0 \\<longrightarrow> x / 3 < x\"\n  \"x < 0 \\<longrightarrow> x / 3 > x\"\n  using [[z3_extensions]]\n  by smt+\n\nlemma\n  \"(3::real) * (x / 3) = x\"\n  \"(x * 3) / 3 = x\"\n  \"x > 0 \\<longrightarrow> 2 * x / 3 < x\"\n  \"x < 0 \\<longrightarrow> 2 * x / 3 > x\"\n  using [[z3_extensions]]\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  \"cy (p \\<lparr> cx := a \\<rparr>) = cy p\"\n  \"cx (p \\<lparr> cy := a \\<rparr>) = cx p\"\n  \"p \\<lparr> cx := 3 \\<rparr> \\<lparr> cy := 4 \\<rparr> = p \\<lparr> cy := 4 \\<rparr> \\<lparr> cx := 3 \\<rparr>\"\n  sorry\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  using [[smt_oracle, z3_extensions]]\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)\n  using [[smt_oracle, z3_extensions]]\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  using [[smt_oracle, z3_extensions]]\n  by smt+\n\n\nsubsubsection \\<open>Records\\<close>\n\nlemma\n  \"\\<lparr>cx = x, cy = y\\<rparr> = \\<lparr>cx = x', cy = y'\\<rparr> \\<Longrightarrow> x = x' \\<and> y = y'\"\n  using [[smt_oracle, z3_extensions]]\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  using [[smt_oracle, z3_extensions]]\n  by smt+\n\nlemma\n  \"cy (p \\<lparr> cx := a \\<rparr>) = cy p\"\n  \"cx (p \\<lparr> cy := a \\<rparr>) = cx p\"\n  \"p \\<lparr> cx := 3 \\<rparr> \\<lparr> cy := 4 \\<rparr> = p \\<lparr> cy := 4 \\<rparr> \\<lparr> cx := 3 \\<rparr>\"\n  using point.simps\n  using [[smt_oracle, z3_extensions]]\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 [[smt_oracle, z3_extensions]]\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  using [[smt_oracle, z3_extensions]]\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  sorry\n\nlemma\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  using point.simps bw_point.simps\n  using [[smt_oracle, z3_extensions]]\n  by smt\n\n\nsubsubsection \\<open>Type definitions\\<close>\n\nlemma\n  \"n0 \\<noteq> n1\"\n  \"plus' n1 n1 = n2\"\n  \"plus' n0 n2 = n2\"\n  using [[smt_oracle, z3_extensions]]\n  by (smt n0_def n1_def n2_def plus'_def)+\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\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.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.867035752930664, "lm_q2_score": 0.847967764140929, "lm_q1q2_score": 0.7352183688428621}}
{"text": "(*  Title:      Restricted_Measure_Space.thy\n    Author:     Mnacho Echenim, Univ. Grenoble Alpes\n*)\n\nsection \\<open>Generated subalgebras\\<close>\n\ntext \\<open>This section contains definitions and properties related to generated subalgebras.\\<close>\n\ntheory Generated_Subalgebra imports \"HOL-Probability.Probability\"\n\nbegin\n\n\n\ndefinition gen_subalgebra where\n\"gen_subalgebra M G = sigma (space M) G\"\n\n\nlemma gen_subalgebra_space:\n  shows \"space (gen_subalgebra M G) = space M\"\nby (simp add: gen_subalgebra_def space_measure_of_conv)\n\n\nlemma gen_subalgebra_sets:\n  assumes \"G \\<subseteq> sets M\"\n  and \"A \\<in> G\"\n  shows \"A \\<in> sets (gen_subalgebra M G)\"\nby (metis assms gen_subalgebra_def sets.space_closed sets_measure_of sigma_sets.Basic subset_trans)\n\n\nlemma gen_subalgebra_sig_sets:\n  assumes \"G \\<subseteq> Pow (space M)\"\n  shows \"sets (gen_subalgebra M G) = sigma_sets (space M) G\" unfolding gen_subalgebra_def\nby (metis assms gen_subalgebra_def sets_measure_of)\n\nlemma  gen_subalgebra_sigma_sets:\n  assumes \"G \\<subseteq> sets M\"\n  and \"sigma_algebra (space M) G\"\n  shows \"sets (gen_subalgebra M G) = G\"\nusing assms by (simp add: gen_subalgebra_def sigma_algebra.sets_measure_of_eq)\n\n\nlemma gen_subalgebra_is_subalgebra:\n  assumes sub: \"G \\<subseteq> sets M\"\n  and sigal:\"sigma_algebra (space M) G\"\n  shows \"subalgebra M (gen_subalgebra M G)\" (is \"subalgebra M ?N\")\nunfolding subalgebra_def\nproof (intro conjI)\n  show \"space ?N = space M\" using space_measure_of_conv[of \"(space M)\"]  unfolding gen_subalgebra_def by simp\n  have geqn: \"G = sets ?N\" using assms by (simp add:gen_subalgebra_sigma_sets)\n  thus \"sets ?N \\<subseteq> sets M\" using assms by simp\nqed\n\n\ndefinition  fct_gen_subalgebra :: \"'a measure \\<Rightarrow> 'b measure \\<Rightarrow> ('a \\<Rightarrow> 'b) \\<Rightarrow> 'a measure\" where\n  \"fct_gen_subalgebra M N X = gen_subalgebra M (sigma_sets (space M) {X -` B \\<inter> (space M) | B. B \\<in> sets N})\"\n\n\n\nlemma fct_gen_subalgebra_sets:\n  shows \"sets (fct_gen_subalgebra M N X) = sigma_sets (space M) {X -` B \\<inter> space M |B. B \\<in> sets N}\"\nunfolding fct_gen_subalgebra_def gen_subalgebra_def\nproof -\n  have \"{X -` B \\<inter> space M |B. B \\<in> sets N} \\<subseteq> Pow (space M)\"\n    by blast\n  then show \"sets (sigma (space M) (sigma_sets (space M) {X -` B \\<inter> space M |B. B \\<in> sets N})) = sigma_sets (space M) {X -` B \\<inter> space M |B. B \\<in> sets N}\"\n    by (meson sigma_algebra.sets_measure_of_eq sigma_algebra_sigma_sets)\nqed\n\nlemma fct_gen_subalgebra_space:\n  shows \"space (fct_gen_subalgebra M N X) = space M\"\n  unfolding fct_gen_subalgebra_def by (simp add: gen_subalgebra_space)\n\nlemma fct_gen_subalgebra_eq_sets:\n  assumes \"sets M = sets P\"\n  shows \"fct_gen_subalgebra M N X = fct_gen_subalgebra P N X\"\nproof -\n  have \"space M = space P\" using sets_eq_imp_space_eq assms by auto\n  thus ?thesis unfolding fct_gen_subalgebra_def gen_subalgebra_def by simp\nqed\n\nlemma fct_gen_subalgebra_sets_mem:\n  assumes \"B\\<in> sets N\"\n  shows \"X -` B \\<inter> (space M) \\<in> sets (fct_gen_subalgebra M N X)\" unfolding fct_gen_subalgebra_def\nproof -\n  have f1: \"{X -` A \\<inter> space M |A. A \\<in> sets N} \\<subseteq> Pow (space M)\"\n    by blast\n  have \"\\<exists>A. X -` B \\<inter> space M = X -` A \\<inter> space M \\<and> A \\<in> sets N\"\n    by (metis assms)\n  then show \"X -` B \\<inter> space M \\<in> sets (gen_subalgebra M (sigma_sets (space M) {X -` A \\<inter> space M |A. A \\<in> sets N}))\"\n    using f1 by (simp add: gen_subalgebra_def sigma_algebra.sets_measure_of_eq sigma_algebra_sigma_sets)\nqed\n\nlemma fct_gen_subalgebra_is_subalgebra:\n  assumes \"X\\<in> measurable M N\"\n  shows \"subalgebra M (fct_gen_subalgebra M N X)\"\nunfolding fct_gen_subalgebra_def\nproof (rule gen_subalgebra_is_subalgebra)\n  show \"sigma_sets (space M) {X -` B \\<inter> space M |B. B \\<in> sets N} \\<subseteq> sets M\" (is \"?L \\<subseteq> ?R\")\n  proof (rule sigma_algebra.sigma_sets_subset)\n    show \"{X -` B \\<inter> space M |B. B \\<in> sets N} \\<subseteq> sets M\"\n    proof\n      fix a\n      assume \"a \\<in> {X -` B \\<inter> (space M) | B. B \\<in> sets N}\"\n      then obtain B where \"B \\<in> sets N\" and \"a = X -` B \\<inter> (space M)\" by auto\n      thus \"a \\<in> sets M\" using measurable_sets assms by simp\n    qed\n    show \"sigma_algebra (space M) (sets M)\" using measure_space by (auto simp add: measure_space_def)\n  qed\n  show \"sigma_algebra (space M) ?L\"\n  proof (rule sigma_algebra_sigma_sets)\n    let ?preimages = \"{X -` B \\<inter> (space M) | B. B \\<in> sets N}\"\n    show \"?preimages \\<le> Pow (space M)\" using assms by auto\n  qed\nqed\n\nlemma fct_gen_subalgebra_fct_measurable:\n  assumes \"X \\<in> space M \\<rightarrow> space N\"\n  shows \"X\\<in> measurable (fct_gen_subalgebra M N X) N\"\nunfolding measurable_def\nproof ((intro CollectI), (intro conjI))\n  have speq: \"space M = space (fct_gen_subalgebra M N X)\"\n      by (simp add: fct_gen_subalgebra_space)\n  show \"X \\<in> space (fct_gen_subalgebra M N X) \\<rightarrow> space N\"\n  proof -\n    have \"X \\<in> space M \\<rightarrow> space N\"  using assms by simp\n    thus ?thesis using speq by simp\n  qed\n  show \"\\<forall>y\\<in>sets N.\n       X -` y \\<inter> space (fct_gen_subalgebra M N X) \\<in> sets (fct_gen_subalgebra M N X)\"\n  using  fct_gen_subalgebra_sets_mem speq by metis\nqed\n\n\n\n\nlemma fct_gen_subalgebra_min:\n  assumes \"subalgebra M P\"\n  and \"f\\<in> measurable P N\"\n  shows \"subalgebra P (fct_gen_subalgebra M N f)\"\nunfolding subalgebra_def\nproof (intro conjI)\n  let ?Mf = \"fct_gen_subalgebra M N f\"\n  show \"space ?Mf = space P\" using assms\n    by (simp add: fct_gen_subalgebra_def gen_subalgebra_space subalgebra_def)\n  show inc: \"sets ?Mf \\<subseteq> sets P\"\n  proof -\n    have \"space M = space P\" using assms by (simp add:subalgebra_def)\n    have \"f\\<in> measurable M N\" using assms using measurable_from_subalg by blast\n    have \"sigma_algebra (space P) (sets P)\" using assms measure_space measure_space_def by auto\n    have \"\\<forall> A \\<in> sets N. f-`A \\<inter> space P \\<in> sets P\" using assms by simp\n    hence \"{f -` A \\<inter> (space M) | A. A \\<in> sets N} \\<subseteq> sets P\" using \\<open>space M = space P\\<close> by auto\n    hence \"sigma_sets (space M) {f -` A \\<inter> (space M) | A. A \\<in> sets N} \\<subseteq> sets P\"\n      by (simp add: \\<open>sigma_algebra (space P) (sets P)\\<close> \\<open>space M = space P\\<close> sigma_algebra.sigma_sets_subset)\n    thus ?thesis using fct_gen_subalgebra_sets \\<open>f \\<in> M \\<rightarrow>\\<^sub>M N\\<close> \\<open>space M = space P\\<close> assms(2)\n      measurable_sets mem_Collect_eq sets.sigma_sets_subset subsetI by blast\n  qed\nqed\n\nlemma fct_preimage_sigma_sets:\n  assumes \"X\\<in> space M \\<rightarrow> space N\"\n  shows \"sigma_sets (space M) {X -` B \\<inter> space M |B. B \\<in> sets N} = {X -` B \\<inter> space M |B. B \\<in> sets N}\" (is \"?L = ?R\")\nproof\n  show \"?R\\<subseteq> ?L\" by blast\n  show \"?L\\<subseteq> ?R\"\n  proof\n    fix A\n    assume \"A\\<in> ?L\"\n    thus \"A\\<in> ?R\"\n    proof (induct rule:sigma_sets.induct, auto)\n      {\n        fix B\n        assume \"B\\<in> sets N\"\n        let ?cB = \"space N - B\"\n        have \"?cB \\<in> sets N\" by (simp add: \\<open>B \\<in> sets N\\<close> sets.compl_sets)\n        have \"space M - X -` B \\<inter> space M = X -` ?cB \\<inter> space M\"\n        proof\n          show \"space M - X -` B \\<inter> space M \\<subseteq> X -` (space N - B) \\<inter> space M\"\n          proof\n            fix w\n            assume \"w \\<in> space M - X -` B \\<inter> space M\"\n            hence \"X w \\<in> (space N - B)\" using assms by blast\n            thus \"w\\<in> X -` (space N - B) \\<inter> space M\" using \\<open>w \\<in> space M - X -` B \\<inter> space M\\<close> by blast\n          qed\n          show \"X -` (space N - B) \\<inter> space M \\<subseteq> space M - X -` B \\<inter> space M\"\n          proof\n            fix w\n            assume \"w\\<in> X -` (space N - B) \\<inter> space M\"\n            thus \"w \\<in> space M - X -` B \\<inter> space M\" by blast\n          qed\n        qed\n        thus \"\\<exists>Ba. space M - X -` B \\<inter> space M = X -` Ba \\<inter> space M \\<and> Ba \\<in> sets N\" using \\<open>?cB \\<in> sets N\\<close> by auto\n      }\n      {\n        fix S::\"nat \\<Rightarrow> 'a set\"\n        assume \"(\\<And>i. \\<exists>B. S i = X -` B \\<inter> space M \\<and> B \\<in> sets N)\"\n        hence \"(\\<forall>i. \\<exists>B. S i = X -` B \\<inter> space M \\<and> B \\<in> sets N)\" by auto\n        hence \"\\<exists> f. \\<forall> x. S x = X -`(f x) \\<inter> space M \\<and> (f x) \\<in> sets N\"\n          using choice[of \"\\<lambda>i B . S i = X -` B \\<inter> space M \\<and> B \\<in> sets N\"] by simp\n        from this obtain rep where \"\\<forall>i. S i = X -` (rep i) \\<inter> space M \\<and> (rep i) \\<in> sets N\" by auto note rProp = this\n        let ?uB = \"\\<Union>i\\<in> UNIV. rep i\"\n        have \"?uB \\<in> sets N\"\n          by (simp add: \\<open>\\<forall>i. S i = X -` rep i \\<inter> space M \\<and> rep i \\<in> sets N\\<close> countable_Un_Int(1))\n        have \"(\\<Union>x. S x) = X -` ?uB \\<inter> space M\"\n        proof\n          show \"(\\<Union>x. S x) \\<subseteq> X -` (\\<Union>i. rep i) \\<inter> space M\"\n          proof\n            fix w\n            assume \"w\\<in> (\\<Union>x. S x)\"\n            hence \"\\<exists>x. w \\<in> S x\" by auto\n            from this obtain x where \"w \\<in> S x\" by auto\n            hence \"w\\<in>  X -` rep x \\<inter> space M\" using rProp by simp\n            hence \"w\\<in> (\\<Union>i. (X -`(rep i)\\<inter> space M))\" by blast\n            also have \"... = X -` (\\<Union>i. rep i) \\<inter> space M\" by auto\n            finally show \"w \\<in> X -` (\\<Union>i. rep i) \\<inter> space M\" .\n          qed\n          show \"X -` (\\<Union>i. rep i) \\<inter> space M \\<subseteq> (\\<Union>x. S x)\"\n          proof\n            fix w\n            assume \"w\\<in> X -` (\\<Union>i. rep i) \\<inter> space M\"\n            hence \"\\<exists> x. w\\<in> X -` (rep x) \\<inter> space M\" by auto\n            from this obtain x where \"w\\<in> X -` (rep x) \\<inter> space M\" by auto\n            hence \"w\\<in> S x\" using rProp by simp\n            thus \"w\\<in> (\\<Union>x. S x)\" by blast\n          qed\n        qed\n        thus \"\\<exists>B. (\\<Union>x. S x) = X -` B \\<inter> space M \\<and> B \\<in> sets N\" using \\<open>?uB \\<in> sets N\\<close> by auto\n      }\n    qed\n  qed\nqed\n\nlemma fct_gen_subalgebra_sigma_sets:\n  assumes \"X\\<in> space M \\<rightarrow> space N\"\n  shows \"sets (fct_gen_subalgebra M N X) = {X -` B \\<inter> space M |B. B \\<in> sets N}\"\n  by (simp add: assms fct_gen_subalgebra_sets fct_preimage_sigma_sets)\n\n\nlemma fct_gen_subalgebra_info:\n  assumes \"f\\<in> space M \\<rightarrow> space N\"\n  and \"x\\<in> space M\"\n  and \"w\\<in> space M\"\n  and \"f x = f w\"\n  shows \"\\<And>A. A\\<in> sets (fct_gen_subalgebra M N f) \\<Longrightarrow> (x\\<in> A) = (w\\<in> A)\"\nproof -\n  {fix A\n  assume \"A \\<in> sigma_sets (space M)  {f -` B \\<inter> (space M) | B. B \\<in> sets N}\"\n  from this have  \"(x\\<in> A) = (w\\<in> A)\"\n  proof (induct rule:sigma_sets.induct)\n    {\n      fix a\n      assume \"a \\<in> {f -` B \\<inter> space M |B. B \\<in> sets N}\"\n      hence \"\\<exists> B\\<in> sets N. a = f -` B \\<inter> space M\" by auto\n      from this obtain B where \"B\\<in> sets N\" and \"a = f -` B \\<inter> space M\" by blast note bhyps = this\n      show \"(x\\<in> a) = (w\\<in> a)\" by (simp add: assms(2) assms(3) assms(4) bhyps(2))\n    }\n    {\n      fix a\n      assume \"a \\<in> sigma_sets (space M) {f -` B \\<inter> space M |B. B \\<in> sets N}\"\n      and \"(x \\<in> a) = (w \\<in> a)\" note xh = this\n      show \"(x \\<in> space M - a) = (w \\<in> space M - a)\" by (simp add: assms(2) assms(3) xh(2))\n    }\n    {\n      fix a::\"nat \\<Rightarrow> 'a set\"\n      assume \"(\\<And>i. a i \\<in> sigma_sets (space M) {f -` B \\<inter> space M |B. B \\<in> sets N})\"\n      and \"(\\<And>i. (x \\<in> a i) = (w \\<in> a i))\"\n      show \"(x \\<in> \\<Union>(a ` UNIV)) = (w \\<in> \\<Union>(a ` UNIV))\" by (simp add: \\<open>\\<And>i. (x \\<in> a i) = (w \\<in> a i)\\<close>)\n    }\n    {show \"(x\\<in> {}) = (w\\<in> {})\" by simp}\n  qed} note eqsig = this\n  fix A\n  assume \"A\\<in> sets (fct_gen_subalgebra M N f)\"\n  hence \"A \\<in> sigma_sets (space M)  {f -` B \\<inter> (space M) | B. B \\<in> sets N}\"\n    using assms(1) fct_gen_subalgebra_sets by blast\n  thus \"(x\\<in> A) = (w\\<in> A)\" using eqsig by simp\nqed\n\nsubsection \\<open>Independence between a random variable and a subalgebra.\\<close>\n\ndefinition (in prob_space) subalgebra_indep_var :: \"('a \\<Rightarrow> real) \\<Rightarrow> 'a measure \\<Rightarrow> bool\" where\n  \"subalgebra_indep_var X N \\<longleftrightarrow>\n    X\\<in> borel_measurable M &\n    (subalgebra M N) &\n    (indep_set (sigma_sets (space M) { X -` A \\<inter> space M | A. A \\<in> sets borel}) (sets N))\"\n\n\nlemma (in prob_space) indep_set_mono:\n  assumes \"indep_set A B\"\n  assumes \"A' \\<subseteq> A\"\n  assumes \"B' \\<subseteq> B\"\n  shows \"indep_set A' B'\"\nby (meson indep_sets2_eq assms subsetCE subset_trans)\n\n\nlemma (in prob_space) subalgebra_indep_var_indicator:\n  fixes X::\"'a\\<Rightarrow>real\"\n  assumes \"subalgebra_indep_var X N\"\n  and \"X \\<in> borel_measurable M\"\n  and \"A \\<in> sets N\"\n  shows \"indep_var borel X borel (indicator A)\"\nproof ((rule indep_var_eq[THEN iffD2]), (intro conjI))\n  let ?IA = \"(indicator A)::'a\\<Rightarrow> real\"\n  show bm:\"random_variable borel X\" by (simp add: assms(2))\n  show \"random_variable borel ?IA\" using assms indep_setD_ev2 unfolding subalgebra_indep_var_def by auto\n  show \"indep_set (sigma_sets (space M) {X -` A \\<inter> space M |A. A \\<in> sets borel})\n   (sigma_sets (space M) {?IA -` Aa \\<inter> space M |Aa. Aa \\<in> sets borel})\"\n  proof (rule indep_set_mono)\n    show \"sigma_sets (space M) {X -` A \\<inter> space M |A. A \\<in> sets borel} \\<subseteq> sigma_sets (space M) {X -` A \\<inter> space M |A. A \\<in> sets borel}\" by simp\n    show \"sigma_sets (space M) {?IA -` B \\<inter> space M |B. B \\<in> sets borel} \\<subseteq> sets N\"\n    proof -\n      have \"sigma_algebra (space M) (sets N)\" using assms\n        by (metis subalgebra_indep_var_def sets.sigma_algebra_axioms subalgebra_def)\n      have \"sigma_sets (space M) {?IA -` B \\<inter> space M |B. B \\<in> sets borel} \\<subseteq> sigma_sets (space M) (sets N)\"\n      proof (rule sigma_sets_subseteq)\n        show \"{?IA -` B \\<inter> space M |B. B \\<in> sets borel} \\<subseteq> sets N\"\n        proof\n          fix x\n          assume \"x \\<in> {?IA -` B \\<inter> space M |B. B \\<in> sets borel}\"\n          then obtain B where \"B \\<in> sets borel\" and \"x = ?IA -` B \\<inter> space M\" by auto\n          thus \"x \\<in> sets N\"\n            by (metis (no_types, lifting) assms(1) assms(3) borel_measurable_indicator measurable_sets subalgebra_indep_var_def subalgebra_def)\n        qed\n      qed\n      also have \"... = sets N\"\n        by (simp add: \\<open>sigma_algebra (space M) (sets N)\\<close> sigma_algebra.sigma_sets_eq)\n      finally show \"sigma_sets (space M) {?IA -` B \\<inter> space M |B. B \\<in> sets borel} \\<subseteq> sets N\" .\n    qed\n    show \"indep_set (sigma_sets (space M) {X -` A \\<inter> space M |A. A \\<in> sets borel}) (sets N) \"\n      using assms unfolding subalgebra_indep_var_def by simp\n  qed\nqed\n\nlemma fct_gen_subalgebra_cong:\n  assumes \"space M = space P\"\n  and \"sets N = sets Q\"\n  shows \"fct_gen_subalgebra M N X = fct_gen_subalgebra P Q X\"\nproof -\n  have \"space M = space P\" using assms by simp\n  thus ?thesis using assms unfolding fct_gen_subalgebra_def gen_subalgebra_def by simp\nqed\n\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/DiscretePricing/Generated_Subalgebra.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8670357494949105, "lm_q2_score": 0.8479677583778258, "lm_q1q2_score": 0.7352183609326374}}
{"text": "section \\<open>\\isaheader{Operations on sorted Lists}\\<close>\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: 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": "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/Collections/Lib/Sorted_List_Operations.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677583778258, "lm_q2_score": 0.8670357494949105, "lm_q1q2_score": 0.7352183609326374}}
{"text": "(*  Title:      CCL/Type.thy\n    Author:     Martin Coen\n    Copyright   1993  University of Cambridge\n*)\n\nsection \\<open>Types in CCL are defined as sets of terms\\<close>\n\ntheory Type\nimports Term\nbegin\n\ndefinition Subtype :: \"['a set, 'a \\<Rightarrow> o] \\<Rightarrow> 'a set\"\n  where \"Subtype(A, P) == {x. x:A \\<and> P(x)}\"\n\nsyntax\n  \"_Subtype\" :: \"[idt, 'a set, o] \\<Rightarrow> 'a set\"  (\"(1{_: _ ./ _})\")\ntranslations\n  \"{x: A. B}\" == \"CONST Subtype(A, \\<lambda>x. B)\"\n\ndefinition Unit :: \"i set\"\n  where \"Unit == {x. x=one}\"\n\ndefinition Bool :: \"i set\"\n  where \"Bool == {x. x=true | x=false}\"\n\ndefinition Plus :: \"[i set, i set] \\<Rightarrow> i set\"  (infixr \"+\" 55)\n  where \"A+B == {x. (EX a:A. x=inl(a)) | (EX b:B. x=inr(b))}\"\n\ndefinition Pi :: \"[i set, i \\<Rightarrow> i set] \\<Rightarrow> i set\"\n  where \"Pi(A,B) == {x. EX b. x=lam x. b(x) \\<and> (ALL x:A. b(x):B(x))}\"\n\ndefinition Sigma :: \"[i set, i \\<Rightarrow> i set] \\<Rightarrow> i set\"\n  where \"Sigma(A,B) == {x. EX a:A. EX b:B(a).x=<a,b>}\"\n\nsyntax\n  \"_Pi\" :: \"[idt, i set, i set] \\<Rightarrow> i set\"  (\"(3PROD _:_./ _)\" [0,0,60] 60)\n  \"_Sigma\" :: \"[idt, i set, i set] \\<Rightarrow> i set\"  (\"(3SUM _:_./ _)\" [0,0,60] 60)\n  \"_arrow\" :: \"[i set, i set] \\<Rightarrow> i set\"  (\"(_ ->/ _)\"  [54, 53] 53)\n  \"_star\"  :: \"[i set, i set] \\<Rightarrow> i set\"  (\"(_ */ _)\" [56, 55] 55)\ntranslations\n  \"PROD x:A. B\" \\<rightharpoonup> \"CONST Pi(A, \\<lambda>x. B)\"\n  \"A -> B\" \\<rightharpoonup> \"CONST Pi(A, \\<lambda>_. B)\"\n  \"SUM x:A. B\" \\<rightharpoonup> \"CONST Sigma(A, \\<lambda>x. B)\"\n  \"A * B\" \\<rightharpoonup> \"CONST Sigma(A, \\<lambda>_. B)\"\nprint_translation \\<open>\n [(\\<^const_syntax>\\<open>Pi\\<close>,\n    fn _ => Syntax_Trans.dependent_tr' (\\<^syntax_const>\\<open>_Pi\\<close>, \\<^syntax_const>\\<open>_arrow\\<close>)),\n  (\\<^const_syntax>\\<open>Sigma\\<close>,\n    fn _ => Syntax_Trans.dependent_tr' (\\<^syntax_const>\\<open>_Sigma\\<close>, \\<^syntax_const>\\<open>_star\\<close>))]\n\\<close>\n\ndefinition Nat :: \"i set\"\n  where \"Nat == lfp(\\<lambda>X. Unit + X)\"\n\ndefinition List :: \"i set \\<Rightarrow> i set\"\n  where \"List(A) == lfp(\\<lambda>X. Unit + A*X)\"\n\ndefinition Lists :: \"i set \\<Rightarrow> i set\"\n  where \"Lists(A) == gfp(\\<lambda>X. Unit + A*X)\"\n\ndefinition ILists :: \"i set \\<Rightarrow> i set\"\n  where \"ILists(A) == gfp(\\<lambda>X.{} + A*X)\"\n\n\ndefinition TAll :: \"(i set \\<Rightarrow> i set) \\<Rightarrow> i set\"  (binder \"TALL \" 55)\n  where \"TALL X. B(X) == Inter({X. EX Y. X=B(Y)})\"\n\ndefinition TEx :: \"(i set \\<Rightarrow> i set) \\<Rightarrow> i set\"  (binder \"TEX \" 55)\n  where \"TEX X. B(X) == Union({X. EX Y. X=B(Y)})\"\n\ndefinition Lift :: \"i set \\<Rightarrow> i set\"  (\"(3[_])\")\n  where \"[A] == A Un {bot}\"\n\ndefinition SPLIT :: \"[i, [i, i] \\<Rightarrow> i set] \\<Rightarrow> i set\"\n  where \"SPLIT(p,B) == Union({A. EX x y. p=<x,y> \\<and> A=B(x,y)})\"\n\n\nlemmas simp_type_defs =\n    Subtype_def Unit_def Bool_def Plus_def Sigma_def Pi_def Lift_def TAll_def TEx_def\n  and ind_type_defs = Nat_def List_def\n  and simp_data_defs = one_def inl_def inr_def\n  and ind_data_defs = zero_def succ_def nil_def cons_def\n\nlemma subsetXH: \"A <= B \\<longleftrightarrow> (ALL x. x:A \\<longrightarrow> x:B)\"\n  by blast\n\n\nsubsection \\<open>Exhaustion Rules\\<close>\n\nlemma EmptyXH: \"\\<And>a. a : {} \\<longleftrightarrow> False\"\n  and SubtypeXH: \"\\<And>a A P. a : {x:A. P(x)} \\<longleftrightarrow> (a:A \\<and> P(a))\"\n  and UnitXH: \"\\<And>a. a : Unit          \\<longleftrightarrow> a=one\"\n  and BoolXH: \"\\<And>a. a : Bool          \\<longleftrightarrow> a=true | a=false\"\n  and PlusXH: \"\\<And>a A B. a : A+B           \\<longleftrightarrow> (EX x:A. a=inl(x)) | (EX x:B. a=inr(x))\"\n  and PiXH: \"\\<And>a A B. a : PROD x:A. B(x) \\<longleftrightarrow> (EX b. a=lam x. b(x) \\<and> (ALL x:A. b(x):B(x)))\"\n  and SgXH: \"\\<And>a A B. a : SUM x:A. B(x)  \\<longleftrightarrow> (EX x:A. EX y:B(x).a=<x,y>)\"\n  unfolding simp_type_defs by blast+\n\nlemmas XHs = EmptyXH SubtypeXH UnitXH BoolXH PlusXH PiXH SgXH\n\nlemma LiftXH: \"a : [A] \\<longleftrightarrow> (a=bot | a:A)\"\n  and TallXH: \"a : TALL X. B(X) \\<longleftrightarrow> (ALL X. a:B(X))\"\n  and TexXH: \"a : TEX X. B(X) \\<longleftrightarrow> (EX X. a:B(X))\"\n  unfolding simp_type_defs by blast+\n\nML \\<open>ML_Thms.bind_thms (\"case_rls\", XH_to_Es @{thms XHs})\\<close>\n\n\nsubsection \\<open>Canonical Type Rules\\<close>\n\nlemma oneT: \"one : Unit\"\n  and trueT: \"true : Bool\"\n  and falseT: \"false : Bool\"\n  and lamT: \"\\<And>b B. (\\<And>x. x:A \\<Longrightarrow> b(x):B(x)) \\<Longrightarrow> lam x. b(x) : Pi(A,B)\"\n  and pairT: \"\\<And>b B. \\<lbrakk>a:A; b:B(a)\\<rbrakk> \\<Longrightarrow> <a,b>:Sigma(A,B)\"\n  and inlT: \"a:A \\<Longrightarrow> inl(a) : A+B\"\n  and inrT: \"b:B \\<Longrightarrow> inr(b) : A+B\"\n  by (blast intro: XHs [THEN iffD2])+\n\nlemmas canTs = oneT trueT falseT pairT lamT inlT inrT\n\n\nsubsection \\<open>Non-Canonical Type Rules\\<close>\n\nlemma lem: \"\\<lbrakk>a:B(u); u = v\\<rbrakk> \\<Longrightarrow> a : B(v)\"\n  by blast\n\n\nML \\<open>\nfun mk_ncanT_tac top_crls crls =\n  SUBPROOF (fn {context = ctxt, prems = major :: prems, ...} =>\n    resolve_tac ctxt ([major] RL top_crls) 1 THEN\n    REPEAT_SOME (eresolve_tac ctxt (crls @ @{thms exE bexE conjE disjE})) THEN\n    ALLGOALS (asm_simp_tac ctxt) THEN\n    ALLGOALS (assume_tac ctxt ORELSE' resolve_tac ctxt (prems RL [@{thm lem}])\n      ORELSE' eresolve_tac ctxt @{thms bspec}) THEN\n    safe_tac (ctxt addSIs prems))\n\\<close>\n\nmethod_setup ncanT = \\<open>\n  Scan.succeed (SIMPLE_METHOD' o mk_ncanT_tac @{thms case_rls} @{thms case_rls})\n\\<close>\n\nlemma ifT: \"\\<lbrakk>b:Bool; b=true \\<Longrightarrow> t:A(true); b=false \\<Longrightarrow> u:A(false)\\<rbrakk> \\<Longrightarrow> if b then t else u : A(b)\"\n  by ncanT\n\nlemma applyT: \"\\<lbrakk>f : Pi(A,B); a:A\\<rbrakk> \\<Longrightarrow> f ` a : B(a)\"\n  by ncanT\n\nlemma splitT: \"\\<lbrakk>p:Sigma(A,B); \\<And>x y. \\<lbrakk>x:A; y:B(x); p=<x,y>\\<rbrakk> \\<Longrightarrow> c(x,y):C(<x,y>)\\<rbrakk> \\<Longrightarrow> split(p,c):C(p)\"\n  by ncanT\n\nlemma whenT:\n  \"\\<lbrakk>p:A+B;\n    \\<And>x. \\<lbrakk>x:A; p=inl(x)\\<rbrakk> \\<Longrightarrow> a(x):C(inl(x));\n    \\<And>y. \\<lbrakk>y:B;  p=inr(y)\\<rbrakk> \\<Longrightarrow> b(y):C(inr(y))\\<rbrakk> \\<Longrightarrow> when(p,a,b) : C(p)\"\n  by ncanT\n\nlemmas ncanTs = ifT applyT splitT whenT\n\n\nsubsection \\<open>Subtypes\\<close>\n\nlemma SubtypeD1: \"a : Subtype(A, P) \\<Longrightarrow> a : A\"\n  and SubtypeD2: \"a : Subtype(A, P) \\<Longrightarrow> P(a)\"\n  by (simp_all add: SubtypeXH)\n\nlemma SubtypeI: \"\\<lbrakk>a:A; P(a)\\<rbrakk> \\<Longrightarrow> a : {x:A. P(x)}\"\n  by (simp add: SubtypeXH)\n\nlemma SubtypeE: \"\\<lbrakk>a : {x:A. P(x)}; \\<lbrakk>a:A; P(a)\\<rbrakk> \\<Longrightarrow> Q\\<rbrakk> \\<Longrightarrow> Q\"\n  by (simp add: SubtypeXH)\n\n\nsubsection \\<open>Monotonicity\\<close>\n\nlemma idM: \"mono (\\<lambda>X. X)\"\n  apply (rule monoI)\n  apply assumption\n  done\n\nlemma constM: \"mono(\\<lambda>X. A)\"\n  apply (rule monoI)\n  apply (rule subset_refl)\n  done\n\nlemma \"mono(\\<lambda>X. A(X)) \\<Longrightarrow> mono(\\<lambda>X.[A(X)])\"\n  apply (rule subsetI [THEN monoI])\n  apply (drule LiftXH [THEN iffD1])\n  apply (erule disjE)\n   apply (erule disjI1 [THEN LiftXH [THEN iffD2]])\n  apply (rule disjI2 [THEN LiftXH [THEN iffD2]])\n  apply (drule (1) monoD)\n  apply blast\n  done\n\nlemma SgM:\n  \"\\<lbrakk>mono(\\<lambda>X. A(X)); \\<And>x X. x:A(X) \\<Longrightarrow> mono(\\<lambda>X. B(X,x))\\<rbrakk> \\<Longrightarrow>\n    mono(\\<lambda>X. Sigma(A(X),B(X)))\"\n  by (blast intro!: subsetI [THEN monoI] canTs elim!: case_rls\n    dest!: monoD [THEN subsetD])\n\nlemma PiM: \"(\\<And>x. x:A \\<Longrightarrow> mono(\\<lambda>X. B(X,x))) \\<Longrightarrow> mono(\\<lambda>X. Pi(A,B(X)))\"\n  by (blast intro!: subsetI [THEN monoI] canTs elim!: case_rls\n    dest!: monoD [THEN subsetD])\n\nlemma PlusM: \"\\<lbrakk>mono(\\<lambda>X. A(X)); mono(\\<lambda>X. B(X))\\<rbrakk> \\<Longrightarrow> mono(\\<lambda>X. A(X)+B(X))\"\n  by (blast intro!: subsetI [THEN monoI] canTs elim!: case_rls\n    dest!: monoD [THEN subsetD])\n\n\nsubsection \\<open>Recursive types\\<close>\n\nsubsubsection \\<open>Conversion Rules for Fixed Points via monotonicity and Tarski\\<close>\n\nlemma NatM: \"mono(\\<lambda>X. Unit+X)\"\n  apply (rule PlusM constM idM)+\n  done\n\nlemma def_NatB: \"Nat = Unit + Nat\"\n  apply (rule def_lfp_Tarski [OF Nat_def])\n  apply (rule NatM)\n  done\n\nlemma ListM: \"mono(\\<lambda>X.(Unit+Sigma(A,\\<lambda>y. X)))\"\n  apply (rule PlusM SgM constM idM)+\n  done\n\nlemma def_ListB: \"List(A) = Unit + A * List(A)\"\n  apply (rule def_lfp_Tarski [OF List_def])\n  apply (rule ListM)\n  done\n\nlemma def_ListsB: \"Lists(A) = Unit + A * Lists(A)\"\n  apply (rule def_gfp_Tarski [OF Lists_def])\n  apply (rule ListM)\n  done\n\nlemma IListsM: \"mono(\\<lambda>X.({} + Sigma(A,\\<lambda>y. X)))\"\n  apply (rule PlusM SgM constM idM)+\n  done\n\nlemma def_IListsB: \"ILists(A) = {} + A * ILists(A)\"\n  apply (rule def_gfp_Tarski [OF ILists_def])\n  apply (rule IListsM)\n  done\n\nlemmas ind_type_eqs = def_NatB def_ListB def_ListsB def_IListsB\n\n\nsubsection \\<open>Exhaustion Rules\\<close>\n\nlemma NatXH: \"a : Nat \\<longleftrightarrow> (a=zero | (EX x:Nat. a=succ(x)))\"\n  and ListXH: \"a : List(A) \\<longleftrightarrow> (a=[] | (EX x:A. EX xs:List(A).a=x$xs))\"\n  and ListsXH: \"a : Lists(A) \\<longleftrightarrow> (a=[] | (EX x:A. EX xs:Lists(A).a=x$xs))\"\n  and IListsXH: \"a : ILists(A) \\<longleftrightarrow> (EX x:A. EX xs:ILists(A).a=x$xs)\"\n  unfolding ind_data_defs\n  by (rule ind_type_eqs [THEN XHlemma1], blast intro!: canTs elim!: case_rls)+\n\nlemmas iXHs = NatXH ListXH\n\nML \\<open>ML_Thms.bind_thms (\"icase_rls\", XH_to_Es @{thms iXHs})\\<close>\n\n\nsubsection \\<open>Type Rules\\<close>\n\nlemma zeroT: \"zero : Nat\"\n  and succT: \"n:Nat \\<Longrightarrow> succ(n) : Nat\"\n  and nilT: \"[] : List(A)\"\n  and consT: \"\\<lbrakk>h:A; t:List(A)\\<rbrakk> \\<Longrightarrow> h$t : List(A)\"\n  by (blast intro: iXHs [THEN iffD2])+\n\nlemmas icanTs = zeroT succT nilT consT\n\n\nmethod_setup incanT = \\<open>\n  Scan.succeed (SIMPLE_METHOD' o mk_ncanT_tac @{thms icase_rls} @{thms case_rls})\n\\<close>\n\nlemma ncaseT: \"\\<lbrakk>n:Nat; n=zero \\<Longrightarrow> b:C(zero); \\<And>x. \\<lbrakk>x:Nat; n=succ(x)\\<rbrakk> \\<Longrightarrow> c(x):C(succ(x))\\<rbrakk>\n    \\<Longrightarrow> ncase(n,b,c) : C(n)\"\n  by incanT\n\nlemma lcaseT: \"\\<lbrakk>l:List(A); l = [] \\<Longrightarrow> b:C([]); \\<And>h t. \\<lbrakk>h:A; t:List(A); l=h$t\\<rbrakk> \\<Longrightarrow> c(h,t):C(h$t)\\<rbrakk>\n    \\<Longrightarrow> lcase(l,b,c) : C(l)\"\n  by incanT\n\nlemmas incanTs = ncaseT lcaseT\n\n\nsubsection \\<open>Induction Rules\\<close>\n\nlemmas ind_Ms = NatM ListM\n\nlemma Nat_ind: \"\\<lbrakk>n:Nat; P(zero); \\<And>x. \\<lbrakk>x:Nat; P(x)\\<rbrakk> \\<Longrightarrow> P(succ(x))\\<rbrakk> \\<Longrightarrow> P(n)\"\n  apply (unfold ind_data_defs)\n  apply (erule def_induct [OF Nat_def _ NatM])\n  apply (blast intro: canTs elim!: case_rls)\n  done\n\nlemma List_ind: \"\\<lbrakk>l:List(A); P([]); \\<And>x xs. \\<lbrakk>x:A; xs:List(A); P(xs)\\<rbrakk> \\<Longrightarrow> P(x$xs)\\<rbrakk> \\<Longrightarrow> P(l)\"\n  apply (unfold ind_data_defs)\n  apply (erule def_induct [OF List_def _ ListM])\n  apply (blast intro: canTs elim!: case_rls)\n  done\n\nlemmas inds = Nat_ind List_ind\n\n\nsubsection \\<open>Primitive Recursive Rules\\<close>\n\nlemma nrecT: \"\\<lbrakk>n:Nat; b:C(zero); \\<And>x g. \\<lbrakk>x:Nat; g:C(x)\\<rbrakk> \\<Longrightarrow> c(x,g):C(succ(x))\\<rbrakk>\n    \\<Longrightarrow> nrec(n,b,c) : C(n)\"\n  by (erule Nat_ind) auto\n\nlemma lrecT: \"\\<lbrakk>l:List(A); b:C([]); \\<And>x xs g. \\<lbrakk>x:A; xs:List(A); g:C(xs)\\<rbrakk> \\<Longrightarrow> c(x,xs,g):C(x$xs) \\<rbrakk>\n    \\<Longrightarrow> lrec(l,b,c) : C(l)\"\n  by (erule List_ind) auto\n\nlemmas precTs = nrecT lrecT\n\n\nsubsection \\<open>Theorem proving\\<close>\n\nlemma SgE2: \"\\<lbrakk><a,b> : Sigma(A,B); \\<lbrakk>a:A; b:B(a)\\<rbrakk> \\<Longrightarrow> P\\<rbrakk> \\<Longrightarrow> P\"\n  unfolding SgXH by blast\n\n(* General theorem proving ignores non-canonical term-formers,             *)\n(*         - intro rules are type rules for canonical terms                *)\n(*         - elim rules are case rules (no non-canonical terms appear)     *)\n\nML \\<open>ML_Thms.bind_thms (\"XHEs\", XH_to_Es @{thms XHs})\\<close>\n\nlemmas [intro!] = SubtypeI canTs icanTs\n  and [elim!] = SubtypeE XHEs\n\n\nsubsection \\<open>Infinite Data Types\\<close>\n\nlemma lfp_subset_gfp: \"mono(f) \\<Longrightarrow> lfp(f) <= gfp(f)\"\n  apply (rule lfp_lowerbound [THEN subset_trans])\n   apply (erule gfp_lemma3)\n  apply (rule subset_refl)\n  done\n\nlemma gfpI:\n  assumes \"a:A\"\n    and \"\\<And>x X. \\<lbrakk>x:A; ALL y:A. t(y):X\\<rbrakk> \\<Longrightarrow> t(x) : B(X)\"\n  shows \"t(a) : gfp(B)\"\n  apply (rule coinduct)\n   apply (rule_tac P = \"\\<lambda>x. EX y:A. x=t (y)\" in CollectI)\n   apply (blast intro!: assms)+\n  done\n\nlemma def_gfpI: \"\\<lbrakk>C == gfp(B); a:A; \\<And>x X. \\<lbrakk>x:A; ALL y:A. t(y):X\\<rbrakk> \\<Longrightarrow> t(x) : B(X)\\<rbrakk> \\<Longrightarrow> t(a) : C\"\n  apply unfold\n  apply (erule gfpI)\n  apply blast\n  done\n\n(* EG *)\nlemma \"letrec g x be zero$g(x) in g(bot) : Lists(Nat)\"\n  apply (rule refl [THEN UnitXH [THEN iffD2], THEN Lists_def [THEN def_gfpI]])\n  apply (subst letrecB)\n  apply (unfold cons_def)\n  apply blast\n  done\n\n\nsubsection \\<open>Lemmas and tactics for using the rule \\<open>coinduct3\\<close> on \\<open>[=\\<close> and \\<open>=\\<close>\\<close>\n\nlemma lfpI: \"\\<lbrakk>mono(f); a : f(lfp(f))\\<rbrakk> \\<Longrightarrow> a : lfp(f)\"\n  apply (erule lfp_Tarski [THEN ssubst])\n  apply assumption\n  done\n\nlemma ssubst_single: \"\\<lbrakk>a = a'; a' : A\\<rbrakk> \\<Longrightarrow> a : A\"\n  by simp\n\nlemma ssubst_pair: \"\\<lbrakk>a = a'; b = b'; <a',b'> : A\\<rbrakk> \\<Longrightarrow> <a,b> : A\"\n  by simp\n\n\nML \\<open>\n  val coinduct3_tac = SUBPROOF (fn {context = ctxt, prems = mono :: prems, ...} =>\n    fast_tac (ctxt addIs (mono RS @{thm coinduct3_mono_lemma} RS @{thm lfpI}) :: prems) 1);\n\\<close>\n\nmethod_setup coinduct3 = \\<open>Scan.succeed (SIMPLE_METHOD' o coinduct3_tac)\\<close>\n\nlemma ci3_RI: \"\\<lbrakk>mono(Agen); a : R\\<rbrakk> \\<Longrightarrow> a : lfp(\\<lambda>x. Agen(x) Un R Un A)\"\n  by coinduct3\n\nlemma ci3_AgenI: \"\\<lbrakk>mono(Agen); a : Agen(lfp(\\<lambda>x. Agen(x) Un R Un A))\\<rbrakk> \\<Longrightarrow>\n    a : lfp(\\<lambda>x. Agen(x) Un R Un A)\"\n  by coinduct3\n\nlemma ci3_AI: \"\\<lbrakk>mono(Agen); a : A\\<rbrakk> \\<Longrightarrow> a : lfp(\\<lambda>x. Agen(x) Un R Un A)\"\n  by coinduct3\n\nML \\<open>\nfun genIs_tac ctxt genXH gen_mono =\n  resolve_tac ctxt [genXH RS @{thm iffD2}] THEN'\n  simp_tac ctxt THEN'\n  TRY o fast_tac\n    (ctxt addIs [genXH RS @{thm iffD2}, gen_mono RS @{thm coinduct3_mono_lemma} RS @{thm lfpI}])\n\\<close>\n\nmethod_setup genIs = \\<open>\n  Attrib.thm -- Attrib.thm >>\n    (fn (genXH, gen_mono) => fn ctxt => SIMPLE_METHOD' (genIs_tac ctxt genXH gen_mono))\n\\<close>\n\n\nsubsection \\<open>POgen\\<close>\n\nlemma PO_refl: \"<a,a> : PO\"\n  by (rule po_refl [THEN PO_iff [THEN iffD1]])\n\nlemma POgenIs:\n  \"<true,true> : POgen(R)\"\n  \"<false,false> : POgen(R)\"\n  \"\\<lbrakk><a,a'> : R; <b,b'> : R\\<rbrakk> \\<Longrightarrow> <<a,b>,<a',b'>> : POgen(R)\"\n  \"\\<And>b b'. (\\<And>x. <b(x),b'(x)> : R) \\<Longrightarrow> <lam x. b(x),lam x. b'(x)> : POgen(R)\"\n  \"<one,one> : POgen(R)\"\n  \"<a,a'> : lfp(\\<lambda>x. POgen(x) Un R Un PO) \\<Longrightarrow>\n    <inl(a),inl(a')> : POgen(lfp(\\<lambda>x. POgen(x) Un R Un PO))\"\n  \"<b,b'> : lfp(\\<lambda>x. POgen(x) Un R Un PO) \\<Longrightarrow>\n    <inr(b),inr(b')> : POgen(lfp(\\<lambda>x. POgen(x) Un R Un PO))\"\n  \"<zero,zero> : POgen(lfp(\\<lambda>x. POgen(x) Un R Un PO))\"\n  \"<n,n'> : lfp(\\<lambda>x. POgen(x) Un R Un PO) \\<Longrightarrow>\n    <succ(n),succ(n')> : POgen(lfp(\\<lambda>x. POgen(x) Un R Un PO))\"\n  \"<[],[]> : POgen(lfp(\\<lambda>x. POgen(x) Un R Un PO))\"\n  \"\\<lbrakk><h,h'> : lfp(\\<lambda>x. POgen(x) Un R Un PO);  <t,t'> : lfp(\\<lambda>x. POgen(x) Un R Un PO)\\<rbrakk>\n    \\<Longrightarrow> <h$t,h'$t'> : POgen(lfp(\\<lambda>x. POgen(x) Un R Un PO))\"\n  unfolding data_defs by (genIs POgenXH POgen_mono)+\n\nML \\<open>\nfun POgen_tac ctxt (rla, rlb) i =\n  SELECT_GOAL (safe_tac ctxt) i THEN\n  resolve_tac ctxt [rlb RS (rla RS @{thm ssubst_pair})] i THEN\n  (REPEAT (resolve_tac ctxt\n      (@{thms POgenIs} @ [@{thm PO_refl} RS (@{thm POgen_mono} RS @{thm ci3_AI})] @\n        (@{thms POgenIs} RL [@{thm POgen_mono} RS @{thm ci3_AgenI}]) @\n        [@{thm POgen_mono} RS @{thm ci3_RI}]) i))\n\\<close>\n\n\nsubsection \\<open>EQgen\\<close>\n\nlemma EQ_refl: \"<a,a> : EQ\"\n  by (rule refl [THEN EQ_iff [THEN iffD1]])\n\nlemma EQgenIs:\n  \"<true,true> : EQgen(R)\"\n  \"<false,false> : EQgen(R)\"\n  \"\\<lbrakk><a,a'> : R; <b,b'> : R\\<rbrakk> \\<Longrightarrow> <<a,b>,<a',b'>> : EQgen(R)\"\n  \"\\<And>b b'. (\\<And>x. <b(x),b'(x)> : R) \\<Longrightarrow> <lam x. b(x),lam x. b'(x)> : EQgen(R)\"\n  \"<one,one> : EQgen(R)\"\n  \"<a,a'> : lfp(\\<lambda>x. EQgen(x) Un R Un EQ) \\<Longrightarrow>\n    <inl(a),inl(a')> : EQgen(lfp(\\<lambda>x. EQgen(x) Un R Un EQ))\"\n  \"<b,b'> : lfp(\\<lambda>x. EQgen(x) Un R Un EQ) \\<Longrightarrow>\n    <inr(b),inr(b')> : EQgen(lfp(\\<lambda>x. EQgen(x) Un R Un EQ))\"\n  \"<zero,zero> : EQgen(lfp(\\<lambda>x. EQgen(x) Un R Un EQ))\"\n  \"<n,n'> : lfp(\\<lambda>x. EQgen(x) Un R Un EQ) \\<Longrightarrow>\n    <succ(n),succ(n')> : EQgen(lfp(\\<lambda>x. EQgen(x) Un R Un EQ))\"\n  \"<[],[]> : EQgen(lfp(\\<lambda>x. EQgen(x) Un R Un EQ))\"\n  \"\\<lbrakk><h,h'> : lfp(\\<lambda>x. EQgen(x) Un R Un EQ); <t,t'> : lfp(\\<lambda>x. EQgen(x) Un R Un EQ)\\<rbrakk>\n    \\<Longrightarrow> <h$t,h'$t'> : EQgen(lfp(\\<lambda>x. EQgen(x) Un R Un EQ))\"\n  unfolding data_defs by (genIs EQgenXH EQgen_mono)+\n\nML \\<open>\nfun EQgen_raw_tac ctxt i =\n  (REPEAT (resolve_tac ctxt (@{thms EQgenIs} @\n        [@{thm EQ_refl} RS (@{thm EQgen_mono} RS @{thm ci3_AI})] @\n        (@{thms EQgenIs} RL [@{thm EQgen_mono} RS @{thm ci3_AgenI}]) @\n        [@{thm EQgen_mono} RS @{thm ci3_RI}]) i))\n\n(* Goals of the form R <= EQgen(R) - rewrite elements <a,b> : EQgen(R) using rews and *)\n(* then reduce this to a goal <a',b'> : R (hopefully?)                                *)\n(*      rews are rewrite rules that would cause looping in the simpifier              *)\n\nfun EQgen_tac ctxt rews i =\n SELECT_GOAL\n   (TRY (safe_tac ctxt) THEN\n    resolve_tac ctxt ((rews @ [@{thm refl}]) RL ((rews @ [@{thm refl}]) RL [@{thm ssubst_pair}])) i THEN\n    ALLGOALS (simp_tac ctxt) THEN\n    ALLGOALS (EQgen_raw_tac ctxt)) i\n\\<close>\n\nmethod_setup EQgen = \\<open>\n  Attrib.thms >> (fn ths => fn ctxt => SIMPLE_METHOD' (EQgen_tac ctxt ths))\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/CCL/Type.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8991213826762114, "lm_q2_score": 0.817574471748733, "lm_q1q2_score": 0.735098689479494}}
{"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 (Plus (N i) (N j)) = False\" |\n  \"optimal (N i) = True\" |\n  \"optimal (V str) = True\" |\n  \"optimal (Plus a b) = conj (optimal a) (optimal b)\"\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 i) = i\" |\n  \"sumN (Plus a b) = sumN a + sumN b\"|\n  \"sumN (V str) = 0\"\n\nfun zeroN :: \"aexp \\<Rightarrow> aexp\" where\n  \"zeroN (N i) = N 0\" |\n  \"zeroN (Plus a b) = Plus (zeroN a) (zeroN b)\" |\n  \"zeroN (V str) = V str\"\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 \nfun sepN :: \"aexp \\<Rightarrow> aexp\" where\n  \"sepN a = Plus (N (sumN a)) (zeroN a)\" \n\nvalue \"asimp (sepN (Plus (V t) (Plus (N 3) (N 4))))\"  \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 auto\n  done  \n    \nlemma aval_sepN: \"aval t s = aval (sepN t) s\"\n  apply (induction t)\n  apply auto\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\nfun 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)\n  apply auto  \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 v1 a (V v2)  = (if v1 = v2 then a else (V v2))\" |\n  \"subst v1 a (Plus x y) = Plus (subst v1 a x) (subst v1 a y)\" |\n  \"subst v1 a (N x) = N x\"  \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: {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\n  \nlemma subst_\n\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\n  \ndatatype aexp1 = N1 int | V1 vname | Plus1 aexp1 aexp1 | Times aexp1 aexp1\n\nfun aval1 :: \"aexp1 \\<Rightarrow> state \\<Rightarrow> val\" where\n\"aval1 (N1 n) s = n\" |\n\"aval1 (V1 x) s = s x\" |\n\"aval1 (Plus1 a\\<^sub>1 a\\<^sub>2) s = aval1 a\\<^sub>1 s + aval1 a\\<^sub>2 s\" |\n\"aval1 (Times a\\<^sub>1 a\\<^sub>2) s = (aval1 a\\<^sub>1 s) * (aval1 a\\<^sub>2  s)\"\n\nvalue \"aval1 (Times (N1 3) (Plus1 (N1 4) (N1 5))) (\\<lambda>x. 0) \"\n\nfun plus1 :: \"aexp1 \\<Rightarrow> aexp1 \\<Rightarrow> aexp1\" where\n\"plus1 (N1 i\\<^sub>1) (N1 i\\<^sub>2) = N1 (i\\<^sub>1+i\\<^sub>2)\" |\n\"plus1 (N1 i) a = (if i=0 then a else Plus1 (N1 i) a)\" |\n\"plus1 a (N1 i) = (if i=0 then a else Plus1 a (N1 i))\" |\n\"plus1 a\\<^sub>1 a\\<^sub>2 = Plus1 a\\<^sub>1 a\\<^sub>2\"\n\nfun mult :: \"aexp1 \\<Rightarrow> aexp1 \\<Rightarrow> aexp1\" where\n\"mult (N1 i\\<^sub>1) (N1 i\\<^sub>2) = N1 (i\\<^sub>1*i\\<^sub>2)\" |\n\"mult (N1 i) a = \n  (if i=1 then a else if i=0 then (N1 0) else Times (N1 i) a)\" |\n\"mult a (N1 i) = (if i=0 then (N1 0) else if i = 1 then a else Times a (N1 i))\" |\n\"mult a\\<^sub>1 a\\<^sub>2 = Times a\\<^sub>1 a\\<^sub>2\"\n\n\nfun asimp1 :: \"aexp1 \\<Rightarrow> aexp1\" where\n\"asimp1 (N1 n) = N1 n\" |\n\"asimp1 (V1 x) = V1 x\" |\n\"asimp1 (Plus1 a\\<^sub>1 a\\<^sub>2) = plus1 (asimp1 a\\<^sub>1) (asimp1 a\\<^sub>2)\"|\n\"asimp1 (Times a\\<^sub>1 a\\<^sub>2) = mult (asimp1 a\\<^sub>1) (asimp1 a\\<^sub>2)\"   \n\n\nlemma aval1_plus[simp]:\n  \"aval1 (plus1 a1 a2) s = aval1 a1 s + aval1 a2 s\"\napply(induction a1 a2 rule: plus1.induct)\napply simp_all (* just for a change from auto *)\ndone\n\nlemma aval1_mult[simp]:\n  \"aval1 (mult a1 a2) s = aval1 a1 s * aval1 a2 s\"\n  apply (induction a1 a2 rule: mult.induct)\n  apply simp_all\n  done  \n\ntheorem aval1_asimp[simp]:\n  \"aval1 (asimp1 a) s = aval1 a s\"\napply(induction a)\napply auto\ndone  \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 | PostInc vname \n                        |  Times2 aexp2 aexp2 | Div2 aexp2 aexp2 \nfun aval2 :: \"aexp2 \\<Rightarrow> state \\<Rightarrow> (val \\<times> state)\" where\n  \"aval2 (N2 a) s = (a,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) \n  + (snd (aval2 b s) x) - (s x)))\" |\n  \"aval2 (PostInc x) s = (s x, s(x:= 1 + s x))\" |\n  \"aval2 (Times2 a b) s = (fst (aval2 a s) * fst (aval2 b s),(\\<lambda> x. (snd (aval2 a s) x) \n  + (snd (aval2 b s) x) - (s x)))\" |  \n  \"aval2 (Div2 a b) s = (fst (aval2 a s) div fst (aval2 b s),(\\<lambda> x. (snd (aval2 a s) x) \n  + (snd (aval2 b s) x) - (s x)))\"\n  \n  \nvalue \"aval2 (Div2 (N2 9) (N2 3))  (\\<lambda> x. 0) \"\nvalue \"aval2 (PostInc u)  (\\<lambda> x. 0) \"\n\n  \ntext{*\n\\endexercise\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)\"}.\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\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 x e1 e2) s = lval e2 (s(x:= lval e1 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 x e1 e2) = subst x (inline e1) (inline e2)\"\n  \n    \nlemma \"aval (inline e) s = lval e s\"\n  apply (induction e arbitrary: s)\n  apply auto    \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  \n  \ntext{*\nand prove that they do what they are supposed to:\n*}\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  \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 e1 e2 e3) s = (if (ifval e1 s) then (ifval e2 s) else (ifval e3 s))\" |\n  \"ifval (Less2 e1 e2) s = (aval e1 s < aval e2 s)\"\n\ntext{* Then define two translation functions *}\n\nfun b2ifexp :: \"bexp \\<Rightarrow> ifexp\" where\n  \"b2ifexp (Bc b) = Bc2 b\" |\n  \"b2ifexp (Not e) = If (b2ifexp e) (Bc2 False) (Bc2 True)\" |\n  \"b2ifexp (And e1 e2) = If (b2ifexp e1) (b2ifexp e2) (Bc2 False)\" |\n  \"b2ifexp (Less e1 e2) = (Less2 e1 e2)\"\n\nfun if2bexp :: \"ifexp \\<Rightarrow> bexp\" where\n  \"if2bexp (Bc2 b) = Bc b\" |\n  \"if2bexp (If e1 e2 e3) = And (Not (And (if2bexp e1) (Not (if2bexp e2)))) \n                            (Not (And (Not (if2bexp e1)) (Not (if2bexp e3))))\" |\n  \"if2bexp (Less2 e1 e2) = Less e1 e2\"\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  \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 e) = False\" |\n \"is_nnf (AND e1 e2) = (is_nnf e1 \\<and> is_nnf e2)\" |\n \"is_nnf (OR e1 e2) = (is_nnf e1 \\<and> is_nnf e2)\"\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 e)) = nnf e\" |\n  \"nnf (AND e1 e2) = AND (nnf e1) (nnf e2)\" |\n  \"nnf (OR e1 e2) = OR (nnf e1) (nnf e2)\" |\n  \"nnf (NOT (AND e1 e2)) = OR (nnf (NOT e1)) (nnf (NOT e2))\" |\n  \"nnf (NOT (OR e1 e2)) = AND (nnf (NOT e1)) (nnf (NOT e2))\"\n\ntext{*\nProve that @{const nnf} does what it is supposed to do:\n*}\n\nlemma neg_aux [simp] : \"pbval (nnf (NOT e)) s = (\\<not> (pbval (nnf e) s))\"\n  apply (induction e)\n  apply auto  \n  done\n  \nlemma pbval_nnf: \"pbval (nnf e) s = pbval e s\"\n  apply (induction e)\n  apply auto  \n  done  \n  \nlemma is_nnf_nnf: \"is_nnf (nnf e)\"\n  apply (induction e 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 not_OR :: \"pbexp \\<Rightarrow> bool\" where\n  \"not_OR (OR e1 e2) = False\" |\n  \"not_OR (AND e1 e2) = (not_OR e1 \\<and> not_OR e2)\" |\n  \"not_OR e = True\"\n  \n  \nfun is_dnf :: \"pbexp \\<Rightarrow> bool\" where\n  \"is_dnf (VAR x) = True\" |\n  \"is_dnf (NOT e) = True\" |\n  \"is_dnf (AND e1 e2) = ((not_OR e1) \\<and> (not_OR e2))\" |\n  \"is_dnf (OR e1 e2) = ((is_dnf e1) \\<and> (is_dnf e2))\"\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 e (OR e1 e2) = OR (dist_AND e e1) (dist_AND e e2)\" |\n  \"dist_AND (OR e1 e2) e = OR (dist_AND e1 e) (dist_AND e2 e)\" |\n  \"dist_AND e1 e2 = AND e1 e2\"\n\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 e) = NOT e\" |\n  \"dnf_of_nnf (OR e1 e2) = OR (dnf_of_nnf e1) (dnf_of_nnf e2)\" |\n  \"dnf_of_nnf (AND e1 e2) = dist_AND (dnf_of_nnf e1) (dnf_of_nnf e2)\"\n  \ntext {* Prove the correctness of your function: *}\n\nlemma \"pbval (dnf_of_nnf b) s = pbval b s\"\n  apply (induction b arbitrary: s)\n  apply (auto simp add:)\n  done\n\n    \nlemma [simp]: \"is_dnf e1 \\<Longrightarrow> is_dnf e2 \\<Longrightarrow> is_dnf (dist_AND e1 e2)\"\n  apply (induction e1 e2 rule: dist_AND.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\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 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\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  \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*}\n\ntype_synonym reg = nat\ndatatype instr = LDI val reg | LD vname reg | ADD reg reg\n\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 n r) s rs = rs(r:=n)\" |\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\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 [] s rs = rs\" |\n  \"exec (x # xs) s rs = exec xs s (exec1 x 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 e1 e2) r = (comp' e1 r) @ (comp' e2 (r+1)) @ [ADD r (r+1)]\" \n\n\nlemma [simp]: \"exec (xs @ ys) s rs = exec ys s (exec xs s rs)\"\napply (induction xs arbitrary: rs)\napply (auto)\ndone\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\ntheorem \"exec (comp' a r) s rs r = aval a s\"\n  apply (induction a arbitrary: rs r)\n  apply auto  \n  done\n    \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 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 0)+(rs r))\"\n\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 [] s rs = rs\" |\n\"exec0 (x # xs) s rs = exec0 xs s (exec01 x s rs)\"\n\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\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: rs r q)\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": "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/Chapter3.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8056321889812554, "lm_q2_score": 0.9124361604769414, "lm_q1q2_score": 0.7350879412706904}}
{"text": "(* Author: Amine Chaieb, TU Muenchen *)\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  using complex_mod_triangle_ineq2[of \"w + z\" \"-z\"] by auto\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> norm c + r * m\"\n      using mult_mono[OF H th rp norm_ge_zero[of \"poly cs z\"]]\n      by (simp add: norm_mult)\n    also have \"\\<dots> \\<le> ?k\"\n      by simp\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: \"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  apply (induct p)\n  apply (simp add: offset_poly_0)\n  apply (simp add: offset_poly_pCons algebra_simps)\n  done\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: \"offset_poly p h = 0 \\<longleftrightarrow> p = 0\"\n  apply (safe intro!: offset_poly_0)\n  apply (induct p)\n  apply simp\n  apply (simp add: offset_poly_pCons)\n  apply (frule offset_poly_eq_0_lemma, simp)\n  done\n\nlemma degree_offset_poly: \"degree (offset_poly p h) = degree p\"\n  apply (induct p)\n  apply (simp add: offset_poly_0)\n  apply (case_tac \"p = 0\")\n  apply (simp add: offset_poly_0 offset_poly_pCons)\n  apply (simp add: offset_poly_pCons)\n  apply (subst degree_add_eq_right)\n  apply (rule le_less_trans [OF degree_smult_le])\n  apply (simp add: offset_poly_eq_0_iff)\n  apply (simp add: offset_poly_eq_0_iff)\n  done\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))\"\nproof (intro exI conjI)\n  show \"psize (offset_poly p a) = psize p\"\n    unfolding psize_def\n    by (simp add: offset_poly_eq_0_iff degree_offset_poly)\n  show \"\\<forall>x. poly (offset_poly p a) x = poly p (a + x)\"\n    by (simp add: poly_offset_poly)\nqed\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 - (rule power_mono, simp, simp)+\n    then have th0: \"4 * x\\<^sup>2 \\<le> 1\" \"4 * y\\<^sup>2 \\<le> 1\"\n      by (simp_all add: power_mult_distrib)\n    from add_mono[OF th0] xy show ?thesis\n      by simp\n  qed\n  then show ?thesis\n    unfolding linorder_not_le[symmetric] by blast\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 have \"\\<exists>m. n = 2 * m\"\n      by presburger\n    then obtain m where m: \"n = 2 * m\"\n      by blast\n    from n m have \"m \\<noteq> 0\" \"m < n\"\n      by presburger+\n    with IH[rule_format, of m] 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 th0: \"cmod (complex_of_real (cmod b) / b) = 1\"\n      using b by (simp add: norm_divide)\n    from unimodular_reduce_norm[OF th0] \\<open>odd n\\<close>\n    have \"\\<exists>v. cmod (complex_of_real (cmod b) / b + v^n) < 1\"\n      apply (cases \"cmod (complex_of_real (cmod b) / b + 1) < 1\")\n      apply (rule_tac x=\"1\" in exI)\n      apply simp\n      apply (cases \"cmod (complex_of_real (cmod b) / b - 1) < 1\")\n      apply (rule_tac x=\"-1\" in exI)\n      apply simp\n      apply (cases \"cmod (complex_of_real (cmod b) / b + \\<i>) < 1\")\n      apply (cases \"even m\")\n      apply (rule_tac x=\"\\<i>\" in exI)\n      apply (simp add: m power_mult)\n      apply (rule_tac x=\"- \\<i>\" in exI)\n      apply (simp add: m power_mult)\n      apply (cases \"even m\")\n      apply (rule_tac x=\"- \\<i>\" in exI)\n      apply (simp add: m power_mult)\n      apply (auto simp add: m power_mult)\n      apply (rule_tac x=\"\\<i>\" in exI)\n      apply (auto simp add: m power_mult)\n      done\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 th1: \"?w ^ n = v^n / complex_of_real (cmod b)\"\n      by (simp add: power_divide of_real_power[symmetric])\n    have th2:\"cmod (complex_of_real (cmod b) / b) = 1\"\n      using b by (simp add: norm_divide)\n    then have th3: \"cmod (complex_of_real (cmod b) / b) \\<ge> 0\"\n      by simp\n    have th4: \"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: th2)\n      done\n    from mult_left_less_imp_less[OF th4 th3]\n    have \"?P ?w n\" unfolding th1 .\n    then show ?thesis ..\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. subseq f \\<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: \"subseq 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: \"subseq g\" \"monoseq (\\<lambda>n. Im (s (f (g n))))\"\n    unfolding o_def by blast\n  let ?h = \"f \\<circ> g\"\n  from r[rule_format, of 0] have rp: \"r \\<ge> 0\"\n    using norm_ge_zero[of \"s 0\"] by arith\n  have th: \"\\<forall>n. r + 1 \\<ge> \\<bar>Re (s n)\\<bar>\"\n  proof\n    fix n\n    from abs_Re_le_cmod[of \"s n\"] r[rule_format, of n]\n    show \"\\<bar>Re (s n)\\<bar> \\<le> r + 1\" by arith\n  qed\n  have conv1: \"convergent (\\<lambda>n. Re (s (f n)))\"\n    apply (rule Bseq_monoseq_convergent)\n    apply (simp add: Bseq_def)\n    apply (metis gt_ex le_less_linear less_trans order.trans th)\n    apply (rule f(2))\n    done\n  have th: \"\\<forall>n. r + 1 \\<ge> \\<bar>Im (s n)\\<bar>\"\n  proof\n    fix n\n    from abs_Im_le_cmod[of \"s n\"] r[rule_format, of n]\n    show \"\\<bar>Im (s n)\\<bar> \\<le> r + 1\"\n      by arith\n  qed\n\n  have conv2: \"convergent (\\<lambda>n. Im (s (f (g n))))\"\n    apply (rule Bseq_monoseq_convergent)\n    apply (simp add: Bseq_def)\n    apply (metis gt_ex le_less_linear less_trans order.trans th)\n    apply (rule g(2))\n    done\n\n  from conv1[unfolded convergent_def] obtain x where \"LIMSEQ (\\<lambda>n. Re (s (f n))) x\"\n    by blast\n  then have x: \"\\<forall>r>0. \\<exists>n0. \\<forall>n\\<ge>n0. \\<bar>Re (s (f n)) - x\\<bar> < r\"\n    unfolding LIMSEQ_iff real_norm_def .\n\n  from conv2[unfolded convergent_def] obtain y where \"LIMSEQ (\\<lambda>n. Im (s (f (g n)))) y\"\n    by blast\n  then have y: \"\\<forall>r>0. \\<exists>n0. \\<forall>n\\<ge>n0. \\<bar>Im (s (f (g n))) - y\\<bar> < r\"\n    unfolding LIMSEQ_iff real_norm_def .\n  let ?w = \"Complex x y\"\n  from f(1) g(1) have hs: \"subseq ?h\"\n    unfolding subseq_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[rule_format, OF e2] y[rule_format, OF 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      from add_strict_mono[OF N1[rule_format, OF nN1] N2[rule_format, OF nN2]]\n      show ?thesis\n        using metric_bound_lemma[of \"s (f (g n))\" ?w] by simp\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 q: \"degree q = degree p\" \"poly q x = poly p (z + x)\" for x\n  proof\n    show \"degree (offset_poly p z) = degree p\"\n      by (rule degree_offset_poly)\n    show \"\\<And>x. poly (offset_poly p z) x = poly p (z + x)\"\n      by (rule poly_offset_poly)\n  qed\n  have th: \"\\<And>w. poly q (w - z) = poly p w\"\n    using q(2)[of \"w - z\" for w] by simp\n  show ?thesis unfolding th[symmetric]\n  proof (induct q)\n    case 0\n    then show ?case\n      using ep by auto\n  next\n    case (pCons c cs)\n    from poly_bound_exists[of 1 \"cs\"]\n    obtain m where m: \"m > 0\" \"norm z \\<le> 1 \\<Longrightarrow> norm (poly cs z) \\<le> m\" for z\n      by blast\n    from ep m(1) have em0: \"e/m > 0\"\n      by (simp add: field_simps)\n    have one0: \"1 > (0::real)\"\n      by arith\n    from real_lbound_gt_zero[OF one0 em0]\n    obtain d where d: \"d > 0\" \"d < 1\" \"d < e / m\"\n      by blast\n    from d(1,3) m(1) have dm: \"d * m > 0\" \"d * m < e\"\n      by (simp_all add: field_simps)\n    show ?case\n    proof (rule ex_forward[OF real_lbound_gt_zero[OF one0 em0]], clarsimp simp add: norm_mult)\n      fix d w\n      assume H: \"d > 0\" \"d < 1\" \"d < e/m\" \"w \\<noteq> z\" \"norm (w - z) < d\"\n      then have d1: \"norm (w-z) \\<le> 1\" \"d \\<ge> 0\"\n        by simp_all\n      from H(3) m(1) have dme: \"d*m < e\"\n        by (simp add: field_simps)\n      from H have th: \"norm (w - z) \\<le> d\"\n        by simp\n      from mult_mono[OF th m(2)[OF d1(1)] d1(2) norm_ge_zero] dme\n      show \"norm (w - z) * norm (poly cs (w - z)) < e\"\n        by simp\n    qed\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 \"cmod 0 \\<le> r \\<and> cmod (poly p 0) = - (- cmod (poly p 0))\"\n      by simp\n    then have mth1: \"\\<exists>x z. cmod z \\<le> r \\<and> cmod (poly p z) = - x\"\n      by blast\n    have False if \"cmod z \\<le> r\" \"cmod (poly p z) = - x\" \"\\<not> x < 1\" for x z\n    proof -\n      from that have \"- x < 0 \"\n        by arith\n      with that(2) norm_ge_zero[of \"poly p z\"] show ?thesis\n        by simp\n    qed\n    then have mth2: \"\\<exists>z. \\<forall>x. (\\<exists>z. cmod z \\<le> r \\<and> cmod (poly p z) = - x) \\<longrightarrow> x < z\"\n      by blast\n    from real_sup_exists[OF mth1 mth2] obtain s where\n      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 blast\n    let ?m = \"- s\"\n    have s1[unfolded minus_minus]:\n      \"(\\<exists>z x. cmod z \\<le> r \\<and> - (- cmod (poly p z)) < y) \\<longleftrightarrow> ?m < y\" for y\n      using s[rule_format, of \"-y\"]\n      unfolding minus_less_iff[of y] equation_minus_iff by blast\n    from s1[of ?m] have s1m: \"\\<And>z x. cmod z \\<le> r \\<Longrightarrow> cmod (poly p z) \\<ge> ?m\"\n      by auto\n    have \"\\<exists>z. cmod z \\<le> r \\<and> cmod (poly p z) < - s + 1 / real (Suc n)\" for n\n      using s1[rule_format, of \"?m + 1/real (Suc n)\"] by simp\n    then have th: \"\\<forall>n. \\<exists>z. cmod z \\<le> r \\<and> cmod (poly p z) < - s + 1 / real (Suc n)\" ..\n    from choice[OF th] obtain g where\n        g: \"\\<forall>n. cmod (g n) \\<le> r\" \"\\<forall>n. cmod (poly p (g n)) <?m + 1 /real(Suc n)\"\n      by blast\n    from bolzano_weierstrass_complex_disc[OF g(1)]\n    obtain f z where fz: \"subseq 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        from poly_cont[OF e2, of z p] obtain d where\n            d: \"d > 0\" \"\\<forall>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 th1: \"cmod(poly p w - poly p z) < ?e / 2\" if w: \"cmod (w - z) < d\" for w\n          using d(2)[rule_format, of w] w e by (cases \"w = z\") simp_all\n        from fz(2) d(1) obtain N1 where N1: \"\\<forall>n\\<ge>N1. cmod (g (f n) - z) < d\"\n          by blast\n        from reals_Archimedean2[of \"2/?e\"] obtain N2 :: nat where N2: \"2/?e < real N2\"\n          by blast\n        have th2: \"cmod (poly p (g (f (N1 + N2))) - poly p z) < ?e/2\"\n          using N1[rule_format, of \"N1 + N2\"] th1 by simp\n        have th0: \"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        have ath: \"m \\<le> x \\<Longrightarrow> x < m + e \\<Longrightarrow> \\<bar>x - m\\<bar> < e\" for m x e :: real\n          by arith\n        from s1m[OF g(1)[rule_format]] have th31: \"?m \\<le> cmod(poly p (g (f (N1 + N2))))\" .\n        from seq_suble[OF fz(1), of \"N1 + N2\"]\n        have th00: \"real (Suc (N1 + N2)) \\<le> real (Suc (f (N1 + N2)))\"\n          by simp\n        have th000: \"0 \\<le> (1::real)\" \"(1::real) \\<le> 1\" \"real (Suc (N1 + N2)) > 0\"\n          using N2 by auto\n        from frac_le[OF th000 th00]\n        have th00: \"?m + 1 / real (Suc (f (N1 + N2))) \\<le> ?m + 1 / real (Suc (N1 + N2))\"\n          by simp\n        from g(2)[rule_format, of \"f (N1 + N2)\"]\n        have th01:\"cmod (poly p (g (f (N1 + N2)))) < - s + 1 / real (Suc (f (N1 + N2)))\" .\n        from order_less_le_trans[OF th01 th00]\n        have th32: \"cmod (poly p (g (f (N1 + N2)))) < ?m + (1/ real(Suc (N1 + N2)))\" .\n        from N2 have \"2/?e < real (Suc (N1 + N2))\"\n          by arith\n        with 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 ath[OF th31 th32] have thc1: \"\\<bar>cmod (poly p (g (f (N1 + N2)))) - ?m\\<bar> < ?e/2\"\n          by arith\n        have ath2: \"\\<bar>a - b\\<bar> \\<le> c \\<Longrightarrow> \\<bar>b - m\\<bar> \\<le> \\<bar>a - m\\<bar> + c\" for a b c m :: real\n          by arith\n        have th22: \"\\<bar>cmod (poly p (g (f (N1 + N2)))) - cmod (poly p z)\\<bar> \\<le>\n            cmod (poly p (g (f (N1 + N2))) - poly p z)\"\n          by (simp add: norm_triangle_ineq3)\n        from ath2[OF th22, of ?m]\n        have thc2: \"2 * (?e/2) \\<le>\n            \\<bar>cmod(poly p (g (f (N1 + N2)))) - ?m\\<bar> + cmod (poly p (g (f (N1 + N2))) - poly p z)\"\n          by simp\n        from th0[OF th2 thc1 thc2] have False .\n      }\n      then have \"?e = 0\"\n        by auto\n      then have \"cmod (poly p z) = ?m\"\n        by simp\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 r0: \"r \\<le> norm z\"\n        using that by arith\n      from r[rule_format, OF r0] have th0: \"d + norm a \\<le> 1 * norm(poly (pCons c cs) z)\"\n        by arith\n      from that have z1: \"norm z \\<ge> 1\"\n        by arith\n      from order_trans[OF th0 mult_right_mono[OF z1 norm_ge_zero[of \"poly (pCons c cs) z\"]]]\n      have th1: \"d \\<le> norm(z * poly (pCons c cs) z) - norm a\"\n        unfolding norm_mult by (simp add: algebra_simps)\n      from norm_diff_ineq[of \"z * poly (pCons c cs) z\" a]\n      have th2: \"norm (z * poly (pCons c cs) z) - norm a \\<le> norm (poly (pCons a (pCons c cs)) z)\"\n        by (simp add: algebra_simps)\n      from th1 th2 show ?thesis\n        by arith\n    qed\n    then show ?thesis by blast\n  next\n    case True\n    with pCons.prems have c0: \"c \\<noteq> 0\"\n      by simp\n    have \"d \\<le> norm (poly (pCons a (pCons c cs)) z)\"\n      if h: \"(\\<bar>d\\<bar> + norm a) / norm c \\<le> norm z\" for z :: 'a\n    proof -\n      from c0 have \"norm c > 0\"\n        by simp\n      from h c0 have th0: \"\\<bar>d\\<bar> + norm a \\<le> norm (z * c)\"\n        by (simp add: field_simps norm_mult)\n      have ath: \"\\<And>mzh mazh ma. mzh \\<le> mazh + ma \\<Longrightarrow> \\<bar>d\\<bar> + ma \\<le> mzh \\<Longrightarrow> d \\<le> mazh\"\n        by arith\n      from norm_diff_ineq[of \"z * c\" a] have th1: \"norm (z * c) \\<le> norm (a + z * c) + norm a\"\n        by (simp add: algebra_simps)\n      from ath[OF th1 th0] show ?thesis\n        using True by simp\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    have ath: \"\\<And>z r. r \\<le> cmod z \\<or> cmod z \\<le> \\<bar>r\\<bar>\"\n      by arith\n    from poly_minimum_modulus_disc[of \"\\<bar>r\\<bar>\" \"pCons c cs\"]\n    obtain v where v: \"cmod (poly (pCons c cs) v) \\<le> cmod (poly (pCons c cs) w)\"\n      if \"cmod w \\<le> \\<bar>r\\<bar>\" for w\n      by blast\n    have \"cmod (poly (pCons c cs) v) \\<le> cmod (poly (pCons c cs) z)\" if z: \"r \\<le> cmod z\" for z\n      using v[of 0] r[OF z] by simp\n    with v ath[of r] show ?thesis\n      by blast\n  next\n    case True\n    with pCons.hyps show ?thesis\n      by simp\n  qed\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  next\n    case False\n    show ?thesis\n      apply (rule exI[where x=0])\n      apply (rule exI[where x=c])\n      apply (auto simp: False)\n      done\n  qed\nqed\n\nlemma poly_decompose:\n  assumes nc: \"\\<not> constant (poly p)\"\n  shows \"\\<exists>k a q. a \\<noteq> (0::'a::idom) \\<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  proof\n    assume \"\\<forall>z. z \\<noteq> 0 \\<longrightarrow> poly cs z = 0\"\n    then have \"poly (pCons c cs) x = poly (pCons c cs) y\" for x y\n      by (cases \"x = 0\") auto\n    with pCons.prems show False\n      by (auto simp add: constant_def)\n  qed\n  from poly_decompose_lemma[OF this]\n  show ?case\n    apply clarsimp\n    apply (rule_tac x=\"k+1\" in exI)\n    apply (rule_tac x=\"a\" in exI)\n    apply simp\n    apply (rule_tac x=\"q\" in exI)\n    apply (auto simp add: psize_def split: if_splits)\n    done\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    from poly_offset[of p c] obtain q where q: \"psize q = psize p\" \"\\<forall>x. poly q x = ?p (c + x)\"\n      by blast\n    have False if h: \"constant (poly q)\"\n    proof -\n      from q(2) have th: \"\\<forall>x. poly q (x - c) = ?p x\"\n        by auto\n      have \"?p x = ?p y\" for x y\n      proof -\n        from th have \"?p x = poly q (x - c)\"\n          by auto\n        also have \"\\<dots> = poly q (y - c)\"\n          using h unfolding constant_def by blast\n        also have \"\\<dots> = ?p y\"\n          using th by auto\n        finally show ?thesis .\n      qed\n      with less(2) show ?thesis\n        unfolding constant_def by blast\n    qed\n    then have qnc: \"\\<not> constant (poly q)\"\n      by blast\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      using a00\n      unfolding psize_def degree_def\n      by (simp add: poly_eq_iff)\n    have False if h: \"\\<And>x y. poly ?r x = poly ?r y\"\n    proof -\n      have \"poly q x = poly q y\" for x y\n      proof -\n        from qr[rule_format, of x] have \"poly q x = poly ?r x * ?a0\"\n          by auto\n        also have \"\\<dots> = poly ?r y * ?a0\"\n          using h by simp\n        also have \"\\<dots> = poly q y\"\n          using qr[rule_format, of y] by simp\n        finally show ?thesis .\n      qed\n      with qnc show ?thesis\n        unfolding constant_def by blast\n    qed\n    then have rnc: \"\\<not> constant (poly ?r)\"\n      unfolding constant_def by blast\n    from qr[rule_format, of 0] a00 have r01: \"poly ?r 0 = 1\"\n      by auto\n    have mrmq_eq: \"cmod (poly ?r w) < 1 \\<longleftrightarrow> cmod (poly q w) < cmod ?a0\" for w\n    proof -\n      have \"cmod (poly ?r w) < 1 \\<longleftrightarrow> cmod (poly q w / ?a0) < 1\"\n        using qr[rule_format, of w] a00 by (simp add: divide_inverse ac_simps)\n      also have \"\\<dots> \\<longleftrightarrow> cmod (poly q w) < cmod ?a0\"\n        using a00 unfolding norm_divide by (simp add: field_simps)\n      finally show ?thesis .\n    qed\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(3) lgqr[symmetric] q(1) have s0: \"s = 0\"\n        by auto\n      have hth[symmetric]: \"cmod (poly ?r w) = cmod (1 + a * w ^ k)\" for w\n        using kas(4)[rule_format, of w] s0 r01 by (simp add: algebra_simps)\n      from reduce_poly_simple[OF kas(1,2)] show ?thesis\n        unfolding hth by blast\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 th01: \"\\<not> constant (poly (pCons 1 (monom a (k - 1))))\"\n        unfolding constant_def poly_pCons poly_monom\n        using kas(1)\n        apply simp\n        apply (rule exI[where x=0])\n        apply (rule exI[where x=1])\n        apply simp\n        done\n      from kas(1) kas(2) have th02: \"k + 1 = psize (pCons 1 (monom a (k - 1)))\"\n        by (simp add: psize_def degree_monom_eq)\n      from less(1) [OF k1n [simplified th02] th01]\n      obtain w where w: \"1 + w^k * a = 0\"\n        unfolding poly_pCons poly_monom\n        using kas(2) by (cases k) (auto simp add: algebra_simps)\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 w0: \"w \\<noteq> 0\"\n        using kas(2) w by (auto simp add: power_0_left)\n      from w have \"(1 + w ^ k * a) - 1 = 0 - 1\"\n        by simp\n      then have wm1: \"w^k * a = - 1\"\n        by simp\n      have inv0: \"0 < inverse (cmod w ^ (k + 1) * m)\"\n        using norm_ge_zero[of w] w0 m(1)\n        by (simp add: inverse_eq_divide zero_less_mult_iff)\n      with real_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 th11: \"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 \"t * cmod w \\<le> 1 * cmod w\"\n        apply (rule mult_mono)\n        using t(1,2)\n        apply auto\n        done\n      then have tw: \"cmod ?w \\<le> cmod w\"\n        using t(1) by (simp add: norm_mult)\n      from t inv0 have \"t * (cmod w ^ (k + 1) * m) < 1\"\n        by (simp add: field_simps)\n      with zero_less_power[OF t(1), of k] have th30: \"t^k * (t* (cmod w ^ (k + 1) * m)) < t^k * 1\"\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 w0 t(1)\n        by (simp add: algebra_simps power_mult_distrib norm_power norm_mult)\n      then have \"cmod (?w^k * ?w * poly s ?w) \\<le> t^k * (t* (cmod w ^ (k + 1) * m))\"\n        using t(1,2) m(2)[rule_format, OF tw] w0\n        by auto\n      with th30 have th120: \"cmod (?w^k * ?w * poly s ?w) < t^k\"\n        by simp\n      from power_strict_mono[OF t(2), of k] t(1) kas(2) have th121: \"t^k \\<le> 1\"\n        by auto\n      from ath[OF norm_ge_zero[of \"?w^k * ?w * poly s ?w\"] th120 th121]\n      have th12: \"\\<bar>1 - t^k\\<bar> + cmod (?w^k * ?w * poly s ?w) < 1\" .\n      from th11 th12 have \"cmod (1 + ?w^k * (a + ?w * poly s ?w)) < 1\"\n        by arith\n      then have \"cmod (poly ?r ?w) < 1\"\n        unfolding kas(4)[rule_format, of ?w] r01 by simp\n      then show ?thesis\n        by blast\n    qed\n    with cq0 q(2) show ?thesis\n      unfolding mrmq_eq not_less[symmetric] by auto\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)\"\n  using nc\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    then show ?thesis by auto\n  next\n    case False\n    have \"\\<not> constant (poly (pCons c cs))\"\n    proof\n      assume nc: \"constant (poly (pCons c cs))\"\n      from nc[unfolded constant_def, rule_format, of 0]\n      have \"\\<forall>w. w \\<noteq> 0 \\<longrightarrow> poly cs w = 0\" by auto\n      then have \"cs = 0\"\n      proof (induct cs)\n        case 0\n        then show ?case by simp\n      next\n        case (pCons d ds)\n        show ?case\n        proof (cases \"d = 0\")\n          case True\n          then show ?thesis\n            using pCons.prems pCons.hyps by simp\n        next\n          case False\n          from poly_bound_exists[of 1 ds] obtain m where\n            m: \"m > 0\" \"\\<forall>z. \\<forall>z. cmod z \\<le> 1 \\<longrightarrow> cmod (poly ds z) \\<le> m\" by blast\n          have dm: \"cmod d / m > 0\"\n            using False m(1) by (simp add: field_simps)\n          from real_lbound_gt_zero[OF dm zero_less_one]\n          obtain x where x: \"x > 0\" \"x < cmod d / m\" \"x < 1\"\n            by blast\n          let ?x = \"complex_of_real x\"\n          from x have cx: \"?x \\<noteq> 0\" \"cmod ?x \\<le> 1\"\n            by simp_all\n          from pCons.prems[rule_format, OF cx(1)]\n          have cth: \"cmod (?x*poly ds ?x) = cmod d\"\n            by (simp add: eq_diff_eq[symmetric])\n          from m(2)[rule_format, OF cx(2)] x(1)\n          have th0: \"cmod (?x*poly ds ?x) \\<le> x*m\"\n            by (simp add: norm_mult)\n          from x(2) m(1) have \"x * m < cmod d\"\n            by (simp add: field_simps)\n          with th0 have \"cmod (?x*poly ds ?x) \\<noteq> cmod d\"\n            by auto\n          with cth show ?thesis\n            by blast\n        qed\n      qed\n      then show False\n        using pCons.prems False by blast\n    qed\n    then show ?thesis\n      by (rule fundamental_theorem_of_algebra)\n  qed\nqed\n\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 = p * ?w\"\n            apply (subst r)\n            apply (subst s)\n            apply (subst kpn)\n            using k oop [of a]\n            apply (subst power_mult_distrib)\n            apply simp\n            apply (subst power_add [symmetric])\n            apply simp\n            done\n          then 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            apply auto\n            apply (erule ssubst)\n            apply (simp add: degree_mult_eq degree_linear_power)\n            done\n          have \"poly r x = 0\" if h: \"poly s x = 0\" for x\n          proof -\n            have xa: \"x \\<noteq> a\"\n            proof\n              assume \"x = a\"\n              from h[unfolded this poly_eq_0_iff_dvd] obtain u where u: \"s = [:- a, 1:] * u\"\n                by (rule dvdE)\n              have \"p = [:- a, 1:] ^ (Suc ?op) * u\"\n                apply (subst s)\n                apply (subst u)\n                apply (simp only: power_Suc ac_simps)\n                done\n              with ap(2)[unfolded dvd_def] show False\n                by blast\n            qed\n            from h have \"poly p x = 0\"\n              by (subst s) simp\n            with pq0 have \"poly q x = 0\"\n              by blast\n            with r xa show ?thesis\n              by auto\n          qed\n          with IH[rule_format, OF dsn, of s r] False have \"s dvd (r ^ (degree s))\"\n            by blast\n          then obtain u where u: \"r ^ (degree s) = s * u\" ..\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          let ?w = \"(u * ([:-a,1:] ^ (n - ?op))) * (r ^ (n - degree s))\"\n          from oop[of a] dsn have \"q ^ n = p * ?w\"\n            apply -\n            apply (subst s)\n            apply (subst r)\n            apply (simp only: power_mult_distrib)\n            apply (subst mult.assoc [where b=s])\n            apply (subst mult.assoc [where a=u])\n            apply (subst mult.assoc [where b=u, symmetric])\n            apply (subst u [symmetric])\n            apply (simp add: ac_simps power_add [symmetric])\n            done\n          then show ?thesis\n            unfolding dvd_def by blast\n        qed\n      qed\n    qed\n    then show ?thesis\n      using a order_root pne by blast\n  next\n    case False\n    with fundamental_theorem_of_algebra_alt[of p]\n    obtain c where ccs: \"c \\<noteq> 0\" \"p = pCons c 0\"\n      by blast\n    then have pp: \"poly p x = c\" for x\n      by simp\n    let ?w = \"[:1/c:] * (q ^ n)\"\n    from ccs have \"(q ^ n) = (p * ?w)\"\n      by simp\n    then show ?thesis\n      unfolding dvd_def by blast\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 eq: \"(\\<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    {\n      assume \"p dvd (q ^ (degree p))\"\n      then obtain r where r: \"q ^ (degree p) = p * r\" ..\n      from r p have False by simp\n    }\n    with eq p show ?thesis by blast\n  next\n    case dp: 2\n    then obtain k where k: \"p = [:k:]\" \"k \\<noteq> 0\"\n      by (cases p) (simp split: if_splits)\n    then have th1: \"\\<forall>x. poly p x \\<noteq> 0\"\n      by simp\n    from k dp(2) have \"q ^ (degree p) = p * [:1/k:]\"\n      by (simp add: one_poly_def)\n    then have th2: \"p dvd (q ^ (degree p))\" ..\n    from dp(1) th1 th2 show ?thesis\n      by blast\n  next\n    case dp: 3\n    have False if dvd: \"p dvd (q ^ (Suc n))\" and h: \"poly p x = 0\" \"poly q x \\<noteq> 0\" for x\n    proof -\n      from dvd obtain u where u: \"q ^ (Suc n) = p * u\" ..\n      from h have \"poly (q ^ (Suc n)) x \\<noteq> 0\"\n        by simp\n      with u h(1) show ?thesis\n        by (simp only: poly_mult) simp\n    qed\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 th: \"poly p = poly [:poly p 0:]\"\n      by auto\n    then have \"p = [:poly p 0:]\"\n      by (simp add: poly_eq_poly_eq_iff)\n    then have \"degree p = degree [:poly p 0:]\"\n      by simp\n    then show ?thesis\n      by simp\n  qed\n  show ?lhs if ?rhs\n  proof -\n    from that obtain k where \"p = [:k:]\"\n      by (cases p) (simp split: if_splits)\n    then show ?thesis\n      unfolding constant_def by auto\n  qed\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)\"\nproof -\n  have \"pCons 0 q = q * [:0,1:]\" by simp\n  then have \"q dvd (pCons 0 q)\" ..\n  with pq show ?thesis by (rule dvd_trans)\nqed\n\nlemma poly_divides_conv0:\n  fixes p:: \"'a::field poly\"\n  assumes lgpq: \"degree q < degree p\"\n    and lq: \"p \\<noteq> 0\"\n  shows \"p dvd q \\<longleftrightarrow> q = 0\" (is \"?lhs \\<longleftrightarrow> ?rhs\")\nproof\n  assume ?rhs\n  then have \"q = p * 0\" by simp\n  then show ?lhs ..\nnext\n  assume l: ?lhs\n  show ?rhs\n  proof (cases \"q = 0\")\n    case True\n    then show ?thesis by simp\n  next\n    assume q0: \"q \\<noteq> 0\"\n    from l q0 have \"degree p \\<le> degree q\"\n      by (rule dvd_imp_degree_le)\n    with lgpq show ?thesis by simp\n  qed\nqed\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\" (is \"?lhs \\<longleftrightarrow> ?rhs\")\nproof\n  from pp' obtain t where t: \"p' = p * t\" ..\n  show ?rhs if ?lhs\n  proof -\n    from that obtain u where u: \"q = p * u\" ..\n    have \"r = p * (smult a u - t)\"\n      using u qrp' [symmetric] t by (simp add: algebra_simps)\n    then show ?thesis ..\n  qed\n  show ?lhs if ?rhs\n  proof -\n    from that obtain u where u: \"r = p * u\" ..\n    from u [symmetric] t qrp' [symmetric] a0\n    have \"q = p * smult (1/a) (u + t)\"\n      by (simp add: algebra_simps)\n    then show ?thesis ..\n  qed\nqed\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)\"\nproof -\n  have False if \"h \\<noteq> 0\" \"t = 0\" and \"pCons a (pCons b p) = pCons h t\" for h t\n    using l that by simp\n  then have th: \"\\<not> (\\<exists> h t. h \\<noteq> 0 \\<and> t = 0 \\<and> pCons a (pCons b p) = pCons h t)\"\n    by blast\n  from fundamental_theorem_of_algebra_alt[OF th] show ?thesis\n    by auto\nqed\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)\"\nproof -\n  from l have dp: \"degree (pCons a p) = psize p\"\n    by (simp add: psize_def)\n  from nullstellensatz_univariate[of \"pCons a p\" q] l\n  show ?thesis\n    by (metis dp pCons_eq_0_iff)\nqed\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\"\nproof -\n  from h have \"poly (q ^ n) = poly r\"\n    by auto\n  then have \"(q ^ n) = r\"\n    by (simp add: poly_eq_poly_eq_iff)\n  then show \"p dvd (q ^ n) \\<longleftrightarrow> p dvd r\"\n    by simp\nqed\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": "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/Fundamental_Theorem_Algebra.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8459424411924673, "lm_q2_score": 0.8688267762381844, "lm_q1q2_score": 0.7349774440643112}}
{"text": "(*  Title:      HOL/Isar_Examples/Group_Context.thy\n    Author:     Makarius\n*)\n\nsection \\<open>Some algebraic identities derived from group axioms -- theory context version\\<close>\n\ntheory Group_Context\n  imports MainRLT\nbegin\n\ntext \\<open>hypothetical group axiomatization\\<close>\n\ncontext\n  fixes prod :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a\"  (infixl \"\\<odot>\" 70)\n    and one :: \"'a\"\n    and inverse :: \"'a \\<Rightarrow> 'a\"\n  assumes assoc: \"(x \\<odot> y) \\<odot> z = x \\<odot> (y \\<odot> z)\"\n    and left_one: \"one \\<odot> x = x\"\n    and left_inverse: \"inverse x \\<odot> x = one\"\nbegin\n\ntext \\<open>some consequences\\<close>\n\nlemma right_inverse: \"x \\<odot> inverse x = one\"\nproof -\n  have \"x \\<odot> inverse x = one \\<odot> (x \\<odot> inverse x)\"\n    by (simp only: left_one)\n  also have \"\\<dots> = one \\<odot> x \\<odot> inverse x\"\n    by (simp only: assoc)\n  also have \"\\<dots> = inverse (inverse x) \\<odot> inverse x \\<odot> x \\<odot> inverse x\"\n    by (simp only: left_inverse)\n  also have \"\\<dots> = inverse (inverse x) \\<odot> (inverse x \\<odot> x) \\<odot> inverse x\"\n    by (simp only: assoc)\n  also have \"\\<dots> = inverse (inverse x) \\<odot> one \\<odot> inverse x\"\n    by (simp only: left_inverse)\n  also have \"\\<dots> = inverse (inverse x) \\<odot> (one \\<odot> inverse x)\"\n    by (simp only: assoc)\n  also have \"\\<dots> = inverse (inverse x) \\<odot> inverse x\"\n    by (simp only: left_one)\n  also have \"\\<dots> = one\"\n    by (simp only: left_inverse)\n  finally show ?thesis .\nqed\n\nlemma right_one: \"x \\<odot> one = x\"\nproof -\n  have \"x \\<odot> one = x \\<odot> (inverse x \\<odot> x)\"\n    by (simp only: left_inverse)\n  also have \"\\<dots> = x \\<odot> inverse x \\<odot> x\"\n    by (simp only: assoc)\n  also have \"\\<dots> = one \\<odot> x\"\n    by (simp only: right_inverse)\n  also have \"\\<dots> = x\"\n    by (simp only: left_one)\n  finally show ?thesis .\nqed\n\nlemma one_equality:\n  assumes eq: \"e \\<odot> x = x\"\n  shows \"one = e\"\nproof -\n  have \"one = x \\<odot> inverse x\"\n    by (simp only: right_inverse)\n  also have \"\\<dots> = (e \\<odot> x) \\<odot> inverse x\"\n    by (simp only: eq)\n  also have \"\\<dots> = e \\<odot> (x \\<odot> inverse x)\"\n    by (simp only: assoc)\n  also have \"\\<dots> = e \\<odot> one\"\n    by (simp only: right_inverse)\n  also have \"\\<dots> = e\"\n    by (simp only: right_one)\n  finally show ?thesis .\nqed\n\nlemma inverse_equality:\n  assumes eq: \"x' \\<odot> x = one\"\n  shows \"inverse x = x'\"\nproof -\n  have \"inverse x = one \\<odot> inverse x\"\n    by (simp only: left_one)\n  also have \"\\<dots> = (x' \\<odot> x) \\<odot> inverse x\"\n    by (simp only: eq)\n  also have \"\\<dots> = x' \\<odot> (x \\<odot> inverse x)\"\n    by (simp only: assoc)\n  also have \"\\<dots> = x' \\<odot> one\"\n    by (simp only: right_inverse)\n  also have \"\\<dots> = x'\"\n    by (simp only: right_one)\n  finally show ?thesis .\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/Isar_Examples/Group_Context.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.868826769445233, "lm_q2_score": 0.84594244507642, "lm_q1q2_score": 0.7349774416923475}}
{"text": "theory Padic_Field_Polynomials\n  imports Padic_Fields\n\nbegin\n\n(**************************************************************************************************)\n(**************************************************************************************************)\nsection\\<open>$p$-adic Univariate Polynomials and Hensel's Lemma\\<close>\n(**************************************************************************************************)\n(**************************************************************************************************)\ntype_synonym padic_field_poly = \"nat \\<Rightarrow> padic_number\"\n\ntype_synonym padic_field_fun = \"padic_number \\<Rightarrow> padic_number\"\n\n(**************************************************************************************************)\n(**************************************************************************************************)\nsubsection\\<open>Gauss Norms of Polynomials\\<close>\n(**************************************************************************************************)\n(**************************************************************************************************)\n\ntext \\<open>\n  The Gauss norm of a polynomial is defined to be the minimum valuation of a coefficient of that\n  polynomial. This induces a valuation on the ring of polynomials, and in particular it satisfies\n  the ultrametric inequality. In addition, the Gauss norm of a polynomial $f(x)$ gives a lower\n  bound for the value $\\text{val } (f(a))$ in terms of $\\text{val }(a)$, for a point\n  $a \\in \\mathbb{Q}_p$. We introduce Gauss norms here as a useful tool for stating and proving\n  Hensel's Lemma for the field $\\mathbb{Q}_p$. We are abusing terminology slightly in calling\n  this the Gauss norm, rather than the Gauss valuation, but this is just to conform with our\n  decision to work exclusively with the $p$-adic valuation and not discuss the equivalent\n  real-valued $p$-adic norm. For a detailed treatment of Gauss norms one can see, for example\n  \\<^cite>\\<open>\"engler2005valued\"\\<close>.\n\\<close>\ncontext padic_fields\nbegin\n\nno_notation Zp.to_fun (infixl\\<open>\\<bullet>\\<close> 70)\n\nabbreviation(input) Q\\<^sub>p_x where\n\"Q\\<^sub>p_x \\<equiv> UP Q\\<^sub>p\"\n\ndefinition gauss_norm where\n\"gauss_norm g = Min (val ` g ` {..degree g}) \"\n\nlemma gauss_normE:\n  assumes \"g \\<in> carrier Q\\<^sub>p_x\"\n  shows \"gauss_norm g \\<le> val (g k)\"\n  apply(cases \"k \\<le> degree g\")\n  unfolding gauss_norm_def\n  using assms apply auto[1]\nproof-\n  assume \"\\<not> k \\<le> degree g\"\n  then have \"g k = \\<zero>\\<^bsub>Q\\<^sub>p\\<^esub> \"\n    by (simp add: UPQ.deg_leE assms)\n  then show \"Min (val ` g ` {..deg Q\\<^sub>p g}) \\<le> val (g k)\"\n    by (simp add: local.val_zero)\nqed\n\nlemma gauss_norm_geqI:\n  assumes \"g \\<in> carrier (UP Q\\<^sub>p)\"\n  assumes \"\\<And>n. val (g n) \\<ge> \\<alpha>\"\n  shows \"gauss_norm g \\<ge> \\<alpha>\"\n  unfolding gauss_norm_def using assms\n  by simp\n\nlemma gauss_norm_eqI:\n  assumes \"g \\<in> carrier (UP Q\\<^sub>p)\"\n  assumes \"\\<And>n. val (g n) \\<ge> \\<alpha>\"\n  assumes \"val (g i) = \\<alpha>\"\n  shows \"gauss_norm g = \\<alpha>\"\nproof-\n  have 0: \"gauss_norm g \\<le> \\<alpha>\"\n    using assms gauss_normE gauss_norm_def by fastforce\n  have 1: \"gauss_norm g \\<ge> \\<alpha>\"\n    using assms gauss_norm_geqI by auto\n  show ?thesis using 0 1 by auto\nqed\n\nlemma nonzero_poly_nonzero_coeff:\n  assumes \"g \\<in> carrier Q\\<^sub>p_x\"\n  assumes \"g \\<noteq> \\<zero>\\<^bsub>Q\\<^sub>p_x\\<^esub>\"\n  shows \"\\<exists>k. k \\<le>degree g \\<and> g k \\<noteq>\\<zero>\\<^bsub>Q\\<^sub>p\\<^esub>\"\nproof(rule ccontr)\n  assume \"\\<not> (\\<exists>k\\<le>degree g. g k \\<noteq> \\<zero>\\<^bsub>Q\\<^sub>p\\<^esub>)\"\n  then have 0: \"\\<And>k. g k = \\<zero>\\<^bsub>Q\\<^sub>p\\<^esub>\"\n    by (meson UPQ.deg_leE assms(1) not_le_imp_less)\n  then show False\n    using assms  UPQ.cfs_zero by blast\nqed\n\nlemma gauss_norm_prop:\n  assumes \"g \\<in> carrier Q\\<^sub>p_x\"\n  assumes \"g \\<noteq> \\<zero>\\<^bsub>Q\\<^sub>p_x\\<^esub>\"\n  shows \"gauss_norm g \\<noteq> \\<infinity>\"\nproof-\n  obtain k where k_def: \"k \\<le>degree g \\<and> g k \\<noteq>\\<zero>\\<^bsub>Q\\<^sub>p\\<^esub>\"\n    using assms nonzero_poly_nonzero_coeff\n    by blast\n  then have 0: \"gauss_norm g \\<le> val (g k)\"\n    using assms(1) gauss_normE by blast\n  have \"g k \\<in> carrier Q\\<^sub>p\"\n    using UPQ.cfs_closed assms(1) by blast\n  hence \"val (g k) < \\<infinity>\"\n    using k_def assms\n    by (metis eint_ord_code(3) eint_ord_simps(4) val_ineq)\n  then show ?thesis\n    using 0 not_le by fastforce\nqed\n\nlemma gauss_norm_coeff_norm:\n  \"\\<exists>n \\<le> degree g. (gauss_norm g) = val (g n)\"\nproof-\n  have \"finite (val ` g ` {..deg Q\\<^sub>p g})\"\n    by blast\n  hence \"\\<exists>x \\<in> (val ` g ` {..deg Q\\<^sub>p g}). gauss_norm g = x\"\n  unfolding gauss_norm_def\n  by auto\n  thus ?thesis unfolding gauss_norm_def\n    by blast\nqed\n\nlemma gauss_norm_smult_cfs:\n  assumes \"g \\<in> carrier Q\\<^sub>p_x\"\n  assumes \"a \\<in> carrier Q\\<^sub>p\"\n  assumes \"gauss_norm g = val (g k)\"\n  shows \"gauss_norm (a \\<odot>\\<^bsub>Q\\<^sub>p_x\\<^esub> g) = val a + val (g k)\"\nproof-\n  obtain l where l_def: \"gauss_norm (a \\<odot>\\<^bsub>Q\\<^sub>p_x\\<^esub> g) =  val ((a \\<odot>\\<^bsub>Q\\<^sub>p_x\\<^esub> g) l)\"\n    using gauss_norm_coeff_norm\n    by blast\n  then have \"gauss_norm (a \\<odot>\\<^bsub>Q\\<^sub>p_x\\<^esub> g) =  val (a \\<otimes>\\<^bsub>Q\\<^sub>p\\<^esub> (g l))\"\n    using assms\n    by simp\n  then have \"gauss_norm (a \\<odot>\\<^bsub>Q\\<^sub>p_x\\<^esub> g) =  val a + val (g l)\"\n    by (simp add: UPQ.cfs_closed assms(1) assms(2) val_mult)\n  then have 0: \"gauss_norm (a \\<odot>\\<^bsub>Q\\<^sub>p_x\\<^esub> g) \\<le> val a +val (g k)\"\n    using assms  gauss_normE[of g l]\n    by (metis UPQ.UP_smult_closed UPQ.cfs_closed UPQ.cfs_smult gauss_normE val_mult)\n  have \"val a + val (g k) = val ((a \\<odot>\\<^bsub>Q\\<^sub>p_x\\<^esub> g) k)\"\n    by (simp add: UPQ.cfs_closed assms(1) assms(2) val_mult)\n  then have \"gauss_norm (a \\<odot>\\<^bsub>Q\\<^sub>p_x\\<^esub> g) \\<ge> val a + val (g k)\"\n    by (metis \\<open>gauss_norm (a \\<odot>\\<^bsub>UP Q\\<^sub>p\\<^esub> g) = val a + val (g l)\\<close> add_left_mono assms(1) assms(3) gauss_normE)\n  then show ?thesis\n    using 0  by auto\nqed\n\nlemma gauss_norm_smult:\n  assumes \"g \\<in> carrier Q\\<^sub>p_x\"\n  assumes \"a \\<in> carrier Q\\<^sub>p\"\n  shows \"gauss_norm (a \\<odot>\\<^bsub>Q\\<^sub>p_x\\<^esub> g) = val a + gauss_norm g\"\n  using gauss_norm_smult_cfs[of g a] gauss_norm_coeff_norm[of g] assms\n  by metis\n\nlemma gauss_norm_ultrametric:\n  assumes \"g \\<in> carrier Q\\<^sub>p_x\"\n  assumes \"h \\<in> carrier Q\\<^sub>p_x\"\n  shows \"gauss_norm (g \\<oplus>\\<^bsub>Q\\<^sub>p_x\\<^esub> h) \\<ge> min (gauss_norm g) (gauss_norm h)\"\nproof-\n  obtain k where \"gauss_norm (g \\<oplus>\\<^bsub>Q\\<^sub>p_x\\<^esub> h) = val ((g \\<oplus>\\<^bsub>Q\\<^sub>p_x\\<^esub> h) k)\"\n    using gauss_norm_coeff_norm\n    by blast\n  then have 0: \"gauss_norm (g \\<oplus>\\<^bsub>Q\\<^sub>p_x\\<^esub> h) = val (g k \\<oplus>\\<^bsub>Q\\<^sub>p\\<^esub> h k)\"\n    by (simp add: assms(1) assms(2))\n  have \"min (val (g k)) (val (h k))\\<ge> min (gauss_norm g) (gauss_norm h)\"\n    using gauss_normE[of g k] gauss_normE[of h k]  assms(1) assms(2) min.mono\n    by blast\n  then show ?thesis\n    using 0 val_ultrametric[of \"g k\" \"h k\"] assms(1) assms(2) dual_order.trans\n    by (metis (no_types, lifting) UPQ.cfs_closed)\nqed\n\nlemma gauss_norm_a_inv:\n  assumes \"f \\<in> carrier (UP Q\\<^sub>p)\"\n  shows \"gauss_norm (\\<ominus>\\<^bsub>UP Q\\<^sub>p\\<^esub>f) = gauss_norm f\"\nproof-\n  have 0: \"\\<And>n. ((\\<ominus>\\<^bsub>UP Q\\<^sub>p\\<^esub>f) n) = \\<ominus> (f n)\"\n    using assms by simp\n  have 1: \"\\<And>n. val ((\\<ominus>\\<^bsub>UP Q\\<^sub>p\\<^esub>f) n) = val (f n)\"\n    using 0 assms UPQ.UP_car_memE(1) val_minus by presburger\n  obtain i where i_def: \"gauss_norm f = val (f i)\"\n    using assms gauss_norm_coeff_norm by blast\n  have 2: \"\\<And>k. val ((\\<ominus>\\<^bsub>UP Q\\<^sub>p\\<^esub>f) k) \\<ge> val (f i)\"\n    unfolding 1\n    using i_def assms gauss_normE by fastforce\n  show ?thesis\n    apply(rule gauss_norm_eqI[of _ _ i])\n      apply (simp add: assms; fail)\n    unfolding 1 using assms gauss_normE apply blast\n    unfolding i_def by blast\nqed\n\nlemma gauss_norm_ultrametric':\n  assumes \"f \\<in> carrier (UP Q\\<^sub>p)\"\n  assumes \"g \\<in> carrier (UP Q\\<^sub>p)\"\n  shows \"gauss_norm (f \\<ominus>\\<^bsub>UP Q\\<^sub>p\\<^esub> g) \\<ge> min (gauss_norm f) (gauss_norm g)\"\n  unfolding a_minus_def\n  using assms gauss_norm_a_inv[of g] gauss_norm_ultrametric\n  by (metis UPQ.UP_a_inv_closed)\n\nlemma gauss_norm_finsum:\n  assumes \"f \\<in> A \\<rightarrow> carrier Q\\<^sub>p_x\"\n  assumes \"finite A\"\n  assumes \"A \\<noteq> {}\"\n  shows \" gauss_norm (\\<Oplus>\\<^bsub>Q\\<^sub>p_x\\<^esub>i\\<in>A. f i) \\<ge> Min (gauss_norm ` (f`A))\"\nproof-\n  obtain k where k_def: \"val ((\\<Oplus>\\<^bsub>Q\\<^sub>p_x\\<^esub>i\\<in>A. f i) k) = gauss_norm (\\<Oplus>\\<^bsub>Q\\<^sub>p_x\\<^esub>i\\<in>A. f i)\"\n    by (metis gauss_norm_coeff_norm)\n  then have 0: \"val (\\<Oplus>\\<^bsub>Q\\<^sub>p\\<^esub>i\\<in>A. f i k) \\<ge> Min (val ` (\\<lambda> i. f i k) ` A)\"\n    using finsum_val_ultrametric[of \"\\<lambda> i. f i k\" A] assms\n    by (simp add: \\<open>\\<lbrakk>(\\<lambda>i. f i k) \\<in> A \\<rightarrow> carrier Q\\<^sub>p; finite A; A \\<noteq> {}\\<rbrakk> \\<Longrightarrow> Min (val ` (\\<lambda>i. f i k) ` A) \\<le> val (\\<Oplus>i\\<in>A. f i k)\\<close> Pi_iff UPQ.cfs_closed)\n  have \"(\\<And>a. a \\<in> A \\<Longrightarrow> (val \\<circ> (\\<lambda>i. f i k)) a \\<ge> gauss_norm (f a))\"\n    using gauss_normE assms\n    by (metis (no_types, lifting) Pi_split_insert_domain Set.set_insert comp_apply)\n  then have \"Min (val ` (\\<lambda> i. f i k) ` A) \\<ge> Min ((\\<lambda> i. gauss_norm (f  i)) ` A)\"\n    using Min_mono'[of A]\n    by (simp add: assms(2) image_comp)\n  then have 1: \"Min (val ` (\\<lambda> i. f i k) ` A) \\<ge> Min (gauss_norm ` f ` A)\"\n    by (metis image_image)\n  have \"f \\<in> A \\<rightarrow> carrier (UP Q\\<^sub>p) \\<longrightarrow> ((\\<Oplus>\\<^bsub>Q\\<^sub>p_x\\<^esub>i\\<in>A. f i) \\<in> carrier Q\\<^sub>p_x \\<and> ((\\<Oplus>\\<^bsub>Q\\<^sub>p_x\\<^esub>i\\<in>A. f i) k) = (\\<Oplus>\\<^bsub>Q\\<^sub>p\\<^esub>i\\<in>A. f i k)) \"\n    apply(rule finite.induct[of A])\n      apply (simp add: assms(2); fail)\n     apply (metis (no_types, lifting) Pi_I Qp.add.finprod_one_eqI UPQ.P.finsum_closed UPQ.P.finsum_empty UPQ.cfs_zero empty_iff)\n  proof-\n    fix a A assume A: \"finite A\" \"f \\<in> A \\<rightarrow> carrier (UP Q\\<^sub>p) \\<longrightarrow> ( finsum (UP Q\\<^sub>p) f A \\<in> carrier (UP Q\\<^sub>p) \\<and> finsum (UP Q\\<^sub>p) f A k = (\\<Oplus>i\\<in>A. f i k)) \"\n    show \" f \\<in> insert a A \\<rightarrow> carrier (UP Q\\<^sub>p) \\<longrightarrow>  finsum (UP Q\\<^sub>p) f (insert a A) \\<in> carrier (UP Q\\<^sub>p) \\<and> finsum (UP Q\\<^sub>p) f (insert a A) k = (\\<Oplus>i\\<in>insert a A. f i k)\"\n      apply(cases \"a \\<in> A\")\n      using A\n      apply (simp add: insert_absorb; fail)\n    proof assume B: \"a \\<notin> A\" \" f \\<in> insert a A \\<rightarrow> carrier (UP Q\\<^sub>p)\"\n      then have f_a: \"f a \\<in> carrier (UP Q\\<^sub>p)\"\n        by blast\n      have f_A: \"f \\<in> A \\<rightarrow> carrier (UP Q\\<^sub>p)\"\n        using B by blast\n      have \"finsum (UP Q\\<^sub>p) f (insert a A) = f a \\<oplus>\\<^bsub>UP Q\\<^sub>p\\<^esub>finsum (UP Q\\<^sub>p) f A\"\n        using assms A B f_a f_A  finsum_insert by simp\n      then have 0: \"finsum (UP Q\\<^sub>p) f (insert a A) k = f a k \\<oplus>\\<^bsub>Q\\<^sub>p\\<^esub> (finsum (UP Q\\<^sub>p) f A) k\"\n        using f_a f_A A B\n        by simp\n      have \" ( \\<lambda> a. f a k) \\<in> A \\<rightarrow> carrier Q\\<^sub>p\"\n      proof fix a assume \"a \\<in> A\"\n        then have \"f a \\<in> carrier (UP Q\\<^sub>p)\"\n          using f_A by blast\n        then show \"f a k \\<in> carrier Q\\<^sub>p\"\n          using A cfs_closed by blast\n      qed\n      then have 0: \"finsum (UP Q\\<^sub>p) f (insert a A) k = (\\<Oplus>i\\<in>insert a A. f i k)\"\n        using A B Qp.finsum_insert[of A a \"\\<lambda> a. f a k\"]\n        by (simp add: UPQ.cfs_closed)\n      thus \" finsum (UP Q\\<^sub>p) f (insert a A) \\<in> carrier (UP Q\\<^sub>p) \\<and> finsum (UP Q\\<^sub>p) f (insert a A) k = (\\<Oplus>i\\<in>insert a A. f i k)\"\n        using B(2) UPQ.P.finsum_closed by blast\n    qed\n  qed\n  then have \"(\\<Oplus>\\<^bsub>Q\\<^sub>p_x\\<^esub>i\\<in>A. f i) \\<in> carrier Q\\<^sub>p_x \\<and> ((\\<Oplus>\\<^bsub>Q\\<^sub>p_x\\<^esub>i\\<in>A. f i) k) = (\\<Oplus>\\<^bsub>Q\\<^sub>p\\<^esub>i\\<in>A. f i k)\"\n    using assms by blast\n  hence 3: \"gauss_norm (\\<Oplus>\\<^bsub>Q\\<^sub>p_x\\<^esub>i\\<in>A. f i) \\<ge> Min (val ` (\\<lambda> i. f i k) ` A)\"\n    using 0  k_def by auto\n  thus ?thesis\n    using 1 le_trans by auto\nqed\n\nlemma gauss_norm_monom:\n  assumes \"a \\<in> carrier Q\\<^sub>p\"\n  shows \"gauss_norm (monom Q\\<^sub>p_x a n) = val a\"\nproof-\n  have \"val ((monom Q\\<^sub>p_x a n) n) \\<ge> gauss_norm (monom Q\\<^sub>p_x a n)\"\n    using assms gauss_normE[of \"monom Q\\<^sub>p_x a n\" n] UPQ.monom_closed\n    by blast\n  then show ?thesis\n    using gauss_norm_coeff_norm[of \"monom Q\\<^sub>p_x a n\"] assms val_ineq UPQ.cfs_monom by fastforce\nqed\n\nlemma val_val_ring_prod:\n  assumes \"a \\<in> \\<O>\\<^sub>p\"\n  assumes \"b \\<in> carrier Q\\<^sub>p\"\n  shows \"val (a \\<otimes>\\<^bsub>Q\\<^sub>p\\<^esub> b) \\<ge> val b\"\nproof-\n  have 0: \"val (a \\<otimes>\\<^bsub>Q\\<^sub>p\\<^esub> b) = val a + val b\"\n    using assms val_ring_memE[of a] val_mult\n    by blast\n  have 1: \" val a \\<ge> 0\"\n    using assms\n    by (simp add: val_ring_memE)\n  then show ?thesis\n    using assms 0\n    by simp\nqed\n\nlemma val_val_ring_prod':\n  assumes \"a \\<in> \\<O>\\<^sub>p\"\n  assumes \"b \\<in> carrier Q\\<^sub>p\"\n  shows \"val (b \\<otimes>\\<^bsub>Q\\<^sub>p\\<^esub> a) \\<ge> val b\"\n  using val_val_ring_prod[of a b]\n  by (simp add: Qp.m_comm val_ring_memE assms(1) assms(2))\n\nlemma val_ring_nat_pow_closed:\n  assumes \"a \\<in> \\<O>\\<^sub>p\"\n  shows \"(a[^](n::nat)) \\<in> \\<O>\\<^sub>p\"\n  apply(induction n)\n  apply auto[1]\n  using Qp.inv_one Z\\<^sub>p_mem apply blast\n  by (metis Qp.nat_pow_Suc Qp.nat_pow_closed val_ring_memE assms image_eqI inc_of_prod to_Zp_closed to_Zp_inc to_Zp_mult)\n\nlemma val_ringI:\n  assumes \"a \\<in> carrier Q\\<^sub>p\"\n  assumes \"val a \\<ge>0\"\n  shows \" a \\<in> \\<O>\\<^sub>p\"\n  apply(rule val_ring_val_criterion)\n  using assms by auto\n\nnotation UPQ.to_fun (infixl\\<open>\\<bullet>\\<close> 70)\n\nlemma val_gauss_norm_eval:\n  assumes \"g \\<in> carrier Q\\<^sub>p_x\"\n  assumes \"a \\<in> \\<O>\\<^sub>p\"\n  shows \"val (g \\<bullet> a) \\<ge> gauss_norm g\"\nproof-\n  have 0: \"g\\<bullet>a = (\\<Oplus>\\<^bsub>Q\\<^sub>p\\<^esub>i\\<in>{..degree g}. (g i)\\<otimes>\\<^bsub>Q\\<^sub>p\\<^esub> (a[^]i))\"\n    using val_ring_memE assms to_fun_formula[of g a] by auto\n\n  have 1: \"(\\<lambda>i. g i \\<otimes>\\<^bsub>Q\\<^sub>p\\<^esub> (a[^]i)) \\<in> {..degree g} \\<rightarrow> carrier Q\\<^sub>p\"\n     using assms\n    by (meson Pi_I val_ring_memE cfs_closed monom_term_car)\n  then have 2: \"val (g\\<bullet>a) \\<ge> Min (val ` (\\<lambda> i. ((g i)\\<otimes>\\<^bsub>Q\\<^sub>p\\<^esub> (a[^]i))) ` {..degree g})\"\n    using 0 finsum_val_ultrametric[of \"\\<lambda> i. ((g i)\\<otimes>\\<^bsub>Q\\<^sub>p\\<^esub> (a[^]i))\" \"{..degree g}\" ]\n    by (metis finite_atMost not_empty_eq_Iic_eq_empty)\n  have 3: \"\\<And> i. val ((g i)\\<otimes>\\<^bsub>Q\\<^sub>p\\<^esub> (a[^]i)) = val (g i) + val (a[^]i)\"\n    using assms val_mult\n    by (simp add: val_ring_memE UPQ.cfs_closed)\n  have 4: \"\\<And> i. val ((g i)\\<otimes>\\<^bsub>Q\\<^sub>p\\<^esub> (a[^]i)) \\<ge> val (g i)\"\n  proof-\n    fix i\n    show \"val ((g i)\\<otimes>\\<^bsub>Q\\<^sub>p\\<^esub> (a[^]i)) \\<ge> val (g i)\"\n      using val_val_ring_prod'[of \"a[^]i\" \"g i\" ]\n        assms(1) assms(2) val_ring_nat_pow_closed cfs_closed\n      by simp\n  qed\n  have \"Min (val ` (\\<lambda>i. g i \\<otimes>\\<^bsub>Q\\<^sub>p\\<^esub> (a[^]i)) ` {..degree g}) \\<ge> Min ((\\<lambda>i. val (g i)) ` {..degree g})\"\n    using Min_mono'[of \"{..degree g}\" \"\\<lambda>i. val (g i)\" \"\\<lambda>i. val (g i \\<otimes>\\<^bsub>Q\\<^sub>p\\<^esub> (a[^]i))\" ] 4 2\n    by (metis finite_atMost image_image)\n  then have \"Min (val ` (\\<lambda>i. g i \\<otimes>\\<^bsub>Q\\<^sub>p\\<^esub> (a[^]i)) ` {..degree g}) \\<ge> Min (val ` g ` {..degree g})\"\n    by (metis  image_image)\n  then have  \"val (g\\<bullet>a) \\<ge> Min (val ` g ` {..degree g})\"\n    using 2\n    by (meson atMost_iff atMost_subset_iff in_mono)\n  then show ?thesis\n    by (simp add: \\<open>val (g\\<bullet>a) \\<ge> Min (val ` g ` {..degree g})\\<close> gauss_norm_def)\nqed\n\nlemma positive_gauss_norm_eval:\n  assumes \"g \\<in> carrier Q\\<^sub>p_x\"\n  assumes \"gauss_norm g \\<ge> 0\"\n  assumes \"a \\<in> \\<O>\\<^sub>p\"\n  shows \"(g\\<bullet>a) \\<in> \\<O>\\<^sub>p\"\n  apply(rule val_ring_val_criterion[of \"g\\<bullet>a\"])\n  using assms val_ring_memE\n  using UPQ.to_fun_closed apply blast\n  using assms val_gauss_norm_eval[of g a] by auto\n\nlemma positive_gauss_norm_valuation_ring_coeffs:\n  assumes \"g \\<in> carrier Q\\<^sub>p_x\"\n  assumes \"gauss_norm g \\<ge> 0\"\n  shows \"g n \\<in> \\<O>\\<^sub>p\"\n  apply(rule val_ringI)\n  using cfs_closed assms(1) apply blast\n  using gauss_normE[of g n] assms by auto\n\nlemma val_ring_cfs_imp_nonneg_gauss_norm:\n  assumes \"g \\<in> carrier (UP Q\\<^sub>p)\"\n  assumes \"\\<And>n. g n \\<in> \\<O>\\<^sub>p\"\n  shows \"gauss_norm g \\<ge> 0\"\n  by(rule gauss_norm_geqI, rule assms, rule val_ring_memE, rule assms)\n\nlemma val_of_add_pow:\n  assumes \"a \\<in> carrier Q\\<^sub>p\"\n  shows \"val ([(n::nat)]\\<cdot>a) \\<ge> val a\"\nproof-\n  have 0: \"[(n::nat)]\\<cdot>a = ([n]\\<cdot>\\<one>)\\<otimes>a\"\n    using assms Qp.add_pow_ldistr Qp.cring_simprules(12) Qp.one_closed by presburger\n  have 1: \"val ([(n::nat)]\\<cdot>a) = val ([n]\\<cdot>\\<one>) + val a\"\n    unfolding 0 by(rule val_mult, simp, rule assms)\n  show ?thesis unfolding 1 using assms\n    by (simp add: val_of_nat_inc)\nqed\n\nlemma gauss_norm_pderiv:\n  assumes \"g \\<in> carrier (UP Q\\<^sub>p)\"\n  shows \"gauss_norm g \\<le> gauss_norm (pderiv g)\"\n  apply(rule gauss_norm_geqI)\n  using UPQ.pderiv_closed assms apply blast\n  using gauss_normE pderiv_cfs val_of_add_pow\n  by (smt UPQ.cfs_closed assms dual_order.trans)\n\n(**************************************************************************************************)\n(**************************************************************************************************)\nsubsection\\<open>Mapping Polynomials with Value Ring Coefficients to Polynomials over $\\mathbb{Z}_p$\\<close>\n(**************************************************************************************************)\n(**************************************************************************************************)\n\ndefinition to_Zp_poly where\n\"to_Zp_poly g = (\\<lambda>n. to_Zp (g n))\"\n\nlemma to_Zp_poly_closed:\n  assumes \"g \\<in> carrier Q\\<^sub>p_x\"\n  assumes \"gauss_norm g \\<ge> 0\"\n  shows \"to_Zp_poly g \\<in> carrier (UP Z\\<^sub>p)\"\nproof-\n  have  \"to_Zp_poly g \\<in> up Z\\<^sub>p\"\n    apply(rule mem_upI)\n   unfolding to_Zp_poly_def\n   using cfs_closed[of g ] assms(1) to_Zp_closed[of ]  apply blast\n  proof-\n    have \"\\<exists>n. bound \\<zero>\\<^bsub>Q\\<^sub>p\\<^esub> n g\"\n     using UPQ.deg_leE assms(1) by auto\n    then obtain n where n_def: \" bound \\<zero>\\<^bsub>Q\\<^sub>p\\<^esub> n g\"\n      by blast\n    then have \" bound \\<zero>\\<^bsub>Z\\<^sub>p\\<^esub> n (\\<lambda>n. to_Zp (g n))\"\n      unfolding bound_def\n      by (simp add: to_Zp_zero)\n    then show \"\\<exists>n. bound \\<zero>\\<^bsub>Z\\<^sub>p\\<^esub> n (\\<lambda>n. to_Zp (g n))\"\n      by blast\n  qed\n  then show ?thesis using UP_def[of Z\\<^sub>p]\n    by simp\nqed\n\ndefinition poly_inc where\n\"poly_inc g = (\\<lambda>n::nat. \\<iota> (g n))\"\n\nlemma poly_inc_closed:\n  assumes \"g \\<in> carrier (UP Z\\<^sub>p)\"\n  shows \"poly_inc g \\<in> carrier Q\\<^sub>p_x\"\nproof-\n  have \"poly_inc g \\<in> up Q\\<^sub>p\"\n  proof(rule mem_upI)\n    show \"\\<And>n. poly_inc g n \\<in> carrier Q\\<^sub>p\"\n    proof- fix n\n      have \"g n \\<in> carrier Z\\<^sub>p\"\n        using assms UP_def\n        by (simp add: UP_def mem_upD)\n      then show \"poly_inc g n \\<in> carrier Q\\<^sub>p\"\n        using assms poly_inc_def[of g] inc_def[of \"g n\" ] inc_closed\n        by force\n    qed\n    show \"\\<exists>n. bound \\<zero>\\<^bsub>Q\\<^sub>p\\<^esub> n (poly_inc g)\"\n    proof-\n      obtain n where n_def: \" bound \\<zero>\\<^bsub>Z\\<^sub>p\\<^esub> n g\"\n        using assms  bound_def[of \"\\<zero>\\<^bsub>Z\\<^sub>p\\<^esub>\" _ g]Zp.cring_axioms UP_cring.deg_leE[of Z\\<^sub>p g]\n        unfolding UP_cring_def\n        by metis\n      then have \" bound \\<zero>\\<^bsub>Q\\<^sub>p\\<^esub> n (poly_inc g)\"\n        unfolding poly_inc_def bound_def\n        by (metis Qp.nat_inc_zero Zp.nat_inc_zero inc_of_nat)\n      then show ?thesis by blast\n    qed\n  qed\n  then show ?thesis\n    by (simp add: \\<open>poly_inc g \\<in> up Q\\<^sub>p\\<close> UP_def)\nqed\n\nlemma poly_inc_inverse_right:\n  assumes \"g \\<in> carrier (UP Z\\<^sub>p)\"\n  shows \"to_Zp_poly (poly_inc g) = g\"\nproof-\n  have 0: \"\\<And>n. g n \\<in> carrier Z\\<^sub>p\"\n    by (simp add: Zp.cfs_closed assms)\n  show ?thesis\n    unfolding to_Zp_poly_def poly_inc_def\n  proof\n    fix n\n    show \"to_Zp (\\<iota> (g n)) = g n\"\n      using 0 inc_to_Zp\n      by auto\n  qed\nqed\n\nlemma poly_inc_inverse_left:\n  assumes \"g \\<in> carrier Q\\<^sub>p_x\"\n  assumes \"gauss_norm g \\<ge>0\"\n  shows \"poly_inc (to_Zp_poly g) = g\"\nproof\n  fix x\n  show \"poly_inc (to_Zp_poly g) x = g x\"\n    using assms unfolding poly_inc_def to_Zp_poly_def\n    by (simp add: positive_gauss_norm_valuation_ring_coeffs to_Zp_inc)\nqed\n\nlemma poly_inc_plus:\n  assumes \"f \\<in> carrier (UP Z\\<^sub>p)\"\n  assumes \"g \\<in> carrier (UP Z\\<^sub>p)\"\n  shows \"poly_inc (f \\<oplus>\\<^bsub>UP Z\\<^sub>p\\<^esub> g) = poly_inc f \\<oplus>\\<^bsub>UP Q\\<^sub>p\\<^esub> poly_inc g\"\nproof\n  fix n\n  have 0: \"poly_inc (f \\<oplus>\\<^bsub>UP Z\\<^sub>p\\<^esub> g) n = \\<iota> (f n \\<oplus>\\<^bsub>Z\\<^sub>p\\<^esub> g n)\"\n    unfolding poly_inc_def using assms by auto\n  have 1: \"(poly_inc f \\<oplus>\\<^bsub>UP Q\\<^sub>p\\<^esub> poly_inc g) n = poly_inc f n \\<oplus> poly_inc g n\"\n    by(rule cfs_add, rule poly_inc_closed, rule assms, rule poly_inc_closed, rule assms)\n  show \"poly_inc (f \\<oplus>\\<^bsub>UP Z\\<^sub>p\\<^esub> g) n = (poly_inc f \\<oplus>\\<^bsub>UP Q\\<^sub>p\\<^esub> poly_inc g) n\"\n    unfolding 0 1 unfolding poly_inc_def\n    apply(rule inc_of_sum)\n    using assms apply (simp add: Zp.cfs_closed; fail)\n        using assms by (simp add: Zp.cfs_closed)\nqed\n\nlemma poly_inc_monom:\n  assumes \"a \\<in> carrier Z\\<^sub>p\"\n  shows \"poly_inc (monom (UP Z\\<^sub>p) a m) = monom (UP Q\\<^sub>p) (\\<iota> a) m\"\nproof fix n\n  show \"poly_inc (monom (UP Z\\<^sub>p) a m) n = monom (UP Q\\<^sub>p) (\\<iota> a) m n\"\n    apply(cases \"m = n\")\n    using assms cfs_monom[of \"\\<iota> a\"] Zp.cfs_monom[of a] unfolding poly_inc_def\n     apply (simp add: inc_closed; fail)\n    using assms cfs_monom[of \"\\<iota> a\"] Zp.cfs_monom[of a] unfolding poly_inc_def\n    by (metis Qp.nat_mult_zero Zp_nat_inc_zero inc_closed inc_of_nat)\nqed\n\nlemma poly_inc_times:\n  assumes \"f \\<in> carrier (UP Z\\<^sub>p)\"\n  assumes \"g \\<in> carrier (UP Z\\<^sub>p)\"\n  shows \"poly_inc (f \\<otimes>\\<^bsub>UP Z\\<^sub>p\\<^esub> g) = poly_inc f \\<otimes>\\<^bsub>UP Q\\<^sub>p\\<^esub> poly_inc g\"\n  apply(rule UP_ring.poly_induct3[of Z\\<^sub>p])\n  apply (simp add: Zp.is_UP_ring; fail)\n  using assms apply blast\nproof-\n  fix p q\n  assume A: \"q \\<in> carrier (UP Z\\<^sub>p)\"  \"p \\<in> carrier (UP Z\\<^sub>p)\"\n            \"poly_inc (f \\<otimes>\\<^bsub>UP Z\\<^sub>p\\<^esub> p) = poly_inc f \\<otimes>\\<^bsub>UP Q\\<^sub>p\\<^esub> poly_inc p\"\n            \"poly_inc (f \\<otimes>\\<^bsub>UP Z\\<^sub>p\\<^esub> q) = poly_inc f \\<otimes>\\<^bsub>UP Q\\<^sub>p\\<^esub> poly_inc q\"\n  have 0: \"(f \\<otimes>\\<^bsub>UP Z\\<^sub>p\\<^esub> (p \\<oplus>\\<^bsub>UP Z\\<^sub>p\\<^esub> q)) = (f \\<otimes>\\<^bsub>UP Z\\<^sub>p\\<^esub> p) \\<oplus>\\<^bsub>UP Z\\<^sub>p\\<^esub> (f \\<otimes>\\<^bsub>UP Z\\<^sub>p\\<^esub> q)\"\n    using assms(1) A\n    by (simp add: Zp.P.r_distr)\n  have 1: \"poly_inc (p \\<oplus>\\<^bsub>UP Z\\<^sub>p\\<^esub> q) = poly_inc p \\<oplus>\\<^bsub>UP Q\\<^sub>p\\<^esub> poly_inc q\"\n    by(rule poly_inc_plus, rule A, rule A)\n  show \"poly_inc (f \\<otimes>\\<^bsub>UP Z\\<^sub>p\\<^esub> (p \\<oplus>\\<^bsub>UP Z\\<^sub>p\\<^esub> q)) = poly_inc f \\<otimes>\\<^bsub>UP Q\\<^sub>p\\<^esub> poly_inc (p \\<oplus>\\<^bsub>UP Z\\<^sub>p\\<^esub> q)\"\n    unfolding 0 1 using A poly_inc_closed poly_inc_plus\n    by (simp add: UPQ.P.r_distr assms(1))\nnext\n  fix a fix n::nat\n  assume A: \"a \\<in> carrier Z\\<^sub>p\"\n  show \"poly_inc (f \\<otimes>\\<^bsub>UP Z\\<^sub>p\\<^esub> monom (UP Z\\<^sub>p) a n) =\n           poly_inc f \\<otimes>\\<^bsub>UP Q\\<^sub>p\\<^esub> poly_inc (monom (UP Z\\<^sub>p) a n)\"\n  proof\n    fix m\n    show \"poly_inc (f \\<otimes>\\<^bsub>UP Z\\<^sub>p\\<^esub> monom (UP Z\\<^sub>p) a n) m =\n         (poly_inc f \\<otimes>\\<^bsub>UP Q\\<^sub>p\\<^esub> poly_inc (monom (UP Z\\<^sub>p) a n)) m\"\n    proof(cases \"m < n\")\n      case True\n      have T0: \"(f \\<otimes>\\<^bsub>UP Z\\<^sub>p\\<^esub> monom (UP Z\\<^sub>p) a n) m = \\<zero>\\<^bsub>Z\\<^sub>p\\<^esub>\"\n        using True Zp.cfs_monom_mult[of f a m n] A assms\n        by blast\n      have T1: \"poly_inc (monom (UP Z\\<^sub>p) a n) =  (monom (UP Q\\<^sub>p) (\\<iota> a) n)\"\n        by(rule poly_inc_monom , rule A)\n      show ?thesis\n        unfolding T0 T1 using True\n        by (metis A Q\\<^sub>p_def T0 UPQ.cfs_monom_mult Zp_def assms(1) inc_closed padic_fields.to_Zp_zero padic_fields_axioms poly_inc_closed poly_inc_def to_Zp_inc zero_in_val_ring)\n    next\n      case False\n      then have F0: \"m \\<ge> n\"\n        using False by simp\n      have F1: \"(f \\<otimes>\\<^bsub>UP Z\\<^sub>p\\<^esub> monom (UP Z\\<^sub>p) a n) m = a \\<otimes>\\<^bsub>Z\\<^sub>p\\<^esub> f (m - n)\"\n        using Zp.cfs_monom_mult_l' F0 A assms by simp\n      have F2: \"poly_inc (monom (UP Z\\<^sub>p) a n)  = monom (UP Q\\<^sub>p) (\\<iota> a) n \"\n        by(rule poly_inc_monom, rule A)\n      have F3: \"(poly_inc f \\<otimes>\\<^bsub>UP Q\\<^sub>p\\<^esub> poly_inc (monom (UP Z\\<^sub>p) a n)) m\n                = (\\<iota> a) \\<otimes> (poly_inc f (m -n))\"\n        using UPQ.cfs_monom_mult_l' F0 A assms poly_inc_closed\n        by (simp add: F2 inc_closed)\n      show ?thesis\n        unfolding F3 unfolding poly_inc_def F1\n        apply(rule inc_of_prod, rule A)\n        using assms Zp.cfs_closed by blast\n    qed\n  qed\nqed\n\nlemma poly_inc_one:\n\"poly_inc (\\<one>\\<^bsub>UP Z\\<^sub>p\\<^esub>) = \\<one>\\<^bsub>UP Q\\<^sub>p\\<^esub>\"\napply(rule ext)\n  unfolding poly_inc_def\n  using inc_of_one inc_of_zero\n  by simp\n\nlemma poly_inc_zero:\n\"poly_inc (\\<zero>\\<^bsub>UP Z\\<^sub>p\\<^esub>) = \\<zero>\\<^bsub>UP Q\\<^sub>p\\<^esub>\"\napply(rule ext)\n  unfolding poly_inc_def\n  using inc_of_one inc_of_zero\n  by simp\n\nlemma poly_inc_hom:\n\"poly_inc \\<in> ring_hom (UP Z\\<^sub>p) (UP Q\\<^sub>p)\"\n  apply(rule ring_hom_memI)\n     apply(rule poly_inc_closed, blast)\n    apply(rule poly_inc_times, blast, blast)\n   apply(rule poly_inc_plus, blast, blast)\n  by(rule poly_inc_one)\n\nlemma poly_inc_as_poly_lift_hom:\n  assumes \"f \\<in> carrier (UP Z\\<^sub>p)\"\n  shows \"poly_inc f = poly_lift_hom Z\\<^sub>p Q\\<^sub>p \\<iota> f\"\n  apply(rule ext)\n  unfolding poly_inc_def\n  using Zp.poly_lift_hom_cf[of Q\\<^sub>p \\<iota> f] assms UPQ.R_cring local.inc_is_hom\n  by blast\n\nlemma poly_inc_eval:\n  assumes \"g \\<in> carrier (UP Z\\<^sub>p)\"\n  assumes \"a \\<in> carrier Z\\<^sub>p\"\n  shows \"to_function Q\\<^sub>p (poly_inc g) (\\<iota> a) = \\<iota> (to_function Z\\<^sub>p g a)\"\nproof-\n  have 0: \"poly_inc g = poly_lift_hom Z\\<^sub>p Q\\<^sub>p \\<iota> g\"\n    using assms poly_inc_as_poly_lift_hom[of g] by blast\n  have 1: \"to_function Q\\<^sub>p (poly_lift_hom Z\\<^sub>p Q\\<^sub>p \\<iota> g) (\\<iota> a) = \\<iota> (to_function Z\\<^sub>p g a)\"\n    using Zp.poly_lift_hom_eval[of Q\\<^sub>p \\<iota> g a] assms inc_is_hom\n    unfolding to_fun_def Zp.to_fun_def\n    using UPQ.R_cring by blast\n  show ?thesis unfolding 0 1\n    by blast\nqed\n\nlemma val_ring_poly_eval:\n  assumes \"f \\<in> carrier (UP Q\\<^sub>p)\"\n  assumes \"\\<And> i. f i \\<in> \\<O>\\<^sub>p\"\n  shows \"\\<And>x. x \\<in> \\<O>\\<^sub>p \\<Longrightarrow> f \\<bullet> x \\<in> \\<O>\\<^sub>p\"\n  apply(rule positive_gauss_norm_eval, rule assms)\n  apply(rule val_ring_cfs_imp_nonneg_gauss_norm)\n  using assms by auto\n\nlemma Zp_res_of_pow:\n  assumes \"a \\<in> carrier Z\\<^sub>p\"\n  assumes \"b \\<in> carrier Z\\<^sub>p\"\n  assumes \"a n = b n\"\n  shows \"(a[^]\\<^bsub>Z\\<^sub>p\\<^esub>(k::nat)) n = (b[^]\\<^bsub>Z\\<^sub>p\\<^esub>(k::nat)) n\"\n  apply(induction k)\n  using assms Group.nat_pow_0 to_Zp_one apply metis\n  using Zp.geometric_series_id[of a b] Zp_residue_mult_zero(1) assms(1) assms(2) assms(3)\n    pow_closed res_diff_zero_fact'' res_diff_zero_fact(1) by metis\n\nlemma to_Zp_nat_pow:\n  assumes \"a \\<in> \\<O>\\<^sub>p\"\n  shows \"to_Zp (a[^](n::nat)) = (to_Zp a)[^]\\<^bsub>Z\\<^sub>p\\<^esub>(n::nat)\"\n  apply(induction n)\n  using assms Group.nat_pow_0 to_Zp_one apply metis\n  using assms to_Zp_mult[of a] Qp.m_comm Qp.nat_pow_Suc val_ring_memE pow_suc to_Zp_closed val_ring_nat_pow_closed\n  by metis\n\nlemma  to_Zp_res_of_pow:\n  assumes \"a \\<in> \\<O>\\<^sub>p\"\n  assumes \"b \\<in> \\<O>\\<^sub>p\"\n  assumes \"to_Zp a n = to_Zp b n\"\n  shows \"to_Zp (a[^](k::nat)) n = to_Zp (b[^](k::nat)) n\"\n  using assms val_ring_memE Zp_res_of_pow to_Zp_closed to_Zp_nat_pow by presburger\n\nlemma poly_eval_cong:\n  assumes \"g \\<in> carrier (UP Q\\<^sub>p)\"\n  assumes \"\\<And>i. g i \\<in> \\<O>\\<^sub>p\"\n  assumes \"a \\<in> \\<O>\\<^sub>p\"\n  assumes \"b \\<in> \\<O>\\<^sub>p\"\n  assumes \"to_Zp a k = to_Zp b k\"\n  shows \"to_Zp (g \\<bullet> a) k = to_Zp (g \\<bullet> b) k\"\nproof-\n  have \"(\\<forall>i. g i \\<in> \\<O>\\<^sub>p) \\<longrightarrow> to_Zp (g \\<bullet> a) k = to_Zp (g \\<bullet> b) k\"\n  proof(rule UPQ.poly_induct[of g])\n    show \" g \\<in> carrier (UP Q\\<^sub>p)\"\n      using assms by blast\n    show \"\\<And>p. p \\<in> carrier (UP Q\\<^sub>p) \\<Longrightarrow> deg Q\\<^sub>p p = 0 \\<Longrightarrow> (\\<forall>i. p i \\<in> \\<O>\\<^sub>p) \\<longrightarrow> to_Zp (p \\<bullet> a) k = to_Zp (p \\<bullet> b) k\"\n    proof fix p assume A: \"p \\<in> carrier (UP Q\\<^sub>p)\" \"deg Q\\<^sub>p p = 0\" \"\\<forall>i. p i \\<in> \\<O>\\<^sub>p\"\n      obtain c where c_def: \"c \\<in> carrier Q\\<^sub>p \\<and> p = up_ring.monom (UP Q\\<^sub>p) c 0\"\n        using A\n        by (metis UPQ.zcf_degree_zero UPQ.cfs_closed UPQ.trms_of_deg_leq_0 UPQ.trms_of_deg_leq_degree_f)\n      have p_eq: \"p = up_ring.monom (UP Q\\<^sub>p) c 0\"\n        using c_def by blast\n      have p_cfs: \"p 0 = c\"\n        unfolding p_eq using c_def UP_ring.cfs_monom[of Q\\<^sub>p c 0 0] UPQ.P_is_UP_ring by presburger\n      have c_closed: \"c \\<in> \\<O>\\<^sub>p\"\n        using p_cfs A(3) by blast\n      have 0: \"(p \\<bullet> a) = c\"\n        unfolding p_eq using c_def assms by (meson UPQ.to_fun_const val_ring_memE(2))\n      have 1: \"(p \\<bullet> b) = c\"\n        unfolding p_eq using c_def assms UPQ.to_fun_const val_ring_memE(2) by presburger\n      show \" to_Zp (p \\<bullet> a) k = to_Zp (p \\<bullet> b) k\"\n        unfolding 0 1 by blast\n    qed\n    show \"\\<And>p. (\\<And>q. q \\<in> carrier (UP Q\\<^sub>p) \\<Longrightarrow> deg Q\\<^sub>p q < deg Q\\<^sub>p p \\<Longrightarrow> (\\<forall>i. q i \\<in> \\<O>\\<^sub>p) \\<longrightarrow> to_Zp (q \\<bullet> a) k = to_Zp (q \\<bullet> b) k) \\<Longrightarrow>\n         p \\<in> carrier (UP Q\\<^sub>p) \\<Longrightarrow> 0 < deg Q\\<^sub>p p \\<Longrightarrow> (\\<forall>i. p i \\<in> \\<O>\\<^sub>p) \\<longrightarrow> to_Zp (p \\<bullet> a) k = to_Zp (p \\<bullet> b) k\"\n    proof\n      fix p assume A: \"(\\<And>q. q \\<in> carrier (UP Q\\<^sub>p) \\<Longrightarrow> deg Q\\<^sub>p q < deg Q\\<^sub>p p \\<Longrightarrow> (\\<forall>i. q i \\<in> \\<O>\\<^sub>p) \\<longrightarrow> to_Zp (q \\<bullet> a) k = to_Zp (q \\<bullet> b) k)\"\n                      \"p \\<in> carrier (UP Q\\<^sub>p)\" \"0 < deg Q\\<^sub>p p \" \" \\<forall>i. p i \\<in> \\<O>\\<^sub>p\"\n      obtain q where q_def: \"q \\<in> carrier (UP Q\\<^sub>p) \\<and> deg Q\\<^sub>p q < deg Q\\<^sub>p p \\<and> p = UPQ.ltrm p \\<oplus>\\<^bsub>UP Q\\<^sub>p\\<^esub>q\"\n        by (metis A(2) A(3) UPQ.ltrm_closed UPQ.ltrm_decomp UPQ.UP_a_comm)\n      have 0: \"\\<And>i.  p i = q i \\<oplus> UPQ.ltrm p i\"\n        using q_def A\n        by (metis Qp.a_ac(2) UPQ.ltrm_closed UPQ.UP_car_memE(1) UPQ.cfs_add)\n      have 1: \"\\<forall>i. q i \\<in> \\<O>\\<^sub>p\"\n      proof fix i\n        show \"q i \\<in> \\<O>\\<^sub>p\"\n          apply(cases \"i < deg Q\\<^sub>p p\")\n          using 0[of i] A(4) A(2) q_def\n          using UPQ.ltrm_closed UPQ.P.a_ac(2) UPQ.trunc_cfs UPQ.trunc_closed UPQ.trunc_simps(1)\n           apply (metis Qp.r_zero UPQ.ltrm_cfs UPQ.cfs_closed UPQ.deg_leE)\n          using q_def\n          by (metis (no_types, opaque_lifting) A(2) A(4) UPQ.P.add.m_closed UPQ.coeff_of_sum_diff_degree0 UPQ.deg_leE UPQ.equal_deg_sum UPQ.equal_deg_sum' \\<open>\\<And>thesis. (\\<And>q. q \\<in> carrier (UP Q\\<^sub>p) \\<and> deg Q\\<^sub>p q < deg Q\\<^sub>p p \\<and> p = up_ring.monom (UP Q\\<^sub>p) (p (deg Q\\<^sub>p p)) (deg Q\\<^sub>p p) \\<oplus>\\<^bsub>UP Q\\<^sub>p\\<^esub> q \\<Longrightarrow> thesis) \\<Longrightarrow> thesis\\<close> lessI linorder_neqE_nat)\n      qed\n      have 2: \"UPQ.lcf p \\<in> \\<O>\\<^sub>p\"\n        using A(4) by blast\n      have 3: \"UPQ.ltrm p \\<bullet> a = UPQ.lcf p \\<otimes> a[^] deg Q\\<^sub>p p\"\n        apply(rule UP_cring.to_fun_monom) unfolding UP_cring_def\n          apply (simp add: UPQ.R_cring)\n         apply (simp add: A(2) UPQ.cfs_closed)\n        using assms(3) val_ring_memE(2) by blast\n      have 4: \"UPQ.ltrm p \\<bullet> b = UPQ.lcf p \\<otimes> b[^] deg Q\\<^sub>p p\"\n        apply(rule UP_cring.to_fun_monom) unfolding UP_cring_def\n          apply (simp add: UPQ.R_cring)\n         apply (simp add: A(2) UPQ.cfs_closed)\n        using assms val_ring_memE(2) by blast\n      have p_eq: \"p = q \\<oplus>\\<^bsub>UP Q\\<^sub>p\\<^esub> UPQ.ltrm p\"\n        using q_def by (metis A(2) UPQ.ltrm_closed UPQ.UP_a_comm)\n      have 5: \"p \\<bullet> a = q \\<bullet> a \\<oplus>  UPQ.lcf p \\<otimes> a[^] deg Q\\<^sub>p p\"\n        using assms val_ring_memE(2) p_eq q_def UPQ.to_fun_plus[of q \"UPQ.ltrm p\" a]\n        by (metis \"3\" A(2) UPQ.ltrm_closed UPQ.to_fun_plus)\n      have 6: \"p \\<bullet> b = q \\<bullet> b \\<oplus>  UPQ.lcf p \\<otimes> b[^] deg Q\\<^sub>p p\"\n        using assms val_ring_memE(2) p_eq q_def UPQ.to_fun_plus[of q \"UPQ.ltrm p\" a]\n        by (metis \"4\" A(2) UPQ.ltrm_closed UPQ.to_fun_plus)\n      have 7: \"UPQ.lcf p \\<otimes> b[^] deg Q\\<^sub>p p \\<in> \\<O>\\<^sub>p\"\n        apply(rule val_ring_times_closed)\n        using \"2\" apply linarith\n        by(rule val_ring_nat_pow_closed, rule assms)\n      have 8: \"UPQ.lcf p \\<otimes> a[^] deg Q\\<^sub>p p \\<in> \\<O>\\<^sub>p\"\n        apply(rule val_ring_times_closed)\n        using \"2\" apply linarith\n        by(rule val_ring_nat_pow_closed, rule assms)\n      have 9: \"q \\<bullet> a \\<in> \\<O>\\<^sub>p\"\n        using q_def 1 assms(3) val_ring_poly_eval by blast\n      have 10: \"q \\<bullet> b \\<in> \\<O>\\<^sub>p\"\n        using q_def 1 assms(4) val_ring_poly_eval by blast\n      have 11: \"to_Zp (p \\<bullet> a) = to_Zp (q \\<bullet> a) \\<oplus>\\<^bsub>Z\\<^sub>p\\<^esub> to_Zp (UPQ.ltrm p \\<bullet> a)\"\n        using 5 8 9 to_Zp_add 3 by presburger\n      have 12: \"to_Zp (p \\<bullet> b) = to_Zp (q \\<bullet> b) \\<oplus>\\<^bsub>Z\\<^sub>p\\<^esub> to_Zp (UPQ.ltrm p \\<bullet> b)\"\n        using 6 10 7 to_Zp_add 4  by presburger\n      have 13: \"to_Zp (p \\<bullet> a) k = to_Zp (q \\<bullet> a) k \\<oplus>\\<^bsub>Zp_res_ring k\\<^esub> to_Zp (UPQ.ltrm p \\<bullet> a) k\"\n        unfolding 11 using residue_of_sum by blast\n      have 14: \"to_Zp (p \\<bullet> b) k = to_Zp (q \\<bullet> b) k \\<oplus>\\<^bsub>Zp_res_ring k\\<^esub> to_Zp (UPQ.ltrm p \\<bullet> b) k\"\n        unfolding 12 using residue_of_sum by blast\n      have 15: \"to_Zp (UPQ.ltrm p \\<bullet> a) k = to_Zp (UPQ.ltrm p \\<bullet> b) k\"\n      proof(cases \"k = 0\")\n        case True\n        have T0: \"to_Zp (UPQ.ltrm p \\<bullet> a) \\<in> carrier Z\\<^sub>p\"\n          unfolding 3 using 8  to_Zp_closed val_ring_memE(2) by blast\n        have T1: \"to_Zp (UPQ.ltrm p \\<bullet> b) \\<in> carrier Z\\<^sub>p\"\n          unfolding 4 using 7 to_Zp_closed val_ring_memE(2) by blast\n        show ?thesis unfolding True using T0 T1 padic_integers.p_res_ring_0\n          by (metis p_res_ring_0' residues_closed)\n      next\n        case False\n        have k_pos: \"k > 0\"\n          using False by presburger\n        have 150: \"to_Zp (p (deg Q\\<^sub>p p) \\<otimes> a [^] deg Q\\<^sub>p p) = to_Zp (p (deg Q\\<^sub>p p)) \\<otimes>\\<^bsub>Z\\<^sub>p\\<^esub> to_Zp( a [^] deg Q\\<^sub>p p)\"\n         apply(rule to_Zp_mult)\n          using \"2\" apply blast\n         by(rule val_ring_nat_pow_closed, rule assms)\n        have 151: \"to_Zp (p (deg Q\\<^sub>p p) \\<otimes> b [^] deg Q\\<^sub>p p) = to_Zp (p (deg Q\\<^sub>p p)) \\<otimes>\\<^bsub>Z\\<^sub>p\\<^esub> to_Zp( b [^] deg Q\\<^sub>p p)\"\n         apply(rule to_Zp_mult)\n          using \"2\" apply blast\n         by(rule val_ring_nat_pow_closed, rule assms)\n       have 152: \"to_Zp (p (deg Q\\<^sub>p p) \\<otimes> a [^] deg Q\\<^sub>p p) k = to_Zp (p (deg Q\\<^sub>p p)) k \\<otimes>\\<^bsub>Zp_res_ring k\\<^esub> to_Zp( a [^] deg Q\\<^sub>p p) k\"\n         unfolding 150 using residue_of_prod by blast\n       have 153: \"to_Zp (p (deg Q\\<^sub>p p) \\<otimes> b [^] deg Q\\<^sub>p p) k = to_Zp (p (deg Q\\<^sub>p p)) k \\<otimes>\\<^bsub>Zp_res_ring k\\<^esub> to_Zp( b [^] deg Q\\<^sub>p p) k\"\n         unfolding 151 using residue_of_prod by blast\n       have 154: \"to_Zp( a [^] deg Q\\<^sub>p p) k = to_Zp a k [^]\\<^bsub>Zp_res_ring k\\<^esub> deg Q\\<^sub>p p\"\n       proof-\n       have 01: \"\\<And>m::nat. to_Zp (a[^]m) k = to_Zp a k [^]\\<^bsub>Zp_res_ring k\\<^esub> m\"\n       proof-\n         fix m::nat show \"to_Zp (a [^] m) k = to_Zp a k [^]\\<^bsub>Zp_res_ring k\\<^esub> m\"\n       proof-\n         have 00: \"to_Zp (a[^]m) = to_Zp a [^]\\<^bsub>Z\\<^sub>p\\<^esub> m\"\n         using assms to_Zp_nat_pow[of a \"m\"] by blast\n       have 01: \"to_Zp a \\<in> carrier Z\\<^sub>p\"\n         using assms to_Zp_closed val_ring_memE(2) by blast\n       have 02: \"to_Zp a k \\<in> carrier (Zp_res_ring k)\"\n         using 01 residues_closed by blast\n       have 03: \"cring (Zp_res_ring k)\"\n         using k_pos padic_integers.R_cring padic_integers_axioms by blast\n       have 01: \"(to_Zp a [^]\\<^bsub>Z\\<^sub>p\\<^esub> m) k = (to_Zp a) k [^]\\<^bsub>Zp_res_ring k\\<^esub> m\"\n         apply(induction m)\n         using 01 02 apply (metis Group.nat_pow_0 k_pos residue_of_one(1))\n         using residue_of_prod[of \"to_Zp a [^]\\<^bsub>Z\\<^sub>p\\<^esub> m\" \"to_Zp a\" k] 01 02 03\n       proof -\n         fix ma :: nat\n         assume \"(to_Zp a [^]\\<^bsub>Z\\<^sub>p\\<^esub> ma) k = to_Zp a k [^]\\<^bsub>Zp_res_ring k\\<^esub> ma\"\n         then show \"(to_Zp a [^]\\<^bsub>Z\\<^sub>p\\<^esub> Suc ma) k = to_Zp a k [^]\\<^bsub>Zp_res_ring k\\<^esub> Suc ma\"\n           by (metis (no_types) Group.nat_pow_Suc residue_of_prod)\n       qed\n       show ?thesis unfolding 00 01 by blast\n       qed\n       qed\n       thus ?thesis by blast\n       qed\n       have 155: \"to_Zp( b [^] deg Q\\<^sub>p p) k = to_Zp b k [^]\\<^bsub>Zp_res_ring k\\<^esub> deg Q\\<^sub>p p\"\n         using assms by (metis \"154\" to_Zp_res_of_pow)\n       show ?thesis\n         unfolding 3 4 152 153 154 155 assms by blast\n     qed\n     show \"to_Zp (p \\<bullet> a) k = to_Zp (p \\<bullet> b) k\"\n       unfolding 13 14 15 using A 1 q_def by presburger\n   qed\n  qed\n  thus ?thesis using assms by blast\nqed\n\nlemma to_Zp_poly_eval:\n  assumes \"g \\<in> carrier Q\\<^sub>p_x\"\n  assumes \"gauss_norm g \\<ge> 0\"\n  assumes \"a \\<in> \\<O>\\<^sub>p\"\n  shows \"to_Zp (to_function Q\\<^sub>p g a) = to_function Z\\<^sub>p (to_Zp_poly g) (to_Zp a)\"\nproof-\n  obtain h where h_def: \"h = to_Zp_poly g\"\n    by blast\n  obtain b where b_def: \"b = to_Zp a\"\n    by blast\n  have h_poly_inc: \"poly_inc h = g\"\n    unfolding h_def using assms\n    by (simp add: poly_inc_inverse_left)\n  have b_inc: \"\\<iota> b = a\"\n    unfolding b_def using assms\n    by (simp add: to_Zp_inc)\n  have h_closed: \"h \\<in> carrier (UP Z\\<^sub>p)\"\n    unfolding h_def using assms\n    by (simp add: to_Zp_poly_closed)\n  have b_closed: \"b \\<in> carrier Z\\<^sub>p\"\n    unfolding b_def using assms\n    by (simp add: to_Zp_closed val_ring_memE)\n  have 0: \"to_function Q\\<^sub>p (poly_inc h) (\\<iota> b) = \\<iota> (to_function Z\\<^sub>p h b)\"\n    apply(rule poly_inc_eval)\n    using h_def assms apply (simp add: to_Zp_poly_closed; fail)\n    unfolding b_def using assms\n    by (simp add: to_Zp_closed val_ring_memE)\n  have 1: \"to_Zp (to_function Q\\<^sub>p (poly_inc h) (\\<iota> b)) = to_function Z\\<^sub>p h b\"\n    unfolding 0\n    using h_closed b_closed Zp.to_fun_closed Zp.to_fun_def inc_to_Zp by auto\n  show ?thesis\n    using 1 unfolding h_poly_inc b_inc\n    unfolding h_def b_def by blast\nqed\n\nlemma poly_eval_equal_val:\n  assumes \"g \\<in> carrier (UP Q\\<^sub>p)\"\n  assumes \"\\<And>x. g x \\<in> \\<O>\\<^sub>p\"\n  assumes \"a \\<in> \\<O>\\<^sub>p\"\n  assumes \"b \\<in> \\<O>\\<^sub>p\"\n  assumes \"val (g \\<bullet> a) < eint n\"\n  assumes \"to_Zp a n = to_Zp b n\"\n  shows \"val (g \\<bullet> b) = val (g \\<bullet> a)\"\nproof-\n  have \"(\\<forall>x. g x \\<in> \\<O>\\<^sub>p) \\<longrightarrow> to_Zp (g \\<bullet> b) n = to_Zp (g \\<bullet> a) n\"\n  proof(rule poly_induct[of g])\n    show \"g \\<in> carrier (UP Q\\<^sub>p)\"\n      by (simp add: assms(1))\n    show \"\\<And>p. p \\<in> carrier (UP Q\\<^sub>p) \\<Longrightarrow> deg Q\\<^sub>p p = 0 \\<Longrightarrow> (\\<forall>x. p x \\<in> \\<O>\\<^sub>p) \\<longrightarrow> to_Zp (p \\<bullet> b) n = to_Zp (p \\<bullet> a) n\"\n    proof fix p assume A: \"p \\<in> carrier (UP Q\\<^sub>p)\" \" deg Q\\<^sub>p p = 0 \" \"\\<forall>x. p x \\<in> \\<O>\\<^sub>p \"\n      show \"to_Zp (p \\<bullet> b) n = to_Zp (p \\<bullet> a) n\"\n        using A  by (metis val_ring_memE UPQ.to_fun_ctrm UPQ.trms_of_deg_leq_0 UPQ.trms_of_deg_leq_degree_f assms(3) assms(4))\n    qed\n    show \"\\<And>p. (\\<And>q. q \\<in> carrier (UP Q\\<^sub>p) \\<Longrightarrow> deg Q\\<^sub>p q < deg Q\\<^sub>p p \\<Longrightarrow> (\\<forall>x. q x \\<in> \\<O>\\<^sub>p) \\<longrightarrow> to_Zp (q \\<bullet> b) n = to_Zp (q \\<bullet> a) n) \\<Longrightarrow>\n         p \\<in> carrier (UP Q\\<^sub>p) \\<Longrightarrow> 0 < deg Q\\<^sub>p p \\<Longrightarrow> (\\<forall>x. p x \\<in> \\<O>\\<^sub>p) \\<longrightarrow> to_Zp (p \\<bullet> b) n = to_Zp (p \\<bullet> a) n\"\n    proof fix p assume IH: \"(\\<And>q. q \\<in> carrier (UP Q\\<^sub>p) \\<Longrightarrow> deg Q\\<^sub>p q < deg Q\\<^sub>p p \\<Longrightarrow> (\\<forall>x. q x \\<in> \\<O>\\<^sub>p) \\<longrightarrow> to_Zp (q \\<bullet> b) n = to_Zp (q \\<bullet> a) n)\"\n      assume A: \"p \\<in> carrier (UP Q\\<^sub>p)\" \"0 < deg Q\\<^sub>p p\" \"\\<forall>x. p x \\<in> \\<O>\\<^sub>p\"\n      show \"to_Zp (p \\<bullet> b) n = to_Zp (p \\<bullet> a) n\"\n      proof-\n        obtain q where q_def: \"q \\<in> carrier (UP Q\\<^sub>p) \\<and> deg Q\\<^sub>p q < deg Q\\<^sub>p p \\<and>\n                      p = q \\<oplus>\\<^bsub>UP Q\\<^sub>p\\<^esub> ltrm p\"\n          using A  by (meson UPQ.ltrm_decomp)\n        have p_eq: \"p = q \\<oplus>\\<^bsub>UP Q\\<^sub>p\\<^esub> ltrm p\"\n          using q_def by blast\n        have \"\\<forall>x. q x \\<in> \\<O>\\<^sub>p\" proof fix x\n          have px: \"p x = (q \\<oplus>\\<^bsub>UP Q\\<^sub>p\\<^esub> ltrm p) x\"\n            using p_eq by simp\n          show \"q x \\<in> \\<O>\\<^sub>p\"\n          proof(cases \"x \\<le> deg Q\\<^sub>p q\")\n            case True\n            then have \"p x = q x\"\n              unfolding px using q_def A\n              by (smt UPQ.ltrm_closed UPQ.P.add.right_cancel UPQ.coeff_of_sum_diff_degree0 UPQ.deg_ltrm UPQ.trunc_cfs UPQ.trunc_closed UPQ.trunc_simps(1) less_eq_Suc_le nat_neq_iff not_less_eq_eq)\n            then show ?thesis using A\n              by blast\n          next\n            case False\n            then show ?thesis\n              using q_def UPQ.deg_eqI eq_imp_le nat_le_linear zero_in_val_ring\n              by (metis (no_types, lifting) UPQ.coeff_simp UPQ.deg_belowI)\n          qed\n        qed\n        then have 0: \" to_Zp (q \\<bullet> b) n = to_Zp (q \\<bullet> a) n\"\n          using IH q_def by blast\n        have 1: \"to_Zp (ltrm p \\<bullet> b) n = to_Zp (ltrm p \\<bullet> a) n\"\n        proof-\n          have 10: \"(ltrm p \\<bullet> b) = (p (deg Q\\<^sub>p p)) \\<otimes> b[^] (deg Q\\<^sub>p p)\"\n            using assms A  by (meson val_ring_memE UPQ.to_fun_monom)\n          have 11: \"(ltrm p \\<bullet> a) = (p (deg Q\\<^sub>p p)) \\<otimes> a[^] (deg Q\\<^sub>p p)\"\n            using assms A by (meson val_ring_memE UPQ.to_fun_monom)\n          have 12: \"to_Zp (b[^] (deg Q\\<^sub>p p)) n = to_Zp (a[^] (deg Q\\<^sub>p p)) n\"\n            using to_Zp_res_of_pow assms by metis\n          have 13: \"p (deg Q\\<^sub>p p) \\<in> \\<O>\\<^sub>p\"\n            using A(3) by blast\n          have 14: \"b[^] (deg Q\\<^sub>p p) \\<in> \\<O>\\<^sub>p\"\n            using assms(4) val_ring_nat_pow_closed by blast\n          have 15: \"a[^] (deg Q\\<^sub>p p) \\<in> \\<O>\\<^sub>p\"\n            using assms(3) val_ring_nat_pow_closed by blast\n          have 16: \"(ltrm p \\<bullet> b) \\<in> \\<O>\\<^sub>p\"\n            by (simp add: \"10\" \"13\" \"14\" val_ring_times_closed)\n          have 17: \"to_Zp (ltrm p \\<bullet> b) n = to_Zp (p (deg Q\\<^sub>p p)) n \\<otimes>\\<^bsub>Zp_res_ring n\\<^esub> to_Zp (b[^] (deg Q\\<^sub>p p)) n\"\n            using 10 13 14 15 16 assms residue_of_prod to_Zp_mult by presburger\n          have 18: \"(ltrm p \\<bullet> a) \\<in> \\<O>\\<^sub>p\"\n            by (simp add: \"11\" \"15\" A(3) val_ring_times_closed)\n          have 19: \"to_Zp (ltrm p \\<bullet> a) n = to_Zp (p (deg Q\\<^sub>p p)) n \\<otimes>\\<^bsub>Zp_res_ring n\\<^esub> to_Zp (a[^] (deg Q\\<^sub>p p)) n\"\n            using 10 13 14 15 16 17 18 assms residue_of_prod to_Zp_mult 11  by presburger\n          show ?thesis using 12 17 19 by presburger\n        qed\n        have 2: \"p (deg Q\\<^sub>p p) \\<in> \\<O>\\<^sub>p\"\n          using A(3) by blast\n        have 3: \"(ltrm p \\<bullet> b) \\<in> \\<O>\\<^sub>p\"\n          using 2 assms\n          by (metis A(1) Q\\<^sub>p_def val_ring_memE val_ring_memE UPQ.ltrm_closed Zp_def \\<iota>_def\n              gauss_norm_monom padic_fields.positive_gauss_norm_eval padic_fields_axioms)\n        have 4: \"(ltrm p \\<bullet> a) \\<in> \\<O>\\<^sub>p\"\n          using 2 assms\n          by (metis A(1) Q\\<^sub>p_def val_ring_memE val_ring_memE UPQ.ltrm_closed Zp_def \\<iota>_def\n              gauss_norm_monom padic_fields.positive_gauss_norm_eval padic_fields_axioms)\n        have 5: \"(q \\<bullet> b) \\<in> \\<O>\\<^sub>p\"\n          using  \\<open>\\<forall>x. q x \\<in> \\<O>\\<^sub>p\\<close> assms(4) q_def\n          by (metis gauss_norm_coeff_norm positive_gauss_norm_eval val_ring_memE(1))\n        have 6: \"(q \\<bullet> a) \\<in> \\<O>\\<^sub>p\"\n          using  \\<open>\\<forall>x. q x \\<in> \\<O>\\<^sub>p\\<close> assms(3) q_def\n          by (metis gauss_norm_coeff_norm positive_gauss_norm_eval val_ring_memE(1))\n        have 7: \"to_Zp (p \\<bullet> b) = to_Zp (ltrm p \\<bullet> b)  \\<oplus>\\<^bsub>Z\\<^sub>p\\<^esub> to_Zp (q \\<bullet> b)\"\n          using 5 3 q_def by (metis (no_types, lifting) A(1) val_ring_memE UPQ.ltrm_closed UPQ.to_fun_plus add_comm assms(4) to_Zp_add)\n        have 8: \"to_Zp (p \\<bullet> a) = to_Zp (ltrm p \\<bullet> a)  \\<oplus>\\<^bsub>Z\\<^sub>p\\<^esub> to_Zp (q \\<bullet> a)\"\n          using 4 6 q_def by (metis (no_types, lifting) A(1) val_ring_memE UPQ.ltrm_closed UPQ.to_fun_plus add_comm assms(3) to_Zp_add)\n        have 9: \"to_Zp (p \\<bullet> b) \\<in> carrier Z\\<^sub>p\"\n          using A assms by (meson val_ring_memE UPQ.to_fun_closed to_Zp_closed)\n        have 10: \"to_Zp (p \\<bullet> a) \\<in> carrier Z\\<^sub>p\"\n          using A assms val_ring_memE UPQ.to_fun_closed to_Zp_closed by presburger\n        have 11: \"to_Zp (p \\<bullet> b) n = to_Zp (ltrm p \\<bullet> b) n  \\<oplus>\\<^bsub>Zp_res_ring n\\<^esub> to_Zp (q \\<bullet> b) n\"\n          using 7 9 5 3 residue_of_sum by presburger\n        have 12: \"to_Zp (p \\<bullet> a) n = to_Zp (ltrm p \\<bullet> a) n \\<oplus>\\<^bsub>Zp_res_ring n\\<^esub> to_Zp (q \\<bullet> a) n\"\n          using 8 6 4 residue_of_sum by presburger\n        show ?thesis using 0 11 12 q_def assms\n          using \"1\" by presburger\n      qed\n    qed\n  qed\n  have \"(\\<forall>x. g x \\<in> \\<O>\\<^sub>p) \"\n    using assms by blast\n  hence 0: \"to_Zp (g \\<bullet> b) n = to_Zp (g \\<bullet> a) n\"\n    using \\<open>(\\<forall>x. g x \\<in> \\<O>\\<^sub>p) \\<longrightarrow> to_Zp (g \\<bullet> b) n = to_Zp (g \\<bullet> a) n\\<close> by blast\n  have 1: \"g \\<bullet> a \\<in> \\<O>\\<^sub>p\"\n    using  assms(1) assms(2) assms(3)\n    by (metis gauss_norm_coeff_norm positive_gauss_norm_eval val_ring_memE(1))\n  have 2: \"g \\<bullet> b \\<in> \\<O>\\<^sub>p\"\n    using  assms(1) assms(2) assms(4)\n    by (metis gauss_norm_coeff_norm positive_gauss_norm_eval val_ring_memE(1))\n  have 3: \"val (g \\<bullet> b) < eint n\"\n  proof-\n    have P0: \"to_Zp (g \\<bullet> a) \\<in> carrier Z\\<^sub>p\"\n      using 1 val_ring_memE to_Zp_closed by blast\n    have P1: \"to_Zp (g \\<bullet> b) \\<in> carrier Z\\<^sub>p\"\n      using 2 val_ring_memE to_Zp_closed by blast\n    have P2: \"val_Zp (to_Zp (g \\<bullet> a)) < n\"\n      using 1 assms to_Zp_val by presburger\n    have P3: \"to_Zp (g \\<bullet> a) \\<noteq> \\<zero>\\<^bsub>Z\\<^sub>p\\<^esub>\"\n      using P2 P0 unfolding val_Zp_def     by (metis P2 infinity_ilessE val_Zp_def)\n    have P4: \"(to_Zp (g \\<bullet> a)) n \\<noteq> 0\"\n      using 1 P2 P3 above_ord_nonzero[of \"to_Zp (g \\<bullet> a)\" n]\n      by (metis P0 eint.inject less_eintE val_ord_Zp)\n    then have \"to_Zp (g \\<bullet> b) n \\<noteq> 0\"\n      using 0 by linarith\n    then have \"val_Zp (to_Zp (g \\<bullet> b)) < n\"\n      using P1 P0\n      by (smt below_val_Zp_zero eint_ile eint_ord_simps(1) eint_ord_simps(2) nonzero_imp_ex_nonzero_res residue_of_zero(2) zero_below_val_Zp)\n    then show ?thesis using 2\n      by (metis to_Zp_val)\n  qed\n  thus ?thesis using 0 1 2 assms val_ring_equal_res_imp_equal_val[of \"g \\<bullet> b\" \"g \\<bullet> a\" n] by blast\nqed\n\nlemma to_Zp_poly_monom:\n  assumes \"a \\<in> \\<O>\\<^sub>p\"\n  shows \"to_Zp_poly (monom (UP Q\\<^sub>p) a n) = monom (UP Z\\<^sub>p) (to_Zp a) n\"\n  unfolding to_Zp_poly_def\n  apply(rule ext)\n  using assms cfs_monom[of a n] Zp.cfs_monom[of \"to_Zp a\" n]\n  by (simp add: to_Zp_closed to_Zp_zero val_ring_memE(2))\n\nlemma to_Zp_poly_add:\n  assumes \"f \\<in> carrier (UP Q\\<^sub>p)\"\n  assumes \"gauss_norm f \\<ge> 0\"\n  assumes \"g \\<in> carrier (UP Q\\<^sub>p)\"\n  assumes \"gauss_norm g \\<ge> 0\"\n  shows \"to_Zp_poly (f \\<oplus>\\<^bsub>UP Q\\<^sub>p\\<^esub> g) = to_Zp_poly f \\<oplus>\\<^bsub>UP Z\\<^sub>p\\<^esub> to_Zp_poly g\"\nproof-\n  obtain F where F_def: \"F = to_Zp_poly f\"\n    by blast\n  obtain G where G_def: \"G = to_Zp_poly g\"\n    by blast\n  have F_closed: \"F \\<in> carrier (UP Z\\<^sub>p)\"\n    unfolding F_def using assms\n    by (simp add: to_Zp_poly_closed)\n  have G_closed: \"G \\<in> carrier (UP Z\\<^sub>p)\"\n    unfolding G_def using assms\n    by (simp add: to_Zp_poly_closed)\n  have F_inc: \"poly_inc F = f\"\n    using assms unfolding F_def\n    using poly_inc_inverse_left by blast\n  have G_inc: \"poly_inc G = g\"\n    using assms unfolding G_def\n    by (simp add: poly_inc_inverse_left)\n  have 0: \"poly_inc (F \\<oplus>\\<^bsub>UP Z\\<^sub>p\\<^esub> G) = poly_inc F \\<oplus>\\<^bsub>UP Q\\<^sub>p\\<^esub> poly_inc G\"\n    using F_closed G_closed\n    by (simp add: poly_inc_plus)\n  have 1: \"to_Zp_poly (poly_inc (F \\<oplus>\\<^bsub>UP Z\\<^sub>p\\<^esub> G)) = F \\<oplus>\\<^bsub>UP Z\\<^sub>p\\<^esub> G\"\n    using G_closed F_closed\n    by (simp add: poly_inc_inverse_right)\n  show ?thesis\n    using  1 unfolding F_inc G_inc 0 unfolding F_def G_def\n    by blast\nqed\n\nlemma to_Zp_poly_zero:\n\"to_Zp_poly (\\<zero>\\<^bsub>UP Q\\<^sub>p\\<^esub>) = \\<zero>\\<^bsub>UP Z\\<^sub>p\\<^esub>\"\n  unfolding to_Zp_poly_def\n  apply(rule ext)\n  by (simp add: to_Zp_zero)\n\nlemma to_Zp_poly_one:\n\"to_Zp_poly (\\<one>\\<^bsub>UP Q\\<^sub>p\\<^esub>) = \\<one>\\<^bsub>UP Z\\<^sub>p\\<^esub>\"\n  unfolding to_Zp_poly_def\n  apply(rule ext)\n  by (metis Zp.UP_one_closed poly_inc_inverse_right poly_inc_one to_Zp_poly_def)\n\nlemma val_ring_add_pow:\n  assumes \"a \\<in> carrier Q\\<^sub>p\"\n  assumes \"val a \\<ge> 0\"\n  shows \"val ([(n::nat)]\\<cdot>a) \\<ge> 0\"\nproof-\n  have 0: \"[(n::nat)]\\<cdot>a = ([n]\\<cdot>\\<one>)\\<otimes>a\"\n    using assms Qp.add_pow_ldistr Qp.cring_simprules(12) Qp.one_closed by presburger\n  show ?thesis unfolding 0 using assms\n    by (meson Qp.nat_inc_closed val_ring_memE val_of_nat_inc val_ringI val_ring_times_closed)\nqed\n\nlemma to_Zp_poly_pderiv:\n  assumes \"g \\<in> carrier (UP Q\\<^sub>p)\"\n  assumes \"gauss_norm g \\<ge> 0\"\n  shows \"to_Zp_poly (pderiv g) = Zp.pderiv (to_Zp_poly g)\"\nproof-\n  have 0: \"gauss_norm g \\<ge> 0 \\<longrightarrow> to_Zp_poly (pderiv g) = Zp.pderiv (to_Zp_poly g)\"\n  proof(rule poly_induct, rule assms, rule)\n    fix p\n    assume A: \" p \\<in> carrier (UP Q\\<^sub>p)\"\n         \"deg Q\\<^sub>p p = 0\"\n         \"0 \\<le> gauss_norm p\"\n    obtain a where a_def: \"a \\<in> \\<O>\\<^sub>p \\<and> p = monom (UP Q\\<^sub>p) a 0\"\n      using A\n      by (metis UPQ.ltrm_deg_0 positive_gauss_norm_valuation_ring_coeffs)\n    have p_eq: \"p = monom (UP Q\\<^sub>p) a 0\"\n      using a_def by blast\n    have 0: \"to_Zp_poly p = monom (UP Z\\<^sub>p) (to_Zp a) 0\"\n      unfolding p_eq\n      apply(rule to_Zp_poly_monom)\n      using a_def by blast\n    have 1: \"UPQ.pderiv (monom (UP Q\\<^sub>p) a 0) = \\<zero>\\<^bsub>UP Q\\<^sub>p\\<^esub>\"\n      using A(1) A(2) UPQ.pderiv_deg_0 p_eq by blast\n    have 2: \"Zp.pderiv (monom (UP Z\\<^sub>p) (to_Zp a) 0) = \\<zero>\\<^bsub>UP Z\\<^sub>p\\<^esub>\"\n      apply(rule Zp.pderiv_deg_0)\n       apply(rule Zp.monom_closed, rule to_Zp_closed)\n      using a_def\n       apply (simp add: val_ring_memE(2); fail)\n      apply(cases \"to_Zp a = \\<zero>\\<^bsub>Z\\<^sub>p\\<^esub>\")\n      apply (simp; fail)\n      apply(rule Zp.deg_monom, blast)\n      using a_def\n      by (simp add: to_Zp_closed val_ring_memE(2))\n    show \"to_Zp_poly (UPQ.pderiv p) = Zp.pderiv (to_Zp_poly p)\"\n      unfolding 0 unfolding p_eq\n      unfolding 1 2 to_Zp_poly_zero by blast\n  next\n    fix p\n    assume A: \"\\<And>q. q \\<in> carrier (UP Q\\<^sub>p) \\<Longrightarrow>\n              deg Q\\<^sub>p q < deg Q\\<^sub>p p \\<Longrightarrow>\n              0 \\<le> gauss_norm q \\<longrightarrow>\n              to_Zp_poly (UPQ.pderiv q) = Zp.pderiv (to_Zp_poly q)\"\n              \"p \\<in> carrier (UP Q\\<^sub>p)\"\n              \" 0 < deg Q\\<^sub>p p\"\n    show \"0 \\<le> gauss_norm p \\<longrightarrow> to_Zp_poly (UPQ.pderiv p) = Zp.pderiv (to_Zp_poly p)\"\n    proof\n      assume B: \"0 \\<le> gauss_norm p\"\n      obtain q where q_def: \"q = trunc p\"\n        by blast\n      have p_eq: \"p = q \\<oplus>\\<^bsub>UP Q\\<^sub>p\\<^esub> ltrm p\"\n        by (simp add: A(2) UPQ.trunc_simps(1) q_def)\n      have q_gauss_norm:    \"gauss_norm q \\<ge> 0\"\n        unfolding q_def\n        apply(rule gauss_norm_geqI)\n        using A apply (simp add: UPQ.trunc_closed; fail)\n        using trunc_cfs[of p] A gauss_normE\n      proof -\n        fix n :: nat\n        have f1: \"\\<zero> = q (deg Q\\<^sub>p p)\"\n          by (simp add: UPQ.deg_leE UPQ.trunc_closed UPQ.trunc_degree \\<open>0 < deg Q\\<^sub>p p\\<close> \\<open>p \\<in> carrier (UP Q\\<^sub>p)\\<close> q_def)\n        have \"\\<forall>n. 0 \\<le> val (p n)\"\n          by (meson B \\<open>p \\<in> carrier (UP Q\\<^sub>p)\\<close> eint_ord_trans gauss_normE)\n        then show \"0 \\<le> val (Cring_Poly.truncate Q\\<^sub>p p n)\"\n          using f1 by (metis (no_types) Qp.nat_mult_zero UPQ.ltrm_closed UPQ.coeff_of_sum_diff_degree0 UPQ.deg_ltrm UPQ.trunc_closed \\<open>\\<And>n. \\<lbrakk>p \\<in> carrier (UP Q\\<^sub>p); n < deg Q\\<^sub>p p\\<rbrakk> \\<Longrightarrow> Cring_Poly.truncate Q\\<^sub>p p n = p n\\<close> \\<open>p \\<in> carrier (UP Q\\<^sub>p)\\<close> nat_neq_iff p_eq q_def val_of_nat_inc)\n      qed\n      have 0: \"to_Zp_poly (UPQ.pderiv q) = Zp.pderiv (to_Zp_poly q)\"\n        using A q_def q_gauss_norm\n        by (simp add: UPQ.trunc_closed UPQ.trunc_degree)\n      have 1: \"UPQ.pderiv (monom (UP Q\\<^sub>p) (p (deg Q\\<^sub>p p)) (deg Q\\<^sub>p p)) =\n               monom (UP Q\\<^sub>p) ([deg Q\\<^sub>p p] \\<cdot> p (deg Q\\<^sub>p p)) (deg Q\\<^sub>p p - 1)\"\n        apply(rule pderiv_monom)\n        using A by (simp add: UPQ.UP_car_memE(1))\n      have 2: \"Zp.pderiv (monom (UP Z\\<^sub>p) (to_Zp (p (deg Q\\<^sub>p p))) (deg Q\\<^sub>p p)) =\n    monom (UP Z\\<^sub>p) ([deg Q\\<^sub>p p] \\<cdot>\\<^bsub>Z\\<^sub>p\\<^esub> to_Zp ( p (deg Q\\<^sub>p p))) (deg Q\\<^sub>p p - 1)\"\n        using A  Zp.pderiv_monom[of \"to_Zp ( p (deg Q\\<^sub>p p))\" \"deg Q\\<^sub>p p\"]\n        by (simp add: UPQ.lcf_closed to_Zp_closed)\n      have 3: \"to_Zp_poly (UPQ.pderiv (monom (UP Q\\<^sub>p) (p (deg Q\\<^sub>p p)) (deg Q\\<^sub>p p))) = monom (UP Z\\<^sub>p) (to_Zp ([deg Q\\<^sub>p p] \\<cdot> p (deg Q\\<^sub>p p))) (deg Q\\<^sub>p p - 1)\"\n        unfolding 1 apply(rule to_Zp_poly_monom)\n        apply(rule val_ring_memI)\n         apply (simp add: A(2) UPQ.UP_car_memE(1); fail)\n        apply(rule val_ring_add_pow)\n        using A\n        apply (simp add: UPQ.lcf_closed; fail)\n        using B A\n        by (simp add: positive_gauss_norm_valuation_ring_coeffs val_ring_memE(1))\n      have 4: \"to_Zp_poly (ltrm p) = monom (UP Z\\<^sub>p) (to_Zp (p (deg Q\\<^sub>p p))) (deg Q\\<^sub>p p)\"\n        apply(rule to_Zp_poly_monom) using A\n        by (simp add: B positive_gauss_norm_valuation_ring_coeffs)\n      have 5: \"to_Zp_poly (UPQ.pderiv (ltrm p)) = Zp.pderiv (to_Zp_poly (ltrm p))\"\n        unfolding 3 4 2\n        by (simp add: A(2) B positive_gauss_norm_valuation_ring_coeffs to_Zp_nat_add_pow)\n      have 6: \"pderiv p = pderiv q \\<oplus>\\<^bsub>UP Q\\<^sub>p\\<^esub> pderiv (ltrm p)\"\n        using p_eq\n        by (metis A(2) UPQ.ltrm_closed UPQ.pderiv_add UPQ.trunc_closed p_eq q_def)\n      have 7: \"to_Zp_poly p = to_Zp_poly q \\<oplus>\\<^bsub>UP Z\\<^sub>p\\<^esub> to_Zp_poly (ltrm p)\"\n        using p_eq\n        by (metis (no_types, lifting) A(2) B UPQ.ltrm_closed UPQ.cfs_closed UPQ.trunc_closed gauss_norm_monom positive_gauss_norm_valuation_ring_coeffs q_def q_gauss_norm to_Zp_poly_add val_ring_memE(1))\n      have 8: \"to_Zp_poly  (pderiv p) =\n                to_Zp_poly (UPQ.pderiv q) \\<oplus>\\<^bsub>UP Z\\<^sub>p\\<^esub>\n                 to_Zp_poly (UPQ.pderiv (monom (UP Q\\<^sub>p) (p (deg Q\\<^sub>p p)) (deg Q\\<^sub>p p)))\"\n        unfolding 6 apply(rule to_Zp_poly_add)\n           apply (simp add: A(2) UPQ.pderiv_closed UPQ.trunc_closed q_def; fail)\n          apply (metis A(2) UPQ.cfs_closed UPQ.pderiv_cfs UPQ.trunc_closed gauss_norm_coeff_norm positive_gauss_norm_valuation_ring_coeffs q_def q_gauss_norm val_ring_add_pow val_ring_memE(1))\n         apply (simp add: A(2) UPQ.UP_car_memE(1) UPQ.pderiv_closed; fail)\n        apply(rule eint_ord_trans[of _ \"gauss_norm (monom (UP Q\\<^sub>p) (p (deg Q\\<^sub>p p)) (deg Q\\<^sub>p p))\"])\n        apply (simp add: A(2) B UPQ.cfs_closed gauss_norm_monom positive_gauss_norm_valuation_ring_coeffs val_ring_memE(1); fail)\n        apply(rule gauss_norm_pderiv)\n        using A(2) UPQ.ltrm_closed by blast\n      have 9: \"Zp.pderiv  (to_Zp_poly p) =  Zp.pderiv (to_Zp_poly q) \\<oplus>\\<^bsub>UP Z\\<^sub>p\\<^esub>\n         Zp.pderiv (to_Zp_poly (monom (UP Q\\<^sub>p) (p (deg Q\\<^sub>p p)) (deg Q\\<^sub>p p)))\"\n          unfolding 7 apply(rule Zp.pderiv_add)\n           apply(rule to_Zp_poly_closed)\n            apply (simp add: A(2) UPQ.trunc_closed q_def; fail)\n           apply (simp add: q_gauss_norm; fail)\n           apply(rule to_Zp_poly_closed)\n           apply (simp add: A(2) UPQ.UP_car_memE(1); fail)\n          by (simp add: A(2) B UPQ.cfs_closed gauss_norm_monom positive_gauss_norm_valuation_ring_coeffs val_ring_memE(1))\n      show \"to_Zp_poly (UPQ.pderiv p) = Zp.pderiv (to_Zp_poly p)\"\n          unfolding 9 8 5 0 by blast\n    qed\n  qed\n  thus ?thesis using assms by blast\nqed\n\nlemma val_p_int_pow:\n\"val (\\<pp>[^]k) = eint (k)\"\n  by (simp add: ord_p_pow_int p_intpow_closed(2))\n\ndefinition int_gauss_norm where\n\"int_gauss_norm g = (SOME n::int. eint n = gauss_norm g)\"\n\nlemma int_gauss_norm_eq:\n  assumes \"g \\<in> carrier (UP Q\\<^sub>p)\"\n  assumes \"g \\<noteq> \\<zero>\\<^bsub>UP Q\\<^sub>p\\<^esub>\"\n  shows \"eint (int_gauss_norm g) = gauss_norm g\"\nproof-\n  have 0: \"gauss_norm g < \\<infinity>\"\n    using assms by (simp add: gauss_norm_prop)\n  then show ?thesis unfolding int_gauss_norm_def\n    using assms\n    by fastforce\nqed\n\nlemma int_gauss_norm_smult:\n  assumes \"g \\<in> carrier (UP Q\\<^sub>p)\"\n  assumes \"g \\<noteq> \\<zero>\\<^bsub>UP Q\\<^sub>p\\<^esub>\"\n  assumes \"a \\<in> nonzero Q\\<^sub>p\"\n  shows \"int_gauss_norm (a \\<odot>\\<^bsub>UP Q\\<^sub>p\\<^esub> g) = ord a + int_gauss_norm g\"\n  using gauss_norm_smult[of g a] int_gauss_norm_eq val_ord assms\n  by (metis (no_types, opaque_lifting) Qp.nonzero_closed UPQ.UP_smult_closed UPQ.cfs_zero\n      eint.distinct(2) eint.inject gauss_norm_coeff_norm local.val_zero plus_eint_simps(1))\n\ndefinition normalize_poly where\n\"normalize_poly g = (if g = \\<zero>\\<^bsub>UP Q\\<^sub>p\\<^esub> then g else (\\<pp>[^](- int_gauss_norm g)) \\<odot>\\<^bsub>Q\\<^sub>p_x\\<^esub> g)\"\n\nlemma normalize_poly_zero:\n\"normalize_poly \\<zero>\\<^bsub>UP Q\\<^sub>p\\<^esub> = \\<zero>\\<^bsub>UP Q\\<^sub>p\\<^esub>\"\n  unfolding normalize_poly_def by simp\n\nlemma normalize_poly_nonzero_eq:\n  assumes \"g \\<noteq> \\<zero>\\<^bsub>UP Q\\<^sub>p\\<^esub>\"\n  assumes \"g \\<in> carrier (UP Q\\<^sub>p)\"\n  shows \"normalize_poly g = (\\<pp>[^](- int_gauss_norm g)) \\<odot>\\<^bsub>UP Q\\<^sub>p\\<^esub> g\"\n  using assms unfolding normalize_poly_def by simp\n\nlemma int_gauss_norm_normalize_poly:\n  assumes \"g \\<noteq> \\<zero>\\<^bsub>UP Q\\<^sub>p\\<^esub>\"\n  assumes \"g \\<in> carrier (UP Q\\<^sub>p)\"\n  shows \"int_gauss_norm (normalize_poly g) = 0\"\n  using normalize_poly_nonzero_eq int_gauss_norm_smult assms\n  by (simp add: ord_p_pow_int p_intpow_closed(2))\n\nlemma normalize_poly_closed:\n  assumes \"g \\<in> carrier (UP Q\\<^sub>p)\"\n  shows \"normalize_poly g \\<in> carrier (UP Q\\<^sub>p)\"\n  using assms unfolding normalize_poly_def\n  by (simp add: p_intpow_closed(1))\n\nlemma normalize_poly_nonzero:\n  assumes \"g \\<noteq> \\<zero>\\<^bsub>UP Q\\<^sub>p\\<^esub>\"\n  assumes \"g \\<in> carrier (UP Q\\<^sub>p)\"\n  shows \"normalize_poly g \\<noteq> \\<zero>\\<^bsub>UP Q\\<^sub>p\\<^esub>\"\n  using assms normalize_poly_nonzero_eq\n  by (metis (no_types, lifting) UPQ.UP_smult_one UPQ.module_axioms UPQ.smult_r_null module.smult_assoc1 p_intpow_closed(1) p_intpow_inv')\n\nlemma gauss_norm_normalize_poly:\n  assumes \"g \\<noteq> \\<zero>\\<^bsub>UP Q\\<^sub>p\\<^esub>\"\n  assumes \"g \\<in> carrier (UP Q\\<^sub>p)\"\n  shows \"gauss_norm (normalize_poly g) = 0\"\nproof-\n  have 0: \"eint (int_gauss_norm (normalize_poly g)) = gauss_norm (normalize_poly g)\"\n    by(rule int_gauss_norm_eq, rule normalize_poly_closed, rule assms,\n          rule normalize_poly_nonzero, rule assms, rule assms)\n  show ?thesis\n    using 0 int_gauss_norm_normalize_poly assms\n    by (simp add: zero_eint_def)\nqed\n\nlemma taylor_term_eval_eq:\n  assumes \"f \\<in> carrier (UP Q\\<^sub>p)\"\n  assumes \"x \\<in> carrier Q\\<^sub>p\"\n  assumes \"t \\<in> carrier Q\\<^sub>p\"\n  assumes \"\\<And>j. i \\<noteq> j \\<Longrightarrow> val (UPQ.taylor_term x f i \\<bullet> t) < val (UPQ.taylor_term x f j \\<bullet> t) \"\n  shows \"val (f \\<bullet> t) = val (UPQ.taylor_term x f i \\<bullet> t)\"\nproof-\n  have 0: \"f = finsum (UP Q\\<^sub>p) (UPQ.taylor_term x f) {..deg Q\\<^sub>p f}\"\n    by(rule UPQ.taylor_term_sum[of f \"deg Q\\<^sub>p f\" x], rule assms, blast, rule assms)\n  show ?thesis\n  proof(cases \"i \\<in> {..deg Q\\<^sub>p f}\")\n    case True\n    have T0: \"finsum (UP Q\\<^sub>p) (UPQ.taylor_term x f) {..deg Q\\<^sub>p f} = UPQ.taylor_term x f i \\<oplus>\\<^bsub>UP Q\\<^sub>p\\<^esub> finsum (UP Q\\<^sub>p) (UPQ.taylor_term x f) ({..deg Q\\<^sub>p f} - {i})\"\n      apply(rule UPQ.P.finsum_remove[of \"{..deg Q\\<^sub>p f}\" \"UPQ.taylor_term x f\" i])\n      by(rule UPQ.taylor_term_closed, rule assms, rule assms, blast, rule True)\n    have T1: \"f = UPQ.taylor_term x f i \\<oplus>\\<^bsub>UP Q\\<^sub>p\\<^esub> finsum (UP Q\\<^sub>p) (UPQ.taylor_term x f) ({..deg Q\\<^sub>p f} - {i})\"\n      using 0 T0 by metis\n    have T2: \"finsum (UP Q\\<^sub>p) (UPQ.taylor_term x f) ({..deg Q\\<^sub>p f} - {i}) \\<in> carrier (UP Q\\<^sub>p)\"\n      apply(rule UPQ.P.finsum_closed)\n      using UPQ.taylor_term_closed assms(1) assms(2) by blast\n    have T3: \"UPQ.taylor_term x f i \\<in> carrier (UP Q\\<^sub>p)\"\n      by(rule UPQ.taylor_term_closed, rule assms, rule assms )\n    obtain g where g_def: \"g = f\"\n      by blast\n    have T4: \"g = UPQ.taylor_term x f i \\<oplus>\\<^bsub>UP Q\\<^sub>p\\<^esub> finsum (UP Q\\<^sub>p) (UPQ.taylor_term x f) ({..deg Q\\<^sub>p f} - {i})\"\n      unfolding g_def by(rule T1)\n    have g_closed: \"g \\<in> carrier (UP Q\\<^sub>p)\"\n      unfolding g_def by(rule assms)\n    have T5: \"g \\<bullet> t = UPQ.taylor_term x f i \\<bullet> t \\<oplus> ( finsum (UP Q\\<^sub>p) (UPQ.taylor_term x f) ({..deg Q\\<^sub>p f} - {i})) \\<bullet> t\"\n      unfolding T4 by(rule UPQ.to_fun_plus, rule T2, rule T3, rule assms)\n    have T6: \"( finsum (UP Q\\<^sub>p) (UPQ.taylor_term x f) ({..deg Q\\<^sub>p f} - {i})) \\<bullet> t =\n                ( finsum Q\\<^sub>p (\\<lambda>i. UPQ.taylor_term x f i \\<bullet> t) ({..deg Q\\<^sub>p f} - {i}))\"\n      apply(rule UPQ.to_fun_finsum, blast)\n      using assms UPQ.taylor_term_closed apply blast\n      using assms by blast\n    have T7: \"\\<And>j. j \\<in> {..deg Q\\<^sub>p f} - {i} \\<Longrightarrow> val (UPQ.taylor_term x f j \\<bullet> t) > val (UPQ.taylor_term x f i \\<bullet> t)\"\n      using assms  by (metis Diff_iff singletonI)\n    have T8: \"val (( finsum (UP Q\\<^sub>p) (UPQ.taylor_term x f) ({..deg Q\\<^sub>p f} - {i})) \\<bullet> t) > val (UPQ.taylor_term x f i \\<bullet> t)\"\n      unfolding T6\n      apply(rule finsum_val_ultrametric'')\n      using UPQ.taylor_term_closed assms\n      apply (metis (no_types, lifting) Pi_I UPQ.to_fun_closed)\n        apply blast\n      using assms T7 apply blast\n      using assms(4)[of \"Suc i\"] using eint_ord_simps(4)\n        assms(4) eint_ord_code(6)  g_def gr_implies_not_zero less_one by smt\n    have T9: \"val (g \\<bullet> t) =  val (UPQ.taylor_term x f i \\<bullet> t)\"\n      unfolding T5 using T8 T2 T3\n      by (metis (no_types, lifting) Qp.add.m_comm UPQ.to_fun_closed assms(3) val_ultrametric_noteq)\n    show ?thesis using T9 unfolding g_def by blast\n  next\n    case False\n    have \"i > deg Q\\<^sub>p f\"\n      using False by simp\n    hence \"i > deg Q\\<^sub>p (UPQ.taylor x f)\"\n      using assms UPQ.taylor_deg by presburger\n    hence F0: \"UPQ.taylor x f i = \\<zero>\"\n      using assms UPQ.taylor_closed UPQ.deg_leE by blast\n    have F1: \"(UPQ.taylor_term x f i \\<bullet> t) = \\<zero>\"\n      using UPQ.to_fun_taylor_term[of f t x i]\n      unfolding F0\n      using assms Qp.cring_simprules(2) Qp.cring_simprules(4) Qp.integral_iff Qp.nat_pow_closed by presburger\n    show ?thesis\n      using assms(4)[of \"Suc i\"] unfolding F1\n      by (metis eint_ord_code(6) local.val_zero n_not_Suc_n)\n  qed\nqed\n\n\n(**************************************************************************************************)\n(**************************************************************************************************)\nsubsection\\<open>Hensel's Lemma for \\<open>p\\<close>-adic fields\\<close>\n(**************************************************************************************************)\n(**************************************************************************************************)\n\ntheorem hensels_lemma:\n  assumes \"f \\<in> carrier (UP Q\\<^sub>p)\"\n  assumes \"a \\<in> \\<O>\\<^sub>p\"\n  assumes \"gauss_norm f \\<ge> 0\"\n  assumes \"val (f\\<bullet>a) > 2*val ((pderiv f)\\<bullet>a)\"\n  shows \"\\<exists>!\\<alpha> \\<in> \\<O>\\<^sub>p. f\\<bullet>\\<alpha> = \\<zero> \\<and> val (a \\<ominus> \\<alpha>) > val ((pderiv f)\\<bullet>a)\"\nproof-\n  have a_closed: \"a \\<in> carrier Q\\<^sub>p\"\n    using assms val_ring_memE by auto\n  have f_nonzero: \"f \\<noteq> \\<zero>\\<^bsub>UP Q\\<^sub>p\\<^esub>\"\n  proof(rule ccontr)\n    assume N: \"\\<not> f \\<noteq> \\<zero>\\<^bsub>UP Q\\<^sub>p\\<^esub>\"\n    then have 0: \"pderiv f = \\<zero>\\<^bsub>UP Q\\<^sub>p\\<^esub>\"\n      using UPQ.deg_zero UPQ.pderiv_deg_0 by blast\n    have 1: \"f = \\<zero>\\<^bsub>UP Q\\<^sub>p\\<^esub>\"\n      using N by auto\n    have 2: \"eint 2 * val (UPQ.pderiv \\<zero>\\<^bsub>UP Q\\<^sub>p\\<^esub> \\<bullet> a) = \\<infinity>\"\n      by (simp add: UPQ.to_fun_zero local.a_closed local.val_zero)\n    show False using assms a_closed\n      unfolding 2 1\n      using eint_ord_simps(6) by blast\n  qed\n  obtain h where h_def: \"h = to_Zp_poly f\"\n    by blast\n  have h_closed: \"h \\<in> carrier (UP Z\\<^sub>p)\"\n    unfolding h_def using assms\n    by (simp add: to_Zp_poly_closed)\n  have h_deriv: \"Zp.pderiv h = to_Zp_poly (pderiv f)\"\n    unfolding h_def\n    using to_Zp_poly_pderiv[of f] assms by auto\n  have 0: \"to_Zp (f\\<bullet>a) = to_function Z\\<^sub>p h (to_Zp a)\"\n    unfolding h_def\n    using assms a_closed\n    by (simp add: UPQ.to_fun_def to_Zp_poly_eval)\n  have 1: \"to_Zp ((pderiv f)\\<bullet>a) = to_function Z\\<^sub>p (Zp.pderiv h) (to_Zp a)\"\n    unfolding h_deriv\n    using assms a_closed  UPQ.pderiv_closed UPQ.to_fun_def eint_ord_trans gauss_norm_pderiv to_Zp_poly_eval\n    by presburger\n  have 2: \"val (f\\<bullet>a) = val_Zp (to_function Z\\<^sub>p h (to_Zp a))\"\n  proof-\n    have 20: \"f\\<bullet>a \\<in> \\<O>\\<^sub>p\"\n      using assms positive_gauss_norm_eval by blast\n    have 21: \"val (f\\<bullet>a) = val_Zp (to_Zp (f\\<bullet>a))\"\n      using 20 by (simp add: to_Zp_val)\n    show ?thesis unfolding 21 0 by blast\n  qed\n  have 3: \"val ((pderiv f)\\<bullet>a) = val_Zp ( to_function Z\\<^sub>p (Zp.pderiv h) (to_Zp a))\"\n  proof-\n    have 30: \"(pderiv f)\\<bullet>a \\<in> \\<O>\\<^sub>p\"\n      using positive_gauss_norm_eval assms gauss_norm_pderiv\n      by (meson UPQ.pderiv_closed eint_ord_trans)\n    have 31: \"val ((pderiv f)\\<bullet>a) = val_Zp (to_Zp ((pderiv f)\\<bullet>a))\"\n      using 30 by (simp add: to_Zp_val)\n    show ?thesis unfolding 31 1 by blast\n  qed\n  have 4: \"\\<exists>!\\<alpha>. \\<alpha> \\<in> carrier Z\\<^sub>p \\<and>\n        Zp.to_fun (to_Zp_poly f) \\<alpha> = \\<zero>\\<^bsub>Z\\<^sub>p\\<^esub> \\<and>\n        val_Zp (Zp.to_fun (Zp.pderiv (to_Zp_poly f)) (to_Zp a))\n        < val_Zp (to_Zp a \\<ominus>\\<^bsub>Z\\<^sub>p\\<^esub> \\<alpha>)\"\n    apply(rule hensels_lemma')\n    using h_closed h_def apply blast\n    using assms local.a_closed to_Zp_closed apply blast\n    using assms unfolding 2 3 h_def Zp.to_fun_def by blast\n  obtain \\<alpha> where \\<alpha>_def: \"\\<alpha> \\<in> carrier Z\\<^sub>p \\<and>\n        Zp.to_fun (to_Zp_poly f) \\<alpha> = \\<zero>\\<^bsub>Z\\<^sub>p\\<^esub> \\<and>\n        val_Zp (Zp.to_fun (Zp.pderiv (to_Zp_poly f)) (to_Zp a))\n        < val_Zp (to_Zp a \\<ominus>\\<^bsub>Z\\<^sub>p\\<^esub> \\<alpha>)\n        \\<and> (\\<forall>x.  x \\<in> carrier Z\\<^sub>p \\<and>\n        Zp.to_fun (to_Zp_poly f) x = \\<zero>\\<^bsub>Z\\<^sub>p\\<^esub> \\<and>\n        val_Zp (Zp.to_fun (Zp.pderiv (to_Zp_poly f)) (to_Zp a))\n        < val_Zp (to_Zp a \\<ominus>\\<^bsub>Z\\<^sub>p\\<^esub> x) \\<longrightarrow> x = \\<alpha>)\"\n    using 4 by blast\n  obtain \\<beta> where \\<beta>_def: \"\\<beta> = \\<iota> \\<alpha>\"\n    by blast\n  have \\<beta>_closed: \"\\<beta> \\<in> \\<O>\\<^sub>p\"\n    using \\<alpha>_def unfolding \\<beta>_def by simp\n  have 5: \"(Zp.to_fun (to_Zp_poly f) \\<alpha>) = to_Zp (f\\<bullet>\\<beta>)\"\n    using \\<beta>_closed to_Zp_poly_eval[of f \\<beta>] assms\n    unfolding \\<beta>_def UPQ.to_fun_def\n    by (simp add: Zp.to_fun_def \\<alpha>_def inc_to_Zp)\n  have 6: \"to_Zp (f\\<bullet>\\<beta>) = \\<zero>\\<^bsub>Z\\<^sub>p\\<^esub>\"\n    using 5 \\<alpha>_def by auto\n  have \\<beta>_closed: \"\\<beta> \\<in> \\<O>\\<^sub>p\"\n    unfolding \\<beta>_def using \\<alpha>_def  by simp\n  have 7: \"(f\\<bullet>\\<beta>) = \\<zero>\"\n    using 6 assms unfolding \\<beta>_def\n    by (metis \\<beta>_closed \\<beta>_def inc_of_zero positive_gauss_norm_eval to_Zp_inc)\n  have 8: \"\\<alpha> = to_Zp \\<beta>\"\n    unfolding \\<beta>_def using \\<alpha>_def\n    by (simp add: inc_to_Zp)\n  have 9: \"to_Zp a \\<ominus>\\<^bsub>Z\\<^sub>p\\<^esub> \\<alpha> = to_Zp (a \\<ominus> \\<beta>)\"\n    unfolding 8 using assms(2) \\<beta>_closed\n    by (simp add: to_Zp_minus)\n  have 10: \"val (a \\<ominus> \\<beta>) = val_Zp (to_Zp a \\<ominus>\\<^bsub>Z\\<^sub>p\\<^esub> \\<alpha>)\"\n    unfolding 9 using \\<beta>_closed assms(2)\n    to_Zp_val val_ring_minus_closed by presburger\n  have 11: \"val (a \\<ominus> \\<beta>) > val ((pderiv f)\\<bullet>a)\"\n    using \\<alpha>_def unfolding 9 10 3 h_def\n    by (simp add: Zp.to_fun_def)\n  have 12: \"\\<beta> \\<in> \\<O>\\<^sub>p \\<and> f \\<bullet> \\<beta> = \\<zero> \\<and> val (UPQ.pderiv f \\<bullet> a) < val (a \\<ominus> \\<beta>)\"\n    using \"11\" \"7\" \\<beta>_closed by linarith\n  have 13: \"\\<forall>x. x\\<in> \\<O>\\<^sub>p \\<and> f \\<bullet> x = \\<zero> \\<and> val (UPQ.pderiv f \\<bullet> a) < val (a \\<ominus> x)\n            \\<longrightarrow> x = \\<beta>\"\n  proof(rule, rule)\n    fix x assume A: \"x \\<in> \\<O>\\<^sub>p \\<and>  f \\<bullet> x = \\<zero> \\<and> val (UPQ.pderiv f \\<bullet> a) < val (a \\<ominus> x)\"\n    obtain y where y_def: \"y = to_Zp x\"\n      by blast\n    have y_closed: \"y \\<in> carrier Z\\<^sub>p\"\n      unfolding y_def using A\n      by (simp add: to_Zp_closed val_ring_memE(2))\n    have eval: \"Zp.to_fun (to_Zp_poly f) y = \\<zero>\\<^bsub>Z\\<^sub>p\\<^esub>\"\n      unfolding y_def using A assms\n      by (metis UPQ.to_fun_def Zp.to_fun_def to_Zp_poly_eval to_Zp_zero)\n    have 0: \"to_Zp a \\<ominus>\\<^bsub>Z\\<^sub>p\\<^esub> y = to_Zp (a \\<ominus> x)\"\n      unfolding y_def using A assms\n      by (simp add: to_Zp_minus)\n    have q: \" val_Zp (Zp.to_fun (Zp.pderiv (to_Zp_poly f)) (to_Zp a)) = val (UPQ.pderiv f \\<bullet> a)\"\n      by (simp add: \"3\" Zp.to_fun_def h_def)\n    have 1: \"y \\<in> carrier Z\\<^sub>p \\<and>\n        Zp.to_fun (to_Zp_poly f) y = \\<zero>\\<^bsub>Z\\<^sub>p\\<^esub> \\<and>\n        val_Zp (Zp.to_fun (Zp.pderiv (to_Zp_poly f)) (to_Zp a))\n        < val_Zp (to_Zp a \\<ominus>\\<^bsub>Z\\<^sub>p\\<^esub> y)\"\n      unfolding 0 eval Zp.to_fun_def h_def\n      apply(intro conjI y_closed)\n      using eval Zp.to_fun_def apply (simp; fail)\n      using A unfolding 0 eval Zp.to_fun_def h_def 3\n      using assms(2) to_Zp_val val_ring_minus_closed by presburger\n    have 2: \"y = \\<alpha>\"\n      using 1 \\<alpha>_def by blast\n    show \"x = \\<beta>\"\n      using y_def unfolding 2 8 using A \\<beta>_closed\n      by (metis to_Zp_inc)\n  qed\n  show \"\\<exists>!\\<alpha>. \\<alpha> \\<in> \\<O>\\<^sub>p \\<and> f \\<bullet> \\<alpha> = \\<zero> \\<and> val (UPQ.pderiv f \\<bullet> a) < val (a \\<ominus> \\<alpha>)\"\n    using 12 13 by metis\nqed\n\nlemma nth_root_poly_root_fixed:\n  assumes \"(n::nat) > 1\"\n  assumes \"a \\<in> \\<O>\\<^sub>p\"\n  assumes \"val (\\<one> \\<ominus>\\<^bsub>Q\\<^sub>p\\<^esub> a) > 2* val ([n]\\<cdot>\\<one>)\"\n  shows \"(\\<exists>! b \\<in> \\<O>\\<^sub>p. (b[^]n) = a \\<and>  val (b \\<ominus> \\<one>) > val ([n]\\<cdot>\\<one>))\"\nproof-\n  obtain f where f_def: \"f = up_ring.monom (UP Q\\<^sub>p) \\<one> n \\<ominus>\\<^bsub>UP Q\\<^sub>p\\<^esub> up_ring.monom (UP Q\\<^sub>p) a 0\"\n    by blast\n  have f_closed: \"f \\<in> carrier (UP Q\\<^sub>p)\"\n    unfolding f_def apply(rule UPQ.P.ring_simprules)\n     apply (simp; fail)   using assms\n    by (simp add: val_ring_memE(2))\n  have 0: \"UPQ.pderiv (up_ring.monom (UP Q\\<^sub>p) a 0) = \\<zero>\\<^bsub>UP Q\\<^sub>p\\<^esub>\"\n    using assms\n    by (simp add: val_ring_memE(2))\n  have 1: \"UPQ.pderiv (up_ring.monom (UP Q\\<^sub>p) (\\<one>) n) = (up_ring.monom (UP Q\\<^sub>p) ([n]\\<cdot>\\<one>) (n-1)) \"\n    using UPQ.pderiv_monom by blast\n  have 2: \"up_ring.monom (UP Q\\<^sub>p) \\<one> n \\<in> carrier (UP Q\\<^sub>p)\"\n    by simp\n  have 3: \"up_ring.monom (UP Q\\<^sub>p) a 0 \\<in> carrier (UP Q\\<^sub>p)\"\n    using assms val_ring_memE by simp\n  have 4: \"UPQ.pderiv f  = up_ring.monom (UP Q\\<^sub>p) ([n] \\<cdot> \\<one>) (n - 1)  \\<ominus>\\<^bsub>UP Q\\<^sub>p\\<^esub> \\<zero>\\<^bsub>UP Q\\<^sub>p\\<^esub>\"\n    using 2 3 assms val_ring_memE UPQ.pderiv_minus[of \"up_ring.monom (UP Q\\<^sub>p) \\<one> n\" \"up_ring.monom (UP Q\\<^sub>p) a 0\"]\n    unfolding f_def 0 1 by blast\n  have 5: \"UPQ.pderiv f = (up_ring.monom (UP Q\\<^sub>p) ([n]\\<cdot>\\<one>) (n-1))\"\n    unfolding 4 a_minus_def by simp\n  have a_closed: \"a \\<in> carrier Q\\<^sub>p\"\n    using assms val_ring_memE by blast\n  have 6: \"UPQ.pderiv f \\<bullet> \\<one> = [n]\\<cdot>\\<one> \\<otimes> \\<one>[^](n-1)\"\n    unfolding 5 using a_closed\n    by (simp add: UPQ.to_fun_monom)\n  have 7: \"val (\\<one> \\<ominus>\\<^bsub>Q\\<^sub>p\\<^esub> a) > val \\<one>\"\n  proof-\n    have \"eint 2 * val ([n] \\<cdot> \\<one>) \\<ge> 0\"\n      by (meson eint_ord_trans eint_pos_int_times_ge val_of_nat_inc zero_less_numeral)\n    thus ?thesis\n      using assms unfolding val_one\n      by (simp add: Q\\<^sub>p_def)\n  qed\n  hence 8: \"val a = val \\<one>\"\n    using a_closed\n    by (metis Qp.cring_simprules(6) ultrametric_equal_eq')\n  have 9:\"val (a [^] (n - 1)) = 0\"\n    by (simp add: \"8\" local.a_closed val_zero_imp_val_pow_zero)\n  have 10: \"val ([n]\\<cdot>\\<one> \\<otimes> \\<one>[^](n-1)) = val ([n]\\<cdot>\\<one>)\"\n    unfolding val_one 9 by simp\n  have 11: \"0 \\<le> gauss_norm f\"\n  proof-\n    have p0: \"gauss_norm (up_ring.monom (UP Q\\<^sub>p) \\<one> n) \\<ge> 0\"\n      using gauss_norm_monom by simp\n    have p1: \"gauss_norm (up_ring.monom (UP Q\\<^sub>p) a 0) \\<ge> 0\"\n      using gauss_norm_monom assms val_ring_memE by simp\n    have p2: \"min (gauss_norm (up_ring.monom (UP Q\\<^sub>p) \\<one> n)) (gauss_norm (up_ring.monom (UP Q\\<^sub>p) a 0)) \\<ge> 0\"\n      using p0 p1 by simp\n    have p3: \"0 \\<le> gauss_norm\n      (up_ring.monom (UP Q\\<^sub>p) \\<one> n \\<ominus>\\<^bsub>UP Q\\<^sub>p\\<^esub> up_ring.monom (UP Q\\<^sub>p) a 0)\"\n      using gauss_norm_ultrametric'[of \"up_ring.monom (UP Q\\<^sub>p) \\<one> n\" \"up_ring.monom (UP Q\\<^sub>p) a 0\"]\n            p2  \"2\" \"3\" eint_ord_trans  by blast\n    show ?thesis using p3 unfolding f_def by simp\n  qed\n  have 12: \"\\<And>\\<alpha>. \\<alpha> \\<in> \\<O>\\<^sub>p \\<Longrightarrow> f \\<bullet> \\<alpha> = \\<alpha>[^]n \\<ominus> a\"\n    unfolding f_def using a_closed\n    by (simp add: UPQ.to_fun_const UPQ.to_fun_diff UPQ.to_fun_monic_monom val_ring_memE(2))\n  have 13: \"\\<exists>!\\<alpha>. \\<alpha> \\<in> \\<O>\\<^sub>p \\<and> f \\<bullet> \\<alpha> = \\<zero> \\<and> val (UPQ.pderiv f \\<bullet> \\<one>) < val (\\<one> \\<ominus> \\<alpha>)\"\n    apply(rule hensels_lemma, rule f_closed, rule one_in_val_ring, rule 11)\n    unfolding 6 10\n    using a_closed assms 12[of \\<one>] assms(3)\n    by (simp add: one_in_val_ring)\n  have 14: \"\\<And>\\<alpha>. \\<alpha> \\<in> \\<O>\\<^sub>p \\<Longrightarrow> \\<alpha>[^]n = a \\<longleftrightarrow> f \\<bullet> \\<alpha> = \\<zero>\"\n    unfolding f_def using a_closed 12 f_def val_ring_memE(2) by auto\n  have 15: \"val (UPQ.pderiv f \\<bullet> \\<one>) = val ([n]\\<cdot>\\<one>)\"\n    unfolding 6 10 by auto\n  have 16: \"\\<And>\\<alpha>. \\<alpha> \\<in> \\<O>\\<^sub>p \\<Longrightarrow> val (\\<one> \\<ominus> \\<alpha>) = val (\\<alpha> \\<ominus> \\<one>)\"\n  proof-\n    have 17: \"\\<And>\\<alpha>. \\<alpha> \\<in> \\<O>\\<^sub>p \\<Longrightarrow> (\\<one> \\<ominus> \\<alpha>) = \\<ominus> (\\<alpha> \\<ominus> \\<one>)\"\n      using val_ring_memE\n      by (meson Qp.minus_a_inv Qp.one_closed)\n    show \"\\<And>\\<alpha>. \\<alpha> \\<in> \\<O>\\<^sub>p \\<Longrightarrow> val (\\<one> \\<ominus> \\<alpha>) = val (\\<alpha> \\<ominus> \\<one>)\"\n      unfolding 17\n      using Qp.minus_closed Qp.one_closed val_minus val_ring_memE(2) by presburger\n  qed\n  show ?thesis using 13 unfolding 15 using 14 16 Qp.one_closed val_ring_memE(2) by metis\nqed\n\nlemma mod_zeroE:\n  assumes \"(a::int) mod k  = 0\"\n  shows \"\\<exists>l. a = l*k\"\n  using assms\n  using Groups.mult_ac(2) by blast\n\nlemma to_Zp_poly_closed':\n  assumes \"g \\<in> carrier (UP Q\\<^sub>p)\"\n  assumes \"\\<And>i. g i \\<in> \\<O>\\<^sub>p\"\n  shows \"to_Zp_poly g \\<in> carrier (UP Z\\<^sub>p)\"\nproof(rule to_Zp_poly_closed)\n  show \"g \\<in> carrier (UP Q\\<^sub>p)\"\n    using assms(1) by blast\n  show \"0 \\<le> gauss_norm g\"\n  proof-\n    have \"\\<And>i. val (g i) \\<ge> 0\"\n      using assms val_ring_memE by blast\n    thus ?thesis unfolding gauss_norm_def\n      by (metis  gauss_norm_coeff_norm gauss_norm_def)\n  qed\nqed\n\nlemma to_Zp_poly_eval_to_Zp:\n  assumes \"g \\<in> carrier (UP Q\\<^sub>p)\"\n  assumes \"\\<And>i. g i \\<in> \\<O>\\<^sub>p\"\n  assumes \"a \\<in> \\<O>\\<^sub>p\"\n  shows \"to_function Z\\<^sub>p (to_Zp_poly g) (to_Zp a) = to_Zp (g \\<bullet> a)\"\nproof-\n  have \"(\\<forall>i. g i \\<in> \\<O>\\<^sub>p) \\<longrightarrow> to_function Z\\<^sub>p (to_Zp_poly g) (to_Zp a) = to_Zp (g \\<bullet> a)\"\n    apply(rule UPQ.poly_induct[of g]) using assms apply blast\n  proof\n    fix p assume A: \"p \\<in> carrier (UP Q\\<^sub>p)\" \"deg Q\\<^sub>p p = 0\" \"\\<forall>i. p i \\<in> \\<O>\\<^sub>p\"\n    obtain c where c_def: \"c \\<in> carrier Q\\<^sub>p \\<and> p = up_ring.monom (UP Q\\<^sub>p) c  0\"\n      using A  by (metis UPQ.ltrm_deg_0 val_ring_memE(2))\n    have 0: \"to_Zp_poly (up_ring.monom (UP Q\\<^sub>p) c  0) = up_ring.monom (UP Z\\<^sub>p) (to_Zp c) 0\"\n      unfolding to_Zp_poly_def proof fix n show \" to_Zp (up_ring.monom (UP Q\\<^sub>p) c 0 n) = up_ring.monom (UP Z\\<^sub>p) (to_Zp c) 0 n\"\n        using UP_ring.cfs_monom[of Z\\<^sub>p \"to_Zp c\" 0 n] UP_ring.cfs_monom[of Q\\<^sub>p c 0 n] to_Zp_closed[of c ]\n        unfolding UP_ring_def\n        apply(cases \"0 = n\")\n        using UPQ.cfs_monom Zp.cfs_monom c_def apply presburger\n         using UPQ.cfs_monom Zp.cfs_monom c_def\n         using to_Zp_zero by presburger\n    qed\n    have p_eq: \"p = up_ring.monom (UP Q\\<^sub>p) c  0\"\n      using c_def by blast\n    have 1: \"(up_ring.monom (UP Q\\<^sub>p) c 0 \\<bullet> a) = c\"\n      using UPQ.to_fun_to_poly[of c a]  c_def assms val_ring_memE\n      unfolding to_polynomial_def  by blast\n    show \"to_function Z\\<^sub>p (to_Zp_poly p) (to_Zp a) = to_Zp (p \\<bullet> a)\"\n      using c_def assms(3) val_ring_memE(2)[of a]\n      UP_cring.to_fun_to_poly[of Z\\<^sub>p \"to_Zp c\" \"to_Zp a\"]\n      unfolding p_eq 0 1 Zp.to_fun_def to_polynomial_def\n      using Zp.UP_cring_axioms to_Zp_closed by blast\n  next\n    show \"\\<And>p. (\\<And>q. q \\<in> carrier (UP Q\\<^sub>p) \\<Longrightarrow>\n              deg Q\\<^sub>p q < deg Q\\<^sub>p p \\<Longrightarrow> (\\<forall>i. q i \\<in> \\<O>\\<^sub>p) \\<longrightarrow> to_function Z\\<^sub>p (to_Zp_poly q) (to_Zp a) = to_Zp (q \\<bullet> a)) \\<Longrightarrow>\n         p \\<in> carrier (UP Q\\<^sub>p) \\<Longrightarrow> 0 < deg Q\\<^sub>p p \\<Longrightarrow> (\\<forall>i. p i \\<in> \\<O>\\<^sub>p) \\<longrightarrow> to_function Z\\<^sub>p (to_Zp_poly p) (to_Zp a) = to_Zp (p \\<bullet> a)\"\n    proof  fix p\n      assume A: \"(\\<And>q. q \\<in> carrier (UP Q\\<^sub>p) \\<Longrightarrow>\n              deg Q\\<^sub>p q < deg Q\\<^sub>p p \\<Longrightarrow> (\\<forall>i. q i \\<in> \\<O>\\<^sub>p) \\<longrightarrow> to_function Z\\<^sub>p (to_Zp_poly q) (to_Zp a) = to_Zp (q \\<bullet> a))\"\n            \"p \\<in> carrier (UP Q\\<^sub>p)\" \"0 < deg Q\\<^sub>p p\" \"\\<forall>i. p i \\<in> \\<O>\\<^sub>p\"\n      show \"to_function Z\\<^sub>p (to_Zp_poly p) (to_Zp a) = to_Zp (p \\<bullet> a)\"\n      proof-\n        obtain q where q_def: \"q = truncate Q\\<^sub>p  p\"\n          by blast\n        have  q_closed: \"q \\<in> carrier (UP Q\\<^sub>p)\"\n          unfolding q_def by(rule UPQ.trunc_closed, rule A)\n        obtain c where c_def: \"c = UPQ.lcf p\"\n          by blast\n        obtain n where n_def: \"n = deg Q\\<^sub>p p\"\n          by blast\n        have 0: \"p = q \\<oplus>\\<^bsub>UP Q\\<^sub>p\\<^esub> up_ring.monom (UP Q\\<^sub>p) c n\"\n          unfolding c_def n_def q_def\n          using A(2) UPQ.trunc_simps(1) by blast\n        have 1: \"up_ring.monom (UP Q\\<^sub>p) c n \\<in> carrier  (UP Q\\<^sub>p)\"\n          using A(2) UPQ.ltrm_closed c_def n_def by blast\n        have 2: \"p \\<bullet> a  = q  \\<bullet> a \\<oplus> (c \\<otimes> a[^]n)\"\n          unfolding 0 using assms val_ring_memE\n          by (metis \"1\" A(4) UPQ.to_fun_monom UPQ.to_fun_plus c_def q_closed)\n        have 3: \"\\<And>i. i < n \\<Longrightarrow> q i = p i\"\n          unfolding n_def q_def\n          using A(2) UPQ.trunc_cfs by blast\n        have 4: \"deg Q\\<^sub>p q < n\"\n          unfolding n_def q_def using A\n          using UPQ.trunc_degree by presburger\n        have 5: \"\\<And>i. i \\<ge> n \\<Longrightarrow> i >  deg Q\\<^sub>p q\"\n          using A[of ] less_le_trans[of \"deg Q\\<^sub>p q\" \"deg Q\\<^sub>p p\"] unfolding q_def n_def\n          using \"4\" n_def q_def by blast\n        have 6: \"\\<And>i. i \\<ge> n \\<Longrightarrow> q i = \\<zero>\"\n          using q_closed 5 UPQ.deg_leE by blast\n        have 7: \"(\\<forall>i. q i \\<in> \\<O>\\<^sub>p) \\<longrightarrow> to_function Z\\<^sub>p (to_Zp_poly q) (to_Zp a) = to_Zp (q \\<bullet> a)\"\n          apply(rule   A) unfolding q_def\n          using q_closed q_def apply blast\n          using \"4\" n_def q_def by blast\n        have 8: \"(\\<forall>i. q i \\<in> \\<O>\\<^sub>p)\"\n        proof fix i show \"q i \\<in> \\<O>\\<^sub>p\" apply(cases \"i < n\")\n            using 3 A(4) apply blast using 6[of i]\n            by (metis less_or_eq_imp_le linorder_neqE_nat zero_in_val_ring)\n        qed\n        have 9: \"to_function Z\\<^sub>p (to_Zp_poly q) (to_Zp a) = to_Zp (q \\<bullet> a)\"\n          using 7 8 by blast\n        have 10: \"to_Zp_poly p = to_Zp_poly q \\<oplus>\\<^bsub>UP Z\\<^sub>p\\<^esub> to_Zp_poly (up_ring.monom (UP Q\\<^sub>p) c n)\"\n        proof fix x\n          have 100: \"to_Zp_poly (up_ring.monom (UP Q\\<^sub>p) c n) = (up_ring.monom (UP Z\\<^sub>p) (to_Zp c) n)\"\n            using to_Zp_poly_monom[of c] A(4) c_def by blast\n          have 101: \"deg Z\\<^sub>p (to_Zp_poly q) \\<le> n-1\"\n              apply(rule  UP_cring.deg_leqI)\n              unfolding UP_cring_def using Zp.R_cring apply auto[1]\n              using to_Zp_poly_closed' 8 q_closed apply blast\n              unfolding to_Zp_poly_def using 4 6\n              by (simp add: to_Zp_zero)\n          have 102: \"(to_Zp_poly q) \\<in> carrier (UP Z\\<^sub>p)\"\n            apply(rule to_Zp_poly_closed', rule q_closed) using 8 by blast\n          have 103: \"deg Z\\<^sub>p (to_Zp_poly q) < n\"\n            using 101 4 by linarith\n            have T0: \"(to_Zp_poly q \\<oplus>\\<^bsub>UP Z\\<^sub>p\\<^esub> to_Zp_poly (up_ring.monom (UP Q\\<^sub>p) c n)) x =\n                    (to_Zp_poly q x) \\<oplus>\\<^bsub>Z\\<^sub>p\\<^esub> (to_Zp_poly (up_ring.monom (UP Q\\<^sub>p) c n) x)\"\n              apply(rule  UP_ring.cfs_add)\n                apply (simp add: Zp.is_UP_ring)\n               apply (simp add: \"102\")\n              using \"100\" A(2) UPQ.lcf_closed c_def to_Zp_closed by auto\n            have c_closed: \"c \\<in> \\<O>\\<^sub>p\"\n              unfolding c_def  using A(4) by blast\n            have to_Zp_c_closed: \"to_Zp c \\<in> carrier Z\\<^sub>p\"\n              using c_closed to_Zp_closed val_ring_memE(2) by blast\n          show \"to_Zp_poly p x = (to_Zp_poly q \\<oplus>\\<^bsub>UP Z\\<^sub>p\\<^esub> to_Zp_poly (up_ring.monom (UP Q\\<^sub>p) c n)) x\"\n          proof(cases \"x < n\")\n            case True\n            have T1: \"(to_Zp_poly (up_ring.monom (UP Q\\<^sub>p) c n) x) = \\<zero>\\<^bsub>Z\\<^sub>p\\<^esub>\"\n              using True UP_ring.cfs_monom[of Z\\<^sub>p] unfolding UP_ring_def\n              by (simp add: A(2) UPQ.ltrm_cfs c_def n_def to_Zp_poly_def to_Zp_zero)\n            have T2: \"to_Zp (p x) = to_Zp (q x)\" using 3[of x] True by smt\n            have T3: \"to_Zp (p x) \\<in> carrier Z\\<^sub>p\"\n              apply(rule to_Zp_closed) using A(2) UPQ.UP_car_memE(1) by blast\n            show ?thesis using T3\n              unfolding T0  unfolding T1 unfolding  to_Zp_poly_def  T2\n              using Zp.cring_simprules(8) add_comm by presburger\n          next\n            case False\n            have F: \"q x = \\<zero> \"\n              using False\n              by (metis \"6\" less_or_eq_imp_le linorder_neqE_nat)\n            have F': \"(to_Zp_poly q) x = \\<zero>\\<^bsub>Z\\<^sub>p\\<^esub>\"\n             unfolding to_Zp_poly_def F using to_Zp_zero by blast\n            show \"to_Zp_poly p x = (to_Zp_poly q \\<oplus>\\<^bsub>UP Z\\<^sub>p\\<^esub> to_Zp_poly (up_ring.monom (UP Q\\<^sub>p) c n)) x\"\n            proof(cases \"x = n\")\n              case True\n              have T1: \"to_Zp (p x) \\<in> carrier Z\\<^sub>p\"\n                apply(rule to_Zp_closed)\n                using A(2) UPQ.UP_car_memE(1) by blast\n              have T2: \"(to_Zp_poly (up_ring.monom (UP Q\\<^sub>p) c n) x) = to_Zp c\"\n                unfolding 100 using UP_ring.cfs_monom[of Z\\<^sub>p \"to_Zp c\" n n] unfolding UP_ring_def True\n                using Zp.ring_axioms to_Zp_c_closed by presburger\n              show ?thesis using to_Zp_c_closed unfolding T0 F' T2 unfolding to_Zp_poly_def True c_def n_def\n                using Zp.cring_simprules(8) by presburger\n            next\n              case FF: False\n              have F0: \"p x = \\<zero>\"\n                using FF False unfolding n_def\n                using A(2) UPQ.UP_car_memE(2) linorder_neqE_nat by blast\n              have F1: \"q x = \\<zero>\"\n                using FF False F by linarith\n              have F2: \"(up_ring.monom (UP Q\\<^sub>p) c n) x = \\<zero>\"\n                using FF False A(2) UPQ.cfs_closed UPQ.cfs_monom c_def by presburger\n              show ?thesis unfolding T0 unfolding to_Zp_poly_def F0 F1 F2\n                using Zp.r_zero Zp.zero_closed to_Zp_zero by presburger\n            qed\n          qed\n        qed\n        have 11: \"deg Z\\<^sub>p (to_Zp_poly q) \\<le> n-1\"\n          apply(rule  UP_cring.deg_leqI)\n          unfolding UP_cring_def using Zp.R_cring apply auto[1]\n          using to_Zp_poly_closed' 8 q_closed apply blast\n          unfolding to_Zp_poly_def using 4 6\n          by (smt diff_commute diff_diff_cancel less_one less_or_eq_imp_le linorder_neqE_nat to_Zp_zero zero_less_diff)\n        have 12: \"(to_Zp_poly q) \\<in> carrier (UP Z\\<^sub>p)\"\n          apply(rule to_Zp_poly_closed', rule q_closed) using 8 by blast\n        have 13: \"deg Z\\<^sub>p (to_Zp_poly q) < n\"\n          using 11 4 by linarith\n        have 14: \"to_Zp_poly (up_ring.monom (UP Q\\<^sub>p) c n) = (up_ring.monom (UP Z\\<^sub>p) (to_Zp c) n)\"\n          using to_Zp_poly_monom[of c] A(4) c_def by blast\n        have 15: \"Zp.to_fun (to_Zp_poly q \\<oplus>\\<^bsub>UP Z\\<^sub>p\\<^esub> to_Zp_poly (up_ring.monom (UP Q\\<^sub>p) c n)) (to_Zp a)=\n            Zp.to_fun (to_Zp_poly q) (to_Zp a) \\<oplus>\\<^bsub>Z\\<^sub>p\\<^esub> Zp.to_fun (to_Zp_poly (up_ring.monom (UP Q\\<^sub>p) c n)) (to_Zp a)\"\n          apply(rule Zp.to_fun_plus)\n          unfolding 14  apply(rule UP_ring.monom_closed)\n          unfolding UP_ring_def\n             apply (simp add: Zp.ring_axioms)\n            apply (simp add: A(2) UPQ.cfs_closed c_def to_Zp_closed)\n           using \"12\" apply blast\n          apply(rule to_Zp_closed) using assms val_ring_memE by blast\n        have 16: \"to_Zp (q \\<bullet> a \\<oplus> c \\<otimes> a [^] n) = to_Zp (q \\<bullet> a)  \\<oplus>\\<^bsub>Z\\<^sub>p\\<^esub> to_Zp (c \\<otimes> a [^] n)\"\n          apply(rule to_Zp_add)\n           apply(rule val_ring_poly_eval, rule q_closed)\n            using \"8\" apply blast\n             apply(rule assms)\n            apply(rule val_ring_times_closed)\n            unfolding c_def using A(4) apply blast\n          by(rule val_ring_nat_pow_closed, rule assms)\n        have  17: \" to_function Z\\<^sub>p (up_ring.monom (UP Z\\<^sub>p) (to_Zp c) n) (to_Zp a) =  to_Zp (c \\<otimes> a [^] n)\"\n          proof-\n            have 170: \"to_Zp (c \\<otimes> a [^] n) = to_Zp c \\<otimes>\\<^bsub>Z\\<^sub>p\\<^esub> to_Zp (a [^] n)\"\n              apply(rule  to_Zp_mult[of c \"a[^]n\"])\n              unfolding c_def using A(4) apply blast\n              by(rule val_ring_nat_pow_closed, rule assms)\n            have 171: \"to_Zp (a [^] n) = (to_Zp a [^]\\<^bsub>Z\\<^sub>p\\<^esub>n)\"\n              by(rule to_Zp_nat_pow, rule assms)\n            have 172: \"to_Zp c \\<in> carrier Z\\<^sub>p \"\n              apply(rule to_Zp_closed) unfolding c_def\n              using A(2) UPQ.UP_car_memE(1) by blast\n            have 173: \"to_Zp a \\<in> carrier Z\\<^sub>p \"\n              apply(rule to_Zp_closed) using assms val_ring_memE by blast\n            show ?thesis\n              using 172 173 Zp.to_fun_monom[of \"to_Zp c\" \"to_Zp a\" n] unfolding Zp.to_fun_def 170 171\n              by blast\n        qed\n        show ?thesis\n          using 15 unfolding Zp.to_fun_def 10 2 16 9 unfolding 14 17\n          by blast\n      qed\n    qed\n  qed\n  thus ?thesis using assms by blast\nqed\n\nlemma inc_nat_pow:\n  assumes \"a \\<in> carrier Z\\<^sub>p\"\n  shows \"\\<iota> ([(n::nat)] \\<cdot>\\<^bsub>Z\\<^sub>p\\<^esub>a) = [n]\\<cdot>(\\<iota> a)\"\n  apply(induction n)\n  apply (metis Q\\<^sub>p_def Qp.int_inc_zero Qp.nat_mult_zero Zp.add.nat_pow_0 Zp_int_inc_zero' \\<iota>_def frac_inc_of_int)\n  unfolding Qp.add.nat_pow_Suc Zp.add.nat_pow_Suc\n  using Zp_nat_mult_closed assms inc_of_sum by presburger\n\nlemma poly_inc_pderiv:\n  assumes \"g \\<in> carrier (UP Z\\<^sub>p)\"\n  shows \"poly_inc (Zp.pderiv g) = UPQ.pderiv (poly_inc g)\"\nproof fix x\n  have 0: \"UPQ.pderiv (poly_inc g) x = [Suc x] \\<cdot> poly_inc g (Suc x)\"\n    apply(rule UPQ.pderiv_cfs[of \"poly_inc g\" x])\n    by(rule poly_inc_closed, rule assms)\n  have 1: \"Zp.pderiv g x = [Suc x] \\<cdot>\\<^bsub>Z\\<^sub>p\\<^esub> g (Suc x)\"\n    by(rule Zp.pderiv_cfs[of g x], rule assms)\n  show \"poly_inc (Zp.pderiv g) x = UPQ.pderiv (poly_inc g) x\"\n    unfolding 0  unfolding poly_inc_def 1 apply(rule  inc_nat_pow)\n    using Zp.UP_car_memE(1) assms by blast\nqed\n\nlemma Zp_hensels_lemma:\n  assumes \"f \\<in> carrier Zp_x\"\n  assumes \"a \\<in> carrier Z\\<^sub>p\"\n  assumes \"Zp.to_fun (Zp.pderiv f) a \\<noteq> \\<zero>\\<^bsub>Z\\<^sub>p\\<^esub>\"\n  assumes \"Zp.to_fun f a \\<noteq> \\<zero>\\<^bsub>Z\\<^sub>p \\<^esub>\"\n  assumes \"val_Zp (Zp.to_fun f a) > eint 2 * val_Zp (Zp.to_fun (Zp.pderiv f) a)\"\n  obtains \\<alpha> where\n       \"Zp.to_fun f \\<alpha> = \\<zero>\\<^bsub>Z\\<^sub>p\\<^esub>\" and \"\\<alpha> \\<in> carrier Z\\<^sub>p\"\n       \"val_Zp (a \\<ominus>\\<^bsub>Z\\<^sub>p\\<^esub> \\<alpha>) > val_Zp (Zp.to_fun (Zp.pderiv f) a)\"\n       \"val_Zp (a \\<ominus>\\<^bsub>Z\\<^sub>p\\<^esub> \\<alpha>) = val_Zp (divide (Zp.to_fun f a) (Zp.to_fun (Zp.pderiv f) a))\"\n       \"val_Zp (Zp.to_fun (Zp.pderiv f) \\<alpha>) = val_Zp (Zp.to_fun (Zp.pderiv f) a)\"\nproof-\n  have \"hensel p f a\"\n    using assms\n    by (simp add: Zp_def hensel.intro hensel_axioms.intro padic_integers_axioms)\n  then show ?thesis\n    using hensel.full_hensels_lemma[of p f a] that\n    unfolding Zp_def\n    by blast\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/Padic_Field/Padic_Field_Polynomials.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8688267830311355, "lm_q2_score": 0.8459424314825853, "lm_q1q2_score": 0.7349774413745513}}
{"text": "(*<*)\n(* Author: Dmitriy Traytel *)\n\nheader {* A Codatatype of Formal Languages *}\n\ntheory Coinductive_Language\nimports Main\nbegin\n\nhide_const (open) Inter\n(*>*)\n\nsection {* Introduction *}\n\ntext {*\nWe define formal languages as a codataype of infinite trees branching over the\nalphabet @{typ 'a}. Each node in such a tree indicates whether the path to this\nnode constitutes a word inside or outside of the language.\n\n*}\n\ncodatatype 'a language = Lang (\\<oo>: bool) (\\<dd>: \"'a \\<Rightarrow> 'a language\")\n\ntext {* \nThis codatatype is isormorphic to the set of lists representation of languages,\nbut caters for definitions by corecursion and proofs by coinduction.\n\nRegular operations on languages are then defined by primitive corecursion.\nA difficulty arises here, since the standard definitions of concatenation and\niteration from the coalgebraic literature are not primitively corecursive---they\nrequire guardedness up-to union/concatenation. Without support for up-to corecursion,\nthese operation must be defined as a composition of primitive ones (and proved being\nequal to the standard definitions). As an exercise in coinduction we also prove the\naxioms of Kleene algebra for the defined regular operations.\n\nFurthermore, a language for context-free grammars given by productions in Greibach\nnormal form and an initial nonterminal is constructed by primitive corecursion,\nyielding an executable decision procedure for the word problem without further ado.\n*}\n(*<*)\n(* custom coinduction theorem (getting rid of rel_fun) *)\ndeclare language.coinduct[unfolded rel_fun_def, simplified, case_names Lang, coinduct pred]\n(*>*)\n\nsection {* Regular Languages *}\n\nprimcorec Zero :: \"'a language\" where\n  \"\\<oo> Zero = False\"\n| \"\\<dd> Zero = (\\<lambda>_. Zero)\"\n\nprimcorec One :: \"'a language\" where\n  \"\\<oo> One = True\"\n| \"\\<dd> One = (\\<lambda>_. Zero)\"\n\nprimcorec Atom :: \"'a \\<Rightarrow> 'a language\" where\n  \"\\<oo> (Atom a) = False\"\n| \"\\<dd> (Atom a) = (\\<lambda>b. if a = b then One else Zero)\"\n\nprimcorec Plus :: \"'a language \\<Rightarrow> 'a language \\<Rightarrow> 'a language\" where\n  \"\\<oo> (Plus r s) = (\\<oo> r \\<or> \\<oo> s)\"\n| \"\\<dd> (Plus r s) = (\\<lambda>a. Plus (\\<dd> r a) (\\<dd> s a))\"\n\ntheorem Plus_ZeroL[simp]: \"Plus Zero r = r\"\n  by (coinduction arbitrary: r) simp\n\ntheorem Plus_ZeroR[simp]: \"Plus r Zero = r\"\n  by (coinduction arbitrary: r) simp\n\n\n\ntheorem Plus_comm: \"Plus r s = Plus s r\"\n  by (coinduction arbitrary: r s) auto\n\nlemma Plus_rotate: \"Plus r (Plus s t) = Plus s (Plus r t)\"\n  using Plus_assoc Plus_comm by metis\n\ntheorem Plus_idem: \"Plus r r = r\"\n  by (coinduction arbitrary: r) auto\n\nlemma Plus_idem_assoc: \"Plus r (Plus r s) = Plus r s\"\n  by (metis Plus_assoc Plus_idem)\n\nlemmas Plus_ACI[simp] = Plus_rotate Plus_comm Plus_assoc Plus_idem_assoc Plus_idem\n\ntext {*\n  Coinduction up-to @{term Plus}--congruence relaxes the coinduction hypothesis by requiring\n  membership in the congruence closure of the bisimulation rather than in the bisimulation itself.\n*}\n\ninductive Plus_cong where\n  Refl[intro]: \"x = y \\<Longrightarrow> Plus_cong R x y\"\n| Base[intro]: \"R x y \\<Longrightarrow> Plus_cong R x y\"\n| Trans[intro]: \"Plus_cong R x y \\<Longrightarrow> Plus_cong R y z \\<Longrightarrow> Plus_cong R x z\"\n| Plus[intro]: \"\\<lbrakk>Plus_cong R x y; Plus_cong R x' y'\\<rbrakk> \\<Longrightarrow> Plus_cong R (Plus x x') (Plus y y')\"\n\nlemma language_coinduct_upto_Plus[unfolded rel_fun_def, simplified, case_names Lang, consumes 1]: \n  assumes R: \"R L K\" and hyp:\n    \"(\\<And>L K. R L K \\<Longrightarrow> \\<oo> L = \\<oo> K \\<and> rel_fun op = (Plus_cong R) (\\<dd> L) (\\<dd> K))\"\n  shows \"L = K\"\nproof (coinduct rule: language.coinduct[of \"Plus_cong R\"])\n  fix L K assume \"Plus_cong R L K\"\n  then show \"\\<oo> L = \\<oo> K \\<and> rel_fun op = (Plus_cong R) (\\<dd> L) (\\<dd> K)\" using hyp\n    by (induct rule: Plus_cong.induct) (auto simp: rel_fun_def)\nqed (intro Base R)\n\nlemma Plus_OneL[simp]: \"\\<oo> r \\<Longrightarrow> Plus One r = r\"\n  by (coinduction arbitrary: r rule: language_coinduct_upto_Plus) auto\n\nlemma Plus_OneR[simp]: \"\\<oo> r \\<Longrightarrow> Plus r One = r\"\n  by (coinduction arbitrary: r rule: language_coinduct_upto_Plus) auto\n\ntext {*\n  Concatenation is not primitively corecursive---the corecursive call of its derivative is\n  guarded by @{term Plus}. However, it can be defined as a composition of two primitively\n  corecursive functions.\n*}\n\nprimcorec TimesLR :: \"'a language \\<Rightarrow> 'a language \\<Rightarrow> ('a \\<times> bool) language\" where\n  \"\\<oo> (TimesLR r s) = (\\<oo> r \\<and> \\<oo> s)\"\n| \"\\<dd> (TimesLR r s) = (\\<lambda>(r, s). TimesLR r s) o (\\<lambda>(a, b). \n   (if b then (\\<dd> r a, s) else if \\<oo> r then (\\<dd> s a, One) else (Zero, One)))\"\n\nprimcorec Times_Plus :: \"('a \\<times> bool) language \\<Rightarrow> 'a language\" where\n  \"\\<oo> (Times_Plus r) = \\<oo> r\"\n| \"\\<dd> (Times_Plus r) = (\\<lambda>a. Times_Plus (Plus (\\<dd> r (a, True)) (\\<dd> r (a, False))))\"\n\nlemma TimesLR_ZeroL[simp]: \"TimesLR Zero r = Zero\"\n  by (coinduction arbitrary: r) auto\n\nlemma TimesLR_ZeroR[simp]: \"TimesLR r Zero = Zero\"\n  by (coinduction arbitrary: r) (auto intro: exI[of _ Zero])\n\nlemma TimesLR_PlusL[simp]: \"TimesLR (Plus r s) t = Plus (TimesLR r t) (TimesLR s t)\"\n  by (coinduction arbitrary: r s t rule: language_coinduct_upto_Plus) auto\n\nlemma TimesLR_PlusR[simp]: \"TimesLR r (Plus s t) = Plus (TimesLR r s) (TimesLR r t)\"\n  by (coinduction arbitrary: r s t rule: language_coinduct_upto_Plus) auto\n\nlemma Times_Plus_Zero[simp]: \"Times_Plus Zero = Zero\"\n  by coinduction simp\n\nlemma Times_Plus_Plus[simp]: \"Times_Plus (Plus r s) = Plus (Times_Plus r) (Times_Plus s)\"\nproof (coinduction arbitrary: r s)\n  case (Lang r s)\n  then show ?case unfolding Times_Plus.sel Plus.sel\n    by (intro conjI[OF refl] allI exI conjI[rotated], rule refl) (metis Plus_comm Plus_rotate) \nqed\n\nlemma Times_Plus_TimesLR_One[simp]: \"Times_Plus (TimesLR r One) = r\"\n  by (coinduction arbitrary: r) simp\n\nlemma Times_Plus_TimesLR_PlusL[simp]:\n  \"Times_Plus (TimesLR (Plus r s) t) = Plus (Times_Plus (TimesLR r t)) (Times_Plus (TimesLR s t))\"\n  by (coinduction arbitrary: r s t rule: language_coinduct_upto_Plus) auto\n\nlemma Times_Plus_TimesLR_PlusR[simp]:\n  \"Times_Plus (TimesLR r (Plus s t)) = Plus (Times_Plus (TimesLR r s)) (Times_Plus (TimesLR r t))\"\n  by (coinduction arbitrary: r s t rule: language_coinduct_upto_Plus) auto\n\ndefinition Times :: \"'a language \\<Rightarrow> 'a language \\<Rightarrow> 'a language\" where\n  \"Times r s = Times_Plus (TimesLR r s)\"\n\nlemma \\<oo>_Times[simp]:\n  \"\\<oo> (Times r s) = (\\<oo> r \\<and> \\<oo> s)\"\n  unfolding Times_def by simp\n\nlemma \\<dd>_Times[simp]:\n  \"\\<dd> (Times r s) = (\\<lambda>a. if \\<oo> r then Plus (Times (\\<dd> r a) s) (\\<dd> s a) else Times (\\<dd> r a) s)\"\n  unfolding Times_def by (rule ext, coinduction arbitrary: r s rule: language_coinduct_upto_Plus) auto\n\ntheorem Times_ZeroL[simp]: \"Times Zero r = Zero\"\n  by coinduction simp\n\ntheorem Times_ZeroR[simp]: \"Times r Zero = Zero\"\n  by (coinduction arbitrary: r) auto\n\n\n\ntheorem Times_OneR[simp]: \"Times r One = r\"\n  by (coinduction arbitrary: r) simp\n\ntheorem Times_PlusL[simp]: \"Times (Plus r s) t = Plus (Times r t) (Times s t)\"\n  by (coinduction arbitrary: r s rule: language_coinduct_upto_Plus) fastforce\n\ntheorem Times_PlusR[simp]: \"Times r (Plus s t) = Plus (Times r s) (Times r t)\"\n  by (coinduction arbitrary: r s rule: language_coinduct_upto_Plus) fastforce\n\n\n\ntext {*\n  Similarly to @{term Times}, iteration is not primitively corecursive (guardedness by\n  @{term Times} is required). We apply a similar trick to obtain its definition.\n*}\n\nprimcorec StarLR :: \"'a language \\<Rightarrow> 'a language \\<Rightarrow> 'a language\" where\n  \"\\<oo> (StarLR r s) = \\<oo> r\"\n| \"\\<dd> (StarLR r s) = (\\<lambda>a. StarLR (\\<dd> (Times r (Plus One s)) a) s)\"\n\nlemma StarLR_Zero[simp]: \"StarLR Zero r = Zero\"\n  by coinduction auto\n\nlemma StarLR_Plus[simp]: \"StarLR (Plus r s) t = Plus (StarLR r t) (StarLR s t)\"\n  by (coinduction arbitrary: r s) (auto simp del: Plus_ACI Times_PlusR)\n\nlemma StarLR_Times_Plus_One[simp]: \"StarLR (Times r (Plus One s)) s = StarLR r s\"\nproof (coinduction arbitrary: r s)\n  case Lang\n  { fix a\n    def L \\<equiv> \"Plus (\\<dd> r a) (Plus (Times (\\<dd> r a) s) (\\<dd> s a))\"\n    and R \\<equiv> \"Times (Plus (\\<dd> r a) (Plus (Times (\\<dd> r a) s) (\\<dd> s a))) s\"\n    have \"Plus L (Plus R (\\<dd> s a)) = Plus (Plus L (\\<dd> s a)) R\" by (metis Plus_assoc Plus_comm)\n    also have \"Plus L (\\<dd> s a) = L\" unfolding L_def by simp\n    finally have \"Plus L (Plus R (\\<dd> s a)) = Plus L R\" .\n  }\n  then show ?case by (auto simp del: StarLR_Plus Plus_assoc Times_PlusL)\nqed\n\nlemma StarLR_Times: \"StarLR (Times r s) t = Times r (StarLR s t)\"\n  by (coinduction arbitrary: r s t rule: language_coinduct_upto_Plus)\n    (fastforce simp del: Plus_ACI Times_PlusR)\n\ndefinition Star :: \"'a language \\<Rightarrow> 'a language\" where\n  \"Star r = StarLR One r\"\n\nlemma \\<oo>_Star[simp]: \"\\<oo> (Star r)\"\n  unfolding Star_def by simp\n\nlemma \\<dd>_Star[simp]: \"\\<dd> (Star r) = (\\<lambda>a. Times (\\<dd> r a) (Star r))\"\n  unfolding Star_def by (rule ext, coinduction arbitrary: r rule: language_coinduct_upto_Plus)\n    (auto simp add: Star_def StarLR_Times[symmetric])\n\nlemma Star_Zero[simp]: \"Star Zero = One\"\n  by (coinduction rule: language.coinduct_strong) auto\n\nlemma Star_One[simp]: \"Star One = One\"\n  by (coinduction rule: language.coinduct_strong) auto\n\nlemma Star_unfoldL: \"Star r = Plus One (Times r (Star r))\"\n  by (coinduction arbitrary: r rule: language_coinduct_upto_Plus) auto\n\nprimcorec Inter :: \"'a language \\<Rightarrow> 'a language \\<Rightarrow> 'a language\" where\n  \"\\<oo> (Inter r s) = (\\<oo> r \\<and> \\<oo> s)\"\n| \"\\<dd> (Inter r s) = (\\<lambda>a. Inter (\\<dd> r a) (\\<dd> s a))\"\n\nprimcorec Not :: \"'a language \\<Rightarrow> 'a language\" where\n  \"\\<oo> (Not r) = (\\<not> \\<oo> r)\"\n| \"\\<dd> (Not r) = (\\<lambda>a. Not (\\<dd> r a))\"\n\nprimcorec Full :: \"'a language\" (\"\\<Sigma>\\<^sup>*\") where\n  \"\\<oo> Full = True\"\n| \"\\<dd> Full = (\\<lambda>_. Full)\"\n\ntext {*\n  Shuffle product is not primitively corecursive---the corecursive call of its derivative is\n  guarded by @{term Plus}. However, it can be defined as a composition of two primitively\n  corecursive functions.\n*}\n\nprimcorec ShuffleLR :: \"'a language \\<Rightarrow> 'a language \\<Rightarrow> ('a \\<times> bool) language\" where\n  \"\\<oo> (ShuffleLR r s) = (\\<oo> r \\<and> \\<oo> s)\"\n| \"\\<dd> (ShuffleLR r s) = (\\<lambda>(r, s). ShuffleLR r s) o (\\<lambda>(a, b). (if b then (\\<dd> r a, s) else (r, \\<dd> s a)))\"\n\nprimcorec Shuffle_Plus :: \"('a \\<times> bool) language \\<Rightarrow> 'a language\" where\n  \"\\<oo> (Shuffle_Plus r) = \\<oo> r\"\n| \"\\<dd> (Shuffle_Plus r) = (\\<lambda>a. Shuffle_Plus (Plus (\\<dd> r (a, True)) (\\<dd> r (a, False))))\"\n\nlemma ShuffleLR_ZeroL[simp]: \"ShuffleLR Zero r = Zero\"\n  by (coinduction arbitrary: r) auto\n\nlemma ShuffleLR_ZeroR[simp]: \"ShuffleLR r Zero = Zero\"\n  by (coinduction arbitrary: r) (auto intro: exI[of _ Zero])\n\nlemma ShuffleLR_PlusL[simp]: \"ShuffleLR (Plus r s) t = Plus (ShuffleLR r t) (ShuffleLR s t)\"\n  by (coinduction arbitrary: r s t rule: language_coinduct_upto_Plus) auto\n\nlemma ShuffleLR_PlusR[simp]: \"ShuffleLR r (Plus s t) = Plus (ShuffleLR r s) (ShuffleLR r t)\"\n  by (coinduction arbitrary: r s t rule: language_coinduct_upto_Plus) auto\n\nlemma Shuffle_Plus_Zero[simp]: \"Shuffle_Plus Zero = Zero\"\n  by coinduction simp\n\nlemma Shuffle_Plus_Plus[simp]: \"Shuffle_Plus (Plus r s) = Plus (Shuffle_Plus r) (Shuffle_Plus s)\"\nproof (coinduction arbitrary: r s)\n  case (Lang r s)\n  then show ?case unfolding Shuffle_Plus.sel Plus.sel\n    by (intro conjI[OF refl] allI exI conjI[rotated], rule refl) (metis Plus_comm Plus_rotate) \nqed\n\nlemma Shuffle_Plus_ShuffleLR_One[simp]: \"Shuffle_Plus (ShuffleLR r One) = r\"\n  by (coinduction arbitrary: r) simp\n\nlemma Shuffle_Plus_ShuffleLR_PlusL[simp]:\n  \"Shuffle_Plus (ShuffleLR (Plus r s) t) = Plus (Shuffle_Plus (ShuffleLR r t)) (Shuffle_Plus (ShuffleLR s t))\"\n  by (coinduction arbitrary: r s t rule: language_coinduct_upto_Plus) auto\n\nlemma Shuffle_Plus_ShuffleLR_PlusR[simp]:\n  \"Shuffle_Plus (ShuffleLR r (Plus s t)) = Plus (Shuffle_Plus (ShuffleLR r s)) (Shuffle_Plus (ShuffleLR r t))\"\n  by (coinduction arbitrary: r s t rule: language_coinduct_upto_Plus) auto\n\ndefinition Shuffle :: \"'a language \\<Rightarrow> 'a language \\<Rightarrow> 'a language\" where\n  \"Shuffle r s = Shuffle_Plus (ShuffleLR r s)\"\n\nlemma \\<oo>_Shuffle[simp]:\n  \"\\<oo> (Shuffle r s) = (\\<oo> r \\<and> \\<oo> s)\"\n  unfolding Shuffle_def by simp\n\nlemma \\<dd>_Shuffle[simp]:\n  \"\\<dd> (Shuffle r s) = (\\<lambda>a. Plus (Shuffle (\\<dd> r a) s) (Shuffle r (\\<dd> s a)))\"\n  unfolding Shuffle_def by (rule ext, coinduction arbitrary: r s rule: language_coinduct_upto_Plus) auto\n\ntheorem Shuffle_ZeroL[simp]: \"Shuffle Zero r = Zero\"\n  by (coinduction arbitrary: r rule: language_coinduct_upto_Plus) (auto 0 4)\n\ntheorem Shuffle_ZeroR[simp]: \"Shuffle r Zero = Zero\"\n  by (coinduction arbitrary: r rule: language_coinduct_upto_Plus) (auto 0 4)\n\ntheorem Shuffle_OneL[simp]: \"Shuffle One r = r\"\n  by (coinduction arbitrary: r rule: language.coinduct_strong) (simp add: rel_fun_def)\n\ntheorem Shuffle_OneR[simp]: \"Shuffle r One = r\"\n  by (coinduction arbitrary: r) simp\n\ntheorem Shuffle_PlusL[simp]: \"Shuffle (Plus r s) t = Plus (Shuffle r t) (Shuffle s t)\"\n  by (coinduction arbitrary: r s t rule: language_coinduct_upto_Plus)\n    (force intro!: Trans[OF Plus[OF Base Base] Refl])\n\ntheorem Shuffle_PlusR[simp]: \"Shuffle r (Plus s t) = Plus (Shuffle r s) (Shuffle r t)\"\n  by (coinduction arbitrary: r s t rule: language_coinduct_upto_Plus)\n    (force intro!: Trans[OF Plus[OF Base Base] Refl])\n\ntheorem Shuffle_assoc[simp]: \"Shuffle (Shuffle r s) t = Shuffle r (Shuffle s t)\"\n  by (coinduction arbitrary: r s t rule: language_coinduct_upto_Plus) fastforce\n\ntext {*\n  We generalize coinduction up-to @{term Plus} to coinduction up-to all previously defined concepts.\n*}\n\ninductive regular_cong where\n  Refl[intro]: \"x = y \\<Longrightarrow> regular_cong R x y\"\n| Sym[intro]: \"regular_cong R x y \\<Longrightarrow> regular_cong R y x\"\n| Trans[intro]: \"\\<lbrakk>regular_cong R x y; regular_cong R y z\\<rbrakk> \\<Longrightarrow> regular_cong R x z\"\n| Base[intro]: \"R x y \\<Longrightarrow> regular_cong R x y\"\n| Plus[intro]: \"\\<lbrakk>regular_cong R x y; regular_cong R x' y'\\<rbrakk> \\<Longrightarrow>\n    regular_cong R (Plus x x') (Plus y y')\"\n| Times[intro]: \"\\<lbrakk>regular_cong R x y; regular_cong R x' y'\\<rbrakk> \\<Longrightarrow>\n    regular_cong R (Times x x') (Times y y')\"\n| Star[intro]: \"\\<lbrakk>regular_cong R x y\\<rbrakk> \\<Longrightarrow>\n    regular_cong R (Star x) (Star y)\"\n| Inter[intro]: \"\\<lbrakk>regular_cong R x y; regular_cong R x' y'\\<rbrakk> \\<Longrightarrow>\n    regular_cong R (Inter x x') (Inter y y')\"\n| Not[intro]: \"\\<lbrakk>regular_cong R x y\\<rbrakk> \\<Longrightarrow>\n    regular_cong R (Not x) (Not y)\"\n| Shuffle[intro]: \"\\<lbrakk>regular_cong R x y; regular_cong R x' y'\\<rbrakk> \\<Longrightarrow>\n    regular_cong R (Shuffle x x') (Shuffle y y')\"\n\nlemma language_coinduct_upto_regular[unfolded rel_fun_def, simplified, case_names Lang, consumes 1]: \n  assumes R: \"R L K\" and hyp:\n    \"(\\<And>L K. R L K \\<Longrightarrow> \\<oo> L = \\<oo> K \\<and> rel_fun op = (regular_cong R) (\\<dd> L) (\\<dd> K))\"\n  shows \"L = K\"\nproof (coinduct rule: language.coinduct[of \"regular_cong R\"])\n  fix L K assume \"regular_cong R L K\"\n  then show \"\\<oo> L = \\<oo> K \\<and> rel_fun op = (regular_cong R) (\\<dd> L) (\\<dd> K)\" using hyp\n    by (induct rule: regular_cong.induct) (auto simp: rel_fun_def)\nqed (intro Base R)\n\nlemma Star_unfoldR: \"Star r = Plus One (Times (Star r) r)\"\nproof (coinduction arbitrary: r rule: language_coinduct_upto_regular)\n  case Lang\n  { fix a have \"Plus (Times (\\<dd> r a) (Times (Star r) r)) (\\<dd> r a) = \n      Times (\\<dd> r a) (Plus One (Times (Star r) r))\" by simp\n  }\n  then show ?case by (auto simp del: Times_PlusR)\nqed\n\nlemma Star_Star[simp]: \"Star (Star r) = Star r\"\n  by (subst Star_unfoldL, coinduction arbitrary: r rule: language_coinduct_upto_regular) auto\n\nlemma Times_Star[simp]: \"Times (Star r) (Star r) = Star r\"\nproof (coinduction arbitrary: r rule: language_coinduct_upto_regular)\n  case Lang\n  have *: \"\\<And>r s. Plus (Times r s) r = Times r (Plus s One)\" by simp\n  show ?case by (auto simp del: Times_PlusR Plus_ACI simp: Times_PlusR[symmetric] *)\nqed\n\ninstantiation language :: (type) \"{semiring_1, order}\"\nbegin\n\nlemma Zero_One[simp]: \"Zero \\<noteq> One\"\n  by (metis One.simps(1) Zero.simps(1))\n\ndefinition \"zero_language = Zero\"\ndefinition \"one_language = One\"\ndefinition \"plus_language = Plus\"\ndefinition \"times_language = Times\"\n\ndefinition \"less_eq_language r s = (Plus r s = s)\"\ndefinition \"less_language r s = (Plus r s = s \\<and> r \\<noteq> s)\"\n\nlemmas language_defs = zero_language_def one_language_def plus_language_def times_language_def\n  less_eq_language_def less_language_def\n\ninstance proof intro_classes\n  fix x y z :: \"'a language\" assume \"x \\<le> y\" \"y \\<le> z\"\n  then show \"x \\<le> z\" unfolding language_defs by (metis Plus_assoc)\nnext\n  fix x y z :: \"'a language\"\n  show \"x + y + z = x + (y + z)\" unfolding language_defs by (rule Plus_assoc)\nqed (auto simp: language_defs)\n\nend\n\ntext {*\n  We prove the missing axioms of Kleene Algebras about @{term Star}, as well as monotonicity\n  properties and three standard interesting rules: bisimulation, sliding, and denesting.\n*}\n\ntheorem le_StarL: \"Plus One (Times r (Star r)) \\<le> Star r\"\n  by (rule order_eq_refl[OF Star_unfoldL[symmetric]])\n\ntheorem le_StarR: \"Plus One (Times (Star r) r) \\<le> Star r\"\n  by (rule order_eq_refl[OF Star_unfoldR[symmetric]])\n\ntheorem ardenL: \"Plus r (Times s x) \\<le> x \\<Longrightarrow> Times (Star s) r \\<le> x\"\nunfolding language_defs\nproof (coinduction arbitrary: r s x rule: language_coinduct_upto_regular)\n  case Lang\n  hence \"\\<oo> r \\<Longrightarrow> \\<oo> x\" by (metis Plus.sel(1))\n  moreover\n  { fix a\n    let ?R = \"(\\<lambda>L K. \\<exists>r s.  L = Plus (Times (Star s) r) K \\<and> Plus r (Plus (Times s K) K) = K)\"\n    have \"regular_cong ?R (Plus x (Times (Star s) r)) x\"\n      using Lang[unfolded Plus_assoc] by (auto simp only: Plus_comm)\n    hence \"regular_cong ?R\n      (Plus (Times (\\<dd> s a) (Plus x (Times (Star s) r))) (Plus (\\<dd> r a) (\\<dd> x a)))\n      (Plus (\\<dd> r a) (Plus (Times (\\<dd> s a) x) (\\<dd> x a)))\"\n      by (auto simp del: Times_PlusR)\n    also have \"(Plus (Times (\\<dd> s a) (Plus x (Times (Star s) r))) (Plus (\\<dd> r a) (\\<dd> x a))) = \n      (Plus (Times (\\<dd> s a) (Times (Star s) r)) (Plus (\\<dd> r a) (\\<dd> x a)))\"\n      by (subst (3) Lang[symmetric]) auto\n    finally have \"regular_cong ?R\n      (Plus (Times (\\<dd> s a) (Times (Star s) r)) (Plus (\\<dd> r a) (\\<dd> x a)))\n      (Plus (\\<dd> r a) (Plus (Times (\\<dd> s a) x) (\\<dd> x a)))\" .\n  }\n  ultimately show ?case by (subst (4) Lang[symmetric]) auto\nqed\n\ntheorem ardenR: \"Plus r (Times x s) \\<le> x \\<Longrightarrow> Times r (Star s) \\<le> x\"\nunfolding language_defs\nproof (coinduction arbitrary: r s x rule: language_coinduct_upto_regular)\n  case Lang\n  let ?R = \"(\\<lambda>L K. \\<exists>r s. L = Plus (Times r (Star s)) K \\<and> Plus r (Plus (Times K s) K) = K)\"\n  have \"\\<And>a. \\<oo> x \\<Longrightarrow> Plus (\\<dd> s a) (\\<dd> x a) = \\<dd> x a\"\n    by (subst (1 2) Lang[symmetric]) auto\n  then have *: \"\\<And>a. ?R (Plus (Times (\\<dd> r a) (Star s)) (\\<dd> x a)) (\\<dd> x a)\"\n    by (subst Lang[symmetric]) (auto simp del: Plus_comm)\n  moreover\n  from Lang have \"\\<oo> r \\<Longrightarrow> \\<oo> x\" by (metis Plus.sel(1))\n  moreover\n  { fix a assume \"\\<oo> x\"\n    have \"regular_cong ?R (Plus (Times (\\<dd> s a) (Star s)) (\\<dd> x a)) (\\<dd> x a)\"\n    proof (rule Base exI conjI[OF refl])+\n      from `\\<oo> x` show \"Plus (\\<dd> s a) (Plus (Times (\\<dd> x a) s) (\\<dd> x a)) = \\<dd> x a\"\n        by (subst (1 3) Lang[symmetric]) auto\n    qed\n    from Plus[OF Base[of ?R, OF *[of a]] this] have \"regular_cong ?R\n      (Plus (Times (\\<dd> r a) (Star s)) (Plus (Times (\\<dd> s a) (Star s)) (\\<dd> x a))) (\\<dd> x a)\" by auto\n  }\n  ultimately show ?case by auto\nqed\n\nlemma ge_One[simp]: \"One \\<le> r \\<longleftrightarrow> \\<oo> r\"\n  unfolding less_eq_language_def by (metis One.sel(1) Plus.sel(1) Plus_OneL)\n\nlemma Plus_mono[intro]: \"\\<lbrakk>r1 \\<le> s1; r2 \\<le> s2\\<rbrakk> \\<Longrightarrow> Plus r1 r2 \\<le> Plus s1 s2\"\n  unfolding less_eq_language_def by (metis Plus_assoc Plus_comm)\n\nlemma Plus_upper: \"\\<lbrakk>r1 \\<le> s; r2 \\<le> s\\<rbrakk> \\<Longrightarrow> Plus r1 r2 \\<le> s\"\n  by (metis Plus_mono Plus_idem)\n\nlemma le_PlusL: \"r \\<le> Plus r s\"\n  by (metis Plus_idem_assoc less_eq_language_def)\n\nlemma le_PlusR: \"s \\<le> Plus r s\"\n  by (metis Plus_comm Plus_idem_assoc less_eq_language_def)\n\nlemma Times_mono[intro]: \"\\<lbrakk>r1 \\<le> s1; r2 \\<le> s2\\<rbrakk> \\<Longrightarrow> Times r1 r2 \\<le> Times s1 s2\"\nproof (unfold less_eq_language_def)\n  assume s1[symmetric]: \"Plus r1 s1 = s1\" and s2[symmetric]: \"Plus r2 s2 = s2\"\n  have \"Plus (Times r1 r2) (Times s1 s2) =\n    Plus (Times r1 r2) (Plus (Times r1 r2) (Plus (Times s1 r2) (Plus (Times r1 s2) (Times s1 s2))))\"\n    by (subst s1, subst s2) auto\n  also have \"\\<dots> = Plus (Times r1 r2) (Plus (Times s1 r2) (Plus (Times r1 s2) (Times s1 s2)))\"\n    by (metis Plus_idem Plus_assoc)\n  also have \"\\<dots> = Times s1 s2\" by (subst s1, subst s2) auto\n  finally show \"Plus (Times r1 r2) (Times s1 s2) = Times s1 s2\" .\nqed\n\nlemma le_TimesL: \"\\<oo> s \\<Longrightarrow> r \\<le> Times r s\"\n  by (metis Plus_OneL Times_OneR Times_mono le_PlusL order_refl)\n\nlemma le_TimesR: \"\\<oo> r \\<Longrightarrow> s \\<le> Times r s\"\n  by (metis Plus_OneR Times_OneL Times_mono le_PlusR order_refl)\n\nlemma le_Star: \"s \\<le> Star s\"\n  by (subst Star_unfoldL, subst Star_unfoldL) (auto intro: order_trans[OF le_PlusL le_PlusR])\n\nlemma Star_mono:\n  assumes rs: \"r \\<le> s\"\n  shows \"Star r \\<le> Star s\"\nproof -\n  have \"Star r = Plus One (Times (Star r) r)\" by (rule Star_unfoldR)\n  also have \"\\<dots> \\<le> Plus One (Times (Star r) s)\" by (blast intro: rs)\n  also have \"Times (Star r) s \\<le> Star s\"\n  proof (rule ardenL[OF Plus_upper[OF le_Star]])\n    have \"Times r (Star s) \\<le> Times s (Star s)\" by (blast intro: rs)\n    also have \"Times s (Star s) \\<le> Plus One (Times s (Star s))\" by (rule le_PlusR)\n    finally show \"Times r (Star s) \\<le> Star s\" by (subst (2) Star_unfoldL)\n  qed\n  finally show ?thesis by auto\nqed\n\nlemma Inter_mono: \"\\<lbrakk>r1 \\<le> s1; r2 \\<le> s2\\<rbrakk> \\<Longrightarrow> Inter r1 r2 \\<le> Inter s1 s2\"\nunfolding less_eq_language_def proof (coinduction arbitrary: r1 r2 s1 s2)\n  case Lang\n  then have \"\\<oo> (Plus r1 s1) = \\<oo> s1\" \"\\<oo> (Plus r2 s2) = \\<oo> s2\"\n        \"\\<forall>a. \\<dd> (Plus r1 s1) a = \\<dd> s1 a\" \"\\<forall>a. \\<dd> (Plus r2 s2) a = \\<dd> s2 a\" by simp_all\n  then show ?case by fastforce\nqed\n\nlemma Not_antimono: \"r \\<le> s \\<Longrightarrow> Not s \\<le> Not r\"\nunfolding less_eq_language_def proof (coinduction arbitrary: r s)\n  case Lang\n  then have \"\\<oo> (Plus r s) = \\<oo> s\" \"\\<forall>a. \\<dd> (Plus r s) a = \\<dd> s a\" by simp_all\n  then show ?case by auto\nqed\n\nlemma Not_Plus[simp]: \"Not (Plus r s) = Inter (Not r) (Not s)\"\n  by (coinduction arbitrary: r s) auto\n\nlemma Not_Inter[simp]: \"Not (Inter r s) = Plus (Not r) (Not s)\"\n  by (coinduction arbitrary: r s) auto\n\nlemma Inter_assoc[simp]: \"Inter (Inter r s) t = Inter r (Inter s t)\"\n  by (coinduction arbitrary: r s t) auto\n\nlemma Inter_comm: \"Inter r s = Inter s r\"\n  by (coinduction arbitrary: r s) auto\n\nlemma Inter_idem[simp]: \"Inter r r = r\"\n  by (coinduction arbitrary: r) auto\n\nlemma Inter_ZeroL[simp]: \"Inter Zero r = Zero\"\n  by (coinduction arbitrary: r) auto\n\nlemma Inter_ZeroR[simp]: \"Inter r Zero = Zero\"\n  by (coinduction arbitrary: r) auto\n\nlemma Inter_FullL[simp]: \"Inter Full r = r\"\n  by (coinduction arbitrary: r) auto\n\nlemma Inter_FullR[simp]: \"Inter r Full = r\"\n  by (coinduction arbitrary: r) auto\n\nlemma Plus_FullL[simp]: \"Plus Full r = Full\"\n  by (coinduction arbitrary: r) auto\n\nlemma Plus_FullR[simp]: \"Plus r Full = Full\"\n  by (coinduction arbitrary: r) auto\n\nlemma Not_Not[simp]: \"Not (Not r) = r\"\n  by (coinduction arbitrary: r) auto\n\nlemma Not_Zero[simp]: \"Not Zero = Full\"\n  by coinduction simp\n\nlemma Not_Full[simp]: \"Not Full = Zero\"\n  by coinduction simp\n\nlemma bisimulation:\n  assumes \"Times r s = Times s t\"\n  shows \"Times (Star r) s = Times s (Star t)\"\nproof (rule antisym[OF ardenL[OF Plus_upper[OF le_TimesL]] ardenR[OF Plus_upper[OF le_TimesR]]])\n  have \"Times r (Times s (Star t)) = Times s (Times t (Star t))\" (is \"?L = _\")\n    by (simp only: assms Times_assoc[symmetric])\n  also have \"\\<dots> \\<le> Times s (Star t)\" (is \"_ \\<le> ?R\")\n    by (rule Times_mono[OF order_refl ord_le_eq_trans[OF le_PlusR Star_unfoldL[symmetric]]])\n  finally show \"?L \\<le> ?R\" .\nnext\n  have \"Times (Times (Star r) s) t = Times (Times (Star r) r) s\" (is \"?L = _\")\n    by (simp only: assms Times_assoc)\n  also have \"\\<dots> \\<le> Times (Star r) s\" (is \"_ \\<le> ?R\")\n    by (rule Times_mono[OF ord_le_eq_trans[OF le_PlusR Star_unfoldR[symmetric]] order_refl])\n  finally show \"?L \\<le> ?R\" .\nqed simp_all\n\nlemma sliding: \"Times (Star (Times r s)) r = Times r (Star (Times s r))\"\nproof (rule antisym[OF ardenL[OF Plus_upper[OF le_TimesL]] ardenR[OF Plus_upper[OF le_TimesR]]])\n  have \"Times (Times r s) (Times r (Star (Times s r))) =\n    Times r (Times (Times s r) (Star (Times s r)))\" (is \"?L = _\") by simp\n  also have \"\\<dots> \\<le> Times r (Star (Times s r))\" (is \"_ \\<le> ?R\")\n    by (rule Times_mono[OF order_refl ord_le_eq_trans[OF le_PlusR Star_unfoldL[symmetric]]])\n  finally show \"?L \\<le> ?R\" .\nnext\n  have \"Times (Times (Star (Times r s)) r) (Times s r) =\n    Times (Times (Star (Times r s)) (Times r s)) r\" (is \"?L = _\") by simp\n  also have \"\\<dots> \\<le> Times (Star (Times r s)) r\" (is \"_ \\<le> ?R\")\n    by (rule Times_mono[OF ord_le_eq_trans[OF le_PlusR Star_unfoldR[symmetric]] order_refl])\n  finally show \"?L \\<le> ?R\" .\nqed simp_all\n\nlemma denesting: \"Star (Plus r s) = Times (Star r) (Star (Times s (Star r)))\"\nproof (rule antisym[OF _ ardenR[OF Plus_upper[OF Star_mono[OF le_PlusL]]]])\n  have \"Star (Plus r s) = Times (Star (Plus r s)) One\" by simp\n  also have \"\\<dots> \\<le> Times (Star r) (Star (Times s (Star r)))\"\n  proof (rule ardenL[OF Plus_upper])\n    show \"Times (Plus r s) (Times (Star r) (Star (Times s (Star r)))) \\<le>\n      Times (Star r) (Star (Times s (Star r)))\" (is \"Times _ ?L \\<le> ?R\")\n    proof (subst Times_PlusL, rule Plus_upper)\n      show \"Times s ?L \\<le> ?R\"\n        by (subst (5) Star_unfoldL, rule order_trans[OF order_trans[OF _ le_PlusR] le_TimesR]) auto\n    qed (subst (4) Times_Star[symmetric], auto simp del: Times_Star intro: le_Star)\n  qed simp\n  finally show \"Star (Plus r s) \\<le> Times (Star r) (Star (Times s (Star r)))\" .\nnext\n  have \"Times (Star (Plus r s)) (Times s (Star r)) \\<le> Times (Star (Plus r s)) (Star (Plus r s))\"\n    by (subst (4) Star_unfoldL, rule Times_mono[OF order_refl\n      order_trans[OF Times_mono[OF le_PlusR Star_mono[OF le_PlusL]] le_PlusR]])\n  also have \"\\<dots> = Star (Plus r s)\" by simp\n  finally show \"Times (Star (Plus r s)) (Times s (Star r)) \\<le> Star (Plus r s)\" .\nqed\n\ntext {*\nIt is useful to lift binary operators @{term Plus} and @{term Times}\nto $n$-ary operators (that take a list as input).\n*}\n\ndefinition PLUS :: \"'a language list \\<Rightarrow> 'a language\" where\n  \"PLUS xs \\<equiv> foldr Plus xs Zero\"\n\nlemma \\<oo>_foldr_Plus: \"\\<oo> (foldr Plus xs s) = (\\<exists>x\\<in>set (s # xs). \\<oo> x)\"\n  by (induct xs arbitrary: s) auto\n\nlemma \\<dd>_foldr_Plus: \"\\<dd> (foldr Plus xs s) a = foldr Plus (map (\\<lambda>r. \\<dd> r a) xs) (\\<dd> s a)\"\n  by (induct xs arbitrary: s) simp_all\n\n\n\nlemma \\<dd>_PLUS[simp]: \"\\<dd> (PLUS xs) a = PLUS (map (\\<lambda>r. \\<dd> r a) xs)\"\n  unfolding PLUS_def \\<dd>_foldr_Plus by simp\n\ndefinition TIMES :: \"'a language list \\<Rightarrow> 'a language\" where\n  \"TIMES xs \\<equiv> foldr Times xs One\"\n\nlemma \\<oo>_foldr_Times: \"\\<oo> (foldr Times xs s) = (\\<forall>x\\<in>set (s # xs). \\<oo> x)\"\n  by (induct xs) (auto simp: PLUS_def)\n\nprimrec tails where\n  \"tails [] = [[]]\"\n| \"tails (x # xs) = (x # xs) # tails xs\"\n\nlemma tails_snoc[simp]: \"tails (xs @ [x]) = map (\\<lambda>ys. ys @ [x]) (tails xs) @ [[]]\"\n  by (induct xs) auto\n\nlemma length_tails[simp]: \"length (tails xs) = Suc (length xs)\"\n  by (induct xs) auto\n\nlemma \\<dd>_foldr_Times: \"\\<dd> (foldr Times xs s) a =\n  (let n = length (takeWhile \\<oo> xs)\n  in PLUS (map (\\<lambda>zs. TIMES (\\<dd> (hd zs) a # tl zs)) (take (Suc n) (tails (xs @ [s])))))\"\n  by (induct xs) (auto simp: TIMES_def PLUS_def Let_def foldr_map o_def)\n\nlemma \\<oo>_TIMES[simp]: \"\\<oo> (TIMES xs) = (\\<forall>x\\<in>set xs. \\<oo> x)\"\n  unfolding TIMES_def \\<oo>_foldr_Times by simp\n\nlemma TIMES_snoc_One[simp]: \"TIMES (xs @ [One]) = TIMES xs\"\n  by (induct xs) (auto simp: TIMES_def)\n\nlemma \\<dd>_TIMES[simp]: \"\\<dd> (TIMES xs) a = (let n = length (takeWhile \\<oo> xs)\n  in PLUS (map (\\<lambda>zs. TIMES (\\<dd> (hd zs) a # tl zs)) (take (Suc n) (tails (xs @ [One])))))\"\n  unfolding TIMES_def \\<dd>_foldr_Times by simp\n\nsection {* Context Free Languages *}\n\ncontext\nfixes init :: \"'n::enum\"\nand   prod :: \"'n \\<Rightarrow> ('t + 'n) language\"\nbegin\n\nprimcorec deep_subst :: \"('t + 'n) language \\<Rightarrow> 't language\" where\n  \"deep_subst r =\n     (let shallow_subst = PLUS (r # map (\\<lambda>N. Times (prod N) (\\<dd> r (Inr N))) Enum.enum)\n     in Lang (\\<oo> shallow_subst) (\\<lambda>a. deep_subst (\\<dd> shallow_subst (Inl a))))\"\n\ndefinition subst where\n  \"subst = deep_subst (prod init)\"\n\nend\n\ntext {*\nA context-free grammar consists of a list of productions for every nonterminal\nand an initial nonterminal. The productions are required to be in weak Greibach\nnormal form, i.e. each right hand side of a production must either be empty or\nstart with a terminal.\n*}\n\nlocale cfg =\nfixes init :: \"'n::enum\"\nand   prod :: \"'n \\<Rightarrow> ('t + 'n) list list\"\nassumes weakGreibach: \"\\<forall>N. \\<forall>rhs \\<in> set (prod N). case rhs of (Inr N # _) \\<Rightarrow> False | _ \\<Rightarrow> True\"\nbegin\n\nabbreviation lang :: \"'t language\" where\n  \"lang \\<equiv> subst init (\\<lambda>N. PLUS (map (TIMES o map Atom) (prod N)))\"\n\nend\n\nsection {* Word-theoretic Semantics of Languages *}\n\ntext {*\nWe show our @{type language} codatatype being isomorphic to the standard\nlanguage representation as a set of lists.\n*}\n\nprimrec in_language :: \"'a language \\<Rightarrow> 'a list \\<Rightarrow> bool\" where\n  \"in_language L [] = \\<oo> L\"\n| \"in_language L (x # xs) = in_language (\\<dd> L x) xs\"\n\nprimcorec to_language :: \"'a list set \\<Rightarrow> 'a language\" where\n  \"\\<oo> (to_language L) = ([] \\<in> L)\"\n| \"\\<dd> (to_language L) = (\\<lambda>a. to_language {w. a # w \\<in> L})\"\n\nlemma in_language_to_language[simp]: \"Collect (in_language (to_language L)) = L\"\nproof (rule set_eqI, unfold mem_Collect_eq)\n  fix w show \"in_language (to_language L) w = (w \\<in> L)\" by (induct w arbitrary: L) auto\nqed\n\nlemma to_language_in_language[simp]: \"to_language (Collect (in_language L)) = L\"\n  by (coinduction arbitrary: L) auto\n\nlemma in_language_bij: \"bij (Collect o in_language)\"\nproof (rule bijI', unfold o_apply, safe)\n  fix L R :: \"'a language\" assume \"Collect (in_language L) = Collect (in_language R)\"\n  then show \"L = R\" unfolding set_eq_iff mem_Collect_eq\n    by (coinduction arbitrary: L R) (metis in_language.simps)\nnext\n  fix L :: \"'a list set\"\n  have \"L = Collect (in_language (to_language L))\" by simp\n  then show \"\\<exists>K. L = Collect (in_language K)\" by blast\nqed\n\nlemma to_language_bij: \"bij to_language\"\n  by (rule o_bij[of \"Collect o in_language\"]) (simp_all add: fun_eq_iff)\n\n(*<*)\nhide_const (open) TimesLR Times_Plus StarLR deep_subst subst\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/Coinductive_Languages/Coinductive_Language.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267728417087, "lm_q2_score": 0.8459424411924673, "lm_q1q2_score": 0.7349774411910883}}
{"text": "(*  Title:       Matrix norms\n    Author:      Jonathan Juli\u00e1n Huerta y Munive, 2020\n    Maintainer:  Jonathan Juli\u00e1n Huerta y Munive <jonjulian23@gmail.com>\n*)\n\nsection \\<open> Matrix norms \\<close>\n\ntext \\<open> Here, we explore some properties about the operator and the maximum norms for matrices. \\<close>\n\ntheory MTX_Norms\n  imports MTX_Preliminaries\n\nbegin\n\n\nsubsection\\<open> Matrix operator norm \\<close>\n\nabbreviation op_norm :: \"('a::real_normed_algebra_1)^'n^'m \\<Rightarrow> real\" (\"(1\\<parallel>_\\<parallel>\\<^sub>o\\<^sub>p)\" [65] 61)\n  where \"\\<parallel>A\\<parallel>\\<^sub>o\\<^sub>p \\<equiv> onorm (\\<lambda>x. A *v x)\"\n\nlemma norm_matrix_bound:\n  fixes A :: \"('a::real_normed_algebra_1)^'n^'m\"\n  shows \"\\<parallel>x\\<parallel> = 1 \\<Longrightarrow> \\<parallel>A *v x\\<parallel> \\<le> \\<parallel>(\\<chi> i j. \\<parallel>A $ i $ j\\<parallel>) *v 1\\<parallel>\"\nproof-\n  fix x :: \"('a, 'n) vec\" assume \"\\<parallel>x\\<parallel> = 1\"\n  hence xi_le1:\"\\<And>i. \\<parallel>x $ i\\<parallel> \\<le> 1\" \n    by (metis Finite_Cartesian_Product.norm_nth_le) \n  {fix j::'m \n    have \"\\<parallel>(\\<Sum>i\\<in>UNIV. A $ j $ i * x $ i)\\<parallel> \\<le> (\\<Sum>i\\<in>UNIV. \\<parallel>A $ j $ i * x $ i\\<parallel>)\"\n      using norm_sum by blast\n    also have \"... \\<le> (\\<Sum>i\\<in>UNIV. (\\<parallel>A $ j $ i\\<parallel>) * (\\<parallel>x $ i\\<parallel>))\"\n      by (simp add: norm_mult_ineq sum_mono)\n    also have \"... \\<le> (\\<Sum>i\\<in>UNIV. (\\<parallel>A $ j $ i\\<parallel>) * 1)\"\n      using xi_le1 by (simp add: sum_mono mult_left_le)\n    finally have \"\\<parallel>(\\<Sum>i\\<in>UNIV. A $ j $ i * x $ i)\\<parallel> \\<le> (\\<Sum>i\\<in>UNIV. (\\<parallel>A $ j $ i\\<parallel>) * 1)\" by simp}\n  hence \"\\<And>j. \\<parallel>(A *v x) $ j\\<parallel> \\<le> ((\\<chi> i1 i2. \\<parallel>A $ i1 $ i2\\<parallel>) *v 1) $ j\"\n    unfolding matrix_vector_mult_def by simp\n  hence \"(\\<Sum>j\\<in>UNIV. (\\<parallel>(A *v x) $ j\\<parallel>)\\<^sup>2) \\<le> (\\<Sum>j\\<in>UNIV. (\\<parallel>((\\<chi> i1 i2. \\<parallel>A $ i1 $ i2\\<parallel>) *v 1) $ j\\<parallel>)\\<^sup>2)\"\n    by (metis (mono_tags, lifting) norm_ge_zero power2_abs power_mono real_norm_def sum_mono) \n  thus \"\\<parallel>A *v x\\<parallel> \\<le> \\<parallel>(\\<chi> i j. \\<parallel>A $ i $ j\\<parallel>) *v 1\\<parallel>\"\n    unfolding norm_vec_def L2_set_def by simp\nqed\n\nlemma onorm_set_proptys:\n  fixes A :: \"('a::real_normed_algebra_1)^'n^'m\"\n  shows \"bounded (range (\\<lambda>x. (\\<parallel>A *v x\\<parallel>) / (\\<parallel>x\\<parallel>)))\"\n    and \"bdd_above (range (\\<lambda>x. (\\<parallel>A *v x\\<parallel>) / (\\<parallel>x\\<parallel>)))\"\n    and \"(range (\\<lambda>x. (\\<parallel>A *v x\\<parallel>) / (\\<parallel>x\\<parallel>))) \\<noteq> {}\"\n  unfolding bounded_def bdd_above_def image_def dist_real_def \n    apply(rule_tac x=0 in exI)\n  by (rule_tac x=\"\\<parallel>(\\<chi> i j. \\<parallel>A $ i $ j\\<parallel>) *v 1\\<parallel>\" in exI, clarsimp,\n      subst mult_norm_matrix_sgn_eq[symmetric], clarsimp,\n      rule_tac x=\"sgn _\" in norm_matrix_bound, simp add: norm_sgn)+ force\n\nlemma op_norm_set_proptys:\n  fixes A :: \"('a::real_normed_algebra_1)^'n^'m\"\n  shows \"bounded {\\<parallel>A *v x\\<parallel> | x. \\<parallel>x\\<parallel> = 1}\"\n    and \"bdd_above {\\<parallel>A *v x\\<parallel> | x. \\<parallel>x\\<parallel> = 1}\"\n    and \"{\\<parallel>A *v x\\<parallel> | x. \\<parallel>x\\<parallel> = 1} \\<noteq> {}\"\n  unfolding bounded_def bdd_above_def apply safe\n    apply(rule_tac x=0 in exI, rule_tac x=\"\\<parallel>(\\<chi> i j. \\<parallel>A $ i $ j\\<parallel>) *v 1\\<parallel>\" in exI)\n    apply(force simp: norm_matrix_bound dist_real_def)\n   apply(rule_tac x=\"\\<parallel>(\\<chi> i j. \\<parallel>A $ i $ j\\<parallel>) *v 1\\<parallel>\" in exI, force simp: norm_matrix_bound)\n  using ex_norm_eq_1 by blast\n\nlemma op_norm_def: \"\\<parallel>A\\<parallel>\\<^sub>o\\<^sub>p = Sup {\\<parallel>A *v x\\<parallel> | x. \\<parallel>x\\<parallel> = 1}\"\n  apply(rule antisym[OF onorm_le cSup_least[OF op_norm_set_proptys(3)]])\n   apply(case_tac \"x = 0\", simp)\n   apply(subst mult_norm_matrix_sgn_eq[symmetric], simp)\n   apply(rule cSup_upper[OF _ op_norm_set_proptys(2)])\n   apply(force simp: norm_sgn)\n  unfolding onorm_def \n  apply(rule cSup_upper[OF _ onorm_set_proptys(2)])\n  by (simp add: image_def, clarsimp) (metis div_by_1)\n\nlemma norm_matrix_le_op_norm: \"\\<parallel>x\\<parallel> = 1 \\<Longrightarrow> \\<parallel>A *v x\\<parallel> \\<le> \\<parallel>A\\<parallel>\\<^sub>o\\<^sub>p\"\n  apply(unfold onorm_def, rule cSup_upper[OF _ onorm_set_proptys(2)])\n  unfolding image_def by (clarsimp, rule_tac x=x in exI) simp\n\nlemma op_norm_ge_0: \"0 \\<le> \\<parallel>A\\<parallel>\\<^sub>o\\<^sub>p\"\n  using ex_norm_eq_1 norm_ge_zero norm_matrix_le_op_norm basic_trans_rules(23) by blast\n\nlemma norm_sgn_le_op_norm: \"\\<parallel>A *v sgn x\\<parallel> \\<le> \\<parallel>A\\<parallel>\\<^sub>o\\<^sub>p\"\n  by (cases \"x=0\", simp_all add: norm_sgn norm_matrix_le_op_norm op_norm_ge_0)\n\nlemma norm_matrix_le_mult_op_norm: \"\\<parallel>A *v x\\<parallel> \\<le> (\\<parallel>A\\<parallel>\\<^sub>o\\<^sub>p) * (\\<parallel>x\\<parallel>)\"\nproof-\n  have \"\\<parallel>A *v x\\<parallel> = (\\<parallel>A *v sgn x\\<parallel>) * (\\<parallel>x\\<parallel>)\"\n    by(simp add: mult_norm_matrix_sgn_eq)\n  also have \"... \\<le> (\\<parallel>A\\<parallel>\\<^sub>o\\<^sub>p) * (\\<parallel>x\\<parallel>)\"\n    using norm_sgn_le_op_norm[of A] by (simp add: mult_mono')\n  finally show ?thesis by simp\nqed\n\nlemma blin_matrix_vector_mult: \"bounded_linear ((*v) A)\" for A :: \"('a::real_normed_algebra_1)^'n^'m\"\n  by (unfold_locales) (auto intro: norm_matrix_le_mult_op_norm simp: \n      mult.commute matrix_vector_right_distrib vector_scaleR_commute)\n\nlemma op_norm_eq_0: \"(\\<parallel>A\\<parallel>\\<^sub>o\\<^sub>p = 0) = (A = 0)\" for A :: \"('a::real_normed_field)^'n^'m\"\n  unfolding onorm_eq_0[OF blin_matrix_vector_mult] using matrix_axis_0[of 1 A] by fastforce\n\nlemma op_norm0: \"\\<parallel>(0::('a::real_normed_field)^'n^'m)\\<parallel>\\<^sub>o\\<^sub>p = 0\"\n  using op_norm_eq_0[of 0] by simp\n                  \nlemma op_norm_triangle: \"\\<parallel>A + B\\<parallel>\\<^sub>o\\<^sub>p \\<le> (\\<parallel>A\\<parallel>\\<^sub>o\\<^sub>p) + (\\<parallel>B\\<parallel>\\<^sub>o\\<^sub>p)\" \n  using onorm_triangle[OF blin_matrix_vector_mult[of A] blin_matrix_vector_mult[of B]]\n    matrix_vector_mult_add_rdistrib[symmetric, of A _ B] by simp\n\nlemma op_norm_scaleR: \"\\<parallel>c *\\<^sub>R A\\<parallel>\\<^sub>o\\<^sub>p = \\<bar>c\\<bar> * (\\<parallel>A\\<parallel>\\<^sub>o\\<^sub>p)\"\n  unfolding onorm_scaleR[OF blin_matrix_vector_mult, symmetric] scaleR_vector_assoc ..\n\n\n\nlemma norm_matrix_vec_mult_le_transpose:\n  \"\\<parallel>x\\<parallel> = 1 \\<Longrightarrow> (\\<parallel>A *v x\\<parallel>) \\<le> sqrt (\\<parallel>transpose A ** A\\<parallel>\\<^sub>o\\<^sub>p) * (\\<parallel>x\\<parallel>)\" for A :: \"real^'n^'n\"\nproof-\n  assume \"\\<parallel>x\\<parallel> = 1\"\n  have \"(\\<parallel>A *v x\\<parallel>)\\<^sup>2 = (A *v x) \\<bullet> (A *v x)\"\n    using dot_square_norm[of \"(A *v x)\"] by simp\n  also have \"... = x \\<bullet> (transpose A *v (A *v x))\"\n    using vec_mult_inner by blast\n  also have \"... \\<le> (\\<parallel>x\\<parallel>) * (\\<parallel>transpose A *v (A *v x)\\<parallel>)\"\n    using norm_cauchy_schwarz by blast\n  also have \"... \\<le> (\\<parallel>transpose A ** A\\<parallel>\\<^sub>o\\<^sub>p) * (\\<parallel>x\\<parallel>)^2\"\n    apply(subst matrix_vector_mul_assoc) \n    using norm_matrix_le_mult_op_norm[of \"transpose A ** A\" x]\n    by (simp add: \\<open>\\<parallel>x\\<parallel> = 1\\<close>) \n  finally have \"((\\<parallel>A *v x\\<parallel>))^2 \\<le> (\\<parallel>transpose A ** A\\<parallel>\\<^sub>o\\<^sub>p) * (\\<parallel>x\\<parallel>)^2\"\n    by linarith\n  thus \"(\\<parallel>A *v x\\<parallel>) \\<le> sqrt ((\\<parallel>transpose A ** A\\<parallel>\\<^sub>o\\<^sub>p)) * (\\<parallel>x\\<parallel>)\"\n    by (simp add: \\<open>\\<parallel>x\\<parallel> = 1\\<close> real_le_rsqrt)\nqed\n\nlemma op_norm_le_sum_column: \"\\<parallel>A\\<parallel>\\<^sub>o\\<^sub>p \\<le> (\\<Sum>i\\<in>UNIV. \\<parallel>column i A\\<parallel>)\" for A :: \"real^'n^'m\"  \nproof(unfold op_norm_def, rule cSup_least[OF op_norm_set_proptys(3)], clarsimp)\n  fix x :: \"real^'n\" assume x_def:\"\\<parallel>x\\<parallel> = 1\" \n  hence x_hyp:\"\\<And>i. \\<parallel>x $ i\\<parallel> \\<le> 1\"\n    by (simp add: norm_bound_component_le_cart)\n  have \"(\\<parallel>A *v x\\<parallel>) = \\<parallel>(\\<Sum>i\\<in>UNIV. x $ i *s column i A)\\<parallel>\"\n    by(subst matrix_mult_sum[of A], simp)\n  also have \"... \\<le> (\\<Sum>i\\<in>UNIV. \\<parallel>x $ i *s column i A\\<parallel>)\"\n    by (simp add: sum_norm_le)\n  also have \"... = (\\<Sum>i\\<in>UNIV. (\\<parallel>x $ i\\<parallel>) * (\\<parallel>column i A\\<parallel>))\"\n    by (simp add: mult_norm_matrix_sgn_eq)\n  also have \"... \\<le> (\\<Sum>i\\<in>UNIV. \\<parallel>column i A\\<parallel>)\"\n    using x_hyp by (simp add: mult_left_le_one_le sum_mono) \n  finally show \"\\<parallel>A *v x\\<parallel> \\<le> (\\<Sum>i\\<in>UNIV. \\<parallel>column i A\\<parallel>)\" .\nqed\n\nlemma op_norm_le_transpose: \"\\<parallel>A\\<parallel>\\<^sub>o\\<^sub>p \\<le> \\<parallel>transpose A\\<parallel>\\<^sub>o\\<^sub>p\" for A :: \"real^'n^'n\"  \nproof-\n  have obs:\"\\<forall>x. \\<parallel>x\\<parallel> = 1 \\<longrightarrow> (\\<parallel>A *v x\\<parallel>) \\<le> sqrt ((\\<parallel>transpose A ** A\\<parallel>\\<^sub>o\\<^sub>p)) * (\\<parallel>x\\<parallel>)\"\n    using norm_matrix_vec_mult_le_transpose by blast\n  have \"(\\<parallel>A\\<parallel>\\<^sub>o\\<^sub>p) \\<le> sqrt ((\\<parallel>transpose A ** A\\<parallel>\\<^sub>o\\<^sub>p))\"\n    using obs apply(unfold op_norm_def)\n    by (rule cSup_least[OF op_norm_set_proptys(3)]) clarsimp\n  hence \"((\\<parallel>A\\<parallel>\\<^sub>o\\<^sub>p))\\<^sup>2 \\<le> (\\<parallel>transpose A ** A\\<parallel>\\<^sub>o\\<^sub>p)\"\n    using power_mono[of \"(\\<parallel>A\\<parallel>\\<^sub>o\\<^sub>p)\" _ 2] op_norm_ge_0\n    by (metis not_le real_less_lsqrt)\n  also have \"... \\<le> (\\<parallel>transpose A\\<parallel>\\<^sub>o\\<^sub>p) * (\\<parallel>A\\<parallel>\\<^sub>o\\<^sub>p)\"\n    using op_norm_matrix_matrix_mult_le by blast\n  finally have \"((\\<parallel>A\\<parallel>\\<^sub>o\\<^sub>p))\\<^sup>2 \\<le> (\\<parallel>transpose A\\<parallel>\\<^sub>o\\<^sub>p) * (\\<parallel>A\\<parallel>\\<^sub>o\\<^sub>p)\"\n    by linarith\n  thus \"(\\<parallel>A\\<parallel>\\<^sub>o\\<^sub>p) \\<le> (\\<parallel>transpose A\\<parallel>\\<^sub>o\\<^sub>p)\"\n    using sq_le_cancel[of \"(\\<parallel>A\\<parallel>\\<^sub>o\\<^sub>p)\"] op_norm_ge_0 by metis\nqed\n\n\nsubsection\\<open> Matrix maximum norm \\<close>\n\nabbreviation max_norm :: \"real^'n^'m \\<Rightarrow> real\" (\"(1\\<parallel>_\\<parallel>\\<^sub>m\\<^sub>a\\<^sub>x)\" [65] 61)\n  where \"\\<parallel>A\\<parallel>\\<^sub>m\\<^sub>a\\<^sub>x \\<equiv> Max (abs ` (entries A))\"\n\nlemma max_norm_def: \"\\<parallel>A\\<parallel>\\<^sub>m\\<^sub>a\\<^sub>x = Max {\\<bar>A $ i $ j\\<bar>|i j. i\\<in>UNIV \\<and> j\\<in>UNIV}\"\n  by (simp add: image_def, rule arg_cong[of _ _ Max], blast)\n\nlemma max_norm_set_proptys: \"finite {\\<bar>A $ i $ j\\<bar> |i j. i \\<in> UNIV \\<and> j \\<in> UNIV}\" (is \"finite ?X\")\nproof-\n  have \"\\<And>i. finite {\\<bar>A $ i $ j\\<bar> | j. j \\<in> UNIV}\"\n    using finite_Atleast_Atmost_nat by fastforce\n  hence \"finite (\\<Union>i\\<in>UNIV. {\\<bar>A $ i $ j\\<bar> | j. j \\<in> UNIV})\" (is \"finite ?Y\")\n    using finite_class.finite_UNIV by blast\n  also have \"?X \\<subseteq> ?Y\" \n    by auto\n  ultimately show ?thesis \n    using finite_subset by blast\nqed\n\nlemma max_norm_ge_0: \"0 \\<le> \\<parallel>A\\<parallel>\\<^sub>m\\<^sub>a\\<^sub>x\"\n  unfolding max_norm_def \n  apply(rule order.trans[OF abs_ge_zero[of \"A $ _ $ _\"] Max_ge])\n  using max_norm_set_proptys by auto\n\nlemma op_norm_le_max_norm:\n  fixes A :: \"real^('n::finite)^('m::finite)\"\n  shows \"\\<parallel>A\\<parallel>\\<^sub>o\\<^sub>p \\<le> real CARD('m) * real CARD('n) * (\\<parallel>A\\<parallel>\\<^sub>m\\<^sub>a\\<^sub>x)\"\n  apply(rule onorm_le_matrix_component)\n  unfolding max_norm_def by(rule Max_ge[OF max_norm_set_proptys]) force\n\nlemma sqrt_Sup_power2_eq_Sup_abs:\n  \"finite A \\<Longrightarrow> A \\<noteq> {} \\<Longrightarrow> sqrt (Sup {(f i)\\<^sup>2 |i. i \\<in> A}) = Sup {\\<bar>f i\\<bar> |i. i \\<in> A}\"\nproof(rule sym)\n  assume assms: \"finite A\" \"A \\<noteq> {}\"\n  then obtain i where i_def: \"i \\<in> A \\<and> Sup {(f i)\\<^sup>2|i. i \\<in> A} = (f i)^2\"\n    using cSup_finite_ex[of \"{(f i)\\<^sup>2|i. i \\<in> A}\"] by auto\n  hence lhs: \"sqrt (Sup {(f i)\\<^sup>2 |i. i \\<in> A}) = \\<bar>f i\\<bar>\"\n    by simp\n  have \"finite {(f i)\\<^sup>2|i. i \\<in> A}\"\n    using assms by simp\n  hence \"\\<forall>j\\<in>A. (f j)\\<^sup>2 \\<le> (f i)\\<^sup>2\"\n    using i_def cSup_upper[of _ \"{(f i)\\<^sup>2 |i. i \\<in> A}\"] by force\n  hence \"\\<forall>j\\<in>A. \\<bar>f j\\<bar> \\<le> \\<bar>f i\\<bar>\"\n    using abs_le_square_iff by blast\n  also have \"\\<bar>f i\\<bar> \\<in> {\\<bar>f i\\<bar> |i. i \\<in> A}\"\n    using i_def by auto\n  ultimately show \"Sup {\\<bar>f i\\<bar> |i. i \\<in> A} = sqrt (Sup {(f i)\\<^sup>2 |i. i \\<in> A})\"\n    using cSup_mem_eq[of \"\\<bar>f i\\<bar>\" \"{\\<bar>f i\\<bar> |i. i \\<in> A}\"] lhs by auto\nqed\n\nlemma sqrt_Max_power2_eq_max_abs:\n  \"finite A \\<Longrightarrow> A \\<noteq> {} \\<Longrightarrow> sqrt (Max {(f i)\\<^sup>2|i. i \\<in> A}) = Max {\\<bar>f i\\<bar> |i. i \\<in> A}\"\n  apply(subst cSup_eq_Max[symmetric], simp_all)+\n  using sqrt_Sup_power2_eq_Sup_abs .\n\nlemma op_norm_diag_mat_eq: \"\\<parallel>diag_mat f\\<parallel>\\<^sub>o\\<^sub>p = Max {\\<bar>f i\\<bar> |i. i \\<in> UNIV}\" (is \"_ = Max ?A\")\nproof(unfold op_norm_def)\n  have obs: \"\\<And>x i. (f i)\\<^sup>2 * (x $ i)\\<^sup>2 \\<le> Max {(f i)\\<^sup>2|i. i \\<in> UNIV} * (x $ i)\\<^sup>2\"\n    apply(rule mult_right_mono[OF _ zero_le_power2])\n    using le_max_image_of_finite[of \"\\<lambda>i. (f i)^2\"] by simp\n  {fix r assume \"r \\<in> {\\<parallel>diag_mat f *v x\\<parallel> |x. \\<parallel>x\\<parallel> = 1}\"\n    then obtain x where x_def: \"\\<parallel>diag_mat f *v x\\<parallel> = r \\<and> \\<parallel>x\\<parallel> = 1\"\n      by blast\n    hence \"r\\<^sup>2 = (\\<Sum>i\\<in>UNIV. (f i)\\<^sup>2 * (x $ i)\\<^sup>2)\"\n      unfolding norm_vec_def L2_set_def matrix_vector_mul_diag_mat \n      apply (simp add: power_mult_distrib)\n      by (metis (no_types, lifting) x_def norm_ge_zero real_sqrt_ge_0_iff real_sqrt_pow2)\n    also have \"... \\<le> (Max {(f i)\\<^sup>2|i. i \\<in> UNIV}) * (\\<Sum>i\\<in>UNIV. (x $ i)\\<^sup>2)\"\n      using obs[of _ x] by (simp add: sum_mono sum_distrib_left)\n    also have \"... = Max {(f i)\\<^sup>2|i. i \\<in> UNIV}\"\n      using x_def by (simp add: norm_vec_def L2_set_def)\n    finally have \"r \\<le> sqrt (Max {(f i)\\<^sup>2|i. i \\<in> UNIV})\"\n      using x_def real_le_rsqrt by blast \n    hence \"r \\<le> Max ?A\"\n      by (subst (asm) sqrt_Max_power2_eq_max_abs[of UNIV f], simp_all)}\n  hence 1: \"\\<forall>x\\<in>{\\<parallel>diag_mat f *v x\\<parallel> |x. \\<parallel>x\\<parallel> = 1}. x \\<le> Max ?A\"\n    unfolding diag_mat_def by blast\n  obtain i where i_def: \"Max ?A = \\<parallel>diag_mat f *v \\<e> i\\<parallel>\"\n    using cMax_finite_ex[of ?A] by force\n  hence 2: \"\\<exists>x\\<in>{\\<parallel>diag_mat f *v x\\<parallel> |x. \\<parallel>x\\<parallel> = 1}. Max ?A \\<le> x\"\n    by (metis (mono_tags, lifting) abs_1 mem_Collect_eq norm_axis_eq order_refl real_norm_def)\n  show \"Sup {\\<parallel>diag_mat f *v x\\<parallel> |x. \\<parallel>x\\<parallel> = 1} = Max ?A\"\n    by (rule cSup_eq[OF 1 2])\nqed\n\nlemma op_max_norms_eq_at_diag: \"\\<parallel>diag_mat f\\<parallel>\\<^sub>o\\<^sub>p = \\<parallel>diag_mat f\\<parallel>\\<^sub>m\\<^sub>a\\<^sub>x\"\nproof(rule antisym)\n  have \"{\\<bar>f i\\<bar> |i. i \\<in> UNIV} \\<subseteq> {\\<bar>diag_mat f $ i $ j\\<bar> |i j. i \\<in> UNIV \\<and> j \\<in> UNIV}\"\n    by (smt Collect_mono diag_mat_vec_nth_simps(1))\n  thus \"\\<parallel>diag_mat f\\<parallel>\\<^sub>o\\<^sub>p \\<le> \\<parallel>diag_mat f\\<parallel>\\<^sub>m\\<^sub>a\\<^sub>x\"\n    unfolding op_norm_diag_mat_eq max_norm_def\n    by (rule Max.subset_imp) (blast, simp only: finite_image_of_finite2)\nnext\n  have \"Sup {\\<bar>diag_mat f $ i $ j\\<bar> |i j. i \\<in> UNIV \\<and> j \\<in> UNIV} \\<le> Sup {\\<bar>f i\\<bar> |i. i \\<in> UNIV}\"\n    apply(rule cSup_least, blast, clarify, case_tac \"i = j\", simp)\n    by (rule cSup_upper, blast, simp_all) (rule cSup_upper2, auto)\n  thus \"\\<parallel>diag_mat f\\<parallel>\\<^sub>m\\<^sub>a\\<^sub>x \\<le> \\<parallel>diag_mat f\\<parallel>\\<^sub>o\\<^sub>p\"\n    unfolding op_norm_diag_mat_eq max_norm_def\n    apply (subst cSup_eq_Max[symmetric], simp only: finite_image_of_finite2, blast)\n    by (subst cSup_eq_Max[symmetric], simp, blast)\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/Matrices_for_ODEs/MTX_Norms.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8688267694452331, "lm_q2_score": 0.8459424431344437, "lm_q1q2_score": 0.7349774400051065}}
{"text": "theory NatStrongInduct\n\nimports Main\n\nbegin\n\n\\<comment> \\<open>\n  Transformation of our induction hypothesis into the form expected by less_induct.\n\\<close>\nlemma suc_induct:\n  assumes \\<open>\\<And>n. \\<forall>m \\<le> n. P m \\<Longrightarrow> P (Suc n)\\<close>\n  and     \\<open>P 0\\<close>\n  and     \\<open>\\<forall>m < n. P m\\<close>\n  shows   \\<open>P n\\<close>\nproof (cases n)\n  case 0\n    thus ?thesis using assms(2) by simp\nnext\n  case (Suc k)\n    thus ?thesis using assms le_imp_less_Suc by blast\nqed\n\n\\<comment> \\<open>\n Another induction rule for Noetherian induction that is easier to use in some proofs\n\\<close>\nlemma nat_strong_induct [case_names 0 Suc]:\n  fixes P :: \\<open>nat \\<Rightarrow> bool\\<close>\n  assumes \\<open>P 0\\<close>\n      and \\<open>\\<And>n. \\<forall>m \\<le> n. P m \\<Longrightarrow> P (Suc n)\\<close>\n    shows \\<open>P n\\<close>\nusing suc_induct[of \\<open>P\\<close>] assms less_induct[of \\<open>P\\<close> \\<open>n\\<close>] by blast\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/NatStrongInduct.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8688267626522814, "lm_q2_score": 0.8459424431344437, "lm_q1q2_score": 0.7349774342586604}}
{"text": "(*  Title:       Matrix norms\n    Author:      Jonathan Juli\u00e1n Huerta y Munive, 2020\n    Maintainer:  Jonathan Juli\u00e1n Huerta y Munive <jjhuertaymunive1@sheffield.ac.uk>\n*)\n\nsection \\<open> Matrix norms \\<close>\n\ntext \\<open> Here, we explore some properties about the operator and the maximum norms for matrices. \\<close>\n\ntheory MTX_Norms\n  imports MTX_Preliminaries\n\nbegin\n\n\nsubsection\\<open> Matrix operator norm \\<close>\n\nabbreviation op_norm :: \"('a::real_normed_algebra_1)^'n^'m \\<Rightarrow> real\" (\"(1\\<parallel>_\\<parallel>\\<^sub>o\\<^sub>p)\" [65] 61)\n  where \"\\<parallel>A\\<parallel>\\<^sub>o\\<^sub>p \\<equiv> onorm (\\<lambda>x. A *v x)\"\n\nlemma norm_matrix_bound:\n  fixes A :: \"('a::real_normed_algebra_1)^'n^'m\"\n  shows \"\\<parallel>x\\<parallel> = 1 \\<Longrightarrow> \\<parallel>A *v x\\<parallel> \\<le> \\<parallel>(\\<chi> i j. \\<parallel>A $ i $ j\\<parallel>) *v 1\\<parallel>\"\nproof-\n  fix x :: \"('a, 'n) vec\" assume \"\\<parallel>x\\<parallel> = 1\"\n  hence xi_le1:\"\\<And>i. \\<parallel>x $ i\\<parallel> \\<le> 1\" \n    by (metis Finite_Cartesian_Product.norm_nth_le) \n  {fix j::'m \n    have \"\\<parallel>(\\<Sum>i\\<in>UNIV. A $ j $ i * x $ i)\\<parallel> \\<le> (\\<Sum>i\\<in>UNIV. \\<parallel>A $ j $ i * x $ i\\<parallel>)\"\n      using norm_sum by blast\n    also have \"... \\<le> (\\<Sum>i\\<in>UNIV. (\\<parallel>A $ j $ i\\<parallel>) * (\\<parallel>x $ i\\<parallel>))\"\n      by (simp add: norm_mult_ineq sum_mono)\n    also have \"... \\<le> (\\<Sum>i\\<in>UNIV. (\\<parallel>A $ j $ i\\<parallel>) * 1)\"\n      using xi_le1 by (simp add: sum_mono mult_left_le)\n    finally have \"\\<parallel>(\\<Sum>i\\<in>UNIV. A $ j $ i * x $ i)\\<parallel> \\<le> (\\<Sum>i\\<in>UNIV. (\\<parallel>A $ j $ i\\<parallel>) * 1)\" by simp}\n  hence \"\\<And>j. \\<parallel>(A *v x) $ j\\<parallel> \\<le> ((\\<chi> i1 i2. \\<parallel>A $ i1 $ i2\\<parallel>) *v 1) $ j\"\n    unfolding matrix_vector_mult_def by simp\n  hence \"(\\<Sum>j\\<in>UNIV. (\\<parallel>(A *v x) $ j\\<parallel>)\\<^sup>2) \\<le> (\\<Sum>j\\<in>UNIV. (\\<parallel>((\\<chi> i1 i2. \\<parallel>A $ i1 $ i2\\<parallel>) *v 1) $ j\\<parallel>)\\<^sup>2)\"\n    by (metis (mono_tags, lifting) norm_ge_zero power2_abs power_mono real_norm_def sum_mono) \n  thus \"\\<parallel>A *v x\\<parallel> \\<le> \\<parallel>(\\<chi> i j. \\<parallel>A $ i $ j\\<parallel>) *v 1\\<parallel>\"\n    unfolding norm_vec_def L2_set_def by simp\nqed\n\nlemma onorm_set_proptys:\n  fixes A :: \"('a::real_normed_algebra_1)^'n^'m\"\n  shows \"bounded (range (\\<lambda>x. (\\<parallel>A *v x\\<parallel>) / (\\<parallel>x\\<parallel>)))\"\n    and \"bdd_above (range (\\<lambda>x. (\\<parallel>A *v x\\<parallel>) / (\\<parallel>x\\<parallel>)))\"\n    and \"(range (\\<lambda>x. (\\<parallel>A *v x\\<parallel>) / (\\<parallel>x\\<parallel>))) \\<noteq> {}\"\n  unfolding bounded_def bdd_above_def image_def dist_real_def \n    apply(rule_tac x=0 in exI)\n  by (rule_tac x=\"\\<parallel>(\\<chi> i j. \\<parallel>A $ i $ j\\<parallel>) *v 1\\<parallel>\" in exI, clarsimp,\n      subst mult_norm_matrix_sgn_eq[symmetric], clarsimp,\n      rule_tac x=\"sgn _\" in norm_matrix_bound, simp add: norm_sgn)+ force\n\nlemma op_norm_set_proptys:\n  fixes A :: \"('a::real_normed_algebra_1)^'n^'m\"\n  shows \"bounded {\\<parallel>A *v x\\<parallel> | x. \\<parallel>x\\<parallel> = 1}\"\n    and \"bdd_above {\\<parallel>A *v x\\<parallel> | x. \\<parallel>x\\<parallel> = 1}\"\n    and \"{\\<parallel>A *v x\\<parallel> | x. \\<parallel>x\\<parallel> = 1} \\<noteq> {}\"\n  unfolding bounded_def bdd_above_def apply safe\n    apply(rule_tac x=0 in exI, rule_tac x=\"\\<parallel>(\\<chi> i j. \\<parallel>A $ i $ j\\<parallel>) *v 1\\<parallel>\" in exI)\n    apply(force simp: norm_matrix_bound dist_real_def)\n   apply(rule_tac x=\"\\<parallel>(\\<chi> i j. \\<parallel>A $ i $ j\\<parallel>) *v 1\\<parallel>\" in exI, force simp: norm_matrix_bound)\n  using ex_norm_eq_1 by blast\n\nlemma op_norm_def: \"\\<parallel>A\\<parallel>\\<^sub>o\\<^sub>p = Sup {\\<parallel>A *v x\\<parallel> | x. \\<parallel>x\\<parallel> = 1}\"\n  apply(rule antisym[OF onorm_le cSup_least[OF op_norm_set_proptys(3)]])\n   apply(case_tac \"x = 0\", simp)\n   apply(subst mult_norm_matrix_sgn_eq[symmetric], simp)\n   apply(rule cSup_upper[OF _ op_norm_set_proptys(2)])\n   apply(force simp: norm_sgn)\n  unfolding onorm_def \n  apply(rule cSup_upper[OF _ onorm_set_proptys(2)])\n  by (simp add: image_def, clarsimp) (metis div_by_1)\n\nlemma norm_matrix_le_op_norm: \"\\<parallel>x\\<parallel> = 1 \\<Longrightarrow> \\<parallel>A *v x\\<parallel> \\<le> \\<parallel>A\\<parallel>\\<^sub>o\\<^sub>p\"\n  apply(unfold onorm_def, rule cSup_upper[OF _ onorm_set_proptys(2)])\n  unfolding image_def by (clarsimp, rule_tac x=x in exI) simp\n\nlemma op_norm_ge_0: \"0 \\<le> \\<parallel>A\\<parallel>\\<^sub>o\\<^sub>p\"\n  using ex_norm_eq_1 norm_ge_zero norm_matrix_le_op_norm basic_trans_rules(23) by blast\n\nlemma norm_sgn_le_op_norm: \"\\<parallel>A *v sgn x\\<parallel> \\<le> \\<parallel>A\\<parallel>\\<^sub>o\\<^sub>p\"\n  by (cases \"x=0\", simp_all add: norm_sgn norm_matrix_le_op_norm op_norm_ge_0)\n\nlemma norm_matrix_le_mult_op_norm: \"\\<parallel>A *v x\\<parallel> \\<le> (\\<parallel>A\\<parallel>\\<^sub>o\\<^sub>p) * (\\<parallel>x\\<parallel>)\"\nproof-\n  have \"\\<parallel>A *v x\\<parallel> = (\\<parallel>A *v sgn x\\<parallel>) * (\\<parallel>x\\<parallel>)\"\n    by(simp add: mult_norm_matrix_sgn_eq)\n  also have \"... \\<le> (\\<parallel>A\\<parallel>\\<^sub>o\\<^sub>p) * (\\<parallel>x\\<parallel>)\"\n    using norm_sgn_le_op_norm[of A] by (simp add: mult_mono')\n  finally show ?thesis by simp\nqed\n\nlemma blin_matrix_vector_mult: \"bounded_linear ((*v) A)\" for A :: \"('a::real_normed_algebra_1)^'n^'m\"\n  by (unfold_locales) (auto intro: norm_matrix_le_mult_op_norm simp: \n      mult.commute matrix_vector_right_distrib vector_scaleR_commute)\n\nlemma op_norm_eq_0: \"(\\<parallel>A\\<parallel>\\<^sub>o\\<^sub>p = 0) = (A = 0)\" for A :: \"('a::real_normed_field)^'n^'m\"\n  unfolding onorm_eq_0[OF blin_matrix_vector_mult] using matrix_axis_0[of 1 A] by fastforce\n\nlemma op_norm0: \"\\<parallel>(0::('a::real_normed_field)^'n^'m)\\<parallel>\\<^sub>o\\<^sub>p = 0\"\n  using op_norm_eq_0[of 0] by simp\n                  \nlemma op_norm_triangle: \"\\<parallel>A + B\\<parallel>\\<^sub>o\\<^sub>p \\<le> (\\<parallel>A\\<parallel>\\<^sub>o\\<^sub>p) + (\\<parallel>B\\<parallel>\\<^sub>o\\<^sub>p)\" \n  using onorm_triangle[OF blin_matrix_vector_mult[of A] blin_matrix_vector_mult[of B]]\n    matrix_vector_mult_add_rdistrib[symmetric, of A _ B] by simp\n\nlemma op_norm_scaleR: \"\\<parallel>c *\\<^sub>R A\\<parallel>\\<^sub>o\\<^sub>p = \\<bar>c\\<bar> * (\\<parallel>A\\<parallel>\\<^sub>o\\<^sub>p)\"\n  unfolding onorm_scaleR[OF blin_matrix_vector_mult, symmetric] scaleR_vector_assoc ..\n\n\n\nlemma norm_matrix_vec_mult_le_transpose:\n  \"\\<parallel>x\\<parallel> = 1 \\<Longrightarrow> (\\<parallel>A *v x\\<parallel>) \\<le> sqrt (\\<parallel>transpose A ** A\\<parallel>\\<^sub>o\\<^sub>p) * (\\<parallel>x\\<parallel>)\" for A :: \"real^'n^'n\"\nproof-\n  assume \"\\<parallel>x\\<parallel> = 1\"\n  have \"(\\<parallel>A *v x\\<parallel>)\\<^sup>2 = (A *v x) \\<bullet> (A *v x)\"\n    using dot_square_norm[of \"(A *v x)\"] by simp\n  also have \"... = x \\<bullet> (transpose A *v (A *v x))\"\n    using vec_mult_inner by blast\n  also have \"... \\<le> (\\<parallel>x\\<parallel>) * (\\<parallel>transpose A *v (A *v x)\\<parallel>)\"\n    using norm_cauchy_schwarz by blast\n  also have \"... \\<le> (\\<parallel>transpose A ** A\\<parallel>\\<^sub>o\\<^sub>p) * (\\<parallel>x\\<parallel>)^2\"\n    apply(subst matrix_vector_mul_assoc) \n    using norm_matrix_le_mult_op_norm[of \"transpose A ** A\" x]\n    by (simp add: \\<open>\\<parallel>x\\<parallel> = 1\\<close>) \n  finally have \"((\\<parallel>A *v x\\<parallel>))^2 \\<le> (\\<parallel>transpose A ** A\\<parallel>\\<^sub>o\\<^sub>p) * (\\<parallel>x\\<parallel>)^2\"\n    by linarith\n  thus \"(\\<parallel>A *v x\\<parallel>) \\<le> sqrt ((\\<parallel>transpose A ** A\\<parallel>\\<^sub>o\\<^sub>p)) * (\\<parallel>x\\<parallel>)\"\n    by (simp add: \\<open>\\<parallel>x\\<parallel> = 1\\<close> real_le_rsqrt)\nqed\n\nlemma op_norm_le_sum_column: \"\\<parallel>A\\<parallel>\\<^sub>o\\<^sub>p \\<le> (\\<Sum>i\\<in>UNIV. \\<parallel>column i A\\<parallel>)\" for A :: \"real^'n^'m\"  \nproof(unfold op_norm_def, rule cSup_least[OF op_norm_set_proptys(3)], clarsimp)\n  fix x :: \"real^'n\" assume x_def:\"\\<parallel>x\\<parallel> = 1\" \n  hence x_hyp:\"\\<And>i. \\<parallel>x $ i\\<parallel> \\<le> 1\"\n    by (simp add: norm_bound_component_le_cart)\n  have \"(\\<parallel>A *v x\\<parallel>) = \\<parallel>(\\<Sum>i\\<in>UNIV. x $ i *s column i A)\\<parallel>\"\n    by(subst matrix_mult_sum[of A], simp)\n  also have \"... \\<le> (\\<Sum>i\\<in>UNIV. \\<parallel>x $ i *s column i A\\<parallel>)\"\n    by (simp add: sum_norm_le)\n  also have \"... = (\\<Sum>i\\<in>UNIV. (\\<parallel>x $ i\\<parallel>) * (\\<parallel>column i A\\<parallel>))\"\n    by (simp add: mult_norm_matrix_sgn_eq)\n  also have \"... \\<le> (\\<Sum>i\\<in>UNIV. \\<parallel>column i A\\<parallel>)\"\n    using x_hyp by (simp add: mult_left_le_one_le sum_mono) \n  finally show \"\\<parallel>A *v x\\<parallel> \\<le> (\\<Sum>i\\<in>UNIV. \\<parallel>column i A\\<parallel>)\" .\nqed\n\nlemma op_norm_le_transpose: \"\\<parallel>A\\<parallel>\\<^sub>o\\<^sub>p \\<le> \\<parallel>transpose A\\<parallel>\\<^sub>o\\<^sub>p\" for A :: \"real^'n^'n\"  \nproof-\n  have obs:\"\\<forall>x. \\<parallel>x\\<parallel> = 1 \\<longrightarrow> (\\<parallel>A *v x\\<parallel>) \\<le> sqrt ((\\<parallel>transpose A ** A\\<parallel>\\<^sub>o\\<^sub>p)) * (\\<parallel>x\\<parallel>)\"\n    using norm_matrix_vec_mult_le_transpose by blast\n  have \"(\\<parallel>A\\<parallel>\\<^sub>o\\<^sub>p) \\<le> sqrt ((\\<parallel>transpose A ** A\\<parallel>\\<^sub>o\\<^sub>p))\"\n    using obs apply(unfold op_norm_def)\n    by (rule cSup_least[OF op_norm_set_proptys(3)]) clarsimp\n  hence \"((\\<parallel>A\\<parallel>\\<^sub>o\\<^sub>p))\\<^sup>2 \\<le> (\\<parallel>transpose A ** A\\<parallel>\\<^sub>o\\<^sub>p)\"\n    using power_mono[of \"(\\<parallel>A\\<parallel>\\<^sub>o\\<^sub>p)\" _ 2] op_norm_ge_0\n    by (metis not_le real_less_lsqrt)\n  also have \"... \\<le> (\\<parallel>transpose A\\<parallel>\\<^sub>o\\<^sub>p) * (\\<parallel>A\\<parallel>\\<^sub>o\\<^sub>p)\"\n    using op_norm_matrix_matrix_mult_le by blast\n  finally have \"((\\<parallel>A\\<parallel>\\<^sub>o\\<^sub>p))\\<^sup>2 \\<le> (\\<parallel>transpose A\\<parallel>\\<^sub>o\\<^sub>p) * (\\<parallel>A\\<parallel>\\<^sub>o\\<^sub>p)\"\n    by linarith\n  thus \"(\\<parallel>A\\<parallel>\\<^sub>o\\<^sub>p) \\<le> (\\<parallel>transpose A\\<parallel>\\<^sub>o\\<^sub>p)\"\n    using sq_le_cancel[of \"(\\<parallel>A\\<parallel>\\<^sub>o\\<^sub>p)\"] op_norm_ge_0 by metis\nqed\n\n\nsubsection\\<open> Matrix maximum norm \\<close>\n\nabbreviation max_norm :: \"real^'n^'m \\<Rightarrow> real\" (\"(1\\<parallel>_\\<parallel>\\<^sub>m\\<^sub>a\\<^sub>x)\" [65] 61)\n  where \"\\<parallel>A\\<parallel>\\<^sub>m\\<^sub>a\\<^sub>x \\<equiv> Max (abs ` (entries A))\"\n\nlemma max_norm_def: \"\\<parallel>A\\<parallel>\\<^sub>m\\<^sub>a\\<^sub>x = Max {\\<bar>A $ i $ j\\<bar>|i j. i\\<in>UNIV \\<and> j\\<in>UNIV}\"\n  by (simp add: image_def, rule arg_cong[of _ _ Max], blast)\n\nlemma max_norm_set_proptys: \"finite {\\<bar>A $ i $ j\\<bar> |i j. i \\<in> UNIV \\<and> j \\<in> UNIV}\" (is \"finite ?X\")\nproof-\n  have \"\\<And>i. finite {\\<bar>A $ i $ j\\<bar> | j. j \\<in> UNIV}\"\n    using finite_Atleast_Atmost_nat by fastforce\n  hence \"finite (\\<Union>i\\<in>UNIV. {\\<bar>A $ i $ j\\<bar> | j. j \\<in> UNIV})\" (is \"finite ?Y\")\n    using finite_class.finite_UNIV by blast\n  also have \"?X \\<subseteq> ?Y\" \n    by auto\n  ultimately show ?thesis \n    using finite_subset by blast\nqed\n\nlemma max_norm_ge_0: \"0 \\<le> \\<parallel>A\\<parallel>\\<^sub>m\\<^sub>a\\<^sub>x\"\n  unfolding max_norm_def \n  apply(rule order.trans[OF abs_ge_zero[of \"A $ _ $ _\"] Max_ge])\n  using max_norm_set_proptys by auto\n\nlemma op_norm_le_max_norm:\n  fixes A :: \"real^('n::finite)^('m::finite)\"\n  shows \"\\<parallel>A\\<parallel>\\<^sub>o\\<^sub>p \\<le> real CARD('m) * real CARD('n) * (\\<parallel>A\\<parallel>\\<^sub>m\\<^sub>a\\<^sub>x)\"\n  apply(rule onorm_le_matrix_component)\n  unfolding max_norm_def by(rule Max_ge[OF max_norm_set_proptys]) force\n\nlemma sqrt_Sup_power2_eq_Sup_abs:\n  \"finite A \\<Longrightarrow> A \\<noteq> {} \\<Longrightarrow> sqrt (Sup {(f i)\\<^sup>2 |i. i \\<in> A}) = Sup {\\<bar>f i\\<bar> |i. i \\<in> A}\"\nproof(rule sym)\n  assume assms: \"finite A\" \"A \\<noteq> {}\"\n  then obtain i where i_def: \"i \\<in> A \\<and> Sup {(f i)\\<^sup>2|i. i \\<in> A} = (f i)^2\"\n    using cSup_finite_ex[of \"{(f i)\\<^sup>2|i. i \\<in> A}\"] by auto\n  hence lhs: \"sqrt (Sup {(f i)\\<^sup>2 |i. i \\<in> A}) = \\<bar>f i\\<bar>\"\n    by simp\n  have \"finite {(f i)\\<^sup>2|i. i \\<in> A}\"\n    using assms by simp\n  hence \"\\<forall>j\\<in>A. (f j)\\<^sup>2 \\<le> (f i)\\<^sup>2\"\n    using i_def cSup_upper[of _ \"{(f i)\\<^sup>2 |i. i \\<in> A}\"] by force\n  hence \"\\<forall>j\\<in>A. \\<bar>f j\\<bar> \\<le> \\<bar>f i\\<bar>\"\n    using abs_le_square_iff by blast\n  also have \"\\<bar>f i\\<bar> \\<in> {\\<bar>f i\\<bar> |i. i \\<in> A}\"\n    using i_def by auto\n  ultimately show \"Sup {\\<bar>f i\\<bar> |i. i \\<in> A} = sqrt (Sup {(f i)\\<^sup>2 |i. i \\<in> A})\"\n    using cSup_mem_eq[of \"\\<bar>f i\\<bar>\" \"{\\<bar>f i\\<bar> |i. i \\<in> A}\"] lhs by auto\nqed\n\nlemma sqrt_Max_power2_eq_max_abs:\n  \"finite A \\<Longrightarrow> A \\<noteq> {} \\<Longrightarrow> sqrt (Max {(f i)\\<^sup>2|i. i \\<in> A}) = Max {\\<bar>f i\\<bar> |i. i \\<in> A}\"\n  apply(subst cSup_eq_Max[symmetric], simp_all)+\n  using sqrt_Sup_power2_eq_Sup_abs .\n\nlemma op_norm_diag_mat_eq: \"\\<parallel>diag_mat f\\<parallel>\\<^sub>o\\<^sub>p = Max {\\<bar>f i\\<bar> |i. i \\<in> UNIV}\" (is \"_ = Max ?A\")\nproof(unfold op_norm_def)\n  have obs: \"\\<And>x i. (f i)\\<^sup>2 * (x $ i)\\<^sup>2 \\<le> Max {(f i)\\<^sup>2|i. i \\<in> UNIV} * (x $ i)\\<^sup>2\"\n    apply(rule mult_right_mono[OF _ zero_le_power2])\n    using le_max_image_of_finite[of \"\\<lambda>i. (f i)^2\"] by simp\n  {fix r assume \"r \\<in> {\\<parallel>diag_mat f *v x\\<parallel> |x. \\<parallel>x\\<parallel> = 1}\"\n    then obtain x where x_def: \"\\<parallel>diag_mat f *v x\\<parallel> = r \\<and> \\<parallel>x\\<parallel> = 1\"\n      by blast\n    hence \"r\\<^sup>2 = (\\<Sum>i\\<in>UNIV. (f i)\\<^sup>2 * (x $ i)\\<^sup>2)\"\n      unfolding norm_vec_def L2_set_def matrix_vector_mul_diag_mat \n      apply (simp add: power_mult_distrib)\n      by (metis (no_types, lifting) x_def norm_ge_zero real_sqrt_ge_0_iff real_sqrt_pow2)\n    also have \"... \\<le> (Max {(f i)\\<^sup>2|i. i \\<in> UNIV}) * (\\<Sum>i\\<in>UNIV. (x $ i)\\<^sup>2)\"\n      using obs[of _ x] by (simp add: sum_mono sum_distrib_left)\n    also have \"... = Max {(f i)\\<^sup>2|i. i \\<in> UNIV}\"\n      using x_def by (simp add: norm_vec_def L2_set_def)\n    finally have \"r \\<le> sqrt (Max {(f i)\\<^sup>2|i. i \\<in> UNIV})\"\n      using x_def real_le_rsqrt by blast \n    hence \"r \\<le> Max ?A\"\n      by (subst (asm) sqrt_Max_power2_eq_max_abs[of UNIV f], simp_all)}\n  hence 1: \"\\<forall>x\\<in>{\\<parallel>diag_mat f *v x\\<parallel> |x. \\<parallel>x\\<parallel> = 1}. x \\<le> Max ?A\"\n    unfolding diag_mat_def by blast\n  obtain i where i_def: \"Max ?A = \\<parallel>diag_mat f *v \\<e> i\\<parallel>\"\n    using cMax_finite_ex[of ?A] by force\n  hence 2: \"\\<exists>x\\<in>{\\<parallel>diag_mat f *v x\\<parallel> |x. \\<parallel>x\\<parallel> = 1}. Max ?A \\<le> x\"\n    by (metis (mono_tags, lifting) abs_1 mem_Collect_eq norm_axis_eq order_refl real_norm_def)\n  show \"Sup {\\<parallel>diag_mat f *v x\\<parallel> |x. \\<parallel>x\\<parallel> = 1} = Max ?A\"\n    by (rule cSup_eq[OF 1 2])\nqed\n\nlemma op_max_norms_eq_at_diag: \"\\<parallel>diag_mat f\\<parallel>\\<^sub>o\\<^sub>p = \\<parallel>diag_mat f\\<parallel>\\<^sub>m\\<^sub>a\\<^sub>x\"\nproof(rule antisym)\n  have \"{\\<bar>f i\\<bar> |i. i \\<in> UNIV} \\<subseteq> {\\<bar>diag_mat f $ i $ j\\<bar> |i j. i \\<in> UNIV \\<and> j \\<in> UNIV}\"\n    by (smt Collect_mono diag_mat_vec_nth_simps(1))\n  thus \"\\<parallel>diag_mat f\\<parallel>\\<^sub>o\\<^sub>p \\<le> \\<parallel>diag_mat f\\<parallel>\\<^sub>m\\<^sub>a\\<^sub>x\"\n    unfolding op_norm_diag_mat_eq max_norm_def\n    by (rule Max.subset_imp) (blast, simp only: finite_image_of_finite2)\nnext\n  have \"Sup {\\<bar>diag_mat f $ i $ j\\<bar> |i j. i \\<in> UNIV \\<and> j \\<in> UNIV} \\<le> Sup {\\<bar>f i\\<bar> |i. i \\<in> UNIV}\"\n    apply(rule cSup_least, blast, clarify, case_tac \"i = j\", simp)\n    by (rule cSup_upper, blast, simp_all) (rule cSup_upper2, auto)\n  thus \"\\<parallel>diag_mat f\\<parallel>\\<^sub>m\\<^sub>a\\<^sub>x \\<le> \\<parallel>diag_mat f\\<parallel>\\<^sub>o\\<^sub>p\"\n    unfolding op_norm_diag_mat_eq max_norm_def\n    apply (subst cSup_eq_Max[symmetric], simp only: finite_image_of_finite2, blast)\n    by (subst cSup_eq_Max[symmetric], simp, blast)\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/Matrices_for_ODEs/MTX_Norms.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8688267728417087, "lm_q2_score": 0.8459424314825853, "lm_q1q2_score": 0.7349774327548829}}
{"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_MainRLT\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  using complex_mod_triangle_ineq2[of \"w + z\" \"-z\"] by auto\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> norm c + r * m\"\n      using mult_mono[OF H th rp norm_ge_zero[of \"poly cs z\"]]\n      by (simp add: norm_mult)\n    also have \"\\<dots> \\<le> ?k\"\n      by simp\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: \"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  apply (induct p)\n  apply (simp add: offset_poly_0)\n  apply (simp add: offset_poly_pCons algebra_simps)\n  done\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: \"offset_poly p h = 0 \\<longleftrightarrow> p = 0\"\n  apply (safe intro!: offset_poly_0)\n  apply (induct p)\n  apply simp\n  apply (simp add: offset_poly_pCons)\n  apply (frule offset_poly_eq_0_lemma, simp)\n  done\n\nlemma degree_offset_poly: \"degree (offset_poly p h) = degree p\"\n  apply (induct p)\n  apply (simp add: offset_poly_0)\n  apply (case_tac \"p = 0\")\n  apply (simp add: offset_poly_0 offset_poly_pCons)\n  apply (simp add: offset_poly_pCons)\n  apply (subst degree_add_eq_right)\n  apply (rule le_less_trans [OF degree_smult_le])\n  apply (simp add: offset_poly_eq_0_iff)\n  apply (simp add: offset_poly_eq_0_iff)\n  done\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))\"\nproof (intro exI conjI)\n  show \"psize (offset_poly p a) = psize p\"\n    unfolding psize_def\n    by (simp add: offset_poly_eq_0_iff degree_offset_poly)\n  show \"\\<forall>x. poly (offset_poly p a) x = poly p (a + x)\"\n    by (simp add: poly_offset_poly)\nqed\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 - (rule power_mono, simp, simp)+\n    then have th0: \"4 * x\\<^sup>2 \\<le> 1\" \"4 * y\\<^sup>2 \\<le> 1\"\n      by (simp_all add: power_mult_distrib)\n    from add_mono[OF th0] xy show ?thesis\n      by simp\n  qed\n  then show ?thesis\n    unfolding linorder_not_le[symmetric] by blast\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 have \"\\<exists>m. n = 2 * m\"\n      by presburger\n    then obtain m where m: \"n = 2 * m\"\n      by blast\n    from n m have \"m \\<noteq> 0\" \"m < n\"\n      by presburger+\n    with IH[rule_format, of m] 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 th0: \"cmod (complex_of_real (cmod b) / b) = 1\"\n      using b by (simp add: norm_divide)\n    from unimodular_reduce_norm[OF th0] \\<open>odd n\\<close>\n    have \"\\<exists>v. cmod (complex_of_real (cmod b) / b + v^n) < 1\"\n      apply (cases \"cmod (complex_of_real (cmod b) / b + 1) < 1\")\n      apply (rule_tac x=\"1\" in exI)\n      apply simp\n      apply (cases \"cmod (complex_of_real (cmod b) / b - 1) < 1\")\n      apply (rule_tac x=\"-1\" in exI)\n      apply simp\n      apply (cases \"cmod (complex_of_real (cmod b) / b + \\<i>) < 1\")\n      apply (cases \"even m\")\n      apply (rule_tac x=\"\\<i>\" in exI)\n      apply (simp add: m power_mult)\n      apply (rule_tac x=\"- \\<i>\" in exI)\n      apply (simp add: m power_mult)\n      apply (cases \"even m\")\n      apply (rule_tac x=\"- \\<i>\" in exI)\n      apply (simp add: m power_mult)\n      apply (auto simp add: m power_mult)\n      apply (rule_tac x=\"\\<i>\" in exI)\n      apply (auto simp add: m power_mult)\n      done\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 th1: \"?w ^ n = v^n / complex_of_real (cmod b)\"\n      by (simp add: power_divide of_real_power[symmetric])\n    have th2:\"cmod (complex_of_real (cmod b) / b) = 1\"\n      using b by (simp add: norm_divide)\n    then have th3: \"cmod (complex_of_real (cmod b) / b) \\<ge> 0\"\n      by simp\n    have th4: \"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: th2)\n      done\n    from mult_left_less_imp_less[OF th4 th3]\n    have \"?P ?w n\" unfolding th1 .\n    then show ?thesis ..\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  from r[rule_format, of 0] have rp: \"r \\<ge> 0\"\n    using norm_ge_zero[of \"s 0\"] by arith\n  have th: \"\\<forall>n. r + 1 \\<ge> \\<bar>Re (s n)\\<bar>\"\n  proof\n    fix n\n    from abs_Re_le_cmod[of \"s n\"] r[rule_format, of n]\n    show \"\\<bar>Re (s n)\\<bar> \\<le> r + 1\" by arith\n  qed\n  have conv1: \"convergent (\\<lambda>n. Re (s (f n)))\"\n    apply (rule Bseq_monoseq_convergent)\n    apply (simp add: Bseq_def)\n    apply (metis gt_ex le_less_linear less_trans order.trans th)\n    apply (rule f(2))\n    done\n  have th: \"\\<forall>n. r + 1 \\<ge> \\<bar>Im (s n)\\<bar>\"\n  proof\n    fix n\n    from abs_Im_le_cmod[of \"s n\"] r[rule_format, of n]\n    show \"\\<bar>Im (s n)\\<bar> \\<le> r + 1\"\n      by arith\n  qed\n\n  have conv2: \"convergent (\\<lambda>n. Im (s (f (g n))))\"\n    apply (rule Bseq_monoseq_convergent)\n    apply (simp add: Bseq_def)\n    apply (metis gt_ex le_less_linear less_trans order.trans th)\n    apply (rule g(2))\n    done\n\n  from conv1[unfolded convergent_def] obtain x where \"LIMSEQ (\\<lambda>n. Re (s (f n))) x\"\n    by blast\n  then have x: \"\\<forall>r>0. \\<exists>n0. \\<forall>n\\<ge>n0. \\<bar>Re (s (f n)) - x\\<bar> < r\"\n    unfolding LIMSEQ_iff real_norm_def .\n\n  from conv2[unfolded convergent_def] obtain y where \"LIMSEQ (\\<lambda>n. Im (s (f (g n)))) y\"\n    by blast\n  then have y: \"\\<forall>r>0. \\<exists>n0. \\<forall>n\\<ge>n0. \\<bar>Im (s (f (g n))) - y\\<bar> < r\"\n    unfolding LIMSEQ_iff real_norm_def .\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[rule_format, OF e2] y[rule_format, OF 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      from add_strict_mono[OF N1[rule_format, OF nN1] N2[rule_format, OF nN2]]\n      show ?thesis\n        using metric_bound_lemma[of \"s (f (g n))\" ?w] by simp\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 q: \"degree q = degree p\" \"poly q x = poly p (z + x)\" for x\n  proof\n    show \"degree (offset_poly p z) = degree p\"\n      by (rule degree_offset_poly)\n    show \"\\<And>x. poly (offset_poly p z) x = poly p (z + x)\"\n      by (rule poly_offset_poly)\n  qed\n  have th: \"\\<And>w. poly q (w - z) = poly p w\"\n    using q(2)[of \"w - z\" for w] by simp\n  show ?thesis unfolding th[symmetric]\n  proof (induct q)\n    case 0\n    then show ?case\n      using ep by auto\n  next\n    case (pCons c cs)\n    from poly_bound_exists[of 1 \"cs\"]\n    obtain m where m: \"m > 0\" \"norm z \\<le> 1 \\<Longrightarrow> norm (poly cs z) \\<le> m\" for z\n      by blast\n    from ep m(1) have em0: \"e/m > 0\"\n      by (simp add: field_simps)\n    have one0: \"1 > (0::real)\"\n      by arith\n    from field_lbound_gt_zero[OF one0 em0]\n    obtain d where d: \"d > 0\" \"d < 1\" \"d < e / m\"\n      by blast\n    from d(1,3) m(1) have dm: \"d * m > 0\" \"d * m < e\"\n      by (simp_all add: field_simps)\n    show ?case\n    proof (rule ex_forward[OF field_lbound_gt_zero[OF one0 em0]], clarsimp simp add: norm_mult)\n      fix d w\n      assume H: \"d > 0\" \"d < 1\" \"d < e/m\" \"w \\<noteq> z\" \"norm (w - z) < d\"\n      then have d1: \"norm (w-z) \\<le> 1\" \"d \\<ge> 0\"\n        by simp_all\n      from H(3) m(1) have dme: \"d*m < e\"\n        by (simp add: field_simps)\n      from H have th: \"norm (w - z) \\<le> d\"\n        by simp\n      from mult_mono[OF th m(2)[OF d1(1)] d1(2) norm_ge_zero] dme\n      show \"norm (w - z) * norm (poly cs (w - z)) < e\"\n        by simp\n    qed\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 \"cmod 0 \\<le> r \\<and> cmod (poly p 0) = - (- cmod (poly p 0))\"\n      by simp\n    then have mth1: \"\\<exists>x z. cmod z \\<le> r \\<and> cmod (poly p z) = - x\"\n      by blast\n    have False if \"cmod z \\<le> r\" \"cmod (poly p z) = - x\" \"\\<not> x < 1\" for x z\n    proof -\n      from that have \"- x < 0 \"\n        by arith\n      with that(2) norm_ge_zero[of \"poly p z\"] show ?thesis\n        by simp\n    qed\n    then have mth2: \"\\<exists>z. \\<forall>x. (\\<exists>z. cmod z \\<le> r \\<and> cmod (poly p z) = - x) \\<longrightarrow> x < z\"\n      by blast\n    from real_sup_exists[OF mth1 mth2] obtain s where\n      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 blast\n    let ?m = \"- s\"\n    have s1[unfolded minus_minus]:\n      \"(\\<exists>z x. cmod z \\<le> r \\<and> - (- cmod (poly p z)) < y) \\<longleftrightarrow> ?m < y\" for y\n      using s[rule_format, of \"-y\"]\n      unfolding minus_less_iff[of y] equation_minus_iff by blast\n    from s1[of ?m] have s1m: \"\\<And>z x. cmod z \\<le> r \\<Longrightarrow> cmod (poly p z) \\<ge> ?m\"\n      by auto\n    have \"\\<exists>z. cmod z \\<le> r \\<and> cmod (poly p z) < - s + 1 / real (Suc n)\" for n\n      using s1[rule_format, of \"?m + 1/real (Suc n)\"] by simp\n    then have th: \"\\<forall>n. \\<exists>z. cmod z \\<le> r \\<and> cmod (poly p z) < - s + 1 / real (Suc n)\" ..\n    from choice[OF th] obtain g where\n        g: \"\\<forall>n. cmod (g n) \\<le> r\" \"\\<forall>n. cmod (poly p (g n)) <?m + 1 /real(Suc n)\"\n      by blast\n    from Bolzano_Weierstrass_complex_disc[OF g(1)]\n    obtain f z where fz: \"strict_mono (f :: nat \\<Rightarrow> nat)\" \"\\<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        from poly_cont[OF e2, of z p] obtain d where\n            d: \"d > 0\" \"\\<forall>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 th1: \"cmod(poly p w - poly p z) < ?e / 2\" if w: \"cmod (w - z) < d\" for w\n          using d(2)[rule_format, of w] w e by (cases \"w = z\") simp_all\n        from fz(2) d(1) obtain N1 where N1: \"\\<forall>n\\<ge>N1. cmod (g (f n) - z) < d\"\n          by blast\n        from reals_Archimedean2[of \"2/?e\"] obtain N2 :: nat where N2: \"2/?e < real N2\"\n          by blast\n        have th2: \"cmod (poly p (g (f (N1 + N2))) - poly p z) < ?e/2\"\n          using N1[rule_format, of \"N1 + N2\"] th1 by simp\n        have th0: \"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        have ath: \"m \\<le> x \\<Longrightarrow> x < m + e \\<Longrightarrow> \\<bar>x - m\\<bar> < e\" for m x e :: real\n          by arith\n        from s1m[OF g(1)[rule_format]] have th31: \"?m \\<le> cmod(poly p (g (f (N1 + N2))))\" .\n        from seq_suble[OF fz(1), of \"N1 + N2\"]\n        have th00: \"real (Suc (N1 + N2)) \\<le> real (Suc (f (N1 + N2)))\"\n          by simp\n        have th000: \"0 \\<le> (1::real)\" \"(1::real) \\<le> 1\" \"real (Suc (N1 + N2)) > 0\"\n          using N2 by auto\n        from frac_le[OF th000 th00]\n        have th00: \"?m + 1 / real (Suc (f (N1 + N2))) \\<le> ?m + 1 / real (Suc (N1 + N2))\"\n          by simp\n        from g(2)[rule_format, of \"f (N1 + N2)\"]\n        have th01:\"cmod (poly p (g (f (N1 + N2)))) < - s + 1 / real (Suc (f (N1 + N2)))\" .\n        from order_less_le_trans[OF th01 th00]\n        have th32: \"cmod (poly p (g (f (N1 + N2)))) < ?m + (1/ real(Suc (N1 + N2)))\" .\n        from N2 have \"2/?e < real (Suc (N1 + N2))\"\n          by arith\n        with 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 ath[OF th31 th32] have thc1: \"\\<bar>cmod (poly p (g (f (N1 + N2)))) - ?m\\<bar> < ?e/2\"\n          by arith\n        have ath2: \"\\<bar>a - b\\<bar> \\<le> c \\<Longrightarrow> \\<bar>b - m\\<bar> \\<le> \\<bar>a - m\\<bar> + c\" for a b c m :: real\n          by arith\n        have th22: \"\\<bar>cmod (poly p (g (f (N1 + N2)))) - cmod (poly p z)\\<bar> \\<le>\n            cmod (poly p (g (f (N1 + N2))) - poly p z)\"\n          by (simp add: norm_triangle_ineq3)\n        from ath2[OF th22, of ?m]\n        have thc2: \"2 * (?e/2) \\<le>\n            \\<bar>cmod(poly p (g (f (N1 + N2)))) - ?m\\<bar> + cmod (poly p (g (f (N1 + N2))) - poly p z)\"\n          by simp\n        from th0[OF th2 thc1 thc2] have False .\n      }\n      then have \"?e = 0\"\n        by auto\n      then have \"cmod (poly p z) = ?m\"\n        by simp\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 r0: \"r \\<le> norm z\"\n        using that by arith\n      from r[rule_format, OF r0] have th0: \"d + norm a \\<le> 1 * norm(poly (pCons c cs) z)\"\n        by arith\n      from that have z1: \"norm z \\<ge> 1\"\n        by arith\n      from order_trans[OF th0 mult_right_mono[OF z1 norm_ge_zero[of \"poly (pCons c cs) z\"]]]\n      have th1: \"d \\<le> norm(z * poly (pCons c cs) z) - norm a\"\n        unfolding norm_mult by (simp add: algebra_simps)\n      from norm_diff_ineq[of \"z * poly (pCons c cs) z\" a]\n      have th2: \"norm (z * poly (pCons c cs) z) - norm a \\<le> norm (poly (pCons a (pCons c cs)) z)\"\n        by (simp add: algebra_simps)\n      from th1 th2 show ?thesis\n        by arith\n    qed\n    then show ?thesis by blast\n  next\n    case True\n    with pCons.prems have c0: \"c \\<noteq> 0\"\n      by simp\n    have \"d \\<le> norm (poly (pCons a (pCons c cs)) z)\"\n      if h: \"(\\<bar>d\\<bar> + norm a) / norm c \\<le> norm z\" for z :: 'a\n    proof -\n      from c0 have \"norm c > 0\"\n        by simp\n      from h c0 have th0: \"\\<bar>d\\<bar> + norm a \\<le> norm (z * c)\"\n        by (simp add: field_simps norm_mult)\n      have ath: \"\\<And>mzh mazh ma. mzh \\<le> mazh + ma \\<Longrightarrow> \\<bar>d\\<bar> + ma \\<le> mzh \\<Longrightarrow> d \\<le> mazh\"\n        by arith\n      from norm_diff_ineq[of \"z * c\" a] have th1: \"norm (z * c) \\<le> norm (a + z * c) + norm a\"\n        by (simp add: algebra_simps)\n      from ath[OF th1 th0] show ?thesis\n        using True by simp\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    have ath: \"\\<And>z r. r \\<le> cmod z \\<or> cmod z \\<le> \\<bar>r\\<bar>\"\n      by arith\n    from poly_minimum_modulus_disc[of \"\\<bar>r\\<bar>\" \"pCons c cs\"]\n    obtain v where v: \"cmod (poly (pCons c cs) v) \\<le> cmod (poly (pCons c cs) w)\"\n      if \"cmod w \\<le> \\<bar>r\\<bar>\" for w\n      by blast\n    have \"cmod (poly (pCons c cs) v) \\<le> cmod (poly (pCons c cs) z)\" if z: \"r \\<le> cmod z\" for z\n      using v[of 0] r[OF z] by simp\n    with v ath[of r] show ?thesis\n      by blast\n  next\n    case True\n    with pCons.hyps show ?thesis\n      by simp\n  qed\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  next\n    case False\n    show ?thesis\n      apply (rule exI[where x=0])\n      apply (rule exI[where x=c])\n      apply (auto simp: False)\n      done\n  qed\nqed\n\nlemma poly_decompose:\n  assumes nc: \"\\<not> constant (poly p)\"\n  shows \"\\<exists>k a q. a \\<noteq> (0::'a::idom) \\<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  proof\n    assume \"\\<forall>z. z \\<noteq> 0 \\<longrightarrow> poly cs z = 0\"\n    then have \"poly (pCons c cs) x = poly (pCons c cs) y\" for x y\n      by (cases \"x = 0\") auto\n    with pCons.prems show False\n      by (auto simp add: constant_def)\n  qed\n  from poly_decompose_lemma[OF this]\n  show ?case\n    apply clarsimp\n    apply (rule_tac x=\"k+1\" in exI)\n    apply (rule_tac x=\"a\" in exI)\n    apply simp\n    apply (rule_tac x=\"q\" in exI)\n    apply (auto simp add: psize_def split: if_splits)\n    done\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    from poly_offset[of p c] obtain q where q: \"psize q = psize p\" \"\\<forall>x. poly q x = ?p (c + x)\"\n      by blast\n    have False if h: \"constant (poly q)\"\n    proof -\n      from q(2) have th: \"\\<forall>x. poly q (x - c) = ?p x\"\n        by auto\n      have \"?p x = ?p y\" for x y\n      proof -\n        from th have \"?p x = poly q (x - c)\"\n          by auto\n        also have \"\\<dots> = poly q (y - c)\"\n          using h unfolding constant_def by blast\n        also have \"\\<dots> = ?p y\"\n          using th by auto\n        finally show ?thesis .\n      qed\n      with less(2) show ?thesis\n        unfolding constant_def by blast\n    qed\n    then have qnc: \"\\<not> constant (poly q)\"\n      by blast\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      using a00\n      unfolding psize_def degree_def\n      by (simp add: poly_eq_iff)\n    have False if h: \"\\<And>x y. poly ?r x = poly ?r y\"\n    proof -\n      have \"poly q x = poly q y\" for x y\n      proof -\n        from qr[rule_format, of x] have \"poly q x = poly ?r x * ?a0\"\n          by auto\n        also have \"\\<dots> = poly ?r y * ?a0\"\n          using h by simp\n        also have \"\\<dots> = poly q y\"\n          using qr[rule_format, of y] by simp\n        finally show ?thesis .\n      qed\n      with qnc show ?thesis\n        unfolding constant_def by blast\n    qed\n    then have rnc: \"\\<not> constant (poly ?r)\"\n      unfolding constant_def by blast\n    from qr[rule_format, of 0] a00 have r01: \"poly ?r 0 = 1\"\n      by auto\n    have mrmq_eq: \"cmod (poly ?r w) < 1 \\<longleftrightarrow> cmod (poly q w) < cmod ?a0\" for w\n    proof -\n      have \"cmod (poly ?r w) < 1 \\<longleftrightarrow> cmod (poly q w / ?a0) < 1\"\n        using qr[rule_format, of w] a00 by (simp add: divide_inverse ac_simps)\n      also have \"\\<dots> \\<longleftrightarrow> cmod (poly q w) < cmod ?a0\"\n        using a00 unfolding norm_divide by (simp add: field_simps)\n      finally show ?thesis .\n    qed\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(3) lgqr[symmetric] q(1) have s0: \"s = 0\"\n        by auto\n      have hth[symmetric]: \"cmod (poly ?r w) = cmod (1 + a * w ^ k)\" for w\n        using kas(4)[rule_format, of w] s0 r01 by (simp add: algebra_simps)\n      from reduce_poly_simple[OF kas(1,2)] show ?thesis\n        unfolding hth by blast\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 th01: \"\\<not> constant (poly (pCons 1 (monom a (k - 1))))\"\n        unfolding constant_def poly_pCons poly_monom\n        using kas(1)\n        apply simp\n        apply (rule exI[where x=0])\n        apply (rule exI[where x=1])\n        apply simp\n        done\n      from kas(1) kas(2) have th02: \"k + 1 = psize (pCons 1 (monom a (k - 1)))\"\n        by (simp add: psize_def degree_monom_eq)\n      from less(1) [OF k1n [simplified th02] th01]\n      obtain w where w: \"1 + w^k * a = 0\"\n        unfolding poly_pCons poly_monom\n        using kas(2) by (cases k) (auto simp add: algebra_simps)\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 w0: \"w \\<noteq> 0\"\n        using kas(2) w by (auto simp add: power_0_left)\n      from w have \"(1 + w ^ k * a) - 1 = 0 - 1\"\n        by simp\n      then have wm1: \"w^k * a = - 1\"\n        by simp\n      have inv0: \"0 < inverse (cmod w ^ (k + 1) * m)\"\n        using norm_ge_zero[of w] w0 m(1)\n        by (simp add: inverse_eq_divide zero_less_mult_iff)\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 th11: \"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 \"t * cmod w \\<le> 1 * cmod w\"\n        apply (rule mult_mono)\n        using t(1,2)\n        apply auto\n        done\n      then have tw: \"cmod ?w \\<le> cmod w\"\n        using t(1) by (simp add: norm_mult)\n      from t inv0 have \"t * (cmod w ^ (k + 1) * m) < 1\"\n        by (simp add: field_simps)\n      with zero_less_power[OF t(1), of k] have th30: \"t^k * (t* (cmod w ^ (k + 1) * m)) < t^k * 1\"\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 w0 t(1)\n        by (simp add: algebra_simps power_mult_distrib norm_power norm_mult)\n      then have \"cmod (?w^k * ?w * poly s ?w) \\<le> t^k * (t* (cmod w ^ (k + 1) * m))\"\n        using t(1,2) m(2)[rule_format, OF tw] w0\n        by auto\n      with th30 have th120: \"cmod (?w^k * ?w * poly s ?w) < t^k\"\n        by simp\n      from power_strict_mono[OF t(2), of k] t(1) kas(2) have th121: \"t^k \\<le> 1\"\n        by auto\n      from ath[OF norm_ge_zero[of \"?w^k * ?w * poly s ?w\"] th120 th121]\n      have th12: \"\\<bar>1 - t^k\\<bar> + cmod (?w^k * ?w * poly s ?w) < 1\" .\n      from th11 th12 have \"cmod (1 + ?w^k * (a + ?w * poly s ?w)) < 1\"\n        by arith\n      then have \"cmod (poly ?r ?w) < 1\"\n        unfolding kas(4)[rule_format, of ?w] r01 by simp\n      then show ?thesis\n        by blast\n    qed\n    with cq0 q(2) show ?thesis\n      unfolding mrmq_eq not_less[symmetric] by auto\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)\"\n  using nc\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    then show ?thesis by auto\n  next\n    case False\n    have \"\\<not> constant (poly (pCons c cs))\"\n    proof\n      assume nc: \"constant (poly (pCons c cs))\"\n      from nc[unfolded constant_def, rule_format, of 0]\n      have \"\\<forall>w. w \\<noteq> 0 \\<longrightarrow> poly cs w = 0\" by auto\n      then have \"cs = 0\"\n      proof (induct cs)\n        case 0\n        then show ?case by simp\n      next\n        case (pCons d ds)\n        show ?case\n        proof (cases \"d = 0\")\n          case True\n          then show ?thesis\n            using pCons.prems pCons.hyps by simp\n        next\n          case False\n          from poly_bound_exists[of 1 ds] obtain m where\n            m: \"m > 0\" \"\\<forall>z. \\<forall>z. cmod z \\<le> 1 \\<longrightarrow> cmod (poly ds z) \\<le> m\" by blast\n          have dm: \"cmod d / m > 0\"\n            using False m(1) by (simp add: field_simps)\n          from field_lbound_gt_zero[OF dm zero_less_one]\n          obtain x where x: \"x > 0\" \"x < cmod d / m\" \"x < 1\"\n            by blast\n          let ?x = \"complex_of_real x\"\n          from x have cx: \"?x \\<noteq> 0\" \"cmod ?x \\<le> 1\"\n            by simp_all\n          from pCons.prems[rule_format, OF cx(1)]\n          have cth: \"cmod (?x*poly ds ?x) = cmod d\"\n            by (simp add: eq_diff_eq[symmetric])\n          from m(2)[rule_format, OF cx(2)] x(1)\n          have th0: \"cmod (?x*poly ds ?x) \\<le> x*m\"\n            by (simp add: norm_mult)\n          from x(2) m(1) have \"x * m < cmod d\"\n            by (simp add: field_simps)\n          with th0 have \"cmod (?x*poly ds ?x) \\<noteq> cmod d\"\n            by auto\n          with cth show ?thesis\n            by blast\n        qed\n      qed\n      then show False\n        using pCons.prems False by blast\n    qed\n    then show ?thesis\n      by (rule fundamental_theorem_of_algebra)\n  qed\nqed\n\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 = p * ?w\"\n            apply (subst r)\n            apply (subst s)\n            apply (subst kpn)\n            using k oop [of a]\n            apply (subst power_mult_distrib)\n            apply simp\n            apply (subst power_add [symmetric])\n            apply simp\n            done\n          then 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            apply auto\n            apply (erule ssubst)\n            apply (simp add: degree_mult_eq degree_linear_power)\n            done\n          have \"poly r x = 0\" if h: \"poly s x = 0\" for x\n          proof -\n            have xa: \"x \\<noteq> a\"\n            proof\n              assume \"x = a\"\n              from h[unfolded this poly_eq_0_iff_dvd] obtain u where u: \"s = [:- a, 1:] * u\"\n                by (rule dvdE)\n              have \"p = [:- a, 1:] ^ (Suc ?op) * u\"\n                apply (subst s)\n                apply (subst u)\n                apply (simp only: power_Suc ac_simps)\n                done\n              with ap(2)[unfolded dvd_def] show False\n                by blast\n            qed\n            from h have \"poly p x = 0\"\n              by (subst s) simp\n            with pq0 have \"poly q x = 0\"\n              by blast\n            with r xa show ?thesis\n              by auto\n          qed\n          with IH[rule_format, OF dsn, of s r] False have \"s dvd (r ^ (degree s))\"\n            by blast\n          then obtain u where u: \"r ^ (degree s) = s * u\" ..\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          let ?w = \"(u * ([:-a,1:] ^ (n - ?op))) * (r ^ (n - degree s))\"\n          from oop[of a] dsn have \"q ^ n = p * ?w\"\n            apply -\n            apply (subst s)\n            apply (subst r)\n            apply (simp only: power_mult_distrib)\n            apply (subst mult.assoc [where b=s])\n            apply (subst mult.assoc [where a=u])\n            apply (subst mult.assoc [where b=u, symmetric])\n            apply (subst u [symmetric])\n            apply (simp add: ac_simps power_add [symmetric])\n            done\n          then show ?thesis\n            unfolding dvd_def by blast\n        qed\n      qed\n    qed\n    then show ?thesis\n      using a order_root pne by blast\n  next\n    case False\n    with fundamental_theorem_of_algebra_alt[of p]\n    obtain c where ccs: \"c \\<noteq> 0\" \"p = pCons c 0\"\n      by blast\n    then have pp: \"poly p x = c\" for x\n      by simp\n    let ?w = \"[:1/c:] * (q ^ n)\"\n    from ccs have \"(q ^ n) = (p * ?w)\"\n      by simp\n    then show ?thesis\n      unfolding dvd_def by blast\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 eq: \"(\\<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    {\n      assume \"p dvd (q ^ (degree p))\"\n      then obtain r where r: \"q ^ (degree p) = p * r\" ..\n      from r p have False by simp\n    }\n    with eq p show ?thesis by blast\n  next\n    case dp: 2\n    then obtain k where k: \"p = [:k:]\" \"k \\<noteq> 0\"\n      by (cases p) (simp split: if_splits)\n    then have th1: \"\\<forall>x. poly p x \\<noteq> 0\"\n      by simp\n    from k dp(2) have \"q ^ (degree p) = p * [:1/k:]\"\n      by simp\n    then have th2: \"p dvd (q ^ (degree p))\" ..\n    from dp(1) th1 th2 show ?thesis\n      by blast\n  next\n    case dp: 3\n    have False if dvd: \"p dvd (q ^ (Suc n))\" and h: \"poly p x = 0\" \"poly q x \\<noteq> 0\" for x\n    proof -\n      from dvd obtain u where u: \"q ^ (Suc n) = p * u\" ..\n      from h have \"poly (q ^ (Suc n)) x \\<noteq> 0\"\n        by simp\n      with u h(1) show ?thesis\n        by (simp only: poly_mult) simp\n    qed\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 th: \"poly p = poly [:poly p 0:]\"\n      by auto\n    then have \"p = [:poly p 0:]\"\n      by (simp add: poly_eq_poly_eq_iff)\n    then have \"degree p = degree [:poly p 0:]\"\n      by simp\n    then show ?thesis\n      by simp\n  qed\n  show ?lhs if ?rhs\n  proof -\n    from that obtain k where \"p = [:k:]\"\n      by (cases p) (simp split: if_splits)\n    then show ?thesis\n      unfolding constant_def by auto\n  qed\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)\"\nproof -\n  have \"pCons 0 q = q * [:0,1:]\" by simp\n  then have \"q dvd (pCons 0 q)\" ..\n  with pq show ?thesis by (rule dvd_trans)\nqed\n\nlemma poly_divides_conv0:\n  fixes p:: \"'a::field poly\"\n  assumes lgpq: \"degree q < degree p\"\n    and lq: \"p \\<noteq> 0\"\n  shows \"p dvd q \\<longleftrightarrow> q = 0\" (is \"?lhs \\<longleftrightarrow> ?rhs\")\nproof\n  assume ?rhs\n  then have \"q = p * 0\" by simp\n  then show ?lhs ..\nnext\n  assume l: ?lhs\n  show ?rhs\n  proof (cases \"q = 0\")\n    case True\n    then show ?thesis by simp\n  next\n    assume q0: \"q \\<noteq> 0\"\n    from l q0 have \"degree p \\<le> degree q\"\n      by (rule dvd_imp_degree_le)\n    with lgpq show ?thesis by simp\n  qed\nqed\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\" (is \"?lhs \\<longleftrightarrow> ?rhs\")\nproof\n  from pp' obtain t where t: \"p' = p * t\" ..\n  show ?rhs if ?lhs\n  proof -\n    from that obtain u where u: \"q = p * u\" ..\n    have \"r = p * (smult a u - t)\"\n      using u qrp' [symmetric] t by (simp add: algebra_simps)\n    then show ?thesis ..\n  qed\n  show ?lhs if ?rhs\n  proof -\n    from that obtain u where u: \"r = p * u\" ..\n    from u [symmetric] t qrp' [symmetric] a0\n    have \"q = p * smult (1/a) (u + t)\"\n      by (simp add: algebra_simps)\n    then show ?thesis ..\n  qed\nqed\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)\"\nproof -\n  have False if \"h \\<noteq> 0\" \"t = 0\" and \"pCons a (pCons b p) = pCons h t\" for h t\n    using l that by simp\n  then have th: \"\\<not> (\\<exists> h t. h \\<noteq> 0 \\<and> t = 0 \\<and> pCons a (pCons b p) = pCons h t)\"\n    by blast\n  from fundamental_theorem_of_algebra_alt[OF th] show ?thesis\n    by auto\nqed\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)\"\nproof -\n  from l have dp: \"degree (pCons a p) = psize p\"\n    by (simp add: psize_def)\n  from nullstellensatz_univariate[of \"pCons a p\" q] l\n  show ?thesis\n    by (metis dp pCons_eq_0_iff)\nqed\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\"\nproof -\n  from h have \"poly (q ^ n) = poly r\"\n    by auto\n  then have \"(q ^ n) = r\"\n    by (simp add: poly_eq_poly_eq_iff)\n  then show \"p dvd (q ^ n) \\<longleftrightarrow> p dvd r\"\n    by simp\nqed\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": "dtraytel", "repo": "HOLRLT", "sha": "e9029da59bb3af0c835604a65308498f9696a364", "save_path": "github-repos/isabelle/dtraytel-HOLRLT", "path": "github-repos/isabelle/dtraytel-HOLRLT/HOLRLT-e9029da59bb3af0c835604a65308498f9696a364/HOLRLT/Computational_Algebra/Fundamental_Theorem_Algebra.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8688267728417087, "lm_q2_score": 0.8459424314825853, "lm_q1q2_score": 0.7349774327548829}}
{"text": "theory Practical\n  imports\n    Main\n    HOL.Real\nbegin\n\nsection\\<open>Part 1: Propositional and First-Order Proofs (40 marks)\\<close>\n\ntext\\<open>Allowed methods:\n  \\<^item> rule and rule_tac\n  \\<^item> drule and drule_tac\n  \\<^item> erule and erule_tac\n  \\<^item> frule and frule_tac\n  \\<^item> cut_tac\n  \\<^item> assumption\\<close>\n\ntext\\<open>Allowed introduction and elimination rules:\\<close>\nthm exI exE\nthm allI allE spec\nthm conjI conjE\nthm ccontr excluded_middle\nthm notI notE notnotD\nthm impI impE mp\nthm iffI iffE iffD1 iffD2\nthm disjI1 disjI2 disjE\n\ntext\\<open>All proofs in this part must be procedural (apply-style).\\<close>\n\nsubsection\\<open>Problem 1 (3 marks)\\<close>\n\ntext\\<open>1 mark\\<close>\nlemma contrapos: \"P \\<longrightarrow> Q \\<Longrightarrow> \\<not> Q \\<longrightarrow> \\<not> P\"\n  apply (rule impI)\n  apply (rule ccontr)\n  apply (frule notnotD)\n  apply (erule notE)\n  apply (drule mp)\n  by assumption\n\n \n\ntext\\<open>2 marks\\<close>\nlemma flowers_knights: \"((\\<exists>x. F x) \\<longrightarrow> (\\<forall>x. G x)) \\<longrightarrow> (\\<forall>x y. F x \\<longrightarrow> G y)\"\n  apply (rule impI)\n  apply (rule allI)+\n  apply (rule impI)\n  apply (frule_tac P=F in exI)\n  apply (drule mp)\n   apply assumption\n  apply (rule_tac P=G in spec)\n  by assumption\n  \n\nsubsection\\<open>Problem 2 (7 marks)\\<close>\n\ntext\\<open>The portait is not in the golden box.\\<close>\nlemma not_g: \"\\<lbrakk>G \\<longrightarrow> False\\<rbrakk> \\<Longrightarrow> \\<not>G\"\n  apply (rule ccontr)\n  apply (frule notnotD)\n  apply (frule mp)\n  by assumption\n\ntext\\<open>De Morgan's Laws\\<close>\n\nlemma dm1: \"\\<not>(P \\<or> Q) \\<Longrightarrow> \\<not>P \\<and> \\<not>Q\"\n  apply (cut_tac P=P in excluded_middle)\n  apply (rule conjI)\n   apply (rule ccontr)\n   apply (drule notnotD)\n   apply (drule_tac P=P and Q=Q in disjI1)\n   apply (erule_tac P=\"P\\<or>Q\" and R=False in notE)\n   apply assumption\n  apply (rule ccontr)\n   apply (drule notnotD)\n   apply (drule_tac P=P and Q=Q in disjI2)\n   apply (erule_tac P=\"P\\<or>Q\" in notE)\n  by assumption  \n\ntext\\<open>The portait is not in the silver box.\\<close>\nlemma not_s: \"\\<lbrakk>S \\<longrightarrow> \\<not>(S \\<or> G)\\<rbrakk> \\<Longrightarrow> \\<not>S\"\n  apply (rule ccontr)\n  apply (drule notnotD)\n  apply (drule_tac P=S in mp)\n   apply assumption\n  apply (cut_tac P=S and Q=G in dm1)\n   apply assumption\n  apply (drule conjunct1)\n  apply (erule_tac P=S in notE)\n  by assumption\n\ntext\\<open>Helper\\<close>\nlemma disj_other: \"\\<lbrakk>P \\<or> Q; ~P\\<rbrakk> \\<Longrightarrow> Q\"\n  apply (rule ccontr)\n  apply (drule_tac R=\"False\" in disjE)\n    apply (drule_tac P=P and R=\"False\" in notE)\n     apply assumption+\n   apply (drule_tac P=Q and R=\"False\" in notE)\n  by assumption\n  \n  \ntext\\<open>The portait is in the lead boxx.\\<close>\nlemma l: \"\\<lbrakk>G \\<longrightarrow> False; S \\<longrightarrow> \\<not>(S \\<or> G);  L \\<longrightarrow> (L \\<longrightarrow> L); G \\<or> S \\<or> L\\<rbrakk> \\<Longrightarrow> L\"\n  apply (cut_tac S=S and G=G in not_s)\n   apply assumption\n  apply (cut_tac G=G in not_g)\n   apply assumption\n  apply (rule ccontr)\n  apply (cut_tac P=G and Q=\"S\\<or>L\" in disj_other)\n    apply assumption+\n  apply (cut_tac P=S and Q=L in disj_other)\n    apply assumption+\n  apply (drule_tac P=L and R=\"False\" in notE)\n  by assumption\n\ntext\\<open>The portait is only in the lead box.\\<close>\ntheorem \"\\<lbrakk>G \\<longrightarrow> False; S \\<longrightarrow> \\<not>(S \\<or> G);  L \\<longrightarrow> (L \\<longrightarrow> L); G \\<or> S \\<or> L\\<rbrakk> \\<Longrightarrow> ~G \\<and> ~S \\<and> L\"\n  apply (rule conjI)\n   apply (cut_tac G=G in not_g)\n    apply assumption+\n  apply (rule conjI)\n  apply (cut_tac G=G and S=S in not_s)\n    apply assumption+\n  apply (cut_tac G=G and S=S and L=L in l)\n  by assumption+\n\n  \n\nsection\\<open>Knights and Knaves Problems: (30 marks)\\<close>\n\nlocale knights_knaves =\n    fixes V :: \"'a \\<Rightarrow> bool\"\n    fixes G :: \"'a \\<Rightarrow> bool\"\n    fixes S :: \"nat \\<Rightarrow> 'a \\<Rightarrow> bool\"\n  assumes V_iff_not_G: \"\\<forall>x. V x \\<longleftrightarrow> \\<not> G x\"\n      and V_imp_not_S: \"\\<forall>x. \\<forall> y. V x \\<longrightarrow> \\<not> S y x\"\n      and G_imp_S: \"\\<forall>x. \\<forall> y. G x \\<longrightarrow> S y x\"\nbegin\n\nthm impE\n\nsubsection\\<open>Problem 3 (4 marks)\\<close>\nlemma S_imp_G: \"\\<forall>x. \\<forall> y. S y x \\<longrightarrow> G x\"\n  apply (rule allI)+\n  apply (cut_tac V_imp_not_S)\n  apply (rule impI)\n  apply (drule_tac x=x in spec)\n  apply (drule_tac x=y in spec)\n  apply (rule ccontr)\n  apply (cut_tac V_iff_not_G)\n  apply (drule_tac x=x in spec)\n  apply (drule iffD2)\n   apply assumption\n  apply (drule mp)\n   apply assumption\n  apply (drule_tac P=\"S y x\" and R=\"False\" in notE)\n  by assumption\n\nlemma not_S_imp_V: \"\\<forall>x. \\<forall> y. \\<not> S y x \\<longrightarrow> V x\"\n  apply (rule allI)+\n  apply (cut_tac G_imp_S)\n  apply (rule impI)\n  apply (drule_tac x=x in spec)\n  apply (drule_tac x=y in spec)\n  apply (drule_tac contrapos)\n  apply (drule mp)\n   apply assumption\n  apply (cut_tac V_iff_not_G)\n  apply (drule_tac x=x in spec)\n  apply (drule iffD2)\n  by assumption\n\nlemma iff_flip: \"P \\<longleftrightarrow> Q \\<Longrightarrow> \\<not>P \\<longleftrightarrow> \\<not>Q\" \n  apply (rule iffI)\n   apply (rule ccontr)\n   apply (drule notnotD)\n   apply (drule iffD2)\n    apply assumption\n   apply (rule_tac P=P and R=False in notE)\n    apply assumption+\n  apply (rule ccontr)\n  apply (drule notnotD)\n  apply (drule iffD1)\n   apply assumption\n  apply (rule_tac P=Q and R=False in notE)\n  by assumption+\n\nsubsection\\<open>Problem 4 (6 marks)\\<close>\n\nlemma Zoey: \"\\<lbrakk>S 1 z = V m; S 1 m = (\\<not> V z \\<and> \\<not> V m)\\<rbrakk> \\<Longrightarrow> G z\"\n  apply (cut_tac S_imp_G)\n  apply (drule_tac x=z in spec)\n  apply (drule_tac x=1 in spec)\n  apply (rule ccontr)\n   apply (cut_tac P=\"S 1 z\" and Q=\"G z\" in contrapos)\n    apply assumption\n   apply (drule_tac P=\"~G z\" in mp)\n    apply assumption\n   apply (drule iffD2)\n    apply (rule ccontr)\n    apply (cut_tac V_iff_not_G)\n    apply (drule_tac x=z in spec)\n    apply (drule_tac Q=\"(~ G z)\" in iffD2)\n     apply assumption\n    apply (cut_tac P=\"S 1 m\" and Q=\"(\\<not> V z \\<and> \\<not> V m)\" in iff_flip)\n     apply assumption\n    apply (drule_tac P=\"(~ S 1 m)\" and Q=\"~(~ V z \\<and> ~ V m)\" in iffD2)\n     apply (rule ccontr)\n     apply (drule notnotD)\n     apply (drule_tac conjunct1)\n     apply (drule_tac P=\"V z\" and R=False in notE)\n      apply assumption+\n    apply (cut_tac not_S_imp_V)\n    apply (drule_tac x=m in spec)\n    apply (drule_tac x=1 in spec)\n    apply (drule_tac P=\"~ S 1 m\" in mp)\n     apply assumption\n  apply (drule_tac P=\"V m\" and R=False in notE)\n     apply assumption+\n   apply (drule_tac P=\"S 1 z\" and R=False in notE)\n  by assumption+\n\nlemma Mel_and_Zoey: \"\\<lbrakk>S 1 z = V m; S 1 m = (\\<not> V z \\<and> \\<not> V m)\\<rbrakk> \\<Longrightarrow> G z \\<and> V m\"\n  apply (cut_tac z=z and m=m in Zoey)\n    apply assumption+\n  apply (rule conjI)\n   apply assumption\n  apply (cut_tac V_iff_not_G)\n  apply (drule_tac x=z in spec)\n  apply (cut_tac P=\"V z\" and Q=\"~ G z\" in iff_flip)\n   apply assumption\n  apply (cut_tac G_imp_S)\n  apply (drule_tac x=z in spec)\n  apply (drule_tac x=1 in spec)\n  apply (drule mp)\n  apply assumption\n  apply (drule_tac Q=\"S 1 z\" in iffD1)\n  by assumption+\n\nsubsection\\<open>Problem 5 (20 marks)\\<close>\ntext\\<open>5 marks for formalisation + 15 marks for proof\\<close>\n\ntext\\<open>The next two proofs are very similar to Zoey and Mel...\\<close>\nlemma Abel_G: \"\\<lbrakk>  S 2 a = V b; S 2 b = (G a \\<and> G b) \\<rbrakk> \\<Longrightarrow> G a\"\n  apply (cut_tac S_imp_G)\n  apply (drule_tac x=a in spec)\n  apply (drule_tac x=2 in spec)\n  apply (rule ccontr)\n   apply (cut_tac P=\"S 2 a\" and Q=\"G a\" in contrapos)\n    apply assumption\n   apply (drule_tac P=\"~G a\" in mp)\n    apply assumption\n   apply (drule iffD2)\n    apply (rule ccontr)\n    apply (cut_tac V_iff_not_G)\n    apply (drule_tac x=a in spec)\n    apply (drule_tac Q=\"(~ G a)\" in iffD2)\n     apply assumption\n    apply (cut_tac P=\"S 2 b\" and Q=\"G a \\<and> G b\" in iff_flip)\n  apply assumption\n    apply (drule_tac P=\"(~ S 2 b)\" and Q=\"~(G a \\<and> G b)\" in iffD2)\n     apply (rule ccontr)\n     apply (drule notnotD)\n    apply (drule_tac conjunct1)\n    apply (cut_tac V_iff_not_G)\n    apply (drule_tac x=a in spec)\n    apply (drule_tac Q=\"V a\" in iffD1)\n     apply assumption\n     apply (drule_tac P=\"G a\" and R=False in notE)\n      apply assumption+\n    apply (cut_tac not_S_imp_V)\n    apply (drule_tac x=b in spec)\n    apply (drule_tac x=2 in spec)\n    apply (drule_tac P=\"~ S 2 b\" in mp)\n     apply assumption\n  apply (drule_tac P=\"V b\" and R=False in notE)\n     apply assumption+\n   apply (drule_tac P=\"S 2 a\" and R=False in notE)\n  by assumption+\n\nlemma Abel_and_Beatrice_G_and_V: \"\\<lbrakk> S 2 a = V b; S 2 b = (G a \\<and> G b) \\<rbrakk> \\<Longrightarrow> G a \\<and> V b\"\n  apply (cut_tac a=a and b=b in Abel_G)\n    apply assumption+\n  apply (rule conjI)\n   apply assumption\n  apply (cut_tac V_iff_not_G)\n  apply (drule_tac x=a in spec)\n  apply (cut_tac P=\"V a\" and Q=\"~ G a\" in iff_flip)\n   apply assumption\n  apply (cut_tac G_imp_S)\n  apply (drule_tac x=a in spec)\n  apply (drule_tac x=2 in spec)\n  apply (drule mp)\n  apply assumption\n  apply (drule_tac Q=\"S 2 a\" in iffD1)\n  by assumption+\n\nlemma Abel_and_Beatrice: \"\\<lbrakk>S 1 a = ((\\<exists>x. F x) \\<longrightarrow> (\\<forall> x. G x)); S 1 b = (\\<not>(\\<forall>x. \\<forall>y. F x \\<longrightarrow> G y)); S 2 a = V b; S 2 b = (G a \\<and> G b)\\<rbrakk> \\<Longrightarrow> G a \\<and> V b \\<and> ~F a \\<and> ~F b\"\n  apply (cut_tac a=a and b=b in Abel_and_Beatrice_G_and_V)\n    apply assumption+\n  apply (erule_tac P=\"G a\" and Q=\"V b\" in conjE)\n  apply (rule conjI)\n   apply assumption\n  apply (rule conjI)\n   apply assumption\n  apply (cut_tac V_imp_not_S)\n  apply (drule_tac x=b in spec)\n  apply (drule_tac x=1 in spec)\n  apply (drule_tac P=\"V b\" in mp)\n   apply assumption\n  apply (cut_tac P=\"S 1 b\" and Q=\"(\\<not> (\\<forall>x y. F x \\<longrightarrow> G y))\" in iff_flip)\n   apply assumption\n  apply (drule_tac Q=\"\\<not> S 1 b\" in iffD1)\n   apply assumption\n  apply (drule notnotD)\n  apply (frule_tac x=a in spec)\n  apply (drule_tac x=b in spec)+\n  apply (cut_tac P=\"F b\" and Q=\"G b\" in contrapos)\n    apply assumption\n  apply (cut_tac P=\"F a\" and Q=\"G b\" in contrapos)\n   apply assumption\n  apply (cut_tac V_iff_not_G)\n  apply (drule_tac x=b in spec)\n  apply (drule_tac Q=\"V b\" in iffD1)\n   apply assumption\n  apply (drule_tac P=\"\\<not>G b\" in mp)\n   apply assumption\n  apply (drule_tac P=\"\\<not>G b\" in mp)\n   apply assumption\n  apply (rule conjI)\n  by assumption+\n\nend\n\nsection\\<open>Part 2: Geometry with Order and Signed Areas (60 marks)\\<close>\n\ntext\\<open>Additional allowed methods:\n  \\<^item> subst, unfold\n  \\<^item> auto, simp, blast\n  \\<^item> fast, force, fastforce\n  \\<^item> presburger\n  \\<^item> algebra, arith, linarith\n\n  All proofs must now be in structured (Isar) style.\n  In this part you are not allowed to use tactics metis, meson, smt.\n  You may use sledgehammer, try, try0 but if they suggest metis, meson or smt you should find an alternative proof.\n\\<close>\n\nsubsection\\<open>Geometry with Ordered Points (14 marks)\\<close>\nlocale points =\n    fixes order :: \"'p \\<Rightarrow> 'p \\<Rightarrow> 'p \\<Rightarrow> bool\"\n  assumes order_CBA: \"order A B C \\<Longrightarrow> order C B A\"\n      and order_notBCA: \"order A B C \\<Longrightarrow> \\<not> order B C A\"\n      and order_distinctAC: \"order A B C \\<Longrightarrow> A \\<noteq> C\"\nbegin\n\nsubsubsection\\<open>Problem 6 (3 marks)\\<close>\n\nlemma order_distinctAB: \n  fixes A::'p and B::'p and C::'p\n  assumes \"order A B C\"\n  shows \"A \\<noteq> B\"\nproof\n  assume a: \"A=B\"\n  then have \"order B A C\" using assms by blast\n  then have \"order C A B\" using order_CBA by blast\n  then have \"\\<not> order A B C\" using order_notBCA by blast\n  then show False using assms by auto\nqed\n\nlemma order_distinctBC:\n    fixes A::'p and B::'p and C::'p\n    assumes \"order A B C\"\n    shows \"B \\<noteq> C\"\nproof\n  assume \"B = C\" \n  then have \"order A C B\" using assms by blast\n  then have \"order B C A\" using order_CBA by blast\n  also have \"~order B C A\"\n    using \\<open>B = C\\<close> order_distinctAB by blast \n  then show False using calculation by auto\nqed\n\ntext\\<open>Line through two points:\\<close>\ndefinition line :: \"'p \\<Rightarrow> 'p \\<Rightarrow> 'p set\"\n  where \"A \\<noteq> B \\<Longrightarrow> line A B = {X. X=A \\<or> X=B \\<or> order A B X \\<or> order A X B \\<or> order X A B}\"\n\ntext\\<open>Set of all lines:\\<close>\ndefinition Lines :: \"'p set set\"\n  where \"Lines = {l. \\<exists> C D. l = line C D}\"\n\nend\n\nsubsubsection\\<open>Problem 7 (6 marks)\\<close>\n\nlocale lines =\n  points order\n    for order :: \"'p \\<Rightarrow> 'p \\<Rightarrow> 'p \\<Rightarrow> bool\" +\n  assumes A_V:\"A \\<noteq> B \\<Longrightarrow> \\<exists>C. order A B C\"\n      and A_VI:\"\\<lbrakk>C \\<in> line A B; D \\<in> line A B; C \\<noteq> D\\<rbrakk> \\<Longrightarrow> A \\<in> line C D\"\n      and unique_line:\"A\\<noteq>B \\<Longrightarrow> \\<exists>!l\\<in>Lines. A \\<in> l \\<and> B \\<in> l\"\n      and A_VII: \"\\<exists> A. \\<exists> B. \\<exists> C. A \\<noteq> B \\<and> B \\<noteq> C \\<and> C \\<noteq> A \\<and> ~order A B C \\<and> ~order B C A \\<and> ~order C A B\"\n      and A_VIII: \"\\<lbrakk>~(A \\<in> line B C); order B C D; order C E A \\<rbrakk> \\<Longrightarrow> \\<exists> F. order A F B \\<and> D \\<in> line E F\"\nbegin\n\nlemma uniqueness: \"[|\\<exists>!x. P x; P A; P B|] ==> A = B\"\n  by blast\n  \n\nsubsubsection\\<open>Problem 8 (5 marks)\\<close>\n\nlemma symmetric_line:\n  fixes A::'p and B::'p and X::'p\n  assumes p1: \"X \\<in> line A B\"\n    and p2: \"A \\<noteq> B\"\n  shows \"X \\<in> line B A\" \nproof -\n  have a: \"X=A \\<or> X=B \\<or> order A B X \\<or> order A X B \\<or> order X A B\"\n    using line_def p1 p2 points.order_CBA by fastforce\n  have b: \"X=B \\<or> X=A \\<or> order B A X \\<or> order B X A \\<or> order X B A\"\n    using order_CBA a by blast \n  show \"X \\<in> line B A\"\n    using b p2 points.line_def points_axioms by fastforce\nqed\n\n(* Formalise and prove that given a line, there is a point not on the line *)\nlemma not_all_on_line: \"\\<forall> D. \\<forall> E. \\<exists> F. ~(F \\<in> line D E)\"\nproof (rule ccontr)\n  assume assumption: \"~(\\<forall> D. \\<forall> E. \\<exists> F. ~(F \\<in> line D E))\"\n  then have \"\\<exists> D. \\<exists> E. \\<forall> F. F \\<in> line D E\" \n     by blast\n   then obtain D where \"\\<exists> E. \\<forall> F. F \\<in> line D E\" \n     by auto\n   then obtain E where all_p_on_DE: \"\\<forall> F. F \\<in> line D E\" \n     by auto\n   obtain A where \"\\<exists> B. \\<exists> C. (A \\<noteq> B \\<and> B \\<noteq> C \\<and> C \\<noteq> A \\<and> ~(order A B C) \\<and> ~(order B C A) \\<and> ~(order C A B))\" \n     using A_VII by auto\n   then obtain B where \"\\<exists> C. (A \\<noteq> B \\<and> B \\<noteq> C \\<and> C \\<noteq> A \\<and> ~(order A B C) \\<and> ~(order B C A) \\<and> ~(order C A B))\"\n     by auto\n   then obtain C where spec_A_VII: \"A \\<noteq> B \\<and> B \\<noteq> C \\<and> C \\<noteq> A \\<and> ~(order A B C) \\<and> ~(order B C A) \\<and> ~(order C A B)\"\n     by auto\n   have A_on_DE: \"A \\<in> line D E\" \n     using all_p_on_DE by simp\n   have B_on_DE: \"B \\<in> line D E\"\n     using all_p_on_DE by simp\n   have A_and_B_on_AB: \"line A B \\<in> Lines \\<and> A \\<in> line A B \\<and> B \\<in> line A B\"\n     using Lines_def line_def spec_A_VII by blast \n   have A_and_B_on_DE: \"line D E \\<in> Lines \\<and> A \\<in> line D E \\<and> B \\<in> line D E\"\n     using Lines_def A_on_DE B_on_DE by blast \n   have \"\\<exists>!l\\<in>Lines. A \\<in> l \\<and> B \\<in> l\" using spec_A_VII unique_line by blast\n   then have \"line D E = line A B\"\n     using A_and_B_on_AB A_and_B_on_DE by blast \n   then have \"C \\<in> line A B\"\n     using all_p_on_DE by auto \n   then have \"\\<forall> D. \\<forall> E. \\<exists> F. ~(F \\<in> line D E)\"\n     using order_CBA points.line_def points_axioms spec_A_VII by fastforce    \n   then show False using assumption by auto\nqed\nend\n\nsubsection\\<open>Triangle Geometry (26 marks)\\<close>\n\nlocale triangles =\n    fixes \\<Delta> :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> real\" (* \\Delta then Ctrl+B \\<rightarrow> \\<Delta> *)\n  assumes axiom0_a: \"\\<Delta> x y z = \\<Delta> y z x\"\n      and axiom0_b: \" - \\<Delta> z y x = \\<Delta> x y z\"\n      and axiom2: \"x \\<noteq> y \\<Longrightarrow> \\<exists>z. (R::real) = \\<Delta> x y z\"\n      and axiom3_a: \"\\<Delta> x y z + \\<Delta> h z y + \\<Delta> z h x + \\<Delta> y x h = 0\"\n      and axiom5: \"\\<Delta> x y z = 0 \\<Longrightarrow> (\\<Delta> h x y)*(\\<Delta> k x z) = (\\<Delta> k x y)*(\\<Delta> h x z)\"\n\ncontext triangles begin\n\nsubsubsection\\<open>Problem 9 (16 marks)\\<close>\n\nlemma reverse_order1: \"- \\<Delta> x z y = \\<Delta> x y z\"\nproof -\n  have \"\\<Delta> x y z = \\<Delta> y z x\" by (rule axiom0_a)\n  also have \"\\<dots> = - \\<Delta> x z y\" by (subst axiom0_b) arith\n  finally show ?thesis by simp\nqed\n\nlemma reverse_order2: \"- \\<Delta> y x z = \\<Delta> x y z\"\nproof -\n  have \"\\<Delta> x y z = - \\<Delta> x z y\" by (subst reverse_order1) arith\n  also have \"\\<dots> = - \\<Delta> y x z\" by (subst axiom0_a) arith\n  finally show ?thesis by simp\nqed\n\nlemma same_order1: \"\\<Delta> x y z = \\<Delta> z x y\"\nproof -\n  have \"\\<Delta> x y z = \\<Delta> y z x\" by (rule axiom0_a)\n  also have \"\\<dots> = \\<Delta> z x y\" by (rule axiom0_a)\n  finally show ?thesis by simp\nqed\n\ntext\\<open>Group similar rules under shared names to make them easier to use:\\<close>\nlemmas reverse_order = reverse_order2 reverse_order1 axiom0_b\nlemmas same_order = same_order1 axiom0_a\n\nlemma pos_order_eq_zero:\n  assumes \"\\<Delta> x y z = 0\"\n    shows \"\\<Delta> y x z = 0\"\n      and \"\\<Delta> x z y = 0\"\n      and \"\\<Delta> y z x = 0\"\n      and \"\\<Delta> z y x = 0\"\n      and \"\\<Delta> z x y = 0\"\nproof -\n  show \"\\<Delta> y x z = 0\"\n  proof -\n   have \"- \\<Delta> y x z = \\<Delta> x y z\"\n      by (rule reverse_order)\n    then show ?thesis\n      using assms by arith\n  qed\nnext\n  show \"\\<Delta> x z y = 0\"\n  proof -\n   have \"- \\<Delta> x z y = \\<Delta> x y z\"\n      by (rule reverse_order)\n    then show ?thesis\n      using assms by arith\n  qed\nnext\n  show \"\\<Delta> y z x = 0\"\n  proof -\n   have \" \\<Delta> x y z = \\<Delta> y z x\"\n      by (rule axiom0_a)\n    then show ?thesis\n      by (simp add: assms)\n  qed\nnext\n  show \"\\<Delta> z y x = 0\"\n  proof -\n   have \"- \\<Delta> z y x = \\<Delta> x y z\"\n      by (rule reverse_order)\n    then show ?thesis\n      using assms by arith\n  qed\nnext\n  show \"\\<Delta> z x y = 0\"\n  proof -\n   have \"\\<Delta> z x y = \\<Delta> x y z\"\n      by (rule same_order)\n    then show ?thesis\n      using assms by arith\n  qed\nqed\n\nlemma neg_order_eq_zero:\n  assumes \" \\<Delta> x y z = 0\"\n    shows \"-\\<Delta> x y z = 0\"\n      and \"-\\<Delta> y x z = 0\"\n      and \"-\\<Delta> x z y = 0\"\n      and \"-\\<Delta> y z x = 0\"\n      and \"-\\<Delta> z y x = 0\"\n      and \"-\\<Delta> z x y = 0\"\nproof -\n  show \"-\\<Delta> x y z = 0\"\n    proof -\n      show ?thesis\n        using assms by arith\n    qed\nnext\n  show \"-\\<Delta> y x z = 0\"\n    proof -\n   have \"-\\<Delta> y x z = \\<Delta> x y z\"\n      by (rule reverse_order)\n   also have \"\\<Delta> x y z = 0\" using assms by simp\n   finally show \"-\\<Delta> y x z = 0\" by simp\n    qed\nnext\n  show \"-\\<Delta> x z y = 0\"\n    proof -\n    have \"-\\<Delta> x z y = \\<Delta> x y z\"\n       by (rule reverse_order)\n   also have \"\\<Delta> x y z = 0\" using assms by simp\n   finally show ?thesis by simp\n   qed\nnext\n show \"-\\<Delta> y z x = 0\"\n    proof -\n    have \"\\<Delta> y z x = \\<Delta> x y z\"\n       by (rule same_order)\n   also have \"\\<Delta> x y z = 0\" using assms by simp\n   finally show ?thesis by simp\n   qed\nnext\n show \"-\\<Delta> z y x = 0\"\n    proof -\n    have \"-\\<Delta> z y x = \\<Delta> x y z\"\n       by (rule reverse_order)\n   also have \"\\<Delta> x y z = 0\" using assms by simp\n   finally show ?thesis by simp\n   qed\nnext\n show \"-\\<Delta> z x y = 0\"\n    proof -\n    have \"\\<Delta> z x y = \\<Delta> x y z\"\n       by (rule same_order)\n   also have \"\\<Delta> x y z = 0\" using assms by simp\n   finally show ?thesis by simp\n   qed\nqed\n\nlemma order_eq_zero:\n  assumes \"\\<Delta> x y z = 0\"\n    shows \" \\<Delta> y x z = 0\" and \" \\<Delta> x z y = 0\" and \" \\<Delta> y z x = 0\"\n      and \" \\<Delta> z y x = 0\" and \" \\<Delta> z x y = 0\"\n      and \"-\\<Delta> x y z = 0\" and \"-\\<Delta> y x z = 0\" and \"-\\<Delta> x z y = 0\"\n      and \"-\\<Delta> y z x = 0\" and \"-\\<Delta> z y x = 0\" and \"-\\<Delta> z x y = 0\"\n  using assms by (rule pos_order_eq_zero neg_order_eq_zero)+\n\nlemma pos_order_neq_zero:\n  assumes \"\\<Delta> x y z \\<noteq> 0\"\n    shows \"\\<Delta> y x z \\<noteq> 0\" and \"\\<Delta> x z y \\<noteq> 0\" and \"\\<Delta> y z x \\<noteq> 0\"\n      and \"\\<Delta> z y x \\<noteq> 0\" and \"\\<Delta> z x y \\<noteq> 0\"\n  using assms pos_order_eq_zero by blast+\n\nlemma axiom1:\n  assumes p: \"x = y\"\n    shows \"\\<Delta> x y z = 0\"\nproof -\n  have p1: \"\\<Delta> x x z = \\<Delta> x y z\" using p by blast  \n  have \"\\<Delta> x x z = - \\<Delta> x x z\" using reverse_order2 by force\n  then have \"\\<Delta> x x z = 0\" by fastforce\n  then show \"\\<Delta> x y z = 0\" using p1 by auto\nqed\n\nlemma axiom3_b: \"\\<Delta> x y z = \\<Delta> h y z + \\<Delta> x h z + \\<Delta> x y h\"\nproof -\n  have \"\\<Delta> x y z + \\<Delta> h z y + \\<Delta> z h x + \\<Delta> y x h = 0\" by (rule axiom3_a)\n  then have \"\\<Delta> x y z = - \\<Delta> h z y - \\<Delta> z h x - \\<Delta> y x h\" by arith\n  also have \"\\<dots> = \\<Delta> h y z - \\<Delta> z h x - \\<Delta> y x h\" by (subst reverse_order1) arith\n  also have \"\\<dots> = \\<Delta> h y z + \\<Delta> x h z - \\<Delta> y x h\" using reverse_order by auto\n  also have \"\\<dots> = \\<Delta> h y z + \\<Delta> x h z + \\<Delta> x y h\" using reverse_order axiom0_a by auto\n  finally show ?thesis by simp\nqed\n\n\nlemma axiom3_c: \"\\<Delta> x h y + \\<Delta> y k x = \\<Delta> h y k + \\<Delta> k x h\"\nproof -\n  have \"\\<Delta> x h y = \\<Delta> k h y + \\<Delta> x k y + \\<Delta> x h k\" by (rule axiom3_b)\n  then have \"\\<Delta> x h y - \\<Delta> x k y = \\<Delta> k h y + \\<Delta> x h k\" by arith\n  moreover have \"- \\<Delta> x k y = \\<Delta> y k x\" by (rule reverse_order)\n  ultimately have \"\\<Delta> x h y + \\<Delta> y k x = \\<Delta> k h y + \\<Delta> x h k\" by arith\n  also have \"\\<dots> = \\<Delta> h y k + \\<Delta> x h k\" by (subst same_order1) arith\n  also have \"\\<dots> = \\<Delta> h y k + \\<Delta> k x h\" by (subst same_order1) arith\n  finally show ?thesis by simp\nqed\n\nlemma lemma4:\n  assumes \"\\<Delta> x y z = 0\"\n    shows \"\\<Delta> x h y + \\<Delta> y h z = \\<Delta> x h z\"\nproof -\n  have \"\\<Delta> x y z = \\<Delta> h y z + \\<Delta> x h z + \\<Delta> x y h\" by (rule axiom3_b)\n  then have \"0 = \\<Delta> h y z + \\<Delta> x h z + \\<Delta> x y h\" by (simp add: assms)\n  then have \"- \\<Delta> x y h - \\<Delta> h y z = \\<Delta> x h z\" by arith\n  then have \"\\<Delta> x h y - \\<Delta> h y z = \\<Delta> x h z\" by (simp add: reverse_order axiom0_a)\n  moreover have \" - \\<Delta> h y z = \\<Delta> y h z\" by (rule reverse_order)\n  ultimately show ?thesis by arith\nqed\n\nlemma two_points1: \"\\<Delta> x x y = 0\"\nproof -\n  have \"\\<Delta> x x x + \\<Delta> x x x + \\<Delta> x x x + \\<Delta> x x x = 0\" by (rule axiom3_a)\n  then have \"\\<Delta> x x x = 0\" by arith\n  have \"\\<Delta> x x y + \\<Delta> x y x + \\<Delta> y x x + \\<Delta> x x x = 0\" by (rule axiom3_a)\n  from this and `\\<Delta> x x x = 0` have \"\\<Delta> x x y + \\<Delta> x y x + \\<Delta> y x x = 0\" by simp\n  moreover have \"- \\<Delta> x y x = \\<Delta> y x x\" by (rule reverse_order)\n  ultimately have \"\\<Delta> x x y + \\<Delta> x y x - \\<Delta> x y x = 0\" by arith\n  then show \"\\<Delta> x x y = 0\" by arith\nqed\n\nlemma two_points2: \"\\<Delta> x y y = 0\"\nproof -\n  have \"\\<Delta> x y y = - \\<Delta> y y x\" by (subst axiom0_b) arith\n  also have \"\\<dots> = 0\" by (subst two_points1) arith\n  finally show ?thesis by simp\nqed\n\nlemma two_points3: \"\\<Delta> x y x = 0\"\nproof -\n  have \"\\<Delta> x y x = \\<Delta> x x y\" by (subst same_order) arith\n  also have \"\\<dots> = 0\" by (subst two_points1) arith\n  finally show ?thesis by simp\nqed\n\nlemmas two_points = two_points1 two_points2 two_points3\n\nlemma a_b_distinct:\n  assumes \"\\<Delta> a b c \\<noteq> 0\"\n    shows \" a \\<noteq> b\"\nproof (rule ccontr)\n  assume \"\\<not> a \\<noteq> b\"\n  then have \"a = b\" by simp\n  then have that: \"\\<Delta> a b c = 0\" by (rule axiom1)\n  have \"\\<not> \\<Delta> a b c = 0\" using assms by simp\n  from this and that show False by (rule notE)\nqed\n\nlemma axiom6:\n  assumes col: \"\\<Delta> x y z = 0\"\n      and neq: \"x \\<noteq> z\"\n    shows \"\\<exists>L. \\<forall>h. \\<Delta> h x y = L * \\<Delta> h x z\"\nproof -\n  define a :: real where \"a = 1\"\n  obtain p where \"a = \\<Delta> x z p\" using axiom2 neq by blast\n  then have area: \"\\<Delta> p x z = a\" using axiom0_a by blast\n  define q :: real where \"q = \\<Delta> p x y\"\n  also have q_works: \"\\<forall>h. \\<Delta> h x y = q * \\<Delta> h x z\"\n    using area a_def axiom5 col q_def by simp\n  show \"\\<exists>L. \\<forall>h. \\<Delta> h x y = L * \\<Delta> h x z\"\n    using q_works by simp \nqed\n\nend\n\nsubsubsection\\<open>Problem 10 (10 marks)\\<close>\n\ntext\\<open>For all of the following proofs, you may use any previously proven Isabelle lemmas in the theory or its imports.\\<close>\n\ntype_synonym point = \"real * real\"\n\ndefinition xCoord :: \"point \\<Rightarrow> real\"\n  where \"xCoord P = fst P\"\n\ndefinition yCoord :: \"point \\<Rightarrow> real\"\n  where \"yCoord P = snd  P\"\n\ndefinition signedArea :: \"[point, point, point] \\<Rightarrow> real\"\nwhere \"signedArea a b c = (1/2) *\n    ((xCoord b - xCoord a) * (yCoord c - yCoord a)\n  - (yCoord b - yCoord a) * (xCoord c - xCoord a))\"\n\nlemma signedArea_0_a: \"signedArea p q r = signedArea q r p\"\nproof -\n  have \"signedArea p q r = (1/2) * ((xCoord q - xCoord p) * (yCoord r - yCoord p)\n    - (yCoord q - yCoord p) * (xCoord r - xCoord p))\" by (rule signedArea_def)\n  also have \"... = (1/2) * ((xCoord r - xCoord q) * (yCoord p - yCoord q)\n    - (yCoord r - yCoord q) * (xCoord p - xCoord q))\" by algebra\n  also have \"... = signedArea q r p\" by (rule signedArea_def[symmetric])\n  finally show ?thesis .\nqed\n\nlemma signedArea_0_b: \"signedArea p q r = - signedArea p r q\"\nproof -\n  have \"signedArea p q r = (1/2) * ((xCoord q - xCoord p)*(yCoord r - yCoord p)\n    - (yCoord q - yCoord p) * (xCoord r - xCoord p))\" by (rule signedArea_def)\n  also have \"... = - (1/2 * ((xCoord r - xCoord p) * (yCoord q - yCoord p)\n    - (yCoord r - yCoord p) * (xCoord q - xCoord p)))\" by algebra\n  also have \"... = - signedArea p r q\" by (subst signedArea_def, rule refl)\n  finally show ?thesis .\nqed\n\nlemma signedArea_2:\n  assumes \"x \\<noteq> y\"\n    shows \"\\<exists>z. (R::real) = signedArea x y z\"\nproof (cases \"yCoord x = yCoord y\")\n  case True\n  then show ?thesis\n  proof (cases \"xCoord x = xCoord y\")\n    case True\n    from this `yCoord x = yCoord y` have \"x = y\" using xCoord_def yCoord_def\n      by (simp add: prod.expand)\n    from this assms show ?thesis by contradiction\n  next\n    case False\n    define z where \"z = (( xCoord x, (2*R/(xCoord y - xCoord x) + yCoord x))::point)\"\n    then have xCoord_z_def:\"yCoord z = 2*R/(xCoord y - xCoord x) + yCoord x\" using yCoord_def\n      by force\n    from z_def have yCoord_z_def: \"xCoord z = xCoord x\" using xCoord_def\n      by force\n    have \"signedArea x y z = (1/2) * ((xCoord y - xCoord x) * (yCoord z - yCoord x)\n              - (yCoord y - yCoord x) * (xCoord z - xCoord x))\" by (rule signedArea_def)\n    also have \"... = (1/2) * ((xCoord y - xCoord x) * (2*R/(xCoord y - xCoord x) + yCoord x - yCoord x)\n              - (yCoord y - yCoord x) * (xCoord x - xCoord x))\"\n      by (subst xCoord_z_def, subst yCoord_z_def, rule refl)\n    also have \"... = (xCoord y - xCoord x) * R/(xCoord y - xCoord x)\"\n      by algebra\n    also from False have \"... = R\" by fastforce\n    finally show ?thesis\n      by blast\n  qed\nnext\n  case False\n  define z where \"z = (((2*R/(yCoord x - yCoord y) + xCoord x, yCoord x ))::point)\"\n  then have xCoord_z_def:\"xCoord z = 2*R/(yCoord x - yCoord y) + xCoord x\" using xCoord_def\n    by force\n  from z_def have yCoord_z_def: \"yCoord z = yCoord x\" using yCoord_def\n    by force\n  have \"signedArea x y z = (1/2) *((xCoord y - xCoord x)*(yCoord z - yCoord x)\n            - (yCoord y - yCoord x)*(xCoord z - xCoord x))\" by (rule signedArea_def)\n  also have \"... = (1/2) *((xCoord y - xCoord x)*(yCoord x - yCoord x)\n            - (yCoord y - yCoord x)*(2*R/(yCoord x - yCoord y) + xCoord x - xCoord x))\"\n    by (subst xCoord_z_def, subst yCoord_z_def, rule refl)\n  also have \"... = -(yCoord y - yCoord x)*R/(yCoord x - yCoord y)\"\n    by algebra\n  also from False have \"... = R\" by fastforce\n  finally show ?thesis by blast\nqed\n\nlemma signedArea_3_a: \"signedArea x y z + signedArea h z y + signedArea z h x + signedArea y x h = 0\"\nproof -\n  have \"signedArea x y z + signedArea h z y + signedArea z h x + signedArea y x h =\n  (1/2)*((xCoord y - xCoord x)*(yCoord z - yCoord x) - (yCoord y - yCoord x)*(xCoord z - xCoord x))\n+ (1/2)*((xCoord z - xCoord h)*(yCoord y - yCoord h) - (yCoord z - yCoord h)*(xCoord y - xCoord h))\n+ (1/2)*((xCoord h - xCoord z)*(yCoord x - yCoord z) - (yCoord h - yCoord z)*(xCoord x - xCoord z))\n+ (1/2)*((xCoord x - xCoord y)*(yCoord h - yCoord y) - (yCoord x - yCoord y)*(xCoord h - xCoord y))\"\n    by ((subst signedArea_def)+, rule refl)\n  also have \"... = 0\" by algebra\n  finally show ?thesis by blast\nqed\n\n(* Formulate and prove signedArea_5 *)\n\nlemma signedArea_5: \n  fixes x::point and y :: point and z :: point\n  assumes col: \"signedArea x y z = 0\"\n  shows \"(signedArea h x y)*(signedArea k x z) \n    = (signedArea k x y)*(signedArea h x z)\"\nproof -\n  have \"signedArea x y z + signedArea h z y + signedArea z h x + signedArea y x h = 0\" using signedArea_3_a by simp\n  then have \"signedArea h z y + signedArea z h x + signedArea y x h = 0\" using col by simp\n  also have \"signedArea h z y = -signedArea h y z\"\n    using signedArea_0_b by blast\n  then have \"-signedArea h y z + signedArea z h x + signedArea y x h = 0\" using signedArea_0_b\n    using calculation by force\n  then have \"-signedArea h y z + signedArea h x z + signedArea y x h = 0\"\n    by (simp add: signedArea_0_a)\n  then have \"-signedArea h y z + signedArea h x z + signedArea y h x = 0\"\n    sorry\n  show ?thesis by sorry\nqed \n\n(* Now using the definition of signedArea instantiate the triangles locale\n  so that \\<Delta> corresponds to  signedArea. Use command 'interpretation'\n  (it may be easier to prove the assumptions of the locale separately first). *)\n\ninterpretation signedArea_as_triangles: triangles signedArea\nproof\n  fix x and y and z\n  show \"signedArea x y z = signedArea y z x\"\n    using signedArea_0_a by blast\n  fix x and y and z\n  show \"- signedArea z y x = signedArea x y z\"\n  proof -\n    have \"signedArea z y x = - signedArea z x y\"\n      using signedArea_0_b by blast\n    then have \"- signedArea z y x = signedArea z x y\"\n      by auto\n    also have \"signedArea x y z = signedArea z x y\"\n      by (simp add: signedArea_0_a)\n    then show ?thesis by (simp add: calculation)\n  qed\n  fix x and y and R\n  show \"x \\<noteq> y \\<Longrightarrow> \\<exists>z. R = signedArea x y z\"\n    using signedArea_2 by blast\n  fix x and y and z and h\n  show \"signedArea x y z + signedArea h z y + signedArea z h x + signedArea y x h = 0\"\n    by (simp add: signedArea_3_a)\n  fix x y z h k\n  show \"signedArea x y z = 0 \\<Longrightarrow> (signedArea h x y) * (signedArea k x z) = (signedArea k x y) * (signedArea h x z)\"\n    using signedArea_5 by auto\nqed\n\nsubsection\\<open>Problem 11: Challenge (20 marks)\\<close>\n\nlocale triangles_continuum_pt =\n  triangles \\<Delta>\n    for \\<Delta> :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> real\" +\n  assumes \"\\<exists> (a::'a) b. a \\<noteq> b\" (* then by axiom 2 we can get a continuum of points *)\nbegin\n\ndefinition triangles_order :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> bool\"\n  where \n    \"triangles_order x y z = (\\<Delta> x y z = 0 \\<and> x \\<noteq> y \\<and> (\\<forall>p. \\<Delta> p x y > 0 \\<longrightarrow> (\\<Delta> p y z > 0 \\<and> \\<Delta> p x z > 0)))\"\n\nlemma triangles_order_CBA:\n  fixes A B C\n  assumes \"triangles_order A B C\"\n  shows \"triangles_order C B A\"\nproof -\n    have ABC_zero_area: \"\\<Delta> A B C = 0\" using triangles_order_def assms by blast\n    then have \"\\<Delta> C B A = 0\"\n      using pos_order_neq_zero(4) by blast \n    have ABC_in_order: \"\\<forall>p. \\<Delta> p A B > 0 \\<longrightarrow> (\\<Delta> p B C > 0 \\<and> \\<Delta> p A C > 0)\"\n      using triangles_order_def assms by auto\n    have \"A \\<noteq> B\"\n      using assms triangles_order_def by auto\n    then have \"\\<exists>z. 1 = \\<Delta> A B z\"\n      using axiom2 by blast\n    then obtain P where \"1 = \\<Delta> A B P\"\n      by force\n    then have \"\\<Delta> P A B = 1\"\n      using axiom0_b reverse_order2 by auto\n    then have P_pos_areas: \"\\<Delta> P B C > 0 \\<and> \\<Delta> P A C > 0\"\n      by (simp add: ABC_in_order)\n    have main_prop: \"\\<forall>p. \\<Delta> p C B > 0 \\<longrightarrow> (\\<Delta> p B A > 0 \\<and> \\<Delta> p C A > 0)\" \n    proof\n      fix Q\n      have \"(\\<Delta> P A B)*(\\<Delta> Q A C) = (\\<Delta> Q A B)*(\\<Delta> P A C)\"\n        by (simp add: ABC_zero_area axiom5)\n      then have qac_eq: \"\\<Delta> Q A C = (\\<Delta> Q A B)*(\\<Delta> P A C)\"\n        by (simp add: \\<open>\\<Delta> P A B = 1\\<close>)\n      then show \"\\<Delta> Q C B > 0 \\<longrightarrow> (\\<Delta> Q B A > 0 \\<and> \\<Delta> Q C A > 0)\"\n      proof (cases \"\\<Delta> Q C B > 0\")\n        case False\n        show ?thesis\n          using False by auto \n      next\n        case True\n        have \"\\<Delta> P A C > 0\"\n          using P_pos_areas by blast\n        have \"(\\<Delta> Q C B)*(\\<Delta> P C A) = (\\<Delta> P C B)*(\\<Delta> Q C A)\"\n          by (simp add: \\<open>\\<Delta> C B A = 0\\<close> axiom5)\n        then have ax3: \"(\\<Delta> Q C B)*(\\<Delta> P C A)/(\\<Delta> P C B) = (\\<Delta> Q C A)\"\n          using P_pos_areas pos_order_neq_zero(2) by force\n        have \"\\<Delta> P C A = - \\<Delta> P A C\"\n          using axiom0_b reverse_order2 by presburger\n        then have \"\\<Delta> P C A < 0\"\n          by (simp add: P_pos_areas)\n        then have lhs_neg: \"(\\<Delta> Q C B)*(\\<Delta> P C A) < 0\"\n          by (simp add: True mult.commute mult_pos_neg2)\n        have \"\\<Delta> P C B = - \\<Delta> P B C\"\n          using axiom0_b reverse_order2 by presburger\n        then have \"\\<Delta> P C B < 0\"\n          by (simp add: P_pos_areas)\n        then have \"(\\<Delta> Q C B)*(\\<Delta> P C A)/(\\<Delta> P C B) > 0\"\n          by (simp add: divide_neg_neg lhs_neg)\n        then have \"\\<Delta> Q C A > 0\"\n          by (simp add: ax3)\n        have \"-\\<Delta> Q C A = (\\<Delta> Q A B)*(\\<Delta> P A C)\"\n          using axiom0_b qac_eq reverse_order2 by auto\n        then have \"(\\<Delta> Q A B)*(\\<Delta> P A C) < 0\"\n          using \\<open>0 < \\<Delta> Q C A\\<close> by linarith\n        then have \"\\<Delta> Q A B < 0\"\n          using ABC_in_order mult_less_0_iff qac_eq by force\n        also have \"\\<Delta> Q A B = - \\<Delta> Q B A\"\n          by (simp add: reverse_order1)\n        then have \"\\<Delta> Q B A > 0\"\n          using calculation by auto\n        show ?thesis\n          by (simp add: \\<open>0 < \\<Delta> Q B A\\<close> \\<open>0 < \\<Delta> Q C A\\<close>)\n      qed\n    qed\n    have \"C \\<noteq> B\"\n      using P_pos_areas two_points2 by force\n    show ?thesis\n      by (simp add: \\<open>C \\<noteq> B\\<close> main_prop triangles_order_def \\<open>\\<Delta> C B A = 0\\<close>)  \n  qed\n\nlemma triangles_order_notBCA:\n  fixes A B C\n  assumes \"triangles_order A B C\"\n  shows \"~triangles_order B C A\"\nproof\n  obtain P where \"1 = \\<Delta> A B P\"\n    using assms axiom2 triangles_order_def by blast\n  have \"\\<Delta> P A B > 0 \\<longrightarrow> (\\<Delta> P B C > 0 \\<and> \\<Delta> P A C > 0)\"\n    using assms triangles_order_def by auto\n  then have \"\\<Delta> P B C > 0\"\n    using \\<open>1 = \\<Delta> A B P\\<close> axiom0_b reverse_order2 by auto\n  assume \"triangles_order B C A\"\n  have \"\\<Delta> P B C > 0 \\<longrightarrow> (\\<Delta> P C A > 0 \\<and> \\<Delta> P B A > 0)\"\n    using \\<open>triangles_order B C A\\<close> triangles_order_def by auto\n  then have \"\\<Delta> P B A > 0\"\n    by (simp add: \\<open>0 < \\<Delta> P B C\\<close>)\n  then have \"\\<Delta> P A B < 0\"\n    by (simp add: axiom0_a less_real_def reverse_order2)\n  then show False\n    using \\<open>1 = \\<Delta> A B P\\<close> axiom0_a by auto\nqed\n\nlemma triangles_order_distinctAC:\n  fixes A B C\n  assumes \"triangles_order A B C\"\n  shows \"A \\<noteq> C\"\nproof\n  assume \"A = C\"\n  have \"triangles_order C B A\"\n    by (simp add: assms triangles_order_CBA)\n  then have def: \"\\<Delta> C B A = 0 \\<and> C \\<noteq> B \\<and> (\\<forall>p. \\<Delta> p C B > 0 \\<longrightarrow> (\\<Delta> p B A > 0 \\<and> \\<Delta> p C A > 0))\"\n    using triangles_order_def by force\n  then have \"C \\<noteq> B\"\n    by blast\n  then have \"\\<exists>p. 1 = \\<Delta> C B p\"\n    using axiom2 by blast\n  then obtain P where \"1 = \\<Delta> C B P\"\n    by blast\n  then have \"\\<Delta> P C B = 1\"\n    by (simp add: axiom0_a)\n  have \"\\<forall>p. \\<Delta> p C B > 0 \\<longrightarrow> (\\<Delta> p B A > 0 \\<and> \\<Delta> p C A > 0)\"\n    using def by auto\n  then have gtz: \"\\<Delta> P C A > 0\"\n    by (simp add: \\<open>\\<Delta> P C B = 1\\<close>)\n  have eqz: \"\\<Delta> P C A = 0\"\n    by (simp add: \\<open>A = C\\<close> two_points2)\n  show False\n    using eqz gtz by auto\nqed\n    \ninterpretation points triangles_order\n  using points_def triangles_order_CBA triangles_order_distinctAC triangles_order_notBCA by blast\n\nend\n\n\nend\n\n", "meta": {"author": "mifrandir", "repo": "ar", "sha": "785436c092405042f5479398381329bb024350a0", "save_path": "github-repos/isabelle/mifrandir-ar", "path": "github-repos/isabelle/mifrandir-ar/ar-785436c092405042f5479398381329bb024350a0/Practical.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8962513759047848, "lm_q2_score": 0.8198933425148213, "lm_q1q2_score": 0.7348305363240816}}
{"text": "theory Tarjan\nimports Main\nbegin\n\ntext \\<open>\n  Tarjan's algorithm computes the strongly connected components (Loops) of\n  a finite graph using depth-first search. \n  This is heavily inspired by the implementation by Stephan Marz that can be found here\n  https://homepages.loria.fr/SMerz/projects/tarjan/\n\\<close>\n\ntext \\<open>\n  Definition of the environment to hold local variables\n  during the execution of Tarjan's algorithm.\n\\<close>\nrecord 'v env =\n  stack :: \"'v list\"\n  sccs  :: \"'v set set\"\n  sn    :: nat\n  lowlink   :: \"'v \\<Rightarrow> nat\"  \\<comment> \\<open>Map to keep track of lowlink\\<close>\n  nodeIndex :: \"'v \\<Rightarrow> nat\"\n  exploredNodes :: \"'v set\"\n\n\ntext \\<open>\n  Definition of a Graph\n  A graph has a finite number of vertices and every node can only have a node to other nodes in the graph\n\\<close>\nlocale graph =\n  fixes vertices :: \"'v set\"\n    and edges :: \"'v \\<Rightarrow> 'v set\"\n  assumes vfin: \"finite vertices\"\n    and sclosed: \"\\<forall>x \\<in> vertices. edges x \\<subseteq> vertices\" \n\n\ncontext graph\nbegin\ntext \\<open>\\<close>\nabbreviation edge where\n  \"edge x y \\<equiv> y \\<in> edges x\"\n\ntext \\<open>Transitive closure - x can reach itself and if \\<close>\ninductive reach where\n  reach_refl[iff]: \"reach x x\"\n| reach_succ[elim]: \"\\<lbrakk>edge x y; reach y z\\<rbrakk> \\<Longrightarrow> reach x z\"\n\nlemma reachable_edge: \"edge x y \\<Longrightarrow> reach x y\"\n  by auto\n\nlemma reach_is_transitive:\n  assumes y: \"reach x y\" and z: \"reach y z\"\n  shows \"reach x z\"                  \n  using assms by induct auto\n                                         \n\nsection {* Strongly connected components from the definition of Tarjan*}\n\ndefinition is_subscc where      \n  \"is_subscc S \\<equiv> \\<forall>x \\<in> S. \\<forall>y \\<in> S. reach x y\"\n\ntext\\<open>If S is a SCC and S is a subset of S' and S' is a ASK about this\\<close>\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 \"reach x y\" and \"reach y x\"\n  shows \"is_subscc (insert y S)\"\nusing assms unfolding is_subscc_def by (metis insert_iff reach_is_transitive)\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 \"reach x y\" and \"reach 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\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\\<close>\ndefinition add_stack_incr:: \"'v \\<Rightarrow> 'v env \\<Rightarrow> 'v env\" where \n  \"add_stack_incr x e =\n      e \\<lparr> stack := x # (stack e),\n          exploredNodes := {x} \\<union> (exploredNodes e),\n          sn := sn e + 1,\n          lowlink := (lowlink e) (x := sn e), \n          nodeIndex := (nodeIndex e) (x := sn e)\\<rparr>\"\n                     \nabbreviation infty (\"\\<infinity>\") where\n  \\<comment> \\<open>nat exceeding any one used as a vertex number during the algorithm\\<close>\n  \"\\<infinity> \\<equiv> (card vertices)\"  \n\nfun split_list:: \"'v \\<Rightarrow> 'v list \\<Rightarrow> ('v list * 'v 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                                \n *)\nsection \\<open>Tarjan's algorithm implementation\\<close>\n                                   \nsubsection \\<open>Function definitions\\<close>\n                                  \nfunction (domintros) visit and dfs where\n  \"visit x e  =\n    (let (newLowLink, e1) = dfs (edges x) (add_stack_incr x e) in\n  \\<comment>\\<open>Extract a function\\<close>\n      if newLowLink < (nodeIndex e x) then (newLowLink, e1)\n      else\n       (let (scc,rest) = split_list x (stack e1) in\n         (\\<infinity>, \n           \\<lparr> stack = rest,\n             sccs = insert (set scc) (sccs e1),\n             sn = sn e1,\n             lowlink = lowlink e1,\n             nodeIndex = nodeIndex e1,\n             exploredNodes = exploredNodes e1 \\<rparr> )))\"\n| \"dfs roots e =\n    (if roots = {} then (\\<infinity>, e)\n    else\n      (let x = SOME x. x \\<in> roots;\n           \\<comment> \\<open>If node is unexplored explore it using dfs\\<close>\n           res1 = (if x \\<in> exploredNodes e then (lowlink e x, e) else visit x e);\n           res2 = dfs (roots - {x}) (snd res1)\n      in (min (fst res1) (fst res2), snd res2) ))\" \\<comment> \\<open>Return lowest lowlink and current env\\<close>\n  by pat_completeness auto\n\n(*Use Monads in state of state*)\ntext\\<open>Setup environment\\<close>\ndefinition init_env where\n  \"init_env \\<equiv> \\<lparr> stack = [],\n                sccs = {},           \n                sn = 0,\n                lowlink = \\<lambda>_. 0,\n                nodeIndex = \\<lambda>_. 0,\n                exploredNodes = {}\\<rparr>\"\n\n(*Get SCC from the environment after performing tarjan*)\ndefinition tarjan where\n  \"tarjan \\<equiv> sccs (snd (dfs vertices init_env))\"\n                                                                                                                   \ndefinition tarjan_pre:: \"'v \\<Rightarrow> 'v env \\<Rightarrow> bool\" where\n\"tarjan_pre x e \\<equiv> exploredNodes e = {} \n                   \\<and> sn e = 0  \n                   \\<and> (stack e) = [] \n                   \\<and> card (sccs e) = 0\"\n                                      \ndefinition tarjan_post:: \"'v \\<Rightarrow> 'v env \\<Rightarrow> 'v env \\<Rightarrow> bool\" where\n\"tarjan_post x e e' \\<equiv> x \\<in> vertices\n                    \\<and> card (exploredNodes e') = card vertices\n                    \\<and> sn e' = card vertices\"\n\n                             \n\n                                                  \ntext \\<open>How to make invariants?\\<close>\n(*                                       \n  Possible useful invariants could be the stack should always contain only unique elements\n  And All The elements in the stack should also be present in the exploredNodes\n*)                                                    \ndefinition invariants:: \"'v env \\<Rightarrow> bool\" where          \n \"invariants e \\<equiv> \\<forall>x \\<in> set (stack e). x \\<in> (exploredNodes e)\n                  \\<and> distinct (stack e)\"\n                                                                      \ndefinition exploredNodes_num where\n  \"exploredNodes_num e \\<equiv> \\<forall>v \\<in> exploredNodes e. v \\<in> vertices \\<and> nodeIndex e v > 0\"\n                                   \n                            \ntext \\<open>                          \n  The set of nodes explored nodes never decreases in the course\n  of the computation.\n\\<close>\nlemma exploredNodes_increasing:\n\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/Tarjan.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8962513703624558, "lm_q2_score": 0.8198933403143929, "lm_q1q2_score": 0.7348305298078259}}
{"text": "(*  Title:      HOL/UNITY/ListOrder.thy\n    Author:     Lawrence C Paulson, Cambridge University Computer Laboratory\n    Copyright   1998  University of Cambridge\n\nLists are partially ordered by Charpentier's Generalized Prefix Relation\n   (xs,ys) : genPrefix(r)\n     if ys = xs' @ zs where length xs = length xs'\n     and corresponding elements of xs, xs' are pairwise related by r\n\nAlso overloads <= and < for lists!\n*)\n\nsection {*The Prefix Ordering on Lists*}\n\ntheory ListOrder\nimports Main\nbegin\n\ninductive_set\n  genPrefix :: \"('a * 'a)set => ('a list * 'a list)set\"\n  for r :: \"('a * 'a)set\"\n where\n   Nil:     \"([],[]) : genPrefix(r)\"\n\n | prepend: \"[| (xs,ys) : genPrefix(r);  (x,y) : r |] ==>\n             (x#xs, y#ys) : genPrefix(r)\"\n\n | append:  \"(xs,ys) : genPrefix(r) ==> (xs, ys@zs) : genPrefix(r)\"\n\ninstantiation list :: (type) ord \nbegin\n\ndefinition\n  prefix_def:        \"xs <= zs \\<longleftrightarrow>  (xs, zs) : genPrefix Id\"\n\ndefinition\n  strict_prefix_def: \"xs < zs  \\<longleftrightarrow>  xs \\<le> zs \\<and> \\<not> zs \\<le> (xs :: 'a list)\"\n\ninstance ..  \n\n(*Constants for the <= and >= relations, used below in translations*)\n\nend\n\ndefinition Le :: \"(nat*nat) set\" where\n    \"Le == {(x,y). x <= y}\"\n\ndefinition  Ge :: \"(nat*nat) set\" where\n    \"Ge == {(x,y). y <= x}\"\n\nabbreviation\n  pfixLe :: \"[nat list, nat list] => bool\"  (infixl \"pfixLe\" 50)  where\n  \"xs pfixLe ys == (xs,ys) : genPrefix Le\"\n\nabbreviation\n  pfixGe :: \"[nat list, nat list] => bool\"  (infixl \"pfixGe\" 50)  where\n  \"xs pfixGe ys == (xs,ys) : genPrefix Ge\"\n\n\nsubsection{*preliminary lemmas*}\n\nlemma Nil_genPrefix [iff]: \"([], xs) : genPrefix r\"\nby (cut_tac genPrefix.Nil [THEN genPrefix.append], auto)\n\nlemma genPrefix_length_le: \"(xs,ys) : genPrefix r ==> length xs <= length ys\"\nby (erule genPrefix.induct, auto)\n\nlemma cdlemma:\n     \"[| (xs', ys'): genPrefix r |]  \n      ==> (ALL x xs. xs' = x#xs --> (EX y ys. ys' = y#ys & (x,y) : r & (xs, ys) : genPrefix r))\"\napply (erule genPrefix.induct, blast, blast)\napply (force intro: genPrefix.append)\ndone\n\n(*As usual converting it to an elimination rule is tiresome*)\nlemma cons_genPrefixE [elim!]: \n     \"[| (x#xs, zs): genPrefix r;   \n         !!y ys. [| zs = y#ys;  (x,y) : r;  (xs, ys) : genPrefix r |] ==> P  \n      |] ==> P\"\nby (drule cdlemma, simp, blast)\n\nlemma Cons_genPrefix_Cons [iff]:\n     \"((x#xs,y#ys) : genPrefix r) = ((x,y) : r & (xs,ys) : genPrefix r)\"\nby (blast intro: genPrefix.prepend)\n\n\nsubsection{*genPrefix is a partial order*}\n\nlemma refl_genPrefix: \"refl r ==> refl (genPrefix r)\"\napply (unfold refl_on_def, auto)\napply (induct_tac \"x\")\nprefer 2 apply (blast intro: genPrefix.prepend)\napply (blast intro: genPrefix.Nil)\ndone\n\nlemma genPrefix_refl [simp]: \"refl r ==> (l,l) : genPrefix r\"\nby (erule refl_onD [OF refl_genPrefix UNIV_I])\n\nlemma genPrefix_mono: \"r<=s ==> genPrefix r <= genPrefix s\"\napply clarify\napply (erule genPrefix.induct)\napply (auto intro: genPrefix.append)\ndone\n\n\n(** Transitivity **)\n\n(*A lemma for proving genPrefix_trans_O*)\nlemma append_genPrefix:\n     \"(xs @ ys, zs) : genPrefix r \\<Longrightarrow> (xs, zs) : genPrefix r\"\n  by (induct xs arbitrary: zs) auto\n\n(*Lemma proving transitivity and more*)\nlemma genPrefix_trans_O:\n  assumes \"(x, y) : genPrefix r\"\n  shows \"\\<And>z. (y, z) : genPrefix s \\<Longrightarrow> (x, z) : genPrefix (r O s)\"\n  apply (atomize (full))\n  using assms\n  apply induct\n    apply blast\n   apply (blast intro: genPrefix.prepend)\n  apply (blast dest: append_genPrefix)\n  done\n\nlemma genPrefix_trans:\n  \"(x, y) : genPrefix r \\<Longrightarrow> (y, z) : genPrefix r \\<Longrightarrow> trans r\n    \\<Longrightarrow> (x, z) : genPrefix r\"\n  apply (rule trans_O_subset [THEN genPrefix_mono, THEN subsetD])\n   apply assumption\n  apply (blast intro: genPrefix_trans_O)\n  done\n\nlemma prefix_genPrefix_trans:\n  \"[| x<=y;  (y,z) : genPrefix r |] ==> (x, z) : genPrefix r\"\napply (unfold prefix_def)\napply (drule genPrefix_trans_O, assumption)\napply simp\ndone\n\nlemma genPrefix_prefix_trans:\n  \"[| (x,y) : genPrefix r;  y<=z |] ==> (x,z) : genPrefix r\"\napply (unfold prefix_def)\napply (drule genPrefix_trans_O, assumption)\napply simp\ndone\n\nlemma trans_genPrefix: \"trans r ==> trans (genPrefix r)\"\nby (blast intro: transI genPrefix_trans)\n\n\n(** Antisymmetry **)\n\nlemma genPrefix_antisym:\n  assumes 1: \"(xs, ys) : genPrefix r\"\n    and 2: \"antisym r\"\n    and 3: \"(ys, xs) : genPrefix r\"\n  shows \"xs = ys\"\n  using 1 3\nproof induct\n  case Nil\n  then show ?case by blast\nnext\n  case prepend\n  then show ?case using 2 by (simp add: antisym_def)\nnext\n  case (append xs ys zs)\n  then show ?case\n    apply -\n    apply (subgoal_tac \"length zs = 0\", force)\n    apply (drule genPrefix_length_le)+\n    apply (simp del: length_0_conv)\n    done\nqed\n\nlemma antisym_genPrefix: \"antisym r ==> antisym (genPrefix r)\"\n  by (blast intro: antisymI genPrefix_antisym)\n\n\nsubsection{*recursion equations*}\n\nlemma genPrefix_Nil [simp]: \"((xs, []) : genPrefix r) = (xs = [])\"\n  by (induct xs) auto\n\nlemma same_genPrefix_genPrefix [simp]: \n    \"refl r ==> ((xs@ys, xs@zs) : genPrefix r) = ((ys,zs) : genPrefix r)\"\n  by (induct xs) (simp_all add: refl_on_def)\n\nlemma genPrefix_Cons:\n     \"((xs, y#ys) : genPrefix r) =  \n      (xs=[] | (EX z zs. xs=z#zs & (z,y) : r & (zs,ys) : genPrefix r))\"\n  by (cases xs) auto\n\nlemma genPrefix_take_append:\n     \"[| refl r;  (xs,ys) : genPrefix r |]  \n      ==>  (xs@zs, take (length xs) ys @ zs) : genPrefix r\"\napply (erule genPrefix.induct)\napply (frule_tac [3] genPrefix_length_le)\napply (simp_all (no_asm_simp) add: diff_is_0_eq [THEN iffD2])\ndone\n\nlemma genPrefix_append_both:\n     \"[| refl r;  (xs,ys) : genPrefix r;  length xs = length ys |]  \n      ==>  (xs@zs, ys @ zs) : genPrefix r\"\napply (drule genPrefix_take_append, assumption)\napply simp\ndone\n\n\n(*NOT suitable for rewriting since [y] has the form y#ys*)\nlemma append_cons_eq: \"xs @ y # ys = (xs @ [y]) @ ys\"\nby auto\n\nlemma aolemma:\n     \"[| (xs,ys) : genPrefix r;  refl r |]  \n      ==> length xs < length ys --> (xs @ [ys ! length xs], ys) : genPrefix r\"\napply (erule genPrefix.induct)\n  apply blast\n apply simp\ntxt{*Append case is hardest*}\napply simp\napply (frule genPrefix_length_le [THEN le_imp_less_or_eq])\napply (erule disjE)\napply (simp_all (no_asm_simp) add: neq_Nil_conv nth_append)\napply (blast intro: genPrefix.append, auto)\napply (subst append_cons_eq, fast intro: genPrefix_append_both genPrefix.append)\ndone\n\nlemma append_one_genPrefix:\n     \"[| (xs,ys) : genPrefix r;  length xs < length ys;  refl r |]  \n      ==> (xs @ [ys ! length xs], ys) : genPrefix r\"\nby (blast intro: aolemma [THEN mp])\n\n\n(** Proving the equivalence with Charpentier's definition **)\n\nlemma genPrefix_imp_nth:\n    \"i < length xs \\<Longrightarrow> (xs, ys) : genPrefix r \\<Longrightarrow> (xs ! i, ys ! i) : r\"\n  apply (induct xs arbitrary: i ys)\n   apply auto\n  apply (case_tac i)\n   apply auto\n  done\n\nlemma nth_imp_genPrefix:\n  \"length xs <= length ys \\<Longrightarrow>\n     (\\<forall>i. i < length xs --> (xs ! i, ys ! i) : r) \\<Longrightarrow>\n     (xs, ys) : genPrefix r\"\n  apply (induct xs arbitrary: ys)\n   apply (simp_all add: less_Suc_eq_0_disj all_conj_distrib)\n  apply (case_tac ys)\n   apply (force+)\n  done\n\nlemma genPrefix_iff_nth:\n     \"((xs,ys) : genPrefix r) =  \n      (length xs <= length ys & (ALL i. i < length xs --> (xs!i, ys!i) : r))\"\napply (blast intro: genPrefix_length_le genPrefix_imp_nth nth_imp_genPrefix)\ndone\n\n\nsubsection{*The type of lists is partially ordered*}\n\ndeclare refl_Id [iff] \n        antisym_Id [iff] \n        trans_Id [iff]\n\nlemma prefix_refl [iff]: \"xs <= (xs::'a list)\"\nby (simp add: prefix_def)\n\nlemma prefix_trans: \"!!xs::'a list. [| xs <= ys; ys <= zs |] ==> xs <= zs\"\napply (unfold prefix_def)\napply (blast intro: genPrefix_trans)\ndone\n\nlemma prefix_antisym: \"!!xs::'a list. [| xs <= ys; ys <= xs |] ==> xs = ys\"\napply (unfold prefix_def)\napply (blast intro: genPrefix_antisym)\ndone\n\nlemma prefix_less_le_not_le: \"!!xs::'a list. (xs < zs) = (xs <= zs & \\<not> zs \\<le> xs)\"\nby (unfold strict_prefix_def, auto)\n\ninstance list :: (type) order\n  by (intro_classes,\n      (assumption | rule prefix_refl prefix_trans prefix_antisym\n                     prefix_less_le_not_le)+)\n\n(*Monotonicity of \"set\" operator WRT prefix*)\nlemma set_mono: \"xs <= ys ==> set xs <= set ys\"\napply (unfold prefix_def)\napply (erule genPrefix.induct, auto)\ndone\n\n\n(** recursion equations **)\n\nlemma Nil_prefix [iff]: \"[] <= xs\"\nby (simp add: prefix_def)\n\nlemma prefix_Nil [simp]: \"(xs <= []) = (xs = [])\"\nby (simp add: prefix_def)\n\nlemma Cons_prefix_Cons [simp]: \"(x#xs <= y#ys) = (x=y & xs<=ys)\"\nby (simp add: prefix_def)\n\nlemma same_prefix_prefix [simp]: \"(xs@ys <= xs@zs) = (ys <= zs)\"\nby (simp add: prefix_def)\n\nlemma append_prefix [iff]: \"(xs@ys <= xs) = (ys <= [])\"\nby (insert same_prefix_prefix [of xs ys \"[]\"], simp)\n\nlemma prefix_appendI [simp]: \"xs <= ys ==> xs <= ys@zs\"\napply (unfold prefix_def)\napply (erule genPrefix.append)\ndone\n\nlemma prefix_Cons: \n   \"(xs <= y#ys) = (xs=[] | (? zs. xs=y#zs & zs <= ys))\"\nby (simp add: prefix_def genPrefix_Cons)\n\nlemma append_one_prefix: \n  \"[| xs <= ys; length xs < length ys |] ==> xs @ [ys ! length xs] <= ys\"\napply (unfold prefix_def)\napply (simp add: append_one_genPrefix)\ndone\n\nlemma prefix_length_le: \"xs <= ys ==> length xs <= length ys\"\napply (unfold prefix_def)\napply (erule genPrefix_length_le)\ndone\n\nlemma splemma: \"xs<=ys ==> xs~=ys --> length xs < length ys\"\napply (unfold prefix_def)\napply (erule genPrefix.induct, auto)\ndone\n\nlemma strict_prefix_length_less: \"xs < ys ==> length xs < length ys\"\napply (unfold strict_prefix_def)\napply (blast intro: splemma [THEN mp])\ndone\n\nlemma mono_length: \"mono length\"\nby (blast intro: monoI prefix_length_le)\n\n(*Equivalence to the definition used in Lex/Prefix.thy*)\nlemma prefix_iff: \"(xs <= zs) = (EX ys. zs = xs@ys)\"\napply (unfold prefix_def)\napply (auto simp add: genPrefix_iff_nth nth_append)\napply (rule_tac x = \"drop (length xs) zs\" in exI)\napply (rule nth_equalityI)\napply (simp_all (no_asm_simp) add: nth_append)\ndone\n\nlemma prefix_snoc [simp]: \"(xs <= ys@[y]) = (xs = ys@[y] | xs <= ys)\"\napply (simp add: prefix_iff)\napply (rule iffI)\n apply (erule exE)\n apply (rename_tac \"zs\")\n apply (rule_tac xs = zs in rev_exhaust)\n  apply simp\n apply clarify\n apply (simp del: append_assoc add: append_assoc [symmetric], force)\ndone\n\nlemma prefix_append_iff:\n     \"(xs <= ys@zs) = (xs <= ys | (? us. xs = ys@us & us <= zs))\"\napply (rule_tac xs = zs in rev_induct)\n apply force\napply (simp del: append_assoc add: append_assoc [symmetric], force)\ndone\n\n(*Although the prefix ordering is not linear, the prefixes of a list\n  are linearly ordered.*)\nlemma common_prefix_linear:\n  fixes xs ys zs :: \"'a list\"\n  shows \"xs <= zs \\<Longrightarrow> ys <= zs \\<Longrightarrow> xs <= ys | ys <= xs\"\n  by (induct zs rule: rev_induct) auto\n\nsubsection{*pfixLe, pfixGe: properties inherited from the translations*}\n\n(** pfixLe **)\n\nlemma refl_Le [iff]: \"refl Le\"\nby (unfold refl_on_def Le_def, auto)\n\nlemma antisym_Le [iff]: \"antisym Le\"\nby (unfold antisym_def Le_def, auto)\n\nlemma trans_Le [iff]: \"trans Le\"\nby (unfold trans_def Le_def, auto)\n\nlemma pfixLe_refl [iff]: \"x pfixLe x\"\nby simp\n\nlemma pfixLe_trans: \"[| x pfixLe y; y pfixLe z |] ==> x pfixLe z\"\nby (blast intro: genPrefix_trans)\n\nlemma pfixLe_antisym: \"[| x pfixLe y; y pfixLe x |] ==> x = y\"\nby (blast intro: genPrefix_antisym)\n\nlemma prefix_imp_pfixLe: \"xs<=ys ==> xs pfixLe ys\"\napply (unfold prefix_def Le_def)\napply (blast intro: genPrefix_mono [THEN [2] rev_subsetD])\ndone\n\nlemma refl_Ge [iff]: \"refl Ge\"\nby (unfold refl_on_def Ge_def, auto)\n\nlemma antisym_Ge [iff]: \"antisym Ge\"\nby (unfold antisym_def Ge_def, auto)\n\nlemma trans_Ge [iff]: \"trans Ge\"\nby (unfold trans_def Ge_def, auto)\n\nlemma pfixGe_refl [iff]: \"x pfixGe x\"\nby simp\n\nlemma pfixGe_trans: \"[| x pfixGe y; y pfixGe z |] ==> x pfixGe z\"\nby (blast intro: genPrefix_trans)\n\nlemma pfixGe_antisym: \"[| x pfixGe y; y pfixGe x |] ==> x = y\"\nby (blast intro: genPrefix_antisym)\n\nlemma prefix_imp_pfixGe: \"xs<=ys ==> xs pfixGe ys\"\napply (unfold prefix_def Ge_def)\napply (blast intro: genPrefix_mono [THEN [2] rev_subsetD])\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/ListOrder.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392909114836, "lm_q2_score": 0.8311430436757313, "lm_q1q2_score": 0.7347631069771058}}
{"text": "theory Desargues_Property\n  imports Main Projective_Plane_Axioms Pappus_Property Pascal_Property\nbegin\n\n(* Author: Anthony Bordg, University of Cambridge, apdb3@cam.ac.uk .*)\n\ntext \\<open>\nContents:\n\\<^item> We formalize Desargues's property, [desargues_prop], that states that if two triangles are perspective \nfrom a point, then they are perspective from a line. \nNote that some planes satisfy that property and some others don't, hence Desargues's property is\nnot a theorem though it is a theorem in projective space geometry. \n\\<close>\n\nsection \\<open>Desargues's Property\\<close>\n\ndefinition distinct3 :: \"[Points, Points, Points] \\<Rightarrow> bool\" where\n\"distinct3 A B C \\<equiv> A \\<noteq> B \\<and> A \\<noteq> C \\<and> B \\<noteq> C\"\n\ndefinition triangle :: \"[Points, Points, Points] \\<Rightarrow> bool\" where\n\"triangle A B C \\<equiv> distinct3 A B C \\<and> (line A B \\<noteq> line A C)\"\n\ndefinition meet_in :: \"Lines \\<Rightarrow> Lines => Points => bool \" where\n\"meet_in l m P \\<equiv> incid P l \\<and> incid P m\"\n\nlemma meet_col_1:\n  assumes \"meet_in (line A B) (line C D) P\"\n  shows \"col A B P\"\n  using assms col_def incidA_lAB incidB_lAB meet_in_def \n  by blast\n\nlemma meet_col_2:\n  assumes \"meet_in (line A B) (line C D) P\"\n  shows \"col C D P\"\n  using assms meet_col_1 meet_in_def \n  by auto\n\ndefinition meet_3_in :: \"[Lines, Lines, Lines, Points] \\<Rightarrow> bool\" where\n\"meet_3_in l m n P \\<equiv> meet_in l m P \\<and> meet_in l n P\"\n\nlemma meet_all_3:\n  assumes \"meet_3_in l m n P\"\n  shows \"meet_in m n P\"\n  using assms meet_3_in_def meet_in_def \n  by auto\n\n\n\nlemma meet_3_col_1:\n  assumes \"meet_3_in (line A B) m n P\"\n  shows \"col A B P\"\n  using assms meet_3_in_def meet_col_2 meet_in_def \n  by auto\n\nlemma meet_3_col_2:\n  assumes \"meet_3_in l (line A B) n P\"\n  shows \"col A B P\"\n  using assms col_def incidA_lAB incidB_lAB meet_3_in_def meet_in_def \n  by blast\n\nlemma meet_3_col_3:\n  assumes \"meet_3_in l m (line A B) P\"\n  shows \"col A B P\"\n  using assms meet_3_col_2 meet_3_in_def \n  by auto\n\ndefinition distinct7 ::\n  \"[Points, Points, Points, Points, Points, Points, Points] \\<Rightarrow> bool\" where\n\"distinct7 A B C D E F G \\<equiv> (A \\<noteq> B) \\<and> (A \\<noteq> C) \\<and> (A \\<noteq> D) \\<and> (A \\<noteq> E) \\<and> (A \\<noteq> F) \\<and> (A \\<noteq> G) \\<and>\n(B \\<noteq> C) \\<and> (B \\<noteq> D) \\<and> (B \\<noteq> E) \\<and> (B \\<noteq> F) \\<and> (B \\<noteq> G) \\<and>\n(C \\<noteq> D) \\<and> (C \\<noteq> E) \\<and> (C \\<noteq> F) \\<and> (C \\<noteq> G) \\<and>\n(D \\<noteq> E) \\<and> (D \\<noteq> F) \\<and> (D \\<noteq> G) \\<and>\n(E \\<noteq> F) \\<and> (E \\<noteq> G) \\<and>\n(F \\<noteq> G)\"\n\ndefinition distinct3l :: \"[Lines, Lines, Lines] \\<Rightarrow> bool\" where\n\"distinct3l l m n \\<equiv> l \\<noteq> m \\<and> l \\<noteq> n \\<and> m \\<noteq> n\"\n\n(* From now on we give less general statements on purpose to avoid a lot of uninteresting \ndegenerate cases, since we can hardly think of any interesting application where one would need \nto instantiate a statement on such degenerate case, hence our statements and proofs will be more \ntextbook-like. For the working mathematician the only thing that probably matters is the main\ntheorem without considering all the degenerate cases for which the statement might still hold. *)\n\ndefinition desargues_config :: \n  \"[Points, Points, Points, Points, Points, Points, Points, Points, Points, Points] => bool\" where\n\"desargues_config A B C A' B' C' M N P R \\<equiv> distinct7 A B C A' B' C' R \\<and> \\<not> col A B C \n\\<and> \\<not> col A' B' C' \\<and> distinct3l (line A A') (line B B') (line C C') \\<and> \nmeet_3_in (line A A') (line B B') (line C C') R \\<and> (line A B) \\<noteq> (line A' B') \\<and> \n(line B C) \\<noteq> (line B' C') \\<and> (line A C) \\<noteq> (line A' C') \\<and> meet_in (line B C) (line B' C') M \\<and>\nmeet_in (line A C) (line A' C') N \\<and> meet_in (line A B) (line A' B') P\"\n\nlemma distinct7_rot_CW:\n  assumes \"distinct7 A B C D E F G\"\n  shows \"distinct7 C A B F D E G\"\n  using assms distinct7_def \n  by auto\n\n(* Desargues configurations are stable under any rotation (i,j,k) of {1,2,3} *)\n\n\nlemma desargues_config_rot_CCW:\n  assumes \"desargues_config A B C A' B' C' M N P R\"\n  shows \"desargues_config B C A B' C' A' N P M R\"\n  by (simp add: assms desargues_config_rot_CW)\n\n(* With the two following definitions we repackage the definition of a Desargues configuration in a \n\"high-level\", i.e. textbook-like, way. *)\n\ndefinition are_perspective_from_point :: \n  \"[Points, Points, Points, Points, Points, Points, Points] \\<Rightarrow> bool\" where\n\"are_perspective_from_point A B C A' B' C' R \\<equiv> distinct7 A B C A' B' C' R \\<and> triangle A B C \\<and>\ntriangle A' B' C' \\<and> distinct3l (line A A') (line B B') (line C C') \\<and> \nmeet_3_in (line A A') (line B B') (line C C') R\"\n\ndefinition are_perspective_from_line ::\n  \"[Points, Points, Points, Points, Points, Points] \\<Rightarrow> bool\" where\n\"are_perspective_from_line A B C A' B' C' \\<equiv> distinct6 A B C A' B' C' \\<longrightarrow> triangle A B C \\<longrightarrow>\ntriangle A' B' C' \\<longrightarrow> line A B \\<noteq> line A' B' \\<longrightarrow> line A C \\<noteq> line A' C' \\<longrightarrow> line B C \\<noteq> line B' C' \\<longrightarrow>\ncol (inter (line A B) (line A' B')) (inter (line A C) (line A' C')) (inter (line B C) (line B' C'))\"\n\nlemma meet_in_inter:\n  assumes \"l \\<noteq> m\"\n  shows \"meet_in l m (inter l m)\"\n  by (simp add: incid_inter_left incid_inter_right meet_in_def)\n\nlemma perspective_from_point_desargues_config:\n  assumes \"are_perspective_from_point A B C A' B' C' R\" and \"line A B \\<noteq> line A' B'\" and \n    \"line A C \\<noteq> line A' C'\" and \"line B C \\<noteq> line B' C'\"\n  shows \"desargues_config A B C A' B' C' (inter (line B C) (line B' C')) (inter (line A C) (line A' C')) \n    (inter (line A B) (line A' B')) R\"\n  by (smt are_perspective_from_point_def assms(1) assms(2) assms(3) assms(4) col_line_ext_1 \n      desargues_config_def distinct3_def incidB_lAB inter_line_ext_2 line_comm meet_in_inter \n      triangle_def uniq_inter)\n\n(* Now, we state Desargues's property in a textbook-like form *)\ndefinition desargues_prop :: \"bool\" where\n\"desargues_prop \\<equiv> \n\\<forall>A B C A' B' C' P. \n  are_perspective_from_point A B C A' B' C' P \\<longrightarrow> are_perspective_from_line A B C A' B' C'\"\n\nend\n\n\n\n\n\n\n", "meta": {"author": "AnthonyBordg", "repo": "Isabelle_marries_Desargues", "sha": "e5061842d78328635169eba6e1c7c970fd33313f", "save_path": "github-repos/isabelle/AnthonyBordg-Isabelle_marries_Desargues", "path": "github-repos/isabelle/AnthonyBordg-Isabelle_marries_Desargues/Isabelle_marries_Desargues-e5061842d78328635169eba6e1c7c970fd33313f/Plane/Desargues_Property.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587993853654, "lm_q2_score": 0.8267117983401363, "lm_q1q2_score": 0.7347473853304959}}
{"text": "(*  Title:      HOL/ex/Sqrt.thy\n    Author:     Markus Wenzel, Tobias Nipkow, TU Muenchen\n*)\n\nsection \\<open>Square roots of primes are irrational\\<close>\n\ntheory Sqrt\nimports Complex_Main \"~~/src/HOL/Number_Theory/Primes\"\nbegin\n\ntext \\<open>The square root of any prime number (including 2) is irrational.\\<close>\n\ntheorem sqrt_prime_irrational:\n  assumes \"prime (p::nat)\"\n  shows \"sqrt p \\<notin> \\<rat>\"\nproof\n  from \\<open>prime p\\<close> have p: \"1 < p\" by (simp add: prime_nat_iff)\n  assume \"sqrt p \\<in> \\<rat>\"\n  then obtain m n :: nat where\n      n: \"n \\<noteq> 0\" 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\"\n      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 show ?thesis using of_nat_eq_iff by blast\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_nat)\n    then obtain k where \"m = p * k\" ..\n    with eq have \"p * n\\<^sup>2 = p\\<^sup>2 * k\\<^sup>2\" by (auto simp add: power2_eq_square ac_simps)\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_nat)\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\n\nsubsection \\<open>Variations\\<close>\n\ntext \\<open>\n  Here is an alternative version of the main proof, using mostly\n  linear forward-reasoning.  While this results in less top-down\n  structure, it is probably closer to proofs seen in mathematics.\n\\<close>\n\ntheorem\n  assumes \"prime (p::nat)\"\n  shows \"sqrt p \\<notin> \\<rat>\"\nproof\n  from \\<open>prime p\\<close> have p: \"1 < p\" by (simp add: prime_nat_iff)\n  assume \"sqrt p \\<in> \\<rat>\"\n  then obtain m n :: nat where\n      n: \"n \\<noteq> 0\" 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\"\n    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\" using of_nat_eq_iff by blast\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_nat)\n  then obtain k where \"m = p * k\" ..\n  with eq have \"p * n\\<^sup>2 = p\\<^sup>2 * k\\<^sup>2\" by (auto simp add: power2_eq_square ac_simps)\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_nat)\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>Another old chestnut, which is a consequence of the irrationality of 2.\\<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\n  assume \"sqrt 2 powr sqrt 2 \\<in> \\<rat>\"\n  then have \"?P (sqrt 2) (sqrt 2)\"\n    by (metis sqrt_2_not_rat)\n  then show ?thesis by blast\nnext\n  assume 1: \"sqrt 2 powr sqrt 2 \\<notin> \\<rat>\"\n  have \"(sqrt 2 powr sqrt 2) powr sqrt 2 = 2\"\n    using powr_realpow [of _ 2]\n    by (simp add: powr_powr power2_eq_square [symmetric])\n  then have \"?P (sqrt 2 powr sqrt 2) (sqrt 2)\"\n    by (metis 1 Rats_number_of sqrt_2_not_rat)\n  then 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/ex/Sqrt.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950947024555, "lm_q2_score": 0.8705972768020108, "lm_q1q2_score": 0.7346927713545328}}
{"text": "(*  Title:      HOL/Modules.thy\n    Author:     Amine Chaieb, University of Cambridge\n    Author:     Jose Divas\u00f3n <jose.divasonm at unirioja.es>\n    Author:     Jes\u00fas Aransay <jesus-maria.aransay at unirioja.es>\n    Author:     Johannes H\u00f6lzl, VU Amsterdam\n    Author:     Fabian Immler, TUM\n*)\n\nsection \\<open>Modules\\<close>\n\ntext \\<open>Bases of a linear algebra based on modules (i.e. vector spaces of rings). \\<close>\n\ntheory Modules\n  imports Hull\nbegin\n\nsubsection \\<open>Locale for additive functions\\<close>\n\nlocale additive =\n  fixes f :: \"'a::ab_group_add \\<Rightarrow> 'b::ab_group_add\"\n  assumes add: \"f (x + y) = f x + f y\"\nbegin\n\nlemma zero: \"f 0 = 0\"\nproof -\n  have \"f 0 = f (0 + 0)\" by simp\n  also have \"\\<dots> = f 0 + f 0\" by (rule add)\n  finally show \"f 0 = 0\" by simp\nqed\n\nlemma minus: \"f (- x) = - f x\"\nproof -\n  have \"f (- x) + f x = f (- x + x)\" by (rule add [symmetric])\n  also have \"\\<dots> = - f x + f x\" by (simp add: zero)\n  finally show \"f (- x) = - f x\" by (rule add_right_imp_eq)\nqed\n\nlemma diff: \"f (x - y) = f x - f y\"\n  using add [of x \"- y\"] by (simp add: minus)\n\nlemma sum: \"f (sum g A) = (\\<Sum>x\\<in>A. f (g x))\"\n  by (induct A rule: infinite_finite_induct) (simp_all add: zero add)\n\nend\n\n\ntext \\<open>Modules form the central spaces in linear algebra. They are a generalization from vector\nspaces by replacing the scalar field by a scalar ring.\\<close>\nlocale module =\n  fixes scale :: \"'a::comm_ring_1 \\<Rightarrow> 'b::ab_group_add \\<Rightarrow> 'b\" (infixr \"*s\" 75)\n  assumes scale_right_distrib [algebra_simps, algebra_split_simps]:\n      \"a *s (x + y) = a *s x + a *s y\"\n    and scale_left_distrib [algebra_simps, algebra_split_simps]:\n      \"(a + b) *s x = a *s x + b *s x\"\n    and scale_scale [simp]: \"a *s (b *s x) = (a * b) *s x\"\n    and scale_one [simp]: \"1 *s x = x\"\nbegin\n\nlemma scale_left_commute: \"a *s (b *s x) = b *s (a *s x)\"\n  by (simp add: mult.commute)\n\nlemma scale_zero_left [simp]: \"0 *s x = 0\"\n  and scale_minus_left [simp]: \"(- a) *s x = - (a *s x)\"\n  and scale_left_diff_distrib [algebra_simps, algebra_split_simps]:\n    \"(a - b) *s x = a *s x - b *s x\"\n  and scale_sum_left: \"(sum f A) *s x = (\\<Sum>a\\<in>A. (f a) *s x)\"\nproof -\n  interpret s: additive \"\\<lambda>a. a *s x\"\n    by standard (rule scale_left_distrib)\n  show \"0 *s x = 0\" by (rule s.zero)\n  show \"(- a) *s x = - (a *s x)\" by (rule s.minus)\n  show \"(a - b) *s x = a *s x - b *s x\" by (rule s.diff)\n  show \"(sum f A) *s x = (\\<Sum>a\\<in>A. (f a) *s x)\" by (rule s.sum)\nqed\n\nlemma scale_zero_right [simp]: \"a *s 0 = 0\"\n  and scale_minus_right [simp]: \"a *s (- x) = - (a *s x)\"\n  and scale_right_diff_distrib [algebra_simps, algebra_split_simps]: \n    \"a *s (x - y) = a *s x - a *s y\"\n  and scale_sum_right: \"a *s (sum f A) = (\\<Sum>x\\<in>A. a *s (f x))\"\nproof -\n  interpret s: additive \"\\<lambda>x. a *s x\"\n    by standard (rule scale_right_distrib)\n  show \"a *s 0 = 0\" by (rule s.zero)\n  show \"a *s (- x) = - (a *s x)\" by (rule s.minus)\n  show \"a *s (x - y) = a *s x - a *s y\" by (rule s.diff)\n  show \"a *s (sum f A) = (\\<Sum>x\\<in>A. a *s (f x))\" by (rule s.sum)\nqed\n\nlemma sum_constant_scale: \"(\\<Sum>x\\<in>A. y) = scale (of_nat (card A)) y\"\n  by (induct A rule: infinite_finite_induct) (simp_all add: algebra_simps)\n\nend\n\nsetup \\<open>Sign.add_const_constraint (\\<^const_name>\\<open>divide\\<close>, SOME \\<^typ>\\<open>'a \\<Rightarrow> 'a \\<Rightarrow> 'a\\<close>)\\<close>\n\ncontext module\nbegin\n\nlemma [field_simps, field_split_simps]:\n  shows scale_left_distrib_NO_MATCH: \"NO_MATCH (x div y) c \\<Longrightarrow> (a + b) *s x = a *s x + b *s x\"\n    and scale_right_distrib_NO_MATCH: \"NO_MATCH (x div y) a \\<Longrightarrow> a *s (x + y) = a *s x + a *s y\"\n    and scale_left_diff_distrib_NO_MATCH: \"NO_MATCH (x div y) c \\<Longrightarrow> (a - b) *s x = a *s x - b *s x\"\n    and scale_right_diff_distrib_NO_MATCH: \"NO_MATCH (x div y) a \\<Longrightarrow> a *s (x - y) = a *s x - a *s y\"\n  by (rule scale_left_distrib scale_right_distrib scale_left_diff_distrib scale_right_diff_distrib)+\n\nend\n\nsetup \\<open>Sign.add_const_constraint (\\<^const_name>\\<open>divide\\<close>, SOME \\<^typ>\\<open>'a::divide \\<Rightarrow> 'a \\<Rightarrow> 'a\\<close>)\\<close>\n\n\nsection \\<open>Subspace\\<close>\n\ncontext module\nbegin\n\ndefinition subspace :: \"'b set \\<Rightarrow> bool\"\n  where \"subspace S \\<longleftrightarrow> 0 \\<in> S \\<and> (\\<forall>x\\<in>S. \\<forall>y\\<in>S. x + y \\<in> S) \\<and> (\\<forall>c. \\<forall>x\\<in>S. c *s x \\<in> S)\"\n\nlemma subspaceI:\n  \"0 \\<in> S \\<Longrightarrow> (\\<And>x y. x \\<in> S \\<Longrightarrow> y \\<in> S \\<Longrightarrow> x + y \\<in> S) \\<Longrightarrow> (\\<And>c x. x \\<in> S \\<Longrightarrow> c *s x \\<in> S) \\<Longrightarrow> subspace S\"\n  by (auto simp: subspace_def)\n\nlemma subspace_UNIV[simp]: \"subspace UNIV\"\n  by (simp add: subspace_def)\n\nlemma subspace_single_0[simp]: \"subspace {0}\"\n  by (simp add: subspace_def)\n\nlemma subspace_0: \"subspace S \\<Longrightarrow> 0 \\<in> S\"\n  by (metis subspace_def)\n\nlemma subspace_add: \"subspace S \\<Longrightarrow> x \\<in> S \\<Longrightarrow> y \\<in> S \\<Longrightarrow> x + y \\<in> S\"\n  by (metis subspace_def)\n\nlemma subspace_scale: \"subspace S \\<Longrightarrow> x \\<in> S \\<Longrightarrow> c *s x \\<in> S\"\n  by (metis subspace_def)\n\nlemma subspace_neg: \"subspace S \\<Longrightarrow> x \\<in> S \\<Longrightarrow> - x \\<in> S\"\n  by (metis scale_minus_left scale_one subspace_scale)\n\nlemma subspace_diff: \"subspace S \\<Longrightarrow> x \\<in> S \\<Longrightarrow> y \\<in> S \\<Longrightarrow> x - y \\<in> S\"\n  by (metis diff_conv_add_uminus subspace_add subspace_neg)\n\nlemma subspace_sum: \"subspace A \\<Longrightarrow> (\\<And>x. x \\<in> B \\<Longrightarrow> f x \\<in> A) \\<Longrightarrow> sum f B \\<in> A\"\n  by (induct B rule: infinite_finite_induct) (auto simp add: subspace_add subspace_0)\n\nlemma subspace_Int: \"(\\<And>i. i \\<in> I \\<Longrightarrow> subspace (s i)) \\<Longrightarrow> subspace (\\<Inter>i\\<in>I. s i)\"\n  by (auto simp: subspace_def)\n\nlemma subspace_Inter: \"\\<forall>s \\<in> f. subspace s \\<Longrightarrow> subspace (\\<Inter>f)\"\n  unfolding subspace_def by auto\n\nlemma subspace_inter: \"subspace A \\<Longrightarrow> subspace B \\<Longrightarrow> subspace (A \\<inter> B)\"\n  by (simp add: subspace_def)\n\n\nsection \\<open>Span: subspace generated by a set\\<close>\n\ndefinition span :: \"'b set \\<Rightarrow> 'b set\"\n  where span_explicit: \"span b = {(\\<Sum>a\\<in>t. r a *s  a) | t r. finite t \\<and> t \\<subseteq> b}\"\n\nlemma span_explicit':\n  \"span b = {(\\<Sum>v | f v \\<noteq> 0. f v *s v) | f. finite {v. f v \\<noteq> 0} \\<and> (\\<forall>v. f v \\<noteq> 0 \\<longrightarrow> v \\<in> b)}\"\n  unfolding span_explicit\nproof safe\n  fix t r assume \"finite t\" \"t \\<subseteq> b\"\n  then show \"\\<exists>f. (\\<Sum>a\\<in>t. r a *s a) = (\\<Sum>v | f v \\<noteq> 0. f v *s v) \\<and> finite {v. f v \\<noteq> 0} \\<and> (\\<forall>v. f v \\<noteq> 0 \\<longrightarrow> v \\<in> b)\"\n    by (intro exI[of _ \"\\<lambda>v. if v \\<in> t then r v else 0\"]) (auto intro!: sum.mono_neutral_cong_right)\nnext\n  fix f :: \"'b \\<Rightarrow> 'a\" assume \"finite {v. f v \\<noteq> 0}\" \"(\\<forall>v. f v \\<noteq> 0 \\<longrightarrow> v \\<in> b)\"\n  then show \"\\<exists>t r. (\\<Sum>v | f v \\<noteq> 0. f v *s v) = (\\<Sum>a\\<in>t. r a *s a) \\<and> finite t \\<and> t \\<subseteq> b\"\n    by (intro exI[of _ \"{v. f v \\<noteq> 0}\"] exI[of _ f]) auto\nqed\n\nlemma span_alt:\n  \"span B = {(\\<Sum>x | f x \\<noteq> 0. f x *s x) | f. {x. f x \\<noteq> 0} \\<subseteq> B \\<and> finite {x. f x \\<noteq> 0}}\"\n  unfolding span_explicit' by auto\n\nlemma span_finite:\n  assumes fS: \"finite S\"\n  shows \"span S = range (\\<lambda>u. \\<Sum>v\\<in>S. u v *s v)\"\n  unfolding span_explicit\nproof safe\n  fix t r assume \"t \\<subseteq> S\" then show \"(\\<Sum>a\\<in>t. r a *s a) \\<in> range (\\<lambda>u. \\<Sum>v\\<in>S. u v *s v)\"\n    by (intro image_eqI[of _ _ \"\\<lambda>a. if a \\<in> t then r a else 0\"])\n       (auto simp: if_distrib[of \"\\<lambda>r. r *s a\" for a] sum.If_cases fS Int_absorb1)\nnext\n  show \"\\<exists>t r. (\\<Sum>v\\<in>S. u v *s v) = (\\<Sum>a\\<in>t. r a *s a) \\<and> finite t \\<and> t \\<subseteq> S\" for u\n    by (intro exI[of _ u] exI[of _ S]) (auto intro: fS)\nqed\n\nlemma span_induct_alt [consumes 1, case_names base step, induct set: span]:\n  assumes x: \"x \\<in> span S\"\n  assumes h0: \"h 0\" and hS: \"\\<And>c x y. x \\<in> S \\<Longrightarrow> h y \\<Longrightarrow> h (c *s x + y)\"\n  shows \"h x\"\n  using x unfolding span_explicit\nproof safe\n  fix t r assume \"finite t\" \"t \\<subseteq> S\" then show \"h (\\<Sum>a\\<in>t. r a *s a)\"\n    by (induction t) (auto intro!: hS h0)\nqed\n\nlemma span_mono: \"A \\<subseteq> B \\<Longrightarrow> span A \\<subseteq> span B\"\n  by (auto simp: span_explicit)\n\nlemma span_base: \"a \\<in> S \\<Longrightarrow> a \\<in> span S\"\n  by (auto simp: span_explicit intro!: exI[of _ \"{a}\"] exI[of _ \"\\<lambda>_. 1\"])\n\nlemma span_superset: \"S \\<subseteq> span S\"\n  by (auto simp: span_base)\n\nlemma span_zero: \"0 \\<in> span S\"\n  by (auto simp: span_explicit intro!: exI[of _ \"{}\"])\n\nlemma span_UNIV[simp]: \"span UNIV = UNIV\"\n  by (auto intro: span_base)\n\nlemma span_add: \"x \\<in> span S \\<Longrightarrow> y \\<in> span S \\<Longrightarrow> x + y \\<in> span S\"\n  unfolding span_explicit\nproof safe\n  fix tx ty rx ry assume *: \"finite tx\" \"finite ty\" \"tx \\<subseteq> S\" \"ty \\<subseteq> S\"\n  have [simp]: \"(tx \\<union> ty) \\<inter> tx = tx\" \"(tx \\<union> ty) \\<inter> ty = ty\"\n    by auto\n  show \"\\<exists>t r. (\\<Sum>a\\<in>tx. rx a *s a) + (\\<Sum>a\\<in>ty. ry a *s a) = (\\<Sum>a\\<in>t. r a *s a) \\<and> finite t \\<and> t \\<subseteq> S\"\n    apply (intro exI[of _ \"tx \\<union> ty\"])\n    apply (intro exI[of _ \"\\<lambda>a. (if a \\<in> tx then rx a else 0) + (if a \\<in> ty then ry a else 0)\"])\n    apply (auto simp: * scale_left_distrib sum.distrib if_distrib[of \"\\<lambda>r. r *s a\" for a] sum.If_cases)\n    done\nqed\n\nlemma span_scale: \"x \\<in> span S \\<Longrightarrow> c *s x \\<in> span S\"\n  unfolding span_explicit\nproof safe\n  fix t r assume *: \"finite t\" \"t \\<subseteq> S\"\n  show \"\\<exists>t' r'. c *s (\\<Sum>a\\<in>t. r a *s a) = (\\<Sum>a\\<in>t'. r' a *s a) \\<and> finite t' \\<and> t' \\<subseteq> S\"\n    by (intro exI[of _ t] exI[of _ \"\\<lambda>a. c * r a\"]) (auto simp: * scale_sum_right)\nqed\n\nlemma subspace_span [iff]: \"subspace (span S)\"\n  by (auto simp: subspace_def span_zero span_add span_scale)\n\nlemma span_neg: \"x \\<in> span S \\<Longrightarrow> - x \\<in> span S\"\n  by (metis subspace_neg subspace_span)\n\nlemma span_diff: \"x \\<in> span S \\<Longrightarrow> y \\<in> span S \\<Longrightarrow> x - y \\<in> span S\"\n  by (metis subspace_span subspace_diff)\n\nlemma span_sum: \"(\\<And>x. x \\<in> A \\<Longrightarrow> f x \\<in> span S) \\<Longrightarrow> sum f A \\<in> span S\"\n  by (rule subspace_sum, rule subspace_span)\n\nlemma span_minimal: \"S \\<subseteq> T \\<Longrightarrow> subspace T \\<Longrightarrow> span S \\<subseteq> T\"\n  by (auto simp: span_explicit intro!: subspace_sum subspace_scale)\n\nlemma span_def: \"span S = subspace hull S\" \n  by (intro hull_unique[symmetric] span_superset subspace_span span_minimal)\n\nlemma span_unique:\n  \"S \\<subseteq> T \\<Longrightarrow> subspace T \\<Longrightarrow> (\\<And>T'. S \\<subseteq> T' \\<Longrightarrow> subspace T' \\<Longrightarrow> T \\<subseteq> T') \\<Longrightarrow> span S = T\"\n  unfolding span_def by (rule hull_unique)\n\nlemma span_subspace_induct[consumes 2]:\n  assumes x: \"x \\<in> span S\"\n    and P: \"subspace P\"\n    and SP: \"\\<And>x. x \\<in> S \\<Longrightarrow> x \\<in> P\"\n  shows \"x \\<in> P\"\nproof -\n  from SP have SP': \"S \\<subseteq> P\"\n    by (simp add: subset_eq)\n  from x hull_minimal[where S=subspace, OF SP' P, unfolded span_def[symmetric]]\n  show \"x \\<in> P\"\n    by (metis subset_eq)\nqed\n\nlemma (in module) span_induct[consumes 1, case_names base step, induct set: span]:\n  assumes x: \"x \\<in> span S\"\n    and P: \"subspace (Collect P)\"\n    and SP: \"\\<And>x. x \\<in> S \\<Longrightarrow> P x\"\n  shows \"P x\"\n  using P SP span_subspace_induct x by fastforce\n\nlemma span_empty[simp]: \"span {} = {0}\"\n  by (rule span_unique) (auto simp add: subspace_def)\n\nlemma span_subspace: \"A \\<subseteq> B \\<Longrightarrow> B \\<subseteq> span A \\<Longrightarrow> subspace B \\<Longrightarrow> span A = B\"\n  by (metis order_antisym span_def hull_minimal)\n\nlemma span_span: \"span (span A) = span A\"\n  unfolding span_def hull_hull ..\n\n(* TODO: proof generally for subspace: *)\nlemma span_add_eq: assumes x: \"x \\<in> span S\" shows \"x + y \\<in> span S \\<longleftrightarrow> y \\<in> span S\"\nproof\n  assume *: \"x + y \\<in> span S\"\n  have \"(x + y) - x \\<in> span S\" using * x by (rule span_diff)\n  then show \"y \\<in> span S\" by simp\nqed (intro span_add x)\n\nlemma span_add_eq2: assumes y: \"y \\<in> span S\" shows \"x + y \\<in> span S \\<longleftrightarrow> x \\<in> span S\"\n  using span_add_eq[of y S x] y by (auto simp: ac_simps)\n\nlemma span_singleton: \"span {x} = range (\\<lambda>k. k *s x)\"\n  by (auto simp: span_finite)\n\nlemma span_Un: \"span (S \\<union> T) = {x + y | x y. x \\<in> span S \\<and> y \\<in> span T}\"\nproof safe\n  fix x assume \"x \\<in> span (S \\<union> T)\"\n  then obtain t r where t: \"finite t\" \"t \\<subseteq> S \\<union> T\" and x: \"x = (\\<Sum>a\\<in>t. r a *s a)\"\n    by (auto simp: span_explicit)\n  moreover have \"t \\<inter> S \\<union> (t - S) = t\" by auto\n  ultimately show \"\\<exists>xa y. x = xa + y \\<and> xa \\<in> span S \\<and> y \\<in> span T\"\n    unfolding x\n    apply (rule_tac exI[of _ \"\\<Sum>a\\<in>t \\<inter> S. r a *s a\"])\n    apply (rule_tac exI[of _ \"\\<Sum>a\\<in>t - S. r a *s a\"])\n    apply (subst sum.union_inter_neutral[symmetric])\n    apply (auto intro!: span_sum span_scale intro: span_base)\n    done\nnext\n  fix x y assume\"x \\<in> span S\" \"y \\<in> span T\" then show \"x + y \\<in> span (S \\<union> T)\"\n    using span_mono[of S \"S \\<union> T\"] span_mono[of T \"S \\<union> T\"]\n    by (auto intro!: span_add)\nqed\n\nlemma span_insert: \"span (insert a S) = {x. \\<exists>k. (x - k *s a) \\<in> span S}\"\nproof -\n  have \"span ({a} \\<union> S) = {x. \\<exists>k. (x - k *s a) \\<in> span S}\"\n    unfolding span_Un span_singleton\n    apply (auto simp add: set_eq_iff)\n    subgoal for y k by (auto intro!: exI[of _ \"k\"])\n    subgoal for y k by (rule exI[of _ \"k *s a\"], rule exI[of _ \"y - k *s a\"]) auto\n    done\n  then show ?thesis by simp\nqed\n\nlemma span_breakdown:\n  assumes bS: \"b \\<in> S\"\n    and aS: \"a \\<in> span S\"\n  shows \"\\<exists>k. a - k *s b \\<in> span (S - {b})\"\n  using assms span_insert [of b \"S - {b}\"]\n  by (simp add: insert_absorb)\n\nlemma span_breakdown_eq: \"x \\<in> span (insert a S) \\<longleftrightarrow> (\\<exists>k. x - k *s a \\<in> span S)\"\n  by (simp add: span_insert)\n\nlemmas span_clauses = span_base span_zero span_add span_scale\n\nlemma span_eq_iff[simp]: \"span s = s \\<longleftrightarrow> subspace s\"\n  unfolding span_def by (rule hull_eq) (rule subspace_Inter)\n\nlemma span_eq: \"span S = span T \\<longleftrightarrow> S \\<subseteq> span T \\<and> T \\<subseteq> span S\"\n  by (metis span_minimal span_subspace span_superset subspace_span)\n\nlemma eq_span_insert_eq:\n  assumes \"(x - y) \\<in> span S\"\n    shows \"span(insert x S) = span(insert y S)\"\nproof -\n  have *: \"span(insert x S) \\<subseteq> span(insert y S)\" if \"(x - y) \\<in> span S\" for x y\n  proof -\n    have 1: \"(r *s x - r *s y) \\<in> span S\" for r\n      by (metis scale_right_diff_distrib span_scale that)\n    have 2: \"(z - k *s y) - k *s (x - y) = z - k *s x\" for  z k\n      by (simp add: scale_right_diff_distrib)\n  show ?thesis\n    apply (clarsimp simp add: span_breakdown_eq)\n    by (metis 1 2 diff_add_cancel scale_right_diff_distrib span_add_eq)\n  qed\n  show ?thesis\n    apply (intro subset_antisym * assms)\n    using assms subspace_neg subspace_span minus_diff_eq by force\nqed\n\n\nsection \\<open>Dependent and independent sets\\<close>\n\ndefinition dependent :: \"'b set \\<Rightarrow> bool\"\n  where dependent_explicit: \"dependent s \\<longleftrightarrow> (\\<exists>t u. finite t \\<and> t \\<subseteq> s \\<and> (\\<Sum>v\\<in>t. u v *s v) = 0 \\<and> (\\<exists>v\\<in>t. u v \\<noteq> 0))\"\n\nabbreviation \"independent s \\<equiv> \\<not> dependent s\"\n\nlemma dependent_mono: \"dependent B \\<Longrightarrow> B \\<subseteq> A \\<Longrightarrow> dependent A\"\n  by (auto simp add: dependent_explicit)\n\nlemma independent_mono: \"independent A \\<Longrightarrow> B \\<subseteq> A \\<Longrightarrow> independent B\"\n  by (auto intro: dependent_mono)\n\nlemma dependent_zero: \"0 \\<in> A \\<Longrightarrow> dependent A\"\n  by (auto simp: dependent_explicit intro!: exI[of _ \"\\<lambda>i. 1\"] exI[of _ \"{0}\"])\n\nlemma independent_empty[intro]: \"independent {}\"\n  by (simp add: dependent_explicit)\n\nlemma independent_explicit_module:\n  \"independent s \\<longleftrightarrow> (\\<forall>t u v. finite t \\<longrightarrow> t \\<subseteq> s \\<longrightarrow> (\\<Sum>v\\<in>t. u v *s v) = 0 \\<longrightarrow> v \\<in> t \\<longrightarrow> u v = 0)\"\n  unfolding dependent_explicit by auto\n\nlemma independentD: \"independent s \\<Longrightarrow> finite t \\<Longrightarrow> t \\<subseteq> s \\<Longrightarrow> (\\<Sum>v\\<in>t. u v *s v) = 0 \\<Longrightarrow> v \\<in> t \\<Longrightarrow> u v = 0\"\n  by (simp add: independent_explicit_module)\n\nlemma independent_Union_directed:\n  assumes directed: \"\\<And>c d. c \\<in> C \\<Longrightarrow> d \\<in> C \\<Longrightarrow> c \\<subseteq> d \\<or> d \\<subseteq> c\"\n  assumes indep: \"\\<And>c. c \\<in> C \\<Longrightarrow> independent c\"\n  shows \"independent (\\<Union>C)\"\nproof\n  assume \"dependent (\\<Union>C)\"\n  then obtain u v S where S: \"finite S\" \"S \\<subseteq> \\<Union>C\" \"v \\<in> S\" \"u v \\<noteq> 0\" \"(\\<Sum>v\\<in>S. u v *s v) = 0\"\n    by (auto simp: dependent_explicit)\n\n  have \"S \\<noteq> {}\"\n    using \\<open>v \\<in> S\\<close> by auto\n  have \"\\<exists>c\\<in>C. S \\<subseteq> c\"\n    using \\<open>finite S\\<close> \\<open>S \\<noteq> {}\\<close> \\<open>S \\<subseteq> \\<Union>C\\<close>\n  proof (induction rule: finite_ne_induct)\n    case (insert i I)\n    then obtain c d where cd: \"c \\<in> C\" \"d \\<in> C\" and iI: \"I \\<subseteq> c\" \"i \\<in> d\"\n      by blast\n    from directed[OF cd] cd have \"c \\<union> d \\<in> C\"\n      by (auto simp: sup.absorb1 sup.absorb2)\n    with iI show ?case\n      by (intro bexI[of _ \"c \\<union> d\"]) auto\n  qed auto\n  then obtain c where \"c \\<in> C\" \"S \\<subseteq> c\"\n    by auto\n  have \"dependent c\"\n    unfolding dependent_explicit\n    by (intro exI[of _ S] exI[of _ u] bexI[of _ v] conjI) fact+\n  with indep[OF \\<open>c \\<in> C\\<close>] show False\n    by auto\nqed\n\nlemma dependent_finite:\n  assumes \"finite S\"\n  shows \"dependent S \\<longleftrightarrow> (\\<exists>u. (\\<exists>v \\<in> S. u v \\<noteq> 0) \\<and> (\\<Sum>v\\<in>S. u v *s v) = 0)\"\n    (is \"?lhs = ?rhs\")\nproof\n  assume ?lhs\n  then obtain T u v\n    where \"finite T\" \"T \\<subseteq> S\" \"v\\<in>T\" \"u v \\<noteq> 0\" \"(\\<Sum>v\\<in>T. u v *s v) = 0\"\n    by (force simp: dependent_explicit)\n  with assms show ?rhs\n    apply (rule_tac x=\"\\<lambda>v. if v \\<in> T then u v else 0\" in exI)\n    apply (auto simp: sum.mono_neutral_right)\n    done\nnext\n  assume ?rhs  with assms show ?lhs\n    by (fastforce simp add: dependent_explicit)\nqed\n\nlemma dependent_alt:\n  \"dependent B \\<longleftrightarrow>\n    (\\<exists>X. finite {x. X x \\<noteq> 0} \\<and> {x. X x \\<noteq> 0} \\<subseteq> B \\<and> (\\<Sum>x|X x \\<noteq> 0. X x *s x) = 0 \\<and> (\\<exists>x. X x \\<noteq> 0))\"\n  unfolding dependent_explicit\n  apply safe\n  subgoal for S u v\n    apply (intro exI[of _ \"\\<lambda>x. if x \\<in> S then u x else 0\"])\n    apply (subst sum.mono_neutral_cong_left[where T=S])\n    apply (auto intro!: sum.mono_neutral_cong_right cong: rev_conj_cong)\n    done\n  apply auto\n  done\n\nlemma independent_alt:\n  \"independent B \\<longleftrightarrow>\n    (\\<forall>X. finite {x. X x \\<noteq> 0} \\<longrightarrow> {x. X x \\<noteq> 0} \\<subseteq> B \\<longrightarrow> (\\<Sum>x|X x \\<noteq> 0. X x *s x) = 0 \\<longrightarrow> (\\<forall>x. X x = 0))\"\n  unfolding dependent_alt by auto\n\nlemma independentD_alt:\n  \"independent B \\<Longrightarrow> finite {x. X x \\<noteq> 0} \\<Longrightarrow> {x. X x \\<noteq> 0} \\<subseteq> B \\<Longrightarrow> (\\<Sum>x|X x \\<noteq> 0. X x *s x) = 0 \\<Longrightarrow> X x = 0\"\n  unfolding independent_alt by blast\n\nlemma independentD_unique:\n  assumes B: \"independent B\"\n    and X: \"finite {x. X x \\<noteq> 0}\" \"{x. X x \\<noteq> 0} \\<subseteq> B\"\n    and Y: \"finite {x. Y x \\<noteq> 0}\" \"{x. Y x \\<noteq> 0} \\<subseteq> B\"\n    and \"(\\<Sum>x | X x \\<noteq> 0. X x *s x) = (\\<Sum>x| Y x \\<noteq> 0. Y x *s x)\"\n  shows \"X = Y\"\nproof -\n  have \"X x - Y x = 0\" for x\n    using B\n  proof (rule independentD_alt)\n    have \"{x. X x - Y x \\<noteq> 0} \\<subseteq> {x. X x \\<noteq> 0} \\<union> {x. Y x \\<noteq> 0}\"\n      by auto\n    then show \"finite {x. X x - Y x \\<noteq> 0}\" \"{x. X x - Y x \\<noteq> 0} \\<subseteq> B\"\n      using X Y by (auto dest: finite_subset)\n    then have \"(\\<Sum>x | X x - Y x \\<noteq> 0. (X x - Y x) *s x) = (\\<Sum>v\\<in>{S. X S \\<noteq> 0} \\<union> {S. Y S \\<noteq> 0}. (X v - Y v) *s v)\"\n      using X Y by (intro sum.mono_neutral_cong_left) auto\n    also have \"\\<dots> = (\\<Sum>v\\<in>{S. X S \\<noteq> 0} \\<union> {S. Y S \\<noteq> 0}. X v *s v) - (\\<Sum>v\\<in>{S. X S \\<noteq> 0} \\<union> {S. Y S \\<noteq> 0}. Y v *s v)\"\n      by (simp add: scale_left_diff_distrib sum_subtractf assms)\n    also have \"(\\<Sum>v\\<in>{S. X S \\<noteq> 0} \\<union> {S. Y S \\<noteq> 0}. X v *s v) = (\\<Sum>v\\<in>{S. X S \\<noteq> 0}. X v *s v)\"\n      using X Y by (intro sum.mono_neutral_cong_right) auto\n    also have \"(\\<Sum>v\\<in>{S. X S \\<noteq> 0} \\<union> {S. Y S \\<noteq> 0}. Y v *s v) = (\\<Sum>v\\<in>{S. Y S \\<noteq> 0}. Y v *s v)\"\n      using X Y by (intro sum.mono_neutral_cong_right) auto\n    finally show \"(\\<Sum>x | X x - Y x \\<noteq> 0. (X x - Y x) *s x) = 0\"\n      using assms by simp\n  qed\n  then show ?thesis\n    by auto\nqed\n\n\nsection \\<open>Representation of a vector on a specific basis\\<close>\n\ndefinition representation :: \"'b set \\<Rightarrow> 'b \\<Rightarrow> 'b \\<Rightarrow> 'a\"\n  where \"representation basis v =\n    (if independent basis \\<and> v \\<in> span basis then\n      SOME f. (\\<forall>v. f v \\<noteq> 0 \\<longrightarrow> v \\<in> basis) \\<and> finite {v. f v \\<noteq> 0} \\<and> (\\<Sum>v\\<in>{v. f v \\<noteq> 0}. f v *s v) = v\n    else (\\<lambda>b. 0))\"\n\nlemma unique_representation:\n  assumes basis: \"independent basis\"\n    and in_basis: \"\\<And>v. f v \\<noteq> 0 \\<Longrightarrow> v \\<in> basis\" \"\\<And>v. g v \\<noteq> 0 \\<Longrightarrow> v \\<in> basis\"\n    and [simp]: \"finite {v. f v \\<noteq> 0}\" \"finite {v. g v \\<noteq> 0}\"\n    and eq: \"(\\<Sum>v\\<in>{v. f v \\<noteq> 0}. f v *s v) = (\\<Sum>v\\<in>{v. g v \\<noteq> 0}. g v *s v)\"\n  shows \"f = g\"\nproof (rule ext, rule ccontr)\n  fix v assume ne: \"f v \\<noteq> g v\"\n  have \"dependent basis\"\n    unfolding dependent_explicit\n  proof (intro exI conjI)\n    have *: \"{v. f v - g v \\<noteq> 0} \\<subseteq> {v. f v \\<noteq> 0} \\<union> {v. g v \\<noteq> 0}\"\n      by auto\n    show \"finite {v. f v - g v \\<noteq> 0}\"\n      by (rule finite_subset[OF *]) simp\n    show \"\\<exists>v\\<in>{v. f v - g v \\<noteq> 0}. f v - g v \\<noteq> 0\"\n      by (rule bexI[of _ v]) (auto simp: ne)\n    have \"(\\<Sum>v | f v - g v \\<noteq> 0. (f v - g v) *s v) = \n        (\\<Sum>v\\<in>{v. f v \\<noteq> 0} \\<union> {v. g v \\<noteq> 0}. (f v - g v) *s v)\"\n      by (intro sum.mono_neutral_cong_left *) auto\n    also have \"... =\n        (\\<Sum>v\\<in>{v. f v \\<noteq> 0} \\<union> {v. g v \\<noteq> 0}. f v *s v) - (\\<Sum>v\\<in>{v. f v \\<noteq> 0} \\<union> {v. g v \\<noteq> 0}. g v *s v)\"\n      by (simp add: algebra_simps sum_subtractf)\n    also have \"... = (\\<Sum>v | f v \\<noteq> 0. f v *s v) - (\\<Sum>v | g v \\<noteq> 0. g v *s v)\"\n      by (intro arg_cong2[where f= \"(-)\"] sum.mono_neutral_cong_right) auto\n    finally show \"(\\<Sum>v | f v - g v \\<noteq> 0. (f v - g v) *s v) = 0\"\n      by (simp add: eq)\n    show \"{v. f v - g v \\<noteq> 0} \\<subseteq> basis\"\n      using in_basis * by auto\n  qed\n  with basis show False by auto\nqed\n\nlemma\n  shows representation_ne_zero: \"\\<And>b. representation basis v b \\<noteq> 0 \\<Longrightarrow> b \\<in> basis\"\n    and finite_representation: \"finite {b. representation basis v b \\<noteq> 0}\"\n    and sum_nonzero_representation_eq:\n      \"independent basis \\<Longrightarrow> v \\<in> span basis \\<Longrightarrow> (\\<Sum>b | representation basis v b \\<noteq> 0. representation basis v b *s b) = v\"\nproof -\n  { assume basis: \"independent basis\" and v: \"v \\<in> span basis\"\n    define p where \"p f \\<longleftrightarrow>\n      (\\<forall>v. f v \\<noteq> 0 \\<longrightarrow> v \\<in> basis) \\<and> finite {v. f v \\<noteq> 0} \\<and> (\\<Sum>v\\<in>{v. f v \\<noteq> 0}. f v *s v) = v\" for f\n    obtain t r where *: \"finite t\" \"t \\<subseteq> basis\" \"(\\<Sum>b\\<in>t. r b *s b) = v\"\n      using \\<open>v \\<in> span basis\\<close> by (auto simp: span_explicit)\n    define f where \"f b = (if b \\<in> t then r b else 0)\" for b\n    have \"p f\"\n      using * by (auto simp: p_def f_def intro!: sum.mono_neutral_cong_left)\n    have *: \"representation basis v = Eps p\" by (simp add: p_def[abs_def] representation_def basis v)\n    from someI[of p f, OF \\<open>p f\\<close>] have \"p (representation basis v)\"\n      unfolding * . }\n  note * = this\n\n  show \"representation basis v b \\<noteq> 0 \\<Longrightarrow> b \\<in> basis\" for b\n    using * by (cases \"independent basis \\<and> v \\<in> span basis\") (auto simp: representation_def)\n\n  show \"finite {b. representation basis v b \\<noteq> 0}\"\n    using * by (cases \"independent basis \\<and> v \\<in> span basis\") (auto simp: representation_def)\n\n  show \"independent basis \\<Longrightarrow> v \\<in> span basis \\<Longrightarrow> (\\<Sum>b | representation basis v b \\<noteq> 0. representation basis v b *s b) = v\"\n    using * by auto\nqed\n\nlemma sum_representation_eq:\n  \"(\\<Sum>b\\<in>B. representation basis v b *s b) = v\"\n  if \"independent basis\" \"v \\<in> span basis\" \"finite B\" \"basis \\<subseteq> B\"\nproof -\n  have \"(\\<Sum>b\\<in>B. representation basis v b *s b) =\n      (\\<Sum>b | representation basis v b \\<noteq> 0. representation basis v b *s b)\"\n    apply (rule sum.mono_neutral_cong)\n        apply (rule finite_representation)\n       apply fact\n    subgoal for b\n      using that representation_ne_zero[of basis v b]\n      by auto\n    subgoal by auto\n    subgoal by simp\n    done\n  also have \"\\<dots> = v\"\n    by (rule sum_nonzero_representation_eq; fact)\n  finally show ?thesis .\nqed\n\nlemma representation_eqI:\n  assumes basis: \"independent basis\" and b: \"v \\<in> span basis\"\n    and ne_zero: \"\\<And>b. f b \\<noteq> 0 \\<Longrightarrow> b \\<in> basis\"\n    and finite: \"finite {b. f b \\<noteq> 0}\"\n    and eq: \"(\\<Sum>b | f b \\<noteq> 0. f b *s b) = v\"\n  shows \"representation basis v = f\"\n  by (rule unique_representation[OF basis])\n     (auto simp: representation_ne_zero finite_representation\n       sum_nonzero_representation_eq[OF basis b] ne_zero finite eq)\n\nlemma representation_basis:\n  assumes basis: \"independent basis\" and b: \"b \\<in> basis\"\n  shows \"representation basis b = (\\<lambda>v. if v = b then 1 else 0)\"\nproof (rule unique_representation[OF basis])\n  show \"representation basis b v \\<noteq> 0 \\<Longrightarrow> v \\<in> basis\" for v\n    using representation_ne_zero .\n  show \"finite {v. representation basis b v \\<noteq> 0}\"\n    using finite_representation .\n  show \"(if v = b then 1 else 0) \\<noteq> 0 \\<Longrightarrow> v \\<in> basis\" for v\n    by (cases \"v = b\") (auto simp: b)\n  have *: \"{v. (if v = b then 1 else 0 :: 'a) \\<noteq> 0} = {b}\"\n    by auto\n  show \"finite {v. (if v = b then 1 else 0) \\<noteq> 0}\" unfolding * by auto\n  show \"(\\<Sum>v | representation basis b v \\<noteq> 0. representation basis b v *s v) =\n    (\\<Sum>v | (if v = b then 1 else 0::'a) \\<noteq> 0. (if v = b then 1 else 0) *s v)\"\n    unfolding * sum_nonzero_representation_eq[OF basis span_base[OF b]] by auto\nqed\n\nlemma representation_zero: \"representation basis 0 = (\\<lambda>b. 0)\"\nproof cases\n  assume basis: \"independent basis\" show ?thesis\n    by (rule representation_eqI[OF basis span_zero]) auto\nqed (simp add: representation_def)\n\nlemma representation_diff:\n  assumes basis: \"independent basis\" and v: \"v \\<in> span basis\" and u: \"u \\<in> span basis\"\n  shows \"representation basis (u - v) = (\\<lambda>b. representation basis u b - representation basis v b)\"\nproof (rule representation_eqI[OF basis span_diff[OF u v]])\n  let ?R = \"representation basis\"\n  note finite_representation[simp] u[simp] v[simp]\n  have *: \"{b. ?R u b - ?R v b \\<noteq> 0} \\<subseteq> {b. ?R u b \\<noteq> 0} \\<union> {b. ?R v b \\<noteq> 0}\"\n    by auto\n  then show \"?R u b - ?R v b \\<noteq> 0 \\<Longrightarrow> b \\<in> basis\" for b\n    by (auto dest: representation_ne_zero)\n  show \"finite {b. ?R u b - ?R v b \\<noteq> 0}\"\n    by (intro finite_subset[OF *]) simp_all\n  have \"(\\<Sum>b | ?R u b - ?R v b \\<noteq> 0. (?R u b - ?R v b) *s b) =\n      (\\<Sum>b\\<in>{b. ?R u b \\<noteq> 0} \\<union> {b. ?R v b \\<noteq> 0}. (?R u b - ?R v b) *s b)\"\n    by (intro sum.mono_neutral_cong_left *) auto\n  also have \"... =\n      (\\<Sum>b\\<in>{b. ?R u b \\<noteq> 0} \\<union> {b. ?R v b \\<noteq> 0}. ?R u b *s b) - (\\<Sum>b\\<in>{b. ?R u b \\<noteq> 0} \\<union> {b. ?R v b \\<noteq> 0}. ?R v b *s b)\"\n    by (simp add: algebra_simps sum_subtractf)\n  also have \"... = (\\<Sum>b | ?R u b \\<noteq> 0. ?R u b *s b) - (\\<Sum>b | ?R v b \\<noteq> 0. ?R v b *s b)\"\n    by (intro arg_cong2[where f= \"(-)\"] sum.mono_neutral_cong_right) auto\n  finally show \"(\\<Sum>b | ?R u b - ?R v b \\<noteq> 0. (?R u b - ?R v b) *s b) = u - v\"\n    by (simp add: sum_nonzero_representation_eq[OF basis])\nqed\n\nlemma representation_neg:\n  \"independent basis \\<Longrightarrow> v \\<in> span basis \\<Longrightarrow> representation basis (- v) = (\\<lambda>b. - representation basis v b)\"\n  using representation_diff[of basis v 0] by (simp add: representation_zero span_zero)\n\nlemma representation_add:\n  \"independent basis \\<Longrightarrow> v \\<in> span basis \\<Longrightarrow> u \\<in> span basis \\<Longrightarrow>\n    representation basis (u + v) = (\\<lambda>b. representation basis u b + representation basis v b)\"\n  using representation_diff[of basis \"-v\" u] by (simp add: representation_neg representation_diff span_neg)\n\nlemma representation_sum:\n  \"independent basis \\<Longrightarrow> (\\<And>i. i \\<in> I \\<Longrightarrow> v i \\<in> span basis) \\<Longrightarrow>\n    representation basis (sum v I) = (\\<lambda>b. \\<Sum>i\\<in>I. representation basis (v i) b)\"\n  by (induction I rule: infinite_finite_induct)\n     (auto simp: representation_zero representation_add span_sum)\n\nlemma representation_scale:\n  assumes basis: \"independent basis\" and v: \"v \\<in> span basis\"\n  shows \"representation basis (r *s v) = (\\<lambda>b. r * representation basis v b)\"\nproof (rule representation_eqI[OF basis span_scale[OF v]])\n  let ?R = \"representation basis\"\n  note finite_representation[simp] v[simp]\n  have *: \"{b. r * ?R v b \\<noteq> 0} \\<subseteq> {b. ?R v b \\<noteq> 0}\"\n    by auto\n  then show \"r * representation basis v b \\<noteq> 0 \\<Longrightarrow> b \\<in> basis\" for b\n    using representation_ne_zero by auto\n  show \"finite {b. r * ?R v b \\<noteq> 0}\"\n    by (intro finite_subset[OF *]) simp_all\n  have \"(\\<Sum>b | r * ?R v b \\<noteq> 0. (r * ?R v b) *s b) = (\\<Sum>b\\<in>{b. ?R v b \\<noteq> 0}. (r * ?R v b) *s b)\"\n    by (intro sum.mono_neutral_cong_left *) auto\n  also have \"... = r *s (\\<Sum>b | ?R v b \\<noteq> 0. ?R v b *s b)\"\n    by (simp add: scale_scale[symmetric] scale_sum_right del: scale_scale)\n  finally show \"(\\<Sum>b | r * ?R v b \\<noteq> 0. (r * ?R v b) *s b) = r *s v\"\n    by (simp add: sum_nonzero_representation_eq[OF basis])\nqed\n\nlemma representation_extend:\n  assumes basis: \"independent basis\" and v: \"v \\<in> span basis'\" and basis': \"basis' \\<subseteq> basis\"\n  shows \"representation basis v = representation basis' v\"\nproof (rule representation_eqI[OF basis])\n  show v': \"v \\<in> span basis\" using span_mono[OF basis'] v by auto\n  have *: \"independent basis'\" using basis' basis by (auto intro: dependent_mono)\n  show \"representation basis' v b \\<noteq> 0 \\<Longrightarrow> b \\<in> basis\" for b\n    using representation_ne_zero basis' by auto\n  show \"finite {b. representation basis' v b \\<noteq> 0}\"\n    using finite_representation .\n  show \"(\\<Sum>b | representation basis' v b \\<noteq> 0. representation basis' v b *s b) = v\"\n    using sum_nonzero_representation_eq[OF * v] .\nqed\n\ntext \\<open>The set \\<open>B\\<close> is the maximal independent set for \\<open>span B\\<close>, or \\<open>A\\<close> is the minimal spanning set\\<close>\nlemma spanning_subset_independent:\n  assumes BA: \"B \\<subseteq> A\"\n    and iA: \"independent A\"\n    and AsB: \"A \\<subseteq> span B\"\n  shows \"A = B\"\nproof (intro antisym[OF _ BA] subsetI)\n  have iB: \"independent B\" using independent_mono [OF iA BA] .\n  fix v assume \"v \\<in> A\"\n  with AsB have \"v \\<in> span B\" by auto\n  let ?RB = \"representation B v\" and ?RA = \"representation A v\"\n  have \"?RB v = 1\"\n    unfolding representation_extend[OF iA \\<open>v \\<in> span B\\<close> BA, symmetric] representation_basis[OF iA \\<open>v \\<in> A\\<close>] by simp\n  then show \"v \\<in> B\"\n    using representation_ne_zero[of B v v] by auto\nqed\n\nend\n\n(* We need to introduce more specific modules, where the ring structure gets more and more finer,\n  i.e. Bezout rings & domains, division rings, fields *)\n\ntext \\<open>A linear function is a mapping between two modules over the same ring.\\<close>\n\nlocale module_hom = m1: module s1 + m2: module s2\n    for s1 :: \"'a::comm_ring_1 \\<Rightarrow> 'b::ab_group_add \\<Rightarrow> 'b\" (infixr \"*a\" 75)\n    and s2 :: \"'a::comm_ring_1 \\<Rightarrow> 'c::ab_group_add \\<Rightarrow> 'c\" (infixr \"*b\" 75) +\n  fixes f :: \"'b \\<Rightarrow> 'c\"\n  assumes add: \"f (b1 + b2) = f b1 + f b2\"\n    and scale: \"f (r *a b) = r *b f b\"\nbegin\n\nlemma zero[simp]: \"f 0 = 0\"\n  using scale[of 0 0] by simp\n\nlemma neg: \"f (- x) = - f x\"\n  using scale [where r=\"-1\"] by (metis add add_eq_0_iff zero)\n\nlemma diff: \"f (x - y) = f x - f y\"\n  by (metis diff_conv_add_uminus add neg)\n\nlemma sum: \"f (sum g S) = (\\<Sum>a\\<in>S. f (g a))\"\nproof (induct S rule: infinite_finite_induct)\n  case (insert x F)\n  have \"f (sum g (insert x F)) = f (g x + sum g F)\"\n    using insert.hyps by simp\n  also have \"\\<dots> = f (g x) + f (sum g F)\"\n    using add by simp\n  also have \"\\<dots> = (\\<Sum>a\\<in>insert x F. f (g a))\"\n    using insert.hyps by simp\n  finally show ?case .\nqed simp_all\n\nlemma inj_on_iff_eq_0:\n  assumes s: \"m1.subspace s\"\n  shows \"inj_on f s \\<longleftrightarrow> (\\<forall>x\\<in>s. f x = 0 \\<longrightarrow> x = 0)\"\nproof -\n  have \"inj_on f s \\<longleftrightarrow> (\\<forall>x\\<in>s. \\<forall>y\\<in>s. f x - f y = 0 \\<longrightarrow> x - y = 0)\"\n    by (simp add: inj_on_def)\n  also have \"\\<dots> \\<longleftrightarrow> (\\<forall>x\\<in>s. \\<forall>y\\<in>s. f (x - y) = 0 \\<longrightarrow> x - y = 0)\"\n    by (simp add: diff)\n  also have \"\\<dots> \\<longleftrightarrow> (\\<forall>x\\<in>s. f x = 0 \\<longrightarrow> x = 0)\" (is \"?l = ?r\")(* TODO: sledgehammer! *)\n  proof safe\n    fix x assume ?l assume \"x \\<in> s\" \"f x = 0\" with \\<open>?l\\<close>[rule_format, of x 0] s show \"x = 0\"\n      by (auto simp: m1.subspace_0)\n  next\n    fix x y assume ?r assume \"x \\<in> s\" \"y \\<in> s\" \"f (x - y) = 0\"\n    with \\<open>?r\\<close>[rule_format, of \"x - y\"] s\n    show \"x - y = 0\"\n      by (auto simp: m1.subspace_diff)\n  qed\n  finally show ?thesis\n    by auto\nqed\n\nlemma inj_iff_eq_0: \"inj f = (\\<forall>x. f x = 0 \\<longrightarrow> x = 0)\"\n  by (rule inj_on_iff_eq_0[OF m1.subspace_UNIV, unfolded ball_UNIV])\n\nlemma subspace_image: assumes S: \"m1.subspace S\" shows \"m2.subspace (f ` S)\"\n  unfolding m2.subspace_def\nproof safe\n  show \"0 \\<in> f ` S\"\n    by (rule image_eqI[of _ _ 0]) (auto simp: S m1.subspace_0)\n  show \"x \\<in> S \\<Longrightarrow> y \\<in> S \\<Longrightarrow> f x + f y \\<in> f ` S\" for x y\n    by (rule image_eqI[of _ _ \"x + y\"]) (auto simp: S m1.subspace_add add)\n  show \"x \\<in> S \\<Longrightarrow> r *b f x \\<in> f ` S\" for r x\n    by (rule image_eqI[of _ _ \"r *a x\"]) (auto simp: S m1.subspace_scale scale)\nqed\n\nlemma subspace_vimage: \"m2.subspace S \\<Longrightarrow> m1.subspace (f -` S)\"\n  by (simp add: vimage_def add scale m1.subspace_def m2.subspace_0 m2.subspace_add m2.subspace_scale)\n\nlemma subspace_kernel: \"m1.subspace {x. f x = 0}\"\n  using subspace_vimage[OF m2.subspace_single_0] by (simp add: vimage_def)\n\nlemma span_image: \"m2.span (f ` S) = f ` (m1.span S)\"\nproof (rule m2.span_unique)\n  show \"f ` S \\<subseteq> f ` m1.span S\"\n    by (rule image_mono, rule m1.span_superset)\n  show \"m2.subspace (f ` m1.span S)\"\n    using m1.subspace_span by (rule subspace_image)\nnext\n  fix T assume \"f ` S \\<subseteq> T\" and \"m2.subspace T\" then show \"f ` m1.span S \\<subseteq> T\"\n    unfolding image_subset_iff_subset_vimage by (metis subspace_vimage m1.span_minimal)\nqed\n\nlemma dependent_inj_imageD:\n  assumes d: \"m2.dependent (f ` s)\" and i: \"inj_on f (m1.span s)\"\n  shows \"m1.dependent s\"\nproof -\n  have [intro]: \"inj_on f s\"\n    using \\<open>inj_on f (m1.span s)\\<close> m1.span_superset by (rule inj_on_subset)\n  from d obtain s' r v where *: \"finite s'\" \"s' \\<subseteq> s\" \"(\\<Sum>v\\<in>f ` s'. r v *b v) = 0\" \"v \\<in> s'\" \"r (f v) \\<noteq> 0\"\n    by (auto simp: m2.dependent_explicit subset_image_iff dest!: finite_imageD intro: inj_on_subset)\n  have \"f (\\<Sum>v\\<in>s'. r (f v) *a v) = (\\<Sum>v\\<in>s'. r (f v) *b f v)\"\n    by (simp add: sum scale)\n  also have \"... = (\\<Sum>v\\<in>f ` s'. r v *b v)\"\n    using \\<open>s' \\<subseteq> s\\<close> by (subst sum.reindex) (auto dest!: finite_imageD intro: inj_on_subset)\n  finally have \"f (\\<Sum>v\\<in>s'. r (f v) *a v) = 0\"\n    by (simp add: *)\n  with \\<open>s' \\<subseteq> s\\<close> have \"(\\<Sum>v\\<in>s'. r (f v) *a v) = 0\"\n    by (intro inj_onD[OF i] m1.span_zero m1.span_sum m1.span_scale) (auto intro: m1.span_base)\n  then show \"m1.dependent s\"\n    using \\<open>finite s'\\<close> \\<open>s' \\<subseteq> s\\<close> \\<open>v \\<in> s'\\<close> \\<open>r (f v) \\<noteq> 0\\<close> by (force simp add: m1.dependent_explicit)\nqed\n\nlemma eq_0_on_span:\n  assumes f0: \"\\<And>x. x \\<in> b \\<Longrightarrow> f x = 0\" and x: \"x \\<in> m1.span b\" shows \"f x = 0\"\n  using m1.span_induct[OF x subspace_kernel] f0 by simp\n\nlemma independent_injective_image: \"m1.independent s \\<Longrightarrow> inj_on f (m1.span s) \\<Longrightarrow> m2.independent (f ` s)\"\n  using dependent_inj_imageD[of s] by auto\n\nlemma inj_on_span_independent_image:\n  assumes ifB: \"m2.independent (f ` B)\" and f: \"inj_on f B\" shows \"inj_on f (m1.span B)\"\n  unfolding inj_on_iff_eq_0[OF m1.subspace_span] unfolding m1.span_explicit'\nproof safe\n  fix r assume fr: \"finite {v. r v \\<noteq> 0}\" and r: \"\\<forall>v. r v \\<noteq> 0 \\<longrightarrow> v \\<in> B\"\n    and eq0: \"f (\\<Sum>v | r v \\<noteq> 0. r v *a v) = 0\"\n  have \"0 = (\\<Sum>v | r v \\<noteq> 0. r v *b f v)\"\n    using eq0 by (simp add: sum scale)\n  also have \"... = (\\<Sum>v\\<in>f ` {v. r v \\<noteq> 0}. r (the_inv_into B f v) *b v)\"\n    using r by (subst sum.reindex) (auto simp: the_inv_into_f_f[OF f] intro!: inj_on_subset[OF f] sum.cong)\n  finally have \"r v \\<noteq> 0 \\<Longrightarrow> r (the_inv_into B f (f v)) = 0\" for v\n    using fr r ifB[unfolded m2.independent_explicit_module, rule_format,\n        of \"f ` {v. r v \\<noteq> 0}\" \"\\<lambda>v. r (the_inv_into B f v)\"]\n    by auto\n  then have \"r v = 0\" for v\n    using the_inv_into_f_f[OF f] r by auto\n  then show \"(\\<Sum>v | r v \\<noteq> 0. r v *a v) = 0\" by auto\nqed\n\nlemma inj_on_span_iff_independent_image: \"m2.independent (f ` B) \\<Longrightarrow> inj_on f (m1.span B) \\<longleftrightarrow> inj_on f B\"\n  using inj_on_span_independent_image[of B] inj_on_subset[OF _ m1.span_superset, of f B] by auto\n\nlemma subspace_linear_preimage: \"m2.subspace S \\<Longrightarrow> m1.subspace {x. f x \\<in> S}\"\n  by (simp add: add scale m1.subspace_def m2.subspace_def)\n\nlemma spans_image: \"V \\<subseteq> m1.span B \\<Longrightarrow> f ` V \\<subseteq> m2.span (f ` B)\"\n  by (metis image_mono span_image)\n\ntext \\<open>Relation between bases and injectivity/surjectivity of map.\\<close>\n\nlemma spanning_surjective_image:\n  assumes us: \"UNIV \\<subseteq> m1.span S\"\n    and sf: \"surj f\"\n  shows \"UNIV \\<subseteq> m2.span (f ` S)\"\nproof -\n  have \"UNIV \\<subseteq> f ` UNIV\"\n    using sf by (auto simp add: surj_def)\n  also have \" \\<dots> \\<subseteq> m2.span (f ` S)\"\n    using spans_image[OF us] .\n  finally show ?thesis .\nqed\n\nlemmas independent_inj_on_image = independent_injective_image\n\nlemma independent_inj_image:\n  \"m1.independent S \\<Longrightarrow> inj f \\<Longrightarrow> m2.independent (f ` S)\"\n  using independent_inj_on_image[of S] by (auto simp: subset_inj_on)\n\nend\n\nlemma module_hom_iff:\n  \"module_hom s1 s2  f \\<longleftrightarrow>\n    module s1 \\<and> module s2 \\<and>\n    (\\<forall>x y. f (x + y) = f x + f y) \\<and> (\\<forall>c x. f (s1 c x) = s2 c (f x))\"\n  by (simp add: module_hom_def module_hom_axioms_def)\n\nlocale module_pair = m1: module s1 + m2: module s2\n  for s1 :: \"'a :: comm_ring_1 \\<Rightarrow> 'b \\<Rightarrow> 'b :: ab_group_add\"\n  and s2 :: \"'a :: comm_ring_1 \\<Rightarrow> 'c \\<Rightarrow> 'c :: ab_group_add\"\nbegin\n\nlemma module_hom_zero: \"module_hom s1 s2 (\\<lambda>x. 0)\"\n  by (simp add: module_hom_iff m1.module_axioms m2.module_axioms)\n\nlemma module_hom_add: \"module_hom s1 s2 f \\<Longrightarrow> module_hom s1 s2 g \\<Longrightarrow> module_hom s1 s2 (\\<lambda>x. f x + g x)\"\n  by (simp add: module_hom_iff module.scale_right_distrib)\n\nlemma module_hom_sub: \"module_hom s1 s2 f \\<Longrightarrow> module_hom s1 s2 g \\<Longrightarrow> module_hom s1 s2 (\\<lambda>x. f x - g x)\"\n  by (simp add: module_hom_iff module.scale_right_diff_distrib)\n\nlemma module_hom_neg: \"module_hom s1 s2 f \\<Longrightarrow> module_hom s1 s2 (\\<lambda>x. - f x)\"\n  by (simp add: module_hom_iff module.scale_minus_right)\n\nlemma module_hom_scale: \"module_hom s1 s2 f \\<Longrightarrow> module_hom s1 s2 (\\<lambda>x. s2 c (f x))\"\n  by (simp add: module_hom_iff module.scale_scale module.scale_right_distrib ac_simps)\n\nlemma module_hom_compose_scale:\n  \"module_hom s1 s2 (\\<lambda>x. s2 (f x) (c))\"\n  if \"module_hom s1 (*) f\"\nproof -\n  interpret mh: module_hom s1 \"(*)\" f by fact\n  show ?thesis\n    by unfold_locales (simp_all add: mh.add mh.scale m2.scale_left_distrib)\nqed\n\nlemma bij_module_hom_imp_inv_module_hom: \"module_hom scale1 scale2 f \\<Longrightarrow> bij f \\<Longrightarrow>\n  module_hom scale2 scale1 (inv f)\"\n  by (auto simp: module_hom_iff bij_is_surj bij_is_inj surj_f_inv_f\n      intro!: Hilbert_Choice.inv_f_eq)\n\nlemma module_hom_sum: \"(\\<And>i. i \\<in> I \\<Longrightarrow> module_hom s1 s2 (f i)) \\<Longrightarrow> (I = {} \\<Longrightarrow> module s1 \\<and> module s2) \\<Longrightarrow> module_hom s1 s2 (\\<lambda>x. \\<Sum>i\\<in>I. f i x)\"\n  apply (induction I rule: infinite_finite_induct)\n  apply (auto intro!: module_hom_zero module_hom_add)\n  using m1.module_axioms m2.module_axioms by blast\n\nlemma module_hom_eq_on_span: \"f x = g x\"\n  if \"module_hom s1 s2 f\" \"module_hom s1 s2 g\"\n  and \"(\\<And>x. x \\<in> B \\<Longrightarrow> f x = g x)\" \"x \\<in> m1.span B\"\nproof -\n  interpret module_hom s1 s2 \"\\<lambda>x. f x - g x\"\n    by (rule module_hom_sub that)+\n  from eq_0_on_span[OF _ that(4)] that(3) show ?thesis by auto\nqed\n\nend\n\ncontext module begin\n\nlemma module_hom_scale_self[simp]:\n  \"module_hom scale scale (\\<lambda>x. scale c x)\"\n  using module_axioms module_hom_iff scale_left_commute scale_right_distrib by blast\n\nlemma module_hom_scale_left[simp]:\n  \"module_hom (*) scale (\\<lambda>r. scale r x)\"\n  by unfold_locales (auto simp: algebra_simps)\n\nlemma module_hom_id: \"module_hom scale scale id\"\n  by (simp add: module_hom_iff module_axioms)\n\nlemma module_hom_ident: \"module_hom scale scale (\\<lambda>x. x)\"\n  by (simp add: module_hom_iff module_axioms)\n\nlemma module_hom_uminus: \"module_hom scale scale uminus\"\n  by (simp add: module_hom_iff module_axioms)\n\nend\n\nlemma module_hom_compose: \"module_hom s1 s2 f \\<Longrightarrow> module_hom s2 s3 g \\<Longrightarrow> module_hom s1 s3 (g o f)\"\n  by (auto simp: module_hom_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/Modules.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951104066293, "lm_q2_score": 0.8705972600147106, "lm_q1q2_score": 0.7346927708598232}}
{"text": "(* Topological Spaces\n   Based on \"A Bridge to Advanced Mathematics\" by Dennis Sentilles\n   Translated to Isar by Michal J Wallace *)\ntheory TopSpace\n  imports Main\nbegin\n\nsection \\<open>axioms\\<close>\n\ntext \\<open>A topological space (X,T) is a pair where X is a set whose elements\nare called the \"points\" of the topological space, and T is a fixed collection of\nsubsets of X called neighborhoods, with the following properties:\\<close>\n\nlocale topspace =\n    fixes X :: \"'a set\"\n    fixes T :: \"('a set) set\"\n    assumes A1 [simp]: \"x\\<in>X \\<equiv> \\<exists>N\\<in>T. x\\<in>N\"\n    assumes A2 [simp]: \"U\\<in>T \\<and> V\\<in>T \\<and> x\\<in>(U\\<inter>V) \\<Longrightarrow> \\<exists>N\\<in>T. x\\<in>N \\<and> N\\<subseteq>(U\\<inter>V)\"\nbegin\n\nsection \\<open>limits, boundaries, and open and closed sets\\<close>\n\n  text \\<open>A set N\\<in>T which contains p\\<in>X is called a neighborhood of p.\\<close>\n\n  definition nhs :: \"'a \\<Rightarrow> ('a set) set\"\n    where [simp]: \"nhs p \\<equiv> {N\\<in>T. p\\<in>N}\"\n\n  text \\<open>If \\<open>A\\<subseteq>X\\<close> in topological space \\<open>(X,T)\\<close>, then \\<open>p\\<in>X\\<close> is called a \\<^bold>\\<open>limit point\\<close>\n    of \\<open>A\\<close> if the intersection of every neighborhood of \\<open>p\\<close> with \\<open>A\\<close> is non-empty.\n    In loose geometrical terms, \\<open>p\\<close> is either a point in \\<open>A\\<close> or as close as possible\n    to \\<open>A\\<close> without actually being in it.\\<close>\n\n  definition limpt :: \"'a set \\<Rightarrow> 'a \\<Rightarrow> bool\" (* def 4.2.1 *)\n    where [simp]: \"limpt A p \\<equiv> A\\<subseteq>X \\<and> p\\<in>X \\<and> (\\<forall>N\\<in>nhs p. (A\\<inter>N) \\<noteq> {})\"\n\n  text \\<open>If \\<open>A\\<subset>X\\<close> in topological space \\<open>(X,T)\\<close>, then \\<open>x\\<in>X\\<close> is called an \\<^bold>\\<open>interior point\\<close>\n    of \\<open>A\\<close> if at least one neighborhood of \\<open>x\\<close> is contained entirely within \\<open>A\\<close>.\\<close>\n\n  definition intpt :: \"'a set \\<Rightarrow> 'a \\<Rightarrow> bool\" (* def 4.2.2 *)\n    where [simp]: \"intpt A p \\<equiv> A\\<subseteq>X \\<and> p\\<in>A \\<and> (\\<exists>N\\<in>nhs p. N\\<subseteq>A)\"\n\n  definition boundpt :: \"'a set \\<Rightarrow> 'a \\<Rightarrow> bool\" (* def 4.2.3 *)\n    where \"boundpt A p \\<equiv> (limpt A p) \\<and> (limpt (X-A) p)\"\n\n  definition \"open\" :: \"'a set \\<Rightarrow> bool\" (* def 4.2.4a *)\n    where \"open A \\<equiv> (\\<forall>p\\<in>A. intpt A p)\"\n\n  definition closed :: \"'a set \\<Rightarrow> bool\" (* def 4.2.4b *)\n    where [simp, intro]: \"closed A \\<longleftrightarrow> open (X-A)\"\n\n  text \\<open>THEOREM 4.2.5: A set \\<open>A\\<in>X\\<close> in a topological space \"\\<open>(X,T)\\<close> is closed\n        iff every limit point of \\<open>A\\<close> belongs to \\<open>A\\<close>. Hence, if \\<open>\\<exists>\\<close> a limit point\n        of \\<open>A\\<close> not in \\<open>A\\<close>, then \\<open>A\\<close> is not closed. Conversely, if \\<open>A\\<close> is not\n        closed, then  \\<open>\\<exists>\\<close> a limit point of \\<open>A\\<close> not in \\<open>A\\<close>.\\<close>\n\n  theorem t425a: assumes \"closed A\" and \"limpt A p\" shows \"p \\<in> A\"\n    proof (rule ccontr)\n      assume \"p\\<notin>A\"\n      with `limpt A p` have \"p\\<in>(X-A)\" by simp\n      moreover from `closed A` have \"open (X-A)\" by simp\n      ultimately have \"intpt (X-A) p\" using open_def by blast\n      \\<comment> \\<open>that is, there's a neighborhood, \\<open>N\\<in>T\\<close> of p such that \\<open>N\\<subseteq>(X-A)\\<close> \\<close>\n      with A2 `p\\<in>(X-A)` obtain N where \"p\\<in>N\" and \"N\\<in>T\" and \"N\\<subseteq>(X-A)\" by auto\n      then have \"N\\<inter>A={}\" by auto   \\<comment> \\<open>which contradicts the definition of a limit point.\\<close>\n      moreover have \"N\\<inter>A\\<noteq>{}\" using `limpt A p` `p\\<in>N` `N\\<in>T` limpt_def by auto\n      ultimately show \"False\" by simp\n    qed\n\n    text \\<open>To prove the converse in Isar, I needed to make use of the following lemma,\n  which says that if some \\<open>x\\<in>X\\<close> is not a limit point of \\<open>A\\<subseteq>X\\<close> then there must be some\n  neighborhood \\<open>N\\<close> of \\<open>x\\<close> that does not intersect \\<open>A\\<close> at all.\\<close>\n  lemma non_limpt_nh:\n    assumes \"A\\<subseteq>X\" \"x\\<in>X\" and \"\\<not>(limpt A x)\"\n    obtains N where \"N\\<in>nhs x\" and \"N\\<inter>A={}\"\n  proof -\n    \\<comment> \"Start with the (negated) definition of \\<open>limpt A x\\<close>\"\n    from limpt_def have \"\\<not>(limpt A x) \\<equiv> \\<not>(A\\<subseteq>X \\<and> x\\<in>X \\<and> (\\<forall>N\\<in>nhs x. (A\\<inter>N) \\<noteq> {}))\" by simp\n    \\<comment> \"Distributing \\<not> over \\<and> gives us three possibilities \\<dots>\"\n    also have \"\\<dots> \\<equiv> \\<not>(A\\<subseteq>X) \\<or> (x\\<notin>X) \\<or> (\\<exists>N\\<in>nhs x. A\\<inter>N={})\" by simp\n    \\<comment> \"\\<dots> But our assumptions rule out the first two.\"\n    finally have \"\\<dots> \\<equiv> \\<exists>N\\<in>nhs x. A\\<inter>N = {}\" using assms by auto\n    with `\\<not>(limpt A x)` obtain N where \"N\\<in>nhs x\" and \"N\\<inter>A={}\" by auto\n    then show ?thesis using that by auto\n  qed\n\n  text \\<open>Now we can prove the second part of theorem 4.2.5: if \\<open>A\\<close> contains all its limit\n        points, then A is closed.\\<close>\n  theorem t425b: assumes a0: \"A\\<subseteq>X\" and a1: \"\\<forall>p. limpt A p \\<longrightarrow> p\\<in>A\" shows \"closed A\"\n    \\<comment> \\<open>Quoting Sentilles here (replacing his syntax with isar's and using my variable names:\\<close>\n    \\<comment> \\<open>\"To show \\<open>A\\<close> is closed, we must argue that \\<open>X-A\\<close> is open.\"\\<close>\n    \\<comment> \\<open>\"That is, that any point of \\<open>X-A\\<close> is an interior point of \\<open>X-A\\<close>.\"\\<close>\n       \\<comment> \\<open>\"Suppose \\<open>x\\<in>X-A\\<close>. Then \\<open>x\\<notin>A\\<close>.\"\\<close>\n       \\<comment> \\<open>\"Since \\<open>A\\<close> contains all its limit points, then \\<open>x\\<close> is not a limit point of \\<open>A\\<close>.\"\\<close>\n       \\<comment> \\<open>\"By [\\<open>limpt_def\\<close>] this means there is a neighborhood \\<open>N\\<in>T\\<close> of \\<open>x\\<close>\n            whose intersection with \\<open>A\\<close> is empty. In other words, \\<open>N\\<subseteq>(X-A)\\<close>.\"\\<close>\n       \\<comment> \\<open>\"But this means \\<open>X-A\\<close> is open by [\\<open>open_def\\<close>].\"\\<close>\n       \\<comment> \\<open>\"This is what we wished to prove.\"\\<close>\n    proof -\n      have \"\\<forall>x\\<in>(X-A). intpt (X-A) x\" proof\n        fix x assume \"x\\<in>(X-A)\" hence \"x\\<notin>A\" by auto\n        have  \"\\<not>(limpt A x)\" using a1 \\<open>x\\<notin>A\\<close> by auto\n        with `x \\<in> X-A` obtain N where \"N\\<in>nhs x\" and \"N\\<inter>A={}\" using a0 non_limpt_nh by blast\n        hence \"N\\<subseteq>X-A\" by auto\n        with `N\\<in>nhs x` show \"intpt (X-A) x\" by auto\n      qed\n      hence \"open (X-A)\" using open_def by simp\n      thus \"closed A\" by simp\n    qed\n\n\n  text \\<open>\\<^bold>\\<open>COROLLARY 4.2.6\\<close>\n      A subset \\<open>A\\<subseteq>X\\<close> of a topological space \\<open>(X,T)\\<close> is closed if \\<open>A\\<close> contains its boundary.\\<close>\n\n  text \\<open>\n    The last theorem shows that if \\<open>A\\<subseteq>X\\<close> contains all its limit points, then it's closed.\n    Can we show that if \\<open>A\\<close> contains all its boundary points, it must contain all\n    its limit points?\n\n    First, many of the limit points are interior points, right? From intpt_def,\n    it seems like all interior points are limit points... right?\n\\<close>\n\n  lemma int_lim:\n    assumes \"A\\<subseteq>X\" \"intpt A p\" shows \"limpt A p\"\n    using assms ball_empty intpt_def by auto\n\n  text \\<open>\n    It seems so. (We won't actually need that lemma, so I'll just trust the proof.\n    Isabelle generated when i typed the word 'try' after the `shows` clause.)\n\n    Anyway, back to the question of whether \\<open>A\\<close> containing its boundary implies\n    that it contains all its limit points.\n\n    Assume \\<open>A\\<subseteq>X\\<close> contains its boundary points, and let \\<open>p\\<close> be a limit point of \\<open>A\\<close>\n       If \\<open>p\\<close> is an interior point, then \\<open>p\\<in>A\\<close>.\n       else if it's a boundary point, then \\<open>p\\<in>A\\<close> by assumption.\n       else ... well, what would that even mean?\n\n    The final case would be a limit point that is neither an interior point\n    nor a boundary point. It's hard for me to imagine such a thing, so maybe no\n    such thing exists.\n\n    If it doesn't exist, then we've covered all our bases, and the corollary\n    can be proven just by formalizing the argument above.\n\n    So... let's try to show that if \\<open>limpt A p \\<Longrightarrow> (intpt A p) \\<or> (boundpt A p)\\<close>.\n    We know all boundary points are limit points by definition, and all interior\n    points are limit points from the lemma above, so really we only need to show\n    that a limit point that isn't one of those two things must be the other.\n\n    Here's the proof I came up with:\n\\<close>\n\n  lemma bnd_ext_lim: assumes \"A\\<subseteq>X\" \"limpt A p\" \"~intpt A p\" shows \"boundpt A p\"\n  proof -\n    from `limpt A p` have \"p\\<in>X\" by simp\n    moreover have \"\\<forall>N\\<in>nhs p. (X-A)\\<inter>N\\<noteq>{}\"\n      proof\n        fix N assume \"N\\<in>nhs p\"\n        from `\\<not>intpt A p` `A\\<subseteq>X` have \"p\\<notin>A \\<or> \\<not>(\\<exists>N\\<in>nhs p. N\\<subseteq>A)\" by auto\n        then consider \"p\\<in>(X-A)\" | \"(\\<forall>N\\<in>nhs p. \\<not>N\\<subseteq>A)\" by auto\n        thus\"(X-A)\\<inter>N\\<noteq>{}\" proof (cases)\n          case 1 then show ?thesis using \\<open>N \\<in> nhs p\\<close> by fastforce\n        next\n          case 2 then have \"\\<not>N\\<subseteq>A\" using \\<open>N \\<in> nhs p\\<close> by blast\n          thus ?thesis using \\<open>N \\<in> nhs p\\<close> by fastforce\n        qed\n     qed\n     moreover from `A\\<subseteq>X` have \"(X-A) \\<subseteq>X\" by auto\n     ultimately have \"limpt (X-A) p\" by simp\n     thus \"boundpt A p\" using `limpt A p` boundpt_def by blast\n   qed\n\n  text \\<open>I'll let Isabelle prove to itself that the two cases are mutually exclusive:\\<close>\n  lemma lim_bnd_xor_int: assumes \"limpt A p\" shows \"(boundpt A p) \\<noteq> (intpt A p)\"\n    using assms bnd_ext_lim boundpt_def by auto\n\n  text \\<open>Now we can show what we really wanted to show:\\<close>\n\n  corollary c426:  (* cor 4.2.6 *)\n    assumes ax: \"A\\<subseteq>X\"\n        and ap: \"\\<forall>p. boundpt A p \\<longrightarrow> p\\<in>A\"\n    shows \"closed A\"\n    proof -\n      have \"\\<And>p. limpt A p \\<longrightarrow> p\\<in>A\" proof\n        fix p assume \"limpt A p\"\n        consider (0) \"boundpt A p\"\n               | (1) \"intpt A p\"\n          using \\<open>limpt A p\\<close> lim_bnd_xor_int by auto\n        then show \"p\\<in>A\" using ap intpt_def by auto\n      qed\n      thus \"closed A\" using ax t425b by simp\n    qed\n\n  text \\<open>\\<^bold>\\<open>COROLLARY 4.2.7\\<close>\n     In any topological space \\<open>(X,T)\\<close>, both \\<open>X\\<close> and \\<open>{}\\<close> are closed sets,\n     and both are empty sets.\\<close>\n\n    \\<comment> \"The first two statements can be proved directly from the definition of 'open':\"\n    corollary open_empty: \"open {}\"      using open_def by auto\n    corollary open_univ: \"open X\"        using open_def by fastforce\n    \\<comment> \"Once we have those two, the others two are obvious:\"\n    corollary closed_univ: \"closed X\"    using open_empty by simp\n    corollary closed_empty: \"closed {}\"  using open_univ by simp\n\n\nsection \\<open>The closure of a set\\<close>\n\ndefinition closure :: \"'a set \\<Rightarrow> 'a set\" (* def 4.3.1 *)\n  where \"closure A \\<equiv> {x. limpt A x}\"\n\n\ntext \\<open>Theorem 4.3.2: For any set \\<open>A\\<close> in topological space \\<open>X\\<close>, \\<open>closure A\\<close> is closed.\nFurthermore, one always has \\<open>A \\<subseteq> closure A\\<close>\\<close>\n\ntheorem t432: assumes \"A\\<subseteq>X\" shows \"closed (closure A)\" sorry\n\ncorollary c433: assumes \"A\\<subseteq>X\" and \"closed A\" shows \"A = closure A\" sorry\n\ncorollary c434: assumes \"closed B\" \"A\\<subseteq>B\" shows \"(closure A) \\<subseteq> B\" sorry\n\nsection \"Topology and Set Theory\"\n\ntheorem t441a: assumes \"open S0\" \"open S1\" shows \"open (S0 \\<inter> S1)\" sorry\ntheorem t441b: assumes \"closed S0\" \"closed S1\" shows \"closed (S0 \\<union> S1)\" sorry\ntext \\<open>theorem t441c: the union of any collection of open sets is open\\<close>\ntext \\<open>theorem t441d: the intersection of any collection of closed sets is closed\\<close>\n\n\ntext \\<open>theorem 442: if A and B are subsets of a topspace (X,T) then \n  1. closure(A\\<union>B) = (closure A) \\<union> (closure B)\n  2. closure(A\\<inter>B) = (closure A) \\<inter> (closure B)\\<close>\n\ntext \\<open>theorem 443. If \\<open>A\\<noteq>{}\\<close> is a bounded set of real numbers in \\<R>, and \\<R> is given the usual\ntopology, then \\<open>sup A\\<in> closure A\\<close>. Hence, if \\<open>A\\<close> is closed, then \\<open>sup A\\<in>A\\<close>\\<close>\n\nsection \\<open>4.5 connectedness in a topological space\\<close>\n\nsection \\<open>4.6 the general theory of connected sets\\<close>\n\n\nend (* locale topspace *)\n\nend (* theory TopSpace *)\n", "meta": {"author": "tangentstorm", "repo": "tangentlabs", "sha": "49d7a335221e1ae67e8de0203a3f056bc4ab1d00", "save_path": "github-repos/isabelle/tangentstorm-tangentlabs", "path": "github-repos/isabelle/tangentstorm-tangentlabs/tangentlabs-49d7a335221e1ae67e8de0203a3f056bc4ab1d00/isar/TopSpace.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8791467770088163, "lm_q2_score": 0.8354835432479661, "lm_q1q2_score": 0.7345126642903554}}
{"text": "(*  Title:      HOL/Library/Poly_Deriv.thy\n    Author:     Amine Chaieb\n    Author:     Brian Huffman\n*)\n\nsection{* Polynomials and Differentiation *}\n\ntheory Poly_Deriv\nimports Deriv Polynomial\nbegin\n\nsubsection {* Derivatives of univariate polynomials *}\n\nfunction pderiv :: \"'a::real_normed_field poly \\<Rightarrow> 'a poly\"\nwhere\n  [simp del]: \"pderiv (pCons a p) = (if p = 0 then 0 else p + pCons 0 (pderiv p))\"\n  by (auto intro: pCons_cases)\n\ntermination pderiv\n  by (relation \"measure degree\") simp_all\n\nlemma pderiv_0 [simp]:\n  \"pderiv 0 = 0\"\n  using pderiv.simps [of 0 0] by simp\n\nlemma pderiv_pCons:\n  \"pderiv (pCons a p) = p + pCons 0 (pderiv p)\"\n  by (simp add: pderiv.simps)\n\nlemma coeff_pderiv: \"coeff (pderiv p) n = of_nat (Suc n) * coeff p (Suc n)\"\n  by (induct p arbitrary: n) \n     (auto simp add: pderiv_pCons coeff_pCons algebra_simps split: nat.split)\n\nprimrec pderiv_coeffs :: \"'a::comm_monoid_add list \\<Rightarrow> 'a list\"\nwhere\n  \"pderiv_coeffs [] = []\"\n| \"pderiv_coeffs (x # xs) = plus_coeffs xs (cCons 0 (pderiv_coeffs xs))\"\n\nlemma coeffs_pderiv [code abstract]:\n  \"coeffs (pderiv p) = pderiv_coeffs (coeffs p)\"\n  by (rule sym, induct p) (simp_all add: pderiv_pCons coeffs_plus_eq_plus_coeffs cCons_def)\n\nlemma pderiv_eq_0_iff: \"pderiv p = 0 \\<longleftrightarrow> degree p = 0\"\n  apply (rule iffI)\n  apply (cases p, simp)\n  apply (simp add: poly_eq_iff coeff_pderiv del: of_nat_Suc)\n  apply (simp add: poly_eq_iff coeff_pderiv coeff_eq_0)\n  done\n\nlemma degree_pderiv: \"degree (pderiv p) = degree p - 1\"\n  apply (rule order_antisym [OF degree_le])\n  apply (simp add: coeff_pderiv coeff_eq_0)\n  apply (cases \"degree p\", simp)\n  apply (rule le_degree)\n  apply (simp add: coeff_pderiv del: of_nat_Suc)\n  apply (metis degree_0 leading_coeff_0_iff nat.distinct(1))\n  done\n\nlemma pderiv_singleton [simp]: \"pderiv [:a:] = 0\"\nby (simp add: pderiv_pCons)\n\nlemma pderiv_add: \"pderiv (p + q) = pderiv p + pderiv q\"\nby (rule poly_eqI, simp add: coeff_pderiv algebra_simps)\n\nlemma pderiv_minus: \"pderiv (- p) = - pderiv p\"\nby (rule poly_eqI, simp add: coeff_pderiv)\n\nlemma pderiv_diff: \"pderiv (p - q) = pderiv p - pderiv q\"\nby (rule poly_eqI, simp add: coeff_pderiv algebra_simps)\n\nlemma pderiv_smult: \"pderiv (smult a p) = smult a (pderiv p)\"\nby (rule poly_eqI, simp add: coeff_pderiv algebra_simps)\n\nlemma pderiv_mult: \"pderiv (p * q) = p * pderiv q + q * pderiv p\"\nby (induct p) (auto simp: pderiv_add pderiv_smult pderiv_pCons algebra_simps)\n\nlemma pderiv_power_Suc:\n  \"pderiv (p ^ Suc n) = smult (of_nat (Suc n)) (p ^ n) * pderiv p\"\napply (induct n)\napply simp\napply (subst power_Suc)\napply (subst pderiv_mult)\napply (erule ssubst)\napply (simp only: of_nat_Suc smult_add_left smult_1_left)\napply (simp add: algebra_simps)\ndone\n\nlemma DERIV_pow2: \"DERIV (%x. x ^ Suc n) x :> real (Suc n) * (x ^ n)\"\nby (rule DERIV_cong, rule DERIV_pow, simp)\ndeclare DERIV_pow2 [simp] DERIV_pow [simp]\n\nlemma DERIV_add_const: \"DERIV f x :> D ==>  DERIV (%x. a + f x :: 'a::real_normed_field) x :> D\"\nby (rule DERIV_cong, rule DERIV_add, auto)\n\nlemma poly_DERIV[simp]: \"DERIV (%x. poly p x) x :> poly (pderiv p) x\"\n  by (induct p, auto intro!: derivative_eq_intros simp add: pderiv_pCons)\n\ntext{* Consequences of the derivative theorem above*}\n\nlemma poly_differentiable[simp]: \"(%x. poly p x) differentiable (at x::real filter)\"\napply (simp add: real_differentiable_def)\napply (blast intro: poly_DERIV)\ndone\n\nlemma poly_isCont[simp]: \"isCont (%x. poly p x) (x::real)\"\nby (rule poly_DERIV [THEN DERIV_isCont])\n\nlemma poly_IVT_pos: \"[| a < b; poly p (a::real) < 0; 0 < poly p b |]\n      ==> \\<exists>x. a < x & x < b & (poly p x = 0)\"\nusing IVT_objl [of \"poly p\" a 0 b]\nby (auto simp add: order_le_less)\n\nlemma poly_IVT_neg: \"[| (a::real) < b; 0 < poly p a; poly p b < 0 |]\n      ==> \\<exists>x. a < x & x < b & (poly p x = 0)\"\nby (insert poly_IVT_pos [where p = \"- p\" ]) simp\n\nlemma poly_MVT: \"(a::real) < b ==>\n     \\<exists>x. a < x & x < b & (poly p b - poly p a = (b - a) * poly (pderiv p) x)\"\nusing MVT [of a b \"poly p\"]\napply auto\napply (rule_tac x = z in exI)\napply (auto simp add: mult_left_cancel poly_DERIV [THEN DERIV_unique])\ndone\n\ntext{*Lemmas for Derivatives*}\n\nlemma order_unique_lemma:\n  fixes p :: \"'a::idom poly\"\n  assumes \"[:-a, 1:] ^ n dvd p\" \"\\<not> [:-a, 1:] ^ Suc n dvd p\"\n  shows \"n = order a p\"\nunfolding Polynomial.order_def\napply (rule Least_equality [symmetric])\napply (fact assms)\napply (rule classical)\napply (erule notE)\nunfolding not_less_eq_eq\nusing assms(1) apply (rule power_le_dvd)\napply assumption\ndone\n\nlemma lemma_order_pderiv1:\n  \"pderiv ([:- a, 1:] ^ Suc n * q) = [:- a, 1:] ^ Suc n * pderiv q +\n    smult (of_nat (Suc n)) (q * [:- a, 1:] ^ n)\"\napply (simp only: pderiv_mult pderiv_power_Suc)\napply (simp del: power_Suc of_nat_Suc add: pderiv_pCons)\ndone\n\nlemma dvd_add_cancel1:\n  fixes a b c :: \"'a::comm_ring_1\"\n  shows \"a dvd b + c \\<Longrightarrow> a dvd b \\<Longrightarrow> a dvd c\"\n  by (drule (1) Rings.dvd_diff, simp)\n\nlemma lemma_order_pderiv:\n  assumes n: \"0 < n\" \n      and pd: \"pderiv p \\<noteq> 0\" \n      and pe: \"p = [:- a, 1:] ^ n * q\" \n      and nd: \"~ [:- a, 1:] dvd q\"\n    shows \"n = Suc (order a (pderiv p))\"\nusing n \nproof -\n  have \"pderiv ([:- a, 1:] ^ n * q) \\<noteq> 0\"\n    using assms by auto\n  obtain n' where \"n = Suc n'\" \"0 < Suc n'\" \"pderiv ([:- a, 1:] ^ Suc n' * q) \\<noteq> 0\"\n    using assms by (cases n) auto\n  then have *: \"!!k l. k dvd k * pderiv q + smult (of_nat (Suc n')) l \\<Longrightarrow> k dvd l\"\n    by (metis dvd_add_cancel1 dvd_smult_iff dvd_triv_left of_nat_eq_0_iff old.nat.distinct(2))\n  have \"n' = order a (pderiv ([:- a, 1:] ^ Suc n' * q))\" \n  proof (rule order_unique_lemma)\n    show \"[:- a, 1:] ^ n' dvd pderiv ([:- a, 1:] ^ Suc n' * q)\"\n      apply (subst lemma_order_pderiv1)\n      apply (rule dvd_add)\n      apply (metis dvdI dvd_mult2 power_Suc2)\n      apply (metis dvd_smult dvd_triv_right)\n      done\n  next\n    show \"\\<not> [:- a, 1:] ^ Suc n' dvd pderiv ([:- a, 1:] ^ Suc n' * q)\"\n     apply (subst lemma_order_pderiv1)\n     by (metis * nd dvd_mult_cancel_right field_power_not_zero pCons_eq_0_iff power_Suc zero_neq_one)\n  qed\n  then show ?thesis\n    by (metis `n = Suc n'` pe)\nqed\n\nlemma order_decomp:\n     \"p \\<noteq> 0\n      ==> \\<exists>q. p = [:-a, 1:] ^ (order a p) * q &\n                ~([:-a, 1:] dvd q)\"\napply (drule order [where a=a])\nby (metis dvdE dvd_mult_cancel_left power_Suc2)\n\nlemma order_pderiv: \"[| pderiv p \\<noteq> 0; order a p \\<noteq> 0 |]\n      ==> (order a p = Suc (order a (pderiv p)))\"\napply (case_tac \"p = 0\", simp)\napply (drule_tac a = a and p = p in order_decomp)\nusing neq0_conv\napply (blast intro: lemma_order_pderiv)\ndone\n\nlemma order_mult: \"p * q \\<noteq> 0 \\<Longrightarrow> order a (p * q) = order a p + order a q\"\nproof -\n  def i \\<equiv> \"order a p\"\n  def j \\<equiv> \"order a q\"\n  def t \\<equiv> \"[:-a, 1:]\"\n  have t_dvd_iff: \"\\<And>u. t dvd u \\<longleftrightarrow> poly u a = 0\"\n    unfolding t_def by (simp add: dvd_iff_poly_eq_0)\n  assume \"p * q \\<noteq> 0\"\n  then show \"order a (p * q) = i + j\"\n    apply clarsimp\n    apply (drule order [where a=a and p=p, folded i_def t_def])\n    apply (drule order [where a=a and p=q, folded j_def t_def])\n    apply clarify\n    apply (erule dvdE)+\n    apply (rule order_unique_lemma [symmetric], fold t_def)\n    apply (simp_all add: power_add t_dvd_iff)\n    done\nqed\n\ntext{*Now justify the standard squarefree decomposition, i.e. f / gcd(f,f'). *}\n\nlemma order_divides: \"[:-a, 1:] ^ n dvd p \\<longleftrightarrow> p = 0 \\<or> n \\<le> order a p\"\napply (cases \"p = 0\", auto)\napply (drule order_2 [where a=a and p=p])\napply (metis not_less_eq_eq power_le_dvd)\napply (erule power_le_dvd [OF order_1])\ndone\n\nlemma poly_squarefree_decomp_order:\n  assumes \"pderiv p \\<noteq> 0\"\n  and p: \"p = q * d\"\n  and p': \"pderiv p = e * d\"\n  and d: \"d = r * p + s * pderiv p\"\n  shows \"order a q = (if order a p = 0 then 0 else 1)\"\nproof (rule classical)\n  assume 1: \"order a q \\<noteq> (if order a p = 0 then 0 else 1)\"\n  from `pderiv p \\<noteq> 0` have \"p \\<noteq> 0\" by auto\n  with p have \"order a p = order a q + order a d\"\n    by (simp add: order_mult)\n  with 1 have \"order a p \\<noteq> 0\" by (auto split: if_splits)\n  have \"order a (pderiv p) = order a e + order a d\"\n    using `pderiv p \\<noteq> 0` `pderiv p = e * d` by (simp add: order_mult)\n  have \"order a p = Suc (order a (pderiv p))\"\n    using `pderiv p \\<noteq> 0` `order a p \\<noteq> 0` by (rule order_pderiv)\n  have \"d \\<noteq> 0\" using `p \\<noteq> 0` `p = q * d` by simp\n  have \"([:-a, 1:] ^ (order a (pderiv p))) dvd d\"\n    apply (simp add: d)\n    apply (rule dvd_add)\n    apply (rule dvd_mult)\n    apply (simp add: order_divides `p \\<noteq> 0`\n           `order a p = Suc (order a (pderiv p))`)\n    apply (rule dvd_mult)\n    apply (simp add: order_divides)\n    done\n  then have \"order a (pderiv p) \\<le> order a d\"\n    using `d \\<noteq> 0` by (simp add: order_divides)\n  show ?thesis\n    using `order a p = order a q + order a d`\n    using `order a (pderiv p) = order a e + order a d`\n    using `order a p = Suc (order a (pderiv p))`\n    using `order a (pderiv p) \\<le> order a d`\n    by auto\nqed\n\nlemma poly_squarefree_decomp_order2: \"[| pderiv p \\<noteq> 0;\n         p = q * d;\n         pderiv p = e * d;\n         d = r * p + s * pderiv p\n      |] ==> \\<forall>a. order a q = (if order a p = 0 then 0 else 1)\"\nby (blast intro: poly_squarefree_decomp_order)\n\nlemma order_pderiv2: \"[| pderiv p \\<noteq> 0; order a p \\<noteq> 0 |]\n      ==> (order a (pderiv p) = n) = (order a p = Suc n)\"\nby (auto dest: order_pderiv)\n\ndefinition\n  rsquarefree :: \"'a::idom poly => bool\" where\n  \"rsquarefree p = (p \\<noteq> 0 & (\\<forall>a. (order a p = 0) | (order a p = 1)))\"\n\nlemma pderiv_iszero: \"pderiv p = 0 \\<Longrightarrow> \\<exists>h. p = [:h:]\"\napply (simp add: pderiv_eq_0_iff)\napply (case_tac p, auto split: if_splits)\ndone\n\nlemma rsquarefree_roots:\n  \"rsquarefree p = (\\<forall>a. ~(poly p a = 0 & poly (pderiv p) a = 0))\"\napply (simp add: rsquarefree_def)\napply (case_tac \"p = 0\", simp, simp)\napply (case_tac \"pderiv p = 0\")\napply simp\napply (drule pderiv_iszero, clarsimp)\napply (metis coeff_0 coeff_pCons_0 degree_pCons_0 le0 le_antisym order_degree)\napply (force simp add: order_root order_pderiv2)\ndone\n\nlemma poly_squarefree_decomp:\n  assumes \"pderiv p \\<noteq> 0\"\n    and \"p = q * d\"\n    and \"pderiv p = e * d\"\n    and \"d = r * p + s * pderiv p\"\n  shows \"rsquarefree q & (\\<forall>a. (poly q a = 0) = (poly p a = 0))\"\nproof -\n  from `pderiv p \\<noteq> 0` have \"p \\<noteq> 0\" by auto\n  with `p = q * d` have \"q \\<noteq> 0\" by simp\n  have \"\\<forall>a. order a q = (if order a p = 0 then 0 else 1)\"\n    using assms by (rule poly_squarefree_decomp_order2)\n  with `p \\<noteq> 0` `q \\<noteq> 0` show ?thesis\n    by (simp add: rsquarefree_def order_root)\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/Poly_Deriv.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8354835289107307, "lm_q2_score": 0.8791467754256017, "lm_q1q2_score": 0.7345126503630715}}
{"text": "theory Safe_Distance_Isar\nimports\n  Safe_Distance_Auxiliarities\n  \"~~/src/HOL/Library/Sum_of_Squares\"\n  \"~~/src/HOL/Decision_Procs/Approximation\"\n  \"$AFP/Sturm_Sequences/Sturm\"\nbegin\n\nsubsection \\<open>quadratic equations\\<close>\ntext \\<open>\\label{sec:quadroot}\\<close>\n\nlemma discriminant: \"a * x\\<^sup>2 + b * x + c = (0::real) \\<Longrightarrow> 0 \\<le> b\\<^sup>2 - 4 * a * c\" \n  by (sos \"(((A<0 * R<1) + (R<1 * (R<1 * [2*a*x + b]^2))))\")\n\nlemma quadratic_eq_factoring:\n  assumes D: \"D = b\\<^sup>2 - 4 * a * c\"\n  assumes nn: \"0 \\<le> D\"\n  assumes x1: \"x\\<^sub>1 = (-b + sqrt D) / (2 * a)\"\n  assumes x2: \"x\\<^sub>2 = (-b - sqrt D) / (2 * a)\"\n  assumes a: \"a \\<noteq> 0\"\n  shows \"a * x\\<^sup>2 + b * x + c = a * (x - x\\<^sub>1) * (x - x\\<^sub>2)\"\n  using nn\n  by (simp add: D x1 x2)\n    (simp add: assms algebra_simps power2_eq_square power3_eq_cube divide_simps)\n\nlemma quadratic_eq_zeroes_iff:\n  assumes D: \"D = b\\<^sup>2 - 4 * a * c\"\n  assumes x1: \"x\\<^sub>1 = (-b + sqrt D) / (2 * a)\"\n  assumes x2: \"x\\<^sub>2 = (-b - sqrt D) / (2 * a)\"\n  assumes a: \"a \\<noteq> 0\"\n  shows \"a * x\\<^sup>2 + b * x + c = 0 \\<longleftrightarrow> (D \\<ge> 0 \\<and> (x = x\\<^sub>1 \\<or> x = x\\<^sub>2))\" (is \"?z \\<longleftrightarrow> _\")\n  using quadratic_eq_factoring[OF D _ x1 x2 a, of x] discriminant[of a x b c] a\n  by (auto simp: D)\n\nsubsubsection\\<open>convexity condition\\<close>\ntext \\<open>\\label{sec:convex}\\<close>\n\nlemma p_convex:\n  fixes a b c x y z::real\n  assumes p_def: \"p = (\\<lambda>x. a * x\\<^sup>2 + b * x + c)\"\n  assumes less: \"x < y\" \"y < z\" and ge: \"p x > p y\" \"p y \\<le> p z\"\n  shows \"a > 0\"\n  using less ge unfolding p_def\n  by (sos \"((((A<0 * (A<1 * A<2)) * R<1) + (((A<2 * R<1) * (R<1/4 * [y + ~1*z]^2)) +\n    (((A<=1 * R<1) * (R<1 * [x + ~1*y]^2)) + (((A<=1 * (A<0 * (A<1 * R<1))) * (R<1/4 * [1]^2)) +\n    (((A<=0 * R<1) * (R<1/4 * [~1*y^2 + x*y + ~1*x*z + y*z]^2)) +\n    ((A<=0 * (A<0 * (A<1 * R<1))) * (R<1 * [x + ~1/2*y + ~1/2*z]^2))))))))\")\n  \ndefinition root_in::\"real \\<Rightarrow> real \\<Rightarrow> (real \\<Rightarrow> real) \\<Rightarrow> bool\" where\n  \"root_in m M f = (\\<exists>x\\<in>{m .. M}. f x = 0)\"\n\ndefinition \"quadroot_in m M a b c = root_in m M (\\<lambda>x. a * x^2 + b * x + c)\"\n\nlemma card_iff_exists: \"0 < card X \\<longleftrightarrow> finite X \\<and> (\\<exists>x. x \\<in> X)\"\n  by (auto simp: card_gt_0_iff)\n  \nlemma quadroot_in_sturm[code]:\n  \"quadroot_in m M a b c \\<longleftrightarrow> (a = 0 \\<and> b = 0 \\<and> c = 0 \\<and> m \\<le> M) \\<or>\n    (m \\<le> M \\<and> poly [:c, b, a:] m = 0) \\<or>\n    count_roots_between [:c, b, a:] m M > 0\"\n  apply (cases \"a = 0 \\<and> b = 0 \\<and> c = 0 \\<and> m \\<le> M\")\n  apply (force simp: quadroot_in_def root_in_def)\n  apply (cases \"m \\<le> M \\<and> poly [:c, b, a:] m = 0\")\n  apply (force simp: quadroot_in_def root_in_def algebra_simps power2_eq_square count_roots_between_correct card_iff_exists)\nproof -\n  assume H: \"\\<not> (a = 0 \\<and> b = 0 \\<and> c = 0 \\<and> m \\<le> M)\" \"\\<not> (m \\<le> M \\<and> poly [:c, b, a:] m = 0)\"\n  hence \"poly [:c, b, a:] m \\<noteq> 0 \\<or> m > M\"\n    by auto\n  then have \"quadroot_in m M a b c \\<longleftrightarrow> 0 < count_roots_between [:c, b, a:] m M\"\n  proof (rule disjE)\n    assume pnz: \"poly [:c, b, a:] m \\<noteq> 0\"\n    then have nz: \"[:c, b, a:] \\<noteq> 0\" by auto\n    show ?thesis\n      unfolding count_roots_between_correct card_iff_exists\n      apply safe\n      apply (rule finite_subset[where B=\"{x. poly [:c, b, a:] x = 0}\"])\n      apply force\n      apply (rule poly_roots_finite)\n      apply (rule nz)\n      using pnz\n      apply (auto simp add: count_roots_between_correct quadroot_in_def root_in_def card_iff_exists\n        algebra_simps power2_eq_square)\n      apply (case_tac \"x = m\")\n      apply (force simp: algebra_simps)\n      apply force\n      done\n  qed (auto simp: quadroot_in_def count_roots_between_correct root_in_def card_eq_0_iff)\n  then show \"quadroot_in m M a b c = (a = 0 \\<and> b = 0 \\<and> c = 0 \\<and> m \\<le> M \\<or>\n     m \\<le> M \\<and> poly [:c, b, a:] m = 0 \\<or>\n     0 < count_roots_between [:c, b, a:] m M)\"\n    using H by metis\nqed\n\nlemma sqrt_divide: \"b \\<ge> 0 \\<Longrightarrow> sqrt a / b = sqrt (a / b\\<^sup>2)\"\n  by (auto simp: real_sqrt_divide)\n\nlemma check_quadroot_linear:\n  fixes a b c::real\n  assumes \"a = 0\"\n  shows \"\\<not> quadroot_in m M a b c \\<longleftrightarrow>\n    ((b = 0 \\<and> c = 0 \\<and> M < m) \\<or> (b = 0 \\<and> c \\<noteq> 0) \\<or>\n     (b \\<noteq> 0 \\<and> (let x = - c / b in m > x \\<or> x > M)))\"\nproof -\n  have \"quadroot_in m M a b c \\<longleftrightarrow> (b = 0 \\<longrightarrow> quadroot_in m M a b c) \\<and> (b \\<noteq> 0 \\<longrightarrow> quadroot_in m M a b c)\"\n    by auto\n  also have \"(b = 0 \\<longrightarrow> quadroot_in m M a b c) \\<longleftrightarrow>\n    ((b = 0 \\<longrightarrow> c = 0 \\<longrightarrow> m \\<le> M) \\<and> (b \\<noteq> 0 \\<or> c = 0))\"\n    by (auto simp: quadroot_in_def Let_def root_in_def assms field_simps divide_simps\n      intro!: bexI[where x=\"-c / b\"])\n  also have \"(b \\<noteq> 0 \\<longrightarrow> quadroot_in m M a b c) \\<longleftrightarrow> (b = 0 \\<or> (let x = -c / b in m \\<le> x \\<and> x \\<le> M))\"\n    apply (auto simp: quadroot_in_def Let_def root_in_def assms field_simps divide_simps\n      intro!: bexI[where x=\"-c / b\"])\n    apply (metis mult.commute mult_le_cancel_left_neg add_eq_0_iff)\n    apply (metis mult.commute mult_le_cancel_left_neg add_eq_0_iff)\n    apply (metis mult.commute add_eq_0_iff real_mult_le_cancel_iff2)\n    by (metis mult.commute add_eq_0_iff real_mult_le_cancel_iff2)\n  finally show ?thesis\n    by (simp add: Let_def not_less not_le)\nqed \n\nlemma check_quadroot_nonlinear:\n  assumes \"a \\<noteq> 0\"\n  shows \"quadroot_in m M a b c =\n    (let D = b^2 - 4 * a * c in D \\<ge> 0 \\<and>\n      ((let x = (-b + sqrt D)/(2*a) in m \\<le> x \\<and> x \\<le> M) \\<or>\n      (let x = (-b - sqrt D)/(2*a) in m \\<le> x \\<and> x \\<le> M)))\"\n  by (auto simp: quadroot_in_def Let_def root_in_def\n    quadratic_eq_zeroes_iff[OF refl refl refl assms])\n\nlemma ncheck_quadroot:\n  shows \"\\<not>quadroot_in m M a b c \\<longleftrightarrow>\n    (a = 0 \\<longrightarrow>\\<not>quadroot_in m M a b c) \\<and>\n    (a = 0 \\<or> \\<not>quadroot_in m M a b c)\"\n  by auto\n\nlocale movement = fixes a v s0 :: real\nbegin\n\ntext \\<open>\n  function to compute the distance using equation\n    @{text \"s(t) = s\\<^sub>0 + v\\<^sub>0 \\<cdot> t + 1/2 \\<cdot> a \\<cdot> t\\<^sup>2\"}\n  \n  Input parameters : \n     1. @{term s\\<^sub>0}     :   initial distance\n     2. @{term v\\<^sub>0}     :   initial velocity (positive means forward direction and the converse is true)\n     3. @{term a}      :   acceleration (positive for increasing and negative for decreasing)\n     4. @{term t}      :   time \n\n  For the time @{term \"t < 0\"}, we assume the output of the function is @{term s\\<^sub>0}. Otherwise, the output\n  is calculated according to the equation above.\n\\<close>\n\nsubsubsection \\<open>continuous dynamics\\<close>\ntext \\<open>\\label{sec:cont-dynamics}\\<close>\ndefinition \"p t = s0 + v * t + 1/2 * a * t\\<^sup>2\"\n\nlemma p_all_zeroes:\n  assumes D: \"D = v\\<^sup>2 - 2 * a * s0\"\n  shows \"p t = 0 \\<longleftrightarrow> ((a \\<noteq> 0 \\<and> 0 \\<le> D \\<and> ((t = (- v + sqrt D) / a) \\<or> t = (- v - sqrt D) / a)) \\<or>\n    (a = 0 \\<and> v = 0 \\<and> s0 = 0) \\<or> (a = 0 \\<and> v \\<noteq> 0 \\<and> t = (- s0 / v)))\"\n  using quadratic_eq_zeroes_iff[OF refl refl refl, of \"a / 2\" t v s0]\n  by (auto simp: movement.p_def algebra_simps D power2_eq_square divide_simps)\n\nlemma p_zero[simp]: \"p 0 = s0\"\n  by (simp add: p_def)\n\nlemma p_continuous[continuous_intros]: \"continuous_on T p\"\n  by (auto intro!: continuous_intros simp: p_def)\n\nlemma isCont_p[continuous_intros]: \"isCont p x\"\n  using p_continuous[of UNIV]\n  by (auto simp: continuous_on_eq_continuous_at)\n\ndefinition \"p' t = v + a * t\"\n\nlemma p'_zero: \"p' 0 = v\"\n  by (simp add: p'_def)\n\nlemma p_has_vector_derivative[derivative_intros]: \"(p has_vector_derivative p' t) (at t within s)\"\n  by (auto simp: p_def[abs_def] p'_def has_vector_derivative_def algebra_simps\n    intro!: derivative_eq_intros)\n\nlemma p_has_real_derivative[derivative_intros]: \"(p has_real_derivative p' t) (at t within s)\"\n  using p_has_vector_derivative\n  by (simp add: has_field_derivative_iff_has_vector_derivative)\n\ndefinition \"p'' t = a\"\n\nlemma p'_has_vector_derivative[derivative_intros]: \"(p' has_vector_derivative p'' t) (at t within s)\"\n  by (auto simp: p'_def[abs_def] p''_def has_vector_derivative_def algebra_simps\n    intro!: derivative_eq_intros)\n\nlemma p'_has_real_derivative[derivative_intros]: \"(p' has_real_derivative p'' t) (at t within s)\"\n  using p'_has_vector_derivative\n  by (simp add: has_field_derivative_iff_has_vector_derivative)\n\ndefinition t_stop :: real where \"t_stop = - v / a\"\n\nlemma p'_stop_zero: \"p' t_stop = (if a = 0 then v else 0)\" by (auto simp: p'_def t_stop_def)\n\nlemma p'_pos_iff: \"p' x > 0 \\<longleftrightarrow>\n    (if a > 0 then x > -v / a else if a < 0 then x < -v / a else v > 0)\"\n  by (auto simp: p'_def divide_simps algebra_simps)\n\nlemma le_t_stop_iff: \"a \\<noteq> 0 \\<Longrightarrow> x \\<le> t_stop \\<longleftrightarrow> (if a < 0 then p' x \\<ge> 0 else p' x \\<le> 0)\"\n  by (auto simp: p'_def divide_simps algebra_simps t_stop_def)\n\nlemma p'_continuous[continuous_intros]: \"continuous_on T p'\"\n  by (auto simp: p'_def intro!: continuous_intros)\n\nlemma isCont_p'[continuous_intros]: \"isCont p' x\"\n  using p'_continuous[of UNIV]\n  by (auto simp: continuous_on_eq_continuous_at)\n\ndefinition p_max :: real where \"p_max = p t_stop\"\n\nlemmas p_t_stop = p_max_def[symmetric]\n\nlemma p_max_eq: \"p_max = s0 - v\\<^sup>2 / a / 2\"\n  by (auto simp: p_max_def p_def t_stop_def algebra_simps divide_simps power2_eq_square)\n\nsubsubsection \\<open>Hybrid dynamics\\<close>\ntext \\<open>\\label{sec:hybrid-dynamics}\\<close>\ndefinition\n  \"s t = (     if t \\<le> 0      then s0\n          else if t \\<le> t_stop then p t\n          else                p_max)\"\n\ndefinition \n  \"q t = s0 + v * t\"\n\ndefinition \n  \"q' t = v\"\n\nlemma init_q: \"q 0 = s0\" unfolding q_def by auto\n\nlemma q_continuous[continuous_intros]: \"continuous_on T q\"\n  by (auto intro!: continuous_intros simp:q_def)\n\nlemma isCont_q[continuous_intros]: \"isCont q x\"\n  using q_continuous[of UNIV]\n  by (auto simp:continuous_on_eq_continuous_at)\n\nlemma q_has_vector_derivative[derivative_intros]: \"(q has_vector_derivative q' t) (at t within u)\"\n  by (auto simp: q_def[abs_def] q'_def has_vector_derivative_def algebra_simps\n          intro!: derivative_eq_intros)\n\nlemma q_has_real_derivative[derivative_intros]: \"(q has_real_derivative q' t) (at t within u)\"\n  using q_has_vector_derivative\n  by (simp add:has_field_derivative_iff_has_vector_derivative)\n\nlemma\n  s_cond_def:\n  \"t \\<le> 0 \\<Longrightarrow> s t = s0\"\n  \"0 \\<le> t \\<Longrightarrow> t \\<le> t_stop \\<Longrightarrow> s t = p t\"\n  by (simp_all add: s_def)\n  \nend\n\nlocale braking_movement = movement +\nassumes decel: \"a < 0\"\nassumes nonneg_vel: \"v \\<ge> 0\"\nbegin\n\nlemma t_stop_nonneg: \"0 \\<le> t_stop\"\n  using decel nonneg_vel\n  by (auto simp: t_stop_def divide_simps)\n\nlemma t_stop_pos:\n  assumes \"v \\<noteq> 0\"\n  shows \"0 < t_stop\"\n  using decel nonneg_vel assms\n  by (auto simp: t_stop_def divide_simps)\n\nlemma t_stop_zero:\n  assumes \"t_stop = 0\"\n  shows \"v = 0\"\n  using assms decel\n  by (auto simp: t_stop_def)\n\nlemma t_stop_zero_not_moving: \"t_stop = 0 \\<Longrightarrow> q t = s0\" unfolding q_def using t_stop_zero by auto\n\nabbreviation \"s_stop \\<equiv> s t_stop\"\n\nlemma s_t_stop: \"s_stop = p_max\"\n  using t_stop_nonneg                         \n  by (auto simp: s_def t_stop_def p_max_def p_def)\n\nthm mult_nonneg_nonneg\n\nlemma s0_le_s_stop: \"s0 \\<le> s_stop\" \nproof (rule subst[where t=\"s_stop\" and s=\"p_max\"])\n  show \"p_max = s_stop\" by (rule sym[OF s_t_stop])\nnext\n  show \"s0 \\<le> p_max\" \n  proof (rule subst[where t=\"p_max\" and s=\"s0 - v\\<^sup>2 / a / 2\"]) \n    show \" s0 - v\\<^sup>2 / a / 2 = p_max\" using p_max_eq by auto\n  next\n    have \"0 \\<le> - v\\<^sup>2 / a / 2\" using decel zero_le_square[of v]\n    proof -\n      have f1: \"a \\<le> 0\"\n        using \\<open>a < 0\\<close> by linarith\n      have \"(- 1 * v\\<^sup>2 \\<le> 0) = (0 \\<le> v\\<^sup>2)\"\n        by auto\n      then have \"0 \\<le> - 1 * v\\<^sup>2 / a\"\n        using f1 by (meson zero_le_divide_iff zero_le_power2)\n      then show ?thesis\n        by force\n    qed\n    thus \"s0 \\<le> s0 - v\\<^sup>2 / a / 2\" by auto\n  qed\nqed\n\nlemma p_mono: \"x \\<le> y \\<Longrightarrow> y \\<le> t_stop \\<Longrightarrow> p x \\<le> p y\"\n  using decel\n  unfolding p_max_def p_def t_stop_def\n  by (sos \"((((A<0 * A<1) * R<1) + ((R<1 * (R<2 * [a*x + ~1*a*y]^2)) +\n    ((A<=0 * (A<=1 * (A<0 * R<1))) * (R<4 * [1]^2)))))\")\n\nlemma p_antimono: \"x \\<le> y \\<Longrightarrow> t_stop \\<le> x \\<Longrightarrow> p y \\<le> p x\"\n  using decel\n  unfolding p_max_def p_def t_stop_def\n  by (sos \"((((A<0 * A<1) * R<1) + ((R<1 * (R<2 * [a*x + ~1*a*y]^2)) +\n    ((A<=0 * (A<=1 * (A<0 * R<1))) * (R<4 * [1]^2)))))\")\n\nlemma p_strict_mono: \"x < y \\<Longrightarrow> y \\<le> t_stop \\<Longrightarrow> p x < p y\"\n  using decel\n  unfolding p_max_def p_def t_stop_def\n  by (sos \"((((A<0 * A<1) * ((A<0 * A<1) * R<1)) + (((A<=1 * (A<0 * R<1)) * (R<1/2 * [1]^2)) +\n    ((A<=0 * (A<0 * (A<1 * R<1))) * (R<2 * [1]^2)))))\")\n\nlemma p_strict_antimono: \"x < y \\<Longrightarrow> t_stop \\<le> x\\<Longrightarrow> p y < p x\"\n  using decel\n  unfolding p_max_def p_def t_stop_def\n  by (sos \"((((A<0 * A<1) * ((A<0 * A<1) * R<1)) + (((A<=1 * (A<0 * R<1)) * (R<1/2 * [1]^2)) +\n    ((A<=0 * (A<0 * (A<1 * R<1))) * (R<2 * [1]^2)))))\")\n\nlemma p_max: \"p x \\<le> p_max\"\n  unfolding p_max_def\n  by (cases \"x \\<le> t_stop\") (auto intro: p_mono p_antimono)\n\nlemma continuous_on_s[continuous_intros]: \"continuous_on T s\"\n  unfolding s_def[abs_def]\n  using t_stop_nonneg\n  by (intro continuous_on_subset[where t=T and s = \"{.. 0}\\<union>({0 .. t_stop} \\<union> {t_stop ..})\"] continuous_on_If)\n    (auto simp: p_max_def continuous_intros antisym_conv[where x=0])\n\nlemma isCont_s[continuous_intros]: \"isCont s x\"\n  using continuous_on_s[of UNIV]\n  by (auto simp: continuous_on_eq_continuous_at)\n\ndefinition \"s' t = (if t \\<le> t_stop then p' t else 0)\"\n\nlemma s_has_real_derivative:\n  assumes \"t \\<ge> 0\" \"v / a \\<le> 0\" \"a \\<noteq> 0\"\n  shows \"(s has_real_derivative s' t) (at t within {0..})\"\nproof -\n  from assms have *: \"t \\<le> t_stop \\<longleftrightarrow> t \\<in> {0 .. t_stop}\" by simp\n  from assms have \"0 \\<le> t_stop\" by (auto simp: t_stop_def)\n\n  have \"((\\<lambda>t. if t \\<in> {0 .. t_stop} then p t else p_max) has_real_derivative\n    (if t \\<in> {0..t_stop} then p' t else 0)) (at t within {0..})\"\n    unfolding s_def[abs_def] s'_def \n      has_field_derivative_iff_has_vector_derivative\n    apply (rule has_vector_derivative_If[where t = \"{t_stop ..}\"])\n    using \\<open>0 \\<le> t_stop\\<close> \\<open>a \\<noteq> 0\\<close>\n    by (auto simp: assms p'_stop_zero p_t_stop max_def insert_absorb\n      intro!: p_has_vector_derivative)\n  from _ _ this show ?thesis\n    unfolding has_vector_derivative_def has_field_derivative_iff_has_vector_derivative\n      s'_def s_def[abs_def] *\n    by (rule has_derivative_transform)\n      (auto simp: assms s_def p_max_def t_stop_def)\nqed\n\nlemma s_has_vector_derivative[derivative_intros]:\n  assumes \"t \\<ge> 0\" \"v / a \\<le> 0\" \"a \\<noteq> 0\"\n  shows  \"(s has_vector_derivative s' t) (at t within {0..})\"\n  using s_has_real_derivative[OF assms]\n  by (simp add:has_field_derivative_iff_has_vector_derivative)\n   \nlemma s_has_field_derivative[derivative_intros]:\n  assumes \"t \\<ge> 0\" \"v / a \\<le> 0\" \"a \\<noteq> 0\"\n  shows \"(s has_field_derivative s' t) (at t within {0..})\"\n  using s_has_vector_derivative[OF assms]\n  by(simp add:has_field_derivative_iff_has_vector_derivative)\n  \nlemma s_has_real_derivative_at:\n  assumes \"0 < x\" \"0 \\<le> v\" \"a < 0\"\n  shows \"(s has_real_derivative s' x) (at x)\"\nproof -\n  from assms have \"(s has_real_derivative s' x) (at x within {0 ..})\"\n    by (intro s_has_real_derivative) (auto intro!: divide_nonneg_nonpos)\n  then have \"(s has_real_derivative s' x) (at x within {0<..})\"\n    by (rule DERIV_subset) auto\n  then show \"(s has_real_derivative s' x) (at x)\" using assms\n    by (subst (asm) at_within_open) auto\nqed\n\n                     \nlemma s_delayed_has_field_derivative[derivative_intros]:\n  assumes \"\\<delta> < t\" \"0 \\<le> v\" \"a < 0\"\n  shows \"((\\<lambda>x. s (x - \\<delta>)) has_field_derivative s' (t - \\<delta>)) (at t within {\\<delta><..})\"\nproof -\n  from assms have \"((\\<lambda>x. s (x + - \\<delta>)) has_real_derivative s' (t - \\<delta>)) (at t)\"\n  using DERIV_shift[of \"s\" \"(s' (t - \\<delta>))\" t \"-\\<delta>\"] s_has_real_derivative_at \n  by auto  \n  \n  thus \"((\\<lambda>x. s (x - \\<delta>)) has_field_derivative s' (t - \\<delta>)) (at t within {\\<delta><..})\"\n  using has_field_derivative_at_within by auto\nqed  \n\nlemma s_delayed_has_vector_derivative[derivative_intros]:\n  assumes \"\\<delta> < t\" \"0 \\<le> v\" \"a < 0\"\n  shows  \"((\\<lambda>x. s (x - \\<delta>)) has_vector_derivative s' (t - \\<delta>)) (at t within {\\<delta><..})\"\n  using s_delayed_has_field_derivative[OF assms]  \n  by(simp add:has_field_derivative_iff_has_vector_derivative)\n\nlemma s'_nonneg: \"0 \\<le> v \\<Longrightarrow> a \\<le> 0 \\<Longrightarrow> 0 \\<le> s' x\"\n  by (auto simp: s'_def p'_def divide_simps t_stop_def algebra_simps) \n\nlemma s'_pos: \"0 \\<le> x \\<Longrightarrow> x < t_stop \\<Longrightarrow> 0 \\<le> v \\<Longrightarrow> a \\<le> 0 \\<Longrightarrow> 0 < s' x\"\n  by (intro le_neq_trans s'_nonneg)\n    (auto simp: s'_def p'_def divide_simps t_stop_def algebra_simps)\n\nsubsubsection \\<open>Monotonicity of movement\\<close>\ntext \\<open>\\label{sec:mono}\\<close>\n\nlemma s_mono:\n  assumes \"t \\<ge> u\" \"u \\<ge> 0\"\n  shows \"s t \\<ge> s u\"\n  using p_mono[of u t] assms p_max[of u]\n  by (auto simp: s_def)\n\nlemma s_strict_mono:\n  assumes \"u < t\" \"t \\<le> t_stop\" \"u \\<ge> 0\"\n  shows \"s u < s t\"\n  using p_strict_mono[of u t] assms p_max[of u]\n  by (auto simp: s_def)\n\nlemma s_antimono:\n  assumes \"x \\<le> y\"\n  assumes \"t_stop \\<le> x\"\n  shows \"s y \\<le> s x\"\nproof -\n  from assms have \"t_stop \\<le> y\" by auto  \n  hence \"s y \\<le> p_max\" unfolding s_def p_max_eq\n    using p_max_def p_max_eq s0_le_s_stop s_t_stop by auto\n  also have \"... \\<le> s x\" \n    using \\<open>t_stop \\<le> x\\<close> s_mono s_t_stop t_stop_nonneg by fastforce\n  ultimately show \"s y \\<le> s x\" by auto\nqed\n\n\n\nlemma q_min: \"0 \\<le> t \\<Longrightarrow> s0 \\<le> q t\"\n  unfolding q_def\n  using nonneg_vel by auto\n\nlemma q_mono: \"x \\<le> y \\<Longrightarrow> q x \\<le> q y\"\n  unfolding q_def using nonneg_vel by (auto simp: mult_left_mono)\n\nsubsubsection \\<open>maximum at stopping time\\<close>\ntext \\<open>\\label{sec:tstop}\\<close>\nlemma s_max: \"s x \\<le> s_stop\"\n  using p_max[of x] p_max[of 0]\n  unfolding s_t_stop\n  by (auto simp: s_def)\n\nlemma s_eq_s_stop: \"NO_MATCH t_stop x \\<Longrightarrow> x \\<ge> t_stop \\<Longrightarrow> s x = s_stop\"\n  using t_stop_nonneg\n  by (auto simp: s_def p_max_def)\n\nend\n\nlocale safe_distance =\n  fixes a\\<^sub>e v\\<^sub>e s\\<^sub>e :: real\n  fixes a\\<^sub>o v\\<^sub>o s\\<^sub>o :: real\n  assumes nonneg_vel_ego   : \"0 \\<le> v\\<^sub>e\"\n  assumes nonneg_vel_other : \"0 \\<le> v\\<^sub>o\"\n  assumes decelerate_ego   : \"a\\<^sub>e < 0\"\n  assumes decelerate_other : \"a\\<^sub>o < 0\"\n  assumes in_front         : \"s\\<^sub>e < s\\<^sub>o\"\nbegin\n\nlemmas hyps =\n  nonneg_vel_ego   \n  nonneg_vel_other \n  decelerate_ego   \n  decelerate_other \n  in_front\n\nsublocale ego: braking_movement a\\<^sub>e v\\<^sub>e s\\<^sub>e by (unfold_locales; rule hyps)\nsublocale other: braking_movement a\\<^sub>o v\\<^sub>o s\\<^sub>o by (unfold_locales; rule hyps)\nsublocale ego_other: movement \"a\\<^sub>o - a\\<^sub>e\" \"v\\<^sub>o - v\\<^sub>e\" \"s\\<^sub>o - s\\<^sub>e\" by unfold_locales\n\nsubsubsection \\<open>collision\\<close>\ntext \\<open>\\label{sec:collision}\\<close>\ndefinition collision :: \"real set \\<Rightarrow> bool\" where\n\"collision time_set \\<equiv> (\\<exists>t\\<in>time_set. ego.s t = other.s t )\"\n\nabbreviation no_collision :: \"real set \\<Rightarrow> bool\" where\n\"no_collision time_set \\<equiv> \\<not> collision time_set\"\n\nlemma no_collision_initially : \"no_collision {.. 0}\"\n  using decelerate_ego nonneg_vel_ego\n  using decelerate_other nonneg_vel_other in_front\n  by (auto simp: divide_simps collision_def ego.s_def other.s_def)\n\nlemma\n  no_collisionI:\n  assumes \"\\<And>t. t \\<in> S \\<Longrightarrow> ego.s t \\<noteq> other.s t\"\n  shows \"no_collision S\"\n  using assms\n  unfolding collision_def\n  by blast\n\nsubsubsection \\<open>Theorem 1\\<close>\ntext \\<open>\\label{sec:thm1}\\<close>\n\n(* condition 1 : ego.s_stop < s\\<^sub>o *)\ntheorem cond_1 : \"ego.s_stop < s\\<^sub>o \\<Longrightarrow> no_collision {0..}\"\nproof (rule no_collisionI, simp)\n  fix t::real\n  assume \"t \\<ge> 0\"\n  have \"ego.s t \\<le> ego.s_stop\"\n    by (rule ego.s_max)\n  also assume \"\\<dots> < s\\<^sub>o\"\n  also have \"\\<dots> = other.s 0\"\n    by (simp add: other.init_s)\n  also have \"\\<dots> \\<le> other.s t\"\n    using \\<open>0 \\<le> t\\<close> hyps\n    by (intro other.s_mono) auto\n  finally show \"ego.s t \\<noteq> other.s t\"\n    by simp\nqed\n\nsubsubsection \\<open>Lemma 1\\<close>\ntext \\<open>\\label{sec:lemma1}\\<close>\n\nlemma ego_other_strict_ivt:\n  assumes \"ego.s t > other.s t\"\n  shows \"collision {0 ..< t}\"\nproof cases\n  assume \"0 \\<le> t\"\n  with assms in_front\n  have \"\\<exists>x\\<ge>0. x \\<le> t \\<and> other.s x - ego.s x = 0\"\n    by (intro IVT2)\n    (auto intro!: continuous_intros simp: ego_other.s_def ego.init_s other.init_s)\n  then show ?thesis\n    using assms\n    by (auto simp add: algebra_simps collision_def Bex_def order.order_iff_strict)\nqed (insert assms hyps, auto simp: collision_def ego.init_s other.init_s intro!: bexI[where x=0])\n\n\nlemma collision_subset: \"collision s \\<Longrightarrow> s \\<subseteq> t \\<Longrightarrow> collision t\"\n  by (auto simp: collision_def)\n\nlemma ego_other_ivt:\n  assumes \"ego.s t \\<ge> other.s t\"\n  shows \"collision {0 .. t}\"\nproof cases\n  assume \"ego.s t > other.s t\"\n  from ego_other_strict_ivt[OF this]\n  show ?thesis\n    by (rule collision_subset) auto\nqed (insert hyps assms; cases \"t \\<ge> 0\"; force simp: collision_def ego.init_s other.init_s)\n\n\nsubsubsection \\<open>Theorem 2\\<close>\ntext \\<open>\\label{sec:thm2}\\<close>\n\n(* condition 2: ego.s_stop \\<ge> other.s_stop *)\ntheorem cond_2 :\n  assumes \"ego.s_stop \\<ge> other.s_stop\"\n  shows \"collision {0 ..}\"\n  using assms\n  apply (intro collision_subset[where t=\"{0 ..}\" and s = \"{0 .. max ego.t_stop other.t_stop}\"])\n  apply (intro ego_other_ivt[where t = \"max ego.t_stop other.t_stop\"])\n  apply (auto simp: ego.s_eq_s_stop other.s_eq_s_stop)\n  done\n\nabbreviation D2 :: \"real\" where\n\"D2 \\<equiv> (v\\<^sub>o - v\\<^sub>e)^2 - 2 * (a\\<^sub>o - a\\<^sub>e) * (s\\<^sub>o - s\\<^sub>e)\"\n\nabbreviation  t\\<^sub>D' :: \"real\" where\n\"t\\<^sub>D' \\<equiv> sqrt (2 * (ego.s_stop - other.s_stop) / a\\<^sub>o)\"\n\nlemma\n  pos_via_half_dist:\n  \"dist a b < b / 2 \\<Longrightarrow> b > 0 \\<Longrightarrow> a > 0\"\n  by (auto simp: dist_real_def abs_real_def split: if_splits)\n\nsubsubsection \\<open>Lemma 2\\<close>\ntext \\<open>\\label{sec:lemma2}\\<close>\n\nlemma collision_within_p:\n  assumes \"s\\<^sub>o \\<le> ego.s_stop\" \"ego.s_stop < other.s_stop\"\n  shows \"collision {0..} \\<longleftrightarrow> (\\<exists>t\\<ge>0. ego.p t = other.p t \\<and> t < ego.t_stop \\<and> t < other.t_stop)\"\nproof (auto simp: collision_def, goal_cases)\n  case (2 t)\n  then show ?case\n    by (intro bexI[where x = t]) (auto simp: ego.s_def other.s_def)\nnext\n  case (1 t)\n  then show ?case using assms hyps ego.t_stop_nonneg other.t_stop_nonneg\n    apply (auto simp: ego.s_def other.s_def ego.s_t_stop other.s_t_stop ego.p_t_stop other.p_t_stop\n      split: if_splits)\n    defer\n    apply (auto simp: not_le)\n  proof goal_cases\n    case 1\n    from 1 have le: \"ego.t_stop \\<le> other.t_stop\" by auto\n    from 1 have \"ego.t_stop < t\" by simp\n    from other.s_strict_mono[OF this] 1\n    have \"other.s ego.t_stop < other.s t\"\n      by auto\n    also have \"\\<dots> = ego.s ego.t_stop\"\n      using ego.s_t_stop ego.t_stop_nonneg 1 other.s_def by auto\n    finally have \"other.s ego.t_stop < ego.s ego.t_stop\" .\n    from ego_other_strict_ivt[OF this] le in_front\n    show ?case\n      by (auto simp add: collision_def) (auto simp: movement.s_def split: if_splits)\n  next\n    case 2\n    from 2 have \"other.p_max = ego.p t\" by simp\n    also have \"\\<dots> \\<le> ego.p ego.t_stop\"\n      using 2\n      by (intro ego.p_mono) auto\n    also have \"\\<dots> = ego.p_max\"\n      by (simp add: ego.p_t_stop)\n    also note \\<open>\\<dots> < other.p_max\\<close>\n    finally show ?case by arith\n  next\n    case 3\n    thus ?case\n      apply (cases \"t = other.t_stop\")\n      apply (simp add: other.p_t_stop )\n      apply (metis (no_types) ego.p_max not_le)\n      apply (cases \"t = ego.t_stop\")\n      apply (simp add: ego.p_t_stop)\n      defer\n      apply force\n    proof goal_cases\n      case (1)\n      let ?d = \"\\<lambda>t. other.p' t - ego.p' t\"\n      def d' \\<equiv> \"?d ego.t_stop / 2\"\n      have d_cont: \"isCont ?d ego.t_stop\"\n        by (auto intro!: continuous_intros)\n      have \"?d ego.t_stop > 0\"\n        using 1\n        by (simp add: ego.p'_stop_zero other.p'_pos_iff) (simp add: ego.t_stop_def other.t_stop_def)\n      then have \"d' > 0\" by (auto simp: d'_def)\n      from d_cont[unfolded continuous_at_eps_delta, THEN spec, rule_format, OF \\<open>d' > 0\\<close>]\n      obtain e where e: \"e > 0\" \"\\<And>x. dist x ego.t_stop < e \\<Longrightarrow> ?d x > 0\"\n        unfolding d'_def\n        using \\<open>?d ego.t_stop > 0\\<close> pos_via_half_dist\n        by force\n      def t' \\<equiv> \"ego.t_stop - min (ego.t_stop / 2) (e / 2)\"\n      have \"0 < ego.t_stop\" using 1 by auto\n      have \"other.p t' - ego.p t' < other.p ego.t_stop - ego.p ego.t_stop\"\n        apply (rule DERIV_pos_imp_increasing[of t'])\n        apply (force simp: t'_def e min_def \\<open>0 < ego.t_stop\\<close>)\n        apply (auto intro!: exI[where x = \"?d x\" for x] intro!: derivative_intros e)\n        using \\<open>e > 0\\<close>\n        apply (auto simp: t'_def dist_real_def algebra_simps)\n        done\n      also have \"\\<dots> = 0\" using 1 by (simp add: ego.p_t_stop)\n      finally have less: \"other.p t' < ego.p t'\" by simp\n      have \"t' > 0\"\n        using 1 by (auto simp: t'_def algebra_simps min_def)\n      have \"t' < ego.t_stop\" by (auto simp: t'_def \\<open>e > 0\\<close> \\<open>ego.t_stop > 0\\<close>)\n      from less_le_trans[OF \\<open>t' < ego.t_stop\\<close> \\<open>ego.t_stop \\<le> other.t_stop\\<close>]\n      have \"t' < other.t_stop\" .\n      from ego_other_strict_ivt[of t'] less\n      have \"collision {0..<t'}\"\n        using \\<open>t' > 0\\<close> \\<open>t' < ego.t_stop\\<close> \\<open>t' < other.t_stop\\<close>\n        by (auto simp: other.s_def ego.s_def split: if_splits)\n      thus ?case\n        using \\<open>t' > 0\\<close> \\<open>t' < ego.t_stop\\<close> \\<open>t' < other.t_stop\\<close>\n        apply (auto simp: collision_def ego.s_def other.s_def movement.p_def\n          split: if_splits)\n        apply (rule_tac x = t in exI) apply (auto simp: movement.p_def)[]\n        done\n    qed\n  qed\nqed\n\nlemma collision_within_eq:\n  assumes \"s\\<^sub>o \\<le> ego.s_stop\" \"ego.s_stop < other.s_stop\"\n  shows \"collision {0..} \\<longleftrightarrow> collision {0 ..< min ego.t_stop other.t_stop}\"\n  unfolding collision_within_p[OF assms]\n  unfolding collision_def\n  by (safe;\n    force\n      simp: ego.s_def other.s_def movement.p_def ego.t_stop_def other.t_stop_def\n      split: if_splits)\n\nlemma collision_excluded: \"(\\<And>t. t \\<in> T \\<Longrightarrow> ego.s t \\<noteq> other.s t) \\<Longrightarrow> collision S \\<longleftrightarrow> collision (S - T)\"\n  by (auto simp: collision_def)\n\nlemma collision_within_less:\n  assumes \"s\\<^sub>o \\<le> ego.s_stop\" \"ego.s_stop < other.s_stop\"\n  shows \"collision {0..} \\<longleftrightarrow> collision {0 <..< min ego.t_stop other.t_stop}\"\nproof -\n  note collision_within_eq[OF assms]\n  also have \"collision {0 ..< min ego.t_stop other.t_stop} \\<longleftrightarrow>\n    collision ({0 ..< min ego.t_stop other.t_stop} - {0})\"\n    using hyps assms\n    by (intro collision_excluded) (auto simp: ego.s_def other.s_def)\n  also have \"{0 ..< min ego.t_stop other.t_stop} - {0} = {0 <..< min ego.t_stop other.t_stop}\"\n    by auto\n  finally show ?thesis \n    unfolding collision_def\n    by (safe;\n      force\n        simp: ego.s_def other.s_def movement.p_def ego.t_stop_def other.t_stop_def\n        split: if_splits)\nqed\n\nsubsubsection \\<open>Theorem 3\\<close>\ntext \\<open>\\label{sec:thm3}\\<close>\n\ntheorem cond_3 :\n  assumes \"s\\<^sub>o \\<le> ego.s_stop\" \"ego.s_stop < other.s_stop\"\n  shows \"collision {0..} \\<longleftrightarrow> (a\\<^sub>o > a\\<^sub>e \\<and> v\\<^sub>o < v\\<^sub>e \\<and> 0 \\<le> D2 \\<and> sqrt D2 > v\\<^sub>e - a\\<^sub>e / a\\<^sub>o * v\\<^sub>o)\"\nproof -\n  have \"v\\<^sub>o \\<noteq> 0\"\n    using assms(1) assms(2) movement.s_def movement.t_stop_def by auto\n  with hyps have \"v\\<^sub>o > 0\" by auto\n  note hyps = hyps this\n  def t1 \\<equiv> \"(- (v\\<^sub>o - v\\<^sub>e) + sqrt D2) / (a\\<^sub>o - a\\<^sub>e)\"\n  def t2 \\<equiv> \"(- (v\\<^sub>o - v\\<^sub>e) - sqrt D2) / (a\\<^sub>o - a\\<^sub>e)\"\n  def bounded \\<equiv> \"\\<lambda>t. (0 \\<le> t \\<and> t \\<le> ego.t_stop \\<and> t \\<le> other.t_stop)\"\n  have ego_other_conv:\n    \"\\<And>t. bounded t \\<Longrightarrow> ego.p t = other.p t \\<longleftrightarrow> ego_other.p t = 0\"\n    by (auto simp: movement.p_def algebra_simps divide_simps)\n  let ?r = \"{0 <..< min ego.t_stop other.t_stop}\"\n  have D2: \"D2 = (v\\<^sub>o - v\\<^sub>e)\\<^sup>2 - 4 * ((a\\<^sub>o - a\\<^sub>e) / 2) * (s\\<^sub>o - s\\<^sub>e)\" by simp\n  def D \\<equiv> D2\n  note D = D_def[symmetric]\n  def x1 \\<equiv> \"(- (v\\<^sub>o - v\\<^sub>e) + sqrt D2) / (2 * ((a\\<^sub>o - a\\<^sub>e) / 2))\"\n  def x2 \\<equiv> \"(- (v\\<^sub>o - v\\<^sub>e) - sqrt D2) / (2 * ((a\\<^sub>o - a\\<^sub>e) / 2))\"\n  have x2: \"x2 =(- (v\\<^sub>o - v\\<^sub>e) - sqrt D2) / (a\\<^sub>o - a\\<^sub>e)\"\n    by (simp add: x2_def divide_simps algebra_simps)\n  have x1: \"x1 =(- (v\\<^sub>o - v\\<^sub>e) + sqrt D2) / (a\\<^sub>o - a\\<^sub>e)\"\n    by (simp add: x1_def divide_simps algebra_simps)\n  from collision_within_less[OF assms]\n  have coll_eq: \"collision {0..} = collision ?r\"\n    by (auto simp add: bounded_def)\n  also have \"\\<dots> \\<longleftrightarrow> (a\\<^sub>o > a\\<^sub>e \\<and> v\\<^sub>o < v\\<^sub>e \\<and> 0 \\<le> D2 \\<and> sqrt D2 > v\\<^sub>e - a\\<^sub>e / a\\<^sub>o * v\\<^sub>o)\"\n  proof safe\n    assume H: \"a\\<^sub>e < a\\<^sub>o\" \"v\\<^sub>o < v\\<^sub>e\" \"0 \\<le> D2\"\n    assume sqrt: \"sqrt D2 > v\\<^sub>e - a\\<^sub>e / a\\<^sub>o * v\\<^sub>o\"\n    have nz: \"(a\\<^sub>o - a\\<^sub>e) / 2 \\<noteq> 0\" using \\<open>a\\<^sub>e < a\\<^sub>o\\<close> by simp\n    note sol = quadratic_eq_zeroes_iff[OF D2 x1_def[THEN meta_eq_to_obj_eq] x2_def[THEN meta_eq_to_obj_eq] nz]\n    from sol[of x2] \\<open>0 \\<le> D2\\<close>\n    have \"other.p x2 = ego.p x2\"\n      by (auto simp: ego.p_def other.p_def algebra_simps divide_simps)\n    moreover\n    have \"x2 > 0\"\n    proof (rule ccontr)\n      assume \"\\<not> 0 < x2\"\n      then have \"ego_other.p x2 \\<ge> ego_other.p 0\"\n        using H hyps\n        by (intro DERIV_nonpos_imp_nonincreasing[of x2]) \n          (auto intro!: exI[where x=\"ego_other.p' x\" for x] derivative_eq_intros\n            simp: ego_other.p'_def add_nonpos_nonpos mult_nonneg_nonpos)\n      also have \"ego_other.p 0 > 0\" using hyps by (simp add: ego_other.p_def)\n      finally (xtrans) show False using \\<open>other.p x2 = ego.p x2\\<close>\n        by (simp add: movement.p_def algebra_simps divide_simps power2_eq_square)\n    qed\n    moreover\n    have \"x2 < other.t_stop\"\n      using sqrt H hyps\n      by (auto simp: x2 other.t_stop_def divide_simps algebra_simps power2_eq_square)\n\n    ultimately\n    show \"collision {0<..<min ego.t_stop other.t_stop}\"\n    proof (cases \"x2 < ego.t_stop\", goal_cases)\n      case 2\n      then have \"other.s x2 = other.p x2\"\n        by (auto simp: other.s_def)\n      also from 2 have \"\\<dots> \\<le> ego.p ego.t_stop\"\n        by (auto intro!: ego.p_antimono)\n      also have \"\\<dots> = ego.s x2\"\n        using 2 by (auto simp: ego.s_def ego.p_t_stop)\n      finally have \"other.s x2 \\<le> ego.s x2\" .\n      from ego_other_ivt[OF this]\n      show ?thesis\n        unfolding coll_eq[symmetric]\n        by (rule collision_subset) auto\n    qed (auto simp: collision_def ego.s_def other.s_def not_le intro!: bexI[where x=x2])\n  next\n    let ?max = \"max ego.t_stop other.t_stop\"\n    let ?min = \"min ego.t_stop other.t_stop\"\n    assume \"collision ?r\"\n    then obtain t where t: \"ego.p t = other.p t\" \"0 < t\" \"t < ?min\"\n      by (auto simp: collision_def ego.s_def other.s_def)\n    then have \"t < - (v\\<^sub>e / a\\<^sub>e)\" \"t < - (v\\<^sub>o / a\\<^sub>o)\" \"t < other.t_stop\"\n      by (simp_all add: ego.t_stop_def other.t_stop_def)\n    from t have \"ego_other.p t = 0\"\n      by (auto simp: algebra_simps movement.p_def divide_simps)\n    from t have \"t < ?max\" by auto\n    from hyps assms have \"0 < ego_other.p 0\"\n      by simp\n    from ego_other.p_def[abs_def, THEN meta_eq_to_obj_eq]\n    have eop_eq: \"ego_other.p = (\\<lambda>t. 1 / 2 * (a\\<^sub>o - a\\<^sub>e) * t\\<^sup>2 + (v\\<^sub>o - v\\<^sub>e) * t + (s\\<^sub>o - s\\<^sub>e))\"\n      by (simp add: algebra_simps)\n    show \"a\\<^sub>o > a\\<^sub>e\"\n    proof -\n      have \"ego.p other.t_stop \\<le> ego.p_max\"\n        by (rule ego.p_max)\n      also have \"... \\<le> other.p other.t_stop\" using hyps assms\n        by (auto simp:other.s_def ego.s_def ego.p_t_stop split:if_splits)\n      finally have \"0 \\<le> ego_other.p other.t_stop\"\n        by (auto simp add:movement.p_def field_simps)\n      from p_convex[OF eop_eq, of 0 t other.t_stop, simplified \\<open>ego_other.p t = 0\\<close>,\n        OF \\<open>0 < t\\<close> \\<open>t < other.t_stop\\<close> \\<open>0 < ego_other.p 0\\<close> \\<open>0 \\<le> ego_other.p other.t_stop\\<close>]\n      show \"a\\<^sub>o > a\\<^sub>e\" by (simp add: algebra_simps)\n    qed\n    have rewr: \"4 * ((a\\<^sub>o - a\\<^sub>e) / 2) = 2 * (a\\<^sub>o - a\\<^sub>e)\" by simp\n    from \\<open>a\\<^sub>o > a\\<^sub>e\\<close> \\<open>ego_other.p t = 0\\<close> ego_other.p_all_zeroes[OF D2[symmetric], of t]\n    have \"0 \\<le> D2\" and disj: \"(t = (- (v\\<^sub>o - v\\<^sub>e) + sqrt D2) / (a\\<^sub>o - a\\<^sub>e) \\<or> t = (- (v\\<^sub>o - v\\<^sub>e) - sqrt D2) / (a\\<^sub>o - a\\<^sub>e))\"\n      using hyps assms\n      unfolding rewr by simp_all\n    show \"0 \\<le> D2\" by fact\n    from add_strict_mono[OF \\<open>t < - (v\\<^sub>e / a\\<^sub>e)\\<close> \\<open>t < - (v\\<^sub>o / a\\<^sub>o)\\<close>] `0 < t` \\<open>a\\<^sub>o > a\\<^sub>e\\<close>\n    have \"0 < - (v\\<^sub>e / a\\<^sub>e) + - (v\\<^sub>o / a\\<^sub>o)\" by (simp add: divide_simps)\n    then have \"0 > v\\<^sub>e * a\\<^sub>o + a\\<^sub>e * v\\<^sub>o\" using hyps\n      by (simp add: mult_less_0_iff divide_simps algebra_simps split: if_splits)\n    show \"v\\<^sub>o < v\\<^sub>e\"\n      using `a\\<^sub>e < a\\<^sub>o` `movement.p (a\\<^sub>o - a\\<^sub>e) (v\\<^sub>o - v\\<^sub>e) (s\\<^sub>o - s\\<^sub>e) t = 0` in_front  t(2)\n      apply (auto simp: movement.p_def divide_less_0_iff algebra_simps power2_eq_square)\n      by (smt divide_less_0_iff mult_le_cancel_right mult_mono mult_nonneg_nonneg nonneg_vel_ego)\n    from disj have \"x2 < ?min\"\n    proof rule\n      assume \"t = (- (v\\<^sub>o - v\\<^sub>e) - sqrt D2) / (a\\<^sub>o - a\\<^sub>e)\"\n      then show ?thesis\n        using \\<open>t < ?min\\<close>\n        by (simp add: x2)\n    next\n      assume \"t = (- (v\\<^sub>o - v\\<^sub>e) + sqrt D2) / (a\\<^sub>o - a\\<^sub>e)\"\n      also have \"\\<dots> \\<ge> x2\"\n        unfolding x2\n        apply (rule divide_right_mono)\n        apply (subst (2) diff_conv_add_uminus)\n        apply (rule add_left_mono)\n        using \\<open>a\\<^sub>o > a\\<^sub>e\\<close> \\<open>D2 \\<ge> 0\\<close>\n        by auto\n      also (xtrans) note \\<open>t < ?min\\<close>\n      finally show ?thesis .\n    qed\n    then show \"sqrt D2 > v\\<^sub>e - a\\<^sub>e / a\\<^sub>o * v\\<^sub>o\"\n      using hyps \\<open>a\\<^sub>o > a\\<^sub>e\\<close>\n      by (auto simp: x2 divide_simps algebra_simps other.t_stop_def)\n  qed\n  finally show ?thesis .\nqed\n\nthm cond_1 cond_2 cond_3\n\nsection{* Formalising the definition of safe distance *}\n\n(* First definition of safe distance which is based on cond_1 above *)\n\ndefinition \"absolute_safe_distance = - v\\<^sub>e\\<^sup>2 / (2 * a\\<^sub>e)\"\n\nlemma absolute_safe_distance:\n  assumes \"s\\<^sub>o - s\\<^sub>e > absolute_safe_distance\"\n  shows \"no_collision {0..}\"\n  proof -\n  from assms hyps absolute_safe_distance_def have \"ego.s_stop < s\\<^sub>o\" \n    by (auto simp add:ego.s_def ego.p_def ego.t_stop_def power_def)\n  thus ?thesis by (rule cond_1)\n  qed\n\n(* first definition of safe distance if absolute safe distance is not satisfied *)\ndefinition \"fst_safe_distance = v\\<^sub>o\\<^sup>2 / (2 * a\\<^sub>o) - v\\<^sub>e\\<^sup>2 / (2 * a\\<^sub>e)\"\n\n(* distance to ensure that sqrt D2 \\<le>  v\\<^sub>e - a\\<^sub>e / a\\<^sub>o * v\\<^sub>o*)\ndefinition \"distance_leq_d2 = (a\\<^sub>e + a\\<^sub>o) / (2 * a\\<^sub>o\\<^sup>2) * v\\<^sub>o\\<^sup>2 - v\\<^sub>o * v\\<^sub>e / a\\<^sub>o\"\n\nsubsubsection \\<open>Lemma 3\\<close>\ntext \\<open>\\label{sec:lemma3}\\<close>\n\nlemma snd_leq_fst_exp: \"distance_leq_d2 \\<le> fst_safe_distance\"\nproof -\n  have \"0 \\<le> (other.t_stop - ego.t_stop)\\<^sup>2\" by auto\n\n  -- \\<open>expanding the expression on the RHS\\<close>\n  hence \"- ego.t_stop\\<^sup>2 \\<le> other.t_stop\\<^sup>2 - 2 * other.t_stop * ego.t_stop\" by (simp add:power_def algebra_simps) \n  -- \\<open>multiply both sides with @{term \"a\\<^sub>e / 2\"}\\<close>\n  with hyps(3) have \"- ego.t_stop\\<^sup>2 * (a\\<^sub>e / 2) \\<ge> (other.t_stop\\<^sup>2 - 2 * other.t_stop * ego.t_stop) * (a\\<^sub>e / 2)\" \n    by (smt half_gt_zero_iff mult_le_cancel_right)\n\n  -- \\<open>simplifying both sides\\<close>\n  with ego.t_stop_def other.t_stop_def hyps \n  have \"- v\\<^sub>e\\<^sup>2 / (2 * a\\<^sub>e) \\<ge> a\\<^sub>e * v\\<^sub>o\\<^sup>2 / (2 * a\\<^sub>o\\<^sup>2) - v\\<^sub>o * v\\<^sub>e / a\\<^sub>o\" by (simp add:power_def algebra_simps)\n\n  -- \\<open>add both sides with the term @{term \"v\\<^sub>o\\<^sup>2 / (2 * a\\<^sub>o)\"}\\<close>\n  with fst_safe_distance_def distance_leq_d2_def\n  have 1: \"fst_safe_distance \\<ge>  a\\<^sub>e * v\\<^sub>o\\<^sup>2 / (2 * a\\<^sub>o\\<^sup>2) - v\\<^sub>o * v\\<^sub>e / a\\<^sub>o + v\\<^sub>o\\<^sup>2 / (2 * a\\<^sub>o)\" by (auto simp add:algebra_simps)\n\n  -- \\<open>prove that RHS is \\<open>snd_safe_distance\\<close>\\<close> \n  have \"a\\<^sub>e * v\\<^sub>o\\<^sup>2 / (2 * a\\<^sub>o\\<^sup>2) - v\\<^sub>o * v\\<^sub>e / a\\<^sub>o + v\\<^sub>o\\<^sup>2 / (2 * a\\<^sub>o) = distance_leq_d2\" (is \"?LHS = _\")\n  proof -\n    have \"?LHS = a\\<^sub>e * v\\<^sub>o\\<^sup>2 / (2 * a\\<^sub>o\\<^sup>2) - v\\<^sub>o * v\\<^sub>e / a\\<^sub>o + a\\<^sub>o * v\\<^sub>o\\<^sup>2 / (2 * a\\<^sub>o\\<^sup>2)\"  \n    by (auto simp add:algebra_simps power_def)\n    \n    also have \"...  = distance_leq_d2\" \n    by (auto simp add: algebra_simps power_def divide_simps distance_leq_d2_def)\n    \n    finally show ?thesis by auto    \n  qed\n  with 1 show ?thesis by auto\nqed  \n\nlemma sqrt_D2_leq_stop_time_diff:\n  assumes \"a\\<^sub>e < a\\<^sub>o\"\n  assumes \"0 \\<le> v\\<^sub>e - a\\<^sub>e / a\\<^sub>o * v\\<^sub>o \"\n  assumes \"s\\<^sub>o - s\\<^sub>e \\<ge> distance_leq_d2\"\n  shows \"sqrt D2 \\<le> v\\<^sub>e - a\\<^sub>e / a\\<^sub>o * v\\<^sub>o\"\nproof -\n  from assms have \"- 2 * (a\\<^sub>o - a\\<^sub>e) * (s\\<^sub>o - s\\<^sub>e) \\<le> - 2 * (a\\<^sub>o - a\\<^sub>e) * distance_leq_d2\" (is \"?L \\<le> ?R\") \n  by simp\n  hence \"D2 \\<le> (v\\<^sub>o - v\\<^sub>e)\\<^sup>2 - 2 * (a\\<^sub>o - a\\<^sub>e) * distance_leq_d2\" by (simp add:algebra_simps)\n  also have \"... = (v\\<^sub>e - a\\<^sub>e / a\\<^sub>o * v\\<^sub>o)\\<^sup>2\"\n  proof -\n    from distance_leq_d2_def\n    have 1: \"(v\\<^sub>o - v\\<^sub>e)\\<^sup>2 - 2 * (a\\<^sub>o - a\\<^sub>e) * distance_leq_d2 = \n             (v\\<^sub>o - v\\<^sub>e)\\<^sup>2 - (a\\<^sub>o - a\\<^sub>e) * (a\\<^sub>e + a\\<^sub>o) / a\\<^sub>o\\<^sup>2 * v\\<^sub>o\\<^sup>2 + 2 * (a\\<^sub>o - a\\<^sub>e) * v\\<^sub>o * v\\<^sub>e / a\\<^sub>o\"\n    -- \\<open>expanding the subtrahend\\<close>\n    by (auto simp add:algebra_simps divide_simps)\n    with hyps(4) have \"... = (v\\<^sub>e - a\\<^sub>e / a\\<^sub>o * v\\<^sub>o)\\<^sup>2\"\n    -- \\<open>expanding the minuend, simplifying terms, and regrouping into quadratic terms\\<close>\n    by (auto simp add:algebra_simps power_def divide_simps)\n    with 1 show ?thesis by auto\n  qed\n  finally show ?thesis  by (smt assms(2) real_le_lsqrt real_sqrt_le_0_iff)\nqed\n\nlemma cond2_imp_pos_vo:\n  assumes \"s\\<^sub>o \\<le> ego.s_stop\" \"ego.s_stop < other.s_stop\"\n  shows \"v\\<^sub>o \\<noteq> 0\"\nproof (rule ccontr)\n  assume \"\\<not> v\\<^sub>o \\<noteq> 0\"\n  with other.s_def other.t_stop_def have \"other.s_stop = s\\<^sub>o\" by auto\n  with assms(2) have \"ego.s_stop < s\\<^sub>o\" by auto\n  with assms(1) show \"False\" by auto\nqed\n\nlemma cond2_imp_gt_fst_sd:\n  assumes \"s\\<^sub>o \\<le> ego.s_stop\" \"ego.s_stop < other.s_stop\"\n  shows \"fst_safe_distance < s\\<^sub>o - s\\<^sub>e\"\nproof (cases \"v\\<^sub>e \\<noteq> 0\")\n  case True\n  from fst_safe_distance_def assms ego.s_def ego.t_stop_pos[OF \\<open>v\\<^sub>e \\<noteq> 0\\<close>] ego.p_def ego.t_stop_def\n       other.s_def other.t_stop_pos[OF cond2_imp_pos_vo[OF assms]] other.p_def other.t_stop_def hyps\n  show ?thesis by (simp add:power_def algebra_simps)\nnext\n  case False\n  with fst_safe_distance_def  have \"fst_safe_distance = v\\<^sub>o\\<^sup>2 / (2 * a\\<^sub>o)\" by auto\n  also have \"... \\<le> 0\"  by (simp add: divide_nonneg_neg hyps)\n  also have \"... < s\\<^sub>o - s\\<^sub>e\" by (simp add:algebra_simps hyps)\n  finally show ?thesis by auto\nqed\n\ndefinition \"snd_safe_distance = (v\\<^sub>o - v\\<^sub>e)\\<^sup>2 / (2 * (a\\<^sub>o - a\\<^sub>e))\"\n\nlemma fst_leq_snd_safe_distance:\n  assumes \"a\\<^sub>e < a\\<^sub>o\"\n  shows\"fst_safe_distance \\<le> snd_safe_distance\"\nproof -\n  have \"0 \\<le> (v\\<^sub>o / a\\<^sub>o - v\\<^sub>e / a\\<^sub>e)\\<^sup>2\" by auto\n  hence 1: \"0 \\<le> (v\\<^sub>o / a\\<^sub>o)\\<^sup>2 - 2 * v\\<^sub>o * v\\<^sub>e / (a\\<^sub>o * a\\<^sub>e) + (v\\<^sub>e / a\\<^sub>e)\\<^sup>2\" by (auto simp add:power_def algebra_simps)\n  from hyps have \"0 \\<le> a\\<^sub>o * a\\<^sub>e\"  by (simp add: mult_nonpos_nonpos)  \n  from mult_right_mono[OF 1 this] hyps\n  have \"0 \\<le> v\\<^sub>o\\<^sup>2 * a\\<^sub>e / a\\<^sub>o - 2 * v\\<^sub>o * v\\<^sub>e  + v\\<^sub>e\\<^sup>2 * a\\<^sub>o / a\\<^sub>e\" by (auto simp add:power_def algebra_simps)\n  with hyps have 2: \"(v\\<^sub>o\\<^sup>2 / (2 * a\\<^sub>o) - v\\<^sub>e\\<^sup>2 / (2 * a\\<^sub>e)) * (2 * (a\\<^sub>o - a\\<^sub>e)) \\<le> (v\\<^sub>o - v\\<^sub>e)\\<^sup>2\" by (auto simp add:power_def divide_simps algebra_simps)\n  from assms have \"0 \\<le> 2 * (a\\<^sub>o - a\\<^sub>e)\" by auto\n  from divide_right_mono[OF 2 this] assms fst_safe_distance_def snd_safe_distance_def\n  show ?thesis by auto\nqed\n\n\n\nlemma t_stop_diff_neg_means_leq_D2:\n  assumes \"s\\<^sub>o \\<le> ego.s_stop\" \"ego.s_stop < other.s_stop\" \"a\\<^sub>e < a\\<^sub>o\" \"0 \\<le> D2\"\n  shows \"v\\<^sub>e - a\\<^sub>e / a\\<^sub>o * v\\<^sub>o < 0 \\<longleftrightarrow> sqrt D2 > v\\<^sub>e - a\\<^sub>e / a\\<^sub>o * v\\<^sub>o\"\nproof\n  assume only_if: \"v\\<^sub>e - a\\<^sub>e / a\\<^sub>o * v\\<^sub>o < 0\"\n  from assms have \"... \\<le> sqrt D2\" by auto\n  with only_if show \"v\\<^sub>e - a\\<^sub>e / a\\<^sub>o * v\\<^sub>o < sqrt D2\" by linarith\nnext\n  assume if_part: \"v\\<^sub>e - a\\<^sub>e / a\\<^sub>o * v\\<^sub>o < sqrt D2\"\n  from cond2_imp_gt_fst_sd[OF assms(1) assms(2)] snd_leq_fst_exp have \"distance_leq_d2 \\<le> s\\<^sub>o - s\\<^sub>e\" by auto\n  from if_part and sqrt_D2_leq_stop_time_diff [OF \\<open>a\\<^sub>e < a\\<^sub>o\\<close> _ \\<open>distance_leq_d2 \\<le> s\\<^sub>o - s\\<^sub>e\\<close>]\n  show \" v\\<^sub>e - a\\<^sub>e / a\\<^sub>o * v\\<^sub>o < 0\"  by linarith\nqed\n\n\n\n    from t_stop_diff_neg_means_leq_D2[OF assms \\<open>a\\<^sub>e < a\\<^sub>o\\<close>]\n    have \"... = (a\\<^sub>e < a\\<^sub>o \\<and> v\\<^sub>o < v\\<^sub>e \\<and> 0 \\<le> D2 \\<and> sqrt D2 > v\\<^sub>e - a\\<^sub>e / a\\<^sub>o * v\\<^sub>o)\" by auto\n\n    with 1 cond_3[OF assms] show ?thesis by blast\n  qed\nqed\n\nlemma \"v\\<^sub>e - a\\<^sub>e / a\\<^sub>o * v\\<^sub>o < 0 \\<longleftrightarrow> ego.t_stop < other.t_stop\"\n  unfolding \"ego.t_stop_def\" \"other.t_stop_def\"\n  using hyps\n  by (auto simp add:algebra_simps divide_simps)\n\ndefinition \"d t =\n  (if t \\<le> 0 then s\\<^sub>o - s\\<^sub>e\n  else if t \\<le> ego.t_stop \\<and> t \\<le> other.t_stop then ego_other.p t\n  else if ego.t_stop \\<le> t \\<and> t \\<le> other.t_stop then other.p t - ego.s_stop\n  else if other.t_stop \\<le> t \\<and> t \\<le> ego.t_stop then other.s_stop - ego.p t\n  else other.s_stop - ego.s_stop)\"\n\nlemma d_diff: \"d t = other.s t - ego.s t\"\n  by (auto simp: d_def ego.s_eq_s_stop other.s_eq_s_stop ego.s_cond_def other.s_cond_def\n    movement.p_def divide_simps algebra_simps)\n\nlemma collision_d: \"collision S \\<longleftrightarrow> (\\<exists>t\\<in>S. d t = 0)\"\n  by (force simp: d_diff collision_def )\n\nlemma collision_restrict: \"collision {0..} \\<longleftrightarrow> collision {0..max ego.t_stop other.t_stop}\"  \n  by (auto simp: max.coboundedI1 ego.t_stop_nonneg min_def\n    ego.s_eq_s_stop other.s_eq_s_stop collision_def\n    intro!: bexI[where x = \"min t (max (movement.t_stop a\\<^sub>e v\\<^sub>e) (movement.t_stop a\\<^sub>o v\\<^sub>o))\" for t])\n\nlemma collision_union: \"collision (A \\<union> B) \\<longleftrightarrow> collision A \\<or> collision B\"\n  by (auto simp: collision_def)\n\nsubsubsection \\<open>Theorem 4\\<close>\ntext \\<open>\\label{sec:thm4}\\<close>\n\nlemma symbolic_checker:\n  \"collision {0..} \\<longleftrightarrow>\n    (quadroot_in 0 (min ego.t_stop other.t_stop) (1/2 * (a\\<^sub>o - a\\<^sub>e)) (v\\<^sub>o - v\\<^sub>e) (s\\<^sub>o - s\\<^sub>e)) \\<or>\n    (quadroot_in ego.t_stop other.t_stop (1/2 * a\\<^sub>o) v\\<^sub>o (s\\<^sub>o - ego.s_stop)) \\<or>\n    (quadroot_in other.t_stop ego.t_stop (1/2 * a\\<^sub>e) v\\<^sub>e (s\\<^sub>e - other.s_stop))\"\n (is \"_ \\<longleftrightarrow> ?q1 \\<or> ?q2 \\<or> ?q3\")\nproof -\n  have *: \"{0..max ego.t_stop other.t_stop} =\n    {0 .. min ego.t_stop other.t_stop} \\<union> {ego.t_stop .. other.t_stop} \\<union> {other.t_stop .. ego.t_stop}\"\n    using ego.t_stop_nonneg other.t_stop_nonneg\n    by auto\n  have \"collision {0..min (movement.t_stop a\\<^sub>e v\\<^sub>e) (movement.t_stop a\\<^sub>o v\\<^sub>o)} = ?q1\"\n    by (force simp: collision_def quadroot_in_def root_in_def d_def\n      algebra_simps power2_eq_square divide_simps movement.p_def movement.s_cond_def)\n  moreover\n  have \"collision {ego.t_stop .. other.t_stop} = ?q2\"\n    using ego.t_stop_nonneg\n    by (force simp: collision_def quadroot_in_def root_in_def d_def\n      ego.s_eq_s_stop movement.s_cond_def movement.p_def)\n  moreover\n  have \"collision {other.t_stop .. ego.t_stop} = ?q3\"\n    using other.t_stop_nonneg\n    by (force simp: collision_def quadroot_in_def root_in_def d_def\n      other.s_eq_s_stop movement.s_cond_def movement.p_def)\n  ultimately\n  show ?thesis\n    unfolding collision_restrict * collision_union\n    by auto\nqed\n\nend\n\nsubsection \\<open>Extending Analysis with a reaction time delay\\<close>\n                                    \nlocale safe_distance_normal = safe_distance +\n  fixes \\<delta> :: real\n  assumes pos_react         : \"0 < \\<delta>\"\nbegin\n\nsublocale ego2: braking_movement a\\<^sub>e v\\<^sub>e \"(ego.q \\<delta>)\" ..\n\nlemma ego2_s_init: \"ego2.s 0 = ego.q \\<delta>\" unfolding ego2.s_def by auto\n\ndefinition \"\\<tau>  (t::real) = t - \\<delta>\"\ndefinition \"\\<tau>' (t::real) = 1\"\n\nlemma \\<tau>_continuous[continuous_intros]: \"continuous_on T \\<tau>\"\n  by (auto intro!: continuous_intros simp:\\<tau>_def)\n\nlemma isCont_\\<tau>[continuous_intros]: \"isCont \\<tau> x\"\n  using \\<tau>_continuous[of UNIV]\n  by (auto simp:continuous_on_eq_continuous_at)\n\nlemma del_has_vector_derivative[derivative_intros]: \"(\\<tau> has_vector_derivative \\<tau>' t) (at t within u)\"\n  by (auto simp: \\<tau>_def[abs_def] \\<tau>'_def has_vector_derivative_def algebra_simps\n          intro!: derivative_eq_intros)\n                                                             \nlemma del_has_real_derivative[derivative_intros]: \"(\\<tau> has_real_derivative \\<tau>' t) (at t within u)\"\n  using del_has_vector_derivative\n  by (simp add:has_field_derivative_iff_has_vector_derivative)\n\nlemma delay_image: \"\\<tau> ` {\\<delta>..} = {0..}\"\nproof (rule subset_antisym, unfold image_def, unfold \\<tau>_def)\n  show \"{y. \\<exists>x\\<in>{\\<delta>..}. y = x - \\<delta>} \\<subseteq> {0..}\" by auto\nnext\n  show \"{0..} \\<subseteq> {y. \\<exists>x\\<in>{\\<delta>..}. y = x - \\<delta>}\"\n  proof (rule subsetI)\n    fix a\n    assume \"(a::real) \\<in> {0..}\"\n    hence \"0 \\<le> a\" by simp\n    hence \"\\<exists>x\\<in>{\\<delta>..}. a = x - \\<delta>\" using bexI[where x = \"a + \\<delta>\"] by auto\n    thus \"a \\<in> {y. \\<exists>x\\<in>{\\<delta>..}. y = x - \\<delta>}\" by auto\n  qed\nqed\n\nlemma s_delayed_has_real_derivative[derivative_intros]:\n  assumes \"\\<delta> \\<le> t\"\n  shows \"((ego2.s \\<circ> \\<tau>) has_field_derivative ego2.s' (t - \\<delta>) * \\<tau>' t) (at t within {\\<delta>..})\"\nproof (rule DERIV_image_chain)\n  from assms have 0: \"0 \\<le> t - \\<delta>\" by simp\n  from ego2.t_stop_nonneg have 1: \"v\\<^sub>e / a\\<^sub>e \\<le> 0\" unfolding ego2.t_stop_def by simp\n  from ego2.decel have 2: \"a\\<^sub>e \\<noteq> 0\" by simp\n  show \"(ego2.s has_real_derivative ego2.s' (t - \\<delta>)) (at (\\<tau> t) within \\<tau> ` {\\<delta>..})\"\n  using ego2.s_has_real_derivative[OF 0 1 2] sym[OF delay_image]\n  unfolding \\<tau>_def by simp\nnext\n  from del_has_real_derivative show \"(\\<tau> has_real_derivative \\<tau>' t) (at t within {\\<delta>..})\" \n  by auto\nqed\n\nlemma s_delayed_has_real_derivative' [derivative_intros]:\n  assumes \"\\<delta> \\<le> t\"\n  shows \"((ego2.s \\<circ> \\<tau>) has_field_derivative (ego2.s' \\<circ> \\<tau>) t) (at t within {\\<delta>..})\"\nproof -\n  from s_delayed_has_real_derivative[OF assms] have\n  \"((ego2.s \\<circ> \\<tau>) has_field_derivative ego2.s' (t - \\<delta>) * \\<tau>' t) (at t within {\\<delta>..})\"\n  by auto\n  hence \"((ego2.s \\<circ> \\<tau>) has_field_derivative ego2.s' (t - \\<delta>) * 1) (at t within {\\<delta>..})\"\n  using \\<tau>'_def[of t] by metis\n  hence \"((ego2.s \\<circ> \\<tau>) has_field_derivative ego2.s' (t - \\<delta>)) (at t within {\\<delta>..})\"\n  by (simp add:algebra_simps)  \n  thus ?thesis unfolding comp_def \\<tau>_def by auto\nqed\n\nlemma s_delayed_has_vector_derivative' [derivative_intros]:\n  assumes \"\\<delta> \\<le> t\"\n  shows \"((ego2.s \\<circ> \\<tau>) has_vector_derivative (ego2.s' \\<circ> \\<tau>) t) (at t within {\\<delta>..})\"\n  using s_delayed_has_real_derivative'[OF assms]\n  by (simp add:has_field_derivative_iff_has_vector_derivative)\n  \ndefinition \n  \"u t = (     if t \\<le> 0 then s\\<^sub>e\n          else if t \\<le> \\<delta> then ego.q t \n          else          (ego2.s \\<circ> \\<tau>) t)\"\n\nlemma init_u: \"t \\<le> 0 \\<Longrightarrow> u t = s\\<^sub>e\" unfolding u_def by auto\n\nlemma u_delta: \"u \\<delta> = ego2.s 0\"\nproof -  \n  have \"u \\<delta> = ego.q \\<delta>\" using pos_react unfolding u_def by auto\n  also have \"... = ego2.s 0\" unfolding ego2.s_def by auto\n  finally show \"u \\<delta> = ego2.s 0\" .\nqed\n\nlemma q_delta: \"ego.q \\<delta> = ego2.s 0\" using u_delta pos_react unfolding u_def by auto\n\ndefinition \n  \"u' t = (if t \\<le> \\<delta> then ego.q' t else ego2.s' (t - \\<delta>))\"\n\nlemma u'_delta: \"u' \\<delta> = ego2.s' 0\"\nproof -\n  have \"u' \\<delta> = ego.q' \\<delta>\" unfolding u'_def by auto\n  also have \"... = v\\<^sub>e\" unfolding ego2.q'_def by simp\n  also have \"... = ego2.p' 0\" unfolding ego2.p'_def by simp\n  also have \"... = ego2.s' 0\" using ego2.t_stop_nonneg unfolding ego2.s'_def by auto \n  finally show \"u' \\<delta> = ego.s' 0\" .\nqed\n\nlemma q'_delta: \"ego.q' \\<delta> = ego2.s' 0\" using u'_delta unfolding u'_def by auto\n\nlemma u_has_real_derivative[derivative_intros]:\n  assumes nonneg_t: \"t \\<ge> 0\"\n  shows \"(u has_real_derivative u' t) (at t within {0..})\"\nproof -\n  from pos_react have \"0 \\<le> \\<delta>\" by simp\n\n  have temp: \"((\\<lambda>t. if t \\<in> {0 .. \\<delta>} then ego.q t else (ego2.s \\<circ> \\<tau>) t) has_real_derivative\n    (if t \\<in> {0..\\<delta>} then ego.q' t else (ego2.s' \\<circ> \\<tau>) t)) (at t within {0..})\" (is \"(?f1 has_real_derivative ?f2) (?net)\")\n    unfolding u_def[abs_def] u'_def \n      has_field_derivative_iff_has_vector_derivative\n    apply (rule has_vector_derivative_If[where t = \"{\\<delta>..}\"])\n    using \\<open>0 \\<le> \\<delta>\\<close> q_delta q'_delta ego.s_has_vector_derivative[OF assms] ego.decel ego.t_stop_nonneg \n    s_delayed_has_vector_derivative'[of \"t\"] \\<tau>_def\n    unfolding comp_def\n    by (auto simp: assms  max_def insert_absorb   \n      intro!: ego.q_has_vector_derivative)\n  show ?thesis\n    unfolding has_vector_derivative_def has_field_derivative_iff_has_vector_derivative\n      u'_def u_def[abs_def] \n    proof (rule has_derivative_transform[where f=\"(\\<lambda>t. if t \\<in> {0..\\<delta>} then ego.q t else (ego2.s \\<circ> \\<tau>) t)\"])\n      from nonneg_t show \" t \\<in> {0..}\" by auto\n    next\n      fix x\n      assume \"(x::real) \\<in> {0..}\"\n      hence  \"x \\<le> \\<delta> \\<longleftrightarrow> x \\<in> {0 .. \\<delta>}\" by simp\n      thus  \" (if x \\<le> 0 then s\\<^sub>e else if x \\<le> \\<delta> then ego.q x else (ego2.s \\<circ> \\<tau>) x) =\n         (if x \\<in> {0..\\<delta>} then ego.q x else (ego2.s \\<circ> \\<tau>) x)\" using pos_react unfolding ego.q_def by auto\n    next\n      from temp have \"(?f1 has_vector_derivative ?f2) ?net\"\n      using has_field_derivative_iff_has_vector_derivative by auto      \n      moreover with assms have \"t \\<in> {0 .. \\<delta>} \\<longleftrightarrow> t \\<le> \\<delta>\" by auto\n      ultimately show \" ((\\<lambda>t. if t \\<in> {0..\\<delta>} then ego.q t else (ego2.s \\<circ> \\<tau>) t) has_derivative\n              (\\<lambda>x. x *\\<^sub>R (if t \\<le> \\<delta> then ego2.q' t else ego2.s' (t - \\<delta>)))) (at t within {0..})\" \n      unfolding comp_def \\<tau>_def has_vector_derivative_def by auto\n    qed \nqed\n\ndefinition t_stop :: real where \"t_stop = ego2.t_stop + \\<delta>\"\n\nlemma t_stop_nonneg: \"0 \\<le> t_stop\"\n  unfolding t_stop_def\n  using ego2.t_stop_nonneg pos_react\n  by auto\n\nlemma t_stop_pos: \"0 < t_stop\"\n  unfolding t_stop_def\n  using ego2.t_stop_nonneg pos_react\n  by auto\n\nlemma t_stop_zero:\n  assumes \"t_stop \\<le> x\"\n  assumes \"x \\<le> \\<delta>\"\n  shows \"v\\<^sub>e = 0\"\n  using assms unfolding t_stop_def using ego2.t_stop_nonneg pos_react ego2.t_stop_zero by auto\n\nlemma u'_stop_zero: \"u' t_stop = 0\" \n  unfolding u'_def t_stop_def ego2.q'_def ego2.s'_def\n  using ego2.t_stop_nonneg ego2.p'_stop_zero decelerate_ego ego2.t_stop_zero by auto\n\ndefinition u_max :: real where \"u_max = u (ego2.t_stop + \\<delta>)\"\n\nlemma u_max_eq: \"u_max = ego.q \\<delta> - v\\<^sub>e\\<^sup>2 / a\\<^sub>e / 2\"\nproof (cases \"ego2.t_stop = 0\")\n  assume \"ego2.t_stop = 0\"\n  hence \"v\\<^sub>e = 0\" using ego2.t_stop_zero by simp\n  with \\<open>ego2.t_stop = 0\\<close> show \"u_max = ego.q \\<delta> - v\\<^sub>e\\<^sup>2 / a\\<^sub>e / 2\"  unfolding u_max_def u_def using pos_react by auto\nnext\n  assume \"ego2.t_stop \\<noteq> 0\"\n  hence \"u_max = (ego2.s \\<circ> \\<tau>) (ego2.t_stop + \\<delta>)\" \n    unfolding u_max_def u_def  using ego2.t_stop_nonneg pos_react by auto \n  moreover have \"... = ego2.s ego2.t_stop\" unfolding comp_def \\<tau>_def by auto\n  moreover have \"... = ego2.p_max\" \n    unfolding ego2.s_def ego2.p_max_def using \\<open>ego2.t_stop \\<noteq> 0\\<close> ego2.t_stop_nonneg by auto\n  moreover have \"... = ego.q \\<delta> - v\\<^sub>e\\<^sup>2 / a\\<^sub>e / 2\" using ego2.p_max_eq .\n  ultimately show ?thesis by auto\nqed\n\nlemma u_mono: assumes \"x \\<le> y\" and \"y \\<le> t_stop\" \n              shows \"u x \\<le> u y\"\nproof -\n  have \"y \\<le> 0 \\<or> (0 < y \\<and> y \\<le> \\<delta>) \\<or> \\<delta> < y\" by auto\n\n  moreover\n  { assume \"y \\<le> 0\"\n    with assms have \"x \\<le> 0\" by auto\n    with \\<open>y \\<le> 0\\<close> have \"u x \\<le> u y\" unfolding u_def by auto }\n\n  moreover\n  { assume \"0 < y \\<and> y \\<le> \\<delta>\"\n    with assms have \"x \\<le> \\<delta>\" by auto\n    hence \"u x \\<le> u y\" \n    proof (cases \"x \\<le> 0\")\n      assume \"x \\<le> 0\"\n      with \\<open>x \\<le> \\<delta>\\<close> and \\<open>0 < y \\<and> y \\<le> \\<delta>\\<close> show \"u x \\<le> u y\"  unfolding u_def using ego.q_min by auto\n    next\n      assume \"\\<not> x \\<le> 0\"\n      with \\<open>0 < y \\<and> y \\<le> \\<delta>\\<close> and assms show \"u x \\<le> u y\" \n        unfolding u_def  using ego.q_mono by auto\n    qed }\n  \n  moreover\n  { assume \"\\<delta> < y\"\n    have \"u x \\<le> u y\"\n    proof (cases \"\\<delta> < x\")\n      assume \"\\<delta> < x\" \n      with pos_react have \"\\<not> x \\<le> 0\" by auto\n      moreover from \\<open>\\<delta> < y\\<close> and pos_react have \"\\<not> y \\<le> 0\" by auto\n      ultimately show \"u x \\<le> u y\"  unfolding u_def comp_def \n        using assms ego2.s_mono[of \"x - \\<delta>\" \"y - \\<delta>\"] \\<open>\\<delta> < y\\<close> \\<open>\\<delta> < x\\<close> by (auto simp:\\<tau>_def)\n    next\n      assume \"\\<not> \\<delta> < x\"\n      hence \"x \\<le> \\<delta>\" by simp\n      hence \"u x \\<le> ego.q \\<delta>\" unfolding u_def using pos_react nonneg_vel_ego\n        by (auto simp add:ego.q_def mult_left_mono)\n      also have \"... = ego2.s (\\<tau> \\<delta>)\" unfolding ego2.s_def unfolding \\<tau>_def by auto\n      also have \"... \\<le> ego2.s (\\<tau> y)\" unfolding \\<tau>_def using \\<open>\\<delta> < y\\<close> by (auto simp add:ego2.s_mono)\n      also have \"... = u y\" unfolding u_def using \\<open>\\<delta> < y\\<close> pos_react by auto     \n      ultimately show \"u x \\<le> u y\" by auto\n    qed }\n  \n  ultimately show \"u x \\<le> u y\" by auto\nqed\n\nlemma u_antimono: \"x \\<le> y \\<Longrightarrow> t_stop \\<le> x \\<Longrightarrow> u y \\<le> u x\"\nproof -\n  assume 1: \"x \\<le> y\"\n  assume 2: \"t_stop \\<le> x\"\n  hence \"\\<delta> \\<le> x\" unfolding \\<tau>_def t_stop_def using pos_react ego2.t_stop_nonneg by auto\n  with 1 have \"\\<delta> \\<le> y\" by auto\n  from 1 and 2 have 3: \"t_stop \\<le> y\" by auto\n  show \"u y \\<le> u x\"\n  proof (cases \"x \\<noteq> \\<delta> \\<and> y \\<noteq> \\<delta>\")\n    assume \"x \\<noteq> \\<delta> \\<and> y \\<noteq> \\<delta>\"\n    hence \"x \\<noteq> \\<delta>\" and \"y \\<noteq> \\<delta>\" by auto\n    have \"u y \\<le> (ego2.s \\<circ> \\<tau>) y\" unfolding u_def using \\<open>\\<delta> \\<le> y\\<close> \\<open>y \\<noteq> \\<delta>\\<close> pos_react by auto\n    also have \"... \\<le> (ego2.s \\<circ> \\<tau>) x\" unfolding comp_def\n    proof (intro ego2.s_antimono)\n      show \"\\<tau> x \\<le> \\<tau> y\" unfolding \\<tau>_def using \\<open>x \\<le> y\\<close> by auto\n    next\n      show \"ego2.t_stop \\<le> \\<tau> x\" unfolding \\<tau>_def using \\<open>t_stop \\<le> x\\<close> by (auto simp: t_stop_def)\n    qed\n    also have \"... \\<le> u x\" unfolding u_def using \\<open>\\<delta> \\<le> x\\<close>\\<open>x \\<noteq> \\<delta>\\<close> pos_react by auto\n    ultimately show \"u y \\<le> u x\" by auto\n  next\n    assume \"\\<not> (x \\<noteq> \\<delta> \\<and> y \\<noteq> \\<delta>)\"\n    have \"x \\<noteq> \\<delta> \\<longrightarrow> y \\<noteq> \\<delta>\"\n    proof (rule impI; erule contrapos_pp[where Q=\"\\<not> x = \\<delta>\"])\n      assume \"\\<not> y \\<noteq> \\<delta>\"\n      hence \"y = \\<delta>\" by simp\n      with \\<open>t_stop \\<le> y\\<close> have \"ego2.t_stop = 0\" unfolding t_stop_def \n        using ego2.t_stop_nonneg by auto\n      with \\<open>t_stop \\<le> x\\<close> have \"x = \\<delta>\" unfolding t_stop_def using \\<open>x \\<le> y\\<close> \\<open>y = \\<delta>\\<close> by auto\n      thus \"\\<not> x \\<noteq> \\<delta>\" by auto\n    qed\n    with \\<open>\\<not> (x \\<noteq> \\<delta> \\<and> y \\<noteq> \\<delta>)\\<close> have \"(x = \\<delta> \\<and> y = \\<delta>) \\<or> (x = \\<delta>)\" by auto\n    \n    moreover\n    { assume \"x = \\<delta> \\<and> y = \\<delta>\"\n      hence \"x = \\<delta>\" and \"y = \\<delta>\" by auto\n      hence \"u y \\<le> ego.q \\<delta>\" unfolding u_def using pos_react by auto\n      also have \"... \\<le> u x\" unfolding u_def using \\<open>x = \\<delta>\\<close> pos_react by auto\n      ultimately have \"u y \\<le> u x\" by auto }\n\n    moreover\n    { assume \"x = \\<delta>\" \n      hence \"ego2.t_stop = 0\" using \\<open>t_stop \\<le> x\\<close> ego2.t_stop_nonneg by (auto simp:t_stop_def)\n      hence \"v\\<^sub>e = 0\" by (rule ego2.t_stop_zero)\n      hence \"u y \\<le> ego.q \\<delta>\"\n        using pos_react \\<open>x = \\<delta>\\<close> \\<open>x \\<le> y\\<close> \\<open>v\\<^sub>e = 0\\<close>\n        unfolding u_def comp_def \\<tau>_def ego2.s_def ego2.p_def ego2.p_max_def ego2.t_stop_def \n        by auto\n      also have \"... \\<le> u x\" using \\<open>x = \\<delta>\\<close> pos_react unfolding u_def by auto       \n      ultimately have \"u y \\<le> u x\" by auto }\n\n    ultimately show ?thesis by auto\n  qed\nqed\n\nlemma u_max: \"u x \\<le> u_max\" \n  unfolding u_max_def using t_stop_def        \n  by (cases \"x \\<le> t_stop\") (auto intro: u_mono u_antimono)\n\nlemma u_eq_u_stop: \"NO_MATCH t_stop x \\<Longrightarrow> x \\<ge> t_stop \\<Longrightarrow> u x = u_max\"\nproof -\n  assume \"t_stop \\<le> x\"\n  with t_stop_pos have \"0 < x\" by auto\n  from \\<open>t_stop \\<le> x\\<close> have \"\\<delta> \\<le> x\" unfolding t_stop_def using ego2.t_stop_nonneg by auto\n  show  \"u x = u_max\"\n  proof (cases \"x \\<le> \\<delta>\")\n    assume \"x \\<le> \\<delta>\" \n    with \\<open>t_stop \\<le> x\\<close> have \"v\\<^sub>e = 0\" by (rule t_stop_zero)\n    also have \"x = \\<delta>\" using \\<open>x \\<le> \\<delta>\\<close> and \\<open>\\<delta> \\<le> x\\<close> by auto\n    ultimately have \"u x = ego.q \\<delta>\" unfolding u_def using pos_react by auto\n    also have \"... = u_max\" unfolding u_max_eq using \\<open>v\\<^sub>e = 0\\<close> by auto\n    ultimately show \"u x = u_max\" by simp\n  next\n    assume \"\\<not> x \\<le> \\<delta>\"\n    hence \"\\<delta> < x\" by auto\n    hence \"u x = (ego2.s \\<circ> \\<tau>) x\" unfolding u_def using pos_react by auto\n    also have \"... = ego2.s ego2.t_stop\" \n      proof (unfold comp_def; unfold \\<tau>_def; intro order.antisym)\n        have \"x - \\<delta> \\<ge> ego2.t_stop\" using \\<open>t_stop \\<le> x\\<close> unfolding t_stop_def by auto\n        thus \"ego2.s (x - \\<delta>) \\<le> ego2.s ego2.t_stop\" by (rule ego2.s_antimono) simp\n      next\n        thm ego2.s_mono\n        have \"x - \\<delta> \\<ge> ego2.t_stop\" using \\<open>t_stop \\<le> x\\<close> unfolding t_stop_def by auto\n        thus \"ego2.s ego2.t_stop \\<le> ego2.s (x - \\<delta>)\" using ego2.t_stop_nonneg by (rule ego2.s_mono)\n      qed\n    also have \"... = u_max\" unfolding u_max_eq ego2.s_t_stop ego2.p_max_eq by auto\n    ultimately show \"u x = u_max\" by auto\n  qed\nqed\n\nlemma at_least_delta:\n  assumes \"x \\<le> \\<delta>\"\n  assumes \"t_stop \\<le> x\"\n  shows \"ego.q x = ego2.s (x - \\<delta>)\"\n  using assms ego2.t_stop_nonneg \n  unfolding t_stop_def ego2.s_def by smt\n\nlemma continuous_on_u[continuous_intros]: \"continuous_on T u\"\n  unfolding u_def[abs_def]\n  using t_stop_nonneg pos_react at_least_delta\n  proof (intro continuous_on_subset[where t=T and s = \"{..0} \\<union> ({0..\\<delta>} \\<union> ({\\<delta> .. t_stop} \\<union> {t_stop ..}))\"] continuous_on_If continuous_intros)\n    fix x\n    assume \" \\<not> x \\<le> \\<delta>\"\n    assume \"x \\<in> {0..\\<delta>}\"\n    hence \"0 \\<le> x\" and \"x \\<le> \\<delta>\" by auto\n    thus \"ego.q x = (ego2.s \\<circ> \\<tau>) x\" \n      unfolding comp_def \\<tau>_def ego2.s_def \n      using \\<open>\\<not> x \\<le> \\<delta>\\<close> by auto\n  next\n    fix x\n    assume \"x \\<in> {\\<delta>..t_stop} \\<union> {t_stop..}\"\n    hence \"\\<delta> \\<le> x\" unfolding t_stop_def using pos_react ego.t_stop_nonneg by auto\n    also assume \"x \\<le> \\<delta>\"\n    ultimately have \"x = \\<delta>\" by auto\n    thus \"ego.q x = (ego2.s \\<circ> \\<tau>) x\" unfolding comp_def \\<tau>_def ego2.s_def by auto\n  next\n    fix t::real\n    assume \"t \\<in> {.. 0}\"\n    hence \"t \\<le> 0\" by auto\n    also assume \"\\<not> t \\<le> 0\"\n    ultimately have \"t = 0\" by auto\n    hence \"s\\<^sub>e = ego.q t\" unfolding ego.q_def by auto\n    with pos_react \\<open>t = 0\\<close> show \"s\\<^sub>e = (if t \\<le> \\<delta> then ego.q t else (ego2.s \\<circ> \\<tau>) t)\" by auto\n  next\n    fix t::real\n    assume \"t \\<in> {0..\\<delta>} \\<union> ({\\<delta>..t_stop} \\<union> {t_stop..})\"\n    hence \"0 \\<le> t\" using pos_react ego2.t_stop_nonneg by (auto simp: t_stop_def)\n    also assume \"t \\<le> 0\"\n    ultimately have \"t = 0\" by auto\n    hence \" s\\<^sub>e = (if t \\<le> \\<delta> then ego.q t else (ego2.s \\<circ> \\<tau>) t)\" using pos_react ego.init_q by auto\n    thus \"s\\<^sub>e = (if t \\<le> \\<delta> then ego.q t else (ego2.s \\<circ> \\<tau>) t)\" by auto\n  next\n    show \"T \\<subseteq> {..0} \\<union> ({0..\\<delta>} \\<union> ({\\<delta>..t_stop} \\<union> {t_stop..}))\" by auto  \n  qed\n\nlemma isCont_u[continuous_intros]: \"isCont u x\"\n  using continuous_on_u[of UNIV]\n  by (auto simp:continuous_on_eq_continuous_at)\n\ndefinition collision_react :: \"real set \\<Rightarrow> bool\" where\n\"collision_react time_set \\<equiv> (\\<exists>t\\<in>time_set. u t = other.s t )\"\n\nabbreviation no_collision_react :: \"real set \\<Rightarrow> bool\" where\n\"no_collision_react time_set \\<equiv> \\<not> collision_react time_set\"\n\nlemma\n  no_collision_reactI:\n  assumes \"\\<And>t. t \\<in> S \\<Longrightarrow> u t \\<noteq> other.s t\"\n  shows \"no_collision_react S\"\n  using assms\n  unfolding collision_react_def\n  by blast\n\nlemma \n  no_collision_union:\n  assumes \"no_collision_react S\"\n  assumes \"no_collision_react T\"\n  shows \"no_collision_react (S \\<union> T)\"\n  using assms\n  unfolding collision_react_def\n  by auto\n\nlemma collision_trim_subset:\n  assumes \"collision_react S\"\n  assumes \"no_collision_react T\"\n  assumes \"T \\<subseteq> S\"\n  shows \"collision_react (S - T)\"\n  using assms\n  unfolding collision_react_def by auto\n\ntheorem cond_1r : \"u_max < s\\<^sub>o \\<Longrightarrow> no_collision_react {0..}\"\nproof (rule no_collision_reactI, simp)\n  fix t :: real\n  assume \"0 \\<le> t\"\n  have \"u t \\<le> u_max\" by (rule u_max)\n  also assume \"... < s\\<^sub>o\"\n  also have \"... = other.s 0\"\n    by (simp add: other.init_s)\n  also have \"... \\<le> other.s t\"\n    using \\<open>0 \\<le> t\\<close> hyps\n    by (intro other.s_mono) auto\n  finally show \"u t \\<noteq> other.s t\"\n    by simp\nqed\n\ndefinition safe_distance_1r:: real where \"safe_distance_1r = v\\<^sub>e * \\<delta> - v\\<^sub>e\\<^sup>2 / a\\<^sub>e / 2\"\n\nlemma sd_1r_eq: \"(s\\<^sub>o - s\\<^sub>e > safe_distance_1r) = (u_max < s\\<^sub>o)\"\nproof -\n  have \"(s\\<^sub>o - s\\<^sub>e > safe_distance_1r) = (s\\<^sub>o - s\\<^sub>e > v\\<^sub>e * \\<delta> - v\\<^sub>e\\<^sup>2 / a\\<^sub>e / 2)\" unfolding safe_distance_1r_def by auto\n  moreover have \"... = (s\\<^sub>e + v\\<^sub>e * \\<delta> - v\\<^sub>e\\<^sup>2 / a\\<^sub>e / 2 < s\\<^sub>o)\" by auto\n  ultimately show ?thesis using u_max_eq ego.q_def by auto\nqed\n  \nlemma sd_1r_correct:\n  assumes \"s\\<^sub>o - s\\<^sub>e > safe_distance_1r\"\n  shows \"no_collision_react {0..}\"\nproof -\n  from assms have \"u_max < s\\<^sub>o\" using sd_1r_eq by auto\n  thus ?thesis by (rule cond_1r)  \nqed\n\nlemma u_other_strict_ivt:\n  assumes \"u t > other.s t\"\n  shows \"collision_react {0..<t}\"\nproof cases\n  assume \"0 \\<le> t\"\n  with assms in_front\n  have \"\\<exists>x\\<ge>0. x \\<le> t \\<and> other.s x - u x = 0\"\n    by (intro IVT2)\n    (auto intro!: continuous_intros simp: init_u other.init_s)\n  then show ?thesis\n    using assms\n    by (auto simp add:algebra_simps collision_react_def Bex_def order.order_iff_strict)\nqed(insert assms hyps, auto simp: collision_react_def init_u other.init_s)\n\nlemma collision_react_subset: \"collision_react s \\<Longrightarrow> s \\<subseteq> t \\<Longrightarrow> collision_react t\"\n  by (auto simp:collision_react_def) \n\nlemma u_other_ivt:\n  assumes \"u t \\<ge> other.s t\"\n  shows \"collision_react {0 .. t}\"\nproof cases\n  assume \"u t > other.s t\"\n  from u_other_strict_ivt[OF this]\n  show ?thesis\n    by (rule collision_react_subset) auto\nqed (insert hyps assms; cases \"t \\<ge> 0\"; force simp: collision_react_def init_u other.init_s)\n\n\ntheorem cond_2r:\n  assumes \"u_max \\<ge> other.s_stop\"             \n  shows \"collision_react {0 ..}\"\n  using assms\n  apply(intro collision_react_subset[where t=\"{0..}\" and s =\"{0 .. max t_stop other.t_stop}\"])\n  apply(intro u_other_ivt[where t =\"max t_stop other.t_stop\"])\n  apply(auto simp: u_eq_u_stop other.s_eq_s_stop)\n  done\n\ndefinition ego_other2 :: \"real \\<Rightarrow> real\" where\n  \"ego_other2 t = other.s t - u t\"\n\nlemma continuous_on_ego_other2[continuous_intros]: \"continuous_on T ego_other2\"\n  unfolding ego_other2_def[abs_def]\n  by (intro continuous_intros)\n\nlemma isCont_ego_other2[continuous_intros]: \"isCont ego_other2 x\"\n  using continuous_on_ego_other2[of UNIV]\n  by (auto simp: continuous_on_eq_continuous_at)\n\ndefinition ego_other2' :: \"real \\<Rightarrow> real\" where\n  \"ego_other2' t  = other.s' t - u' t\"\n\nlemma ego_other2_has_real_derivative[derivative_intros]: \n  assumes \"0 \\<le> t\"\n  shows \"(ego_other2 has_real_derivative ego_other2' t) (at t within {0..})\"\n  using assms other.t_stop_nonneg decelerate_other\n  unfolding other.t_stop_def\n  by (auto simp: ego_other2_def[abs_def] ego_other2'_def  algebra_simps\n           intro!: derivative_eq_intros)\n\ntheorem cond_3r_1:\n  assumes \"u \\<delta> \\<ge> other.s \\<delta>\"\n  shows \"collision_react {0 .. \\<delta>}\"\n  proof (unfold collision_react_def) \n  have 1: \"\\<exists>t\\<ge>0. t \\<le> \\<delta> \\<and> ego_other2 t = 0\"\n    proof (intro IVT2)\n      show \"ego_other2 \\<delta> \\<le> 0\" unfolding ego_other2_def using assms by auto\n    next\n      show \"0 \\<le> ego_other2 0\" unfolding ego_other2_def \n        using other.init_s[of 0] init_u[of 0] in_front by auto\n    next\n      show \"0 \\<le> \\<delta>\" using pos_react by auto\n    next\n      show \"\\<forall>t. 0 \\<le> t \\<and> t \\<le> \\<delta> \\<longrightarrow> isCont ego_other2 t\" \n        using isCont_ego_other2 by auto\n    qed\n    then obtain t where \"0 \\<le> t \\<and> t \\<le> \\<delta> \\<and> ego_other2 t = 0\" by auto\n    hence \"t \\<in> {0 .. \\<delta>}\" and \"u t = other.s t\" unfolding ego_other2_def by auto\n    thus \"\\<exists>t\\<in>{0..\\<delta>}. u t = other.s t\" by (intro bexI)    \n  qed\n    \ndefinition distance0 :: real where \"distance0 =  v\\<^sub>e * \\<delta> - v\\<^sub>o * \\<delta> - a\\<^sub>o * \\<delta>\\<^sup>2 / 2\"    \ndefinition distance0_2 :: real where \"distance0_2 = v\\<^sub>e * \\<delta> + 1 / 2 * v\\<^sub>o\\<^sup>2 / a\\<^sub>o\"    \n\ntheorem cond_3r_1':\n  assumes \"s\\<^sub>o - s\\<^sub>e \\<le> distance0\"\n  assumes \"\\<delta> \\<le> other.t_stop\"  \n  shows \"collision_react {0 .. \\<delta>}\"\nproof -\n  from assms have \"u \\<delta> \\<ge> other.s \\<delta>\" unfolding distance0_def other.s_def \n    other.p_def u_def ego.q_def using pos_react by auto    \n  thus ?thesis using cond_3r_1 by auto\nqed\n  \ntheorem distance0_2_eq: \n  assumes \"\\<delta> > other.t_stop\"\n  shows \"(u \\<delta> < other.s \\<delta>) = (s\\<^sub>o - s\\<^sub>e > distance0_2)\"\nproof -\n  from assms have \"(u \\<delta> < other.s \\<delta>) = (ego.q \\<delta> < other.p_max)\"\n    using u_def other.s_def pos_react by auto\n  also have \"... = (s\\<^sub>e + v\\<^sub>e * \\<delta> < s\\<^sub>o + v\\<^sub>o * (- v\\<^sub>o / a\\<^sub>o) + 1 / 2 * a\\<^sub>o * (- v\\<^sub>o / a\\<^sub>o)\\<^sup>2)\" \n    using ego.q_def other.p_max_def other.p_def other.t_stop_def by auto\n  also have \"... = (v\\<^sub>e * \\<delta> - v\\<^sub>o * (- v\\<^sub>o / a\\<^sub>o) - 1 / 2 * a\\<^sub>o * (- v\\<^sub>o / a\\<^sub>o)\\<^sup>2 < s\\<^sub>o - s\\<^sub>e)\" by linarith\n  also have \"... = (v\\<^sub>e * \\<delta> + v\\<^sub>o\\<^sup>2 / a\\<^sub>o - 1 / 2 * v\\<^sub>o\\<^sup>2 / a\\<^sub>o < s\\<^sub>o - s\\<^sub>e)\"\n    using other.p_def other.p_max_def other.p_max_eq other.t_stop_def by auto\n  also have \"... = (v\\<^sub>e * \\<delta> + 1 / 2 * v\\<^sub>o\\<^sup>2 / a\\<^sub>o < s\\<^sub>o - s\\<^sub>e)\" by linarith\n  thus ?thesis using distance0_2_def by (simp add: calculation)\nqed\n\n\n\nlemma distance0_at_most_sd4r:\n  assumes \"a\\<^sub>o > a\\<^sub>e\"\n  shows \"distance0 \\<le> safe_distance_4r\"\nproof -\n  from assms have \"a\\<^sub>o \\<ge> a\\<^sub>e\" by auto\n  have \"0 \\<le> (v\\<^sub>o + a\\<^sub>o * \\<delta> - v\\<^sub>e)\\<^sup>2 / (2 * a\\<^sub>o - 2 * a\\<^sub>e)\"\n    by (rule divide_nonneg_nonneg) (auto simp add:assms `a\\<^sub>e \\<le> a\\<^sub>o`)  \n  thus ?thesis unfolding distance0_def safe_distance_4r_def\n    by auto      \nqed    \n  \ndefinition safe_distance_2r::real where \"safe_distance_2r = v\\<^sub>e * \\<delta> - v\\<^sub>e\\<^sup>2 / 2 / a\\<^sub>e + v\\<^sub>o\\<^sup>2 / 2 / a\\<^sub>o\"\n  \nlemma vo_start_geq_ve:\n  assumes \"\\<delta> \\<le> other.t_stop\"\n  assumes \"other.s' \\<delta> \\<ge> v\\<^sub>e\"  \n  shows \"u \\<delta> < other.s \\<delta>\"    \nproof -\n    from assms have \"v\\<^sub>e \\<le> v\\<^sub>o + a\\<^sub>o * \\<delta>\" unfolding other.s'_def other.p'_def by auto\n    with  mult_right_mono[OF this, of \"\\<delta>\"] have \"v\\<^sub>e * \\<delta> \\<le> v\\<^sub>o * \\<delta> + a\\<^sub>o * \\<delta>\\<^sup>2\" (is \"?l0 \\<le> ?r0\")\n      using pos_react by (auto simp add:field_simps power_def)\n    hence \"s\\<^sub>e + ?l0 \\<le> s\\<^sub>e + ?r0\" by auto\n    also have \"... < s\\<^sub>o + ?r0\" using in_front by auto\n    also have \"... < s\\<^sub>o + v\\<^sub>o * \\<delta> + a\\<^sub>o * \\<delta>\\<^sup>2 / 2\" using decelerate_other pos_react by auto\n    finally show ?thesis using pos_react assms(1) \n      unfolding u_def ego.q_def other.s_def other.t_stop_def other.p_def by auto \nqed\n  \ntheorem so_star_stop_leq_se_stop:\n  assumes \"\\<delta> \\<le> other.t_stop\"\n  assumes \"other.s' \\<delta> < v\\<^sub>e\"\n  assumes \"\\<not> (a\\<^sub>o > a\\<^sub>e \\<and> other.s' \\<delta> < v\\<^sub>e \\<and> v\\<^sub>e - a\\<^sub>e / a\\<^sub>o * other.s' \\<delta> < 0)\"    \n  shows \"0 \\<le> - v\\<^sub>e\\<^sup>2 / a\\<^sub>e / 2 + (v\\<^sub>o + a\\<^sub>o * \\<delta>)\\<^sup>2 / a\\<^sub>o / 2\"\nproof -\n  consider \"v\\<^sub>e - a\\<^sub>e / a\\<^sub>o * other.s' \\<delta> \\<ge> 0\" | \"\\<not> (v\\<^sub>e - a\\<^sub>e / a\\<^sub>o * other.s' \\<delta> \\<ge> 0)\" by auto\n  thus ?thesis\n  proof (cases)\n    case 1\n    hence \"v\\<^sub>e - a\\<^sub>e / a\\<^sub>o * (v\\<^sub>o + a\\<^sub>o * \\<delta>) \\<ge> 0\" unfolding other.s'_def other.p'_def \n      by (auto simp add:assms(1))\n    hence \"v\\<^sub>e - a\\<^sub>e / a\\<^sub>o * v\\<^sub>o - a\\<^sub>e * \\<delta> \\<ge> 0\" (is \"?l0 \\<ge> 0\") using decelerate_other \n      by (auto simp add:field_simps)\n    hence \"?l0 / a\\<^sub>e \\<le> 0\" using divide_right_mono_neg[OF `?l0 \\<ge> 0`] decelerate_ego by auto \n    hence \"0 \\<ge> v\\<^sub>e / a\\<^sub>e - v\\<^sub>o / a\\<^sub>o - \\<delta>\" using decelerate_ego by (auto simp add:field_simps)\n    hence *: \"- v\\<^sub>e / a\\<^sub>e \\<ge> - (v\\<^sub>o + a\\<^sub>o * \\<delta>) / a\\<^sub>o\" using decelerate_other by (auto simp add:field_simps)     \n    from assms have **: \"v\\<^sub>o + a\\<^sub>o * \\<delta> \\<le> v\\<^sub>e\" unfolding other.s'_def other.p'_def by auto\n    have vo_star_nneg: \"v\\<^sub>o + a\\<^sub>o * \\<delta> \\<ge> 0\" \n    proof -\n      from assms(1) have \"- v\\<^sub>o \\<le> a\\<^sub>o * \\<delta>\" unfolding other.t_stop_def using decelerate_other\n        by (auto simp add:field_simps)\n      thus ?thesis by auto                \n    qed\n    from mult_mono[OF * ** _ `0 \\<le> v\\<^sub>o + a\\<^sub>o * \\<delta>`] \n    have \"- (v\\<^sub>o + a\\<^sub>o * \\<delta>) / a\\<^sub>o * (v\\<^sub>o + a\\<^sub>o * \\<delta>) \\<le> - v\\<^sub>e / a\\<^sub>e * v\\<^sub>e\" using nonneg_vel_ego decelerate_ego\n      by (auto simp add:field_simps)\n    hence \"- (v\\<^sub>o + a\\<^sub>o * \\<delta>)\\<^sup>2 / a\\<^sub>o \\<le> - v\\<^sub>e\\<^sup>2 / a\\<^sub>e \" by (auto simp add: field_simps power_def)\n    thus ?thesis by (auto simp add:field_simps)        \n  next\n    case 2\n    with assms have \"a\\<^sub>o \\<le> a\\<^sub>e\" by auto\n    from assms(2) have \"(v\\<^sub>o + a\\<^sub>o * \\<delta>) \\<le> v\\<^sub>e\" unfolding other.s'_def using assms unfolding other.p'_def\n      by auto   \n    have vo_star_nneg: \"v\\<^sub>o + a\\<^sub>o * \\<delta> \\<ge> 0\" \n    proof -\n      from assms(1) have \"- v\\<^sub>o \\<le> a\\<^sub>o * \\<delta>\" unfolding other.t_stop_def using decelerate_other\n        by (auto simp add:field_simps)\n      thus ?thesis by auto                \n    qed\n    with mult_mono[OF `v\\<^sub>o + a\\<^sub>o * \\<delta> \\<le> v\\<^sub>e` `v\\<^sub>o + a\\<^sub>o * \\<delta> \\<le> v\\<^sub>e`] have *: \"(v\\<^sub>o + a\\<^sub>o * \\<delta>)\\<^sup>2 \\<le> v\\<^sub>e\\<^sup>2\"\n      using nonneg_vel_ego by (auto simp add:power_def)\n    from `a\\<^sub>o \\<le> a\\<^sub>e` have \"- 1 /a\\<^sub>o \\<le> - 1 / a\\<^sub>e\" using decelerate_ego decelerate_other\n      by (auto simp add:field_simps)        \n    from mult_mono[OF * this] have \"(v\\<^sub>o + a\\<^sub>o * \\<delta>)\\<^sup>2 * (- 1 / a\\<^sub>o) \\<le> v\\<^sub>e\\<^sup>2 * (- 1 / a\\<^sub>e)\"\n      using nonneg_vel_ego decelerate_other by (auto simp add:field_simps)        \n    then show ?thesis by auto\n  qed    \nqed\n  \ntheorem distance0_at_most_distance2r:\n  assumes \"\\<delta> \\<le> other.t_stop\"\n  assumes \"other.s' \\<delta> < v\\<^sub>e\"\n  assumes \"\\<not> (a\\<^sub>o > a\\<^sub>e \\<and> other.s' \\<delta> < v\\<^sub>e \\<and> v\\<^sub>e - a\\<^sub>e / a\\<^sub>o * other.s' \\<delta> < 0)\"\n  shows \"distance0 \\<le> safe_distance_2r\"\nproof -\n  from so_star_stop_leq_se_stop[OF assms] have \" 0 \\<le> - v\\<^sub>e\\<^sup>2 / a\\<^sub>e / 2 + (v\\<^sub>o + a\\<^sub>o * \\<delta>)\\<^sup>2 / a\\<^sub>o / 2 \" (is \"0 \\<le> ?term\")\n    by auto\n  have \"safe_distance_2r = v\\<^sub>e * \\<delta> - v\\<^sub>e\\<^sup>2 / 2 / a\\<^sub>e + v\\<^sub>o\\<^sup>2 / 2 / a\\<^sub>o\" unfolding safe_distance_2r_def by auto\n  also have \"... = v\\<^sub>e * \\<delta> - v\\<^sub>e\\<^sup>2 / 2 / a\\<^sub>e + (v\\<^sub>o + a\\<^sub>o * \\<delta>)\\<^sup>2 / 2 / a\\<^sub>o - v\\<^sub>o * \\<delta> - a\\<^sub>o * \\<delta>\\<^sup>2 / 2\"\n    using decelerate_other by (auto simp add:field_simps power_def)\n  also have \"... = v\\<^sub>e * \\<delta> - v\\<^sub>o * \\<delta> - a\\<^sub>o * \\<delta>\\<^sup>2 / 2 + ?term\" (is \"_ = ?left + ?term\") \n    by (auto simp add:field_simps)      \n  finally have \"safe_distance_2r = distance0 + ?term\" unfolding distance0_def by auto\n  with `0 \\<le> ?term` show \"distance0 \\<le> safe_distance_2r\" by auto      \nqed\n  \ntheorem dist0_sd2r_1:\n  assumes \"\\<delta> \\<le> other.t_stop\"\n  assumes \"\\<not> (a\\<^sub>o > a\\<^sub>e \\<and> other.s' \\<delta> < v\\<^sub>e \\<and> v\\<^sub>e - a\\<^sub>e / a\\<^sub>o * other.s' \\<delta> < 0)\"\n  assumes \"s\\<^sub>o - s\\<^sub>e > safe_distance_2r\"\n  shows \"s\\<^sub>o - s\\<^sub>e > distance0\"\nproof (cases \"other.s' \\<delta> \\<ge> v\\<^sub>e\")\n  assume \"v\\<^sub>e \\<le> other.s' \\<delta>\" \n  from vo_start_geq_ve[OF assms(1) this] have \"u \\<delta> < other.s \\<delta>\" by auto\n  thus ?thesis unfolding distance0_def u_def using pos_react assms(1) unfolding ego.q_def \n    other.s_def other.p_def by auto\nnext\n  assume \"\\<not> v\\<^sub>e \\<le> other.s' \\<delta>\"\n  hence \"v\\<^sub>e > other.s' \\<delta>\" by auto\n  from distance0_at_most_distance2r[OF assms(1) this assms(2)] have \"distance0 \\<le> safe_distance_2r\"\n    by auto\n  with assms(3) show ?thesis by auto  \nqed  \n\ntheorem sd2r_eq: \n  assumes \"\\<delta> > other.t_stop\"\n  shows \"(u_max < other.s \\<delta>) = (s\\<^sub>o - s\\<^sub>e > safe_distance_2r)\"\nproof -\n  from assms have \"(u_max < other.s \\<delta>) = (ego2.s (- v\\<^sub>e / a\\<^sub>e) < other.p_max)\"\n    using u_max_def ego2.t_stop_def u_def other.s_def \\<tau>_def pos_react ego2.p_max_eq ego2.s_t_stop u_max_eq by auto\n  also have \"... = (s\\<^sub>e + v\\<^sub>e * \\<delta> + v\\<^sub>e * (- v\\<^sub>e / a\\<^sub>e) + 1 / 2 * a\\<^sub>e * (- v\\<^sub>e / a\\<^sub>e)\\<^sup>2 < s\\<^sub>o + v\\<^sub>o * (- v\\<^sub>o / a\\<^sub>o) + 1 / 2 * a\\<^sub>o * (- v\\<^sub>o / a\\<^sub>o)\\<^sup>2)\" \n    using ego2.s_def ego2.p_def ego.q_def other.p_max_def other.p_def other.t_stop_def ego2.p_max_def ego2.s_t_stop ego2.t_stop_def by auto\n  also have \"... = (v\\<^sub>e * \\<delta> + v\\<^sub>e * (- v\\<^sub>e / a\\<^sub>e) + 1 / 2 * a\\<^sub>e * (- v\\<^sub>e / a\\<^sub>e)\\<^sup>2 - v\\<^sub>o * (- v\\<^sub>o / a\\<^sub>o) - 1 / 2 * a\\<^sub>o * (- v\\<^sub>o / a\\<^sub>o)\\<^sup>2 < s\\<^sub>o  - s\\<^sub>e)\" by linarith\n  also have \"... = (v\\<^sub>e * \\<delta> - v\\<^sub>e\\<^sup>2 / a\\<^sub>e + 1 / 2 * v\\<^sub>e\\<^sup>2 / a\\<^sub>e + v\\<^sub>o\\<^sup>2 / a\\<^sub>o - 1 / 2 * v\\<^sub>o\\<^sup>2 / a\\<^sub>o < s\\<^sub>o  - s\\<^sub>e)\"\n    using ego2.p_def ego2.p_max_def ego2.p_max_eq ego2.t_stop_def other.p_def other.p_max_def other.p_max_eq other.t_stop_def by auto\n  also have \"... = (v\\<^sub>e * \\<delta> - v\\<^sub>e\\<^sup>2 / 2 / a\\<^sub>e + v\\<^sub>o\\<^sup>2 / 2 / a\\<^sub>o  < s\\<^sub>o - s\\<^sub>e)\" by linarith\n  thus ?thesis using distance0_2_def by (simp add: calculation safe_distance_2r_def)\nqed  \n  \n    \ntheorem dist0_sd2r_2:\n  assumes \"\\<delta> > - v\\<^sub>o / a\\<^sub>o\"\n  assumes \"s\\<^sub>o - s\\<^sub>e > safe_distance_2r\"\n  shows \"s\\<^sub>o - s\\<^sub>e > distance0_2\"\nproof -\n  have \"- v\\<^sub>e\\<^sup>2 / 2 / a\\<^sub>e \\<ge> 0\" using zero_le_power2 hyps(3) divide_nonneg_neg by (auto simp add:field_simps)\n  hence \"v\\<^sub>e * \\<delta> - v\\<^sub>e\\<^sup>2 / 2 / a\\<^sub>e + v\\<^sub>o\\<^sup>2 / 2 / a\\<^sub>o \\<ge> v\\<^sub>e * \\<delta> + v\\<^sub>o\\<^sup>2 / 2 / a\\<^sub>o\" by simp\n  hence \"safe_distance_2r \\<ge> distance0_2\" using safe_distance_2r_def distance0_2_def by auto\n  thus ?thesis using assms(2)  by linarith\nqed      \nend\n  \nlocale safe_distance_no_collsion_delta = safe_distance_normal +\nassumes no_collision_delta: \"u \\<delta> < other.s \\<delta>\"\nbegin\n  \nsublocale delayed_safe_distance: safe_distance a\\<^sub>e v\\<^sub>e \"ego.q \\<delta>\" a\\<^sub>o \"other.s' \\<delta>\" \"other.s \\<delta>\"\n  proof (unfold_locales)\n    from nonneg_vel_ego show \"0 \\<le> v\\<^sub>e\" by auto\n  next\n    from nonneg_vel_other show \"0 \\<le> other.s' \\<delta>\" unfolding other.s'_def other.p'_def other.t_stop_def\n      using decelerate_other by (auto simp add:algebra_simps divide_simps)\n  next\n    from decelerate_ego show \"a\\<^sub>e < 0\" by auto\n  next\n    from decelerate_other show \"a\\<^sub>o < 0\" by auto\n  next\n    from no_collision_delta show \"ego.q \\<delta> < other.s \\<delta>\" unfolding u_def using pos_react by auto\n  qed\n\nlemma no_collision_react_initially_strict:\n  assumes \"s\\<^sub>o \\<le> u_max\"\n  assumes \"u_max < other.s_stop\"\n  shows \"no_collision_react {0 <..< \\<delta>}\"\nproof (rule no_collision_reactI)\n  fix t::real\n  assume \"t \\<in> {0 <..< \\<delta>}\" \n  show \"u t \\<noteq> other.s t\"\n  proof (rule ccontr)\n    assume \"\\<not> u t \\<noteq> other.s t\"\n    hence \"ego_other2 t = 0\" unfolding ego_other2_def by auto\n    from \\<open>t \\<in> {0 <..< \\<delta>}\\<close> have \"ego_other2 t = other.s t - ego.q t\" \n      unfolding ego_other2_def u_def using ego.init_q by auto\n    thm other.s_def\n    have \"\\<delta> \\<le> other.t_stop \\<or> other.t_stop < \\<delta>\" by auto\n    \n    moreover\n    { assume le_t_stop: \"\\<delta> \\<le> other.t_stop\"\n      with \\<open>ego_other2 t = other.s t - ego.q t\\<close> have \"ego_other2 t = other.p t - ego.q t\"\n        unfolding other.s_def using \\<open>t \\<in> {0 <..< \\<delta>}\\<close> by auto\n      with \\<open>ego_other2 t = 0\\<close> have \"other.p t - ego.q t = 0\" by auto\n      hence eq: \"(s\\<^sub>o- s\\<^sub>e) + (v\\<^sub>o - v\\<^sub>e) * t + (1/2 * a\\<^sub>o) * t\\<^sup>2 = 0\"\n        unfolding other.p_def ego.q_def by (auto simp: algebra_simps)\n      def p \\<equiv> \"\\<lambda>x. (1/2 * a\\<^sub>o) * x\\<^sup>2 + (v\\<^sub>o - v\\<^sub>e) * x + (s\\<^sub>o - s\\<^sub>e)\"\n      have \"0 < 1/2 * a\\<^sub>o\"\n      proof (intro p_convex[where p=p and b=\"v\\<^sub>o - v\\<^sub>e\" and c=\"s\\<^sub>o - s\\<^sub>e\"])\n        defer\n          show \"0 < t\" using \\<open>t \\<in> {0 <..< \\<delta>}\\<close> by auto\n        next\n          show \"t < \\<delta>\" using  \\<open>t \\<in> {0 <..< \\<delta>}\\<close> by auto\n        next\n          show \"p t < p 0\" unfolding p_def using eq in_front by (auto simp: algebra_simps)\n        next\n          from eq have \"p t = 0\" unfolding p_def by auto\n          also have \"... < p \\<delta>\"  using no_collision_delta pos_react le_t_stop             \n            unfolding p_def u_def other.s_def ego.q_def other.p_def by (auto simp:algebra_simps)\n          finally have \"p t < p \\<delta>\" by simp\n          thus \"p t \\<le> p \\<delta>\" by auto\n        next\n          show \"p = (\\<lambda>x. 1 / 2 * a\\<^sub>o * x\\<^sup>2 + (v\\<^sub>o - v\\<^sub>e) * x + (s\\<^sub>o - s\\<^sub>e))\" unfolding p_def\n          by (rule refl)\n      qed\n      hence \"0 < a\\<^sub>o\" by auto\n      with decelerate_other have False by simp }\n\n    moreover\n    { assume gt_t_stop: \"\\<delta> > other.t_stop\"\n      have t_lt_t_stop: \"t < other.t_stop\"\n      proof (rule ccontr)\n        assume \"\\<not> t < other.t_stop\"\n        hence \"other.t_stop \\<le> t\" by simp\n        from \\<open>ego_other2 t = 0\\<close> have \"ego.q t = other.p_max\"\n          unfolding ego_other2_def u_def other.s_def comp_def \\<tau>_def other.p_max_def\n          using \\<open>t \\<in> {0 <..< \\<delta>}\\<close> \\<open>other.t_stop \\<le> t\\<close> gt_t_stop by (auto split:if_splits)\n        have \"ego.q t = u t\" unfolding u_def using \\<open>t \\<in> {0 <..< \\<delta>}\\<close> by auto\n        also have \"... \\<le> u_max\" using u_max by auto\n        also have \"... < other.p_max\" using assms(2) other.s_t_stop by auto\n        finally have \"ego.q t < other.p_max\" by auto\n        with \\<open>ego.q t = other.p_max\\<close> show False by auto  \n      qed\n      \n      with \\<open>ego_other2 t = other.s t - ego.q t\\<close> have \"ego_other2 t = other.p t - ego.q t\"\n        unfolding other.s_def using \\<open>t \\<in> {0 <..< \\<delta>}\\<close> by auto\n      with \\<open>ego_other2 t = 0\\<close> have \"other.p t - ego.q t = 0\" by auto\n      hence eq: \"(s\\<^sub>o- s\\<^sub>e) + (v\\<^sub>o - v\\<^sub>e) * t + (1/2 * a\\<^sub>o) * t\\<^sup>2 = 0\"\n        unfolding other.p_def ego.q_def by (auto simp: algebra_simps)\n      def p \\<equiv> \"\\<lambda>x. (1/2 * a\\<^sub>o) * x\\<^sup>2 + (v\\<^sub>o - v\\<^sub>e) * x + (s\\<^sub>o - s\\<^sub>e)\"\n      have \"0 < 1/2 * a\\<^sub>o\"\n      proof (intro p_convex[where p=p and b=\"v\\<^sub>o - v\\<^sub>e\" and c=\"s\\<^sub>o - s\\<^sub>e\"])\n        defer\n          show \"0 < t\" using \\<open>t \\<in> {0 <..< \\<delta>}\\<close> by auto\n        next\n          show \"t < other.t_stop\" using t_lt_t_stop by auto\n        next\n          show \"p t < p 0\" unfolding p_def using eq in_front by (auto simp: algebra_simps)\n        next\n          from eq have zero: \"p t = 0\" unfolding p_def by auto\n          have eq: \"p other.t_stop = ego_other2 other.t_stop\" \n            unfolding ego_other2_def other.s_t_stop u_def ego.q_def \n                      other.s_def other.p_def p_def\n            using \\<open>\\<delta> > other.t_stop\\<close> other.t_stop_nonneg other.t_stop_def\n            by (auto simp: field_simps)\n          have \"u other.t_stop \\<le> u_max\" using u_max by auto\n          also have \"... < other.s_stop\" using assms by auto\n          finally have \"0 \\<le> other.s_stop - u other.t_stop\" by auto\n          hence \"0 \\<le> ego_other2 other.t_stop\" unfolding ego_other2_def by auto\n          hence \"0 \\<le> p other.t_stop\" using eq by auto\n          with zero show \"p t \\<le> p other.t_stop\" by auto\n        next\n          show \"p = (\\<lambda>x. 1 / 2 * a\\<^sub>o * x\\<^sup>2 + (v\\<^sub>o - v\\<^sub>e) * x + (s\\<^sub>o - s\\<^sub>e))\"\n          unfolding p_def by (rule refl)\n      qed \n      hence False using decelerate_other by auto }\n\n     ultimately show False by auto\n  qed\nqed\n\nlemma no_collision_react_initially:\n  assumes \"s\\<^sub>o \\<le> u_max\"\n  assumes \"u_max < other.s_stop\"\n  shows \"no_collision_react {0 .. \\<delta>}\"\nproof -\n  have \"no_collision_react {0 <..< \\<delta>}\" by (rule no_collision_react_initially_strict[OF assms])\n  have \"u 0 \\<noteq> other.s 0\" using init_u other.init_s in_front by auto\n  hence \"no_collision_react {0}\" unfolding collision_react_def by auto\n  with \\<open>no_collision_react {0 <..< \\<delta>}\\<close> have \"no_collision_react ({0} \\<union> {0 <..< \\<delta>})\"\n    using no_collision_union[of \"{0}\" \"{0 <..< \\<delta>}\"] by auto\n  moreover have \"{0} \\<union> {0 <..< \\<delta>} = {0 ..< \\<delta>}\" using pos_react by auto\n  ultimately have \"no_collision_react {0 ..< \\<delta>}\" by auto\n\n  have \"u \\<delta> \\<noteq> other.s \\<delta>\" using no_collision_delta by auto\n  hence \"no_collision_react {\\<delta>}\" unfolding collision_react_def by auto\n  with \\<open>no_collision_react {0 ..< \\<delta>}\\<close> have \"no_collision_react ({\\<delta>} \\<union> {0 ..< \\<delta>})\"\n    using no_collision_union[of \"{\\<delta>}\" \"{0 ..< \\<delta>}\"] by auto\n  moreover have \"{\\<delta>} \\<union> {0 ..< \\<delta>} = {0 .. \\<delta>}\" using pos_react by auto\n  ultimately show \"no_collision_react {0 .. \\<delta>}\" by auto\nqed\n\nlemma collision_after_delta:\n  assumes \"s\\<^sub>o \\<le> u_max\"\n  assumes \"u_max < other.s_stop\"\n  shows \"collision_react {0 ..} \\<longleftrightarrow> collision_react {\\<delta>..}\" \nproof\n  assume \"collision_react {0 ..}\"\n  have \"no_collision_react {0 .. \\<delta>}\" by (rule no_collision_react_initially[OF assms])\n  with \\<open>collision_react {0..}\\<close> have \"collision_react ({0..} - {0 .. \\<delta>})\"\n  using pos_react by (auto intro: collision_trim_subset)\n  \n  moreover have \"{0..} - {0 .. \\<delta>} = {\\<delta> <..}\" using pos_react by auto\n  ultimately have \"collision_react {\\<delta> <..}\" by auto\n  thus \"collision_react {\\<delta> ..}\" by (auto intro:collision_react_subset)\nnext\n  assume \"collision_react {\\<delta>..}\"\n  moreover have \"{\\<delta>..} \\<subseteq> {0 ..}\" using pos_react by auto\n  ultimately show \"collision_react {0 ..}\" by (rule collision_react_subset)\nqed\n\nlemma collision_react_strict:\n  assumes \"s\\<^sub>o \\<le> u_max\"\n  assumes \"u_max < other.s_stop\"\n  shows \"collision_react {\\<delta> ..} \\<longleftrightarrow> collision_react {\\<delta> <..}\"\nproof\n  assume asm: \"collision_react {\\<delta> ..}\"\n  have \"no_collision_react {\\<delta>}\" using no_collision_delta unfolding collision_react_def by auto\n  thm collision_trim_subset\n  moreover have \"{\\<delta> <..} \\<subseteq> {\\<delta> ..}\" by auto\n  ultimately have \"collision_react ({\\<delta> ..} - {\\<delta>})\" using asm collision_trim_subset by simp\n  moreover have \"{\\<delta> <..} = {\\<delta> ..} - {\\<delta>}\" by auto\n  ultimately show \"collision_react {\\<delta> <..}\" by auto\nnext\n  assume \"collision_react {\\<delta> <..}\"\n  thus \"collision_react {\\<delta> ..}\" \n    using collision_react_subset[where t=\"{\\<delta> ..}\" and s=\"{\\<delta> <..}\"] by fastforce\nqed\n\nlemma delayed_other_s_stop_eq: \"delayed_safe_distance.other.s_stop = other.s_stop\"\nproof (unfold other.s_t_stop; unfold delayed_safe_distance.other.s_t_stop; unfold movement.p_max_eq)\n  have \"\\<delta> \\<le> other.t_stop \\<or> other.t_stop < \\<delta>\" by auto\n\n  moreover\n  { assume \"\\<delta> \\<le> other.t_stop\"\n    hence \"other.s \\<delta> - (other.s' \\<delta>)\\<^sup>2 / a\\<^sub>o / 2 = s\\<^sub>o - v\\<^sub>o\\<^sup>2 / a\\<^sub>o / 2\"\n    unfolding other.s_def other.s'_def\n    using  pos_react decelerate_other\n    by (auto simp add: other.p_def other.p'_def power2_eq_square algebra_simps divide_simps) }\n\n  moreover\n  { assume \"other.t_stop < \\<delta>\"\n    hence \"other.s \\<delta> - (other.s' \\<delta>)\\<^sup>2 / a\\<^sub>o / 2 = s\\<^sub>o - v\\<^sub>o\\<^sup>2 / a\\<^sub>o / 2\"\n    unfolding other.s_def other.s'_def other.p_max_eq\n    using pos_react decelerate_other \n    by (auto) }\n\n  ultimately show \"other.s \\<delta> - (other.s' \\<delta>)\\<^sup>2 / a\\<^sub>o / 2 = s\\<^sub>o - v\\<^sub>o\\<^sup>2 / a\\<^sub>o / 2\" by auto\nqed\n\nlemma delayed_cond3':\n  assumes \"other.s \\<delta> \\<le> u_max\" \n  assumes \"u_max < other.s_stop\"\n  shows \"delayed_safe_distance.collision {0 ..} \\<longleftrightarrow>  \n          (a\\<^sub>o > a\\<^sub>e \\<and> other.s' \\<delta> < v\\<^sub>e \\<and> other.s \\<delta> - ego.q \\<delta> \\<le> delayed_safe_distance.snd_safe_distance \\<and> v\\<^sub>e - a\\<^sub>e / a\\<^sub>o * other.s' \\<delta> < 0)\"\n  proof (rule delayed_safe_distance.cond_3')\n    have \"other.s \\<delta> \\<le> u_max\" using \\<open>other.s \\<delta> \\<le> u_max\\<close> . \n    also have \"... = ego2.s_stop\" unfolding u_max_eq ego2.s_t_stop ego2.p_max_eq by (rule refl)\n    finally show \"other.s \\<delta> \\<le> ego2.s_stop\" by auto\n  next\n    have \"ego2.s_stop = u_max\" unfolding ego2.s_t_stop ego2.p_max_eq u_max_eq by (rule refl)\n    also have \"... < other.s_stop\" using assms by auto\n    also have \"... \\<le> delayed_safe_distance.other.s_stop\" using delayed_other_s_stop_eq by auto\n    finally show \"ego2.s_stop < delayed_safe_distance.other.s_stop\" by auto\n  qed\n\nlemma delayed_other_t_stop_eq:\n  assumes \"\\<delta> \\<le> other.t_stop\"\n  shows \"delayed_safe_distance.other.t_stop + \\<delta> = other.t_stop\"\n  using assms decelerate_other\n  unfolding delayed_safe_distance.other.t_stop_def other.t_stop_def other.s'_def\n            movement.t_stop_def other.p'_def\n  by (auto simp add:algebra_simps divide_simps)\n\nlemma delayed_other_s_eq:\n  assumes \"0 \\<le> t\"\n  shows \"delayed_safe_distance.other.s t = other.s (t + \\<delta>)\"\nproof (cases \"\\<delta> \\<le> other.t_stop\")\n  assume 1: \"\\<delta> \\<le> other.t_stop\"\n  have \"t + \\<delta> \\<le> other.t_stop \\<or> other.t_stop < t + \\<delta>\" by auto\n  moreover\n  { assume \"t + \\<delta> \\<le> other.t_stop\"\n    hence \"delayed_safe_distance.other.s t = delayed_safe_distance.other.p t\"    \n      using delayed_other_t_stop_eq [OF 1] assms\n      unfolding delayed_safe_distance.other.s_def by auto \n    \n    also have \"... = other.p (t + \\<delta>)\" \n      unfolding movement.p_def other.s_def other.s'_def other.p'_def\n      using pos_react 1 \n      by (auto simp add: power2_eq_square divide_simps algebra_simps)\n      \n    also have \"... = other.s (t + \\<delta>)\"\n      unfolding other.s_def \n      using assms pos_react \\<open>t + \\<delta> \\<le> other.t_stop\\<close> by auto\n\n    finally have \"delayed_safe_distance.other.s t = other.s (t + \\<delta>)\" by auto }\n\n  moreover\n  { assume \"other.t_stop < t + \\<delta>\"\n    hence \"delayed_safe_distance.other.s t = delayed_safe_distance.other.p_max\"\n      using delayed_other_t_stop_eq [OF 1] assms delayed_safe_distance.other.t_stop_nonneg\n      unfolding delayed_safe_distance.other.s_def by auto\n    \n    also have \"... = other.p_max\" \n      unfolding movement.p_max_eq other.s_def other.s'_def other.p_def other.p'_def\n      using pos_react 1 decelerate_other \n      by (auto simp add:power2_eq_square divide_simps algebra_simps)\n\n    also have \"... = other.s (t + \\<delta>)\"\n      unfolding other.s_def\n      using assms pos_react \\<open>other.t_stop < t + \\<delta>\\<close> by auto\n\n    finally have \"delayed_safe_distance.other.s t = other.s (t + \\<delta>)\" by auto }\n\n  ultimately show ?thesis by auto\nnext\n  assume \"\\<not> \\<delta> \\<le> other.t_stop\"\n  hence \"other.t_stop < \\<delta>\" by auto\n  hence \"other.s' \\<delta> = 0\" and \"other.s \\<delta> = other.p_max\" \n    unfolding other.s'_def other.s_def using pos_react by auto\n  hence \"delayed_safe_distance.other.s t = delayed_safe_distance.other.p_max\"\n    unfolding delayed_safe_distance.other.s_def using assms decelerate_other \n    by (auto simp add:movement.p_max_eq movement.p_def movement.t_stop_def)\n  also have \"... = other.p_max\" \n    unfolding movement.p_max_eq using \\<open>other.s' \\<delta> = 0\\<close> \\<open>other.s \\<delta> = other.p_max\\<close>\n    using other.p_max_eq by auto\n  also have \"... = other.s (t + \\<delta>)\" \n    unfolding other.s_def using pos_react assms \\<open>other.t_stop < \\<delta>\\<close> by auto\n  finally show \"delayed_safe_distance.other.s t = other.s (t + \\<delta>)\" by auto\nqed\n\nlemma translate_collision_range:\n  assumes \"s\\<^sub>o \\<le> u_max\"\n  assumes \"u_max < other.s_stop\"\n  shows \"delayed_safe_distance.collision {0 ..} \\<longleftrightarrow> collision_react {\\<delta> ..}\"\nproof \n  assume \"delayed_safe_distance.collision {0 ..}\" \n  then obtain t where eq: \"ego2.s t = delayed_safe_distance.other.s t\" and \"0 \\<le> t\"\n    unfolding delayed_safe_distance.collision_def by auto\n\n  have \"ego2.s t = (ego2.s \\<circ> \\<tau>) (t + \\<delta>)\" unfolding comp_def \\<tau>_def by auto\n  also have \"... = u (t + \\<delta>)\" unfolding u_def using \\<open>0 \\<le> t\\<close> pos_react \n    by (auto simp: \\<tau>_def ego2.init_s)\n  finally have left:\"ego2.s t = u (t + \\<delta>)\" by auto\n\n  have right: \"delayed_safe_distance.other.s t = other.s (t + \\<delta>)\"\n    using delayed_other_s_eq pos_react \\<open>0 \\<le> t\\<close> by auto\n\n  with eq and left have \"u (t + \\<delta>) = other.s (t + \\<delta>)\" by auto\n  moreover have \"\\<delta> \\<le> t + \\<delta>\" using \\<open>0 \\<le> t\\<close> by auto\n  ultimately show \"collision_react {\\<delta> ..}\" unfolding collision_react_def by auto\nnext\n  assume \"collision_react {\\<delta> ..}\"\n  hence \"collision_react {\\<delta> <..}\" using collision_react_strict[OF assms] by simp\n  then obtain t where eq: \"u t = other.s t\" and \"\\<delta> < t\"\n    unfolding collision_react_def by auto\n  moreover hence \"u t = (ego2.s \\<circ> \\<tau>) t\" unfolding u_def using pos_react by auto\n  moreover have \"other.s t = delayed_safe_distance.other.s (t - \\<delta>)\"\n    using delayed_other_s_eq \\<open>\\<delta> < t\\<close> by auto\n  ultimately have \"ego2.s (t - \\<delta>) = delayed_safe_distance.other.s (t - \\<delta>)\"\n    unfolding comp_def \\<tau>_def by auto\n  with \\<open>\\<delta> < t\\<close> show \"delayed_safe_distance.collision {0 ..}\" \n    unfolding delayed_safe_distance.collision_def by auto\nqed\n\ntheorem cond_3r_2:\n  assumes \"s\\<^sub>o \\<le> u_max\"\n  assumes \"u_max < other.s_stop\"\n  assumes \"other.s \\<delta> \\<le> u_max\"\n  shows \"collision_react {0 ..} \\<longleftrightarrow> \n         (a\\<^sub>o > a\\<^sub>e \\<and> other.s' \\<delta> < v\\<^sub>e \\<and> other.s \\<delta> -  ego.q \\<delta> \\<le> delayed_safe_distance.snd_safe_distance \\<and> v\\<^sub>e - a\\<^sub>e / a\\<^sub>o * other.s' \\<delta> < 0)\"\nproof -\n  have \"collision_react {0 ..} \\<longleftrightarrow> collision_react {\\<delta> ..}\" by (rule collision_after_delta[OF assms(1) assms(2)])\n  also have \"... \\<longleftrightarrow> delayed_safe_distance.collision {0 ..}\" by (simp add: translate_collision_range[OF assms(1) assms(2)])\n  also have \"... \\<longleftrightarrow>  (a\\<^sub>o > a\\<^sub>e \\<and> other.s' \\<delta> < v\\<^sub>e \\<and> other.s \\<delta> -  ego.q \\<delta> \\<le> delayed_safe_distance.snd_safe_distance \\<and> v\\<^sub>e - a\\<^sub>e / a\\<^sub>o * other.s' \\<delta> < 0)\"\n    by (rule delayed_cond3'[OF assms(3) assms(2)])\n  finally show \"collision_react {0 ..} \\<longleftrightarrow>  (a\\<^sub>o > a\\<^sub>e \\<and> other.s' \\<delta> < v\\<^sub>e \\<and> other.s \\<delta> -  ego.q \\<delta> \\<le> delayed_safe_distance.snd_safe_distance \\<and> v\\<^sub>e - a\\<^sub>e / a\\<^sub>o * other.s' \\<delta> < 0)\"\n    by auto\nqed\n\nlemma sd_2r_correct_for_3r_2:\n  assumes \"s\\<^sub>o - s\\<^sub>e > safe_distance_2r\"\n  assumes \"other.s \\<delta> \\<le> u_max\"\n  assumes \"\\<not> (a\\<^sub>o > a\\<^sub>e \\<and> other.s' \\<delta> < v\\<^sub>e \\<and> v\\<^sub>e - a\\<^sub>e / a\\<^sub>o * other.s' \\<delta> < 0)\"\n  shows \"no_collision_react {0..}\"\nproof -\n  from assms have \"s\\<^sub>o - s\\<^sub>e > v\\<^sub>e * \\<delta> - v\\<^sub>e\\<^sup>2 / 2 / a\\<^sub>e + v\\<^sub>o\\<^sup>2 / 2 / a\\<^sub>o\" unfolding safe_distance_2r_def by auto\n  hence \"s\\<^sub>o - v\\<^sub>o\\<^sup>2 / 2 / a\\<^sub>o > s\\<^sub>e + v\\<^sub>e * \\<delta> - v\\<^sub>e\\<^sup>2 / 2 / a\\<^sub>e\" by auto\n  hence \"s\\<^sub>o - v\\<^sub>o\\<^sup>2 / a\\<^sub>o + v\\<^sub>o\\<^sup>2 / 2 / a\\<^sub>o > s\\<^sub>e + v\\<^sub>e * \\<delta> - v\\<^sub>e\\<^sup>2 / 2 / a\\<^sub>e\" by auto\n  hence \"s\\<^sub>o + v\\<^sub>o * (- v\\<^sub>o / a\\<^sub>o) + 1/2 * a\\<^sub>o * (-v\\<^sub>o / a\\<^sub>o)\\<^sup>2 > s\\<^sub>e + v\\<^sub>e * \\<delta> - v\\<^sub>e\\<^sup>2 / 2 / a\\<^sub>e\"\n    using other.p_def other.p_max_def other.p_max_eq other.t_stop_def by auto\n  hence \"other.s_stop > u_max\" unfolding other.s_def using u_max_eq other.t_stop_def\n    using ego.q_def other.p_def other.p_max_def other.s_def other.s_t_stop by auto\n  thus ?thesis\n    using assms(2) assms(3) collision_after_delta cond_1r delayed_cond3' translate_collision_range by linarith\nqed\n        \nlemma sd2_at_most_sd4:\n  assumes \"a\\<^sub>o > a\\<^sub>e\"\n  shows \"safe_distance_2r \\<le> safe_distance_4r\"    \nproof -\n  have \"a\\<^sub>o \\<noteq> 0\" and \"a\\<^sub>e \\<noteq> 0\" and \"a\\<^sub>o - a\\<^sub>e \\<noteq> 0\" and \"0 < 2 * (a\\<^sub>o - a\\<^sub>e)\" using hyps assms(1) by auto\n  have \"0 \\<le> (- v\\<^sub>e * a\\<^sub>o + v\\<^sub>o * a\\<^sub>e + a\\<^sub>o * a\\<^sub>e * \\<delta>) * (- v\\<^sub>e * a\\<^sub>o + v\\<^sub>o * a\\<^sub>e + a\\<^sub>o * a\\<^sub>e * \\<delta>)\"\n    (is \"0 \\<le> (?l1 + ?l2 + ?l3) * ?r\") by auto\n  also have \"... = v\\<^sub>e\\<^sup>2 * a\\<^sub>o\\<^sup>2 + v\\<^sub>o\\<^sup>2 * a\\<^sub>e\\<^sup>2 + a\\<^sub>o\\<^sup>2 * a\\<^sub>e\\<^sup>2 * \\<delta>\\<^sup>2 - 2 * v\\<^sub>e * a\\<^sub>o * v\\<^sub>o * a\\<^sub>e - 2 * a\\<^sub>o\\<^sup>2 * a\\<^sub>e * \\<delta> * v\\<^sub>e + 2 * a\\<^sub>o * a\\<^sub>e\\<^sup>2 * \\<delta> * v\\<^sub>o\"\n    (is \"?lhs = ?rhs\")\n    by (auto simp add:algebra_simps power_def)\n  finally have \"0 \\<le> ?rhs\" by auto\n  hence \"(- v\\<^sub>e\\<^sup>2 * a\\<^sub>o / a\\<^sub>e - v\\<^sub>o\\<^sup>2 * a\\<^sub>e / a\\<^sub>o) * (a\\<^sub>o * a\\<^sub>e) \\<le> (a\\<^sub>o * a\\<^sub>e * \\<delta>\\<^sup>2 - 2 * v\\<^sub>e * v\\<^sub>o - 2 * a\\<^sub>o * \\<delta> * v\\<^sub>e + 2 * a\\<^sub>e * \\<delta> * v\\<^sub>o) * (a\\<^sub>o * a\\<^sub>e)\"\n    by (auto simp add: algebra_simps power_def)\n  hence \"2 * v\\<^sub>e * \\<delta> * (a\\<^sub>o - a\\<^sub>e) - v\\<^sub>e\\<^sup>2 * a\\<^sub>o / a\\<^sub>e + v\\<^sub>e\\<^sup>2 + v\\<^sub>o\\<^sup>2 - v\\<^sub>o\\<^sup>2 * a\\<^sub>e / a\\<^sub>o \\<le> v\\<^sub>o\\<^sup>2 + a\\<^sub>o\\<^sup>2 * \\<delta>\\<^sup>2 + v\\<^sub>e\\<^sup>2 + 2 * v\\<^sub>o * \\<delta> * a\\<^sub>o - 2 * v\\<^sub>e * v\\<^sub>o - 2 * a\\<^sub>o * \\<delta> * v\\<^sub>e - 2 * v\\<^sub>o * \\<delta> * a\\<^sub>o + 2 * a\\<^sub>e * \\<delta> * v\\<^sub>o - a\\<^sub>o\\<^sup>2 * \\<delta>\\<^sup>2 + a\\<^sub>o * a\\<^sub>e * \\<delta>\\<^sup>2 + 2 * v\\<^sub>e * \\<delta> * (a\\<^sub>o - a\\<^sub>e)\"\n    by (auto simp add: ego2.decel other.decel)\n  hence \"2 * v\\<^sub>e * \\<delta> * (a\\<^sub>o - a\\<^sub>e) - v\\<^sub>e\\<^sup>2 * a\\<^sub>o / a\\<^sub>e + v\\<^sub>e\\<^sup>2 + v\\<^sub>o\\<^sup>2 - v\\<^sub>o\\<^sup>2 * a\\<^sub>e / a\\<^sub>o \\<le> (v\\<^sub>o + \\<delta> * a\\<^sub>o - v\\<^sub>e)\\<^sup>2 - 2 * v\\<^sub>o * \\<delta> * a\\<^sub>o + 2 * a\\<^sub>e * \\<delta> * v\\<^sub>o - a\\<^sub>o\\<^sup>2 * \\<delta>\\<^sup>2 + a\\<^sub>o * a\\<^sub>e * \\<delta>\\<^sup>2 + 2 * v\\<^sub>e * \\<delta> * (a\\<^sub>o - a\\<^sub>e)\"\n    by (auto simp add: algebra_simps power_def)\n  hence \"v\\<^sub>e * \\<delta> * 2 * (a\\<^sub>o - a\\<^sub>e) - v\\<^sub>e\\<^sup>2 / 2 / a\\<^sub>e * 2 * a\\<^sub>o + v\\<^sub>e\\<^sup>2 / 2 / a\\<^sub>e * 2 * a\\<^sub>e + v\\<^sub>o\\<^sup>2 / 2 / a\\<^sub>o * 2 * a\\<^sub>o - v\\<^sub>o\\<^sup>2 / 2 / a\\<^sub>o * 2 * a\\<^sub>e \\<le> (v\\<^sub>o + \\<delta> * a\\<^sub>o - v\\<^sub>e)\\<^sup>2 - v\\<^sub>o * \\<delta> * 2 * a\\<^sub>o - v\\<^sub>o * \\<delta> * 2 * -a\\<^sub>e - a\\<^sub>o * \\<delta>\\<^sup>2 / 2 * 2 * a\\<^sub>o - a\\<^sub>o * \\<delta>\\<^sup>2 / 2 * 2 * -a\\<^sub>e + v\\<^sub>e * \\<delta> * 2 * (a\\<^sub>o - a\\<^sub>e)\"\n    (is \"?lhs1 \\<le> ?rhs1\")\n    by (simp add: \\<open>a\\<^sub>o \\<noteq> 0\\<close> \\<open>a\\<^sub>e \\<noteq> 0\\<close> power2_eq_square algebra_simps)\n  hence \"v\\<^sub>e * \\<delta> * 2 * (a\\<^sub>o - a\\<^sub>e) - v\\<^sub>e\\<^sup>2 / 2 / a\\<^sub>e * 2 * (a\\<^sub>o - a\\<^sub>e) + v\\<^sub>o\\<^sup>2 / 2 / a\\<^sub>o * 2 * (a\\<^sub>o - a\\<^sub>e) \\<le> (v\\<^sub>o + a\\<^sub>o * \\<delta> - v\\<^sub>e)\\<^sup>2 / 2 / (a\\<^sub>o - a\\<^sub>e) * 2 * (a\\<^sub>o - a\\<^sub>e) - v\\<^sub>o * \\<delta> * 2 * (a\\<^sub>o - a\\<^sub>e) - a\\<^sub>o * \\<delta>\\<^sup>2 / 2 * 2 * (a\\<^sub>o - a\\<^sub>e) + v\\<^sub>e * \\<delta> * 2 *(a\\<^sub>o - a\\<^sub>e)\"\n    (is \"?lhs2 \\<le> ?rhs2\")\n  proof -\n    assume \"?lhs1 \\<le> ?rhs1\"\n    have \"?lhs1 = ?lhs2\" by (auto simp add:field_simps)       \n    moreover    \n    have \"?rhs1 = ?rhs2\" using `a\\<^sub>o - a\\<^sub>e \\<noteq> 0` by (auto simp add:field_simps)\n    ultimately show ?thesis using `?lhs1 \\<le> ?rhs1` by auto         \n  qed\n  hence \"(v\\<^sub>e * \\<delta> - v\\<^sub>e\\<^sup>2 / 2 / a\\<^sub>e + v\\<^sub>o\\<^sup>2 / 2 / a\\<^sub>o) * 2 * (a\\<^sub>o - a\\<^sub>e) \\<le> ((v\\<^sub>o + a\\<^sub>o * \\<delta> - v\\<^sub>e)\\<^sup>2 / 2 / (a\\<^sub>o - a\\<^sub>e) - v\\<^sub>o * \\<delta> - 1/2 * a\\<^sub>o * \\<delta>\\<^sup>2 + v\\<^sub>e * \\<delta>) * 2 *(a\\<^sub>o - a\\<^sub>e)\"\n    by (simp add: algebra_simps)\n  hence \"v\\<^sub>e * \\<delta> - v\\<^sub>e\\<^sup>2 / 2 / a\\<^sub>e + v\\<^sub>o\\<^sup>2 / 2 / a\\<^sub>o \\<le> (v\\<^sub>o + a\\<^sub>o * \\<delta> - v\\<^sub>e)\\<^sup>2 / 2 / (a\\<^sub>o - a\\<^sub>e) - v\\<^sub>o * \\<delta> - 1/2 * a\\<^sub>o * \\<delta>\\<^sup>2 + v\\<^sub>e * \\<delta>\"\n    using \\<open>a\\<^sub>o > a\\<^sub>e\\<close> real_mult_le_cancel_iff1[OF `0 < 2 * (a\\<^sub>o - a\\<^sub>e)`, of \"(v\\<^sub>e * \\<delta> - v\\<^sub>e\\<^sup>2 / 2 / a\\<^sub>e + v\\<^sub>o\\<^sup>2 / 2 / a\\<^sub>o)\" \n    \"(v\\<^sub>o + a\\<^sub>o * \\<delta> - v\\<^sub>e)\\<^sup>2 / 2 / (a\\<^sub>o - a\\<^sub>e) - v\\<^sub>o * \\<delta> - 1/2 * a\\<^sub>o * \\<delta>\\<^sup>2 + v\\<^sub>e * \\<delta>\"] semiring_normalization_rules(18)\n    by (metis (no_types, lifting) real_mult_le_cancel_iff1)\n  thus ?thesis using safe_distance_2r_def safe_distance_4r_def by auto\nqed\n  \nlemma sd_4r_correct:\n  assumes \"s\\<^sub>o - s\\<^sub>e > safe_distance_4r\"\n  assumes \"other.s \\<delta> \\<le> u_max\"\n  assumes \"\\<delta> \\<le> other.t_stop\"\n  assumes \"a\\<^sub>o > a\\<^sub>e\"    \n  shows \"no_collision_react {0..}\"\nproof -\n  from assms have \"s\\<^sub>o - s\\<^sub>e > (v\\<^sub>o + a\\<^sub>o * \\<delta> - v\\<^sub>e)\\<^sup>2 / 2 / (a\\<^sub>o - a\\<^sub>e) - v\\<^sub>o * \\<delta> - 1/2 * a\\<^sub>o * \\<delta>\\<^sup>2 + v\\<^sub>e * \\<delta>\" \n    unfolding safe_distance_4r_def by auto\n  hence \"s\\<^sub>o + v\\<^sub>o * \\<delta> + 1/2 * a\\<^sub>o * \\<delta>\\<^sup>2 - s\\<^sub>e - v\\<^sub>e * \\<delta> > (v\\<^sub>o + a\\<^sub>o * \\<delta> - v\\<^sub>e)\\<^sup>2 / 2 / (a\\<^sub>o - a\\<^sub>e)\" by linarith\n  hence \"other.s \\<delta> -  ego.q \\<delta> > (other.s' \\<delta> - v\\<^sub>e)\\<^sup>2 / 2 / (a\\<^sub>o - a\\<^sub>e)\" \n    using assms(3) ego.q_def other.p_def other.s_def other.p'_def other.s'_def pos_react by auto\n  hence \"other.s \\<delta> -  ego.q \\<delta> > delayed_safe_distance.snd_safe_distance\"\n    by (simp add: delayed_safe_distance.snd_safe_distance_def)\n  hence c: \"\\<not> (other.s \\<delta> -  ego.q \\<delta> \\<le> delayed_safe_distance.snd_safe_distance)\" by linarith\n  have \"u_max < other.s_stop\" \n    unfolding u_max_eq other.s_t_stop other.p_max_eq ego.q_def using assms(1) sd2_at_most_sd4[OF assms(4)]\n    unfolding safe_distance_4r_def safe_distance_2r_def by auto    \n  consider \"s\\<^sub>o \\<le> u_max\" | \"s\\<^sub>o > u_max\" by linarith         \n  thus ?thesis \n  proof (cases)\n    case 1\n    from cond_3r_2[OF this `u_max < other.s_stop` assms(2)]  show ?thesis \n      using c by auto\n  next\n    case 2\n    then show ?thesis using cond_1r by auto\n  qed        \nqed      \n\n(*irrelevant since this safe_distance is unreachable in the checker*)\ndefinition safe_distance_5r::real where \"safe_distance_5r = v\\<^sub>e\\<^sup>2 / 2 / (a\\<^sub>o - a\\<^sub>e) + v\\<^sub>o\\<^sup>2 / 2 / a\\<^sub>o + v\\<^sub>e * \\<delta>\"\n  \nlemma sd_5r_correct:\n  assumes \"s\\<^sub>o - s\\<^sub>e > safe_distance_5r\"\n  assumes \"u_max < other.s_stop\"\n  assumes \"other.s \\<delta> \\<le> u_max\"\n  assumes \"\\<delta> > other.t_stop\"\n  shows \"no_collision_react {0..}\"\nproof -\n  from assms have \"s\\<^sub>o - s\\<^sub>e > v\\<^sub>e\\<^sup>2 / 2 / (a\\<^sub>o - a\\<^sub>e) + v\\<^sub>o\\<^sup>2 / 2 / a\\<^sub>o + v\\<^sub>e * \\<delta>\" \n    unfolding safe_distance_5r_def by auto\n  hence \"s\\<^sub>o + v\\<^sub>o\\<^sup>2 / 2 / a\\<^sub>o - s\\<^sub>e - v\\<^sub>e * \\<delta> > (0 - v\\<^sub>e)\\<^sup>2 / 2 / (a\\<^sub>o - a\\<^sub>e)\"\n    by (smt assms(2) assms(3) assms(4) other.s_def other.s_t_stop)\n  hence \"other.s \\<delta> -  ego.q \\<delta> > (other.s' \\<delta> - v\\<^sub>e)\\<^sup>2 / 2 / (a\\<^sub>o - a\\<^sub>e)\"\n    using assms(2) assms(3) assms(4) other.s_def other.s_t_stop by auto\n  hence \"other.s \\<delta> -  ego.q \\<delta> > delayed_safe_distance.snd_safe_distance\"\n    by (simp add: delayed_safe_distance.snd_safe_distance_def)\n  hence \"\\<not> (other.s \\<delta> -  ego.q \\<delta> \\<le> delayed_safe_distance.snd_safe_distance)\" by linarith\n  thus ?thesis using assms(2) assms(3) cond_1r cond_3r_2 by linarith\nqed\n  \n(*lemma sd_25:\n  assumes \"a\\<^sub>o > a\\<^sub>e\"\n  assumes \"\\<delta> > other.t_stop\"\n  shows \"safe_distance_2r \\<le> safe_distance_5r\"\nproof -\n  from assms \n  have \"(a\\<^sub>o - a\\<^sub>e) > 0\" using assms(1) by simp\n  hence \"- v\\<^sub>e\\<^sup>2 \\<le> 0\" by simp\n  hence  \"- v\\<^sub>e\\<^sup>2 * 2 * a\\<^sub>o / 2 / a\\<^sub>e \\<le> 0\"\n    by (smt divide_le_0_iff mult_nonpos_nonpos other.decel real_sum_of_halves safe_distance.decelerate_ego safe_distance_axioms)\n  hence \"- v\\<^sub>e\\<^sup>2 * 2 * a\\<^sub>o / 2 / a\\<^sub>e +  v\\<^sub>e\\<^sup>2 \\<le> v\\<^sub>e\\<^sup>2\" by linarith\n  hence \"- v\\<^sub>e\\<^sup>2 / 2 / a\\<^sub>e * 2 * a\\<^sub>o - v\\<^sub>e\\<^sup>2 / 2 / a\\<^sub>e * (- 2 * a\\<^sub>e) \\<le> v\\<^sub>e\\<^sup>2\" by simp\n  hence \"- v\\<^sub>e\\<^sup>2 / 2 / a\\<^sub>e * (2 * a\\<^sub>o - 2 * a\\<^sub>e) \\<le> v\\<^sub>e\\<^sup>2\"\n    proof -\n      have f1: \"a\\<^sub>o * (2 * (- v\\<^sub>e\\<^sup>2 / 2 / a\\<^sub>e)) - a\\<^sub>e * - 2 * (v\\<^sub>e\\<^sup>2 / 2 / a\\<^sub>e) \\<le> v\\<^sub>e\\<^sup>2\"\n        by (metis \\<open>- v\\<^sub>e\\<^sup>2 / 2 / a\\<^sub>e * 2 * a\\<^sub>o - v\\<^sub>e\\<^sup>2 / 2 / a\\<^sub>e * (- 2 * a\\<^sub>e) \\<le> v\\<^sub>e\\<^sup>2\\<close> mult.commute)\n      have f2: \"\\<And>r ra. - ((r::real) * ra) = ra * - r\"\n        by simp\n      have \"\\<And>r ra rb. (r::real) * (ra * rb) = r * rb * ra\"\n        by simp\n      then show ?thesis\n        using f2 f1 by (metis (no_types) divide_minus_left left_diff_distrib mult.commute mult.left_commute mult_minus_right)\n    qed\n  hence \"2 * (a\\<^sub>o - a\\<^sub>e) * (- v\\<^sub>e\\<^sup>2 / 2 / a\\<^sub>e) \\<le> 2 * (a\\<^sub>o - a\\<^sub>e)  * v\\<^sub>e\\<^sup>2 / 2 / (a\\<^sub>o - a\\<^sub>e)\" by (simp add: mult.commute)\n  hence \"(a\\<^sub>o - a\\<^sub>e) * (- v\\<^sub>e\\<^sup>2 / 2 / a\\<^sub>e) \\<le> (a\\<^sub>o - a\\<^sub>e) * v\\<^sub>e\\<^sup>2 / 2 / (a\\<^sub>o - a\\<^sub>e)\" using Real.real_mult_le_cancel_iff2 by linarith\n  hence \"- v\\<^sub>e\\<^sup>2 / 2 / a\\<^sub>e \\<le> v\\<^sub>e\\<^sup>2 / 2 / (a\\<^sub>o - a\\<^sub>e)\" \n    using \\<open>0 < a\\<^sub>o - a\\<^sub>e\\<close> real_mult_le_cancel_iff1 by blast\n  hence \"v\\<^sub>e * \\<delta> - v\\<^sub>e\\<^sup>2 / 2 / a\\<^sub>e + v\\<^sub>o\\<^sup>2 / 2 / a\\<^sub>o \\<le> v\\<^sub>e\\<^sup>2 / 2 / (a\\<^sub>o - a\\<^sub>e) + v\\<^sub>o\\<^sup>2 / 2 / a\\<^sub>o + v\\<^sub>e * \\<delta>\" by linarith\n  thus ?thesis using safe_distance_2r_def safe_distance_5r_def by linarith\nqed *)\n  \nlemma translate_no_collision_range:\n  \"delayed_safe_distance.no_collision {0 ..} \\<longleftrightarrow> no_collision_react {\\<delta> ..}\"  \nproof\n  assume left: \"delayed_safe_distance.no_collision {0 ..}\" \n  show \"no_collision_react {\\<delta> ..}\" \n  proof (unfold collision_react_def; simp; rule ballI)\n    fix t::real  \n    assume \"t \\<in> {\\<delta> ..}\"\n    hence \"\\<delta> \\<le> t\" by simp\n    with pos_react have \"0 \\<le> t - \\<delta>\" by simp\n    with left have ineq: \"ego2.s (t - \\<delta>) \\<noteq> delayed_safe_distance.other.s (t - \\<delta>)\"\n      unfolding delayed_safe_distance.collision_def by auto\n    \n    (* TODO: abstract this part. This is copied from  lemma translate_collision_range *)\n    have \"ego2.s (t - \\<delta>) = (ego2.s \\<circ> \\<tau>) t\" unfolding comp_def \\<tau>_def by auto\n    also have \"... = u t\" unfolding u_def using \\<open>\\<delta> \\<le> t\\<close> pos_react \n      by (auto simp: \\<tau>_def ego2.init_s)\n    finally have \"ego2.s (t - \\<delta>) = u t\" by auto\n\n    moreover have \"delayed_safe_distance.other.s (t - \\<delta>) = other.s t\"\n      using delayed_other_s_eq pos_react \\<open>\\<delta> \\<le> t\\<close> by auto\n  \n    ultimately show \"u t \\<noteq> other.s t\" using ineq by auto\n  qed\nnext\n  assume right:\"no_collision_react {\\<delta> ..}\"\n  show \"delayed_safe_distance.no_collision {0 ..}\"\n  proof (unfold delayed_safe_distance.collision_def; simp; rule ballI)\n    fix t ::real\n    assume \"t \\<in> {0 ..}\"\n    hence \"0 \\<le> t\" by auto\n    hence \"\\<delta> \\<le> t + \\<delta>\" by auto\n    with right have ineq: \"u (t + \\<delta>) \\<noteq> other.s (t + \\<delta>)\" unfolding collision_react_def by auto\n            \n    have \"u (t + \\<delta>) = ego2.s t\" unfolding u_def comp_def \\<tau>_def \n      using \\<open>0 \\<le> t\\<close> pos_react \\<open>\\<delta> \\<le> t+ \\<delta>\\<close> by (auto simp add:ego2.init_s)\n    moreover have \"other.s (t + \\<delta>) = delayed_safe_distance.other.s t\"\n      using delayed_other_s_eq[of t] using \\<open>0 \\<le> t\\<close> by auto\n    ultimately show \"ego2.s t \\<noteq> delayed_safe_distance.other.s t\" using ineq by auto\n  qed\nqed\n\nlemma delayed_cond1:\n  assumes \"other.s \\<delta> > u_max\"\n  shows \"delayed_safe_distance.no_collision {0 ..}\"\nproof -\n  have \"ego2.s_stop = u_max\"  unfolding ego2.s_t_stop ego2.p_max_eq u_max_eq by auto\n  also have \"... < other.s \\<delta>\" using assms by simp\n  finally have \"ego2.s_stop < other.s \\<delta>\" by auto\n  thus \"delayed_safe_distance.no_collision {0 ..}\" by (simp add: delayed_safe_distance.cond_1)\nqed\n\ntheorem cond_3r_3:\n  assumes \"s\\<^sub>o \\<le> u_max\"\n  assumes \"u_max < other.s_stop\"\n  assumes \"other.s \\<delta> > u_max\"\n  shows \"no_collision_react {0 ..}\"\nproof -\n  have eq: \"{0 ..} = {0 .. \\<delta>} \\<union> {\\<delta> ..}\" using pos_react by auto\n  show ?thesis unfolding eq \n  proof (intro no_collision_union)\n    show \"no_collision_react {0 .. \\<delta>}\" by (rule no_collision_react_initially[OF assms(1) assms(2)])  \n  next\n    have \"delayed_safe_distance.no_collision {0 ..}\" by (rule delayed_cond1[OF assms(3)])\n    with translate_no_collision_range show \"no_collision_react {\\<delta> ..}\" by auto\n  qed\nqed\n\nlemma sd_2r_correct_for_3r_3:\n  assumes \"s\\<^sub>o - s\\<^sub>e > safe_distance_2r\"\n  assumes \"other.s \\<delta> > u_max\"\n  shows \"no_collision_react {0..}\"\nproof -\n  from assms have \"s\\<^sub>o - s\\<^sub>e > v\\<^sub>e * \\<delta> - v\\<^sub>e\\<^sup>2 / 2 / a\\<^sub>e + v\\<^sub>o\\<^sup>2 / 2 / a\\<^sub>o\" unfolding safe_distance_2r_def by auto\n  hence \"s\\<^sub>o - v\\<^sub>o\\<^sup>2 / 2 / a\\<^sub>o > s\\<^sub>e + v\\<^sub>e * \\<delta> - v\\<^sub>e\\<^sup>2 / 2 / a\\<^sub>e\" by auto\n  hence \"s\\<^sub>o - v\\<^sub>o\\<^sup>2 / a\\<^sub>o + v\\<^sub>o\\<^sup>2 / 2 / a\\<^sub>o > s\\<^sub>e + v\\<^sub>e * \\<delta> - v\\<^sub>e\\<^sup>2 / 2 / a\\<^sub>e\" by auto\n  hence \"s\\<^sub>o + v\\<^sub>o * (- v\\<^sub>o / a\\<^sub>o) + 1/2 * a\\<^sub>o * (-v\\<^sub>o / a\\<^sub>o)\\<^sup>2 > s\\<^sub>e + v\\<^sub>e * \\<delta> - v\\<^sub>e\\<^sup>2 / 2 / a\\<^sub>e\"\n    using other.p_def other.p_max_def other.p_max_eq other.t_stop_def by auto\n  hence \"other.s_stop > u_max\" unfolding other.s_def using u_max_eq other.t_stop_def\n    using ego.q_def other.p_def other.p_max_def other.s_def other.s_t_stop by auto\n  thus ?thesis\n    using assms(2) cond_1r cond_3r_3 by linarith\nqed\n    \nlemma sd_3r_correct:\n  assumes \"s\\<^sub>o - s\\<^sub>e > safe_distance_3r\"\n  assumes \"\\<delta> \\<le> other.t_stop\"\n  shows \"no_collision_react {0 ..}\"\nproof -\n  from assms have \"s\\<^sub>o - s\\<^sub>e > v\\<^sub>e * \\<delta> - v\\<^sub>e\\<^sup>2 / 2 / a\\<^sub>e - v\\<^sub>o * \\<delta> - 1/2 * a\\<^sub>o * \\<delta>\\<^sup>2\" unfolding safe_distance_3r_def by auto\n  hence \"s\\<^sub>o + v\\<^sub>o * \\<delta> + 1/2 * a\\<^sub>o * \\<delta>\\<^sup>2 > s\\<^sub>e + v\\<^sub>e * \\<delta> - v\\<^sub>e\\<^sup>2 / 2 / a\\<^sub>e\" by auto\n  hence \"other.s \\<delta> > u_max\" using other.s_def u_max_eq assms(2) ego.q_def other.p_def pos_react by auto\n  thus ?thesis using cond_1r cond_3r_3 delayed_other_s_stop_eq delayed_safe_distance.other.s0_le_s_stop by linarith\nqed      \n\nlemma sd_2_at_least_sd_3:\n  assumes \"\\<delta> \\<le> other.t_stop\"\n  shows \"safe_distance_3r \\<ge> safe_distance_2r\"\nproof -\n  from assms have \"\\<delta> = other.t_stop \\<or> \\<delta> < other.t_stop\" by auto\n  then have \"safe_distance_3r = safe_distance_2r \\<or> safe_distance_3r > safe_distance_2r\"\n  proof (rule Meson.disj_forward)\n      assume \"\\<delta> = other.t_stop\"\n      hence \"\\<delta> = - v\\<^sub>o / a\\<^sub>o\" unfolding other.t_stop_def by auto\n      hence \"- v\\<^sub>o * \\<delta> - 1/2 * a\\<^sub>o * \\<delta>\\<^sup>2 = - v\\<^sub>o  * other.t_stop - 1/2 * a\\<^sub>o * other.t_stop\\<^sup>2\" by (simp add: movement.t_stop_def)\n      thus \"safe_distance_3r = safe_distance_2r\" \n        using other.p_def other.p_max_def other.p_max_eq safe_distance_2r_def safe_distance_3r_def by auto\n    next \n      assume \"\\<delta> < other.t_stop\"\n      hence \"\\<delta> < - v\\<^sub>o / a\\<^sub>o\" unfolding other.t_stop_def by auto\n      hence \"0 < v\\<^sub>o + a\\<^sub>o * \\<delta>\" \n        by (smt divide_right_mono_neg nonzero_mult_div_cancel_left other.decel)\n      hence \"0 < v\\<^sub>o + 1/2 * a\\<^sub>o * (\\<delta> + other.t_stop)\" by (auto simp add:field_simps other.t_stop_def)\n      hence \"0 > v\\<^sub>o * (\\<delta> - other.t_stop) + 1/2 * a\\<^sub>o * (\\<delta> + other.t_stop) * (\\<delta> - other.t_stop)\" \n        by (smt \\<open>\\<delta> < other.t_stop\\<close> linordered_field_class.sign_simps(35) linordered_field_class.sign_simps(45))\n      hence \" (\\<delta> + other.t_stop) * (\\<delta> - other.t_stop) = (\\<delta>\\<^sup>2 - other.t_stop\\<^sup>2)\" \n        by (simp add: power2_eq_square square_diff_square_factored)\n      hence \"0 > v\\<^sub>o * (\\<delta> - other.t_stop) + 1/2 * a\\<^sub>o * (\\<delta>\\<^sup>2 - other.t_stop\\<^sup>2)\" \n        by (metis (no_types, hide_lams) \\<open>v\\<^sub>o * (\\<delta> - other.t_stop) + 1 / 2 * a\\<^sub>o * (\\<delta> + other.t_stop) * (\\<delta> - other.t_stop) < 0\\<close> divide_divide_eq_left divide_divide_eq_right times_divide_eq_left)\n      hence \"0 > v\\<^sub>o * \\<delta> - v\\<^sub>o * other.t_stop  + 1/2 * a\\<^sub>o * \\<delta>\\<^sup>2 -  1/2 * a\\<^sub>o * other.t_stop\\<^sup>2 \" \n        by (simp add: linordered_field_class.sign_simps(38))\n      hence \"- v\\<^sub>o * \\<delta> - 1/2 * a\\<^sub>o * \\<delta>\\<^sup>2 > - v\\<^sub>o  * (- v\\<^sub>o / a\\<^sub>o) - 1/2 * a\\<^sub>o * (- v\\<^sub>o / a\\<^sub>o)\\<^sup>2\"  by (smt movement.t_stop_def mult_minus_left)\n      thus \"safe_distance_3r > safe_distance_2r\"\n        using other.p_def other.p_max_def other.p_max_eq other.t_stop_def safe_distance_2r_def safe_distance_3r_def by auto\n  qed\n  thus ?thesis by auto\nqed\nend\n\nsubsubsection \\<open>Designing Checker\\<close>\n(* checker function *)\ndefinition rel_dist_to_stop :: \"real \\<Rightarrow> real \\<Rightarrow> real\" where\n\"rel_dist_to_stop v a \\<equiv> - v\\<^sup>2 / (2 * a)\"\ndefinition \"rel_dist_to_stop_expr v a = Mult (Minus (Power (Var v) 2)) (Inverse (Mult (Num 2) (Var a)))\"\ndefinition \"rel_dist_to_stop' p v a = approx p (rel_dist_to_stop_expr 0 1) [v, a]\"\nlemma rel_dist_to_stop': \"interpret_floatarith (rel_dist_to_stop_expr 0 1) [v, a] = rel_dist_to_stop v a\"\n  by (simp add: rel_dist_to_stop_def rel_dist_to_stop_expr_def inverse_eq_divide)\n\ndefinition first_safe_dist :: \"real \\<Rightarrow> real \\<Rightarrow> real\" where\n\"first_safe_dist v\\<^sub>e a\\<^sub>e \\<equiv> rel_dist_to_stop v\\<^sub>e a\\<^sub>e\"\n\ndefinition second_safe_dist :: \"real \\<Rightarrow> real \\<Rightarrow> real \\<Rightarrow> real \\<Rightarrow> real\" where\n\"second_safe_dist v\\<^sub>e a\\<^sub>e v\\<^sub>o a\\<^sub>o \\<equiv> rel_dist_to_stop v\\<^sub>e a\\<^sub>e - rel_dist_to_stop v\\<^sub>o a\\<^sub>o\"\ndefinition \"second_safe_dist_expr ve ae vo ao =\n  Add (rel_dist_to_stop_expr ve ae) (Minus (rel_dist_to_stop_expr vo ao))\"\ndefinition \"second_safe_dist' p v\\<^sub>e a\\<^sub>e v\\<^sub>o a\\<^sub>o = approx p (second_safe_dist_expr 0 1 2 3) [v\\<^sub>e, a\\<^sub>e, v\\<^sub>o, a\\<^sub>o]\"\nlemma second_safe_dist':\n  \"interpret_floatarith (second_safe_dist_expr 0 1 2 3) [v, a, v', a'] = second_safe_dist v a v' a'\"\n  by (simp add: second_safe_dist_def second_safe_dist_expr_def rel_dist_to_stop_def rel_dist_to_stop_expr_def inverse_eq_divide)\n\ndefinition t_stop :: \"real \\<Rightarrow> real \\<Rightarrow> real\" where\n\"t_stop v a \\<equiv> - v / a\"\ndefinition \"t_stop_expr v a = Minus (Mult (Var v) (Inverse (Var a)))\"\n\ndefinition s_stop :: \"real \\<Rightarrow> real \\<Rightarrow> real \\<Rightarrow> real\" where\n\"s_stop s v a \\<equiv> s + rel_dist_to_stop v a\"\n\ndefinition discriminant :: \"real \\<Rightarrow> real \\<Rightarrow> real \\<Rightarrow> real \\<Rightarrow> real \\<Rightarrow> real \\<Rightarrow> real\" where\n\"discriminant s\\<^sub>e v\\<^sub>e a\\<^sub>e s\\<^sub>o v\\<^sub>o a\\<^sub>o \\<equiv> (v\\<^sub>o - v\\<^sub>e)\\<^sup>2 - 2 * (a\\<^sub>o - a\\<^sub>e) * (s\\<^sub>o - s\\<^sub>e)\"\n\ndefinition suff_cond_safe_dist2 :: \"real \\<Rightarrow> real \\<Rightarrow> real \\<Rightarrow> real \\<Rightarrow> real \\<Rightarrow> real \\<Rightarrow> bool\" where\n\"suff_cond_safe_dist2 s\\<^sub>e v\\<^sub>e a\\<^sub>e s\\<^sub>o v\\<^sub>o a\\<^sub>o \\<equiv> let D2 = discriminant s\\<^sub>e v\\<^sub>e a\\<^sub>e s\\<^sub>o v\\<^sub>o a\\<^sub>o in \n                                             \\<not> (a\\<^sub>e < a\\<^sub>o \\<and> v\\<^sub>o < v\\<^sub>e \\<and> 0 \\<le> D2 \\<and> v\\<^sub>e - a\\<^sub>e / a\\<^sub>o * v\\<^sub>o < sqrt D2)\"\n\nlemma less_sqrt_iff: \"y \\<ge> 0 \\<Longrightarrow> x < sqrt y \\<longleftrightarrow> (x \\<ge> 0 \\<longrightarrow> x\\<^sup>2 < y)\"\nby (smt real_le_lsqrt real_less_rsqrt real_sqrt_ge_zero)\n\n\nlemma suff_cond_safe_dist2_code[code]:\n  \"suff_cond_safe_dist2 s\\<^sub>e v\\<^sub>e a\\<^sub>e s\\<^sub>o v\\<^sub>o a\\<^sub>o =\n    (let D2 = discriminant s\\<^sub>e v\\<^sub>e a\\<^sub>e s\\<^sub>o v\\<^sub>o a\\<^sub>o in\n      (a\\<^sub>e < a\\<^sub>o \\<longrightarrow> v\\<^sub>o < v\\<^sub>e \\<longrightarrow> 0 \\<le> D2 \\<longrightarrow> (v\\<^sub>e - a\\<^sub>e / a\\<^sub>o * v\\<^sub>o \\<ge> 0 \\<and> (v\\<^sub>e - a\\<^sub>e / a\\<^sub>o * v\\<^sub>o)\\<^sup>2 \\<ge> D2)))\"\n  using real_sqrt_ge_zero real_less_rsqrt less_sqrt_iff\n  by (auto simp: suff_cond_safe_dist2_def Let_def)\n  \ntext \\<open>\nThere are two expressions for safe distance. The first safe distance safe_dist1 is always valid. \nWhenever the distance is bigger than safe_dist1, it is guarantee to be collision free. \n\nThe second one is safe_dist2. If the sufficient condition suff_cond_safe_dist2 is satisfied and \nthe distance is bigger than safe_dist2, it is guarantee to be collision free. \n\\<close>\n\ndefinition \"check_precond s\\<^sub>e v\\<^sub>e a\\<^sub>e s\\<^sub>o v\\<^sub>o a\\<^sub>o \\<longleftrightarrow> s\\<^sub>o > s\\<^sub>e \\<and> 0 \\<le> v\\<^sub>e \\<and> 0 \\<le> v\\<^sub>o \\<and> a\\<^sub>e < 0 \\<and> a\\<^sub>o < 0 \"\n\n(* TODO: get rid of check_precond: *)\nlemma check_precond_safe_distance: \"check_precond s\\<^sub>e v\\<^sub>e a\\<^sub>e s\\<^sub>o v\\<^sub>o a\\<^sub>o = safe_distance a\\<^sub>e v\\<^sub>e s\\<^sub>e a\\<^sub>o v\\<^sub>o s\\<^sub>o\"\nproof\n  assume \"safe_distance a\\<^sub>e v\\<^sub>e s\\<^sub>e a\\<^sub>o v\\<^sub>o s\\<^sub>o\"\n  then interpret safe_distance a\\<^sub>e v\\<^sub>e s\\<^sub>e a\\<^sub>o v\\<^sub>o s\\<^sub>o .\n  show \"check_precond s\\<^sub>e v\\<^sub>e a\\<^sub>e s\\<^sub>o v\\<^sub>o a\\<^sub>o\"\n    by (auto simp: check_precond_def; fact)\nqed (unfold_locales; auto simp: check_precond_def)\n  \ndefinition checker :: \"real \\<Rightarrow> real \\<Rightarrow> real \\<Rightarrow> real \\<Rightarrow> real \\<Rightarrow> real \\<Rightarrow> bool\" where\n\"checker s\\<^sub>e v\\<^sub>e a\\<^sub>e s\\<^sub>o v\\<^sub>o a\\<^sub>o \\<equiv> let distance = s\\<^sub>o - s\\<^sub>e;\n                                precond = check_precond s\\<^sub>e v\\<^sub>e a\\<^sub>e s\\<^sub>o v\\<^sub>o a\\<^sub>o;\n                                safe_dist1 = first_safe_dist v\\<^sub>e a\\<^sub>e; \n                                safe_dist2 = second_safe_dist v\\<^sub>e a\\<^sub>e v\\<^sub>o a\\<^sub>o;\n                                cond2 = suff_cond_safe_dist2 s\\<^sub>e v\\<^sub>e a\\<^sub>e s\\<^sub>o v\\<^sub>o a\\<^sub>o in\n                                  precond \\<and> (\n                                    safe_dist1 < distance \\<or> \n                                   (safe_dist2 < distance \\<and> distance \\<le> safe_dist1 \\<and> cond2))\"\n\nsubsubsection \\<open>prescriptive checker\\<close>\ntext \\<open>\\label{sec:checkerp}\\<close>\n\ndefinition checker2 :: \"real \\<Rightarrow> real \\<Rightarrow> real \\<Rightarrow> real \\<Rightarrow> real \\<Rightarrow> real \\<Rightarrow> bool\" where\n\"checker2 s\\<^sub>e v\\<^sub>e a\\<^sub>e s\\<^sub>o v\\<^sub>o a\\<^sub>o \\<equiv> let distance = s\\<^sub>o - s\\<^sub>e;\n                                precond = check_precond s\\<^sub>e v\\<^sub>e a\\<^sub>e s\\<^sub>o v\\<^sub>o a\\<^sub>o;\n                                safe_dist1 = first_safe_dist v\\<^sub>e a\\<^sub>e; \n                                safe_dist2 = second_safe_dist v\\<^sub>e a\\<^sub>e v\\<^sub>o a\\<^sub>o;\n                                safe_dist3 = - rel_dist_to_stop (v\\<^sub>o - v\\<^sub>e) (a\\<^sub>o - a\\<^sub>e) in\n                             if \\<not> precond then \n                                False \n                             else if distance > safe_dist1 then \n                                True \n                             else if a\\<^sub>o > a\\<^sub>e \\<and> v\\<^sub>o < v\\<^sub>e \\<and> v\\<^sub>e - a\\<^sub>e / a\\<^sub>o * v\\<^sub>o < 0 then\n                                distance > safe_dist3\n                             else \n                                distance > safe_dist2\"\n\nthm\n  safe_distance.cond_1\n  safe_distance.cond_2\n  safe_distance.cond_3'\ndefinition checker3 :: \"real \\<Rightarrow> real \\<Rightarrow> real \\<Rightarrow> real \\<Rightarrow> real \\<Rightarrow> real \\<Rightarrow> bool\" where\n\"checker3 s\\<^sub>e v\\<^sub>e a\\<^sub>e s\\<^sub>o v\\<^sub>o a\\<^sub>o \\<equiv> let distance = s\\<^sub>o - s\\<^sub>e;\n                                precond = check_precond s\\<^sub>e v\\<^sub>e a\\<^sub>e s\\<^sub>o v\\<^sub>o a\\<^sub>o;\n                                s_stop_e = s\\<^sub>e + rel_dist_to_stop v\\<^sub>e a\\<^sub>e;\n                                s_stop_o = s\\<^sub>o + rel_dist_to_stop v\\<^sub>o a\\<^sub>o in\n                                precond \\<and>\n                                (s_stop_e < s\\<^sub>o \\<or>\n                                (s\\<^sub>o \\<le> s_stop_e \\<and> s_stop_e < s_stop_o \\<and>\n                                (\\<not>(a\\<^sub>o > a\\<^sub>e \\<and> v\\<^sub>o < v\\<^sub>e \\<and> v\\<^sub>e - a\\<^sub>e / a\\<^sub>o * v\\<^sub>o < 0 \\<and> distance * (a\\<^sub>o - a\\<^sub>e) \\<le> (v\\<^sub>o - v\\<^sub>e)\\<^sup>2 / 2))))\"\n\ntheorem checker_eq_checker2: \"checker s\\<^sub>e v\\<^sub>e a\\<^sub>e s\\<^sub>o v\\<^sub>o a\\<^sub>o \\<longleftrightarrow> checker2 s\\<^sub>e v\\<^sub>e a\\<^sub>e s\\<^sub>o v\\<^sub>o a\\<^sub>o\"\nproof (cases \"check_precond s\\<^sub>e v\\<^sub>e a\\<^sub>e s\\<^sub>o v\\<^sub>o a\\<^sub>o\")\n  case False\n  with checker_def checker2_def\n  show ?thesis by auto\nnext\n  case True\n  with check_precond_def safe_distance_def \n  have \"safe_distance a\\<^sub>e v\\<^sub>e s\\<^sub>e a\\<^sub>o v\\<^sub>o s\\<^sub>o\"  by (simp add: check_precond_safe_distance)\n  \n  from this interpret safe_distance a\\<^sub>e v\\<^sub>e s\\<^sub>e a\\<^sub>o v\\<^sub>o s\\<^sub>o by auto\n  interpret ego: braking_movement a\\<^sub>e v\\<^sub>e s\\<^sub>e by (unfold_locales; fact)\n  interpret other: braking_movement a\\<^sub>o v\\<^sub>o s\\<^sub>o by (unfold_locales; fact)\n\n  from \\<open>check_precond s\\<^sub>e v\\<^sub>e a\\<^sub>e s\\<^sub>o v\\<^sub>o a\\<^sub>o\\<close>  cond_3 cond_3'[symmetric] fst_leq_snd_safe_distance\n  ego.s_t_stop ego.p_max_def ego.p_def ego.t_stop_def hyps other.s_t_stop other.p_max_def other.p_def \n  other.t_stop_def checker2_def checker_def suff_cond_safe_dist2_def fst_safe_distance_def \n  first_safe_dist_def snd_safe_distance_def second_safe_dist_def rel_dist_to_stop_def discriminant_def \n  show ?thesis\n  by (auto simp add:power_def Let_def split:if_splits)\nqed\n\n\ntheorem checker2_eq_checker3:\n  \"checker2 s\\<^sub>e v\\<^sub>e a\\<^sub>e s\\<^sub>o v\\<^sub>o a\\<^sub>o \\<longleftrightarrow> checker3 s\\<^sub>e v\\<^sub>e a\\<^sub>e s\\<^sub>o v\\<^sub>o a\\<^sub>o\"\n  apply (auto simp: checker2_def checker3_def Let_def first_safe_dist_def not_less\n    suff_cond_safe_dist2_def second_safe_dist_def rel_dist_to_stop_def check_precond_def)\nproof goal_cases\n  case 1\n  then interpret safe_distance\n    by unfold_locales auto\n  from fst_leq_snd_safe_distance 1\n  show ?case\n    by (auto simp: fst_safe_distance_def snd_safe_distance_def)\nnext\n  case 2\n  then interpret safe_distance\n    by unfold_locales auto\n  from fst_leq_snd_safe_distance 2\n  show ?case\n    by (auto simp: fst_safe_distance_def snd_safe_distance_def divide_simps algebra_simps)\nnext\n  case 3\n  then interpret safe_distance\n    by unfold_locales auto\n  from fst_leq_snd_safe_distance 3\n  show ?case\n    by (auto simp: fst_safe_distance_def snd_safe_distance_def divide_simps algebra_simps)\nqed\n\n(* proof that the exact checker guarantee collision free *)\nlemma aux_logic:\n  assumes \"a \\<Longrightarrow> b\"\n  assumes \"b \\<Longrightarrow> a \\<longleftrightarrow> c\"\n  shows \"a \\<longleftrightarrow> b \\<and> c\"\n  using assms by blast\n\ntheorem soundness_correctness:\n  \"checker s\\<^sub>e v\\<^sub>e a\\<^sub>e s\\<^sub>o v\\<^sub>o a\\<^sub>o \\<longleftrightarrow> check_precond s\\<^sub>e v\\<^sub>e a\\<^sub>e s\\<^sub>o v\\<^sub>o a\\<^sub>o \\<and> safe_distance.no_collision a\\<^sub>e v\\<^sub>e s\\<^sub>e a\\<^sub>o v\\<^sub>o s\\<^sub>o {0..}\"\nproof (rule aux_logic, simp add: checker_def Let_def)\n  assume cp: \"check_precond s\\<^sub>e v\\<^sub>e a\\<^sub>e s\\<^sub>o v\\<^sub>o a\\<^sub>o\"\n  then have in_front': \"s\\<^sub>o > s\\<^sub>e\"\n    and nonneg_vel_ego: \"0 \\<le> v\\<^sub>e\"\n    and nonneg_vel_other: \"0 \\<le> v\\<^sub>o\"\n    and decelerate_ego: \"a\\<^sub>e < 0\"\n    and decelerate_other: \"a\\<^sub>o < 0\"\n    by (auto simp: check_precond_def)\n\n  from in_front' have in_front: \"0 < s\\<^sub>o - s\\<^sub>e\" by arith\n\n  interpret safe_distance a\\<^sub>e v\\<^sub>e s\\<^sub>e a\\<^sub>o v\\<^sub>o s\\<^sub>o by (unfold_locales; fact)\n  interpret ego: braking_movement a\\<^sub>e v\\<^sub>e s\\<^sub>e by (unfold_locales; fact)\n  interpret other: braking_movement a\\<^sub>o v\\<^sub>o s\\<^sub>o by (unfold_locales; fact)\n\n  have \"ego.p_max < s\\<^sub>o \\<or> other.p_max \\<le> ego.p_max \\<or> s\\<^sub>o \\<le> ego.p_max \\<and> ego.p_max < other.p_max\"\n    by arith\n  then show \"checker s\\<^sub>e v\\<^sub>e a\\<^sub>e s\\<^sub>o v\\<^sub>o a\\<^sub>o = safe_distance.no_collision a\\<^sub>e v\\<^sub>e s\\<^sub>e a\\<^sub>o v\\<^sub>o s\\<^sub>o {0..}\"\n  proof (elim disjE)\n    assume \"ego.p_max < s\\<^sub>o\"\n    then have \"checker s\\<^sub>e v\\<^sub>e a\\<^sub>e s\\<^sub>o v\\<^sub>o a\\<^sub>o\"\n      using \\<open>a\\<^sub>e < 0\\<close> cp\n      by (simp add: checker_def Let_def first_safe_dist_def rel_dist_to_stop_def ego.p_max_def\n        ego.p_def ego.t_stop_def algebra_simps power2_eq_square)\n    moreover\n    have \"no_collision {0..}\"\n      using \\<open>ego.p_max < s\\<^sub>o\\<close>\n      by (intro cond_1) (auto simp: ego.s_t_stop)\n    ultimately show ?thesis by auto\n  next\n    assume \"other.p_max \\<le> ego.p_max\"\n    then have \"\\<not> checker s\\<^sub>e v\\<^sub>e a\\<^sub>e s\\<^sub>o v\\<^sub>o a\\<^sub>o\"\n      using \\<open>a\\<^sub>e < 0\\<close> \\<open>a\\<^sub>o < 0\\<close> other.nonneg_vel\n      by (auto simp add: checker_def Let_def first_safe_dist_def second_safe_dist_def\n        rel_dist_to_stop_def movement.p_max_def\n        movement.p_def movement.t_stop_def algebra_simps power2_eq_square)\n         (smt divide_nonneg_neg mult_nonneg_nonneg)\n    moreover have \"collision {0..}\"\n      using \\<open>other.p_max \\<le> ego.p_max\\<close>\n      by (intro cond_2) (auto simp: other.s_t_stop ego.s_t_stop)\n    ultimately show ?thesis by auto\n  next\n    assume H: \"s\\<^sub>o \\<le> ego.p_max \\<and> ego.p_max < other.p_max\"\n    then have \"checker s\\<^sub>e v\\<^sub>e a\\<^sub>e s\\<^sub>o v\\<^sub>o a\\<^sub>o = (\\<not> (a\\<^sub>e < a\\<^sub>o \\<and> v\\<^sub>o < v\\<^sub>e \\<and> 0 \\<le> D2 \\<and> v\\<^sub>e - a\\<^sub>e / a\\<^sub>o * v\\<^sub>o < sqrt D2))\"\n      using \\<open>a\\<^sub>e < 0\\<close> \\<open>a\\<^sub>o < 0\\<close> cp\n      by (simp add: checker_def Let_def first_safe_dist_def rel_dist_to_stop_def ego.p_max_def\n        ego.p_def ego.t_stop_def algebra_simps power2_eq_square second_safe_dist_def\n        suff_cond_safe_dist2_def discriminant_def not_less other.p_max_def other.p_def other.t_stop_def)\n    also have \"\\<dots> = no_collision {0..}\"\n      using H\n      unfolding Not_eq_iff\n      by (intro cond_3[symmetric]) (auto simp: ego.s_t_stop other.s_t_stop)\n    finally show ?thesis by auto\n  qed\nqed\n\nsubsubsection \\<open>Theorem 5\\<close>\ntext \\<open>\\label{sec:thm5}\\<close>\ntheorem soundness_correctness2:\n  \"checker2 s\\<^sub>e v\\<^sub>e a\\<^sub>e s\\<^sub>o v\\<^sub>o a\\<^sub>o \\<longleftrightarrow> check_precond s\\<^sub>e v\\<^sub>e a\\<^sub>e s\\<^sub>o v\\<^sub>o a\\<^sub>o \\<and> safe_distance.no_collision a\\<^sub>e v\\<^sub>e s\\<^sub>e a\\<^sub>o v\\<^sub>o s\\<^sub>o {0..}\"\n  unfolding soundness_correctness[symmetric] checker_eq_checker2 ..\n\nsubsubsection \\<open>Checker extended with reaction time delay\\<close>\ntext \\<open>\\label{sec:checker_react}\\<close>  \n(* We define two checkers for different cases: one checker for the case that \\<delta> \\<le> other.t_stop (other.t_stop = - v\\<^sub>o / a\\<^sub>o) and a second checker for the case that \\<delta> > other.t_stop *)\ndefinition \"check_precond_r1 s\\<^sub>e v\\<^sub>e a\\<^sub>e s\\<^sub>o v\\<^sub>o a\\<^sub>o \\<delta> \\<longleftrightarrow> s\\<^sub>o > s\\<^sub>e \\<and> 0 \\<le> v\\<^sub>e \\<and> 0 \\<le> v\\<^sub>o \\<and> a\\<^sub>e < 0 \\<and> a\\<^sub>o < 0 \\<and> 0 < \\<delta> \\<and> \\<delta> \\<le> - v\\<^sub>o / a\\<^sub>o\"\n    \ndefinition safe_distance0 where \"safe_distance0 v\\<^sub>e a\\<^sub>o v\\<^sub>o \\<delta> = v\\<^sub>e * \\<delta> - v\\<^sub>o * \\<delta> - a\\<^sub>o * \\<delta>\\<^sup>2 / 2\"\ndefinition safe_distance_1r where \"safe_distance_1r a\\<^sub>e v\\<^sub>e \\<delta> = v\\<^sub>e * \\<delta> - v\\<^sub>e\\<^sup>2 / a\\<^sub>e / 2\"  \ndefinition safe_distance_2r where \"safe_distance_2r a\\<^sub>e v\\<^sub>e a\\<^sub>o v\\<^sub>o \\<delta> = v\\<^sub>e * \\<delta> - v\\<^sub>e\\<^sup>2 / 2 / a\\<^sub>e + v\\<^sub>o\\<^sup>2 / 2 / a\\<^sub>o\"\ndefinition safe_distance_4r where \"safe_distance_4r a\\<^sub>e v\\<^sub>e a\\<^sub>o v\\<^sub>o \\<delta> =\n                               (v\\<^sub>o + a\\<^sub>o * \\<delta> - v\\<^sub>e)\\<^sup>2 / 2 / (a\\<^sub>o - a\\<^sub>e) - v\\<^sub>o * \\<delta> - 1 / 2 * a\\<^sub>o * \\<delta>\\<^sup>2 + v\\<^sub>e * \\<delta>\" \ndefinition safe_distance_3r where \"safe_distance_3r a\\<^sub>e v\\<^sub>e a\\<^sub>o v\\<^sub>o \\<delta> = \n                                                      v\\<^sub>e * \\<delta> - v\\<^sub>e\\<^sup>2 / 2 / a\\<^sub>e - v\\<^sub>o * \\<delta> - 1 / 2 * a\\<^sub>o * \\<delta>\\<^sup>2\"  \n          \ndefinition checker_r1 :: \"real \\<Rightarrow> real \\<Rightarrow> real \\<Rightarrow> real \\<Rightarrow> real \\<Rightarrow> real \\<Rightarrow> real \\<Rightarrow> bool\" where\n  \"checker_r1 s\\<^sub>e v\\<^sub>e a\\<^sub>e s\\<^sub>o v\\<^sub>o a\\<^sub>o \\<delta> \\<equiv> let distance = s\\<^sub>o - s\\<^sub>e;\n\t\t\t\tprecond = check_precond_r1 s\\<^sub>e v\\<^sub>e a\\<^sub>e s\\<^sub>o v\\<^sub>o a\\<^sub>o \\<delta>;\n        vo_star = v\\<^sub>o + a\\<^sub>o * \\<delta>;\n        t_stop_o_star = - vo_star / a\\<^sub>o; \n        t_stop_e = - v\\<^sub>e / a\\<^sub>e;\n        safe_dist0 = safe_distance_1r a\\<^sub>e v\\<^sub>e \\<delta>;\n        safe_dist1 = safe_distance_2r a\\<^sub>e v\\<^sub>e a\\<^sub>o v\\<^sub>o \\<delta>;\n        safe_dist2 = safe_distance_4r a\\<^sub>e v\\<^sub>e a\\<^sub>o v\\<^sub>o \\<delta>;\n        safe_dist3 = safe_distance_3r a\\<^sub>e v\\<^sub>e a\\<^sub>o v\\<^sub>o \\<delta> in \n   if \\<not> precond then \n      False\n   else if distance > safe_dist0 \\<or> distance > safe_dist3 then \n      True\n   else if (a\\<^sub>o > a\\<^sub>e \\<and> vo_star < v\\<^sub>e \\<and> t_stop_e < t_stop_o_star) then\n      distance > safe_dist2\n   else               \n      distance > safe_dist1\"  \n  \ntheorem checker_r1_correctness:\n  \"(checker_r1 s\\<^sub>e v\\<^sub>e a\\<^sub>e s\\<^sub>o v\\<^sub>o a\\<^sub>o \\<delta> \\<longleftrightarrow> check_precond_r1 s\\<^sub>e v\\<^sub>e a\\<^sub>e s\\<^sub>o v\\<^sub>o a\\<^sub>o \\<delta> \\<and> safe_distance_normal.no_collision_react a\\<^sub>e v\\<^sub>e s\\<^sub>e a\\<^sub>o v\\<^sub>o s\\<^sub>o \\<delta> {0..})\"\nproof \n  assume asm: \"checker_r1 s\\<^sub>e v\\<^sub>e a\\<^sub>e s\\<^sub>o v\\<^sub>o a\\<^sub>o \\<delta>\"\n  have pre: \"check_precond_r1 s\\<^sub>e v\\<^sub>e a\\<^sub>e s\\<^sub>o v\\<^sub>o a\\<^sub>o \\<delta>\"\n  proof (rule ccontr)\n    assume \"\\<not> check_precond_r1 s\\<^sub>e v\\<^sub>e a\\<^sub>e s\\<^sub>o v\\<^sub>o a\\<^sub>o \\<delta>\"  \n    with asm show \"False\" unfolding checker_r1_def Let_def by auto      \n  qed\n  from pre have sdn': \"safe_distance_normal a\\<^sub>e v\\<^sub>e s\\<^sub>e a\\<^sub>o v\\<^sub>o s\\<^sub>o \\<delta>\"\n    by (unfold_locales) (auto simp add: check_precond_r1_def)      \n  interpret sdn: safe_distance_normal a\\<^sub>e v\\<^sub>e s\\<^sub>e a\\<^sub>o v\\<^sub>o s\\<^sub>o \\<delta>\n    rewrites \"sdn.distance0 = safe_distance0 v\\<^sub>e a\\<^sub>o v\\<^sub>o \\<delta>\" and\n             \"sdn.safe_distance_1r = safe_distance_1r a\\<^sub>e v\\<^sub>e \\<delta>\" and\n             \"sdn.safe_distance_2r = safe_distance_2r a\\<^sub>e v\\<^sub>e a\\<^sub>o v\\<^sub>o \\<delta>\" and \n             \"sdn.safe_distance_4r = safe_distance_4r a\\<^sub>e v\\<^sub>e a\\<^sub>o v\\<^sub>o \\<delta>\" and \n             \"sdn.safe_distance_3r = safe_distance_3r a\\<^sub>e v\\<^sub>e a\\<^sub>o v\\<^sub>o \\<delta>\"\n  proof -\n    from sdn' show \"safe_distance_normal a\\<^sub>e v\\<^sub>e s\\<^sub>e a\\<^sub>o v\\<^sub>o s\\<^sub>o \\<delta>\" by auto\n  next\n    show \"safe_distance_normal.distance0 v\\<^sub>e a\\<^sub>o v\\<^sub>o \\<delta> = safe_distance0 v\\<^sub>e a\\<^sub>o v\\<^sub>o \\<delta> \"\n      unfolding safe_distance_normal.distance0_def[OF sdn'] safe_distance0_def by auto\n  next\n    show \"safe_distance_normal.safe_distance_1r a\\<^sub>e v\\<^sub>e \\<delta> = safe_distance_1r a\\<^sub>e v\\<^sub>e \\<delta>\"\n      unfolding safe_distance_normal.safe_distance_1r_def[OF sdn'] safe_distance_1r_def by auto\n  next\n    show \"safe_distance_normal.safe_distance_2r a\\<^sub>e v\\<^sub>e a\\<^sub>o v\\<^sub>o \\<delta> = safe_distance_2r a\\<^sub>e v\\<^sub>e a\\<^sub>o v\\<^sub>o \\<delta>\"\n      unfolding safe_distance_normal.safe_distance_2r_def[OF sdn'] safe_distance_2r_def by auto\n  next \n    show \"safe_distance_normal.safe_distance_4r a\\<^sub>e v\\<^sub>e a\\<^sub>o v\\<^sub>o \\<delta> = safe_distance_4r a\\<^sub>e v\\<^sub>e a\\<^sub>o v\\<^sub>o \\<delta> \"\n      unfolding safe_distance_normal.safe_distance_4r_def[OF sdn'] safe_distance_4r_def by auto\n  next\n    show \"safe_distance_normal.safe_distance_3r a\\<^sub>e v\\<^sub>e a\\<^sub>o v\\<^sub>o \\<delta> = safe_distance_3r a\\<^sub>e v\\<^sub>e a\\<^sub>o v\\<^sub>o \\<delta>\"\n      unfolding safe_distance_normal.safe_distance_3r_def[OF sdn'] safe_distance_3r_def by auto\n  qed    \n  have \"0 < \\<delta>\" and \"\\<delta> \\<le> - v\\<^sub>o / a\\<^sub>o\" using pre unfolding check_precond_r1_def by auto  \n  define so_delta where \"so_delta = s\\<^sub>o + v\\<^sub>o * \\<delta> + a\\<^sub>o * \\<delta>\\<^sup>2 / 2\"\n  define q_e_delta where \"q_e_delta \\<equiv> s\\<^sub>e + v\\<^sub>e * \\<delta>\" \n  define u_stop_e where \"u_stop_e \\<equiv> q_e_delta - v\\<^sub>e\\<^sup>2 / (2 * a\\<^sub>e)\"\n  define vo_star where \"vo_star = v\\<^sub>o + a\\<^sub>o * \\<delta>\"\n  define t_stop_o_star where \"t_stop_o_star \\<equiv> - vo_star / a\\<^sub>o\"\n  define t_stop_e where \"t_stop_e = - v\\<^sub>e / a\\<^sub>e\"\n  define distance where \"distance \\<equiv> s\\<^sub>o - s\\<^sub>e\"\n  define distance0 where \"distance0 = safe_distance0 v\\<^sub>e a\\<^sub>o v\\<^sub>o \\<delta>\"    \n  define safe_dist0 where \"safe_dist0 = safe_distance_1r a\\<^sub>e v\\<^sub>e \\<delta>\"          \n  define safe_dist2 where \"safe_dist2 \\<equiv> safe_distance_4r a\\<^sub>e v\\<^sub>e a\\<^sub>o v\\<^sub>o \\<delta>\"\n  define safe_dist1 where \"safe_dist1 \\<equiv> safe_distance_2r a\\<^sub>e v\\<^sub>e a\\<^sub>o v\\<^sub>o \\<delta>\"    \n  define safe_dist3 where \"safe_dist3 = safe_distance_3r a\\<^sub>e v\\<^sub>e a\\<^sub>o v\\<^sub>o \\<delta>\"        \n  note abb = so_delta_def q_e_delta_def u_stop_e_def vo_star_def t_stop_o_star_def t_stop_e_def\n             distance_def safe_dist2_def safe_dist1_def safe_dist0_def safe_dist3_def distance0_def\n  consider \"distance > safe_dist0\" | \"distance > safe_dist3\" | \"distance \\<le> safe_dist0 \\<and> distance \\<le> safe_dist3\"\n    by linarith\n  hence \"sdn.no_collision_react {0..}\"\n  proof (cases)\n    case 1\n    then show ?thesis using sdn.sd_1r_correct unfolding  abb by auto\n  next\n    case 2\n    hence pre2: \"distance > distance0\" using sdn.distance0_at_most_sd3r unfolding abb by auto\n    hence \"sdn.u \\<delta> < sdn.other.s \\<delta>\" using pre unfolding sdn.u_def sdn.ego.q_def\n      sdn.other.s_def sdn.other.t_stop_def sdn.other.p_def abb check_precond_r1_def sdn.distance0_def\n      by auto          \n    from pre interpret sdr: safe_distance_no_collsion_delta a\\<^sub>e v\\<^sub>e s\\<^sub>e a\\<^sub>o v\\<^sub>o s\\<^sub>o \\<delta>\n      by (unfold_locales) (auto simp add:check_precond_r1_def `sdn.u \\<delta> < sdn.other.s \\<delta>`)     \n    show ?thesis using sdr.sd_3r_correct 2 pre unfolding check_precond_r1_def abb sdn.other.t_stop_def\n      by auto                    \n  next\n    case 3\n    hence \"distance \\<le> safe_dist3\" by auto  \n    hence \"sdn.other.s \\<delta> \\<le> sdn.u_max\" using pre unfolding check_precond_r1_def sdn.other.s_def sdn.other.t_stop_def\n      sdn.other.p_def sdn.u_max_eq sdn.ego.q_def abb sdn.safe_distance_3r_def by auto        \n    have \" (a\\<^sub>o > a\\<^sub>e \\<and> vo_star < v\\<^sub>e \\<and> t_stop_e < t_stop_o_star) \\<or> \\<not>  (a\\<^sub>o > a\\<^sub>e \\<and> vo_star < v\\<^sub>e \\<and> t_stop_e < t_stop_o_star) \"\n      by auto\n    moreover\n    { assume cond: \"(a\\<^sub>o > a\\<^sub>e \\<and> vo_star < v\\<^sub>e \\<and> t_stop_e < t_stop_o_star)\"\n      with 3 pre have \"distance > safe_dist2\" using asm unfolding checker_r1_def\n          Let_def abb by auto\n      with sdn.distance0_at_most_sd4r have \"distance > distance0\" unfolding abb using cond by auto\n      hence \"sdn.u \\<delta> < sdn.other.s \\<delta>\" using pre unfolding sdn.u_def sdn.ego.q_def\n          sdn.other.s_def sdn.other.t_stop_def sdn.other.p_def abb check_precond_r1_def sdn.distance0_def\n        by auto          \n      from pre interpret sdr: safe_distance_no_collsion_delta a\\<^sub>e v\\<^sub>e s\\<^sub>e a\\<^sub>o v\\<^sub>o s\\<^sub>o \\<delta>\n        by (unfold_locales) (auto simp add:check_precond_r1_def `sdn.u \\<delta> < sdn.other.s \\<delta>`)               \n      from sdr.sd_4r_correct[OF _ `sdn.other.s \\<delta> \\<le> sdn.u_max`] `distance > safe_dist2` \n        have ?thesis using pre cond  unfolding check_precond_r1_def sdn.other.t_stop_def abb by auto }  \n    moreover\n    { assume not_cond: \"\\<not>  (a\\<^sub>o > a\\<^sub>e \\<and> vo_star < v\\<^sub>e \\<and> t_stop_e < t_stop_o_star)\"\n      with 3 pre have \"distance > safe_dist1\" using asm unfolding checker_r1_def   \n        Let_def abb by auto\n      with sdn.dist0_sd2r_1 have \"distance > distance0\" using pre not_cond unfolding check_precond_r1_def\n        sdn.other.t_stop_def sdn.other.s'_def sdn.other.p'_def abb by (auto simp add:field_simps) \n      hence \"sdn.u \\<delta> < sdn.other.s \\<delta>\" using pre unfolding sdn.u_def sdn.ego.q_def\n          sdn.other.s_def sdn.other.t_stop_def sdn.other.p_def abb check_precond_r1_def sdn.distance0_def\n        by auto          \n      from pre interpret sdr: safe_distance_no_collsion_delta a\\<^sub>e v\\<^sub>e s\\<^sub>e a\\<^sub>o v\\<^sub>o s\\<^sub>o \\<delta>\n        by (unfold_locales) (auto simp add:check_precond_r1_def `sdn.u \\<delta> < sdn.other.s \\<delta>`)                         \n      from sdr.sd_2r_correct_for_3r_2[OF _ `sdn.other.s \\<delta> \\<le> sdn.u_max`] not_cond `distance > safe_dist1` \n        have ?thesis using pre unfolding abb sdn.other.s'_def check_precond_r1_def sdn.other.t_stop_def sdn.other.p'_def\n        by (auto simp add:field_simps) }\n    ultimately show ?thesis by auto\n  qed\n  with pre show \" check_precond_r1 s\\<^sub>e v\\<^sub>e a\\<^sub>e s\\<^sub>o v\\<^sub>o a\\<^sub>o \\<delta> \\<and> sdn.no_collision_react {0..}\" by auto\nnext  \n  assume \"check_precond_r1 s\\<^sub>e v\\<^sub>e a\\<^sub>e s\\<^sub>o v\\<^sub>o a\\<^sub>o \\<delta> \\<and> safe_distance_normal.no_collision_react a\\<^sub>e v\\<^sub>e s\\<^sub>e a\\<^sub>o v\\<^sub>o s\\<^sub>o \\<delta> {0..}\"\n  hence pre: \"check_precond_r1 s\\<^sub>e v\\<^sub>e a\\<^sub>e s\\<^sub>o v\\<^sub>o a\\<^sub>o \\<delta>\" and as2: \"safe_distance_normal.no_collision_react a\\<^sub>e v\\<^sub>e s\\<^sub>e a\\<^sub>o v\\<^sub>o s\\<^sub>o \\<delta> {0..}\"\n  by auto\n  show \"checker_r1 s\\<^sub>e v\\<^sub>e a\\<^sub>e s\\<^sub>o v\\<^sub>o a\\<^sub>o \\<delta> \"\n  proof (rule ccontr)    \n    assume as1: \"\\<not> checker_r1 s\\<^sub>e v\\<^sub>e a\\<^sub>e s\\<^sub>o v\\<^sub>o a\\<^sub>o \\<delta>\"\n    from pre have \"0 < \\<delta>\" and \"\\<delta> \\<le> - v\\<^sub>o / a\\<^sub>o\" unfolding check_precond_r1_def by auto  \n    define so_delta where \"so_delta = s\\<^sub>o + v\\<^sub>o * \\<delta> + a\\<^sub>o * \\<delta>\\<^sup>2 / 2\"\n    define q_e_delta where \"q_e_delta \\<equiv> s\\<^sub>e + v\\<^sub>e * \\<delta>\" \n    define u_stop_e where \"u_stop_e \\<equiv> q_e_delta - v\\<^sub>e\\<^sup>2 / (2 * a\\<^sub>e)\"\n    define vo_star where \"vo_star \\<equiv> v\\<^sub>o + a\\<^sub>o * \\<delta>\"\n    define t_stop_o_star where \"t_stop_o_star \\<equiv> - vo_star / a\\<^sub>o\"\n    define t_stop_e where \"t_stop_e \\<equiv> - v\\<^sub>e / a\\<^sub>e\"\n    define distance where \"distance \\<equiv> s\\<^sub>o - s\\<^sub>e\"                   \n    define distance0 where \"distance0 \\<equiv> safe_distance0 v\\<^sub>e a\\<^sub>o v\\<^sub>o \\<delta>\"    \n    define safe_dist0 where \"safe_dist0 \\<equiv> safe_distance_1r a\\<^sub>e v\\<^sub>e \\<delta>\"          \n    define safe_dist2 where \"safe_dist2 \\<equiv> safe_distance_4r a\\<^sub>e v\\<^sub>e a\\<^sub>o v\\<^sub>o \\<delta>\"\n    define safe_dist1 where \"safe_dist1 \\<equiv> safe_distance_2r a\\<^sub>e v\\<^sub>e a\\<^sub>o v\\<^sub>o \\<delta>\"    \n    define safe_dist3 where \"safe_dist3 \\<equiv> safe_distance_3r a\\<^sub>e v\\<^sub>e a\\<^sub>o v\\<^sub>o \\<delta>\"        \n    note abb = so_delta_def q_e_delta_def u_stop_e_def vo_star_def t_stop_o_star_def t_stop_e_def\n               distance_def safe_dist2_def safe_dist1_def safe_dist0_def safe_dist3_def distance0_def\n    from pre have sdn': \"safe_distance_normal a\\<^sub>e v\\<^sub>e s\\<^sub>e a\\<^sub>o v\\<^sub>o s\\<^sub>o \\<delta>\"\n      by (unfold_locales) (auto simp add: check_precond_r1_def)      \n    interpret sdn: safe_distance_normal a\\<^sub>e v\\<^sub>e s\\<^sub>e a\\<^sub>o v\\<^sub>o s\\<^sub>o \\<delta>\n      rewrites \"sdn.distance0 = safe_distance0 v\\<^sub>e a\\<^sub>o v\\<^sub>o \\<delta>\" and\n               \"sdn.safe_distance_1r = safe_distance_1r a\\<^sub>e v\\<^sub>e \\<delta>\" and\n               \"sdn.safe_distance_2r = safe_distance_2r a\\<^sub>e v\\<^sub>e a\\<^sub>o v\\<^sub>o \\<delta>\" and \n               \"sdn.safe_distance_4r = safe_distance_4r a\\<^sub>e v\\<^sub>e a\\<^sub>o v\\<^sub>o \\<delta>\" and \n               \"sdn.safe_distance_3r = safe_distance_3r a\\<^sub>e v\\<^sub>e a\\<^sub>o v\\<^sub>o \\<delta>\"\n    proof -\n      from sdn' show \"safe_distance_normal a\\<^sub>e v\\<^sub>e s\\<^sub>e a\\<^sub>o v\\<^sub>o s\\<^sub>o \\<delta>\" by auto\n    next\n      show \"safe_distance_normal.distance0 v\\<^sub>e a\\<^sub>o v\\<^sub>o \\<delta> = safe_distance0 v\\<^sub>e a\\<^sub>o v\\<^sub>o \\<delta> \"\n        unfolding safe_distance_normal.distance0_def[OF sdn'] safe_distance0_def by auto\n    next\n      show \"safe_distance_normal.safe_distance_1r a\\<^sub>e v\\<^sub>e \\<delta> = safe_distance_1r a\\<^sub>e v\\<^sub>e \\<delta>\"\n        unfolding safe_distance_normal.safe_distance_1r_def[OF sdn'] safe_distance_1r_def by auto\n    next\n      show \"safe_distance_normal.safe_distance_2r a\\<^sub>e v\\<^sub>e a\\<^sub>o v\\<^sub>o \\<delta> = safe_distance_2r a\\<^sub>e v\\<^sub>e a\\<^sub>o v\\<^sub>o \\<delta>\"\n        unfolding safe_distance_normal.safe_distance_2r_def[OF sdn'] safe_distance_2r_def by auto\n    next \n      show \"safe_distance_normal.safe_distance_4r a\\<^sub>e v\\<^sub>e a\\<^sub>o v\\<^sub>o \\<delta> = safe_distance_4r a\\<^sub>e v\\<^sub>e a\\<^sub>o v\\<^sub>o \\<delta> \"\n        unfolding safe_distance_normal.safe_distance_4r_def[OF sdn'] safe_distance_4r_def by auto\n    next\n      show \"safe_distance_normal.safe_distance_3r a\\<^sub>e v\\<^sub>e a\\<^sub>o v\\<^sub>o \\<delta> = safe_distance_3r a\\<^sub>e v\\<^sub>e a\\<^sub>o v\\<^sub>o \\<delta>\"\n        unfolding safe_distance_normal.safe_distance_3r_def[OF sdn'] safe_distance_3r_def by auto\n    qed       \n    have \"\\<not> distance > distance0 \\<or>  distance > distance0\" by auto \n    moreover\n    { assume \"\\<not> distance > distance0\"\n      hence \"distance \\<le> distance0\" by auto\n      with sdn.cond_3r_1' have \"sdn.collision_react {0..\\<delta>}\" using pre unfolding check_precond_r1_def abb\n        sdn.other.t_stop_def by auto    \n      with sdn.collision_react_subset have \"sdn.collision_react {0..}\" by auto\n      with as2 have \"False\" by auto }    \n    moreover\n    { assume if2: \"distance > distance0\"\n      have \"\\<not> (distance > safe_dist0 \\<or> distance > safe_dist3)\"\n      proof (rule ccontr)  \n        assume \"\\<not> \\<not> (safe_dist0 < distance \\<or> safe_dist3 < distance)\"\n        hence \"(safe_dist0 < distance \\<or> safe_dist3 < distance)\" by auto\n        with as1 show \"False\" using pre if2 unfolding checker_r1_def Let_def abb\n          by auto\n      qed\n      hence if31: \"distance \\<le> safe_dist0\" and if32: \"distance \\<le> safe_dist3\" by auto\n      have \"sdn.u \\<delta> < sdn.other.s \\<delta>\" using if2 pre unfolding sdn.u_def sdn.ego.q_def\n          sdn.other.s_def sdn.other.t_stop_def sdn.other.p_def abb check_precond_r1_def sdn.distance0_def\n          by auto\n      from pre interpret sdr: safe_distance_no_collsion_delta a\\<^sub>e v\\<^sub>e s\\<^sub>e a\\<^sub>o v\\<^sub>o s\\<^sub>o \\<delta>\n        by (unfold_locales) (auto simp add:check_precond_r1_def `sdn.u \\<delta> < sdn.other.s \\<delta>`)   \n      have \" s\\<^sub>o \\<le> sdn.u_max\" using if31 unfolding sdn.u_max_eq sdn.ego.q_def abb \n        sdn.safe_distance_1r_def by auto      \n      have \"sdn.other.s \\<delta> \\<le> sdn.u_max\" using if32 pre unfolding sdn.other.s_def check_precond_r1_def\n        sdn.other.t_stop_def sdn.other.p_def sdn.u_max_eq sdn.ego.q_def abb sdn.safe_distance_3r_def\n        by auto\n      consider \"(a\\<^sub>o > a\\<^sub>e \\<and> vo_star < v\\<^sub>e \\<and> t_stop_e < t_stop_o_star)\" | \n               \"\\<not> (a\\<^sub>o > a\\<^sub>e \\<and> vo_star < v\\<^sub>e \\<and> t_stop_e < t_stop_o_star)\" by auto\n      hence \"False\" \n      proof (cases)\n        case 1\n        hence rest_conjunct:\"(a\\<^sub>e < a\\<^sub>o \\<and> sdn.other.s' \\<delta> < v\\<^sub>e \\<and> v\\<^sub>e - a\\<^sub>e / a\\<^sub>o * sdn.other.s' \\<delta> < 0)\"\n          using pre unfolding check_precond_r1_def unfolding sdn.other.s'_def sdn.other.t_stop_def\n          sdn.other.p'_def abb by (auto simp add:field_simps)\n        from 1 have \"distance \\<le> safe_dist2\" using as1 pre if2 if31 if32 unfolding checker_r1_def\n          Let_def abb by auto\n        hence cond_f: \"sdn.other.s \\<delta> - sdn.ego.q \\<delta> \\<le> sdr.delayed_safe_distance.snd_safe_distance\" \n          using pre unfolding check_precond_r1_def sdn.other.s_def sdn.other.t_stop_def sdn.other.p_def\n          sdn.ego.q_def sdr.delayed_safe_distance.snd_safe_distance_def using sdn.other.s'_def[of \"\\<delta>\"]\n          unfolding sdn.other.t_stop_def sdn.other.p'_def abb sdn.safe_distance_4r_def\n          by auto            \n        have \"distance > safe_dist1 \\<or> distance \\<le> safe_dist1\" by auto\n        moreover\n        { assume \"distance > safe_dist1\"\n          hence \"sdn.u_max < sdn.other.s_stop\" unfolding sdn.u_max_eq sdn.ego.q_def sdn.other.s_t_stop\n              sdn.other.p_max_eq abb sdn.safe_distance_2r_def by (auto simp add:field_simps)\n          from sdr.cond_3r_2[OF `s\\<^sub>o \\<le> sdn.u_max` this `sdn.other.s \\<delta> \\<le> sdn.u_max`] \n          have \"sdn.collision_react {0..}\" using cond_f rest_conjunct by auto\n          with as2 have \"False\" by auto }\n        moreover\n        { assume \"distance \\<le> safe_dist1\"\n          hence \"sdn.u_max \\<ge> sdn.other.s_stop\" unfolding sdn.u_max_eq sdn.ego.q_def sdn.other.s_t_stop\n              sdn.other.p_max_eq abb sdn.safe_distance_2r_def by (auto simp add:field_simps)            \n          with sdn.cond_2r[OF this] have \"sdn.collision_react {0..}\" by auto\n          with as2 have \"False\" by auto }\n        ultimately show ?thesis by auto\n      next\n        case 2\n        hence \"distance \\<le> safe_dist1\" using as1 pre if2 if31 if32 unfolding checker_r1_def\n          Let_def abb by auto\n        hence \"sdn.u_max \\<ge> sdn.other.s_stop\" unfolding sdn.u_max_eq sdn.ego.q_def sdn.other.s_t_stop\n          sdn.other.p_max_eq abb sdn.safe_distance_2r_def by (auto simp add:field_simps)            \n        with sdn.cond_2r[OF this] have \"sdn.collision_react {0..}\" by auto\n        with as2 show \"False\" by auto                     \n      qed }\n    ultimately show \"False\" by auto  \n  qed  \nqed            \n  \ndefinition \"check_precond_r2 s\\<^sub>e v\\<^sub>e a\\<^sub>e s\\<^sub>o v\\<^sub>o a\\<^sub>o \\<delta> \\<longleftrightarrow> s\\<^sub>o > s\\<^sub>e \\<and> 0 \\<le> v\\<^sub>e \\<and> 0 \\<le> v\\<^sub>o \\<and> a\\<^sub>e < 0 \\<and> a\\<^sub>o < 0 \\<and> 0 < \\<delta> \\<and> \\<delta> > - v\\<^sub>o / a\\<^sub>o\"\ndefinition safe_distance0_2 where \"safe_distance0_2 v\\<^sub>e a\\<^sub>o v\\<^sub>o \\<delta> = v\\<^sub>e * \\<delta> + 1 / 2 * v\\<^sub>o\\<^sup>2 / a\\<^sub>o\"\n\ndefinition checker_r2 :: \"real \\<Rightarrow> real \\<Rightarrow> real \\<Rightarrow> real \\<Rightarrow> real \\<Rightarrow> real \\<Rightarrow> real \\<Rightarrow> bool\" where\n  \"checker_r2 s\\<^sub>e v\\<^sub>e a\\<^sub>e s\\<^sub>o v\\<^sub>o a\\<^sub>o \\<delta> \\<equiv> let distance = s\\<^sub>o - s\\<^sub>e;\n\t\t\t\tprecond = check_precond_r2 s\\<^sub>e v\\<^sub>e a\\<^sub>e s\\<^sub>o v\\<^sub>o a\\<^sub>o \\<delta>;\n        safe_dist0 = safe_distance_1r a\\<^sub>e v\\<^sub>e \\<delta>;\n        safe_dist1 = safe_distance_2r a\\<^sub>e v\\<^sub>e a\\<^sub>o v\\<^sub>o \\<delta> in \n   if \\<not> precond then \n      False\n   else if distance > safe_dist0 then \n      True\n   else              \n      distance > safe_dist1\"\n\ntheorem checker_r2_correctness:\n  \"(checker_r2 s\\<^sub>e v\\<^sub>e a\\<^sub>e s\\<^sub>o v\\<^sub>o a\\<^sub>o \\<delta> \\<longleftrightarrow> check_precond_r2 s\\<^sub>e v\\<^sub>e a\\<^sub>e s\\<^sub>o v\\<^sub>o a\\<^sub>o \\<delta> \\<and> safe_distance_normal.no_collision_react a\\<^sub>e v\\<^sub>e s\\<^sub>e a\\<^sub>o v\\<^sub>o s\\<^sub>o \\<delta> {0..})\"\nproof\n  assume asm: \"checker_r2 s\\<^sub>e v\\<^sub>e a\\<^sub>e s\\<^sub>o v\\<^sub>o a\\<^sub>o \\<delta>\"\n  have pre: \"check_precond_r2 s\\<^sub>e v\\<^sub>e a\\<^sub>e s\\<^sub>o v\\<^sub>o a\\<^sub>o \\<delta>\"\n  proof (rule ccontr)\n    assume \"\\<not> check_precond_r2 s\\<^sub>e v\\<^sub>e a\\<^sub>e s\\<^sub>o v\\<^sub>o a\\<^sub>o \\<delta>\"\n      with asm show \"False\" unfolding checker_r2_def Let_def by auto      \n    qed\n      from pre have sdn': \"safe_distance_normal a\\<^sub>e v\\<^sub>e s\\<^sub>e a\\<^sub>o v\\<^sub>o s\\<^sub>o \\<delta>\"\n    by (unfold_locales) (auto simp add: check_precond_r2_def)      \n  interpret sdn: safe_distance_normal a\\<^sub>e v\\<^sub>e s\\<^sub>e a\\<^sub>o v\\<^sub>o s\\<^sub>o \\<delta>\n    rewrites \"sdn.distance0_2 = safe_distance0_2 v\\<^sub>e a\\<^sub>o v\\<^sub>o \\<delta>\" and\n             \"sdn.safe_distance_1r = safe_distance_1r a\\<^sub>e v\\<^sub>e \\<delta>\" and\n             \"sdn.safe_distance_2r = safe_distance_2r a\\<^sub>e v\\<^sub>e a\\<^sub>o v\\<^sub>o \\<delta>\"\n  proof -\n    from sdn' show \"safe_distance_normal a\\<^sub>e v\\<^sub>e s\\<^sub>e a\\<^sub>o v\\<^sub>o s\\<^sub>o \\<delta>\" by auto\n  next \n    show \"safe_distance_normal.distance0_2 v\\<^sub>e a\\<^sub>o v\\<^sub>o \\<delta> = safe_distance0_2 v\\<^sub>e a\\<^sub>o v\\<^sub>o \\<delta>\"\n      unfolding safe_distance_normal.distance0_2_def[OF sdn'] safe_distance0_2_def by auto\n  next\n    show \"safe_distance_normal.safe_distance_1r a\\<^sub>e v\\<^sub>e \\<delta> = safe_distance_1r a\\<^sub>e v\\<^sub>e \\<delta>\"\n      unfolding safe_distance_normal.safe_distance_1r_def[OF sdn'] safe_distance_1r_def by auto\n  next\n    show \"safe_distance_normal.safe_distance_2r a\\<^sub>e v\\<^sub>e a\\<^sub>o v\\<^sub>o \\<delta> = safe_distance_2r a\\<^sub>e v\\<^sub>e a\\<^sub>o v\\<^sub>o \\<delta>\"\n      unfolding safe_distance_normal.safe_distance_2r_def[OF sdn'] safe_distance_2r_def by auto\n  qed\n  have \"0 < \\<delta>\" and \"\\<delta> > - v\\<^sub>o / a\\<^sub>o\" using pre unfolding check_precond_r2_def by auto\n  define distance where \"distance \\<equiv> s\\<^sub>o - s\\<^sub>e\"\n  define distance0_2 where \"distance0_2 = safe_distance0_2 v\\<^sub>e a\\<^sub>o v\\<^sub>o \\<delta>\"    \n  define safe_dist0 where \"safe_dist0 = safe_distance_1r a\\<^sub>e v\\<^sub>e \\<delta>\"    \n  define safe_dist1 where \"safe_dist1 \\<equiv> safe_distance_2r a\\<^sub>e v\\<^sub>e a\\<^sub>o v\\<^sub>o \\<delta>\"  \n  note abb = distance_def safe_dist1_def safe_dist0_def distance0_2_def\n  consider \"distance > safe_dist0\" | \"distance \\<le> safe_dist0\"\n    by linarith\n  hence \"sdn.no_collision_react {0..}\"\n  proof (cases)\n    case 1\n    then show ?thesis using sdn.sd_1r_correct unfolding abb by auto\n  next\n    case 2\n    hence \"(s\\<^sub>o \\<le> sdn.u_max)\" using distance_def safe_dist0_def sdn.sd_1r_eq by linarith\n    with 2 pre have \"distance > safe_dist1\" using asm unfolding checker_r2_def Let_def abb by auto\n    with sdn.dist0_sd2r_2 have \"distance > distance0_2\" using abb \\<open>- v\\<^sub>o / a\\<^sub>o < \\<delta>\\<close> by auto\n    hence \"sdn.u \\<delta> < sdn.other.s \\<delta>\" using abb sdn.distance0_2_eq \\<open>\\<delta> > - v\\<^sub>o / a\\<^sub>o\\<close> sdn.other.t_stop_def by auto\n    have \"sdn.u_max < sdn.other.s \\<delta>\" using abb sdn.sd2r_eq  \\<open>\\<delta> > - v\\<^sub>o / a\\<^sub>o\\<close> sdn.other.t_stop_def `distance > safe_dist1` by auto\n    from pre interpret sdr: safe_distance_no_collsion_delta a\\<^sub>e v\\<^sub>e s\\<^sub>e a\\<^sub>o v\\<^sub>o s\\<^sub>o \\<delta>\n        by (unfold_locales) (auto simp add:check_precond_r2_def `sdn.u \\<delta> < sdn.other.s \\<delta>`)      \n    from sdr.sd_2r_correct_for_3r_3[OF] `distance > safe_dist1` `sdn.u \\<delta> < sdn.other.s \\<delta>` `sdn.u_max < sdn.other.s \\<delta>`\n       show ?thesis using pre unfolding abb sdn.other.s'_def check_precond_r2_def sdn.other.t_stop_def sdn.other.p'_def\n            by (auto simp add:field_simps)             \n  qed\n  with pre show \" check_precond_r2 s\\<^sub>e v\\<^sub>e a\\<^sub>e s\\<^sub>o v\\<^sub>o a\\<^sub>o \\<delta> \\<and> sdn.no_collision_react {0..}\" by auto\nnext\n  assume \"check_precond_r2 s\\<^sub>e v\\<^sub>e a\\<^sub>e s\\<^sub>o v\\<^sub>o a\\<^sub>o \\<delta> \\<and> safe_distance_normal.no_collision_react a\\<^sub>e v\\<^sub>e s\\<^sub>e a\\<^sub>o v\\<^sub>o s\\<^sub>o \\<delta> {0..}\"\n  hence pre: \"check_precond_r2 s\\<^sub>e v\\<^sub>e a\\<^sub>e s\\<^sub>o v\\<^sub>o a\\<^sub>o \\<delta>\" and as2: \"safe_distance_normal.no_collision_react a\\<^sub>e v\\<^sub>e s\\<^sub>e a\\<^sub>o v\\<^sub>o s\\<^sub>o \\<delta> {0..}\"\n    by auto\n  show \"checker_r2 s\\<^sub>e v\\<^sub>e a\\<^sub>e s\\<^sub>o v\\<^sub>o a\\<^sub>o \\<delta>\"\n  proof (rule ccontr)\n    assume as1: \"\\<not> checker_r2 s\\<^sub>e v\\<^sub>e a\\<^sub>e s\\<^sub>o v\\<^sub>o a\\<^sub>o \\<delta>\"\n    from pre have \"0 < \\<delta>\" and \"\\<delta> > - v\\<^sub>o / a\\<^sub>o\" unfolding check_precond_r2_def by auto\n    define distance where \"distance \\<equiv> s\\<^sub>o - s\\<^sub>e\"\n    define distance0_2 where \"distance0_2 = safe_distance0_2 v\\<^sub>e a\\<^sub>o v\\<^sub>o \\<delta>\"    \n    define safe_dist0 where \"safe_dist0 = safe_distance_1r a\\<^sub>e v\\<^sub>e \\<delta>\"    \n    define safe_dist1 where \"safe_dist1 \\<equiv> safe_distance_2r a\\<^sub>e v\\<^sub>e a\\<^sub>o v\\<^sub>o \\<delta>\"  \n    note abb = distance_def safe_dist1_def safe_dist0_def distance0_2_def\n    from pre have sdn': \"safe_distance_normal a\\<^sub>e v\\<^sub>e s\\<^sub>e a\\<^sub>o v\\<^sub>o s\\<^sub>o \\<delta>\"\n      by (unfold_locales) (auto simp add: check_precond_r2_def) \n   interpret sdn: safe_distance_normal a\\<^sub>e v\\<^sub>e s\\<^sub>e a\\<^sub>o v\\<^sub>o s\\<^sub>o \\<delta>\n    rewrites \"sdn.distance0_2 = safe_distance0_2 v\\<^sub>e a\\<^sub>o v\\<^sub>o \\<delta>\" and\n             \"sdn.safe_distance_1r = safe_distance_1r a\\<^sub>e v\\<^sub>e \\<delta>\" and\n             \"sdn.safe_distance_2r = safe_distance_2r a\\<^sub>e v\\<^sub>e a\\<^sub>o v\\<^sub>o \\<delta>\"\n    proof -\n      from sdn' show \"safe_distance_normal a\\<^sub>e v\\<^sub>e s\\<^sub>e a\\<^sub>o v\\<^sub>o s\\<^sub>o \\<delta>\" by auto\n    next \n      show \"safe_distance_normal.distance0_2 v\\<^sub>e a\\<^sub>o v\\<^sub>o \\<delta> = safe_distance0_2 v\\<^sub>e a\\<^sub>o v\\<^sub>o \\<delta>\"\n        unfolding safe_distance_normal.distance0_2_def[OF sdn'] safe_distance0_2_def by auto\n    next\n      show \"safe_distance_normal.safe_distance_1r a\\<^sub>e v\\<^sub>e \\<delta> = safe_distance_1r a\\<^sub>e v\\<^sub>e \\<delta>\"\n        unfolding safe_distance_normal.safe_distance_1r_def[OF sdn'] safe_distance_1r_def by auto\n    next\n      show \"safe_distance_normal.safe_distance_2r a\\<^sub>e v\\<^sub>e a\\<^sub>o v\\<^sub>o \\<delta> = safe_distance_2r a\\<^sub>e v\\<^sub>e a\\<^sub>o v\\<^sub>o \\<delta>\"\n        unfolding safe_distance_normal.safe_distance_2r_def[OF sdn'] safe_distance_2r_def by auto\n    qed\n    have \"\\<not> distance > distance0_2 \\<or>  distance > distance0_2\" by auto \n    moreover\n    { assume \"\\<not> distance > distance0_2\"\n      hence \"distance \\<le> distance0_2\" by auto\n      with sdn.cond_3r_1'_2 have \"sdn.collision_react {0..\\<delta>}\" using pre unfolding check_precond_r2_def abb sdn.other.t_stop_def by auto    \n      with sdn.collision_react_subset have \"sdn.collision_react {0..}\" by auto\n      with as2 have \"False\" by auto } \n    moreover\n    { assume if2: \"distance > distance0_2\"\n      have \"\\<not> (distance > safe_dist0)\"\n      proof (rule ccontr)  \n        assume \"\\<not> \\<not> (safe_dist0 < distance)\"\n        hence \"(safe_dist0 < distance)\" by auto\n        with as1 show \"False\" using pre if2 unfolding checker_r2_def Let_def abb by auto\n      qed\n      hence if3: \"distance \\<le> safe_dist0\" by auto\n      with pre have \"distance \\<le> safe_dist1\" using as1 unfolding checker_r2_def Let_def abb by auto\n   \n      have \"sdn.u \\<delta> < sdn.other.s \\<delta>\" using abb if2 sdn.distance0_2_eq \\<open>\\<delta> > - v\\<^sub>o / a\\<^sub>o\\<close> sdn.other.t_stop_def by auto\n      from pre interpret sdr: safe_distance_no_collsion_delta a\\<^sub>e v\\<^sub>e s\\<^sub>e a\\<^sub>o v\\<^sub>o s\\<^sub>o \\<delta>\n          by (unfold_locales) (auto simp add:check_precond_r2_def `sdn.u \\<delta> < sdn.other.s \\<delta>`)      \n      have \"sdn.u_max \\<ge> sdn.other.s \\<delta>\" using abb sdn.sd2r_eq  \\<open>\\<delta> > - v\\<^sub>o / a\\<^sub>o\\<close> sdn.other.t_stop_def `distance \\<le> safe_dist1` by auto\n      with `\\<delta> > - v\\<^sub>o / a\\<^sub>o` have \"sdn.u_max \\<ge> sdn.other.s_stop\" by (smt movement.t_stop_def sdn.other.s_mono sdn.other.t_stop_nonneg)\n      hence \"sdn.collision_react {0..}\" using sdn.cond_2r by auto\n      with as2 have \"False\" by auto }\n    ultimately show \"False\" by auto\n  qed\nqed\n \n(* combine the two checkers into one*)\ndefinition \"check_precond_r s\\<^sub>e v\\<^sub>e a\\<^sub>e s\\<^sub>o v\\<^sub>o a\\<^sub>o \\<delta> \\<longleftrightarrow> s\\<^sub>o > s\\<^sub>e \\<and> 0 \\<le> v\\<^sub>e \\<and> 0 \\<le> v\\<^sub>o \\<and> a\\<^sub>e < 0 \\<and> a\\<^sub>o < 0 \\<and> 0 < \\<delta>\"\ndefinition checker_r :: \"real \\<Rightarrow> real \\<Rightarrow> real \\<Rightarrow> real \\<Rightarrow> real \\<Rightarrow> real \\<Rightarrow> real \\<Rightarrow> bool\" where\n  \"checker_r s\\<^sub>e v\\<^sub>e a\\<^sub>e s\\<^sub>o v\\<^sub>o a\\<^sub>o \\<delta> \\<equiv> let distance = s\\<^sub>o - s\\<^sub>e;\n\t\t\t\tprecond = check_precond_r s\\<^sub>e v\\<^sub>e a\\<^sub>e s\\<^sub>o v\\<^sub>o a\\<^sub>o \\<delta>;\n        vo_star = v\\<^sub>o + a\\<^sub>o * \\<delta>;\n        t_stop_o_star = - vo_star / a\\<^sub>o; \n        t_stop_e = - v\\<^sub>e / a\\<^sub>e;\n        t_stop_o = - v\\<^sub>o / a\\<^sub>o;\n        safe_dist0 = safe_distance_1r a\\<^sub>e v\\<^sub>e \\<delta>;\n        safe_dist1 = safe_distance_2r a\\<^sub>e v\\<^sub>e a\\<^sub>o v\\<^sub>o \\<delta>;\n        safe_dist2 = safe_distance_4r a\\<^sub>e v\\<^sub>e a\\<^sub>o v\\<^sub>o \\<delta>;\n        safe_dist3 = safe_distance_3r a\\<^sub>e v\\<^sub>e a\\<^sub>o v\\<^sub>o \\<delta> in \n   if \\<not> precond then \n      False\n   else if distance > safe_dist0 then \n      True\n   else if \\<delta> \\<le> t_stop_o \\<and> distance > safe_dist3 then \n      True\n   else if \\<delta> \\<le> t_stop_o \\<and> (a\\<^sub>o > a\\<^sub>e \\<and> vo_star < v\\<^sub>e \\<and> t_stop_e < t_stop_o_star) then\n      distance > safe_dist2\n   else               \n      distance > safe_dist1\"\n  \ntheorem checker_eq_1:\n  \"checker_r s\\<^sub>e v\\<^sub>e a\\<^sub>e s\\<^sub>o v\\<^sub>o a\\<^sub>o \\<delta> \\<and> \\<delta> \\<le> - v\\<^sub>o / a\\<^sub>o  \\<longleftrightarrow> checker_r1 s\\<^sub>e v\\<^sub>e a\\<^sub>e s\\<^sub>o v\\<^sub>o a\\<^sub>o \\<delta>\"\nproof -\n  have \"checker_r s\\<^sub>e v\\<^sub>e a\\<^sub>e s\\<^sub>o v\\<^sub>o a\\<^sub>o \\<delta> \\<and> \\<delta> \\<le> - v\\<^sub>o / a\\<^sub>o \\<longleftrightarrow> check_precond_r s\\<^sub>e v\\<^sub>e a\\<^sub>e s\\<^sub>o v\\<^sub>o a\\<^sub>o \\<delta> \n    \\<and> (s\\<^sub>o - s\\<^sub>e > safe_distance_1r a\\<^sub>e v\\<^sub>e \\<delta> \n        \\<or> s\\<^sub>o - s\\<^sub>e > safe_distance_3r a\\<^sub>e v\\<^sub>e a\\<^sub>o v\\<^sub>o \\<delta>\n        \\<or> (((a\\<^sub>o > a\\<^sub>e \\<and> v\\<^sub>o + a\\<^sub>o * \\<delta> < v\\<^sub>e \\<and> - v\\<^sub>e / a\\<^sub>e < - (v\\<^sub>o + a\\<^sub>o * \\<delta>) / a\\<^sub>o) \\<longrightarrow> s\\<^sub>o - s\\<^sub>e > safe_distance_4r a\\<^sub>e v\\<^sub>e a\\<^sub>o v\\<^sub>o \\<delta>)\n            \\<and> (\\<not> (a\\<^sub>o > a\\<^sub>e \\<and> v\\<^sub>o + a\\<^sub>o * \\<delta> < v\\<^sub>e \\<and> - v\\<^sub>e / a\\<^sub>e < - (v\\<^sub>o + a\\<^sub>o * \\<delta>) / a\\<^sub>o) \\<longrightarrow> s\\<^sub>o - s\\<^sub>e > safe_distance_2r a\\<^sub>e v\\<^sub>e a\\<^sub>o v\\<^sub>o \\<delta>)))\n    \\<and> \\<delta> \\<le> - v\\<^sub>o / a\\<^sub>o\" using checker_r_def by metis\n  also have \"... \\<longleftrightarrow> check_precond_r1 s\\<^sub>e v\\<^sub>e a\\<^sub>e s\\<^sub>o v\\<^sub>o a\\<^sub>o \\<delta> \n    \\<and> (s\\<^sub>o - s\\<^sub>e > safe_distance_1r a\\<^sub>e v\\<^sub>e \\<delta> \n        \\<or> s\\<^sub>o - s\\<^sub>e > safe_distance_3r a\\<^sub>e v\\<^sub>e a\\<^sub>o v\\<^sub>o \\<delta>\n        \\<or> (((a\\<^sub>o > a\\<^sub>e \\<and> v\\<^sub>o + a\\<^sub>o * \\<delta> < v\\<^sub>e \\<and> - v\\<^sub>e / a\\<^sub>e < - (v\\<^sub>o + a\\<^sub>o * \\<delta>) / a\\<^sub>o) \\<longrightarrow> s\\<^sub>o - s\\<^sub>e > safe_distance_4r a\\<^sub>e v\\<^sub>e a\\<^sub>o v\\<^sub>o \\<delta>)\n            \\<and> (\\<not> (a\\<^sub>o > a\\<^sub>e \\<and> v\\<^sub>o + a\\<^sub>o * \\<delta> < v\\<^sub>e \\<and> - v\\<^sub>e / a\\<^sub>e < - (v\\<^sub>o + a\\<^sub>o * \\<delta>) / a\\<^sub>o) \\<longrightarrow> s\\<^sub>o - s\\<^sub>e > safe_distance_2r a\\<^sub>e v\\<^sub>e a\\<^sub>o v\\<^sub>o \\<delta>)))\"\n    by (auto simp add:check_precond_r_def check_precond_r1_def)\n  also have \"... \\<longleftrightarrow> checker_r1 s\\<^sub>e v\\<^sub>e a\\<^sub>e s\\<^sub>o v\\<^sub>o a\\<^sub>o \\<delta>\" by (metis checker_r1_def)\n  finally show ?thesis by auto\nqed\n     \ntheorem checker_eq_2:\n  \"checker_r s\\<^sub>e v\\<^sub>e a\\<^sub>e s\\<^sub>o v\\<^sub>o a\\<^sub>o \\<delta> \\<and> \\<delta> > - v\\<^sub>o / a\\<^sub>o \\<longleftrightarrow> checker_r2 s\\<^sub>e v\\<^sub>e a\\<^sub>e s\\<^sub>o v\\<^sub>o a\\<^sub>o \\<delta>\"\nproof -\n  have \"checker_r s\\<^sub>e v\\<^sub>e a\\<^sub>e s\\<^sub>o v\\<^sub>o a\\<^sub>o \\<delta> \\<and> \\<delta> > - v\\<^sub>o / a\\<^sub>o \\<longleftrightarrow> check_precond_r s\\<^sub>e v\\<^sub>e a\\<^sub>e s\\<^sub>o v\\<^sub>o a\\<^sub>o \\<delta> \\<and> (\\<not> check_precond_r s\\<^sub>e v\\<^sub>e a\\<^sub>e s\\<^sub>o v\\<^sub>o a\\<^sub>o \\<delta> \\<or>\n   s\\<^sub>o - s\\<^sub>e > safe_distance_1r a\\<^sub>e v\\<^sub>e \\<delta> \\<or> \n   (\\<delta> \\<le> - v\\<^sub>o / a\\<^sub>o \\<and> s\\<^sub>o - s\\<^sub>e > safe_distance_3r a\\<^sub>e v\\<^sub>e a\\<^sub>o v\\<^sub>o \\<delta>) \\<or>\n   (\\<delta> \\<le> - v\\<^sub>o / a\\<^sub>o \\<and> a\\<^sub>o > a\\<^sub>e \\<and> v\\<^sub>o + a\\<^sub>o * \\<delta> < v\\<^sub>e \\<and> - v\\<^sub>e / a\\<^sub>e < - (v\\<^sub>o + a\\<^sub>o * \\<delta>) / a\\<^sub>o \\<and> s\\<^sub>o - s\\<^sub>e > safe_distance_4r a\\<^sub>e v\\<^sub>e a\\<^sub>o v\\<^sub>o \\<delta>) \\<or> \n   s\\<^sub>o - s\\<^sub>e > safe_distance_2r a\\<^sub>e v\\<^sub>e a\\<^sub>o v\\<^sub>o \\<delta>) \\<and> \\<delta> > - v\\<^sub>o / a\\<^sub>o\" unfolding checker_r_def Let_def if_splits by auto\n  also have \n   \"... \\<longleftrightarrow> check_precond_r s\\<^sub>e v\\<^sub>e a\\<^sub>e s\\<^sub>o v\\<^sub>o a\\<^sub>o \\<delta> \n   \\<and> (s\\<^sub>o - s\\<^sub>e > safe_distance_1r a\\<^sub>e v\\<^sub>e \\<delta> \\<or> s\\<^sub>o - s\\<^sub>e > safe_distance_2r a\\<^sub>e v\\<^sub>e a\\<^sub>o v\\<^sub>o \\<delta>)\n   \\<and> \\<delta> > - v\\<^sub>o / a\\<^sub>o\"  by (auto simp add:HOL.disjE)\n  also have\n    \"... \\<longleftrightarrow> check_precond_r2 s\\<^sub>e v\\<^sub>e a\\<^sub>e s\\<^sub>o v\\<^sub>o a\\<^sub>o \\<delta>\n   \\<and> (s\\<^sub>o - s\\<^sub>e > safe_distance_1r a\\<^sub>e v\\<^sub>e \\<delta> \\<or> s\\<^sub>o - s\\<^sub>e > safe_distance_2r a\\<^sub>e v\\<^sub>e a\\<^sub>o v\\<^sub>o \\<delta>)\"\n    by (auto simp add:check_precond_r_def check_precond_r2_def)\n  also have \"... \\<longleftrightarrow> checker_r2 s\\<^sub>e v\\<^sub>e a\\<^sub>e s\\<^sub>o v\\<^sub>o a\\<^sub>o \\<delta>\" by (auto simp add:checker_r2_def Let_def if_splits)\n  thus ?thesis using calculation by auto\nqed\n     \ntheorem checker_r_correctness:\n  \"(checker_r s\\<^sub>e v\\<^sub>e a\\<^sub>e s\\<^sub>o v\\<^sub>o a\\<^sub>o \\<delta> \\<longleftrightarrow> check_precond_r s\\<^sub>e v\\<^sub>e a\\<^sub>e s\\<^sub>o v\\<^sub>o a\\<^sub>o \\<delta> \\<and> safe_distance_normal.no_collision_react a\\<^sub>e v\\<^sub>e s\\<^sub>e a\\<^sub>o v\\<^sub>o s\\<^sub>o \\<delta> {0..})\"\nproof -\n  have \"checker_r s\\<^sub>e v\\<^sub>e a\\<^sub>e s\\<^sub>o v\\<^sub>o a\\<^sub>o \\<delta> \\<longleftrightarrow> (checker_r s\\<^sub>e v\\<^sub>e a\\<^sub>e s\\<^sub>o v\\<^sub>o a\\<^sub>o \\<delta> \\<and> \\<delta> \\<le> - v\\<^sub>o / a\\<^sub>o) \\<or> (checker_r s\\<^sub>e v\\<^sub>e a\\<^sub>e s\\<^sub>o v\\<^sub>o a\\<^sub>o \\<delta> \\<and> \\<delta> > - v\\<^sub>o / a\\<^sub>o)\" by auto\n  also have \"... \\<longleftrightarrow> checker_r1 s\\<^sub>e v\\<^sub>e a\\<^sub>e s\\<^sub>o v\\<^sub>o a\\<^sub>o \\<delta> \\<or> checker_r2 s\\<^sub>e v\\<^sub>e a\\<^sub>e s\\<^sub>o v\\<^sub>o a\\<^sub>o \\<delta>\" using checker_eq_1 checker_eq_2 by auto\n  also have \"... \\<longleftrightarrow> (check_precond_r1 s\\<^sub>e v\\<^sub>e a\\<^sub>e s\\<^sub>o v\\<^sub>o a\\<^sub>o \\<delta> \\<and> safe_distance_normal.no_collision_react a\\<^sub>e v\\<^sub>e s\\<^sub>e a\\<^sub>o v\\<^sub>o s\\<^sub>o \\<delta> {0..})\n      \\<or> (check_precond_r2 s\\<^sub>e v\\<^sub>e a\\<^sub>e s\\<^sub>o v\\<^sub>o a\\<^sub>o \\<delta> \\<and> safe_distance_normal.no_collision_react a\\<^sub>e v\\<^sub>e s\\<^sub>e a\\<^sub>o v\\<^sub>o s\\<^sub>o \\<delta> {0..})\" \n    using checker_r1_correctness checker_r2_correctness by auto\n  also have \"... \\<longleftrightarrow> (\\<delta> \\<le> - v\\<^sub>o / a\\<^sub>o \\<and> check_precond_r s\\<^sub>e v\\<^sub>e a\\<^sub>e s\\<^sub>o v\\<^sub>o a\\<^sub>o \\<delta> \\<and> safe_distance_normal.no_collision_react a\\<^sub>e v\\<^sub>e s\\<^sub>e a\\<^sub>o v\\<^sub>o s\\<^sub>o \\<delta> {0..})\n      \\<or> (\\<delta> > - v\\<^sub>o / a\\<^sub>o \\<and> check_precond_r s\\<^sub>e v\\<^sub>e a\\<^sub>e s\\<^sub>o v\\<^sub>o a\\<^sub>o \\<delta> \\<and> safe_distance_normal.no_collision_react a\\<^sub>e v\\<^sub>e s\\<^sub>e a\\<^sub>o v\\<^sub>o s\\<^sub>o \\<delta> {0..})\" \n    by (auto simp add:check_precond_r_def check_precond_r1_def check_precond_r2_def)\n  also have \"... \\<longleftrightarrow> check_precond_r s\\<^sub>e v\\<^sub>e a\\<^sub>e s\\<^sub>o v\\<^sub>o a\\<^sub>o \\<delta> \\<and> safe_distance_normal.no_collision_react a\\<^sub>e v\\<^sub>e s\\<^sub>e a\\<^sub>o v\\<^sub>o s\\<^sub>o \\<delta> {0..}\"\n    by auto\n  finally show ?thesis by auto\nqed\n\nsubsection \\<open>serialize printing\\<close>\n\nconsts print::\"String.literal \\<Rightarrow> unit\"\nconsts integer_to_string::\"integer \\<Rightarrow> String.literal\"\nconsts concat_string::\"String.literal \\<Rightarrow> String.literal \\<Rightarrow> String.literal\" (infixr \"@s\" 65)\n\ndefinition \"int_to_string x = integer_to_string (integer_of_int x)\"\ncode_printing\n  constant print \\<rightharpoonup> (SML) \"TextIO.print\"\n| constant integer_to_string \\<rightharpoonup> (SML) \"IntInf.toString\"\n| constant concat_string \\<rightharpoonup> (SML) \"String.^ ((_), (_))\"\n| constant String.explode \\<rightharpoonup> (SML) \"String.explode\"\n\nclass \"show\" = fixes \"show\"::\"'a \\<Rightarrow> String.literal\"\n\ninstantiation nat::\"show\"\nbegin\ndefinition \"show_nat n = (int_to_string (int n))\"\ninstance proof qed\nend\n\ninstantiation int::\"show\"\nbegin\ndefinition \"show_int i = int_to_string i\"\ninstance proof qed\nend\n\ninstantiation float::\"show\"\nbegin\ndefinition \"show_float f = (show (mantissa f) @s STR ''*2^('' @s show (exponent f)) @s STR '')''\"\ninstance proof qed\nend\n\nsubsection \\<open>approximate checker\\<close>\n\nlemma checker2_def': \"checker2 a b c d e f =\n  (let distance = d - a;\n    precond = check_precond a b c d e f;\n    safe_dist1 = first_safe_dist b c;\n    safe_dist2 = second_safe_dist b c e f;\n    C = c < f \\<and> e < b \\<and> b * f > c * e;\n    P1 = (e - b)\\<^sup>2 < 2 * distance * (f - c);\n    P2 = - b\\<^sup>2 / c + e\\<^sup>2 / f < 2 * distance\n    in precond \\<and>\n      (safe_dist1 < distance \\<or>\n      safe_dist1 \\<ge> distance \\<and> (C \\<and> P1 \\<or> \\<not>C \\<and> P2)))\"\n  unfolding checker2_def\n  by (auto simp: Let_def algebra_simps divide_simps check_precond_def second_safe_dist_def\n    rel_dist_to_stop_def)\n\nlemma power2_less_sqrt_iff: \"(x::real)\\<^sup>2 < y \\<longleftrightarrow> (y \\<ge> 0 \\<and> abs x < sqrt y)\"\n  apply (auto simp: real_less_rsqrt abs_real_def less_sqrt_iff)\n  apply (meson le_less le_less_trans not_less power2_less_0)+\n  done\n\nschematic_goal checker_form: \"interpret_form ?x ?y \\<Longrightarrow> checker s\\<^sub>e v\\<^sub>e a\\<^sub>e s\\<^sub>o v\\<^sub>o a\\<^sub>o\"\n  unfolding checker_eq_checker2 checker2_eq_checker3 checker3_def check_precond_def first_safe_dist_def second_safe_dist_def\n    suff_cond_safe_dist2_def Let_def t_stop_def s_stop_def\n    rel_dist_to_stop_def\n    discriminant_def\n    not_le not_less\n    de_Morgan_conj\n    de_Morgan_disj\n    power2_less_sqrt_iff        \n  apply (tactic \\<open>(Reification.tac @{context} @{thms interpret_form.simps interpret_floatarith.simps interpret_floatarith_divide interpret_floatarith_diff}) NONE 1\\<close>)\n  apply assumption\n  done\n\ndefinition \"print_width l u f = (let _ = print (show (u - l) @s STR ''\\<newline>'') in f)\"\n  \ndefinition \"checker' p s\\<^sub>e v\\<^sub>e a\\<^sub>e s\\<^sub>o v\\<^sub>o a\\<^sub>o = approx_form p\n           (Conj (Conj (Less (Var (Suc (Suc 0))) (Var (Suc (Suc (Suc 0)))))\n                   (Conj (LessEqual (Var (Suc (Suc (Suc (Suc (Suc (Suc (Suc 0)))))))) (Var (Suc (Suc (Suc (Suc (Suc 0)))))))\n                     (Conj (LessEqual (Var (Suc (Suc (Suc (Suc (Suc (Suc (Suc 0)))))))) (Var (Suc (Suc (Suc (Suc (Suc (Suc 0))))))))\n                       (Conj (Less (Var 0) (Var (Suc (Suc (Suc (Suc (Suc (Suc (Suc 0)))))))))\n                         (Less (Var (Suc 0)) (Var (Suc (Suc (Suc (Suc (Suc (Suc (Suc 0)))))))))))))\n             (Disj (Less (Add (Var (Suc (Suc 0)))\n                           (Mult (Minus (Power (Var (Suc (Suc (Suc (Suc (Suc 0)))))) 2)) (Inverse (Mult (Var (Suc (Suc (Suc (Suc 0))))) (Var 0)))))\n                     (Var (Suc (Suc (Suc 0)))))\n               (Conj (LessEqual (Var (Suc (Suc (Suc 0))))\n                       (Add (Var (Suc (Suc 0)))\n                         (Mult (Minus (Power (Var (Suc (Suc (Suc (Suc (Suc 0)))))) 2)) (Inverse (Mult (Var (Suc (Suc (Suc (Suc 0))))) (Var 0))))))\n                 (Conj (Less (Add (Var (Suc (Suc 0)))\n                               (Mult (Minus (Power (Var (Suc (Suc (Suc (Suc (Suc 0)))))) 2)) (Inverse (Mult (Var (Suc (Suc (Suc (Suc 0))))) (Var 0)))))\n                         (Add (Var (Suc (Suc (Suc 0))))\n                           (Mult (Minus (Power (Var (Suc (Suc (Suc (Suc (Suc (Suc 0))))))) 2))\n                             (Inverse (Mult (Var (Suc (Suc (Suc (Suc 0))))) (Var (Suc 0)))))))\n                   (Disj (LessEqual (Var (Suc 0)) (Var 0))\n                     (Disj (LessEqual (Var (Suc (Suc (Suc (Suc (Suc 0)))))) (Var (Suc (Suc (Suc (Suc (Suc (Suc 0))))))))\n                       (Disj (LessEqual (Var (Suc (Suc (Suc (Suc (Suc (Suc (Suc 0))))))))\n                               (Add (Var (Suc (Suc (Suc (Suc (Suc 0))))))\n                                 (Minus (Mult (Mult (Var 0) (Inverse (Var (Suc 0)))) (Var (Suc (Suc (Suc (Suc (Suc (Suc 0)))))))))))\n                         (Less (Mult (Power (Add (Var (Suc (Suc (Suc (Suc (Suc (Suc 0))))))) (Minus (Var (Suc (Suc (Suc (Suc (Suc 0)))))))) 2)\n                                 (Inverse (Var (Suc (Suc (Suc (Suc 0)))))))\n                           (Mult (Add (Var (Suc (Suc (Suc 0)))) (Minus (Var (Suc (Suc 0))))) (Add (Var (Suc 0)) (Minus (Var 0))))))))))))\n  (map Some [a\\<^sub>e, a\\<^sub>o, s\\<^sub>e, s\\<^sub>o, (Float 2 0, Float 2 0),v\\<^sub>e, v\\<^sub>o, (Float 0 1, Float 0 1)]) (replicate 8 0)\"\n\nlemma less_Suc_iff_disj: \"i < Suc x \\<longleftrightarrow> i = x \\<or> i < x\"\n  by auto\n    \nlemma checker':\n  assumes \"a \\<in> {real_of_float al .. real_of_float au}\"\n  assumes \"b \\<in> {real_of_float bl .. real_of_float bu}\"\n  assumes \"c \\<in> {real_of_float cl .. real_of_float cu}\"\n  assumes \"d \\<in> {real_of_float dl .. real_of_float du}\"\n  assumes \"e \\<in> {real_of_float el .. real_of_float eu}\"\n  assumes \"f \\<in> {real_of_float fl .. real_of_float fu}\"\n  assumes chk: \"checker' p (al, au) (bl, bu) (cl, cu) (dl, du) (el, eu) (fl, fu)\"\n  shows \"checker a b c d e f\"\n  apply (rule checker_form)\n  apply (rule approx_form_aux)\n  apply (rule chk[unfolded checker'_def])\n  using assms(1-6)\n  by (auto simp: bounded_by_def less_Suc_iff_disj)\n\nsubsubsection\\<open>Theorem 6\\<close>\ntext \\<open>\\label{sec:thm6}\\<close>\nlemma\n  assumes \"a \\<in> {real_of_float al .. real_of_float au}\"\n  assumes \"b \\<in> {real_of_float bl .. real_of_float bu}\"\n  assumes \"c \\<in> {real_of_float cl .. real_of_float cu}\"\n  assumes \"d \\<in> {real_of_float dl .. real_of_float du}\"\n  assumes \"e \\<in> {real_of_float el .. real_of_float eu}\"\n  assumes \"f \\<in> {real_of_float fl .. real_of_float fu}\"\n  assumes chk: \"checker' p (al, au) (bl, bu) (cl, cu) (dl, du) (el, eu) (fl, fu)\"\n  shows checker'_precond: \"check_precond a b c d e f\"\n    and checker'_no_collision: \"safe_distance.no_collision c b a f e d  {0..}\"\n  unfolding atomize_conj\n  apply (subst soundness_correctness[symmetric])\n  using checker'[OF assms]\n  by (auto simp: checker_def Let_def)\n\nsubsection \\<open>a more direct (?) approach\\<close>\n\nlemma \"x \\<in> {-2 .. 0::real} \\<longrightarrow> x * (x + 2) > -4.1\"\n  by (approximation 40)\n\ndefinition symbolic_checker :: \"real \\<Rightarrow> real \\<Rightarrow> real \\<Rightarrow> real \\<Rightarrow> real \\<Rightarrow> real \\<Rightarrow> bool\" where\n\"symbolic_checker s\\<^sub>e v\\<^sub>e a\\<^sub>e s\\<^sub>o v\\<^sub>o a\\<^sub>o \\<equiv>\n  let\n    e_stop = - v\\<^sub>e / a\\<^sub>e;\n    o_stop = - v\\<^sub>o / a\\<^sub>o\n  in\n    check_precond s\\<^sub>e v\\<^sub>e a\\<^sub>e s\\<^sub>o v\\<^sub>o a\\<^sub>o \\<and>\n    (\\<not>quadroot_in 0 (min e_stop o_stop) (1/2 * (a\\<^sub>o - a\\<^sub>e)) (v\\<^sub>o - v\\<^sub>e) (s\\<^sub>o - s\\<^sub>e) \\<and>\n    \\<not>quadroot_in e_stop o_stop (1/2 * a\\<^sub>o) v\\<^sub>o (s\\<^sub>o - movement.p a\\<^sub>e v\\<^sub>e s\\<^sub>e e_stop) \\<and>\n    \\<not>quadroot_in o_stop e_stop (1/2 * a\\<^sub>e) v\\<^sub>e (s\\<^sub>e - movement.p a\\<^sub>o v\\<^sub>o s\\<^sub>o o_stop))\"\n\ntheorem symbolic_soundness_correctness:\n  \"symbolic_checker s\\<^sub>e v\\<^sub>e a\\<^sub>e s\\<^sub>o v\\<^sub>o a\\<^sub>o \\<longleftrightarrow> check_precond s\\<^sub>e v\\<^sub>e a\\<^sub>e s\\<^sub>o v\\<^sub>o a\\<^sub>o \\<and> safe_distance.no_collision a\\<^sub>e v\\<^sub>e s\\<^sub>e a\\<^sub>o v\\<^sub>o s\\<^sub>o {0..}\"\nproof -\n  {\n    assume c: \"check_precond s\\<^sub>e v\\<^sub>e a\\<^sub>e s\\<^sub>o v\\<^sub>o a\\<^sub>o\"\n    then interpret safe_distance a\\<^sub>e v\\<^sub>e s\\<^sub>e a\\<^sub>o v\\<^sub>o s\\<^sub>o\n      by (simp add: check_precond_safe_distance)\n    have \"symbolic_checker s\\<^sub>e v\\<^sub>e a\\<^sub>e s\\<^sub>o v\\<^sub>o a\\<^sub>o = no_collision {0..}\"\n      using c\n      unfolding symbolic_checker symbolic_checker_def ego.s_t_stop other.s_t_stop ego.p_max_def other.p_max_def\n      by (auto simp: Let_def movement.t_stop_def)\n  }\n  then show ?thesis\n    by (auto simp: symbolic_checker_def Let_def)\nqed\n\n\nsubsection \\<open>Checking using global optimizaition\\<close>\n\ndefinition \"parabola a b c x = Add c (Mult x (Add b (Mult x a)))\"\n\ndefinition \"check_precond_form s\\<^sub>e v\\<^sub>e a\\<^sub>e s\\<^sub>o v\\<^sub>o a\\<^sub>o =\n  Conj (Less (Var s\\<^sub>e) (Var s\\<^sub>o))\n  (Conj (LessEqual (Num 0) (Var v\\<^sub>e))\n    (Conj (LessEqual (Num 0) (Var v\\<^sub>o))\n      (Conj (Less (Var a\\<^sub>e) (Num 0)) (Less (Var a\\<^sub>o) (Num 0)))))\"\n\n\nlemma interpret_parabola:\n  \"interpret_floatarith (parabola (Var 0) (Var 1) (Var 2) (Var 3)) [a, b, c, x] =\n    a * x\\<^sup>2 + b * x + c\"\n  by (simp add: parabola_def algebra_simps power2_eq_square)\n\ndefinition \"nroot_in_form a b x f =\n  (let nonzero = (\\<lambda>x. Less (Num 0) (Abs x))\n  in (Bound (Var x) a b (nonzero f)))\"\n\nlemma \"interpret_form (nroot_in_form a b x f) xs \\<longleftrightarrow>\n  \\<not>(root_in (interpret_floatarith a xs) (interpret_floatarith b xs) (\\<lambda>s. interpret_floatarith f (xs[x:=s])))\"\n  unfolding nroot_in_form_def Let_def\n  unfolding interpret_form.simps interpret_floatarith.simps\n  oops\n\nlemma\n  \"(\\<forall>t. (t \\<in> A \\<longrightarrow> P t) \\<and> (t \\<in> B \\<longrightarrow> Q t)) \\<longleftrightarrow> (\\<forall>t \\<in> A. P t) \\<and> (\\<forall>t \\<in> B. Q t)\"\n  by (auto)\n\ndefinition\n  checker_form where\n  \"checker_form s\\<^sub>e v\\<^sub>e a\\<^sub>e s\\<^sub>o v\\<^sub>o a\\<^sub>o t =\n    (let\n      e_stop = Minus (Mult (Var v\\<^sub>e) (Inverse (Var a\\<^sub>e)));\n      o_stop = Minus (Mult (Var v\\<^sub>o) (Inverse (Var a\\<^sub>o)));\n      nonzero = (\\<lambda>x. Less (Num 0) (Abs x));\n      half = (\\<lambda>x. Mult (Inverse (Num 2)) x);\n      minus = (\\<lambda>x y. Add x (Minus y));\n      minusv = (\\<lambda>x y. minus (Var x) (Var y));\n      mov_p = (\\<lambda>a v s t. parabola (half (Var a)) (Var v) (Var s) t)\n    in Conj (check_precond_form s\\<^sub>e v\\<^sub>e a\\<^sub>e s\\<^sub>o v\\<^sub>o a\\<^sub>o)\n      (Conj\n        (Bound (Var t) (Num 0) (Min e_stop o_stop)\n          (nonzero (parabola (half (minusv a\\<^sub>o a\\<^sub>e)) (minusv v\\<^sub>o v\\<^sub>e) (minusv s\\<^sub>o s\\<^sub>e) (Var t))))\n      (Conj\n        (Bound (Var t) e_stop o_stop\n          (nonzero (parabola (half (Var a\\<^sub>o)) (Var v\\<^sub>o) (minus (Var s\\<^sub>o) (mov_p a\\<^sub>e v\\<^sub>e s\\<^sub>e e_stop)) (Var t))))\n        (Bound (Var t) o_stop e_stop\n          (nonzero (parabola (half (Var a\\<^sub>e)) (Var v\\<^sub>e) (minus (Var s\\<^sub>e) (mov_p a\\<^sub>o v\\<^sub>o s\\<^sub>o o_stop)) (Var t)))))))\"\n\nlemma \"interpret_form (check_precond_form i j k l m n) xs =\n  check_precond (xs ! i) (xs ! j) (xs ! k) (xs ! l) (xs ! m) (xs ! n)\"\n  by (auto simp: check_precond_form_def check_precond_def)\n  \n\nlemma \"interpret_form (checker_form 0 1 2 3 4 5 6) [se, ve, ae, so, vo, ao, t] =\n  symbolic_checker se ve ae so vo ao\"\n  apply (auto simp: checker_form_def Let_def )\n  unfolding symbolic_checker_def Let_def\n  oops\n\nend", "meta": {"author": "rizaldialbert", "repo": "overtaking", "sha": "0e76426d75f791635cd9e23b8e07669b7ce61a81", "save_path": "github-repos/isabelle/rizaldialbert-overtaking", "path": "github-repos/isabelle/rizaldialbert-overtaking/overtaking-0e76426d75f791635cd9e23b8e07669b7ce61a81/safe_distance/Safe_Distance_Isar.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467611766711, "lm_q2_score": 0.8354835350552604, "lm_q1q2_score": 0.7345126438602679}}
{"text": "(*\n    File:      Multiplicative_Function.thy\n    Author:    Manuel Eberl, TU M\u00fcnchen\n*)\nsection \\<open>Multiplicative arithmetic functions\\<close>\ntheory Multiplicative_Function\n  imports \n    \"HOL-Number_Theory.Number_Theory\" \n    Dirichlet_Misc\nbegin\n\nsubsection \\<open>Definition\\<close>\n\nlocale multiplicative_function =\n  fixes f :: \"nat \\<Rightarrow> 'a :: comm_semiring_1\"\n  assumes zero [simp]: \"f 0 = 0\"\n  assumes one [simp]: \"f 1 = 1\"\n  assumes mult_coprime_aux: \"a > 1 \\<Longrightarrow> b > 1 \\<Longrightarrow> coprime a b \\<Longrightarrow> f (a * b) = f a * f b\"\nbegin\n\nlemma Suc_0 [simp]: \"f (Suc 0) = 1\"\n  using one by (simp del: one)\n    \nlemma mult_coprime:\n  assumes \"coprime a b\"\n  shows   \"f (a * b) = f a * f b\"\nproof -\n  {fix n :: nat consider \"n = 0\" | \"n = 1\" | \"n > 1\" by force} note P = this\n  show ?thesis by (cases a rule: P; cases b rule: P) (simp_all add: mult_coprime_aux assms)\nqed\n\nlemma prod_coprime:\n  assumes \"\\<And>x y. x \\<in> A \\<Longrightarrow> y \\<in> A \\<Longrightarrow> x \\<noteq> y \\<Longrightarrow> coprime (g x) (g y)\"\n  shows   \"f (prod g A) = (\\<Prod>x\\<in>A. f (g x))\"\n  using assms\nproof (induction rule: infinite_finite_induct)\n  case (insert x A)\n  from insert have \"f (prod g (insert x A)) = f (g x * prod g A)\" by simp\n  also have \"\\<dots> = f (g x) * f (prod g A)\" using insert.prems insert.hyps\n    by (auto intro: mult_coprime prod_coprime_right)\n  also have \"\\<dots> = (\\<Prod>x\\<in>insert x A. f (g x))\" using insert by simp\n  finally show ?case .\nqed auto\n\nlemma prod_prime_factors:\n  assumes \"n > 0\"\n  shows   \"f n = (\\<Prod>p\\<in>prime_factors n. f (p ^ multiplicity p n))\"\nproof -\n  have \"n = (\\<Prod>p\\<in>prime_factors n. p ^ multiplicity p n)\"\n    using Primes.prime_factorization_nat assms by blast\n  also have \"f \\<dots> = (\\<Prod>p\\<in>prime_factors n. f (p ^ multiplicity p n))\"\n    by (rule prod_coprime) (auto simp add: in_prime_factors_imp_prime primes_coprime) \n  finally show ?thesis .\nqed\n\nlemma multiplicative_sum_divisors: \"multiplicative_function (\\<lambda>n. \\<Sum>d | d dvd n. f d)\"\nproof\n  fix a b :: nat assume ab: \"a > 1\" \"b > 1\" \"coprime a b\"\n  hence \"(\\<Sum>d | d dvd a * b. f d) = (\\<Sum>r | r dvd a. \\<Sum>s | s dvd b. f (r * s))\"\n    by (intro sum_divisors_coprime_mult)\n  also have \"\\<dots> = (\\<Sum>r | r dvd a. \\<Sum>s | s dvd b. f r * f s)\"\n    using ab(3)\n    by (auto intro!: sum.cong intro: mult_coprime coprime_imp_coprime dvd_trans)\n  also have \"\\<dots> = (\\<Sum>r | r dvd a. f r) * (\\<Sum>s | s dvd b. f s)\"\n    by (subst sum_distrib_right, subst sum_distrib_left) simp_all\n  finally show \"(\\<Sum>d | d dvd a * b. f d) = (\\<Sum>r | r dvd a. f r) * (\\<Sum>s | s dvd b. f s)\" .\nqed auto\n\nend\n\nlocale multiplicative_function' = multiplicative_function f for f :: \"nat \\<Rightarrow> 'a :: comm_semiring_1\" +\n  fixes f_prime_power :: \"nat \\<Rightarrow> nat \\<Rightarrow> 'a\" and f_prime :: \"nat \\<Rightarrow> 'a\"\n  assumes prime_power: \"prime p \\<Longrightarrow> k > 0 \\<Longrightarrow> f (p ^ k) = f_prime_power p k\"\n  assumes prime_aux: \"prime p \\<Longrightarrow> f_prime_power p 1 = f_prime p\"\nbegin\n  \nlemma prime: \"prime p \\<Longrightarrow> f p = f_prime p\"\n  using prime_power[of p 1] prime_aux[of p] by simp\n\nlemma prod_prime_factors':\n  assumes \"n > 0\"\n  shows   \"f n = (\\<Prod>p\\<in>prime_factors n. f_prime_power p (multiplicity p n))\"\n  by (subst prod_prime_factors[OF assms(1)])\n     (intro prod.cong refl prime_power, auto simp: prime_factors_multiplicity)\n\nlemma efficient_code_aux:\n  assumes \"n > 0\" \"set ps = (\\<lambda>p. (p, multiplicity p n - 1)) ` prime_factors n\" \"distinct ps\"\n  shows   \"f n = (\\<Prod>(p,d) \\<leftarrow> ps. f_prime_power p (Suc d))\"\nproof -\n  from assms have \n    \"(\\<Prod>(p,d) \\<leftarrow> ps. f_prime_power p (Suc d)) = \n       (\\<Prod>(p,d)\\<in>(\\<lambda>p. (p, multiplicity p n - 1)) ` prime_factors n. f_prime_power p (Suc d))\"\n    by (subst prod.distinct_set_conv_list [symmetric]) simp_all\n  also have \"\\<dots> = (\\<Prod>x\\<in>prime_factors n. f_prime_power x (multiplicity x n))\"\n    by (subst prod.reindex) (auto simp: inj_on_def prime_factors_multiplicity intro!: prod.cong)\n  also have \"\\<dots> = f n\" by (rule prod_prime_factors' [symmetric]) fact+\n  finally show ?thesis ..\nqed\n\nlemma efficient_code:\n  assumes \"set (ps ()) = (\\<lambda>p. (p, multiplicity p n - 1)) ` prime_factors n\" \"distinct (ps ())\"\n  shows   \"f n = (if n = 0 then 0 else (\\<Prod>(p,d) \\<leftarrow> ps (). f_prime_power p (Suc d)))\"\n  using efficient_code_aux[of n \"ps ()\"] assms by simp\n\nend\n\n\nlocale completely_multiplicative_function =\n  fixes f :: \"nat \\<Rightarrow> 'a :: comm_semiring_1\"\n  assumes zero_aux: \"f 0 = 0\"\n  assumes one_aux:  \"f (Suc 0) = 1\"\n  assumes mult_aux: \"a > 1 \\<Longrightarrow> b > 1 \\<Longrightarrow> f (a * b) = f a * f b\"\nbegin\n  \nlemma mult: \"f (a * b) = f a * f b\"\nproof -\n  {fix n :: nat consider \"n = 0\" | \"n = 1\" | \"n > 1\" by force} note P = this\n  show ?thesis by (cases a rule: P; cases b rule: P) (simp_all add: zero_aux one_aux mult_aux)\nqed\n\nsublocale multiplicative_function f\n  by standard (simp_all add: zero_aux one_aux mult)\n \nlemma prod: \"f (prod g A) = (\\<Prod>x\\<in>A. f (g x))\"\n  by (induction A rule: infinite_finite_induct) (simp_all add: mult)\n    \nlemma power: \"f (n ^ m) = f n ^ m\"\n  by (induction m) (simp_all add: mult)\n\nlemma prod_prime_factors': \"n > 0 \\<Longrightarrow> f n = (\\<Prod>p\\<in>prime_factors n. f p ^ multiplicity p n)\"\n  by (subst prime_factorization_nat) (simp_all add: prod power)\n\nend\n\nlocale completely_multiplicative_function' =\n  completely_multiplicative_function f for f :: \"nat \\<Rightarrow> 'a :: comm_semiring_1\" +\n  fixes f_prime :: \"nat \\<Rightarrow> 'a\"\n  assumes f_prime: \"prime p \\<Longrightarrow> f p = f_prime p\"\nbegin\n\nlemma prod_prime_factors'': \"n > 0 \\<Longrightarrow> f n = (\\<Prod>p\\<in>prime_factors n. f_prime p ^ multiplicity p n)\"\n  by (subst prod_prime_factors') (auto simp: f_prime prime_factors_multiplicity intro!: prod.cong)\n    \nlemma efficient_code_aux:\n  assumes \"n > 0\" \"set ps = (\\<lambda>p. (p, multiplicity p n - 1)) ` prime_factors n\" \"distinct ps\"\n  shows   \"f n = (\\<Prod>(p,d) \\<leftarrow> ps. f_prime p ^ Suc d)\"\nproof -\n  from assms have \n    \"(\\<Prod>(p,d) \\<leftarrow> ps. f_prime p ^ Suc d) = \n       (\\<Prod>(p,d)\\<in>(\\<lambda>p. (p, multiplicity p n - 1)) ` prime_factors n. f_prime p ^ Suc d)\"\n    by (subst prod.distinct_set_conv_list [symmetric]) simp_all\n  also have \"\\<dots> = (\\<Prod>x\\<in>prime_factors n. f_prime x ^ multiplicity x n)\"\n    by (subst prod.reindex) (auto simp: inj_on_def prime_factors_multiplicity \n                                  simp del: power_Suc intro!: prod.cong)\n  also have \"\\<dots> = f n\" by (rule prod_prime_factors'' [symmetric]) fact+\n  finally show ?thesis ..\nqed\n\nlemma efficient_code:\n  assumes \"set (ps ()) = (\\<lambda>p. (p, multiplicity p n - 1)) ` prime_factors n\" \"distinct (ps ())\"\n  shows   \"f n = (if n = 0 then 0 else (\\<Prod>(p,d) \\<leftarrow> ps (). f_prime p ^ Suc d))\"\n  using efficient_code_aux[of n \"ps ()\"] assms by simp\n\nend\n  \nlemma multiplicative_function_eqI:\n  assumes \"multiplicative_function f\" \"multiplicative_function g\"\n  assumes \"\\<And>p k. prime p \\<Longrightarrow> k > 0 \\<Longrightarrow> f (p ^ k) = g (p ^ k)\"\n  shows   \"f n = g n\"\nproof -\n  interpret f: multiplicative_function f by fact\n  interpret g: multiplicative_function g by fact\n  show ?thesis\n  proof (cases \"n > 0\")\n    case True\n    thus ?thesis \n      using f.prod_prime_factors[OF True] g.prod_prime_factors[OF True]\n      by (auto intro!: prod.cong assms simp: prime_factors_multiplicity)\n  qed simp_all\nqed\n\nlemma multiplicative_function_of_natI:\n  \"multiplicative_function f \\<Longrightarrow> multiplicative_function (\\<lambda>n. of_nat (f n))\"\n  unfolding multiplicative_function_def by auto\n\nlemma multiplicative_function_of_natD:\n  \"multiplicative_function (\\<lambda>n. of_nat (f n) :: 'a :: {ring_char_0, comm_semiring_1}) \\<Longrightarrow> \n     multiplicative_function f\"\n  unfolding multiplicative_function_def \n  by (auto simp: of_nat_mult [symmetric] of_nat_eq_1_iff simp del: of_nat_mult)\n\nlemma multiplicative_function_mult:\n  assumes \"multiplicative_function f\"  \"multiplicative_function g\"\n  shows   \"multiplicative_function (\\<lambda>n. f n * g n)\"\nproof\n  interpret f: multiplicative_function f by fact\n  interpret g: multiplicative_function g by fact\n  show \"f 0 * g 0 = 0\" \"f 1 * g 1 = 1\" by simp_all\n  fix a b :: nat assume \"a > 1\" \"b > 1\" \"coprime a b\"\n  thus \"f (a * b) * g (a * b) = (f a * g a) * (f b * g b)\"\n    by (simp_all add: f.mult_coprime g.mult_coprime mult_ac)\nqed\n\nlemma multiplicative_function_inverse:\n  fixes f :: \"nat \\<Rightarrow> 'a :: field\"\n  assumes \"multiplicative_function f\"\n  shows   \"multiplicative_function (\\<lambda>n. inverse (f n))\"\nproof\n  interpret f: multiplicative_function f by fact\n  show \"inverse (f 0) = 0\" \"inverse (f 1) = 1\" by simp_all\n  fix a b :: nat assume \"a > 1\" \"b > 1\" \"coprime a b\"\n  thus \"inverse (f (a * b)) = inverse (f a) * inverse (f b)\"\n    by (simp_all add: f.mult_coprime field_simps)\nqed\n\nlemma multiplicative_function_divide:\n  fixes f :: \"nat \\<Rightarrow> 'a :: field\"\n  assumes \"multiplicative_function f\"  \"multiplicative_function g\"\n  shows   \"multiplicative_function (\\<lambda>n. f n / g n)\"\nproof -\n  have \"multiplicative_function (\\<lambda>n. f n * inverse (g n))\"\n    by (intro multiplicative_function_mult multiplicative_function_inverse assms)\n  also have \"(\\<lambda>n. f n * inverse (g n)) = (\\<lambda>n. f n / g n)\" \n    by (simp add: field_simps)\n  finally show ?thesis .\nqed\n\nlemma completely_multiplicative_function_mult:\n  assumes \"completely_multiplicative_function f\" \"completely_multiplicative_function g\"\n  shows   \"completely_multiplicative_function (\\<lambda>n. f n * g n)\"\nproof\n  interpret f: completely_multiplicative_function f by fact\n  interpret g: completely_multiplicative_function g by fact\n  show \"f 0 * g 0 = 0\" \"f (Suc 0) * g (Suc 0) = 1\" by simp_all\n  fix a b :: nat assume \"a > 1\" \"b > 1\"\n  thus \"f (a * b) * g (a * b) = (f a * g a) * (f b * g b)\"\n    by (simp_all add: f.mult g.mult mult_ac)\nqed\n\nlemma completely_multiplicative_function_inverse:\n  fixes f :: \"nat \\<Rightarrow> 'a :: field\"\n  assumes \"completely_multiplicative_function f\"\n  shows   \"completely_multiplicative_function (\\<lambda>n. inverse (f n))\"\nproof\n  interpret f: completely_multiplicative_function f by fact\n  show \"inverse (f 0) = 0\" \"inverse (f (Suc 0)) = 1\" by simp_all\n  fix a b :: nat assume \"a > 1\" \"b > 1\"\n  thus \"inverse (f (a * b)) = inverse (f a) * inverse (f b)\"\n    by (simp_all add: f.mult field_simps)\nqed\n\nlemma completely_multiplicative_function_divide:\n  fixes f :: \"nat \\<Rightarrow> 'a :: field\"\n  assumes \"completely_multiplicative_function f\"  \"completely_multiplicative_function g\"\n  shows   \"completely_multiplicative_function (\\<lambda>n. f n / g n)\"\nproof -\n  have \"completely_multiplicative_function (\\<lambda>n. f n * inverse (g n))\"\n    by (intro completely_multiplicative_function_mult \n              completely_multiplicative_function_inverse assms)\n  also have \"(\\<lambda>n. f n * inverse (g n)) = (\\<lambda>n. f n / g n)\" \n    by (simp add: field_simps)\n  finally show ?thesis .\nqed\n\nlemma (in multiplicative_function) completely_multiplicativeI:\n  assumes \"\\<And>p k. prime p \\<Longrightarrow> k > 0 \\<Longrightarrow> f (p ^ k) = f p ^ k\"\n  shows   \"completely_multiplicative_function f\"\nproof\n  fix m n :: nat assume mn: \"m > 1\" \"n > 1\"\n  define P where \"P = prime_factors (m * n)\"\n  have \"f (m * n) = (\\<Prod>p\\<in>P. f (p ^ multiplicity p (m * n)))\"\n    using mn by (subst prod_prime_factors) (auto simp: P_def)\n  also have \"\\<dots> = (\\<Prod>p\\<in>P. f p ^ multiplicity p (m * n))\"\n    by (intro prod.cong) (auto simp: assms prime_factors_multiplicity P_def)\n  also have \"\\<dots> = (\\<Prod>p\\<in>P. f p ^ multiplicity p m * f p ^ multiplicity p n)\"\n    by (intro prod.cong refl, subst prime_elem_multiplicity_mult_distrib)\n       (use mn in \\<open>auto simp: P_def prime_factors_multiplicity power_add\\<close>)\n  also have \"\\<dots> = (\\<Prod>p\\<in>P. f p ^ multiplicity p m) * (\\<Prod>p\\<in>P. f p ^ multiplicity p n)\"\n    by (rule prod.distrib)\n  also have \"(\\<Prod>p\\<in>P. f p ^ multiplicity p m) = (\\<Prod>p\\<in>prime_factors m. f p ^ multiplicity p m)\"\n    unfolding P_def by (intro prod.mono_neutral_right dvd_prime_factors finite_set_mset)\n                       (use mn in \\<open>auto simp: prime_factors_multiplicity\\<close>)\n  also have \"\\<dots> = (\\<Prod>p\\<in>prime_factors m. f (p ^ multiplicity p m))\"\n    by (intro prod.cong) (auto simp: assms prime_factors_multiplicity)\n  also have \"\\<dots> = f m\"\n    using mn by (intro prod_prime_factors [symmetric]) auto\n  also have \"(\\<Prod>p\\<in>P. f p ^ multiplicity p n) = (\\<Prod>p\\<in>prime_factors n. f p ^ multiplicity p n)\"\n    unfolding P_def by (intro prod.mono_neutral_right dvd_prime_factors finite_set_mset)\n                       (use mn in \\<open>auto simp: prime_factors_multiplicity\\<close>)\n  also have \"\\<dots> = (\\<Prod>p\\<in>prime_factors n. f (p ^ multiplicity p n))\"\n    by (intro prod.cong) (auto simp: assms prime_factors_multiplicity)\n  also have \"\\<dots> = f n\"\n    using mn by (intro prod_prime_factors [symmetric]) auto\n  finally show \"f (m * n) = f m * f n\" .\nqed auto\n\n\nsubsection \\<open>Indicator function\\<close>\n\ndefinition ind :: \"(nat \\<Rightarrow> bool) \\<Rightarrow> nat \\<Rightarrow> 'a :: semiring_1\" where\n  \"ind P n = (if n > 0 \\<and> P n then 1 else 0)\"\n  \nlemma ind_0 [simp]: \"ind P 0 = 0\" by (simp add: ind_def)\n\nlemma ind_nonzero: \"n > 0 \\<Longrightarrow> ind P n = (if P n then 1 else 0)\"\n  by (simp add: ind_def)\n\nlemma ind_True [simp]: \"P n \\<Longrightarrow> n > 0 \\<Longrightarrow> ind P n = 1\"\n  by (simp add: ind_nonzero)\n\nlemma ind_False [simp]: \"\\<not>P n \\<Longrightarrow> n > 0 \\<Longrightarrow> ind P n = 0\"\n  by (simp add: ind_nonzero)\n\nlemma ind_eq_1_iff: \"ind P n = 1 \\<longleftrightarrow> n > 0 \\<and> P n\"\n  by (simp add: ind_def)\n\nlemma ind_eq_0_iff: \"ind P n = 0 \\<longleftrightarrow> n = 0 \\<or> \\<not>P n\"\n  by (simp add: ind_def)\n\nlemma multiplicative_function_ind [intro?]:\n  assumes \"P 1\" \"\\<And>a b. a > 1 \\<Longrightarrow> b > 1 \\<Longrightarrow> coprime a b \\<Longrightarrow> P (a * b) \\<longleftrightarrow> P a \\<and> P b\"\n  shows   \"multiplicative_function (ind P)\"\n  by standard (insert assms, auto simp: ind_nonzero)\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/Multiplicative_Function.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8791467611766711, "lm_q2_score": 0.8354835330070839, "lm_q1q2_score": 0.7345126420596202}}
{"text": "theory ex4_05 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\ninductive T :: \"alpha list \\<Rightarrow> bool\" where\nt1: \"T []\"  |\nt2: \"\\<lbrakk> T x; T y \\<rbrakk> \\<Longrightarrow> T (x @ a # y @ [b])\"\n  \nlemma lem1:\"T w \\<Longrightarrow> T (a # w @ [b])\"\nusing t1 t2 by force\n\nlemma t2':\"\\<lbrakk> T w2; T w1 \\<rbrakk> \\<Longrightarrow> T (a # w1 @ b # w2)\"\napply(induction rule: T.induct)\napply(auto simp add: t1 t2)\nusing t1 t2 apply force\nusing t2 by fastforce\n\n\n\n\n\ntheorem s2t: \"S w \\<Longrightarrow> T w\"\napply(induction rule: S.induct)\napply(auto simp add: t1 lem1)\ndone\n\ntheorem t2s: \"T w \\<Longrightarrow> S w\"\napply(induction rule: T.induct)\napply(auto simp add: s1 s2 s3)\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_05.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9173026573249612, "lm_q2_score": 0.8006919997179627, "lm_q1q2_score": 0.7344768990401243}}
{"text": "section \\<open> Protocol parameters \\<close>\n\ntheory Protocol_Parameters\nimports Complex_Main\nbegin\n\ntext \\<open>\n  The protocol depends on a number of parameters, among others are the following:\n\n  \\<^item> \\<open>k\\<close>: Establishes how deep in the chain (in terms of number of blocks) a transaction needs to be\n    in order to be declared as stable.\n  \\<^item> \\<open>f\\<close>: The `active slot coefficient'. Establishes the probability that at least one stakeholder\n    is elected as a slot leader in each slot, that is, the probability that a slot is not empty.\n    Must be a strictly positive probability.\n\\<close>\n\nlocale protocol_parameters =\n  fixes k :: nat\n    and f :: real\n  assumes f_non_zero_probability: \"f \\<in> {0<..1}\"\nbegin\n\ntext \\<open>\n  According to Definition 21.3 in @{cite \"cardano-consensus-tr\"} (which is based on the analysis in\n  Section 4 of @{cite \"genesis-praos-parametrization\"}), the default value for the Genesis window\n  size is set to \\<open>3k/f\\<close>:\n\\<close>\n\nabbreviation default_window_size :: nat where\n  \"default_window_size \\<equiv> nat \\<lceil>3 * k / f\\<rceil>\"\n\ntext \\<open>\n  We can show that the default value is at least \\<open>k\\<close>:\n\\<close>\n\nlemma default_window_greater_or_equal_than_k:\n  shows \"default_window_size \\<ge> k\"\nproof -\n  have \"default_window_size \\<ge> 3 * k\"\n    using f_non_zero_probability\n    by (smt divide_numeral_1 frac_le greaterThanAtMost_iff nat_le_0 of_nat_ceiling of_nat_le_iff\n        zero_less_ceiling)\n  then show ?thesis\n    by linarith\nqed\n\nend\n\nend\n\n", "meta": {"author": "input-output-hk", "repo": "ouroboros-high-assurance", "sha": "f1b63cb176b119183bcbe14786cd5a61e0c5bf97", "save_path": "github-repos/isabelle/input-output-hk-ouroboros-high-assurance", "path": "github-repos/isabelle/input-output-hk-ouroboros-high-assurance/ouroboros-high-assurance-f1b63cb176b119183bcbe14786cd5a61e0c5bf97/src/Chain_Selection_Density_Equivalence/Protocol_Parameters.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8933094174159129, "lm_q2_score": 0.8221891370573388, "lm_q1q2_score": 0.7344692990303834}}
{"text": "theory Reg_Exp\nimports \"../NonFreeInput\"\nbegin\n\n(* Regular expressions as the freely generated Kleene algebra: *)\nnonfree_datatype 'a exp = Let 'a | Zero | One | Plus \"'a exp\" \"'a exp\" |\n                     Times \"'a exp\" \"'a exp\" | Star \"'a exp\"\nwhere\n   Plus_Assoc: \"Plus (Plus e1 e2) e3 = Plus e1 (Plus e2 e3)\"\n | Plus_Comm: \"Plus e1 e2 = Plus e2 e1\"\n | Plus_Zero: \"Plus Zero e = e\"\n | Plus_Idem: \"Plus e e = e\"\n | Times_Assoc: \"Times (Times e1 e2) e3 = Times e1 (Times e2 e3)\"\n | Times_One: \"Times One e = e\"\n | Times_Zero: \"Times Zero e = Zero\"\n | Times_Plus: \"Times e1 (Plus e2 e3) = Plus (Times e1 e2) (Times e1 e3)\"\n | Star_Left: \"Plus (Plus One (Times (Star e) e)) (Star e) = Star e\"\n | Star_Right: \"Plus (Plus One (Times e (Star e))) (Star e) = Star e\"\n | Star_Left_Min: \"Plus (Times e e1) e1 = e1 \\<Longrightarrow> Plus (Times (Star e) e1) e1 = e1\"\n | Star_Right_Min: \"Plus (Times e1 e) e1 = e1 \\<Longrightarrow> Plus e1 (Times e1 (Star e)) = e1\"\n\n(* Interpretation as abstract relation algebra, on the powerset of a monoid: *)\ndefinition Mult :: \"('a::monoid_mult) set \\<Rightarrow> 'a set \\<Rightarrow> 'a set\"\nwhere\n\"Mult P Q \\<equiv> {p * q | p q. p \\<in> P \\<and> q \\<in> Q}\"\n\ndeclare algebra_simps[simp]\n\nlemma Mult_Assoc: \"Mult (Mult L1 L2) L3 = Mult L1 (Mult L2 L3)\"\nunfolding Mult_def apply auto apply blast\nunfolding mult_assoc[symmetric] by blast\n\nlemma Mult_Singl_One: \"Mult {1} L = L\"\nunfolding Mult_def by auto\n\nlemma Mult_emp: \"Mult {} L = {}\"\nunfolding Mult_def by auto\n\nlemma Mult_Un: \"Mult L (L1 \\<union> L2) = Mult L L1 \\<union> Mult L L2\"\nunfolding Mult_def by auto\n\ninductive_set Mstar for L :: \"('a::monoid_mult) set\" where\nOne: \"1 \\<in> Mstar L\"\n|\nTimes: \"\\<lbrakk>w \\<in> L; w1 \\<in> Mstar L\\<rbrakk> \\<Longrightarrow> w * w1 \\<in> Mstar L\"\n\nlemma incl_Mstar[simp]: \"w \\<in> L \\<Longrightarrow> w \\<in> Mstar L\"\nusing Mstar.intros by (metis mult_1_right)\n\nlemma append_Mstar: \"\\<lbrakk>w \\<in> Mstar L; w1 \\<in> L\\<rbrakk> \\<Longrightarrow> w * w1 \\<in> Mstar L\"\napply(induction rule: Mstar.induct) by (auto intro: Mstar.intros)\n\nlemma Mult_Mstar_R: \"Mult L (Mstar L) \\<subseteq> Mstar L\"\nunfolding Mult_def by (auto intro: Mstar.intros)\n\nlemma Mult_Mstar_L: \"Mult (Mstar L) L \\<subseteq> Mstar L\"\nunfolding Mult_def by (auto intro: append_Mstar)\n\nlemma Mult_Mstar_Min_L:\nassumes \"Mult L1 L \\<subseteq> L\"  shows \"Mult (Mstar L1) L \\<subseteq> L\"\nunfolding Mult_def proof safe\n  fix x w1 w2 assume \"w1 \\<in> Mstar L1\" and \"w2 \\<in> L\"\n  thus \"w1 * w2 \\<in> L\"\n  using assms unfolding Mult_def by (induction rule: Mstar.induct) auto\nqed\n\nlemma Mult_Mstar_Min_R:\nassumes \"Mult L L1 \\<subseteq> L\"  shows \"Mult L (Mstar L1) \\<subseteq> L\"\nunfolding Mult_def proof safe\n  fix x w1 w2 assume \"w2 \\<in> Mstar L1\" and \"w1 \\<in> L\"\n  thus \"w1 * w2 \\<in> L\"\n  proof (induction arbitrary: w1 rule: Mstar.induct)\n    case (Times w w1 w1a)\n    hence \"w1a * w \\<in> L\" using assms unfolding Mult_def by auto\n    from Times.IH[OF this] show ?case by simp\n  qed auto\nqed\n\nnonfree_primrec kinter :: \"('a \\<Rightarrow> 'b::monoid_mult) \\<Rightarrow> 'a exp \\<Rightarrow> 'b set\"\nwhere\n  \"kinter f (Let a) = {f a}\"\n| \"kinter f Zero = {}\"\n| \"kinter f One = {1}\"\n| \"kinter f (Plus e1 e2) = kinter f e1 \\<union> kinter f e2\"\n| \"kinter f (Times e1 e2) = Mult (kinter f e1) (kinter f e2)\"\n| \"kinter f (Star e) = Mstar (kinter f e)\"\napply (metis sup.commute)\napply (metis Sup_fin.idem)\napply (metis sup_bot_left)\napply auto[]\napply (metis Mstar.One)\napply (metis Mult_Mstar_L subsetD)\napply (metis Mult_Singl_One)\napply (metis Un_left_commute sup.commute)\napply auto[]\napply (metis Mstar.One)\napply (metis Mult_Mstar_R subsetD)\napply (metis Mult_Un)\napply (metis Mult_emp)\napply (metis Mult_Assoc)\napply (metis Mult_Mstar_Min_L Un_commute sup_absorb1 sup_ge1)\nby (metis Mult_Mstar_Min_R Un_upper2 sup.commute sup_absorb1)\n\n(* Instantiation to regular languages: *)\ninstantiation list :: (type)monoid_mult begin\n  definition times_list where \"xs * ys = xs @ ys\"\n  definition one_list where \"1 = []\"\n  instance apply default unfolding times_list_def one_list_def by auto\nend\n\ndefinition \"lang \\<equiv> kinter (\\<lambda> a. [a])\"\nabbreviation \"Append \\<equiv> Mult :: 'a list set \\<Rightarrow> 'a list set \\<Rightarrow> 'a list set\"\nabbreviation \"Lstar \\<equiv> Mstar :: 'a list set \\<Rightarrow> 'a list set\"\n\nlemma lang_simps:\n  \"lang (Let a) = {[a]}\"\n  \"lang Zero = {}\"\n  \"lang One = {[]}\"\n  \"lang (Plus e1 e2) = lang e1 \\<union> lang e2\"\n  \"lang (Times e1 e2) = Append (lang e1) (lang e2)\"\n  \"lang (Star e) = Lstar (lang e)\"\nunfolding lang_def by (auto simp: times_list_def one_list_def)\n\n(* Interpretation in the algebra of relations: *)\nnonfree_primrec rinter :: \"('a \\<Rightarrow> ('b \\<times> 'b) set) \\<Rightarrow> 'a exp \\<Rightarrow> ('b \\<times> 'b) set\"\nwhere\n  \"rinter f (Let a) = f a\"\n| \"rinter f Zero = {}\"\n| \"rinter f One = Id\"\n| \"rinter f (Plus e1 e2) = rinter f e1 \\<union> rinter f e2\"\n| \"rinter f (Times e1 e2) = (rinter f e1) O (rinter f e2)\"\n| \"rinter f (Star e) = (rinter f e) ^*\"\napply auto\nproof-\n  fix x' x'a x y z assume \"(x, y) \\<in> x'\\<^sup>*\" \"(y, z) \\<in> x'a\" \"x' O x'a \\<union> x'a = x'a\"\n  thus \"(x, z) \\<in> x'a\" by (induction rule: rtrancl_induct) auto\nnext\n  fix x' x'a x y z assume \"(y, z) \\<in> x'a\\<^sup>*\" \"(x, y) \\<in> x'\" \"x' O x'a \\<union> x' = x'\"\n  thus \"(x, z) \\<in> x'\" by (induction rule: rtrancl_induct) auto\nqed\n\n\n\n\nend\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/Reg_Exp.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094174159129, "lm_q2_score": 0.822189121808099, "lm_q1q2_score": 0.734469285408094}}
{"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_HSort2Permutes\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 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\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 hinsert :: \"Nat => Heap => Heap\" where\n  \"hinsert x y = hmerge (Node Nil x Nil) y\"\n\nfun toHeap2 :: \"Nat list => Heap\" where\n  \"toHeap2 (nil2) = Nil\"\n| \"toHeap2 (cons2 y xs) = hinsert y (toHeap2 xs)\"\n\nfun hsort2 :: \"Nat list => Nat list\" where\n  \"hsort2 x = toList (toHeap2 x)\"\n\nfun elem :: \"'a => 'a list => bool\" where\n  \"elem x (nil2) = False\"\n| \"elem x (cons2 z xs) = ((z = x) | (elem x xs))\"\n\nfun deleteBy :: \"('a => ('a => bool)) => 'a => 'a list =>\n                 'a list\" where\n  \"deleteBy x y (nil2) = nil2\"\n| \"deleteBy x y (cons2 y2 ys) =\n     (if (x y) y2 then ys else cons2 y2 (deleteBy x y ys))\"\n\nfun isPermutation :: \"'a list => 'a list => bool\" where\n  \"isPermutation (nil2) (nil2) = True\"\n| \"isPermutation (nil2) (cons2 z x2) = False\"\n| \"isPermutation (cons2 x3 xs) y =\n     ((elem x3 y) &\n        (isPermutation\n           xs (deleteBy (% (x4 :: 'a) => % (x5 :: 'a) => (x4 = x5)) x3 y)))\"\n\ntheorem property0 :\n  \"isPermutation (hsort2 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_sort_nat_HSort2Permutes.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933093946927837, "lm_q2_score": 0.8221891283434876, "lm_q1q2_score": 0.7344692725635084}}
{"text": "theory Homework4_2\nimports Main\nbegin\n\n  (*\n    ISSUED: Wednesday, October 11\n    DUE: Wednesday, October 18, 11:59pm\n    POINTS: 5\n  *)\n\n  (*\n    In a directed graph, we have a path of length n from u to v,\n    if we can go from u to v using exactly n edges. \n\n    Specify an inductive predicate pol E x n y, which is true if and only\n    if there is a path of length n from x to y.\n  *)\n  \n  inductive pol :: \"('a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> 'a \\<Rightarrow> nat \\<Rightarrow> 'a \\<Rightarrow> bool\" \n    (* Add inductive specification here! *)\n     \n  (* Show that two paths can be appended. Their length is the sum of the two lengths.\n    Hint: Make sure the premises are in the right order,\n      as rule induction will pick the first matching premise.\n      If not, use rotate_tac.\n  *)  \n  lemma pol_append: \"\\<lbrakk>pol E x k y; pol E y l z\\<rbrakk> \\<Longrightarrow> pol E x (k+l) z\"\n    sorry\n\n  (*\n    Write a recursive function that checks whether there is a path of length n.\n    Hint: Recursion over n. Use an \\<exists>-quantifier to obtain a next state.\n  *)\n      \n  fun fpol :: \"('a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> 'a \\<Rightarrow> nat \\<Rightarrow> 'a \\<Rightarrow> bool\"\n    where\n    \"fpol _ _ _ _ = undefined\"\n\n  (* Show that the function is equivalent to the inductive version! \n\n    You may either show the two directions separately, as indicated in this template.\n    Alternatively, you may derive recursive equations for pol, as done in LTS.thy.\n\n    The only lemma that MUST be proved at the end is fpol_eq_pol!\n  *)  \n  lemma fpol_imp_pol: \"fpol E x l y \\<Longrightarrow> pol E x l y\"\n    sorry\n      \n  lemma pol_imp_fpol: \"pol E x l y \\<Longrightarrow> fpol E x l y\"\n    sorry\n    \n  lemma fpol_eq_pol: \"fpol = pol\" \n    sorry\n      \n  (* Using fpol, show that a path can be split *)    \n  lemma fpol_split: \"fpol E x (l1+l2) z \\<Longrightarrow> (\\<exists>y. fpol E x l1 y \\<and> fpol E y l2 z)\"    \n    sorry\n      \n  (* Combine the split and append lemma *)\n  lemma pol_append_conv: \"pol E x (l1+l2) z \\<longleftrightarrow> (\\<exists>y. pol E x l1 y \\<and> pol E y l2 z)\"\n    sorry\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_2.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473746782093, "lm_q2_score": 0.8418256492357358, "lm_q1q2_score": 0.7343643950475732}}
{"text": "(*  Title:       Countable Ordinals\n\n    Author:      Brian Huffman, 2005\n    Maintainer:  Brian Huffman <brianh at cse.ogi.edu>\n*)\n\nsection \\<open>Definition of Ordinals\\<close>\n\ntheory OrdinalDef\nimports Main\nbegin\n\nsubsection \\<open>Preliminary datatype for ordinals\\<close>\n\ndatatype ord0 = ord0_Zero | ord0_Lim \"nat \\<Rightarrow> ord0\"\n\ntext \\<open>subterm ordering on ord0\\<close>\n\ndefinition\n  ord0_prec :: \"(ord0 \\<times> ord0) set\" where\n  \"ord0_prec = (\\<Union>f i. {(f i, ord0_Lim f)})\"\n\nlemma wf_ord0_prec: \"wf ord0_prec\"\n apply (unfold ord0_prec_def)\n apply (rule wfUNIVI, induct_tac x)\n  apply (drule spec, erule mp, simp)\n apply (drule spec, erule mp, auto)\ndone\n\nlemmas ord0_prec_induct = wf_induct[OF wf_trancl[OF wf_ord0_prec]]\n\n\ntext \\<open>less-than-or-equal ordering on ord0\\<close>\n\ninductive_set ord0_leq :: \"(ord0 \\<times> ord0) set\" where\n\"\\<lbrakk>\\<forall>a. (a,x) \\<in> ord0_prec\\<^sup>+ \\<longrightarrow> (\\<exists>b. (b,y) \\<in> ord0_prec\\<^sup>+ \\<and> (a,b) \\<in> ord0_leq)\\<rbrakk>\n  \\<Longrightarrow> (x,y) \\<in> ord0_leq\"\n\nlemma ord0_leqI:\n\"\\<lbrakk>\\<forall>a. (a,x) \\<in> ord0_prec\\<^sup>+ \\<longrightarrow> (a,y) \\<in> ord0_leq O ord0_prec\\<^sup>+\\<rbrakk>\n \\<Longrightarrow> (x,y) \\<in> ord0_leq\"\nby (rule ord0_leq.intros, auto)\n\nlemma ord0_leqD:\n\"\\<lbrakk>(x,y) \\<in> ord0_leq; (a,x) \\<in> ord0_prec\\<^sup>+\\<rbrakk> \\<Longrightarrow> (a,y) \\<in> ord0_leq O ord0_prec\\<^sup>+\"\nby (ind_cases \"(x,y) \\<in> ord0_leq\", auto)\n\nlemma ord0_leq_refl: \"(x, x) \\<in> ord0_leq\"\nby (rule ord0_prec_induct, rule ord0_leqI, auto)\n\nlemma ord0_leq_trans[rule_format]:\n\"\\<forall>y. (x,y) \\<in> ord0_leq \\<longrightarrow>\n   (\\<forall>z. (y,z) \\<in> ord0_leq \\<longrightarrow> (x,z) \\<in> ord0_leq)\"\n apply (rule ord0_prec_induct, clarify)\n apply (rule ord0_leqI, clarify)\n apply (drule spec, drule mp, assumption)\n apply (drule ord0_leqD, assumption, clarify)\n apply (drule spec, drule mp, assumption)\n apply (drule ord0_leqD, assumption, clarify)\n apply (drule spec, drule mp, assumption)\n apply auto\ndone\n\nlemma wf_ord0_leq: \"wf (ord0_leq O ord0_prec\\<^sup>+)\"\n apply (unfold wf_def, clarify)\n apply (subgoal_tac \"\\<forall>z. (z,x) \\<in> ord0_leq \\<longrightarrow> P z\")\n  apply (drule spec, erule mp, rule ord0_leq_refl)\n apply (rule ord0_prec_induct, clarify)\n apply (drule spec, erule mp, clarify)\n apply (drule ord0_leqD, assumption, clarify)\n apply (drule spec, drule mp, assumption)\n apply (drule spec, erule mp)\n apply (erule ord0_leq_trans, assumption)\ndone\n\n\ntext \\<open>ordering on ord0\\<close>\n\ninstantiation ord0 :: ord\nbegin\n\ndefinition\n  ord0_less_def: \"x < y \\<longleftrightarrow> (x,y) \\<in> ord0_leq O ord0_prec\\<^sup>+\"\n\ndefinition\n  ord0_le_def:   \"x \\<le> y \\<longleftrightarrow> (x,y) \\<in> ord0_leq\"\n\ninstance ..\n\nend\n\nlemma ord0_order_refl[simp]: \"(x::ord0) \\<le> x\"\nby (unfold ord0_le_def, rule ord0_leq_refl)\n\nlemma ord0_order_trans: \"\\<lbrakk>(x::ord0) \\<le> y; y \\<le> z\\<rbrakk> \\<Longrightarrow> x \\<le> z\"\nby (unfold ord0_le_def, rule ord0_leq_trans)\n\nlemma ord0_wf: \"wf {(x,y::ord0). x < y}\"\n apply (subgoal_tac \"{(x,y). x < y} = ord0_leq O ord0_prec\\<^sup>+\")\n  apply (simp add: wf_ord0_leq)\n apply (auto simp add: ord0_less_def)\ndone\n\nlemmas ord0_less_induct = wf_induct[OF ord0_wf]\n\nlemma ord0_leI:\n\"\\<lbrakk>\\<forall>a::ord0. a < x \\<longrightarrow> a < y\\<rbrakk> \\<Longrightarrow> x \\<le> y\"\n apply (unfold ord0_less_def ord0_le_def)\n apply (rule ord0_leqI[rule_format])\n apply (drule spec, erule mp)\n apply (erule relcompI[OF ord0_leq_refl])\ndone\n\nlemma ord0_less_le_trans:\n\"\\<lbrakk>(x::ord0) < y; y \\<le> z\\<rbrakk> \\<Longrightarrow> x < z\"\n apply (unfold ord0_le_def ord0_less_def, clarify)\n apply (drule ord0_leqD, assumption, clarify)\nby (rule relcompI[OF ord0_leq_trans])\n\nlemma ord0_le_less_trans:\n\"\\<lbrakk>(x::ord0) \\<le> y; y < z\\<rbrakk> \\<Longrightarrow> x < z\"\n apply (unfold ord0_le_def ord0_less_def, clarify)\nby (rule relcompI[OF ord0_leq_trans])\n\nlemma rev_ord0_le_less_trans:\n\"\\<lbrakk>(y::ord0) < z; x \\<le> y\\<rbrakk> \\<Longrightarrow> x < z\"\nby (rule ord0_le_less_trans)\n\nlemma ord0_less_trans:\n\"\\<lbrakk>(x::ord0) < y; y < z\\<rbrakk> \\<Longrightarrow> x < z\"\n apply (unfold ord0_less_def, clarify)\n apply (drule ord0_leqD, assumption, clarify)\nby (rule relcompI[OF ord0_leq_trans trancl_trans])\n\nlemma ord0_less_imp_le: \"(x::ord0) < y \\<Longrightarrow> x \\<le> y\"\nby (rule ord0_leI[rule_format], rule ord0_less_trans)\n\nlemma ord0_linear_lemma:\nfixes m :: ord0 and n :: ord0\nshows \"m < n \\<or> n < m \\<or> (m \\<le> n \\<and> n \\<le> m)\"\n apply (rule_tac x=m in spec)\n apply (rule_tac a=n in ord0_less_induct, rename_tac n)\n apply (rule allI, rename_tac m)\n apply (rule_tac a=m in ord0_less_induct, rename_tac m)\n apply (case_tac \"\\<forall>a. a < n \\<longrightarrow> a < m\")\n  apply (rule disjI2)\n  apply (case_tac \"\\<forall>a. a < m \\<longrightarrow> a < n\")\n   apply (rule disjI2)\n   apply (rule conjI, erule ord0_leI, erule ord0_leI)\n  apply (rule disjI1, clarsimp)\n  apply (drule spec, drule mp, assumption)\n  apply (erule rev_ord0_le_less_trans)\n  apply (force simp add: ord0_less_imp_le)\n apply (rule disjI1, clarsimp)\n apply (drule spec, drule mp, assumption)\n apply (drule_tac x=m in spec, simp)\n apply (erule rev_ord0_le_less_trans)\n apply (force simp add: ord0_less_imp_le)\ndone\n\nlemma ord0_linear: \"(x::ord0) \\<le> y \\<or> y \\<le> x\"\n apply (cut_tac ord0_linear_lemma[of x y])\n apply (auto dest: ord0_less_imp_le)\ndone\n\nlemma ord0_order_less_le: \"(x::ord0) < y = (x \\<le> y \\<and> \\<not> y \\<le> x)\"\n apply (rule iffI)\n  apply (clarsimp simp add: ord0_less_imp_le)\n  apply (drule ord0_less_le_trans, assumption)\n  apply (cut_tac a=x in wf_not_refl[OF ord0_wf], simp)\n apply (cut_tac ord0_linear_lemma[of x y], simp)\n apply (auto dest: ord0_less_imp_le)\ndone\n\n\nsubsection \\<open>Ordinal type\\<close>\n\ndefinition\n  ord0rel :: \"(ord0 \\<times> ord0) set\" where\n  \"ord0rel = {(x,y). x \\<le> y \\<and> y \\<le> x}\"\n\ntypedef ordinal = \"(UNIV::ord0 set) // ord0rel\"\nby (unfold quotient_def, auto)\n\ntheorem Abs_ordinal_cases2 [case_names Abs_ordinal, cases type: ordinal]:\n\"(\\<And>z. x = Abs_ordinal (ord0rel `` {z}) \\<Longrightarrow> P) \\<Longrightarrow> P\"\nby (cases x, auto simp add: quotient_def)\n\n\ninstantiation ordinal :: ord\nbegin\n\ndefinition\n  ordinal_less_def: \"x < y \\<longleftrightarrow> (\\<forall>a\\<in>Rep_ordinal x. \\<forall>b\\<in>Rep_ordinal y. a < b)\"\n\ndefinition\n  ordinal_le_def: \"x \\<le> y \\<longleftrightarrow> (\\<forall>a\\<in>Rep_ordinal x. \\<forall>b\\<in>Rep_ordinal y. a \\<le> b)\"\n\ninstance ..\n\nend\n\nlemma Rep_Abs_ord0rel [simp]:\n\"Rep_ordinal (Abs_ordinal (ord0rel `` {x})) = (ord0rel `` {x})\"\nby (simp add: Abs_ordinal_inverse quotientI)\n\nlemma mem_ord0rel_Image [simp, intro!]: \"x \\<in> ord0rel `` {x}\"\nby (simp add: ord0rel_def)\n\nlemma equiv_ord0rel: \"equiv UNIV ord0rel\"\n apply (unfold equiv_def refl_on_def sym_def trans_def ord0rel_def)\n apply (auto elim: ord0_order_trans)\ndone\n\nlemma Abs_ordinal_eq[simp]:\n\"(Abs_ordinal (ord0rel `` {x}) = Abs_ordinal (ord0rel `` {y}))\n  = (x \\<le> y \\<and> y \\<le> x)\"\n apply (simp add: Abs_ordinal_inject quotientI)\n apply (simp add: eq_equiv_class_iff[OF equiv_ord0rel])\n apply (simp add: ord0rel_def)\ndone\n\nlemma Abs_ordinal_le[simp]:\n\"Abs_ordinal (ord0rel `` {x}) \\<le> Abs_ordinal (ord0rel `` {y}) = (x \\<le> y)\"\n apply (auto simp add: ordinal_le_def)\n apply (unfold ord0rel_def)\n apply (auto elim: ord0_order_trans)\ndone\n\nlemma Abs_ordinal_less[simp]:\n\"Abs_ordinal (ord0rel `` {x}) < Abs_ordinal (ord0rel `` {y}) = (x < y)\"\n apply (auto simp add: ordinal_less_def)\n apply (unfold ord0rel_def)\n apply (auto elim: ord0_less_le_trans[OF rev_ord0_le_less_trans])\ndone\n\nlemma ordinal_order_refl: \"(x::ordinal) \\<le> x\"\nby (cases x, simp)\n\nlemma ordinal_order_trans: \"(x::ordinal) \\<le> y \\<Longrightarrow> y \\<le> z \\<Longrightarrow> x \\<le> z\"\nby (cases x, cases y, cases z, auto elim: ord0_order_trans)\n\nlemma ordinal_order_antisym: \"(x::ordinal) \\<le> y \\<Longrightarrow> y \\<le> x \\<Longrightarrow> x = y\"\nby (cases x, cases y, simp)\n\n\n\nlemma ordinal_linear: \"(x::ordinal) \\<le> y \\<or> y \\<le> x\"\nby (cases x, cases y, simp add: ord0_linear)\n\nlemma ordinal_wf: \"wf {(x,y::ordinal). x < y}\"\n apply (rule wfUNIVI)\n apply (rule_tac x=x in Abs_ordinal_cases2, clarify)\n apply (rule ord0_less_induct, rename_tac a)\n apply (drule spec, erule mp, clarify)\n apply (rule_tac x=y in Abs_ordinal_cases2, simp)\ndone\n\ninstance ordinal :: wellorder\n apply (rule wf_wellorderI)\n apply (rule ordinal_wf)\n apply (intro_classes)\n       apply (rule ordinal_order_less_le_not_le)\n      apply (rule ordinal_order_refl)\n     apply (rule ordinal_order_trans, assumption+)\n    apply (rule ordinal_order_antisym, assumption+)\n  apply (rule ordinal_linear)\ndone\n\n\nsubsection \\<open>Induction over ordinals\\<close>\n\ntext \"zero and strict limits\"\n\ndefinition\n  oZero :: \"ordinal\" where\n    \"oZero = Abs_ordinal (ord0rel `` {ord0_Zero})\"\n\ndefinition\n  oStrictLimit :: \"(nat \\<Rightarrow> ordinal) \\<Rightarrow> ordinal\" where\n    \"oStrictLimit f = Abs_ordinal\n      (ord0rel `` {ord0_Lim (\\<lambda>n. SOME x. x \\<in> Rep_ordinal (f n))})\"\n\ntext \"induction over ordinals\"\n\nlemma ord0relD: \"(x,y) \\<in> ord0rel \\<Longrightarrow> x \\<le> y \\<and> y \\<le> x\"\nby (simp add: ord0rel_def)\n\nlemma ord0_precD: \"(x,y) \\<in> ord0_prec \\<Longrightarrow> \\<exists>f n. x = f n \\<and> y = ord0_Lim f\"\nby (simp add: ord0_prec_def)\n\nlemma less_ord0_LimI: \"f n < ord0_Lim f\"\n apply (simp add: ord0_less_def)\n apply (rule relcompI[OF ord0_leq_refl])\n apply (rule r_into_trancl)\n apply (auto simp add: ord0_prec_def)\ndone\n\nlemma less_ord0_LimD: \"x < ord0_Lim f \\<Longrightarrow> \\<exists>n. x \\<le> f n\"\n apply (simp add: ord0_less_def, clarify)\n apply (erule tranclE)\n  apply (drule ord0_precD, clarify)\n  apply (force simp add: ord0_le_def)\n apply (drule ord0_precD, clarify)\n apply (rule_tac x=n in exI)\n apply (rule ord0_less_imp_le)\n apply (auto simp add: ord0_less_def)\ndone\n\nlemma some_ord0rel: \"(x, SOME y. (x,y) \\<in> ord0rel) \\<in> ord0rel\"\nby (rule_tac x=x in someI, simp add: ord0rel_def)\n\nlemma ord0_Lim_le:\n\"\\<forall>n. f n \\<le> g n \\<Longrightarrow> ord0_Lim f \\<le> ord0_Lim g\"\n apply (rule ord0_leI[rule_format])\n apply (drule less_ord0_LimD, clarify)\n apply (erule ord0_le_less_trans)\n apply (drule_tac x=n in spec)\n apply (erule ord0_le_less_trans)\n apply (rule less_ord0_LimI)\ndone\n\nlemma ord0_Lim_ord0rel:\n\"\\<forall>n. (f n, g n) \\<in> ord0rel \\<Longrightarrow> (ord0_Lim f, ord0_Lim g) \\<in> ord0rel\"\nby (simp add: ord0rel_def ord0_Lim_le)\n\nlemma Abs_ordinal_oStrictLimit:\n\"Abs_ordinal (ord0rel `` {ord0_Lim f})\n  = oStrictLimit (\\<lambda>n. Abs_ordinal (ord0rel `` {f n}))\"\n apply (simp add: oStrictLimit_def)\n apply (rule ord0relD)\n apply (rule ord0_Lim_ord0rel)\n apply (simp add: some_ord0rel)\ndone\n\nlemma oStrictLimit_induct:\nassumes base: \"P oZero\"\nassumes step: \"\\<And>f. \\<forall>n. P (f n) \\<Longrightarrow> P (oStrictLimit f)\"\nshows \"P a\"\n apply (cases a, clarsimp)\n apply (induct_tac z)\n  apply (rule base[unfolded oZero_def])\n apply (simp add: Abs_ordinal_oStrictLimit step)\ndone\n\ntext \"order properties of 0 and strict limits\"\n\nlemma oZero_least: \"oZero \\<le> x\"\n apply (unfold oZero_def, cases x, clarsimp)\n apply (induct_tac z, simp, atomize)\n apply (rule ord0_less_imp_le)\n apply (rule ord0_le_less_trans)\n apply (auto simp: less_ord0_LimI)\ndone\n\nlemma oStrictLimit_ub: \"f n < oStrictLimit f\"\n apply (cases \"f n\", simp add: oStrictLimit_def)\n apply (rule_tac y=\"SOME x. x \\<in> Rep_ordinal (f n)\" in ord0_le_less_trans)\n  apply (simp, rule ord0relD[THEN conjunct1])\n  apply (rule some_ord0rel)\n apply (rule less_ord0_LimI)\ndone\n\nlemma oStrictLimit_lub: \"\\<forall>n. f n < x \\<Longrightarrow> oStrictLimit f \\<le> x\"\n apply (erule contrapos_pp, simp add: linorder_not_less linorder_not_le)\n apply (cases x, simp add: oStrictLimit_def)\n apply (drule less_ord0_LimD, clarify)\n apply (rule_tac x=n in exI)\n apply (rule_tac x=\"f n\" in Abs_ordinal_cases2, simp, rename_tac y)\n apply (erule ord0_order_trans)\n apply (rule ord0relD[THEN conjunct2])\n apply (rule some_ord0rel)\ndone\n\nlemma less_oStrictLimitD: \"x < oStrictLimit f \\<Longrightarrow> \\<exists>n. x \\<le> f n\"\n apply (erule contrapos_pp)\n apply (simp add: linorder_not_less linorder_not_le)\n apply (erule oStrictLimit_lub)\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/Ordinal/OrdinalDef.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473813156294, "lm_q2_score": 0.8418256412990657, "lm_q1q2_score": 0.7343643937115903}}
{"text": "theory Chapter03\n  imports Main\nbegin\n\ndeclare [[names_short]]\n\nsection \"Chapter 3\"\n\ndatatype t = \n  TTrue\n  | FFalse\n  | Zero \n  | Succ t\n  | Pred t\n  | IsZero t\n  | IfElse t t t (\"If _ Then _ Else _\" [85,85,85] 80)\n\n(* 3.2.5 *)\nfun terms :: \"nat \\<Rightarrow> t set\" where\n\"terms 0 = {}\" |\n\"terms (Suc n) = \n  {TTrue,FFalse,Zero}\n  \\<union> {Succ t | t. t \\<in> terms n} \\<union> {Pred t | t. t \\<in> terms n} \\<union> {IsZero t | t. t \\<in> terms n}\n  \\<union> {IfElse t1 t2 t3 | t1 t2 t3. let termsn = terms n in t1 \\<in> termsn \\<and> t2 \\<in> termsn \\<and> t3 \\<in> termsn}\"\n\nlemma succ: \"Succ t \\<in> terms (Suc n) \\<longleftrightarrow> t \\<in> terms n\" \n  by (induction n) auto\n\nlemma pred: \"Pred t \\<in> terms (Suc n) \\<longleftrightarrow> t \\<in> terms n\" \n  by (induction n) auto\n\nlemma iszero: \"IsZero t \\<in> terms (Suc n) \\<longleftrightarrow> t \\<in> terms n\" \n  by (induction n) auto\n\nlemma ifelse: \"IfElse t1 t2 t3 \\<in> terms (Suc n) \\<longleftrightarrow> t1 \\<in> terms n \\<and> t2 \\<in> terms n \\<and> t3 \\<in> terms n\" \n  by (induction n) auto\nthm terms.simps\nlemma \"terms n \\<subseteq> terms (Suc n)\"\nproof (induction n)\n  case 0\n  then show ?case\n    by simp\nnext\n  case (Suc n)\n  have \"t \\<in> terms (Suc n) \\<Longrightarrow> t \\<in> terms (Suc (Suc n))\" for t\n  proof (induction t)\n    case (Succ t)\n    then show ?case\n      using Suc.IH\n      by (meson in_mono succ) \n  next\n    case (Pred t)\n    then show ?case \n      using Suc.IH\n      by (meson in_mono pred) \n  next\n    case (IsZero t)\n    then show ?case \n      using Suc.IH\n      by (meson in_mono iszero) \n  next\n    case (IfElse t1 t2 t3)\n    then show ?case \n      using Suc.IH\n      by (meson in_mono ifelse) \n  qed auto\n  then show ?case \n    by blast\nqed\n\n(* 3.3.1 *)\nfun Consts :: \"t \\<Rightarrow> t set\" where\n\"Consts TTrue = {TTrue}\" |\n\"Consts FFalse = {FFalse}\" |\n\"Consts Zero = {Zero}\" |\n\"Consts (Succ t1) = Consts t1\" |\n\"Consts (Pred t1) = Consts t1\" |\n\"Consts (IsZero t1) = Consts t1\" |\n\"Consts (IfElse t1 t2 t3) = Consts t1 \\<union> Consts t2 \\<union> Consts t3\" \n\n(* 3.3.2 *)\nfun size :: \"t \\<Rightarrow> nat\" where\n\"size TTrue = 1\" |\n\"size FFalse = 1\" |\n\"size Zero = 1\" |\n\"size (Succ t1) = 1 + size t1\" |\n\"size (Pred t1) = 1 + size t1\" |\n\"size (IsZero t1) = 1 + size t1\" |\n\"size (IfElse t1 t2 t3) = 1 + size t1 + size t2 + size t3\" \n\nlemma size_not_zero: \"size t > 0\"\n  by (cases t) auto\n\nfun depth :: \"t \\<Rightarrow> nat\" where\n\"depth TTrue = 1\" |\n\"depth FFalse = 1\" |\n\"depth Zero = 1\" |\n\"depth (Succ t1) = 1 + depth t1\" |\n\"depth (Pred t1) = 1 + depth t1\" |\n\"depth (IsZero t1) = 1 + depth t1\" |\n\"depth (IfElse t1 t2 t3) = Max {depth t1, depth t2, depth t3}\" \n\nlemma depth_not_zero: \"depth t > 0\"\n  by (induction t) auto\n\n(* 3.3.3 *)\nlemma \"card (Consts t) \\<le> size t\"\nproof (induction t)\n  case (IfElse t1 t2 t3)\n  have \"card (Consts (IfElse t1 t2 t3)) = card (Consts t1 \\<union> Consts t2 \\<union> Consts t3)\" \n    by simp\n  also have \"\\<dots> \\<le> card (Consts t1) + card (Consts t2) + card (Consts t3)\"\n    by (metis add_mono_thms_linordered_semiring(3) card_Un_le order_trans) \n  also have \"\\<dots> \\<le> size t1 + size t2 + size t3\" \n    using IfElse.IH by (simp add: add_mono)\n  also have \"\\<dots> \\<le> size (IfElse t1 t2 t3)\" \n    by simp\n  finally show ?case .\nqed auto\n\n(* 3.3.4 *)\nlemma raw_induct[case_names TTrue FFalse Zero Succ Pred IsZero IfElse]: \n  assumes \"P TTrue\" \n    and \"P FFalse\"\n    and \"P Zero\"\n    and \"\\<And>t. P (Succ t)\"\n    and \"\\<And>t. P (Pred t)\" \n    and \"\\<And>t. P (IsZero t)\"\n    and \"\\<And>t1 t2 t3. P (IfElse t1 t2 t3)\"\n  shows \"P t\"\n  using assms\n  by (cases t) auto\n\nlemma depth_induct: \n  \"(\\<And>r::t. depth r < depth s \\<Longrightarrow> P r) \\<Longrightarrow> P s\"\n  sorry\n\nlemma size_induct: \n  \"(\\<And>r::t. size r < size s \\<Longrightarrow> P r) \\<Longrightarrow> P s\"\n  sorry\n\nend", "meta": {"author": "waynee95", "repo": "isabelle-tapl", "sha": "2ed724f904b20798190891c5097613c2b9c44d9c", "save_path": "github-repos/isabelle/waynee95-isabelle-tapl", "path": "github-repos/isabelle/waynee95-isabelle-tapl/isabelle-tapl-2ed724f904b20798190891c5097613c2b9c44d9c/Chapter03.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.872347368040789, "lm_q2_score": 0.8418256393148982, "lm_q1q2_score": 0.7343643808056061}}
{"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_mod_same\nimports \"../../Test_Base\"\nbegin\n\ndatatype Nat = Z | S \"Nat\"\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\n(*fun did not finish the proof*)\nfunction mod2 :: \"Nat => Nat => Nat\" where\n\"mod2 x (Z) = Z\"\n| \"mod2 x (S z) =\n     (if lt x (S z) then x else mod2 (minus x (S z)) (S z))\"\nby pat_completeness auto\n\nfun go :: \"Nat => Nat => Nat => Nat\" where\n\"go x y (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 x y = go x Z y\"\n\ntheorem property0 :\n  \"((mod2 m n) = (modstructural m n))\"\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_mod_same.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898203834277, "lm_q2_score": 0.810478913248044, "lm_q1q2_score": 0.7342856450381511}}
{"text": "(*  Title:       Graph.thy\n    Author:      Filip Smola, 2019\n*)\n\nsection\\<open>Graphs\\<close>\ntext\\<open>The graph theory required to define bigraphs and their constituents.\nFocused on forests (for place graphs) and hypergraphs (for link graphs).\n\nHeavily inspired by Tom Ridge's 2005 paper \"Graphs and Trees in Isabelle/HOL\".\\<close>\n\ntheory Graph\n  imports\n    Main\nbegin\n\nsubsection\\<open>Paths and Edges\\<close>\n\ntext\\<open>A path is a list of nodes with some extra conditions. The extra conditions are introduced in a\nlater subsection.\\<close>\ntype_synonym 'a prepath = \"'a list\"\n\ntext\\<open>An edge is a set of one or more connected nodes.\\<close>\ntype_synonym 'a edge = \"'a set\"\n\ntext\\<open>A pre-path gives rise to a list of edges.\\<close>\nprimrec edge_list :: \"'a prepath \\<Rightarrow> 'a edge list\"\n  where\n    \"edge_list [] = []\"\n  | \"edge_list (x#xs) = (case xs of\n        [] \\<Rightarrow> []\n      | (y#ys) \\<Rightarrow> ({x,y}#(edge_list xs)))\"\n\ntext\\<open>A path is loop-free if its generated edge list contains no loops (i.e. edges \\<open>{x,x}\\<close>).\\<close>\ndefinition is_loop_free :: \"'a prepath \\<Rightarrow> bool\"\n  where \"is_loop_free p = (\\<forall>x . {x,x} \\<notin> set (edge_list p))\"\n\nsubsection\\<open>Graphs and Subgraphs\\<close>\n\ntext\\<open>A graph is a record with a set of vertices and a set of edges.\\<close>\nrecord 'a pregraph =\n  Verts :: \"'a set\"\n  Edges :: \"'a edge set\"\n\n(*TODO paper suggests defining the next two on pregraph instead of pregraph_scheme*)\ntext\\<open>A graph is well-formed iff its edge set is a subset of the powerset of the vertices and\ncontains no loops.\\<close>\ndefinition is_graph :: \"('a,'b) pregraph_scheme \\<Rightarrow> bool\"\n  where \"is_graph g = (Edges g \\<subseteq> Pow (Verts g) \\<and> (\\<forall>x. {x,x} \\<notin> (Edges g)))\"\n\ntext\\<open>A graph G is a subgraph of a graph H iff the vertex and edge sets of G are subsets of those of\nH.\\<close>\ndefinition is_subgraph :: \"('a,'b) pregraph_scheme \\<Rightarrow> ('a,'c) pregraph_scheme \\<Rightarrow> bool\"\n  where \"is_subgraph G H = (Verts G \\<subseteq> Verts H \\<and> Edges G \\<subseteq> Edges H)\"\n\nsubsection\\<open>Paths Continued\\<close>\n\ntext\\<open>A path consists of a set of vertices and gives rise to a set of edges, therefore it represents\na graph.\\<close>\ndefinition graph_of :: \"'a prepath \\<Rightarrow> 'a pregraph\"\n  where \"graph_of p = \\<lparr> Verts = set p, Edges = set (edge_list p) \\<rparr>\"\n\ntext\\<open>A path lies in a graph G if its graph is a subgraph of G. Therefore we do not require a special\npredicate for that.\\<close>\n\ntext\\<open>We constrain the type of prepaths with the following properties:\n  * The empty list does not represent a valid path,\n  * A path should be loop-free (which respects the restriction placed on graphs)\nThis most general form of a path is called a walk.\\<close>\ndefinition is_walk :: \"'a prepath \\<Rightarrow> bool\"\n  where \"is_walk p = (p \\<noteq> [] \\<and> is_loop_free p)\"\n\ntext\\<open>A trail is a walk whose all edges are distinct.\\<close>\ndefinition is_trail :: \"'a prepath \\<Rightarrow> bool\"\n  where \"is_trail p = (is_walk p \\<and> distinct (edge_list p))\"\n\n(* Deviation from source: I note length constraints of circuits as lemmas instead of including them\nin the circuit definition. *)\ntext\\<open>A circuit is a trail whose start and end vertices are the same and which contains at least one\nedge.\\<close>\ndefinition is_circuit :: \"'a prepath \\<Rightarrow> bool\"\n  where \"is_circuit p = (is_trail p \\<and> hd p = last p \\<and> length (edge_list p) > 0)\"\n\ntext\\<open>A circuit can't be of length 0 because walks can't be empty.\nIt can't be of length 1 because it has to contain an edge.\nIt can't be of length 2 because walks are loop-free.\nIt can't be of length 3 because edges have to be distinct (i.e. not \\<open>{x,y}\\<close> and \\<open>{y,x}\\<close>).\\<close>\nlemma circuit_length:\n  assumes circ: \"is_circuit p\"\n  shows \"length p > 3\"\nproof -\n  have l0: \"length p \\<noteq> 0\"\n    using circ is_circuit_def is_trail_def is_walk_def by blast\n\n  moreover have \"length p \\<noteq> 1\"\n  proof (rule ccontr)\n    assume \"\\<not>length p \\<noteq> 1\"\n    then have \"length p = 1\"\n      by simp\n    then have \"\\<exists>x. p = [x]\"\n      using length_0_conv length_Suc_conv One_nat_def by metis\n    then obtain x where \"p = [x]\"\n      by auto\n    then have \"edge_list p = []\"\n      by simp\n    then have \"length (edge_list p) = 0\"\n      by simp\n    then show \"False\"\n      using circ is_circuit_def by blast\n  qed\n\n  moreover have \"length p \\<noteq> 2\"\n  proof (rule ccontr)\n    assume \"\\<not>length p \\<noteq> 2\"\n    then have \"length p = 2\"\n      by simp\n    then have \"\\<exists>x y. p = [x,y]\"\n      using length_0_conv length_Suc_conv One_nat_def Suc_1 by metis\n    then obtain x y where cont_p: \"p = [x,y]\" and \"hd p = x\" and \"last p = y\"\n      by auto\n    then have \"x = y\"\n      using is_circuit_def circ by metis\n    moreover have \"edge_list p = [{x,y}]\"\n      using cont_p by simp\n    ultimately have \"\\<not>is_loop_free p\"\n      by (simp add: is_loop_free_def)\n    then show \"False\"\n      using circ is_circuit_def is_trail_def is_walk_def by blast\n  qed\n\n  moreover have \"length p \\<noteq> 3\"\n  proof (rule ccontr)\n    assume \"\\<not>length p \\<noteq> 3\"\n    then have \"length p = 3\"\n      by simp\n    then have \"\\<exists>x y z. p = [x,y,z]\"\n      using length_0_conv length_Suc_conv numeral_3_eq_3 by smt\n    then obtain x y z where cont_p: \"p = [x,y,z]\" and \"hd p = x\" and \"last p = z\"\n      by auto\n    then have \"x = z\"\n      using is_circuit_def circ by metis\n    then have \"{x,y} = {y,z}\"\n      by (simp add: insert_commute)\n    moreover have \"edge_list p = [{x,y},{y,z}]\"\n      using cont_p by simp\n    ultimately have \"\\<not>distinct (edge_list p)\"\n      by simp\n    then show \"False\"\n      using circ is_circuit_def is_trail_def by blast\n  qed\n\n  moreover have \"length p \\<ge> 0\"\n    by simp\n\n  ultimately show \"length p > 3\"\n    by (simp add: Suc_lessI numeral_3_eq_3)\nqed\n\ntext\\<open>A path is a trail whose vertices are distinct.\\<close>\ndefinition is_path :: \"'a prepath \\<Rightarrow> bool\"\n  where \"is_path p = (is_trail p \\<and> distinct p)\"\n\ntext\\<open>If the vertices are distinct, then the edge list is also distinct.\\<close>\nlemma vertices_distinct_then_edges:\n  assumes \"distinct (p :: 'a prepath)\"\n  shows \"distinct (edge_list p)\"\nproof (cases \"length p < 2\")\n  (* Trivial for zero, one vertices *)\n  case True\n  then have \"length p = 0 \\<or> length p = 1\"\n    by (simp add: less_Suc_eq numeral_2_eq_2)\n  then have \"p = [] \\<or> (\\<exists>x. p = [x])\"\n      using length_0_conv length_Suc_conv One_nat_def Suc_1 by metis\n  then have \"edge_list p = []\"\n    by auto\n  then show ?thesis\n    by simp\nnext\n  case geq: False\n  then show ?thesis\n  proof (cases \"length p = 2\")\n    (* Still simple with two vertices giving rise to one edge. *)\n    case True\n    then have \"\\<exists>x y. p = [x,y]\"\n      using length_0_conv length_Suc_conv One_nat_def Suc_1 by metis\n    then obtain x y where cont_p: \"p = [x, y]\"\n      by auto\n    then have \"edge_list p = [{x,y}]\"\n      by simp\n    then show \"distinct (edge_list p)\"\n      by simp\n  next\n    (* If edge list wasn't distinct, there would be two edges {a,b} in it and those can only arise by\nhaving two sequences of a followed by b in the vertex list. *)\n    case False\n    then have ge: \"length p > 2\"\n      using geq by simp\n    show ?thesis\n    proof (rule ccontr)\n      assume \"\\<not>distinct (edge_list p)\"\n      then have \"\\<exists>a b l r. edge_list p = l@{a,b}#r \\<and> distinct l \\<and> {a,b} \\<in> set r\"\n        sorry\n      show \"False\" sorry\n    qed\n  qed\nqed\n\ntext\\<open>We can then derive an alternative definition of a path as a non-empty distinct list.\\<close>\nlemma is_path_def_2: \"is_path p = (p \\<noteq> [] \\<and> distinct p)\"\n  sorry\n\ntext\\<open>We define a cycle as a circuit whose vertices are distinct, except for the first and last.\\<close>\ndefinition is_cycle :: \"'a prepath \\<Rightarrow> bool\"\n  where \"is_cycle p = (is_circuit p \\<and> is_path (tl p))\"\n\ntext\\<open>We can also derive a cycle definition removing some redundancy.\\<close>\nlemma is_cycle_def_2: \"is_cycle p = (hd p = last p \\<and> distinct (tl p) \\<and> length (edge_list p) > 0)\"\n  sorry\nend", "meta": {"author": "pilif0", "repo": "bigraph", "sha": "62c303bd8a523d27a19c957114390b08cebe0faa", "save_path": "github-repos/isabelle/pilif0-bigraph", "path": "github-repos/isabelle/pilif0-bigraph/bigraph-62c303bd8a523d27a19c957114390b08cebe0faa/Graph.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9032942119105696, "lm_q2_score": 0.8128673201042493, "lm_q1q2_score": 0.7342583453014246}}
{"text": "\ntheory Binary_operations\n imports Bij_betw_simplicial_complex_bool_func\nbegin\n\nsection\\<open>Binary operations over Boolean functions and simplicial complexes\\<close>\n\ntext\\<open>In this theory some results on binary operations over Boolean functions and\n  their relationship to operations over the induced simplicial complexes are\n  presented. We follow the presentation by Chastain and Scoville~\\cite[Sect. 1.1]{CHSC}.\\<close>\n\ndefinition bool_fun_or :: \"nat \\<Rightarrow> (bool vec \\<Rightarrow> bool) \\<Rightarrow> (bool vec \\<Rightarrow> bool) \\<Rightarrow> (bool vec \\<Rightarrow> bool)\"\n  where \"(bool_fun_or n f g) \\<equiv> (\\<lambda>x. f x \\<or> g x)\"\n\ndefinition bool_fun_and :: \"nat \\<Rightarrow> (bool vec \\<Rightarrow> bool) \\<Rightarrow> (bool vec \\<Rightarrow> bool) \\<Rightarrow> (bool vec \\<Rightarrow> bool)\"\n  where \"(bool_fun_and n f g) \\<equiv> (\\<lambda>x. f x \\<and> g x)\"\n\nlemma eq_union_or: \n  \"simplicial_complex_induced_by_monotone_boolean_function n (bool_fun_or n f g)\n  = simplicial_complex_induced_by_monotone_boolean_function n f \n    \\<union> simplicial_complex_induced_by_monotone_boolean_function n g\"\n  (is \"?sc n (?bf_or n f g) = ?sc n f \\<union> ?sc n g\")\nproof\n  show \"?sc n f \\<union> ?sc n g \\<subseteq> ?sc n (?bf_or n f g)\"\n  proof\n    fix \\<sigma> :: \"nat set\"\n    assume \"\\<sigma> \\<in> (?sc n f \\<union> ?sc n g)\"\n    hence sigma: \"\\<sigma> \\<in> ?sc n f \\<or> \\<sigma> \\<in> ?sc n g\" by auto\n    have \"f (simplicial_complex.bool_vec_from_simplice n \\<sigma>) \n           \\<or> g (simplicial_complex.bool_vec_from_simplice n \\<sigma>)\"\n    proof (cases \"\\<sigma> \\<in> ?sc n f\")\n      case True\n      from simplicial_complex.simplicial_complex_implies_true [OF True]\n      show \"f (simplicial_complex.bool_vec_from_simplice n \\<sigma>) \n           \\<or> g (simplicial_complex.bool_vec_from_simplice n \\<sigma>)\" by fast\n    next\n      case False\n      hence sigmain: \"\\<sigma> \\<in> ?sc n g\" using sigma by fast\n      from simplicial_complex.simplicial_complex_implies_true [OF sigmain]\n      show \"f (simplicial_complex.bool_vec_from_simplice n \\<sigma>) \n           \\<or> g (simplicial_complex.bool_vec_from_simplice n \\<sigma>)\" by fast\n    qed\n    thus \"\\<sigma> \\<in> ?sc n (?bf_or n f g)\"\n      using simplicial_complex_induced_by_monotone_boolean_function_def\n      using bool_fun_or_def sigma by auto\n  qed\nnext\n  show \"?sc n (?bf_or n f g) \\<subseteq> ?sc n f \\<union> ?sc n g\"\n  proof\n    fix \\<sigma>::\"nat set\"\n    assume sigma: \"\\<sigma> \\<in> ?sc n (?bf_or n f g)\"\n    hence \"bool_fun_or n f g (simplicial_complex.bool_vec_from_simplice n \\<sigma>)\"\n      unfolding simplicial_complex.bool_vec_from_simplice_def\n      unfolding simplicial_complex_induced_by_monotone_boolean_function_def\n      unfolding ceros_of_boolean_input_def\n      by auto (smt (verit) dim_vec eq_vecI index_vec)+\n    hence \"(f (simplicial_complex.bool_vec_from_simplice n \\<sigma>)) \n            \\<or> (g (simplicial_complex.bool_vec_from_simplice n \\<sigma>))\"\n      unfolding bool_fun_or_def\n      by auto\n    hence \"\\<sigma> \\<in> ?sc n f \\<or> \\<sigma> \\<in> ?sc n g\"\n      by (smt (z3) sigma bool_fun_or_def mem_Collect_eq \n            simplicial_complex_induced_by_monotone_boolean_function_def)\n    thus \"\\<sigma> \\<in> simplicial_complex_induced_by_monotone_boolean_function n f \n          \\<union> simplicial_complex_induced_by_monotone_boolean_function n g\"\n      by auto\n  qed\nqed\n\nlemma eq_inter_and:\n  \"simplicial_complex_induced_by_monotone_boolean_function n (bool_fun_and n f g)\n  = simplicial_complex_induced_by_monotone_boolean_function n f \n    \\<inter> simplicial_complex_induced_by_monotone_boolean_function n g\"\n  (is \"?sc n (?bf_and n f g) = ?sc n f \\<inter> ?sc n g\")\nproof\n  show \"?sc n f \\<inter> ?sc n g \\<subseteq> ?sc n (?bf_and n f g)\"\n  proof\n    fix \\<sigma> :: \"nat set\"\n    assume \"\\<sigma> \\<in> (?sc n f \\<inter> ?sc n g)\"\n    hence sigma: \"\\<sigma> \\<in> ?sc n f \\<and> \\<sigma> \\<in> ?sc n g\" by auto\n    have \"f (simplicial_complex.bool_vec_from_simplice n \\<sigma>) \n           \\<and> g (simplicial_complex.bool_vec_from_simplice n \\<sigma>)\"\n    proof -\n      from sigma have sigmaf: \"\\<sigma> \\<in> ?sc n f\" and sigmag: \"\\<sigma> \\<in> ?sc n g\"\n        by auto\n      have \"f (simplicial_complex.bool_vec_from_simplice n \\<sigma>)\"\n        using simplicial_complex.simplicial_complex_implies_true [OF sigmaf] .\n      moreover have \"g (simplicial_complex.bool_vec_from_simplice n \\<sigma>)\"\n        using simplicial_complex.simplicial_complex_implies_true [OF sigmag] .\n      ultimately show ?thesis by fast\n    qed\n    thus \"\\<sigma> \\<in> ?sc n (?bf_and n f g)\"\n      unfolding simplicial_complex_induced_by_monotone_boolean_function_def\n      unfolding bool_fun_and_def\n      using sigma apply auto\n      by (smt (z3) Collect_cong ceros_of_boolean_input_def dim_vec index_vec mem_Collect_eq \n          simplicial_complex.bool_vec_from_simplice_def \n          simplicial_complex_induced_by_monotone_boolean_function_def)\n  qed\nnext\n  show \"?sc n (?bf_and n f g) \\<subseteq> ?sc n f \\<inter> ?sc n g\"\n  proof\n    fix \\<sigma> :: \"nat set\"\n    assume sigma: \"\\<sigma> \\<in> ?sc n (?bf_and n f g)\"\n    hence \"bool_fun_and n f g (simplicial_complex.bool_vec_from_simplice n \\<sigma>)\"\n      unfolding simplicial_complex.bool_vec_from_simplice_def\n      unfolding simplicial_complex_induced_by_monotone_boolean_function_def\n      unfolding ceros_of_boolean_input_def\n      by auto (smt (verit) dim_vec eq_vecI index_vec)+\n    hence \"(f (simplicial_complex.bool_vec_from_simplice n \\<sigma>)) \n          \\<and> (g (simplicial_complex.bool_vec_from_simplice n \\<sigma>))\"\n      unfolding bool_fun_and_def\n      by auto\n    hence \"\\<sigma> \\<in> ?sc n f \\<and> \\<sigma> \\<in> ?sc n g\"\n      using bool_fun_and_def sigma simplicial_complex_induced_by_monotone_boolean_function_def by auto\n    thus \"\\<sigma> \\<in> simplicial_complex_induced_by_monotone_boolean_function n f \n          \\<inter> simplicial_complex_induced_by_monotone_boolean_function n g\"\n      by auto\n  qed\nqed\n\ndefinition bool_fun_ast :: \"(nat \\<times> nat) \\<Rightarrow> (bool vec \\<Rightarrow> bool) \\<times> (bool vec \\<Rightarrow> bool) \n    \\<Rightarrow> (bool vec \\<times> bool vec \\<Rightarrow> bool)\"\n  where \"(bool_fun_ast n f) \\<equiv> (\\<lambda> (x,y). (fst f x) \\<and> (snd f y))\"\n\ndefinition\n  simplicial_complex_induced_by_monotone_boolean_function_ast\n    :: \"(nat \\<times> nat) \\<Rightarrow> ((bool vec \\<times> bool vec \\<Rightarrow> bool)) \\<Rightarrow> (nat set * nat set) set\"\n  where \"simplicial_complex_induced_by_monotone_boolean_function_ast n f =\n        {z. \\<exists>x y. dim_vec x = fst n \\<and> dim_vec y = snd n \\<and> f (x, y) \n          \\<and> ((ceros_of_boolean_input x), (ceros_of_boolean_input y)) = z}\"\n\nlemma fst_es_simplice:\n  \"a \\<in> simplicial_complex_induced_by_monotone_boolean_function_ast n f\n    \\<Longrightarrow> (\\<exists>x y. f (x, y) \\<and> (ceros_of_boolean_input x) = fst(a))\"\n  by (smt (verit) fst_conv mem_Collect_eq \n        simplicial_complex_induced_by_monotone_boolean_function_ast_def)\n\nlemma snd_es_simplice:\n  \"a \\<in> simplicial_complex_induced_by_monotone_boolean_function_ast n f \n    \\<Longrightarrow> (\\<exists>x y. f (x, y) \\<and> (ceros_of_boolean_input y) = snd(a))\"\n  by (smt (verit) snd_conv mem_Collect_eq \n      simplicial_complex_induced_by_monotone_boolean_function_ast_def)\n\ndefinition set_ast :: \"(nat set) set \\<Rightarrow> (nat set) set \\<Rightarrow> ((nat set*nat set) set)\"\n  where \"set_ast A B \\<equiv> {c. \\<exists>a\\<in>A. \\<exists>b\\<in>B. c = (a,b)}\"\n\ndefinition set_fst :: \"(nat*nat) set \\<Rightarrow> nat set\"\n  where \"set_fst AB = {a. \\<exists>ab\\<in>AB. a = fst ab}\"\n\nlemma set_fst_simp [simp]:\n  assumes \"y \\<noteq> {}\"\n  shows \"set_fst (x \\<times> y) = x\"\nproof\n  show \"set_fst (x \\<times> y) \\<subseteq> x\"\n    by (smt (verit) SigmaE mem_Collect_eq prod.sel(1) set_fst_def subsetI)\n  show \"x \\<subseteq> set_fst (x \\<times> y)\"\n  proof\n    fix a::\"nat\"\n    assume \"a \\<in> x\"\n    then obtain b where \"b \\<in> y\" and \"(a,b) \\<in> (x\\<times>y)\"\n      using assms by blast\n    then show \"a \\<in> set_fst (x \\<times> y)\"\n      using set_fst_def by fastforce\n  qed\nqed\n\ndefinition set_snd :: \"(nat*nat) set \\<Rightarrow> nat set\"\n  where \"set_snd AB = {b. \\<exists>ab\\<in>AB. b = snd(ab)}\"\n\nlemma\n  simplicial_complex_ast_implies_fst_true:\n  assumes \"\\<gamma> \\<in> simplicial_complex_induced_by_monotone_boolean_function_ast nn\n     (bool_fun_ast nn f)\"\n  shows \"fst f (simplicial_complex.bool_vec_from_simplice (fst nn) (fst \\<gamma>))\"\n  using assms\n  unfolding simplicial_complex.bool_vec_from_simplice_def\n  unfolding simplicial_complex_induced_by_monotone_boolean_function_ast_def\n  unfolding bool_fun_ast_def\n  unfolding ceros_of_boolean_input_def\n  apply auto\n  by (smt (verit, ccfv_threshold) bool_fun_ast_def case_prod_conv dim_vec index_vec vec_eq_iff)\n\nlemma\n  simplicial_complex_ast_implies_snd_true:\n  assumes \"\\<gamma> \\<in> simplicial_complex_induced_by_monotone_boolean_function_ast nn\n     (bool_fun_ast nn f)\"\n  shows \"snd f (simplicial_complex.bool_vec_from_simplice (snd nn) (snd \\<gamma>))\"\n  using assms\n  unfolding simplicial_complex.bool_vec_from_simplice_def\n  unfolding simplicial_complex_induced_by_monotone_boolean_function_ast_def\n  unfolding bool_fun_ast_def\n  unfolding ceros_of_boolean_input_def\n  by auto (smt (verit, ccfv_threshold) bool_fun_ast_def \n        case_prod_conv dim_vec index_vec vec_eq_iff)\n\nlemma eq_ast:\n\"simplicial_complex_induced_by_monotone_boolean_function_ast (n, m) (bool_fun_ast (n, m) f)\n= set_ast (simplicial_complex_induced_by_monotone_boolean_function n (fst f)) \n          (simplicial_complex_induced_by_monotone_boolean_function m (snd f))\"\nproof\n  show \"set_ast (simplicial_complex_induced_by_monotone_boolean_function n (fst f))\n     (simplicial_complex_induced_by_monotone_boolean_function m (snd f))\n    \\<subseteq> simplicial_complex_induced_by_monotone_boolean_function_ast (n, m)\n        (bool_fun_ast (n, m) f)\"\n  proof\n    fix \\<gamma>::\"nat set*nat set\"\n    assume pert: \"\\<gamma> \\<in> set_ast (simplicial_complex_induced_by_monotone_boolean_function n (fst f))\n     (simplicial_complex_induced_by_monotone_boolean_function m (snd f))\"\n    hence f: \"(fst \\<gamma>) \\<in> simplicial_complex_induced_by_monotone_boolean_function n (fst f)\"\n      unfolding set_ast_def\n      by auto\n    have sigma: \"fst f (simplicial_complex.bool_vec_from_simplice n (fst \\<gamma>))\"\n      using simplicial_complex.simplicial_complex_implies_true [OF f] .\n    from pert have g: \"(snd \\<gamma>) \\<in> simplicial_complex_induced_by_monotone_boolean_function m (snd f)\"\n      unfolding set_ast_def by auto\n    have tau: \"(snd f) (simplicial_complex.bool_vec_from_simplice m (snd \\<gamma>))\"\n      using simplicial_complex.simplicial_complex_implies_true [OF g] .\n    from sigma and tau have sigtau: \"bool_fun_ast (n, m) f \n        ((simplicial_complex.bool_vec_from_simplice n (fst \\<gamma>)), \n         (simplicial_complex.bool_vec_from_simplice m (snd \\<gamma>)))\"\n      unfolding bool_fun_ast_def\n      by auto\n    from sigtau \n    show \"\\<gamma> \\<in> simplicial_complex_induced_by_monotone_boolean_function_ast (n, m) \n              (bool_fun_ast (n, m) f)\"\n      unfolding simplicial_complex_induced_by_monotone_boolean_function_ast_def\n      unfolding bool_fun_ast_def\n      using sigma apply auto\n      using f g simplicial_complex_induced_by_monotone_boolean_function_def by fastforce\n  qed\nnext\n  show \"simplicial_complex_induced_by_monotone_boolean_function_ast (n, m)\n     (bool_fun_ast (n, m) f)\n    \\<subseteq> set_ast (simplicial_complex_induced_by_monotone_boolean_function n (fst f))\n        (simplicial_complex_induced_by_monotone_boolean_function m (snd f))\"\n    proof\n    fix \\<gamma> :: \"nat set*nat set\"\n    assume pert: \"\\<gamma> \\<in> simplicial_complex_induced_by_monotone_boolean_function_ast (n, m)\n     (bool_fun_ast (n, m) f)\"\n    have sigma: \"(fst \\<gamma>) \\<in> simplicial_complex_induced_by_monotone_boolean_function n (fst f)\"\n      unfolding bool_fun_ast_def\n      unfolding simplicial_complex_induced_by_monotone_boolean_function_def\n      unfolding simplicial_complex_induced_by_monotone_boolean_function_ast_def\n      apply auto\n      apply (rule exI [of _ \"simplicial_complex.bool_vec_from_simplice n (fst \\<gamma>)\"], safe)\n      using simplicial_complex.bool_vec_from_simplice_def apply auto[1]\n        apply (metis fst_conv pert simplicial_complex_ast_implies_fst_true)\n      using ceros_of_boolean_input_def simplicial_complex.bool_vec_from_simplice_def \n        apply fastforce\n      using ceros_of_boolean_input_def pert \n          simplicial_complex.bool_vec_from_simplice_def \n          simplicial_complex_induced_by_monotone_boolean_function_ast_def by force\n   have tau: \"(snd \\<gamma>) \\<in> simplicial_complex_induced_by_monotone_boolean_function m (snd f)\"\n      unfolding bool_fun_ast_def\n      unfolding simplicial_complex_induced_by_monotone_boolean_function_def\n      unfolding simplicial_complex_induced_by_monotone_boolean_function_ast_def\n      apply auto\n      apply (rule exI [of _ \"simplicial_complex.bool_vec_from_simplice m (snd \\<gamma>)\"], safe)\n      using simplicial_complex.bool_vec_from_simplice_def apply auto[1]\n        apply (metis snd_conv pert simplicial_complex_ast_implies_snd_true)\n      using ceros_of_boolean_input_def simplicial_complex.bool_vec_from_simplice_def \n       apply fastforce\n      using ceros_of_boolean_input_def pert \n        simplicial_complex.bool_vec_from_simplice_def \n        simplicial_complex_induced_by_monotone_boolean_function_ast_def by force\n    from sigma and tau \n    show \"\\<gamma> \\<in> set_ast \n        (simplicial_complex_induced_by_monotone_boolean_function n (fst f)) \n        (simplicial_complex_induced_by_monotone_boolean_function m (snd f))\"\n      using set_ast_def\n      by force\n  qed\nqed\n\nend", "meta": {"author": "jmaransay", "repo": "morse", "sha": "99d05d63fad13f5b4827f2f656ebbad989e90e09", "save_path": "github-repos/isabelle/jmaransay-morse", "path": "github-repos/isabelle/jmaransay-morse/morse-99d05d63fad13f5b4827f2f656ebbad989e90e09/Binary_operations.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9032942014971871, "lm_q2_score": 0.8128673155708975, "lm_q1q2_score": 0.7342583327417759}}
{"text": "(*\n  File:     Solovay_Strassen.thy\n  Authors:  Daniel St\u00fcwe, Manuel Eberl\n\n  The Solovay--Strassen primality test.\n*)\nsection \\<open>The Solovay--Strassen Test\\<close>\ntheory Solovay_Strassen_Test\nimports \n  Generalized_Primality_Test\n  Euler_Witness\nbegin\n\ndefinition solovay_strassen_witness :: \"nat \\<Rightarrow> nat \\<Rightarrow> bool\" where\n  \"solovay_strassen_witness n a =\n     (let x = Jacobi (int a) (int n) in x \\<noteq> 0 \\<and> [x = int a ^ ((n - 1) div 2)] (mod n))\"\n\ndefinition solovay_strassen :: \"nat \\<Rightarrow> bool pmf\" where\n  \"solovay_strassen = primality_test solovay_strassen_witness\"\n\nlemma prime_imp_solovay_strassen_witness:\n  assumes \"prime p\" \"odd p\" \"a \\<in> {2..<p}\"\n  shows   \"solovay_strassen_witness p a\"\nproof -\n  have eq: \"Jacobi a p = Legendre a p\"\n    using prime_p_Jacobi_eq_Legendre assms by simp\n  from \\<open>prime p\\<close> have \"coprime p a\"\n    by (rule prime_imp_coprime) (use assms in auto)\n\n  show ?thesis unfolding solovay_strassen_witness_def Let_def eq\n  proof\n    from \\<open>coprime p a\\<close> and \\<open>prime p\\<close> show \"Legendre (int a) (int p) \\<noteq> 0\"\n      by (auto simp: coprime_commute)\n  next\n    show \"[Legendre (int a) (int p) = int a ^ ((p - 1) div 2)] (mod int p)\"\n      using assms by (intro euler_criterion) auto\n  qed\nqed\n    \nlemma card_solovay_strassen_liars_composite:\n  fixes n :: nat\n  assumes \"\\<not>prime n\" \"n > 2\" \"odd n\"\n  shows   \"card {a \\<in> {2..<n}. solovay_strassen_witness n a} < (n - 2) div 2\"\n    (is \"card ?A < _\")\nproof -\n  interpret euler_witness_context n\n    using assms unfolding euler_witness_context_def by simp\n  have \"card H < (n - 1) div 2\"\n    by (intro card_euler_liars_cosets_limit(2) assms)\n  also from assms have \"H = insert 1 ?A\"\n    by (auto simp: solovay_strassen_witness_def Let_def\n                   euler_witness_def H_def Jacobi_eq_0_iff_not_coprime)\n  also have \"card \\<dots> = card ?A + 1\"\n    by (subst card.insert) auto\n  finally show \"card ?A < (n - 2) div 2\"\n    by linarith\nqed\n\ninterpretation solovay_strassen: good_prob_primality_test solovay_strassen_witness n \"1 / 2\"\n  rewrites \"primality_test solovay_strassen_witness = solovay_strassen\"\nproof -\n  show \"good_prob_primality_test solovay_strassen_witness n (1 / 2)\"\n  proof\n    fix n :: nat assume \"\\<not>prime n\" \"n > 2\" \"odd n\"\n    thus \"real (card {a. 2 \\<le> a \\<and> a < n \\<and> solovay_strassen_witness n a}) < (1 / 2) * real (n - 2)\"\n      using card_solovay_strassen_liars_composite[of n] by auto\n  qed (use prime_imp_solovay_strassen_witness in auto)\nqed (simp_all add: solovay_strassen_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/Probabilistic_Prime_Tests/Solovay_Strassen_Test.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178895092415, "lm_q2_score": 0.8080672112416737, "lm_q1q2_score": 0.734224324060028}}
{"text": "(*  Title:      HOL/Statespace/DistinctTreeProver.thy\n    Author:     Norbert Schirmer, TU Muenchen\n*)\n\nsection {* Distinctness of Names in a Binary Tree \\label{sec:DistinctTreeProver}*}\n\ntheory DistinctTreeProver \nimports Main\nbegin\n\ntext {* A state space manages a set of (abstract) names and assumes\nthat the names are distinct. The names are stored as parameters of a\nlocale and distinctness as an assumption. The most common request is\nto proof distinctness of two given names. We maintain the names in a\nbalanced binary tree and formulate a predicate that all nodes in the\ntree have distinct names. This setup leads to logarithmic certificates.\n*}\n\nsubsection {* The Binary Tree *}\n\ndatatype 'a tree = Node \"'a tree\" 'a bool \"'a tree\" | Tip\n\n\ntext {* The boolean flag in the node marks the content of the node as\ndeleted, without having to build a new tree. We prefer the boolean\nflag to an option type, so that the ML-layer can still use the node\ncontent to facilitate binary search in the tree. The ML code keeps the\nnodes sorted using the term order. We do not have to push ordering to\nthe HOL level. *}\n\nsubsection {* Distinctness of Nodes *}\n\n\nprimrec set_of :: \"'a tree \\<Rightarrow> 'a set\"\nwhere\n  \"set_of Tip = {}\"\n| \"set_of (Node l x d r) = (if d then {} else {x}) \\<union> set_of l \\<union> set_of r\"\n\nprimrec all_distinct :: \"'a tree \\<Rightarrow> bool\"\nwhere\n  \"all_distinct Tip = True\"\n| \"all_distinct (Node l x d r) =\n    ((d \\<or> (x \\<notin> set_of l \\<and> x \\<notin> set_of r)) \\<and> \n      set_of l \\<inter> set_of r = {} \\<and>\n      all_distinct l \\<and> all_distinct r)\"\n\ntext {* Given a binary tree @{term \"t\"} for which \n@{const all_distinct} holds, given two different nodes contained in the tree,\nwe want to write a ML function that generates a logarithmic\ncertificate that the content of the nodes is distinct. We use the\nfollowing lemmas to achieve this.  *} \n\nlemma all_distinct_left: \"all_distinct (Node l x b r) \\<Longrightarrow> all_distinct l\"\n  by simp\n\nlemma all_distinct_right: \"all_distinct (Node l x b r) \\<Longrightarrow> all_distinct r\"\n  by simp\n\nlemma distinct_left: \"all_distinct (Node l x False r) \\<Longrightarrow> y \\<in> set_of l \\<Longrightarrow> x \\<noteq> y\"\n  by auto\n\nlemma distinct_right: \"all_distinct (Node l x False r) \\<Longrightarrow> y \\<in> set_of r \\<Longrightarrow> x \\<noteq> y\"\n  by auto\n\nlemma distinct_left_right:\n    \"all_distinct (Node l z b r) \\<Longrightarrow> x \\<in> set_of l \\<Longrightarrow> y \\<in> set_of r \\<Longrightarrow> x \\<noteq> y\"\n  by auto\n\nlemma in_set_root: \"x \\<in> set_of (Node l x False r)\"\n  by simp\n\nlemma in_set_left: \"y \\<in> set_of l \\<Longrightarrow>  y \\<in> set_of (Node l x False r)\"\n  by simp\n\nlemma in_set_right: \"y \\<in> set_of r \\<Longrightarrow>  y \\<in> set_of (Node l x False r)\"\n  by simp\n\nlemma swap_neq: \"x \\<noteq> y \\<Longrightarrow> y \\<noteq> x\"\n  by blast\n\nlemma neq_to_eq_False: \"x\\<noteq>y \\<Longrightarrow> (x=y)\\<equiv>False\"\n  by simp\n\nsubsection {* Containment of Trees *}\n\ntext {* When deriving a state space from other ones, we create a new\nname tree which contains all the names of the parent state spaces and\nassume the predicate @{const all_distinct}. We then prove that the new\nlocale interprets all parent locales. Hence we have to show that the\nnew distinctness assumption on all names implies the distinctness\nassumptions of the parent locales. This proof is implemented in ML. We\ndo this efficiently by defining a kind of containment check of trees\nby ``subtraction''.  We subtract the parent tree from the new tree. If\nthis succeeds we know that @{const all_distinct} of the new tree\nimplies @{const all_distinct} of the parent tree.  The resulting\ncertificate is of the order @{term \"n * log(m)\"} where @{term \"n\"} is\nthe size of the (smaller) parent tree and @{term \"m\"} the size of the\n(bigger) new tree.  *}\n\n\nprimrec delete :: \"'a \\<Rightarrow> 'a tree \\<Rightarrow> 'a tree option\"\nwhere\n  \"delete x Tip = None\"\n| \"delete x (Node l y d r) = (case delete x l of\n                                Some l' \\<Rightarrow>\n                                 (case delete x r of \n                                    Some r' \\<Rightarrow> Some (Node l' y (d \\<or> (x=y)) r')\n                                  | None \\<Rightarrow> Some (Node l' y (d \\<or> (x=y)) r))\n                               | None \\<Rightarrow>\n                                  (case delete x r of \n                                     Some r' \\<Rightarrow> Some (Node l y (d \\<or> (x=y)) r')\n                                   | None \\<Rightarrow> if x=y \\<and> \\<not>d then Some (Node l y True r)\n                                             else None))\"\n\n\nlemma delete_Some_set_of: \"delete x t = Some t' \\<Longrightarrow> set_of t' \\<subseteq> set_of t\"\nproof (induct t arbitrary: t')\n  case Tip thus ?case by simp\nnext\n  case (Node l y d r)\n  have del: \"delete x (Node l y d r) = Some t'\" by fact\n  show ?case\n  proof (cases \"delete x l\")\n    case (Some l')\n    note x_l_Some = this\n    with Node.hyps\n    have l'_l: \"set_of l' \\<subseteq> set_of l\"\n      by simp\n    show ?thesis\n    proof (cases \"delete x r\")\n      case (Some r')\n      with Node.hyps\n      have \"set_of r' \\<subseteq> set_of r\"\n        by simp\n      with l'_l Some x_l_Some del\n      show ?thesis\n        by (auto split: split_if_asm)\n    next\n      case None\n      with l'_l Some x_l_Some del\n      show ?thesis\n        by (fastforce split: split_if_asm)\n    qed\n  next\n    case None\n    note x_l_None = this\n    show ?thesis\n    proof (cases \"delete x r\")\n      case (Some r')\n      with Node.hyps\n      have \"set_of r' \\<subseteq> set_of r\"\n        by simp\n      with Some x_l_None del\n      show ?thesis\n        by (fastforce split: split_if_asm)\n    next\n      case None\n      with x_l_None del\n      show ?thesis\n        by (fastforce split: split_if_asm)\n    qed\n  qed\nqed\n\nlemma delete_Some_all_distinct:\n  \"delete x t = Some t' \\<Longrightarrow> all_distinct t \\<Longrightarrow> all_distinct t'\"\nproof (induct t arbitrary: t')\n  case Tip thus ?case by simp\nnext\n  case (Node l y d r)\n  have del: \"delete x (Node l y d r) = Some t'\" by fact\n  have \"all_distinct (Node l y d r)\" by fact\n  then obtain\n    dist_l: \"all_distinct l\" and\n    dist_r: \"all_distinct r\" and\n    d: \"d \\<or> (y \\<notin> set_of l \\<and> y \\<notin> set_of r)\" and\n    dist_l_r: \"set_of l \\<inter> set_of r = {}\"\n    by auto\n  show ?case\n  proof (cases \"delete x l\")\n    case (Some l')\n    note x_l_Some = this\n    from Node.hyps (1) [OF Some dist_l]\n    have dist_l': \"all_distinct l'\"\n      by simp\n    from delete_Some_set_of [OF x_l_Some]\n    have l'_l: \"set_of l' \\<subseteq> set_of l\".\n    show ?thesis\n    proof (cases \"delete x r\")\n      case (Some r')\n      from Node.hyps (2) [OF Some dist_r]\n      have dist_r': \"all_distinct r'\"\n        by simp\n      from delete_Some_set_of [OF Some]\n      have \"set_of r' \\<subseteq> set_of r\".\n      \n      with dist_l' dist_r' l'_l Some x_l_Some del d dist_l_r\n      show ?thesis\n        by fastforce\n    next\n      case None\n      with l'_l dist_l'  x_l_Some del d dist_l_r dist_r\n      show ?thesis\n        by fastforce\n    qed\n  next\n    case None\n    note x_l_None = this\n    show ?thesis\n    proof (cases \"delete x r\")\n      case (Some r')\n      with Node.hyps (2) [OF Some dist_r]\n      have dist_r': \"all_distinct r'\"\n        by simp\n      from delete_Some_set_of [OF Some]\n      have \"set_of r' \\<subseteq> set_of r\".\n      with Some dist_r' x_l_None del dist_l d dist_l_r\n      show ?thesis\n        by fastforce\n    next\n      case None\n      with x_l_None del dist_l dist_r d dist_l_r\n      show ?thesis\n        by (fastforce split: split_if_asm)\n    qed\n  qed\nqed\n\nlemma delete_None_set_of_conv: \"delete x t = None = (x \\<notin> set_of t)\"\nproof (induct t)\n  case Tip thus ?case by simp\nnext\n  case (Node l y d r)\n  thus ?case\n    by (auto split: option.splits)\nqed\n\nlemma delete_Some_x_set_of:\n  \"delete x t = Some t' \\<Longrightarrow> x \\<in> set_of t \\<and> x \\<notin> set_of t'\"\nproof (induct t arbitrary: t')\n  case Tip thus ?case by simp\nnext\n  case (Node l y d r)\n  have del: \"delete x (Node l y d r) = Some t'\" by fact\n  show ?case\n  proof (cases \"delete x l\")\n    case (Some l')\n    note x_l_Some = this\n    from Node.hyps (1) [OF Some]\n    obtain x_l: \"x \\<in> set_of l\" \"x \\<notin> set_of l'\"\n      by simp\n    show ?thesis\n    proof (cases \"delete x r\")\n      case (Some r')\n      from Node.hyps (2) [OF Some]\n      obtain x_r: \"x \\<in> set_of r\" \"x \\<notin> set_of r'\"\n        by simp\n      from x_r x_l Some x_l_Some del \n      show ?thesis\n        by (clarsimp split: split_if_asm)\n    next\n      case None\n      then have \"x \\<notin> set_of r\"\n        by (simp add: delete_None_set_of_conv)\n      with x_l None x_l_Some del\n      show ?thesis\n        by (clarsimp split: split_if_asm)\n    qed\n  next\n    case None\n    note x_l_None = this\n    then have x_notin_l: \"x \\<notin> set_of l\"\n      by (simp add: delete_None_set_of_conv)\n    show ?thesis\n    proof (cases \"delete x r\")\n      case (Some r')\n      from Node.hyps (2) [OF Some]\n      obtain x_r: \"x \\<in> set_of r\" \"x \\<notin> set_of r'\"\n        by simp\n      from x_r x_notin_l Some x_l_None del \n      show ?thesis\n        by (clarsimp split: split_if_asm)\n    next\n      case None\n      then have \"x \\<notin> set_of r\"\n        by (simp add: delete_None_set_of_conv)\n      with None x_l_None x_notin_l del\n      show ?thesis\n        by (clarsimp split: split_if_asm)\n    qed\n  qed\nqed\n\n\nprimrec subtract :: \"'a tree \\<Rightarrow> 'a tree \\<Rightarrow> 'a tree option\"\nwhere\n  \"subtract Tip t = Some t\"\n| \"subtract (Node l x b r) t =\n     (case delete x t of\n        Some t' \\<Rightarrow> (case subtract l t' of \n                     Some t'' \\<Rightarrow> subtract r t''\n                    | None \\<Rightarrow> None)\n       | None \\<Rightarrow> None)\"\n\nlemma subtract_Some_set_of_res: \n  \"subtract t\\<^sub>1 t\\<^sub>2 = Some t \\<Longrightarrow> set_of t \\<subseteq> set_of t\\<^sub>2\"\nproof (induct t\\<^sub>1 arbitrary: t\\<^sub>2 t)\n  case Tip thus ?case by simp\nnext\n  case (Node l x b r)\n  have sub: \"subtract (Node l x b r) t\\<^sub>2 = Some t\" by fact\n  show ?case\n  proof (cases \"delete x t\\<^sub>2\")\n    case (Some t\\<^sub>2')\n    note del_x_Some = this\n    from delete_Some_set_of [OF Some] \n    have t2'_t2: \"set_of t\\<^sub>2' \\<subseteq> set_of t\\<^sub>2\" .\n    show ?thesis\n    proof (cases \"subtract l t\\<^sub>2'\")\n      case (Some t\\<^sub>2'')\n      note sub_l_Some = this\n      from Node.hyps (1) [OF Some] \n      have t2''_t2': \"set_of t\\<^sub>2'' \\<subseteq> set_of t\\<^sub>2'\" .\n      show ?thesis\n      proof (cases \"subtract r t\\<^sub>2''\")\n        case (Some t\\<^sub>2''')\n        from Node.hyps (2) [OF Some ] \n        have \"set_of t\\<^sub>2''' \\<subseteq> set_of t\\<^sub>2''\" .\n        with Some sub_l_Some del_x_Some sub t2''_t2' t2'_t2\n        show ?thesis\n          by simp\n      next\n        case None\n        with del_x_Some sub_l_Some sub\n        show ?thesis\n          by simp\n      qed\n    next\n      case None\n      with del_x_Some sub \n      show ?thesis\n        by simp\n    qed\n  next\n    case None\n    with sub show ?thesis by simp\n  qed\nqed\n\nlemma subtract_Some_set_of: \n  \"subtract t\\<^sub>1 t\\<^sub>2 = Some t \\<Longrightarrow> set_of t\\<^sub>1 \\<subseteq> set_of t\\<^sub>2\"\nproof (induct t\\<^sub>1 arbitrary: t\\<^sub>2 t)\n  case Tip thus ?case by simp\nnext\n  case (Node l x d r)\n  have sub: \"subtract (Node l x d r) t\\<^sub>2 = Some t\" by fact\n  show ?case\n  proof (cases \"delete x t\\<^sub>2\")\n    case (Some t\\<^sub>2')\n    note del_x_Some = this\n    from delete_Some_set_of [OF Some] \n    have t2'_t2: \"set_of t\\<^sub>2' \\<subseteq> set_of t\\<^sub>2\" .\n    from delete_None_set_of_conv [of x t\\<^sub>2] Some\n    have x_t2: \"x \\<in> set_of t\\<^sub>2\"\n      by simp\n    show ?thesis\n    proof (cases \"subtract l t\\<^sub>2'\")\n      case (Some t\\<^sub>2'')\n      note sub_l_Some = this\n      from Node.hyps (1) [OF Some] \n      have l_t2': \"set_of l \\<subseteq> set_of t\\<^sub>2'\" .\n      from subtract_Some_set_of_res [OF Some]\n      have t2''_t2': \"set_of t\\<^sub>2'' \\<subseteq> set_of t\\<^sub>2'\" .\n      show ?thesis\n      proof (cases \"subtract r t\\<^sub>2''\")\n        case (Some t\\<^sub>2''')\n        from Node.hyps (2) [OF Some ] \n        have r_t\\<^sub>2'': \"set_of r \\<subseteq> set_of t\\<^sub>2''\" .\n        from Some sub_l_Some del_x_Some sub r_t\\<^sub>2'' l_t2' t2'_t2 t2''_t2' x_t2\n        show ?thesis\n          by auto\n      next\n        case None\n        with del_x_Some sub_l_Some sub\n        show ?thesis\n          by simp\n      qed\n    next\n      case None\n      with del_x_Some sub \n      show ?thesis\n        by simp\n    qed\n  next\n    case None\n    with sub show ?thesis by simp\n  qed\nqed\n\nlemma subtract_Some_all_distinct_res: \n  \"subtract t\\<^sub>1 t\\<^sub>2 = Some t \\<Longrightarrow> all_distinct t\\<^sub>2 \\<Longrightarrow> all_distinct t\"\nproof (induct t\\<^sub>1 arbitrary: t\\<^sub>2 t)\n  case Tip thus ?case by simp\nnext\n  case (Node l x d r)\n  have sub: \"subtract (Node l x d r) t\\<^sub>2 = Some t\" by fact\n  have dist_t2: \"all_distinct t\\<^sub>2\" by fact\n  show ?case\n  proof (cases \"delete x t\\<^sub>2\")\n    case (Some t\\<^sub>2')\n    note del_x_Some = this\n    from delete_Some_all_distinct [OF Some dist_t2] \n    have dist_t2': \"all_distinct t\\<^sub>2'\" .\n    show ?thesis\n    proof (cases \"subtract l t\\<^sub>2'\")\n      case (Some t\\<^sub>2'')\n      note sub_l_Some = this\n      from Node.hyps (1) [OF Some dist_t2'] \n      have dist_t2'': \"all_distinct t\\<^sub>2''\" .\n      show ?thesis\n      proof (cases \"subtract r t\\<^sub>2''\")\n        case (Some t\\<^sub>2''')\n        from Node.hyps (2) [OF Some dist_t2''] \n        have dist_t2''': \"all_distinct t\\<^sub>2'''\" .\n        from Some sub_l_Some del_x_Some sub \n             dist_t2'''\n        show ?thesis\n          by simp\n      next\n        case None\n        with del_x_Some sub_l_Some sub\n        show ?thesis\n          by simp\n      qed\n    next\n      case None\n      with del_x_Some sub \n      show ?thesis\n        by simp\n    qed\n  next\n    case None\n    with sub show ?thesis by simp\n  qed\nqed\n\n\nlemma subtract_Some_dist_res: \n  \"subtract t\\<^sub>1 t\\<^sub>2 = Some t \\<Longrightarrow> set_of t\\<^sub>1 \\<inter> set_of t = {}\"\nproof (induct t\\<^sub>1 arbitrary: t\\<^sub>2 t)\n  case Tip thus ?case by simp\nnext\n  case (Node l x d r)\n  have sub: \"subtract (Node l x d r) t\\<^sub>2 = Some t\" by fact\n  show ?case\n  proof (cases \"delete x t\\<^sub>2\")\n    case (Some t\\<^sub>2')\n    note del_x_Some = this\n    from delete_Some_x_set_of [OF Some]\n    obtain x_t2: \"x \\<in> set_of t\\<^sub>2\" and x_not_t2': \"x \\<notin> set_of t\\<^sub>2'\"\n      by simp\n    from delete_Some_set_of [OF Some]\n    have t2'_t2: \"set_of t\\<^sub>2' \\<subseteq> set_of t\\<^sub>2\" .\n    show ?thesis\n    proof (cases \"subtract l t\\<^sub>2'\")\n      case (Some t\\<^sub>2'')\n      note sub_l_Some = this\n      from Node.hyps (1) [OF Some ] \n      have dist_l_t2'': \"set_of l \\<inter> set_of t\\<^sub>2'' = {}\".\n      from subtract_Some_set_of_res [OF Some]\n      have t2''_t2': \"set_of t\\<^sub>2'' \\<subseteq> set_of t\\<^sub>2'\" .\n      show ?thesis\n      proof (cases \"subtract r t\\<^sub>2''\")\n        case (Some t\\<^sub>2''')\n        from Node.hyps (2) [OF Some] \n        have dist_r_t2''': \"set_of r \\<inter> set_of t\\<^sub>2''' = {}\" .\n        from subtract_Some_set_of_res [OF Some]\n        have t2'''_t2'': \"set_of t\\<^sub>2''' \\<subseteq> set_of t\\<^sub>2''\".\n        \n        from Some sub_l_Some del_x_Some sub t2'''_t2'' dist_l_t2'' dist_r_t2'''\n             t2''_t2' t2'_t2 x_not_t2'\n        show ?thesis\n          by auto\n      next\n        case None\n        with del_x_Some sub_l_Some sub\n        show ?thesis\n          by simp\n      qed\n    next\n      case None\n      with del_x_Some sub \n      show ?thesis\n        by simp\n    qed\n  next\n    case None\n    with sub show ?thesis by simp\n  qed\nqed\n        \nlemma subtract_Some_all_distinct:\n  \"subtract t\\<^sub>1 t\\<^sub>2 = Some t \\<Longrightarrow> all_distinct t\\<^sub>2 \\<Longrightarrow> all_distinct t\\<^sub>1\"\nproof (induct t\\<^sub>1 arbitrary: t\\<^sub>2 t)\n  case Tip thus ?case by simp\nnext\n  case (Node l x d r)\n  have sub: \"subtract (Node l x d r) t\\<^sub>2 = Some t\" by fact\n  have dist_t2: \"all_distinct t\\<^sub>2\" by fact\n  show ?case\n  proof (cases \"delete x t\\<^sub>2\")\n    case (Some t\\<^sub>2')\n    note del_x_Some = this\n    from delete_Some_all_distinct [OF Some dist_t2 ] \n    have dist_t2': \"all_distinct t\\<^sub>2'\" .\n    from delete_Some_set_of [OF Some]\n    have t2'_t2: \"set_of t\\<^sub>2' \\<subseteq> set_of t\\<^sub>2\" .\n    from delete_Some_x_set_of [OF Some]\n    obtain x_t2: \"x \\<in> set_of t\\<^sub>2\" and x_not_t2': \"x \\<notin> set_of t\\<^sub>2'\"\n      by simp\n\n    show ?thesis\n    proof (cases \"subtract l t\\<^sub>2'\")\n      case (Some t\\<^sub>2'')\n      note sub_l_Some = this\n      from Node.hyps (1) [OF Some dist_t2' ] \n      have dist_l: \"all_distinct l\" .\n      from subtract_Some_all_distinct_res [OF Some dist_t2'] \n      have dist_t2'': \"all_distinct t\\<^sub>2''\" .\n      from subtract_Some_set_of [OF Some]\n      have l_t2': \"set_of l \\<subseteq> set_of t\\<^sub>2'\" .\n      from subtract_Some_set_of_res [OF Some]\n      have t2''_t2': \"set_of t\\<^sub>2'' \\<subseteq> set_of t\\<^sub>2'\" .\n      from subtract_Some_dist_res [OF Some]\n      have dist_l_t2'': \"set_of l \\<inter> set_of t\\<^sub>2'' = {}\".\n      show ?thesis\n      proof (cases \"subtract r t\\<^sub>2''\")\n        case (Some t\\<^sub>2''')\n        from Node.hyps (2) [OF Some dist_t2''] \n        have dist_r: \"all_distinct r\" .\n        from subtract_Some_set_of [OF Some]\n        have r_t2'': \"set_of r \\<subseteq> set_of t\\<^sub>2''\" .\n        from subtract_Some_dist_res [OF Some]\n        have dist_r_t2''': \"set_of r \\<inter> set_of t\\<^sub>2''' = {}\".\n\n        from dist_l dist_r Some sub_l_Some del_x_Some r_t2'' l_t2' x_t2 x_not_t2' \n             t2''_t2' dist_l_t2'' dist_r_t2'''\n        show ?thesis\n          by auto\n      next\n        case None\n        with del_x_Some sub_l_Some sub\n        show ?thesis\n          by simp\n      qed\n    next\n      case None\n      with del_x_Some sub \n      show ?thesis\n        by simp\n    qed\n  next\n    case None\n    with sub show ?thesis by simp\n  qed\nqed\n\n\nlemma delete_left:\n  assumes dist: \"all_distinct (Node l y d r)\" \n  assumes del_l: \"delete x l = Some l'\"\n  shows \"delete x (Node l y d r) = Some (Node l' y d r)\"\nproof -\n  from delete_Some_x_set_of [OF del_l]\n  obtain x: \"x \\<in> set_of l\"\n    by simp\n  with dist \n  have \"delete x r = None\"\n    by (cases \"delete x r\") (auto dest:delete_Some_x_set_of)\n\n  with x \n  show ?thesis\n    using del_l dist\n    by (auto split: option.splits)\nqed\n\nlemma delete_right:\n  assumes dist: \"all_distinct (Node l y d r)\" \n  assumes del_r: \"delete x r = Some r'\"\n  shows \"delete x (Node l y d r) = Some (Node l y d r')\"\nproof -\n  from delete_Some_x_set_of [OF del_r]\n  obtain x: \"x \\<in> set_of r\"\n    by simp\n  with dist \n  have \"delete x l = None\"\n    by (cases \"delete x l\") (auto dest:delete_Some_x_set_of)\n\n  with x \n  show ?thesis\n    using del_r dist\n    by (auto split: option.splits)\nqed\n\nlemma delete_root: \n  assumes dist: \"all_distinct (Node l x False r)\" \n  shows \"delete x (Node l x False r) = Some (Node l x True r)\"\nproof -\n  from dist have \"delete x r = None\"\n    by (cases \"delete x r\") (auto dest:delete_Some_x_set_of)\n  moreover\n  from dist have \"delete x l = None\"\n    by (cases \"delete x l\") (auto dest:delete_Some_x_set_of)\n  ultimately show ?thesis\n    using dist\n       by (auto split: option.splits)\nqed               \n\nlemma subtract_Node:\n assumes del: \"delete x t = Some t'\"                                \n assumes sub_l: \"subtract l t' = Some t''\"\n assumes sub_r: \"subtract r t'' = Some t'''\"\n shows \"subtract (Node l x False r) t = Some t'''\"\nusing del sub_l sub_r\nby simp\n\nlemma subtract_Tip: \"subtract Tip t = Some t\"\n  by simp\n \ntext {* Now we have all the theorems in place that are needed for the\ncertificate generating ML functions. *}\n\nML_file \"distinct_tree_prover.ML\"\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/Statespace/DistinctTreeProver.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9005297887874625, "lm_q2_score": 0.8152324938410783, "lm_q1q2_score": 0.7341411454913825}}
{"text": "(* Title: List_Bits.thy\n  Author: Andreas Lochbihler, ETH Zurich *)\n\nsubsection \\<open>Exclusive or on lists\\<close>\n\ntheory List_Bits imports Misc_CryptHOL begin\n\ndefinition xor :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a :: {uminus,inf,sup}\" (infixr \"\\<oplus>\" 67)\nwhere \"x \\<oplus> y = inf (sup x y) (- (inf x y))\"\n\n\n\nlemma xor_commute:\n  fixes x y :: \"'a :: {semilattice_sup,semilattice_inf,uminus}\"\n  shows \"x \\<oplus> y = y \\<oplus> x\"\nby(simp add: xor_def sup.commute inf.commute)\n\nlemma xor_assoc:\n  fixes x y :: \"'a :: boolean_algebra\"\n  shows \"(x \\<oplus> y) \\<oplus> z = x \\<oplus> (y \\<oplus> z)\"\nby(simp add: xor_def inf_sup_aci inf_sup_distrib1 inf_sup_distrib2)\n\nlemma xor_left_commute:\n  fixes x y :: \"'a :: boolean_algebra\"\n  shows \"x \\<oplus> (y \\<oplus> z) = y \\<oplus> (x \\<oplus> z)\"\nby (metis xor_assoc xor_commute)\n\n\n\nlemma xor_inverse [simp]:\n  fixes x :: \"'a :: boolean_algebra\"\n  shows \"x \\<oplus> x = bot\"\nby(simp add: xor_def)\n\nlemma xor_left_inverse [simp]:\n  fixes x :: \"'a :: boolean_algebra\"\n  shows \"x \\<oplus> x \\<oplus> y = y\"\nby(metis xor_left_commute xor_inverse xor_bot)\n\nlemmas xor_ac = xor_assoc xor_commute xor_left_commute\n\n\ndefinition xor_list :: \"'a :: {uminus,inf,sup} list \\<Rightarrow> 'a list \\<Rightarrow> 'a list\"  (infixr \"[\\<oplus>]\" 67)\nwhere \"xor_list xs ys = map (case_prod (\\<oplus>)) (zip xs ys)\"\n\nlemma xor_list_unfold:\n  \"xs [\\<oplus>] ys = (case xs of [] \\<Rightarrow> [] | x # xs' \\<Rightarrow> (case ys of [] \\<Rightarrow> [] | y # ys' \\<Rightarrow> x \\<oplus> y # xs' [\\<oplus>] ys'))\"\nby(simp add: xor_list_def split: list.split)\n\nlemma xor_list_commute: fixes xs ys :: \"'a :: {semilattice_sup,semilattice_inf,uminus} list\"\n  shows \"xs [\\<oplus>] ys = ys [\\<oplus>] xs\"\nunfolding xor_list_def by(subst zip_commute)(auto simp add: split_def xor_commute)\n\nlemma xor_list_assoc [simp]: \n  fixes xs ys :: \"'a :: boolean_algebra list\"\n  shows \"(xs [\\<oplus>] ys) [\\<oplus>] zs = xs [\\<oplus>] (ys [\\<oplus>] zs)\"\nunfolding xor_list_def zip_map1 zip_map2\napply(subst (2) zip_commute)\napply(subst zip_left_commute)\napply(subst (2) zip_commute)\napply(auto simp add: zip_map2 split_def xor_assoc)\ndone\n\nlemma xor_list_left_commute:\n  fixes xs ys zs :: \"'a :: boolean_algebra list\"\n  shows \"xs [\\<oplus>] (ys [\\<oplus>] zs) = ys [\\<oplus>] (xs [\\<oplus>] zs)\"\nby(metis xor_list_assoc xor_list_commute)\n\nlemmas xor_list_ac = xor_list_assoc xor_list_commute xor_list_left_commute\n\nlemma xor_list_inverse [simp]: \n  fixes xs :: \"'a :: boolean_algebra list\"\n  shows \"xs [\\<oplus>] xs = replicate (length xs) bot\"\nby(simp add: xor_list_def zip_same_conv_map o_def map_replicate_const)\n\nlemma xor_replicate_bot_right [simp]:\n  fixes xs :: \"'a :: boolean_algebra list\"\n  shows \"\\<lbrakk> length xs \\<le> n; x = bot \\<rbrakk> \\<Longrightarrow> xs [\\<oplus>] replicate n x = xs\"\nby(simp add: xor_list_def zip_replicate2 o_def)\n\nlemma xor_replicate_bot_left [simp]:\n  fixes xs :: \"'a :: boolean_algebra list\"\n  shows \"\\<lbrakk> length xs \\<le> n; x = bot \\<rbrakk> \\<Longrightarrow> replicate n x [\\<oplus>] xs = xs\"\nby(simp add: xor_list_commute)\n\nlemma xor_list_left_inverse [simp]:\n  fixes xs :: \"'a :: boolean_algebra list\"\n  shows \"length ys \\<le> length xs \\<Longrightarrow> xs [\\<oplus>] (xs [\\<oplus>] ys) = ys\"\nby(subst xor_list_assoc[symmetric])(simp)\n\nlemma length_xor_list [simp]: \"length (xor_list xs ys) = min (length xs) (length ys)\"\nby(simp add: xor_list_def)\n\nlemma inj_on_xor_list_nlists [simp]:\n  fixes xs :: \"'a :: boolean_algebra list\"\n  shows \"n \\<le> length xs \\<Longrightarrow> inj_on (xor_list xs) (nlists UNIV n)\"\napply(clarsimp simp add: inj_on_def in_nlists_UNIV)\nusing xor_list_left_inverse by fastforce\n\nlemma one_time_pad:\n  fixes xs :: \"_ :: boolean_algebra list\"\n  shows \"length xs \\<ge> n \\<Longrightarrow> map_spmf (xor_list xs) (spmf_of_set (nlists UNIV n)) = spmf_of_set (nlists UNIV n)\"\nby(auto 4 3 simp add: in_nlists_UNIV intro: xor_list_left_inverse[symmetric] rev_image_eqI intro!: arg_cong[where f=spmf_of_set])\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/CryptHOL/List_Bits.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314798554445, "lm_q2_score": 0.82893881677331, "lm_q1q2_score": 0.7341343110085677}}
{"text": "(*  Title:       Metric and semimetric spaces\n    Author:      Tim Makarios <tjm1983 at gmail.com>, 2012\n    Maintainer:  Tim Makarios <tjm1983 at gmail.com>\n*)\n\nsection \"Metric and semimetric spaces\"\n\ntheory Metric\nimports \"HOL-Analysis.Multivariate_Analysis\"\nbegin\n\nlocale semimetric =\n  fixes dist :: \"'p \\<Rightarrow> 'p \\<Rightarrow> real\"\n  assumes nonneg [simp]: \"dist x y \\<ge> 0\"\n  and eq_0 [simp]: \"dist x y = 0 \\<longleftrightarrow> x = y\"\n  and symm: \"dist x y = dist y x\"\nbegin\n  lemma refl [simp]: \"dist x x = 0\"\n    by simp\nend\n\nlocale metric =\n  fixes dist :: \"'p \\<Rightarrow> 'p \\<Rightarrow> real\"\n  assumes [simp]: \"dist x y = 0 \\<longleftrightarrow> x = y\"\n  and triangle: \"dist x z \\<le> dist y x + dist y z\"\n\nsublocale metric < semimetric\nproof\n  { fix w\n    have \"dist w w = 0\" by simp }\n  note [simp] = this\n  fix x y\n  show \"0 \\<le> dist x y\"\n  proof -\n    from triangle [of y y x] show \"0 \\<le> dist x y\" by simp\n  qed\n  show \"dist x y = 0 \\<longleftrightarrow> x = y\" by simp\n  show \"dist x y = dist y x\"\n  proof -\n    { fix w z\n      have \"dist w z \\<le> dist z w\"\n      proof -\n        from triangle [of w z z] show \"dist w z \\<le> dist z w\" by simp\n      qed }\n    hence \"dist x y \\<le> dist y x\" and \"dist y x \\<le> dist x y\" by simp+\n    thus \"dist x y = dist y x\" by simp\n  qed\nqed\n\ndefinition norm_dist :: \"('a::real_normed_vector) \\<Rightarrow> 'a \\<Rightarrow> real\" where\n[simp]: \"norm_dist x y \\<equiv> norm (x - y)\"\n\ninterpretation norm_metric: metric norm_dist\nproof\n  fix x y\n  show \"norm_dist x y = 0 \\<longleftrightarrow> x = y\" by simp\n  fix z\n  from norm_triangle_ineq [of \"x - y\" \"y - z\"] have\n    \"norm (x - z) \\<le> norm (x - y) + norm (y - z)\" by simp\n  with norm_minus_commute [of x y] show\n    \"norm_dist x z \\<le> norm_dist y x + norm_dist y z\" 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/Tarskis_Geometry/Metric.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314858927011, "lm_q2_score": 0.8289388019824946, "lm_q1q2_score": 0.7341343029138723}}
{"text": "theory Scratch\n  imports Main\nbegin\n\n(*\n  Add\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\n\n\n\nlemma [simp]: \"add x (Suc y) = Suc (add x y)\"\n  apply(induction x)\n   apply(auto)\n  done\n\nlemma add_commut: \"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\nlemma double_to_add: \"double n = add n n\"\n  apply(induction n)\n  apply(auto)\n  done\n\n(*\n  Count\n*)\n\nfun count :: \"'a \\<Rightarrow> 'a list \\<Rightarrow> nat\" where\n  \"count el [] = 0\" |\n  \"count el (x#xs) = (if el = x then Suc (count el xs) else count el xs)\"\n\nlemma count_le_length: \"count el xs \\<le> length xs\"\n  apply(induction xs)\n   apply(auto)\n  done\n\n(*\n  Snoc\n*)\n\nfun snoc :: \"'a list \\<Rightarrow> 'a \\<Rightarrow> 'a list\" where\n  \"snoc [] el = [el]\" |\n  \"snoc (x#xs) el = x#(snoc xs el)\"\n\nfun reverse :: \"'a list \\<Rightarrow> 'a list\" where\n  \"reverse [] = []\" |\n  \"reverse (x#xs) = snoc (reverse xs) x\"\n\nlemma [simp]: \"reverse (snoc xs el) = el # (reverse xs)\"\n  apply(induction xs)\n   apply(auto)\n  done\n\nlemma reverse_reverse: \"reverse (reverse xs) = xs\"\n  apply(induction xs)\n  apply(auto)\n  done\n\n(*\n  Sum up to\n*)\n\nfun sum_upto :: \"nat \\<Rightarrow> nat\" where\n  \"sum_upto 0 = 0\" |\n  \"sum_upto (Suc n) = add (Suc n) (sum_upto n)\"\n\nlemma [simp]: \"add x y = x + y\"\n  apply(induction x)\n  apply(auto)\n  done\n\nlemma sum_upto_formula: \"sum_upto n = n * (n + 1) div 2\"\n  apply(induction n)\n  apply(auto)\n  done\n\nend", "meta": {"author": "fedurok-learn", "repo": "interactive-theorem-proving", "sha": "b4237a63af8688efabf69931df73b286f0c87f5e", "save_path": "github-repos/isabelle/fedurok-learn-interactive-theorem-proving", "path": "github-repos/isabelle/fedurok-learn-interactive-theorem-proving/interactive-theorem-proving-b4237a63af8688efabf69931df73b286f0c87f5e/isabelle/01_induction/Scratch.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314707995588, "lm_q2_score": 0.8289388104343893, "lm_q1q2_score": 0.7341342978878449}}
{"text": "theory Practical\nimports Main\nbegin\n\nsection \\<open>Part 1\\<close>\n\n(* 1 mark *)\nlemma disjunction_idempotence:\n  \"A \\<or> A \\<longleftrightarrow> A\"\n  apply (rule iffI)\n  apply (erule disjE)\n  apply assumption+\n  apply (rule disjI1)\n  apply assumption\n  done\n\n(* 1 mark *)\nlemma conjunction_idempotence:\n  \"A \\<and> A \\<longleftrightarrow> A\"\n  apply (rule iffI)\n  apply (erule conjE)\n  apply assumption\n  apply (rule conjI)\n  apply assumption+\n  done\n\n(* 1 mark *)\nlemma disjunction_to_conditional:\n  \"(\\<not> P \\<or> R) \\<longrightarrow> (P \\<longrightarrow> R)\"\n  apply (rule impI)+\n  apply (erule disjE)\n  apply (erule notE)\n  apply assumption+ \n  done\n\n(* 1 mark *)\nlemma\n  \"(\\<exists>x. P x \\<and> Q x) \\<longrightarrow> (\\<exists>x. P x) \\<and> (\\<exists>x. Q x)\"\n  apply (rule impI)\n  apply (erule exE)\n  apply (erule conjE)\n  apply (rule conjI)\n  apply (erule exI)+\n  done\n\n(* 1 mark *)\nlemma\n  \"(\\<not> (\\<exists>x. \\<not>P x) \\<or> R) \\<longrightarrow> ((\\<exists>x. \\<not> P x) \\<longrightarrow> R)\"\n  apply (rule impI)+\n  apply (erule disjE)\n  apply (erule notE)\n  apply assumption+\n  done\n\n(* 2 marks *)\nlemma\n  \"(\\<forall>x. P x) \\<longrightarrow> \\<not> (\\<exists>x. \\<not> P x)\"  \n  apply (rule impI)\n \n  apply (rule notI)\n  apply (erule exE)\n  apply (erule notE)\n  apply (erule allE)\n  apply assumption\n  done\n\n(* 3 marks *)\ntext \\<open>Prove using ccontr\\<close>\nlemma excluded_middle:\n  \"P \\<or> \\<not> P\"\n  apply (rule ccontr)\n  apply (rule ccontr)\n  apply (rule_tac P = \"P \\<or> \\<not> P\" in notE)\n  apply assumption\n  apply (rule disjI1)\n  apply (rule ccontr)\n  apply (erule notE)\n  apply (rule disjI2)\n  apply assumption \n  done\n\n(* 3 marks *)\ntext \\<open>Prove using excluded middle\\<close>\nlemma notnotD:\n  \"\\<not>\\<not> P \\<Longrightarrow> P\"\n  apply (cut_tac P = \"P\" in  excluded_middle)\n  apply (erule disjE)\n  apply assumption\n  apply (erule notE)\n  apply assumption\n  done\n\n(* 3 marks *)\ntext \\<open>Prove using double-negation (rule notnotD)\\<close>\nlemma classical:\n  \"(\\<not> P \\<Longrightarrow> P) \\<Longrightarrow> P\"\n  apply (drule impI)\n  apply (rule notnotD)\n  apply (rule notI)\n  apply (erule impE)\n  apply assumption\n  apply (erule notE)\n  apply assumption\n  done\n\n\n(* 3 marks *)\ntext \\<open>Prove using classical\\<close>\nlemma ccontr:\n  \"(\\<not> P \\<Longrightarrow> False) \\<Longrightarrow> P\"\n  apply (drule impI)\n  apply (rule classical)\n  apply (erule impE)\n  apply assumption\n  apply (rule_tac P = \"\\<not> P\" in notE)\n  apply (rule notI)\n  apply assumption+\n  done\n\n(* 3 marks *)\nlemma\n  \"(\\<not> (\\<forall>x. P x \\<or> R x)) = (\\<exists>x. \\<not> P x \\<and> \\<not> R x)\"\n  apply (rule iffI)\n\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 \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\n  apply (erule exE)\n  apply (rule notI)\n  apply (erule allE)\n  apply (erule disjE)\n  apply (erule conjE)\n  apply (erule notE)\n  apply assumption\n  apply (erule conjE)\n  apply (erule notE)\n  apply (erule notE)\n  apply assumption\n  done   \n \n(* 3 marks *)\nlemma\n  \"(\\<exists>x. P x \\<or> R x) = (\\<not>((\\<forall>x. \\<not> P x) \\<and> \\<not> (\\<exists>x. R x)))\"\n  apply (rule iffI)\n  \n  apply (erule exE)\n  apply (rule notI)\n  apply (erule conjE)\n  apply (erule allE)\n  apply (erule disjE)\n  apply (erule notE)\n  apply (erule notE)\n  apply assumption\n  apply (erule notE)\n  apply (rule exI)\n  apply assumption\n\n  apply (rule classical)\n  apply (erule notE)\n  apply (rule conjI)\n  apply (rule allI)\n  apply (rule notI)\n  apply (erule notE)\n  apply (rule exI)\n  apply (rule disjI1)\n  apply assumption\n  apply (rule notI)\n  apply (erule exE)\n  apply (erule notE)\n  apply (rule exI)\n  apply (rule disjI2)\n  apply assumption\n  done\n\nsection \\<open>Part 2.1\\<close>\n\nlocale partof =\n  fixes partof :: \"'region \\<Rightarrow> 'region \\<Rightarrow> bool\" (infix \"\\<sqsubseteq>\" 100)\nbegin\n\n(* 1 mark *)\ndefinition properpartof :: \"'region \\<Rightarrow> 'region \\<Rightarrow> bool\" (infix \"\\<sqsubset>\" 100) where\n  \"x \\<sqsubset> y \\<equiv>  x \\<sqsubseteq> y \\<and> x \\<noteq> y \"\n\n(* 1 mark *)\ndefinition overlaps :: \"'region \\<Rightarrow> 'region \\<Rightarrow> bool\" (infix \"\\<frown>\" 100) where\n  \"x \\<frown> y \\<equiv> \\<exists>z. z \\<sqsubseteq> x \\<and> z \\<sqsubseteq> y\"\n\ndefinition disjoint :: \"'region \\<Rightarrow> 'region \\<Rightarrow> bool\" (infix \"\\<asymp>\" 100) where\n  \"x \\<asymp> y \\<equiv> \\<not> x \\<frown> y\"\n\n(* 1 mark *)\ndefinition partialoverlap :: \"'region \\<Rightarrow> 'region \\<Rightarrow> bool\" (infix \"~\\<frown>\" 100) where\n  \"x ~\\<frown> y \\<equiv> x \\<frown> y \\<and> \\<not>x \\<sqsubseteq> y \\<and> \\<not>y \\<sqsubseteq> x\"\n\n(* 1 mark *)\ndefinition sumregions :: \"'region set \\<Rightarrow> 'region \\<Rightarrow> bool\" (\"\\<Squnion> _ _\" [100, 100] 100) where\n  \"\\<Squnion> \\<alpha> x \\<equiv> (\\<forall>y \\<in> \\<alpha>. y \\<sqsubseteq> x) \\<and> (\\<forall>y. y \\<sqsubseteq> x \\<longrightarrow> (\\<exists>z \\<in> \\<alpha>. y \\<frown> z))\"\n\nend\n\n(* 1+1+1=3 marks *)\nlocale mereology = partof +\n  assumes A1: \"\\<forall>x y z. x\\<sqsubseteq>y \\<and> y\\<sqsubseteq>z \\<longrightarrow> x\\<sqsubseteq>z\"\n      and A2: \"\\<forall>\\<alpha>. \\<alpha> \\<noteq>  {} \\<longrightarrow> (\\<exists>x. \\<Squnion> \\<alpha> x)\"\n      and A2': \"\\<forall>\\<alpha> x y. \\<Squnion> \\<alpha> x \\<and>  \\<Squnion>\\<alpha> y \\<longrightarrow> (x = y)\"\nbegin\n\nsection \\<open>Part 2.2\\<close>\n\n(* 2 marks *)\ntheorem overlaps_sym:\n  \"(x \\<frown> y) = (y \\<frown> x)\"\n   apply (unfold overlaps_def)\n   apply (rule iffI)\n\n   apply (erule exE)+\n   apply (erule conjE)+\n   apply (rule exI)+\n   apply (rule conjI)+\n   apply assumption+\n\n   apply (erule exE)+\n   apply (erule conjE)+\n   apply (rule exI)+\n   apply (rule conjI)+\n   apply assumption+\n\n  done\n\n(* 1 mark *)\ntheorem in_sum_set_partof:\n  \"\\<forall>x. x \\<in> \\<alpha> \\<and>  \\<Squnion> \\<alpha> y \\<longrightarrow>  x \\<sqsubseteq> y\"\nproof-\n  show \"\\<forall>x. x \\<in> \\<alpha> \\<and>  \\<Squnion> \\<alpha> y \\<longrightarrow>  x \\<sqsubseteq> y\" by (simp add: partof.sumregions_def)\nqed\n\n\n(* 3 marks *)\ntheorem overlaps_refl:\n  \"x \\<frown> x\"\nproof- \n  have \"\\<exists>z. \\<Squnion> {x} z\" \n  using A2  by auto\n  then obtain z where \"\\<Squnion> {x} z\" by blast\n  then show \"x \\<frown> x\"\n  using sumregions_def by auto\nqed\n\n(* 1 mark *)\ntheorem all_has_partof:\n    \"\\<forall>x.\\<exists>y. y \\<sqsubseteq> x\"\nproof-\n  show \"\\<forall>x.\\<exists>y. y \\<sqsubseteq> x\" using overlaps_def overlaps_refl by auto\nqed\n\n\n(* 2 marks *)\ntheorem partof_overlaps:\n  assumes \"x \\<sqsubseteq> y\" \n  shows \"x \\<frown> y\"\nproof-\n  obtain p where \"p \\<sqsubseteq> x \\<and> p \\<sqsubseteq> y\"\n  using A1 all_has_partof assms by blast \n  then show \"x \\<frown> y\"\n    using overlaps_def by blast \nqed\n\n\n\n(* 1 mark *)\ntheorem sum_parts_eq:\n  \"\\<Squnion> {a. a \\<sqsubseteq> x} x\"\nproof -\n   show \"\\<Squnion> {a. a \\<sqsubseteq> x} x\" using overlaps_refl sumregions_def by auto\nqed\n\n(* 2 marks *)\ntheorem sum_relation_is_same':\n  assumes \"\\<And>c. r y c \\<Longrightarrow> c \\<sqsubseteq> y\"\n      and \"\\<And>f. y \\<frown> f \\<Longrightarrow> \\<exists>g. r y g \\<and> g \\<frown> f\"\n      and \"\\<Squnion> {y} x\"\n    shows \"\\<Squnion> {k. r y k} x\"\nproof-\n  have \"\\<And>k. r y k \\<Longrightarrow> k \\<sqsubseteq> y\"  by (simp add: assms(1))\n  then have \"y \\<sqsubseteq> x\" using assms(3) in_sum_set_partof  by blast \n  then have a: \"\\<forall>k. r y k \\<longrightarrow> k \\<sqsubseteq> x\" using A1 assms(1) by blast \n  then have b: \"\\<forall>q. q \\<sqsubseteq> x \\<longrightarrow> (\\<exists>z \\<in> {k. r y k}. q \\<frown> z)\"\n  using assms(2) assms(3) overlaps_sym sumregions_def by auto\n  from a and b show \"\\<Squnion> {k. r y k} x\"\n  using sumregions_def by auto  \nqed\n   \n  \n(* 1 mark *)\ntheorem overlap_has_partof_overlap:\n  assumes a: \"e \\<frown> f\"\n  shows \"\\<exists>g. g \\<sqsubseteq> e \\<and> g \\<frown> f\"\nproof-\n  from a have b :  \"\\<exists>g. g \\<sqsubseteq> e \\<and> g \\<sqsubseteq> f\" using overlaps_def by blast\n  from b show \"\\<exists>g. g \\<sqsubseteq> e \\<and> g \\<frown> f\"   using partof_overlaps by blast\nqed\n  \n\n(* 1 marks *)\ntheorem sum_parts_of_one_eq:\n  assumes \"\\<Squnion> {y} x\"\n  shows \"\\<Squnion> {k. k\\<sqsubseteq>y} x\"\nproof-\n  note sum_relation_is_same' [where r = \"\\<lambda>y k. k \\<sqsubseteq> y\"]\n  show ?thesis\n    using assms sum_relation_is_same' overlap_has_partof_overlap by fastforce\nqed\n\n(* 5 marks *)\ntheorem both_partof_eq:\n  assumes \"x \\<sqsubseteq> y \\<and> y \\<sqsubseteq> x\"\n  shows \"x = y\"\nproof-\n  have \"\\<Squnion> {k. k \\<sqsubseteq> x} y\" \n  proof (rule ccontr)\n    assume \"\\<not> \\<Squnion> {k. k \\<sqsubseteq> x} y\"\n    then have \" (\\<exists>p. p \\<sqsubseteq> x \\<and> \\<not>(p \\<sqsubseteq> y)) \\<or> (\\<exists>w. w \\<sqsubseteq> y \\<and> (\\<forall>p. p \\<sqsubseteq> x \\<longrightarrow> w \\<asymp> p))\"\n      using assms partof_overlaps sumregions_def by auto\n     then show \"False\" \n    proof \n      assume a1: \" (\\<exists>p. p \\<sqsubseteq> x \\<and> \\<not>(p \\<sqsubseteq> y))\"\n      then  show \"False\"\n      using A1 assms by blast \n    next\n      assume a: \"\\<exists>w. w \\<sqsubseteq> y \\<and> (\\<forall>p. p \\<sqsubseteq> x \\<longrightarrow> w \\<asymp> p)\"\n      obtain w where b : \"w \\<sqsubseteq> y \\<and> (\\<forall>z. z \\<sqsubseteq> x \\<longrightarrow> w \\<asymp> z)\"\n        using a by auto\n       have c:\" y \\<sqsubseteq> x \"\n         by (simp add: assms)\n       then have \" y \\<asymp> w\"\n         using b disjoint_def partof_overlaps by blast\n      then show \"False\"\n        by (simp add: b disjoint_def overlaps_sym partof_overlaps)\n    qed\n  qed\n  then show  \"x = y\"\n    using A2' sum_parts_eq by blast \nqed\n\n(* 4 marks *)\ntheorem sum_all_with_parts_overlapping:\n  assumes \"\\<Squnion> {z. \\<forall>a. a \\<sqsubseteq> z \\<longrightarrow> a \\<frown> y} x\"\n  shows \"\\<Squnion> {y} x\"\nproof-\n  show  \"\\<Squnion> {y} x\"\n  proof (rule ccontr)\n   assume \"\\<not> \\<Squnion> {y} x\"\n   then have \"\\<not>(y \\<sqsubseteq> x) \\<or> (\\<exists>w. w \\<sqsubseteq> x \\<and> w \\<asymp> y) \"\n   by (simp add: disjoint_def partof.sumregions_def)\n   then show \"False\" \n   proof \n     assume a: \"\\<not>(y \\<sqsubseteq> x)\"\n     then have b: \" y \\<in> {k .k\\<frown>y} \"\n       by (simp add: overlaps_refl)\n     have \"y \\<sqsubseteq> x\"\n       using assms partof_overlaps sumregions_def by auto \n     then show \"False\"\n       using a by blast\n   next\n     assume a: \"\\<exists>w. w \\<sqsubseteq> x \\<and> w \\<asymp> y\" \n     obtain w where b:\"w \\<sqsubseteq> x \\<and> w \\<asymp> y\"\n       using a by blast \n     obtain a where c: \"a \\<in> {z. \\<forall>p. p \\<sqsubseteq> z \\<longrightarrow> p\\<frown>y} \\<and> w \\<frown> a\"\n       using assms b sumregions_def by auto\n     obtain wz where d :\"wz \\<sqsubseteq> w \\<and> wz \\<sqsubseteq> a\"\n       using c overlaps_def by auto \n     have 0 : \"wz \\<frown> y\"  \n       using c d by blast \n     obtain wzy where 1:\"wzy \\<sqsubseteq> wz \\<and> wzy \\<sqsubseteq> y\"\n       using \"0\" overlaps_def by blast\n     have \"wzy \\<sqsubseteq> w\"\n       using \"1\" A1 d by blast  \n     then have \"w \\<frown> y\"\n       using \"0\" A1 d overlaps_def by blast    \n      then show \"False\"\n        using b disjoint_def by blast  \n    qed\n  qed\nqed\n\n(* 2 marks *)\ntheorem sum_one_is_self:\n  \"\\<Squnion> {x} x\"\nproof-\n  obtain y where a: \"\\<Squnion> {x} y \"\n    using A2 by blast\n  then have b: \"\\<Squnion> {a. a \\<sqsubseteq> x} y\"\n    using sum_parts_of_one_eq by blast\n  have c : \"\\<Squnion> {a. a \\<sqsubseteq> x} x\"\n    by (simp add: sum_parts_eq) \n  from b and c have \"x = y\"\n    using A2' by blast\n  then show ?thesis\n    using a by blast \nqed\n\n(* 2 marks *)\ntheorem sum_all_with_parts_overlapping_self:\n  \"\\<Squnion> {z. \\<forall>a. a \\<sqsubseteq> z \\<longrightarrow> a \\<frown> x} x\"\nproof-\n  have \"{z. \\<forall>a. a \\<sqsubseteq> z \\<longrightarrow> a \\<frown> x} \\<noteq> {}\" using partof_overlaps by force \n  then have \"\\<exists>y. \\<Squnion> {z. \\<forall>a. a \\<sqsubseteq> z \\<longrightarrow> a \\<frown> x} y\"\n    by (simp add: A2)\n  then obtain y where a:\"\\<Squnion> {z. \\<forall>a. a \\<sqsubseteq> z \\<longrightarrow> a \\<frown> x} y\"\n    by blast\n  then have b: \"x = y\"\n    using A2' sum_all_with_parts_overlapping sum_one_is_self by blast\n  then show ?thesis\n  proof -\n    show ?thesis\n      using a b by blast\n  qed\nqed\n(* 4 marks *)\ntheorem proper_have_nonoverlapping_proper:\n  assumes \"s \\<sqsubset> r \"\n  shows \"\\<exists>a. a \\<sqsubset> r \\<and> a \\<asymp> s\"\nproof(rule ccontr)\n  assume 0 :\"\\<nexists>a. a \\<sqsubset>r \\<and> a \\<asymp> s\"\n  then show \"False\"\n  proof-\n    have \"\\<forall>a. a \\<sqsubset> r \\<longrightarrow> a \\<frown> s\"\n      using 0 disjoint_def by blast\n    then have 1: \"\\<forall>a. a \\<sqsubseteq> r \\<longrightarrow> a \\<frown> s\"\n      using assms overlaps_sym partof_overlaps properpartof_def by blast \n    have \"\\<Squnion> {r. \\<forall>a. a \\<sqsubseteq> r \\<longrightarrow> a \\<frown> s} s\"\n      using sum_all_with_parts_overlapping_self by blast \n    then have 2 :\"r \\<sqsubseteq> s\"\n      by (simp add: \"1\" partof.sumregions_def) \n    have 3: \"s \\<sqsubseteq> r\"\n      using assms properpartof_def by blast \n    from 2 and 3 have \"s = r\"\n      by (simp add: both_partof_eq) \n    then show \"False\"\n      using assms properpartof_def by blast   \n  qed\nqed\n\n(* 1 mark *)\nsublocale parthood_partial_order: order \"(\\<sqsubseteq>)\" \"(\\<sqsubset>)\"\nproof\n  show \"\\<And>x y. x \\<sqsubset> y = (x \\<sqsubseteq> y \\<and> \\<not> y \\<sqsubseteq> x)\"\n    using both_partof_eq properpartof_def by auto\nnext\n  show \"\\<And>x. x \\<sqsubseteq> x\"\n    using in_sum_set_partof sum_one_is_self by auto    \nnext\n  show \"\\<And>x y z. \\<lbrakk>x \\<sqsubseteq> y; y \\<sqsubseteq> z\\<rbrakk> \\<Longrightarrow> x \\<sqsubseteq> z\"\n    using A1 by blast\nnext\n  show \"\\<And>x y. \\<lbrakk>x \\<sqsubseteq> y; y \\<sqsubseteq> x\\<rbrakk> \\<Longrightarrow> x = y\"\n    by (simp add: both_partof_eq)    \nqed\n\nend\n\nsection \\<open>Part 2.3\\<close>\n\nlocale sphere =\n  fixes sphere :: \"'a \\<Rightarrow> bool\"\nbegin\n\nabbreviation AllSpheres :: \"('a \\<Rightarrow> bool) \\<Rightarrow> bool\" (binder \"\\<forall>\\<degree>\" 10) where\n  \"\\<forall>\\<degree>x. P x \\<equiv> \\<forall>x. sphere x \\<longrightarrow> P x\"\n\nabbreviation ExSpheres :: \"('a \\<Rightarrow> bool) \\<Rightarrow> bool\" (binder \"\\<exists>\\<degree>\" 10) where\n  \"\\<exists>\\<degree>x. P x \\<equiv> \\<exists>x. sphere x \\<and> P x\"\n\nend\n\nlocale mereology_sphere = mereology partof + sphere sphere\n  for partof :: \"'region \\<Rightarrow> 'region \\<Rightarrow> bool\" (infix \"\\<sqsubseteq>\" 100)\n  and sphere :: \"'region \\<Rightarrow> bool\"\nbegin\n\ndefinition exttan :: \"'region \\<Rightarrow> 'region \\<Rightarrow> bool\" where\n  \"exttan a b \\<equiv> sphere a \\<and> sphere b \\<and> a \\<asymp> b \\<and> (\\<forall>\\<degree>x y. a \\<sqsubseteq> x \\<and> a \\<sqsubseteq> y \\<and> b \\<asymp> x \\<and> b \\<asymp> y\n                                                        \\<longrightarrow> x \\<sqsubseteq> y \\<or> y \\<sqsubseteq> x)\"\n\ndefinition inttan :: \"'region \\<Rightarrow> 'region \\<Rightarrow> bool\" where\n  \"inttan a b \\<equiv> sphere a \\<and> sphere b \\<and> a \\<sqsubset> b \\<and> (\\<forall>\\<degree>x y. a \\<sqsubseteq> x \\<and> a \\<sqsubseteq> y \\<and> x \\<sqsubseteq> b \\<and> y \\<sqsubseteq> b\n                                                        \\<longrightarrow> x \\<sqsubseteq> y \\<or> y \\<sqsubseteq> x)\"\n\ndefinition extdiam :: \"'region \\<Rightarrow> 'region \\<Rightarrow> 'region \\<Rightarrow> bool\" where\n  \"extdiam a b c \\<equiv> exttan a c \\<and> exttan b c\n                 \\<and> (\\<forall>\\<degree>x y. x \\<asymp> c \\<and> y \\<asymp> c \\<and> a \\<sqsubseteq> x \\<and> b \\<sqsubseteq> y \\<longrightarrow> x \\<asymp> y)\"\n\ndefinition intdiam :: \"'region \\<Rightarrow> 'region \\<Rightarrow> 'region \\<Rightarrow> bool\" where\n  \"intdiam a b c \\<equiv> inttan a c \\<and> inttan b c\n                 \\<and> (\\<forall>\\<degree>x y. x \\<asymp> c \\<and> y \\<asymp> c \\<and> exttan a x \\<and> exttan b y \\<longrightarrow> x \\<asymp> y)\"\n\nabbreviation properconcentric :: \"'region \\<Rightarrow> 'region \\<Rightarrow> bool\" where\n  \"properconcentric a b \\<equiv> a \\<sqsubset> b\n                        \\<and> (\\<forall>\\<degree>x y. extdiam x y a \\<and> inttan x b \\<and> inttan y b \\<longrightarrow> intdiam x y b)\"\n\ndefinition concentric :: \"'region \\<Rightarrow> 'region \\<Rightarrow> bool\" (infix \"\\<odot>\" 100) where\n  \"a \\<odot> b \\<equiv> sphere a \\<and> sphere b \\<and> (a = b \\<or> properconcentric a b \\<or> properconcentric b a)\"\n\ndefinition onboundary :: \"'region \\<Rightarrow> 'region \\<Rightarrow> bool\" where\n  \"onboundary s r \\<equiv> sphere s \\<and> (\\<forall>s'. s' \\<odot> s \\<longrightarrow> s' \\<frown> r \\<and> \\<not> s' \\<sqsubseteq> r)\"\n\ndefinition equidistant3 :: \"'region \\<Rightarrow> 'region \\<Rightarrow> 'region \\<Rightarrow> bool\" where\n  \"equidistant3 x y z \\<equiv> \\<exists>\\<degree>z'. z' \\<odot> z \\<and> onboundary y z' \\<and> onboundary x z'\"\n\ndefinition betw :: \"'region \\<Rightarrow> 'region \\<Rightarrow> 'region \\<Rightarrow> bool\" (\"[_ _ _]\" [100, 100, 100] 100) where\n  \"[x y z] \\<equiv> sphere x \\<and> sphere z\n             \\<and> (x \\<odot> y \\<or> y \\<odot> z\n                \\<or> (\\<exists>x' y' z' v w. x' \\<odot> x \\<and> y' \\<odot> y \\<and> z' \\<odot> z\n                                  \\<and> extdiam x' y' v \\<and> extdiam v w y' \\<and> extdiam y' z' w))\"\n\ndefinition mid :: \"'region \\<Rightarrow> 'region \\<Rightarrow> 'region \\<Rightarrow> bool\" where\n  \"mid x y z \\<equiv> [x y z] \\<and> (\\<exists>\\<degree>y'. y' \\<odot> y \\<and> onboundary x y' \\<and> onboundary z y')\"\n\ndefinition equidistant4 :: \"'region \\<Rightarrow> 'region \\<Rightarrow> 'region \\<Rightarrow> 'region \\<Rightarrow> bool\" (\"_ _ \\<doteq> _ _\" [100, 100, 100, 100] 100) where\n  \"x y \\<doteq> z w \\<equiv> \\<exists>\\<degree>u v. mid w u y \\<and> mid x u v \\<and> equidistant3 v z y\"\n\ndefinition oninterior :: \"'region \\<Rightarrow> 'region \\<Rightarrow> bool\" where\n  \"oninterior s r \\<equiv> \\<exists>s'. s' \\<odot> s \\<and> s' \\<sqsubseteq> r\"\n\ndefinition nearer :: \"'region \\<Rightarrow> 'region \\<Rightarrow> 'region \\<Rightarrow> 'region \\<Rightarrow> bool\" where\n  \"nearer w x y z \\<equiv> \\<exists>\\<degree>x'. [w x x'] \\<and> \\<not> x \\<odot> x' \\<and> w x' \\<doteq> y z\"\n\nend\n\nlocale partial_region_geometry = mereology_sphere partof sphere\n  for partof :: \"'region \\<Rightarrow> 'region \\<Rightarrow> bool\" (infix \"\\<sqsubseteq>\" 100)\n  and sphere :: \"'region \\<Rightarrow> bool\" +\n  assumes A4: \"\\<lbrakk>x \\<odot> y; y \\<odot> z\\<rbrakk> \\<Longrightarrow> x \\<odot> z\"\n      and A5: \"\\<lbrakk>x y \\<doteq> z w; x' \\<odot> x\\<rbrakk> \\<Longrightarrow> x' y \\<doteq> z w\"\n      and A6: \"\\<lbrakk>sphere x; sphere y; \\<not> x \\<odot> y\\<rbrakk>\n               \\<Longrightarrow> \\<exists>\\<degree>s. \\<forall>\\<degree>z. oninterior z s = nearer x z x y\"\n      and A7: \"sphere x \\<Longrightarrow> \\<exists>\\<degree>y. \\<not> x \\<odot> y \\<and> (\\<forall>\\<degree>z. oninterior z x = nearer x z x y)\"\n      and A8: \"x \\<sqsubseteq> y = (\\<forall>s. oninterior s x \\<longrightarrow> oninterior s y)\"\n      and A9: \"\\<exists>\\<degree>s. s \\<sqsubseteq> r\"\nbegin\n\n(* 2 marks *)\nthm equiv_def\ntheorem conc_equiv:\n  \"equiv {A. sphere A} {(x,y). x \\<odot> y}\"\nproof- \n  have \"\\<forall>x\\<in>{A. sphere A}. x \\<odot> x\"\n    using concentric_def by auto \n  then have a:\"refl_on {A. sphere A}{(x,y). x \\<odot> y}\"\n    by (simp add: concentric_def refl_on_def')\n  have \"\\<forall> y\\<in>{A. sphere A}. x \\<odot> y \\<longrightarrow> y \\<odot> x \"\n    using concentric_def by auto\n  have b: \"sym {(x,y). x \\<odot> y}\"\n    using concentric_def sym_def by fastforce\n  have \"\\<forall> z\\<in>{A. sphere A}. (x \\<odot> y \\<and> y \\<odot> z) \\<longrightarrow> x \\<odot> z\"\n    using A4 by blast\n  have c:\"trans {(x,y). x \\<odot> y}\"\n    using concentric_def Relation.transp_trans A4 transp_def by blast \n  from a and b and c show ?thesis\n    using equiv_def by blast\nqed\n\n(* 6 marks *)\ntheorem region_is_spherical_sum:\n  \"\\<Squnion> {A. sphere A \\<and> A \\<sqsubseteq> x} x\"\nproof-\n    have a: \"\\<exists>a. \\<Squnion>{A. sphere A \\<and> A \\<sqsubseteq> x} a\" using A2 A9 by simp\n    then obtain a where a: \"\\<Squnion>{A. sphere A \\<and> A \\<sqsubseteq> x} a\" by blast\n    show ?thesis\nproof (rule ccontr)\n  assume b: \"\\<not>\\<Squnion> {A. sphere A \\<and> A \\<sqsubseteq> x} x \"\n  show \"False\"\n  proof-\n   have c: \"(\\<forall>s. oninterior s x \\<longrightarrow> oninterior s a)\"\n     using a concentric_def oninterior_def sumregions_def by auto\n    then have d: \"\\<forall>s.(oninterior s a \\<longleftrightarrow> oninterior s x)\"\n      using A8 a b sumregions_def by auto\n    then have e:\" \\<forall>s.(oninterior s a \\<longrightarrow> oninterior s x)\"\n      by simp\n\n    then have 0: \"x \\<sqsubseteq> a\"\n      using A8 c by blast \n    then have 1:\"a \\<sqsubseteq> x\"\n      using A8 d by blast\n    from 0 and 1 have \"a = x\"\n      by auto\n    then show ?thesis\n      using a b by blast\n  qed\n qed\nqed\n       \n(* 1 mark *)\ntheorem region_spherical_interior:\n  \" sphere s \\<and> oninterior s r \\<longleftrightarrow> (\\<exists>s'. sphere s' \\<and> s' \\<sqsubseteq> r \\<and> oninterior s s')\"\nproof- \n  have \"sphere s \\<and>oninterior s r \\<longleftrightarrow> (\\<exists>a. a \\<sqsubseteq> r \\<and> oninterior s a)\"\n    using concentric_def oninterior_def by auto\n  then obtain a where \"\\<exists>s. sphere s \\<and> oninterior s r \\<longleftrightarrow> (a \\<sqsubseteq> r \\<and> oninterior s a)\"\n    by auto\n  then have \"\\<exists>\\<degree>s'. s' \\<sqsubseteq> a\"\n    by (simp add: A9) \n  show ?thesis\n    using concentric_def oninterior_def by auto\nqed\n\n(* 2 marks *)\n(*as we assume x and y have equal interiors, so according to A8, we could get x is part of y \n  and y is part of x, so use both_partof_eq leamma, we could know x=y. *)\ntheorem equal_interiors_equal_regions:\n  assumes \"\\<forall>s. oninterior s x = oninterior s y \"\n  shows \"x = y\"\nproof- \n  show ?thesis\n    by (simp add: A8 assms both_partof_eq)\nqed\n\n(* 2 marks *)\ntheorem proper_have_nonoverlapping_proper_sphere:\n  assumes \"s \\<sqsubset> r\"\n  shows \"\\<exists>\\<degree>a. a \\<sqsubset> r \\<and> a \\<asymp> s\"\nproof-\n  have \"\\<exists>k.  k \\<sqsubset> r \\<and> k \\<asymp> s\"\n    using assms proper_have_nonoverlapping_proper by blast\n  then obtain k where 0:\" k \\<sqsubset> r \\<and> k \\<asymp> s\" by blast\n  then have 1: \"\\<exists>\\<degree>a. a \\<sqsubseteq> k\"\n    by (simp add: A9)\n  then obtain a where \"a \\<sqsubseteq> k\"\n    by blast\n  then show \"\\<exists>\\<degree>a. a \\<sqsubset> r \\<and> a \\<asymp> s\"\n    using \"0\" \"1\" disjoint_def overlaps_def by auto\n  qed\n\n\n(* 4 marks *)\ntheorem not_sphere_spherical_parts_gt1:\n  assumes \"\\<not>sphere x\"\n      and \"sphere s \\<and>  s \\<sqsubseteq> x\"\n    shows \"\\<exists>\\<degree>a. a \\<sqsubset> x \\<and> a \\<asymp> s\"\nproof-\n  have 1:\"s \\<sqsubset> x\"\n  using assms(1) assms(2) parthood_partial_order.le_imp_less_or_eq by blast\n  obtain s where \"sphere s \\<and>  s \\<sqsubset> x\"\n    using \"1\" assms(2) by blast \n  then have \"s \\<sqsubset> x\"\n    by blast\n  then show ?thesis\n    using \"1\" proper_have_nonoverlapping_proper_sphere by blast \nqed\n\nend\n\nsection \\<open>Part 3\\<close>\n\ncontext mereology_sphere\nbegin\n\n(* 3 marks *)\nlemma\n  assumes T4: \"\\<And>x y. \\<lbrakk>sphere x; sphere y\\<rbrakk> \\<Longrightarrow> x y \\<doteq> y x\"\n      and A9: \"\\<exists>\\<degree>s. s \\<sqsubseteq> r\"\n  shows False\noops\n\n(* 3 marks *)\ndefinition equidistant3' :: \"'region \\<Rightarrow> 'region \\<Rightarrow> 'region \\<Rightarrow> bool\" where\n  \"equidistant3' x y z \\<equiv> undefined\"\n\nno_notation equidistant4 (\"_ _ \\<doteq> _ _\" [100, 100, 100, 100] 100)\n\ndefinition equidistant4' :: \"'region \\<Rightarrow> 'region \\<Rightarrow> 'region \\<Rightarrow> 'region \\<Rightarrow> bool\" (\"_ _ \\<doteq> _ _\" [100, 100, 100, 100] 100) where\n  \"x y \\<doteq> z w \\<equiv> \\<exists>\\<degree>u v. mid w u y \\<and> mid x u v \\<and> equidistant3' v z y\"\n\nend\n\ndatatype two_reg = Left | Right | Both\n\n(* 2 marks *)\ndefinition tworeg_partof :: \"two_reg \\<Rightarrow> two_reg \\<Rightarrow> bool\" (infix \"\\<sqsubseteq>\" 100) where\n  \"x \\<sqsubseteq> y \\<equiv> undefined\"\n\n(* 12 marks *)\ninterpretation mereology \"(\\<sqsubseteq>)\"\noops\n\n\nend", "meta": {"author": "JeffreyZhang1117", "repo": "ARCW", "sha": "c7c3d4246f68623e78df9b47ef75e3bbed49f343", "save_path": "github-repos/isabelle/JeffreyZhang1117-ARCW", "path": "github-repos/isabelle/JeffreyZhang1117-ARCW/ARCW-c7c3d4246f68623e78df9b47ef75e3bbed49f343/Practical.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637612961506, "lm_q2_score": 0.8539127492339909, "lm_q1q2_score": 0.7340778458252293}}
{"text": "(*  Title:      HOL/Multivariate_Analysis/L2_Norm.thy\n    Author:     Brian Huffman, Portland State University\n*)\n\nsection {* Square root of sum of squares *}\n\ntheory L2_Norm\nimports NthRoot\nbegin\n\ndefinition\n  \"setL2 f A = sqrt (\\<Sum>i\\<in>A. (f i)\\<^sup>2)\"\n\nlemma setL2_cong:\n  \"\\<lbrakk>A = B; \\<And>x. x \\<in> B \\<Longrightarrow> f x = g x\\<rbrakk> \\<Longrightarrow> setL2 f A = setL2 g B\"\n  unfolding setL2_def by simp\n\nlemma strong_setL2_cong:\n  \"\\<lbrakk>A = B; \\<And>x. x \\<in> B =simp=> f x = g x\\<rbrakk> \\<Longrightarrow> setL2 f A = setL2 g B\"\n  unfolding setL2_def simp_implies_def by simp\n\nlemma setL2_infinite [simp]: \"\\<not> finite A \\<Longrightarrow> setL2 f A = 0\"\n  unfolding setL2_def by simp\n\nlemma setL2_empty [simp]: \"setL2 f {} = 0\"\n  unfolding setL2_def by simp\n\nlemma setL2_insert [simp]:\n  \"\\<lbrakk>finite F; a \\<notin> F\\<rbrakk> \\<Longrightarrow>\n    setL2 f (insert a F) = sqrt ((f a)\\<^sup>2 + (setL2 f F)\\<^sup>2)\"\n  unfolding setL2_def by (simp add: setsum_nonneg)\n\nlemma setL2_nonneg [simp]: \"0 \\<le> setL2 f A\"\n  unfolding setL2_def by (simp add: setsum_nonneg)\n\nlemma setL2_0': \"\\<forall>a\\<in>A. f a = 0 \\<Longrightarrow> setL2 f A = 0\"\n  unfolding setL2_def by simp\n\nlemma setL2_constant: \"setL2 (\\<lambda>x. y) A = sqrt (of_nat (card A)) * \\<bar>y\\<bar>\"\n  unfolding setL2_def by (simp add: real_sqrt_mult)\n\nlemma setL2_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 \"setL2 f K \\<le> setL2 g K\"\n  unfolding setL2_def\n  by (simp add: setsum_nonneg setsum_mono power_mono assms)\n\nlemma setL2_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 \"setL2 f K < setL2 g K\"\n  unfolding setL2_def\n  by (simp add: setsum_strict_mono power_strict_mono assms)\n\nlemma setL2_right_distrib:\n  \"0 \\<le> r \\<Longrightarrow> r * setL2 f A = setL2 (\\<lambda>x. r * f x) A\"\n  unfolding setL2_def\n  apply (simp add: power_mult_distrib)\n  apply (simp add: setsum_right_distrib [symmetric])\n  apply (simp add: real_sqrt_mult setsum_nonneg)\n  done\n\nlemma setL2_left_distrib:\n  \"0 \\<le> r \\<Longrightarrow> setL2 f A * r = setL2 (\\<lambda>x. f x * r) A\"\n  unfolding setL2_def\n  apply (simp add: power_mult_distrib)\n  apply (simp add: setsum_left_distrib [symmetric])\n  apply (simp add: real_sqrt_mult setsum_nonneg)\n  done\n\nlemma setsum_nonneg_eq_0_iff:\n  fixes f :: \"'a \\<Rightarrow> 'b::ordered_ab_group_add\"\n  shows \"\\<lbrakk>finite A; \\<forall>x\\<in>A. 0 \\<le> f x\\<rbrakk> \\<Longrightarrow> setsum f A = 0 \\<longleftrightarrow> (\\<forall>x\\<in>A. f x = 0)\"\n  apply (induct set: finite, simp)\n  apply (simp add: add_nonneg_eq_0_iff setsum_nonneg)\n  done\n\nlemma setL2_eq_0_iff: \"finite A \\<Longrightarrow> setL2 f A = 0 \\<longleftrightarrow> (\\<forall>x\\<in>A. f x = 0)\"\n  unfolding setL2_def\n  by (simp add: setsum_nonneg setsum_nonneg_eq_0_iff)\n\nlemma setL2_triangle_ineq:\n  shows \"setL2 (\\<lambda>i. f i + g i) A \\<le> setL2 f A + setL2 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 + (setL2 (\\<lambda>i. f i + g i) F)\\<^sup>2) \\<le>\n           sqrt ((f x + g x)\\<^sup>2 + (setL2 f F + setL2 g F)\\<^sup>2)\"\n      by (intro real_sqrt_le_mono add_left_mono power_mono insert\n                setL2_nonneg add_increasing zero_le_power2)\n    also have\n      \"\\<dots> \\<le> sqrt ((f x)\\<^sup>2 + (setL2 f F)\\<^sup>2) + sqrt ((g x)\\<^sup>2 + (setL2 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 sqrt_sum_squares_le_sum:\n  \"\\<lbrakk>0 \\<le> x; 0 \\<le> y\\<rbrakk> \\<Longrightarrow> sqrt (x\\<^sup>2 + y\\<^sup>2) \\<le> x + y\"\n  apply (rule power2_le_imp_le)\n  apply (simp add: power2_sum)\n  apply simp\n  done\n\nlemma setL2_le_setsum [rule_format]:\n  \"(\\<forall>i\\<in>A. 0 \\<le> f i) \\<longrightarrow> setL2 f A \\<le> setsum 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 sqrt_sum_squares_le_sum_abs: \"sqrt (x\\<^sup>2 + y\\<^sup>2) \\<le> \\<bar>x\\<bar> + \\<bar>y\\<bar>\"\n  apply (rule power2_le_imp_le)\n  apply (simp add: power2_sum)\n  apply simp\n  done\n\nlemma setL2_le_setsum_abs: \"setL2 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 setL2_mult_ineq_lemma:\n  fixes a b c d :: real\n  shows \"2 * (a * c) * (b * d) \\<le> a\\<^sup>2 * d\\<^sup>2 + b\\<^sup>2 * c\\<^sup>2\"\nproof -\n  have \"0 \\<le> (a * d - b * c)\\<^sup>2\" by simp\n  also have \"\\<dots> = a\\<^sup>2 * d\\<^sup>2 + b\\<^sup>2 * c\\<^sup>2 - 2 * (a * d) * (b * c)\"\n    by (simp only: power2_diff power_mult_distrib)\n  also have \"\\<dots> = a\\<^sup>2 * d\\<^sup>2 + b\\<^sup>2 * c\\<^sup>2 - 2 * (a * c) * (b * d)\"\n    by simp\n  finally show \"2 * (a * c) * (b * d) \\<le> a\\<^sup>2 * d\\<^sup>2 + b\\<^sup>2 * c\\<^sup>2\"\n    by simp\nqed\n\nlemma setL2_mult_ineq: \"(\\<Sum>i\\<in>A. \\<bar>f i\\<bar> * \\<bar>g i\\<bar>) \\<le> setL2 f A * setL2 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: setsum_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 setL2_mult_ineq_lemma)\n  apply simp_all\n  done\n\nlemma member_le_setL2: \"\\<lbrakk>finite A; i \\<in> A\\<rbrakk> \\<Longrightarrow> f i \\<le> setL2 f A\"\n  apply (rule_tac s=\"insert i (A - {i})\" and t=\"A\" in subst)\n  apply fast\n  apply (subst setL2_insert)\n  apply simp\n  apply simp\n  apply simp\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/HOL/Multivariate_Analysis/L2_Norm.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127492339909, "lm_q2_score": 0.8596637541053281, "lm_q1q2_score": 0.7340778396848943}}
{"text": "theory Peano\n  imports Main\nbegin\n\nsection \\<open>Natural Numbers\\<close>\n\ndatatype nat = Zero | Suc nat\n\nfun add :: \"nat => nat => nat\" where\n  \"add Zero m = m\" |\n  \"add (Suc n) m = Suc (add n m)\"\n\nlemma neutral[simp]: \"add m Zero = m\"\n  apply (induction m)\n  apply auto\n  done\n\nlemma suc_commutation[simp]: \"add m (Suc n) = Suc (add m n)\"\n  apply (induction m)\n   apply auto\n  done\n\nlemma commutation[simp]: \"add m n = add n m\"\n  apply (induction m)\n   apply auto\n  done\n\nlemma preassociation: \"nat.Suc (add n (add k m)) = add n (add m (nat.Suc k))\"\n  apply (induction n)\n   apply auto\n  done\n\nlemma association[simp]: \"add k (add m n) = add (add k m) n\"\n  apply (induction k)\n   apply (auto simp:preassociation)\n  done\n\nfun double :: \"nat \\<Rightarrow> nat\" where\n  \"double Zero = Zero\" |\n  \"double (Suc n) = add (double n) (Suc (Suc Zero))\"\n\nlemma double_def: \"double n = add n n\"\n  apply (induction n)\n  apply auto\n\nend \n", "meta": {"author": "Darkneew", "repo": "Peano", "sha": "eba1a2c9d04112104bafc7273e5f8dea7b2e5285", "save_path": "github-repos/isabelle/Darkneew-Peano", "path": "github-repos/isabelle/Darkneew-Peano/Peano-eba1a2c9d04112104bafc7273e5f8dea7b2e5285/Peano.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9111797124237605, "lm_q2_score": 0.8056321889812553, "lm_q1q2_score": 0.7340757062752649}}
{"text": "theory Multiplicity\n  imports Main\nbegin\n\nsection \"Linear order of \\<M>, which is the set of natural numbers \\<union> {\\<star>}\"\n\ndatatype \\<M> = Star | Nr nat\n\nnotation\n  Star (\"(\\<^emph>)\" 1000) and\n  Nr (\"(\\<^bold>_)\" [1000] 1000)\n\ninstantiation \\<M> :: linorder\nbegin\n\nfun less_eq_\\<M> :: \"\\<M> \\<Rightarrow> \\<M> \\<Rightarrow> bool\" where\n\"less_eq_\\<M> _ \\<^emph> = True\" |\n\"less_eq_\\<M> (\\<^bold>a) (\\<^bold>b) = (a \\<le> b)\" | \n\"less_eq_\\<M> _ _ = False\"\n\nfun less_\\<M> :: \"\\<M> \\<Rightarrow> \\<M> \\<Rightarrow> bool\" where\n\"less_\\<M> (\\<^bold>_) \\<^emph> = True\" |\n\"less_\\<M> (\\<^bold>a) (\\<^bold>b) = (a < b)\" |\n\"less_\\<M> _ _ = False\"\n\ninstance proof\n  fix x y z :: \\<M>\n  show \"(x < y) = (x \\<le> y \\<and> \\<not> y \\<le> x)\"\n  proof (induction x arbitrary: y)\n    case Star\n    then show ?case by simp_all\n  next\n    case (Nr x)\n    then show ?case by (cases y) auto\n  qed\n\n  show \"x \\<le> x\" by (induction x) simp_all\n  then show \"x \\<le> y \\<Longrightarrow> y \\<le> x \\<Longrightarrow> x = y\"\n  proof (induction x arbitrary: y)\n    case Star\n    then show ?case by (cases y) simp_all\n  next\n    case (Nr x)\n    then show ?case by (cases y) simp_all\n  qed\n\n  show \"x \\<le> y \\<Longrightarrow> y \\<le> z \\<Longrightarrow> x \\<le> z\"\n  proof (induction x arbitrary: y z)\n    case Star\n    then show ?case by (cases y) simp_all\n  next\n    case (Nr x)\n    then show ?case\n    proof (induction y arbitrary: z)\n      case Star\n      then show ?case by (cases z) simp_all\n    next\n      case (Nr x)\n      then show ?case by (cases z) simp_all\n    qed\n  qed\n\n  show \"x \\<le> y \\<or> y \\<le> x\"\n  proof (induction x arbitrary: y)\n    case Star\n    then show ?case by simp\n  next\n    case (Nr x)\n    then show ?case by (cases y) auto\n  qed\nqed\n\nend\n\n\n\nsection \"Definition of multiplicity\"\n\ntype_synonym multiplicity = \"\\<M> \\<times> \\<M>\"\n\ndefinition lower :: \"multiplicity \\<Rightarrow> \\<M>\" where\n  \"lower m \\<equiv> fst m\"\n\ndeclare lower_def[simp add]\n\ndefinition upper :: \"multiplicity \\<Rightarrow> \\<M>\" where\n  \"upper m \\<equiv> snd m\"\n\ndeclare upper_def[simp add]\n\nlocale multiplicity = fixes mult :: \"multiplicity\"\n  assumes lower_bound_valid[simp]: \"lower mult \\<noteq> \\<^emph>\"\n  assumes upper_bound_valid: \"upper mult \\<noteq> \\<^bold>0\"\n  assumes properly_bounded[simp]: \"lower mult \\<le> upper mult\"\n\ncontext multiplicity\nbegin\n\nlemma upper_bound_valid_alt[simp]: \"upper mult \\<ge> \\<^bold>1\"\n  using less_\\<M>.elims not_less upper_bound_valid by fastforce\n\nend\n\nabbreviation multiplicity_notation :: \"\\<M> \\<Rightarrow> \\<M> \\<Rightarrow> multiplicity\" (\"(_/.._)\" [52, 52] 51) where\n  \"l..u \\<equiv> (l,u)\"\n\ndefinition within_multiplicity :: \"nat \\<Rightarrow> multiplicity \\<Rightarrow> bool\" (infixl \"in\" 50) where\n  \"n in m \\<equiv> lower m \\<le> \\<^bold>n \\<and> \\<^bold>n \\<le> upper m\"\n\ntheorem mult_zero_unbounded_valid[simp]: \"n in \\<^bold>0..\\<^emph>\"\n  unfolding within_multiplicity_def\n  by simp\n\ntheorem mult_single_value_bound[simp]: \"n in \\<^bold>m..\\<^bold>m \\<Longrightarrow> n = m\"\n  unfolding within_multiplicity_def\n  by auto\n\n\n\nsection \"Intersection of multiplicities\"\n\ndefinition mult_intersect :: \"multiplicity \\<Rightarrow> multiplicity \\<Rightarrow> multiplicity\" where\n  \"mult_intersect m1 m2 \\<equiv> (max (lower m1) (lower m2))..(min (upper m1) (upper m2))\"\n\nabbreviation mult_intersect_notation :: \"multiplicity \\<Rightarrow> multiplicity \\<Rightarrow> multiplicity\" (\"(_ \\<sqinter> _)\" [52, 52] 51) where\n  \"m1 \\<sqinter> m2 \\<equiv> mult_intersect m1 m2\"\n\nlemma mult_intersect_identity[simp]: \"m \\<sqinter> (\\<^bold>0..\\<^emph>) = m\"\nproof\n  show \"fst (m \\<sqinter> (\\<^bold>0..\\<^emph>)) = fst m\"\n    unfolding mult_intersect_def\n    using less_eq_\\<M>.elims(3) max.absorb1\n    by fastforce\nnext\n  show \"snd (m \\<sqinter> (\\<^bold>0..\\<^emph>)) = snd m\"\n    unfolding mult_intersect_def\n    by (simp add: min_absorb1)\nqed\n\nlemma mult_intersect_commute[simp]: \"m1 \\<sqinter> m2 = m2 \\<sqinter> m1\"\n  by (simp add: max.commute min.commute mult_intersect_def)\n\nlemma mult_intersect_assoc[simp]: \"(m1 \\<sqinter> m2) \\<sqinter> m3 = m1 \\<sqinter> (m2 \\<sqinter> m3)\"\n  unfolding mult_intersect_def\n  by (simp add: max.assoc min.assoc)\n\nlemma mult_intersect_idemp[simp]: \"m \\<sqinter> m = m\"\n  unfolding mult_intersect_def\n  by simp\n\nlemma mult_intersect_invalid[simp]: \"m \\<sqinter> (\\<^emph>..\\<^bold>0) = (\\<^emph>..\\<^bold>0)\"\nproof\n  show \"fst (m \\<sqinter> (\\<^emph>..\\<^bold>0)) = fst (\\<^emph>..\\<^bold>0)\"\n    unfolding mult_intersect_def\n    by (simp add: max.absorb2)\nnext\n  show \"snd (m \\<sqinter> (\\<^emph>..\\<^bold>0)) = snd (\\<^emph>..\\<^bold>0)\"\n    unfolding mult_intersect_def\n    using less_eq_\\<M>.elims(3) min.absorb2\n    by fastforce\nqed\n\ntheorem mult_intersect_correct[simp]: \"multiplicity m1 \\<Longrightarrow> multiplicity m2 \\<Longrightarrow> max (lower m1) (lower m2) \\<le> min (upper m1) (upper m2) \\<Longrightarrow> multiplicity (m1 \\<sqinter> m2)\"\nproof\n  fix m1 m2\n  assume m1_is_multiplicity: \"multiplicity m1\"\n  assume m2_is_multiplicity: \"multiplicity m2\"\n  have lower_bound_m1_valid: \"lower m1 \\<noteq> \\<^emph>\"\n    using m1_is_multiplicity multiplicity.lower_bound_valid by auto\n  have lower_bound_m2_valid: \"lower m2 \\<noteq> \\<^emph>\"\n    using m2_is_multiplicity multiplicity.lower_bound_valid by auto\n  have intersect_lower_def: \"lower (m1 \\<sqinter> m2) = max (lower m1) (lower m2)\"\n    by (simp add: mult_intersect_def)\n  then show \"lower (m1 \\<sqinter> m2) \\<noteq> \\<^emph>\"\n    using lower_bound_m1_valid lower_bound_m2_valid max_def\n    by metis\n  have upper_bound_m1_valid: \"upper m1 \\<noteq> \\<^bold>0\"\n    using m1_is_multiplicity multiplicity.upper_bound_valid by auto\n  have upper_bound_m2_valid: \"upper m2 \\<noteq> \\<^bold>0\"\n    using m2_is_multiplicity multiplicity.upper_bound_valid by auto\n  have intersect_upper_def: \"upper (m1 \\<sqinter> m2) = min (upper m1) (upper m2)\"\n    by (simp add: mult_intersect_def)\n  then show \"upper (m1 \\<sqinter> m2) \\<noteq> \\<^bold>0\"\n    using min_def upper_bound_m1_valid upper_bound_m2_valid\n    by metis\n  assume \"max (lower m1) (lower m2) \\<le> min (upper m1) (upper m2)\"\n  then show \"lower (m1 \\<sqinter> m2) \\<le> upper (m1 \\<sqinter> m2)\"\n    using intersect_lower_def intersect_upper_def by auto\nqed\n\nlemma mult_intersect_eq[simp]: \"m = m \\<sqinter> m\"\n  by (simp add: mult_intersect_def)\n\nend", "meta": {"author": "RemcodM", "repo": "thesis-ecore-groove-formalisation", "sha": "a0e860c4b60deb2f3798ae2ffc09f18a98cf42ca", "save_path": "github-repos/isabelle/RemcodM-thesis-ecore-groove-formalisation", "path": "github-repos/isabelle/RemcodM-thesis-ecore-groove-formalisation/thesis-ecore-groove-formalisation-a0e860c4b60deb2f3798ae2ffc09f18a98cf42ca/isabelle/Ecore/Multiplicity.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9111797148356994, "lm_q2_score": 0.805632181981183, "lm_q1q2_score": 0.7340757018400766}}
{"text": "theory Test_Code_Generation\nimports\n  Environment_Executable\nbegin                                                        \n\nsection \"Code generation for segment intersection\"  \n\ntype_synonym segment = \"(real*real)*real*real\"\ndefinition segment1::segment where\n  \"segment1 = ((0.0,0.0), (5.0,0.0))\"\ndefinition segment2::segment where\n  \"segment2 = ((0.0,0.0), (5.0,1.0))\"\ndefinition \"reoi x = (real_of_int (int_of_integer x))\"\ndefinition \"raoi i j = reoi i / reoi j\"\n    \nML \\<open>\nval segment_intersection = @{code segment_intersection}\nval segment1 = @{code segment1}\nval segment2 = @{code segment2}\nval reoi = @{code reoi}\nval raoi = @{code raoi}\nfun mk_segment a b c d = ((reoi a, reoi b), (reoi c, reoi d))\nval segment3 = mk_segment 0 1 2 3\n\\<close>\nML \\<open>segment_intersection segment1 segment2\\<close>\nML \\<open>segment_intersection segment1 segment3\\<close>\n\nsection \"Code generation for point in drivable area\"\n  \nfun polychain2 :: \"('a \\<times> 'a) list \\<Rightarrow> bool\" where\n  \"polychain2 [] = True\" | \n  \"polychain2 [x] = True\" | \n  \"polychain2 (x # y # zs) = (if snd x = fst y then polychain2 (y # zs) else False)\"\n\ntheorem univ_unfold_at_0:\n  assumes \"1 < m\" \n  shows \"(\\<forall>i::nat. Suc i < m \\<longrightarrow> P i) \\<longleftrightarrow> (P 0 \\<and> (\\<forall>i::nat. 1 \\<le> i \\<and> Suc i < m \\<longrightarrow> P i))\"  \nproof \n  assume 0: \"\\<forall>i. Suc i < m \\<longrightarrow> P i\"\n  with assms have c1: \"P 0\" by auto\n  with assms 0 have c2: \"(\\<forall>i::nat. 1 \\<le> i \\<and> Suc i < m \\<longrightarrow> P i)\" by auto      \n  with c1 show \" P 0 \\<and> (\\<forall>i. 1 \\<le> i \\<and> Suc i < m \\<longrightarrow> P i)\" by auto\nnext\n  show \"P 0 \\<and> (\\<forall>i. 1 \\<le> i \\<and> Suc i < m \\<longrightarrow> P i) \\<Longrightarrow> \\<forall>i. Suc i < m \\<longrightarrow> P i\" using assms \n      by (metis One_nat_def le_add2 le_add_same_cancel2 le_eq_less_or_eq le_simps(3))\nqed\n\nlemma polychain_polychain2[code]: \n  \"polychain xs = polychain2 xs\"\nproof (induction xs rule:polychain2.induct)\n  case 1\n  then show ?case by auto\nnext\n  case (2 x)\n  then show ?case by auto\nnext\n  case (3 x y zs)  \n  note case3 = this  \n  have \"1 < length (x # y # zs)\" by auto  \n  have \"polychain (x # y # zs) = (snd ((x # y # zs) ! 0) = fst ((x # y # zs) ! Suc 0) \\<and> \n                                 (\\<forall>i. 1 \\<le> i \\<and> Suc i < length (x # y # zs) \\<longrightarrow> snd ((x # y # zs) ! i) = fst ((x # y # zs) ! Suc i)))\"\n    unfolding polychain_def univ_unfold_at_0[OF `1 < length (x # y # zs)`, where P=\"\\<lambda>i. snd ((x # y # zs) ! i) = (fst ((x # y # zs) ! Suc i))\"]\n    by auto\n  also have \"... = (snd x = fst y \\<and> polychain (y # zs))\" unfolding polychain_def by auto\n  finally have \"polychain (x # y # zs) = (snd x = fst y \\<and> polychain (y # zs))\" by auto\n  with case3 show ?case  by auto  \nqed\n  \ndefinition points_le :: \"segment list\" where\n  \"points_le = [((0,0), (1,0)), ((1,0), (2,0)), ((2,0), (3,0))]\"\n    \ntheorem pple: \"polychain points_le\" unfolding points_le_def by eval\n      \ntheorem univ_unfold_at_0':\n  assumes \"0 < m\"\n  shows \"(\\<forall>i::nat. i < m \\<longrightarrow> P i) \\<longleftrightarrow> (P 0 \\<and> (\\<forall>i::nat. 1 \\<le> i \\<and> i < m \\<longrightarrow> P i))\"    \nproof     \n  assume 0: \"\\<forall>i<m. P i\"\n  with assms have \"P 0\" by auto\n  from 0 have \"(\\<forall>i::nat. 1 \\<le> i \\<and> i < m \\<longrightarrow> P i)\" by auto\n  with `P 0` show \"P 0 \\<and> (\\<forall>i. 1 \\<le> i \\<and> i < m \\<longrightarrow> P i)\" by auto\nnext\n  assume \" P 0 \\<and> (\\<forall>i. 1 \\<le> i \\<and> i < m \\<longrightarrow> P i)\"\n  with assms show \"\\<forall>i<m. P i\" \n    by (metis less_one not_less)  \nqed\n  \nfun monotone_polychain2 :: \"((real \\<times> real) \\<times> real \\<times> real) list \\<Rightarrow> bool\" where\n  \"monotone_polychain2 [] = True\" | \n  \"monotone_polychain2 (x # xs) = (if fst (fst x) < fst (snd x) then monotone_polychain2 xs else False)\"\n\nlemma monotone_polychain2:\n  \"(\\<forall>i<length xs. fst (fst (xs ! i)) < fst (snd (xs ! i))) = monotone_polychain2 xs\"  \nproof (induction xs)\n  case Nil\n  then show ?case by auto\nnext\n  case (Cons a xs)\n  note case_cons = this\n  have \"0 < length (a # xs)\" by auto  \n  have \"(\\<forall>i<length (a # xs). fst (fst ((a # xs) ! i)) < fst (snd ((a # xs) ! i))) = \n    (fst (fst a) < fst (snd a) \\<and> (\\<forall>i < length xs. fst (fst (xs ! i)) < fst (snd (xs ! i))))\"\n    unfolding univ_unfold_at_0'[OF `0 < length (a #xs)`, where P=\"\\<lambda>x. fst (fst ((a # xs) ! x)) < fst (snd ((a # xs) ! x))\"]\n    by auto\n  with case_cons show ?case by auto \nqed\n\nlemma monotone_polychain_monotone_polychain2 [code]:  \n  \"monotone_polychain xs = (polychain2 xs \\<and> monotone_polychain2 xs)\"    \n  unfolding monotone_polychain_def polychain_polychain2 monotone_polychain2 by auto\n\ntheorem mple: \"monotone_polychain points_le\" unfolding points_le_def by eval\n        \nglobal_interpretation llsb: lanelet_simple_boundary points_le\n  using points_le_def by (unfold_locales) (auto simp add:pple mple)\n    \ndefinition points_ri :: \"segment list\" where\n  \"points_ri = [((0,1), (1,1)), ((1,1), (2,1)), ((2,1), (3,1))]\"    \n  \ntheorem ppri: \"polychain points_ri\" unfolding points_ri_def by eval  \ntheorem mpri: \"monotone_polychain points_ri\" unfolding points_ri_def by eval\n    \nglobal_interpretation rlsb: lanelet_simple_boundary points_ri\n  using points_ri_def by (unfold_locales) (auto simp add:ppri mpri)\n\ntheorem pathstart_boundary [code]:\n  \"pathstart_boundary [x] = fst x\"\n  \"pathstart_boundary (x # y # zs) = fst x\"\n  unfolding pathstart_boundary_def points_path2_def by auto  \n    \ntheorem pathfinish_boundary [code]:\n  \"pathfinish_boundary [x] = snd x\"\n  \"pathfinish_boundary (x # y # zs) = pathfinish_boundary (y # zs)\"\n  unfolding pathfinish_boundary_def points_path2_def by auto\n        \ntheorem \"pathfinish_boundary points_ri = (3,1)\" by eval  \n    \nvalue [code] \"above_and_inside_polychains points_le (3,1)\"    \n \nglobal_interpretation l: lanelet points_ri points_le\n  defines right = l.direction_right and pida = l.point_in_drivable_area\n  by (unfold_locales) (eval+) \n    \nvalue [code] \"right\"    \nvalue [code] \"pida (1,0.5)\"\n  \nterm \"rotation_matrix'\"  \n    \n  \nend", "meta": {"author": "rizaldialbert", "repo": "overtaking", "sha": "0e76426d75f791635cd9e23b8e07669b7ce61a81", "save_path": "github-repos/isabelle/rizaldialbert-overtaking", "path": "github-repos/isabelle/rizaldialbert-overtaking/overtaking-0e76426d75f791635cd9e23b8e07669b7ce61a81/Test_Code_Generation.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772318846386, "lm_q2_score": 0.8397339736884712, "lm_q1q2_score": 0.7339923472411068}}
{"text": "(*  Title:      Util_Nat.thy\n    Date:       Oct 2006\n    Author:     David Trachtenherz\n*)\n\nheader {* Results for natural arithmetics *}\n\ntheory Util_Nat\nimports Main\nbegin\n\nsubsection {* Some convenience arithmetic lemmata *}\n\nthm Nat.add_Suc_right\nlemma add_1_Suc_conv: \"m + 1 = Suc m\" by simp\nlemma sub_Suc0_sub_Suc_conv: \"b - a - Suc 0 = b - Suc a\" by simp\nthm Nat.Suc_pred\nlemma Suc_diff_Suc: \"m < n \\<Longrightarrow> Suc (n - Suc m) = n - m\"\napply (rule subst[OF sub_Suc0_sub_Suc_conv])\napply (rule Suc_pred)\napply (simp only: zero_less_diff)\ndone\n\nlemma nat_grSuc0_conv: \"(Suc 0 < n) = (n \\<noteq> 0 \\<and> n \\<noteq> Suc 0)\"\nby fastforce\nlemma nat_geSucSuc0_conv: \"(Suc (Suc 0) \\<le> n) = (n \\<noteq> 0 \\<and> n \\<noteq> Suc 0)\"\nby fastforce\n\nlemma nat_lessSucSuc0_conv: \"(n < Suc (Suc 0)) = (n = 0 \\<or> n = Suc 0)\"\nby fastforce\nlemma nat_leSuc0_conv: \"(n \\<le> Suc 0) = (n = 0 \\<or> n = Suc 0)\"\nby fastforce\n\n\n\nthm Nat.mult_Suc\nlemma mult_pred: \"(m - Suc 0) * n = m * n - n\" \nby (simp add: diff_mult_distrib)\nthm Nat.mult_Suc_right\nlemma mult_pred_right: \"m * (n - Suc 0) = m * n - m\"\nby (simp add: diff_mult_distrib2)\n\nlemma gr_implies_gr0: \"m < (n::nat) \\<Longrightarrow> 0 < n\" by simp\n\n\nthm \n  Nat.mult_cancel1\n  Nat.mult_cancel1\ncorollary mult_cancel1_gr0: \"\n  (0::nat) < k \\<Longrightarrow> (k * m = k * n) = (m = n)\" by simp\ncorollary mult_cancel2_gr0: \"\n  (0::nat) < k \\<Longrightarrow> (m * k = n * k) = (m = n)\" by simp\n\nthm\n  Nat.mult_le_cancel1\n  Nat.mult_le_cancel2\ncorollary mult_le_cancel1_gr0: \"\n  (0::nat) < k \\<Longrightarrow> (k * m \\<le> k * n) = (m \\<le> n)\" by simp\ncorollary mult_le_cancel2_gr0: \"\n  (0::nat) < k \\<Longrightarrow> (m * k \\<le> n * k) = (m \\<le> n)\" by simp\n\n\n\nthm mult_le_mono\nlemma gr0_imp_self_le_mult1: \"0 < (k::nat) \\<Longrightarrow> m \\<le> m * k\"\nby (drule Suc_leI, drule mult_le_mono[OF order_refl], simp)\n\nlemma gr0_imp_self_le_mult2: \"0 < (k::nat) \\<Longrightarrow> m \\<le> k * m\"\nby (subst mult.commute, rule gr0_imp_self_le_mult1)\n\nlemma less_imp_Suc_mult_le: \"m < n \\<Longrightarrow> Suc m * k \\<le> n * k\"\nby (rule mult_le_mono1, simp)\n\nlemma less_imp_Suc_mult_pred_less: \"\\<lbrakk> m < n; 0 < k \\<rbrakk> \\<Longrightarrow> Suc m * k - Suc 0 < n * k\"\napply (rule Suc_le_lessD)\napply (simp only: Suc_pred[OF nat_0_less_mult_iff[THEN iffD2, OF conjI, OF zero_less_Suc]])\napply (rule less_imp_Suc_mult_le, assumption)\ndone\n\nthm Nat.zero_less_diff\nlemma ord_zero_less_diff: \"(0 < (b::'a::ordered_ab_group_add) - a) = (a < b)\"\nby (simp add: less_diff_eq)\n\nlemma ord_zero_le_diff: \"(0 \\<le> (b::'a::ordered_ab_group_add) - a) = (a \\<le> b)\"\nby (simp add: le_diff_eq)\n\ntext {* @{text diff_diff_right} in rule format *}\nlemmas diff_diff_right = Nat.diff_diff_right[rule_format]\n\n\n\n\nthm Nat.le_add1 Nat.le_add2\nlemma less_add1: \"(0::nat) < j \\<Longrightarrow> i < i + j\" by simp\nlemma less_add2: \"(0::nat) < j \\<Longrightarrow> i < j + i\" by simp\n\nthm Nat.add_leD1 Nat.add_leD2\nthm Nat.add_lessD1\nlemma add_lessD2: \"i + j < (k::nat) \\<Longrightarrow> j < k\" by simp\n\nthm Nat.add_le_mono1\nlemma add_le_mono2: \"i \\<le> (j::nat) \\<Longrightarrow> k + i \\<le> k + j\" by simp\nthm Nat.add_less_mono1\nlemma add_less_mono2: \"i < (j::nat) \\<Longrightarrow> k + i < k + j\" by simp\n\nthm Nat.diff_le_self\nlemma diff_less_self: \"\\<lbrakk> (0::nat) < i;  0 < j \\<rbrakk> \\<Longrightarrow> i - j < i\" by simp\n\nlemma \n  ge_less_neq_conv: \"((a::'a::linorder) \\<le> n) = (\\<forall>x. x < a \\<longrightarrow> n \\<noteq> x)\" and\n  le_greater_neq_conv: \"(n \\<le> (a::'a::linorder)) = (\\<forall>x. a < x \\<longrightarrow> n \\<noteq> x)\"\nby (subst linorder_not_less[symmetric], blast)+\nlemma \n  greater_le_neq_conv: \"((a::'a::linorder) < n) = (\\<forall>x. x \\<le> a \\<longrightarrow> n \\<noteq> x)\" and\n  less_ge_neq_conv: \"(n < (a::'a::linorder)) = (\\<forall>x. a \\<le> x \\<longrightarrow> n \\<noteq> x)\"\nby (subst linorder_not_le[symmetric], blast)+\n\n\n\ntext {* Lemmas for @term{abs} function *}\n\nlemma leq_pos_imp_abs_leq: \"\\<lbrakk> 0 \\<le> (a::'a::ordered_ab_group_add_abs); a \\<le> b \\<rbrakk> \\<Longrightarrow> \\<bar>a\\<bar> \\<le> \\<bar>b\\<bar>\"\nby simp\nlemma leq_neg_imp_abs_geq: \"\\<lbrakk> (a::'a::ordered_ab_group_add_abs) \\<le> 0; b \\<le> a \\<rbrakk> \\<Longrightarrow> \\<bar>a\\<bar> \\<le> \\<bar>b\\<bar>\"\nby simp\nlemma abs_range: \"\\<lbrakk> 0 \\<le> (a::'a::{ordered_ab_group_add_abs,abs_if}); -a \\<le> x; x \\<le> a \\<rbrakk> \\<Longrightarrow> \\<bar>x\\<bar> \\<le> a\"\napply (clarsimp simp: abs_if)\nthm neg_le_iff_le[THEN iffD1]\napply (rule neg_le_iff_le[THEN iffD1], simp)\ndone\n\n\n\ntext {* Lemmas for @term{sgn} function *}\n\nlemma sgn_abs:\"(x::'a::linordered_idom) \\<noteq> 0 \\<Longrightarrow> \\<bar>sgn x\\<bar> = 1\"\nby (case_tac \"x < 0\", simp+)\nlemma sgn_mult_abs:\"\\<bar>x\\<bar> * \\<bar>sgn (a::'a::linordered_idom)\\<bar> = \\<bar>x * sgn a\\<bar>\"\nby (fastforce simp add: sgn_if abs_if)\nlemma abs_imp_sgn_abs: \"\\<bar>a\\<bar> = \\<bar>b\\<bar> \\<Longrightarrow> \\<bar>sgn (a::'a::linordered_idom)\\<bar> = \\<bar>sgn b\\<bar>\"\nby (fastforce simp add: abs_if)\nlemma sgn_mono: \"a \\<le> b \\<Longrightarrow> sgn (a::'a::{linordered_idom,linordered_semidom}) \\<le> sgn b\"\nby (auto simp add: sgn_if)\n\n\n\n\n\n\n\nsubsection {* Additional facts about inequalities *}\n\nthm Nat.le_add_diff\nlemma add_diff_le: \"k \\<le> n \\<Longrightarrow> m + k - n \\<le> (m::nat)\"\nby (case_tac \"m + k < n\", simp_all)\nthm \n  Nat.le_add_diff\n  add_diff_le\n\nlemma less_add_diff: \"k < (n::nat) \\<Longrightarrow> m < n + m - k\"\nthm add_less_imp_less_right[of _ k]\nby (rule add_less_imp_less_right[of _ k], simp)\nthm add_diff_le\nlemma add_diff_less: \"\\<lbrakk> k < n; 0 < m \\<rbrakk> \\<Longrightarrow> m + k - n < (m::nat)\"\nby (case_tac \"m + k < n\", simp_all)\nthm \n  Nat.le_add_diff\n  add_diff_le\n  less_add_diff\n  add_diff_less\n\n\n\nthm Nat.less_diff_conv\nlemma add_le_imp_le_diff1: \"i + k \\<le> j \\<Longrightarrow> i \\<le> j - (k::nat)\"\nby (case_tac \"k \\<le> j\", simp_all)\nlemma add_le_imp_le_diff2: \"k + i \\<le> j \\<Longrightarrow> i \\<le> j - (k::nat)\" by simp\nthm \n  Nat.less_diff_conv[symmetric]\n  Nat.le_diff_conv2[symmetric]\n  add_le_imp_le_diff1\n  add_le_imp_le_diff2\n\n\nthm \n  Nat.le_diff_conv Nat.le_diff_conv2 \n  Nat.less_diff_conv\nlemma diff_less_imp_less_add: \"j - (k::nat) < i \\<Longrightarrow> j < i + k\" by simp\nthm Nat.le_diff_conv\nlemma diff_less_conv: \"0 < i \\<Longrightarrow> (j - (k::nat) < i) = (j < i + k)\" \nby (safe, simp_all)\n\n\n\nlemma diff_less_imp_swap: \"\\<lbrakk> 0 < (i::nat); k - i < j \\<rbrakk> \\<Longrightarrow> (k - j < i)\" by simp\nlemma diff_less_swap: \"\\<lbrakk> 0 < (i::nat); 0 < j \\<rbrakk> \\<Longrightarrow> (k - j < i) = (k - i < j)\" \nby (blast intro: diff_less_imp_swap)\n\nlemma less_diff_imp_less: \"(i::nat) < j - m \\<Longrightarrow> i < j\" by simp\nlemma le_diff_imp_le: \"(i::nat) \\<le> j - m \\<Longrightarrow> i \\<le> j\" by simp\n\nlemma less_diff_le_imp_less: \"\\<lbrakk> (i::nat) < j - m; n \\<le> m \\<rbrakk> \\<Longrightarrow> i < j - n\" by simp\nlemma le_diff_le_imp_le: \"\\<lbrakk> (i::nat) \\<le> j - m; n \\<le> m \\<rbrakk> \\<Longrightarrow> i \\<le> j - n\" by simp\n\nthm Nat.less_imp_diff_less\nlemma le_imp_diff_le: \"(j::nat) \\<le> k \\<Longrightarrow> j - n \\<le> k\" by simp\n\n\n\nsubsection {* Inequalities for Suc and pred *}\n\nthm Nat.less_Suc_eq_le\ncorollary less_eq_le_pred: \"0 < (n::nat) \\<Longrightarrow> (m < n) = (m \\<le> n - Suc 0)\"\nby (safe, simp_all)\ncorollary less_imp_le_pred: \"m < n \\<Longrightarrow> m \\<le> n - Suc 0\" by simp\ncorollary le_pred_imp_less: \"\\<lbrakk> 0 < n; m \\<le> n - Suc 0 \\<rbrakk> \\<Longrightarrow> m < n\" by simp\n\nthm Nat.Suc_le_eq\ncorollary pred_less_eq_le: \"0 < m \\<Longrightarrow> (m - Suc 0 < n) = (m \\<le> n)\" \nby (safe, simp_all)\ncorollary pred_less_imp_le: \"m - Suc 0 < n \\<Longrightarrow> m \\<le> n\" by simp\ncorollary le_imp_pred_less: \"\\<lbrakk> 0 < m; m \\<le> n \\<rbrakk> \\<Longrightarrow> m - Suc 0 < n\" by simp\n\n\n\n\nthm Nat.diff_add_inverse\nlemma diff_add_inverse_Suc: \"n < m \\<Longrightarrow> n + (m - Suc n) = m - Suc 0\" by simp\n\nthm Nat.Suc_mono\nlemma pred_mono: \"\\<lbrakk> m < n; 0 < m \\<rbrakk> \\<Longrightarrow> m - Suc 0 < n - Suc 0\" by simp\ncorollary pred_Suc_mono: \"\\<lbrakk> m < Suc n; 0 < m \\<rbrakk> \\<Longrightarrow> m - Suc 0 < n\" by simp\n\nlemma Suc_less_pred_conv: \"(Suc m < n) = (m < n - Suc 0)\" by (safe, simp_all)\nlemma Suc_le_pred_conv: \"0 < n \\<Longrightarrow> (Suc m \\<le> n) = (m \\<le> n - Suc 0)\" by (safe, simp_all)\nlemma Suc_le_imp_le_pred: \"Suc m \\<le> n \\<Longrightarrow> m \\<le> n - Suc 0\" by simp\n\n\n\nsubsection {* Additional facts about cancellation in (in-)equalities *}\n\nlemma diff_cancel_imp_eq: \"\\<lbrakk> 0 < (n::nat);  n + i - j = n \\<rbrakk> \\<Longrightarrow> i = j\" by simp\n\nthm\n  Nat.nat_add_left_cancel_less\n  Nat.nat_add_left_cancel_le\n  Nat.nat_add_right_cancel\n  Nat.nat_add_left_cancel\n  Nat.diff_diff_eq\n  Nat.eq_diff_iff\n  Nat.less_diff_iff\n  Nat.le_diff_iff\nlemma nat_diff_left_cancel_less: \"k - m < k - (n::nat) \\<Longrightarrow> n < m\" by simp\nlemma nat_diff_right_cancel_less: \"n - k < (m::nat) - k \\<Longrightarrow> n < m\" by simp\n\nlemma nat_diff_left_cancel_le1: \"\\<lbrakk> k - m \\<le> k - (n::nat); m < k \\<rbrakk> \\<Longrightarrow> n \\<le> m\" by simp\nlemma nat_diff_left_cancel_le2: \"\\<lbrakk> k - m \\<le> k - (n::nat); n \\<le> k \\<rbrakk> \\<Longrightarrow> n \\<le> m\" by simp\n\nlemma nat_diff_right_cancel_le1: \"\\<lbrakk> m - k \\<le> n - (k::nat); k < m \\<rbrakk> \\<Longrightarrow> m \\<le> n\" by simp\nlemma nat_diff_right_cancel_le2: \"\\<lbrakk> m - k \\<le> n - (k::nat); k \\<le> n \\<rbrakk> \\<Longrightarrow> m \\<le> n\" by simp\n\nlemma nat_diff_left_cancel_eq1: \"\\<lbrakk> k - m = k - (n::nat); m < k \\<rbrakk> \\<Longrightarrow> m = n\" by simp\nlemma nat_diff_left_cancel_eq2: \"\\<lbrakk> k - m = k - (n::nat); n < k \\<rbrakk> \\<Longrightarrow> m = n\" by simp\n\nlemma nat_diff_right_cancel_eq1: \"\\<lbrakk> m - k = n - (k::nat); k < m \\<rbrakk> \\<Longrightarrow> m = n\" by simp\nlemma nat_diff_right_cancel_eq2: \"\\<lbrakk> m - k = n - (k::nat); k < n \\<rbrakk> \\<Longrightarrow> m = n\" by simp\n\nthm eq_diff_iff\nlemma eq_diff_left_iff: \"\\<lbrakk> (m::nat) \\<le> k; n \\<le> k\\<rbrakk> \\<Longrightarrow> (k - m = k - n) = (m = n)\" \nby (safe, simp_all)\n\nthm Nat.nat_add_right_cancel Nat.nat_add_left_cancel\nthm Nat.diff_le_mono\nlemma eq_imp_diff_eq: \"m = (n::nat) \\<Longrightarrow> m - k = n - k\" by simp\n\ntext {* List of definitions and lemmas *}\n\nthm \n  Nat.add_Suc_right\n  add_1_Suc_conv\n  sub_Suc0_sub_Suc_conv\n\nthm\n  Nat.mult_cancel1\n  Nat.mult_cancel2\n  mult_cancel1_gr0\n  mult_cancel2_gr0\n\nthm \n  Nat.add_lessD1\n  add_lessD2\n\nthm\n  Nat.zero_less_diff\n  ord_zero_less_diff\n  ord_zero_le_diff\n\nthm\n  Nat.le_add_diff\n  add_diff_le\n  less_add_diff\n  add_diff_less\n\nthm \n  Nat.le_diff_conv Nat.le_diff_conv2 \n  Nat.less_diff_conv\n  diff_less_imp_less_add \n  diff_less_conv\n\nthm\n  le_diff_swap\n  diff_less_imp_swap\n  diff_less_swap\n\nthm\n  less_diff_imp_less\n  le_diff_imp_le\n\nthm\n  less_diff_le_imp_less\n  le_diff_le_imp_le\n\nthm\n  Nat.less_imp_diff_less\n  le_imp_diff_le\n\nthm\n  Nat.less_Suc_eq_le\n  less_eq_le_pred\n  less_imp_le_pred\n  le_pred_imp_less\n\nthm\n  Nat.Suc_le_eq\n  pred_less_eq_le\n  pred_less_imp_le\n  le_imp_pred_less\n\nthm\n  diff_cancel_imp_eq\nthm\n  diff_add_inverse_Suc\nthm\n  Nat.nat_add_left_cancel_less\n  Nat.nat_add_left_cancel_le\n  Nat.nat_add_right_cancel\n  Nat.nat_add_left_cancel\n  Nat.eq_diff_iff\n  Nat.less_diff_iff\n  Nat.le_diff_iff\nthm\n  nat_diff_left_cancel_less\n  nat_diff_right_cancel_less\nthm\n  nat_diff_left_cancel_le1\n  nat_diff_left_cancel_le2\n  nat_diff_right_cancel_le1\n  nat_diff_right_cancel_le2\nthm\n  nat_diff_left_cancel_eq1\n  nat_diff_left_cancel_eq2\n  nat_diff_right_cancel_eq1\n  nat_diff_right_cancel_eq2\n\nthm \n  Nat.eq_diff_iff\n  eq_diff_left_iff\n\nthm \n  Nat.nat_add_right_cancel Nat.nat_add_left_cancel\n  Nat.diff_le_mono\n  eq_imp_diff_eq\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/CommonArith/Util_Nat.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772318846386, "lm_q2_score": 0.8397339616560072, "lm_q1q2_score": 0.733992336723804}}
{"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: \"(!!x. x \\<in> M \\<Longrightarrow> EX y : 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> EX y : 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": "Josh-Tilles", "repo": "AFP", "sha": "f4bf1d502bde2a3469d482b62c531f1c3af3e881", "save_path": "github-repos/isabelle/Josh-Tilles-AFP", "path": "github-repos/isabelle/Josh-Tilles-AFP/AFP-f4bf1d502bde2a3469d482b62c531f1c3af3e881/thys/Flyspeck-Tame/Quasi_Order.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.86153820232079, "lm_q2_score": 0.8519527963298946, "lm_q1q2_score": 0.7339898806122276}}
{"text": "header {* Partition iteration algorithm *}\n\n(*<*)\ntheory Partition_iterate imports Helpers\nbegin\n(*>*)\n\ntext {*\nThe partition iteration algorithm @{text partition_iterate} takes four parameters:\n\\begin{itemize}\n\\item a predicate $P$,\n\\item an accumulator update function $f$,\n\\item an accumulator $a$,\n\\item and finally a list $l$.\n\\end{itemize}\nIn each iteration of the algorithm, it splits the input list $l$\ninto two lists $yes$ and $no$, which contain the list elements satisfying\n$P\\, a$ respectively those which do not. Then, we calculate a new\naccumulator $a'$ using the accumulator update function $f$, i.e.\n$a'=f\\, a\\, yes$, and call the algorithm again with the updated accumulator\n$a'$ and those list elements which did not satisfy the predicate\n$P\\, a$, namely $no$. We continue this process as long as there\nare list elements which satisfy the predicate; when this is no longer\nthe case, we return the last accumulator and those list elements which\nnever satisfied the predicate.\n*}\n\nfunction partition_iterate ::\n  \"('a \\<Rightarrow> 'b \\<Rightarrow> bool) \\<Rightarrow> ('a \\<Rightarrow> 'b list \\<Rightarrow> 'a) \\<Rightarrow> 'a \\<Rightarrow> 'b list \\<Rightarrow>\n    'a \\<times> 'b list\" where\n  \"partition_iterate P f a l = (case partition (P a) l of\n       ([] , no) \\<Rightarrow> (a, no)\n     | (yes, no) \\<Rightarrow> partition_iterate P f (f a yes) no)\"\nby auto\n\ntermination partition_iterate\nby (relation \"measure (\\<lambda>(p, f, a, l). length l)\")\n   (auto simp add: filter_length_smaller)\n\n(*<*)\nlemma pi_induct [case_names Base Step]:\n  assumes B: \"P (a, l)\"\n      and S: \"\\<And>a l yes no. P (a, l) \\<Longrightarrow> partition (p a) l = (yes, no) \\<Longrightarrow> P (f a yes, no)\"\n  shows \"P (partition_iterate p f a l)\" using B\nproof (induct l arbitrary: a rule: length_induct)\n  case (1 l a) then show ?case\n  proof (cases \"filter (p a) l\")\n    case Nil show ?thesis using 1(2) filter_one_empty_other_full[of \"p a\"] Nil by auto\n  next\n    case (Cons yesh yest)\n    def no \\<equiv> \"filter (Not \\<circ> p a) l\"\n    have \"(\\<forall>x. P (x, no) \\<longrightarrow> P (partition_iterate p f x no))\"\n      using spec[OF 1(1), of no] filter_length_smaller[of _ _ p, OF Cons[symmetric]] no_def by auto\n    then have \"P (partition_iterate p f (f a (yesh#yest)) no)\"\n      using S[OF 1(2), of \"yesh#yest\"] Cons no_def by auto\n    then show ?thesis using Cons no_def[symmetric] by simp\n  qed\nqed\n\nlemma pi_termination_condition:\n  assumes \"partition_iterate P f a l = (ac, no)\"\n  shows \"filter (P ac) no = []\"\nproof -\n  have \"(ac, no) = (case partition (P a) l of ([], no) \\<Rightarrow>\n    (a, no) | (x # l, no) \\<Rightarrow> partition_iterate P f (f a (x # l)) no)\" using assms by simp\n  then show ?thesis proof (induct l arbitrary: ac no a rule: length_induct)\n    case (1 l)\n    def yes \\<equiv> \"filter (P a) l\"\n    def noa \\<equiv> \"filter (Not \\<circ> P a) l\"\n    then show ?case proof (cases yes)\n      case Nil then show ?thesis using 1 yes_def by simp\n    next\n      case Cons\n      then have E: \"(ac, no) = (partition_iterate P f (f a yes) noa)\" using 1(2)\n        unfolding yes_def partition_filter_conv noa_def by (metis list.simps(5) split_conv)\n\n      have S: \"length noa < length l\" using Cons filter_length_smaller[of _ _ P a l]\n        unfolding yes_def noa_def by auto\n      then show ?thesis using 1 E by (metis (mono_tags) partition_iterate.simps)\n    qed\n  qed\nqed\n\nlemma pi_invariant:\n  assumes \"\\<And>a. f a [] = a\"\n    shows \"partition_iterate P f a l =\n           (\\<lambda>(acc, no). (f acc (filter (P acc) no), no)) (partition_iterate P f a l)\"\nproof -\n  def pi \\<equiv> \"partition_iterate P f a l\"\n  def ac \\<equiv> \"fst pi\"\n  def no \\<equiv> \"snd pi\"\n  have PI: \"partition_iterate P f a l = (ac, no)\" using pi_def ac_def no_def by auto\n\n  have \"filter (P ac) no = []\" using pi_termination_condition PI .\n  then have \"f ac (filter (P ac) no) = ac\" using assms by auto\n  then show ?thesis unfolding ac_def no_def pi_def by (case_tac \"partition_iterate P f a l\") auto\nqed\n(*>*)\n\nend\n", "meta": {"author": "01mf02", "repo": "thesis", "sha": "d0a5f8e8b6416877c4ba897f6030f2b491c67b0c", "save_path": "github-repos/isabelle/01mf02-thesis", "path": "github-repos/isabelle/01mf02-thesis/thesis-d0a5f8e8b6416877c4ba897f6030f2b491c67b0c/Isabelle/Partition_iterate.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527906914787, "lm_q2_score": 0.86153820232079, "lm_q1q2_score": 0.7339898757545168}}
{"text": "(* -------------------------------------------------------------------------- *)\nsubsection \\<open>Canonical angle\\<close> \n(* -------------------------------------------------------------------------- *)\n\ntext \\<open>Canonize any angle to $(-\\pi, \\pi]$ (taking account of $2\\pi$ periodicity of @{term sin} and\n@{term cos}). With this function, for example, multiplicative properties of @{term arg} for complex\nnumbers can easily be expressed and proved.\\<close>\n\ntheory Canonical_Angle\nimports More_Transcendental\nbegin\n\n\nabbreviation canon_ang_P where\n \"canon_ang_P \\<alpha> \\<alpha>' \\<equiv> (-pi < \\<alpha>' \\<and> \\<alpha>' \\<le> pi) \\<and> (\\<exists> k::int. \\<alpha> - \\<alpha>' = 2*k*pi)\"\n\ndefinition canon_ang :: \"real \\<Rightarrow> real\" (\"\\<downharpoonright>_\\<downharpoonleft>\") where\n  \"\\<downharpoonright>\\<alpha>\\<downharpoonleft> = (THE \\<alpha>'. canon_ang_P \\<alpha> \\<alpha>')\"\n\ntext \\<open>There is a canonical angle for every angle.\\<close>\nlemma canon_ang_ex:\n  shows \"\\<exists> \\<alpha>'. canon_ang_P \\<alpha> \\<alpha>'\"\nproof-\n  have ***: \"\\<forall> \\<alpha>::real. \\<exists> \\<alpha>'. 0 < \\<alpha>' \\<and> \\<alpha>' \\<le> 1 \\<and> (\\<exists> k::int. \\<alpha>' = \\<alpha> - k)\"\n  proof\n    fix \\<alpha>::real\n    show \"\\<exists>\\<alpha>'>0. \\<alpha>' \\<le> 1 \\<and> (\\<exists>k::int. \\<alpha>' = \\<alpha> - k)\"\n    proof (cases \"\\<alpha> = floor \\<alpha>\")\n      case True\n      thus ?thesis\n        by (rule_tac x=\"\\<alpha> - floor \\<alpha> + 1\" in exI, auto) (rule_tac x=\"floor \\<alpha> - 1\" in exI, auto)\n    next\n      case False\n      thus ?thesis\n        using real_of_int_floor_ge_diff_one[of \"\\<alpha>\"]\n        using of_int_floor_le[of \"\\<alpha>\"]\n        by (rule_tac x=\"\\<alpha> - floor \\<alpha>\" in exI) smt\n    qed\n  qed\n\n  have **: \"\\<forall> \\<alpha>::real. \\<exists> \\<alpha>'. 0 < \\<alpha>' \\<and> \\<alpha>' \\<le> 2 \\<and> (\\<exists> k::int. \\<alpha> - \\<alpha>' = 2*k - 1)\"\n  proof\n    fix \\<alpha>::real\n    from ***[rule_format, of \"(\\<alpha> + 1) /2\"]\n    obtain \\<alpha>' and k::int where \"0 < \\<alpha>'\" \"\\<alpha>' \\<le> 1\" \"\\<alpha>' = (\\<alpha> + 1)/2 - k\"\n      by force\n    hence \"0 < \\<alpha>'\" \"\\<alpha>' \\<le> 1\" \"\\<alpha>' = \\<alpha>/2 - k + 1/2\"\n      by auto\n    thus \"\\<exists>\\<alpha>'>0. \\<alpha>' \\<le> 2 \\<and> (\\<exists>k::int. \\<alpha> - \\<alpha>' = real_of_int (2 * k - 1))\"\n      by (rule_tac x=\"2*\\<alpha>'\" in exI) auto\n  qed\n  have *: \"\\<forall> \\<alpha>::real. \\<exists> \\<alpha>'. -1 < \\<alpha>' \\<and> \\<alpha>' \\<le> 1 \\<and> (\\<exists> k::int. \\<alpha> - \\<alpha>' = 2*k)\"\n  proof\n    fix \\<alpha>::real\n    from ** obtain \\<alpha>' and k :: int where\n      \"0 < \\<alpha>' \\<and> \\<alpha>' \\<le> 2 \\<and> \\<alpha> - \\<alpha>' = 2*k - 1\"\n      by force\n    thus \"\\<exists>\\<alpha>'>-1. \\<alpha>' \\<le> 1 \\<and> (\\<exists>k. \\<alpha> - \\<alpha>' = real_of_int (2 * (k::int)))\"\n      by (rule_tac x=\"\\<alpha>' - 1\" in exI) (auto simp add: field_simps)\n  qed\n  obtain \\<alpha>' k where 1: \"\\<alpha>' >- 1 \\<and> \\<alpha>' \\<le> 1\" and 2: \"\\<alpha> / pi - \\<alpha>' = real_of_int (2 * k)\"\n    using *[rule_format, of \"\\<alpha> / pi\"]\n    by auto\n  have \"\\<alpha>'*pi > -pi \\<and> \\<alpha>'*pi \\<le> pi\" \n    using 1\n    by (smt mult.commute mult_le_cancel_left1 mult_minus_right pi_gt_zero)\n  moreover\n  have \"\\<alpha> - \\<alpha>'*pi = 2 * real_of_int k * pi\"\n    using 2\n    by (auto simp add: field_simps)\n  ultimately\n  show ?thesis\n    by auto\nqed\n\ntext \\<open>Canonical angle of any angle is unique.\\<close>\nlemma canon_ang_unique:\n  assumes \"canon_ang_P \\<alpha> \\<alpha>\\<^sub>1\" and \"canon_ang_P \\<alpha> \\<alpha>\\<^sub>2\"\n  shows \"\\<alpha>\\<^sub>1 = \\<alpha>\\<^sub>2\"\nproof-\n  obtain k1::int where \"\\<alpha> - \\<alpha>\\<^sub>1 = 2*k1*pi\"\n    using assms(1)\n    by auto\n  obtain k2::int where \"\\<alpha> - \\<alpha>\\<^sub>2 = 2*k2*pi\"\n    using assms(2)\n    by auto\n  hence *: \"-\\<alpha>\\<^sub>1 + \\<alpha>\\<^sub>2 = 2*(k1 - k2)*pi\"\n    using \\<open>\\<alpha> - \\<alpha>\\<^sub>1 = 2*k1*pi\\<close>\n    by (simp add:field_simps)\n  moreover\n  have \"-\\<alpha>\\<^sub>1 + \\<alpha>\\<^sub>2 < 2 * pi\" \"-\\<alpha>\\<^sub>1 + \\<alpha>\\<^sub>2 > -2*pi\"\n    using assms\n    by auto\n  ultimately\n  have \"-\\<alpha>\\<^sub>1 + \\<alpha>\\<^sub>2 = 0\"\n    using mult_less_cancel_right[of \"-2\" pi \"real_of_int(2 * (k1 - k2))\"]\n    by auto\n  thus ?thesis\n    by auto\nqed\n\ntext \\<open>Canonical angle is always in $(-\\pi, \\pi]$ and differs from the starting angle by $2k\\pi$.\\<close>\nlemma canon_ang:\n  shows \"-pi < \\<downharpoonright>\\<alpha>\\<downharpoonleft>\" and \"\\<downharpoonright>\\<alpha>\\<downharpoonleft> \\<le> pi\" and \"\\<exists> k::int. \\<alpha> - \\<downharpoonright>\\<alpha>\\<downharpoonleft> = 2*k*pi\"\nproof-\n  obtain \\<alpha>' where \"canon_ang_P \\<alpha> \\<alpha>'\"\n    using canon_ang_ex[of \\<alpha>]\n    by auto\n  have \"canon_ang_P \\<alpha> \\<downharpoonright>\\<alpha>\\<downharpoonleft>\"\n    unfolding canon_ang_def\n  proof (rule theI[where a=\"\\<alpha>'\"])\n    show \"canon_ang_P \\<alpha> \\<alpha>'\"\n      by fact\n  next\n    fix \\<alpha>''\n    assume \"canon_ang_P \\<alpha> \\<alpha>''\"\n    thus \"\\<alpha>'' = \\<alpha>'\"\n      using \\<open>canon_ang_P \\<alpha> \\<alpha>'\\<close>\n      using canon_ang_unique[of \\<alpha>' \\<alpha> \\<alpha>'']\n      by simp\n  qed\n  thus \"-pi < \\<downharpoonright>\\<alpha>\\<downharpoonleft>\" \"\\<downharpoonright>\\<alpha>\\<downharpoonleft> \\<le> pi\" \"\\<exists> k::int. \\<alpha> - \\<downharpoonright>\\<alpha>\\<downharpoonleft> = 2*k*pi\"\n    by auto\nqed\n\ntext \\<open>Angles in $(-\\pi, \\pi]$ are already canonical.\\<close>\nlemma canon_ang_id:\n  assumes  \"-pi < \\<alpha> \\<and> \\<alpha> \\<le> pi\"\n  shows \"\\<downharpoonright>\\<alpha>\\<downharpoonleft> = \\<alpha>\"\n  using assms\n  using canon_ang_unique[of \"canon_ang \\<alpha>\" \\<alpha> \\<alpha>] canon_ang[of \\<alpha>]\n  by auto\n\ntext \\<open>Angles that differ by $2k\\pi$ have equal canonical angles.\\<close>\nlemma canon_ang_eq:\n  assumes \"\\<exists> k::int. \\<alpha>\\<^sub>1 - \\<alpha>\\<^sub>2 = 2*k*pi\"\n  shows \"\\<downharpoonright>\\<alpha>\\<^sub>1\\<downharpoonleft> = \\<downharpoonright>\\<alpha>\\<^sub>2\\<downharpoonleft>\"\nproof-\n  obtain k'::int where *: \"- pi < \\<downharpoonright>\\<alpha>\\<^sub>1\\<downharpoonleft>\" \"\\<downharpoonright>\\<alpha>\\<^sub>1\\<downharpoonleft> \\<le> pi\" \"\\<alpha>\\<^sub>1 - \\<downharpoonright>\\<alpha>\\<^sub>1\\<downharpoonleft> = 2 * k' * pi\"\n    using canon_ang[of \\<alpha>\\<^sub>1]\n    by auto\n\n  obtain k''::int where **: \"- pi < \\<downharpoonright>\\<alpha>\\<^sub>2\\<downharpoonleft>\" \"\\<downharpoonright>\\<alpha>\\<^sub>2\\<downharpoonleft> \\<le> pi\" \"\\<alpha>\\<^sub>2 - \\<downharpoonright>\\<alpha>\\<^sub>2\\<downharpoonleft> = 2 * k'' * pi\"\n    using canon_ang[of \\<alpha>\\<^sub>2]\n    by auto\n\n  obtain k::int where ***: \"\\<alpha>\\<^sub>1 - \\<alpha>\\<^sub>2 = 2*k*pi\"\n    using assms\n    by auto\n\n  have \"\\<exists>m::int. \\<alpha>\\<^sub>1 - \\<downharpoonright>\\<alpha>\\<^sub>2\\<downharpoonleft> = 2 * m * pi\"\n    using **(3) ***\n    by (rule_tac x=\"k+k''\" in exI) (auto simp add: field_simps)\n\n  thus ?thesis\n    using canon_ang_unique[of \"\\<downharpoonright>\\<alpha>\\<^sub>1\\<downharpoonleft>\" \\<alpha>\\<^sub>1 \"\\<downharpoonright>\\<alpha>\\<^sub>2\\<downharpoonleft>\"] * **\n    by auto\nqed\n\ntext \\<open>Introduction and elimination rules\\<close>\nlemma canon_ang_eqI:\n  assumes \"\\<exists>k::int. \\<alpha>' - \\<alpha> = 2 * k * pi\" and \"- pi < \\<alpha>' \\<and> \\<alpha>' \\<le> pi\"\n  shows \"\\<downharpoonright>\\<alpha>\\<downharpoonleft> = \\<alpha>'\"\n  using assms\n  using canon_ang_eq[of \\<alpha>' \\<alpha>]\n  using canon_ang_id[of \\<alpha>']\n  by auto\n\nlemma canon_ang_eqE:\n  assumes \"\\<downharpoonright>\\<alpha>\\<^sub>1\\<downharpoonleft> = \\<downharpoonright>\\<alpha>\\<^sub>2\\<downharpoonleft>\"\n  shows \"\\<exists> (k::int). \\<alpha>\\<^sub>1 - \\<alpha>\\<^sub>2 = 2 *k * pi\"\nproof-\n  obtain k1 k2 :: int where\n    \"\\<alpha>\\<^sub>1 - \\<downharpoonright>\\<alpha>\\<^sub>1\\<downharpoonleft> = 2 * k1 * pi\"\n    \"\\<alpha>\\<^sub>2 - \\<downharpoonright>\\<alpha>\\<^sub>2\\<downharpoonleft> = 2 * k2 * pi\"\n    using canon_ang[of \\<alpha>\\<^sub>1] canon_ang[of \\<alpha>\\<^sub>2]\n    by auto\n  thus ?thesis\n    using assms\n    by (rule_tac x=\"k1 - k2\" in exI) (auto simp add: field_simps)\nqed\n\ntext \\<open>Canonical angle of opposite angle\\<close>\n\nlemma canon_ang_uminus:\n  assumes \"\\<downharpoonright>\\<alpha>\\<downharpoonleft> \\<noteq> pi\"\n  shows \"\\<downharpoonright>-\\<alpha>\\<downharpoonleft> = -\\<downharpoonright>\\<alpha>\\<downharpoonleft>\"\nproof (rule canon_ang_eqI)\n  show \"\\<exists>x::int. - \\<downharpoonright>\\<alpha>\\<downharpoonleft> - - \\<alpha> = 2 * x * pi\"\n    using canon_ang(3)[of \\<alpha>]\n    by (metis minus_diff_eq minus_diff_minus)\nnext\n  show \"- pi < - \\<downharpoonright>\\<alpha>\\<downharpoonleft> \\<and> - \\<downharpoonright>\\<alpha>\\<downharpoonleft> \\<le> pi\"\n    using canon_ang(1)[of \\<alpha>] canon_ang(2)[of \\<alpha>] assms\n    by auto\nqed\n\nlemma canon_ang_uminus_pi:\n  assumes \"\\<downharpoonright>\\<alpha>\\<downharpoonleft> = pi\"\n  shows \"\\<downharpoonright>-\\<alpha>\\<downharpoonleft> = \\<downharpoonright>\\<alpha>\\<downharpoonleft>\"\nproof (rule canon_ang_eqI)\n  obtain k::int where \"\\<alpha> - \\<downharpoonright>\\<alpha>\\<downharpoonleft> = 2 * k * pi\"\n    using canon_ang(3)[of \\<alpha>]\n    by auto\n  thus \"\\<exists>x::int. \\<downharpoonright>\\<alpha>\\<downharpoonleft> - - \\<alpha> = 2 * x * pi\"\n    using assms\n    by (rule_tac x=\"k+(1::int)\" in exI) (auto simp add: field_simps)\nnext\n  show \"- pi < \\<downharpoonright>\\<alpha>\\<downharpoonleft> \\<and> \\<downharpoonright>\\<alpha>\\<downharpoonleft> \\<le> pi\"\n    using assms\n    by auto\nqed\n\ntext \\<open>Canonical angle of difference of two angles\\<close>\nlemma canon_ang_diff:\n  shows \"\\<downharpoonright>\\<alpha> - \\<beta>\\<downharpoonleft> = \\<downharpoonright>\\<downharpoonright>\\<alpha>\\<downharpoonleft> - \\<downharpoonright>\\<beta>\\<downharpoonleft>\\<downharpoonleft>\"\nproof (rule canon_ang_eq)\n  show \"\\<exists>x::int. \\<alpha> - \\<beta> - (\\<downharpoonright>\\<alpha>\\<downharpoonleft> - \\<downharpoonright>\\<beta>\\<downharpoonleft>) = 2 * x * pi\"\n  proof-\n    obtain k1::int where \"\\<alpha> - \\<downharpoonright>\\<alpha>\\<downharpoonleft> = 2*k1*pi\"\n      using canon_ang(3)\n      by auto\n    moreover\n    obtain k2::int where \"\\<beta> - \\<downharpoonright>\\<beta>\\<downharpoonleft> = 2*k2*pi\"\n      using canon_ang(3)\n      by auto\n    ultimately\n    show ?thesis\n      by (rule_tac x=\"k1 - k2\" in exI) (auto simp add: field_simps)\n  qed\nqed\n\ntext \\<open>Canonical angle of sum of two angles\\<close>\nlemma canon_ang_sum:\n  shows \"\\<downharpoonright>\\<alpha> + \\<beta>\\<downharpoonleft> = \\<downharpoonright>\\<downharpoonright>\\<alpha>\\<downharpoonleft> + \\<downharpoonright>\\<beta>\\<downharpoonleft>\\<downharpoonleft>\"\nproof (rule canon_ang_eq)\n  show \"\\<exists>x::int. \\<alpha> + \\<beta> - (\\<downharpoonright>\\<alpha>\\<downharpoonleft> + \\<downharpoonright>\\<beta>\\<downharpoonleft>) = 2 * x * pi\"\n  proof-\n    obtain k1::int where \"\\<alpha> - \\<downharpoonright>\\<alpha>\\<downharpoonleft> = 2*k1*pi\"\n      using canon_ang(3)\n      by auto\n    moreover\n    obtain k2::int where \"\\<beta> - \\<downharpoonright>\\<beta>\\<downharpoonleft> = 2*k2*pi\"\n      using canon_ang(3)\n      by auto\n    ultimately\n    show ?thesis\n      by (rule_tac x=\"k1 + k2\" in exI) (auto simp add: field_simps)\n  qed\nqed\n\ntext \\<open>Canonical angle of angle from $(0, 2\\pi]$ shifted by $\\pi$\\<close>\n\nlemma canon_ang_plus_pi1:\n  assumes \"0 < \\<alpha>\" and \"\\<alpha> \\<le> 2*pi\"\n  shows \"\\<downharpoonright>\\<alpha> + pi\\<downharpoonleft> = \\<alpha> - pi\"\nproof (rule canon_ang_eqI)\n  show \"\\<exists> x::int. \\<alpha> - pi - (\\<alpha> + pi) = 2 * x * pi\"\n    by (rule_tac x=\"-1\" in exI) auto\nnext\n  show \"- pi < \\<alpha> - pi \\<and> \\<alpha> - pi \\<le> pi\"\n    using assms\n    by auto\nqed\n\nlemma canon_ang_minus_pi1:\n  assumes \"0 < \\<alpha>\" and \"\\<alpha> \\<le> 2*pi\"\n  shows \"\\<downharpoonright>\\<alpha> - pi\\<downharpoonleft> = \\<alpha> - pi\"\nproof (rule canon_ang_id)\n  show \"- pi < \\<alpha> - pi \\<and> \\<alpha> - pi \\<le> pi\"\n    using assms\n    by auto\nqed\n\ntext \\<open>Canonical angle of angles from $(-2\\pi, 0]$ shifted by $\\pi$\\<close>\n\nlemma canon_ang_plus_pi2:\n  assumes \"-2*pi < \\<alpha>\" and \"\\<alpha> \\<le> 0\"\n  shows \"\\<downharpoonright>\\<alpha> + pi\\<downharpoonleft> = \\<alpha> + pi\"\nproof (rule canon_ang_id)\n  show \"- pi < \\<alpha> + pi \\<and> \\<alpha> + pi \\<le> pi\"\n    using assms\n    by auto\nqed\n\nlemma canon_ang_minus_pi2:\n  assumes \"-2*pi < \\<alpha>\" and \"\\<alpha> \\<le> 0\"\n  shows \"\\<downharpoonright>\\<alpha> - pi\\<downharpoonleft> = \\<alpha> + pi\"\nproof (rule canon_ang_eqI)\n  show \"\\<exists> x::int. \\<alpha> + pi - (\\<alpha> - pi) = 2 * x * pi\"\n    by (rule_tac x=\"1\" in exI) auto\nnext\n  show \"- pi < \\<alpha> + pi \\<and> \\<alpha> + pi \\<le> pi\"\n    using assms\n    by auto\nqed\n\ntext \\<open>Canonical angle of angle in $(\\pi, 3\\pi]$.\\<close>\nlemma canon_ang_pi_3pi: \n  assumes \"pi < \\<alpha>\" and \"\\<alpha> \\<le> 3 * pi\"\n  shows \"\\<downharpoonright>\\<alpha>\\<downharpoonleft> = \\<alpha> - 2*pi\"\nproof-\n  have \"\\<exists>x. - pi = pi * real_of_int x\"\n    by (rule_tac x=\"-1\" in exI, simp)\n  thus ?thesis\n    using assms canon_ang_eqI[of \"\\<alpha> - 2*pi\" \"\\<alpha>\"]\n    by auto\nqed\n\ntext \\<open>Canonical angle of angle in $(-3\\pi, -\\pi]$.\\<close>\nlemma canon_ang_minus_3pi_minus_pi: \n  assumes \"-3*pi < \\<alpha>\" and \"\\<alpha> \\<le> -pi\"\n  shows \"\\<downharpoonright>\\<alpha>\\<downharpoonleft> = \\<alpha> + 2*pi\"\nproof-\n  have \"\\<exists>x. pi = pi * real_of_int x\"\n    by (rule_tac x=\"1\" in exI, simp)\n  thus ?thesis\n    using assms canon_ang_eqI[of \"\\<alpha> + 2*pi\" \"\\<alpha>\"]\n    by auto\nqed\n\ntext \\<open>Canonical angles for some special angles\\<close>\n\nlemma zero_canonical [simp]:\n  shows \"\\<downharpoonright>0\\<downharpoonleft> = 0\"\n  using canon_ang_eqI[of 0 0]\n  by simp\n\nlemma pi_canonical [simp]:\n  shows \"\\<downharpoonright>pi\\<downharpoonleft> = pi\"\n  by (simp add: canon_ang_id)\n\nlemma two_pi_canonical [simp]:\n  shows \"\\<downharpoonright>2 * pi\\<downharpoonleft> = 0\"\n  using canon_ang_plus_pi1[of \"pi\"]\n  by simp\n\ntext \\<open>Canonization preserves sine and cosine\\<close>\nlemma canon_ang_sin [simp]:\n  shows \"sin \\<downharpoonright>\\<alpha>\\<downharpoonleft> = sin \\<alpha>\"\nproof-\n  obtain x::int where \"\\<alpha> = \\<downharpoonright>\\<alpha>\\<downharpoonleft> + pi * (x * 2)\"\n    using canon_ang(3)[of \\<alpha>]\n    by (auto simp add: field_simps)\n  thus ?thesis\n    using sin_periodic_int[of \"\\<downharpoonright>\\<alpha>\\<downharpoonleft>\" x]\n    by (simp add: field_simps)\nqed\n\nlemma canon_ang_cos [simp]:\n  shows \"cos \\<downharpoonright>\\<alpha>\\<downharpoonleft> = cos \\<alpha>\"\nproof-\n  obtain x::int where \"\\<alpha> = \\<downharpoonright>\\<alpha>\\<downharpoonleft> + pi * (x * 2)\"\n    using canon_ang(3)[of \\<alpha>]\n    by (auto simp add: field_simps)\n  thus ?thesis\n    using cos_periodic_int[of \"\\<downharpoonright>\\<alpha>\\<downharpoonleft>\" x]\n    by (simp add: field_simps)\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/Canonical_Angle.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8807970811069351, "lm_q2_score": 0.8333245973817158, "lm_q1q2_score": 0.7339898729884272}}
{"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.*)\n  theory TIP_prop_29\n  imports \"../../Test_Base\"\nbegin\n\ndatatype 'a list = nil2 | cons2 \"'a\" \"'a list\"\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 qrev :: \"'a list => 'a list => 'a list\" where\n  \"qrev (nil2) z = z\"\n| \"qrev (cons2 z2 xs) z = qrev xs (cons2 z2 z)\"\n\nlemma app_assoc: \"x (x y z) w = x y (x z w)\" by (induction y, auto)\nlemma qrev_rev: \"qrev y z = x (rev y) z\"\n  apply(induction y arbitrary: z, auto)\n  apply(simp add: app_assoc)\n  done\nlemma app_nil: \"x y nil2 = y\" by(induction y, auto)\nlemma rev_app: \"rev (x y z) = x (rev z) (rev y)\" \n  apply(induction y, auto)\n   apply(simp add: app_nil) \n  using app_assoc apply(auto)\n  done\ntheorem property0 :\n  \"((rev (qrev y (nil2))) = y)\"\n  apply(induction y, auto)\n  apply(simp add: qrev_rev)\n  apply(simp add: rev_app)\n  done\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_29.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970873650401, "lm_q2_score": 0.8333245891029457, "lm_q1q2_score": 0.7339898709115434}}
{"text": "(*\n  File: FixedPt.thy\n  Author: Bohua Zhan\n\n  Fixed point theorems, roughly following FixedPt in Isabelle/ZF.\n*)\n\ntheory FixedPt\n  imports OrderRel\nbegin\n\n(* h is a function from Pow(D) to itself, and is monotone in the sense that\n   given two subsets W and X of D such that W \\<subseteq> X, then h(W) \\<subseteq> h(X). *)\ndefinition bnd_mono :: \"i \\<Rightarrow> (i \\<Rightarrow> i) \\<Rightarrow> o\" where [rewrite]:\n  \"bnd_mono(D,h) \\<longleftrightarrow> (h(D) \\<subseteq> D \\<and> (\\<forall>W X. W \\<subseteq> X \\<longrightarrow> X \\<subseteq> D \\<longrightarrow> h(W) \\<subseteq> h(X)))\"\n\n(* Least fixed point of h. *)\ndefinition lfp :: \"i \\<Rightarrow> (i \\<Rightarrow> i) \\<Rightarrow> i\" where [rewrite]:\n  \"lfp(D,h) = \\<Inter>({X \\<in> Pow(D). h(X) \\<subseteq> X})\"\nsetup {* add_prfstep_check_req (\"lfp(D,h)\", \"bnd_mono(D,h)\") *}\n\n(* Greatest fixed point of h. *)\ndefinition gfp :: \"i \\<Rightarrow> (i \\<Rightarrow> i) \\<Rightarrow> i\" where [rewrite]:\n  \"gfp(D,h) = \\<Union>({X \\<in> Pow(D). X \\<subseteq> h(X)})\"\n\nsection \\<open>Monotone operators\\<close>\n\nlemma bnd_monoD1 [forward]: \"bnd_mono(D,h) \\<Longrightarrow> h(D) \\<subseteq> D\" by auto2\nlemma bnd_monoD2 [backward2]: \"bnd_mono(D,h) \\<Longrightarrow> W \\<subseteq> X \\<Longrightarrow> X \\<subseteq> D \\<Longrightarrow> h(W) \\<subseteq> h(X)\" by auto2\nsetup {* del_prfstep_thm_eqforward @{thm bnd_mono_def} *}\n\nlemma bnd_mono_subset: \"bnd_mono(D,h) \\<Longrightarrow> X \\<subseteq> D \\<Longrightarrow> h(X) \\<subseteq> D\" by auto2\nlemma bnd_mono_Un: \"bnd_mono(D,h) \\<Longrightarrow> A \\<subseteq> D \\<Longrightarrow> B \\<subseteq> D \\<Longrightarrow> h(A) \\<union> h(B) \\<subseteq> h(A \\<union> B)\" by auto2\n\nsection \\<open>Knaster-Tarski Theorem using lfp\\<close>\n\nlemma lfp_set_nonempty [backward2]:\n  \"h(A) \\<subseteq> A \\<Longrightarrow> A \\<subseteq> D \\<Longrightarrow> {X \\<in> Pow(D). h(X) \\<subseteq> X} \\<noteq> \\<emptyset>\"\n@proof @have \"A \\<in> {X \\<in> Pow(D). h(X) \\<subseteq> X}\" @qed\n\n(* lfp(D,h) is a subset of any fixed point of h. *)\nlemma lfp_lowerbound [backward]:\n  \"h(A) \\<subseteq> A \\<Longrightarrow> A \\<subseteq> D \\<Longrightarrow> lfp(D,h) \\<subseteq> A\" by auto2\n\n(* If A is a subset of any fixed point of h, then A is a subset of lfp(D,h). *)\nlemma lfp_greatest [backward2]:\n  \"h(D) \\<subseteq> D \\<Longrightarrow> \\<forall>X. h(X) \\<subseteq> X \\<longrightarrow> X \\<subseteq> D \\<longrightarrow> A \\<subseteq> X \\<Longrightarrow> A \\<subseteq> lfp(D,h)\" by auto2\n\n(* lfp is indeed a fixed point of h. *)\nlemma lfp_unfold [rewrite]:\n  \"bnd_mono(D,h) \\<Longrightarrow> h(lfp(D,h)) = lfp(D,h)\"\n@proof @have  \"h(lfp(D,h)) \\<subseteq> lfp(D,h)\" @qed\n\nsection \\<open>General induction rule for least fixed points\\<close>\n\n(* Induction rule: given predicate P and let A be the subset of lfp that satisfies P.\n   If everything in h(A) also satisfies P, then in fact A = lfp. *)\nlemma lfp_induct [script_induct]:\n  \"a \\<in> lfp(D,h) \\<Longrightarrow> bnd_mono(D,h) \\<Longrightarrow> \\<forall>x\\<in>h(Collect(lfp(D,h),P)). P(x) \\<Longrightarrow> P(a)\"\n@proof @have \"h(Collect(lfp(D,h),P)) \\<subseteq> lfp(D,h)\" @qed\n\nlemma lfp_Int_lowerbound [backward1]:\n  \"bnd_mono(D,h) \\<Longrightarrow> h(D \\<inter> A) \\<subseteq> A \\<Longrightarrow> lfp(D,h) \\<subseteq> A\" by auto2\n\nlemma lfp_mono:\n  \"bnd_mono(D,h) \\<Longrightarrow> bnd_mono(E,i) \\<Longrightarrow> \\<forall>X. X \\<subseteq> D \\<longrightarrow> h(X) \\<subseteq> i(X) \\<Longrightarrow>\n   lfp(D,h) \\<subseteq> lfp(E,i)\"\n@proof\n  @have \"\\<forall>X. i(X) \\<subseteq> X \\<longrightarrow> X \\<subseteq> E \\<longrightarrow> lfp(D,h) \\<subseteq> X\" @with\n    @have \"h(D \\<inter> X) \\<subseteq> X\" @with @have \"h(D \\<inter> X) \\<subseteq> i(D \\<inter> X)\" @end @end\n@qed\n\nlemma lfp_cong:\n  \"\\<forall>X. X \\<subseteq> D \\<longrightarrow> h(X) = h'(X) \\<Longrightarrow> lfp(D,h) = lfp(D,h')\" by auto2\nsetup {* del_prfstep_thm @{thm lfp_def} *}\n\nsection \\<open>Knaster-Tarski Theorem using gfp\\<close>\n\n(* Any fixed point of h is contained in gfp(D,h). *)\nlemma gfp_upperbound [backward]:\n  \"A \\<subseteq> h(A) \\<Longrightarrow> A \\<subseteq> D \\<Longrightarrow> A \\<subseteq> gfp(D,h)\" by auto2\n\n(* If A contains any fixed point of h, then A contains gfp(D,h). *)\nlemma gfp_least [backward2]:\n  \"h(D) \\<subseteq> D \\<Longrightarrow> \\<forall>X. X \\<subseteq> h(X) \\<longrightarrow> X \\<subseteq> D \\<longrightarrow> X \\<subseteq> A \\<Longrightarrow> gfp(D,h) \\<subseteq> A\" by auto2\n\n(* gfp is indeed a fixed point of h. *)\nlemma gfp_unfold [rewrite]:\n  \"bnd_mono(D,h) \\<Longrightarrow> h(gfp(D,h)) = gfp(D,h)\"\n@proof @have \"gfp(D,h) \\<subseteq> h(gfp(D,h))\" @qed\n\nsection \\<open>General induction rule for greatest fixed points\\<close>\n\nlemma gfp_weak_coinduct:\n  \"a \\<in> X \\<Longrightarrow> X \\<subseteq> h(X) \\<Longrightarrow> X \\<subseteq> D \\<Longrightarrow> a \\<in> gfp(D,h)\" by auto2\n\nlemma gfp_coinduct_lemma [backward1]:\n  \"X \\<subseteq> D \\<Longrightarrow> bnd_mono(D,h) \\<Longrightarrow> X \\<subseteq> h(X \\<union> gfp(D,h)) \\<Longrightarrow> X \\<union> gfp(D,h) \\<subseteq> h(X \\<union> gfp(D,h))\" by auto2\n\nlemma gfp_coinduct:\n  \"bnd_mono(D,h) \\<Longrightarrow> a \\<in> X \\<Longrightarrow> X \\<subseteq> h(X \\<union> gfp(D,h)) \\<Longrightarrow> X \\<subseteq> D \\<Longrightarrow> a \\<in> gfp(D,h)\" by auto2\n\nlemma gfp_mono:\n  \"bnd_mono(D,h) \\<Longrightarrow> D \\<subseteq> E \\<Longrightarrow> \\<forall>X. X \\<subseteq> D \\<longrightarrow> h(X) \\<subseteq> i(X) \\<Longrightarrow> gfp(D,h) \\<subseteq> gfp(E,i)\" by auto2\nsetup {* del_prfstep_thm @{thm gfp_def} *}\n\nsection \\<open>Transitive closure\\<close>\n\ndefinition rtrans_cl :: \"i \\<Rightarrow> i\" where [rewrite]:\n  \"rtrans_cl(r) = lfp(gr_field(r)\\<times>gr_field(r), \\<lambda>s. gr_id(gr_field(r)) \\<union> (r \\<circ>\\<^sub>g s))\"\n\nlemma rtrans_cl_bnd_mono [resolve]:\n  \"bnd_mono(gr_field(r)\\<times>gr_field(r), \\<lambda>s. gr_id(gr_field(r)) \\<union> (r \\<circ>\\<^sub>g s))\" by auto2\n\nlemma rtrans_cl_eq [rewrite]:\n  \"rtrans_cl(r) = gr_id(gr_field(r)) \\<union> (r \\<circ>\\<^sub>g rtrans_cl(r))\" by auto2\n\nlemma rtrans_cl_is_graph [forward]: \"is_graph(r) \\<Longrightarrow> is_graph(rtrans_cl(r))\" by auto2\nlemma rtrans_clI1 [typing2]: \"a \\<in> gr_field(r) \\<Longrightarrow> \\<langle>a,a\\<rangle>\\<in>rtrans_cl(r)\" by auto2\nlemma rtrans_clI2 [typing2]: \"\\<langle>a,b\\<rangle> \\<in> r \\<Longrightarrow> \\<langle>a,b\\<rangle> \\<in> rtrans_cl(r)\" by auto2\nlemma rtrans_clI3 [forward]: \"\\<langle>a,b\\<rangle>\\<in>rtrans_cl(r) \\<Longrightarrow> \\<langle>b,c\\<rangle>\\<in>r \\<Longrightarrow> \\<langle>a,c\\<rangle>\\<in>rtrans_cl(r)\" by auto2\n\nlemma rtrans_cl_full_induct [script_induct]:\n  \"x \\<in> rtrans_cl(r) \\<Longrightarrow> \\<forall>x\\<in>gr_field(r). P(\\<langle>x,x\\<rangle>) \\<Longrightarrow>\n   \\<forall>x y z. P(\\<langle>x,y\\<rangle>) \\<longrightarrow> \\<langle>x,y\\<rangle>\\<in>rtrans_cl(r) \\<longrightarrow> \\<langle>y,z\\<rangle>\\<in>r \\<longrightarrow> P(\\<langle>x,z\\<rangle>) \\<Longrightarrow> P(x)\"\n@proof\n  @induct \"x \\<in> lfp(gr_field(r)\\<times>gr_field(r), \\<lambda>s. gr_id(gr_field(r)) \\<union> (r \\<circ>\\<^sub>g s))\" \"P(x)\"\n@qed\nsetup {* del_prfstep_thm @{thm rtrans_cl_def} *}\n\nlemma rtrans_cl_induct [script_induct]:\n  \"\\<langle>a,b\\<rangle> \\<in> rtrans_cl(r) \\<Longrightarrow>\n   \\<forall>y z. \\<langle>a,y\\<rangle>\\<in>rtrans_cl(r) \\<longrightarrow> \\<langle>y,z\\<rangle>\\<in>r \\<longrightarrow> y \\<noteq> z \\<longrightarrow> P(y) \\<longrightarrow> P(z) \\<Longrightarrow>\n   P(a) \\<Longrightarrow> P(b)\"\n@proof\n  @induct \"\\<langle>a,b\\<rangle> \\<in> rtrans_cl(r)\" \"fst(\\<langle>a,b\\<rangle>) = a \\<longrightarrow> P(snd(\\<langle>a,b\\<rangle>))\"\n@qed\nsetup {* delete_script_induct_data @{thm rtrans_cl_full_induct} *}\n\nlemma rtrans_cl_trans [forward]:\n  \"\\<langle>c,a\\<rangle>\\<in>rtrans_cl(r) \\<Longrightarrow> \\<langle>a,b\\<rangle>\\<in>rtrans_cl(r) \\<Longrightarrow> \\<langle>c,b\\<rangle>\\<in>rtrans_cl(r)\"\n@proof\n  @induct \"\\<langle>a,b\\<rangle> \\<in> rtrans_cl(r)\" \"\\<langle>c,b\\<rangle>\\<in>rtrans_cl(r)\"\n@qed\nsetup {* del_prfstep_thm @{thm rtrans_cl_eq} *}\n\ndefinition rel_rtrans_cl :: \"i \\<Rightarrow> i\" where [rewrite]:\n  \"rel_rtrans_cl(R) = Order(carrier(R), \\<lambda>x y. \\<langle>x,y\\<rangle> \\<in> rtrans_cl(order_graph(R)))\"\n\nlemma rel_rtrans_cl_is_rel [typing]:\n  \"raworder(R) \\<Longrightarrow> rel_rtrans_cl(R) \\<in> raworder_space(carrier(R))\" by auto2\n\nlemma rel_rtrans_clI1:\n  \"raworder(R) \\<Longrightarrow> x \\<le>\\<^sub>R y \\<Longrightarrow> le(rel_rtrans_cl(R),x,y)\"\n@proof @have \"\\<langle>x,y\\<rangle> \\<in> order_graph(R)\" @qed\nsetup {* add_forward_prfstep_cond @{thm rel_rtrans_clI1} [with_term \"rel_rtrans_cl(?R)\"] *}\n\nlemma rel_rtrans_clI2 [forward]: \"raworder(R) \\<Longrightarrow> trans(rel_rtrans_cl(R))\" by auto2\nlemma rel_rtrans_clI3 [forward]: \"refl_order(R) \\<Longrightarrow> preorder(rel_rtrans_cl(R))\"\n@proof\n  @let \"S = rel_rtrans_cl(R)\"\n  @have \"\\<forall>x\\<in>.S. x \\<le>\\<^sub>S x\" @with @have \"\\<langle>x,x\\<rangle> \\<in> order_graph(R)\" @end\n@qed\n\nlemma rel_rtrans_cl_induct [script_induct]:\n  \"le(rel_rtrans_cl(R),a,b) \\<Longrightarrow> raworder(R) \\<Longrightarrow>\n   \\<forall>y z. le(rel_rtrans_cl(R),a,y) \\<longrightarrow> y <\\<^sub>R z \\<longrightarrow> P(y) \\<longrightarrow> P(z) \\<Longrightarrow> P(a) \\<Longrightarrow> P(b)\"\n@proof\n  @induct \"\\<langle>a,b\\<rangle>\\<in>rtrans_cl(order_graph(R))\" \"P(b)\"\n@qed\n\nsetup {* del_prfstep_thm @{thm rel_rtrans_cl_def} *}\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/FixedPt.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.880797071719777, "lm_q2_score": 0.8333246015211008, "lm_q1q2_score": 0.7339898688118356}}
{"text": "theory Interval_Help\n  imports \"HOL-Library.Interval\" \"HOL-Decision_Procs.Approximation_Bounds\"\n\nbegin\n\nsection \"General Lemmas on Intervals\"\n\ndefinition Interval'' where\n\"Interval'' = (\\<lambda>(l,u). if (l :: 'a :: linorder) \\<le> u then Interval (l, u) else Interval (u, l))\"\n\nlemma normal_interval'': \"l \\<le> u \\<Longrightarrow> Interval'' (l, u) = Interval (l, u)\" unfolding Interval''_def by simp\n\ndefinition closed_real_segment :: \"real \\<Rightarrow> real \\<Rightarrow> real set\" where\n\"closed_real_segment a b = (if a \\<le> b then {a..b} else {b..a})\"\n\nlemma lower_Interval[simp]: \"l \\<le> u \\<Longrightarrow> lower (Interval (l, u)) = l\"\nby (metis Ivl.rep_eq bounds_of_interval_inverse fst_conv lower.rep_eq min_def)\n\nlemma upper_Interval[simp]: \"l \\<le> u \\<Longrightarrow> upper (Interval (l, u)) = u\"\nby (simp add: Interval_inverse upper.rep_eq)\n\nlemma set_of_Interval: \"l \\<le> u \\<Longrightarrow> set_of (Interval (l, u)) = {l..u}\"\n  by (simp add: set_of_eq)\n\nlemma sign_of_element: \"upper ivl < 0 \\<Longrightarrow> \\<forall>x \\<in> set_of ivl. x < 0\"\n  by (metis atLeastAtMost_iff le_less_trans set_of_eq)\n\nlemma sign_of_element': \"0 < lower ivl \\<Longrightarrow> \\<forall>x \\<in> set_of ivl. 0 < x\"\n  by (simp add: less_le_trans set_of_eq)\n\nsection \"Lemmas and Definitions on Real Intervals\"\nsubsection \"General\"\n\n(* inverse, iff 0 \\<notin> ivl, this is guaranteed in the implementation *)\ndefinition inverse_interval' :: \"real interval \\<Rightarrow> real interval\" where\n\"inverse_interval' ivl = Interval (inverse (upper ivl), inverse (lower ivl))\"\n\nlemma inverse_in_inverse_interval': \"x \\<in> set_of ivl \\<and> 0 \\<notin> set_of ivl \\<Longrightarrow> inverse x \\<in> set_of (inverse_interval' ivl)\"\n  by (smt atLeastAtMost_iff inverse_interval'_def le_imp_inverse_le le_imp_inverse_le_neg lower_Interval set_of_eq upper_Interval)\n\nfun set_of_interval_list:: \"real interval list \\<Rightarrow> real set\" where\n\"set_of_interval_list (ivl#ivls) = set_of ivl \\<union> set_of_interval_list ivls\" |\n\"set_of_interval_list [] = {}\"\n\nlemma in_interval_in_set_of_interval_list: \"x \\<in> set_of ivl \\<Longrightarrow> x \\<in> set_of_interval_list (ivls @ ivl # ivls')\"\n  by (induct ivls) auto\n\nlemma in_larger_interval_list_set_l: \"x \\<in> set_of_interval_list ivls \\<Longrightarrow> x \\<in> set_of_interval_list (ivls' @ ivls)\"\n  by (induct ivls') auto\n\nlemma in_larger_interval_list_set_r: \"x \\<in> set_of_interval_list ivls \\<Longrightarrow> x \\<in> set_of_interval_list (ivls @ ivls')\"\n  by (induct ivls) auto\n\nsubsection \"Intersections and Split\"\n\n(* ivl \\<inter> ivl' *)\ndefinition interval_intersection:: \"real interval \\<Rightarrow> real interval \\<Rightarrow> real interval list\" where\n\"interval_intersection ivl ivl' = (\n  if upper ivl' < lower ivl \\<or> upper ivl < lower ivl' then []\n  else [Interval (max (lower ivl) (lower ivl'), min (upper ivl) (upper ivl'))]\n)\"\n\n(* x \\<in> ivl \\<and> x \\<in> ivl' \\<Longrightarrow> ivl \\<inter> ivl' *)\nlemma in_both_intervals_in_intersection:\n  assumes \"x \\<in> set_of ivl\" \"x \\<in> set_of ivl'\"\n  shows \"x \\<in> set_of_interval_list (interval_intersection ivl ivl')\"\nproof -\n  have order: \"lower ivl \\<le> x \\<and> x \\<le> upper ivl \\<and> lower ivl' \\<le> x \\<and> x \\<le> upper ivl'\" using assms(1) assms(2) by (simp add: set_of_eq)\n  then have \"x \\<in> set_of (Interval (max (lower ivl) (lower ivl'), min (upper ivl) (upper ivl')))\" by (simp add: set_of_eq)\n  then show ?thesis using in_interval_in_set_of_interval_list interval_intersection_def order by auto\nqed\n\n(* ivl \\<inter> [l,\\<infinity>) *)\ndefinition interval_intersection_unbounded_upper:: \"real interval \\<Rightarrow> real \\<Rightarrow> real interval list\" where\n\"interval_intersection_unbounded_upper ivl l = (\n  if upper ivl < l then []\n  else [Interval (max (lower ivl) l, upper ivl)]\n)\"\n\n(* x \\<in> ivl \\<and> x \\<in> [l,\\<infinity>) \\<Longrightarrow> ivl \\<inter> [l,\\<infinity>) *)\nlemma in_both_intervals_in_uu_intersection:\n  assumes \"x \\<in> set_of ivl\" \"l \\<le> x\"\n  shows \"x \\<in> set_of_interval_list (interval_intersection_unbounded_upper ivl l)\"\nproof -\n  have \"lower ivl \\<le> x \\<and> x \\<le> upper ivl\" using assms(1) by (simp add: set_of_eq)\n  then have \"max (lower ivl) l \\<le> x \\<and> x \\<le> upper ivl\" by (simp add: assms(2))\n  then show ?thesis using interval_intersection_unbounded_upper_def by (simp add: set_of_eq)\nqed\n\n(* (\\<infinity>,u] \\<inter> ivl *)\ndefinition interval_intersection_unbounded_lower:: \"real interval \\<Rightarrow> real \\<Rightarrow> real interval list\" where\n\"interval_intersection_unbounded_lower ivl u = (\n  if u < lower ivl then []\n  else [Interval (lower ivl, min (upper ivl) u)]\n)\"\n\n(* x \\<in> (\\<infinity>,u] \\<and> x \\<in> ivl \\<Longrightarrow> (\\<infinity>,u] \\<inter> ivl *)\nlemma in_both_intervals_in_ul_intersection:\n  assumes \"x \\<in> set_of ivl\" \"x \\<le> u\"\n  shows \"x \\<in> set_of_interval_list (interval_intersection_unbounded_lower ivl u)\"\nproof -\n  have \"lower ivl \\<le> x \\<and> x \\<le> upper ivl\" using assms(1) by (simp add: set_of_eq)\n  then have \"lower ivl \\<le> x \\<and> x \\<le> min (upper ivl) u\" by (simp add: assms(2))\n  then show ?thesis using interval_intersection_unbounded_lower_def by (simp add: set_of_eq)\nqed\n\n(* m \\<in> [l,u] \\<Longrightarrow> [l,u] \\<leadsto> [l,m],[m,u] *)\ndefinition split_interval:: \"real interval \\<Rightarrow> real \\<Rightarrow> real interval list\" where\n\"split_interval ivl m = (if m \\<in> set_of ivl then [Interval (lower ivl, m), Interval (m, upper ivl)] else [ivl])\"\n\n(* m \\<in> [l,u] \\<Longrightarrow> [l,u] = [l,m] \\<union> [m,u] *)\nlemma split_same_set: \"set_of ivl = set_of_interval_list (split_interval ivl m)\"\nproof (cases \"m \\<in> set_of ivl\")\ncase True\n  show ?thesis\n  proof\n    show \"set_of ivl \\<subseteq> set_of_interval_list (split_interval ivl m)\"\n    proof\n      fix x\n      assume x: \"x \\<in> set_of ivl\"\n      then have \"lower ivl \\<le> x \\<and> x \\<le> upper ivl \\<and> m \\<le> x \\<or> x \\<le> m\" by (auto simp: set_of_eq)\n      then have \"lower ivl \\<le> x \\<and> x \\<le> m \\<or> m \\<le> x \\<and> x \\<le> upper ivl\" using set_of_eq x by fastforce \n      then show \"x \\<in> set_of_interval_list (split_interval ivl m)\" using True split_interval_def by (simp add: set_of_eq)\n    qed\n  next\n    show \"set_of_interval_list (split_interval ivl m) \\<subseteq> set_of ivl\"\n    proof\n      fix x\n      assume \"x \\<in> set_of_interval_list (split_interval ivl m)\"\n      then have \"lower ivl \\<le> x \\<and> x \\<le> m \\<or> m \\<le> x \\<and> x \\<le> upper ivl\" using True split_interval_def by (simp add: set_of_eq)\n      then have \"lower ivl \\<le> x \\<and> x \\<le> upper ivl\" using True atLeastAtMost_iff by (auto simp: set_of_eq)\n      then show \"x \\<in> set_of ivl\" by (simp add: set_of_eq)\n    qed\n  qed\nnext\n  case False\n  then show ?thesis using split_interval_def by simp\nqed\n\nsection \"Lemmas and Definitions on Float Intervals\"\nsubsection \"General\"\n\n(* inverse, iff 0 \\<notin> ivl; inverse_float_interval without option *)\ndefinition inverse_float_interval':: \"nat \\<Rightarrow> float interval \\<Rightarrow> float interval\" where\n\"inverse_float_interval' prec ivl = Interval'' (float_divl prec 1 (upper ivl), float_divr prec 1 (lower ivl))\"\n\nfun set_of_float_interval_list:: \"float interval list \\<Rightarrow> float set\" where\n\"set_of_float_interval_list (ivl#ivls) = set_of ivl \\<union> set_of_float_interval_list ivls\" |\n\"set_of_float_interval_list [] = {}\"\n\nlemma in_float_interval_in_set_of_float_interval_list: \"x \\<in> set_of ivl \\<Longrightarrow> x \\<in> set_of_float_interval_list (ivls @ ivl # ivls')\"\n  by (induct ivls) auto\n\nlemma in_larger_float_interval_list_set_l: \"x \\<in> set_of_float_interval_list ivls \\<Longrightarrow> x \\<in> set_of_float_interval_list (ivls' @ ivls)\"\n  by (induct ivls') auto\n\nlemma in_larger_float_interval_list_set_r: \"x \\<in> set_of_float_interval_list ivls \\<Longrightarrow> x \\<in> set_of_float_interval_list (ivls @ ivls')\"\n  by (induct ivls) auto\n\nlemma in_float_interval_list_in_set_of_float_interval:\n  \"x \\<in> set_of_float_interval_list ivls \\<Longrightarrow> \\<exists>i. x \\<in> set_of (ivls ! i) \\<and> i < length ivls\"\nproof (induction ivls)\n  case Nil\n  then show ?case by simp\nnext\n  case (Cons ivl ivls)\n  then show ?case\n  proof (cases \"x \\<in> set_of ivl\")\n    case True\n    then have \"x \\<in> set_of ((ivl # ivls) ! 0) \\<and> 0 < length (ivl # ivls)\" by simp\n    then show ?thesis by blast\n  next\n    case False\n    then obtain i where i: \"x \\<in> set_of (ivls ! i)\" \"i < length ivls\"  using Cons.IH Cons.prems by auto\n    then have \"x \\<in> set_of ((ivl # ivls) ! (i + 1)) \\<and> (i + 1) < length (ivl # ivls)\" by auto\n    then show ?thesis by blast \n  qed\nqed\n\nfun real_set_of_float_interval_list:: \"float interval list \\<Rightarrow> real set\" where\n\"real_set_of_float_interval_list (ivl#ivls) = set_of (real_interval ivl) \\<union> real_set_of_float_interval_list ivls\" |\n\"real_set_of_float_interval_list [] = {}\"\n\nlemma in_float_interval_in_real_set_of_float_interval_list: \"x \\<in> set_of (real_interval ivl) \\<Longrightarrow> x \\<in> real_set_of_float_interval_list (ivls @ ivl # ivls')\"\n  by (induct ivls) auto\n\nlemma in_larger_real_set_of_float_interval_list_l: \"x \\<in> real_set_of_float_interval_list ivls \\<Longrightarrow> x \\<in> real_set_of_float_interval_list (ivls' @ ivls)\"\n  by (induct ivls') auto\n\nlemma in_larger_real_set_of_float_interval_list_r: \"x \\<in> real_set_of_float_interval_list ivls \\<Longrightarrow> x \\<in> real_set_of_float_interval_list (ivls @ ivls')\"\n  by (induct ivls) auto\n\nlemma in_float_interval_list_in_set_of_float_interval':\n  \"x \\<in> real_set_of_float_interval_list ivls \\<Longrightarrow> \\<exists>i. x \\<in> set_of (real_interval (ivls ! i)) \\<and> i < length ivls\"\nproof (induction ivls)\n  case Nil\n  then show ?case by simp\nnext\n  case (Cons ivl ivls)\n  thm Cons.IH\n  then show ?case\n  proof (cases \"x \\<in> set_of (real_interval ivl)\")\n    case True\n    then have \"x \\<in> set_of (real_interval ((ivl # ivls) ! 0)) \\<and> 0 < length (ivl # ivls)\" by simp\n    then show ?thesis by blast\n  next\n    case False\n    then obtain i where i: \"x \\<in> set_of (real_interval (ivls ! i))\" \"i < length ivls\"  using Cons.IH Cons.prems by auto\n    then have \"x \\<in> set_of (real_interval ((ivl # ivls) ! (i + 1))) \\<and> (i + 1) < length (ivl # ivls)\" by auto\n    then show ?thesis by blast\n  qed\nqed\n\nlemma in_rounded_interval_list:\n  \"x \\<in> real_set_of_float_interval_list ivls \\<Longrightarrow> x \\<in> real_set_of_float_interval_list (map (round_interval prec) ivls)\"\n  by (induct ivls) (auto simp: in_round_intervalI)\n\nlemma real_interval_subset:\n  assumes \"ivl \\<le> ivl'\"\n  shows \"real_interval ivl \\<le> real_interval ivl'\"\nproof -\n  have \"lower ivl' \\<le> lower ivl \\<and> upper ivl \\<le> upper ivl'\" using assms using less_eq_interval_def by blast\n  then show ?thesis by (simp add: less_eq_interval_def) \nqed\n\nsubsection \"Definition of plus_float_interval\"\n\ncontext includes interval.lifting\n\nbegin\n\nlift_definition plus_float_interval::\"nat \\<Rightarrow> float interval \\<Rightarrow> float interval \\<Rightarrow> float interval\"\n  is \"\\<lambda>prec. \\<lambda>(a1, a2). \\<lambda>(b1, b2). (float_plus_down prec a1 b1, float_plus_up prec a2 b2)\"\n  by (auto intro!: add_mono simp: float_plus_down_le float_plus_up_le)\n\nlemma lower_plus_float_interval:\n  \"lower (plus_float_interval prec ivl ivl') = float_plus_down prec (lower ivl) (lower ivl')\"\n  by transfer auto\nlemma upper_plus_float_interval:\n  \"upper (plus_float_interval prec ivl ivl') = float_plus_up prec (upper ivl) (upper ivl')\"\n  by transfer auto\n\nlemma plus_float_interval_monotonic:\n  \"set_of (ivl + ivl') \\<subseteq> set_of (plus_float_interval prec ivl ivl')\"\n  using float_plus_down_le float_plus_up_le lower_plus_float_interval upper_plus_float_interval\n  by (simp add: set_of_subset_iff)\n\nlemma plus_float_interval:\n  \"set_of (real_interval A) + set_of (real_interval B) \\<subseteq>\n    set_of (real_interval (plus_float_interval prec A B))\"\nproof\n  fix x\n  assume x: \"x \\<in> set_of (real_interval A) + set_of (real_interval B)\"\n  then have x: \"x \\<in> set_of(real_interval (A + B))\" by (metis plus_in_float_intervalI set_plus_elim) \n  then have \"lower A + lower B \\<le> x \\<and> x \\<le> upper A + upper B\" by (simp add: set_of_eq)\n  then have \"float_plus_down prec (lower A) (lower B) \\<le> x \\<and> x \\<le> float_plus_up prec (upper A) (upper B)\"\n    by (simp add: float_plus_down_le float_plus_up_le)\n  then show \"x \\<in> set_of (real_interval (plus_float_interval prec A B))\"\n    by (simp add: in_intervalI lower_plus_float_interval upper_plus_float_interval) \nqed\n\nlemma plus_float_interval_mono:\n  assumes \"a \\<le> real_interval a'\" \"b \\<le> real_interval b'\"\n  shows   \"a + b \\<le> real_interval (plus_float_interval prec a' b')\"\n  using assms float_plus_down float_plus_up lower_plus_float_interval upper_plus_float_interval\n  by (smt (z3) less_eq_interval_def lower_plus lower_real_interval upper_plus upper_real_interval)\n\nlemma minus_float_interval_monotonic:\n  \"set_of (ivl - ivl') \\<subseteq> set_of (plus_float_interval prec ivl (- ivl'))\"\n  using float_plus_down_le float_plus_up_le lower_plus_float_interval upper_plus_float_interval\n  by (simp add: minus_interval_def plus_float_interval_monotonic)\n\nend\n\nsubsection \"Intersections and Split\"\n\n(* ivl \\<inter> ivl' *)\ndefinition float_interval_intersection:: \"float interval \\<Rightarrow> float interval \\<Rightarrow> float interval list\" where\n\"float_interval_intersection ivl ivl' = (\n  if upper ivl' < lower ivl \\<or> upper ivl < lower ivl' then []\n  else [Interval (max (lower ivl) (lower ivl'), min (upper ivl) (upper ivl'))]\n)\"\n\n(* x \\<in> ivl \\<and> x \\<in> ivl' \\<Longrightarrow> x \\<in> ivl \\<inter> ivl' *)\nlemma in_both_float_intervals_in_float_intersection:\n  assumes \"x \\<in> set_of ivl\" \"x \\<in> set_of ivl'\"\n  shows \"x \\<in> set_of_float_interval_list (float_interval_intersection ivl ivl')\"\nproof -\n  have order: \"lower ivl \\<le> x \\<and> x \\<le> upper ivl \\<and> lower ivl' \\<le> x \\<and> x \\<le> upper ivl'\" using assms(1) assms(2) by (simp add: set_of_eq)\n  then have \"x \\<in> set_of (Interval (max (lower ivl) (lower ivl'), min (upper ivl) (upper ivl')))\"\n    by (metis atLeastAtMost_iff max.bounded_iff min.bounded_iff order.trans set_of_Interval) \n  then show ?thesis using order by (simp add: float_interval_intersection_def)\nqed\n\nlemma in_both_float_intervals_in_float_intersection':\n  assumes \"x \\<in> set_of (real_interval ivl)\" \"x \\<in> set_of (real_interval ivl')\"\n  shows \"x \\<in> real_set_of_float_interval_list (float_interval_intersection ivl ivl')\"\nproof -\n  have order: \"lower ivl \\<le> x \\<and> x \\<le> upper ivl \\<and> lower ivl' \\<le> x \\<and> x \\<le> upper ivl'\" using assms(1) assms(2) by (simp add: set_of_eq)\n  then have \"x \\<in> set_of (real_interval (Interval (max (lower ivl) (lower ivl'), min (upper ivl) (upper ivl'))))\"\n    using in_real_intervalI by auto\n  then show ?thesis using order by (simp add: float_interval_intersection_def)\nqed\n\n(* ivl \\<inter> [l,\\<infinity>) *)\ndefinition float_interval_intersection_unbounded_upper:: \"float interval \\<Rightarrow> float \\<Rightarrow> float interval list\" where\n\"float_interval_intersection_unbounded_upper ivl l = (\n  if upper ivl < l then []\n  else [Interval (max (lower ivl) l, upper ivl)]\n)\"\n\n(* x \\<in> ivl \\<and> x \\<in> [l,\\<infinity>) \\<Longrightarrow> ivl \\<inter> [l,\\<infinity>) *)\nlemma in_both_float_intervals_in_uu_intersection:\n  assumes \"x \\<in> set_of ivl\" \"l \\<le> x\"\n  shows \"x \\<in> set_of_float_interval_list (float_interval_intersection_unbounded_upper ivl l)\"\nproof -\n  have \"lower ivl \\<le> x \\<and> x \\<le> upper ivl\" using assms(1) by (simp add: set_of_eq)\n  then show ?thesis using float_interval_intersection_unbounded_upper_def assms(2) by (auto simp add: set_of_eq)\nqed\n\nlemma in_both_float_intervals_in_uu_intersection':\n  assumes \"x \\<in> set_of (real_interval ivl)\" \"l \\<le> x\"\n  shows \"x \\<in> real_set_of_float_interval_list (float_interval_intersection_unbounded_upper ivl l)\"\nproof -\n  have \"lower ivl \\<le> x \\<and> x \\<le> upper ivl\" using assms(1) by (simp add: set_of_eq)\n  then show ?thesis using float_interval_intersection_unbounded_upper_def assms(2) by (auto simp: set_of_eq)\nqed\n\n(* (\\<infinity>,u] \\<inter> ivl *)\ndefinition float_interval_intersection_unbounded_lower:: \"float interval \\<Rightarrow> float \\<Rightarrow> float interval list\" where\n\"float_interval_intersection_unbounded_lower ivl u = (\n  if u < lower ivl then []\n  else [Interval (lower ivl, min (upper ivl) u)]\n)\"\n\n(* x \\<in> (\\<infinity>,u] \\<and> x \\<in> ivl \\<Longrightarrow> (\\<infinity>,u] \\<inter> ivl *)\nlemma in_both_float_intervals_in_ul_intersection:\n  assumes \"x \\<in> set_of ivl\" \"x \\<le> u\"\n  shows \"x \\<in> set_of_float_interval_list (float_interval_intersection_unbounded_lower ivl u)\"\nproof -\n  have \"lower ivl \\<le> x \\<and> x \\<le> upper ivl\" using assms(1) by (simp add: set_of_eq)\n  then show ?thesis using float_interval_intersection_unbounded_lower_def assms(2) by (auto simp add: set_of_eq)\nqed\n\nlemma in_both_float_intervals_in_ul_intersection':\n  assumes \"x \\<in> set_of (real_interval ivl)\" \"x \\<le> u\"\n  shows \"x \\<in> real_set_of_float_interval_list (float_interval_intersection_unbounded_lower ivl u)\"\nproof -\n  have \"lower ivl \\<le> x \\<and> x \\<le> upper ivl\" using assms(1) by (simp add: set_of_eq)\n  then show ?thesis using float_interval_intersection_unbounded_lower_def assms(2) by (auto simp add: set_of_eq)\nqed\n\n(* x \\<in> (\\<infinity>,u] \\<and> x \\<in> ivl \\<Longrightarrow> (\\<infinity>,u] \\<inter> ivl *)\ndefinition split_float_interval:: \"float interval \\<Rightarrow> float \\<Rightarrow> float interval list\" where\n\"split_float_interval ivl m = (if m \\<in> set_of ivl then [Interval (lower ivl, m), Interval (m, upper ivl)] else [ivl])\"\n\n(* x \\<in> (\\<infinity>,u] \\<and> x \\<in> ivl \\<Longrightarrow> (\\<infinity>,u] \\<inter> ivl *)\nlemma split_float_same_set: \"set_of ivl = set_of_float_interval_list (split_float_interval ivl m)\"\nproof (cases \"m \\<in> set_of ivl\")\ncase True\n  show ?thesis\n  proof\n    show \"set_of ivl \\<subseteq> set_of_float_interval_list (split_float_interval ivl m)\"\n    proof\n      fix x\n      assume x: \"x \\<in> set_of ivl\"\n      then have \"lower ivl \\<le> x \\<and> x \\<le> upper ivl \\<and> m \\<le> x \\<or> x \\<le> m\" by (auto simp: set_of_eq)\n      then have \"lower ivl \\<le> x \\<and> x \\<le> m \\<or> m \\<le> x \\<and> x \\<le> upper ivl\" using set_of_eq x atLeastAtMost_iff by blast \n      then show \"x \\<in> set_of_float_interval_list (split_float_interval ivl m)\" using True split_float_interval_def by (simp add: set_of_eq)\n    qed\n  next\n    show \"set_of_float_interval_list (split_float_interval ivl m) \\<subseteq> set_of ivl\"\n    proof\n      fix x\n      assume x: \"x \\<in> set_of_float_interval_list (split_float_interval ivl m)\"\n      then have \"lower ivl \\<le> x \\<and> x \\<le> m \\<or> m \\<le> x \\<and> x \\<le> upper ivl\" using True split_float_interval_def by (simp add: set_of_eq)\n      then have \"lower ivl \\<le> x \\<and> x \\<le> upper ivl\" using True atLeastAtMost_iff by (auto simp: set_of_eq)\n      then show \"x \\<in> set_of ivl\" by (simp add: set_of_eq)\n    qed\n  qed\nnext\n  case False\n  then show ?thesis using split_float_interval_def by simp\nqed\n\nlemma split_float_same_set': \"set_of (real_interval ivl) = real_set_of_float_interval_list (split_float_interval ivl m)\"\nproof (cases \"m \\<in> set_of ivl\")\ncase True\n  show ?thesis\n  proof\n    show \"set_of (real_interval ivl) \\<subseteq> real_set_of_float_interval_list (split_float_interval ivl m)\"\n    proof\n      fix x\n      assume x: \"x \\<in> set_of (real_interval ivl)\"\n      then have \"lower ivl \\<le> x \\<and> x \\<le> upper ivl \\<and> m \\<le> x \\<or> x \\<le> m\" by (auto simp: set_of_eq)\n      then have \"lower ivl \\<le> x \\<and> x \\<le> m \\<or> m \\<le> x \\<and> x \\<le> upper ivl\"\n        using set_of_eq x atLeastAtMost_iff by (metis lower_real_interval) \n      then show \"x \\<in> real_set_of_float_interval_list (split_float_interval ivl m)\"\n        using True split_float_interval_def by (simp add: set_of_eq)\n    qed\n  next\n    show \"real_set_of_float_interval_list (split_float_interval ivl m) \\<subseteq> set_of (real_interval ivl)\"\n    proof\n      fix x\n      assume x: \"x \\<in> real_set_of_float_interval_list (split_float_interval ivl m)\"\n      then have \"lower ivl \\<le> x \\<and> x \\<le> m \\<or> m \\<le> x \\<and> x \\<le> upper ivl\"\n        using True split_float_interval_def by (simp add: set_of_eq)\n      then have \"lower ivl \\<le> x \\<and> x \\<le> upper ivl\" using True atLeastAtMost_iff by (auto simp: set_of_eq)\n      then show \"x \\<in> set_of (real_interval ivl)\" by (simp add: set_of_eq)\n    qed\n  qed\nnext\n  case False\n  then show ?thesis using split_float_interval_def by simp\nqed\n\nsubsection \"Lemmas Showing Monotonicity\"\n\nlemma set_of_subset_iff':\n  \"set_of a \\<subseteq> set_of (b :: 'a :: linorder interval) \\<longleftrightarrow> a \\<le> b\"\n  unfolding less_eq_interval_def set_of_subset_iff ..\n\nlemma set_of_times': \"set_of (a * b) = set_of a * set_of b\"\n  for a b :: \"'a :: {linordered_ring, real_normed_algebra, linear_continuum_topology} interval\"\n  by (auto simp: set_of_times set_times_def)\n\nlemma mult_mono_interval:\n  fixes a b :: \"'a :: {linordered_ring, real_normed_algebra, linear_continuum_topology} interval\"\n  assumes \"a \\<le> a'\" \"b \\<le> b'\"\n  shows   \"a * b \\<le> a' * b'\"\n  using assms unfolding set_of_subset_iff'[symmetric] set_of_times' by (intro set_times_mono2)\n\nlemma add_mono_interval:\n  assumes \"a \\<le> a'\" \"b \\<le> b'\"\n  shows   \"a + b \\<le> a' + (b' :: 'a :: ordered_ab_semigroup_add interval)\"\n  using assms\n  by (auto simp: less_eq_interval_def add_mono)\n\nlemma diff_mono_interval:\n  assumes \"a \\<le> a'\" \"b \\<le> b'\"\n  shows   \"a - b \\<le> a' - (b' :: 'a :: ordered_ab_group_add interval)\"\n  using assms\n  by (auto simp: less_eq_interval_def diff_mono)\n\nlemma add_mono_real_interval:\n  assumes \"a \\<le> real_interval a'\" \"b \\<le> real_interval b'\"\n  shows   \"a + b \\<le> real_interval (a' + b')\"\n  using assms\n  by (auto simp: less_eq_interval_def add_mono)\n\nlemma diff_mono_real_interval:\n  assumes \"a \\<le> real_interval a'\" \"b \\<le> real_interval b'\"\n  shows   \"a - b \\<le> real_interval (a' - b')\"\n  using assms\n  by (auto simp: less_eq_interval_def diff_mono)\n\nlemma mult_float_interval_mono:\n  assumes \"a \\<le> real_interval a'\" \"b \\<le> real_interval b'\"\n  shows   \"a * b \\<le> real_interval (mult_float_interval prec a' b')\"\nproof -\n  have \"a * b \\<le> real_interval a' * real_interval b'\"\n    by (intro mult_mono_interval assms)\n  also {\n    have \"set_of (real_interval a' * real_interval b') =\n            set_of (real_interval a') * set_of (real_interval b')\"\n      by (auto simp: set_of_times set_times_def)\n    also have \"\\<dots> \\<subseteq> set_of (real_interval (mult_float_interval prec a' b'))\"\n      by (rule mult_float_interval)\n    finally have \"real_interval a' * real_interval b' \\<le> real_interval (mult_float_interval prec a' b')\"\n      by (simp add: set_of_subset_iff')\n  }\n  finally show ?thesis .\nqed\n\nlemma real_of_float_le_iff: \"real_of_float x \\<le> real_of_float y \\<longleftrightarrow> x \\<le> y\"\n  by simp\n\nlemma real_of_float_less_iff: \"real_of_float x < real_of_float y \\<longleftrightarrow> x < y\"\n  by simp\n\nlemma real_of_float_leI: \"x \\<le> y \\<Longrightarrow> real_of_float x \\<le> real_of_float y\"\n  by simp\n\nlemma inverse_float_interval'_correctness:\n  assumes \"0 \\<notin> set_of ivl\"\n  shows lower_inverse_float_interval:\n          \"lower (inverse_float_interval' prec ivl) = float_divl prec 1 (upper ivl)\"\n    and upper_inverse_float_interval:\n          \"upper (inverse_float_interval' prec ivl) = float_divr prec 1 (lower ivl)\"\nproof -\n  from assms have \"lower ivl > 0 \\<or> upper ivl < 0\"\n    by (meson in_intervalI not_le)\n  moreover have \"real_of_float (lower ivl) \\<le> real_of_float (upper ivl)\"\n    by (meson less_eq_float.rep_eq lower_le_upper)\n  ultimately have *: \"1 / real_of_float (upper ivl) \\<le> 1 / real_of_float (lower ivl)\"\n    by (auto simp: divide_simps)\n\n  show \"lower (inverse_float_interval' prec ivl) = float_divl prec 1 (upper ivl)\"\n    using *  unfolding inverse_float_interval'_def\n    by (smt Interval''_def Interval_Help.lower_Interval float_divl float_divr normal_interval'' one_float.rep_eq real_of_float_le_iff)\n  show \"upper (inverse_float_interval' prec ivl) = float_divr prec 1 (lower ivl)\"\n    using * unfolding inverse_float_interval'_def\n    by (smt Interval''_def Interval_Help.upper_Interval float_divl float_divr normal_interval'' one_float.rep_eq real_of_float_le_iff)\nqed\n\nlemma inverse_interval'_correctness:\n  assumes \"0 \\<notin> set_of ivl\"\n  shows   lower_inverse_interval': \"lower (inverse_interval' ivl) = inverse (upper ivl)\"\n    and   upper_inverse_interval': \"upper (inverse_interval' ivl) = inverse (lower ivl)\"\nproof -\n  have \"lower ivl > 0 \\<or> upper ivl < 0\"\n    using assms by (meson in_intervalI not_le)\n  hence *: \"inverse (upper ivl) \\<le> inverse (lower ivl)\"\n    by (auto simp: divide_simps)\n  show \"lower (inverse_interval' ivl) = inverse (upper ivl)\"\n    using * unfolding inverse_interval'_def\n    by (subst lower.abs_eq) (auto simp: eq_onp_def)\n  show \"upper (inverse_interval' ivl) = inverse (lower ivl)\"\n    using * unfolding inverse_interval'_def\n    by (subst upper.abs_eq) (auto simp: eq_onp_def)\nqed\n\nlemma inverse_float_interval'_mono:\n  assumes \"a \\<le> real_interval a'\" \"0 \\<notin> set_of a'\"\n  shows   \"inverse_interval' a \\<le> real_interval (inverse_float_interval' prec a')\"\nproof -\n  have *: \"lower a' > 0 \\<or> upper a' < 0\"\n    using assms(2) by (meson in_intervalI not_le)\n  have **: \"real_of_float (lower a') \\<le> real_of_float (upper a')\"\n    by (intro real_of_float_leI lower_le_upper)\n  have ***: \"1 / real_of_float (upper a') \\<le> inverse (upper a)\"\n            \"1 / real_of_float (lower a') \\<ge> inverse (lower a)\"\n    using * ** lower_le_upper[of a] assms\n      by (auto simp: divide_simps less_eq_interval_def simp del: lower_le_upper)\n  have \"0 \\<notin> set_of a\"\n    using assms\n    by (metis atLeastAtMost_iff in_mono less_eq_float.rep_eq lower_real_interval set_of_eq\n              set_of_subset_iff' upper_real_interval zero_float.rep_eq)\n  thus ?thesis using assms ***\n    by (auto simp: less_eq_interval_def lower_inverse_float_interval upper_inverse_float_interval\n                   lower_inverse_interval' upper_inverse_interval'\n             intro!: order.trans[OF float_divl] order.trans[OF _ float_divr])\nqed\n\nlemma real_interval_interval_of [simp]:\n  \"real_interval (interval_of m) = interval_of (real_of_float m)\"\n  by (simp add: interval_eq_iff)\n\nend", "meta": {"author": "N3TZW3RG", "repo": "Interval_Newton_Method", "sha": "848928be6e14618c33b36c179ad1092afa8d2812", "save_path": "github-repos/isabelle/N3TZW3RG-Interval_Newton_Method", "path": "github-repos/isabelle/N3TZW3RG-Interval_Newton_Method/Interval_Newton_Method-848928be6e14618c33b36c179ad1092afa8d2812/Interval_Help.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.897695292107347, "lm_q2_score": 0.817574478416099, "lm_q1q2_score": 0.7339327602212519}}
{"text": "section \\<open>Bounded Degree Polynomials\\<close>\n\ntext \\<open>This section contains a definition for the set of polynomials with a degree bound and\nestablishes its cardinality.\\<close>\n\ntheory Bounded_Degree_Polynomials\n  imports \"HOL-Algebra.Polynomial_Divisibility\"\nbegin\n\nlemma (in ring) coeff_in_carrier: \"p \\<in> carrier (poly_ring R) \\<Longrightarrow> coeff p i \\<in> carrier R\"\n  using poly_coeff_in_carrier carrier_is_subring by (simp add: univ_poly_carrier)\n\ndefinition bounded_degree_polynomials\n  where \"bounded_degree_polynomials F n = {x. x \\<in> carrier (poly_ring F) \\<and> (degree x < n \\<or> x = [])}\"\n\ntext \\<open>Note: The definition for @{term \"bounded_degree_polynomials\"} includes the zero polynomial\nin @{term \"bounded_degree_polynomials F 0\"}. The reason for this adjustment is that, contrary to\ndefinition in HOL Algebra, most authors set the degree of the zero polynomial to\n$-\\infty$~\\<^cite>\\<open>\\<open>\\textsection 7.2.2\\<close> in \"shoup2009computational\"\\<close>. That\ndefinition make some identities, such as $\\mathrm{deg}(f g) = \\mathrm{deg}\\, f + \\mathrm{deg}\\, g$\nfor polynomials $f$ and $g$ unconditionally true.\nIn particular, it prevents an unnecessary corner case in the statement of the results established\nin this entry.\\<close>\n\nlemma bounded_degree_polynomials_length:\n  \"bounded_degree_polynomials F n = {x. x \\<in> carrier (poly_ring F) \\<and> length x \\<le> n}\"\n  unfolding bounded_degree_polynomials_def using leI order_less_le_trans by fastforce\n\nlemma (in ring) fin_degree_bounded:\n  assumes \"finite (carrier R)\"\n  shows \"finite (bounded_degree_polynomials R n)\"\nproof -\n  have \"bounded_degree_polynomials R n \\<subseteq> {p. set p \\<subseteq> carrier R \\<and> length p \\<le> n}\"\n    unfolding bounded_degree_polynomials_length\n    using assms polynomial_incl univ_poly_carrier by blast\n  thus ?thesis\n    using assms finite_lists_length_le finite_subset by fast\nqed\n\nlemma (in ring) non_empty_bounded_degree_polynomials:\n  \"bounded_degree_polynomials R k \\<noteq> {}\"\nproof -\n  have \"\\<zero>\\<^bsub>poly_ring R\\<^esub> \\<in> bounded_degree_polynomials R k\"\n    by (simp add: bounded_degree_polynomials_def univ_poly_zero univ_poly_zero_closed)\n  thus ?thesis by auto\nqed\n\nlemma in_image_by_witness:\n  assumes \"\\<And>x. x \\<in> A \\<Longrightarrow> g x \\<in> B \\<and> f (g x) = x\"\n  shows \"A \\<subseteq> f ` B\"\n  by (metis assms image_eqI subsetI)\n\nlemma card_mostly_constant_maps:\n  assumes \"y \\<in> B\"\n  shows \"card {f. range f \\<subseteq> B \\<and> (\\<forall>x. x \\<ge> n \\<longrightarrow> f x = y)} = card B ^ n\" (is \"card ?A = ?B\")\nproof -\n  define f where \"f = (\\<lambda>f k. if k < n then f k else y)\"\n\n  have a:\"?A \\<subseteq> (f ` ({0..<n}  \\<rightarrow>\\<^sub>E B))\"\n    unfolding f_def\n    by (rule in_image_by_witness[where g=\"\\<lambda>f. restrict f {0..<n}\"], auto)\n\n  have b:\"(f ` ({0..<n}  \\<rightarrow>\\<^sub>E B)) \\<subseteq> ?A\"\n    using f_def assms by auto\n\n  have c: \"inj_on f ({0..<n} \\<rightarrow>\\<^sub>E B)\"\n    by (rule inj_onI, metis PiE_E atLeastLessThan_iff ext f_def)\n\n  have \"card ?A = card (f ` ({0..<n}  \\<rightarrow>\\<^sub>E B))\"\n    using a b by auto\n  also have \"... = card ({0..<n} \\<rightarrow>\\<^sub>E B)\"\n    by (metis c card_image)\n  also have \"... = card B ^ n\"\n    by (simp add: card_PiE[OF finite_atLeastLessThan])\n  finally show ?thesis by simp\nqed\n\ndefinition (in ring) build_poly where\n  \"build_poly f n = normalize (rev (map f [0..<n]))\"\n\nlemma (in ring) poly_degree_bound_from_coeff:\n  assumes \"x \\<in> carrier (poly_ring R)\"\n  assumes \"\\<And>k. k \\<ge> n \\<Longrightarrow> coeff x k = \\<zero>\"\n  shows \"degree x < n \\<or> x = \\<zero>\\<^bsub>poly_ring R\\<^esub>\"\nproof (rule ccontr)\n  assume a:\"\\<not>(degree x < n \\<or> x = \\<zero>\\<^bsub>poly_ring R\\<^esub>)\"\n  hence b:\"lead_coeff x \\<noteq> \\<zero>\\<^bsub>R\\<^esub>\"\n    by (metis assms(1) polynomial_def univ_poly_carrier univ_poly_zero)\n  hence \"coeff x (degree x) \\<noteq> \\<zero>\"\n    by (metis a lead_coeff_simp univ_poly_zero)\n  moreover have \"degree x \\<ge> n\" by (meson a not_le)\n  ultimately show \"False\" using assms(2) by blast\nqed\n\nlemma (in ring) poly_degree_bound_from_coeff_1:\n  assumes \"x \\<in> carrier (poly_ring R)\"\n  assumes \"\\<And>k. k \\<ge> n \\<Longrightarrow> coeff x k = \\<zero>\"\n  shows \"x \\<in> bounded_degree_polynomials R n\"\n  using poly_degree_bound_from_coeff[OF assms]\n  by (simp add:bounded_degree_polynomials_def univ_poly_zero assms)\n\nlemma (in ring) length_build_poly:\n  \"length (build_poly f n) \\<le> n\"\n  by (metis length_map build_poly_def normalize_length_le length_rev length_upt\n      less_imp_diff_less linorder_not_less)\n\nlemma (in ring) build_poly_degree:\n  \"degree (build_poly f n) \\<le> n-1\"\n  using length_build_poly diff_le_mono by presburger\n\nlemma (in ring) build_poly_poly:\n  assumes \"\\<And>i. i < n \\<Longrightarrow> f i \\<in> carrier R\"\n  shows \"build_poly f n \\<in> carrier (poly_ring R)\"\n  unfolding build_poly_def univ_poly_carrier[symmetric]\n  by (rule normalize_gives_polynomial, simp add:image_subset_iff Ball_def assms)\n\nlemma (in ring) build_poly_coeff:\n  \"coeff (build_poly f n) i = (if i < n then f i else \\<zero>)\"\nproof -\n  show \"coeff (build_poly f n) i = (if i < n then f i else \\<zero>)\"\n    unfolding build_poly_def normalize_coeff[symmetric]\n    by (cases \"i < n\", (simp add:coeff_nth rev_nth coeff_length)+)\nqed\n\nlemma (in ring) build_poly_bounded:\n  assumes \"\\<And>k. k < n \\<Longrightarrow> f k \\<in> carrier R\"\n  shows \"build_poly f n \\<in> bounded_degree_polynomials R n\"\n  unfolding bounded_degree_polynomials_length\n  using build_poly_poly[OF assms] length_build_poly by auto\n\ntext \\<open>The following establishes the total number of polynomials with a degree less than $n$.\nUnlike the results in the following sections, it is already possible to establish this property for\npolynomials with coefficients in a ring.\\<close>\n\nlemma (in ring) bounded_degree_polynomials_card:\n  \"card (bounded_degree_polynomials R n) = card (carrier R) ^ n\"\nproof -\n  have a:\"coeff ` bounded_degree_polynomials R n \\<subseteq> {f. range f \\<subseteq> (carrier R) \\<and> (\\<forall>k \\<ge> n. f k = \\<zero>)}\"\n    by (rule image_subsetI, auto simp add:bounded_degree_polynomials_def coeff_length coeff_in_carrier)\n\n  have b:\"{f. range f \\<subseteq> (carrier R) \\<and> (\\<forall>k \\<ge> n. f k = \\<zero>)} \\<subseteq> coeff ` bounded_degree_polynomials R n\"\n    apply (rule in_image_by_witness[where g=\"\\<lambda>x. build_poly x n\"])\n    by (auto simp add:build_poly_coeff intro:build_poly_bounded)\n\n  have \"inj_on coeff (carrier (poly_ring R))\"\n    by (rule inj_onI, simp add: coeff_iff_polynomial_cond univ_poly_carrier)\n\n  hence coeff_inj: \"inj_on coeff (bounded_degree_polynomials R n)\"\n    using inj_on_subset bounded_degree_polynomials_def by blast\n\n  have \"card ( bounded_degree_polynomials R n) = card (coeff `  bounded_degree_polynomials R n)\"\n    using coeff_inj card_image[symmetric] by blast\n  also have \"... = card {f. range f \\<subseteq> (carrier R) \\<and> (\\<forall>k \\<ge> n. f k = \\<zero>)}\"\n    by (rule arg_cong[where f=\"card\"], rule order_antisym[OF a b])\n  also have \"... = card (carrier R)^n\"\n    by (rule card_mostly_constant_maps, simp)\n  finally show ?thesis by simp\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/Interpolation_Polynomials_HOL_Algebra/Bounded_Degree_Polynomials.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391602943619, "lm_q2_score": 0.8499711699569787, "lm_q1q2_score": 0.7338579708850191}}
{"text": "(*  Title:      HOL/Corec_Examples/Tests/Small_Concrete.thy\n    Author:     Aymeric Bouzy, Ecole polytechnique\n    Author:     Jasmin Blanchette, Inria, LORIA, MPII\n    Copyright   2015, 2016\n\nSmall concrete examples.\n*)\n\nsection \\<open>Small Concrete Examples\\<close>\n\ntheory Small_Concrete\nimports \"~~/src/HOL/Library/BNF_Corec\"\nbegin\n\nsubsection \\<open>Streams of Natural Numbers\\<close>\n\ncodatatype natstream = S (head: nat) (tail: natstream)\n\ncorec (friend) incr_all where\n  \"incr_all s = S (head s + 1) (incr_all (tail s))\"\n\ncorec all_numbers where\n  \"all_numbers = S 0 (incr_all all_numbers)\"\n\ncorec all_numbers_efficient where\n  \"all_numbers_efficient n = S n (all_numbers_efficient (n + 1))\"\n\ncorec remove_multiples where\n  \"remove_multiples n s =\n    (if (head s) mod n = 0 then\n      S (head (tail s)) (remove_multiples n (tail (tail s)))\n    else\n      S (head s) (remove_multiples n (tail s)))\"\n\ncorec prime_numbers where\n  \"prime_numbers known_primes =\n    (let next_prime = head (fold (%n s. remove_multiples n s) known_primes (tail (tail all_numbers))) in\n      S next_prime (prime_numbers (next_prime # known_primes)))\"\n\nterm \"prime_numbers []\"\n\ncorec prime_numbers_more_efficient where\n  \"prime_numbers_more_efficient n remaining_numbers =\n    (let remaining_numbers = remove_multiples n remaining_numbers in\n      S (head remaining_numbers) (prime_numbers_more_efficient (head remaining_numbers) remaining_numbers))\"\n\nterm \"prime_numbers_more_efficient 0 (tail (tail all_numbers))\"\n\ncorec (friend) alternate where\n  \"alternate s1 s2 = S (head s1) (S (head s2) (alternate (tail s1) (tail s2)))\"\n\ncorec (friend) all_sums where\n  \"all_sums s1 s2 = S (head s1 + head s2) (alternate (all_sums s1 (tail s2)) (all_sums (tail s1) s2))\"\n\ncorec app_list where\n  \"app_list s l = (case l of\n    [] \\<Rightarrow> s\n  | a # r \\<Rightarrow> S a (app_list s r))\"\n\nfriend_of_corec app_list where\n  \"app_list s l = (case l of\n    [] \\<Rightarrow> (case s of S a b \\<Rightarrow> S a b)\n  | a # r \\<Rightarrow> S a (app_list s r))\"\n  sorry\n\ncorec expand_with where\n  \"expand_with f s = (let l = f (head s) in S (hd l) (app_list (expand_with f (tail s)) (tl l)))\"\n\nfriend_of_corec expand_with where\n  \"expand_with f s = (let l = f (head s) in S (hd l) (app_list (expand_with f (tail s)) (tl l)))\"\n  sorry\n\ncorec iterations where\n  \"iterations f a = S a (iterations f (f a))\"\n\ncorec exponential_iterations where\n  \"exponential_iterations f a = S (f a) (exponential_iterations (f o f) a)\"\n\ncorec (friend) alternate_list where\n  \"alternate_list l = (let heads = (map head l) in S (hd heads) (app_list (alternate_list (map tail l)) (tl heads)))\"\n\ncorec switch_one_two0 where\n  \"switch_one_two0 f a s = (case s of\n    S b r \\<Rightarrow> S b (S a (f r)))\"\n\ncorec switch_one_two where\n  \"switch_one_two s = (case s of\n    S a (S b r) \\<Rightarrow> S b (S a (switch_one_two r)))\"\n\ncorec fibonacci where\n  \"fibonacci n m = S m (fibonacci (n + m) n)\"\n\ncorec sequence2 where\n  \"sequence2 f u1 u0 = S u0 (sequence2 f (f u1 u0) u1)\"\n\ncorec (friend) alternate_with_function where\n  \"alternate_with_function f s =\n    (let f_head_s = f (head s) in S (head f_head_s) (alternate (tail f_head_s) (alternate_with_function f (tail s))))\"\n\ncorec h where\n  \"h l s = (case l of\n    [] \\<Rightarrow> s\n  | (S a s') # r \\<Rightarrow> S a (alternate s (h r s')))\"\n\nfriend_of_corec h where\n  \"h l s = (case l of\n    [] \\<Rightarrow> (case s of S a b \\<Rightarrow> S a b)\n  | (S a s') # r \\<Rightarrow> S a (alternate s (h r s')))\"\n  sorry\n\ncorec z where\n  \"z = S 0 (S 0 z)\"\n\nlemma \"\\<And>x. x = S 0 (S 0 x) \\<Longrightarrow> x = z\"\n  apply corec_unique\n  apply (rule z.code)\n  done\n\ncorec enum where\n  \"enum m = S m (enum (m + 1))\"\n\nlemma \"(\\<And>m. f m = S m (f (m + 1))) \\<Longrightarrow> f m = enum m\"\n  apply corec_unique\n  apply (rule enum.code)\n  done\n\nlemma \"(\\<forall>m. f m = S m (f (m + 1))) \\<Longrightarrow> f m = enum m\"\n  apply corec_unique\n  apply (rule enum.code)\n  done\n\n\nsubsection \\<open>Lazy Lists of Natural Numbers\\<close>\n\ncodatatype llist = LNil | LCons nat llist\n\ncorec h1 where\n  \"h1 x = (if x = 1 then\n    LNil\n  else\n    let x = if x mod 2 = 0 then x div 2 else 3 * x + 1 in\n    LCons x (h1 x))\"\n\ncorec h3 where\n  \"h3 s = (case s of\n    LNil \\<Rightarrow> LNil\n  | LCons x r \\<Rightarrow> LCons x (h3 r))\"\n\ncorec fold_map where\n  \"fold_map f a s = (let v = f a (head s) in S v (fold_map f v (tail s)))\"\n\nfriend_of_corec fold_map where\n  \"fold_map f a s = (let v = f a (head s) in S v (fold_map f v (tail s)))\"\n   apply (rule fold_map.code)\n  sorry\n\n\nsubsection \\<open>Coinductive Natural Numbers\\<close>\n\ncodatatype conat = CoZero | CoSuc conat\n\ncorec sum where\n  \"sum x y = (case x of\n      CoZero \\<Rightarrow> y\n    | CoSuc x \\<Rightarrow> CoSuc (sum x y))\"\n\nfriend_of_corec sum where\n  \"sum x y = (case x of\n      CoZero \\<Rightarrow> (case y of CoZero \\<Rightarrow> CoZero | CoSuc y \\<Rightarrow> CoSuc y)\n    | CoSuc x \\<Rightarrow> CoSuc (sum x y))\"\n  sorry\n\ncorec (friend) prod where\n  \"prod x y = (case (x, y) of\n      (CoZero, _) \\<Rightarrow> CoZero\n    | (_, CoZero) \\<Rightarrow> CoZero\n    | (CoSuc x, CoSuc y) \\<Rightarrow> CoSuc (sum (prod x y) (sum x y)))\"\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/Corec_Examples/Tests/Small_Concrete.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8479677660619633, "lm_q2_score": 0.8652240877899776, "lm_q1q2_score": 0.7336821368662674}}
{"text": "(* Title: Interval\n   Author: Christoph Traut, TU Muenchen\n           Fabian Immler, TU Muenchen\n*)\nsection \\<open>Interval Type\\<close>\ntheory Interval\n  imports\n    Complex_Main\n    Lattice_Algebras\n    Set_Algebras\nbegin\n\ntext \\<open>A type of non-empty, closed intervals.\\<close>\n\ntypedef (overloaded) 'a interval =\n  \"{(a::'a::preorder, b). a \\<le> b}\"\n  morphisms bounds_of_interval Interval\n  by auto\n\nsetup_lifting type_definition_interval\n\nlift_definition lower::\"('a::preorder) interval \\<Rightarrow> 'a\" is fst .\n\nlift_definition upper::\"('a::preorder) interval \\<Rightarrow> 'a\" is snd .\n\nlemma interval_eq_iff: \"a = b \\<longleftrightarrow> lower a = lower b \\<and> upper a = upper b\"\n  by transfer auto\n\nlemma interval_eqI: \"lower a = lower b \\<Longrightarrow> upper a = upper b \\<Longrightarrow> a = b\"\n  by (auto simp: interval_eq_iff)\n\nlemma lower_le_upper[simp]: \"lower i \\<le> upper i\"\n  by transfer auto\n\nlift_definition set_of :: \"'a::preorder interval \\<Rightarrow> 'a set\" is \"\\<lambda>x. {fst x .. snd x}\" .\n\nlemma set_of_eq: \"set_of x = {lower x .. upper x}\"\n  by transfer simp\n\ncontext notes [[typedef_overloaded]] begin\n\nlift_definition(code_dt) Interval'::\"'a::preorder \\<Rightarrow> 'a::preorder \\<Rightarrow> 'a interval option\"\n  is \"\\<lambda>a b. if a \\<le> b then Some (a, b) else None\"\n  by auto\n\nlemma Interval'_split:\n  \"P (Interval' a b) \\<longleftrightarrow>\n    (\\<forall>ivl. a \\<le> b \\<longrightarrow> lower ivl = a \\<longrightarrow> upper ivl = b \\<longrightarrow> P (Some ivl)) \\<and> (\\<not>a\\<le>b \\<longrightarrow> P None)\"\n  by transfer auto\n\nlemma Interval'_split_asm:\n  \"P (Interval' a b) \\<longleftrightarrow>\n    \\<not>((\\<exists>ivl. a \\<le> b \\<and> lower ivl = a \\<and> upper ivl = b \\<and> \\<not>P (Some ivl)) \\<or> (\\<not>a\\<le>b \\<and> \\<not>P None))\"\n  unfolding Interval'_split\n  by auto\n\nlemmas Interval'_splits = Interval'_split Interval'_split_asm\n\nlemma Interval'_eq_Some: \"Interval' a b = Some i \\<Longrightarrow> lower i = a \\<and> upper i = b\"\n  by (simp split: Interval'_splits)\n\nend\n\ninstantiation \"interval\" :: (\"{preorder,equal}\") equal\nbegin\n\ndefinition \"equal_class.equal a b \\<equiv> (lower a = lower b) \\<and> (upper a = upper b)\"\n\ninstance proof qed (simp add: equal_interval_def interval_eq_iff)\nend\n\ninstantiation interval :: (\"preorder\") ord begin\n\ndefinition less_eq_interval :: \"'a interval \\<Rightarrow> 'a interval \\<Rightarrow> bool\"\n  where \"less_eq_interval a b \\<longleftrightarrow> lower b \\<le> lower a \\<and> upper a \\<le> upper b\"\n\ndefinition less_interval :: \"'a interval \\<Rightarrow> 'a interval \\<Rightarrow> bool\"\n  where  \"less_interval x y = (x \\<le> y \\<and> \\<not> y \\<le> x)\"\n\ninstance proof qed\nend\n\ninstantiation interval :: (\"lattice\") semilattice_sup\nbegin\n\nlift_definition sup_interval :: \"'a interval \\<Rightarrow> 'a interval \\<Rightarrow> 'a interval\"\n  is \"\\<lambda>(a, b) (c, d). (inf a c, sup b d)\"\n  by (auto simp: le_infI1 le_supI1)\n\nlemma lower_sup[simp]: \"lower (sup A B) = inf (lower A) (lower B)\"\n  by transfer auto\n\nlemma upper_sup[simp]: \"upper (sup A B) = sup (upper A) (upper B)\"\n  by transfer auto\n\ninstance proof qed (auto simp: less_eq_interval_def less_interval_def interval_eq_iff)\nend\n\nlemma set_of_interval_union: \"set_of A \\<union> set_of B \\<subseteq> set_of (sup A B)\" for A::\"'a::lattice interval\"\n  by (auto simp: set_of_eq)\n\nlemma interval_union_commute: \"sup A B = sup B A\" for A::\"'a::lattice interval\"\n  by (auto simp add: interval_eq_iff inf.commute sup.commute)\n\nlemma interval_union_mono1: \"set_of a \\<subseteq> set_of (sup a A)\" for A :: \"'a::lattice interval\"\n  using set_of_interval_union by blast\n\nlemma interval_union_mono2: \"set_of A \\<subseteq> set_of (sup a A)\" for A :: \"'a::lattice interval\"\n  using set_of_interval_union by blast\n\nlift_definition interval_of :: \"'a::preorder \\<Rightarrow> 'a interval\" is \"\\<lambda>x. (x, x)\"\n  by auto\n\nlemma lower_interval_of[simp]: \"lower (interval_of a) = a\"\n  by transfer auto\n\nlemma upper_interval_of[simp]: \"upper (interval_of a) = a\"\n  by transfer auto\n\ndefinition width :: \"'a::{preorder,minus} interval \\<Rightarrow> 'a\"\n  where \"width i = upper i - lower i\"\n\n\ninstantiation \"interval\" :: (\"ordered_ab_semigroup_add\") ab_semigroup_add\nbegin\n\nlift_definition plus_interval::\"'a interval \\<Rightarrow> 'a interval \\<Rightarrow> 'a interval\"\n  is \"\\<lambda>(a, b). \\<lambda>(c, d). (a + c, b + d)\"\n  by (auto intro!: add_mono)\nlemma lower_plus[simp]: \"lower (plus A B) = plus (lower A) (lower B)\"\n  by transfer auto\nlemma upper_plus[simp]: \"upper (plus A B) = plus (upper A) (upper B)\"\n  by transfer auto\n\ninstance proof qed (auto simp: interval_eq_iff less_eq_interval_def ac_simps)\nend\n\ninstance \"interval\" :: (\"{ordered_ab_semigroup_add, lattice}\") ordered_ab_semigroup_add\nproof qed (auto simp: less_eq_interval_def intro!: add_mono)\n\ninstantiation \"interval\" :: (\"{preorder,zero}\") zero\nbegin\n\nlift_definition zero_interval::\"'a interval\" is \"(0, 0)\" by auto\nlemma lower_zero[simp]: \"lower 0 = 0\"\n  by transfer auto\nlemma upper_zero[simp]: \"upper 0 = 0\"\n  by transfer auto\ninstance proof qed\nend\n\ninstance \"interval\" :: (\"{ordered_comm_monoid_add}\") comm_monoid_add\nproof qed (auto simp: interval_eq_iff)\n\ninstance \"interval\" :: (\"{ordered_comm_monoid_add,lattice}\") ordered_comm_monoid_add ..\n\ninstantiation \"interval\" :: (\"{ordered_ab_group_add}\") uminus\nbegin\n\nlift_definition uminus_interval::\"'a interval \\<Rightarrow> 'a interval\" is \"\\<lambda>(a, b). (-b, -a)\" by auto\nlemma lower_uminus[simp]: \"lower (- A) = - upper A\"\n  by transfer auto\nlemma upper_uminus[simp]: \"upper (- A) = - lower A\"\n  by transfer auto\ninstance ..\nend\n\ninstantiation \"interval\" :: (\"{ordered_ab_group_add}\") minus\nbegin\n\ndefinition minus_interval::\"'a interval \\<Rightarrow> 'a interval \\<Rightarrow> 'a interval\"\n  where \"minus_interval a b = a + - b\"\nlemma lower_minus[simp]: \"lower (minus A B) = minus (lower A) (upper B)\"\n  by (auto simp: minus_interval_def)\nlemma upper_minus[simp]: \"upper (minus A B) = minus (upper A) (lower B)\"\n  by (auto simp: minus_interval_def)\n\ninstance ..\nend\n\ninstantiation \"interval\" :: (linordered_semiring) times\nbegin\n\nlift_definition times_interval :: \"'a interval \\<Rightarrow> 'a interval \\<Rightarrow> 'a interval\"\n  is \"\\<lambda>(a1, a2). \\<lambda>(b1, b2).\n    (let x1 = a1 * b1; x2 = a1 * b2; x3 = a2 * b1; x4 = a2 * b2\n    in (min x1 (min x2 (min x3 x4)), max x1 (max x2 (max x3 x4))))\"\n  by (auto simp: Let_def intro!: min.coboundedI1 max.coboundedI1)\n\nlemma lower_times:\n  \"lower (times A B) = Min {lower A * lower B, lower A * upper B, upper A * lower B, upper A * upper B}\"\n  by transfer (auto simp: Let_def)\n\nlemma upper_times:\n  \"upper (times A B) = Max {lower A * lower B, lower A * upper B, upper A * lower B, upper A * upper B}\"\n  by transfer (auto simp: Let_def)\n\ninstance ..\nend\n\nlemma interval_eq_set_of_iff: \"X = Y \\<longleftrightarrow> set_of X = set_of Y\" for X Y::\"'a::order interval\"\n  by (auto simp: set_of_eq interval_eq_iff)\n\n\nsubsection \\<open>Membership\\<close>\n\nabbreviation (in preorder) in_interval (\"(_/ \\<in>\\<^sub>i _)\" [51, 51] 50)\n  where \"in_interval x X \\<equiv> x \\<in> set_of X\"\n\nlemma in_interval_to_interval[intro!]: \"a \\<in>\\<^sub>i interval_of a\"\n  by (auto simp: set_of_eq)\n\nlemma plus_in_intervalI:\n  fixes x y :: \"'a :: ordered_ab_semigroup_add\"\n  shows \"x \\<in>\\<^sub>i X \\<Longrightarrow> y \\<in>\\<^sub>i Y \\<Longrightarrow> x + y \\<in>\\<^sub>i X + Y\"\n  by (simp add: add_mono_thms_linordered_semiring(1) set_of_eq)\n\nlemma connected_set_of[intro, simp]:\n  \"connected (set_of X)\" for X::\"'a::linear_continuum_topology interval\"\n  by (auto simp: set_of_eq )\n\nlemma ex_sum_in_interval_lemma: \"\\<exists>xa\\<in>{la .. ua}. \\<exists>xb\\<in>{lb .. ub}. x = xa + xb\"\n  if \"la \\<le> ua\" \"lb \\<le> ub\" \"la + lb \\<le> x\" \"x \\<le> ua + ub\"\n    \"ua - la \\<le> ub - lb\"\n  for la b c d::\"'a::linordered_ab_group_add\"\nproof -\n  define wa where \"wa = ua - la\"\n  define wb where \"wb = ub - lb\"\n  define w where \"w = wa + wb\"\n  define d where \"d = x - la - lb\"\n  define da where \"da = max 0 (min wa (d - wa))\"\n  define db where \"db = d - da\"\n  from that have nonneg: \"0 \\<le> wa\" \"0 \\<le> wb\" \"0 \\<le> w\" \"0 \\<le> d\" \"d \\<le> w\"\n    by (auto simp add: wa_def wb_def w_def d_def add.commute le_diff_eq)\n  have \"0 \\<le> db\"\n    by (auto simp: da_def nonneg db_def intro!: min.coboundedI2)\n  have \"x = (la + da) + (lb + db)\"\n    by (simp add: da_def db_def d_def)\n  moreover\n  have \"x - la - ub \\<le> da\"\n    using that\n    unfolding da_def\n    by (intro max.coboundedI2) (auto simp: wa_def d_def diff_le_eq diff_add_eq)\n  then have \"db \\<le> wb\"\n    by (auto simp: db_def d_def wb_def algebra_simps)\n  with \\<open>0 \\<le> db\\<close> that nonneg have \"lb + db \\<in> {lb..ub}\"\n    by (auto simp: wb_def algebra_simps)\n  moreover\n  have \"da \\<le> wa\"\n    by (auto simp: da_def nonneg)\n  then have \"la + da \\<in> {la..ua}\"\n    by (auto simp: da_def wa_def algebra_simps)\n  ultimately show ?thesis\n    by force\nqed\n\n\nlemma ex_sum_in_interval: \"\\<exists>xa\\<ge>la. xa \\<le> ua \\<and> (\\<exists>xb\\<ge>lb. xb \\<le> ub \\<and> x = xa + xb)\"\n  if a: \"la \\<le> ua\" and b: \"lb \\<le> ub\" and x: \"la + lb \\<le> x\" \"x \\<le> ua + ub\"\n  for la b c d::\"'a::linordered_ab_group_add\"\nproof -\n  from linear consider \"ua - la \\<le> ub - lb\" | \"ub - lb \\<le> ua - la\"\n    by blast\n  then show ?thesis\n  proof cases\n    case 1\n    from ex_sum_in_interval_lemma[OF that 1]\n    show ?thesis by auto\n  next\n    case 2\n    from x have \"lb + la \\<le> x\" \"x \\<le> ub + ua\" by (simp_all add: ac_simps)\n    from ex_sum_in_interval_lemma[OF b a this 2]\n    show ?thesis by auto\n  qed\nqed\n\nlemma Icc_plus_Icc:\n  \"{a .. b} + {c .. d} = {a + c .. b + d}\"\n  if \"a \\<le> b\" \"c \\<le> d\"\n  for a b c d::\"'a::linordered_ab_group_add\"\n  using ex_sum_in_interval[OF that]\n  by (auto intro: add_mono simp: atLeastAtMost_iff Bex_def set_plus_def)\n\nlemma set_of_plus:\n  fixes A :: \"'a::linordered_ab_group_add interval\"\n  shows \"set_of (A + B) = set_of A + set_of B\"\n  using Icc_plus_Icc[of \"lower A\" \"upper A\" \"lower B\" \"upper B\"]\n  by (auto simp: set_of_eq)\n\nlemma plus_in_intervalE:\n  fixes xy :: \"'a :: linordered_ab_group_add\"\n  assumes \"xy \\<in>\\<^sub>i X + Y\"\n  obtains x y where \"xy = x + y\" \"x \\<in>\\<^sub>i X\" \"y \\<in>\\<^sub>i Y\"\n  using assms\n  unfolding set_of_plus set_plus_def\n  by auto\n\nlemma set_of_uminus: \"set_of (-X) = {- x | x. x \\<in> set_of X}\"\n  for X :: \"'a :: ordered_ab_group_add interval\"\n  by (auto simp: set_of_eq simp: le_minus_iff minus_le_iff\n      intro!: exI[where x=\"-x\" for x])\n\nlemma uminus_in_intervalI:\n  fixes x :: \"'a :: ordered_ab_group_add\"\n  shows \"x \\<in>\\<^sub>i X \\<Longrightarrow> -x \\<in>\\<^sub>i -X\"\n  by (auto simp: set_of_uminus)\n\nlemma uminus_in_intervalD:\n  fixes x :: \"'a :: ordered_ab_group_add\"\n  shows \"x \\<in>\\<^sub>i - X \\<Longrightarrow> - x \\<in>\\<^sub>i X\"\n  by (auto simp: set_of_uminus)\n\nlemma minus_in_intervalI:\n  fixes x y :: \"'a :: ordered_ab_group_add\"\n  shows \"x \\<in>\\<^sub>i X \\<Longrightarrow> y \\<in>\\<^sub>i Y \\<Longrightarrow> x - y \\<in>\\<^sub>i X - Y\"\n  by (metis diff_conv_add_uminus minus_interval_def plus_in_intervalI uminus_in_intervalI)\n\nlemma set_of_minus: \"set_of (X - Y) = {x - y | x y . x \\<in> set_of X \\<and> y \\<in> set_of Y}\"\n  for X Y :: \"'a :: linordered_ab_group_add interval\"\n  unfolding minus_interval_def set_of_plus set_of_uminus set_plus_def\n  by force\n\nlemma times_in_intervalI:\n  fixes x y::\"'a::linordered_ring\"\n  assumes \"x \\<in>\\<^sub>i X\" \"y \\<in>\\<^sub>i Y\"\n  shows \"x * y \\<in>\\<^sub>i X * Y\"\nproof -\n  define X1 where \"X1 \\<equiv> lower X\"\n  define X2 where \"X2 \\<equiv> upper X\"\n  define Y1 where \"Y1 \\<equiv> lower Y\"\n  define Y2 where \"Y2 \\<equiv> upper Y\"\n  from assms have assms: \"X1 \\<le> x\" \"x \\<le> X2\" \"Y1 \\<le> y\" \"y \\<le> Y2\"\n    by (auto simp: X1_def X2_def Y1_def Y2_def set_of_eq)\n  have \"(X1 * Y1 \\<le> x * y \\<or> X1 * Y2 \\<le> x * y \\<or> X2 * Y1 \\<le> x * y \\<or> X2 * Y2 \\<le> x * y) \\<and>\n        (X1 * Y1 \\<ge> x * y \\<or> X1 * Y2 \\<ge> x * y \\<or> X2 * Y1 \\<ge> x * y \\<or> X2 * Y2 \\<ge> x * y)\"\n  proof (cases x \"0::'a\" rule: linorder_cases)\n    case x0: less\n    show ?thesis\n    proof (cases \"y < 0\")\n      case y0: True\n      from y0 x0 assms have \"x * y \\<le> X1 * y\" by (intro mult_right_mono_neg, auto)\n      also from x0 y0 assms have \"X1 * y \\<le> X1 * Y1\" by (intro mult_left_mono_neg, auto)\n      finally have 1: \"x * y \\<le> X1 * Y1\".\n      show ?thesis proof(cases \"X2 \\<le> 0\")\n        case True\n        with assms have \"X2 * Y2 \\<le> X2 * y\" by (auto intro: mult_left_mono_neg)\n        also from assms y0 have \"... \\<le> x * y\" by (auto intro: mult_right_mono_neg)\n        finally have \"X2 * Y2 \\<le> x * y\".\n        with 1 show ?thesis by auto\n      next\n        case False\n        with assms have \"X2 * Y1 \\<le> X2 * y\" by (auto intro: mult_left_mono)\n        also from assms y0 have \"... \\<le> x * y\" by (auto intro: mult_right_mono_neg)\n        finally have \"X2 * Y1 \\<le> x * y\".\n        with 1 show ?thesis by auto\n      qed\n    next\n      case False\n      then have y0: \"y \\<ge> 0\" by auto\n      from x0 y0 assms have \"X1 * Y2 \\<le> x * Y2\" by (intro mult_right_mono, auto)\n      also from y0 x0 assms have \"... \\<le> x * y\" by (intro mult_left_mono_neg, auto)\n      finally have 1: \"X1 * Y2 \\<le> x * y\".\n      show ?thesis\n      proof(cases \"X2 \\<le> 0\")\n        case X2: True\n        from assms y0 have \"x * y \\<le> X2 * y\" by (intro mult_right_mono)\n        also from assms X2 have \"... \\<le> X2 * Y1\" by (auto intro: mult_left_mono_neg)\n        finally have \"x * y \\<le> X2 * Y1\".\n        with 1 show ?thesis by auto\n      next\n        case X2: False\n        from assms y0 have \"x * y \\<le> X2 * y\" by (intro mult_right_mono)\n        also from assms X2 have \"... \\<le> X2 * Y2\" by (auto intro: mult_left_mono)\n        finally have \"x * y \\<le> X2 * Y2\".\n        with 1 show ?thesis by auto\n      qed\n    qed\n  next\n    case [simp]: equal\n    with assms show ?thesis by (cases \"Y2 \\<le> 0\", auto intro:mult_sign_intros)\n  next\n    case x0: greater\n    show ?thesis\n    proof (cases \"y < 0\")\n      case y0: True\n      from x0 y0 assms have \"X2 * Y1 \\<le> X2 * y\" by (intro mult_left_mono, auto)\n      also from y0 x0 assms have \"X2 * y \\<le> x * y\" by (intro mult_right_mono_neg, auto)\n      finally have 1: \"X2 * Y1 \\<le> x * y\".\n      show ?thesis\n      proof(cases \"Y2 \\<le> 0\")\n        case Y2: True\n        from x0 assms have \"x * y \\<le> x * Y2\" by (auto intro: mult_left_mono)\n        also from assms Y2 have \"... \\<le> X1 * Y2\" by (auto intro: mult_right_mono_neg)\n        finally have \"x * y \\<le> X1 * Y2\".\n        with 1 show ?thesis by auto\n      next\n        case Y2: False\n        from x0 assms have \"x * y \\<le> x * Y2\" by (auto intro: mult_left_mono)\n        also from assms Y2 have \"... \\<le> X2 * Y2\" by (auto intro: mult_right_mono)\n        finally have \"x * y \\<le> X2 * Y2\".\n        with 1 show ?thesis by auto\n      qed\n    next\n      case y0: False\n      from x0 y0 assms have \"x * y \\<le> X2 * y\" by (intro mult_right_mono, auto)\n      also from y0 x0 assms have \"... \\<le> X2 * Y2\" by (intro mult_left_mono, auto)\n      finally have 1: \"x * y \\<le> X2 * Y2\".\n      show ?thesis\n      proof(cases \"X1 \\<le> 0\")\n        case True\n        with assms have \"X1 * Y2 \\<le> X1 * y\" by (auto intro: mult_left_mono_neg)\n        also from assms y0 have \"... \\<le> x * y\" by (auto intro: mult_right_mono)\n        finally have \"X1 * Y2 \\<le> x * y\".\n        with 1 show ?thesis by auto\n      next\n        case False\n        with assms have \"X1 * Y1 \\<le> X1 * y\" by (auto intro: mult_left_mono)\n        also from assms y0 have \"... \\<le> x * y\" by (auto intro: mult_right_mono)\n        finally have \"X1 * Y1 \\<le> x * y\".\n        with 1 show ?thesis by auto\n      qed\n    qed\n  qed\n  hence min:\"min (X1 * Y1) (min (X1 * Y2) (min (X2 * Y1) (X2 * Y2))) \\<le> x * y\"\n    and max:\"x * y \\<le> max (X1 * Y1) (max (X1 * Y2) (max (X2 * Y1) (X2 * Y2)))\"\n    by (auto simp:min_le_iff_disj le_max_iff_disj)\n  show ?thesis using min max\n    by (auto simp: Let_def X1_def X2_def Y1_def Y2_def set_of_eq lower_times upper_times)\nqed\n\nlemma times_in_intervalE:\n  fixes xy :: \"'a :: {linordered_semiring, real_normed_algebra, linear_continuum_topology}\"\n    \\<comment> \\<open>TODO: linear continuum topology is pretty strong\\<close>\n  assumes \"xy \\<in>\\<^sub>i X * Y\"\n  obtains x y where \"xy = x * y\" \"x \\<in>\\<^sub>i X\" \"y \\<in>\\<^sub>i Y\"\nproof -\n  let ?mult = \"\\<lambda>(x, y). x * y\"\n  let ?XY = \"set_of X \\<times> set_of Y\"\n  have cont: \"continuous_on ?XY ?mult\"\n    by (auto intro!: tendsto_eq_intros simp: continuous_on_def split_beta')\n  have conn: \"connected (?mult ` ?XY)\"\n    by (rule connected_continuous_image[OF cont]) auto\n  have \"lower (X * Y) \\<in> ?mult ` ?XY\" \"upper (X * Y) \\<in> ?mult ` ?XY\"\n    by (auto simp: set_of_eq lower_times upper_times min_def max_def split: if_splits)\n  from connectedD_interval[OF conn this, of xy] assms\n  obtain x y where \"xy = x * y\" \"x \\<in>\\<^sub>i X\" \"y \\<in>\\<^sub>i Y\" by (auto simp: set_of_eq)\n  then show ?thesis ..\nqed\n\nlemma set_of_times: \"set_of (X * Y) = {x * y | x y. x \\<in> set_of X \\<and> y \\<in> set_of Y}\"\n  for X Y::\"'a :: {linordered_ring, real_normed_algebra, linear_continuum_topology} interval\"\n  by (auto intro!: times_in_intervalI elim!: times_in_intervalE)\n\ninstance \"interval\" :: (linordered_idom) cancel_semigroup_add\nproof qed (auto simp: interval_eq_iff)\n\nlemma interval_mul_commute: \"A * B = B * A\" for A B:: \"'a::linordered_idom interval\"\n  by (simp add: interval_eq_iff lower_times upper_times ac_simps)\n\nlemma interval_times_zero_right[simp]: \"A * 0 = 0\" for A :: \"'a::linordered_ring interval\"\n  by (simp add: interval_eq_iff lower_times upper_times ac_simps)\n\nlemma interval_times_zero_left[simp]:\n  \"0 * A = 0\" for A :: \"'a::linordered_ring interval\"\n  by (simp add: interval_eq_iff lower_times upper_times ac_simps)\n\ninstantiation \"interval\" :: (\"{preorder,one}\") one\nbegin\n\nlift_definition one_interval::\"'a interval\" is \"(1, 1)\" by auto\nlemma lower_one[simp]: \"lower 1 = 1\"\n  by transfer auto\nlemma upper_one[simp]: \"upper 1 = 1\"\n  by transfer auto\ninstance proof qed\nend\n\ninstance interval :: (\"{one, preorder, linordered_semiring}\") power\nproof qed\n\nlemma set_of_one[simp]: \"set_of (1::'a::{one, order} interval) = {1}\"\n  by (auto simp: set_of_eq)\n\ninstance \"interval\" ::\n  (\"{linordered_idom,linordered_ring, real_normed_algebra, linear_continuum_topology}\") monoid_mult\n  apply standard\n  unfolding interval_eq_set_of_iff set_of_times\n  subgoal\n    by (auto simp: interval_eq_set_of_iff set_of_times; metis mult.assoc)\n  by auto\n\nlemma one_times_ivl_left[simp]: \"1 * A = A\" for A :: \"'a::linordered_idom interval\"\n  by (simp add: interval_eq_iff lower_times upper_times ac_simps min_def max_def)\n\nlemma one_times_ivl_right[simp]: \"A * 1 = A\" for A :: \"'a::linordered_idom interval\"\n  by (metis interval_mul_commute one_times_ivl_left)\n\nlemma set_of_power_mono: \"a^n \\<in> set_of (A^n)\" if \"a \\<in> set_of A\"\n  for a :: \"'a::linordered_idom\"\n  using that\n  by (induction n) (auto intro!: times_in_intervalI)\n\nlemma set_of_add_cong:\n  \"set_of (A + B) = set_of (A' + B')\"\n  if \"set_of A = set_of A'\" \"set_of B = set_of B'\"\n  for A :: \"'a::linordered_ab_group_add interval\"\n  unfolding set_of_plus that ..\n\nlemma set_of_add_inc_left:\n  \"set_of (A + B) \\<subseteq> set_of (A' + B)\"\n  if \"set_of A \\<subseteq> set_of A'\"\n  for A :: \"'a::linordered_ab_group_add interval\"\n  unfolding set_of_plus using that by (auto simp: set_plus_def)\n\nlemma set_of_add_inc_right:\n  \"set_of (A + B) \\<subseteq> set_of (A + B')\"\n  if \"set_of B \\<subseteq> set_of B'\"\n  for A :: \"'a::linordered_ab_group_add interval\"\n  using set_of_add_inc_left[OF that]\n  by (simp add: add.commute)\n\nlemma set_of_add_inc:\n  \"set_of (A + B) \\<subseteq> set_of (A' + B')\"\n  if \"set_of A \\<subseteq> set_of A'\" \"set_of B \\<subseteq> set_of B'\"\n  for A :: \"'a::linordered_ab_group_add interval\"\n  using set_of_add_inc_left[OF that(1)] set_of_add_inc_right[OF that(2)]\n  by auto\n\nlemma set_of_neg_inc:\n  \"set_of (-A) \\<subseteq> set_of (-A')\"\n  if \"set_of A \\<subseteq> set_of A'\"\n  for A :: \"'a::ordered_ab_group_add interval\"\n  using that\n  unfolding set_of_uminus\n  by auto\n\nlemma set_of_sub_inc_left:\n  \"set_of (A - B) \\<subseteq> set_of (A' - B)\"\n  if \"set_of A \\<subseteq> set_of A'\"\n  for A :: \"'a::linordered_ab_group_add interval\"\n  using that\n  unfolding set_of_minus\n  by auto\n\nlemma set_of_sub_inc_right:\n  \"set_of (A - B) \\<subseteq> set_of (A - B')\"\n  if \"set_of B \\<subseteq> set_of B'\"\n  for A :: \"'a::linordered_ab_group_add interval\"\n  using that\n  unfolding set_of_minus\n  by auto\n\nlemma set_of_sub_inc:\n  \"set_of (A - B) \\<subseteq> set_of (A' - B')\"\n  if \"set_of A \\<subseteq> set_of A'\" \"set_of B \\<subseteq> set_of B'\"\n  for A :: \"'a::linordered_idom interval\"\n  using set_of_sub_inc_left[OF that(1)] set_of_sub_inc_right[OF that(2)]\n  by auto\n\nlemma set_of_mul_inc_right:\n  \"set_of (A * B) \\<subseteq> set_of (A * B')\"\n  if \"set_of B \\<subseteq> set_of B'\"\n  for A :: \"'a::linordered_ring interval\"\n  using that\n  apply transfer\n  apply (clarsimp simp add: Let_def)\n  apply (intro conjI)\n         apply (metis linear min.coboundedI1 min.coboundedI2 mult_left_mono mult_left_mono_neg order_trans)\n        apply (metis linear min.coboundedI1 min.coboundedI2 mult_left_mono mult_left_mono_neg order_trans)\n       apply (metis linear min.coboundedI1 min.coboundedI2 mult_left_mono mult_left_mono_neg order_trans)\n      apply (metis linear min.coboundedI1 min.coboundedI2 mult_left_mono mult_left_mono_neg order_trans)\n     apply (metis linear max.coboundedI1 max.coboundedI2 mult_left_mono mult_left_mono_neg order_trans)\n    apply (metis linear max.coboundedI1 max.coboundedI2 mult_left_mono mult_left_mono_neg order_trans)\n   apply (metis linear max.coboundedI1 max.coboundedI2 mult_left_mono mult_left_mono_neg order_trans)\n  apply (metis linear max.coboundedI1 max.coboundedI2 mult_left_mono mult_left_mono_neg order_trans)\n  done\n\nlemma set_of_distrib_left:\n  \"set_of (B * (A1 + A2)) \\<subseteq> set_of (B * A1 + B * A2)\"\n  for A1 :: \"'a::linordered_ring interval\"\n  apply transfer\n  apply (clarsimp simp: Let_def distrib_left distrib_right)\n  apply (intro conjI)\n         apply (metis add_mono min.cobounded1 min.left_commute)\n        apply (metis add_mono min.cobounded1 min.left_commute)\n       apply (metis add_mono min.cobounded1 min.left_commute)\n      apply (metis add_mono min.assoc min.cobounded2)\n     apply (meson add_mono order.trans max.cobounded1 max.cobounded2)\n    apply (meson add_mono order.trans max.cobounded1 max.cobounded2)\n   apply (meson add_mono order.trans max.cobounded1 max.cobounded2)\n  apply (meson add_mono order.trans max.cobounded1 max.cobounded2)\n  done\n\nlemma set_of_distrib_right:\n  \"set_of ((A1 + A2) * B) \\<subseteq> set_of (A1 * B + A2 * B)\"\n  for A1 A2 B :: \"'a::{linordered_ring, real_normed_algebra, linear_continuum_topology} interval\"\n  unfolding set_of_times set_of_plus set_plus_def\n  apply clarsimp\n  subgoal for b a1 a2\n    apply (rule exI[where x=\"a1 * b\"])\n    apply (rule conjI)\n    subgoal by force\n    subgoal\n      apply (rule exI[where x=\"a2 * b\"])\n      apply (rule conjI)\n      subgoal by force\n      subgoal by (simp add: algebra_simps)\n      done\n    done\n  done\n\nlemma set_of_mul_inc_left:\n  \"set_of (A * B) \\<subseteq> set_of (A' * B)\"\n  if \"set_of A \\<subseteq> set_of A'\"\n  for A :: \"'a::{linordered_ring, real_normed_algebra, linear_continuum_topology} interval\"\n  using that\n  unfolding set_of_times\n  by auto\n\nlemma set_of_mul_inc:\n  \"set_of (A * B) \\<subseteq> set_of (A' * B')\"\n  if \"set_of A \\<subseteq> set_of A'\" \"set_of B \\<subseteq> set_of B'\"\n  for A :: \"'a::{linordered_ring, real_normed_algebra, linear_continuum_topology} interval\"\n  using that unfolding set_of_times by auto\n\nlemma set_of_pow_inc:\n  \"set_of (A^n) \\<subseteq> set_of (A'^n)\"\n  if \"set_of A \\<subseteq> set_of A'\"\n  for A :: \"'a::{linordered_idom, real_normed_algebra, linear_continuum_topology} interval\"\n  using that\n  by (induction n, simp_all add: set_of_mul_inc)\n\nlemma set_of_distrib_right_left:\n  \"set_of ((A1 + A2) * (B1 + B2)) \\<subseteq> set_of (A1 * B1 + A1 * B2 + A2 * B1 + A2 * B2)\"\n  for A1 :: \"'a::{linordered_idom, real_normed_algebra, linear_continuum_topology} interval\"\nproof-\n  have \"set_of ((A1 + A2) * (B1 + B2)) \\<subseteq> set_of (A1 * (B1 + B2) + A2 * (B1 + B2))\"\n    by (rule set_of_distrib_right)\n  also have \"... \\<subseteq> set_of ((A1 * B1 + A1 * B2) + A2 * (B1 + B2))\"\n    by (rule set_of_add_inc_left[OF set_of_distrib_left])\n  also have \"... \\<subseteq> set_of ((A1 * B1 + A1 * B2) + (A2 * B1 + A2 * B2))\"\n    by (rule set_of_add_inc_right[OF set_of_distrib_left])\n  finally show ?thesis\n    by (simp add: add.assoc)\nqed\n\nlemma mult_bounds_enclose_zero1:\n  \"min (la * lb) (min (la * ub) (min (lb * ua) (ua * ub))) \\<le> 0\"\n  \"0 \\<le> max (la * lb) (max (la * ub) (max (lb * ua) (ua * ub)))\"\n  if \"la \\<le> 0\" \"0 \\<le> ua\"\n  for la lb ua ub:: \"'a::linordered_idom\"\n  subgoal by (metis (no_types, opaque_lifting) that eq_iff min_le_iff_disj mult_zero_left mult_zero_right\n        zero_le_mult_iff)\n  subgoal by (metis that le_max_iff_disj mult_zero_right order_refl zero_le_mult_iff)\n  done\n\nlemma mult_bounds_enclose_zero2:\n  \"min (la * lb) (min (la * ub) (min (lb * ua) (ua * ub))) \\<le> 0\"\n  \"0 \\<le> max (la * lb) (max (la * ub) (max (lb * ua) (ua * ub)))\"\n  if \"lb \\<le> 0\" \"0 \\<le> ub\"\n  for la lb ua ub:: \"'a::linordered_idom\"\n  using mult_bounds_enclose_zero1[OF that, of la ua]\n  by (simp_all add: ac_simps)\n\nlemma set_of_mul_contains_zero:\n  \"0 \\<in> set_of (A * B)\"\n  if \"0 \\<in> set_of A \\<or> 0 \\<in> set_of B\"\n  for A :: \"'a::linordered_idom interval\"\n  using that\n  by (auto simp: set_of_eq lower_times upper_times algebra_simps mult_le_0_iff\n      mult_bounds_enclose_zero1 mult_bounds_enclose_zero2)\n\ninstance \"interval\" :: (linordered_semiring) mult_zero\n  apply standard\n  subgoal by transfer auto\n  subgoal by transfer auto\n  done\n\nlift_definition min_interval::\"'a::linorder interval \\<Rightarrow> 'a interval \\<Rightarrow> 'a interval\" is\n  \"\\<lambda>(l1, u1). \\<lambda>(l2, u2). (min l1 l2, min u1 u2)\"\n  by (auto simp: min_def)\nlemma lower_min_interval[simp]: \"lower (min_interval x y) = min (lower x) (lower y)\"\n  by transfer auto\nlemma upper_min_interval[simp]: \"upper (min_interval x y) = min (upper x) (upper y)\"\n  by transfer auto\n\nlemma min_intervalI:\n  \"a \\<in>\\<^sub>i A \\<Longrightarrow> b \\<in>\\<^sub>i B \\<Longrightarrow> min a b \\<in>\\<^sub>i min_interval A B\"\n  by (auto simp: set_of_eq min_def)\n\nlift_definition max_interval::\"'a::linorder interval \\<Rightarrow> 'a interval \\<Rightarrow> 'a interval\" is\n  \"\\<lambda>(l1, u1). \\<lambda>(l2, u2). (max l1 l2, max u1 u2)\"\n  by (auto simp: max_def)\nlemma lower_max_interval[simp]: \"lower (max_interval x y) = max (lower x) (lower y)\"\n  by transfer auto\nlemma upper_max_interval[simp]: \"upper (max_interval x y) = max (upper x) (upper y)\"\n  by transfer auto\n\nlemma max_intervalI:\n  \"a \\<in>\\<^sub>i A \\<Longrightarrow> b \\<in>\\<^sub>i B \\<Longrightarrow> max a b \\<in>\\<^sub>i max_interval A B\"\n  by (auto simp: set_of_eq max_def)\n\nlift_definition abs_interval::\"'a::linordered_idom interval \\<Rightarrow> 'a interval\" is\n  \"(\\<lambda>(l,u). (if l < 0 \\<and> 0 < u then 0 else min \\<bar>l\\<bar> \\<bar>u\\<bar>, max \\<bar>l\\<bar> \\<bar>u\\<bar>))\"\n  by auto\n\nlemma lower_abs_interval[simp]:\n  \"lower (abs_interval x) = (if lower x < 0 \\<and> 0 < upper x then 0 else min \\<bar>lower x\\<bar> \\<bar>upper x\\<bar>)\"\n  by transfer auto\nlemma upper_abs_interval[simp]: \"upper (abs_interval x) = max \\<bar>lower x\\<bar> \\<bar>upper x\\<bar>\"\n  by transfer auto\n\nlemma in_abs_intervalI1:\n  \"lx < 0 \\<Longrightarrow> 0 < ux \\<Longrightarrow> 0 \\<le> xa \\<Longrightarrow> xa \\<le> max (- lx) (ux) \\<Longrightarrow> xa \\<in> abs ` {lx..ux}\"\n  for xa::\"'a::linordered_idom\"\n  by (metis abs_minus_cancel abs_of_nonneg atLeastAtMost_iff image_eqI le_less le_max_iff_disj\n      le_minus_iff neg_le_0_iff_le order_trans)\n\nlemma in_abs_intervalI2:\n  \"min (\\<bar>lx\\<bar>) \\<bar>ux\\<bar> \\<le> xa \\<Longrightarrow> xa \\<le> max \\<bar>lx\\<bar> \\<bar>ux\\<bar> \\<Longrightarrow> lx \\<le> ux \\<Longrightarrow> 0 \\<le> lx \\<or> ux \\<le> 0 \\<Longrightarrow>\n    xa \\<in> abs ` {lx..ux}\"\n  for xa::\"'a::linordered_idom\"\n  by (force intro: image_eqI[where x=\"-xa\"] image_eqI[where x=\"xa\"])\n\nlemma set_of_abs_interval: \"set_of (abs_interval x) = abs ` set_of x\"\n  by (auto simp: set_of_eq not_less intro: in_abs_intervalI1 in_abs_intervalI2 cong del: image_cong_simp)\n\nfun split_domain :: \"('a::preorder interval \\<Rightarrow> 'a interval list) \\<Rightarrow> 'a interval list \\<Rightarrow> 'a interval list list\"\n  where \"split_domain split [] = [[]]\"\n  | \"split_domain split (I#Is) = (\n         let S = split I;\n             D = split_domain split Is\n         in concat (map (\\<lambda>d. map (\\<lambda>s. s # d) S) D)\n       )\"\n\ncontext notes [[typedef_overloaded]] begin\nlift_definition(code_dt) split_interval::\"'a::linorder interval \\<Rightarrow> 'a \\<Rightarrow> ('a interval \\<times> 'a interval)\"\n  is \"\\<lambda>(l, u) x. ((min l x, max l x), (min u x, max u x))\"\n  by (auto simp: min_def)\nend\n\nlemma split_domain_nonempty:\n  assumes \"\\<And>I. split I \\<noteq> []\"\n  shows \"split_domain split I \\<noteq> []\"\n  using last_in_set assms\n  by (induction I, auto)\n\nlemma lower_split_interval1: \"lower (fst (split_interval X m)) = min (lower X) m\"\n  and lower_split_interval2: \"lower (snd (split_interval X m)) = min (upper X) m\"\n  and upper_split_interval1: \"upper (fst (split_interval X m)) = max (lower X) m\"\n  and upper_split_interval2: \"upper (snd (split_interval X m)) = max (upper X) m\"\n  subgoal by transfer auto\n  subgoal by transfer (auto simp: min.commute)\n  subgoal by transfer auto\n  subgoal by transfer auto\n  done\n\nlemma split_intervalD: \"split_interval X x = (A, B) \\<Longrightarrow> set_of X \\<subseteq> set_of A \\<union> set_of B\"\n  unfolding set_of_eq\n  by transfer (auto simp: min_def max_def split: if_splits)\n\ninstantiation interval :: (\"{topological_space, preorder}\") topological_space\nbegin\n\ndefinition open_interval_def[code del]: \"open (X::'a interval set) =\n  (\\<forall>x\\<in>X.\n      \\<exists>A B.\n         open A \\<and>\n         open B \\<and>\n         lower x \\<in> A \\<and> upper x \\<in> B \\<and> Interval ` (A \\<times> B) \\<subseteq> X)\"\n\ninstance\nproof\n  show \"open (UNIV :: ('a interval) set)\"\n    unfolding open_interval_def by auto\nnext\n  fix S T :: \"('a interval) set\"\n  assume \"open S\" \"open T\"\n  show \"open (S \\<inter> T)\"\n    unfolding open_interval_def\n  proof (safe)\n    fix x assume \"x \\<in> S\" \"x \\<in> T\"\n    from \\<open>x \\<in> S\\<close> \\<open>open S\\<close> obtain Sl Su where S:\n      \"open Sl\" \"open Su\" \"lower x \\<in> Sl\" \"upper x \\<in> Su\" \"Interval ` (Sl \\<times> Su) \\<subseteq> S\"\n      by (auto simp: open_interval_def)\n    from \\<open>x \\<in> T\\<close> \\<open>open T\\<close> obtain Tl Tu where T:\n      \"open Tl\" \"open Tu\" \"lower x \\<in> Tl\" \"upper x \\<in> Tu\" \"Interval ` (Tl \\<times> Tu) \\<subseteq> T\"\n      by (auto simp: open_interval_def)\n\n    let ?L = \"Sl \\<inter> Tl\" and ?U = \"Su \\<inter> Tu\" \n    have \"open ?L \\<and> open ?U \\<and> lower x \\<in> ?L \\<and> upper x \\<in> ?U \\<and> Interval ` (?L \\<times> ?U) \\<subseteq> S \\<inter> T\"\n      using S T by (auto simp add: open_Int)\n    then show \"\\<exists>A B. open A \\<and> open B \\<and> lower x \\<in> A \\<and> upper x \\<in> B \\<and> Interval ` (A \\<times> B) \\<subseteq> S \\<inter> T\"\n      by fast\n  qed\nqed (unfold open_interval_def, fast)\n\nend\n\n\nsubsection \\<open>Quickcheck\\<close>\n\nlift_definition Ivl::\"'a \\<Rightarrow> 'a::preorder \\<Rightarrow> 'a interval\" is \"\\<lambda>a b. (min a b, b)\"\n  by (auto simp: min_def)\n\ninstantiation interval :: (\"{exhaustive,preorder}\") exhaustive\nbegin\n\ndefinition exhaustive_interval::\"('a interval \\<Rightarrow> (bool \\<times> term list) option)\n     \\<Rightarrow> natural \\<Rightarrow> (bool \\<times> term list) option\"\n  where\n    \"exhaustive_interval f d =\n    Quickcheck_Exhaustive.exhaustive (\\<lambda>x. Quickcheck_Exhaustive.exhaustive (\\<lambda>y. f (Ivl x y)) d) d\"\n\ninstance ..\n\nend\n\ncontext\n  includes term_syntax\nbegin\n\ndefinition [code_unfold]:\n  \"valtermify_interval x y = Code_Evaluation.valtermify (Ivl::'a::{preorder,typerep}\\<Rightarrow>_) {\\<cdot>} x {\\<cdot>} y\"\n\nend\n\ninstantiation interval :: (\"{full_exhaustive,preorder,typerep}\") full_exhaustive\nbegin\n\ndefinition full_exhaustive_interval::\n  \"('a interval \\<times> (unit \\<Rightarrow> term) \\<Rightarrow> (bool \\<times> term list) option)\n     \\<Rightarrow> natural \\<Rightarrow> (bool \\<times> term list) option\" where\n  \"full_exhaustive_interval f d =\n    Quickcheck_Exhaustive.full_exhaustive\n      (\\<lambda>x. Quickcheck_Exhaustive.full_exhaustive (\\<lambda>y. f (valtermify_interval x y)) d) d\"\n\ninstance ..\n\nend\n\ninstantiation interval :: (\"{random,preorder,typerep}\") random\nbegin\n\ndefinition random_interval ::\n  \"natural\n  \\<Rightarrow> natural \\<times> natural\n     \\<Rightarrow> ('a interval \\<times> (unit \\<Rightarrow> term)) \\<times> natural \\<times> natural\" where\n  \"random_interval i =\n  scomp (Quickcheck_Random.random i)\n    (\\<lambda>man. scomp (Quickcheck_Random.random i) (\\<lambda>exp. Pair (valtermify_interval man exp)))\"\n\ninstance ..\n\nend\n\nlifting_update interval.lifting\nlifting_forget interval.lifting\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/Interval.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789457685656, "lm_q2_score": 0.8198933425148214, "lm_q1q2_score": 0.7336319193089168}}
{"text": "(*  Title:      HOL/Limits.thy\n    Author:     Brian Huffman\n    Author:     Jacques D. Fleuriot, University of Cambridge\n    Author:     Lawrence C Paulson\n    Author:     Jeremy Avigad\n*)\n\nsection {* Limits on Real Vector Spaces *}\n\ntheory Limits\nimports Real_Vector_Spaces\nbegin\n\nsubsection {* Filter going to infinity norm *}\n\ndefinition at_infinity :: \"'a::real_normed_vector filter\" where\n  \"at_infinity = (INF r. principal {x. r \\<le> norm x})\"\n\nlemma eventually_at_infinity: \"eventually P at_infinity \\<longleftrightarrow> (\\<exists>b. \\<forall>x. b \\<le> norm x \\<longrightarrow> P x)\"\n  unfolding at_infinity_def\n  by (subst eventually_INF_base)\n     (auto simp: subset_eq eventually_principal intro!: exI[of _ \"max a b\" for a b])\n\nlemma at_infinity_eq_at_top_bot:\n  \"(at_infinity \\<Colon> real filter) = sup at_top at_bot\"\n  apply (simp add: filter_eq_iff eventually_sup eventually_at_infinity\n                   eventually_at_top_linorder eventually_at_bot_linorder)\n  apply safe\n  apply (rule_tac x=\"b\" in exI, simp)\n  apply (rule_tac x=\"- b\" in exI, simp)\n  apply (rule_tac x=\"max (- Na) N\" in exI, auto simp: abs_real_def)\n  done\n\nlemma at_top_le_at_infinity: \"at_top \\<le> (at_infinity :: real filter)\"\n  unfolding at_infinity_eq_at_top_bot by simp\n\nlemma at_bot_le_at_infinity: \"at_bot \\<le> (at_infinity :: real filter)\"\n  unfolding at_infinity_eq_at_top_bot by simp\n\nlemma filterlim_at_top_imp_at_infinity:\n  fixes f :: \"_ \\<Rightarrow> real\"\n  shows \"filterlim f at_top F \\<Longrightarrow> filterlim f at_infinity F\"\n  by (rule filterlim_mono[OF _ at_top_le_at_infinity order_refl])\n\nsubsubsection {* Boundedness *}\n\ndefinition Bfun :: \"('a \\<Rightarrow> 'b::metric_space) \\<Rightarrow> 'a filter \\<Rightarrow> bool\" where\n  Bfun_metric_def: \"Bfun f F = (\\<exists>y. \\<exists>K>0. eventually (\\<lambda>x. dist (f x) y \\<le> K) F)\"\n\nabbreviation Bseq :: \"(nat \\<Rightarrow> 'a::metric_space) \\<Rightarrow> bool\" where\n  \"Bseq X \\<equiv> Bfun X sequentially\"\n\nlemma Bseq_conv_Bfun: \"Bseq X \\<longleftrightarrow> Bfun X sequentially\" ..\n\nlemma Bseq_ignore_initial_segment: \"Bseq X \\<Longrightarrow> Bseq (\\<lambda>n. X (n + k))\"\n  unfolding Bfun_metric_def by (subst eventually_sequentially_seg)\n\nlemma Bseq_offset: \"Bseq (\\<lambda>n. X (n + k)) \\<Longrightarrow> Bseq X\"\n  unfolding Bfun_metric_def by (subst (asm) eventually_sequentially_seg)\n\nlemma Bfun_def:\n  \"Bfun f F \\<longleftrightarrow> (\\<exists>K>0. eventually (\\<lambda>x. norm (f x) \\<le> K) F)\"\n  unfolding Bfun_metric_def norm_conv_dist\nproof safe\n  fix y K assume \"0 < K\" and *: \"eventually (\\<lambda>x. dist (f x) y \\<le> K) F\"\n  moreover have \"eventually (\\<lambda>x. dist (f x) 0 \\<le> dist (f x) y + dist 0 y) F\"\n    by (intro always_eventually) (metis dist_commute dist_triangle)\n  with * have \"eventually (\\<lambda>x. dist (f x) 0 \\<le> K + dist 0 y) F\"\n    by eventually_elim auto\n  with `0 < K` show \"\\<exists>K>0. eventually (\\<lambda>x. dist (f x) 0 \\<le> K) F\"\n    by (intro exI[of _ \"K + dist 0 y\"] add_pos_nonneg conjI zero_le_dist) auto\nqed auto\n\nlemma BfunI:\n  assumes K: \"eventually (\\<lambda>x. norm (f x) \\<le> K) F\" shows \"Bfun f F\"\nunfolding Bfun_def\nproof (intro exI conjI allI)\n  show \"0 < max K 1\" by simp\nnext\n  show \"eventually (\\<lambda>x. norm (f x) \\<le> max K 1) F\"\n    using K by (rule eventually_elim1, simp)\nqed\n\nlemma BfunE:\n  assumes \"Bfun f F\"\n  obtains B where \"0 < B\" and \"eventually (\\<lambda>x. norm (f x) \\<le> B) F\"\nusing assms unfolding Bfun_def by fast\n\nlemma Cauchy_Bseq: \"Cauchy X \\<Longrightarrow> Bseq X\"\n  unfolding Cauchy_def Bfun_metric_def eventually_sequentially\n  apply (erule_tac x=1 in allE)\n  apply simp\n  apply safe\n  apply (rule_tac x=\"X M\" in exI)\n  apply (rule_tac x=1 in exI)\n  apply (erule_tac x=M in allE)\n  apply simp\n  apply (rule_tac x=M in exI)\n  apply (auto simp: dist_commute)\n  done\n\n\nsubsubsection {* Bounded Sequences *}\n\nlemma BseqI': \"(\\<And>n. norm (X n) \\<le> K) \\<Longrightarrow> Bseq X\"\n  by (intro BfunI) (auto simp: eventually_sequentially)\n\nlemma BseqI2': \"\\<forall>n\\<ge>N. norm (X n) \\<le> K \\<Longrightarrow> Bseq X\"\n  by (intro BfunI) (auto simp: eventually_sequentially)\n\nlemma Bseq_def: \"Bseq X \\<longleftrightarrow> (\\<exists>K>0. \\<forall>n. norm (X n) \\<le> K)\"\n  unfolding Bfun_def eventually_sequentially\nproof safe\n  fix N K assume \"0 < K\" \"\\<forall>n\\<ge>N. norm (X n) \\<le> K\"\n  then show \"\\<exists>K>0. \\<forall>n. norm (X n) \\<le> K\"\n    by (intro exI[of _ \"max (Max (norm ` X ` {..N})) K\"] max.strict_coboundedI2)\n       (auto intro!: imageI not_less[where 'a=nat, THEN iffD1] Max_ge simp: le_max_iff_disj)\nqed auto\n\nlemma BseqE: \"\\<lbrakk>Bseq X; \\<And>K. \\<lbrakk>0 < K; \\<forall>n. norm (X n) \\<le> K\\<rbrakk> \\<Longrightarrow> Q\\<rbrakk> \\<Longrightarrow> Q\"\nunfolding Bseq_def by auto\n\nlemma BseqD: \"Bseq X ==> \\<exists>K. 0 < K & (\\<forall>n. norm (X n) \\<le> K)\"\nby (simp add: Bseq_def)\n\nlemma BseqI: \"[| 0 < K; \\<forall>n. norm (X n) \\<le> K |] ==> Bseq X\"\nby (auto simp add: Bseq_def)\n\nlemma Bseq_bdd_above: \"Bseq (X::nat \\<Rightarrow> real) \\<Longrightarrow> bdd_above (range X)\"\nproof (elim BseqE, intro bdd_aboveI2)\n  fix K n assume \"0 < K\" \"\\<forall>n. norm (X n) \\<le> K\" then show \"X n \\<le> K\"\n    by (auto elim!: allE[of _ n])\nqed\n\nlemma Bseq_bdd_below: \"Bseq (X::nat \\<Rightarrow> real) \\<Longrightarrow> bdd_below (range X)\"\nproof (elim BseqE, intro bdd_belowI2)\n  fix K n assume \"0 < K\" \"\\<forall>n. norm (X n) \\<le> K\" then show \"- K \\<le> X n\"\n    by (auto elim!: allE[of _ n])\nqed\n\nlemma lemma_NBseq_def:\n  \"(\\<exists>K > 0. \\<forall>n. norm (X n) \\<le> K) = (\\<exists>N. \\<forall>n. norm (X n) \\<le> real(Suc N))\"\nproof safe\n  fix K :: real\n  from reals_Archimedean2 obtain n :: nat where \"K < real n\" ..\n  then have \"K \\<le> real (Suc n)\" by auto\n  moreover assume \"\\<forall>m. norm (X m) \\<le> K\"\n  ultimately have \"\\<forall>m. norm (X m) \\<le> real (Suc n)\"\n    by (blast intro: order_trans)\n  then show \"\\<exists>N. \\<forall>n. norm (X n) \\<le> real (Suc N)\" ..\nqed (force simp add: real_of_nat_Suc)\n\ntext{* alternative definition for Bseq *}\nlemma Bseq_iff: \"Bseq X = (\\<exists>N. \\<forall>n. norm (X n) \\<le> real(Suc N))\"\napply (simp add: Bseq_def)\napply (simp (no_asm) add: lemma_NBseq_def)\ndone\n\nlemma lemma_NBseq_def2:\n     \"(\\<exists>K > 0. \\<forall>n. norm (X n) \\<le> K) = (\\<exists>N. \\<forall>n. norm (X n) < real(Suc N))\"\napply (subst lemma_NBseq_def, auto)\napply (rule_tac x = \"Suc N\" in exI)\napply (rule_tac [2] x = N in exI)\napply (auto simp add: real_of_nat_Suc)\n prefer 2 apply (blast intro: order_less_imp_le)\napply (drule_tac x = n in spec, simp)\ndone\n\n(* yet another definition for Bseq *)\nlemma Bseq_iff1a: \"Bseq X = (\\<exists>N. \\<forall>n. norm (X n) < real(Suc N))\"\nby (simp add: Bseq_def lemma_NBseq_def2)\n\nsubsubsection{*A Few More Equivalence Theorems for Boundedness*}\n\ntext{*alternative formulation for boundedness*}\nlemma Bseq_iff2: \"Bseq X = (\\<exists>k > 0. \\<exists>x. \\<forall>n. norm (X(n) + -x) \\<le> k)\"\napply (unfold Bseq_def, safe)\napply (rule_tac [2] x = \"k + norm x\" in exI)\napply (rule_tac x = K in exI, simp)\napply (rule exI [where x = 0], auto)\napply (erule order_less_le_trans, simp)\napply (drule_tac x=n in spec)\napply (drule order_trans [OF norm_triangle_ineq2])\napply simp\ndone\n\ntext{*alternative formulation for boundedness*}\nlemma Bseq_iff3:\n  \"Bseq X \\<longleftrightarrow> (\\<exists>k>0. \\<exists>N. \\<forall>n. norm (X n + - X N) \\<le> k)\" (is \"?P \\<longleftrightarrow> ?Q\")\nproof\n  assume ?P\n  then obtain K\n    where *: \"0 < K\" and **: \"\\<And>n. norm (X n) \\<le> K\" by (auto simp add: Bseq_def)\n  from * have \"0 < K + norm (X 0)\" by (rule order_less_le_trans) simp\n  from ** have \"\\<forall>n. norm (X n - X 0) \\<le> K + norm (X 0)\"\n    by (auto intro: order_trans norm_triangle_ineq4)\n  then have \"\\<forall>n. norm (X n + - X 0) \\<le> K + norm (X 0)\"\n    by simp\n  with `0 < K + norm (X 0)` show ?Q by blast\nnext\n  assume ?Q then show ?P by (auto simp add: Bseq_iff2)\nqed\n\nlemma BseqI2: \"(\\<forall>n. k \\<le> f n & f n \\<le> (K::real)) ==> Bseq f\"\napply (simp add: Bseq_def)\napply (rule_tac x = \" (\\<bar>k\\<bar> + \\<bar>K\\<bar>) + 1\" in exI, auto)\napply (drule_tac x = n in spec, arith)\ndone\n\n\nsubsubsection{*Upper Bounds and Lubs of Bounded Sequences*}\n\nlemma Bseq_minus_iff: \"Bseq (%n. -(X n) :: 'a :: real_normed_vector) = Bseq X\"\n  by (simp add: Bseq_def)\n\nlemma Bseq_eq_bounded: \"range f \\<subseteq> {a .. b::real} \\<Longrightarrow> Bseq f\"\n  apply (simp add: subset_eq)\n  apply (rule BseqI'[where K=\"max (norm a) (norm b)\"])\n  apply (erule_tac x=n in allE)\n  apply auto\n  done\n\nlemma incseq_bounded: \"incseq X \\<Longrightarrow> \\<forall>i. X i \\<le> (B::real) \\<Longrightarrow> Bseq X\"\n  by (intro Bseq_eq_bounded[of X \"X 0\" B]) (auto simp: incseq_def)\n\nlemma decseq_bounded: \"decseq X \\<Longrightarrow> \\<forall>i. (B::real) \\<le> X i \\<Longrightarrow> Bseq X\"\n  by (intro Bseq_eq_bounded[of X B \"X 0\"]) (auto simp: decseq_def)\n\nsubsection {* Bounded Monotonic Sequences *}\n\nsubsubsection{*A Bounded and Monotonic Sequence Converges*}\n\n(* TODO: delete *)\n(* FIXME: one use in NSA/HSEQ.thy *)\nlemma Bmonoseq_LIMSEQ: \"\\<forall>n. m \\<le> n --> X n = X m ==> \\<exists>L. (X ----> L)\"\n  apply (rule_tac x=\"X m\" in exI)\n  apply (rule filterlim_cong[THEN iffD2, OF refl refl _ tendsto_const])\n  unfolding eventually_sequentially\n  apply blast\n  done\n\nsubsection {* Convergence to Zero *}\n\ndefinition Zfun :: \"('a \\<Rightarrow> 'b::real_normed_vector) \\<Rightarrow> 'a filter \\<Rightarrow> bool\"\n  where \"Zfun f F = (\\<forall>r>0. eventually (\\<lambda>x. norm (f x) < r) F)\"\n\nlemma ZfunI:\n  \"(\\<And>r. 0 < r \\<Longrightarrow> eventually (\\<lambda>x. norm (f x) < r) F) \\<Longrightarrow> Zfun f F\"\n  unfolding Zfun_def by simp\n\nlemma ZfunD:\n  \"\\<lbrakk>Zfun f F; 0 < r\\<rbrakk> \\<Longrightarrow> eventually (\\<lambda>x. norm (f x) < r) F\"\n  unfolding Zfun_def by simp\n\nlemma Zfun_ssubst:\n  \"eventually (\\<lambda>x. f x = g x) F \\<Longrightarrow> Zfun g F \\<Longrightarrow> Zfun f F\"\n  unfolding Zfun_def by (auto elim!: eventually_rev_mp)\n\nlemma Zfun_zero: \"Zfun (\\<lambda>x. 0) F\"\n  unfolding Zfun_def by simp\n\nlemma Zfun_norm_iff: \"Zfun (\\<lambda>x. norm (f x)) F = Zfun (\\<lambda>x. f x) F\"\n  unfolding Zfun_def by simp\n\nlemma Zfun_imp_Zfun:\n  assumes f: \"Zfun f F\"\n  assumes g: \"eventually (\\<lambda>x. norm (g x) \\<le> norm (f x) * K) F\"\n  shows \"Zfun (\\<lambda>x. g x) F\"\nproof (cases)\n  assume K: \"0 < K\"\n  show ?thesis\n  proof (rule ZfunI)\n    fix r::real assume \"0 < r\"\n    hence \"0 < r / K\" using K by simp\n    then have \"eventually (\\<lambda>x. norm (f x) < r / K) F\"\n      using ZfunD [OF f] by fast\n    with g show \"eventually (\\<lambda>x. norm (g x) < r) F\"\n    proof eventually_elim\n      case (elim x)\n      hence \"norm (f x) * K < r\"\n        by (simp add: pos_less_divide_eq K)\n      thus ?case\n        by (simp add: order_le_less_trans [OF elim(1)])\n    qed\n  qed\nnext\n  assume \"\\<not> 0 < K\"\n  hence K: \"K \\<le> 0\" by (simp only: not_less)\n  show ?thesis\n  proof (rule ZfunI)\n    fix r :: real\n    assume \"0 < r\"\n    from g show \"eventually (\\<lambda>x. norm (g x) < r) F\"\n    proof eventually_elim\n      case (elim x)\n      also have \"norm (f x) * K \\<le> norm (f x) * 0\"\n        using K norm_ge_zero by (rule mult_left_mono)\n      finally show ?case\n        using `0 < r` by simp\n    qed\n  qed\nqed\n\nlemma Zfun_le: \"\\<lbrakk>Zfun g F; \\<forall>x. norm (f x) \\<le> norm (g x)\\<rbrakk> \\<Longrightarrow> Zfun f F\"\n  by (erule_tac K=\"1\" in Zfun_imp_Zfun, simp)\n\nlemma Zfun_add:\n  assumes f: \"Zfun f F\" and g: \"Zfun g F\"\n  shows \"Zfun (\\<lambda>x. f x + g x) F\"\nproof (rule ZfunI)\n  fix r::real assume \"0 < r\"\n  hence r: \"0 < r / 2\" by simp\n  have \"eventually (\\<lambda>x. norm (f x) < r/2) F\"\n    using f r by (rule ZfunD)\n  moreover\n  have \"eventually (\\<lambda>x. norm (g x) < r/2) F\"\n    using g r by (rule ZfunD)\n  ultimately\n  show \"eventually (\\<lambda>x. norm (f x + g x) < r) F\"\n  proof eventually_elim\n    case (elim x)\n    have \"norm (f x + g x) \\<le> norm (f x) + norm (g x)\"\n      by (rule norm_triangle_ineq)\n    also have \"\\<dots> < r/2 + r/2\"\n      using elim by (rule add_strict_mono)\n    finally show ?case\n      by simp\n  qed\nqed\n\nlemma Zfun_minus: \"Zfun f F \\<Longrightarrow> Zfun (\\<lambda>x. - f x) F\"\n  unfolding Zfun_def by simp\n\nlemma Zfun_diff: \"\\<lbrakk>Zfun f F; Zfun g F\\<rbrakk> \\<Longrightarrow> Zfun (\\<lambda>x. f x - g x) F\"\n  using Zfun_add [of f F \"\\<lambda>x. - g x\"] by (simp add: Zfun_minus)\n\nlemma (in bounded_linear) Zfun:\n  assumes g: \"Zfun g F\"\n  shows \"Zfun (\\<lambda>x. f (g x)) F\"\nproof -\n  obtain K where \"\\<And>x. norm (f x) \\<le> norm x * K\"\n    using bounded by fast\n  then have \"eventually (\\<lambda>x. norm (f (g x)) \\<le> norm (g x) * K) F\"\n    by simp\n  with g show ?thesis\n    by (rule Zfun_imp_Zfun)\nqed\n\nlemma (in bounded_bilinear) Zfun:\n  assumes f: \"Zfun f F\"\n  assumes g: \"Zfun g F\"\n  shows \"Zfun (\\<lambda>x. f x ** g x) F\"\nproof (rule ZfunI)\n  fix r::real assume r: \"0 < r\"\n  obtain K where K: \"0 < K\"\n    and norm_le: \"\\<And>x y. norm (x ** y) \\<le> norm x * norm y * K\"\n    using pos_bounded by fast\n  from K have K': \"0 < inverse K\"\n    by (rule positive_imp_inverse_positive)\n  have \"eventually (\\<lambda>x. norm (f x) < r) F\"\n    using f r by (rule ZfunD)\n  moreover\n  have \"eventually (\\<lambda>x. norm (g x) < inverse K) F\"\n    using g K' by (rule ZfunD)\n  ultimately\n  show \"eventually (\\<lambda>x. norm (f x ** g x) < r) F\"\n  proof eventually_elim\n    case (elim x)\n    have \"norm (f x ** g x) \\<le> norm (f x) * norm (g x) * K\"\n      by (rule norm_le)\n    also have \"norm (f x) * norm (g x) * K < r * inverse K * K\"\n      by (intro mult_strict_right_mono mult_strict_mono' norm_ge_zero elim K)\n    also from K have \"r * inverse K * K = r\"\n      by simp\n    finally show ?case .\n  qed\nqed\n\nlemma (in bounded_bilinear) Zfun_left:\n  \"Zfun f F \\<Longrightarrow> Zfun (\\<lambda>x. f x ** a) F\"\n  by (rule bounded_linear_left [THEN bounded_linear.Zfun])\n\nlemma (in bounded_bilinear) Zfun_right:\n  \"Zfun f F \\<Longrightarrow> Zfun (\\<lambda>x. a ** f x) F\"\n  by (rule bounded_linear_right [THEN bounded_linear.Zfun])\n\nlemmas Zfun_mult = bounded_bilinear.Zfun [OF bounded_bilinear_mult]\nlemmas Zfun_mult_right = bounded_bilinear.Zfun_right [OF bounded_bilinear_mult]\nlemmas Zfun_mult_left = bounded_bilinear.Zfun_left [OF bounded_bilinear_mult]\n\nlemma tendsto_Zfun_iff: \"(f ---> a) F = Zfun (\\<lambda>x. f x - a) F\"\n  by (simp only: tendsto_iff Zfun_def dist_norm)\n\nlemma tendsto_0_le: \"\\<lbrakk>(f ---> 0) F; eventually (\\<lambda>x. norm (g x) \\<le> norm (f x) * K) F\\<rbrakk> \n                     \\<Longrightarrow> (g ---> 0) F\"\n  by (simp add: Zfun_imp_Zfun tendsto_Zfun_iff)\n\nsubsubsection {* Distance and norms *}\n\nlemma tendsto_dist [tendsto_intros]:\n  fixes l m :: \"'a :: metric_space\"\n  assumes f: \"(f ---> l) F\" and g: \"(g ---> m) F\"\n  shows \"((\\<lambda>x. dist (f x) (g x)) ---> dist l m) F\"\nproof (rule tendstoI)\n  fix e :: real assume \"0 < e\"\n  hence e2: \"0 < e/2\" by simp\n  from tendstoD [OF f e2] tendstoD [OF g e2]\n  show \"eventually (\\<lambda>x. dist (dist (f x) (g x)) (dist l m) < e) F\"\n  proof (eventually_elim)\n    case (elim x)\n    then show \"dist (dist (f x) (g x)) (dist l m) < e\"\n      unfolding dist_real_def\n      using dist_triangle2 [of \"f x\" \"g x\" \"l\"]\n      using dist_triangle2 [of \"g x\" \"l\" \"m\"]\n      using dist_triangle3 [of \"l\" \"m\" \"f x\"]\n      using dist_triangle [of \"f x\" \"m\" \"g x\"]\n      by arith\n  qed\nqed\n\nlemma continuous_dist[continuous_intros]:\n  fixes f g :: \"_ \\<Rightarrow> 'a :: metric_space\"\n  shows \"continuous F f \\<Longrightarrow> continuous F g \\<Longrightarrow> continuous F (\\<lambda>x. dist (f x) (g x))\"\n  unfolding continuous_def by (rule tendsto_dist)\n\nlemma continuous_on_dist[continuous_intros]:\n  fixes f g :: \"_ \\<Rightarrow> 'a :: metric_space\"\n  shows \"continuous_on s f \\<Longrightarrow> continuous_on s g \\<Longrightarrow> continuous_on s (\\<lambda>x. dist (f x) (g x))\"\n  unfolding continuous_on_def by (auto intro: tendsto_dist)\n\nlemma tendsto_norm [tendsto_intros]:\n  \"(f ---> a) F \\<Longrightarrow> ((\\<lambda>x. norm (f x)) ---> norm a) F\"\n  unfolding norm_conv_dist by (intro tendsto_intros)\n\nlemma continuous_norm [continuous_intros]:\n  \"continuous F f \\<Longrightarrow> continuous F (\\<lambda>x. norm (f x))\"\n  unfolding continuous_def by (rule tendsto_norm)\n\nlemma continuous_on_norm [continuous_intros]:\n  \"continuous_on s f \\<Longrightarrow> continuous_on s (\\<lambda>x. norm (f x))\"\n  unfolding continuous_on_def by (auto intro: tendsto_norm)\n\nlemma tendsto_norm_zero:\n  \"(f ---> 0) F \\<Longrightarrow> ((\\<lambda>x. norm (f x)) ---> 0) F\"\n  by (drule tendsto_norm, simp)\n\nlemma tendsto_norm_zero_cancel:\n  \"((\\<lambda>x. norm (f x)) ---> 0) F \\<Longrightarrow> (f ---> 0) F\"\n  unfolding tendsto_iff dist_norm by simp\n\nlemma tendsto_norm_zero_iff:\n  \"((\\<lambda>x. norm (f x)) ---> 0) F \\<longleftrightarrow> (f ---> 0) F\"\n  unfolding tendsto_iff dist_norm by simp\n\nlemma tendsto_rabs [tendsto_intros]:\n  \"(f ---> (l::real)) F \\<Longrightarrow> ((\\<lambda>x. \\<bar>f x\\<bar>) ---> \\<bar>l\\<bar>) F\"\n  by (fold real_norm_def, rule tendsto_norm)\n\nlemma continuous_rabs [continuous_intros]:\n  \"continuous F f \\<Longrightarrow> continuous F (\\<lambda>x. \\<bar>f x :: real\\<bar>)\"\n  unfolding real_norm_def[symmetric] by (rule continuous_norm)\n\nlemma continuous_on_rabs [continuous_intros]:\n  \"continuous_on s f \\<Longrightarrow> continuous_on s (\\<lambda>x. \\<bar>f x :: real\\<bar>)\"\n  unfolding real_norm_def[symmetric] by (rule continuous_on_norm)\n\nlemma tendsto_rabs_zero:\n  \"(f ---> (0::real)) F \\<Longrightarrow> ((\\<lambda>x. \\<bar>f x\\<bar>) ---> 0) F\"\n  by (fold real_norm_def, rule tendsto_norm_zero)\n\nlemma tendsto_rabs_zero_cancel:\n  \"((\\<lambda>x. \\<bar>f x\\<bar>) ---> (0::real)) F \\<Longrightarrow> (f ---> 0) F\"\n  by (fold real_norm_def, rule tendsto_norm_zero_cancel)\n\nlemma tendsto_rabs_zero_iff:\n  \"((\\<lambda>x. \\<bar>f x\\<bar>) ---> (0::real)) F \\<longleftrightarrow> (f ---> 0) F\"\n  by (fold real_norm_def, rule tendsto_norm_zero_iff)\n\nsubsubsection {* Addition and subtraction *}\n\nlemma tendsto_add [tendsto_intros]:\n  fixes a b :: \"'a::real_normed_vector\"\n  shows \"\\<lbrakk>(f ---> a) F; (g ---> b) F\\<rbrakk> \\<Longrightarrow> ((\\<lambda>x. f x + g x) ---> a + b) F\"\n  by (simp only: tendsto_Zfun_iff add_diff_add Zfun_add)\n\nlemma continuous_add [continuous_intros]:\n  fixes f g :: \"'a::t2_space \\<Rightarrow> 'b::real_normed_vector\"\n  shows \"continuous F f \\<Longrightarrow> continuous F g \\<Longrightarrow> continuous F (\\<lambda>x. f x + g x)\"\n  unfolding continuous_def by (rule tendsto_add)\n\nlemma continuous_on_add [continuous_intros]:\n  fixes f g :: \"_ \\<Rightarrow> 'b::real_normed_vector\"\n  shows \"continuous_on s f \\<Longrightarrow> continuous_on s g \\<Longrightarrow> continuous_on s (\\<lambda>x. f x + g x)\"\n  unfolding continuous_on_def by (auto intro: tendsto_add)\n\nlemma tendsto_add_zero:\n  fixes f g :: \"_ \\<Rightarrow> 'b::real_normed_vector\"\n  shows \"\\<lbrakk>(f ---> 0) F; (g ---> 0) F\\<rbrakk> \\<Longrightarrow> ((\\<lambda>x. f x + g x) ---> 0) F\"\n  by (drule (1) tendsto_add, simp)\n\nlemma tendsto_minus [tendsto_intros]:\n  fixes a :: \"'a::real_normed_vector\"\n  shows \"(f ---> a) F \\<Longrightarrow> ((\\<lambda>x. - f x) ---> - a) F\"\n  by (simp only: tendsto_Zfun_iff minus_diff_minus Zfun_minus)\n\nlemma continuous_minus [continuous_intros]:\n  fixes f :: \"'a::t2_space \\<Rightarrow> 'b::real_normed_vector\"\n  shows \"continuous F f \\<Longrightarrow> continuous F (\\<lambda>x. - f x)\"\n  unfolding continuous_def by (rule tendsto_minus)\n\nlemma continuous_on_minus [continuous_intros]:\n  fixes f :: \"_ \\<Rightarrow> 'b::real_normed_vector\"\n  shows \"continuous_on s f \\<Longrightarrow> continuous_on s (\\<lambda>x. - f x)\"\n  unfolding continuous_on_def by (auto intro: tendsto_minus)\n\nlemma tendsto_minus_cancel:\n  fixes a :: \"'a::real_normed_vector\"\n  shows \"((\\<lambda>x. - f x) ---> - a) F \\<Longrightarrow> (f ---> a) F\"\n  by (drule tendsto_minus, simp)\n\nlemma tendsto_minus_cancel_left:\n    \"(f ---> - (y::_::real_normed_vector)) F \\<longleftrightarrow> ((\\<lambda>x. - f x) ---> y) F\"\n  using tendsto_minus_cancel[of f \"- y\" F]  tendsto_minus[of f \"- y\" F]\n  by auto\n\nlemma tendsto_diff [tendsto_intros]:\n  fixes a b :: \"'a::real_normed_vector\"\n  shows \"\\<lbrakk>(f ---> a) F; (g ---> b) F\\<rbrakk> \\<Longrightarrow> ((\\<lambda>x. f x - g x) ---> a - b) F\"\n  using tendsto_add [of f a F \"\\<lambda>x. - g x\" \"- b\"] by (simp add: tendsto_minus)\n\nlemma continuous_diff [continuous_intros]:\n  fixes f g :: \"'a::t2_space \\<Rightarrow> 'b::real_normed_vector\"\n  shows \"continuous F f \\<Longrightarrow> continuous F g \\<Longrightarrow> continuous F (\\<lambda>x. f x - g x)\"\n  unfolding continuous_def by (rule tendsto_diff)\n\nlemma continuous_on_diff [continuous_intros]:\n  fixes f g :: \"'a::t2_space \\<Rightarrow> 'b::real_normed_vector\"\n  shows \"continuous_on s f \\<Longrightarrow> continuous_on s g \\<Longrightarrow> continuous_on s (\\<lambda>x. f x - g x)\"\n  unfolding continuous_on_def by (auto intro: tendsto_diff)\n\nlemma tendsto_setsum [tendsto_intros]:\n  fixes f :: \"'a \\<Rightarrow> 'b \\<Rightarrow> 'c::real_normed_vector\"\n  assumes \"\\<And>i. i \\<in> S \\<Longrightarrow> (f i ---> a i) F\"\n  shows \"((\\<lambda>x. \\<Sum>i\\<in>S. f i x) ---> (\\<Sum>i\\<in>S. a i)) F\"\nproof (cases \"finite S\")\n  assume \"finite S\" thus ?thesis using assms\n    by (induct, simp, simp add: tendsto_add)\nqed simp\n\nlemma continuous_setsum [continuous_intros]:\n  fixes f :: \"'a \\<Rightarrow> 'b::t2_space \\<Rightarrow> 'c::real_normed_vector\"\n  shows \"(\\<And>i. i \\<in> S \\<Longrightarrow> continuous F (f i)) \\<Longrightarrow> continuous F (\\<lambda>x. \\<Sum>i\\<in>S. f i x)\"\n  unfolding continuous_def by (rule tendsto_setsum)\n\nlemma continuous_on_setsum [continuous_intros]:\n  fixes f :: \"'a \\<Rightarrow> _ \\<Rightarrow> 'c::real_normed_vector\"\n  shows \"(\\<And>i. i \\<in> S \\<Longrightarrow> continuous_on s (f i)) \\<Longrightarrow> continuous_on s (\\<lambda>x. \\<Sum>i\\<in>S. f i x)\"\n  unfolding continuous_on_def by (auto intro: tendsto_setsum)\n\nlemmas real_tendsto_sandwich = tendsto_sandwich[where 'b=real]\n\nsubsubsection {* Linear operators and multiplication *}\n\nlemma (in bounded_linear) tendsto:\n  \"(g ---> a) F \\<Longrightarrow> ((\\<lambda>x. f (g x)) ---> f a) F\"\n  by (simp only: tendsto_Zfun_iff diff [symmetric] Zfun)\n\nlemma (in bounded_linear) continuous:\n  \"continuous F g \\<Longrightarrow> continuous F (\\<lambda>x. f (g x))\"\n  using tendsto[of g _ F] by (auto simp: continuous_def)\n\nlemma (in bounded_linear) continuous_on:\n  \"continuous_on s g \\<Longrightarrow> continuous_on s (\\<lambda>x. f (g x))\"\n  using tendsto[of g] by (auto simp: continuous_on_def)\n\nlemma (in bounded_linear) tendsto_zero:\n  \"(g ---> 0) F \\<Longrightarrow> ((\\<lambda>x. f (g x)) ---> 0) F\"\n  by (drule tendsto, simp only: zero)\n\nlemma (in bounded_bilinear) tendsto:\n  \"\\<lbrakk>(f ---> a) F; (g ---> b) F\\<rbrakk> \\<Longrightarrow> ((\\<lambda>x. f x ** g x) ---> a ** b) F\"\n  by (simp only: tendsto_Zfun_iff prod_diff_prod\n                 Zfun_add Zfun Zfun_left Zfun_right)\n\nlemma (in bounded_bilinear) continuous:\n  \"continuous F f \\<Longrightarrow> continuous F g \\<Longrightarrow> continuous F (\\<lambda>x. f x ** g x)\"\n  using tendsto[of f _ F g] by (auto simp: continuous_def)\n\nlemma (in bounded_bilinear) continuous_on:\n  \"continuous_on s f \\<Longrightarrow> continuous_on s g \\<Longrightarrow> continuous_on s (\\<lambda>x. f x ** g x)\"\n  using tendsto[of f _ _ g] by (auto simp: continuous_on_def)\n\nlemma (in bounded_bilinear) tendsto_zero:\n  assumes f: \"(f ---> 0) F\"\n  assumes g: \"(g ---> 0) F\"\n  shows \"((\\<lambda>x. f x ** g x) ---> 0) F\"\n  using tendsto [OF f g] by (simp add: zero_left)\n\nlemma (in bounded_bilinear) tendsto_left_zero:\n  \"(f ---> 0) F \\<Longrightarrow> ((\\<lambda>x. f x ** c) ---> 0) F\"\n  by (rule bounded_linear.tendsto_zero [OF bounded_linear_left])\n\nlemma (in bounded_bilinear) tendsto_right_zero:\n  \"(f ---> 0) F \\<Longrightarrow> ((\\<lambda>x. c ** f x) ---> 0) F\"\n  by (rule bounded_linear.tendsto_zero [OF bounded_linear_right])\n\nlemmas tendsto_of_real [tendsto_intros] =\n  bounded_linear.tendsto [OF bounded_linear_of_real]\n\nlemmas tendsto_scaleR [tendsto_intros] =\n  bounded_bilinear.tendsto [OF bounded_bilinear_scaleR]\n\nlemmas tendsto_mult [tendsto_intros] =\n  bounded_bilinear.tendsto [OF bounded_bilinear_mult]\n\nlemmas continuous_of_real [continuous_intros] =\n  bounded_linear.continuous [OF bounded_linear_of_real]\n\nlemmas continuous_scaleR [continuous_intros] =\n  bounded_bilinear.continuous [OF bounded_bilinear_scaleR]\n\nlemmas continuous_mult [continuous_intros] =\n  bounded_bilinear.continuous [OF bounded_bilinear_mult]\n\nlemmas continuous_on_of_real [continuous_intros] =\n  bounded_linear.continuous_on [OF bounded_linear_of_real]\n\nlemmas continuous_on_scaleR [continuous_intros] =\n  bounded_bilinear.continuous_on [OF bounded_bilinear_scaleR]\n\nlemmas continuous_on_mult [continuous_intros] =\n  bounded_bilinear.continuous_on [OF bounded_bilinear_mult]\n\nlemmas tendsto_mult_zero =\n  bounded_bilinear.tendsto_zero [OF bounded_bilinear_mult]\n\nlemmas tendsto_mult_left_zero =\n  bounded_bilinear.tendsto_left_zero [OF bounded_bilinear_mult]\n\nlemmas tendsto_mult_right_zero =\n  bounded_bilinear.tendsto_right_zero [OF bounded_bilinear_mult]\n\nlemma tendsto_power [tendsto_intros]:\n  fixes f :: \"'a \\<Rightarrow> 'b::{power,real_normed_algebra}\"\n  shows \"(f ---> a) F \\<Longrightarrow> ((\\<lambda>x. f x ^ n) ---> a ^ n) F\"\n  by (induct n) (simp_all add: tendsto_mult)\n\nlemma continuous_power [continuous_intros]:\n  fixes f :: \"'a::t2_space \\<Rightarrow> 'b::{power,real_normed_algebra}\"\n  shows \"continuous F f \\<Longrightarrow> continuous F (\\<lambda>x. (f x)^n)\"\n  unfolding continuous_def by (rule tendsto_power)\n\nlemma continuous_on_power [continuous_intros]:\n  fixes f :: \"_ \\<Rightarrow> 'b::{power,real_normed_algebra}\"\n  shows \"continuous_on s f \\<Longrightarrow> continuous_on s (\\<lambda>x. (f x)^n)\"\n  unfolding continuous_on_def by (auto intro: tendsto_power)\n\nlemma tendsto_setprod [tendsto_intros]:\n  fixes f :: \"'a \\<Rightarrow> 'b \\<Rightarrow> 'c::{real_normed_algebra,comm_ring_1}\"\n  assumes \"\\<And>i. i \\<in> S \\<Longrightarrow> (f i ---> L i) F\"\n  shows \"((\\<lambda>x. \\<Prod>i\\<in>S. f i x) ---> (\\<Prod>i\\<in>S. L i)) F\"\nproof (cases \"finite S\")\n  assume \"finite S\" thus ?thesis using assms\n    by (induct, simp, simp add: tendsto_mult)\nqed simp\n\nlemma continuous_setprod [continuous_intros]:\n  fixes f :: \"'a \\<Rightarrow> 'b::t2_space \\<Rightarrow> 'c::{real_normed_algebra,comm_ring_1}\"\n  shows \"(\\<And>i. i \\<in> S \\<Longrightarrow> continuous F (f i)) \\<Longrightarrow> continuous F (\\<lambda>x. \\<Prod>i\\<in>S. f i x)\"\n  unfolding continuous_def by (rule tendsto_setprod)\n\nlemma continuous_on_setprod [continuous_intros]:\n  fixes f :: \"'a \\<Rightarrow> _ \\<Rightarrow> 'c::{real_normed_algebra,comm_ring_1}\"\n  shows \"(\\<And>i. i \\<in> S \\<Longrightarrow> continuous_on s (f i)) \\<Longrightarrow> continuous_on s (\\<lambda>x. \\<Prod>i\\<in>S. f i x)\"\n  unfolding continuous_on_def by (auto intro: tendsto_setprod)\n\nsubsubsection {* Inverse and division *}\n\nlemma (in bounded_bilinear) Zfun_prod_Bfun:\n  assumes f: \"Zfun f F\"\n  assumes g: \"Bfun g F\"\n  shows \"Zfun (\\<lambda>x. f x ** g x) F\"\nproof -\n  obtain K where K: \"0 \\<le> K\"\n    and norm_le: \"\\<And>x y. norm (x ** y) \\<le> norm x * norm y * K\"\n    using nonneg_bounded by fast\n  obtain B where B: \"0 < B\"\n    and norm_g: \"eventually (\\<lambda>x. norm (g x) \\<le> B) F\"\n    using g by (rule BfunE)\n  have \"eventually (\\<lambda>x. norm (f x ** g x) \\<le> norm (f x) * (B * K)) F\"\n  using norm_g proof eventually_elim\n    case (elim x)\n    have \"norm (f x ** g x) \\<le> norm (f x) * norm (g x) * K\"\n      by (rule norm_le)\n    also have \"\\<dots> \\<le> norm (f x) * B * K\"\n      by (intro mult_mono' order_refl norm_g norm_ge_zero\n                mult_nonneg_nonneg K elim)\n    also have \"\\<dots> = norm (f x) * (B * K)\"\n      by (rule mult.assoc)\n    finally show \"norm (f x ** g x) \\<le> norm (f x) * (B * K)\" .\n  qed\n  with f show ?thesis\n    by (rule Zfun_imp_Zfun)\nqed\n\nlemma (in bounded_bilinear) flip:\n  \"bounded_bilinear (\\<lambda>x y. y ** x)\"\n  apply default\n  apply (rule add_right)\n  apply (rule add_left)\n  apply (rule scaleR_right)\n  apply (rule scaleR_left)\n  apply (subst mult.commute)\n  using bounded by fast\n\nlemma (in bounded_bilinear) Bfun_prod_Zfun:\n  assumes f: \"Bfun f F\"\n  assumes g: \"Zfun g F\"\n  shows \"Zfun (\\<lambda>x. f x ** g x) F\"\n  using flip g f by (rule bounded_bilinear.Zfun_prod_Bfun)\n\nlemma Bfun_inverse_lemma:\n  fixes x :: \"'a::real_normed_div_algebra\"\n  shows \"\\<lbrakk>r \\<le> norm x; 0 < r\\<rbrakk> \\<Longrightarrow> norm (inverse x) \\<le> inverse r\"\n  apply (subst nonzero_norm_inverse, clarsimp)\n  apply (erule (1) le_imp_inverse_le)\n  done\n\nlemma Bfun_inverse:\n  fixes a :: \"'a::real_normed_div_algebra\"\n  assumes f: \"(f ---> a) F\"\n  assumes a: \"a \\<noteq> 0\"\n  shows \"Bfun (\\<lambda>x. inverse (f x)) F\"\nproof -\n  from a have \"0 < norm a\" by simp\n  hence \"\\<exists>r>0. r < norm a\" by (rule dense)\n  then obtain r where r1: \"0 < r\" and r2: \"r < norm a\" by fast\n  have \"eventually (\\<lambda>x. dist (f x) a < r) F\"\n    using tendstoD [OF f r1] by fast\n  hence \"eventually (\\<lambda>x. norm (inverse (f x)) \\<le> inverse (norm a - r)) F\"\n  proof eventually_elim\n    case (elim x)\n    hence 1: \"norm (f x - a) < r\"\n      by (simp add: dist_norm)\n    hence 2: \"f x \\<noteq> 0\" using r2 by auto\n    hence \"norm (inverse (f x)) = inverse (norm (f x))\"\n      by (rule nonzero_norm_inverse)\n    also have \"\\<dots> \\<le> inverse (norm a - r)\"\n    proof (rule le_imp_inverse_le)\n      show \"0 < norm a - r\" using r2 by simp\n    next\n      have \"norm a - norm (f x) \\<le> norm (a - f x)\"\n        by (rule norm_triangle_ineq2)\n      also have \"\\<dots> = norm (f x - a)\"\n        by (rule norm_minus_commute)\n      also have \"\\<dots> < r\" using 1 .\n      finally show \"norm a - r \\<le> norm (f x)\" by simp\n    qed\n    finally show \"norm (inverse (f x)) \\<le> inverse (norm a - r)\" .\n  qed\n  thus ?thesis by (rule BfunI)\nqed\n\nlemma tendsto_inverse [tendsto_intros]:\n  fixes a :: \"'a::real_normed_div_algebra\"\n  assumes f: \"(f ---> a) F\"\n  assumes a: \"a \\<noteq> 0\"\n  shows \"((\\<lambda>x. inverse (f x)) ---> inverse a) F\"\nproof -\n  from a have \"0 < norm a\" by simp\n  with f have \"eventually (\\<lambda>x. dist (f x) a < norm a) F\"\n    by (rule tendstoD)\n  then have \"eventually (\\<lambda>x. f x \\<noteq> 0) F\"\n    unfolding dist_norm by (auto elim!: eventually_elim1)\n  with a have \"eventually (\\<lambda>x. inverse (f x) - inverse a =\n    - (inverse (f x) * (f x - a) * inverse a)) F\"\n    by (auto elim!: eventually_elim1 simp: inverse_diff_inverse)\n  moreover have \"Zfun (\\<lambda>x. - (inverse (f x) * (f x - a) * inverse a)) F\"\n    by (intro Zfun_minus Zfun_mult_left\n      bounded_bilinear.Bfun_prod_Zfun [OF bounded_bilinear_mult]\n      Bfun_inverse [OF f a] f [unfolded tendsto_Zfun_iff])\n  ultimately show ?thesis\n    unfolding tendsto_Zfun_iff by (rule Zfun_ssubst)\nqed\n\nlemma continuous_inverse:\n  fixes f :: \"'a::t2_space \\<Rightarrow> 'b::real_normed_div_algebra\"\n  assumes \"continuous F f\" and \"f (Lim F (\\<lambda>x. x)) \\<noteq> 0\"\n  shows \"continuous F (\\<lambda>x. inverse (f x))\"\n  using assms unfolding continuous_def by (rule tendsto_inverse)\n\nlemma continuous_at_within_inverse[continuous_intros]:\n  fixes f :: \"'a::t2_space \\<Rightarrow> 'b::real_normed_div_algebra\"\n  assumes \"continuous (at a within s) f\" and \"f a \\<noteq> 0\"\n  shows \"continuous (at a within s) (\\<lambda>x. inverse (f x))\"\n  using assms unfolding continuous_within by (rule tendsto_inverse)\n\nlemma isCont_inverse[continuous_intros, simp]:\n  fixes f :: \"'a::t2_space \\<Rightarrow> 'b::real_normed_div_algebra\"\n  assumes \"isCont f a\" and \"f a \\<noteq> 0\"\n  shows \"isCont (\\<lambda>x. inverse (f x)) a\"\n  using assms unfolding continuous_at by (rule tendsto_inverse)\n\nlemma continuous_on_inverse[continuous_intros]:\n  fixes f :: \"'a::topological_space \\<Rightarrow> 'b::real_normed_div_algebra\"\n  assumes \"continuous_on s f\" and \"\\<forall>x\\<in>s. f x \\<noteq> 0\"\n  shows \"continuous_on s (\\<lambda>x. inverse (f x))\"\n  using assms unfolding continuous_on_def by (fast intro: tendsto_inverse)\n\nlemma tendsto_divide [tendsto_intros]:\n  fixes a b :: \"'a::real_normed_field\"\n  shows \"\\<lbrakk>(f ---> a) F; (g ---> b) F; b \\<noteq> 0\\<rbrakk>\n    \\<Longrightarrow> ((\\<lambda>x. f x / g x) ---> a / b) F\"\n  by (simp add: tendsto_mult tendsto_inverse divide_inverse)\n\nlemma continuous_divide:\n  fixes f g :: \"'a::t2_space \\<Rightarrow> 'b::real_normed_field\"\n  assumes \"continuous F f\" and \"continuous F g\" and \"g (Lim F (\\<lambda>x. x)) \\<noteq> 0\"\n  shows \"continuous F (\\<lambda>x. (f x) / (g x))\"\n  using assms unfolding continuous_def by (rule tendsto_divide)\n\nlemma continuous_at_within_divide[continuous_intros]:\n  fixes f g :: \"'a::t2_space \\<Rightarrow> 'b::real_normed_field\"\n  assumes \"continuous (at a within s) f\" \"continuous (at a within s) g\" and \"g a \\<noteq> 0\"\n  shows \"continuous (at a within s) (\\<lambda>x. (f x) / (g x))\"\n  using assms unfolding continuous_within by (rule tendsto_divide)\n\nlemma isCont_divide[continuous_intros, simp]:\n  fixes f g :: \"'a::t2_space \\<Rightarrow> 'b::real_normed_field\"\n  assumes \"isCont f a\" \"isCont g a\" \"g a \\<noteq> 0\"\n  shows \"isCont (\\<lambda>x. (f x) / g x) a\"\n  using assms unfolding continuous_at by (rule tendsto_divide)\n\nlemma continuous_on_divide[continuous_intros]:\n  fixes f :: \"'a::topological_space \\<Rightarrow> 'b::real_normed_field\"\n  assumes \"continuous_on s f\" \"continuous_on s g\" and \"\\<forall>x\\<in>s. g x \\<noteq> 0\"\n  shows \"continuous_on s (\\<lambda>x. (f x) / (g x))\"\n  using assms unfolding continuous_on_def by (fast intro: tendsto_divide)\n\nlemma tendsto_sgn [tendsto_intros]:\n  fixes l :: \"'a::real_normed_vector\"\n  shows \"\\<lbrakk>(f ---> l) F; l \\<noteq> 0\\<rbrakk> \\<Longrightarrow> ((\\<lambda>x. sgn (f x)) ---> sgn l) F\"\n  unfolding sgn_div_norm by (simp add: tendsto_intros)\n\nlemma continuous_sgn:\n  fixes f :: \"'a::t2_space \\<Rightarrow> 'b::real_normed_vector\"\n  assumes \"continuous F f\" and \"f (Lim F (\\<lambda>x. x)) \\<noteq> 0\"\n  shows \"continuous F (\\<lambda>x. sgn (f x))\"\n  using assms unfolding continuous_def by (rule tendsto_sgn)\n\nlemma continuous_at_within_sgn[continuous_intros]:\n  fixes f :: \"'a::t2_space \\<Rightarrow> 'b::real_normed_vector\"\n  assumes \"continuous (at a within s) f\" and \"f a \\<noteq> 0\"\n  shows \"continuous (at a within s) (\\<lambda>x. sgn (f x))\"\n  using assms unfolding continuous_within by (rule tendsto_sgn)\n\nlemma isCont_sgn[continuous_intros]:\n  fixes f :: \"'a::t2_space \\<Rightarrow> 'b::real_normed_vector\"\n  assumes \"isCont f a\" and \"f a \\<noteq> 0\"\n  shows \"isCont (\\<lambda>x. sgn (f x)) a\"\n  using assms unfolding continuous_at by (rule tendsto_sgn)\n\nlemma continuous_on_sgn[continuous_intros]:\n  fixes f :: \"'a::topological_space \\<Rightarrow> 'b::real_normed_vector\"\n  assumes \"continuous_on s f\" and \"\\<forall>x\\<in>s. f x \\<noteq> 0\"\n  shows \"continuous_on s (\\<lambda>x. sgn (f x))\"\n  using assms unfolding continuous_on_def by (fast intro: tendsto_sgn)\n\nlemma filterlim_at_infinity:\n  fixes f :: \"_ \\<Rightarrow> 'a\\<Colon>real_normed_vector\"\n  assumes \"0 \\<le> c\"\n  shows \"(LIM x F. f x :> at_infinity) \\<longleftrightarrow> (\\<forall>r>c. eventually (\\<lambda>x. r \\<le> norm (f x)) F)\"\n  unfolding filterlim_iff eventually_at_infinity\nproof safe\n  fix P :: \"'a \\<Rightarrow> bool\" and b\n  assume *: \"\\<forall>r>c. eventually (\\<lambda>x. r \\<le> norm (f x)) F\"\n    and P: \"\\<forall>x. b \\<le> norm x \\<longrightarrow> P x\"\n  have \"max b (c + 1) > c\" by auto\n  with * have \"eventually (\\<lambda>x. max b (c + 1) \\<le> norm (f x)) F\"\n    by auto\n  then show \"eventually (\\<lambda>x. P (f x)) F\"\n  proof eventually_elim\n    fix x assume \"max b (c + 1) \\<le> norm (f x)\"\n    with P show \"P (f x)\" by auto\n  qed\nqed force\n\n\nsubsection {* Relate @{const at}, @{const at_left} and @{const at_right} *}\n\ntext {*\n\nThis lemmas are useful for conversion between @{term \"at x\"} to @{term \"at_left x\"} and\n@{term \"at_right x\"} and also @{term \"at_right 0\"}.\n\n*}\n\nlemmas filterlim_split_at_real = filterlim_split_at[where 'a=real]\n\nlemma filtermap_homeomorph:\n  assumes f: \"continuous (at a) f\"\n  assumes g: \"continuous (at (f a)) g\"\n  assumes bij1: \"\\<forall>x. f (g x) = x\" and bij2: \"\\<forall>x. g (f x) = x\"\n  shows \"filtermap f (nhds a) = nhds (f a)\"\n  unfolding filter_eq_iff eventually_filtermap eventually_nhds\nproof safe\n  fix P S assume S: \"open S\" \"f a \\<in> S\" and P: \"\\<forall>x\\<in>S. P x\"\n  from continuous_within_topological[THEN iffD1, rule_format, OF f S] P\n  show \"\\<exists>S. open S \\<and> a \\<in> S \\<and> (\\<forall>x\\<in>S. P (f x))\" by auto\nnext\n  fix P S assume S: \"open S\" \"a \\<in> S\" and P: \"\\<forall>x\\<in>S. P (f x)\"\n  with continuous_within_topological[THEN iffD1, rule_format, OF g, of S] bij2\n  obtain A where \"open A\" \"f a \\<in> A\" \"(\\<forall>y\\<in>A. g y \\<in> S)\"\n    by (metis UNIV_I)\n  with P bij1 show \"\\<exists>S. open S \\<and> f a \\<in> S \\<and> (\\<forall>x\\<in>S. P x)\"\n    by (force intro!: exI[of _ A])\nqed\n\nlemma filtermap_nhds_shift: \"filtermap (\\<lambda>x. x - d) (nhds a) = nhds (a - d::'a::real_normed_vector)\"\n  by (rule filtermap_homeomorph[where g=\"\\<lambda>x. x + d\"]) (auto intro: continuous_intros)\n\nlemma filtermap_nhds_minus: \"filtermap (\\<lambda>x. - x) (nhds a) = nhds (- a::'a::real_normed_vector)\"\n  by (rule filtermap_homeomorph[where g=uminus]) (auto intro: continuous_minus)\n\nlemma filtermap_at_shift: \"filtermap (\\<lambda>x. x - d) (at a) = at (a - d::'a::real_normed_vector)\"\n  by (simp add: filter_eq_iff eventually_filtermap eventually_at_filter filtermap_nhds_shift[symmetric])\n\nlemma filtermap_at_right_shift: \"filtermap (\\<lambda>x. x - d) (at_right a) = at_right (a - d::real)\"\n  by (simp add: filter_eq_iff eventually_filtermap eventually_at_filter filtermap_nhds_shift[symmetric])\n\nlemma at_right_to_0: \"at_right (a::real) = filtermap (\\<lambda>x. x + a) (at_right 0)\"\n  using filtermap_at_right_shift[of \"-a\" 0] by simp\n\nlemma filterlim_at_right_to_0:\n  \"filterlim f F (at_right (a::real)) \\<longleftrightarrow> filterlim (\\<lambda>x. f (x + a)) F (at_right 0)\"\n  unfolding filterlim_def filtermap_filtermap at_right_to_0[of a] ..\n\nlemma eventually_at_right_to_0:\n  \"eventually P (at_right (a::real)) \\<longleftrightarrow> eventually (\\<lambda>x. P (x + a)) (at_right 0)\"\n  unfolding at_right_to_0[of a] by (simp add: eventually_filtermap)\n\nlemma filtermap_at_minus: \"filtermap (\\<lambda>x. - x) (at a) = at (- a::'a::real_normed_vector)\"\n  by (simp add: filter_eq_iff eventually_filtermap eventually_at_filter filtermap_nhds_minus[symmetric])\n\nlemma at_left_minus: \"at_left (a::real) = filtermap (\\<lambda>x. - x) (at_right (- a))\"\n  by (simp add: filter_eq_iff eventually_filtermap eventually_at_filter filtermap_nhds_minus[symmetric])\n\nlemma at_right_minus: \"at_right (a::real) = filtermap (\\<lambda>x. - x) (at_left (- a))\"\n  by (simp add: filter_eq_iff eventually_filtermap eventually_at_filter filtermap_nhds_minus[symmetric])\n\nlemma filterlim_at_left_to_right:\n  \"filterlim f F (at_left (a::real)) \\<longleftrightarrow> filterlim (\\<lambda>x. f (- x)) F (at_right (-a))\"\n  unfolding filterlim_def filtermap_filtermap at_left_minus[of a] ..\n\nlemma eventually_at_left_to_right:\n  \"eventually P (at_left (a::real)) \\<longleftrightarrow> eventually (\\<lambda>x. P (- x)) (at_right (-a))\"\n  unfolding at_left_minus[of a] by (simp add: eventually_filtermap)\n\nlemma at_top_mirror: \"at_top = filtermap uminus (at_bot :: real filter)\"\n  unfolding filter_eq_iff eventually_filtermap eventually_at_top_linorder eventually_at_bot_linorder\n  by (metis le_minus_iff minus_minus)\n\nlemma at_bot_mirror: \"at_bot = filtermap uminus (at_top :: real filter)\"\n  unfolding at_top_mirror filtermap_filtermap by (simp add: filtermap_ident)\n\nlemma filterlim_at_top_mirror: \"(LIM x at_top. f x :> F) \\<longleftrightarrow> (LIM x at_bot. f (-x::real) :> F)\"\n  unfolding filterlim_def at_top_mirror filtermap_filtermap ..\n\nlemma filterlim_at_bot_mirror: \"(LIM x at_bot. f x :> F) \\<longleftrightarrow> (LIM x at_top. f (-x::real) :> F)\"\n  unfolding filterlim_def at_bot_mirror filtermap_filtermap ..\n\nlemma filterlim_uminus_at_top_at_bot: \"LIM x at_bot. - x :: real :> at_top\"\n  unfolding filterlim_at_top eventually_at_bot_dense\n  by (metis leI minus_less_iff order_less_asym)\n\nlemma filterlim_uminus_at_bot_at_top: \"LIM x at_top. - x :: real :> at_bot\"\n  unfolding filterlim_at_bot eventually_at_top_dense\n  by (metis leI less_minus_iff order_less_asym)\n\nlemma filterlim_uminus_at_top: \"(LIM x F. f x :> at_top) \\<longleftrightarrow> (LIM x F. - (f x) :: real :> at_bot)\"\n  using filterlim_compose[OF filterlim_uminus_at_bot_at_top, of f F]\n  using filterlim_compose[OF filterlim_uminus_at_top_at_bot, of \"\\<lambda>x. - f x\" F]\n  by auto\n\nlemma filterlim_uminus_at_bot: \"(LIM x F. f x :> at_bot) \\<longleftrightarrow> (LIM x F. - (f x) :: real :> at_top)\"\n  unfolding filterlim_uminus_at_top by simp\n\nlemma filterlim_inverse_at_top_right: \"LIM x at_right (0::real). inverse x :> at_top\"\n  unfolding filterlim_at_top_gt[where c=0] eventually_at_filter\nproof safe\n  fix Z :: real assume [arith]: \"0 < Z\"\n  then have \"eventually (\\<lambda>x. x < inverse Z) (nhds 0)\"\n    by (auto simp add: eventually_nhds_metric dist_real_def intro!: exI[of _ \"\\<bar>inverse Z\\<bar>\"])\n  then show \"eventually (\\<lambda>x. x \\<noteq> 0 \\<longrightarrow> x \\<in> {0<..} \\<longrightarrow> Z \\<le> inverse x) (nhds 0)\"\n    by (auto elim!: eventually_elim1 simp: inverse_eq_divide field_simps)\nqed\n\nlemma filterlim_inverse_at_top:\n  \"(f ---> (0 :: real)) F \\<Longrightarrow> eventually (\\<lambda>x. 0 < f x) F \\<Longrightarrow> LIM x F. inverse (f x) :> at_top\"\n  by (intro filterlim_compose[OF filterlim_inverse_at_top_right])\n     (simp add: filterlim_def eventually_filtermap eventually_elim1 at_within_def le_principal)\n\nlemma filterlim_inverse_at_bot_neg:\n  \"LIM x (at_left (0::real)). inverse x :> at_bot\"\n  by (simp add: filterlim_inverse_at_top_right filterlim_uminus_at_bot filterlim_at_left_to_right)\n\nlemma filterlim_inverse_at_bot:\n  \"(f ---> (0 :: real)) F \\<Longrightarrow> eventually (\\<lambda>x. f x < 0) F \\<Longrightarrow> LIM x F. inverse (f x) :> at_bot\"\n  unfolding filterlim_uminus_at_bot inverse_minus_eq[symmetric]\n  by (rule filterlim_inverse_at_top) (simp_all add: tendsto_minus_cancel_left[symmetric])\n\nlemma tendsto_inverse_0:\n  fixes x :: \"_ \\<Rightarrow> 'a\\<Colon>real_normed_div_algebra\"\n  shows \"(inverse ---> (0::'a)) at_infinity\"\n  unfolding tendsto_Zfun_iff diff_0_right Zfun_def eventually_at_infinity\nproof safe\n  fix r :: real assume \"0 < r\"\n  show \"\\<exists>b. \\<forall>x. b \\<le> norm x \\<longrightarrow> norm (inverse x :: 'a) < r\"\n  proof (intro exI[of _ \"inverse (r / 2)\"] allI impI)\n    fix x :: 'a\n    from `0 < r` have \"0 < inverse (r / 2)\" by simp\n    also assume *: \"inverse (r / 2) \\<le> norm x\"\n    finally show \"norm (inverse x) < r\"\n      using * `0 < r` by (subst nonzero_norm_inverse) (simp_all add: inverse_eq_divide field_simps)\n  qed\nqed\n\nlemma at_right_to_top: \"(at_right (0::real)) = filtermap inverse at_top\"\nproof (rule antisym)\n  have \"(inverse ---> (0::real)) at_top\"\n    by (metis tendsto_inverse_0 filterlim_mono at_top_le_at_infinity order_refl)\n  then show \"filtermap inverse at_top \\<le> at_right (0::real)\"\n    by (simp add: le_principal eventually_filtermap eventually_gt_at_top filterlim_def at_within_def)\nnext\n  have \"filtermap inverse (filtermap inverse (at_right (0::real))) \\<le> filtermap inverse at_top\"\n    using filterlim_inverse_at_top_right unfolding filterlim_def by (rule filtermap_mono)\n  then show \"at_right (0::real) \\<le> filtermap inverse at_top\"\n    by (simp add: filtermap_ident filtermap_filtermap)\nqed\n\nlemma eventually_at_right_to_top:\n  \"eventually P (at_right (0::real)) \\<longleftrightarrow> eventually (\\<lambda>x. P (inverse x)) at_top\"\n  unfolding at_right_to_top eventually_filtermap ..\n\nlemma filterlim_at_right_to_top:\n  \"filterlim f F (at_right (0::real)) \\<longleftrightarrow> (LIM x at_top. f (inverse x) :> F)\"\n  unfolding filterlim_def at_right_to_top filtermap_filtermap ..\n\nlemma at_top_to_right: \"at_top = filtermap inverse (at_right (0::real))\"\n  unfolding at_right_to_top filtermap_filtermap inverse_inverse_eq filtermap_ident ..\n\nlemma eventually_at_top_to_right:\n  \"eventually P at_top \\<longleftrightarrow> eventually (\\<lambda>x. P (inverse x)) (at_right (0::real))\"\n  unfolding at_top_to_right eventually_filtermap ..\n\nlemma filterlim_at_top_to_right:\n  \"filterlim f F at_top \\<longleftrightarrow> (LIM x (at_right (0::real)). f (inverse x) :> F)\"\n  unfolding filterlim_def at_top_to_right filtermap_filtermap ..\n\nlemma filterlim_inverse_at_infinity:\n  fixes x :: \"_ \\<Rightarrow> 'a\\<Colon>{real_normed_div_algebra, division_ring_inverse_zero}\"\n  shows \"filterlim inverse at_infinity (at (0::'a))\"\n  unfolding filterlim_at_infinity[OF order_refl]\nproof safe\n  fix r :: real assume \"0 < r\"\n  then show \"eventually (\\<lambda>x::'a. r \\<le> norm (inverse x)) (at 0)\"\n    unfolding eventually_at norm_inverse\n    by (intro exI[of _ \"inverse r\"])\n       (auto simp: norm_conv_dist[symmetric] field_simps inverse_eq_divide)\nqed\n\nlemma filterlim_inverse_at_iff:\n  fixes g :: \"'a \\<Rightarrow> 'b\\<Colon>{real_normed_div_algebra, division_ring_inverse_zero}\"\n  shows \"(LIM x F. inverse (g x) :> at 0) \\<longleftrightarrow> (LIM x F. g x :> at_infinity)\"\n  unfolding filterlim_def filtermap_filtermap[symmetric]\nproof\n  assume \"filtermap g F \\<le> at_infinity\"\n  then have \"filtermap inverse (filtermap g F) \\<le> filtermap inverse at_infinity\"\n    by (rule filtermap_mono)\n  also have \"\\<dots> \\<le> at 0\"\n    using tendsto_inverse_0[where 'a='b]\n    by (auto intro!: exI[of _ 1]\n             simp: le_principal eventually_filtermap filterlim_def at_within_def eventually_at_infinity)\n  finally show \"filtermap inverse (filtermap g F) \\<le> at 0\" .\nnext\n  assume \"filtermap inverse (filtermap g F) \\<le> at 0\"\n  then have \"filtermap inverse (filtermap inverse (filtermap g F)) \\<le> filtermap inverse (at 0)\"\n    by (rule filtermap_mono)\n  with filterlim_inverse_at_infinity show \"filtermap g F \\<le> at_infinity\"\n    by (auto intro: order_trans simp: filterlim_def filtermap_filtermap)\nqed\n\nlemma tendsto_inverse_0_at_top: \"LIM x F. f x :> at_top \\<Longrightarrow> ((\\<lambda>x. inverse (f x) :: real) ---> 0) F\"\n by (metis filterlim_at filterlim_mono[OF _ at_top_le_at_infinity order_refl] filterlim_inverse_at_iff)\n\ntext {*\n\nWe only show rules for multiplication and addition when the functions are either against a real\nvalue or against infinity. Further rules are easy to derive by using @{thm filterlim_uminus_at_top}.\n\n*}\n\nlemma filterlim_tendsto_pos_mult_at_top: \n  assumes f: \"(f ---> c) F\" and c: \"0 < c\"\n  assumes g: \"LIM x F. g x :> at_top\"\n  shows \"LIM x F. (f x * g x :: real) :> at_top\"\n  unfolding filterlim_at_top_gt[where c=0]\nproof safe\n  fix Z :: real assume \"0 < Z\"\n  from f `0 < c` have \"eventually (\\<lambda>x. c / 2 < f x) F\"\n    by (auto dest!: tendstoD[where e=\"c / 2\"] elim!: eventually_elim1\n             simp: dist_real_def abs_real_def split: split_if_asm)\n  moreover from g have \"eventually (\\<lambda>x. (Z / c * 2) \\<le> g x) F\"\n    unfolding filterlim_at_top by auto\n  ultimately show \"eventually (\\<lambda>x. Z \\<le> f x * g x) F\"\n  proof eventually_elim\n    fix x assume \"c / 2 < f x\" \"Z / c * 2 \\<le> g x\"\n    with `0 < Z` `0 < c` have \"c / 2 * (Z / c * 2) \\<le> f x * g x\"\n      by (intro mult_mono) (auto simp: zero_le_divide_iff)\n    with `0 < c` show \"Z \\<le> f x * g x\"\n       by simp\n  qed\nqed\n\nlemma filterlim_at_top_mult_at_top: \n  assumes f: \"LIM x F. f x :> at_top\"\n  assumes g: \"LIM x F. g x :> at_top\"\n  shows \"LIM x F. (f x * g x :: real) :> at_top\"\n  unfolding filterlim_at_top_gt[where c=0]\nproof safe\n  fix Z :: real assume \"0 < Z\"\n  from f have \"eventually (\\<lambda>x. 1 \\<le> f x) F\"\n    unfolding filterlim_at_top by auto\n  moreover from g have \"eventually (\\<lambda>x. Z \\<le> g x) F\"\n    unfolding filterlim_at_top by auto\n  ultimately show \"eventually (\\<lambda>x. Z \\<le> f x * g x) F\"\n  proof eventually_elim\n    fix x assume \"1 \\<le> f x\" \"Z \\<le> g x\"\n    with `0 < Z` have \"1 * Z \\<le> f x * g x\"\n      by (intro mult_mono) (auto simp: zero_le_divide_iff)\n    then show \"Z \\<le> f x * g x\"\n       by simp\n  qed\nqed\n\nlemma filterlim_tendsto_pos_mult_at_bot:\n  assumes \"(f ---> c) F\" \"0 < (c::real)\" \"filterlim g at_bot F\"\n  shows \"LIM x F. f x * g x :> at_bot\"\n  using filterlim_tendsto_pos_mult_at_top[OF assms(1,2), of \"\\<lambda>x. - g x\"] assms(3)\n  unfolding filterlim_uminus_at_bot by simp\n\nlemma filterlim_pow_at_top:\n  fixes f :: \"real \\<Rightarrow> real\"\n  assumes \"0 < n\" and f: \"LIM x F. f x :> at_top\"\n  shows \"LIM x F. (f x)^n :: real :> at_top\"\nusing `0 < n` proof (induct n)\n  case (Suc n) with f show ?case\n    by (cases \"n = 0\") (auto intro!: filterlim_at_top_mult_at_top)\nqed simp\n\nlemma filterlim_pow_at_bot_even:\n  fixes f :: \"real \\<Rightarrow> real\"\n  shows \"0 < n \\<Longrightarrow> LIM x F. f x :> at_bot \\<Longrightarrow> even n \\<Longrightarrow> LIM x F. (f x)^n :> at_top\"\n  using filterlim_pow_at_top[of n \"\\<lambda>x. - f x\" F] by (simp add: filterlim_uminus_at_top)\n\nlemma filterlim_pow_at_bot_odd:\n  fixes f :: \"real \\<Rightarrow> real\"\n  shows \"0 < n \\<Longrightarrow> LIM x F. f x :> at_bot \\<Longrightarrow> odd n \\<Longrightarrow> LIM x F. (f x)^n :> at_bot\"\n  using filterlim_pow_at_top[of n \"\\<lambda>x. - f x\" F] by (simp add: filterlim_uminus_at_bot)\n\nlemma filterlim_tendsto_add_at_top: \n  assumes f: \"(f ---> c) F\"\n  assumes g: \"LIM x F. g x :> at_top\"\n  shows \"LIM x F. (f x + g x :: real) :> at_top\"\n  unfolding filterlim_at_top_gt[where c=0]\nproof safe\n  fix Z :: real assume \"0 < Z\"\n  from f have \"eventually (\\<lambda>x. c - 1 < f x) F\"\n    by (auto dest!: tendstoD[where e=1] elim!: eventually_elim1 simp: dist_real_def)\n  moreover from g have \"eventually (\\<lambda>x. Z - (c - 1) \\<le> g x) F\"\n    unfolding filterlim_at_top by auto\n  ultimately show \"eventually (\\<lambda>x. Z \\<le> f x + g x) F\"\n    by eventually_elim simp\nqed\n\nlemma LIM_at_top_divide:\n  fixes f g :: \"'a \\<Rightarrow> real\"\n  assumes f: \"(f ---> a) F\" \"0 < a\"\n  assumes g: \"(g ---> 0) F\" \"eventually (\\<lambda>x. 0 < g x) F\"\n  shows \"LIM x F. f x / g x :> at_top\"\n  unfolding divide_inverse\n  by (rule filterlim_tendsto_pos_mult_at_top[OF f]) (rule filterlim_inverse_at_top[OF g])\n\nlemma filterlim_at_top_add_at_top: \n  assumes f: \"LIM x F. f x :> at_top\"\n  assumes g: \"LIM x F. g x :> at_top\"\n  shows \"LIM x F. (f x + g x :: real) :> at_top\"\n  unfolding filterlim_at_top_gt[where c=0]\nproof safe\n  fix Z :: real assume \"0 < Z\"\n  from f have \"eventually (\\<lambda>x. 0 \\<le> f x) F\"\n    unfolding filterlim_at_top by auto\n  moreover from g have \"eventually (\\<lambda>x. Z \\<le> g x) F\"\n    unfolding filterlim_at_top by auto\n  ultimately show \"eventually (\\<lambda>x. Z \\<le> f x + g x) F\"\n    by eventually_elim simp\nqed\n\nlemma tendsto_divide_0:\n  fixes f :: \"_ \\<Rightarrow> 'a\\<Colon>{real_normed_div_algebra, division_ring_inverse_zero}\"\n  assumes f: \"(f ---> c) F\"\n  assumes g: \"LIM x F. g x :> at_infinity\"\n  shows \"((\\<lambda>x. f x / g x) ---> 0) F\"\n  using tendsto_mult[OF f filterlim_compose[OF tendsto_inverse_0 g]] by (simp add: divide_inverse)\n\nlemma linear_plus_1_le_power:\n  fixes x :: real\n  assumes x: \"0 \\<le> x\"\n  shows \"real n * x + 1 \\<le> (x + 1) ^ n\"\nproof (induct n)\n  case (Suc n)\n  have \"real (Suc n) * x + 1 \\<le> (x + 1) * (real n * x + 1)\"\n    by (simp add: field_simps real_of_nat_Suc x)\n  also have \"\\<dots> \\<le> (x + 1)^Suc n\"\n    using Suc x by (simp add: mult_left_mono)\n  finally show ?case .\nqed simp\n\nlemma filterlim_realpow_sequentially_gt1:\n  fixes x :: \"'a :: real_normed_div_algebra\"\n  assumes x[arith]: \"1 < norm x\"\n  shows \"LIM n sequentially. x ^ n :> at_infinity\"\nproof (intro filterlim_at_infinity[THEN iffD2] allI impI)\n  fix y :: real assume \"0 < y\"\n  have \"0 < norm x - 1\" by simp\n  then obtain N::nat where \"y < real N * (norm x - 1)\" by (blast dest: reals_Archimedean3)\n  also have \"\\<dots> \\<le> real N * (norm x - 1) + 1\" by simp\n  also have \"\\<dots> \\<le> (norm x - 1 + 1) ^ N\" by (rule linear_plus_1_le_power) simp\n  also have \"\\<dots> = norm x ^ N\" by simp\n  finally have \"\\<forall>n\\<ge>N. y \\<le> norm x ^ n\"\n    by (metis order_less_le_trans power_increasing order_less_imp_le x)\n  then show \"eventually (\\<lambda>n. y \\<le> norm (x ^ n)) sequentially\"\n    unfolding eventually_sequentially\n    by (auto simp: norm_power)\nqed simp\n\n\nsubsection {* Limits of Sequences *}\n\nlemma [trans]: \"X=Y ==> Y ----> z ==> X ----> z\"\n  by simp\n\nlemma LIMSEQ_iff:\n  fixes L :: \"'a::real_normed_vector\"\n  shows \"(X ----> L) = (\\<forall>r>0. \\<exists>no. \\<forall>n \\<ge> no. norm (X n - L) < r)\"\nunfolding LIMSEQ_def dist_norm ..\n\nlemma LIMSEQ_I:\n  fixes L :: \"'a::real_normed_vector\"\n  shows \"(\\<And>r. 0 < r \\<Longrightarrow> \\<exists>no. \\<forall>n\\<ge>no. norm (X n - L) < r) \\<Longrightarrow> X ----> L\"\nby (simp add: LIMSEQ_iff)\n\nlemma LIMSEQ_D:\n  fixes L :: \"'a::real_normed_vector\"\n  shows \"\\<lbrakk>X ----> L; 0 < r\\<rbrakk> \\<Longrightarrow> \\<exists>no. \\<forall>n\\<ge>no. norm (X n - L) < r\"\nby (simp add: LIMSEQ_iff)\n\nlemma LIMSEQ_linear: \"\\<lbrakk> X ----> x ; l > 0 \\<rbrakk> \\<Longrightarrow> (\\<lambda> n. X (n * l)) ----> x\"\n  unfolding tendsto_def eventually_sequentially\n  by (metis div_le_dividend div_mult_self1_is_m le_trans mult.commute)\n\nlemma Bseq_inverse_lemma:\n  fixes x :: \"'a::real_normed_div_algebra\"\n  shows \"\\<lbrakk>r \\<le> norm x; 0 < r\\<rbrakk> \\<Longrightarrow> norm (inverse x) \\<le> inverse r\"\napply (subst nonzero_norm_inverse, clarsimp)\napply (erule (1) le_imp_inverse_le)\ndone\n\nlemma Bseq_inverse:\n  fixes a :: \"'a::real_normed_div_algebra\"\n  shows \"\\<lbrakk>X ----> a; a \\<noteq> 0\\<rbrakk> \\<Longrightarrow> Bseq (\\<lambda>n. inverse (X n))\"\n  by (rule Bfun_inverse)\n\nlemma LIMSEQ_diff_approach_zero:\n  fixes L :: \"'a::real_normed_vector\"\n  shows \"g ----> L ==> (%x. f x - g x) ----> 0 ==> f ----> L\"\n  by (drule (1) tendsto_add, simp)\n\nlemma LIMSEQ_diff_approach_zero2:\n  fixes L :: \"'a::real_normed_vector\"\n  shows \"f ----> L ==> (%x. f x - g x) ----> 0 ==> g ----> L\"\n  by (drule (1) tendsto_diff, simp)\n\ntext{*An unbounded sequence's inverse tends to 0*}\n\nlemma LIMSEQ_inverse_zero:\n  \"\\<forall>r::real. \\<exists>N. \\<forall>n\\<ge>N. r < X n \\<Longrightarrow> (\\<lambda>n. inverse (X n)) ----> 0\"\n  apply (rule filterlim_compose[OF tendsto_inverse_0])\n  apply (simp add: filterlim_at_infinity[OF order_refl] eventually_sequentially)\n  apply (metis abs_le_D1 linorder_le_cases linorder_not_le)\n  done\n\ntext{*The sequence @{term \"1/n\"} tends to 0 as @{term n} tends to infinity*}\n\nlemma LIMSEQ_inverse_real_of_nat: \"(%n. inverse(real(Suc n))) ----> 0\"\n  by (metis filterlim_compose tendsto_inverse_0 filterlim_mono order_refl filterlim_Suc\n            filterlim_compose[OF filterlim_real_sequentially] at_top_le_at_infinity)\n\ntext{*The sequence @{term \"r + 1/n\"} tends to @{term r} as @{term n} tends to\ninfinity is now easily proved*}\n\nlemma LIMSEQ_inverse_real_of_nat_add:\n     \"(%n. r + inverse(real(Suc n))) ----> r\"\n  using tendsto_add [OF tendsto_const LIMSEQ_inverse_real_of_nat] by auto\n\nlemma LIMSEQ_inverse_real_of_nat_add_minus:\n     \"(%n. r + -inverse(real(Suc n))) ----> r\"\n  using tendsto_add [OF tendsto_const tendsto_minus [OF LIMSEQ_inverse_real_of_nat]]\n  by auto\n\nlemma LIMSEQ_inverse_real_of_nat_add_minus_mult:\n     \"(%n. r*( 1 + -inverse(real(Suc n)))) ----> r\"\n  using tendsto_mult [OF tendsto_const LIMSEQ_inverse_real_of_nat_add_minus [of 1]]\n  by auto\n\nsubsection {* Convergence on sequences *}\n\nlemma convergent_add:\n  fixes X Y :: \"nat \\<Rightarrow> 'a::real_normed_vector\"\n  assumes \"convergent (\\<lambda>n. X n)\"\n  assumes \"convergent (\\<lambda>n. Y n)\"\n  shows \"convergent (\\<lambda>n. X n + Y n)\"\n  using assms unfolding convergent_def by (fast intro: tendsto_add)\n\nlemma convergent_setsum:\n  fixes X :: \"'a \\<Rightarrow> nat \\<Rightarrow> 'b::real_normed_vector\"\n  assumes \"\\<And>i. i \\<in> A \\<Longrightarrow> convergent (\\<lambda>n. X i n)\"\n  shows \"convergent (\\<lambda>n. \\<Sum>i\\<in>A. X i n)\"\nproof (cases \"finite A\")\n  case True from this and assms show ?thesis\n    by (induct A set: finite) (simp_all add: convergent_const convergent_add)\nqed (simp add: convergent_const)\n\nlemma (in bounded_linear) convergent:\n  assumes \"convergent (\\<lambda>n. X n)\"\n  shows \"convergent (\\<lambda>n. f (X n))\"\n  using assms unfolding convergent_def by (fast intro: tendsto)\n\nlemma (in bounded_bilinear) convergent:\n  assumes \"convergent (\\<lambda>n. X n)\" and \"convergent (\\<lambda>n. Y n)\"\n  shows \"convergent (\\<lambda>n. X n ** Y n)\"\n  using assms unfolding convergent_def by (fast intro: tendsto)\n\nlemma convergent_minus_iff:\n  fixes X :: \"nat \\<Rightarrow> 'a::real_normed_vector\"\n  shows \"convergent X \\<longleftrightarrow> convergent (\\<lambda>n. - X n)\"\napply (simp add: convergent_def)\napply (auto dest: tendsto_minus)\napply (drule tendsto_minus, auto)\ndone\n\n\ntext {* A monotone sequence converges to its least upper bound. *}\n\nlemma LIMSEQ_incseq_SUP:\n  fixes X :: \"nat \\<Rightarrow> 'a::{conditionally_complete_linorder, linorder_topology}\"\n  assumes u: \"bdd_above (range X)\"\n  assumes X: \"incseq X\"\n  shows \"X ----> (SUP i. X i)\"\n  by (rule order_tendstoI)\n     (auto simp: eventually_sequentially u less_cSUP_iff intro: X[THEN incseqD] less_le_trans cSUP_lessD[OF u])\n\nlemma LIMSEQ_decseq_INF:\n  fixes X :: \"nat \\<Rightarrow> 'a::{conditionally_complete_linorder, linorder_topology}\"\n  assumes u: \"bdd_below (range X)\"\n  assumes X: \"decseq X\"\n  shows \"X ----> (INF i. X i)\"\n  by (rule order_tendstoI)\n     (auto simp: eventually_sequentially u cINF_less_iff intro: X[THEN decseqD] le_less_trans less_cINF_D[OF u])\n\ntext{*Main monotonicity theorem*}\n\nlemma Bseq_monoseq_convergent: \"Bseq X \\<Longrightarrow> monoseq X \\<Longrightarrow> convergent (X::nat\\<Rightarrow>real)\"\n  by (auto simp: monoseq_iff convergent_def intro: LIMSEQ_decseq_INF LIMSEQ_incseq_SUP dest: Bseq_bdd_above Bseq_bdd_below)\n\nlemma Bseq_mono_convergent: \"Bseq X \\<Longrightarrow> (\\<forall>m n. m \\<le> n \\<longrightarrow> X m \\<le> X n) \\<Longrightarrow> convergent (X::nat\\<Rightarrow>real)\"\n  by (auto intro!: Bseq_monoseq_convergent incseq_imp_monoseq simp: incseq_def)\n\nlemma Cauchy_iff:\n  fixes X :: \"nat \\<Rightarrow> 'a::real_normed_vector\"\n  shows \"Cauchy X \\<longleftrightarrow> (\\<forall>e>0. \\<exists>M. \\<forall>m\\<ge>M. \\<forall>n\\<ge>M. norm (X m - X n) < e)\"\n  unfolding Cauchy_def dist_norm ..\n\nlemma CauchyI:\n  fixes X :: \"nat \\<Rightarrow> 'a::real_normed_vector\"\n  shows \"(\\<And>e. 0 < e \\<Longrightarrow> \\<exists>M. \\<forall>m\\<ge>M. \\<forall>n\\<ge>M. norm (X m - X n) < e) \\<Longrightarrow> Cauchy X\"\nby (simp add: Cauchy_iff)\n\nlemma CauchyD:\n  fixes X :: \"nat \\<Rightarrow> 'a::real_normed_vector\"\n  shows \"\\<lbrakk>Cauchy X; 0 < e\\<rbrakk> \\<Longrightarrow> \\<exists>M. \\<forall>m\\<ge>M. \\<forall>n\\<ge>M. norm (X m - X n) < e\"\nby (simp add: Cauchy_iff)\n\nlemma incseq_convergent:\n  fixes X :: \"nat \\<Rightarrow> real\"\n  assumes \"incseq X\" and \"\\<forall>i. X i \\<le> B\"\n  obtains L where \"X ----> L\" \"\\<forall>i. X i \\<le> L\"\nproof atomize_elim\n  from incseq_bounded[OF assms] `incseq X` Bseq_monoseq_convergent[of X]\n  obtain L where \"X ----> L\"\n    by (auto simp: convergent_def monoseq_def incseq_def)\n  with `incseq X` show \"\\<exists>L. X ----> L \\<and> (\\<forall>i. X i \\<le> L)\"\n    by (auto intro!: exI[of _ L] incseq_le)\nqed\n\nlemma decseq_convergent:\n  fixes X :: \"nat \\<Rightarrow> real\"\n  assumes \"decseq X\" and \"\\<forall>i. B \\<le> X i\"\n  obtains L where \"X ----> L\" \"\\<forall>i. L \\<le> X i\"\nproof atomize_elim\n  from decseq_bounded[OF assms] `decseq X` Bseq_monoseq_convergent[of X]\n  obtain L where \"X ----> L\"\n    by (auto simp: convergent_def monoseq_def decseq_def)\n  with `decseq X` show \"\\<exists>L. X ----> L \\<and> (\\<forall>i. L \\<le> X i)\"\n    by (auto intro!: exI[of _ L] decseq_le)\nqed\n\nsubsubsection {* Cauchy Sequences are Bounded *}\n\ntext{*A Cauchy sequence is bounded -- this is the standard\n  proof mechanization rather than the nonstandard proof*}\n\nlemma lemmaCauchy: \"\\<forall>n \\<ge> M. norm (X M - X n) < (1::real)\n          ==>  \\<forall>n \\<ge> M. norm (X n :: 'a::real_normed_vector) < 1 + norm (X M)\"\napply (clarify, drule spec, drule (1) mp)\napply (simp only: norm_minus_commute)\napply (drule order_le_less_trans [OF norm_triangle_ineq2])\napply simp\ndone\n\nsubsection {* Power Sequences *}\n\ntext{*The sequence @{term \"x^n\"} tends to 0 if @{term \"0\\<le>x\"} and @{term\n\"x<1\"}.  Proof will use (NS) Cauchy equivalence for convergence and\n  also fact that bounded and monotonic sequence converges.*}\n\nlemma Bseq_realpow: \"[| 0 \\<le> (x::real); x \\<le> 1 |] ==> Bseq (%n. x ^ n)\"\napply (simp add: Bseq_def)\napply (rule_tac x = 1 in exI)\napply (simp add: power_abs)\napply (auto dest: power_mono)\ndone\n\nlemma monoseq_realpow: fixes x :: real shows \"[| 0 \\<le> x; x \\<le> 1 |] ==> monoseq (%n. x ^ n)\"\napply (clarify intro!: mono_SucI2)\napply (cut_tac n = n and N = \"Suc n\" and a = x in power_decreasing, auto)\ndone\n\nlemma convergent_realpow:\n  \"[| 0 \\<le> (x::real); x \\<le> 1 |] ==> convergent (%n. x ^ n)\"\nby (blast intro!: Bseq_monoseq_convergent Bseq_realpow monoseq_realpow)\n\nlemma LIMSEQ_inverse_realpow_zero: \"1 < (x::real) \\<Longrightarrow> (\\<lambda>n. inverse (x ^ n)) ----> 0\"\n  by (rule filterlim_compose[OF tendsto_inverse_0 filterlim_realpow_sequentially_gt1]) simp\n\nlemma LIMSEQ_realpow_zero:\n  \"\\<lbrakk>0 \\<le> (x::real); x < 1\\<rbrakk> \\<Longrightarrow> (\\<lambda>n. x ^ n) ----> 0\"\nproof cases\n  assume \"0 \\<le> x\" and \"x \\<noteq> 0\"\n  hence x0: \"0 < x\" by simp\n  assume x1: \"x < 1\"\n  from x0 x1 have \"1 < inverse x\"\n    by (rule one_less_inverse)\n  hence \"(\\<lambda>n. inverse (inverse x ^ n)) ----> 0\"\n    by (rule LIMSEQ_inverse_realpow_zero)\n  thus ?thesis by (simp add: power_inverse)\nqed (rule LIMSEQ_imp_Suc, simp)\n\nlemma LIMSEQ_power_zero:\n  fixes x :: \"'a::{real_normed_algebra_1}\"\n  shows \"norm x < 1 \\<Longrightarrow> (\\<lambda>n. x ^ n) ----> 0\"\napply (drule LIMSEQ_realpow_zero [OF norm_ge_zero])\napply (simp only: tendsto_Zfun_iff, erule Zfun_le)\napply (simp add: power_abs norm_power_ineq)\ndone\n\nlemma LIMSEQ_divide_realpow_zero: \"1 < x \\<Longrightarrow> (\\<lambda>n. a / (x ^ n) :: real) ----> 0\"\n  by (rule tendsto_divide_0 [OF tendsto_const filterlim_realpow_sequentially_gt1]) simp\n\ntext{*Limit of @{term \"c^n\"} for @{term\"\\<bar>c\\<bar> < 1\"}*}\n\nlemma LIMSEQ_rabs_realpow_zero: \"\\<bar>c\\<bar> < 1 \\<Longrightarrow> (\\<lambda>n. \\<bar>c\\<bar> ^ n :: real) ----> 0\"\n  by (rule LIMSEQ_realpow_zero [OF abs_ge_zero])\n\nlemma LIMSEQ_rabs_realpow_zero2: \"\\<bar>c\\<bar> < 1 \\<Longrightarrow> (\\<lambda>n. c ^ n :: real) ----> 0\"\n  by (rule LIMSEQ_power_zero) simp\n\n\nsubsection {* Limits of Functions *}\n\nlemma LIM_eq:\n  fixes a :: \"'a::real_normed_vector\" and L :: \"'b::real_normed_vector\"\n  shows \"f -- a --> L =\n     (\\<forall>r>0.\\<exists>s>0.\\<forall>x. x \\<noteq> a & norm (x-a) < s --> norm (f x - L) < r)\"\nby (simp add: LIM_def dist_norm)\n\nlemma LIM_I:\n  fixes a :: \"'a::real_normed_vector\" and L :: \"'b::real_normed_vector\"\n  shows \"(!!r. 0<r ==> \\<exists>s>0.\\<forall>x. x \\<noteq> a & norm (x-a) < s --> norm (f x - L) < r)\n      ==> f -- a --> L\"\nby (simp add: LIM_eq)\n\nlemma LIM_D:\n  fixes a :: \"'a::real_normed_vector\" and L :: \"'b::real_normed_vector\"\n  shows \"[| f -- a --> L; 0<r |]\n      ==> \\<exists>s>0.\\<forall>x. x \\<noteq> a & norm (x-a) < s --> norm (f x - L) < r\"\nby (simp add: LIM_eq)\n\nlemma LIM_offset:\n  fixes a :: \"'a::real_normed_vector\"\n  shows \"f -- a --> L \\<Longrightarrow> (\\<lambda>x. f (x + k)) -- a - k --> L\"\n  unfolding filtermap_at_shift[symmetric, of a k] filterlim_def filtermap_filtermap by simp\n\nlemma LIM_offset_zero:\n  fixes a :: \"'a::real_normed_vector\"\n  shows \"f -- a --> L \\<Longrightarrow> (\\<lambda>h. f (a + h)) -- 0 --> L\"\nby (drule_tac k=\"a\" in LIM_offset, simp add: add.commute)\n\nlemma LIM_offset_zero_cancel:\n  fixes a :: \"'a::real_normed_vector\"\n  shows \"(\\<lambda>h. f (a + h)) -- 0 --> L \\<Longrightarrow> f -- a --> L\"\nby (drule_tac k=\"- a\" in LIM_offset, simp)\n\nlemma LIM_offset_zero_iff:\n  fixes f :: \"'a :: real_normed_vector \\<Rightarrow> _\"\n  shows  \"f -- a --> L \\<longleftrightarrow> (\\<lambda>h. f (a + h)) -- 0 --> L\"\n  using LIM_offset_zero_cancel[of f a L] LIM_offset_zero[of f L a] by auto\n\nlemma LIM_zero:\n  fixes f :: \"'a::topological_space \\<Rightarrow> 'b::real_normed_vector\"\n  shows \"(f ---> l) F \\<Longrightarrow> ((\\<lambda>x. f x - l) ---> 0) F\"\nunfolding tendsto_iff dist_norm by simp\n\nlemma LIM_zero_cancel:\n  fixes f :: \"'a::topological_space \\<Rightarrow> 'b::real_normed_vector\"\n  shows \"((\\<lambda>x. f x - l) ---> 0) F \\<Longrightarrow> (f ---> l) F\"\nunfolding tendsto_iff dist_norm by simp\n\nlemma LIM_zero_iff:\n  fixes f :: \"'a::metric_space \\<Rightarrow> 'b::real_normed_vector\"\n  shows \"((\\<lambda>x. f x - l) ---> 0) F = (f ---> l) F\"\nunfolding tendsto_iff dist_norm by simp\n\nlemma LIM_imp_LIM:\n  fixes f :: \"'a::topological_space \\<Rightarrow> 'b::real_normed_vector\"\n  fixes g :: \"'a::topological_space \\<Rightarrow> 'c::real_normed_vector\"\n  assumes f: \"f -- a --> l\"\n  assumes le: \"\\<And>x. x \\<noteq> a \\<Longrightarrow> norm (g x - m) \\<le> norm (f x - l)\"\n  shows \"g -- a --> m\"\n  by (rule metric_LIM_imp_LIM [OF f],\n    simp add: dist_norm le)\n\nlemma LIM_equal2:\n  fixes f g :: \"'a::real_normed_vector \\<Rightarrow> 'b::topological_space\"\n  assumes 1: \"0 < R\"\n  assumes 2: \"\\<And>x. \\<lbrakk>x \\<noteq> a; norm (x - a) < R\\<rbrakk> \\<Longrightarrow> f x = g x\"\n  shows \"g -- a --> l \\<Longrightarrow> f -- a --> l\"\nby (rule metric_LIM_equal2 [OF 1 2], simp_all add: dist_norm)\n\nlemma LIM_compose2:\n  fixes a :: \"'a::real_normed_vector\"\n  assumes f: \"f -- a --> b\"\n  assumes g: \"g -- b --> c\"\n  assumes inj: \"\\<exists>d>0. \\<forall>x. x \\<noteq> a \\<and> norm (x - a) < d \\<longrightarrow> f x \\<noteq> b\"\n  shows \"(\\<lambda>x. g (f x)) -- a --> c\"\nby (rule metric_LIM_compose2 [OF f g inj [folded dist_norm]])\n\nlemma real_LIM_sandwich_zero:\n  fixes f g :: \"'a::topological_space \\<Rightarrow> real\"\n  assumes f: \"f -- a --> 0\"\n  assumes 1: \"\\<And>x. x \\<noteq> a \\<Longrightarrow> 0 \\<le> g x\"\n  assumes 2: \"\\<And>x. x \\<noteq> a \\<Longrightarrow> g x \\<le> f x\"\n  shows \"g -- a --> 0\"\nproof (rule LIM_imp_LIM [OF f]) (* FIXME: use tendsto_sandwich *)\n  fix x assume x: \"x \\<noteq> a\"\n  have \"norm (g x - 0) = g x\" by (simp add: 1 x)\n  also have \"g x \\<le> f x\" by (rule 2 [OF x])\n  also have \"f x \\<le> \\<bar>f x\\<bar>\" by (rule abs_ge_self)\n  also have \"\\<bar>f x\\<bar> = norm (f x - 0)\" by simp\n  finally show \"norm (g x - 0) \\<le> norm (f x - 0)\" .\nqed\n\n\nsubsection {* Continuity *}\n\nlemma LIM_isCont_iff:\n  fixes f :: \"'a::real_normed_vector \\<Rightarrow> 'b::topological_space\"\n  shows \"(f -- a --> f a) = ((\\<lambda>h. f (a + h)) -- 0 --> f a)\"\nby (rule iffI [OF LIM_offset_zero LIM_offset_zero_cancel])\n\nlemma isCont_iff:\n  fixes f :: \"'a::real_normed_vector \\<Rightarrow> 'b::topological_space\"\n  shows \"isCont f x = (\\<lambda>h. f (x + h)) -- 0 --> f x\"\nby (simp add: isCont_def LIM_isCont_iff)\n\nlemma isCont_LIM_compose2:\n  fixes a :: \"'a::real_normed_vector\"\n  assumes f [unfolded isCont_def]: \"isCont f a\"\n  assumes g: \"g -- f a --> l\"\n  assumes inj: \"\\<exists>d>0. \\<forall>x. x \\<noteq> a \\<and> norm (x - a) < d \\<longrightarrow> f x \\<noteq> f a\"\n  shows \"(\\<lambda>x. g (f x)) -- a --> l\"\nby (rule LIM_compose2 [OF f g inj])\n\n\nlemma isCont_norm [simp]:\n  fixes f :: \"'a::t2_space \\<Rightarrow> 'b::real_normed_vector\"\n  shows \"isCont f a \\<Longrightarrow> isCont (\\<lambda>x. norm (f x)) a\"\n  by (fact continuous_norm)\n\nlemma isCont_rabs [simp]:\n  fixes f :: \"'a::t2_space \\<Rightarrow> real\"\n  shows \"isCont f a \\<Longrightarrow> isCont (\\<lambda>x. \\<bar>f x\\<bar>) a\"\n  by (fact continuous_rabs)\n\nlemma isCont_add [simp]:\n  fixes f :: \"'a::t2_space \\<Rightarrow> 'b::real_normed_vector\"\n  shows \"\\<lbrakk>isCont f a; isCont g a\\<rbrakk> \\<Longrightarrow> isCont (\\<lambda>x. f x + g x) a\"\n  by (fact continuous_add)\n\nlemma isCont_minus [simp]:\n  fixes f :: \"'a::t2_space \\<Rightarrow> 'b::real_normed_vector\"\n  shows \"isCont f a \\<Longrightarrow> isCont (\\<lambda>x. - f x) a\"\n  by (fact continuous_minus)\n\nlemma isCont_diff [simp]:\n  fixes f :: \"'a::t2_space \\<Rightarrow> 'b::real_normed_vector\"\n  shows \"\\<lbrakk>isCont f a; isCont g a\\<rbrakk> \\<Longrightarrow> isCont (\\<lambda>x. f x - g x) a\"\n  by (fact continuous_diff)\n\nlemma isCont_mult [simp]:\n  fixes f g :: \"'a::t2_space \\<Rightarrow> 'b::real_normed_algebra\"\n  shows \"\\<lbrakk>isCont f a; isCont g a\\<rbrakk> \\<Longrightarrow> isCont (\\<lambda>x. f x * g x) a\"\n  by (fact continuous_mult)\n\nlemma (in bounded_linear) isCont:\n  \"isCont g a \\<Longrightarrow> isCont (\\<lambda>x. f (g x)) a\"\n  by (fact continuous)\n\nlemma (in bounded_bilinear) isCont:\n  \"\\<lbrakk>isCont f a; isCont g a\\<rbrakk> \\<Longrightarrow> isCont (\\<lambda>x. f x ** g x) a\"\n  by (fact continuous)\n\nlemmas isCont_scaleR [simp] = \n  bounded_bilinear.isCont [OF bounded_bilinear_scaleR]\n\nlemmas isCont_of_real [simp] =\n  bounded_linear.isCont [OF bounded_linear_of_real]\n\nlemma isCont_power [simp]:\n  fixes f :: \"'a::t2_space \\<Rightarrow> 'b::{power,real_normed_algebra}\"\n  shows \"isCont f a \\<Longrightarrow> isCont (\\<lambda>x. f x ^ n) a\"\n  by (fact continuous_power)\n\nlemma isCont_setsum [simp]:\n  fixes f :: \"'a \\<Rightarrow> 'b::t2_space \\<Rightarrow> 'c::real_normed_vector\"\n  shows \"\\<forall>i\\<in>A. isCont (f i) a \\<Longrightarrow> isCont (\\<lambda>x. \\<Sum>i\\<in>A. f i x) a\"\n  by (auto intro: continuous_setsum)\n\nsubsection {* Uniform Continuity *}\n\ndefinition\n  isUCont :: \"['a::metric_space \\<Rightarrow> 'b::metric_space] \\<Rightarrow> bool\" where\n  \"isUCont f = (\\<forall>r>0. \\<exists>s>0. \\<forall>x y. dist x y < s \\<longrightarrow> dist (f x) (f y) < r)\"\n\nlemma isUCont_isCont: \"isUCont f ==> isCont f x\"\nby (simp add: isUCont_def isCont_def LIM_def, force)\n\nlemma isUCont_Cauchy:\n  \"\\<lbrakk>isUCont f; Cauchy X\\<rbrakk> \\<Longrightarrow> Cauchy (\\<lambda>n. f (X n))\"\nunfolding isUCont_def\napply (rule metric_CauchyI)\napply (drule_tac x=e in spec, safe)\napply (drule_tac e=s in metric_CauchyD, safe)\napply (rule_tac x=M in exI, simp)\ndone\n\nlemma (in bounded_linear) isUCont: \"isUCont f\"\nunfolding isUCont_def dist_norm\nproof (intro allI impI)\n  fix r::real assume r: \"0 < r\"\n  obtain K where K: \"0 < K\" and norm_le: \"\\<And>x. norm (f x) \\<le> norm x * K\"\n    using pos_bounded by fast\n  show \"\\<exists>s>0. \\<forall>x y. norm (x - y) < s \\<longrightarrow> norm (f x - f y) < r\"\n  proof (rule exI, safe)\n    from r K show \"0 < r / K\" by simp\n  next\n    fix x y :: 'a\n    assume xy: \"norm (x - y) < r / K\"\n    have \"norm (f x - f y) = norm (f (x - y))\" by (simp only: diff)\n    also have \"\\<dots> \\<le> norm (x - y) * K\" by (rule norm_le)\n    also from K xy have \"\\<dots> < r\" by (simp only: pos_less_divide_eq)\n    finally show \"norm (f x - f y) < r\" .\n  qed\nqed\n\nlemma (in bounded_linear) Cauchy: \"Cauchy X \\<Longrightarrow> Cauchy (\\<lambda>n. f (X n))\"\nby (rule isUCont [THEN isUCont_Cauchy])\n\nlemma LIM_less_bound: \n  fixes f :: \"real \\<Rightarrow> real\"\n  assumes ev: \"b < x\" \"\\<forall> x' \\<in> { b <..< x}. 0 \\<le> f x'\" and \"isCont f x\"\n  shows \"0 \\<le> f x\"\nproof (rule tendsto_le_const)\n  show \"(f ---> f x) (at_left x)\"\n    using `isCont f x` by (simp add: filterlim_at_split isCont_def)\n  show \"eventually (\\<lambda>x. 0 \\<le> f x) (at_left x)\"\n    using ev by (auto simp: eventually_at dist_real_def intro!: exI[of _ \"x - b\"])\nqed simp\n\n\nsubsection {* Nested Intervals and Bisection -- Needed for Compactness *}\n\nlemma nested_sequence_unique:\n  assumes \"\\<forall>n. f n \\<le> f (Suc n)\" \"\\<forall>n. g (Suc n) \\<le> g n\" \"\\<forall>n. f n \\<le> g n\" \"(\\<lambda>n. f n - g n) ----> 0\"\n  shows \"\\<exists>l::real. ((\\<forall>n. f n \\<le> l) \\<and> f ----> l) \\<and> ((\\<forall>n. l \\<le> g n) \\<and> g ----> l)\"\nproof -\n  have \"incseq f\" unfolding incseq_Suc_iff by fact\n  have \"decseq g\" unfolding decseq_Suc_iff by fact\n\n  { fix n\n    from `decseq g` have \"g n \\<le> g 0\" by (rule decseqD) simp\n    with `\\<forall>n. f n \\<le> g n`[THEN spec, of n] have \"f n \\<le> g 0\" by auto }\n  then obtain u where \"f ----> u\" \"\\<forall>i. f i \\<le> u\"\n    using incseq_convergent[OF `incseq f`] by auto\n  moreover\n  { fix n\n    from `incseq f` have \"f 0 \\<le> f n\" by (rule incseqD) simp\n    with `\\<forall>n. f n \\<le> g n`[THEN spec, of n] have \"f 0 \\<le> g n\" by simp }\n  then obtain l where \"g ----> l\" \"\\<forall>i. l \\<le> g i\"\n    using decseq_convergent[OF `decseq g`] by auto\n  moreover note LIMSEQ_unique[OF assms(4) tendsto_diff[OF `f ----> u` `g ----> l`]]\n  ultimately show ?thesis by auto\nqed\n\nlemma Bolzano[consumes 1, case_names trans local]:\n  fixes P :: \"real \\<Rightarrow> real \\<Rightarrow> bool\"\n  assumes [arith]: \"a \\<le> b\"\n  assumes trans: \"\\<And>a b c. \\<lbrakk>P a b; P b c; a \\<le> b; b \\<le> c\\<rbrakk> \\<Longrightarrow> P a c\"\n  assumes local: \"\\<And>x. a \\<le> x \\<Longrightarrow> x \\<le> b \\<Longrightarrow> \\<exists>d>0. \\<forall>a b. a \\<le> x \\<and> x \\<le> b \\<and> b - a < d \\<longrightarrow> P a b\"\n  shows \"P a b\"\nproof -\n  def bisect \\<equiv> \"rec_nat (a, b) (\\<lambda>n (x, y). if P x ((x+y) / 2) then ((x+y)/2, y) else (x, (x+y)/2))\"\n  def l \\<equiv> \"\\<lambda>n. fst (bisect n)\" and u \\<equiv> \"\\<lambda>n. snd (bisect n)\"\n  have l[simp]: \"l 0 = a\" \"\\<And>n. l (Suc n) = (if P (l n) ((l n + u n) / 2) then (l n + u n) / 2 else l n)\"\n    and u[simp]: \"u 0 = b\" \"\\<And>n. u (Suc n) = (if P (l n) ((l n + u n) / 2) then u n else (l n + u n) / 2)\"\n    by (simp_all add: l_def u_def bisect_def split: prod.split)\n\n  { fix n have \"l n \\<le> u n\" by (induct n) auto } note this[simp]\n\n  have \"\\<exists>x. ((\\<forall>n. l n \\<le> x) \\<and> l ----> x) \\<and> ((\\<forall>n. x \\<le> u n) \\<and> u ----> x)\"\n  proof (safe intro!: nested_sequence_unique)\n    fix n show \"l n \\<le> l (Suc n)\" \"u (Suc n) \\<le> u n\" by (induct n) auto\n  next\n    { fix n have \"l n - u n = (a - b) / 2^n\" by (induct n) (auto simp: field_simps) }\n    then show \"(\\<lambda>n. l n - u n) ----> 0\" by (simp add: LIMSEQ_divide_realpow_zero)\n  qed fact\n  then obtain x where x: \"\\<And>n. l n \\<le> x\" \"\\<And>n. x \\<le> u n\" and \"l ----> x\" \"u ----> x\" by auto\n  obtain d where \"0 < d\" and d: \"\\<And>a b. a \\<le> x \\<Longrightarrow> x \\<le> b \\<Longrightarrow> b - a < d \\<Longrightarrow> P a b\"\n    using `l 0 \\<le> x` `x \\<le> u 0` local[of x] by auto\n\n  show \"P a b\"\n  proof (rule ccontr)\n    assume \"\\<not> P a b\" \n    { fix n have \"\\<not> P (l n) (u n)\"\n      proof (induct n)\n        case (Suc n) with trans[of \"l n\" \"(l n + u n) / 2\" \"u n\"] show ?case by auto\n      qed (simp add: `\\<not> P a b`) }\n    moreover\n    { have \"eventually (\\<lambda>n. x - d / 2 < l n) sequentially\"\n        using `0 < d` `l ----> x` by (intro order_tendstoD[of _ x]) auto\n      moreover have \"eventually (\\<lambda>n. u n < x + d / 2) sequentially\"\n        using `0 < d` `u ----> x` by (intro order_tendstoD[of _ x]) auto\n      ultimately have \"eventually (\\<lambda>n. P (l n) (u n)) sequentially\"\n      proof eventually_elim\n        fix n assume \"x - d / 2 < l n\" \"u n < x + d / 2\"\n        from add_strict_mono[OF this] have \"u n - l n < d\" by simp\n        with x show \"P (l n) (u n)\" by (rule d)\n      qed }\n    ultimately show False by simp\n  qed\nqed\n\nlemma compact_Icc[simp, intro]: \"compact {a .. b::real}\"\nproof (cases \"a \\<le> b\", rule compactI)\n  fix C assume C: \"a \\<le> b\" \"\\<forall>t\\<in>C. open t\" \"{a..b} \\<subseteq> \\<Union>C\"\n  def T == \"{a .. b}\"\n  from C(1,3) show \"\\<exists>C'\\<subseteq>C. finite C' \\<and> {a..b} \\<subseteq> \\<Union>C'\"\n  proof (induct rule: Bolzano)\n    case (trans a b c)\n    then have *: \"{a .. c} = {a .. b} \\<union> {b .. c}\" by auto\n    from trans obtain C1 C2 where \"C1\\<subseteq>C \\<and> finite C1 \\<and> {a..b} \\<subseteq> \\<Union>C1\" \"C2\\<subseteq>C \\<and> finite C2 \\<and> {b..c} \\<subseteq> \\<Union>C2\"\n      by (auto simp: *)\n    with trans show ?case\n      unfolding * by (intro exI[of _ \"C1 \\<union> C2\"]) auto\n  next\n    case (local x)\n    then have \"x \\<in> \\<Union>C\" using C by auto\n    with C(2) obtain c where \"x \\<in> c\" \"open c\" \"c \\<in> C\" by auto\n    then obtain e where \"0 < e\" \"{x - e <..< x + e} \\<subseteq> c\"\n      by (auto simp: open_real_def dist_real_def subset_eq Ball_def abs_less_iff)\n    with `c \\<in> C` show ?case\n      by (safe intro!: exI[of _ \"e/2\"] exI[of _ \"{c}\"]) auto\n  qed\nqed simp\n\n\nlemma continuous_image_closed_interval:\n  fixes a b and f :: \"real \\<Rightarrow> real\"\n  defines \"S \\<equiv> {a..b}\"\n  assumes \"a \\<le> b\" and f: \"continuous_on S f\"\n  shows \"\\<exists>c d. f`S = {c..d} \\<and> c \\<le> d\"\nproof -\n  have S: \"compact S\" \"S \\<noteq> {}\"\n    using `a \\<le> b` by (auto simp: S_def)\n  obtain c where \"c \\<in> S\" \"\\<forall>d\\<in>S. f d \\<le> f c\"\n    using continuous_attains_sup[OF S f] by auto\n  moreover obtain d where \"d \\<in> S\" \"\\<forall>c\\<in>S. f d \\<le> f c\"\n    using continuous_attains_inf[OF S f] by auto\n  moreover have \"connected (f`S)\"\n    using connected_continuous_image[OF f] connected_Icc by (auto simp: S_def)\n  ultimately have \"f ` S = {f d .. f c} \\<and> f d \\<le> f c\"\n    by (auto simp: connected_iff_interval)\n  then show ?thesis\n    by auto\nqed\n\nsubsection {* Boundedness of continuous functions *}\n\ntext{*By bisection, function continuous on closed interval is bounded above*}\n\nlemma isCont_eq_Ub:\n  fixes f :: \"real \\<Rightarrow> 'a::linorder_topology\"\n  shows \"a \\<le> b \\<Longrightarrow> \\<forall>x::real. a \\<le> x \\<and> x \\<le> b \\<longrightarrow> isCont f x \\<Longrightarrow>\n    \\<exists>M. (\\<forall>x. a \\<le> x \\<and> x \\<le> b \\<longrightarrow> f x \\<le> M) \\<and> (\\<exists>x. a \\<le> x \\<and> x \\<le> b \\<and> f x = M)\"\n  using continuous_attains_sup[of \"{a .. b}\" f]\n  by (auto simp add: continuous_at_imp_continuous_on Ball_def Bex_def)\n\nlemma isCont_eq_Lb:\n  fixes f :: \"real \\<Rightarrow> 'a::linorder_topology\"\n  shows \"a \\<le> b \\<Longrightarrow> \\<forall>x. a \\<le> x \\<and> x \\<le> b \\<longrightarrow> isCont f x \\<Longrightarrow>\n    \\<exists>M. (\\<forall>x. a \\<le> x \\<and> x \\<le> b \\<longrightarrow> M \\<le> f x) \\<and> (\\<exists>x. a \\<le> x \\<and> x \\<le> b \\<and> f x = M)\"\n  using continuous_attains_inf[of \"{a .. b}\" f]\n  by (auto simp add: continuous_at_imp_continuous_on Ball_def Bex_def)\n\nlemma isCont_bounded:\n  fixes f :: \"real \\<Rightarrow> 'a::linorder_topology\"\n  shows \"a \\<le> b \\<Longrightarrow> \\<forall>x. a \\<le> x \\<and> x \\<le> b \\<longrightarrow> isCont f x \\<Longrightarrow> \\<exists>M. \\<forall>x. a \\<le> x \\<and> x \\<le> b \\<longrightarrow> f x \\<le> M\"\n  using isCont_eq_Ub[of a b f] by auto\n\nlemma isCont_has_Ub:\n  fixes f :: \"real \\<Rightarrow> 'a::linorder_topology\"\n  shows \"a \\<le> b \\<Longrightarrow> \\<forall>x. a \\<le> x \\<and> x \\<le> b \\<longrightarrow> isCont f x \\<Longrightarrow>\n    \\<exists>M. (\\<forall>x. a \\<le> x \\<and> x \\<le> b \\<longrightarrow> f x \\<le> M) \\<and> (\\<forall>N. N < M \\<longrightarrow> (\\<exists>x. a \\<le> x \\<and> x \\<le> b \\<and> N < f x))\"\n  using isCont_eq_Ub[of a b f] by auto\n\n(*HOL style here: object-level formulations*)\nlemma IVT_objl: \"(f(a::real) \\<le> (y::real) & y \\<le> f(b) & a \\<le> b &\n      (\\<forall>x. a \\<le> x & x \\<le> b --> isCont f x))\n      --> (\\<exists>x. a \\<le> x & x \\<le> b & f(x) = y)\"\n  by (blast intro: IVT)\n\nlemma IVT2_objl: \"(f(b::real) \\<le> (y::real) & y \\<le> f(a) & a \\<le> b &\n      (\\<forall>x. a \\<le> x & x \\<le> b --> isCont f x))\n      --> (\\<exists>x. a \\<le> x & x \\<le> b & f(x) = y)\"\n  by (blast intro: IVT2)\n\nlemma isCont_Lb_Ub:\n  fixes f :: \"real \\<Rightarrow> real\"\n  assumes \"a \\<le> b\" \"\\<forall>x. a \\<le> x \\<and> x \\<le> b \\<longrightarrow> isCont f x\"\n  shows \"\\<exists>L M. (\\<forall>x. a \\<le> x \\<and> x \\<le> b \\<longrightarrow> L \\<le> f x \\<and> f x \\<le> M) \\<and> \n               (\\<forall>y. L \\<le> y \\<and> y \\<le> M \\<longrightarrow> (\\<exists>x. a \\<le> x \\<and> x \\<le> b \\<and> (f x = y)))\"\nproof -\n  obtain M where M: \"a \\<le> M\" \"M \\<le> b\" \"\\<forall>x. a \\<le> x \\<and> x \\<le> b \\<longrightarrow> f x \\<le> f M\"\n    using isCont_eq_Ub[OF assms] by auto\n  obtain L where L: \"a \\<le> L\" \"L \\<le> b\" \"\\<forall>x. a \\<le> x \\<and> x \\<le> b \\<longrightarrow> f L \\<le> f x\"\n    using isCont_eq_Lb[OF assms] by auto\n  show ?thesis\n    using IVT[of f L _ M] IVT2[of f L _ M] M L assms\n    apply (rule_tac x=\"f L\" in exI)\n    apply (rule_tac x=\"f M\" in exI)\n    apply (cases \"L \\<le> M\")\n    apply (simp, metis order_trans)\n    apply (simp, metis order_trans)\n    done\nqed\n\n\ntext{*Continuity of inverse function*}\n\nlemma isCont_inverse_function:\n  fixes f g :: \"real \\<Rightarrow> real\"\n  assumes d: \"0 < d\"\n      and inj: \"\\<forall>z. \\<bar>z-x\\<bar> \\<le> d \\<longrightarrow> g (f z) = z\"\n      and cont: \"\\<forall>z. \\<bar>z-x\\<bar> \\<le> d \\<longrightarrow> isCont f z\"\n  shows \"isCont g (f x)\"\nproof -\n  let ?A = \"f (x - d)\" and ?B = \"f (x + d)\" and ?D = \"{x - d..x + d}\"\n\n  have f: \"continuous_on ?D f\"\n    using cont by (intro continuous_at_imp_continuous_on ballI) auto\n  then have g: \"continuous_on (f`?D) g\"\n    using inj by (intro continuous_on_inv) auto\n\n  from d f have \"{min ?A ?B <..< max ?A ?B} \\<subseteq> f ` ?D\"\n    by (intro connected_contains_Ioo connected_continuous_image) (auto split: split_min split_max)\n  with g have \"continuous_on {min ?A ?B <..< max ?A ?B} g\"\n    by (rule continuous_on_subset)\n  moreover\n  have \"(?A < f x \\<and> f x < ?B) \\<or> (?B < f x \\<and> f x < ?A)\"\n    using d inj by (intro continuous_inj_imp_mono[OF _ _ f] inj_on_imageI2[of g, OF inj_onI]) auto\n  then have \"f x \\<in> {min ?A ?B <..< max ?A ?B}\"\n    by auto\n  ultimately\n  show ?thesis\n    by (simp add: continuous_on_eq_continuous_at)\nqed\n\nlemma isCont_inverse_function2:\n  fixes f g :: \"real \\<Rightarrow> real\" shows\n  \"\\<lbrakk>a < x; x < b;\n    \\<forall>z. a \\<le> z \\<and> z \\<le> b \\<longrightarrow> g (f z) = z;\n    \\<forall>z. a \\<le> z \\<and> z \\<le> b \\<longrightarrow> isCont f z\\<rbrakk>\n   \\<Longrightarrow> isCont g (f x)\"\napply (rule isCont_inverse_function\n       [where f=f and d=\"min (x - a) (b - x)\"])\napply (simp_all add: abs_le_iff)\ndone\n\n(* need to rename second isCont_inverse *)\n\nlemma isCont_inv_fun:\n  fixes f g :: \"real \\<Rightarrow> real\"\n  shows \"[| 0 < d; \\<forall>z. \\<bar>z - x\\<bar> \\<le> d --> g(f(z)) = z;  \n         \\<forall>z. \\<bar>z - x\\<bar> \\<le> d --> isCont f z |]  \n      ==> isCont g (f x)\"\nby (rule isCont_inverse_function)\n\ntext{*Bartle/Sherbert: Introduction to Real Analysis, Theorem 4.2.9, p. 110*}\nlemma LIM_fun_gt_zero:\n  fixes f :: \"real \\<Rightarrow> real\"\n  shows \"f -- c --> l \\<Longrightarrow> 0 < l \\<Longrightarrow> \\<exists>r. 0 < r \\<and> (\\<forall>x. x \\<noteq> c \\<and> \\<bar>c - x\\<bar> < r \\<longrightarrow> 0 < f x)\"\napply (drule (1) LIM_D, clarify)\napply (rule_tac x = s in exI)\napply (simp add: abs_less_iff)\ndone\n\nlemma LIM_fun_less_zero:\n  fixes f :: \"real \\<Rightarrow> real\"\n  shows \"f -- c --> l \\<Longrightarrow> l < 0 \\<Longrightarrow> \\<exists>r. 0 < r \\<and> (\\<forall>x. x \\<noteq> c \\<and> \\<bar>c - x\\<bar> < r \\<longrightarrow> f x < 0)\"\napply (drule LIM_D [where r=\"-l\"], simp, clarify)\napply (rule_tac x = s in exI)\napply (simp add: abs_less_iff)\ndone\n\nlemma LIM_fun_not_zero:\n  fixes f :: \"real \\<Rightarrow> real\"\n  shows \"f -- c --> l \\<Longrightarrow> l \\<noteq> 0 \\<Longrightarrow> \\<exists>r. 0 < r \\<and> (\\<forall>x. x \\<noteq> c \\<and> \\<bar>c - x\\<bar> < r \\<longrightarrow> f x \\<noteq> 0)\"\n  using LIM_fun_gt_zero[of f l c] LIM_fun_less_zero[of f l c] by (auto simp add: neq_iff)\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/Limits.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8947894632969137, "lm_q2_score": 0.8198933337131076, "lm_q1q2_score": 0.7336319160338689}}
{"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.*)\n  theory TIP_prop_34\n  imports \"../../Test_Base\"\nbegin\n\ndatatype Nat = Z | S \"Nat\"\n\nfun t2 :: \"Nat => Nat => Nat\" where\n  \"t2 (Z) y = y\"\n| \"t2 (S z) y = S (t2 z y)\"\n\nfun t22 :: \"Nat => Nat => Nat\" where\n  \"t22 (Z) y = Z\"\n| \"t22 (S z) y = t2 y (t22 z y)\"\n\nfun mult :: \"Nat => Nat => Nat => Nat\" where\n  \"mult (Z) y z = z\"\n| \"mult (S x2) y z = mult x2 y (t2 y z)\"\nlemma t2_0: \"t2 x Z = x\" by (induction x, auto)\nlemma t2_assoc: \"t2 (t2 x y) z = t2 x (t2 y z)\" by(induction x, auto)\nlemma t2_comm_suc: \"t2 (S x) y = t2 x (S y)\" by (induction x, auto)\nlemma t2_comm: \"t2 x y = t2 y x\" using t2_0 t2_comm_suc by (induction x, simp_all)\nlemma t2_mult: \"t2 w (mult x y z) = mult x y (t2 w z)\"\n  using t2_assoc t2_comm by(induction x arbitrary: w y z, simp_all)\ntheorem property0 :\n  \"((t22 x y) = (mult x y Z))\"\n  apply(induction x arbitrary: y, auto)\n  apply(simp add: t2_mult)\n  done\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_34.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869981319863, "lm_q2_score": 0.8376199653600372, "lm_q1q2_score": 0.7335766750380854}}
{"text": "theory Cantor\n  imports Main\nbegin\n\ntext \\<open>\n  Cantor's theorem states that every set has more subsets than it has element.\n\n  This version of the theorem states for every function from \\<alpha> to its powerset,\n  some subset is outside its range.\n\\<close>\n\n(* \"automatic\" *)\ntheorem Cantor: \"\\<exists>S. S \\<notin> range (f :: 'a \\<Rightarrow> 'a set)\"\n  by blast\n\n(* \"exploring, but unstructured\" *)\ntheorem Cantor': \"\\<exists>S. S \\<notin> range (f :: 'a \\<Rightarrow> 'a set)\"\n  apply (rule_tac x = \"{ x. x \\<notin> f x}\" in exI)\n  apply (rule notI)\n  apply clarsimp\n  apply blast\n  done\n\n(* \"structured, explaining\" *)\ntheorem Cantor'': \"\\<exists>S. S \\<notin> range (f :: 'a \\<Rightarrow> 'a set)\"\nproof\n  let ?S = \"{ x. x \\<notin> f x }\"\n  show \"?S \\<notin> range f\"\n  proof\n    assume \"?S \\<in> range f\"\n    then obtain y where fy: \"?S = f y\" ..\n    show False\n    proof cases\n      assume \"y \\<in> ?S\"\n      hence \"y \\<notin> f y\" by simp\n      hence \"y \\<notin> ?S\" by (simp add:fy)\n      with \\<open>y \\<in> ?S\\<close> show False by contradiction\n    next\n      assume \"y \\<notin> ?S\"\n      hence \"y \\<in> f y\" by simp\n      hence \"y \\<in> ?S\" by (simp add:fy)\n      with \\<open>y \\<notin> ?S\\<close> show False by contradiction\n    qed\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/Cantor.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045877523147, "lm_q2_score": 0.8267117962054049, "lm_q1q2_score": 0.7334624983423919}}
{"text": "(*\n  File:       E_Transcendental.thy\n  Author:     Manuel Eberl <eberlm@in.tum.de>\n\n  A proof that e (Euler's number) is transcendental.\n  Could possibly be extended to a transcendence proof for pi or\n  the very general Lindemann-Weierstrass theorem.\n*)\nsection \\<open>Proof of the Transcendence of $e$\\<close>\ntheory E_Transcendental\n  imports\n    \"HOL-Complex_Analysis.Complex_Analysis\"\n    \"HOL-Number_Theory.Number_Theory\"\n    \"HOL-Computational_Algebra.Polynomial\"\nbegin\n\n(* TODO: Lots of stuff to move to the distribution *)\n  \nsubsection \\<open>Various auxiliary facts\\<close>\n\nlemma fact_dvd_pochhammer:\n  assumes \"m \\<le> n + 1\"\n  shows   \"fact m dvd pochhammer (int n - int m + 1) m\"\nproof -\n  have \"(real n gchoose m) * fact m = of_int (pochhammer (int n - int m + 1) m)\"\n    by (simp add: gbinomial_pochhammer' pochhammer_of_int [symmetric])\n  also have \"(real n gchoose m) * fact m = of_int (int (n choose m) * fact m)\"\n    by (simp add: binomial_gbinomial)\n  finally have \"int (n choose m) * fact m = pochhammer (int n - int m + 1) m\"\n    by (subst (asm) of_int_eq_iff)\n  from this [symmetric] show ?thesis by simp\nqed\n\nlemma of_nat_eq_1_iff [simp]: \"of_nat x = (1 :: 'a :: semiring_char_0) \\<longleftrightarrow> x = 1\"\n  by (fact of_nat_eq_1_iff)\n\nlemma prime_elem_int_not_dvd_neg1_power:\n  \"prime_elem (p :: int) \\<Longrightarrow> \\<not>p dvd (-1) ^ n\"\n  by (rule notI, frule (1) prime_elem_dvd_power, cases \"p \\<ge> 0\") (auto simp: prime_elem_def)\n\nlemma nat_fact [simp]: \"nat (fact n) = fact n\"\n  by (subst of_nat_fact [symmetric]) (rule nat_int)\n\nlemma prime_dvd_fact_iff_int:\n  \"p dvd fact n \\<longleftrightarrow> p \\<le> int n\" if \"prime p\"\n  using that prime_dvd_fact_iff [of \"nat \\<bar>p\\<bar>\" n]\n  by auto (simp add: prime_ge_0_int)\n\nlemma filterlim_minus_nat_at_top:\n  \"filterlim (\\<lambda>n. n - k :: nat) at_top at_top\"\nproof -\n  have \"sequentially = filtermap (\\<lambda>n. n + k) at_top\"\n    by (auto simp: filter_eq_iff eventually_filtermap)\n  also have \"filterlim (\\<lambda>n. n - k :: nat) at_top \\<dots>\"\n    by (simp add: filterlim_filtermap filterlim_ident)\n  finally show ?thesis .\nqed\n\nlemma power_over_fact_tendsto_0:\n  \"(\\<lambda>n. (x :: real) ^ n / fact n) \\<longlonglongrightarrow> 0\"\n  using summable_exp[of x] by (intro summable_LIMSEQ_zero) (simp add: sums_iff field_simps)\n\nlemma power_over_fact_tendsto_0':\n  \"(\\<lambda>n. c * (x :: real) ^ n / fact n) \\<longlonglongrightarrow> 0\"\n  using tendsto_mult[OF tendsto_const[of c] power_over_fact_tendsto_0[of x]] by simp\n\n\nsubsection \\<open>Lifting integer polynomials\\<close>\n\nlift_definition of_int_poly :: \"int poly \\<Rightarrow> 'a :: comm_ring_1 poly\" is \"\\<lambda>g x. of_int (g x)\"\n  by (auto elim: eventually_mono)\n\nlemma coeff_of_int_poly [simp]: \"coeff (of_int_poly p) n = of_int (coeff p n)\"\n  by transfer' simp\n\nlemma of_int_poly_0 [simp]: \"of_int_poly 0 = 0\"\n  by transfer (simp add: fun_eq_iff)\n\nlemma of_int_poly_pCons [simp]: \"of_int_poly (pCons c p) = pCons (of_int c) (of_int_poly p)\"\n  by transfer' (simp add: fun_eq_iff split: nat.splits)\n\nlemma of_int_poly_smult [simp]: \"of_int_poly (smult c p) = smult (of_int c) (of_int_poly p)\"\n  by transfer simp\n\nlemma of_int_poly_1 [simp]: \"of_int_poly 1 = 1\"\n  by (simp add: one_pCons)\n\nlemma of_int_poly_add [simp]: \"of_int_poly (p + q) = of_int_poly p + of_int_poly q\"\n  by transfer' (simp add: fun_eq_iff)\n\nlemma of_int_poly_mult [simp]: \"of_int_poly (p * q) = (of_int_poly p * of_int_poly q)\"\n  by (induction p) simp_all\n\nlemma of_int_poly_sum [simp]: \"of_int_poly (sum f A) = sum (\\<lambda>x. of_int_poly (f x)) A\"\n  by (induction A rule: infinite_finite_induct) simp_all\n\nlemma of_int_poly_prod [simp]: \"of_int_poly (prod f A) = prod (\\<lambda>x. of_int_poly (f x)) A\"\n  by (induction A rule: infinite_finite_induct) simp_all\n\nlemma of_int_poly_power [simp]: \"of_int_poly (p ^ n) = of_int_poly p ^ n\"\n  by (induction n) simp_all\n\nlemma of_int_poly_monom [simp]: \"of_int_poly (monom c n) = monom (of_int c) n\"\n  by transfer (simp add: fun_eq_iff)\n\nlemma poly_of_int_poly [simp]: \"poly (of_int_poly p) (of_int x) = of_int (poly p x)\"\n  by (induction p) simp_all\n\nlemma poly_of_int_poly_of_nat [simp]: \"poly (of_int_poly p) (of_nat x) = of_int (poly p (int x))\"\n  by (induction p) simp_all\n\nlemma poly_of_int_poly_0 [simp]: \"poly (of_int_poly p) 0 = of_int (poly p 0)\"\n  by (induction p) simp_all\n\nlemma poly_of_int_poly_1 [simp]: \"poly (of_int_poly p) 1 = of_int (poly p 1)\"\n  by (induction p) simp_all\n\nlemma poly_of_int_poly_of_real [simp]:\n    \"poly (of_int_poly p) (of_real x) = of_real (poly (of_int_poly p) x)\"\n  by (induction p) simp_all\n\nlemma of_int_poly_eq_iff [simp]:\n  \"of_int_poly p = (of_int_poly q :: 'a :: {comm_ring_1, ring_char_0} poly) \\<longleftrightarrow> p = q\"\n  by (simp add: poly_eq_iff)\n\nlemma of_int_poly_eq_0_iff [simp]:\n  \"of_int_poly p = (0 :: 'a :: {comm_ring_1, ring_char_0} poly) \\<longleftrightarrow> p = 0\"\n  using of_int_poly_eq_iff[of p 0] by (simp del: of_int_poly_eq_iff)\n\nlemma degree_of_int_poly [simp]:\n  \"degree (of_int_poly p :: 'a :: {comm_ring_1, ring_char_0} poly) = degree p\"\n  by (simp add: degree_def)\n\nlemma pderiv_of_int_poly [simp]: \"pderiv (of_int_poly p) = of_int_poly (pderiv p)\"\n  by (induction p) (simp_all add: pderiv_pCons)\n\nlemma higher_pderiv_of_int_poly [simp]:\n  \"(pderiv ^^ n) (of_int_poly p) = of_int_poly ((pderiv ^^ n) p)\"\n  by (induction n) simp_all\n\nlemma int_polyE:\n  assumes \"\\<And>n. coeff (p :: 'a :: {comm_ring_1, ring_char_0} poly) n \\<in> \\<int>\"\n  obtains p' where \"p = of_int_poly p'\"\nproof -\n  from assms have \"\\<forall>n. \\<exists>c. coeff p n = of_int c\" by (auto simp: Ints_def)\n  hence \"\\<exists>c. \\<forall>n. of_int (c n) = coeff p n\" by (simp add: choice_iff eq_commute)\n  then obtain c where c: \"of_int (c n) = coeff p n\" for n by blast\n  have [simp]: \"coeff (Abs_poly c) = c\"\n  proof (rule poly.Abs_poly_inverse, clarify)\n    have \"eventually (\\<lambda>n. n > degree p) at_top\" by (rule eventually_gt_at_top)\n    hence \"eventually (\\<lambda>n. coeff p n = 0) at_top\"\n      by eventually_elim (simp add: coeff_eq_0)\n    thus \"eventually (\\<lambda>n. c n = 0) cofinite\"\n      by (simp add: c [symmetric] cofinite_eq_sequentially)\n  qed\n  have \"p = of_int_poly (Abs_poly c)\"\n    by (rule poly_eqI) (simp add: c)\n  thus ?thesis by (rule that)\nqed\n\n\nsubsection \\<open>General facts about polynomials\\<close>\n\nlemma pderiv_power:\n  \"pderiv (p ^ n) = smult (of_nat n) (p ^ (n - 1) * pderiv p)\"\n  by (cases n) (simp_all add: pderiv_power_Suc del: power_Suc)\n\nlemma degree_prod_sum_eq:\n  \"(\\<And>x. x \\<in> A \\<Longrightarrow> f x \\<noteq> 0) \\<Longrightarrow>\n     degree (prod f A :: 'a :: idom poly) = (\\<Sum>x\\<in>A. degree (f x))\"\n  by (induction A rule: infinite_finite_induct) (auto simp: degree_mult_eq)\n\nlemma pderiv_monom:\n  \"pderiv (monom c n) = monom (of_nat n * c) (n - 1)\"\n  by (cases n)\n     (simp_all add: monom_altdef pderiv_power_Suc pderiv_smult pderiv_pCons mult_ac del: power_Suc)\n\nlemma power_poly_const [simp]: \"[:c:] ^ n = [:c ^ n:]\"\n  by (induction n) (simp_all add: power_commutes)\n\nlemma monom_power: \"monom c n ^ k = monom (c ^ k) (n * k)\"\n  by (induction k) (simp_all add: mult_monom)\n\nlemma coeff_higher_pderiv:\n  \"coeff ((pderiv ^^ m) f) n = pochhammer (of_nat (Suc n)) m * coeff f (n + m)\"\n  by (induction m arbitrary: n) (simp_all add: coeff_pderiv pochhammer_rec algebra_simps)\n\nlemma higher_pderiv_add: \"(pderiv ^^ n) (p + q) = (pderiv ^^ n) p + (pderiv ^^ n) q\"\n  by (induction n arbitrary: p q) (simp_all del: funpow.simps add: funpow_Suc_right pderiv_add)\n\nlemma higher_pderiv_smult: \"(pderiv ^^ n) (smult c p) = smult c ((pderiv ^^ n) p)\"\n  by (induction n arbitrary: p) (simp_all del: funpow.simps add: funpow_Suc_right pderiv_smult)\n\nlemma higher_pderiv_0 [simp]: \"(pderiv ^^ n) 0 = 0\"\n  by (induction n) simp_all\n\nlemma higher_pderiv_monom:\n  \"m \\<le> n + 1 \\<Longrightarrow> (pderiv ^^ m) (monom c n) = monom (pochhammer (int n - int m + 1) m * c) (n - m)\"\nproof (induction m arbitrary: c n)\n  case (Suc m)\n  thus ?case\n    by (cases n)\n       (simp_all del: funpow.simps add: funpow_Suc_right pderiv_monom pochhammer_rec' Suc.IH)\nqed simp_all\n\nlemma higher_pderiv_monom_eq_zero:\n  \"m > n + 1 \\<Longrightarrow> (pderiv ^^ m) (monom c n) = 0\"\nproof (induction m arbitrary: c n)\n  case (Suc m)\n  thus ?case\n    by (cases n)\n       (simp_all del: funpow.simps add: funpow_Suc_right pderiv_monom pochhammer_rec' Suc.IH)\nqed simp_all\n\nlemma higher_pderiv_sum: \"(pderiv ^^ n) (sum f A) = (\\<Sum>x\\<in>A. (pderiv ^^ n) (f x))\"\n  by (induction A rule: infinite_finite_induct) (simp_all add: higher_pderiv_add)\n\nlemma fact_dvd_higher_pderiv:\n  \"[:fact n :: int:] dvd (pderiv ^^ n) p\"\nproof -\n  have \"[:fact n:] dvd (pderiv ^^ n) (monom c k)\" for c :: int and k :: nat\n    by (cases \"n \\<le> k + 1\")\n       (simp_all add: higher_pderiv_monom higher_pderiv_monom_eq_zero\n          fact_dvd_pochhammer const_poly_dvd_iff)\n  hence \"[:fact n:] dvd (pderiv ^^ n) (\\<Sum>k\\<le>degree p. monom (coeff p k) k)\"\n    by (simp_all add: higher_pderiv_sum dvd_sum)\n  thus ?thesis by (simp add: poly_as_sum_of_monoms)\nqed\n\nlemma fact_dvd_poly_higher_pderiv_aux:\n  \"(fact n :: int) dvd poly ((pderiv ^^ n) p) x\"\nproof -\n  have \"[:fact n:] dvd (pderiv ^^ n) p\" by (rule fact_dvd_higher_pderiv)\n  then obtain q where \"(pderiv ^^ n) p = [:fact n:] * q\" by (erule dvdE)\n  thus ?thesis by simp\nqed\n\nlemma fact_dvd_poly_higher_pderiv_aux':\n  \"m \\<le> n \\<Longrightarrow> (fact m :: int) dvd poly ((pderiv ^^ n) p) x\"\n  by (rule dvd_trans[OF fact_dvd fact_dvd_poly_higher_pderiv_aux]) simp_all\n\nlemma algebraicE':\n  assumes \"algebraic (x :: 'a :: field_char_0)\"\n  obtains p where \"p \\<noteq> 0\" \"poly (of_int_poly p) x = 0\"\nproof -\n  from assms obtain q where \"\\<And>i. coeff q i \\<in> \\<int>\" \"q \\<noteq> 0\" \"poly q x = 0\"\n    by (erule algebraicE)\n  moreover from this(1) obtain q' where \"q = of_int_poly q'\" by (erule int_polyE)\n  ultimately show ?thesis by (intro that[of q']) simp_all\nqed\n\nlemma algebraicE'_nonzero:\n  assumes \"algebraic (x :: 'a :: field_char_0)\" \"x \\<noteq> 0\"\n  obtains p where \"p \\<noteq> 0\" \"coeff p 0 \\<noteq> 0\" \"poly (of_int_poly p) x = 0\"\nproof -\n  from assms(1) obtain p where p: \"p \\<noteq> 0\" \"poly (of_int_poly p) x = 0\"\n    by (erule algebraicE')\n  define n :: nat where \"n = order 0 p\"\n  have \"monom 1 n dvd p\" by (simp add: monom_1_dvd_iff p n_def)\n  then obtain q where q: \"p = monom 1 n * q\" by (erule dvdE)\n  from p have \"q \\<noteq> 0\" \"poly (of_int_poly q) x = 0\" by (auto simp: q poly_monom assms(2))\n  moreover from this have \"order 0 p = n + order 0 q\" by (simp add: q order_mult)\n  hence \"order 0 q = 0\" by (simp add: n_def)\n  with \\<open>q \\<noteq> 0\\<close> have \"poly q 0 \\<noteq> 0\" by (simp add: order_root)\n  ultimately show ?thesis using that[of q] by (auto simp: poly_0_coeff_0)\nqed\n\nlemma algebraic_of_real_iff [simp]:\n   \"algebraic (of_real x :: 'a :: {real_algebra_1,field_char_0}) \\<longleftrightarrow> algebraic x\"\nproof\n  assume \"algebraic (of_real x :: 'a)\"\n  then obtain p where \"p \\<noteq> 0\" \"poly (of_int_poly p) (of_real x :: 'a) = 0\"\n    by (erule algebraicE')\n  hence \"(of_int_poly p :: real poly) \\<noteq> 0\"\n        \"poly (of_int_poly p :: real poly) x = 0\" by simp_all\n  thus \"algebraic x\" by (intro algebraicI[of \"of_int_poly p\"]) simp_all\nnext\n  assume \"algebraic x\"\n  then obtain p where \"p \\<noteq> 0\" \"poly (of_int_poly p) x = 0\" by (erule algebraicE')\n  hence \"of_int_poly p \\<noteq> (0 :: 'a poly)\" \"poly (of_int_poly p) (of_real x :: 'a) = 0\"\n    by simp_all\n  thus \"algebraic (of_real x)\" by (intro algebraicI[of \"of_int_poly p\"]) simp_all\nqed\n\n\nsubsection \\<open>Main proof\\<close>\n\nlemma lindemann_weierstrass_integral:\n  fixes u :: complex and f :: \"complex poly\"\n  defines \"df \\<equiv> \\<lambda>n. (pderiv ^^ n) f\"\n  defines \"m \\<equiv> degree f\"\n  defines \"I \\<equiv> \\<lambda>f u. exp u * (\\<Sum>j\\<le>degree f. poly ((pderiv ^^ j) f) 0) -\n                       (\\<Sum>j\\<le>degree f. poly ((pderiv ^^ j) f) u)\"\n  shows \"((\\<lambda>t. exp (u - t) * poly f t) has_contour_integral I f u) (linepath 0 u)\"\nproof -\n  note [derivative_intros] =\n    exp_scaleR_has_vector_derivative_right vector_diff_chain_within\n  let ?g = \"\\<lambda>t. 1 - t\" and ?f = \"\\<lambda>t. -exp (t *\\<^sub>R u)\"\n  have \"((\\<lambda>t. exp ((1 - t) *\\<^sub>R u) * u) has_integral\n          (?f \\<circ> ?g) 1 - (?f \\<circ> ?g) 0) {0..1}\"\n    by (rule fundamental_theorem_of_calculus)\n       (auto intro!: derivative_eq_intros simp del: o_apply)\n  hence aux_integral: \"((\\<lambda>t. exp (u - t *\\<^sub>R u) * u) has_integral exp u - 1) {0..1}\"\n    by (simp add: algebra_simps)\n\n  have \"((\\<lambda>t. exp (u - t *\\<^sub>R u) * u * poly f (t *\\<^sub>R u)) has_integral I f u) {0..1}\"\n    unfolding df_def m_def\n  proof (induction \"degree f\" arbitrary: f)\n    case 0\n    then obtain c where c: \"f = [:c:]\" by (auto elim: degree_eq_zeroE)\n    have \"((\\<lambda>t. c * (exp (u - t *\\<^sub>R u) * u)) has_integral c * (exp u - 1)) {0..1}\"\n      using aux_integral by (rule has_integral_mult_right)\n    with c show ?case by (simp add: algebra_simps I_def)\n  next\n    case (Suc m)\n    define df where \"df = (\\<lambda>j. (pderiv ^^ j) f)\"\n    show ?case\n    proof (rule integration_by_parts[OF bounded_bilinear_mult])\n      fix t :: real assume \"t \\<in> {0..1}\"\n      have \"((?f \\<circ> ?g) has_vector_derivative exp (u - t *\\<^sub>R u) * u) (at t)\"\n        by (auto intro!: derivative_eq_intros simp: algebra_simps simp del: o_apply)\n      thus \"((\\<lambda>t. -exp (u - t *\\<^sub>R u)) has_vector_derivative exp (u - t *\\<^sub>R u) * u) (at t)\"\n        by (simp add: algebra_simps o_def)\n    next\n      fix t :: real assume \"t \\<in> {0..1}\"\n      have \"(poly f \\<circ> (\\<lambda>t. t *\\<^sub>R u) has_vector_derivative u * poly (pderiv f) (t *\\<^sub>R u)) (at t)\"\n        by (rule field_vector_diff_chain_at) (auto intro!: derivative_eq_intros)\n      thus \"((\\<lambda>t. poly f (t *\\<^sub>R u)) has_vector_derivative u * poly (pderiv f) (t *\\<^sub>R u)) (at t)\"\n        by (simp add: o_def)\n    next\n      from Suc(2) have m: \"m = degree (pderiv f)\" by (simp add: degree_pderiv)\n      from Suc(1)[OF this] this\n        have \"((\\<lambda>t. exp (u - t *\\<^sub>R u) * u * poly (pderiv f) (t *\\<^sub>R u)) has_integral\n                exp u * (\\<Sum>j=0..m. poly (df (Suc j)) 0) - (\\<Sum>j=0..m. poly (df (Suc j)) u)) {0..1}\"\n        by (simp add: df_def funpow_swap1 atMost_atLeast0 I_def)\n      also have \"(\\<Sum>j=0..m. poly (df (Suc j)) 0) = (\\<Sum>j=Suc 0..Suc m. poly (df j) 0)\"\n        by (rule sum.shift_bounds_cl_Suc_ivl [symmetric])\n      also have \"\\<dots> = (\\<Sum>j=0..Suc m. poly (df j) 0) - poly f 0\"\n        by (subst (2) sum.atLeast_Suc_atMost) (simp_all add: df_def)\n      also have \"(\\<Sum>j=0..m. poly (df (Suc j)) u) = (\\<Sum>j=Suc 0..Suc m. poly (df j) u)\"\n        by (rule sum.shift_bounds_cl_Suc_ivl [symmetric])\n      also have \"\\<dots> = (\\<Sum>j=0..Suc m. poly (df j) u) - poly f u\"\n        by (subst (2) sum.atLeast_Suc_atMost) (simp_all add: df_def)\n      finally have \"((\\<lambda>t. - (exp (u - t *\\<^sub>R u) * u * poly (pderiv f) (t *\\<^sub>R u))) has_integral\n                        -(exp u * ((\\<Sum>j = 0..Suc m. poly (df j) 0) - poly f 0) -\n                                  ((\\<Sum>j = 0..Suc m. poly (df j) u) - poly f u))) {0..1}\"\n          (is \"(_ has_integral ?I) _\") by (rule has_integral_neg)\n      also have \"?I = - exp (u - 1 *\\<^sub>R u) * poly f (1 *\\<^sub>R u) -\n                       - exp (u - 0 *\\<^sub>R u) * poly f (0 *\\<^sub>R u) - I f u\"\n        by (simp add: df_def algebra_simps Suc(2) atMost_atLeast0 I_def)\n      finally show \"((\\<lambda>t. - exp (u - t *\\<^sub>R u) * (u * poly (pderiv f) (t *\\<^sub>R u)))\n                        has_integral \\<dots>) {0..1}\" by (simp add: algebra_simps)\n    qed (auto intro!: continuous_intros)\n  qed\n  thus ?thesis by (simp add: has_contour_integral_linepath algebra_simps)\nqed\n\nlocale lindemann_weierstrass_aux =\n  fixes f :: \"complex poly\"\nbegin\n\ndefinition I :: \"complex \\<Rightarrow> complex\" where\n  \"I u = exp u * (\\<Sum>j\\<le>degree f. poly ((pderiv ^^ j) f) 0) -\n                       (\\<Sum>j\\<le>degree f. poly ((pderiv ^^ j) f) u)\"\n\nlemma lindemann_weierstrass_integral_bound:\n  fixes u :: complex\n  assumes \"C \\<ge> 0\" \"\\<And>t. t \\<in> closed_segment 0 u \\<Longrightarrow> norm (poly f t) \\<le> C\"\n  shows \"norm (I u) \\<le> norm u * exp (norm u) * C\"\nproof -\n  have \"I u = contour_integral (linepath 0 u) (\\<lambda>t. exp (u - t) * poly f t)\"\n    using contour_integral_unique[OF lindemann_weierstrass_integral[of u f]] unfolding I_def ..\n  also have \"norm \\<dots> \\<le> exp (norm u) * C * norm (u - 0)\"\n  proof (intro contour_integral_bound_linepath)\n    fix t assume t: \"t \\<in> closed_segment 0 u\"\n    then obtain s where s: \"s \\<in> {0..1}\" \"t = s *\\<^sub>R u\" by (auto simp: closed_segment_def)\n    hence \"s * norm u \\<le> 1 * norm u\" by (intro mult_right_mono) simp_all\n    with s have norm_t: \"norm t \\<le> norm u\" by auto\n\n    from s have \"Re u - Re t = (1 - s) * Re u\" by (simp add: algebra_simps)\n    also have \"\\<dots> \\<le> norm u\"\n    proof (cases \"Re u \\<ge> 0\")\n      case True\n      with \\<open>s \\<in> {0..1}\\<close> have \"(1 - s) * Re u \\<le> 1 * Re u\" by (intro mult_right_mono) simp_all\n      also have \"Re u \\<le> norm u\" by (rule complex_Re_le_cmod)\n      finally show ?thesis by simp\n    next\n      case False\n      with \\<open>s \\<in> {0..1}\\<close> have \"(1 - s) * Re u \\<le> 0\" by (intro mult_nonneg_nonpos) simp_all\n      also have \"\\<dots> \\<le> norm u\" by simp\n      finally show ?thesis .\n    qed\n    finally have \"exp (Re u - Re t) \\<le> exp (norm u)\" by simp\n\n    hence \"exp (Re u - Re t) * norm (poly f t) \\<le> exp (norm u) * C\"\n      using assms t norm_t by (intro mult_mono) simp_all\n    thus \"norm (exp (u - t) * poly f t) \\<le> exp (norm u) * C\"\n      by (simp add: norm_mult exp_diff norm_divide field_simps)\n  qed (auto simp: intro!: mult_nonneg_nonneg contour_integrable_continuous_linepath\n                          continuous_intros assms)\n  finally show ?thesis by (simp add: mult_ac)\nqed\n\nend\n\nlemma poly_higher_pderiv_aux1:\n  fixes c :: \"'a :: idom\"\n  assumes \"k < n\"\n  shows   \"poly ((pderiv ^^ k) ([:-c, 1:] ^ n * p)) c = 0\"\n  using assms\nproof (induction k arbitrary: n p)\n  case (Suc k n p)\n  from Suc.prems obtain n' where n: \"n = Suc n'\" by (cases n) auto\n  from Suc.prems n have \"k < n'\" by simp\n  have \"(pderiv ^^ Suc k) ([:- c, 1:] ^ n * p) =\n          (pderiv ^^ k) ([:- c, 1:] ^ n * pderiv p + [:- c, 1:] ^ n' * smult (of_nat n) p)\"\n    by (simp only: funpow_Suc_right o_def pderiv_mult n pderiv_power_Suc,\n        simp only: n [symmetric]) (simp add: pderiv_pCons mult_ac)\n  also from Suc.prems \\<open>k < n'\\<close> have \"poly \\<dots> c = 0\"\n    by (simp add: higher_pderiv_add Suc.IH del: mult_smult_right)\n  finally show ?case .\nqed simp_all\n\nlemma poly_higher_pderiv_aux1':\n  fixes c :: \"'a :: idom\"\n  assumes \"k < n\" \"[:-c, 1:] ^ n dvd p\"\n  shows   \"poly ((pderiv ^^ k) p) c = 0\"\nproof -\n  from assms(2) obtain q where \"p = [:-c, 1:] ^ n * q\" by (elim dvdE)\n  also from assms(1) have \"poly ((pderiv ^^ k) \\<dots>) c = 0\"\n    by (rule poly_higher_pderiv_aux1)\n  finally show ?thesis .\nqed\n\nlemma poly_higher_pderiv_aux2:\n  fixes c :: \"'a :: {idom, semiring_char_0}\"\n  shows   \"poly ((pderiv ^^ n) ([:-c, 1:] ^ n * p)) c = fact n * poly p c\"\nproof (induction n arbitrary: p)\n  case (Suc n p)\n  have \"(pderiv ^^ Suc n) ([:- c, 1:] ^ Suc n * p) =\n          (pderiv ^^ n) ([:- c, 1:] ^ Suc n * pderiv p) +\n            (pderiv ^^ n) ([:- c, 1:] ^ n * smult (1 + of_nat n) p)\"\n    by (simp del: funpow.simps power_Suc add: funpow_Suc_right pderiv_mult\n          pderiv_power_Suc higher_pderiv_add pderiv_pCons mult_ac)\n  also have \"[:- c, 1:] ^ Suc n * pderiv p = [:- c, 1:] ^ n * ([:-c, 1:] * pderiv p)\"\n    by (simp add: algebra_simps)\n  finally show ?case by (simp add: Suc.IH del: mult_smult_right power_Suc)\nqed simp_all\n\nlemma poly_higher_pderiv_aux3:\n  fixes c :: \"'a :: {idom,semiring_char_0}\"\n  assumes \"k \\<ge> n\"\n  shows   \"\\<exists>q. poly ((pderiv ^^ k) ([:-c, 1:] ^ n * p)) c = fact n * poly q c\"\n  using assms\nproof (induction k arbitrary: n p)\n  case (Suc k n p)\n  show ?case\n  proof (cases n)\n    fix n' assume n: \"n = Suc n'\"\n    have \"poly ((pderiv ^^ Suc k) ([:-c, 1:] ^ n * p)) c =\n            poly ((pderiv ^^ k) ([:- c, 1:] ^ n * pderiv p)) c +\n              of_nat n * poly ((pderiv ^^ k) ([:-c, 1:] ^ n' * p)) c\"\n      by (simp del: funpow.simps power_Suc add: funpow_Suc_right pderiv_power_Suc\n            pderiv_mult n pderiv_pCons higher_pderiv_add mult_ac higher_pderiv_smult)\n    also have \"\\<exists>q1. poly ((pderiv ^^ k) ([:-c, 1:] ^ n * pderiv p)) c = fact n * poly q1 c\"\n      using Suc.prems Suc.IH[of n \"pderiv p\"]\n      by (cases \"n' = k\") (auto simp: n poly_higher_pderiv_aux1 simp del: power_Suc of_nat_Suc\n                                intro: exI[of _ \"0::'a poly\"])\n    then obtain q1\n      where \"poly ((pderiv ^^ k) ([:-c, 1:] ^ n * pderiv p)) c = fact n * poly q1 c\" ..\n    also from Suc.IH[of n' p] Suc.prems obtain q2\n      where \"poly ((pderiv ^^ k) ([:-c, 1:] ^ n' * p)) c = fact n' * poly q2 c\"\n      by (auto simp: n)\n    finally show ?case by (auto intro!: exI[of _ \"q1 + q2\"] simp: n algebra_simps)\n  qed auto\nqed auto\n\nlemma poly_higher_pderiv_aux3':\n  fixes c :: \"'a :: {idom, semiring_char_0}\"\n  assumes \"k \\<ge> n\" \"[:-c, 1:] ^ n dvd p\"\n  shows   \"fact n dvd poly ((pderiv ^^ k) p) c\"\nproof -\n  from assms(2) obtain q where \"p = [:-c, 1:] ^ n * q\" by (elim dvdE)\n  with poly_higher_pderiv_aux3[OF assms(1), of c q] show ?thesis by auto\nqed\n\nlemma e_transcendental_aux_bound:\n  obtains C where \"C \\<ge> 0\"\n    \"\\<And>x. x \\<in> closed_segment 0 (of_nat n) \\<Longrightarrow>\n        norm (\\<Prod>k\\<in>{1..n}. (x - of_nat k :: complex)) \\<le> C\"\nproof -\n  let ?f = \"\\<lambda>x. (\\<Prod>k\\<in>{1..n}. (x - of_nat k))\"\n  define C where \"C = max 0 (Sup (cmod ` ?f ` closed_segment 0 (of_nat n)))\"\n  have \"C \\<ge> 0\" by (simp add: C_def)\n  moreover {\n    fix x :: complex assume \"x \\<in> closed_segment 0 (of_nat n)\"\n    hence \"cmod (?f x) \\<le> Sup ((cmod \\<circ> ?f) ` closed_segment 0 (of_nat n))\"\n      by (intro cSup_upper bounded_imp_bdd_above compact_imp_bounded compact_continuous_image)\n         (auto intro!: continuous_intros)\n    also have \"\\<dots> \\<le> C\" by (simp add: C_def image_comp)\n    finally have \"cmod (?f x) \\<le> C\" .\n  }\n  ultimately show ?thesis by (rule that)\nqed\n\n\ntheorem e_transcendental_complex: \"\\<not> algebraic (exp 1 :: complex)\"\nproof\n  assume \"algebraic (exp 1 :: complex)\"\n  then obtain q :: \"int poly\"\n    where q: \"q \\<noteq> 0\" \"coeff q 0 \\<noteq> 0\" \"poly (of_int_poly q) (exp 1 :: complex) = 0\"\n      by (elim algebraicE'_nonzero) simp_all\n\n  define n :: nat where \"n = degree q\"\n  from q have [simp]: \"n \\<noteq> 0\" by (intro notI) (auto simp: n_def elim!: degree_eq_zeroE)\n  define qmax where \"qmax = Max (insert 0 (abs ` set (coeffs q)))\"\n  have qmax_nonneg [simp]: \"qmax \\<ge> 0\" by (simp add: qmax_def)\n  have qmax: \"\\<bar>coeff q k\\<bar> \\<le> qmax\" for k\n    by (cases \"k \\<le> degree q\")\n       (auto simp: qmax_def coeff_eq_0 coeffs_def simp del: upt_Suc intro: Max.coboundedI)\n  obtain C where C: \"C \\<ge> 0\"\n    \"\\<And>x. x \\<in> closed_segment 0 (of_nat n) \\<Longrightarrow> norm (\\<Prod>k\\<in>{1..n}. (x - of_nat k :: complex)) \\<le> C\"\n    by (erule e_transcendental_aux_bound)\n  define E where \"E = (1 + real n) * real_of_int qmax * real n * exp (real n) / real n\"\n  define F where \"F = real n * C\"\n\n  have ineq: \"fact (p - 1) \\<le> E * F ^ p\" if p: \"prime p\" \"p > n\" \"p > abs (coeff q 0)\" for p\n  proof -\n    from p(1) have p_pos: \"p > 0\" by (simp add: prime_gt_0_nat)\n    define f :: \"int poly\"\n      where \"f = monom 1 (p - 1) * (\\<Prod>k\\<in>{1..n}. [:-of_nat k, 1:] ^ p)\"\n    have poly_f: \"poly (of_int_poly f) x = x ^ (p - 1) * (\\<Prod>k\\<in>{1..n}. (x - of_nat k)) ^ p\"\n      for x :: complex by (simp add: f_def poly_prod poly_monom prod_power_distrib)\n    define m :: nat where \"m = degree f\"\n    from p_pos have m: \"m = (n + 1) * p - 1\"\n      by (simp add: m_def f_def degree_mult_eq degree_monom_eq degree_prod_sum_eq degree_linear_power)\n\n    define M :: int where \"M = (- 1) ^ (n * p) * fact n ^ p\"\n    with p have p_not_dvd_M: \"\\<not>int p dvd M\"\n      by (auto simp: M_def prime_elem_int_not_dvd_neg1_power prime_dvd_power_iff\n            prime_gt_0_nat prime_dvd_fact_iff_int prime_dvd_mult_iff)\n\n    interpret lindemann_weierstrass_aux \"of_int_poly f\" .\n    define J :: complex where \"J = (\\<Sum>k\\<le>n. of_int (coeff q k) * I (of_nat k))\"\n    define idxs where \"idxs = ({..n}\\<times>{..m}) - {(0, p - 1)}\"\n\n    hence \"J = (\\<Sum>k\\<le>n. of_int (coeff q k) * exp 1 ^ k) * (\\<Sum>n\\<le>m. of_int (poly ((pderiv ^^ n) f) 0)) -\n                 of_int (\\<Sum>k\\<le>n. \\<Sum>n\\<le>m. coeff q k * poly ((pderiv ^^ n) f) (int k))\"\n      by (simp add: J_def I_def algebra_simps sum_subtractf sum_distrib_left m_def\n                    exp_of_nat_mult [symmetric])\n    also have \"(\\<Sum>k\\<le>n. of_int (coeff q k) * exp 1 ^ k) = poly (of_int_poly q) (exp 1 :: complex)\"\n      by (simp add: poly_altdef n_def)\n    also have \"\\<dots> = 0\" by fact\n    finally have \"J = of_int (-(\\<Sum>(k,n)\\<in>{..n}\\<times>{..m}. coeff q k * poly ((pderiv ^^ n) f) (int k)))\"\n      by (simp add: sum.cartesian_product)\n    also have \"{..n}\\<times>{..m} = insert (0, p - 1) idxs\" by (auto simp: m idxs_def)\n    also have \"-(\\<Sum>(k,n)\\<in>\\<dots>. coeff q k * poly ((pderiv ^^ n) f) (int k)) =\n       - (coeff q 0 * poly ((pderiv ^^ (p - 1)) f) 0) -\n         (\\<Sum>(k, n)\\<in>idxs. coeff q k * poly ((pderiv ^^ n) f) (of_nat k))\"\n      by (subst sum.insert) (simp_all add: idxs_def)\n    also have \"coeff q 0 * poly ((pderiv ^^ (p - 1)) f) 0 = coeff q 0 * M * fact (p - 1)\"\n    proof -\n      have \"f = [:-0, 1:] ^ (p - 1) * (\\<Prod>k = 1..n. [:- of_nat k, 1:] ^ p)\"\n        by (simp add: f_def monom_altdef)\n      also have \"poly ((pderiv ^^ (p - 1)) \\<dots>) 0 =\n                   fact (p - 1) * poly (\\<Prod>k = 1..n. [:- of_nat k, 1:] ^ p) 0\"\n        by (rule poly_higher_pderiv_aux2)\n      also have \"poly (\\<Prod>k = 1..n. [:- of_nat k :: int, 1:] ^ p) 0 = (-1)^(n*p) * fact n ^ p\"\n        by (induction n) (simp_all add: prod.nat_ivl_Suc' power_mult_distrib mult_ac\n                            power_minus' power_add del: of_nat_Suc)\n      finally show ?thesis by (simp add: mult_ac M_def)\n    qed\n    also have \"\\<exists>N. (\\<Sum>(k, n)\\<in>idxs. coeff q k * poly ((pderiv ^^ n) f) (int k)) = fact p * N\"\n    proof -\n      have \"\\<forall>(k, n)\\<in>idxs. fact p dvd poly ((pderiv ^^ n) f) (of_nat k)\"\n      proof clarify\n        fix k j assume idxs: \"(k, j) \\<in> idxs\"\n        then consider \"k = 0\" \"j < p - 1\" | \"k = 0\" \"j > p - 1\" | \"k \\<noteq> 0\" \"j < p\" | \"k \\<noteq> 0\" \"j \\<ge> p\"\n          by (fastforce simp: idxs_def)\n        thus \"fact p dvd poly ((pderiv ^^ j) f) (of_nat k)\"\n        proof cases\n          case 1\n          thus ?thesis\n            by (simp add: f_def poly_higher_pderiv_aux1' monom_altdef)\n        next\n          case 2\n          thus ?thesis\n            by (simp add: f_def poly_higher_pderiv_aux3' monom_altdef fact_dvd_poly_higher_pderiv_aux')\n        next\n          case 3\n          thus ?thesis unfolding f_def\n            by (subst poly_higher_pderiv_aux1'[of _ p])\n               (insert idxs, auto simp: idxs_def intro!: dvd_mult)\n        next\n          case 4\n          thus ?thesis unfolding f_def\n            by (intro poly_higher_pderiv_aux3') (insert idxs, auto intro!: dvd_mult simp: idxs_def)\n        qed\n      qed\n      hence \"fact p dvd (\\<Sum>(k, n)\\<in>idxs. coeff q k * poly ((pderiv ^^ n) f) (int k))\"\n        by (auto intro!: dvd_sum dvd_mult simp del: of_int_fact)\n      thus ?thesis by (blast elim: dvdE)\n    qed\n    then guess N .. note N = this\n    also from p have \"- (coeff q 0 * M * fact (p - 1)) - fact p * N =\n                        - fact (p - 1) * (coeff q 0 * M + p * N)\"\n      by (subst fact_reduce[of p]) (simp_all add: algebra_simps)\n    finally have J: \"J = -of_int (fact (p - 1) * (coeff q 0 * M + p * N))\" by simp\n\n    from p q(2) have \"\\<not>p dvd coeff q 0 * M + p * N\"\n      by (auto simp: dvd_add_left_iff p_not_dvd_M prime_dvd_fact_iff_int prime_dvd_mult_iff\n               dest: dvd_imp_le_int)\n    hence \"coeff q 0 * M + p * N \\<noteq> 0\" by (intro notI) simp_all\n    hence \"abs (coeff q 0 * M + p * N) \\<ge> 1\" by simp\n    hence \"norm (of_int (coeff q 0 * M + p * N) :: complex) \\<ge> 1\" by (simp only: norm_of_int)\n    hence \"fact (p - 1) * \\<dots> \\<ge> fact (p - 1) * 1\" by (intro mult_left_mono) simp_all\n    hence J_lower: \"norm J \\<ge> fact (p - 1)\" unfolding J norm_minus_cancel of_int_mult of_int_fact\n      by (simp add: norm_mult)\n\n    have \"norm J \\<le> (\\<Sum>k\\<le>n. norm (of_int (coeff q k) * I (of_nat k)))\"\n      unfolding J_def by (rule norm_sum)\n    also have \"\\<dots> \\<le> (\\<Sum>k\\<le>n. of_int qmax * (real n * exp (real n) * real n ^ (p - 1) * C ^ p))\"\n    proof (intro sum_mono)\n      fix k assume k: \"k \\<in> {..n}\"\n      have \"n > 0\" by (rule ccontr) simp\n      {\n        fix x :: complex assume x: \"x \\<in> closed_segment 0 (of_nat k)\"\n        then obtain t where t: \"t \\<ge> 0\" \"t \\<le> 1\" \"x = of_real t * of_nat k\"\n          by (auto simp: closed_segment_def scaleR_conv_of_real)\n        hence \"norm x = t * real k\" by (simp add: norm_mult)\n        also from \\<open>t \\<le> 1\\<close> k have *: \"\\<dots> \\<le> 1 * real n\" by (intro mult_mono) simp_all\n        finally have x': \"norm x \\<le> real n\" by simp\n        from t \\<open>n > 0\\<close> * have x'': \"x \\<in> closed_segment 0 (of_nat n)\"\n          by (auto simp: closed_segment_def scaleR_conv_of_real field_simps\n                   intro!: exI[of _ \"t * real k / real n\"] )\n        have \"norm (poly (of_int_poly f) x) =\n                norm x ^ (p - 1) * cmod (\\<Prod>i = 1..n. x - i) ^ p\"\n          by (simp add: poly_f norm_mult norm_power)\n        also from x x' x'' have \"\\<dots> \\<le> of_nat n ^ (p - 1) * C ^ p\"\n          by (intro mult_mono C power_mono) simp_all\n        finally have \"norm (poly (of_int_poly f) x) \\<le> real n ^ (p - 1) * C ^ p\" .\n      } note A = this\n\n      have \"norm (I (of_nat k)) \\<le>\n                      cmod (of_nat k) * exp (cmod (of_nat k)) * (of_nat n ^ (p - 1) * C ^ p)\"\n        by (intro lindemann_weierstrass_integral_bound[OF _ A]\n              C mult_nonneg_nonneg zero_le_power) auto\n      also have \"\\<dots> \\<le> cmod (of_nat n) * exp (cmod (of_nat n)) * (of_nat n ^ (p - 1) * C ^ p)\"\n        using k by (intro mult_mono zero_le_power mult_nonneg_nonneg C) simp_all\n      finally show \"cmod (of_int (coeff q k) * I (of_nat k)) \\<le>\n                      of_int qmax * (real n * exp (real n) * real n ^ (p - 1) * C ^ p)\"\n        unfolding norm_mult\n        by (intro mult_mono) (simp_all add: qmax of_int_abs [symmetric] del: of_int_abs)\n    qed\n    also have \"\\<dots> = E * F ^ p\" using p_pos\n      by (simp add: power_diff power_mult_distrib E_def F_def)\n    finally show \"fact (p - 1) \\<le> E * F ^ p\" using J_lower by linarith\n  qed\n\n  have \"(\\<lambda>n. E * F * F ^ (n - 1) / fact (n - 1)) \\<longlonglongrightarrow> 0\" (is ?P)\n    by (intro filterlim_compose[OF power_over_fact_tendsto_0' filterlim_minus_nat_at_top])\n  also have \"?P \\<longleftrightarrow> (\\<lambda>n. E * F ^ n / fact (n - 1)) \\<longlonglongrightarrow> 0\"\n    by (intro filterlim_cong refl eventually_mono[OF eventually_gt_at_top[of \"0::nat\"]])\n       (auto simp: power_Suc [symmetric] simp del: power_Suc)\n  finally have \"eventually (\\<lambda>n. E * F ^ n / fact (n - 1) < 1) at_top\"\n    by (rule order_tendstoD) simp_all\n  hence \"eventually (\\<lambda>n. E * F ^ n < fact (n - 1)) at_top\" by eventually_elim simp\n  then obtain P where P: \"\\<And>n. n \\<ge> P \\<Longrightarrow> E * F ^ n < fact (n - 1)\"\n    by (auto simp: eventually_at_top_linorder)\n\n  have \"\\<exists>p. prime p \\<and> p > Max {nat (abs (coeff q 0)), n, P}\" by (rule bigger_prime)\n  then obtain p where \"prime p\" \"p > Max {nat (abs (coeff q 0)), n, P}\" by blast\n  hence \"int p > abs (coeff q 0)\" \"p > n\" \"p \\<ge> P\" by auto\n  with ineq[of p] \\<open>prime p\\<close> have \"fact (p - 1) \\<le> E * F ^ p\" by simp\n  moreover from \\<open>p \\<ge> P\\<close> have \"fact (p - 1) > E * F ^ p\" by (rule P)\n  ultimately show False by linarith\nqed\n\ncorollary e_transcendental_real: \"\\<not> algebraic (exp 1 :: real)\"\nproof -\n  have \"\\<not>algebraic (exp 1 :: complex)\" by (rule e_transcendental_complex)\n  also have \"(exp 1 :: complex) = of_real (exp 1)\" using exp_of_real[of 1] by simp\n  also have \"algebraic \\<dots> \\<longleftrightarrow> algebraic (exp 1 :: real)\" by simp\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/E_Transcendental/E_Transcendental.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357563664174, "lm_q2_score": 0.8459424411924673, "lm_q1q2_score": 0.7334623443417645}}
{"text": "(*\n    File:      Multiplicative_Characters.thy\n    Author:    Manuel Eberl, TU M\u00fcnchen; Joseph Thommes, TU M\u00fcnchen\n*)\nsection \\<open>Multiplicative Characters of Finite Abelian Groups\\<close>\ntheory Multiplicative_Characters\n  imports\n  Complex_Main\n  \"Finitely_Generated_Abelian_Groups.Finitely_Generated_Abelian_Groups\"\nbegin\n\nnotation integer_mod_group (\"Z\")\n\nsubsection \\<open>Definition of characters\\<close>\n\ntext \\<open>\n  A (multiplicative) character is a completely multiplicative function from a group to the\n  complex numbers. For simplicity, we restrict this to finite abelian groups here, which is\n  the most interesting case.\n\n  Characters form a group where the identity is the \\emph{principal} character that maps all\n  elements to $1$, multiplication is point-wise multiplication of the characters, and the inverse\n  is the point-wise complex conjugate.\n\n  This group is often called the \\emph{Pontryagin dual} group and is isomorphic to the original\n  group (in a non-natural way) while the double-dual group \\<^emph>\\<open>is\\<close> naturally isomorphic to the\n  original group.\n\n  To get extensionality of the characters, we also require characters to map anything that is\n  not in the group to $0$.\n\\<close>\n\ndefinition principal_char :: \"('a, 'b) monoid_scheme \\<Rightarrow> 'a \\<Rightarrow> complex\" where\n  \"principal_char G a = (if a \\<in> carrier G then 1 else 0)\"\n\ndefinition inv_character where\n  \"inv_character \\<chi> = (\\<lambda>a. cnj (\\<chi> a))\"\n\nlemma inv_character_principal [simp]: \"inv_character (principal_char G) = principal_char G\"\n  by (simp add: inv_character_def principal_char_def fun_eq_iff)\n\nlemma inv_character_inv_character [simp]: \"inv_character (inv_character \\<chi>) = \\<chi>\"\n  by (simp add: inv_character_def)\n\nlemma eval_inv_character: \"inv_character \\<chi> j = cnj (\\<chi> j)\"\n  by (simp add: inv_character_def)\n\n\nbundle character_syntax\nbegin\nnotation principal_char (\"\\<chi>\\<^sub>0\\<index>\")\nend\n\nlocale character = finite_comm_group +\n  fixes \\<chi> :: \"'a \\<Rightarrow> complex\"\n  assumes char_one_nz: \"\\<chi> \\<one> \\<noteq> 0\"\n  assumes char_eq_0:   \"a \\<notin> carrier G \\<Longrightarrow> \\<chi> a = 0\"\n  assumes char_mult [simp]: \"a \\<in> carrier G \\<Longrightarrow> b \\<in> carrier G \\<Longrightarrow> \\<chi> (a \\<otimes> b) = \\<chi> a * \\<chi> b\"\nbegin\n\n\nsubsection \\<open>Basic properties\\<close>\n\nlemma char_one [simp]: \"\\<chi> \\<one> = 1\"\nproof-\n  from char_mult[of \\<one> \\<one>] have \"\\<chi> \\<one> * (\\<chi> \\<one> - 1) = 0\"\n    by (auto simp del: char_mult)\n  with char_one_nz show ?thesis by simp\nqed\n\nlemma char_power [simp]: \"a \\<in> carrier G \\<Longrightarrow> \\<chi> (a [^] k) = \\<chi> a ^ k\"\n  by (induction k) auto\n\nlemma char_root:\n  assumes \"a \\<in> carrier G\"\n  shows   \"\\<chi> a ^ ord a = 1\"\nproof -\n  from assms have \"\\<chi> a ^ ord a = \\<chi> (a [^] ord a)\"\n    by (subst char_power) auto\n  also from fin and assms have \"a [^] ord a = \\<one>\" by (intro pow_ord_eq_1) auto\n  finally show ?thesis by simp\nqed\n\nlemma char_root':\n  assumes \"a \\<in> carrier G\"\n  shows   \"\\<chi> a ^ order G = 1\"\nproof -\n  from assms have \"\\<chi> a ^ order G = \\<chi> (a [^] order G)\" by simp\n  also from fin and assms have \"a [^] order G = \\<one>\" by (intro pow_order_eq_1) auto\n  finally show ?thesis by simp\nqed\n\nlemma norm_char: \"norm (\\<chi> a) = (if a \\<in> carrier G then 1 else 0)\"\nproof (cases \"a \\<in> carrier G\")\n  case True\n  have \"norm (\\<chi> a) ^ order G = norm (\\<chi> a ^ order G)\" by (simp add: norm_power)\n  also from True have \"\\<chi> a ^ order G = 1\" by (rule char_root')\n  finally have \"norm (\\<chi> a) ^ order G = 1 ^ order G\" by simp\n  hence \"norm (\\<chi> a) = 1\" by (subst (asm) power_eq_iff_eq_base) auto\n  with True show ?thesis by auto\nnext\n  case False\n  thus ?thesis by (auto simp: char_eq_0)\nqed\n\nlemma char_eq_0_iff: \"\\<chi> a = 0 \\<longleftrightarrow> a \\<notin> carrier G\"\nproof -\n  have \"\\<chi> a = 0 \\<longleftrightarrow> norm (\\<chi> a) = 0\" by simp\n  also have \"\\<dots> \\<longleftrightarrow> a \\<notin> carrier G\" by (subst norm_char) auto\n  finally show ?thesis .\nqed\n\nlemma inv_character: \"character G (inv_character \\<chi>)\"\n  by standard (auto simp: inv_character_def char_eq_0)\n\nlemma mult_inv_character: \"\\<chi> k * inv_character \\<chi> k = principal_char G k\"\nproof -\n  have \"\\<chi> k * inv_character \\<chi> k = of_real (norm (\\<chi> k) ^ 2)\"\n    by (subst complex_norm_square) (simp add: inv_character_def)\n  also have \"\\<dots> = principal_char G k\"\n    by (simp add: principal_char_def norm_char)\n  finally show ?thesis .\nqed\n\nlemma\n  assumes \"a \\<in> carrier G\"\n  shows    char_inv: \"\\<chi> (inv a) = cnj (\\<chi> a)\" and char_inv': \"\\<chi> (inv a) = inverse (\\<chi> a)\"\nproof -\n  from assms have \"inv a \\<otimes> a = \\<one>\" by simp\n  also have \"\\<chi> \\<dots> = 1\" by simp\n  also from assms have \"\\<chi> (inv a \\<otimes> a) = \\<chi> (inv a) * \\<chi> a\"\n    by (intro char_mult) auto\n  finally have *: \"\\<chi> (inv a) * \\<chi> a = 1\" .\n  thus \"\\<chi> (inv a) = inverse (\\<chi> a)\" by (auto simp: divide_simps)\n  also from mult_inv_character[of a] and assms have \"inverse (\\<chi> a) = cnj (\\<chi> a)\"\n    by (auto simp add: inv_character_def principal_char_def divide_simps mult.commute)\n  finally show \"\\<chi> (inv a) = cnj (\\<chi> a)\" .\nqed\n\nend\n\nlemma (in finite_comm_group) character_principal [simp, intro]: \"character G (principal_char G)\"\n  by standard (auto simp: principal_char_def)\n\nlemmas [simp,intro] = finite_comm_group.character_principal\n\nlemma character_ext:\n  assumes \"character G \\<chi>\" \"character G \\<chi>'\" \"\\<And>x. x \\<in> carrier G \\<Longrightarrow> \\<chi> x = \\<chi>' x\"\n  shows   \"\\<chi> = \\<chi>'\"\nproof\n  fix x :: 'a\n  show \"\\<chi> x = \\<chi>' x\"\n    using assms by (cases \"x \\<in> carrier G\") (auto simp: character.char_eq_0)\nqed\n\nlemma character_mult [intro]: \n  assumes \"character G \\<chi>\" \"character G \\<chi>'\"\n  shows   \"character G (\\<lambda>x. \\<chi> x * \\<chi>' x)\"\nproof -\n  interpret \\<chi>: character G \\<chi> by fact\n  interpret \\<chi>': character G \\<chi>' by fact\n  show ?thesis by standard (auto simp: \\<chi>.char_eq_0)\nqed\n \n\nlemma character_inv_character_iff [simp]: \"character G (inv_character \\<chi>) \\<longleftrightarrow> character G \\<chi>\"\nproof\n  assume \"character G (inv_character \\<chi>)\"\n  from character.inv_character [OF this] show \"character G \\<chi>\" by simp\nqed (auto simp: character.inv_character)\n\n\ndefinition characters :: \"('a, 'b) monoid_scheme \\<Rightarrow> ('a \\<Rightarrow> complex) set\"  where\n  \"characters G = {\\<chi>. character G \\<chi>}\"\n\n\nsubsection \\<open>The Character group\\<close>\n\ntext \\<open>\n  The characters of a finite abelian group $G$ form another group $\\widehat{G}$, which is called\n  its Pontryagin dual group. This generalises to the more general setting of locally compact\n  abelian groups, but we restrict ourselves to the finite setting because it is much easier.\n\\<close>\ndefinition Characters :: \"('a, 'b) monoid_scheme \\<Rightarrow> ('a \\<Rightarrow> complex) monoid\"\n  where \"Characters G = \\<lparr> carrier = characters G, monoid.mult = (\\<lambda>\\<chi>\\<^sub>1 \\<chi>\\<^sub>2 k. \\<chi>\\<^sub>1 k * \\<chi>\\<^sub>2 k),\n                          one = principal_char G \\<rparr>\"\n\nlemma carrier_Characters: \"carrier (Characters G) = characters G\"\n  by (simp add: Characters_def)\n\nlemma one_Characters: \"one (Characters G) = principal_char G\"\n  by (simp add: Characters_def)\n\nlemma mult_Characters: \"monoid.mult (Characters G) \\<chi>\\<^sub>1 \\<chi>\\<^sub>2 = (\\<lambda>a. \\<chi>\\<^sub>1 a * \\<chi>\\<^sub>2 a)\"\n  by (simp add: Characters_def)\n\ncontext finite_comm_group\nbegin\n\nsublocale principal: character G \"principal_char G\" ..\n\nlemma finite_characters [intro]: \"finite (characters G)\"\nproof (rule finite_subset)\n  show \"characters G \\<subseteq> (\\<lambda>f x. if x \\<in> carrier G then f x else 0) ` \n                          Pi\\<^sub>E (carrier G) (\\<lambda>_. {z. z ^ order G = 1})\" (is \"_ \\<subseteq> ?h ` ?Chars\")\n  proof (intro subsetI, goal_cases)\n    case (1 \\<chi>)\n    then interpret \\<chi>: character G \\<chi> by (simp add: characters_def)\n    have \"?h (restrict \\<chi> (carrier G)) \\<in> ?h ` ?Chars\"\n      by (intro imageI) (auto simp: \\<chi>.char_root')\n    also have \"?h (restrict \\<chi> (carrier G)) = \\<chi>\" by (simp add: fun_eq_iff \\<chi>.char_eq_0)\n    finally show ?case .\n  qed\n  show \"finite (?h ` ?Chars)\"\n    by (intro finite_imageI finite_PiE finite_roots_unity) (auto simp: Suc_le_eq)\nqed\n\nlemma finite_comm_group_Characters [intro]: \"finite_comm_group (Characters G)\"\nproof\n  fix \\<chi> \\<chi>' assume *: \"\\<chi> \\<in> carrier (Characters G)\" \"\\<chi>' \\<in> carrier (Characters G)\"\n  from * interpret \\<chi>: character G \\<chi> by (simp_all add: characters_def carrier_Characters)\n  from * interpret \\<chi>': character G \\<chi>' by (simp_all add: characters_def  carrier_Characters)\n  have \"character G (\\<lambda>k. \\<chi> k * \\<chi>' k)\"\n    by standard (insert *, simp_all add: \\<chi>.char_eq_0 one_Characters \n                                         mult_Characters characters_def  carrier_Characters)\n  thus \"\\<chi> \\<otimes>\\<^bsub>Characters G\\<^esub> \\<chi>' \\<in> carrier (Characters G)\"\n    by (simp add: characters_def one_Characters mult_Characters  carrier_Characters)\nnext\n  have \"character G (principal_char G)\" ..\n  thus \"\\<one>\\<^bsub>Characters G\\<^esub> \\<in> carrier (Characters G)\"\n    by (simp add: characters_def one_Characters mult_Characters  carrier_Characters)\nnext\n  fix \\<chi> assume *: \"\\<chi> \\<in> carrier (Characters G)\"\n  from * interpret \\<chi>: character G \\<chi> by (simp_all add: characters_def carrier_Characters)\n  show \"\\<one>\\<^bsub>Characters G\\<^esub> \\<otimes>\\<^bsub>Characters G\\<^esub> \\<chi> = \\<chi>\" and \"\\<chi> \\<otimes>\\<^bsub>Characters G\\<^esub> \\<one>\\<^bsub>Characters G\\<^esub> = \\<chi>\"\n    by (simp_all add: principal_char_def fun_eq_iff \\<chi>.char_eq_0 one_Characters mult_Characters)\nnext\n  have \"\\<chi> \\<in> Units (Characters G)\" if \"\\<chi> \\<in> carrier (Characters G)\" for \\<chi>\n  proof -\n    from that interpret \\<chi>: character G \\<chi> by (simp add: characters_def carrier_Characters)\n    have \"\\<chi> \\<otimes>\\<^bsub>Characters G\\<^esub> inv_character \\<chi> = \\<one>\\<^bsub>Characters G\\<^esub>\" and \n         \"inv_character \\<chi> \\<otimes>\\<^bsub>Characters G\\<^esub> \\<chi> = \\<one>\\<^bsub>Characters G\\<^esub>\"\n      by (simp_all add: \\<chi>.mult_inv_character mult_ac one_Characters mult_Characters)\n    moreover from that have \"inv_character \\<chi> \\<in> carrier (Characters G)\"\n      by (simp add: characters_def carrier_Characters)\n    ultimately show ?thesis using that unfolding Units_def by blast\n  qed\n  thus \"carrier (Characters G) \\<subseteq> Units (Characters G)\" ..\nqed (auto simp: principal_char_def one_Characters mult_Characters carrier_Characters)\n\nend\n\nlemma (in character) character_in_order_1:\n  assumes \"order G = 1\"\n  shows   \"\\<chi> = principal_char G\"\nproof -\n  from assms have \"card (carrier G - {\\<one>}) = 0\"\n    by (subst card_Diff_subset) (auto simp: order_def)\n  hence \"carrier G - {\\<one>} = {}\"\n    by (subst (asm) card_0_eq) auto\n  hence \"carrier G = {\\<one>}\" by auto\n  thus ?thesis\n    by (intro ext) (simp_all add: principal_char_def char_eq_0)\nqed\n\nlemma (in finite_comm_group) characters_in_order_1:\n  assumes \"order G = 1\"\n  shows   \"characters G = {principal_char G}\"\n  using character.character_in_order_1 [OF _ assms] by (auto simp: characters_def)\n\nlemma (in character) inv_Characters: \"inv\\<^bsub>Characters G\\<^esub> \\<chi> = inv_character \\<chi>\"\nproof -\n  interpret Characters: finite_comm_group \"Characters G\" ..\n  have \"character G \\<chi>\" ..\n  thus ?thesis\n    by (intro Characters.inv_equality) \n       (auto simp: characters_def mult_inv_character mult_ac \n                   carrier_Characters one_Characters mult_Characters)\nqed\n\nlemma (in finite_comm_group) inv_Characters': \n  \"\\<chi> \\<in> characters G \\<Longrightarrow> inv\\<^bsub>Characters G\\<^esub> \\<chi> = inv_character \\<chi>\"\n  by (intro character.inv_Characters) (auto simp: characters_def)\n\nlemmas (in finite_comm_group) Characters_simps = \n  carrier_Characters mult_Characters one_Characters inv_Characters'\n\nlemma inv_Characters': \"\\<chi> \\<in> characters G \\<Longrightarrow> inv\\<^bsub>Characters G\\<^esub> \\<chi> = inv_character \\<chi>\"\n  using character.inv_Characters[of G \\<chi>] by (simp add: characters_def)\n\nsubsection \\<open>The isomorphism between a group and its dual\\<close>\n\ntext \\<open>We start this section by inspecting the special case of a cyclic group. Here, any character\nis fixed by the value it assigns to the generating element of the cyclic group. This can then be\nused to construct a bijection between the nth unit roots and the elements of the character group -\nimplying the other results.\\<close>\n\nlemma (in finite_cyclic_group)\n  defines ic: \"induce_char \\<equiv> (\\<lambda>c::complex. (\\<lambda>a. if a\\<in>carrier G then c powi get_exp gen a else 0))\"\n  shows order_Characters: \"order (Characters G) = order G\"\n  and   gen_fixes_char: \"\\<lbrakk>character G a; character G b; a gen = b gen\\<rbrakk> \\<Longrightarrow> a = b\"\n  and   unity_root_induce_char: \"z ^ order G = 1 \\<Longrightarrow> character G (induce_char z)\"\nproof -\n  interpret C: finite_comm_group \"Characters G\" using finite_comm_group_Characters . \n  define n where \"n = order G\"\n  hence n: \"n > 0\" using order_gt_0 by presburger\n  from n_def have nog: \"n = ord gen\" using ord_gen_is_group_order by simp\n  have xnz: \"x \\<noteq> 0\" if \"x ^ n = 1\" for x::complex using n(1) that by (metis zero_neq_one zero_power)\n  have m: \"x powi m = x powi (m mod n)\" if \"x ^ n = 1\" for x::complex and m::int\n    using powi_mod[OF that n] .\n  show cf: \"character G (induce_char x)\" if x: \"x ^ n = 1\" for x\n  proof\n    show \"induce_char x \\<one> \\<noteq> 0\" using xnz[OF that] unfolding ic by auto\n    show \"induce_char x a = 0\" if \"a \\<notin> carrier G\" for a using that unfolding ic by simp\n    show \"induce_char x (a \\<otimes> b) = induce_char x a * induce_char x b\"\n      if \"a \\<in> carrier G\" \"b \\<in> carrier G\" for a b\n    proof -\n      have \"x powi get_exp gen (a \\<otimes> b) = x powi get_exp gen a * x powi get_exp gen b\"\n      proof -\n        have \"x powi get_exp gen (a \\<otimes> b) = x powi ((get_exp gen a + get_exp gen b) mod n)\"\n          using m[OF x] get_exp_mult_mod[OF that] n_def ord_gen_is_group_order by metis\n        also have \"\\<dots> = x powi (get_exp gen a + get_exp gen b)\" using m[OF x] by presburger\n        finally show ?thesis by (simp add: power_int_add xnz[OF x])\n      qed\n      thus ?thesis using that unfolding ic by simp\n    qed\n  qed\n  define get_c where gc: \"get_c = (\\<lambda>c::'a \\<Rightarrow> complex. c gen)\"\n  have biji: \"bij_betw induce_char {z. z ^ n = 1} (characters G)\"\n   and bijg: \"bij_betw get_c (characters G) {z. z ^ n = 1}\"\n  proof (intro bij_betwI[of _ _ _ get_c])\n    show iin: \"induce_char \\<in> {z. z ^ n = 1} \\<rightarrow> characters G\" using cf unfolding characters_def\n      by blast\n    show gi: \"get_c (induce_char x) = x\" if \"x \\<in> {z. z ^ n = 1}\" for x\n    proof (cases \"n = 1\")\n      case True\n      with that have \"x = 1\" by force\n      thus ?thesis unfolding ic gc by simp\n    next\n      case False\n      have x: \"x ^ n = 1\" using that by blast\n      have \"x powi get_exp gen gen = x\"\n      proof -\n        have \"x powi get_exp gen gen = x powi (get_exp gen gen mod n)\" using m[OF x] by blast\n        moreover have \"(get_exp gen gen mod n) = 1\"\n        proof -\n          have \"1 = 1 mod int n\" using False n by auto\n          also have \"\\<dots> = get_exp gen gen mod n\"\n            by (unfold nog, intro pow_eq_int_mod[OF gen_closed],\n                use get_exp_fulfills[OF gen_closed] in auto)\n          finally show ?thesis by argo\n        qed\n        ultimately show \"x powi get_exp gen gen = x\" by simp\n      qed\n      thus ?thesis unfolding ic gc by simp\n    qed\n    show gin: \"get_c \\<in> characters G \\<rightarrow> {z. z ^ n = 1}\"\n    proof -\n      have \"False\" if \"get_c c ^ n \\<noteq> 1\" \"character G c\" for c\n      proof -\n        interpret character G c by fact\n        show False using that(1)[unfolded gc] by (simp add: char_root' n_def)\n      qed\n      thus ?thesis unfolding characters_def by blast\n    qed\n    show ig: \"induce_char (get_c y) = y\" if y: \"y \\<in> characters G\" for y\n    proof (cases \"n = 1\")\n      case True\n      hence \"y = principal_char G\" using y n_def character.character_in_order_1 characters_def\n        by auto\n      thus ?thesis unfolding ic gc principal_char_def by force\n    next\n      case False\n      have yc: \"y \\<in> carrier (Characters G)\" using y[unfolded carrier_Characters[symmetric]] .\n      interpret character G y using that unfolding characters_def by simp\n      have ygo: \"y gen ^ n = 1\" using char_root'[OF gen_closed] n_def by blast\n      have \"y gen powi get_exp gen a = y a\" if \"a \\<in> carrier G\" for a using that\n      proof(induction rule: generator_induct1)\n        case gen\n        have \"y gen powi get_exp gen gen = y gen powi (get_exp gen gen mod n)\"\n          using m[OF ygo] by blast\n        also have \"\\<dots> = y gen powi ((1::int) mod n)\"\n          using get_exp_self[OF gen_closed] nog by argo\n        also have \"\\<dots> = y gen powi 1\" using False n by simp\n        finally have yg: \"y gen powi get_exp gen gen = y gen\" by simp\n        thus ?case .\n        case (step x)\n        have \"y gen powi get_exp gen (x \\<otimes> gen) = y gen powi (get_exp gen (x \\<otimes> gen) mod n)\"\n          using m[OF ygo] by blast\n        also have \"\\<dots> = y gen powi ((get_exp gen x + get_exp gen gen) mod n)\"\n          using get_exp_mult_mod[OF step(1) gen_closed, unfolded nog[symmetric]] by argo\n        also have \"\\<dots> = y gen powi (get_exp gen x + get_exp gen gen)\" using m[OF ygo] by presburger\n        also have \"\\<dots> = y gen powi get_exp gen x * y gen powi get_exp gen gen\"\n          by (simp add: char_eq_0_iff power_int_add)\n        also have \"\\<dots> = y x * y gen\" using yg step(2) by argo\n        also have \"\\<dots> = y (x \\<otimes> gen)\" using step(1) by simp\n        finally show ?case .\n      qed\n      thus \"induce_char (get_c y) = y\" unfolding ic gc using char_eq_0 by auto\n    qed\n    show \"bij_betw get_c (characters G) {z. z ^ n = 1}\" using ig gi iin gin\n      by (auto intro: bij_betwI)\n  qed\n  with card_roots_unity_eq[OF n] n_def show \"order (Characters G) = order G\" unfolding order_def\n    by (metis bij_betw_same_card carrier_Characters)\n  assume assm: \"character G a\" \"character G b\" \"a gen = b gen\"\n  with bijg[unfolded gc characters_def bij_betw_def inj_on_def] show \"a = b\" by auto\nqed\n\ntext \\<open>Moreover, we can show that a character that assigns a \"true\" root of unity to the\ngenerating element of the group, generates the character group.\\<close>\n\nlemma (in finite_cyclic_group) finite_cyclic_group_Characters:\n  obtains \\<chi> where \"finite_cyclic_group (Characters G) \\<chi>\"\nproof -\n  interpret C: finite_comm_group \"Characters G\" by (rule finite_comm_group_Characters)\n  define n where n: \"n = order G\"\n  hence nnz: \"n \\<noteq> 0\" by blast\n  from n have nog: \"n = ord gen\" using ord_gen_is_group_order by simp\n  obtain x::complex where x: \"x ^ n = 1\" \"\\<And>m. \\<lbrakk>0<m; m<n\\<rbrakk> \\<Longrightarrow> x ^ m \\<noteq> 1\"\n    using true_nth_unity_root by blast\n  have xnz: \"x \\<noteq> 0\" using x n by (metis order_gt_0 zero_neq_one zero_power)\n  have m: \"x powi m = x powi (m mod n)\" for m::int\n    using powi_mod[OF x(1)] nnz by blast\n  let ?f = \"(\\<lambda>a. if a \\<in> carrier G then x powi (get_exp gen a) else 0)\"\n  have cf: \"character G ?f\" using unity_root_induce_char[OF x(1)[unfolded n]] .\n  have fpow: \"(?f [^]\\<^bsub>Characters G\\<^esub> m) a = x powi ((get_exp gen a) * m)\"\n    if \"a \\<in> carrier G\" for a::'a and m::nat\n    using that\n  proof(unfold Characters_def principal_char_def, induction m)\n    case s: (Suc m)\n    have \"x powi (get_exp gen a * int m) * x powi get_exp gen a\n        = x powi (get_exp gen a * (1 + int m))\"\n    proof -\n      fix ma :: nat\n      have \"x powi ((1 + int ma) * get_exp gen a)\n          = x powi (get_exp gen a + int ma * get_exp gen a) \\<and> 0 \\<noteq> x\"\n        by (simp add: comm_semiring_class.distrib xnz)\n      then show \"x powi (get_exp gen a * int ma) * x powi get_exp gen a\n               = x powi (get_exp gen a * (1 + int ma))\"\n        by (simp add: mult.commute power_int_add)\n    qed\n    thus ?case using s by simp\n  qed simp\n  interpret cyclic_group \"Characters G\" ?f\n  proof (intro C.element_ord_generates_cyclic)\n    show fc: \"?f \\<in> carrier (Characters G)\" using cf carrier_Characters[of G] characters_def by fast\n    from x nnz have fno: \"?f [^]\\<^bsub>Characters G\\<^esub> m \\<noteq> \\<one>\\<^bsub>Characters G\\<^esub>\" if \"0 < m\" \"m < n\" for m\n    proof (cases \"n = 1\")\n      case False\n      have \"\\<one>\\<^bsub>Characters G\\<^esub> gen = 1\" unfolding Characters_def principal_char_def using that by simp\n      moreover have \"(?f [^]\\<^bsub>Characters G\\<^esub> m) gen \\<noteq> 1\"\n      proof -\n        have \"(?f [^]\\<^bsub>Characters G\\<^esub> m) gen = x powi ((get_exp gen gen) * m)\" using fpow by blast\n        also have \"\\<dots> = (x powi (get_exp gen gen)) ^ m\" by (simp add: power_int_mult)\n        also have \"\\<dots> = x ^ m\"\n        proof -\n          have \"x powi (get_exp gen gen) = x powi ((get_exp gen gen) mod n)\" using m by blast\n          moreover have \"((get_exp gen gen) mod n) = 1\"\n          proof -\n            have \"1 = 1 mod int n\" using False nnz by simp\n            also have \"\\<dots> = get_exp gen gen mod n\"\n              by (unfold nog, intro pow_eq_int_mod[OF gen_closed],\n                  use get_exp_fulfills[OF gen_closed] in auto)\n            finally show ?thesis by argo\n          qed\n          ultimately have \"x powi (get_exp gen gen) = x\" by simp\n          thus ?thesis by simp\n        qed\n        finally show ?thesis using x(2)[OF that] by argo\n      qed\n      ultimately show ?thesis by fastforce\n    qed (use that in blast)\n    have \"C.ord ?f = n\"\n    proof -\n      from nnz have \"C.ord ?f \\<le> n\" unfolding n\n        using C.ord_dvd_group_order[OF fc] order_Characters dvd_nat_bounds by auto\n      with C.ord_conv_Least[OF fc] C.pow_order_eq_1[OF fc] n nnz show \"C.ord ?f = n\"\n        by (metis (no_types, lifting) C.ord_pos C.pow_ord_eq_1 fc fno le_neq_implies_less)\n    qed\n    thus \"C.ord ?f = order (Characters G)\" using n order_Characters by argo\n  qed\n  have \"finite_cyclic_group (Characters G) ?f\" by unfold_locales\n  with that show ?thesis by blast\nqed\n\ntext \\<open>And as two cyclic groups of the same order are isomorphic it follows the isomorphism of a\nfinite cyclic group and its dual.\\<close>\n\nlemma (in finite_cyclic_group) Characters_iso:\n  \"G \\<cong> Characters G\"\nproof -\n  from finite_cyclic_group_Characters obtain f where f: \"finite_cyclic_group (Characters G) f\" .\n  then interpret C: finite_cyclic_group \"Characters G\" f .\n  have \"cyclic_group (Characters G) f\" by unfold_locales\n  from iso_cyclic_groups_same_order[OF this order_Characters[symmetric]] show ?thesis .\nqed\n\ntext \\<open>The character groups of two isomorphic groups are also isomorphic.\\<close>\n\nlemma (in finite_comm_group) iso_imp_iso_chars:\n  assumes \"G \\<cong> H\" \"group H\"\n  shows \"Characters G \\<cong> Characters H\"\nproof -\n  interpret H: finite_comm_group H by (rule iso_imp_finite_comm[OF assms])\n  from assms have \"H \\<cong> G\" using iso_sym by auto\n  then obtain g where g: \"g \\<in> iso H G\" unfolding is_iso_def by blast\n  then interpret ggh: group_hom H G g by (unfold_locales, unfold iso_def, simp)\n  let ?f = \"(\\<lambda>c a. if a \\<in> carrier H then (c \\<circ> g) a else 0)\"\n  have \"?f \\<in> iso (Characters G) (Characters H)\"\n  proof (intro isoI)\n    interpret CG: finite_comm_group \"Characters G\" by (intro finite_comm_group_Characters)\n    interpret CH: finite_comm_group \"Characters H\" by (intro H.finite_comm_group_Characters)\n    have f_in: \"?f x \\<in> carrier (Characters H)\" if \"x \\<in> carrier (Characters G)\" for x\n    proof (unfold carrier_Characters characters_def, rule, unfold_locales)\n      interpret character G x using that characters_def carrier_Characters by blast\n      show \"(if \\<one>\\<^bsub>H\\<^esub> \\<in> carrier H then (x \\<circ> g) \\<one>\\<^bsub>H\\<^esub> else 0) \\<noteq> 0\" using g iso_iff by auto\n      show \"\\<And>a. a \\<notin> carrier H \\<Longrightarrow> (if a \\<in> carrier H then (x \\<circ> g) a else 0) = 0\" by simp\n      show \"?f x (a \\<otimes>\\<^bsub>H\\<^esub> b) = ?f x a * ?f x b\" if \"a \\<in> carrier H\" \"b \\<in> carrier H\" for a b\n        using that by auto\n    qed\n    show \"?f \\<in> hom (Characters G) (Characters H)\"\n    proof (intro homI)\n      show \"?f x \\<in> carrier (Characters H)\" if \"x \\<in> carrier (Characters G)\" for x\n        using f_in[OF that] .\n      show \"?f (x \\<otimes>\\<^bsub>Characters G\\<^esub> y) = ?f x \\<otimes>\\<^bsub>Characters H\\<^esub> ?f y\"\n        if \"x \\<in> carrier (Characters G)\" \"y \\<in> carrier (Characters G)\" for x y\n      proof -\n        interpret x: character G x using that characters_def carrier_Characters by blast\n        interpret y: character G y using that characters_def carrier_Characters by blast\n        show ?thesis using that mult_Characters[of G] mult_Characters[of H] by auto\n      qed\n    qed\n    show \"bij_betw ?f (carrier (Characters G)) (carrier (Characters H))\"\n    proof(intro bij_betwI)\n      define f where \"f = inv_into (carrier H) g\"\n      hence f: \"f \\<in> iso G H\" using H.iso_set_sym[OF g] by simp\n      then interpret fgh: group_hom G H f by (unfold_locales, unfold iso_def, simp)\n      let ?g = \"(\\<lambda>c a. if a \\<in> carrier G then (c \\<circ> f) a else 0)\"\n      show \"?f \\<in> carrier (Characters G) \\<rightarrow> carrier (Characters H)\" using f_in by fast\n      show \"?g \\<in> carrier (Characters H) \\<rightarrow> carrier (Characters G)\"\n      proof -\n        have g_in: \"?g x \\<in> carrier (Characters G)\" if \"x \\<in> carrier (Characters H)\" for x\n        proof (unfold carrier_Characters characters_def, rule, unfold_locales)\n          interpret character H x using that characters_def carrier_Characters by blast\n          show \"(if \\<one>\\<^bsub>G\\<^esub> \\<in> carrier G then (x \\<circ> f) \\<one>\\<^bsub>G\\<^esub> else 0) \\<noteq> 0\" using f iso_iff by auto\n          show \"\\<And>a. a \\<notin> carrier G \\<Longrightarrow> (if a \\<in> carrier G then (x \\<circ> f) a else 0) = 0\" by simp\n          show \"?g x (a \\<otimes>\\<^bsub>G\\<^esub> b) = ?g x a * ?g x b\" if \"a \\<in> carrier G\" \"b \\<in> carrier G\" for a b\n            using that by auto\n        qed\n        thus ?thesis by simp\n      qed\n      show \"?f (?g x) = x\" if x: \"x \\<in> carrier (Characters H)\" for x\n      proof -\n        interpret character H x using x characters_def carrier_Characters by blast\n        have \"?f (?g x) a = x a\" if a: \"a \\<notin> carrier H\" for a using a char_eq_0[OF a] by auto\n        moreover have \"?f (?g x) a = x a\" if a: \"a \\<in> carrier H\" for a\n        proof -\n          from a have \"inv_into (carrier H) g (g a) = a\"\n            by (simp add: g ggh.inj_iff_trivial_ker ggh.iso_kernel)\n          thus ?thesis using a f_def by auto\n        qed\n        ultimately show ?thesis by fast\n      qed\n      show \"?g (?f x) = x\" if x: \"x \\<in> carrier (Characters G)\" for x\n      proof -\n        interpret character G x using x characters_def carrier_Characters by blast\n        have \"?g (?f x) a = x a\" if a: \"a \\<notin> carrier G\" for a using a char_eq_0[OF a] by auto\n        moreover have \"?g (?f x) a = x a\" if a: \"a \\<in> carrier G\" for a using a f_def\n        proof -\n          from a have \"g (inv_into (carrier H) g a) = a\"\n            by (meson f_inv_into_f g ggh.iso_iff subset_iff)\n          thus ?thesis using a f_def fgh.hom_closed by auto\n        qed\n        ultimately show ?thesis by fast\n      qed\n    qed\n  qed\n  thus ?thesis unfolding is_iso_def by blast\nqed\n\ntext \\<open>The following two lemmas characterize the way a character behaves in a direct group product:\na character on the product induces characters on each of the factors. Also, any character on the\ndirect product can be decomposed into a pointwise product of characters on the factors.\\<close>\n\nlemma DirProds_subchar:\n  assumes \"finite_comm_group (DirProds Gs I)\"\n  and x: \"x \\<in> carrier (Characters (DirProds Gs I))\" \n  and i: \"i \\<in> I\"\n  and I: \"finite I\"\n  defines g: \"g \\<equiv> (\\<lambda>c. (\\<lambda>i\\<in>I. (\\<lambda>a. c ((\\<lambda>i\\<in>I. \\<one>\\<^bsub>Gs i\\<^esub>)(i:=a)))))\"\n  shows \"character (Gs i) (g x i)\"\nproof -\n  interpret DP: finite_comm_group \"DirProds Gs I\" by fact\n  interpret xc: character \"DirProds Gs I\" x using x unfolding Characters_def characters_def by auto\n  interpret Gi: finite_comm_group \"Gs i\"\n    using i DirProds_finite_comm_group_iff[OF I] DP.finite_comm_group_axioms by blast\n  have allg: \"\\<And>i. i\\<in>I \\<Longrightarrow> group (Gs i)\" using DirProds_group_imp_groups[OF DP.is_group] .\n  show ?thesis\n  proof(unfold_locales)\n    have \"(\\<lambda>i\\<in>I. \\<one>\\<^bsub>Gs i\\<^esub>) = (\\<lambda>i\\<in>I. \\<one>\\<^bsub>Gs i\\<^esub>)(i := \\<one>\\<^bsub>Gs i\\<^esub>)\" using i by force\n    thus \"g x i \\<one>\\<^bsub>Gs i\\<^esub> \\<noteq> 0\" using i g DirProds_one''[of Gs I] xc.char_one_nz by auto\n    show \"g x i a = 0\" if a: \"a \\<notin> carrier (Gs i)\" for a\n    proof -\n      from a i have \"((\\<lambda>i\\<in>I. \\<one>\\<^bsub>Gs i\\<^esub>)(i := a)) \\<notin> carrier (DirProds Gs I)\"\n        unfolding DirProds_def by force\n      from xc.char_eq_0[OF this] show ?thesis using i g by auto\n    qed\n    show \"g x i (a \\<otimes>\\<^bsub>Gs i\\<^esub> b) = g x i a * g x i b\"\n      if ab: \"a \\<in> carrier (Gs i)\" \"b \\<in> carrier (Gs i)\" for a b\n    proof -\n      have \"g x i (a \\<otimes>\\<^bsub>Gs i\\<^esub> b)\n          = x ((\\<lambda>i\\<in>I. \\<one>\\<^bsub>Gs i\\<^esub>)(i := a) \\<otimes>\\<^bsub>DirProds Gs I\\<^esub> (\\<lambda>i\\<in>I. \\<one>\\<^bsub>Gs i\\<^esub>)(i := b))\"\n      proof -\n        have \"((\\<lambda>i\\<in>I. \\<one>\\<^bsub>Gs i\\<^esub>)(i := a) \\<otimes>\\<^bsub>DirProds Gs I\\<^esub> (\\<lambda>i\\<in>I. \\<one>\\<^bsub>Gs i\\<^esub>)(i := b))\n            = ((\\<lambda>i\\<in>I. \\<one>\\<^bsub>Gs i\\<^esub>)(i := (a \\<otimes>\\<^bsub>Gs i\\<^esub> b)))\"\n        proof -\n          have \"((\\<lambda>i\\<in>I. \\<one>\\<^bsub>Gs i\\<^esub>)(i := a) \\<otimes>\\<^bsub>DirProds Gs I\\<^esub> (\\<lambda>i\\<in>I. \\<one>\\<^bsub>Gs i\\<^esub>)(i := b)) j\n              = ((\\<lambda>i\\<in>I. \\<one>\\<^bsub>Gs i\\<^esub>)(i := (a \\<otimes>\\<^bsub>Gs i\\<^esub> b))) j\"\n            for j\n          proof (cases \"j \\<in> I\")\n            case True\n            from allg[OF True] interpret Gj: group \"Gs j\" .\n            show ?thesis using ab True i unfolding DirProds_mult by simp\n          next\n            case False\n            then show ?thesis unfolding DirProds_mult using i by fastforce\n          qed\n          thus ?thesis by fast\n        qed\n        thus ?thesis using i g by auto\n      qed \n      also have \"\\<dots> = x ((\\<lambda>i\\<in>I. \\<one>\\<^bsub>Gs i\\<^esub>)(i := a)) * x ((\\<lambda>i\\<in>I. \\<one>\\<^bsub>Gs i\\<^esub>)(i := b))\"\n      proof -\n        have ac: \"((\\<lambda>i\\<in>I. \\<one>\\<^bsub>Gs i\\<^esub>)(i := a)) \\<in> carrier (DirProds Gs I)\"\n          unfolding DirProds_def using ab i monoid.one_closed[OF group.is_monoid[OF allg]] by force\n        have bc: \"((\\<lambda>i\\<in>I. \\<one>\\<^bsub>Gs i\\<^esub>)(i := b)) \\<in> carrier (DirProds Gs I)\"\n          unfolding DirProds_def using ab i monoid.one_closed[OF group.is_monoid[OF allg]] by force\n        from xc.char_mult[OF ac bc] show ?thesis .\n      qed\n      also have \"\\<dots> = g x i a * g x i b\" using i g by auto\n      finally show ?thesis .\n    qed\n  qed\nqed\n\nlemma Characters_DirProds_single_prod:\n  assumes \"finite_comm_group (DirProds Gs I)\"\n  and x: \"x \\<in> carrier (Characters (DirProds Gs I))\"\n  and I: \"finite I\"\n  defines g: \"g \\<equiv> (\\<lambda>I. (\\<lambda>c. (\\<lambda>i\\<in>I. (\\<lambda>a. c ((\\<lambda>i\\<in>I. \\<one>\\<^bsub>Gs i\\<^esub>)(i:=a))))))\"\n  shows \"(\\<lambda>e. if e\\<in>carrier(DirProds Gs I) then \\<Prod>i\\<in>I. (g I x i) (e i) else 0) = x\" (is \"?g x = x\")\nproof\n  show \"?g x e = x e\" for e\n  proof (cases \"e \\<in> carrier (DirProds Gs I)\")\n    case True\n    show ?thesis using I x assms(1) True unfolding g\n    proof(induction I arbitrary: x e rule: finite_induct)\n      case empty\n      interpret DP: finite_comm_group \"DirProds Gs {}\" by fact\n      from DirProds_empty[of Gs] have \"order (DirProds Gs {}) = 1\" unfolding order_def by simp\n      with DP.characters_in_order_1[OF this] empty(1) show ?case\n        using DirProds_empty[of Gs] unfolding Characters_def principal_char_def by auto\n    next\n      case j: (insert j I)\n      interpret DP: finite_comm_group \"DirProds Gs (insert j I)\" by fact\n      interpret DP2: finite_comm_group \"DirProds Gs I\"\n      proof -\n        from DirProds_finite_comm_group_iff[of \"insert j I\" Gs] DP.finite_comm_group_axioms j\n        have \"(\\<forall>i\\<in>(insert j I). finite_comm_group (Gs i))\" by blast\n        with DirProds_finite_comm_group_iff[OF j(1), of Gs] show \"finite_comm_group (DirProds Gs I)\"\n          by blast\n      qed\n      interpret xc: character \"DirProds Gs (insert j I)\" x\n        using j(4) unfolding Characters_def characters_def by simp\n      have allg: \"\\<And>i. i\\<in>(insert j I) \\<Longrightarrow> group (Gs i)\"\n        using DirProds_group_imp_groups[OF DP.is_group] .\n      have e1c: \"e(j:= \\<one>\\<^bsub>Gs j\\<^esub>) \\<in> carrier (DirProds Gs (insert j I))\"\n        using j(6) monoid.one_closed[OF group.is_monoid[OF allg[of j]]]\n        unfolding DirProds_def PiE_def Pi_def by simp\n      have e2c: \"(\\<lambda>i\\<in>(insert j I). \\<one>\\<^bsub>Gs i\\<^esub>)(j := e j) \\<in> carrier (DirProds Gs (insert j I))\"\n        unfolding DirProds_def PiE_def Pi_def\n        using monoid.one_closed[OF group.is_monoid[OF allg]] comp_in_carr[OF j(6)] by auto\n      have \"e = e(j:= \\<one>\\<^bsub>Gs j\\<^esub>) \\<otimes>\\<^bsub>DirProds Gs (insert j I)\\<^esub> (\\<lambda>i\\<in>(insert j I). \\<one>\\<^bsub>Gs i\\<^esub>)(j := e j)\"\n      proof -\n        have \"e k\n            = (e(j:= \\<one>\\<^bsub>Gs j\\<^esub>) \\<otimes>\\<^bsub>DirProds Gs (insert j I)\\<^esub> (\\<lambda>i\\<in>(insert j I). \\<one>\\<^bsub>Gs i\\<^esub>)(j := e j)) k\"\n          for k\n        proof(cases \"k\\<in>(insert j I)\")\n          case k: True\n          from allg[OF k] interpret Gk: group \"Gs k\" .\n          from allg[of j] interpret Gj: group \"Gs j\" by simp\n          from k show ?thesis unfolding comp_mult[OF k] using comp_in_carr[OF j(6) k] by auto\n        next\n          case False\n          then show ?thesis using j(6) unfolding DirProds_def by auto\n        qed\n        thus ?thesis by blast\n      qed\n      hence \"x e = x (e(j:= \\<one>\\<^bsub>Gs j\\<^esub>)) * x ((\\<lambda>i\\<in>(insert j I). \\<one>\\<^bsub>Gs i\\<^esub>)(j := e j))\"\n        using xc.char_mult[OF e1c e2c] by argo\n      also have \"\\<dots> = (\\<Prod>i\\<in>I. g (insert j I) x i (e i)) * g (insert j I) x j (e j)\"\n      proof -\n        have \"x (e(j:= \\<one>\\<^bsub>Gs j\\<^esub>)) = (\\<Prod>i\\<in>I. g (insert j I) x i (e i))\"\n        proof -\n          have eu: \"e(j:=undefined) \\<in> carrier (DirProds Gs I)\" using j(2, 6)\n            unfolding DirProds_def PiE_def Pi_def extensional_def by fastforce\n          let ?x = \"\\<lambda>p. if p\\<in>carrier(DirProds Gs I) then x (p(j:= \\<one>\\<^bsub>Gs j\\<^esub>)) else 0\"\n          have cx2: \"character (DirProds Gs I) ?x\"\n          proof\n            show \"?x \\<one>\\<^bsub>DirProds Gs I\\<^esub> \\<noteq> 0\"\n            proof -\n              have \"\\<one>\\<^bsub>DirProds Gs I\\<^esub>(j := \\<one>\\<^bsub>Gs j\\<^esub>) = \\<one>\\<^bsub>DirProds Gs (insert j I)\\<^esub>\"\n                unfolding DirProds_one'' by force\n              thus ?thesis by simp\n            qed\n            show \"?x a = 0\" if a: \"a \\<notin> carrier (DirProds Gs I)\" for a using a by argo\n            show \"?x (a \\<otimes>\\<^bsub>DirProds Gs I\\<^esub> b) = ?x a * ?x b\"\n              if ab: \"a \\<in> carrier (DirProds Gs I)\" \"b \\<in> carrier (DirProds Gs I)\" for a b\n            proof -\n              have ac: \"a(j := \\<one>\\<^bsub>Gs j\\<^esub>) \\<in> carrier (DirProds Gs (insert j I))\"\n                using ab monoid.one_closed[OF group.is_monoid[OF allg[of j]]]\n                unfolding DirProds_def PiE_def Pi_def by simp\n              have bc: \"b(j := \\<one>\\<^bsub>Gs j\\<^esub>) \\<in> carrier (DirProds Gs (insert j I))\"\n                using ab monoid.one_closed[OF group.is_monoid[OF allg[of j]]]\n                unfolding DirProds_def PiE_def Pi_def by simp\n              have m: \"((a \\<otimes>\\<^bsub>DirProds Gs I\\<^esub> b)(j := \\<one>\\<^bsub>Gs j\\<^esub>))\n                     = (a(j := \\<one>\\<^bsub>Gs j\\<^esub>) \\<otimes>\\<^bsub>DirProds Gs (insert j I)\\<^esub> b(j := \\<one>\\<^bsub>Gs j\\<^esub>))\"\n              proof -\n                have \"((a \\<otimes>\\<^bsub>DirProds Gs I\\<^esub> b)(j := \\<one>\\<^bsub>Gs j\\<^esub>)) h\n                    = (a(j := \\<one>\\<^bsub>Gs j\\<^esub>) \\<otimes>\\<^bsub>DirProds Gs (insert j I)\\<^esub> b(j := \\<one>\\<^bsub>Gs j\\<^esub>)) h\"\n                  if h: \"h\\<in>(insert j I)\" for h\n                proof(cases \"h=j\")\n                  case True\n                  interpret Gj: group \"Gs j\" using allg[of j] by blast\n                  from True comp_mult[OF h, of Gs \"a(j := \\<one>\\<^bsub>Gs j\\<^esub>)\" \"b(j := \\<one>\\<^bsub>Gs j\\<^esub>)\"] show ?thesis\n                    by auto\n                next\n                  case False\n                  interpret Gj: group \"Gs h\" using allg[OF h] .\n                  from False h comp_mult[OF h, of Gs \"a(j := \\<one>\\<^bsub>Gs j\\<^esub>)\" \"b(j := \\<one>\\<^bsub>Gs j\\<^esub>)\"]\n                       comp_mult[of h I Gs a b]\n                  show ?thesis by auto\n                qed\n                moreover have \"((a \\<otimes>\\<^bsub>DirProds Gs I\\<^esub> b)(j := \\<one>\\<^bsub>Gs j\\<^esub>)) h\n                             = (a(j := \\<one>\\<^bsub>Gs j\\<^esub>) \\<otimes>\\<^bsub>DirProds Gs (insert j I)\\<^esub> b(j := \\<one>\\<^bsub>Gs j\\<^esub>)) h\"\n                  if h: \"h\\<notin>(insert j I)\" for h using h unfolding DirProds_def PiE_def by simp\n                ultimately show ?thesis by blast\n              qed\n              have \"x ((a \\<otimes>\\<^bsub>DirProds Gs I\\<^esub> b)(j := \\<one>\\<^bsub>Gs j\\<^esub>))\n                  = x (a(j := \\<one>\\<^bsub>Gs j\\<^esub>)) * x (b(j := \\<one>\\<^bsub>Gs j\\<^esub>))\"\n                by (unfold m, intro xc.char_mult[OF ac bc])\n              thus ?thesis using ab by auto\n            qed\n          qed\n          then interpret cx2: character \"DirProds Gs I\" ?x .\n          from cx2 have cx3:\"?x \\<in> carrier (Characters (DirProds Gs I))\"\n            unfolding Characters_def characters_def by simp\n          from j(3)[OF cx3 DP2.finite_comm_group_axioms eu] have\n           \"(if e(j:=undefined) \\<in> carrier (DirProds Gs I)\n             then \\<Prod>i\\<in>I. g I ?x i ((e(j:=undefined)) i)\n             else 0) = ?x (e(j:=undefined))\"\n            using eu j(2) unfolding g by fast\n          with eu have \"(\\<Prod>i\\<in>I. g I (\\<lambda>p. if p \\<in> carrier (DirProds Gs I)\n                                         then x (p(j := \\<one>\\<^bsub>Gs j\\<^esub>))\n                                         else 0) i ((e(j := undefined)) i)) = x (e(j := \\<one>\\<^bsub>Gs j\\<^esub>))\"\n            by simp\n          moreover have \"g I (\\<lambda>a. if a \\<in> carrier (DirProds Gs I)\n                                  then x (a(j := \\<one>\\<^bsub>Gs j\\<^esub>))\n                                  else 0) i ((e(j := undefined)) i) = g (insert j I) x i (e i)\"\n            if i: \"i\\<in>I\" for i\n          proof -\n            have \"(\\<lambda>i\\<in>I. \\<one>\\<^bsub>Gs i\\<^esub>)(i := e i) \\<in> carrier (DirProds Gs I)\"\n              unfolding DirProds_def PiE_def Pi_def extensional_def\n              using monoid.one_closed[OF group.is_monoid[OF allg]] comp_in_carr[OF j(6)] i by simp\n            moreover have \"((\\<lambda>i\\<in>I. \\<one>\\<^bsub>Gs i\\<^esub>)(i := e i, j := \\<one>\\<^bsub>Gs j\\<^esub>))\n                         = ((\\<lambda>i\\<in>insert j I. \\<one>\\<^bsub>Gs i\\<^esub>)(i := e i))\" using i j(2) by auto\n            ultimately show ?thesis using i j(2, 4, 6) unfolding g by auto\n          qed\n          ultimately show ?thesis by simp\n        qed\n        moreover have \"x ((\\<lambda>i\\<in>(insert j I). \\<one>\\<^bsub>Gs i\\<^esub>)(j := e j)) = g (insert j I) x j (e j)\"\n          unfolding g by simp\n        ultimately show ?thesis by argo\n      qed  \n      finally show ?case using j unfolding g by auto\n    qed \n  next\n    case False\n    interpret xc: character \"DirProds Gs I\" x\n      using x unfolding Characters_def characters_def by simp\n    from xc.char_eq_0[OF False] False show ?thesis by argo\n  qed\nqed\n\ntext \\<open>This allows for the following: the character group of a direct product is isomorphic to the\ndirect product of the character groups of the factors.\\<close>\n\nlemma (in finite_comm_group) Characters_DirProds_iso:\n  assumes \"DirProds Gs I \\<cong> G\" \"group (DirProds Gs I)\" \"finite I\"\n  shows \"DirProds (Characters \\<circ> Gs) I \\<cong> Characters G\"\nproof -\n  interpret DP: group \"DirProds Gs I\" by fact\n  interpret DP: finite_comm_group \"DirProds Gs I\"\n    by (intro iso_imp_finite_comm[OF DP.iso_sym[OF assms(1)]], unfold_locales)\n  interpret DPC: finite_comm_group \"DirProds (Characters \\<circ> Gs) I\"\n    using DirProds_finite_comm_group_iff[OF assms(3), of \"Characters \\<circ> Gs\"]\n          DirProds_finite_comm_group_iff[OF assms(3), of Gs]\n          DP.finite_comm_group_axioms finite_comm_group.finite_comm_group_Characters by auto\n  interpret CDP: finite_comm_group \"Characters (DirProds Gs I)\"\n    using DP.finite_comm_group_Characters .\n  interpret C: finite_comm_group \"Characters G\" using finite_comm_group_Characters .\n  have allg: \"\\<And>i. i\\<in>I \\<Longrightarrow> group (Gs i)\" using DirProds_group_imp_groups[OF assms(2)] .\n  let ?f = \"(\\<lambda>cp. (\\<lambda>e. (if e\\<in>carrier (DirProds Gs I) then \\<Prod>i\\<in>I. cp i (e i) else 0)))\"\n  have f_in: \"?f x \\<in> carrier (Characters (DirProds Gs I))\"\n    if x: \"x \\<in> carrier (DirProds (Characters \\<circ> Gs) I)\" for x\n  proof(unfold carrier_Characters characters_def, safe, unfold_locales)\n    show \"?f x \\<one>\\<^bsub>DirProds Gs I\\<^esub> \\<noteq> 0\"\n    proof -\n      have \"x i (\\<one>\\<^bsub>DirProds Gs I\\<^esub> i) \\<noteq> 0\" if i: \"i \\<in> I\" for i\n      proof -\n        interpret Gi: finite_comm_group \"Gs i\"\n          using DirProds_finite_comm_group_iff[OF assms(3)] DP.finite_comm_group_axioms i by blast\n        interpret xi: character \"Gs i\" \"x i\"\n          using i x unfolding DirProds_def Characters_def characters_def by auto\n        show ?thesis using DirProds_one'[OF i, of Gs] by simp\n      qed\n      thus ?thesis by (simp add: assms(3))\n    qed\n    show \"?f x a = 0\" if \"a \\<notin> carrier (DirProds Gs I)\" for a using that by simp\n    show \"?f x (a \\<otimes>\\<^bsub>DirProds Gs I\\<^esub> b) = ?f x a * ?f x b\"\n      if ab: \"a \\<in> carrier (DirProds Gs I)\" \"b \\<in> carrier (DirProds Gs I)\" for a b\n    proof -\n      have \"a \\<otimes>\\<^bsub>DirProds Gs I\\<^esub> b \\<in> carrier (DirProds Gs I)\" using that by blast\n      moreover have \"(\\<Prod>i\\<in>I. x i ((a \\<otimes>\\<^bsub>DirProds Gs I\\<^esub> b) i))\n                   = (\\<Prod>i\\<in>I. x i (a i)) * (\\<Prod>i\\<in>I. x i (b i))\"\n      proof -\n        have \"x i ((a \\<otimes>\\<^bsub>DirProds Gs I\\<^esub> b) i) = x i (a i) * x i (b i)\" if i: \"i\\<in>I\" for i\n        proof -\n          interpret xi: character \"Gs i\" \"x i\"\n            using i x unfolding DirProds_def Characters_def characters_def by auto\n          show ?thesis using ab comp_mult[OF i, of Gs a b] by(auto simp: comp_in_carr[OF _ i])\n        qed\n        thus ?thesis using prod.distrib by force\n      qed\n      ultimately show ?thesis using that by auto\n    qed\n  qed\n  have \"?f \\<in> iso (DirProds (Characters \\<circ> Gs) I) (Characters (DirProds Gs I))\"\n  proof (intro isoI)\n    show \"?f \\<in> hom (DirProds (Characters \\<circ> Gs) I) (Characters (DirProds Gs I))\"\n    proof (intro homI)\n      show \"?f x \\<in> carrier (Characters (DirProds Gs I))\"\n        if x: \"x \\<in> carrier (DirProds (Characters \\<circ> Gs) I)\" for x using f_in[OF that] .\n      show \"?f (x \\<otimes>\\<^bsub>DirProds (Characters \\<circ> Gs) I\\<^esub> y) = ?f x \\<otimes>\\<^bsub>Characters (DirProds Gs I)\\<^esub> ?f y\"\n        if \"x \\<in> carrier (DirProds (Characters \\<circ> Gs) I)\" \"y \\<in> carrier (DirProds (Characters \\<circ> Gs) I)\"\n        for x y\n      proof -\n        have \"?f x \\<otimes>\\<^bsub>Characters (DirProds Gs I)\\<^esub> ?f y\n         = (\\<lambda>e. if e \\<in> carrier (DirProds Gs I) then (\\<Prod>i\\<in>I. x i (e i)) * (\\<Prod>i\\<in>I. y i (e i)) else 0)\"\n          unfolding Characters_def by auto\n        also have \"\\<dots> = ?f (x \\<otimes>\\<^bsub>DirProds (Characters \\<circ> Gs) I\\<^esub> y)\"\n        proof -\n          have \"(\\<Prod>i\\<in>I. x i (e i)) * (\\<Prod>i\\<in>I. y i (e i))\n              = (\\<Prod>i\\<in>I. (x \\<otimes>\\<^bsub>DirProds (Characters \\<circ> Gs) I\\<^esub> y) i (e i))\" for e\n            unfolding DirProds_def Characters_def by (auto simp: prod.distrib)\n          thus ?thesis by presburger\n        qed\n        finally show ?thesis by argo\n      qed\n    qed\n    then interpret fgh: group_hom \"DirProds (Characters \\<circ> Gs) I\" \"Characters (DirProds Gs I)\" ?f\n      by (unfold_locales, simp)\n    show \"bij_betw ?f (carrier (DirProds (Characters \\<circ> Gs) I)) (carrier (Characters (DirProds Gs I)))\"\n    proof (intro bij_betwI)\n      let ?g = \"(\\<lambda>c. (\\<lambda>i\\<in>I. (\\<lambda>a. c ((\\<lambda>i\\<in>I. \\<one>\\<^bsub>Gs i\\<^esub>)(i:=a)))))\"\n      have allc: \"character (Gs i) (?g x i)\"\n        if x: \"x \\<in> carrier (Characters (DirProds Gs I))\" and i: \"i \\<in> I\" for x i\n        using DirProds_subchar[OF DP.finite_comm_group_axioms x i assms(3)] .\n      have g_in: \"?g x \\<in> carrier (DirProds (Characters \\<circ> Gs) I)\"\n        if x: \"x \\<in> carrier (Characters (DirProds Gs I))\" for x\n        using allc[OF x] unfolding DirProds_def Characters_def characters_def by simp\n      show fi: \"?f \\<in> carrier (DirProds (Characters \\<circ> Gs) I) \\<rightarrow> carrier (Characters (DirProds Gs I))\"\n        using f_in by fast\n      show gi: \"?g \\<in> carrier (Characters (DirProds Gs I)) \\<rightarrow> carrier (DirProds (Characters \\<circ> Gs) I)\"\n        using g_in by fast\n      show \"?f (?g x) = x\" if x: \"x \\<in> carrier (Characters (DirProds Gs I))\" for x\n      proof -\n        from x interpret x: character \"DirProds Gs I\" x unfolding Characters_def characters_def\n          by auto\n        from f_in[OF g_in[OF x]] interpret character \"DirProds Gs I\" \"?f (?g x)\"\n          unfolding Characters_def characters_def by simp\n        have \"(\\<Prod>i\\<in>I. (\\<lambda>i\\<in>I. \\<lambda>a. x ((\\<lambda>i\\<in>I. \\<one>\\<^bsub>Gs i\\<^esub>)(i := a))) i (e i)) = x e\"\n          if e: \"e \\<in> carrier (DirProds Gs I)\" for e\n        proof -\n          define y where y: \"y = (\\<lambda>e. if e \\<in> carrier (DirProds Gs I)\n                                      then \\<Prod>i\\<in>I. (\\<lambda>i\\<in>I. \\<lambda>a. x ((\\<lambda>i\\<in>I. \\<one>\\<^bsub>Gs i\\<^esub>)(i := a))) i (e i)\n                                      else 0)\"\n          from Characters_DirProds_single_prod[OF DP.finite_comm_group_axioms x assms(3)]\n          have \"y = x\" using y by force\n          hence \"y e = x e\" by blast\n          thus ?thesis using e unfolding y by argo\n        qed\n        with x.char_eq_0 show ?thesis by force\n      qed\n      show \"?g (?f x) = x\" if x: \"x \\<in> carrier (DirProds (Characters \\<circ> Gs) I)\" for x\n      proof(intro eq_parts_imp_eq[OF g_in[OF f_in[OF x]] x])\n        show \"?g (?f x) i = x i\" if i: \"i\\<in>I\" for i\n        proof -\n          interpret xi: character \"Gs i\" \"x i\"\n            using x i unfolding DirProds_def Characters_def characters_def by auto \n          have \"?g (?f x) i a = x i a\" if a: \"a\\<notin>carrier (Gs i)\" for a\n          proof -\n            have \"(\\<lambda>i\\<in>I. \\<one>\\<^bsub>Gs i\\<^esub>)(i := a) \\<notin> carrier (DirProds Gs I)\"\n              using a i unfolding DirProds_def PiE_def Pi_def by auto\n            with xi.char_eq_0[OF a] a i show ?thesis by auto\n          qed\n          moreover have \"?g (?f x) i a = x i a\" if a: \"a\\<in>carrier (Gs i)\" for a\n          proof -\n            have \"(\\<lambda>i\\<in>I. \\<one>\\<^bsub>Gs i\\<^esub>)(i := a) \\<in> carrier (DirProds Gs I)\"\n              using a i monoid.one_closed[OF group.is_monoid[OF allg]]\n              unfolding DirProds_def by force\n            moreover have \"(\\<Prod>j\\<in>I. x j (((\\<lambda>i\\<in>I. \\<one>\\<^bsub>Gs i\\<^esub>)(i := a)) j)) = x i a\"\n            proof -\n              have \"(\\<Prod>j\\<in>I. x j (((\\<lambda>i\\<in>I. \\<one>\\<^bsub>Gs i\\<^esub>)(i := a)) j))\n               = x i (((\\<lambda>i\\<in>I. \\<one>\\<^bsub>Gs i\\<^esub>)(i := a)) i) * (\\<Prod>j\\<in>I-{i}. x j (((\\<lambda>i\\<in>I. \\<one>\\<^bsub>Gs i\\<^esub>)(i := a)) j))\"\n                by (meson assms(3) i prod.remove)\n              moreover have \"x j (((\\<lambda>i\\<in>I. \\<one>\\<^bsub>Gs i\\<^esub>)(i := a)) j) = 1\" if j: \"j\\<in>I\" \"j \\<noteq> i\" for j\n              proof -\n                interpret xj: character \"Gs j\" \"x j\"\n                  using j(1) x unfolding DirProds_def Characters_def characters_def by auto\n                show ?thesis using j by auto\n              qed\n              moreover have \"x i (((\\<lambda>i\\<in>I. \\<one>\\<^bsub>Gs i\\<^esub>)(i := a)) i) = x i a\" by simp\n              ultimately show ?thesis by auto\n            qed\n            ultimately show ?thesis using a i by simp\n          qed\n          ultimately show ?thesis by blast\n        qed\n      qed\n    qed\n  qed\n  hence \"DirProds (Characters \\<circ> Gs) I \\<cong> Characters (DirProds Gs I)\" unfolding is_iso_def by blast\n  moreover have \"Characters (DirProds Gs I) \\<cong> Characters G\"\n    using DP.iso_imp_iso_chars[OF assms(1) is_group] .\n  ultimately show ?thesis using iso_trans by blast\nqed\n\ntext \\<open>As thus both the group and its character group can be decomposed into the same cyclic factors,\nthe isomorphism follows for any finite abelian group.\\<close>\n\ntheorem (in finite_comm_group) Characters_iso:\n  shows \"G \\<cong> Characters G\"\nproof -\n  from cyclic_product obtain ns\n    where ns: \"DirProds (\\<lambda>n. Z (ns ! n)) {..<length ns} \\<cong> G\" \"\\<forall>n\\<in>set ns. n \\<noteq> 0\" .\n  interpret DP: group \"DirProds (\\<lambda>n. Z (ns ! n)) {..<length ns}\"\n    by (intro DirProds_is_group, auto)\n  have \"G \\<cong> DirProds (\\<lambda>n. Z (ns ! n)) {..<length ns}\" using DP.iso_sym[OF ns(1)] .\n  moreover have \"DirProds (Characters \\<circ> (\\<lambda>n. Z (ns ! n))) {..<length ns} \\<cong> Characters G\"\n    by (intro Characters_DirProds_iso[OF ns(1) DirProds_is_group], auto)\n  moreover have \"DirProds (\\<lambda>n. Z (ns ! n)) {..<length ns}\n               \\<cong> DirProds (Characters \\<circ> (\\<lambda>n. Z (ns ! n))) {..<length ns}\"\n  proof (intro DirProds_iso1)\n    fix i assume i: \"i \\<in> {..<length ns}\"\n    obtain a where \"cyclic_group (Z (ns!i)) a\" using Zn_cyclic_group .\n    then interpret Zi: cyclic_group \"Z (ns!i)\" a .\n    interpret Zi: finite_cyclic_group \"Z (ns!i)\" a\n    proof\n      have \"order (Z (ns ! i)) \\<noteq> 0\" using ns(2) i Zn_order by simp\n      thus \"finite (carrier (Z (ns ! i)))\" unfolding order_def by (simp add: card_eq_0_iff)\n    qed\n    show \"Group.group ((Characters \\<circ> (\\<lambda>n. Z (ns ! n))) i)\"\n         \"Group.group (Z (ns ! i))\" \"Z (ns ! i) \\<cong> (Characters \\<circ> (\\<lambda>n. Z (ns ! n))) i\"\n      using Zi.Characters_iso Zi.finite_comm_group_Characters comm_group_def finite_comm_group_def\n      by auto\n  qed\n  ultimately show ?thesis by (auto elim: iso_trans)\nqed\n\ntext \\<open>Hence, the orders are also equal.\\<close>\n\ncorollary (in finite_comm_group) order_Characters:\n  \"order (Characters G) = order G\"\n  using iso_same_card[OF Characters_iso] unfolding order_def by argo\n\ncorollary (in finite_comm_group) card_characters: \"card (characters G) = order G\"\n  using order_Characters unfolding order_def Characters_def by simp\n\nsubsection \\<open>Non-trivial facts about characters\\<close>\n\ntext \\<open>We characterize the character group of a quotient group as the group of characters that map\nall elements of the subgroup onto $1$.\\<close>\n\nlemma (in finite_comm_group) iso_Characters_FactGroup:\n  assumes H: \"subgroup H G\"\n  shows \"(\\<lambda>\\<chi> x. if x \\<in> carrier G then \\<chi> (H #> x) else 0) \\<in>\n           iso (Characters (G Mod H)) ((Characters G)\\<lparr>carrier := {\\<chi>\\<in>characters G. \\<forall>x\\<in>H. \\<chi> x = 1}\\<rparr>)\"\nproof -\n  interpret H: normal H G using subgroup_imp_normal[OF H] .\n  interpret Chars: finite_comm_group \"Characters G\"\n    by (rule finite_comm_group_Characters)\n  interpret Fact: comm_group \"G Mod H\"\n    by (simp add: H.subgroup_axioms comm_group.abelian_FactGroup comm_group_axioms)\n  interpret Fact: finite_comm_group \"G Mod H\"\n    by unfold_locales (auto simp: carrier_FactGroup)\n\n  define C :: \"('a \\<Rightarrow> complex) set\" where \"C = {\\<chi>\\<in>characters G. \\<forall>x\\<in>H. \\<chi> x = 1}\"\n  interpret C: subgroup C \"Characters G\"\n  proof (unfold_locales, goal_cases)\n    case 1\n    thus ?case\n      by (auto simp: C_def one_Characters mult_Characters carrier_Characters characters_def)\n  next\n    case 2\n    thus ?case\n      by (auto simp: C_def one_Characters mult_Characters carrier_Characters characters_def)\n  next\n    case 3\n    thus ?case\n      by (auto simp: C_def one_Characters mult_Characters\n                     carrier_Characters characters_def principal_char_def)\n  next\n    case (4 \\<chi>)\n    hence \"inv\\<^bsub>Characters G\\<^esub> \\<chi> = inv_character \\<chi>\"\n      by (subst inv_Characters') (auto simp: C_def carrier_Characters)\n    moreover have \"inv_character \\<chi> \\<in> characters G\"\n      using 4 by (auto simp: C_def characters_def)\n    moreover have \"\\<forall>x\\<in>H. inv_character \\<chi> x = 1\"\n      using 4 by (auto simp: C_def inv_character_def)\n    ultimately show ?case\n      by (auto simp: C_def)\n  qed\n\n  define f :: \"('a set \\<Rightarrow> complex) \\<Rightarrow> ('a \\<Rightarrow> complex)\"\n    where \"f = (\\<lambda>\\<chi> x. if x \\<in> carrier G then \\<chi> (H #> x) else 0)\"\n\n  have [intro]: \"character G (f \\<chi>)\" if \"character (G Mod H) \\<chi>\" for \\<chi>\n  proof -\n    interpret character \"G Mod H\" \\<chi> by fact\n    show ?thesis\n    proof (unfold_locales, goal_cases)\n      case 1\n      thus ?case by (auto simp: f_def char_eq_0_iff carrier_FactGroup)\n    next\n      case (2 x)\n      thus ?case by (auto simp: f_def)\n    next\n      case (3 x y)\n      have \"\\<chi> (H #> x) * \\<chi> (H #> y) = \\<chi> ((H #> x) \\<otimes>\\<^bsub>G Mod H\\<^esub> (H #> y))\"\n        using 3 by (intro char_mult [symmetric]) (auto simp: carrier_FactGroup)\n      also have \"(H #> x) \\<otimes>\\<^bsub>G Mod H\\<^esub> (H #> y) = H #> (x \\<otimes> y)\"\n        using 3 by (simp add: H.rcos_sum)\n      finally show ?case\n        using 3 by (simp add: f_def)\n    qed\n  qed\n\n  have [intro]: \"f \\<chi> \\<in> C\" if \"character (G Mod H) \\<chi>\" for \\<chi>\n  proof -\n    interpret \\<chi>: character \"G Mod H\" \\<chi>\n      by fact\n    have \"character G (f \\<chi>)\"\n      using \\<chi>.character_axioms by auto\n    moreover have \"\\<chi> (H #> x) = 1\" if \"x \\<in> H\" for x\n      using that H.rcos_const \\<chi>.char_one by force\n    ultimately show ?thesis\n      by (auto simp: carrier_Characters C_def characters_def f_def)\n  qed\n\n  show \"f \\<in> iso (Characters (G Mod H)) ((Characters G)\\<lparr>carrier := C\\<rparr>)\"\n  proof (rule isoI)\n    show \"f \\<in> hom (Characters (G Mod H)) (Characters G\\<lparr>carrier := C\\<rparr>)\"\n    proof (rule homI, goal_cases)\n      case (1 \\<chi>)\n      thus ?case\n        by (auto simp: carrier_Characters characters_def)\n    qed (auto simp: f_def carrier_Characters fun_eq_iff mult_Characters)\n  next\n    have \"bij_betw f (characters (G Mod H)) C\"\n      unfolding bij_betw_def\n    proof\n      show inj: \"inj_on f (characters (G Mod H))\"\n      proof (rule inj_onI, goal_cases)\n        case (1 \\<chi>1 \\<chi>2)\n        interpret \\<chi>1: character \"G Mod H\" \\<chi>1\n          using 1 by (auto simp: characters_def)\n        interpret \\<chi>2: character \"G Mod H\" \\<chi>2\n          using 1 by (auto simp: characters_def)\n\n        have \"\\<chi>1 H' = \\<chi>2 H'\" for H'\n        proof (cases \"H' \\<in> carrier (G Mod H)\")\n          case False\n          thus ?thesis by (simp add: \\<chi>1.char_eq_0 \\<chi>2.char_eq_0)\n        next\n          case True\n          then obtain x where x: \"x \\<in> carrier G\" \"H' = H #> x\"\n            by (auto simp: carrier_FactGroup)\n          from 1 have \"f \\<chi>1 x = f \\<chi>2 x\"\n            by simp\n          with x show ?thesis\n            by (auto simp: f_def)\n        qed\n        thus \"\\<chi>1 = \\<chi>2\" by force\n      qed\n    \n      have \"f ` characters (G Mod H) \\<subseteq> C\"\n        by (auto simp: characters_def)\n      moreover have \"C \\<subseteq> f ` characters (G Mod H)\"\n      proof safe\n        fix \\<chi> assume \\<chi>: \"\\<chi> \\<in> C\"\n        from \\<chi> interpret character G \\<chi>\n          by (auto simp: C_def characters_def)\n        have [simp]: \"\\<chi> x = 1\" if \"x \\<in> H\" for x\n          using \\<chi> that by (auto simp: C_def)\n\n        have \"\\<forall>H'\\<in>carrier (G Mod H). \\<exists>x\\<in>carrier G. H' = H #> x\"\n          by (auto simp: carrier_FactGroup)\n        then obtain h where h: \"h H' \\<in> carrier G\" \"H' = H #> h H'\" if \"H' \\<in> carrier (G Mod H)\" for H'\n          by metis\n        define \\<chi>' where \"\\<chi>' = (\\<lambda>H'. if H' \\<in> carrier (G Mod H) then \\<chi> (h H') else 0)\"\n\n        have \\<chi>_cong: \"\\<chi> x = \\<chi> y\" if \"H #> x = H #> y\" \"x \\<in> carrier G\" \"y \\<in> carrier G\" for x y\n        proof -\n          have \"x \\<in> H #> x\"\n            by (simp add: H.subgroup_axioms rcos_self that(2))\n          also have \"\\<dots> = H #> y\"\n            by fact\n          finally obtain z where z: \"z \\<in> H\" \"x = z \\<otimes> y\"\n            unfolding r_coset_def by auto\n          thus ?thesis\n            using z H.subset that by simp\n        qed\n\n        have \"character (G Mod H) \\<chi>'\"\n        proof (unfold_locales, goal_cases)\n          case 1\n          have H: \"H \\<in> carrier (G Mod H)\"\n            using Fact.one_closed unfolding one_FactGroup .\n          with h[of H] have \"h H \\<in> carrier G\"\n            by blast\n          thus ?case using H\n            by (auto simp: char_eq_0_iff \\<chi>'_def)\n        next\n          case (2 H')\n          thus ?case by (auto simp: \\<chi>'_def)\n        next\n          case (3 H1 H2)\n          from 3 have H12: \"H1 <#> H2 \\<in> carrier (G Mod H)\"\n            using Fact.m_closed by force\n          have \"\\<chi> (h (H1 <#> H2)) = \\<chi> (h H1 \\<otimes> h H2)\"\n          proof (rule \\<chi>_cong)\n            show \"H #> h (H1 <#> H2) = H #> (h H1 \\<otimes> h H2)\"\n              by (metis \"3\" H.rcos_sum H12 h)\n          qed (use 3 h[of H1] h[of H2] h[OF H12] in auto)\n          thus ?case\n            using 3 H12 h[of H1] h[of H2] by (auto simp: \\<chi>'_def)\n        qed\n\n        moreover have \"f \\<chi>' x = \\<chi> x\" for x\n        proof (cases \"x \\<in> carrier G\")\n          case False\n          thus ?thesis\n            by (auto simp: f_def \\<chi>'_def char_eq_0_iff)\n        next\n          case True\n          hence *: \"H #> x \\<in> carrier (G Mod H)\"\n            by (auto simp: carrier_FactGroup)\n          have \"\\<chi> (h (H #> x)) = \\<chi> x\"\n            using True * h[of \"H #> x\"] by (intro \\<chi>_cong) auto\n          thus ?thesis\n            using True * by (auto simp: f_def fun_eq_iff \\<chi>'_def)\n        qed\n        hence \"f \\<chi>' = \\<chi>\" by force\n\n        ultimately show \"\\<chi> \\<in> f ` characters (G Mod H)\"\n          unfolding characters_def by blast\n      qed\n\n      ultimately show \"f ` characters (G Mod H) = C\"\n        by blast\n\n    qed\n    thus \"bij_betw f (carrier (Characters (G Mod H))) (carrier (Characters G\\<lparr>carrier := C\\<rparr>))\"\n      by (simp add: carrier_Characters)\n  qed \nqed\n\nlemma (in finite_comm_group) is_iso_Characters_FactGroup:\n  assumes H: \"subgroup H G\"\n  shows \"Characters (G Mod H) \\<cong> (Characters G)\\<lparr>carrier := {\\<chi>\\<in>characters G. \\<forall>x\\<in>H. \\<chi> x = 1}\\<rparr>\"\n  using iso_Characters_FactGroup[OF assms] unfolding is_iso_def by blast\n\ntext \\<open>In order to derive the number of extensions a character on a subgroup has to the entire group,\nwe introduce the group homomorphism \\<open>restrict_char\\<close> that restricts a character to a given subgroup \\<open>H\\<close>.\\<close>\n\ndefinition restrict_char::\"'a set \\<Rightarrow> ('a \\<Rightarrow> complex) \\<Rightarrow> ('a \\<Rightarrow> complex) \" where\n\"restrict_char H \\<chi> = (\\<lambda>e. if e\\<in>H then \\<chi> e else 0)\"\n\nlemma (in finite_comm_group) restrict_char_hom:\n  assumes \"subgroup H G\"\n  shows \"group_hom (Characters G) (Characters (G\\<lparr>carrier := H\\<rparr>)) (restrict_char H)\"\nproof -\n  let ?CG = \"Characters G\"\n  let ?H = \"G\\<lparr>carrier := H\\<rparr>\"\n  let ?CH = \"Characters ?H\" \n  interpret H: subgroup H G by fact\n  interpret H: finite_comm_group ?H by (simp add: assms subgroup_imp_finite_comm_group)\n  interpret CG: finite_comm_group ?CG using finite_comm_group_Characters .\n  interpret CH: finite_comm_group ?CH using H.finite_comm_group_Characters .\n  show ?thesis\n  proof(unfold_locales, intro homI)\n    show \"restrict_char H x \\<in> carrier ?CH\" if x: \"x \\<in> carrier ?CG\" for x\n    proof -\n      interpret xc: character G x using x unfolding Characters_def characters_def by simp\n      have \"character ?H (restrict_char H x)\"\n        by (unfold restrict_char_def, unfold_locales, auto)\n      thus ?thesis unfolding Characters_def characters_def by simp\n    qed\n    show \"restrict_char H (x \\<otimes>\\<^bsub>?CG\\<^esub> y) = restrict_char H x \\<otimes>\\<^bsub>?CH\\<^esub> restrict_char H y\"\n      if x: \"x \\<in> carrier ?CG\" and y: \"y \\<in> carrier ?CG\" for x y\n    proof -\n      interpret xc: character G x using x unfolding Characters_def characters_def by simp\n      interpret yc: character G y using y unfolding Characters_def characters_def by simp\n      show ?thesis unfolding Characters_def restrict_char_def by auto\n    qed\n  qed\nqed\n\ntext \\<open>The kernel is just the set of the characters that are $1$ on all of \\<open>H\\<close>.\\<close>\n\nlemma (in finite_comm_group) restrict_char_kernel:\n  assumes \"subgroup H G\"\n  shows \"kernel (Characters G) (Characters (G\\<lparr>carrier := H\\<rparr>)) (restrict_char H)\n       = {\\<chi>\\<in>characters G. \\<forall>x\\<in>H. \\<chi> x = 1}\"\n  by (unfold restrict_char_def kernel_def one_Characters\n             carrier_Characters principal_char_def characters_def, simp, metis)\n\ntext \\<open>Also, all of the characters on the subgroup are the image of some character on the whole group.\\<close>\n\nlemma (in finite_comm_group) restrict_char_image:\n  assumes \"subgroup H G\"\n  shows \"restrict_char H ` (carrier (Characters G)) = carrier (Characters (G\\<lparr>carrier := H\\<rparr>))\"\nproof -\n  interpret H: subgroup H G by fact\n  interpret H: finite_comm_group \"G\\<lparr>carrier := H\\<rparr>\" using subgroup_imp_finite_comm_group[OF assms] .\n  interpret r: group_hom \"Characters G\" \"Characters (G\\<lparr>carrier := H\\<rparr>)\" \"restrict_char H\"\n    using restrict_char_hom[OF assms] .\n  interpret Mod: finite_comm_group \"G Mod H\" using finite_comm_FactGroup[OF assms] .\n  interpret CG: finite_comm_group \"Characters G\" using finite_comm_group_Characters .\n  have c1: \"order (Characters (G\\<lparr>carrier := H\\<rparr>)) = card H\" using H.order_Characters\n    unfolding order_def by simp\n  \n  have \"card H * card (kernel (Characters G) (Characters (G\\<lparr>carrier := H\\<rparr>)) (restrict_char H))\n      = order G\"\n    using restrict_char_kernel[OF assms] iso_same_card[OF is_iso_Characters_FactGroup[OF assms]]\n          Mod.order_Characters lagrange[OF assms] unfolding order_def FactGroup_def\n    by (force simp: algebra_simps)\n  moreover have \"card (kernel (Characters G) (Characters (G\\<lparr>carrier := H\\<rparr>)) (restrict_char H)) \\<noteq> 0\"\n    using r.one_in_kernel unfolding kernel_def CG.fin by auto\n  ultimately have c2: \"card H = card (restrict_char H ` carrier (Characters G))\"\n    using r.image_kernel_product[unfolded order_Characters] by (metis mult_right_cancel)\n\n  have \"restrict_char H ` (carrier (Characters G)) \\<subseteq> carrier (Characters (G\\<lparr>carrier := H\\<rparr>))\"\n    by auto\n  with c2 H.fin show ?thesis\n    by (auto, metis H.finite_imp_card_positive c1 card_subset_eq fin_gen\n                    order_def r.H.order_gt_0_iff_finite)\nqed\n\ntext \\<open>\n  It follows that any character on \\<open>H\\<close> can be extended\n  to a character on \\<open>G\\<close>.\n\\<close>\n\nlemma (in finite_comm_group) character_extension_exists:\n  assumes \"subgroup H G\" \"character (G\\<lparr>carrier := H\\<rparr>) \\<chi>\"\n  obtains \\<chi>' where \"character G \\<chi>'\" and \"\\<And>x. x \\<in> H \\<Longrightarrow> \\<chi>' x = \\<chi> x\"\nproof -\n  from restrict_char_image[OF assms(1)] assms(2) obtain \\<chi>'\n    where chi': \"restrict_char H \\<chi>' = \\<chi>\" \"character G \\<chi>'\"\n    by (force simp: carrier_Characters characters_def)\n  thus ?thesis using that restrict_char_def by metis\nqed\n\ntext \\<open>For two characters on a group \\<open>G\\<close> the number of characters on subgroup \\<open>H\\<close> that share the\nvalues with them is the same for both.\\<close>\n\nlemma (in finite_comm_group) character_restrict_card: \n  assumes \"subgroup H G\" \"character G a\" \"character G b\"\n  shows   \"card {\\<chi>'\\<in>characters G. \\<forall>x\\<in>H. \\<chi>' x = a x} = card {\\<chi>'\\<in>characters G. \\<forall>x\\<in>H. \\<chi>' x = b x}\"\nproof -\n  interpret H: subgroup H G by fact\n  interpret H: finite_comm_group \"G\\<lparr>carrier := H\\<rparr>\" using assms(1)\n    by (simp add: subgroup_imp_finite_comm_group)\n  interpret CG: finite_comm_group \"Characters G\" using finite_comm_group_Characters .\n  interpret a: character G a by fact\n  interpret b: character G b by fact\n  have ac: \"a \\<in> carrier (Characters G)\" unfolding Characters_def characters_def using assms by simp\n  have bc: \"b \\<in> carrier (Characters G)\" unfolding Characters_def characters_def using assms by simp\n  define f where f: \"f = (\\<lambda>c. b \\<otimes>\\<^bsub>Characters G\\<^esub> inv\\<^bsub>Characters G\\<^esub> a \\<otimes>\\<^bsub>Characters G\\<^esub> c)\"\n  define g where g: \"g = (\\<lambda>c. a \\<otimes>\\<^bsub>Characters G\\<^esub> inv\\<^bsub>Characters G\\<^esub> b \\<otimes>\\<^bsub>Characters G\\<^esub> c)\"\n  let ?A = \"{\\<chi>'\\<in>characters G. \\<forall>x\\<in>H. \\<chi>' x = a x}\"\n  let ?B = \"{\\<chi>'\\<in>characters G. \\<forall>x\\<in>H. \\<chi>' x = b x}\"\n  have \"bij_betw f ?A ?B\"\n  proof(intro bij_betwI[of _ _ _ g])\n    show \"f \\<in> ?A \\<rightarrow> ?B\"\n    proof\n      show \"f x \\<in> ?B\" if x: \"x \\<in> ?A\" for x\n      proof -\n        interpret xc: character G x using x unfolding characters_def by blast\n        have xc: \"x \\<in> carrier (Characters G)\" using x unfolding Characters_def by simp\n        have \"f x y = b y\" if y: \"y \\<in> H\" for y\n        proof -\n          have \"(inv\\<^bsub>Characters G\\<^esub> a) y * a y =  1\"\n            by (simp add: a.inv_Characters a.mult_inv_character mult.commute principal_char_def y)\n          thus ?thesis unfolding f mult_Characters using x y by fastforce\n        qed\n        thus \"f x \\<in> ?B\" unfolding f carrier_Characters[symmetric] using ac bc xc by blast\n      qed\n    qed\n    show \"g \\<in> ?B \\<rightarrow> ?A\"\n    proof\n      show \"g x \\<in> ?A\" if x: \"x \\<in> ?B\" for x\n      proof -\n        interpret xc: character G x using x unfolding characters_def by blast\n        have xc: \"x \\<in> carrier (Characters G)\" using x unfolding Characters_def by simp\n        have \"g x y = a y\" if y: \"y \\<in> H\" for y\n        proof -\n          have \"(inv\\<^bsub>Characters G\\<^esub> b) y * x y = 1\" using x y\n            by (simp add: b.inv_Characters b.mult_inv_character mult.commute principal_char_def)\n          thus ?thesis unfolding g mult_Characters by simp\n        qed\n        thus \"g x \\<in> ?A\" unfolding g carrier_Characters[symmetric] using ac bc xc by blast\n      qed\n    qed\n    show \"g (f x) = x\" if x: \"x \\<in> ?A\" for x\n    proof -\n      have xc: \"x \\<in> carrier (Characters G)\" using x unfolding Characters_def by force\n      with ac bc show ?thesis unfolding f g\n        by (auto simp: CG.m_assoc[symmetric],\n            metis CG.inv_closed CG.inv_comm CG.l_inv CG.m_assoc CG.r_one)\n    qed\n    show \"f (g x) = x\" if x: \"x \\<in> ?B\" for x\n    proof -\n      have xc: \"x \\<in> carrier (Characters G)\" using x unfolding Characters_def by force\n      with ac bc show ?thesis unfolding f g\n        by (auto simp: CG.m_assoc[symmetric],\n            metis CG.inv_closed CG.inv_comm CG.l_inv CG.m_assoc CG.r_one)\n    qed\n  qed\n  thus ?thesis using bij_betw_same_card by blast\nqed\n\ntext \\<open>These lemmas allow to show that the number of extensions of a character on \\<open>H\\<close> to a\ncharacter on \\<open>G\\<close> is just $|G|/|H|$.\\<close>\n\ntheorem (in finite_comm_group) card_character_extensions:\n  assumes \"subgroup H G\" \"character (G\\<lparr>carrier := H\\<rparr>) \\<chi>\"\n  shows   \"card {\\<chi>'\\<in>characters G. \\<forall>x\\<in>H. \\<chi>' x = \\<chi> x} * card H = order G\"\nproof -\n  interpret H: subgroup H G by fact\n  interpret H: finite_comm_group \"G\\<lparr>carrier := H\\<rparr>\"\n    using subgroup_imp_finite_comm_group[OF assms(1)] .\n  interpret chi: character \"G\\<lparr>carrier := H\\<rparr>\" \\<chi> by fact\n  interpret C: finite_comm_group \"Characters G\" using finite_comm_group_Characters .\n  interpret Mod: finite_comm_group \"G Mod H\" using finite_comm_FactGroup[OF assms(1)] .\n  obtain a where a: \"a \\<in> carrier (Characters G)\" \"restrict_char H a = \\<chi>\"\n  proof -\n    have \"\\<exists>a\\<in>carrier (Characters G). restrict_char H a = \\<chi>\"\n      using restrict_char_image[OF assms(1)] assms(2)\n      unfolding carrier_Characters characters_def image_def by force\n    thus ?thesis using that by blast\n  qed\n  show ?thesis\n  proof -\n    have p: \"{\\<chi>\\<in>characters G. \\<forall>x\\<in>H. \\<chi> x = 1} = {\\<chi>\\<in>characters G. \\<forall>x\\<in>H. \\<chi> x = principal_char G x}\"\n      unfolding principal_char_def by force\n    have ac: \"{\\<chi>'\\<in>characters G. \\<forall>x\\<in>H. \\<chi>' x = \\<chi> x} = {\\<chi>'\\<in>characters G. \\<forall>x\\<in>H. \\<chi>' x = a x}\"\n      using a(2) unfolding restrict_char_def by force\n    have \"card {\\<chi>\\<in>characters G. \\<forall>x\\<in>H. \\<chi> x = 1} = card {\\<chi>'\\<in>characters G. \\<forall>x\\<in>H. \\<chi>' x = \\<chi> x}\"\n      by (unfold ac p; intro character_restrict_card[OF assms(1)],\n          use a[unfolded Characters_def characters_def] in auto)\n    moreover have \"card {\\<chi>\\<in>characters G. \\<forall>x\\<in>H. \\<chi> x = 1} = card (carrier (G Mod H))\"\n      using iso_same_card[OF is_iso_Characters_FactGroup[OF assms(1)]]\n            Mod.order_Characters[unfolded order_def] by force\n    moreover have \"card (carrier (G Mod H)) * card H = order G\"\n      using lagrange[OF assms(1)] unfolding FactGroup_def by simp\n    ultimately show ?thesis by argo\n  qed\nqed\n\ntext \\<open>\n  Lastly, we can also show that for each $x\\in H$ of order $n > 1$ and each \\<open>n\\<close>-th root of\n  unity \\<open>z\\<close>, there exists a character \\<open>\\<chi>\\<close> on \\<open>G\\<close> such that $\\chi(x) = z$.\n\\<close>\n\nlemma (in group) powi_get_exp_self:\n  fixes z::complex\n  assumes \"z ^ n = 1\" \"x \\<in> carrier G\" \"ord x = n\" \"n > 1\"\n  shows \"z powi get_exp x x = z\"\nproof -\n  from assms have ngt0: \"n > 0\" by simp\n  from powi_mod[OF assms(1) ngt0, of \"get_exp x x\"] get_exp_self[OF assms(2), unfolded assms(3)]\n  have \"z powi get_exp x x = z powi (1 mod int n)\" by argo    \n  also have \"\\<dots> = z\" using assms(4) by simp\n  finally show ?thesis .\nqed\n\ncorollary (in finite_comm_group) character_with_value_exists:\n  assumes \"x \\<in> carrier G\" and \"x \\<noteq> \\<one>\" and \"z ^ ord x = 1\"\n  obtains \\<chi> where \"character G \\<chi>\" and \"\\<chi> x = z\"\nproof -\n  interpret H: subgroup \"generate G {x}\" G using generate_is_subgroup assms(1) by simp\n  interpret H: finite_comm_group \"G\\<lparr>carrier := generate G {x}\\<rparr>\"\n    using subgroup_imp_finite_comm_group[OF H.subgroup_axioms] . \n  interpret H: finite_cyclic_group \"G\\<lparr>carrier := generate G {x}\\<rparr>\" x\n  proof(unfold finite_cyclic_group_def, safe)\n    show \"finite_group (G\\<lparr>carrier := generate G {x}\\<rparr>)\" by unfold_locales\n    show \"cyclic_group (G\\<lparr>carrier := generate G {x}\\<rparr>) x\"\n    proof(intro H.cyclic_groupI0)\n      show \"x \\<in> carrier (G\\<lparr>carrier := generate G {x}\\<rparr>)\" using generate.incl[of x \"{x}\" G] by simp\n      show \"carrier (G\\<lparr>carrier := generate G {x}\\<rparr>) = generate (G\\<lparr>carrier := generate G {x}\\<rparr>) {x}\"\n        using generate_consistent[OF generate_sincl H.subgroup_axioms] by simp\n    qed\n  qed\n  have ox: \"H.ord x = ord x\" using H.gen_closed H.subgroup_axioms subgroup_ord_eq by auto\n  have ogt1: \"ord x > 1\" using ord_pos by (metis assms(1, 2) less_one nat_neq_iff ord_eq_1)\n  from assms H.unity_root_induce_char[unfolded H.ord_gen_is_group_order[symmetric] ox, OF assms(3)]\n  obtain c where c: \"character (G\\<lparr>carrier := generate G {x}\\<rparr>) c\"\n                    \"c = (\\<lambda>a. if a \\<in> carrier (G\\<lparr>carrier := generate G {x}\\<rparr>)\n                              then z powi H.get_exp x a else 0)\" by blast\n  have cx: \"c x = z\" unfolding c(2)\n    using H.powi_get_exp_self[OF assms(3) _ ox ogt1] generate_sincl[of \"{x}\"] by simp\n  obtain f where f: \"character G f\" \"\\<And>y. y \\<in> (generate G {x}) \\<Longrightarrow> f y = c y\"\n    using character_extension_exists[OF H.subgroup_axioms c(1)] by blast\n  show ?thesis by (intro that[OF f(1)], use cx f(2) generate_sincl in blast)\nqed\n\ntext \\<open>\n  In particular, for any \\<open>x\\<close> that is not the identity element, there exists a character \\<open>\\<chi>\\<close>\n  such that $\\chi(x)\\neq 1$.\n\\<close>\ncorollary (in finite_comm_group) character_neq_1_exists:\n  assumes \"x \\<in> carrier G\" and \"x \\<noteq> \\<one>\"\n  obtains \\<chi> where \"character G \\<chi>\" and \"\\<chi> x \\<noteq> 1\"\nproof -\n  define z where \"z = cis (2 * pi / ord x)\"\n  have z_pow_h: \"z ^ ord x = 1\"\n    by (auto simp: z_def DeMoivre)\n\n  from assms have \"ord x \\<ge> 1\" by (intro ord_ge_1) auto\n  moreover have \"ord x \\<noteq> 1\"\n    using pow_ord_eq_1[of x] assms fin by (intro notI) simp_all\n  ultimately have \"ord x > 1\" by linarith\n\n  have [simp]: \"z \\<noteq> 1\"\n  proof\n    assume \"z = 1\"\n    have \"bij_betw (\\<lambda>k. cis (2 * pi * real k / real (ord x))) {..<ord x} {z. z ^ ord x = 1}\"\n      using \\<open>ord x > 1\\<close> by (intro bij_betw_roots_unity) auto\n    hence inj: \"inj_on (\\<lambda>k. cis (2 * pi * real k / real (ord x))) {..<ord x}\"\n      by (auto simp: bij_betw_def)\n    have \"0 = (1 :: nat)\"\n      using \\<open>z = 1\\<close> and \\<open>ord x > 1\\<close> by (intro inj_onD[OF inj]) (auto simp: z_def)\n    thus False by simp\n  qed\n\n  obtain \\<chi> where \"character G \\<chi>\" and \"\\<chi> x = z\"\n    using character_with_value_exists[OF assms z_pow_h] .\n  thus ?thesis using that[of \\<chi>] by simp\nqed\n\nsubsection \\<open>The first orthogonality relation\\<close>\n\ntext \\<open>\n  The entries of any non-principal character sum to 0.\n\\<close>\ntheorem (in character) sum_character:\n  \"(\\<Sum>x\\<in>carrier G. \\<chi> x) = (if \\<chi> = principal_char G then of_nat (order G) else 0)\"\nproof (cases \"\\<chi> = principal_char G\")\n  case True\n  hence \"(\\<Sum>x\\<in>carrier G. \\<chi> x) = (\\<Sum>x\\<in>carrier G. 1)\"\n    by (intro sum.cong) (auto simp: principal_char_def)\n  also have \"\\<dots> = order G\" by (simp add: order_def)\n  finally show ?thesis using True by simp\nnext\n  case False\n  define S where \"S = (\\<Sum>x\\<in>carrier G. \\<chi> x)\"\n  from False obtain y where y: \"y \\<in> carrier G\" \"\\<chi> y \\<noteq> 1\"\n    by (auto simp: principal_char_def fun_eq_iff char_eq_0_iff split: if_splits)\n  from y have \"S = (\\<Sum>x\\<in>carrier G. \\<chi> (y \\<otimes> x))\" unfolding S_def\n    by (intro sum.reindex_bij_betw [symmetric] bij_betw_mult_left)\n  also have \"\\<dots> = (\\<Sum>x\\<in>carrier G. \\<chi> y * \\<chi> x)\"\n    by (intro sum.cong refl char_mult y)\n  also have \"\\<dots> = \\<chi> y * S\" by (simp add: S_def sum_distrib_left)\n  finally have \"(\\<chi> y - 1) * S = 0\" by (simp add: algebra_simps)\n  with y have \"S = 0\" by simp\n  with False show ?thesis by (simp add: S_def)\nqed\n\ncorollary (in finite_comm_group) character_orthogonality1:\n  assumes \"character G \\<chi>\" and \"character G \\<chi>'\"\n  shows   \"(\\<Sum>x\\<in>carrier G. \\<chi> x * cnj (\\<chi>' x)) = (if \\<chi> = \\<chi>' then of_nat (order G) else 0)\"\nproof -\n  define C where [simp]: \"C = Characters G\"\n  interpret C: finite_comm_group C unfolding C_def\n    by (rule finite_comm_group_Characters)\n  let ?\\<chi> = \"\\<lambda>x. \\<chi> x * inv_character \\<chi>' x\"\n  interpret character G \"\\<lambda>x. \\<chi> x * inv_character \\<chi>' x\"\n    by (intro character_mult character.inv_character assms)\n  have \"(\\<Sum>x\\<in>carrier G. \\<chi> x * cnj (\\<chi>' x)) = (\\<Sum>x\\<in>carrier G. ?\\<chi> x)\"\n    by (intro sum.cong) (auto simp: inv_character_def)\n  also have \"\\<dots> = (if ?\\<chi> = principal_char G then of_nat (order G) else 0)\"\n    by (rule sum_character)\n  also have \"?\\<chi> = principal_char G \\<longleftrightarrow> \\<chi> \\<otimes>\\<^bsub>C\\<^esub> inv\\<^bsub>C\\<^esub> \\<chi>' = \\<one>\\<^bsub>C\\<^esub>\"\n    using assms by (simp add: Characters_simps characters_def)\n  also have \"\\<dots> \\<longleftrightarrow> \\<chi> = \\<chi>'\"\n  proof\n    assume \"\\<chi> \\<otimes>\\<^bsub>C\\<^esub> inv\\<^bsub>C\\<^esub> \\<chi>' = \\<one>\\<^bsub>C\\<^esub>\"\n    from C.inv_equality [OF this] and assms show \"\\<chi> = \\<chi>'\"\n      by (auto simp: characters_def Characters_simps)\n  next\n    assume *: \"\\<chi> = \\<chi>'\"\n    from assms show \"\\<chi> \\<otimes>\\<^bsub>C\\<^esub> inv\\<^bsub>C\\<^esub> \\<chi>' = \\<one>\\<^bsub>C\\<^esub>\" \n      by (subst *, intro C.r_inv) (auto simp: carrier_Characters characters_def)\n  qed\n  finally show ?thesis .\nqed\n\n\nsubsection \\<open>The isomorphism between a group and its double dual\\<close>\n\ntext \\<open>\n  Lastly, we show that the double dual of a finite abelian group is naturally isomorphic\n  to the original group via the obvious isomorphism $x\\mapsto (\\chi\\mapsto \\chi(x))$.\n  It is easy to see that this is a homomorphism and that it is injective. The fact \n  $|\\widehat{\\widehat{G}}| = |\\widehat{G}| = |G|$ then shows that it is also surjective.\n\\<close>\ncontext finite_comm_group\nbegin\n\ndefinition double_dual_iso :: \"'a \\<Rightarrow> ('a \\<Rightarrow> complex) \\<Rightarrow> complex\" where\n  \"double_dual_iso x = (\\<lambda>\\<chi>. if character G \\<chi> then \\<chi> x else 0)\"\n\nlemma double_dual_iso_apply [simp]: \"character G \\<chi> \\<Longrightarrow> double_dual_iso x \\<chi> = \\<chi> x\"\n  by (simp add: double_dual_iso_def)\n\nlemma character_double_dual_iso [intro]:\n  assumes x: \"x \\<in> carrier G\"\n  shows   \"character (Characters G) (double_dual_iso x)\"\nproof -\n  interpret G': finite_comm_group \"Characters G\"\n    by (rule finite_comm_group_Characters)\n  show \"character (Characters G) (double_dual_iso x)\"\n    using x by unfold_locales (auto simp: double_dual_iso_def characters_def Characters_def\n                                              principal_char_def character.char_eq_0)\nqed\n\nlemma double_dual_iso_mult [simp]:\n  assumes \"x \\<in> carrier G\" \"y \\<in> carrier G\"\n  shows   \"double_dual_iso (x \\<otimes> y) =\n             double_dual_iso x \\<otimes>\\<^bsub>Characters (Characters G)\\<^esub> double_dual_iso y\"\n  using assms by (auto simp: double_dual_iso_def Characters_def fun_eq_iff character.char_mult)\n\nlemma double_dual_iso_one [simp]:\n  \"double_dual_iso \\<one> = principal_char (Characters G)\"\n  by (auto simp: fun_eq_iff double_dual_iso_def principal_char_def\n                 carrier_Characters characters_def character.char_one)\n\nlemma inj_double_dual_iso: \"inj_on double_dual_iso (carrier G)\"\nproof -\n  interpret G': finite_comm_group \"Characters G\"\n    by (rule finite_comm_group_Characters)\n  interpret G'': finite_comm_group \"Characters (Characters G)\"\n    by (rule G'.finite_comm_group_Characters)\n  have hom: \"double_dual_iso \\<in> hom G (Characters (Characters G))\"\n    by (rule homI) (auto simp: carrier_Characters characters_def)\n  have inj_aux: \"x = \\<one>\"\n    if x: \"x \\<in> carrier G\" \"double_dual_iso x = \\<one>\\<^bsub>Characters (Characters G)\\<^esub>\" for x\n  proof (rule ccontr)\n    assume \"x \\<noteq> \\<one>\"\n    obtain \\<chi> where \\<chi>: \"character G \\<chi>\" \"\\<chi> x \\<noteq> 1\"\n      using character_neq_1_exists[OF x(1) \\<open>x \\<noteq> \\<one>\\<close>] .\n    from x have \"\\<forall>\\<chi>. (if \\<chi> \\<in> characters G then \\<chi> x else 0) = (if \\<chi> \\<in> characters G then 1 else 0)\"\n      by (auto simp: double_dual_iso_def Characters_def fun_eq_iff\n                     principal_char_def characters_def)\n    hence eq1: \"\\<forall>\\<chi>\\<in>characters G. \\<chi> x = 1\" by metis\n    with \\<chi> show False unfolding characters_def by auto\n  qed\n  thus ?thesis\n    using inj_aux hom is_group G''.is_group by (subst inj_on_one_iff') auto\nqed\n\nlemma double_dual_iso_eq_iff [simp]:\n  \"x \\<in> carrier G \\<Longrightarrow> y \\<in> carrier G \\<Longrightarrow> double_dual_iso x = double_dual_iso y \\<longleftrightarrow> x = y\"\n  by (auto dest: inj_onD[OF inj_double_dual_iso])\n\ntheorem double_dual_iso: \"double_dual_iso \\<in> iso G (Characters (Characters G))\"\nproof (rule isoI)\n  interpret G': finite_comm_group \"Characters G\"\n    by (rule finite_comm_group_Characters)\n  interpret G'': finite_comm_group \"Characters (Characters G)\"\n    by (rule G'.finite_comm_group_Characters)\n\n  show hom: \"double_dual_iso \\<in> hom G (Characters (Characters G))\"\n    by (rule homI) (auto simp: carrier_Characters characters_def)\n\n  show \"bij_betw double_dual_iso (carrier G) (carrier (Characters (Characters G)))\"\n    unfolding bij_betw_def\n  proof\n    show \"inj_on double_dual_iso (carrier G)\" by (fact inj_double_dual_iso)\n  next\n    show \"double_dual_iso ` carrier G = carrier (Characters (Characters G))\"\n    proof (rule card_subset_eq)\n      show \"finite (carrier (Characters (Characters G)))\"\n        by (fact G''.fin)\n    next\n      have \"card (carrier (Characters (Characters G))) = card (carrier G)\"\n        by (simp add: carrier_Characters G'.card_characters card_characters order_def)\n      also have \"\\<dots> = card (double_dual_iso ` carrier G)\"\n        by (intro card_image [symmetric] inj_double_dual_iso)\n      finally show \"card (double_dual_iso ` carrier G) =\n                      card (carrier (Characters (Characters G)))\" ..\n    next\n      show \"double_dual_iso ` carrier G \\<subseteq> carrier (Characters (Characters G))\"\n        using hom by (auto simp: hom_def)\n    qed\n  qed\nqed\n\nlemma double_dual_is_iso: \"Characters (Characters G) \\<cong> G\"\n  by (rule iso_sym) (use double_dual_iso in \\<open>auto simp: is_iso_def\\<close>)\n\ntext \\<open>\n  The second orthogonality relation follows from the first one via Pontryagin duality:\n\\<close>\ntheorem sum_characters:\n  assumes x: \"x \\<in> carrier G\"\n  shows   \"(\\<Sum>\\<chi>\\<in>characters G. \\<chi> x) = (if x = \\<one> then of_nat (order G) else 0)\"\nproof -\n  interpret G': finite_comm_group \"Characters G\"\n    by (rule finite_comm_group_Characters)\n  interpret x: character \"Characters G\" \"double_dual_iso x\"\n    using x by auto\n  from x.sum_character show ?thesis using double_dual_iso_eq_iff[of x \\<one>] x\n    by (auto simp: characters_def carrier_Characters order_Characters simp del: double_dual_iso_eq_iff)\nqed\n\ncorollary character_orthogonality2:\n  assumes \"x \\<in> carrier G\" \"y \\<in> carrier G\"\n  shows   \"(\\<Sum>\\<chi>\\<in>characters G. \\<chi> x * cnj (\\<chi> y)) = (if x = y then of_nat (order G) else 0)\"\nproof -\n  from assms have \"(\\<Sum>\\<chi>\\<in>characters G. \\<chi> x * cnj (\\<chi> y)) = (\\<Sum>\\<chi>\\<in>characters G. \\<chi> (x \\<otimes> inv y))\"\n    by (intro sum.cong) (simp_all add: character.char_inv character.char_mult characters_def)\n  also from assms have \"\\<dots> = (if x \\<otimes> inv y = \\<one> then of_nat (order G) else 0)\"\n    by (intro sum_characters) auto\n  also from assms have \"x \\<otimes> inv y = \\<one> \\<longleftrightarrow> x = y\"\n    using inv_equality[of x \"inv y\"] by auto\n  finally show ?thesis .\nqed\n\nend\n\nno_notation integer_mod_group (\"Z\")\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_L/Multiplicative_Characters.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8670357563664175, "lm_q2_score": 0.8459424334245617, "lm_q1q2_score": 0.7334623376067126}}
{"text": "(*<*)\ntheory simplification imports Main begin\n(*>*)\n\ntext\\<open>\nOnce we have proved all the termination conditions, the \\isacommand{recdef} \nrecursion equations become simplification rules, just as with\n\\isacommand{primrec}. In most cases this works fine, but there is a subtle\nproblem that must be mentioned: simplification may not\nterminate because of automatic splitting of \\<open>if\\<close>.\n\\index{*if expressions!splitting of}\nLet us look at an example:\n\\<close>\n\nconsts gcd :: \"nat\\<times>nat \\<Rightarrow> nat\"\nrecdef gcd \"measure (\\<lambda>(m,n).n)\"\n  \"gcd (m, n) = (if n=0 then m else gcd(n, m mod n))\"\n\ntext\\<open>\\noindent\nAccording to the measure function, the second argument should decrease with\neach recursive call. The resulting termination condition\n@{term[display]\"n ~= (0::nat) ==> m mod n < n\"}\nis proved automatically because it is already present as a lemma in\nHOL\\@.  Thus the recursion equation becomes a simplification\nrule. Of course the equation is nonterminating if we are allowed to unfold\nthe recursive call inside the \\<open>else\\<close> branch, which is why programming\nlanguages and our simplifier don't do that. Unfortunately the simplifier does\nsomething else that leads to the same problem: it splits \neach \\<open>if\\<close>-expression unless its\ncondition simplifies to @{term True} or @{term False}.  For\nexample, simplification reduces\n@{term[display]\"gcd(m,n) = k\"}\nin one step to\n@{term[display]\"(if n=0 then m else gcd(n, m mod n)) = k\"}\nwhere the condition cannot be reduced further, and splitting leads to\n@{term[display]\"(n=0 --> m=k) & (n ~= 0 --> gcd(n, m mod n)=k)\"}\nSince the recursive call @{term\"gcd(n, m mod n)\"} is no longer protected by\nan \\<open>if\\<close>, it is unfolded again, which leads to an infinite chain of\nsimplification steps. Fortunately, this problem can be avoided in many\ndifferent ways.\n\nThe most radical solution is to disable the offending theorem\n@{thm[source]if_split},\nas shown in \\S\\ref{sec:AutoCaseSplits}.  However, we do not recommend this\napproach: you will often have to invoke the rule explicitly when\n\\<open>if\\<close> is involved.\n\nIf possible, the definition should be given by pattern matching on the left\nrather than \\<open>if\\<close> on the right. In the case of @{term gcd} the\nfollowing alternative definition suggests itself:\n\\<close>\n\nconsts gcd1 :: \"nat\\<times>nat \\<Rightarrow> nat\"\nrecdef gcd1 \"measure (\\<lambda>(m,n).n)\"\n  \"gcd1 (m, 0) = m\"\n  \"gcd1 (m, n) = gcd1(n, m mod n)\"\n\n\ntext\\<open>\\noindent\nThe order of equations is important: it hides the side condition\n@{prop\"n ~= (0::nat)\"}.  Unfortunately, in general the case distinction\nmay not be expressible by pattern matching.\n\nA simple alternative is to replace \\<open>if\\<close> by \\<open>case\\<close>, \nwhich is also available for @{typ bool} and is not split automatically:\n\\<close>\n\nconsts gcd2 :: \"nat\\<times>nat \\<Rightarrow> nat\"\nrecdef gcd2 \"measure (\\<lambda>(m,n).n)\"\n  \"gcd2(m,n) = (case n=0 of True \\<Rightarrow> m | False \\<Rightarrow> gcd2(n,m mod n))\"\n\ntext\\<open>\\noindent\nThis is probably the neatest solution next to pattern matching, and it is\nalways available.\n\nA final alternative is to replace the offending simplification rules by\nderived conditional ones. For @{term gcd} it means we have to prove\nthese lemmas:\n\\<close>\n\n\n\nlemma [simp]: \"n \\<noteq> 0 \\<Longrightarrow> gcd(m, n) = gcd(n, m mod n)\"\napply(simp)\ndone\n\ntext\\<open>\\noindent\nSimplification terminates for these proofs because the condition of the \\<open>if\\<close> simplifies to @{term True} or @{term False}.\nNow we can disable the original simplification rule:\n\\<close>\n\ndeclare gcd.simps [simp del]\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/Recdef/simplification.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430520409023, "lm_q2_score": 0.8824278710924296, "lm_q1q2_score": 0.7334237939857179}}
{"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_TSortSorts\nimports \"../../Test_Base\"\nbegin\n\ndatatype 'a list = nil2 | cons2 \"'a\" \"'a list\"\n\ndatatype Tree = TNode \"Tree\" \"int\" \"Tree\" | TNil\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 flatten :: \"Tree => int list => int list\" where\n\"flatten (TNode p z q) y = flatten p (cons2 z (flatten q y))\"\n| \"flatten (TNil) y = y\"\n\nfun add :: \"int => Tree => Tree\" where\n\"add x (TNode p z q) =\n   (if x <= z then TNode (add x p) z q else TNode p z (add x q))\"\n| \"add x (TNil) = TNode TNil x TNil\"\n\nfun toTree :: \"int list => Tree\" where\n\"toTree (nil2) = TNil\"\n| \"toTree (cons2 y xs) = add y (toTree xs)\"\n\nfun tsort :: \"int list => int 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_TSortSorts.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505428129514, "lm_q2_score": 0.810478913248044, "lm_q1q2_score": 0.733200188808294}}
{"text": "(*  \n    Title:      Inverse_IArrays.thy\n    Author:     Jose Divas\u00f3n <jose.divasonm at unirioja.es>\n    Author:     Jes\u00fas Aransay <jesus-maria.aransay at unirioja.es>\n*)\n\nsection\\<open>Inverse of a matrix using the Gauss Jordan algorithm over nested IArrays\\<close>\n\ntheory Inverse_IArrays\nimports \n  Inverse\n  Gauss_Jordan_PA_IArrays\nbegin\n\nsubsection\\<open>Definitions\\<close>\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\\<open>Some lemmas and code generation\\<close>\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": "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/Inverse_IArrays.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9046505351008904, "lm_q2_score": 0.8104789155369048, "lm_q1q2_score": 0.7332001846284503}}
{"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\nheader {* Cantor pairing function *}\n\ntheory CPair\nimports Main\nbegin\n\ntext {*\n  We introduce a particular coding @{text \"c_pair\"} from ordered pairs\n  of natural numbers to natural numbers.  See \\cite{Rogers} and the\n  Isabelle documentation for more information.\n*}\n\nsubsection {* Pairing function *}\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 {* Auxiliary lemmas *}\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 {* Basic properties of c\\_pair function *}\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 {* Inverse mapping *}\n\ntext {*\n  @{text \"c_fst\"} and @{text \"c_snd\"} are the functions which yield\n  the inverse mapping to @{text \"c_pair\"}.\n*}\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", "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/Recursion-Theory-I/CPair.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8688267660487572, "lm_q2_score": 0.8438950986284991, "lm_q1q2_score": 0.7331986494257958}}
{"text": "theory simp_playground\n  imports Main\nbegin\n\ndatatype 'a boolexp =\n   TRUE \n  | FALSE \n  | Var 'a \n  | Not \"'a boolexp\"\n  | And \"'a boolexp\" \"'a boolexp\"\n  | Or \"'a boolexp\" \"'a boolexp\"\n  | Implies \"'a boolexp\" \"'a boolexp\"\nprint_theorems\n\nfun boolexp_eval :: \"('a \\<Rightarrow> bool) \\<Rightarrow> 'a boolexp \\<Rightarrow> bool\" where\n   \"boolexp_eval env TRUE = True\"\n | \"boolexp_eval env FALSE = False\"\n | \"boolexp_eval env (Var x) = env x\"\n | \"boolexp_eval env (Not b) = (\\<not> (boolexp_eval env b))\"\n | \"boolexp_eval env (And a b) = ((boolexp_eval env a) \\<and> (boolexp_eval env b))\"\n | \"boolexp_eval env (Or a b) = ((boolexp_eval env a) \\<or> (boolexp_eval env b))\"\n | \"boolexp_eval env (Implies a b) = ((\\<not> (boolexp_eval env a)) \\<or> (boolexp_eval env b))\"\n\ndefinition env1 where \"env1 \\<equiv> (\\<lambda> x. case x of (0::nat) \\<Rightarrow> True | _ \\<Rightarrow> False)\"\n\nvalue \"boolexp_eval env1 (Not (Var (1::nat)))\"\n\nlemma  \"boolexp_eval env1 (Not (Var (1::nat))) = True\"\n  apply (simp only: env1_def)\n  apply (simp only: boolexp_eval.simps(4))\n  by simp\n\nlemma \"A \\<longrightarrow> A \\<and> B = (if A then B else False)\" by simp\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/other/simp_playground.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122163480668, "lm_q2_score": 0.8080672158638527, "lm_q1q2_score": 0.7331692565836438}}
{"text": "(* \n  Title: Closure and Co-Closure Operators\n  Author: Georg Struth \n  Maintainer: Georg Struth <g.struth@sheffield.ac.uk> \n*)\n\nsection \\<open>Closure and Co-Closure Operators\\<close>\n\ntheory Closure_Operators\n  imports Galois_Connections \n\nbegin\n\nsubsection \\<open>Closure Operators\\<close>\n\ntext \\<open>Closure and coclosure operators in orders and complete lattices are defined in this section,\nand some basic properties are proved. Isabelle infers the appropriate types. Facts are \ntaken mainly from the Compendium of Continuous Lattices~\\<^cite>\\<open>\"GierzHKLMS80\"\\<close> and \nRosenthal's book on quantales~\\<^cite>\\<open>\"Rosenthal90\"\\<close>.\\<close>\n\ndefinition clop :: \"('a::order \\<Rightarrow> 'a) \\<Rightarrow> bool\" where\n  \"clop f = (id \\<le> f \\<and> mono f \\<and> f \\<circ> f \\<le> f)\"\n\nlemma clop_extensive: \"clop f \\<Longrightarrow> id \\<le> f\"\n  by (simp add: clop_def)\n\nlemma clop_extensive_var: \"clop f \\<Longrightarrow> x \\<le> f x\"\n  by (simp add: clop_def le_fun_def)\n\nlemma clop_iso: \"clop f \\<Longrightarrow> mono f\"\n  by (simp add: clop_def)\n\nlemma clop_iso_var: \"clop f \\<Longrightarrow> x \\<le> y \\<Longrightarrow> f x \\<le> f y\"\n  by (simp add: clop_def mono_def)\n\nlemma clop_idem: \"clop f \\<Longrightarrow> f \\<circ> f = f\"\n  by (simp add: antisym clop_def le_fun_def)\n\nlemma clop_Fix_range: \"clop f \\<Longrightarrow> (Fix f = range f)\"\n  by (simp add: clop_idem retraction_prop_fix)\n\n\n\nlemma clop_Inf_closed_var: \n  fixes f :: \"'a::complete_lattice \\<Rightarrow> 'a\" \n  shows \"clop f \\<Longrightarrow> f \\<circ> Inf \\<circ> (`) f  = Inf \\<circ> (`) f\"    \n  unfolding clop_def mono_def comp_def le_fun_def \n  by (metis (mono_tags, lifting) antisym id_apply le_INF_iff order_refl)\n\nlemma clop_top:\n  fixes f :: \"'a::complete_lattice \\<Rightarrow> 'a\"\n  shows \"clop f \\<Longrightarrow> f \\<top> = \\<top>\"\n  by (simp add: clop_extensive_var top.extremum_uniqueI)\n\nlemma \"clop (f::'a::complete_lattice \\<Rightarrow> 'a) \\<Longrightarrow> f (\\<Squnion>x \\<in> X. f x) = (\\<Squnion>x \\<in> X. f x)\" (*nitpick*)\n  oops\n\nlemma \"clop (f::'a::complete_lattice \\<Rightarrow> 'a) \\<Longrightarrow> f (f x \\<squnion> f y) = f x \\<squnion> f y\" (*nitpick*)\n  oops\n\nlemma  \"clop (f::'a::complete_lattice \\<Rightarrow> 'a) \\<Longrightarrow> f \\<bottom> = \\<bottom>\" (*nitpick *)\n  oops\n  \nlemma \"clop (f::'a set \\<Rightarrow> 'a set) \\<Longrightarrow> f (\\<Squnion>x \\<in> X. f x) = (\\<Squnion>x \\<in> X. f x)\" (*nitpick*)\n  oops\n\nlemma \"clop (f::'a set \\<Rightarrow> 'a set) \\<Longrightarrow> f (f x \\<squnion> f y) = f x \\<squnion> f y\" (*nitpick*)\n  oops\n\nlemma  \"clop (f::'a set \\<Rightarrow> 'a set) \\<Longrightarrow> f \\<bottom> = \\<bottom>\" (*nitpick *)\n  oops\n\nlemma clop_closure: \"clop f \\<Longrightarrow> (x \\<in> range f) = (f x = x)\"\n  by (simp add: clop_idem retraction_prop)\n\nlemma clop_closure_set: \"clop f \\<Longrightarrow> range f = Fix f\"\n  by (simp add: clop_Fix_range)\n\nlemma clop_closure_prop: \"(clop::('a::complete_lattice_with_dual\\<Rightarrow> 'a) \\<Rightarrow> bool) (Inf \\<circ> \\<up>)\"\n  by (simp add: clop_def mono_def)\n\nlemma clop_closure_prop_var: \"clop (\\<lambda>x::'a::complete_lattice. \\<Sqinter>{y. x \\<le> y})\"\n  unfolding clop_def comp_def le_fun_def mono_def by (simp add: Inf_lower le_Inf_iff)\n\nlemma clop_alt: \"(clop f) = (\\<forall>x y. x \\<le> f y \\<longleftrightarrow> f x \\<le> f y)\"\n  unfolding clop_def mono_def le_fun_def comp_def id_def by (meson dual_order.refl order_trans)\n\ntext \\<open>Finally it is shown that adjoints in a Galois connection yield closure operators.\\<close>\n\nlemma clop_adj: \n  fixes f :: \"'a::order \\<Rightarrow> 'b::order\"\n  shows \"f \\<stileturn> g \\<Longrightarrow> clop (g \\<circ> f)\"\n  by (simp add: adj_cancel2 adj_idem2 adj_iso4 clop_def)\n\ntext \\<open>Closure operators are monads for posets, and monads arise from adjunctions. \nThis fact is not formalised at this point. But here is the first step: every function \ncan be decomposed into a surjection followed by an injection.\\<close>\n\ndefinition \"surj_on f Y = (\\<forall>y \\<in> Y. \\<exists>x. y = f x)\"\n\nlemma surj_surj_on: \"surj f \\<Longrightarrow> surj_on f Y\"\n  by (simp add: surjD surj_on_def)\n\nlemma fun_surj_inj: \"\\<exists>g h. f = g \\<circ> h \\<and> surj_on h (range f) \\<and> inj_on g (range f)\"\nproof-\n  obtain h where a: \"\\<forall>x. f x = h x\"\n    by blast\n  then have \"surj_on h (range f)\"\n    by (metis (mono_tags, lifting) imageE surj_on_def)\n  then show ?thesis\n    unfolding inj_on_def surj_on_def fun_eq_iff using a by auto\nqed\n\ntext \\<open>Connections between downsets, upsets and closure operators are outlined next.\\<close>\n\nlemma preorder_clop: \"clop (\\<Down>::'a::preorder set \\<Rightarrow> 'a set)\"\n  by (simp add: clop_def downset_set_ext downset_set_iso)\n\nlemma clop_preorder_aux: \"clop f \\<Longrightarrow> (x \\<in> f {y} \\<longleftrightarrow> f {x} \\<subseteq> f {y})\"\n  by (simp add: clop_alt)\n\nlemma clop_preorder: \"clop f \\<Longrightarrow> class.preorder (\\<lambda>x y. f {x} \\<subseteq> f {y}) (\\<lambda>x y. f {x} \\<subset> f {y})\"\n  unfolding clop_def mono_def le_fun_def id_def comp_def by standard (auto simp: subset_not_subset_eq)\n\nlemma preorder_clop_dual: \"clop (\\<Up>::'a::preorder_with_dual set \\<Rightarrow> 'a set)\"\n  by (simp add: clop_def upset_set_anti upset_set_ext)\n\ntext \\<open>The closed elements of any closure operator over a complete lattice form an Inf-closed set (a Moore family).\\<close>\n\nlemma clop_Inf_closed: \n  fixes f :: \"'a::complete_lattice \\<Rightarrow> 'a\"\n  shows  \"clop f \\<Longrightarrow> Inf_closed_set (Fix f)\" \n  unfolding clop_def Inf_closed_set_def mono_def le_fun_def comp_def id_def Fix_def\n  by (smt Inf_greatest Inf_lower antisym mem_Collect_eq subsetCE)\n\nlemma clop_top_Fix: \n  fixes f :: \"'a::complete_lattice \\<Rightarrow> 'a\"\n  shows  \"clop f \\<Longrightarrow> \\<top> \\<in> Fix f\"\n  by (simp add: clop_Fix_range clop_closure clop_top)\n\n\ntext \\<open>Conversely, every Inf-closed subset of a complete lattice is the set of fixpoints of some closure operator.\\<close>\n \nlemma Inf_closed_clop: \n  fixes X :: \"'a::complete_lattice set\"\n  shows \"Inf_closed_set X \\<Longrightarrow> clop (\\<lambda>y. \\<Sqinter>{x \\<in> X. y \\<le> x})\"\n  by (smt Collect_mono_iff Inf_superset_mono clop_alt dual_order.trans le_Inf_iff mem_Collect_eq)\n\nlemma Inf_closed_clop_var: \n  fixes X :: \"'a::complete_lattice set\"\n  shows \"clop f \\<Longrightarrow> \\<forall>x \\<in> X. x \\<in> range f \\<Longrightarrow> \\<Sqinter>X \\<in> range f\"\n  by (metis Inf_closed_set_def clop_Fix_range clop_Inf_closed subsetI)\n\ntext \\<open>It is well known that downsets and upsets over an ordering form subalgebras of the complete powerset lattice.\\<close>\n\ntypedef (overloaded) 'a downsets = \"range (\\<Down>::'a::order set \\<Rightarrow> 'a set)\"\n  by fastforce\n\nsetup_lifting type_definition_downsets\n\ntypedef (overloaded) 'a upsets = \"range (\\<Up>::'a::order set \\<Rightarrow> 'a set)\"\n  by fastforce\n\nsetup_lifting type_definition_upsets\n\ninstantiation downsets :: (order) Inf_lattice\nbegin\n\nlift_definition Inf_downsets :: \"'a downsets set \\<Rightarrow> 'a downsets\" is \"Abs_downsets \\<circ> Inf \\<circ> (`) Rep_downsets\".\n  \nlift_definition less_eq_downsets :: \"'a downsets \\<Rightarrow> 'a downsets \\<Rightarrow> bool\" is \"\\<lambda>X Y. Rep_downsets X \\<subseteq> Rep_downsets Y\".\n\nlift_definition less_downsets :: \"'a downsets \\<Rightarrow> 'a downsets \\<Rightarrow> bool\" is \"\\<lambda>X Y. Rep_downsets X \\<subset> Rep_downsets Y\".\n\ninstance\n  apply intro_classes \n      apply (transfer, simp)\n     apply (transfer, blast)\n    apply (simp add: Closure_Operators.less_eq_downsets.abs_eq Rep_downsets_inject)\n   apply (transfer, smt Abs_downsets_inverse INF_lower Inf_closed_clop_var Rep_downsets image_iff o_def preorder_clop)\n  by transfer (smt comp_def Abs_downsets_inverse Inf_closed_clop_var Rep_downsets image_iff le_INF_iff preorder_clop)\n\nend\n\ninstantiation upsets :: (order_with_dual) Inf_lattice\nbegin\n\nlift_definition Inf_upsets :: \"'a upsets set \\<Rightarrow> 'a upsets\" is \"Abs_upsets \\<circ> Inf \\<circ> (`) Rep_upsets\".\n  \nlift_definition less_eq_upsets :: \"'a upsets \\<Rightarrow> 'a upsets \\<Rightarrow> bool\" is \"\\<lambda>X Y. Rep_upsets X \\<subseteq> Rep_upsets Y\".\n\nlift_definition less_upsets :: \"'a upsets \\<Rightarrow> 'a upsets \\<Rightarrow> bool\" is \"\\<lambda>X Y. Rep_upsets X \\<subset> Rep_upsets Y\".\n\ninstance\n  apply intro_classes\n      apply (transfer, simp)\n     apply (transfer, blast)\n    apply (simp add: Closure_Operators.less_eq_upsets.abs_eq Rep_upsets_inject)\n   apply (transfer, smt Abs_upsets_inverse Inf_closed_clop_var Inf_lower Rep_upsets comp_apply image_iff preorder_clop_dual)\n  by transfer (smt comp_def Abs_upsets_inverse Inf_closed_clop_var Inter_iff Rep_upsets image_iff preorder_clop_dual subsetCE subsetI)\n\nend\n\ntext \\<open>It has already been shown in the section on representations that the map ds, which maps elements of the order to its downset, is an order \nembedding. However, the duality between the underlying ordering and the lattices of up- and down-closed sets as categories can probably not be expressed, \nas there is no easy access to contravariant functors. \\<close>\n\n\nsubsection \\<open>Co-Closure Operators\\<close>\n                                \ntext \\<open>Next, the co-closure (or kernel) operation satisfies dual laws.\\<close>\n\ndefinition coclop :: \"('a::order \\<Rightarrow> 'a::order) \\<Rightarrow> bool\" where\n  \"coclop f = (f \\<le> id \\<and> mono f \\<and> f \\<le> f \\<circ> f)\"\n\nlemma coclop_dual: \"(coclop::('a::order_with_dual \\<Rightarrow> 'a) \\<Rightarrow> bool) = clop \\<circ> \\<partial>\\<^sub>F\"\n  unfolding coclop_def clop_def id_def mono_def map_dual_def comp_def fun_eq_iff le_fun_def\n  by (metis invol_dual_var ord_dual)\n\nlemma coclop_dual_var: \n  fixes f :: \"'a::order_with_dual \\<Rightarrow> 'a\"\n  shows \"coclop f = clop (\\<partial>\\<^sub>F f)\"\n  by (simp add: coclop_dual)\n\nlemma clop_dual: \"(clop::('a::order_with_dual \\<Rightarrow> 'a) \\<Rightarrow> bool) = coclop \\<circ> \\<partial>\\<^sub>F\"\n  by (simp add: coclop_dual comp_assoc map_dual_invol)\n\nlemma clop_dual_var: \n  fixes f :: \"'a::order_with_dual \\<Rightarrow> 'a\"\n  shows \"clop f = coclop (\\<partial>\\<^sub>F f)\"\n  by (simp add: clop_dual)\n\nlemma coclop_coextensive: \"coclop f \\<Longrightarrow> f \\<le> id\"\n  by (simp add: coclop_def)\n\nlemma coclop_coextensive_var: \"coclop f \\<Longrightarrow> f x \\<le> x\"\n  using coclop_def le_funD by fastforce\n\nlemma coclop_iso: \"coclop f \\<Longrightarrow> mono f\"\n  by (simp add: coclop_def)\n\nlemma coclop_iso_var: \"coclop f \\<Longrightarrow> (x \\<le> y \\<longrightarrow> f x \\<le> f y)\"\n  by (simp add: coclop_iso monoD)\n\nlemma coclop_idem: \"coclop f \\<Longrightarrow> f \\<circ> f = f\"\n  by (simp add: antisym coclop_def le_fun_def)\n\nlemma coclop_closure: \"coclop f \\<Longrightarrow> (x \\<in> range f) = (f x = x)\"\n  by (simp add: coclop_idem retraction_prop)\n\nlemma coclop_Fix_range: \"coclop f \\<Longrightarrow> (Fix f = range f)\"\n  by (simp add: coclop_idem retraction_prop_fix)\n\nlemma coclop_idem_var: \"coclop f \\<Longrightarrow> f (f x) = f x\"\n  by (simp add: coclop_idem retraction_prop)\n\nlemma coclop_Sup_closed_var: \n  fixes f :: \"'a::complete_lattice_with_dual \\<Rightarrow> 'a\"\n  shows \"coclop f \\<Longrightarrow> f \\<circ> Sup \\<circ> (`) f  = Sup \\<circ> (`) f\"\n  unfolding coclop_def mono_def comp_def le_fun_def \n  by (metis (mono_tags, lifting) SUP_le_iff antisym id_apply order_refl)\n\nlemma Sup_closed_coclop_var: \n  fixes X :: \"'a::complete_lattice set\"\n  shows \"coclop f \\<Longrightarrow> \\<forall>x \\<in> X. x \\<in> range f \\<Longrightarrow> \\<Squnion>X \\<in> range f\"\n  by (smt Inf.INF_id_eq Sup.SUP_cong antisym coclop_closure coclop_coextensive_var coclop_iso id_apply mono_SUP)\n\nlemma coclop_bot: \n  fixes f :: \"'a::complete_lattice_with_dual \\<Rightarrow> 'a\"\n  shows \"coclop f \\<Longrightarrow> f \\<bottom> = \\<bottom>\"\n  by (simp add: bot.extremum_uniqueI coclop_coextensive_var)\n\nlemma \"coclop (f::'a::complete_lattice \\<Rightarrow> 'a) \\<Longrightarrow> f (\\<Sqinter>x \\<in> X. f x) = (\\<Sqinter>x \\<in> X. f x)\" (*nitpick*)\n  oops\n\nlemma \"coclop (f::'a::complete_lattice \\<Rightarrow> 'a) \\<Longrightarrow> f (f x \\<sqinter> f y) = f x \\<sqinter> f y\" (*nitpick*)\n  oops\n\nlemma  \"coclop (f::'a::complete_lattice \\<Rightarrow> 'a) \\<Longrightarrow> f \\<top> = \\<top>\" (*nitpick*) \n  oops\n  \nlemma \"coclop (f::'a set \\<Rightarrow> 'a set) \\<Longrightarrow> f (\\<Sqinter>x \\<in> X. f x) = (\\<Sqinter>x \\<in> X. f x)\" (*nitpick*)\n  oops\n\nlemma \"coclop (f::'a set \\<Rightarrow> 'a set) \\<Longrightarrow> f (f x \\<sqinter> f y) = f x \\<sqinter> f y\" (*nitpick*)\n  oops\n\nlemma  \"coclop (f::'a set \\<Rightarrow> 'a set) \\<Longrightarrow> f \\<top> = \\<top>\" (*nitpick *)\n  oops\n\nlemma coclop_coclosure: \"coclop f \\<Longrightarrow> f x = x \\<longleftrightarrow> x \\<in> range f\"\n by (simp add: coclop_idem retraction_prop)\n                                              \nlemma coclop_coclosure_set: \"coclop f \\<Longrightarrow> range f = Fix f\"\n  by (simp add: coclop_idem retraction_prop_fix)\n\nlemma coclop_coclosure_prop: \"(coclop::('a::complete_lattice \\<Rightarrow> 'a) \\<Rightarrow> bool) (Sup \\<circ> \\<down>)\"\n  by (simp add: coclop_def mono_def)\n\nlemma coclop_coclosure_prop_var: \"coclop (\\<lambda>x::'a::complete_lattice. \\<Squnion>{y. y \\<le> x})\"\n  by (metis (mono_tags, lifting) Sup_atMost atMost_def coclop_def comp_apply eq_id_iff eq_refl mono_def)\n\nlemma coclop_alt: \"(coclop f) = (\\<forall>x y. f x \\<le> y \\<longleftrightarrow> f x \\<le> f y)\"\n  unfolding coclop_def mono_def le_fun_def comp_def id_def\n  by (meson dual_order.refl order_trans)\n\nlemma coclop_adj: \n  fixes f :: \"'a::order \\<Rightarrow> 'b::order\"\n  shows \"f \\<stileturn> g \\<Longrightarrow> coclop (f \\<circ> g)\"\n  by (simp add: adj_cancel1 adj_idem1 adj_iso3 coclop_def)\n\ntext \\<open>Finally, a subset of a complete lattice is Sup-closed if and only if it is the set of fixpoints\nof some co-closure operator.\\<close>\n\nlemma coclop_Sup_closed: \n  fixes f :: \"'a::complete_lattice \\<Rightarrow> 'a\"\n  shows  \"coclop f \\<Longrightarrow> Sup_closed_set (Fix f)\"\n  unfolding coclop_def Sup_closed_set_def mono_def le_fun_def comp_def id_def Fix_def\n  by (smt Sup_least Sup_upper antisym_conv mem_Collect_eq subsetCE)\n\nlemma Sup_closed_coclop: \n  fixes X :: \"'a::complete_lattice set\"\n  shows \"Sup_closed_set X \\<Longrightarrow> coclop (\\<lambda>y. \\<Squnion>{x \\<in> X. x \\<le> y})\"\n  unfolding Sup_closed_set_def coclop_def mono_def le_fun_def comp_def\n  apply safe\n  apply (metis (no_types, lifting) Sup_least eq_id_iff mem_Collect_eq)\n  apply (smt Collect_mono_iff Sup_subset_mono dual_order.trans)\n  by (simp add: Collect_mono_iff Sup_subset_mono Sup_upper)\n\n\nsubsection \\<open>Complete Lattices of Closed Elements\\<close>\n\ntext \\<open>The machinery developed allows showing that the closed elements in a complete\nlattice (with respect to some closure operation) form themselves a complete lattice.\\<close>\n\nclass cl_op = ord +\n  fixes cl_op :: \"'a \\<Rightarrow> 'a\"\n  assumes clop_ext: \"x \\<le> cl_op x\"\n  and clop_iso: \"x \\<le> y \\<Longrightarrow> cl_op x \\<le> cl_op y\"\n  and clop_wtrans: \"cl_op (cl_op x) \\<le> cl_op x\"\n\nclass clattice_with_clop = complete_lattice + cl_op\n\nbegin\n\nlemma clop_cl_op: \"clop cl_op\"\n  unfolding clop_def le_fun_def comp_def\n  by (simp add: cl_op_class.clop_ext cl_op_class.clop_iso cl_op_class.clop_wtrans order_class.mono_def)\n\nlemma clop_idem [simp]: \"cl_op \\<circ> cl_op = cl_op\"\n  using clop_ext clop_wtrans order.antisym by auto\n\nlemma clop_idem_var [simp]: \"cl_op (cl_op x) = cl_op x\"\n  by (simp add: order.antisym clop_ext clop_wtrans)\n\nlemma clop_range_Fix: \"range cl_op = Fix cl_op\"\n  by (simp add: retraction_prop_fix)\n\nlemma Inf_closed_cl_op_var: \n  fixes X :: \"'a set\"\n  shows \"\\<forall>x \\<in> X. x \\<in> range cl_op \\<Longrightarrow> \\<Sqinter>X \\<in> range cl_op\"\nproof-\n  assume h: \"\\<forall>x \\<in> X. x \\<in> range cl_op\"\n  hence \"\\<forall>x \\<in> X. cl_op x = x\"\n    by (simp add: retraction_prop)\n  hence \"cl_op (\\<Sqinter>X) = \\<Sqinter>X\"\n    by (metis Inf_lower clop_ext clop_iso dual_order.antisym le_Inf_iff)\n  thus ?thesis\n    by (metis rangeI)\nqed\n\nlemma inf_closed_cl_op_var: \"x \\<in> range cl_op \\<Longrightarrow> y \\<in> range cl_op \\<Longrightarrow> x \\<sqinter> y \\<in> range cl_op\"\n  by (smt Inf_closed_cl_op_var UnI1 insert_iff insert_is_Un inf_Inf)\n\nend\n\ntypedef (overloaded) 'a::clattice_with_clop cl_op_im = \"range (cl_op::'a \\<Rightarrow> 'a)\"\n  by force\n\nsetup_lifting type_definition_cl_op_im\n\nlemma cl_op_prop [iff]: \"(cl_op (x \\<squnion> y) = cl_op y) = (cl_op (x::'a::clattice_with_clop) \\<le> cl_op y)\"\n  by (smt cl_op_class.clop_iso clop_ext clop_wtrans inf_sup_ord(4) le_iff_sup sup.absorb_iff1 sup_left_commute)\n\nlemma cl_op_prop_var [iff]: \"(cl_op (x \\<squnion> cl_op y) = cl_op y) = (cl_op (x::'a::clattice_with_clop) \\<le> cl_op y)\"\n  by (metis cl_op_prop clattice_with_clop_class.clop_idem_var)\n\ninstantiation cl_op_im :: (clattice_with_clop) complete_lattice\nbegin\n\nlift_definition Inf_cl_op_im :: \"'a cl_op_im set \\<Rightarrow> 'a cl_op_im\" is Inf\n  by (simp add: Inf_closed_cl_op_var)\n \nlift_definition Sup_cl_op_im :: \"'a cl_op_im set \\<Rightarrow> 'a cl_op_im\" is \"\\<lambda>X. cl_op (\\<Squnion>X)\"\n  by simp\n\nlift_definition inf_cl_op_im :: \"'a cl_op_im \\<Rightarrow> 'a cl_op_im \\<Rightarrow> 'a cl_op_im\" is inf\n  by (simp add: inf_closed_cl_op_var)\n\nlift_definition sup_cl_op_im :: \"'a cl_op_im \\<Rightarrow> 'a cl_op_im \\<Rightarrow> 'a cl_op_im\" is \"\\<lambda>x y. cl_op (x \\<squnion> y)\"\n  by simp\n\nlift_definition less_eq_cl_op_im :: \"'a cl_op_im \\<Rightarrow> 'a cl_op_im \\<Rightarrow> bool\" is \"(\\<le>)\".\n\nlift_definition less_cl_op_im :: \"'a cl_op_im \\<Rightarrow> 'a cl_op_im \\<Rightarrow> bool\" is \"(<)\".\n\nlift_definition bot_cl_op_im :: \"'a cl_op_im\" is \"cl_op \\<bottom>\"\n  by simp\n\nlift_definition top_cl_op_im :: \"'a cl_op_im\" is \"\\<top>\"\n  by (simp add: clop_cl_op clop_closure clop_top)\n\n\ninstance\n  apply (intro_classes; transfer)\n                 apply (simp_all add: less_le_not_le Inf_lower Inf_greatest)\n      apply (meson clop_cl_op clop_extensive_var dual_order.trans inf_sup_ord(3))\n     apply (meson clop_cl_op clop_extensive_var dual_order.trans sup_ge2)\n    apply (metis cl_op_class.clop_iso clop_cl_op clop_closure le_sup_iff)\n   apply (meson Sup_upper clop_cl_op clop_extensive_var dual_order.trans)\n  by (metis Sup_le_iff cl_op_class.clop_iso clop_cl_op clop_closure)\n\nend\n\ntext \\<open>This statement is perhaps less useful as it might seem, because it is difficult to make it cooperate with concrete closure operators, \nwhich one would not generally like to define within a type class. Alternatively, a sublocale statement could perhaps be given. It would also \nhave been nice to prove this statement for Sup-lattices---this would have cut down the number of proof obligations significantly.\nBut this would require a tighter integration of these structures. A similar statement could have been proved for co-closure operators. But this would\nnot lead to new insights.\\<close>\n\ntext \\<open>Next I show that for every surjective Sup-preserving function between complete lattices there is a closure operator \nsuch that the set of closed elements is isomorphic to the range of the surjection.\\<close>\n\nlemma surj_Sup_pres_id:\n  fixes f :: \"'a::complete_lattice_with_dual \\<Rightarrow> 'b::complete_lattice_with_dual\"\n  assumes \"surj f\"\n  and \"Sup_pres f\" \n  shows \"f \\<circ> (radj f) = id\"\nproof-\n  have \"f \\<stileturn> (radj f)\"\n    using Sup_pres_ladj assms(2) radj_adj by auto\n  thus ?thesis\n    using adj_sur_inv assms(1) by blast\nqed\n\nlemma surj_Sup_pres_inj:\n  fixes f :: \"'a::complete_lattice_with_dual \\<Rightarrow> 'b::complete_lattice_with_dual\"\n  assumes \"surj f\"\n  and \"Sup_pres f\" \n  shows \"inj (radj f)\"\n  by (metis assms comp_eq_dest_lhs id_apply injI surj_Sup_pres_id)\n\nlemma surj_Sup_pres_inj_on: \n  fixes f :: \"'a::complete_lattice_with_dual \\<Rightarrow> 'b::complete_lattice_with_dual\"\n  assumes \"surj f\"\n  and \"Sup_pres f\" \n  shows \"inj_on f (range (radj f \\<circ> f))\"\n  by (smt Sup_pres_ladj_aux adj_idem2 assms(2) comp_apply inj_on_def retraction_prop)\n\nlemma surj_Sup_pres_bij_on: \n  fixes f :: \"'a::complete_lattice_with_dual \\<Rightarrow> 'b::complete_lattice_with_dual\"\n  assumes \"surj f\"\n  and \"Sup_pres f\" \n  shows \"bij_betw f (range (radj f \\<circ> f)) UNIV\"\n  unfolding bij_betw_def\n  apply safe\n    apply (simp add: assms(1) assms(2) surj_Sup_pres_inj_on cong del: image_cong_simp)\n   apply auto\n  apply (metis (mono_tags) UNIV_I assms(1) assms(2) comp_apply id_apply image_image surj_Sup_pres_id surj_def)\n  done\n\ntext \\<open>Thus the restriction of $f$ to the set of closed elements is indeed a bijection. The final fact\nshows that it preserves Sups of closed elements, and hence is an isomorphism of complete lattices.\\<close>\n\nlemma surj_Sup_pres_iso: \n  fixes f :: \"'a::complete_lattice_with_dual \\<Rightarrow> 'b::complete_lattice_with_dual\"\n  assumes \"surj f\"\n  and \"Sup_pres f\" \n  shows \"f ((radj f \\<circ> f) (\\<Squnion>X)) = (\\<Squnion>x \\<in> X. f x)\"\n  by (metis assms(1) assms(2) comp_def pointfree_idE surj_Sup_pres_id)\n\n\nsubsection \\<open>A Quick Example: Dedekind-MacNeille Completions\\<close>\n\ntext \\<open>I only outline the basic construction. Additional facts about join density, and that the completion yields \nthe least complete lattice that contains all Sups and Infs of the underlying posets, are left for future consideration.\\<close>\n\nabbreviation \"dm \\<equiv> lb_set \\<circ> ub_set\"\n\nlemma up_set_prop: \"(X::'a::preorder set) \\<noteq> {} \\<Longrightarrow> ub_set X = \\<Inter>{\\<up>x |x. x \\<in> X}\"\n  unfolding ub_set_def upset_def upset_set_def by (safe, simp_all, blast)\n\nlemma lb_set_prop: \"(X::'a::preorder set) \\<noteq> {} \\<Longrightarrow> lb_set X = \\<Inter>{\\<down>x |x. x \\<in> X}\"\n  unfolding lb_set_def downset_def downset_set_def by (safe, simp_all, blast)\n\nlemma dm_downset_var: \"dm {x} = \\<down>(x::'a::preorder)\"\n  unfolding lb_set_def ub_set_def downset_def downset_set_def \n  by (clarsimp, meson order_refl order_trans)\n\nlemma dm_downset: \"dm \\<circ> \\<eta> = (\\<down>::'a::preorder \\<Rightarrow> 'a set)\"\n  using dm_downset_var fun.map_cong by fastforce\n\nlemma dm_inj: \"inj ((dm::'a::order set \\<Rightarrow> 'a set) \\<circ> \\<eta>)\"\n  by (simp add: dm_downset downset_inj)\n\nlemma \"clop (lb_set \\<circ> ub_set)\"\n  unfolding clop_def lb_set_def ub_set_def\n  apply safe\n  unfolding le_fun_def comp_def id_def mono_def\n  by auto\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/Order_Lattice_Props/Closure_Operators.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9019206712569267, "lm_q2_score": 0.8128673223709251, "lm_q1q2_score": 0.7331418410356053}}
{"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  theory TIP_prop_20\n  imports \"../../Test_Base\"\nbegin\n\ndatatype 'a list = nil2 | cons2 \"'a\" \"'a list\"\n\ndatatype Nat = Z | S \"Nat\"\n\nfun len :: \"'a list => Nat\" where\n  \"len (nil2) = Z\"\n| \"len (cons2 y xs) = S (len xs)\"\n\nfun t2 :: \"Nat => Nat => bool\" where\n  \"t2 (Z) y = True\"\n| \"t2 (S z) (Z) = False\"\n| \"t2 (S z) (S x2) = t2 z x2\"\n\nfun insort :: \"Nat => Nat list => Nat list\" where\n  \"insort x (nil2) = cons2 x (nil2)\"\n| \"insort x (cons2 z xs) =\n     (if t2 x z then cons2 x (cons2 z xs) else cons2 z (insort x xs))\"\n\nfun sort :: \"Nat list => Nat list\" where\n  \"sort (nil2) = nil2\"\n| \"sort (cons2 y xs) = insort y (sort xs)\"\n\ntheorem property0 :\n  \"((len (sort xs)) = (len 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/Isaplanner/Isaplanner/TIP_prop_20.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206659843132, "lm_q2_score": 0.8128673087708699, "lm_q1q2_score": 0.7331418244834993}}
{"text": "theory Nat_Demo\nimports 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\n(* Automatic proof. This is what we will focus on first! *)    \nlemma \"add m 0 = m\"\n  apply(induction m)\n  apply(auto)\n  done\n\n\n(* Completely manual proof. You do not need to understand \n  all the syntax details etc right now!     *)    \nthm add.simps(1)\nthm refl  \n\nlemma \"add m 0 = m\"\n  apply(induction m)\n  (* Base case *)  \n   apply (subst add.simps(1)) (* Rewrite with first equation of add *) \n   apply (rule refl) (* Use reflexivity: Syntactically equal terms are actually equal! *)\n    \n  (* Induction step *)  \n  subgoal premises prems for m\n    apply (subst add.simps(2)) (* Rewrite with second equation of add *) \n    thm prems  (* Diagnostic command to display induction hypothesis (assumption): *)\n    apply (subst prems) (* Rewrite with I.H. *)\n    apply (rule refl) (* Reflexivity again *)\n    done\n  done    \n\n    \n\nfun gs :: \"nat \\<Rightarrow> nat\" where\n  \"gs 0 = 0\"\n| \"gs (Suc n) = Suc n + gs n\"  \n    \nlemma \"gs n = n*(n+1) div 2\"\n  apply (induction n)\n  apply auto\n  done  \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/Nat_Demo.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9399133515091156, "lm_q2_score": 0.7799929104825007, "lm_q1q2_score": 0.7331257506449569}}
{"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_03\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 length :: \"'a list => Nat\" where\n  \"length (nil2) = Z\"\n| \"length (cons2 z xs) = S (length xs)\"\n\nfun t2 :: \"Nat => Nat => Nat\" where\n  \"t2 (Z) z = z\"\n| \"t2 (S z2) z = S (t2 z2 z)\"\n\n(* This apply-style proof script repeats the proof of \"t2 n m = t2 m n\" twice,\n * whereas Kei's original proof script caches \"t2 n m = t2 m n\". *)\ntheorem property0 :\n  \"((length (x y z)) = (t2 (length z) (length y)))\"\n  apply(induct y)\n   apply simp\n   apply(subgoal_tac \"\\<And>n m. t2 n m = t2 m n\")(*(meta-)universal quantifiers are necessary.*)\n    apply fastforce\n   apply(induct_tac n)\n    apply simp\n    apply(induct_tac m)\n     apply fastforce+\n   apply clarsimp\n   apply(case_tac m)\n    apply fastforce+\n   apply(thin_tac \"m = S x2\")\n   apply(thin_tac \"t2 x m = t2 m x\")\n   apply(induct_tac m)\n    apply fastforce+\n  apply(case_tac z)\n   apply fastforce\n  apply(subgoal_tac \"\\<And>n m. t2 n m = t2 m n\")(*(meta-)universal quantifiers are necessary.*)\n   apply fastforce\n  apply(thin_tac \"TIP_prop_03.length (x y z) = t2 (TIP_prop_03.length z) (TIP_prop_03.length y)\")\n  apply(thin_tac \"z = cons2 x21 x22\")\n  apply(induct_tac n)\n   apply simp\n   apply(induct_tac m)\n    apply fastforce+\n  apply clarsimp\n  apply(case_tac m)\n   apply fastforce+\n  apply(thin_tac \"m = S x2\")\n  apply(thin_tac \"t2 x m = t2 m x\")\n  apply(induct_tac m)\n   apply fastforce+\n  done\n\nlemma swap_t2_aux_1:\n  \"(\\<And>m. t2 n m = t2 m n) \\<Longrightarrow> t2 (S n) m = t2 m (S n)\"\n  apply(induct m)\n   apply fastforce+\n  done\n\nlemma swap_t2_aux_0:\n  \"m = t2 m Z\"\n  apply(induct m)\n   apply fastforce+\n  done\n\nlemma swap_t2:(*commutative property*)\n  \"t2 n m = t2 m n\"\n  apply(induct n arbitrary: m)\n   apply clarsimp\n   apply(rule swap_t2_aux_0)(*just a nested induction*)\n  apply(rule swap_t2_aux_1)(*just a nested induction*)\n  apply assumption (*to handle induction hypotheses*)\n  done\n\ntheorem property:\n  \"((length (x y z)) = (t2 (length z) (length y)))\"\n  apply(induct y)\n   apply clarsimp\n  using swap_t2 apply fastforce (*sledgehammer*)\n  apply(cases z)\n   apply fastforce\n  using swap_t2 apply fastforce (*sledgehammer*)\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/Prod/Prod/TIP_prop_03.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767842777551, "lm_q2_score": 0.8354835411997897, "lm_q1q2_score": 0.7331174110489829}}
{"text": "(*  Author:     Tobias Nipkow, TU M\u00fcnchen\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\n  imports 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 \\<and> \\<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": "seL4", "repo": "isabelle", "sha": "e1ab32a3bb41728cd19541063283e37919978a4c", "save_path": "github-repos/isabelle/seL4-isabelle", "path": "github-repos/isabelle/seL4-isabelle/isabelle-e1ab32a3bb41728cd19541063283e37919978a4c/src/HOL/Library/Extended.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8774767842777551, "lm_q2_score": 0.8354835371034368, "lm_q1q2_score": 0.7331174074545282}}
{"text": "theory styleShow\n  imports Main\nbegin\n(* Cantor's Theorem *)\nlemma \"\\<not> surj(f :: 'a \\<Rightarrow> 'a set)\" \nproof\nassume 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\nassume \"surj f\"\n  from this have \"\\<exists>a. {x. x \\<notin> f x} = f a\" by(auto simp: surj_def) \n  from this show \"False\" by blast\nqed\n\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\n(*Exercise 5.1*)\nlemma\n  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\"\n  using A T TA assms(4) by blast\n \n\n\n(*\nlemma\n  fixes f :: \"'a \\<Rightarrow> 'a set\" \n  assumes s: \"surj f\" \n  shows \"False\"\n*)\n\nend", "meta": {"author": "hotessy", "repo": "reasoning_practice", "sha": "4bdd6403880b5bae2d95c0f5ce8f4c2bc7ca000f", "save_path": "github-repos/isabelle/hotessy-reasoning_practice", "path": "github-repos/isabelle/hotessy-reasoning_practice/reasoning_practice-4bdd6403880b5bae2d95c0f5ce8f4c2bc7ca000f/styleShow.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.899121388082479, "lm_q2_score": 0.815232489352, "lm_q1q2_score": 0.732992967436105}}
{"text": "(*  Title:      HOL/Isar_Examples/Group_Context.thy\n    Author:     Makarius\n*)\n\nsection \\<open>Some algebraic identities derived from group axioms -- theory context version\\<close>\n\ntheory Group_Context\nimports Main\nbegin\n\ntext \\<open>hypothetical group axiomatization\\<close>\n\ncontext\n  fixes prod :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a\"  (infixl \"**\" 70)\n    and one :: \"'a\"\n    and inverse :: \"'a \\<Rightarrow> 'a\"\n  assumes assoc: \"(x ** y) ** z = x ** (y ** z)\"\n    and left_one: \"one ** x = x\"\n    and left_inverse: \"inverse x ** x = one\"\nbegin\n\ntext \\<open>some consequences\\<close>\n\nlemma right_inverse: \"x ** inverse x = one\"\nproof -\n  have \"x ** inverse x = one ** (x ** inverse x)\"\n    by (simp only: left_one)\n  also have \"\\<dots> = one ** x ** inverse x\"\n    by (simp only: assoc)\n  also have \"\\<dots> = inverse (inverse x) ** inverse x ** x ** inverse x\"\n    by (simp only: left_inverse)\n  also have \"\\<dots> = inverse (inverse x) ** (inverse x ** x) ** inverse x\"\n    by (simp only: assoc)\n  also have \"\\<dots> = inverse (inverse x) ** one ** inverse x\"\n    by (simp only: left_inverse)\n  also have \"\\<dots> = inverse (inverse x) ** (one ** inverse x)\"\n    by (simp only: assoc)\n  also have \"\\<dots> = inverse (inverse x) ** inverse x\"\n    by (simp only: left_one)\n  also have \"\\<dots> = one\"\n    by (simp only: left_inverse)\n  finally show \"x ** inverse x = one\" .\nqed\n\nlemma right_one: \"x ** one = x\"\nproof -\n  have \"x ** one = x ** (inverse x ** x)\"\n    by (simp only: left_inverse)\n  also have \"\\<dots> = x ** inverse x ** x\"\n    by (simp only: assoc)\n  also have \"\\<dots> = one ** x\"\n    by (simp only: right_inverse)\n  also have \"\\<dots> = x\"\n    by (simp only: left_one)\n  finally show \"x ** one = x\" .\nqed\n\nlemma one_equality:\n  assumes eq: \"e ** x = x\"\n  shows \"one = e\"\nproof -\n  have \"one = x ** inverse x\"\n    by (simp only: 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: assoc)\n  also have \"\\<dots> = e ** one\"\n    by (simp only: right_inverse)\n  also have \"\\<dots> = e\"\n    by (simp only: right_one)\n  finally show \"one = e\" .\nqed\n\nlemma inverse_equality:\n  assumes eq: \"x' ** x = one\"\n  shows \"inverse x = x'\"\nproof -\n  have \"inverse x = one ** inverse x\"\n    by (simp only: 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: assoc)\n  also have \"\\<dots> = x' ** one\"\n    by (simp only: right_inverse)\n  also have \"\\<dots> = x'\"\n    by (simp only: right_one)\n  finally show \"inverse x = x'\" .\nqed\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/Isar_Examples/Group_Context.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972583359805, "lm_q2_score": 0.8418256532040708, "lm_q1q2_score": 0.7328911056763598}}
{"text": "(*\n * Copyright 2020, Data61, CSIRO (ABN 41 687 119 230)\n *\n * SPDX-License-Identifier: BSD-2-Clause\n *)\n\nsection \"Distinct Proposition\"\n\ntheory Distinct_Prop  (* part of non-AFP Word_Lib *)\nimports\n  \"HOL_Lemmas\"\n  \"HOL-Library.Prefix_Order\"\nbegin\n\nprimrec\n  distinct_prop :: \"('a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> ('a list \\<Rightarrow> bool)\"\nwhere\n  \"distinct_prop P [] = True\"\n| \"distinct_prop P (x # xs) = ((\\<forall>y\\<in>set xs. P x y) \\<and> distinct_prop P xs)\"\n\nprimrec\n  distinct_sets :: \"'a set list \\<Rightarrow> bool\"\nwhere\n  \"distinct_sets [] = True\"\n| \"distinct_sets (x#xs) = (x \\<inter> \\<Union> (set xs) = {} \\<and> distinct_sets xs)\"\n\n\nlemma distinct_prop_map:\n  \"distinct_prop P (map f xs) = distinct_prop (\\<lambda>x y. P (f x) (f y)) xs\"\n  by (induct xs) auto\n\nlemma distinct_prop_append:\n  \"distinct_prop P (xs @ ys) =\n    (distinct_prop P xs \\<and> distinct_prop P ys \\<and> (\\<forall>x \\<in> set xs. \\<forall>y \\<in> set ys. P x y))\"\n  by (induct xs arbitrary: ys) (auto simp: conj_comms ball_Un)\n\nlemma distinct_prop_distinct:\n  \"\\<lbrakk> distinct xs; \\<And>x y. \\<lbrakk> x \\<in> set xs; y \\<in> set xs; x \\<noteq> y \\<rbrakk> \\<Longrightarrow> P x y \\<rbrakk> \\<Longrightarrow> distinct_prop P xs\"\n  by (induct xs) auto\n\nlemma distinct_prop_True [simp]:\n  \"distinct_prop (\\<lambda>x y. True) xs\"\n  by (induct xs, auto)\n\n\nlemma distinct_prefix:\n  \"\\<lbrakk> distinct xs; ys \\<le> xs \\<rbrakk> \\<Longrightarrow> distinct ys\"\n  apply (induct xs arbitrary: ys; clarsimp)\n  apply (case_tac ys; clarsimp)\n  by (fastforce simp: less_eq_list_def dest: set_mono_prefix)\n\nlemma distinct_sets_prop:\n  \"distinct_sets xs = distinct_prop (\\<lambda>x y. x \\<inter> y = {}) xs\"\n  by (induct xs) auto\n\nlemma distinct_take_strg:\n  \"distinct xs \\<longrightarrow> distinct (take n xs)\"\n  by simp\n\nlemma distinct_prop_prefixE:\n  \"\\<lbrakk> distinct_prop P ys; prefix xs ys \\<rbrakk> \\<Longrightarrow> distinct_prop P xs\"\n  apply (induct xs arbitrary: ys; clarsimp)\n  apply (case_tac ys; clarsimp)\n  by (fastforce dest: set_mono_prefix)\n\n\nlemma distinct_sets_union_sub:\n  \"\\<lbrakk>x \\<in> A; distinct_sets [A,B]\\<rbrakk> \\<Longrightarrow> A \\<union> B - {x} = A - {x} \\<union> B\"\n  by (auto simp: distinct_sets_def)\n\nlemma distinct_sets_append:\n  \"distinct_sets (xs @ ys) \\<Longrightarrow> distinct_sets xs \\<and> distinct_sets ys\"\n  apply (subst distinct_sets_prop)+\n  apply (subst (asm) distinct_sets_prop)\n  apply (subst (asm) distinct_prop_append)\n  apply clarsimp\n  done\n\nlemma distinct_sets_append1:\n  \"distinct_sets (xs @ ys) \\<Longrightarrow> distinct_sets xs\"\n  by (drule distinct_sets_append, simp)\n\nlemma distinct_sets_append2:\n  \"distinct_sets (xs @ ys) \\<Longrightarrow> distinct_sets ys\"\n  by (drule distinct_sets_append, simp)\n\nlemma distinct_sets_append_Cons:\n  \"distinct_sets (xs @ a # ys) \\<Longrightarrow> distinct_sets (xs @ ys)\"\n  apply (subst distinct_sets_prop)+\n  apply (subst (asm) distinct_sets_prop)\n  apply (subst distinct_prop_append)\n  apply (subst (asm) distinct_prop_append)\n  apply clarsimp\n  done\n\nlemma distinct_sets_append_Cons_disjoint:\n  \"distinct_sets (xs @ a # ys) \\<Longrightarrow>  a \\<inter> \\<Union> (set xs) = {} \"\n  apply (subst (asm) distinct_sets_prop)\n  apply (subst (asm) distinct_prop_append)\n  apply (subst Int_commute)\n  apply (subst Union_disjoint)\n  apply clarsimp\n  done\n\nlemma distinct_prop_take:\n  \"\\<lbrakk>distinct_prop P xs; i < length xs\\<rbrakk> \\<Longrightarrow> distinct_prop P (take i xs)\"\n  by (metis take_is_prefix distinct_prop_prefixE)\n\nlemma distinct_sets_take:\n  \"\\<lbrakk>distinct_sets xs; i < length xs\\<rbrakk> \\<Longrightarrow> distinct_sets (take i xs)\"\n  by (simp add: distinct_sets_prop distinct_prop_take)\n\nlemma distinct_prop_take_Suc:\n  \"\\<lbrakk>distinct_prop P xs; i < length xs\\<rbrakk> \\<Longrightarrow> distinct_prop P (take (Suc i) xs)\"\n  by (metis distinct_prop_take not_less take_all)\n\nlemma distinct_sets_take_Suc:\n  \"\\<lbrakk>distinct_sets xs; i < length xs\\<rbrakk> \\<Longrightarrow> distinct_sets (take (Suc i) xs)\"\n  by (simp add: distinct_sets_prop distinct_prop_take_Suc)\n\nlemma distinct_prop_rev:\n  \"distinct_prop P (rev xs) = distinct_prop (\\<lambda>y x. P x y) xs\"\n  by (induct xs) (auto simp: distinct_prop_append)\n\nlemma distinct_sets_rev [simp]:\n  \"distinct_sets (rev xs) = distinct_sets xs\"\n  apply (unfold distinct_sets_prop)\n  apply (subst distinct_prop_rev)\n  apply (subst Int_commute)\n  apply clarsimp\n  done\n\nlemma distinct_sets_drop:\n  \"\\<lbrakk>distinct_sets xs; i < length xs\\<rbrakk> \\<Longrightarrow> distinct_sets (drop i xs)\"\n  apply (cases \"i=0\", simp)\n  apply (subst distinct_sets_rev [symmetric])\n  apply (subst rev_drop)\n  apply (subst distinct_sets_take, simp_all)\n  done\n\nlemma distinct_sets_drop_Suc:\n  \"\\<lbrakk>distinct_sets xs; i < length xs\\<rbrakk> \\<Longrightarrow> distinct_sets (drop (Suc i) xs)\"\n  apply (subst distinct_sets_rev [symmetric])\n  apply (subst rev_drop)\n  apply (subst distinct_sets_take, simp_all)\n  done\n\nlemma distinct_sets_take_nth:\n  \"\\<lbrakk>distinct_sets xs; i < length xs; x \\<in> set (take i xs)\\<rbrakk> \\<Longrightarrow> x \\<inter> xs ! i = {}\"\n  apply (drule (1) distinct_sets_take_Suc)\n  apply (subst (asm) take_Suc_conv_app_nth, assumption)\n  apply (unfold distinct_sets_prop)\n  apply (subst (asm) distinct_prop_append)\n  apply clarsimp\n  done\n\nlemma distinct_sets_drop_nth:\n  \"\\<lbrakk>distinct_sets xs; i < length xs; x \\<in> set (drop (Suc i) xs)\\<rbrakk> \\<Longrightarrow> x \\<inter> xs ! i = {}\"\n  apply (drule (1) distinct_sets_drop)\n  apply (subst (asm) drop_Suc_nth, assumption)\n  apply fastforce\n  done\n\nlemma distinct_sets_append_distinct:\n  \"\\<lbrakk>x \\<in> set xs; y \\<in> set ys; distinct_sets (xs @ ys)\\<rbrakk> \\<Longrightarrow> x \\<inter> y = {}\"\n  unfolding distinct_sets_prop by (clarsimp simp: distinct_prop_append)\n\nlemma distinct_sets_update:\n \"\\<lbrakk>a \\<subseteq> xs ! i; distinct_sets xs; i < length xs\\<rbrakk> \\<Longrightarrow> distinct_sets (xs[i := a])\"\n  apply (subst distinct_sets_prop)\n  apply (subst (asm) distinct_sets_prop)\n  apply (subst upd_conv_take_nth_drop, simp)\n  apply (subst distinct_prop_append)\n  apply (intro conjI)\n    apply (erule (1) distinct_prop_take)\n   apply (rule conjI|clarsimp)+\n    apply (fold distinct_sets_prop)\n    apply (drule (1) distinct_sets_drop)\n    apply (subst (asm) drop_Suc_nth, assumption)\n    apply fastforce\n   apply (drule (1) distinct_sets_drop)\n   apply (subst (asm) drop_Suc_nth, assumption)\n   apply clarsimp\n  apply clarsimp\n  apply (rule conjI)\n   apply (drule (2) distinct_sets_take_nth)\n   apply blast\n  apply clarsimp\n  apply (thin_tac \"P \\<subseteq> Q\" for P Q)\n  apply (subst (asm) id_take_nth_drop, assumption)\n  apply (drule distinct_sets_append_Cons)\n  apply (erule (2) distinct_sets_append_distinct)\n  done\n\nlemma distinct_sets_map_update:\n  \"\\<lbrakk>distinct_sets (map f xs); i < length xs; f a \\<subseteq> f(xs ! i)\\<rbrakk>\n  \\<Longrightarrow> distinct_sets (map f (xs[i := a]))\"\n  by (metis distinct_sets_update length_map map_update nth_map)\n\nlemma Union_list_update:\n  \"\\<lbrakk>i < length xs; distinct_sets (map f xs)\\<rbrakk>\n  \\<Longrightarrow> (\\<Union>x\\<in>set (xs [i := a]). f x) = (\\<Union>x\\<in>set xs. f x) - f (xs ! i) \\<union> f a\"\n  apply (induct xs arbitrary: i; clarsimp)\n  apply (case_tac i; (clarsimp, fastforce))\n  done\n\nlemma fst_enumerate:\n  \"i < length xs \\<Longrightarrow> fst (enumerate n xs ! i) = i + n\"\n  by (metis add.commute fst_conv nth_enumerate_eq)\n\nlemma snd_enumerate:\n  \"i < length xs \\<Longrightarrow> snd (enumerate n xs ! i) = xs ! i\"\n  by (metis nth_enumerate_eq snd_conv)\n\nlemma enumerate_member:\n  assumes \"i < length xs\"\n  shows \"(n + i, xs ! i) \\<in> set (enumerate n xs)\"\nproof -\n  have pair_unpack: \"\\<And>a b x. ((a, b) = x) = (a = fst x \\<and> b = snd x)\" by fastforce\n  from assms have \"(n + i, xs ! i) = enumerate n xs ! i\"\n    by (auto simp: fst_enumerate snd_enumerate pair_unpack)\n  with assms show ?thesis by simp\nqed\n\nlemma distinct_prop_nth:\n  \"\\<lbrakk> distinct_prop P ls; n < n'; n' < length ls \\<rbrakk> \\<Longrightarrow> P (ls ! n) (ls ! n')\"\n  apply (induct ls arbitrary: n n'; simp)\n  apply (case_tac n'; simp)\n  apply (case_tac n; simp)\n  done\n\nend\n", "meta": {"author": "CompSoftVer", "repo": "CSim2", "sha": "b09a4d77ea089168b1805db5204ac151df2b9eff", "save_path": "github-repos/isabelle/CompSoftVer-CSim2", "path": "github-repos/isabelle/CompSoftVer-CSim2/CSim2-b09a4d77ea089168b1805db5204ac151df2b9eff/lib/Word_Lib/Distinct_Prop.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392939666335, "lm_q2_score": 0.828938806208442, "lm_q1q2_score": 0.732814476982055}}
{"text": "(*  Title:       Category theory using Isar and Locales\n    Author:      Greg O'Keefe, June, July, August 2003\n    License: LGPL\n*)\n\nsection \\<open>Categories\\<close>\n\ntheory Cat\nimports \"HOL-Library.FuncSet\"\nbegin\n\nsubsection \\<open>Definitions\\<close>\n\nrecord ('o, 'a) category =\n  ob :: \"'o set\" (\"Ob\\<index>\"  70)\n  ar :: \"'a set\" (\"Ar\\<index>\"  70)\n  dom :: \"'a \\<Rightarrow> 'o\" (\"Dom\\<index> _\" [81] 70)\n  cod :: \"'a \\<Rightarrow> 'o\" (\"Cod\\<index> _\" [81] 70)\n  id :: \"'o \\<Rightarrow> 'a\" (\"Id\\<index> _\" [81] 80)\n  comp :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a\"  (infixl \"\\<bullet>\\<index>\" 60)\n\ndefinition\n  hom :: \"[('o,'a,'m) category_scheme, 'o, 'o] \\<Rightarrow> 'a set\"\n    (\"Hom\\<index> _ _\" [81,81] 80) where\n  \"hom CC A B = { f. f\\<in>ar CC & dom CC f = A & cod CC f = B }\"\n\nlocale category =\n  fixes CC (structure)\n  assumes dom_object [intro]:\n  \"f \\<in> Ar \\<Longrightarrow> Dom f \\<in> Ob\"\n  and cod_object [intro]:\n  \"f \\<in> Ar \\<Longrightarrow> Cod f \\<in> Ob\"\n  and id_left [simp]:\n  \"f \\<in> Ar \\<Longrightarrow> Id (Cod f) \\<bullet> f = f\"\n  and id_right [simp]:\n  \"f \\<in> Ar \\<Longrightarrow> f \\<bullet> Id (Dom f) = f\"\n  and id_hom [intro]:\n  \"A \\<in> Ob \\<Longrightarrow> Id A \\<in> Hom A A\"\n  and comp_types [intro]:\n  \"\\<And>A B C. (comp CC) : (Hom B C) \\<rightarrow> (Hom A B) \\<rightarrow> (Hom A C)\"\n  and comp_associative [simp]:\n  \"f \\<in> Ar \\<Longrightarrow> g \\<in> Ar \\<Longrightarrow> h \\<in> Ar\n  \\<Longrightarrow> Cod h = Dom g \\<Longrightarrow> Cod g = Dom f\n  \\<Longrightarrow> f \\<bullet> (g \\<bullet> h) = (f \\<bullet> g) \\<bullet> h\"\n\n\nsubsection \\<open>Lemmas\\<close>\n\nlemma (in category) homI:\n  assumes \"f \\<in> Ar\" and \"Dom f = A\" and \"Cod f = B\"\n  shows \"f \\<in> Hom A B\"\n  using assms by (auto simp add: hom_def)\n\n\n\nlemma (in category) id_dom_cod:\n  assumes \"A \\<in> Ob\"\n  shows \"Dom (Id A) = A\" and \"Cod (Id A) = A\"\nproof-\n  from \\<open>A \\<in> Ob\\<close> have 1: \"Id A \\<in> Hom A A\" ..\n  then show \"Dom (Id A) = A\" and \"Cod (Id A) = A\"\n    by (simp_all add: hom_def)\nqed\n\n\nlemma (in category) compI [intro]:\n  assumes f: \"f \\<in> Ar\" and g: \"g \\<in> Ar\" and \"Cod f = Dom g\"\n  shows \"g \\<bullet> f \\<in> Ar\"\n  and \"Dom (g \\<bullet> f) = Dom f\"\n  and \"Cod (g \\<bullet> f) = Cod g\"\nproof-\n  have \"f \\<in> Hom (Dom f) (Cod f)\" using f by (simp add: hom_def)\n  with \\<open>Cod f = Dom g\\<close> have f_homset: \"f \\<in> Hom (Dom f) (Dom g)\" by simp\n  have g_homset: \"g \\<in> Hom (Dom g) (Cod g)\" using g by (simp add: hom_def)\n  have \"(\\<bullet>) : Hom (Dom g) (Cod g) \\<rightarrow> Hom (Dom f) (Dom g) \\<rightarrow> Hom (Dom f) (Cod g)\" ..\n  from this and g_homset \n  have \"(\\<bullet>) g \\<in> Hom (Dom f) (Dom g) \\<rightarrow> Hom (Dom f) (Cod g)\" \n    by (rule funcset_mem)\n  from this and f_homset \n  have gf_homset: \"g \\<bullet> f \\<in> Hom (Dom f) (Cod g)\"\n    by (rule funcset_mem)\n  thus \"g \\<bullet> f \\<in> Ar\"\n    by (simp add: hom_def) \n  from gf_homset show \"Dom (g \\<bullet> f) = Dom f\" and \"Cod (g \\<bullet> f) = Cod g\"\n    by (simp_all add: hom_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/Category/Cat.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392848011834, "lm_q2_score": 0.8289388146603364, "lm_q1q2_score": 0.7328144768562646}}
{"text": "\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 \n        \\<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 bubblesort\napply(relation \"measure size\")\napply simp\napply (auto simp: size_bubble_min dest!: bubble_minD_size \n        split: list.splits if_splits)\ndone\n\nvalue \"bubblesort [3::nat,5,7,39,15,1,2,20]\"\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": "LVPGroup", "repo": "fpp", "sha": "7e18377ea2c553bf6e57412727a4f06832d93577", "save_path": "github-repos/isabelle/LVPGroup-fpp", "path": "github-repos/isabelle/LVPGroup-fpp/fpp-7e18377ea2c553bf6e57412727a4f06832d93577/4_ds_algo/Sorting/Bubblesort.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392756357326, "lm_q2_score": 0.8289388083214156, "lm_q1q2_score": 0.7328144636548116}}
{"text": "(*  Title:      HOL/UNITY/ListOrder.thy\n    Author:     Lawrence C Paulson, Cambridge University Computer Laboratory\n    Copyright   1998  University of Cambridge\n\nLists are partially ordered by Charpentier's Generalized Prefix Relation\n   (xs,ys) : genPrefix(r)\n     if ys = xs' @ zs where length xs = length xs'\n     and corresponding elements of xs, xs' are pairwise related by r\n\nAlso overloads <= and < for lists!\n*)\n\nsection \\<open>The Prefix Ordering on Lists\\<close>\n\ntheory ListOrder\nimports Main\nbegin\n\ninductive_set\n  genPrefix :: \"('a * 'a)set => ('a list * 'a list)set\"\n  for r :: \"('a * 'a)set\"\n where\n   Nil:     \"([],[]) \\<in> genPrefix(r)\"\n\n | prepend: \"[| (xs,ys) \\<in> genPrefix(r);  (x,y) \\<in> r |] ==>\n             (x#xs, y#ys) \\<in> genPrefix(r)\"\n\n | append:  \"(xs,ys) \\<in> genPrefix(r) ==> (xs, ys@zs) \\<in> genPrefix(r)\"\n\ninstantiation list :: (type) ord \nbegin\n\ndefinition\n  prefix_def:        \"xs <= zs \\<longleftrightarrow>  (xs, zs) \\<in> genPrefix Id\"\n\ndefinition\n  strict_prefix_def: \"xs < zs  \\<longleftrightarrow>  xs \\<le> zs \\<and> \\<not> zs \\<le> (xs :: 'a list)\"\n\ninstance ..  \n\n(*Constants for the <= and >= relations, used below in translations*)\n\nend\n\ndefinition Le :: \"(nat*nat) set\" where\n    \"Le == {(x,y). x <= y}\"\n\ndefinition  Ge :: \"(nat*nat) set\" where\n    \"Ge == {(x,y). y <= x}\"\n\nabbreviation\n  pfixLe :: \"[nat list, nat list] => bool\"  (infixl \"pfixLe\" 50)  where\n  \"xs pfixLe ys == (xs,ys) \\<in> genPrefix Le\"\n\nabbreviation\n  pfixGe :: \"[nat list, nat list] => bool\"  (infixl \"pfixGe\" 50)  where\n  \"xs pfixGe ys == (xs,ys) \\<in> genPrefix Ge\"\n\n\nsubsection\\<open>preliminary lemmas\\<close>\n\nlemma Nil_genPrefix [iff]: \"([], xs) \\<in> genPrefix r\"\nby (cut_tac genPrefix.Nil [THEN genPrefix.append], auto)\n\nlemma genPrefix_length_le: \"(xs,ys) \\<in> genPrefix r \\<Longrightarrow> length xs <= length ys\"\nby (erule genPrefix.induct, auto)\n\nlemma cdlemma:\n     \"[| (xs', ys') \\<in> genPrefix r |]  \n      ==> (\\<forall>x xs. xs' = x#xs \\<longrightarrow> (\\<exists>y ys. ys' = y#ys & (x,y) \\<in> r & (xs, ys) \\<in> genPrefix r))\"\napply (erule genPrefix.induct, blast, blast)\napply (force intro: genPrefix.append)\ndone\n\n(*As usual converting it to an elimination rule is tiresome*)\nlemma cons_genPrefixE [elim!]: \n     \"[| (x#xs, zs) \\<in> genPrefix r;   \n         !!y ys. [| zs = y#ys;  (x,y) \\<in> r;  (xs, ys) \\<in> genPrefix r |] ==> P  \n      |] ==> P\"\nby (drule cdlemma, simp, blast)\n\nlemma Cons_genPrefix_Cons [iff]:\n     \"((x#xs,y#ys) \\<in> genPrefix r) = ((x,y) \\<in> r \\<and> (xs,ys) \\<in> genPrefix r)\"\nby (blast intro: genPrefix.prepend)\n\n\nsubsection\\<open>genPrefix is a partial order\\<close>\n\nlemma refl_genPrefix: \"refl r ==> refl (genPrefix r)\"\napply (unfold refl_on_def, auto)\napply (induct_tac \"x\")\nprefer 2 apply (blast intro: genPrefix.prepend)\napply (blast intro: genPrefix.Nil)\ndone\n\nlemma genPrefix_refl [simp]: \"refl r \\<Longrightarrow> (l,l) \\<in> genPrefix r\"\nby (erule refl_onD [OF refl_genPrefix UNIV_I])\n\nlemma genPrefix_mono: \"r<=s ==> genPrefix r <= genPrefix s\"\napply clarify\napply (erule genPrefix.induct)\napply (auto intro: genPrefix.append)\ndone\n\n\n(** Transitivity **)\n\n(*A lemma for proving genPrefix_trans_O*)\nlemma append_genPrefix:\n     \"(xs @ ys, zs) \\<in> genPrefix r \\<Longrightarrow> (xs, zs) \\<in> genPrefix r\"\n  by (induct xs arbitrary: zs) auto\n\n(*Lemma proving transitivity and more*)\nlemma genPrefix_trans_O:\n  assumes \"(x, y) \\<in> genPrefix r\"\n  shows \"\\<And>z. (y, z) \\<in> genPrefix s \\<Longrightarrow> (x, z) \\<in> genPrefix (r O s)\"\n  apply (atomize (full))\n  using assms\n  apply induct\n    apply blast\n   apply (blast intro: genPrefix.prepend)\n  apply (blast dest: append_genPrefix)\n  done\n\nlemma genPrefix_trans:\n  \"(x, y) \\<in> genPrefix r \\<Longrightarrow> (y, z) \\<in> genPrefix r \\<Longrightarrow> trans r\n    \\<Longrightarrow> (x, z) \\<in> genPrefix r\"\n  apply (rule trans_O_subset [THEN genPrefix_mono, THEN subsetD])\n   apply assumption\n  apply (blast intro: genPrefix_trans_O)\n  done\n\nlemma prefix_genPrefix_trans:\n  \"[| x<=y;  (y,z) \\<in> genPrefix r |] ==> (x, z) \\<in> genPrefix r\"\napply (unfold prefix_def)\napply (drule genPrefix_trans_O, assumption)\napply simp\ndone\n\nlemma genPrefix_prefix_trans:\n  \"[| (x,y) \\<in> genPrefix r;  y<=z |] ==> (x,z) \\<in> genPrefix r\"\napply (unfold prefix_def)\napply (drule genPrefix_trans_O, assumption)\napply simp\ndone\n\nlemma trans_genPrefix: \"trans r ==> trans (genPrefix r)\"\nby (blast intro: transI genPrefix_trans)\n\n\n(** Antisymmetry **)\n\nlemma genPrefix_antisym:\n  assumes 1: \"(xs, ys) \\<in> genPrefix r\"\n    and 2: \"antisym r\"\n    and 3: \"(ys, xs) \\<in> genPrefix r\"\n  shows \"xs = ys\"\n  using 1 3\nproof induct\n  case Nil\n  then show ?case by blast\nnext\n  case prepend\n  then show ?case using 2 by (simp add: antisym_def)\nnext\n  case (append xs ys zs)\n  then show ?case\n    apply -\n    apply (subgoal_tac \"length zs = 0\", force)\n    apply (drule genPrefix_length_le)+\n    apply (simp del: length_0_conv)\n    done\nqed\n\nlemma antisym_genPrefix: \"antisym r ==> antisym (genPrefix r)\"\n  by (blast intro: antisymI genPrefix_antisym)\n\n\nsubsection\\<open>recursion equations\\<close>\n\nlemma genPrefix_Nil [simp]: \"((xs, []) \\<in> genPrefix r) = (xs = [])\"\n  by (induct xs) auto\n\nlemma same_genPrefix_genPrefix [simp]: \n    \"refl r \\<Longrightarrow> ((xs@ys, xs@zs) \\<in> genPrefix r) = ((ys,zs) \\<in> genPrefix r)\"\n  by (induct xs) (simp_all add: refl_on_def)\n\nlemma genPrefix_Cons:\n     \"((xs, y#ys) \\<in> genPrefix r) =  \n      (xs=[] | (\\<exists>z zs. xs=z#zs & (z,y) \\<in> r & (zs,ys) \\<in> genPrefix r))\"\n  by (cases xs) auto\n\nlemma genPrefix_take_append:\n     \"[| refl r;  (xs,ys) \\<in> genPrefix r |]  \n      ==>  (xs@zs, take (length xs) ys @ zs) \\<in> genPrefix r\"\napply (erule genPrefix.induct)\napply (frule_tac [3] genPrefix_length_le)\napply (simp_all (no_asm_simp) add: diff_is_0_eq [THEN iffD2])\ndone\n\nlemma genPrefix_append_both:\n     \"[| refl r;  (xs,ys) \\<in> genPrefix r;  length xs = length ys |]  \n      ==>  (xs@zs, ys @ zs) \\<in> genPrefix r\"\napply (drule genPrefix_take_append, assumption)\napply simp\ndone\n\n\n(*NOT suitable for rewriting since [y] has the form y#ys*)\nlemma append_cons_eq: \"xs @ y # ys = (xs @ [y]) @ ys\"\nby auto\n\nlemma aolemma:\n     \"[| (xs,ys) \\<in> genPrefix r;  refl r |]  \n      ==> length xs < length ys \\<longrightarrow> (xs @ [ys ! length xs], ys) \\<in> genPrefix r\"\napply (erule genPrefix.induct)\n  apply blast\n apply simp\ntxt\\<open>Append case is hardest\\<close>\napply simp\napply (frule genPrefix_length_le [THEN le_imp_less_or_eq])\napply (erule disjE)\napply (simp_all (no_asm_simp) add: neq_Nil_conv nth_append)\napply (blast intro: genPrefix.append, auto)\napply (subst append_cons_eq, fast intro: genPrefix_append_both genPrefix.append)\ndone\n\nlemma append_one_genPrefix:\n     \"[| (xs,ys) \\<in> genPrefix r;  length xs < length ys;  refl r |]  \n      ==> (xs @ [ys ! length xs], ys) \\<in> genPrefix r\"\nby (blast intro: aolemma [THEN mp])\n\n\n(** Proving the equivalence with Charpentier's definition **)\n\nlemma genPrefix_imp_nth:\n    \"i < length xs \\<Longrightarrow> (xs, ys) \\<in> genPrefix r \\<Longrightarrow> (xs ! i, ys ! i) \\<in> r\"\n  apply (induct xs arbitrary: i ys)\n   apply auto\n  apply (case_tac i)\n   apply auto\n  done\n\nlemma nth_imp_genPrefix:\n  \"length xs <= length ys \\<Longrightarrow>\n     (\\<forall>i. i < length xs \\<longrightarrow> (xs ! i, ys ! i) \\<in> r) \\<Longrightarrow>\n     (xs, ys) \\<in> genPrefix r\"\n  apply (induct xs arbitrary: ys)\n   apply (simp_all add: less_Suc_eq_0_disj all_conj_distrib)\n  apply (case_tac ys)\n   apply (force+)\n  done\n\nlemma genPrefix_iff_nth:\n     \"((xs,ys) \\<in> genPrefix r) =  \n      (length xs <= length ys & (\\<forall>i. i < length xs \\<longrightarrow> (xs!i, ys!i) \\<in> r))\"\napply (blast intro: genPrefix_length_le genPrefix_imp_nth nth_imp_genPrefix)\ndone\n\n\nsubsection\\<open>The type of lists is partially ordered\\<close>\n\ndeclare refl_Id [iff] \n        antisym_Id [iff] \n        trans_Id [iff]\n\nlemma prefix_refl [iff]: \"xs <= (xs::'a list)\"\nby (simp add: prefix_def)\n\nlemma prefix_trans: \"!!xs::'a list. [| xs <= ys; ys <= zs |] ==> xs <= zs\"\napply (unfold prefix_def)\napply (blast intro: genPrefix_trans)\ndone\n\nlemma prefix_antisym: \"!!xs::'a list. [| xs <= ys; ys <= xs |] ==> xs = ys\"\napply (unfold prefix_def)\napply (blast intro: genPrefix_antisym)\ndone\n\nlemma prefix_less_le_not_le: \"!!xs::'a list. (xs < zs) = (xs <= zs & \\<not> zs \\<le> xs)\"\nby (unfold strict_prefix_def, auto)\n\ninstance list :: (type) order\n  by (intro_classes,\n      (assumption | rule prefix_refl prefix_trans prefix_antisym\n                     prefix_less_le_not_le)+)\n\n(*Monotonicity of \"set\" operator WRT prefix*)\nlemma set_mono: \"xs <= ys ==> set xs <= set ys\"\napply (unfold prefix_def)\napply (erule genPrefix.induct, auto)\ndone\n\n\n(** recursion equations **)\n\nlemma Nil_prefix [iff]: \"[] <= xs\"\nby (simp add: prefix_def)\n\nlemma prefix_Nil [simp]: \"(xs <= []) = (xs = [])\"\nby (simp add: prefix_def)\n\nlemma Cons_prefix_Cons [simp]: \"(x#xs <= y#ys) = (x=y & xs<=ys)\"\nby (simp add: prefix_def)\n\nlemma same_prefix_prefix [simp]: \"(xs@ys <= xs@zs) = (ys <= zs)\"\nby (simp add: prefix_def)\n\nlemma append_prefix [iff]: \"(xs@ys <= xs) = (ys <= [])\"\nby (insert same_prefix_prefix [of xs ys \"[]\"], simp)\n\nlemma prefix_appendI [simp]: \"xs <= ys ==> xs <= ys@zs\"\napply (unfold prefix_def)\napply (erule genPrefix.append)\ndone\n\nlemma prefix_Cons: \n   \"(xs <= y#ys) = (xs=[] | (\\<exists>zs. xs=y#zs \\<and> zs <= ys))\"\nby (simp add: prefix_def genPrefix_Cons)\n\nlemma append_one_prefix: \n  \"[| xs <= ys; length xs < length ys |] ==> xs @ [ys ! length xs] <= ys\"\napply (unfold prefix_def)\napply (simp add: append_one_genPrefix)\ndone\n\nlemma prefix_length_le: \"xs <= ys ==> length xs <= length ys\"\napply (unfold prefix_def)\napply (erule genPrefix_length_le)\ndone\n\nlemma splemma: \"xs<=ys ==> xs~=ys --> length xs < length ys\"\napply (unfold prefix_def)\napply (erule genPrefix.induct, auto)\ndone\n\nlemma strict_prefix_length_less: \"xs < ys ==> length xs < length ys\"\napply (unfold strict_prefix_def)\napply (blast intro: splemma [THEN mp])\ndone\n\nlemma mono_length: \"mono length\"\nby (blast intro: monoI prefix_length_le)\n\n(*Equivalence to the definition used in Lex/Prefix.thy*)\nlemma prefix_iff: \"(xs <= zs) = (\\<exists>ys. zs = xs@ys)\"\napply (unfold prefix_def)\napply (auto simp add: genPrefix_iff_nth nth_append)\napply (rule_tac x = \"drop (length xs) zs\" in exI)\napply (rule nth_equalityI)\napply (simp_all (no_asm_simp) add: nth_append)\ndone\n\nlemma prefix_snoc [simp]: \"(xs <= ys@[y]) = (xs = ys@[y] | xs <= ys)\"\napply (simp add: prefix_iff)\napply (rule iffI)\n apply (erule exE)\n apply (rename_tac \"zs\")\n apply (rule_tac xs = zs in rev_exhaust)\n  apply simp\n apply clarify\n apply (simp del: append_assoc add: append_assoc [symmetric], force)\ndone\n\nlemma prefix_append_iff:\n     \"(xs <= ys@zs) = (xs <= ys | (\\<exists>us. xs = ys@us & us <= zs))\"\napply (rule_tac xs = zs in rev_induct)\n apply force\napply (simp del: append_assoc add: append_assoc [symmetric], force)\ndone\n\n(*Although the prefix ordering is not linear, the prefixes of a list\n  are linearly ordered.*)\nlemma common_prefix_linear:\n  fixes xs ys zs :: \"'a list\"\n  shows \"xs <= zs \\<Longrightarrow> ys <= zs \\<Longrightarrow> xs <= ys | ys <= xs\"\n  by (induct zs rule: rev_induct) auto\n\nsubsection\\<open>pfixLe, pfixGe: properties inherited from the translations\\<close>\n\n(** pfixLe **)\n\nlemma refl_Le [iff]: \"refl Le\"\nby (unfold refl_on_def Le_def, auto)\n\nlemma antisym_Le [iff]: \"antisym Le\"\nby (unfold antisym_def Le_def, auto)\n\nlemma trans_Le [iff]: \"trans Le\"\nby (unfold trans_def Le_def, auto)\n\nlemma pfixLe_refl [iff]: \"x pfixLe x\"\nby simp\n\nlemma pfixLe_trans: \"[| x pfixLe y; y pfixLe z |] ==> x pfixLe z\"\nby (blast intro: genPrefix_trans)\n\nlemma pfixLe_antisym: \"[| x pfixLe y; y pfixLe x |] ==> x = y\"\nby (blast intro: genPrefix_antisym)\n\nlemma prefix_imp_pfixLe: \"xs<=ys ==> xs pfixLe ys\"\napply (unfold prefix_def Le_def)\napply (blast intro: genPrefix_mono [THEN [2] rev_subsetD])\ndone\n\nlemma refl_Ge [iff]: \"refl Ge\"\nby (unfold refl_on_def Ge_def, auto)\n\nlemma antisym_Ge [iff]: \"antisym Ge\"\nby (unfold antisym_def Ge_def, auto)\n\nlemma trans_Ge [iff]: \"trans Ge\"\nby (unfold trans_def Ge_def, auto)\n\nlemma pfixGe_refl [iff]: \"x pfixGe x\"\nby simp\n\nlemma pfixGe_trans: \"[| x pfixGe y; y pfixGe z |] ==> x pfixGe z\"\nby (blast intro: genPrefix_trans)\n\nlemma pfixGe_antisym: \"[| x pfixGe y; y pfixGe x |] ==> x = y\"\nby (blast intro: genPrefix_antisym)\n\nlemma prefix_imp_pfixGe: \"xs<=ys ==> xs pfixGe ys\"\napply (unfold prefix_def Ge_def)\napply (blast intro: genPrefix_mono [THEN [2] rev_subsetD])\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/UNITY/ListOrder.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392725805823, "lm_q2_score": 0.8289388083214156, "lm_q1q2_score": 0.7328144611222791}}
{"text": "(* Author: Anthony Bordg, University of Cambridge, apdb3@cam.ac.uk *)\n\ntheory Tensor\nimports  \n  Complex_Vectors\n  Matrix_Tensor.Matrix_Tensor\n  Jordan_Normal_Form.Matrix\nbegin\n\ntext \\<open>\nThere is already a formalization of tensor products in the Archive of Formal Proofs, \nnamely Matrix_Tensor.thy in Tensor Product of Matrices[1] by T.V.H. Prathamesh, but it does not build \non top of the formalization of vectors and matrices given in Matrices, Jordan Normal Forms, and \nSpectral Radius Theory[2] by Ren\u00e9 Thiemann and Akihisa Yamada. \nIn the present theory our purpose consists in giving such a formalization. Of course, we will reuse \nPrathamesh's code as much as possible, and in order to achieve that we formalize some lemmas that\ntranslate back and forth between vectors (resp. matrices) seen as lists (resp. lists of lists) and \nvectors (resp. matrices) as formalized in [2].\n\\<close>\n\nsection \\<open>Tensor Products\\<close>\n\nsubsection \\<open>The Kronecker Product of Complex Vectors\\<close>\n\ndefinition tensor_vec:: \"complex Matrix.vec \\<Rightarrow> complex Matrix.vec \\<Rightarrow> complex Matrix.vec\" (infixl \"\\<otimes>\" 63) \nwhere \"tensor_vec u v \\<equiv> vec_of_list (mult.vec_vec_Tensor (*) (list_of_vec u) (list_of_vec v))\"\n\nsubsection \\<open>The Tensor Product of Complex Matrices\\<close>\n\ntext \\<open>To see a matrix in the sense of [2] as a matrix in the sense of [1], we convert it into its list\nof column vectors.\\<close>\n\ndefinition mat_to_cols_list:: \"complex Matrix.mat \\<Rightarrow> complex list list\" where\n  \"mat_to_cols_list A = [[A $$ (i,j) . i <- [0..< dim_row A]] . j <- [0..< dim_col A]]\"\n\nlemma length_mat_to_cols_list [simp]:\n  \"length (mat_to_cols_list A) = dim_col A\"\n  by (simp add: mat_to_cols_list_def)\n\nlemma length_cols_mat_to_cols_list [simp]:\n  assumes \"j < dim_col A\"\n  shows \"length [A $$ (i,j) . i <- [0..< dim_row A]] = dim_row A\"\n  using assms by simp\n\nlemma length_row_mat_to_cols_list [simp]:\n  assumes \"i < dim_row A\"\n  shows \"length (row (mat_to_cols_list A) i) = dim_col A\"\n  using assms by (simp add: row_def)\n\nlemma length_col_mat_to_cols_list [simp]:\n  assumes \"j < dim_col A\"\n  shows \"length (col (mat_to_cols_list A) j) = dim_row A\"\n  using assms by (simp add: col_def mat_to_cols_list_def)\n\nlemma mat_to_cols_list_is_not_Nil [simp]:\n  assumes \"dim_col A > 0\"\n  shows \"mat_to_cols_list A \\<noteq> []\"\n  using assms by (simp add: mat_to_cols_list_def)\n\ntext \\<open>Link between Matrix_Tensor.row_length and Matrix.dim_row\\<close>\n\nlemma row_length_mat_to_cols_list [simp]:\n  assumes \"dim_col A > 0\"\n  shows \"mult.row_length (mat_to_cols_list A) = dim_row A\"\nproof -\n  have \"mat_to_cols_list A \\<noteq> []\" by (simp add: assms)\n  then have \"mult.row_length (mat_to_cols_list A) = length (hd (mat_to_cols_list A))\"\n    using mult.row_length_def[of \"1\" \"(*)\"]\n    by (simp add: \\<open>\\<And>xs. Matrix_Tensor.mult 1 (*) \\<Longrightarrow> mult.row_length xs \\<equiv> if xs = [] then 0 else length (hd xs)\\<close> mult.intro)\n  thus ?thesis by (simp add: assms mat_to_cols_list_def upt_conv_Cons)\nqed\n\ntext \\<open>@{term mat_to_cols_list} is a matrix in the sense of @{theory Matrix.Matrix_Legacy}.\\<close>\n\nlemma mat_to_cols_list_is_mat [simp]:\n  assumes \"dim_col A > 0\"\n  shows \"mat (mult.row_length (mat_to_cols_list A)) (length (mat_to_cols_list A)) (mat_to_cols_list A)\"\nproof -\n  have \"Ball (set (mat_to_cols_list A)) (Matrix_Legacy.vec (mult.row_length (mat_to_cols_list A)))\"\n    using assms row_length_mat_to_cols_list mat_to_cols_list_def Ball_def set_def vec_def by fastforce\n  thus ?thesis by(auto simp: mat_def)\nqed\n\ndefinition mat_of_cols_list:: \"nat \\<Rightarrow> complex list list \\<Rightarrow> complex Matrix.mat\" where\n  \"mat_of_cols_list nr cs = Matrix.mat nr (length cs) (\\<lambda> (i,j). cs ! j ! i)\"\n\nlemma index_mat_of_cols_list [simp]:\n  assumes \"i < nr\" and \"j < length cs\"\n  shows \"mat_of_cols_list nr cs $$ (i,j) = cs ! j ! i\"\n  by (simp add: assms mat_of_cols_list_def) \n\nlemma mat_to_cols_list_to_mat [simp]:\n  \"mat_of_cols_list (dim_row A) (mat_to_cols_list A) = A\"\nproof\n  show f1:\"dim_row (mat_of_cols_list (dim_row A) (mat_to_cols_list A)) = dim_row A\" \n    by (simp add: mat_of_cols_list_def)\nnext\n  show f2:\"dim_col (mat_of_cols_list (dim_row A) (mat_to_cols_list A)) = dim_col A\"\n    by (simp add: Tensor.mat_of_cols_list_def)\nnext\n  show \"\\<And>i j. i < dim_row A \\<Longrightarrow> j < dim_col A \\<Longrightarrow> \n    (mat_of_cols_list (dim_row A) (mat_to_cols_list A)) $$ (i, j) = A $$ (i, j)\"\n    by (simp add: mat_of_cols_list_def mat_to_cols_list_def)\nqed\n\nlemma plus_mult_cpx [simp]:\n  \"plus_mult 1 (*) 0 (+) (a_inv cpx_rng)\"\n  apply unfold_locales\n  apply (auto intro: cpx_cring_is_field simp: field_simps)\nproof -\n  show \"\\<And>x. x + \\<ominus>\\<^bsub>cpx_rng\\<^esub> x = 0\"\n    using group.r_inv[of \"cpx_rng\"] cpx_cring_is_field field_def domain_def cpx_rng_def\n    by (metis UNIV_I cring.cring_simprules(17) ordered_semiring_record_simps(1) \n        ordered_semiring_record_simps(11) ordered_semiring_record_simps(12))\n  show \"\\<And>x. x + \\<ominus>\\<^bsub>cpx_rng\\<^esub> x = 0\"\n    using group.r_inv[of \"cpx_rng\"] cpx_cring_is_field field_def domain_def cpx_rng_def\n    by (metis UNIV_I cring.cring_simprules(17) ordered_semiring_record_simps(1) \n        ordered_semiring_record_simps(11) ordered_semiring_record_simps(12))\nqed\n\nlemma list_to_mat_to_cols_list [simp]:\n  fixes l::\"complex list list\"\n  assumes \"mat nr nc l\"\n  shows \"mat_to_cols_list (mat_of_cols_list nr l) = l\"\nproof -\n  have \"length (mat_to_cols_list (mat_of_cols_list nr l)) = length l\"\n    by (simp add: mat_of_cols_list_def)\n  moreover have f1:\"\\<forall>j<length l. length(l ! j) = mult.row_length l\"\n    using assms plus_mult.row_length_constant plus_mult_cpx by fastforce\n  moreover have \"\\<And>j. j<length l \\<longrightarrow> mat_to_cols_list (mat_of_cols_list nr l) ! j = l ! j\"\n  proof\n    fix j\n    assume a:\"j < length l\"\n    then have f2:\"length (mat_to_cols_list (mat_of_cols_list nr l) ! j) = length (l ! j)\"\n      by (metis col_def mat_def vec_def mat_of_cols_list_def assms dim_col_mat(1) dim_row_mat(1) \nlength_col_mat_to_cols_list nth_mem)\n    then have \"\\<forall>i<mult.row_length l. mat_to_cols_list (mat_of_cols_list nr l) ! j ! i = l ! j ! i\"\n      using a mat_to_cols_list_def mat_of_cols_list_def f1 by simp\n    thus \"mat_to_cols_list (Tensor.mat_of_cols_list nr l) ! j = l ! j\"\n      using f2 by(simp add: nth_equalityI a f1)\n  qed\n  ultimately show ?thesis using nth_equalityI by metis\nqed\n\nlemma col_mat_of_cols_list [simp]:\n  assumes \"j < length l\"\n  shows \"Matrix.col (mat_of_cols_list (length (l ! j)) l) j = vec_of_list (l ! j)\"\nproof -\n  define u where \"u = Matrix.col (mat_of_cols_list (length (l ! j)) l) j\"\n  then have \"dim_vec u = dim_vec (vec_of_list (l ! j))\"\n    apply(auto simp: u_def mat_of_cols_list_def Matrix.col_def vec_of_list_def)\n    by (metis dim_vec_of_list vec_of_list.abs_eq)\n  moreover have \"\\<forall>i<length(l ! j). u $ i = vec_of_list (l ! j) $ i\"\n    by (simp add: u_def vec_of_list_index mat_of_cols_list_def assms)\n  ultimately show ?thesis by(simp add: vec_eq_iff u_def)\nqed\n\ndefinition tensor_mat:: \"[complex Matrix.mat, complex Matrix.mat] \\<Rightarrow> complex Matrix.mat\" (infixl \"\\<Otimes>\" 63) where \n\"tensor_mat A B \\<equiv> \n  mat_of_cols_list (dim_row A * dim_row B) (mult.Tensor (*) (mat_to_cols_list A) (mat_to_cols_list B))\"\n  \nlemma dim_row_tensor_mat [simp]:\n  \"dim_row (A \\<Otimes> B) = dim_row A * dim_row B\"\n  by (simp add: mat_of_cols_list_def tensor_mat_def)\n\nlemma dim_col_tensor_mat [simp]:\n  \"dim_col (A \\<Otimes> B) = dim_col A * dim_col B\"\n  using tensor_mat_def mat_of_cols_list_def mult.length_Tensor[of \"1\" \"(*)\"]\n  by(simp add: \\<open>\\<And>M2 M1. Matrix_Tensor.mult 1 (*) \\<Longrightarrow> length (mult.Tensor (*) M1 M2) = length M1 * length M2\\<close> mult.intro)\n\nlemma index_tensor_mat [simp]:\n  assumes a1:\"dim_row A = rA\" and a2:\"dim_col A = cA\" and a3:\"dim_row B = rB\" and a4:\"dim_col B = cB\"\n    and a5:\"i < rA * rB\" and a6:\"j < cA * cB\" and a7:\"cA > 0\" and a8:\"cB > 0\"\n  shows \"(A \\<Otimes> B) $$ (i,j) = A $$ (i div rB, j div cB) * B $$ (i mod rB, j mod cB)\"\nproof -\n  have \"(A \\<Otimes> B) $$ (i,j) = (mult.Tensor (*) (mat_to_cols_list A) (mat_to_cols_list B)) ! j ! i\"\n    using assms tensor_mat_def mat_of_cols_list_def dim_col_tensor_mat by simp\n  moreover have f:\"i < mult.row_length (mat_to_cols_list A) * mult.row_length (mat_to_cols_list B)\"\n    by (simp add: a1 a2 a3 a4 a5 a7 a8)\n  moreover have \"j < length (mat_to_cols_list A) * length (mat_to_cols_list B)\"\n    by (simp add: a2 a4 a6)\n  moreover have \"mat (mult.row_length (mat_to_cols_list A)) (length (mat_to_cols_list A)) (mat_to_cols_list A)\"\n    using a2 a7 mat_to_cols_list_is_mat by blast \n  moreover have \"mat (mult.row_length (mat_to_cols_list B)) (length (mat_to_cols_list B)) (mat_to_cols_list B)\"\n    using a4 a8 mat_to_cols_list_is_mat by blast\n  ultimately have \"(A \\<Otimes> B) $$ (i,j) = \n    (mat_to_cols_list A) ! (j div length (mat_to_cols_list B)) ! (i div mult.row_length (mat_to_cols_list B)) \n    * (mat_to_cols_list B) ! (j mod length (mat_to_cols_list B)) ! (i mod mult.row_length (mat_to_cols_list B))\"\n    using mult.matrix_Tensor_elements[of \"1\" \"(*)\"]\n    by(simp add: \\<open>\\<And>M2 M1. mult 1 (*) \\<Longrightarrow> \\<forall>i j. (i<mult.row_length M1 * mult.row_length M2 \n    \\<and> j<length M1 * length M2) \\<and> mat (mult.row_length M1) (length M1) M1 \\<and> mat (mult.row_length M2) (length M2) M2 \\<longrightarrow> \n    mult.Tensor (*) M1 M2 ! j ! i = M1 ! (j div length M2) ! (i div mult.row_length M2) * M2 ! (j mod length M2) ! (i mod mult.row_length M2)\\<close>  mult.intro)\n  thus ?thesis\n    using mat_to_cols_list_def\n    by (metis a2 a3 a4 a6 f index_mat_of_cols_list length_mat_to_cols_list less_mult_imp_div_less \nless_nat_zero_code mat_to_cols_list_to_mat mult_0_right neq0_conv row_length_mat_to_cols_list \nunique_euclidean_semiring_numeral_class.pos_mod_bound)\nqed\n\ntext \\<open>To go from @{term Matrix.row} to @{term Matrix_Legacy.row}\\<close>\n\nlemma Matrix_row_is_Legacy_row:\n  assumes \"i < dim_row A\"\n  shows \"Matrix.row A i = vec_of_list (row (mat_to_cols_list A) i)\"\nproof\n  show \"dim_vec (Matrix.row A i) = dim_vec (vec_of_list (row (mat_to_cols_list A) i))\"\n    using length_mat_to_cols_list Matrix.dim_vec_of_list by (metis row_def index_row(2) length_map)\nnext\n  show \"\\<And>j. j<dim_vec (vec_of_list (row (mat_to_cols_list A) i)) \\<Longrightarrow> \n              Matrix.row A i $ j = vec_of_list (row (mat_to_cols_list A) i) $ j\"\n    using Matrix.row_def vec_of_list_def mat_to_cols_list_def\n    by(smt row_def assms dim_vec_of_list index_mat_of_cols_list index_row(1) \nlength_mat_to_cols_list length_row_mat_to_cols_list mat_to_cols_list_to_mat nth_map vec_of_list_index)\nqed\n\ntext \\<open>To go from @{term Matrix_Legacy.row} to @{term Matrix.row}\\<close>\n\nlemma Legacy_row_is_Matrix_row:\n  assumes \"i < mult.row_length A\"\n  shows \"row A i = list_of_vec (Matrix.row (mat_of_cols_list (mult.row_length A) A) i)\"\nproof (rule nth_equalityI)\n  show \"length (row A i) = length (list_of_vec (Matrix.row (mat_of_cols_list (mult.row_length A) A) i))\"\n    using row_def length_list_of_vec by(metis mat_of_cols_list_def dim_col_mat(1) index_row(2) length_map)\nnext\n  fix j:: nat\n  assume \"j < length (row A i)\"\n  then show \"row A i ! j = list_of_vec (Matrix.row (mat_of_cols_list (mult.row_length A) A) i) ! j\"\n    using assms index_mat_of_cols_list\n    by(metis row_def mat_of_cols_list_def dim_col_mat(1) dim_row_mat(1) index_row(1) length_map list_of_vec_index nth_map)\nqed\n\ntext \\<open>To go from @{term Matrix.col} to @{term Matrix_Legacy.col}\\<close>\n\nlemma Matrix_col_is_Legacy_col:\n  assumes \"j < dim_col A\"\n  shows \"Matrix.col A j = vec_of_list (col (mat_to_cols_list A) j)\"\nproof\n  show \"dim_vec (Matrix.col A j) = dim_vec (vec_of_list (col (mat_to_cols_list A) j))\"\n    by (simp add: col_def assms mat_to_cols_list_def)\nnext\n  show \"\\<And>i. i < dim_vec (vec_of_list (col (mat_to_cols_list A) j)) \\<Longrightarrow>\n         Matrix.col A j $ i = vec_of_list (col (mat_to_cols_list A) j) $ i\"\n    using mat_to_cols_list_def\n    by (metis col_def assms col_mat_of_cols_list length_col_mat_to_cols_list length_mat_to_cols_list \nmat_to_cols_list_to_mat)\nqed\n\ntext \\<open>To go from @{term Matrix_Legacy.col} to @{term Matrix.col}\\<close>\n\nlemma Legacy_col_is_Matrix_col:\n  assumes a1:\"j < length A\" and a2:\"length (A ! j) = mult.row_length A\"\n  shows \"col A j = list_of_vec (Matrix.col (mat_of_cols_list (mult.row_length A) A) j)\"\nproof (rule nth_equalityI)\n  have \"length (list_of_vec (Matrix.col (mat_of_cols_list (mult.row_length A) A) j)) = \ndim_vec (Matrix.col (mat_of_cols_list (mult.row_length A) A) j)\"\n    using length_list_of_vec by blast\n  also have \"\\<dots> = dim_row (mat_of_cols_list (mult.row_length A) A)\"\n    using Matrix.col_def by simp\n  also have f1:\"\\<dots> = mult.row_length A\"\n    by (simp add: mat_of_cols_list_def)\n  finally show f2:\"length (col A j) = length (list_of_vec (Matrix.col (mat_of_cols_list (mult.row_length A) A) j))\"\n    using a2 by (simp add: col_def)\nnext\n  fix i:: nat\n  assume \"i<length (col A j)\"\n  then show \"(col A j) ! i = (list_of_vec (Matrix.col (mat_of_cols_list (mult.row_length A) A) j)) ! i\"\n    by (metis col_def a1 a2 col_mat_of_cols_list list_vec) \nqed\n\ntext \\<open>Link between @{term plus_mult.scalar_product} and @{term Matrix.scalar_prod}\\<close>\n\nlemma scalar_prod_is_Matrix_scalar_prod [simp]:\n  fixes u::\"complex list\" and v::\"complex list\"\n  assumes \"length u = length v\"\n  shows \"plus_mult.scalar_product (*) 0 (+) u v = (vec_of_list u) \\<bullet> (vec_of_list v)\"\nproof -\n  have f:\"(vec_of_list u) \\<bullet> (vec_of_list v) = (\\<Sum>i=0..<length v. u ! i * v ! i)\"\n    using assms scalar_prod_def[of \"vec_of_list u\" \"vec_of_list v\"] Matrix.dim_vec_of_list[of v] index_vec_of_list\n    by (metis (no_types, lifting) atLeastLessThan_iff sum.cong)\n  thus ?thesis\n  proof -\n    have \"plus_mult.scalar_product (*) 0 (+) u v = semiring_0_class.scalar_prod u v\"\n      using  plus_mult.scalar_product_def[of 1 \"(*)\" 0 \"(+)\" \"a_inv cpx_rng\" u v] by simp\n    also have \"\\<dots> = sum_list (map (\\<lambda>(x,y). x * y) (zip u v))\"\n      by (simp add: scalar_prod) \n    moreover have \"\\<forall>i<length v. (zip u v) ! i = (u ! i, v ! i)\"\n      using assms zip_def by simp\n    then have \"\\<forall>i<length v. (map (\\<lambda>(x,y). x * y) (zip u v)) ! i = u ! i * v ! i\"\n      by (simp add: assms)\n    ultimately have \"plus_mult.scalar_product (*) 0 (+) u v = (\\<Sum>i=0..<length v. u ! i * v ! i)\"\n      by(metis (no_types, lifting) assms atLeastLessThan_iff length_map map_fst_zip sum.cong sum_list_sum_nth)\n    thus ?thesis by (simp add: f)\n  qed\nqed\n\ntext \\<open>Link between @{term times} and @{term plus_mult.matrix_mult}\\<close>\n\nlemma matrix_mult_to_times_mat:\n  assumes \"dim_col A > 0\" and \"dim_col B > 0\" and \"dim_col (A::complex Matrix.mat) = dim_row B\"\n  shows \"A * B = mat_of_cols_list (dim_row A) (plus_mult.matrix_mult (*) 0 (+) (mat_to_cols_list A) (mat_to_cols_list B))\"\nproof\n  define M where \"M = mat_of_cols_list (dim_row A) (plus_mult.matrix_mult (*) 0 (+) (mat_to_cols_list A) (mat_to_cols_list B))\"\n  then show f1:\"dim_row (A * B) = dim_row M\"\n    by (simp add: mat_of_cols_list_def times_mat_def)\n  have \"length (plus_mult.matrix_mult (*) 0 (+) (mat_to_cols_list A) (mat_to_cols_list B)) = dim_col B\"\n    by (simp add: mat_multI_def)\n  then show f2:\"dim_col (A * B) = dim_col M\"\n    by (simp add: M_def times_mat_def mat_of_cols_list_def)\n  show \"\\<And>i j. i < dim_row M \\<Longrightarrow> j < dim_col M \\<Longrightarrow> (A * B) $$ (i, j) = M $$ (i, j)\"\n  proof -\n    fix i j\n    assume a1:\"i < dim_row M\" and a2:\"j < dim_col M\"\n    then have \"(A * B) $$ (i,j) = Matrix.row A i \\<bullet> Matrix.col B j\"\n      using f1 f2 by simp\n    also have \"\\<dots> = vec_of_list (row (mat_to_cols_list A) i) \\<bullet> vec_of_list (col (mat_to_cols_list B) j)\"\n      using f1 f2 a1 a2 by (simp add: Matrix_row_is_Legacy_row Matrix_col_is_Legacy_col)\n    also have \"\\<dots> = plus_mult.scalar_product (*) 0 (+) (row (mat_to_cols_list A) i) (col (mat_to_cols_list B) j)\"\n      using a1 a2 assms(3) f1 f2 by simp\n    also have \"M $$ (i,j) =  plus_mult.scalar_product (*) 0 (+) (row (mat_to_cols_list A) i) (col (mat_to_cols_list B) j)\"\n    proof-\n      have \"M $$ (i,j) = (plus_mult.matrix_mult (*) 0 (+) (mat_to_cols_list A) (mat_to_cols_list B)) ! j ! i\"\n        using M_def f1 f2 \n\\<open>length (mat_mult (mult.row_length (mat_to_cols_list A)) (mat_to_cols_list A) (mat_to_cols_list B)) = dim_col B\\<close> a1 a2 by simp\n      moreover have \"mat (mult.row_length (mat_to_cols_list A)) (dim_col A) (mat_to_cols_list A)\"\n        using mat_to_cols_list_is_mat assms(1) by simp\n      moreover have \"mat (dim_col A) (dim_col B) (mat_to_cols_list B)\"\n        using assms(2) assms(3) mat_to_cols_list_is_mat by simp\n      ultimately show ?thesis\n        using assms(1) a1 a2 row_length_mat_to_cols_list plus_mult.matrix_index[of 1 \"(*)\" 0 \"(+)\"] plus_mult_cpx\n        by (smt f1 f2 index_mult_mat(2) index_mult_mat(3))\n    qed\n    finally show \"(A * B) $$ (i, j) = M $$ (i, j)\" by simp\n  qed\nqed\n\nlemma mat_to_cols_list_times_mat [simp]:\n  assumes \"dim_col A = dim_row B\" and \"dim_col A > 0\"\n  shows \"mat_to_cols_list (A * B) = plus_mult.matrix_mult (*) 0 (+) (mat_to_cols_list A) (mat_to_cols_list B)\"\nproof (rule nth_equalityI)\n  define M where \"M = plus_mult.matrix_mult (*) 0 (+) (mat_to_cols_list A) (mat_to_cols_list B)\"\n  then show f0:\"length (mat_to_cols_list (A * B)) = length M\" by (simp add: mat_multI_def)\n  moreover have f1:\"\\<And>j. j<length (mat_to_cols_list (A * B)) \\<longrightarrow> mat_to_cols_list (A * B) ! j = M ! j\"\n  proof\n    fix j:: nat\n    assume a0:\"j < length (mat_to_cols_list (A * B))\"\n    then have \"length (mat_to_cols_list (A * B) ! j) = dim_row A\"\n      by (simp add: mat_to_cols_list_def)\n    then also have f2:\"length (M ! j) = dim_row A\"\n      using a0 M_def mat_multI_def[of 0 \"(+)\" \"(*)\" \"dim_row A\" \"mat_to_cols_list A\" \"mat_to_cols_list B\"] \n        row_length_mat_to_cols_list assms(2)\n      by (metis assms(1) f0 length_greater_0_conv length_map length_mat_to_cols_list \nlist_to_mat_to_cols_list mat_mult mat_to_cols_list_is_mat matrix_mult_to_times_mat)\n    ultimately have \"length (mat_to_cols_list (A * B) ! j) = length (M ! j)\" by simp\n    moreover have \"\\<And>i. i<dim_row A \\<longrightarrow> mat_to_cols_list (A * B) ! j ! i = M ! j ! i\"\n    proof\n      fix i\n      assume a1:\"i < dim_row A\"\n      have \"mat (mult.row_length (mat_to_cols_list A)) (dim_col A) (mat_to_cols_list A)\"\n        using mat_to_cols_list_is_mat assms(2) by simp\n      moreover have \"mat (dim_col A) (dim_col B) (mat_to_cols_list B)\"\n        using mat_to_cols_list_is_mat assms(1) a0 by simp\n      ultimately have \"M ! j ! i = plus_mult.scalar_product (*) 0 (+) (row (mat_to_cols_list A) i) (col (mat_to_cols_list B) j)\"\n        using plus_mult.matrix_index a0 a1 row_length_mat_to_cols_list assms(2) plus_mult_cpx M_def\n        by (metis index_mult_mat(3) length_mat_to_cols_list)\n      also have \"\\<dots> = vec_of_list (row (mat_to_cols_list A) i) \\<bullet> vec_of_list (col (mat_to_cols_list B) j)\"\n        using a0 a1 assms(1) by simp\n      finally show \"mat_to_cols_list (A * B) ! j ! i = M ! j ! i\"\n        using mat_to_cols_list_def index_mult_mat(1) a0 a1 \n        by(simp add: Matrix_row_is_Legacy_row Matrix_col_is_Legacy_col)\n    qed\n    ultimately show \"mat_to_cols_list (A * B) ! j = M ! j\" by(simp add: nth_equalityI f2)\n  qed\n  fix i:: nat\n  assume \"i < length (mat_to_cols_list (A * B))\"\n  thus \"mat_to_cols_list (A * B) ! i = M ! i\" by (simp add: f1)\nqed\n\ntext \\<open> \nFinally, we prove that the tensor product of complex matrices is distributive over the \nmultiplication of complex matrices. \n\\<close>\n\nlemma mult_distr_tensor:\n  assumes a1:\"dim_col A = dim_row B\" and a2:\"dim_col C = dim_row D\" and a3:\"dim_col A > 0\" and \n    a4:\"dim_col B > 0\" and a5:\"dim_col C > 0\" and a6:\"dim_col D > 0\"\n  shows \"(A * B) \\<Otimes> (C * D) = (A \\<Otimes> C) * (B \\<Otimes> D)\"\nproof -\n  define A' B' C' D' M N where \"A' = mat_to_cols_list A\" and \"B' = mat_to_cols_list B\" and \n    \"C' = mat_to_cols_list C\" and \"D' = mat_to_cols_list D\" and\n    \"M = mat_of_cols_list (dim_row A * dim_row C) (mult.Tensor (*) (mat_to_cols_list A) (mat_to_cols_list C))\" and\n    \"N = mat_of_cols_list (dim_row B * dim_row D) (mult.Tensor (*) (mat_to_cols_list B) (mat_to_cols_list D))\"\n  then have \"(A \\<Otimes> C) * (B \\<Otimes> D) = M * N\"\n    by (simp add: tensor_mat_def)\n  also have \"\\<dots> = mat_of_cols_list (dim_row A * dim_row C) (plus_mult.matrix_mult (*) 0 (+) \n  (mat_to_cols_list M) (mat_to_cols_list N))\"\n    using assms M_def N_def dim_col_tensor_mat dim_row_tensor_mat tensor_mat_def \n    by(simp add: matrix_mult_to_times_mat)\n  also have f1:\"\\<dots> = mat_of_cols_list (dim_row A * dim_row C) (plus_mult.matrix_mult (*) 0 (+) \n  (mult.Tensor (*) A' C') (mult.Tensor (*) B' D'))\"\n  proof -\n    define M' N' where \"M' = mult.Tensor (*) (mat_to_cols_list A) (mat_to_cols_list C)\" and\n      \"N' = mult.Tensor (*) (mat_to_cols_list B) (mat_to_cols_list D)\"\n    then have \"mat (mult.row_length M') (length M') M'\"\n      using M'_def mult.effective_well_defined_Tensor[of 1 \"(*)\"] mat_to_cols_list_is_mat a3 a5\n      by (smt mult.length_Tensor mult.row_length_mat plus_mult_cpx plus_mult_def)\n    moreover have \"mat (mult.row_length N') (length N') N'\"\n      using N'_def mult.effective_well_defined_Tensor[of 1 \"(*)\"] mat_to_cols_list_is_mat a4 a6\n      by (smt mult.length_Tensor mult.row_length_mat plus_mult_cpx plus_mult_def)\n    ultimately show ?thesis\n      using list_to_mat_to_cols_list M_def N_def mult.row_length_mat row_length_mat_to_cols_list \n      assms(3) a4 a5 a6 A'_def B'_def C'_def D'_def by(metis M'_def N'_def plus_mult_cpx plus_mult_def)\n   qed\n   also have \"\\<dots> = mat_of_cols_list (dim_row A * dim_row C) (mult.Tensor (*)\n    (plus_mult.matrix_mult (*) 0 (+) A' B')\n    (plus_mult.matrix_mult (*) 0 (+) C' D'))\"\n   proof -\n     have f2:\"mat (mult.row_length A') (length A') A'\"\n       using A'_def a3 mat_to_cols_list_is_mat by simp\n     moreover have \"mat (mult.row_length B') (length B') B'\"\n       using B'_def a4 mat_to_cols_list_is_mat by simp\n     moreover have \"mat (mult.row_length C') (length C') C'\"\n       using C'_def a5 mat_to_cols_list_is_mat by simp\n     moreover have \"mat (mult.row_length D') (length D') D'\"\n       using D'_def a6 mat_to_cols_list_is_mat by simp\n     moreover have \"length A' = mult.row_length B'\"\n       using A'_def B'_def a1 a4 by simp\n     moreover have \"length C' = mult.row_length D'\"\n       using C'_def D'_def a2 a6 by simp\n     moreover have \"A' \\<noteq> [] \\<and> B' \\<noteq> [] \\<and> C' \\<noteq> [] \\<and> D' \\<noteq> []\"\n       using A'_def B'_def C'_def D'_def a3 a4 a5 a6 by simp\n     ultimately have \"plus_mult.matrix_match A' B' C' D'\"\n       using plus_mult.matrix_match_def[of 1 \"(*)\" 0 \"(+)\" \"a_inv cpx_rng\"] by simp\n     thus ?thesis\n       using f1 plus_mult.distributivity plus_mult_cpx by fastforce\n   qed\n   also have \"\\<dots> = mat_of_cols_list (dim_row A * dim_row C) (mult.Tensor (*) \n   (mat_to_cols_list (A * B)) (mat_to_cols_list (C * D)))\"\n     using A'_def B'_def C'_def D'_def a1 a2 a3 a5 by simp\n   finally show ?thesis by(simp add: tensor_mat_def)\n qed\n\nlemma tensor_mat_is_assoc:\n  fixes A B C:: \"complex Matrix.mat\"\n  shows \"A \\<Otimes> (B \\<Otimes> C) = (A \\<Otimes> B) \\<Otimes> C\"\nproof-\n  define M where d:\"M = mat_of_cols_list (dim_row B * dim_row C) (mult.Tensor (*) (mat_to_cols_list B) (mat_to_cols_list C))\"\n  then have \"B \\<Otimes> C = M\" \n    using tensor_mat_def by simp\n  moreover have \"A \\<Otimes> (B \\<Otimes> C) = mat_of_cols_list (dim_row A * (dim_row B * dim_row C))\n(mult.Tensor (*) (mat_to_cols_list A) (mat_to_cols_list M))\"\n    using tensor_mat_def d dim_row_tensor_mat by simp\n  moreover have \"mat_to_cols_list M = mult.Tensor (*) (mat_to_cols_list B) (mat_to_cols_list C)\"\n    using d list_to_mat_to_cols_list\n    by (smt calculation(1) dim_col_tensor_mat length_greater_0_conv length_mat_to_cols_list mat_to_cols_list_is_mat \nmult.Tensor.simps(1) mult.Tensor_null mult.well_defined_Tensor nat_0_less_mult_iff plus_mult_cpx plus_mult_def row_length_mat_to_cols_list)\n  ultimately have \"A \\<Otimes> (B \\<Otimes> C) = mat_of_cols_list (dim_row A * (dim_row B * dim_row C))\n(mult.Tensor (*) (mat_to_cols_list A) (mult.Tensor (*) (mat_to_cols_list B) (mat_to_cols_list C)))\" by simp\n  moreover have \"\\<dots> = mat_of_cols_list ((dim_row A * dim_row B) * dim_row C) \n(mult.Tensor (*) (mult.Tensor (*) (mat_to_cols_list A) (mat_to_cols_list B)) (mat_to_cols_list C))\"\n    using Matrix_Tensor.mult.associativity\n    by (smt length_greater_0_conv length_mat_to_cols_list linordered_field_class.sign_simps(4) \nmat_to_cols_list_is_mat mult.Tensor.simps(1) mult.Tensor_null plus_mult_cpx plus_mult_def)\n  ultimately show ?thesis\n    using tensor_mat_def\n    by (smt Tensor.mat_of_cols_list_def dim_col_mat(1) dim_col_tensor_mat dim_row_tensor_mat length_0_conv \nlist_to_mat_to_cols_list mat_to_cols_list_is_mat mult.well_defined_Tensor mult_is_0 neq0_conv \nplus_mult_cpx plus_mult_def row_length_mat_to_cols_list)\nqed\n\n\nend", "meta": {"author": "AnthonyBordg", "repo": "Isabelle_marries_Dirac", "sha": "ab313fb4028c99bd5d97f8e30aaf1644e200d57b", "save_path": "github-repos/isabelle/AnthonyBordg-Isabelle_marries_Dirac", "path": "github-repos/isabelle/AnthonyBordg-Isabelle_marries_Dirac/Isabelle_marries_Dirac-ab313fb4028c99bd5d97f8e30aaf1644e200d57b/Tensor.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.884039278690883, "lm_q2_score": 0.8289388019824946, "lm_q1q2_score": 0.7328144605834892}}
{"text": "(*  Author:     Gertrud Bauer, Tobias Nipkow\n*)\n\nsection \"Summation Over Lists\"\n\ntheory ListSum\nimports ListAux\nbegin\n\nprimrec ListSum :: \"'b list \\<Rightarrow> ('b \\<Rightarrow> 'a::comm_monoid_add) \\<Rightarrow> 'a::comm_monoid_add\"  where\n  \"ListSum [] f = 0\"\n| \"ListSum (l#ls) f = f l + ListSum ls f\"\n\nsyntax \"_ListSum\" :: \"idt \\<Rightarrow> 'b list \\<Rightarrow> ('a::comm_monoid_add) \\<Rightarrow> \n  ('a::comm_monoid_add)\"    (\"\\<Sum>\\<^bsub>_\\<in>_\\<^esub> _\" [0, 0, 10] 10)\ntranslations \"\\<Sum>\\<^bsub>x\\<in>xs\\<^esub> f\" == \"CONST ListSum xs (\\<lambda>x. f)\" \n\n\n\nlemma ListSum_compl1: \n  \"(\\<Sum>\\<^bsub>x \\<in> [x\\<leftarrow>xs. \\<not> P x]\\<^esub> f x) + (\\<Sum>\\<^bsub>x \\<in> [x\\<leftarrow>xs. P x]\\<^esub> f x) = (\\<Sum>\\<^bsub>x \\<in> xs\\<^esub> (f x::nat))\" \n by (induct xs) simp_all\n\nlemma ListSum_compl2: \n  \"(\\<Sum>\\<^bsub>x \\<in>  [x\\<leftarrow>xs. P x]\\<^esub> f x) + (\\<Sum>\\<^bsub>x \\<in>  [x\\<leftarrow>xs. \\<not> P x]\\<^esub> f x) = (\\<Sum>\\<^bsub>x \\<in> xs\\<^esub> (f x::nat))\" \n by (induct xs) simp_all\n\nlemmas ListSum_compl = ListSum_compl1 ListSum_compl2\n\n\nlemma ListSum_conv_sum:\n \"distinct xs \\<Longrightarrow> ListSum xs f =  sum f (set xs)\"\nby(induct xs) simp_all\n\n\nlemma listsum_cong:\n \"\\<lbrakk> xs = ys; \\<And>y. y \\<in> set ys \\<Longrightarrow> f y = g y \\<rbrakk>\n  \\<Longrightarrow> ListSum xs f = ListSum ys g\"\napply simp\napply(erule thin_rl)\nby (induct ys) simp_all\n\n\nlemma strong_listsum_cong[cong]:\n \"\\<lbrakk> xs = ys; \\<And>y. y \\<in> set ys =simp=> f y = g y \\<rbrakk>\n  \\<Longrightarrow> ListSum xs f = ListSum ys g\"\nby(auto simp:simp_implies_def intro!:listsum_cong)\n\n\nlemma ListSum_eq [trans]: \n  \"(\\<And>v. v \\<in> set V \\<Longrightarrow> f v = g v) \\<Longrightarrow> (\\<Sum>\\<^bsub>v \\<in> V\\<^esub> f v) = (\\<Sum>\\<^bsub>v \\<in> V\\<^esub> g v)\" \nby(auto intro!:listsum_cong)\n\n\nlemma ListSum_disj_union: \n  \"distinct A \\<Longrightarrow> distinct B \\<Longrightarrow> distinct C \\<Longrightarrow> \n  set C = set A \\<union> set B  \\<Longrightarrow> \n  set A \\<inter> set B = {} \\<Longrightarrow>\n  (\\<Sum>\\<^bsub>a \\<in> C\\<^esub> (f a)) = (\\<Sum>\\<^bsub>a \\<in> A\\<^esub> f a) + (\\<Sum>\\<^bsub>a \\<in> B\\<^esub> (f a::nat))\"\nby (simp add: ListSum_conv_sum sum.union_disjoint)\n\n\nlemma listsum_const[simp]: \n  \"(\\<Sum>\\<^bsub>x \\<in> xs\\<^esub> k) = length xs * k\"\nby (induct xs) (simp_all add: ring_distribs)\n\nlemma ListSum_add: \n  \"(\\<Sum>\\<^bsub>x \\<in> V\\<^esub> f x) + (\\<Sum>\\<^bsub>x \\<in> V\\<^esub> g x) = (\\<Sum>\\<^bsub>x \\<in> V\\<^esub> (f x + (g x::nat)))\" \n  by (induct V) auto\n\nlemma ListSum_le: \n  \"(\\<And>v. v \\<in> set V \\<Longrightarrow> f v \\<le> g v) \\<Longrightarrow> (\\<Sum>\\<^bsub>v \\<in> V\\<^esub> f v) \\<le> (\\<Sum>\\<^bsub>v \\<in> V\\<^esub> (g v::nat))\"\nproof (induct V)\n  case Nil then show ?case by simp\nnext\n  case (Cons v V) then have \"(\\<Sum>\\<^bsub>v \\<in> V\\<^esub> f v) \\<le> (\\<Sum>\\<^bsub>v \\<in> V\\<^esub> g v)\" by simp\n  moreover from Cons have \"f v \\<le> g v\" by simp\n  ultimately show ?case by simp\nqed\n\nlemma ListSum1_bound:\n \"a \\<in> set F \\<Longrightarrow> (d a::nat)\\<le> (\\<Sum>\\<^bsub>f \\<in> F\\<^esub> d f)\"\nby (induct F) 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/Flyspeck-Tame/ListSum.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513786759491, "lm_q2_score": 0.817574478416099, "lm_q1q2_score": 0.7327522534506987}}
{"text": "(*\n    Authors:    Ralph Bottesch\n                Maximilian Haslbeck\n                Ren\u00e9 Thiemann\n    License:    BSD\n*)\nsubsection \\<open>Gram-Schmidt Implementation for Integer Vectors\\<close>\n\ntext \\<open>This theory implements the Gram-Schmidt algorithm on integer vectors\n  using purely integer arithmetic. The formalization is based on \\cite{GS_EKM}.\\<close>\n\ntheory Gram_Schmidt_Int\n  imports \n    Gram_Schmidt_2\n    More_IArray\nbegin\n\ncontext fixes\n  fs :: \"int vec iarray\" and m :: nat\nbegin \nfun sigma_array where\n  \"sigma_array dmus dmusi dmusj dll l = (if l = 0 then dmusi !! l * dmusj !! l\n      else let l1 = l - 1; dll1 = dmus !! l1 !! l1 in\n      (dll * sigma_array dmus dmusi dmusj dll1 l1 + dmusi !! l * dmusj !! l) div \n          dll1)\"\n\ndeclare sigma_array.simps[simp del]\n\npartial_function(tailrec) dmu_array_row_main where\n  [code]: \"dmu_array_row_main fi i dmus j = (if j = i then dmus\n     else let sj = Suc j; \n       dmus_i = dmus !! i;\n       djj = dmus !! j !! j;\n       dmu_ij = djj * (fi \\<bullet> fs !! sj) - sigma_array dmus dmus_i (dmus !! sj) djj j;\n       dmus' = iarray_update dmus i (iarray_append dmus_i dmu_ij)\n      in dmu_array_row_main fi i dmus' sj)\" \n\ndefinition dmu_array_row where\n  \"dmu_array_row dmus i = (let fi = fs !! i in \n      dmu_array_row_main fi i (iarray_append dmus (IArray [fi \\<bullet> fs !! 0])) 0)\" \n\npartial_function (tailrec) dmu_array where \n  [code]: \"dmu_array dmus i = (if i = m then dmus else \n    let dmus' = dmu_array_row dmus i \n      in dmu_array dmus' (Suc i))\"\nend\n\ndefinition d\\<mu>_impl :: \"int vec list \\<Rightarrow> int iarray iarray\" where\n  \"d\\<mu>_impl fs = dmu_array (IArray fs) (length fs) (IArray []) 0\" \n\n\ndefinition (in gram_schmidt) \\<beta> where \"\\<beta> fs l = Gramian_determinant fs (Suc l) / Gramian_determinant fs l\"\n\ncontext gram_schmidt_fs_lin_indpt\nbegin\n\nlemma Gramian_beta:\n  assumes \"i < m\"\n  shows \"\\<beta> fs i = \\<parallel>fs ! i\\<parallel>\\<^sup>2 - (\\<Sum>j = 0..<i. (\\<mu> i j)\\<^sup>2 * \\<beta> fs j)\"\nproof -\n  let ?S = \"M.sumlist (map (\\<lambda>j. - \\<mu> i j \\<cdot>\\<^sub>v gso j) [0..<i])\"\n  have S: \"?S \\<in> carrier_vec n\"\n    using assms by (auto intro!: M.sumlist_carrier gso_carrier)\n  have fi: \"fs ! i \\<in> carrier_vec n\" using assms by auto\n  have \"\\<beta> fs i = gso i \\<bullet> gso i\"\n    unfolding \\<beta>_def\n    using assms dist by (auto simp add: Gramian_determinant_div sq_norm_vec_as_cscalar_prod)\n  also have \"\\<dots> = (fs ! i + ?S) \\<bullet> (fs ! i + ?S)\"\n    by (subst gso.simps, subst (2) gso.simps) auto\n  also have \"\\<dots> = fs ! i \\<bullet> fs ! i + ?S \\<bullet> fs ! i + fs ! i \\<bullet> ?S + ?S \\<bullet> ?S\"\n    using assms S by (auto simp add: add_scalar_prod_distrib[of _ n] scalar_prod_add_distrib[of _ n])\n  also have \"fs ! i \\<bullet> ?S = ?S \\<bullet> fs ! i\" \n    by (rule comm_scalar_prod[OF fi S])\n  also have \"?S \\<bullet> fs ! i = ?S \\<bullet> gso i - ?S \\<bullet> ?S\"\n  proof -\n    have \"fs ! i = gso i - M.sumlist (map (\\<lambda>j. - \\<mu> i j \\<cdot>\\<^sub>v gso j) [0..<i])\"\n       using assms S by (subst gso.simps) auto\n    then show ?thesis\n      using assms S by (auto simp add: minus_scalar_prod_distrib[of _ n] scalar_prod_minus_distrib[of _ n])\n  qed\n  also have \"?S \\<bullet> gso i = 0\"\n    using assms orthogonal\n    by(subst scalar_prod_left_sum_distrib)\n      (auto intro!: sum_list_neutral M.sumlist_carrier gso_carrier)\n  also have \"?S \\<bullet> ?S = (\\<Sum>j = 0..<i. (\\<mu> i j)\\<^sup>2 * (gso j \\<bullet> gso j))\"\n    using assms dist by (subst scalar_prod_lincomb_gso)\n       (auto simp add: power2_eq_square interv_sum_list_conv_sum_set_nat)\n  also have \"\\<dots> =  (\\<Sum>j = 0..<i. (\\<mu> i j)\\<^sup>2 * \\<beta> fs j)\"\n    using assms dist\n    by (auto simp add: \\<beta>_def Gramian_determinant_div sq_norm_vec_as_cscalar_prod\n        intro!: sum.cong)\n  finally show ?thesis\n    by (auto simp add: sq_norm_vec_as_cscalar_prod)\nqed\n\nlemma gso_norm_beta:\n  assumes \"j < m\"\n  shows \"\\<beta> fs j = sq_norm (gso j)\"\n  unfolding \\<beta>_def\n  using assms dist by (auto simp add: Gramian_determinant_div sq_norm_vec_as_cscalar_prod)\n\nlemma mu_Gramian_beta_def:\n  assumes \"j < i\" \"i < m\"\n  shows \"\\<mu> i j = (fs ! i \\<bullet> fs ! j - (\\<Sum>k = 0..<j. \\<mu> j k * \\<mu> i k * \\<beta> fs k)) / \\<beta> fs j\"\nproof -\n  let ?list = \"map (\\<lambda>ja. \\<mu> i ja \\<cdot>\\<^sub>v gso ja) [0..<i]\" \n  let ?neg_sum = \"M.sumlist (map (\\<lambda>ja. - \\<mu> j ja \\<cdot>\\<^sub>v gso ja) [0..<j])\"\n  have list: \"set ?list \\<subseteq> carrier_vec n\" using gso_carrier assms by auto\n  define fi where \"fi = fs ! i\"\n  have list_id: \"[0..<i] = [0..<j] @ [j..<i]\" \n    using assms by (metis append.simps(1) neq0_conv upt.simps(1) upt_append)\n  have \"\\<mu> i j = (fs ! i) \\<bullet> (gso j) / sq_norm (gso j) \"\n    unfolding \\<mu>.simps using assms by auto\n  also have \" ... = fs ! i \\<bullet> (fs ! j + ?neg_sum) / sq_norm (gso j)\" \n    by (subst gso.simps, simp)\n  also have \" ... = (fi \\<bullet> fs ! j + fs ! i \\<bullet> ?neg_sum) / sq_norm (gso j)\"\n    using assms unfolding fi_def\n    by (subst scalar_prod_add_distrib [of _ n]) (auto intro!: M.sumlist_carrier gso_carrier)\n  also have \"fs ! i = gso i + M.sumlist ?list \"\n    by (rule fs_by_gso_def[OF assms(2)])\n  also have \"... \\<bullet> ?neg_sum = gso i \\<bullet> ?neg_sum + M.sumlist ?list \\<bullet> ?neg_sum\"\n    using assms by (subst add_scalar_prod_distrib [of _ n]) (auto intro!: M.sumlist_carrier gso_carrier)\n  also have \" M.sumlist ?list = M.sumlist (map (\\<lambda>ja. \\<mu> i ja \\<cdot>\\<^sub>v gso ja) [0..<j]) \n     + M.sumlist (map (\\<lambda>ja. \\<mu> i ja \\<cdot>\\<^sub>v gso ja) [j..<i]) \" (is \"_ = ?sumj + ?sumi\")\n    unfolding list_id\n    by (subst M.sumlist_append[symmetric], insert gso_carrier assms, auto)\n  also have \"gso i \\<bullet> ?neg_sum = 0\"\n    by (rule orthogonal_sumlist, insert gso_carrier dist assms orthogonal, auto)\n  also have \" (?sumj + ?sumi) \\<bullet> ?neg_sum = ?sumj \\<bullet> ?neg_sum + ?sumi \\<bullet> ?neg_sum\"\n    using assms\n    by (subst add_scalar_prod_distrib [of _ n], auto intro!: M.sumlist_carrier gso_carrier)\n  also have \" ?sumj \\<bullet> ?neg_sum = (\\<Sum>l = 0..<j. (\\<mu> i l) * (-\\<mu> j l) * (gso l \\<bullet> gso l)) \"\n    using assms\n    by (subst scalar_prod_lincomb_gso) (auto simp add: interv_sum_list_conv_sum_set_nat)\n  also have \"\\<dots> = - (\\<Sum>l = 0..<j. (\\<mu> i l) * (\\<mu> j l) * (gso l \\<bullet> gso l)) \" (is \"_ = - ?sum\")\n    by (auto simp add: sum_negf)\n  also have \"?sum = (\\<Sum>l = 0..<j. (\\<mu> j l) * (\\<mu> i l) * \\<beta> fs l)\" \n    using assms\n    by (intro sum.cong, auto simp: gso_norm_beta sq_norm_vec_as_cscalar_prod)\n  also have \"?sumi \\<bullet> ?neg_sum = 0\"\n    apply (rule orthogonal_sumlist, insert gso_carrier assms orthogonal, auto intro!: M.sumlist_carrier gso_carrier)\n    apply (subst comm_scalar_prod[of _ n], auto intro!: M.sumlist_carrier)\n    by (rule orthogonal_sumlist, use dist in auto)\n  also have \"sq_norm (gso j) = \\<beta> fs j\"\n    using assms\n    by (subst gso_norm_beta, auto)\n  finally show ?thesis unfolding fi_def by simp\nqed\n\nend\n\nlemma (in gram_schmidt) Gramian_matrix_alt_alt_alt_def:\n  assumes \"k \\<le> length fs\" \"set fs \\<subseteq> carrier_vec n\"\n  shows \"Gramian_matrix fs k = mat k k (\\<lambda>(i,j). fs ! i \\<bullet> fs ! j)\"\nproof -\n  have *: \"vec n (($) (fs ! i)) = fs ! i\" if \"i < length fs\" for i\n    using that assms\n    by (metis carrier_vecD dim_vec eq_vecI index_vec nth_mem subsetCE)\n  then show ?thesis\n    unfolding Gramian_matrix_def using  assms\n    by (intro eq_matI) (auto simp add: Let_def)\nqed\n\nlemma (in gram_schmidt_fs_Rn) Gramian_determinant_1 [simp]:\n  assumes \"0 < length fs\"\n  shows \"Gramian_determinant fs (Suc 0) = \\<parallel>fs ! 0\\<parallel>\\<^sup>2\"\nproof -\n  have \"Gramian_determinant fs (Suc 0) = fs ! 0 \\<bullet> fs ! 0\"\n    using assms unfolding Gramian_determinant_def \n    by (subst det_def') (auto simp add: Gramian_matrix_def Let_def scalar_prod_def)\n  then show ?thesis\n    by (subst sq_norm_vec_as_cscalar_prod) simp\nqed\n\n\ncontext gram_schmidt_fs_lin_indpt\nbegin\n\n\ndefinition \\<mu>' where \"\\<mu>' i j \\<equiv> d (Suc j) * \\<mu> i j\" \n\n\nfun \\<sigma> where \n  \"\\<sigma> 0 i j = 0\" \n| \"\\<sigma> (Suc l) i j = (d (Suc l) * \\<sigma> l i j + \\<mu>' i l * \\<mu>' j l) / d l\" \n\nlemma d_Suc: \"d (Suc i) = \\<mu>' i i\" unfolding \\<mu>'_def by (simp add: \\<mu>.simps)\nlemma d_0: \"d 0 = 1\" by (rule Gramian_determinant_0)\n\nlemma \\<sigma>: assumes lj: \"l \\<le> m\" \n  shows \"\\<sigma> l i j = d l * (\\<Sum>k < l. \\<mu> i k * \\<mu> j k * \\<beta> fs k)\"\n  using lj\nproof (induct l)\n  case (Suc l)\n  from Suc(2-) have lj: \"l \\<le> m\" by auto\n  note IH = Suc(1)[OF lj]\n  let ?f = \"\\<lambda> k. \\<mu> i k * \\<mu> j k * \\<beta> fs k\" \n  have dl0: \"d l > 0\" using lj Gramian_determinant dist unfolding lin_indpt_list_def by auto\n  have \"\\<sigma> (Suc l) i j = (d (Suc l) * \\<sigma> l i j + \\<mu>' i l * \\<mu>' j l) / d l\" by simp\n  also have \"\\<dots> = (d (Suc l) * \\<sigma> l i j) / d l + (\\<mu>' i l * \\<mu>' j l) / d l\" using dl0 \n    by (simp add: field_simps)\n  also have \"(\\<mu>' i l * \\<mu>' j l) / d l = d (Suc l) * ?f l\" (is \"_ = ?one\")\n    unfolding \\<beta>_def \\<mu>'_def by auto\n  also have \"(d (Suc l) * \\<sigma> l i j) / d l = d (Suc l) * (\\<Sum>k < l. ?f k)\" (is \"_ = ?sum\")\n    using dl0 unfolding IH by simp\n  also have \"?sum + ?one = d (Suc l) * (?f l + (\\<Sum>k < l. ?f k))\" by (simp add: field_simps)\n  also have \"?f l + (\\<Sum>k < l. ?f k) = (\\<Sum>k < Suc l. ?f k)\" by simp\n  finally show ?case .\nqed auto\n\nlemma \\<mu>': assumes j: \"j \\<le> i\" and i: \"i < m\" \n  shows \"\\<mu>' i j = d j * (fs ! i \\<bullet> fs ! j) - \\<sigma> j i j\" \nproof (cases \"j < i\")\n  case j: True\n  have dsj: \"d (Suc j) > 0\"\n    using j i Gramian_determinant dist unfolding lin_indpt_list_def\n    by (meson less_trans_Suc nat_less_le)\n  let ?sum = \" (\\<Sum>k = 0..<j. \\<mu> j k * \\<mu> i k * \\<beta> fs k)\" \n  have \"\\<mu>' i j = (fs ! i \\<bullet> fs ! j - ?sum) * (d (Suc j) / \\<beta> fs j)\"     \n    unfolding mu_Gramian_beta_def[OF j i] \\<mu>'_def by simp\n  also have \"d (Suc j) / \\<beta> fs j = d j\" unfolding \\<beta>_def using dsj by auto\n  also have \"(fs ! i \\<bullet> fs ! j - ?sum) * d j = (fs ! i \\<bullet> fs ! j) * d j - d j * ?sum\" \n    by (simp add: ring_distribs)\n  also have \"d j * ?sum = \\<sigma> j i j\" \n    by (subst \\<sigma>, (insert j i, force), intro arg_cong[of _ _ \"\\<lambda> x. _ * x\"] sum.cong, auto)\n  finally show ?thesis by simp\nnext\n  case False\n  with j have j: \"j = i\" by auto\n  have dsi: \"d (Suc i) > 0\" \"d i > 0\"\n    using i Suc_leI dist  unfolding lin_indpt_list_def\n    by (simp_all add: Suc_leI Gramian_determinant(2))\n  let ?sum = \" (\\<Sum>k = 0..<i. \\<mu> i k * \\<mu> i k * \\<beta> fs k)\" \n  have bzero: \"\\<beta> fs i \\<noteq> 0\" unfolding \\<beta>_def using dsi by auto\n  have \"\\<mu>' i i = d (Suc i)\" by (simp add: \\<mu>.simps \\<mu>'_def)\n  also have \"\\<dots> = \\<beta> fs i * (d (Suc i)  / \\<beta> fs i)\" using bzero by simp \n  also have \"d (Suc i) / \\<beta> fs i = d i\" unfolding \\<beta>_def using dsi by auto\n  also have \"\\<beta> fs i = (fs ! i \\<bullet> fs ! i - ?sum)\" \n    unfolding Gramian_beta[OF i]\n    by (rule arg_cong2[of _ _ _ _ \"(-)\", OF _ sum.cong], \n        auto simp: power2_eq_square sq_norm_vec_as_cscalar_prod)\n  also have \"(fs ! i \\<bullet> fs ! i - ?sum) * d i = (fs ! i \\<bullet> fs ! i) * d i - d i * ?sum\" \n    by (simp add: ring_distribs)\n  also have \"d i * ?sum = \\<sigma> i i i\" \n    by (subst \\<sigma>, (insert i i, force), intro arg_cong[of _ _ \"\\<lambda> x. _ * x\"] sum.cong, auto)\n  finally show ?thesis using j by simp\nqed\n\nlemma \\<sigma>_via_\\<mu>': \"\\<sigma> (Suc l) i j = \n  (if l = 0 then \\<mu>' i 0 * \\<mu>' j 0 else (\\<mu>' l l * \\<sigma> l i j + \\<mu>' i l * \\<mu>' j l) / \\<mu>' (l - 1) (l - 1))\"\n  by (cases l, auto simp: d_Suc)\n\nlemma \\<mu>'_via_\\<sigma>: assumes j: \"j \\<le> i\" and i: \"i < m\" \n  shows \"\\<mu>' i j = \n    (if j = 0 then fs ! i \\<bullet> fs ! j else \\<mu>' (j - 1) (j - 1) * (fs ! i \\<bullet> fs ! j) - \\<sigma> j i j)\"\n  unfolding \\<mu>'[OF assms] by (cases j, auto simp: d_Suc)\n\nlemma fs_i_sumlist_\\<kappa>:\n  assumes \"i < m\" \"l \\<le> i\" \"j < l\"\n  shows \"(fs ! i + sumlist (map (\\<lambda>j. \\<kappa> i l j \\<cdot>\\<^sub>v fs ! j) [0..<l])) \\<bullet> fs ! j = 0\"\nproof -\n  have \"fs ! i + sumlist (map (\\<lambda>j. \\<kappa> i l j \\<cdot>\\<^sub>v fs ! j) [0..<l])\n        = fs ! i - M.sumlist (map (\\<lambda>j. \\<mu> i j \\<cdot>\\<^sub>v gso j) [0..<l])\"\n    using assms gso_carrier assms \n    by (subst \\<kappa>_def[symmetric]) (auto simp add: dim_sumlist sumlist_nth sum_negf)\n  also have \"\\<dots> = M.sumlist (map (\\<lambda>j. \\<mu> i j \\<cdot>\\<^sub>v gso j) [l..<Suc i])\"\n  proof -\n    have \"fs ! i = M.sumlist (map (\\<lambda>j. \\<mu> i j \\<cdot>\\<^sub>v gso j) [0..<Suc i])\"\n      using assms by (intro fi_is_sum_of_mu_gso) auto\n    also have \"\\<dots> = M.sumlist (map (\\<lambda>j. \\<mu> i j \\<cdot>\\<^sub>v gso j) [0..<l]) +\n                  M.sumlist (map (\\<lambda>j. \\<mu> i j \\<cdot>\\<^sub>v gso j) [l..<Suc i])\"\n    proof -\n      have *: \"[0..<Suc i] = [0..<l] @ [l..<Suc i]\"\n        using assms by (metis diff_zero le_imp_less_Suc length_upt list_trisect upt_conv_Cons)\n      show ?thesis\n        by (subst *, subst map_append, subst sumlist_append) (use gso_carrier assms in auto)\n    qed\n    finally show ?thesis\n      using assms gso_carrier assms by (auto simp add: algebra_simps dim_sumlist)\n  qed\n  finally have \"fs ! i + M.sumlist (map (\\<lambda>j. \\<kappa> i l j \\<cdot>\\<^sub>v fs ! j) [0..<l]) =\n                M.sumlist (map (\\<lambda>j. \\<mu> i j \\<cdot>\\<^sub>v gso j) [l..<Suc i])\"\n    by simp\n  moreover have \"\\<dots> \\<bullet> (fs ! j) = 0\"\n    using assms gso_carrier assms unfolding lin_indpt_list_def\n    by (subst scalar_prod_left_sum_distrib)\n       (auto simp add: algebra_simps dim_sumlist gso_scalar_zero intro!: sum_list_zero)\n  ultimately show ?thesis using assms by auto\nqed\n\n\nend (* gram_schmidt_fs_lin_indpt *)\n\ncontext gram_schmidt_fs_int\nbegin\n\n\nlemma \\<beta>_pos : \"i < m \\<Longrightarrow> \\<beta> fs i > 0\" \n  using Gramian_determinant(2) unfolding lin_indpt_list_def \\<beta>_def by auto\n\nlemma \\<beta>_zero : \"i < m \\<Longrightarrow> \\<beta> fs i \\<noteq> 0\" \n  using \\<beta>_pos[of i] by simp\n\nlemma \\<sigma>_integer:  \n  assumes l: \"l \\<le> j\" and j: \"j \\<le> i\" and i: \"i < m\"\n  shows \"\\<sigma> l i j \\<in> \\<int>\" \nproof -\n  from assms have ll: \"l \\<le> m\" by auto\n  have fs_carr: \"j < m \\<Longrightarrow> fs ! j \\<in> carrier_vec n\" for j using assms fs_carrier unfolding set_conv_nth by force\n  with assms have fs_carr_j: \"fs ! j \\<in> carrier_vec n\" by auto\n  have dim_gso: \"i < m \\<Longrightarrow> dim_vec (gso i) = n\" for i using gso_carrier by auto\n  have dim_fs: \"k < m \\<Longrightarrow> dim_vec (fs ! k) = n\" for k using smult_carrier_vec fs_carr by auto\n  have i_l_m: \"i < l \\<Longrightarrow> i < m\" for i using assms by auto\n  have smult: \"\\<And> i j . j < n \\<Longrightarrow> i < l \\<Longrightarrow> (c \\<cdot>\\<^sub>v fs ! i) $ j = c * (fs ! i $ j)\" for c\n    using i_l_m dim_fs by auto\n  have \"\\<sigma> l i j = d l * (\\<Sum>k < l. \\<mu> i k * \\<mu> j k * \\<beta> fs k)\"\n    unfolding \\<sigma>[OF ll] by simp\n  also have \" ... = d l * (\\<Sum>k < l. \\<mu> i k * ((fs ! j) \\<bullet> (gso k) /  sq_norm (gso k)) * \\<beta> fs k)\" (is \"_ = _ * ?sum\")\n    unfolding \\<mu>.simps using assms by auto\n  also have \"?sum =  (\\<Sum>k < l. \\<mu> i k * ((fs ! j) \\<bullet> (gso k) /  \\<beta> fs k) * \\<beta> fs k)\"\n    using assms by (auto simp add: gso_norm_beta[symmetric] intro!: sum.cong)\n\n  also have \"... = (\\<Sum>k < l. \\<mu> i k * ((fs ! j) \\<bullet> (gso k) ))\"\n    using \\<beta>_zero assms by (auto intro!: sum.cong)\n\n  also have \" ... = (fs ! j) \\<bullet> M.sumlist (map (\\<lambda>k. (\\<mu> i k) \\<cdot>\\<^sub>v (gso k)) [0..<l] )\"\n    using assms fs_carr[of j] gso_carrier\n    by (subst scalar_prod_right_sum_distrib) (auto intro!: gso_carrier fs_carr sum.cong simp: sum_list_sum_nth)\n\n  also have \"d l * \\<dots> = (fs ! j) \\<bullet> (d l \\<cdot>\\<^sub>v M.sumlist (map (\\<lambda>k. (\\<mu> i k) \\<cdot>\\<^sub>v (gso k)) [0..<l]))\" (is \"_ = _ \\<bullet> (_ \\<cdot>\\<^sub>v ?sum2)\")\n    apply (rule scalar_prod_smult_distrib[symmetric])\n     apply (rule fs_carr)\n    using assms gso_carrier\n    by (auto intro!: sumlist_carrier)\n\n\t  also have \"?sum2 = - sumlist (map (\\<lambda>k. (- \\<mu> i k) \\<cdot>\\<^sub>v (gso k)) [0..<l])\"\n\t    apply(rule eq_vecI)\n\t    using fs_carr gso_carrier assms i_l_m\n\t    by(auto simp: sum_negf[symmetric] dim_sumlist sumlist_nth dim_gso intro!: sum.cong)\n\n\t  also have \"\\<dots> = - sumlist (map (\\<lambda>k. \\<kappa> i l k \\<cdot>\\<^sub>v fs ! k) [0..<l])\"\n\t    using assms gso_carrier assms \n\t    apply (subst \\<kappa>_def)\n\t    by (auto)\n\n\t  also have \"(d l \\<cdot>\\<^sub>v - sumlist (map (\\<lambda>k. \\<kappa> i l k \\<cdot>\\<^sub>v fs ! k) [0..<l])) =\n\t\t     (- sumlist (map (\\<lambda>k. (d l * \\<kappa> i l k) \\<cdot>\\<^sub>v fs ! k) [0..<l]))\"\n\t    apply(rule eq_vecI)\n\t    using fs_carr smult_carrier_vec dim_fs\n\t    using dim_fs i_l_m \n\t    by (auto simp: smult dim_sumlist sumlist_nth sum_distrib_left intro!: sum.cong)\n\n\t  finally have id: \" \\<sigma> l i j = fs ! j \\<bullet> - M.sumlist (map (\\<lambda>k. d l * \\<kappa> i l k \\<cdot>\\<^sub>v fs ! k) [0..<l]) \" .\n\t  (* now we are able to apply d_\\<kappa>_int *)\n\t  show \"\\<sigma> l i j \\<in> \\<int>\" unfolding id\n\t    using i_l_m fs_carr assms fs_int d_\\<kappa>_Ints\n\t    by (auto simp: dim_sumlist sumlist_nth smult \n\t        intro!: sumlist_carrier Ints_minus Ints_sum Ints_mult[of _ \"fs ! _ $ _\"]  Ints_scalar_prod[OF fs_carr])\n\tqed\n\nend (* gram_schmidt_fs_int *)\n\n\n\ncontext fs_int_indpt\nbegin\n\nfun \\<sigma>s and \\<mu>' where \n  \"\\<sigma>s 0 i j = \\<mu>' i 0 * \\<mu>' j 0\" \n| \"\\<sigma>s (Suc l) i j = (\\<mu>' (Suc l) (Suc l) * \\<sigma>s l i j + \\<mu>' i (Suc l) * \\<mu>' j (Suc l)) div \\<mu>' l l\" \n| \"\\<mu>' i j = (if j = 0 then fs ! i \\<bullet> fs ! j else \\<mu>' (j - 1) (j - 1) * (fs ! i \\<bullet> fs ! j) - \\<sigma>s (j - 1) i j)\"\n\ndeclare \\<mu>'.simps[simp del]\n\nlemma \\<sigma>s_\\<mu>': \"l < j \\<Longrightarrow> j \\<le> i \\<Longrightarrow> i < m \\<Longrightarrow> of_int (\\<sigma>s l i j) = gs.\\<sigma> (Suc l) i j\" \n  \"i < m \\<Longrightarrow> j \\<le> i \\<Longrightarrow> of_int (\\<mu>'  i j) = gs.\\<mu>' i j\" \nproof (induct l i j and i j rule: \\<sigma>s_\\<mu>'.induct)\n  case (1 i j)                          \n  thus ?case by (simp add: gs.\\<sigma>.simps)\nnext\n  case (2 l i j)\n  have \"gs.\\<sigma>(Suc (Suc l)) i j \\<in> \\<int>\" \n    by (rule gs.\\<sigma>_integer, insert 2 gs.fs_carrier, auto)\n  then have \"rat_of_int (\\<mu>' (Suc l) (Suc l) * \\<sigma>s l i j + \\<mu>' i (Suc l) * \\<mu>' j (Suc l)) / rat_of_int (\\<mu>' l l) \\<in> \\<int>\"\n    using 2 gs.d_Suc by (auto)\n  then have \"rat_of_int (\\<sigma>s (Suc l) i j) = \n             of_int (\\<mu>' (Suc l) (Suc l) * \\<sigma>s l i j + \\<mu>' i (Suc l) * \\<mu>' j (Suc l)) / of_int (\\<mu>' l l)\"\n    by (subst \\<sigma>s.simps, subst exact_division) auto\n  also have \"\\<dots> = gs.\\<sigma> (Suc (Suc l)) i j\"\n    using 2 gs.d_Suc by (auto)\n  finally show ?case\n    by simp\nnext\n  case (3 i j)\n  have \"dim_vec (fs ! j) = dim_vec (fs ! i)\"\n    using 3 f_carrier[of i] f_carrier[of j] carrier_vec_def by auto\n  then have \"of_int_hom.vec_hom (fs ! i) $ k = rat_of_int (fs ! i $ k)\" if \"k < dim_vec (fs ! j)\" for k\n    using that by simp\n  then have *: \"of_int_hom.vec_hom (fs ! i) \\<bullet> of_int_hom.vec_hom (fs ! j) = rat_of_int (fs ! i \\<bullet> fs ! j)\"\n    using 3 by (auto simp add: scalar_prod_def)\n  show ?case\n  proof (cases \"j = 0\")\n    case True\n    have \"dim_vec (fs ! 0) = dim_vec (fs ! i)\"\n      using 3 f_carrier[of i] f_carrier[of 0] carrier_vec_def by fastforce\n    then have 1: \"of_int_hom.vec_hom (fs ! i) $ k = rat_of_int (fs ! i $ k)\" if \"k < dim_vec (fs ! 0)\" for k\n      using that by simp\n    have \"(\\<mu>' i j) = fs ! i \\<bullet> fs ! j\"\n      using True by (simp add: \\<mu>'.simps)\n    also note *[symmetric]\n    also have  \"of_int_hom.vec_hom (fs ! j) = map of_int_hom.vec_hom fs ! j\"\n      using 3 by auto\n    finally show ?thesis\n      using 3 True by (subst gs.\\<mu>'_via_\\<sigma>) (auto)\n  next\n    case False\n    then have \"gs.\\<mu>' i j = gs.\\<mu>' (j - Suc 0) (j - Suc 0) * (rat_of_int (fs ! i \\<bullet> fs ! j)) - gs.\\<sigma> j i j\"\n      using * False 3 by (subst gs.\\<mu>'_via_\\<sigma>) (auto)\n    then show ?thesis\n      using False 3 by (subst \\<mu>'.simps) (auto)\n\tqed\nqed\n\n\nlemma \\<mu>': assumes \"i < m\" \"j \\<le> i\"\n  shows \"\\<mu>' i j = d\\<mu> i j\"\n    \"j = i \\<Longrightarrow> \\<mu>' i j = d fs (Suc i)\"  \nproof -\n  let ?r = rat_of_int\n  from assms have \"j < m\" by auto\n  note d\\<mu> = d\\<mu>[OF this assms(1)]\n  have \"?r (\\<mu>' i j) = gs.\\<mu>' i j\" \n    using \\<sigma>s_\\<mu>' assms by auto\n  also have \"\\<dots> = ?r (d\\<mu> i j)\"\n    unfolding gs.\\<mu>'_def d\\<mu>\n    by (subst of_int_Gramian_determinant, insert assms fs_carrier, auto simp: d_def subset_eq)\n  finally show 1: \"\\<mu>' i j = d\\<mu> i j\"\n    by simp\n  assume j: \"j = i\"\n  have \"?r (\\<mu>' i j) = ?r (d\\<mu> i j)\"\n    unfolding 1 ..\n  also have \"\\<dots> = ?r (d fs (Suc i))\"\n    unfolding d\\<mu> unfolding j by (simp add: gs.\\<mu>.simps)\n  finally show \"\\<mu>' i j = d fs (Suc i)\"\n    by simp\nqed\n\nlemma sigma_array: assumes mm: \"mm \\<le> m\" and j: \"j < mm\" \n  shows \"l \\<le> j \\<Longrightarrow> sigma_array (IArray.of_fun (\\<lambda>i. IArray.of_fun (\\<mu>' i) (if i = mm then Suc j else Suc i)) (Suc mm))\n\t     (IArray.of_fun (\\<mu>' mm) (Suc j)) (IArray.of_fun (\\<mu>' (Suc j)) (if Suc j = mm then Suc j else Suc (Suc j))) (\\<mu>' l l) l =\n\t    \\<sigma>s l mm (Suc j)\"\nproof (induct l)\n  case 0\n  show ?case unfolding \\<sigma>s.simps sigma_array.simps[of _ _ _ _ 0]\n    using mm j by (auto simp: nth_append)\nnext\n  case (Suc l)\n  hence l: \"l < j\" \"l \\<le> j\" by auto\n  have id: \"(Suc l = 0) = False\" \"Suc l - 1 = l\" by auto\n  have ineq: \"Suc l < Suc mm\" \"l < Suc mm\" \n    \"Suc l < (if Suc l = mm then Suc j else Suc (Suc l))\" \n    \"Suc l < (if Suc j = mm then Suc j else Suc (Suc j))\" \n    \"l < (if l = mm then Suc j else Suc l)\" \n    \"Suc l < Suc j\" \n    using mm l j by auto\n  note IH = Suc(1)[OF l(2)]\n  show ?case unfolding sigma_array.simps[of _ _ _ _ \"Suc l\"] id if_False Let_def IH\n\t    of_fun_nth[OF ineq(1)] of_fun_nth[OF ineq(2)] of_fun_nth[OF ineq(3)] \n\t    of_fun_nth[OF ineq(4)] of_fun_nth[OF ineq(5)] of_fun_nth[OF ineq(6)]\n\t  unfolding \\<sigma>s.simps by simp\nqed\n\nlemma dmu_array_row_main: assumes mm: \"mm \\<le> m\" shows\n  \"j \\<le> mm \\<Longrightarrow> dmu_array_row_main (IArray fs) (IArray fs !!  mm) mm\n\t    (IArray.of_fun (\\<lambda>i. IArray.of_fun (\\<mu>' i) (if i = mm then Suc j else Suc i)) (Suc mm))    \n\t     j = IArray.of_fun (\\<lambda>i. IArray.of_fun (\\<mu>' i) (Suc i)) (Suc mm)\" \nproof (induct \"mm - j\" arbitrary: j)\n  case 0\n  thus ?case unfolding dmu_array_row_main.simps[of _ _ _ _ j] by simp\nnext\n  case (Suc x j)\n  hence prems: \"x = mm - Suc j\" \"Suc j \\<le> mm\" and j: \"j < mm\" by auto\n  note IH = Suc(1)[OF prems]\n  have id: \"(j = mm) = False\" \"(mm = mm) = True\" using Suc(2-) by auto\n  have id2: \"IArray.of_fun (\\<mu>' mm) (Suc j) = IArray (map (\\<mu>' mm) [0..<Suc j])\" \n    by simp\n  have id3: \"IArray fs !! mm = fs ! mm\" \"IArray fs !! Suc j = fs ! Suc j\" by auto\n  have le: \"j < Suc j\" \"Suc j < Suc mm\" \"mm < Suc mm\" \"j < Suc mm\" \n    \"j < (if j = mm then Suc j else Suc j)\" using j by auto\n  show ?case unfolding dmu_array_row_main.simps[of _ _ _ _ j] \n      IH[symmetric] Let_def id if_True if_False id3\n      of_fun_nth[OF le(1)] of_fun_nth[OF le(2)]\n      of_fun_nth[OF le(3)] of_fun_nth[OF le(4)]\n      of_fun_nth[OF le(5)]  \n      sigma_array[OF mm j le_refl, folded id2]\n      iarray_length_of_fun iarray_update_of_fun iarray_append_of_fun\n  proof (rule arg_cong[of _ _ \"\\<lambda> x. dmu_array_row_main _ _ _ x _\"], rule iarray_cong', goal_cases)\n    case (1 i)\n    show ?case unfolding of_fun_nth[OF 1] using j 1\n      by (cases \"i = mm\", auto simp: \\<mu>'.simps[of _ \"Suc j\"])\n  qed\nqed\n\nlemma dmu_array_row: assumes mm: \"mm \\<le> m\" shows\n  \"dmu_array_row (IArray fs) (IArray.of_fun (\\<lambda>i. IArray.of_fun (\\<mu>' i) (Suc i)) mm) mm =\n\t    IArray.of_fun (\\<lambda>i. IArray.of_fun (\\<mu>' i) (Suc i)) (Suc mm)\" \nproof -\n  have 0: \"0 \\<le> mm\" by auto\n  show ?thesis unfolding dmu_array_row_def Let_def dmu_array_row_main[OF assms 0, symmetric]\n    unfolding iarray_append.simps IArray.of_fun_def id map_append list.simps\n    by (rule arg_cong[of _ _ \"\\<lambda> x. dmu_array_row_main _ _ _ (IArray x) _\"], rule nth_equalityI, \n\t      auto simp: nth_append \\<mu>'.simps[of _ 0])\nqed\n\nlemma dmu_array: assumes \"mm \\<le> m\" \n  shows \"dmu_array (IArray fs) m (IArray.of_fun (\\<lambda> i. IArray.of_fun (\\<lambda> j. \\<mu>' i j) (Suc i)) mm) mm \n\t  = IArray.of_fun (\\<lambda> i. IArray.of_fun (\\<lambda> j. \\<mu>' i j) (Suc i)) m\" \n\tusing assms\nproof (induct mm rule: wf_induct[OF wf_measure[of \"\\<lambda> mm. m - mm\"]])\n  case (1 mm)\n  show ?case\n  proof (cases \"mm = m\")\n    case True\n    thus ?thesis unfolding dmu_array.simps[of _ _ _ mm] by simp\n  next\n    case False\n    with 1(2-)\n    have mm: \"mm \\<le> m\" and id: \"(Suc mm = 0) = False\" \"Suc mm - 1 = mm\" \"(mm = m) = False\"\n      and prems: \"(Suc mm, mm) \\<in> measure ((-) m)\" \"Suc mm \\<le> m\" by auto\n    have list: \"[0..<Suc mm] = [0..< mm] @ [mm]\" by auto\n    note IH = 1(1)[rule_format, OF prems]\n    show ?thesis unfolding dmu_array.simps[of _ _ _ mm] id if_False Let_def \n      unfolding dmu_array_row[OF mm] IH[symmetric]\n      by (rule arg_cong[of _ _ \"\\<lambda> x. dmu_array _ _ x _\"], rule iarray_cong, auto)\n  qed\nqed\n\nlemma d\\<mu>_impl: \"d\\<mu>_impl fs = IArray.of_fun (\\<lambda> i. IArray.of_fun (\\<lambda> j. d\\<mu> i j) (Suc i)) m\" \n  unfolding d\\<mu>_impl_def using dmu_array[of 0] by (auto simp: \\<mu>')\n\nend (* fs_int_indpt *)\n\ncontext gram_schmidt_fs_int\nbegin\n\nlemma N_\\<mu>':\n  assumes \"i < m\" \"j \\<le> i\"\n  shows \"(\\<mu>' i j)\\<^sup>2 \\<le> N ^ (3 * Suc j)\"\nproof -\n  have 1: \"1 \\<le> N * N ^ j\"\n    using assms N_1 one_le_power[of _ \"Suc j\"] by fastforce\n  have \"0 < d (Suc j)\"\n     using assms by (intro Gramian_determinant) auto\n  then have [simp]: \"0 \\<le> d (Suc j)\"\n    by arith\n  have N_d: \"d (Suc j) \\<le> N ^ (Suc j)\"\n    using assms by (intro N_d) auto\n  have \"(\\<mu>' i j)\\<^sup>2 = (d (Suc j)) * (d (Suc j)) * (\\<mu> i j)\\<^sup>2\"\n    unfolding \\<mu>'_def by (auto simp add: power2_eq_square)\n  also have \"\\<dots> \\<le> (d (Suc j)) * (d (Suc j)) * N ^ (Suc j)\"\n  proof -\n    have \"(\\<mu> i j)\\<^sup>2 \\<le> N ^ (Suc j)\" if \"i = j\"\n      using that 1 by (auto simp add: \\<mu>.simps)\n    moreover have \"(\\<mu> i j)\\<^sup>2 \\<le> N ^ (Suc j)\" if \"i \\<noteq> j\"\n      using N_mu assms that by (auto)\n    ultimately have \"(\\<mu> i j)\\<^sup>2 \\<le> N ^ (Suc j)\"\n      by fastforce\n    then show ?thesis\n      by (intro mult_mono[of _ _ \"(\\<mu> i j)\\<^sup>2\"]) (auto)\n  qed\n  also have \"\\<dots> \\<le> N ^ (Suc j) * N ^ (Suc j) * N ^ (Suc j)\"\n    using assms 1 N_d by (auto intro!: mult_mono)\n  also have \"N ^ (Suc j) * N ^ (Suc j) * N ^ (Suc j) = N ^ (3 * (Suc j))\"\n    using nat_pow_distrib nat_pow_pow power3_eq_cube by metis\n  finally show ?thesis\n    by simp\nqed\n\nlemma N_\\<sigma>:\n  assumes \"i < m\" \"j \\<le> i\" \"l \\<le> j\"\n  shows \"\\<bar>\\<sigma> l i j\\<bar> \\<le> of_nat l * N ^ (2 * l + 2)\"\nproof -\n  have 1: \"\\<bar>d l\\<bar> = d l\"\n    using Gramian_determinant(2) assms by (intro abs_of_pos) auto\n  then have \"\\<bar>\\<sigma> l i j\\<bar> = d l * \\<bar>\\<Sum>k<l. \\<mu> i k * \\<mu> j k * \\<beta> fs k\\<bar>\"\n    using assms by (subst \\<sigma>, fastforce, subst abs_mult) auto\n  also have \"\\<dots> \\<le> N ^ l * (of_nat l * N ^ (l + 2))\"\n  proof -\n    have \"\\<bar>\\<Sum>k<l. \\<mu> i k * \\<mu> j k * \\<beta> fs k\\<bar> \\<le> of_nat l * N ^ (l + 2)\"\n    proof -\n      have [simp]: \"0 \\<le> \\<beta> fs k\" \"\\<parallel>gso k\\<parallel>\\<^sup>2 \\<le> N\" if \"k < l\" for k\n        using that assms N_gso \\<beta>_pos[of k] by auto\n      have [simp]: \"0 \\<le> N * N ^ k\" for k\n        using N_ge_0 assms by fastforce\n      have \"\\<bar>(\\<Sum>k < l. \\<mu> i k * \\<mu> j k * \\<beta> fs k)\\<bar> \\<le> (\\<Sum>k < l. \\<bar>\\<mu> i k * \\<mu> j k * \\<beta> fs k\\<bar>)\"\n        using sum_abs by blast\n      also have \"\\<dots> = (\\<Sum>k < l. \\<bar>\\<mu> i k * \\<mu> j k\\<bar> * \\<beta> fs k)\"\n        using assms by (auto intro!: sum.cong simp add: gso_norm_beta abs_mult_pos sq_norm_vec_ge_0)\n      also have \"\\<dots> = (\\<Sum>k < l. \\<bar>\\<mu> i k\\<bar> * \\<bar>\\<mu> j k\\<bar> * \\<beta> fs k)\"\n        using abs_mult by (fastforce intro!: sum.cong)\n      also have \"\\<dots> \\<le> (\\<Sum>k < l. (max \\<bar>\\<mu> i k\\<bar> \\<bar>\\<mu> j k\\<bar>) * (max \\<bar>\\<mu> i k\\<bar> \\<bar>\\<mu> j k\\<bar>) * \\<beta> fs k)\"\n        by (auto intro!: sum_mono mult_mono)\n      also have \"\\<dots> = (\\<Sum>k < l. (max \\<bar>\\<mu> i k\\<bar> \\<bar>\\<mu> j k\\<bar>)\\<^sup>2 * \\<beta> fs k)\"\n        by (auto simp add: power2_eq_square)\n      also have \"\\<dots> \\<le> (\\<Sum>k < l. N ^ (Suc k) * \\<beta> fs k)\"\n        using assms N_mu[of i] N_mu[of j] assms\n        by (auto intro!: sum_mono mult_right_mono simp add: max_def)\n      also have \"\\<dots> \\<le> (\\<Sum>k < l. N ^ (Suc k) * N)\"\n        using assms by (auto simp add: gso_norm_beta intro!: sum_mono mult_left_mono)\n      also have \"\\<dots> \\<le> (\\<Sum>k < l. N ^ (Suc l) * N)\"\n        using assms N_1 N_ge_0 assms by (fastforce intro!: sum_mono mult_right_mono power_increasing)\n      also have \"\\<dots> = of_nat l * N ^ (l + 2)\"\n        by auto\n      finally show ?thesis\n        by auto\n    qed\n    then show ?thesis\n      using assms N_d N_ge_0 by (fastforce intro!: mult_mono zero_le_power)\n  qed\n  also have \"\\<dots> = of_nat l * N ^ (2 * l + 2)\"\n    by (auto simp add: field_simps mult_2_right simp flip: power_add)\n  finally show ?thesis\n    by simp\nqed\n\nlemma leq_squared: \"(z::int) \\<le> z\\<^sup>2\"\nproof (cases \"0 < z\")\n  case True\n  then show ?thesis\n    by (auto intro!: self_le_power)\nnext\n  case False\n  then have \"z \\<le> 0\"\n    by (simp)\n  also have \"0 \\<le> z\\<^sup>2\"\n    by (auto)\n  finally show ?thesis\n    by simp\nqed\n\nlemma abs_leq_squared: \"\\<bar>z::int\\<bar> \\<le> z\\<^sup>2\"\n  using leq_squared[of \"\\<bar>z\\<bar>\"] by auto\n\nend (* gram_schmidt_fs_int *)\n\ncontext gram_schmidt_fs_int\nbegin\n\ndefinition gso' where \"gso' i = d i \\<cdot>\\<^sub>v (gso i)\"\n\nfun a where\n  \"a i 0 = fs ! i\" |\n  \"a i (Suc l) = (1 / d l) \\<cdot>\\<^sub>v ((d (Suc l) \\<cdot>\\<^sub>v (a i l)) - ( \\<mu>' i l) \\<cdot>\\<^sub>v gso' l)\"\n\nlemma gso'_carrier_vec: \n  assumes \"i < m\"\n  shows \"gso' i \\<in> carrier_vec n\"\n  using assms by (auto simp add: gso'_def)\n\nlemma a_carrier_vec: \n  assumes \"l \\<le> i\" \"i < m\"\n  shows \"a i l \\<in> carrier_vec n\"\n  using assms by (induction l arbitrary: i) (auto simp add: gso'_def)\n\nlemma a_l: \n  assumes \"l \\<le> i\" \"i < m\"\n  shows \"a i l = d l \\<cdot>\\<^sub>v (fs ! i + M.sumlist (map (\\<lambda>j. - \\<mu> i j \\<cdot>\\<^sub>v gso j) [0..<l]))\"\nusing assms proof (induction l)\n  case 0\n  then show ?case by auto\nnext\n  case (Suc l)\n  have fsi: \"fs ! i \\<in> carrier_vec n\" using f_carrier[of i] assms by auto\n  have l_i_m: \"l \\<le> i \\<Longrightarrow> l < m\" using assms by auto\n  let ?a = \"fs ! i\"\n  let ?sum = \"M.sumlist (map (\\<lambda>j. - \\<mu> i j \\<cdot>\\<^sub>v gso j) [0..<l])\" \n  let ?term = \"(- \\<mu> i l \\<cdot>\\<^sub>v gso l)\" \n  have carr: \"{?a,?sum,?term} \\<subseteq> carrier_vec n\" \n    using gso_dim l_i_m Suc(2) sumlist_dim assms\n    by (auto intro!: sumlist_carrier)\n  have \"a i (Suc l) = \n        (1 / d l) \\<cdot>\\<^sub>v ((d (Suc l) \\<cdot>\\<^sub>v (d l \\<cdot>\\<^sub>v (fs ! i + M.sumlist (map (\\<lambda>j. - \\<mu> i j \\<cdot>\\<^sub>v gso j) [0..<l]))))\n        - ( \\<mu>' i l) \\<cdot>\\<^sub>v gso' l)\" using a.simps Suc by auto\n  also have \"\\<dots> = (1 / d l) \\<cdot>\\<^sub>v ((d (Suc l) \\<cdot>\\<^sub>v (d l \\<cdot>\\<^sub>v (fs ! i + M.sumlist (map (\\<lambda>j. - \\<mu> i j \\<cdot>\\<^sub>v gso j) [0..<l]))))\n        + -d (Suc l) * \\<mu> i l * d l \\<cdot>\\<^sub>v gso l )\"  (is \"_ = _ \\<cdot>\\<^sub>v (?t1 + ?t2)\")\n    unfolding \\<mu>'_def gso'_def by auto\n  also have \"?t2 = d l \\<cdot>\\<^sub>v (-d (Suc l) * \\<mu> i l \\<cdot>\\<^sub>v gso l )\" (is \"_ = d l \\<cdot>\\<^sub>v ?tt2\")\n    using smult_smult_assoc by (auto)\n  also have \"?t1 = d l \\<cdot>\\<^sub>v ((d (Suc l) \\<cdot>\\<^sub>v (fs ! i + M.sumlist (map (\\<lambda>j. - \\<mu> i j \\<cdot>\\<^sub>v gso j) [0..<l]))))\" (is \"_ = d l \\<cdot>\\<^sub>v ?tt1\")\n    using smult_smult_assoc smult_smult_assoc[symmetric] by (auto)\n  also have \"d l \\<cdot>\\<^sub>v ?tt1 + d l \\<cdot>\\<^sub>v ?tt2 = d l \\<cdot>\\<^sub>v (?tt1 + ?tt2)\"\n    using gso_carrier l_i_m Suc fsi \n    by (auto intro!: smult_add_distrib_vec[symmetric, of _ n] add_carrier_vec sumlist_carrier)\n  also have \"(1 / d l) \\<cdot>\\<^sub>v \\<dots> = (d l / d l) \\<cdot>\\<^sub>v (?tt1 + ?tt2)\"\n    by (intro eq_vecI, auto)\n  also have \"d l / d l = 1\" \n     using Gramian_determinant(2)[of l] l_i_m Suc by(auto simp: field_simps)\n  also have  \"1 \\<cdot>\\<^sub>v (?tt1 + ?tt2) = ?tt1 + ?tt2\"  by simp\n  also have \"?tt2 = d (Suc l) \\<cdot>\\<^sub>v (- \\<mu> i l \\<cdot>\\<^sub>v gso l)\" by auto\n  also have \"d (Suc l) \\<cdot>\\<^sub>v (fs ! i + ?sum) + \\<dots> =\n             d (Suc l) \\<cdot>\\<^sub>v (fs ! i + ?sum + ?term)\"\n    using carr by (subst smult_add_distrib_vec) (auto)\n  also have \"(?a + ?sum) + ?term = ?a + (?sum + ?term)\"\n    using carr by auto\n  also have \"?term = M.sumlist (map (\\<lambda>j. - \\<mu> i j \\<cdot>\\<^sub>v gso j) [l..<Suc l])\"\n    using gso_carrier Suc l_i_m by auto\n  also have \"?sum + ... = M.sumlist (map (\\<lambda>j. - \\<mu> i j \\<cdot>\\<^sub>v gso j) [0..<Suc l])\"\n    apply(subst sumlist_append[symmetric])\n    using fsi l_i_m Suc sumlist_carrier gso_carrier by (auto intro!: sumlist_carrier)\n  finally show ?case by auto\nqed\n\nlemma a_l': \n  assumes \"i < m\"\n  shows \"a i i = gso' i\"\nproof -\n  have \"a i i = d i \\<cdot>\\<^sub>v (fs ! i + M.sumlist (map (\\<lambda>j. - \\<mu> i j \\<cdot>\\<^sub>v gso j) [0..<i]))\"\n    using a_l assms by auto\n  also have \"\\<dots> = d i \\<cdot>\\<^sub>v gso i\"\n    by (subst gso.simps, auto)\n  finally have \"a i i = gso' i\" using gso'_def by auto\n  from this show ?thesis by auto\nqed\n\nlemma \n  assumes \"i < m\" \"l' \\<le> i\"\n  shows \"a i l' = (case l' of\n         0 \\<Rightarrow> fs ! i |\n         Suc l \\<Rightarrow> (1 / d l) \\<cdot>\\<^sub>v (d (Suc l) \\<cdot>\\<^sub>v (a i l) - (\\<mu>' i l) \\<cdot>\\<^sub>v a l l))\"\nproof (cases l')\n  case (Suc l)\n  have \"a i (Suc l) = (1 / d l) \\<cdot>\\<^sub>v ((d (Suc l) \\<cdot>\\<^sub>v (a i l)) - ( \\<mu>' i l) \\<cdot>\\<^sub>v a l l)\" \n    using assms a_l Suc by(subst a_l', auto)\n  from this Suc show ?thesis by auto\nqed auto\n\nlemma a_Ints:\n  assumes \"i < m\" \"l \\<le> i\" \"k < n\"\n  shows \"a i l $ k \\<in> \\<int>\"\nproof -\n  have fsi: \"fs ! i \\<in> carrier_vec n\" using f_carrier[of i] assms by auto\n  have \"a i l = d l \\<cdot>\\<^sub>v (fs ! i + M.sumlist (map (\\<lambda>j. - \\<mu> i j \\<cdot>\\<^sub>v gso j) [0..<l]))\" \n    (is \"_ = _ \\<cdot>\\<^sub>v (_ + ?sum)\")\n    using assms by (subst a_l, auto)\n  also have \"?sum = sumlist (map (\\<lambda>k. \\<kappa> i l k \\<cdot>\\<^sub>v fs ! k) [0..<l])\"\n    using assms gso_carrier\n    by (subst \\<kappa>_def, auto)\n  also have \"d l \\<cdot>\\<^sub>v (fs ! i + sumlist (map (\\<lambda>k. \\<kappa> i l k \\<cdot>\\<^sub>v fs ! k) [0..<l])) \n           = d l \\<cdot>\\<^sub>v fs ! i + d l \\<cdot>\\<^sub>v sumlist (map (\\<lambda>k. \\<kappa> i l k \\<cdot>\\<^sub>v fs ! k) [0..<l])\"\n    (is \"_ = _ + ?sum\")\n    using sumlist_carrier fsi apply\n      (subst smult_add_distrib_vec[symmetric])\n      apply force\n    using assms fsi by (subst sumlist_carrier, auto) \n  also have \"?sum = sumlist  (map (\\<lambda>k. (d l * \\<kappa> i l k) \\<cdot>\\<^sub>v fs ! k) [0..<l])\"\n    apply(subst eq_vecI sumlist_nth)\n    using fsi assms\n    by (auto simp: dim_sumlist sum_distrib_left sumlist_nth smult_smult_assoc algebra_simps)\n  finally have \"a i l = d l \\<cdot>\\<^sub>v fs ! i + sumlist  (map (\\<lambda>k. (d l * \\<kappa> i l k) \\<cdot>\\<^sub>v fs ! k) [0..<l])\"\n    by auto\n  \n  hence \"a i l $ k = (d l \\<cdot>\\<^sub>v fs ! i + sumlist (map (\\<lambda>k. (d l * \\<kappa> i l k) \\<cdot>\\<^sub>v fs ! k) [0..<l])) $ k\" by simp\n  also have \"\\<dots> = (d l \\<cdot>\\<^sub>v fs ! i) $ k + (sumlist (map (\\<lambda>k. (d l * \\<kappa> i l k) \\<cdot>\\<^sub>v fs ! k) [0..<l])) $ k\" \n    apply (subst index_add_vec)\n    using assms fsi by (subst sumlist_dim, auto)\n  finally have id: \"a i l $ k = (d l \\<cdot>\\<^sub>v fs ! i) $ k + (sumlist (map (\\<lambda>k. (d l * \\<kappa> i l k) \\<cdot>\\<^sub>v fs ! k) [0..<l])) $ k\".\n  \n  show ?thesis unfolding id\n    using fsi assms d_\\<kappa>_Ints fs_int\n    by (auto simp: dim_sumlist sumlist_nth\n      intro!: Gramian_determinant_Ints sumlist_carrier Ints_minus Ints_add Ints_sum Ints_mult[of _ \"fs ! _ $ _\"]  Ints_scalar_prod[OF fsi])\nqed\n\nlemma a_alt_def:\n  assumes \"l < length fs\"\n  shows \"a i (Suc l) = (let v = \\<mu>' l l \\<cdot>\\<^sub>v (a i l) - ( \\<mu>' i l) \\<cdot>\\<^sub>v a l l in\n                       (if l = 0 then v else (1 / \\<mu>' (l - 1) (l - 1)) \\<cdot>\\<^sub>v v))\"\nproof -\n  have [simp]: \"\\<mu>' (l - Suc 0) (l - Suc 0) = d l\" if \"0 < l\"\n    using that unfolding \\<mu>'_def by (auto simp add: \\<mu>.simps)\n  have [simp]: \"\\<mu>' l l = d (Suc l)\"\n    unfolding \\<mu>'_def by (auto simp add: \\<mu>.simps)\n  show ?thesis\n    using assms by (auto simp add: Let_def a_l')\nqed\n\nend (* gram_schmidt_fs_int *)\n\n\ncontext fs_int_indpt\nbegin\n\n\nfun gso_int :: \"nat \\<Rightarrow> nat \\<Rightarrow> int vec\" where\n  \"gso_int i 0 = fs ! i\" |\n  \"gso_int i (Suc l) = (let v = \\<mu>' l l \\<cdot>\\<^sub>v (gso_int i l) - \\<mu>' i l \\<cdot>\\<^sub>v gso_int l l in\n                         (if l = 0 then v else map_vec (\\<lambda>k. k div \\<mu>' (l - 1) (l - 1)) v))\"\n\nlemma gso_int_carrier_vec:\n  assumes \"i < length fs\" \"l \\<le> i\"\n  shows \"gso_int i l \\<in> carrier_vec n\"\n  using assms by (induction l arbitrary: i) (fastforce simp add: Let_def)+\n\nlemma gso_int:\n  assumes \"i < length fs\" \"l \\<le> i\"\n  shows \"of_int_hom.vec_hom (gso_int i l) = gs.a i l\"\nproof -\n  have \"dim_vec (gso_int i l) = n\" \"dim_vec (gs.a i l) = n\"\n    using gs.a_carrier_vec assms gso_int_carrier_vec carrier_dim_vec by auto\n  moreover have \"of_int_hom.vec_hom (gso_int i l) $ k = gs.a i l $ k\" if k: \"k < n\" for k\n    using assms proof (induction l arbitrary: i)\n    case (Suc l)\n    note IH = Suc(1)\n    have [simp]: \"dim_vec (gso_int i l) = n\" \"dim_vec (gs.a i l) = n\" \"dim_vec (gso_int l l) = n\"\n      \"dim_vec (gs.a l l) = n\"\n      using Suc gs.a_carrier_vec gso_int_carrier_vec carrier_dim_vec gs.gso'_carrier_vec by auto\n    have \"rat_of_int (gso_int i l $ k) = gs.a i l $ k\" \"rat_of_int (gso_int l l $ k) = gs.a l l $ k\"\n      using that Suc(1)[of l] Suc(1)[of i] Suc by auto\n    then have ?case if \"l = 0\"\n    proof -\n      have [simp]: \"fs \\<noteq> []\"\n        using Suc by auto\n      have [simp]: \"dim_vec (gso_int i 0) = n\" \"dim_vec (gso_int 0 0) = n\" \"dim_vec (gs.a i 0) = n\"\n        \"dim_vec (gs.a 0 0) = n\"\n        using Suc fs_carrier carrier_dim_vec gs.a_carrier_vec f_carrier by auto\n      have [simp]: \"rat_of_int (\\<mu>' i 0) = gs.\\<mu>' i 0\" \"rat_of_int (\\<mu>' 0 0) = gs.\\<mu>' 0 0\"\n        using Suc \\<sigma>s_\\<mu>' by (auto intro!: \\<sigma>s_\\<mu>')\n      then show ?thesis\n        using that k Suc IH[of i ] Suc(1)[of 0]\n        by (subst gso_int.simps, subst gs.a_alt_def) (auto simp del: gso_int.simps gs.a.simps)\n    qed\n    moreover have ?case if \"0 < l\"\n    proof -\n      have *: \"rat_of_int (\\<mu>' l l * gso_int i l $ k - \\<mu>' i l * gso_int l l $ k) / rat_of_int (\\<mu>' (l - Suc 0) (l - Suc 0))\n     = gs.a i (Suc l) $ k\"\n        using Suc IH[of l] IH[of i] \\<sigma>s_\\<mu>' k that by (subst gs.a_alt_def) (auto simp add: Let_def )\n      have \"of_int_hom.vec_hom (gso_int i (Suc l)) $ k =\n            rat_of_int ((\\<mu>' l l * gso_int i l $ k - \\<mu>' i l * gso_int l l $ k) \n                        div \\<mu>' (l - Suc 0) (l - Suc 0))\"\n        using that gso_int_carrier_vec k by (auto)\n      also have \"\\<dots> = rat_of_int (\\<mu>' l l * gso_int i l $ k - \\<mu>' i l * gso_int l l $ k) / rat_of_int (\\<mu>' (l - Suc 0) (l - Suc 0))\"\n        using gs.a_Ints k Suc by (intro exact_division, subst *, force)\n      also note *\n      finally show ?thesis\n        by (auto)\n    qed\n    ultimately show ?case\n      by blast\n  qed (auto)\n  ultimately show ?thesis\n    by auto\nqed\n\nfunction gso_int_tail' :: \"nat \\<Rightarrow> nat \\<Rightarrow> int vec \\<Rightarrow> int vec\" where\n  \"gso_int_tail' i l acc = (if l \\<ge> i then acc\n    else (let v = \\<mu>' l l \\<cdot>\\<^sub>v acc - \\<mu>' i l \\<cdot>\\<^sub>v gso_int l l;\n              acc' = (map_vec (\\<lambda>k. k div \\<mu>' (l - 1) (l - 1)) v)\n        in gso_int_tail' i (l + 1) acc'))\"\n  by pat_completeness auto\ntermination\n  by  (relation \"(\\<lambda>(i,l,acc). i - l)  <*mlex*> {}\",  goal_cases) (auto intro!: mlex_less wf_mlex)\n\nfun gso_int_tail :: \"nat \\<Rightarrow> int vec\" where\n  \"gso_int_tail i = (if i = 0 then fs ! 0 else\n     let acc = \\<mu>' 0 0 \\<cdot>\\<^sub>v fs ! i - \\<mu>' i 0 \\<cdot>\\<^sub>v fs ! 0 in\n     gso_int_tail' i 1 acc)\"\n\nlemma gso_int_tail':\n  assumes \"acc = gso_int i l\" \"0 < i\" \"0 < l\" \"l \\<le> i\"\n  shows \"gso_int_tail' i l acc = gso_int i i\"\n  using assms proof (induction i l acc rule: gso_int_tail'.induct)\n  case (1 i l acc)\n  { assume li: \"l < i\"\n    then have \"gso_int_tail' i l acc =\n        gso_int_tail' i (l + 1) (map_vec (\\<lambda>k. k div \\<mu>' (l - 1) (l - 1)) (\\<mu>' l l \\<cdot>\\<^sub>v acc - \\<mu>' i l \\<cdot>\\<^sub>v gso_int l l))\"  \n      using 1 by (auto simp add: Let_def)\n    also have \"\\<dots> = gso_int i i\"\n      using 1 li by (intro 1) (auto)\n  }\n  then show ?case\n    using 1 by fastforce\nqed\n\nlemma gso_int_tail: \"gso_int_tail i = gso_int i i\"\nproof (cases \"0 < i\")\n  assume i: \"0 < i\"\n  then have \"gso_int_tail i = gso_int_tail' i (Suc 0) (gso_int i 1)\"\n    by (subst gso_int_tail.simps) (auto)\n  also have \"\\<dots> = gso_int i i\"\n    using i by (intro gso_int_tail') (auto intro!: gso_int_tail')\n  finally show \"gso_int_tail i = gso_int i i\"\n    by simp\nqed (auto)\n\nend\n\nlocale gso_array\nbegin\n\nfunction while :: \"nat \\<Rightarrow> nat \\<Rightarrow> int vec iarray \\<Rightarrow> int iarray iarray \\<Rightarrow> int vec \\<Rightarrow> int vec\" where\n  \"while i l gsa dmusa acc =  (if l \\<ge> i then acc\n    else (let v = dmusa !! l !! l \\<cdot>\\<^sub>v acc - dmusa !! i !! l \\<cdot>\\<^sub>v gsa !! l;\n              acc' = (map_vec (\\<lambda>k. k div dmusa !! (l - 1) !! (l - 1)) v)\n        in while i (l + 1) gsa dmusa acc'))\"\n  by pat_completeness auto\ntermination\n  by  (relation \"(\\<lambda>(i,l,acc). i - l)  <*mlex*> {}\",  goal_cases) (auto intro!: mlex_less wf_mlex)\n\ndeclare while.simps[simp del]\n\ndefinition gso' where\n  \"gso' i fsa gsa dmusa = (if i = 0 then fsa !! 0 else\n     let acc = dmusa !! 0 !! 0 \\<cdot>\\<^sub>v fsa !! i - dmusa !! i !! 0 \\<cdot>\\<^sub>v fsa !! 0 in\n     while i 1 gsa dmusa acc)\"\n\nfunction gsos' where\n  \"gsos' i n dmusa fsa gsa = (if i \\<ge> n then gsa else\n    gsos' (i + 1) n dmusa fsa (iarray_append gsa (gso' i fsa gsa dmusa)))\"\n  by pat_completeness auto\ntermination\n  by  (relation \"(\\<lambda>(i,n,dmusa,fsa,gsa). n - i)  <*mlex*> {}\",  goal_cases) (auto intro!: mlex_less wf_mlex)\n\ndeclare gsos'.simps[simp del]\n\ndefinition gso'_array where\n  \"gso'_array dmusa fs = gsos' 0 (length fs) dmusa (IArray fs) (IArray [])\"\n\ndefinition gso_array where\n  \"gso_array fs = (let dmusa = d\\<mu>_impl fs; gsa = gso'_array dmusa fs\n                   in IArray.of_fun (\\<lambda>i. (if i = 0 then 1 else inverse (rat_of_int (dmusa !! (i - 1) !! (i - 1))))\n                      \\<cdot>\\<^sub>v of_int_hom.vec_hom (gsa !! i)) (length fs))\"\n\nend\n\ndeclare gso_array.gso_array_def[code]\ndeclare gso_array.gso'_array_def[code]\ndeclare gso_array.gsos'.simps[code]\ndeclare gso_array.gso'_def[code]\ndeclare gso_array.while.simps[code]\n\nlemma map_vec_id[simp]: \"map_vec id = id\"\n  by (auto intro!: eq_vecI)\n\ncontext fs_int_indpt\nbegin\n\nlemma \"gso_array.gso'_array (d\\<mu>_impl fs) fs = IArray (map (\\<lambda>k. gso_int k k) [0..<length fs])\"\nproof -\n  have a[simp]: \"IArray (IArray.list_of a) = a\" for a:: \"'a iarray\"\n    by (metis iarray.exhaust list_of.simps)\n  have [simp]: \"length (IArray.list_of (iarray_append xs x)) = Suc (IArray.length xs)\" for x xs\n    unfolding iarray_append_code by (simp)\n  have [simp]: \"map_iarray f as = IArray (map f (IArray.list_of as))\" for f as\n    by (metis a iarray.simps(4))\n  have d[simp]: \"IArray.list_of (IArray.list_of (d\\<mu>_impl fs) ! i) ! j = \\<mu>' i j\"\n    if \"i < length fs\" \"j \\<le> i\" for j i\n    using that by (auto simp add: \\<mu>' d\\<mu>_impl nth_append)\n  let ?rat_vec = \"of_int_hom.vec_hom\"\n  have *: \"gso_array.while i j gsa (d\\<mu>_impl fs) acc = gso_int_tail' i j acc'\"\n      if \"i < length fs\" \"j \\<le> i\" \"acc = acc'\"\n         \"\\<And>k. k < i \\<Longrightarrow> gsa !! k = gso_int k k\" for i j gsa acc acc'\n    using that apply (induction i j acc arbitrary: acc' rule: gso_int_tail'.induct)\n    by (subst gso_array.while.simps, subst gso_int_tail'.simps, auto)\n  then have *: \"gso_array.gso' i (IArray fs) gsa (d\\<mu>_impl fs) = gso_int i i\"\n    if assms: \"i < length fs\" \"\\<And>k. k < i \\<Longrightarrow> gsa !! k = gso_int k k\" for i gsa\n  proof -\n    have \"IArray.list_of (IArray.list_of (d\\<mu>_impl fs) ! 0) ! 0 = \\<mu>' 0 0\"\n      using that by (subst d) (auto)\n    then have \"gso_array.gso' i (IArray fs) gsa (d\\<mu>_impl fs) = gso_int_tail i\"\n      unfolding gso_array.gso'_def gso_int_tail.simps Let_def\n      using that * by (auto simp del: gso_int_tail'.simps)\n    then show ?thesis\n      using gso_int_tail by simp\n  qed\n  then have *: \"gso_array.gsos' i n (d\\<mu>_impl fs) (IArray fs) gsa =\n         IArray (IArray.list_of gsa @ (map (\\<lambda>k. gso_int k k) [i..<n]))\"\n    if \"n \\<le> length fs\"\n       \"gsa = IArray.of_fun (\\<lambda>k. gso_int k k) i\" for i n gsa\n    using that proof (induction i n \"(d\\<mu>_impl fs)\" \"(IArray fs)\" gsa rule: gso_array.gsos'.induct)\n    case (1 i n gsa)\n    { assume i_n: \"i < n\"\n      have [simp]: \"gso_array.gso' i (IArray fs) gsa (d\\<mu>_impl fs) = gso_int i i\"\n        using 1 i_n by (intro *) auto\n      have \"gso_array.gsos' i n (d\\<mu>_impl fs) (IArray fs) gsa = gso_array.gsos' (i + 1) n (d\\<mu>_impl fs) (IArray fs) (iarray_append gsa (gso_array.gso' i (IArray fs) gsa (d\\<mu>_impl fs)))\"\n        using i_n by (simp add: gso_array.gsos'.simps)\n      also have \"\\<dots> = IArray (IArray.list_of gsa @ gso_int i i # map (\\<lambda>k. gso_int k k) [Suc i..<n])\"\n        using 1 i_n by (subst 1) (auto simp add: iarray_append_code)\n      also have \"\\<dots> = IArray (IArray.list_of gsa @ map (\\<lambda>k. gso_int k k) [i..<n])\"\n        using i_n by (auto simp add: upt_conv_Cons)\n      finally have ?case\n        by simp }\n    then show ?case\n      by (auto simp add: gso_array.gsos'.simps)\n  qed\n  then show ?thesis\n    unfolding gso_array.gso'_array_def by (subst *) auto\nqed\n\nend\n\nsubsection \\<open>Lemmas Summarizing All Bounds During GSO Computation\\<close>\n\ncontext gram_schmidt_fs_int\nbegin\n\nlemma combined_size_bound_integer:  \n  assumes x: \"x \\<in> {fs ! i $ j | i j. i < m \\<and> j < n} \n    \\<union> {\\<mu>' i j | i j. j \\<le> i \\<and> i < m}\n    \\<union> {\\<sigma> l i j | i j l. i < m \\<and> j \\<le> i \\<and> l \\<le> j}\" \n    (is \"x \\<in> ?fs \\<union> ?\\<mu>' \\<union> ?\\<sigma>\")\n    and m: \"m \\<noteq> 0\"\n  shows \"\\<bar>x\\<bar> \\<le> of_nat m * N ^ (3 * Suc m)\"\nproof -\n  let ?m = \"(of_nat m)::'a::trivial_conjugatable_linordered_field\"\n  have [simp]: \"1 \\<le> ?m\"\n    using m by (metis Num.of_nat_simps One_nat_def Suc_leI neq0_conv of_nat_mono)\n  have [simp]: \"\\<bar>(of_int z)::'a::trivial_conjugatable_linordered_field\\<bar> \\<le> (of_int z)\\<^sup>2\" for z\n    using abs_leq_squared by (metis of_int_abs of_int_le_iff of_int_power)\n  have \"\\<bar>fs ! i $ j\\<bar> \\<le> of_nat m * N ^ (3 * Suc m)\" if \"i < m\" \"j < n\" for i j\n  proof -\n    have \"\\<bar>fs ! i $ j\\<bar> \\<le> \\<bar>fs ! i $ j\\<bar>\\<^sup>2\"\n      by (rule Ints_cases[of \"fs ! i $ j\"]) (use fs_int that in auto)\n    also have \"\\<bar>fs ! i $ j\\<bar>\\<^sup>2 \\<le> \\<parallel>fs ! i\\<parallel>\\<^sup>2\"\n      using that by (intro vec_le_sq_norm) (auto)\n    also have \"... \\<le> 1 * N\"\n      using N_fs that by auto\n    also have \"\\<dots> \\<le> of_nat m * N ^ (3 * Suc m)\"\n      using m N_1 by (intro mult_mono) (auto intro!: mult_mono self_le_power)\n    finally show ?thesis\n      by (auto)\n  qed\n  then have \"\\<bar>x\\<bar> \\<le> of_nat m * N ^ (3 * Suc m)\" if \"x \\<in> ?fs\"\n    using that by auto\n  moreover have \"\\<bar>x\\<bar> \\<le> of_nat m * N ^ (3 * Suc m)\" if \"x \\<in> ?\\<mu>'\"\n  proof -\n    have \"\\<bar>\\<mu>' i j\\<bar> \\<le> of_nat m * N ^ (3 + 3 * m)\" if \"j \\<le> i\" \"i < m\" for i j\n    proof -\n      have \"\\<mu>' i j \\<in> \\<int>\"\n        unfolding \\<mu>'_def using that d_mu_Ints by auto\n      then have \"\\<bar>\\<mu>' i j\\<bar> \\<le> (\\<mu>' i j)\\<^sup>2\"\n        by (rule Ints_cases[of \"\\<mu>' i j\"]) auto\n      also have \"\\<dots> \\<le> N ^ (3 * Suc j)\"\n        using that N_\\<mu>' by auto\n      also have \"\\<dots> \\<le> 1 * N ^ (3 * Suc m)\"\n        using that assms N_1 by (auto intro!: power_increasing)\n      also have \"\\<dots> \\<le> of_nat m * N ^ (3 * Suc m)\"\n        using N_ge_0 assms zero_le_power by (intro mult_mono) auto\n      finally show ?thesis\n        by auto\n    qed\n    then show ?thesis\n      using that by auto\n  qed\n  moreover have \"\\<bar>x\\<bar> \\<le> of_nat m * N ^ (3 * Suc m)\" if \"x \\<in> ?\\<sigma>\"\n  proof -\n    have \"\\<bar>\\<sigma> l i j\\<bar> \\<le> of_nat m * N ^ (3 + 3 * m)\" if \"i < m\" \"j \\<le> i\" \"l \\<le> j\" for i j l\n    proof -\n      have \"\\<bar>\\<sigma> l i j\\<bar> \\<le> of_nat l * N ^ (2 * l + 2)\"\n        using that N_\\<sigma> by auto\n      also have \"\\<dots> \\<le> of_nat m * N ^ (2 * l + 2)\"\n        using that N_ge_0 assms zero_le_power by (intro mult_mono) auto\n      also have \"\\<dots> \\<le> of_nat m * N ^ (3 * Suc m)\"\n      proof -\n        have \"N ^ (2 * l + 2) \\<le> N ^ (3 * Suc m)\"\n          using that assms N_1 by (intro power_increasing) (auto intro!: power_increasing)\n        then show ?thesis\n          using that assms N_1 by (intro mult_mono) (auto)\n      qed\n      finally show ?thesis\n        by simp\n    qed\n    then show ?thesis\n      using that by (auto)\n  qed\n  ultimately show ?thesis\n    using assms by auto\nqed\n\nend (* gram_schmidt_fs_int *)\n\n (* \"x \\<noteq> 0 \\<Longrightarrow> log 2 \\<bar>x\\<bar> \\<le> 2 * m * log 2 N       + m + log 2 m\" (is \"_ \\<Longrightarrow> ?l1 \\<le> ?b1\")\n  \"x \\<noteq> 0 \\<Longrightarrow> log 2 \\<bar>x\\<bar> \\<le> 4 * m * log 2 (M * n) + m + log 2 m\" (is \"_ \\<Longrightarrow> _ \\<le> ?b2\") *)\n\ncontext fs_int_indpt\nbegin\n\n\nlemma combined_size_bound_rat_log:  \n  assumes x: \"x \\<in> {gs.\\<mu>' i j | i j. j \\<le> i \\<and> i < m}\n    \\<union> {gs.\\<sigma> l i j | i j l. i < m \\<and> j \\<le> i \\<and> l \\<le> j}\" \n    (is \"x \\<in> ?\\<mu>' \\<union> ?\\<sigma>\")\n    and m: \"m \\<noteq> 0\" \"x \\<noteq> 0\"\n  shows \"log 2 \\<bar>real_of_rat x\\<bar> \\<le> log 2 m + (3 + 3 * m) * log 2 (real_of_rat gs.N)\"\nproof -\n  let ?r_fs = \"map of_int_hom.vec_hom fs::rat vec list\"\n  have 1: \"map of_int_hom.vec_hom fs ! i $ j = of_int (fs ! i $ j)\" if \"i < m\" \"j < n\" for i j\n    using that by auto\n  then have \"{?r_fs ! i $ j |i j. i < length ?r_fs \\<and> j < n} = \n             {rat_of_int (fs ! i $ j) |i j. i < length fs \\<and> j < n}\"\n    by (metis (mono_tags, hide_lams) length_map)\n  then have \"x \\<in> {?r_fs ! i $ j |i j. i < length (map of_int_hom.vec_hom fs) \\<and> j < n}\n                 \\<union> {gs.\\<mu>' i j |i j. j \\<le> i \\<and> i < length ?r_fs}\n                 \\<union> {gs.\\<sigma> l i j |i j l. i < length ?r_fs \\<and> j \\<le> i \\<and> l \\<le> j}\"\n    using assms by auto\n  then have 1: \"\\<bar>x\\<bar> \\<le> rat_of_nat (length ?r_fs) * gs.N ^ (3 * Suc (length ?r_fs))\" (is \"?ax \\<le> ?t\")\n    using assms by (intro gs.combined_size_bound_integer) auto\n  then have 1: \"real_of_rat ?ax \\<le> real_of_rat ?t\"\n    using of_rat_less_eq 1 by auto\n  have 2: \"\\<bar>real_of_rat x\\<bar> = real_of_rat \\<bar>x\\<bar>\"\n    by auto\n  have \"log 2 \\<bar>real_of_rat x\\<bar> \\<le> log 2 (real_of_rat ?t)\"\n  proof -\n    have \"0 < rat_of_nat (length fs) * gs.N ^ (3 + 3 * length fs)\"\n      using assms gs.N_1 by (auto)\n    then show ?thesis\n      using 1 assms by (subst log_le_cancel_iff) (auto)\n  qed\n  also have \"real_of_rat ?t = real m * real_of_rat gs.N ^ (3 + 3 * m)\"\n    by (auto simp add: of_rat_mult of_rat_power)\n  also have \"log 2 (m * real_of_rat gs.N ^ (3 + 3 * m)) = log 2 m + log 2 (real_of_rat gs.N ^ (3 + 3 * m))\"\n    using gs.N_1 assms by (subst log_mult) auto\n  also have \"log 2 (real_of_rat gs.N ^ (3 + 3 * m)) = real (3 + 3 * length fs) * log 2 (real_of_rat gs.N)\"\n    using gs.N_1 assms by (subst log_nat_power) auto\n  finally show ?thesis\n    by (auto)\nqed\n\nlemma combined_size_bound_integer_log:  \n  assumes x: \"x \\<in> {\\<mu>' i j | i j. j \\<le> i \\<and> i < m}\n    \\<union> {\\<sigma>s l i j | i j l. i < m \\<and> j \\<le> i \\<and> l < j}\" \n    (is \"x \\<in> ?\\<mu>' \\<union> ?\\<sigma>\")\n    and m: \"m \\<noteq> 0\" \"x \\<noteq> 0\"\n  shows \"log 2 \\<bar>real_of_int x\\<bar> \\<le> log 2 m + (3 + 3 * m) * log 2 (real_of_rat gs.N)\"\nproof -\n  let ?x = \"rat_of_int x\" \n  from m have m: \"m \\<noteq> 0\" \"?x \\<noteq> 0\" by auto\n  show ?thesis\n  proof (rule order_trans[OF _ combined_size_bound_rat_log[OF _ m]], force)\n    from x consider (1) i j where \"x = \\<mu>' i j\" \"j \\<le> i\" \"i < m\" \n      | (2) l i j where \"x = \\<sigma>s l i j\" \"i < m\" \"j \\<le> i\" \"l < j\" by blast\n    thus \"?x \\<in> {gs.\\<mu>' i j |i j. j \\<le> i \\<and> i < m} \\<union> {gs.\\<sigma> l i j |i j l. i < m \\<and> j \\<le> i \\<and> l \\<le> j}\" \n    proof (cases)\n      case (1 i j)\n      with \\<sigma>s_\\<mu>'(2) show ?thesis by blast\n    next\n      case (2 l i j)\n      hence \"Suc l \\<le> j\" by auto\n      from \\<sigma>s_\\<mu>'(1) 2 this show ?thesis by blast\n    qed\n  qed\nqed\n\nend\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/Gram_Schmidt_Int.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8962513842182777, "lm_q2_score": 0.8175744673038222, "lm_q1q2_score": 0.7327522480225717}}
{"text": "(*  \n    Author:      Ren\u00e9 Thiemann \n                 Akihisa Yamada\n    License:     BSD\n*)\ntheory Conjugate\n  imports HOL.Complex\nbegin\n\nclass conjugate =\n  fixes conjugate :: \"'a \\<Rightarrow> 'a\"\n  assumes conjugate_id[simp]: \"conjugate (conjugate a) = a\"\n      and conjugate_cancel_iff[simp]: \"conjugate a = conjugate b \\<longleftrightarrow> a = b\"\n\nclass conjugatable_ring = ring + conjugate +\n  assumes conjugate_dist_mul: \"conjugate (a * b) = conjugate a * conjugate b\"\n      and conjugate_dist_add: \"conjugate (a + b) = conjugate a + conjugate b\"\n      and conjugate_neg: \"conjugate (-a) = - conjugate a\"\n      and conjugate_zero[simp]: \"conjugate 0 = 0\"\nbegin\n  lemma conjugate_zero_iff[simp]: \"conjugate a = 0 \\<longleftrightarrow> a = 0\"\n    using conjugate_cancel_iff[of _ 0, unfolded conjugate_zero].\nend\n\nclass conjugatable_field = conjugatable_ring + field\n\nlemma sum_conjugate:\n  fixes f :: \"'b \\<Rightarrow> 'a :: conjugatable_ring\"\n  assumes finX: \"finite X\"\n  shows \"conjugate (sum f X) = sum (\\<lambda>x. conjugate (f x)) X\"\n  using finX by (induct set:finite, auto simp: conjugate_dist_add)\n\nclass conjugatable_ordered_ring = conjugatable_ring + ordered_comm_monoid_add +\n  assumes conjugate_square_positive: \"a * conjugate a \\<ge> 0\"\n\nclass conjugatable_ordered_field = conjugatable_ordered_ring + field\nbegin\n  subclass conjugatable_field..\nend\n\nlemma conjugate_square_0:\n  fixes a :: \"'a :: {conjugatable_ordered_ring, semiring_no_zero_divisors}\"\n  shows \"a * conjugate a = 0 \\<Longrightarrow> a = 0\" by auto\n\n\nsubsection \\<open>Instantiations\\<close>\n\ninstantiation complex :: conjugatable_ordered_field\nbegin\n  definition [simp]: \"conjugate \\<equiv> cnj\"\n  definition [simp]: \"x < y \\<equiv> Im x = Im y \\<and> Re x < Re y\"\n  definition [simp]: \"x \\<le> y \\<equiv> Im x = Im y \\<and> Re x \\<le> Re y\"\n  \n  instance by (intro_classes, auto simp: complex.expand)\nend\n\ninstantiation real :: conjugatable_ordered_field\nbegin\n  definition [simp]: \"conjugate (x::real) \\<equiv> x\"\n  instance by (intro_classes, auto)\nend\n\ninstantiation rat :: conjugatable_ordered_field\nbegin\n  definition [simp]: \"conjugate (x::rat) \\<equiv> x\"\n  instance by (intro_classes, auto)\nend\n\ninstantiation int :: conjugatable_ordered_ring\nbegin\n  definition [simp]: \"conjugate (x::int) \\<equiv> x\"\n  instance by (intro_classes, auto)\nend\n\nlemma conjugate_square_eq_0 [simp]:\n  fixes x :: \"'a :: {conjugatable_ring,semiring_no_zero_divisors}\"\n  shows \"x * conjugate x = 0 \\<longleftrightarrow> x = 0\" \"conjugate x * x = 0 \\<longleftrightarrow> x = 0\"\n  by auto\n\nlemma conjugate_square_greater_0 [simp]:\n  fixes x :: \"'a :: {conjugatable_ordered_ring,ring_no_zero_divisors}\"\n  shows \"x * conjugate x > 0 \\<longleftrightarrow> x \\<noteq> 0\" \n  using conjugate_square_positive[of x]\n  by (auto simp: le_less)\n\nlemma conjugate_square_smaller_0 [simp]:\n  fixes x :: \"'a :: {conjugatable_ordered_ring,ring_no_zero_divisors}\"\n  shows \"\\<not> x * conjugate x < 0\"\n  using conjugate_square_positive[of x] 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/Jordan_Normal_Form/Conjugate.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8962513675912913, "lm_q2_score": 0.8175744695262777, "lm_q1q2_score": 0.7327522364206509}}
{"text": "(*\n    $Id: ex.thy,v 1.4 2012/01/04 14:12:56 webertj Exp $\n    Author: Farhad Mehta\n*)\n\nheader {* Counting Occurrences *}\n\n(*<*) theory ex 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\n(*<*)consts(*>*)  occurs :: \"'a \\<Rightarrow> 'a list \\<Rightarrow> nat\"\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*}\n\nlemma \"occurs a xs = occurs a (rev xs)\"\n(*<*)oops(*>*)\n\nlemma \"occurs a xs <= length xs\"\n(*<*)oops(*>*)\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]\"}. *}\n\nlemma \"occurs a (map f xs) = occurs (f a) xs\"\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) = e\"\n(*<*)oops(*>*)\n\n\ntext{*\nWith the help of @{term occurs}, define a function @{term remDups}\nthat removes all duplicates from a list.\n*}\n\n(*<*)consts(*>*)  remDups :: \"'a list \\<Rightarrow> 'a list\"\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\nlemma \"occurs x (remDups xs) = e\"\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\n(*<*)consts(*>*)  unique :: \"'a list \\<Rightarrow> bool\"\n\n\ntext{* Show that the result of @{term remDups} is @{term unique}. *}\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/occurs/ex.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8175744673038222, "lm_q2_score": 0.8962513641273354, "lm_q1q2_score": 0.7327522315967302}}
{"text": "(*  \n    Title:      System_Of_Equations.thy\n    Author:     Jose Divas\u00f3n <jose.divasonm at unirioja.es>\n    Author:     Jes\u00fas Aransay <jesus-maria.aransay at unirioja.es>\n*)\n\nheader{*Solving systems of equations using the Gauss Jordan algorithm*}\n\ntheory System_Of_Equations\nimports\n Gauss_Jordan_PA\n Bases_Of_Fundamental_Subspaces\nbegin\n\nsubsection{*Definitions*}\n\ntext{*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\"}.*}\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{*Relationship between @{term \"is_solution_def\"} and @{term \"solve_system_def\"}*}\n\nlemma is_solution_imp_solve_system:\nfixes A::\"'a::{field}^'cols::{mod_type}^'rows::{mod_type}\"\nassumes xAb:\"is_solution x A b\"\nshows \"is_solution x (fst (solve_system A b)) (snd (solve_system A b))\"\nproof -\nhave \"(fst (Gauss_Jordan_PA A)*v(A *v x) = fst (Gauss_Jordan_PA A) *v b)\"\nusing xAb unfolding is_solution_def by fast\nhence \"(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] .\nthus \"is_solution x (fst (solve_system A b)) (snd (solve_system A b))\"\nunfolding is_solution_def solve_system_def Let_def by simp\nqed\n\n\nlemma solve_system_imp_is_solution:\nfixes A::\"'a::{field}^'cols::{mod_type}^'rows::{mod_type}\"\nassumes xAb: \"is_solution x (fst (solve_system A b)) (snd (solve_system A b))\"\nshows \"is_solution x A b\" \nproof -\nhave \"fst (solve_system A b) *v x = snd (solve_system A b)\" \n  using xAb unfolding is_solution_def .\nhence \"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 .\nhence \"(fst (Gauss_Jordan_PA A) ** A) *v x = fst (Gauss_Jordan_PA A) *v b\" \n  unfolding fst_Gauss_Jordan_PA .\nhence \"fst (Gauss_Jordan_PA A) *v (A *v x) = fst (Gauss_Jordan_PA A) *v b\" \n  unfolding matrix_vector_mul_assoc .\nhence \"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\nhence \"(A *v x) = b\"\nunfolding matrix_vector_mul_assoc[of \"matrix_inv (fst (Gauss_Jordan_PA A))\"]\nunfolding matrix_inv_left[OF invertible_fst_Gauss_Jordan_PA]\nunfolding matrix_vector_mul_lid .\nthus ?thesis unfolding is_solution_def .\nqed\n\nlemma is_solution_solve_system:\nfixes A::\"'a::{field}^'cols::{mod_type}^'rows::{mod_type}\"\nshows \"is_solution x A b = is_solution x (fst (solve_system A b)) (snd (solve_system A b))\"\nusing solve_system_imp_is_solution is_solution_imp_solve_system by blast\n\nsubsection{*Consistent and inconsistent systems of equations*}\n\ndefinition consistent :: \"'a::{field}^'cols::{mod_type}^'rows::{mod_type} \\<Rightarrow> 'a::{field}^'rows::{mod_type} \\<Rightarrow> bool\"\nwhere \"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))\"\nunfolding inconsistent_def consistent_def by simp\n\ntext{*The following function will be use to solve consistent systems which are already in the reduced row echelon form.*}\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}\"\nwhere \"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]:\nshows \"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)\"\nunfolding solve_consistent_rref_def by auto\n\n\nlemma rank_ge_imp_is_solution:\nfixes A::\"'a::{field}^'cols::{mod_type}^'rows::{mod_type}\"\nassumes 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)\"\nshows \"is_solution (solve_consistent_rref (Gauss_Jordan A) (P_Gauss_Jordan A *v b)) A b\"\nproof -\nhave \"is_solution (solve_consistent_rref (Gauss_Jordan A) (P_Gauss_Jordan A *v b)) (Gauss_Jordan A) (P_Gauss_Jordan A *v b)\"\nproof (unfold is_solution_def solve_consistent_rref_def, subst matrix_vector_mult_def, vector, auto)\nfix a\nlet ?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)\"\nshow \"setsum ?f UNIV = (P_Gauss_Jordan A *v b) $ a\"\nproof (cases \"A=0\")\ncase True\nhence rank_A_eq_0:\"rank A = 0\" using rank_0 by simp\nhave \"(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\nthus ?thesis unfolding A_0_imp_Gauss_Jordan_0[OF True] by force\nnext\ncase False note A_not_zero=False\ndef not_zero_positions_row_a\\<equiv>\"{j. Gauss_Jordan A $ a $ j \\<noteq> 0}\"\ndef zero_positions_row_a\\<equiv>\"{j. Gauss_Jordan A $ a $ j = 0}\"\nhave 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\nhave 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\nhave setsum_zero: \"(setsum ?f zero_positions_row_a) = 0\" \n  by (unfold zero_positions_row_a_def, rule setsum.neutral, fastforce)\nhave \"setsum ?f (UNIV::'cols set)=setsum ?f (not_zero_positions_row_a \\<union> zero_positions_row_a)\" \n  unfolding UNIV_rw ..\nalso have \"... = setsum ?f (not_zero_positions_row_a) + (setsum ?f zero_positions_row_a)\" \n  by (rule setsum.union_disjoint[OF _ _ disj], simp+)\nalso have \"... = setsum ?f (not_zero_positions_row_a)\" unfolding setsum_zero by simp\nalso 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 setsum_zero': \"setsum ?f (not_zero_positions_row_a - {LEAST j. (Gauss_Jordan A) $ a $ j \\<noteq> 0}) = 0\"\n      by (rule setsum.neutral, auto, metis is_zero_row_def' rref_Gauss_Jordan rref_condition4_explicit zero_neq_one)    \n    have \"setsum ?f (not_zero_positions_row_a) = setsum ?f {LEAST j. (Gauss_Jordan A) $ a $ j \\<noteq> 0} + setsum ?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 setsum.union_disjoint[OF _ _ _], simp+)\n    also have \"... = ?f (LEAST j. (Gauss_Jordan A) $ a $ j \\<noteq> 0)\" using setsum_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 .\nqed\nfinally show \"setsum ?f UNIV = (P_Gauss_Jordan A *v b) $ a\" .\nqed\nqed\nthus ?thesis apply (subst is_solution_solve_system)\nunfolding 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:\nfixes A::\"'a::{field}^'cols::{mod_type}^'rows::{mod_type}\"\nassumes inc: \"inconsistent A b\"\nshows \"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)\nassume \"\\<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)\"\nhence \"(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\nhence \"consistent A b\" using rank_ge_imp_consistent by auto\nthus False using inc unfolding inconsistent_def by contradiction\nqed\n\n\nlemma rank_less_imp_inconsistent:\nfixes A::\"'a::{field}^'cols::{mod_type}^'rows::{mod_type}\"\nassumes 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)\"\nshows \"inconsistent A b\"\nproof (rule ccontr)\ndef i\\<equiv>\"(GREATEST' a. (P_Gauss_Jordan A *v b) $ a \\<noteq> 0)\"\ndef j\\<equiv>\"(GREATEST' a. \\<not> is_zero_row a (Gauss_Jordan A))\"\nassume \"\\<not> inconsistent A b\"\nhence ex_solution: \"\\<exists>x. is_solution x A b\" unfolding inconsistent_def consistent_def by auto\nfrom this obtain x where \"is_solution x A b\"  by auto\nhence 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)\nshow 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    by (metis True exists_not_0 is_solution_def A_0_imp_Gauss_Jordan_0 transpose_vector \n        transpose_zero vector_matrix_zero' is_solution_solve vec_0 vec_component)\n  next\n  case False\nhave j_less_i: \"j<i\"\nproof -\nhave rank_less_greatest_i: \"rank A < to_nat i + 1\"\n  using inc unfolding i_def inconsistent by presburger\nmoreover have rank_eq_greatest_A: \"rank A = to_nat j + 1\" unfolding j_def by (rule rank_eq_suc_to_nat_greatest[OF False])\nultimately have \"to_nat j + 1 < to_nat i + 1\" by simp\nhence \"to_nat j < to_nat i\" by auto\nthus \"j<i\" by (metis (full_types) not_le to_nat_mono')\nqed\nhave is_zero_i: \"is_zero_row i (Gauss_Jordan A)\" by (metis (full_types) j_def j_less_i not_greater_Greatest')\nhave \"(Gauss_Jordan A *v x) $ i = 0\" \n  proof (unfold matrix_vector_mult_def, auto, rule setsum.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\nmoreover 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 Greatest'I_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 .\nqed\nultimately show \"False\" by contradiction\nqed\nqed\n\n\ncorollary consistent_imp_rank_ge:\nfixes A::\"'a::{field}^'cols::{mod_type}^'rows::{mod_type}\"\nassumes \"consistent A b\"\nshows \"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)\"\nusing rank_less_imp_inconsistent by (metis assms inconsistent_def not_less)\n\nlemma inconsistent_eq_rank_less:\nfixes A::\"'a::{field}^'cols::{mod_type}^'rows::{mod_type}\"\nshows \"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))\"\nusing inconsistent_imp_rank_less rank_less_imp_inconsistent by blast\n\nlemma consistent_eq_rank_ge:\nfixes A::\"'a::{field}^'cols::{mod_type}^'rows::{mod_type}\"\nshows \"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))\"\nusing consistent_imp_rank_ge rank_ge_imp_consistent by blast\n\ncorollary consistent_imp_is_solution:\nfixes A::\"'a::{field}^'cols::{mod_type}^'rows::{mod_type}\"\nassumes \"consistent A b\"\nshows \"is_solution (solve_consistent_rref (Gauss_Jordan A) (P_Gauss_Jordan A *v b)) A b\"\nby (rule rank_ge_imp_is_solution[OF assms[unfolded consistent_eq_rank_ge]])\n\n\ncorollary consistent_imp_is_solution':\nfixes A::\"'a::{field}^'cols::{mod_type}^'rows::{mod_type}\"\nassumes \"consistent A b\"\nshows \"is_solution (solve_consistent_rref (fst (solve_system A b)) (snd (solve_system A b))) A b\"\nusing consistent_imp_is_solution[OF assms] unfolding solve_system_def Let_def snd_conv fst_conv\nunfolding Gauss_Jordan_PA_eq P_Gauss_Jordan_def .\n\n\ntext{*Code equations optimized using Lets*}\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{*Solution set of a system of equations. Dependent and independent systems.*}\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_zero 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 comm_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_zero by fast\n\nlemma dim_solution_set_0:\nfixes A::\"'a::{field}^'n::{mod_type}^'rows::{mod_type}\"\nshows \"(vec.dim (solution_set A 0) = 0) = (solution_set A 0 = {0})\"\nproof (auto)\nshow \"vec.dim {0::'a^'n::{mod_type}} = 0\" using vec.dim_zero_eq'[of \"{0::'a^'n::{mod_type}}\"] by fast\nfix x assume dim0: \"vec.dim (solution_set A 0) = 0\" \nshow \"0 \\<in> solution_set A 0\" using zero_is_solution_homogeneous_system .\nassume x: \"x \\<in> solution_set A 0\"\nshow \"x = 0\" \n using independent_and_consistent_imp_uniqueness_solution[OF dim0 consistent_homogeneous] zero_is_solution_homogeneous_system x unfolding solution_set_def by blast\nqed\n\n\ntext{*We have to impose the restriction @{text \"semiring_char_0\"} 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.*}\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\ndef f\\<equiv>\"\\<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 by auto\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:\nfixes A::\"'a::{field}^'n::{mod_type}^'rows::{mod_type}\"\nassumes i: \"infinite (solution_set A 0)\"\nshows \"vec.dim (solution_set A 0) > 0\"\nproof (rule ccontr, simp)\nassume \"vec.dim (solution_set A 0) = 0\"\nhence \"solution_set A 0 = {0}\" using dim_solution_set_0 by auto\nhence \"finite (solution_set A 0)\" by simp\nthus False using i by contradiction\nqed\n\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:\nfixes A::\"'a::{field}^'n::{mod_type}^'rows::{mod_type}\"\nassumes i: \"infinite (solution_set A b)\"\nshows \"consistent A b\"\nproof -\nhave \"(\\<exists>\\<^sub>\\<infinity>x. is_solution x A b)\" using i unfolding solution_set_def INFM_iff_infinite .\nthus ?thesis unfolding consistent_def by (metis (full_types) INFM_MOST_simps(1) INFM_mono)\nqed\n\n\n\n\n\nlemma infinite_solutions_no_homogeneous_imp_dim_solution_set_not_zero_imp:\nfixes A::\"'a::{field}^'n::{mod_type}^'rows::{mod_type}\"\nassumes i: \"infinite (solution_set A b)\"\nshows \"vec.dim (solution_set A 0) > 0\"\nproof (rule ccontr, simp)\nhave \"(\\<exists>\\<^sub>\\<infinity>x. is_solution x A b)\" using i unfolding solution_set_def INFM_iff_infinite .\nfrom this obtain x where x: \"is_solution x A b\" by (metis (full_types) INFM_MOST_simps(1) INFM_mono)\nassume \"vec.dim (solution_set A 0) = 0\"\nhence \"solution_set A 0 = {0}\" using dim_solution_set_0 by auto\nhence \"solution_set A b = {x} + {0}\"  unfolding solution_set_rel[OF x] by simp\nalso have \"... = {x}\" unfolding set_plus_def by force\nfinally show False using i by simp\nqed\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{*Solving systems of linear equations*}\n\ntext{*The following function will solve any system of linear equations. Given a matrix @{text \"A\"} and a vector @{text \"b\"}, \nFirstly it makes use of the funcion @{term \"solve_system\"} to transform the original matrix @{text \"A\"} and the vector @{text \"b\"} \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 @{text \"Some\"} 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 @{text \"None\"}.\n\\end{itemize}\n*}\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]:\nshows \"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))\"\nunfolding Let_def solve_def\nunfolding consistent_eq_rank_ge_code[unfolded Let_def,symmetric]\nunfolding basis_null_space_def Let_def\nunfolding P_Gauss_Jordan_def\nunfolding rank_Gauss_Jordan_code Let_def Gauss_Jordan_PA_eq\nunfolding solve_system_def Let_def fst_conv snd_conv\nunfolding Gauss_Jordan_PA_eq ..\n\nlemma consistent_imp_is_solution_solve:\nfixes A::\"'a::{field}^'cols::{mod_type}^'rows::{mod_type}\"\nassumes con: \"consistent A b\"\nshows \"is_solution (fst (the (solve A b))) A b\"\nunfolding solve_def unfolding if_P[OF con] fst_conv using consistent_imp_is_solution'[OF con] \nby simp\n\ncorollary consistent_eq_solution_solve:\nfixes A::\"'a::{field}^'cols::{mod_type}^'rows::{mod_type}\"\nshows \"consistent A b = is_solution (fst (the (solve A b))) A b\"\nby (metis consistent_def consistent_imp_is_solution_solve)\n\nlemma inconsistent_imp_solve_eq_none:\nfixes A::\"'a::{field}^'cols::{mod_type}^'rows::{mod_type}\"\nassumes con: \"inconsistent A b\"\nshows \"solve A b = None\" unfolding solve_def unfolding if_not_P[OF con[unfolded inconsistent_def]] ..\n\ncorollary inconsistent_eq_solve_eq_none:\nfixes A::\"'a::{field}^'cols::{mod_type}^'rows::{mod_type}\"\nshows \"inconsistent A b = (solve A b = None)\"\nunfolding solve_def unfolding inconsistent_def by force\n\ntext{*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\"}*}\n\nlemma solution_set_rel_solve:\nfixes A::\"'a::{field}^'cols::{mod_type}^'rows::{mod_type}\"\nassumes con: \"consistent A b\"\nshows \"solution_set A b = {fst (the (solve A b))} + vec.span (snd (the (solve A b)))\"\nproof -\nhave s: \"is_solution (fst (the (solve A b))) A b\" using consistent_imp_is_solution_solve[OF con] by simp\nhave \"solution_set A b = {fst (the (solve A b))} + solution_set A 0\" using solution_set_rel[OF s] .\nalso 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 (auto)\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\nfinally 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:\nfixes A::\"'a::{field}^'cols::{mod_type}^'rows::{mod_type}\"\nassumes con: \"consistent A b\"\nshows \"(is_solution x A b) = (x \\<in> {fst (the (solve A b))} + vec.span (snd (the (solve A b))))\"\nusing solution_set_rel_solve[OF con] unfolding solution_set_def 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/Gauss_Jordan/System_Of_Equations.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8887587964389112, "lm_q2_score": 0.8244619242200082, "lm_q1q2_score": 0.7327477874794833}}
{"text": "(*  Title:      Fun With Functions\n    Author:     Tobias Nipkow\n*)\n\ntheory FunWithFunctions imports Complex_Main begin\n\ntext\\<open>See \\<^cite>\\<open>\"Tao2006\"\\<close>. Was first brought to our attention by Herbert\nEhler who provided a similar proof.\\<close>\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 \\<open>n \\<le> f(n)\\<close> show \"f n = n\" by arith\nqed\n\n\ntext\\<open>See \\<^cite>\\<open>\"Tao2006\"\\<close>. Possible extension:\nShould also hold if the range of \\<open>f\\<close> is the reals!\n\\<close>\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 \\<open>k \\<ge> 2\\<close> by arith\n    hence \"f(2) \\<le> 2\"\n      using mono_nat_linear_lb[of f 2 \"k - 2\",OF f_mono] \\<open>f k = k\\<close>\n      by simp\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 \"\\<exists>k. i=2*k\" by arith\n        then obtain k where \"i = 2*k\" ..\n        hence \"0 < k\" and \"k<i\" using \\<open>~i\\<le>1\\<close> by arith+\n        hence \"f(k) = k\" using less(1) by blast\n        thus \"f(i) = i\" using \\<open>i = 2*k\\<close> by(simp add:f_times 2)\n      next\n        assume \"i mod 2 \\<noteq> 0\"\n        hence \"\\<exists>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 \\<open>~i\\<le>1\\<close> by arith+\n        have \"2*k < f(2*k+1)\"\n        proof -\n          have \"2*k = 2*f(k)\" using less(1) \\<open>i=2*k+1\\<close> 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) \\<open>i=2*k+1\\<close> \\<open>~i\\<le>1\\<close> by simp\n          finally show ?thesis .\n        qed\n        ultimately show \"f(i) = i\" using \\<open>i = 2*k+1\\<close> by arith\n      qed\n    qed\n  qed\nqed\n\n\ntext\\<open>One more from Tao's booklet. If \\<open>f\\<close> is also assumed to be\ncontinuous, @{term\"f(x::real) = x+1\"} holds for all reals, not only\nrationals. Extend the proof!\\<close>\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 have \"f(of_int i) = of_int 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(of_int (i+1)) = f(of_int i + 0 + 1)\" by simp\n      also have \"\\<dots> = f(of_int i) + f 0\" by(rule f_add)\n      also have \"\\<dots> = of_int (i+1) + 1\" using step1 0 by simp\n      finally show ?case .\n    next\n      case (step2 i)\n      have \"f(of_int i) = f(of_int (i - 1) + 0 + 1)\" by simp\n      also have \"\\<dots> = f(of_int (i - 1)) + f 0\" by(rule f_add)\n      also have \"\\<dots> = f(of_int (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(of_int (Suc n)*r + of_int n) = of_int (Suc n) * f r\"\n    proof(induct n)\n      case 0 show ?case by simp\n    next\n      case (Suc n)\n      have \"of_int (Suc(Suc n))*r + of_int (Suc n) =\n            r + (of_int (Suc n)*r + of_int n) + 1\" (is \"?a = ?b\")\n        by(simp add: field_simps)\n      hence \"f ?a = f ?b\"\n        by presburger\n      also have \"\\<dots> = f r + f(of_int (Suc n)*r + of_int n)\" by(rule f_add)\n      also have \"\\<dots> = f r + of_int (Suc n) * f r\" by(simp only:Suc)\n      finally show ?case by(simp add: field_simps)\n    qed }\n  note 1 = this\n  { fix n::nat and r assume \"n\\<noteq>0\"\n    have \"f(of_int (n)*r + of_int (n - 1)) = of_int (n) * f r\"\n    proof(cases n)\n      case 0 thus ?thesis using \\<open>n\\<noteq>0\\<close> by simp\n    next\n      case Suc thus ?thesis using \\<open>n\\<noteq>0\\<close> using \"1\" by auto\n    qed }\n  note f_mult = this\n  from \\<open>r:\\<rat>\\<close> obtain i::int and n::nat where r: \"r = of_int i/of_int n\" and \"n\\<noteq>0\"\n    by(fastforce simp:Rats_eq_int_div_nat)\n  have \"of_int (n) * f(of_int i / of_int n) = f(of_int i + of_int (n - 1))\"\n    using \\<open>n\\<noteq>0\\<close>\n    by (metis (no_types, opaque_lifting) f_mult mult.commute nonzero_divide_eq_eq of_int_of_nat_eq of_nat_0_eq_iff) \n  also have \"\\<dots> = f(of_int (i + int n - 1))\" using \\<open>n\\<noteq>0\\<close>[simplified]\n    by (metis One_nat_def Suc_leI of_nat_1 add_diff_eq of_int_add of_nat_diff)\n  also have \"\\<dots> = of_int (i + int n - 1) + 1\" by(rule f_int)\n  also have \"\\<dots> = of_int i + of_int n\" by arith\n  finally show ?thesis using \\<open>n\\<noteq>0\\<close> unfolding r by (simp add:field_simps)\nqed\n\n\ntext\\<open>The only total model of a naive recursion equation of factorial on\nintegers is 0 for all negative arguments. Probably folklore.\\<close>\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 \\<open>j\\<le>i\\<close>])\n       apply(rule \\<open>ifac i \\<noteq> 0\\<close>)\n      apply (metis \\<open>i<0\\<close> 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 \\<open>j<i\\<close> \\<open>i<0\\<close> by arith\n    have \"ifac(j - 1) \\<noteq> 0\" using \\<open>j<i\\<close> by(simp add: below0)\n    then have \"\\<bar>ifac (j - 1)\\<bar> < (-j) * \\<bar>ifac (j - 1)\\<bar>\" using \\<open>j<i\\<close>\n      mult_le_less_imp_less[OF order_refl[of \"abs(ifac(j - 1))\"] \\<open>1 < -j\\<close>]\n      by(simp add:mult.commute)\n    hence \"abs(ifac(j - 1)) < abs(ifac j)\"\n      using \\<open>1 < -j\\<close> 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": "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/FunWithFunctions/FunWithFunctions.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245994514084, "lm_q2_score": 0.8791467738423873, "lm_q1q2_score": 0.7326146331712052}}
{"text": "(*\n  File:    Linear_Homogenous_Recurrences.thy\n  Author:  Manuel Eberl, TU M\u00fcnchen\n*)\nsection \\<open>Homogenous linear recurrences\\<close>\ntheory Linear_Homogenous_Recurrences\nimports \n  Complex_Main\n  RatFPS\n  Rational_FPS_Solver\n  Linear_Recurrences_Common\nbegin\n\ntext \\<open>\n  The following is the numerator of the rational generating function of a \n  linear homogenous recurrence.\n\\<close>\ndefinition lhr_fps_numerator where\n  \"lhr_fps_numerator m cs f = (let N = length cs - 1 in \n      Poly [(\\<Sum>i\\<le>min N k. cs ! (N - i) * f (k - i)). k \\<leftarrow> [0..<N+m]])\"\n      \nlemma lhr_fps_numerator_code [code abstract]:\n  \"coeffs (lhr_fps_numerator m cs f) = (let N = length cs - 1 in \n     strip_while ((=) 0) [(\\<Sum>i\\<le>min N k. cs ! (N - i) * f (k - i)). k \\<leftarrow> [0..<N+m]])\"\n  by (simp add: lhr_fps_numerator_def Let_def)\n \nlemma lhr_fps_aux:\n  fixes f :: \"nat \\<Rightarrow> 'a :: field\"\n  assumes \"\\<And>n. n \\<ge> m \\<Longrightarrow> (\\<Sum>k\\<le>N. c k * f (n + k)) = 0\"\n  assumes cN: \"c N \\<noteq> 0\"\n  defines \"p \\<equiv> Poly [c (N - k). k \\<leftarrow> [0..<Suc N]]\"\n  defines \"q \\<equiv> Poly [(\\<Sum>i\\<le>min N k. c (N - i) * f (k - i)). k \\<leftarrow> [0..<N+m]]\"\n  shows   \"Abs_fps f = fps_of_poly q / fps_of_poly p\"\nproof -\n  include fps_notation\n  define F where \"F = Abs_fps f\"\n  have [simp]: \"F $ n = f n\" for n by (simp add: F_def)\n  have [simp]: \"coeff p 0 = c N\" \n    by (simp add: p_def nth_default_def del: upt_Suc)\n  \n  have \"(fps_of_poly p * F) $ n = coeff q n\" for n\n  proof (cases \"n \\<ge> N + m\")\n    case True\n    let ?f = \"\\<lambda>i. N - i\"\n    have \"(fps_of_poly p * F) $ n = (\\<Sum>i\\<le>n. coeff p i * f (n - i))\"\n      by (simp add: fps_mult_nth atLeast0AtMost)\n    also from True have \"\\<dots> = (\\<Sum>i\\<le>N. coeff p i * f (n - i))\"\n      by (intro sum.mono_neutral_right) (auto simp: nth_default_def p_def)\n    also have \"\\<dots> = (\\<Sum>i\\<le>N. c (N - i) * f (n - i))\" \n      by (intro sum.cong) (auto simp: nth_default_def p_def simp del: upt_Suc)\n    also from True have \"\\<dots> = (\\<Sum>i\\<le>N. c i * f (n - N + i))\"\n      by (intro sum.reindex_bij_witness[of _ ?f ?f]) auto\n    also from True have \"\\<dots> = 0\" by (intro assms) simp_all\n    also from True have \"\\<dots> = coeff q n\" \n      by (simp add: q_def nth_default_def del: upt_Suc)\n    finally show ?thesis .\n  next\n    case False\n    hence \"(fps_of_poly p * F) $ n = (\\<Sum>i\\<le>n. coeff p i * f (n - i))\"\n      by (simp add: fps_mult_nth atLeast0AtMost)\n    also have \"\\<dots> = (\\<Sum>i\\<le>min N n. coeff p i * f (n - i))\"\n      by (intro sum.mono_neutral_right)\n         (auto simp: p_def nth_default_def simp del: upt_Suc)\n    also have \"\\<dots> = (\\<Sum>i\\<le>min N n. c (N - i) * f (n - i))\"\n      by (intro sum.cong) (simp_all add: p_def nth_default_def del: upt_Suc)\n    also from False have \"\\<dots> = coeff q n\" by (simp add: q_def nth_default_def)\n    finally show ?thesis .\n  qed\n  hence \"fps_of_poly p * F = fps_of_poly q\" \n    by (intro fps_ext) simp\n  with cN show \"F = fps_of_poly q / fps_of_poly p\"\n    by (subst unit_eq_div2) (simp_all add: mult_ac)\nqed\n\nlemma lhr_fps:\n  fixes f :: \"nat \\<Rightarrow> 'a :: field\" and cs :: \"'a list\"\n  defines \"N \\<equiv> length cs - 1\"\n  assumes cs: \"cs \\<noteq> []\"\n  assumes \"\\<And>n. n \\<ge> m \\<Longrightarrow> (\\<Sum>k\\<le>N. cs ! k * f (n + k)) = 0\"\n  assumes cN: \"last cs \\<noteq> 0\"\n  shows   \"Abs_fps f = fps_of_poly (lhr_fps_numerator m cs f) / \n              fps_of_poly (lr_fps_denominator cs)\"\nproof -\n  define p and q \n    where \"p = Poly (map (\\<lambda>k. \\<Sum>i\\<le>min N k. cs ! (N - i) * f (k - i)) [0..<N + m])\"\n      and \"q = Poly (map (\\<lambda>k. cs ! (N - k)) [0..<Suc N])\"\n\n  from assms have \"Abs_fps f = fps_of_poly p / fps_of_poly q\" unfolding p_def q_def\n    by (intro lhr_fps_aux) (simp_all add: last_conv_nth)\n  also have \"p = lhr_fps_numerator m cs f\"\n    unfolding p_def lhr_fps_numerator_def by (auto simp: Let_def N_def)\n  also from cN have \"q = lr_fps_denominator cs\"\n    unfolding q_def lr_fps_denominator_def\n    by (intro poly_eqI)\n       (auto simp add: nth_default_def rev_nth N_def not_less cs simp del: upt_Suc)\n  finally show ?thesis .\nqed\n\n(* TODO: Do I even need this? *)\nfun lhr where\n  \"lhr cs fs n =\n     (if (cs :: 'a :: field list) = [] \\<or> last cs = 0 \\<or> length fs < length cs - 1 then undefined else\n     (if n < length fs then fs ! n else \n          (\\<Sum>k<length cs - 1. cs ! k * lhr cs fs (n + 1 - length cs + k)) / -last cs))\"\n\ndeclare lhr.simps [simp del]\n\nlemma lhr_rec: \n  assumes \"cs \\<noteq> []\" \"last cs \\<noteq> 0\" \"length fs \\<ge> length cs - 1\" \"n \\<ge> length fs\"\n  shows   \"(\\<Sum>k<length cs. cs ! k * lhr cs fs (n + 1 - length cs + k)) = 0\"\nproof -\n  from assms have \"{..<length cs} = insert (length cs - 1) {..<length cs - 1}\" by auto\n  also have \"(\\<Sum>k\\<in>\\<dots> . cs ! k * lhr cs fs (n + 1 - length cs + k)) =\n               (\\<Sum>k<length cs - 1. cs ! k * lhr cs fs (n + 1 - length cs + k)) + \n                    last cs * lhr cs fs n\" using assms\n    by (cases cs) (simp_all add: algebra_simps last_conv_nth)\n  also from assms have \"\\<dots> = 0\" by (subst (2) lhr.simps) (simp_all add: field_simps)\n  finally show ?thesis .\nqed\n\nlemma lhrI:\n  assumes \"cs \\<noteq> []\" \"last cs \\<noteq> 0\" \"length fs \\<ge> length cs - 1\"\n  assumes \"\\<And>n. n < length fs \\<Longrightarrow> f n = fs ! n\"\n  assumes \"\\<And>n. n \\<ge> length fs \\<Longrightarrow> (\\<Sum>k<length cs. cs ! k * f (n + 1 - length cs + k)) = 0\"\n  shows   \"f n = lhr cs fs n\"\nusing assms\nproof (induction cs fs n rule: lhr.induct)\n  case (1 cs fs n)\n  show ?case\n  proof (cases \"n < length fs\")\n    case False\n    with 1 have \"0 = (\\<Sum>k<length cs. cs ! k * f (n + 1 - length cs + k))\" by simp\n    also from 1 have \"{..<length cs} = insert (length cs - 1) {..<length cs - 1}\" by auto\n    also have \"(\\<Sum>k\\<in>\\<dots> . cs ! k * f (n + 1 - length cs + k)) =\n                 (\\<Sum>k<length cs - 1. cs ! k * f (n + 1 - length cs + k)) + \n                      last cs * f n\" using 1 False\n      by (cases cs) (simp_all add: algebra_simps last_conv_nth)\n    also have \"(\\<Sum>k<length cs - 1. cs ! k * f (n + 1 - length cs + k)) =\n                   (\\<Sum>k<length cs - 1. cs ! k * lhr cs fs (n + 1 - length cs + k))\"\n      using False 1 by (intro sum.cong refl) simp\n    finally have \"f n = (\\<Sum>k<length cs - 1. cs ! k * lhr cs fs (n + 1 - length cs + k)) / -last cs\"\n      using \\<open>last cs \\<noteq> 0\\<close> by (simp add: field_simps eq_neg_iff_add_eq_0)\n  also from 1(2-4) False have \"\\<dots> = lhr cs fs n\" by (subst lhr.simps) simp\n    finally show ?thesis .\n  qed (insert 1(2-5), simp add: lhr.simps)\nqed\n(* END TODO *)\n\nlocale linear_homogenous_recurrence =\n  fixes f :: \"nat \\<Rightarrow> 'a :: comm_semiring_0\" and cs fs :: \"'a list\"\n  assumes base: \"n < length fs \\<Longrightarrow> f n = fs ! n\"\n  assumes cs_not_null [simp]: \"cs \\<noteq> []\" and last_cs [simp]: \"last cs \\<noteq> 0\"\n      and hd_cs [simp]: \"hd cs \\<noteq> 0\" and enough_base: \"length fs + 1 \\<ge> length cs\"\n  assumes rec:  \"n \\<ge> length fs - length cs \\<Longrightarrow> (\\<Sum>k<length cs. cs ! k * f (n + k)) = 0\"\nbegin\n\nlemma lhr_fps_numerator_altdef:\n  \"lhr_fps_numerator (length fs + 1 - length cs) cs f =\n     lhr_fps_numerator (length fs + 1 - length cs) cs ((!) fs)\"\nproof -\n  define N where \"N = length cs - 1\"\n  define m where \"m = length fs + 1 - length cs\"\n  have \"lhr_fps_numerator m cs f = \n          Poly (map (\\<lambda>k. (\\<Sum>i\\<le>min N k. cs ! (N - i) * f (k - i))) [0..<N + m])\"\n    by (simp add: lhr_fps_numerator_def Let_def N_def)\n  also from enough_base have \"N + m = length fs\"\n    by (cases cs) (simp_all add: N_def m_def algebra_simps)\n  also {\n    fix k assume k: \"k \\<in> {0..<length fs}\"\n    hence \"f (k - i) = fs ! (k - i)\" if \"i \\<le> min N k\" for i \n      using enough_base that by (intro base) (auto simp: Suc_le_eq N_def m_def algebra_simps)\n    hence \"(\\<Sum>i\\<le>min N k. cs ! (N - i) * f (k - i)) = (\\<Sum>i\\<le>min N k. cs ! (N - i) * fs ! (k - i))\"\n      by simp\n  }\n  hence \"map (\\<lambda>k. (\\<Sum>i\\<le>min N k. cs ! (N - i) * f (k - i))) [0..<length fs] =\n           map (\\<lambda>k. (\\<Sum>i\\<le>min N k. cs ! (N - i) * fs ! (k - i))) [0..<length fs]\"\n    by (intro map_cong) simp_all\n  also have \"Poly \\<dots> = lhr_fps_numerator m cs ((!) fs)\" using enough_base\n    by (cases cs) (simp_all add: lhr_fps_numerator_def Let_def m_def N_def)\n  finally show ?thesis unfolding m_def .\nqed\n\nend\n\n(* TODO Duplication *)\nlemma solve_lhr_aux:\n  assumes \"linear_homogenous_recurrence f cs fs\"\n  assumes \"is_factorization_of fctrs (lr_fps_denominator' cs)\"\n  shows   \"f = interp_ratfps_solution (solve_factored_ratfps' (lhr_fps_numerator \n                  (length fs + 1 - length cs) cs ((!) fs)) fctrs)\"\nproof -\n  interpret linear_homogenous_recurrence f cs fs by fact\n\n  note assms(2)\n  hence \"is_alt_factorization_of fctrs (reflect_poly (lr_fps_denominator' cs))\"\n    by (intro reflect_factorization) \n       (simp_all add: lr_fps_denominator'_def\n                      nth_default_def hd_conv_nth [symmetric])\n  also have \"reflect_poly (lr_fps_denominator' cs) = lr_fps_denominator cs\"\n    unfolding lr_fps_denominator_def lr_fps_denominator'_def\n    by (subst coeffs_eq_iff) (simp add: coeffs_reflect_poly strip_while_rev [symmetric]\n                                 no_trailing_unfold last_rev del: strip_while_rev)\n  finally have factorization: \"is_alt_factorization_of fctrs (lr_fps_denominator cs)\" .\n\n  define m where \"m = length fs + 1 - length cs\"\n  obtain a ds where fctrs: \"fctrs = (a, ds)\" by (cases fctrs) simp_all\n  define p and p' where \"p = lhr_fps_numerator m cs ((!) fs)\" and \"p' = smult (inverse a) p\"\n  obtain b es where sol: \"solve_factored_ratfps' p fctrs = (b, es)\" \n    by (cases \"solve_factored_ratfps' p fctrs\") simp_all\n  have sol': \"(b, es) = solve_factored_ratfps p' ds\"\n    by (subst sol [symmetric]) (simp add: fctrs p'_def solve_factored_ratfps_def \n                                          solve_factored_ratfps'_def case_prod_unfold)\n  have factorization': \"lr_fps_denominator cs = interp_alt_factorization fctrs\"\n    using factorization by (simp add: is_alt_factorization_of_def)\n  from assms(2) have distinct: \"distinct (map fst ds)\"\n    by (simp add: fctrs is_factorization_of_def)\n  have coeff_0_denom: \"coeff (lr_fps_denominator cs) 0 \\<noteq> 0\" \n    by (simp add: lr_fps_denominator_def nth_default_def \n                  hd_conv_nth [symmetric] hd_rev)\n  have \"coeff (lr_fps_denominator' cs) 0 \\<noteq> 0\"\n    by (simp add: lr_fps_denominator'_def nth_default_def hd_conv_nth [symmetric])\n  with assms(2) have no_zero: \"0 \\<notin> fst ` set ds\" by (simp add: zero_in_factorization_iff fctrs)\n    \n  from assms(2) have a_nz [simp]: \"a \\<noteq> 0\"\n    by (auto simp: fctrs interp_factorization_def is_factorization_of_def lr_fps_denominator'_nz)\n  hence unit1: \"is_unit (fps_const a)\" by simp\n  moreover have \"is_unit (fps_of_poly (interp_alt_factorization fctrs))\"\n    by (simp add: coeff_0_denom factorization' [symmetric])\n  ultimately have unit2: \"is_unit (fps_of_poly (\\<Prod>p\\<leftarrow>ds. [:1, - fst p:] ^ Suc (snd p)))\"\n    by (simp add: fctrs case_prod_unfold interp_alt_factorization_def del: power_Suc)\n  \n  have \"Abs_fps f = fps_of_poly (lhr_fps_numerator m cs f) /\n                        fps_of_poly (lr_fps_denominator cs)\"\n  proof (intro lhr_fps)\n    fix n assume n: \"n \\<ge> m\"\n    have \"{..length cs - 1} = {..<length cs}\" by (cases cs) auto\n    also from n have \"(\\<Sum>k\\<in>\\<dots> . cs ! k * f (n + k)) = 0\"\n      by (intro rec) (simp_all add: m_def algebra_simps)\n    finally show \"(\\<Sum>k\\<le>length cs - 1. cs ! k * f (n + k)) = 0\" .\n  qed (simp_all add: m_def)\n  also have \"lhr_fps_numerator m cs f = lhr_fps_numerator m cs ((!) fs)\"\n    unfolding lhr_fps_numerator_def using enough_base\n    by (auto simp: Let_def poly_eq_iff nth_default_def base \n                   m_def Suc_le_eq intro!: sum.cong)\n  also have \"fps_of_poly \\<dots> / fps_of_poly (lr_fps_denominator cs) = \n               fps_of_poly (lhr_fps_numerator m cs ((!) fs)) / \n                 (fps_const (fst fctrs) * \n                   fps_of_poly (\\<Prod>p\\<leftarrow>snd fctrs. [:1, - fst p:] ^ Suc (snd p)))\"\n    unfolding assms factorization' interp_alt_factorization_def\n    by (simp add: case_prod_unfold Let_def fps_of_poly_smult)\n  also from unit1 unit2 have \"\\<dots> = fps_of_poly p / fps_const a / \n                                     fps_of_poly (\\<Prod>(c,n)\\<leftarrow>ds. [:1, -c:]^Suc n)\"\n    by (subst is_unit_div_mult2_eq) (simp_all add: fctrs case_prod_unfold p_def)\n  also from unit1 have \"fps_of_poly p / fps_const a = fps_of_poly p'\"\n    by (simp add: fps_divide_unit fps_of_poly_smult fps_const_inverse p'_def)\n  also from distinct no_zero have \"\\<dots> / fps_of_poly (\\<Prod>(c,n)\\<leftarrow>ds. [:1, -c:]^Suc n) = \n      Abs_fps (interp_ratfps_solution (solve_factored_ratfps' p fctrs))\"\n    by (subst solve_factored_ratfps) (simp_all add: case_prod_unfold sol' sol)\n  finally show ?thesis unfolding p_def m_def\n    by (intro ext) (simp add: fps_eq_iff)\nqed\n\ndefinition\n  \"lhr_fps as fs = (\n     let m = length fs + 1 - length as;\n         p = lhr_fps_numerator m as (\\<lambda>n. fs ! n);\n         q = lr_fps_denominator as\n     in  ratfps_of_poly p / ratfps_of_poly q)\"\n\nlemma lhr_fps_correct:\n  fixes   f :: \"nat \\<Rightarrow> 'a :: {field_char_0,field_gcd}\"\n  assumes \"linear_homogenous_recurrence f cs fs\"\n  shows   \"fps_of_ratfps (lhr_fps cs fs) = Abs_fps f\"\nproof -\n  interpret linear_homogenous_recurrence f cs fs by fact\n  define m where \"m = length fs + 1 - length cs\"\n  let ?num = \"lhr_fps_numerator m cs f\"\n  let ?num' = \"lhr_fps_numerator m cs ((!) fs)\"\n  let ?denom = \"lr_fps_denominator cs\"\n \n  have \"{..length cs - 1} = {..<length cs}\" by (cases cs) auto\n  moreover have \"length cs \\<ge> 1\" by (cases cs) auto\n  ultimately have \"Abs_fps f = fps_of_poly ?num / fps_of_poly ?denom\"\n    by (intro lhr_fps) (insert rec, simp_all add: m_def)\n  also have \"?num = ?num'\"\n    by (rule lhr_fps_numerator_altdef [folded m_def])\n  also have \"fps_of_poly ?num' / fps_of_poly ?denom = \n                fps_of_ratfps (ratfps_of_poly ?num' / ratfps_of_poly ?denom)\"\n    by simp\n  also from enough_base have \"\\<dots> = fps_of_ratfps (lhr_fps cs fs)\"\n    by (cases cs)  (simp_all add: base fps_of_ratfps_def case_prod_unfold lhr_fps_def m_def)\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/Linear_Recurrences/Linear_Homogenous_Recurrences.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8791467643431001, "lm_q2_score": 0.8333246015211008, "lm_q1q2_score": 0.732614627074779}}
{"text": "\nsection \\<open>Quantales\\<close>\n\ntheory Quantale_iso\n  imports Main\n  \"HOL-Library.Lattice_Syntax\"\n\nbegin\n\nnotation times (infixl \"\\<cdot>\" 70)\n\nclass quantale = complete_lattice + monoid_mult + \n  assumes Sup_distl: \"x \\<cdot> \\<Squnion>Y = (\\<Squnion>y \\<in> Y. x \\<cdot> y)\" \n  assumes Sup_distr: \"\\<Squnion>X \\<cdot> y = (\\<Squnion>x \\<in> X. x \\<cdot> y)\"\n\n\nsubsection \\<open>Relational Model of Kleene algebra\\<close>\n\nnotation relcomp (infixl \";\" 70)\n\ninterpretation rel_quantale: quantale Inf Sup inf \"(\\<subseteq>)\" \"(\\<subset>)\" sup \"{}\" \"UNIV\" Id \"(;)\"\n  by (unfold_locales, auto) \n\nsubsection \\<open>State Transformer Model of Kleene Algebra\\<close>\n\ntype_synonym 'a sta = \"'a \\<Rightarrow> 'a set\"\n\ndefinition eta :: \"'a sta\" (\"\\<eta>\") where\n  \"\\<eta> x = {x}\"\n\ndefinition nsta :: \"'a sta\" (\"\\<nu>\") where \n  \"\\<nu> x = {}\" \n\ndefinition tsta :: \"'a sta\" (\"\\<tau>\") where \n  \"\\<tau> x = UNIV\" \n\ndefinition kcomp :: \"'a sta \\<Rightarrow> 'a sta \\<Rightarrow> 'a sta\" (infixl \"\\<circ>\\<^sub>K\" 75) where\n  \"(f \\<circ>\\<^sub>K g) x = \\<Union>{g y |y. y \\<in> f x}\"\n\ndefinition kSup :: \"'a sta set \\<Rightarrow> 'a sta\" where\n  \"(kSup F) x = \\<Union>{f x |f. f \\<in> F}\" \n\ndefinition kInf :: \"'a sta set \\<Rightarrow> 'a sta\" where\n  \"(kInf F) x = \\<Inter>{f x |f. f \\<in> F}\" \n\ndefinition ksup :: \"'a sta \\<Rightarrow> 'a sta \\<Rightarrow> 'a sta\" where\n  \"(ksup f g) x = f x \\<union> g x\" \n\ndefinition kinf :: \"'a sta \\<Rightarrow> 'a sta \\<Rightarrow> 'a sta\" where\n  \"(kinf f g) x = f x \\<inter> g x\" \n\ndefinition kleq :: \"'a sta \\<Rightarrow> 'a sta \\<Rightarrow> bool\" (infix \"\\<sqsubseteq>\" 50) where\n  \"f \\<sqsubseteq> g = (\\<forall>x. f x \\<subseteq> g x)\"\n\ndefinition kle :: \"'a sta \\<Rightarrow> 'a sta \\<Rightarrow> bool\" (infix \"\\<sqsubset>\" 50) where\n  \"f \\<sqsubset> g = (f \\<sqsubseteq> g \\<and> f \\<noteq> g)\"\n\nsubsection \\<open>Bijections between the relations and state transformers\\<close>\n\ndefinition r2s :: \"'a rel \\<Rightarrow> 'a sta\" (\"\\<S>\") where\n  \"\\<S> R = Image R \\<circ> \\<eta>\" \n\ndefinition s2r :: \"'a sta \\<Rightarrow> 'a rel\" (\"\\<R>\") where\n  \"\\<R> f = {(x,y). y \\<in> f x}\"\n\nlemma r2s2r_galois: \"(\\<R> f = R) = (\\<S> R = f)\"\n  by (force simp: s2r_def eta_def r2s_def)\n\nlemma r2s_bij: \"bij \\<S>\"\n  by (metis bij_def inj_def r2s2r_galois surj_def)\n\nlemma s2r_bij: \"bij \\<R>\"\n  by (metis bij_def inj_def r2s2r_galois surj_def)\n\nsubsection \\<open>Type definition and lifting for bijections\\<close>\n\nlemma type_definition_s2r_r2s: \"type_definition \\<R> \\<S> UNIV\"\n  unfolding type_definition_def by (meson iso_tuple_UNIV_I r2s2r_galois)\n\ndefinition \"rel_s2r R f = (R = \\<R> f)\"\n\nlemma bi_unique_rel_s2r [transfer_rule]: \"bi_unique rel_s2r\"\n  by (metis rel_s2r_def type_definition_s2r_r2s typedef_bi_unique)\n\nlemma bi_total_rel_s2r [transfer_rule]: \"bi_total rel_s2r\"\n  by (metis bi_total_def r2s2r_galois rel_s2r_def)\n\n\nsubsection \\<open>Transfer functions\\<close>\n\nlemma r2s_id: \"\\<R> \\<eta> = Id\"\n  unfolding s2r_def Id_def eta_def by force\n\nlemma Id_eta_transfer [transfer_rule]: \"rel_s2r Id \\<eta>\"\n  unfolding rel_s2r_def\n  by (simp add: r2s_id rel_s2r_def)\n\nlemma r2s_zero: \"\\<R> \\<nu> = {}\"\n  by (simp add: s2r_def nsta_def)\n\nlemma emp_nsta_transfer [transfer_rule]: \"rel_s2r {} \\<nu>\"\n  by (simp add: r2s_zero rel_s2r_def)\n\nlemma r2s_tau: \"\\<R> \\<tau> = UNIV\"\n  unfolding s2r_def tsta_def by simp\n\nlemma UNIV_tsta_transfer [transfer_rule]: \"rel_s2r UNIV \\<tau>\"\n  by (simp add: r2s_tau rel_s2r_def)\n\nlemma r2s_comp: \"\\<R> (f \\<circ>\\<^sub>K g) = \\<R> f ; \\<R> g\"\n  unfolding s2r_def kcomp_def by force\n\nlemma relcomp_kcomp_transfer [transfer_rule]: \"rel_fun rel_s2r (rel_fun rel_s2r rel_s2r) (;) (\\<circ>\\<^sub>K)\"\n  by (metis r2s_comp rel_funI rel_s2r_def)\n\nlemma s2r_kSup: \"\\<R> (kSup F) = \\<Union>(image \\<R> F)\"\n  unfolding s2r_def kSup_def by force\n\nlemma Un_kSup_transfer [transfer_rule]: \"rel_fun (rel_set rel_s2r) rel_s2r Union kSup\"\n  unfolding rel_s2r_def rel_fun_def rel_set_def s2r_kSup by fastforce\n\nlemma s2r_kInf: \"\\<R> (kInf F) = \\<Inter>(image \\<R> F)\"\n  unfolding s2r_def kInf_def by force\n\nlemma Un_kInf_transfer [transfer_rule]: \"rel_fun (rel_set rel_s2r) rel_s2r Inter kInf\"\n  unfolding rel_s2r_def rel_fun_def rel_set_def s2r_kInf by fastforce\n\nlemma s2r_ksup: \"\\<R> (ksup f g) = \\<R> f \\<union> \\<R> g\"\n  unfolding s2r_def ksup_def by force\n\nlemma un_ksup_transfer [transfer_rule]: \"rel_fun rel_s2r (rel_fun rel_s2r rel_s2r) (\\<union>) (ksup)\"\n  by (metis rel_funI rel_s2r_def s2r_ksup)\n\nlemma s2r_kinf: \"\\<R> (kinf f g) = \\<R> f \\<inter> \\<R> g\"\n  unfolding s2r_def kinf_def by force\n\nlemma in_kinf_transfer [transfer_rule]: \"rel_fun rel_s2r (rel_fun rel_s2r rel_s2r) (\\<inter>) (kinf)\"\n  by (metis rel_funI rel_s2r_def s2r_kinf)\n\nlemma leq_kleq_transfer [transfer_rule]: \"rel_fun rel_s2r (rel_fun rel_s2r (=)) (\\<subseteq>) (\\<sqsubseteq>)\"\n  unfolding kleq_def s2r_def rel_s2r_def by force\n\nlemma le_kle_transfer [transfer_rule]: \"rel_fun rel_s2r (rel_fun rel_s2r (=)) (\\<subset>) (\\<sqsubset>)\"\n  unfolding kle_def kleq_def s2r_def rel_s2r_def by blast\n\n\ntext \\<open>State transformer model of Kleene algebra\\<close>\n\ninterpretation sta_quantale: quantale kInf kSup kinf \"(\\<sqsubseteq>)\" \"(\\<sqsubset>)\" ksup \"\\<nu>\" tsta \"\\<eta>\" \"(\\<circ>\\<^sub>K)\"\n  by unfold_locales (transfer, force)+\n \nend\n\n\n\n\n\n", "meta": {"author": "BraeWebb", "repo": "stackoverflow", "sha": "a043b47f0f5ed97f73f55af74c6f63ffbc727904", "save_path": "github-repos/isabelle/BraeWebb-stackoverflow", "path": "github-repos/isabelle/BraeWebb-stackoverflow/stackoverflow-a043b47f0f5ed97f73f55af74c6f63ffbc727904/isabelle/Quantale_iso.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467643431001, "lm_q2_score": 0.8333245994514084, "lm_q1q2_score": 0.7326146252552156}}
{"text": "text\\<open>\nFormal Languages and Automata Theory (FLAT)\naccording to the book with same name (2nd version) by Zongli Jiang\ncreated by Yongwang Zhao (zhaoyw@buaa.edu.cn)\nSchool of Computer Science and Engineering, Beihang University, Beijing, China\n\\<close>\n\nsection\\<open>3. Finite Automaton\\<close>\n\nsubsection\\<open>3.3: nondeterministic finite automaton\\<close>\n\ntheory NFA\nimports AutoProj\nbegin\n\nsubsubsection\\<open>definition 3-7: nondeterministic finite automaton\\<close>\n\ntext\\<open>\nM = <Q,\\<Sigma>,\\<delta>,q0,F>\nQ: states, represented as 's\n\\<Sigma>: input alphabet, represented as 'a\n\\<delta>: transition function\nq0: initial state\nF: final states\nnfa defined as below is a triple <q0,\\<delta>,F>\n\\<close>\ntype_synonym ('a,'s) nfa = \"'s * ('a \\<Rightarrow> 's \\<Rightarrow> 's set) * ('s set)\"\n\nabbreviation \"q0 \\<equiv> start\"\nabbreviation \"\\<delta> \\<equiv> next\"\nabbreviation \"F \\<equiv> fin\"\n\nprimrec \\<delta>' :: \"('a,'s)nfa \\<Rightarrow> 'a list \\<Rightarrow> 's \\<Rightarrow> 's set\" where\n\"\\<delta>' A []    p = {p}\" |\n\"\\<delta>' A (a#w) p = \\<Union>(\\<delta>' A w ` \\<delta> A a p)\"\n\nsubsubsection\\<open>definition 3-8: accepted language\\<close>\ndefinition\n accepts :: \"('a,'s)nfa \\<Rightarrow> 'a list \\<Rightarrow> bool\" where\n\"accepts A w = (\\<exists>q \\<in> \\<delta>' A w (q0 A). q \\<in> F A)\"\n\ntype_synonym 'a lang = \"'a list set\"\n\ndefinition NFALang :: \"('a,'s)nfa \\<Rightarrow> 'a lang\"\n  where \"NFALang m \\<equiv> {x. accepts m x}\"\n\n\ndefinition\n step :: \"('a,'s)nfa \\<Rightarrow> 'a \\<Rightarrow> ('s * 's)set\" where\n\"step A a = {(p,q) . q \\<in> \\<delta> A a p}\"\n\nprimrec steps :: \"('a,'s)nfa \\<Rightarrow> 'a list \\<Rightarrow> ('s * 's)set\" where\n\"steps A [] = Id\" |\n\"steps A (a#w) = step A a O steps A w\"\n\nlemma steps_append[simp]:\n \"steps A (v@w) = steps A v  O  steps A w\"\nby(induct v, simp_all add:O_assoc)\n\nlemma in_steps_append[iff]:\n  \"(p,r) : steps A (v@w) = ((p,r) : (steps A v O steps A w))\"\napply(rule steps_append[THEN equalityE])\napply blast\ndone\n\nlemma delta_conv_steps: \"\\<And>p. \\<delta>' A w p = {q. (p,q) \\<in> steps A w}\"\nby(induct w)(auto simp:step_def)\n\nlemma accepts_conv_steps:\n \"accepts A w = (\\<exists>q. (q0 A,q) \\<in> steps A w \\<and> q \\<in> F A)\"\nby(simp add: delta_conv_steps accepts_def)\n\nabbreviation\n  Cons_syn :: \"'a \\<Rightarrow> 'a list set \\<Rightarrow> 'a list set\" (infixr \"##\" 65) where\n  \"x ## S \\<equiv> Cons x ` S\"\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/Section3_FA/NFA.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8791467706759584, "lm_q2_score": 0.8333245891029456, "lm_q1q2_score": 0.7326146214347246}}
{"text": "(* Author: Tobias Nipkow *)\n\nsection \\<open>Function \\textit{lookup} for Tree2\\<close>\n\ntheory Lookup2\nimports\n  Tree2\n  Cmp\n  Map_by_Ordered\nbegin\n\nfun lookup :: \"('a::linorder * 'b, 'c) tree \\<Rightarrow> 'a \\<Rightarrow> 'b option\" where\n\"lookup Leaf x = None\" |\n\"lookup (Node _ l (a,b) r) x =\n  (case cmp x a of LT \\<Rightarrow> lookup l x | GT \\<Rightarrow> lookup r x | EQ \\<Rightarrow> Some b)\"\n\nlemma lookup_map_of:\n  \"sorted1(inorder t) \\<Longrightarrow> lookup t x = map_of (inorder t) x\"\nby(induction t) (auto simp: map_of_simps split: option.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/Lookup2.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.879146761176671, "lm_q2_score": 0.8333245953120233, "lm_q1q2_score": 0.7326146189774254}}
{"text": "(*  Title:      HOL/Induct/ABexp.thy\n    Author:     Stefan Berghofer, TU Muenchen\n*)\n\nsection \\<open>Arithmetic and boolean expressions\\<close>\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 \\<open>\\medskip Evaluation of arithmetic and boolean expressions\\<close>\n\nprimrec evala :: \"('a \\<Rightarrow> nat) \\<Rightarrow> 'a aexp \\<Rightarrow> nat\"\n  and evalb :: \"('a \\<Rightarrow> nat) \\<Rightarrow> 'a bexp \\<Rightarrow> 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 \\<open>\\medskip Substitution on arithmetic and boolean expressions\\<close>\n\nprimrec substa :: \"('a \\<Rightarrow> 'b aexp) \\<Rightarrow> 'a aexp \\<Rightarrow> 'b aexp\"\n  and substb :: \"('a \\<Rightarrow> 'b aexp) \\<Rightarrow> 'a bexp \\<Rightarrow> '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    \\<comment>  \\<open>one variable\\<close>\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": "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/Induct/ABexp.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9149009619539554, "lm_q2_score": 0.8006919997179627, "lm_q1q2_score": 0.7325538807708003}}
{"text": "theory Scratch\n  imports Main\nbegin\n  \ndatatype mybool = MTrue | MFalse\n  \nfun myconj :: \"mybool \\<Rightarrow> mybool \\<Rightarrow> mybool\" where\n  \"myconj MTrue MTrue = MTrue\" |\n  \"myconj _    _    = MFalse\"\n  \nvalue \"myconj MTrue MFalse\"\n  \ndatatype mynat = MZero | MSuc mynat\n  \nfun myadd :: \"mynat \\<Rightarrow> mynat \\<Rightarrow> mynat\" where\n  \"myadd MZero    r = r\" |\n  \"myadd (MSuc l) r = MSuc(myadd l r)\"\n  (* \"myadd (MSuc l) r = myadd l (MSuc r)\" *)\n  \nlemma add_02: \"myadd l MZero = l\"\n  apply(induction l)\n   apply(auto)\n  done\n    \nvalue \"myadd (MSuc MZero) MZero\"\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  \n  \nvalue \"rev(Cons True (Cons False Nil))\"\nvalue \"rev(Cons a (Cons b Nil))\"\n  \nend", "meta": {"author": "gittywithexcitement", "repo": "isabelle", "sha": "42c53b2797e1b14c741c316f2585449b818a8f07", "save_path": "github-repos/isabelle/gittywithexcitement-isabelle", "path": "github-repos/isabelle/gittywithexcitement-isabelle/isabelle-42c53b2797e1b14c741c316f2585449b818a8f07/MyTypes.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009526726545, "lm_q2_score": 0.8006920068519376, "lm_q1q2_score": 0.7325538798662173}}
{"text": "(*  Title:      HOL/Power.thy\n    Author:     Lawrence C Paulson, Cambridge University Computer Laboratory\n    Copyright   1997  University of Cambridge\n*)\n\nsection \\<open>Exponentiation\\<close>\n\ntheory Power\n  imports Num\nbegin\n\nsubsection \\<open>Powers for Arbitrary Monoids\\<close>\n\nclass power = one + times\nbegin\n\nprimrec power :: \"'a \\<Rightarrow> nat \\<Rightarrow> 'a\"  (infixr \"^\" 80)\n  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\ntext \\<open>Special syntax for squares.\\<close>\nabbreviation power2 :: \"'a \\<Rightarrow> 'a\"  (\"(_\\<^sup>2)\" [1000] 999)\n  where \"x\\<^sup>2 \\<equiv> x ^ 2\"\n\nend\n\ncontext monoid_mult\nbegin\n\nsubclass power .\n\nlemma power_one [simp]: \"1 ^ n = 1\"\n  by (induct n) simp_all\n\nlemma power_one_right [simp]: \"a ^ 1 = a\"\n  by simp\n\nlemma power_Suc0_right [simp]: \"a ^ Suc 0 = a\"\n  by simp\n\nlemma power_commutes: \"a ^ n * a = a * a ^ n\"\n  by (induct n) (simp_all add: mult.assoc)\n\nlemma power_Suc2: \"a ^ Suc n = a ^ n * a\"\n  by (simp add: power_commutes)\n\nlemma power_add: \"a ^ (m + n) = a ^ m * a ^ n\"\n  by (induct m) (simp_all add: algebra_simps)\n\nlemma power_mult: \"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: \"a ^ (2 * n) = (a ^ n)\\<^sup>2\"\n  by (subst mult.commute) (simp add: power_mult)\n\nlemma power_odd_eq: \"a ^ Suc (2*n) = a * (a ^ n)\\<^sup>2\"\n  by (simp add: power_even_eq)\n\nlemma power_numeral_even: \"z ^ numeral (Num.Bit0 w) = (let w = z ^ (numeral w) in w * w)\"\n  by (simp only: numeral_Bit0 power_add Let_def)\n\nlemma power_numeral_odd: \"z ^ numeral (Num.Bit1 w) = (let w = z ^ (numeral w) in z * w * w)\"\n  by (simp only: numeral_Bit1 One_nat_def add_Suc_right add_0_right\n      power_Suc power_add Let_def mult.assoc)\n\nlemma funpow_times_power: \"(times x ^^ f x) = times (x ^ f x)\"\nproof (induct \"f x\" arbitrary: f)\n  case 0\n  then show ?case by (simp add: fun_eq_iff)\nnext\n  case (Suc n)\n  define g where \"g x = f x - 1\" for x\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\n    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 0\n  then show ?case by simp\nnext\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    by (simp only: Suc power_Suc2) (simp add: ac_simps)\n  finally show ?case .\nqed\n\nlemma power_minus_mult: \"0 < n \\<Longrightarrow> a ^ (n - 1) * a = a ^ n\"\n  by (simp add: power_commutes split: nat_diff_split)\n\nend\n\ncontext comm_monoid_mult\nbegin\n\nlemma power_mult_distrib [field_simps]: \"(a * b) ^ n = (a ^ n) * (b ^ n)\"\n  by (induct n) (simp_all add: ac_simps)\n\nend\n\ntext \\<open>Extract constant factors from powers.\\<close>\ndeclare power_mult_distrib [where a = \"numeral w\" for w, simp]\ndeclare power_mult_distrib [where b = \"numeral w\" for w, simp]\n\nlemma power_add_numeral [simp]: \"a^numeral m * a^numeral n = a^numeral (m + n)\"\n  for a :: \"'a::monoid_mult\"\n  by (simp add: power_add [symmetric])\n\nlemma power_add_numeral2 [simp]: \"a^numeral m * (a^numeral n * b) = a^numeral (m + n) * b\"\n  for a :: \"'a::monoid_mult\"\n  by (simp add: mult.assoc [symmetric])\n\nlemma power_mult_numeral [simp]: \"(a^numeral m)^numeral n = a^numeral (m * n)\"\n  for a :: \"'a::monoid_mult\"\n  by (simp only: numeral_mult power_mult)\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)\n    (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\nlemma of_nat_power [simp]: \"of_nat (m ^ n) = of_nat m ^ n\"\n  by (induct n) simp_all\n\nlemma zero_power: \"0 < n \\<Longrightarrow> 0 ^ n = 0\"\n  by (cases n) simp_all\n\nlemma power_zero_numeral [simp]: \"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\nlemma power_0_Suc [simp]: \"0 ^ Suc n = 0\"\n  by simp\n\ntext \\<open>It looks plausible as a simprule, but its effect can be strange.\\<close>\nlemma power_0_left: \"0 ^ n = (if n = 0 then 1 else 0)\"\n  by (cases n) simp_all\n\nend\n\ncontext comm_semiring_1\nbegin\n\ntext \\<open>The divides relation.\\<close>\n\nlemma le_imp_power_dvd:\n  assumes \"m \\<le> n\"\n  shows \"a ^ m dvd a ^ n\"\nproof\n  from assms have \"a ^ n = a ^ (m + (n - m))\" by simp\n  also have \"\\<dots> = a ^ m * a ^ (n - m)\" by (rule power_add)\n  finally show \"a ^ n = a ^ m * a ^ (n - m)\" .\nqed\n\nlemma power_le_dvd: \"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: \"x dvd y \\<Longrightarrow> x ^ n dvd y ^ n\"\n  by (induct n) (auto simp add: mult_dvd_mono)\n\nlemma dvd_power_le: \"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  fixes n :: nat\n  assumes \"n > 0 \\<or> x = 1\"\n  shows \"x dvd (x ^ n)\"\n  using assms\nproof\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 semiring_1_no_zero_divisors\nbegin\n\nsubclass power .\n\nlemma power_eq_0_iff [simp]: \"a ^ n = 0 \\<longleftrightarrow> a = 0 \\<and> n > 0\"\n  by (induct n) auto\n\nlemma power_not_zero: \"a \\<noteq> 0 \\<Longrightarrow> a ^ n \\<noteq> 0\"\n  by (induct n) auto\n\nlemma zero_eq_power2 [simp]: \"a\\<^sup>2 = 0 \\<longleftrightarrow> a = 0\"\n  unfolding power2_eq_square by simp\n\nend\n\ncontext ring_1\nbegin\n\nlemma power_minus: \"(- a) ^ n = (- 1) ^ n * a ^ n\"\nproof (induct n)\n  case 0\n  show ?case by simp\nnext\n  case (Suc n)\n  then show ?case\n    by (simp del: power_Suc add: power_Suc2 mult.assoc)\nqed\n\nlemma power_minus': \"NO_MATCH 1 x \\<Longrightarrow> (-x) ^ n = (-1)^n * x ^ n\"\n  by (rule power_minus)\n\nlemma power_minus_Bit0: \"(- 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: \"(- 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]: \"(- a)\\<^sup>2 = a\\<^sup>2\"\n  by (fact power_minus_Bit0)\n\nlemma power_minus1_even [simp]: \"(- 1) ^ (2*n) = 1\"\nproof (induct n)\n  case 0\n  show ?case by simp\nnext\n  case (Suc n)\n  then show ?case by (simp add: power_add power2_eq_square)\nqed\n\nlemma power_minus1_odd: \"(- 1) ^ Suc (2*n) = -1\"\n  by simp\n\nlemma power_minus_even [simp]: \"(-a) ^ (2*n) = a ^ (2*n)\"\n  by (simp add: power_minus [of a])\n\nend\n\ncontext ring_1_no_zero_divisors\nbegin\n\nlemma power2_eq_1_iff: \"a\\<^sup>2 = 1 \\<longleftrightarrow> a = 1 \\<or> a = - 1\"\n  using square_eq_1_iff [of a] by (simp add: power2_eq_square)\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 algebraic_semidom\nbegin\n\nlemma div_power: \"b dvd a \\<Longrightarrow> (a div b) ^ n = a ^ n div b ^ n\"\n  by (induct n) (simp_all add: div_mult_div_if_dvd dvd_power_same)\n\nlemma is_unit_power_iff: \"is_unit (a ^ n) \\<longleftrightarrow> is_unit a \\<or> n = 0\"\n  by (induct n) (auto simp add: is_unit_mult_iff)\n\nlemma dvd_power_iff:\n  assumes \"x \\<noteq> 0\"\n  shows   \"x ^ m dvd x ^ n \\<longleftrightarrow> is_unit x \\<or> m \\<le> n\"\nproof\n  assume *: \"x ^ m dvd x ^ n\"\n  {\n    assume \"m > n\"\n    note *\n    also have \"x ^ n = x ^ n * 1\" by simp\n    also from \\<open>m > n\\<close> have \"m = n + (m - n)\" by simp\n    also have \"x ^ \\<dots> = x ^ n * x ^ (m - n)\" by (rule power_add)\n    finally have \"x ^ (m - n) dvd 1\"\n      by (subst (asm) dvd_times_left_cancel_iff) (insert assms, simp_all)\n    with \\<open>m > n\\<close> have \"is_unit x\" by (simp add: is_unit_power_iff)\n  }\n  thus \"is_unit x \\<or> m \\<le> n\" by force\nqed (auto intro: unit_imp_dvd simp: is_unit_power_iff le_imp_power_dvd)\n\n\nend\n\ncontext normalization_semidom\nbegin\n\nlemma normalize_power: \"normalize (a ^ n) = normalize a ^ n\"\n  by (induct n) (simp_all add: normalize_mult)\n\nlemma unit_factor_power: \"unit_factor (a ^ n) = unit_factor a ^ n\"\n  by (induct n) (simp_all add: unit_factor_mult)\n\nend\n\ncontext division_ring\nbegin\n\ntext \\<open>Perhaps these should be simprules.\\<close>\nlemma power_inverse [field_simps, divide_simps]: \"inverse a ^ n = inverse (a ^ n)\"\nproof (cases \"a = 0\")\n  case True\n  then show ?thesis by (simp add: power_0_left)\nnext\n  case False\n  then have \"inverse (a ^ n) = inverse a ^ n\"\n    by (induct n) (simp_all add: nonzero_inverse_mult_distrib power_commutes)\n  then show ?thesis by simp\nqed\n\nlemma power_one_over [field_simps, divide_simps]: \"(1 / a) ^ n = 1 / a ^ n\"\n  using power_inverse [of a] by (simp add: divide_inverse)\n\nend\n\ncontext field\nbegin\n\nlemma power_diff:\n  assumes \"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: assms power_not_zero)\n\nlemma power_divide [field_simps, divide_simps]: \"(a / b) ^ n = a ^ n / b ^ n\"\n  by (induct n) simp_all\n\nend\n\n\nsubsection \\<open>Exponentiation on ordered types\\<close>\n\ncontext linordered_semidom\nbegin\n\nlemma zero_less_power [simp]: \"0 < a \\<Longrightarrow> 0 < a ^ n\"\n  by (induct n) simp_all\n\nlemma zero_le_power [simp]: \"0 \\<le> a \\<Longrightarrow> 0 \\<le> a ^ n\"\n  by (induct n) simp_all\n\nlemma power_mono: \"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: \"0 \\<le> a \\<Longrightarrow> a \\<le> 1 \\<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  from gt1 have \"1 * 1 < a * 1\" by simp\n  also from gt1 have \"\\<dots> \\<le> a * a ^ n\"\n    by (simp only: mult_mono \\<open>0 \\<le> a\\<close> one_le_power order_less_imp_le zero_le_one order_refl)\n  finally show ?thesis by simp\nqed\n\nlemma power_gt1: \"1 < a \\<Longrightarrow> 1 < a ^ Suc n\"\n  by (simp add: power_gt1_lemma)\n\nlemma one_less_power [simp]: \"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 have \"a * a ^ m \\<le> 1\" by simp\n    with gt1 show ?thesis\n      by (force simp only: power_gt1_lemma 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 simp add: less_trans [OF zero_less_one gt1])\n  qed\nqed\n\nlemma of_nat_zero_less_power_iff [simp]: \"of_nat x ^ n > 0 \\<longleftrightarrow> x > 0 \\<or> n = 0\"\n  by (induct n) auto\n\ntext \\<open>Surely we can strengthen this? It holds for \\<open>0<a<1\\<close> too.\\<close>\nlemma power_inject_exp [simp]: \"1 < a \\<Longrightarrow> a ^ m = a ^ n \\<longleftrightarrow> m = n\"\n  by (force simp add: order_antisym power_le_imp_le_exp)\n\ntext \\<open>\n  Can relax the first premise to @{term \"0<a\"} in the case of the\n  natural numbers.\n\\<close>\nlemma power_less_imp_less_exp: \"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\"] power_le_imp_le_exp)\n\nlemma power_strict_mono [rule_format]: \"a < b \\<Longrightarrow> 0 \\<le> a \\<Longrightarrow> 0 < n \\<longrightarrow> a ^ n < b ^ n\"\n  by (induct n) (auto simp: mult_strict_mono le_less_trans [of 0 a b])\n\ntext\\<open>Lemma for \\<open>power_strict_decreasing\\<close>\\<close>\nlemma power_Suc_less: \"0 < a \\<Longrightarrow> a < 1 \\<Longrightarrow> a * a ^ n < a ^ n\"\n  by (induct n) (auto simp: mult_strict_left_mono)\n\nlemma power_strict_decreasing [rule_format]: \"n < N \\<Longrightarrow> 0 < a \\<Longrightarrow> a < 1 \\<longrightarrow> a ^ N < a ^ n\"\nproof (induct N)\n  case 0\n  then show ?case by simp\nnext\n  case (Suc N)\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)\n       apply auto\n    done\nqed\n\ntext \\<open>Proof resembles that of \\<open>power_strict_decreasing\\<close>.\\<close>\nlemma power_decreasing: \"n \\<le> N \\<Longrightarrow> 0 \\<le> a \\<Longrightarrow> a \\<le> 1 \\<Longrightarrow> a ^ N \\<le> a ^ n\"\nproof (induct N)\n  case 0\n  then show ?case by simp\nnext\n  case (Suc N)\n  then show ?case\n    apply (auto simp add: le_Suc_eq)\n    apply (subgoal_tac \"a * a^N \\<le> 1 * a^n\")\n     apply simp\n    apply (rule mult_mono)\n       apply auto\n    done\nqed\n\nlemma power_Suc_less_one: \"0 < a \\<Longrightarrow> a < 1 \\<Longrightarrow> a ^ Suc n < 1\"\n  using power_strict_decreasing [of 0 \"Suc n\" a] by simp\n\ntext \\<open>Proof again resembles that of \\<open>power_strict_decreasing\\<close>.\\<close>\nlemma power_increasing: \"n \\<le> N \\<Longrightarrow> 1 \\<le> a \\<Longrightarrow> a ^ n \\<le> a ^ N\"\nproof (induct N)\n  case 0\n  then show ?case by simp\nnext\n  case (Suc N)\n  then show ?case\n    apply (auto simp add: le_Suc_eq)\n    apply (subgoal_tac \"1 * a^n \\<le> a * a^N\")\n     apply simp\n    apply (rule mult_mono)\n       apply (auto simp add: order_trans [OF zero_le_one])\n    done\nqed\n\ntext \\<open>Lemma for \\<open>power_strict_increasing\\<close>.\\<close>\nlemma power_less_power_Suc: \"1 < a \\<Longrightarrow> a ^ n < a * a ^ n\"\n  by (induct n) (auto simp: mult_strict_left_mono less_trans [OF zero_less_one])\n\nlemma power_strict_increasing: \"n < N \\<Longrightarrow> 1 < a \\<Longrightarrow> a ^ n < a ^ N\"\nproof (induct N)\n  case 0\n  then show ?case by simp\nnext\n  case (Suc N)\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\")\n     apply simp\n    apply (rule mult_strict_mono)\n    apply (auto simp add: less_trans [OF zero_less_one] less_imp_le)\n    done\nqed\n\nlemma power_increasing_iff [simp]: \"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]: \"1 < b \\<Longrightarrow> b ^ x < b ^ y \\<longleftrightarrow> x < y\"\n  by (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 \"0 \\<le> b\"\n  shows \"a \\<le> b\"\nproof (rule ccontr)\n  assume \"\\<not> ?thesis\"\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(2) power_strict_mono)\n  with le 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 \"\\<not> ?thesis\"\n  then have \"b \\<le> a\" by (simp only: linorder_not_less)\n  from this nonneg have \"b ^ n \\<le> a ^ n\" by (rule power_mono)\n  then show \"\\<not> a ^ n < b ^ n\" by (simp only: linorder_not_less)\nqed\n\nlemma power_inject_base: \"a ^ Suc n = b ^ Suc n \\<Longrightarrow> 0 \\<le> a \\<Longrightarrow> 0 \\<le> b \\<Longrightarrow> a = b\"\n  by (blast intro: power_le_imp_le_base antisym eq_refl sym)\n\nlemma power_eq_imp_eq_base: \"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 power_eq_iff_eq_base: \"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\nlemma power2_le_imp_le: \"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: \"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: \"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\nlemma power_Suc_le_self: \"0 \\<le> a \\<Longrightarrow> a \\<le> 1 \\<Longrightarrow> a ^ Suc n \\<le> a\"\n  using power_decreasing [of 1 \"Suc n\" a] by simp\n\nend\n\ncontext linordered_ring_strict\nbegin\n\nlemma sum_squares_eq_zero_iff: \"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: \"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: \"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: \"\\<bar>a ^ n\\<bar> = \\<bar>a\\<bar> ^ n\"\n  by (induct n) (auto simp add: abs_mult)\n\nlemma abs_power_minus [simp]: \"\\<bar>(-a) ^ n\\<bar> = \\<bar>a ^ n\\<bar>\"\n  by (simp add: power_abs)\n\nlemma zero_less_power_abs_iff [simp]: \"0 < \\<bar>a\\<bar> ^ n \\<longleftrightarrow> a \\<noteq> 0 \\<or> n = 0\"\nproof (induct n)\n  case 0\n  show ?case by simp\nnext\n  case Suc\n  then show ?case by (auto simp: zero_less_mult_iff)\nqed\n\nlemma zero_le_power_abs [simp]: \"0 \\<le> \\<bar>a\\<bar> ^ n\"\n  by (rule zero_le_power [OF abs_ge_zero])\n\nlemma zero_le_power2 [simp]: \"0 \\<le> a\\<^sup>2\"\n  by (simp add: power2_eq_square)\n\nlemma zero_less_power2 [simp]: \"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]: \"\\<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]: \"a\\<^sup>2 \\<le> 0 \\<longleftrightarrow> a = 0\"\n  by (simp add: le_less)\n\nlemma abs_power2 [simp]: \"\\<bar>a\\<^sup>2\\<bar> = a\\<^sup>2\"\n  by (simp add: power2_eq_square)\n\nlemma power2_abs [simp]: \"\\<bar>a\\<bar>\\<^sup>2 = a\\<^sup>2\"\n  by (simp add: power2_eq_square)\n\nlemma odd_power_less_zero: \"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  then show ?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: \"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]: \"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  then show ?case\n    by (simp add: Suc zero_le_mult_iff)\nqed\n\nlemma sum_power2_ge_zero: \"0 \\<le> x\\<^sup>2 + y\\<^sup>2\"\n  by (intro add_nonneg_nonneg zero_le_power2)\n\nlemma not_sum_power2_lt_zero: \"\\<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: \"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: \"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: \"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\nlemma abs_le_square_iff: \"\\<bar>x\\<bar> \\<le> \\<bar>y\\<bar> \\<longleftrightarrow> x\\<^sup>2 \\<le> y\\<^sup>2\"\n  (is \"?lhs \\<longleftrightarrow> ?rhs\")\nproof\n  assume ?lhs\n  then have \"\\<bar>x\\<bar>\\<^sup>2 \\<le> \\<bar>y\\<bar>\\<^sup>2\" by (rule power_mono) simp\n  then show ?rhs by simp\nnext\n  assume ?rhs\n  then show ?lhs\n    by (auto intro!: power2_le_imp_le [OF _ abs_ge_zero])\nqed\n\nlemma abs_square_le_1:\"x\\<^sup>2 \\<le> 1 \\<longleftrightarrow> \\<bar>x\\<bar> \\<le> 1\"\n  using abs_le_square_iff [of x 1] by simp\n\nlemma abs_square_eq_1: \"x\\<^sup>2 = 1 \\<longleftrightarrow> \\<bar>x\\<bar> = 1\"\n  by (auto simp add: abs_if power2_eq_1_iff)\n\nlemma abs_square_less_1: \"x\\<^sup>2 < 1 \\<longleftrightarrow> \\<bar>x\\<bar> < 1\"\n  using  abs_square_eq_1 [of x] abs_square_le_1 [of x] by (auto simp add: le_less)\n\nend\n\n\nsubsection \\<open>Miscellaneous rules\\<close>\n\nlemma (in linordered_semidom) self_le_power: \"1 \\<le> a \\<Longrightarrow> 0 < n \\<Longrightarrow> a \\<le> a ^ n\"\n  using power_increasing [of 1 n a] power_one_right [of a] by auto\n\nlemma (in power) 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: \"(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\ncontext comm_ring_1\nbegin\n\nlemma power2_diff: \"(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 power2_commute: \"(x - y)\\<^sup>2 = (y - x)\\<^sup>2\"\n  by (simp add: algebra_simps power2_eq_square)\n\nlemma minus_power_mult_self: \"(- a) ^ n * (- a) ^ n = a ^ (2 * n)\"\n  by (simp add: power_mult_distrib [symmetric])\n    (simp add: power2_eq_square [symmetric] power_mult [symmetric])\n\nlemma minus_one_mult_self [simp]: \"(- 1) ^ n * (- 1) ^ n = 1\"\n  using minus_power_mult_self [of 1 n] by simp\n\nlemma left_minus_one_mult_self [simp]: \"(- 1) ^ n * ((- 1) ^ n * a) = a\"\n  by (simp add: mult.assoc [symmetric])\n\nend\n\ntext \\<open>Simprules for comparisons where common factors can be cancelled.\\<close>\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 \\<open>Exponentiation for the Natural Numbers\\<close>\n\nlemma nat_one_le_power [simp]: \"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]: \"x ^ n > 0 \\<longleftrightarrow> x > 0 \\<or> n = 0\"\n  for x :: nat\n  by (induct n) auto\n\nlemma nat_power_eq_Suc_0_iff [simp]: \"x ^ m = Suc 0 \\<longleftrightarrow> m = 0 \\<or> x = Suc 0\"\n  by (induct m) auto\n\nlemma power_Suc_0 [simp]: \"Suc 0 ^ n = Suc 0\"\n  by simp\n\ntext \\<open>\n  Valid for the naturals, but what if \\<open>0 < i < 1\\<close>? Premises cannot be\n  weakened: consider the case where \\<open>i = 0\\<close>, \\<open>m = 1\\<close> and \\<open>n = 0\\<close>.\n\\<close>\n\nlemma nat_power_less_imp_less:\n  fixes i :: nat\n  assumes nonneg: \"0 < i\"\n  assumes less: \"i ^ m < i ^ n\"\n  shows \"m < n\"\nproof (cases \"i = 1\")\n  case True\n  with less power_one [where 'a = nat] show ?thesis by simp\nnext\n  case False\n  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: \"i ^ m dvd i ^ n \\<Longrightarrow> 1 < i \\<Longrightarrow> m \\<le> n\"\n  for i m n :: nat\n  apply (rule power_le_imp_le_exp)\n   apply assumption\n  apply (erule dvd_imp_le)\n  apply simp\n  done\n\nlemma power2_nat_le_eq_le: \"m\\<^sup>2 \\<le> n\\<^sup>2 \\<longleftrightarrow> m \\<le> n\"\n  for m n :: nat\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\n  then show ?thesis by simp\nnext\n  case (Suc k)\n  show ?thesis\n  proof (rule ccontr)\n    assume \"\\<not> ?thesis\"\n    then have \"n < m\" by simp\n    with assms Suc show False\n      by (simp add: power2_eq_square)\n  qed\nqed\n\nlemma ex_power_ivl1: fixes b k :: nat assumes \"b \\<ge> 2\"\nshows \"k \\<ge> 1 \\<Longrightarrow> \\<exists>n. b^n \\<le> k \\<and> k < b^(n+1)\" (is \"_ \\<Longrightarrow> \\<exists>n. ?P k n\")\nproof(induction k)\n  case 0 thus ?case by simp\nnext\n  case (Suc k)\n  show ?case\n  proof cases\n    assume \"k=0\"\n    hence \"?P (Suc k) 0\" using assms by simp\n    thus ?case ..\n  next\n    assume \"k\\<noteq>0\"\n    with Suc obtain n where IH: \"?P k n\" by auto\n    show ?case\n    proof (cases \"k = b^(n+1) - 1\")\n      case True\n      hence \"?P (Suc k) (n+1)\" using assms\n        by (simp add: power_less_power_Suc)\n      thus ?thesis ..\n    next\n      case False\n      hence \"?P (Suc k) n\" using IH by auto\n      thus ?thesis ..\n    qed\n  qed\nqed\n\nlemma ex_power_ivl2: fixes b k :: nat assumes \"b \\<ge> 2\" \"k \\<ge> 2\"\nshows \"\\<exists>n. b^n < k \\<and> k \\<le> b^(n+1)\"\nproof -\n  have \"1 \\<le> k - 1\" using assms(2) by arith\n  from ex_power_ivl1[OF assms(1) this]\n  obtain n where \"b ^ n \\<le> k - 1 \\<and> k - 1 < b ^ (n + 1)\" ..\n  hence \"b^n < k \\<and> k \\<le> b^(n+1)\" using assms by auto\n  thus ?thesis ..\nqed\n\n\nsubsubsection \\<open>Cardinality of the Powerset\\<close>\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  with insert show ?case\n    apply (simp add: Pow_insert)\n    apply (subst card_Un_disjoint)\n       apply auto\n    done\nqed\n\n\nsubsection \\<open>Code generator tweak\\<close>\n\ncode_identifier\n  code_module Power \\<rightharpoonup> (SML) Arith and (OCaml) Arith and (Haskell) Arith\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/Power.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473879530491, "lm_q2_score": 0.8397339756938818, "lm_q1q2_score": 0.732539740271987}}
{"text": "(*  Title:      HOL/Analysis/Path_Connected.thy\n    Authors:    LC Paulson and Robert Himmelmann (TU Muenchen), based on material from HOL Light\n*)\n\nsection \\<open>Continuous paths and path-connected sets\\<close>\n\ntheory Path_Connected\nimports Continuous_Extension Continuum_Not_Denumerable\nbegin\n\nsubsection \\<open>Paths and Arcs\\<close>\n\ndefinition path :: \"(real \\<Rightarrow> 'a::topological_space) \\<Rightarrow> bool\"\n  where \"path g \\<longleftrightarrow> continuous_on {0..1} g\"\n\ndefinition pathstart :: \"(real \\<Rightarrow> 'a::topological_space) \\<Rightarrow> 'a\"\n  where \"pathstart g = g 0\"\n\ndefinition pathfinish :: \"(real \\<Rightarrow> 'a::topological_space) \\<Rightarrow> 'a\"\n  where \"pathfinish g = g 1\"\n\ndefinition path_image :: \"(real \\<Rightarrow> 'a::topological_space) \\<Rightarrow> 'a set\"\n  where \"path_image g = g ` {0 .. 1}\"\n\ndefinition reversepath :: \"(real \\<Rightarrow> 'a::topological_space) \\<Rightarrow> real \\<Rightarrow> 'a\"\n  where \"reversepath g = (\\<lambda>x. g(1 - x))\"\n\ndefinition joinpaths :: \"(real \\<Rightarrow> 'a::topological_space) \\<Rightarrow> (real \\<Rightarrow> 'a) \\<Rightarrow> real \\<Rightarrow> 'a\"\n    (infixr \"+++\" 75)\n  where \"g1 +++ g2 = (\\<lambda>x. if x \\<le> 1/2 then g1 (2 * x) else g2 (2 * x - 1))\"\n\ndefinition simple_path :: \"(real \\<Rightarrow> 'a::topological_space) \\<Rightarrow> bool\"\n  where \"simple_path g \\<longleftrightarrow>\n     path g \\<and> (\\<forall>x\\<in>{0..1}. \\<forall>y\\<in>{0..1}. g x = g y \\<longrightarrow> x = y \\<or> x = 0 \\<and> y = 1 \\<or> x = 1 \\<and> y = 0)\"\n\ndefinition arc :: \"(real \\<Rightarrow> 'a :: topological_space) \\<Rightarrow> bool\"\n  where \"arc g \\<longleftrightarrow> path g \\<and> inj_on g {0..1}\"\n\n\nsubsection\\<open>Invariance theorems\\<close>\n\nlemma path_eq: \"path p \\<Longrightarrow> (\\<And>t. t \\<in> {0..1} \\<Longrightarrow> p t = q t) \\<Longrightarrow> path q\"\n  using continuous_on_eq path_def by blast\n\nlemma path_continuous_image: \"path g \\<Longrightarrow> continuous_on (path_image g) f \\<Longrightarrow> path(f o g)\"\n  unfolding path_def path_image_def\n  using continuous_on_compose by blast\n\nlemma path_translation_eq:\n  fixes g :: \"real \\<Rightarrow> 'a :: real_normed_vector\"\n  shows \"path((\\<lambda>x. a + x) o g) = path g\"\nproof -\n  have g: \"g = (\\<lambda>x. -a + x) o ((\\<lambda>x. a + x) o g)\"\n    by (rule ext) simp\n  show ?thesis\n    unfolding path_def\n    apply safe\n    apply (subst g)\n    apply (rule continuous_on_compose)\n    apply (auto intro: continuous_intros)\n    done\nqed\n\nlemma path_linear_image_eq:\n  fixes f :: \"'a::euclidean_space \\<Rightarrow> 'b::euclidean_space\"\n   assumes \"linear f\" \"inj f\"\n     shows \"path(f o g) = path g\"\nproof -\n  from linear_injective_left_inverse [OF assms]\n  obtain h where h: \"linear h\" \"h \\<circ> f = id\"\n    by blast\n  then have g: \"g = h o (f o g)\"\n    by (metis comp_assoc id_comp)\n  show ?thesis\n    unfolding path_def\n    using h assms\n    by (metis g continuous_on_compose linear_continuous_on linear_conv_bounded_linear)\nqed\n\nlemma pathstart_translation: \"pathstart((\\<lambda>x. a + x) o g) = a + pathstart g\"\n  by (simp add: pathstart_def)\n\nlemma pathstart_linear_image_eq: \"linear f \\<Longrightarrow> pathstart(f o g) = f(pathstart g)\"\n  by (simp add: pathstart_def)\n\nlemma pathfinish_translation: \"pathfinish((\\<lambda>x. a + x) o g) = a + pathfinish g\"\n  by (simp add: pathfinish_def)\n\nlemma pathfinish_linear_image: \"linear f \\<Longrightarrow> pathfinish(f o g) = f(pathfinish g)\"\n  by (simp add: pathfinish_def)\n\nlemma path_image_translation: \"path_image((\\<lambda>x. a + x) o g) = (\\<lambda>x. a + x) ` (path_image g)\"\n  by (simp add: image_comp path_image_def)\n\nlemma path_image_linear_image: \"linear f \\<Longrightarrow> path_image(f o g) = f ` (path_image g)\"\n  by (simp add: image_comp path_image_def)\n\nlemma reversepath_translation: \"reversepath((\\<lambda>x. a + x) o g) = (\\<lambda>x. a + x) o reversepath g\"\n  by (rule ext) (simp add: reversepath_def)\n\nlemma reversepath_linear_image: \"linear f \\<Longrightarrow> reversepath(f o g) = f o reversepath g\"\n  by (rule ext) (simp add: reversepath_def)\n\nlemma joinpaths_translation:\n    \"((\\<lambda>x. a + x) o g1) +++ ((\\<lambda>x. a + x) o g2) = (\\<lambda>x. a + x) o (g1 +++ g2)\"\n  by (rule ext) (simp add: joinpaths_def)\n\nlemma joinpaths_linear_image: \"linear f \\<Longrightarrow> (f o g1) +++ (f o g2) = f o (g1 +++ g2)\"\n  by (rule ext) (simp add: joinpaths_def)\n\nlemma simple_path_translation_eq:\n  fixes g :: \"real \\<Rightarrow> 'a::euclidean_space\"\n  shows \"simple_path((\\<lambda>x. a + x) o g) = simple_path g\"\n  by (simp add: simple_path_def path_translation_eq)\n\nlemma simple_path_linear_image_eq:\n  fixes f :: \"'a::euclidean_space \\<Rightarrow> 'b::euclidean_space\"\n  assumes \"linear f\" \"inj f\"\n    shows \"simple_path(f o g) = simple_path g\"\n  using assms inj_on_eq_iff [of f]\n  by (auto simp: path_linear_image_eq simple_path_def path_translation_eq)\n\nlemma arc_translation_eq:\n  fixes g :: \"real \\<Rightarrow> 'a::euclidean_space\"\n  shows \"arc((\\<lambda>x. a + x) o g) = arc g\"\n  by (auto simp: arc_def inj_on_def path_translation_eq)\n\nlemma arc_linear_image_eq:\n  fixes f :: \"'a::euclidean_space \\<Rightarrow> 'b::euclidean_space\"\n   assumes \"linear f\" \"inj f\"\n     shows  \"arc(f o g) = arc g\"\n  using assms inj_on_eq_iff [of f]\n  by (auto simp: arc_def inj_on_def path_linear_image_eq)\n\nsubsection\\<open>Basic lemmas about paths\\<close>\n\nlemma arc_imp_simple_path: \"arc g \\<Longrightarrow> simple_path g\"\n  by (simp add: arc_def inj_on_def simple_path_def)\n\nlemma arc_imp_path: \"arc g \\<Longrightarrow> path g\"\n  using arc_def by blast\n\nlemma simple_path_imp_path: \"simple_path g \\<Longrightarrow> path g\"\n  using simple_path_def by blast\n\nlemma simple_path_cases: \"simple_path g \\<Longrightarrow> arc g \\<or> pathfinish g = pathstart g\"\n  unfolding simple_path_def arc_def inj_on_def pathfinish_def pathstart_def\n  by (force)\n\nlemma simple_path_imp_arc: \"simple_path g \\<Longrightarrow> pathfinish g \\<noteq> pathstart g \\<Longrightarrow> arc g\"\n  using simple_path_cases by auto\n\nlemma arc_distinct_ends: \"arc g \\<Longrightarrow> pathfinish g \\<noteq> pathstart g\"\n  unfolding arc_def inj_on_def pathfinish_def pathstart_def\n  by fastforce\n\nlemma arc_simple_path: \"arc g \\<longleftrightarrow> simple_path g \\<and> pathfinish g \\<noteq> pathstart g\"\n  using arc_distinct_ends arc_imp_simple_path simple_path_cases by blast\n\nlemma simple_path_eq_arc: \"pathfinish g \\<noteq> pathstart g \\<Longrightarrow> (simple_path g = arc g)\"\n  by (simp add: arc_simple_path)\n\nlemma path_image_nonempty [simp]: \"path_image g \\<noteq> {}\"\n  unfolding path_image_def image_is_empty box_eq_empty\n  by auto\n\nlemma pathstart_in_path_image[intro]: \"pathstart g \\<in> path_image g\"\n  unfolding pathstart_def path_image_def\n  by auto\n\nlemma pathfinish_in_path_image[intro]: \"pathfinish g \\<in> path_image g\"\n  unfolding pathfinish_def path_image_def\n  by auto\n\nlemma connected_path_image[intro]: \"path g \\<Longrightarrow> connected (path_image g)\"\n  unfolding path_def path_image_def\n  using connected_continuous_image connected_Icc by blast\n\nlemma compact_path_image[intro]: \"path g \\<Longrightarrow> compact (path_image g)\"\n  unfolding path_def path_image_def\n  using compact_continuous_image connected_Icc by blast\n\nlemma reversepath_reversepath[simp]: \"reversepath (reversepath g) = g\"\n  unfolding reversepath_def\n  by auto\n\nlemma pathstart_reversepath[simp]: \"pathstart (reversepath g) = pathfinish g\"\n  unfolding pathstart_def reversepath_def pathfinish_def\n  by auto\n\nlemma pathfinish_reversepath[simp]: \"pathfinish (reversepath g) = pathstart g\"\n  unfolding pathstart_def reversepath_def pathfinish_def\n  by auto\n\nlemma pathstart_join[simp]: \"pathstart (g1 +++ g2) = pathstart g1\"\n  unfolding pathstart_def joinpaths_def pathfinish_def\n  by auto\n\nlemma pathfinish_join[simp]: \"pathfinish (g1 +++ g2) = pathfinish g2\"\n  unfolding pathstart_def joinpaths_def pathfinish_def\n  by auto\n\nlemma path_image_reversepath[simp]: \"path_image (reversepath g) = path_image g\"\nproof -\n  have *: \"\\<And>g. path_image (reversepath g) \\<subseteq> path_image g\"\n    unfolding path_image_def subset_eq reversepath_def Ball_def image_iff\n    by force\n  show ?thesis\n    using *[of g] *[of \"reversepath g\"]\n    unfolding reversepath_reversepath\n    by auto\nqed\n\nlemma path_reversepath [simp]: \"path (reversepath g) \\<longleftrightarrow> path g\"\nproof -\n  have *: \"\\<And>g. path g \\<Longrightarrow> path (reversepath g)\"\n    unfolding path_def reversepath_def\n    apply (rule continuous_on_compose[unfolded o_def, of _ \"\\<lambda>x. 1 - x\"])\n    apply (intro continuous_intros)\n    apply (rule continuous_on_subset[of \"{0..1}\"])\n    apply assumption\n    apply auto\n    done\n  show ?thesis\n    using *[of \"reversepath g\"] *[of g]\n    unfolding reversepath_reversepath\n    by (rule iffI)\nqed\n\nlemma arc_reversepath:\n  assumes \"arc g\" shows \"arc(reversepath g)\"\nproof -\n  have injg: \"inj_on g {0..1}\"\n    using assms\n    by (simp add: arc_def)\n  have **: \"\\<And>x y::real. 1-x = 1-y \\<Longrightarrow> x = y\"\n    by simp\n  show ?thesis\n    apply (auto simp: arc_def inj_on_def path_reversepath)\n    apply (simp add: arc_imp_path assms)\n    apply (rule **)\n    apply (rule inj_onD [OF injg])\n    apply (auto simp: reversepath_def)\n    done\nqed\n\nlemma simple_path_reversepath: \"simple_path g \\<Longrightarrow> simple_path (reversepath g)\"\n  apply (simp add: simple_path_def)\n  apply (force simp: reversepath_def)\n  done\n\nlemmas reversepath_simps =\n  path_reversepath path_image_reversepath pathstart_reversepath pathfinish_reversepath\n\nlemma path_join[simp]:\n  assumes \"pathfinish g1 = pathstart g2\"\n  shows \"path (g1 +++ g2) \\<longleftrightarrow> path g1 \\<and> path g2\"\n  unfolding path_def pathfinish_def pathstart_def\nproof safe\n  assume cont: \"continuous_on {0..1} (g1 +++ g2)\"\n  have g1: \"continuous_on {0..1} g1 \\<longleftrightarrow> continuous_on {0..1} ((g1 +++ g2) \\<circ> (\\<lambda>x. x / 2))\"\n    by (intro continuous_on_cong refl) (auto simp: joinpaths_def)\n  have g2: \"continuous_on {0..1} g2 \\<longleftrightarrow> continuous_on {0..1} ((g1 +++ g2) \\<circ> (\\<lambda>x. x / 2 + 1/2))\"\n    using assms\n    by (intro continuous_on_cong refl) (auto simp: joinpaths_def pathfinish_def pathstart_def)\n  show \"continuous_on {0..1} g1\" and \"continuous_on {0..1} g2\"\n    unfolding g1 g2\n    by (auto intro!: continuous_intros continuous_on_subset[OF cont] simp del: o_apply)\nnext\n  assume g1g2: \"continuous_on {0..1} g1\" \"continuous_on {0..1} g2\"\n  have 01: \"{0 .. 1} = {0..1/2} \\<union> {1/2 .. 1::real}\"\n    by auto\n  {\n    fix x :: real\n    assume \"0 \\<le> x\" and \"x \\<le> 1\"\n    then have \"x \\<in> (\\<lambda>x. x * 2) ` {0..1 / 2}\"\n      by (intro image_eqI[where x=\"x/2\"]) auto\n  }\n  note 1 = this\n  {\n    fix x :: real\n    assume \"0 \\<le> x\" and \"x \\<le> 1\"\n    then have \"x \\<in> (\\<lambda>x. x * 2 - 1) ` {1 / 2..1}\"\n      by (intro image_eqI[where x=\"x/2 + 1/2\"]) auto\n  }\n  note 2 = this\n  show \"continuous_on {0..1} (g1 +++ g2)\"\n    using assms\n    unfolding joinpaths_def 01\n    apply (intro continuous_on_cases closed_atLeastAtMost g1g2[THEN continuous_on_compose2] continuous_intros)\n    apply (auto simp: field_simps pathfinish_def pathstart_def intro!: 1 2)\n    done\nqed\n\nsection \\<open>Path Images\\<close>\n\nlemma bounded_path_image: \"path g \\<Longrightarrow> bounded(path_image g)\"\n  by (simp add: compact_imp_bounded compact_path_image)\n\nlemma closed_path_image:\n  fixes g :: \"real \\<Rightarrow> 'a::t2_space\"\n  shows \"path g \\<Longrightarrow> closed(path_image g)\"\n  by (metis compact_path_image compact_imp_closed)\n\nlemma connected_simple_path_image: \"simple_path g \\<Longrightarrow> connected(path_image g)\"\n  by (metis connected_path_image simple_path_imp_path)\n\nlemma compact_simple_path_image: \"simple_path g \\<Longrightarrow> compact(path_image g)\"\n  by (metis compact_path_image simple_path_imp_path)\n\nlemma bounded_simple_path_image: \"simple_path g \\<Longrightarrow> bounded(path_image g)\"\n  by (metis bounded_path_image simple_path_imp_path)\n\nlemma closed_simple_path_image:\n  fixes g :: \"real \\<Rightarrow> 'a::t2_space\"\n  shows \"simple_path g \\<Longrightarrow> closed(path_image g)\"\n  by (metis closed_path_image simple_path_imp_path)\n\nlemma connected_arc_image: \"arc g \\<Longrightarrow> connected(path_image g)\"\n  by (metis connected_path_image arc_imp_path)\n\nlemma compact_arc_image: \"arc g \\<Longrightarrow> compact(path_image g)\"\n  by (metis compact_path_image arc_imp_path)\n\nlemma bounded_arc_image: \"arc g \\<Longrightarrow> bounded(path_image g)\"\n  by (metis bounded_path_image arc_imp_path)\n\nlemma closed_arc_image:\n  fixes g :: \"real \\<Rightarrow> 'a::t2_space\"\n  shows \"arc g \\<Longrightarrow> closed(path_image g)\"\n  by (metis closed_path_image arc_imp_path)\n\nlemma path_image_join_subset: \"path_image (g1 +++ g2) \\<subseteq> path_image g1 \\<union> path_image g2\"\n  unfolding path_image_def joinpaths_def\n  by auto\n\nlemma subset_path_image_join:\n  assumes \"path_image g1 \\<subseteq> s\"\n    and \"path_image g2 \\<subseteq> s\"\n  shows \"path_image (g1 +++ g2) \\<subseteq> s\"\n  using path_image_join_subset[of g1 g2] and assms\n  by auto\n\nlemma path_image_join:\n    \"pathfinish g1 = pathstart g2 \\<Longrightarrow> path_image(g1 +++ g2) = path_image g1 \\<union> path_image g2\"\n  apply (rule subset_antisym [OF path_image_join_subset])\n  apply (auto simp: pathfinish_def pathstart_def path_image_def joinpaths_def image_def)\n  apply (drule sym)\n  apply (rule_tac x=\"xa/2\" in bexI, auto)\n  apply (rule ccontr)\n  apply (drule_tac x=\"(xa+1)/2\" in bspec)\n  apply (auto simp: field_simps)\n  apply (drule_tac x=\"1/2\" in bspec, auto)\n  done\n\nlemma not_in_path_image_join:\n  assumes \"x \\<notin> path_image g1\"\n    and \"x \\<notin> path_image g2\"\n  shows \"x \\<notin> path_image (g1 +++ g2)\"\n  using assms and path_image_join_subset[of g1 g2]\n  by auto\n\nlemma pathstart_compose: \"pathstart(f o p) = f(pathstart p)\"\n  by (simp add: pathstart_def)\n\nlemma pathfinish_compose: \"pathfinish(f o p) = f(pathfinish p)\"\n  by (simp add: pathfinish_def)\n\nlemma path_image_compose: \"path_image (f o p) = f ` (path_image p)\"\n  by (simp add: image_comp path_image_def)\n\nlemma path_compose_join: \"f o (p +++ q) = (f o p) +++ (f o q)\"\n  by (rule ext) (simp add: joinpaths_def)\n\nlemma path_compose_reversepath: \"f o reversepath p = reversepath(f o p)\"\n  by (rule ext) (simp add: reversepath_def)\n\nlemma joinpaths_eq:\n  \"(\\<And>t. t \\<in> {0..1} \\<Longrightarrow> p t = p' t) \\<Longrightarrow>\n   (\\<And>t. t \\<in> {0..1} \\<Longrightarrow> q t = q' t)\n   \\<Longrightarrow>  t \\<in> {0..1} \\<Longrightarrow> (p +++ q) t = (p' +++ q') t\"\n  by (auto simp: joinpaths_def)\n\nlemma simple_path_inj_on: \"simple_path g \\<Longrightarrow> inj_on g {0<..<1}\"\n  by (auto simp: simple_path_def path_image_def inj_on_def less_eq_real_def Ball_def)\n\n\nsubsection\\<open>Simple paths with the endpoints removed\\<close>\n\nlemma simple_path_endless:\n    \"simple_path c \\<Longrightarrow> path_image c - {pathstart c,pathfinish c} = c ` {0<..<1}\"\n  apply (auto simp: simple_path_def path_image_def pathstart_def pathfinish_def Ball_def Bex_def image_def)\n  apply (metis eq_iff le_less_linear)\n  apply (metis leD linear)\n  using less_eq_real_def zero_le_one apply blast\n  using less_eq_real_def zero_le_one apply blast\n  done\n\nlemma connected_simple_path_endless:\n    \"simple_path c \\<Longrightarrow> connected(path_image c - {pathstart c,pathfinish c})\"\napply (simp add: simple_path_endless)\napply (rule connected_continuous_image)\napply (meson continuous_on_subset greaterThanLessThan_subseteq_atLeastAtMost_iff le_numeral_extra(3) le_numeral_extra(4) path_def simple_path_imp_path)\nby auto\n\nlemma nonempty_simple_path_endless:\n    \"simple_path c \\<Longrightarrow> path_image c - {pathstart c,pathfinish c} \\<noteq> {}\"\n  by (simp add: simple_path_endless)\n\n\nsubsection\\<open>The operations on paths\\<close>\n\nlemma path_image_subset_reversepath: \"path_image(reversepath g) \\<le> path_image g\"\n  by (auto simp: path_image_def reversepath_def)\n\nlemma path_imp_reversepath: \"path g \\<Longrightarrow> path(reversepath g)\"\n  apply (auto simp: path_def reversepath_def)\n  using continuous_on_compose [of \"{0..1}\" \"\\<lambda>x. 1 - x\" g]\n  apply (auto simp: continuous_on_op_minus)\n  done\n\nlemma half_bounded_equal: \"1 \\<le> x * 2 \\<Longrightarrow> x * 2 \\<le> 1 \\<longleftrightarrow> x = (1/2::real)\"\n  by simp\n\nlemma continuous_on_joinpaths:\n  assumes \"continuous_on {0..1} g1\" \"continuous_on {0..1} g2\" \"pathfinish g1 = pathstart g2\"\n    shows \"continuous_on {0..1} (g1 +++ g2)\"\nproof -\n  have *: \"{0..1::real} = {0..1/2} \\<union> {1/2..1}\"\n    by auto\n  have gg: \"g2 0 = g1 1\"\n    by (metis assms(3) pathfinish_def pathstart_def)\n  have 1: \"continuous_on {0..1/2} (g1 +++ g2)\"\n    apply (rule continuous_on_eq [of _ \"g1 o (\\<lambda>x. 2*x)\"])\n    apply (rule continuous_intros | simp add: joinpaths_def assms)+\n    done\n  have \"continuous_on {1/2..1} (g2 o (\\<lambda>x. 2*x-1))\"\n    apply (rule continuous_on_subset [of \"{1/2..1}\"])\n    apply (rule continuous_intros | simp add: image_affinity_atLeastAtMost_diff assms)+\n    done\n  then have 2: \"continuous_on {1/2..1} (g1 +++ g2)\"\n    apply (rule continuous_on_eq [of \"{1/2..1}\" \"g2 o (\\<lambda>x. 2*x-1)\"])\n    apply (rule assms continuous_intros | simp add: joinpaths_def mult.commute half_bounded_equal gg)+\n    done\n  show ?thesis\n    apply (subst *)\n    apply (rule continuous_on_closed_Un)\n    using 1 2\n    apply auto\n    done\nqed\n\nlemma path_join_imp: \"\\<lbrakk>path g1; path g2; pathfinish g1 = pathstart g2\\<rbrakk> \\<Longrightarrow> path(g1 +++ g2)\"\n  by (simp add: path_join)\n\nlemma simple_path_join_loop:\n  assumes \"arc g1\" \"arc g2\"\n          \"pathfinish g1 = pathstart g2\"  \"pathfinish g2 = pathstart g1\"\n          \"path_image g1 \\<inter> path_image g2 \\<subseteq> {pathstart g1, pathstart g2}\"\n  shows \"simple_path(g1 +++ g2)\"\nproof -\n  have injg1: \"inj_on g1 {0..1}\"\n    using assms\n    by (simp add: arc_def)\n  have injg2: \"inj_on g2 {0..1}\"\n    using assms\n    by (simp add: arc_def)\n  have g12: \"g1 1 = g2 0\"\n   and g21: \"g2 1 = g1 0\"\n   and sb:  \"g1 ` {0..1} \\<inter> g2 ` {0..1} \\<subseteq> {g1 0, g2 0}\"\n    using assms\n    by (simp_all add: arc_def pathfinish_def pathstart_def path_image_def)\n  { fix x and y::real\n    assume xyI: \"x = 1 \\<longrightarrow> y \\<noteq> 0\"\n       and xy: \"x \\<le> 1\" \"0 \\<le> y\" \" y * 2 \\<le> 1\" \"\\<not> x * 2 \\<le> 1\" \"g2 (2 * x - 1) = g1 (2 * y)\"\n    have g1im: \"g1 (2 * y) \\<in> g1 ` {0..1} \\<inter> g2 ` {0..1}\"\n      using xy\n      apply simp\n      apply (rule_tac x=\"2 * x - 1\" in image_eqI, auto)\n      done\n    have False\n      using subsetD [OF sb g1im] xy\n      apply auto\n      apply (drule inj_onD [OF injg1])\n      using g21 [symmetric] xyI\n      apply (auto dest: inj_onD [OF injg2])\n      done\n   } note * = this\n  { fix x and y::real\n    assume xy: \"y \\<le> 1\" \"0 \\<le> x\" \"\\<not> y * 2 \\<le> 1\" \"x * 2 \\<le> 1\" \"g1 (2 * x) = g2 (2 * y - 1)\"\n    have g1im: \"g1 (2 * x) \\<in> g1 ` {0..1} \\<inter> g2 ` {0..1}\"\n      using xy\n      apply simp\n      apply (rule_tac x=\"2 * x\" in image_eqI, auto)\n      done\n    have \"x = 0 \\<and> y = 1\"\n      using subsetD [OF sb g1im] xy\n      apply auto\n      apply (force dest: inj_onD [OF injg1])\n      using  g21 [symmetric]\n      apply (auto dest: inj_onD [OF injg2])\n      done\n   } note ** = this\n  show ?thesis\n    using assms\n    apply (simp add: arc_def simple_path_def path_join, clarify)\n    apply (simp add: joinpaths_def split: if_split_asm)\n    apply (force dest: inj_onD [OF injg1])\n    apply (metis *)\n    apply (metis **)\n    apply (force dest: inj_onD [OF injg2])\n    done\nqed\n\nlemma arc_join:\n  assumes \"arc g1\" \"arc g2\"\n          \"pathfinish g1 = pathstart g2\"\n          \"path_image g1 \\<inter> path_image g2 \\<subseteq> {pathstart g2}\"\n    shows \"arc(g1 +++ g2)\"\nproof -\n  have injg1: \"inj_on g1 {0..1}\"\n    using assms\n    by (simp add: arc_def)\n  have injg2: \"inj_on g2 {0..1}\"\n    using assms\n    by (simp add: arc_def)\n  have g11: \"g1 1 = g2 0\"\n   and sb:  \"g1 ` {0..1} \\<inter> g2 ` {0..1} \\<subseteq> {g2 0}\"\n    using assms\n    by (simp_all add: arc_def pathfinish_def pathstart_def path_image_def)\n  { fix x and y::real\n    assume xy: \"x \\<le> 1\" \"0 \\<le> y\" \" y * 2 \\<le> 1\" \"\\<not> x * 2 \\<le> 1\" \"g2 (2 * x - 1) = g1 (2 * y)\"\n    have g1im: \"g1 (2 * y) \\<in> g1 ` {0..1} \\<inter> g2 ` {0..1}\"\n      using xy\n      apply simp\n      apply (rule_tac x=\"2 * x - 1\" in image_eqI, auto)\n      done\n    have False\n      using subsetD [OF sb g1im] xy\n      by (auto dest: inj_onD [OF injg2])\n   } note * = this\n  show ?thesis\n    apply (simp add: arc_def inj_on_def)\n    apply (clarsimp simp add: arc_imp_path assms path_join)\n    apply (simp add: joinpaths_def split: if_split_asm)\n    apply (force dest: inj_onD [OF injg1])\n    apply (metis *)\n    apply (metis *)\n    apply (force dest: inj_onD [OF injg2])\n    done\nqed\n\nlemma reversepath_joinpaths:\n    \"pathfinish g1 = pathstart g2 \\<Longrightarrow> reversepath(g1 +++ g2) = reversepath g2 +++ reversepath g1\"\n  unfolding reversepath_def pathfinish_def pathstart_def joinpaths_def\n  by (rule ext) (auto simp: mult.commute)\n\n\nsubsection\\<open>Some reversed and \"if and only if\" versions of joining theorems\\<close>\n\nlemma path_join_path_ends:\n  fixes g1 :: \"real \\<Rightarrow> 'a::metric_space\"\n  assumes \"path(g1 +++ g2)\" \"path g2\"\n    shows \"pathfinish g1 = pathstart g2\"\nproof (rule ccontr)\n  define e where \"e = dist (g1 1) (g2 0)\"\n  assume Neg: \"pathfinish g1 \\<noteq> pathstart g2\"\n  then have \"0 < dist (pathfinish g1) (pathstart g2)\"\n    by auto\n  then have \"e > 0\"\n    by (metis e_def pathfinish_def pathstart_def)\n  then obtain d1 where \"d1 > 0\"\n       and d1: \"\\<And>x'. \\<lbrakk>x'\\<in>{0..1}; norm x' < d1\\<rbrakk> \\<Longrightarrow> dist (g2 x') (g2 0) < e/2\"\n    using assms(2) unfolding path_def continuous_on_iff\n    apply (drule_tac x=0 in bspec, simp)\n    by (metis half_gt_zero_iff norm_conv_dist)\n  obtain d2 where \"d2 > 0\"\n       and d2: \"\\<And>x'. \\<lbrakk>x'\\<in>{0..1}; dist x' (1/2) < d2\\<rbrakk>\n                      \\<Longrightarrow> dist ((g1 +++ g2) x') (g1 1) < e/2\"\n    using assms(1) \\<open>e > 0\\<close> unfolding path_def continuous_on_iff\n    apply (drule_tac x=\"1/2\" in bspec, simp)\n    apply (drule_tac x=\"e/2\" in spec)\n    apply (force simp: joinpaths_def)\n    done\n  have int01_1: \"min (1/2) (min d1 d2) / 2 \\<in> {0..1}\"\n    using \\<open>d1 > 0\\<close> \\<open>d2 > 0\\<close> by (simp add: min_def)\n  have dist1: \"norm (min (1 / 2) (min d1 d2) / 2) < d1\"\n    using \\<open>d1 > 0\\<close> \\<open>d2 > 0\\<close> by (simp add: min_def dist_norm)\n  have int01_2: \"1/2 + min (1/2) (min d1 d2) / 4 \\<in> {0..1}\"\n    using \\<open>d1 > 0\\<close> \\<open>d2 > 0\\<close> by (simp add: min_def)\n  have dist2: \"dist (1 / 2 + min (1 / 2) (min d1 d2) / 4) (1 / 2) < d2\"\n    using \\<open>d1 > 0\\<close> \\<open>d2 > 0\\<close> by (simp add: min_def dist_norm)\n  have [simp]: \"~ min (1 / 2) (min d1 d2) \\<le> 0\"\n    using \\<open>d1 > 0\\<close> \\<open>d2 > 0\\<close> by (simp add: min_def)\n  have \"dist (g2 (min (1 / 2) (min d1 d2) / 2)) (g1 1) < e/2\"\n       \"dist (g2 (min (1 / 2) (min d1 d2) / 2)) (g2 0) < e/2\"\n    using d1 [OF int01_1 dist1] d2 [OF int01_2 dist2] by (simp_all add: joinpaths_def)\n  then have \"dist (g1 1) (g2 0) < e/2 + e/2\"\n    using dist_triangle_half_r e_def by blast\n  then show False\n    by (simp add: e_def [symmetric])\nqed\n\nlemma path_join_eq [simp]:\n  fixes g1 :: \"real \\<Rightarrow> 'a::metric_space\"\n  assumes \"path g1\" \"path g2\"\n    shows \"path(g1 +++ g2) \\<longleftrightarrow> pathfinish g1 = pathstart g2\"\n  using assms by (metis path_join_path_ends path_join_imp)\n\nlemma simple_path_joinE:\n  assumes \"simple_path(g1 +++ g2)\" and \"pathfinish g1 = pathstart g2\"\n  obtains \"arc g1\" \"arc g2\"\n          \"path_image g1 \\<inter> path_image g2 \\<subseteq> {pathstart g1, pathstart g2}\"\nproof -\n  have *: \"\\<And>x y. \\<lbrakk>0 \\<le> x; x \\<le> 1; 0 \\<le> y; y \\<le> 1; (g1 +++ g2) x = (g1 +++ g2) y\\<rbrakk>\n               \\<Longrightarrow> x = y \\<or> x = 0 \\<and> y = 1 \\<or> x = 1 \\<and> y = 0\"\n    using assms by (simp add: simple_path_def)\n  have \"path g1\"\n    using assms path_join simple_path_imp_path by blast\n  moreover have \"inj_on g1 {0..1}\"\n  proof (clarsimp simp: inj_on_def)\n    fix x y\n    assume \"g1 x = g1 y\" \"0 \\<le> x\" \"x \\<le> 1\" \"0 \\<le> y\" \"y \\<le> 1\"\n    then show \"x = y\"\n      using * [of \"x/2\" \"y/2\"] by (simp add: joinpaths_def split_ifs)\n  qed\n  ultimately have \"arc g1\"\n    using assms  by (simp add: arc_def)\n  have [simp]: \"g2 0 = g1 1\"\n    using assms by (metis pathfinish_def pathstart_def)\n  have \"path g2\"\n    using assms path_join simple_path_imp_path by blast\n  moreover have \"inj_on g2 {0..1}\"\n  proof (clarsimp simp: inj_on_def)\n    fix x y\n    assume \"g2 x = g2 y\" \"0 \\<le> x\" \"x \\<le> 1\" \"0 \\<le> y\" \"y \\<le> 1\"\n    then show \"x = y\"\n      using * [of \"(x + 1) / 2\" \"(y + 1) / 2\"]\n      by (force simp: joinpaths_def split_ifs divide_simps)\n  qed\n  ultimately have \"arc g2\"\n    using assms  by (simp add: arc_def)\n  have \"g2 y = g1 0 \\<or> g2 y = g1 1\"\n       if \"g1 x = g2 y\" \"0 \\<le> x\" \"x \\<le> 1\" \"0 \\<le> y\" \"y \\<le> 1\" for x y\n      using * [of \"x / 2\" \"(y + 1) / 2\"] that\n      by (auto simp: joinpaths_def split_ifs divide_simps)\n  then have \"path_image g1 \\<inter> path_image g2 \\<subseteq> {pathstart g1, pathstart g2}\"\n    by (fastforce simp: pathstart_def pathfinish_def path_image_def)\n  with \\<open>arc g1\\<close> \\<open>arc g2\\<close> show ?thesis using that by blast\nqed\n\nlemma simple_path_join_loop_eq:\n  assumes \"pathfinish g2 = pathstart g1\" \"pathfinish g1 = pathstart g2\"\n    shows \"simple_path(g1 +++ g2) \\<longleftrightarrow>\n             arc g1 \\<and> arc g2 \\<and> path_image g1 \\<inter> path_image g2 \\<subseteq> {pathstart g1, pathstart g2}\"\nby (metis assms simple_path_joinE simple_path_join_loop)\n\nlemma arc_join_eq:\n  assumes \"pathfinish g1 = pathstart g2\"\n    shows \"arc(g1 +++ g2) \\<longleftrightarrow>\n           arc g1 \\<and> arc g2 \\<and> path_image g1 \\<inter> path_image g2 \\<subseteq> {pathstart g2}\"\n           (is \"?lhs = ?rhs\")\nproof\n  assume ?lhs\n  then have \"simple_path(g1 +++ g2)\" by (rule arc_imp_simple_path)\n  then have *: \"\\<And>x y. \\<lbrakk>0 \\<le> x; x \\<le> 1; 0 \\<le> y; y \\<le> 1; (g1 +++ g2) x = (g1 +++ g2) y\\<rbrakk>\n               \\<Longrightarrow> x = y \\<or> x = 0 \\<and> y = 1 \\<or> x = 1 \\<and> y = 0\"\n    using assms by (simp add: simple_path_def)\n  have False if \"g1 0 = g2 u\" \"0 \\<le> u\" \"u \\<le> 1\" for u\n    using * [of 0 \"(u + 1) / 2\"] that assms arc_distinct_ends [OF \\<open>?lhs\\<close>]\n    by (auto simp: joinpaths_def pathstart_def pathfinish_def split_ifs divide_simps)\n  then have n1: \"~ (pathstart g1 \\<in> path_image g2)\"\n    unfolding pathstart_def path_image_def\n    using atLeastAtMost_iff by blast\n  show ?rhs using \\<open>?lhs\\<close>\n    apply (rule simple_path_joinE [OF arc_imp_simple_path assms])\n    using n1 by force\nnext\n  assume ?rhs then show ?lhs\n    using assms\n    by (fastforce simp: pathfinish_def pathstart_def intro!: arc_join)\nqed\n\nlemma arc_join_eq_alt:\n        \"pathfinish g1 = pathstart g2\n        \\<Longrightarrow> (arc(g1 +++ g2) \\<longleftrightarrow>\n             arc g1 \\<and> arc g2 \\<and>\n             path_image g1 \\<inter> path_image g2 = {pathstart g2})\"\nusing pathfinish_in_path_image by (fastforce simp: arc_join_eq)\n\n\nsubsection\\<open>The joining of paths is associative\\<close>\n\nlemma path_assoc:\n    \"\\<lbrakk>pathfinish p = pathstart q; pathfinish q = pathstart r\\<rbrakk>\n     \\<Longrightarrow> path(p +++ (q +++ r)) \\<longleftrightarrow> path((p +++ q) +++ r)\"\nby simp\n\nlemma simple_path_assoc:\n  assumes \"pathfinish p = pathstart q\" \"pathfinish q = pathstart r\"\n    shows \"simple_path (p +++ (q +++ r)) \\<longleftrightarrow> simple_path ((p +++ q) +++ r)\"\nproof (cases \"pathstart p = pathfinish r\")\n  case True show ?thesis\n  proof\n    assume \"simple_path (p +++ q +++ r)\"\n    with assms True show \"simple_path ((p +++ q) +++ r)\"\n      by (fastforce simp add: simple_path_join_loop_eq arc_join_eq path_image_join\n                    dest: arc_distinct_ends [of r])\n  next\n    assume 0: \"simple_path ((p +++ q) +++ r)\"\n    with assms True have q: \"pathfinish r \\<notin> path_image q\"\n      using arc_distinct_ends\n      by (fastforce simp add: simple_path_join_loop_eq arc_join_eq path_image_join)\n    have \"pathstart r \\<notin> path_image p\"\n      using assms\n      by (metis 0 IntI arc_distinct_ends arc_join_eq_alt empty_iff insert_iff\n              pathfinish_in_path_image pathfinish_join simple_path_joinE)\n    with assms 0 q True show \"simple_path (p +++ q +++ r)\"\n      by (auto simp: simple_path_join_loop_eq arc_join_eq path_image_join\n               dest!: subsetD [OF _ IntI])\n  qed\nnext\n  case False\n  { fix x :: 'a\n    assume a: \"path_image p \\<inter> path_image q \\<subseteq> {pathstart q}\"\n              \"(path_image p \\<union> path_image q) \\<inter> path_image r \\<subseteq> {pathstart r}\"\n              \"x \\<in> path_image p\" \"x \\<in> path_image r\"\n    have \"pathstart r \\<in> path_image q\"\n      by (metis assms(2) pathfinish_in_path_image)\n    with a have \"x = pathstart q\"\n      by blast\n  }\n  with False assms show ?thesis\n    by (auto simp: simple_path_eq_arc simple_path_join_loop_eq arc_join_eq path_image_join)\nqed\n\nlemma arc_assoc:\n     \"\\<lbrakk>pathfinish p = pathstart q; pathfinish q = pathstart r\\<rbrakk>\n      \\<Longrightarrow> arc(p +++ (q +++ r)) \\<longleftrightarrow> arc((p +++ q) +++ r)\"\nby (simp add: arc_simple_path simple_path_assoc)\n\nsubsubsection\\<open>Symmetry and loops\\<close>\n\nlemma path_sym:\n    \"\\<lbrakk>pathfinish p = pathstart q; pathfinish q = pathstart p\\<rbrakk> \\<Longrightarrow> path(p +++ q) \\<longleftrightarrow> path(q +++ p)\"\n  by auto\n\nlemma simple_path_sym:\n    \"\\<lbrakk>pathfinish p = pathstart q; pathfinish q = pathstart p\\<rbrakk>\n     \\<Longrightarrow> simple_path(p +++ q) \\<longleftrightarrow> simple_path(q +++ p)\"\nby (metis (full_types) inf_commute insert_commute simple_path_joinE simple_path_join_loop)\n\nlemma path_image_sym:\n    \"\\<lbrakk>pathfinish p = pathstart q; pathfinish q = pathstart p\\<rbrakk>\n     \\<Longrightarrow> path_image(p +++ q) = path_image(q +++ p)\"\nby (simp add: path_image_join sup_commute)\n\n\nsection\\<open>Choosing a subpath of an existing path\\<close>\n\ndefinition subpath :: \"real \\<Rightarrow> real \\<Rightarrow> (real \\<Rightarrow> 'a) \\<Rightarrow> real \\<Rightarrow> 'a::real_normed_vector\"\n  where \"subpath a b g \\<equiv> \\<lambda>x. g((b - a) * x + a)\"\n\nlemma path_image_subpath_gen:\n  fixes g :: \"_ \\<Rightarrow> 'a::real_normed_vector\"\n  shows \"path_image(subpath u v g) = g ` (closed_segment u v)\"\n  apply (simp add: closed_segment_real_eq path_image_def subpath_def)\n  apply (subst o_def [of g, symmetric])\n  apply (simp add: image_comp [symmetric])\n  done\n\nlemma path_image_subpath:\n  fixes g :: \"real \\<Rightarrow> 'a::real_normed_vector\"\n  shows \"path_image(subpath u v g) = (if u \\<le> v then g ` {u..v} else g ` {v..u})\"\n  by (simp add: path_image_subpath_gen closed_segment_eq_real_ivl)\n\nlemma path_subpath [simp]:\n  fixes g :: \"real \\<Rightarrow> 'a::real_normed_vector\"\n  assumes \"path g\" \"u \\<in> {0..1}\" \"v \\<in> {0..1}\"\n    shows \"path(subpath u v g)\"\nproof -\n  have \"continuous_on {0..1} (g o (\\<lambda>x. ((v-u) * x+ u)))\"\n    apply (rule continuous_intros | simp)+\n    apply (simp add: image_affinity_atLeastAtMost [where c=u])\n    using assms\n    apply (auto simp: path_def continuous_on_subset)\n    done\n  then show ?thesis\n    by (simp add: path_def subpath_def)\nqed\n\nlemma pathstart_subpath [simp]: \"pathstart(subpath u v g) = g(u)\"\n  by (simp add: pathstart_def subpath_def)\n\nlemma pathfinish_subpath [simp]: \"pathfinish(subpath u v g) = g(v)\"\n  by (simp add: pathfinish_def subpath_def)\n\nlemma subpath_trivial [simp]: \"subpath 0 1 g = g\"\n  by (simp add: subpath_def)\n\nlemma subpath_reversepath: \"subpath 1 0 g = reversepath g\"\n  by (simp add: reversepath_def subpath_def)\n\nlemma reversepath_subpath: \"reversepath(subpath u v g) = subpath v u g\"\n  by (simp add: reversepath_def subpath_def algebra_simps)\n\nlemma subpath_translation: \"subpath u v ((\\<lambda>x. a + x) o g) = (\\<lambda>x. a + x) o subpath u v g\"\n  by (rule ext) (simp add: subpath_def)\n\nlemma subpath_linear_image: \"linear f \\<Longrightarrow> subpath u v (f o g) = f o subpath u v g\"\n  by (rule ext) (simp add: subpath_def)\n\nlemma affine_ineq:\n  fixes x :: \"'a::linordered_idom\"\n  assumes \"x \\<le> 1\" \"v \\<le> u\"\n    shows \"v + x * u \\<le> u + x * v\"\nproof -\n  have \"(1-x)*(u-v) \\<ge> 0\"\n    using assms by auto\n  then show ?thesis\n    by (simp add: algebra_simps)\nqed\n\nlemma sum_le_prod1:\n  fixes a::real shows \"\\<lbrakk>a \\<le> 1; b \\<le> 1\\<rbrakk> \\<Longrightarrow> a + b \\<le> 1 + a * b\"\nby (metis add.commute affine_ineq less_eq_real_def mult.right_neutral)\n\nlemma simple_path_subpath_eq:\n  \"simple_path(subpath u v g) \\<longleftrightarrow>\n     path(subpath u v g) \\<and> u\\<noteq>v \\<and>\n     (\\<forall>x y. x \\<in> closed_segment u v \\<and> y \\<in> closed_segment u v \\<and> g x = g y\n                \\<longrightarrow> x = y \\<or> x = u \\<and> y = v \\<or> x = v \\<and> y = u)\"\n    (is \"?lhs = ?rhs\")\nproof (rule iffI)\n  assume ?lhs\n  then have p: \"path (\\<lambda>x. g ((v - u) * x + u))\"\n        and sim: \"(\\<And>x y. \\<lbrakk>x\\<in>{0..1}; y\\<in>{0..1}; g ((v - u) * x + u) = g ((v - u) * y + u)\\<rbrakk>\n                  \\<Longrightarrow> x = y \\<or> x = 0 \\<and> y = 1 \\<or> x = 1 \\<and> y = 0)\"\n    by (auto simp: simple_path_def subpath_def)\n  { fix x y\n    assume \"x \\<in> closed_segment u v\" \"y \\<in> closed_segment u v\" \"g x = g y\"\n    then have \"x = y \\<or> x = u \\<and> y = v \\<or> x = v \\<and> y = u\"\n    using sim [of \"(x-u)/(v-u)\" \"(y-u)/(v-u)\"] p\n    by (auto simp: closed_segment_real_eq image_affinity_atLeastAtMost divide_simps\n       split: if_split_asm)\n  } moreover\n  have \"path(subpath u v g) \\<and> u\\<noteq>v\"\n    using sim [of \"1/3\" \"2/3\"] p\n    by (auto simp: subpath_def)\n  ultimately show ?rhs\n    by metis\nnext\n  assume ?rhs\n  then\n  have d1: \"\\<And>x y. \\<lbrakk>g x = g y; u \\<le> x; x \\<le> v; u \\<le> y; y \\<le> v\\<rbrakk> \\<Longrightarrow> x = y \\<or> x = u \\<and> y = v \\<or> x = v \\<and> y = u\"\n   and d2: \"\\<And>x y. \\<lbrakk>g x = g y; v \\<le> x; x \\<le> u; v \\<le> y; y \\<le> u\\<rbrakk> \\<Longrightarrow> x = y \\<or> x = u \\<and> y = v \\<or> x = v \\<and> y = u\"\n   and ne: \"u < v \\<or> v < u\"\n   and psp: \"path (subpath u v g)\"\n    by (auto simp: closed_segment_real_eq image_affinity_atLeastAtMost)\n  have [simp]: \"\\<And>x. u + x * v = v + x * u \\<longleftrightarrow> u=v \\<or> x=1\"\n    by algebra\n  show ?lhs using psp ne\n    unfolding simple_path_def subpath_def\n    by (fastforce simp add: algebra_simps affine_ineq mult_left_mono crossproduct_eq dest: d1 d2)\nqed\n\nlemma arc_subpath_eq:\n  \"arc(subpath u v g) \\<longleftrightarrow> path(subpath u v g) \\<and> u\\<noteq>v \\<and> inj_on g (closed_segment u v)\"\n    (is \"?lhs = ?rhs\")\nproof (rule iffI)\n  assume ?lhs\n  then have p: \"path (\\<lambda>x. g ((v - u) * x + u))\"\n        and sim: \"(\\<And>x y. \\<lbrakk>x\\<in>{0..1}; y\\<in>{0..1}; g ((v - u) * x + u) = g ((v - u) * y + u)\\<rbrakk>\n                  \\<Longrightarrow> x = y)\"\n    by (auto simp: arc_def inj_on_def subpath_def)\n  { fix x y\n    assume \"x \\<in> closed_segment u v\" \"y \\<in> closed_segment u v\" \"g x = g y\"\n    then have \"x = y\"\n    using sim [of \"(x-u)/(v-u)\" \"(y-u)/(v-u)\"] p\n    by (force simp add: inj_on_def closed_segment_real_eq image_affinity_atLeastAtMost divide_simps\n       split: if_split_asm)\n  } moreover\n  have \"path(subpath u v g) \\<and> u\\<noteq>v\"\n    using sim [of \"1/3\" \"2/3\"] p\n    by (auto simp: subpath_def)\n  ultimately show ?rhs\n    unfolding inj_on_def\n    by metis\nnext\n  assume ?rhs\n  then\n  have d1: \"\\<And>x y. \\<lbrakk>g x = g y; u \\<le> x; x \\<le> v; u \\<le> y; y \\<le> v\\<rbrakk> \\<Longrightarrow> x = y\"\n   and d2: \"\\<And>x y. \\<lbrakk>g x = g y; v \\<le> x; x \\<le> u; v \\<le> y; y \\<le> u\\<rbrakk> \\<Longrightarrow> x = y\"\n   and ne: \"u < v \\<or> v < u\"\n   and psp: \"path (subpath u v g)\"\n    by (auto simp: inj_on_def closed_segment_real_eq image_affinity_atLeastAtMost)\n  show ?lhs using psp ne\n    unfolding arc_def subpath_def inj_on_def\n    by (auto simp: algebra_simps affine_ineq mult_left_mono crossproduct_eq dest: d1 d2)\nqed\n\n\nlemma simple_path_subpath:\n  assumes \"simple_path g\" \"u \\<in> {0..1}\" \"v \\<in> {0..1}\" \"u \\<noteq> v\"\n  shows \"simple_path(subpath u v g)\"\n  using assms\n  apply (simp add: simple_path_subpath_eq simple_path_imp_path)\n  apply (simp add: simple_path_def closed_segment_real_eq image_affinity_atLeastAtMost, fastforce)\n  done\n\nlemma arc_simple_path_subpath:\n    \"\\<lbrakk>simple_path g; u \\<in> {0..1}; v \\<in> {0..1}; g u \\<noteq> g v\\<rbrakk> \\<Longrightarrow> arc(subpath u v g)\"\n  by (force intro: simple_path_subpath simple_path_imp_arc)\n\nlemma arc_subpath_arc:\n    \"\\<lbrakk>arc g; u \\<in> {0..1}; v \\<in> {0..1}; u \\<noteq> v\\<rbrakk> \\<Longrightarrow> arc(subpath u v g)\"\n  by (meson arc_def arc_imp_simple_path arc_simple_path_subpath inj_onD)\n\nlemma arc_simple_path_subpath_interior:\n    \"\\<lbrakk>simple_path g; u \\<in> {0..1}; v \\<in> {0..1}; u \\<noteq> v; \\<bar>u-v\\<bar> < 1\\<rbrakk> \\<Longrightarrow> arc(subpath u v g)\"\n    apply (rule arc_simple_path_subpath)\n    apply (force simp: simple_path_def)+\n    done\n\nlemma path_image_subpath_subset:\n    \"\\<lbrakk>path g; u \\<in> {0..1}; v \\<in> {0..1}\\<rbrakk> \\<Longrightarrow> path_image(subpath u v g) \\<subseteq> path_image g\"\n  apply (simp add: closed_segment_real_eq image_affinity_atLeastAtMost path_image_subpath)\n  apply (auto simp: path_image_def)\n  done\n\nlemma join_subpaths_middle: \"subpath (0) ((1 / 2)) p +++ subpath ((1 / 2)) 1 p = p\"\n  by (rule ext) (simp add: joinpaths_def subpath_def divide_simps)\n\nsubsection\\<open>There is a subpath to the frontier\\<close>\n\nlemma subpath_to_frontier_explicit:\n    fixes S :: \"'a::metric_space set\"\n    assumes g: \"path g\" and \"pathfinish g \\<notin> S\"\n    obtains u where \"0 \\<le> u\" \"u \\<le> 1\"\n                \"\\<And>x. 0 \\<le> x \\<and> x < u \\<Longrightarrow> g x \\<in> interior S\"\n                \"(g u \\<notin> interior S)\" \"(u = 0 \\<or> g u \\<in> closure S)\"\nproof -\n  have gcon: \"continuous_on {0..1} g\"     using g by (simp add: path_def)\n  then have com: \"compact ({0..1} \\<inter> {u. g u \\<in> closure (- S)})\"\n    apply (simp add: Int_commute [of \"{0..1}\"] compact_eq_bounded_closed closed_vimage_Int [unfolded vimage_def])\n    using compact_eq_bounded_closed apply fastforce\n    done\n  have \"1 \\<in> {u. g u \\<in> closure (- S)}\"\n    using assms by (simp add: pathfinish_def closure_def)\n  then have dis: \"{0..1} \\<inter> {u. g u \\<in> closure (- S)} \\<noteq> {}\"\n    using atLeastAtMost_iff zero_le_one by blast\n  then obtain u where \"0 \\<le> u\" \"u \\<le> 1\" and gu: \"g u \\<in> closure (- S)\"\n                  and umin: \"\\<And>t. \\<lbrakk>0 \\<le> t; t \\<le> 1; g t \\<in> closure (- S)\\<rbrakk> \\<Longrightarrow> u \\<le> t\"\n    using compact_attains_inf [OF com dis] by fastforce\n  then have umin': \"\\<And>t. \\<lbrakk>0 \\<le> t; t \\<le> 1; t < u\\<rbrakk> \\<Longrightarrow>  g t \\<in> S\"\n    using closure_def by fastforce\n  { assume \"u \\<noteq> 0\"\n    then have \"u > 0\" using \\<open>0 \\<le> u\\<close> by auto\n    { fix e::real assume \"e > 0\"\n      obtain d where \"d>0\" and d: \"\\<And>x'. \\<lbrakk>x' \\<in> {0..1}; dist x' u \\<le> d\\<rbrakk> \\<Longrightarrow> dist (g x') (g u) < e\"\n        using continuous_onE [OF gcon _ \\<open>e > 0\\<close>] \\<open>0 \\<le> _\\<close> \\<open>_ \\<le> 1\\<close> atLeastAtMost_iff by auto\n      have *: \"dist (max 0 (u - d / 2)) u \\<le> d\"\n        using \\<open>0 \\<le> u\\<close> \\<open>u \\<le> 1\\<close> \\<open>d > 0\\<close> by (simp add: dist_real_def)\n      have \"\\<exists>y\\<in>S. dist y (g u) < e\"\n        using \\<open>0 < u\\<close> \\<open>u \\<le> 1\\<close> \\<open>d > 0\\<close>\n        by (force intro: d [OF _ *] umin')\n    }\n    then have \"g u \\<in> closure S\"\n      by (simp add: frontier_def closure_approachable)\n  }\n  then show ?thesis\n    apply (rule_tac u=u in that)\n    apply (auto simp: \\<open>0 \\<le> u\\<close> \\<open>u \\<le> 1\\<close> gu interior_closure umin)\n    using \\<open>_ \\<le> 1\\<close> interior_closure umin apply fastforce\n    done\nqed\n\nlemma subpath_to_frontier_strong:\n    assumes g: \"path g\" and \"pathfinish g \\<notin> S\"\n    obtains u where \"0 \\<le> u\" \"u \\<le> 1\" \"g u \\<notin> interior S\"\n                    \"u = 0 \\<or> (\\<forall>x. 0 \\<le> x \\<and> x < 1 \\<longrightarrow> subpath 0 u g x \\<in> interior S)  \\<and>  g u \\<in> closure S\"\nproof -\n  obtain u where \"0 \\<le> u\" \"u \\<le> 1\"\n             and gxin: \"\\<And>x. 0 \\<le> x \\<and> x < u \\<Longrightarrow> g x \\<in> interior S\"\n             and gunot: \"(g u \\<notin> interior S)\" and u0: \"(u = 0 \\<or> g u \\<in> closure S)\"\n    using subpath_to_frontier_explicit [OF assms] by blast\n  show ?thesis\n    apply (rule that [OF \\<open>0 \\<le> u\\<close> \\<open>u \\<le> 1\\<close>])\n    apply (simp add: gunot)\n    using \\<open>0 \\<le> u\\<close> u0 by (force simp: subpath_def gxin)\nqed\n\nlemma subpath_to_frontier:\n    assumes g: \"path g\" and g0: \"pathstart g \\<in> closure S\" and g1: \"pathfinish g \\<notin> S\"\n    obtains u where \"0 \\<le> u\" \"u \\<le> 1\" \"g u \\<in> frontier S\" \"(path_image(subpath 0 u g) - {g u}) \\<subseteq> interior S\"\nproof -\n  obtain u where \"0 \\<le> u\" \"u \\<le> 1\"\n             and notin: \"g u \\<notin> interior S\"\n             and disj: \"u = 0 \\<or>\n                        (\\<forall>x. 0 \\<le> x \\<and> x < 1 \\<longrightarrow> subpath 0 u g x \\<in> interior S) \\<and> g u \\<in> closure S\"\n    using subpath_to_frontier_strong [OF g g1] by blast\n  show ?thesis\n    apply (rule that [OF \\<open>0 \\<le> u\\<close> \\<open>u \\<le> 1\\<close>])\n    apply (metis DiffI disj frontier_def g0 notin pathstart_def)\n    using \\<open>0 \\<le> u\\<close> g0 disj\n    apply (simp add: path_image_subpath_gen)\n    apply (auto simp: closed_segment_eq_real_ivl pathstart_def pathfinish_def subpath_def)\n    apply (rename_tac y)\n    apply (drule_tac x=\"y/u\" in spec)\n    apply (auto split: if_split_asm)\n    done\nqed\n\nlemma exists_path_subpath_to_frontier:\n    fixes S :: \"'a::real_normed_vector set\"\n    assumes \"path g\" \"pathstart g \\<in> closure S\" \"pathfinish g \\<notin> S\"\n    obtains h where \"path h\" \"pathstart h = pathstart g\" \"path_image h \\<subseteq> path_image g\"\n                    \"path_image h - {pathfinish h} \\<subseteq> interior S\"\n                    \"pathfinish h \\<in> frontier S\"\nproof -\n  obtain u where u: \"0 \\<le> u\" \"u \\<le> 1\" \"g u \\<in> frontier S\" \"(path_image(subpath 0 u g) - {g u}) \\<subseteq> interior S\"\n    using subpath_to_frontier [OF assms] by blast\n  show ?thesis\n    apply (rule that [of \"subpath 0 u g\"])\n    using assms u\n    apply (simp_all add: path_image_subpath)\n    apply (simp add: pathstart_def)\n    apply (force simp: closed_segment_eq_real_ivl path_image_def)\n    done\nqed\n\nlemma exists_path_subpath_to_frontier_closed:\n    fixes S :: \"'a::real_normed_vector set\"\n    assumes S: \"closed S\" and g: \"path g\" and g0: \"pathstart g \\<in> S\" and g1: \"pathfinish g \\<notin> S\"\n    obtains h where \"path h\" \"pathstart h = pathstart g\" \"path_image h \\<subseteq> path_image g \\<inter> S\"\n                    \"pathfinish h \\<in> frontier S\"\nproof -\n  obtain h where h: \"path h\" \"pathstart h = pathstart g\" \"path_image h \\<subseteq> path_image g\"\n                    \"path_image h - {pathfinish h} \\<subseteq> interior S\"\n                    \"pathfinish h \\<in> frontier S\"\n    using exists_path_subpath_to_frontier [OF g _ g1] closure_closed [OF S] g0 by auto\n  show ?thesis\n    apply (rule that [OF \\<open>path h\\<close>])\n    using assms h\n    apply auto\n    apply (metis Diff_single_insert frontier_subset_eq insert_iff interior_subset subset_iff)\n    done\nqed\n\nsubsection \\<open>Reparametrizing a closed curve to start at some chosen point\\<close>\n\ndefinition shiftpath :: \"real \\<Rightarrow> (real \\<Rightarrow> 'a::topological_space) \\<Rightarrow> real \\<Rightarrow> 'a\"\n  where \"shiftpath a f = (\\<lambda>x. if (a + x) \\<le> 1 then f (a + x) else f (a + x - 1))\"\n\nlemma pathstart_shiftpath: \"a \\<le> 1 \\<Longrightarrow> pathstart (shiftpath a g) = g a\"\n  unfolding pathstart_def shiftpath_def by auto\n\nlemma pathfinish_shiftpath:\n  assumes \"0 \\<le> a\"\n    and \"pathfinish g = pathstart g\"\n  shows \"pathfinish (shiftpath a g) = g a\"\n  using assms\n  unfolding pathstart_def pathfinish_def shiftpath_def\n  by auto\n\nlemma endpoints_shiftpath:\n  assumes \"pathfinish g = pathstart g\"\n    and \"a \\<in> {0 .. 1}\"\n  shows \"pathfinish (shiftpath a g) = g a\"\n    and \"pathstart (shiftpath a g) = g a\"\n  using assms\n  by (auto intro!: pathfinish_shiftpath pathstart_shiftpath)\n\nlemma closed_shiftpath:\n  assumes \"pathfinish g = pathstart g\"\n    and \"a \\<in> {0..1}\"\n  shows \"pathfinish (shiftpath a g) = pathstart (shiftpath a g)\"\n  using endpoints_shiftpath[OF assms]\n  by auto\n\nlemma path_shiftpath:\n  assumes \"path g\"\n    and \"pathfinish g = pathstart g\"\n    and \"a \\<in> {0..1}\"\n  shows \"path (shiftpath a g)\"\nproof -\n  have *: \"{0 .. 1} = {0 .. 1-a} \\<union> {1-a .. 1}\"\n    using assms(3) by auto\n  have **: \"\\<And>x. x + a = 1 \\<Longrightarrow> g (x + a - 1) = g (x + a)\"\n    using assms(2)[unfolded pathfinish_def pathstart_def]\n    by auto\n  show ?thesis\n    unfolding path_def shiftpath_def *\n    apply (rule continuous_on_closed_Un)\n    apply (rule closed_real_atLeastAtMost)+\n    apply (rule continuous_on_eq[of _ \"g \\<circ> (\\<lambda>x. a + x)\"])\n    prefer 3\n    apply (rule continuous_on_eq[of _ \"g \\<circ> (\\<lambda>x. a - 1 + x)\"])\n    prefer 3\n    apply (rule continuous_intros)+\n    prefer 2\n    apply (rule continuous_intros)+\n    apply (rule_tac[1-2] continuous_on_subset[OF assms(1)[unfolded path_def]])\n    using assms(3) and **\n    apply auto\n    apply (auto simp add: field_simps)\n    done\nqed\n\nlemma shiftpath_shiftpath:\n  assumes \"pathfinish g = pathstart g\"\n    and \"a \\<in> {0..1}\"\n    and \"x \\<in> {0..1}\"\n  shows \"shiftpath (1 - a) (shiftpath a g) x = g x\"\n  using assms\n  unfolding pathfinish_def pathstart_def shiftpath_def\n  by auto\n\nlemma path_image_shiftpath:\n  assumes \"a \\<in> {0..1}\"\n    and \"pathfinish g = pathstart g\"\n  shows \"path_image (shiftpath a g) = path_image g\"\nproof -\n  { fix x\n    assume as: \"g 1 = g 0\" \"x \\<in> {0..1::real}\" \" \\<forall>y\\<in>{0..1} \\<inter> {x. \\<not> a + x \\<le> 1}. g x \\<noteq> g (a + y - 1)\"\n    then have \"\\<exists>y\\<in>{0..1} \\<inter> {x. a + x \\<le> 1}. g x = g (a + y)\"\n    proof (cases \"a \\<le> x\")\n      case False\n      then show ?thesis\n        apply (rule_tac x=\"1 + x - a\" in bexI)\n        using as(1,2) and as(3)[THEN bspec[where x=\"1 + x - a\"]] and assms(1)\n        apply (auto simp add: field_simps atomize_not)\n        done\n    next\n      case True\n      then show ?thesis\n        using as(1-2) and assms(1)\n        apply (rule_tac x=\"x - a\" in bexI)\n        apply (auto simp add: field_simps)\n        done\n    qed\n  }\n  then show ?thesis\n    using assms\n    unfolding shiftpath_def path_image_def pathfinish_def pathstart_def\n    by (auto simp add: image_iff)\nqed\n\n\nsubsection \\<open>Special case of straight-line paths\\<close>\n\ndefinition linepath :: \"'a::real_normed_vector \\<Rightarrow> 'a \\<Rightarrow> real \\<Rightarrow> 'a\"\n  where \"linepath a b = (\\<lambda>x. (1 - x) *\\<^sub>R a + x *\\<^sub>R b)\"\n\nlemma pathstart_linepath[simp]: \"pathstart (linepath a b) = a\"\n  unfolding pathstart_def linepath_def\n  by auto\n\nlemma pathfinish_linepath[simp]: \"pathfinish (linepath a b) = b\"\n  unfolding pathfinish_def linepath_def\n  by auto\n\nlemma continuous_linepath_at[intro]: \"continuous (at x) (linepath a b)\"\n  unfolding linepath_def\n  by (intro continuous_intros)\n\nlemma continuous_on_linepath [intro,continuous_intros]: \"continuous_on s (linepath a b)\"\n  using continuous_linepath_at\n  by (auto intro!: continuous_at_imp_continuous_on)\n\nlemma path_linepath[iff]: \"path (linepath a b)\"\n  unfolding path_def\n  by (rule continuous_on_linepath)\n\nlemma path_image_linepath[simp]: \"path_image (linepath a b) = closed_segment a b\"\n  unfolding path_image_def segment linepath_def\n  by auto\n\nlemma reversepath_linepath[simp]: \"reversepath (linepath a b) = linepath b a\"\n  unfolding reversepath_def linepath_def\n  by auto\n\nlemma linepath_0 [simp]: \"linepath 0 b x = x *\\<^sub>R b\"\n  by (simp add: linepath_def)\n\nlemma arc_linepath:\n  assumes \"a \\<noteq> b\" shows [simp]: \"arc (linepath a b)\"\nproof -\n  {\n    fix x y :: \"real\"\n    assume \"x *\\<^sub>R b + y *\\<^sub>R a = x *\\<^sub>R a + y *\\<^sub>R b\"\n    then have \"(x - y) *\\<^sub>R a = (x - y) *\\<^sub>R b\"\n      by (simp add: algebra_simps)\n    with assms have \"x = y\"\n      by simp\n  }\n  then show ?thesis\n    unfolding arc_def inj_on_def\n    by (simp add:  path_linepath) (force simp: algebra_simps linepath_def)\nqed\n\nlemma simple_path_linepath[intro]: \"a \\<noteq> b \\<Longrightarrow> simple_path (linepath a b)\"\n  by (simp add: arc_imp_simple_path arc_linepath)\n\nlemma linepath_trivial [simp]: \"linepath a a x = a\"\n  by (simp add: linepath_def real_vector.scale_left_diff_distrib)\n\nlemma linepath_refl: \"linepath a a = (\\<lambda>x. a)\"\n  by auto\n\nlemma subpath_refl: \"subpath a a g = linepath (g a) (g a)\"\n  by (simp add: subpath_def linepath_def algebra_simps)\n\nlemma linepath_of_real: \"(linepath (of_real a) (of_real b) x) = of_real ((1 - x)*a + x*b)\"\n  by (simp add: scaleR_conv_of_real linepath_def)\n\nlemma of_real_linepath: \"of_real (linepath a b x) = linepath (of_real a) (of_real b) x\"\n  by (metis linepath_of_real mult.right_neutral of_real_def real_scaleR_def)\n\nlemma inj_on_linepath:\n  assumes \"a \\<noteq> b\" shows \"inj_on (linepath a b) {0..1}\"\nproof (clarsimp simp: inj_on_def linepath_def)\n  fix x y\n  assume \"(1 - x) *\\<^sub>R a + x *\\<^sub>R b = (1 - y) *\\<^sub>R a + y *\\<^sub>R b\" \"0 \\<le> x\" \"x \\<le> 1\" \"0 \\<le> y\" \"y \\<le> 1\"\n  then have \"x *\\<^sub>R (a - b) = y *\\<^sub>R (a - b)\"\n    by (auto simp: algebra_simps)\n  then show \"x=y\"\n    using assms by auto\nqed\n\n\nsubsection\\<open>Segments via convex hulls\\<close>\n\nlemma segments_subset_convex_hull:\n    \"closed_segment a b \\<subseteq> (convex hull {a,b,c})\"\n    \"closed_segment a c \\<subseteq> (convex hull {a,b,c})\"\n    \"closed_segment b c \\<subseteq> (convex hull {a,b,c})\"\n    \"closed_segment b a \\<subseteq> (convex hull {a,b,c})\"\n    \"closed_segment c a \\<subseteq> (convex hull {a,b,c})\"\n    \"closed_segment c b \\<subseteq> (convex hull {a,b,c})\"\nby (auto simp: segment_convex_hull linepath_of_real  elim!: rev_subsetD [OF _ hull_mono])\n\nlemma midpoints_in_convex_hull:\n  assumes \"x \\<in> convex hull s\" \"y \\<in> convex hull s\"\n    shows \"midpoint x y \\<in> convex hull s\"\nproof -\n  have \"(1 - inverse(2)) *\\<^sub>R x + inverse(2) *\\<^sub>R y \\<in> convex hull s\"\n    apply (rule convexD_alt)\n    using assms\n    apply (auto simp: convex_convex_hull)\n    done\n  then show ?thesis\n    by (simp add: midpoint_def algebra_simps)\nqed\n\nlemma not_in_interior_convex_hull_3:\n  fixes a :: \"complex\"\n  shows \"a \\<notin> interior(convex hull {a,b,c})\"\n        \"b \\<notin> interior(convex hull {a,b,c})\"\n        \"c \\<notin> interior(convex hull {a,b,c})\"\n  by (auto simp: card_insert_le_m1 not_in_interior_convex_hull)\n\nlemma midpoint_in_closed_segment [simp]: \"midpoint a b \\<in> closed_segment a b\"\n  using midpoints_in_convex_hull segment_convex_hull by blast\n\nlemma midpoint_in_open_segment [simp]: \"midpoint a b \\<in> open_segment a b \\<longleftrightarrow> a \\<noteq> b\"\n  by (simp add: open_segment_def)\n\nlemma continuous_IVT_local_extremum:\n  fixes f :: \"'a::euclidean_space \\<Rightarrow> real\"\n  assumes contf: \"continuous_on (closed_segment a b) f\"\n      and \"a \\<noteq> b\" \"f a = f b\"\n  obtains z where \"z \\<in> open_segment a b\"\n                  \"(\\<forall>w \\<in> closed_segment a b. (f w) \\<le> (f z)) \\<or>\n                   (\\<forall>w \\<in> closed_segment a b. (f z) \\<le> (f w))\"\nproof -\n  obtain c where \"c \\<in> closed_segment a b\" and c: \"\\<And>y. y \\<in> closed_segment a b \\<Longrightarrow> f y \\<le> f c\"\n    using continuous_attains_sup [of \"closed_segment a b\" f] contf by auto\n  obtain d where \"d \\<in> closed_segment a b\" and d: \"\\<And>y. y \\<in> closed_segment a b \\<Longrightarrow> f d \\<le> f y\"\n    using continuous_attains_inf [of \"closed_segment a b\" f] contf by auto\n  show ?thesis\n  proof (cases \"c \\<in> open_segment a b \\<or> d \\<in> open_segment a b\")\n    case True\n    then show ?thesis\n      using c d that by blast\n  next\n    case False\n    then have \"(c = a \\<or> c = b) \\<and> (d = a \\<or> d = b)\"\n      by (simp add: \\<open>c \\<in> closed_segment a b\\<close> \\<open>d \\<in> closed_segment a b\\<close> open_segment_def)\n    with \\<open>a \\<noteq> b\\<close> \\<open>f a = f b\\<close> c d show ?thesis\n      by (rule_tac z = \"midpoint a b\" in that) (fastforce+)\n  qed\nqed\n\ntext\\<open>An injective map into R is also an open map w.r.T. the universe, and conversely. \\<close>\nproposition injective_eq_1d_open_map_UNIV:\n  fixes f :: \"real \\<Rightarrow> real\"\n  assumes contf: \"continuous_on S f\" and S: \"is_interval S\"\n    shows \"inj_on f S \\<longleftrightarrow> (\\<forall>T. open T \\<and> T \\<subseteq> S \\<longrightarrow> open(f ` T))\"\n          (is \"?lhs = ?rhs\")\nproof safe\n  fix T\n  assume injf: ?lhs and \"open T\" and \"T \\<subseteq> S\"\n  have \"\\<exists>U. open U \\<and> f x \\<in> U \\<and> U \\<subseteq> f ` T\" if \"x \\<in> T\" for x\n  proof -\n    obtain \\<delta> where \"\\<delta> > 0\" and \\<delta>: \"cball x \\<delta> \\<subseteq> T\"\n      using \\<open>open T\\<close> \\<open>x \\<in> T\\<close> open_contains_cball_eq by blast\n    show ?thesis\n    proof (intro exI conjI)\n      have \"closed_segment (x-\\<delta>) (x+\\<delta>) = {x-\\<delta>..x+\\<delta>}\"\n        using \\<open>0 < \\<delta>\\<close> by (auto simp: closed_segment_eq_real_ivl)\n      also have \"... \\<subseteq> S\"\n        using \\<delta> \\<open>T \\<subseteq> S\\<close> by (auto simp: dist_norm subset_eq)\n      finally have \"f ` (open_segment (x-\\<delta>) (x+\\<delta>)) = open_segment (f (x-\\<delta>)) (f (x+\\<delta>))\"\n        using continuous_injective_image_open_segment_1\n        by (metis continuous_on_subset [OF contf] inj_on_subset [OF injf])\n      then show \"open (f ` {x-\\<delta><..<x+\\<delta>})\"\n        using \\<open>0 < \\<delta>\\<close> by (simp add: open_segment_eq_real_ivl)\n      show \"f x \\<in> f ` {x - \\<delta><..<x + \\<delta>}\"\n        by (auto simp: \\<open>\\<delta> > 0\\<close>)\n      show \"f ` {x - \\<delta><..<x + \\<delta>} \\<subseteq> f ` T\"\n        using \\<delta> by (auto simp: dist_norm subset_iff)\n    qed\n  qed\n  with open_subopen show \"open (f ` T)\"\n    by blast\nnext\n  assume R: ?rhs\n  have False if xy: \"x \\<in> S\" \"y \\<in> S\" and \"f x = f y\" \"x \\<noteq> y\" for x y\n  proof -\n    have \"open (f ` open_segment x y)\"\n      using R\n      by (metis S convex_contains_open_segment is_interval_convex open_greaterThanLessThan open_segment_eq_real_ivl xy)\n    moreover\n    have \"continuous_on (closed_segment x y) f\"\n      by (meson S closed_segment_subset contf continuous_on_subset is_interval_convex that)\n    then obtain \\<xi> where \"\\<xi> \\<in> open_segment x y\"\n                    and \\<xi>: \"(\\<forall>w \\<in> closed_segment x y. (f w) \\<le> (f \\<xi>)) \\<or>\n                            (\\<forall>w \\<in> closed_segment x y. (f \\<xi>) \\<le> (f w))\"\n      using continuous_IVT_local_extremum [of x y f] \\<open>f x = f y\\<close> \\<open>x \\<noteq> y\\<close> by blast\n    ultimately obtain e where \"e>0\" and e: \"\\<And>u. dist u (f \\<xi>) < e \\<Longrightarrow> u \\<in> f ` open_segment x y\"\n      using open_dist by (metis image_eqI)\n    have fin: \"f \\<xi> + (e/2) \\<in> f ` open_segment x y\" \"f \\<xi> - (e/2) \\<in> f ` open_segment x y\"\n      using e [of \"f \\<xi> + (e/2)\"] e [of \"f \\<xi> - (e/2)\"] \\<open>e > 0\\<close> by (auto simp: dist_norm)\n    show ?thesis\n      using \\<xi> \\<open>0 < e\\<close> fin open_closed_segment by fastforce\n  qed\n  then show ?lhs\n    by (force simp: inj_on_def)\nqed\n\nsubsection \\<open>Bounding a point away from a path\\<close>\n\nlemma not_on_path_ball:\n  fixes g :: \"real \\<Rightarrow> 'a::heine_borel\"\n  assumes \"path g\"\n    and \"z \\<notin> path_image g\"\n  shows \"\\<exists>e > 0. ball z e \\<inter> path_image g = {}\"\nproof -\n  obtain a where \"a \\<in> path_image g\" \"\\<forall>y \\<in> path_image g. dist z a \\<le> dist z y\"\n    apply (rule distance_attains_inf[OF _ path_image_nonempty, of g z])\n    using compact_path_image[THEN compact_imp_closed, OF assms(1)] by auto\n  then show ?thesis\n    apply (rule_tac x=\"dist z a\" in exI)\n    using assms(2)\n    apply (auto intro!: dist_pos_lt)\n    done\nqed\n\nlemma not_on_path_cball:\n  fixes g :: \"real \\<Rightarrow> 'a::heine_borel\"\n  assumes \"path g\"\n    and \"z \\<notin> path_image g\"\n  shows \"\\<exists>e>0. cball z e \\<inter> (path_image g) = {}\"\nproof -\n  obtain e where \"ball z e \\<inter> path_image g = {}\" \"e > 0\"\n    using not_on_path_ball[OF assms] by auto\n  moreover have \"cball z (e/2) \\<subseteq> ball z e\"\n    using \\<open>e > 0\\<close> by auto\n  ultimately show ?thesis\n    apply (rule_tac x=\"e/2\" in exI)\n    apply auto\n    done\nqed\n\n\nsection \\<open>Path component, considered as a \"joinability\" relation (from Tom Hales)\\<close>\n\ndefinition \"path_component s x y \\<longleftrightarrow>\n  (\\<exists>g. path g \\<and> path_image g \\<subseteq> s \\<and> pathstart g = x \\<and> pathfinish g = y)\"\n\nabbreviation\n   \"path_component_set s x \\<equiv> Collect (path_component s x)\"\n\nlemmas path_defs = path_def pathstart_def pathfinish_def path_image_def path_component_def\n\nlemma path_component_mem:\n  assumes \"path_component s x y\"\n  shows \"x \\<in> s\" and \"y \\<in> s\"\n  using assms\n  unfolding path_defs\n  by auto\n\nlemma path_component_refl:\n  assumes \"x \\<in> s\"\n  shows \"path_component s x x\"\n  unfolding path_defs\n  apply (rule_tac x=\"\\<lambda>u. x\" in exI)\n  using assms\n  apply (auto intro!: continuous_intros)\n  done\n\nlemma path_component_refl_eq: \"path_component s x x \\<longleftrightarrow> x \\<in> s\"\n  by (auto intro!: path_component_mem path_component_refl)\n\nlemma path_component_sym: \"path_component s x y \\<Longrightarrow> path_component s y x\"\n  unfolding path_component_def\n  apply (erule exE)\n  apply (rule_tac x=\"reversepath g\" in exI)\n  apply auto\n  done\n\nlemma path_component_trans:\n  assumes \"path_component s x y\" and \"path_component s y z\"\n  shows \"path_component s x z\"\n  using assms\n  unfolding path_component_def\n  apply (elim exE)\n  apply (rule_tac x=\"g +++ ga\" in exI)\n  apply (auto simp add: path_image_join)\n  done\n\nlemma path_component_of_subset: \"s \\<subseteq> t \\<Longrightarrow> path_component s x y \\<Longrightarrow> path_component t x y\"\n  unfolding path_component_def by auto\n\nlemma path_connected_linepath:\n    fixes s :: \"'a::real_normed_vector set\"\n    shows \"closed_segment a b \\<subseteq> s \\<Longrightarrow> path_component s a b\"\n  apply (simp add: path_component_def)\n  apply (rule_tac x=\"linepath a b\" in exI, auto)\n  done\n\n\nsubsubsection \\<open>Path components as sets\\<close>\n\nlemma path_component_set:\n  \"path_component_set s x =\n    {y. (\\<exists>g. path g \\<and> path_image g \\<subseteq> s \\<and> pathstart g = x \\<and> pathfinish g = y)}\"\n  by (auto simp: path_component_def)\n\nlemma path_component_subset: \"path_component_set s x \\<subseteq> s\"\n  by (auto simp add: path_component_mem(2))\n\nlemma path_component_eq_empty: \"path_component_set s x = {} \\<longleftrightarrow> x \\<notin> s\"\n  using path_component_mem path_component_refl_eq\n    by fastforce\n\nlemma path_component_mono:\n     \"s \\<subseteq> t \\<Longrightarrow> (path_component_set s x) \\<subseteq> (path_component_set t x)\"\n  by (simp add: Collect_mono path_component_of_subset)\n\nlemma path_component_eq:\n   \"y \\<in> path_component_set s x \\<Longrightarrow> path_component_set s y = path_component_set s x\"\nby (metis (no_types, lifting) Collect_cong mem_Collect_eq path_component_sym path_component_trans)\n\nsubsection \\<open>Path connectedness of a space\\<close>\n\ndefinition \"path_connected s \\<longleftrightarrow>\n  (\\<forall>x\\<in>s. \\<forall>y\\<in>s. \\<exists>g. path g \\<and> path_image g \\<subseteq> s \\<and> pathstart g = x \\<and> pathfinish g = y)\"\n\nlemma path_connected_component: \"path_connected s \\<longleftrightarrow> (\\<forall>x\\<in>s. \\<forall>y\\<in>s. path_component s x y)\"\n  unfolding path_connected_def path_component_def by auto\n\nlemma path_connected_component_set: \"path_connected s \\<longleftrightarrow> (\\<forall>x\\<in>s. path_component_set s x = s)\"\n  unfolding path_connected_component path_component_subset\n  using path_component_mem by blast\n\nlemma path_component_maximal:\n     \"\\<lbrakk>x \\<in> t; path_connected t; t \\<subseteq> s\\<rbrakk> \\<Longrightarrow> t \\<subseteq> (path_component_set s x)\"\n  by (metis path_component_mono path_connected_component_set)\n\nlemma convex_imp_path_connected:\n  fixes s :: \"'a::real_normed_vector set\"\n  assumes \"convex s\"\n  shows \"path_connected s\"\n  unfolding path_connected_def\n  apply rule\n  apply rule\n  apply (rule_tac x = \"linepath x y\" in exI)\n  unfolding path_image_linepath\n  using assms [unfolded convex_contains_segment]\n  apply auto\n  done\n\nlemma path_connected_UNIV [iff]: \"path_connected (UNIV :: 'a::real_normed_vector set)\"\n  by (simp add: convex_imp_path_connected)\n\nlemma path_component_UNIV: \"path_component_set UNIV x = (UNIV :: 'a::real_normed_vector set)\"\n  using path_connected_component_set by auto\n\nlemma path_connected_imp_connected:\n  assumes \"path_connected s\"\n  shows \"connected s\"\n  unfolding connected_def not_ex\n  apply rule\n  apply rule\n  apply (rule ccontr)\n  unfolding not_not\n  apply (elim conjE)\nproof -\n  fix e1 e2\n  assume as: \"open e1\" \"open e2\" \"s \\<subseteq> e1 \\<union> e2\" \"e1 \\<inter> e2 \\<inter> s = {}\" \"e1 \\<inter> s \\<noteq> {}\" \"e2 \\<inter> s \\<noteq> {}\"\n  then obtain x1 x2 where obt:\"x1 \\<in> e1 \\<inter> s\" \"x2 \\<in> e2 \\<inter> s\"\n    by auto\n  then obtain g where g: \"path g\" \"path_image g \\<subseteq> s\" \"pathstart g = x1\" \"pathfinish g = x2\"\n    using assms[unfolded path_connected_def,rule_format,of x1 x2] by auto\n  have *: \"connected {0..1::real}\"\n    by (auto intro!: convex_connected convex_real_interval)\n  have \"{0..1} \\<subseteq> {x \\<in> {0..1}. g x \\<in> e1} \\<union> {x \\<in> {0..1}. g x \\<in> e2}\"\n    using as(3) g(2)[unfolded path_defs] by blast\n  moreover have \"{x \\<in> {0..1}. g x \\<in> e1} \\<inter> {x \\<in> {0..1}. g x \\<in> e2} = {}\"\n    using as(4) g(2)[unfolded path_defs]\n    unfolding subset_eq\n    by auto\n  moreover have \"{x \\<in> {0..1}. g x \\<in> e1} \\<noteq> {} \\<and> {x \\<in> {0..1}. g x \\<in> e2} \\<noteq> {}\"\n    using g(3,4)[unfolded path_defs]\n    using obt\n    by (simp add: ex_in_conv [symmetric], metis zero_le_one order_refl)\n  ultimately show False\n    using *[unfolded connected_local not_ex, rule_format,\n      of \"{x\\<in>{0..1}. g x \\<in> e1}\" \"{x\\<in>{0..1}. g x \\<in> e2}\"]\n    using continuous_openin_preimage_gen[OF g(1)[unfolded path_def] as(1)]\n    using continuous_openin_preimage_gen[OF g(1)[unfolded path_def] as(2)]\n    by auto\nqed\n\nlemma open_path_component:\n  fixes s :: \"'a::real_normed_vector set\"\n  assumes \"open s\"\n  shows \"open (path_component_set s x)\"\n  unfolding open_contains_ball\nproof\n  fix y\n  assume as: \"y \\<in> path_component_set s x\"\n  then have \"y \\<in> s\"\n    apply -\n    apply (rule path_component_mem(2))\n    unfolding mem_Collect_eq\n    apply auto\n    done\n  then obtain e where e: \"e > 0\" \"ball y e \\<subseteq> s\"\n    using assms[unfolded open_contains_ball]\n    by auto\n  show \"\\<exists>e > 0. ball y e \\<subseteq> path_component_set s x\"\n    apply (rule_tac x=e in exI)\n    apply (rule,rule \\<open>e>0\\<close>)\n    apply rule\n    unfolding mem_ball mem_Collect_eq\n  proof -\n    fix z\n    assume \"dist y z < e\"\n    then show \"path_component s x z\"\n      apply (rule_tac path_component_trans[of _ _ y])\n      defer\n      apply (rule path_component_of_subset[OF e(2)])\n      apply (rule convex_imp_path_connected[OF convex_ball, unfolded path_connected_component, rule_format])\n      using \\<open>e > 0\\<close> as\n      apply auto\n      done\n  qed\nqed\n\nlemma open_non_path_component:\n  fixes s :: \"'a::real_normed_vector set\"\n  assumes \"open s\"\n  shows \"open (s - path_component_set s x)\"\n  unfolding open_contains_ball\nproof\n  fix y\n  assume as: \"y \\<in> s - path_component_set s x\"\n  then obtain e where e: \"e > 0\" \"ball y e \\<subseteq> s\"\n    using assms [unfolded open_contains_ball]\n    by auto\n  show \"\\<exists>e>0. ball y e \\<subseteq> s - path_component_set s x\"\n    apply (rule_tac x=e in exI)\n    apply rule\n    apply (rule \\<open>e>0\\<close>)\n    apply rule\n    apply rule\n    defer\n  proof (rule ccontr)\n    fix z\n    assume \"z \\<in> ball y e\" \"\\<not> z \\<notin> path_component_set s x\"\n    then have \"y \\<in> path_component_set s x\"\n      unfolding not_not mem_Collect_eq using \\<open>e>0\\<close>\n      apply -\n      apply (rule path_component_trans, assumption)\n      apply (rule path_component_of_subset[OF e(2)])\n      apply (rule convex_imp_path_connected[OF convex_ball, unfolded path_connected_component, rule_format])\n      apply auto\n      done\n    then show False\n      using as by auto\n  qed (insert e(2), auto)\nqed\n\nlemma connected_open_path_connected:\n  fixes s :: \"'a::real_normed_vector set\"\n  assumes \"open s\"\n    and \"connected s\"\n  shows \"path_connected s\"\n  unfolding path_connected_component_set\nproof (rule, rule, rule path_component_subset, rule)\n  fix x y\n  assume \"x \\<in> s\" and \"y \\<in> s\"\n  show \"y \\<in> path_component_set s x\"\n  proof (rule ccontr)\n    assume \"\\<not> ?thesis\"\n    moreover have \"path_component_set s x \\<inter> s \\<noteq> {}\"\n      using \\<open>x \\<in> s\\<close> path_component_eq_empty path_component_subset[of s x]\n      by auto\n    ultimately\n    show False\n      using \\<open>y \\<in> s\\<close> open_non_path_component[OF assms(1)] open_path_component[OF assms(1)]\n      using assms(2)[unfolded connected_def not_ex, rule_format,\n        of \"path_component_set s x\" \"s - path_component_set s x\"]\n      by auto\n  qed\nqed\n\nlemma path_connected_continuous_image:\n  assumes \"continuous_on s f\"\n    and \"path_connected s\"\n  shows \"path_connected (f ` s)\"\n  unfolding path_connected_def\nproof (rule, rule)\n  fix x' y'\n  assume \"x' \\<in> f ` s\" \"y' \\<in> f ` s\"\n  then obtain x y where x: \"x \\<in> s\" and y: \"y \\<in> s\" and x': \"x' = f x\" and y': \"y' = f y\"\n    by auto\n  from x y obtain g where \"path g \\<and> path_image g \\<subseteq> s \\<and> pathstart g = x \\<and> pathfinish g = y\"\n    using assms(2)[unfolded path_connected_def] by fast\n  then show \"\\<exists>g. path g \\<and> path_image g \\<subseteq> f ` s \\<and> pathstart g = x' \\<and> pathfinish g = y'\"\n    unfolding x' y'\n    apply (rule_tac x=\"f \\<circ> g\" in exI)\n    unfolding path_defs\n    apply (intro conjI continuous_on_compose continuous_on_subset[OF assms(1)])\n    apply auto\n    done\nqed\n\nlemma path_connected_segment:\n    fixes a :: \"'a::real_normed_vector\"\n    shows \"path_connected (closed_segment a b)\"\n  by (simp add: convex_imp_path_connected)\n\nlemma path_connected_open_segment:\n    fixes a :: \"'a::real_normed_vector\"\n    shows \"path_connected (open_segment a b)\"\n  by (simp add: convex_imp_path_connected)\n\nlemma homeomorphic_path_connectedness:\n  \"s homeomorphic t \\<Longrightarrow> path_connected s \\<longleftrightarrow> path_connected t\"\n  unfolding homeomorphic_def homeomorphism_def by (metis path_connected_continuous_image)\n\nlemma path_connected_empty: \"path_connected {}\"\n  unfolding path_connected_def by auto\n\nlemma path_connected_singleton: \"path_connected {a}\"\n  unfolding path_connected_def pathstart_def pathfinish_def path_image_def\n  apply clarify\n  apply (rule_tac x=\"\\<lambda>x. a\" in exI)\n  apply (simp add: image_constant_conv)\n  apply (simp add: path_def continuous_on_const)\n  done\n\nlemma path_connected_Un:\n  assumes \"path_connected s\"\n    and \"path_connected t\"\n    and \"s \\<inter> t \\<noteq> {}\"\n  shows \"path_connected (s \\<union> t)\"\n  unfolding path_connected_component\nproof (rule, rule)\n  fix x y\n  assume as: \"x \\<in> s \\<union> t\" \"y \\<in> s \\<union> t\"\n  from assms(3) obtain z where \"z \\<in> s \\<inter> t\"\n    by auto\n  then show \"path_component (s \\<union> t) x y\"\n    using as and assms(1-2)[unfolded path_connected_component]\n    apply -\n    apply (erule_tac[!] UnE)+\n    apply (rule_tac[2-3] path_component_trans[of _ _ z])\n    apply (auto simp add:path_component_of_subset [OF Un_upper1] path_component_of_subset[OF Un_upper2])\n    done\nqed\n\nlemma path_connected_UNION:\n  assumes \"\\<And>i. i \\<in> A \\<Longrightarrow> path_connected (S i)\"\n    and \"\\<And>i. i \\<in> A \\<Longrightarrow> z \\<in> S i\"\n  shows \"path_connected (\\<Union>i\\<in>A. S i)\"\n  unfolding path_connected_component\nproof clarify\n  fix x i y j\n  assume *: \"i \\<in> A\" \"x \\<in> S i\" \"j \\<in> A\" \"y \\<in> S j\"\n  then have \"path_component (S i) x z\" and \"path_component (S j) z y\"\n    using assms by (simp_all add: path_connected_component)\n  then have \"path_component (\\<Union>i\\<in>A. S i) x z\" and \"path_component (\\<Union>i\\<in>A. S i) z y\"\n    using *(1,3) by (auto elim!: path_component_of_subset [rotated])\n  then show \"path_component (\\<Union>i\\<in>A. S i) x y\"\n    by (rule path_component_trans)\nqed\n\nlemma path_component_path_image_pathstart:\n  assumes p: \"path p\" and x: \"x \\<in> path_image p\"\n  shows \"path_component (path_image p) (pathstart p) x\"\nusing x\nproof (clarsimp simp add: path_image_def)\n  fix y\n  assume \"x = p y\" and y: \"0 \\<le> y\" \"y \\<le> 1\"\n  show \"path_component (p ` {0..1}) (pathstart p) (p y)\"\n  proof (cases \"y=0\")\n    case True then show ?thesis\n      by (simp add: path_component_refl_eq pathstart_def)\n  next\n    case False have \"continuous_on {0..1} (p o (op*y))\"\n      apply (rule continuous_intros)+\n      using p [unfolded path_def] y\n      apply (auto simp: mult_le_one intro: continuous_on_subset [of _ p])\n      done\n    then have \"path (\\<lambda>u. p (y * u))\"\n      by (simp add: path_def)\n    then show ?thesis\n      apply (simp add: path_component_def)\n      apply (rule_tac x = \"\\<lambda>u. p (y * u)\" in exI)\n      apply (intro conjI)\n      using y False\n      apply (auto simp: mult_le_one pathstart_def pathfinish_def path_image_def)\n      done\n  qed\nqed\n\nlemma path_connected_path_image: \"path p \\<Longrightarrow> path_connected(path_image p)\"\n  unfolding path_connected_component\n  by (meson path_component_path_image_pathstart path_component_sym path_component_trans)\n\nlemma path_connected_path_component:\n   \"path_connected (path_component_set s x)\"\nproof -\n  { fix y z\n    assume pa: \"path_component s x y\" \"path_component s x z\"\n    then have pae: \"path_component_set s x = path_component_set s y\"\n      using path_component_eq by auto\n    have yz: \"path_component s y z\"\n      using pa path_component_sym path_component_trans by blast\n    then have \"\\<exists>g. path g \\<and> path_image g \\<subseteq> path_component_set s x \\<and> pathstart g = y \\<and> pathfinish g = z\"\n      apply (simp add: path_component_def, clarify)\n      apply (rule_tac x=g in exI)\n      by (simp add: pae path_component_maximal path_connected_path_image pathstart_in_path_image)\n  }\n  then show ?thesis\n    by (simp add: path_connected_def)\nqed\n\nlemma path_component: \"path_component s x y \\<longleftrightarrow> (\\<exists>t. path_connected t \\<and> t \\<subseteq> s \\<and> x \\<in> t \\<and> y \\<in> t)\"\n  apply (intro iffI)\n  apply (metis path_connected_path_image path_defs(5) pathfinish_in_path_image pathstart_in_path_image)\n  using path_component_of_subset path_connected_component by blast\n\nlemma path_component_path_component [simp]:\n   \"path_component_set (path_component_set s x) x = path_component_set s x\"\nproof (cases \"x \\<in> s\")\n  case True show ?thesis\n    apply (rule subset_antisym)\n    apply (simp add: path_component_subset)\n    by (simp add: True path_component_maximal path_component_refl path_connected_path_component)\nnext\n  case False then show ?thesis\n    by (metis False empty_iff path_component_eq_empty)\nqed\n\nlemma path_component_subset_connected_component:\n   \"(path_component_set s x) \\<subseteq> (connected_component_set s x)\"\nproof (cases \"x \\<in> s\")\n  case True show ?thesis\n    apply (rule connected_component_maximal)\n    apply (auto simp: True path_component_subset path_component_refl path_connected_imp_connected path_connected_path_component)\n    done\nnext\n  case False then show ?thesis\n    using path_component_eq_empty by auto\nqed\n\nsubsection\\<open>Lemmas about path-connectedness\\<close>\n\nlemma path_connected_linear_image:\n  fixes f :: \"'a::real_normed_vector \\<Rightarrow> 'b::real_normed_vector\"\n  assumes \"path_connected s\" \"bounded_linear f\"\n    shows \"path_connected(f ` s)\"\nby (auto simp: linear_continuous_on assms path_connected_continuous_image)\n\nlemma is_interval_path_connected: \"is_interval s \\<Longrightarrow> path_connected s\"\n  by (simp add: convex_imp_path_connected is_interval_convex)\n\nlemma linear_homeomorphism_image:\n  fixes f :: \"'a::euclidean_space \\<Rightarrow> 'b::euclidean_space\"\n  assumes \"linear f\" \"inj f\"\n    obtains g where \"homeomorphism (f ` S) S g f\"\nusing linear_injective_left_inverse [OF assms]\napply clarify\napply (rule_tac g=g in that)\nusing assms\napply (auto simp: homeomorphism_def eq_id_iff [symmetric] image_comp comp_def linear_conv_bounded_linear linear_continuous_on)\ndone\n\nlemma linear_homeomorphic_image:\n  fixes f :: \"'a::euclidean_space \\<Rightarrow> 'b::euclidean_space\"\n  assumes \"linear f\" \"inj f\"\n    shows \"S homeomorphic f ` S\"\nby (meson homeomorphic_def homeomorphic_sym linear_homeomorphism_image [OF assms])\n\nlemma path_connected_Times:\n  assumes \"path_connected s\" \"path_connected t\"\n    shows \"path_connected (s \\<times> t)\"\nproof (simp add: path_connected_def Sigma_def, clarify)\n  fix x1 y1 x2 y2\n  assume \"x1 \\<in> s\" \"y1 \\<in> t\" \"x2 \\<in> s\" \"y2 \\<in> t\"\n  obtain g where \"path g\" and g: \"path_image g \\<subseteq> s\" and gs: \"pathstart g = x1\" and gf: \"pathfinish g = x2\"\n    using \\<open>x1 \\<in> s\\<close> \\<open>x2 \\<in> s\\<close> assms by (force simp: path_connected_def)\n  obtain h where \"path h\" and h: \"path_image h \\<subseteq> t\" and hs: \"pathstart h = y1\" and hf: \"pathfinish h = y2\"\n    using \\<open>y1 \\<in> t\\<close> \\<open>y2 \\<in> t\\<close> assms by (force simp: path_connected_def)\n  have \"path (\\<lambda>z. (x1, h z))\"\n    using \\<open>path h\\<close>\n    apply (simp add: path_def)\n    apply (rule continuous_on_compose2 [where f = h])\n    apply (rule continuous_intros | force)+\n    done\n  moreover have \"path (\\<lambda>z. (g z, y2))\"\n    using \\<open>path g\\<close>\n    apply (simp add: path_def)\n    apply (rule continuous_on_compose2 [where f = g])\n    apply (rule continuous_intros | force)+\n    done\n  ultimately have 1: \"path ((\\<lambda>z. (x1, h z)) +++ (\\<lambda>z. (g z, y2)))\"\n    by (metis hf gs path_join_imp pathstart_def pathfinish_def)\n  have \"path_image ((\\<lambda>z. (x1, h z)) +++ (\\<lambda>z. (g z, y2))) \\<subseteq> path_image (\\<lambda>z. (x1, h z)) \\<union> path_image (\\<lambda>z. (g z, y2))\"\n    by (rule Path_Connected.path_image_join_subset)\n  also have \"... \\<subseteq> (\\<Union>x\\<in>s. \\<Union>x1\\<in>t. {(x, x1)})\"\n    using g h \\<open>x1 \\<in> s\\<close> \\<open>y2 \\<in> t\\<close> by (force simp: path_image_def)\n  finally have 2: \"path_image ((\\<lambda>z. (x1, h z)) +++ (\\<lambda>z. (g z, y2))) \\<subseteq> (\\<Union>x\\<in>s. \\<Union>x1\\<in>t. {(x, x1)})\" .\n  show \"\\<exists>g. path g \\<and> path_image g \\<subseteq> (\\<Union>x\\<in>s. \\<Union>x1\\<in>t. {(x, x1)}) \\<and>\n            pathstart g = (x1, y1) \\<and> pathfinish g = (x2, y2)\"\n    apply (intro exI conjI)\n       apply (rule 1)\n      apply (rule 2)\n     apply (metis hs pathstart_def pathstart_join)\n    by (metis gf pathfinish_def pathfinish_join)\nqed\n\nlemma is_interval_path_connected_1:\n  fixes s :: \"real set\"\n  shows \"is_interval s \\<longleftrightarrow> path_connected s\"\nusing is_interval_connected_1 is_interval_path_connected path_connected_imp_connected by blast\n\n\nlemma Union_path_component [simp]:\n   \"Union {path_component_set S x |x. x \\<in> S} = S\"\napply (rule subset_antisym)\nusing path_component_subset apply force\nusing path_component_refl by auto\n\nlemma path_component_disjoint:\n   \"disjnt (path_component_set S a) (path_component_set S b) \\<longleftrightarrow>\n    (a \\<notin> path_component_set S b)\"\napply (auto simp: disjnt_def)\nusing path_component_eq apply fastforce\nusing path_component_sym path_component_trans by blast\n\nlemma path_component_eq_eq:\n   \"path_component S x = path_component S y \\<longleftrightarrow>\n        (x \\<notin> S) \\<and> (y \\<notin> S) \\<or> x \\<in> S \\<and> y \\<in> S \\<and> path_component S x y\"\napply (rule iffI, metis (no_types) path_component_mem(1) path_component_refl)\napply (erule disjE, metis Collect_empty_eq_bot path_component_eq_empty)\napply (rule ext)\napply (metis path_component_trans path_component_sym)\ndone\n\nlemma path_component_unique:\n  assumes \"x \\<in> c\" \"c \\<subseteq> S\" \"path_connected c\"\n          \"\\<And>c'. \\<lbrakk>x \\<in> c'; c' \\<subseteq> S; path_connected c'\\<rbrakk> \\<Longrightarrow> c' \\<subseteq> c\"\n   shows \"path_component_set S x = c\"\napply (rule subset_antisym)\nusing assms\napply (metis mem_Collect_eq subsetCE path_component_eq_eq path_component_subset path_connected_path_component)\nby (simp add: assms path_component_maximal)\n\nlemma path_component_intermediate_subset:\n   \"path_component_set u a \\<subseteq> t \\<and> t \\<subseteq> u\n        \\<Longrightarrow> path_component_set t a = path_component_set u a\"\nby (metis (no_types) path_component_mono path_component_path_component subset_antisym)\n\nlemma complement_path_component_Union:\n  fixes x :: \"'a :: topological_space\"\n  shows \"S - path_component_set S x =\n         \\<Union>({path_component_set S y| y. y \\<in> S} - {path_component_set S x})\"\nproof -\n  have *: \"(\\<And>x. x \\<in> S - {a} \\<Longrightarrow> disjnt a x) \\<Longrightarrow> \\<Union>S - a = \\<Union>(S - {a})\"\n    for a::\"'a set\" and S\n    by (auto simp: disjnt_def)\n  have \"\\<And>y. y \\<in> {path_component_set S x |x. x \\<in> S} - {path_component_set S x}\n            \\<Longrightarrow> disjnt (path_component_set S x) y\"\n    using path_component_disjoint path_component_eq by fastforce\n  then have \"\\<Union>{path_component_set S x |x. x \\<in> S} - path_component_set S x =\n             \\<Union>({path_component_set S y |y. y \\<in> S} - {path_component_set S x})\"\n    by (meson *)\n  then show ?thesis by simp\nqed\n\n\nsubsection \\<open>Sphere is path-connected\\<close>\n\nlemma path_connected_punctured_universe:\n  assumes \"2 \\<le> DIM('a::euclidean_space)\"\n  shows \"path_connected (- {a::'a})\"\nproof -\n  let ?A = \"{x::'a. \\<exists>i\\<in>Basis. x \\<bullet> i < a \\<bullet> i}\"\n  let ?B = \"{x::'a. \\<exists>i\\<in>Basis. a \\<bullet> i < x \\<bullet> i}\"\n\n  have A: \"path_connected ?A\"\n    unfolding Collect_bex_eq\n  proof (rule path_connected_UNION)\n    fix i :: 'a\n    assume \"i \\<in> Basis\"\n    then show \"(\\<Sum>i\\<in>Basis. (a \\<bullet> i - 1)*\\<^sub>R i) \\<in> {x::'a. x \\<bullet> i < a \\<bullet> i}\"\n      by simp\n    show \"path_connected {x. x \\<bullet> i < a \\<bullet> i}\"\n      using convex_imp_path_connected [OF convex_halfspace_lt, of i \"a \\<bullet> i\"]\n      by (simp add: inner_commute)\n  qed\n  have B: \"path_connected ?B\"\n    unfolding Collect_bex_eq\n  proof (rule path_connected_UNION)\n    fix i :: 'a\n    assume \"i \\<in> Basis\"\n    then show \"(\\<Sum>i\\<in>Basis. (a \\<bullet> i + 1) *\\<^sub>R i) \\<in> {x::'a. a \\<bullet> i < x \\<bullet> i}\"\n      by simp\n    show \"path_connected {x. a \\<bullet> i < x \\<bullet> i}\"\n      using convex_imp_path_connected [OF convex_halfspace_gt, of \"a \\<bullet> i\" i]\n      by (simp add: inner_commute)\n  qed\n  obtain S :: \"'a set\" where \"S \\<subseteq> Basis\" and \"card S = Suc (Suc 0)\"\n    using ex_card[OF assms]\n    by auto\n  then obtain b0 b1 :: 'a where \"b0 \\<in> Basis\" and \"b1 \\<in> Basis\" and \"b0 \\<noteq> b1\"\n    unfolding card_Suc_eq by auto\n  then have \"a + b0 - b1 \\<in> ?A \\<inter> ?B\"\n    by (auto simp: inner_simps inner_Basis)\n  then have \"?A \\<inter> ?B \\<noteq> {}\"\n    by fast\n  with A B have \"path_connected (?A \\<union> ?B)\"\n    by (rule path_connected_Un)\n  also have \"?A \\<union> ?B = {x. \\<exists>i\\<in>Basis. x \\<bullet> i \\<noteq> a \\<bullet> i}\"\n    unfolding neq_iff bex_disj_distrib Collect_disj_eq ..\n  also have \"\\<dots> = {x. x \\<noteq> a}\"\n    unfolding euclidean_eq_iff [where 'a='a]\n    by (simp add: Bex_def)\n  also have \"\\<dots> = - {a}\"\n    by auto\n  finally show ?thesis .\nqed\n\ncorollary connected_punctured_universe:\n  \"2 \\<le> DIM('N::euclidean_space) \\<Longrightarrow> connected(- {a::'N})\"\n  by (simp add: path_connected_punctured_universe path_connected_imp_connected)\n\nlemma path_connected_sphere:\n  assumes \"2 \\<le> DIM('a::euclidean_space)\"\n  shows \"path_connected {x::'a. norm (x - a) = r}\"\nproof (rule linorder_cases [of r 0])\n  assume \"r < 0\"\n  then have \"{x::'a. norm(x - a) = r} = {}\"\n    by auto\n  then show ?thesis\n    using path_connected_empty by simp\nnext\n  assume \"r = 0\"\n  then show ?thesis\n    using path_connected_singleton by simp\nnext\n  assume r: \"0 < r\"\n  have *: \"{x::'a. norm(x - a) = r} = (\\<lambda>x. a + r *\\<^sub>R x) ` {x. norm x = 1}\"\n    apply (rule set_eqI)\n    apply rule\n    unfolding image_iff\n    apply (rule_tac x=\"(1/r) *\\<^sub>R (x - a)\" in bexI)\n    unfolding mem_Collect_eq norm_scaleR\n    using r\n    apply (auto simp add: scaleR_right_diff_distrib)\n    done\n  have **: \"{x::'a. norm x = 1} = (\\<lambda>x. (1/norm x) *\\<^sub>R x) ` (- {0})\"\n    apply (rule set_eqI)\n    apply rule\n    unfolding image_iff\n    apply (rule_tac x=x in bexI)\n    unfolding mem_Collect_eq\n    apply (auto split: if_split_asm)\n    done\n  have \"continuous_on (- {0}) (\\<lambda>x::'a. 1 / norm x)\"\n    by (auto intro!: continuous_intros)\n  then show ?thesis\n    unfolding * **\n    using path_connected_punctured_universe[OF assms]\n    by (auto intro!: path_connected_continuous_image continuous_intros)\nqed\n\ncorollary connected_sphere: \"2 \\<le> DIM('a::euclidean_space) \\<Longrightarrow> connected {x::'a. norm (x - a) = r}\"\n  using path_connected_sphere path_connected_imp_connected\n  by auto\n\ncorollary path_connected_complement_bounded_convex:\n    fixes s :: \"'a :: euclidean_space set\"\n    assumes \"bounded s\" \"convex s\" and 2: \"2 \\<le> DIM('a)\"\n    shows \"path_connected (- s)\"\nproof (cases \"s={}\")\n  case True then show ?thesis\n    using convex_imp_path_connected by auto\nnext\n  case False\n  then obtain a where \"a \\<in> s\" by auto\n  { fix x y assume \"x \\<notin> s\" \"y \\<notin> s\"\n    then have \"x \\<noteq> a\" \"y \\<noteq> a\" using \\<open>a \\<in> s\\<close> by auto\n    then have bxy: \"bounded(insert x (insert y s))\"\n      by (simp add: \\<open>bounded s\\<close>)\n    then obtain B::real where B: \"0 < B\" and Bx: \"norm (a - x) < B\" and By: \"norm (a - y) < B\"\n                          and \"s \\<subseteq> ball a B\"\n      using bounded_subset_ballD [OF bxy, of a] by (auto simp: dist_norm)\n    define C where \"C = B / norm(x - a)\"\n    { fix u\n      assume u: \"(1 - u) *\\<^sub>R x + u *\\<^sub>R (a + C *\\<^sub>R (x - a)) \\<in> s\" and \"0 \\<le> u\" \"u \\<le> 1\"\n      have CC: \"1 \\<le> 1 + (C - 1) * u\"\n        using \\<open>x \\<noteq> a\\<close> \\<open>0 \\<le> u\\<close>\n        apply (simp add: C_def divide_simps norm_minus_commute)\n        using Bx by auto\n      have *: \"\\<And>v. (1 - u) *\\<^sub>R x + u *\\<^sub>R (a + v *\\<^sub>R (x - a)) = a + (1 + (v - 1) * u) *\\<^sub>R (x - a)\"\n        by (simp add: algebra_simps)\n      have \"a + ((1 / (1 + C * u - u)) *\\<^sub>R x + ((u / (1 + C * u - u)) *\\<^sub>R a + (C * u / (1 + C * u - u)) *\\<^sub>R x)) =\n            (1 + (u / (1 + C * u - u))) *\\<^sub>R a + ((1 / (1 + C * u - u)) + (C * u / (1 + C * u - u))) *\\<^sub>R x\"\n        by (simp add: algebra_simps)\n      also have \"... = (1 + (u / (1 + C * u - u))) *\\<^sub>R a + (1 + (u / (1 + C * u - u))) *\\<^sub>R x\"\n        using CC by (simp add: field_simps)\n      also have \"... = x + (1 + (u / (1 + C * u - u))) *\\<^sub>R a + (u / (1 + C * u - u)) *\\<^sub>R x\"\n        by (simp add: algebra_simps)\n      also have \"... = x + ((1 / (1 + C * u - u)) *\\<^sub>R a +\n              ((u / (1 + C * u - u)) *\\<^sub>R x + (C * u / (1 + C * u - u)) *\\<^sub>R a))\"\n        using CC by (simp add: field_simps) (simp add: add_divide_distrib scaleR_add_left)\n      finally have xeq: \"(1 - 1 / (1 + (C - 1) * u)) *\\<^sub>R a + (1 / (1 + (C - 1) * u)) *\\<^sub>R (a + (1 + (C - 1) * u) *\\<^sub>R (x - a)) = x\"\n        by (simp add: algebra_simps)\n      have False\n        using \\<open>convex s\\<close>\n        apply (simp add: convex_alt)\n        apply (drule_tac x=a in bspec)\n         apply (rule  \\<open>a \\<in> s\\<close>)\n        apply (drule_tac x=\"a + (1 + (C - 1) * u) *\\<^sub>R (x - a)\" in bspec)\n         using u apply (simp add: *)\n        apply (drule_tac x=\"1 / (1 + (C - 1) * u)\" in spec)\n        using \\<open>x \\<noteq> a\\<close> \\<open>x \\<notin> s\\<close> \\<open>0 \\<le> u\\<close> CC\n        apply (auto simp: xeq)\n        done\n    }\n    then have pcx: \"path_component (- s) x (a + C *\\<^sub>R (x - a))\"\n      by (force simp: closed_segment_def intro!: path_connected_linepath)\n    define D where \"D = B / norm(y - a)\"  \\<comment>\\<open>massive duplication with the proof above\\<close>\n    { fix u\n      assume u: \"(1 - u) *\\<^sub>R y + u *\\<^sub>R (a + D *\\<^sub>R (y - a)) \\<in> s\" and \"0 \\<le> u\" \"u \\<le> 1\"\n      have DD: \"1 \\<le> 1 + (D - 1) * u\"\n        using \\<open>y \\<noteq> a\\<close> \\<open>0 \\<le> u\\<close>\n        apply (simp add: D_def divide_simps norm_minus_commute)\n        using By by auto\n      have *: \"\\<And>v. (1 - u) *\\<^sub>R y + u *\\<^sub>R (a + v *\\<^sub>R (y - a)) = a + (1 + (v - 1) * u) *\\<^sub>R (y - a)\"\n        by (simp add: algebra_simps)\n      have \"a + ((1 / (1 + D * u - u)) *\\<^sub>R y + ((u / (1 + D * u - u)) *\\<^sub>R a + (D * u / (1 + D * u - u)) *\\<^sub>R y)) =\n            (1 + (u / (1 + D * u - u))) *\\<^sub>R a + ((1 / (1 + D * u - u)) + (D * u / (1 + D * u - u))) *\\<^sub>R y\"\n        by (simp add: algebra_simps)\n      also have \"... = (1 + (u / (1 + D * u - u))) *\\<^sub>R a + (1 + (u / (1 + D * u - u))) *\\<^sub>R y\"\n        using DD by (simp add: field_simps)\n      also have \"... = y + (1 + (u / (1 + D * u - u))) *\\<^sub>R a + (u / (1 + D * u - u)) *\\<^sub>R y\"\n        by (simp add: algebra_simps)\n      also have \"... = y + ((1 / (1 + D * u - u)) *\\<^sub>R a +\n              ((u / (1 + D * u - u)) *\\<^sub>R y + (D * u / (1 + D * u - u)) *\\<^sub>R a))\"\n        using DD by (simp add: field_simps) (simp add: add_divide_distrib scaleR_add_left)\n      finally have xeq: \"(1 - 1 / (1 + (D - 1) * u)) *\\<^sub>R a + (1 / (1 + (D - 1) * u)) *\\<^sub>R (a + (1 + (D - 1) * u) *\\<^sub>R (y - a)) = y\"\n        by (simp add: algebra_simps)\n      have False\n        using \\<open>convex s\\<close>\n        apply (simp add: convex_alt)\n        apply (drule_tac x=a in bspec)\n         apply (rule  \\<open>a \\<in> s\\<close>)\n        apply (drule_tac x=\"a + (1 + (D - 1) * u) *\\<^sub>R (y - a)\" in bspec)\n         using u apply (simp add: *)\n        apply (drule_tac x=\"1 / (1 + (D - 1) * u)\" in spec)\n        using \\<open>y \\<noteq> a\\<close> \\<open>y \\<notin> s\\<close> \\<open>0 \\<le> u\\<close> DD\n        apply (auto simp: xeq)\n        done\n    }\n    then have pdy: \"path_component (- s) y (a + D *\\<^sub>R (y - a))\"\n      by (force simp: closed_segment_def intro!: path_connected_linepath)\n    have pyx: \"path_component (- s) (a + D *\\<^sub>R (y - a)) (a + C *\\<^sub>R (x - a))\"\n      apply (rule path_component_of_subset [of \"{x. norm(x - a) = B}\"])\n       using \\<open>s \\<subseteq> ball a B\\<close>\n       apply (force simp: ball_def dist_norm norm_minus_commute)\n      apply (rule path_connected_sphere [OF 2, of a B, simplified path_connected_component, rule_format])\n      using \\<open>x \\<noteq> a\\<close>  using \\<open>y \\<noteq> a\\<close>  B apply (auto simp: C_def D_def)\n      done\n    have \"path_component (- s) x y\"\n      by (metis path_component_trans path_component_sym pcx pdy pyx)\n  }\n  then show ?thesis\n    by (auto simp: path_connected_component)\nqed\n\n\nlemma connected_complement_bounded_convex:\n    fixes s :: \"'a :: euclidean_space set\"\n    assumes \"bounded s\" \"convex s\" \"2 \\<le> DIM('a)\"\n      shows  \"connected (- s)\"\n  using path_connected_complement_bounded_convex [OF assms] path_connected_imp_connected by blast\n\nlemma connected_diff_ball:\n    fixes s :: \"'a :: euclidean_space set\"\n    assumes \"connected s\" \"cball a r \\<subseteq> s\" \"2 \\<le> DIM('a)\"\n      shows \"connected (s - ball a r)\"\n  apply (rule connected_diff_open_from_closed [OF ball_subset_cball])\n  using assms connected_sphere\n  apply (auto simp: cball_diff_eq_sphere dist_norm)\n  done\n\nproposition connected_open_delete:\n  assumes \"open S\" \"connected S\" and 2: \"2 \\<le> DIM('N::euclidean_space)\"\n    shows \"connected(S - {a::'N})\"\nproof (cases \"a \\<in> S\")\n  case True\n  with \\<open>open S\\<close> obtain \\<epsilon> where \"\\<epsilon> > 0\" and \\<epsilon>: \"cball a \\<epsilon> \\<subseteq> S\"\n    using open_contains_cball_eq by blast\n  have \"dist a (a + \\<epsilon> *\\<^sub>R (SOME i. i \\<in> Basis)) = \\<epsilon>\"\n    by (simp add: dist_norm SOME_Basis \\<open>0 < \\<epsilon>\\<close> less_imp_le)\n  with \\<epsilon> have \"\\<Inter>{S - ball a r |r. 0 < r \\<and> r < \\<epsilon>} \\<subseteq> {} \\<Longrightarrow> False\"\n    apply (drule_tac c=\"a + scaleR (\\<epsilon>) ((SOME i. i \\<in> Basis))\" in subsetD)\n    by auto\n  then have nonemp: \"(\\<Inter>{S - ball a r |r. 0 < r \\<and> r < \\<epsilon>}) = {} \\<Longrightarrow> False\"\n    by auto\n  have con: \"\\<And>r. r < \\<epsilon> \\<Longrightarrow> connected (S - ball a r)\"\n    using \\<epsilon> by (force intro: connected_diff_ball [OF \\<open>connected S\\<close> _ 2])\n  have \"x \\<in> \\<Union>{S - ball a r |r. 0 < r \\<and> r < \\<epsilon>}\" if \"x \\<in> S - {a}\" for x\n    apply (rule UnionI [of \"S - ball a (min \\<epsilon> (dist a x) / 2)\"])\n     using that \\<open>0 < \\<epsilon>\\<close> apply (simp_all add:)\n    apply (rule_tac x=\"min \\<epsilon> (dist a x) / 2\" in exI)\n    apply auto\n    done\n  then have \"S - {a} = \\<Union>{S - ball a r | r. 0 < r \\<and> r < \\<epsilon>}\"\n    by auto\n  then show ?thesis\n    by (auto intro: connected_Union con dest!: nonemp)\nnext\n  case False then show ?thesis\n    by (simp add: \\<open>connected S\\<close>)\nqed\n\ncorollary path_connected_open_delete:\n  assumes \"open S\" \"connected S\" and 2: \"2 \\<le> DIM('N::euclidean_space)\"\n    shows \"path_connected(S - {a::'N})\"\nby (simp add: assms connected_open_delete connected_open_path_connected open_delete)\n\ncorollary path_connected_punctured_ball:\n   \"2 \\<le> DIM('N::euclidean_space) \\<Longrightarrow> path_connected(ball a r - {a::'N})\"\nby (simp add: path_connected_open_delete)\n\ncorollary connected_punctured_ball:\n   \"2 \\<le> DIM('N::euclidean_space) \\<Longrightarrow> connected(ball a r - {a::'N})\"\nby (simp add: connected_open_delete)\n\ncorollary connected_open_delete_finite:\n  fixes S T::\"'a::euclidean_space set\"\n  assumes S: \"open S\" \"connected S\" and 2: \"2 \\<le> DIM('a)\" and \"finite T\"\n  shows \"connected(S - T)\"\n  using \\<open>finite T\\<close> S\nproof (induct T)\n  case empty\n  show ?case using \\<open>connected S\\<close> by simp\nnext\n  case (insert x F)\n  then have \"connected (S-F)\" by auto\n  moreover have \"open (S - F)\" using finite_imp_closed[OF \\<open>finite F\\<close>] \\<open>open S\\<close> by auto\n  ultimately have \"connected (S - F - {x})\" using connected_open_delete[OF _ _ 2] by auto\n  thus ?case by (metis Diff_insert)\nqed\n\nlemma psubset_sphere_Compl_connected:\n  fixes S :: \"'a::euclidean_space set\"\n  assumes S: \"S \\<subset> sphere a r\" and \"0 < r\" and 2: \"2 \\<le> DIM('a)\"\n  shows \"connected(- S)\"\nproof -\n  have \"S \\<subseteq> sphere a r\"\n    using S by blast\n  obtain b where \"dist a b = r\" and \"b \\<notin> S\"\n    using S mem_sphere by blast\n  have CS: \"- S = {x. dist a x \\<le> r \\<and> (x \\<notin> S)} \\<union> {x. r \\<le> dist a x \\<and> (x \\<notin> S)}\"\n    by (auto simp: )\n  have \"{x. dist a x \\<le> r \\<and> x \\<notin> S} \\<inter> {x. r \\<le> dist a x \\<and> x \\<notin> S} \\<noteq> {}\"\n    using \\<open>b \\<notin> S\\<close> \\<open>dist a b = r\\<close> by blast\n  moreover have \"connected {x. dist a x \\<le> r \\<and> x \\<notin> S}\"\n    apply (rule connected_intermediate_closure [of \"ball a r\"])\n    using assms by auto\n  moreover\n  have \"connected {x. r \\<le> dist a x \\<and> x \\<notin> S}\"\n    apply (rule connected_intermediate_closure [of \"- cball a r\"])\n    using assms apply (auto intro: connected_complement_bounded_convex)\n    apply (metis ComplI interior_cball interior_closure mem_ball not_less)\n    done\n  ultimately show ?thesis\n    by (simp add: CS connected_Un)\nqed\n\nsubsection\\<open>Relations between components and path components\\<close>\n\nlemma open_connected_component:\n  fixes s :: \"'a::real_normed_vector set\"\n  shows \"open s \\<Longrightarrow> open (connected_component_set s x)\"\n    apply (simp add: open_contains_ball, clarify)\n    apply (rename_tac y)\n    apply (drule_tac x=y in bspec)\n     apply (simp add: connected_component_in, clarify)\n    apply (rule_tac x=e in exI)\n    by (metis mem_Collect_eq connected_component_eq connected_component_maximal centre_in_ball connected_ball)\n\ncorollary open_components:\n    fixes s :: \"'a::real_normed_vector set\"\n    shows \"\\<lbrakk>open u; s \\<in> components u\\<rbrakk> \\<Longrightarrow> open s\"\n  by (simp add: components_iff) (metis open_connected_component)\n\nlemma in_closure_connected_component:\n  fixes s :: \"'a::real_normed_vector set\"\n  assumes x: \"x \\<in> s\" and s: \"open s\"\n  shows \"x \\<in> closure (connected_component_set s y) \\<longleftrightarrow>  x \\<in> connected_component_set s y\"\nproof -\n  { assume \"x \\<in> closure (connected_component_set s y)\"\n    moreover have \"x \\<in> connected_component_set s x\"\n      using x by simp\n    ultimately have \"x \\<in> connected_component_set s y\"\n      using s by (meson Compl_disjoint closure_iff_nhds_not_empty connected_component_disjoint disjoint_eq_subset_Compl open_connected_component)\n  }\n  then show ?thesis\n    by (auto simp: closure_def)\nqed\n\nlemma connected_disjoint_Union_open_pick:\n  assumes \"pairwise disjnt B\"\n          \"\\<And>S. S \\<in> A \\<Longrightarrow> connected S \\<and> S \\<noteq> {}\"\n          \"\\<And>S. S \\<in> B \\<Longrightarrow> open S\"\n          \"\\<Union>A \\<subseteq> \\<Union>B\"\n          \"S \\<in> A\"\n  obtains T where \"T \\<in> B\" \"S \\<subseteq> T\" \"S \\<inter> \\<Union>(B - {T}) = {}\"\nproof -\n  have \"S \\<subseteq> \\<Union>B\" \"connected S\" \"S \\<noteq> {}\"\n    using assms \\<open>S \\<in> A\\<close> by blast+\n  then obtain T where \"T \\<in> B\" \"S \\<inter> T \\<noteq> {}\"\n    by (metis Sup_inf_eq_bot_iff inf.absorb_iff2 inf_commute)\n  have 1: \"open T\" by (simp add: \\<open>T \\<in> B\\<close> assms)\n  have 2: \"open (\\<Union>(B-{T}))\" using assms by blast\n  have 3: \"S \\<subseteq> T \\<union> \\<Union>(B - {T})\" using \\<open>S \\<subseteq> \\<Union>B\\<close> by blast\n  have \"T \\<inter> \\<Union>(B - {T}) = {}\" using \\<open>T \\<in> B\\<close> \\<open>pairwise disjnt B\\<close>\n    by (auto simp: pairwise_def disjnt_def)\n  then have 4: \"T \\<inter> \\<Union>(B - {T}) \\<inter> S = {}\" by auto\n  from connectedD [OF \\<open>connected S\\<close> 1 2 3 4]\n  have \"S \\<inter> \\<Union>(B-{T}) = {}\"\n    by (auto simp: Int_commute \\<open>S \\<inter> T \\<noteq> {}\\<close>)\n  with \\<open>T \\<in> B\\<close> have \"S \\<subseteq> T\"\n    using \"3\" by auto\n  show ?thesis\n    using \\<open>S \\<inter> \\<Union>(B - {T}) = {}\\<close> \\<open>S \\<subseteq> T\\<close> \\<open>T \\<in> B\\<close> that by auto\nqed\n\nlemma connected_disjoint_Union_open_subset:\n  assumes A: \"pairwise disjnt A\" and B: \"pairwise disjnt B\"\n      and SA: \"\\<And>S. S \\<in> A \\<Longrightarrow> open S \\<and> connected S \\<and> S \\<noteq> {}\"\n      and SB: \"\\<And>S. S \\<in> B \\<Longrightarrow> open S \\<and> connected S \\<and> S \\<noteq> {}\"\n      and eq [simp]: \"\\<Union>A = \\<Union>B\"\n    shows \"A \\<subseteq> B\"\nproof\n  fix S\n  assume \"S \\<in> A\"\n  obtain T where \"T \\<in> B\" \"S \\<subseteq> T\" \"S \\<inter> \\<Union>(B - {T}) = {}\"\n      apply (rule connected_disjoint_Union_open_pick [OF B, of A])\n      using SA SB \\<open>S \\<in> A\\<close> by auto\n  moreover obtain S' where \"S' \\<in> A\" \"T \\<subseteq> S'\" \"T \\<inter> \\<Union>(A - {S'}) = {}\"\n      apply (rule connected_disjoint_Union_open_pick [OF A, of B])\n      using SA SB \\<open>T \\<in> B\\<close> by auto\n  ultimately have \"S' = S\"\n    by (metis A Int_subset_iff SA \\<open>S \\<in> A\\<close> disjnt_def inf.orderE pairwise_def)\n  with \\<open>T \\<subseteq> S'\\<close> have \"T \\<subseteq> S\" by simp\n  with \\<open>S \\<subseteq> T\\<close> have \"S = T\" by blast\n  with \\<open>T \\<in> B\\<close> show \"S \\<in> B\" by simp\nqed\n\nlemma connected_disjoint_Union_open_unique:\n  assumes A: \"pairwise disjnt A\" and B: \"pairwise disjnt B\"\n      and SA: \"\\<And>S. S \\<in> A \\<Longrightarrow> open S \\<and> connected S \\<and> S \\<noteq> {}\"\n      and SB: \"\\<And>S. S \\<in> B \\<Longrightarrow> open S \\<and> connected S \\<and> S \\<noteq> {}\"\n      and eq [simp]: \"\\<Union>A = \\<Union>B\"\n    shows \"A = B\"\nby (rule subset_antisym; metis connected_disjoint_Union_open_subset assms)\n\nproposition components_open_unique:\n fixes S :: \"'a::real_normed_vector set\"\n  assumes \"pairwise disjnt A\" \"\\<Union>A = S\"\n          \"\\<And>X. X \\<in> A \\<Longrightarrow> open X \\<and> connected X \\<and> X \\<noteq> {}\"\n    shows \"components S = A\"\nproof -\n  have \"open S\" using assms by blast\n  show ?thesis\n    apply (rule connected_disjoint_Union_open_unique)\n    apply (simp add: components_eq disjnt_def pairwise_def)\n    using \\<open>open S\\<close>\n    apply (simp_all add: assms open_components in_components_connected in_components_nonempty)\n    done\nqed\n\n\nsubsection\\<open>Existence of unbounded components\\<close>\n\nlemma cobounded_unbounded_component:\n    fixes s :: \"'a :: euclidean_space set\"\n    assumes \"bounded (-s)\"\n      shows \"\\<exists>x. x \\<in> s \\<and> ~ bounded (connected_component_set s x)\"\nproof -\n  obtain i::'a where i: \"i \\<in> Basis\"\n    using nonempty_Basis by blast\n  obtain B where B: \"B>0\" \"-s \\<subseteq> ball 0 B\"\n    using bounded_subset_ballD [OF assms, of 0] by auto\n  then have *: \"\\<And>x. B \\<le> norm x \\<Longrightarrow> x \\<in> s\"\n    by (force simp add: ball_def dist_norm)\n  have unbounded_inner: \"~ bounded {x. inner i x \\<ge> B}\"\n    apply (auto simp: bounded_def dist_norm)\n    apply (rule_tac x=\"x + (max B e + 1 + \\<bar>i \\<bullet> x\\<bar>) *\\<^sub>R i\" in exI)\n    apply simp\n    using i\n    apply (auto simp: algebra_simps)\n    done\n  have **: \"{x. B \\<le> i \\<bullet> x} \\<subseteq> connected_component_set s (B *\\<^sub>R i)\"\n    apply (rule connected_component_maximal)\n    apply (auto simp: i intro: convex_connected convex_halfspace_ge [of B])\n    apply (rule *)\n    apply (rule order_trans [OF _ Basis_le_norm [OF i]])\n    by (simp add: inner_commute)\n  have \"B *\\<^sub>R i \\<in> s\"\n    by (rule *) (simp add: norm_Basis [OF i])\n  then show ?thesis\n    apply (rule_tac x=\"B *\\<^sub>R i\" in exI, clarify)\n    apply (frule bounded_subset [of _ \"{x. B \\<le> i \\<bullet> x}\", OF _ **])\n    using unbounded_inner apply blast\n    done\nqed\n\nlemma cobounded_unique_unbounded_component:\n    fixes s :: \"'a :: euclidean_space set\"\n    assumes bs: \"bounded (-s)\" and \"2 \\<le> DIM('a)\"\n        and bo: \"~ bounded(connected_component_set s x)\"\n                \"~ bounded(connected_component_set s y)\"\n      shows \"connected_component_set s x = connected_component_set s y\"\nproof -\n  obtain i::'a where i: \"i \\<in> Basis\"\n    using nonempty_Basis by blast\n  obtain B where B: \"B>0\" \"-s \\<subseteq> ball 0 B\"\n    using bounded_subset_ballD [OF bs, of 0] by auto\n  then have *: \"\\<And>x. B \\<le> norm x \\<Longrightarrow> x \\<in> s\"\n    by (force simp add: ball_def dist_norm)\n  have ccb: \"connected (- ball 0 B :: 'a set)\"\n    using assms by (auto intro: connected_complement_bounded_convex)\n  obtain x' where x': \"connected_component s x x'\" \"norm x' > B\"\n    using bo [unfolded bounded_def dist_norm, simplified, rule_format]\n    by (metis diff_zero norm_minus_commute not_less)\n  obtain y' where y': \"connected_component s y y'\" \"norm y' > B\"\n    using bo [unfolded bounded_def dist_norm, simplified, rule_format]\n    by (metis diff_zero norm_minus_commute not_less)\n  have x'y': \"connected_component s x' y'\"\n    apply (simp add: connected_component_def)\n    apply (rule_tac x=\"- ball 0 B\" in exI)\n    using x' y'\n    apply (auto simp: ccb dist_norm *)\n    done\n  show ?thesis\n    apply (rule connected_component_eq)\n    using x' y' x'y'\n    by (metis (no_types, lifting) connected_component_eq_empty connected_component_eq_eq connected_component_idemp connected_component_in)\nqed\n\nlemma cobounded_unbounded_components:\n    fixes s :: \"'a :: euclidean_space set\"\n    shows \"bounded (-s) \\<Longrightarrow> \\<exists>c. c \\<in> components s \\<and> ~bounded c\"\n  by (metis cobounded_unbounded_component components_def imageI)\n\nlemma cobounded_unique_unbounded_components:\n    fixes s :: \"'a :: euclidean_space set\"\n    shows  \"\\<lbrakk>bounded (- s); c \\<in> components s; \\<not> bounded c; c' \\<in> components s; \\<not> bounded c'; 2 \\<le> DIM('a)\\<rbrakk> \\<Longrightarrow> c' = c\"\n  unfolding components_iff\n  by (metis cobounded_unique_unbounded_component)\n\nlemma cobounded_has_bounded_component:\n  fixes S :: \"'a :: euclidean_space set\"\n  assumes \"bounded (- S)\" \"\\<not> connected S\" \"2 \\<le> DIM('a)\"\n  obtains C where \"C \\<in> components S\" \"bounded C\"\n  by (meson cobounded_unique_unbounded_components connected_eq_connected_components_eq assms)\n\n\nsection\\<open>The \"inside\" and \"outside\" of a set\\<close>\n\ntext\\<open>The inside comprises the points in a bounded connected component of the set's complement.\n  The outside comprises the points in unbounded connected component of the complement.\\<close>\n\ndefinition inside where\n  \"inside s \\<equiv> {x. (x \\<notin> s) \\<and> bounded(connected_component_set ( - s) x)}\"\n\ndefinition outside where\n  \"outside s \\<equiv> -s \\<inter> {x. ~ bounded(connected_component_set (- s) x)}\"\n\nlemma outside: \"outside s = {x. ~ bounded(connected_component_set (- s) x)}\"\n  by (auto simp: outside_def) (metis Compl_iff bounded_empty connected_component_eq_empty)\n\nlemma inside_no_overlap [simp]: \"inside s \\<inter> s = {}\"\n  by (auto simp: inside_def)\n\nlemma outside_no_overlap [simp]:\n   \"outside s \\<inter> s = {}\"\n  by (auto simp: outside_def)\n\nlemma inside_Int_outside [simp]: \"inside s \\<inter> outside s = {}\"\n  by (auto simp: inside_def outside_def)\n\nlemma inside_Un_outside [simp]: \"inside s \\<union> outside s = (- s)\"\n  by (auto simp: inside_def outside_def)\n\nlemma inside_eq_outside:\n   \"inside s = outside s \\<longleftrightarrow> s = UNIV\"\n  by (auto simp: inside_def outside_def)\n\nlemma inside_outside: \"inside s = (- (s \\<union> outside s))\"\n  by (force simp add: inside_def outside)\n\nlemma outside_inside: \"outside s = (- (s \\<union> inside s))\"\n  by (auto simp: inside_outside) (metis IntI equals0D outside_no_overlap)\n\nlemma union_with_inside: \"s \\<union> inside s = - outside s\"\n  by (auto simp: inside_outside) (simp add: outside_inside)\n\nlemma union_with_outside: \"s \\<union> outside s = - inside s\"\n  by (simp add: inside_outside)\n\nlemma outside_mono: \"s \\<subseteq> t \\<Longrightarrow> outside t \\<subseteq> outside s\"\n  by (auto simp: outside bounded_subset connected_component_mono)\n\nlemma inside_mono: \"s \\<subseteq> t \\<Longrightarrow> inside s - t \\<subseteq> inside t\"\n  by (auto simp: inside_def bounded_subset connected_component_mono)\n\nlemma segment_bound_lemma:\n  fixes u::real\n  assumes \"x \\<ge> B\" \"y \\<ge> B\" \"0 \\<le> u\" \"u \\<le> 1\"\n  shows \"(1 - u) * x + u * y \\<ge> B\"\nproof -\n  obtain dx dy where \"dx \\<ge> 0\" \"dy \\<ge> 0\" \"x = B + dx\" \"y = B + dy\"\n    using assms by auto (metis add.commute diff_add_cancel)\n  with \\<open>0 \\<le> u\\<close> \\<open>u \\<le> 1\\<close> show ?thesis\n    by (simp add: add_increasing2 mult_left_le field_simps)\nqed\n\nlemma cobounded_outside:\n  fixes s :: \"'a :: real_normed_vector set\"\n  assumes \"bounded s\" shows \"bounded (- outside s)\"\nproof -\n  obtain B where B: \"B>0\" \"s \\<subseteq> ball 0 B\"\n    using bounded_subset_ballD [OF assms, of 0] by auto\n  { fix x::'a and C::real\n    assume Bno: \"B \\<le> norm x\" and C: \"0 < C\"\n    have \"\\<exists>y. connected_component (- s) x y \\<and> norm y > C\"\n    proof (cases \"x = 0\")\n      case True with B Bno show ?thesis by force\n    next\n      case False with B C show ?thesis\n        apply (rule_tac x=\"((B+C)/norm x) *\\<^sub>R x\" in exI)\n        apply (simp add: connected_component_def)\n        apply (rule_tac x=\"closed_segment x (((B+C)/norm x) *\\<^sub>R x)\" in exI)\n        apply simp\n        apply (rule_tac y=\"- ball 0 B\" in order_trans)\n         prefer 2 apply force\n        apply (simp add: closed_segment_def ball_def dist_norm, clarify)\n        apply (simp add: real_vector_class.scaleR_add_left [symmetric] divide_simps)\n        using segment_bound_lemma [of B \"norm x\" \"B+C\" ] Bno\n        by (meson le_add_same_cancel1 less_eq_real_def not_le)\n    qed\n  }\n  then show ?thesis\n    apply (simp add: outside_def assms)\n    apply (rule bounded_subset [OF bounded_ball [of 0 B]])\n    apply (force simp add: dist_norm not_less bounded_pos)\n    done\nqed\n\nlemma unbounded_outside:\n    fixes s :: \"'a::{real_normed_vector, perfect_space} set\"\n    shows \"bounded s \\<Longrightarrow> ~ bounded(outside s)\"\n  using cobounded_imp_unbounded cobounded_outside by blast\n\nlemma bounded_inside:\n    fixes s :: \"'a::{real_normed_vector, perfect_space} set\"\n    shows \"bounded s \\<Longrightarrow> bounded(inside s)\"\n  by (simp add: bounded_Int cobounded_outside inside_outside)\n\nlemma connected_outside:\n    fixes s :: \"'a::euclidean_space set\"\n    assumes \"bounded s\" \"2 \\<le> DIM('a)\"\n      shows \"connected(outside s)\"\n  apply (simp add: connected_iff_connected_component, clarify)\n  apply (simp add: outside)\n  apply (rule_tac s=\"connected_component_set (- s) x\" in connected_component_of_subset)\n  apply (metis (no_types) assms cobounded_unbounded_component cobounded_unique_unbounded_component connected_component_eq_eq connected_component_idemp double_complement mem_Collect_eq)\n  apply clarify\n  apply (metis connected_component_eq_eq connected_component_in)\n  done\n\nlemma outside_connected_component_lt:\n    \"outside s = {x. \\<forall>B. \\<exists>y. B < norm(y) \\<and> connected_component (- s) x y}\"\napply (auto simp: outside bounded_def dist_norm)\napply (metis diff_0 norm_minus_cancel not_less)\nby (metis less_diff_eq norm_minus_commute norm_triangle_ineq2 order.trans pinf(6))\n\nlemma outside_connected_component_le:\n   \"outside s =\n            {x. \\<forall>B. \\<exists>y. B \\<le> norm(y) \\<and>\n                         connected_component (- s) x y}\"\napply (simp add: outside_connected_component_lt)\napply (simp add: Set.set_eq_iff)\nby (meson gt_ex leD le_less_linear less_imp_le order.trans)\n\nlemma not_outside_connected_component_lt:\n    fixes s :: \"'a::euclidean_space set\"\n    assumes s: \"bounded s\" and \"2 \\<le> DIM('a)\"\n      shows \"- (outside s) = {x. \\<forall>B. \\<exists>y. B < norm(y) \\<and> ~ (connected_component (- s) x y)}\"\nproof -\n  obtain B::real where B: \"0 < B\" and Bno: \"\\<And>x. x \\<in> s \\<Longrightarrow> norm x \\<le> B\"\n    using s [simplified bounded_pos] by auto\n  { fix y::'a and z::'a\n    assume yz: \"B < norm z\" \"B < norm y\"\n    have \"connected_component (- cball 0 B) y z\"\n      apply (rule connected_componentI [OF _ subset_refl])\n      apply (rule connected_complement_bounded_convex)\n      using assms yz\n      by (auto simp: dist_norm)\n    then have \"connected_component (- s) y z\"\n      apply (rule connected_component_of_subset)\n      apply (metis Bno Compl_anti_mono mem_cball_0 subset_iff)\n      done\n  } note cyz = this\n  show ?thesis\n    apply (auto simp: outside)\n    apply (metis Compl_iff bounded_iff cobounded_imp_unbounded mem_Collect_eq not_le)\n    apply (simp add: bounded_pos)\n    by (metis B connected_component_trans cyz not_le)\nqed\n\nlemma not_outside_connected_component_le:\n    fixes s :: \"'a::euclidean_space set\"\n    assumes s: \"bounded s\"  \"2 \\<le> DIM('a)\"\n      shows \"- (outside s) = {x. \\<forall>B. \\<exists>y. B \\<le> norm(y) \\<and> ~ (connected_component (- s) x y)}\"\napply (auto intro: less_imp_le simp: not_outside_connected_component_lt [OF assms])\nby (meson gt_ex less_le_trans)\n\nlemma inside_connected_component_lt:\n    fixes s :: \"'a::euclidean_space set\"\n    assumes s: \"bounded s\"  \"2 \\<le> DIM('a)\"\n      shows \"inside s = {x. (x \\<notin> s) \\<and> (\\<forall>B. \\<exists>y. B < norm(y) \\<and> ~(connected_component (- s) x y))}\"\n  by (auto simp: inside_outside not_outside_connected_component_lt [OF assms])\n\nlemma inside_connected_component_le:\n    fixes s :: \"'a::euclidean_space set\"\n    assumes s: \"bounded s\"  \"2 \\<le> DIM('a)\"\n      shows \"inside s = {x. (x \\<notin> s) \\<and> (\\<forall>B. \\<exists>y. B \\<le> norm(y) \\<and> ~(connected_component (- s) x y))}\"\n  by (auto simp: inside_outside not_outside_connected_component_le [OF assms])\n\nlemma inside_subset:\n  assumes \"connected u\" and \"~bounded u\" and \"t \\<union> u = - s\"\n  shows \"inside s \\<subseteq> t\"\napply (auto simp: inside_def)\nby (metis bounded_subset [of \"connected_component_set (- s) _\"] connected_component_maximal\n       Compl_iff Un_iff assms subsetI)\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 connected_Int_frontier:\n     \"\\<lbrakk>connected s; s \\<inter> t \\<noteq> {}; s - t \\<noteq> {}\\<rbrakk> \\<Longrightarrow> (s \\<inter> frontier t \\<noteq> {})\"\n  apply (simp add: frontier_interiors connected_openin, safe)\n  apply (drule_tac x=\"s \\<inter> interior t\" in spec, safe)\n   apply (drule_tac [2] x=\"s \\<inter> interior (-t)\" in spec)\n   apply (auto simp: disjoint_eq_subset_Compl dest: interior_subset [THEN subsetD])\n  done\n\nlemma frontier_not_empty:\n  fixes S :: \"'a :: real_normed_vector set\"\n  shows \"\\<lbrakk>S \\<noteq> {}; S \\<noteq> UNIV\\<rbrakk> \\<Longrightarrow> frontier S \\<noteq> {}\"\n    using connected_Int_frontier [of UNIV S] by auto\n\nlemma frontier_eq_empty:\n  fixes S :: \"'a :: real_normed_vector set\"\n  shows \"frontier S = {} \\<longleftrightarrow> S = {} \\<or> S = UNIV\"\nusing frontier_UNIV frontier_empty frontier_not_empty by blast\n\nlemma frontier_of_connected_component_subset:\n  fixes S :: \"'a::real_normed_vector set\"\n  shows \"frontier(connected_component_set S x) \\<subseteq> frontier S\"\nproof -\n  { fix y\n    assume y1: \"y \\<in> closure (connected_component_set S x)\"\n       and y2: \"y \\<notin> interior (connected_component_set S x)\"\n    have \"y \\<in> closure S\"\n      using y1 closure_mono connected_component_subset by blast\n    moreover have \"z \\<in> interior (connected_component_set S x)\"\n          if \"0 < e\" \"ball y e \\<subseteq> interior S\" \"dist y z < e\" for e z\n    proof -\n      have \"ball y e \\<subseteq> connected_component_set S y\"\n        apply (rule connected_component_maximal)\n        using that interior_subset mem_ball apply auto\n        done\n      then show ?thesis\n        using y1 apply (simp add: closure_approachable open_contains_ball_eq [OF open_interior])\n        by (metis connected_component_eq dist_commute mem_Collect_eq mem_ball mem_interior subsetD \\<open>0 < e\\<close> y2)\n    qed\n    then have \"y \\<notin> interior S\"\n      using y2 by (force simp: open_contains_ball_eq [OF open_interior])\n    ultimately have \"y \\<in> frontier S\"\n      by (auto simp: frontier_def)\n  }\n  then show ?thesis by (auto simp: frontier_def)\nqed\n\nlemma frontier_Union_subset_closure:\n  fixes F :: \"'a::real_normed_vector set set\"\n  shows \"frontier(\\<Union>F) \\<subseteq> closure(\\<Union>t \\<in> F. frontier t)\"\nproof -\n  have \"\\<exists>y\\<in>F. \\<exists>y\\<in>frontier y. dist y x < e\"\n       if \"T \\<in> F\" \"y \\<in> T\" \"dist y x < e\"\n          \"x \\<notin> interior (\\<Union>F)\" \"0 < e\" for x y e T\n  proof (cases \"x \\<in> T\")\n    case True with that show ?thesis\n      by (metis Diff_iff Sup_upper closure_subset contra_subsetD dist_self frontier_def interior_mono)\n  next\n    case False\n    have 1: \"closed_segment x y \\<inter> T \\<noteq> {}\" using \\<open>y \\<in> T\\<close> by blast\n    have 2: \"closed_segment x y - T \\<noteq> {}\"\n      using False by blast\n    obtain c where \"c \\<in> closed_segment x y\" \"c \\<in> frontier T\"\n       using False connected_Int_frontier [OF connected_segment 1 2] by auto\n    then show ?thesis\n    proof -\n      have \"norm (y - x) < e\"\n        by (metis dist_norm \\<open>dist y x < e\\<close>)\n      moreover have \"norm (c - x) \\<le> norm (y - x)\"\n        by (simp add: \\<open>c \\<in> closed_segment x y\\<close> segment_bound(1))\n      ultimately have \"norm (c - x) < e\"\n        by linarith\n      then show ?thesis\n        by (metis (no_types) \\<open>c \\<in> frontier T\\<close> dist_norm that(1))\n    qed\n  qed\n  then show ?thesis\n    by (fastforce simp add: frontier_def closure_approachable)\nqed\n\nlemma frontier_Union_subset:\n  fixes F :: \"'a::real_normed_vector set set\"\n  shows \"finite F \\<Longrightarrow> frontier(\\<Union>F) \\<subseteq> (\\<Union>t \\<in> F. frontier t)\"\nby (rule order_trans [OF frontier_Union_subset_closure])\n   (auto simp: closure_subset_eq)\n\nlemma frontier_of_components_subset:\n  fixes S :: \"'a::real_normed_vector set\"\n  shows \"C \\<in> components S \\<Longrightarrow> frontier C \\<subseteq> frontier S\"\n  by (metis Path_Connected.frontier_of_connected_component_subset components_iff)\n\nlemma frontier_of_components_closed_complement:\n  fixes S :: \"'a::real_normed_vector set\"\n  shows \"\\<lbrakk>closed S; C \\<in> components (- S)\\<rbrakk> \\<Longrightarrow> frontier C \\<subseteq> S\"\n  using frontier_complement frontier_of_components_subset frontier_subset_eq by blast\n\nlemma frontier_minimal_separating_closed:\n  fixes S :: \"'a::real_normed_vector set\"\n  assumes \"closed S\"\n      and nconn: \"~ connected(- S)\"\n      and C: \"C \\<in> components (- S)\"\n      and conn: \"\\<And>T. \\<lbrakk>closed T; T \\<subset> S\\<rbrakk> \\<Longrightarrow> connected(- T)\"\n    shows \"frontier C = S\"\nproof (rule ccontr)\n  assume \"frontier C \\<noteq> S\"\n  then have \"frontier C \\<subset> S\"\n    using frontier_of_components_closed_complement [OF \\<open>closed S\\<close> C] by blast\n  then have \"connected(- (frontier C))\"\n    by (simp add: conn)\n  have \"\\<not> connected(- (frontier C))\"\n    unfolding connected_def not_not\n  proof (intro exI conjI)\n    show \"open C\"\n      using C \\<open>closed S\\<close> open_components by blast\n    show \"open (- closure C)\"\n      by blast\n    show \"C \\<inter> - closure C \\<inter> - frontier C = {}\"\n      using closure_subset by blast\n    show \"C \\<inter> - frontier C \\<noteq> {}\"\n      using C \\<open>open C\\<close> components_eq frontier_disjoint_eq by fastforce\n    show \"- frontier C \\<subseteq> C \\<union> - closure C\"\n      by (simp add: \\<open>open C\\<close> closed_Compl frontier_closures)\n    then show \"- closure C \\<inter> - frontier C \\<noteq> {}\"\n      by (metis (no_types, lifting) C Compl_subset_Compl_iff \\<open>frontier C \\<subset> S\\<close> compl_sup frontier_closures in_components_subset psubsetE sup.absorb_iff2 sup.boundedE sup_bot.right_neutral sup_inf_absorb)\n  qed\n  then show False\n    using \\<open>connected (- frontier C)\\<close> by blast\nqed\n\nlemma connected_component_UNIV [simp]:\n    fixes x :: \"'a::real_normed_vector\"\n    shows \"connected_component_set UNIV x = UNIV\"\nusing connected_iff_eq_connected_component_set [of \"UNIV::'a set\"] connected_UNIV\nby auto\n\nlemma connected_component_eq_UNIV:\n    fixes x :: \"'a::real_normed_vector\"\n    shows \"connected_component_set s x = UNIV \\<longleftrightarrow> s = UNIV\"\n  using connected_component_in connected_component_UNIV by blast\n\nlemma components_univ [simp]: \"components UNIV = {UNIV :: 'a::real_normed_vector set}\"\n  by (auto simp: components_eq_sing_iff)\n\nlemma interior_inside_frontier:\n    fixes s :: \"'a::real_normed_vector set\"\n    assumes \"bounded s\"\n      shows \"interior s \\<subseteq> inside (frontier s)\"\nproof -\n  { fix x y\n    assume x: \"x \\<in> interior s\" and y: \"y \\<notin> s\"\n       and cc: \"connected_component (- frontier s) x y\"\n    have \"connected_component_set (- frontier s) x \\<inter> frontier s \\<noteq> {}\"\n      apply (rule connected_Int_frontier, simp)\n      apply (metis IntI cc connected_component_in connected_component_refl empty_iff interiorE mem_Collect_eq set_rev_mp x)\n      using  y cc\n      by blast\n    then have \"bounded (connected_component_set (- frontier s) x)\"\n      using connected_component_in by auto\n  }\n  then show ?thesis\n    apply (auto simp: inside_def frontier_def)\n    apply (rule classical)\n    apply (rule bounded_subset [OF assms], blast)\n    done\nqed\n\nlemma inside_empty [simp]: \"inside {} = ({} :: 'a :: {real_normed_vector, perfect_space} set)\"\n  by (simp add: inside_def connected_component_UNIV)\n\nlemma outside_empty [simp]: \"outside {} = (UNIV :: 'a :: {real_normed_vector, perfect_space} set)\"\nusing inside_empty inside_Un_outside by blast\n\nlemma inside_same_component:\n   \"\\<lbrakk>connected_component (- s) x y; x \\<in> inside s\\<rbrakk> \\<Longrightarrow> y \\<in> inside s\"\n  using connected_component_eq connected_component_in\n  by (fastforce simp add: inside_def)\n\nlemma outside_same_component:\n   \"\\<lbrakk>connected_component (- s) x y; x \\<in> outside s\\<rbrakk> \\<Longrightarrow> y \\<in> outside s\"\n  using connected_component_eq connected_component_in\n  by (fastforce simp add: outside_def)\n\nlemma convex_in_outside:\n  fixes s :: \"'a :: {real_normed_vector, perfect_space} set\"\n  assumes s: \"convex s\" and z: \"z \\<notin> s\"\n    shows \"z \\<in> outside s\"\nproof (cases \"s={}\")\n  case True then show ?thesis by simp\nnext\n  case False then obtain a where \"a \\<in> s\" by blast\n  with z have zna: \"z \\<noteq> a\" by auto\n  { assume \"bounded (connected_component_set (- s) z)\"\n    with bounded_pos_less obtain B where \"B>0\" and B: \"\\<And>x. connected_component (- s) z x \\<Longrightarrow> norm x < B\"\n      by (metis mem_Collect_eq)\n    define C where \"C = (B + 1 + norm z) / norm (z-a)\"\n    have \"C > 0\"\n      using \\<open>0 < B\\<close> zna by (simp add: C_def divide_simps add_strict_increasing)\n    have \"\\<bar>norm (z + C *\\<^sub>R (z-a)) - norm (C *\\<^sub>R (z-a))\\<bar> \\<le> norm z\"\n      by (metis add_diff_cancel norm_triangle_ineq3)\n    moreover have \"norm (C *\\<^sub>R (z-a)) > norm z + B\"\n      using zna \\<open>B>0\\<close> by (simp add: C_def le_max_iff_disj field_simps)\n    ultimately have C: \"norm (z + C *\\<^sub>R (z-a)) > B\" by linarith\n    { fix u::real\n      assume u: \"0\\<le>u\" \"u\\<le>1\" and ins: \"(1 - u) *\\<^sub>R z + u *\\<^sub>R (z + C *\\<^sub>R (z - a)) \\<in> s\"\n      then have Cpos: \"1 + u * C > 0\"\n        by (meson \\<open>0 < C\\<close> add_pos_nonneg less_eq_real_def zero_le_mult_iff zero_less_one)\n      then have *: \"(1 / (1 + u * C)) *\\<^sub>R z + (u * C / (1 + u * C)) *\\<^sub>R z = z\"\n        by (simp add: scaleR_add_left [symmetric] divide_simps)\n      then have False\n        using convexD_alt [OF s \\<open>a \\<in> s\\<close> ins, of \"1/(u*C + 1)\"] \\<open>C>0\\<close> \\<open>z \\<notin> s\\<close> Cpos u\n        by (simp add: * divide_simps algebra_simps)\n    } note contra = this\n    have \"connected_component (- s) z (z + C *\\<^sub>R (z-a))\"\n      apply (rule connected_componentI [OF connected_segment [of z \"z + C *\\<^sub>R (z-a)\"]])\n      apply (simp add: closed_segment_def)\n      using contra\n      apply auto\n      done\n    then have False\n      using zna B [of \"z + C *\\<^sub>R (z-a)\"] C\n      by (auto simp: divide_simps max_mult_distrib_right)\n  }\n  then show ?thesis\n    by (auto simp: outside_def z)\nqed\n\nlemma outside_convex:\n  fixes s :: \"'a :: {real_normed_vector, perfect_space} set\"\n  assumes \"convex s\"\n    shows \"outside s = - s\"\n  by (metis ComplD assms convex_in_outside equalityI inside_Un_outside subsetI sup.cobounded2)\n\nlemma inside_convex:\n  fixes s :: \"'a :: {real_normed_vector, perfect_space} set\"\n  shows \"convex s \\<Longrightarrow> inside s = {}\"\n  by (simp add: inside_outside outside_convex)\n\nlemma outside_subset_convex:\n  fixes s :: \"'a :: {real_normed_vector, perfect_space} set\"\n  shows \"\\<lbrakk>convex t; s \\<subseteq> t\\<rbrakk> \\<Longrightarrow> - t \\<subseteq> outside s\"\n  using outside_convex outside_mono by blast\n\nlemma outside_frontier_misses_closure:\n    fixes s :: \"'a::real_normed_vector set\"\n    assumes \"bounded s\"\n    shows  \"outside(frontier s) \\<subseteq> - closure s\"\n  unfolding outside_inside Lattices.boolean_algebra_class.compl_le_compl_iff\nproof -\n  { assume \"interior s \\<subseteq> inside (frontier s)\"\n    hence \"interior s \\<union> inside (frontier s) = inside (frontier s)\"\n      by (simp add: subset_Un_eq)\n    then have \"closure s \\<subseteq> frontier s \\<union> inside (frontier s)\"\n      using frontier_def by auto\n  }\n  then show \"closure s \\<subseteq> frontier s \\<union> inside (frontier s)\"\n    using interior_inside_frontier [OF assms] by blast\nqed\n\nlemma outside_frontier_eq_complement_closure:\n  fixes s :: \"'a :: {real_normed_vector, perfect_space} set\"\n    assumes \"bounded s\" \"convex s\"\n      shows \"outside(frontier s) = - closure s\"\nby (metis Diff_subset assms convex_closure frontier_def outside_frontier_misses_closure\n          outside_subset_convex subset_antisym)\n\nlemma inside_frontier_eq_interior:\n     fixes s :: \"'a :: {real_normed_vector, perfect_space} set\"\n     shows \"\\<lbrakk>bounded s; convex s\\<rbrakk> \\<Longrightarrow> inside(frontier s) = interior s\"\n  apply (simp add: inside_outside outside_frontier_eq_complement_closure)\n  using closure_subset interior_subset\n  apply (auto simp add: frontier_def)\n  done\n\nlemma open_inside:\n    fixes s :: \"'a::real_normed_vector set\"\n    assumes \"closed s\"\n      shows \"open (inside s)\"\nproof -\n  { fix x assume x: \"x \\<in> inside s\"\n    have \"open (connected_component_set (- s) x)\"\n      using assms open_connected_component by blast\n    then obtain e where e: \"e>0\" and e: \"\\<And>y. dist y x < e \\<longrightarrow> connected_component (- s) x y\"\n      using dist_not_less_zero\n      apply (simp add: open_dist)\n      by (metis (no_types, lifting) Compl_iff connected_component_refl_eq inside_def mem_Collect_eq x)\n    then have \"\\<exists>e>0. ball x e \\<subseteq> inside s\"\n      by (metis e dist_commute inside_same_component mem_ball subsetI x)\n  }\n  then show ?thesis\n    by (simp add: open_contains_ball)\nqed\n\nlemma open_outside:\n    fixes s :: \"'a::real_normed_vector set\"\n    assumes \"closed s\"\n      shows \"open (outside s)\"\nproof -\n  { fix x assume x: \"x \\<in> outside s\"\n    have \"open (connected_component_set (- s) x)\"\n      using assms open_connected_component by blast\n    then obtain e where e: \"e>0\" and e: \"\\<And>y. dist y x < e \\<longrightarrow> connected_component (- s) x y\"\n      using dist_not_less_zero\n      apply (simp add: open_dist)\n      by (metis Int_iff outside_def connected_component_refl_eq  x)\n    then have \"\\<exists>e>0. ball x e \\<subseteq> outside s\"\n      by (metis e dist_commute outside_same_component mem_ball subsetI x)\n  }\n  then show ?thesis\n    by (simp add: open_contains_ball)\nqed\n\nlemma closure_inside_subset:\n    fixes s :: \"'a::real_normed_vector set\"\n    assumes \"closed s\"\n      shows \"closure(inside s) \\<subseteq> s \\<union> inside s\"\nby (metis assms closure_minimal open_closed open_outside sup.cobounded2 union_with_inside)\n\nlemma frontier_inside_subset:\n    fixes s :: \"'a::real_normed_vector set\"\n    assumes \"closed s\"\n      shows \"frontier(inside s) \\<subseteq> s\"\nproof -\n  have \"closure (inside s) \\<inter> - inside s = closure (inside s) - interior (inside s)\"\n    by (metis (no_types) Diff_Compl assms closure_closed interior_closure open_closed open_inside)\n  moreover have \"- inside s \\<inter> - outside s = s\"\n    by (metis (no_types) compl_sup double_compl inside_Un_outside)\n  moreover have \"closure (inside s) \\<subseteq> - outside s\"\n    by (metis (no_types) assms closure_inside_subset union_with_inside)\n  ultimately have \"closure (inside s) - interior (inside s) \\<subseteq> s\"\n    by blast\n  then show ?thesis\n    by (simp add: frontier_def open_inside interior_open)\nqed\n\nlemma closure_outside_subset:\n    fixes s :: \"'a::real_normed_vector set\"\n    assumes \"closed s\"\n      shows \"closure(outside s) \\<subseteq> s \\<union> outside s\"\n  apply (rule closure_minimal, simp)\n  by (metis assms closed_open inside_outside open_inside)\n\nlemma frontier_outside_subset:\n    fixes s :: \"'a::real_normed_vector set\"\n    assumes \"closed s\"\n      shows \"frontier(outside s) \\<subseteq> s\"\n  apply (simp add: frontier_def open_outside interior_open)\n  by (metis Diff_subset_conv assms closure_outside_subset interior_eq open_outside sup.commute)\n\nlemma inside_complement_unbounded_connected_empty:\n     \"\\<lbrakk>connected (- s); \\<not> bounded (- s)\\<rbrakk> \\<Longrightarrow> inside s = {}\"\n  apply (simp add: inside_def)\n  by (meson Compl_iff bounded_subset connected_component_maximal order_refl)\n\nlemma inside_bounded_complement_connected_empty:\n    fixes s :: \"'a::{real_normed_vector, perfect_space} set\"\n    shows \"\\<lbrakk>connected (- s); bounded s\\<rbrakk> \\<Longrightarrow> inside s = {}\"\n  by (metis inside_complement_unbounded_connected_empty cobounded_imp_unbounded)\n\nlemma inside_inside:\n    assumes \"s \\<subseteq> inside t\"\n    shows \"inside s - t \\<subseteq> inside t\"\nunfolding inside_def\nproof clarify\n  fix x\n  assume x: \"x \\<notin> t\" \"x \\<notin> s\" and bo: \"bounded (connected_component_set (- s) x)\"\n  show \"bounded (connected_component_set (- t) x)\"\n  proof (cases \"s \\<inter> connected_component_set (- t) x = {}\")\n    case True show ?thesis\n      apply (rule bounded_subset [OF bo])\n      apply (rule connected_component_maximal)\n      using x True apply auto\n      done\n  next\n    case False then show ?thesis\n      using assms [unfolded inside_def] x\n      apply (simp add: disjoint_iff_not_equal, clarify)\n      apply (drule subsetD, assumption, auto)\n      by (metis (no_types, hide_lams) ComplI connected_component_eq_eq)\n  qed\nqed\n\nlemma inside_inside_subset: \"inside(inside s) \\<subseteq> s\"\n  using inside_inside union_with_outside by fastforce\n\nlemma inside_outside_intersect_connected:\n      \"\\<lbrakk>connected t; inside s \\<inter> t \\<noteq> {}; outside s \\<inter> t \\<noteq> {}\\<rbrakk> \\<Longrightarrow> s \\<inter> t \\<noteq> {}\"\n  apply (simp add: inside_def outside_def ex_in_conv [symmetric] disjoint_eq_subset_Compl, clarify)\n  by (metis (no_types, hide_lams) Compl_anti_mono connected_component_eq connected_component_maximal contra_subsetD double_compl)\n\nlemma outside_bounded_nonempty:\n  fixes s :: \"'a :: {real_normed_vector, perfect_space} set\"\n    assumes \"bounded s\" shows \"outside s \\<noteq> {}\"\n  by (metis (no_types, lifting) Collect_empty_eq Collect_mem_eq Compl_eq_Diff_UNIV Diff_cancel\n                   Diff_disjoint UNIV_I assms ball_eq_empty bounded_diff cobounded_outside convex_ball\n                   double_complement order_refl outside_convex outside_def)\n\nlemma outside_compact_in_open:\n    fixes s :: \"'a :: {real_normed_vector,perfect_space} set\"\n    assumes s: \"compact s\" and t: \"open t\" and \"s \\<subseteq> t\" \"t \\<noteq> {}\"\n      shows \"outside s \\<inter> t \\<noteq> {}\"\nproof -\n  have \"outside s \\<noteq> {}\"\n    by (simp add: compact_imp_bounded outside_bounded_nonempty s)\n  with assms obtain a b where a: \"a \\<in> outside s\" and b: \"b \\<in> t\" by auto\n  show ?thesis\n  proof (cases \"a \\<in> t\")\n    case True with a show ?thesis by blast\n  next\n    case False\n      have front: \"frontier t \\<subseteq> - s\"\n        using \\<open>s \\<subseteq> t\\<close> frontier_disjoint_eq t by auto\n      { fix \\<gamma>\n        assume \"path \\<gamma>\" and pimg_sbs: \"path_image \\<gamma> - {pathfinish \\<gamma>} \\<subseteq> interior (- t)\"\n           and pf: \"pathfinish \\<gamma> \\<in> frontier t\" and ps: \"pathstart \\<gamma> = a\"\n        define c where \"c = pathfinish \\<gamma>\"\n        have \"c \\<in> -s\" unfolding c_def using front pf by blast\n        moreover have \"open (-s)\" using s compact_imp_closed by blast\n        ultimately obtain \\<epsilon>::real where \"\\<epsilon> > 0\" and \\<epsilon>: \"cball c \\<epsilon> \\<subseteq> -s\"\n          using open_contains_cball[of \"-s\"] s by blast\n        then obtain d where \"d \\<in> t\" and d: \"dist d c < \\<epsilon>\"\n          using closure_approachable [of c t] pf unfolding c_def\n          by (metis Diff_iff frontier_def)\n        then have \"d \\<in> -s\" using \\<epsilon>\n          using dist_commute by (metis contra_subsetD mem_cball not_le not_less_iff_gr_or_eq)\n        have pimg_sbs_cos: \"path_image \\<gamma> \\<subseteq> -s\"\n          using pimg_sbs apply (auto simp: path_image_def)\n          apply (drule subsetD)\n          using \\<open>c \\<in> - s\\<close> \\<open>s \\<subseteq> t\\<close> interior_subset apply (auto simp: c_def)\n          done\n        have \"closed_segment c d \\<le> cball c \\<epsilon>\"\n          apply (simp add: segment_convex_hull)\n          apply (rule hull_minimal)\n          using  \\<open>\\<epsilon> > 0\\<close> d apply (auto simp: dist_commute)\n          done\n        with \\<epsilon> have \"closed_segment c d \\<subseteq> -s\" by blast\n        moreover have con_gcd: \"connected (path_image \\<gamma> \\<union> closed_segment c d)\"\n          by (rule connected_Un) (auto simp: c_def \\<open>path \\<gamma>\\<close> connected_path_image)\n        ultimately have \"connected_component (- s) a d\"\n          unfolding connected_component_def using pimg_sbs_cos ps by blast\n        then have \"outside s \\<inter> t \\<noteq> {}\"\n          using outside_same_component [OF _ a]  by (metis IntI \\<open>d \\<in> t\\<close> empty_iff)\n      } note * = this\n      have pal: \"pathstart (linepath a b) \\<in> closure (- t)\"\n        by (auto simp: False closure_def)\n      show ?thesis\n        by (rule exists_path_subpath_to_frontier [OF path_linepath pal _ *]) (auto simp: b)\n  qed\nqed\n\nlemma inside_inside_compact_connected:\n    fixes s :: \"'a :: euclidean_space set\"\n    assumes s: \"closed s\" and t: \"compact t\" and \"connected t\" \"s \\<subseteq> inside t\"\n      shows \"inside s \\<subseteq> inside t\"\nproof (cases \"inside t = {}\")\n  case True with assms show ?thesis by auto\nnext\n  case False\n  consider \"DIM('a) = 1\" | \"DIM('a) \\<ge> 2\"\n    using antisym not_less_eq_eq by fastforce\n  then show ?thesis\n  proof cases\n    case 1 then show ?thesis\n             using connected_convex_1_gen assms False inside_convex by blast\n  next\n    case 2\n    have coms: \"compact s\"\n      using assms apply (simp add: s compact_eq_bounded_closed)\n       by (meson bounded_inside bounded_subset compact_imp_bounded)\n    then have bst: \"bounded (s \\<union> t)\"\n      by (simp add: compact_imp_bounded t)\n    then obtain r where \"0 < r\" and r: \"s \\<union> t \\<subseteq> ball 0 r\"\n      using bounded_subset_ballD by blast\n    have outst: \"outside s \\<inter> outside t \\<noteq> {}\"\n    proof -\n      have \"- ball 0 r \\<subseteq> outside s\"\n        apply (rule outside_subset_convex)\n        using r by auto\n      moreover have \"- ball 0 r \\<subseteq> outside t\"\n        apply (rule outside_subset_convex)\n        using r by auto\n      ultimately show ?thesis\n        by (metis Compl_subset_Compl_iff Int_subset_iff bounded_ball inf.orderE outside_bounded_nonempty outside_no_overlap)\n    qed\n    have \"s \\<inter> t = {}\" using assms\n      by (metis disjoint_iff_not_equal inside_no_overlap subsetCE)\n    moreover have \"outside s \\<inter> inside t \\<noteq> {}\"\n      by (meson False assms(4) compact_eq_bounded_closed coms open_inside outside_compact_in_open t)\n    ultimately have \"inside s \\<inter> t = {}\"\n      using inside_outside_intersect_connected [OF \\<open>connected t\\<close>, of s]\n      by (metis \"2\" compact_eq_bounded_closed coms connected_outside inf.commute inside_outside_intersect_connected outst)\n    then show ?thesis\n      using inside_inside [OF \\<open>s \\<subseteq> inside t\\<close>] by blast\n  qed\nqed\n\nlemma connected_with_inside:\n    fixes s :: \"'a :: real_normed_vector set\"\n    assumes s: \"closed s\" and cons: \"connected s\"\n      shows \"connected(s \\<union> inside s)\"\nproof (cases \"s \\<union> inside s = UNIV\")\n  case True with assms show ?thesis by auto\nnext\n  case False\n  then obtain b where b: \"b \\<notin> s\" \"b \\<notin> inside s\" by blast\n  have *: \"\\<exists>y t. y \\<in> s \\<and> connected t \\<and> a \\<in> t \\<and> y \\<in> t \\<and> t \\<subseteq> (s \\<union> inside s)\" if \"a \\<in> (s \\<union> inside s)\" for a\n  using that proof\n    assume \"a \\<in> s\" then show ?thesis\n      apply (rule_tac x=a in exI)\n      apply (rule_tac x=\"{a}\" in exI)\n      apply (simp add:)\n      done\n  next\n    assume a: \"a \\<in> inside s\"\n    show ?thesis\n      apply (rule exists_path_subpath_to_frontier [OF path_linepath [of a b], of \"inside s\"])\n      using a apply (simp add: closure_def)\n      apply (simp add: b)\n      apply (rule_tac x=\"pathfinish h\" in exI)\n      apply (rule_tac x=\"path_image h\" in exI)\n      apply (simp add: pathfinish_in_path_image connected_path_image, auto)\n      using frontier_inside_subset s apply fastforce\n      by (metis (no_types, lifting) frontier_inside_subset insertE insert_Diff interior_eq open_inside pathfinish_in_path_image s subsetCE)\n  qed\n  show ?thesis\n    apply (simp add: connected_iff_connected_component)\n    apply (simp add: connected_component_def)\n    apply (clarify dest!: *)\n    apply (rename_tac u u' t t')\n    apply (rule_tac x=\"(s \\<union> t \\<union> t')\" in exI)\n    apply (auto simp: intro!: connected_Un cons)\n    done\nqed\n\ntext\\<open>The proof is virtually the same as that above.\\<close>\nlemma connected_with_outside:\n    fixes s :: \"'a :: real_normed_vector set\"\n    assumes s: \"closed s\" and cons: \"connected s\"\n      shows \"connected(s \\<union> outside s)\"\nproof (cases \"s \\<union> outside s = UNIV\")\n  case True with assms show ?thesis by auto\nnext\n  case False\n  then obtain b where b: \"b \\<notin> s\" \"b \\<notin> outside s\" by blast\n  have *: \"\\<exists>y t. y \\<in> s \\<and> connected t \\<and> a \\<in> t \\<and> y \\<in> t \\<and> t \\<subseteq> (s \\<union> outside s)\" if \"a \\<in> (s \\<union> outside s)\" for a\n  using that proof\n    assume \"a \\<in> s\" then show ?thesis\n      apply (rule_tac x=a in exI)\n      apply (rule_tac x=\"{a}\" in exI)\n      apply (simp add:)\n      done\n  next\n    assume a: \"a \\<in> outside s\"\n    show ?thesis\n      apply (rule exists_path_subpath_to_frontier [OF path_linepath [of a b], of \"outside s\"])\n      using a apply (simp add: closure_def)\n      apply (simp add: b)\n      apply (rule_tac x=\"pathfinish h\" in exI)\n      apply (rule_tac x=\"path_image h\" in exI)\n      apply (simp add: pathfinish_in_path_image connected_path_image, auto)\n      using frontier_outside_subset s apply fastforce\n      by (metis (no_types, lifting) frontier_outside_subset insertE insert_Diff interior_eq open_outside pathfinish_in_path_image s subsetCE)\n  qed\n  show ?thesis\n    apply (simp add: connected_iff_connected_component)\n    apply (simp add: connected_component_def)\n    apply (clarify dest!: *)\n    apply (rename_tac u u' t t')\n    apply (rule_tac x=\"(s \\<union> t \\<union> t')\" in exI)\n    apply (auto simp: intro!: connected_Un cons)\n    done\nqed\n\nlemma inside_inside_eq_empty [simp]:\n    fixes s :: \"'a :: {real_normed_vector, perfect_space} set\"\n    assumes s: \"closed s\" and cons: \"connected s\"\n      shows \"inside (inside s) = {}\"\n  by (metis (no_types) unbounded_outside connected_with_outside [OF assms] bounded_Un\n           inside_complement_unbounded_connected_empty unbounded_outside union_with_outside)\n\nlemma inside_in_components:\n     \"inside s \\<in> components (- s) \\<longleftrightarrow> connected(inside s) \\<and> inside s \\<noteq> {}\"\n  apply (simp add: in_components_maximal)\n  apply (auto intro: inside_same_component connected_componentI)\n  apply (metis IntI empty_iff inside_no_overlap)\n  done\n\ntext\\<open>The proof is virtually the same as that above.\\<close>\nlemma outside_in_components:\n     \"outside s \\<in> components (- s) \\<longleftrightarrow> connected(outside s) \\<and> outside s \\<noteq> {}\"\n  apply (simp add: in_components_maximal)\n  apply (auto intro: outside_same_component connected_componentI)\n  apply (metis IntI empty_iff outside_no_overlap)\n  done\n\nlemma bounded_unique_outside:\n    fixes s :: \"'a :: euclidean_space set\"\n    shows \"\\<lbrakk>bounded s; DIM('a) \\<ge> 2\\<rbrakk> \\<Longrightarrow> (c \\<in> components (- s) \\<and> ~bounded c \\<longleftrightarrow> c = outside s)\"\n  apply (rule iffI)\n  apply (metis cobounded_unique_unbounded_components connected_outside double_compl outside_bounded_nonempty outside_in_components unbounded_outside)\n  by (simp add: connected_outside outside_bounded_nonempty outside_in_components unbounded_outside)\n\nsubsection\\<open>Condition for an open map's image to contain a ball\\<close>\n\nlemma ball_subset_open_map_image:\n  fixes f :: \"'a::heine_borel \\<Rightarrow> 'b :: {real_normed_vector,heine_borel}\"\n  assumes contf: \"continuous_on (closure S) f\"\n      and oint: \"open (f ` interior S)\"\n      and le_no: \"\\<And>z. z \\<in> frontier S \\<Longrightarrow> r \\<le> norm(f z - f a)\"\n      and \"bounded S\" \"a \\<in> S\" \"0 < r\"\n    shows \"ball (f a) r \\<subseteq> f ` S\"\nproof (cases \"f ` S = UNIV\")\n  case True then show ?thesis by simp\nnext\n  case False\n    obtain w where w: \"w \\<in> frontier (f ` S)\"\n               and dw_le: \"\\<And>y. y \\<in> frontier (f ` S) \\<Longrightarrow> norm (f a - w) \\<le> norm (f a - y)\"\n      apply (rule distance_attains_inf [of \"frontier(f ` S)\" \"f a\"])\n      using \\<open>a \\<in> S\\<close> by (auto simp: frontier_eq_empty dist_norm False)\n    then obtain \\<xi> where \\<xi>: \"\\<And>n. \\<xi> n \\<in> f ` S\" and tendsw: \"\\<xi> \\<longlonglongrightarrow> w\"\n      by (metis Diff_iff frontier_def closure_sequential)\n    then have \"\\<And>n. \\<exists>x \\<in> S. \\<xi> n = f x\" by force\n    then obtain z where zs: \"\\<And>n. z n \\<in> S\" and fz: \"\\<And>n. \\<xi> n = f (z n)\"\n      by metis\n    then obtain y K where y: \"y \\<in> closure S\" and \"subseq K\" and Klim: \"(z \\<circ> K) \\<longlonglongrightarrow> y\"\n      using \\<open>bounded S\\<close>\n      apply (simp add: compact_closure [symmetric] compact_def)\n      apply (drule_tac x=z in spec)\n      using closure_subset apply force\n      done\n    then have ftendsw: \"((\\<lambda>n. f (z n)) \\<circ> K) \\<longlonglongrightarrow> w\"\n      by (metis LIMSEQ_subseq_LIMSEQ fun.map_cong0 fz tendsw)\n    have zKs: \"\\<And>n. (z o K) n \\<in> S\" by (simp add: zs)\n    have fz: \"f \\<circ> z = \\<xi>\"  \"(\\<lambda>n. f (z n)) = \\<xi>\"\n      using fz by auto\n    then have \"(\\<xi> \\<circ> K) \\<longlonglongrightarrow> f y\"\n      by (metis (no_types) Klim zKs y contf comp_assoc continuous_on_closure_sequentially)\n    with fz have wy: \"w = f y\" using fz LIMSEQ_unique ftendsw by auto\n    have rle: \"r \\<le> norm (f y - f a)\"\n      apply (rule le_no)\n      using w wy oint\n      by (force simp: imageI image_mono interiorI interior_subset frontier_def y)\n    have **: \"(~(b \\<inter> (- S) = {}) \\<and> ~(b - (- S) = {}) \\<Longrightarrow> (b \\<inter> f \\<noteq> {}))\n              \\<Longrightarrow> (b \\<inter> S \\<noteq> {}) \\<Longrightarrow> b \\<inter> f = {} \\<Longrightarrow>\n              b \\<subseteq> S\" for b f and S :: \"'b set\"\n      by blast\n    show ?thesis\n      apply (rule **)   (*such a horrible mess*)\n      apply (rule connected_Int_frontier [where t = \"f`S\", OF connected_ball])\n      using \\<open>a \\<in> S\\<close> \\<open>0 < r\\<close>\n      apply (auto simp: disjoint_iff_not_equal  dist_norm)\n      by (metis dw_le norm_minus_commute not_less order_trans rle wy)\nqed\n\nsection\\<open> Homotopy of maps p,q : X=>Y with property P of all intermediate maps.\\<close>\n\ntext\\<open> We often just want to require that it fixes some subset, but to take in\n  the case of a loop homotopy, it's convenient to have a general property P.\\<close>\n\ndefinition homotopic_with ::\n  \"[('a::topological_space \\<Rightarrow> 'b::topological_space) \\<Rightarrow> bool, 'a set, 'b set, 'a \\<Rightarrow> 'b, 'a \\<Rightarrow> 'b] \\<Rightarrow> bool\"\nwhere\n \"homotopic_with P X Y p q \\<equiv>\n   (\\<exists>h:: real \\<times> 'a \\<Rightarrow> 'b.\n       continuous_on ({0..1} \\<times> X) h \\<and>\n       h ` ({0..1} \\<times> X) \\<subseteq> Y \\<and>\n       (\\<forall>x. h(0, x) = p x) \\<and>\n       (\\<forall>x. h(1, x) = q x) \\<and>\n       (\\<forall>t \\<in> {0..1}. P(\\<lambda>x. h(t, x))))\"\n\n\ntext\\<open> We often want to just localize the ending function equality or whatever.\\<close>\nproposition homotopic_with:\n  fixes X :: \"'a::topological_space set\" and Y :: \"'b::topological_space set\"\n  assumes \"\\<And>h k. (\\<And>x. x \\<in> X \\<Longrightarrow> h x = k x) \\<Longrightarrow> (P h \\<longleftrightarrow> P k)\"\n  shows \"homotopic_with P X Y p q \\<longleftrightarrow>\n           (\\<exists>h :: real \\<times> 'a \\<Rightarrow> 'b.\n              continuous_on ({0..1} \\<times> X) h \\<and>\n              h ` ({0..1} \\<times> X) \\<subseteq> Y \\<and>\n              (\\<forall>x \\<in> X. h(0,x) = p x) \\<and>\n              (\\<forall>x \\<in> X. h(1,x) = q x) \\<and>\n              (\\<forall>t \\<in> {0..1}. P(\\<lambda>x. h(t, x))))\"\n  unfolding homotopic_with_def\n  apply (rule iffI, blast, clarify)\n  apply (rule_tac x=\"\\<lambda>(u,v). if v \\<in> X then h(u,v) else if u = 0 then p v else q v\" in exI)\n  apply (auto simp:)\n  apply (force elim: continuous_on_eq)\n  apply (drule_tac x=t in bspec, force)\n  apply (subst assms; simp)\n  done\n\nproposition homotopic_with_eq:\n   assumes h: \"homotopic_with P X Y f g\"\n       and f': \"\\<And>x. x \\<in> X \\<Longrightarrow> f' x = f x\"\n       and g': \"\\<And>x. x \\<in> X \\<Longrightarrow> g' x = g x\"\n       and P:  \"(\\<And>h k. (\\<And>x. x \\<in> X \\<Longrightarrow> h x = k x) \\<Longrightarrow> (P h \\<longleftrightarrow> P k))\"\n   shows \"homotopic_with P X Y f' g'\"\n  using h unfolding homotopic_with_def\n  apply safe\n  apply (rule_tac x=\"\\<lambda>(u,v). if v \\<in> X then h(u,v) else if u = 0 then f' v else g' v\" in exI)\n  apply (simp add: f' g', safe)\n  apply (fastforce intro: continuous_on_eq)\n  apply fastforce\n  apply (subst P; fastforce)\n  done\n\nproposition homotopic_with_equal:\n   assumes contf: \"continuous_on X f\" and fXY: \"f ` X \\<subseteq> Y\"\n       and gf: \"\\<And>x. x \\<in> X \\<Longrightarrow> g x = f x\"\n       and P:  \"P f\" \"P g\"\n   shows \"homotopic_with P X Y f g\"\n  unfolding homotopic_with_def\n  apply (rule_tac x=\"\\<lambda>(u,v). if u = 1 then g v else f v\" in exI)\n  using assms\n  apply (intro conjI)\n  apply (rule continuous_on_eq [where f = \"f o snd\"])\n  apply (rule continuous_intros | force)+\n  apply clarify\n  apply (case_tac \"t=1\"; force)\n  done\n\n\nlemma image_Pair_const: \"(\\<lambda>x. (x, c)) ` A = A \\<times> {c}\"\n  by (auto simp:)\n\nlemma homotopic_constant_maps:\n   \"homotopic_with (\\<lambda>x. True) s t (\\<lambda>x. a) (\\<lambda>x. b) \\<longleftrightarrow> s = {} \\<or> path_component t a b\"\nproof (cases \"s = {} \\<or> t = {}\")\n  case True with continuous_on_const show ?thesis\n    by (auto simp: homotopic_with path_component_def)\nnext\n  case False\n  then obtain c where \"c \\<in> s\" by blast\n  show ?thesis\n  proof\n    assume \"homotopic_with (\\<lambda>x. True) s t (\\<lambda>x. a) (\\<lambda>x. b)\"\n    then obtain h :: \"real \\<times> 'a \\<Rightarrow> 'b\"\n        where conth: \"continuous_on ({0..1} \\<times> s) h\"\n          and h: \"h ` ({0..1} \\<times> s) \\<subseteq> t\" \"(\\<forall>x\\<in>s. h (0, x) = a)\" \"(\\<forall>x\\<in>s. h (1, x) = b)\"\n      by (auto simp: homotopic_with)\n    have \"continuous_on {0..1} (h \\<circ> (\\<lambda>t. (t, c)))\"\n      apply (rule continuous_intros conth | simp add: image_Pair_const)+\n      apply (blast intro:  \\<open>c \\<in> s\\<close> continuous_on_subset [OF conth] )\n      done\n    with \\<open>c \\<in> s\\<close> h show \"s = {} \\<or> path_component t a b\"\n      apply (simp_all add: homotopic_with path_component_def)\n      apply (auto simp:)\n      apply (drule_tac x=\"h o (\\<lambda>t. (t, c))\" in spec)\n      apply (auto simp: pathstart_def pathfinish_def path_image_def path_def)\n      done\n  next\n    assume \"s = {} \\<or> path_component t a b\"\n    with False show \"homotopic_with (\\<lambda>x. True) s t (\\<lambda>x. a) (\\<lambda>x. b)\"\n      apply (clarsimp simp: homotopic_with path_component_def pathstart_def pathfinish_def path_image_def path_def)\n      apply (rule_tac x=\"g o fst\" in exI)\n      apply (rule conjI continuous_intros | force)+\n      done\n  qed\nqed\n\n\nsubsection\\<open> Trivial properties.\\<close>\n\nlemma homotopic_with_imp_property: \"homotopic_with P X Y f g \\<Longrightarrow> P f \\<and> P g\"\n  unfolding homotopic_with_def Ball_def\n  apply clarify\n  apply (frule_tac x=0 in spec)\n  apply (drule_tac x=1 in spec)\n  apply (auto simp:)\n  done\n\nlemma continuous_on_o_Pair: \"\\<lbrakk>continuous_on (T \\<times> X) h; t \\<in> T\\<rbrakk> \\<Longrightarrow> continuous_on X (h o Pair t)\"\n  by (fast intro: continuous_intros elim!: continuous_on_subset)\n\nlemma homotopic_with_imp_continuous:\n    assumes \"homotopic_with P X Y f g\"\n    shows \"continuous_on X f \\<and> continuous_on X g\"\nproof -\n  obtain h :: \"real \\<times> 'a \\<Rightarrow> 'b\"\n    where conth: \"continuous_on ({0..1} \\<times> X) h\"\n      and h: \"\\<forall>x. h (0, x) = f x\" \"\\<forall>x. h (1, x) = g x\"\n    using assms by (auto simp: homotopic_with_def)\n  have *: \"t \\<in> {0..1} \\<Longrightarrow> continuous_on X (h o (\\<lambda>x. (t,x)))\" for t\n    by (rule continuous_intros continuous_on_subset [OF conth] | force)+\n  show ?thesis\n    using h *[of 0] *[of 1] by auto\nqed\n\nproposition homotopic_with_imp_subset1:\n     \"homotopic_with P X Y f g \\<Longrightarrow> f ` X \\<subseteq> Y\"\n  by (simp add: homotopic_with_def image_subset_iff) (metis atLeastAtMost_iff order_refl zero_le_one)\n\nproposition homotopic_with_imp_subset2:\n     \"homotopic_with P X Y f g \\<Longrightarrow> g ` X \\<subseteq> Y\"\n  by (simp add: homotopic_with_def image_subset_iff) (metis atLeastAtMost_iff order_refl zero_le_one)\n\nproposition homotopic_with_mono:\n    assumes hom: \"homotopic_with P X Y f g\"\n        and Q: \"\\<And>h. \\<lbrakk>continuous_on X h; image h X \\<subseteq> Y \\<and> P h\\<rbrakk> \\<Longrightarrow> Q h\"\n      shows \"homotopic_with Q X Y f g\"\n  using hom\n  apply (simp add: homotopic_with_def)\n  apply (erule ex_forward)\n  apply (force simp: intro!: Q dest: continuous_on_o_Pair)\n  done\n\nproposition homotopic_with_subset_left:\n     \"\\<lbrakk>homotopic_with P X Y f g; Z \\<subseteq> X\\<rbrakk> \\<Longrightarrow> homotopic_with P Z Y f g\"\n  apply (simp add: homotopic_with_def)\n  apply (fast elim!: continuous_on_subset ex_forward)\n  done\n\nproposition homotopic_with_subset_right:\n     \"\\<lbrakk>homotopic_with P X Y f g; Y \\<subseteq> Z\\<rbrakk> \\<Longrightarrow> homotopic_with P X Z f g\"\n  apply (simp add: homotopic_with_def)\n  apply (fast elim!: continuous_on_subset ex_forward)\n  done\n\nproposition homotopic_with_compose_continuous_right:\n    \"\\<lbrakk>homotopic_with (\\<lambda>f. p (f \\<circ> h)) X Y f g; continuous_on W h; h ` W \\<subseteq> X\\<rbrakk>\n     \\<Longrightarrow> homotopic_with p W Y (f o h) (g o h)\"\n  apply (clarsimp simp add: homotopic_with_def)\n  apply (rename_tac k)\n  apply (rule_tac x=\"k o (\\<lambda>y. (fst y, h (snd y)))\" in exI)\n  apply (rule conjI continuous_intros continuous_on_compose [where f=snd and g=h, unfolded o_def] | simp)+\n  apply (erule continuous_on_subset)\n  apply (fastforce simp: o_def)+\n  done\n\nproposition homotopic_compose_continuous_right:\n     \"\\<lbrakk>homotopic_with (\\<lambda>f. True) X Y f g; continuous_on W h; h ` W \\<subseteq> X\\<rbrakk>\n      \\<Longrightarrow> homotopic_with (\\<lambda>f. True) W Y (f o h) (g o h)\"\n  using homotopic_with_compose_continuous_right by fastforce\n\nproposition homotopic_with_compose_continuous_left:\n     \"\\<lbrakk>homotopic_with (\\<lambda>f. p (h \\<circ> f)) X Y f g; continuous_on Y h; h ` Y \\<subseteq> Z\\<rbrakk>\n      \\<Longrightarrow> homotopic_with p X Z (h o f) (h o g)\"\n  apply (clarsimp simp add: homotopic_with_def)\n  apply (rename_tac k)\n  apply (rule_tac x=\"h o k\" in exI)\n  apply (rule conjI continuous_intros continuous_on_compose [where f=snd and g=h, unfolded o_def] | simp)+\n  apply (erule continuous_on_subset)\n  apply (fastforce simp: o_def)+\n  done\n\nproposition homotopic_compose_continuous_left:\n   \"\\<lbrakk>homotopic_with (\\<lambda>_. True) X Y f g;\n     continuous_on Y h; h ` Y \\<subseteq> Z\\<rbrakk>\n    \\<Longrightarrow> homotopic_with (\\<lambda>f. True) X Z (h o f) (h o g)\"\n  using homotopic_with_compose_continuous_left by fastforce\n\nproposition homotopic_with_Pair:\n   assumes hom: \"homotopic_with p s t f g\" \"homotopic_with p' s' t' f' g'\"\n       and q: \"\\<And>f g. \\<lbrakk>p f; p' g\\<rbrakk> \\<Longrightarrow> q(\\<lambda>(x,y). (f x, g y))\"\n     shows \"homotopic_with q (s \\<times> s') (t \\<times> t')\n                  (\\<lambda>(x,y). (f x, f' y)) (\\<lambda>(x,y). (g x, g' y))\"\n  using hom\n  apply (clarsimp simp add: homotopic_with_def)\n  apply (rename_tac k k')\n  apply (rule_tac x=\"\\<lambda>z. ((k o (\\<lambda>x. (fst x, fst (snd x)))) z, (k' o (\\<lambda>x. (fst x, snd (snd x)))) z)\" in exI)\n  apply (rule conjI continuous_intros | erule continuous_on_subset | clarsimp)+\n  apply (auto intro!: q [unfolded case_prod_unfold])\n  done\n\nlemma homotopic_on_empty [simp]: \"homotopic_with (\\<lambda>x. True) {} t f g\"\n  by (metis continuous_on_def empty_iff homotopic_with_equal image_subset_iff)\n\n\ntext\\<open>Homotopy with P is an equivalence relation (on continuous functions mapping X into Y that satisfy P,\n     though this only affects reflexivity.\\<close>\n\n\nproposition homotopic_with_refl:\n   \"homotopic_with P X Y f f \\<longleftrightarrow> continuous_on X f \\<and> image f X \\<subseteq> Y \\<and> P f\"\n  apply (rule iffI)\n  using homotopic_with_imp_continuous homotopic_with_imp_property homotopic_with_imp_subset2 apply blast\n  apply (simp add: homotopic_with_def)\n  apply (rule_tac x=\"f o snd\" in exI)\n  apply (rule conjI continuous_intros | force)+\n  done\n\nlemma homotopic_with_symD:\n  fixes X :: \"'a::real_normed_vector set\"\n    assumes \"homotopic_with P X Y f g\"\n      shows \"homotopic_with P X Y g f\"\n  using assms\n  apply (clarsimp simp add: homotopic_with_def)\n  apply (rename_tac h)\n  apply (rule_tac x=\"h o (\\<lambda>y. (1 - fst y, snd y))\" in exI)\n  apply (rule conjI continuous_intros | erule continuous_on_subset | force simp add: image_subset_iff)+\n  done\n\nproposition homotopic_with_sym:\n    fixes X :: \"'a::real_normed_vector set\"\n    shows \"homotopic_with P X Y f g \\<longleftrightarrow> homotopic_with P X Y g f\"\n  using homotopic_with_symD by blast\n\nlemma split_01: \"{0..1::real} = {0..1/2} \\<union> {1/2..1}\"\n  by force\n\nlemma split_01_prod: \"{0..1::real} \\<times> X = ({0..1/2} \\<times> X) \\<union> ({1/2..1} \\<times> X)\"\n  by force\n\nproposition homotopic_with_trans:\n    fixes X :: \"'a::real_normed_vector set\"\n    assumes \"homotopic_with P X Y f g\" and \"homotopic_with P X Y g h\"\n      shows \"homotopic_with P X Y f h\"\nproof -\n  have clo1: \"closedin (subtopology euclidean ({0..1/2} \\<times> X \\<union> {1/2..1} \\<times> X)) ({0..1/2::real} \\<times> X)\"\n    apply (simp add: closedin_closed split_01_prod [symmetric])\n    apply (rule_tac x=\"{0..1/2} \\<times> UNIV\" in exI)\n    apply (force simp add: closed_Times)\n    done\n  have clo2: \"closedin (subtopology euclidean ({0..1/2} \\<times> X \\<union> {1/2..1} \\<times> X)) ({1/2..1::real} \\<times> X)\"\n    apply (simp add: closedin_closed split_01_prod [symmetric])\n    apply (rule_tac x=\"{1/2..1} \\<times> UNIV\" in exI)\n    apply (force simp add: closed_Times)\n    done\n  { fix k1 k2:: \"real \\<times> 'a \\<Rightarrow> 'b\"\n    assume cont: \"continuous_on ({0..1} \\<times> X) k1\" \"continuous_on ({0..1} \\<times> X) k2\"\n       and Y: \"k1 ` ({0..1} \\<times> X) \\<subseteq> Y\" \"k2 ` ({0..1} \\<times> X) \\<subseteq> Y\"\n       and geq: \"\\<forall>x. k1 (1, x) = g x\" \"\\<forall>x. k2 (0, x) = g x\"\n       and k12: \"\\<forall>x. k1 (0, x) = f x\" \"\\<forall>x. k2 (1, x) = h x\"\n       and P:   \"\\<forall>t\\<in>{0..1}. P (\\<lambda>x. k1 (t, x))\" \"\\<forall>t\\<in>{0..1}. P (\\<lambda>x. k2 (t, x))\"\n    define k where \"k y =\n      (if fst y \\<le> 1 / 2\n       then (k1 o (\\<lambda>x. (2 *\\<^sub>R fst x, snd x))) y\n       else (k2 o (\\<lambda>x. (2 *\\<^sub>R fst x -1, snd x))) y)\" for y\n    have keq: \"k1 (2 * u, v) = k2 (2 * u - 1, v)\" if \"u = 1/2\"  for u v\n      by (simp add: geq that)\n    have \"continuous_on ({0..1} \\<times> X) k\"\n      using cont\n      apply (simp add: split_01_prod k_def)\n      apply (rule clo1 clo2 continuous_on_cases_local continuous_intros | erule continuous_on_subset | simp add: linear image_subset_iff)+\n      apply (force simp add: keq)\n      done\n    moreover have \"k ` ({0..1} \\<times> X) \\<subseteq> Y\"\n      using Y by (force simp add: k_def)\n    moreover have \"\\<forall>x. k (0, x) = f x\"\n      by (simp add: k_def k12)\n    moreover have \"(\\<forall>x. k (1, x) = h x)\"\n      by (simp add: k_def k12)\n    moreover have \"\\<forall>t\\<in>{0..1}. P (\\<lambda>x. k (t, x))\"\n      using P\n      apply (clarsimp simp add: k_def)\n      apply (case_tac \"t \\<le> 1/2\")\n      apply (auto simp:)\n      done\n    ultimately have *: \"\\<exists>k :: real \\<times> 'a \\<Rightarrow> 'b.\n                       continuous_on ({0..1} \\<times> X) k \\<and> k ` ({0..1} \\<times> X) \\<subseteq> Y \\<and>\n                       (\\<forall>x. k (0, x) = f x) \\<and> (\\<forall>x. k (1, x) = h x) \\<and> (\\<forall>t\\<in>{0..1}. P (\\<lambda>x. k (t, x)))\"\n      by blast\n  } note * = this\n  show ?thesis\n    using assms by (auto intro: * simp add: homotopic_with_def)\nqed\n\nproposition homotopic_compose:\n      fixes s :: \"'a::real_normed_vector set\"\n      shows \"\\<lbrakk>homotopic_with (\\<lambda>x. True) s t f f'; homotopic_with (\\<lambda>x. True) t u g g'\\<rbrakk>\n             \\<Longrightarrow> homotopic_with (\\<lambda>x. True) s u (g o f) (g' o f')\"\n  apply (rule homotopic_with_trans [where g = \"g o f'\"])\n  apply (metis homotopic_compose_continuous_left homotopic_with_imp_continuous homotopic_with_imp_subset1)\n  by (metis homotopic_compose_continuous_right homotopic_with_imp_continuous homotopic_with_imp_subset2)\n\n\nsubsection\\<open>Homotopy of paths, maintaining the same endpoints.\\<close>\n\n\ndefinition homotopic_paths :: \"['a set, real \\<Rightarrow> 'a, real \\<Rightarrow> 'a::topological_space] \\<Rightarrow> bool\"\n  where\n     \"homotopic_paths s p q \\<equiv>\n       homotopic_with (\\<lambda>r. pathstart r = pathstart p \\<and> pathfinish r = pathfinish p) {0..1} s p q\"\n\nlemma homotopic_paths:\n   \"homotopic_paths s p q \\<longleftrightarrow>\n      (\\<exists>h. continuous_on ({0..1} \\<times> {0..1}) h \\<and>\n          h ` ({0..1} \\<times> {0..1}) \\<subseteq> s \\<and>\n          (\\<forall>x \\<in> {0..1}. h(0,x) = p x) \\<and>\n          (\\<forall>x \\<in> {0..1}. h(1,x) = q x) \\<and>\n          (\\<forall>t \\<in> {0..1::real}. pathstart(h o Pair t) = pathstart p \\<and>\n                        pathfinish(h o Pair t) = pathfinish p))\"\n  by (auto simp: homotopic_paths_def homotopic_with pathstart_def pathfinish_def)\n\nproposition homotopic_paths_imp_pathstart:\n     \"homotopic_paths s p q \\<Longrightarrow> pathstart p = pathstart q\"\n  by (metis (mono_tags, lifting) homotopic_paths_def homotopic_with_imp_property)\n\nproposition homotopic_paths_imp_pathfinish:\n     \"homotopic_paths s p q \\<Longrightarrow> pathfinish p = pathfinish q\"\n  by (metis (mono_tags, lifting) homotopic_paths_def homotopic_with_imp_property)\n\nlemma homotopic_paths_imp_path:\n     \"homotopic_paths s p q \\<Longrightarrow> path p \\<and> path q\"\n  using homotopic_paths_def homotopic_with_imp_continuous path_def by blast\n\nlemma homotopic_paths_imp_subset:\n     \"homotopic_paths s p q \\<Longrightarrow> path_image p \\<subseteq> s \\<and> path_image q \\<subseteq> s\"\n  by (simp add: homotopic_paths_def homotopic_with_imp_subset1 homotopic_with_imp_subset2 path_image_def)\n\nproposition homotopic_paths_refl [simp]: \"homotopic_paths s p p \\<longleftrightarrow> path p \\<and> path_image p \\<subseteq> s\"\nby (simp add: homotopic_paths_def homotopic_with_refl path_def path_image_def)\n\nproposition homotopic_paths_sym: \"homotopic_paths s p q \\<Longrightarrow> homotopic_paths s q p\"\n  by (metis (mono_tags) homotopic_paths_def homotopic_paths_imp_pathfinish homotopic_paths_imp_pathstart homotopic_with_symD)\n\nproposition homotopic_paths_sym_eq: \"homotopic_paths s p q \\<longleftrightarrow> homotopic_paths s q p\"\n  by (metis homotopic_paths_sym)\n\nproposition homotopic_paths_trans [trans]:\n     \"\\<lbrakk>homotopic_paths s p q; homotopic_paths s q r\\<rbrakk> \\<Longrightarrow> homotopic_paths s p r\"\n  apply (simp add: homotopic_paths_def)\n  apply (rule homotopic_with_trans, assumption)\n  by (metis (mono_tags, lifting) homotopic_with_imp_property homotopic_with_mono)\n\nproposition homotopic_paths_eq:\n     \"\\<lbrakk>path p; path_image p \\<subseteq> s; \\<And>t. t \\<in> {0..1} \\<Longrightarrow> p t = q t\\<rbrakk> \\<Longrightarrow> homotopic_paths s p q\"\n  apply (simp add: homotopic_paths_def)\n  apply (rule homotopic_with_eq)\n  apply (auto simp: path_def homotopic_with_refl pathstart_def pathfinish_def path_image_def elim: continuous_on_eq)\n  done\n\nproposition homotopic_paths_reparametrize:\n  assumes \"path p\"\n      and pips: \"path_image p \\<subseteq> s\"\n      and contf: \"continuous_on {0..1} f\"\n      and f01:\"f ` {0..1} \\<subseteq> {0..1}\"\n      and [simp]: \"f(0) = 0\" \"f(1) = 1\"\n      and q: \"\\<And>t. t \\<in> {0..1} \\<Longrightarrow> q(t) = p(f t)\"\n    shows \"homotopic_paths s p q\"\nproof -\n  have contp: \"continuous_on {0..1} p\"\n    by (metis \\<open>path p\\<close> path_def)\n  then have \"continuous_on {0..1} (p o f)\"\n    using contf continuous_on_compose continuous_on_subset f01 by blast\n  then have \"path q\"\n    by (simp add: path_def) (metis q continuous_on_cong)\n  have piqs: \"path_image q \\<subseteq> s\"\n    by (metis (no_types, hide_lams) pips f01 image_subset_iff path_image_def q)\n  have fb0: \"\\<And>a b. \\<lbrakk>0 \\<le> a; a \\<le> 1; 0 \\<le> b; b \\<le> 1\\<rbrakk> \\<Longrightarrow> 0 \\<le> (1 - a) * f b + a * b\"\n    using f01 by force\n  have fb1: \"\\<lbrakk>0 \\<le> a; a \\<le> 1; 0 \\<le> b; b \\<le> 1\\<rbrakk> \\<Longrightarrow> (1 - a) * f b + a * b \\<le> 1\" for a b\n    using f01 [THEN subsetD, of \"f b\"] by (simp add: convex_bound_le)\n  have \"homotopic_paths s q p\"\n  proof (rule homotopic_paths_trans)\n    show \"homotopic_paths s q (p \\<circ> f)\"\n      using q by (force intro: homotopic_paths_eq [OF  \\<open>path q\\<close> piqs])\n  next\n    show \"homotopic_paths s (p \\<circ> f) p\"\n      apply (simp add: homotopic_paths_def homotopic_with_def)\n      apply (rule_tac x=\"p o (\\<lambda>y. (1 - (fst y)) *\\<^sub>R ((f o snd) y) + (fst y) *\\<^sub>R snd y)\"  in exI)\n      apply (rule conjI contf continuous_intros continuous_on_subset [OF contp] | simp)+\n      using pips [unfolded path_image_def]\n      apply (auto simp: fb0 fb1 pathstart_def pathfinish_def)\n      done\n  qed\n  then show ?thesis\n    by (simp add: homotopic_paths_sym)\nqed\n\nlemma homotopic_paths_subset: \"\\<lbrakk>homotopic_paths s p q; s \\<subseteq> t\\<rbrakk> \\<Longrightarrow> homotopic_paths t p q\"\n  using homotopic_paths_def homotopic_with_subset_right by blast\n\n\ntext\\<open> A slightly ad-hoc but useful lemma in constructing homotopies.\\<close>\nlemma homotopic_join_lemma:\n  fixes q :: \"[real,real] \\<Rightarrow> 'a::topological_space\"\n  assumes p: \"continuous_on ({0..1} \\<times> {0..1}) (\\<lambda>y. p (fst y) (snd y))\"\n      and q: \"continuous_on ({0..1} \\<times> {0..1}) (\\<lambda>y. q (fst y) (snd y))\"\n      and pf: \"\\<And>t. t \\<in> {0..1} \\<Longrightarrow> pathfinish(p t) = pathstart(q t)\"\n    shows \"continuous_on ({0..1} \\<times> {0..1}) (\\<lambda>y. (p(fst y) +++ q(fst y)) (snd y))\"\nproof -\n  have 1: \"(\\<lambda>y. p (fst y) (2 * snd y)) = (\\<lambda>y. p (fst y) (snd y)) o (\\<lambda>y. (fst y, 2 * snd y))\"\n    by (rule ext) (simp )\n  have 2: \"(\\<lambda>y. q (fst y) (2 * snd y - 1)) = (\\<lambda>y. q (fst y) (snd y)) o (\\<lambda>y. (fst y, 2 * snd y - 1))\"\n    by (rule ext) (simp )\n  show ?thesis\n    apply (simp add: joinpaths_def)\n    apply (rule continuous_on_cases_le)\n    apply (simp_all only: 1 2)\n    apply (rule continuous_intros continuous_on_subset [OF p] continuous_on_subset [OF q] | force)+\n    using pf\n    apply (auto simp: mult.commute pathstart_def pathfinish_def)\n    done\nqed\n\ntext\\<open> Congruence properties of homotopy w.r.t. path-combining operations.\\<close>\n\nlemma homotopic_paths_reversepath_D:\n      assumes \"homotopic_paths s p q\"\n      shows   \"homotopic_paths s (reversepath p) (reversepath q)\"\n  using assms\n  apply (simp add: homotopic_paths_def homotopic_with_def, clarify)\n  apply (rule_tac x=\"h o (\\<lambda>x. (fst x, 1 - snd x))\" in exI)\n  apply (rule conjI continuous_intros)+\n  apply (auto simp: reversepath_def pathstart_def pathfinish_def elim!: continuous_on_subset)\n  done\n\nproposition homotopic_paths_reversepath:\n     \"homotopic_paths s (reversepath p) (reversepath q) \\<longleftrightarrow> homotopic_paths s p q\"\n  using homotopic_paths_reversepath_D by force\n\n\nproposition homotopic_paths_join:\n    \"\\<lbrakk>homotopic_paths s p p'; homotopic_paths s q q'; pathfinish p = pathstart q\\<rbrakk> \\<Longrightarrow> homotopic_paths s (p +++ q) (p' +++ q')\"\n  apply (simp add: homotopic_paths_def homotopic_with_def, clarify)\n  apply (rename_tac k1 k2)\n  apply (rule_tac x=\"(\\<lambda>y. ((k1 o Pair (fst y)) +++ (k2 o Pair (fst y))) (snd y))\" in exI)\n  apply (rule conjI continuous_intros homotopic_join_lemma)+\n  apply (auto simp: joinpaths_def pathstart_def pathfinish_def path_image_def)\n  done\n\nproposition homotopic_paths_continuous_image:\n    \"\\<lbrakk>homotopic_paths s f g; continuous_on s h; h ` s \\<subseteq> t\\<rbrakk> \\<Longrightarrow> homotopic_paths t (h o f) (h o g)\"\n  unfolding homotopic_paths_def\n  apply (rule homotopic_with_compose_continuous_left [of _ _ _ s])\n  apply (auto simp: pathstart_def pathfinish_def elim!: homotopic_with_mono)\n  done\n\nsubsection\\<open>Group properties for homotopy of paths\\<close>\n\ntext\\<open>So taking equivalence classes under homotopy would give the fundamental group\\<close>\n\nproposition homotopic_paths_rid:\n    \"\\<lbrakk>path p; path_image p \\<subseteq> s\\<rbrakk> \\<Longrightarrow> homotopic_paths s (p +++ linepath (pathfinish p) (pathfinish p)) p\"\n  apply (subst homotopic_paths_sym)\n  apply (rule homotopic_paths_reparametrize [where f = \"\\<lambda>t. if  t \\<le> 1 / 2 then 2 *\\<^sub>R t else 1\"])\n  apply (simp_all del: le_divide_eq_numeral1)\n  apply (subst split_01)\n  apply (rule continuous_on_cases continuous_intros | force simp: pathfinish_def joinpaths_def)+\n  done\n\nproposition homotopic_paths_lid:\n   \"\\<lbrakk>path p; path_image p \\<subseteq> s\\<rbrakk> \\<Longrightarrow> homotopic_paths s (linepath (pathstart p) (pathstart p) +++ p) p\"\nusing homotopic_paths_rid [of \"reversepath p\" s]\n  by (metis homotopic_paths_reversepath path_image_reversepath path_reversepath pathfinish_linepath\n        pathfinish_reversepath reversepath_joinpaths reversepath_linepath)\n\nproposition homotopic_paths_assoc:\n   \"\\<lbrakk>path p; path_image p \\<subseteq> s; path q; path_image q \\<subseteq> s; path r; path_image r \\<subseteq> s; pathfinish p = pathstart q;\n     pathfinish q = pathstart r\\<rbrakk>\n    \\<Longrightarrow> homotopic_paths s (p +++ (q +++ r)) ((p +++ q) +++ r)\"\n  apply (subst homotopic_paths_sym)\n  apply (rule homotopic_paths_reparametrize\n           [where f = \"\\<lambda>t. if  t \\<le> 1 / 2 then inverse 2 *\\<^sub>R t\n                           else if  t \\<le> 3 / 4 then t - (1 / 4)\n                           else 2 *\\<^sub>R t - 1\"])\n  apply (simp_all del: le_divide_eq_numeral1)\n  apply (simp add: subset_path_image_join)\n  apply (rule continuous_on_cases_1 continuous_intros)+\n  apply (auto simp: joinpaths_def)\n  done\n\nproposition homotopic_paths_rinv:\n  assumes \"path p\" \"path_image p \\<subseteq> s\"\n    shows \"homotopic_paths s (p +++ reversepath p) (linepath (pathstart p) (pathstart p))\"\nproof -\n  have \"continuous_on ({0..1} \\<times> {0..1}) (\\<lambda>x. (subpath 0 (fst x) p +++ reversepath (subpath 0 (fst x) p)) (snd x))\"\n    using assms\n    apply (simp add: joinpaths_def subpath_def reversepath_def path_def del: le_divide_eq_numeral1)\n    apply (rule continuous_on_cases_le)\n    apply (rule_tac [2] continuous_on_compose [of _ _ p, unfolded o_def])\n    apply (rule continuous_on_compose [of _ _ p, unfolded o_def])\n    apply (auto intro!: continuous_intros simp del: eq_divide_eq_numeral1)\n    apply (force elim!: continuous_on_subset simp add: mult_le_one)+\n    done\n  then show ?thesis\n    using assms\n    apply (subst homotopic_paths_sym_eq)\n    unfolding homotopic_paths_def homotopic_with_def\n    apply (rule_tac x=\"(\\<lambda>y. (subpath 0 (fst y) p +++ reversepath(subpath 0 (fst y) p)) (snd y))\" in exI)\n    apply (simp add: path_defs joinpaths_def subpath_def reversepath_def)\n    apply (force simp: mult_le_one)\n    done\nqed\n\nproposition homotopic_paths_linv:\n  assumes \"path p\" \"path_image p \\<subseteq> s\"\n    shows \"homotopic_paths s (reversepath p +++ p) (linepath (pathfinish p) (pathfinish p))\"\nusing homotopic_paths_rinv [of \"reversepath p\" s] assms by simp\n\n\nsubsection\\<open> Homotopy of loops without requiring preservation of endpoints.\\<close>\n\ndefinition homotopic_loops :: \"'a::topological_space set \\<Rightarrow> (real \\<Rightarrow> 'a) \\<Rightarrow> (real \\<Rightarrow> 'a) \\<Rightarrow> bool\"  where\n \"homotopic_loops s p q \\<equiv>\n     homotopic_with (\\<lambda>r. pathfinish r = pathstart r) {0..1} s p q\"\n\nlemma homotopic_loops:\n   \"homotopic_loops s p q \\<longleftrightarrow>\n      (\\<exists>h. continuous_on ({0..1::real} \\<times> {0..1}) h \\<and>\n          image h ({0..1} \\<times> {0..1}) \\<subseteq> s \\<and>\n          (\\<forall>x \\<in> {0..1}. h(0,x) = p x) \\<and>\n          (\\<forall>x \\<in> {0..1}. h(1,x) = q x) \\<and>\n          (\\<forall>t \\<in> {0..1}. pathfinish(h o Pair t) = pathstart(h o Pair t)))\"\n  by (simp add: homotopic_loops_def pathstart_def pathfinish_def homotopic_with)\n\nproposition homotopic_loops_imp_loop:\n     \"homotopic_loops s p q \\<Longrightarrow> pathfinish p = pathstart p \\<and> pathfinish q = pathstart q\"\nusing homotopic_with_imp_property homotopic_loops_def by blast\n\nproposition homotopic_loops_imp_path:\n     \"homotopic_loops s p q \\<Longrightarrow> path p \\<and> path q\"\n  unfolding homotopic_loops_def path_def\n  using homotopic_with_imp_continuous by blast\n\nproposition homotopic_loops_imp_subset:\n     \"homotopic_loops s p q \\<Longrightarrow> path_image p \\<subseteq> s \\<and> path_image q \\<subseteq> s\"\n  unfolding homotopic_loops_def path_image_def\n  by (metis homotopic_with_imp_subset1 homotopic_with_imp_subset2)\n\nproposition homotopic_loops_refl:\n     \"homotopic_loops s p p \\<longleftrightarrow>\n      path p \\<and> path_image p \\<subseteq> s \\<and> pathfinish p = pathstart p\"\n  by (simp add: homotopic_loops_def homotopic_with_refl path_image_def path_def)\n\nproposition homotopic_loops_sym: \"homotopic_loops s p q \\<Longrightarrow> homotopic_loops s q p\"\n  by (simp add: homotopic_loops_def homotopic_with_sym)\n\nproposition homotopic_loops_sym_eq: \"homotopic_loops s p q \\<longleftrightarrow> homotopic_loops s q p\"\n  by (metis homotopic_loops_sym)\n\nproposition homotopic_loops_trans:\n   \"\\<lbrakk>homotopic_loops s p q; homotopic_loops s q r\\<rbrakk> \\<Longrightarrow> homotopic_loops s p r\"\n  unfolding homotopic_loops_def by (blast intro: homotopic_with_trans)\n\nproposition homotopic_loops_subset:\n   \"\\<lbrakk>homotopic_loops s p q; s \\<subseteq> t\\<rbrakk> \\<Longrightarrow> homotopic_loops t p q\"\n  by (simp add: homotopic_loops_def homotopic_with_subset_right)\n\nproposition homotopic_loops_eq:\n   \"\\<lbrakk>path p; path_image p \\<subseteq> s; pathfinish p = pathstart p; \\<And>t. t \\<in> {0..1} \\<Longrightarrow> p(t) = q(t)\\<rbrakk>\n          \\<Longrightarrow> homotopic_loops s p q\"\n  unfolding homotopic_loops_def\n  apply (rule homotopic_with_eq)\n  apply (rule homotopic_with_refl [where f = p, THEN iffD2])\n  apply (simp_all add: path_image_def path_def pathstart_def pathfinish_def)\n  done\n\nproposition homotopic_loops_continuous_image:\n   \"\\<lbrakk>homotopic_loops s f g; continuous_on s h; h ` s \\<subseteq> t\\<rbrakk> \\<Longrightarrow> homotopic_loops t (h \\<circ> f) (h \\<circ> g)\"\n  unfolding homotopic_loops_def\n  apply (rule homotopic_with_compose_continuous_left)\n  apply (erule homotopic_with_mono)\n  by (simp add: pathfinish_def pathstart_def)\n\n\nsubsection\\<open>Relations between the two variants of homotopy\\<close>\n\nproposition homotopic_paths_imp_homotopic_loops:\n    \"\\<lbrakk>homotopic_paths s p q; pathfinish p = pathstart p; pathfinish q = pathstart p\\<rbrakk> \\<Longrightarrow> homotopic_loops s p q\"\n  by (auto simp: homotopic_paths_def homotopic_loops_def intro: homotopic_with_mono)\n\nproposition homotopic_loops_imp_homotopic_paths_null:\n  assumes \"homotopic_loops s p (linepath a a)\"\n    shows \"homotopic_paths s p (linepath (pathstart p) (pathstart p))\"\nproof -\n  have \"path p\" by (metis assms homotopic_loops_imp_path)\n  have ploop: \"pathfinish p = pathstart p\" by (metis assms homotopic_loops_imp_loop)\n  have pip: \"path_image p \\<subseteq> s\" by (metis assms homotopic_loops_imp_subset)\n  obtain h where conth: \"continuous_on ({0..1::real} \\<times> {0..1}) h\"\n             and hs: \"h ` ({0..1} \\<times> {0..1}) \\<subseteq> s\"\n             and [simp]: \"\\<And>x. x \\<in> {0..1} \\<Longrightarrow> h(0,x) = p x\"\n             and [simp]: \"\\<And>x. x \\<in> {0..1} \\<Longrightarrow> h(1,x) = a\"\n             and ends: \"\\<And>t. t \\<in> {0..1} \\<Longrightarrow> pathfinish (h \\<circ> Pair t) = pathstart (h \\<circ> Pair t)\"\n    using assms by (auto simp: homotopic_loops homotopic_with)\n  have conth0: \"path (\\<lambda>u. h (u, 0))\"\n    unfolding path_def\n    apply (rule continuous_on_compose [of _ _ h, unfolded o_def])\n    apply (force intro: continuous_intros continuous_on_subset [OF conth])+\n    done\n  have pih0: \"path_image (\\<lambda>u. h (u, 0)) \\<subseteq> s\"\n    using hs by (force simp: path_image_def)\n  have c1: \"continuous_on ({0..1} \\<times> {0..1}) (\\<lambda>x. h (fst x * snd x, 0))\"\n    apply (rule continuous_on_compose [of _ _ h, unfolded o_def])\n    apply (force simp: mult_le_one intro: continuous_intros continuous_on_subset [OF conth])+\n    done\n  have c2: \"continuous_on ({0..1} \\<times> {0..1}) (\\<lambda>x. h (fst x - fst x * snd x, 0))\"\n    apply (rule continuous_on_compose [of _ _ h, unfolded o_def])\n    apply (force simp: mult_left_le mult_le_one intro: continuous_intros continuous_on_subset [OF conth])+\n    apply (rule continuous_on_subset [OF conth])\n    apply (auto simp: algebra_simps add_increasing2 mult_left_le)\n    done\n  have [simp]: \"\\<And>t. \\<lbrakk>0 \\<le> t \\<and> t \\<le> 1\\<rbrakk> \\<Longrightarrow> h (t, 1) = h (t, 0)\"\n    using ends by (simp add: pathfinish_def pathstart_def)\n  have adhoc_le: \"c * 4 \\<le> 1 + c * (d * 4)\" if \"\\<not> d * 4 \\<le> 3\" \"0 \\<le> c\" \"c \\<le> 1\" for c d::real\n  proof -\n    have \"c * 3 \\<le> c * (d * 4)\" using that less_eq_real_def by auto\n    with \\<open>c \\<le> 1\\<close> show ?thesis by fastforce\n  qed\n  have *: \"\\<And>p x. (path p \\<and> path(reversepath p)) \\<and>\n                  (path_image p \\<subseteq> s \\<and> path_image(reversepath p) \\<subseteq> s) \\<and>\n                  (pathfinish p = pathstart(linepath a a +++ reversepath p) \\<and>\n                   pathstart(reversepath p) = a) \\<and> pathstart p = x\n                  \\<Longrightarrow> homotopic_paths s (p +++ linepath a a +++ reversepath p) (linepath x x)\"\n    by (metis homotopic_paths_lid homotopic_paths_join\n              homotopic_paths_trans homotopic_paths_sym homotopic_paths_rinv)\n  have 1: \"homotopic_paths s p (p +++ linepath (pathfinish p) (pathfinish p))\"\n    using \\<open>path p\\<close> homotopic_paths_rid homotopic_paths_sym pip by blast\n  moreover have \"homotopic_paths s (p +++ linepath (pathfinish p) (pathfinish p))\n                                   (linepath (pathstart p) (pathstart p) +++ p +++ linepath (pathfinish p) (pathfinish p))\"\n    apply (rule homotopic_paths_sym)\n    using homotopic_paths_lid [of \"p +++ linepath (pathfinish p) (pathfinish p)\" s]\n    by (metis 1 homotopic_paths_imp_path homotopic_paths_imp_pathstart homotopic_paths_imp_subset)\n  moreover have \"homotopic_paths s (linepath (pathstart p) (pathstart p) +++ p +++ linepath (pathfinish p) (pathfinish p))\n                                   ((\\<lambda>u. h (u, 0)) +++ linepath a a +++ reversepath (\\<lambda>u. h (u, 0)))\"\n    apply (simp add: homotopic_paths_def homotopic_with_def)\n    apply (rule_tac x=\"\\<lambda>y. (subpath 0 (fst y) (\\<lambda>u. h (u, 0)) +++ (\\<lambda>u. h (Pair (fst y) u)) +++ subpath (fst y) 0 (\\<lambda>u. h (u, 0))) (snd y)\" in exI)\n    apply (simp add: subpath_reversepath)\n    apply (intro conjI homotopic_join_lemma)\n    using ploop\n    apply (simp_all add: path_defs joinpaths_def o_def subpath_def conth c1 c2)\n    apply (force simp: algebra_simps mult_le_one mult_left_le intro: hs [THEN subsetD] adhoc_le)\n    done\n  moreover have \"homotopic_paths s ((\\<lambda>u. h (u, 0)) +++ linepath a a +++ reversepath (\\<lambda>u. h (u, 0)))\n                                   (linepath (pathstart p) (pathstart p))\"\n    apply (rule *)\n    apply (simp add: pih0 pathstart_def pathfinish_def conth0)\n    apply (simp add: reversepath_def joinpaths_def)\n    done\n  ultimately show ?thesis\n    by (blast intro: homotopic_paths_trans)\nqed\n\nproposition homotopic_loops_conjugate:\n  fixes s :: \"'a::real_normed_vector set\"\n  assumes \"path p\" \"path q\" and pip: \"path_image p \\<subseteq> s\" and piq: \"path_image q \\<subseteq> s\"\n      and papp: \"pathfinish p = pathstart q\" and qloop: \"pathfinish q = pathstart q\"\n    shows \"homotopic_loops s (p +++ q +++ reversepath p) q\"\nproof -\n  have contp: \"continuous_on {0..1} p\"  using \\<open>path p\\<close> [unfolded path_def] by blast\n  have contq: \"continuous_on {0..1} q\"  using \\<open>path q\\<close> [unfolded path_def] by blast\n  have c1: \"continuous_on ({0..1} \\<times> {0..1}) (\\<lambda>x. p ((1 - fst x) * snd x + fst x))\"\n    apply (rule continuous_on_compose [of _ _ p, unfolded o_def])\n    apply (force simp: mult_le_one intro!: continuous_intros)\n    apply (rule continuous_on_subset [OF contp])\n    apply (auto simp: algebra_simps add_increasing2 mult_right_le_one_le sum_le_prod1)\n    done\n  have c2: \"continuous_on ({0..1} \\<times> {0..1}) (\\<lambda>x. p ((fst x - 1) * snd x + 1))\"\n    apply (rule continuous_on_compose [of _ _ p, unfolded o_def])\n    apply (force simp: mult_le_one intro!: continuous_intros)\n    apply (rule continuous_on_subset [OF contp])\n    apply (auto simp: algebra_simps add_increasing2 mult_left_le_one_le)\n    done\n  have ps1: \"\\<And>a b. \\<lbrakk>b * 2 \\<le> 1; 0 \\<le> b; 0 \\<le> a; a \\<le> 1\\<rbrakk> \\<Longrightarrow> p ((1 - a) * (2 * b) + a) \\<in> s\"\n    using sum_le_prod1\n    by (force simp: algebra_simps add_increasing2 mult_left_le intro: pip [unfolded path_image_def, THEN subsetD])\n  have ps2: \"\\<And>a b. \\<lbrakk>\\<not> 4 * b \\<le> 3; b \\<le> 1; 0 \\<le> a; a \\<le> 1\\<rbrakk> \\<Longrightarrow> p ((a - 1) * (4 * b - 3) + 1) \\<in> s\"\n    apply (rule pip [unfolded path_image_def, THEN subsetD])\n    apply (rule image_eqI, blast)\n    apply (simp add: algebra_simps)\n    by (metis add_mono_thms_linordered_semiring(1) affine_ineq linear mult.commute mult.left_neutral mult_right_mono not_le\n              add.commute zero_le_numeral)\n  have qs: \"\\<And>a b. \\<lbrakk>4 * b \\<le> 3; \\<not> b * 2 \\<le> 1\\<rbrakk> \\<Longrightarrow> q (4 * b - 2) \\<in> s\"\n    using path_image_def piq by fastforce\n  have \"homotopic_loops s (p +++ q +++ reversepath p)\n                          (linepath (pathstart q) (pathstart q) +++ q +++ linepath (pathstart q) (pathstart q))\"\n    apply (simp add: homotopic_loops_def homotopic_with_def)\n    apply (rule_tac x=\"(\\<lambda>y. (subpath (fst y) 1 p +++ q +++ subpath 1 (fst y) p) (snd y))\" in exI)\n    apply (simp add: subpath_refl subpath_reversepath)\n    apply (intro conjI homotopic_join_lemma)\n    using papp qloop\n    apply (simp_all add: path_defs joinpaths_def o_def subpath_def c1 c2)\n    apply (force simp: contq intro: continuous_on_compose [of _ _ q, unfolded o_def] continuous_on_id continuous_on_snd)\n    apply (auto simp: ps1 ps2 qs)\n    done\n  moreover have \"homotopic_loops s (linepath (pathstart q) (pathstart q) +++ q +++ linepath (pathstart q) (pathstart q)) q\"\n  proof -\n    have \"homotopic_paths s (linepath (pathfinish q) (pathfinish q) +++ q) q\"\n      using \\<open>path q\\<close> homotopic_paths_lid qloop piq by auto\n    hence 1: \"\\<And>f. homotopic_paths s f q \\<or> \\<not> homotopic_paths s f (linepath (pathfinish q) (pathfinish q) +++ q)\"\n      using homotopic_paths_trans by blast\n    hence \"homotopic_paths s (linepath (pathfinish q) (pathfinish q) +++ q +++ linepath (pathfinish q) (pathfinish q)) q\"\n    proof -\n      have \"homotopic_paths s (q +++ linepath (pathfinish q) (pathfinish q)) q\"\n        by (simp add: \\<open>path q\\<close> homotopic_paths_rid piq)\n      thus ?thesis\n        by (metis (no_types) 1 \\<open>path q\\<close> homotopic_paths_join homotopic_paths_rinv homotopic_paths_sym\n                  homotopic_paths_trans qloop pathfinish_linepath piq)\n    qed\n    thus ?thesis\n      by (metis (no_types) qloop homotopic_loops_sym homotopic_paths_imp_homotopic_loops homotopic_paths_imp_pathfinish homotopic_paths_sym)\n  qed\n  ultimately show ?thesis\n    by (blast intro: homotopic_loops_trans)\nqed\n\n\nsubsection\\<open> Homotopy of \"nearby\" function, paths and loops.\\<close>\n\nlemma homotopic_with_linear:\n  fixes f g :: \"_ \\<Rightarrow> 'b::real_normed_vector\"\n  assumes contf: \"continuous_on s f\"\n      and contg:\"continuous_on s g\"\n      and sub: \"\\<And>x. x \\<in> s \\<Longrightarrow> closed_segment (f x) (g x) \\<subseteq> t\"\n    shows \"homotopic_with (\\<lambda>z. True) s t f g\"\n  apply (simp add: homotopic_with_def)\n  apply (rule_tac x=\"\\<lambda>y. ((1 - (fst y)) *\\<^sub>R f(snd y) + (fst y) *\\<^sub>R g(snd y))\" in exI)\n  apply (intro conjI)\n  apply (rule subset_refl continuous_intros continuous_on_subset [OF contf] continuous_on_compose2 [where g=f]\n                                            continuous_on_subset [OF contg] continuous_on_compose2 [where g=g]| simp)+\n  using sub closed_segment_def apply fastforce+\n  done\n\nlemma homotopic_paths_linear:\n  fixes g h :: \"real \\<Rightarrow> 'a::real_normed_vector\"\n  assumes \"path g\" \"path h\" \"pathstart h = pathstart g\" \"pathfinish h = pathfinish g\"\n          \"\\<And>t. t \\<in> {0..1} \\<Longrightarrow> closed_segment (g t) (h t) \\<subseteq> s\"\n    shows \"homotopic_paths s g h\"\n  using assms\n  unfolding path_def\n  apply (simp add: closed_segment_def pathstart_def pathfinish_def homotopic_paths_def homotopic_with_def)\n  apply (rule_tac x=\"\\<lambda>y. ((1 - (fst y)) *\\<^sub>R (g o snd) y + (fst y) *\\<^sub>R (h o snd) y)\" in exI)\n  apply (intro conjI subsetI continuous_intros; force)\n  done\n\nlemma homotopic_loops_linear:\n  fixes g h :: \"real \\<Rightarrow> 'a::real_normed_vector\"\n  assumes \"path g\" \"path h\" \"pathfinish g = pathstart g\" \"pathfinish h = pathstart h\"\n          \"\\<And>t x. t \\<in> {0..1} \\<Longrightarrow> closed_segment (g t) (h t) \\<subseteq> s\"\n    shows \"homotopic_loops s g h\"\n  using assms\n  unfolding path_def\n  apply (simp add: pathstart_def pathfinish_def homotopic_loops_def homotopic_with_def)\n  apply (rule_tac x=\"\\<lambda>y. ((1 - (fst y)) *\\<^sub>R g(snd y) + (fst y) *\\<^sub>R h(snd y))\" in exI)\n  apply (auto intro!: continuous_intros intro: continuous_on_compose2 [where g=g] continuous_on_compose2 [where g=h])\n  apply (force simp: closed_segment_def)\n  done\n\nlemma homotopic_paths_nearby_explicit:\n  assumes \"path g\" \"path h\" \"pathstart h = pathstart g\" \"pathfinish h = pathfinish g\"\n      and no: \"\\<And>t x. \\<lbrakk>t \\<in> {0..1}; x \\<notin> s\\<rbrakk> \\<Longrightarrow> norm(h t - g t) < norm(g t - x)\"\n    shows \"homotopic_paths s g h\"\n  apply (rule homotopic_paths_linear [OF assms(1-4)])\n  by (metis no segment_bound(1) subsetI norm_minus_commute not_le)\n\nlemma homotopic_loops_nearby_explicit:\n  assumes \"path g\" \"path h\" \"pathfinish g = pathstart g\" \"pathfinish h = pathstart h\"\n      and no: \"\\<And>t x. \\<lbrakk>t \\<in> {0..1}; x \\<notin> s\\<rbrakk> \\<Longrightarrow> norm(h t - g t) < norm(g t - x)\"\n    shows \"homotopic_loops s g h\"\n  apply (rule homotopic_loops_linear [OF assms(1-4)])\n  by (metis no segment_bound(1) subsetI norm_minus_commute not_le)\n\nlemma homotopic_nearby_paths:\n  fixes g h :: \"real \\<Rightarrow> 'a::euclidean_space\"\n  assumes \"path g\" \"open s\" \"path_image g \\<subseteq> s\"\n    shows \"\\<exists>e. 0 < e \\<and>\n               (\\<forall>h. path h \\<and>\n                    pathstart h = pathstart g \\<and> pathfinish h = pathfinish g \\<and>\n                    (\\<forall>t \\<in> {0..1}. norm(h t - g t) < e) \\<longrightarrow> homotopic_paths s g h)\"\nproof -\n  obtain e where \"e > 0\" and e: \"\\<And>x y. x \\<in> path_image g \\<Longrightarrow> y \\<in> - s \\<Longrightarrow> e \\<le> dist x y\"\n    using separate_compact_closed [of \"path_image g\" \"-s\"] assms by force\n  show ?thesis\n    apply (intro exI conjI)\n    using e [unfolded dist_norm]\n    apply (auto simp: intro!: homotopic_paths_nearby_explicit assms  \\<open>e > 0\\<close>)\n    by (metis atLeastAtMost_iff imageI le_less_trans not_le path_image_def)\nqed\n\nlemma homotopic_nearby_loops:\n  fixes g h :: \"real \\<Rightarrow> 'a::euclidean_space\"\n  assumes \"path g\" \"open s\" \"path_image g \\<subseteq> s\" \"pathfinish g = pathstart g\"\n    shows \"\\<exists>e. 0 < e \\<and>\n               (\\<forall>h. path h \\<and> pathfinish h = pathstart h \\<and>\n                    (\\<forall>t \\<in> {0..1}. norm(h t - g t) < e) \\<longrightarrow> homotopic_loops s g h)\"\nproof -\n  obtain e where \"e > 0\" and e: \"\\<And>x y. x \\<in> path_image g \\<Longrightarrow> y \\<in> - s \\<Longrightarrow> e \\<le> dist x y\"\n    using separate_compact_closed [of \"path_image g\" \"-s\"] assms by force\n  show ?thesis\n    apply (intro exI conjI)\n    using e [unfolded dist_norm]\n    apply (auto simp: intro!: homotopic_loops_nearby_explicit assms  \\<open>e > 0\\<close>)\n    by (metis atLeastAtMost_iff imageI le_less_trans not_le path_image_def)\nqed\n\nsubsection\\<open> Homotopy and subpaths\\<close>\n\nlemma homotopic_join_subpaths1:\n  assumes \"path g\" and pag: \"path_image g \\<subseteq> s\"\n      and u: \"u \\<in> {0..1}\" and v: \"v \\<in> {0..1}\" and w: \"w \\<in> {0..1}\" \"u \\<le> v\" \"v \\<le> w\"\n    shows \"homotopic_paths s (subpath u v g +++ subpath v w g) (subpath u w g)\"\nproof -\n  have 1: \"t * 2 \\<le> 1 \\<Longrightarrow> u + t * (v * 2) \\<le> v + t * (u * 2)\" for t\n    using affine_ineq \\<open>u \\<le> v\\<close> by fastforce\n  have 2: \"t * 2 > 1 \\<Longrightarrow> u + (2*t - 1) * v \\<le> v + (2*t - 1) * w\" for t\n    by (metis add_mono_thms_linordered_semiring(1) diff_gt_0_iff_gt less_eq_real_def mult.commute mult_right_mono \\<open>u \\<le> v\\<close> \\<open>v \\<le> w\\<close>)\n  have t2: \"\\<And>t::real. t*2 = 1 \\<Longrightarrow> t = 1/2\" by auto\n  show ?thesis\n    apply (rule homotopic_paths_subset [OF _ pag])\n    using assms\n    apply (cases \"w = u\")\n    using homotopic_paths_rinv [of \"subpath u v g\" \"path_image g\"]\n    apply (force simp: closed_segment_eq_real_ivl image_mono path_image_def subpath_refl)\n      apply (rule homotopic_paths_sym)\n      apply (rule homotopic_paths_reparametrize\n             [where f = \"\\<lambda>t. if  t \\<le> 1 / 2\n                             then inverse((w - u)) *\\<^sub>R (2 * (v - u)) *\\<^sub>R t\n                             else inverse((w - u)) *\\<^sub>R ((v - u) + (w - v) *\\<^sub>R (2 *\\<^sub>R t - 1))\"])\n      using \\<open>path g\\<close> path_subpath u w apply blast\n      using \\<open>path g\\<close> path_image_subpath_subset u w(1) apply blast\n      apply simp_all\n      apply (subst split_01)\n      apply (rule continuous_on_cases continuous_intros | force simp: pathfinish_def joinpaths_def)+\n      apply (simp_all add: field_simps not_le)\n      apply (force dest!: t2)\n      apply (force simp: algebra_simps mult_left_mono affine_ineq dest!: 1 2)\n      apply (simp add: joinpaths_def subpath_def)\n      apply (force simp: algebra_simps)\n      done\nqed\n\nlemma homotopic_join_subpaths2:\n  assumes \"homotopic_paths s (subpath u v g +++ subpath v w g) (subpath u w g)\"\n    shows \"homotopic_paths s (subpath w v g +++ subpath v u g) (subpath w u g)\"\nby (metis assms homotopic_paths_reversepath_D pathfinish_subpath pathstart_subpath reversepath_joinpaths reversepath_subpath)\n\nlemma homotopic_join_subpaths3:\n  assumes hom: \"homotopic_paths s (subpath u v g +++ subpath v w g) (subpath u w g)\"\n      and \"path g\" and pag: \"path_image g \\<subseteq> s\"\n      and u: \"u \\<in> {0..1}\" and v: \"v \\<in> {0..1}\" and w: \"w \\<in> {0..1}\"\n    shows \"homotopic_paths s (subpath v w g +++ subpath w u g) (subpath v u g)\"\nproof -\n  have \"homotopic_paths s (subpath u w g +++ subpath w v g) ((subpath u v g +++ subpath v w g) +++ subpath w v g)\"\n    apply (rule homotopic_paths_join)\n    using hom homotopic_paths_sym_eq apply blast\n    apply (metis \\<open>path g\\<close> homotopic_paths_eq pag path_image_subpath_subset path_subpath subset_trans v w)\n    apply (simp add:)\n    done\n  also have \"homotopic_paths s ((subpath u v g +++ subpath v w g) +++ subpath w v g) (subpath u v g +++ subpath v w g +++ subpath w v g)\"\n    apply (rule homotopic_paths_sym [OF homotopic_paths_assoc])\n    using assms by (simp_all add: path_image_subpath_subset [THEN order_trans])\n  also have \"homotopic_paths s (subpath u v g +++ subpath v w g +++ subpath w v g)\n                               (subpath u v g +++ linepath (pathfinish (subpath u v g)) (pathfinish (subpath u v g)))\"\n    apply (rule homotopic_paths_join)\n    apply (metis \\<open>path g\\<close> homotopic_paths_eq order.trans pag path_image_subpath_subset path_subpath u v)\n    apply (metis (no_types, lifting) \\<open>path g\\<close> homotopic_paths_linv order_trans pag path_image_subpath_subset path_subpath pathfinish_subpath reversepath_subpath v w)\n    apply (simp add:)\n    done\n  also have \"homotopic_paths s (subpath u v g +++ linepath (pathfinish (subpath u v g)) (pathfinish (subpath u v g))) (subpath u v g)\"\n    apply (rule homotopic_paths_rid)\n    using \\<open>path g\\<close> path_subpath u v apply blast\n    apply (meson \\<open>path g\\<close> order.trans pag path_image_subpath_subset u v)\n    done\n  finally have \"homotopic_paths s (subpath u w g +++ subpath w v g) (subpath u v g)\" .\n  then show ?thesis\n    using homotopic_join_subpaths2 by blast\nqed\n\nproposition homotopic_join_subpaths:\n   \"\\<lbrakk>path g; path_image g \\<subseteq> s; u \\<in> {0..1}; v \\<in> {0..1}; w \\<in> {0..1}\\<rbrakk>\n    \\<Longrightarrow> homotopic_paths s (subpath u v g +++ subpath v w g) (subpath u w g)\"\napply (rule le_cases3 [of u v w])\nusing homotopic_join_subpaths1 homotopic_join_subpaths2 homotopic_join_subpaths3 by metis+\n\ntext\\<open>Relating homotopy of trivial loops to path-connectedness.\\<close>\n\nlemma path_component_imp_homotopic_points:\n    \"path_component S a b \\<Longrightarrow> homotopic_loops S (linepath a a) (linepath b b)\"\napply (simp add: path_component_def homotopic_loops_def homotopic_with_def\n                 pathstart_def pathfinish_def path_image_def path_def, clarify)\napply (rule_tac x=\"g o fst\" in exI)\napply (intro conjI continuous_intros continuous_on_compose)+\napply (auto elim!: continuous_on_subset)\ndone\n\nlemma homotopic_loops_imp_path_component_value:\n   \"\\<lbrakk>homotopic_loops S p q; 0 \\<le> t; t \\<le> 1\\<rbrakk>\n        \\<Longrightarrow> path_component S (p t) (q t)\"\napply (simp add: path_component_def homotopic_loops_def homotopic_with_def\n                 pathstart_def pathfinish_def path_image_def path_def, clarify)\napply (rule_tac x=\"h o (\\<lambda>u. (u, t))\" in exI)\napply (intro conjI continuous_intros continuous_on_compose)+\napply (auto elim!: continuous_on_subset)\ndone\n\nlemma homotopic_points_eq_path_component:\n   \"homotopic_loops S (linepath a a) (linepath b b) \\<longleftrightarrow>\n        path_component S a b\"\nby (auto simp: path_component_imp_homotopic_points\n         dest: homotopic_loops_imp_path_component_value [where t=1])\n\nlemma path_connected_eq_homotopic_points:\n    \"path_connected S \\<longleftrightarrow>\n      (\\<forall>a b. a \\<in> S \\<and> b \\<in> S \\<longrightarrow> homotopic_loops S (linepath a a) (linepath b b))\"\nby (auto simp: path_connected_def path_component_def homotopic_points_eq_path_component)\n\n\nsubsection\\<open>Simply connected sets\\<close>\n\ntext\\<open>defined as \"all loops are homotopic (as loops)\\<close>\n\ndefinition simply_connected where\n  \"simply_connected S \\<equiv>\n        \\<forall>p q. path p \\<and> pathfinish p = pathstart p \\<and> path_image p \\<subseteq> S \\<and>\n              path q \\<and> pathfinish q = pathstart q \\<and> path_image q \\<subseteq> S\n              \\<longrightarrow> homotopic_loops S p q\"\n\nlemma simply_connected_empty [iff]: \"simply_connected {}\"\n  by (simp add: simply_connected_def)\n\nlemma simply_connected_imp_path_connected:\n  fixes S :: \"_::real_normed_vector set\"\n  shows \"simply_connected S \\<Longrightarrow> path_connected S\"\nby (simp add: simply_connected_def path_connected_eq_homotopic_points)\n\nlemma simply_connected_imp_connected:\n  fixes S :: \"_::real_normed_vector set\"\n  shows \"simply_connected S \\<Longrightarrow> connected S\"\nby (simp add: path_connected_imp_connected simply_connected_imp_path_connected)\n\nlemma simply_connected_eq_contractible_loop_any:\n  fixes S :: \"_::real_normed_vector set\"\n  shows \"simply_connected S \\<longleftrightarrow>\n            (\\<forall>p a. path p \\<and> path_image p \\<subseteq> S \\<and>\n                  pathfinish p = pathstart p \\<and> a \\<in> S\n                  \\<longrightarrow> homotopic_loops S p (linepath a a))\"\napply (simp add: simply_connected_def)\napply (rule iffI, force, clarify)\napply (rule_tac q = \"linepath (pathstart p) (pathstart p)\" in homotopic_loops_trans)\napply (fastforce simp add:)\nusing homotopic_loops_sym apply blast\ndone\n\nlemma simply_connected_eq_contractible_loop_some:\n  fixes S :: \"_::real_normed_vector set\"\n  shows \"simply_connected S \\<longleftrightarrow>\n                path_connected S \\<and>\n                (\\<forall>p. path p \\<and> path_image p \\<subseteq> S \\<and> pathfinish p = pathstart p\n                    \\<longrightarrow> (\\<exists>a. a \\<in> S \\<and> homotopic_loops S p (linepath a a)))\"\napply (rule iffI)\n apply (fastforce simp: simply_connected_imp_path_connected simply_connected_eq_contractible_loop_any)\napply (clarsimp simp add: simply_connected_eq_contractible_loop_any)\napply (drule_tac x=p in spec)\nusing homotopic_loops_trans path_connected_eq_homotopic_points\n  apply blast\ndone\n\nlemma simply_connected_eq_contractible_loop_all:\n  fixes S :: \"_::real_normed_vector set\"\n  shows \"simply_connected S \\<longleftrightarrow>\n         S = {} \\<or>\n         (\\<exists>a \\<in> S. \\<forall>p. path p \\<and> path_image p \\<subseteq> S \\<and> pathfinish p = pathstart p\n                \\<longrightarrow> homotopic_loops S p (linepath a a))\"\n        (is \"?lhs = ?rhs\")\nproof (cases \"S = {}\")\n  case True then show ?thesis by force\nnext\n  case False\n  then obtain a where \"a \\<in> S\" by blast\n  show ?thesis\n  proof\n    assume \"simply_connected S\"\n    then show ?rhs\n      using \\<open>a \\<in> S\\<close> \\<open>simply_connected S\\<close> simply_connected_eq_contractible_loop_any\n      by blast\n  next\n    assume ?rhs\n    then show \"simply_connected S\"\n      apply (simp add: simply_connected_eq_contractible_loop_any False)\n      by (meson homotopic_loops_refl homotopic_loops_sym homotopic_loops_trans\n             path_component_imp_homotopic_points path_component_refl)\n  qed\nqed\n\nlemma simply_connected_eq_contractible_path:\n  fixes S :: \"_::real_normed_vector set\"\n  shows \"simply_connected S \\<longleftrightarrow>\n           path_connected S \\<and>\n           (\\<forall>p. path p \\<and> path_image p \\<subseteq> S \\<and> pathfinish p = pathstart p\n            \\<longrightarrow> homotopic_paths S p (linepath (pathstart p) (pathstart p)))\"\napply (rule iffI)\n apply (simp add: simply_connected_imp_path_connected)\n apply (metis simply_connected_eq_contractible_loop_some homotopic_loops_imp_homotopic_paths_null)\nby (meson homotopic_paths_imp_homotopic_loops pathfinish_linepath pathstart_in_path_image\n         simply_connected_eq_contractible_loop_some subset_iff)\n\nlemma simply_connected_eq_homotopic_paths:\n  fixes S :: \"_::real_normed_vector set\"\n  shows \"simply_connected S \\<longleftrightarrow>\n          path_connected S \\<and>\n          (\\<forall>p q. path p \\<and> path_image p \\<subseteq> S \\<and>\n                path q \\<and> path_image q \\<subseteq> S \\<and>\n                pathstart q = pathstart p \\<and> pathfinish q = pathfinish p\n                \\<longrightarrow> homotopic_paths S p q)\"\n         (is \"?lhs = ?rhs\")\nproof\n  assume ?lhs\n  then have pc: \"path_connected S\"\n        and *:  \"\\<And>p. \\<lbrakk>path p; path_image p \\<subseteq> S;\n                       pathfinish p = pathstart p\\<rbrakk>\n                      \\<Longrightarrow> homotopic_paths S p (linepath (pathstart p) (pathstart p))\"\n    by (auto simp: simply_connected_eq_contractible_path)\n  have \"homotopic_paths S p q\"\n        if \"path p\" \"path_image p \\<subseteq> S\" \"path q\"\n           \"path_image q \\<subseteq> S\" \"pathstart q = pathstart p\"\n           \"pathfinish q = pathfinish p\" for p q\n  proof -\n    have \"homotopic_paths S p (p +++ linepath (pathfinish p) (pathfinish p))\"\n      by (simp add: homotopic_paths_rid homotopic_paths_sym that)\n    also have \"homotopic_paths S (p +++ linepath (pathfinish p) (pathfinish p))\n                                 (p +++ reversepath q +++ q)\"\n      using that\n      by (metis homotopic_paths_join homotopic_paths_linv homotopic_paths_refl homotopic_paths_sym_eq pathstart_linepath)\n    also have \"homotopic_paths S (p +++ reversepath q +++ q)\n                                 ((p +++ reversepath q) +++ q)\"\n      by (simp add: that homotopic_paths_assoc)\n    also have \"homotopic_paths S ((p +++ reversepath q) +++ q)\n                                 (linepath (pathstart q) (pathstart q) +++ q)\"\n      using * [of \"p +++ reversepath q\"] that\n      by (simp add: homotopic_paths_join path_image_join)\n    also have \"homotopic_paths S (linepath (pathstart q) (pathstart q) +++ q) q\"\n      using that homotopic_paths_lid by blast\n    finally show ?thesis .\n  qed\n  then show ?rhs\n    by (blast intro: pc *)\nnext\n  assume ?rhs\n  then show ?lhs\n    by (force simp: simply_connected_eq_contractible_path)\nqed\n\nproposition simply_connected_Times:\n  fixes S :: \"'a::real_normed_vector set\" and T :: \"'b::real_normed_vector set\"\n  assumes S: \"simply_connected S\" and T: \"simply_connected T\"\n    shows \"simply_connected(S \\<times> T)\"\nproof -\n  have \"homotopic_loops (S \\<times> T) p (linepath (a, b) (a, b))\"\n       if \"path p\" \"path_image p \\<subseteq> S \\<times> T\" \"p 1 = p 0\" \"a \\<in> S\" \"b \\<in> T\"\n       for p a b\n  proof -\n    have \"path (fst \\<circ> p)\"\n      apply (rule Path_Connected.path_continuous_image [OF \\<open>path p\\<close>])\n      apply (rule continuous_intros)+\n      done\n    moreover have \"path_image (fst \\<circ> p) \\<subseteq> S\"\n      using that apply (simp add: path_image_def) by force\n    ultimately have p1: \"homotopic_loops S (fst o p) (linepath a a)\"\n      using S that\n      apply (simp add: simply_connected_eq_contractible_loop_any)\n      apply (drule_tac x=\"fst o p\" in spec)\n      apply (drule_tac x=a in spec)\n      apply (auto simp: pathstart_def pathfinish_def)\n      done\n    have \"path (snd \\<circ> p)\"\n      apply (rule Path_Connected.path_continuous_image [OF \\<open>path p\\<close>])\n      apply (rule continuous_intros)+\n      done\n    moreover have \"path_image (snd \\<circ> p) \\<subseteq> T\"\n      using that apply (simp add: path_image_def) by force\n    ultimately have p2: \"homotopic_loops T (snd o p) (linepath b b)\"\n      using T that\n      apply (simp add: simply_connected_eq_contractible_loop_any)\n      apply (drule_tac x=\"snd o p\" in spec)\n      apply (drule_tac x=b in spec)\n      apply (auto simp: pathstart_def pathfinish_def)\n      done\n    show ?thesis\n      using p1 p2\n      apply (simp add: homotopic_loops, clarify)\n      apply (rename_tac h k)\n      apply (rule_tac x=\"\\<lambda>z. Pair (h z) (k z)\" in exI)\n      apply (intro conjI continuous_intros | assumption)+\n      apply (auto simp: pathstart_def pathfinish_def)\n      done\n  qed\n  with assms show ?thesis\n    by (simp add: simply_connected_eq_contractible_loop_any pathfinish_def pathstart_def)\nqed\n\n\nsubsection\\<open>Contractible sets\\<close>\n\ndefinition contractible where\n \"contractible S \\<equiv> \\<exists>a. homotopic_with (\\<lambda>x. True) S S id (\\<lambda>x. a)\"\n\nproposition contractible_imp_simply_connected:\n  fixes S :: \"_::real_normed_vector set\"\n  assumes \"contractible S\" shows \"simply_connected S\"\nproof (cases \"S = {}\")\n  case True then show ?thesis by force\nnext\n  case False\n  obtain a where a: \"homotopic_with (\\<lambda>x. True) S S id (\\<lambda>x. a)\"\n    using assms by (force simp add: contractible_def)\n  then have \"a \\<in> S\"\n    by (metis False homotopic_constant_maps homotopic_with_symD homotopic_with_trans path_component_mem(2))\n  show ?thesis\n    apply (simp add: simply_connected_eq_contractible_loop_all False)\n    apply (rule bexI [OF _ \\<open>a \\<in> S\\<close>])\n    using a apply (simp add: homotopic_loops_def homotopic_with_def path_def path_image_def pathfinish_def pathstart_def)\n    apply clarify\n    apply (rule_tac x=\"(h o (\\<lambda>y. (fst y, (p \\<circ> snd) y)))\" in exI)\n    apply (intro conjI continuous_on_compose continuous_intros)\n    apply (erule continuous_on_subset | force)+\n    done\nqed\n\ncorollary contractible_imp_connected:\n  fixes S :: \"_::real_normed_vector set\"\n  shows \"contractible S \\<Longrightarrow> connected S\"\nby (simp add: contractible_imp_simply_connected simply_connected_imp_connected)\n\nlemma contractible_imp_path_connected:\n  fixes S :: \"_::real_normed_vector set\"\n  shows \"contractible S \\<Longrightarrow> path_connected S\"\nby (simp add: contractible_imp_simply_connected simply_connected_imp_path_connected)\n\nlemma nullhomotopic_through_contractible:\n  fixes S :: \"_::topological_space set\"\n  assumes f: \"continuous_on S f\" \"f ` S \\<subseteq> T\"\n      and g: \"continuous_on T g\" \"g ` T \\<subseteq> U\"\n      and T: \"contractible T\"\n    obtains c where \"homotopic_with (\\<lambda>h. True) S U (g o f) (\\<lambda>x. c)\"\nproof -\n  obtain b where b: \"homotopic_with (\\<lambda>x. True) T T id (\\<lambda>x. b)\"\n    using assms by (force simp add: contractible_def)\n  have \"homotopic_with (\\<lambda>f. True) T U (g \\<circ> id) (g \\<circ> (\\<lambda>x. b))\"\n    by (rule homotopic_compose_continuous_left [OF b g])\n  then have \"homotopic_with (\\<lambda>f. True) S U (g \\<circ> id \\<circ> f) (g \\<circ> (\\<lambda>x. b) \\<circ> f)\"\n    by (rule homotopic_compose_continuous_right [OF _ f])\n  then show ?thesis\n    by (simp add: comp_def that)\nqed\n\nlemma nullhomotopic_into_contractible:\n  assumes f: \"continuous_on S f\" \"f ` S \\<subseteq> T\"\n      and T: \"contractible T\"\n    obtains c where \"homotopic_with (\\<lambda>h. True) S T f (\\<lambda>x. c)\"\napply (rule nullhomotopic_through_contractible [OF f, of id T])\nusing assms\napply (auto simp: continuous_on_id)\ndone\n\nlemma nullhomotopic_from_contractible:\n  assumes f: \"continuous_on S f\" \"f ` S \\<subseteq> T\"\n      and S: \"contractible S\"\n    obtains c where \"homotopic_with (\\<lambda>h. True) S T f (\\<lambda>x. c)\"\napply (rule nullhomotopic_through_contractible [OF continuous_on_id _ f S, of S])\nusing assms\napply (auto simp: comp_def)\ndone\n\nlemma homotopic_through_contractible:\n  fixes S :: \"_::real_normed_vector set\"\n  assumes \"continuous_on S f1\" \"f1 ` S \\<subseteq> T\"\n          \"continuous_on T g1\" \"g1 ` T \\<subseteq> U\"\n          \"continuous_on S f2\" \"f2 ` S \\<subseteq> T\"\n          \"continuous_on T g2\" \"g2 ` T \\<subseteq> U\"\n          \"contractible T\" \"path_connected U\"\n   shows \"homotopic_with (\\<lambda>h. True) S U (g1 o f1) (g2 o f2)\"\nproof -\n  obtain c1 where c1: \"homotopic_with (\\<lambda>h. True) S U (g1 o f1) (\\<lambda>x. c1)\"\n    apply (rule nullhomotopic_through_contractible [of S f1 T g1 U])\n    using assms apply (auto simp: )\n    done\n  obtain c2 where c2: \"homotopic_with (\\<lambda>h. True) S U (g2 o f2) (\\<lambda>x. c2)\"\n    apply (rule nullhomotopic_through_contractible [of S f2 T g2 U])\n    using assms apply (auto simp: )\n    done\n  have *: \"S = {} \\<or> (\\<exists>t. path_connected t \\<and> t \\<subseteq> U \\<and> c2 \\<in> t \\<and> c1 \\<in> t)\"\n  proof (cases \"S = {}\")\n    case True then show ?thesis by force\n  next\n    case False\n    with c1 c2 have \"c1 \\<in> U\" \"c2 \\<in> U\"\n      using homotopic_with_imp_subset2 all_not_in_conv image_subset_iff by blast+\n    with \\<open>path_connected U\\<close> show ?thesis by blast\n  qed\n  show ?thesis\n    apply (rule homotopic_with_trans [OF c1])\n    apply (rule homotopic_with_symD)\n    apply (rule homotopic_with_trans [OF c2])\n    apply (simp add: path_component homotopic_constant_maps *)\n    done\nqed\n\nlemma homotopic_into_contractible:\n  fixes S :: \"'a::real_normed_vector set\" and T:: \"'b::real_normed_vector set\"\n  assumes f: \"continuous_on S f\" \"f ` S \\<subseteq> T\"\n      and g: \"continuous_on S g\" \"g ` S \\<subseteq> T\"\n      and T: \"contractible T\"\n    shows \"homotopic_with (\\<lambda>h. True) S T f g\"\nusing homotopic_through_contractible [of S f T id T g id]\nby (simp add: assms contractible_imp_path_connected continuous_on_id)\n\nlemma homotopic_from_contractible:\n  fixes S :: \"'a::real_normed_vector set\" and T:: \"'b::real_normed_vector set\"\n  assumes f: \"continuous_on S f\" \"f ` S \\<subseteq> T\"\n      and g: \"continuous_on S g\" \"g ` S \\<subseteq> T\"\n      and \"contractible S\" \"path_connected T\"\n    shows \"homotopic_with (\\<lambda>h. True) S T f g\"\nusing homotopic_through_contractible [of S id S f T id g]\nby (simp add: assms contractible_imp_path_connected continuous_on_id)\n\nlemma starlike_imp_contractible_gen:\n  fixes S :: \"'a::real_normed_vector set\"\n  assumes S: \"starlike S\"\n      and P: \"\\<And>a T. \\<lbrakk>a \\<in> S; 0 \\<le> T; T \\<le> 1\\<rbrakk> \\<Longrightarrow> P(\\<lambda>x. (1 - T) *\\<^sub>R x + T *\\<^sub>R a)\"\n    obtains a where \"homotopic_with P S S (\\<lambda>x. x) (\\<lambda>x. a)\"\nproof -\n  obtain a where \"a \\<in> S\" and a: \"\\<And>x. x \\<in> S \\<Longrightarrow> closed_segment a x \\<subseteq> S\"\n    using S by (auto simp add: starlike_def)\n  have \"(\\<lambda>y. (1 - fst y) *\\<^sub>R snd y + fst y *\\<^sub>R a) ` ({0..1} \\<times> S) \\<subseteq> S\"\n    apply clarify\n    apply (erule a [unfolded closed_segment_def, THEN subsetD])\n    apply (simp add: )\n    apply (metis add_diff_cancel_right' diff_ge_0_iff_ge le_add_diff_inverse pth_c(1))\n    done\n  then show ?thesis\n    apply (rule_tac a=\"a\" in that)\n    using \\<open>a \\<in> S\\<close>\n    apply (simp add: homotopic_with_def)\n    apply (rule_tac x=\"\\<lambda>y. (1 - (fst y)) *\\<^sub>R snd y + (fst y) *\\<^sub>R a\" in exI)\n    apply (intro conjI ballI continuous_on_compose continuous_intros)\n    apply (simp_all add: P)\n    done\nqed\n\nlemma starlike_imp_contractible:\n  fixes S :: \"'a::real_normed_vector set\"\n  shows \"starlike S \\<Longrightarrow> contractible S\"\nusing starlike_imp_contractible_gen contractible_def by (fastforce simp: id_def)\n\nlemma contractible_UNIV: \"contractible (UNIV :: 'a::real_normed_vector set)\"\n  by (simp add: starlike_imp_contractible)\n\nlemma starlike_imp_simply_connected:\n  fixes S :: \"'a::real_normed_vector set\"\n  shows \"starlike S \\<Longrightarrow> simply_connected S\"\nby (simp add: contractible_imp_simply_connected starlike_imp_contractible)\n\nlemma convex_imp_simply_connected:\n  fixes S :: \"'a::real_normed_vector set\"\n  shows \"convex S \\<Longrightarrow> simply_connected S\"\nusing convex_imp_starlike starlike_imp_simply_connected by blast\n\nlemma starlike_imp_path_connected:\n  fixes S :: \"'a::real_normed_vector set\"\n  shows \"starlike S \\<Longrightarrow> path_connected S\"\nby (simp add: simply_connected_imp_path_connected starlike_imp_simply_connected)\n\nlemma starlike_imp_connected:\n  fixes S :: \"'a::real_normed_vector set\"\n  shows \"starlike S \\<Longrightarrow> connected S\"\nby (simp add: path_connected_imp_connected starlike_imp_path_connected)\n\nlemma is_interval_simply_connected_1:\n  fixes S :: \"real set\"\n  shows \"is_interval S \\<longleftrightarrow> simply_connected S\"\nusing convex_imp_simply_connected is_interval_convex_1 is_interval_path_connected_1 simply_connected_imp_path_connected by auto\n\nlemma contractible_empty: \"contractible {}\"\n  by (simp add: continuous_on_empty contractible_def homotopic_with)\n\nlemma contractible_convex_tweak_boundary_points:\n  fixes S :: \"'a::euclidean_space set\"\n  assumes \"convex S\" and TS: \"rel_interior S \\<subseteq> T\" \"T \\<subseteq> closure S\"\n  shows \"contractible T\"\nproof (cases \"S = {}\")\n  case True\n  with assms show ?thesis\n    by (simp add: contractible_empty subsetCE)\nnext\n  case False\n  show ?thesis\n    apply (rule starlike_imp_contractible)\n    apply (rule starlike_convex_tweak_boundary_points [OF \\<open>convex S\\<close> False TS])\n    done\nqed\n\nlemma convex_imp_contractible:\n  fixes S :: \"'a::real_normed_vector set\"\n  shows \"convex S \\<Longrightarrow> contractible S\"\nusing contractible_empty convex_imp_starlike starlike_imp_contractible by auto\n\nlemma contractible_sing:\n  fixes a :: \"'a::real_normed_vector\"\n  shows \"contractible {a}\"\nby (rule convex_imp_contractible [OF convex_singleton])\n\nlemma is_interval_contractible_1:\n  fixes S :: \"real set\"\n  shows  \"is_interval S \\<longleftrightarrow> contractible S\"\nusing contractible_imp_simply_connected convex_imp_contractible is_interval_convex_1\n      is_interval_simply_connected_1 by auto\n\nlemma contractible_Times:\n  fixes S :: \"'a::euclidean_space set\" and T :: \"'b::euclidean_space set\"\n  assumes S: \"contractible S\" and T: \"contractible T\"\n  shows \"contractible (S \\<times> T)\"\nproof -\n  obtain a h where conth: \"continuous_on ({0..1} \\<times> S) h\"\n             and hsub: \"h ` ({0..1} \\<times> S) \\<subseteq> S\"\n             and [simp]: \"\\<And>x. x \\<in> S \\<Longrightarrow> h (0, x) = x\"\n             and [simp]: \"\\<And>x. x \\<in> S \\<Longrightarrow>  h (1::real, x) = a\"\n    using S by (auto simp add: contractible_def homotopic_with)\n  obtain b k where contk: \"continuous_on ({0..1} \\<times> T) k\"\n             and ksub: \"k ` ({0..1} \\<times> T) \\<subseteq> T\"\n             and [simp]: \"\\<And>x. x \\<in> T \\<Longrightarrow> k (0, x) = x\"\n             and [simp]: \"\\<And>x. x \\<in> T \\<Longrightarrow>  k (1::real, x) = b\"\n    using T by (auto simp add: contractible_def homotopic_with)\n  show ?thesis\n    apply (simp add: contractible_def homotopic_with)\n    apply (rule exI [where x=a])\n    apply (rule exI [where x=b])\n    apply (rule exI [where x = \"\\<lambda>z. (h (fst z, fst(snd z)), k (fst z, snd(snd z)))\"])\n    apply (intro conjI ballI continuous_intros continuous_on_compose2 [OF conth] continuous_on_compose2 [OF contk])\n    using hsub ksub\n    apply (auto simp: )\n    done\nqed\n\nlemma homotopy_dominated_contractibility:\n  fixes S :: \"'a::real_normed_vector set\" and T :: \"'b::real_normed_vector set\"\n  assumes S: \"contractible S\"\n      and f: \"continuous_on S f\" \"image f S \\<subseteq> T\"\n      and g: \"continuous_on T g\" \"image g T \\<subseteq> S\"\n      and hom: \"homotopic_with (\\<lambda>x. True) T T (f o g) id\"\n    shows \"contractible T\"\nproof -\n  obtain b where \"homotopic_with (\\<lambda>h. True) S T f (\\<lambda>x. b)\"\n    using nullhomotopic_from_contractible [OF f S] .\n  then have homg: \"homotopic_with (\\<lambda>x. True) T T ((\\<lambda>x. b) \\<circ> g) (f \\<circ> g)\"\n    by (rule homotopic_with_compose_continuous_right [OF homotopic_with_symD g])\n  show ?thesis\n    apply (simp add: contractible_def)\n    apply (rule exI [where x = b])\n    apply (rule homotopic_with_symD)\n    apply (rule homotopic_with_trans [OF _ hom])\n    using homg apply (simp add: o_def)\n    done\nqed\n\nsubsection\\<open>Local versions of topological properties in general\\<close>\n\ndefinition locally :: \"('a::topological_space set \\<Rightarrow> bool) \\<Rightarrow> 'a set \\<Rightarrow> bool\"\nwhere\n \"locally P S \\<equiv>\n        \\<forall>w x. openin (subtopology euclidean S) w \\<and> x \\<in> w\n              \\<longrightarrow> (\\<exists>u v. openin (subtopology euclidean S) u \\<and> P v \\<and>\n                        x \\<in> u \\<and> u \\<subseteq> v \\<and> v \\<subseteq> w)\"\n\nlemma locallyI:\n  assumes \"\\<And>w x. \\<lbrakk>openin (subtopology euclidean S) w; x \\<in> w\\<rbrakk>\n                  \\<Longrightarrow> \\<exists>u v. openin (subtopology euclidean S) u \\<and> P v \\<and>\n                        x \\<in> u \\<and> u \\<subseteq> v \\<and> v \\<subseteq> w\"\n    shows \"locally P S\"\nusing assms by (force simp: locally_def)\n\nlemma locallyE:\n  assumes \"locally P S\" \"openin (subtopology euclidean S) w\" \"x \\<in> w\"\n  obtains u v where \"openin (subtopology euclidean S) u\"\n                    \"P v\" \"x \\<in> u\" \"u \\<subseteq> v\" \"v \\<subseteq> w\"\nusing assms by (force simp: locally_def)\n\nlemma locally_mono:\n  assumes \"locally P S\" \"\\<And>t. P t \\<Longrightarrow> Q t\"\n    shows \"locally Q S\"\nby (metis assms locally_def)\n\nlemma locally_open_subset:\n  assumes \"locally P S\" \"openin (subtopology euclidean S) t\"\n    shows \"locally P t\"\nusing assms\napply (simp add: locally_def)\napply (erule all_forward)+\napply (rule impI)\napply (erule impCE)\n using openin_trans apply blast\napply (erule ex_forward)\nby (metis (no_types, hide_lams) Int_absorb1 Int_lower1 Int_subset_iff openin_open openin_subtopology_Int_subset)\n\nlemma locally_diff_closed:\n    \"\\<lbrakk>locally P S; closedin (subtopology euclidean S) t\\<rbrakk> \\<Longrightarrow> locally P (S - t)\"\n  using locally_open_subset closedin_def by fastforce\n\nlemma locally_empty [iff]: \"locally P {}\"\n  by (simp add: locally_def openin_subtopology)\n\nlemma locally_singleton [iff]:\n  fixes a :: \"'a::metric_space\"\n  shows \"locally P {a} \\<longleftrightarrow> P {a}\"\napply (simp add: locally_def openin_euclidean_subtopology_iff subset_singleton_iff conj_disj_distribR cong: conj_cong)\nusing zero_less_one by blast\n\nlemma locally_iff:\n    \"locally P S \\<longleftrightarrow>\n     (\\<forall>T x. open T \\<and> x \\<in> S \\<inter> T \\<longrightarrow> (\\<exists>U. open U \\<and> (\\<exists>v. P v \\<and> x \\<in> S \\<inter> U \\<and> S \\<inter> U \\<subseteq> v \\<and> v \\<subseteq> S \\<inter> T)))\"\napply (simp add: le_inf_iff locally_def openin_open, safe)\napply (metis IntE IntI le_inf_iff)\napply (metis IntI Int_subset_iff)\ndone\n\nlemma locally_Int:\n  assumes S: \"locally P S\" and t: \"locally P t\"\n      and P: \"\\<And>S t. P S \\<and> P t \\<Longrightarrow> P(S \\<inter> t)\"\n    shows \"locally P (S \\<inter> t)\"\nusing S t unfolding locally_iff\napply clarify\napply (drule_tac x=T in spec)+\napply (drule_tac x=x in spec)+\napply clarsimp\napply (rename_tac U1 U2 V1 V2)\napply (rule_tac x=\"U1 \\<inter> U2\" in exI)\napply (simp add: open_Int)\napply (rule_tac x=\"V1 \\<inter> V2\" in exI)\napply (auto intro: P)\ndone\n\n\nproposition homeomorphism_locally_imp:\n  fixes S :: \"'a::metric_space set\" and t :: \"'b::t2_space set\"\n  assumes S: \"locally P S\" and hom: \"homeomorphism S t f g\"\n      and Q: \"\\<And>S t. \\<lbrakk>P S; homeomorphism S t f g\\<rbrakk> \\<Longrightarrow> Q t\"\n    shows \"locally Q t\"\nproof (clarsimp simp: locally_def)\n  fix w y\n  assume \"y \\<in> w\" and \"openin (subtopology euclidean t) w\"\n  then obtain T where T: \"open T\" \"w = t \\<inter> T\"\n    by (force simp: openin_open)\n  then have \"w \\<subseteq> t\" by auto\n  have f: \"\\<And>x. x \\<in> S \\<Longrightarrow> g(f x) = x\" \"f ` S = t\" \"continuous_on S f\"\n   and g: \"\\<And>y. y \\<in> t \\<Longrightarrow> f(g y) = y\" \"g ` t = S\" \"continuous_on t g\"\n    using hom by (auto simp: homeomorphism_def)\n  have gw: \"g ` w = S \\<inter> {x. f x \\<in> w}\"\n    using \\<open>w \\<subseteq> t\\<close>\n    apply auto\n    using \\<open>g ` t = S\\<close> \\<open>w \\<subseteq> t\\<close> apply blast\n    using g \\<open>w \\<subseteq> t\\<close> apply auto[1]\n    by (simp add: f rev_image_eqI)\n  have o: \"openin (subtopology euclidean S) (g ` w)\"\n  proof -\n    have \"continuous_on S f\"\n      using f(3) by blast\n    then show \"openin (subtopology euclidean S) (g ` w)\"\n      by (simp add: gw Collect_conj_eq \\<open>openin (subtopology euclidean t) w\\<close> continuous_on_open f(2))\n  qed\n  then obtain u v\n    where osu: \"openin (subtopology euclidean S) u\" and uv: \"P v\" \"g y \\<in> u\" \"u \\<subseteq> v\" \"v \\<subseteq> g ` w\"\n    using S [unfolded locally_def, rule_format, of \"g ` w\" \"g y\"] \\<open>y \\<in> w\\<close> by force\n  have \"v \\<subseteq> S\" using uv by (simp add: gw)\n  have fv: \"f ` v = t \\<inter> {x. g x \\<in> v}\"\n    using \\<open>f ` S = t\\<close> f \\<open>v \\<subseteq> S\\<close> by auto\n  have \"f ` v \\<subseteq> w\"\n    using uv using Int_lower2 gw image_subsetI mem_Collect_eq subset_iff by auto\n  have contvf: \"continuous_on v f\"\n    using \\<open>v \\<subseteq> S\\<close> continuous_on_subset f(3) by blast\n  have contvg: \"continuous_on (f ` v) g\"\n    using \\<open>f ` v \\<subseteq> w\\<close> \\<open>w \\<subseteq> t\\<close> continuous_on_subset g(3) by blast\n  have homv: \"homeomorphism v (f ` v) f g\"\n    using \\<open>v \\<subseteq> S\\<close> \\<open>w \\<subseteq> t\\<close> f\n    apply (simp add: homeomorphism_def contvf contvg, auto)\n    by (metis f(1) rev_image_eqI rev_subsetD)\n  have 1: \"openin (subtopology euclidean t) {x \\<in> t. g x \\<in> u}\"\n    apply (rule continuous_on_open [THEN iffD1, rule_format])\n    apply (rule \\<open>continuous_on t g\\<close>)\n    using \\<open>g ` t = S\\<close> apply (simp add: osu)\n    done\n  have 2: \"\\<exists>v. Q v \\<and> y \\<in> {x \\<in> t. g x \\<in> u} \\<and> {x \\<in> t. g x \\<in> u} \\<subseteq> v \\<and> v \\<subseteq> w\"\n    apply (rule_tac x=\"f ` v\" in exI)\n    apply (intro conjI Q [OF \\<open>P v\\<close> homv])\n    using \\<open>w \\<subseteq> t\\<close> \\<open>y \\<in> w\\<close>  \\<open>f ` v \\<subseteq> w\\<close>  uv  apply (auto simp: fv)\n    done\n  show \"\\<exists>u. openin (subtopology euclidean t) u \\<and>\n            (\\<exists>v. Q v \\<and> y \\<in> u \\<and> u \\<subseteq> v \\<and> v \\<subseteq> w)\"\n    by (meson 1 2)\nqed\n\nlemma homeomorphism_locally:\n  fixes f:: \"'a::metric_space \\<Rightarrow> 'b::metric_space\"\n  assumes hom: \"homeomorphism S t f g\"\n      and eq: \"\\<And>S t. homeomorphism S t f g \\<Longrightarrow> (P S \\<longleftrightarrow> Q t)\"\n    shows \"locally P S \\<longleftrightarrow> locally Q t\"\napply (rule iffI)\napply (erule homeomorphism_locally_imp [OF _ hom])\napply (simp add: eq)\napply (erule homeomorphism_locally_imp)\nusing eq homeomorphism_sym homeomorphism_symD [OF hom] apply blast+\ndone\n\nlemma homeomorphic_locally:\n  fixes S:: \"'a::metric_space set\" and T:: \"'b::metric_space set\"\n  assumes hom: \"S homeomorphic T\"\n          and iff: \"\\<And>X Y. X homeomorphic Y \\<Longrightarrow> (P X \\<longleftrightarrow> Q Y)\"\n    shows \"locally P S \\<longleftrightarrow> locally Q T\"\nproof -\n  obtain f g where hom: \"homeomorphism S T f g\"\n    using assms by (force simp: homeomorphic_def)\n  then show ?thesis\n    using homeomorphic_def local.iff\n    by (blast intro!: homeomorphism_locally)\nqed\n\nlemma homeomorphic_local_compactness:\n  fixes S:: \"'a::metric_space set\" and T:: \"'b::metric_space set\"\n  shows \"S homeomorphic T \\<Longrightarrow> locally compact S \\<longleftrightarrow> locally compact T\"\nby (simp add: homeomorphic_compactness homeomorphic_locally)\n\nlemma locally_translation:\n  fixes P :: \"'a :: real_normed_vector set \\<Rightarrow> bool\"\n  shows\n   \"(\\<And>S. P (image (\\<lambda>x. a + x) S) \\<longleftrightarrow> P S)\n        \\<Longrightarrow> locally P (image (\\<lambda>x. a + x) S) \\<longleftrightarrow> locally P S\"\napply (rule homeomorphism_locally [OF homeomorphism_translation])\napply (simp add: homeomorphism_def)\nby metis\n\nlemma locally_injective_linear_image:\n  fixes f :: \"'a::euclidean_space \\<Rightarrow> 'b::euclidean_space\"\n  assumes f: \"linear f\" \"inj f\" and iff: \"\\<And>S. P (f ` S) \\<longleftrightarrow> Q S\"\n    shows \"locally P (f ` S) \\<longleftrightarrow> locally Q S\"\napply (rule linear_homeomorphism_image [OF f])\napply (rule_tac f=g and g = f in homeomorphism_locally, assumption)\nby (metis iff homeomorphism_def)\n\nlemma locally_open_map_image:\n  fixes f :: \"'a::real_normed_vector \\<Rightarrow> 'b::real_normed_vector\"\n  assumes P: \"locally P S\"\n      and f: \"continuous_on S f\"\n      and oo: \"\\<And>t. openin (subtopology euclidean S) t\n                   \\<Longrightarrow> openin (subtopology euclidean (f ` S)) (f ` t)\"\n      and Q: \"\\<And>t. \\<lbrakk>t \\<subseteq> S; P t\\<rbrakk> \\<Longrightarrow> Q(f ` t)\"\n    shows \"locally Q (f ` S)\"\nproof (clarsimp simp add: locally_def)\n  fix w y\n  assume oiw: \"openin (subtopology euclidean (f ` S)) w\" and \"y \\<in> w\"\n  then have \"w \\<subseteq> f ` S\" by (simp add: openin_euclidean_subtopology_iff)\n  have oivf: \"openin (subtopology euclidean S) {x \\<in> S. f x \\<in> w}\"\n    by (rule continuous_on_open [THEN iffD1, rule_format, OF f oiw])\n  then obtain x where \"x \\<in> S\" \"f x = y\"\n    using \\<open>w \\<subseteq> f ` S\\<close> \\<open>y \\<in> w\\<close> by blast\n  then obtain u v\n    where \"openin (subtopology euclidean S) u\" \"P v\" \"x \\<in> u\" \"u \\<subseteq> v\" \"v \\<subseteq> {x \\<in> S. f x \\<in> w}\"\n    using P [unfolded locally_def, rule_format, of \"{x. x \\<in> S \\<and> f x \\<in> w}\" x] oivf \\<open>y \\<in> w\\<close>\n    by auto\n  then show \"\\<exists>u. openin (subtopology euclidean (f ` S)) u \\<and>\n            (\\<exists>v. Q v \\<and> y \\<in> u \\<and> u \\<subseteq> v \\<and> v \\<subseteq> w)\"\n    apply (rule_tac x=\"f ` u\" in exI)\n    apply (rule conjI, blast intro!: oo)\n    apply (rule_tac x=\"f ` v\" in exI)\n    apply (force simp: \\<open>f x = y\\<close> rev_image_eqI intro: Q)\n    done\nqed\n\nsubsection\\<open>Sort of induction principle for connected sets\\<close>\n\nlemma connected_induction:\n  assumes \"connected S\"\n      and opD: \"\\<And>T a. \\<lbrakk>openin (subtopology euclidean S) T; a \\<in> T\\<rbrakk> \\<Longrightarrow> \\<exists>z. z \\<in> T \\<and> P z\"\n      and opI: \"\\<And>a. a \\<in> S\n             \\<Longrightarrow> \\<exists>T. openin (subtopology euclidean S) T \\<and> a \\<in> T \\<and>\n                     (\\<forall>x \\<in> T. \\<forall>y \\<in> T. P x \\<and> P y \\<and> Q x \\<longrightarrow> Q y)\"\n      and etc: \"a \\<in> S\" \"b \\<in> S\" \"P a\" \"P b\" \"Q a\"\n    shows \"Q b\"\nproof -\n  have 1: \"openin (subtopology euclidean S)\n             {b. \\<exists>T. openin (subtopology euclidean S) T \\<and>\n                     b \\<in> T \\<and> (\\<forall>x\\<in>T. P x \\<longrightarrow> Q x)}\"\n    apply (subst openin_subopen, clarify)\n    apply (rule_tac x=T in exI, auto)\n    done\n  have 2: \"openin (subtopology euclidean S)\n             {b. \\<exists>T. openin (subtopology euclidean S) T \\<and>\n                     b \\<in> T \\<and> (\\<forall>x\\<in>T. P x \\<longrightarrow> ~ Q x)}\"\n    apply (subst openin_subopen, clarify)\n    apply (rule_tac x=T in exI, auto)\n    done\n  show ?thesis\n    using \\<open>connected S\\<close>\n    apply (simp only: connected_openin HOL.not_ex HOL.de_Morgan_conj)\n    apply (elim disjE allE)\n         apply (blast intro: 1)\n        apply (blast intro: 2, simp_all)\n       apply clarify apply (metis opI)\n      using opD apply (blast intro: etc elim: dest:)\n     using opI etc apply meson+\n    done\nqed\n\nlemma connected_equivalence_relation_gen:\n  assumes \"connected S\"\n      and etc: \"a \\<in> S\" \"b \\<in> S\" \"P a\" \"P b\"\n      and trans: \"\\<And>x y z. \\<lbrakk>R x y; R y z\\<rbrakk> \\<Longrightarrow> R x z\"\n      and opD: \"\\<And>T a. \\<lbrakk>openin (subtopology euclidean S) T; a \\<in> T\\<rbrakk> \\<Longrightarrow> \\<exists>z. z \\<in> T \\<and> P z\"\n      and opI: \"\\<And>a. a \\<in> S\n             \\<Longrightarrow> \\<exists>T. openin (subtopology euclidean S) T \\<and> a \\<in> T \\<and>\n                     (\\<forall>x \\<in> T. \\<forall>y \\<in> T. P x \\<and> P y \\<longrightarrow> R x y)\"\n    shows \"R a b\"\nproof -\n  have \"\\<And>a b c. \\<lbrakk>a \\<in> S; P a; b \\<in> S; c \\<in> S; P b; P c; R a b\\<rbrakk> \\<Longrightarrow> R a c\"\n    apply (rule connected_induction [OF \\<open>connected S\\<close> opD], simp_all)\n    by (meson trans opI)\n  then show ?thesis by (metis etc opI)\nqed\n\nlemma connected_induction_simple:\n  assumes \"connected S\"\n      and etc: \"a \\<in> S\" \"b \\<in> S\" \"P a\"\n      and opI: \"\\<And>a. a \\<in> S\n             \\<Longrightarrow> \\<exists>T. openin (subtopology euclidean S) T \\<and> a \\<in> T \\<and>\n                     (\\<forall>x \\<in> T. \\<forall>y \\<in> T. P x \\<longrightarrow> P y)\"\n    shows \"P b\"\napply (rule connected_induction [OF \\<open>connected S\\<close> _, where P = \"\\<lambda>x. True\"], blast)\napply (frule opI)\nusing etc apply simp_all\ndone\n\nlemma connected_equivalence_relation:\n  assumes \"connected S\"\n      and etc: \"a \\<in> S\" \"b \\<in> S\"\n      and sym: \"\\<And>x y. \\<lbrakk>R x y; x \\<in> S; y \\<in> S\\<rbrakk> \\<Longrightarrow> R y x\"\n      and trans: \"\\<And>x y z. \\<lbrakk>R x y; R y z; x \\<in> S; y \\<in> S; z \\<in> S\\<rbrakk> \\<Longrightarrow> R x z\"\n      and opI: \"\\<And>a. a \\<in> S \\<Longrightarrow> \\<exists>T. openin (subtopology euclidean S) T \\<and> a \\<in> T \\<and> (\\<forall>x \\<in> T. R a x)\"\n    shows \"R a b\"\nproof -\n  have \"\\<And>a b c. \\<lbrakk>a \\<in> S; b \\<in> S; c \\<in> S; R a b\\<rbrakk> \\<Longrightarrow> R a c\"\n    apply (rule connected_induction_simple [OF \\<open>connected S\\<close>], simp_all)\n    by (meson local.sym local.trans opI openin_imp_subset subsetCE)\n  then show ?thesis by (metis etc opI)\nqed\n\nlemma locally_constant_imp_constant:\n  assumes \"connected S\"\n      and opI: \"\\<And>a. a \\<in> S\n             \\<Longrightarrow> \\<exists>T. openin (subtopology euclidean S) T \\<and> a \\<in> T \\<and> (\\<forall>x \\<in> T. f x = f a)\"\n    shows \"f constant_on S\"\nproof -\n  have \"\\<And>x y. x \\<in> S \\<Longrightarrow> y \\<in> S \\<Longrightarrow> f x = f y\"\n    apply (rule connected_equivalence_relation [OF \\<open>connected S\\<close>], simp_all)\n    by (metis opI)\n  then show ?thesis\n    by (metis constant_on_def)\nqed\n\nlemma locally_constant:\n     \"connected S \\<Longrightarrow> locally (\\<lambda>U. f constant_on U) S \\<longleftrightarrow> f constant_on S\"\napply (simp add: locally_def)\napply (rule iffI)\n apply (rule locally_constant_imp_constant, assumption)\n apply (metis (mono_tags, hide_lams) constant_on_def constant_on_subset openin_subtopology_self)\nby (meson constant_on_subset openin_imp_subset order_refl)\n\n\nsubsection\\<open>Basic properties of local compactness\\<close>\n\nlemma locally_compact:\n  fixes s :: \"'a :: metric_space set\"\n  shows\n    \"locally compact s \\<longleftrightarrow>\n     (\\<forall>x \\<in> s. \\<exists>u v. x \\<in> u \\<and> u \\<subseteq> v \\<and> v \\<subseteq> s \\<and>\n                    openin (subtopology euclidean s) u \\<and> compact v)\"\n     (is \"?lhs = ?rhs\")\nproof\n  assume ?lhs\n  then show ?rhs\n    apply clarify\n    apply (erule_tac w = \"s \\<inter> ball x 1\" in locallyE)\n    by auto\nnext\n  assume r [rule_format]: ?rhs\n  have *: \"\\<exists>u v.\n              openin (subtopology euclidean s) u \\<and>\n              compact v \\<and> x \\<in> u \\<and> u \\<subseteq> v \\<and> v \\<subseteq> s \\<inter> T\"\n          if \"open T\" \"x \\<in> s\" \"x \\<in> T\" for x T\n  proof -\n    obtain u v where uv: \"x \\<in> u\" \"u \\<subseteq> v\" \"v \\<subseteq> s\" \"compact v\" \"openin (subtopology euclidean s) u\"\n      using r [OF \\<open>x \\<in> s\\<close>] by auto\n    obtain e where \"e>0\" and e: \"cball x e \\<subseteq> T\"\n      using open_contains_cball \\<open>open T\\<close> \\<open>x \\<in> T\\<close> by blast\n    show ?thesis\n      apply (rule_tac x=\"(s \\<inter> ball x e) \\<inter> u\" in exI)\n      apply (rule_tac x=\"cball x e \\<inter> v\" in exI)\n      using that \\<open>e > 0\\<close> e uv\n      apply auto\n      done\n  qed\n  show ?lhs\n    apply (rule locallyI)\n    apply (subst (asm) openin_open)\n    apply (blast intro: *)\n    done\nqed\n\nlemma locally_compactE:\n  fixes s :: \"'a :: metric_space set\"\n  assumes \"locally compact s\"\n  obtains u v where \"\\<And>x. x \\<in> s \\<Longrightarrow> x \\<in> u x \\<and> u x \\<subseteq> v x \\<and> v x \\<subseteq> s \\<and>\n                             openin (subtopology euclidean s) (u x) \\<and> compact (v x)\"\nusing assms\nunfolding locally_compact by metis\n\nlemma locally_compact_alt:\n  fixes s :: \"'a :: heine_borel set\"\n  shows \"locally compact s \\<longleftrightarrow>\n         (\\<forall>x \\<in> s. \\<exists>u. x \\<in> u \\<and>\n                    openin (subtopology euclidean s) u \\<and> compact(closure u) \\<and> closure u \\<subseteq> s)\"\napply (simp add: locally_compact)\napply (intro ball_cong ex_cong refl iffI)\napply (metis bounded_subset closure_eq closure_mono compact_eq_bounded_closed dual_order.trans)\nby (meson closure_subset compact_closure)\n\nlemma locally_compact_Int_cball:\n  fixes s :: \"'a :: heine_borel set\"\n  shows \"locally compact s \\<longleftrightarrow> (\\<forall>x \\<in> s. \\<exists>e. 0 < e \\<and> closed(cball x e \\<inter> s))\"\n        (is \"?lhs = ?rhs\")\nproof\n  assume ?lhs\n  then show ?rhs\n    apply (simp add: locally_compact openin_contains_cball)\n    apply (clarify | assumption | drule bspec)+\n    by (metis (no_types, lifting)  compact_cball compact_imp_closed compact_Int inf.absorb_iff2 inf.orderE inf_sup_aci(2))\nnext\n  assume ?rhs\n  then show ?lhs\n    apply (simp add: locally_compact openin_contains_cball)\n    apply (clarify | assumption | drule bspec)+\n    apply (rule_tac x=\"ball x e \\<inter> s\" in exI, simp)\n    apply (rule_tac x=\"cball x e \\<inter> s\" in exI)\n    using compact_eq_bounded_closed\n    apply auto\n    apply (metis open_ball le_infI1 mem_ball open_contains_cball_eq)\n    done\nqed\n\nlemma locally_compact_compact:\n  fixes s :: \"'a :: heine_borel set\"\n  shows \"locally compact s \\<longleftrightarrow>\n         (\\<forall>k. k \\<subseteq> s \\<and> compact k\n              \\<longrightarrow> (\\<exists>u v. k \\<subseteq> u \\<and> u \\<subseteq> v \\<and> v \\<subseteq> s \\<and>\n                         openin (subtopology euclidean s) u \\<and> compact v))\"\n        (is \"?lhs = ?rhs\")\nproof\n  assume ?lhs\n  then obtain u v where\n    uv: \"\\<And>x. x \\<in> s \\<Longrightarrow> x \\<in> u x \\<and> u x \\<subseteq> v x \\<and> v x \\<subseteq> s \\<and>\n                             openin (subtopology euclidean s) (u x) \\<and> compact (v x)\"\n    by (metis locally_compactE)\n  have *: \"\\<exists>u v. k \\<subseteq> u \\<and> u \\<subseteq> v \\<and> v \\<subseteq> s \\<and> openin (subtopology euclidean s) u \\<and> compact v\"\n          if \"k \\<subseteq> s\" \"compact k\" for k\n  proof -\n    have \"\\<And>C. (\\<forall>c\\<in>C. openin (subtopology euclidean k) c) \\<and> k \\<subseteq> \\<Union>C \\<Longrightarrow>\n                    \\<exists>D\\<subseteq>C. finite D \\<and> k \\<subseteq> \\<Union>D\"\n      using that by (simp add: compact_eq_openin_cover)\n    moreover have \"\\<forall>c \\<in> (\\<lambda>x. k \\<inter> u x) ` k. openin (subtopology euclidean k) c\"\n      using that by clarify (metis subsetD inf.absorb_iff2 openin_subset openin_subtopology_Int_subset topspace_euclidean_subtopology uv)\n    moreover have \"k \\<subseteq> \\<Union>((\\<lambda>x. k \\<inter> u x) ` k)\"\n      using that by clarsimp (meson subsetCE uv)\n    ultimately obtain D where \"D \\<subseteq> (\\<lambda>x. k \\<inter> u x) ` k\" \"finite D\" \"k \\<subseteq> \\<Union>D\"\n      by metis\n    then obtain T where T: \"T \\<subseteq> k\" \"finite T\" \"k \\<subseteq> \\<Union>((\\<lambda>x. k \\<inter> u x) ` T)\"\n      by (metis finite_subset_image)\n    have Tuv: \"UNION T u \\<subseteq> UNION T v\"\n      using T that by (force simp: dest!: uv)\n    show ?thesis\n      apply (rule_tac x=\"\\<Union>(u ` T)\" in exI)\n      apply (rule_tac x=\"\\<Union>(v ` T)\" in exI)\n      apply (simp add: Tuv)\n      using T that\n      apply (auto simp: dest!: uv)\n      done\n  qed\n  show ?rhs\n    by (blast intro: *)\nnext\n  assume ?rhs\n  then show ?lhs\n    apply (clarsimp simp add: locally_compact)\n    apply (drule_tac x=\"{x}\" in spec, simp)\n    done\nqed\n\nlemma open_imp_locally_compact:\n  fixes s :: \"'a :: heine_borel set\"\n  assumes \"open s\"\n    shows \"locally compact s\"\nproof -\n  have *: \"\\<exists>u v. x \\<in> u \\<and> u \\<subseteq> v \\<and> v \\<subseteq> s \\<and> openin (subtopology euclidean s) u \\<and> compact v\"\n          if \"x \\<in> s\" for x\n  proof -\n    obtain e where \"e>0\" and e: \"cball x e \\<subseteq> s\"\n      using open_contains_cball assms \\<open>x \\<in> s\\<close> by blast\n    have ope: \"openin (subtopology euclidean s) (ball x e)\"\n      by (meson e open_ball ball_subset_cball dual_order.trans open_subset)\n    show ?thesis\n      apply (rule_tac x=\"ball x e\" in exI)\n      apply (rule_tac x=\"cball x e\" in exI)\n      using \\<open>e > 0\\<close> e apply (auto simp: ope)\n      done\n  qed\n  show ?thesis\n    unfolding locally_compact\n    by (blast intro: *)\nqed\n\nlemma closed_imp_locally_compact:\n  fixes s :: \"'a :: heine_borel set\"\n  assumes \"closed s\"\n    shows \"locally compact s\"\nproof -\n  have *: \"\\<exists>u v. x \\<in> u \\<and> u \\<subseteq> v \\<and> v \\<subseteq> s \\<and>\n                 openin (subtopology euclidean s) u \\<and> compact v\"\n          if \"x \\<in> s\" for x\n  proof -\n    show ?thesis\n      apply (rule_tac x = \"s \\<inter> ball x 1\" in exI)\n      apply (rule_tac x = \"s \\<inter> cball x 1\" in exI)\n      using \\<open>x \\<in> s\\<close> assms apply auto\n      done\n  qed\n  show ?thesis\n    unfolding locally_compact\n    by (blast intro: *)\nqed\n\nlemma locally_compact_UNIV: \"locally compact (UNIV :: 'a :: heine_borel set)\"\n  by (simp add: closed_imp_locally_compact)\n\nlemma locally_compact_Int:\n  fixes s :: \"'a :: t2_space set\"\n  shows \"\\<lbrakk>locally compact s; locally compact t\\<rbrakk> \\<Longrightarrow> locally compact (s \\<inter> t)\"\nby (simp add: compact_Int locally_Int)\n\nlemma locally_compact_closedin:\n  fixes s :: \"'a :: heine_borel set\"\n  shows \"\\<lbrakk>closedin (subtopology euclidean s) t; locally compact s\\<rbrakk>\n        \\<Longrightarrow> locally compact t\"\nunfolding closedin_closed\nusing closed_imp_locally_compact locally_compact_Int by blast\n\nlemma locally_compact_delete:\n     fixes s :: \"'a :: t1_space set\"\n     shows \"locally compact s \\<Longrightarrow> locally compact (s - {a})\"\n  by (auto simp: openin_delete locally_open_subset)\n\nlemma locally_closed:\n  fixes s :: \"'a :: heine_borel set\"\n  shows \"locally closed s \\<longleftrightarrow> locally compact s\"\n        (is \"?lhs = ?rhs\")\nproof\n  assume ?lhs\n  then show ?rhs\n    apply (simp only: locally_def)\n    apply (erule all_forward imp_forward asm_rl exE)+\n    apply (rule_tac x = \"u \\<inter> ball x 1\" in exI)\n    apply (rule_tac x = \"v \\<inter> cball x 1\" in exI)\n    apply (force intro: openin_trans)\n    done\nnext\n  assume ?rhs then show ?lhs\n    using compact_eq_bounded_closed locally_mono by blast\nqed\n\nsubsection\\<open>Important special cases of local connectedness and path connectedness\\<close>\n\nlemma locally_connected_1:\n  assumes\n    \"\\<And>v x. \\<lbrakk>openin (subtopology euclidean S) v; x \\<in> v\\<rbrakk>\n              \\<Longrightarrow> \\<exists>u. openin (subtopology euclidean S) u \\<and>\n                      connected u \\<and> x \\<in> u \\<and> u \\<subseteq> v\"\n   shows \"locally connected S\"\napply (clarsimp simp add: locally_def)\napply (drule assms; blast)\ndone\n\nlemma locally_connected_2:\n  assumes \"locally connected S\"\n          \"openin (subtopology euclidean S) t\"\n          \"x \\<in> t\"\n   shows \"openin (subtopology euclidean S) (connected_component_set t x)\"\nproof -\n  { fix y :: 'a\n    let ?SS = \"subtopology euclidean S\"\n    assume 1: \"openin ?SS t\"\n              \"\\<forall>w x. openin ?SS w \\<and> x \\<in> w \\<longrightarrow> (\\<exists>u. openin ?SS u \\<and> (\\<exists>v. connected v \\<and> x \\<in> u \\<and> u \\<subseteq> v \\<and> v \\<subseteq> w))\"\n    and \"connected_component t x y\"\n    then have \"y \\<in> t\" and y: \"y \\<in> connected_component_set t x\"\n      using connected_component_subset by blast+\n    obtain F where\n      \"\\<forall>x y. (\\<exists>w. openin ?SS w \\<and> (\\<exists>u. connected u \\<and> x \\<in> w \\<and> w \\<subseteq> u \\<and> u \\<subseteq> y)) = (openin ?SS (F x y) \\<and> (\\<exists>u. connected u \\<and> x \\<in> F x y \\<and> F x y \\<subseteq> u \\<and> u \\<subseteq> y))\"\n      by moura\n    then obtain G where\n       \"\\<forall>a A. (\\<exists>U. openin ?SS U \\<and> (\\<exists>V. connected V \\<and> a \\<in> U \\<and> U \\<subseteq> V \\<and> V \\<subseteq> A)) = (openin ?SS (F a A) \\<and> connected (G a A) \\<and> a \\<in> F a A \\<and> F a A \\<subseteq> G a A \\<and> G a A \\<subseteq> A)\"\n      by moura\n    then have *: \"openin ?SS (F y t) \\<and> connected (G y t) \\<and> y \\<in> F y t \\<and> F y t \\<subseteq> G y t \\<and> G y t \\<subseteq> t\"\n      using 1 \\<open>y \\<in> t\\<close> by presburger\n    have \"G y t \\<subseteq> connected_component_set t y\"\n      by (metis (no_types) * connected_component_eq_self connected_component_mono contra_subsetD)\n    then have \"\\<exists>A. openin ?SS A \\<and> y \\<in> A \\<and> A \\<subseteq> connected_component_set t x\"\n      by (metis (no_types) * connected_component_eq dual_order.trans y)\n  }\n  then show ?thesis\n    using assms openin_subopen by (force simp: locally_def)\nqed\n\nlemma locally_connected_3:\n  assumes \"\\<And>t x. \\<lbrakk>openin (subtopology euclidean S) t; x \\<in> t\\<rbrakk>\n              \\<Longrightarrow> openin (subtopology euclidean S)\n                          (connected_component_set t x)\"\n          \"openin (subtopology euclidean S) v\" \"x \\<in> v\"\n   shows  \"\\<exists>u. openin (subtopology euclidean S) u \\<and> connected u \\<and> x \\<in> u \\<and> u \\<subseteq> v\"\nusing assms connected_component_subset by fastforce\n\nlemma locally_connected:\n  \"locally connected S \\<longleftrightarrow>\n   (\\<forall>v x. openin (subtopology euclidean S) v \\<and> x \\<in> v\n          \\<longrightarrow> (\\<exists>u. openin (subtopology euclidean S) u \\<and> connected u \\<and> x \\<in> u \\<and> u \\<subseteq> v))\"\nby (metis locally_connected_1 locally_connected_2 locally_connected_3)\n\nlemma locally_connected_open_connected_component:\n  \"locally connected S \\<longleftrightarrow>\n   (\\<forall>t x. openin (subtopology euclidean S) t \\<and> x \\<in> t\n          \\<longrightarrow> openin (subtopology euclidean S) (connected_component_set t x))\"\nby (metis locally_connected_1 locally_connected_2 locally_connected_3)\n\nlemma locally_path_connected_1:\n  assumes\n    \"\\<And>v x. \\<lbrakk>openin (subtopology euclidean S) v; x \\<in> v\\<rbrakk>\n              \\<Longrightarrow> \\<exists>u. openin (subtopology euclidean S) u \\<and> path_connected u \\<and> x \\<in> u \\<and> u \\<subseteq> v\"\n   shows \"locally path_connected S\"\napply (clarsimp simp add: locally_def)\napply (drule assms; blast)\ndone\n\nlemma locally_path_connected_2:\n  assumes \"locally path_connected S\"\n          \"openin (subtopology euclidean S) t\"\n          \"x \\<in> t\"\n   shows \"openin (subtopology euclidean S) (path_component_set t x)\"\nproof -\n  { fix y :: 'a\n    let ?SS = \"subtopology euclidean S\"\n    assume 1: \"openin ?SS t\"\n              \"\\<forall>w x. openin ?SS w \\<and> x \\<in> w \\<longrightarrow> (\\<exists>u. openin ?SS u \\<and> (\\<exists>v. path_connected v \\<and> x \\<in> u \\<and> u \\<subseteq> v \\<and> v \\<subseteq> w))\"\n    and \"path_component t x y\"\n    then have \"y \\<in> t\" and y: \"y \\<in> path_component_set t x\"\n      using path_component_mem(2) by blast+\n    obtain F where\n      \"\\<forall>x y. (\\<exists>w. openin ?SS w \\<and> (\\<exists>u. path_connected u \\<and> x \\<in> w \\<and> w \\<subseteq> u \\<and> u \\<subseteq> y)) = (openin ?SS (F x y) \\<and> (\\<exists>u. path_connected u \\<and> x \\<in> F x y \\<and> F x y \\<subseteq> u \\<and> u \\<subseteq> y))\"\n      by moura\n    then obtain G where\n       \"\\<forall>a A. (\\<exists>U. openin ?SS U \\<and> (\\<exists>V. path_connected V \\<and> a \\<in> U \\<and> U \\<subseteq> V \\<and> V \\<subseteq> A)) = (openin ?SS (F a A) \\<and> path_connected (G a A) \\<and> a \\<in> F a A \\<and> F a A \\<subseteq> G a A \\<and> G a A \\<subseteq> A)\"\n      by moura\n    then have *: \"openin ?SS (F y t) \\<and> path_connected (G y t) \\<and> y \\<in> F y t \\<and> F y t \\<subseteq> G y t \\<and> G y t \\<subseteq> t\"\n      using 1 \\<open>y \\<in> t\\<close> by presburger\n    have \"G y t \\<subseteq> path_component_set t y\"\n      using * path_component_maximal set_rev_mp by blast\n    then have \"\\<exists>A. openin ?SS A \\<and> y \\<in> A \\<and> A \\<subseteq> path_component_set t x\"\n      by (metis \"*\" \\<open>G y t \\<subseteq> path_component_set t y\\<close> dual_order.trans path_component_eq y)\n  }\n  then show ?thesis\n    using assms openin_subopen by (force simp: locally_def)\nqed\n\nlemma locally_path_connected_3:\n  assumes \"\\<And>t x. \\<lbrakk>openin (subtopology euclidean S) t; x \\<in> t\\<rbrakk>\n              \\<Longrightarrow> openin (subtopology euclidean S) (path_component_set t x)\"\n          \"openin (subtopology euclidean S) v\" \"x \\<in> v\"\n   shows  \"\\<exists>u. openin (subtopology euclidean S) u \\<and> path_connected u \\<and> x \\<in> u \\<and> u \\<subseteq> v\"\nproof -\n  have \"path_component v x x\"\n    by (meson assms(3) path_component_refl)\n  then show ?thesis\n    by (metis assms(1) assms(2) assms(3) mem_Collect_eq path_component_subset path_connected_path_component)\nqed\n\nproposition locally_path_connected:\n  \"locally path_connected S \\<longleftrightarrow>\n   (\\<forall>v x. openin (subtopology euclidean S) v \\<and> x \\<in> v\n          \\<longrightarrow> (\\<exists>u. openin (subtopology euclidean S) u \\<and> path_connected u \\<and> x \\<in> u \\<and> u \\<subseteq> v))\"\nby (metis locally_path_connected_1 locally_path_connected_2 locally_path_connected_3)\n\nproposition locally_path_connected_open_path_component:\n  \"locally path_connected S \\<longleftrightarrow>\n   (\\<forall>t x. openin (subtopology euclidean S) t \\<and> x \\<in> t\n          \\<longrightarrow> openin (subtopology euclidean S) (path_component_set t x))\"\nby (metis locally_path_connected_1 locally_path_connected_2 locally_path_connected_3)\n\nlemma locally_connected_open_component:\n  \"locally connected S \\<longleftrightarrow>\n   (\\<forall>t c. openin (subtopology euclidean S) t \\<and> c \\<in> components t\n          \\<longrightarrow> openin (subtopology euclidean S) c)\"\nby (metis components_iff locally_connected_open_connected_component)\n\nproposition locally_connected_im_kleinen:\n  \"locally connected S \\<longleftrightarrow>\n   (\\<forall>v x. openin (subtopology euclidean S) v \\<and> x \\<in> v\n       \\<longrightarrow> (\\<exists>u. openin (subtopology euclidean S) u \\<and>\n                x \\<in> u \\<and> u \\<subseteq> v \\<and>\n                (\\<forall>y. y \\<in> u \\<longrightarrow> (\\<exists>c. connected c \\<and> c \\<subseteq> v \\<and> x \\<in> c \\<and> y \\<in> c))))\"\n   (is \"?lhs = ?rhs\")\nproof\n  assume ?lhs\n  then show ?rhs\n    by (fastforce simp add: locally_connected)\nnext\n  assume ?rhs\n  have *: \"\\<exists>T. openin (subtopology euclidean S) T \\<and> x \\<in> T \\<and> T \\<subseteq> c\"\n       if \"openin (subtopology euclidean S) t\" and c: \"c \\<in> components t\" and \"x \\<in> c\" for t c x\n  proof -\n    from that \\<open>?rhs\\<close> [rule_format, of t x]\n    obtain u where u:\n      \"openin (subtopology euclidean S) u \\<and> x \\<in> u \\<and> u \\<subseteq> t \\<and>\n       (\\<forall>y. y \\<in> u \\<longrightarrow> (\\<exists>c. connected c \\<and> c \\<subseteq> t \\<and> x \\<in> c \\<and> y \\<in> c))\"\n      by auto (meson subsetD in_components_subset)\n    obtain F :: \"'a set \\<Rightarrow> 'a set \\<Rightarrow> 'a\" where\n      \"\\<forall>x y. (\\<exists>z. z \\<in> x \\<and> y = connected_component_set x z) = (F x y \\<in> x \\<and> y = connected_component_set x (F x y))\"\n      by moura\n    then have F: \"F t c \\<in> t \\<and> c = connected_component_set t (F t c)\"\n      by (meson components_iff c)\n    obtain G :: \"'a set \\<Rightarrow> 'a set \\<Rightarrow> 'a\" where\n        G: \"\\<forall>x y. (\\<exists>z. z \\<in> y \\<and> z \\<notin> x) = (G x y \\<in> y \\<and> G x y \\<notin> x)\"\n      by moura\n     have \"G c u \\<notin> u \\<or> G c u \\<in> c\"\n      using F by (metis (full_types) u connected_componentI connected_component_eq mem_Collect_eq that(3))\n    then show ?thesis\n      using G u by auto\n  qed\n  show ?lhs\n    apply (clarsimp simp add: locally_connected_open_component)\n    apply (subst openin_subopen)\n    apply (blast intro: *)\n    done\nqed\n\nproposition locally_path_connected_im_kleinen:\n  \"locally path_connected S \\<longleftrightarrow>\n   (\\<forall>v x. openin (subtopology euclidean S) v \\<and> x \\<in> v\n       \\<longrightarrow> (\\<exists>u. openin (subtopology euclidean S) u \\<and>\n                x \\<in> u \\<and> u \\<subseteq> v \\<and>\n                (\\<forall>y. y \\<in> u \\<longrightarrow> (\\<exists>p. path p \\<and> path_image p \\<subseteq> v \\<and>\n                                pathstart p = x \\<and> pathfinish p = y))))\"\n   (is \"?lhs = ?rhs\")\nproof\n  assume ?lhs\n  then show ?rhs\n    apply (simp add: locally_path_connected path_connected_def)\n    apply (erule all_forward ex_forward imp_forward conjE | simp)+\n    by (meson dual_order.trans)\nnext\n  assume ?rhs\n  have *: \"\\<exists>T. openin (subtopology euclidean S) T \\<and>\n               x \\<in> T \\<and> T \\<subseteq> path_component_set u z\"\n       if \"openin (subtopology euclidean S) u\" and \"z \\<in> u\" and c: \"path_component u z x\" for u z x\n  proof -\n    have \"x \\<in> u\"\n      by (meson c path_component_mem(2))\n    with that \\<open>?rhs\\<close> [rule_format, of u x]\n    obtain U where U:\n      \"openin (subtopology euclidean S) U \\<and> x \\<in> U \\<and> U \\<subseteq> u \\<and>\n       (\\<forall>y. y \\<in> U \\<longrightarrow> (\\<exists>p. path p \\<and> path_image p \\<subseteq> u \\<and> pathstart p = x \\<and> pathfinish p = y))\"\n       by blast\n    show ?thesis\n      apply (rule_tac x=U in exI)\n      apply (auto simp: U)\n      apply (metis U c path_component_trans path_component_def)\n      done\n  qed\n  show ?lhs\n    apply (clarsimp simp add: locally_path_connected_open_path_component)\n    apply (subst openin_subopen)\n    apply (blast intro: *)\n    done\nqed\n\nlemma locally_path_connected_imp_locally_connected:\n  \"locally path_connected S \\<Longrightarrow> locally connected S\"\nusing locally_mono path_connected_imp_connected by blast\n\nlemma locally_connected_components:\n  \"\\<lbrakk>locally connected S; c \\<in> components S\\<rbrakk> \\<Longrightarrow> locally connected c\"\nby (meson locally_connected_open_component locally_open_subset openin_subtopology_self)\n\nlemma locally_path_connected_components:\n  \"\\<lbrakk>locally path_connected S; c \\<in> components S\\<rbrakk> \\<Longrightarrow> locally path_connected c\"\nby (meson locally_connected_open_component locally_open_subset locally_path_connected_imp_locally_connected openin_subtopology_self)\n\nlemma locally_path_connected_connected_component:\n  \"locally path_connected S \\<Longrightarrow> locally path_connected (connected_component_set S x)\"\nby (metis components_iff connected_component_eq_empty locally_empty locally_path_connected_components)\n\nlemma open_imp_locally_path_connected:\n  fixes S :: \"'a :: real_normed_vector set\"\n  shows \"open S \\<Longrightarrow> locally path_connected S\"\napply (rule locally_mono [of convex])\napply (simp_all add: locally_def openin_open_eq convex_imp_path_connected)\napply (meson Topology_Euclidean_Space.open_ball centre_in_ball convex_ball openE order_trans)\ndone\n\nlemma open_imp_locally_connected:\n  fixes S :: \"'a :: real_normed_vector set\"\n  shows \"open S \\<Longrightarrow> locally connected S\"\nby (simp add: locally_path_connected_imp_locally_connected open_imp_locally_path_connected)\n\nlemma locally_path_connected_UNIV: \"locally path_connected (UNIV::'a :: real_normed_vector set)\"\n  by (simp add: open_imp_locally_path_connected)\n\nlemma locally_connected_UNIV: \"locally connected (UNIV::'a :: real_normed_vector set)\"\n  by (simp add: open_imp_locally_connected)\n\nlemma openin_connected_component_locally_connected:\n    \"locally connected S\n     \\<Longrightarrow> openin (subtopology euclidean S) (connected_component_set S x)\"\napply (simp add: locally_connected_open_connected_component)\nby (metis connected_component_eq_empty connected_component_subset open_empty open_subset openin_subtopology_self)\n\nlemma openin_components_locally_connected:\n    \"\\<lbrakk>locally connected S; c \\<in> components S\\<rbrakk> \\<Longrightarrow> openin (subtopology euclidean S) c\"\n  using locally_connected_open_component openin_subtopology_self by blast\n\nlemma openin_path_component_locally_path_connected:\n  \"locally path_connected S\n        \\<Longrightarrow> openin (subtopology euclidean S) (path_component_set S x)\"\nby (metis (no_types) empty_iff locally_path_connected_2 openin_subopen openin_subtopology_self path_component_eq_empty)\n\nlemma closedin_path_component_locally_path_connected:\n    \"locally path_connected S\n        \\<Longrightarrow> closedin (subtopology euclidean S) (path_component_set S x)\"\napply  (simp add: closedin_def path_component_subset complement_path_component_Union)\napply (rule openin_Union)\nusing openin_path_component_locally_path_connected by auto\n\nlemma convex_imp_locally_path_connected:\n  fixes S :: \"'a:: real_normed_vector set\"\n  shows \"convex S \\<Longrightarrow> locally path_connected S\"\napply (clarsimp simp add: locally_path_connected)\napply (subst (asm) openin_open)\napply clarify\napply (erule (1) Topology_Euclidean_Space.openE)\napply (rule_tac x = \"S \\<inter> ball x e\" in exI)\napply (force simp: convex_Int convex_imp_path_connected)\ndone\n\nlemma convex_imp_locally_connected:\n  fixes S :: \"'a:: real_normed_vector set\"\n  shows \"convex S \\<Longrightarrow> locally connected S\"\n  by (simp add: locally_path_connected_imp_locally_connected convex_imp_locally_path_connected)\n\n\nsubsection\\<open>Relations between components and path components\\<close>\n\nlemma path_component_eq_connected_component:\n  assumes \"locally path_connected S\"\n    shows \"(path_component S x = connected_component S x)\"\nproof (cases \"x \\<in> S\")\n  case True\n  have \"openin (subtopology euclidean (connected_component_set S x)) (path_component_set S x)\"\n    apply (rule openin_subset_trans [of S])\n    apply (intro conjI openin_path_component_locally_path_connected [OF assms])\n    using path_component_subset_connected_component   apply (auto simp: connected_component_subset)\n    done\n  moreover have \"closedin (subtopology euclidean (connected_component_set S x)) (path_component_set S x)\"\n    apply (rule closedin_subset_trans [of S])\n    apply (intro conjI closedin_path_component_locally_path_connected [OF assms])\n    using path_component_subset_connected_component   apply (auto simp: connected_component_subset)\n    done\n  ultimately have *: \"path_component_set S x = connected_component_set S x\"\n    by (metis connected_connected_component connected_clopen True path_component_eq_empty)\n  then show ?thesis\n    by blast\nnext\n  case False then show ?thesis\n    by (metis Collect_empty_eq_bot connected_component_eq_empty path_component_eq_empty)\nqed\n\nlemma path_component_eq_connected_component_set:\n     \"locally path_connected S \\<Longrightarrow> (path_component_set S x = connected_component_set S x)\"\nby (simp add: path_component_eq_connected_component)\n\nlemma locally_path_connected_path_component:\n     \"locally path_connected S \\<Longrightarrow> locally path_connected (path_component_set S x)\"\nusing locally_path_connected_connected_component path_component_eq_connected_component by fastforce\n\nlemma open_path_connected_component:\n  fixes S :: \"'a :: real_normed_vector set\"\n  shows \"open S \\<Longrightarrow> path_component S x = connected_component S x\"\nby (simp add: path_component_eq_connected_component open_imp_locally_path_connected)\n\nlemma open_path_connected_component_set:\n  fixes S :: \"'a :: real_normed_vector set\"\n  shows \"open S \\<Longrightarrow> path_component_set S x = connected_component_set S x\"\nby (simp add: open_path_connected_component)\n\nproposition locally_connected_quotient_image:\n  assumes lcS: \"locally connected S\"\n      and oo: \"\\<And>T. T \\<subseteq> f ` S\n                \\<Longrightarrow> openin (subtopology euclidean S) {x. x \\<in> S \\<and> f x \\<in> T} \\<longleftrightarrow>\n                    openin (subtopology euclidean (f ` S)) T\"\n    shows \"locally connected (f ` S)\"\nproof (clarsimp simp: locally_connected_open_component)\n  fix U C\n  assume opefSU: \"openin (subtopology euclidean (f ` S)) U\" and \"C \\<in> components U\"\n  then have \"C \\<subseteq> U\" \"U \\<subseteq> f ` S\"\n    by (meson in_components_subset openin_imp_subset)+\n  then have \"openin (subtopology euclidean (f ` S)) C \\<longleftrightarrow>\n             openin (subtopology euclidean S) {x \\<in> S. f x \\<in> C}\"\n    by (auto simp: oo)\n  moreover have \"openin (subtopology euclidean S) {x \\<in> S. f x \\<in> C}\"\n  proof (subst openin_subopen, clarify)\n    fix x\n    assume \"x \\<in> S\" \"f x \\<in> C\"\n    show \"\\<exists>T. openin (subtopology euclidean S) T \\<and> x \\<in> T \\<and> T \\<subseteq> {x \\<in> S. f x \\<in> C}\"\n    proof (intro conjI exI)\n      show \"openin (subtopology euclidean S) (connected_component_set {w \\<in> S. f w \\<in> U} x)\"\n      proof (rule ccontr)\n        assume **: \"\\<not> openin (subtopology euclidean S) (connected_component_set {a \\<in> S. f a \\<in> U} x)\"\n        then have \"x \\<notin> {a \\<in> S. f a \\<in> U}\"\n          using \\<open>U \\<subseteq> f ` S\\<close> opefSU lcS locally_connected_2 oo by blast\n        with ** show False\n          by (metis (no_types) connected_component_eq_empty empty_iff openin_subopen)\n      qed\n    next\n      show \"x \\<in> connected_component_set {w \\<in> S. f w \\<in> U} x\"\n        using \\<open>C \\<subseteq> U\\<close> \\<open>f x \\<in> C\\<close> \\<open>x \\<in> S\\<close> by auto\n    next\n      have contf: \"continuous_on S f\"\n        by (simp add: continuous_on_open oo openin_imp_subset)\n      then have \"continuous_on (connected_component_set {w \\<in> S. f w \\<in> U} x) f\"\n        apply (rule continuous_on_subset)\n        using connected_component_subset apply blast\n        done\n      then have \"connected (f ` connected_component_set {w \\<in> S. f w \\<in> U} x)\"\n        by (rule connected_continuous_image [OF _ connected_connected_component])\n      moreover have \"f ` connected_component_set {w \\<in> S. f w \\<in> U} x \\<subseteq> U\"\n        using connected_component_in by blast\n      moreover have \"C \\<inter> f ` connected_component_set {w \\<in> S. f w \\<in> U} x \\<noteq> {}\"\n        using \\<open>C \\<subseteq> U\\<close> \\<open>f x \\<in> C\\<close> \\<open>x \\<in> S\\<close> by fastforce\n      ultimately have fC: \"f ` (connected_component_set {w \\<in> S. f w \\<in> U} x) \\<subseteq> C\"\n        by (rule components_maximal [OF \\<open>C \\<in> components U\\<close>])\n      have cUC: \"connected_component_set {a \\<in> S. f a \\<in> U} x \\<subseteq> {a \\<in> S. f a \\<in> C}\"\n        using connected_component_subset fC by blast\n      have \"connected_component_set {w \\<in> S. f w \\<in> U} x \\<subseteq> connected_component_set {w \\<in> S. f w \\<in> C} x\"\n      proof -\n        { assume \"x \\<in> connected_component_set {a \\<in> S. f a \\<in> U} x\"\n          then have ?thesis\n            by (simp add: cUC connected_component_maximal) }\n        then show ?thesis\n          using connected_component_eq_empty by auto\n      qed\n      also have \"... \\<subseteq> {w \\<in> S. f w \\<in> C}\"\n        by (rule connected_component_subset)\n      finally show \"connected_component_set {w \\<in> S. f w \\<in> U} x \\<subseteq> {x \\<in> S. f x \\<in> C}\" .\n    qed\n  qed\n  ultimately show \"openin (subtopology euclidean (f ` S)) C\"\n    by metis\nqed\n\ntext\\<open>The proof resembles that above but is not identical!\\<close>\nproposition locally_path_connected_quotient_image:\n  assumes lcS: \"locally path_connected S\"\n      and oo: \"\\<And>T. T \\<subseteq> f ` S\n                \\<Longrightarrow> openin (subtopology euclidean S) {x. x \\<in> S \\<and> f x \\<in> T} \\<longleftrightarrow>\n                    openin (subtopology euclidean (f ` S)) T\"\n    shows \"locally path_connected (f ` S)\"\nproof (clarsimp simp: locally_path_connected_open_path_component)\n  fix U y\n  assume opefSU: \"openin (subtopology euclidean (f ` S)) U\" and \"y \\<in> U\"\n  then have \"path_component_set U y \\<subseteq> U\" \"U \\<subseteq> f ` S\"\n    by (meson path_component_subset openin_imp_subset)+\n  then have \"openin (subtopology euclidean (f ` S)) (path_component_set U y) \\<longleftrightarrow>\n             openin (subtopology euclidean S) {x \\<in> S. f x \\<in> path_component_set U y}\"\n  proof -\n    have \"path_component_set U y \\<subseteq> f ` S\"\n      using \\<open>U \\<subseteq> f ` S\\<close> \\<open>path_component_set U y \\<subseteq> U\\<close> by blast\n    then show ?thesis\n      using oo by blast\n  qed\n  moreover have \"openin (subtopology euclidean S) {x \\<in> S. f x \\<in> path_component_set U y}\"\n  proof (subst openin_subopen, clarify)\n    fix x\n    assume \"x \\<in> S\" and Uyfx: \"path_component U y (f x)\"\n    then have \"f x \\<in> U\"\n      using path_component_mem by blast\n    show \"\\<exists>T. openin (subtopology euclidean S) T \\<and> x \\<in> T \\<and> T \\<subseteq> {x \\<in> S. f x \\<in> path_component_set U y}\"\n    proof (intro conjI exI)\n      show \"openin (subtopology euclidean S) (path_component_set {w \\<in> S. f w \\<in> U} x)\"\n      proof (rule ccontr)\n        assume **: \"\\<not> openin (subtopology euclidean S) (path_component_set {a \\<in> S. f a \\<in> U} x)\"\n        then have \"x \\<notin> {a \\<in> S. f a \\<in> U}\"\n          by (metis (no_types, lifting) \\<open>U \\<subseteq> f ` S\\<close> opefSU lcS oo locally_path_connected_open_path_component)\n        then show False\n          using ** \\<open>path_component_set U y \\<subseteq> U\\<close>  \\<open>x \\<in> S\\<close> \\<open>path_component U y (f x)\\<close> by blast\n      qed\n    next\n      show \"x \\<in> path_component_set {w \\<in> S. f w \\<in> U} x\"\n        by (metis (no_types, lifting) \\<open>x \\<in> S\\<close> IntD2 Int_Collect \\<open>path_component U y (f x)\\<close> path_component_mem(2) path_component_refl)\n    next\n      have contf: \"continuous_on S f\"\n        by (simp add: continuous_on_open oo openin_imp_subset)\n      then have \"continuous_on (path_component_set {w \\<in> S. f w \\<in> U} x) f\"\n        apply (rule continuous_on_subset)\n        using path_component_subset apply blast\n        done\n      then have \"path_connected (f ` path_component_set {w \\<in> S. f w \\<in> U} x)\"\n        by (simp add: path_connected_continuous_image path_connected_path_component)\n      moreover have \"f ` path_component_set {w \\<in> S. f w \\<in> U} x \\<subseteq> U\"\n        using path_component_mem by fastforce\n      moreover have \"f x \\<in> f ` path_component_set {w \\<in> S. f w \\<in> U} x\"\n        by (force simp: \\<open>x \\<in> S\\<close> \\<open>f x \\<in> U\\<close> path_component_refl_eq)\n      ultimately have \"f ` (path_component_set {w \\<in> S. f w \\<in> U} x) \\<subseteq> path_component_set U (f x)\"\n        by (meson path_component_maximal)\n       also have  \"... \\<subseteq> path_component_set U y\"\n        by (simp add: Uyfx path_component_maximal path_component_subset path_component_sym path_connected_path_component)\n      finally have fC: \"f ` (path_component_set {w \\<in> S. f w \\<in> U} x) \\<subseteq> path_component_set U y\" .\n      have cUC: \"path_component_set {a \\<in> S. f a \\<in> U} x \\<subseteq> {a \\<in> S. f a \\<in> path_component_set U y}\"\n        using path_component_subset fC by blast\n      have \"path_component_set {w \\<in> S. f w \\<in> U} x \\<subseteq> path_component_set {w \\<in> S. f w \\<in> path_component_set U y} x\"\n      proof -\n        have \"\\<And>a. path_component_set (path_component_set {a \\<in> S. f a \\<in> U} x) a \\<subseteq> path_component_set {a \\<in> S. f a \\<in> path_component_set U y} a\"\n          using cUC path_component_mono by blast\n        then show ?thesis\n          using path_component_path_component by blast\n      qed\n      also have \"... \\<subseteq> {w \\<in> S. f w \\<in> path_component_set U y}\"\n        by (rule path_component_subset)\n      finally show \"path_component_set {w \\<in> S. f w \\<in> U} x \\<subseteq> {x \\<in> S. f x \\<in> path_component_set U y}\" .\n    qed\n  qed\n  ultimately show \"openin (subtopology euclidean (f ` S)) (path_component_set U y)\"\n    by metis\nqed\n\nsubsection\\<open>Components, continuity, openin, closedin\\<close>\n\nlemma continuous_on_components_gen:\n fixes f :: \"'a::topological_space \\<Rightarrow> 'b::topological_space\"\n  assumes \"\\<And>c. c \\<in> components S \\<Longrightarrow>\n              openin (subtopology euclidean S) c \\<and> continuous_on c f\"\n    shows \"continuous_on S f\"\nproof (clarsimp simp: continuous_openin_preimage_eq)\n  fix t :: \"'b set\"\n  assume \"open t\"\n  have \"{x. x \\<in> S \\<and> f x \\<in> t} = \\<Union>{{x. x \\<in> c \\<and> f x \\<in> t} |c. c \\<in> components S}\"\n    apply auto\n    apply (metis (lifting) components_iff connected_component_refl_eq mem_Collect_eq)\n    using Union_components by blast\n  then show \"openin (subtopology euclidean S) {x \\<in> S. f x \\<in> t}\"\n    using \\<open>open t\\<close> assms\n    by (fastforce intro: openin_trans continuous_openin_preimage_gen)\nqed\n\nlemma continuous_on_components:\n fixes f :: \"'a::topological_space \\<Rightarrow> 'b::topological_space\"\n  assumes \"locally connected S \"\n          \"\\<And>c. c \\<in> components S \\<Longrightarrow> continuous_on c f\"\n    shows \"continuous_on S f\"\napply (rule continuous_on_components_gen)\napply (auto simp: assms intro: openin_components_locally_connected)\ndone\n\nlemma continuous_on_components_eq:\n    \"locally connected S\n     \\<Longrightarrow> (continuous_on S f \\<longleftrightarrow> (\\<forall>c \\<in> components S. continuous_on c f))\"\nby (meson continuous_on_components continuous_on_subset in_components_subset)\n\nlemma continuous_on_components_open:\n fixes S :: \"'a::real_normed_vector set\"\n  assumes \"open S \"\n          \"\\<And>c. c \\<in> components S \\<Longrightarrow> continuous_on c f\"\n    shows \"continuous_on S f\"\nusing continuous_on_components open_imp_locally_connected assms by blast\n\nlemma continuous_on_components_open_eq:\n  fixes S :: \"'a::real_normed_vector set\"\n  shows \"open S \\<Longrightarrow> (continuous_on S f \\<longleftrightarrow> (\\<forall>c \\<in> components S. continuous_on c f))\"\nusing continuous_on_subset in_components_subset\nby (blast intro: continuous_on_components_open)\n\nlemma closedin_union_complement_components:\n  assumes u: \"locally connected u\"\n      and S: \"closedin (subtopology euclidean u) S\"\n      and cuS: \"c \\<subseteq> components(u - S)\"\n    shows \"closedin (subtopology euclidean u) (S \\<union> \\<Union>c)\"\nproof -\n  have di: \"(\\<And>S t. S \\<in> c \\<and> t \\<in> c' \\<Longrightarrow> disjnt S t) \\<Longrightarrow> disjnt (\\<Union> c) (\\<Union> c')\" for c'\n    by (simp add: disjnt_def) blast\n  have \"S \\<subseteq> u\"\n    using S closedin_imp_subset by blast\n  moreover have \"u - S = \\<Union>c \\<union> \\<Union>(components (u - S) - c)\"\n    by (metis Diff_partition Topology_Euclidean_Space.Union_components Union_Un_distrib assms(3))\n  moreover have \"disjnt (\\<Union>c) (\\<Union>(components (u - S) - c))\"\n    apply (rule di)\n    by (metis DiffD1 DiffD2 assms(3) components_nonoverlap disjnt_def subsetCE)\n  ultimately have eq: \"S \\<union> \\<Union>c = u - (\\<Union>(components(u - S) - c))\"\n    by (auto simp: disjnt_def)\n  have *: \"openin (subtopology euclidean u) (\\<Union>(components (u - S) - c))\"\n    apply (rule openin_Union)\n    apply (rule openin_trans [of \"u - S\"])\n    apply (simp add: u S locally_diff_closed openin_components_locally_connected)\n    apply (simp add: openin_diff S)\n    done\n  have \"openin (subtopology euclidean u) (u - (u - \\<Union>(components (u - S) - c)))\"\n    apply (rule openin_diff, simp)\n    apply (metis closedin_diff closedin_topspace topspace_euclidean_subtopology *)\n    done\n  then show ?thesis\n    by (force simp: eq closedin_def)\nqed\n\nlemma closed_union_complement_components:\n  fixes S :: \"'a::real_normed_vector set\"\n  assumes S: \"closed S\" and c: \"c \\<subseteq> components(- S)\"\n    shows \"closed(S \\<union> \\<Union> c)\"\nproof -\n  have \"closedin (subtopology euclidean UNIV) (S \\<union> \\<Union>c)\"\n    apply (rule closedin_union_complement_components [OF locally_connected_UNIV])\n    using S apply (simp add: closed_closedin)\n    using c apply (simp add: Compl_eq_Diff_UNIV)\n    done\n  then show ?thesis\n    by (simp add: closed_closedin)\nqed\n\nlemma closedin_Un_complement_component:\n  fixes S :: \"'a::real_normed_vector set\"\n  assumes u: \"locally connected u\"\n      and S: \"closedin (subtopology euclidean u) S\"\n      and c: \" c \\<in> components(u - S)\"\n    shows \"closedin (subtopology euclidean u) (S \\<union> c)\"\nproof -\n  have \"closedin (subtopology euclidean u) (S \\<union> \\<Union>{c})\"\n    using c by (blast intro: closedin_union_complement_components [OF u S])\n  then show ?thesis\n    by simp\nqed\n\nlemma closed_Un_complement_component:\n  fixes S :: \"'a::real_normed_vector set\"\n  assumes S: \"closed S\" and c: \" c \\<in> components(-S)\"\n    shows \"closed (S \\<union> c)\"\nby (metis Compl_eq_Diff_UNIV S c closed_closedin closedin_Un_complement_component locally_connected_UNIV subtopology_UNIV)\n\n\nsubsection\\<open>Existence of isometry between subspaces of same dimension\\<close>\n\nlemma isometry_subset_subspace:\n  fixes S :: \"'a::euclidean_space set\"\n    and T :: \"'b::euclidean_space set\"\n  assumes S: \"subspace S\"\n      and T: \"subspace T\"\n      and d: \"dim S \\<le> dim T\"\n  obtains f where \"linear f\" \"f ` S \\<subseteq> T\" \"\\<And>x. x \\<in> S \\<Longrightarrow> norm(f x) = norm x\"\nproof -\n  obtain B where \"B \\<subseteq> S\" and Borth: \"pairwise orthogonal B\"\n             and B1: \"\\<And>x. x \\<in> B \\<Longrightarrow> norm x = 1\"\n             and \"independent B\" \"finite B\" \"card B = dim S\" \"span B = S\"\n    by (metis orthonormal_basis_subspace [OF S] independent_finite)\n  obtain C where \"C \\<subseteq> T\" and Corth: \"pairwise orthogonal C\"\n             and C1:\"\\<And>x. x \\<in> C \\<Longrightarrow> norm x = 1\"\n             and \"independent C\" \"finite C\" \"card C = dim T\" \"span C = T\"\n    by (metis orthonormal_basis_subspace [OF T] independent_finite)\n  obtain fb where \"fb ` B \\<subseteq> C\" \"inj_on fb B\"\n    by (metis \\<open>card B = dim S\\<close> \\<open>card C = dim T\\<close> \\<open>finite B\\<close> \\<open>finite C\\<close> card_le_inj d)\n  then have pairwise_orth_fb: \"pairwise (\\<lambda>v j. orthogonal (fb v) (fb j)) B\"\n    using Corth\n    apply (auto simp: pairwise_def orthogonal_clauses)\n    by (meson subsetD image_eqI inj_on_def)\n  obtain f where \"linear f\" and ffb: \"\\<And>x. x \\<in> B \\<Longrightarrow> f x = fb x\"\n    using linear_independent_extend \\<open>independent B\\<close> by fastforce\n  have \"f ` S \\<subseteq> T\"\n    by (metis ffb \\<open>fb ` B \\<subseteq> C\\<close> \\<open>linear f\\<close> \\<open>span B = S\\<close> \\<open>span C = T\\<close> image_cong span_linear_image span_mono)\n  have [simp]: \"\\<And>x. x \\<in> B \\<Longrightarrow> norm (fb x) = norm x\"\n    using B1 C1 \\<open>fb ` B \\<subseteq> C\\<close> by auto\n  have \"norm (f x) = norm x\" if \"x \\<in> S\" for x\n  proof -\n    obtain a where x: \"x = (\\<Sum>v \\<in> B. a v *\\<^sub>R v)\"\n      using \\<open>finite B\\<close> \\<open>span B = S\\<close> \\<open>x \\<in> S\\<close> span_finite by fastforce\n    have \"f x = (\\<Sum>v \\<in> B. f (a v *\\<^sub>R v))\"\n      using linear_sum [OF \\<open>linear f\\<close>] x by auto\n    also have \"... = (\\<Sum>v \\<in> B. a v *\\<^sub>R f v)\"\n      using \\<open>linear f\\<close> by (simp add: linear_sum linear.scaleR)\n    also have \"... = (\\<Sum>v \\<in> B. a v *\\<^sub>R fb v)\"\n      by (simp add: ffb cong: sum.cong)\n    finally have \"norm (f x)^2 = norm (\\<Sum>v\\<in>B. a v *\\<^sub>R fb v)^2\" by simp\n    also have \"... = (\\<Sum>v\\<in>B. norm ((a v *\\<^sub>R fb v))^2)\"\n      apply (rule norm_sum_Pythagorean [OF \\<open>finite B\\<close>])\n      apply (rule pairwise_ortho_scaleR [OF pairwise_orth_fb])\n      done\n    also have \"... = norm x ^2\"\n      by (simp add: x pairwise_ortho_scaleR Borth norm_sum_Pythagorean [OF \\<open>finite B\\<close>])\n    finally show ?thesis\n      by (simp add: norm_eq_sqrt_inner)\n  qed\n  then show ?thesis\n    by (rule that [OF \\<open>linear f\\<close> \\<open>f ` S \\<subseteq> T\\<close>])\nqed\n\nproposition isometries_subspaces:\n  fixes S :: \"'a::euclidean_space set\"\n    and T :: \"'b::euclidean_space set\"\n  assumes S: \"subspace S\"\n      and T: \"subspace T\"\n      and d: \"dim S = dim T\"\n  obtains f g where \"linear f\" \"linear g\" \"f ` S = T\" \"g ` T = S\"\n                    \"\\<And>x. x \\<in> S \\<Longrightarrow> norm(f x) = norm x\"\n                    \"\\<And>x. x \\<in> T \\<Longrightarrow> norm(g x) = norm x\"\n                    \"\\<And>x. x \\<in> S \\<Longrightarrow> g(f x) = x\"\n                    \"\\<And>x. x \\<in> T \\<Longrightarrow> f(g x) = x\"\nproof -\n  obtain B where \"B \\<subseteq> S\" and Borth: \"pairwise orthogonal B\"\n             and B1: \"\\<And>x. x \\<in> B \\<Longrightarrow> norm x = 1\"\n             and \"independent B\" \"finite B\" \"card B = dim S\" \"span B = S\"\n    by (metis orthonormal_basis_subspace [OF S] independent_finite)\n  obtain C where \"C \\<subseteq> T\" and Corth: \"pairwise orthogonal C\"\n             and C1:\"\\<And>x. x \\<in> C \\<Longrightarrow> norm x = 1\"\n             and \"independent C\" \"finite C\" \"card C = dim T\" \"span C = T\"\n    by (metis orthonormal_basis_subspace [OF T] independent_finite)\n  obtain fb where \"bij_betw fb B C\"\n    by (metis \\<open>finite B\\<close> \\<open>finite C\\<close> bij_betw_iff_card \\<open>card B = dim S\\<close> \\<open>card C = dim T\\<close> d)\n  then have pairwise_orth_fb: \"pairwise (\\<lambda>v j. orthogonal (fb v) (fb j)) B\"\n    using Corth\n    apply (auto simp: pairwise_def orthogonal_clauses bij_betw_def)\n    by (meson subsetD image_eqI inj_on_def)\n  obtain f where \"linear f\" and ffb: \"\\<And>x. x \\<in> B \\<Longrightarrow> f x = fb x\"\n    using linear_independent_extend \\<open>independent B\\<close> by fastforce\n  define gb where \"gb \\<equiv> inv_into B fb\"\n  then have pairwise_orth_gb: \"pairwise (\\<lambda>v j. orthogonal (gb v) (gb j)) C\"\n    using Borth\n    apply (auto simp: pairwise_def orthogonal_clauses bij_betw_def)\n    by (metis \\<open>bij_betw fb B C\\<close> bij_betw_imp_surj_on bij_betw_inv_into_right inv_into_into)\n  obtain g where \"linear g\" and ggb: \"\\<And>x. x \\<in> C \\<Longrightarrow> g x = gb x\"\n    using linear_independent_extend \\<open>independent C\\<close> by fastforce\n  have \"f ` S \\<subseteq> T\"\n    by (metis \\<open>bij_betw fb B C\\<close> bij_betw_imp_surj_on eq_iff ffb  \\<open>linear f\\<close> \\<open>span B = S\\<close> \\<open>span C = T\\<close> image_cong span_linear_image)\n  have [simp]: \"\\<And>x. x \\<in> B \\<Longrightarrow> norm (fb x) = norm x\"\n    using B1 C1 \\<open>bij_betw fb B C\\<close> bij_betw_imp_surj_on by fastforce\n  have f [simp]: \"norm (f x) = norm x\" \"g (f x) = x\" if \"x \\<in> S\" for x\n  proof -\n    obtain a where x: \"x = (\\<Sum>v \\<in> B. a v *\\<^sub>R v)\"\n      using \\<open>finite B\\<close> \\<open>span B = S\\<close> \\<open>x \\<in> S\\<close> span_finite by fastforce\n    have \"f x = (\\<Sum>v \\<in> B. f (a v *\\<^sub>R v))\"\n      using linear_sum [OF \\<open>linear f\\<close>] x by auto\n    also have \"... = (\\<Sum>v \\<in> B. a v *\\<^sub>R f v)\"\n      using \\<open>linear f\\<close> by (simp add: linear_sum linear.scaleR)\n    also have \"... = (\\<Sum>v \\<in> B. a v *\\<^sub>R fb v)\"\n      by (simp add: ffb cong: sum.cong)\n    finally have *: \"f x = (\\<Sum>v\\<in>B. a v *\\<^sub>R fb v)\" .\n    then have \"(norm (f x))\\<^sup>2 = (norm (\\<Sum>v\\<in>B. a v *\\<^sub>R fb v))\\<^sup>2\" by simp\n    also have \"... = (\\<Sum>v\\<in>B. norm ((a v *\\<^sub>R fb v))^2)\"\n      apply (rule norm_sum_Pythagorean [OF \\<open>finite B\\<close>])\n      apply (rule pairwise_ortho_scaleR [OF pairwise_orth_fb])\n      done\n    also have \"... = (norm x)\\<^sup>2\"\n      by (simp add: x pairwise_ortho_scaleR Borth norm_sum_Pythagorean [OF \\<open>finite B\\<close>])\n    finally show \"norm (f x) = norm x\"\n      by (simp add: norm_eq_sqrt_inner)\n    have \"g (f x) = g (\\<Sum>v\\<in>B. a v *\\<^sub>R fb v)\" by (simp add: *)\n    also have \"... = (\\<Sum>v\\<in>B. g (a v *\\<^sub>R fb v))\"\n      using \\<open>linear g\\<close> by (simp add: linear_sum linear.scaleR)\n    also have \"... = (\\<Sum>v\\<in>B. a v *\\<^sub>R g (fb v))\"\n      by (simp add: \\<open>linear g\\<close> linear.scaleR)\n    also have \"... = (\\<Sum>v\\<in>B. a v *\\<^sub>R v)\"\n      apply (rule sum.cong [OF refl])\n      using \\<open>bij_betw fb B C\\<close> gb_def bij_betwE bij_betw_inv_into_left gb_def ggb by fastforce\n    also have \"... = x\"\n      using x by blast\n    finally show \"g (f x) = x\" .\n  qed\n  have [simp]: \"\\<And>x. x \\<in> C \\<Longrightarrow> norm (gb x) = norm x\"\n    by (metis B1 C1 \\<open>bij_betw fb B C\\<close> bij_betw_imp_surj_on gb_def inv_into_into)\n  have g [simp]: \"f (g x) = x\" if \"x \\<in> T\" for x\n  proof -\n    obtain a where x: \"x = (\\<Sum>v \\<in> C. a v *\\<^sub>R v)\"\n      using \\<open>finite C\\<close> \\<open>span C = T\\<close> \\<open>x \\<in> T\\<close> span_finite by fastforce\n    have \"g x = (\\<Sum>v \\<in> C. g (a v *\\<^sub>R v))\"\n      using linear_sum [OF \\<open>linear g\\<close>] x by auto\n    also have \"... = (\\<Sum>v \\<in> C. a v *\\<^sub>R g v)\"\n      using \\<open>linear g\\<close> by (simp add: linear_sum linear.scaleR)\n    also have \"... = (\\<Sum>v \\<in> C. a v *\\<^sub>R gb v)\"\n      by (simp add: ggb cong: sum.cong)\n    finally have \"f (g x) = f (\\<Sum>v\\<in>C. a v *\\<^sub>R gb v)\" by simp\n    also have \"... = (\\<Sum>v\\<in>C. f (a v *\\<^sub>R gb v))\"\n      using \\<open>linear f\\<close> by (simp add: linear_sum linear.scaleR)\n    also have \"... = (\\<Sum>v\\<in>C. a v *\\<^sub>R f (gb v))\"\n      by (simp add: \\<open>linear f\\<close> linear.scaleR)\n    also have \"... = (\\<Sum>v\\<in>C. a v *\\<^sub>R v)\"\n      using \\<open>bij_betw fb B C\\<close>\n      by (simp add: bij_betw_def gb_def bij_betw_inv_into_right ffb inv_into_into)\n    also have \"... = x\"\n      using x by blast\n    finally show \"f (g x) = x\" .\n  qed\n  have gim: \"g ` T = S\"\n    by (metis (no_types, lifting) \\<open>f ` S \\<subseteq> T\\<close> \\<open>linear g\\<close> \\<open>span B = S\\<close> \\<open>span C = T\\<close> d dim_eq_span dim_image_le f(2) image_subset_iff span_linear_image span_span subsetI)\n  have fim: \"f ` S = T\"\n    using \\<open>g ` T = S\\<close> image_iff by fastforce\n  have [simp]: \"norm (g x) = norm x\" if \"x \\<in> T\" for x\n    using fim that by auto\n  show ?thesis\n    apply (rule that [OF \\<open>linear f\\<close> \\<open>linear g\\<close>])\n    apply (simp_all add: fim gim)\n    done\nqed\n\ncorollary isometry_subspaces:\n  fixes S :: \"'a::euclidean_space set\"\n    and T :: \"'b::euclidean_space set\"\n  assumes S: \"subspace S\"\n      and T: \"subspace T\"\n      and d: \"dim S = dim T\"\n  obtains f where \"linear f\" \"f ` S = T\" \"\\<And>x. x \\<in> S \\<Longrightarrow> norm(f x) = norm x\"\nusing isometries_subspaces [OF assms]\nby metis\n\ncorollary isomorphisms_UNIV_UNIV:\n  assumes \"DIM('M) = DIM('N)\"\n  obtains f::\"'M::euclidean_space \\<Rightarrow>'N::euclidean_space\" and g\n  where \"linear f\" \"linear g\"\n                    \"\\<And>x. norm(f x) = norm x\" \"\\<And>y. norm(g y) = norm y\"\n                    \"\\<And>x. g(f x) = x\" \"\\<And>y. f(g y) = y\"\n  using assms by (auto simp: dim_UNIV intro: isometries_subspaces [of \"UNIV::'M set\" \"UNIV::'N set\"])\n\nlemma homeomorphic_subspaces:\n  fixes S :: \"'a::euclidean_space set\"\n    and T :: \"'b::euclidean_space set\"\n  assumes S: \"subspace S\"\n      and T: \"subspace T\"\n      and d: \"dim S = dim T\"\n    shows \"S homeomorphic T\"\nproof -\n  obtain f g where \"linear f\" \"linear g\" \"f ` S = T\" \"g ` T = S\"\n                   \"\\<And>x. x \\<in> S \\<Longrightarrow> g(f x) = x\" \"\\<And>x. x \\<in> T \\<Longrightarrow> f(g x) = x\"\n    by (blast intro: isometries_subspaces [OF assms])\n  then show ?thesis\n    apply (simp add: homeomorphic_def homeomorphism_def)\n    apply (rule_tac x=f in exI)\n    apply (rule_tac x=g in exI)\n    apply (auto simp: linear_continuous_on linear_conv_bounded_linear)\n    done\nqed\n\nlemma homeomorphic_affine_sets:\n  assumes \"affine S\" \"affine T\" \"aff_dim S = aff_dim T\"\n    shows \"S homeomorphic T\"\nproof (cases \"S = {} \\<or> T = {}\")\n  case True  with assms aff_dim_empty homeomorphic_empty show ?thesis\n    by metis\nnext\n  case False\n  then obtain a b where ab: \"a \\<in> S\" \"b \\<in> T\" by auto\n  then have ss: \"subspace (op + (- a) ` S)\" \"subspace (op + (- b) ` T)\"\n    using affine_diffs_subspace assms by blast+\n  have dd: \"dim (op + (- a) ` S) = dim (op + (- b) ` T)\"\n    using assms ab  by (simp add: aff_dim_eq_dim  [OF hull_inc] image_def)\n  have \"S homeomorphic (op + (- a) ` S)\"\n    by (simp add: homeomorphic_translation)\n  also have \"... homeomorphic (op + (- b) ` T)\"\n    by (rule homeomorphic_subspaces [OF ss dd])\n  also have \"... homeomorphic T\"\n    using homeomorphic_sym homeomorphic_translation by auto\n  finally show ?thesis .\nqed\n\nsubsection\\<open>Retracts, in a general sense, preserve (co)homotopic triviality)\\<close>\n\nlocale Retracts =\n  fixes s h t k\n  assumes conth: \"continuous_on s h\"\n      and imh: \"h ` s = t\"\n      and contk: \"continuous_on t k\"\n      and imk: \"k ` t \\<subseteq> s\"\n      and idhk: \"\\<And>y. y \\<in> t \\<Longrightarrow> h(k y) = y\"\n\nbegin\n\nlemma homotopically_trivial_retraction_gen:\n  assumes P: \"\\<And>f. \\<lbrakk>continuous_on u f; f ` u \\<subseteq> t; Q f\\<rbrakk> \\<Longrightarrow> P(k o f)\"\n      and Q: \"\\<And>f. \\<lbrakk>continuous_on u f; f ` u \\<subseteq> s; P f\\<rbrakk> \\<Longrightarrow> Q(h o f)\"\n      and Qeq: \"\\<And>h k. (\\<And>x. x \\<in> u \\<Longrightarrow> h x = k x) \\<Longrightarrow> Q h = Q k\"\n      and hom: \"\\<And>f g. \\<lbrakk>continuous_on u f; f ` u \\<subseteq> s; P f;\n                       continuous_on u g; g ` u \\<subseteq> s; P g\\<rbrakk>\n                       \\<Longrightarrow> homotopic_with P u s f g\"\n      and contf: \"continuous_on u f\" and imf: \"f ` u \\<subseteq> t\" and Qf: \"Q f\"\n      and contg: \"continuous_on u g\" and img: \"g ` u \\<subseteq> t\" and Qg: \"Q g\"\n    shows \"homotopic_with Q u t f g\"\nproof -\n  have feq: \"\\<And>x. x \\<in> u \\<Longrightarrow> (h \\<circ> (k \\<circ> f)) x = f x\" using idhk imf by auto\n  have geq: \"\\<And>x. x \\<in> u \\<Longrightarrow> (h \\<circ> (k \\<circ> g)) x = g x\" using idhk img by auto\n  have \"continuous_on u (k \\<circ> f)\"\n    using contf continuous_on_compose continuous_on_subset contk imf by blast\n  moreover have \"(k \\<circ> f) ` u \\<subseteq> s\"\n    using imf imk by fastforce\n  moreover have \"P (k \\<circ> f)\"\n    by (simp add: P Qf contf imf)\n  moreover have \"continuous_on u (k \\<circ> g)\"\n    using contg continuous_on_compose continuous_on_subset contk img by blast\n  moreover have \"(k \\<circ> g) ` u \\<subseteq> s\"\n    using img imk by fastforce\n  moreover have \"P (k \\<circ> g)\"\n    by (simp add: P Qg contg img)\n  ultimately have \"homotopic_with P u s (k \\<circ> f) (k \\<circ> g)\"\n    by (rule hom)\n  then have \"homotopic_with Q u t (h \\<circ> (k \\<circ> f)) (h \\<circ> (k \\<circ> g))\"\n    apply (rule homotopic_with_compose_continuous_left [OF homotopic_with_mono])\n    using Q by (auto simp: conth imh)\n  then show ?thesis\n    apply (rule homotopic_with_eq)\n    apply (metis feq)\n    apply (metis geq)\n    apply (metis Qeq)\n    done\nqed\n\nlemma homotopically_trivial_retraction_null_gen:\n  assumes P: \"\\<And>f. \\<lbrakk>continuous_on u f; f ` u \\<subseteq> t; Q f\\<rbrakk> \\<Longrightarrow> P(k o f)\"\n      and Q: \"\\<And>f. \\<lbrakk>continuous_on u f; f ` u \\<subseteq> s; P f\\<rbrakk> \\<Longrightarrow> Q(h o f)\"\n      and Qeq: \"\\<And>h k. (\\<And>x. x \\<in> u \\<Longrightarrow> h x = k x) \\<Longrightarrow> Q h = Q k\"\n      and hom: \"\\<And>f. \\<lbrakk>continuous_on u f; f ` u \\<subseteq> s; P f\\<rbrakk>\n                     \\<Longrightarrow> \\<exists>c. homotopic_with P u s f (\\<lambda>x. c)\"\n      and contf: \"continuous_on u f\" and imf:\"f ` u \\<subseteq> t\" and Qf: \"Q f\"\n  obtains c where \"homotopic_with Q u t f (\\<lambda>x. c)\"\nproof -\n  have feq: \"\\<And>x. x \\<in> u \\<Longrightarrow> (h \\<circ> (k \\<circ> f)) x = f x\" using idhk imf by auto\n  have \"continuous_on u (k \\<circ> f)\"\n    using contf continuous_on_compose continuous_on_subset contk imf by blast\n  moreover have \"(k \\<circ> f) ` u \\<subseteq> s\"\n    using imf imk by fastforce\n  moreover have \"P (k \\<circ> f)\"\n    by (simp add: P Qf contf imf)\n  ultimately obtain c where \"homotopic_with P u s (k \\<circ> f) (\\<lambda>x. c)\"\n    by (metis hom)\n  then have \"homotopic_with Q u t (h \\<circ> (k \\<circ> f)) (h o (\\<lambda>x. c))\"\n    apply (rule homotopic_with_compose_continuous_left [OF homotopic_with_mono])\n    using Q by (auto simp: conth imh)\n  then show ?thesis\n    apply (rule_tac c = \"h c\" in that)\n    apply (erule homotopic_with_eq)\n    apply (metis feq, simp)\n    apply (metis Qeq)\n    done\nqed\n\nlemma cohomotopically_trivial_retraction_gen:\n  assumes P: \"\\<And>f. \\<lbrakk>continuous_on t f; f ` t \\<subseteq> u; Q f\\<rbrakk> \\<Longrightarrow> P(f o h)\"\n      and Q: \"\\<And>f. \\<lbrakk>continuous_on s f; f ` s \\<subseteq> u; P f\\<rbrakk> \\<Longrightarrow> Q(f o k)\"\n      and Qeq: \"\\<And>h k. (\\<And>x. x \\<in> t \\<Longrightarrow> h x = k x) \\<Longrightarrow> Q h = Q k\"\n      and hom: \"\\<And>f g. \\<lbrakk>continuous_on s f; f ` s \\<subseteq> u; P f;\n                       continuous_on s g; g ` s \\<subseteq> u; P g\\<rbrakk>\n                       \\<Longrightarrow> homotopic_with P s u f g\"\n      and contf: \"continuous_on t f\" and imf: \"f ` t \\<subseteq> u\" and Qf: \"Q f\"\n      and contg: \"continuous_on t g\" and img: \"g ` t \\<subseteq> u\" and Qg: \"Q g\"\n    shows \"homotopic_with Q t u f g\"\nproof -\n  have feq: \"\\<And>x. x \\<in> t \\<Longrightarrow> (f \\<circ> h \\<circ> k) x = f x\" using idhk imf by auto\n  have geq: \"\\<And>x. x \\<in> t \\<Longrightarrow> (g \\<circ> h \\<circ> k) x = g x\" using idhk img by auto\n  have \"continuous_on s (f \\<circ> h)\"\n    using contf conth continuous_on_compose imh by blast\n  moreover have \"(f \\<circ> h) ` s \\<subseteq> u\"\n    using imf imh by fastforce\n  moreover have \"P (f \\<circ> h)\"\n    by (simp add: P Qf contf imf)\n  moreover have \"continuous_on s (g o h)\"\n    using contg continuous_on_compose continuous_on_subset conth imh by blast\n  moreover have \"(g \\<circ> h) ` s \\<subseteq> u\"\n    using img imh by fastforce\n  moreover have \"P (g \\<circ> h)\"\n    by (simp add: P Qg contg img)\n  ultimately have \"homotopic_with P s u (f o h) (g \\<circ> h)\"\n    by (rule hom)\n  then have \"homotopic_with Q t u (f o h o k) (g \\<circ> h o k)\"\n    apply (rule homotopic_with_compose_continuous_right [OF homotopic_with_mono])\n    using Q by (auto simp: contk imk)\n  then show ?thesis\n    apply (rule homotopic_with_eq)\n    apply (metis feq)\n    apply (metis geq)\n    apply (metis Qeq)\n    done\nqed\n\nlemma cohomotopically_trivial_retraction_null_gen:\n  assumes P: \"\\<And>f. \\<lbrakk>continuous_on t f; f ` t \\<subseteq> u; Q f\\<rbrakk> \\<Longrightarrow> P(f o h)\"\n      and Q: \"\\<And>f. \\<lbrakk>continuous_on s f; f ` s \\<subseteq> u; P f\\<rbrakk> \\<Longrightarrow> Q(f o k)\"\n      and Qeq: \"\\<And>h k. (\\<And>x. x \\<in> t \\<Longrightarrow> h x = k x) \\<Longrightarrow> Q h = Q k\"\n      and hom: \"\\<And>f g. \\<lbrakk>continuous_on s f; f ` s \\<subseteq> u; P f\\<rbrakk>\n                       \\<Longrightarrow> \\<exists>c. homotopic_with P s u f (\\<lambda>x. c)\"\n      and contf: \"continuous_on t f\" and imf: \"f ` t \\<subseteq> u\" and Qf: \"Q f\"\n  obtains c where \"homotopic_with Q t u f (\\<lambda>x. c)\"\nproof -\n  have feq: \"\\<And>x. x \\<in> t \\<Longrightarrow> (f \\<circ> h \\<circ> k) x = f x\" using idhk imf by auto\n  have \"continuous_on s (f \\<circ> h)\"\n    using contf conth continuous_on_compose imh by blast\n  moreover have \"(f \\<circ> h) ` s \\<subseteq> u\"\n    using imf imh by fastforce\n  moreover have \"P (f \\<circ> h)\"\n    by (simp add: P Qf contf imf)\n  ultimately obtain c where \"homotopic_with P s u (f o h) (\\<lambda>x. c)\"\n    by (metis hom)\n  then have \"homotopic_with Q t u (f o h o k) ((\\<lambda>x. c) o k)\"\n    apply (rule homotopic_with_compose_continuous_right [OF homotopic_with_mono])\n    using Q by (auto simp: contk imk)\n  then show ?thesis\n    apply (rule_tac c = c in that)\n    apply (erule homotopic_with_eq)\n    apply (metis feq, simp)\n    apply (metis Qeq)\n    done\nqed\n\nend\n\nlemma simply_connected_retraction_gen:\n  shows \"\\<lbrakk>simply_connected S; continuous_on S h; h ` S = T;\n          continuous_on T k; k ` T \\<subseteq> S; \\<And>y. y \\<in> T \\<Longrightarrow> h(k y) = y\\<rbrakk>\n        \\<Longrightarrow> simply_connected T\"\napply (simp add: simply_connected_def path_def path_image_def homotopic_loops_def, clarify)\napply (rule Retracts.homotopically_trivial_retraction_gen\n        [of S h _ k _ \"\\<lambda>p. pathfinish p = pathstart p\"  \"\\<lambda>p. pathfinish p = pathstart p\"])\napply (simp_all add: Retracts_def pathfinish_def pathstart_def)\ndone\n\nlemma homeomorphic_simply_connected:\n    \"\\<lbrakk>S homeomorphic T; simply_connected S\\<rbrakk> \\<Longrightarrow> simply_connected T\"\n  by (auto simp: homeomorphic_def homeomorphism_def intro: simply_connected_retraction_gen)\n\nlemma homeomorphic_simply_connected_eq:\n    \"S homeomorphic T \\<Longrightarrow> (simply_connected S \\<longleftrightarrow> simply_connected T)\"\n  by (metis homeomorphic_simply_connected homeomorphic_sym)\n\nsubsection\\<open>Homotopy equivalence\\<close>\n\ndefinition homotopy_eqv :: \"'a::topological_space set \\<Rightarrow> 'b::topological_space set \\<Rightarrow> bool\"\n             (infix \"homotopy'_eqv\" 50)\n  where \"S homotopy_eqv T \\<equiv>\n        \\<exists>f g. continuous_on S f \\<and> f ` S \\<subseteq> T \\<and>\n              continuous_on T g \\<and> g ` T \\<subseteq> S \\<and>\n              homotopic_with (\\<lambda>x. True) S S (g o f) id \\<and>\n              homotopic_with (\\<lambda>x. True) T T (f o g) id\"\n\nlemma homeomorphic_imp_homotopy_eqv: \"S homeomorphic T \\<Longrightarrow> S homotopy_eqv T\"\n  unfolding homeomorphic_def homotopy_eqv_def homeomorphism_def\n  by (fastforce intro!: homotopic_with_equal continuous_on_compose)\n\nlemma homotopy_eqv_refl: \"S homotopy_eqv S\"\n  by (rule homeomorphic_imp_homotopy_eqv homeomorphic_refl)+\n\nlemma homotopy_eqv_sym: \"S homotopy_eqv T \\<longleftrightarrow> T homotopy_eqv S\"\n  by (auto simp: homotopy_eqv_def)\n\nlemma homotopy_eqv_trans [trans]:\n    fixes S :: \"'a::real_normed_vector set\" and U :: \"'c::real_normed_vector set\"\n  assumes ST: \"S homotopy_eqv T\" and TU: \"T homotopy_eqv U\"\n    shows \"S homotopy_eqv U\"\nproof -\n  obtain f1 g1 where f1: \"continuous_on S f1\" \"f1 ` S \\<subseteq> T\"\n                 and g1: \"continuous_on T g1\" \"g1 ` T \\<subseteq> S\"\n                 and hom1: \"homotopic_with (\\<lambda>x. True) S S (g1 o f1) id\"\n                           \"homotopic_with (\\<lambda>x. True) T T (f1 o g1) id\"\n    using ST by (auto simp: homotopy_eqv_def)\n  obtain f2 g2 where f2: \"continuous_on T f2\" \"f2 ` T \\<subseteq> U\"\n                 and g2: \"continuous_on U g2\" \"g2 ` U \\<subseteq> T\"\n                 and hom2: \"homotopic_with (\\<lambda>x. True) T T (g2 o f2) id\"\n                           \"homotopic_with (\\<lambda>x. True) U U (f2 o g2) id\"\n    using TU by (auto simp: homotopy_eqv_def)\n  have \"homotopic_with (\\<lambda>f. True) S T (g2 \\<circ> f2 \\<circ> f1) (id \\<circ> f1)\"\n    by (rule homotopic_with_compose_continuous_right hom2 f1)+\n  then have \"homotopic_with (\\<lambda>f. True) S T (g2 \\<circ> (f2 \\<circ> f1)) (id \\<circ> f1)\"\n    by (simp add: o_assoc)\n  then have \"homotopic_with (\\<lambda>x. True) S S\n         (g1 \\<circ> (g2 \\<circ> (f2 \\<circ> f1))) (g1 o (id o f1))\"\n    by (simp add: g1 homotopic_with_compose_continuous_left)\n  moreover have \"homotopic_with (\\<lambda>x. True) S S (g1 o id o f1) id\"\n    using hom1 by simp\n  ultimately have SS: \"homotopic_with (\\<lambda>x. True) S S (g1 \\<circ> g2 \\<circ> (f2 \\<circ> f1)) id\"\n    apply (simp add: o_assoc)\n    apply (blast intro: homotopic_with_trans)\n    done\n  have \"homotopic_with (\\<lambda>f. True) U T (f1 \\<circ> g1 \\<circ> g2) (id \\<circ> g2)\"\n    by (rule homotopic_with_compose_continuous_right hom1 g2)+\n  then have \"homotopic_with (\\<lambda>f. True) U T (f1 \\<circ> (g1 \\<circ> g2)) (id \\<circ> g2)\"\n    by (simp add: o_assoc)\n  then have \"homotopic_with (\\<lambda>x. True) U U\n         (f2 \\<circ> (f1 \\<circ> (g1 \\<circ> g2))) (f2 o (id o g2))\"\n    by (simp add: f2 homotopic_with_compose_continuous_left)\n  moreover have \"homotopic_with (\\<lambda>x. True) U U (f2 o id o g2) id\"\n    using hom2 by simp\n  ultimately have UU: \"homotopic_with (\\<lambda>x. True) U U (f2 \\<circ> f1 \\<circ> (g1 \\<circ> g2)) id\"\n    apply (simp add: o_assoc)\n    apply (blast intro: homotopic_with_trans)\n    done\n  show ?thesis\n    unfolding homotopy_eqv_def\n    apply (rule_tac x = \"f2 \\<circ> f1\" in exI)\n    apply (rule_tac x = \"g1 \\<circ> g2\" in exI)\n    apply (intro conjI continuous_on_compose SS UU)\n    using f1 f2 g1 g2  apply (force simp: elim!: continuous_on_subset)+\n    done\nqed\n\nlemma homotopy_eqv_inj_linear_image:\n  fixes f :: \"'a::euclidean_space \\<Rightarrow> 'b::euclidean_space\"\n  assumes \"linear f\" \"inj f\"\n    shows \"(f ` S) homotopy_eqv S\"\napply (rule homeomorphic_imp_homotopy_eqv)\nusing assms homeomorphic_sym linear_homeomorphic_image by auto\n\nlemma homotopy_eqv_translation:\n    fixes S :: \"'a::real_normed_vector set\"\n    shows \"op + a ` S homotopy_eqv S\"\n  apply (rule homeomorphic_imp_homotopy_eqv)\n  using homeomorphic_translation homeomorphic_sym by blast\n\nlemma homotopy_eqv_homotopic_triviality_imp:\n  fixes S :: \"'a::real_normed_vector set\"\n    and T :: \"'b::real_normed_vector set\"\n    and U :: \"'c::real_normed_vector set\"\n  assumes \"S homotopy_eqv T\"\n      and f: \"continuous_on U f\" \"f ` U \\<subseteq> T\"\n      and g: \"continuous_on U g\" \"g ` U \\<subseteq> T\"\n      and homUS: \"\\<And>f g. \\<lbrakk>continuous_on U f; f ` U \\<subseteq> S;\n                         continuous_on U g; g ` U \\<subseteq> S\\<rbrakk>\n                         \\<Longrightarrow> homotopic_with (\\<lambda>x. True) U S f g\"\n    shows \"homotopic_with (\\<lambda>x. True) U T f g\"\nproof -\n  obtain h k where h: \"continuous_on S h\" \"h ` S \\<subseteq> T\"\n               and k: \"continuous_on T k\" \"k ` T \\<subseteq> S\"\n               and hom: \"homotopic_with (\\<lambda>x. True) S S (k o h) id\"\n                        \"homotopic_with (\\<lambda>x. True) T T (h o k) id\"\n    using assms by (auto simp: homotopy_eqv_def)\n  have \"homotopic_with (\\<lambda>f. True) U S (k \\<circ> f) (k \\<circ> g)\"\n    apply (rule homUS)\n    using f g k\n    apply (safe intro!: continuous_on_compose h k f elim!: continuous_on_subset)\n    apply (force simp: o_def)+\n    done\n  then have \"homotopic_with (\\<lambda>x. True) U T (h o (k o f)) (h o (k o g))\"\n    apply (rule homotopic_with_compose_continuous_left)\n    apply (simp_all add: h)\n    done\n  moreover have \"homotopic_with (\\<lambda>x. True) U T (h o k o f) (id o f)\"\n    apply (rule homotopic_with_compose_continuous_right [where X=T and Y=T])\n    apply (auto simp: hom f)\n    done\n  moreover have \"homotopic_with (\\<lambda>x. True) U T (h o k o g) (id o g)\"\n    apply (rule homotopic_with_compose_continuous_right [where X=T and Y=T])\n    apply (auto simp: hom g)\n    done\n  ultimately show \"homotopic_with (\\<lambda>x. True) U T f g\"\n    apply (simp add: o_assoc)\n    using homotopic_with_trans homotopic_with_sym by blast\nqed\n\nlemma homotopy_eqv_homotopic_triviality:\n  fixes S :: \"'a::real_normed_vector set\"\n    and T :: \"'b::real_normed_vector set\"\n    and U :: \"'c::real_normed_vector set\"\n  assumes \"S homotopy_eqv T\"\n    shows \"(\\<forall>f g. continuous_on U f \\<and> f ` U \\<subseteq> S \\<and>\n                   continuous_on U g \\<and> g ` U \\<subseteq> S\n                   \\<longrightarrow> homotopic_with (\\<lambda>x. True) U S f g) \\<longleftrightarrow>\n           (\\<forall>f g. continuous_on U f \\<and> f ` U \\<subseteq> T \\<and>\n                  continuous_on U g \\<and> g ` U \\<subseteq> T\n                  \\<longrightarrow> homotopic_with (\\<lambda>x. True) U T f g)\"\napply (rule iffI)\napply (metis assms homotopy_eqv_homotopic_triviality_imp)\nby (metis (no_types) assms homotopy_eqv_homotopic_triviality_imp homotopy_eqv_sym)\n\nlemma homotopy_eqv_cohomotopic_triviality_null_imp:\n  fixes S :: \"'a::real_normed_vector set\"\n    and T :: \"'b::real_normed_vector set\"\n    and U :: \"'c::real_normed_vector set\"\n  assumes \"S homotopy_eqv T\"\n      and f: \"continuous_on T f\" \"f ` T \\<subseteq> U\"\n      and homSU: \"\\<And>f. \\<lbrakk>continuous_on S f; f ` S \\<subseteq> U\\<rbrakk>\n                      \\<Longrightarrow> \\<exists>c. homotopic_with (\\<lambda>x. True) S U f (\\<lambda>x. c)\"\n  obtains c where \"homotopic_with (\\<lambda>x. True) T U f (\\<lambda>x. c)\"\nproof -\n  obtain h k where h: \"continuous_on S h\" \"h ` S \\<subseteq> T\"\n               and k: \"continuous_on T k\" \"k ` T \\<subseteq> S\"\n               and hom: \"homotopic_with (\\<lambda>x. True) S S (k o h) id\"\n                        \"homotopic_with (\\<lambda>x. True) T T (h o k) id\"\n    using assms by (auto simp: homotopy_eqv_def)\n  obtain c where \"homotopic_with (\\<lambda>x. True) S U (f \\<circ> h) (\\<lambda>x. c)\"\n    apply (rule exE [OF homSU [of \"f \\<circ> h\"]])\n    apply (intro continuous_on_compose h)\n    using h f  apply (force elim!: continuous_on_subset)+\n    done\n  then have \"homotopic_with (\\<lambda>x. True) T U ((f o h) o k) ((\\<lambda>x. c) o k)\"\n    apply (rule homotopic_with_compose_continuous_right [where X=S])\n    using k by auto\n  moreover have \"homotopic_with (\\<lambda>x. True) T U (f \\<circ> id) (f \\<circ> (h \\<circ> k))\"\n    apply (rule homotopic_with_compose_continuous_left [where Y=T])\n      apply (simp add: hom homotopic_with_symD)\n     using f apply auto\n    done\n  ultimately show ?thesis\n    apply (rule_tac c=c in that)\n    apply (simp add: o_def)\n    using homotopic_with_trans by blast\nqed\n\nlemma homotopy_eqv_cohomotopic_triviality_null:\n  fixes S :: \"'a::real_normed_vector set\"\n    and T :: \"'b::real_normed_vector set\"\n    and U :: \"'c::real_normed_vector set\"\n  assumes \"S homotopy_eqv T\"\n    shows \"(\\<forall>f. continuous_on S f \\<and> f ` S \\<subseteq> U\n                \\<longrightarrow> (\\<exists>c. homotopic_with (\\<lambda>x. True) S U f (\\<lambda>x. c))) \\<longleftrightarrow>\n           (\\<forall>f. continuous_on T f \\<and> f ` T \\<subseteq> U\n                \\<longrightarrow> (\\<exists>c. homotopic_with (\\<lambda>x. True) T U f (\\<lambda>x. c)))\"\napply (rule iffI)\napply (metis assms homotopy_eqv_cohomotopic_triviality_null_imp)\nby (metis assms homotopy_eqv_cohomotopic_triviality_null_imp homotopy_eqv_sym)\n\nlemma homotopy_eqv_homotopic_triviality_null_imp:\n  fixes S :: \"'a::real_normed_vector set\"\n    and T :: \"'b::real_normed_vector set\"\n    and U :: \"'c::real_normed_vector set\"\n  assumes \"S homotopy_eqv T\"\n      and f: \"continuous_on U f\" \"f ` U \\<subseteq> T\"\n      and homSU: \"\\<And>f. \\<lbrakk>continuous_on U f; f ` U \\<subseteq> S\\<rbrakk>\n                      \\<Longrightarrow> \\<exists>c. homotopic_with (\\<lambda>x. True) U S f (\\<lambda>x. c)\"\n    shows \"\\<exists>c. homotopic_with (\\<lambda>x. True) U T f (\\<lambda>x. c)\"\nproof -\n  obtain h k where h: \"continuous_on S h\" \"h ` S \\<subseteq> T\"\n               and k: \"continuous_on T k\" \"k ` T \\<subseteq> S\"\n               and hom: \"homotopic_with (\\<lambda>x. True) S S (k \\<circ> h) id\"\n                        \"homotopic_with (\\<lambda>x. True) T T (h \\<circ> k) id\"\n    using assms by (auto simp: homotopy_eqv_def)\n  obtain c::'a where \"homotopic_with (\\<lambda>x. True) U S (k \\<circ> f) (\\<lambda>x. c)\"\n    apply (rule exE [OF homSU [of \"k \\<circ> f\"]])\n    apply (intro continuous_on_compose h)\n    using k f  apply (force elim!: continuous_on_subset)+\n    done\n  then have \"homotopic_with (\\<lambda>x. True) U T (h \\<circ> (k \\<circ> f)) (h \\<circ> (\\<lambda>x. c))\"\n    apply (rule homotopic_with_compose_continuous_left [where Y=S])\n    using h by auto\n  moreover have \"homotopic_with (\\<lambda>x. True) U T (id \\<circ> f) ((h \\<circ> k) \\<circ> f)\"\n    apply (rule homotopic_with_compose_continuous_right [where X=T])\n      apply (simp add: hom homotopic_with_symD)\n     using f apply auto\n    done\n  ultimately show ?thesis\n    using homotopic_with_trans by (fastforce simp add: o_def)\nqed\n\nlemma homotopy_eqv_homotopic_triviality_null:\n  fixes S :: \"'a::real_normed_vector set\"\n    and T :: \"'b::real_normed_vector set\"\n    and U :: \"'c::real_normed_vector set\"\n  assumes \"S homotopy_eqv T\"\n    shows \"(\\<forall>f. continuous_on U f \\<and> f ` U \\<subseteq> S\n                  \\<longrightarrow> (\\<exists>c. homotopic_with (\\<lambda>x. True) U S f (\\<lambda>x. c))) \\<longleftrightarrow>\n           (\\<forall>f. continuous_on U f \\<and> f ` U \\<subseteq> T\n                  \\<longrightarrow> (\\<exists>c. homotopic_with (\\<lambda>x. True) U T f (\\<lambda>x. c)))\"\napply (rule iffI)\napply (metis assms homotopy_eqv_homotopic_triviality_null_imp)\nby (metis assms homotopy_eqv_homotopic_triviality_null_imp homotopy_eqv_sym)\n\nlemma homotopy_eqv_contractible_sets:\n  fixes S :: \"'a::real_normed_vector set\"\n    and T :: \"'b::real_normed_vector set\"\n  assumes \"contractible S\" \"contractible T\" \"S = {} \\<longleftrightarrow> T = {}\"\n    shows \"S homotopy_eqv T\"\nproof (cases \"S = {}\")\n  case True with assms show ?thesis\n    by (simp add: homeomorphic_imp_homotopy_eqv)\nnext\n  case False\n  with assms obtain a b where \"a \\<in> S\" \"b \\<in> T\"\n    by auto\n  then show ?thesis\n    unfolding homotopy_eqv_def\n    apply (rule_tac x=\"\\<lambda>x. b\" in exI)\n    apply (rule_tac x=\"\\<lambda>x. a\" in exI)\n    apply (intro assms conjI continuous_on_id' homotopic_into_contractible)\n    apply (auto simp: o_def continuous_on_const)\n    done\nqed\n\nlemma homotopy_eqv_empty1 [simp]:\n  fixes S :: \"'a::real_normed_vector set\"\n  shows \"S homotopy_eqv ({}::'b::real_normed_vector set) \\<longleftrightarrow> S = {}\"\napply (rule iffI)\nusing homotopy_eqv_def apply fastforce\nby (simp add: homotopy_eqv_contractible_sets contractible_empty)\n\nlemma homotopy_eqv_empty2 [simp]:\n  fixes S :: \"'a::real_normed_vector set\"\n  shows \"({}::'b::real_normed_vector set) homotopy_eqv S \\<longleftrightarrow> S = {}\"\nby (metis homotopy_eqv_empty1 homotopy_eqv_sym)\n\nlemma homotopy_eqv_contractibility:\n  fixes S :: \"'a::real_normed_vector set\" and T :: \"'b::real_normed_vector set\"\n  shows \"S homotopy_eqv T \\<Longrightarrow> (contractible S \\<longleftrightarrow> contractible T)\"\nunfolding homotopy_eqv_def\nby (blast intro: homotopy_dominated_contractibility)\n\nlemma homotopy_eqv_sing:\n  fixes S :: \"'a::real_normed_vector set\" and a :: \"'b::real_normed_vector\"\n  shows \"S homotopy_eqv {a} \\<longleftrightarrow> S \\<noteq> {} \\<and> contractible S\"\nproof (cases \"S = {}\")\n  case True then show ?thesis\n    by simp\nnext\n  case False then show ?thesis\n    by (metis contractible_sing empty_not_insert homotopy_eqv_contractibility homotopy_eqv_contractible_sets)\nqed\n\nlemma homeomorphic_contractible_eq:\n  fixes S :: \"'a::real_normed_vector set\" and T :: \"'b::real_normed_vector set\"\n  shows \"S homeomorphic T \\<Longrightarrow> (contractible S \\<longleftrightarrow> contractible T)\"\nby (simp add: homeomorphic_imp_homotopy_eqv homotopy_eqv_contractibility)\n\nlemma homeomorphic_contractible:\n  fixes S :: \"'a::real_normed_vector set\" and T :: \"'b::real_normed_vector set\"\n  shows \"\\<lbrakk>contractible S; S homeomorphic T\\<rbrakk> \\<Longrightarrow> contractible T\"\n  by (metis homeomorphic_contractible_eq)\n\nsubsection\\<open>Misc other results\\<close>\n\nlemma bounded_connected_Compl_real:\n  fixes S :: \"real set\"\n  assumes \"bounded S\" and conn: \"connected(- S)\"\n    shows \"S = {}\"\nproof -\n  obtain a b where \"S \\<subseteq> box a b\"\n    by (meson assms bounded_subset_open_interval)\n  then have \"a \\<notin> S\" \"b \\<notin> S\"\n    by auto\n  then have \"\\<forall>x. a \\<le> x \\<and> x \\<le> b \\<longrightarrow> x \\<in> - S\"\n    by (meson Compl_iff conn connected_iff_interval)\n  then show ?thesis\n    using \\<open>S \\<subseteq> box a b\\<close> by auto\nqed\n\nlemma bounded_connected_Compl_1:\n  fixes S :: \"'a::{euclidean_space} set\"\n  assumes \"bounded S\" and conn: \"connected(- S)\" and 1: \"DIM('a) = 1\"\n    shows \"S = {}\"\nproof -\n  have \"DIM('a) = DIM(real)\"\n    by (simp add: \"1\")\n  then obtain f::\"'a \\<Rightarrow> real\" and g\n  where \"linear f\" \"\\<And>x. norm(f x) = norm x\" \"\\<And>x. g(f x) = x\" \"\\<And>y. f(g y) = y\"\n    by (rule isomorphisms_UNIV_UNIV) blast\n  with \\<open>bounded S\\<close> have \"bounded (f ` S)\"\n    using bounded_linear_image linear_linear by blast\n  have \"connected (f ` (-S))\"\n    using connected_linear_image assms \\<open>linear f\\<close> by blast\n  moreover have \"f ` (-S) = - (f ` S)\"\n    apply (rule bij_image_Compl_eq)\n    apply (auto simp: bij_def)\n     apply (metis \\<open>\\<And>x. g (f x) = x\\<close> injI)\n    by (metis UNIV_I \\<open>\\<And>y. f (g y) = y\\<close> image_iff)\n  finally have \"connected (- (f ` S))\"\n    by simp\n  then have \"f ` S = {}\"\n    using \\<open>bounded (f ` S)\\<close> bounded_connected_Compl_real by blast\n  then show ?thesis\n    by blast\nqed\n\nsubsection\\<open>Some Uncountable Sets\\<close>\n\nlemma uncountable_closed_segment:\n  fixes a :: \"'a::real_normed_vector\"\n  assumes \"a \\<noteq> b\" shows \"uncountable (closed_segment a b)\"\nunfolding path_image_linepath [symmetric] path_image_def\n  using inj_on_linepath [OF assms] uncountable_closed_interval [of 0 1]\n        countable_image_inj_on by auto\n\nlemma uncountable_open_segment:\n  fixes a :: \"'a::real_normed_vector\"\n  assumes \"a \\<noteq> b\" shows \"uncountable (open_segment a b)\"\n  by (simp add: assms open_segment_def uncountable_closed_segment uncountable_minus_countable)\n\nlemma uncountable_convex:\n  fixes a :: \"'a::real_normed_vector\"\n  assumes \"convex S\" \"a \\<in> S\" \"b \\<in> S\" \"a \\<noteq> b\"\n    shows \"uncountable S\"\nproof -\n  have \"uncountable (closed_segment a b)\"\n    by (simp add: uncountable_closed_segment assms)\n  then show ?thesis\n    by (meson assms convex_contains_segment countable_subset)\nqed\n\nlemma uncountable_ball:\n  fixes a :: \"'a::euclidean_space\"\n  assumes \"r > 0\"\n    shows \"uncountable (ball a r)\"\nproof -\n  have \"uncountable (open_segment a (a + r *\\<^sub>R (SOME i. i \\<in> Basis)))\"\n    by (metis Basis_zero SOME_Basis add_cancel_right_right assms less_le real_vector.scale_eq_0_iff uncountable_open_segment)\n  moreover have \"open_segment a (a + r *\\<^sub>R (SOME i. i \\<in> Basis)) \\<subseteq> ball a r\"\n    using assms by (auto simp: in_segment algebra_simps dist_norm SOME_Basis)\n  ultimately show ?thesis\n    by (metis countable_subset)\nqed\n\nlemma uncountable_cball:\n  fixes a :: \"'a::euclidean_space\"\n  assumes \"r > 0\"\n  shows \"uncountable (cball a r)\"\n  using assms countable_subset uncountable_ball by auto\n\nlemma pairwise_disjnt_countable:\n  fixes \\<N> :: \"nat set set\"\n  assumes \"pairwise disjnt \\<N>\"\n    shows \"countable \\<N>\"\nproof -\n  have \"inj_on (\\<lambda>X. SOME n. n \\<in> X) (\\<N> - {{}})\"\n    apply (clarsimp simp add: inj_on_def)\n    by (metis assms disjnt_insert2 insert_absorb pairwise_def subsetI subset_empty tfl_some)\n  then show ?thesis\n    by (metis countable_Diff_eq countable_def)\nqed\n\nlemma pairwise_disjnt_countable_Union:\n    assumes \"countable (\\<Union>\\<N>)\" and pwd: \"pairwise disjnt \\<N>\"\n    shows \"countable \\<N>\"\nproof -\n  obtain f :: \"_ \\<Rightarrow> nat\" where f: \"inj_on f (\\<Union>\\<N>)\"\n    using assms by blast\n  then have \"pairwise disjnt (\\<Union> X \\<in> \\<N>. {f ` X})\"\n    using assms by (force simp: pairwise_def disjnt_inj_on_iff [OF f])\n  then have \"countable (\\<Union> X \\<in> \\<N>. {f ` X})\"\n    using pairwise_disjnt_countable by blast\n  then show ?thesis\n    by (meson pwd countable_image_inj_on disjoint_image f inj_on_image pairwise_disjnt_countable)\nqed\n\n\nsubsection\\<open> Some simple positive connection theorems\\<close>\n\nproposition path_connected_convex_diff_countable:\n  fixes U :: \"'a::euclidean_space set\"\n  assumes \"convex U\" \"~ collinear U\" \"countable S\"\n    shows \"path_connected(U - S)\"\nproof (clarsimp simp add: path_connected_def)\n  fix a b\n  assume \"a \\<in> U\" \"a \\<notin> S\" \"b \\<in> U\" \"b \\<notin> S\"\n  let ?m = \"midpoint a b\"\n  show \"\\<exists>g. path g \\<and> path_image g \\<subseteq> U - S \\<and> pathstart g = a \\<and> pathfinish g = b\"\n  proof (cases \"a = b\")\n    case True\n    then show ?thesis\n      by (metis DiffI \\<open>a \\<in> U\\<close> \\<open>a \\<notin> S\\<close> path_component_def path_component_refl)\n  next\n    case False\n    then have \"a \\<noteq> ?m\" \"b \\<noteq> ?m\"\n      using midpoint_eq_endpoint by fastforce+\n    have \"?m \\<in> U\"\n      using \\<open>a \\<in> U\\<close> \\<open>b \\<in> U\\<close> \\<open>convex U\\<close> convex_contains_segment by force\n    obtain c where \"c \\<in> U\" and nc_abc: \"\\<not> collinear {a,b,c}\"\n      by (metis False \\<open>a \\<in> U\\<close> \\<open>b \\<in> U\\<close> \\<open>~ collinear U\\<close> collinear_triples insert_absorb)\n    have ncoll_mca: \"\\<not> collinear {?m,c,a}\"\n      by (metis (full_types) \\<open>a \\<noteq> ?m\\<close> collinear_3_trans collinear_midpoint insert_commute nc_abc)\n    have ncoll_mcb: \"\\<not> collinear {?m,c,b}\"\n      by (metis (full_types) \\<open>b \\<noteq> ?m\\<close> collinear_3_trans collinear_midpoint insert_commute nc_abc)\n    have \"c \\<noteq> ?m\"\n      by (metis collinear_midpoint insert_commute nc_abc)\n    then have \"closed_segment ?m c \\<subseteq> U\"\n      by (simp add: \\<open>c \\<in> U\\<close> \\<open>?m \\<in> U\\<close> \\<open>convex U\\<close> closed_segment_subset)\n    then obtain z where z: \"z \\<in> closed_segment ?m c\"\n                    and disjS: \"(closed_segment a z \\<union> closed_segment z b) \\<inter> S = {}\"\n    proof -\n      have False if \"closed_segment ?m c \\<subseteq> {z. (closed_segment a z \\<union> closed_segment z b) \\<inter> S \\<noteq> {}}\"\n      proof -\n        have closb: \"closed_segment ?m c \\<subseteq>\n                 {z \\<in> closed_segment ?m c. closed_segment a z \\<inter> S \\<noteq> {}} \\<union> {z \\<in> closed_segment ?m c. closed_segment z b \\<inter> S \\<noteq> {}}\"\n          using that by blast\n        have *: \"countable {z \\<in> closed_segment ?m c. closed_segment z u \\<inter> S \\<noteq> {}}\"\n          if \"u \\<in> U\" \"u \\<notin> S\" and ncoll: \"\\<not> collinear {?m, c, u}\" for u\n        proof -\n          have **: False if x1: \"x1 \\<in> closed_segment ?m c\" and x2: \"x2 \\<in> closed_segment ?m c\"\n                            and \"x1 \\<noteq> x2\" \"x1 \\<noteq> u\"\n                            and w: \"w \\<in> closed_segment x1 u\" \"w \\<in> closed_segment x2 u\"\n                            and \"w \\<in> S\" for x1 x2 w\n          proof -\n            have \"x1 \\<in> affine hull {?m,c}\" \"x2 \\<in> affine hull {?m,c}\"\n              using segment_as_ball x1 x2 by auto\n            then have coll_x1: \"collinear {x1, ?m, c}\" and coll_x2: \"collinear {?m, c, x2}\"\n              by (simp_all add: affine_hull_3_imp_collinear) (metis affine_hull_3_imp_collinear insert_commute)\n            have \"\\<not> collinear {x1, u, x2}\"\n            proof\n              assume \"collinear {x1, u, x2}\"\n              then have \"collinear {?m, c, u}\"\n                by (metis (full_types) \\<open>c \\<noteq> ?m\\<close> coll_x1 coll_x2 collinear_3_trans insert_commute ncoll \\<open>x1 \\<noteq> x2\\<close>)\n              with ncoll show False ..\n            qed\n            then have \"closed_segment x1 u \\<inter> closed_segment u x2 = {u}\"\n              by (blast intro!: Int_closed_segment)\n            then have \"w = u\"\n              using closed_segment_commute w by auto\n            show ?thesis\n              using \\<open>u \\<notin> S\\<close> \\<open>w = u\\<close> that(7) by auto\n          qed\n          then have disj: \"disjoint ((\\<Union>z\\<in>closed_segment ?m c. {closed_segment z u \\<inter> S}))\"\n            by (fastforce simp: pairwise_def disjnt_def)\n          have cou: \"countable ((\\<Union>z \\<in> closed_segment ?m c. {closed_segment z u \\<inter> S}) - {{}})\"\n            apply (rule pairwise_disjnt_countable_Union [OF _ pairwise_subset [OF disj]])\n             apply (rule countable_subset [OF _ \\<open>countable S\\<close>], auto)\n            done\n          define f where \"f \\<equiv> \\<lambda>X. (THE z. z \\<in> closed_segment ?m c \\<and> X = closed_segment z u \\<inter> S)\"\n          show ?thesis\n          proof (rule countable_subset [OF _ countable_image [OF cou, where f=f]], clarify)\n            fix x\n            assume x: \"x \\<in> closed_segment ?m c\" \"closed_segment x u \\<inter> S \\<noteq> {}\"\n            show \"x \\<in> f ` ((\\<Union>z\\<in>closed_segment ?m c. {closed_segment z u \\<inter> S}) - {{}})\"\n            proof (rule_tac x=\"closed_segment x u \\<inter> S\" in image_eqI)\n              show \"x = f (closed_segment x u \\<inter> S)\"\n                unfolding f_def\n                apply (rule the_equality [symmetric])\n                using x  apply (auto simp: dest: **)\n                done\n            qed (use x in auto)\n          qed\n        qed\n        have \"uncountable (closed_segment ?m c)\"\n          by (metis \\<open>c \\<noteq> ?m\\<close> uncountable_closed_segment)\n        then show False\n          using closb * [OF \\<open>a \\<in> U\\<close> \\<open>a \\<notin> S\\<close> ncoll_mca] * [OF \\<open>b \\<in> U\\<close> \\<open>b \\<notin> S\\<close> ncoll_mcb]\n          apply (simp add: closed_segment_commute)\n          by (simp add: countable_subset)\n      qed\n      then show ?thesis\n        by (force intro: that)\n    qed\n    show ?thesis\n    proof (intro exI conjI)\n      have \"path_image (linepath a z +++ linepath z b) \\<subseteq> U\"\n        by (metis \\<open>a \\<in> U\\<close> \\<open>b \\<in> U\\<close> \\<open>closed_segment ?m c \\<subseteq> U\\<close> z \\<open>convex U\\<close> closed_segment_subset contra_subsetD path_image_linepath subset_path_image_join)\n      with disjS show \"path_image (linepath a z +++ linepath z b) \\<subseteq> U - S\"\n        by (force simp: path_image_join)\n    qed auto\n  qed\nqed\n\n\ncorollary connected_convex_diff_countable:\n  fixes U :: \"'a::euclidean_space set\"\n  assumes \"convex U\" \"~ collinear U\" \"countable S\"\n  shows \"connected(U - S)\"\n  by (simp add: assms path_connected_convex_diff_countable path_connected_imp_connected)\n\nlemma path_connected_punctured_convex:\n  assumes \"convex S\" and aff: \"aff_dim S \\<noteq> 1\"\n    shows \"path_connected(S - {a})\"\nproof -\n  consider \"aff_dim S = -1\" | \"aff_dim S = 0\" | \"aff_dim S \\<ge> 2\"\n    using assms aff_dim_geq [of S] by linarith\n  then show ?thesis\n  proof cases\n    assume \"aff_dim S = -1\"\n    then show ?thesis\n      by (metis aff_dim_empty empty_Diff path_connected_empty)\n  next\n    assume \"aff_dim S = 0\"\n    then show ?thesis\n      by (metis aff_dim_eq_0 Diff_cancel Diff_empty Diff_insert0 convex_empty convex_imp_path_connected path_connected_singleton singletonD)\n  next\n    assume ge2: \"aff_dim S \\<ge> 2\"\n    then have \"\\<not> collinear S\"\n    proof (clarsimp simp add: collinear_affine_hull)\n      fix u v\n      assume \"S \\<subseteq> affine hull {u, v}\"\n      then have \"aff_dim S \\<le> aff_dim {u, v}\"\n        by (metis (no_types) aff_dim_affine_hull aff_dim_subset)\n      with ge2 show False\n        by (metis (no_types) aff_dim_2 antisym aff not_numeral_le_zero one_le_numeral order_trans)\n    qed\n    then show ?thesis\n      apply (rule path_connected_convex_diff_countable [OF \\<open>convex S\\<close>])\n      by simp\n  qed\nqed\n\nlemma connected_punctured_convex:\n  shows \"\\<lbrakk>convex S; aff_dim S \\<noteq> 1\\<rbrakk> \\<Longrightarrow> connected(S - {a})\"\n  using path_connected_imp_connected path_connected_punctured_convex by blast\n\nlemma path_connected_complement_countable:\n  fixes S :: \"'a::euclidean_space set\"\n  assumes \"2 \\<le> DIM('a)\" \"countable S\"\n  shows \"path_connected(- S)\"\nproof -\n  have \"path_connected(UNIV - S)\"\n    apply (rule path_connected_convex_diff_countable)\n    using assms by (auto simp: collinear_aff_dim [of \"UNIV :: 'a set\"])\n  then show ?thesis\n    by (simp add: Compl_eq_Diff_UNIV)\nqed\n\nproposition path_connected_openin_diff_countable:\n  fixes S :: \"'a::euclidean_space set\"\n  assumes \"connected S\" and ope: \"openin (subtopology euclidean (affine hull S)) S\"\n      and \"~ collinear S\" \"countable T\"\n    shows \"path_connected(S - T)\"\nproof (clarsimp simp add: path_connected_component)\n  fix x y\n  assume xy: \"x \\<in> S\" \"x \\<notin> T\" \"y \\<in> S\" \"y \\<notin> T\"\n  show \"path_component (S - T) x y\"\n  proof (rule connected_equivalence_relation_gen [OF \\<open>connected S\\<close>, where P = \"\\<lambda>x. x \\<notin> T\"])\n    show \"\\<exists>z. z \\<in> U \\<and> z \\<notin> T\" if opeU: \"openin (subtopology euclidean S) U\" and \"x \\<in> U\" for U x\n    proof -\n      have \"openin (subtopology euclidean (affine hull S)) U\"\n        using opeU ope openin_trans by blast\n      with \\<open>x \\<in> U\\<close> obtain r where Usub: \"U \\<subseteq> affine hull S\" and \"r > 0\"\n                              and subU: \"ball x r \\<inter> affine hull S \\<subseteq> U\"\n        by (auto simp: openin_contains_ball)\n      with \\<open>x \\<in> U\\<close> have x: \"x \\<in> ball x r \\<inter> affine hull S\"\n        by auto\n      have \"~ S \\<subseteq> {x}\"\n        using \\<open>~ collinear S\\<close>  collinear_subset by blast\n      then obtain x' where \"x' \\<noteq> x\" \"x' \\<in> S\"\n        by blast\n      obtain y where y: \"y \\<noteq> x\" \"y \\<in> ball x r \\<inter> affine hull S\"\n      proof\n        show \"x + (r / 2 / norm(x' - x)) *\\<^sub>R (x' - x) \\<noteq> x\"\n          using \\<open>x' \\<noteq> x\\<close> \\<open>r > 0\\<close> by auto\n        show \"x + (r / 2 / norm (x' - x)) *\\<^sub>R (x' - x) \\<in> ball x r \\<inter> affine hull S\"\n          using \\<open>x' \\<noteq> x\\<close> \\<open>r > 0\\<close> \\<open>x' \\<in> S\\<close> x\n          by (simp add: dist_norm mem_affine_3_minus hull_inc)\n      qed\n      have \"convex (ball x r \\<inter> affine hull S)\"\n        by (simp add: affine_imp_convex convex_Int)\n      with x y subU have \"uncountable U\"\n        by (meson countable_subset uncountable_convex)\n      then have \"\\<not> U \\<subseteq> T\"\n        using \\<open>countable T\\<close> countable_subset by blast\n      then show ?thesis by blast\n    qed\n    show \"\\<exists>U. openin (subtopology euclidean S) U \\<and> x \\<in> U \\<and>\n              (\\<forall>x\\<in>U. \\<forall>y\\<in>U. x \\<notin> T \\<and> y \\<notin> T \\<longrightarrow> path_component (S - T) x y)\"\n          if \"x \\<in> S\" for x\n    proof -\n      obtain r where Ssub: \"S \\<subseteq> affine hull S\" and \"r > 0\"\n                 and subS: \"ball x r \\<inter> affine hull S \\<subseteq> S\"\n        using ope \\<open>x \\<in> S\\<close> by (auto simp: openin_contains_ball)\n      then have conv: \"convex (ball x r \\<inter> affine hull S)\"\n        by (simp add: affine_imp_convex convex_Int)\n      have \"\\<not> aff_dim (affine hull S) \\<le> 1\"\n        using \\<open>\\<not> collinear S\\<close> collinear_aff_dim by auto\n      then have \"\\<not> collinear (ball x r \\<inter> affine hull S)\"\n        apply (simp add: collinear_aff_dim)\n        by (metis (no_types, hide_lams) aff_dim_convex_Int_open IntI Topology_Euclidean_Space.open_ball \\<open>0 < r\\<close> aff_dim_affine_hull affine_affine_hull affine_imp_convex centre_in_ball empty_iff hull_subset inf_commute subsetCE that)\n      then have *: \"path_connected ((ball x r \\<inter> affine hull S) - T)\"\n        by (rule path_connected_convex_diff_countable [OF conv _ \\<open>countable T\\<close>])\n      have ST: \"ball x r \\<inter> affine hull S - T \\<subseteq> S - T\"\n        using subS by auto\n      show ?thesis\n      proof (intro exI conjI)\n        show \"x \\<in> ball x r \\<inter> affine hull S\"\n          using \\<open>x \\<in> S\\<close> \\<open>r > 0\\<close> by (simp add: hull_inc)\n        have \"openin (subtopology euclidean (affine hull S)) (ball x r \\<inter> affine hull S)\"\n          by (simp add: inf.commute openin_Int_open)\n        then show \"openin (subtopology euclidean S) (ball x r \\<inter> affine hull S)\"\n          by (rule openin_subset_trans [OF _ subS Ssub])\n      qed (use * path_component_trans in \\<open>auto simp: path_connected_component path_component_of_subset [OF ST]\\<close>)\n    qed\n  qed (use xy path_component_trans in auto)\nqed\n\ncorollary connected_openin_diff_countable:\n  fixes S :: \"'a::euclidean_space set\"\n  assumes \"connected S\" and ope: \"openin (subtopology euclidean (affine hull S)) S\"\n      and \"~ collinear S\" \"countable T\"\n    shows \"connected(S - T)\"\n  by (metis path_connected_imp_connected path_connected_openin_diff_countable [OF assms])\n\ncorollary path_connected_open_diff_countable:\n  fixes S :: \"'a::euclidean_space set\"\n  assumes \"2 \\<le> DIM('a)\" \"open S\" \"connected S\" \"countable T\"\n  shows \"path_connected(S - T)\"\nproof (cases \"S = {}\")\n  case True\n  then show ?thesis\n    by (simp add: path_connected_empty)\nnext\n  case False\n  show ?thesis\n  proof (rule path_connected_openin_diff_countable)\n    show \"openin (subtopology euclidean (affine hull S)) S\"\n      by (simp add: assms hull_subset open_subset)\n    show \"\\<not> collinear S\"\n      using assms False by (simp add: collinear_aff_dim aff_dim_open)\n  qed (simp_all add: assms)\nqed\n\ncorollary connected_open_diff_countable:\n  fixes S :: \"'a::euclidean_space set\"\n  assumes \"2 \\<le> DIM('a)\" \"open S\" \"connected S\" \"countable T\"\n  shows \"connected(S - T)\"\nby (simp add: assms path_connected_imp_connected path_connected_open_diff_countable)\n\n\n\nsubsection\\<open> Self-homeomorphisms shuffling points about in various ways.\\<close>\n\nsubsubsection\\<open>The theorem @{text homeomorphism_moving_points_exists}\\<close>\n\nlemma homeomorphism_moving_point_1:\n  fixes a :: \"'a::euclidean_space\"\n  assumes \"affine T\" \"a \\<in> T\" and u: \"u \\<in> ball a r \\<inter> T\"\n  obtains f g where \"homeomorphism (cball a r \\<inter> T) (cball a r \\<inter> T) f g\"\n                    \"f a = u\" \"\\<And>x. x \\<in> sphere a r \\<Longrightarrow> f x = x\"\nproof -\n  have nou: \"norm (u - a) < r\" and \"u \\<in> T\"\n    using u by (auto simp: dist_norm norm_minus_commute)\n  then have \"0 < r\"\n    by (metis DiffD1 Diff_Diff_Int ball_eq_empty centre_in_ball not_le u)\n  define f where \"f \\<equiv> \\<lambda>x. (1 - norm(x - a) / r) *\\<^sub>R (u - a) + x\"\n  have *: \"False\" if eq: \"x + (norm y / r) *\\<^sub>R u = y + (norm x / r) *\\<^sub>R u\"\n                  and nou: \"norm u < r\" and yx: \"norm y < norm x\" for x y and u::'a\n  proof -\n    have \"x = y + (norm x / r - (norm y / r)) *\\<^sub>R u\"\n      using eq by (simp add: algebra_simps)\n    then have \"norm x = norm (y + ((norm x - norm y) / r) *\\<^sub>R u)\"\n      by (metis diff_divide_distrib)\n    also have \"... \\<le> norm y + norm(((norm x - norm y) / r) *\\<^sub>R u)\"\n      using norm_triangle_ineq by blast\n    also have \"... = norm y + (norm x - norm y) * (norm u / r)\"\n      using yx \\<open>r > 0\\<close>\n      by (simp add: divide_simps)\n    also have \"... < norm y + (norm x - norm y) * 1\"\n      apply (subst add_less_cancel_left)\n      apply (rule mult_strict_left_mono)\n      using nou \\<open>0 < r\\<close> yx\n       apply (simp_all add: field_simps)\n      done\n    also have \"... = norm x\"\n      by simp\n    finally show False by simp\n  qed\n  have \"inj f\"\n    unfolding f_def\n  proof (clarsimp simp: inj_on_def)\n    fix x y\n    assume \"(1 - norm (x - a) / r) *\\<^sub>R (u - a) + x =\n            (1 - norm (y - a) / r) *\\<^sub>R (u - a) + y\"\n    then have eq: \"(x - a) + (norm (y - a) / r) *\\<^sub>R (u - a) = (y - a) + (norm (x - a) / r) *\\<^sub>R (u - a)\"\n      by (auto simp: algebra_simps)\n    show \"x=y\"\n    proof (cases \"norm (x - a) = norm (y - a)\")\n      case True\n      then show ?thesis\n        using eq by auto\n    next\n      case False\n      then consider \"norm (x - a) < norm (y - a)\" | \"norm (x - a) > norm (y - a)\"\n        by linarith\n      then have \"False\"\n      proof cases\n        case 1 show False\n          using * [OF _ nou 1] eq by simp\n      next\n        case 2 with * [OF eq nou] show False\n          by auto\n      qed\n      then show \"x=y\" ..\n    qed\n  qed\n  then have inj_onf: \"inj_on f (cball a r \\<inter> T)\"\n    using inj_on_Int by fastforce\n  have contf: \"continuous_on (cball a r \\<inter> T) f\"\n    unfolding f_def using \\<open>0 < r\\<close>  by (intro continuous_intros) blast\n  have fim: \"f ` (cball a r \\<inter> T) = cball a r \\<inter> T\"\n  proof\n    have *: \"norm (y + (1 - norm y / r) *\\<^sub>R u) \\<le> r\" if \"norm y \\<le> r\" \"norm u < r\" for y u::'a\n    proof -\n      have \"norm (y + (1 - norm y / r) *\\<^sub>R u) \\<le> norm y + norm((1 - norm y / r) *\\<^sub>R u)\"\n        using norm_triangle_ineq by blast\n      also have \"... = norm y + abs(1 - norm y / r) * norm u\"\n        by simp\n      also have \"... \\<le> r\"\n      proof -\n        have \"(r - norm u) * (r - norm y) \\<ge> 0\"\n          using that by auto\n        then have \"r * norm u + r * norm y \\<le> r * r + norm u * norm y\"\n          by (simp add: algebra_simps)\n        then show ?thesis\n        using that \\<open>0 < r\\<close> by (simp add: abs_if field_simps)\n      qed\n      finally show ?thesis .\n    qed\n    have \"f ` (cball a r) \\<subseteq> cball a r\"\n      apply (clarsimp simp add: dist_norm norm_minus_commute f_def)\n      using * by (metis diff_add_eq diff_diff_add diff_diff_eq2 norm_minus_commute nou)\n    moreover have \"f ` T \\<subseteq> T\"\n      unfolding f_def using \\<open>affine T\\<close> \\<open>a \\<in> T\\<close> \\<open>u \\<in> T\\<close>\n      by (force simp: add.commute mem_affine_3_minus)\n    ultimately show \"f ` (cball a r \\<inter> T) \\<subseteq> cball a r \\<inter> T\"\n      by blast\n  next\n    show \"cball a r \\<inter> T \\<subseteq> f ` (cball a r \\<inter> T)\"\n    proof (clarsimp simp add: dist_norm norm_minus_commute)\n      fix x\n      assume x: \"norm (x - a) \\<le> r\" and \"x \\<in> T\"\n      have \"\\<exists>v \\<in> {0..1}. ((1 - v) * r - norm ((x - a) - v *\\<^sub>R (u - a))) \\<bullet> 1 = 0\"\n        by (rule ivt_decreasing_component_on_1) (auto simp: x continuous_intros)\n      then obtain v where \"0\\<le>v\" \"v\\<le>1\" and v: \"(1 - v) * r = norm ((x - a) - v *\\<^sub>R (u - a))\"\n        by auto\n      show \"x \\<in> f ` (cball a r \\<inter> T)\"\n      proof (rule image_eqI)\n        show \"x = f (x - v *\\<^sub>R (u - a))\"\n          using \\<open>r > 0\\<close> v by (simp add: f_def field_simps)\n        have \"x - v *\\<^sub>R (u - a) \\<in> cball a r\"\n          using \\<open>r > 0\\<close> v \\<open>0 \\<le> v\\<close>\n          apply (simp add: field_simps dist_norm norm_minus_commute)\n          by (metis le_add_same_cancel2 order.order_iff_strict zero_le_mult_iff)\n        moreover have \"x - v *\\<^sub>R (u - a) \\<in> T\"\n          by (simp add: f_def \\<open>affine T\\<close> \\<open>u \\<in> T\\<close> \\<open>x \\<in> T\\<close> assms mem_affine_3_minus2)\n        ultimately show \"x - v *\\<^sub>R (u - a) \\<in> cball a r \\<inter> T\"\n          by blast\n      qed\n    qed\n  qed\n  have \"\\<exists>g. homeomorphism (cball a r \\<inter> T) (cball a r \\<inter> T) f g\"\n    apply (rule homeomorphism_compact [OF _ contf fim inj_onf])\n    apply (simp add: affine_closed compact_Int_closed \\<open>affine T\\<close>)\n    done\n  then show ?thesis\n    apply (rule exE)\n    apply (erule_tac f=f in that)\n    using \\<open>r > 0\\<close>\n     apply (simp_all add: f_def dist_norm norm_minus_commute)\n    done\nqed\n\ncorollary homeomorphism_moving_point_2:\n  fixes a :: \"'a::euclidean_space\"\n  assumes \"affine T\" \"a \\<in> T\" and u: \"u \\<in> ball a r \\<inter> T\" and v: \"v \\<in> ball a r \\<inter> T\"\n  obtains f g where \"homeomorphism (cball a r \\<inter> T) (cball a r \\<inter> T) f g\"\n                    \"f u = v\" \"\\<And>x. \\<lbrakk>x \\<in> sphere a r; x \\<in> T\\<rbrakk> \\<Longrightarrow> f x = x\"\nproof -\n  have \"0 < r\"\n    by (metis DiffD1 Diff_Diff_Int ball_eq_empty centre_in_ball not_le u)\n  obtain f1 g1 where hom1: \"homeomorphism (cball a r \\<inter> T) (cball a r \\<inter> T) f1 g1\"\n                 and \"f1 a = u\" and f1: \"\\<And>x. x \\<in> sphere a r \\<Longrightarrow> f1 x = x\"\n    using homeomorphism_moving_point_1 [OF \\<open>affine T\\<close> \\<open>a \\<in> T\\<close> u] by blast\n  obtain f2 g2 where hom2: \"homeomorphism (cball a r \\<inter> T) (cball a r \\<inter> T) f2 g2\"\n                 and \"f2 a = v\" and f2: \"\\<And>x. x \\<in> sphere a r \\<Longrightarrow> f2 x = x\"\n    using homeomorphism_moving_point_1 [OF \\<open>affine T\\<close> \\<open>a \\<in> T\\<close> v] by blast\n  show ?thesis\n  proof\n    show \"homeomorphism (cball a r \\<inter> T) (cball a r \\<inter> T) (f2 \\<circ> g1) (f1 \\<circ> g2)\"\n      by (metis homeomorphism_compose homeomorphism_symD hom1 hom2)\n    have \"g1 u = a\"\n      using \\<open>0 < r\\<close> \\<open>f1 a = u\\<close> assms hom1 homeomorphism_apply1 by fastforce\n    then show \"(f2 \\<circ> g1) u = v\"\n      by (simp add: \\<open>f2 a = v\\<close>)\n    show \"\\<And>x. \\<lbrakk>x \\<in> sphere a r; x \\<in> T\\<rbrakk> \\<Longrightarrow> (f2 \\<circ> g1) x = x\"\n      using f1 f2 hom1 homeomorphism_apply1 by fastforce\n  qed\nqed\n\n\ncorollary homeomorphism_moving_point_3:\n  fixes a :: \"'a::euclidean_space\"\n  assumes \"affine T\" \"a \\<in> T\" and ST: \"ball a r \\<inter> T \\<subseteq> S\" \"S \\<subseteq> T\"\n      and u: \"u \\<in> ball a r \\<inter> T\" and v: \"v \\<in> ball a r \\<inter> T\"\n  obtains f g where \"homeomorphism S S f g\"\n                    \"f u = v\" \"{x. ~ (f x = x \\<and> g x = x)} \\<subseteq> ball a r \\<inter> T\"\nproof -\n  obtain f g where hom: \"homeomorphism (cball a r \\<inter> T) (cball a r \\<inter> T) f g\"\n               and \"f u = v\" and fid: \"\\<And>x. \\<lbrakk>x \\<in> sphere a r; x \\<in> T\\<rbrakk> \\<Longrightarrow> f x = x\"\n    using homeomorphism_moving_point_2 [OF \\<open>affine T\\<close> \\<open>a \\<in> T\\<close> u v] by blast\n  have gid: \"\\<And>x. \\<lbrakk>x \\<in> sphere a r; x \\<in> T\\<rbrakk> \\<Longrightarrow> g x = x\"\n    using fid hom homeomorphism_apply1 by fastforce\n  define ff where \"ff \\<equiv> \\<lambda>x. if x \\<in> ball a r \\<inter> T then f x else x\"\n  define gg where \"gg \\<equiv> \\<lambda>x. if x \\<in> ball a r \\<inter> T then g x else x\"\n  show ?thesis\n  proof\n    show \"homeomorphism S S ff gg\"\n    proof (rule homeomorphismI)\n      have \"continuous_on ((cball a r \\<inter> T) \\<union> (T - ball a r)) ff\"\n        apply (simp add: ff_def)\n        apply (rule continuous_on_cases)\n        using homeomorphism_cont1 [OF hom]\n            apply (auto simp: affine_closed \\<open>affine T\\<close> continuous_on_id fid)\n        done\n      then show \"continuous_on S ff\"\n        apply (rule continuous_on_subset)\n        using ST by auto\n      have \"continuous_on ((cball a r \\<inter> T) \\<union> (T - ball a r)) gg\"\n        apply (simp add: gg_def)\n        apply (rule continuous_on_cases)\n        using homeomorphism_cont2 [OF hom]\n            apply (auto simp: affine_closed \\<open>affine T\\<close> continuous_on_id gid)\n        done\n      then show \"continuous_on S gg\"\n        apply (rule continuous_on_subset)\n        using ST by auto\n      show \"ff ` S \\<subseteq> S\"\n      proof (clarsimp simp add: ff_def)\n        fix x\n        assume \"x \\<in> S\" and x: \"dist a x < r\" and \"x \\<in> T\"\n        then have \"f x \\<in> cball a r \\<inter> T\"\n          using homeomorphism_image1 [OF hom] by force\n        then show \"f x \\<in> S\"\n          using ST(1) \\<open>x \\<in> T\\<close> gid hom homeomorphism_def x by fastforce\n      qed\n      show \"gg ` S \\<subseteq> S\"\n      proof (clarsimp simp add: gg_def)\n        fix x\n        assume \"x \\<in> S\" and x: \"dist a x < r\" and \"x \\<in> T\"\n        then have \"g x \\<in> cball a r \\<inter> T\"\n          using homeomorphism_image2 [OF hom] by force\n        then have \"g x \\<in> ball a r\"\n          using homeomorphism_apply2 [OF hom]\n            by (metis Diff_Diff_Int Diff_iff  \\<open>x \\<in> T\\<close> cball_def fid le_less mem_Collect_eq mem_ball mem_sphere x)\n        then show \"g x \\<in> S\"\n          using ST(1) \\<open>g x \\<in> cball a r \\<inter> T\\<close> by force\n        qed\n      show \"\\<And>x. x \\<in> S \\<Longrightarrow> gg (ff x) = x\"\n        apply (simp add: ff_def gg_def)\n        using homeomorphism_apply1 [OF hom] homeomorphism_image1 [OF hom]\n        apply auto\n        apply (metis Int_iff homeomorphism_apply1 [OF hom] fid image_eqI less_eq_real_def mem_cball mem_sphere)\n        done\n      show \"\\<And>x. x \\<in> S \\<Longrightarrow> ff (gg x) = x\"\n        apply (simp add: ff_def gg_def)\n        using homeomorphism_apply2 [OF hom] homeomorphism_image2 [OF hom]\n        apply auto\n        apply (metis Int_iff fid image_eqI less_eq_real_def mem_cball mem_sphere)\n        done\n    qed\n    show \"ff u = v\"\n      using u by (auto simp: ff_def \\<open>f u = v\\<close>)\n    show \"{x. \\<not> (ff x = x \\<and> gg x = x)} \\<subseteq> ball a r \\<inter> T\"\n      by (auto simp: ff_def gg_def)\n  qed\nqed\n\n\nproposition homeomorphism_moving_point:\n  fixes a :: \"'a::euclidean_space\"\n  assumes ope: \"openin (subtopology euclidean (affine hull S)) S\"\n      and \"S \\<subseteq> T\"\n      and TS: \"T \\<subseteq> affine hull S\"\n      and S: \"connected S\" \"a \\<in> S\" \"b \\<in> S\"\n  obtains f g where \"homeomorphism T T f g\" \"f a = b\"\n                    \"{x. ~ (f x = x \\<and> g x = x)} \\<subseteq> S\"\n                    \"bounded {x. ~ (f x = x \\<and> g x = x)}\"\nproof -\n  have 1: \"\\<exists>h k. homeomorphism T T h k \\<and> h (f d) = d \\<and>\n              {x. ~ (h x = x \\<and> k x = x)} \\<subseteq> S \\<and> bounded {x. ~ (h x = x \\<and> k x = x)}\"\n        if \"d \\<in> S\" \"f d \\<in> S\" and homfg: \"homeomorphism T T f g\"\n        and S: \"{x. ~ (f x = x \\<and> g x = x)} \\<subseteq> S\"\n        and bo: \"bounded {x. ~ (f x = x \\<and> g x = x)}\" for d f g\n  proof (intro exI conjI)\n    show homgf: \"homeomorphism T T g f\"\n      by (metis homeomorphism_symD homfg)\n    then show \"g (f d) = d\"\n      by (meson \\<open>S \\<subseteq> T\\<close> homeomorphism_def subsetD \\<open>d \\<in> S\\<close>)\n    show \"{x. \\<not> (g x = x \\<and> f x = x)} \\<subseteq> S\"\n      using S by blast\n    show \"bounded {x. \\<not> (g x = x \\<and> f x = x)}\"\n      using bo by (simp add: conj_commute)\n  qed\n  have 2: \"\\<exists>f g. homeomorphism T T f g \\<and> f x = f2 (f1 x) \\<and>\n                 {x. \\<not> (f x = x \\<and> g x = x)} \\<subseteq> S \\<and> bounded {x. \\<not> (f x = x \\<and> g x = x)}\"\n             if \"x \\<in> S\" \"f1 x \\<in> S\" \"f2 (f1 x) \\<in> S\"\n                and hom: \"homeomorphism T T f1 g1\" \"homeomorphism T T f2 g2\"\n                and sub: \"{x. \\<not> (f1 x = x \\<and> g1 x = x)} \\<subseteq> S\"   \"{x. \\<not> (f2 x = x \\<and> g2 x = x)} \\<subseteq> S\"\n                and bo: \"bounded {x. \\<not> (f1 x = x \\<and> g1 x = x)}\"  \"bounded {x. \\<not> (f2 x = x \\<and> g2 x = x)}\"\n             for x f1 f2 g1 g2\n  proof (intro exI conjI)\n    show homgf: \"homeomorphism T T (f2 \\<circ> f1) (g1 \\<circ> g2)\"\n      by (metis homeomorphism_compose hom)\n    then show \"(f2 \\<circ> f1) x = f2 (f1 x)\"\n      by force\n    show \"{x. \\<not> ((f2 \\<circ> f1) x = x \\<and> (g1 \\<circ> g2) x = x)} \\<subseteq> S\"\n      using sub by force\n    have \"bounded ({x. ~(f1 x = x \\<and> g1 x = x)} \\<union> {x. ~(f2 x = x \\<and> g2 x = x)})\"\n      using bo by simp\n    then show \"bounded {x. \\<not> ((f2 \\<circ> f1) x = x \\<and> (g1 \\<circ> g2) x = x)}\"\n      by (rule bounded_subset) auto\n  qed\n  have 3: \"\\<exists>U. openin (subtopology euclidean S) U \\<and>\n              d \\<in> U \\<and>\n              (\\<forall>x\\<in>U.\n                  \\<exists>f g. homeomorphism T T f g \\<and> f d = x \\<and>\n                        {x. \\<not> (f x = x \\<and> g x = x)} \\<subseteq> S \\<and>\n                        bounded {x. \\<not> (f x = x \\<and> g x = x)})\"\n           if \"d \\<in> S\" for d\n  proof -\n    obtain r where \"r > 0\" and r: \"ball d r \\<inter> affine hull S \\<subseteq> S\"\n      by (metis \\<open>d \\<in> S\\<close> ope openin_contains_ball)\n    have *: \"\\<exists>f g. homeomorphism T T f g \\<and> f d = e \\<and>\n                   {x. \\<not> (f x = x \\<and> g x = x)} \\<subseteq> S \\<and>\n                   bounded {x. \\<not> (f x = x \\<and> g x = x)}\" if \"e \\<in> S\" \"e \\<in> ball d r\" for e\n      apply (rule homeomorphism_moving_point_3 [of \"affine hull S\" d r T d e])\n      using r \\<open>S \\<subseteq> T\\<close> TS that\n            apply (auto simp: \\<open>d \\<in> S\\<close> \\<open>0 < r\\<close> hull_inc)\n      using bounded_subset by blast\n    show ?thesis\n      apply (rule_tac x=\"S \\<inter> ball d r\" in exI)\n      apply (intro conjI)\n        apply (simp add: openin_open_Int)\n       apply (simp add: \\<open>0 < r\\<close> that)\n      apply (blast intro: *)\n      done\n  qed\n  have \"\\<exists>f g. homeomorphism T T f g \\<and> f a = b \\<and>\n              {x. ~ (f x = x \\<and> g x = x)} \\<subseteq> S \\<and> bounded {x. ~ (f x = x \\<and> g x = x)}\"\n    apply (rule connected_equivalence_relation [OF S], safe)\n      apply (blast intro: 1 2 3)+\n    done\n  then show ?thesis\n    using that by auto\nqed\n\n\nlemma homeomorphism_moving_points_exists_gen:\n  assumes K: \"finite K\" \"\\<And>i. i \\<in> K \\<Longrightarrow> x i \\<in> S \\<and> y i \\<in> S\"\n             \"pairwise (\\<lambda>i j. (x i \\<noteq> x j) \\<and> (y i \\<noteq> y j)) K\"\n      and \"2 \\<le> aff_dim S\"\n      and ope: \"openin (subtopology euclidean (affine hull S)) S\"\n      and \"S \\<subseteq> T\" \"T \\<subseteq> affine hull S\" \"connected S\"\n  shows \"\\<exists>f g. homeomorphism T T f g \\<and> (\\<forall>i \\<in> K. f(x i) = y i) \\<and>\n               {x. ~ (f x = x \\<and> g x = x)} \\<subseteq> S \\<and> bounded {x. ~ (f x = x \\<and> g x = x)}\"\n  using assms\nproof (induction K)\n  case empty\n  then show ?case\n    by (force simp: homeomorphism_ident)\nnext\n  case (insert i K)\n  then have xney: \"\\<And>j. \\<lbrakk>j \\<in> K; j \\<noteq> i\\<rbrakk> \\<Longrightarrow> x i \\<noteq> x j \\<and> y i \\<noteq> y j\"\n       and pw: \"pairwise (\\<lambda>i j. x i \\<noteq> x j \\<and> y i \\<noteq> y j) K\"\n       and \"x i \\<in> S\" \"y i \\<in> S\"\n       and xyS: \"\\<And>i. i \\<in> K \\<Longrightarrow> x i \\<in> S \\<and> y i \\<in> S\"\n    by (simp_all add: pairwise_insert)\n  obtain f g where homfg: \"homeomorphism T T f g\" and feq: \"\\<And>i. i \\<in> K \\<Longrightarrow> f(x i) = y i\"\n               and fg_sub: \"{x. ~ (f x = x \\<and> g x = x)} \\<subseteq> S\"\n               and bo_fg: \"bounded {x. ~ (f x = x \\<and> g x = x)}\"\n    using insert.IH [OF xyS pw] insert.prems by (blast intro: that)\n  then have \"\\<exists>f g. homeomorphism T T f g \\<and> (\\<forall>i \\<in> K. f(x i) = y i) \\<and>\n                   {x. ~ (f x = x \\<and> g x = x)} \\<subseteq> S \\<and> bounded {x. ~ (f x = x \\<and> g x = x)}\"\n    using insert by blast\n  have aff_eq: \"affine hull (S - y ` K) = affine hull S\"\n    apply (rule affine_hull_Diff)\n    apply (auto simp: insert)\n    using \\<open>y i \\<in> S\\<close> insert.hyps(2) xney xyS by fastforce\n  have f_in_S: \"f x \\<in> S\" if \"x \\<in> S\" for x\n    using homfg fg_sub homeomorphism_apply1 \\<open>S \\<subseteq> T\\<close>\n  proof -\n    have \"(f (f x) \\<noteq> f x \\<or> g (f x) \\<noteq> f x) \\<or> f x \\<in> S\"\n      by (metis \\<open>S \\<subseteq> T\\<close> homfg subsetD homeomorphism_apply1 that)\n    then show ?thesis\n      using fg_sub by force\n  qed\n  obtain h k where homhk: \"homeomorphism T T h k\" and heq: \"h (f (x i)) = y i\"\n               and hk_sub: \"{x. \\<not> (h x = x \\<and> k x = x)} \\<subseteq> S - y ` K\"\n               and bo_hk:  \"bounded {x. \\<not> (h x = x \\<and> k x = x)}\"\n  proof (rule homeomorphism_moving_point [of \"S - y`K\" T \"f(x i)\" \"y i\"])\n    show \"openin (subtopology euclidean (affine hull (S - y ` K))) (S - y ` K)\"\n      by (simp add: aff_eq openin_diff finite_imp_closedin image_subset_iff hull_inc insert xyS)\n    show \"S - y ` K \\<subseteq> T\"\n      using \\<open>S \\<subseteq> T\\<close> by auto\n    show \"T \\<subseteq> affine hull (S - y ` K)\"\n      using insert by (simp add: aff_eq)\n    show \"connected (S - y ` K)\"\n    proof (rule connected_openin_diff_countable [OF \\<open>connected S\\<close> ope])\n      show \"\\<not> collinear S\"\n        using collinear_aff_dim \\<open>2 \\<le> aff_dim S\\<close> by force\n      show \"countable (y ` K)\"\n        using countable_finite insert.hyps(1) by blast\n    qed\n    show \"f (x i) \\<in> S - y ` K\"\n      apply (auto simp: f_in_S \\<open>x i \\<in> S\\<close>)\n        by (metis feq homfg \\<open>x i \\<in> S\\<close> homeomorphism_def \\<open>S \\<subseteq> T\\<close> \\<open>i \\<notin> K\\<close> subsetCE xney xyS)\n    show \"y i \\<in> S - y ` K\"\n      using insert.hyps xney by (auto simp: \\<open>y i \\<in> S\\<close>)\n  qed blast\n  show ?case\n  proof (intro exI conjI)\n    show \"homeomorphism T T (h \\<circ> f) (g \\<circ> k)\"\n      using homfg homhk homeomorphism_compose by blast\n    show \"\\<forall>i \\<in> insert i K. (h \\<circ> f) (x i) = y i\"\n      using feq hk_sub by (auto simp: heq)\n    show \"{x. \\<not> ((h \\<circ> f) x = x \\<and> (g \\<circ> k) x = x)} \\<subseteq> S\"\n      using fg_sub hk_sub by force\n    have \"bounded ({x. ~(f x = x \\<and> g x = x)} \\<union> {x. ~(h x = x \\<and> k x = x)})\"\n      using bo_fg bo_hk bounded_Un by blast\n    then show \"bounded {x. \\<not> ((h \\<circ> f) x = x \\<and> (g \\<circ> k) x = x)}\"\n      by (rule bounded_subset) auto\n  qed\nqed\n\nproposition homeomorphism_moving_points_exists:\n  fixes S :: \"'a::euclidean_space set\"\n  assumes 2: \"2 \\<le> DIM('a)\" \"open S\" \"connected S\" \"S \\<subseteq> T\" \"finite K\"\n      and KS: \"\\<And>i. i \\<in> K \\<Longrightarrow> x i \\<in> S \\<and> y i \\<in> S\"\n      and pw: \"pairwise (\\<lambda>i j. (x i \\<noteq> x j) \\<and> (y i \\<noteq> y j)) K\"\n      and S: \"S \\<subseteq> T\" \"T \\<subseteq> affine hull S\" \"connected S\"\n  obtains f g where \"homeomorphism T T f g\" \"\\<And>i. i \\<in> K \\<Longrightarrow> f(x i) = y i\"\n                    \"{x. ~ (f x = x \\<and> g x = x)} \\<subseteq> S\" \"bounded {x. (~ (f x = x \\<and> g x = x))}\"\nproof (cases \"S = {}\")\n  case True\n  then show ?thesis\n    using KS homeomorphism_ident that by fastforce\nnext\n  case False\n  then have affS: \"affine hull S = UNIV\"\n    by (simp add: affine_hull_open \\<open>open S\\<close>)\n  then have ope: \"openin (subtopology euclidean (affine hull S)) S\"\n    using \\<open>open S\\<close> open_openin by auto\n  have \"2 \\<le> DIM('a)\" by (rule 2)\n  also have \"... = aff_dim (UNIV :: 'a set)\"\n    by simp\n  also have \"... \\<le> aff_dim S\"\n    by (metis aff_dim_UNIV aff_dim_affine_hull aff_dim_le_DIM affS)\n  finally have \"2 \\<le> aff_dim S\"\n    by linarith\n  then show ?thesis\n    using homeomorphism_moving_points_exists_gen [OF \\<open>finite K\\<close> KS pw _ ope S] that by fastforce\nqed\n\n\nsubsubsection\\<open>The theorem @{text homeomorphism_grouping_points_exists}\\<close>\n\nlemma homeomorphism_grouping_point_1:\n  fixes a::real and c::real\n  assumes \"a < b\" \"c < d\"\n  obtains f g where \"homeomorphism (cbox a b) (cbox c d) f g\" \"f a = c\" \"f b = d\"\nproof -\n  define f where \"f \\<equiv> \\<lambda>x. ((d - c) / (b - a)) * x + (c - a * ((d - c) / (b - a)))\"\n  have \"\\<exists>g. homeomorphism (cbox a b) (cbox c d) f g\"\n  proof (rule homeomorphism_compact)\n    show \"continuous_on (cbox a b) f\"\n      apply (simp add: f_def)\n      apply (intro continuous_intros)\n      using assms by auto\n    have \"f ` {a..b} = {c..d}\"\n      unfolding f_def image_affinity_atLeastAtMost\n      using assms sum_sqs_eq by (auto simp: divide_simps algebra_simps)\n    then show \"f ` cbox a b = cbox c d\"\n      by auto\n    show \"inj_on f (cbox a b)\"\n      unfolding f_def inj_on_def using assms by auto\n  qed auto\n  then obtain g where \"homeomorphism (cbox a b) (cbox c d) f g\" ..\n  then show ?thesis\n  proof\n    show \"f a = c\"\n      by (simp add: f_def)\n    show \"f b = d\"\n      using assms sum_sqs_eq [of a b] by (auto simp: f_def divide_simps algebra_simps)\n  qed\nqed\n\nlemma homeomorphism_grouping_point_2:\n  fixes a::real and w::real\n  assumes hom_ab: \"homeomorphism (cbox a b) (cbox u v) f1 g1\"\n      and hom_bc: \"homeomorphism (cbox b c) (cbox v w) f2 g2\"\n      and \"b \\<in> cbox a c\" \"v \\<in> cbox u w\"\n      and eq: \"f1 a = u\" \"f1 b = v\" \"f2 b = v\" \"f2 c = w\"\n obtains f g where \"homeomorphism (cbox a c) (cbox u w) f g\" \"f a = u\" \"f c = w\"\n                   \"\\<And>x. x \\<in> cbox a b \\<Longrightarrow> f x = f1 x\" \"\\<And>x. x \\<in> cbox b c \\<Longrightarrow> f x = f2 x\"\nproof -\n  have le: \"a \\<le> b\" \"b \\<le> c\" \"u \\<le> v\" \"v \\<le> w\"\n    using assms by simp_all\n  then have ac: \"cbox a c = cbox a b \\<union> cbox b c\" and uw: \"cbox u w = cbox u v \\<union> cbox v w\"\n    by auto\n  define f where \"f \\<equiv> \\<lambda>x. if x \\<le> b then f1 x else f2 x\"\n  have \"\\<exists>g. homeomorphism (cbox a c) (cbox u w) f g\"\n  proof (rule homeomorphism_compact)\n    have cf1: \"continuous_on (cbox a b) f1\"\n      using hom_ab homeomorphism_cont1 by blast\n    have cf2: \"continuous_on (cbox b c) f2\"\n      using hom_bc homeomorphism_cont1 by blast\n    show \"continuous_on (cbox a c) f\"\n      apply (simp add: f_def)\n      apply (rule continuous_on_cases_le [OF continuous_on_subset [OF cf1] continuous_on_subset [OF cf2]])\n      using le eq apply (force simp: continuous_on_id)+\n      done\n    have \"f ` cbox a b = f1 ` cbox a b\" \"f ` cbox b c = f2 ` cbox b c\"\n      unfolding f_def using eq by force+\n    then show \"f ` cbox a c = cbox u w\"\n      apply (simp only: ac uw image_Un)\n      by (metis hom_ab hom_bc homeomorphism_def)\n    have neq12: \"f1 x \\<noteq> f2 y\" if x: \"a \\<le> x\" \"x \\<le> b\" and y: \"b < y\" \"y \\<le> c\" for x y\n    proof -\n      have \"f1 x \\<in> cbox u v\"\n        by (metis hom_ab homeomorphism_def image_eqI mem_box_real(2) x)\n      moreover have \"f2 y \\<in> cbox v w\"\n        by (metis (full_types) hom_bc homeomorphism_def image_subset_iff mem_box_real(2) not_le not_less_iff_gr_or_eq order_refl y)\n      moreover have \"f2 y \\<noteq> f2 b\"\n        by (metis cancel_comm_monoid_add_class.diff_cancel diff_gt_0_iff_gt hom_bc homeomorphism_def le(2) less_imp_le less_numeral_extra(3) mem_box_real(2) order_refl y)\n      ultimately show ?thesis\n        using le eq by simp\n    qed\n    have \"inj_on f1 (cbox a b)\"\n      by (metis (full_types) hom_ab homeomorphism_def inj_onI)\n    moreover have \"inj_on f2 (cbox b c)\"\n      by (metis (full_types) hom_bc homeomorphism_def inj_onI)\n    ultimately show \"inj_on f (cbox a c)\"\n      apply (simp (no_asm) add: inj_on_def)\n      apply (simp add: f_def inj_on_eq_iff)\n      using neq12  apply force\n      done\n  qed auto\n  then obtain g where \"homeomorphism (cbox a c) (cbox u w) f g\" ..\n  then show ?thesis\n    apply (rule that)\n    using eq le by (auto simp: f_def)\nqed\n\nlemma homeomorphism_grouping_point_3:\n  fixes a::real\n  assumes cbox_sub: \"cbox c d \\<subseteq> box a b\" \"cbox u v \\<subseteq> box a b\"\n      and box_ne: \"box c d \\<noteq> {}\" \"box u v \\<noteq> {}\"\n  obtains f g where \"homeomorphism (cbox a b) (cbox a b) f g\" \"f a = a\" \"f b = b\"\n                    \"\\<And>x. x \\<in> cbox c d \\<Longrightarrow> f x \\<in> cbox u v\"\nproof -\n  have less: \"a < c\" \"a < u\" \"d < b\" \"v < b\" \"c < d\" \"u < v\" \"cbox c d \\<noteq> {}\"\n    using assms\n    by (simp_all add: cbox_sub subset_eq)\n  obtain f1 g1 where 1: \"homeomorphism (cbox a c) (cbox a u) f1 g1\"\n                   and f1_eq: \"f1 a = a\" \"f1 c = u\"\n    using homeomorphism_grouping_point_1 [OF \\<open>a < c\\<close> \\<open>a < u\\<close>] .\n  obtain f2 g2 where 2: \"homeomorphism (cbox c d) (cbox u v) f2 g2\"\n                   and f2_eq: \"f2 c = u\" \"f2 d = v\"\n    using homeomorphism_grouping_point_1 [OF \\<open>c < d\\<close> \\<open>u < v\\<close>] .\n  obtain f3 g3 where 3: \"homeomorphism (cbox d b) (cbox v b) f3 g3\"\n                   and f3_eq: \"f3 d = v\" \"f3 b = b\"\n    using homeomorphism_grouping_point_1 [OF \\<open>d < b\\<close> \\<open>v < b\\<close>] .\n  obtain f4 g4 where 4: \"homeomorphism (cbox a d) (cbox a v) f4 g4\" and \"f4 a = a\" \"f4 d = v\"\n                 and f4_eq: \"\\<And>x. x \\<in> cbox a c \\<Longrightarrow> f4 x = f1 x\" \"\\<And>x. x \\<in> cbox c d \\<Longrightarrow> f4 x = f2 x\"\n    using homeomorphism_grouping_point_2 [OF 1 2] less  by (auto simp: f1_eq f2_eq)\n  obtain f g where fg: \"homeomorphism (cbox a b) (cbox a b) f g\" \"f a = a\" \"f b = b\"\n               and f_eq: \"\\<And>x. x \\<in> cbox a d \\<Longrightarrow> f x = f4 x\" \"\\<And>x. x \\<in> cbox d b \\<Longrightarrow> f x = f3 x\"\n    using homeomorphism_grouping_point_2 [OF 4 3] less by (auto simp: f4_eq f3_eq f2_eq f1_eq)\n  show ?thesis\n    apply (rule that [OF fg])\n    using f4_eq f_eq homeomorphism_image1 [OF 2]\n    apply simp\n    by (metis atLeastAtMost_iff box_real(1) box_real(2) cbox_sub(1) greaterThanLessThan_iff imageI less_eq_real_def subset_eq)\nqed\n\n\nlemma homeomorphism_grouping_point_4:\n  fixes T :: \"real set\"\n  assumes \"open U\" \"open S\" \"connected S\" \"U \\<noteq> {}\" \"finite K\" \"K \\<subseteq> S\" \"U \\<subseteq> S\" \"S \\<subseteq> T\"\n  obtains f g where \"homeomorphism T T f g\"\n                    \"\\<And>x. x \\<in> K \\<Longrightarrow> f x \\<in> U\" \"{x. (~ (f x = x \\<and> g x = x))} \\<subseteq> S\"\n                    \"bounded {x. (~ (f x = x \\<and> g x = x))}\"\nproof -\n  obtain c d where \"box c d \\<noteq> {}\" \"cbox c d \\<subseteq> U\"\n  proof -\n    obtain u where \"u \\<in> U\"\n      using \\<open>U \\<noteq> {}\\<close> by blast\n    then obtain e where \"e > 0\" \"cball u e \\<subseteq> U\"\n      using \\<open>open U\\<close> open_contains_cball by blast\n    then show ?thesis\n      by (rule_tac c=u and d=\"u+e\" in that) (auto simp: dist_norm subset_iff)\n  qed\n  have \"compact K\"\n    by (simp add: \\<open>finite K\\<close> finite_imp_compact)\n  obtain a b where \"box a b \\<noteq> {}\" \"K \\<subseteq> cbox a b\" \"cbox a b \\<subseteq> S\"\n  proof (cases \"K = {}\")\n    case True then show ?thesis\n      using \\<open>box c d \\<noteq> {}\\<close> \\<open>cbox c d \\<subseteq> U\\<close> \\<open>U \\<subseteq> S\\<close> that by blast\n  next\n    case False\n    then obtain a b where \"a \\<in> K\" \"b \\<in> K\"\n            and a: \"\\<And>x. x \\<in> K \\<Longrightarrow> a \\<le> x\" and b: \"\\<And>x. x \\<in> K \\<Longrightarrow> x \\<le> b\"\n      using compact_attains_inf compact_attains_sup by (metis \\<open>compact K\\<close>)+\n    obtain e where \"e > 0\" \"cball b e \\<subseteq> S\"\n      using \\<open>open S\\<close> open_contains_cball\n      by (metis \\<open>b \\<in> K\\<close> \\<open>K \\<subseteq> S\\<close> subsetD)\n    show ?thesis\n    proof\n      show \"box a (b + e) \\<noteq> {}\"\n        using \\<open>0 < e\\<close> \\<open>b \\<in> K\\<close> a by force\n      show \"K \\<subseteq> cbox a (b + e)\"\n        using \\<open>0 < e\\<close> a b by fastforce\n      have \"a \\<in> S\"\n        using \\<open>a \\<in> K\\<close> assms(6) by blast\n      have \"b + e \\<in> S\"\n        using \\<open>0 < e\\<close> \\<open>cball b e \\<subseteq> S\\<close>  by (force simp: dist_norm)\n      show \"cbox a (b + e) \\<subseteq> S\"\n        using \\<open>a \\<in> S\\<close> \\<open>b + e \\<in> S\\<close> \\<open>connected S\\<close> connected_contains_Icc by auto\n    qed\n  qed\n  obtain w z where \"cbox w z \\<subseteq> S\" and sub_wz: \"cbox a b \\<union> cbox c d \\<subseteq> box w z\"\n  proof -\n    have \"a \\<in> S\" \"b \\<in> S\"\n      using \\<open>box a b \\<noteq> {}\\<close> \\<open>cbox a b \\<subseteq> S\\<close> by auto\n    moreover have \"c \\<in> S\" \"d \\<in> S\"\n      using \\<open>box c d \\<noteq> {}\\<close> \\<open>cbox c d \\<subseteq> U\\<close> \\<open>U \\<subseteq> S\\<close> by force+\n    ultimately have \"min a c \\<in> S\" \"max b d \\<in> S\"\n      by linarith+\n    then obtain e1 e2 where \"e1 > 0\" \"cball (min a c) e1 \\<subseteq> S\" \"e2 > 0\" \"cball (max b d) e2 \\<subseteq> S\"\n      using \\<open>open S\\<close> open_contains_cball by metis\n    then have *: \"min a c - e1 \\<in> S\" \"max b d + e2 \\<in> S\"\n      by (auto simp: dist_norm)\n    show ?thesis\n    proof\n      show \"cbox (min a c - e1) (max b d+ e2) \\<subseteq> S\"\n        using * \\<open>connected S\\<close> connected_contains_Icc by auto\n      show \"cbox a b \\<union> cbox c d \\<subseteq> box (min a c - e1) (max b d + e2)\"\n        using \\<open>0 < e1\\<close> \\<open>0 < e2\\<close> by auto\n    qed\n  qed\n  then\n  obtain f g where hom: \"homeomorphism (cbox w z) (cbox w z) f g\"\n               and \"f w = w\" \"f z = z\"\n               and fin: \"\\<And>x. x \\<in> cbox a b \\<Longrightarrow> f x \\<in> cbox c d\"\n    using homeomorphism_grouping_point_3 [of a b w z c d]\n    using \\<open>box a b \\<noteq> {}\\<close> \\<open>box c d \\<noteq> {}\\<close> by blast\n  have contfg: \"continuous_on (cbox w z) f\" \"continuous_on (cbox w z) g\"\n    using hom homeomorphism_def by blast+\n  define f' where \"f' \\<equiv> \\<lambda>x. if x \\<in> cbox w z then f x else x\"\n  define g' where \"g' \\<equiv> \\<lambda>x. if x \\<in> cbox w z then g x else x\"\n  show ?thesis\n  proof\n    have T: \"cbox w z \\<union> (T - box w z) = T\"\n      using \\<open>cbox w z \\<subseteq> S\\<close> \\<open>S \\<subseteq> T\\<close> by auto\n    show \"homeomorphism T T f' g'\"\n    proof\n      have clo: \"closedin (subtopology euclidean (cbox w z \\<union> (T - box w z))) (T - box w z)\"\n        by (metis Diff_Diff_Int Diff_subset T closedin_def open_box openin_open_Int topspace_euclidean_subtopology)\n      have \"continuous_on (cbox w z \\<union> (T - box w z)) f'\" \"continuous_on (cbox w z \\<union> (T - box w z)) g'\"\n        unfolding f'_def g'_def\n         apply (safe intro!: continuous_on_cases_local contfg continuous_on_id clo)\n         apply (simp_all add: closed_subset)\n        using \\<open>f w = w\\<close> \\<open>f z = z\\<close> apply force\n        by (metis \\<open>f w = w\\<close> \\<open>f z = z\\<close> hom homeomorphism_def less_eq_real_def mem_box_real(2))\n      then show \"continuous_on T f'\" \"continuous_on T g'\"\n        by (simp_all only: T)\n      show \"f' ` T \\<subseteq> T\"\n        unfolding f'_def\n        by clarsimp (metis \\<open>cbox w z \\<subseteq> S\\<close> \\<open>S \\<subseteq> T\\<close> subsetD hom homeomorphism_def imageI mem_box_real(2))\n      show \"g' ` T \\<subseteq> T\"\n        unfolding g'_def\n        by clarsimp (metis \\<open>cbox w z \\<subseteq> S\\<close> \\<open>S \\<subseteq> T\\<close> subsetD hom homeomorphism_def imageI mem_box_real(2))\n      show \"\\<And>x. x \\<in> T \\<Longrightarrow> g' (f' x) = x\"\n        unfolding f'_def g'_def\n        using homeomorphism_apply1 [OF hom]  homeomorphism_image1 [OF hom] by fastforce\n      show \"\\<And>y. y \\<in> T \\<Longrightarrow> f' (g' y) = y\"\n        unfolding f'_def g'_def\n        using homeomorphism_apply2 [OF hom]  homeomorphism_image2 [OF hom] by fastforce\n    qed\n    show \"\\<And>x. x \\<in> K \\<Longrightarrow> f' x \\<in> U\"\n      using fin sub_wz \\<open>K \\<subseteq> cbox a b\\<close> \\<open>cbox c d \\<subseteq> U\\<close> by (force simp: f'_def)\n    show \"{x. \\<not> (f' x = x \\<and> g' x = x)} \\<subseteq> S\"\n      using \\<open>cbox w z \\<subseteq> S\\<close> by (auto simp: f'_def g'_def)\n    show \"bounded {x. \\<not> (f' x = x \\<and> g' x = x)}\"\n      apply (rule bounded_subset [of \"cbox w z\"])\n      using bounded_cbox apply blast\n      apply (auto simp: f'_def g'_def)\n      done\n  qed\nqed\n\nproposition homeomorphism_grouping_points_exists:\n  fixes S :: \"'a::euclidean_space set\"\n  assumes \"open U\" \"open S\" \"connected S\" \"U \\<noteq> {}\" \"finite K\" \"K \\<subseteq> S\" \"U \\<subseteq> S\" \"S \\<subseteq> T\"\n  obtains f g where \"homeomorphism T T f g\" \"{x. (~ (f x = x \\<and> g x = x))} \\<subseteq> S\"\n                    \"bounded {x. (~ (f x = x \\<and> g x = x))}\" \"\\<And>x. x \\<in> K \\<Longrightarrow> f x \\<in> U\"\nproof (cases \"2 \\<le> DIM('a)\")\n  case True\n  have TS: \"T \\<subseteq> affine hull S\"\n    using affine_hull_open assms by blast\n  have \"infinite U\"\n    using \\<open>open U\\<close> \\<open>U \\<noteq> {}\\<close> finite_imp_not_open by blast\n  then obtain P where \"P \\<subseteq> U\" \"finite P\" \"card K = card P\"\n    using infinite_arbitrarily_large by metis\n  then obtain \\<gamma> where \\<gamma>: \"bij_betw \\<gamma> K P\"\n    using \\<open>finite K\\<close> finite_same_card_bij by blast\n  obtain f g where \"homeomorphism T T f g\" \"\\<And>i. i \\<in> K \\<Longrightarrow> f (id i) = \\<gamma> i\" \"{x. \\<not> (f x = x \\<and> g x = x)} \\<subseteq> S\" \"bounded {x. \\<not> (f x = x \\<and> g x = x)}\"\n  proof (rule homeomorphism_moving_points_exists [OF True \\<open>open S\\<close> \\<open>connected S\\<close> \\<open>S \\<subseteq> T\\<close> \\<open>finite K\\<close>])\n    show \"\\<And>i. i \\<in> K \\<Longrightarrow> id i \\<in> S \\<and> \\<gamma> i \\<in> S\"\n      using \\<open>P \\<subseteq> U\\<close> \\<open>bij_betw \\<gamma> K P\\<close> \\<open>K \\<subseteq> S\\<close> \\<open>U \\<subseteq> S\\<close> bij_betwE by blast\n    show \"pairwise (\\<lambda>i j. id i \\<noteq> id j \\<and> \\<gamma> i \\<noteq> \\<gamma> j) K\"\n      using \\<gamma> by (auto simp: pairwise_def bij_betw_def inj_on_def)\n  qed (use affine_hull_open assms that in auto)\n  then show ?thesis\n    using \\<gamma> \\<open>P \\<subseteq> U\\<close> bij_betwE by (fastforce simp add: intro!: that)\nnext\n  case False\n  with DIM_positive have \"DIM('a) = 1\"\n    by (simp add: dual_order.antisym)\n  then obtain h::\"'a \\<Rightarrow>real\" and j\n  where \"linear h\" \"linear j\"\n    and noh: \"\\<And>x. norm(h x) = norm x\" and noj: \"\\<And>y. norm(j y) = norm y\"\n    and hj:  \"\\<And>x. j(h x) = x\" \"\\<And>y. h(j y) = y\"\n    and ranh: \"surj h\"\n    using isomorphisms_UNIV_UNIV\n    by (metis (mono_tags, hide_lams) DIM_real UNIV_eq_I range_eqI)\n  obtain f g where hom: \"homeomorphism (h ` T) (h ` T) f g\"\n               and f: \"\\<And>x. x \\<in> h ` K \\<Longrightarrow> f x \\<in> h ` U\"\n               and sub: \"{x. \\<not> (f x = x \\<and> g x = x)} \\<subseteq> h ` S\"\n               and bou: \"bounded {x. \\<not> (f x = x \\<and> g x = x)}\"\n    apply (rule homeomorphism_grouping_point_4 [of \"h ` U\" \"h ` S\" \"h ` K\" \"h ` T\"])\n    by (simp_all add: assms image_mono  \\<open>linear h\\<close> open_surjective_linear_image connected_linear_image ranh)\n  have jf: \"j (f (h x)) = x \\<longleftrightarrow> f (h x) = h x\" for x\n    by (metis hj)\n  have jg: \"j (g (h x)) = x \\<longleftrightarrow> g (h x) = h x\" for x\n    by (metis hj)\n  have cont_hj: \"continuous_on X h\"  \"continuous_on Y j\" for X Y\n    by (simp_all add: \\<open>linear h\\<close> \\<open>linear j\\<close> linear_linear linear_continuous_on)\n  show ?thesis\n  proof\n    show \"homeomorphism T T (j \\<circ> f \\<circ> h) (j \\<circ> g \\<circ> h)\"\n    proof\n      show \"continuous_on T (j \\<circ> f \\<circ> h)\"\n        apply (intro continuous_on_compose cont_hj)\n        using hom homeomorphism_def by blast\n      show \"continuous_on T (j \\<circ> g \\<circ> h)\"\n        apply (intro continuous_on_compose cont_hj)\n        using hom homeomorphism_def by blast\n      show \"(j \\<circ> f \\<circ> h) ` T \\<subseteq> T\"\n        by clarsimp (metis (mono_tags, hide_lams) hj(1) hom homeomorphism_def imageE imageI)\n      show \"(j \\<circ> g \\<circ> h) ` T \\<subseteq> T\"\n        by clarsimp (metis (mono_tags, hide_lams) hj(1) hom homeomorphism_def imageE imageI)\n      show \"\\<And>x. x \\<in> T \\<Longrightarrow> (j \\<circ> g \\<circ> h) ((j \\<circ> f \\<circ> h) x) = x\"\n        using hj hom homeomorphism_apply1 by fastforce\n      show \"\\<And>y. y \\<in> T \\<Longrightarrow> (j \\<circ> f \\<circ> h) ((j \\<circ> g \\<circ> h) y) = y\"\n        using hj hom homeomorphism_apply2 by fastforce\n    qed\n    show \"{x. \\<not> ((j \\<circ> f \\<circ> h) x = x \\<and> (j \\<circ> g \\<circ> h) x = x)} \\<subseteq> S\"\n      apply (clarsimp simp: jf jg hj)\n      using sub hj\n      apply (drule_tac c=\"h x\" in subsetD, force)\n      by (metis imageE)\n    have \"bounded (j ` {x. (~ (f x = x \\<and> g x = x))})\"\n      apply (rule bounded_linear_image [OF bou])\n      using \\<open>linear j\\<close> linear_conv_bounded_linear by auto\n    moreover\n    have *: \"{x. ~((j \\<circ> f \\<circ> h) x = x \\<and> (j \\<circ> g \\<circ> h) x = x)} = j ` {x. (~ (f x = x \\<and> g x = x))}\"\n      using hj apply (auto simp: jf jg image_iff, metis+)\n      done\n    ultimately show \"bounded {x. \\<not> ((j \\<circ> f \\<circ> h) x = x \\<and> (j \\<circ> g \\<circ> h) x = x)}\"\n      by metis\n    show \"\\<And>x. x \\<in> K \\<Longrightarrow> (j \\<circ> f \\<circ> h) x \\<in> U\"\n      using f hj by fastforce\n  qed\nqed\n\n\nproposition homeomorphism_grouping_points_exists_gen:\n  fixes S :: \"'a::euclidean_space set\"\n  assumes opeU: \"openin (subtopology euclidean S) U\"\n      and opeS: \"openin (subtopology euclidean (affine hull S)) S\"\n      and \"U \\<noteq> {}\" \"finite K\" \"K \\<subseteq> S\" and S: \"S \\<subseteq> T\" \"T \\<subseteq> affine hull S\" \"connected S\"\n  obtains f g where \"homeomorphism T T f g\" \"{x. (~ (f x = x \\<and> g x = x))} \\<subseteq> S\"\n                    \"bounded {x. (~ (f x = x \\<and> g x = x))}\" \"\\<And>x. x \\<in> K \\<Longrightarrow> f x \\<in> U\"\nproof (cases \"2 \\<le> aff_dim S\")\n  case True\n  have opeU': \"openin (subtopology euclidean (affine hull S)) U\"\n    using opeS opeU openin_trans by blast\n  obtain u where \"u \\<in> U\" \"u \\<in> S\"\n    using \\<open>U \\<noteq> {}\\<close> opeU openin_imp_subset by fastforce+\n  have \"infinite U\"\n    apply (rule infinite_openin [OF opeU \\<open>u \\<in> U\\<close>])\n    apply (rule connected_imp_perfect_aff_dim [OF \\<open>connected S\\<close> _ \\<open>u \\<in> S\\<close>])\n    using True apply simp\n    done\n  then obtain P where \"P \\<subseteq> U\" \"finite P\" \"card K = card P\"\n    using infinite_arbitrarily_large by metis\n  then obtain \\<gamma> where \\<gamma>: \"bij_betw \\<gamma> K P\"\n    using \\<open>finite K\\<close> finite_same_card_bij by blast\n  have \"\\<exists>f g. homeomorphism T T f g \\<and> (\\<forall>i \\<in> K. f(id i) = \\<gamma> i) \\<and>\n               {x. ~ (f x = x \\<and> g x = x)} \\<subseteq> S \\<and> bounded {x. ~ (f x = x \\<and> g x = x)}\"\n  proof (rule homeomorphism_moving_points_exists_gen [OF \\<open>finite K\\<close> _ _ True opeS S])\n    show \"\\<And>i. i \\<in> K \\<Longrightarrow> id i \\<in> S \\<and> \\<gamma> i \\<in> S\"\n      by (metis id_apply opeU openin_contains_cball subsetCE \\<open>P \\<subseteq> U\\<close> \\<open>bij_betw \\<gamma> K P\\<close> \\<open>K \\<subseteq> S\\<close> bij_betwE)\n    show \"pairwise (\\<lambda>i j. id i \\<noteq> id j \\<and> \\<gamma> i \\<noteq> \\<gamma> j) K\"\n      using \\<gamma> by (auto simp: pairwise_def bij_betw_def inj_on_def)\n  qed\n  then show ?thesis\n    using \\<gamma> \\<open>P \\<subseteq> U\\<close> bij_betwE by (fastforce simp add: intro!: that)\nnext\n  case False\n  with aff_dim_geq [of S] consider \"aff_dim S = -1\" | \"aff_dim S = 0\" | \"aff_dim S = 1\" by linarith\n  then show ?thesis\n  proof cases\n    assume \"aff_dim S = -1\"\n    then have \"S = {}\"\n      using aff_dim_empty by blast\n    then have \"False\"\n      using \\<open>U \\<noteq> {}\\<close> \\<open>K \\<subseteq> S\\<close> openin_imp_subset [OF opeU] by blast\n    then show ?thesis ..\n  next\n    assume \"aff_dim S = 0\"\n    then obtain a where \"S = {a}\"\n      using aff_dim_eq_0 by blast\n    then have \"K \\<subseteq> U\"\n      using \\<open>U \\<noteq> {}\\<close> \\<open>K \\<subseteq> S\\<close> openin_imp_subset [OF opeU] by blast\n    show ?thesis\n      apply (rule that [of id id])\n      using \\<open>K \\<subseteq> U\\<close> by (auto simp: continuous_on_id intro: homeomorphismI)\n  next\n    assume \"aff_dim S = 1\"\n    then have \"affine hull S homeomorphic (UNIV :: real set)\"\n      by (auto simp: homeomorphic_affine_sets)\n    then obtain h::\"'a\\<Rightarrow>real\" and j where homhj: \"homeomorphism (affine hull S) UNIV h j\"\n      using homeomorphic_def by blast\n    then have h: \"\\<And>x. x \\<in> affine hull S \\<Longrightarrow> j(h(x)) = x\" and j: \"\\<And>y. j y \\<in> affine hull S \\<and> h(j y) = y\"\n      by (auto simp: homeomorphism_def)\n    have connh: \"connected (h ` S)\"\n      by (meson Topological_Spaces.connected_continuous_image \\<open>connected S\\<close> homeomorphism_cont1 homeomorphism_of_subsets homhj hull_subset top_greatest)\n    have hUS: \"h ` U \\<subseteq> h ` S\"\n      by (meson homeomorphism_imp_open_map homeomorphism_of_subsets homhj hull_subset opeS opeU open_UNIV openin_open_eq)\n    have op: \"openin (subtopology euclidean (affine hull S)) U \\<Longrightarrow> open (h ` U)\" for U\n      using homeomorphism_imp_open_map [OF homhj]  by simp\n    have \"open (h ` U)\" \"open (h ` S)\"\n      by (auto intro: opeS opeU openin_trans op)\n    then obtain f g where hom: \"homeomorphism (h ` T) (h ` T) f g\"\n                 and f: \"\\<And>x. x \\<in> h ` K \\<Longrightarrow> f x \\<in> h ` U\"\n                 and sub: \"{x. \\<not> (f x = x \\<and> g x = x)} \\<subseteq> h ` S\"\n                 and bou: \"bounded {x. \\<not> (f x = x \\<and> g x = x)}\"\n      apply (rule homeomorphism_grouping_points_exists [of \"h ` U\" \"h ` S\" \"h ` K\" \"h ` T\"])\n      using assms by (auto simp: connh hUS)\n    have jf: \"\\<And>x. x \\<in> affine hull S \\<Longrightarrow> j (f (h x)) = x \\<longleftrightarrow> f (h x) = h x\"\n      by (metis h j)\n    have jg: \"\\<And>x. x \\<in> affine hull S \\<Longrightarrow> j (g (h x)) = x \\<longleftrightarrow> g (h x) = h x\"\n      by (metis h j)\n    have cont_hj: \"continuous_on T h\"  \"continuous_on Y j\" for Y\n      apply (rule continuous_on_subset [OF _ \\<open>T \\<subseteq> affine hull S\\<close>])\n      using homeomorphism_def homhj apply blast\n      by (meson continuous_on_subset homeomorphism_def homhj top_greatest)\n    define f' where \"f' \\<equiv> \\<lambda>x. if x \\<in> affine hull S then (j \\<circ> f \\<circ> h) x else x\"\n    define g' where \"g' \\<equiv> \\<lambda>x. if x \\<in> affine hull S then (j \\<circ> g \\<circ> h) x else x\"\n    show ?thesis\n    proof\n      show \"homeomorphism T T f' g'\"\n      proof\n        have \"continuous_on T (j \\<circ> f \\<circ> h)\"\n          apply (intro continuous_on_compose cont_hj)\n          using hom homeomorphism_def by blast\n        then show \"continuous_on T f'\"\n          apply (rule continuous_on_eq)\n          using \\<open>T \\<subseteq> affine hull S\\<close> f'_def by auto\n        have \"continuous_on T (j \\<circ> g \\<circ> h)\"\n          apply (intro continuous_on_compose cont_hj)\n          using hom homeomorphism_def by blast\n        then show \"continuous_on T g'\"\n          apply (rule continuous_on_eq)\n          using \\<open>T \\<subseteq> affine hull S\\<close> g'_def by auto\n        show \"f' ` T \\<subseteq> T\"\n        proof (clarsimp simp: f'_def)\n          fix x assume \"x \\<in> T\"\n          then have \"f (h x) \\<in> h ` T\"\n            by (metis (no_types) hom homeomorphism_def image_subset_iff subset_refl)\n          then show \"j (f (h x)) \\<in> T\"\n            using \\<open>T \\<subseteq> affine hull S\\<close> h by auto\n        qed\n        show \"g' ` T \\<subseteq> T\"\n        proof (clarsimp simp: g'_def)\n          fix x assume \"x \\<in> T\"\n          then have \"g (h x) \\<in> h ` T\"\n            by (metis (no_types) hom homeomorphism_def image_subset_iff subset_refl)\n          then show \"j (g (h x)) \\<in> T\"\n            using \\<open>T \\<subseteq> affine hull S\\<close> h by auto\n        qed\n        show \"\\<And>x. x \\<in> T \\<Longrightarrow> g' (f' x) = x\"\n          using h j hom homeomorphism_apply1 by (fastforce simp add: f'_def g'_def)\n        show \"\\<And>y. y \\<in> T \\<Longrightarrow> f' (g' y) = y\"\n          using h j hom homeomorphism_apply2 by (fastforce simp add: f'_def g'_def)\n      qed\n    next\n      show \"{x. \\<not> (f' x = x \\<and> g' x = x)} \\<subseteq> S\"\n        apply (clarsimp simp: f'_def g'_def jf jg)\n        apply (rule imageE [OF subsetD [OF sub]], force)\n        by (metis h hull_inc)\n    next\n      have \"bounded (j ` {x. (~ (f x = x \\<and> g x = x))})\"\n        apply (rule bounded_closure_image)\n        apply (rule compact_imp_bounded)\n        using bou by (auto simp: compact_continuous_image cont_hj)\n      moreover\n      have *: \"{x \\<in> affine hull S. j (f (h x)) \\<noteq> x \\<or> j (g (h x)) \\<noteq> x} = j ` {x. (~ (f x = x \\<and> g x = x))}\"\n        using h j by (auto simp: image_iff; metis)\n      ultimately have \"bounded {x \\<in> affine hull S. j (f (h x)) \\<noteq> x \\<or> j (g (h x)) \\<noteq> x}\"\n        by metis\n      then show \"bounded {x. \\<not> (f' x = x \\<and> g' x = x)}\"\n        by (simp add: f'_def g'_def Collect_mono bounded_subset)\n    next\n      show \"f' x \\<in> U\" if \"x \\<in> K\" for x\n      proof -\n        have \"U \\<subseteq> S\"\n          using opeU openin_imp_subset by blast\n        then have \"j (f (h x)) \\<in> U\"\n          using f h hull_subset that by fastforce\n        then show \"f' x \\<in> U\"\n          using \\<open>K \\<subseteq> S\\<close> S f'_def that by auto\n      qed\n    qed\n  qed\nqed\n\nsubsection\\<open>nullhomotopic mappings\\<close>\n\ntext\\<open> A mapping out of a sphere is nullhomotopic iff it extends to the ball.\nThis even works out in the degenerate cases when the radius is \\<open>\\<le>\\<close> 0, and\nwe also don't need to explicitly assume continuity since it's already implicit\nin both sides of the equivalence.\\<close>\n\nlemma nullhomotopic_from_lemma:\n  assumes contg: \"continuous_on (cball a r - {a}) g\"\n      and fa: \"\\<And>e. 0 < e\n               \\<Longrightarrow> \\<exists>d. 0 < d \\<and> (\\<forall>x. x \\<noteq> a \\<and> norm(x - a) < d \\<longrightarrow> norm(g x - f a) < e)\"\n      and r: \"\\<And>x. x \\<in> cball a r \\<and> x \\<noteq> a \\<Longrightarrow> f x = g x\"\n    shows \"continuous_on (cball a r) f\"\nproof (clarsimp simp: continuous_on_eq_continuous_within Ball_def)\n  fix x\n  assume x: \"dist a x \\<le> r\"\n  show \"continuous (at x within cball a r) f\"\n  proof (cases \"x=a\")\n    case True\n    then show ?thesis\n      by (metis continuous_within_eps_delta fa dist_norm dist_self r)\n  next\n    case False\n    show ?thesis\n    proof (rule continuous_transform_within [where f=g and d = \"norm(x-a)\"])\n      have \"\\<exists>d>0. \\<forall>x'\\<in>cball a r.\n                      dist x' x < d \\<longrightarrow> dist (g x') (g x) < e\" if \"e>0\" for e\n      proof -\n        obtain d where \"d > 0\"\n           and d: \"\\<And>x'. \\<lbrakk>dist x' a \\<le> r; x' \\<noteq> a; dist x' x < d\\<rbrakk> \\<Longrightarrow>\n                                 dist (g x') (g x) < e\"\n          using contg False x \\<open>e>0\\<close>\n          unfolding continuous_on_iff by (fastforce simp add: dist_commute intro: that)\n        show ?thesis\n          using \\<open>d > 0\\<close> \\<open>x \\<noteq> a\\<close>\n          by (rule_tac x=\"min d (norm(x - a))\" in exI)\n             (auto simp: dist_commute dist_norm [symmetric]  intro!: d)\n      qed\n      then show \"continuous (at x within cball a r) g\"\n        using contg False by (auto simp: continuous_within_eps_delta)\n      show \"0 < norm (x - a)\"\n        using False by force\n      show \"x \\<in> cball a r\"\n        by (simp add: x)\n      show \"\\<And>x'. \\<lbrakk>x' \\<in> cball a r; dist x' x < norm (x - a)\\<rbrakk>\n        \\<Longrightarrow> g x' = f x'\"\n        by (metis dist_commute dist_norm less_le r)\n    qed\n  qed\nqed\n\nproposition nullhomotopic_from_sphere_extension:\n  fixes f :: \"'M::euclidean_space \\<Rightarrow> 'a::real_normed_vector\"\n  shows  \"(\\<exists>c. homotopic_with (\\<lambda>x. True) (sphere a r) S f (\\<lambda>x. c)) \\<longleftrightarrow>\n          (\\<exists>g. continuous_on (cball a r) g \\<and> g ` (cball a r) \\<subseteq> S \\<and>\n               (\\<forall>x \\<in> sphere a r. g x = f x))\"\n         (is \"?lhs = ?rhs\")\nproof (cases r \"0::real\" rule: linorder_cases)\n  case less\n  then show ?thesis by simp\nnext\n  case equal\n  with continuous_on_const show ?thesis\n    apply (auto simp: homotopic_with)\n    apply (rule_tac x=\"\\<lambda>x. h (0, a)\" in exI)\n    apply (fastforce simp add:)\n    done\nnext\n  case greater\n  let ?P = \"continuous_on {x. norm(x - a) = r} f \\<and> f ` {x. norm(x - a) = r} \\<subseteq> S\"\n  have ?P if ?lhs using that\n  proof\n    fix c\n    assume c: \"homotopic_with (\\<lambda>x. True) (sphere a r) S f (\\<lambda>x. c)\"\n    then have contf: \"continuous_on (sphere a r) f\" and fim: \"f ` sphere a r \\<subseteq> S\"\n      by (auto simp: homotopic_with_imp_subset1 homotopic_with_imp_continuous)\n    show ?P\n      using contf fim by (auto simp: sphere_def dist_norm norm_minus_commute)\n  qed\n  moreover have ?P if ?rhs using that\n  proof\n    fix g\n    assume g: \"continuous_on (cball a r) g \\<and> g ` cball a r \\<subseteq> S \\<and> (\\<forall>xa\\<in>sphere a r. g xa = f xa)\"\n    then\n    show ?P\n      apply (safe elim!: continuous_on_eq [OF continuous_on_subset])\n      apply (auto simp: dist_norm norm_minus_commute)\n      by (metis dist_norm image_subset_iff mem_sphere norm_minus_commute sphere_cball subsetCE)\n  qed\n  moreover have ?thesis if ?P\n  proof\n    assume ?lhs\n    then obtain c where \"homotopic_with (\\<lambda>x. True) (sphere a r) S (\\<lambda>x. c) f\"\n      using homotopic_with_sym by blast\n    then obtain h where conth: \"continuous_on ({0..1::real} \\<times> sphere a r) h\"\n                    and him: \"h ` ({0..1} \\<times> sphere a r) \\<subseteq> S\"\n                    and h: \"\\<And>x. h(0, x) = c\" \"\\<And>x. h(1, x) = f x\"\n      by (auto simp: homotopic_with_def)\n    obtain b1::'M where \"b1 \\<in> Basis\"\n      using SOME_Basis by auto\n    have \"c \\<in> S\"\n      apply (rule him [THEN subsetD])\n      apply (rule_tac x = \"(0, a + r *\\<^sub>R b1)\" in image_eqI)\n      using h greater \\<open>b1 \\<in> Basis\\<close>\n       apply (auto simp: dist_norm)\n      done\n    have uconth: \"uniformly_continuous_on ({0..1::real} \\<times> (sphere a r)) h\"\n      by (force intro: compact_Times conth compact_uniformly_continuous)\n    let ?g = \"\\<lambda>x. h (norm (x - a)/r,\n                     a + (if x = a then r *\\<^sub>R b1 else (r / norm(x - a)) *\\<^sub>R (x - a)))\"\n    let ?g' = \"\\<lambda>x. h (norm (x - a)/r, a + (r / norm(x - a)) *\\<^sub>R (x - a))\"\n    show ?rhs\n    proof (intro exI conjI)\n      have \"continuous_on (cball a r - {a}) ?g'\"\n        apply (rule continuous_on_compose2 [OF conth])\n         apply (intro continuous_intros)\n        using greater apply (auto simp: dist_norm norm_minus_commute)\n        done\n      then show \"continuous_on (cball a r) ?g\"\n      proof (rule nullhomotopic_from_lemma)\n        show \"\\<exists>d>0. \\<forall>x. x \\<noteq> a \\<and> norm (x - a) < d \\<longrightarrow> norm (?g' x - ?g a) < e\" if \"0 < e\" for e\n        proof -\n          obtain d where \"0 < d\"\n             and d: \"\\<And>x x'. \\<lbrakk>x \\<in> {0..1} \\<times> sphere a r; x' \\<in> {0..1} \\<times> sphere a r; dist x' x < d\\<rbrakk>\n                        \\<Longrightarrow> dist (h x') (h x) < e\"\n            using uniformly_continuous_onE [OF uconth \\<open>0 < e\\<close>] by auto\n          have *: \"norm (h (norm (x - a) / r,\n                         a + (r / norm (x - a)) *\\<^sub>R (x - a)) - h (0, a + r *\\<^sub>R b1)) < e\"\n                   if \"x \\<noteq> a\" \"norm (x - a) < r\" \"norm (x - a) < d * r\" for x\n          proof -\n            have \"norm (h (norm (x - a) / r, a + (r / norm (x - a)) *\\<^sub>R (x - a)) - h (0, a + r *\\<^sub>R b1)) =\n                  norm (h (norm (x - a) / r, a + (r / norm (x - a)) *\\<^sub>R (x - a)) - h (0, a + (r / norm (x - a)) *\\<^sub>R (x - a)))\"\n              by (simp add: h)\n            also have \"... < e\"\n              apply (rule d [unfolded dist_norm])\n              using greater \\<open>0 < d\\<close> \\<open>b1 \\<in> Basis\\<close> that\n                by (auto simp: dist_norm divide_simps)\n            finally show ?thesis .\n          qed\n          show ?thesis\n            apply (rule_tac x = \"min r (d * r)\" in exI)\n            using greater \\<open>0 < d\\<close> by (auto simp: *)\n        qed\n        show \"\\<And>x. x \\<in> cball a r \\<and> x \\<noteq> a \\<Longrightarrow> ?g x = ?g' x\"\n          by auto\n      qed\n    next\n      show \"?g ` cball a r \\<subseteq> S\"\n        using greater him \\<open>c \\<in> S\\<close>\n        by (force simp: h dist_norm norm_minus_commute)\n    next\n      show \"\\<forall>x\\<in>sphere a r. ?g x = f x\"\n        using greater by (auto simp: h dist_norm norm_minus_commute)\n    qed\n  next\n    assume ?rhs\n    then obtain g where contg: \"continuous_on (cball a r) g\"\n                    and gim: \"g ` cball a r \\<subseteq> S\"\n                    and gf: \"\\<forall>x \\<in> sphere a r. g x = f x\"\n      by auto\n    let ?h = \"\\<lambda>y. g (a + (fst y) *\\<^sub>R (snd y - a))\"\n    have \"continuous_on ({0..1} \\<times> sphere a r) ?h\"\n      apply (rule continuous_on_compose2 [OF contg])\n       apply (intro continuous_intros)\n      apply (auto simp: dist_norm norm_minus_commute mult_left_le_one_le)\n      done\n    moreover\n    have \"?h ` ({0..1} \\<times> sphere a r) \\<subseteq> S\"\n      by (auto simp: dist_norm norm_minus_commute mult_left_le_one_le gim [THEN subsetD])\n    moreover\n    have \"\\<forall>x\\<in>sphere a r. ?h (0, x) = g a\" \"\\<forall>x\\<in>sphere a r. ?h (1, x) = f x\"\n      by (auto simp: dist_norm norm_minus_commute mult_left_le_one_le gf)\n    ultimately\n    show ?lhs\n      apply (subst homotopic_with_sym)\n      apply (rule_tac x=\"g a\" in exI)\n      apply (auto simp: homotopic_with)\n      done\n  qed\n  ultimately\n  show ?thesis by meson\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/Path_Connected.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473813156294, "lm_q2_score": 0.83973396967765, "lm_q1q2_score": 0.7325397294500762}}
{"text": "(* Title:      Formal Power Series Model of Kleene Algebra\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>Formal Power Series\\<close>\n\ntheory Formal_Power_Series\nimports Finite_Suprema Kleene_Algebra\nbegin\n\nsubsection \\<open>The Type of Formal Power Series\\<close>\n\ntext \\<open>Formal powerseries are functions from a free monoid into a\ndioid. They have applications in formal language theory, e.g.,\nweighted automata. As usual, we represent elements of a free monoid\nby lists.\n\nThis theory generalises Amine Chaieb's development of formal power\nseries as functions from natural numbers, which may be found in {\\em\nHOL/Library/Formal\\_Power\\_Series.thy}.\\<close>\n\ntypedef ('a, 'b) fps = \"{f::'a list \\<Rightarrow> 'b. True}\"\n  morphisms fps_nth Abs_fps\n  by simp\n\ntext \\<open>It is often convenient to reason about functions, and transfer\nresults to formal power series.\\<close>\n\nsetup_lifting type_definition_fps\n\ndeclare fps_nth_inverse [simp]\n\nnotation fps_nth (infixl \"$\" 75)\n\nlemma expand_fps_eq: \"p = q \\<longleftrightarrow> (\\<forall>n. p $ n = q $ n)\"\nby (simp add: fps_nth_inject [symmetric] fun_eq_iff)\n\nlemma fps_ext: \"(\\<And>n. p $ n = q $ n) \\<Longrightarrow> p = q\"\nby (simp add: expand_fps_eq)\n\nlemma fps_nth_Abs_fps [simp]: \"Abs_fps f $ n = f n\"\nby (simp add: Abs_fps_inverse)\n\n\nsubsection \\<open>Definition of the Basic Elements~0 and~1 and the Basic\nOperations of Addition and Multiplication\\<close>\n\ntext \\<open>The zero formal power series maps all elements of the monoid\n(all lists) to zero.\\<close>\n\ninstantiation fps :: (type,zero) zero\nbegin\n  definition zero_fps where\n    \"0 = Abs_fps (\\<lambda>n. 0)\"\n  instance ..\nend\n\nlemma fps_zero_nth [simp]: \"0 $ n = 0\"\nunfolding zero_fps_def by simp\n\ntext \\<open>The unit formal power series maps the monoidal unit (the empty\nlist) to one and all other elements to zero.\\<close>\n\ninstantiation fps :: (type,\"{one,zero}\") one\nbegin\n  definition one_fps where\n    \"1 = Abs_fps (\\<lambda>n. if n = [] then 1 else 0)\"\n  instance ..\nend\n\nlemma fps_one_nth_Nil [simp]: \"1 $ [] = 1\"\nunfolding one_fps_def by simp\n\nlemma fps_one_nth_Cons [simp]: \"1 $ (x # xs) = 0\"\nunfolding one_fps_def by simp\n\ntext \\<open>Addition of formal power series is the usual pointwise\naddition of functions.\\<close>\n\ninstantiation fps :: (type,plus) plus\nbegin\n  definition plus_fps where\n    \"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\"\nunfolding plus_fps_def by simp\n\ntext \\<open>This directly shows that formal power series form a\nsemilattice with zero.\\<close>\n\nlemma fps_add_assoc: \"((f::('a,'b::semigroup_add) fps) + g) + h = f + (g + h)\"\nunfolding plus_fps_def by (simp add: add.assoc)\n\nlemma fps_add_comm [simp]: \"(f::('a,'b::ab_semigroup_add) fps) + g = g + f\"\nunfolding plus_fps_def by (simp add: add.commute)\n\nlemma fps_add_idem [simp]: \"(f::('a,'b::join_semilattice) fps) + f = f\"\nunfolding plus_fps_def by simp\n\nlemma fps_zerol [simp]: \"(f::('a,'b::monoid_add) fps) + 0 = f\"\nunfolding plus_fps_def by simp\n\nlemma fps_zeror [simp]: \"0 + (f::('a,'b::monoid_add) fps) = f\"\nunfolding plus_fps_def by simp\n\ntext \\<open>The product of formal power series is convolution. The product\nof two formal powerseries at a list is obtained by splitting the list\ninto all possible prefix/suffix pairs, taking the product of the first\nseries applied to the first coordinate and the second series applied\nto the second coordinate of each pair, and then adding the results.\\<close>\n\ninstantiation fps :: (type,\"{comm_monoid_add,times}\") times\nbegin\n  definition times_fps where\n    \"f * g = Abs_fps (\\<lambda>n. \\<Sum>{f $ y * g $ z |y z. n = y @ z})\"\n  instance ..\nend\n\ntext \\<open>We call the set of all prefix/suffix splittings of a\nlist~@{term xs} the \\emph{splitset} of~@{term xs}.\\<close>\n\ndefinition splitset where\n  \"splitset xs \\<equiv> {(p, q). xs = p @ q}\"\n\ntext \\<open>Altenatively, splitsets can be defined recursively, which\nyields convenient simplification rules in Isabelle.\\<close>\n\nfun splitset_fun where\n  \"splitset_fun []       = {([], [])}\"\n| \"splitset_fun (x # xs) = insert ([], x # xs) (apfst (Cons x) ` splitset_fun xs)\"\n\nlemma splitset_consl:\n  \"splitset (x # xs) = insert ([], x # xs) (apfst (Cons x) ` splitset xs)\"\nby (auto simp add: image_def splitset_def) (metis append_eq_Cons_conv)+\n\nlemma splitset_eq_splitset_fun: \"splitset xs = splitset_fun xs\"\napply (induct xs)\n apply (simp add: splitset_def)\napply (simp add: splitset_consl)\ndone\n\ntext \\<open>The definition of multiplication is now more precise.\\<close>\n\nlemma fps_mult_var:\n  \"(f * g) $ n = \\<Sum>{f $ (fst p) * g $ (snd p) | p. p \\<in> splitset n}\"\nby (simp add: times_fps_def splitset_def)\n\nlemma fps_mult_image:\n  \"(f * g) $ n = \\<Sum>((\\<lambda>p. f $ (fst p) * g $ (snd p)) ` splitset n)\"\nby (simp only: Collect_mem_eq fps_mult_var fun_im)\n\ntext \\<open>Next we show that splitsets are finite and non-empty.\\<close>\n\nlemma splitset_fun_finite [simp]: \"finite (splitset_fun xs)\"\n  by (induct xs, simp_all)\n\nlemma splitset_finite [simp]: \"finite (splitset xs)\"\n  by (simp add: splitset_eq_splitset_fun)\n\nlemma split_append_finite [simp]: \"finite {(p, q). xs = p @ q}\"\n  by (fold splitset_def, fact splitset_finite)\n\nlemma splitset_fun_nonempty [simp]: \"splitset_fun xs \\<noteq> {}\"\n  by (cases xs, simp_all)\n\nlemma splitset_nonempty [simp]: \"splitset xs \\<noteq> {}\"\n  by (simp add: splitset_eq_splitset_fun)\n\ntext \\<open>We now proceed with proving algebraic properties of formal\npower series.\\<close>\n\nlemma fps_annil [simp]:\n  \"0 * (f::('a::type,'b::{comm_monoid_add,mult_zero}) fps) = 0\"\nby (rule fps_ext) (simp add: times_fps_def sum.neutral)\n\nlemma fps_annir [simp]:\n  \"(f::('a::type,'b::{comm_monoid_add,mult_zero}) fps) * 0 = 0\"\nby (simp add: fps_ext times_fps_def sum.neutral)\n\nlemma fps_distl:\n  \"(f::('a::type,'b::{join_semilattice_zero,semiring}) fps) * (g + h) = (f * g) + (f * h)\"\nby (simp add: fps_ext fps_mult_image distrib_left sum_fun_sum)\n\nlemma fps_distr:\n  \"((f::('a::type,'b::{join_semilattice_zero,semiring}) fps) + g) * h = (f * h) + (g * h)\"\nby (simp add: fps_ext fps_mult_image distrib_right sum_fun_sum)\n\ntext \\<open>The multiplicative unit laws are surprisingly tedious. For the\nproof of the left unit law we use the recursive definition, which we\ncould as well have based on splitlists instead of splitsets.\n\nHowever, a right unit law cannot simply be obtained along the lines of\nthis proofs. The reason is that an alternative recursive definition\nthat produces a unit with coordinates flipped would be needed. But\nthis is difficult to obtain without snoc lists. We therefore prove the\nright unit law more directly by using properties of suprema.\\<close>\n\nlemma fps_onel [simp]:\n  \"1 * (f::('a::type,'b::{join_semilattice_zero,monoid_mult,mult_zero}) fps) = f\"\nproof (rule fps_ext)\n  fix n :: \"'a list\"\n  show \"(1 * f) $ n = f $ n\"\n  proof (cases n)\n    case Nil thus ?thesis\n      by (simp add: times_fps_def)\n  next\n    case Cons thus ?thesis\n      by (simp add: fps_mult_image splitset_eq_splitset_fun image_comp one_fps_def comp_def image_constant_conv)\n  qed\nqed\n\nlemma fps_oner [simp]:\n  \"(f::('a::type,'b::{join_semilattice_zero,monoid_mult,mult_zero}) fps) * 1 = f\"\nproof (rule fps_ext)\n  fix n :: \"'a list\"\n  {\n    fix z :: 'b\n    have \"(f * 1) $ n \\<le> z \\<longleftrightarrow> (\\<forall>p \\<in> splitset n. f $ (fst p) * 1 $ (snd p) \\<le> z)\"\n      by (simp add: fps_mult_image sum_fun_image_sup)\n    also have \"... \\<longleftrightarrow> (\\<forall>a b. n = a @ b \\<longrightarrow> f $ a * 1 $ b \\<le> z)\"\n      unfolding splitset_def by simp\n    also have \"... \\<longleftrightarrow> (f $ n * 1 $ [] \\<le> z)\"\n      by (simp add: one_fps_def)\n    finally have \"(f * 1) $ n \\<le> z \\<longleftrightarrow> f $ n \\<le> z\"\n      by simp\n  }\n  thus \"(f * 1) $ n = f $ n\"\n    by (metis eq_iff)\nqed\n\ntext \\<open>Finally we prove associativity of convolution. This requires\nsplitting lists into three parts and rearranging these parts in two\ndifferent ways into splitsets. This rearrangement is captured by the\nfollowing technical lemma.\\<close>\n\nlemma splitset_rearrange:\n  fixes F :: \"'a list \\<Rightarrow> 'a list \\<Rightarrow> 'a list \\<Rightarrow> 'b::join_semilattice_zero\"\n  shows \"\\<Sum>{\\<Sum>{F (fst p) (fst q) (snd q) | q. q \\<in> splitset (snd p)} | p. p \\<in> splitset x} =\n         \\<Sum>{\\<Sum>{F (fst q) (snd q) (snd p) | q. q \\<in> splitset (fst p)} | p. p \\<in> splitset x}\"\n    (is \"?lhs = ?rhs\")\nproof -\n  {\n    fix z :: 'b\n    have \"?lhs \\<le> z \\<longleftrightarrow> (\\<forall>p q r. x = p @ q @ r \\<longrightarrow> F p q r \\<le> z)\"\n      by (simp only: fset_to_im sum_fun_image_sup splitset_finite)\n         (auto simp add: splitset_def)\n    hence \"?lhs \\<le> z \\<longleftrightarrow> ?rhs \\<le> z\"\n      by (simp only: fset_to_im sum_fun_image_sup splitset_finite)\n         (auto simp add: splitset_def)\n  }\n  thus ?thesis\n    by (simp add: eq_iff)\nqed\n\nlemma fps_mult_assoc: \"(f::('a::type,'b::dioid_one_zero) fps) * (g * h) = (f * g) * h\"\nproof (rule fps_ext)\n  fix n :: \"'a list\"\n  have \"(f * (g * h)) $ n = \\<Sum>{\\<Sum>{f $ (fst p) * g $ (fst q) * h $ (snd q) | q. q \\<in> splitset (snd p)} | p. p \\<in> splitset n}\"\n    by (simp add: fps_mult_image sum_sum_distl_fun mult.assoc)\n  also have \"... = \\<Sum>{\\<Sum>{f $ (fst q) * g $ (snd q) * h $ (snd p) | q. q \\<in> splitset (fst p)} | p. p \\<in> splitset n}\"\n    by (fact splitset_rearrange)\n  finally show \"(f * (g * h)) $ n = ((f * g) * h) $ n\"\n    by (simp add: fps_mult_image sum_sum_distr_fun mult.assoc)\nqed\n\n\nsubsection \\<open>The Dioid Model of Formal Power Series\\<close>\n\ntext \\<open>We can now show that formal power series with suitably\ndefined operations form a dioid. Many of the underlying properties\nalready hold in weaker settings, where the target algebra is a\nsemilattice or semiring. We currently ignore this fact.\\<close>\n\nsubclass (in dioid_one_zero) mult_zero\nproof\n  fix x :: 'a\n  show \"0 * x = 0\"\n    by (fact annil)\n  show \"x * 0 = 0\"\n    by (fact annir)\nqed\n\ninstantiation fps :: (type,dioid_one_zero) dioid_one_zero\nbegin\n\n  definition less_eq_fps where\n    \"(f::('a,'b) fps) \\<le> g \\<longleftrightarrow> f + g = g\"\n\n  definition less_fps where\n    \"(f::('a,'b) fps) < g \\<longleftrightarrow> f \\<le> g \\<and> f \\<noteq> g\"\n\n  instance\n  proof\n    fix f g h :: \"('a,'b) fps\"\n    show \"f + g + h = f + (g + h)\"\n      by (fact fps_add_assoc)\n    show \"f + g = g + f\"\n      by (fact fps_add_comm)\n    show \"f * g * h = f * (g * h)\"\n      by (metis fps_mult_assoc)\n    show \"(f + g) * h = f * h + g * h\"\n      by (fact fps_distr)\n    show \"1 * f = f\"\n      by (fact fps_onel)\n    show \"f * 1 = f\"\n      by (fact fps_oner)\n    show \"0 + f = f\"\n      by (fact fps_zeror)\n    show \"0 * f = 0\"\n      by (fact fps_annil)\n    show \"f * 0 = 0\"\n      by (fact fps_annir)\n    show \"f \\<le> g \\<longleftrightarrow> f + g = g\"\n      by (fact less_eq_fps_def)\n    show \"f < g \\<longleftrightarrow> f \\<le> g \\<and> f \\<noteq> g\"\n      by (fact less_fps_def)\n    show \"f + f = f\"\n      by (fact fps_add_idem)\n    show \"f * (g + h) = f \\<cdot> g + f \\<cdot> h\"\n      by (fact fps_distl)\n  qed\n\nend (* instantiation *)\n\nlemma expand_fps_less_eq: \"(f::('a,'b::dioid_one_zero) fps) \\<le> g \\<longleftrightarrow> (\\<forall>n. f $ n \\<le> g $ n)\"\nby (simp add: expand_fps_eq less_eq_def less_eq_fps_def)\n\n\nsubsection \\<open>The Kleene Algebra Model of Formal Power Series\\<close>\n\ntext \\<open>There are two approaches to define the Kleene star. The first\none defines the star for a certain kind of (so-called proper) formal\npower series into a semiring or dioid. The second one, which is more\ninteresting in the context of our algebraic hierarchy, shows that\nformal power series into a Kleene algebra form a Kleene algebra. We\nhave only formalised the latter approach.\\<close>\n\nlemma Sum_splitlist_nonempty:\n  \"\\<Sum>{f ys zs |ys zs. xs = ys @ zs} = ((f [] xs)::'a::join_semilattice_zero) + \\<Sum>{f ys zs |ys zs. xs = ys @ zs \\<and> ys \\<noteq> []}\"\nproof -\n  have \"{f ys zs |ys zs. xs = ys @ zs} = {f ys zs |ys zs. xs = ys @ zs \\<and> ys = []} \\<union> {f ys zs |ys zs. xs = ys @ zs \\<and> ys \\<noteq> []}\"\n    by blast\n  thus ?thesis using [[simproc add: finite_Collect]]\n    by (simp add: sum.insert)\nqed\n\nlemma (in left_kleene_algebra) add_star_eq:\n  \"x + y \\<cdot> y\\<^sup>\\<star> \\<cdot> x = y\\<^sup>\\<star> \\<cdot> x\"\nby (metis add.commute mult_onel star2 star_one troeger)\n\ndeclare rev_conj_cong[fundef_cong]\n  \\<comment> \\<open>required for the function package to prove termination of @{term star_fps_rep}\\<close>\n\nfun star_fps_rep where\n  star_fps_rep_Nil: \"star_fps_rep f [] = (f [])\\<^sup>\\<star>\"\n| star_fps_rep_Cons: \"star_fps_rep f n = (f [])\\<^sup>\\<star> \\<cdot> \\<Sum>{f y \\<cdot> star_fps_rep f z |y z. n = y @ z \\<and> y \\<noteq> []}\"\n\ninstantiation fps :: (type,kleene_algebra) kleene_algebra\nbegin\n\n  text \\<open>We first define the star on functions, where we can use\n  Isabelle's package for recursive functions, before lifting the\n  definition to the type of formal power series.\n\n  This definition of the star is from an unpublished manuscript by\n  Esik and Kuich.\\<close>\n\n  lift_definition star_fps :: \"('a, 'b) fps \\<Rightarrow> ('a, 'b) fps\" is star_fps_rep ..\n\n  lemma star_fps_Nil [simp]: \"f\\<^sup>\\<star> $ [] = (f $ [])\\<^sup>\\<star>\"\n  by (simp add: star_fps_def)\n\n  lemma star_fps_Cons [simp]: \"f\\<^sup>\\<star> $ (x # xs) = (f $ [])\\<^sup>\\<star> \\<cdot> \\<Sum>{f $ y \\<cdot> f\\<^sup>\\<star> $ z |y z. x # xs = y @ z \\<and> y \\<noteq> []}\"\n  by (simp add: star_fps_def)\n\n  instance\n  proof\n    fix f g h :: \"('a,'b) fps\"  \n    have \"1 + f \\<cdot> f\\<^sup>\\<star> = f\\<^sup>\\<star>\"\n      apply (rule fps_ext)\n      apply (case_tac n)\n       apply (auto simp add: times_fps_def)\n      apply (simp add: add_star_eq mult.assoc[THEN sym] Sum_splitlist_nonempty)\n      apply (simp add: add_star_eq join.sup_commute)\n    done\n    thus \"1 + f \\<cdot> f\\<^sup>\\<star> \\<le> f\\<^sup>\\<star>\"\n      by (metis order_refl)\n    have \"f \\<cdot> g \\<le> g \\<longrightarrow> f\\<^sup>\\<star> \\<cdot> g \\<le> g\"\n      proof\n        assume \"f \\<cdot> g \\<le> g\"\n        hence 1: \"\\<And>u v. f $ u \\<cdot> g $ v \\<le> g $ (u @ v)\"\n          using [[simproc add: finite_Collect]]\n          apply (simp add: expand_fps_less_eq)\n          apply (drule_tac x=\"u @ v\" in spec)\n          apply (simp add: times_fps_def)\n          apply (auto elim!: sum_less_eqE)\n        done\n        hence 2: \"\\<And>v. (f $ []) \\<^sup>\\<star> \\<cdot> g $ v \\<le> g $ v\"\n          apply (subgoal_tac \"f $ [] \\<cdot> g $ v \\<le> g $ v\")\n           apply (metis star_inductl_var)\n          apply (metis append_Nil)\n        done\n        show \"f\\<^sup>\\<star> \\<cdot> g \\<le> g\"\n          using [[simproc add: finite_Collect]]\n          apply (auto intro!: sum_less_eqI simp add: expand_fps_less_eq times_fps_def)\n          apply (induct_tac \"y\" rule: length_induct)\n          apply (case_tac \"xs\")\n           apply (simp add: \"2\")\n          using \"2\" apply (auto simp add: mult.assoc sum_distr)\n          apply (rule_tac y=\"(f $ [])\\<^sup>\\<star> \\<cdot> g $ (a # list @ z)\" in order_trans)\n           prefer 2\n           apply (rule \"2\")\n          apply (auto intro!: mult_isol[rule_format] sum_less_eqI)\n          apply (drule_tac x=\"za\" in spec)\n          apply (drule mp)\n           apply (metis append_eq_Cons_conv length_append less_not_refl2 add.commute not_less_eq trans_less_add1)\n          apply (drule_tac z=\"f $ y\" in mult_isol[rule_format])\n          apply (auto elim!: order_trans simp add: mult.assoc)\n          apply (metis \"1\" append_Cons append_assoc)\n        done\n      qed\n    thus \"h + f \\<cdot> g \\<le> g \\<Longrightarrow> f\\<^sup>\\<star> \\<cdot> h \\<le> g\"\n      by (metis (no_types, lifting) distrib_left join.sup.bounded_iff less_eq_def)\n    have \"g \\<cdot> f \\<le> g \\<longrightarrow> g \\<cdot> f\\<^sup>\\<star> \\<le> g\"\n      \\<comment> \\<open>this property is dual to the previous one; the proof is slightly different\\<close>\n      proof\n        assume \"g \\<cdot> f \\<le> g\"\n        hence 1: \"\\<And>u v. g $ u \\<cdot> f $ v \\<le> g $ (u @ v)\"\n          using [[simproc add: finite_Collect]]\n          apply (simp add: expand_fps_less_eq)\n          apply (drule_tac x=\"u @ v\" in spec)\n          apply (simp add: times_fps_def)\n          apply (auto elim!: sum_less_eqE)\n        done\n        hence 2: \"\\<And>u. g $ u \\<cdot> (f $ [])\\<^sup>\\<star> \\<le> g $ u\"\n          apply (subgoal_tac \"g $ u \\<cdot> f $ [] \\<le> g $ u\")\n           apply (metis star_inductr_var)\n          apply (metis append_Nil2)\n        done\n        show \"g \\<cdot> f\\<^sup>\\<star> \\<le> g\"\n          using [[simproc add: finite_Collect]]\n          apply (auto intro!: sum_less_eqI simp add: expand_fps_less_eq times_fps_def)\n          apply (rule_tac P=\"\\<lambda>y. g $ y \\<cdot> f\\<^sup>\\<star> $ z \\<le> g $ (y @ z)\" and x=\"y\" in allE)\n           prefer 2\n           apply assumption\n          apply (induct_tac \"z\" rule: length_induct)\n          apply (case_tac \"xs\")\n           apply (simp add: \"2\")\n          apply (auto intro!: sum_less_eqI simp add: sum_distl)\n          apply (rule_tac y=\"g $ x \\<cdot> f $ yb \\<cdot> f\\<^sup>\\<star> $ z\" in order_trans)\n           apply (simp add: \"2\" mult.assoc[THEN sym] mult_isor)\n          apply (rule_tac y=\"g $ (x @ yb) \\<cdot> f\\<^sup>\\<star> $ z\" in order_trans)\n           apply (simp add: \"1\" mult_isor)\n          apply (drule_tac x=\"z\" in spec)\n          apply (drule mp)\n           apply (metis append_eq_Cons_conv length_append less_not_refl2 add.commute not_less_eq trans_less_add1)\n          apply (metis append_assoc)\n        done\n      qed\n    thus \"h + g \\<cdot> f \\<le> g \\<Longrightarrow> h \\<cdot> f\\<^sup>\\<star> \\<le> g\"\n      by (metis (no_types, lifting) distrib_right' join.sup.bounded_iff order_prop)\n  qed\n\nend (* instantiation *)\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/Formal_Power_Series.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339676722393, "lm_q2_score": 0.8723473796562744, "lm_q1q2_score": 0.7325397263072446}}
{"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 MainRLT\nbegin\n\ntext \\<open>\n  Combinator terms do not have free variables.\n  Example taken from @{cite camilleri92}.\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": "dtraytel", "repo": "HOLRLT", "sha": "e9029da59bb3af0c835604a65308498f9696a364", "save_path": "github-repos/isabelle/dtraytel-HOLRLT", "path": "github-repos/isabelle/dtraytel-HOLRLT/HOLRLT-e9029da59bb3af0c835604a65308498f9696a364/HOLRLT/Induct/Comb.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8397339596505965, "lm_q2_score": 0.8723473663814338, "lm_q1q2_score": 0.7325397081622511}}
{"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\u00f6der-Bernstein Theorem, etc.\\<close>\n\ntheory Set_Theory\nimports MainRLT\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\u00f6der-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": "dtraytel", "repo": "HOLRLT", "sha": "e9029da59bb3af0c835604a65308498f9696a364", "save_path": "github-repos/isabelle/dtraytel-HOLRLT", "path": "github-repos/isabelle/dtraytel-HOLRLT/HOLRLT-e9029da59bb3af0c835604a65308498f9696a364/HOLRLT/ex/Set_Theory.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8539127641048443, "lm_q2_score": 0.8577681049901037, "lm_q1q2_score": 0.7324591334930737}}
{"text": "theory topological_dynamics imports continuous   begin\n\ndefinition (in topological_space )\n  covering ::\"'a set set \\<Rightarrow> bool\"where\n \"covering C \\<longleftrightarrow> (\\<Union>C = X \\<and> C \\<subseteq> Pow X ) \"\n\ndefinition (in topological_space)\n  open_covering ::\"'a set set \\<Rightarrow> bool\" where\n  \"open_covering C \\<longleftrightarrow> (covering C \\<and>  (\\<forall>c\\<in>C. (open_set c)))\"\n\ndefinition (in topological_space)\n  compact where\n  \"compact \\<longleftrightarrow> ( \\<forall>C. (open_covering C)\\<longrightarrow>  (\\<exists>A. ( A \\<subseteq> C   \\<and>  \\<Union>A = X \\<and>  finite A )) )\"\n  \nthm  topological_space.compact_def\n\n\nlocale Group =\n  fixes G\n  fixes f \n  fixes e\n  fixes f_inv\n  assumes G1: \"e\\<in> G\"\n    and   G2: \"\\<forall>x\\<in>G. f(x,e) = x \"  \n    and   G3: \"\\<forall>x\\<in>G. f(e,x) = x\"\n    and   G4: \"f: G \\<times> G \\<rightarrow> G\"\n    and   G5: \"f_inv: G \\<rightarrow> G\"\n    and   G6: \"\\<forall>x\\<in>G. \\<forall>y\\<in>G. \\<forall>z\\<in>G. f(f(x,y),z)=f(x,f(y,z))\"\n    and   G7: \"\\<forall>x\\<in>G. f(x,f_inv(x))=e\"\n    and   G8: \"\\<forall>x\\<in>G. f(f_inv(x),x)=e\"\nthm Group_def\n(*  this is Tx is top\ndefinition product_topology_base where\n   \"product_topology_base Tx Ty \\<equiv>{u. \\<forall>x\\<in>Tx. \\<forall>y\\<in>Ty. ( (u=(x \\<times> y)) \\<and>  (topological_space (\\<Union>Tx) Tx) \\<and>  (topological_space (\\<Union>Ty) Ty))  \n\n}\"*)\n\ndefinition product_topology_base where\n   \"product_topology_base Tx Ty \\<equiv>{b. \\<forall>x\\<in>Tx. \\<forall>y\\<in>Ty.  (b=(x \\<times> y)) }\"\n\n\ndefinition\n  \"product_topology Tx Ty  \\<equiv>  {t.  \\<forall>p \\<in> Pow(product_topology_base Tx Ty ). t=\\<Union>p}\"\n\n\nlocale topological_group = topological_space +\n  fixes f\n  fixes e\n  fixes f_inv\n  assumes tg1:\"Group X f e f_inv\"\n   and    tg2:\"continuous f  (X\\<times>X) (product_topology T T) X T\"\n   and    tg3:\"continuous f_inv X T X T\"\nthm topological_group_def\n\nthm topological_group_axioms_def\n\n\nlocale topological_transformation_group = topological_group +\n  fixes M\n  fixes Tm\n  fixes mappi (\"\\<phi>  _\" 89)\n  assumes istop :\"topological_space M Tm\"\n  assumes map1 : \"mappi : (X  \\<times>  M \\<rightarrow>  M)\"\n  assumes ident : \"\\<forall>x \\<in> M.  \\<phi> (x, e) = x\"\n  assumes Homom:   \"\\<forall>x\\<in>M. \\<forall>g1\\<in>X. \\<forall>g2\\<in>X. \\<phi>(g1,\\<phi>(g2,x) ) = \\<phi>(f(g1,g2),x)\"\n  assumes Conti:   \"continuous f  (X\\<times>M) (product_topology T Tm ) M Tm\" \n\nlocale hausdorff_space = topological_space +\n      assumes t1 : \"!! x1 x2. [|x1: X; x2: X; x1 ~= x2 |]\n                    ==> EX U V. (neighborhood U x1)  &\n                            (neighborhood V x2)  &\n                             x2 ~: U & x1 ~: V \"\nthm hausdorff_space_def\nthm topological_space.compact_def\n\nlocale topological_dynamic_system =\n    topological_transformation_group +\n  assumes iscompact :\"topological_space.compact M Tm\"\n  assumes map1 : \"hausdorff_space M Tm\"\n\nthm topological_dynamic_system_def\n\ndefinition (in topological_transformation_group )\n  invariant_set where\n  \"invariant_set A \\<longleftrightarrow> (A \\<subseteq> M \\<and> (\\<forall>g \\<in> X.  {x. \\<exists>a\\<in>A. x = \\<phi>(g,a)} \\<subseteq> A)) \" \n\n\n\nlemma forall_conjI:\"\\<lbrakk> (\\<forall>x\\<in>X. (P x)); (\\<forall>x\\<in>X. (Q x))\\<rbrakk> \\<Longrightarrow> \\<forall>x\\<in>X. (P x) \\<and> (Q x)\"\napply blast\ndone\n\nlemma \"\\<lbrakk>\\<forall>x\\<in>X. (P x) \\<and> (Q x)\\<rbrakk> \\<Longrightarrow> (\\<forall>x\\<in>X. (P x)) \\<and> (\\<forall>x\\<in>X. (Q x))\"\napply blast\ndone \n\nlemma  \"\\<lbrakk>A \\<subseteq> M; B \\<subseteq> M\\<rbrakk> \\<Longrightarrow> A \\<inter> B \\<subseteq> M\"\napply blast\ndone \nlemma (in topological_transformation_group)\nint_is_inv:\n\"\\<lbrakk> invariant_set A; invariant_set B \\<rbrakk> \\<Longrightarrow> invariant_set (A \\<inter> B)\"\napply (simp add :invariant_set_def)\napply (rule conjI)\napply (drule_tac  conjunct1)\napply (drule_tac  conjunct1)\napply (blast 1)\napply (drule_tac conjunct2)\napply (drule_tac  conjunct2)\napply (rule forall_conjI)\napply blast\napply (rotate_tac 1)\napply blast\ndone\n(*\nlemma  (in topological_transformation_group) closure_is_invariant:\n  \"invariant_set A ==> invariant_set (closure A) \"\napply (simp add :closure_def invariant_set_def)\napply (rule conjI)\napply (drule_tac conjunct1)\napply (drule_tac conjunct1)\napply (simp add:Lattices.lower_semilattice_class.le_infI1)\napply (drule_tac conjunct2)\napply (drule_tac conjunct2)\napply (rule forall_conjI)\napply blast\napply (rotate_tac 1)\napply blast\n*)\n\nlemma (in topological_transformation_group)\nint_is_inv1:\nassumes a1: \"invariant_set A\"\n and  a2:\" invariant_set B\"\nshows \"invariant_set (A\\<inter>B)\"\nproof-\n from a1 have s1:\"A \\<subseteq> M\" by (simp add:invariant_set_def)\n from a2 have s2:\"B \\<subseteq> M\" by (simp add:invariant_set_def)\n from s1 s2 have s3: \"A \\<inter> B \\<subseteq> M\" by blast\n from a1 have s4:\"\\<forall>g \\<in> X.  {x. \\<exists> a\\<in>A. x = \\<phi>(g,a)} \\<subseteq> A\" by (simp add:invariant_set_def)\n from a2 have s5:\"\\<forall>g \\<in> X.  {x. \\<exists> a\\<in>B. x = \\<phi>(g,a)} \\<subseteq> B\" by (simp add:invariant_set_def)\n from s4 s5 have s6:\"\\<forall>g \\<in> X. {x. \\<exists> a\\<in>A. x = \\<phi>(g,a)} \\<subseteq> A  \\<and>  {x. \\<exists>a\\<in>B. x = \\<phi>(g,a)} \\<subseteq> B\" by (simp) \n from s4 have s7:\"\\<And> g. g \\<in> X \\<Longrightarrow>  {x. \\<exists>a\\<in>A \\<inter> B. x = \\<phi>(g,a)} \\<subseteq>  A\"  apply blast done \n from s5 have s8:\"\\<And> g. g \\<in> X \\<Longrightarrow>  {x. \\<exists>a\\<in>A \\<inter> B. x = \\<phi>(g,a)} \\<subseteq>  B\"  apply blast done \n from s7 s8 have s9:\"\\<And> g. g \\<in> X \\<Longrightarrow>  {x. \\<exists>a\\<in>A \\<inter> B. x = \\<phi>(g,a)} \\<subseteq>  A \\<inter> B\" apply auto done\n from s1 s2 s9 show ?thesis apply (simp add:invariant_set_def)  apply blast done\nqed\n\nlemma dddd:\"y \\<in> {x. \\<exists> a\\<in> A\\<union> B . x =P a} \\<Longrightarrow>  y \\<in> {x. \\<exists> a\\<in> A. x =P a} \\<or> y \\<in> {x. \\<exists> a\\<in> B. x =P a}\"\napply blast\ndone\n\nlemma eeee:\"{x. \\<exists> a\\<in> A\\<union> B . x =P a}\\<subseteq>  {x. \\<exists> a\\<in> A. x =P a} \\<union> {x. \\<exists> a\\<in> B. x =P a}\"\napply auto\ndone\n\n\nlemma (in topological_transformation_group)\nunion_is_inv:\nassumes a1: \"invariant_set A\"\n and  a2:\" invariant_set B\"\nshows \"invariant_set (A \\<union> B)\"\nproof-\n from a1 have s1:\"A \\<subseteq> M\" by (simp add:invariant_set_def)\n from a2 have s2:\"B \\<subseteq> M\" by (simp add:invariant_set_def)\n from s1 s2 have s3: \"A \\<union>  B \\<subseteq> M\" by blast\n from a1 have s4:\"\\<And>g. g \\<in> X \\<Longrightarrow>   {x. \\<exists> a\\<in>A. x = \\<phi>(g,a)} \\<subseteq> A\" by (simp add:invariant_set_def)\n from a2 have s5:\"\\<And>g. g \\<in> X \\<Longrightarrow> {x. \\<exists> a\\<in>B. x = \\<phi>(g,a)} \\<subseteq> B\" by (simp add:invariant_set_def)\n from s4 s5 have s6:\"\\<And>g. g \\<in> X \\<Longrightarrow>  {x. \\<exists> a\\<in>A. x = \\<phi>(g,a)} \\<subseteq> A  \\<and>  {x. \\<exists>a\\<in>B. x = \\<phi>(g,a)} \\<subseteq> B\" by (simp)\n from s6 have s7: \"\\<And>g. g \\<in> X \\<Longrightarrow>  {x. \\<exists> a\\<in>A \\<union> B. x = \\<phi>(g,a)} \\<subseteq>  {x. \\<exists> a\\<in>A. x = \\<phi>(g,a)} \\<union> {x. \\<exists> a\\<in>B. x = \\<phi>(g,a)}\" \n by blast\n from s7 s6 have s8:\"\\<And> g. g \\<in> X \\<Longrightarrow>  {x. \\<exists>a\\<in>A \\<union>  B. x = \\<phi>(g,a)} \\<subseteq>  A \\<union> B\" \n   proof- \n     fix g assume a8_1: \"g \\<in> X\"\n     show \"{x. \\<exists>a\\<in>A \\<union>  B. x = \\<phi>(g,a)} \\<subseteq>  A \\<union> B\"\n     proof- \n        from a8_1  s7 have s8_1: \"{x. \\<exists> a\\<in>A \\<union> B. x = \\<phi>(g,a)} \\<subseteq>  {x. \\<exists> a\\<in>A. x = \\<phi>(g,a)} \\<union> {x. \\<exists> a\\<in>B. x = \\<phi>(g,a)}\" apply simp done\n        from a8_1 s4 have s8_2:\" {x. \\<exists> a\\<in>A. x = \\<phi>(g,a)} \\<subseteq> A\" by simp\n        from a8_1 s5 have s8_3:\" {x. \\<exists> a\\<in>B. x = \\<phi>(g,a)} \\<subseteq> B\" by simp\n        from s8_1 s8_2 s8_3 show ?thesis by blast\n qed\nqed        \n from s3 s8 show ?thesis apply (simp add:invariant_set_def)  done \nqed\n\n\n\n(*\n\n(*\nlemma  (in topological_transformation_group) closure_is_invariant:\n  \"invariant_set A ==> invariant_set (closure A) \"\napply (simp add :closure_def invariant_set_def)\napply (rule conjI)\napply (drule_tac conjunct1)\napply (drule_tac conjunct1)\napply (simp add:Lattices.lower_semilattice_class.le_infI1)\napply (drule_tac conjunct2)\napply (drule_tac conjunct2)\napply (rule forall_conjI)\napply blast\napply (rotate_tac 1)\napply blast\n*)\n*)\n(*\nlemma \"\\<lbrakk> A\\<Longrightarrow>B \\<rbrakk> \\<Longrightarrow>  A\\<longrightarrow> B\" impI *)\n\nthm topological_transformation_group_def\nlemma (in topological_transformation_group)\n \" \\<lbrakk>g \\<in> X; x\\<in> M \\<rbrakk> \\<Longrightarrow> \\<phi> (g, x) \\<in> M\"\napply (insert map1)\napply blast\ndone\n\nlemma (in topological_transformation_group)\n\"\\<lbrakk> g\\<in>X; h= (\\<lambda>x. \\<phi>(g,x)) \\<rbrakk> \\<Longrightarrow> (h: M\\<rightarrow>M)\"\napply (insert map1)\napply blast\ndone\n\ndefinition orbit where\n  \"orbit x G = {g}\"\n\ndefinition product1 where\n  \"product1 A B \\<equiv> (A \\<times> B) \"\n\n\n\ndefinition product2 where\n  \"product2 A B \\<equiv> {(product1 a b). ( a \\<subseteq> A  \\<and> b \\<subseteq> B)} \"\n\n\n(*lemma \"\\<lbrakk> A\\<subseteq> B; C \\<subseteq> D \\<rbrakk> \\<Longrightarrow> (A \\<times> C) \\<subseteq> (B \\<times> D)\"\n*)\n\n\nthm times_def\n\ndefinition ProductTopology where\n  \"ProductTopology T S \\<equiv>  {\\<Union>W. W \\<in> Pow(ProductCollection T S)}\"\n\ndefinition  product_topology  where\n \"product X Y =\"\nlemma \"\\<lbrakk> topological_space X Tx;topological_space Y Ty \\<rbrakk> \\<Longrightarrow> \"\n\nlocale \n(*\n  defines prodtop_def [simp]: \"$\\tau \\equiv$ ProductTopology(T,T)\"\n  fixes f\n  assumes isgroup: \"IsAgroup(G,f)\"\n  assumes isconti: \"IsContinuous($\\tau$,T,f)\"\n  assumes invisconti: \"IsContinuous(T,T,GroupInv(G,f))\"*)\n\n(*  defines G_def [simp]: \"G $\\equiv \\bigcup$ T\"\n  fixes prodtop (\"$\\tau$\")\n  defines prodtop_def [simp]: \"$\\tau \\equiv$ ProductTopology(T,T)\"\n  fixes f\n  assumes isgroup: \"IsAgroup(G,f)\"\n  assumes isconti: \"IsContinuous($\\tau$,T,f)\"\n  assumes invisconti: \"IsContinuous(T,T,GroupInv(G,f))\"*)\n\nlemma \"\\<lbrakk> topological_space X T ;\n         Y = (X \\<times> X); \n         Ty = (ProductTopology T T) \\<rbrakk> \\<Longrightarrow> topological_space Y Ty \"\napply (si)\n\ndefinition product_topology1 where\n   \"product_topology1 X Tx  Y Ty \\<equiv> \\<Union>{u. \\<exists>x\\<in>Tx. \\<exists>y\\<in>Ty. ( (u=(x \\<times> y)) \\<and>  \n                (topological_space X  Tx) \\<and> \n                 (topological_space Y Ty))  }\"*)\n(*\nlemma \"\\<lbrakk> topological_space X  (T::'a set set) ;Y = (X \\<times> X) \\<rbrakk> \\<Longrightarrow> (product_topology1 T T) \\<subseteq> Pow Y  \"\n\nlemma \"\\<lbrakk> topological_space X  T ;\n          Y = (X \\<times> X) ; \n          Ty = Pow Y\n       \\<rbrakk> \\<Longrightarrow>  Y \\<in> Ty\"\n\nlemma \"\\<lbrakk> topological_space X  T ;\n     orbit     Y = (X \\<times> X) ; \n          Ty = (product_topology1 X T X T ) \n       \\<rbrakk> \\<Longrightarrow> topological_space Y Ty \"\napply (simp add:product_topology_def topological_space_def)\n\n\nend", "meta": {"author": "JianlinWang", "repo": "topology", "sha": "843567e1368d8c9e912e4395b3679ec8ae0b21b7", "save_path": "github-repos/isabelle/JianlinWang-topology", "path": "github-repos/isabelle/JianlinWang-topology/topology-843567e1368d8c9e912e4395b3679ec8ae0b21b7/toplogical_dynamics.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094060543487, "lm_q2_score": 0.8198933425148214, "lm_q1q2_score": 0.7324184348298298}}
{"text": "(*\n    $Id: ex.thy,v 1.3 2011/06/28 18:11:39 webertj Exp $\n    Author: Stefan Berghofer\n*)\n\nheader {* Binary Decision Diagrams *}\n\n(*<*) theory ex imports Main begin (*>*)\n\ntext {*\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*}\n\ndatatype bdd = Leaf bool | Branch bdd bdd\n\ntext {*\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*}\n\nconsts eval :: \"(nat \\<Rightarrow> bool) \\<Rightarrow> nat \\<Rightarrow> bdd \\<Rightarrow> bool\"\n\ntext {*\nthat evaluates a BDD under a given variable assignment, beginning at a variable\nwith a given index.\n*}\n\n\ntext {*\n{\\bf Exercise 2:} Define two functions\n*}\n\nconsts\n  bdd_unop :: \"(bool \\<Rightarrow> bool) \\<Rightarrow> bdd \\<Rightarrow> bdd\"\n  bdd_binop :: \"(bool \\<Rightarrow> bool \\<Rightarrow> bool) \\<Rightarrow> bdd \\<Rightarrow> bdd \\<Rightarrow> bdd\"\n\ntext {*\nfor the application of unary and binary operators to BDDs, and prove their\ncorrectness.\n*}\n\n\ntext {*\nNow use @{term \"bdd_unop\"} and @{term \"bdd_binop\"} to define\n*}\n\nconsts\n  bdd_and :: \"bdd \\<Rightarrow> bdd \\<Rightarrow> bdd\"\n  bdd_or :: \"bdd \\<Rightarrow> bdd \\<Rightarrow> bdd\"\n  bdd_not :: \"bdd \\<Rightarrow> bdd\"\n  bdd_xor :: \"bdd \\<Rightarrow> bdd \\<Rightarrow> bdd\"\n\ntext {*\nand show correctness.\n*}\n\n\ntext {*\nFinally, define a function\n*}\n\nconsts bdd_var :: \"nat \\<Rightarrow> bdd\"\n\ntext {*\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*}\n\ntext_raw {* \\begin{minipage}[t]{0.45\\textwidth} *}\n \ntext{*\n{\\bf Example:} instead of\n*}\n\nlemma \"P (b::bdd) x\" \napply (induct b) (*<*) oops (*>*)\n\ntext_raw {* \\end{minipage} *}\ntext_raw {* \\begin{minipage}[t]{0.45\\textwidth} *}   \n\ntext {* Strengthening: *}\n\nlemma \"\\<forall>x. P (b::bdd) x\"\napply (induct b) (*<*) oops (*>*)  \n\ntext_raw {* \\end{minipage} \\\\[0.5cm]*} \n\n\ntext {*\n{\\bf Exercise 3:} Recall the following data type of propositional formulae\n(cf.\\ the exercise on ``Representation of Propositional Formulae by\nPolynomials'')\n*}\n\ndatatype form = T | Var nat | And form form | Xor form form\n\ntext {*\ntogether with the evaluation function @{text \"evalf\"}:\n*}\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\ntext {*\nDefine a function\n*}\n\nconsts mk_bdd :: \"form \\<Rightarrow> bdd\"\n\ntext {*\nthat transforms a propositional formula of type @{typ \"form\"} into a BDD.\nProve the correctness theorem\n*}\n\ntheorem mk_bdd_correct: \"eval e 0 (mk_bdd f) = evalf e f\"\n(*<*) oops (*>*)\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/trees/bdd/ex.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8519527982093666, "lm_q2_score": 0.8596637451167997, "lm_q1q2_score": 0.7323929331714012}}
{"text": "(*<*)\ntheory hw10_1_tmpl\nimports Main\nbegin\n(*>*)\n\n\ntext \\<open>\\NumHomework{Tries with Same-Length Keys}{22.~6.~2018}\n\n  Consider the following trie datatype:\n\\<close>\n\ndatatype trie = LeafF | LeafT | Node \"trie * trie\"\n\ntext \\<open>It is meant to store keys of the same length only.\n  Thus, the @{const Node} constructor stores inner nodes, and there are two\n  types of leaves, @{const LeafF} if this path is not in the set,\n  and @{const LeafT} if it is in the set.\n\n  Define an invariant \\<open>is_trie N t\\<close> that states that all keys in \\<open>t\\<close>\n  have length \\<open>N\\<close>, and that there are no superfluous nodes, i.e.,\n  no nodes of the form @{term \\<open>Node (LeafF, LeafF)\\<close>}.\n\\<close>\n\nfun is_trie :: \"nat \\<Rightarrow> trie \\<Rightarrow> bool\"\nwhere\n  \"is_trie 0 (Node (x,y)) \\<longleftrightarrow> False\"\n| \"is_trie 0 _ \\<longleftrightarrow> True\"\n| \"is_trie _ (Node (LeafF, LeafF)) \\<longleftrightarrow> False\"\n| \"is_trie (Suc n) LeafT \\<longleftrightarrow> False\"\n| \"is_trie (Suc n) LeafF \\<longleftrightarrow> True\"\n(*| \"is_trie (Suc 0) (Node (x,y)) \\<longleftrightarrow> ((x = LeafF) \\<or> (x = LeafT)) \\<and> ((y = LeafF) \\<or> (y = LeafT))\"*)\n| \"is_trie (Suc n) (Node (x,y)) \\<longleftrightarrow> is_trie n x \\<and> is_trie n y\"\n\ntext \\<open>Hint: The following should evaluate to true!\\<close>\nvalue \"is_trie 42 LeafF\"\nvalue \"is_trie 2 (Node (LeafF,Node (LeafT,LeafF)))\"\ntext \\<open>Whereas these should be false\\<close>\nvalue \"is_trie 42 LeafT\" -- \\<open>Wrong key length\\<close>\nvalue \"is_trie 2 (Node (LeafT,Node (LeafT,LeafF)))\" -- \\<open>Wrong key length\\<close>\nvalue \"is_trie 1 (Node (LeafT,Node (LeafF,LeafF)))\" -- \\<open>Superfluous node\\<close>\n\nvalue \"is_trie 1 (Node (LeafT,LeafF))\"\n\n\ntext \\<open>Define membership, insert, and delete functions, and prove them correct! \\<close>\n\nfun isin :: \"trie \\<Rightarrow> bool list \\<Rightarrow> bool\"\n  where\n  \"isin (Node (x, y)) (b#[]) = (if b then (x = LeafT) else (y = LeafT))\"\n| \"isin (Node (x, y)) (b#bs) = (if b then (isin x bs) else (isin y bs))\"\n| \"isin LeafT [] = True\"\n| \"isin _ _ = False\"\n\nvalue \"isin (Node (LeafF,Node (LeafT,LeafF))) [False, True]\"\n\nfun ins :: \"bool list \\<Rightarrow> trie \\<Rightarrow> trie\"\n  where\n  \"ins (b#[]) LeafF = (if b then (Node (LeafT, LeafF)) else (Node(LeafF, LeafT)))\"\n| \"ins (b#[]) LeafT = (if b then (Node (LeafT, LeafF)) else (Node(LeafF, LeafT)))\"\n| \"ins (b#[]) (Node(x,y)) = (if b then (Node (LeafT, y)) else (Node(x, LeafT)))\"\n| \"ins [] x = x\"\n| \"ins (b#bs) (Node(x,y)) =  (if b then (Node ((ins bs x),y)) else (Node (x, (ins bs y))))\"\n| \"ins (b#bs) LeafF = (if b then (Node ((ins bs LeafF),LeafF)) else (Node (LeafF, (ins bs LeafF))))\"\n| \"ins (b#bs) LeafT = (if b then (Node ((ins bs LeafT),LeafF)) else (Node (LeafF, (ins bs LeafT))))\"\n\n(*fun ins :: \"bool list \\<Rightarrow> trie \\<Rightarrow> trie\"\n  where\n  \"ins [] x = LeafT\"\n| \"ins (b#bs) (Node(x,y)) =  (if b then (Node ((ins bs x),y)) else (Node (x, (ins bs y))))\"\n| \"ins (b#bs) x = (if b then (Node ((ins bs x),LeafF)) else (Node (LeafF, (ins bs x))))\"*)\n\nvalue \"ins [True, False] (Node (LeafF,Node (LeafT,LeafF)))\"\nvalue \"ins [False] LeafF\"\nvalue \"ins [True,True,True] (Node (LeafF,Node (LeafT,LeafF)))\"\n\n\n\nlemma isin_ins1:\n  assumes \"is_trie n t\" and \"length as = n\"\n  shows \"isin (ins as t) bs = (as = bs \\<or> isin t bs)\"\n  apply (induction as t arbitrary: bs n rule: ins.induct)\n  \n  \n  \n  \n  \n\n\nlemma isin_ins2:\n  assumes \"is_trie n t\" and \"length as = n\"\n  shows \"is_trie n (ins as t)\"\nproof(induction as)\n  case Nil\nthen show ?case\n  by (simp add: assms(1))\nnext\ncase (Cons a as)\n  then show ?case\n    by (metis One_nat_def ins.simps(2) ins.simps(3) is_trie.simps(2) isin.simps(4) isin_ins1 le_numeral_extra(4) length_Cons list.size(3) not_less_eq_eq not_one_le_zero order_antisym_conv zero_induct)\nqed\n\n\n\n\nlemma isin_ins:\n  assumes \"is_trie n t\" and \"length as = n\"\n  shows \"isin (ins as t) bs = (as = bs \\<or> isin t bs)\"\n    and \"is_trie n (ins as t)\"\n  using assms(1) assms(2) isin_ins1 apply auto[1]\n\n\nfun delete2 :: \"bool list \\<Rightarrow> trie \\<Rightarrow> trie\" where\n  \"delete2 _ _ = undefined\"\n\nlemma\n  assumes \"is_trie n t\"\n  shows \"isin (delete2 as t) bs = (as\\<noteq>bs \\<and> isin t bs)\"\n    and \"(is_trie n (delete2 as t))\"\n  oops\n\ntext \\<open>Hints:\n  \\<^item> Like in the \\<open>delete2\\<close> function for standard tries, you may want to define\n    a \"smart-constructor\" \\<open>node :: trie \\<times> trie \\<Rightarrow> trie\\<close> for nodes,\n    that constructs a node and handles the case that both successors are \\<open>LeafF\\<close>.\n  \\<^item> Consider proving auxiliary lemmas about the smart-constructor, instead of\n    always unfolding it with the simplifier.\n\\<close>\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/10/hw10_1_tmpl.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8499711832583696, "lm_q2_score": 0.861538211208597, "lm_q1q2_score": 0.7322826528032703}}
{"text": "theory MyList\n  imports Main\nbegin\n\n(* datatype requires no quotation marks on the left-hand side, but on the\nright-hand side each of the argument types of a constructor needs to be\nenclosed in quotation marks, unless it is just an identifier (e.g., nat or 'a).*)\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\n(* \nTo prove that some property P holds for\nall lists xs, i.e., P xs, you need to prove\n1. the base case P Nil and\n2. the inductive case P (Cons x xs) under the assumption P xs, for some\narbitrary but fixed x and xs.\nThis is often called structural induction\n *)\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\n(*\nlemma app_assoc[simp]: \"rev (app xs ys) = app (rev ys) (rev xs) \\<Longrightarrow>\n       app (app (rev ys) (rev xs)) (Cons x1 Nil) =\n       app (rev ys) (app (rev xs) (Cons x1 Nil))\"\n  apply(induction xs)\n   apply(auto)\n  done\n*)\n\n(*\nInsert this lemma, and find more simpler lemma `app_Nil`\nlemma \" (app (app (rev xs) (Cons x1a Nil)) (Cons x1 Nil)) = Cons x1 (Cons x1a xs)\"\n*)\n(*\n 1. \\<And>x1 xs.\n       MyList.rev (app xs ys) = app (MyList.rev xs) (MyList.rev ys) \\<Longrightarrow>\n       app (app (MyList.rev xs) (MyList.rev ys)) (MyList.list.Cons x1 MyList.list.Nil) =\n       app (app (MyList.rev xs) (MyList.list.Cons x1 MyList.list.Nil)) (MyList.rev ys)\n 1. \\<And>x1 xs.\n       MyList.rev (app xs ys) = app (MyList.rev xs) (MyList.rev ys) \\<Longrightarrow>\n       app (MyList.rev xs) (app (MyList.rev ys) (MyList.list.Cons x1 MyList.list.Nil)) =\n       app (MyList.rev xs) (MyList.list.Cons x1 (MyList.rev ys))\n*)\n\n(*lemma rev_app [simp]: \"rev (app (rev xs) (Cons x1 Nil)) = Cons x1 xs\" *)\nlemma rev_app [simp]: \"rev (app xs ys) = app (rev ys) (rev xs)\" \n  apply(induction xs)\n   apply(auto)\n  done\n\n(* rev (app (rev xs) (Cons x1 Nil)) = Cons x1 xs is needed to be proved*)\n\ntheorem rev_rev [simp]: \"rev(rev xs) = xs\" (* Via the bracketed attribute simp we also tell *)\n                                           (* Isabelle to make the eventual theorem a simplification rule *) \n  apply(induction xs)\n  apply(auto) (* subgoal 1 is proved *)\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/ConcreteSemanticsChapter2/MyList.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382129861583, "lm_q2_score": 0.8499711699569786, "lm_q1q2_score": 0.7322826428544896}}
{"text": "(*  Author:     Lukas Bulwahn <lukas.bulwahn-at-gmail.com> *)\nsection \\<open>Sum of Powers\\<close>\n\ntheory Sum_of_Powers\nimports Complex_Main\nbegin\n\nsubsection \\<open>Preliminaries\\<close>\n\nlemma integrals_eq:\n  assumes \"f a = g a\"\n  assumes \"\\<And> x. ((\\<lambda>x. f x - g x) has_real_derivative 0) (at x)\"\n  shows \"f x = g x\"\n  by (metis (no_types, lifting) DERIV_isconst_all assms(1) assms(2) eq_iff_diff_eq_0)\n\nlemma sum_diff: \"((\\<Sum>i\\<le>n::nat. f (i + 1) - f i)::'a::field) = f (n + 1) - f 0\"\n  by (induct n) (auto simp add: field_simps)\n\ndeclare One_nat_def [simp del]\n\nsubsection \\<open>Bernoulli Numbers and Bernoulli Polynomials\\<close>\n\ndeclare sum.cong [fundef_cong]\n\nfun bernoulli :: \"nat \\<Rightarrow> real\"\nwhere\n  \"bernoulli 0 = (1::real)\"\n| \"bernoulli (Suc n) =  (-1 / (n + 2)) * (\\<Sum>k \\<le> n. ((n + 2 choose k) * bernoulli k))\"\n\ndeclare bernoulli.simps[simp del]\n\ndefinition\n  \"bernpoly n = (\\<lambda>x. \\<Sum>k \\<le> n. (n choose k) * bernoulli k * x ^ (n - k))\"\n\nsubsection \\<open>Basic Observations on Bernoulli Polynomials\\<close>\n\nlemma bernpoly_0: \"bernpoly n 0 = bernoulli n\"\nproof (cases n)\n  case 0\n  then show \"bernpoly n 0 = bernoulli n\"\n    unfolding bernpoly_def bernoulli.simps by auto\nnext\n  case (Suc n')\n  have \"(\\<Sum>k\\<le>n'. real (Suc n' choose k) * bernoulli k * 0 ^ (Suc n' - k)) = 0\"\n    by (rule sum.neutral) auto\n  with Suc show ?thesis\n    unfolding bernpoly_def by simp\nqed\n\nlemma sum_binomial_times_bernoulli:\n  \"(\\<Sum>k\\<le>n. ((Suc n) choose k) * bernoulli k) = (if n = 0 then 1 else 0)\"\nproof (cases n)\n  case 0\n  then show ?thesis by (simp add: bernoulli.simps)\nnext\n  case Suc\n  then show ?thesis\n  by (simp add: bernoulli.simps)\n    (simp add: field_simps add_2_eq_Suc'[symmetric] del: add_2_eq_Suc add_2_eq_Suc')\nqed\n\nsubsection \\<open>Sum of Powers with Bernoulli Polynomials\\<close>\n\nlemma bernpoly_derivative [derivative_intros]:\n  \"(bernpoly (Suc n) has_real_derivative ((n + 1) * bernpoly n x)) (at x)\"\nproof -\n  have \"(bernpoly (Suc n) has_real_derivative (\\<Sum>k\\<le>n. real (Suc n - k) * x ^ (n - k) * (real (Suc n choose k) * bernoulli k))) (at x)\"\n    unfolding bernpoly_def by (rule DERIV_cong) (fast intro!: derivative_intros, simp)\n  moreover have \"(\\<Sum>k\\<le>n. real (Suc n - k) * x ^ (n - k) * (real (Suc n choose k) * bernoulli k)) = (n + 1) * bernpoly n x\"\n    unfolding bernpoly_def\n    by (auto intro: sum.cong simp add: sum_distrib_left real_binomial_eq_mult_binomial_Suc[of _ n] Suc_eq_plus1 of_nat_diff)\n  ultimately show ?thesis by auto\nqed\n\nlemma diff_bernpoly:\n  \"bernpoly n (x + 1) - bernpoly n x = n * x ^ (n - 1)\"\nproof (induct n arbitrary: x)\n  case 0\n  show ?case unfolding bernpoly_def by auto\nnext\n  case (Suc n)\n  have \"bernpoly (Suc n) (0 + 1) - bernpoly (Suc n) 0 = (Suc n) * 0 ^ n\"\n    unfolding bernpoly_0 unfolding bernpoly_def by (simp add: sum_binomial_times_bernoulli zero_power)\n  then have const: \"bernpoly (Suc n) (0 + 1) - bernpoly (Suc n) 0 = real (Suc n) * 0 ^ n\" by (simp add: power_0_left)\n  have hyps': \"\\<And>x. (real n + 1) * bernpoly n (x + 1) - (real n + 1) * bernpoly n x = real n * x ^ (n - Suc 0) * real (Suc n)\"\n    unfolding right_diff_distrib[symmetric] by (simp add: Suc.hyps One_nat_def)\n  note [derivative_intros] = DERIV_chain'[where f = \"\\<lambda>x::real. x + 1\" and g = \"bernpoly (Suc n)\" and s=\"UNIV\"]\n  have derivative: \"\\<And>x. ((%x. bernpoly (Suc n) (x + 1) - bernpoly (Suc n) x - real (Suc n) * x ^ n) has_real_derivative 0) (at x)\"\n    by (rule DERIV_cong) (fast intro!: derivative_intros, simp add: hyps')\n  from integrals_eq[OF const derivative] show ?case by simp\nqed\n\nlemma sum_of_powers: \"(\\<Sum>k\\<le>n::nat. (real k) ^ m) = (bernpoly (Suc m) (n + 1) - bernpoly (Suc m) 0) / (m + 1)\"\nproof -\n  from diff_bernpoly[of \"Suc m\", simplified] have \"(m + (1::real)) * (\\<Sum>k\\<le>n. (real k) ^ m) = (\\<Sum>k\\<le>n. bernpoly (Suc m) (real k + 1) - bernpoly (Suc m) (real k))\"\n    by (auto simp add: sum_distrib_left intro!: sum.cong)\n  also have \"... = (\\<Sum>k\\<le>n. bernpoly (Suc m) (real (k + 1)) - bernpoly (Suc m) (real k))\"\n    by simp\n  also have \"... = bernpoly (Suc m) (n + 1) - bernpoly (Suc m) 0\"\n    by (simp only: sum_diff[where f=\"\\<lambda>k. bernpoly (Suc m) (real k)\"]) simp\n  finally show ?thesis by (auto simp add: field_simps intro!: eq_divide_imp)\nqed\n\nsubsection \\<open>Instances for Square And Cubic Numbers\\<close>\n\nlemma binomial_unroll:\n  \"n > 0 \\<Longrightarrow> (n choose k) = (if k = 0 then 1 else (n - 1) choose (k - 1) + ((n - 1) choose k))\"\n  by (auto simp add: gr0_conv_Suc)\n\nlemma sum_unroll:\n  \"(\\<Sum>k\\<le>n::nat. f k) = (if n = 0 then f 0 else f n + (\\<Sum>k\\<le>n - 1. f k))\"\nby auto (metis One_nat_def Suc_pred add.commute sum.atMost_Suc)\n\nlemma bernoulli_unroll:\n  \"n > 0 \\<Longrightarrow> bernoulli n = - 1 / (real n + 1) * (\\<Sum>k\\<le>n - 1. real (n + 1 choose k) * bernoulli k)\"\nby (cases n) (simp add: bernoulli.simps One_nat_def)+\n\nlemmas unroll = binomial_unroll\n  bernoulli.simps(1) bernoulli_unroll sum_unroll bernpoly_def\n\nlemma sum_of_squares: \"(\\<Sum>k\\<le>n::nat. k ^ 2) = (2 * n ^ 3 + 3 * n ^ 2 + n) / 6\"\nproof -\n  have \"real (\\<Sum>k\\<le>n::nat. k ^ 2) = (\\<Sum>k\\<le>n::nat. (real k) ^ 2)\" by simp\n  also have \"... = (bernpoly 3 (real (n + 1)) - bernpoly 3 0) / real (3 :: nat)\"\n    by (auto simp add: sum_of_powers)\n  also have \"... = (2 * n ^ 3 + 3 * n ^ 2 + n) / 6\"\n    by (simp add: unroll algebra_simps power2_eq_square power3_eq_cube One_nat_def[symmetric])\n  finally show ?thesis by simp\nqed\n\nlemma sum_of_squares_nat: \"(\\<Sum>k\\<le>n::nat. k ^ 2) = (2 * n ^ 3 + 3 * n ^ 2 + n) div 6\"\nproof -\n  from sum_of_squares have \"real (6 * (\\<Sum>k\\<le>n. k ^ 2)) = real (2 * n ^ 3 + 3 * n ^ 2 + n)\"\n    by (auto simp add: field_simps)\n  then have \"6 * (\\<Sum>k\\<le>n. k ^ 2) = 2 * n ^ 3 + 3 * n ^ 2 + n\"\n    using of_nat_eq_iff by blast\n  then show ?thesis by auto\nqed\n\nlemma sum_of_cubes: \"(\\<Sum>k\\<le>n::nat. k ^ 3) = (n ^ 2 + n) ^ 2 / 4\"\nproof -\n  have two_plus_two: \"2 + 2 = 4\" by simp\n  have power4_eq: \"\\<And>x::real. x ^ 4 = x * x * x * x\"\n    by (simp only: two_plus_two[symmetric] power_add power2_eq_square)\n  have \"real (\\<Sum>k\\<le>n::nat. k ^ 3) = (\\<Sum>k\\<le>n::nat. (real k) ^ 3)\" by simp\n  also have \"... = ((bernpoly 4 (n + 1) - bernpoly 4 0)) / (real (4 :: nat))\"\n    by (auto simp add: sum_of_powers)\n  also have \"... = ((n ^ 2 + n) / 2) ^ 2\"\n    by (simp add: unroll algebra_simps power2_eq_square power4_eq power3_eq_cube)\n  finally show ?thesis by (simp add: power_divide)\nqed\n                       \nlemma sum_of_cubes_nat: \"(\\<Sum>k\\<le>n::nat. k ^ 3) = (n ^ 2 + n) ^ 2 div 4\"\nproof -\n  from sum_of_cubes have \"real (4 * (\\<Sum>k\\<le>n. k ^ 3)) = real ((n ^ 2 + n) ^ 2)\"\n    by (auto simp add: field_simps)\n  then have \"4 * (\\<Sum>k\\<le>n. k ^ 3) = (n ^ 2 + n) ^ 2\"\n    using of_nat_eq_iff by blast\n  then show ?thesis by auto\nqed\n\nend\n", "meta": {"author": "lexbailey", "repo": "itrees_isabelle_fork", "sha": "60e0b4893d0f767483ad3a4e43d2001ca10deef3", "save_path": "github-repos/isabelle/lexbailey-itrees_isabelle_fork", "path": "github-repos/isabelle/lexbailey-itrees_isabelle_fork/itrees_isabelle_fork-60e0b4893d0f767483ad3a4e43d2001ca10deef3/src/HOL/ex/Sum_of_Powers.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615381987656672, "lm_q2_score": 0.8499711718571775, "lm_q1q2_score": 0.732282632404576}}
{"text": "(*\nTitle: Aristotle's Assertoric Syllogistic\nAuthor: Angeliki Koutsoukou-Argyraki, University of Cambridge.\nOctober 2019\n\nWe formalise with Isabelle/HOL some basic elements of Aristotle's assertoric syllogistic following\nthe article from the Stanford Encyclopedia of Philosophy by Robin Smith:\nhttps://plato.stanford.edu/entries/aristotle-logic/.\nTo this end, we use a set theoretic formulation (covering both individual and general predication).\nIn particular, we formalise the deductions in the Figures and after that we present Aristotle's\nmetatheoretical observation that all deductions in the Figures can in fact be reduced to either\nBarbara or Celarent. As the formal proofs prove to be straightforward, the interest of this entry \nlies in illustrating the functionality of Isabelle and high efficiency of Sledgehammer for simple \nexercises in philosophy.*)\n\n\nsection\\<open>Aristotle's Assertoric Syllogistic\\<close>\n\ntheory AristotlesAssertoric \n  imports Main \nbegin\n\n\nsubsection\\<open>Aristotelean Categorical Sentences\\<close>\n\ntext\\<open> Aristotle's universal, particular and indefinite predications (affirmations and denials)\nare expressed here using a set theoretic formulation.\nAristotle handles in the same way individual and general predications i.e. \nhe gives the same logical analysis to \"Socrates is an animal\" and \"humans are animals\".\nHere we define the general predication i.e. predications are defined as relations between sets.\nThis has the benefit that individual predication can also be expressed as set membership (e.g. see\nthe lemma SocratesMortal). \\<close>\n\ndefinition universal_affirmation :: \"'a set  \\<Rightarrow>'a set  \\<Rightarrow> bool\"  (infixr \"Q\" 80)\n  where \"A Q B \\<equiv> \\<forall> b \\<in> B . b \\<in> A \" \n\ndefinition universal_denial ::  \"'a set  \\<Rightarrow>'a set   \\<Rightarrow> bool\"  (infixr \"E\" 80)\n  where \"A E B \\<equiv> \\<forall> b \\<in> B. ( b \\<notin> A)  \"\n\ndefinition particular_affirmation ::  \" 'a set  \\<Rightarrow>'a set  \\<Rightarrow> bool\"  (infixr \"I\" 80)\n  where \"A I B \\<equiv> \\<exists> b \\<in> B. ( b \\<in> A) \"\n\ndefinition particular_denial ::  \"'a set  \\<Rightarrow>'a set \\<Rightarrow> bool\"  (infixr \"Z\" 80)\n  where \"A Z B \\<equiv> \\<exists> b \\<in> B. ( b \\<notin> A) \"\n\ntext\\<open> The above four definitions are known as the \"square of opposition\".\\<close>\n\ndefinition indefinite_affirmation ::  \" 'a set \\<Rightarrow>'a set \\<Rightarrow> bool\"  (infixr \"QI\" 80)\n  where \"A QI B \\<equiv>(( \\<forall> b \\<in> B. (b \\<in> A)) \\<or>  (\\<exists> b \\<in> B. (b \\<in> A))) \"\n\ndefinition indefinite_denial ::  \"'a set  \\<Rightarrow>'a set \\<Rightarrow> bool\"  (infixr \"EZ\" 80)\n  where \"A EZ  B \\<equiv> (( \\<forall> b \\<in> B. (b \\<notin> A)) \\<or> (\\<exists> b \\<in> B. (b \\<notin> A)))  \"\n\nlemma aristo_conversion1 : \n  assumes \"A E B\" shows \"B E A\"\n  using assms universal_denial_def by blast\n\nlemma aristo_conversion2 : \n  assumes \"A I B\" shows \"B I A\"\n  using assms unfolding  particular_affirmation_def\n  by blast\n\nlemma aristo_conversion3 : assumes \"A Q B\" and \"B \\<noteq>{} \"  shows \"B I A\"\n  using assms \n  unfolding universal_affirmation_def particular_affirmation_def by blast\n\ntext\\<open>Remark: Aristotle in general supposes that sets have to be nonempty. Indeed, we observe that \n in many instances it is necessary to assume that the sets are nonempty,\n otherwise Isabelle's automation finds counterexamples.\\<close>\n\nsubsection\\<open>The Deductions in the Figures (\"Moods\")\\<close>\n\ntext\\<open>The medieval mnemonic names are used.\\<close> \n\nsubsubsection\\<open>First Figure\\<close>\n\nlemma Barbara:\n  assumes \"A Q B \" and \"B Q C\" shows \"A Q C\"\nby (meson assms universal_affirmation_def)\n\nlemma Celarent:\n  assumes \"A E B \" and \"B Q C\" shows \"A E C\"\nby (meson assms universal_affirmation_def universal_denial_def)\n\nlemma Darii:\n  assumes  \"A Q B\" and \"B I C\" shows \"A I C\"\nby (meson assms particular_affirmation_def universal_affirmation_def)\n\nlemma Ferio:\n  assumes  \"A E B\" and \"B I C\" shows \"A Z C\"\nby (meson assms particular_affirmation_def particular_denial_def universal_denial_def)\n\nsubsubsection\\<open>Second Figure\\<close>\n\nlemma Cesare:\n  assumes  \"A E B \" and \"A Q C\" shows \"B E C\"\nusing Celarent aristo_conversion1 assms by blast\n\nlemma Camestres:\n  assumes  \"A Q B \" and \"A E C\" shows \"B E C \"\nusing Cesare aristo_conversion1 assms by blast\n\nlemma Festino:\n  assumes  \"A E B \" and \"A I C\" shows \"B Z C \"\nusing Ferio aristo_conversion1 assms by blast\n\nlemma Baroco:\n  assumes  \"A Q B \" and \"A Z C\" shows \"B Z C   \"\nby (meson assms particular_denial_def universal_affirmation_def)\n\n\nsubsubsection\\<open>Third Figure\\<close>\n\nlemma Darapti:\n  assumes  \"A Q C \" and \"B Q C\" and \"C \\<noteq>{}\"   shows \"A I B \"\n  using Darii assms unfolding  universal_affirmation_def particular_affirmation_def\n  by blast\n\nlemma Felapton:\n  assumes  \"A E C\" and \"B Q C\"  and  \"C \\<noteq>{}\"   shows \"A Z B\"\n using Festino aristo_conversion1 aristo_conversion3 assms by blast\n\nlemma Disamis:\n  assumes  \"A I C\" and \"B Q C\" shows \"A I B\"\n  using Darii aristo_conversion2 assms by blast\n\nlemma Datisi:\n  assumes  \"A Q C\" and \"B I C\" shows \"A I B\"\n  using Disamis aristo_conversion2 assms by blast\n\nlemma Bocardo:\n  assumes  \"A Z C\" and \"B Q C\" shows \"A Z B\"\n by (meson assms particular_denial_def universal_affirmation_def)\n\nlemma Ferison:  \n  assumes  \"A E C \" and \"B I C\" shows \"A Z B   \"\nusing Ferio aristo_conversion2 assms by blast\n\nsubsubsection\\<open>Examples\\<close>\n\ntext\\<open>Example of a deduction with general predication.\\<close>\n\nlemma GreekMortal : \n  assumes  \"Mortal Q Human\" and \"Human Q Greek \"\n  shows \" Mortal Q Greek \"\nusing assms Barbara by auto\n\ntext\\<open>Example of a deduction with individual predication.\\<close>\n\nlemma SocratesMortal:\n  assumes \"Socrates \\<in> Human \" and \"Mortal Q Human\"  \n  shows \"Socrates \\<in> Mortal \" \nusing assms by (simp add: universal_affirmation_def)\n\nsubsection\\<open>Metatheoretical comments\\<close>\n\ntext\\<open>The following are presented to demonstrate one of Aristotle's metatheoretical\nexplorations. Namely, Aristotle's metatheorem that:\n\"All deductions in all three Figures can eventually be reduced to either Barbara or Celarent\"\nis demonstrated by the proofs below and by considering the proofs from the previous subsection. \\<close>\n\nlemma Darii_reducedto_Camestres:  \n  assumes \"A Q B \" and \"B I C\" and \"A E C  \" (*assms, concl. of Darii  and A E C *)\n  shows \"A I C\"\nproof-\n  have \"B E C\" using Camestres \\<open> A Q B   \\<close>  \\<open>A E C\\<close>    by blast\n  show ?thesis using \\<open> B I C \\<close>   \\<open>B E C\\<close> \n    by (simp add: particular_affirmation_def universal_denial_def)\nqed\n\ntext\\<open>It is already evident from the proofs in the previous subsection that:\n\nCamestres can be reduced to Cesare.\n\nCesare can be reduced to Celarent.\n\nFestino can be reduced to Ferio.\\<close>\n\nlemma Ferio_reducedto_Cesare:  assumes\n  \"A E B \" and \"B I C\" and \"A Q C  \" (*assms, concl. of Ferio  and A Q C *)\nshows \"A Z C\"\n proof-\n  have \"B E C\" using Cesare \\<open>A E B \\<close>  \\<open>A Q C\\<close>  by blast\n  show ?thesis using  \\<open>B I C \\<close>  \\<open>B E C\\<close>\n    by (simp add: particular_affirmation_def universal_denial_def)\nqed\n\nlemma Baroco_reducedto_Barbara :\n  assumes \"A Q B \" and \" A Z C  \" and \" B Q C \" \n  shows \"B Z C\" (*assms , concl. of Baroco and  B Q C *)\nproof-\n  have \"A Q C\" using  \\<open>A Q B \\<close>  \\<open> B Q C \\<close> Barbara by blast\n  show ?thesis using  \\<open>A Q C\\<close>  \\<open> A Z C \\<close>\n    by (simp add: particular_denial_def universal_affirmation_def)\nqed\n\nlemma Bocardo_reducedto_Barbara :\n  assumes \" A Z C\" and \"B Q C\" and \"A Q B\" \n  shows \"A Z B\" (*assms, concl of Bocardo and A Q B *)\nproof-\n  have \"A Q C\" using  \\<open>B Q C\\<close>  \\<open> A Q B\\<close> using Barbara by blast\n  show ?thesis using  \\<open>A Q C\\<close> \\<open> A Z C\\<close> \n    by (simp add: particular_denial_def universal_affirmation_def)\nqed\n\ntext\\<open>Finally, it is already evident from the proofs in the previous subsection that :\n\n Darapti can be reduced to Darii.\n\n Felapton can be reduced to Festino. \n\n Disamis can be reduced to Darii. \n\n Datisi can be reduced to Disamis. \n\n Ferison can be reduced to Ferio. \\<close>\n\ntext\\<open>In conclusion, the aforementioned deductions have thus been shown to be reduced to either \nBarbara or Celarent as follows:\n\nBaroco  $\\Rightarrow$ Barbara \n\nBocardo $\\Rightarrow$ Barbara \n\nFelapton $\\Rightarrow$ Festino $\\Rightarrow$ Ferio $\\Rightarrow$ Cesare $\\Rightarrow$ Celarent \n\nDatisi $\\Rightarrow$ Disamis $\\Rightarrow$ Darii $\\Rightarrow$ Camestres $\\Rightarrow$ Cesare \n\nDarapti $\\Rightarrow$ Darii \n\nFerison $\\Rightarrow$ Ferio \n\\<close>\n\nsubsection\\<open>Acknowledgements\\<close>\n \ntext\\<open>A.K.-A. was supported by the ERC Advanced Grant ALEXANDRIA (Project 742178)\n funded by the European Research Council and led by Professor Lawrence Paulson\n at the University of Cambridge, UK. Thanks to Wenda Li.\\<close>\n\nsubsection\\<open>Bibliography\\<close>\ntext\\<open>Smith, Robin, \"Aristotle\u2019s Logic\", \nThe Stanford Encyclopedia of Philosophy (Summer 2019 Edition),\nEdward N. Zalta (ed.), URL = @{url \"https://plato.stanford.edu/archives/sum2019/entries/aristotle-logic/\"}\n\\<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/Aristotles_Assertoric_Syllogistic/AristotlesAssertoric.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9173026505426832, "lm_q2_score": 0.7981867801399695, "lm_q1q2_score": 0.732178849050524}}
{"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_19\n  imports \"../../Test_Base\"\nbegin\n\ndatatype 'a list = nil2 | cons2 \"'a\" \"'a list\"\n\ndatatype Nat = Z | S \"Nat\"\n\nfun len :: \"'a list => Nat\" where\n  \"len (nil2) = Z\"\n| \"len (cons2 y xs) = S (len xs)\"\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\nfun t2 :: \"Nat => Nat => Nat\" where\n  \"t2 (Z) y = Z\"\n| \"t2 (S z) (Z) = S z\"\n| \"t2 (S z) (S x2) = t2 z x2\"\n\ntheorem property0 :\n  \"((len (drop n xs)) = (t2 (len xs) n))\"\n  apply(induct xs arbitrary:n)(*This \"arbitrary:n\" is mandatory.*)\n   apply clarsimp(*This clarsimp is optional.*)\n   apply(induct_tac n)(*\"induct_tac\" instead of \"induct\" because of \"\\<And>n\"*)\n    apply fastforce+\n  apply clarsimp(*This clarsimp is optional.*)\n  apply(induct_tac n)(*\"induct_tac\" instead of \"induct\" because of \"\\<And>n\"*)\n   apply fastforce+\n  done\n\n(*It is also a valid choice to start with induction on n.*)\ntheorem property0' :\n  \"((len (drop n xs)) = (t2 (len xs) n))\"\n  apply(induct n arbitrary:xs)(*This \"arbitrary:xs\" is mandatory.*)\n   apply clarsimp(*This clarsimp is optional.*)\n   apply(induct_tac xs)(*\"induct_tac\" instead of \"induct\" because of \"\\<And>n\"*)\n    apply fastforce+\n  apply(induct_tac xs)(*\"induct_tac\" instead of \"induct\" because of \"\\<And>n\"*)\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_19.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314858927012, "lm_q2_score": 0.8267118026095991, "lm_q1q2_score": 0.7321620021501728}}
{"text": "theory Tut01\n  imports Main\nbegin\n\nvalue \"2 + (2::nat)\"\nvalue \"(2::nat) * (5 + 3)\"\nvalue \"(3::nat) * 4 - 2 * (7 + 1)\"\n\nlemma comm: \"(a::nat) + b = b + a\"\n  by simp\n\nlemma assoc: \"(a::nat) + (b + c) = (a + b) + c\"\n  by simp\n\nfun count :: \"'a list \\<Rightarrow> 'a \\<Rightarrow> nat\" where\n  \"count [] v = 0\" |\n  \"count (x#xs) v = (if x = v then 1 else 0) + count xs v\"\n\nlemma \"x \\<notin> set xs \\<Longrightarrow> count xs x = 0\"\n  apply(induction xs) by auto\n\nlemma \"count (x#xs) x = 1 + count xs x\"\n  apply(induction xs) by auto\n\ntheorem \"count xs x \\<le> length xs\"\n  apply(induction xs) by auto\n\nfun snoc :: \"'a list \\<Rightarrow> 'a \\<Rightarrow> 'a list\" where\n  \"snoc [] c = [c]\" |\n  \"snoc (x#xs) c = x # (snoc xs c)\"\n\nlemma \"snoc [] c = [c]\"\n  by simp\n\nlemma snoc_is_append[simp]: \"snoc xs x = xs @ [x]\"\n  apply(induction xs) by auto\n\nfun reverse :: \"'a list \\<Rightarrow> 'a list\" where\n  \"reverse [] = []\" |\n  \"reverse (x#xs) = snoc (reverse xs) x\"\n\nlemma reverse_is_rev[simp]: \"reverse xs = rev xs\"\n  apply(induction xs) by auto\n\ntheorem \"reverse (reverse xs) = xs\"\n  apply(induction xs) by auto\n\nend", "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/tutorial/Tut01.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314738181875, "lm_q2_score": 0.8267117898012104, "lm_q1q2_score": 0.7321619808245177}}
{"text": "theory trivia imports ZF\nbegin\n\nlemma In_sound_right : \\<open>x\\<in>A \\<Longrightarrow> A=B \\<Longrightarrow> x\\<in>B\\<close>\n  apply (erule subst[where b=B])\n  apply assumption\n  done\n\nlemma UnE :\n  assumes \\<open>x \\<in> (a \\<union> b)\\<close>\n  shows \\<open>x \\<in> a \\<or> x \\<in> b\\<close>\nproof -\n  from \\<open>x\\<in>(a\\<union>b)\\<close> have \\<open>x \\<in> \\<Union>(Upair(a, b))\\<close> by (unfold Un_def)\n  from \\<open>x \\<in> \\<Union>(Upair(a, b))\\<close> obtain B\n    where p1:\\<open>x \\<in> B\\<close> and p2:\\<open>B \\<in> Upair(a, b)\\<close>\n    by (erule UnionE)\n  from \\<open>B \\<in> Upair(a, b)\\<close> have \\<open>B = a \\<or> B = b\\<close> by (rule UpairE, auto)\n  from p1 have l1:\\<open>B = a \\<Longrightarrow> x \\<in> a\\<close> by (rule In_sound_right)\n  from p1 have l2:\\<open>B = b \\<Longrightarrow> x \\<in> b\\<close> by (rule In_sound_right)\n  from \\<open>B = a \\<or> B = b\\<close> and l1 and l2\n  show \\<open>x \\<in> a \\<or> x \\<in> b\\<close> by (rule disj_imp_disj)\nqed\n\nlemma SuccE :\n  fixes xa and k\n  assumes \\<open>xa \\<in> succ(k)\\<close>\n  shows \\<open>xa = k \\<or> xa \\<in> k\\<close>\nproof -\n  from \\<open>xa \\<in> succ(k)\\<close> have \\<open>xa \\<in> cons(k, k)\\<close> by (unfold succ_def)\n  hence \\<open>xa \\<in> (Upair(k,k) \\<union> k)\\<close> by (unfold cons_def)\n  hence \\<open>xa \\<in> Upair(k,k) \\<or> xa \\<in> k\\<close> by (rule UnE) \n  thus \\<open>xa = k \\<or> xa \\<in> k\\<close>\n  proof (rule disjE)\n    show \\<open>xa \\<in> k \\<Longrightarrow> xa = k \\<or> xa \\<in> k\\<close> by (rule disjI2)\n  next\n    assume \\<open>xa \\<in> Upair(k, k)\\<close>\n    hence \\<open>xa = k\\<close> by (rule upair.UpairE)\n    thus \\<open>xa = k \\<or> xa \\<in> k\\<close> by (rule disjI1)\n  qed\nqed\n\nlemma AeqUPA:\\<open>A = \\<Union>Pow(A)\\<close>\nproof (rule equalityI)\n  have \\<open>\\<And>x. x \\<in> \\<Union>Pow(A) \\<Longrightarrow> x \\<in> A\\<close>\n  proof -\n    fix x\n    assume \\<open>x \\<in> \\<Union>Pow(A)\\<close>\n    from \\<open>x \\<in> \\<Union>Pow(A)\\<close> obtain B\n      where p1:\\<open>x \\<in> B\\<close> and p2:\\<open>B \\<in> Pow(A)\\<close>\n      by (erule UnionE)\n    from \\<open>B \\<in> Pow(A)\\<close> have \\<open>B \\<subseteq> A\\<close> by (rule PowD)\n    from \\<open>x \\<in> B\\<close> and \\<open>B \\<subseteq> A\\<close> show \\<open>x \\<in> A\\<close> by (rule rev_subsetD)\n  qed\n  then show \\<open>\\<Union>Pow(A) \\<subseteq> A\\<close>\n    by (rule subsetI)\nnext\n  have \\<open>\\<And>x. x \\<in> A \\<Longrightarrow> x \\<in> \\<Union>Pow(A)\\<close>\n  proof -\n    fix x\n    assume \\<open>x \\<in> A\\<close>\n    have \\<open>A \\<in> Pow(A)\\<close> by auto\n    from \\<open>A \\<in> Pow(A)\\<close> and \\<open>x \\<in> A\\<close>\n    show \\<open>x \\<in> \\<Union>Pow(A)\\<close> by (rule UnionI)\n  qed\n  then show \\<open>A \\<subseteq> \\<Union>Pow(A)\\<close> by (rule subsetI)\nqed\n\nend\n\n", "meta": {"author": "georgydunaev", "repo": "JechExercises", "sha": "3ccce3c880a8b965c34f8ca364f38bd53cfb9fdd", "save_path": "github-repos/isabelle/georgydunaev-JechExercises", "path": "github-repos/isabelle/georgydunaev-JechExercises/JechExercises-3ccce3c880a8b965c34f8ca364f38bd53cfb9fdd/trivia.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.885631470799559, "lm_q2_score": 0.826711787666479, "lm_q1q2_score": 0.7321619764383965}}
{"text": "(*  Title:      HOL/Algebra/Product_Groups.thy\n    Author:     LC Paulson (ported from HOL Light)\n*)\n\nsection \\<open>Product and Sum Groups\\<close>\n\ntheory Product_Groups\n  imports Elementary_Groups \"HOL-Library.Equipollence\" \n  \nbegin\n\nsubsection \\<open>Product of a Family of Groups\\<close>\n\ndefinition product_group:: \"'a set \\<Rightarrow> ('a \\<Rightarrow> ('b, 'c) monoid_scheme) \\<Rightarrow> ('a \\<Rightarrow> 'b) monoid\"\n  where \"product_group I G \\<equiv> \\<lparr>carrier = (\\<Pi>\\<^sub>E i\\<in>I. carrier (G i)),\n                              monoid.mult = (\\<lambda>x y. (\\<lambda>i\\<in>I. x i \\<otimes>\\<^bsub>G i\\<^esub> y i)),\n                              one = (\\<lambda>i\\<in>I. \\<one>\\<^bsub>G i\\<^esub>)\\<rparr>\"\n\nlemma carrier_product_group [simp]: \"carrier(product_group I G) = (\\<Pi>\\<^sub>E i\\<in>I. carrier (G i))\"\n  by (simp add: product_group_def)\n\nlemma one_product_group [simp]: \"one(product_group I G) = (\\<lambda>i\\<in>I. one (G i))\"\n  by (simp add: product_group_def)\n\nlemma mult_product_group [simp]: \"(\\<otimes>\\<^bsub>product_group I G\\<^esub>) = (\\<lambda>x y. \\<lambda>i\\<in>I. x i \\<otimes>\\<^bsub>G i\\<^esub> y i)\"\n  by (simp add: product_group_def)\n\nlemma product_group [simp]:\n  assumes \"\\<And>i. i \\<in> I \\<Longrightarrow> group (G i)\" shows \"group (product_group I G)\"\nproof (rule groupI; simp)\n  show \"(\\<lambda>i. x i \\<otimes>\\<^bsub>G i\\<^esub> y i) \\<in> (\\<Pi> i\\<in>I. carrier (G i))\"\n    if \"x \\<in> (\\<Pi>\\<^sub>E i\\<in>I. carrier (G i))\" \"y \\<in> (\\<Pi>\\<^sub>E i\\<in>I. carrier (G i))\" for x y\n    using that assms group.subgroup_self subgroup.m_closed by fastforce\n  show \"(\\<lambda>i. \\<one>\\<^bsub>G i\\<^esub>) \\<in> (\\<Pi> i\\<in>I. carrier (G i))\"\n    by (simp add: assms group.is_monoid)\n  show \"(\\<lambda>i\\<in>I. (if i \\<in> I then x i \\<otimes>\\<^bsub>G i\\<^esub> y i else undefined) \\<otimes>\\<^bsub>G i\\<^esub> z i) =\n        (\\<lambda>i\\<in>I. x i \\<otimes>\\<^bsub>G i\\<^esub> (if i \\<in> I then y i \\<otimes>\\<^bsub>G i\\<^esub> z i else undefined))\"\n    if \"x \\<in> (\\<Pi>\\<^sub>E i\\<in>I. carrier (G i))\" \"y \\<in> (\\<Pi>\\<^sub>E i\\<in>I. carrier (G i))\" \"z \\<in> (\\<Pi>\\<^sub>E i\\<in>I. carrier (G i))\" for x y z\n    using that  by (auto simp: PiE_iff assms group.is_monoid monoid.m_assoc intro: restrict_ext)\n  show \"(\\<lambda>i\\<in>I. (if i \\<in> I then \\<one>\\<^bsub>G i\\<^esub> else undefined) \\<otimes>\\<^bsub>G i\\<^esub> x i) = x\"\n    if \"x \\<in> (\\<Pi>\\<^sub>E i\\<in>I. carrier (G i))\" for x\n    using assms that by (fastforce simp: Group.group_def PiE_iff)\n  show \"\\<exists>y\\<in>\\<Pi>\\<^sub>E i\\<in>I. carrier (G i). (\\<lambda>i\\<in>I. y i \\<otimes>\\<^bsub>G i\\<^esub> x i) = (\\<lambda>i\\<in>I. \\<one>\\<^bsub>G i\\<^esub>)\"\n    if \"x \\<in> (\\<Pi>\\<^sub>E i\\<in>I. carrier (G i))\" for x\n    by (rule_tac x=\"\\<lambda>i\\<in>I. inv\\<^bsub>G i\\<^esub> x i\" in bexI) (use assms that in \\<open>auto simp: PiE_iff group.l_inv\\<close>)\nqed\n\nlemma inv_product_group [simp]:\n  assumes \"f \\<in> (\\<Pi>\\<^sub>E i\\<in>I. carrier (G i))\" \"\\<And>i. i \\<in> I \\<Longrightarrow> group (G i)\"\n  shows \"inv\\<^bsub>product_group I G\\<^esub> f = (\\<lambda>i\\<in>I. inv\\<^bsub>G i\\<^esub> f i)\"\nproof (rule group.inv_equality)\n  show \"Group.group (product_group I G)\"\n    by (simp add: assms)\n  show \"(\\<lambda>i\\<in>I. inv\\<^bsub>G i\\<^esub> f i) \\<otimes>\\<^bsub>product_group I G\\<^esub> f = \\<one>\\<^bsub>product_group I G\\<^esub>\"\n    using assms by (auto simp: PiE_iff group.l_inv)\n  show \"f \\<in> carrier (product_group I G)\"\n    using assms by simp\n  show \"(\\<lambda>i\\<in>I. inv\\<^bsub>G i\\<^esub> f i) \\<in> carrier (product_group I G)\"\n    using PiE_mem assms by fastforce\nqed\n\n\nlemma trivial_product_group: \"trivial_group(product_group I G) \\<longleftrightarrow> (\\<forall>i \\<in> I. trivial_group(G i))\"\n (is \"?lhs = ?rhs\")\nproof\n  assume L: ?lhs\n  then have \"inv\\<^bsub>product_group I G\\<^esub> (\\<lambda>a\\<in>I. \\<one>\\<^bsub>G a\\<^esub>) = \\<one>\\<^bsub>product_group I G\\<^esub>\"\n    by (metis group.is_monoid monoid.inv_one one_product_group trivial_group_def)\n  have [simp]: \"\\<one>\\<^bsub>G i\\<^esub> \\<otimes>\\<^bsub>G i\\<^esub> \\<one>\\<^bsub>G i\\<^esub> = \\<one>\\<^bsub>G i\\<^esub>\" if \"i \\<in> I\" for i\n    unfolding trivial_group_def\n  proof -\n    have 1: \"(\\<lambda>a\\<in>I. \\<one>\\<^bsub>G a\\<^esub>) i = \\<one>\\<^bsub>G i\\<^esub>\"\n      by (simp add: that)\n    have \"(\\<lambda>a\\<in>I. \\<one>\\<^bsub>G a\\<^esub>) = (\\<lambda>a\\<in>I. \\<one>\\<^bsub>G a\\<^esub>) \\<otimes>\\<^bsub>product_group I G\\<^esub> (\\<lambda>a\\<in>I. \\<one>\\<^bsub>G a\\<^esub>)\"\n      by (metis (no_types) L group.is_monoid monoid.l_one one_product_group singletonI trivial_group_def)\n    then show ?thesis\n      using 1 by (simp add: that)\n  qed\n  show ?rhs\n    using L\n    by (auto simp: trivial_group_def product_group_def PiE_eq_singleton intro: groupI)\nnext\n  assume ?rhs\n  then show ?lhs\n    by (simp add: PiE_eq_singleton trivial_group_def)\nqed\n\n\nlemma PiE_subgroup_product_group:\n  assumes \"\\<And>i. i \\<in> I \\<Longrightarrow> group (G i)\"\n  shows \"subgroup (PiE I H) (product_group I G) \\<longleftrightarrow> (\\<forall>i \\<in> I. subgroup (H i) (G i))\"\n    (is \"?lhs = ?rhs\")\nproof\n  assume L: ?lhs\n  then have [simp]: \"PiE I H \\<noteq> {}\"\n    using subgroup_nonempty by force\n  show ?rhs\n  proof (clarify; unfold_locales)\n    show sub: \"H i \\<subseteq> carrier (G i)\" if \"i \\<in> I\" for i\n      using that L by (simp add: subgroup_def) (metis (no_types, lifting) L subgroup_nonempty subset_PiE)\n    show \"x \\<otimes>\\<^bsub>G i\\<^esub> y \\<in> H i\" if \"i \\<in> I\" \"x \\<in> H i\" \"y \\<in> H i\" for i x y\n    proof -\n      have *: \"\\<And>x. x \\<in> Pi\\<^sub>E I H \\<Longrightarrow> (\\<forall>y \\<in> Pi\\<^sub>E I H. \\<forall>i\\<in>I. x i \\<otimes>\\<^bsub>G i\\<^esub> y i \\<in> H i)\"\n        using L by (auto simp: subgroup_def Pi_iff)\n      have \"\\<forall>y\\<in>H i. f i \\<otimes>\\<^bsub>G i\\<^esub> y \\<in> H i\" if f: \"f \\<in> Pi\\<^sub>E I H\" and \"i \\<in> I\" for i f\n        using * [OF f] \\<open>i \\<in> I\\<close>\n        by (subst(asm) all_PiE_elements) auto\n      then have \"\\<forall>f \\<in> Pi\\<^sub>E I H. \\<forall>i \\<in> I. \\<forall>y\\<in>H i. f i \\<otimes>\\<^bsub>G i\\<^esub> y \\<in> H i\"\n        by blast\n      with that show ?thesis\n        by (subst(asm) all_PiE_elements) auto\n    qed\n    show \"\\<one>\\<^bsub>G i\\<^esub> \\<in> H i\" if \"i \\<in> I\" for i\n      using L subgroup.one_closed that by fastforce\n    show \"inv\\<^bsub>G i\\<^esub> x \\<in> H i\" if \"i \\<in> I\" and x: \"x \\<in> H i\" for i x\n    proof -\n      have *: \"\\<forall>y \\<in> Pi\\<^sub>E I H. \\<forall>i\\<in>I. inv\\<^bsub>G i\\<^esub> y i \\<in> H i\"\n      proof\n        fix y\n        assume y: \"y \\<in> Pi\\<^sub>E I H\"\n        then have yc: \"y \\<in> carrier (product_group I G)\"\n          by (metis (no_types) L subgroup_def subsetCE)\n        have \"inv\\<^bsub>product_group I G\\<^esub> y \\<in> Pi\\<^sub>E I H\"\n          by (simp add: y L subgroup.m_inv_closed)\n        moreover have \"inv\\<^bsub>product_group I G\\<^esub> y = (\\<lambda>i\\<in>I. inv\\<^bsub>G i\\<^esub> y i)\"\n          using yc by (simp add: assms)\n        ultimately show \"\\<forall>i\\<in>I. inv\\<^bsub>G i\\<^esub> y i \\<in> H i\"\n          by auto\n      qed\n      then have \"\\<forall>i\\<in>I. \\<forall>x\\<in>H i. inv\\<^bsub>G i\\<^esub> x \\<in> H i\"\n        by (subst(asm) all_PiE_elements) auto\n      then show ?thesis\n        using that(1) x by blast\n    qed\n  qed\nnext\n  assume R: ?rhs\n  show ?lhs\n  proof\n    show \"Pi\\<^sub>E I H \\<subseteq> carrier (product_group I G)\"\n      using R by (force simp: subgroup_def)\n    show \"x \\<otimes>\\<^bsub>product_group I G\\<^esub> y \\<in> Pi\\<^sub>E I H\" if \"x \\<in> Pi\\<^sub>E I H\" \"y \\<in> Pi\\<^sub>E I H\" for x y\n      using R that by (auto simp: PiE_iff subgroup_def)\n    show \"\\<one>\\<^bsub>product_group I G\\<^esub> \\<in> Pi\\<^sub>E I H\"\n      using R by (force simp: subgroup_def)\n    show \"inv\\<^bsub>product_group I G\\<^esub> x \\<in> Pi\\<^sub>E I H\" if \"x \\<in> Pi\\<^sub>E I H\" for x\n    proof -\n      have x: \"x \\<in> (\\<Pi>\\<^sub>E i\\<in>I. carrier (G i))\"\n        using R that by (force simp:  subgroup_def)\n      show ?thesis\n        using assms R that by (fastforce simp: x assms subgroup_def)\n    qed\n  qed\nqed\n\nlemma product_group_subgroup_generated:\n  assumes \"\\<And>i. i \\<in> I \\<Longrightarrow> subgroup (H i) (G i)\" and gp: \"\\<And>i. i \\<in> I \\<Longrightarrow> group (G i)\"\n  shows \"product_group I (\\<lambda>i. subgroup_generated (G i) (H i))\n       = subgroup_generated (product_group I G) (PiE I H)\"\nproof (rule monoid.equality)\n  have [simp]: \"\\<And>i. i \\<in> I \\<Longrightarrow> carrier (G i) \\<inter> H i = H i\" \"(\\<Pi>\\<^sub>E i\\<in>I. carrier (G i)) \\<inter> Pi\\<^sub>E I H = Pi\\<^sub>E I H\"\n    using assms by (force simp: subgroup_def)+\n  have \"(\\<Pi>\\<^sub>E i\\<in>I. generate (G i) (H i)) = generate (product_group I G) (Pi\\<^sub>E I H)\"\n  proof (rule group.generateI)\n    show \"Group.group (product_group I G)\"\n      using assms by simp\n    show \"subgroup (\\<Pi>\\<^sub>E i\\<in>I. generate (G i) (H i)) (product_group I G)\"\n      using assms by (simp add: PiE_subgroup_product_group group.generate_is_subgroup subgroup.subset)\n    show \"Pi\\<^sub>E I H \\<subseteq> (\\<Pi>\\<^sub>E i\\<in>I. generate (G i) (H i))\"\n      using assms by (auto simp: PiE_iff generate.incl)\n    show \"(\\<Pi>\\<^sub>E i\\<in>I. generate (G i) (H i)) \\<subseteq> K\"\n      if \"subgroup K (product_group I G)\" \"Pi\\<^sub>E I H \\<subseteq> K\" for K\n      using assms that group.generate_subgroup_incl by fastforce\n  qed\n  with assms\n  show \"carrier (product_group I (\\<lambda>i. subgroup_generated (G i) (H i))) =\n        carrier (subgroup_generated (product_group I G) (Pi\\<^sub>E I H))\"\n    by (simp add: carrier_subgroup_generated cong: PiE_cong)\nqed auto\n\nlemma finite_product_group:\n  assumes \"\\<And>i. i \\<in> I \\<Longrightarrow> group (G i)\"\n  shows\n   \"finite (carrier (product_group I G)) \\<longleftrightarrow>\n    finite {i. i \\<in> I \\<and> ~ trivial_group(G i)} \\<and> (\\<forall>i \\<in> I. finite(carrier(G i)))\"\nproof -\n  have [simp]: \"\\<And>i. i \\<in> I \\<Longrightarrow> carrier (G i) \\<noteq> {}\"\n    using assms group.is_monoid by blast\n  show ?thesis\n    by (auto simp: finite_PiE_iff PiE_eq_empty_iff group.trivial_group_alt [OF assms] cong: Collect_cong conj_cong)\nqed\n\nsubsection \\<open>Sum of a Family of Groups\\<close>\n\ndefinition sum_group :: \"'a set \\<Rightarrow> ('a \\<Rightarrow> ('b, 'c) monoid_scheme) \\<Rightarrow> ('a \\<Rightarrow> 'b) monoid\"\n  where \"sum_group I G \\<equiv>\n        subgroup_generated\n         (product_group I G)\n         {x \\<in> \\<Pi>\\<^sub>E i\\<in>I. carrier (G i). finite {i \\<in> I. x i \\<noteq> \\<one>\\<^bsub>G i\\<^esub>}}\"\n\nlemma subgroup_sum_group:\n  assumes \"\\<And>i. i \\<in> I \\<Longrightarrow> group (G i)\"\n  shows \"subgroup {x \\<in> \\<Pi>\\<^sub>E i\\<in>I. carrier (G i). finite {i \\<in> I. x i \\<noteq> \\<one>\\<^bsub>G i\\<^esub>}}\n                  (product_group I G)\"\nproof unfold_locales\n  fix x y\n  have *: \"{i. (i \\<in> I \\<longrightarrow> x i \\<otimes>\\<^bsub>G i\\<^esub> y i \\<noteq> \\<one>\\<^bsub>G i\\<^esub>) \\<and> i \\<in> I}\n        \\<subseteq> {i \\<in> I. x i \\<noteq> \\<one>\\<^bsub>G i\\<^esub>} \\<union> {i \\<in> I. y i \\<noteq> \\<one>\\<^bsub>G i\\<^esub>}\"\n    by (auto simp: Group.group_def dest: assms)\n  assume\n    \"x \\<in> {x \\<in> \\<Pi>\\<^sub>E i\\<in>I. carrier (G i). finite {i \\<in> I. x i \\<noteq> \\<one>\\<^bsub>G i\\<^esub>}}\"\n    \"y \\<in> {x \\<in> \\<Pi>\\<^sub>E i\\<in>I. carrier (G i). finite {i \\<in> I. x i \\<noteq> \\<one>\\<^bsub>G i\\<^esub>}}\"\n  then\n  show \"x \\<otimes>\\<^bsub>product_group I G\\<^esub> y \\<in> {x \\<in> \\<Pi>\\<^sub>E i\\<in>I. carrier (G i). finite {i \\<in> I. x i \\<noteq> \\<one>\\<^bsub>G i\\<^esub>}}\"\n    using assms\n    apply (auto simp: Group.group_def monoid.m_closed PiE_iff)\n    apply (rule finite_subset [OF *])\n    by blast\nnext\n  fix x\n  assume \"x \\<in> {x \\<in> \\<Pi>\\<^sub>E i\\<in>I. carrier (G i). finite {i \\<in> I. x i \\<noteq> \\<one>\\<^bsub>G i\\<^esub>}}\"\n  then show \"inv\\<^bsub>product_group I G\\<^esub> x \\<in> {x \\<in> \\<Pi>\\<^sub>E i\\<in>I. carrier (G i). finite {i \\<in> I. x i \\<noteq> \\<one>\\<^bsub>G i\\<^esub>}}\"\n    using assms\n    by (auto simp: PiE_iff assms group.inv_eq_1_iff [OF assms] conj_commute cong: rev_conj_cong)\nqed (use assms [unfolded Group.group_def] in auto)\n\nlemma carrier_sum_group:\n  assumes \"\\<And>i. i \\<in> I \\<Longrightarrow> group (G i)\"\n  shows \"carrier(sum_group I G) = {x \\<in> \\<Pi>\\<^sub>E i\\<in>I. carrier (G i). finite {i \\<in> I. x i \\<noteq> \\<one>\\<^bsub>G i\\<^esub>}}\"\nproof -\n  interpret SG: subgroup \"{x \\<in> \\<Pi>\\<^sub>E i\\<in>I. carrier (G i). finite {i \\<in> I. x i \\<noteq> \\<one>\\<^bsub>G i\\<^esub>}}\" \"(product_group I G)\"\n    by (simp add: assms subgroup_sum_group)\n  show ?thesis\n    by (simp add: sum_group_def subgroup_sum_group carrier_subgroup_generated_alt)\nqed\n\nlemma one_sum_group [simp]: \"\\<one>\\<^bsub>sum_group I G\\<^esub> = (\\<lambda>i\\<in>I. \\<one>\\<^bsub>G i\\<^esub>)\"\n  by (simp add: sum_group_def)\n\nlemma mult_sum_group [simp]: \"(\\<otimes>\\<^bsub>sum_group I G\\<^esub>) = (\\<lambda>x y. (\\<lambda>i\\<in>I. x i \\<otimes>\\<^bsub>G i\\<^esub> y i))\"\n  by (auto simp: sum_group_def)\n\nlemma sum_group [simp]:\n  assumes \"\\<And>i. i \\<in> I \\<Longrightarrow> group (G i)\" shows \"group (sum_group I G)\"\nproof (rule groupI)\n  note group.is_monoid [OF assms, simp]\n  show \"x \\<otimes>\\<^bsub>sum_group I G\\<^esub> y \\<in> carrier (sum_group I G)\"\n    if \"x \\<in> carrier (sum_group I G)\" and\n      \"y \\<in> carrier (sum_group I G)\" for x y\n  proof -\n    have *: \"{i \\<in> I. x i \\<otimes>\\<^bsub>G i\\<^esub> y i \\<noteq> \\<one>\\<^bsub>G i\\<^esub>} \\<subseteq> {i \\<in> I. x i \\<noteq> \\<one>\\<^bsub>G i\\<^esub>} \\<union> {i \\<in> I. y i \\<noteq> \\<one>\\<^bsub>G i\\<^esub>}\"\n      by auto\n    show ?thesis\n      using that\n      apply (simp add: assms carrier_sum_group PiE_iff monoid.m_closed conj_commute cong: rev_conj_cong)\n      apply (blast intro: finite_subset [OF *])\n      done\n  qed\n  show \"\\<one>\\<^bsub>sum_group I G\\<^esub> \\<otimes>\\<^bsub>sum_group I G\\<^esub> x = x\"\n    if \"x \\<in> carrier (sum_group I G)\" for x\n    using that by (auto simp: assms carrier_sum_group PiE_iff extensional_def)\n  show \"\\<exists>y\\<in>carrier (sum_group I G). y \\<otimes>\\<^bsub>sum_group I G\\<^esub> x = \\<one>\\<^bsub>sum_group I G\\<^esub>\"\n    if \"x \\<in> carrier (sum_group I G)\" for x\n  proof\n    let ?y = \"\\<lambda>i\\<in>I. m_inv (G i) (x i)\"\n    show \"?y \\<otimes>\\<^bsub>sum_group I G\\<^esub> x = \\<one>\\<^bsub>sum_group I G\\<^esub>\"\n      using that assms\n      by (auto simp: carrier_sum_group PiE_iff group.l_inv)\n    show \"?y \\<in> carrier (sum_group I G)\"\n      using that assms\n      by (auto simp: carrier_sum_group PiE_iff group.inv_eq_1_iff group.l_inv cong: conj_cong)\n  qed\nqed (auto simp: assms carrier_sum_group PiE_iff group.is_monoid monoid.m_assoc)\n\nlemma inv_sum_group [simp]:\n  assumes \"\\<And>i. i \\<in> I \\<Longrightarrow> group (G i)\" and x: \"x \\<in> carrier (sum_group I G)\"\n  shows \"m_inv (sum_group I G) x = (\\<lambda>i\\<in>I. m_inv (G i) (x i))\"\nproof (rule group.inv_equality)\n  show \"(\\<lambda>i\\<in>I. inv\\<^bsub>G i\\<^esub> x i) \\<otimes>\\<^bsub>sum_group I G\\<^esub> x = \\<one>\\<^bsub>sum_group I G\\<^esub>\"\n    using x by (auto simp: carrier_sum_group PiE_iff group.l_inv assms intro: restrict_ext)\n  show \"(\\<lambda>i\\<in>I. inv\\<^bsub>G i\\<^esub> x i) \\<in> carrier (sum_group I G)\"\n    using x by (simp add: carrier_sum_group PiE_iff group.inv_eq_1_iff assms conj_commute cong: rev_conj_cong)\nqed (auto simp: assms)\n\n\nthm group.subgroups_Inter (*REPLACE*)\ntheorem subgroup_Inter:\n  assumes subgr: \"(\\<And>H. H \\<in> A \\<Longrightarrow> subgroup H G)\"\n    and not_empty: \"A \\<noteq> {}\"\n  shows \"subgroup (\\<Inter>A) G\"\nproof\n  show \"\\<Inter> A \\<subseteq> carrier G\"\n    by (simp add: Inf_less_eq not_empty subgr subgroup.subset)\nqed (auto simp: subgr subgroup.m_closed subgroup.one_closed subgroup.m_inv_closed)\n\nthm group.subgroups_Inter_pair (*REPLACE*)\nlemma subgroup_Int:\n  assumes \"subgroup I G\" \"subgroup J G\"\n  shows \"subgroup (I \\<inter> J) G\" using subgroup_Inter[ where ?A = \"{I,J}\"] assms by auto\n\n\nlemma sum_group_subgroup_generated:\n  assumes \"\\<And>i. i \\<in> I \\<Longrightarrow> group (G i)\" and sg: \"\\<And>i. i \\<in> I \\<Longrightarrow> subgroup (H i) (G i)\"\n  shows \"sum_group I (\\<lambda>i. subgroup_generated (G i) (H i)) = subgroup_generated (sum_group I G) (PiE I H)\"\nproof (rule monoid.equality)\n  have \"subgroup (carrier (sum_group I G) \\<inter> Pi\\<^sub>E I H) (product_group I G)\"\n    by (rule subgroup_Int) (auto simp: assms carrier_sum_group subgroup_sum_group PiE_subgroup_product_group)\n  moreover have \"carrier (sum_group I G) \\<inter> Pi\\<^sub>E I H\n              \\<subseteq> carrier (subgroup_generated (product_group I G)\n                    {x \\<in> \\<Pi>\\<^sub>E i\\<in>I. carrier (G i). finite {i \\<in> I. x i \\<noteq> \\<one>\\<^bsub>G i\\<^esub>}})\"\n    by (simp add: assms subgroup_sum_group subgroup.carrier_subgroup_generated_subgroup carrier_sum_group)\n  ultimately\n  have \"subgroup (carrier (sum_group I G) \\<inter> Pi\\<^sub>E I H) (sum_group I G)\"\n    by (simp add: assms sum_group_def group.subgroup_subgroup_generated_iff)\n  then have *: \"{f \\<in> \\<Pi>\\<^sub>E i\\<in>I. carrier (subgroup_generated (G i) (H i)). finite {i \\<in> I. f i \\<noteq> \\<one>\\<^bsub>G i\\<^esub>}}\n      = carrier (subgroup_generated (sum_group I G) (carrier (sum_group I G) \\<inter> Pi\\<^sub>E I H))\"\n    apply (simp only: subgroup.carrier_subgroup_generated_subgroup)\n    using subgroup.subset [OF sg]\n    apply (auto simp: set_eq_iff PiE_def Pi_def assms carrier_sum_group subgroup.carrier_subgroup_generated_subgroup)\n    done\n  then show \"carrier (sum_group I (\\<lambda>i. subgroup_generated (G i) (H i))) =\n        carrier (subgroup_generated (sum_group I G) (Pi\\<^sub>E I H))\"\n    by simp (simp add: assms group.subgroupE(1) group.group_subgroup_generated carrier_sum_group)\nqed (auto simp: sum_group_def subgroup_generated_def)\n\n\nlemma iso_product_groupI:\n  assumes iso: \"\\<And>i. i \\<in> I \\<Longrightarrow> G i \\<cong> H i\"\n    and G: \"\\<And>i. i \\<in> I \\<Longrightarrow> group (G i)\" and H: \"\\<And>i. i \\<in> I \\<Longrightarrow> group (H i)\"\n  shows \"product_group I G \\<cong> product_group I H\" (is \"?IG \\<cong> ?IH\")\nproof -\n  have \"\\<And>i. i \\<in> I \\<Longrightarrow> \\<exists>h. h \\<in> iso (G i) (H i)\"\n    using iso by (auto simp: is_iso_def)\n  then obtain f where f: \"\\<And>i. i \\<in> I \\<Longrightarrow> f i \\<in> iso (G i) (H i)\"\n    by metis\n  define h where \"h \\<equiv> \\<lambda>x. (\\<lambda>i\\<in>I. f i (x i))\"\n  have hom: \"h \\<in> iso ?IG ?IH\"\n  proof (rule isoI)\n    show hom: \"h \\<in> hom ?IG ?IH\"\n    proof (rule homI)\n      fix x\n      assume \"x \\<in> carrier ?IG\"\n      with f show \"h x \\<in> carrier ?IH\"\n        using PiE by (fastforce simp add: h_def PiE_def iso_def hom_def)\n    next\n      fix x y\n      assume \"x \\<in> carrier ?IG\" \"y \\<in> carrier ?IG\"\n      with f show \"h (x \\<otimes>\\<^bsub>?IG\\<^esub> y) = h x \\<otimes>\\<^bsub>?IH\\<^esub> h y\"\n        apply (simp add: h_def PiE_def iso_def hom_def)\n        using PiE by (fastforce simp add: h_def PiE_def iso_def hom_def intro: restrict_ext)\n    qed\n    with G H interpret GH : group_hom \"?IG\" \"?IH\" h\n      by (simp add: group_hom_def group_hom_axioms_def)\n    show \"bij_betw h (carrier ?IG) (carrier ?IH)\"\n      unfolding bij_betw_def\n    proof (intro conjI subset_antisym)\n      have \"\\<gamma> i = \\<one>\\<^bsub>G i\\<^esub>\"\n        if \\<gamma>: \"\\<gamma> \\<in> (\\<Pi>\\<^sub>E i\\<in>I. carrier (G i))\" and eq: \"(\\<lambda>i\\<in>I. f i (\\<gamma> i)) = (\\<lambda>i\\<in>I. \\<one>\\<^bsub>H i\\<^esub>)\" and \"i \\<in> I\"\n        for \\<gamma> i\n      proof -\n        have \"inj_on (f i) (carrier (G i))\" \"f i \\<in> hom (G i) (H i)\"\n          using \\<open>i \\<in> I\\<close> f by (auto simp: iso_def bij_betw_def)\n        then have *: \"\\<And>x. \\<lbrakk>f i x = \\<one>\\<^bsub>H i\\<^esub>; x \\<in> carrier (G i)\\<rbrakk> \\<Longrightarrow> x = \\<one>\\<^bsub>G i\\<^esub>\"\n          by (metis G Group.group_def H hom_one inj_onD monoid.one_closed \\<open>i \\<in> I\\<close>)\n        show ?thesis\n          using eq \\<open>i \\<in> I\\<close> * \\<gamma> by (simp add: fun_eq_iff) (meson PiE_iff)\n      qed\n      then show \"inj_on h (carrier ?IG)\"\n        apply (simp add: iso_def bij_betw_def GH.inj_on_one_iff flip: carrier_product_group)\n        apply (force simp: h_def)\n        done\n    next\n      show \"h ` carrier ?IG \\<subseteq> carrier ?IH\"\n        unfolding h_def using f\n        by (force simp: PiE_def Pi_def Group.iso_def dest!: bij_betwE)\n    next\n      show \"carrier ?IH \\<subseteq> h ` carrier ?IG\"\n        unfolding h_def\n      proof (clarsimp simp: iso_def bij_betw_def)\n        fix x\n        assume \"x \\<in> (\\<Pi>\\<^sub>E i\\<in>I. carrier (H i))\"\n        with f have x: \"x \\<in> (\\<Pi>\\<^sub>E i\\<in>I. f i ` carrier (G i))\"\n          unfolding h_def by (auto simp: iso_def bij_betw_def)\n        have \"\\<And>i. i \\<in> I \\<Longrightarrow> inj_on (f i) (carrier (G i))\"\n          using f by (auto simp: iso_def bij_betw_def)\n        let ?g = \"\\<lambda>i\\<in>I. inv_into (carrier (G i)) (f i) (x i)\"\n        show \"x \\<in> (\\<lambda>g. \\<lambda>i\\<in>I. f i (g i)) ` (\\<Pi>\\<^sub>E i\\<in>I. carrier (G i))\"\n        proof\n          show \"x = (\\<lambda>i\\<in>I. f i (?g i))\"\n            using x by (auto simp: PiE_iff fun_eq_iff extensional_def f_inv_into_f)\n          show \"?g \\<in> (\\<Pi>\\<^sub>E i\\<in>I. carrier (G i))\"\n            using x by (auto simp: PiE_iff inv_into_into)\n        qed\n      qed\n    qed\n  qed\n  then show ?thesis\n    using is_iso_def by auto\nqed\n\nlemma iso_sum_groupI:\n  assumes iso: \"\\<And>i. i \\<in> I \\<Longrightarrow> G i \\<cong> H i\"\n    and G: \"\\<And>i. i \\<in> I \\<Longrightarrow> group (G i)\" and H: \"\\<And>i. i \\<in> I \\<Longrightarrow> group (H i)\"\n  shows \"sum_group I G \\<cong> sum_group I H\" (is \"?IG \\<cong> ?IH\")\nproof -\n  have \"\\<And>i. i \\<in> I \\<Longrightarrow> \\<exists>h. h \\<in> iso (G i) (H i)\"\n    using iso by (auto simp: is_iso_def)\n  then obtain f where f: \"\\<And>i. i \\<in> I \\<Longrightarrow> f i \\<in> iso (G i) (H i)\"\n    by metis\n  then have injf: \"inj_on (f i) (carrier (G i))\"\n    and homf: \"f i \\<in> hom (G i) (H i)\" if \"i \\<in> I\" for i\n    using \\<open>i \\<in> I\\<close> f by (auto simp: iso_def bij_betw_def)\n  then have one: \"\\<And>x. \\<lbrakk>f i x = \\<one>\\<^bsub>H i\\<^esub>; x \\<in> carrier (G i)\\<rbrakk> \\<Longrightarrow> x = \\<one>\\<^bsub>G i\\<^esub>\" if \"i \\<in> I\" for i\n    by (metis G H group.subgroup_self hom_one inj_on_eq_iff subgroup.one_closed that)\n  have fin1: \"finite {i \\<in> I. x i \\<noteq> \\<one>\\<^bsub>G i\\<^esub>} \\<Longrightarrow> finite {i \\<in> I. f i (x i) \\<noteq> \\<one>\\<^bsub>H i\\<^esub>}\" for x\n    using homf by (auto simp: G H hom_one elim!: rev_finite_subset)\n  define h where \"h \\<equiv> \\<lambda>x. (\\<lambda>i\\<in>I. f i (x i))\"\n  have hom: \"h \\<in> iso ?IG ?IH\"\n  proof (rule isoI)\n    show hom: \"h \\<in> hom ?IG ?IH\"\n    proof (rule homI)\n      fix x\n      assume \"x \\<in> carrier ?IG\"\n      with f fin1 show \"h x \\<in> carrier ?IH\"\n        by (force simp: h_def PiE_def iso_def hom_def carrier_sum_group assms conj_commute cong: conj_cong)\n    next\n      fix x y\n      assume \"x \\<in> carrier ?IG\" \"y \\<in> carrier ?IG\"\n      with homf show \"h (x \\<otimes>\\<^bsub>?IG\\<^esub> y) = h x \\<otimes>\\<^bsub>?IH\\<^esub> h y\"\n        by (fastforce simp add: h_def PiE_def hom_def carrier_sum_group assms intro: restrict_ext)\n    qed\n    with G H interpret GH : group_hom \"?IG\" \"?IH\" h\n      by (simp add: group_hom_def group_hom_axioms_def)\n    show \"bij_betw h (carrier ?IG) (carrier ?IH)\"\n      unfolding bij_betw_def\n    proof (intro conjI subset_antisym)\n      have \\<gamma>: \"\\<gamma> i = \\<one>\\<^bsub>G i\\<^esub>\"\n        if \"\\<gamma> \\<in> (\\<Pi>\\<^sub>E i\\<in>I. carrier (G i))\" and eq: \"(\\<lambda>i\\<in>I. f i (\\<gamma> i)) = (\\<lambda>i\\<in>I. \\<one>\\<^bsub>H i\\<^esub>)\" and \"i \\<in> I\"\n        for \\<gamma> i\n        using \\<open>i \\<in> I\\<close> one that by (simp add: fun_eq_iff) (meson PiE_iff)\n      show \"inj_on h (carrier ?IG)\"\n        apply (simp add: iso_def bij_betw_def GH.inj_on_one_iff assms one flip: carrier_sum_group)\n        apply (auto simp: h_def fun_eq_iff carrier_sum_group assms PiE_def Pi_def extensional_def one)\n        done\n    next\n      show \"h ` carrier ?IG \\<subseteq> carrier ?IH\"\n        using homf GH.hom_closed\n        by (fastforce simp: h_def PiE_def Pi_def dest!: bij_betwE)\n    next\n      show \"carrier ?IH \\<subseteq> h ` carrier ?IG\"\n        unfolding h_def\n      proof (clarsimp simp: iso_def bij_betw_def carrier_sum_group assms)\n        fix x\n        assume x: \"x \\<in> (\\<Pi>\\<^sub>E i\\<in>I. carrier (H i))\" and fin: \"finite {i \\<in> I. x i \\<noteq> \\<one>\\<^bsub>H i\\<^esub>}\"\n        with f have xf: \"x \\<in> (\\<Pi>\\<^sub>E i\\<in>I. f i ` carrier (G i))\"\n          unfolding h_def\n          by (auto simp: iso_def bij_betw_def)\n        have \"\\<And>i. i \\<in> I \\<Longrightarrow> inj_on (f i) (carrier (G i))\"\n          using f by (auto simp: iso_def bij_betw_def)\n        let ?g = \"\\<lambda>i\\<in>I. inv_into (carrier (G i)) (f i) (x i)\"\n        show \"x \\<in> (\\<lambda>g. \\<lambda>i\\<in>I. f i (g i))\n                 ` {x \\<in> \\<Pi>\\<^sub>E i\\<in>I. carrier (G i). finite {i \\<in> I. x i \\<noteq> \\<one>\\<^bsub>G i\\<^esub>}}\"\n        proof\n          show xeq: \"x = (\\<lambda>i\\<in>I. f i (?g i))\"\n            using x by (clarsimp simp: PiE_iff fun_eq_iff extensional_def) (metis iso_iff f_inv_into_f f)\n          have \"finite {i \\<in> I. inv_into (carrier (G i)) (f i) (x i) \\<noteq> \\<one>\\<^bsub>G i\\<^esub>}\"\n            apply (rule finite_subset [OF _ fin])\n            using G H group.subgroup_self hom_one homf injf inv_into_f_eq subgroup.one_closed by fastforce\n          with x show \"?g \\<in> {x \\<in> \\<Pi>\\<^sub>E i\\<in>I. carrier (G i). finite {i \\<in> I. x i \\<noteq> \\<one>\\<^bsub>G i\\<^esub>}}\"\n            apply (auto simp: PiE_iff inv_into_into conj_commute cong: conj_cong)\n            by (metis (no_types, opaque_lifting) iso_iff f inv_into_into)\n        qed\n      qed\n    qed\n  qed\n  then show ?thesis\n    using is_iso_def by auto\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/Product_Groups.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8740772286044095, "lm_q2_score": 0.8376199673867852, "lm_q1q2_score": 0.7321445397171571}}
{"text": "(*  Title:      HOL/Corec_Examples/LFilter.thy\n    Author:     Andreas Lochbihler, ETH Zuerich\n    Author:     Dmitriy Traytel, ETH Zuerich\n    Author:     Andrei Popescu, TU Muenchen\n    Copyright   2014, 2016\n\nThe filter function on lazy lists.\n*)\n\nsection \\<open>The Filter Function on Lazy Lists\\<close>\n\ntheory LFilter\nimports \"HOL-Library.BNF_Corec\"\nbegin\n\ncodatatype (lset: 'a) llist =\n  LNil\n| LCons (lhd: 'a) (ltl: \"'a llist\")\n\ncorecursive lfilter where\n  \"lfilter P xs = (if \\<forall>x \\<in> lset xs. \\<not> P x then\n    LNil\n    else if P (lhd xs) then\n      LCons (lhd xs) (lfilter P (ltl xs))\n    else\n      lfilter P (ltl xs))\"\nproof (relation \"measure (\\<lambda>(P, xs). LEAST n. P (lhd ((ltl ^^ n) xs)))\", rule wf_measure, clarsimp)\n  fix P xs x\n  assume \"x \\<in> lset xs\" \"P x\" \"\\<not> P (lhd xs)\"\n  from this(1,2) obtain a where \"P (lhd ((ltl ^^ a) xs))\"\n    by (atomize_elim, induct x xs rule: llist.set_induct)\n       (auto simp: funpow_Suc_right simp del: funpow.simps(2) intro: exI[of _ 0] exI[of _ \"Suc i\" for i])\n  with \\<open>\\<not> P (lhd xs)\\<close>\n    have \"(LEAST n. P (lhd ((ltl ^^ n) xs))) = Suc (LEAST n. P (lhd ((ltl ^^ Suc n) xs)))\"\n    by (intro Least_Suc) auto\n  then show \"(LEAST n. P (lhd ((ltl ^^ n) (ltl xs)))) < (LEAST n. P (lhd ((ltl ^^ n) xs)))\"\n    by (simp add: funpow_swap1[of ltl])\nqed\n\nlemma lfilter_LNil [simp]: \"lfilter P LNil = LNil\"\n  by(simp add: lfilter.code)\n\nlemma lnull_lfilter [simp]: \"lfilter P xs = LNil \\<longleftrightarrow> (\\<forall>x \\<in> lset xs. \\<not> P x)\"\nproof(rule iffI ballI)+\n  show \"\\<not> P x\" if \"x \\<in> lset xs\" \"lfilter P xs = LNil\" for x using that\n    by(induction rule: llist.set_induct)(subst (asm) lfilter.code; auto split: if_split_asm; fail)+\nqed(simp add: lfilter.code)\n\nlemma lfilter_LCons [simp]: \"lfilter P (LCons x xs) = (if P x then LCons x (lfilter P xs) else lfilter P xs)\"\n  by(subst lfilter.code)(auto intro: sym)\n\nlemma llist_in_lfilter [simp]: \"lset (lfilter P xs) = lset xs \\<inter> {x. P x}\"\nproof(intro set_eqI iffI)\n  show \"x \\<in> lset xs \\<inter> {x. P x}\" if \"x \\<in> lset (lfilter P xs)\" for x using that\n  proof(induction ys\\<equiv>\"lfilter P xs\" arbitrary: xs rule: llist.set_induct)\n    case (LCons1 x xs ys)\n    from this show ?case\n      apply(induction arg\\<equiv>\"(P, ys)\" arbitrary: ys rule: lfilter.inner_induct)\n      subgoal by(subst (asm) (2) lfilter.code)(auto split: if_split_asm elim: llist.set_cases)\n      done\n  next\n    case (LCons2 xs y x ys)\n    from LCons2(3) LCons2(1) show ?case\n      apply(induction arg\\<equiv>\"(P, ys)\" arbitrary: ys rule: lfilter.inner_induct)\n      subgoal using LCons2(2) by(subst (asm) (2) lfilter.code)(auto split: if_split_asm elim: llist.set_cases)\n      done\n  qed\n  show \"x \\<in> lset (lfilter P xs)\" if \"x \\<in> lset xs \\<inter> {x. P x}\" for x\n    using that[THEN IntD1] that[THEN IntD2] by(induction) auto\nqed\n\nlemma lfilter_unique_weak:\n  \"(\\<And>xs. f xs = (if \\<forall>x \\<in> lset xs. \\<not> P x then LNil\n    else if P (lhd xs) then LCons (lhd xs) (f (ltl xs))\n    else lfilter P (ltl xs)))\n   \\<Longrightarrow> f = lfilter P\"\n  by(corec_unique)(rule ext lfilter.code)+\n\nlemma lfilter_unique:\n  assumes \"\\<And>xs. f xs = (if \\<forall>x\\<in>lset xs. \\<not> P x then LNil\n    else if P (lhd xs) then LCons (lhd xs) (f (ltl xs))\n    else f (ltl xs))\"\n  shows \"f = lfilter P\"\n\\<comment> \\<open>It seems as if we cannot use @{thm lfilter_unique_weak} for showing this as the induction and the coinduction must be nested\\<close>\nproof(rule ext)\n  show \"f xs = lfilter P xs\" for xs\n  proof(coinduction arbitrary: xs)\n    case (Eq_llist xs)\n    show ?case\n      apply(induction arg\\<equiv>\"(P, xs)\" arbitrary: xs rule: lfilter.inner_induct)\n      apply(subst (1 2 3 4) assms)\n      apply(subst (1 2 3 4) lfilter.code)\n      apply auto\n      done\n  qed\nqed\n\nlemma lfilter_lfilter: \"lfilter P \\<circ> lfilter Q = lfilter (\\<lambda>x. P x \\<and> Q x)\"\n  by(rule lfilter_unique)(auto elim: llist.set_cases)\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/Corec_Examples/LFilter.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677622198947, "lm_q2_score": 0.8633916082162403, "lm_q1q2_score": 0.7321282499385613}}
{"text": "(*\n    ex.thy,v 1.1 2016/09/29 17:37:37 jdf Exp\n    Original Author: Tjark Weber\n    Updated to Isabelle 2016 by Jacques Fleuriot\n*)\n\nsection {* Predicate Logic *}\n\n theory predicateLogic imports Main begin \n\ntext {*\nWe are again talking about proofs in the calculus of Natural Deduction.  In\naddition to the rules given in the exercise \"Propositional Logic\", you may\nnow also use\n\nexI: ?P ?x \\<Longrightarrow> \\<exists>x. ?P x\nexE:\\<lbrakk>\\<exists>x. ?P x; \\<And>x. ?P x \\<Longrightarrow> ?Q\\<rbrakk> \\<Longrightarrow> ?Q\nallI: (\\<And>x. ?P x) \\<Longrightarrow> \\<forall>x. ?P x\nallE: \\<lbrakk>\\<forall>x. ?P x; ?P ?x \\<Longrightarrow> ?R\\<rbrakk> \\<Longrightarrow> ?R\n\nGive a proof of the following propositions or an argument why the formula is\nnot valid:\n*}\n \n  \nlemma \"(\\<exists>x. \\<forall>y. P x y) \\<longrightarrow> (\\<forall>y. \\<exists>x. P x y)\"\n  apply (rule impI)\n  apply (rule allI)\n  apply (erule exE)\n  apply (rule exI)\n  apply (erule allE)\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 \"((\\<forall> x. P x) \\<and> (\\<forall> x. Q x)) = (\\<forall> x. (P x \\<and> Q x))\"\n  apply (rule iffI)\n   apply (rule allI)\n   apply (erule conjE)\n  apply (erule allE)+\n   apply (rule conjI)\n    apply assumption+\n  apply (rule conjI)\n   apply (rule allI)\n   apply (erule allE)\n   apply (erule conjE)\n   apply assumption\n  apply (rule allI)\n  apply (erule allE)\n  apply (erule conjE)\n  apply assumption\n  done\n\nlemma \"((\\<forall> x. P x) \\<or> (\\<forall> x. Q x)) = (\\<forall> x. (P x \\<or> Q x))\"\n  apply (rule iffI)\n   apply (rule allI)\n   apply (erule disjE)\n    apply (rule disjI1)\n    apply (erule allE)\n    apply assumption\n  apply (rule disjI2)\n   apply (erule allE)\n   apply assumption\n  apply (rule classical)\n(* invalid: only provable one way*)\n oops \n\nlemma \"((\\<exists> x. P x) \\<or> (\\<exists> x. Q x)) = (\\<exists> x. (P x \\<or> Q x))\"\n  apply (rule iffI)\n   apply (erule disjE)\n    apply (erule exE)\n  apply (rule exI)\n    apply (rule disjI1)\n    apply assumption\n   apply (erule exE)\n   apply (rule exI)\n   apply (rule disjI2)\n   apply assumption\n  apply (erule exE)\n  apply (erule disjE)\n   apply (rule disjI1)\n   apply (rule exI)\n   apply assumption\n  apply (rule disjI2)\n  apply (rule exI)\n  apply assumption\n  done\n\nlemma \"(\\<forall>x. \\<exists>y. P x y) \\<longrightarrow> (\\<exists>y. \\<forall>x. P x y)\"\n  apply (rule impI)\n  apply (erule allE)\n  apply (erule exE)\n  apply (rule exI)\n  apply (rule allI)\n oops \n\nlemma \"(\\<not> (\\<forall> x. P x)) = (\\<exists> x. \\<not> P x)\"\n  apply (rule iffI)\n   prefer 2\n   apply (erule exE)\n   apply (rule notI)\n   apply (erule allE)\n   apply (erule notE)\n   apply assumption\n  apply (rule ccontr)\n  apply (erule notE)\n  apply (rule allI)\n  apply (rule ccontr)\n  apply (erule notE)\n  apply (rule exI)\n  apply assumption\n  done\n\n end ", "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/predicateLogic.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.903294214513915, "lm_q2_score": 0.8104789040926008, "lm_q1q2_score": 0.7321009050524245}}
{"text": "section\\<open>Simplification Lemmas for Lattices\\<close>\n\n(*\n    Author: Viorel Preoteasa\n*)\n\ntheory Lattice_Prop\nimports Main\nbegin\n\ntext\\<open>\nThis theory introduces some simplification lemmas\nfor semilattices and lattices\n\\<close>\n\nnotation \n   inf (infixl \"\\<sqinter>\" 70) and\n   sup (infixl \"\\<squnion>\" 65)\n\ncontext semilattice_inf begin\n\n\nlemma [simp]: \"x \\<sqinter> y \\<sqinter> z \\<le> y\"\n  by (rule_tac y = \"x \\<sqinter> y\" in order_trans, rule inf_le1, simp)\n\nlemma [simp]: \"x \\<sqinter> (y \\<sqinter> z) \\<le> y\"\n  by (rule_tac y = \"y \\<sqinter> z\" in order_trans, rule inf_le2, simp)\n\nlemma [simp]: \"x \\<sqinter> (y \\<sqinter> z) \\<le> z\"\n  by (rule_tac y = \"y \\<sqinter> z\" in order_trans, rule inf_le2, simp)\nend\n\ncontext semilattice_sup begin\n\nlemma [simp]: \"x \\<le> x \\<squnion> y \\<squnion> z\"\n  by (rule_tac y = \"x \\<squnion> y\" in order_trans, simp_all) \n\nlemma [simp]: \"y \\<le> x \\<squnion> y \\<squnion> z\"\n  by (rule_tac y = \"x \\<squnion> y\" in order_trans, simp_all)\n\nlemma [simp]: \"y \\<le> x \\<squnion> (y \\<squnion> z)\"\n  by (rule_tac y = \"y \\<squnion> z\" in order_trans, simp_all)\n\nlemma [simp]: \"z \\<le> x \\<squnion> (y \\<squnion> z)\"\n  by (rule_tac y = \"y \\<squnion> z\" in order_trans, simp_all)\nend\n\ncontext lattice begin\n\nlemma [simp]: \"x \\<sqinter> y \\<le> x \\<squnion> z\"\n  by (rule_tac y = x in order_trans, simp_all)\n\nlemma [simp]: \"y \\<sqinter> x \\<le> x \\<squnion> z\"\n  by (rule_tac y = x in order_trans, simp_all)\n\nlemma [simp]: \"x \\<sqinter> y \\<le> z \\<squnion> x\"\n  by (rule_tac y = x in order_trans, simp_all)\n\nlemma [simp]: \"y \\<sqinter> x \\<le> z \\<squnion> x\"\n  by (rule_tac y = x in order_trans, simp_all)\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/LatticeProperties/Lattice_Prop.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942119105695, "lm_q2_score": 0.8104789063814616, "lm_q1q2_score": 0.7321009050099826}}
{"text": "(*  Author:  S\u00e9bastien Gou\u00ebzel   sebastien.gouezel@univ-rennes1.fr\n    Author:  Johannes H\u00f6lzl (TUM) -- ported to Limsup\n    License: BSD\n*)\n\ntheory Essential_Supremum\nimports \"HOL-Analysis.Analysis\"\nbegin\n\nlemma ae_filter_eq_bot_iff: \"ae_filter M = bot \\<longleftrightarrow> emeasure M (space M) = 0\"\n  by (simp add: AE_iff_measurable trivial_limit_def)\n\nsection \\<open>The essential supremum\\<close>\n\ntext \\<open>In this paragraph, we define the essential supremum and give its basic properties. The\nessential supremum of a function is its maximum value if one is allowed to throw away a set\nof measure $0$. It is convenient to define it to be infinity for non-measurable functions, as\nit allows for neater statements in general. This is a prerequisiste to define the space $L^\\infty$.\\<close>\n\ndefinition esssup::\"'a measure \\<Rightarrow> ('a \\<Rightarrow> 'b::{second_countable_topology, dense_linorder, linorder_topology, complete_linorder}) \\<Rightarrow> 'b\"\n  where \"esssup M f = (if f \\<in> borel_measurable M then Limsup (ae_filter M) f else top)\"\n\nlemma esssup_non_measurable: \"f \\<notin> M \\<rightarrow>\\<^sub>M borel \\<Longrightarrow> esssup M f = top\"\n  by (simp add: esssup_def)\n\nlemma esssup_eq_AE:\n  assumes f: \"f \\<in> M \\<rightarrow>\\<^sub>M borel\" shows \"esssup M f = Inf {z. AE x in M. f x \\<le> z}\"\n  unfolding esssup_def if_P[OF f] Limsup_def\nproof (intro antisym INF_greatest Inf_greatest; clarsimp)\n  fix y assume \"AE x in M. f x \\<le> y\"\n  then have \"(\\<lambda>x. f x \\<le> y) \\<in> {P. AE x in M. P x}\"\n    by simp\n  then show \"(INF P\\<in>{P. AE x in M. P x}. SUP x\\<in>Collect P. f x) \\<le> y\"\n    by (rule INF_lower2) (auto intro: SUP_least)\nnext\n  fix P assume P: \"AE x in M. P x\"\n  show \"Inf {z. AE x in M. f x \\<le> z} \\<le> (SUP x\\<in>Collect P. f x)\"\n  proof (rule Inf_lower; clarsimp)\n    show \"AE x in M. f x \\<le> (SUP x\\<in>Collect P. f x)\"\n      using P by (auto elim: eventually_mono simp: SUP_upper)\n  qed\nqed\n\nlemma esssup_eq: \"f \\<in> M \\<rightarrow>\\<^sub>M borel \\<Longrightarrow> esssup M f = Inf {z. emeasure M {x \\<in> space M. f x > z} = 0}\"\n  by (auto simp add: esssup_eq_AE not_less[symmetric] AE_iff_measurable[OF _ refl] intro!: arg_cong[where f=Inf])\n\nlemma esssup_zero_measure:\n  \"emeasure M {x \\<in> space M. f x > esssup M f} = 0\"\nproof (cases \"esssup M f = top\")\n  case True\n  then show ?thesis by auto\nnext\n  case False\n  then have f[measurable]: \"f \\<in> M \\<rightarrow>\\<^sub>M borel\" unfolding esssup_def by meson\n  have \"esssup M f < top\" using False by (auto simp: less_top)\n  have *: \"{x \\<in> space M. f x > z} \\<in> null_sets M\" if \"z > esssup M f\" for z\n  proof -\n    have \"\\<exists>w. w < z \\<and> emeasure M {x \\<in> space M. f x > w} = 0\"\n      using \\<open>z > esssup M f\\<close> f by (auto simp: esssup_eq Inf_less_iff)\n    then obtain w where \"w < z\" \"emeasure M {x \\<in> space M. f x > w} = 0\" by auto\n    then have a: \"{x \\<in> space M. f x > w} \\<in> null_sets M\" by auto\n    have b: \"{x \\<in> space M. f x > z} \\<subseteq> {x \\<in> space M. f x > w}\" using \\<open>w < z\\<close> by auto\n    show ?thesis using null_sets_subset[OF a _ b] by simp\n  qed\n  obtain u::\"nat \\<Rightarrow> 'b\" where u: \"\\<And>n. u n > esssup M f\" \"u \\<longlonglongrightarrow> esssup M f\"\n    using approx_from_above_dense_linorder[OF \\<open>esssup M f < top\\<close>] by auto\n  have \"{x \\<in> space M. f x > esssup M f} = (\\<Union>n. {x \\<in> space M. f x > u n})\"\n    using u apply auto\n    apply (metis (mono_tags, lifting) order_tendsto_iff eventually_mono LIMSEQ_unique)\n    using less_imp_le less_le_trans by blast\n  also have \"... \\<in> null_sets M\"\n    using *[OF u(1)] by auto\n  finally show ?thesis by auto\nqed\n\nlemma esssup_AE: \"AE x in M. f x \\<le> esssup M f\"\nproof (cases \"f \\<in> M \\<rightarrow>\\<^sub>M borel\")\n  case True then show ?thesis\n    by (intro AE_I[OF _ esssup_zero_measure[of _ f]]) auto\nqed (simp add: esssup_non_measurable)\n\nlemma esssup_pos_measure:\n  \"f \\<in> borel_measurable M \\<Longrightarrow> z < esssup M f \\<Longrightarrow> emeasure M {x \\<in> space M. f x > z} > 0\"\n  using Inf_less_iff mem_Collect_eq not_gr_zero by (force simp: esssup_eq)\n\nlemma esssup_I [intro]: \"f \\<in> borel_measurable M \\<Longrightarrow> AE x in M. f x \\<le> c \\<Longrightarrow> esssup M f \\<le> c\"\n  unfolding esssup_def by (simp add: Limsup_bounded)\n\nlemma esssup_AE_mono: \"f \\<in> borel_measurable M \\<Longrightarrow> AE x in M. f x \\<le> g x \\<Longrightarrow> esssup M f \\<le> esssup M g\"\n  by (auto simp: esssup_def Limsup_mono)\n\nlemma esssup_mono: \"f \\<in> borel_measurable M \\<Longrightarrow> (\\<And>x. f x \\<le> g x) \\<Longrightarrow> esssup M f \\<le> esssup M g\"\n  by (rule esssup_AE_mono) auto\n\nlemma esssup_AE_cong:\n  \"f \\<in> borel_measurable M \\<Longrightarrow> g \\<in> borel_measurable M \\<Longrightarrow> AE x in M. f x = g x \\<Longrightarrow> esssup M f = esssup M g\"\n  by (auto simp: esssup_def intro!: Limsup_eq)\n\nlemma esssup_const: \"emeasure M (space M) \\<noteq> 0 \\<Longrightarrow> esssup M (\\<lambda>x. c) = c\"\n  by (simp add: esssup_def Limsup_const ae_filter_eq_bot_iff)\n\nlemma esssup_cmult: assumes \"c > (0::real)\" shows \"esssup M (\\<lambda>x. c * f x::ereal) = c * esssup M f\"\nproof -\n  have \"(\\<lambda>x. ereal c * f x) \\<in> M \\<rightarrow>\\<^sub>M borel \\<Longrightarrow> f \\<in> M \\<rightarrow>\\<^sub>M borel\"\n  proof (subst measurable_cong)\n    fix \\<omega> show \"f \\<omega> = ereal (1/c) * (ereal c * f \\<omega>)\"\n      using \\<open>0 < c\\<close> by (cases \"f \\<omega>\") auto\n  qed auto\n  then have \"(\\<lambda>x. ereal c * f x) \\<in> M \\<rightarrow>\\<^sub>M borel \\<longleftrightarrow> f \\<in> M \\<rightarrow>\\<^sub>M borel\"\n    by(safe intro!: borel_measurable_ereal_times borel_measurable_const)\n  with \\<open>0<c\\<close> show ?thesis\n    by (cases \"ae_filter M = bot\")\n       (auto simp: esssup_def bot_ereal_def top_ereal_def Limsup_ereal_mult_left)\nqed\n\nlemma esssup_add:\n  \"esssup M (\\<lambda>x. f x + g x::ereal) \\<le> esssup M f + esssup M g\"\nproof (cases \"f \\<in> borel_measurable M \\<and> g \\<in> borel_measurable M\")\n  case True\n  then have [measurable]: \"(\\<lambda>x. f x + g x) \\<in> borel_measurable M\" by auto\n  have \"f x + g x \\<le> esssup M f + esssup M g\" if \"f x \\<le> esssup M f\" \"g x \\<le> esssup M g\" for x\n    using that add_mono by auto\n  then have \"AE x in M. f x + g x \\<le> esssup M f + esssup M g\"\n    using esssup_AE[of f M] esssup_AE[of g M] by auto\n  then show ?thesis using esssup_I by auto\nnext\n  case False\n  then have \"esssup M f + esssup M g = \\<infinity>\" unfolding esssup_def top_ereal_def by auto\n  then show ?thesis by auto\nqed\n\nlemma esssup_zero_space:\n  \"emeasure M (space M) = 0 \\<Longrightarrow> f \\<in> borel_measurable M \\<Longrightarrow> esssup M f = (- \\<infinity>::ereal)\"\n  by (simp add: esssup_def ae_filter_eq_bot_iff[symmetric] bot_ereal_def)\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/Probability/Essential_Supremum.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9032941988938414, "lm_q2_score": 0.810478913248044, "lm_q1q2_score": 0.7321009006627431}}
{"text": "header{*V-Sets, Epsilon Closure, Ranks*}\n\ntheory Rank imports Ordinal\nbegin\n\nsection{*V-sets*}\n\ntext{*Definition 4.1*}\ndefinition Vset :: \"hf \\<Rightarrow> hf\"\n  where \"Vset x = ord_rec 0 HPow (\\<lambda>z. 0) x\"\n\nlemma Vset_0 [simp]: \"Vset 0 = 0\"\n  by (simp add: Vset_def)\n\nlemma Vset_succ [simp]: \"Ord k \\<Longrightarrow> Vset (succ k) = HPow (Vset k)\"\n  by (simp add: Vset_def)\n\nlemma Vset_non [simp]: \"~ Ord x \\<Longrightarrow> Vset x = 0\"\n  by (simp add: Vset_def)\n\ntext{*Theorem 4.2(a)*}\nlemma Vset_mono_strict:\n  assumes \"Ord m\" \"n <: m\" shows \"Vset n < Vset m\"\nproof -\n  have n: \"Ord n\"\n    by (metis Ord_in_Ord assms)\n  hence \"Ord m \\<Longrightarrow> n <: m \\<Longrightarrow> Vset n < Vset m\"\n  proof (induct n arbitrary: m rule: Ord_induct2)\n    case 0 thus ?case\n      by (metis HPow_iff Ord_cases Vset_0 Vset_succ hemptyE le_imp_less_or_eq zero_le)\n  next\n    case (succ n)\n    then show ?case using `Ord m`\n      by (metis Ord_cases hemptyE HPow_mono_strict_iff Vset_succ mem_succ_iff)\n  qed\n  thus ?thesis using assms .\nqed\n\nlemma Vset_mono: \"\\<lbrakk>Ord m; n \\<le> m\\<rbrakk> \\<Longrightarrow> Vset n \\<le> Vset m\"\n  by (metis Ord_linear2 Vset_mono_strict Vset_non assms order.order_iff_strict\n            order_class.order.antisym zero_le)\n\ntext{*Theorem 4.2(b)*}\nlemma Vset_Transset: \"Ord m \\<Longrightarrow> Transset (Vset m)\"\n  by (induct rule: Ord_induct2) (auto simp: Transset_def)\n\nlemma Ord_sup [simp]: \"Ord k \\<Longrightarrow> Ord l \\<Longrightarrow> Ord (k \\<squnion> l)\"\n  by (metis Ord_linear_le le_iff_sup sup_absorb1)\n\nlemma Ord_inf [simp]: \"Ord k \\<Longrightarrow> Ord l \\<Longrightarrow> Ord (k \\<sqinter> l)\"\n  by (metis Ord_linear_le inf_absorb2 le_iff_inf)\n\n\ntext{*Theorem 4.3*}\nlemma Vset_universal: \"\\<exists>n. Ord n & x \\<^bold>\\<in> Vset n\"\nproof (induct x rule: hf_induct)\n  case 0 thus ?case\n    by (metis HPow_iff Ord_0 Ord_succ Vset_succ zero_le)\nnext\n  case (hinsert a b)\n  then obtain na nb where nab: \"Ord na\" \"a \\<^bold>\\<in> Vset na\" \"Ord nb\" \"b \\<^bold>\\<in> Vset nb\"\n    by blast\n  hence \"b \\<le> Vset nb\" using Vset_Transset [of nb]\n    by (auto simp: Transset_def)\n  also have \"... \\<le> Vset (na \\<squnion> nb)\" using nab\n    by (metis Ord_sup Vset_mono sup_ge2)\n  finally have \"b \\<triangleleft> a \\<^bold>\\<in> Vset (succ (na \\<squnion> nb))\" using nab\n    by simp (metis Ord_sup Vset_mono sup_ge1 rev_hsubsetD)\n  thus ?case using nab\n    by (metis Ord_succ Ord_sup)\nqed\n\nsection{*Least Ordinal Operator*}\n\ntext{*Definition 4.4. For every x, let rank(x) be the least ordinal n such that...*}\n\nlemma Ord_minimal:\n   \"Ord k \\<Longrightarrow> P k \\<Longrightarrow> \\<exists>n. Ord n & P n & (\\<forall>m. Ord m & P m \\<longrightarrow> n \\<le> m)\"\n  by (induct k rule: Ord_induct) (metis Ord_linear2)\n\nlemma OrdLeastI: \"Ord k \\<Longrightarrow> P k \\<Longrightarrow> P(LEAST n. Ord n & P n)\"\nby (metis (lifting, no_types) Least_equality Ord_minimal)\n\nlemma OrdLeast_le: \"Ord k \\<Longrightarrow> P k \\<Longrightarrow> (LEAST n. Ord n & P n) \\<le> k\"\nby (metis (lifting, no_types) Least_equality Ord_minimal)\n\nlemma OrdLeast_Ord:\n  assumes \"Ord k\" \"P k\"shows \"Ord(LEAST n. Ord n & P n)\"\nproof -\n  obtain n where \"Ord n\" \"P n\" \"\\<forall>m. Ord m & P m \\<longrightarrow> n \\<le> m\"\n    by (metis Ord_minimal assms)\n  thus ?thesis\n    by (metis (lifting) Least_equality)\nqed\n\n\nsection{*Rank Function*}\n\ndefinition rank :: \"hf \\<Rightarrow> hf\"\n  where \"rank x = (LEAST n. Ord n & x \\<^bold>\\<in> Vset (succ n))\"\n\n\n\nlemma in_Vset_rank: \"a \\<^bold>\\<in> Vset(succ(rank a))\"\nproof -\n  from Vset_universal [of a]\n  obtain na where na: \"Ord na\" \"a \\<^bold>\\<in> Vset (succ na)\"\n    by (metis Ord_Union Ord_in_Ord Ord_pred Vset_0 hempty_iff)\n  thus ?thesis\n    by (unfold rank_def) (rule OrdLeastI)\nqed\n\nlemma Ord_rank [simp]: \"Ord (rank a)\"\n  by (metis Ord_succ_iff Vset_non hemptyE in_Vset_rank)\n\nlemma le_Vset_rank: \"a \\<le> Vset(rank a)\"\n  by (metis HPow_iff Ord_succ_iff Vset_non Vset_succ hemptyE in_Vset_rank)\n\nlemma VsetI: \"succ(rank a) \\<le> k \\<Longrightarrow> Ord k \\<Longrightarrow> a \\<^bold>\\<in> Vset k\"\n  by (metis Vset_mono hsubsetCE in_Vset_rank)\n\nlemma Vset_succ_rank_le: \"Ord k \\<Longrightarrow> a \\<^bold>\\<in> Vset (succ k) \\<Longrightarrow> rank a \\<le> k\"\n  by (unfold rank_def) (rule OrdLeast_le)\n\nlemma Vset_rank_lt: assumes a: \"a \\<^bold>\\<in> Vset k\" shows \"rank a < k\"\nproof -\n  { assume k: \"Ord k\"\n    hence ?thesis\n    proof (cases k rule: Ord_cases)\n      case 0 thus ?thesis using a\n        by simp\n    next\n      case (succ l) thus ?thesis using a\n        by (metis Ord_lt_succ_iff_le Ord_succ_iff Vset_non Vset_succ_rank_le hemptyE in_Vset_rank)\n    qed\n  }\n  thus ?thesis using a\n    by (metis Vset_non hemptyE)\nqed\n\ntext{*Theorem 4.5*}\ntheorem rank_lt: \"a \\<^bold>\\<in> b \\<Longrightarrow> rank(a) < rank(b)\"\n  by (metis Vset_rank_lt hsubsetD le_Vset_rank)\n\nlemma rank_mono: \"x \\<le> y \\<Longrightarrow> rank x \\<le> rank y\"\n  by (metis HPow_iff Ord_rank Vset_succ Vset_succ_rank_le dual_order.trans le_Vset_rank)\n\nlemma rank_sup [simp]: \"rank (a \\<squnion> b) = rank a \\<squnion> rank b\"\nproof (rule antisym)\n  have o: \"Ord (rank a \\<squnion> rank b)\"\n    by simp\n  thus \"rank (a \\<squnion> b) \\<le> rank a \\<squnion> rank b\"\n    apply (rule Vset_succ_rank_le, simp)\n    apply (metis le_Vset_rank order_trans Vset_mono sup_ge1 sup_ge2 o)\n    done\nnext\n  show \"rank a \\<squnion> rank b \\<le> rank (a \\<squnion> b)\"\n    by (metis le_supI le_supI1 le_supI2 order_eq_refl rank_mono)\nqed\n\nlemma rank_singleton [simp]: \"rank \\<lbrace>a\\<rbrace> = succ(rank a)\"\nproof -\n  have oba: \"Ord (succ (rank a))\"\n    by simp\n  show ?thesis\n    proof (rule antisym)\n      show \"rank \\<lbrace>a\\<rbrace> \\<le> succ (rank a)\"\n        by (metis Vset_succ_rank_le HPow_iff Vset_succ in_Vset_rank less_eq_insert1_iff oba zero_le)\n    next\n      show \"succ (rank a) \\<le> rank\\<lbrace>a\\<rbrace>\"\n        by (metis Ord_linear_le Ord_lt_succ_iff_le rank_lt Ord_rank hmem_hinsert less_le_not_le oba)\n    qed\nqed\n\nlemma rank_hinsert [simp]: \"rank (b \\<triangleleft> a) = rank b \\<squnion> succ(rank a)\"\n  by (metis hinsert_eq_sup rank_singleton rank_sup)\n\ntext{*Definition 4.6. The transitive closure of @{term x} is\n the minimal transitive set @{term y} such that @{term\"x\\<le>y\"}.*}\n\n\nsection{*Epsilon Closure*}\n\ndefinition\n  eclose    :: \"hf \\<Rightarrow> hf\"  where\n    \"eclose X = \\<Sqinter> \\<lbrace>Y \\<^bold>\\<in> HPow(Vset (rank X)). Transset Y & X\\<le>Y\\<rbrace>\"\n\nlemma eclose_facts:\n  shows Transset_eclose: \"Transset (eclose X)\"\n   and  le_eclose: \"X \\<le> eclose X\"\nproof -\n  have nz: \"\\<lbrace>Y \\<^bold>\\<in> HPow(Vset (rank X)). Transset Y & X\\<le>Y\\<rbrace> \\<noteq> 0\"\n    by (simp add: eclose_def hempty_iff) (metis Ord_rank Vset_Transset le_Vset_rank order_refl)\n  show \"Transset (eclose X)\" \"X \\<le> eclose X\" using HInter_iff [OF nz]\n    by (auto simp: eclose_def Transset_def)\nqed\n\nlemma eclose_minimal:\n  assumes Y: \"Transset Y\" \"X\\<le>Y\" shows \"eclose X \\<le> Y\"\nproof -\n  have \"\\<lbrace>Y \\<^bold>\\<in> HPow(Vset (rank X)). Transset Y & X\\<le>Y\\<rbrace> \\<noteq> 0\"\n    by (simp add: eclose_def hempty_iff) (metis Ord_rank Vset_Transset le_Vset_rank order_refl)\n  moreover have \"Transset (Y \\<sqinter> Vset (rank X))\"\n    by (metis Ord_rank Transset_inf Vset_Transset Y(1))\n  moreover have \"X \\<le> Y \\<sqinter> Vset (rank X)\"\n    by (metis Y(2) le_Vset_rank le_inf_iff)\n  ultimately show \"eclose X \\<le> Y\"\n    apply (auto simp: eclose_def)\n    apply (metis hinter_iff le_inf_iff order_refl)\n    done\nqed\n\nlemma eclose_0 [simp]: \"eclose 0 = 0\"\n  by (metis Ord_0 Vset_0 Vset_Transset eclose_minimal less_eq_hempty)\n\nlemma eclose_sup [simp]: \"eclose (a \\<squnion> b) = eclose a \\<squnion> eclose b\"\nproof (rule order_antisym)\n  show \"eclose (a \\<squnion> b) \\<le> eclose a \\<squnion> eclose b\"\n    by (metis Transset_eclose Transset_sup eclose_minimal le_eclose sup_mono)\nnext\n  show \"eclose a \\<squnion> eclose b \\<le> eclose (a \\<squnion> b)\"\n    by (metis Transset_eclose eclose_minimal le_eclose le_sup_iff)\nqed\n\nlemma eclose_singleton [simp]: \"eclose \\<lbrace>a\\<rbrace> = (eclose a) \\<triangleleft> a\"\nproof (rule order_antisym)\n  show \"eclose \\<lbrace>a\\<rbrace> \\<le> eclose a \\<triangleleft> a\"\n    by (metis eclose_minimal Transset_eclose Transset_hinsert\n              le_eclose less_eq_insert1_iff order_refl zero_le)\nnext\n  show \"eclose a \\<triangleleft> a \\<le> eclose \\<lbrace>a\\<rbrace>\"\n    by (metis Transset_def Transset_eclose eclose_minimal le_eclose less_eq_insert1_iff)\nqed\n\nlemma eclose_hinsert [simp]: \"eclose (b \\<triangleleft> a) = eclose b \\<squnion> (eclose a \\<triangleleft> a)\"\n  by (metis eclose_singleton eclose_sup hinsert_eq_sup)\n\nlemma eclose_succ [simp]: \"eclose (succ a) = eclose a \\<triangleleft> a\"\n  by (auto simp: succ_def)\n\nlemma fst_in_eclose [simp]: \"x \\<^bold>\\<in> eclose \\<langle>x, y\\<rangle>\"\n  by (metis eclose_hinsert hmem_hinsert hpair_def hunion_iff)\n\nlemma snd_in_eclose [simp]: \"y \\<^bold>\\<in> eclose \\<langle>x, y\\<rangle>\"\n  by (metis eclose_hinsert hmem_hinsert hpair_def hunion_iff)\n\ntext{*Theorem 4.7. rank(x) = rank(cl(x)).*}\nlemma rank_eclose [simp]: \"rank (eclose x) = rank x\"\nproof (induct x rule: hf_induct)\n  case 0 thus ?case by simp\nnext\n  case (hinsert a b) thus ?case\n    by simp (metis hinsert_eq_sup succ_def sup.left_idem)\nqed\n\n\nsection{*Epsilon-Recursion*}\n\ntext{*Theorem 4.9.  Definition of a function by recursion on rank.*}\n\nlemma hmem_induct [case_names step]:\n  assumes ih: \"\\<And>x. (\\<And>y. y \\<^bold>\\<in> x \\<Longrightarrow> P y) \\<Longrightarrow> P x\" shows \"P x\"\nproof -\n  have \"\\<And>y. y \\<^bold>\\<in> x \\<Longrightarrow> P y\"\n  proof (induct x rule: hf_induct)\n    case 0 thus ?case by simp\n  next\n    case (hinsert a b) thus ?case\n      by (metis assms hmem_hinsert)\n  qed\n  thus ?thesis by (metis ih)\nqed\n\ndefinition\n  hmem_rel :: \"(hf * hf) set\" where\n  \"hmem_rel = trancl {(x,y). x <: y}\"\n\nlemma wf_hmem_rel: \"wf hmem_rel\"\nproof -\n  have \"wf {(x,y). x <: y}\"\n    by (metis (full_types) hmem_induct wfPUNIVI wfP_def)\n  thus ?thesis\n    by (metis hmem_rel_def wf_trancl)\nqed\n\nlemma hmem_eclose_le: \"y \\<^bold>\\<in> x \\<Longrightarrow> eclose y \\<le> eclose x\"\n  by (metis Transset_def Transset_eclose eclose_minimal hsubsetD le_eclose)\n\nlemma hmem_rel_iff_hmem_eclose: \"(x,y) \\<in> hmem_rel \\<longleftrightarrow> x <: eclose y\"\nproof (unfold hmem_rel_def, rule iffI)\n  assume \"(x, y) \\<in> trancl {(x, y). x \\<^bold>\\<in> y}\"\n  thus \"x \\<^bold>\\<in> eclose y\"\n    proof (induct rule: trancl_induct)\n      case (base y) thus ?case\n        by (metis hsubsetCE le_eclose mem_Collect_eq split_conv)\n    next\n      case (step y z) thus ?case\n        by (metis hmem_eclose_le hsubsetD mem_Collect_eq split_conv)\n    qed\nnext\n  have \"Transset \\<lbrace>x \\<^bold>\\<in> eclose y. (x, y) \\<in> hmem_rel\\<rbrace>\" using Transset_eclose\n    by (auto simp: Transset_def hmem_rel_def intro: trancl_trans)\n  hence \"eclose y \\<le> \\<lbrace>x \\<^bold>\\<in> eclose y. (x, y) \\<in> hmem_rel\\<rbrace>\"\n    by (rule eclose_minimal) (auto simp: le_HCollect_iff le_eclose hmem_rel_def)\n  moreover assume \"x \\<^bold>\\<in> eclose y\"\n  ultimately show \"(x, y) \\<in> trancl {(x, y). x \\<^bold>\\<in> y}\"\n    by (metis HCollect_iff hmem_rel_def hsubsetD)\nqed\n\ndefinition hmemrec :: \"((hf \\<Rightarrow> 'a) \\<Rightarrow> hf \\<Rightarrow> 'a) \\<Rightarrow> hf \\<Rightarrow> 'a\" where\n  \"hmemrec G \\<equiv> wfrec hmem_rel G\"\n\ndefinition ecut :: \"(hf \\<Rightarrow> 'a) \\<Rightarrow> hf \\<Rightarrow> hf \\<Rightarrow> 'a\" where\n  \"ecut f x \\<equiv> (\\<lambda>y. if y \\<^bold>\\<in> eclose x then f y else undefined)\"\n\nlemma hmemrec: \"hmemrec G a = G (ecut (hmemrec G) a) a\"\n  by (simp add: cut_def ecut_def hmem_rel_iff_hmem_eclose def_wfrec [OF hmemrec_def wf_hmem_rel])\n\ntext{*This form avoids giant explosions in proofs.*}\nlemma def_hmemrec: \"f \\<equiv> hmemrec G \\<Longrightarrow> f a = G (ecut (hmemrec G) a) a\"\n  by (metis hmemrec)\n\nlemma ecut_apply: \"y \\<^bold>\\<in> eclose x \\<Longrightarrow> ecut f x y = f y\"\n  by (metis ecut_def)\n\nlemma RepFun_ecut: \"y \\<le> z \\<Longrightarrow> RepFun y (ecut f z) = RepFun y f\"\n  apply (auto simp: hf_ext)\n  apply (metis ecut_def hsubsetD le_eclose)\n  apply (metis ecut_apply le_eclose hsubsetD)\n  done\n\ntext{*Now, a stronger induction rule, for the transitive closure of membership*}\nlemma hmem_rel_induct [case_names step]:\n  assumes ih: \"\\<And>x. (\\<And>y. (y,x) \\<in> hmem_rel \\<Longrightarrow> P y) \\<Longrightarrow> P x\" shows \"P x\"\nproof -\n  have \"\\<And>y. (y,x) \\<in> hmem_rel \\<Longrightarrow> P y\"\n  proof (induct x rule: hf_induct)\n    case 0 thus ?case\n      by (metis eclose_0 hmem_hempty hmem_rel_iff_hmem_eclose)\n  next\n    case (hinsert a b)\n    thus ?case\n      by (metis assms eclose_hinsert hmem_hinsert hmem_rel_iff_hmem_eclose hunion_iff)\n  qed\n  thus ?thesis  by (metis assms)\nqed\n\nlemma rank_HUnion_less:  \"x \\<noteq> 0 \\<Longrightarrow> rank (\\<Squnion>x) < rank x\"\n  apply (induct x rule: hf_induct, auto)\n  apply (metis hmem_hinsert rank_hinsert rank_lt)\n  apply (metis HUnion_hempty Ord_lt_succ_iff_le Ord_rank hunion_hempty_right\n               less_supI1 less_supI2 rank_sup sup.cobounded2)\n  done\n\ncorollary Sup_ne: \"x \\<noteq> 0 \\<Longrightarrow> \\<Squnion>x \\<noteq> x\"\n  by (metis less_irrefl rank_HUnion_less)\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/Rank.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9059898305367525, "lm_q2_score": 0.8080672112416737, "lm_q1q2_score": 0.7321006757751501}}
{"text": "(*  Title:      ZF/Order.thy\n    Author:     Lawrence C Paulson, Cambridge University Computer Laboratory\n    Copyright   1994  University of Cambridge\n\nResults from the book \"Set Theory: an Introduction to Independence Proofs\"\n        by Kenneth Kunen.  Chapter 1, section 6.\nAdditional definitions and lemmas for reflexive orders.\n*)\n\nsection\\<open>Partial and Total Orderings: Basic Definitions and Properties\\<close>\n\ntheory Order imports WF Perm begin\n\ntext \\<open>We adopt the following convention: \\<open>ord\\<close> is used for\n  strict orders and \\<open>order\\<close> is used for their reflexive\n  counterparts.\\<close>\n\ndefinition\n  part_ord :: \"[i,i]=>o\"                (*Strict partial ordering*)  where\n   \"part_ord(A,r) == irrefl(A,r) & trans[A](r)\"\n\ndefinition\n  linear   :: \"[i,i]=>o\"                (*Strict total ordering*)  where\n   \"linear(A,r) == (\\<forall>x\\<in>A. \\<forall>y\\<in>A. <x,y>:r | x=y | <y,x>:r)\"\n\ndefinition\n  tot_ord  :: \"[i,i]=>o\"                (*Strict total ordering*)  where\n   \"tot_ord(A,r) == part_ord(A,r) & linear(A,r)\"\n\ndefinition\n  \"preorder_on(A, r) \\<equiv> refl(A, r) \\<and> trans[A](r)\"\n\ndefinition                              (*Partial ordering*)\n  \"partial_order_on(A, r) \\<equiv> preorder_on(A, r) \\<and> antisym(r)\"\n\nabbreviation\n  \"Preorder(r) \\<equiv> preorder_on(field(r), r)\"\n\nabbreviation\n  \"Partial_order(r) \\<equiv> partial_order_on(field(r), r)\"\n\ndefinition\n  well_ord :: \"[i,i]=>o\"                (*Well-ordering*)  where\n   \"well_ord(A,r) == tot_ord(A,r) & wf[A](r)\"\n\ndefinition\n  mono_map :: \"[i,i,i,i]=>i\"            (*Order-preserving maps*)  where\n   \"mono_map(A,r,B,s) ==\n              {f \\<in> A->B. \\<forall>x\\<in>A. \\<forall>y\\<in>A. <x,y>:r \\<longrightarrow> <f`x,f`y>:s}\"\n\ndefinition\n  ord_iso  :: \"[i,i,i,i]=>i\"  (\\<open>(\\<langle>_, _\\<rangle> \\<cong>/ \\<langle>_, _\\<rangle>)\\<close> 51)  (*Order isomorphisms*)  where\n   \"\\<langle>A,r\\<rangle> \\<cong> \\<langle>B,s\\<rangle> ==\n              {f \\<in> bij(A,B). \\<forall>x\\<in>A. \\<forall>y\\<in>A. <x,y>:r \\<longleftrightarrow> <f`x,f`y>:s}\"\n\ndefinition\n  pred     :: \"[i,i,i]=>i\"              (*Set of predecessors*)  where\n   \"pred(A,x,r) == {y \\<in> A. <y,x>:r}\"\n\ndefinition\n  ord_iso_map :: \"[i,i,i,i]=>i\"         (*Construction for linearity theorem*)  where\n   \"ord_iso_map(A,r,B,s) ==\n     \\<Union>x\\<in>A. \\<Union>y\\<in>B. \\<Union>f \\<in> ord_iso(pred(A,x,r), r, pred(B,y,s), s). {<x,y>}\"\n\ndefinition\n  first :: \"[i, i, i] => o\"  where\n    \"first(u, X, R) == u \\<in> X & (\\<forall>v\\<in>X. v\\<noteq>u \\<longrightarrow> <u,v> \\<in> R)\"\n\nsubsection\\<open>Immediate Consequences of the Definitions\\<close>\n\nlemma part_ord_Imp_asym:\n    \"part_ord(A,r) ==> asym(r \\<inter> A*A)\"\nby (unfold part_ord_def irrefl_def trans_on_def asym_def, blast)\n\nlemma linearE:\n    \"[| linear(A,r);  x \\<in> A;  y \\<in> A;\n        <x,y>:r ==> P;  x=y ==> P;  <y,x>:r ==> P |]\n     ==> P\"\nby (simp add: linear_def, blast)\n\n\n(** General properties of well_ord **)\n\nlemma well_ordI:\n    \"[| wf[A](r); linear(A,r) |] ==> well_ord(A,r)\"\napply (simp add: irrefl_def part_ord_def tot_ord_def\n                 trans_on_def well_ord_def wf_on_not_refl)\napply (fast elim: linearE wf_on_asym wf_on_chain3)\ndone\n\nlemma well_ord_is_wf:\n    \"well_ord(A,r) ==> wf[A](r)\"\nby (unfold well_ord_def, safe)\n\nlemma well_ord_is_trans_on:\n    \"well_ord(A,r) ==> trans[A](r)\"\nby (unfold well_ord_def tot_ord_def part_ord_def, safe)\n\nlemma well_ord_is_linear: \"well_ord(A,r) ==> linear(A,r)\"\nby (unfold well_ord_def tot_ord_def, blast)\n\n\n(** Derived rules for pred(A,x,r) **)\n\nlemma pred_iff: \"y \\<in> pred(A,x,r) \\<longleftrightarrow> <y,x>:r & y \\<in> A\"\nby (unfold pred_def, blast)\n\nlemmas predI = conjI [THEN pred_iff [THEN iffD2]]\n\nlemma predE: \"[| y \\<in> pred(A,x,r);  [| y \\<in> A; <y,x>:r |] ==> P |] ==> P\"\nby (simp add: pred_def)\n\nlemma pred_subset_under: \"pred(A,x,r) \\<subseteq> r -`` {x}\"\nby (simp add: pred_def, blast)\n\nlemma pred_subset: \"pred(A,x,r) \\<subseteq> A\"\nby (simp add: pred_def, blast)\n\nlemma pred_pred_eq:\n    \"pred(pred(A,x,r), y, r) = pred(A,x,r) \\<inter> pred(A,y,r)\"\nby (simp add: pred_def, blast)\n\nlemma trans_pred_pred_eq:\n    \"[| trans[A](r);  <y,x>:r;  x \\<in> A;  y \\<in> A |]\n     ==> pred(pred(A,x,r), y, r) = pred(A,y,r)\"\nby (unfold trans_on_def pred_def, blast)\n\n\nsubsection\\<open>Restricting an Ordering's Domain\\<close>\n\n(** The ordering's properties hold over all subsets of its domain\n    [including initial segments of the form pred(A,x,r) **)\n\n(*Note: a relation s such that s<=r need not be a partial ordering*)\nlemma part_ord_subset:\n    \"[| part_ord(A,r);  B<=A |] ==> part_ord(B,r)\"\nby (unfold part_ord_def irrefl_def trans_on_def, blast)\n\nlemma linear_subset:\n    \"[| linear(A,r);  B<=A |] ==> linear(B,r)\"\nby (unfold linear_def, blast)\n\nlemma tot_ord_subset:\n    \"[| tot_ord(A,r);  B<=A |] ==> tot_ord(B,r)\"\napply (unfold tot_ord_def)\napply (fast elim!: part_ord_subset linear_subset)\ndone\n\nlemma well_ord_subset:\n    \"[| well_ord(A,r);  B<=A |] ==> well_ord(B,r)\"\napply (unfold well_ord_def)\napply (fast elim!: tot_ord_subset wf_on_subset_A)\ndone\n\n\n(** Relations restricted to a smaller domain, by Krzysztof Grabczewski **)\n\nlemma irrefl_Int_iff: \"irrefl(A,r \\<inter> A*A) \\<longleftrightarrow> irrefl(A,r)\"\nby (unfold irrefl_def, blast)\n\nlemma trans_on_Int_iff: \"trans[A](r \\<inter> A*A) \\<longleftrightarrow> trans[A](r)\"\nby (unfold trans_on_def, blast)\n\nlemma part_ord_Int_iff: \"part_ord(A,r \\<inter> A*A) \\<longleftrightarrow> part_ord(A,r)\"\napply (unfold part_ord_def)\napply (simp add: irrefl_Int_iff trans_on_Int_iff)\ndone\n\nlemma linear_Int_iff: \"linear(A,r \\<inter> A*A) \\<longleftrightarrow> linear(A,r)\"\nby (unfold linear_def, blast)\n\nlemma tot_ord_Int_iff: \"tot_ord(A,r \\<inter> A*A) \\<longleftrightarrow> tot_ord(A,r)\"\napply (unfold tot_ord_def)\napply (simp add: part_ord_Int_iff linear_Int_iff)\ndone\n\nlemma wf_on_Int_iff: \"wf[A](r \\<inter> A*A) \\<longleftrightarrow> wf[A](r)\"\napply (unfold wf_on_def wf_def, fast) (*10 times faster than blast!*)\ndone\n\nlemma well_ord_Int_iff: \"well_ord(A,r \\<inter> A*A) \\<longleftrightarrow> well_ord(A,r)\"\napply (unfold well_ord_def)\napply (simp add: tot_ord_Int_iff wf_on_Int_iff)\ndone\n\n\nsubsection\\<open>Empty and Unit Domains\\<close>\n\n(*The empty relation is well-founded*)\nlemma wf_on_any_0: \"wf[A](0)\"\nby (simp add: wf_on_def wf_def, fast)\n\nsubsubsection\\<open>Relations over the Empty Set\\<close>\n\nlemma irrefl_0: \"irrefl(0,r)\"\nby (unfold irrefl_def, blast)\n\nlemma trans_on_0: \"trans[0](r)\"\nby (unfold trans_on_def, blast)\n\nlemma part_ord_0: \"part_ord(0,r)\"\napply (unfold part_ord_def)\napply (simp add: irrefl_0 trans_on_0)\ndone\n\nlemma linear_0: \"linear(0,r)\"\nby (unfold linear_def, blast)\n\nlemma tot_ord_0: \"tot_ord(0,r)\"\napply (unfold tot_ord_def)\napply (simp add: part_ord_0 linear_0)\ndone\n\nlemma wf_on_0: \"wf[0](r)\"\nby (unfold wf_on_def wf_def, blast)\n\nlemma well_ord_0: \"well_ord(0,r)\"\napply (unfold well_ord_def)\napply (simp add: tot_ord_0 wf_on_0)\ndone\n\n\nsubsubsection\\<open>The Empty Relation Well-Orders the Unit Set\\<close>\n\ntext\\<open>by Grabczewski\\<close>\n\nlemma tot_ord_unit: \"tot_ord({a},0)\"\nby (simp add: irrefl_def trans_on_def part_ord_def linear_def tot_ord_def)\n\nlemma well_ord_unit: \"well_ord({a},0)\"\napply (unfold well_ord_def)\napply (simp add: tot_ord_unit wf_on_any_0)\ndone\n\n\nsubsection\\<open>Order-Isomorphisms\\<close>\n\ntext\\<open>Suppes calls them \"similarities\"\\<close>\n\n(** Order-preserving (monotone) maps **)\n\nlemma mono_map_is_fun: \"f \\<in> mono_map(A,r,B,s) ==> f \\<in> A->B\"\nby (simp add: mono_map_def)\n\nlemma mono_map_is_inj:\n    \"[| linear(A,r);  wf[B](s);  f \\<in> mono_map(A,r,B,s) |] ==> f \\<in> inj(A,B)\"\napply (unfold mono_map_def inj_def, clarify)\napply (erule_tac x=w and y=x in linearE, assumption+)\napply (force intro: apply_type dest: wf_on_not_refl)+\ndone\n\nlemma ord_isoI:\n    \"[| f \\<in> bij(A, B);\n        !!x y. [| x \\<in> A; y \\<in> A |] ==> <x, y> \\<in> r \\<longleftrightarrow> <f`x, f`y> \\<in> s |]\n     ==> f \\<in> ord_iso(A,r,B,s)\"\nby (simp add: ord_iso_def)\n\nlemma ord_iso_is_mono_map:\n    \"f \\<in> ord_iso(A,r,B,s) ==> f \\<in> mono_map(A,r,B,s)\"\napply (simp add: ord_iso_def mono_map_def)\napply (blast dest!: bij_is_fun)\ndone\n\nlemma ord_iso_is_bij:\n    \"f \\<in> ord_iso(A,r,B,s) ==> f \\<in> bij(A,B)\"\nby (simp add: ord_iso_def)\n\n(*Needed?  But ord_iso_converse is!*)\nlemma ord_iso_apply:\n    \"[| f \\<in> ord_iso(A,r,B,s);  <x,y>: r;  x \\<in> A;  y \\<in> A |] ==> <f`x, f`y> \\<in> s\"\nby (simp add: ord_iso_def)\n\nlemma ord_iso_converse:\n    \"[| f \\<in> ord_iso(A,r,B,s);  <x,y>: s;  x \\<in> B;  y \\<in> B |]\n     ==> <converse(f) ` x, converse(f) ` y> \\<in> r\"\napply (simp add: ord_iso_def, clarify)\napply (erule bspec [THEN bspec, THEN iffD2])\napply (erule asm_rl bij_converse_bij [THEN bij_is_fun, THEN apply_type])+\napply (auto simp add: right_inverse_bij)\ndone\n\n\n(** Symmetry and Transitivity Rules **)\n\n(*Reflexivity of similarity*)\nlemma ord_iso_refl: \"id(A): ord_iso(A,r,A,r)\"\nby (rule id_bij [THEN ord_isoI], simp)\n\n(*Symmetry of similarity*)\nlemma ord_iso_sym: \"f \\<in> ord_iso(A,r,B,s) ==> converse(f): ord_iso(B,s,A,r)\"\napply (simp add: ord_iso_def)\napply (auto simp add: right_inverse_bij bij_converse_bij\n                      bij_is_fun [THEN apply_funtype])\ndone\n\n(*Transitivity of similarity*)\nlemma mono_map_trans:\n    \"[| g \\<in> mono_map(A,r,B,s);  f \\<in> mono_map(B,s,C,t) |]\n     ==> (f O g): mono_map(A,r,C,t)\"\napply (unfold mono_map_def)\napply (auto simp add: comp_fun)\ndone\n\n(*Transitivity of similarity: the order-isomorphism relation*)\nlemma ord_iso_trans:\n    \"[| g \\<in> ord_iso(A,r,B,s);  f \\<in> ord_iso(B,s,C,t) |]\n     ==> (f O g): ord_iso(A,r,C,t)\"\napply (unfold ord_iso_def, clarify)\napply (frule bij_is_fun [of f])\napply (frule bij_is_fun [of g])\napply (auto simp add: comp_bij)\ndone\n\n(** Two monotone maps can make an order-isomorphism **)\n\nlemma mono_ord_isoI:\n    \"[| f \\<in> mono_map(A,r,B,s);  g \\<in> mono_map(B,s,A,r);\n        f O g = id(B);  g O f = id(A) |] ==> f \\<in> ord_iso(A,r,B,s)\"\napply (simp add: ord_iso_def mono_map_def, safe)\napply (intro fg_imp_bijective, auto)\napply (subgoal_tac \"<g` (f`x), g` (f`y) > \\<in> r\")\napply (simp add: comp_eq_id_iff [THEN iffD1])\napply (blast intro: apply_funtype)\ndone\n\nlemma well_ord_mono_ord_isoI:\n     \"[| well_ord(A,r);  well_ord(B,s);\n         f \\<in> mono_map(A,r,B,s);  converse(f): mono_map(B,s,A,r) |]\n      ==> f \\<in> ord_iso(A,r,B,s)\"\napply (intro mono_ord_isoI, auto)\napply (frule mono_map_is_fun [THEN fun_is_rel])\napply (erule converse_converse [THEN subst], rule left_comp_inverse)\napply (blast intro: left_comp_inverse mono_map_is_inj well_ord_is_linear\n                    well_ord_is_wf)+\ndone\n\n\n(** Order-isomorphisms preserve the ordering's properties **)\n\nlemma part_ord_ord_iso:\n    \"[| part_ord(B,s);  f \\<in> ord_iso(A,r,B,s) |] ==> part_ord(A,r)\"\napply (simp add: part_ord_def irrefl_def trans_on_def ord_iso_def)\napply (fast intro: bij_is_fun [THEN apply_type])\ndone\n\nlemma linear_ord_iso:\n    \"[| linear(B,s);  f \\<in> ord_iso(A,r,B,s) |] ==> linear(A,r)\"\napply (simp add: linear_def ord_iso_def, safe)\napply (drule_tac x1 = \"f`x\" and x = \"f`y\" in bspec [THEN bspec])\napply (safe elim!: bij_is_fun [THEN apply_type])\napply (drule_tac t = \"(`) (converse (f))\" in subst_context)\napply (simp add: left_inverse_bij)\ndone\n\nlemma wf_on_ord_iso:\n    \"[| wf[B](s);  f \\<in> ord_iso(A,r,B,s) |] ==> wf[A](r)\"\napply (simp add: wf_on_def wf_def ord_iso_def, safe)\napply (drule_tac x = \"{f`z. z \\<in> Z \\<inter> A}\" in spec)\napply (safe intro!: equalityI)\napply (blast dest!: equalityD1 intro: bij_is_fun [THEN apply_type])+\ndone\n\nlemma well_ord_ord_iso:\n    \"[| well_ord(B,s);  f \\<in> ord_iso(A,r,B,s) |] ==> well_ord(A,r)\"\napply (unfold well_ord_def tot_ord_def)\napply (fast elim!: part_ord_ord_iso linear_ord_iso wf_on_ord_iso)\ndone\n\n\nsubsection\\<open>Main results of Kunen, Chapter 1 section 6\\<close>\n\n(*Inductive argument for Kunen's Lemma 6.1, etc.\n  Simple proof from Halmos, page 72*)\nlemma well_ord_iso_subset_lemma:\n     \"[| well_ord(A,r);  f \\<in> ord_iso(A,r, A',r);  A'<= A;  y \\<in> A |]\n      ==> ~ <f`y, y>: r\"\napply (simp add: well_ord_def ord_iso_def)\napply (elim conjE CollectE)\napply (rule_tac a=y in wf_on_induct, assumption+)\napply (blast dest: bij_is_fun [THEN apply_type])\ndone\n\n(*Kunen's Lemma 6.1 \\<in> there's no order-isomorphism to an initial segment\n                     of a well-ordering*)\nlemma well_ord_iso_predE:\n     \"[| well_ord(A,r);  f \\<in> ord_iso(A, r, pred(A,x,r), r);  x \\<in> A |] ==> P\"\napply (insert well_ord_iso_subset_lemma [of A r f \"pred(A,x,r)\" x])\napply (simp add: pred_subset)\n(*Now we know  f`x < x *)\napply (drule ord_iso_is_bij [THEN bij_is_fun, THEN apply_type], assumption)\n(*Now we also know @{term\"f`x \\<in> pred(A,x,r)\"}: contradiction! *)\napply (simp add: well_ord_def pred_def)\ndone\n\n(*Simple consequence of Lemma 6.1*)\nlemma well_ord_iso_pred_eq:\n     \"[| well_ord(A,r);  f \\<in> ord_iso(pred(A,a,r), r, pred(A,c,r), r);\n         a \\<in> A;  c \\<in> A |] ==> a=c\"\napply (frule well_ord_is_trans_on)\napply (frule well_ord_is_linear)\napply (erule_tac x=a and y=c in linearE, assumption+)\napply (drule ord_iso_sym)\n(*two symmetric cases*)\napply (auto elim!: well_ord_subset [OF _ pred_subset, THEN well_ord_iso_predE]\n            intro!: predI\n            simp add: trans_pred_pred_eq)\ndone\n\n(*Does not assume r is a wellordering!*)\nlemma ord_iso_image_pred:\n     \"[|f \\<in> ord_iso(A,r,B,s);  a \\<in> A|] ==> f `` pred(A,a,r) = pred(B, f`a, s)\"\napply (unfold ord_iso_def pred_def)\napply (erule CollectE)\napply (simp (no_asm_simp) add: image_fun [OF bij_is_fun Collect_subset])\napply (rule equalityI)\napply (safe elim!: bij_is_fun [THEN apply_type])\napply (rule RepFun_eqI)\napply (blast intro!: right_inverse_bij [symmetric])\napply (auto simp add: right_inverse_bij  bij_is_fun [THEN apply_funtype])\ndone\n\nlemma ord_iso_restrict_image:\n     \"[| f \\<in> ord_iso(A,r,B,s);  C<=A |]\n      ==> restrict(f,C) \\<in> ord_iso(C, r, f``C, s)\"\napply (simp add: ord_iso_def)\napply (blast intro: bij_is_inj restrict_bij)\ndone\n\n(*But in use, A and B may themselves be initial segments.  Then use\n  trans_pred_pred_eq to simplify the pred(pred...) terms.  See just below.*)\nlemma ord_iso_restrict_pred:\n   \"[| f \\<in> ord_iso(A,r,B,s);   a \\<in> A |]\n    ==> restrict(f, pred(A,a,r)) \\<in> ord_iso(pred(A,a,r), r, pred(B, f`a, s), s)\"\napply (simp add: ord_iso_image_pred [symmetric])\napply (blast intro: ord_iso_restrict_image elim: predE)\ndone\n\n(*Tricky; a lot of forward proof!*)\nlemma well_ord_iso_preserving:\n     \"[| well_ord(A,r);  well_ord(B,s);  <a,c>: r;\n         f \\<in> ord_iso(pred(A,a,r), r, pred(B,b,s), s);\n         g \\<in> ord_iso(pred(A,c,r), r, pred(B,d,s), s);\n         a \\<in> A;  c \\<in> A;  b \\<in> B;  d \\<in> B |] ==> <b,d>: s\"\napply (frule ord_iso_is_bij [THEN bij_is_fun, THEN apply_type], (erule asm_rl predI predE)+)\napply (subgoal_tac \"b = g`a\")\napply (simp (no_asm_simp))\napply (rule well_ord_iso_pred_eq, auto)\napply (frule ord_iso_restrict_pred, (erule asm_rl predI)+)\napply (simp add: well_ord_is_trans_on trans_pred_pred_eq)\napply (erule ord_iso_sym [THEN ord_iso_trans], assumption)\ndone\n\n(*See Halmos, page 72*)\nlemma well_ord_iso_unique_lemma:\n     \"[| well_ord(A,r);\n         f \\<in> ord_iso(A,r, B,s);  g \\<in> ord_iso(A,r, B,s);  y \\<in> A |]\n      ==> ~ <g`y, f`y> \\<in> s\"\napply (frule well_ord_iso_subset_lemma)\napply (rule_tac f = \"converse (f) \" and g = g in ord_iso_trans)\napply auto\napply (blast intro: ord_iso_sym)\napply (frule ord_iso_is_bij [of f])\napply (frule ord_iso_is_bij [of g])\napply (frule ord_iso_converse)\napply (blast intro!: bij_converse_bij\n             intro: bij_is_fun apply_funtype)+\napply (erule notE)\napply (simp add: left_inverse_bij bij_is_fun comp_fun_apply [of _ A B])\ndone\n\n\n(*Kunen's Lemma 6.2: Order-isomorphisms between well-orderings are unique*)\nlemma well_ord_iso_unique: \"[| well_ord(A,r);\n         f \\<in> ord_iso(A,r, B,s);  g \\<in> ord_iso(A,r, B,s) |] ==> f = g\"\napply (rule fun_extension)\napply (erule ord_iso_is_bij [THEN bij_is_fun])+\napply (subgoal_tac \"f`x \\<in> B & g`x \\<in> B & linear(B,s)\")\n apply (simp add: linear_def)\n apply (blast dest: well_ord_iso_unique_lemma)\napply (blast intro: ord_iso_is_bij bij_is_fun apply_funtype\n                    well_ord_is_linear well_ord_ord_iso ord_iso_sym)\ndone\n\nsubsection\\<open>Towards Kunen's Theorem 6.3: Linearity of the Similarity Relation\\<close>\n\nlemma ord_iso_map_subset: \"ord_iso_map(A,r,B,s) \\<subseteq> A*B\"\nby (unfold ord_iso_map_def, blast)\n\nlemma domain_ord_iso_map: \"domain(ord_iso_map(A,r,B,s)) \\<subseteq> A\"\nby (unfold ord_iso_map_def, blast)\n\nlemma range_ord_iso_map: \"range(ord_iso_map(A,r,B,s)) \\<subseteq> B\"\nby (unfold ord_iso_map_def, blast)\n\nlemma converse_ord_iso_map:\n    \"converse(ord_iso_map(A,r,B,s)) = ord_iso_map(B,s,A,r)\"\napply (unfold ord_iso_map_def)\napply (blast intro: ord_iso_sym)\ndone\n\nlemma function_ord_iso_map:\n    \"well_ord(B,s) ==> function(ord_iso_map(A,r,B,s))\"\napply (unfold ord_iso_map_def function_def)\napply (blast intro: well_ord_iso_pred_eq ord_iso_sym ord_iso_trans)\ndone\n\nlemma ord_iso_map_fun: \"well_ord(B,s) ==> ord_iso_map(A,r,B,s)\n           \\<in> domain(ord_iso_map(A,r,B,s)) -> range(ord_iso_map(A,r,B,s))\"\nby (simp add: Pi_iff function_ord_iso_map\n                 ord_iso_map_subset [THEN domain_times_range])\n\nlemma ord_iso_map_mono_map:\n    \"[| well_ord(A,r);  well_ord(B,s) |]\n     ==> ord_iso_map(A,r,B,s)\n           \\<in> mono_map(domain(ord_iso_map(A,r,B,s)), r,\n                      range(ord_iso_map(A,r,B,s)), s)\"\napply (unfold mono_map_def)\napply (simp (no_asm_simp) add: ord_iso_map_fun)\napply safe\napply (subgoal_tac \"x \\<in> A & ya:A & y \\<in> B & yb:B\")\n apply (simp add: apply_equality [OF _  ord_iso_map_fun])\n apply (unfold ord_iso_map_def)\n apply (blast intro: well_ord_iso_preserving, blast)\ndone\n\nlemma ord_iso_map_ord_iso:\n    \"[| well_ord(A,r);  well_ord(B,s) |] ==> ord_iso_map(A,r,B,s)\n           \\<in> ord_iso(domain(ord_iso_map(A,r,B,s)), r,\n                      range(ord_iso_map(A,r,B,s)), s)\"\napply (rule well_ord_mono_ord_isoI)\n   prefer 4\n   apply (rule converse_ord_iso_map [THEN subst])\n   apply (simp add: ord_iso_map_mono_map\n                    ord_iso_map_subset [THEN converse_converse])\napply (blast intro!: domain_ord_iso_map range_ord_iso_map\n             intro: well_ord_subset ord_iso_map_mono_map)+\ndone\n\n\n(*One way of saying that domain(ord_iso_map(A,r,B,s)) is downwards-closed*)\nlemma domain_ord_iso_map_subset:\n     \"[| well_ord(A,r);  well_ord(B,s);\n         a \\<in> A;  a \\<notin> domain(ord_iso_map(A,r,B,s)) |]\n      ==>  domain(ord_iso_map(A,r,B,s)) \\<subseteq> pred(A, a, r)\"\napply (unfold ord_iso_map_def)\napply (safe intro!: predI)\n(*Case analysis on  xa vs a in r *)\napply (simp (no_asm_simp))\napply (frule_tac A = A in well_ord_is_linear)\napply (rename_tac b y f)\napply (erule_tac x=b and y=a in linearE, assumption+)\n(*Trivial case: b=a*)\napply clarify\napply blast\n(*Harder case: <a, xa>: r*)\napply (frule ord_iso_is_bij [THEN bij_is_fun, THEN apply_type],\n       (erule asm_rl predI predE)+)\napply (frule ord_iso_restrict_pred)\n apply (simp add: pred_iff)\napply (simp split: split_if_asm\n          add: well_ord_is_trans_on trans_pred_pred_eq domain_UN domain_Union, blast)\ndone\n\n(*For the 4-way case analysis in the main result*)\nlemma domain_ord_iso_map_cases:\n     \"[| well_ord(A,r);  well_ord(B,s) |]\n      ==> domain(ord_iso_map(A,r,B,s)) = A |\n          (\\<exists>x\\<in>A. domain(ord_iso_map(A,r,B,s)) = pred(A,x,r))\"\napply (frule well_ord_is_wf)\napply (unfold wf_on_def wf_def)\napply (drule_tac x = \"A-domain (ord_iso_map (A,r,B,s))\" in spec)\napply safe\n(*The first case: the domain equals A*)\napply (rule domain_ord_iso_map [THEN equalityI])\napply (erule Diff_eq_0_iff [THEN iffD1])\n(*The other case: the domain equals an initial segment*)\napply (blast del: domainI subsetI\n             elim!: predE\n             intro!: domain_ord_iso_map_subset\n             intro: subsetI)+\ndone\n\n(*As above, by duality*)\nlemma range_ord_iso_map_cases:\n    \"[| well_ord(A,r);  well_ord(B,s) |]\n     ==> range(ord_iso_map(A,r,B,s)) = B |\n         (\\<exists>y\\<in>B. range(ord_iso_map(A,r,B,s)) = pred(B,y,s))\"\napply (rule converse_ord_iso_map [THEN subst])\napply (simp add: domain_ord_iso_map_cases)\ndone\n\ntext\\<open>Kunen's Theorem 6.3: Fundamental Theorem for Well-Ordered Sets\\<close>\ntheorem well_ord_trichotomy:\n   \"[| well_ord(A,r);  well_ord(B,s) |]\n    ==> ord_iso_map(A,r,B,s) \\<in> ord_iso(A, r, B, s) |\n        (\\<exists>x\\<in>A. ord_iso_map(A,r,B,s) \\<in> ord_iso(pred(A,x,r), r, B, s)) |\n        (\\<exists>y\\<in>B. ord_iso_map(A,r,B,s) \\<in> ord_iso(A, r, pred(B,y,s), s))\"\napply (frule_tac B = B in domain_ord_iso_map_cases, assumption)\napply (frule_tac B = B in range_ord_iso_map_cases, assumption)\napply (drule ord_iso_map_ord_iso, assumption)\napply (elim disjE bexE)\n   apply (simp_all add: bexI)\napply (rule wf_on_not_refl [THEN notE])\n  apply (erule well_ord_is_wf)\n apply assumption\napply (subgoal_tac \"<x,y>: ord_iso_map (A,r,B,s) \")\n apply (drule rangeI)\n apply (simp add: pred_def)\napply (unfold ord_iso_map_def, blast)\ndone\n\n\nsubsection\\<open>Miscellaneous Results by Krzysztof Grabczewski\\<close>\n\n(** Properties of converse(r) **)\n\nlemma irrefl_converse: \"irrefl(A,r) ==> irrefl(A,converse(r))\"\nby (unfold irrefl_def, blast)\n\nlemma trans_on_converse: \"trans[A](r) ==> trans[A](converse(r))\"\nby (unfold trans_on_def, blast)\n\nlemma part_ord_converse: \"part_ord(A,r) ==> part_ord(A,converse(r))\"\napply (unfold part_ord_def)\napply (blast intro!: irrefl_converse trans_on_converse)\ndone\n\nlemma linear_converse: \"linear(A,r) ==> linear(A,converse(r))\"\nby (unfold linear_def, blast)\n\nlemma tot_ord_converse: \"tot_ord(A,r) ==> tot_ord(A,converse(r))\"\napply (unfold tot_ord_def)\napply (blast intro!: part_ord_converse linear_converse)\ndone\n\n\n(** By Krzysztof Grabczewski.\n    Lemmas involving the first element of a well ordered set **)\n\nlemma first_is_elem: \"first(b,B,r) ==> b \\<in> B\"\nby (unfold first_def, blast)\n\nlemma well_ord_imp_ex1_first:\n        \"[| well_ord(A,r); B<=A; B\\<noteq>0 |] ==> (\\<exists>!b. first(b,B,r))\"\napply (unfold well_ord_def wf_on_def wf_def first_def)\napply (elim conjE allE disjE, blast)\napply (erule bexE)\napply (rule_tac a = x in ex1I, auto)\napply (unfold tot_ord_def linear_def, blast)\ndone\n\nlemma the_first_in:\n     \"[| well_ord(A,r); B<=A; B\\<noteq>0 |] ==> (THE b. first(b,B,r)) \\<in> B\"\napply (drule well_ord_imp_ex1_first, assumption+)\napply (rule first_is_elem)\napply (erule theI)\ndone\n\n\nsubsection \\<open>Lemmas for the Reflexive Orders\\<close>\n\nlemma subset_vimage_vimage_iff:\n  \"[| Preorder(r); A \\<subseteq> field(r); B \\<subseteq> field(r) |] ==>\n  r -`` A \\<subseteq> r -`` B \\<longleftrightarrow> (\\<forall>a\\<in>A. \\<exists>b\\<in>B. <a, b> \\<in> r)\"\n  apply (auto simp: subset_def preorder_on_def refl_def vimage_def image_def)\n   apply blast\n  unfolding trans_on_def\n  apply (erule_tac P = \"(\\<lambda>x. \\<forall>y\\<in>field(r).\n          \\<forall>z\\<in>field(r). \\<langle>x, y\\<rangle> \\<in> r \\<longrightarrow> \\<langle>y, z\\<rangle> \\<in> r \\<longrightarrow> \\<langle>x, z\\<rangle> \\<in> r)\" for r in rev_ballE)\n    (* instance obtained from proof term generated by best *)\n   apply best\n  apply blast\n  done\n\nlemma subset_vimage1_vimage1_iff:\n  \"[| Preorder(r); a \\<in> field(r); b \\<in> field(r) |] ==>\n  r -`` {a} \\<subseteq> r -`` {b} \\<longleftrightarrow> <a, b> \\<in> r\"\n  by (simp add: subset_vimage_vimage_iff)\n\nlemma Refl_antisym_eq_Image1_Image1_iff:\n  \"[| refl(field(r), r); antisym(r); a \\<in> field(r); b \\<in> field(r) |] ==>\n  r `` {a} = r `` {b} \\<longleftrightarrow> a = b\"\n  apply rule\n   apply (frule equality_iffD)\n   apply (drule equality_iffD)\n   apply (simp add: antisym_def refl_def)\n   apply best\n  apply (simp add: antisym_def refl_def)\n  done\n\nlemma Partial_order_eq_Image1_Image1_iff:\n  \"[| Partial_order(r); a \\<in> field(r); b \\<in> field(r) |] ==>\n  r `` {a} = r `` {b} \\<longleftrightarrow> a = b\"\n  by (simp add: partial_order_on_def preorder_on_def\n    Refl_antisym_eq_Image1_Image1_iff)\n\nlemma Refl_antisym_eq_vimage1_vimage1_iff:\n  \"[| refl(field(r), r); antisym(r); a \\<in> field(r); b \\<in> field(r) |] ==>\n  r -`` {a} = r -`` {b} \\<longleftrightarrow> a = b\"\n  apply rule\n   apply (frule equality_iffD)\n   apply (drule equality_iffD)\n   apply (simp add: antisym_def refl_def)\n   apply best\n  apply (simp add: antisym_def refl_def)\n  done\n\nlemma Partial_order_eq_vimage1_vimage1_iff:\n  \"[| Partial_order(r); a \\<in> field(r); b \\<in> field(r) |] ==>\n  r -`` {a} = r -`` {b} \\<longleftrightarrow> a = b\"\n  by (simp add: partial_order_on_def preorder_on_def\n    Refl_antisym_eq_vimage1_vimage1_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/ZF/Order.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9059898178450965, "lm_q2_score": 0.8080672135527632, "lm_q1q2_score": 0.7321006676132626}}
{"text": "(*\n    $Id: ex.thy,v 1.2 2004/11/23 15:14:35 webertj Exp $\n*)\n\nheader {* Predicate Logic *}\n\n(*<*) theory ex imports Main begin (*>*)\n\ntext {*\nWe are again talking about proofs in the calculus of Natural Deduction.  In\naddition to the rules given in the exercise ``Propositional Logic'', you may\nnow also use\n\n  @{text \"exI:\"}~@{thm exI[no_vars]}\\\\\n  @{text \"exE:\"}~@{thm exE[no_vars]}\\\\\n  @{text \"allI:\"}~@{thm allI[no_vars]}\\\\\n  @{text \"allE:\"}~@{thm allE[no_vars]}\\\\\n\nGive a proof of the following propositions or an argument why the formula is\nnot valid:\n*}\n\nlemma \"(\\<exists>x. \\<forall>y. P x y) \\<longrightarrow> (\\<forall>y. \\<exists>x. P x y)\"\n(*<*) oops (*>*)\n\nlemma \"(\\<forall>x. P x \\<longrightarrow> Q) = ((\\<exists>x. P x) \\<longrightarrow> Q)\"\n(*<*) oops (*>*)\n\nlemma \"((\\<forall> x. P x) \\<and> (\\<forall> x. Q x)) = (\\<forall> x. (P x \\<and> Q x))\"\n(*<*) oops (*>*)\n\nlemma \"((\\<forall> x. P x) \\<or> (\\<forall> x. Q x)) = (\\<forall> x. (P x \\<or> Q x))\"\n(*<*) oops (*>*)\n\nlemma \"((\\<exists> x. P x) \\<or> (\\<exists> x. Q x)) = (\\<exists> x. (P x \\<or> Q x))\"\n(*<*) oops (*>*)\n\nlemma \"(\\<forall>x. \\<exists>y. P x y) \\<longrightarrow> (\\<exists>y. \\<forall>x. P x y)\"\n(*<*) oops (*>*)\n\nlemma \"(\\<not> (\\<forall> x. P x)) = (\\<exists> x. \\<not> P x)\"\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/logic/predicate/ex.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9059898178450965, "lm_q2_score": 0.808067204308405, "lm_q1q2_score": 0.7321006592379682}}
{"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 {*\nSet of all increasing subsequences in a prefix of an array\n*}\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 {*\nLength of longest increasing subsequence in a prefix of an array\n*}\n\ndefinition liseq :: \"(nat \\<Rightarrow> 'a::linorder) \\<Rightarrow> nat \\<Rightarrow> nat\" where\n  \"liseq xs i = Max (card ` iseq xs i)\"\n\ntext {*\nLength of longest increasing subsequence ending at a particular position\n*}\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 `j < i` have \"Suc j \\<le> i\" by simp\n          with `is \\<in> iseq xs (Suc j)` 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 `is \\<in> iseq xs (Suc i)` `1 < card is`\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 `Max is = i` [symmetric] `finite is` `is \\<noteq> {}`\n          show \"card is - 1 = card (is - {i})\" by simp\n        next\n          from `is \\<in> iseq xs (Suc i)` `Max is = i` [symmetric]\n          show \"is - {i} \\<in> iseq xs (Suc (Max (is - {i})))\"\n            by simp (rule iseq_diff)\n        next\n          from `1 < card is`\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 `xs (Max (is - {Max is})) \\<le> xs (Max is)`\n            `Max js = Max (is - {i})` `Max is = i`\n          have \"xs (Max js) \\<le> xs i\" by simp\n          moreover from `Max is = i` `Max (is - {Max is}) < Max is`\n          have \"Suc (Max (is - {i})) \\<le> i\"\n            by simp\n          with `js \\<in> iseq xs (Suc (Max (is - {i})))`\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 `js \\<noteq> {}` `finite js` `Max js = Max (is - {i})`\n            `Max is = i` [symmetric] `Max (is - {Max is}) < Max is`\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 `Max is = i` [symmetric] `finite js`\n            `Max (is - {Max is}) < Max is` `Max js = Max (is - {i})`\n          have \"i \\<notin> js\" by (simp add: max_notin)\n          with `finite js`\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 `i \\<notin> js` `Max is = i` [symmetric] `is \\<noteq> {}` `finite is`\n            by simp\n        qed simp\n        with H `Max (is - {Max is}) < Max is`\n          `xs (Max (is - {Max is})) \\<le> xs (Max is)`\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 {* Proof functions *}\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 {* The verification conditions *}\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": "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/SPARK/Examples/Liseq/Longest_Increasing_Subsequence.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970873650401, "lm_q2_score": 0.8311430520409023, "lm_q1q2_score": 0.7320683794213168}}
{"text": "theory Report_demo imports\n  \"../Norm_proofs\"\n  \"~~/src/HOL/Library/LaTeXsugar\"\nbegin\n\ndefinition test_gr :: \"(nat, nat) grammar\" where\n  \"test_gr =\n   [(1, [(0, [])]),\n    (2, [(0, [1])]),\n    (3, [(0, [2])]),\n    (4, [(0, [1, 1, 1])]),\n    (5, [(23, [3]), (24, [4])])]\"\n\ntext {*\nLet us first see what happens when we run the norm iteration algorithm without refinement ---\nrecall that this results in a mere overestimation of the final norms:\n*}\n\nlemma \"iterate_norms test_gr =\n  ([(1, 1, 0, []),\n    (2, 2, 0, [1]),\n    (4, 4, 0, [1, 1, 1]),\n    (3, 3, 0, [2]),\n    (5, 5, 24, [4])],\n   [])\"\nby eval\n\ntext {*\nIn the results of the algorithm, we first note that the grammar is normed, because all\nvariables have a finite norm, which is indicated by the empty list in the second component\nof the result pair.\n\nNow we compare the output from the norm iteration algorithm with the output from\nthe norm iteration algorithm with added refinement at the end.\n*}\n\nlemma \"norms_of_grammar test_gr =\n  [(1, 1, 0, []),\n   (2, 2, 0, [1]),\n   (4, 4, 0, [1, 1, 1]),\n   (3, 3, 0, [2]),\n   (5, 4, 23, [3])]\"\nby eval\n\ntext {*\nComparing the two results, we note that the last norm entries, namely those\nconcering variable 5, differ. That means that the refinement found a smaller\nnorm for variable 5 than the overestimation algorithm.\n\nFinally, we can also calculate the norm of variable words:\n*}\n\nlemma \"norm_fun test_gr [1, 3, 5] = 8\" by eval\n\nend\n", "meta": {"author": "01mf02", "repo": "thesis", "sha": "d0a5f8e8b6416877c4ba897f6030f2b491c67b0c", "save_path": "github-repos/isabelle/01mf02-thesis", "path": "github-repos/isabelle/01mf02-thesis/thesis-d0a5f8e8b6416877c4ba897f6030f2b491c67b0c/Isabelle/docs/Report_demo.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.880797071719777, "lm_q2_score": 0.831143045767024, "lm_q1q2_score": 0.7320683608918513}}
{"text": "section \\<open>Normalizing Derivative\\<close>\n\ntheory NDerivative\nimports\n  Regular_Exp\nbegin\n\nsubsection \\<open>Normalizing operations\\<close>\n\ntext \\<open>associativity, commutativity, idempotence, zero\\<close>\n\nfun nPlus :: \"'a::order rexp \\<Rightarrow> 'a rexp \\<Rightarrow> 'a rexp\"\nwhere\n  \"nPlus Zero r = r\"\n| \"nPlus r Zero = r\"\n| \"nPlus (Plus r s) t = nPlus r (nPlus s t)\"\n| \"nPlus r (Plus s t) =\n     (if r = s then (Plus s t)\n     else if le_rexp r s then Plus r (Plus s t)\n     else Plus s (nPlus r t))\"\n| \"nPlus r s =\n     (if r = s then r\n      else if le_rexp r s then Plus r s\n      else Plus s r)\"\n\nlemma lang_nPlus[simp]: \"lang (nPlus r s) = lang (Plus r s)\"\nby (induction r s rule: nPlus.induct) auto\n\ntext \\<open>associativity, zero, one\\<close>\n\nfun nTimes :: \"'a::order rexp \\<Rightarrow> 'a rexp \\<Rightarrow> 'a rexp\"\nwhere\n  \"nTimes Zero _ = Zero\"\n| \"nTimes _ Zero = Zero\"\n| \"nTimes One r = r\"\n| \"nTimes r One = r\"\n| \"nTimes (Times r s) t = Times r (nTimes s t)\"\n| \"nTimes r s = Times r s\"\n\nlemma lang_nTimes[simp]: \"lang (nTimes r s) = lang (Times r s)\"\nby (induction r s rule: nTimes.induct) (auto simp: conc_assoc)\n\nprimrec norm :: \"'a::order rexp \\<Rightarrow> 'a rexp\"\nwhere\n  \"norm Zero = Zero\"\n| \"norm One = One\"\n| \"norm (Atom a) = Atom a\"\n| \"norm (Plus r s) = nPlus (norm r) (norm s)\"\n| \"norm (Times r s) = nTimes (norm r) (norm s)\"\n| \"norm (Star r) = Star (norm r)\"\n\nlemma lang_norm[simp]: \"lang (norm r) = lang r\"\nby (induct r) auto\n\nprimrec nderiv :: \"'a::order \\<Rightarrow> 'a rexp \\<Rightarrow> 'a rexp\"\nwhere\n  \"nderiv _ Zero = Zero\"\n| \"nderiv _ One = Zero\"\n| \"nderiv a (Atom b) = (if a = b then One else Zero)\"\n| \"nderiv a (Plus r s) = nPlus (nderiv a r) (nderiv a s)\"\n| \"nderiv a (Times r s) =\n    (let r's = nTimes (nderiv a r) s\n     in if nullable r then nPlus r's (nderiv a s) else r's)\"\n| \"nderiv a (Star r) = nTimes (nderiv a r) (Star r)\"\n\nlemma lang_nderiv: \"lang (nderiv a r) = Deriv a (lang r)\"\nby (induction r) (auto simp: Let_def nullable_iff)\n\nlemma deriv_no_occurrence: \n  \"x \\<notin> atoms r \\<Longrightarrow> nderiv x r = Zero\"\nby (induction r) auto\n\nlemma atoms_nPlus[simp]: \"atoms (nPlus r s) = atoms r \\<union> atoms s\"\nby (induction r s rule: nPlus.induct) auto\n\nlemma atoms_nTimes: \"atoms (nTimes r s) \\<subseteq> atoms r \\<union> atoms s\"\nby (induction r s rule: nTimes.induct) auto\n\nlemma atoms_norm: \"atoms (norm r) \\<subseteq> atoms r\"\nby (induction r) (auto dest!:subsetD[OF atoms_nTimes])\n\nlemma atoms_nderiv: \"atoms (nderiv a r) \\<subseteq> atoms r\"\nby (induction r) (auto simp: Let_def dest!:subsetD[OF atoms_nTimes])\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/NDerivative.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9086178870347122, "lm_q2_score": 0.8056321983146848, "lm_q1q2_score": 0.7320118257598192}}
{"text": "(*  Title:       Verification Examples\n    Author:      Jonathan Juli\u00e1n Huerta y Munive, 2021\n    Maintainer:  Jonathan Juli\u00e1n Huerta y Munive <jonjulian23@gmail.com>\n*)\n\nsection \\<open> Verification examples \\<close>\n\n\ntheory MTX_Examples\n  imports \n    MTX_Flows \n    Hybrid_Systems_VCs.HS_VC_Spartan\n\nbegin\n\n\nsubsection \\<open> Examples \\<close>\n\nabbreviation hoareT :: \"('a \\<Rightarrow> bool) \\<Rightarrow> ('a \\<Rightarrow> 'a set) \\<Rightarrow> ('a \\<Rightarrow> bool) \\<Rightarrow> bool\" \n  (\"PRE_ HP _ POST _\" [85,85]85) where \"PRE P HP X POST Q \\<equiv> (P \\<le> |X]Q)\"\n\n\nsubsubsection \\<open> Verification by uniqueness. \\<close>\n\nabbreviation mtx_circ :: \"2 sq_mtx\" (\"A\")\n  where \"A \\<equiv> mtx  \n   ([0,  1] # \n    [-1, 0] # [])\"\n\nabbreviation mtx_circ_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\nlemma mtx_circ_flow_eq: \"exp (t *\\<^sub>R A) *\\<^sub>V s = \\<phi> t s\"\n  apply(rule local_flow.eq_solution[OF local_flow_sq_mtx_linear, symmetric, of _ \"\\<lambda>s. UNIV\"], simp_all)\n    apply(rule ivp_solsI, simp_all add: sq_mtx_vec_mult_eq vec_eq_iff)\n  unfolding UNIV_2 using exhaust_2\n  by (force intro!: poly_derivatives simp: matrix_vector_mult_def)+\n\nlemma mtx_circ: \n  \"PRE(\\<lambda>s. r\\<^sup>2 = (s $ 1)\\<^sup>2 + (s $ 2)\\<^sup>2) \n  HP x\\<acute>=(*\\<^sub>V) A & G \n  POST (\\<lambda>s. r\\<^sup>2 = (s $ 1)\\<^sup>2 + (s $ 2)\\<^sup>2)\"\n  apply(subst local_flow.fbox_g_ode_subset[OF local_flow_sq_mtx_linear])\n  unfolding mtx_circ_flow_eq by auto\n\nno_notation mtx_circ (\"A\")\n        and mtx_circ_flow (\"\\<phi>\")\n\n\nsubsubsection \\<open> Flow of diagonalisable matrix. \\<close>\n\nabbreviation mtx_hOsc :: \"real \\<Rightarrow> real \\<Rightarrow> 2 sq_mtx\" (\"A\")\n  where \"A a b \\<equiv> mtx  \n   ([0, 1] # \n    [a, b] # [])\"\n\nabbreviation mtx_chB_hOsc :: \"real \\<Rightarrow> real \\<Rightarrow> 2 sq_mtx\" (\"P\")\n  where \"P a b \\<equiv> mtx\n   ([a, b] # \n    [1, 1] # [])\"\n\nlemma inv_mtx_chB_hOsc: \n  \"a \\<noteq> b \\<Longrightarrow> (P a b)\\<^sup>-\\<^sup>1 = (1/(a - b)) *\\<^sub>R mtx \n   ([ 1, -b] # \n    [-1,  a] # [])\"\n  apply(rule sq_mtx_inv_unique, unfold scaleR_mtx2 times_mtx2)\n  by (simp add: diff_divide_distrib[symmetric] one_mtx2)+\n\nlemma invertible_mtx_chB_hOsc: \"a \\<noteq> b \\<Longrightarrow> mtx_invertible (P a b)\"\n  apply(rule mtx_invertibleI[of _ \"(P a b)\\<^sup>-\\<^sup>1\"])\n   apply(unfold inv_mtx_chB_hOsc scaleR_mtx2 times_mtx2 one_mtx2)\n  by (subst sq_mtx_eq_iff, simp add: vector_def frac_diff_eq1)+\n\nlemma mtx_hOsc_diagonalizable:\n  fixes a b :: real\n  defines \"\\<iota>\\<^sub>1 \\<equiv> (b - sqrt (b^2+4*a))/2\" and \"\\<iota>\\<^sub>2 \\<equiv> (b + sqrt (b^2+4*a))/2\"\n  assumes \"b\\<^sup>2 + a * 4 > 0\" and \"a \\<noteq> 0\"\n  shows \"A a b = P (-\\<iota>\\<^sub>2/a) (-\\<iota>\\<^sub>1/a) * (\\<d>\\<i>\\<a>\\<g> i. if i = 1 then \\<iota>\\<^sub>1 else \\<iota>\\<^sub>2) * (P (-\\<iota>\\<^sub>2/a) (-\\<iota>\\<^sub>1/a))\\<^sup>-\\<^sup>1\"\n  unfolding assms apply(subst inv_mtx_chB_hOsc)\n  using assms(3,4) apply(simp_all add: diag2_eq[symmetric])\n  unfolding sq_mtx_times_eq sq_mtx_scaleR_eq UNIV_2 apply(subst sq_mtx_eq_iff)\n  using exhaust_2 assms by (auto simp: field_simps, auto simp: field_power_simps)\n\nlemma mtx_hOsc_solution_eq:\n  fixes a b :: real\n  defines \"\\<iota>\\<^sub>1 \\<equiv> (b - sqrt (b\\<^sup>2+4*a))/2\" and \"\\<iota>\\<^sub>2 \\<equiv> (b + sqrt (b\\<^sup>2+4*a))/2\"\n  defines \"\\<Phi> t \\<equiv> mtx (\n   [\\<iota>\\<^sub>2*exp(t*\\<iota>\\<^sub>1) - \\<iota>\\<^sub>1*exp(t*\\<iota>\\<^sub>2),     exp(t*\\<iota>\\<^sub>2)-exp(t*\\<iota>\\<^sub>1)]#\n   [a*exp(t*\\<iota>\\<^sub>2) - a*exp(t*\\<iota>\\<^sub>1), \\<iota>\\<^sub>2*exp(t*\\<iota>\\<^sub>2)-\\<iota>\\<^sub>1*exp(t*\\<iota>\\<^sub>1)]#[])\"\n  assumes \"b\\<^sup>2 + a * 4 > 0\" and \"a \\<noteq> 0\"\n  shows \"P (-\\<iota>\\<^sub>2/a) (-\\<iota>\\<^sub>1/a) * (\\<d>\\<i>\\<a>\\<g> i. exp (t * (if i=1 then \\<iota>\\<^sub>1 else \\<iota>\\<^sub>2))) * (P (-\\<iota>\\<^sub>2/a) (-\\<iota>\\<^sub>1/a))\\<^sup>-\\<^sup>1 \n  = (1/sqrt (b\\<^sup>2 + a * 4)) *\\<^sub>R (\\<Phi> t)\"\n  unfolding assms apply(subst inv_mtx_chB_hOsc)\n  using assms apply(simp_all add: mtx_times_scaleR_commute, subst sq_mtx_eq_iff)\n  unfolding UNIV_2 sq_mtx_times_eq sq_mtx_scaleR_eq sq_mtx_uminus_eq apply(simp_all add: axis_def)\n  by (auto simp: field_simps, auto simp: field_power_simps)+\n \nlemma local_flow_mtx_hOsc:\n  fixes a b\n  defines \"\\<iota>\\<^sub>1 \\<equiv> (b - sqrt (b^2+4*a))/2\" and \"\\<iota>\\<^sub>2 \\<equiv> (b + sqrt (b^2+4*a))/2\"\n  defines \"\\<Phi> t \\<equiv> mtx (\n   [\\<iota>\\<^sub>2*exp(t*\\<iota>\\<^sub>1) - \\<iota>\\<^sub>1*exp(t*\\<iota>\\<^sub>2),     exp(t*\\<iota>\\<^sub>2)-exp(t*\\<iota>\\<^sub>1)]#\n   [a*exp(t*\\<iota>\\<^sub>2) - a*exp(t*\\<iota>\\<^sub>1), \\<iota>\\<^sub>2*exp(t*\\<iota>\\<^sub>2)-\\<iota>\\<^sub>1*exp(t*\\<iota>\\<^sub>1)]#[])\"\n  assumes \"b\\<^sup>2 + a * 4 > 0\" and \"a \\<noteq> 0\"\n  shows \"local_flow ((*\\<^sub>V) (A a b)) UNIV UNIV (\\<lambda>t. (*\\<^sub>V) ((1/sqrt (b\\<^sup>2 + a * 4)) *\\<^sub>R \\<Phi> t))\"\n  unfolding assms using local_flow_sq_mtx_linear[of \"A a b\"] assms\n  apply(subst (asm) exp_scaleR_diagonal2[OF invertible_mtx_chB_hOsc mtx_hOsc_diagonalizable])\n     apply(simp, simp, simp)\n  by (subst (asm) mtx_hOsc_solution_eq) simp_all\n\nlemma overdamped_door_arith:\n  assumes \"b\\<^sup>2 + a * 4 > 0\" and \"a < 0\" and \"b \\<le> 0\" and \"t \\<ge> 0\" and \"s1 > 0\"\n  shows \"0 \\<le> ((b + sqrt (b\\<^sup>2 + 4 * a)) * exp (t * (b - sqrt (b\\<^sup>2 + 4 * a)) / 2) / 2 - \n(b - sqrt (b\\<^sup>2 + 4 * a)) * exp (t * (b + sqrt (b\\<^sup>2 + 4 * a)) / 2) / 2) * s1 / sqrt (b\\<^sup>2 + a * 4)\"\nproof(subst diff_divide_distrib[symmetric], simp)\n  have f0: \"s1 / (2 * sqrt (b\\<^sup>2 + a * 4)) > 0\"  (is \"s1/?c3 > 0\")\n    using assms(1,5) by simp\n  have f1: \"(b - sqrt (b\\<^sup>2 + 4 * a)) < (b + sqrt (b\\<^sup>2 + 4 * a))\" (is \"?c2 < ?c1\") \n    and f2: \"(b + sqrt (b\\<^sup>2 + 4 * a)) < 0\"\n    using sqrt_ge_absD[of b \"b\\<^sup>2 + 4 * a\"] assms by (force, linarith)\n  hence f3: \"exp (t * ?c2 / 2) \\<le> exp (t * ?c1 / 2)\" (is \"exp ?t1 \\<le> exp ?t2\")\n    unfolding exp_le_cancel_iff \n    using assms(4) by (case_tac \"t=0\", simp_all)\n  hence \"?c2 * exp ?t2 \\<le> ?c2 * exp ?t1\"\n    using f1 f2 mult_le_cancel_left_pos[of \"-?c2\" \"exp ?t1\" \"exp ?t2\"] by linarith \n  also have \"... < ?c1 * exp ?t1\"\n    using f1 by auto\n  also have\"... \\<le> ?c1 * exp ?t1\"\n    using f1 f2 by auto\n  ultimately show \"0 \\<le> (?c1 * exp ?t1 - ?c2 * exp ?t2) * s1 / ?c3\"\n    using f0 f1 assms(5) by auto\nqed\n\nabbreviation \"open_door s \\<equiv> {s. s$1 > 0 \\<and> s$2 = 0}\"\n\nlemma overdamped_door:\n  assumes \"b\\<^sup>2 + a * 4 > 0\" and \"a < 0\" and \"b \\<le> 0\"\n  shows \"PRE (\\<lambda>s. s$1 = 0)\n  HP (LOOP open_door; (x\\<acute>=((*\\<^sub>V) (A a b)) & G) INV (\\<lambda>s. 0 \\<le> s$1))\n  POST (\\<lambda>s. 0 \\<le> s $ 1)\"\n  apply(rule fbox_loopI, simp_all add: le_fun_def)\n  apply(subst local_flow.fbox_g_ode_subset[OF local_flow_mtx_hOsc[OF assms(1)]])\n  using assms apply(simp_all add: le_fun_def fbox_def)\n  unfolding sq_mtx_scaleR_eq UNIV_2 sq_mtx_vec_mult_eq\n  by (clarsimp simp: overdamped_door_arith)\n\n\nno_notation mtx_hOsc (\"A\")\n        and mtx_chB_hOsc (\"P\")\n\n\nsubsubsection \\<open> Flow of non-diagonalisable matrix. \\<close>\n\nabbreviation mtx_cnst_acc :: \"3 sq_mtx\" (\"K\")\n  where \"K \\<equiv> mtx (\n  [0,1,0] #\n  [0,0,1] # \n  [0,0,0] # [])\"\n\nlemma pow2_scaleR_mtx_cnst_acc: \"(t *\\<^sub>R K)\\<^sup>2 = mtx (\n  [0,0,t\\<^sup>2] #\n  [0,0,0] # \n  [0,0,0] # [])\"\n  unfolding power2_eq_square apply(subst sq_mtx_eq_iff)\n  unfolding sq_mtx_times_eq UNIV_3 by auto\n\nlemma powN_scaleR_mtx_cnst_acc: \"n > 2 \\<Longrightarrow> (t *\\<^sub>R K)^n = 0\"\n  apply(induct n, simp, case_tac \"n \\<le> 2\")\n   apply(subgoal_tac \"n = 2\", erule ssubst)\n  unfolding power_Suc2 pow2_scaleR_mtx_cnst_acc sq_mtx_times_eq UNIV_3\n  by (auto simp: sq_mtx_eq_iff)\n\n\n\nlemma exp_mtx_cnst_acc_vec_mult_eq: \"exp (t *\\<^sub>R K) *\\<^sub>V s = \n  vector [s$3 * t^2/2 + s$2 * t + s$1, s$3 * t + s$2, s$3]\"\n  apply(subst exp_mtx_cnst_acc, subst pow2_scaleR_mtx_cnst_acc)\n  apply(simp add: sq_mtx_vec_mult_eq vector_def)\n  unfolding UNIV_3 by (simp add: fun_eq_iff)\n\nlemma local_flow_mtx_cnst_acc:\n  \"local_flow ((*\\<^sub>V) K) UNIV UNIV (\\<lambda>t s. ((t *\\<^sub>R K)\\<^sup>2/\\<^sub>R 2 + (t *\\<^sub>R K) + 1) *\\<^sub>V s)\"\n  using local_flow_sq_mtx_linear[of K] unfolding exp_mtx_cnst_acc .  \n\nlemma docking_station_arith:\n  assumes \"(d::real) > x\" and \"v > 0\"\n  shows \"(v = v\\<^sup>2 * t / (2 * d - 2 * x)) \\<longleftrightarrow> (v * t - v\\<^sup>2 * t\\<^sup>2 / (4 * d - 4 * x) + x = d)\"\nproof\n  assume \"v = v\\<^sup>2 * t / (2 * d - 2 * x)\"\n  hence \"v * t = 2 * (d - x)\"\n    using assms by (simp add: eq_divide_eq power2_eq_square) \n  hence \"v * t - v\\<^sup>2 * t\\<^sup>2 / (4 * d - 4 * x) + x = 2 * (d - x) - 4 * (d - x)\\<^sup>2 / (4 * (d - x)) + x\"\n    apply(subst power_mult_distrib[symmetric])\n    by (erule ssubst, subst power_mult_distrib, simp)\n  also have \"... = d\"\n    apply(simp only: mult_divide_mult_cancel_left_if)\n    using assms by (auto simp: power2_eq_square)\n  finally show \"v * t - v\\<^sup>2 * t\\<^sup>2 / (4 * d - 4 * x) + x = d\" .\nnext\n  assume \"v * t - v\\<^sup>2 * t\\<^sup>2 / (4 * d - 4 * x) + x = d\"\n  hence \"0 = v\\<^sup>2 * t\\<^sup>2 / (4 * (d - x)) + (d - x) - v * t\"\n    by auto\n  hence \"0 = (4 * (d - x)) * (v\\<^sup>2 * t\\<^sup>2 / (4 * (d - x)) + (d - x) - v * t)\"\n    by auto\n  also have \"... = v\\<^sup>2 * t\\<^sup>2 + 4 * (d - x)\\<^sup>2  - (4 * (d - x)) * (v * t)\"\n    using assms apply(simp add: distrib_left right_diff_distrib)\n    apply(subst right_diff_distrib[symmetric])+\n    by (simp add: power2_eq_square)\n  also have \"... = (v * t - 2 * (d - x))\\<^sup>2\"\n    by (simp only: power2_diff, auto simp: field_simps power2_diff)\n  finally have \"0 = (v * t - 2 * (d - x))\\<^sup>2\" .\n  hence \"v * t = 2 * (d - x)\"\n    by auto\n  thus \"v = v\\<^sup>2 * t / (2 * d - 2 * x)\"\n    apply(subst power2_eq_square, subst mult.assoc)\n    apply(erule ssubst, subst right_diff_distrib[symmetric])\n    using assms by auto\nqed\n\nlemma docking_station:\n  assumes \"d > x\\<^sub>0\" and \"v\\<^sub>0 > 0\"\n  shows \"PRE (\\<lambda>s. s$1 = x\\<^sub>0 \\<and> s$2 = v\\<^sub>0)\n  HP ((3 ::= (\\<lambda>s. -(v\\<^sub>0^2/(2*(d-x\\<^sub>0))))); x\\<acute>=(*\\<^sub>V) K & G)\n  POST (\\<lambda>s. s$2 = 0 \\<longleftrightarrow> s$1 = d)\"\n  apply(clarsimp simp: le_fun_def local_flow.fbox_g_ode_subset[OF local_flow_sq_mtx_linear[of K]])\n  unfolding exp_mtx_cnst_acc_vec_mult_eq using assms by (simp add: docking_station_arith)\n\nno_notation mtx_cnst_acc (\"K\")\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/Matrices_for_ODEs/MTX_Examples.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9005297781091839, "lm_q2_score": 0.8128673246376009, "lm_q1q2_score": 0.7320112314881047}}
{"text": "section \"Security Type Systems\"\n\nsubsection \"Security Levels and Expressions\"\n\ntheory Sec_Type_Expr imports Big_Step\nbegin\n\ntype_synonym level = nat\n\nclass sec =\nfixes sec :: \"'a \\<Rightarrow> nat\"\n\ntext\\<open>The security/confidentiality level of each variable is globally fixed\nfor simplicity. For the sake of examples --- the general theory does not rely\non it! --- a variable of length \\<open>n\\<close> has security level \\<open>n\\<close>:\\<close>\n\ninstantiation list :: (type)sec\nbegin\n\ndefinition \"sec(x :: 'a list) = length x\"\n\ninstance ..\n\nend\n\ninstantiation aexp :: sec\nbegin\n\nfun sec_aexp :: \"aexp \\<Rightarrow> level\" where\n\"sec (N n) = 0\" |\n\"sec (V x) = sec x\" |\n\"sec (Plus a\\<^sub>1 a\\<^sub>2) = max (sec a\\<^sub>1) (sec a\\<^sub>2)\"\n\ninstance ..\n\nend\n\ninstantiation bexp :: sec\nbegin\n\nfun sec_bexp :: \"bexp \\<Rightarrow> level\" where\n\"sec (Bc v) = 0\" |\n\"sec (Not b) = sec b\" |\n\"sec (And b\\<^sub>1 b\\<^sub>2) = max (sec b\\<^sub>1) (sec b\\<^sub>2)\" |\n\"sec (Less a\\<^sub>1 a\\<^sub>2) = max (sec a\\<^sub>1) (sec a\\<^sub>2)\"\n\ninstance ..\n\nend\n\n\nabbreviation eq_le :: \"state \\<Rightarrow> state \\<Rightarrow> level \\<Rightarrow> bool\"\n  (\"(_ = _ '(\\<le> _'))\" [51,51,0] 50) where\n\"s = s' (\\<le> l) == (\\<forall> x. sec x \\<le> l \\<longrightarrow> s x = s' x)\"\n\nabbreviation eq_less :: \"state \\<Rightarrow> state \\<Rightarrow> level \\<Rightarrow> bool\"\n  (\"(_ = _ '(< _'))\" [51,51,0] 50) where\n\"s = s' (< l) == (\\<forall> x. sec x < l \\<longrightarrow> s x = s' x)\"\n\nlemma aval_eq_if_eq_le:\n  \"\\<lbrakk> s\\<^sub>1 = s\\<^sub>2 (\\<le> l);  sec a \\<le> l \\<rbrakk> \\<Longrightarrow> aval a s\\<^sub>1 = aval a s\\<^sub>2\"\nby (induct a) auto\n\nlemma bval_eq_if_eq_le:\n  \"\\<lbrakk> s\\<^sub>1 = s\\<^sub>2 (\\<le> l);  sec b \\<le> l \\<rbrakk> \\<Longrightarrow> bval b s\\<^sub>1 = bval b s\\<^sub>2\"\nby (induct b) (auto simp add: aval_eq_if_eq_le)\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/Sec_Type_Expr.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8902942261220294, "lm_q2_score": 0.822189134878876, "lm_q1q2_score": 0.7319902395629297}}
{"text": "(*  Title:      HOL/Topological_Spaces.thy\n    Author:     Brian Huffman\n    Author:     Johannes H\u00f6lzl\n*)\n\nsection \\<open>Topological Spaces\\<close>\n\ntheory Topological_Spaces\n  imports Main\nbegin\n\nnamed_theorems continuous_intros \"structural introduction rules for continuity\"\n\nsubsection \\<open>Topological space\\<close>\n\nclass \"open\" =\n  fixes \"open\" :: \"'a set \\<Rightarrow> bool\"\n\nclass topological_space = \"open\" +\n  assumes open_UNIV [simp, intro]: \"open UNIV\"\n  assumes open_Int [intro]: \"open S \\<Longrightarrow> open T \\<Longrightarrow> open (S \\<inter> T)\"\n  assumes open_Union [intro]: \"\\<forall>S\\<in>K. open S \\<Longrightarrow> open (\\<Union>K)\"\nbegin\n\ndefinition closed :: \"'a set \\<Rightarrow> bool\"\n  where \"closed S \\<longleftrightarrow> open (- S)\"\n\nlemma open_empty [continuous_intros, intro, simp]: \"open {}\"\n  using open_Union [of \"{}\"] by simp\n\nlemma open_Un [continuous_intros, intro]: \"open S \\<Longrightarrow> open T \\<Longrightarrow> open (S \\<union> T)\"\n  using open_Union [of \"{S, T}\"] by simp\n\nlemma open_UN [continuous_intros, intro]: \"\\<forall>x\\<in>A. open (B x) \\<Longrightarrow> open (\\<Union>x\\<in>A. B x)\"\n  using open_Union [of \"B ` A\"] by simp\n\nlemma open_Inter [continuous_intros, intro]: \"finite S \\<Longrightarrow> \\<forall>T\\<in>S. open T \\<Longrightarrow> open (\\<Inter>S)\"\n  by (induction set: finite) auto\n\nlemma open_INT [continuous_intros, intro]: \"finite A \\<Longrightarrow> \\<forall>x\\<in>A. open (B x) \\<Longrightarrow> open (\\<Inter>x\\<in>A. B x)\"\n  using open_Inter [of \"B ` A\"] by simp\n\nlemma openI:\n  assumes \"\\<And>x. x \\<in> S \\<Longrightarrow> \\<exists>T. open T \\<and> x \\<in> T \\<and> T \\<subseteq> S\"\n  shows \"open S\"\nproof -\n  have \"open (\\<Union>{T. open T \\<and> T \\<subseteq> S})\" by auto\n  moreover have \"\\<Union>{T. open T \\<and> T \\<subseteq> S} = S\" by (auto dest!: assms)\n  ultimately show \"open S\" by simp\nqed\n\nlemma open_subopen: \"open S \\<longleftrightarrow> (\\<forall>x\\<in>S. \\<exists>T. open T \\<and> x \\<in> T \\<and> T \\<subseteq> S)\"\nby (auto intro: openI)\n\nlemma closed_empty [continuous_intros, intro, simp]: \"closed {}\"\n  unfolding closed_def by simp\n\nlemma closed_Un [continuous_intros, intro]: \"closed S \\<Longrightarrow> closed T \\<Longrightarrow> closed (S \\<union> T)\"\n  unfolding closed_def by auto\n\nlemma closed_UNIV [continuous_intros, intro, simp]: \"closed UNIV\"\n  unfolding closed_def by simp\n\nlemma closed_Int [continuous_intros, intro]: \"closed S \\<Longrightarrow> closed T \\<Longrightarrow> closed (S \\<inter> T)\"\n  unfolding closed_def by auto\n\nlemma closed_INT [continuous_intros, intro]: \"\\<forall>x\\<in>A. closed (B x) \\<Longrightarrow> closed (\\<Inter>x\\<in>A. B x)\"\n  unfolding closed_def by auto\n\nlemma closed_Inter [continuous_intros, intro]: \"\\<forall>S\\<in>K. closed S \\<Longrightarrow> closed (\\<Inter>K)\"\n  unfolding closed_def uminus_Inf by auto\n\nlemma closed_Union [continuous_intros, intro]: \"finite S \\<Longrightarrow> \\<forall>T\\<in>S. closed T \\<Longrightarrow> closed (\\<Union>S)\"\n  by (induct set: finite) auto\n\nlemma closed_UN [continuous_intros, intro]:\n  \"finite A \\<Longrightarrow> \\<forall>x\\<in>A. closed (B x) \\<Longrightarrow> closed (\\<Union>x\\<in>A. B x)\"\n  using closed_Union [of \"B ` A\"] by simp\n\nlemma open_closed: \"open S \\<longleftrightarrow> closed (- S)\"\n  by (simp add: closed_def)\n\nlemma closed_open: \"closed S \\<longleftrightarrow> open (- S)\"\n  by (rule closed_def)\n\nlemma open_Diff [continuous_intros, intro]: \"open S \\<Longrightarrow> closed T \\<Longrightarrow> open (S - T)\"\n  by (simp add: closed_open Diff_eq open_Int)\n\nlemma closed_Diff [continuous_intros, intro]: \"closed S \\<Longrightarrow> open T \\<Longrightarrow> closed (S - T)\"\n  by (simp add: open_closed Diff_eq closed_Int)\n\nlemma open_Compl [continuous_intros, intro]: \"closed S \\<Longrightarrow> open (- S)\"\n  by (simp add: closed_open)\n\nlemma closed_Compl [continuous_intros, intro]: \"open S \\<Longrightarrow> closed (- S)\"\n  by (simp add: open_closed)\n\nlemma open_Collect_neg: \"closed {x. P x} \\<Longrightarrow> open {x. \\<not> P x}\"\n  unfolding Collect_neg_eq by (rule open_Compl)\n\nlemma open_Collect_conj:\n  assumes \"open {x. P x}\" \"open {x. Q x}\"\n  shows \"open {x. P x \\<and> Q x}\"\n  using open_Int[OF assms] by (simp add: Int_def)\n\nlemma open_Collect_disj:\n  assumes \"open {x. P x}\" \"open {x. Q x}\"\n  shows \"open {x. P x \\<or> Q x}\"\n  using open_Un[OF assms] by (simp add: Un_def)\n\nlemma open_Collect_ex: \"(\\<And>i. open {x. P i x}) \\<Longrightarrow> open {x. \\<exists>i. P i x}\"\n  using open_UN[of UNIV \"\\<lambda>i. {x. P i x}\"] unfolding Collect_ex_eq by simp\n\nlemma open_Collect_imp: \"closed {x. P x} \\<Longrightarrow> open {x. Q x} \\<Longrightarrow> open {x. P x \\<longrightarrow> Q x}\"\n  unfolding imp_conv_disj by (intro open_Collect_disj open_Collect_neg)\n\nlemma open_Collect_const: \"open {x. P}\"\n  by (cases P) auto\n\nlemma closed_Collect_neg: \"open {x. P x} \\<Longrightarrow> closed {x. \\<not> P x}\"\n  unfolding Collect_neg_eq by (rule closed_Compl)\n\nlemma closed_Collect_conj:\n  assumes \"closed {x. P x}\" \"closed {x. Q x}\"\n  shows \"closed {x. P x \\<and> Q x}\"\n  using closed_Int[OF assms] by (simp add: Int_def)\n\nlemma closed_Collect_disj:\n  assumes \"closed {x. P x}\" \"closed {x. Q x}\"\n  shows \"closed {x. P x \\<or> Q x}\"\n  using closed_Un[OF assms] by (simp add: Un_def)\n\nlemma closed_Collect_all: \"(\\<And>i. closed {x. P i x}) \\<Longrightarrow> closed {x. \\<forall>i. P i x}\"\n  using closed_INT[of UNIV \"\\<lambda>i. {x. P i x}\"] by (simp add: Collect_all_eq)\n\nlemma closed_Collect_imp: \"open {x. P x} \\<Longrightarrow> closed {x. Q x} \\<Longrightarrow> closed {x. P x \\<longrightarrow> Q x}\"\n  unfolding imp_conv_disj by (intro closed_Collect_disj closed_Collect_neg)\n\nlemma closed_Collect_const: \"closed {x. P}\"\n  by (cases P) auto\n\nend\n\n\nsubsection \\<open>Hausdorff and other separation properties\\<close>\n\nclass t0_space = topological_space +\n  assumes t0_space: \"x \\<noteq> y \\<Longrightarrow> \\<exists>U. open U \\<and> \\<not> (x \\<in> U \\<longleftrightarrow> y \\<in> U)\"\n\nclass t1_space = topological_space +\n  assumes t1_space: \"x \\<noteq> y \\<Longrightarrow> \\<exists>U. open U \\<and> x \\<in> U \\<and> y \\<notin> U\"\n\ninstance t1_space \\<subseteq> t0_space\n  by standard (fast dest: t1_space)\n\ncontext t1_space begin\n\nlemma separation_t1: \"x \\<noteq> y \\<longleftrightarrow> (\\<exists>U. open U \\<and> x \\<in> U \\<and> y \\<notin> U)\"\n  using t1_space[of x y] by blast\n\nlemma closed_singleton [iff]: \"closed {a}\"\nproof -\n  let ?T = \"\\<Union>{S. open S \\<and> a \\<notin> S}\"\n  have \"open ?T\"\n    by (simp add: open_Union)\n  also have \"?T = - {a}\"\n    by (auto simp add: set_eq_iff separation_t1)\n  finally show \"closed {a}\"\n    by (simp only: closed_def)\nqed\n\nlemma closed_insert [continuous_intros, simp]:\n  assumes \"closed S\"\n  shows \"closed (insert a S)\"\nproof -\n  from closed_singleton assms have \"closed ({a} \\<union> S)\"\n    by (rule closed_Un)\n  then show \"closed (insert a S)\"\n    by simp\nqed\n\nlemma finite_imp_closed: \"finite S \\<Longrightarrow> closed S\"\n  by (induct pred: finite) simp_all\n\nend\n\ntext \\<open>T2 spaces are also known as Hausdorff spaces.\\<close>\n\nclass t2_space = topological_space +\n  assumes hausdorff: \"x \\<noteq> y \\<Longrightarrow> \\<exists>U V. open U \\<and> open V \\<and> x \\<in> U \\<and> y \\<in> V \\<and> U \\<inter> V = {}\"\n\ninstance t2_space \\<subseteq> t1_space\n  by standard (fast dest: hausdorff)\n\nlemma (in t2_space) separation_t2: \"x \\<noteq> y \\<longleftrightarrow> (\\<exists>U V. open U \\<and> open V \\<and> x \\<in> U \\<and> y \\<in> V \\<and> U \\<inter> V = {})\"\n  using hausdorff [of x y] by blast\n\nlemma (in t0_space) separation_t0: \"x \\<noteq> y \\<longleftrightarrow> (\\<exists>U. open U \\<and> \\<not> (x \\<in> U \\<longleftrightarrow> y \\<in> U))\"\n  using t0_space [of x y] by blast\n\n\ntext \\<open>A classical separation axiom for topological space, the T3 axiom -- also called regularity:\nif a point is not in a closed set, then there are open sets separating them.\\<close>\n\nclass t3_space = t2_space +\n  assumes t3_space: \"closed S \\<Longrightarrow> y \\<notin> S \\<Longrightarrow> \\<exists>U V. open U \\<and> open V \\<and> y \\<in> U \\<and> S \\<subseteq> V \\<and> U \\<inter> V = {}\"\n\ntext \\<open>A classical separation axiom for topological space, the T4 axiom -- also called normality:\nif two closed sets are disjoint, then there are open sets separating them.\\<close>\n\nclass t4_space = t2_space +\n  assumes t4_space: \"closed S \\<Longrightarrow> closed T \\<Longrightarrow> S \\<inter> T = {} \\<Longrightarrow> \\<exists>U V. open U \\<and> open V \\<and> S \\<subseteq> U \\<and> T \\<subseteq> V \\<and> U \\<inter> V = {}\"\n\ntext \\<open>T4 is stronger than T3, and weaker than metric.\\<close>\n\ninstance t4_space \\<subseteq> t3_space\nproof\n  fix S and y::'a assume \"closed S\" \"y \\<notin> S\"\n  then show \"\\<exists>U V. open U \\<and> open V \\<and> y \\<in> U \\<and> S \\<subseteq> V \\<and> U \\<inter> V = {}\"\n    using t4_space[of \"{y}\" S] by auto\nqed\n\ntext \\<open>A perfect space is a topological space with no isolated points.\\<close>\n\nclass perfect_space = topological_space +\n  assumes not_open_singleton: \"\\<not> open {x}\"\n\nlemma (in perfect_space) UNIV_not_singleton: \"UNIV \\<noteq> {x}\"\n  for x::'a\n  by (metis (no_types) open_UNIV not_open_singleton)\n\n\nsubsection \\<open>Generators for toplogies\\<close>\n\ninductive generate_topology :: \"'a set set \\<Rightarrow> 'a set \\<Rightarrow> bool\" for S :: \"'a set set\"\n  where\n    UNIV: \"generate_topology S UNIV\"\n  | Int: \"generate_topology S (a \\<inter> b)\" if \"generate_topology S a\" and \"generate_topology S b\"\n  | UN: \"generate_topology S (\\<Union>K)\" if \"(\\<And>k. k \\<in> K \\<Longrightarrow> generate_topology S k)\"\n  | Basis: \"generate_topology S s\" if \"s \\<in> S\"\n\nhide_fact (open) UNIV Int UN Basis\n\nlemma generate_topology_Union:\n  \"(\\<And>k. k \\<in> I \\<Longrightarrow> generate_topology S (K k)) \\<Longrightarrow> generate_topology S (\\<Union>k\\<in>I. K k)\"\n  using generate_topology.UN [of \"K ` I\"] by auto\n\nlemma topological_space_generate_topology: \"class.topological_space (generate_topology S)\"\n  by standard (auto intro: generate_topology.intros)\n\n\nsubsection \\<open>Order topologies\\<close>\n\nclass order_topology = order + \"open\" +\n  assumes open_generated_order: \"open = generate_topology (range (\\<lambda>a. {..< a}) \\<union> range (\\<lambda>a. {a <..}))\"\nbegin\n\nsubclass topological_space\n  unfolding open_generated_order\n  by (rule topological_space_generate_topology)\n\nlemma open_greaterThan [continuous_intros, simp]: \"open {a <..}\"\n  unfolding open_generated_order by (auto intro: generate_topology.Basis)\n\nlemma open_lessThan [continuous_intros, simp]: \"open {..< a}\"\n  unfolding open_generated_order by (auto intro: generate_topology.Basis)\n\nlemma open_greaterThanLessThan [continuous_intros, simp]: \"open {a <..< b}\"\n   unfolding greaterThanLessThan_eq by (simp add: open_Int)\n\nend\n\nclass linorder_topology = linorder + order_topology\n\nlemma closed_atMost [continuous_intros, simp]: \"closed {..a}\"\n  for a :: \"'a::linorder_topology\"\n  by (simp add: closed_open)\n\nlemma closed_atLeast [continuous_intros, simp]: \"closed {a..}\"\n  for a :: \"'a::linorder_topology\"\n  by (simp add: closed_open)\n\nlemma closed_atLeastAtMost [continuous_intros, simp]: \"closed {a..b}\"\n  for a b :: \"'a::linorder_topology\"\nproof -\n  have \"{a .. b} = {a ..} \\<inter> {.. b}\"\n    by auto\n  then show ?thesis\n    by (simp add: closed_Int)\nqed\n\nlemma (in order) less_separate:\n  assumes \"x < y\"\n  shows \"\\<exists>a b. x \\<in> {..< a} \\<and> y \\<in> {b <..} \\<and> {..< a} \\<inter> {b <..} = {}\"\nproof (cases \"\\<exists>z. x < z \\<and> z < y\")\n  case True\n  then obtain z where \"x < z \\<and> z < y\" ..\n  then have \"x \\<in> {..< z} \\<and> y \\<in> {z <..} \\<and> {z <..} \\<inter> {..< z} = {}\"\n    by auto\n  then show ?thesis by blast\nnext\n  case False\n  with \\<open>x < y\\<close> have \"x \\<in> {..< y}\" \"y \\<in> {x <..}\" \"{x <..} \\<inter> {..< y} = {}\"\n    by auto\n  then show ?thesis by blast\nqed\n\ninstance linorder_topology \\<subseteq> t2_space\nproof\n  fix x y :: 'a\n  show \"x \\<noteq> y \\<Longrightarrow> \\<exists>U V. open U \\<and> open V \\<and> x \\<in> U \\<and> y \\<in> V \\<and> U \\<inter> V = {}\"\n    using less_separate [of x y] less_separate [of y x]\n    by (elim neqE; metis open_lessThan open_greaterThan Int_commute)\nqed\n\nlemma (in linorder_topology) open_right:\n  assumes \"open S\" \"x \\<in> S\"\n    and gt_ex: \"x < y\"\n  shows \"\\<exists>b>x. {x ..< b} \\<subseteq> S\"\n  using assms unfolding open_generated_order\nproof induct\n  case UNIV\n  then show ?case by blast\nnext\n  case (Int A B)\n  then obtain a b where \"a > x\" \"{x ..< a} \\<subseteq> A\"  \"b > x\" \"{x ..< b} \\<subseteq> B\"\n    by auto\n  then show ?case\n    by (auto intro!: exI[of _ \"min a b\"])\nnext\n  case UN\n  then show ?case by blast\nnext\n  case Basis\n  then show ?case\n    by (fastforce intro: exI[of _ y] gt_ex)\nqed\n\nlemma (in linorder_topology) open_left:\n  assumes \"open S\" \"x \\<in> S\"\n    and lt_ex: \"y < x\"\n  shows \"\\<exists>b<x. {b <.. x} \\<subseteq> S\"\n  using assms unfolding open_generated_order\nproof induction\n  case UNIV\n  then show ?case by blast\nnext\n  case (Int A B)\n  then obtain a b where \"a < x\" \"{a <.. x} \\<subseteq> A\"  \"b < x\" \"{b <.. x} \\<subseteq> B\"\n    by auto\n  then show ?case\n    by (auto intro!: exI[of _ \"max a b\"])\nnext\n  case UN\n  then show ?case by blast\nnext\n  case Basis\n  then show ?case\n    by (fastforce intro: exI[of _ y] lt_ex)\nqed\n\n\nsubsection \\<open>Setup some topologies\\<close>\n\nsubsubsection \\<open>Boolean is an order topology\\<close>\n\nclass discrete_topology = topological_space +\n  assumes open_discrete: \"\\<And>A. open A\"\n\ninstance discrete_topology < t2_space\nproof\n  fix x y :: 'a\n  assume \"x \\<noteq> y\"\n  then show \"\\<exists>U V. open U \\<and> open V \\<and> x \\<in> U \\<and> y \\<in> V \\<and> U \\<inter> V = {}\"\n    by (intro exI[of _ \"{_}\"]) (auto intro!: open_discrete)\nqed\n\ninstantiation bool :: linorder_topology\nbegin\n\ndefinition open_bool :: \"bool set \\<Rightarrow> bool\"\n  where \"open_bool = generate_topology (range (\\<lambda>a. {..< a}) \\<union> range (\\<lambda>a. {a <..}))\"\n\ninstance\n  by standard (rule open_bool_def)\n\nend\n\ninstance bool :: discrete_topology\nproof\n  fix A :: \"bool set\"\n  have *: \"{False <..} = {True}\" \"{..< True} = {False}\"\n    by auto\n  have \"A = UNIV \\<or> A = {} \\<or> A = {False <..} \\<or> A = {..< True}\"\n    using subset_UNIV[of A] unfolding UNIV_bool * by blast\n  then show \"open A\"\n    by auto\nqed\n\ninstantiation nat :: linorder_topology\nbegin\n\ndefinition open_nat :: \"nat set \\<Rightarrow> bool\"\n  where \"open_nat = generate_topology (range (\\<lambda>a. {..< a}) \\<union> range (\\<lambda>a. {a <..}))\"\n\ninstance\n  by standard (rule open_nat_def)\n\nend\n\ninstance nat :: discrete_topology\nproof\n  fix A :: \"nat set\"\n  have \"open {n}\" for n :: nat\n  proof (cases n)\n    case 0\n    moreover have \"{0} = {..<1::nat}\"\n      by auto\n    ultimately show ?thesis\n       by auto\n  next\n    case (Suc n')\n    then have \"{n} = {..<Suc n} \\<inter> {n' <..}\"\n      by auto\n    with Suc show ?thesis\n      by (auto intro: open_lessThan open_greaterThan)\n  qed\n  then have \"open (\\<Union>a\\<in>A. {a})\"\n    by (intro open_UN) auto\n  then show \"open A\"\n    by simp\nqed\n\ninstantiation int :: linorder_topology\nbegin\n\ndefinition open_int :: \"int set \\<Rightarrow> bool\"\n  where \"open_int = generate_topology (range (\\<lambda>a. {..< a}) \\<union> range (\\<lambda>a. {a <..}))\"\n\ninstance\n  by standard (rule open_int_def)\n\nend\n\ninstance int :: discrete_topology\nproof\n  fix A :: \"int set\"\n  have \"{..<i + 1} \\<inter> {i-1 <..} = {i}\" for i :: int\n    by auto\n  then have \"open {i}\" for i :: int\n    using open_Int[OF open_lessThan[of \"i + 1\"] open_greaterThan[of \"i - 1\"]] by auto\n  then have \"open (\\<Union>a\\<in>A. {a})\"\n    by (intro open_UN) auto\n  then show \"open A\"\n    by simp\nqed\n\n\nsubsubsection \\<open>Topological filters\\<close>\n\ndefinition (in topological_space) nhds :: \"'a \\<Rightarrow> 'a filter\"\n  where \"nhds a = (INF S\\<in>{S. open S \\<and> a \\<in> S}. principal S)\"\n\ndefinition (in topological_space) at_within :: \"'a \\<Rightarrow> 'a set \\<Rightarrow> 'a filter\"\n    (\"at (_)/ within (_)\" [1000, 60] 60)\n  where \"at a within s = inf (nhds a) (principal (s - {a}))\"\n\nabbreviation (in topological_space) at :: \"'a \\<Rightarrow> 'a filter\"  (\"at\")\n  where \"at x \\<equiv> at x within (CONST UNIV)\"\n\nabbreviation (in order_topology) at_right :: \"'a \\<Rightarrow> 'a filter\"\n  where \"at_right x \\<equiv> at x within {x <..}\"\n\nabbreviation (in order_topology) at_left :: \"'a \\<Rightarrow> 'a filter\"\n  where \"at_left x \\<equiv> at x within {..< x}\"\n\nlemma (in topological_space) nhds_generated_topology:\n  \"open = generate_topology T \\<Longrightarrow> nhds x = (INF S\\<in>{S\\<in>T. x \\<in> S}. principal S)\"\n  unfolding nhds_def\nproof (safe intro!: antisym INF_greatest)\n  fix S\n  assume \"generate_topology T S\" \"x \\<in> S\"\n  then show \"(INF S\\<in>{S \\<in> T. x \\<in> S}. principal S) \\<le> principal S\"\n    by induct\n      (auto intro: INF_lower order_trans simp: inf_principal[symmetric] simp del: inf_principal)\nqed (auto intro!: INF_lower intro: generate_topology.intros)\n\nlemma (in topological_space) eventually_nhds:\n  \"eventually P (nhds a) \\<longleftrightarrow> (\\<exists>S. open S \\<and> a \\<in> S \\<and> (\\<forall>x\\<in>S. P x))\"\n  unfolding nhds_def by (subst eventually_INF_base) (auto simp: eventually_principal)\n\nlemma eventually_eventually:\n  \"eventually (\\<lambda>y. eventually P (nhds y)) (nhds x) = eventually P (nhds x)\"\n  by (auto simp: eventually_nhds)\n\nlemma (in topological_space) eventually_nhds_in_open:\n  \"open s \\<Longrightarrow> x \\<in> s \\<Longrightarrow> eventually (\\<lambda>y. y \\<in> s) (nhds x)\"\n  by (subst eventually_nhds) blast\n\nlemma (in topological_space) eventually_nhds_x_imp_x: \"eventually P (nhds x) \\<Longrightarrow> P x\"\n  by (subst (asm) eventually_nhds) blast\n\nlemma (in topological_space) nhds_neq_bot [simp]: \"nhds a \\<noteq> bot\"\n  by (simp add: trivial_limit_def eventually_nhds)\n\nlemma (in t1_space) t1_space_nhds: \"x \\<noteq> y \\<Longrightarrow> (\\<forall>\\<^sub>F x in nhds x. x \\<noteq> y)\"\n  by (drule t1_space) (auto simp: eventually_nhds)\n\nlemma (in topological_space) nhds_discrete_open: \"open {x} \\<Longrightarrow> nhds x = principal {x}\"\n  by (auto simp: nhds_def intro!: antisym INF_greatest INF_lower2[of \"{x}\"])\n\nlemma (in discrete_topology) nhds_discrete: \"nhds x = principal {x}\"\n  by (simp add: nhds_discrete_open open_discrete)\n\nlemma (in discrete_topology) at_discrete: \"at x within S = bot\"\n  unfolding at_within_def nhds_discrete by simp\n\nlemma (in discrete_topology) tendsto_discrete:\n  \"filterlim (f :: 'b \\<Rightarrow> 'a) (nhds y) F \\<longleftrightarrow> eventually (\\<lambda>x. f x = y) F\"\n  by (auto simp: nhds_discrete filterlim_principal)\n\nlemma (in topological_space) at_within_eq:\n  \"at x within s = (INF S\\<in>{S. open S \\<and> x \\<in> S}. principal (S \\<inter> s - {x}))\"\n  unfolding nhds_def at_within_def\n  by (subst INF_inf_const2[symmetric]) (auto simp: Diff_Int_distrib)\n\nlemma (in topological_space) eventually_at_filter:\n  \"eventually P (at a within s) \\<longleftrightarrow> eventually (\\<lambda>x. x \\<noteq> a \\<longrightarrow> x \\<in> s \\<longrightarrow> P x) (nhds a)\"\n  by (simp add: at_within_def eventually_inf_principal imp_conjL[symmetric] conj_commute)\n\nlemma (in topological_space) at_le: \"s \\<subseteq> t \\<Longrightarrow> at x within s \\<le> at x within t\"\n  unfolding at_within_def by (intro inf_mono) auto\n\nlemma (in topological_space) eventually_at_topological:\n  \"eventually P (at a within s) \\<longleftrightarrow> (\\<exists>S. open S \\<and> a \\<in> S \\<and> (\\<forall>x\\<in>S. x \\<noteq> a \\<longrightarrow> x \\<in> s \\<longrightarrow> P x))\"\n  by (simp add: eventually_nhds eventually_at_filter)\n\nlemma eventually_at_in_open:\n  assumes \"open A\" \"x \\<in> A\"\n  shows   \"eventually (\\<lambda>y. y \\<in> A - {x}) (at x)\"\n  using assms eventually_at_topological by blast\n\nlemma eventually_at_in_open':\n  assumes \"open A\" \"x \\<in> A\"\n  shows   \"eventually (\\<lambda>y. y \\<in> A) (at x)\"\n  using assms eventually_at_topological by blast\n\nlemma (in topological_space) at_within_open: \"a \\<in> S \\<Longrightarrow> open S \\<Longrightarrow> at a within S = at a\"\n  unfolding filter_eq_iff eventually_at_topological by (metis open_Int Int_iff UNIV_I)\n\nlemma (in topological_space) at_within_open_NO_MATCH:\n  \"a \\<in> s \\<Longrightarrow> open s \\<Longrightarrow> NO_MATCH UNIV s \\<Longrightarrow> at a within s = at a\"\n  by (simp only: at_within_open)\n\nlemma (in topological_space) at_within_open_subset:\n  \"a \\<in> S \\<Longrightarrow> open S \\<Longrightarrow> S \\<subseteq> T \\<Longrightarrow> at a within T = at a\"\n  by (metis at_le at_within_open dual_order.antisym subset_UNIV)\n\nlemma (in topological_space) at_within_nhd:\n  assumes \"x \\<in> S\" \"open S\" \"T \\<inter> S - {x} = U \\<inter> S - {x}\"\n  shows \"at x within T = at x within U\"\n  unfolding filter_eq_iff eventually_at_filter\nproof (intro allI eventually_subst)\n  have \"eventually (\\<lambda>x. x \\<in> S) (nhds x)\"\n    using \\<open>x \\<in> S\\<close> \\<open>open S\\<close> by (auto simp: eventually_nhds)\n  then show \"\\<forall>\\<^sub>F n in nhds x. (n \\<noteq> x \\<longrightarrow> n \\<in> T \\<longrightarrow> P n) = (n \\<noteq> x \\<longrightarrow> n \\<in> U \\<longrightarrow> P n)\" for P\n    by eventually_elim (insert \\<open>T \\<inter> S - {x} = U \\<inter> S - {x}\\<close>, blast)\nqed\n\nlemma (in topological_space) at_within_empty [simp]: \"at a within {} = bot\"\n  unfolding at_within_def by simp\n\nlemma (in topological_space) at_within_union:\n  \"at x within (S \\<union> T) = sup (at x within S) (at x within T)\"\n  unfolding filter_eq_iff eventually_sup eventually_at_filter\n  by (auto elim!: eventually_rev_mp)\n\nlemma (in topological_space) at_eq_bot_iff: \"at a = bot \\<longleftrightarrow> open {a}\"\n  unfolding trivial_limit_def eventually_at_topological\n  by (metis UNIV_I empty_iff is_singletonE is_singletonI' singleton_iff)\n\nlemma (in t1_space) eventually_neq_at_within:\n  \"eventually (\\<lambda>w. w \\<noteq> x) (at z within A)\"\n  by (smt (verit, ccfv_threshold) eventually_True eventually_at_topological separation_t1)\n\nlemma (in perfect_space) at_neq_bot [simp]: \"at a \\<noteq> bot\"\n  by (simp add: at_eq_bot_iff not_open_singleton)\n\nlemma (in order_topology) nhds_order:\n  \"nhds x = inf (INF a\\<in>{x <..}. principal {..< a}) (INF a\\<in>{..< x}. principal {a <..})\"\nproof -\n  have 1: \"{S \\<in> range lessThan \\<union> range greaterThan. x \\<in> S} =\n      (\\<lambda>a. {..< a}) ` {x <..} \\<union> (\\<lambda>a. {a <..}) ` {..< x}\"\n    by auto\n  show ?thesis\n    by (simp only: nhds_generated_topology[OF open_generated_order] INF_union 1 INF_image comp_def)\nqed\n\nlemma (in topological_space) filterlim_at_within_If:\n  assumes \"filterlim f G (at x within (A \\<inter> {x. P x}))\"\n    and \"filterlim g G (at x within (A \\<inter> {x. \\<not>P x}))\"\n  shows \"filterlim (\\<lambda>x. if P x then f x else g x) G (at x within A)\"\nproof (rule filterlim_If)\n  note assms(1)\n  also have \"at x within (A \\<inter> {x. P x}) = inf (nhds x) (principal (A \\<inter> Collect P - {x}))\"\n    by (simp add: at_within_def)\n  also have \"A \\<inter> Collect P - {x} = (A - {x}) \\<inter> Collect P\"\n    by blast\n  also have \"inf (nhds x) (principal \\<dots>) = inf (at x within A) (principal (Collect P))\"\n    by (simp add: at_within_def inf_assoc)\n  finally show \"filterlim f G (inf (at x within A) (principal (Collect P)))\" .\nnext\n  note assms(2)\n  also have \"at x within (A \\<inter> {x. \\<not> P x}) = inf (nhds x) (principal (A \\<inter> {x. \\<not> P x} - {x}))\"\n    by (simp add: at_within_def)\n  also have \"A \\<inter> {x. \\<not> P x} - {x} = (A - {x}) \\<inter> {x. \\<not> P x}\"\n    by blast\n  also have \"inf (nhds x) (principal \\<dots>) = inf (at x within A) (principal {x. \\<not> P x})\"\n    by (simp add: at_within_def inf_assoc)\n  finally show \"filterlim g G (inf (at x within A) (principal {x. \\<not> P x}))\" .\nqed\n\nlemma (in topological_space) filterlim_at_If:\n  assumes \"filterlim f G (at x within {x. P x})\"\n    and \"filterlim g G (at x within {x. \\<not>P x})\"\n  shows \"filterlim (\\<lambda>x. if P x then f x else g x) G (at x)\"\n  using assms by (intro filterlim_at_within_If) simp_all\nlemma (in linorder_topology) at_within_order:\n  assumes \"UNIV \\<noteq> {x}\"\n  shows \"at x within s =\n    inf (INF a\\<in>{x <..}. principal ({..< a} \\<inter> s - {x}))\n        (INF a\\<in>{..< x}. principal ({a <..} \\<inter> s - {x}))\"\nproof (cases \"{x <..} = {}\" \"{..< x} = {}\" rule: case_split [case_product case_split])\n  case True_True\n  have \"UNIV = {..< x} \\<union> {x} \\<union> {x <..}\"\n    by auto\n  with assms True_True show ?thesis\n    by auto\nqed (auto simp del: inf_principal simp: at_within_def nhds_order Int_Diff\n      inf_principal[symmetric] INF_inf_const2 inf_sup_aci[where 'a=\"'a filter\"])\n\nlemma (in linorder_topology) at_left_eq:\n  \"y < x \\<Longrightarrow> at_left x = (INF a\\<in>{..< x}. principal {a <..< x})\"\n  by (subst at_within_order)\n     (auto simp: greaterThan_Int_greaterThan greaterThanLessThan_eq[symmetric] min.absorb2 INF_constant\n           intro!: INF_lower2 inf_absorb2)\n\nlemma (in linorder_topology) eventually_at_left:\n  \"y < x \\<Longrightarrow> eventually P (at_left x) \\<longleftrightarrow> (\\<exists>b<x. \\<forall>y>b. y < x \\<longrightarrow> P y)\"\n  unfolding at_left_eq\n  by (subst eventually_INF_base) (auto simp: eventually_principal Ball_def)\n\nlemma (in linorder_topology) at_right_eq:\n  \"x < y \\<Longrightarrow> at_right x = (INF a\\<in>{x <..}. principal {x <..< a})\"\n  by (subst at_within_order)\n     (auto simp: lessThan_Int_lessThan greaterThanLessThan_eq[symmetric] max.absorb2 INF_constant Int_commute\n           intro!: INF_lower2 inf_absorb1)\n\nlemma (in linorder_topology) eventually_at_right:\n  \"x < y \\<Longrightarrow> eventually P (at_right x) \\<longleftrightarrow> (\\<exists>b>x. \\<forall>y>x. y < b \\<longrightarrow> P y)\"\n  unfolding at_right_eq\n  by (subst eventually_INF_base) (auto simp: eventually_principal Ball_def)\n\nlemma eventually_at_right_less: \"\\<forall>\\<^sub>F y in at_right (x::'a::{linorder_topology, no_top}). x < y\"\n  using gt_ex[of x] eventually_at_right[of x] by auto\n\nlemma trivial_limit_at_right_top: \"at_right (top::_::{order_top,linorder_topology}) = bot\"\n  by (auto simp: filter_eq_iff eventually_at_topological)\n\nlemma trivial_limit_at_left_bot: \"at_left (bot::_::{order_bot,linorder_topology}) = bot\"\n  by (auto simp: filter_eq_iff eventually_at_topological)\n\nlemma trivial_limit_at_left_real [simp]: \"\\<not> trivial_limit (at_left x)\"\n  for x :: \"'a::{no_bot,dense_order,linorder_topology}\"\n  using lt_ex [of x]\n  by safe (auto simp add: trivial_limit_def eventually_at_left dest: dense)\n\nlemma trivial_limit_at_right_real [simp]: \"\\<not> trivial_limit (at_right x)\"\n  for x :: \"'a::{no_top,dense_order,linorder_topology}\"\n  using gt_ex[of x]\n  by safe (auto simp add: trivial_limit_def eventually_at_right dest: dense)\n\nlemma (in linorder_topology) at_eq_sup_left_right: \"at x = sup (at_left x) (at_right x)\"\n  by (auto simp: eventually_at_filter filter_eq_iff eventually_sup\n      elim: eventually_elim2 eventually_mono)\n\nlemma (in linorder_topology) eventually_at_split:\n  \"eventually P (at x) \\<longleftrightarrow> eventually P (at_left x) \\<and> eventually P (at_right x)\"\n  by (subst at_eq_sup_left_right) (simp add: eventually_sup)\n\nlemma (in order_topology) eventually_at_leftI:\n  assumes \"\\<And>x. x \\<in> {a<..<b} \\<Longrightarrow> P x\" \"a < b\"\n  shows   \"eventually P (at_left b)\"\n  using assms unfolding eventually_at_topological by (intro exI[of _ \"{a<..}\"]) auto\n\nlemma (in order_topology) eventually_at_rightI:\n  assumes \"\\<And>x. x \\<in> {a<..<b} \\<Longrightarrow> P x\" \"a < b\"\n  shows   \"eventually P (at_right a)\"\n  using assms unfolding eventually_at_topological by (intro exI[of _ \"{..<b}\"]) auto\n\nlemma eventually_filtercomap_nhds:\n  \"eventually P (filtercomap f (nhds x)) \\<longleftrightarrow> (\\<exists>S. open S \\<and> x \\<in> S \\<and> (\\<forall>x. f x \\<in> S \\<longrightarrow> P x))\"\n  unfolding eventually_filtercomap eventually_nhds by auto\n\nlemma eventually_filtercomap_at_topological:\n  \"eventually P (filtercomap f (at A within B)) \\<longleftrightarrow> \n     (\\<exists>S. open S \\<and> A \\<in> S \\<and> (\\<forall>x. f x \\<in> S \\<inter> B - {A} \\<longrightarrow> P x))\" (is \"?lhs = ?rhs\")\n  unfolding at_within_def filtercomap_inf eventually_inf_principal filtercomap_principal \n          eventually_filtercomap_nhds eventually_principal by blast\n\nlemma eventually_at_right_field:\n  \"eventually P (at_right x) \\<longleftrightarrow> (\\<exists>b>x. \\<forall>y>x. y < b \\<longrightarrow> P y)\"\n  for x :: \"'a::{linordered_field, linorder_topology}\"\n  using linordered_field_no_ub[rule_format, of x]\n  by (auto simp: eventually_at_right)\n\nlemma eventually_at_left_field:\n  \"eventually P (at_left x) \\<longleftrightarrow> (\\<exists>b<x. \\<forall>y>b. y < x \\<longrightarrow> P y)\"\n  for x :: \"'a::{linordered_field, linorder_topology}\"\n  using linordered_field_no_lb[rule_format, of x]\n  by (auto simp: eventually_at_left)\n\nlemma filtermap_nhds_eq_imp_filtermap_at_eq: \n  assumes \"filtermap f (nhds z) = nhds (f z)\"\n  assumes \"eventually (\\<lambda>x. f x = f z \\<longrightarrow> x = z) (at z)\"\n  shows   \"filtermap f (at z) = at (f z)\"\nproof (rule filter_eqI)\n  fix P :: \"'a \\<Rightarrow> bool\"\n  have \"eventually P (filtermap f (at z)) \\<longleftrightarrow> (\\<forall>\\<^sub>F x in nhds z. x \\<noteq> z \\<longrightarrow> P (f x))\"\n    by (simp add: eventually_filtermap eventually_at_filter)\n  also have \"\\<dots> \\<longleftrightarrow> (\\<forall>\\<^sub>F x in nhds z. f x \\<noteq> f z \\<longrightarrow> P (f x))\"\n    by (rule eventually_cong [OF assms(2)[unfolded eventually_at_filter]]) auto\n  also have \"\\<dots> \\<longleftrightarrow> (\\<forall>\\<^sub>F x in filtermap f (nhds z). x \\<noteq> f z \\<longrightarrow> P x)\"\n    by (simp add: eventually_filtermap)\n  also have \"filtermap f (nhds z) = nhds (f z)\"\n    by (rule assms)\n  also have \"(\\<forall>\\<^sub>F x in nhds (f z). x \\<noteq> f z \\<longrightarrow> P x) \\<longleftrightarrow> (\\<forall>\\<^sub>F x in at (f z). P x)\"\n    by (simp add: eventually_at_filter)\n  finally show \"eventually P (filtermap f (at z)) = eventually P (at (f z))\" .\nqed\n\nsubsubsection \\<open>Tendsto\\<close>\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\nlemma (in topological_space) tendsto_eq_rhs: \"(f \\<longlongrightarrow> x) F \\<Longrightarrow> x = y \\<Longrightarrow> (f \\<longlongrightarrow> y) F\"\n  by simp\n\nnamed_theorems tendsto_intros \"introduction rules for tendsto\"\nsetup \\<open>\n  Global_Theory.add_thms_dynamic (\\<^binding>\\<open>tendsto_eq_intros\\<close>,\n    fn context =>\n      Named_Theorems.get (Context.proof_of context) \\<^named_theorems>\\<open>tendsto_intros\\<close>\n      |> map_filter (try (fn thm => @{thm tendsto_eq_rhs} OF [thm])))\n\\<close>\n\ncontext topological_space begin\n\nlemma tendsto_def:\n   \"(f \\<longlongrightarrow> l) F \\<longleftrightarrow> (\\<forall>S. open S \\<longrightarrow> l \\<in> S \\<longrightarrow> eventually (\\<lambda>x. f x \\<in> S) F)\"\n   unfolding nhds_def filterlim_INF filterlim_principal by auto\n\nlemma tendsto_cong: \"(f \\<longlongrightarrow> c) F \\<longleftrightarrow> (g \\<longlongrightarrow> c) F\" if \"eventually (\\<lambda>x. f x = g x) F\"\n  by (rule filterlim_cong [OF refl refl that])\n\nlemma tendsto_mono: \"F \\<le> F' \\<Longrightarrow> (f \\<longlongrightarrow> l) F' \\<Longrightarrow> (f \\<longlongrightarrow> l) F\"\n  unfolding tendsto_def le_filter_def by fast\n\nlemma tendsto_ident_at [tendsto_intros, simp, intro]: \"((\\<lambda>x. x) \\<longlongrightarrow> a) (at a within s)\"\n  by (auto simp: tendsto_def eventually_at_topological)\n\nlemma tendsto_const [tendsto_intros, simp, intro]: \"((\\<lambda>x. k) \\<longlongrightarrow> k) F\"\n  by (simp add: tendsto_def)\n\nlemma filterlim_at:\n  \"(LIM x F. f x :> at b within s) \\<longleftrightarrow> eventually (\\<lambda>x. f x \\<in> s \\<and> f x \\<noteq> b) F \\<and> (f \\<longlongrightarrow> b) F\"\n  by (simp add: at_within_def filterlim_inf filterlim_principal conj_commute)\n\nlemma (in -)\n  assumes \"filterlim f (nhds L) F\"\n  shows tendsto_imp_filterlim_at_right:\n          \"eventually (\\<lambda>x. f x > L) F \\<Longrightarrow> filterlim f (at_right L) F\"\n    and tendsto_imp_filterlim_at_left:\n          \"eventually (\\<lambda>x. f x < L) F \\<Longrightarrow> filterlim f (at_left L) F\"\n  using assms by (auto simp: filterlim_at elim: eventually_mono)\n\nlemma  filterlim_at_withinI:\n  assumes \"filterlim f (nhds c) F\"\n  assumes \"eventually (\\<lambda>x. f x \\<in> A - {c}) F\"\n  shows   \"filterlim f (at c within A) F\"\n  using assms by (simp add: filterlim_at)\n\nlemma filterlim_atI:\n  assumes \"filterlim f (nhds c) F\"\n  assumes \"eventually (\\<lambda>x. f x \\<noteq> c) F\"\n  shows   \"filterlim f (at c) F\"\n  using assms by (intro filterlim_at_withinI) simp_all\n\nlemma topological_tendstoI:\n  \"(\\<And>S. open S \\<Longrightarrow> l \\<in> S \\<Longrightarrow> eventually (\\<lambda>x. f x \\<in> S) F) \\<Longrightarrow> (f \\<longlongrightarrow> l) F\"\n  by (auto simp: tendsto_def)\n\nlemma topological_tendstoD:\n  \"(f \\<longlongrightarrow> l) F \\<Longrightarrow> open S \\<Longrightarrow> l \\<in> S \\<Longrightarrow> eventually (\\<lambda>x. f x \\<in> S) F\"\n  by (auto simp: tendsto_def)\n\nlemma tendsto_bot [simp]: \"(f \\<longlongrightarrow> a) bot\"\n  by (simp add: tendsto_def)\n\nlemma tendsto_eventually: \"eventually (\\<lambda>x. f x = l) net \\<Longrightarrow> ((\\<lambda>x. f x) \\<longlongrightarrow> l) net\"\n  by (rule topological_tendstoI) (auto elim: eventually_mono)\n\n(* Contributed by Dominique Unruh *)\nlemma tendsto_principal_singleton[simp]:\n  shows \"(f \\<longlongrightarrow> f x) (principal {x})\"\n  unfolding tendsto_def eventually_principal by simp\n\nend\n\nlemma (in topological_space) filterlim_within_subset:\n  \"filterlim f l (at x within S) \\<Longrightarrow> T \\<subseteq> S \\<Longrightarrow> filterlim f l (at x within T)\"\n  by (blast intro: filterlim_mono at_le)\n\nlemmas tendsto_within_subset = filterlim_within_subset\n\nlemma (in order_topology) order_tendsto_iff:\n  \"(f \\<longlongrightarrow> x) F \\<longleftrightarrow> (\\<forall>l<x. eventually (\\<lambda>x. l < f x) F) \\<and> (\\<forall>u>x. eventually (\\<lambda>x. f x < u) F)\"\n  by (auto simp: nhds_order filterlim_inf filterlim_INF filterlim_principal)\n\nlemma (in order_topology) order_tendstoI:\n  \"(\\<And>a. a < y \\<Longrightarrow> eventually (\\<lambda>x. a < f x) F) \\<Longrightarrow> (\\<And>a. y < a \\<Longrightarrow> eventually (\\<lambda>x. f x < a) F) \\<Longrightarrow>\n    (f \\<longlongrightarrow> y) F\"\n  by (auto simp: order_tendsto_iff)\n\nlemma (in order_topology) order_tendstoD:\n  assumes \"(f \\<longlongrightarrow> y) F\"\n  shows \"a < y \\<Longrightarrow> eventually (\\<lambda>x. a < f x) F\"\n    and \"y < a \\<Longrightarrow> eventually (\\<lambda>x. f x < a) F\"\n  using assms by (auto simp: order_tendsto_iff)\n\nlemma (in linorder_topology) tendsto_max[tendsto_intros]:\n  assumes X: \"(X \\<longlongrightarrow> x) net\"\n    and Y: \"(Y \\<longlongrightarrow> y) net\"\n  shows \"((\\<lambda>x. max (X x) (Y x)) \\<longlongrightarrow> max x y) net\"\nproof (rule order_tendstoI)\n  fix a\n  assume \"a < max x y\"\n  then show \"eventually (\\<lambda>x. a < max (X x) (Y x)) net\"\n    using order_tendstoD(1)[OF X, of a] order_tendstoD(1)[OF Y, of a]\n    by (auto simp: less_max_iff_disj elim: eventually_mono)\nnext\n  fix a\n  assume \"max x y < a\"\n  then show \"eventually (\\<lambda>x. max (X x) (Y x) < a) net\"\n    using order_tendstoD(2)[OF X, of a] order_tendstoD(2)[OF Y, of a]\n    by (auto simp: eventually_conj_iff)\nqed\n\nlemma (in linorder_topology) tendsto_min[tendsto_intros]:\n  assumes X: \"(X \\<longlongrightarrow> x) net\"\n    and Y: \"(Y \\<longlongrightarrow> y) net\"\n  shows \"((\\<lambda>x. min (X x) (Y x)) \\<longlongrightarrow> min x y) net\"\nproof (rule order_tendstoI)\n  fix a\n  assume \"a < min x y\"\n  then show \"eventually (\\<lambda>x. a < min (X x) (Y x)) net\"\n    using order_tendstoD(1)[OF X, of a] order_tendstoD(1)[OF Y, of a]\n    by (auto simp: eventually_conj_iff)\nnext\n  fix a\n  assume \"min x y < a\"\n  then show \"eventually (\\<lambda>x. min (X x) (Y x) < a) net\"\n    using order_tendstoD(2)[OF X, of a] order_tendstoD(2)[OF Y, of a]\n    by (auto simp: min_less_iff_disj elim: eventually_mono)\nqed\n\nlemma (in order_topology)\n  assumes \"a < b\"\n  shows at_within_Icc_at_right: \"at a within {a..b} = at_right a\"\n    and at_within_Icc_at_left:  \"at b within {a..b} = at_left b\"\n  using order_tendstoD(2)[OF tendsto_ident_at assms, of \"{a<..}\"]\n  using order_tendstoD(1)[OF tendsto_ident_at assms, of \"{..<b}\"]\n  by (auto intro!: order_class.order_antisym filter_leI\n      simp: eventually_at_filter less_le\n      elim: eventually_elim2)\n\nlemma (in order_topology) at_within_Icc_at: \"a < x \\<Longrightarrow> x < b \\<Longrightarrow> at x within {a..b} = at x\"\n  by (rule at_within_open_subset[where S=\"{a<..<b}\"]) auto\n\nlemma (in t2_space) tendsto_unique:\n  assumes \"F \\<noteq> bot\"\n    and \"(f \\<longlongrightarrow> a) F\"\n    and \"(f \\<longlongrightarrow> b) F\"\n  shows \"a = b\"\nproof (rule ccontr)\n  assume \"a \\<noteq> b\"\n  obtain U V where \"open U\" \"open V\" \"a \\<in> U\" \"b \\<in> V\" \"U \\<inter> V = {}\"\n    using hausdorff [OF \\<open>a \\<noteq> b\\<close>] by fast\n  have \"eventually (\\<lambda>x. f x \\<in> U) F\"\n    using \\<open>(f \\<longlongrightarrow> a) F\\<close> \\<open>open U\\<close> \\<open>a \\<in> U\\<close> by (rule topological_tendstoD)\n  moreover\n  have \"eventually (\\<lambda>x. f x \\<in> V) F\"\n    using \\<open>(f \\<longlongrightarrow> b) F\\<close> \\<open>open V\\<close> \\<open>b \\<in> V\\<close> by (rule topological_tendstoD)\n  ultimately\n  have \"eventually (\\<lambda>x. False) F\"\n  proof eventually_elim\n    case (elim x)\n    then have \"f x \\<in> U \\<inter> V\" by simp\n    with \\<open>U \\<inter> V = {}\\<close> show ?case by simp\n  qed\n  with \\<open>\\<not> trivial_limit F\\<close> show \"False\"\n    by (simp add: trivial_limit_def)\nqed\n\nlemma (in t2_space) tendsto_const_iff:\n  fixes a b :: 'a\n  assumes \"\\<not> trivial_limit F\"\n  shows \"((\\<lambda>x. a) \\<longlongrightarrow> b) F \\<longleftrightarrow> a = b\"\n  by (auto intro!: tendsto_unique [OF assms tendsto_const])\n\nlemma (in t2_space) tendsto_unique':\n assumes \"F \\<noteq> bot\"\n shows \"\\<exists>\\<^sub>\\<le>\\<^sub>1l. (f \\<longlongrightarrow> l) F\"\n using Uniq_def assms local.tendsto_unique by fastforce\n\nlemma Lim_in_closed_set:\n  assumes \"closed S\" \"eventually (\\<lambda>x. f(x) \\<in> S) F\" \"F \\<noteq> bot\" \"(f \\<longlongrightarrow> l) F\"\n  shows \"l \\<in> S\"\nproof (rule ccontr)\n  assume \"l \\<notin> S\"\n  with \\<open>closed S\\<close> have \"open (- S)\" \"l \\<in> - S\"\n    by (simp_all add: open_Compl)\n  with assms(4) have \"eventually (\\<lambda>x. f x \\<in> - S) F\"\n    by (rule topological_tendstoD)\n  with assms(2) have \"eventually (\\<lambda>x. False) F\"\n    by (rule eventually_elim2) simp\n  with assms(3) show \"False\"\n    by (simp add: eventually_False)\nqed\n\nlemma (in t3_space) nhds_closed:\n  assumes \"x \\<in> A\" and \"open A\"\n  shows   \"\\<exists>A'. x \\<in> A' \\<and> closed A' \\<and> A' \\<subseteq> A \\<and> eventually (\\<lambda>y. y \\<in> A') (nhds x)\"\nproof -\n  from assms have \"\\<exists>U V. open U \\<and> open V \\<and> x \\<in> U \\<and> - A \\<subseteq> V \\<and> U \\<inter> V = {}\"\n    by (intro t3_space) auto\n  then obtain U V where UV: \"open U\" \"open V\" \"x \\<in> U\" \"-A \\<subseteq> V\" \"U \\<inter> V = {}\"\n    by auto\n  have \"eventually (\\<lambda>y. y \\<in> U) (nhds x)\"\n    using \\<open>open U\\<close> and \\<open>x \\<in> U\\<close> by (intro eventually_nhds_in_open)\n  hence \"eventually (\\<lambda>y. y \\<in> -V) (nhds x)\"\n    by eventually_elim (use UV in auto)\n  with UV show ?thesis by (intro exI[of _ \"-V\"]) auto\nqed\n\nlemma (in order_topology) increasing_tendsto:\n  assumes bdd: \"eventually (\\<lambda>n. f n \\<le> l) F\"\n    and en: \"\\<And>x. x < l \\<Longrightarrow> eventually (\\<lambda>n. x < f n) F\"\n  shows \"(f \\<longlongrightarrow> l) F\"\n  using assms by (intro order_tendstoI) (auto elim!: eventually_mono)\n\nlemma (in order_topology) decreasing_tendsto:\n  assumes bdd: \"eventually (\\<lambda>n. l \\<le> f n) F\"\n    and en: \"\\<And>x. l < x \\<Longrightarrow> eventually (\\<lambda>n. f n < x) F\"\n  shows \"(f \\<longlongrightarrow> l) F\"\n  using assms by (intro order_tendstoI) (auto elim!: eventually_mono)\n\nlemma (in order_topology) tendsto_sandwich:\n  assumes ev: \"eventually (\\<lambda>n. f n \\<le> g n) net\" \"eventually (\\<lambda>n. g n \\<le> h n) net\"\n  assumes lim: \"(f \\<longlongrightarrow> c) net\" \"(h \\<longlongrightarrow> c) net\"\n  shows \"(g \\<longlongrightarrow> c) net\"\nproof (rule order_tendstoI)\n  fix a\n  show \"a < c \\<Longrightarrow> eventually (\\<lambda>x. a < g x) net\"\n    using order_tendstoD[OF lim(1), of a] ev by (auto elim: eventually_elim2)\nnext\n  fix a\n  show \"c < a \\<Longrightarrow> eventually (\\<lambda>x. g x < a) net\"\n    using order_tendstoD[OF lim(2), of a] ev by (auto elim: eventually_elim2)\nqed\n\nlemma (in t1_space) limit_frequently_eq:\n  assumes \"F \\<noteq> bot\"\n    and \"frequently (\\<lambda>x. f x = c) F\"\n    and \"(f \\<longlongrightarrow> d) F\"\n  shows \"d = c\"\nproof (rule ccontr)\n  assume \"d \\<noteq> c\"\n  from t1_space[OF this] obtain U where \"open U\" \"d \\<in> U\" \"c \\<notin> U\"\n    by blast\n  with assms have \"eventually (\\<lambda>x. f x \\<in> U) F\"\n    unfolding tendsto_def by blast\n  then have \"eventually (\\<lambda>x. f x \\<noteq> c) F\"\n    by eventually_elim (insert \\<open>c \\<notin> U\\<close>, blast)\n  with assms(2) show False\n    unfolding frequently_def by contradiction\nqed\n\nlemma (in t1_space) tendsto_imp_eventually_ne:\n  assumes  \"(f \\<longlongrightarrow> c) F\" \"c \\<noteq> c'\"\n  shows \"eventually (\\<lambda>z. f z \\<noteq> c') F\"\nproof (cases \"F=bot\")\n  case True\n  thus ?thesis by auto\nnext\n  case False\n  show ?thesis\n  proof (rule ccontr)\n    assume \"\\<not> eventually (\\<lambda>z. f z \\<noteq> c') F\"\n    then have \"frequently (\\<lambda>z. f z = c') F\"\n      by (simp add: frequently_def)\n    from limit_frequently_eq[OF False this \\<open>(f \\<longlongrightarrow> c) F\\<close>] and \\<open>c \\<noteq> c'\\<close> show False\n      by contradiction\n  qed\nqed\n\nlemma (in linorder_topology) tendsto_le:\n  assumes F: \"\\<not> trivial_limit F\"\n    and x: \"(f \\<longlongrightarrow> x) F\"\n    and y: \"(g \\<longlongrightarrow> y) F\"\n    and ev: \"eventually (\\<lambda>x. g x \\<le> f x) F\"\n  shows \"y \\<le> x\"\nproof (rule ccontr)\n  assume \"\\<not> y \\<le> x\"\n  with less_separate[of x y] obtain a b where xy: \"x < a\" \"b < y\" \"{..<a} \\<inter> {b<..} = {}\"\n    by (auto simp: not_le)\n  then have \"eventually (\\<lambda>x. f x < a) F\" \"eventually (\\<lambda>x. b < g x) F\"\n    using x y by (auto intro: order_tendstoD)\n  with ev have \"eventually (\\<lambda>x. False) F\"\n    by eventually_elim (insert xy, fastforce)\n  with F show False\n    by (simp add: eventually_False)\nqed\n\nlemma (in linorder_topology) tendsto_lowerbound:\n  assumes x: \"(f \\<longlongrightarrow> x) F\"\n      and ev: \"eventually (\\<lambda>i. a \\<le> f i) F\"\n      and F: \"\\<not> trivial_limit F\"\n  shows \"a \\<le> x\"\n  using F x tendsto_const ev by (rule tendsto_le)\n\nlemma (in linorder_topology) tendsto_upperbound:\n  assumes x: \"(f \\<longlongrightarrow> x) F\"\n      and ev: \"eventually (\\<lambda>i. a \\<ge> f i) F\"\n      and F: \"\\<not> trivial_limit F\"\n  shows \"a \\<ge> x\"\n  by (rule tendsto_le [OF F tendsto_const x ev])\n\nlemma filterlim_at_within_not_equal:\n  fixes f::\"'a \\<Rightarrow> 'b::t2_space\"\n  assumes \"filterlim f (at a within s) F\"\n  shows \"eventually (\\<lambda>w. f w\\<in>s \\<and> f w \\<noteq>b) F\"\nproof (cases \"a=b\")\n  case True\n  then show ?thesis using assms by (simp add: filterlim_at)\nnext\n  case False\n  from hausdorff[OF this] obtain U V where UV:\"open U\" \"open V\" \"a \\<in> U\" \"b \\<in> V\" \"U \\<inter> V = {}\"\n    by auto  \n  have \"(f \\<longlongrightarrow> a) F\" using assms filterlim_at by auto\n  then have \"\\<forall>\\<^sub>F x in F. f x \\<in> U\" using UV unfolding tendsto_def by auto\n  moreover have  \"\\<forall>\\<^sub>F x in F. f x \\<in> s \\<and> f x\\<noteq>a\" using assms filterlim_at by auto\n  ultimately show ?thesis \n    apply eventually_elim\n    using UV by auto\nqed\n\nsubsubsection \\<open>Rules about \\<^const>\\<open>Lim\\<close>\\<close>\n\nlemma tendsto_Lim: \"\\<not> trivial_limit net \\<Longrightarrow> (f \\<longlongrightarrow> l) net \\<Longrightarrow> Lim net f = l\"\n  unfolding Lim_def using tendsto_unique [of net f] by auto\n\nlemma Lim_ident_at: \"\\<not> trivial_limit (at x within s) \\<Longrightarrow> Lim (at x within s) (\\<lambda>x. x) = x\"\n  by (rule tendsto_Lim[OF _ tendsto_ident_at]) auto\n\nlemma Lim_cong:\n  assumes \"eventually (\\<lambda>x. f x = g x) F\" \"F = G\"\n  shows   \"Lim F f = Lim G g\"\nproof (cases \"(\\<exists>c. (f \\<longlongrightarrow> c) F) \\<and> F \\<noteq> bot\")\n  case True\n  then obtain c where c: \"(f \\<longlongrightarrow> c) F\"\n    by blast\n  hence \"Lim F f = c\"\n    using True by (intro tendsto_Lim) auto\n  moreover have \"(f \\<longlongrightarrow> c) F \\<longleftrightarrow> (g \\<longlongrightarrow> c) G\"\n    using assms by (intro filterlim_cong) auto\n  with True c assms have \"Lim G g = c\"\n    by (intro tendsto_Lim) auto\n  ultimately show ?thesis\n    by simp\nnext\n  case False\n  show ?thesis\n  proof (cases \"F = bot\")\n    case True\n    thus ?thesis using assms\n      by (auto simp: Topological_Spaces.Lim_def)\n  next\n    case False\n    have \"(f \\<longlongrightarrow> c) F \\<longleftrightarrow> (g \\<longlongrightarrow> c) G\" for c\n      using assms by (intro filterlim_cong) auto\n    thus ?thesis\n      by (auto simp: Topological_Spaces.Lim_def)\n  qed\nqed\n\nlemma eventually_Lim_ident_at:\n  \"(\\<forall>\\<^sub>F y in at x within X. P (Lim (at x within X) (\\<lambda>x. x)) y) \\<longleftrightarrow>\n    (\\<forall>\\<^sub>F y in at x within X. P x y)\" for x::\"'a::t2_space\"\n  by (cases \"at x within X = bot\") (auto simp: Lim_ident_at)\n\nlemma filterlim_at_bot_at_right:\n  fixes f :: \"'a::linorder_topology \\<Rightarrow> 'b::linorder\"\n  assumes mono: \"\\<And>x y. Q x \\<Longrightarrow> Q y \\<Longrightarrow> x \\<le> y \\<Longrightarrow> f x \\<le> f y\"\n    and bij: \"\\<And>x. P x \\<Longrightarrow> f (g x) = x\" \"\\<And>x. P x \\<Longrightarrow> Q (g x)\"\n    and Q: \"eventually Q (at_right a)\"\n    and bound: \"\\<And>b. Q b \\<Longrightarrow> a < b\"\n    and P: \"eventually P at_bot\"\n  shows \"filterlim f at_bot (at_right a)\"\nproof -\n  from P obtain x where x: \"\\<And>y. y \\<le> x \\<Longrightarrow> P y\"\n    unfolding eventually_at_bot_linorder by auto\n  show ?thesis\n  proof (intro filterlim_at_bot_le[THEN iffD2] allI impI)\n    fix z\n    assume \"z \\<le> x\"\n    with x have \"P z\" by auto\n    have \"eventually (\\<lambda>x. x \\<le> g z) (at_right a)\"\n      using bound[OF bij(2)[OF \\<open>P z\\<close>]]\n      unfolding eventually_at_right[OF bound[OF bij(2)[OF \\<open>P z\\<close>]]]\n      by (auto intro!: exI[of _ \"g z\"])\n    with Q show \"eventually (\\<lambda>x. f x \\<le> z) (at_right a)\"\n      by eventually_elim (metis bij \\<open>P z\\<close> mono)\n  qed\nqed\n\nlemma filterlim_at_top_at_left:\n  fixes f :: \"'a::linorder_topology \\<Rightarrow> 'b::linorder\"\n  assumes mono: \"\\<And>x y. Q x \\<Longrightarrow> Q y \\<Longrightarrow> x \\<le> y \\<Longrightarrow> f x \\<le> f y\"\n    and bij: \"\\<And>x. P x \\<Longrightarrow> f (g x) = x\" \"\\<And>x. P x \\<Longrightarrow> Q (g x)\"\n    and Q: \"eventually Q (at_left a)\"\n    and bound: \"\\<And>b. Q b \\<Longrightarrow> b < a\"\n    and P: \"eventually P at_top\"\n  shows \"filterlim f at_top (at_left a)\"\nproof -\n  from P obtain x where x: \"\\<And>y. x \\<le> y \\<Longrightarrow> P y\"\n    unfolding eventually_at_top_linorder by auto\n  show ?thesis\n  proof (intro filterlim_at_top_ge[THEN iffD2] allI impI)\n    fix z\n    assume \"x \\<le> z\"\n    with x have \"P z\" by auto\n    have \"eventually (\\<lambda>x. g z \\<le> x) (at_left a)\"\n      using bound[OF bij(2)[OF \\<open>P z\\<close>]]\n      unfolding eventually_at_left[OF bound[OF bij(2)[OF \\<open>P z\\<close>]]]\n      by (auto intro!: exI[of _ \"g z\"])\n    with Q show \"eventually (\\<lambda>x. z \\<le> f x) (at_left a)\"\n      by eventually_elim (metis bij \\<open>P z\\<close> mono)\n  qed\nqed\n\nlemma filterlim_split_at:\n  \"filterlim f F (at_left x) \\<Longrightarrow> filterlim f F (at_right x) \\<Longrightarrow>\n    filterlim f F (at x)\"\n  for x :: \"'a::linorder_topology\"\n  by (subst at_eq_sup_left_right) (rule filterlim_sup)\n\nlemma filterlim_at_split:\n  \"filterlim f F (at x) \\<longleftrightarrow> filterlim f F (at_left x) \\<and> filterlim f F (at_right x)\"\n  for x :: \"'a::linorder_topology\"\n  by (subst at_eq_sup_left_right) (simp add: filterlim_def filtermap_sup)\n\nlemma eventually_nhds_top:\n  fixes P :: \"'a :: {order_top,linorder_topology} \\<Rightarrow> bool\"\n    and b :: 'a\n  assumes \"b < top\"\n  shows \"eventually P (nhds top) \\<longleftrightarrow> (\\<exists>b<top. (\\<forall>z. b < z \\<longrightarrow> P z))\"\n  unfolding eventually_nhds\nproof safe\n  fix S :: \"'a set\"\n  assume \"open S\" \"top \\<in> S\"\n  note open_left[OF this \\<open>b < top\\<close>]\n  moreover assume \"\\<forall>s\\<in>S. P s\"\n  ultimately show \"\\<exists>b<top. \\<forall>z>b. P z\"\n    by (auto simp: subset_eq Ball_def)\nnext\n  fix b\n  assume \"b < top\" \"\\<forall>z>b. P z\"\n  then show \"\\<exists>S. open S \\<and> top \\<in> S \\<and> (\\<forall>xa\\<in>S. P xa)\"\n    by (intro exI[of _ \"{b <..}\"]) auto\nqed\n\nlemma tendsto_at_within_iff_tendsto_nhds:\n  \"(g \\<longlongrightarrow> g l) (at l within S) \\<longleftrightarrow> (g \\<longlongrightarrow> g l) (inf (nhds l) (principal S))\"\n  unfolding tendsto_def eventually_at_filter eventually_inf_principal\n  by (intro ext all_cong imp_cong) (auto elim!: eventually_mono)\n\n\nsubsection \\<open>Limits on sequences\\<close>\n\nabbreviation (in topological_space)\n  LIMSEQ :: \"[nat \\<Rightarrow> 'a, 'a] \\<Rightarrow> bool\"  (\"((_)/ \\<longlonglongrightarrow> (_))\" [60, 60] 60)\n  where \"X \\<longlonglongrightarrow> L \\<equiv> (X \\<longlongrightarrow> L) sequentially\"\n\nabbreviation (in t2_space) lim :: \"(nat \\<Rightarrow> 'a) \\<Rightarrow> 'a\"\n  where \"lim X \\<equiv> Lim sequentially X\"\n\ndefinition (in topological_space) convergent :: \"(nat \\<Rightarrow> 'a) \\<Rightarrow> bool\"\n  where \"convergent X = (\\<exists>L. X \\<longlonglongrightarrow> L)\"\n\nlemma lim_def: \"lim X = (THE L. X \\<longlonglongrightarrow> L)\"\n  unfolding Lim_def ..\n\nlemma lim_explicit:\n  \"f \\<longlonglongrightarrow> f0 \\<longleftrightarrow> (\\<forall>S. open S \\<longrightarrow> f0 \\<in> S \\<longrightarrow> (\\<exists>N. \\<forall>n\\<ge>N. f n \\<in> S))\"\n  unfolding tendsto_def eventually_sequentially by auto\n\n\nsubsection \\<open>Monotone sequences and subsequences\\<close>\n\ntext \\<open>\n  Definition of monotonicity.\n  The use of disjunction here complicates proofs considerably.\n  One alternative is to add a Boolean argument to indicate the direction.\n  Another is to develop the notions of increasing and decreasing first.\n\\<close>\ndefinition monoseq :: \"(nat \\<Rightarrow> 'a::order) \\<Rightarrow> bool\"\n  where \"monoseq X \\<longleftrightarrow> (\\<forall>m. \\<forall>n\\<ge>m. X m \\<le> X n) \\<or> (\\<forall>m. \\<forall>n\\<ge>m. X n \\<le> X m)\"\n\nabbreviation incseq :: \"(nat \\<Rightarrow> 'a::order) \\<Rightarrow> bool\"\n  where \"incseq X \\<equiv> mono X\"\n\nlemma incseq_def: \"incseq X \\<longleftrightarrow> (\\<forall>m. \\<forall>n\\<ge>m. X n \\<ge> X m)\"\n  unfolding mono_def ..\n\nabbreviation decseq :: \"(nat \\<Rightarrow> 'a::order) \\<Rightarrow> bool\"\n  where \"decseq X \\<equiv> antimono X\"\n\nlemma decseq_def: \"decseq X \\<longleftrightarrow> (\\<forall>m. \\<forall>n\\<ge>m. X n \\<le> X m)\"\n  unfolding antimono_def ..\n\nsubsubsection \\<open>Definition of subsequence.\\<close>\n\n(* For compatibility with the old \"subseq\" *)\nlemma strict_mono_leD: \"strict_mono r \\<Longrightarrow> m \\<le> n \\<Longrightarrow> r m \\<le> r n\"\n  by (erule (1) monoD [OF strict_mono_mono])\n\nlemma strict_mono_id: \"strict_mono id\"\n  by (simp add: strict_mono_def)\n\nlemma incseq_SucI: \"(\\<And>n. X n \\<le> X (Suc n)) \\<Longrightarrow> incseq X\"\n  using lift_Suc_mono_le[of X] by (auto simp: incseq_def)\n\nlemma incseqD: \"incseq f \\<Longrightarrow> i \\<le> j \\<Longrightarrow> f i \\<le> f j\"\n  by (auto simp: incseq_def)\n\nlemma incseq_SucD: \"incseq A \\<Longrightarrow> A i \\<le> A (Suc i)\"\n  using incseqD[of A i \"Suc i\"] by auto\n\nlemma incseq_Suc_iff: \"incseq f \\<longleftrightarrow> (\\<forall>n. f n \\<le> f (Suc n))\"\n  by (auto intro: incseq_SucI dest: incseq_SucD)\n\nlemma incseq_const[simp, intro]: \"incseq (\\<lambda>x. k)\"\n  unfolding incseq_def by auto\n\nlemma decseq_SucI: \"(\\<And>n. X (Suc n) \\<le> X n) \\<Longrightarrow> decseq X\"\n  using order.lift_Suc_mono_le[OF dual_order, of X] by (auto simp: decseq_def)\n\nlemma decseqD: \"decseq f \\<Longrightarrow> i \\<le> j \\<Longrightarrow> f j \\<le> f i\"\n  by (auto simp: decseq_def)\n\nlemma decseq_SucD: \"decseq A \\<Longrightarrow> A (Suc i) \\<le> A i\"\n  using decseqD[of A i \"Suc i\"] by auto\n\nlemma decseq_Suc_iff: \"decseq f \\<longleftrightarrow> (\\<forall>n. f (Suc n) \\<le> f n)\"\n  by (auto intro: decseq_SucI dest: decseq_SucD)\n\nlemma decseq_const[simp, intro]: \"decseq (\\<lambda>x. k)\"\n  unfolding decseq_def by auto\n\nlemma monoseq_iff: \"monoseq X \\<longleftrightarrow> incseq X \\<or> decseq X\"\n  unfolding monoseq_def incseq_def decseq_def ..\n\nlemma monoseq_Suc: \"monoseq X \\<longleftrightarrow> (\\<forall>n. X n \\<le> X (Suc n)) \\<or> (\\<forall>n. X (Suc n) \\<le> X n)\"\n  unfolding monoseq_iff incseq_Suc_iff decseq_Suc_iff ..\n\nlemma monoI1: \"\\<forall>m. \\<forall>n \\<ge> m. X m \\<le> X n \\<Longrightarrow> monoseq X\"\n  by (simp add: monoseq_def)\n\nlemma monoI2: \"\\<forall>m. \\<forall>n \\<ge> m. X n \\<le> X m \\<Longrightarrow> monoseq X\"\n  by (simp add: monoseq_def)\n\nlemma mono_SucI1: \"\\<forall>n. X n \\<le> X (Suc n) \\<Longrightarrow> monoseq X\"\n  by (simp add: monoseq_Suc)\n\nlemma mono_SucI2: \"\\<forall>n. X (Suc n) \\<le> X n \\<Longrightarrow> monoseq X\"\n  by (simp add: monoseq_Suc)\n\nlemma monoseq_minus:\n  fixes a :: \"nat \\<Rightarrow> 'a::ordered_ab_group_add\"\n  assumes \"monoseq a\"\n  shows \"monoseq (\\<lambda> n. - a n)\"\nproof (cases \"\\<forall>m. \\<forall>n \\<ge> m. a m \\<le> a n\")\n  case True\n  then have \"\\<forall>m. \\<forall>n \\<ge> m. - a n \\<le> - a m\" by auto\n  then show ?thesis by (rule monoI2)\nnext\n  case False\n  then have \"\\<forall>m. \\<forall>n \\<ge> m. - a m \\<le> - a n\"\n    using \\<open>monoseq a\\<close>[unfolded monoseq_def] by auto\n  then show ?thesis by (rule monoI1)\nqed\n\n\nsubsubsection \\<open>Subsequence (alternative definition, (e.g. Hoskins)\\<close>\n\nlemma strict_mono_Suc_iff: \"strict_mono f \\<longleftrightarrow> (\\<forall>n. f n < f (Suc n))\"\nproof (intro iffI strict_monoI)\n  assume *: \"\\<forall>n. f n < f (Suc n)\"\n  fix m n :: nat assume \"m < n\"\n  thus \"f m < f n\"\n    by (induction rule: less_Suc_induct) (use * in auto)\nqed (auto simp: strict_mono_def)\n\nlemma strict_mono_add: \"strict_mono (\\<lambda>n::'a::linordered_semidom. n + k)\"\n  by (auto simp: strict_mono_def)\n\ntext \\<open>For any sequence, there is a monotonic subsequence.\\<close>\nlemma seq_monosub:\n  fixes s :: \"nat \\<Rightarrow> 'a::linorder\"\n  shows \"\\<exists>f. strict_mono f \\<and> monoseq (\\<lambda>n. (s (f n)))\"\nproof (cases \"\\<forall>n. \\<exists>p>n. \\<forall>m\\<ge>p. s m \\<le> s p\")\n  case True\n  then have \"\\<exists>f. \\<forall>n. (\\<forall>m\\<ge>f n. s m \\<le> s (f n)) \\<and> f n < f (Suc n)\"\n    by (intro dependent_nat_choice) (auto simp: conj_commute)\n  then obtain f :: \"nat \\<Rightarrow> nat\" \n    where f: \"strict_mono f\" and mono: \"\\<And>n m. f n \\<le> m \\<Longrightarrow> s m \\<le> s (f n)\"\n    by (auto simp: strict_mono_Suc_iff)\n  then have \"incseq f\"\n    unfolding strict_mono_Suc_iff incseq_Suc_iff by (auto intro: less_imp_le)\n  then have \"monoseq (\\<lambda>n. s (f n))\"\n    by (auto simp add: incseq_def intro!: mono monoI2)\n  with f show ?thesis\n    by auto\nnext\n  case False\n  then obtain N where N: \"p > N \\<Longrightarrow> \\<exists>m>p. s p < s m\" for p\n    by (force simp: not_le le_less)\n  have \"\\<exists>f. \\<forall>n. N < f n \\<and> f n < f (Suc n) \\<and> s (f n) \\<le> s (f (Suc n))\"\n  proof (intro dependent_nat_choice)\n    fix x\n    assume \"N < x\" with N[of x]\n    show \"\\<exists>y>N. x < y \\<and> s x \\<le> s y\"\n      by (auto intro: less_trans)\n  qed auto\n  then show ?thesis\n    by (auto simp: monoseq_iff incseq_Suc_iff strict_mono_Suc_iff)\nqed\n\nlemma seq_suble:\n  assumes sf: \"strict_mono (f :: nat \\<Rightarrow> nat)\"\n  shows \"n \\<le> f n\"\nproof (induct n)\n  case 0\n  show ?case by simp\nnext\n  case (Suc n)\n  with sf [unfolded strict_mono_Suc_iff, rule_format, of n] have \"n < f (Suc n)\"\n     by arith\n  then show ?case by arith\nqed\n\nlemma eventually_subseq:\n  \"strict_mono r \\<Longrightarrow> eventually P sequentially \\<Longrightarrow> eventually (\\<lambda>n. P (r n)) sequentially\"\n  unfolding eventually_sequentially by (metis seq_suble le_trans)\n\nlemma not_eventually_sequentiallyD:\n  assumes \"\\<not> eventually P sequentially\"\n  shows \"\\<exists>r::nat\\<Rightarrow>nat. strict_mono r \\<and> (\\<forall>n. \\<not> P (r n))\"\nproof -\n  from assms have \"\\<forall>n. \\<exists>m\\<ge>n. \\<not> P m\"\n    unfolding eventually_sequentially by (simp add: not_less)\n  then obtain r where \"\\<And>n. r n \\<ge> n\" \"\\<And>n. \\<not> P (r n)\"\n    by (auto simp: choice_iff)\n  then show ?thesis\n    by (auto intro!: exI[of _ \"\\<lambda>n. r (((Suc \\<circ> r) ^^ Suc n) 0)\"]\n             simp: less_eq_Suc_le strict_mono_Suc_iff)\nqed\n\nlemma sequentially_offset: \n  assumes \"eventually (\\<lambda>i. P i) sequentially\"\n  shows \"eventually (\\<lambda>i. P (i + k)) sequentially\"\n  using assms by (rule eventually_sequentially_seg [THEN iffD2])\n\nlemma seq_offset_neg: \n  \"(f \\<longlongrightarrow> l) sequentially \\<Longrightarrow> ((\\<lambda>i. f(i - k)) \\<longlongrightarrow> l) sequentially\"\n  apply (erule filterlim_compose)\n  apply (simp add: filterlim_def le_sequentially eventually_filtermap eventually_sequentially, arith)\n  done\n\nlemma filterlim_subseq: \"strict_mono f \\<Longrightarrow> filterlim f sequentially sequentially\"\n  unfolding filterlim_iff by (metis eventually_subseq)\n\nlemma strict_mono_o: \"strict_mono r \\<Longrightarrow> strict_mono s \\<Longrightarrow> strict_mono (r \\<circ> s)\"\n  unfolding strict_mono_def by simp\n\nlemma strict_mono_compose: \"strict_mono r \\<Longrightarrow> strict_mono s \\<Longrightarrow> strict_mono (\\<lambda>x. r (s x))\"\n  using strict_mono_o[of r s] by (simp add: o_def)\n\nlemma incseq_imp_monoseq:  \"incseq X \\<Longrightarrow> monoseq X\"\n  by (simp add: incseq_def monoseq_def)\n\nlemma decseq_imp_monoseq:  \"decseq X \\<Longrightarrow> monoseq X\"\n  by (simp add: decseq_def monoseq_def)\n\nlemma decseq_eq_incseq: \"decseq X = incseq (\\<lambda>n. - X n)\"\n  for X :: \"nat \\<Rightarrow> 'a::ordered_ab_group_add\"\n  by (simp add: decseq_def incseq_def)\n\nlemma INT_decseq_offset:\n  assumes \"decseq F\"\n  shows \"(\\<Inter>i. F i) = (\\<Inter>i\\<in>{n..}. F i)\"\nproof safe\n  fix x i\n  assume x: \"x \\<in> (\\<Inter>i\\<in>{n..}. F i)\"\n  show \"x \\<in> F i\"\n  proof cases\n    from x have \"x \\<in> F n\" by auto\n    also assume \"i \\<le> n\" with \\<open>decseq F\\<close> have \"F n \\<subseteq> F i\"\n      unfolding decseq_def by simp\n    finally show ?thesis .\n  qed (insert x, simp)\nqed auto\n\nlemma LIMSEQ_const_iff: \"(\\<lambda>n. k) \\<longlonglongrightarrow> l \\<longleftrightarrow> k = l\"\n  for k l :: \"'a::t2_space\"\n  using trivial_limit_sequentially by (rule tendsto_const_iff)\n\nlemma LIMSEQ_SUP: \"incseq X \\<Longrightarrow> X \\<longlonglongrightarrow> (SUP i. X i :: 'a::{complete_linorder,linorder_topology})\"\n  by (intro increasing_tendsto)\n    (auto simp: SUP_upper less_SUP_iff incseq_def eventually_sequentially intro: less_le_trans)\n\nlemma LIMSEQ_INF: \"decseq X \\<Longrightarrow> X \\<longlonglongrightarrow> (INF i. X i :: 'a::{complete_linorder,linorder_topology})\"\n  by (intro decreasing_tendsto)\n    (auto simp: INF_lower INF_less_iff decseq_def eventually_sequentially intro: le_less_trans)\n\nlemma LIMSEQ_ignore_initial_segment: \"f \\<longlonglongrightarrow> a \\<Longrightarrow> (\\<lambda>n. f (n + k)) \\<longlonglongrightarrow> a\"\n  unfolding tendsto_def by (subst eventually_sequentially_seg[where k=k])\n\nlemma LIMSEQ_offset: \"(\\<lambda>n. f (n + k)) \\<longlonglongrightarrow> a \\<Longrightarrow> f \\<longlonglongrightarrow> a\"\n  unfolding tendsto_def\n  by (subst (asm) eventually_sequentially_seg[where k=k])\n\nlemma LIMSEQ_Suc: \"f \\<longlonglongrightarrow> l \\<Longrightarrow> (\\<lambda>n. f (Suc n)) \\<longlonglongrightarrow> l\"\n  by (drule LIMSEQ_ignore_initial_segment [where k=\"Suc 0\"]) simp\n\nlemma LIMSEQ_imp_Suc: \"(\\<lambda>n. f (Suc n)) \\<longlonglongrightarrow> l \\<Longrightarrow> f \\<longlonglongrightarrow> l\"\n  by (rule LIMSEQ_offset [where k=\"Suc 0\"]) simp\n\nlemma LIMSEQ_lessThan_iff_atMost:\n  shows \"(\\<lambda>n. f {..<n}) \\<longlonglongrightarrow> x \\<longleftrightarrow> (\\<lambda>n. f {..n}) \\<longlonglongrightarrow> x\"\n  apply (subst filterlim_sequentially_Suc [symmetric])\n  apply (simp only: lessThan_Suc_atMost)\n  done\n\nlemma (in t2_space) LIMSEQ_Uniq: \"\\<exists>\\<^sub>\\<le>\\<^sub>1l. X \\<longlonglongrightarrow> l\"\n by (simp add: tendsto_unique')\n\nlemma (in t2_space) LIMSEQ_unique: \"X \\<longlonglongrightarrow> a \\<Longrightarrow> X \\<longlonglongrightarrow> b \\<Longrightarrow> a = b\"\n  using trivial_limit_sequentially by (rule tendsto_unique)\n\nlemma LIMSEQ_le_const: \"X \\<longlonglongrightarrow> x \\<Longrightarrow> \\<exists>N. \\<forall>n\\<ge>N. a \\<le> X n \\<Longrightarrow> a \\<le> x\"\n  for a x :: \"'a::linorder_topology\"\n  by (simp add: eventually_at_top_linorder tendsto_lowerbound)\n\nlemma LIMSEQ_le: \"X \\<longlonglongrightarrow> x \\<Longrightarrow> Y \\<longlonglongrightarrow> y \\<Longrightarrow> \\<exists>N. \\<forall>n\\<ge>N. X n \\<le> Y n \\<Longrightarrow> x \\<le> y\"\n  for x y :: \"'a::linorder_topology\"\n  using tendsto_le[of sequentially Y y X x] by (simp add: eventually_sequentially)\n\nlemma LIMSEQ_le_const2: \"X \\<longlonglongrightarrow> x \\<Longrightarrow> \\<exists>N. \\<forall>n\\<ge>N. X n \\<le> a \\<Longrightarrow> x \\<le> a\"\n  for a x :: \"'a::linorder_topology\"\n  by (rule LIMSEQ_le[of X x \"\\<lambda>n. a\"]) auto\n\nlemma Lim_bounded: \"f \\<longlonglongrightarrow> l \\<Longrightarrow> \\<forall>n\\<ge>M. f n \\<le> C \\<Longrightarrow> l \\<le> C\"\n  for l :: \"'a::linorder_topology\"\n  by (intro LIMSEQ_le_const2) auto\n\nlemma Lim_bounded2:\n  fixes f :: \"nat \\<Rightarrow> 'a::linorder_topology\"\n  assumes lim:\"f \\<longlonglongrightarrow> l\" and ge: \"\\<forall>n\\<ge>N. f n \\<ge> C\"\n  shows \"l \\<ge> C\"\n  using ge\n  by (intro tendsto_le[OF trivial_limit_sequentially lim tendsto_const])\n     (auto simp: eventually_sequentially)\n\nlemma lim_mono:\n  fixes X Y :: \"nat \\<Rightarrow> 'a::linorder_topology\"\n  assumes \"\\<And>n. N \\<le> n \\<Longrightarrow> X n \\<le> Y n\"\n    and \"X \\<longlonglongrightarrow> x\"\n    and \"Y \\<longlonglongrightarrow> y\"\n  shows \"x \\<le> y\"\n  using assms(1) by (intro LIMSEQ_le[OF assms(2,3)]) auto\n\nlemma Sup_lim:\n  fixes a :: \"'a::{complete_linorder,linorder_topology}\"\n  assumes \"\\<And>n. b n \\<in> s\"\n    and \"b \\<longlonglongrightarrow> a\"\n  shows \"a \\<le> Sup s\"\n  by (metis Lim_bounded assms complete_lattice_class.Sup_upper)\n\nlemma Inf_lim:\n  fixes a :: \"'a::{complete_linorder,linorder_topology}\"\n  assumes \"\\<And>n. b n \\<in> s\"\n    and \"b \\<longlonglongrightarrow> a\"\n  shows \"Inf s \\<le> a\"\n  by (metis Lim_bounded2 assms complete_lattice_class.Inf_lower)\n\nlemma SUP_Lim:\n  fixes X :: \"nat \\<Rightarrow> 'a::{complete_linorder,linorder_topology}\"\n  assumes inc: \"incseq X\"\n    and l: \"X \\<longlonglongrightarrow> l\"\n  shows \"(SUP n. X n) = l\"\n  using LIMSEQ_SUP[OF inc] tendsto_unique[OF trivial_limit_sequentially l]\n  by simp\n\nlemma INF_Lim:\n  fixes X :: \"nat \\<Rightarrow> 'a::{complete_linorder,linorder_topology}\"\n  assumes dec: \"decseq X\"\n    and l: \"X \\<longlonglongrightarrow> l\"\n  shows \"(INF n. X n) = l\"\n  using LIMSEQ_INF[OF dec] tendsto_unique[OF trivial_limit_sequentially l]\n  by simp\n\nlemma convergentD: \"convergent X \\<Longrightarrow> \\<exists>L. X \\<longlonglongrightarrow> L\"\n  by (simp add: convergent_def)\n\nlemma convergentI: \"X \\<longlonglongrightarrow> L \\<Longrightarrow> convergent X\"\n  by (auto simp add: convergent_def)\n\nlemma convergent_LIMSEQ_iff: \"convergent X \\<longleftrightarrow> X \\<longlonglongrightarrow> lim X\"\n  by (auto intro: theI LIMSEQ_unique simp add: convergent_def lim_def)\n\nlemma convergent_const: \"convergent (\\<lambda>n. c)\"\n  by (rule convergentI) (rule tendsto_const)\n\nlemma monoseq_le:\n  \"monoseq a \\<Longrightarrow> a \\<longlonglongrightarrow> x \\<Longrightarrow>\n    (\\<forall>n. a n \\<le> x) \\<and> (\\<forall>m. \\<forall>n\\<ge>m. a m \\<le> a n) \\<or>\n    (\\<forall>n. x \\<le> a n) \\<and> (\\<forall>m. \\<forall>n\\<ge>m. a n \\<le> a m)\"\n  for x :: \"'a::linorder_topology\"\n  by (metis LIMSEQ_le_const LIMSEQ_le_const2 decseq_def incseq_def monoseq_iff)\n\nlemma LIMSEQ_subseq_LIMSEQ: \"X \\<longlonglongrightarrow> L \\<Longrightarrow> strict_mono f \\<Longrightarrow> (X \\<circ> f) \\<longlonglongrightarrow> L\"\n  unfolding comp_def by (rule filterlim_compose [of X, OF _ filterlim_subseq])\n\nlemma convergent_subseq_convergent: \"convergent X \\<Longrightarrow> strict_mono f \\<Longrightarrow> convergent (X \\<circ> f)\"\n  by (auto simp: convergent_def intro: LIMSEQ_subseq_LIMSEQ)\n\nlemma limI: \"X \\<longlonglongrightarrow> L \\<Longrightarrow> lim X = L\"\n  by (rule tendsto_Lim) (rule trivial_limit_sequentially)\n\nlemma lim_le: \"convergent f \\<Longrightarrow> (\\<And>n. f n \\<le> x) \\<Longrightarrow> lim f \\<le> x\"\n  for x :: \"'a::linorder_topology\"\n  using LIMSEQ_le_const2[of f \"lim f\" x] by (simp add: convergent_LIMSEQ_iff)\n\nlemma lim_const [simp]: \"lim (\\<lambda>m. a) = a\"\n  by (simp add: limI)\n\n\nsubsubsection \\<open>Increasing and Decreasing Series\\<close>\n\nlemma incseq_le: \"incseq X \\<Longrightarrow> X \\<longlonglongrightarrow> L \\<Longrightarrow> X n \\<le> L\"\n  for L :: \"'a::linorder_topology\"\n  by (metis incseq_def LIMSEQ_le_const)\n\nlemma decseq_ge: \"decseq X \\<Longrightarrow> X \\<longlonglongrightarrow> L \\<Longrightarrow> L \\<le> X n\"\n  for L :: \"'a::linorder_topology\"\n  by (metis decseq_def LIMSEQ_le_const2)\n\n\nsubsection \\<open>First countable topologies\\<close>\n\nclass first_countable_topology = topological_space +\n  assumes first_countable_basis:\n    \"\\<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))\"\n\nlemma (in first_countable_topology) countable_basis_at_decseq:\n  obtains A :: \"nat \\<Rightarrow> 'a set\" where\n    \"\\<And>i. open (A i)\" \"\\<And>i. x \\<in> (A i)\"\n    \"\\<And>S. open S \\<Longrightarrow> x \\<in> S \\<Longrightarrow> eventually (\\<lambda>i. A i \\<subseteq> S) sequentially\"\nproof atomize_elim\n  from first_countable_basis[of x] obtain A :: \"nat \\<Rightarrow> 'a set\"\n    where nhds: \"\\<And>i. open (A i)\" \"\\<And>i. x \\<in> A i\"\n      and incl: \"\\<And>S. open S \\<Longrightarrow> x \\<in> S \\<Longrightarrow> \\<exists>i. A i \\<subseteq> S\"\n    by auto\n  define F where \"F n = (\\<Inter>i\\<le>n. A i)\" for n\n  show \"\\<exists>A. (\\<forall>i. open (A i)) \\<and> (\\<forall>i. x \\<in> A i) \\<and>\n    (\\<forall>S. open S \\<longrightarrow> x \\<in> S \\<longrightarrow> eventually (\\<lambda>i. A i \\<subseteq> S) sequentially)\"\n  proof (safe intro!: exI[of _ F])\n    fix i\n    show \"open (F i)\"\n      using nhds(1) by (auto simp: F_def)\n    show \"x \\<in> F i\"\n      using nhds(2) by (auto simp: F_def)\n  next\n    fix S\n    assume \"open S\" \"x \\<in> S\"\n    from incl[OF this] obtain i where \"F i \\<subseteq> S\"\n      unfolding F_def by auto\n    moreover have \"\\<And>j. i \\<le> j \\<Longrightarrow> F j \\<subseteq> F i\"\n      by (simp add: Inf_superset_mono F_def image_mono)\n    ultimately show \"eventually (\\<lambda>i. F i \\<subseteq> S) sequentially\"\n      by (auto simp: eventually_sequentially)\n  qed\nqed\n\nlemma (in first_countable_topology) nhds_countable:\n  obtains X :: \"nat \\<Rightarrow> 'a set\"\n  where \"decseq X\" \"\\<And>n. open (X n)\" \"\\<And>n. x \\<in> X n\" \"nhds x = (INF n. principal (X n))\"\nproof -\n  from first_countable_basis obtain A :: \"nat \\<Rightarrow> 'a set\"\n    where *: \"\\<And>n. x \\<in> A n\" \"\\<And>n. open (A n)\" \"\\<And>S. open S \\<Longrightarrow> x \\<in> S \\<Longrightarrow> \\<exists>i. A i \\<subseteq> S\"\n    by metis\n  show thesis\n  proof\n    show \"decseq (\\<lambda>n. \\<Inter>i\\<le>n. A i)\"\n      by (simp add: antimono_iff_le_Suc atMost_Suc)\n    show \"x \\<in> (\\<Inter>i\\<le>n. A i)\" \"\\<And>n. open (\\<Inter>i\\<le>n. A i)\" for n\n      using * by auto\n    with * show \"nhds x = (INF n. principal (\\<Inter>i\\<le>n. A i))\"\n      unfolding nhds_def\n      apply (intro INF_eq)\n       apply fastforce\n      apply blast\n      done\n  qed\nqed\n\nlemma (in first_countable_topology) countable_basis:\n  obtains A :: \"nat \\<Rightarrow> 'a set\" where\n    \"\\<And>i. open (A i)\" \"\\<And>i. x \\<in> A i\"\n    \"\\<And>F. (\\<forall>n. F n \\<in> A n) \\<Longrightarrow> F \\<longlonglongrightarrow> x\"\nproof atomize_elim\n  obtain A :: \"nat \\<Rightarrow> 'a set\" where *:\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 (rule countable_basis_at_decseq) blast\n  have \"eventually (\\<lambda>n. F n \\<in> S) sequentially\"\n    if \"\\<forall>n. F n \\<in> A n\" \"open S\" \"x \\<in> S\" for F S\n    using *(3)[of S] that by (auto elim: eventually_mono simp: subset_eq)\n  with * show \"\\<exists>A. (\\<forall>i. open (A i)) \\<and> (\\<forall>i. x \\<in> A i) \\<and> (\\<forall>F. (\\<forall>n. F n \\<in> A n) \\<longrightarrow> F \\<longlonglongrightarrow> x)\"\n    by (intro exI[of _ A]) (auto simp: tendsto_def)\nqed\n\nlemma (in first_countable_topology) sequentially_imp_eventually_nhds_within:\n  assumes \"\\<forall>f. (\\<forall>n. f n \\<in> s) \\<and> f \\<longlonglongrightarrow> a \\<longrightarrow> eventually (\\<lambda>n. P (f n)) sequentially\"\n  shows \"eventually P (inf (nhds a) (principal s))\"\nproof (rule ccontr)\n  obtain A :: \"nat \\<Rightarrow> 'a set\" where *:\n    \"\\<And>i. open (A i)\"\n    \"\\<And>i. a \\<in> A i\"\n    \"\\<And>F. \\<forall>n. F n \\<in> A n \\<Longrightarrow> F \\<longlonglongrightarrow> a\"\n    by (rule countable_basis) blast\n  assume \"\\<not> ?thesis\"\n  with * have \"\\<exists>F. \\<forall>n. F n \\<in> s \\<and> F n \\<in> A n \\<and> \\<not> P (F n)\"\n    unfolding eventually_inf_principal eventually_nhds\n    by (intro choice) fastforce\n  then obtain F where F: \"\\<forall>n. F n \\<in> s\" and \"\\<forall>n. F n \\<in> A n\" and F': \"\\<forall>n. \\<not> P (F n)\"\n    by blast\n  with * have \"F \\<longlonglongrightarrow> a\"\n    by auto\n  then have \"eventually (\\<lambda>n. P (F n)) sequentially\"\n    using assms F by simp\n  then show False\n    by (simp add: F')\nqed\n\nlemma (in first_countable_topology) eventually_nhds_within_iff_sequentially:\n  \"eventually P (inf (nhds a) (principal s)) \\<longleftrightarrow>\n    (\\<forall>f. (\\<forall>n. f n \\<in> s) \\<and> f \\<longlonglongrightarrow> a \\<longrightarrow> eventually (\\<lambda>n. P (f n)) sequentially)\"\nproof (safe intro!: sequentially_imp_eventually_nhds_within)\n  assume \"eventually P (inf (nhds a) (principal s))\"\n  then obtain S where \"open S\" \"a \\<in> S\" \"\\<forall>x\\<in>S. x \\<in> s \\<longrightarrow> P x\"\n    by (auto simp: eventually_inf_principal eventually_nhds)\n  moreover\n  fix f\n  assume \"\\<forall>n. f n \\<in> s\" \"f \\<longlonglongrightarrow> a\"\n  ultimately show \"eventually (\\<lambda>n. P (f n)) sequentially\"\n    by (auto dest!: topological_tendstoD elim: eventually_mono)\nqed\n\nlemma (in first_countable_topology) eventually_nhds_iff_sequentially:\n  \"eventually P (nhds a) \\<longleftrightarrow> (\\<forall>f. f \\<longlonglongrightarrow> a \\<longrightarrow> eventually (\\<lambda>n. P (f n)) sequentially)\"\n  using eventually_nhds_within_iff_sequentially[of P a UNIV] by simp\n\n(*Thanks to S\u00e9bastien Gou\u00ebzel*)\nlemma Inf_as_limit:\n  fixes A::\"'a::{linorder_topology, first_countable_topology, complete_linorder} set\"\n  assumes \"A \\<noteq> {}\"\n  shows \"\\<exists>u. (\\<forall>n. u n \\<in> A) \\<and> u \\<longlonglongrightarrow> Inf A\"\nproof (cases \"Inf A \\<in> A\")\n  case True\n  show ?thesis\n    by (rule exI[of _ \"\\<lambda>n. Inf A\"], auto simp add: True)\nnext\n  case False\n  obtain y where \"y \\<in> A\" using assms by auto\n  then have \"Inf A < y\" using False Inf_lower less_le by auto\n  obtain F :: \"nat \\<Rightarrow> 'a set\" where F: \"\\<And>i. open (F i)\" \"\\<And>i. Inf A \\<in> F i\"\n                                       \"\\<And>u. (\\<forall>n. u n \\<in> F n) \\<Longrightarrow> u \\<longlonglongrightarrow> Inf A\"\n    by (metis first_countable_topology_class.countable_basis)\n  define u where \"u = (\\<lambda>n. SOME z. z \\<in> F n \\<and> z \\<in> A)\"\n  have \"\\<exists>z. z \\<in> U \\<and> z \\<in> A\" if \"Inf A \\<in> U\" \"open U\" for U\n  proof -\n    obtain b where \"b > Inf A\" \"{Inf A ..<b} \\<subseteq> U\"\n      using open_right[OF \\<open>open U\\<close> \\<open>Inf A \\<in> U\\<close> \\<open>Inf A < y\\<close>] by auto\n    obtain z where \"z < b\" \"z \\<in> A\"\n      using \\<open>Inf A < b\\<close> Inf_less_iff by auto\n    then have \"z \\<in> {Inf A ..<b}\"\n      by (simp add: Inf_lower)\n    then show ?thesis using \\<open>z \\<in> A\\<close> \\<open>{Inf A ..<b} \\<subseteq> U\\<close> by auto\n  qed\n  then have *: \"u n \\<in> F n \\<and> u n \\<in> A\" for n\n    using \\<open>Inf A \\<in> F n\\<close> \\<open>open (F n)\\<close> unfolding u_def by (metis (no_types, lifting) someI_ex)\n  then have \"u \\<longlonglongrightarrow> Inf A\" using F(3) by simp\n  then show ?thesis using * by auto\nqed\n\nlemma tendsto_at_iff_sequentially:\n  \"(f \\<longlongrightarrow> a) (at x within s) \\<longleftrightarrow> (\\<forall>X. (\\<forall>i. X i \\<in> s - {x}) \\<longrightarrow> X \\<longlonglongrightarrow> x \\<longrightarrow> ((f \\<circ> X) \\<longlonglongrightarrow> a))\"\n  for f :: \"'a::first_countable_topology \\<Rightarrow> _\"\n  unfolding filterlim_def[of _ \"nhds a\"] le_filter_def eventually_filtermap\n    at_within_def eventually_nhds_within_iff_sequentially comp_def\n  by metis\n\nlemma approx_from_above_dense_linorder:\n  fixes x::\"'a::{dense_linorder, linorder_topology, first_countable_topology}\"\n  assumes \"x < y\"\n  shows \"\\<exists>u. (\\<forall>n. u n > x) \\<and> (u \\<longlonglongrightarrow> x)\"\nproof -\n  obtain A :: \"nat \\<Rightarrow> 'a set\" where A: \"\\<And>i. open (A i)\" \"\\<And>i. x \\<in> A i\"\n                                      \"\\<And>F. (\\<forall>n. F n \\<in> A n) \\<Longrightarrow> F \\<longlonglongrightarrow> x\"\n    by (metis first_countable_topology_class.countable_basis)\n  define u where \"u = (\\<lambda>n. SOME z. z \\<in> A n \\<and> z > x)\"\n  have \"\\<exists>z. z \\<in> U \\<and> x < z\" if \"x \\<in> U\" \"open U\" for U\n    using open_right[OF \\<open>open U\\<close> \\<open>x \\<in> U\\<close> \\<open>x < y\\<close>]\n    by (meson atLeastLessThan_iff dense less_imp_le subset_eq)\n  then have *: \"u n \\<in> A n \\<and> x < u n\" for n\n    using \\<open>x \\<in> A n\\<close> \\<open>open (A n)\\<close> unfolding u_def by (metis (no_types, lifting) someI_ex)\n  then have \"u \\<longlonglongrightarrow> x\" using A(3) by simp\n  then show ?thesis using * by auto\nqed\n\nlemma approx_from_below_dense_linorder:\n  fixes x::\"'a::{dense_linorder, linorder_topology, first_countable_topology}\"\n  assumes \"x > y\"\n  shows \"\\<exists>u. (\\<forall>n. u n < x) \\<and> (u \\<longlonglongrightarrow> x)\"\nproof -\n  obtain A :: \"nat \\<Rightarrow> 'a set\" where A: \"\\<And>i. open (A i)\" \"\\<And>i. x \\<in> A i\"\n                                      \"\\<And>F. (\\<forall>n. F n \\<in> A n) \\<Longrightarrow> F \\<longlonglongrightarrow> x\"\n    by (metis first_countable_topology_class.countable_basis)\n  define u where \"u = (\\<lambda>n. SOME z. z \\<in> A n \\<and> z < x)\"\n  have \"\\<exists>z. z \\<in> U \\<and> z < x\" if \"x \\<in> U\" \"open U\" for U\n    using open_left[OF \\<open>open U\\<close> \\<open>x \\<in> U\\<close> \\<open>x > y\\<close>]\n    by (meson dense greaterThanAtMost_iff less_imp_le subset_eq)\n  then have *: \"u n \\<in> A n \\<and> u n < x\" for n\n    using \\<open>x \\<in> A n\\<close> \\<open>open (A n)\\<close> unfolding u_def by (metis (no_types, lifting) someI_ex)\n  then have \"u \\<longlonglongrightarrow> x\" using A(3) by simp\n  then show ?thesis using * by auto\nqed\n\n\nsubsection \\<open>Function limit at a point\\<close>\n\nabbreviation LIM :: \"('a::topological_space \\<Rightarrow> 'b::topological_space) \\<Rightarrow> 'a \\<Rightarrow> 'b \\<Rightarrow> bool\"\n    (\"((_)/ \\<midarrow>(_)/\\<rightarrow> (_))\" [60, 0, 60] 60)\n  where \"f \\<midarrow>a\\<rightarrow> L \\<equiv> (f \\<longlongrightarrow> L) (at a)\"\n\nlemma tendsto_within_open: \"a \\<in> S \\<Longrightarrow> open S \\<Longrightarrow> (f \\<longlongrightarrow> l) (at a within S) \\<longleftrightarrow> (f \\<midarrow>a\\<rightarrow> l)\"\n  by (simp add: tendsto_def at_within_open[where S = S])\n\nlemma tendsto_within_open_NO_MATCH:\n  \"a \\<in> S \\<Longrightarrow> NO_MATCH UNIV S \\<Longrightarrow> open S \\<Longrightarrow> (f \\<longlongrightarrow> l)(at a within S) \\<longleftrightarrow> (f \\<longlongrightarrow> l)(at a)\"\n  for f :: \"'a::topological_space \\<Rightarrow> 'b::topological_space\"\n  using tendsto_within_open by blast\n\nlemma LIM_const_not_eq[tendsto_intros]: \"k \\<noteq> L \\<Longrightarrow> \\<not> (\\<lambda>x. k) \\<midarrow>a\\<rightarrow> L\"\n  for a :: \"'a::perfect_space\" and k L :: \"'b::t2_space\"\n  by (simp add: tendsto_const_iff)\n\nlemmas LIM_not_zero = LIM_const_not_eq [where L = 0]\n\nlemma LIM_const_eq: \"(\\<lambda>x. k) \\<midarrow>a\\<rightarrow> L \\<Longrightarrow> k = L\"\n  for a :: \"'a::perfect_space\" and k L :: \"'b::t2_space\"\n  by (simp add: tendsto_const_iff)\n\nlemma LIM_unique: \"f \\<midarrow>a\\<rightarrow> L \\<Longrightarrow> f \\<midarrow>a\\<rightarrow> M \\<Longrightarrow> L = M\"\n  for a :: \"'a::perfect_space\" and L M :: \"'b::t2_space\"\n  using at_neq_bot by (rule tendsto_unique)\n\nlemma LIM_Uniq: \"\\<exists>\\<^sub>\\<le>\\<^sub>1L::'b::t2_space. f \\<midarrow>a\\<rightarrow> L\"\n  for a :: \"'a::perfect_space\"\n by (auto simp add: Uniq_def LIM_unique)\n\n\ntext \\<open>Limits are equal for functions equal except at limit point.\\<close>\nlemma LIM_equal: \"\\<forall>x. x \\<noteq> a \\<longrightarrow> f x = g x \\<Longrightarrow> (f \\<midarrow>a\\<rightarrow> l) \\<longleftrightarrow> (g \\<midarrow>a\\<rightarrow> l)\"\n  by (simp add: tendsto_def eventually_at_topological)\n\nlemma LIM_cong: \"a = b \\<Longrightarrow> (\\<And>x. x \\<noteq> b \\<Longrightarrow> f x = g x) \\<Longrightarrow> l = m \\<Longrightarrow> (f \\<midarrow>a\\<rightarrow> l) \\<longleftrightarrow> (g \\<midarrow>b\\<rightarrow> m)\"\n  by (simp add: LIM_equal)\n\nlemma tendsto_cong_limit: \"(f \\<longlongrightarrow> l) F \\<Longrightarrow> k = l \\<Longrightarrow> (f \\<longlongrightarrow> k) F\"\n  by simp\n\nlemma tendsto_at_iff_tendsto_nhds: \"g \\<midarrow>l\\<rightarrow> g l \\<longleftrightarrow> (g \\<longlongrightarrow> g l) (nhds l)\"\n  unfolding tendsto_def eventually_at_filter\n  by (intro ext all_cong imp_cong) (auto elim!: eventually_mono)\n\nlemma tendsto_compose: \"g \\<midarrow>l\\<rightarrow> g l \\<Longrightarrow> (f \\<longlongrightarrow> l) F \\<Longrightarrow> ((\\<lambda>x. g (f x)) \\<longlongrightarrow> g l) F\"\n  unfolding tendsto_at_iff_tendsto_nhds by (rule filterlim_compose[of g])\n\nlemma tendsto_compose_eventually:\n  \"g \\<midarrow>l\\<rightarrow> m \\<Longrightarrow> (f \\<longlongrightarrow> l) F \\<Longrightarrow> eventually (\\<lambda>x. f x \\<noteq> l) F \\<Longrightarrow> ((\\<lambda>x. g (f x)) \\<longlongrightarrow> m) F\"\n  by (rule filterlim_compose[of g _ \"at l\"]) (auto simp add: filterlim_at)\n\nlemma LIM_compose_eventually:\n  assumes \"f \\<midarrow>a\\<rightarrow> b\"\n    and \"g \\<midarrow>b\\<rightarrow> c\"\n    and \"eventually (\\<lambda>x. f x \\<noteq> b) (at a)\"\n  shows \"(\\<lambda>x. g (f x)) \\<midarrow>a\\<rightarrow> c\"\n  using assms(2,1,3) by (rule tendsto_compose_eventually)\n\nlemma tendsto_compose_filtermap: \"((g \\<circ> f) \\<longlongrightarrow> T) F \\<longleftrightarrow> (g \\<longlongrightarrow> T) (filtermap f F)\"\n  by (simp add: filterlim_def filtermap_filtermap comp_def)\n\nlemma tendsto_compose_at:\n  assumes f: \"(f \\<longlongrightarrow> y) F\" and g: \"(g \\<longlongrightarrow> z) (at y)\" and fg: \"eventually (\\<lambda>w. f w = y \\<longrightarrow> g y = z) F\"\n  shows \"((g \\<circ> f) \\<longlongrightarrow> z) F\"\nproof -\n  have \"(\\<forall>\\<^sub>F a in F. f a \\<noteq> y) \\<or> g y = z\"\n    using fg by force\n  moreover have \"(g \\<longlongrightarrow> z) (filtermap f F) \\<or> \\<not> (\\<forall>\\<^sub>F a in F. f a \\<noteq> y)\"\n    by (metis (no_types) filterlim_atI filterlim_def tendsto_mono f g)\n  ultimately show ?thesis\n    by (metis (no_types) f filterlim_compose filterlim_filtermap g tendsto_at_iff_tendsto_nhds tendsto_compose_filtermap)\nqed\n\nlemma tendsto_nhds_iff: \"(f \\<longlongrightarrow> (c :: 'a :: t1_space)) (nhds x) \\<longleftrightarrow> f \\<midarrow>x\\<rightarrow> c \\<and> f x = c\"\nproof safe\n  assume lim: \"(f \\<longlongrightarrow> c) (nhds x)\"\n  show \"f x = c\"\n  proof (rule ccontr)\n    assume \"f x \\<noteq> c\"\n    hence \"c \\<noteq> f x\"\n      by auto\n    then obtain A where A: \"open A\" \"c \\<in> A\" \"f x \\<notin> A\"\n      by (subst (asm) separation_t1) auto\n    with lim obtain B where \"open B\" \"x \\<in> B\" \"\\<And>x. x \\<in> B \\<Longrightarrow> f x \\<in> A\"\n      unfolding tendsto_def eventually_nhds by metis \n    with \\<open>f x \\<notin> A\\<close> show False\n      by blast\n  qed\n  show \"(f \\<longlongrightarrow> c) (at x)\"\n    using lim by (rule filterlim_mono) (auto simp: at_within_def)\nnext\n  assume \"f \\<midarrow>x\\<rightarrow> f x\" \"c = f x\"\n  thus \"(f \\<longlongrightarrow> f x) (nhds x)\"\n    unfolding tendsto_def eventually_at_filter by (fast elim: eventually_mono)\nqed\n\n\nsubsubsection \\<open>Relation of \\<open>LIM\\<close> and \\<open>LIMSEQ\\<close>\\<close>\n\nlemma (in first_countable_topology) sequentially_imp_eventually_within:\n  \"(\\<forall>f. (\\<forall>n. f n \\<in> s \\<and> f n \\<noteq> a) \\<and> f \\<longlonglongrightarrow> a \\<longrightarrow> eventually (\\<lambda>n. P (f n)) sequentially) \\<Longrightarrow>\n    eventually P (at a within s)\"\n  unfolding at_within_def\n  by (intro sequentially_imp_eventually_nhds_within) auto\n\nlemma (in first_countable_topology) sequentially_imp_eventually_at:\n  \"(\\<forall>f. (\\<forall>n. f n \\<noteq> a) \\<and> f \\<longlonglongrightarrow> a \\<longrightarrow> eventually (\\<lambda>n. P (f n)) sequentially) \\<Longrightarrow> eventually P (at a)\"\n  using sequentially_imp_eventually_within [where s=UNIV] by simp\n\nlemma LIMSEQ_SEQ_conv:\n  \"(\\<forall>S. (\\<forall>n. S n \\<noteq> a) \\<and> S \\<longlonglongrightarrow> a \\<longrightarrow> (\\<lambda>n. X (S n)) \\<longlonglongrightarrow> L)  \\<longleftrightarrow>  X \\<midarrow>a\\<rightarrow> L\"  (is \"?lhs=?rhs\")\n  for a :: \"'a::first_countable_topology\" and L :: \"'b::topological_space\"\nproof\n  assume ?lhs then show ?rhs\n    by (simp add: sequentially_imp_eventually_within tendsto_def) \nnext\n  assume ?rhs then show ?lhs\n    using tendsto_compose_eventually eventuallyI by blast\nqed    \n\nlemma sequentially_imp_eventually_at_left:\n  fixes a :: \"'a::{linorder_topology,first_countable_topology}\"\n  assumes b[simp]: \"b < a\"\n    and *: \"\\<And>f. (\\<And>n. b < f n) \\<Longrightarrow> (\\<And>n. f n < a) \\<Longrightarrow> incseq f \\<Longrightarrow> f \\<longlonglongrightarrow> a \\<Longrightarrow>\n      eventually (\\<lambda>n. P (f n)) sequentially\"\n  shows \"eventually P (at_left a)\"\nproof (safe intro!: sequentially_imp_eventually_within)\n  fix X\n  assume X: \"\\<forall>n. X n \\<in> {..< a} \\<and> X n \\<noteq> a\" \"X \\<longlonglongrightarrow> a\"\n  show \"eventually (\\<lambda>n. P (X n)) sequentially\"\n  proof (rule ccontr)\n    assume neg: \"\\<not> ?thesis\"\n    have \"\\<exists>s. \\<forall>n. (\\<not> P (X (s n)) \\<and> b < X (s n)) \\<and> (X (s n) \\<le> X (s (Suc n)) \\<and> Suc (s n) \\<le> s (Suc n))\"\n      (is \"\\<exists>s. ?P s\")\n    proof (rule dependent_nat_choice)\n      have \"\\<not> eventually (\\<lambda>n. b < X n \\<longrightarrow> P (X n)) sequentially\"\n        by (intro not_eventually_impI neg order_tendstoD(1) [OF X(2) b])\n      then show \"\\<exists>x. \\<not> P (X x) \\<and> b < X x\"\n        by (auto dest!: not_eventuallyD)\n    next\n      fix x n\n      have \"\\<not> eventually (\\<lambda>n. Suc x \\<le> n \\<longrightarrow> b < X n \\<longrightarrow> X x < X n \\<longrightarrow> P (X n)) sequentially\"\n        using X\n        by (intro not_eventually_impI order_tendstoD(1)[OF X(2)] eventually_ge_at_top neg) auto\n      then show \"\\<exists>n. (\\<not> P (X n) \\<and> b < X n) \\<and> (X x \\<le> X n \\<and> Suc x \\<le> n)\"\n        by (auto dest!: not_eventuallyD)\n    qed\n    then obtain s where \"?P s\" ..\n    with X have \"b < X (s n)\"\n      and \"X (s n) < a\"\n      and \"incseq (\\<lambda>n. X (s n))\"\n      and \"(\\<lambda>n. X (s n)) \\<longlonglongrightarrow> a\"\n      and \"\\<not> P (X (s n))\"\n      for n\n      by (auto simp: strict_mono_Suc_iff Suc_le_eq incseq_Suc_iff\n          intro!: LIMSEQ_subseq_LIMSEQ[OF \\<open>X \\<longlonglongrightarrow> a\\<close>, unfolded comp_def])\n    from *[OF this(1,2,3,4)] this(5) show False\n      by auto\n  qed\nqed\n\nlemma tendsto_at_left_sequentially:\n  fixes a b :: \"'b::{linorder_topology,first_countable_topology}\"\n  assumes \"b < a\"\n  assumes *: \"\\<And>S. (\\<And>n. S n < a) \\<Longrightarrow> (\\<And>n. b < S n) \\<Longrightarrow> incseq S \\<Longrightarrow> S \\<longlonglongrightarrow> a \\<Longrightarrow>\n    (\\<lambda>n. X (S n)) \\<longlonglongrightarrow> L\"\n  shows \"(X \\<longlongrightarrow> L) (at_left a)\"\n  using assms by (simp add: tendsto_def [where l=L] sequentially_imp_eventually_at_left)\n\nlemma sequentially_imp_eventually_at_right:\n  fixes a b :: \"'a::{linorder_topology,first_countable_topology}\"\n  assumes b[simp]: \"a < b\"\n  assumes *: \"\\<And>f. (\\<And>n. a < f n) \\<Longrightarrow> (\\<And>n. f n < b) \\<Longrightarrow> decseq f \\<Longrightarrow> f \\<longlonglongrightarrow> a \\<Longrightarrow>\n    eventually (\\<lambda>n. P (f n)) sequentially\"\n  shows \"eventually P (at_right a)\"\nproof (safe intro!: sequentially_imp_eventually_within)\n  fix X\n  assume X: \"\\<forall>n. X n \\<in> {a <..} \\<and> X n \\<noteq> a\" \"X \\<longlonglongrightarrow> a\"\n  show \"eventually (\\<lambda>n. P (X n)) sequentially\"\n  proof (rule ccontr)\n    assume neg: \"\\<not> ?thesis\"\n    have \"\\<exists>s. \\<forall>n. (\\<not> P (X (s n)) \\<and> X (s n) < b) \\<and> (X (s (Suc n)) \\<le> X (s n) \\<and> Suc (s n) \\<le> s (Suc n))\"\n      (is \"\\<exists>s. ?P s\")\n    proof (rule dependent_nat_choice)\n      have \"\\<not> eventually (\\<lambda>n. X n < b \\<longrightarrow> P (X n)) sequentially\"\n        by (intro not_eventually_impI neg order_tendstoD(2) [OF X(2) b])\n      then show \"\\<exists>x. \\<not> P (X x) \\<and> X x < b\"\n        by (auto dest!: not_eventuallyD)\n    next\n      fix x n\n      have \"\\<not> eventually (\\<lambda>n. Suc x \\<le> n \\<longrightarrow> X n < b \\<longrightarrow> X n < X x \\<longrightarrow> P (X n)) sequentially\"\n        using X\n        by (intro not_eventually_impI order_tendstoD(2)[OF X(2)] eventually_ge_at_top neg) auto\n      then show \"\\<exists>n. (\\<not> P (X n) \\<and> X n < b) \\<and> (X n \\<le> X x \\<and> Suc x \\<le> n)\"\n        by (auto dest!: not_eventuallyD)\n    qed\n    then obtain s where \"?P s\" ..\n    with X have \"a < X (s n)\"\n      and \"X (s n) < b\"\n      and \"decseq (\\<lambda>n. X (s n))\"\n      and \"(\\<lambda>n. X (s n)) \\<longlonglongrightarrow> a\"\n      and \"\\<not> P (X (s n))\"\n      for n\n      by (auto simp: strict_mono_Suc_iff Suc_le_eq decseq_Suc_iff\n          intro!: LIMSEQ_subseq_LIMSEQ[OF \\<open>X \\<longlonglongrightarrow> a\\<close>, unfolded comp_def])\n    from *[OF this(1,2,3,4)] this(5) show False\n      by auto\n  qed\nqed\n\nlemma tendsto_at_right_sequentially:\n  fixes a :: \"_ :: {linorder_topology, first_countable_topology}\"\n  assumes \"a < b\"\n    and *: \"\\<And>S. (\\<And>n. a < S n) \\<Longrightarrow> (\\<And>n. S n < b) \\<Longrightarrow> decseq S \\<Longrightarrow> S \\<longlonglongrightarrow> a \\<Longrightarrow>\n      (\\<lambda>n. X (S n)) \\<longlonglongrightarrow> L\"\n  shows \"(X \\<longlongrightarrow> L) (at_right a)\"\n  using assms by (simp add: tendsto_def [where l=L] sequentially_imp_eventually_at_right)\n\n\nsubsection \\<open>Continuity\\<close>\n\nsubsubsection \\<open>Continuity on a set\\<close>\n\ndefinition continuous_on :: \"'a set \\<Rightarrow> ('a::topological_space \\<Rightarrow> 'b::topological_space) \\<Rightarrow> bool\"\n  where \"continuous_on s f \\<longleftrightarrow> (\\<forall>x\\<in>s. (f \\<longlongrightarrow> f x) (at x within s))\"\n\nlemma continuous_on_cong [cong]:\n  \"s = t \\<Longrightarrow> (\\<And>x. x \\<in> t \\<Longrightarrow> f x = g x) \\<Longrightarrow> continuous_on s f \\<longleftrightarrow> continuous_on t g\"\n  unfolding continuous_on_def\n  by (intro ball_cong filterlim_cong) (auto simp: eventually_at_filter)\n\nlemma continuous_on_cong_simp:\n  \"s = t \\<Longrightarrow> (\\<And>x. x \\<in> t =simp=> f x = g x) \\<Longrightarrow> continuous_on s f \\<longleftrightarrow> continuous_on t g\"\n  unfolding simp_implies_def by (rule continuous_on_cong)\n\nlemma continuous_on_topological:\n  \"continuous_on s f \\<longleftrightarrow>\n    (\\<forall>x\\<in>s. \\<forall>B. open B \\<longrightarrow> f x \\<in> B \\<longrightarrow> (\\<exists>A. open A \\<and> x \\<in> A \\<and> (\\<forall>y\\<in>s. y \\<in> A \\<longrightarrow> f y \\<in> B)))\"\n  unfolding continuous_on_def tendsto_def eventually_at_topological by metis\n\nlemma continuous_on_open_invariant:\n  \"continuous_on s f \\<longleftrightarrow> (\\<forall>B. open B \\<longrightarrow> (\\<exists>A. open A \\<and> A \\<inter> s = f -` B \\<inter> s))\"\nproof safe\n  fix B :: \"'b set\"\n  assume \"continuous_on s f\" \"open B\"\n  then have \"\\<forall>x\\<in>f -` B \\<inter> s. (\\<exists>A. open A \\<and> x \\<in> A \\<and> s \\<inter> A \\<subseteq> f -` B)\"\n    by (auto simp: continuous_on_topological subset_eq Ball_def imp_conjL)\n  then obtain A where \"\\<forall>x\\<in>f -` B \\<inter> s. open (A x) \\<and> x \\<in> A x \\<and> s \\<inter> A x \\<subseteq> f -` B\"\n    unfolding bchoice_iff ..\n  then show \"\\<exists>A. open A \\<and> A \\<inter> s = f -` B \\<inter> s\"\n    by (intro exI[of _ \"\\<Union>x\\<in>f -` B \\<inter> s. A x\"]) auto\nnext\n  assume B: \"\\<forall>B. open B \\<longrightarrow> (\\<exists>A. open A \\<and> A \\<inter> s = f -` B \\<inter> s)\"\n  show \"continuous_on s f\"\n    unfolding continuous_on_topological\n  proof safe\n    fix x B\n    assume \"x \\<in> s\" \"open B\" \"f x \\<in> B\"\n    with B obtain A where A: \"open A\" \"A \\<inter> s = f -` B \\<inter> s\"\n      by auto\n    with \\<open>x \\<in> s\\<close> \\<open>f x \\<in> B\\<close> show \"\\<exists>A. open A \\<and> x \\<in> A \\<and> (\\<forall>y\\<in>s. y \\<in> A \\<longrightarrow> f y \\<in> B)\"\n      by (intro exI[of _ A]) auto\n  qed\nqed\n\nlemma continuous_on_open_vimage:\n  \"open s \\<Longrightarrow> continuous_on s f \\<longleftrightarrow> (\\<forall>B. open B \\<longrightarrow> open (f -` B \\<inter> s))\"\n  unfolding continuous_on_open_invariant\n  by (metis open_Int Int_absorb Int_commute[of s] Int_assoc[of _ _ s])\n\ncorollary continuous_imp_open_vimage:\n  assumes \"continuous_on s f\" \"open s\" \"open B\" \"f -` B \\<subseteq> s\"\n  shows \"open (f -` B)\"\n  by (metis assms continuous_on_open_vimage le_iff_inf)\n\ncorollary open_vimage[continuous_intros]:\n  assumes \"open s\"\n    and \"continuous_on UNIV f\"\n  shows \"open (f -` s)\"\n  using assms by (simp add: continuous_on_open_vimage [OF open_UNIV])\n\nlemma continuous_on_closed_invariant:\n  \"continuous_on s f \\<longleftrightarrow> (\\<forall>B. closed B \\<longrightarrow> (\\<exists>A. closed A \\<and> A \\<inter> s = f -` B \\<inter> s))\"\nproof -\n  have *: \"(\\<And>A. P A \\<longleftrightarrow> Q (- A)) \\<Longrightarrow> (\\<forall>A. P A) \\<longleftrightarrow> (\\<forall>A. Q A)\"\n    for P Q :: \"'b set \\<Rightarrow> bool\"\n    by (metis double_compl)\n  show ?thesis\n    unfolding continuous_on_open_invariant\n    by (intro *) (auto simp: open_closed[symmetric])\nqed\n\nlemma continuous_on_closed_vimage:\n  \"closed s \\<Longrightarrow> continuous_on s f \\<longleftrightarrow> (\\<forall>B. closed B \\<longrightarrow> closed (f -` B \\<inter> s))\"\n  unfolding continuous_on_closed_invariant\n  by (metis closed_Int Int_absorb Int_commute[of s] Int_assoc[of _ _ s])\n\ncorollary closed_vimage_Int[continuous_intros]:\n  assumes \"closed s\"\n    and \"continuous_on t f\"\n    and t: \"closed t\"\n  shows \"closed (f -` s \\<inter> t)\"\n  using assms by (simp add: continuous_on_closed_vimage [OF t])\n\ncorollary closed_vimage[continuous_intros]:\n  assumes \"closed s\"\n    and \"continuous_on UNIV f\"\n  shows \"closed (f -` s)\"\n  using closed_vimage_Int [OF assms] by simp\n\nlemma continuous_on_empty [simp]: \"continuous_on {} f\"\n  by (simp add: continuous_on_def)\n\nlemma continuous_on_sing [simp]: \"continuous_on {x} f\"\n  by (simp add: continuous_on_def at_within_def)\n\nlemma continuous_on_open_Union:\n  \"(\\<And>s. s \\<in> S \\<Longrightarrow> open s) \\<Longrightarrow> (\\<And>s. s \\<in> S \\<Longrightarrow> continuous_on s f) \\<Longrightarrow> continuous_on (\\<Union>S) f\"\n  unfolding continuous_on_def\n  by safe (metis open_Union at_within_open UnionI)\n\nlemma continuous_on_open_UN:\n  \"(\\<And>s. s \\<in> S \\<Longrightarrow> open (A s)) \\<Longrightarrow> (\\<And>s. s \\<in> S \\<Longrightarrow> continuous_on (A s) f) \\<Longrightarrow>\n    continuous_on (\\<Union>s\\<in>S. A s) f\"\n  by (rule continuous_on_open_Union) auto\n\nlemma continuous_on_open_Un:\n  \"open s \\<Longrightarrow> open t \\<Longrightarrow> continuous_on s f \\<Longrightarrow> continuous_on t f \\<Longrightarrow> continuous_on (s \\<union> t) f\"\n  using continuous_on_open_Union [of \"{s,t}\"] by auto\n\nlemma continuous_on_closed_Un:\n  \"closed s \\<Longrightarrow> closed t \\<Longrightarrow> continuous_on s f \\<Longrightarrow> continuous_on t f \\<Longrightarrow> continuous_on (s \\<union> t) f\"\n  by (auto simp add: continuous_on_closed_vimage closed_Un Int_Un_distrib)\n\nlemma continuous_on_closed_Union:\n  assumes \"finite I\"\n    \"\\<And>i. i \\<in> I \\<Longrightarrow> closed (U i)\"\n    \"\\<And>i. i \\<in> I \\<Longrightarrow> continuous_on (U i) f\"\n  shows \"continuous_on (\\<Union> i \\<in> I. U i) f\"\n  using assms\n  by (induction I) (auto intro!: continuous_on_closed_Un)\n\nlemma continuous_on_If:\n  assumes closed: \"closed s\" \"closed t\"\n    and cont: \"continuous_on s f\" \"continuous_on t g\"\n    and P: \"\\<And>x. x \\<in> s \\<Longrightarrow> \\<not> P x \\<Longrightarrow> f x = g x\" \"\\<And>x. x \\<in> t \\<Longrightarrow> P x \\<Longrightarrow> f x = g x\"\n  shows \"continuous_on (s \\<union> t) (\\<lambda>x. if P x then f x else g x)\"\n    (is \"continuous_on _ ?h\")\nproof-\n  from P have \"\\<forall>x\\<in>s. f x = ?h x\" \"\\<forall>x\\<in>t. g x = ?h x\"\n    by auto\n  with cont have \"continuous_on s ?h\" \"continuous_on t ?h\"\n    by simp_all\n  with closed show ?thesis\n    by (rule continuous_on_closed_Un)\nqed\n\nlemma continuous_on_cases:\n  \"closed s \\<Longrightarrow> closed t \\<Longrightarrow> continuous_on s f \\<Longrightarrow> continuous_on t g \\<Longrightarrow>\n    \\<forall>x. (x\\<in>s \\<and> \\<not> P x) \\<or> (x \\<in> t \\<and> P x) \\<longrightarrow> f x = g x \\<Longrightarrow>\n    continuous_on (s \\<union> t) (\\<lambda>x. if P x then f x else g x)\"\n  by (rule continuous_on_If) auto\n\nlemma continuous_on_id[continuous_intros,simp]: \"continuous_on s (\\<lambda>x. x)\"\n  unfolding continuous_on_def by fast\n\nlemma continuous_on_id'[continuous_intros,simp]: \"continuous_on s id\"\n  unfolding continuous_on_def id_def by fast\n\nlemma continuous_on_const[continuous_intros,simp]: \"continuous_on s (\\<lambda>x. c)\"\n  unfolding continuous_on_def by auto\n\nlemma continuous_on_subset: \"continuous_on s f \\<Longrightarrow> t \\<subseteq> s \\<Longrightarrow> continuous_on t f\"\n  unfolding continuous_on_def\n  by (metis subset_eq tendsto_within_subset)\n\nlemma continuous_on_compose[continuous_intros]:\n  \"continuous_on s f \\<Longrightarrow> continuous_on (f ` s) g \\<Longrightarrow> continuous_on s (g \\<circ> f)\"\n  unfolding continuous_on_topological by simp metis\n\nlemma continuous_on_compose2:\n  \"continuous_on t g \\<Longrightarrow> continuous_on s f \\<Longrightarrow> f ` s \\<subseteq> t \\<Longrightarrow> continuous_on s (\\<lambda>x. g (f x))\"\n  using continuous_on_compose[of s f g] continuous_on_subset by (force simp add: comp_def)\n\nlemma continuous_on_generate_topology:\n  assumes *: \"open = generate_topology X\"\n    and **: \"\\<And>B. B \\<in> X \\<Longrightarrow> \\<exists>C. open C \\<and> C \\<inter> A = f -` B \\<inter> A\"\n  shows \"continuous_on A f\"\n  unfolding continuous_on_open_invariant\nproof safe\n  fix B :: \"'a set\"\n  assume \"open B\"\n  then show \"\\<exists>C. open C \\<and> C \\<inter> A = f -` B \\<inter> A\"\n    unfolding *\n  proof induct\n    case (UN K)\n    then obtain C where \"\\<And>k. k \\<in> K \\<Longrightarrow> open (C k)\" \"\\<And>k. k \\<in> K \\<Longrightarrow> C k \\<inter> A = f -` k \\<inter> A\"\n      by metis\n    then show ?case\n      by (intro exI[of _ \"\\<Union>k\\<in>K. C k\"]) blast\n  qed (auto intro: **)\nqed\n\nlemma continuous_onI_mono:\n  fixes f :: \"'a::linorder_topology \\<Rightarrow> 'b::{dense_order,linorder_topology}\"\n  assumes \"open (f`A)\"\n    and mono: \"\\<And>x y. x \\<in> A \\<Longrightarrow> y \\<in> A \\<Longrightarrow> x \\<le> y \\<Longrightarrow> f x \\<le> f y\"\n  shows \"continuous_on A f\"\nproof (rule continuous_on_generate_topology[OF open_generated_order], safe)\n  have monoD: \"\\<And>x y. x \\<in> A \\<Longrightarrow> y \\<in> A \\<Longrightarrow> f x < f y \\<Longrightarrow> x < y\"\n    by (auto simp: not_le[symmetric] mono)\n  have \"\\<exists>x. x \\<in> A \\<and> f x < b \\<and> a < x\" if a: \"a \\<in> A\" and fa: \"f a < b\" for a b\n  proof -\n    obtain y where \"f a < y\" \"{f a ..< y} \\<subseteq> f`A\"\n      using open_right[OF \\<open>open (f`A)\\<close>, of \"f a\" b] a fa\n      by auto\n    obtain z where z: \"f a < z\" \"z < min b y\"\n      using dense[of \"f a\" \"min b y\"] \\<open>f a < y\\<close> \\<open>f a < b\\<close> by auto\n    then obtain c where \"z = f c\" \"c \\<in> A\"\n      using \\<open>{f a ..< y} \\<subseteq> f`A\\<close>[THEN subsetD, of z] by (auto simp: less_imp_le)\n    with a z show ?thesis\n      by (auto intro!: exI[of _ c] simp: monoD)\n  qed\n  then show \"\\<exists>C. open C \\<and> C \\<inter> A = f -` {..<b} \\<inter> A\" for b\n    by (intro exI[of _ \"(\\<Union>x\\<in>{x\\<in>A. f x < b}. {..< x})\"])\n       (auto intro: le_less_trans[OF mono] less_imp_le)\n\n  have \"\\<exists>x. x \\<in> A \\<and> b < f x \\<and> x < a\" if a: \"a \\<in> A\" and fa: \"b < f a\" for a b\n  proof -\n    note a fa\n    moreover\n    obtain y where \"y < f a\" \"{y <.. f a} \\<subseteq> f`A\"\n      using open_left[OF \\<open>open (f`A)\\<close>, of \"f a\" b]  a fa\n      by auto\n    then obtain z where z: \"max b y < z\" \"z < f a\"\n      using dense[of \"max b y\" \"f a\"] \\<open>y < f a\\<close> \\<open>b < f a\\<close> by auto\n    then obtain c where \"z = f c\" \"c \\<in> A\"\n      using \\<open>{y <.. f a} \\<subseteq> f`A\\<close>[THEN subsetD, of z] by (auto simp: less_imp_le)\n    with a z show ?thesis\n      by (auto intro!: exI[of _ c] simp: monoD)\n  qed\n  then show \"\\<exists>C. open C \\<and> C \\<inter> A = f -` {b <..} \\<inter> A\" for b\n    by (intro exI[of _ \"(\\<Union>x\\<in>{x\\<in>A. b < f x}. {x <..})\"])\n       (auto intro: less_le_trans[OF _ mono] less_imp_le)\nqed\n\nlemma continuous_on_IccI:\n  \"\\<lbrakk>(f \\<longlongrightarrow> f a) (at_right a);\n    (f \\<longlongrightarrow> f b) (at_left b);\n    (\\<And>x. a < x \\<Longrightarrow> x < b \\<Longrightarrow> f \\<midarrow>x\\<rightarrow> f x); a < b\\<rbrakk> \\<Longrightarrow>\n    continuous_on {a .. b} f\"\n  for a::\"'a::linorder_topology\"\n  using at_within_open[of _ \"{a<..<b}\"]\n  by (auto simp: continuous_on_def at_within_Icc_at_right at_within_Icc_at_left le_less\n      at_within_Icc_at)\n\nlemma\n  fixes a b::\"'a::linorder_topology\"\n  assumes \"continuous_on {a .. b} f\" \"a < b\"\n  shows continuous_on_Icc_at_rightD: \"(f \\<longlongrightarrow> f a) (at_right a)\"\n    and continuous_on_Icc_at_leftD: \"(f \\<longlongrightarrow> f b) (at_left b)\"\n  using assms\n  by (auto simp: at_within_Icc_at_right at_within_Icc_at_left continuous_on_def\n      dest: bspec[where x=a] bspec[where x=b])\n\nlemma continuous_on_discrete [simp]:\n  \"continuous_on A (f :: 'a :: discrete_topology \\<Rightarrow> _)\"\n  by (auto simp: continuous_on_def at_discrete)\n\nlemma continuous_on_of_nat [continuous_intros]:\n  assumes \"continuous_on A f\"\n  shows   \"continuous_on A (\\<lambda>n. of_nat (f n))\"\n  using continuous_on_compose[OF assms continuous_on_discrete[of _ of_nat]]\n  by (simp add: o_def)\n\nlemma continuous_on_of_int [continuous_intros]:\n  assumes \"continuous_on A f\"\n  shows   \"continuous_on A (\\<lambda>n. of_int (f n))\"\n  using continuous_on_compose[OF assms continuous_on_discrete[of _ of_int]]\n  by (simp add: o_def)\n\nsubsubsection \\<open>Continuity at a point\\<close>\n\ndefinition continuous :: \"'a::t2_space filter \\<Rightarrow> ('a \\<Rightarrow> 'b::topological_space) \\<Rightarrow> bool\"\n  where \"continuous F f \\<longleftrightarrow> (f \\<longlongrightarrow> f (Lim F (\\<lambda>x. x))) F\"\n\nlemma continuous_bot[continuous_intros, simp]: \"continuous bot f\"\n  unfolding continuous_def by auto\n\nlemma continuous_trivial_limit: \"trivial_limit net \\<Longrightarrow> continuous net f\"\n  by simp\n\nlemma continuous_within: \"continuous (at x within s) f \\<longleftrightarrow> (f \\<longlongrightarrow> f x) (at x within s)\"\n  by (cases \"trivial_limit (at x within s)\") (auto simp add: Lim_ident_at continuous_def)\n\nlemma continuous_within_topological:\n  \"continuous (at x within s) f \\<longleftrightarrow>\n    (\\<forall>B. open B \\<longrightarrow> f x \\<in> B \\<longrightarrow> (\\<exists>A. open A \\<and> x \\<in> A \\<and> (\\<forall>y\\<in>s. y \\<in> A \\<longrightarrow> f y \\<in> B)))\"\n  unfolding continuous_within tendsto_def eventually_at_topological by metis\n\nlemma continuous_within_compose[continuous_intros]:\n  \"continuous (at x within s) f \\<Longrightarrow> continuous (at (f x) within f ` s) g \\<Longrightarrow>\n    continuous (at x within s) (g \\<circ> f)\"\n  by (simp add: continuous_within_topological) metis\n\nlemma continuous_within_compose2:\n  \"continuous (at x within s) f \\<Longrightarrow> continuous (at (f x) within f ` s) g \\<Longrightarrow>\n    continuous (at x within s) (\\<lambda>x. g (f x))\"\n  using continuous_within_compose[of x s f g] by (simp add: comp_def)\n\nlemma continuous_at: \"continuous (at x) f \\<longleftrightarrow> f \\<midarrow>x\\<rightarrow> f x\"\n  using continuous_within[of x UNIV f] by simp\n\nlemma continuous_ident[continuous_intros, simp]: \"continuous (at x within S) (\\<lambda>x. x)\"\n  unfolding continuous_within by (rule tendsto_ident_at)\n\nlemma continuous_id[continuous_intros, simp]: \"continuous (at x within S) id\"\n  by (simp add: id_def)\n\nlemma continuous_const[continuous_intros, simp]: \"continuous F (\\<lambda>x. c)\"\n  unfolding continuous_def by (rule tendsto_const)\n\nlemma continuous_on_eq_continuous_within:\n  \"continuous_on s f \\<longleftrightarrow> (\\<forall>x\\<in>s. continuous (at x within s) f)\"\n  unfolding continuous_on_def continuous_within ..\n\nlemma continuous_discrete [simp]:\n  \"continuous (at x within A) (f :: 'a :: discrete_topology \\<Rightarrow> _)\"\n  by (auto simp: continuous_def at_discrete)\n\nabbreviation isCont :: \"('a::t2_space \\<Rightarrow> 'b::topological_space) \\<Rightarrow> 'a \\<Rightarrow> bool\"\n  where \"isCont f a \\<equiv> continuous (at a) f\"\n\nlemma isCont_def: \"isCont f a \\<longleftrightarrow> f \\<midarrow>a\\<rightarrow> f a\"\n  by (rule continuous_at)\n\nlemma isContD: \"isCont f x \\<Longrightarrow> f \\<midarrow>x\\<rightarrow> f x\"\n  by (simp add: isCont_def)\n\nlemma isCont_cong:\n  assumes \"eventually (\\<lambda>x. f x = g x) (nhds x)\"\n  shows \"isCont f x \\<longleftrightarrow> isCont g x\"\nproof -\n  from assms have [simp]: \"f x = g x\"\n    by (rule eventually_nhds_x_imp_x)\n  from assms have \"eventually (\\<lambda>x. f x = g x) (at x)\"\n    by (auto simp: eventually_at_filter elim!: eventually_mono)\n  with assms have \"isCont f x \\<longleftrightarrow> isCont g x\" unfolding isCont_def\n    by (intro filterlim_cong) (auto elim!: eventually_mono)\n  with assms show ?thesis by simp\nqed\n\nlemma continuous_at_imp_continuous_at_within: \"isCont f x \\<Longrightarrow> continuous (at x within s) f\"\n  by (auto intro: tendsto_mono at_le simp: continuous_at continuous_within)\n\nlemma continuous_on_eq_continuous_at: \"open s \\<Longrightarrow> continuous_on s f \\<longleftrightarrow> (\\<forall>x\\<in>s. isCont f x)\"\n  by (simp add: continuous_on_def continuous_at at_within_open[of _ s])\n\nlemma continuous_within_open: \"a \\<in> A \\<Longrightarrow> open A \\<Longrightarrow> continuous (at a within A) f \\<longleftrightarrow> isCont f a\"\n  by (simp add: at_within_open_NO_MATCH)\n\nlemma continuous_at_imp_continuous_on: \"\\<forall>x\\<in>s. isCont f x \\<Longrightarrow> continuous_on s f\"\n  by (auto intro: continuous_at_imp_continuous_at_within simp: continuous_on_eq_continuous_within)\n\nlemma isCont_o2: \"isCont f a \\<Longrightarrow> isCont g (f a) \\<Longrightarrow> isCont (\\<lambda>x. g (f x)) a\"\n  unfolding isCont_def by (rule tendsto_compose)\n\nlemma continuous_at_compose[continuous_intros]: \"isCont f a \\<Longrightarrow> isCont g (f a) \\<Longrightarrow> isCont (g \\<circ> f) a\"\n  unfolding o_def by (rule isCont_o2)\n\nlemma isCont_tendsto_compose: \"isCont g l \\<Longrightarrow> (f \\<longlongrightarrow> l) F \\<Longrightarrow> ((\\<lambda>x. g (f x)) \\<longlongrightarrow> g l) F\"\n  unfolding isCont_def by (rule tendsto_compose)\n\nlemma continuous_on_tendsto_compose:\n  assumes f_cont: \"continuous_on s f\"\n    and g: \"(g \\<longlongrightarrow> l) F\"\n    and l: \"l \\<in> s\"\n    and ev: \"\\<forall>\\<^sub>Fx in F. g x \\<in> s\"\n  shows \"((\\<lambda>x. f (g x)) \\<longlongrightarrow> f l) F\"\nproof -\n  from f_cont l have f: \"(f \\<longlongrightarrow> f l) (at l within s)\"\n    by (simp add: continuous_on_def)\n  have i: \"((\\<lambda>x. if g x = l then f l else f (g x)) \\<longlongrightarrow> f l) F\"\n    by (rule filterlim_If)\n       (auto intro!: filterlim_compose[OF f] eventually_conj tendsto_mono[OF _ g]\n             simp: filterlim_at eventually_inf_principal eventually_mono[OF ev])\n  show ?thesis\n    by (rule filterlim_cong[THEN iffD1[OF _ i]]) auto\nqed\n\nlemma continuous_within_compose3:\n  \"isCont g (f x) \\<Longrightarrow> continuous (at x within s) f \\<Longrightarrow> continuous (at x within s) (\\<lambda>x. g (f x))\"\n  using continuous_at_imp_continuous_at_within continuous_within_compose2 by blast\n\nlemma at_within_isCont_imp_nhds:\n  fixes f:: \"'a:: {t2_space,perfect_space} \\<Rightarrow> 'b:: t2_space\"\n  assumes \"\\<forall>\\<^sub>F w in at z. f w = g w\" \"isCont f z\" \"isCont g z\"\n  shows \"\\<forall>\\<^sub>F w in nhds z. f w = g w\"\nproof -\n  have \"g \\<midarrow>z\\<rightarrow> f z\"\n    using assms isContD tendsto_cong by blast \n  moreover have \"g \\<midarrow>z\\<rightarrow> g z\" using \\<open>isCont g z\\<close> using isCont_def by blast\n  ultimately have \"f z=g z\" using LIM_unique by auto\n  moreover have \"\\<forall>\\<^sub>F x in nhds z. x \\<noteq> z \\<longrightarrow> f x = g x\"\n    using assms unfolding eventually_at_filter by auto\n  ultimately show ?thesis \n    by (auto elim:eventually_mono)\nqed\n\nlemma filtermap_nhds_open_map':\n  assumes cont: \"isCont f a\"\n    and \"open A\" \"a \\<in> A\"\n    and open_map: \"\\<And>S. open S \\<Longrightarrow> S \\<subseteq> A \\<Longrightarrow> open (f ` S)\"\n  shows \"filtermap f (nhds a) = nhds (f a)\"\n  unfolding filter_eq_iff\nproof safe\n  fix P\n  assume \"eventually P (filtermap f (nhds a))\"\n  then obtain S where S: \"open S\" \"a \\<in> S\" \"\\<forall>x\\<in>S. P (f x)\"\n    by (auto simp: eventually_filtermap eventually_nhds)\n  show \"eventually P (nhds (f a))\"\n    unfolding eventually_nhds \n  proof (rule exI [of _ \"f ` (A \\<inter> S)\"], safe)\n    show \"open (f ` (A \\<inter> S))\"\n      using S by (intro open_Int assms) auto\n    show \"f a \\<in> f ` (A \\<inter> S)\"\n      using assms S by auto\n    show \"P (f x)\" if \"x \\<in> A\" \"x \\<in> S\" for x\n      using S that by auto\n  qed\nqed (metis filterlim_iff tendsto_at_iff_tendsto_nhds isCont_def eventually_filtermap cont)\n\nlemma filtermap_nhds_open_map:\n  assumes cont: \"isCont f a\"\n    and open_map: \"\\<And>S. open S \\<Longrightarrow> open (f`S)\"\n  shows \"filtermap f (nhds a) = nhds (f a)\"\n  using cont filtermap_nhds_open_map' open_map by blast\n\nlemma continuous_at_split:\n  \"continuous (at x) f \\<longleftrightarrow> continuous (at_left x) f \\<and> continuous (at_right x) f\"\n  for x :: \"'a::linorder_topology\"\n  by (simp add: continuous_within filterlim_at_split)\n\nlemma continuous_on_max [continuous_intros]:\n  fixes f g :: \"'a::topological_space \\<Rightarrow> 'b::linorder_topology\"\n  shows \"continuous_on A f \\<Longrightarrow> continuous_on A g \\<Longrightarrow> continuous_on A (\\<lambda>x. max (f x) (g x))\"\n  by (auto simp: continuous_on_def intro!: tendsto_max)\n\nlemma continuous_on_min [continuous_intros]:\n  fixes f g :: \"'a::topological_space \\<Rightarrow> 'b::linorder_topology\"\n  shows \"continuous_on A f \\<Longrightarrow> continuous_on A g \\<Longrightarrow> continuous_on A (\\<lambda>x. min (f x) (g x))\"\n  by (auto simp: continuous_on_def intro!: tendsto_min)\n\nlemma continuous_max [continuous_intros]:\n  fixes f :: \"'a::t2_space \\<Rightarrow> 'b::linorder_topology\"\n  shows \"\\<lbrakk>continuous F f; continuous F g\\<rbrakk> \\<Longrightarrow> continuous F (\\<lambda>x. (max (f x) (g x)))\"\n  by (simp add: tendsto_max continuous_def)\n\nlemma continuous_min [continuous_intros]:\n  fixes f :: \"'a::t2_space \\<Rightarrow> 'b::linorder_topology\"\n  shows \"\\<lbrakk>continuous F f; continuous F g\\<rbrakk> \\<Longrightarrow> continuous F (\\<lambda>x. (min (f x) (g x)))\"\n  by (simp add: tendsto_min continuous_def)\n\ntext \\<open>\n  The following open/closed Collect lemmas are ported from\n  S\u00e9bastien Gou\u00ebzel's \\<open>Ergodic_Theory\\<close>.\n\\<close>\nlemma open_Collect_neq:\n  fixes f g :: \"'a::topological_space \\<Rightarrow> 'b::t2_space\"\n  assumes f: \"continuous_on UNIV f\" and g: \"continuous_on UNIV g\"\n  shows \"open {x. f x \\<noteq> g x}\"\nproof (rule openI)\n  fix t\n  assume \"t \\<in> {x. f x \\<noteq> g x}\"\n  then obtain U V where *: \"open U\" \"open V\" \"f t \\<in> U\" \"g t \\<in> V\" \"U \\<inter> V = {}\"\n    by (auto simp add: separation_t2)\n  with open_vimage[OF \\<open>open U\\<close> f] open_vimage[OF \\<open>open V\\<close> g]\n  show \"\\<exists>T. open T \\<and> t \\<in> T \\<and> T \\<subseteq> {x. f x \\<noteq> g x}\"\n    by (intro exI[of _ \"f -` U \\<inter> g -` V\"]) auto\nqed\n\nlemma closed_Collect_eq:\n  fixes f g :: \"'a::topological_space \\<Rightarrow> 'b::t2_space\"\n  assumes f: \"continuous_on UNIV f\" and g: \"continuous_on UNIV g\"\n  shows \"closed {x. f x = g x}\"\n  using open_Collect_neq[OF f g] by (simp add: closed_def Collect_neg_eq)\n\nlemma open_Collect_less:\n  fixes f g :: \"'a::topological_space \\<Rightarrow> 'b::linorder_topology\"\n  assumes f: \"continuous_on UNIV f\" and g: \"continuous_on UNIV g\"\n  shows \"open {x. f x < g x}\"\nproof (rule openI)\n  fix t\n  assume t: \"t \\<in> {x. f x < g x}\"\n  show \"\\<exists>T. open T \\<and> t \\<in> T \\<and> T \\<subseteq> {x. f x < g x}\"\n  proof (cases \"\\<exists>z. f t < z \\<and> z < g t\")\n    case True\n    then obtain z where \"f t < z \\<and> z < g t\" by blast\n    then show ?thesis\n      using open_vimage[OF _ f, of \"{..< z}\"] open_vimage[OF _ g, of \"{z <..}\"]\n      by (intro exI[of _ \"f -` {..<z} \\<inter> g -` {z<..}\"]) auto\n  next\n    case False\n    then have *: \"{g t ..} = {f t <..}\" \"{..< g t} = {.. f t}\"\n      using t by (auto intro: leI)\n    show ?thesis\n      using open_vimage[OF _ f, of \"{..< g t}\"] open_vimage[OF _ g, of \"{f t <..}\"] t\n      apply (intro exI[of _ \"f -` {..< g t} \\<inter> g -` {f t<..}\"])\n      apply (simp add: open_Int)\n      apply (auto simp add: *)\n      done\n  qed\nqed\n\nlemma closed_Collect_le:\n  fixes f g :: \"'a :: topological_space \\<Rightarrow> 'b::linorder_topology\"\n  assumes f: \"continuous_on UNIV f\"\n    and g: \"continuous_on UNIV g\"\n  shows \"closed {x. f x \\<le> g x}\"\n  using open_Collect_less [OF g f]\n  by (simp add: closed_def Collect_neg_eq[symmetric] not_le)\n\n\nsubsubsection \\<open>Open-cover compactness\\<close>\n\ncontext topological_space\nbegin\n\ndefinition compact :: \"'a set \\<Rightarrow> bool\" where\ncompact_eq_Heine_Borel:  (* This name is used for backwards compatibility *)\n    \"compact S \\<longleftrightarrow> (\\<forall>C. (\\<forall>c\\<in>C. open c) \\<and> S \\<subseteq> \\<Union>C \\<longrightarrow> (\\<exists>D\\<subseteq>C. finite D \\<and> S \\<subseteq> \\<Union>D))\"\n\nlemma compactI:\n  assumes \"\\<And>C. \\<forall>t\\<in>C. open t \\<Longrightarrow> s \\<subseteq> \\<Union>C \\<Longrightarrow> \\<exists>C'. C' \\<subseteq> C \\<and> finite C' \\<and> s \\<subseteq> \\<Union>C'\"\n  shows \"compact s\"\n  unfolding compact_eq_Heine_Borel using assms by metis\n\nlemma compact_empty[simp]: \"compact {}\"\n  by (auto intro!: compactI)\n\nlemma compactE: (*related to COMPACT_IMP_HEINE_BOREL in HOL Light*)\n  assumes \"compact S\" \"S \\<subseteq> \\<Union>\\<T>\" \"\\<And>B. B \\<in> \\<T> \\<Longrightarrow> open B\"\n  obtains \\<T>' where \"\\<T>' \\<subseteq> \\<T>\" \"finite \\<T>'\" \"S \\<subseteq> \\<Union>\\<T>'\"\n  by (meson assms compact_eq_Heine_Borel)\n\nlemma compactE_image:\n  assumes \"compact S\"\n    and opn: \"\\<And>T. T \\<in> C \\<Longrightarrow> open (f T)\"\n    and S: \"S \\<subseteq> (\\<Union>c\\<in>C. f c)\"\n  obtains C' where \"C' \\<subseteq> C\" and \"finite C'\" and \"S \\<subseteq> (\\<Union>c\\<in>C'. f c)\"\n    apply (rule compactE[OF \\<open>compact S\\<close> S])\n    using opn apply force\n    by (metis finite_subset_image)\n\nlemma compact_Int_closed [intro]:\n  assumes \"compact S\"\n    and \"closed T\"\n  shows \"compact (S \\<inter> T)\"\nproof (rule compactI)\n  fix C\n  assume C: \"\\<forall>c\\<in>C. open c\"\n  assume cover: \"S \\<inter> T \\<subseteq> \\<Union>C\"\n  from C \\<open>closed T\\<close> have \"\\<forall>c\\<in>C \\<union> {- T}. open c\"\n    by auto\n  moreover from cover have \"S \\<subseteq> \\<Union>(C \\<union> {- T})\"\n    by auto\n  ultimately have \"\\<exists>D\\<subseteq>C \\<union> {- T}. finite D \\<and> S \\<subseteq> \\<Union>D\"\n    using \\<open>compact S\\<close> unfolding compact_eq_Heine_Borel by auto\n  then obtain D where \"D \\<subseteq> C \\<union> {- T} \\<and> finite D \\<and> S \\<subseteq> \\<Union>D\" ..\n  then show \"\\<exists>D\\<subseteq>C. finite D \\<and> S \\<inter> T \\<subseteq> \\<Union>D\"\n    by (intro exI[of _ \"D - {-T}\"]) auto\nqed\n\nlemma compact_diff: \"\\<lbrakk>compact S; open T\\<rbrakk> \\<Longrightarrow> compact(S - T)\"\n  by (simp add: Diff_eq compact_Int_closed open_closed)\n\nlemma inj_setminus: \"inj_on uminus (A::'a set set)\"\n  by (auto simp: inj_on_def)\n\n\nsubsection \\<open>Finite intersection property\\<close>\n\nlemma compact_fip:\n  \"compact U \\<longleftrightarrow>\n    (\\<forall>A. (\\<forall>a\\<in>A. closed a) \\<longrightarrow> (\\<forall>B \\<subseteq> A. finite B \\<longrightarrow> U \\<inter> \\<Inter>B \\<noteq> {}) \\<longrightarrow> U \\<inter> \\<Inter>A \\<noteq> {})\"\n  (is \"_ \\<longleftrightarrow> ?R\")\nproof (safe intro!: compact_eq_Heine_Borel[THEN iffD2])\n  fix A\n  assume \"compact U\"\n  assume A: \"\\<forall>a\\<in>A. closed a\" \"U \\<inter> \\<Inter>A = {}\"\n  assume fin: \"\\<forall>B \\<subseteq> A. finite B \\<longrightarrow> U \\<inter> \\<Inter>B \\<noteq> {}\"\n  from A have \"(\\<forall>a\\<in>uminus`A. open a) \\<and> U \\<subseteq> \\<Union>(uminus`A)\"\n    by auto\n  with \\<open>compact U\\<close> obtain B where \"B \\<subseteq> A\" \"finite (uminus`B)\" \"U \\<subseteq> \\<Union>(uminus`B)\"\n    unfolding compact_eq_Heine_Borel by (metis subset_image_iff)\n  with fin[THEN spec, of B] show False\n    by (auto dest: finite_imageD intro: inj_setminus)\nnext\n  fix A\n  assume ?R\n  assume \"\\<forall>a\\<in>A. open a\" \"U \\<subseteq> \\<Union>A\"\n  then have \"U \\<inter> \\<Inter>(uminus`A) = {}\" \"\\<forall>a\\<in>uminus`A. closed a\"\n    by auto\n  with \\<open>?R\\<close> obtain B where \"B \\<subseteq> A\" \"finite (uminus`B)\" \"U \\<inter> \\<Inter>(uminus`B) = {}\"\n    by (metis subset_image_iff)\n  then show \"\\<exists>T\\<subseteq>A. finite T \\<and> U \\<subseteq> \\<Union>T\"\n    by (auto intro!: exI[of _ B] inj_setminus dest: finite_imageD)\nqed\n\nlemma compact_imp_fip:\n  assumes \"compact S\"\n    and \"\\<And>T. T \\<in> F \\<Longrightarrow> closed T\"\n    and \"\\<And>F'. finite F' \\<Longrightarrow> F' \\<subseteq> F \\<Longrightarrow> S \\<inter> (\\<Inter>F') \\<noteq> {}\"\n  shows \"S \\<inter> (\\<Inter>F) \\<noteq> {}\"\n  using assms unfolding compact_fip by auto\n\nlemma compact_imp_fip_image:\n  assumes \"compact s\"\n    and P: \"\\<And>i. i \\<in> I \\<Longrightarrow> closed (f i)\"\n    and Q: \"\\<And>I'. finite I' \\<Longrightarrow> I' \\<subseteq> I \\<Longrightarrow> (s \\<inter> (\\<Inter>i\\<in>I'. f i) \\<noteq> {})\"\n  shows \"s \\<inter> (\\<Inter>i\\<in>I. f i) \\<noteq> {}\"\nproof -\n  from P have \"\\<forall>i \\<in> f ` I. closed i\"\n    by blast\n  moreover have \"\\<forall>A. finite A \\<and> A \\<subseteq> f ` I \\<longrightarrow> (s \\<inter> (\\<Inter>A) \\<noteq> {})\"\n    by (metis Q finite_subset_image)\n  ultimately show \"s \\<inter> (\\<Inter>(f ` I)) \\<noteq> {}\"\n    by (metis \\<open>compact s\\<close> compact_imp_fip)\nqed\n\nend\n\nlemma (in t2_space) compact_imp_closed:\n  assumes \"compact s\"\n  shows \"closed s\"\n  unfolding closed_def\nproof (rule openI)\n  fix y\n  assume \"y \\<in> - s\"\n  let ?C = \"\\<Union>x\\<in>s. {u. open u \\<and> x \\<in> u \\<and> eventually (\\<lambda>y. y \\<notin> u) (nhds y)}\"\n  have \"s \\<subseteq> \\<Union>?C\"\n  proof\n    fix x\n    assume \"x \\<in> s\"\n    with \\<open>y \\<in> - s\\<close> have \"x \\<noteq> y\" by clarsimp\n    then have \"\\<exists>u v. open u \\<and> open v \\<and> x \\<in> u \\<and> y \\<in> v \\<and> u \\<inter> v = {}\"\n      by (rule hausdorff)\n    with \\<open>x \\<in> s\\<close> show \"x \\<in> \\<Union>?C\"\n      unfolding eventually_nhds by auto\n  qed\n  then obtain D where \"D \\<subseteq> ?C\" and \"finite D\" and \"s \\<subseteq> \\<Union>D\"\n    by (rule compactE [OF \\<open>compact s\\<close>]) auto\n  from \\<open>D \\<subseteq> ?C\\<close> have \"\\<forall>x\\<in>D. eventually (\\<lambda>y. y \\<notin> x) (nhds y)\"\n    by auto\n  with \\<open>finite D\\<close> have \"eventually (\\<lambda>y. y \\<notin> \\<Union>D) (nhds y)\"\n    by (simp add: eventually_ball_finite)\n  with \\<open>s \\<subseteq> \\<Union>D\\<close> have \"eventually (\\<lambda>y. y \\<notin> s) (nhds y)\"\n    by (auto elim!: eventually_mono)\n  then show \"\\<exists>t. open t \\<and> y \\<in> t \\<and> t \\<subseteq> - s\"\n    by (simp add: eventually_nhds subset_eq)\nqed\n\nlemma compact_continuous_image:\n  assumes f: \"continuous_on s f\"\n    and s: \"compact s\"\n  shows \"compact (f ` s)\"\nproof (rule compactI)\n  fix C\n  assume \"\\<forall>c\\<in>C. open c\" and cover: \"f`s \\<subseteq> \\<Union>C\"\n  with f have \"\\<forall>c\\<in>C. \\<exists>A. open A \\<and> A \\<inter> s = f -` c \\<inter> s\"\n    unfolding continuous_on_open_invariant by blast\n  then obtain A where A: \"\\<forall>c\\<in>C. open (A c) \\<and> A c \\<inter> s = f -` c \\<inter> s\"\n    unfolding bchoice_iff ..\n  with cover have \"\\<And>c. c \\<in> C \\<Longrightarrow> open (A c)\" \"s \\<subseteq> (\\<Union>c\\<in>C. A c)\"\n    by (fastforce simp add: subset_eq set_eq_iff)+\n  from compactE_image[OF s this] obtain D where \"D \\<subseteq> C\" \"finite D\" \"s \\<subseteq> (\\<Union>c\\<in>D. A c)\" .\n  with A show \"\\<exists>D \\<subseteq> C. finite D \\<and> f`s \\<subseteq> \\<Union>D\"\n    by (intro exI[of _ D]) (fastforce simp add: subset_eq set_eq_iff)+\nqed\n\nlemma continuous_on_inv:\n  fixes f :: \"'a::topological_space \\<Rightarrow> 'b::t2_space\"\n  assumes \"continuous_on s f\"\n    and \"compact s\"\n    and \"\\<forall>x\\<in>s. g (f x) = x\"\n  shows \"continuous_on (f ` s) g\"\n  unfolding continuous_on_topological\nproof (clarsimp simp add: assms(3))\n  fix x :: 'a and B :: \"'a set\"\n  assume \"x \\<in> s\" and \"open B\" and \"x \\<in> B\"\n  have 1: \"\\<forall>x\\<in>s. f x \\<in> f ` (s - B) \\<longleftrightarrow> x \\<in> s - B\"\n    using assms(3) by (auto, metis)\n  have \"continuous_on (s - B) f\"\n    using \\<open>continuous_on s f\\<close> Diff_subset\n    by (rule continuous_on_subset)\n  moreover have \"compact (s - B)\"\n    using \\<open>open B\\<close> and \\<open>compact s\\<close>\n    unfolding Diff_eq by (intro compact_Int_closed closed_Compl)\n  ultimately have \"compact (f ` (s - B))\"\n    by (rule compact_continuous_image)\n  then have \"closed (f ` (s - B))\"\n    by (rule compact_imp_closed)\n  then have \"open (- f ` (s - B))\"\n    by (rule open_Compl)\n  moreover have \"f x \\<in> - f ` (s - B)\"\n    using \\<open>x \\<in> s\\<close> and \\<open>x \\<in> B\\<close> by (simp add: 1)\n  moreover have \"\\<forall>y\\<in>s. f y \\<in> - f ` (s - B) \\<longrightarrow> y \\<in> B\"\n    by (simp add: 1)\n  ultimately show \"\\<exists>A. open A \\<and> f x \\<in> A \\<and> (\\<forall>y\\<in>s. f y \\<in> A \\<longrightarrow> y \\<in> B)\"\n    by fast\nqed\n\nlemma continuous_on_inv_into:\n  fixes f :: \"'a::topological_space \\<Rightarrow> 'b::t2_space\"\n  assumes s: \"continuous_on s f\" \"compact s\"\n    and f: \"inj_on f s\"\n  shows \"continuous_on (f ` s) (the_inv_into s f)\"\n  by (rule continuous_on_inv[OF s]) (auto simp: the_inv_into_f_f[OF f])\n\nlemma (in linorder_topology) compact_attains_sup:\n  assumes \"compact S\" \"S \\<noteq> {}\"\n  shows \"\\<exists>s\\<in>S. \\<forall>t\\<in>S. t \\<le> s\"\nproof (rule classical)\n  assume \"\\<not> (\\<exists>s\\<in>S. \\<forall>t\\<in>S. t \\<le> s)\"\n  then obtain t where t: \"\\<forall>s\\<in>S. t s \\<in> S\" and \"\\<forall>s\\<in>S. s < t s\"\n    by (metis not_le)\n  then have \"\\<And>s. s\\<in>S \\<Longrightarrow> open {..< t s}\" \"S \\<subseteq> (\\<Union>s\\<in>S. {..< t s})\"\n    by auto\n  with \\<open>compact S\\<close> obtain C where \"C \\<subseteq> S\" \"finite C\" and C: \"S \\<subseteq> (\\<Union>s\\<in>C. {..< t s})\"\n    by (metis compactE_image)\n  with \\<open>S \\<noteq> {}\\<close> have Max: \"Max (t`C) \\<in> t`C\" and \"\\<forall>s\\<in>t`C. s \\<le> Max (t`C)\"\n    by (auto intro!: Max_in)\n  with C have \"S \\<subseteq> {..< Max (t`C)}\"\n    by (auto intro: less_le_trans simp: subset_eq)\n  with t Max \\<open>C \\<subseteq> S\\<close> show ?thesis\n    by fastforce\nqed\n\nlemma (in linorder_topology) compact_attains_inf:\n  assumes \"compact S\" \"S \\<noteq> {}\"\n  shows \"\\<exists>s\\<in>S. \\<forall>t\\<in>S. s \\<le> t\"\nproof (rule classical)\n  assume \"\\<not> (\\<exists>s\\<in>S. \\<forall>t\\<in>S. s \\<le> t)\"\n  then obtain t where t: \"\\<forall>s\\<in>S. t s \\<in> S\" and \"\\<forall>s\\<in>S. t s < s\"\n    by (metis not_le)\n  then have \"\\<And>s. s\\<in>S \\<Longrightarrow> open {t s <..}\" \"S \\<subseteq> (\\<Union>s\\<in>S. {t s <..})\"\n    by auto\n  with \\<open>compact S\\<close> obtain C where \"C \\<subseteq> S\" \"finite C\" and C: \"S \\<subseteq> (\\<Union>s\\<in>C. {t s <..})\"\n    by (metis compactE_image)\n  with \\<open>S \\<noteq> {}\\<close> have Min: \"Min (t`C) \\<in> t`C\" and \"\\<forall>s\\<in>t`C. Min (t`C) \\<le> s\"\n    by (auto intro!: Min_in)\n  with C have \"S \\<subseteq> {Min (t`C) <..}\"\n    by (auto intro: le_less_trans simp: subset_eq)\n  with t Min \\<open>C \\<subseteq> S\\<close> show ?thesis\n    by fastforce\nqed\n\nlemma continuous_attains_sup:\n  fixes f :: \"'a::topological_space \\<Rightarrow> 'b::linorder_topology\"\n  shows \"compact s \\<Longrightarrow> s \\<noteq> {} \\<Longrightarrow> continuous_on s f \\<Longrightarrow> (\\<exists>x\\<in>s. \\<forall>y\\<in>s.  f y \\<le> f x)\"\n  using compact_attains_sup[of \"f ` s\"] compact_continuous_image[of s f] by auto\n\nlemma continuous_attains_inf:\n  fixes f :: \"'a::topological_space \\<Rightarrow> 'b::linorder_topology\"\n  shows \"compact s \\<Longrightarrow> s \\<noteq> {} \\<Longrightarrow> continuous_on s f \\<Longrightarrow> (\\<exists>x\\<in>s. \\<forall>y\\<in>s. f x \\<le> f y)\"\n  using compact_attains_inf[of \"f ` s\"] compact_continuous_image[of s f] by auto\n\n\nsubsection \\<open>Connectedness\\<close>\n\ncontext topological_space\nbegin\n\ndefinition \"connected S \\<longleftrightarrow>\n  \\<not> (\\<exists>A B. open A \\<and> open B \\<and> S \\<subseteq> A \\<union> B \\<and> A \\<inter> B \\<inter> S = {} \\<and> A \\<inter> S \\<noteq> {} \\<and> B \\<inter> S \\<noteq> {})\"\n\nlemma connectedI:\n  \"(\\<And>A B. open A \\<Longrightarrow> open B \\<Longrightarrow> A \\<inter> U \\<noteq> {} \\<Longrightarrow> B \\<inter> U \\<noteq> {} \\<Longrightarrow> A \\<inter> B \\<inter> U = {} \\<Longrightarrow> U \\<subseteq> A \\<union> B \\<Longrightarrow> False)\n  \\<Longrightarrow> connected U\"\n  by (auto simp: connected_def)\n\nlemma connected_empty [simp]: \"connected {}\"\n  by (auto intro!: connectedI)\n\nlemma connected_sing [simp]: \"connected {x}\"\n  by (auto intro!: connectedI)\n\nlemma connectedD:\n  \"connected A \\<Longrightarrow> open U \\<Longrightarrow> open V \\<Longrightarrow> U \\<inter> V \\<inter> A = {} \\<Longrightarrow> A \\<subseteq> U \\<union> V \\<Longrightarrow> U \\<inter> A = {} \\<or> V \\<inter> A = {}\"\n  by (auto simp: connected_def)\n\nend\n\nlemma connected_closed:\n  \"connected s \\<longleftrightarrow>\n    \\<not> (\\<exists>A B. closed A \\<and> closed B \\<and> s \\<subseteq> A \\<union> B \\<and> A \\<inter> B \\<inter> s = {} \\<and> A \\<inter> s \\<noteq> {} \\<and> B \\<inter> s \\<noteq> {})\"\n  apply (simp add: connected_def del: ex_simps, safe)\n   apply (drule_tac x=\"-A\" in spec)\n   apply (drule_tac x=\"-B\" in spec)\n   apply (fastforce simp add: closed_def [symmetric])\n  apply (drule_tac x=\"-A\" in spec)\n  apply (drule_tac x=\"-B\" in spec)\n  apply (fastforce simp add: open_closed [symmetric])\n  done\n\nlemma connected_closedD:\n  \"\\<lbrakk>connected s; A \\<inter> B \\<inter> s = {}; s \\<subseteq> A \\<union> B; closed A; closed B\\<rbrakk> \\<Longrightarrow> A \\<inter> s = {} \\<or> B \\<inter> s = {}\"\n  by (simp add: connected_closed)\n\nlemma connected_Union:\n  assumes cs: \"\\<And>s. s \\<in> S \\<Longrightarrow> connected s\"\n    and ne: \"\\<Inter>S \\<noteq> {}\"\n  shows \"connected(\\<Union>S)\"\nproof (rule connectedI)\n  fix A B\n  assume A: \"open A\" and B: \"open B\" and Alap: \"A \\<inter> \\<Union>S \\<noteq> {}\" and Blap: \"B \\<inter> \\<Union>S \\<noteq> {}\"\n    and disj: \"A \\<inter> B \\<inter> \\<Union>S = {}\" and cover: \"\\<Union>S \\<subseteq> A \\<union> B\"\n  have disjs:\"\\<And>s. s \\<in> S \\<Longrightarrow> A \\<inter> B \\<inter> s = {}\"\n    using disj by auto\n  obtain sa where sa: \"sa \\<in> S\" \"A \\<inter> sa \\<noteq> {}\"\n    using Alap by auto\n  obtain sb where sb: \"sb \\<in> S\" \"B \\<inter> sb \\<noteq> {}\"\n    using Blap by auto\n  obtain x where x: \"\\<And>s. s \\<in> S \\<Longrightarrow> x \\<in> s\"\n    using ne by auto\n  then have \"x \\<in> \\<Union>S\"\n    using \\<open>sa \\<in> S\\<close> by blast\n  then have \"x \\<in> A \\<or> x \\<in> B\"\n    using cover by auto\n  then show False\n    using cs [unfolded connected_def]\n    by (metis A B IntI Sup_upper sa sb disjs x cover empty_iff subset_trans)\nqed\n\nlemma connected_Un: \"connected s \\<Longrightarrow> connected t \\<Longrightarrow> s \\<inter> t \\<noteq> {} \\<Longrightarrow> connected (s \\<union> t)\"\n  using connected_Union [of \"{s,t}\"] by auto\n\nlemma connected_diff_open_from_closed:\n  assumes st: \"s \\<subseteq> t\"\n    and tu: \"t \\<subseteq> u\"\n    and s: \"open s\"\n    and t: \"closed t\"\n    and u: \"connected u\"\n    and ts: \"connected (t - s)\"\n  shows \"connected(u - s)\"\nproof (rule connectedI)\n  fix A B\n  assume AB: \"open A\" \"open B\" \"A \\<inter> (u - s) \\<noteq> {}\" \"B \\<inter> (u - s) \\<noteq> {}\"\n    and disj: \"A \\<inter> B \\<inter> (u - s) = {}\"\n    and cover: \"u - s \\<subseteq> A \\<union> B\"\n  then consider \"A \\<inter> (t - s) = {}\" | \"B \\<inter> (t - s) = {}\"\n    using st ts tu connectedD [of \"t-s\" \"A\" \"B\"] by auto\n  then show False\n  proof cases\n    case 1\n    then have \"(A - t) \\<inter> (B \\<union> s) \\<inter> u = {}\"\n      using disj st by auto\n    moreover have \"u \\<subseteq> (A - t) \\<union> (B \\<union> s)\"\n      using 1 cover by auto\n    ultimately show False\n      using connectedD [of u \"A - t\" \"B \\<union> s\"] AB s t 1 u by auto\n  next\n    case 2\n    then have \"(A \\<union> s) \\<inter> (B - t) \\<inter> u = {}\"\n      using disj st by auto\n    moreover have \"u \\<subseteq> (A \\<union> s) \\<union> (B - t)\"\n      using 2 cover by auto\n    ultimately show False\n      using connectedD [of u \"A \\<union> s\" \"B - t\"] AB s t 2 u by auto\n  qed\nqed\n\nlemma connected_iff_const:\n  fixes S :: \"'a::topological_space set\"\n  shows \"connected S \\<longleftrightarrow> (\\<forall>P::'a \\<Rightarrow> bool. continuous_on S P \\<longrightarrow> (\\<exists>c. \\<forall>s\\<in>S. P s = c))\"\nproof safe\n  fix P :: \"'a \\<Rightarrow> bool\"\n  assume \"connected S\" \"continuous_on S P\"\n  then have \"\\<And>b. \\<exists>A. open A \\<and> A \\<inter> S = P -` {b} \\<inter> S\"\n    unfolding continuous_on_open_invariant by (simp add: open_discrete)\n  from this[of True] this[of False]\n  obtain t f where \"open t\" \"open f\" and *: \"f \\<inter> S = P -` {False} \\<inter> S\" \"t \\<inter> S = P -` {True} \\<inter> S\"\n    by meson\n  then have \"t \\<inter> S = {} \\<or> f \\<inter> S = {}\"\n    by (intro connectedD[OF \\<open>connected S\\<close>])  auto\n  then show \"\\<exists>c. \\<forall>s\\<in>S. P s = c\"\n  proof (rule disjE)\n    assume \"t \\<inter> S = {}\"\n    then show ?thesis\n      unfolding * by (intro exI[of _ False]) auto\n  next\n    assume \"f \\<inter> S = {}\"\n    then show ?thesis\n      unfolding * by (intro exI[of _ True]) auto\n  qed\nnext\n  assume P: \"\\<forall>P::'a \\<Rightarrow> bool. continuous_on S P \\<longrightarrow> (\\<exists>c. \\<forall>s\\<in>S. P s = c)\"\n  show \"connected S\"\n  proof (rule connectedI)\n    fix A B\n    assume *: \"open A\" \"open B\" \"A \\<inter> S \\<noteq> {}\" \"B \\<inter> S \\<noteq> {}\" \"A \\<inter> B \\<inter> S = {}\" \"S \\<subseteq> A \\<union> B\"\n    have \"continuous_on S (\\<lambda>x. x \\<in> A)\"\n      unfolding continuous_on_open_invariant\n    proof safe\n      fix C :: \"bool set\"\n      have \"C = UNIV \\<or> C = {True} \\<or> C = {False} \\<or> C = {}\"\n        using subset_UNIV[of C] unfolding UNIV_bool by auto\n      with * show \"\\<exists>T. open T \\<and> T \\<inter> S = (\\<lambda>x. x \\<in> A) -` C \\<inter> S\"\n        by (intro exI[of _ \"(if True \\<in> C then A else {}) \\<union> (if False \\<in> C then B else {})\"]) auto\n    qed\n    from P[rule_format, OF this] obtain c where \"\\<And>s. s \\<in> S \\<Longrightarrow> (s \\<in> A) = c\"\n      by blast\n    with * show False\n      by (cases c) auto\n  qed\nqed\n\nlemma connectedD_const: \"connected S \\<Longrightarrow> continuous_on S P \\<Longrightarrow> \\<exists>c. \\<forall>s\\<in>S. P s = c\"\n  for P :: \"'a::topological_space \\<Rightarrow> bool\"\n  by (auto simp: connected_iff_const)\n\nlemma connectedI_const:\n  \"(\\<And>P::'a::topological_space \\<Rightarrow> bool. continuous_on S P \\<Longrightarrow> \\<exists>c. \\<forall>s\\<in>S. P s = c) \\<Longrightarrow> connected S\"\n  by (auto simp: connected_iff_const)\n\nlemma connected_local_const:\n  assumes \"connected A\" \"a \\<in> A\" \"b \\<in> A\"\n    and *: \"\\<forall>a\\<in>A. eventually (\\<lambda>b. f a = f b) (at a within A)\"\n  shows \"f a = f b\"\nproof -\n  obtain S where S: \"\\<And>a. a \\<in> A \\<Longrightarrow> a \\<in> S a\" \"\\<And>a. a \\<in> A \\<Longrightarrow> open (S a)\"\n    \"\\<And>a x. a \\<in> A \\<Longrightarrow> x \\<in> S a \\<Longrightarrow> x \\<in> A \\<Longrightarrow> f a = f x\"\n    using * unfolding eventually_at_topological by metis\n  let ?P = \"\\<Union>b\\<in>{b\\<in>A. f a = f b}. S b\" and ?N = \"\\<Union>b\\<in>{b\\<in>A. f a \\<noteq> f b}. S b\"\n  have \"?P \\<inter> A = {} \\<or> ?N \\<inter> A = {}\"\n    using \\<open>connected A\\<close> S \\<open>a\\<in>A\\<close>\n    by (intro connectedD) (auto, metis)\n  then show \"f a = f b\"\n  proof\n    assume \"?N \\<inter> A = {}\"\n    then have \"\\<forall>x\\<in>A. f a = f x\"\n      using S(1) by auto\n    with \\<open>b\\<in>A\\<close> show ?thesis by auto\n  next\n    assume \"?P \\<inter> A = {}\" then show ?thesis\n      using \\<open>a \\<in> A\\<close> S(1)[of a] by auto\n  qed\nqed\n\nlemma (in linorder_topology) connectedD_interval:\n  assumes \"connected U\"\n    and xy: \"x \\<in> U\" \"y \\<in> U\"\n    and \"x \\<le> z\" \"z \\<le> y\"\n  shows \"z \\<in> U\"\nproof -\n  have eq: \"{..<z} \\<union> {z<..} = - {z}\"\n    by auto\n  have \"\\<not> connected U\" if \"z \\<notin> U\" \"x < z\" \"z < y\"\n    using xy that\n    apply (simp only: connected_def simp_thms)\n    apply (rule_tac exI[of _ \"{..< z}\"])\n    apply (rule_tac exI[of _ \"{z <..}\"])\n    apply (auto simp add: eq)\n    done\n  with assms show \"z \\<in> U\"\n    by (metis less_le)\nqed\n\nlemma (in linorder_topology) not_in_connected_cases:\n  assumes conn: \"connected S\"\n  assumes nbdd: \"x \\<notin> S\"\n  assumes ne: \"S \\<noteq> {}\"\n  obtains \"bdd_above S\" \"\\<And>y. y \\<in> S \\<Longrightarrow> x \\<ge> y\" | \"bdd_below S\" \"\\<And>y. y \\<in> S \\<Longrightarrow> x \\<le> y\"\nproof -\n  obtain s where \"s \\<in> S\" using ne by blast\n  {\n    assume \"s \\<le> x\"\n    have \"False\" if \"x \\<le> y\" \"y \\<in> S\" for y\n      using connectedD_interval[OF conn \\<open>s \\<in> S\\<close> \\<open>y \\<in> S\\<close> \\<open>s \\<le> x\\<close> \\<open>x \\<le> y\\<close>] \\<open>x \\<notin> S\\<close>\n      by simp\n    then have wit: \"y \\<in> S \\<Longrightarrow> x \\<ge> y\" for y\n      using le_cases by blast\n    then have \"bdd_above S\"\n      by (rule local.bdd_aboveI)\n    note this wit\n  } moreover {\n    assume \"x \\<le> s\"\n    have \"False\" if \"x \\<ge> y\" \"y \\<in> S\" for y\n      using connectedD_interval[OF conn \\<open>y \\<in> S\\<close> \\<open>s \\<in> S\\<close> \\<open>x \\<ge> y\\<close> \\<open>s \\<ge> x\\<close> ] \\<open>x \\<notin> S\\<close>\n      by simp\n    then have wit: \"y \\<in> S \\<Longrightarrow> x \\<le> y\" for y\n      using le_cases by blast\n    then have \"bdd_below S\"\n      by (rule bdd_belowI)\n    note this wit\n  } ultimately show ?thesis\n    by (meson le_cases that)\nqed\n\nlemma connected_continuous_image:\n  assumes *: \"continuous_on s f\"\n    and \"connected s\"\n  shows \"connected (f ` s)\"\nproof (rule connectedI_const)\n  fix P :: \"'b \\<Rightarrow> bool\"\n  assume \"continuous_on (f ` s) P\"\n  then have \"continuous_on s (P \\<circ> f)\"\n    by (rule continuous_on_compose[OF *])\n  from connectedD_const[OF \\<open>connected s\\<close> this] show \"\\<exists>c. \\<forall>s\\<in>f ` s. P s = c\"\n    by auto\nqed\n\nlemma connected_Un_UN:\n  assumes \"connected A\" \"\\<And>X. X \\<in> B \\<Longrightarrow> connected X\" \"\\<And>X. X \\<in> B \\<Longrightarrow> A \\<inter> X \\<noteq> {}\"\n  shows   \"connected (A \\<union> \\<Union>B)\"\nproof (rule connectedI_const)\n  fix f :: \"'a \\<Rightarrow> bool\"\n  assume f: \"continuous_on (A \\<union> \\<Union>B) f\"\n  have \"connected A\" \"continuous_on A f\"\n    by (auto intro: assms continuous_on_subset[OF f(1)])\n  from connectedD_const[OF this] obtain c where c: \"\\<And>x. x \\<in> A \\<Longrightarrow> f x = c\"\n    by metis\n  have \"f x = c\" if \"x \\<in> X\" \"X \\<in> B\" for x X\n  proof -\n    have \"connected X\" \"continuous_on X f\"\n      using that by (auto intro: assms continuous_on_subset[OF f])\n    from connectedD_const[OF this] obtain c' where c': \"\\<And>x. x \\<in> X \\<Longrightarrow> f x = c'\"\n      by metis\n    from assms(3) and that obtain y where \"y \\<in> A \\<inter> X\"\n      by auto\n    with c[of y] c'[of y] c'[of x] that show ?thesis\n      by auto\n  qed\n  with c show \"\\<exists>c. \\<forall>x\\<in>A \\<union> \\<Union> B. f x = c\"\n    by (intro exI[of _ c]) auto\nqed   \n\nsection \\<open>Linear Continuum Topologies\\<close>\n\nclass linear_continuum_topology = linorder_topology + linear_continuum\nbegin\n\nlemma Inf_notin_open:\n  assumes A: \"open A\"\n    and bnd: \"\\<forall>a\\<in>A. x < a\"\n  shows \"Inf A \\<notin> A\"\nproof\n  assume \"Inf A \\<in> A\"\n  then obtain b where \"b < Inf A\" \"{b <.. Inf A} \\<subseteq> A\"\n    using open_left[of A \"Inf A\" x] assms by auto\n  with dense[of b \"Inf A\"] obtain c where \"c < Inf A\" \"c \\<in> A\"\n    by (auto simp: subset_eq)\n  then show False\n    using cInf_lower[OF \\<open>c \\<in> A\\<close>] bnd\n    by (metis not_le less_imp_le bdd_belowI)\nqed\n\nlemma Sup_notin_open:\n  assumes A: \"open A\"\n    and bnd: \"\\<forall>a\\<in>A. a < x\"\n  shows \"Sup A \\<notin> A\"\nproof\n  assume \"Sup A \\<in> A\"\n  with assms obtain b where \"Sup A < b\" \"{Sup A ..< b} \\<subseteq> A\"\n    using open_right[of A \"Sup A\" x] by auto\n  with dense[of \"Sup A\" b] obtain c where \"Sup A < c\" \"c \\<in> A\"\n    by (auto simp: subset_eq)\n  then show False\n    using cSup_upper[OF \\<open>c \\<in> A\\<close>] bnd\n    by (metis less_imp_le not_le bdd_aboveI)\nqed\n\nend\n\ninstance linear_continuum_topology \\<subseteq> perfect_space\nproof\n  fix x :: 'a\n  obtain y where \"x < y \\<or> y < x\"\n    using ex_gt_or_lt [of x] ..\n  with Inf_notin_open[of \"{x}\" y] Sup_notin_open[of \"{x}\" y] show \"\\<not> open {x}\"\n    by auto\nqed\n\nlemma connectedI_interval:\n  fixes U :: \"'a :: linear_continuum_topology set\"\n  assumes *: \"\\<And>x y z. x \\<in> U \\<Longrightarrow> y \\<in> U \\<Longrightarrow> x \\<le> z \\<Longrightarrow> z \\<le> y \\<Longrightarrow> z \\<in> U\"\n  shows \"connected U\"\nproof (rule connectedI)\n  {\n    fix A B\n    assume \"open A\" \"open B\" \"A \\<inter> B \\<inter> U = {}\" \"U \\<subseteq> A \\<union> B\"\n    fix x y\n    assume \"x < y\" \"x \\<in> A\" \"y \\<in> B\" \"x \\<in> U\" \"y \\<in> U\"\n\n    let ?z = \"Inf (B \\<inter> {x <..})\"\n\n    have \"x \\<le> ?z\" \"?z \\<le> y\"\n      using \\<open>y \\<in> B\\<close> \\<open>x < y\\<close> by (auto intro: cInf_lower cInf_greatest)\n    with \\<open>x \\<in> U\\<close> \\<open>y \\<in> U\\<close> have \"?z \\<in> U\"\n      by (rule *)\n    moreover have \"?z \\<notin> B \\<inter> {x <..}\"\n      using \\<open>open B\\<close> by (intro Inf_notin_open) auto\n    ultimately have \"?z \\<in> A\"\n      using \\<open>x \\<le> ?z\\<close> \\<open>A \\<inter> B \\<inter> U = {}\\<close> \\<open>x \\<in> A\\<close> \\<open>U \\<subseteq> A \\<union> B\\<close> by auto\n    have \"\\<exists>b\\<in>B. b \\<in> A \\<and> b \\<in> U\" if \"?z < y\"\n    proof -\n      obtain a where \"?z < a\" \"{?z ..< a} \\<subseteq> A\"\n        using open_right[OF \\<open>open A\\<close> \\<open>?z \\<in> A\\<close> \\<open>?z < y\\<close>] by auto\n      moreover obtain b where \"b \\<in> B\" \"x < b\" \"b < min a y\"\n        using cInf_less_iff[of \"B \\<inter> {x <..}\" \"min a y\"] \\<open>?z < a\\<close> \\<open>?z < y\\<close> \\<open>x < y\\<close> \\<open>y \\<in> B\\<close>\n        by auto\n      moreover have \"?z \\<le> b\"\n        using \\<open>b \\<in> B\\<close> \\<open>x < b\\<close>\n        by (intro cInf_lower) auto\n      moreover have \"b \\<in> U\"\n        using \\<open>x \\<le> ?z\\<close> \\<open>?z \\<le> b\\<close> \\<open>b < min a y\\<close>\n        by (intro *[OF \\<open>x \\<in> U\\<close> \\<open>y \\<in> U\\<close>]) (auto simp: less_imp_le)\n      ultimately show ?thesis\n        by (intro bexI[of _ b]) auto\n    qed\n    then have False\n      using \\<open>?z \\<le> y\\<close> \\<open>?z \\<in> A\\<close> \\<open>y \\<in> B\\<close> \\<open>y \\<in> U\\<close> \\<open>A \\<inter> B \\<inter> U = {}\\<close>\n      unfolding le_less by blast\n  }\n  note not_disjoint = this\n\n  fix A B assume AB: \"open A\" \"open B\" \"U \\<subseteq> A \\<union> B\" \"A \\<inter> B \\<inter> U = {}\"\n  moreover assume \"A \\<inter> U \\<noteq> {}\" then obtain x where x: \"x \\<in> U\" \"x \\<in> A\" by auto\n  moreover assume \"B \\<inter> U \\<noteq> {}\" then obtain y where y: \"y \\<in> U\" \"y \\<in> B\" by auto\n  moreover note not_disjoint[of B A y x] not_disjoint[of A B x y]\n  ultimately show False\n    by (cases x y rule: linorder_cases) auto\nqed\n\nlemma connected_iff_interval: \"connected U \\<longleftrightarrow> (\\<forall>x\\<in>U. \\<forall>y\\<in>U. \\<forall>z. x \\<le> z \\<longrightarrow> z \\<le> y \\<longrightarrow> z \\<in> U)\"\n  for U :: \"'a::linear_continuum_topology set\"\n  by (auto intro: connectedI_interval dest: connectedD_interval)\n\nlemma connected_UNIV[simp]: \"connected (UNIV::'a::linear_continuum_topology set)\"\n  by (simp add: connected_iff_interval)\n\nlemma connected_Ioi[simp]: \"connected {a<..}\"\n  for a :: \"'a::linear_continuum_topology\"\n  by (auto simp: connected_iff_interval)\n\nlemma connected_Ici[simp]: \"connected {a..}\"\n  for a :: \"'a::linear_continuum_topology\"\n  by (auto simp: connected_iff_interval)\n\nlemma connected_Iio[simp]: \"connected {..<a}\"\n  for a :: \"'a::linear_continuum_topology\"\n  by (auto simp: connected_iff_interval)\n\nlemma connected_Iic[simp]: \"connected {..a}\"\n  for a :: \"'a::linear_continuum_topology\"\n  by (auto simp: connected_iff_interval)\n\nlemma connected_Ioo[simp]: \"connected {a<..<b}\"\n  for a b :: \"'a::linear_continuum_topology\"\n  unfolding connected_iff_interval by auto\n\nlemma connected_Ioc[simp]: \"connected {a<..b}\"\n  for a b :: \"'a::linear_continuum_topology\"\n  by (auto simp: connected_iff_interval)\n\nlemma connected_Ico[simp]: \"connected {a..<b}\"\n  for a b :: \"'a::linear_continuum_topology\"\n  by (auto simp: connected_iff_interval)\n\nlemma connected_Icc[simp]: \"connected {a..b}\"\n  for a b :: \"'a::linear_continuum_topology\"\n  by (auto simp: connected_iff_interval)\n\nlemma connected_contains_Ioo:\n  fixes A :: \"'a :: linorder_topology set\"\n  assumes \"connected A\" \"a \\<in> A\" \"b \\<in> A\" shows \"{a <..< b} \\<subseteq> A\"\n  using connectedD_interval[OF assms] by (simp add: subset_eq Ball_def less_imp_le)\n\nlemma connected_contains_Icc:\n  fixes A :: \"'a::linorder_topology set\"\n  assumes \"connected A\" \"a \\<in> A\" \"b \\<in> A\"\n  shows \"{a..b} \\<subseteq> A\"\nproof\n  fix x assume \"x \\<in> {a..b}\"\n  then have \"x = a \\<or> x = b \\<or> x \\<in> {a<..<b}\"\n    by auto\n  then show \"x \\<in> A\"\n    using assms connected_contains_Ioo[of A a b] by auto\nqed\n\n\nsubsection \\<open>Intermediate Value Theorem\\<close>\n\nlemma IVT':\n  fixes f :: \"'a::linear_continuum_topology \\<Rightarrow> 'b::linorder_topology\"\n  assumes y: \"f a \\<le> y\" \"y \\<le> f b\" \"a \\<le> b\"\n    and *: \"continuous_on {a .. b} f\"\n  shows \"\\<exists>x. a \\<le> x \\<and> x \\<le> b \\<and> f x = y\"\nproof -\n  have \"connected {a..b}\"\n    unfolding connected_iff_interval by auto\n  from connected_continuous_image[OF * this, THEN connectedD_interval, of \"f a\" \"f b\" y] y\n  show ?thesis\n    by (auto simp add: atLeastAtMost_def atLeast_def atMost_def)\nqed\n\nlemma IVT2':\n  fixes f :: \"'a :: linear_continuum_topology \\<Rightarrow> 'b :: linorder_topology\"\n  assumes y: \"f b \\<le> y\" \"y \\<le> f a\" \"a \\<le> b\"\n    and *: \"continuous_on {a .. b} f\"\n  shows \"\\<exists>x. a \\<le> x \\<and> x \\<le> b \\<and> f x = y\"\nproof -\n  have \"connected {a..b}\"\n    unfolding connected_iff_interval by auto\n  from connected_continuous_image[OF * this, THEN connectedD_interval, of \"f b\" \"f a\" y] y\n  show ?thesis\n    by (auto simp add: atLeastAtMost_def atLeast_def atMost_def)\nqed\n\nlemma IVT:\n  fixes f :: \"'a::linear_continuum_topology \\<Rightarrow> 'b::linorder_topology\"\n  shows \"f a \\<le> y \\<Longrightarrow> y \\<le> f b \\<Longrightarrow> a \\<le> b \\<Longrightarrow> (\\<forall>x. a \\<le> x \\<and> x \\<le> b \\<longrightarrow> isCont f x) \\<Longrightarrow>\n    \\<exists>x. a \\<le> x \\<and> x \\<le> b \\<and> f x = y\"\n  by (rule IVT') (auto intro: continuous_at_imp_continuous_on)\n\nlemma IVT2:\n  fixes f :: \"'a::linear_continuum_topology \\<Rightarrow> 'b::linorder_topology\"\n  shows \"f b \\<le> y \\<Longrightarrow> y \\<le> f a \\<Longrightarrow> a \\<le> b \\<Longrightarrow> (\\<forall>x. a \\<le> x \\<and> x \\<le> b \\<longrightarrow> isCont f x) \\<Longrightarrow>\n    \\<exists>x. a \\<le> x \\<and> x \\<le> b \\<and> f x = y\"\n  by (rule IVT2') (auto intro: continuous_at_imp_continuous_on)\n\nlemma continuous_inj_imp_mono:\n  fixes f :: \"'a::linear_continuum_topology \\<Rightarrow> 'b::linorder_topology\"\n  assumes x: \"a < x\" \"x < b\"\n    and cont: \"continuous_on {a..b} f\"\n    and inj: \"inj_on f {a..b}\"\n  shows \"(f a < f x \\<and> f x < f b) \\<or> (f b < f x \\<and> f x < f a)\"\nproof -\n  note I = inj_on_eq_iff[OF inj]\n  {\n    assume \"f x < f a\" \"f x < f b\"\n    then obtain s t where \"x \\<le> s\" \"s \\<le> b\" \"a \\<le> t\" \"t \\<le> x\" \"f s = f t\" \"f x < f s\"\n      using IVT'[of f x \"min (f a) (f b)\" b] IVT2'[of f x \"min (f a) (f b)\" a] x\n      by (auto simp: continuous_on_subset[OF cont] less_imp_le)\n    with x I have False by auto\n  }\n  moreover\n  {\n    assume \"f a < f x\" \"f b < f x\"\n    then obtain s t where \"x \\<le> s\" \"s \\<le> b\" \"a \\<le> t\" \"t \\<le> x\" \"f s = f t\" \"f s < f x\"\n      using IVT'[of f a \"max (f a) (f b)\" x] IVT2'[of f b \"max (f a) (f b)\" x] x\n      by (auto simp: continuous_on_subset[OF cont] less_imp_le)\n    with x I have False by auto\n  }\n  ultimately show ?thesis\n    using I[of a x] I[of x b] x less_trans[OF x]\n    by (auto simp add: le_less less_imp_neq neq_iff)\nqed\n\nlemma continuous_at_Sup_mono:\n  fixes f :: \"'a::{linorder_topology,conditionally_complete_linorder} \\<Rightarrow>\n    'b::{linorder_topology,conditionally_complete_linorder}\"\n  assumes \"mono f\"\n    and cont: \"continuous (at_left (Sup S)) f\"\n    and S: \"S \\<noteq> {}\" \"bdd_above S\"\n  shows \"f (Sup S) = (SUP s\\<in>S. f s)\"\nproof (rule antisym)\n  have f: \"(f \\<longlongrightarrow> f (Sup S)) (at_left (Sup S))\"\n    using cont unfolding continuous_within .\n  show \"f (Sup S) \\<le> (SUP s\\<in>S. f s)\"\n  proof cases\n    assume \"Sup S \\<in> S\"\n    then show ?thesis\n      by (rule cSUP_upper) (auto intro: bdd_above_image_mono S \\<open>mono f\\<close>)\n  next\n    assume \"Sup S \\<notin> S\"\n    from \\<open>S \\<noteq> {}\\<close> obtain s where \"s \\<in> S\"\n      by auto\n    with \\<open>Sup S \\<notin> S\\<close> S have \"s < Sup S\"\n      unfolding less_le by (blast intro: cSup_upper)\n    show ?thesis\n    proof (rule ccontr)\n      assume \"\\<not> ?thesis\"\n      with order_tendstoD(1)[OF f, of \"SUP s\\<in>S. f s\"] obtain b where \"b < Sup S\"\n        and *: \"\\<And>y. b < y \\<Longrightarrow> y < Sup S \\<Longrightarrow> (SUP s\\<in>S. f s) < f y\"\n        by (auto simp: not_le eventually_at_left[OF \\<open>s < Sup S\\<close>])\n      with \\<open>S \\<noteq> {}\\<close> obtain c where \"c \\<in> S\" \"b < c\"\n        using less_cSupD[of S b] by auto\n      with \\<open>Sup S \\<notin> S\\<close> S have \"c < Sup S\"\n        unfolding less_le by (blast intro: cSup_upper)\n      from *[OF \\<open>b < c\\<close> \\<open>c < Sup S\\<close>] cSUP_upper[OF \\<open>c \\<in> S\\<close> bdd_above_image_mono[of f]]\n      show False\n        by (auto simp: assms)\n    qed\n  qed\nqed (intro cSUP_least \\<open>mono f\\<close>[THEN monoD] cSup_upper S)\n\nlemma continuous_at_Sup_antimono:\n  fixes f :: \"'a::{linorder_topology,conditionally_complete_linorder} \\<Rightarrow>\n    'b::{linorder_topology,conditionally_complete_linorder}\"\n  assumes \"antimono f\"\n    and cont: \"continuous (at_left (Sup S)) f\"\n    and S: \"S \\<noteq> {}\" \"bdd_above S\"\n  shows \"f (Sup S) = (INF s\\<in>S. f s)\"\nproof (rule antisym)\n  have f: \"(f \\<longlongrightarrow> f (Sup S)) (at_left (Sup S))\"\n    using cont unfolding continuous_within .\n  show \"(INF s\\<in>S. f s) \\<le> f (Sup S)\"\n  proof cases\n    assume \"Sup S \\<in> S\"\n    then show ?thesis\n      by (intro cINF_lower) (auto intro: bdd_below_image_antimono S \\<open>antimono f\\<close>)\n  next\n    assume \"Sup S \\<notin> S\"\n    from \\<open>S \\<noteq> {}\\<close> obtain s where \"s \\<in> S\"\n      by auto\n    with \\<open>Sup S \\<notin> S\\<close> S have \"s < Sup S\"\n      unfolding less_le by (blast intro: cSup_upper)\n    show ?thesis\n    proof (rule ccontr)\n      assume \"\\<not> ?thesis\"\n      with order_tendstoD(2)[OF f, of \"INF s\\<in>S. f s\"] obtain b where \"b < Sup S\"\n        and *: \"\\<And>y. b < y \\<Longrightarrow> y < Sup S \\<Longrightarrow> f y < (INF s\\<in>S. f s)\"\n        by (auto simp: not_le eventually_at_left[OF \\<open>s < Sup S\\<close>])\n      with \\<open>S \\<noteq> {}\\<close> obtain c where \"c \\<in> S\" \"b < c\"\n        using less_cSupD[of S b] by auto\n      with \\<open>Sup S \\<notin> S\\<close> S have \"c < Sup S\"\n        unfolding less_le by (blast intro: cSup_upper)\n      from *[OF \\<open>b < c\\<close> \\<open>c < Sup S\\<close>] cINF_lower[OF bdd_below_image_antimono, of f S c] \\<open>c \\<in> S\\<close>\n      show False\n        by (auto simp: assms)\n    qed\n  qed\nqed (intro cINF_greatest \\<open>antimono f\\<close>[THEN antimonoD] cSup_upper S)\n\nlemma continuous_at_Inf_mono:\n  fixes f :: \"'a::{linorder_topology,conditionally_complete_linorder} \\<Rightarrow>\n    'b::{linorder_topology,conditionally_complete_linorder}\"\n  assumes \"mono f\"\n    and cont: \"continuous (at_right (Inf S)) f\"\n    and S: \"S \\<noteq> {}\" \"bdd_below S\"\n  shows \"f (Inf S) = (INF s\\<in>S. f s)\"\nproof (rule antisym)\n  have f: \"(f \\<longlongrightarrow> f (Inf S)) (at_right (Inf S))\"\n    using cont unfolding continuous_within .\n  show \"(INF s\\<in>S. f s) \\<le> f (Inf S)\"\n  proof cases\n    assume \"Inf S \\<in> S\"\n    then show ?thesis\n      by (rule cINF_lower[rotated]) (auto intro: bdd_below_image_mono S \\<open>mono f\\<close>)\n  next\n    assume \"Inf S \\<notin> S\"\n    from \\<open>S \\<noteq> {}\\<close> obtain s where \"s \\<in> S\"\n      by auto\n    with \\<open>Inf S \\<notin> S\\<close> S have \"Inf S < s\"\n      unfolding less_le by (blast intro: cInf_lower)\n    show ?thesis\n    proof (rule ccontr)\n      assume \"\\<not> ?thesis\"\n      with order_tendstoD(2)[OF f, of \"INF s\\<in>S. f s\"] obtain b where \"Inf S < b\"\n        and *: \"\\<And>y. Inf S < y \\<Longrightarrow> y < b \\<Longrightarrow> f y < (INF s\\<in>S. f s)\"\n        by (auto simp: not_le eventually_at_right[OF \\<open>Inf S < s\\<close>])\n      with \\<open>S \\<noteq> {}\\<close> obtain c where \"c \\<in> S\" \"c < b\"\n        using cInf_lessD[of S b] by auto\n      with \\<open>Inf S \\<notin> S\\<close> S have \"Inf S < c\"\n        unfolding less_le by (blast intro: cInf_lower)\n      from *[OF \\<open>Inf S < c\\<close> \\<open>c < b\\<close>] cINF_lower[OF bdd_below_image_mono[of f] \\<open>c \\<in> S\\<close>]\n      show False\n        by (auto simp: assms)\n    qed\n  qed\nqed (intro cINF_greatest \\<open>mono f\\<close>[THEN monoD] cInf_lower \\<open>bdd_below S\\<close> \\<open>S \\<noteq> {}\\<close>)\n\nlemma continuous_at_Inf_antimono:\n  fixes f :: \"'a::{linorder_topology,conditionally_complete_linorder} \\<Rightarrow>\n    'b::{linorder_topology,conditionally_complete_linorder}\"\n  assumes \"antimono f\"\n    and cont: \"continuous (at_right (Inf S)) f\"\n    and S: \"S \\<noteq> {}\" \"bdd_below S\"\n  shows \"f (Inf S) = (SUP s\\<in>S. f s)\"\nproof (rule antisym)\n  have f: \"(f \\<longlongrightarrow> f (Inf S)) (at_right (Inf S))\"\n    using cont unfolding continuous_within .\n  show \"f (Inf S) \\<le> (SUP s\\<in>S. f s)\"\n  proof cases\n    assume \"Inf S \\<in> S\"\n    then show ?thesis\n      by (rule cSUP_upper) (auto intro: bdd_above_image_antimono S \\<open>antimono f\\<close>)\n  next\n    assume \"Inf S \\<notin> S\"\n    from \\<open>S \\<noteq> {}\\<close> obtain s where \"s \\<in> S\"\n      by auto\n    with \\<open>Inf S \\<notin> S\\<close> S have \"Inf S < s\"\n      unfolding less_le by (blast intro: cInf_lower)\n    show ?thesis\n    proof (rule ccontr)\n      assume \"\\<not> ?thesis\"\n      with order_tendstoD(1)[OF f, of \"SUP s\\<in>S. f s\"] obtain b where \"Inf S < b\"\n        and *: \"\\<And>y. Inf S < y \\<Longrightarrow> y < b \\<Longrightarrow> (SUP s\\<in>S. f s) < f y\"\n        by (auto simp: not_le eventually_at_right[OF \\<open>Inf S < s\\<close>])\n      with \\<open>S \\<noteq> {}\\<close> obtain c where \"c \\<in> S\" \"c < b\"\n        using cInf_lessD[of S b] by auto\n      with \\<open>Inf S \\<notin> S\\<close> S have \"Inf S < c\"\n        unfolding less_le by (blast intro: cInf_lower)\n      from *[OF \\<open>Inf S < c\\<close> \\<open>c < b\\<close>] cSUP_upper[OF \\<open>c \\<in> S\\<close> bdd_above_image_antimono[of f]]\n      show False\n        by (auto simp: assms)\n    qed\n  qed\nqed (intro cSUP_least \\<open>antimono f\\<close>[THEN antimonoD] cInf_lower S)\n\n\nsubsection \\<open>Uniform spaces\\<close>\n\nclass uniformity =\n  fixes uniformity :: \"('a \\<times> 'a) filter\"\nbegin\n\nabbreviation uniformity_on :: \"'a set \\<Rightarrow> ('a \\<times> 'a) filter\"\n  where \"uniformity_on s \\<equiv> inf uniformity (principal (s\\<times>s))\"\n\nend\n\nlemma uniformity_Abort:\n  \"uniformity =\n    Filter.abstract_filter (\\<lambda>u. Code.abort (STR ''uniformity is not executable'') (\\<lambda>u. uniformity))\"\n  by simp\n\nclass open_uniformity = \"open\" + uniformity +\n  assumes open_uniformity:\n    \"\\<And>U. open U \\<longleftrightarrow> (\\<forall>x\\<in>U. eventually (\\<lambda>(x', y). x' = x \\<longrightarrow> y \\<in> U) uniformity)\"\nbegin\n\nsubclass topological_space\n  by standard (force elim: eventually_mono eventually_elim2 simp: split_beta' open_uniformity)+\n\nend\n\nclass uniform_space = open_uniformity +\n  assumes uniformity_refl: \"eventually E uniformity \\<Longrightarrow> E (x, x)\"\n    and uniformity_sym: \"eventually E uniformity \\<Longrightarrow> eventually (\\<lambda>(x, y). E (y, x)) uniformity\"\n    and uniformity_trans:\n      \"eventually E uniformity \\<Longrightarrow>\n        \\<exists>D. eventually D uniformity \\<and> (\\<forall>x y z. D (x, y) \\<longrightarrow> D (y, z) \\<longrightarrow> E (x, z))\"\nbegin\n\nlemma uniformity_bot: \"uniformity \\<noteq> bot\"\n  using uniformity_refl by auto\n\nlemma uniformity_trans':\n  \"eventually E uniformity \\<Longrightarrow>\n    eventually (\\<lambda>((x, y), (y', z)). y = y' \\<longrightarrow> E (x, z)) (uniformity \\<times>\\<^sub>F uniformity)\"\n  by (drule uniformity_trans) (auto simp add: eventually_prod_same)\n\nlemma uniformity_transE:\n  assumes \"eventually E uniformity\"\n  obtains D where \"eventually D uniformity\" \"\\<And>x y z. D (x, y) \\<Longrightarrow> D (y, z) \\<Longrightarrow> E (x, z)\"\n  using uniformity_trans [OF assms] by auto\n\nlemma eventually_nhds_uniformity:\n  \"eventually P (nhds x) \\<longleftrightarrow> eventually (\\<lambda>(x', y). x' = x \\<longrightarrow> P y) uniformity\"\n  (is \"_ \\<longleftrightarrow> ?N P x\")\n  unfolding eventually_nhds\nproof safe\n  assume *: \"?N P x\"\n  have \"?N (?N P) x\" if \"?N P x\" for x\n  proof -\n    from that obtain D where ev: \"eventually D uniformity\"\n      and D: \"D (a, b) \\<Longrightarrow> D (b, c) \\<Longrightarrow> case (a, c) of (x', y) \\<Rightarrow> x' = x \\<longrightarrow> P y\" for a b c\n      by (rule uniformity_transE) simp\n    from ev show ?thesis\n      by eventually_elim (insert ev D, force elim: eventually_mono split: prod.split)\n  qed\n  then have \"open {x. ?N P x}\"\n    by (simp add: open_uniformity)\n  then show \"\\<exists>S. open S \\<and> x \\<in> S \\<and> (\\<forall>x\\<in>S. P x)\"\n    by (intro exI[of _ \"{x. ?N P x}\"]) (auto dest: uniformity_refl simp: *)\nqed (force simp add: open_uniformity elim: eventually_mono)\n\n\nsubsubsection \\<open>Totally bounded sets\\<close>\n\ndefinition totally_bounded :: \"'a set \\<Rightarrow> bool\"\n  where \"totally_bounded S \\<longleftrightarrow>\n    (\\<forall>E. eventually E uniformity \\<longrightarrow> (\\<exists>X. finite X \\<and> (\\<forall>s\\<in>S. \\<exists>x\\<in>X. E (x, s))))\"\n\nlemma totally_bounded_empty[iff]: \"totally_bounded {}\"\n  by (auto simp add: totally_bounded_def)\n\nlemma totally_bounded_subset: \"totally_bounded S \\<Longrightarrow> T \\<subseteq> S \\<Longrightarrow> totally_bounded T\"\n  by (fastforce simp add: totally_bounded_def)\n\nlemma totally_bounded_Union[intro]:\n  assumes M: \"finite M\" \"\\<And>S. S \\<in> M \\<Longrightarrow> totally_bounded S\"\n  shows \"totally_bounded (\\<Union>M)\"\n  unfolding totally_bounded_def\nproof safe\n  fix E\n  assume \"eventually E uniformity\"\n  with M obtain X where \"\\<forall>S\\<in>M. finite (X S) \\<and> (\\<forall>s\\<in>S. \\<exists>x\\<in>X S. E (x, s))\"\n    by (metis totally_bounded_def)\n  with \\<open>finite M\\<close> show \"\\<exists>X. finite X \\<and> (\\<forall>s\\<in>\\<Union>M. \\<exists>x\\<in>X. E (x, s))\"\n    by (intro exI[of _ \"\\<Union>S\\<in>M. X S\"]) force\nqed\n\n\nsubsubsection \\<open>Cauchy filter\\<close>\n\ndefinition cauchy_filter :: \"'a filter \\<Rightarrow> bool\"\n  where \"cauchy_filter F \\<longleftrightarrow> F \\<times>\\<^sub>F F \\<le> uniformity\"\n\ndefinition Cauchy :: \"(nat \\<Rightarrow> 'a) \\<Rightarrow> bool\"\n  where Cauchy_uniform: \"Cauchy X = cauchy_filter (filtermap X sequentially)\"\n\nlemma Cauchy_uniform_iff:\n  \"Cauchy X \\<longleftrightarrow> (\\<forall>P. eventually P uniformity \\<longrightarrow> (\\<exists>N. \\<forall>n\\<ge>N. \\<forall>m\\<ge>N. P (X n, X m)))\"\n  unfolding Cauchy_uniform cauchy_filter_def le_filter_def eventually_prod_same\n    eventually_filtermap eventually_sequentially\nproof safe\n  let ?U = \"\\<lambda>P. eventually P uniformity\"\n  {\n    fix P\n    assume \"?U P\" \"\\<forall>P. ?U P \\<longrightarrow> (\\<exists>Q. (\\<exists>N. \\<forall>n\\<ge>N. Q (X n)) \\<and> (\\<forall>x y. Q x \\<longrightarrow> Q y \\<longrightarrow> P (x, y)))\"\n    then obtain Q N where \"\\<And>n. n \\<ge> N \\<Longrightarrow> Q (X n)\" \"\\<And>x y. Q x \\<Longrightarrow> Q y \\<Longrightarrow> P (x, y)\"\n      by metis\n    then show \"\\<exists>N. \\<forall>n\\<ge>N. \\<forall>m\\<ge>N. P (X n, X m)\"\n      by blast\n  next\n    fix P\n    assume \"?U P\" and P: \"\\<forall>P. ?U P \\<longrightarrow> (\\<exists>N. \\<forall>n\\<ge>N. \\<forall>m\\<ge>N. P (X n, X m))\"\n    then obtain Q where \"?U Q\" and Q: \"\\<And>x y z. Q (x, y) \\<Longrightarrow> Q (y, z) \\<Longrightarrow> P (x, z)\"\n      by (auto elim: uniformity_transE)\n    then have \"?U (\\<lambda>x. Q x \\<and> (\\<lambda>(x, y). Q (y, x)) x)\"\n      unfolding eventually_conj_iff by (simp add: uniformity_sym)\n    from P[rule_format, OF this]\n    obtain N where N: \"\\<And>n m. n \\<ge> N \\<Longrightarrow> m \\<ge> N \\<Longrightarrow> Q (X n, X m) \\<and> Q (X m, X n)\"\n      by auto\n    show \"\\<exists>Q. (\\<exists>N. \\<forall>n\\<ge>N. Q (X n)) \\<and> (\\<forall>x y. Q x \\<longrightarrow> Q y \\<longrightarrow> P (x, y))\"\n    proof (safe intro!: exI[of _ \"\\<lambda>x. \\<forall>n\\<ge>N. Q (x, X n) \\<and> Q (X n, x)\"] exI[of _ N] N)\n      fix x y\n      assume \"\\<forall>n\\<ge>N. Q (x, X n) \\<and> Q (X n, x)\" \"\\<forall>n\\<ge>N. Q (y, X n) \\<and> Q (X n, y)\"\n      then have \"Q (x, X N)\" \"Q (X N, y)\" by auto\n      then show \"P (x, y)\"\n        by (rule Q)\n    qed\n  }\nqed\n\nlemma nhds_imp_cauchy_filter:\n  assumes *: \"F \\<le> nhds x\"\n  shows \"cauchy_filter F\"\nproof -\n  have \"F \\<times>\\<^sub>F F \\<le> nhds x \\<times>\\<^sub>F nhds x\"\n    by (intro prod_filter_mono *)\n  also have \"\\<dots> \\<le> uniformity\"\n    unfolding le_filter_def eventually_nhds_uniformity eventually_prod_same\n  proof safe\n    fix P\n    assume \"eventually P uniformity\"\n    then obtain Ql where ev: \"eventually Ql uniformity\"\n      and \"Ql (x, y) \\<Longrightarrow> Ql (y, z) \\<Longrightarrow> P (x, z)\" for x y z\n      by (rule uniformity_transE) simp\n    with ev[THEN uniformity_sym]\n    show \"\\<exists>Q. eventually (\\<lambda>(x', y). x' = x \\<longrightarrow> Q y) uniformity \\<and>\n        (\\<forall>x y. Q x \\<longrightarrow> Q y \\<longrightarrow> P (x, y))\"\n      by (rule_tac exI[of _ \"\\<lambda>y. Ql (y, x) \\<and> Ql (x, y)\"]) (fastforce elim: eventually_elim2)\n  qed\n  finally show ?thesis\n    by (simp add: cauchy_filter_def)\nqed\n\nlemma LIMSEQ_imp_Cauchy: \"X \\<longlonglongrightarrow> x \\<Longrightarrow> Cauchy X\"\n  unfolding Cauchy_uniform filterlim_def by (intro nhds_imp_cauchy_filter)\n\nlemma Cauchy_subseq_Cauchy:\n  assumes \"Cauchy X\" \"strict_mono f\"\n  shows \"Cauchy (X \\<circ> f)\"\n  unfolding Cauchy_uniform comp_def filtermap_filtermap[symmetric] cauchy_filter_def\n  by (rule order_trans[OF _ \\<open>Cauchy X\\<close>[unfolded Cauchy_uniform cauchy_filter_def]])\n     (intro prod_filter_mono filtermap_mono filterlim_subseq[OF \\<open>strict_mono f\\<close>, unfolded filterlim_def])\n\nlemma convergent_Cauchy: \"convergent X \\<Longrightarrow> Cauchy X\"\n  unfolding convergent_def by (erule exE, erule LIMSEQ_imp_Cauchy)\n\ndefinition complete :: \"'a set \\<Rightarrow> bool\"\n  where complete_uniform: \"complete S \\<longleftrightarrow>\n    (\\<forall>F \\<le> principal S. F \\<noteq> bot \\<longrightarrow> cauchy_filter F \\<longrightarrow> (\\<exists>x\\<in>S. F \\<le> nhds x))\"\n\nlemma (in uniform_space) cauchy_filter_complete_converges:\n  assumes \"cauchy_filter F\" \"complete A\" \"F \\<le> principal A\" \"F \\<noteq> bot\"\n  shows   \"\\<exists>c. F \\<le> nhds c\"\n  using assms unfolding complete_uniform by blast\n\nend\n\nsubsubsection \\<open>Uniformly continuous functions\\<close>\n\ndefinition uniformly_continuous_on :: \"'a set \\<Rightarrow> ('a::uniform_space \\<Rightarrow> 'b::uniform_space) \\<Rightarrow> bool\"\n  where uniformly_continuous_on_uniformity: \"uniformly_continuous_on s f \\<longleftrightarrow>\n    (LIM (x, y) (uniformity_on s). (f x, f y) :> uniformity)\"\n\nlemma uniformly_continuous_onD:\n  \"uniformly_continuous_on s f \\<Longrightarrow> eventually E uniformity \\<Longrightarrow>\n    eventually (\\<lambda>(x, y). x \\<in> s \\<longrightarrow> y \\<in> s \\<longrightarrow> E (f x, f y)) uniformity\"\n  by (simp add: uniformly_continuous_on_uniformity filterlim_iff\n      eventually_inf_principal split_beta' mem_Times_iff imp_conjL)\n\nlemma uniformly_continuous_on_const[continuous_intros]: \"uniformly_continuous_on s (\\<lambda>x. c)\"\n  by (auto simp: uniformly_continuous_on_uniformity filterlim_iff uniformity_refl)\n\nlemma uniformly_continuous_on_id[continuous_intros]: \"uniformly_continuous_on s (\\<lambda>x. x)\"\n  by (auto simp: uniformly_continuous_on_uniformity filterlim_def)\n\nlemma uniformly_continuous_on_compose:\n  \"uniformly_continuous_on s g \\<Longrightarrow> uniformly_continuous_on (g`s) f \\<Longrightarrow>\n    uniformly_continuous_on s (\\<lambda>x. f (g x))\"\n  using filterlim_compose[of \"\\<lambda>(x, y). (f x, f y)\" uniformity\n      \"uniformity_on (g`s)\"  \"\\<lambda>(x, y). (g x, g y)\" \"uniformity_on s\"]\n  by (simp add: split_beta' uniformly_continuous_on_uniformity\n      filterlim_inf filterlim_principal eventually_inf_principal mem_Times_iff)\n\nlemma uniformly_continuous_imp_continuous:\n  assumes f: \"uniformly_continuous_on s f\"\n  shows \"continuous_on s f\"\n  by (auto simp: filterlim_iff eventually_at_filter eventually_nhds_uniformity continuous_on_def\n           elim: eventually_mono dest!: uniformly_continuous_onD[OF f])\n\n\nsection \\<open>Product Topology\\<close>\n\nsubsection \\<open>Product is a topological space\\<close>\n\ninstantiation prod :: (topological_space, topological_space) topological_space\nbegin\n\ndefinition open_prod_def[code del]:\n  \"open (S :: ('a \\<times> 'b) set) \\<longleftrightarrow>\n    (\\<forall>x\\<in>S. \\<exists>A B. open A \\<and> open B \\<and> x \\<in> A \\<times> B \\<and> A \\<times> B \\<subseteq> S)\"\n\nlemma open_prod_elim:\n  assumes \"open S\" and \"x \\<in> S\"\n  obtains A B where \"open A\" and \"open B\" and \"x \\<in> A \\<times> B\" and \"A \\<times> B \\<subseteq> S\"\n  using assms unfolding open_prod_def by fast\n\nlemma open_prod_intro:\n  assumes \"\\<And>x. x \\<in> S \\<Longrightarrow> \\<exists>A B. open A \\<and> open B \\<and> x \\<in> A \\<times> B \\<and> A \\<times> B \\<subseteq> S\"\n  shows \"open S\"\n  using assms unfolding open_prod_def by fast\n\ninstance\nproof\n  show \"open (UNIV :: ('a \\<times> 'b) set)\"\n    unfolding open_prod_def by auto\nnext\n  fix S T :: \"('a \\<times> 'b) set\"\n  assume \"open S\" \"open T\"\n  show \"open (S \\<inter> T)\"\n  proof (rule open_prod_intro)\n    fix x\n    assume x: \"x \\<in> S \\<inter> T\"\n    from x have \"x \\<in> S\" by simp\n    obtain Sa Sb where A: \"open Sa\" \"open Sb\" \"x \\<in> Sa \\<times> Sb\" \"Sa \\<times> Sb \\<subseteq> S\"\n      using \\<open>open S\\<close> and \\<open>x \\<in> S\\<close> by (rule open_prod_elim)\n    from x have \"x \\<in> T\" by simp\n    obtain Ta Tb where B: \"open Ta\" \"open Tb\" \"x \\<in> Ta \\<times> Tb\" \"Ta \\<times> Tb \\<subseteq> T\"\n      using \\<open>open T\\<close> and \\<open>x \\<in> T\\<close> by (rule open_prod_elim)\n    let ?A = \"Sa \\<inter> Ta\" and ?B = \"Sb \\<inter> Tb\"\n    have \"open ?A \\<and> open ?B \\<and> x \\<in> ?A \\<times> ?B \\<and> ?A \\<times> ?B \\<subseteq> S \\<inter> T\"\n      using A B by (auto simp add: open_Int)\n    then show \"\\<exists>A B. open A \\<and> open B \\<and> x \\<in> A \\<times> B \\<and> A \\<times> B \\<subseteq> S \\<inter> T\"\n      by fast\n  qed\nnext\n  fix K :: \"('a \\<times> 'b) set set\"\n  assume \"\\<forall>S\\<in>K. open S\"\n  then show \"open (\\<Union>K)\"\n    unfolding open_prod_def by fast\nqed\n\nend\n\ndeclare [[code abort: \"open :: ('a::topological_space \\<times> 'b::topological_space) set \\<Rightarrow> bool\"]]\n\nlemma open_Times: \"open S \\<Longrightarrow> open T \\<Longrightarrow> open (S \\<times> T)\"\n  unfolding open_prod_def by auto\n\nlemma fst_vimage_eq_Times: \"fst -` S = S \\<times> UNIV\"\n  by auto\n\nlemma snd_vimage_eq_Times: \"snd -` S = UNIV \\<times> S\"\n  by auto\n\nlemma open_vimage_fst: \"open S \\<Longrightarrow> open (fst -` S)\"\n  by (simp add: fst_vimage_eq_Times open_Times)\n\nlemma open_vimage_snd: \"open S \\<Longrightarrow> open (snd -` S)\"\n  by (simp add: snd_vimage_eq_Times open_Times)\n\nlemma closed_vimage_fst: \"closed S \\<Longrightarrow> closed (fst -` S)\"\n  unfolding closed_open vimage_Compl [symmetric]\n  by (rule open_vimage_fst)\n\nlemma closed_vimage_snd: \"closed S \\<Longrightarrow> closed (snd -` S)\"\n  unfolding closed_open vimage_Compl [symmetric]\n  by (rule open_vimage_snd)\n\nlemma closed_Times: \"closed S \\<Longrightarrow> closed T \\<Longrightarrow> closed (S \\<times> T)\"\nproof -\n  have \"S \\<times> T = (fst -` S) \\<inter> (snd -` T)\"\n    by auto\n  then show \"closed S \\<Longrightarrow> closed T \\<Longrightarrow> closed (S \\<times> T)\"\n    by (simp add: closed_vimage_fst closed_vimage_snd closed_Int)\nqed\n\nlemma subset_fst_imageI: \"A \\<times> B \\<subseteq> S \\<Longrightarrow> y \\<in> B \\<Longrightarrow> A \\<subseteq> fst ` S\"\n  unfolding image_def subset_eq by force\n\nlemma subset_snd_imageI: \"A \\<times> B \\<subseteq> S \\<Longrightarrow> x \\<in> A \\<Longrightarrow> B \\<subseteq> snd ` S\"\n  unfolding image_def subset_eq by force\n\nlemma open_image_fst:\n  assumes \"open S\"\n  shows \"open (fst ` S)\"\nproof (rule openI)\n  fix x\n  assume \"x \\<in> fst ` S\"\n  then obtain y where \"(x, y) \\<in> S\"\n    by auto\n  then obtain A B where \"open A\" \"open B\" \"x \\<in> A\" \"y \\<in> B\" \"A \\<times> B \\<subseteq> S\"\n    using \\<open>open S\\<close> unfolding open_prod_def by auto\n  from \\<open>A \\<times> B \\<subseteq> S\\<close> \\<open>y \\<in> B\\<close> have \"A \\<subseteq> fst ` S\"\n    by (rule subset_fst_imageI)\n  with \\<open>open A\\<close> \\<open>x \\<in> A\\<close> have \"open A \\<and> x \\<in> A \\<and> A \\<subseteq> fst ` S\"\n    by simp\n  then show \"\\<exists>T. open T \\<and> x \\<in> T \\<and> T \\<subseteq> fst ` S\" ..\nqed\n\nlemma open_image_snd:\n  assumes \"open S\"\n  shows \"open (snd ` S)\"\nproof (rule openI)\n  fix y\n  assume \"y \\<in> snd ` S\"\n  then obtain x where \"(x, y) \\<in> S\"\n    by auto\n  then obtain A B where \"open A\" \"open B\" \"x \\<in> A\" \"y \\<in> B\" \"A \\<times> B \\<subseteq> S\"\n    using \\<open>open S\\<close> unfolding open_prod_def by auto\n  from \\<open>A \\<times> B \\<subseteq> S\\<close> \\<open>x \\<in> A\\<close> have \"B \\<subseteq> snd ` S\"\n    by (rule subset_snd_imageI)\n  with \\<open>open B\\<close> \\<open>y \\<in> B\\<close> have \"open B \\<and> y \\<in> B \\<and> B \\<subseteq> snd ` S\"\n    by simp\n  then show \"\\<exists>T. open T \\<and> y \\<in> T \\<and> T \\<subseteq> snd ` S\" ..\nqed\n\nlemma nhds_prod: \"nhds (a, b) = nhds a \\<times>\\<^sub>F nhds b\"\n  unfolding nhds_def\nproof (subst prod_filter_INF, auto intro!: antisym INF_greatest simp: principal_prod_principal)\n  fix S T\n  assume \"open S\" \"a \\<in> S\" \"open T\" \"b \\<in> T\"\n  then show \"(INF x \\<in> {S. open S \\<and> (a, b) \\<in> S}. principal x) \\<le> principal (S \\<times> T)\"\n    by (intro INF_lower) (auto intro!: open_Times)\nnext\n  fix S'\n  assume \"open S'\" \"(a, b) \\<in> S'\"\n  then obtain S T where \"open S\" \"a \\<in> S\" \"open T\" \"b \\<in> T\" \"S \\<times> T \\<subseteq> S'\"\n    by (auto elim: open_prod_elim)\n  then show \"(INF x \\<in> {S. open S \\<and> a \\<in> S}. INF y \\<in> {S. open S \\<and> b \\<in> S}.\n      principal (x \\<times> y)) \\<le> principal S'\"\n    by (auto intro!: INF_lower2)\nqed\n\n\nsubsubsection \\<open>Continuity of operations\\<close>\n\nlemma tendsto_fst [tendsto_intros]:\n  assumes \"(f \\<longlongrightarrow> a) F\"\n  shows \"((\\<lambda>x. fst (f x)) \\<longlongrightarrow> fst a) F\"\nproof (rule topological_tendstoI)\n  fix S\n  assume \"open S\" and \"fst a \\<in> S\"\n  then have \"open (fst -` S)\" and \"a \\<in> fst -` S\"\n    by (simp_all add: open_vimage_fst)\n  with assms have \"eventually (\\<lambda>x. f x \\<in> fst -` S) F\"\n    by (rule topological_tendstoD)\n  then show \"eventually (\\<lambda>x. fst (f x) \\<in> S) F\"\n    by simp\nqed\n\nlemma tendsto_snd [tendsto_intros]:\n  assumes \"(f \\<longlongrightarrow> a) F\"\n  shows \"((\\<lambda>x. snd (f x)) \\<longlongrightarrow> snd a) F\"\nproof (rule topological_tendstoI)\n  fix S\n  assume \"open S\" and \"snd a \\<in> S\"\n  then have \"open (snd -` S)\" and \"a \\<in> snd -` S\"\n    by (simp_all add: open_vimage_snd)\n  with assms have \"eventually (\\<lambda>x. f x \\<in> snd -` S) F\"\n    by (rule topological_tendstoD)\n  then show \"eventually (\\<lambda>x. snd (f x) \\<in> S) F\"\n    by simp\nqed\n\nlemma tendsto_Pair [tendsto_intros]:\n  assumes \"(f \\<longlongrightarrow> a) F\" and \"(g \\<longlongrightarrow> b) F\"\n  shows \"((\\<lambda>x. (f x, g x)) \\<longlongrightarrow> (a, b)) F\"\n  unfolding nhds_prod using assms by (rule filterlim_Pair)\n\nlemma continuous_fst[continuous_intros]: \"continuous F f \\<Longrightarrow> continuous F (\\<lambda>x. fst (f x))\"\n  unfolding continuous_def by (rule tendsto_fst)\n\nlemma continuous_snd[continuous_intros]: \"continuous F f \\<Longrightarrow> continuous F (\\<lambda>x. snd (f x))\"\n  unfolding continuous_def by (rule tendsto_snd)\n\nlemma continuous_Pair[continuous_intros]:\n  \"continuous F f \\<Longrightarrow> continuous F g \\<Longrightarrow> continuous F (\\<lambda>x. (f x, g x))\"\n  unfolding continuous_def by (rule tendsto_Pair)\n\nlemma continuous_on_fst[continuous_intros]:\n  \"continuous_on s f \\<Longrightarrow> continuous_on s (\\<lambda>x. fst (f x))\"\n  unfolding continuous_on_def by (auto intro: tendsto_fst)\n\nlemma continuous_on_snd[continuous_intros]:\n  \"continuous_on s f \\<Longrightarrow> continuous_on s (\\<lambda>x. snd (f x))\"\n  unfolding continuous_on_def by (auto intro: tendsto_snd)\n\nlemma continuous_on_Pair[continuous_intros]:\n  \"continuous_on s f \\<Longrightarrow> continuous_on s g \\<Longrightarrow> continuous_on s (\\<lambda>x. (f x, g x))\"\n  unfolding continuous_on_def by (auto intro: tendsto_Pair)\n\nlemma continuous_on_swap[continuous_intros]: \"continuous_on A prod.swap\"\n  by (simp add: prod.swap_def continuous_on_fst continuous_on_snd\n      continuous_on_Pair continuous_on_id)\n\nlemma continuous_on_swap_args:\n  assumes \"continuous_on (A\\<times>B) (\\<lambda>(x,y). d x y)\"\n    shows \"continuous_on (B\\<times>A) (\\<lambda>(x,y). d y x)\"\nproof -\n  have \"(\\<lambda>(x,y). d y x) = (\\<lambda>(x,y). d x y) \\<circ> prod.swap\"\n    by force\n  then show ?thesis\n    by (metis assms continuous_on_compose continuous_on_swap product_swap)\nqed\n\nlemma isCont_fst [simp]: \"isCont f a \\<Longrightarrow> isCont (\\<lambda>x. fst (f x)) a\"\n  by (fact continuous_fst)\n\nlemma isCont_snd [simp]: \"isCont f a \\<Longrightarrow> isCont (\\<lambda>x. snd (f x)) a\"\n  by (fact continuous_snd)\n\nlemma isCont_Pair [simp]: \"\\<lbrakk>isCont f a; isCont g a\\<rbrakk> \\<Longrightarrow> isCont (\\<lambda>x. (f x, g x)) a\"\n  by (fact continuous_Pair)\n\nlemma continuous_on_compose_Pair:\n  assumes f: \"continuous_on (Sigma A B) (\\<lambda>(a, b). f a b)\"\n  assumes g: \"continuous_on C g\"\n  assumes h: \"continuous_on C h\"\n  assumes subset: \"\\<And>c. c \\<in> C \\<Longrightarrow> g c \\<in> A\" \"\\<And>c. c \\<in> C \\<Longrightarrow> h c \\<in> B (g c)\"\n  shows \"continuous_on C (\\<lambda>c. f (g c) (h c))\"\n  using continuous_on_compose2[OF f continuous_on_Pair[OF g h]] subset\n  by auto\n\n\nsubsubsection \\<open>Connectedness of products\\<close>\n\nproposition connected_Times:\n  assumes S: \"connected S\" and T: \"connected T\"\n  shows \"connected (S \\<times> T)\"\nproof (rule connectedI_const)\n  fix P::\"'a \\<times> 'b \\<Rightarrow> bool\"\n  assume P[THEN continuous_on_compose2, continuous_intros]: \"continuous_on (S \\<times> T) P\"\n  have \"continuous_on S (\\<lambda>s. P (s, t))\" if \"t \\<in> T\" for t\n    by (auto intro!: continuous_intros that)\n  from connectedD_const[OF S this]\n  obtain c1 where c1: \"\\<And>s t. t \\<in> T \\<Longrightarrow> s \\<in> S \\<Longrightarrow> P (s, t) = c1 t\"\n    by metis\n  moreover\n  have \"continuous_on T (\\<lambda>t. P (s, t))\" if \"s \\<in> S\" for s\n    by (auto intro!: continuous_intros that)\n  from connectedD_const[OF T this]\n  obtain c2 where \"\\<And>s t. t \\<in> T \\<Longrightarrow> s \\<in> S \\<Longrightarrow> P (s, t) = c2 s\"\n    by metis\n  ultimately show \"\\<exists>c. \\<forall>s\\<in>S \\<times> T. P s = c\"\n    by auto\nqed\n\ncorollary connected_Times_eq [simp]:\n   \"connected (S \\<times> T) \\<longleftrightarrow> S = {} \\<or> T = {} \\<or> connected S \\<and> connected T\"  (is \"?lhs = ?rhs\")\nproof\n  assume L: ?lhs\n  show ?rhs\n  proof cases\n    assume \"S \\<noteq> {} \\<and> T \\<noteq> {}\"\n    moreover\n    have \"connected (fst ` (S \\<times> T))\" \"connected (snd ` (S \\<times> T))\"\n      using continuous_on_fst continuous_on_snd continuous_on_id\n      by (blast intro: connected_continuous_image [OF _ L])+\n    ultimately show ?thesis\n      by auto\n  qed auto\nqed (auto simp: connected_Times)\n\n\nsubsubsection \\<open>Separation axioms\\<close>\n\ninstance prod :: (t0_space, t0_space) t0_space\nproof\n  fix x y :: \"'a \\<times> 'b\"\n  assume \"x \\<noteq> y\"\n  then have \"fst x \\<noteq> fst y \\<or> snd x \\<noteq> snd y\"\n    by (simp add: prod_eq_iff)\n  then show \"\\<exists>U. open U \\<and> (x \\<in> U) \\<noteq> (y \\<in> U)\"\n    by (fast dest: t0_space elim: open_vimage_fst open_vimage_snd)\nqed\n\ninstance prod :: (t1_space, t1_space) t1_space\nproof\n  fix x y :: \"'a \\<times> 'b\"\n  assume \"x \\<noteq> y\"\n  then have \"fst x \\<noteq> fst y \\<or> snd x \\<noteq> snd y\"\n    by (simp add: prod_eq_iff)\n  then show \"\\<exists>U. open U \\<and> x \\<in> U \\<and> y \\<notin> U\"\n    by (fast dest: t1_space elim: open_vimage_fst open_vimage_snd)\nqed\n\ninstance prod :: (t2_space, t2_space) t2_space\nproof\n  fix x y :: \"'a \\<times> 'b\"\n  assume \"x \\<noteq> y\"\n  then have \"fst x \\<noteq> fst y \\<or> snd x \\<noteq> snd y\"\n    by (simp add: prod_eq_iff)\n  then show \"\\<exists>U V. open U \\<and> open V \\<and> x \\<in> U \\<and> y \\<in> V \\<and> U \\<inter> V = {}\"\n    by (fast dest: hausdorff elim: open_vimage_fst open_vimage_snd)\nqed\n\nlemma isCont_swap[continuous_intros]: \"isCont prod.swap a\"\n  using continuous_on_eq_continuous_within continuous_on_swap by blast\n\nlemma open_diagonal_complement:\n  \"open {(x,y) |x y. x \\<noteq> (y::('a::t2_space))}\"\nproof -\n  have \"open {(x, y). x \\<noteq> (y::'a)}\"\n    unfolding split_def by (intro open_Collect_neq continuous_intros)\n  also have \"{(x, y). x \\<noteq> (y::'a)} = {(x, y) |x y. x \\<noteq> (y::'a)}\"\n    by auto\n  finally show ?thesis .\nqed\n\nlemma closed_diagonal:\n  \"closed {y. \\<exists> x::('a::t2_space). y = (x,x)}\"\nproof -\n  have \"{y. \\<exists> x::'a. y = (x,x)} = UNIV - {(x,y) | x y. x \\<noteq> y}\" by auto\n  then show ?thesis using open_diagonal_complement closed_Diff by auto\nqed\n\nlemma open_superdiagonal:\n  \"open {(x,y) | x y. x > (y::'a::{linorder_topology})}\"\nproof -\n  have \"open {(x, y). x > (y::'a)}\"\n    unfolding split_def by (intro open_Collect_less continuous_intros)\n  also have \"{(x, y). x > (y::'a)} = {(x, y) |x y. x > (y::'a)}\"\n    by auto\n  finally show ?thesis .\nqed\n\nlemma closed_subdiagonal:\n  \"closed {(x,y) | x y. x \\<le> (y::'a::{linorder_topology})}\"\nproof -\n  have \"{(x,y) | x y. x \\<le> (y::'a)} = UNIV - {(x,y) | x y. x > (y::'a)}\" by auto\n  then show ?thesis using open_superdiagonal closed_Diff by auto\nqed\n\nlemma open_subdiagonal:\n  \"open {(x,y) | x y. x < (y::'a::{linorder_topology})}\"\nproof -\n  have \"open {(x, y). x < (y::'a)}\"\n    unfolding split_def by (intro open_Collect_less continuous_intros)\n  also have \"{(x, y). x < (y::'a)} = {(x, y) |x y. x < (y::'a)}\"\n    by auto\n  finally show ?thesis .\nqed\n\nlemma closed_superdiagonal:\n  \"closed {(x,y) | x y. x \\<ge> (y::('a::{linorder_topology}))}\"\nproof -\n  have \"{(x,y) | x y. x \\<ge> (y::'a)} = UNIV - {(x,y) | x y. x < y}\" by auto\n  then show ?thesis using open_subdiagonal closed_Diff by auto\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/Topological_Spaces.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.865224072151174, "lm_q2_score": 0.8459424431344437, "lm_q1q2_score": 0.7319297654542963}}
{"text": "(*  Title:      ZF/Order.thy\n    Author:     Lawrence C Paulson, Cambridge University Computer Laboratory\n    Copyright   1994  University of Cambridge\n\nResults from the book \"Set Theory: an Introduction to Independence Proofs\"\n        by Kenneth Kunen.  Chapter 1, section 6.\nAdditional definitions and lemmas for reflexive orders.\n*)\n\nsection{*Partial and Total Orderings: Basic Definitions and Properties*}\n\ntheory Order imports WF Perm begin\n\ntext {* We adopt the following convention: @{text ord} is used for\n  strict orders and @{text order} is used for their reflexive\n  counterparts. *}\n\ndefinition\n  part_ord :: \"[i,i]=>o\"                (*Strict partial ordering*)  where\n   \"part_ord(A,r) == irrefl(A,r) & trans[A](r)\"\n\ndefinition\n  linear   :: \"[i,i]=>o\"                (*Strict total ordering*)  where\n   \"linear(A,r) == (\\<forall>x\\<in>A. \\<forall>y\\<in>A. <x,y>:r | x=y | <y,x>:r)\"\n\ndefinition\n  tot_ord  :: \"[i,i]=>o\"                (*Strict total ordering*)  where\n   \"tot_ord(A,r) == part_ord(A,r) & linear(A,r)\"\n\ndefinition\n  \"preorder_on(A, r) \\<equiv> refl(A, r) \\<and> trans[A](r)\"\n\ndefinition                              (*Partial ordering*)\n  \"partial_order_on(A, r) \\<equiv> preorder_on(A, r) \\<and> antisym(r)\"\n\nabbreviation\n  \"Preorder(r) \\<equiv> preorder_on(field(r), r)\"\n\nabbreviation\n  \"Partial_order(r) \\<equiv> partial_order_on(field(r), r)\"\n\ndefinition\n  well_ord :: \"[i,i]=>o\"                (*Well-ordering*)  where\n   \"well_ord(A,r) == tot_ord(A,r) & wf[A](r)\"\n\ndefinition\n  mono_map :: \"[i,i,i,i]=>i\"            (*Order-preserving maps*)  where\n   \"mono_map(A,r,B,s) ==\n              {f \\<in> A->B. \\<forall>x\\<in>A. \\<forall>y\\<in>A. <x,y>:r \\<longrightarrow> <f`x,f`y>:s}\"\n\ndefinition\n  ord_iso  :: \"[i,i,i,i]=>i\"            (*Order isomorphisms*)  where\n   \"ord_iso(A,r,B,s) ==\n              {f \\<in> bij(A,B). \\<forall>x\\<in>A. \\<forall>y\\<in>A. <x,y>:r \\<longleftrightarrow> <f`x,f`y>:s}\"\n\ndefinition\n  pred     :: \"[i,i,i]=>i\"              (*Set of predecessors*)  where\n   \"pred(A,x,r) == {y \\<in> A. <y,x>:r}\"\n\ndefinition\n  ord_iso_map :: \"[i,i,i,i]=>i\"         (*Construction for linearity theorem*)  where\n   \"ord_iso_map(A,r,B,s) ==\n     \\<Union>x\\<in>A. \\<Union>y\\<in>B. \\<Union>f \\<in> ord_iso(pred(A,x,r), r, pred(B,y,s), s). {<x,y>}\"\n\ndefinition\n  first :: \"[i, i, i] => o\"  where\n    \"first(u, X, R) == u \\<in> X & (\\<forall>v\\<in>X. v\\<noteq>u \\<longrightarrow> <u,v> \\<in> R)\"\n\n\nnotation (xsymbols)\n  ord_iso  (\"(\\<langle>_, _\\<rangle> \\<cong>/ \\<langle>_, _\\<rangle>)\" 51)\n\n\nsubsection{*Immediate Consequences of the Definitions*}\n\nlemma part_ord_Imp_asym:\n    \"part_ord(A,r) ==> asym(r \\<inter> A*A)\"\nby (unfold part_ord_def irrefl_def trans_on_def asym_def, blast)\n\nlemma linearE:\n    \"[| linear(A,r);  x \\<in> A;  y \\<in> A;\n        <x,y>:r ==> P;  x=y ==> P;  <y,x>:r ==> P |]\n     ==> P\"\nby (simp add: linear_def, blast)\n\n\n(** General properties of well_ord **)\n\nlemma well_ordI:\n    \"[| wf[A](r); linear(A,r) |] ==> well_ord(A,r)\"\napply (simp add: irrefl_def part_ord_def tot_ord_def\n                 trans_on_def well_ord_def wf_on_not_refl)\napply (fast elim: linearE wf_on_asym wf_on_chain3)\ndone\n\nlemma well_ord_is_wf:\n    \"well_ord(A,r) ==> wf[A](r)\"\nby (unfold well_ord_def, safe)\n\nlemma well_ord_is_trans_on:\n    \"well_ord(A,r) ==> trans[A](r)\"\nby (unfold well_ord_def tot_ord_def part_ord_def, safe)\n\nlemma well_ord_is_linear: \"well_ord(A,r) ==> linear(A,r)\"\nby (unfold well_ord_def tot_ord_def, blast)\n\n\n(** Derived rules for pred(A,x,r) **)\n\nlemma pred_iff: \"y \\<in> pred(A,x,r) \\<longleftrightarrow> <y,x>:r & y \\<in> A\"\nby (unfold pred_def, blast)\n\nlemmas predI = conjI [THEN pred_iff [THEN iffD2]]\n\nlemma predE: \"[| y \\<in> pred(A,x,r);  [| y \\<in> A; <y,x>:r |] ==> P |] ==> P\"\nby (simp add: pred_def)\n\nlemma pred_subset_under: \"pred(A,x,r) \\<subseteq> r -`` {x}\"\nby (simp add: pred_def, blast)\n\nlemma pred_subset: \"pred(A,x,r) \\<subseteq> A\"\nby (simp add: pred_def, blast)\n\nlemma pred_pred_eq:\n    \"pred(pred(A,x,r), y, r) = pred(A,x,r) \\<inter> pred(A,y,r)\"\nby (simp add: pred_def, blast)\n\nlemma trans_pred_pred_eq:\n    \"[| trans[A](r);  <y,x>:r;  x \\<in> A;  y \\<in> A |]\n     ==> pred(pred(A,x,r), y, r) = pred(A,y,r)\"\nby (unfold trans_on_def pred_def, blast)\n\n\nsubsection{*Restricting an Ordering's Domain*}\n\n(** The ordering's properties hold over all subsets of its domain\n    [including initial segments of the form pred(A,x,r) **)\n\n(*Note: a relation s such that s<=r need not be a partial ordering*)\nlemma part_ord_subset:\n    \"[| part_ord(A,r);  B<=A |] ==> part_ord(B,r)\"\nby (unfold part_ord_def irrefl_def trans_on_def, blast)\n\nlemma linear_subset:\n    \"[| linear(A,r);  B<=A |] ==> linear(B,r)\"\nby (unfold linear_def, blast)\n\nlemma tot_ord_subset:\n    \"[| tot_ord(A,r);  B<=A |] ==> tot_ord(B,r)\"\napply (unfold tot_ord_def)\napply (fast elim!: part_ord_subset linear_subset)\ndone\n\nlemma well_ord_subset:\n    \"[| well_ord(A,r);  B<=A |] ==> well_ord(B,r)\"\napply (unfold well_ord_def)\napply (fast elim!: tot_ord_subset wf_on_subset_A)\ndone\n\n\n(** Relations restricted to a smaller domain, by Krzysztof Grabczewski **)\n\nlemma irrefl_Int_iff: \"irrefl(A,r \\<inter> A*A) \\<longleftrightarrow> irrefl(A,r)\"\nby (unfold irrefl_def, blast)\n\nlemma trans_on_Int_iff: \"trans[A](r \\<inter> A*A) \\<longleftrightarrow> trans[A](r)\"\nby (unfold trans_on_def, blast)\n\nlemma part_ord_Int_iff: \"part_ord(A,r \\<inter> A*A) \\<longleftrightarrow> part_ord(A,r)\"\napply (unfold part_ord_def)\napply (simp add: irrefl_Int_iff trans_on_Int_iff)\ndone\n\nlemma linear_Int_iff: \"linear(A,r \\<inter> A*A) \\<longleftrightarrow> linear(A,r)\"\nby (unfold linear_def, blast)\n\nlemma tot_ord_Int_iff: \"tot_ord(A,r \\<inter> A*A) \\<longleftrightarrow> tot_ord(A,r)\"\napply (unfold tot_ord_def)\napply (simp add: part_ord_Int_iff linear_Int_iff)\ndone\n\nlemma wf_on_Int_iff: \"wf[A](r \\<inter> A*A) \\<longleftrightarrow> wf[A](r)\"\napply (unfold wf_on_def wf_def, fast) (*10 times faster than blast!*)\ndone\n\nlemma well_ord_Int_iff: \"well_ord(A,r \\<inter> A*A) \\<longleftrightarrow> well_ord(A,r)\"\napply (unfold well_ord_def)\napply (simp add: tot_ord_Int_iff wf_on_Int_iff)\ndone\n\n\nsubsection{*Empty and Unit Domains*}\n\n(*The empty relation is well-founded*)\nlemma wf_on_any_0: \"wf[A](0)\"\nby (simp add: wf_on_def wf_def, fast)\n\nsubsubsection{*Relations over the Empty Set*}\n\nlemma irrefl_0: \"irrefl(0,r)\"\nby (unfold irrefl_def, blast)\n\nlemma trans_on_0: \"trans[0](r)\"\nby (unfold trans_on_def, blast)\n\nlemma part_ord_0: \"part_ord(0,r)\"\napply (unfold part_ord_def)\napply (simp add: irrefl_0 trans_on_0)\ndone\n\nlemma linear_0: \"linear(0,r)\"\nby (unfold linear_def, blast)\n\nlemma tot_ord_0: \"tot_ord(0,r)\"\napply (unfold tot_ord_def)\napply (simp add: part_ord_0 linear_0)\ndone\n\nlemma wf_on_0: \"wf[0](r)\"\nby (unfold wf_on_def wf_def, blast)\n\nlemma well_ord_0: \"well_ord(0,r)\"\napply (unfold well_ord_def)\napply (simp add: tot_ord_0 wf_on_0)\ndone\n\n\nsubsubsection{*The Empty Relation Well-Orders the Unit Set*}\n\ntext{*by Grabczewski*}\n\nlemma tot_ord_unit: \"tot_ord({a},0)\"\nby (simp add: irrefl_def trans_on_def part_ord_def linear_def tot_ord_def)\n\nlemma well_ord_unit: \"well_ord({a},0)\"\napply (unfold well_ord_def)\napply (simp add: tot_ord_unit wf_on_any_0)\ndone\n\n\nsubsection{*Order-Isomorphisms*}\n\ntext{*Suppes calls them \"similarities\"*}\n\n(** Order-preserving (monotone) maps **)\n\nlemma mono_map_is_fun: \"f \\<in> mono_map(A,r,B,s) ==> f \\<in> A->B\"\nby (simp add: mono_map_def)\n\nlemma mono_map_is_inj:\n    \"[| linear(A,r);  wf[B](s);  f \\<in> mono_map(A,r,B,s) |] ==> f \\<in> inj(A,B)\"\napply (unfold mono_map_def inj_def, clarify)\napply (erule_tac x=w and y=x in linearE, assumption+)\napply (force intro: apply_type dest: wf_on_not_refl)+\ndone\n\nlemma ord_isoI:\n    \"[| f \\<in> bij(A, B);\n        !!x y. [| x \\<in> A; y \\<in> A |] ==> <x, y> \\<in> r \\<longleftrightarrow> <f`x, f`y> \\<in> s |]\n     ==> f \\<in> ord_iso(A,r,B,s)\"\nby (simp add: ord_iso_def)\n\nlemma ord_iso_is_mono_map:\n    \"f \\<in> ord_iso(A,r,B,s) ==> f \\<in> mono_map(A,r,B,s)\"\napply (simp add: ord_iso_def mono_map_def)\napply (blast dest!: bij_is_fun)\ndone\n\nlemma ord_iso_is_bij:\n    \"f \\<in> ord_iso(A,r,B,s) ==> f \\<in> bij(A,B)\"\nby (simp add: ord_iso_def)\n\n(*Needed?  But ord_iso_converse is!*)\nlemma ord_iso_apply:\n    \"[| f \\<in> ord_iso(A,r,B,s);  <x,y>: r;  x \\<in> A;  y \\<in> A |] ==> <f`x, f`y> \\<in> s\"\nby (simp add: ord_iso_def)\n\nlemma ord_iso_converse:\n    \"[| f \\<in> ord_iso(A,r,B,s);  <x,y>: s;  x \\<in> B;  y \\<in> B |]\n     ==> <converse(f) ` x, converse(f) ` y> \\<in> r\"\napply (simp add: ord_iso_def, clarify)\napply (erule bspec [THEN bspec, THEN iffD2])\napply (erule asm_rl bij_converse_bij [THEN bij_is_fun, THEN apply_type])+\napply (auto simp add: right_inverse_bij)\ndone\n\n\n(** Symmetry and Transitivity Rules **)\n\n(*Reflexivity of similarity*)\nlemma ord_iso_refl: \"id(A): ord_iso(A,r,A,r)\"\nby (rule id_bij [THEN ord_isoI], simp)\n\n(*Symmetry of similarity*)\nlemma ord_iso_sym: \"f \\<in> ord_iso(A,r,B,s) ==> converse(f): ord_iso(B,s,A,r)\"\napply (simp add: ord_iso_def)\napply (auto simp add: right_inverse_bij bij_converse_bij\n                      bij_is_fun [THEN apply_funtype])\ndone\n\n(*Transitivity of similarity*)\nlemma mono_map_trans:\n    \"[| g \\<in> mono_map(A,r,B,s);  f \\<in> mono_map(B,s,C,t) |]\n     ==> (f O g): mono_map(A,r,C,t)\"\napply (unfold mono_map_def)\napply (auto simp add: comp_fun)\ndone\n\n(*Transitivity of similarity: the order-isomorphism relation*)\nlemma ord_iso_trans:\n    \"[| g \\<in> ord_iso(A,r,B,s);  f \\<in> ord_iso(B,s,C,t) |]\n     ==> (f O g): ord_iso(A,r,C,t)\"\napply (unfold ord_iso_def, clarify)\napply (frule bij_is_fun [of f])\napply (frule bij_is_fun [of g])\napply (auto simp add: comp_bij)\ndone\n\n(** Two monotone maps can make an order-isomorphism **)\n\nlemma mono_ord_isoI:\n    \"[| f \\<in> mono_map(A,r,B,s);  g \\<in> mono_map(B,s,A,r);\n        f O g = id(B);  g O f = id(A) |] ==> f \\<in> ord_iso(A,r,B,s)\"\napply (simp add: ord_iso_def mono_map_def, safe)\napply (intro fg_imp_bijective, auto)\napply (subgoal_tac \"<g` (f`x), g` (f`y) > \\<in> r\")\napply (simp add: comp_eq_id_iff [THEN iffD1])\napply (blast intro: apply_funtype)\ndone\n\nlemma well_ord_mono_ord_isoI:\n     \"[| well_ord(A,r);  well_ord(B,s);\n         f \\<in> mono_map(A,r,B,s);  converse(f): mono_map(B,s,A,r) |]\n      ==> f \\<in> ord_iso(A,r,B,s)\"\napply (intro mono_ord_isoI, auto)\napply (frule mono_map_is_fun [THEN fun_is_rel])\napply (erule converse_converse [THEN subst], rule left_comp_inverse)\napply (blast intro: left_comp_inverse mono_map_is_inj well_ord_is_linear\n                    well_ord_is_wf)+\ndone\n\n\n(** Order-isomorphisms preserve the ordering's properties **)\n\nlemma part_ord_ord_iso:\n    \"[| part_ord(B,s);  f \\<in> ord_iso(A,r,B,s) |] ==> part_ord(A,r)\"\napply (simp add: part_ord_def irrefl_def trans_on_def ord_iso_def)\napply (fast intro: bij_is_fun [THEN apply_type])\ndone\n\nlemma linear_ord_iso:\n    \"[| linear(B,s);  f \\<in> ord_iso(A,r,B,s) |] ==> linear(A,r)\"\napply (simp add: linear_def ord_iso_def, safe)\napply (drule_tac x1 = \"f`x\" and x = \"f`y\" in bspec [THEN bspec])\napply (safe elim!: bij_is_fun [THEN apply_type])\napply (drule_tac t = \"op ` (converse (f))\" in subst_context)\napply (simp add: left_inverse_bij)\ndone\n\nlemma wf_on_ord_iso:\n    \"[| wf[B](s);  f \\<in> ord_iso(A,r,B,s) |] ==> wf[A](r)\"\napply (simp add: wf_on_def wf_def ord_iso_def, safe)\napply (drule_tac x = \"{f`z. z \\<in> Z \\<inter> A}\" in spec)\napply (safe intro!: equalityI)\napply (blast dest!: equalityD1 intro: bij_is_fun [THEN apply_type])+\ndone\n\nlemma well_ord_ord_iso:\n    \"[| well_ord(B,s);  f \\<in> ord_iso(A,r,B,s) |] ==> well_ord(A,r)\"\napply (unfold well_ord_def tot_ord_def)\napply (fast elim!: part_ord_ord_iso linear_ord_iso wf_on_ord_iso)\ndone\n\n\nsubsection{*Main results of Kunen, Chapter 1 section 6*}\n\n(*Inductive argument for Kunen's Lemma 6.1, etc.\n  Simple proof from Halmos, page 72*)\nlemma well_ord_iso_subset_lemma:\n     \"[| well_ord(A,r);  f \\<in> ord_iso(A,r, A',r);  A'<= A;  y \\<in> A |]\n      ==> ~ <f`y, y>: r\"\napply (simp add: well_ord_def ord_iso_def)\napply (elim conjE CollectE)\napply (rule_tac a=y in wf_on_induct, assumption+)\napply (blast dest: bij_is_fun [THEN apply_type])\ndone\n\n(*Kunen's Lemma 6.1 \\<in> there's no order-isomorphism to an initial segment\n                     of a well-ordering*)\nlemma well_ord_iso_predE:\n     \"[| well_ord(A,r);  f \\<in> ord_iso(A, r, pred(A,x,r), r);  x \\<in> A |] ==> P\"\napply (insert well_ord_iso_subset_lemma [of A r f \"pred(A,x,r)\" x])\napply (simp add: pred_subset)\n(*Now we know  f`x < x *)\napply (drule ord_iso_is_bij [THEN bij_is_fun, THEN apply_type], assumption)\n(*Now we also know @{term\"f`x \\<in> pred(A,x,r)\"}: contradiction! *)\napply (simp add: well_ord_def pred_def)\ndone\n\n(*Simple consequence of Lemma 6.1*)\nlemma well_ord_iso_pred_eq:\n     \"[| well_ord(A,r);  f \\<in> ord_iso(pred(A,a,r), r, pred(A,c,r), r);\n         a \\<in> A;  c \\<in> A |] ==> a=c\"\napply (frule well_ord_is_trans_on)\napply (frule well_ord_is_linear)\napply (erule_tac x=a and y=c in linearE, assumption+)\napply (drule ord_iso_sym)\n(*two symmetric cases*)\napply (auto elim!: well_ord_subset [OF _ pred_subset, THEN well_ord_iso_predE]\n            intro!: predI\n            simp add: trans_pred_pred_eq)\ndone\n\n(*Does not assume r is a wellordering!*)\nlemma ord_iso_image_pred:\n     \"[|f \\<in> ord_iso(A,r,B,s);  a \\<in> A|] ==> f `` pred(A,a,r) = pred(B, f`a, s)\"\napply (unfold ord_iso_def pred_def)\napply (erule CollectE)\napply (simp (no_asm_simp) add: image_fun [OF bij_is_fun Collect_subset])\napply (rule equalityI)\napply (safe elim!: bij_is_fun [THEN apply_type])\napply (rule RepFun_eqI)\napply (blast intro!: right_inverse_bij [symmetric])\napply (auto simp add: right_inverse_bij  bij_is_fun [THEN apply_funtype])\ndone\n\nlemma ord_iso_restrict_image:\n     \"[| f \\<in> ord_iso(A,r,B,s);  C<=A |]\n      ==> restrict(f,C) \\<in> ord_iso(C, r, f``C, s)\"\napply (simp add: ord_iso_def)\napply (blast intro: bij_is_inj restrict_bij)\ndone\n\n(*But in use, A and B may themselves be initial segments.  Then use\n  trans_pred_pred_eq to simplify the pred(pred...) terms.  See just below.*)\nlemma ord_iso_restrict_pred:\n   \"[| f \\<in> ord_iso(A,r,B,s);   a \\<in> A |]\n    ==> restrict(f, pred(A,a,r)) \\<in> ord_iso(pred(A,a,r), r, pred(B, f`a, s), s)\"\napply (simp add: ord_iso_image_pred [symmetric])\napply (blast intro: ord_iso_restrict_image elim: predE)\ndone\n\n(*Tricky; a lot of forward proof!*)\nlemma well_ord_iso_preserving:\n     \"[| well_ord(A,r);  well_ord(B,s);  <a,c>: r;\n         f \\<in> ord_iso(pred(A,a,r), r, pred(B,b,s), s);\n         g \\<in> ord_iso(pred(A,c,r), r, pred(B,d,s), s);\n         a \\<in> A;  c \\<in> A;  b \\<in> B;  d \\<in> B |] ==> <b,d>: s\"\napply (frule ord_iso_is_bij [THEN bij_is_fun, THEN apply_type], (erule asm_rl predI predE)+)\napply (subgoal_tac \"b = g`a\")\napply (simp (no_asm_simp))\napply (rule well_ord_iso_pred_eq, auto)\napply (frule ord_iso_restrict_pred, (erule asm_rl predI)+)\napply (simp add: well_ord_is_trans_on trans_pred_pred_eq)\napply (erule ord_iso_sym [THEN ord_iso_trans], assumption)\ndone\n\n(*See Halmos, page 72*)\nlemma well_ord_iso_unique_lemma:\n     \"[| well_ord(A,r);\n         f \\<in> ord_iso(A,r, B,s);  g \\<in> ord_iso(A,r, B,s);  y \\<in> A |]\n      ==> ~ <g`y, f`y> \\<in> s\"\napply (frule well_ord_iso_subset_lemma)\napply (rule_tac f = \"converse (f) \" and g = g in ord_iso_trans)\napply auto\napply (blast intro: ord_iso_sym)\napply (frule ord_iso_is_bij [of f])\napply (frule ord_iso_is_bij [of g])\napply (frule ord_iso_converse)\napply (blast intro!: bij_converse_bij\n             intro: bij_is_fun apply_funtype)+\napply (erule notE)\napply (simp add: left_inverse_bij bij_is_fun comp_fun_apply [of _ A B])\ndone\n\n\n(*Kunen's Lemma 6.2: Order-isomorphisms between well-orderings are unique*)\nlemma well_ord_iso_unique: \"[| well_ord(A,r);\n         f \\<in> ord_iso(A,r, B,s);  g \\<in> ord_iso(A,r, B,s) |] ==> f = g\"\napply (rule fun_extension)\napply (erule ord_iso_is_bij [THEN bij_is_fun])+\napply (subgoal_tac \"f`x \\<in> B & g`x \\<in> B & linear(B,s)\")\n apply (simp add: linear_def)\n apply (blast dest: well_ord_iso_unique_lemma)\napply (blast intro: ord_iso_is_bij bij_is_fun apply_funtype\n                    well_ord_is_linear well_ord_ord_iso ord_iso_sym)\ndone\n\nsubsection{*Towards Kunen's Theorem 6.3: Linearity of the Similarity Relation*}\n\nlemma ord_iso_map_subset: \"ord_iso_map(A,r,B,s) \\<subseteq> A*B\"\nby (unfold ord_iso_map_def, blast)\n\nlemma domain_ord_iso_map: \"domain(ord_iso_map(A,r,B,s)) \\<subseteq> A\"\nby (unfold ord_iso_map_def, blast)\n\nlemma range_ord_iso_map: \"range(ord_iso_map(A,r,B,s)) \\<subseteq> B\"\nby (unfold ord_iso_map_def, blast)\n\nlemma converse_ord_iso_map:\n    \"converse(ord_iso_map(A,r,B,s)) = ord_iso_map(B,s,A,r)\"\napply (unfold ord_iso_map_def)\napply (blast intro: ord_iso_sym)\ndone\n\nlemma function_ord_iso_map:\n    \"well_ord(B,s) ==> function(ord_iso_map(A,r,B,s))\"\napply (unfold ord_iso_map_def function_def)\napply (blast intro: well_ord_iso_pred_eq ord_iso_sym ord_iso_trans)\ndone\n\nlemma ord_iso_map_fun: \"well_ord(B,s) ==> ord_iso_map(A,r,B,s)\n           \\<in> domain(ord_iso_map(A,r,B,s)) -> range(ord_iso_map(A,r,B,s))\"\nby (simp add: Pi_iff function_ord_iso_map\n                 ord_iso_map_subset [THEN domain_times_range])\n\nlemma ord_iso_map_mono_map:\n    \"[| well_ord(A,r);  well_ord(B,s) |]\n     ==> ord_iso_map(A,r,B,s)\n           \\<in> mono_map(domain(ord_iso_map(A,r,B,s)), r,\n                      range(ord_iso_map(A,r,B,s)), s)\"\napply (unfold mono_map_def)\napply (simp (no_asm_simp) add: ord_iso_map_fun)\napply safe\napply (subgoal_tac \"x \\<in> A & ya:A & y \\<in> B & yb:B\")\n apply (simp add: apply_equality [OF _  ord_iso_map_fun])\n apply (unfold ord_iso_map_def)\n apply (blast intro: well_ord_iso_preserving, blast)\ndone\n\nlemma ord_iso_map_ord_iso:\n    \"[| well_ord(A,r);  well_ord(B,s) |] ==> ord_iso_map(A,r,B,s)\n           \\<in> ord_iso(domain(ord_iso_map(A,r,B,s)), r,\n                      range(ord_iso_map(A,r,B,s)), s)\"\napply (rule well_ord_mono_ord_isoI)\n   prefer 4\n   apply (rule converse_ord_iso_map [THEN subst])\n   apply (simp add: ord_iso_map_mono_map\n                    ord_iso_map_subset [THEN converse_converse])\napply (blast intro!: domain_ord_iso_map range_ord_iso_map\n             intro: well_ord_subset ord_iso_map_mono_map)+\ndone\n\n\n(*One way of saying that domain(ord_iso_map(A,r,B,s)) is downwards-closed*)\nlemma domain_ord_iso_map_subset:\n     \"[| well_ord(A,r);  well_ord(B,s);\n         a \\<in> A;  a \\<notin> domain(ord_iso_map(A,r,B,s)) |]\n      ==>  domain(ord_iso_map(A,r,B,s)) \\<subseteq> pred(A, a, r)\"\napply (unfold ord_iso_map_def)\napply (safe intro!: predI)\n(*Case analysis on  xa vs a in r *)\napply (simp (no_asm_simp))\napply (frule_tac A = A in well_ord_is_linear)\napply (rename_tac b y f)\napply (erule_tac x=b and y=a in linearE, assumption+)\n(*Trivial case: b=a*)\napply clarify\napply blast\n(*Harder case: <a, xa>: r*)\napply (frule ord_iso_is_bij [THEN bij_is_fun, THEN apply_type],\n       (erule asm_rl predI predE)+)\napply (frule ord_iso_restrict_pred)\n apply (simp add: pred_iff)\napply (simp split: split_if_asm\n          add: well_ord_is_trans_on trans_pred_pred_eq domain_UN domain_Union, blast)\ndone\n\n(*For the 4-way case analysis in the main result*)\nlemma domain_ord_iso_map_cases:\n     \"[| well_ord(A,r);  well_ord(B,s) |]\n      ==> domain(ord_iso_map(A,r,B,s)) = A |\n          (\\<exists>x\\<in>A. domain(ord_iso_map(A,r,B,s)) = pred(A,x,r))\"\napply (frule well_ord_is_wf)\napply (unfold wf_on_def wf_def)\napply (drule_tac x = \"A-domain (ord_iso_map (A,r,B,s))\" in spec)\napply safe\n(*The first case: the domain equals A*)\napply (rule domain_ord_iso_map [THEN equalityI])\napply (erule Diff_eq_0_iff [THEN iffD1])\n(*The other case: the domain equals an initial segment*)\napply (blast del: domainI subsetI\n             elim!: predE\n             intro!: domain_ord_iso_map_subset\n             intro: subsetI)+\ndone\n\n(*As above, by duality*)\nlemma range_ord_iso_map_cases:\n    \"[| well_ord(A,r);  well_ord(B,s) |]\n     ==> range(ord_iso_map(A,r,B,s)) = B |\n         (\\<exists>y\\<in>B. range(ord_iso_map(A,r,B,s)) = pred(B,y,s))\"\napply (rule converse_ord_iso_map [THEN subst])\napply (simp add: domain_ord_iso_map_cases)\ndone\n\ntext{*Kunen's Theorem 6.3: Fundamental Theorem for Well-Ordered Sets*}\ntheorem well_ord_trichotomy:\n   \"[| well_ord(A,r);  well_ord(B,s) |]\n    ==> ord_iso_map(A,r,B,s) \\<in> ord_iso(A, r, B, s) |\n        (\\<exists>x\\<in>A. ord_iso_map(A,r,B,s) \\<in> ord_iso(pred(A,x,r), r, B, s)) |\n        (\\<exists>y\\<in>B. ord_iso_map(A,r,B,s) \\<in> ord_iso(A, r, pred(B,y,s), s))\"\napply (frule_tac B = B in domain_ord_iso_map_cases, assumption)\napply (frule_tac B = B in range_ord_iso_map_cases, assumption)\napply (drule ord_iso_map_ord_iso, assumption)\napply (elim disjE bexE)\n   apply (simp_all add: bexI)\napply (rule wf_on_not_refl [THEN notE])\n  apply (erule well_ord_is_wf)\n apply assumption\napply (subgoal_tac \"<x,y>: ord_iso_map (A,r,B,s) \")\n apply (drule rangeI)\n apply (simp add: pred_def)\napply (unfold ord_iso_map_def, blast)\ndone\n\n\nsubsection{*Miscellaneous Results by Krzysztof Grabczewski*}\n\n(** Properties of converse(r) **)\n\nlemma irrefl_converse: \"irrefl(A,r) ==> irrefl(A,converse(r))\"\nby (unfold irrefl_def, blast)\n\nlemma trans_on_converse: \"trans[A](r) ==> trans[A](converse(r))\"\nby (unfold trans_on_def, blast)\n\nlemma part_ord_converse: \"part_ord(A,r) ==> part_ord(A,converse(r))\"\napply (unfold part_ord_def)\napply (blast intro!: irrefl_converse trans_on_converse)\ndone\n\nlemma linear_converse: \"linear(A,r) ==> linear(A,converse(r))\"\nby (unfold linear_def, blast)\n\nlemma tot_ord_converse: \"tot_ord(A,r) ==> tot_ord(A,converse(r))\"\napply (unfold tot_ord_def)\napply (blast intro!: part_ord_converse linear_converse)\ndone\n\n\n(** By Krzysztof Grabczewski.\n    Lemmas involving the first element of a well ordered set **)\n\nlemma first_is_elem: \"first(b,B,r) ==> b \\<in> B\"\nby (unfold first_def, blast)\n\nlemma well_ord_imp_ex1_first:\n        \"[| well_ord(A,r); B<=A; B\\<noteq>0 |] ==> (EX! b. first(b,B,r))\"\napply (unfold well_ord_def wf_on_def wf_def first_def)\napply (elim conjE allE disjE, blast)\napply (erule bexE)\napply (rule_tac a = x in ex1I, auto)\napply (unfold tot_ord_def linear_def, blast)\ndone\n\nlemma the_first_in:\n     \"[| well_ord(A,r); B<=A; B\\<noteq>0 |] ==> (THE b. first(b,B,r)) \\<in> B\"\napply (drule well_ord_imp_ex1_first, assumption+)\napply (rule first_is_elem)\napply (erule theI)\ndone\n\n\nsubsection {* Lemmas for the Reflexive Orders *}\n\nlemma subset_vimage_vimage_iff:\n  \"[| Preorder(r); A \\<subseteq> field(r); B \\<subseteq> field(r) |] ==>\n  r -`` A \\<subseteq> r -`` B \\<longleftrightarrow> (\\<forall>a\\<in>A. \\<exists>b\\<in>B. <a, b> \\<in> r)\"\n  apply (auto simp: subset_def preorder_on_def refl_def vimage_def image_def)\n   apply blast\n  unfolding trans_on_def\n  apply (erule_tac P = \"(\\<lambda>x. \\<forall>y\\<in>field(?r).\n          \\<forall>z\\<in>field(?r). \\<langle>x, y\\<rangle> \\<in> ?r \\<longrightarrow> \\<langle>y, z\\<rangle> \\<in> ?r \\<longrightarrow> \\<langle>x, z\\<rangle> \\<in> ?r)\" in rev_ballE)\n    (* instance obtained from proof term generated by best *)\n   apply best\n  apply blast\n  done\n\nlemma subset_vimage1_vimage1_iff:\n  \"[| Preorder(r); a \\<in> field(r); b \\<in> field(r) |] ==>\n  r -`` {a} \\<subseteq> r -`` {b} \\<longleftrightarrow> <a, b> \\<in> r\"\n  by (simp add: subset_vimage_vimage_iff)\n\nlemma Refl_antisym_eq_Image1_Image1_iff:\n  \"[| refl(field(r), r); antisym(r); a \\<in> field(r); b \\<in> field(r) |] ==>\n  r `` {a} = r `` {b} \\<longleftrightarrow> a = b\"\n  apply rule\n   apply (frule equality_iffD)\n   apply (drule equality_iffD)\n   apply (simp add: antisym_def refl_def)\n   apply best\n  apply (simp add: antisym_def refl_def)\n  done\n\nlemma Partial_order_eq_Image1_Image1_iff:\n  \"[| Partial_order(r); a \\<in> field(r); b \\<in> field(r) |] ==>\n  r `` {a} = r `` {b} \\<longleftrightarrow> a = b\"\n  by (simp add: partial_order_on_def preorder_on_def\n    Refl_antisym_eq_Image1_Image1_iff)\n\nlemma Refl_antisym_eq_vimage1_vimage1_iff:\n  \"[| refl(field(r), r); antisym(r); a \\<in> field(r); b \\<in> field(r) |] ==>\n  r -`` {a} = r -`` {b} \\<longleftrightarrow> a = b\"\n  apply rule\n   apply (frule equality_iffD)\n   apply (drule equality_iffD)\n   apply (simp add: antisym_def refl_def)\n   apply best\n  apply (simp add: antisym_def refl_def)\n  done\n\nlemma Partial_order_eq_vimage1_vimage1_iff:\n  \"[| Partial_order(r); a \\<in> field(r); b \\<in> field(r) |] ==>\n  r -`` {a} = r -`` {b} \\<longleftrightarrow> a = b\"\n  by (simp add: partial_order_on_def preorder_on_def\n    Refl_antisym_eq_vimage1_vimage1_iff)\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/Order.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797124237605, "lm_q2_score": 0.8031737892899222, "lm_q1q2_score": 0.7318356623514933}}
{"text": "(*  Title:      HOL/Library/Order_Continuity.thy\n    Author:     David von Oheimb, TU Muenchen\n*)\n\nsection {* Continuity and iterations (of set transformers) *}\n\ntheory Order_Continuity\nimports Main\nbegin\n\n(* TODO: Generalize theory to chain-complete partial orders *)\n\nlemma SUP_nat_binary:\n  \"(SUP n::nat. if n = 0 then A else B) = (sup A B::'a::complete_lattice)\"\n  apply (auto intro!: antisym SUP_least)\n  apply (rule SUP_upper2[where i=0])\n  apply simp_all\n  apply (rule SUP_upper2[where i=1])\n  apply simp_all\n  done\n\nlemma INF_nat_binary:\n  \"(INF n::nat. if n = 0 then A else B) = (inf A B::'a::complete_lattice)\"\n  apply (auto intro!: antisym INF_greatest)\n  apply (rule INF_lower2[where i=0])\n  apply simp_all\n  apply (rule INF_lower2[where i=1])\n  apply simp_all\n  done\n\nsubsection {* Continuity for complete lattices *}\n\ndefinition\n  continuous :: \"('a::complete_lattice \\<Rightarrow> 'a::complete_lattice) \\<Rightarrow> bool\" where\n  \"continuous F \\<longleftrightarrow> (\\<forall>M::nat \\<Rightarrow> 'a. mono M \\<longrightarrow> F (SUP i. M i) = (SUP i. F (M i)))\"\n\nlemma continuousD: \"continuous F \\<Longrightarrow> mono M \\<Longrightarrow> F (SUP i::nat. M i) = (SUP i. F (M i))\"\n  by (auto simp: continuous_def)\n\nlemma continuous_mono:\n  fixes F :: \"'a::complete_lattice \\<Rightarrow> 'a::complete_lattice\"\n  assumes [simp]: \"continuous F\" shows \"mono F\"\nproof\n  fix A B :: \"'a\" assume [simp]: \"A \\<le> B\"\n  have \"F B = F (SUP n::nat. if n = 0 then A else B)\"\n    by (simp add: sup_absorb2 SUP_nat_binary)\n  also have \"\\<dots> = (SUP n::nat. if n = 0 then F A else F B)\"\n    by (auto simp: continuousD mono_def intro!: SUP_cong)\n  finally show \"F A \\<le> F B\"\n    by (simp add: SUP_nat_binary le_iff_sup)\nqed\n\nlemma continuous_lfp:\n  assumes \"continuous F\" shows \"lfp F = (SUP i. (F ^^ i) bot)\" (is \"lfp F = ?U\")\nproof (rule antisym)\n  note mono = continuous_mono[OF `continuous F`]\n  show \"?U \\<le> lfp F\"\n  proof (rule SUP_least)\n    fix i show \"(F ^^ i) bot \\<le> lfp F\"\n    proof (induct i)\n      case (Suc i)\n      have \"(F ^^ Suc i) bot = F ((F ^^ i) bot)\" by simp\n      also have \"\\<dots> \\<le> F (lfp F)\" by (rule monoD[OF mono Suc])\n      also have \"\\<dots> = lfp F\" by (simp add: lfp_unfold[OF mono, symmetric])\n      finally show ?case .\n    qed simp\n  qed\n  show \"lfp F \\<le> ?U\"\n  proof (rule lfp_lowerbound)\n    have \"mono (\\<lambda>i::nat. (F ^^ i) bot)\"\n    proof -\n      { fix i::nat have \"(F ^^ i) bot \\<le> (F ^^ (Suc i)) bot\"\n        proof (induct i)\n          case 0 show ?case by simp\n        next\n          case Suc thus ?case using monoD[OF mono Suc] by auto\n        qed }\n      thus ?thesis by (auto simp add: mono_iff_le_Suc)\n    qed\n    hence \"F ?U = (SUP i. (F ^^ Suc i) bot)\" using `continuous F` by (simp add: continuous_def)\n    also have \"\\<dots> \\<le> ?U\" by (fast intro: SUP_least SUP_upper)\n    finally show \"F ?U \\<le> ?U\" .\n  qed\nqed\n\ndefinition\n  down_continuous :: \"('a::complete_lattice \\<Rightarrow> 'a::complete_lattice) \\<Rightarrow> bool\" where\n  \"down_continuous F \\<longleftrightarrow> (\\<forall>M::nat \\<Rightarrow> 'a. antimono M \\<longrightarrow> F (INF i. M i) = (INF i. F (M i)))\"\n\nlemma down_continuousD: \"down_continuous F \\<Longrightarrow> antimono M \\<Longrightarrow> F (INF i::nat. M i) = (INF i. F (M i))\"\n  by (auto simp: down_continuous_def)\n\nlemma down_continuous_mono:\n  fixes F :: \"'a::complete_lattice \\<Rightarrow> 'a::complete_lattice\"\n  assumes [simp]: \"down_continuous F\" shows \"mono F\"\nproof\n  fix A B :: \"'a\" assume [simp]: \"A \\<le> B\"\n  have \"F A = F (INF n::nat. if n = 0 then B else A)\"\n    by (simp add: inf_absorb2 INF_nat_binary)\n  also have \"\\<dots> = (INF n::nat. if n = 0 then F B else F A)\"\n    by (auto simp: down_continuousD antimono_def intro!: INF_cong)\n  finally show \"F A \\<le> F B\"\n    by (simp add: INF_nat_binary le_iff_inf inf_commute)\nqed\n\nlemma down_continuous_gfp:\n  assumes \"down_continuous F\" shows \"gfp F = (INF i. (F ^^ i) top)\" (is \"gfp F = ?U\")\nproof (rule antisym)\n  note mono = down_continuous_mono[OF `down_continuous F`]\n  show \"gfp F \\<le> ?U\"\n  proof (rule INF_greatest)\n    fix i show \"gfp F \\<le> (F ^^ i) top\"\n    proof (induct i)\n      case (Suc i)\n      have \"gfp F = F (gfp F)\" by (simp add: gfp_unfold[OF mono, symmetric])\n      also have \"\\<dots> \\<le> F ((F ^^ i) top)\" by (rule monoD[OF mono Suc])\n      also have \"\\<dots> = (F ^^ Suc i) top\" by simp\n      finally show ?case .\n    qed simp\n  qed\n  show \"?U \\<le> gfp F\"\n  proof (rule gfp_upperbound)\n    have *: \"antimono (\\<lambda>i::nat. (F ^^ i) top)\"\n    proof -\n      { fix i::nat have \"(F ^^ Suc i) top \\<le> (F ^^ i) top\"\n        proof (induct i)\n          case 0 show ?case by simp\n        next\n          case Suc thus ?case using monoD[OF mono Suc] by auto\n        qed }\n      thus ?thesis by (auto simp add: antimono_iff_le_Suc)\n    qed\n    have \"?U \\<le> (INF i. (F ^^ Suc i) top)\"\n      by (fast intro: INF_greatest INF_lower)\n    also have \"\\<dots> \\<le> F ?U\"\n      by (simp add: down_continuousD `down_continuous F` *)\n    finally show \"?U \\<le> F ?U\" .\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/Order_Continuity.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797075998823, "lm_q2_score": 0.803173791645582, "lm_q1q2_score": 0.7318356606235102}}
{"text": "(*<*)\ntheory Geometria\nimports Main  \"HOL-Library.LaTeXsugar\" \"HOL-Library.OptionalSugar\" \nbegin\n(*>*)\n\nsection \\<open>Introducci\u00f3n a la geometr\u00eda \\<close>\n\ntext \\<open>La geometr\u00eda posee una larga de historia de estar presentada y\n representada por sistemas axiom\u00e1ticos; es decir, mediante conjuntos de\n axiomas a partir del cual se pueden derivar l\u00f3gicamente teoremas. Un \n axioma es una declaraci\u00f3n que se considera verdadera, que sirve como \n punto de partida para razonamientos y argumentos adicionales.\n\n Por ello, vamos a representar la geometria simple, que la entenderemos\n definiendo el plano como un conjunto de puntos y las l\u00edneas como \n conjuntos de puntos, la geometr\u00eda no proyectiva a\u00f1adi\u00e9ndole un axioma a \n la simple y por  \u00faltimo, la geometria proyectiva a\u00f1adiendole 3 axiomas \n a la simple. \n\n Todo esto se definir\u00e1 en Isabelle/HOL como un entorno local. Un entorno\n local o declaraci\u00f3n local consiste en secuencia de elementos que\n declarar\u00e1n par\u00e1metros(\\textbf{fixed}) y suposiciones\n (\\textbf{assumption}).\n\n Tambi\u00e9n de cada tipo de geometr\u00eda se dar\u00e1 el modelo m\u00ednimo que posee\n cada una, esto se har\u00e1 mediante el comando \\textbf{interpretation}.\n El comando \\textbf{interpretation} como su nombre indica consiste en\n interpretar los comandos locales; es decir, dar un modelo (que en este\n caso ser\u00e1 el m\u00ednimo que ofrece cada entorno local) y probar todos los\n axiomas que este tenga.\n\\<close>\n\nsection \\<open>Geometr\u00eda simple \\<close>\n\nsubsection \\<open>Entorno local \\<close>\n\ntext \\<open>La geometr\u00eda simple, como ya se ha dicho anteriormente, posee tres\n elementos fundamentales. Los puntos, el plano, que es el conjunto de\n todos ellos, y las rectas, que son conjuntos de puntos. Esta geometr\u00eda\n posee 5 axiomas:\n \\begin{enumerate}\n  \\item{El plano es no vac\u00edo.}\n  \\item{Toda l\u00ednea es un subconjunto no vac\u00edo del plano.}\n  \\item{Para cualquier par de puntos en el plano, existe una l\u00ednea que\n    contiene a ambos.}\n  \\item{Dos l\u00edneas diferentes se cortan en no m\u00e1s de un punto.}\n  \\item{Para cada l\u00ednea, existe un punto del plano que no pertenece a\n    ella.}\n \\end{enumerate}\n\n Se ha declarado un entorno local, denotado \\textbf{Simple$-$Geometry}, \n con un par de constantes (\\textbf{lines} y \\textbf{plane}) junto con \n los 5 axiomas anteriores.\\<close>\n\nlocale Simple_Geometry =\n  fixes plane :: \"'a set\"\n  fixes lines :: \"('a set) set\"\n  assumes A1: \"plane \\<noteq> {}\"\n      and A2: \"\\<forall>l \\<in> lines. l \\<subseteq> plane \\<and> l \\<noteq> {}\"\n      and A3: \"\\<forall>p \\<in> plane. \\<forall>q \\<in> plane. \\<exists>l \\<in> lines. {p,q} \\<subseteq> l\"\n      and A4: \"\\<forall>l \\<in> lines. \\<forall>r \\<in> lines.\n               l \\<noteq> r  \\<longrightarrow>  l \\<inter> r = {} \\<or> (\\<exists>q \\<in> plane. l \\<inter> r = {q}) \"\n      and A5: \"\\<forall>l \\<in> lines. \\<exists>q \\<in> plane. q \\<notin> l\"\n\ntext \\<open>A pesar de la definici\u00f3n del anterior entorno local con 5 axiomas, \n no en todas las demostraciones, se van a usar todos ellos. Sin embargo, \n al haber definido tanto las l\u00edneas como el plano como conjuntos\n tenemos todas las funciones definidas en Isabelle/HOL de la teor\u00eda de\n conjuntos\n  \\href{https://www.cl.cam.ac.uk/research/hvg/Isabelle/dist/library/HOL/HOL/Set.html}{Set.thy}.\n\\<close>\n\nsubsection \\<open>Proposiciones de geometr\u00eda simple\\<close>\n\ntext \\<open>A continuaci\u00f3n vamos a presentar una serie de lemas que vamos a\n demostrar dentro del entorno de la geometr\u00eda simple.\n\n El primer lema es el siguiente:\n \\begin{lema}\\label{one-line-exists}\n  Existe al menos una l\u00ednea.\n \\end{lema}\n\n \\begin{demostracion}\n Vamos a demostrar que el conjunto de l\u00edneas es no vac\u00edo. Para ello,\n supongamos en primer lugar, por el axioma A1, que $q$ es un punto del\n plano. Entonces, por el axioma A3, tenemos que existe una l\u00ednea $l$\n tal que $\\{q,q\\} \\subseteq l$. Luego, ya hemos probado que existe \n una l\u00ednea.\n \\end{demostracion}\n\n La formalizaci\u00f3n del lema y su demostraci\u00f3n en Isabelle/HOl es la \n siguiente:\\<close>\n\nlemma (in Simple_Geometry) one_line_exists:\n  \"\\<exists>l. l \\<in> lines \" \nproof - \n  have \"\\<exists>q. q \\<in> plane \" using A1 by auto\n  then obtain \"q1\" where \"q1 \\<in> plane\" by (rule exE)\n  then obtain \"\\<exists>l \\<in> lines. {q1, q1} \\<subseteq> l\" using A3 by auto\n  then show ?thesis by auto\nqed\n\ntext \\<open>El segundo lema es el siguiente \n  \\begin{lema}\n    Existen al menos dos puntos que son diferentes en el plano \n  \\end{lema}\n\n  \\begin{demostracion}\n  Para la demostraci\u00f3n del lema, usando el lema anterior, tenemos\n  que existe una l\u00ednea $l$. Adem\u00e1s, por el axioma A2, sabemos que \n  $l \\neq \\emptyset$ lo que implica que existe un punto $q$ en $l$. Por \n  otro lado, por el axioma A5, sabemos que existe un punto $p$ que \n  no est\u00e1 en $l$. Luego ya tenemos probada la existencia de dos puntos. \n  A parte, como $p \\notin l$ y $q \\in l$ tienen que ser distintos. \n  \\end{demostracion}\n\n  La especificaci\u00f3n y demostraci\u00f3n del lema en Isabelle/HOL es la \n  siguiente:\\<close>\n\nlemma (in Simple_Geometry) two_points_exist:\n  \"\\<exists>p1 p2. p1 \\<noteq> p2 \\<and> {p1, p2} \\<subseteq> plane\"\nproof -\n  obtain \"l1\" where \"l1 \\<in> lines\" \n    using one_line_exists by (rule exE)\n  then obtain \"l1 \\<subseteq> plane \\<and> l1 \\<noteq> {}\" \n    using A2 by auto\n  then have \"\\<exists>q. q \\<in> l1 \\<and> q \\<in> plane\" \n    by auto\n  then obtain \"p1\" where \"p1 \\<in> l1 \\<and> p1 \\<in> plane\" \n    by (rule exE)\n  moreover obtain \"p2\" where \"p2 \\<in> plane \\<and> p2 \\<notin> l1\" \n    using \\<open>l1 \\<in> lines\\<close> A5 by auto\n  ultimately show ?thesis  \n    by force \nqed\n\ntext \\<open>El siguiente lema es el siguiente: \n  \\begin{lema}\n    Existen al menos tres puntos diferentes en el plano.\n  \\end{lema}\n\n  \\begin{demostracion}\n  Para la demostraci\u00f3n del lema vamos a usar el lema anterior; es decir,\n  tenemos que existen dos puntos distintos $p$ y $q$. Por el axioma A3, \n  se tiene que existe una l\u00ednea $l$ que pasa por esos dos puntos. \n  Usando el axioma A5, sabemos que existe un punto $r$ que no pertenece\n  a $l$. Veamos que son diferentes; es decir, como hemos tomado \n  $p \\neq q$ simplemente tenemos que probar que $r \\neq q$ y $r \\neq p$. \n  Como $r \\notin l$ ya se tiene la prueba.\n  \\end{demostracion}\n\n  La especificaci\u00f3n y demostraci\u00f3n del lema en Isabelle/HOL es la \n  siguiente:\\<close>\n\nlemma (in Simple_Geometry) three_points_exist:\n  \"\\<exists>p1 p2 p3. distinct [p1, p2, p3] \\<and> {p1, p2, p3} \\<subseteq> plane\" \nproof - \n  obtain \"p1\" \"p2\"  where  \"p1 \\<noteq> p2 \\<and> {p1, p2} \\<subseteq> plane\"\n    using two_points_exist by auto  \n  moreover then obtain \"l1\" where \"l1 \\<in> lines \\<and> {p1, p2} \\<subseteq> l1\" \n    using A3 by auto\n  moreover then obtain \"p3\" where \"p3 \\<in> plane \\<and> p3 \\<notin> l1\" \n    using A5 by auto\n  ultimately have \"distinct [p1, p2, p3] \\<and> {p1, p2, p3} \\<subseteq> plane\" \n    by auto\n  then show ?thesis \n    by (intro exI)\nqed\n\ntext \\<open>El siguiente lema es una consecuencia inmediata del lema anterior.\n\n  \\begin{lema}\n    Si el plano es finito, entonces la cardinalidad del plano es mayor o \n    igual que 3.\n    \\end{lema}\n\n  La especificaci\u00f3n y demostraci\u00f3n del lema en Isabelle/HOL es la \n  siguiente:\\<close>\n\nlemma (in Simple_Geometry) card_of_plane_greater:\n  assumes \"finite plane\" \n  shows \"card plane \\<ge> 3\"\nproof -\n  obtain \"p1\" \"p2\" \"p3\" where \n    \"distinct [p1, p2, p3] \\<and> {p1, p2, p3} \\<subseteq> plane\"\n    using three_points_exist by auto\n  moreover then have \"{p1, p2, p3} \\<subseteq> plane\"  \n    by (rule conjE)\n  then have \"card {p1, p2, p3} \\<le> card plane\" \n    using assms by (simp add: card_mono)\n  ultimately show ?thesis  \n    by auto\nqed\n\ntext \\<open>\n  \\begin{lema}\n    Sean $a$ y $b$ dos puntos distintos, $l$ una l\u00ednea que pasa por \n    ellos y $p$ un punto fuera de $l$. Sea $n$ una l\u00ednea que\n    pasa por $a$ y $p$ y $m$ una l\u00ednea que pasa $b$ y $p$. Entonces, \n    $m \\neq n.$ \n\\end{lema}\n\n\\begin{demostracion}\n La demostraci\u00f3n se har\u00e1 por reducci\u00f3n al absurdo; es decir, supongamos\n que $m = n$ y se llegar\u00e1 a un absurdo. Primero notemos que $m \\neq l$\n ya que $p \\notin l$ pero $p \\in m,$ luego podemos aplicar el axioma A4\n a las l\u00edneas $m$ y $l.$ Al aplicarlo resulta que tenemos que $l \\cap m\n = \\emptyset$ o existe un punto $q$ tal que $l \\cap m = \\{q\\}.$ \n\n Primero supongamos que $l \\cap m = \\emptyset,$ sin embargo $b \\in l$ y\n $b \\in m$ luego hemos llegado a n absurdo.\n\n Segundo supongamos que sea $q$ el punto tal que $l \\cap m = {q},$ sin\n embargo al principio se ha supuesto que $m = n$. Por lo tanto, se tiene\n que $\\{a,b\\} \\subseteq \\{q\\}$ con lo que se ha llegado a un absurdo ya \n que $a \\neq b.$\n\n Por los dos casos se ha llegado a un absurdo luego, $m \\neq n.$\n \\end{demostracion}\n\n Para tener una visi\u00f3n geom\u00e9trica de la demostraci\u00f3n incluimos la figura\n \\ref{lineas_diferentes}.\n\n\\begin{figure}[H]\n\\centering\n\\includegraphics[height=6cm]{geogebra.png}\n\\caption{Visi\u00f3n geom\u00e9trica de la demostraci\u00f3n de l\u00edneas diferentes}\n\\label{lineas_diferentes}\n\\end{figure}\n\n La especificaci\u00f3n y demostraci\u00f3n del lema en Isabelle/HOL es la \n siguiente:\\<close>\n\nlemma (in Simple_Geometry) how_to_produce_different_lines:\n  assumes\n    \"l \\<in> lines\" \n    \"{a, b} \\<subseteq> l\" \"a \\<noteq> b\"\n    \"p \\<notin> l\"\n    \"n \\<in> lines\" \"{a, p} \\<subseteq> n\" \n    \"m \\<in> lines\" \"{b, p} \\<subseteq> m\"\n  shows \"m \\<noteq> n\"\nproof (rule notI)\n  assume \"m = n\"\n  show False\n  proof -\n    have \"m \\<noteq> l\" \n      using assms(4, 8) by auto\n    moreover have \"l \\<noteq> m  \\<longrightarrow>  l \\<inter> m = {} \\<or> (\\<exists>q \\<in> plane. l \\<inter> m = {q})\"\n      using assms(1, 7) A4 by auto\n    ultimately have \"l \\<inter> m = {} \\<or> (\\<exists>q \\<in> plane. l \\<inter> m = {q})\"   \n      by auto\n    then show False \n    proof (rule disjE)\n      assume \"l \\<inter> m = {}\"\n      then show False \n        using assms(2, 6) \\<open>m = n\\<close> by auto\n    next\n      assume \"\\<exists>q \\<in> plane. l \\<inter> m = {q}\" \n      then obtain \"q\" where \"q \\<in> plane \\<and> l \\<inter> m = {q}\" \n        by auto\n      then have \"l \\<inter> m = {q}\" \n        by (rule conjE)\n      then have \"{a, b} \\<subseteq> {q}\" \n        using assms(2, 6, 8) \\<open>m = n\\<close> by auto\n      then show False \n        using assms(3) by auto\n    qed\n  qed\nqed\n\ntext \\<open>\n\\begin{lema}\nSea $l$ una l\u00ednea tal que existen dos puntos $\\{a,b\\} \\subseteq l$ con\n $a \\neq b,$  un punto $p$ tal que $p \\notin l.$ Sea $n$ una l\u00ednea tal que\n$\\{a,p\\} \\subseteq n$ y $m$ otra l\u00ednea tal que $\\{b,p\\} \\subseteq m.$\nSupongamos adem\u00e1s que existen otros dos puntos $c,d$ tales que\n pertenecen a $n$ y $m$ respectivamente y $c \\neq p.$ Entonces $c \\neq\n d.$\n\\end{lema}\n\n\\begin{demostracion}\nLa demostraci\u00f3n se har\u00e1 por reducci\u00f3n al absurdo, es decir, supongamos\n que $c = d$ y llegaremos a una contradicci\u00f3n. Tenemos todas las\n hip\u00f3tesis del lema anterior, luego $m \\neq n,$ por lo que podemos\n aplicar el axioma A4 a las l\u00edneas $m$ y $n.$ Se tiene por lo tanto que\n $m \\cap n = \\emptyset$ o existe un punto $q$ tal que $m \\cap n = \\{q\\}.$\n\nPrimero supongamos que $m \\cap n = \\emptyset,$ sin embargo por hip\u00f3tesis\nse tiene que $p \\in m$ y $p \\in n$ luego hemos llegado a una\n contradicci\u00f3n.\n\nSegundo sea $q$ el punto tal que $m \\cap n = \\{q\\}.$ Como se ha supuesto\nque $c = d$ se tiene que ${c,p} \\subseteq \\{q\\},$ pero por hip\u00f3tesis se\n tiene que $c \\neq p$ luego se ha llegado a una contradicci\u00f3n.\n\nEn los dos caso se ha llegado a una contradicci\u00f3n, por lo que $c \\neq d.$\n\\end{demostracion}\n\nPara entender mejor la demostraci\u00f3n se puede ver geom\u00e9tricamente en la \nsiguiente figura \\ref{puntos_diferentes}\n\n\n\\begin{figure}[H]\n\\centering\n\\includegraphics[height=6cm]{geogebra2.png}\n\\caption{Visi\u00f3n geom\u00e9trica de la demostraci\u00f3n de puntos diferentes}\n\\label{puntos_diferentes}\n\\end{figure}\n\nLa especificaci\u00f3n y demostraci\u00f3n del lema en Isabelle/HOL es la siguiente:\n\\<close>\nlemma (in Simple_Geometry) how_to_produce_different_points:\n  assumes\n    \"l \\<in> lines\" \n    \"{a, b} \\<subseteq> l\" \"a \\<noteq> b\"\n    \"p \\<notin> l\"\n    \"n \\<in> lines\" \"{a, p, c} \\<subseteq> n\"  \n    \"m \\<in> lines\" \"{b, p, d} \\<subseteq> m\"\n    \"p \\<noteq> c\"\n  shows \"c \\<noteq> d\" \nproof \n  assume \"c = d\" \n  show False\n  proof -\n    have \"m \\<noteq> n\" \n      using assms how_to_produce_different_lines by simp\n    moreover have \"n \\<noteq> m  \\<longrightarrow>  m \\<inter> n = {} \\<or> (\\<exists>q \\<in> plane. m \\<inter> n = {q})\"\n      using assms(5,7) A4 by auto\n    ultimately have \"m \\<inter> n = {} \\<or> (\\<exists>q \\<in> plane. m \\<inter> n = {q})\" \n      by auto\n    then show False\n    proof (rule disjE)\n      assume \"m \\<inter> n = {}\"\n      then show False \n        using assms(6, 8) by auto\n    next\n      assume \"\\<exists>q \\<in> plane. m \\<inter> n = {q}\"\n      then obtain \"q\" where \"q \\<in> plane \\<and> m \\<inter> n = {q}\" \n        by auto\n      then have \"{p,d} \\<subseteq> {q}\" \n        using \\<open>c = d\\<close> assms by auto\n      then show False \n        using \\<open>c = d\\<close> assms(9) by auto\n    qed\n  qed\nqed\n\n\nsubsection \\<open>Interpretaci\u00f3n m\u00ednimo modelo geometr\u00eda simple\\<close>\n\ntext \\<open>\nEl m\u00ednimo modelo que tiene la geometr\u00eda simple es considerar el plano\n como el conjunto formado por tres n\u00fameros $\\{a,b,c\\}$, ya pueden ser\n enteros,naturales etc y con ellos formar \u00fanicamente 3 l\u00edneas. En este\n caso ser\u00edan las combinaciones que se pueden hacer de 2 elementos de\n un conjunto de 2, es decir, 3. \n\nPara ello se va a dar el la definicion del \\textbf{planes-3} que es el\n plano de 3 elementos y \\textbf{lines-3} que es el conjunto formado por\n 3 l\u00edneas.\n\\<close>\n\ndefinition \"plane_3 \\<equiv> {1::nat,2,3} \"\n\ndefinition \"lines_3 \\<equiv> {{1,2},{2,3},{1,3}}\"\n\ninterpretation Simple_Geometry_smallest_model:\n  Simple_Geometry plane_3 lines_3\n  apply standard \n      apply (simp add: plane_3_def lines_3_def)+\n  done\n\nsection \\<open>Geometr\u00eda no proyectiva \\<close>\n\nsubsection \\<open>Entorno local \\<close>\n\ntext \\<open>\nLa geometr\u00eda no proyectiva es un tipo de geometr\u00eda en el que asumimos\n paralelismo, en nuestro caso entre rectas.\n\n\\begin{definicion}\n El paralelismo es una relaci\u00f3n que se establece entre dos rectas\n cualesquiera del plano, esta relaci\u00f3n dice que dos rectas son paralelas\n si bien son la misma recta o no comparten ning\u00fan punto, es decir, su\n intersecci\u00f3n es vac\u00eda.\n \\end{definicion}\n\n Gracias a esta relaci\u00f3n entre rectas, podemos definir un nuevo entorno\n local a\\-\u00f1a\\-dien\\-do al ya definido \\textbf{Simple-Geometry} un nuevo\n axioma, el axioma de la existencia del pa\\-ra\\-le\\-lis\\-mo.\n\n\n\\textbf{Parallels-Ex}: sea $p$ un punto del plano y $l$ una l\u00ednea. Si $p\n\\notin l$ entonces debe existir una l\u00ednea $m$ tal que $p \\in m$ y $l\n \\cap m = \\emptyset.$\n\nAl nuevo entorno local lo denotaremos como\n \\textbf{Non-Projective-Geometry}.\n\\<close>\n\nlocale Non_Projective_Geometry =\n  Simple_Geometry +\n  assumes parallels_Ex:\n    \"\\<forall>p \\<in> plane. \\<forall>l \\<in> lines. p \\<notin> l \\<longrightarrow> (\\<exists>m \\<in> lines. p \\<in> m \\<and> m \\<inter> l = {} )\"\n\nsubsection \\<open>Proposiciones de geometr\u00eda no proyectiva \\<close>\n\ntext\\<open>\nA continuaci\u00f3n vamos a presentar un lema sobre geometr\u00eda no proyectiva:\n\n\\begin{lema}\nEs falso que todo par de l\u00edneas se cortan.\n\\end{lema}\n\n\\begin{demostracion}\nLa demostraci\u00f3n se har\u00e1 por reducci\u00f3n al absurso. Es decir, supongamos \nque todo par de l\u00edneas se cortan.\n\nSea ahora $l1$ una l\u00ednea obtenida por el el lema \\ref{one-line-exists}. \nPorr el axioma A5 obtenemos un punto $q1$ tal que $q1 \\notin l1$.\nUsando el axioma \\textbf{Parallels-Ex} aplicado\nal punto $q1$ y a la l\u00ednea $l1$ obtenemos que existe una l\u00ednea $m$ tal\nque $q1 \\in m$ y $m \\cap l = \\emptyset$. Por lo tanto, hemos llegado a\nuna contradicci\u00f3n ya que se ha demostrado que existen dos l\u00edneas cuya\nintersecci\u00f3n es vac\u00eda.\n\\end{demostracion}\n\nLa formalizaci\u00f3n y demostraci\u00f3n en Isabelle/Hol es la siguiente:\\<close>\n\nlemma (in Non_Projective_Geometry) non_projective:\n  \"\\<not>(\\<forall>r \\<in> lines. \\<forall>s \\<in> lines. r \\<inter> s \\<noteq> {})\"\nproof \n  assume 4: \"\\<forall>r\\<in>lines. \\<forall>s\\<in>lines. r \\<inter> s \\<noteq> {}\"\n  show False\n  proof -\n    obtain \"l1\" where 1: \"l1 \\<in> lines\" \n      using one_line_exists by auto\n    then obtain \"q1\" where 2: \"q1 \\<in> plane \\<and> q1 \\<notin> l1\" \n      using A5 by auto\n    then have \"q1 \\<notin> l1 \\<longrightarrow> (\\<exists>m \\<in> lines. q1 \\<in> m \\<and> m \\<inter> l1 = {} )\" \n      using 1 parallels_Ex by simp\n    then obtain \"m1\" where 3: \"m1 \\<in> lines \\<and> q1 \\<in> m1 \\<and> m1 \\<inter> l1 = {}\"\n      using 2 by auto\n    then obtain \"m1 \\<inter> l1 \\<noteq> {}\" using 1 4 by auto\n    then show ?thesis using 3 by auto\n  qed\nqed\n\nsubsection \\<open>Interpretacion modelo geometr\u00eda no proyectiva \\<close>\n\ntext \\<open>\n El m\u00ednimo modelo de la geometr\u00eda no proyectiva es considerar que el\n plano tiene 4 elementos; es decir, considerar el plano como\n $\\{a,b,c,d\\}$ siendo estos n\u00fameros enteros,naturales etc. Con estos 4\n elementos para que sea un modelo de la geometr\u00eda no proyectiva hay que\n formar como m\u00ednimo 6 rectas.\n\nPara ello vamos a dar la definicion \\textbf{plane-4} que es el plano\nformado por 4 elementos y \\textbf{lines-4} que son las l\u00edneas asociadas\na estos elementos.\\<close>\n\ndefinition \"plane_4 \\<equiv> {1::nat, 2, 3, 4}\"\n\ndefinition \"lines_4 \\<equiv> {{1,2},{2,3},{1,3},{1,4},{2,4},{3,4}}\"\n\ninterpretation Non_projective_geometry_card_4:\n  Non_Projective_Geometry plane_4 lines_4\n  apply standard\n       apply (simp add: plane_4_def lines_4_def)+\n  done\n\nsection \\<open>Geometr\u00eda proyectiva \\<close>\n\nsubsection \\<open>Entorno local \\<close>\n\ntext \\<open>\n La geometr\u00eda proyectiva es un tipo de geometr\u00eda que se basa en que dado\n cualquier par de rectas su intersecci\u00f3n siempre es un punto. \n\n Para ello vamos a definir un nuevo entorno local\n \\textbf{Projective-Geometry} tal que se basa en el entorno local ya\n definido \\textbf{Simple-Geometry} a\u00f1adi\u00e9ndole dos axiomas m\u00e1s. Estos\n axiomas son los siguientes:\n\n\\begin{enumerate}\n\\item Cualquier par de l\u00edneas se cortan.\n\\item Toda l\u00ednea tiene al menos 3 puntos.\n\\end{enumerate}\n\nEl nuevo entorno local es el siguiente:\\<close>\n\nlocale Projective_Geometry = \n  Simple_Geometry + \n  assumes A6: \"\\<forall>l \\<in> lines. \\<forall>m \\<in> lines. \\<exists>p \\<in> plane. p \\<in> l \\<and> p \\<in> m\"\n      and A7: \"\\<forall>l \\<in> lines. \\<exists>x. card x = 3 \\<and> x \\<subseteq> l\" \n\nsubsection \\<open>Proposiciones de geometr\u00eda proyectiva \\<close>\n\ntext \\<open>\nA continuaci\u00f3n vamos a demostrar una serie de lemas dentro del entorno\n\\textbf{Projective-Geometry}. Antes de los lemas vamos a demostrar en\nIsabelle que si un conjunto $x$ tiene cardinalidad 3, entonces \nest\u00e1 formado por 3 puntos distintos. Este peque\u00f1o lema nos ayudar\u00e1 en \nlas demostraciones de los siguientes.\\<close>\n\nlemma construct_set_of_card3:\n  \"card x = 3 \\<Longrightarrow> \\<exists> p1 p2 p3. distinct [p1,p2,p3] \\<and> x = {p1,p2,p3}\" \n  by (metis card_eq_SucD distinct.simps(2) \n      distinct_singleton list.set(1) list.set(2) numeral_3_eq_3)\n\ntext \\<open>\n Los dos primeros lemas que vamos a demostrar son versiones equivalentes al\n axioma A7 ya definido y en los dos se utilizar\u00e1 el dicho axioma.\n\n\\begin{lema}\\label{A7a}\nPara todo l\u00ednea $l$, existen $p1,p2,p3$ tales que \n$\\{p1,p2,p3\\} \\subseteq l$ y son distintos entre s\u00ed.\n\\end{lema}\n\n\n\\begin{demostracion}\nSea $l$ una l\u00ednea cualquiera. Por el axioma A7 obtenemos que existe $x$\ntal que cardinalidad $x = 3$ y que $x \\subseteq l.$ Por el lema definido\nanteriormente, se obtiene que existen $p1,p2,p3$ distintos entre s\u00ed y \ntales que $x =\\{p1,p2,p3\\}$ y que $p1 \\neq p2 \\neq p3$.\n\\end{demostracion}\n\nLa formalizaci\u00f3n y demostraci\u00f3n en Isabelle/HOL es la siguiente:\\<close>\nlemma (in Projective_Geometry) A7a:\n  \"\\<forall>l \\<in> lines. \\<exists>p1 p2 p3. {p1, p2, p3} \\<subseteq> plane \\<and> \n                          distinct [p1, p2, p3] \\<and> \n                          {p1, p2, p3} \\<subseteq> l\" \nproof\n  fix l\n  assume 1: \"l \\<in> lines\"\n  show \"\\<exists>p1 p2 p3. {p1, p2, p3} \\<subseteq> plane \\<and> \n                   distinct [p1, p2, p3] \\<and> \n                   {p1, p2, p3} \\<subseteq> l\"\n  proof -\n    obtain x where 2: \"card x = 3 \\<and> x \\<subseteq> l\"  \n      using 1 A7 by auto\n    then have 3: \"card x = 3\" \n      by (rule conjE)\n    have \"\\<exists> p1 p2 p3. distinct [p1, p2, p3] \\<and> x = {p1, p2, p3}\" \n      using 3 by (rule construct_set_of_card3)\n    then obtain \"p1\" \"p2\" \"p3\" \n      where 4 :\"distinct [p1,p2,p3] \\<and> x = {p1, p2, p3}\" \n      by auto\n    obtain \"l \\<subseteq> plane \\<and> l \\<noteq> {}\" \n      using 1 A2  by auto\n    then have \n      \"{p1, p2, p3} \\<subseteq> plane \\<and> distinct [p1, p2, p3] \\<and> {p1, p2, p3} \\<subseteq> l\"\n      using 4 2 by auto\n    then show ?thesis \n      by auto\n  qed\nqed\n\ntext \\<open> \n\\begin{lema}\\label{A7b}\nSea $l$ una linea y $p,q$ dos puntos de $l$. Entonces existe un punto\n$r$ tal que $r \\neq p, \\, r \\neq q$ y $r \\in l.$\n\\end{lema}\n\n\\begin{demostracion}\nSea $l$ una linea y $p,q$ dos puntos tales que $\\{p,q\\} \\subseteq l.$\n Por el axioma $A7$ se tiene que existe $x$ tal que la cardinalidad $x\n = 3$ y $x \\subseteq l$. Por el lema demostrado anteriormente, se tiene\n que existen $p1,p2,p3$ distintos entre s\u00ed y tales que\n $\\{p1,p2,p3\\} \\subseteq l$. Luego, usando las hip\u00f3tesis se tiene 3\n posibilidades:\n\\begin{enumerate}\n\\item Si $p1 \\notin{p,q}$ entonces ya tendr\u00edamos probado el lema.\n\\item Si $p2 \\notin{p,q}$ entonces ya tendr\u00edamos probado el lema.\n\\item Si $p3 \\notin{p,q}$ entonces ya tendr\u00edamos probado el lema.\n\\end{enumerate}\n\nEn cualquiera de los 3 casos ya se tendr\u00eda probado el lema.\n\\end{demostracion}\nLa formalizaci\u00f3n y demostraci\u00f3n en Isabelle/HOL es la siguiente:\\<close>\n\nlemma (in Projective_Geometry) A7b: \n  assumes \"l \\<in> lines\"\n    \"{p, q} \\<subseteq> l \" \n  shows   \"\\<exists>r \\<in> plane. r \\<notin> {p, q} \\<and> r \\<in> l\" \nproof -\n  obtain \"x\" where 1: \"card x = 3 \\<and> x \\<subseteq> l\" \n    using assms A7 by auto\n  then have \"card x = 3\" \n    by (rule conjE)\n  then have \"\\<exists> p1 p2 p3. distinct [p1,p2,p3] \\<and> x = {p1,p2,p3}\" \n    by (rule construct_set_of_card3)\n  then obtain \"p1\" \"p2\" \"p3\" \n    where 2: \"distinct [p1,p2,p3] \\<and> x = {p1,p2,p3}\" \n    by auto\n  have \"l \\<subseteq> plane \\<and> l \\<noteq> {}\" \n    using A2 assms by auto\n  then have 3: \"x \\<subseteq> plane\" \n    using 1 by auto\n  then have \"p1 \\<notin> {p,q} \\<or> p2 \\<notin> {p,q} \\<or> p3 \\<notin> {p,q}\" \n    using 2 by auto\n  then show ?thesis \n    using 1 2 3 by auto\nqed\n\ntext \\<open>\n\\begin{lema}\nPara todo punto del plano existen dos l\u00edneas distintas que pasan por \u00e9l.\n\\end{lema}\n\n\\begin{demostracion}\nSea $p$ un punto del plano cualquiera. Por el axioma $A3$ obtenemos que\nexiste una l\u00ednea $l$ tal que $\\{p,p\\} \\subseteq l$. Luego, por el axioma\n$A5$, se obtiene un punto $r$ tal que $r \\notin l$. Por lo tanto, por el\n axioma $A3$ de nuevo, se obtiene otra recta $m$ tal que $\\{p,r\\}\n \\subseteq m$. Ya se tiene probada la existencia de las dos rectas que\n pasan por el punto $p$, para probar que son diferentes simplemente\n se usa que $r \\in m$ y $r \\notin l$.  \n\\end{demostracion}\n\nLa formalizaci\u00f3n y demostraci\u00f3n en Isabelle/HOL  es la siguiente:\\<close>\n\nlemma (in Projective_Geometry) two_lines_per_point:\n  \"\\<forall>p \\<in> plane. \\<exists>l \\<in> lines. \\<exists>m \\<in> lines. l \\<noteq> m \\<and> p \\<in> l \\<inter> m\" \nproof \n  fix p \n  assume 1: \"p \\<in> plane\"\n  show \"\\<exists>l \\<in> lines. \\<exists>m \\<in> lines. l \\<noteq> m \\<and> p \\<in> l \\<inter> m\" \n  proof -\n    obtain l where 2: \"l \\<in> lines \\<and> {p,p} \\<subseteq> l\" \n      using A3 1 by auto\n    then obtain r where 3: \"r \\<notin> l \\<and> r \\<in> plane\" \n      using A5 by auto\n    then obtain m where 4: \"m \\<in> lines \\<and> {p,r} \\<subseteq> m \" \n      using A3 1  by auto\n    then have \"l \\<noteq> m \\<and> p \\<in> l \\<inter> m\" \n      using  2 3 by auto\n    then show ?thesis \n      using 2 4 by auto\n  qed\nqed\n\ntext \\<open>\nPara el pr\u00f3ximo lema se va a usar el siguiente lema auxiliar.\n\n\\begin{lema}\\label{lema1}[Lema auxiliar 1]\nSea $l$ una l\u00ednea y $r,s$ dos puntos tales que $\\{r,s\\} \\subseteq l.$\n Sea tambi\u00e9n $l2$ otra l\u00ednea y $p$ otro punto tal que $\\{p,r\\} \\subseteq\nl2$. Entonces, si $p \\neq r$ y $s \\notin l2$ se tiene que $p \\notin l$. \n\\end{lema}\n\n\\begin{demostracion}\nLa demostraci\u00f3n se har\u00e1 por reducci\u00f3n al absurdo; es decir, supongamos\n $p \\in l$ y se llegar\u00e1 a una contradicci\u00f3n. \n\nSupongamos que $p \\in l.$ Primero obtenemos que como $s \\in l$ y $s\n \\notin l2$ entonces $l \\neq l2$. Usando esto \u00faltimo, obtenemos del\n axioma $A4$ que $l \\cap l2 = \\emptyset$ o $\\exists q$ punto tal que $l\n \\cap l2 = \\{q\\}$\n\\begin{enumerate}\n\\item Supongamos que $l \\cap l2 = \\emptyset$, pero por hip\u00f3tesis se\n tiene que $r \\in l$ y $r \\in l2$. Luego se llega a una contradicci\u00f3n.\n\\item Supongamos que existe $q$ tal que $l \\cap l2 = \\{q,\\}$. Sin\n embargo, como hemos supuesto que $p \\in l$ y, adem\u00e1s, $r \\in l$, \n$r \\in l2$, $p \\in l2$ y $r \\neq p$ se llega a una contradicci\u00f3n.\n\\end{enumerate}\nEn los dos casos hemos llegado a una contradicci\u00f3n luego se tiene que \n$p \\notin l.$\n\\end{demostracion}\n\nLa formalizaci\u00f3n y demostraci\u00f3n en Isabelle/HOL del lema auxiliar es la \nsiguiente:\\<close>\n\nlemma (in Projective_Geometry) punto_no_pertenece:\n  assumes \"l2 \\<in> lines \\<and> {p,r} \\<subseteq> l2\"\n          \"l \\<in> lines \\<and>  {r,s} \\<subseteq> l\"\n          \"p \\<noteq> r\"\n          \"s \\<notin> l2\"\n        shows \"p \\<notin> l\"\nproof \n  assume 1:\"p \\<in> l\"\n  have \"l \\<inter> l2 = {} \\<or> (\\<exists>q \\<in> plane. l \\<inter> l2 = {q})\" \n    using A4 assms(1,2,4) by auto\n  then show False \n  proof \n    assume \"l \\<inter> l2 = {}\"\n    then show False \n      using assms(1,2) by auto\n  next \n    assume \" \\<exists>q\\<in>plane. l \\<inter> l2 = {q}\"\n    then obtain \"t\" where \"l \\<inter> l2 = {t}\" \n      by auto\n    then have \"{p,r} \\<subseteq> {t}\" \n      using assms(1,2) 1  by auto\n    then show False \n      using assms(3) by auto\n  qed\nqed\n\ntext \\<open>El lema a demostrar es el siguiente:\n\n\\begin{lema}\\label{external_line}\nPara todo punto $p$ existe una l\u00ednea $l$ tal que $p \\notin l.$\n\\end{lema}\n\n\\begin{demostracion}\nSea $p$ un punto cualquiera, por el axioma $A3$ obtenemos una l\u00ednea $l1$\n tal que $\\{p,p\\} \\subseteq l1$. Usando el axioma $A5$ se obtiene un\n punto $r$ tal que $r \\notin l1$. De nuevo usando el axioma $A3$\n obtenemos una l\u00ednea $l2$ tal que $\\{p,r\\} \\subseteq l2$. Repitiendo el\n mismo razonamiento, usamos el axioma $A5$ para obtener un punto $s$ tal\nque $s \\notin l2$ y por el axioma $A3$ una l\u00ednea $l$ tal que $\\{r,s\\}\n \\subseteq l$. Por \u00faltimo, usando que $r \\notin l1$ se tiene que $p \\neq\n r$ y, por lo tanto, se tienen todas las hip\u00f3tesis del lema auxiliar\n \\ref{lema1}, luego se ha demostrado que existe una l\u00ednea $l$\n tal que $p \\notin l.$\n\\end{demostracion}\n\nLa formalizacion y demostraci\u00f3n en Isabelle/HOL es la siguiente:\\<close>\n\nlemma (in Projective_Geometry) external_line:\n  \"\\<forall>p \\<in> plane. \\<exists>l \\<in> lines. p \\<notin> l\" \nproof \n  fix p \n  assume 1: \"p \\<in> plane\" \n  show \"\\<exists>l \\<in> lines. p \\<notin> l\"\n  proof - \n    obtain l1 where 2: \"l1 \\<in> lines \\<and> {p,p} \\<subseteq> l1\" \n      using 1 A3 by auto\n    then obtain r where 3: \"r \\<in> plane \\<and> r \\<notin> l1\" \n      using A5 by auto\n    obtain l2 where 4: \"l2 \\<in> lines \\<and> {p,r} \\<subseteq> l2\" \n      using 1 3 A3 by auto\n    then obtain s where 5: \"s \\<in> plane \\<and> s \\<notin> l2\" \n      using A5 3 by auto\n    obtain l where 6: \"l \\<in> lines \\<and> {r,s} \\<subseteq> l\" \n      using 3 5 A3 by auto\n    have \"p \\<noteq> r\" using 2 3 by auto\n    then have \"p \\<notin> l\" \n      using 4 6 5 punto_no_pertenece [of l2 p r l s] by simp\n    then show ?thesis \n      using 6 by auto\n  qed\nqed\n\ntext \\<open>\nPara el pr\u00f3ximo lema, se va a usar el siguiente lema auxiliar:\n\n\\begin{lema}\\label{lineas_diferentes}\nSean $l,l1,l2$ l\u00edneas tales que existen puntos $p,q,r$ tal que $\\{p,r\\}\n \\subseteq l, \\, \\{p,q\\} \\subseteq l1 \\, \\{r,q\\} \\subseteq l2$ y,\n adem\u00e1s, $l \\neq l1$ y $p \\neq r.$ Entonces se tiene que $l1 \\neq l2.$ \n\\end{lema}\n\n\\begin{demostracion}\nLa demostraci\u00f3n se har\u00e1 por reducci\u00f3n al absurdo, es decir, supongamos\n que $l1 = l2$ y se llegar\u00e1 a una contradicci\u00f3n. \n\nSupongamos que $l1 = l2.$ Como por hip\u00f3tesis se tiene que $l \\neq l1$\n entonces usando el axioma $A4$ obtenemos que $l \\cap l1 = \\emptyset$ o\n existe un punto tal que $l \\cap l1 = \\emptyset$. Veamos los dos casos.\n\n\\begin{enumerate}\n\\item Supongamos que $l \\cap l1 = \\emptyset$. Como por hip\u00f3tesis se\n tiene que $p \\in l$ y $p \\in l1$ entonces se llega a un absurdo.\n\\item Supongamos que existe un punto $t$ tal que $l \\cap l1 = \\{t\\}$. \nComo se hab\u00eda supuesto que $l1 = l2$ se tiene que, usando las hip\u00f3tesis,\n $\\{p,r\\} \\subseteq \\{t,\\}$. Sin embargo, como $p \\neq r$ entonces se\n llega a un absurdo.\n\\end{enumerate}\n\nEn ambos casos hemos llegado a un absurdo, luego $l1 \\neq l2.$\n\\end{demostracion}\n\nSu demostraci\u00f3n y formalizaci\u00f3n en Isabelle/HOL es la siguiente:\\<close>\n\nlemma (in Projective_Geometry) lineas_diferentes:\n  assumes \"l \\<in> lines \\<and> {p,r} \\<subseteq> l\"\n          \"l1 \\<in> lines \\<and> {p,q} \\<subseteq> l1\"\n          \"l2 \\<in> lines \\<and> {r,q} \\<subseteq> l2\"\n          \"l1 \\<noteq> l \"\n          \"p \\<noteq> r\"\n  shows   \"l1 \\<noteq> l2\"\nproof \n  assume 1:\"l1 = l2\"\n  have \"l \\<inter> l1 = {} \\<or> (\\<exists>q \\<in> plane. l \\<inter> l1 = {q})\"\n    using A4 assms(1,2,4) by auto\n  then show False \n  proof \n    assume \"l \\<inter> l1 = {}\"\n    then show False \n      using assms(1,2) by auto\n  next\n    assume \"\\<exists>q\\<in>plane. l \\<inter> l1 = {q}\"\n    then obtain t where \"l \\<inter> l1 = {t}\" \n      by auto\n    then have \"{p,r} \\<subseteq> {t}\" \n      using assms(1,2,3) 1 by auto\n    then show False \n      using assms(5) by auto\n  qed\nqed\n\ntext \\<open>\n\\begin{lema}\\label{3lineas_diferentes}\nPara todo punto $p$ en el plano, existen al menos tres l\u00edneas que pasan \npor $p$.\n\\end{lema}\n\n\\begin{demostracion}\nSea $p$ un punto del plano, usando el lema \\ref{external_line} se\n obitene que una l\u00ednea $h$ tal que $p \\notin h$. Usando la\n definici\u00f3n equivalente del axioma $A7$ (lema \\ref{A7a}) se obtienen\n tres puntos $a,b,c$ distintos entre s\u00ed y tales que \n $\\{a,b,c\\} \\subseteq h$. Por lo tanto, usando el axioma $A3$ obtenemos \n de forma equivalente tres l\u00edneas $l,m,n$ tales que \n $\\{a,p\\} \\subseteq l, \\, \\{b,p\\} \\subseteq m,\\, \\{c,p\\} \\subseteq n$. \n Ya hemos probado que existen $3$ l\u00edneas que\n verifican las condiciones, lo \u00fanico que queda por probar es que sean\n diferente. Usando el lema auxiliar \\ref{lineas_diferentes} se\n concluye la prueba.\n\\end{demostracion}\n\nLa siguiente figura \\ref{3lineas_diferentes} muestra una visi\u00f3n\n geom\u00e9trica de la demostraci\u00f3n anterior.\n\\begin{figure}[H]\n\\centering\n\\includegraphics[height=6cm]{geogebra3.png}\n\\caption{Visi\u00f3n geom\u00e9trica de la demostraci\u00f3n del lema\n \\ref{3lineas_diferentes}}\n\\label{3lineas_diferentes}\n\\end{figure}\n\nLa formalizaci\u00f3n y demostraci\u00f3n en Isabelle/HOL es la siguiente:\\<close>\n\nlemma (in Projective_Geometry) three_lines_per_point:\n  \"\\<forall>p \\<in> plane. \\<exists>l m n. \n    distinct [l,m,n] \\<and> {l,m,n} \\<subseteq> lines \\<and> p \\<in> l \\<inter> m \\<inter> n\" \nproof \n  fix p \n  assume 1: \"p \\<in> plane\"\n  show \"\\<exists>l m n. distinct [l,m,n] \\<and> {l,m,n} \\<subseteq> lines \\<and> p \\<in> l \\<inter> m \\<inter> n\"\n  proof - \n    obtain h where 2: \"h \\<in> lines \\<and> p \\<notin> h\" \n      using 1 external_line by auto\n    then obtain a b c \n      where 3: \"{a,b,c} \\<subseteq> plane \\<and> distinct [a,b,c] \\<and> {a,b,c} \\<subseteq> h\"\n      using A7a by auto  \n    then obtain l where 4: \"l \\<in> lines \\<and> {a,p} \\<subseteq> l\" \n      using 1 A3 by auto\n    obtain m  where 5: \"m \\<in> lines \\<and> {b,p} \\<subseteq> m\" \n      using 1 3 A3 by auto\n    obtain n where 6: \"n \\<in> lines \\<and> {c,p} \\<subseteq> n\" \n      using 1 3 A3 by auto\n    have 7:\"h \\<noteq> l\" \n      using 4 2 by auto\n    have \"a \\<noteq> b\" \n      using 3 by auto\n    then have 9: \"m \\<noteq> l\" \n      using 3 4 5 2 7 lineas_diferentes [of h a b l p m ] by simp\n    have 8: \"h \\<noteq> m\" \n      using 5 2 by auto\n    have  \"b \\<noteq> c\" \n      using 3 by auto\n    then have 10: \"m \\<noteq> n\" \n      using 6 5 3 2 8 lineas_diferentes [of h b c m p n ] by simp\n    have \"a \\<noteq> c\" \n      using 3 by auto\n    then  have 11: \"l \\<noteq> n\" \n      using 2 3 4 6 7 lineas_diferentes [of h a c l p n ] by simp \n    show ?thesis \n      using  4 5 6 9 10 11 by auto\n  qed\nqed\n\ntext \\<open>\nPara el siguiente lema se va a usar el siguiente lema auxiliar:\n\n\\begin{lema}\\label{puntos_diferentes}\nSea $l$ y $l1$ l\u00edneas tales que $l \\neq l1$ y existen puntos $p,q,c$ \ntales que $\\{p,c\\} \\subseteq l$ y $\\{q,c\\} \\subseteq l1$ con \n$c \\neq p$. Entonces $p \\neq q$ \n\\end{lema}\n\n\\begin{demostracion}\nLa demostraci\u00f3n se har\u00e1 por reducci\u00f3n al absurdo, es decir, supongamos\n que $p = q$ y se llegar\u00e1 a un absurdo. \n\nSupongamos que $p = q.$ Entonces usando la hip\u00f3tesis $l \\neq l1$ y el\n axioma $A4$ se obtiene que $l \\cap l1 = \\emptyset$ o existe un punto\n tal que $l \\cap l1 = \\{q\\}.$ Veamos los dos casos por separado.\n\n\\begin{enumerate}\n\\item Supongamos que $l \\cap l1 = \\emptyset.$ Como por hip\u00f3tesis se\n tiene que $c \\in l$ y $c \\in l1$ entonces se llega a un contradicci\u00f3n.\n\\item Supongamos que existe $t$ tal que $l \\cap l1 = \\{t\\}$. Sin\n embargo, como hemos supuesto que $p = q$, se tiene que $\\{p,c\\}\n \\subseteq \\{t\\}$. Pero como $p \\neq c$ se llega a una contradicci\u00f3n.\n\\end{enumerate}\n\nEn los dos casos se ha llegado a una contradicci\u00f3n luego se tiene que \n$p \\neq q.$\n\\end{demostracion}\n\nLa formalizaci\u00f3n y demostraci\u00f3n en Isabelle/HOL es la siguiente:\\<close>\nlemma (in Projective_Geometry) puntos_diferentes:\n  assumes \"l \\<in> lines\"\n          \"l1 \\<in> lines\"\n          \"{p,c} \\<subseteq> l\"\n          \"{q,c} \\<subseteq> l1\"\n          \"l \\<noteq> l1\"\n          \"c \\<noteq> p\"\n        shows \"p \\<noteq> q\" \nproof \n  assume 1: \"p = q\" \n  have \"l \\<inter> l1 = {} \\<or> (\\<exists>q \\<in> plane. l \\<inter> l1 = {q})\" \n    using assms(1,2,5) A4 by auto\n  then show False\n  proof \n    assume \"l \\<inter> l1 = {}\"\n    then show False \n      using assms(3,4) by auto\n  next\n    assume \"\\<exists>q\\<in>plane. l \\<inter> l1 = {q}\"\n    then obtain t where \"l \\<inter> l1 = {t}\" \n      by auto\n    then have \"{p,c} \\<subseteq> {t}\" \n      using assms(3,4) 1 by auto\n    then show False \n      using assms(6) by auto\n  qed\nqed\n\ntext \\<open>\n\\begin{lema}\\label{7_puntos}\nExisten al menos 7 puntos diferenetes en el plano.\n\\end{lema}\n\n\\begin{demostracion}\nPrimero sea $l$ una l\u00ednea que se obtiene usando el lema\n \\ref{one-line-exists}, usando el lema equivalente al axioma $A7$ (lema\n \\ref{A7a} ) se obtienen $3$ puntos $p1,p2,p3$ distintos entre s\u00ed tales \n que $\\{p1,p2,p3\\} \\subseteq l$. Ahora usando el axioma $A5$ se\n obtiene que existe $q$ tal que $q \\notin l$, luego ya se tienen\n probado que existen $4$ puntos diferentes, ya que $q$ es diferente del\n resto porque $q \\notin l$.  Consideremos ahora tres l\u00edneas $l1,l2,l3$ \n obtenidas por el axioma $A3$ tales que $\\{p1,q\\} \\subseteq l1, \\,\n \\{p2,q\\} \\subseteq l2, \\, \\{p3,q\\} \\subseteq l3.$ Ahora vamos a obtener\nlos tres puntos restantes, usando que $l \\neq l1 \\neq l2 \\neq l3$ \ngracias al lema auxiliar \\ref{lineas_diferentes}:\n\n\\begin{enumerate}\n\\item Obtenemos $p4$ tal que $p4 \\in l1$ y $p4 \\notin \\{p1,q\\}$\n usando el lema equivalente al axioma $A7$ (lema \\ref{A7b}). Entonces\n veamos que $p4$ es diferente al resto de los puntos. Se tiene que $p4\n \\notin \\{p1,q\\},$ luego veamos que $p4 \\neq p2$ y $p4 \\neq p3.$ Usando\n el lema auxiliar \\ref{puntos_diferentes} se tiene probado. Luego hemos\n probado que $p4$ es diferente al resto de los puntos.\n\n\\item Obtenemos $p5$ tal que $p5 \\in l2$ y $p5 \\notin \\{p2,q\\}$\n usando el lema equivalente al axioma $A7$ (lema \\ref{A7b}). Entonces\n veamos que $p5$ es diferente al resto de los puntos, ya se tiene que\n $p5 \\notin \\{p2,q\\}$ luego falta por probar que $p5 \\notin\n \\{p1,p3,p4\\}.$ Sin embargo es inmediato comprobar que se verifica\n usando el lema auxiliar \\ref{puntos_diferente}, luego ya hemos probado\n que $p5$ es diferente al resto de los puntos.\n\n\\item Obtenemos $p6$ tal que $p6 \\in l3$ y $p6 \\notin \\{p3,q\\}$\n usando el lema equivalente al axioma $A7$ (lema \\ref{A7b}). Entonces\n veamos que $p6$ es diferente al resto de los puntos, ya se tiene que\n $p6 \\notin \\{p3,q\\}$ luego falta por probar que $p6 \\notin\n \\{p1,p2,p4,p5\\}.$ Sin embargo es inmediato comprobar que se verifica\n usando el lema auxiliar \\ref{puntos_diferente}, luego ya hemos probado\n que $p6$ es diferente al resto de los puntos.\n\\end{enumerate}\n\nPor lo tanto, ya tenemos probado la existencia y  la disparidad de $7$\n puntos: $\\{p1,p2,p3,p4,p5,p6,p7\\}.$\n\\end{demostracion}\n\nLa siguiente figura \\ref{7_puntosdiferentes} muestra una intuici\u00f3n geom\u00e9trica de \nla demostraci\u00f3n del lema \\ref{7_puntos}.\n\n\\begin{figure}[H]\n\\centering\n\\includegraphics[height=6cm]{geogebra4.png}\n\\caption{Visi\u00f3n geom\u00e9trica de la demostraci\u00f3n del lema \\ref{7_puntos}}\n\\label{7_puntosdiferentes}\n\\end{figure}\n\n\nLa formalizaci\u00f3n y demostraci\u00f3n del lema en Isabelle/HOL es la\n siguiente:\\<close>\n\nlemma (in Projective_Geometry) at_least_seven_points: \n  \"\\<exists>p1 p2 p3 p4 p5 p6 p7. \n    distinct [p1,p2,p3,p4,p5,p6,p7] \\<and> {p1,p2,p3,p4,p5,p6,p7} \\<subseteq> plane\" \nproof -\n  obtain l where 1: \"l \\<in> lines\" \n    using one_line_exists by auto\n  then obtain x where 2: \"card x = 3 \\<and> x \\<subseteq> l\" \n    using A7 by auto\n  then have \"card x = 3\" \n    by (rule conjE)\n  then obtain p1 p2 p3 \n    where 3: \"distinct [p1,p2,p3] \\<and> x = {p1,p2,p3}\" \n    using construct_set_of_card3 [of x] by auto\n  then have 4: \"{p1,p2,p3} \\<subseteq> l\" \n    using 2 by auto\n  then have 5: \"{p1,p2,p3} \\<subseteq> plane\" \n    using A2 1 by auto\n  obtain q where 6: \"q \\<in> plane \\<and> q \\<notin> l\"\n    using A5 1 by auto\n  then have 7: \"distinct [p1,p2,p3,q]\" \n    using 3 4 by auto\n  obtain l1 where 8: \"l1 \\<in> lines \\<and> {p1,q} \\<subseteq> l1\" \n    using 5 6 A3 by auto\n  then have 9: \"l1 \\<noteq> l\" \n    using 6 by auto\n  obtain p4 where 10: \"p4 \\<notin> {p1,q} \\<and> p4 \\<in> l1\" \n    using A7b [of l1 p1 q] 8 by auto\n  have 11: \"p4 \\<noteq> p2\" \n    using 3 4 1 6 2 10 8 puntos_diferentes [of l1 l p4 p1 p2] by auto\n  have 12: \"p4 \\<noteq> p3\" \n    using 7 1 9 4 10 8 puntos_diferentes [of l1 l p4 p1 p3] by auto\n  obtain l2 where 13: \"l2 \\<in> lines \\<and> {p2,q} \\<subseteq> l2\" \n    using 5 6 A3 by auto\n  then obtain p5 where 14: \"p5 \\<notin> {p2,q} \\<and> p5 \\<in> l2\" \n    using A7b [of l2 p2 q] 7 by auto\n  have 15: \"l2 \\<noteq> l\" \n    using 6 13 by auto\n  have 16: \"p5 \\<noteq> p1\" \n    using 1 13 14 4  15 puntos_diferentes [of l l2 p1 p2  p5] \n    by auto \n  have 17: \"p5 \\<noteq> p3\" \n    using 1 13 14 4  15 puntos_diferentes [of l l2 p3 p2 p5] \n    by auto\n  have 20: \"l1 \\<noteq> l2 \" \n    using 1 9 13 4 8 7 lineas_diferentes [of l p1 p2 l1 q l2 ] \n    by simp\n  have 21: \"p4 \\<noteq> p5\" \n    using 13 8 14 4 10 20 puntos_diferentes [of l1 l2 p4 q p5]  \n    by auto\n  obtain l3 where 22: \"l3 \\<in> lines \\<and> {p3,q} \\<subseteq> l3\" \n    using A3 5 6 by auto\n  then obtain p6 where 23: \"p6 \\<notin> {p3,q} \\<and> p6 \\<in> l3\" \n    using A7b by metis\n  have 25: \"p6 \\<noteq> p1\" \n    using 1 22 6 4  23 puntos_diferentes [of l3 l p1 p3 p6]  \n    by auto \n  have 26: \"p6 \\<noteq> p2\" \n    using 1 22 6 23 4 puntos_diferentes [of l3 l p2 p3 p6] \n    by auto\n  have 29: \"l1 \\<noteq> l3\" \n    using 1 4 9 22 8 7 lineas_diferentes [of l p1 p3 l1 q l3]  \n    by simp\n  have 31: \"p6 \\<noteq> p4\" \n    using 22 8 10 23  29 puntos_diferentes [of l1 l3 p4 q p6] \n    by auto\n  have 34: \"l2 \\<noteq> l3\" \n    using 1 4 13 22 15 7 lineas_diferentes [of l p2 p3 l2 q l3] \n    by simp\n  have 35: \"p6 \\<noteq> p5\" \n    using 22 13 23 14 34 puntos_diferentes [of l2 l3 p5 q p6] \n    by auto\n  moreover have \"distinct [p1,p2,p3,p4,p5,p6,q]\" \n    using 7 10 11 12 14 16 17 21 23 25 26 31 7 35 by auto\n  moreover have \"{p1,p2,p3,p4,p5,p6,q} \\<subseteq> plane\" \n    using 6 5  A2 10 8 14 13 22 23 by auto\n  ultimately show ?thesis  \n    by blast\nqed\n\nsubsection \\<open>Interpretaci\u00f3n modelo geometr\u00eda proyectiva \\<close>\n\ntext \\<open>\nEl m\u00ednimo modelo que presenta la Geometria Proyectiva es considerar que\n el plano tiene $7$ puntos y con ellos formar como m\u00ednimo $7$ l\u00edneas.\n Este modelo se conoce como el \\textbf{plano de Fano} que es el plano \nproyectivo con el menor n\u00famero de puntos y l\u00edneas necesarios para que \nse verifiquen todos los axiomas. Para ello vamos a\n dar la definici\u00f3n en Isabelle del plano de 7 elementos\n \\textbf{plane-7} y la definici\u00f3n \\textbf{lines-7} asociado a sus 7\n l\u00edneas.\n\nLa siguiente figura \\ref{proyectivo} muestra una visi\u00f3n del \n\\textbf{plano de Fano}:\n\n\n\\begin{figure}[H]\n\\centering\n\\includegraphics[height=6cm]{proyectivo.png}\n\\caption{Visi\u00f3n geom\u00e9trica del plano de Fano}\n\\label{proyectivo}\n\\end{figure}\n\n\\<close>\ndefinition \"plane_7 \\<equiv> {1::nat,2,3,4,5,6,7}\"\n\ndefinition \"lines_7 \\<equiv> {{1,2,3},{1,6,5},{3,4,5},{5,7,2},{3,7,6},\n                        {1,4,7},{2,4,6}}\"\n\ntext \\<open>\nPara poder demostrar la existencia de este modelo m\u00ednimo con el comando\n \\textbf{interpretation} es necesario definir los siguientes lemas\n auxiliares:\n\\<close>\nlemma aux1a: \"card {Suc 0, 2, 3} = 3\"\n  by auto\n\nlemma aux1: \"\\<exists>x. card x = 3 \\<and> x \\<subseteq> {Suc 0, 2, 3}\"\n  using aux1a by blast\n\nlemma aux2a: \"card {Suc 0, 6, 5} = 3\"\n  by auto\n\nlemma aux2: \"\\<exists>x. card x = 3 \\<and> x \\<subseteq> {Suc 0, 6, 5}\"\n  using aux2a by blast\n\nlemma aux3a: \"card {3::nat, 4, 5} = 3\"\n  by auto\n\nlemma aux3: \"\\<exists>x. card x = 3 \\<and> x \\<subseteq> {3::nat, 4, 5}\"\n  using aux3a by blast\n\nlemma aux4a: \"card {5::nat, 7, 2} = 3\"\n  by auto\n\nlemma aux4: \"\\<exists>x. card x = 3 \\<and> x \\<subseteq> {5::nat, 7, 2}\"\n  using aux4a by blast\n\nlemma aux5a: \"card {3::nat, 7, 6} = 3\"\n  by auto\n\nlemma aux5: \"\\<exists>x. card x = 3 \\<and> x \\<subseteq> {3::nat, 7, 6}\"\n  using aux5a by blast\n\nlemma aux6a: \"card {Suc 0, 4, 7} = 3\"\n  by auto\n\nlemma aux6: \"\\<exists>x. card x = 3 \\<and> x \\<subseteq> {Suc 0, 4, 7}\"\n  using aux6a by blast\n\nlemma aux7a: \"card {2::nat, 4, 6} = 3\"\n  by auto\n\nlemma aux7: \"\\<exists>x. card x = 3 \\<and> x \\<subseteq> {2::nat, 4, 6}\"\n  using aux7a by blast\n\n\ninterpretation Projective_Geometry_smallest_model:\n  Projective_Geometry plane_7 lines_7\n  apply standard \n        apply (simp add: plane_7_def lines_7_def)+\n  apply (intro conjI)\n  apply (rule aux1)\n  apply (rule aux2)\n  apply (rule aux3)\n  apply (rule aux4)\n  apply (rule aux5)\n  apply (rule aux6)\n  apply (rule aux7)\n  done\n\nend\n", "meta": {"author": "Carnunfer", "repo": "TFG", "sha": "d9f0989088f76442db615c1820f19fb3fad72541", "save_path": "github-repos/isabelle/Carnunfer-TFG", "path": "github-repos/isabelle/Carnunfer-TFG/TFG-d9f0989088f76442db615c1820f19fb3fad72541/Geometria.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951104066295, "lm_q2_score": 0.8670357632379241, "lm_q1q2_score": 0.7316872411441642}}
{"text": "header {* Arctan Upper and Lower Bounds *}\n\ntheory Atan_CF_Bounds\nimports Bounds_Lemmas  \n        \"~~/src/HOL/Library/Sum_of_Squares\"\n\nbegin\n\ntext{*Covers all bounds used in arctan-upper.ax, arctan-lower.ax and arctan-extended.ax,\nexcepting only arctan-extended2.ax, which is used in two atan-error-analysis problems.*}\n\nsection {*Upper Bound 1*}\n\ndefinition arctan_upper_11 :: \"real \\<Rightarrow> real\"\n  where \"arctan_upper_11 \\<equiv> \\<lambda>x. -(pi/2) - 1/x\"\n\ndefinition diff_delta_arctan_upper_11 :: \"real \\<Rightarrow> real\"\n  where \"diff_delta_arctan_upper_11 \\<equiv> \\<lambda>x. 1 / (x^2 * (1 + x^2))\"\n\n\n\nlemma d_delta_arctan_upper_11_pos: \"x \\<noteq> 0 \\<Longrightarrow> diff_delta_arctan_upper_11 x > 0\"\nunfolding diff_delta_arctan_upper_11_def\nby (simp add: divide_simps zero_less_mult_iff add_pos_pos)\n\ntext{*Different proof needed here: they coincide not at zero, but at (-) infinity!*}\n\nlemma arctan_upper_11:\n  assumes \"x < 0\"\n    shows \"arctan(x) < arctan_upper_11 x\"\nproof -\n  have \"((\\<lambda>x. arctan_upper_11 x - arctan x) ---> - (pi / 2) - 0 - (- (pi / 2))) at_bot\"\n    unfolding arctan_upper_11_def\n    apply (intro tendsto_intros tendsto_arctan_at_bot, auto simp: ext [OF divide_inverse])\n    apply (metis tendsto_inverse_0 at_bot_le_at_infinity tendsto_mono)\n    done\n  then have *: \"((\\<lambda>x. arctan_upper_11 x - arctan x) ---> 0) at_bot\"\n    by simp\n  have \"0 < arctan_upper_11 x - arctan x\"\n    apply (rule DERIV_pos_imp_increasing_at_bot [OF _ *])\n    apply (metis assms d_delta_arctan_upper_11 d_delta_arctan_upper_11_pos not_le)\n    done\n  then show ?thesis\n    by auto\nqed\n\ndefinition arctan_upper_12 :: \"real \\<Rightarrow> real\"\n  where \"arctan_upper_12 \\<equiv> \\<lambda>x. 3*x / (x^2 + 3)\"\n\ndefinition diff_delta_arctan_upper_12 :: \"real \\<Rightarrow> real\"\n  where \"diff_delta_arctan_upper_12 \\<equiv> \\<lambda>x. -4*x^4 / ((x^2+3)^2 * (1+x^2))\"\n\nlemma d_delta_arctan_upper_12:\n     \"((\\<lambda>x. arctan_upper_12 x - arctan x) has_field_derivative diff_delta_arctan_upper_12 x) (at x)\"\n  unfolding arctan_upper_12_def diff_delta_arctan_upper_12_def\n  using assms\n  apply (intro derivative_eq_intros,  simp_all)\n  apply (auto simp: divide_simps add_nonneg_eq_0_iff, algebra)\n  done\n\ntext{*Strict inequalities also possible*}\nlemma arctan_upper_12:\n  assumes \"x \\<le> 0\" shows \"arctan(x) \\<le> arctan_upper_12 x\"\napply (rule gen_upper_bound_decreasing [OF assms d_delta_arctan_upper_12])\napply (auto simp: diff_delta_arctan_upper_12_def arctan_upper_12_def)\ndone\n\ndefinition arctan_upper_13 :: \"real \\<Rightarrow> real\"\n  where \"arctan_upper_13 \\<equiv> \\<lambda>x. x\"\n\ndefinition diff_delta_arctan_upper_13 :: \"real \\<Rightarrow> real\"\n  where \"diff_delta_arctan_upper_13 \\<equiv> \\<lambda>x. x^2 / (1 + x^2)\"\n\nlemma d_delta_arctan_upper_13:\n    \"((\\<lambda>x. arctan_upper_13 x - arctan x) has_field_derivative diff_delta_arctan_upper_13 x) (at x)\"\nunfolding arctan_upper_13_def diff_delta_arctan_upper_13_def\napply (intro derivative_eq_intros, simp_all)\napply (simp add: divide_simps add_nonneg_eq_0_iff)\ndone\n\nlemma arctan_upper_13:\n  assumes \"x \\<ge> 0\" shows \"arctan(x) \\<le> arctan_upper_13 x\"\napply (rule gen_upper_bound_increasing [OF assms d_delta_arctan_upper_13])\napply (auto simp: diff_delta_arctan_upper_13_def arctan_upper_13_def)\ndone\n\ndefinition arctan_upper_14 :: \"real \\<Rightarrow> real\"\n  where \"arctan_upper_14 \\<equiv> \\<lambda>x. pi/2 - 3*x / (1 + 3*x^2)\"\n\ndefinition diff_delta_arctan_upper_14 :: \"real \\<Rightarrow> real\"\n  where \"diff_delta_arctan_upper_14 \\<equiv> \\<lambda>x. -4 / ((1 + 3*x^2)^2 * (1+x^2))\"\n\nlemma d_delta_arctan_upper_14:\n  \"((\\<lambda>x. arctan_upper_14 x - arctan x) has_field_derivative diff_delta_arctan_upper_14 x) (at x)\"\nunfolding arctan_upper_14_def diff_delta_arctan_upper_14_def\napply (intro derivative_eq_intros | simp add: add_nonneg_eq_0_iff)+\napply (simp add: divide_simps add_nonneg_eq_0_iff, algebra)\ndone\n\nlemma d_delta_arctan_upper_14_neg: \"diff_delta_arctan_upper_14 x < 0\"\nunfolding diff_delta_arctan_upper_14_def\napply (auto simp: divide_simps add_nonneg_eq_0_iff zero_less_mult_iff)\nusing power2_less_0 [of x]\napply arith\ndone\n\nlemma lim14: \"((\\<lambda>x::real. 3 * x / (1 + 3 * x\\<^sup>2)) ---> 0) at_infinity\"\n  apply (rule tendsto_0_le [where f = inverse and K=1])\n  apply (metis tendsto_inverse_0)\n  apply (simp add: eventually_at_infinity)\n  apply (rule_tac x=1 in exI)\n  apply (simp add: power_eq_if abs_if divide_simps add_sign_intros)\n  done\n\ntext{*Different proof needed here: they coincide not at zero, but at (+) infinity!*}\n\nlemma arctan_upper_14:\n  assumes \"x > 0\"\n    shows \"arctan(x) < arctan_upper_14 x\"\nproof -\n  have \"((\\<lambda>x. arctan_upper_14 x - arctan x) ---> pi / 2 - 0 - pi / 2) at_top\"\n    unfolding arctan_upper_14_def\n    apply (intro tendsto_intros tendsto_arctan_at_top)\n    apply (auto simp: tendsto_mono [OF at_top_le_at_infinity lim14])\n    done\n  then have *: \"((\\<lambda>x. arctan_upper_14 x - arctan x) ---> 0) at_top\"\n    by simp\n  have \"0 < arctan_upper_14 x - arctan x\"\n    apply (rule DERIV_neg_imp_decreasing_at_top [OF _ *])\n    apply (metis d_delta_arctan_upper_14 d_delta_arctan_upper_14_neg)\n    done\n  then show ?thesis\n    by auto\nqed\n\nsection {*Lower Bound 1*}\n\ndefinition arctan_lower_11 :: \"real \\<Rightarrow> real\"\n  where \"arctan_lower_11 \\<equiv> \\<lambda>x. -(pi/2) - 3*x / (1 + 3*x^2)\"\n\nlemma arctan_lower_11:\n  assumes \"x < 0\"\n    shows \"arctan(x) > arctan_lower_11 x\"\n    using arctan_upper_14 [of \"-x\"] assms\n    by (auto simp: arctan_upper_14_def arctan_lower_11_def arctan_minus)\n\nabbreviation \"arctan_lower_12 \\<equiv> arctan_upper_13\"\n\nlemma arctan_lower_12:\n  assumes \"x \\<le> 0\"\n    shows \"arctan(x) \\<ge> arctan_lower_12 x\"\n    using arctan_upper_13 [of \"-x\"] assms\n    by (auto simp: arctan_upper_13_def arctan_minus)\n\nabbreviation \"arctan_lower_13 \\<equiv> arctan_upper_12\"\n\nlemma arctan_lower_13:\n  assumes \"x \\<ge> 0\"\n    shows \"arctan(x) \\<ge> arctan_lower_13 x\"\n    using arctan_upper_12 [of \"-x\"] assms\n    by (auto simp: arctan_upper_12_def arctan_minus)\n\ndefinition arctan_lower_14 :: \"real \\<Rightarrow> real\"\n  where \"arctan_lower_14 \\<equiv> \\<lambda>x. pi/2 - 1/x\"\n\nlemma arctan_lower_14:\n  assumes \"x > 0\"\n    shows \"arctan(x) > arctan_lower_14 x\"\n    using arctan_upper_11 [of \"-x\"] assms\n    by (auto simp: arctan_upper_11_def arctan_lower_14_def arctan_minus)\n\nsection {*Upper Bound 3*}\n\ndefinition arctan_upper_31 :: \"real \\<Rightarrow> real\"\n  where \"arctan_upper_31 \\<equiv> \\<lambda>x. -(pi/2) - (64 + 735*x^2 + 945*x^4) / (15*x*(15 + 70*x^2 + 63*x^4))\"\n\ndefinition diff_delta_arctan_upper_31 :: \"real \\<Rightarrow> real\"\n  where \"diff_delta_arctan_upper_31 \\<equiv> \\<lambda>x. 64 / (x^2 * (15 + 70*x^2 + 63*x^4)^2 * (1 + x^2))\"\n\nlemma d_delta_arctan_upper_31:\n  assumes \"x \\<noteq> 0\"\n    shows \"((\\<lambda>x. arctan_upper_31 x - arctan x) has_field_derivative diff_delta_arctan_upper_31 x) (at x)\"\n  unfolding arctan_upper_31_def diff_delta_arctan_upper_31_def\n  using assms\n  apply (intro derivative_eq_intros)\n  apply (rule refl | simp add: add_nonneg_eq_0_iff)+\n  apply (simp add: divide_simps add_nonneg_eq_0_iff, algebra)\n  done\n\nlemma d_delta_arctan_upper_31_pos: \"x \\<noteq> 0 \\<Longrightarrow> diff_delta_arctan_upper_31 x > 0\"\nunfolding diff_delta_arctan_upper_31_def\nby (auto simp: divide_simps zero_less_mult_iff add_pos_pos add_nonneg_eq_0_iff)\n\nlemma arctan_upper_31:\n  assumes \"x < 0\"\n    shows \"arctan(x) < arctan_upper_31 x\"\nproof -\n  have *: \"\\<And>x::real.  (15 + 70 * x\\<^sup>2 + 63 * x ^ 4) > 0\"\n    by (sos \"((R<1 + ((R<1 * ((R<7/8 * [19/7*x^2 + 1]^2) + ((R<4 * [x]^2) + (R<10/7 * [x^2]^2)))) + ((A<=0 * R<1) * (R<1/8 * [1]^2)))))\")\n  then have **: \"\\<And>x::real. \\<not> (15 + 70 * x\\<^sup>2 + 63 * x ^ 4) < 0\"\n    by (simp add: not_less)\n  have \"((\\<lambda>x::real. (64 + 735 * x\\<^sup>2 + 945 * x ^ 4) / (15 * x * (15 + 70 * x\\<^sup>2 + 63 * x ^ 4))) ---> 0) at_bot\"\n    apply (rule tendsto_0_le [where f = inverse and K=2])\n    apply (metis at_bot_le_at_infinity tendsto_inverse_0 tendsto_mono)\n    apply (simp add: eventually_at_bot_linorder)\n    apply (rule_tac x=\"-1\" in exI)\n    apply (auto simp: divide_simps abs_if zero_less_mult_iff **)\n    done\n  then have \"((\\<lambda>x. arctan_upper_31 x - arctan x) ---> - (pi / 2) - 0 - (- (pi / 2))) at_bot\"\n    unfolding arctan_upper_31_def\n    apply (intro tendsto_intros tendsto_arctan_at_bot, auto)\n    done\n  then have *: \"((\\<lambda>x. arctan_upper_31 x - arctan x) ---> 0) at_bot\"\n    by simp\n  have \"0 < arctan_upper_31 x - arctan x\"\n    apply (rule DERIV_pos_imp_increasing_at_bot [OF _ *])\n    apply (metis assms d_delta_arctan_upper_31 d_delta_arctan_upper_31_pos not_le)\n    done\n  then show ?thesis\n    by auto\nqed\n\ndefinition arctan_upper_32 :: \"real \\<Rightarrow> real\"\n  where \"arctan_upper_32 \\<equiv> \\<lambda>x. 7*(33*x^4 + 170*x^2 + 165)*x / (5*(5*x^6 + 105*x^4 + 315*x^2 + 231))\"\n\ndefinition diff_delta_arctan_upper_32 :: \"real \\<Rightarrow> real\"\n  where \"diff_delta_arctan_upper_32 \\<equiv> \\<lambda>x. -256*x^12 / ((5*x^6+105*x^4+315*x^2+231)^2*(1+x^2))\"\n\nlemma d_delta_arctan_upper_32:\n    \"((\\<lambda>x. arctan_upper_32 x - arctan x) has_field_derivative diff_delta_arctan_upper_32 x) (at x)\"\n    unfolding arctan_upper_32_def diff_delta_arctan_upper_32_def\n    apply (intro derivative_eq_intros | simp)+\n    apply simp_all\n    apply (auto simp: add_nonneg_eq_0_iff divide_simps, algebra)\n    done\n\nlemma arctan_upper_32:\n  assumes \"x \\<le> 0\" shows \"arctan(x) \\<le> arctan_upper_32 x\"\napply (rule gen_upper_bound_decreasing [OF assms d_delta_arctan_upper_32])\napply (auto simp: diff_delta_arctan_upper_32_def arctan_upper_32_def)\ndone\n\ndefinition arctan_upper_33 :: \"real \\<Rightarrow> real\"\n  where \"arctan_upper_33 \\<equiv> \\<lambda>x. (64*x^4+735*x^2+945)*x / (15*(15*x^4+70*x^2+63))\"\n\ndefinition diff_delta_arctan_upper_33 :: \"real \\<Rightarrow> real\"\n  where \"diff_delta_arctan_upper_33 \\<equiv> \\<lambda>x. 64*x^10 / ((15*x^4+70*x^2+63)^2*(1+x^2))\"\n\nlemma d_delta_arctan_upper_33:\n    \"((\\<lambda>x. arctan_upper_33 x - arctan x) has_field_derivative diff_delta_arctan_upper_33 x) (at x)\"\nunfolding arctan_upper_33_def diff_delta_arctan_upper_33_def\napply (intro derivative_eq_intros, simp_all)\napply (auto simp: add_nonneg_eq_0_iff divide_simps, algebra)\ndone\n\nlemma arctan_upper_33:\n  assumes \"x \\<ge> 0\" shows \"arctan(x) \\<le> arctan_upper_33 x\"\napply (rule gen_upper_bound_increasing [OF assms d_delta_arctan_upper_33])\napply (auto simp: diff_delta_arctan_upper_33_def arctan_upper_33_def)\ndone\n\ndefinition arctan_upper_34 :: \"real \\<Rightarrow> real\"\n  where \"arctan_upper_34 \\<equiv>\n         \\<lambda>x. pi/2 - (33 + 170*x^2 + 165*x^4)*7*x / (5*(5 + 105*x^2 + 315*x^4 + 231*x^6))\"\n\ndefinition diff_delta_arctan_upper_34 :: \"real \\<Rightarrow> real\"\n  where \"diff_delta_arctan_upper_34 \\<equiv> \\<lambda>x. -256 / ((5+105*x^2+315*x^4+231*x^6)^2*(1+x^2))\"\n\nlemma d_delta_arctan_upper_34:\n  \"((\\<lambda>x. arctan_upper_34 x - arctan x) has_field_derivative diff_delta_arctan_upper_34 x) (at x)\"\nunfolding arctan_upper_34_def diff_delta_arctan_upper_34_def\napply (intro derivative_eq_intros | simp add: add_nonneg_eq_0_iff)+\napply (simp add: divide_simps add_nonneg_eq_0_iff, algebra)\ndone\n\nlemma d_delta_arctan_upper_34_pos: \"diff_delta_arctan_upper_34 x < 0\"\nunfolding diff_delta_arctan_upper_34_def\napply (simp add: divide_simps add_nonneg_eq_0_iff zero_less_mult_iff)\nusing power2_less_0 [of x]\napply arith\ndone\n\nlemma arctan_upper_34:\n  assumes \"x > 0\"\n    shows \"arctan(x) < arctan_upper_34 x\"\nproof -\n  have \"((\\<lambda>x. arctan_upper_34 x - arctan x) ---> pi / 2 - 0 - pi / 2) at_top\"\n    unfolding arctan_upper_34_def\n    apply (intro tendsto_intros tendsto_arctan_at_top, auto)\n    apply (rule tendsto_0_le [where f = inverse and K=1])\n    apply (metis tendsto_inverse_0 at_top_le_at_infinity tendsto_mono)\n    apply (simp add: eventually_at_top_linorder)\n    apply (rule_tac x=1 in exI)\n    apply (auto simp: divide_simps power_eq_if add_pos_pos algebra_simps)\n    done\n  then have *: \"((\\<lambda>x. arctan_upper_34 x - arctan x) ---> 0) at_top\"\n    by simp\n  have \"0 < arctan_upper_34 x - arctan x\"\n    apply (rule DERIV_neg_imp_decreasing_at_top [OF _ *])\n    apply (metis d_delta_arctan_upper_34 d_delta_arctan_upper_34_pos)\n    done\n  then show ?thesis\n    by auto\nqed\n\nsection {*Lower Bound 3*}\n\ndefinition arctan_lower_31 :: \"real \\<Rightarrow> real\"\n  where \"arctan_lower_31 \\<equiv> \\<lambda>x. -(pi/2) - (33 + 170*x^2 + 165*x^4)*7*x / (5*(5 + 105*x^2 + 315*x^4 + 231*x^6))\"\n\nlemma arctan_lower_31:\n  assumes \"x < 0\"\n    shows \"arctan(x) > arctan_lower_31 x\"\n    using arctan_upper_34 [of \"-x\"] assms\n    by (auto simp: arctan_upper_34_def arctan_lower_31_def arctan_minus)\n\nabbreviation \"arctan_lower_32 \\<equiv> arctan_upper_33\"\n\nlemma arctan_lower_32:\n  assumes \"x \\<le> 0\"\n    shows \"arctan(x) \\<ge> arctan_lower_32 x\"\n    using arctan_upper_33 [of \"-x\"] assms\n    by (auto simp: arctan_upper_33_def arctan_minus)\n\nabbreviation \"arctan_lower_33 \\<equiv> arctan_upper_32\"\n\nlemma arctan_lower_33:\n  assumes \"x \\<ge> 0\"\n    shows \"arctan(x) \\<ge> arctan_lower_33 x\"\n    using arctan_upper_32 [of \"-x\"] assms\n    by (auto simp: arctan_upper_32_def arctan_minus)\n\ndefinition arctan_lower_34 :: \"real \\<Rightarrow> real\"\n  where \"arctan_lower_34 \\<equiv> \\<lambda>x. pi/2 - (64 + 735*x^2 + 945*x^4) / (15*x*(15 + 70*x^2 + 63*x^4))\"\n\nlemma arctan_lower_34:\n  assumes \"x > 0\"\n    shows \"arctan(x) > arctan_lower_34 x\"\n    using arctan_upper_31 [of \"-x\"] assms\n    by (auto simp: arctan_upper_31_def arctan_lower_34_def arctan_minus)\n\nsection {*Upper Bound 4*}\n\ndefinition arctan_upper_41 :: \"real \\<Rightarrow> real\"\n  where \"arctan_upper_41 \\<equiv>\n        \\<lambda>x. -(pi/2) - (256 + 5943*x^2 + 19250*x^4 + 15015*x^6) /\n               (35*x*(35 + 315*x^2 + 693*x^4 + 429*x^6))\"\n\ndefinition diff_delta_arctan_upper_41 :: \"real \\<Rightarrow> real\"\n  where \"diff_delta_arctan_upper_41 \\<equiv> \\<lambda>x. 256 / (x^2*(35+315*x^2+693*x^4+429*x^6)^2*(1+x^2))\"\n\nlemma d_delta_arctan_upper_41:\n  assumes \"x \\<noteq> 0\"\n    shows \"((\\<lambda>x. arctan_upper_41 x - arctan x) has_field_derivative diff_delta_arctan_upper_41 x) (at x)\"\n  unfolding arctan_upper_41_def diff_delta_arctan_upper_41_def\n  using assms\n  apply (intro derivative_eq_intros)\n  apply (rule refl | simp add: add_nonneg_eq_0_iff)+\n  apply (simp add: divide_simps add_nonneg_eq_0_iff, algebra)\n  done\n\nlemma d_delta_arctan_upper_41_pos: \"x \\<noteq> 0 \\<Longrightarrow> diff_delta_arctan_upper_41 x > 0\"\nunfolding diff_delta_arctan_upper_41_def\nby (auto simp: zero_less_mult_iff add_pos_pos add_nonneg_eq_0_iff)\n\nlemma arctan_upper_41:\n  assumes \"x < 0\"\n    shows \"arctan(x) < arctan_upper_41 x\"\nproof -\n  have *: \"\\<And>x::real. (35 + 315 * x\\<^sup>2 + 693 * x ^ 4 + 429 * x ^ 6) > 0\"\n    by (sos \"((R<1 + ((R<1 * ((R<13/8589934592 * [95/26*x^2 + 1]^2) + ((R<38654705675/4294967296 * [170080704731/154618822700*x^3 + x]^2) + ((R<14271/446676598784 * [x^2]^2) + (R<3631584276674589067439/2656331147370089676800 * [x^3]^2))))) + ((A<=0 * R<1) * (R<245426703/8589934592 * [1]^2)))))\")\n  then have **: \"\\<And>x::real. x < 0 \\<Longrightarrow> \\<not> (35 + 315 * x\\<^sup>2 + 693 * x ^ 4 + 429 * x ^ 6) < 0\"\n    by (simp add: not_less)\n  have \"((\\<lambda>x::real. (256 + 5943 * x\\<^sup>2 + 19250 * x ^ 4 + 15015 * x ^ 6) /\n           (35 * x * (35 + 315 * x\\<^sup>2 + 693 * x ^ 4 + 429 * x ^ 6))) ---> 0) at_bot\"\n    apply (rule tendsto_0_le [where f = inverse and K=2])\n    apply (metis at_bot_le_at_infinity tendsto_inverse_0 tendsto_mono)\n    apply (simp add: eventually_at_bot_linorder)\n    apply (rule_tac x=\"-1\" in exI)\n    apply (auto simp: ** abs_if divide_simps zero_less_mult_iff)\n    done\n  then have \"((\\<lambda>x. arctan_upper_41 x - arctan x) ---> - (pi / 2) - 0 - (- (pi / 2))) at_bot\"\n    unfolding arctan_upper_41_def\n    apply (intro tendsto_intros tendsto_arctan_at_bot, auto)\n    done\n  then have *: \"((\\<lambda>x. arctan_upper_41 x - arctan x) ---> 0) at_bot\"\n    by simp\n  have \"0 < arctan_upper_41 x - arctan x\"\n    apply (rule DERIV_pos_imp_increasing_at_bot [OF _ *])\n    apply (metis assms d_delta_arctan_upper_41 d_delta_arctan_upper_41_pos not_le)\n    done\n  then show ?thesis\n    by auto\nqed\n\ndefinition arctan_upper_42 :: \"real \\<Rightarrow> real\"\n  where \"arctan_upper_42 \\<equiv>\n          \\<lambda>x. (15159*x^6+147455*x^4+345345*x^2+225225)*x / (35*(35*x^8+1260*x^6+6930*x^4+12012*x^2+6435))\"\n\ndefinition diff_delta_arctan_upper_42 :: \"real \\<Rightarrow> real\"\n  where \"diff_delta_arctan_upper_42 \\<equiv>\n            \\<lambda>x. -16384*x^16 / ((35*x^8+1260*x^6+6930*x^4+12012*x^2+6435)^2*(1+x^2))\"\n\nlemma d_delta_arctan_upper_42:\n    \"((\\<lambda>x. arctan_upper_42 x - arctan x) has_field_derivative diff_delta_arctan_upper_42 x) (at x)\"\n    unfolding arctan_upper_42_def diff_delta_arctan_upper_42_def\n    apply (intro derivative_eq_intros, simp_all)\n    apply (auto simp: divide_simps add_nonneg_eq_0_iff, algebra)\n    done\n\nlemma arctan_upper_42:\n  assumes \"x \\<le> 0\" shows \"arctan(x) \\<le> arctan_upper_42 x\"\napply (rule gen_upper_bound_decreasing [OF assms d_delta_arctan_upper_42])\napply (auto simp: diff_delta_arctan_upper_42_def arctan_upper_42_def)\ndone\n\ndefinition arctan_upper_43 :: \"real \\<Rightarrow> real\"\n  where \"arctan_upper_43 \\<equiv>\n          \\<lambda>x. (256*x^6+5943*x^4+19250*x^2+15015)*x /\n              (35 * (35*x^6+315*x^4+693*x^2+429))\"\n\ndefinition diff_delta_arctan_upper_43 :: \"real \\<Rightarrow> real\"\n  where \"diff_delta_arctan_upper_43 \\<equiv> \\<lambda>x. 256*x^14 / ((35*x^6+315*x^4+693*x^2+429)^2*(1+x^2))\"\n\nlemma d_delta_arctan_upper_43:\n    \"((\\<lambda>x. arctan_upper_43 x - arctan x) has_field_derivative diff_delta_arctan_upper_43 x) (at x)\"\nunfolding arctan_upper_43_def diff_delta_arctan_upper_43_def\napply (intro derivative_eq_intros, simp_all)\napply (auto simp: add_nonneg_eq_0_iff divide_simps, algebra)\ndone\n\nlemma arctan_upper_43:\n  assumes \"x \\<ge> 0\" shows \"arctan(x) \\<le> arctan_upper_43 x\"\napply (rule gen_upper_bound_increasing [OF assms d_delta_arctan_upper_43])\napply (auto simp: diff_delta_arctan_upper_43_def arctan_upper_43_def)\ndone\n\ndefinition arctan_upper_44 :: \"real \\<Rightarrow> real\"\n  where \"arctan_upper_44 \\<equiv>\n         \\<lambda>x. pi/2 - (15159+147455*x^2+345345*x^4+225225*x^6)*x /\n                 (35*(35+1260*x^2+6930*x^4+12012*x^6+6435*x^8))\"\n\ndefinition diff_delta_arctan_upper_44 :: \"real \\<Rightarrow> real\"\n  where \"diff_delta_arctan_upper_44 \\<equiv>\n    \\<lambda>x. -16384 / ((35+1260*x^2+6930*x^4+12012*x^6+6435*x^8)^2*(1+x^2))\"\n\nlemma d_delta_arctan_upper_44:\n  \"((\\<lambda>x. arctan_upper_44 x - arctan x) has_field_derivative diff_delta_arctan_upper_44 x) (at x)\"\nunfolding arctan_upper_44_def diff_delta_arctan_upper_44_def\napply (intro derivative_eq_intros | simp add: add_nonneg_eq_0_iff)+\napply (simp add: divide_simps add_nonneg_eq_0_iff, algebra)\ndone\n\nlemma d_delta_arctan_upper_44_pos: \"diff_delta_arctan_upper_44 x < 0\"\nunfolding diff_delta_arctan_upper_44_def\napply (auto simp: divide_simps add_nonneg_eq_0_iff zero_less_mult_iff)\nusing power2_less_0 [of x]\napply arith\ndone\n\nlemma arctan_upper_44:\n  assumes \"x > 0\"\n    shows \"arctan(x) < arctan_upper_44 x\"\nproof -\n  have \"((\\<lambda>x. arctan_upper_44 x - arctan x) ---> pi / 2 - 0 - pi / 2) at_top\"\n    unfolding arctan_upper_44_def\n    apply (intro tendsto_intros tendsto_arctan_at_top, auto)\n    apply (rule tendsto_0_le [where f = inverse and K=1])\n    apply (metis tendsto_inverse_0 at_top_le_at_infinity tendsto_mono)\n    apply (simp add: eventually_at_top_linorder)\n    apply (rule_tac x=1 in exI)\n    apply (auto simp: zero_le_mult_iff divide_simps not_le[symmetric] power_eq_if algebra_simps)\n    done\n  then have *: \"((\\<lambda>x. arctan_upper_44 x - arctan x) ---> 0) at_top\"\n    by simp\n  have \"0 < arctan_upper_44 x - arctan x\"\n    apply (rule DERIV_neg_imp_decreasing_at_top [OF _ *])\n    apply (metis d_delta_arctan_upper_44 d_delta_arctan_upper_44_pos)\n    done\n  then show ?thesis\n    by auto\nqed\n\nsection {*Lower Bound 4*}\n\ndefinition arctan_lower_41 :: \"real \\<Rightarrow> real\"\n  where \"arctan_lower_41 \\<equiv>\n     \\<lambda>x. -(pi/2) - (15159+147455*x^2+345345*x^4+225225*x^6)*x /\n                   (35*(35+1260*x^2+6930*x^4+12012*x^6+6435*x^8))\"\n\nlemma arctan_lower_41:\n  assumes \"x < 0\"\n    shows \"arctan(x) > arctan_lower_41 x\"\n    using arctan_upper_44 [of \"-x\"] assms\n    by (auto simp: arctan_upper_44_def arctan_lower_41_def arctan_minus)\n\nabbreviation \"arctan_lower_42 \\<equiv> arctan_upper_43\"\n\nlemma arctan_lower_42:\n  assumes \"x \\<le> 0\"\n    shows \"arctan(x) \\<ge> arctan_lower_42 x\"\n    using arctan_upper_43 [of \"-x\"] assms\n    by (auto simp: arctan_upper_43_def arctan_minus)\n\nabbreviation \"arctan_lower_43 \\<equiv> arctan_upper_42\"\n\nlemma arctan_lower_43:\n  assumes \"x \\<ge> 0\"\n    shows \"arctan(x) \\<ge> arctan_lower_43 x\"\n    using arctan_upper_42 [of \"-x\"] assms\n    by (auto simp: arctan_upper_42_def arctan_minus)\n\ndefinition arctan_lower_44 :: \"real \\<Rightarrow> real\"\n  where \"arctan_lower_44 \\<equiv>\n    \\<lambda>x. pi/2 - (256+5943*x^2+19250*x^4+15015*x^6) /\n               (35*x*(35+315*x^2+693*x^4+429*x^6))\"\n\nlemma arctan_lower_44:\n  assumes \"x > 0\"\n    shows \"arctan(x) > arctan_lower_44 x\"\n    using arctan_upper_41 [of \"-x\"] assms\n    by (auto simp: arctan_upper_41_def arctan_lower_44_def arctan_minus)\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/Special_Function_Bounds/Atan_CF_Bounds.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357666736773, "lm_q2_score": 0.8438951064805861, "lm_q1q2_score": 0.7316872406395595}}
{"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>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": "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/Knaster_Tarski.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951143326727, "lm_q2_score": 0.867035758084294, "lm_q1q2_score": 0.7316872401990608}}
{"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.*)\n  theory TIP_prop_12\n  imports \"../../Test_Base\"\nbegin\n\ndatatype 'a list = nil2 | cons2 \"'a\" \"'a list\"\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 qrev :: \"'a list => 'a list => 'a list\" where\n  \"qrev (nil2) z = z\"\n| \"qrev (cons2 z2 xs) z = qrev xs (cons2 z2 z)\"\n\nlemma app_assoc: \"x (x y z) w = x y (x z w)\" by (induction y, auto)\nlemma qrev_rev: \"qrev y z = x (rev y) z\"\n  apply(induction y arbitrary: z, auto)\n  apply(simp add: app_assoc)\n  done\nlemma app_nil: \"x y nil2 = y\" by(induction y, auto)\nlemma rev_app: \"rev (x y z) = x (rev z) (rev y)\"\n  apply(induction y, auto)\n   apply(simp add: app_nil) \n  using app_assoc apply(auto)\n  done\n\ntheorem property0 :\n  \"((qrev y z) = (x (rev y) z))\"\n  apply(induction y arbitrary: z, auto)\n  apply(simp add: qrev_rev)\n  apply(simp add: app_assoc)\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_12.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357529306639, "lm_q2_score": 0.8438951104066293, "lm_q1q2_score": 0.7316872324459176}}
{"text": "(******************************************************************************)\n(* Project: Isabelle/UTP Toolkit                                              *)\n(* File: Infinity.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> Infinity Supplement \\<close>\n\ntheory Infinity\nimports HOL.Real\n  \"HOL-Library.Infinite_Set\"\n  \"Optics.Two\"\nbegin\n\ntext \\<open>\n  This theory introduces a type class @{text infinite} that guarantees that the\n  underlying universe of the type is infinite. It also provides useful theorems\n  to prove infinity of the universes for various HOL types.\n\\<close>\n\nsubsection \\<open> Type class @{text infinite} \\<close>\n\ntext \\<open>\n  The type class postulates that the universe (carrier) of a type is infinite.\n\\<close>\n\nclass infinite =\n  assumes infinite_UNIV [simp]: \"infinite (UNIV :: 'a set)\"\n\nsubsection \\<open> Infinity Theorems \\<close>\n\ntext \\<open> Useful theorems to prove that a type's @{const UNIV} is infinite. \\<close>\n\ntext \\<open>\n  Note that @{thm [source] infinite_UNIV_nat} is already a simplification rule\n  by default.\n\\<close>\n\nlemmas infinite_UNIV_int [simp]\n\ntheorem infinite_UNIV_real [simp]:\n\"infinite (UNIV :: real set)\"\n  by (rule infinite_UNIV_char_0)\n\ntheorem infinite_UNIV_fun1 [simp]:\n\"infinite (UNIV :: 'a set) \\<Longrightarrow>\n card (UNIV :: 'b set) \\<noteq> Suc 0 \\<Longrightarrow>\n infinite (UNIV :: ('a \\<Rightarrow> 'b) set)\"\n  apply (erule contrapos_nn)\n  apply (erule finite_fun_UNIVD1)\n  apply (assumption)\n  done\n\ntheorem infinite_UNIV_fun2 [simp]:\n\"infinite (UNIV :: 'b set) \\<Longrightarrow>\n infinite (UNIV :: ('a \\<Rightarrow> 'b) set)\"\n  apply (erule contrapos_nn)\n  apply (erule finite_fun_UNIVD2)\n  done\n\ntheorem infinite_UNIV_set [simp]:\n\"infinite (UNIV :: 'a set) \\<Longrightarrow>\n infinite (UNIV :: 'a set set)\"\n  apply (erule contrapos_nn)\n  apply (simp add: Finite_Set.finite_set)\n  done\n\ntheorem infinite_UNIV_prod1 [simp]:\n\"infinite (UNIV :: 'a set) \\<Longrightarrow>\n infinite (UNIV :: ('a \\<times> 'b) set)\"\n  apply (erule contrapos_nn)\n  apply (simp add: finite_prod)\n  done\n\ntheorem infinite_UNIV_prod2 [simp]:\n\"infinite (UNIV :: 'b set) \\<Longrightarrow>\n infinite (UNIV :: ('a \\<times> 'b) set)\"\n  apply (erule contrapos_nn)\n  apply (simp add: finite_prod)\n  done\n\ntheorem infinite_UNIV_sum1 [simp]:\n\"infinite (UNIV :: 'a set) \\<Longrightarrow>\n infinite (UNIV :: ('a + 'b) set)\"\n  apply (erule contrapos_nn)\n  apply (simp)\n  done\n\ntheorem infinite_UNIV_sum2 [simp]:\n\"infinite (UNIV :: 'b set) \\<Longrightarrow>\n infinite (UNIV :: ('a + 'b) set)\"\n  apply (erule contrapos_nn)\n  apply (simp)\n  done\n\n\n\ntheorem infinite_UNIV_option [simp]:\n\"infinite (UNIV :: 'a set) \\<Longrightarrow>\n infinite (UNIV :: 'a option set)\"\n  apply (erule contrapos_nn)\n  apply (simp)\n  done\n\ntheorem infinite_image [intro]:\n\"infinite A \\<Longrightarrow> inj_on f A \\<Longrightarrow> infinite (f ` A)\"\n  apply (metis finite_imageD)\n  done\n\ntheorem infinite_transfer (*[intro]*) :\n\"infinite B \\<Longrightarrow> B \\<subseteq> f ` A \\<Longrightarrow> infinite A\"\n  using infinite_super\n  apply (blast)\n  done\n\nsubsection \\<open> Instantiations \\<close>\n\ntext \\<open>\n  The instantiations for product and sum types have stronger caveats than in\n  principle needed. Namely, it would be sufficient for one type of a product\n  or sum to be infinite. A corresponding rule, however, cannot be formulated\n  using type classes. Generally, classes are not entirely adequate for the\n  purpose of deriving the infinity of HOL types, which is perhaps why a class\n  such as @{class infinite} was omitted from the Isabelle/HOL library.\n\\<close>\n\ninstance nat :: infinite by (intro_classes, simp)\ninstance int :: infinite by (intro_classes, simp)\ninstance real :: infinite by (intro_classes, simp)\ninstance \"fun\" :: (type, infinite) infinite by (intro_classes, simp)\ninstance set :: (infinite) infinite by (intro_classes, simp)\ninstance prod :: (infinite, infinite) infinite by (intro_classes, simp)\ninstance sum :: (infinite, infinite) infinite by (intro_classes, simp)\ninstance list :: (type) infinite by (intro_classes, simp)\ninstance option :: (infinite) infinite by (intro_classes, simp)\n\nsubclass (in infinite) two  by (intro_classes, auto)\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/Infinity.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357494949105, "lm_q2_score": 0.8438951064805861, "lm_q1q2_score": 0.7316872261424823}}
{"text": "(*  Title:      HOL/Corec_Examples/LFilter.thy\n    Author:     Andreas Lochbihler, ETH Zuerich\n    Author:     Dmitriy Traytel, ETH Zuerich\n    Author:     Andrei Popescu, TU Muenchen\n    Copyright   2014, 2016\n\nThe filter function on lazy lists.\n*)\n\nsection \\<open>The Filter Function on Lazy Lists\\<close>\n\ntheory LFilter\nimports \"~~/src/HOL/Library/BNF_Corec\"\nbegin\n\ncodatatype (lset: 'a) llist =\n  LNil\n| LCons (lhd: 'a) (ltl: \"'a llist\")\n\ncorecursive lfilter where\n  \"lfilter P xs = (if \\<forall>x \\<in> lset xs. \\<not> P x then\n    LNil\n    else if P (lhd xs) then\n      LCons (lhd xs) (lfilter P (ltl xs))\n    else\n      lfilter P (ltl xs))\"\nproof (relation \"measure (\\<lambda>(P, xs). LEAST n. P (lhd ((ltl ^^ n) xs)))\", rule wf_measure, clarsimp)\n  fix P xs x\n  assume \"x \\<in> lset xs\" \"P x\" \"\\<not> P (lhd xs)\"\n  from this(1,2) obtain a where \"P (lhd ((ltl ^^ a) xs))\"\n    by (atomize_elim, induct x xs rule: llist.set_induct)\n       (auto simp: funpow_Suc_right simp del: funpow.simps(2) intro: exI[of _ 0] exI[of _ \"Suc i\" for i])\n  with \\<open>\\<not> P (lhd xs)\\<close>\n    have \"(LEAST n. P (lhd ((ltl ^^ n) xs))) = Suc (LEAST n. P (lhd ((ltl ^^ Suc n) xs)))\"\n    by (intro Least_Suc) auto\n  then show \"(LEAST n. P (lhd ((ltl ^^ n) (ltl xs)))) < (LEAST n. P (lhd ((ltl ^^ n) xs)))\"\n    by (simp add: funpow_swap1[of ltl])\nqed\n\nlemma lfilter_LNil [simp]: \"lfilter P LNil = LNil\"\n  by(simp add: lfilter.code)\n\nlemma lnull_lfilter [simp]: \"lfilter P xs = LNil \\<longleftrightarrow> (\\<forall>x \\<in> lset xs. \\<not> P x)\"\nproof(rule iffI ballI)+\n  show \"\\<not> P x\" if \"x \\<in> lset xs\" \"lfilter P xs = LNil\" for x using that\n    by(induction rule: llist.set_induct)(subst (asm) lfilter.code; auto split: if_split_asm; fail)+\nqed(simp add: lfilter.code)\n\nlemma lfilter_LCons [simp]: \"lfilter P (LCons x xs) = (if P x then LCons x (lfilter P xs) else lfilter P xs)\"\n  by(subst lfilter.code)(auto intro: sym)\n\nlemma llist_in_lfilter [simp]: \"lset (lfilter P xs) = lset xs \\<inter> {x. P x}\"\nproof(intro set_eqI iffI)\n  show \"x \\<in> lset xs \\<inter> {x. P x}\" if \"x \\<in> lset (lfilter P xs)\" for x using that\n  proof(induction ys\\<equiv>\"lfilter P xs\" arbitrary: xs rule: llist.set_induct)\n    case (LCons1 x xs ys)\n    from this show ?case\n      apply(induction arg\\<equiv>\"(P, ys)\" arbitrary: ys rule: lfilter.inner_induct)\n      subgoal by(subst (asm) (2) lfilter.code)(auto split: if_split_asm elim: llist.set_cases)\n      done\n  next\n    case (LCons2 xs y x ys)\n    from LCons2(3) LCons2(1) show ?case\n      apply(induction arg\\<equiv>\"(P, ys)\" arbitrary: ys rule: lfilter.inner_induct)\n      subgoal using LCons2(2) by(subst (asm) (2) lfilter.code)(auto split: if_split_asm elim: llist.set_cases)\n      done\n  qed\n  show \"x \\<in> lset (lfilter P xs)\" if \"x \\<in> lset xs \\<inter> {x. P x}\" for x\n    using that[THEN IntD1] that[THEN IntD2] by(induction) auto\nqed\n\nlemma lfilter_unique_weak:\n  \"(\\<And>xs. f xs = (if \\<forall>x \\<in> lset xs. \\<not> P x then LNil\n    else if P (lhd xs) then LCons (lhd xs) (f (ltl xs))\n    else lfilter P (ltl xs)))\n   \\<Longrightarrow> f = lfilter P\"\n  by(corec_unique)(rule ext lfilter.code)+\n\nlemma lfilter_unique:\n  assumes \"\\<And>xs. f xs = (if \\<forall>x\\<in>lset xs. \\<not> P x then LNil\n    else if P (lhd xs) then LCons (lhd xs) (f (ltl xs))\n    else f (ltl xs))\"\n  shows \"f = lfilter P\"\n\\<comment> \\<open>It seems as if we cannot use @{thm lfilter_unique_weak} for showing this as the induction and the coinduction must be nested\\<close>\nproof(rule ext)\n  show \"f xs = lfilter P xs\" for xs\n  proof(coinduction arbitrary: xs)\n    case (Eq_llist xs)\n    show ?case\n      apply(induction arg\\<equiv>\"(P, xs)\" arbitrary: xs rule: lfilter.inner_induct)\n      apply(subst (1 2 3 4) assms)\n      apply(subst (1 2 3 4) lfilter.code)\n      apply auto\n      done\n  qed\nqed\n\nlemma lfilter_lfilter: \"lfilter P \\<circ> lfilter Q = lfilter (\\<lambda>x. P x \\<and> Q x)\"\n  by(rule lfilter_unique)(auto elim: llist.set_cases)\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/Corec_Examples/LFilter.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950868503681, "lm_q2_score": 0.8670357512127872, "lm_q1q2_score": 0.7316872105720892}}
{"text": "(*  Author: Tobias Nipkow, 2007 *)\n\nsection {* Lists as vectors *}\n\ntheory ListVector\nimports List Main\nbegin\n\ntext{* \\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. *}\n\ntext{* Multiplication with a scalar: *}\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 {* @{text\"+\"} and @{text\"-\"} *}\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_listsum_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": "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/ListVector.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894604912849, "lm_q2_score": 0.8175744850834649, "lm_q1q2_score": 0.7315570324192736}}
{"text": "theory Formula\nimports BDT \nbegin\n\ntype_synonym atom = bool\n\ndatatype binop = And | Or | Impl\n\n(* inductive definition of abstract syntax trees for formula *)\n\ndatatype form = \n     Var  \"var\" \n   | Atom \"atom\"\n   | Neg  \"form\"\n   | Bin  \"binop\" \"form\" \"form\"\n\n\ntext \\<open> Notations \\<close>\n\nsyntax        \"_top\"  :: \"form\"   (\"top\\<^sub>F\")\ntranslations  \"top\\<^sub>F\"  == \"(CONST Atom) (CONST True)\"\n\nsyntax        \"_bot\"  :: \"form\"   (\"bot\\<^sub>F\")\ntranslations  \"bot\\<^sub>F\"  == \"(CONST Atom) (CONST False)\"\n\nsyntax        \"_neg\"  :: \"form \\<Rightarrow> form\"   (\"neg\\<^sub>F _\")\ntranslations  \"neg\\<^sub>F F\" == \"(CONST Neg) F\"\n\nsyntax        \"_and\"  :: \"form \\<Rightarrow> form \\<Rightarrow> form\"   (\"and\\<^sub>F _ _\")\ntranslations  \"and\\<^sub>F F1 F2\" == \"(CONST Bin) (CONST And) F1 F2\"\n\nsyntax        \"_or\"  :: \"form \\<Rightarrow> form \\<Rightarrow> form\"   (\"or\\<^sub>F _ _\")\ntranslations  \"or\\<^sub>F F1 F2\" == \"(CONST Bin) (CONST Or) F1 F2\"\n\nsyntax        \"_impl\"  :: \"form \\<Rightarrow> form \\<Rightarrow> form\"   (\"impl\\<^sub>F _ _\")\ntranslations  \"impl\\<^sub>F F1 F2\" == \"(CONST Bin) (CONST Impl) F1 F2\"\n\n(** Test cases *)\n\ndefinition p0 where \"p0 = Var 0\"\ndefinition p1 where \"p1 = Var 1\"\ndefinition p2 where \"p2 = Var 2\"\n\ndefinition P0     where \"P0        = impl\\<^sub>F p0 p1\"\ndefinition P1     where \"P1        = impl\\<^sub>F p1 P0\"\ndefinition dnegp  where \"dnegp P Q = (impl\\<^sub>F (impl\\<^sub>F P Q) Q)\"\ndefinition P2     where \"P2        = dnegp P0 p0\"\n\n(** ** Semantic *)\n(* Boolean interpretation of binary operators *)\n\nfun interp (\"I\\<^sub>f\\<^sub>o\\<^sub>r\\<^sub>m\") where\n    \"I\\<^sub>f\\<^sub>o\\<^sub>r\\<^sub>m  _ _ = undefined\" (* a completer *)\n \nvalue \"I\\<^sub>f\\<^sub>o\\<^sub>r\\<^sub>m P2 Itrue \"\nvalue \"I\\<^sub>f\\<^sub>o\\<^sub>r\\<^sub>m P2 Ifalse \"\nvalue \"I\\<^sub>f\\<^sub>o\\<^sub>r\\<^sub>m P2 (list2interpretation [True,False] False) \"\nvalue \"I\\<^sub>f\\<^sub>o\\<^sub>r\\<^sub>m P2 (list2interpretation [False,True] False) \"\n\n(** ** Equivalence *)\n\ndefinition equiv where \"equiv P Q = (\\<forall>I. I\\<^sub>f\\<^sub>o\\<^sub>r\\<^sub>m  P I = I\\<^sub>f\\<^sub>o\\<^sub>r\\<^sub>m  Q I)\"\n\nlemma negimpl : \"equiv (neg\\<^sub>F (impl\\<^sub>F P Q)) (and\\<^sub>F P (neg\\<^sub>F Q))\"\nunfolding equiv_def\nby auto\n\n\n\nlemma implor : \"equiv (impl\\<^sub>F P Q) (or\\<^sub>F (neg\\<^sub>F P)  Q)\" \nunfolding equiv_def\nby auto\n\n\n(** ** Validity *)\ndefinition valid where \"valid P = (\\<forall> I. I\\<^sub>f\\<^sub>o\\<^sub>r\\<^sub>m  P I = True)\"\n\nlemma Pierce :\" valid (impl\\<^sub>F (impl\\<^sub>F (impl\\<^sub>F P Q) P) P)\"\nunfolding valid_def\nby auto\n\nend\n", "meta": {"author": "JPenuchot", "repo": "bdt-project", "sha": "5ab2fc5c5eb23bef1d30a9fc003fbc04b55847d4", "save_path": "github-repos/isabelle/JPenuchot-bdt-project", "path": "github-repos/isabelle/JPenuchot-bdt-project/bdt-project-5ab2fc5c5eb23bef1d30a9fc003fbc04b55847d4/BDTProject/Formula.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894661025423, "lm_q2_score": 0.8175744761936437, "lm_q1q2_score": 0.7315570290523761}}
{"text": "theory E4_6\n  imports Main\nbegin\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 auto\nnext\n  case (Cons a xs)\n  then show ?case\n  proof (cases \"x = a\")\n    case True\n    then show ?thesis by fastforce\n  next\n    case False\n    hence \"x \\<in> elems xs\" using Cons.prems by auto\n    thus ?thesis by (metis Cons.IH False UnE append_Cons elems.simps(2) empty_iff insert_iff)\n  qed\nqed\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/chapter4/E4_6.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8947894520743981, "lm_q2_score": 0.8175744739711883, "lm_q1q2_score": 0.7315570155946939}}
{"text": "theory Chap3_1ex4\nimports Main\nbegin\n\ntype_synonym vname = string\n\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 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 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 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\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_plus: \"aval (plus a1 a2) s = aval a1 s + aval a2 s\"\n  apply (induction rule: plus.induct)\n  by auto\n\nlemma aval_times: \"aval (times a1 a2) s = aval a1 s * aval a2 s\"\n  apply (induction rule: times.induct)\n  by auto\n\nlemma \"aval (asimp a) s = aval a s\"\n  apply (induction a)\n  using aval_plus aval_times 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/Chap3_1ex4.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789454880027, "lm_q2_score": 0.8175744673038222, "lm_q1q2_score": 0.7315570119226156}}
{"text": "theory Aabid_ProgProv_Exercises2\nimports 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\n\n\nlemma add_zeroright: \"add a 0 = a\"\n  by (induction a, auto)\n\nlemma add_Suceq: \"Suc(add a b) = add a (Suc b)\"\n  by (induction a, auto)\n\nlemma add_comm: \"add a b = add b a\"\n  by (induction a, simp add: add_zeroright, simp add: add_Suceq)\n\nprimrec double :: \"nat \\<Rightarrow>  nat\" where\n\"double 0  = 0\"|\n\"double (Suc n) = Suc (Suc (double n))\"\n\nlemma double_add: \"double m = add m m\"\n  by (induction m, auto, simp add: add_Suceq)\n\n(*2.3*)\nprimrec count :: \"int  \\<Rightarrow> int list \\<Rightarrow> nat\" where\n\"count a [] = 0\"|\n\"count a (y#ys) = (if a = y then (Suc(count a ys)) else (count a ys))\"\n\nlemma count_length: \"count x xs \\<le> length xs\"\n  by (induction xs, auto)\n\n(*2.4*)\nprimrec snoc :: \"'a list \\<Rightarrow> 'a \\<Rightarrow> 'a list\" where\n\"snoc [] a  = (a#[])\"|\n\"snoc (x#xs) a = x#(snoc xs a)\"\n\nprimrec reverse :: \"'a list \\<Rightarrow> 'a list\" where\n\"reverse [] = []\"|\n\"reverse (x#xs) = snoc (reverse xs) x\"\n\nlemma app_assoc: \"(xs @ ys) @ zs = xs @ (ys @ zs)\" \n  by (induction xs, auto)\n\nlemma snoc_app: \"snoc xs x = xs @ [x]\"\n  by (induction xs, auto)\n\nlemma reverse_app_distr: \"reverse (xs @ ys) = (reverse ys) @ reverse(xs)\"\n  by (induction xs, simp add: snoc_app, auto, simp add: snoc_app)\n\nlemma reverse_reverse : \"reverse (reverse xs) = xs\"\n  by (induction xs, auto, simp add: snoc_app, simp add: reverse_app_distr)\n\n(*2.5*)\nprimrec 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_formula: \"sum_upto n = n * (n + 1) div 2\"\n  by (induction n, auto)\n\n(*2.6*)\ndatatype 'a tree = Tip | Node \"'a tree\" 'a \" 'a tree\"\n\nprimrec contents :: \"'a tree \\<Rightarrow> 'a list\" where\n\"contents Tip = []\"|\n\"contents (Node l a r) = a#((contents l) @ (contents r))\"\n\nprimrec 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 sumtree_sumlist: \"sum_tree t = sum_list (contents t)\"\n  by (induction t, auto)\n\n(*2.7*)\n(* primrec mirror :: \"'a tree \\<Rightarrow> 'a tree\" where\n\"mirror Tip = Tip\" |\n\"mirror (Node l a r ) = Node (mirror r ) a (mirror l)\"\n\nprimrec 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\nprimrec post_order :: \"'a tree \\<Rightarrow> 'a list\" where\n\"post_order Tip = []\"|\n\"post_order (Node l a r) = ((pre_order l) @ (pre_order r)) @ (a#[])\" *)\n\n(*2.8*)\nprimrec intersperse :: \"'a \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where\n\"intersperse a [] = []\"|\n\"intersperse a (x#xs) = (x#(a#(intersperse a xs)))\"\n\nlemma map_intersperse: \"map f (intersperse a xs) = intersperse (f a) (map f xs)\"\n  by (induction xs, auto)\n\n(*2.9*)\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 itadd_add: \"itadd n m = add n m\"\n  by(induction n m rule: itadd.induct, auto)\n\n(*2.10*)\ndatatype tree0 = Tip0 | Node0 \"tree0\" \"tree0\"\n\nprimrec nodes :: \"tree0 \\<Rightarrow> nat\" where\n\"nodes Tip0 = 1\"|\n\"nodes (Node0 l r) = 1 + nodes l + nodes r\"\n\nprimrec explode :: \"nat \\<Rightarrow> tree0 \\<Rightarrow> tree0\" where \n\"explode 0 t = t\"|\n\"explode (Suc n) t = explode n (Node0 t t)\"\n\nlemma nodes_explode_formula: \"nodes (explode n t) = ((2^n) * (nodes t)) + ((2^n) - 1)\"\n  by(induction n arbitrary: t, auto simp add: algebra_simps)\n\n(*2.11*)\ndatatype exp = Var | Const int | Add exp exp | Mult exp exp\n\nprimrec eval :: \"exp \\<Rightarrow> int \\<Rightarrow> int\" where\n\"eval Var x = x\"|\n\"eval (Const c) x = c\"|\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\nprimrec evalp :: \"int list \\<Rightarrow> int \\<Rightarrow> int\" where\n\"evalp [] c = 0\"|\n\"evalp (x#xs) c  = x + (c * (evalp xs c))\"", "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/Aabid_ProgProv_Exercises2.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088005554476, "lm_q2_score": 0.7879312031126512, "lm_q1q2_score": 0.7315222632020273}}
{"text": "section \\<open>\\isaheader{Implementing Unique Priority Queues by Annotated Lists}\\<close>\ntheory PrioUniqueByAnnotatedList\nimports \n  \"../spec/AnnotatedListSpec\"\n  \"../spec/PrioUniqueSpec\"\nbegin\n\ntext \\<open>\n  In this theory we use annotated lists to implement unique priority queues \n  with totally ordered elements.\n\n  This theory is written as a generic adapter from the AnnotatedList interface\n  to the unique priority queue interface.\n\n  The annotated list stores a sequence of elements annotated with \n  priorities\\footnote{Technically, the annotated list elements are of unit-type,\n  and the annotations hold both, the priority queue elements and the priorities.\n  This is required as we defined annotated lists to only sum up the elements \n  annotations.}\n\n  The monoids operations forms the maximum over the elements and\n  the minimum over the priorities. \n  The sequence of pairs is ordered by ascending elements' order. \n  The insertion point for a new element, or the priority of an existing element\n  can be found by splitting the\n  sequence at the point where the maximum of the elements read so far gets\n  bigger than the element to be inserted.\n\n  The minimum priority can be read out as the sum over the whole sequence.\n  Finding the element with minimum priority is done by splitting the sequence\n  at the point where the minimum priority of the elements read so far becomes\n  equal to the minimum priority of the whole sequence.\n\\<close>\n\nsubsection \"Definitions\"\n\nsubsubsection \"Monoid\"\ndatatype ('e, 'a) LP = Infty | LP 'e 'a\n\nfun p_unwrap :: \"('e,'a) LP \\<Rightarrow> ('e \\<times> 'a)\" where\n  \"p_unwrap (LP e a) = (e , a)\"\n\nfun p_min :: \"('e::linorder, 'a::linorder) LP \\<Rightarrow> ('e, 'a) LP \\<Rightarrow> ('e, 'a) LP\"  where\n  \"p_min Infty Infty = Infty\"|\n  \"p_min Infty (LP e a) = LP e a\"|\n  \"p_min (LP e a) Infty = LP e a\"|\n  \"p_min (LP e1 a) (LP e2 b) = (LP (max e1 e2) (min a b))\"\n\nfun e_less_eq :: \"'e \\<Rightarrow> ('e::linorder, 'a::linorder) LP \\<Rightarrow> bool\"  where\n  \"e_less_eq e Infty = False\"|\n  \"e_less_eq e (LP e' _) = (e \\<le> e')\"\n\n\ntext_raw\\<open>\\paragraph{Instantiation of classes}\\ \\\\\\<close>\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)\napply (metis max.assoc)\napply (metis min.assoc)\n  done\n\nlemma lp_mono: \"class.monoid_add p_min Infty\" by  unfold_locales  (auto simp add: p_min_asso)\n\ninstantiation LP :: (linorder,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) LP \\<Rightarrow> ('e, 'a) LP \\<Rightarrow> bool\" where\n  \"p_less_eq (LP e a) (LP f b) = (a \\<le> b)\"|\n  \"p_less_eq  _ Infty = True\"|\n  \"p_less_eq Infty (LP e a) = False\"\n\nfun p_less :: \"('e, 'a::linorder) LP \\<Rightarrow> ('e, 'a) LP \\<Rightarrow> bool\" where\n  \"p_less (LP e a) (LP f b) = (a < b)\"|\n  \"p_less (LP 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 LP :: (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\nsubsubsection \"Operations\"\n\ndefinition aluprio_\\<alpha> :: \"('s \\<Rightarrow> (unit \\<times> ('e::linorder,'a::linorder) LP) list) \n  \\<Rightarrow> 's \\<Rightarrow> ('e::linorder \\<rightharpoonup>  'a::linorder)\"\n  where \n  \"aluprio_\\<alpha> \\<alpha> ft == (map_of (map p_unwrap (map snd (\\<alpha> ft))))\"\n\ndefinition aluprio_invar :: \"('s \\<Rightarrow> (unit \\<times> ('c::linorder, 'd::linorder) LP) list)\n  \\<Rightarrow> ('s \\<Rightarrow> bool) \\<Rightarrow> 's \\<Rightarrow> bool\" \n  where\n  \"aluprio_invar \\<alpha> invar ft == \n     invar ft \n     \\<and> (\\<forall> x\\<in>set (\\<alpha> ft). snd x\\<noteq>Infty) \n     \\<and> sorted (map fst (map p_unwrap (map snd (\\<alpha> ft)))) \n     \\<and> distinct (map fst (map p_unwrap (map snd (\\<alpha> ft)))) \"\n\ndefinition aluprio_empty  where \n  \"aluprio_empty empt = empt\"\n\ndefinition aluprio_isEmpty  where \n  \"aluprio_isEmpty isEmpty = isEmpty\"\n\ndefinition aluprio_insert :: \n  \"((('e::linorder,'a::linorder) LP \\<Rightarrow> bool) \n  \\<Rightarrow> ('e,'a) LP \\<Rightarrow> 's \\<Rightarrow> ('s \\<times> (unit \\<times> ('e,'a) LP) \\<times> 's)) \n    \\<Rightarrow> ('s \\<Rightarrow> ('e,'a) LP) \n      \\<Rightarrow> ('s \\<Rightarrow> bool)\n        \\<Rightarrow> ('s \\<Rightarrow> 's \\<Rightarrow> 's) \n          \\<Rightarrow> ('s \\<Rightarrow> unit \\<Rightarrow> ('e,'a) LP \\<Rightarrow> 's)\n            \\<Rightarrow> 's \\<Rightarrow> 'e \\<Rightarrow> 'a \\<Rightarrow> 's\" \n  where\n  \"\n  aluprio_insert splits annot isEmpty app consr s e a = \n    (if e_less_eq e (annot s) \\<and> \\<not> isEmpty s \n    then\n      (let (l, (_,lp) , r) = splits (e_less_eq e) Infty s in \n        (if e < fst (p_unwrap lp)\n        then \n          app (consr (consr l () (LP e a))  () lp) r\n        else \n          app (consr l () (LP e a)) r  ))\n    else \n      consr s () (LP e a))\n  \"\n\ndefinition aluprio_pop :: \"((('e::linorder,'a::linorder) LP \\<Rightarrow> bool) \\<Rightarrow> ('e,'a) LP\n  \\<Rightarrow> 's \\<Rightarrow> ('s \\<times> (unit \\<times> ('e,'a) LP) \\<times> 's)) \n    \\<Rightarrow> ('s \\<Rightarrow> ('e,'a) LP) \n      \\<Rightarrow> ('s \\<Rightarrow> 's \\<Rightarrow> 's) \n        \\<Rightarrow> 's \n          \\<Rightarrow> 'e \\<times>'a \\<times>'s\" \n  where\n  \"aluprio_pop splits annot app s = \n    (let (l, (_,lp) , r) = splits (\\<lambda> x. x \\<le> (annot s)) Infty s \n    in \n      (case lp of \n        (LP e a) \\<Rightarrow> \n          (e, a, app l r) ))\"\n\ndefinition aluprio_prio :: \n  \"((('e::linorder,'a::linorder) LP \\<Rightarrow> bool) \\<Rightarrow> ('e,'a) LP \\<Rightarrow> 's \n  \\<Rightarrow> ('s \\<times> (unit \\<times> ('e,'a) LP) \\<times> 's)) \n    \\<Rightarrow> ('s \\<Rightarrow> ('e,'a) LP) \n      \\<Rightarrow> ('s \\<Rightarrow> bool)\n        \\<Rightarrow> 's \\<Rightarrow> 'e \\<Rightarrow> 'a option\" \n  where\n  \"\n  aluprio_prio splits annot isEmpty s e = \n    (if e_less_eq e (annot s) \\<and> \\<not> isEmpty s \n    then\n      (let (l, (_,lp) , r) = splits (e_less_eq e) Infty s in \n        (if e = fst (p_unwrap lp)\n        then \n          Some (snd (p_unwrap lp))\n        else\n          None))\n    else \n      None)\n  \"\n\nlemmas aluprio_defs =\naluprio_invar_def\naluprio_\\<alpha>_def\naluprio_empty_def\naluprio_isEmpty_def\naluprio_insert_def\naluprio_pop_def\naluprio_prio_def\n\nsubsection \"Correctness\"\n\nsubsubsection \"Auxiliary Lemmas\"\n\nlemma p_linear: \"(x::('e, 'a::linorder) LP) \\<le> y \\<or> y \\<le> x\"\n  by (unfold plesseq_def) (simp only: p_linear2)\n\n\nlemma e_less_eq_mon1: \"e_less_eq e x \\<Longrightarrow> e_less_eq e (x + y)\"\n  apply (cases x) \n  apply (auto simp add: plus_def) \n  apply (cases y) \n  apply (auto simp add: max.coboundedI1)\n  done\nlemma e_less_eq_mon2: \"e_less_eq e y \\<Longrightarrow> e_less_eq e (x + y)\"\n  apply (cases x) \n  apply (auto simp add: plus_def) \n  apply (cases y) \n  apply (auto simp add: max.coboundedI2)\n  done\nlemmas e_less_eq_mon = \n  e_less_eq_mon1\n  e_less_eq_mon2\n\nlemma p_less_eq_mon:\n  \"(x::('e::linorder,'a::linorder) LP) \\<le> z \\<Longrightarrow> (x + y) \\<le> z\"\n  apply(cases y)\n  apply(auto simp add: plus_def)\n  apply (cases x)\n  apply (cases z)\n  apply (auto simp add: plesseq_def)\n  apply (cases z)\n  apply (auto simp add: min.coboundedI1)\n  done\n\n\n\n\nlemma e_less_eq_sum_list: \n  \"\\<lbrakk>\\<not> e_less_eq e (sum_list xs)\\<rbrakk> \\<Longrightarrow> \\<forall>x \\<in> set xs. \\<not> e_less_eq e x\"\nproof (induct xs)\n  case Nil thus ?case by simp\nnext\n  case (Cons a xs)\n  hence \"\\<not> e_less_eq e (sum_list xs)\" by (auto simp add: e_less_eq_mon)\n  hence v1: \"\\<forall>x\\<in>set xs. \\<not> e_less_eq e x\" using Cons.hyps by simp\n  from Cons.prems have \"\\<not> e_less_eq e a\" by (auto simp add: e_less_eq_mon)\n  with v1 show \"\\<forall>x\\<in>set (a#xs). \\<not> e_less_eq e x\" by simp\nqed\n\nlemma e_less_eq_p_unwrap: \n  \"\\<lbrakk>x \\<noteq> Infty;\\<not> e_less_eq e x\\<rbrakk> \\<Longrightarrow> fst (p_unwrap x) < e\"\n  by (cases x) auto\n\nlemma e_less_eq_refl :\n  \"b \\<noteq> Infty \\<Longrightarrow> e_less_eq (fst (p_unwrap b)) b\"\n  by (cases b) auto\n\nlemma e_less_eq_sum_list2:\n  assumes \n  \"\\<forall>x\\<in>set (\\<alpha>s). snd x \\<noteq> Infty\"\n  \"((), b) \\<in> set (\\<alpha>s)\"\n  shows \"e_less_eq (fst (p_unwrap b)) (sum_list (map snd (\\<alpha>s)))\"\n  apply(insert assms)\n  apply (induct \"\\<alpha>s\")\n  apply (auto simp add: zero_def e_less_eq_mon e_less_eq_refl) \n  done\n\nlemma e_less_eq_lem1:\n  \"\\<lbrakk>\\<not> e_less_eq e a;e_less_eq e (a + b)\\<rbrakk> \\<Longrightarrow> e_less_eq e b\"\n  apply (auto simp add: plus_def)\n  apply (cases a)\n  apply auto\n  apply (cases b)\n  apply auto\n  apply (metis le_max_iff_disj)\n  done\n\nlemma p_unwrap_less_sum: \"snd (p_unwrap ((LP e aa) + b)) \\<le> aa\"\n  apply (cases b)\n  apply (auto simp add: plus_def)\ndone\n\nlemma  sum_list_less_elems: \"\\<forall>x\\<in>set xs. snd x \\<noteq> Infty \\<Longrightarrow>\n  \\<forall>y\\<in>set (map snd (map p_unwrap (map snd xs))).\n              snd (p_unwrap (sum_list (map snd xs))) \\<le> 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 \"sum_list (map snd as)\")\n      apply auto\n      apply (metis linorder_linear p_min_re_neut p_unwrap.simps \n        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, sum_list (map snd as))\" rule: p_min.cases)\n      apply auto\n      apply (cases \"map snd as\")\n      apply (auto simp add: infadd)\n      apply (metis min.coboundedI2 snd_conv)\n      done\nqed\n\nlemma distinct_sortet_list_app:\n  \"\\<lbrakk>sorted xs; distinct xs; xs = as @ b # cs\\<rbrakk>\n  \\<Longrightarrow> \\<forall> x\\<in> set cs. b < x\"\n  by (metis distinct.simps(2) distinct_append \n    antisym_conv2 sorted.simps(2) sorted_append)\n\nlemma distinct_sorted_list_lem1:\n  assumes \n  \"sorted xs\"\n  \"sorted ys\"\n  \"distinct xs\"\n  \"distinct ys\"\n  \" \\<forall> x \\<in> set xs. x < e\"\n  \" \\<forall> y \\<in> set ys. e < y\"\n  shows \n  \"sorted (xs @ e # ys)\"\n  \"distinct (xs @ e # ys)\"\nproof -\n  from assms (5,6)\n  have \"\\<forall>x\\<in>set xs. \\<forall>y\\<in>set ys. x \\<le> y\" by force\n  thus \"sorted (xs @ e # ys)\"\n    using assms\n    by (auto simp add: sorted_append)\n  have \"set xs \\<inter> set ys = {}\" using assms (5,6) by force\n  thus \"distinct (xs @ e # ys)\"\n    using assms\n    by (auto)\nqed\n\nlemma distinct_sorted_list_lem2:\n  assumes \n  \"sorted xs\"\n  \"sorted ys\"\n  \"distinct xs\"\n  \"distinct ys\"\n  \"e < e'\"  \n  \" \\<forall> x \\<in> set xs. x < e\"\n  \" \\<forall> y \\<in> set ys. e' < y\"\n  shows \n  \"sorted (xs @ e # e' # ys)\"\n  \"distinct (xs @ e # e' # ys)\"\nproof -\n  have \"sorted (e' # ys)\"\n    \"distinct (e' # ys)\"\n    \"\\<forall> y \\<in> set (e' # ys). e < y\"\n    using assms(2,4,5,7)\n    by (auto)\n  thus \"sorted (xs @ e # e' # ys)\"\n  \"distinct (xs @ e # e' # ys)\"\n    using assms(1,3,6) distinct_sorted_list_lem1[of xs \"e' # ys\" e]  \n    by auto\nqed\n\nlemma map_of_distinct_upd:\n  \"x \\<notin> set (map fst xs) \\<Longrightarrow> [x \\<mapsto> y] ++ map_of xs = (map_of xs) (x \\<mapsto> y)\"\n  by (induct xs) (auto simp add: fun_upd_twist)\n\nlemma map_of_distinct_upd2:\n  assumes \"x \\<notin> set(map fst xs)\"\n  \"x \\<notin> set (map fst ys)\"\n  shows \"map_of (xs @ (x,y) # ys) = (map_of (xs @ ys))(x \\<mapsto> y)\"\n  apply(insert assms)\n  apply(induct xs)\n  apply (auto intro: ext)\n  done\n\nlemma map_of_distinct_upd3:\n  assumes \"x \\<notin> set(map fst xs)\"\n  \"x \\<notin> set (map fst ys)\"\n  shows \"map_of (xs @ (x,y) # ys) = (map_of (xs @ (x,y') # ys))(x \\<mapsto> y)\"\n  apply(insert assms)\n  apply(induct xs)\n  apply (auto intro: ext)\n  done\n\nlemma map_of_distinct_upd4:\n  assumes \"x \\<notin> set(map fst xs)\"\n  \"x \\<notin> set (map fst ys)\"\n  shows \"map_of (xs @ ys) = (map_of (xs @ (x,y) # ys))(x := None)\"\n  apply(insert assms)\n  apply(induct xs)\n\n  apply clarsimp\n  apply (metis dom_map_of_conv_image_fst fun_upd_None_restrict \n    restrict_complement_singleton_eq restrict_map_self)\n\n  apply (auto simp add: map_of_eq_None_iff) []\n  done\n\nlemma map_of_distinct_lookup:\n  assumes \"x \\<notin> set(map fst xs)\"\n  \"x \\<notin> set (map fst ys)\"\n  shows \"map_of (xs @ (x,y) # ys) x = Some y\"\nproof -\n  have \"map_of (xs @ (x,y) # ys) = (map_of (xs @ ys)) (x \\<mapsto> y)\"\n    using assms map_of_distinct_upd2 by simp\n  thus ?thesis\n    by simp\nqed\n\nlemma ran_distinct: \n  assumes dist: \"distinct (map fst al)\" \n  shows \"ran (map_of al) = snd ` set al\"\nusing assms proof (induct al)\n  case Nil then show ?case by simp\nnext\n  case (Cons kv al)\n  then have \"ran (map_of al) = snd ` set al\" by simp\n  moreover from Cons.prems have \"map_of al (fst kv) = None\"\n    by (simp add: map_of_eq_None_iff)\n  ultimately show ?case by (simp only: map_of.simps ran_map_upd) simp\nqed\n\n\n\n\nsubsubsection \"Finite\"\n\nlemma aluprio_finite_correct: \"uprio_finite (aluprio_\\<alpha> \\<alpha>) (aluprio_invar \\<alpha> invar)\" \n  by(unfold_locales) (simp add: aluprio_defs finite_dom_map_of)\n\nsubsubsection \"Empty\"\nlemma aluprio_empty_correct:\n  assumes \"al_empty \\<alpha> invar empt\"\n  shows \"uprio_empty (aluprio_\\<alpha> \\<alpha>) (aluprio_invar \\<alpha> invar) (aluprio_empty empt)\"\nproof -\n  interpret al_empty \\<alpha> invar empt by fact\n  show ?thesis\n    apply (unfold_locales)\n    apply (auto simp add: empty_correct aluprio_defs)\n    done\nqed\n\nsubsubsection \"Is Empty\"\n\nlemma aluprio_isEmpty_correct: \n  assumes \"al_isEmpty \\<alpha> invar isEmpty\"\n  shows \"uprio_isEmpty (aluprio_\\<alpha> \\<alpha>) (aluprio_invar \\<alpha> invar) (aluprio_isEmpty isEmpty)\"\nproof -\n  interpret al_isEmpty \\<alpha> invar isEmpty by fact\n  show ?thesis \n    apply (unfold_locales) \n    apply (auto simp add: aluprio_defs isEmpty_correct)\n    done\nqed\n\n\nsubsubsection \"Insert\"\n\nlemma annot_inf: \n  assumes A: \"invar s\" \"\\<forall>x\\<in>set (\\<alpha> s). snd x \\<noteq> Infty\" \"al_annot \\<alpha> invar annot\"\n  shows \"annot s = Infty \\<longleftrightarrow> \\<alpha> s = [] \" \nproof -\n  from A have invs: \"invar s\" by (simp add: aluprio_defs)  \n  interpret al_annot \\<alpha> invar annot by fact\n  show \"annot s = Infty \\<longleftrightarrow> \\<alpha> s = []\"  \n  proof (cases \"\\<alpha> s = []\")\n    case True\n    hence \"map snd (\\<alpha> s) = []\" by simp\n    hence \"sum_list (map snd (\\<alpha> s)) = Infty\"  \n      by (auto simp add: zero_def)\n    with invs have  \"annot s = Infty\" by (auto simp add: annot_correct)\n    with True show ?thesis by simp\n  next\n    case False\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(2) have \"snd x \\<noteq> Infty\" by (auto simp add: aluprio_defs)\n    hence \"sum_list (map snd (\\<alpha> s)) \\<noteq> Infty\" by (auto simp add: infadd)\n    thus ?thesis using annot_correct invs False by simp\n  qed\nqed\n\nlemma e_less_eq_annot: \n  \n  assumes \"al_annot \\<alpha> invar annot\" \n   \"invar s\" \"\\<forall>x\\<in>set (\\<alpha> s). snd x \\<noteq> Infty\" \"\\<not> e_less_eq e (annot s)\"\n  shows \"\\<forall>x \\<in> set (map (fst \\<circ> (p_unwrap \\<circ> snd)) (\\<alpha> s)). x < e\"\nproof -\n  interpret al_annot \\<alpha> invar annot by fact\n  from assms(2) have \"annot s = sum_list (map snd (\\<alpha> s))\"\n    by (auto simp add: annot_correct)\n  with assms(4) have \n    \"\\<forall>x \\<in> set (map snd (\\<alpha> s)). \\<not> e_less_eq e x\"\n    by (metis e_less_eq_sum_list)\n  with assms(3) \n  show ?thesis\n    by (auto simp add: e_less_eq_p_unwrap)\nqed\n\nlemma aluprio_insert_correct: \n  assumes \n  \"al_splits \\<alpha> invar splits\"\n  \"al_annot \\<alpha> invar annot\"\n  \"al_isEmpty \\<alpha> invar isEmpty\"\n  \"al_app \\<alpha> invar app\"\n  \"al_consr \\<alpha> invar consr\"\n  shows \n  \"uprio_insert (aluprio_\\<alpha> \\<alpha>) (aluprio_invar \\<alpha> invar) \n    (aluprio_insert splits annot isEmpty app consr)\"\nproof -\n  interpret al_splits \\<alpha> invar splits by fact\n  interpret al_annot \\<alpha> invar annot by fact\n  interpret al_isEmpty \\<alpha> invar isEmpty by fact\n  interpret al_app \\<alpha> invar app by fact\n  interpret al_consr \\<alpha> invar consr by fact\n  show ?thesis \n  proof (unfold_locales, unfold aluprio_defs, goal_cases)\n    case g1asms: (1 s e a)\n    thus ?case proof (cases \"e_less_eq e (annot s) \\<and> \\<not> isEmpty s\")\n      case False with g1asms show  ?thesis\n        apply (auto simp add: consr_correct )\n      proof goal_cases\n        case prems: 1\n        with assms(2) have  \n          \"\\<forall>x \\<in> set (map (fst \\<circ> (p_unwrap \\<circ> snd)) (\\<alpha> s)). x < e\"\n          by (simp add: e_less_eq_annot)\n        with prems(3) show ?case\n          by(auto simp add: sorted_append)\n      next\n        case prems: 2\n        hence \"annot s = sum_list (map snd (\\<alpha> s))\" \n          by (simp add: annot_correct)\n        with prems\n        show ?case \n          by (auto simp add: e_less_eq_sum_list2)\n      next\n        case prems: 3\n        hence \"\\<alpha> s = []\" by (auto simp add: isEmpty_correct)\n        thus ?case by simp\n      next\n        case prems: 4\n        hence \"\\<alpha> s = []\" by (auto simp add: isEmpty_correct)\n        with prems show ?case by simp\n      qed\n    next\n      case True note T1 = this\n      obtain l uu lp r where \n        l_lp_r: \"(splits (e_less_eq e) Infty s) = (l, ((), lp), r) \"\n        by (cases \"splits (e_less_eq e) Infty s\", auto)\n      note v2 = splits_correct[of s \"e_less_eq e\" Infty l \"()\" lp r]\n      have \n        v3: \"invar s\" \n        \"\\<not> e_less_eq e Infty\"\n        \"e_less_eq e (Infty + sum_list (map snd (\\<alpha> s)))\"\n        using T1 g1asms annot_correct\n        by (auto simp add: plus_def)\n      have \n        v4: \"\\<alpha> s = \\<alpha> l @ ((), lp) # \\<alpha> r\"  \n        \"\\<not> e_less_eq e (Infty + sum_list (map snd (\\<alpha> l)))\"\n        \"e_less_eq e (Infty + sum_list (map snd (\\<alpha> l)) + lp)\"\n        \"invar l\"\n        \"invar r\"\n        using v2[OF v3(1) _ v3(2) v3(3) l_lp_r] e_less_eq_mon(1) by auto\n      hence v5: \"e_less_eq e lp\"\n        by (metis e_less_eq_lem1)\n      hence v6: \"e \\<le> (fst (p_unwrap lp))\"\n        by (cases lp) auto\n      have \"(Infty + sum_list (map snd (\\<alpha> l))) = (annot l)\"\n        by (metis add_0_left annot_correct v4(4) zero_def)\n      hence v7:\"\\<not> e_less_eq e (annot l)\"\n        using v4(2) by simp\n      have \"\\<forall>x\\<in>set (\\<alpha> l). snd x \\<noteq> Infty\"\n        using g1asms v4(1) by simp\n      hence v7: \"\\<forall>x \\<in> set (map (fst \\<circ> (p_unwrap \\<circ> snd)) (\\<alpha> l)). x < e\"\n        using v4(4) v7 assms(2)\n        by(simp add: e_less_eq_annot)\n      have v8:\"map fst (map p_unwrap (map snd (\\<alpha> s))) = \n        map fst (map p_unwrap (map snd (\\<alpha> l))) @ fst(p_unwrap lp) #\n        map fst (map p_unwrap (map snd (\\<alpha> r)))\"\n        using v4(1)\n        by simp\n      note distinct_sortet_list_app[of \"map fst (map p_unwrap (map snd (\\<alpha> s)))\"\n        \"map fst (map p_unwrap (map snd (\\<alpha> l)))\" \"fst(p_unwrap lp)\" \n        \"map fst (map p_unwrap (map snd (\\<alpha> r)))\"]\n      hence v9: \n        \"\\<forall> x\\<in>set (map (fst \\<circ> (p_unwrap \\<circ> snd)) (\\<alpha> r)). fst(p_unwrap lp) < x\"\n        using v4(1) g1asms v8\n        by auto\n      have v10: \n        \"sorted (map fst (map p_unwrap (map snd (\\<alpha> l))))\"\n        \"distinct (map fst (map p_unwrap (map snd (\\<alpha> l))))\"\n        \"sorted (map fst (map p_unwrap (map snd (\\<alpha> r))))\"\n        \"distinct (map fst (map p_unwrap (map snd (\\<alpha> l))))\"\n        using g1asms v8\n        by (auto simp add: sorted_append)\n      \n      from l_lp_r T1 g1asms show ?thesis        \n      proof (fold aluprio_insert_def, cases \"e < fst (p_unwrap lp)\")\n        case True\n        hence v11: \n          \"aluprio_insert splits annot isEmpty app consr s e a \n            = app (consr (consr l () (LP e a)) () lp) r\"\n          using l_lp_r T1\n          by (auto simp add: aluprio_defs)\n        have  v12: \"invar (app (consr (consr l () (LP e a)) () lp) r)\" \n          using v4(4,5)\n          by (auto simp add: app_correct consr_correct)\n        have v13: \n          \"\\<alpha> (app (consr (consr l () (LP e a)) () lp) r) \n            = \\<alpha> l @ ((),(LP e a)) # ((), lp) # \\<alpha> r\"\n          using v4(4,5) by (auto simp add: app_correct consr_correct)\n        hence v14: \n          \"(\\<forall>x\\<in>set (\\<alpha> (app (consr (consr l () (LP e a)) () lp) r)). \n             snd x \\<noteq> Infty)\"\n          using g1asms v4(1)\n          by auto\n        have v15: \"e = fst(p_unwrap (LP e a))\" by simp\n        hence v16: \n          \"sorted (map fst (map p_unwrap \n             (map snd (\\<alpha> l @ ((),(LP e a)) # ((), lp) # \\<alpha> r))))\"              \n          \"distinct (map fst (map p_unwrap \n             (map snd (\\<alpha> l @ ((),(LP e a)) # ((), lp) # \\<alpha> r))))\"              \n          using v10(1,3) v7 True v9 v4(1) g1asms distinct_sorted_list_lem2\n          by (auto simp add: sorted_append)              \n        thus \"invar (aluprio_insert splits annot isEmpty app consr s e a) \\<and>\n          (\\<forall>x\\<in>set (\\<alpha> (aluprio_insert splits annot isEmpty app consr s e a)). \n             snd x \\<noteq> Infty) \\<and>\n          sorted (map fst (map p_unwrap (map snd (\\<alpha> \n             (aluprio_insert splits annot isEmpty app consr s e a))))) \\<and> \n          distinct (map fst (map p_unwrap (map snd (\\<alpha> \n             (aluprio_insert splits annot isEmpty app consr s e a)))))\"\n          using v11 v12 v13 v14\n          by simp\n      next\n        case False            \n        hence v11: \n          \"aluprio_insert splits annot isEmpty app consr s e a \n             = app (consr l () (LP e a)) r\"\n          using l_lp_r T1\n          by (auto simp add: aluprio_defs)\n        have  v12: \"invar (app (consr l () (LP e a)) r)\" using v4(4,5)\n          by (auto simp add: app_correct consr_correct)\n        have v13: \"\\<alpha> (app (consr l () (LP e a)) r) = \\<alpha> l @ ((),(LP e a)) # \\<alpha> r\"\n          using v4(4,5) by (auto simp add: app_correct consr_correct)\n        hence v14: \"(\\<forall>x\\<in>set (\\<alpha> (app (consr l () (LP e a)) r)). snd x \\<noteq> Infty)\"\n          using g1asms v4(1)\n          by auto\n        have v15: \"e = fst(p_unwrap (LP e a))\" by simp\n        have v16: \"e = fst(p_unwrap lp)\"\n          using False v5 by (cases lp) auto\n        hence v17: \n          \"sorted (map fst (map p_unwrap \n            (map snd (\\<alpha> l @ ((),(LP e a)) # \\<alpha> r))))\"              \n          \"distinct (map fst (map p_unwrap \n            (map snd (\\<alpha> l @ ((),(LP e a)) # \\<alpha> r))))\"              \n          using v16 v15 v10(1,3) v7 True v9 v4(1) \n            g1asms distinct_sorted_list_lem1\n          by (auto simp add: sorted_append)              \n        thus \"invar (aluprio_insert splits annot isEmpty app consr s e a) \\<and>\n          (\\<forall>x\\<in>set (\\<alpha> (aluprio_insert splits annot isEmpty app consr s e a)). \n            snd x \\<noteq> Infty) \\<and>\n          sorted (map fst (map p_unwrap (map snd (\\<alpha> \n            (aluprio_insert splits annot isEmpty app consr s e a))))) \\<and> \n          distinct (map fst (map p_unwrap (map snd (\\<alpha> \n            (aluprio_insert splits annot isEmpty app consr s e a)))))\"\n          using v11 v12 v13 v14\n          by simp\n      qed\n    qed\n  next\n    case g1asms: (2 s e a)\n    thus ?case proof (cases \"e_less_eq e (annot s) \\<and> \\<not> isEmpty s\")\n      case False with g1asms show  ?thesis\n        apply (auto simp add: consr_correct)\n      proof goal_cases\n        case prems: 1\n        with assms(2) have  \n          \"\\<forall>x \\<in> set (map (fst \\<circ> (p_unwrap \\<circ> snd)) (\\<alpha> s)). x < e\"\n          by (simp add: e_less_eq_annot)\n        hence \"e \\<notin> set (map fst ((map (p_unwrap \\<circ> snd)) (\\<alpha> s)))\"\n          by auto\n        thus ?case\n          by (auto simp add: map_of_distinct_upd)\n      next\n        case prems: 2\n        hence \"\\<alpha> s = []\" by (auto simp add: isEmpty_correct)\n        thus ?case\n          by simp\n      qed\n    next\n      case True note T1 = this\n      obtain l lp r where \n        l_lp_r: \"(splits (e_less_eq e) Infty s) = (l, ((), lp), r) \"\n        by (cases \"splits (e_less_eq e) Infty s\", auto)\n      note v2 = splits_correct[of s \"e_less_eq e\" Infty l \"()\" lp r]\n      have \n        v3: \"invar s\" \n        \"\\<not> e_less_eq e Infty\"\n        \"e_less_eq e (Infty + sum_list (map snd (\\<alpha> s)))\"\n        using T1 g1asms annot_correct\n        by (auto simp add: plus_def)\n      have \n        v4: \"\\<alpha> s = \\<alpha> l @ ((), lp) # \\<alpha> r\"  \n        \"\\<not> e_less_eq e (Infty + sum_list (map snd (\\<alpha> l)))\"\n        \"e_less_eq e (Infty + sum_list (map snd (\\<alpha> l)) + lp)\"\n        \"invar l\"\n        \"invar r\"\n        using v2[OF v3(1) _ v3(2) v3(3) l_lp_r] e_less_eq_mon(1) by auto\n      hence v5: \"e_less_eq e lp\"\n        by (metis e_less_eq_lem1)\n      hence v6: \"e \\<le> (fst (p_unwrap lp))\"\n        by (cases lp) auto\n      have \"(Infty + sum_list (map snd (\\<alpha> l))) = (annot l)\"\n        by (metis add_0_left annot_correct v4(4) zero_def)\n      hence v7:\"\\<not> e_less_eq e (annot l)\"\n        using v4(2) by simp\n      have \"\\<forall>x\\<in>set (\\<alpha> l). snd x \\<noteq> Infty\"\n        using g1asms v4(1) by simp\n      hence v7: \"\\<forall>x \\<in> set (map (fst \\<circ> (p_unwrap \\<circ> snd)) (\\<alpha> l)). x < e\"\n        using v4(4) v7 assms(2)\n        by(simp add: e_less_eq_annot)\n      have v8:\"map fst (map p_unwrap (map snd (\\<alpha> s))) = \n        map fst (map p_unwrap (map snd (\\<alpha> l))) @ fst(p_unwrap lp) #\n        map fst (map p_unwrap (map snd (\\<alpha> r)))\"\n        using v4(1)\n        by simp\n      note distinct_sortet_list_app[of \"map fst (map p_unwrap (map snd (\\<alpha> s)))\"\n        \"map fst (map p_unwrap (map snd (\\<alpha> l)))\" \"fst(p_unwrap lp)\" \n        \"map fst (map p_unwrap (map snd (\\<alpha> r)))\"]\n      hence v9: \"\n        \\<forall> x\\<in>set (map (fst \\<circ> (p_unwrap \\<circ> snd)) (\\<alpha> r)). fst(p_unwrap lp) < x\"\n        using v4(1) g1asms v8\n        by auto\n      hence v10: \" \\<forall> x\\<in>set (map (fst \\<circ> (p_unwrap \\<circ> snd)) (\\<alpha> r)). e < x\"\n        using v6 by auto\n      have v11: \n        \"e \\<notin> set (map fst (map p_unwrap (map snd (\\<alpha> l))))\"\n        \"e \\<notin> set (map fst (map p_unwrap (map snd (\\<alpha> r))))\"\n        using v7 v10 v8 g1asms\n        by auto\n      from l_lp_r T1 g1asms show ?thesis        \n      proof (fold aluprio_insert_def, cases \"e < fst (p_unwrap lp)\")\n        case True\n        hence v12: \n          \"aluprio_insert splits annot isEmpty app consr s e a \n            = app (consr (consr l () (LP e a)) () lp) r\"\n          using l_lp_r T1\n          by (auto simp add: aluprio_defs)\n        have v13: \n          \"\\<alpha> (app (consr (consr l () (LP e a)) () lp) r) \n            = \\<alpha> l @ ((),(LP e a)) # ((), lp) # \\<alpha> r\"\n          using v4(4,5) by (auto simp add: app_correct consr_correct)\n        have v14: \"e = fst(p_unwrap (LP e a))\" by simp\n        have v15: \"e \\<notin> set (map fst (map p_unwrap (map snd(((),lp)#\\<alpha> r))))\"\n          using v11(2) True by auto\n        note map_of_distinct_upd2[OF v11(1) v15]\n        thus \n          \"map_of (map p_unwrap (map snd (\\<alpha> \n              (aluprio_insert splits annot isEmpty app consr s e a)))) \n            = map_of (map p_unwrap (map snd (\\<alpha> s)))(e \\<mapsto> a)\"\n          using v12 v13 v4(1)\n          by simp\n      next\n        case False            \n        hence v12: \n          \"aluprio_insert splits annot isEmpty app consr s e a \n            = app (consr l () (LP e a)) r\"\n          using l_lp_r T1\n          by (auto simp add: aluprio_defs)\n        have v13: \n          \"\\<alpha> (app (consr l () (LP e a)) r) = \\<alpha> l @ ((),(LP e a)) # \\<alpha> r\"\n          using v4(4,5) by (auto simp add: app_correct consr_correct)\n        have v14: \"e = fst(p_unwrap lp)\"\n          using False v5 by (cases lp) auto\n        note v15 = map_of_distinct_upd3[OF v11(1) v11(2)]\n        have v16:\"(map p_unwrap (map snd (\\<alpha> s))) = \n          (map p_unwrap (map snd (\\<alpha> l))) @ (e,snd(p_unwrap lp)) #\n          (map p_unwrap (map snd (\\<alpha> r)))\"\n          using v4(1) v14              \n          by simp\n        note v15[of a \"snd(p_unwrap lp)\"]         \n        thus \n          \"map_of (map p_unwrap (map snd (\\<alpha> \n              (aluprio_insert splits annot isEmpty app consr s e a)))) \n            = map_of (map p_unwrap (map snd (\\<alpha> s)))(e \\<mapsto> a)\"\n          using v12 v13 v16\n          by simp\n      qed\n    qed\n  qed\nqed\n\nsubsubsection \"Prio\"\nlemma aluprio_prio_correct: \n  assumes \n  \"al_splits \\<alpha> invar splits\"\n  \"al_annot \\<alpha> invar annot\"\n  \"al_isEmpty \\<alpha> invar isEmpty\"\n  shows \n  \"uprio_prio (aluprio_\\<alpha> \\<alpha>) (aluprio_invar \\<alpha> invar) (aluprio_prio splits annot isEmpty)\"\nproof -\n  interpret al_splits \\<alpha> invar splits by fact\n  interpret al_annot \\<alpha> invar annot by fact\n  interpret al_isEmpty \\<alpha> invar isEmpty by fact\n  show ?thesis \n  proof (unfold_locales)\n    fix s e\n    assume inv1: \"aluprio_invar \\<alpha> invar s\"\n    hence sinv: \"invar s\" \n      \"(\\<forall> x\\<in>set (\\<alpha> s). snd x\\<noteq>Infty)\"\n      \"sorted (map fst (map p_unwrap (map snd (\\<alpha> s))))\" \n      \"distinct (map fst (map p_unwrap (map snd (\\<alpha> s))))\"\n      by (auto simp add: aluprio_defs)\n    show \"aluprio_prio splits annot isEmpty s e = aluprio_\\<alpha> \\<alpha> s e\"\n    proof(cases \"e_less_eq e (annot s) \\<and> \\<not> isEmpty s\")\n      case False note F1 = this      \n      thus ?thesis\n      proof(cases \"isEmpty s\")\n        case True\n        hence \"\\<alpha> s = []\"\n          using sinv isEmpty_correct by simp\n        hence \"aluprio_\\<alpha> \\<alpha> s = Map.empty\" by (simp add:aluprio_defs)\n        hence \"aluprio_\\<alpha> \\<alpha> s e = None\" by simp\n        thus \"aluprio_prio splits annot isEmpty s e = aluprio_\\<alpha> \\<alpha> s e\"\n          using F1 \n          by (auto simp add: aluprio_defs)\n      next\n        case False\n        hence v3:\"\\<not> e_less_eq e (annot s)\"  using F1 by simp\n        note v4=e_less_eq_annot[OF assms(2)]\n        note v4[OF sinv(1) sinv(2) v3]\n        hence v5:\"e\\<notin>set (map (fst \\<circ> (p_unwrap \\<circ> snd)) (\\<alpha> s))\"\n          by auto\n        hence \"map_of (map (p_unwrap \\<circ> snd) (\\<alpha> s)) e = None\"\n          using map_of_eq_None_iff\n          by (metis map_map map_of_eq_None_iff set_map v5) \n        thus \"aluprio_prio splits annot isEmpty s e = aluprio_\\<alpha> \\<alpha> s e\"\n          using F1 \n          by (auto simp add: aluprio_defs)\n      qed\n    next\n      case True note T1 = this\n      obtain l uu lp r where \n        l_lp_r: \"(splits (e_less_eq e) Infty s) = (l, ((), lp), r) \"\n        by (cases \"splits (e_less_eq e) Infty s\", auto)\n      note v2 = splits_correct[of s \"e_less_eq e\" Infty l \"()\" lp r]\n      have \n        v3: \"invar s\" \n        \"\\<not> e_less_eq e Infty\"\n        \"e_less_eq e (Infty + sum_list (map snd (\\<alpha> s)))\"\n        using T1 sinv annot_correct\n        by (auto simp add: plus_def)\n      have \n        v4: \"\\<alpha> s = \\<alpha> l @ ((), lp) # \\<alpha> r\"  \n        \"\\<not> e_less_eq e (Infty + sum_list (map snd (\\<alpha> l)))\"\n        \"e_less_eq e (Infty + sum_list (map snd (\\<alpha> l)) + lp)\"\n        \"invar l\"\n        \"invar r\"\n        using v2[OF v3(1) _ v3(2) v3(3) l_lp_r] e_less_eq_mon(1) by auto\n      hence v5: \"e_less_eq e lp\"\n        by (metis e_less_eq_lem1)\n      hence v6: \"e \\<le> (fst (p_unwrap lp))\"\n        by (cases lp) auto\n      have \"(Infty + sum_list (map snd (\\<alpha> l))) = (annot l)\"\n        by (metis add_0_left annot_correct v4(4) zero_def)\n      hence v7:\"\\<not> e_less_eq e (annot l)\"\n        using v4(2) by simp\n      have \"\\<forall>x\\<in>set (\\<alpha> l). snd x \\<noteq> Infty\"\n        using sinv v4(1) by simp\n      hence v7: \"\\<forall>x \\<in> set (map (fst \\<circ> (p_unwrap \\<circ> snd)) (\\<alpha> l)). x < e\"\n        using v4(4) v7 assms(2)\n        by(simp add: e_less_eq_annot)\n      have v8:\"map fst (map p_unwrap (map snd (\\<alpha> s))) = \n        map fst (map p_unwrap (map snd (\\<alpha> l))) @ fst(p_unwrap lp) #\n        map fst (map p_unwrap (map snd (\\<alpha> r)))\"\n        using v4(1)\n        by simp\n      note distinct_sortet_list_app[of \"map fst (map p_unwrap (map snd (\\<alpha> s)))\"\n        \"map fst (map p_unwrap (map snd (\\<alpha> l)))\" \"fst(p_unwrap lp)\" \n        \"map fst (map p_unwrap (map snd (\\<alpha> r)))\"]\n      hence v9: \n        \"\\<forall> x\\<in>set (map (fst \\<circ> (p_unwrap \\<circ> snd)) (\\<alpha> r)). fst(p_unwrap lp) < x\"\n        using v4(1) sinv v8\n        by auto\n      hence v10: \" \\<forall> x\\<in>set (map (fst \\<circ> (p_unwrap \\<circ> snd)) (\\<alpha> r)). e < x\"\n        using v6 by auto\n      have v11: \n        \"e \\<notin> set (map fst (map p_unwrap (map snd (\\<alpha> l))))\"\n        \"e \\<notin> set (map fst (map p_unwrap (map snd (\\<alpha> r))))\"\n        using v7 v10 v8 sinv\n        by auto\n      from l_lp_r T1 sinv show ?thesis\n      proof (cases \"e = fst (p_unwrap lp)\")\n        case False\n        have v12: \"e \\<notin> set (map fst (map p_unwrap (map snd(\\<alpha> s))))\"\n          using v11 False v4(1) by auto\n        hence \"map_of (map (p_unwrap \\<circ> snd) (\\<alpha> s)) e = None\"\n          using map_of_eq_None_iff\n          by (metis map_map map_of_eq_None_iff set_map v12)\n        thus ?thesis\n          using T1 False l_lp_r\n          by (auto simp add: aluprio_defs)\n      next\n        case True\n        have v12: \"map (p_unwrap \\<circ> snd) (\\<alpha> s) = \n          map p_unwrap (map snd (\\<alpha> l)) @ (e,snd (p_unwrap lp)) #\n          map p_unwrap (map snd (\\<alpha> r))\"\n          using v4(1) True by simp\n        note map_of_distinct_lookup[OF v11]\n        hence\n          \"map_of (map (p_unwrap \\<circ> snd) (\\<alpha> s)) e = Some (snd (p_unwrap lp))\"\n          using v12 by simp\n        thus ?thesis\n          using T1 True l_lp_r\n          by (auto simp add: aluprio_defs)\n      qed\n    qed\n  qed\nqed\n        \n\nsubsubsection \"Pop\"\n\nlemma aluprio_pop_correct: \n  assumes \"al_splits \\<alpha> invar splits\"\n  \"al_annot \\<alpha> invar annot\"\n  \"al_app \\<alpha> invar app\"\n  shows \n  \"uprio_pop (aluprio_\\<alpha> \\<alpha>) (aluprio_invar \\<alpha> invar) (aluprio_pop splits annot app)\"\nproof -\n  interpret al_splits \\<alpha> invar splits by fact\n  interpret al_annot \\<alpha> invar annot by fact\n  interpret al_app \\<alpha> invar app by fact\n  show ?thesis \n  proof (unfold_locales)\n    fix s e a s'\n    assume A: \"aluprio_invar \\<alpha> invar s\" \n      \"aluprio_\\<alpha> \\<alpha> s \\<noteq> Map.empty\" \n      \"aluprio_pop splits annot app s = (e, a, s')\"\n    hence v1: \"\\<alpha> s \\<noteq> []\"\n      by (auto simp add: aluprio_defs)\n    obtain l lp r where\n      l_lp_r: \"splits (\\<lambda> x. x\\<le>annot s) Infty s = (l,((),lp),r)\"\n      by (cases \"splits (\\<lambda> x. x\\<le>annot s) Infty s\", auto)\n    have invs:\n      \"invar s\" \n      \"(\\<forall>x\\<in>set (\\<alpha> s). snd x \\<noteq> Infty)\"\n      \"sorted (map fst (map p_unwrap (map snd (\\<alpha> s))))\"\n      \"distinct (map fst (map p_unwrap (map snd (\\<alpha> s))))\"\n      using A by (auto simp add:aluprio_defs)\n    note a1 = annot_inf[of invar s \\<alpha> annot]\n    note a1[OF invs(1) invs(2) assms(2)]\n    hence v2: \"annot s \\<noteq> Infty\"\n      using v1 by simp\n    hence v3:\n      \"\\<not> Infty \\<le> annot s\"\n      by(cases \"annot s\") (auto simp add: plesseq_def)\n    have v4: \"annot s = sum_list (map snd (\\<alpha> s))\"\n      by (auto simp add: annot_correct invs(1))\n    hence \n      v5:\n      \"(Infty + sum_list (map snd (\\<alpha> s))) \\<le> annot s\"\n      by (auto simp add: plus_def)\n    note p_mon = p_less_eq_mon[of _ \"annot s\"]\n    note v6 = splits_correct[OF invs(1)]\n    note v7 = v6[of \"\\<lambda> x. x \\<le> annot s\"]\n    note v7[OF _ v3 v5 l_lp_r] p_mon\n    hence v8: \n      \" \\<alpha> s = \\<alpha> l @ ((), lp) # \\<alpha> r\"\n      \"\\<not> Infty + sum_list (map snd (\\<alpha> l)) \\<le> annot s\"\n      \"Infty + sum_list (map snd (\\<alpha> l)) + lp \\<le> annot s\"\n      \"invar l\"\n      \"invar r\"\n      by auto\n    hence v9: \"lp \\<noteq> Infty\"\n      using invs(2) by auto\n    hence v10: \n      \"s' = app l r\" \n      \"(e,a) = p_unwrap lp\"\n      using l_lp_r A(3)\n      apply (auto simp add: aluprio_defs)\n      apply (cases lp)\n      apply auto\n      apply (cases lp)\n      apply auto\n      done\n    have \"lp \\<le> annot s\"\n      using v8(2,3) p_less_eq_lem1\n      by auto\n    hence v11: \"a \\<le> snd (p_unwrap (annot s))\"\n      using v10(2) v2 v9\n      apply (cases \"annot s\")\n      apply auto\n      apply (cases lp)\n      apply (auto simp add: plesseq_def)\n      done \n    note sum_list_less_elems[OF invs(2)]\n    hence v12: \"\\<forall>y\\<in>set (map snd (map p_unwrap (map snd (\\<alpha> s)))). a \\<le> y\"\n      using v4 v11 by auto\n    have \"ran (aluprio_\\<alpha> \\<alpha> s) = set (map snd (map p_unwrap (map snd (\\<alpha> s))))\"\n      using ran_distinct[OF invs(4)]\n      apply (unfold aluprio_defs)\n      apply (simp only: set_map)\n      done\n    hence ziel1: \"\\<forall>y\\<in>ran (aluprio_\\<alpha> \\<alpha> s). a \\<le> y\"\n      using v12 by simp\n    have v13:\n      \"map p_unwrap (map snd (\\<alpha> s)) \n        = map p_unwrap (map  snd (\\<alpha> l)) @ (e,a) # map p_unwrap (map snd (\\<alpha> r))\"\n      using v8(1) v10 by auto\n     hence v14:\n      \"map fst (map p_unwrap (map snd (\\<alpha> s))) \n         = map fst (map p_unwrap (map snd (\\<alpha> l))) @ e \n             # map fst (map p_unwrap (map snd (\\<alpha> r)))\"\n       by auto\n    hence v15: \n      \"e \\<notin> set (map fst (map p_unwrap (map snd (\\<alpha> l))))\"\n      \"e \\<notin> set (map fst (map p_unwrap (map snd (\\<alpha> r))))\"\n      using invs(4) by auto\n    note map_of_distinct_lookup[OF v15]\n    note this[of a]\n    hence ziel2: \"aluprio_\\<alpha> \\<alpha> s e = Some a\"\n      using  v13\n      by (unfold aluprio_defs, auto)\n    have v16: \n      \"\\<alpha> s' = \\<alpha> l @ \\<alpha> r\" \n      \"invar s'\"\n      using v8(4,5) app_correct v10 by auto\n    note map_of_distinct_upd4[OF v15]\n    note this[of a]\n    hence \n      ziel3: \"aluprio_\\<alpha> \\<alpha> s' = (aluprio_\\<alpha> \\<alpha> s)(e := None)\"\n      unfolding aluprio_defs\n      using v16(1) v13 by auto\n    have ziel4: \"aluprio_invar \\<alpha> invar s'\"\n      using v16 v8(1) invs(2,3,4)\n      unfolding aluprio_defs\n      by (auto simp add: sorted_append)\n    \n    show \"aluprio_invar \\<alpha> invar s' \\<and>\n          aluprio_\\<alpha> \\<alpha> s' = (aluprio_\\<alpha> \\<alpha> s)(e := None) \\<and>\n          aluprio_\\<alpha> \\<alpha> s e = Some a \\<and> (\\<forall>y\\<in>ran (aluprio_\\<alpha> \\<alpha> s). a \\<le> y)\"\n      using ziel1 ziel2 ziel3 ziel4 by simp\n  qed\nqed\n    \nlemmas aluprio_correct =\n  aluprio_finite_correct\n  aluprio_empty_correct\n  aluprio_isEmpty_correct\n  aluprio_insert_correct\n  aluprio_pop_correct\n  aluprio_prio_correct\n\nlocale aluprio_defs = StdALDefs ops \n  for ops :: \"(unit,('e::linorder,'a::linorder) LP,'s) alist_ops\"\nbegin\n  definition [icf_rec_def]: \"aluprio_ops \\<equiv> \\<lparr>\n    upr_\\<alpha> = aluprio_\\<alpha> \\<alpha>,\n    upr_invar = aluprio_invar \\<alpha> invar,\n    upr_empty = aluprio_empty empty,\n    upr_isEmpty = aluprio_isEmpty isEmpty,\n    upr_insert = aluprio_insert splits annot isEmpty app consr,\n    upr_pop = aluprio_pop splits annot app,\n    upr_prio = aluprio_prio splits annot isEmpty\n    \\<rparr>\"\n  \nend\n\nlocale aluprio = aluprio_defs ops + StdAL ops \n  for ops :: \"(unit,('e::linorder,'a::linorder) LP,'s) alist_ops\"\nbegin\n  lemma aluprio_ops_impl: \"StdUprio aluprio_ops\"\n    apply (rule StdUprio.intro)\n    apply (simp_all add: icf_rec_unf)\n    apply (rule aluprio_correct)\n    apply (rule aluprio_correct, unfold_locales) []\n    apply (rule aluprio_correct, unfold_locales) []\n    apply (rule aluprio_correct, unfold_locales) []\n    apply (rule aluprio_correct, unfold_locales) []\n    apply (rule aluprio_correct, unfold_locales) []\n    done\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/Collections/ICF/gen_algo/PrioUniqueByAnnotatedList.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8824278757303677, "lm_q2_score": 0.8289388146603365, "lm_q1q2_score": 0.7314787173311698}}
{"text": "(*\n  File:     Residues_Nat.thy\n  Authors:  Daniel St\u00fcwe, Manuel Eberl\n\n  The multiplicative group of the ring of residues modulo n.\n*)\nsection \\<open>Residue Rings of Natural Numbers\\<close>\ntheory Residues_Nat\n  imports Algebraic_Auxiliaries\nbegin            \n\nsubsection \\<open>The multiplicative group of residues modulo \\<open>n\\<close>\\<close>\n\ndefinition Residues_Mult :: \"'a :: {linordered_semidom, euclidean_semiring} \\<Rightarrow> 'a monoid\" where\n  \"Residues_Mult p =\n     \\<lparr>carrier = {x \\<in> {1..p} . coprime x p}, monoid.mult = \\<lambda>x y. x * y mod p, one = 1\\<rparr>\"\n\nlocale residues_mult_nat =\n  fixes n :: nat and G\n  assumes n_gt_1: \"n > 1\"\n  defines \"G \\<equiv> Residues_Mult n\"\nbegin\n\nlemma carrier_eq [simp]: \"carrier G = totatives n\"\n  and mult_eq [simp]:    \"(x \\<otimes>\\<^bsub>G\\<^esub> y) = (x * y) mod n\"\n  and one_eq [simp]:     \"\\<one>\\<^bsub>G\\<^esub> = 1\"\n  by (auto simp: G_def Residues_Mult_def totatives_def)\n\nlemma mult_eq': \"(\\<otimes>\\<^bsub>G\\<^esub>) = (\\<lambda>x y. (x * y) mod n)\"\n  by (intro ext; simp)+\n\nsublocale group G\nproof(rule groupI, goal_cases)\n  case (1 x y)\n  from 1 show ?case using n_gt_1\n    by (auto intro!: Nat.gr0I simp: coprime_commute coprime_dvd_mult_left_iff\n                                    coprime_absorb_left nat_dvd_not_less totatives_def)\nnext\n  case (5 x)\n  hence \"(\\<exists>y. y \\<ge> 0 \\<and> y < n \\<and> [x * y = Suc 0] (mod n))\"\n    using coprime_iff_invertible'_nat[of n x] n_gt_1\n    by (auto simp: totatives_def)\n  then obtain y where y: \"y \\<ge> 0\" \"y < n\" \"[x * y = Suc 0] (mod n)\" by blast\n\n  from \\<open>[x * y = Suc 0] (mod n)\\<close> have \"gcd (x * y) n = 1\"\n    by (simp add: cong_gcd_eq)\n  hence \"coprime y n\" by fastforce\n\n  with y n_gt_1 show \"\\<exists>y\\<in>carrier G. y \\<otimes>\\<^bsub>G\\<^esub> x = \\<one>\\<^bsub>G\\<^esub>\"\n    by (intro bexI[of _ y]) (auto simp: totatives_def cong_def mult_ac intro!: Nat.gr0I)\nqed (use n_gt_1 in \\<open>auto simp: mod_simps algebra_simps totatives_less\\<close>)\n\nsublocale comm_group\n  by unfold_locales (auto simp: mult_ac)\n\nlemma nat_pow_eq [simp]: \"x [^]\\<^bsub>G\\<^esub> (k :: nat) = (x ^ k) mod n\"\n  using n_gt_1 by (induction k) (simp_all add: mod_mult_left_eq mod_mult_right_eq mult_ac)\n\nlemma nat_pow_eq': \"([^]\\<^bsub>G\\<^esub>) = (\\<lambda>x k. (x ^ k) mod n)\"\n  by (intro ext) simp\n\nlemma order_eq: \"order G = totient n\"\n  by (simp add: order_def totient_def)\n\nlemma order_less: \"\\<not>prime n \\<Longrightarrow> order G < n - 1\"\n  using totient_less_not_prime[of n] n_gt_1\n  by (auto simp: order_eq)\n\nlemma ord_residue_mult_group:\n  assumes \"a \\<in> totatives n\"\n  shows   \"local.ord a = Pocklington.ord n a\"\nproof (rule dvd_antisym)\n  have \"[a ^ local.ord a = 1] (mod n)\"\n    using pow_ord_eq_1[of a] assms by (auto simp: cong_def)\n  thus \"Pocklington.ord n a dvd local.ord a\"\n    by (subst (asm) ord_divides)\nnext\n  show \"local.ord a dvd Pocklington.ord n a\"\n    using assms Pocklington.ord[of a n] n_gt_1 pow_eq_id by (simp add: cong_def)\nqed\n\nend\n\n\nsubsection \\<open>The ring of residues modulo \\<open>n\\<close>\\<close>\n\ndefinition Residues_nat :: \"nat \\<Rightarrow> nat ring\" where\n  \"Residues_nat m = \\<lparr>carrier = {0..<m}, monoid.mult = \\<lambda>x y. (x * y) mod m, one = 1,\n                     ring.zero = 0, add = \\<lambda>x y. (x + y) mod m\\<rparr>\"\n\nlocale residues_nat =\n  fixes n :: nat and R\n  assumes n_gt_1: \"n > 1\"\n  defines \"R \\<equiv> Residues_nat n\"\nbegin\n\nlemma carrier_eq [simp]: \"carrier R = {0..<n}\"\n  and mult_eq [simp]: \"x \\<otimes>\\<^bsub>R\\<^esub> y = (x * y) mod n\"\n  and add_eq [simp]: \"x \\<oplus>\\<^bsub>R\\<^esub> y = (x + y) mod n\"\n  and one_eq [simp]: \"\\<one>\\<^bsub>R\\<^esub> = 1\"\n  and zero_eq [simp]: \"\\<zero>\\<^bsub>R\\<^esub> = 0\"\n  by (simp_all add: Residues_nat_def R_def)\n\nlemma mult_eq': \"(\\<otimes>\\<^bsub>R\\<^esub>) = (\\<lambda>x y. (x * y) mod n)\"\n  and add_eq': \"(\\<oplus>\\<^bsub>R\\<^esub>) = (\\<lambda>x y. (x + y) mod n)\"\n  by (intro ext; simp)+\n\nsublocale abelian_group R\nproof(rule abelian_groupI, goal_cases)\n  case (1 x y)\n  then show ?case\n    using n_gt_1\n    by (auto simp: mod_simps algebra_simps simp flip: less_Suc_eq_le)\nnext\n  case (6 x)\n  { assume \"x < n\" \"1 < n\"\n    hence \"n - x \\<in> {0..<n}\" \"((n - x) + x) mod n = 0\" if \"x \\<noteq> 0\"\n      using that by auto\n    moreover have \"0 \\<in> {0..<n}\" \"(0 + x) mod n = 0\" if \"x = 0\"\n      using that n_gt_1 by auto\n    ultimately have \"\\<exists>y\\<in>{0..<n}. (y + x) mod n = 0\"\n      by meson\n  }\n\n  with 6 show ?case using n_gt_1 by auto\nqed (use n_gt_1 in \\<open>auto simp add: mod_simps algebra_simps\\<close>)\n\nsublocale comm_monoid R\n  using n_gt_1 by unfold_locales (auto simp: mult_ac mod_simps)\n\nsublocale cring R\n  by unfold_locales (auto simp: mod_simps algebra_simps)\n\nlemma Units_eq: \"Units R = totatives n\"\nproof safe\n  fix x assume x: \"x \\<in> Units R\"\n  then obtain y where y: \"[x * y = 1] (mod n)\"\n    using n_gt_1 by (auto simp: Units_def cong_def)\n  hence \"coprime x n\"\n    using cong_imp_coprime cong_sym coprime_1_left coprime_mult_left_iff by metis\n  with x show \"x \\<in> totatives n\" by (auto simp: totatives_def Units_def intro!: Nat.gr0I)\nnext\n  fix x assume x: \"x \\<in> totatives n\"\n  then obtain y where \"y < n\" \"[x * y = 1] (mod n)\"\n    using coprime_iff_invertible'_nat[of n x] by (auto simp: totatives_def)\n  with x show \"x \\<in> Units R\"\n    using n_gt_1 by (auto simp: Units_def mult_ac cong_def totatives_less)\nqed\n\nsublocale units: residues_mult_nat n \"units_of R\"\nproof unfold_locales\n  show \"units_of R \\<equiv> Residues_Mult n\"\n    by (auto simp: units_of_def Units_eq Residues_Mult_def totatives_def Suc_le_eq mult_eq')\nqed (use n_gt_1 in auto) \n\nlemma nat_pow_eq [simp]: \"x [^]\\<^bsub>R\\<^esub> (k :: nat) = (x ^ k) mod n\"\n  using n_gt_1 by (induction k) (auto simp: mod_simps mult_ac)\n\nlemma nat_pow_eq': \"([^]\\<^bsub>R\\<^esub>) = (\\<lambda>x k. (x ^ k) mod n)\"\n  by (intro ext) simp\n\nend\n\n\nsubsection \\<open>The ring of residues modulo a prime\\<close>\n\nlocale residues_nat_prime =\n  fixes p :: nat and R\n  assumes prime_p: \"prime p\"\n  defines \"R \\<equiv> Residues_nat p\"\nbegin\n\nsublocale residues_nat p R\n  using prime_gt_1_nat[OF prime_p] by unfold_locales (auto simp: R_def)\n\nlemma carrier_eq' [simp]: \"totatives p = {0<..<p}\"\n  using prime_p by (auto simp: totatives_prime)\n\nlemma order_eq: \"order (units_of R) = p - 1\"\n  using prime_p by (simp add: units.order_eq totient_prime)\n\nlemma order_eq' [simp]: \"totient p = p - 1\"\n  using prime_p by (auto simp: totient_prime)\n\nsublocale field R\nproof (rule cring_fieldI)\n  show \"Units R = carrier R - {\\<zero>\\<^bsub>R\\<^esub>}\"\n    by (subst Units_eq) (use prime_p in \\<open>auto simp: totatives_prime\\<close>)\nqed\n\nlemma residues_prime_cyclic: \"\\<exists>x\\<in>{0<..<p}. {0<..<p} = {y. \\<exists>i. y = x ^ i mod p}\"\nproof -\n  from n_gt_1 have \"{0..<p} - {0} = {0<..<p}\" by auto\n  thus ?thesis using finite_field_mult_group_has_gen by simp\nqed\n\nlemma residues_prime_cyclic': \"\\<exists>x\\<in>{0<..<p}. units.ord x = p - 1\"\nproof -\n  from residues_prime_cyclic obtain x\n    where x: \"x \\<in> {0<..<p}\" \"{0<..<p} = {y. \\<exists>i. y = x ^ i mod p}\" by metis\n  have \"units.ord x = p - 1\"\n  proof (intro antisym)\n    show \"units.ord x \\<le> p - 1\"\n      using units.ord_dvd_group_order[of x] x(1) by (auto simp: units.order_eq intro!: dvd_imp_le)\n  next\n    (* TODO FIXME: a bit ugly; could be simplified if we had a theory of finite cyclic rings *)\n    have \"p - 1 = card {0<..<p}\" by simp\n    also have \"{0<..<p} = {y. \\<exists>i. y = x ^ i mod p}\" by fact\n    also have \"card \\<dots> \\<le> card ((\\<lambda>i. x ^ i mod p) ` {..<units.ord x})\"\n    proof (intro card_mono; safe?)\n      fix j :: nat\n      have \"j = units.ord x * (j div units.ord x) + (j mod units.ord x)\"\n        by simp\n      also have \"x [^]\\<^bsub>units_of R\\<^esub> \\<dots> = x [^]\\<^bsub>units_of R\\<^esub> (units.ord x * (j div units.ord x))\n                   \\<otimes>\\<^bsub>units_of R\\<^esub> x [^]\\<^bsub>units_of R\\<^esub> (j mod units.ord x)\"\n        using x by (subst units.nat_pow_mult) auto\n      also have \"x [^]\\<^bsub>units_of R\\<^esub> (units.ord x * (j div units.ord x)) =\n                   (x [^]\\<^bsub>units_of R\\<^esub> units.ord x) [^]\\<^bsub>units_of R\\<^esub> (j div units.ord x)\"\n        using x by (subst units.nat_pow_pow) auto\n      also have \"x [^]\\<^bsub>units_of R\\<^esub> units.ord x = 1\"\n        using x(1) by (subst units.pow_ord_eq_1) auto\n      finally have \"x ^ j mod p = x ^ (j mod units.ord x) mod p\" using n_gt_1 by simp\n      thus \"x ^ j mod p \\<in> (\\<lambda>i. x ^ i mod p) ` {..<units.ord x}\"\n        using units.ord_ge_1[of x] x(1) by force\n    qed auto\n    also have \"\\<dots> \\<le> card {..<units.ord x}\"\n      by (intro card_image_le) auto\n    also have \"\\<dots> = units.ord x\" by simp\n    finally show \"p - 1 \\<le> units.ord x\" .\n  qed\n  with x show ?thesis by metis\nqed\n\nend\n\n\nsubsection \\<open>\\<open>-1\\<close> in residue rings\\<close>\n\nlemma minus_one_cong_solve_weak:\n  fixes n x :: nat\n  assumes \"1 < n\" \"x \\<in> totatives n\" \"y \\<in> totatives n\"\n    and  \"[x = n - 1] (mod n)\" \"[x * y = 1] (mod n)\"\n  shows \"y = n - 1\"\nproof -\n  define G where \"G = Residues_Mult n\"\n  interpret residues_mult_nat n G\n    by unfold_locales (use \\<open>n > 1\\<close> in \\<open>simp_all add: G_def\\<close>)\n  have \"[x * (n - 1) = x * n - x] (mod n)\"\n    by (simp add: algebra_simps)\n  also have \"[x * n - x = (n - 1) * n - (n - 1)] (mod n)\"\n    using assms by (intro cong_diff_nat cong_mult) auto\n  also have \"(n - 1) * n - (n - 1) = (n - 1) ^ 2\"\n    by (simp add: power2_eq_square algebra_simps)\n  also have \"[(n - 1)\\<^sup>2 = 1] (mod n)\"\n    using assms by (intro square_minus_one_cong_one) auto\n  finally have \"x * (n - 1) mod n = 1\"\n    using \\<open>n > 1\\<close> by (simp add: cong_def)\n  hence \"y = n - 1\" \n    using inv_unique'[of x \"n - 1\"] inv_unique'[of x y] minus_one_in_totatives[of n] assms(1-3,5)\n    by (simp_all add: mult_ac cong_def)\n  then show ?thesis by simp\nqed\n\nlemma coprime_imp_mod_not_zero:\n  fixes n x :: nat\n  assumes \"1 < n\" \"coprime x n\"\n  shows \"0 < x mod n\"\n  using assms coprime_0_left_iff nat_dvd_not_less by fastforce\n\nlemma minus_one_cong_solve:\n  fixes n x :: nat\n  assumes \"1 < n\"\n    and eq: \"[x = n - 1] (mod n)\" \"[x * y = 1] (mod n)\"\n    and coprime: \"coprime x n\" \"coprime y n\"\n  shows \"[y = n - 1](mod n)\"\nproof -\n  have \"0 < x mod n\" \"0 < y mod n\"\n    using coprime coprime_imp_mod_not_zero \\<open>1 < n\\<close> by blast+\n  moreover have \"x mod n < n\" \"y mod n < n\"\n    using \\<open>1 < n\\<close> by auto\n  moreover have \"[x mod n = n - 1] (mod n)\" \"[x mod n * (y mod n) = 1] (mod n)\"\n    using eq by auto\n  moreover have \"coprime (x mod n) n\" \"coprime (y mod n) n\"\n    using coprime coprime_mod_left_iff \\<open>1 < n\\<close> by auto\n  ultimately have \"[y mod n = n - 1] (mod n)\"\n    using minus_one_cong_solve_weak[OF \\<open>1 < n\\<close>, of \"x mod n\" \"y mod n\"]\n    by (auto simp: totatives_def)\n  then show ?thesis by simp\nqed\n\ncorollary square_minus_one_cong_one':\n  fixes n x :: nat\n  assumes \"1 < n\"\n  shows \"[(n - 1) * (n - 1) = 1](mod n)\"\n  using square_minus_one_cong_one[OF assms, of \"n - 1\"] assms\n  by (fastforce simp: power2_eq_square)\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/Probabilistic_Prime_Tests/Residues_Nat.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.88242786954645, "lm_q2_score": 0.8289388125473628, "lm_q1q2_score": 0.7314787103405335}}
{"text": "(*  Title:      HOL/Hahn_Banach/Normed_Space.thy\n    Author:     Gertrud Bauer, TU Munich\n*)\n\nsection \\<open>Normed vector spaces\\<close>\n\ntheory Normed_Space\nimports Subspace\nbegin\n\nsubsection \\<open>Quasinorms\\<close>\n\ntext \\<open>\n  A \\<^emph>\\<open>seminorm\\<close> \\<open>\\<parallel>\\<cdot>\\<parallel>\\<close> is a function on a real vector space into the reals that\n  has the following properties: it is positive definite, absolute homogeneous\n  and subadditive.\n\\<close>\n\nlocale seminorm =\n  fixes V :: \"'a::{minus, plus, zero, uminus} set\"\n  fixes norm :: \"'a \\<Rightarrow> real\"    (\"\\<parallel>_\\<parallel>\")\n  assumes ge_zero [iff?]: \"x \\<in> V \\<Longrightarrow> 0 \\<le> \\<parallel>x\\<parallel>\"\n    and abs_homogenous [iff?]: \"x \\<in> V \\<Longrightarrow> \\<parallel>a \\<cdot> x\\<parallel> = \\<bar>a\\<bar> * \\<parallel>x\\<parallel>\"\n    and subadditive [iff?]: \"x \\<in> V \\<Longrightarrow> y \\<in> V \\<Longrightarrow> \\<parallel>x + y\\<parallel> \\<le> \\<parallel>x\\<parallel> + \\<parallel>y\\<parallel>\"\n\ndeclare seminorm.intro [intro?]\n\nlemma (in seminorm) diff_subadditive:\n  assumes \"vectorspace V\"\n  shows \"x \\<in> V \\<Longrightarrow> y \\<in> V \\<Longrightarrow> \\<parallel>x - y\\<parallel> \\<le> \\<parallel>x\\<parallel> + \\<parallel>y\\<parallel>\"\nproof -\n  interpret vectorspace V by fact\n  assume x: \"x \\<in> V\" and y: \"y \\<in> V\"\n  then have \"x - y = x + - 1 \\<cdot> y\"\n    by (simp add: diff_eq2 negate_eq2a)\n  also from x y have \"\\<parallel>\\<dots>\\<parallel> \\<le> \\<parallel>x\\<parallel> + \\<parallel>- 1 \\<cdot> y\\<parallel>\"\n    by (simp add: subadditive)\n  also from y have \"\\<parallel>- 1 \\<cdot> y\\<parallel> = \\<bar>- 1\\<bar> * \\<parallel>y\\<parallel>\"\n    by (rule abs_homogenous)\n  also have \"\\<dots> = \\<parallel>y\\<parallel>\" by simp\n  finally show ?thesis .\nqed\n\nlemma (in seminorm) minus:\n  assumes \"vectorspace V\"\n  shows \"x \\<in> V \\<Longrightarrow> \\<parallel>- x\\<parallel> = \\<parallel>x\\<parallel>\"\nproof -\n  interpret vectorspace V by fact\n  assume x: \"x \\<in> V\"\n  then have \"- x = - 1 \\<cdot> x\" by (simp only: negate_eq1)\n  also from x have \"\\<parallel>\\<dots>\\<parallel> = \\<bar>- 1\\<bar> * \\<parallel>x\\<parallel>\" by (rule abs_homogenous)\n  also have \"\\<dots> = \\<parallel>x\\<parallel>\" by simp\n  finally show ?thesis .\nqed\n\n\nsubsection \\<open>Norms\\<close>\n\ntext \\<open>\n  A \\<^emph>\\<open>norm\\<close> \\<open>\\<parallel>\\<cdot>\\<parallel>\\<close> is a seminorm that maps only the \\<open>0\\<close> vector to \\<open>0\\<close>.\n\\<close>\n\nlocale norm = seminorm +\n  assumes zero_iff [iff]: \"x \\<in> V \\<Longrightarrow> (\\<parallel>x\\<parallel> = 0) = (x = 0)\"\n\n\nsubsection \\<open>Normed vector spaces\\<close>\n\ntext \\<open>\n  A vector space together with a norm is called a \\<^emph>\\<open>normed space\\<close>.\n\\<close>\n\nlocale normed_vectorspace = vectorspace + norm\n\ndeclare normed_vectorspace.intro [intro?]\n\nlemma (in normed_vectorspace) gt_zero [intro?]:\n  assumes x: \"x \\<in> V\" and neq: \"x \\<noteq> 0\"\n  shows \"0 < \\<parallel>x\\<parallel>\"\nproof -\n  from x have \"0 \\<le> \\<parallel>x\\<parallel>\" ..\n  also have \"0 \\<noteq> \\<parallel>x\\<parallel>\"\n  proof\n    assume \"0 = \\<parallel>x\\<parallel>\"\n    with x have \"x = 0\" by simp\n    with neq show False by contradiction\n  qed\n  finally show ?thesis .\nqed\n\ntext \\<open>\n  Any subspace of a normed vector space is again a normed vectorspace.\n\\<close>\n\nlemma subspace_normed_vs [intro?]:\n  fixes F E norm\n  assumes \"subspace F E\" \"normed_vectorspace E norm\"\n  shows \"normed_vectorspace F norm\"\nproof -\n  interpret subspace F E by fact\n  interpret normed_vectorspace E norm by fact\n  show ?thesis\n  proof\n    show \"vectorspace F\" by (rule vectorspace) unfold_locales\n  next\n    have \"Normed_Space.norm E norm\" ..\n    with subset show \"Normed_Space.norm F norm\"\n      by (simp add: norm_def seminorm_def norm_axioms_def)\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/Hahn_Banach/Normed_Space.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278664544912, "lm_q2_score": 0.8289388083214156, "lm_q1q2_score": 0.7314787040483952}}
{"text": "theory neighborRelation\n  imports Main\nbegin\n\ntext {* Idea of edge list representation taken from Nishihara and Minamide's paper:\n      https://www.isa-afp.org/browser_info/current/AFP/Depth-First-Search/document.pdf *}\n\ntype_synonym node = int \ntype_synonym graph = \"(node * node) list\"\n\ndefinition isReachable :: \"[graph, node, node] \u21d2 bool\"\n  where \"isReachable g a b = (if a = b \u2228 ((a, b) \u2208 set g \u2227 (b, a) \u2208 set g) then True else False)\"\n\ntheorem neighbor_reflexive:\n  fixes a :: node\n  fixes g :: graph\n  shows \"isReachable g a a\" \n  by (metis isReachable_def)\n\ntheorem neighbor_symmetric:\n  fixes a b :: node\n  fixes g :: graph\n  assumes \"isReachable g a b\"\n  shows \"isReachable g b a\"\n    by (metis assms isReachable_def)\n\ntheorem neighbor_not_transitive:\n  shows \"\u2203 (g :: graph) (a :: node) (b :: node) (c :: node). isReachable g a b \u2227 isReachable g b c \u2227 \u00acisReachable g a c\"\nproof -\n  obtain a b c :: node where unique: \"a \u2260 b \u2227 b \u2260 c \u2227 a \u2260 c\"\n  proof -\n    assume a1: \"\u22c0a b c. (a::int) \u2260 b \u2227 b \u2260 c \u2227 a \u2260 c \u27f9 thesis\"\n    have f2: \"(0::int) \u2260 2\"\n      by auto\n    have f3: \"(1::int) \u2260 2\"\n      by auto\n    have \"(0::int) \u2260 1\"\n      by auto\n    then show ?thesis\n      using f3 f2 a1 by blast\n  qed\n  obtain g :: graph where G: \"g = (a, b) # (b, a) # (b, c) # (c, b) # []\" by auto\n  \n  have \"(a, b) \u2208 set g\" and baInG: \"(b, a) \u2208 set g\" using G by auto\n  hence ab: \"isReachable g a b\" using isReachable_def by metis\n\n  have \"(b, c) \u2208 set g\" and cbInG: \"(c, b) \u2208 set g\" using G by auto\n  hence bc: \"isReachable g b c\" using isReachable_def by metis\n\n  have ac: \"\u00ac isReachable g a c\" \n  proof-\n    from G have \"g = (a, b) # (b, a) # (b, c) # (c, b) # []\" by auto\n    then have \"set g = {(a, b), (b, a), (b, c), (c, b)}\" by auto\n    then have \"(a, c) \u2209 set g\" using unique by auto\n    thus ?thesis using isReachable_def unique by auto\n  qed\n\n  show ?thesis using ab ac bc by auto\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/neighborRelation.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278602705731, "lm_q2_score": 0.8289388125473628, "lm_q1q2_score": 0.731478702651399}}
{"text": "chapter \"Orbit-Stabiliser Theorem\"\ntext \\<open>\nIn this Theory we will prove the orbit-stabiliser theorem, a basic result in the algebra of groups.\n\n\\<close>\n\ntheory Orbit_Stabiliser\n  imports\n    \"HOL-Algebra.Left_Coset\"\n\nbegin\n\nsection \"Imports\"\ntext \\<open>\n  /HOL/Algebra/Group.thy is used for the definitions of groups and subgroups\n\\<close>\n\ntext \\<open>\n  Left\\_Coset.thy is a copy of /HOL/Algebra/Coset.thy that includes additional theorems about left cosets.\n\n  The version of Coset.thy in the Isabelle library is missing some theorems about left cosets\n  that are available for right cosets, so these had to be added by simply replacing the definitions\n  of right cosets with those of left cosets.\n\n  Coset.thy is used for definitions of group order, quotient groups (operator LMod), and Lagranges theorem.\n\\<close>\n\ntext \\<open>\n  /HOL/Fun.thy is used for function composition and the identity function.\n\\<close>\n\n\nsection \"Group Actions\"\n\ntext \\<open>\n  We begin by augmenting the existing definition of a group with a group action.\n\n  The group action was defined according to \\<^cite>\\<open>groupaction\\<close>.\n\\<close>\n\nlocale orbit_stabiliser = group +\n  fixes action :: \"'a \\<Rightarrow> 'b \\<Rightarrow> 'b\" (infixl \"\\<odot>\" 51)\n  assumes id_act [simp]: \"\\<one> \\<odot> x = x\"\n    and compat_act:\n    \"g \\<in> carrier G \\<and> h \\<in> carrier G \\<longrightarrow> g \\<odot> (h \\<odot> x) = (g \\<otimes> h) \\<odot> x\"\n\nsection \"Orbit and stabiliser\"\n\ntext \\<open>\nNext, we define orbit and stabiliser, according to the same Wikipedia article.\n\\<close>\n\ncontext orbit_stabiliser\nbegin\n\ndefinition orbit :: \"'b \\<Rightarrow> 'b set\" where\n  \"orbit x = {y. (\\<exists> g \\<in> carrier G. y = g \\<odot> x)}\"\n\ndefinition stabiliser :: \"'b \\<Rightarrow> 'a set\"\n  where \"stabiliser x = {g \\<in> carrier G. g \\<odot> x = x}\"\n\n\nsection \"Stabiliser Theorems\"\n\ntext \\<open>\nWe begin our proofs by showing that the stabiliser forms a subgroup.\n\nThis proof follows the template from  \\<^cite>\\<open>stabsub\\<close>.\n\\<close>\n\ntheorem stabiliser_subgroup: \"subgroup (stabiliser x) G\"\nproof(rule subgroupI)\n  show \"stabiliser x \\<subseteq> carrier G\" using stabiliser_def by auto\nnext\n  fix x\n  from id_act have \"\\<one> \\<odot> x = x\" by simp\n  then have \"\\<one> \\<in> stabiliser x\" using stabiliser_def by auto\n  then show \"stabiliser x \\<noteq> {}\" by auto\nnext\n  fix g x\n  assume gStab:\"g \\<in> stabiliser x\"\n  then have g_car:\"g \\<in> carrier G\" using stabiliser_def by simp\n  then have invg_car:\"inv g \\<in> carrier G\" using inv_closed by simp\n  have \"g \\<odot> x = x\" using stabiliser_def gStab by simp\n  then have \"inv g \\<odot> (g \\<odot> x) = inv g \\<odot> x\" by simp\n  then have \"(inv g \\<otimes> g) \\<odot> x = inv g \\<odot> x\" using compat_act g_car invg_car by simp\n  then have \"x = (inv g) \\<odot> x\" using g_car l_inv by simp\n  then show \"inv g \\<in> stabiliser x\" using invg_car stabiliser_def by simp\nnext\n  fix g h x\n  assume g_stab: \"g \\<in> stabiliser x\" and h_stab: \"h \\<in> stabiliser x\"\n  then have g_car: \"g \\<in> carrier G\" and h_car: \"h \\<in> carrier G\" using stabiliser_def by auto\n  then have \"g \\<odot> x = x\" \"h \\<odot> x = x\"\n    using stabiliser_def g_stab h_stab by auto\n  then have \"g \\<odot> (h \\<odot> x) = x\" by simp\n  then have \"(g \\<otimes> h) \\<odot> x = x\" using compat_act g_car h_car by simp\n  then show \"(g \\<otimes> h) \\<in> stabiliser x\"\n    using g_stab h_stab stabiliser_def by auto\nqed\n\ntext \\<open>\nAs an intermediate step we formulate a lemma about the relationship between the group action\nand the stabiliser.\n\nThis proof follows the template from \\<^cite>\\<open>stabsubcor\\<close>.\n\\<close>\n\ncorollary stabiliser_subgroup_corollary:\n  assumes g_car: \"g \\<in> carrier G\" and\n    h_car: \"h \\<in> carrier G\"\n  shows \"(g \\<odot> x) = (h \\<odot> x) \\<longleftrightarrow> ((inv g) \\<otimes> h) \\<in> stabiliser x\"\nproof\n  from g_car have invg_car: \"(inv g) \\<in> carrier G\" by auto\n  show \"(g \\<odot> x) = (h \\<odot> x) \\<Longrightarrow> inv g \\<otimes> h \\<in> stabiliser x\"\n  proof -\n    assume gh: \"(g \\<odot> x) = (h \\<odot> x)\"\n    have \"((inv g) \\<otimes> h) \\<odot> x = (inv g) \\<odot> (h \\<odot> x)\" using assms compat_act by simp\n    moreover have \"(inv g) \\<odot> (h \\<odot> x) = (inv g) \\<odot> (g \\<odot> x)\" using gh by simp\n    moreover have \"(inv g) \\<odot> (g \\<odot> x) = ((inv g) \\<otimes> g) \\<odot> x\" using invg_car g_car compat_act by simp\n    moreover have \"((inv g) \\<otimes> g) \\<odot> x = x\" using g_car by simp\n    ultimately have \"((inv g) \\<otimes> h) \\<odot> x = x\" by simp\n    then show ?thesis using stabiliser_def assms by simp\n  qed\n\n  show \"inv g \\<otimes> h \\<in> stabiliser x \\<Longrightarrow> g \\<odot> x = h \\<odot> x\"\n  proof -\n    assume gh_stab: \"inv g \\<otimes> h \\<in> stabiliser x\"\n    with stabiliser_def have \"x = ((inv g) \\<otimes> h) \\<odot> x\" by simp\n    then have \"\\<one> \\<odot> x = ((inv g) \\<otimes> h) \\<odot> x\"  by simp\n    then have \"((inv g) \\<otimes> g) \\<odot> x = ((inv g) \\<otimes> h) \\<odot> x\" using invg_car g_car by simp\n    then have \"x = (inv g) \\<odot> (h \\<odot> x)\" using compat_act g_car h_car by simp\n    then have \"g \\<odot> x = (g \\<otimes> (inv g)) \\<odot> (h \\<odot> x)\" using compat_act g_car invg_car by metis\n    then have \"g \\<odot> x = h \\<odot> x\" using compat_act g_car id_act invg_car r_inv by simp\n    then show ?thesis by simp\n  qed\nqed\n\ntext \\<open>\nUsing the previous lemma and our proof that the stabiliser forms a subgroup, we can now\nshow that the elements of the orbit map to left cosets of the stabiliser.\n\nThis will later form the basis of showing a bijection between the orbit and those cosets.\n\\<close>\n\nlemma stabiliser_cosets_equivalent:\n  assumes g_car: \"g \\<in> carrier G\" and\n    h_car: \"h \\<in> carrier G\"\n  shows \"(g \\<odot> x) = (h \\<odot> x) \\<longleftrightarrow> (g <# stabiliser x) = (h <# stabiliser x)\"\nproof\n  show \"g \\<odot> x = h \\<odot> x \\<Longrightarrow> g <# stabiliser x = h <# stabiliser x\"\n  proof -\n    assume \"g \\<odot> x = h \\<odot> x\"\n    then have stab_elem: \"((inv g) \\<otimes> h) \\<in> stabiliser x\"\n      using assms stabiliser_subgroup_corollary by simp\n    with subgroup.lcos_module_rev[OF stabiliser_subgroup] have \"h \\<in> g <# (stabiliser x)\"\n      using assms is_group by simp\n    with l_repr_independence have  \"g <# (stabiliser x) = h <# (stabiliser x)\"\n      using assms  stab_elem stabiliser_subgroup by auto\n    then show ?thesis by simp\n  qed\n  show \"g <# stabiliser x = h <# stabiliser x \\<Longrightarrow> g \\<odot> x = h \\<odot> x\"\n  proof -\n    assume \"g <# stabiliser x = h <# stabiliser x\"\n    with subgroup.lcos_module_rev[OF stabiliser_subgroup] have \"h \\<in> g <# (stabiliser x)\"\n      using assms is_group l_inv stabiliser_subgroup subgroup_def by metis\n    with subgroup.lcos_module_imp[OF stabiliser_subgroup] have \"((inv g) \\<otimes> h) \\<in> stabiliser x\"\n      using assms is_group by blast\n    with stabiliser_subgroup_corollary have \"g \\<odot> x = h \\<odot> x\" using assms by simp\n    then show ?thesis by simp\n  qed\nqed\n\nsection \"Picking representatives from cosets\"\n\ntext \\<open>\nBefore we can prove the bijection, we need a few lemmas about representatives from sets.\n\nFirst we define rep to be an arbitrary element from a left coset of the stabiliser.\n\\<close>\ndefinition rep :: \"'a set \\<Rightarrow> 'a\" where\n  \"(H \\<in> carrier (G LMod (stabiliser x))) \\<Longrightarrow> rep H = (SOME y. y \\<in> H)\"\n\ntext \\<open>\n  The next lemma shows that the representative is always an element of its coset.\n\\<close>\nlemma quotient_rep_ex  : \"H \\<in> (carrier (G LMod (stabiliser x))) \\<Longrightarrow> rep H \\<in> H\"\nproof -\n  fix H\n  assume H:\"H \\<in> carrier (G LMod stabiliser x)\"\n  then obtain g where \"g \\<in> carrier G\" \"H = g <# (stabiliser x)\"\n    unfolding LFactGroup_def LCOSETS_def by auto\n  then have \"(SOME x. x \\<in> H) \\<in> H\" using lcos_self stabiliser_subgroup someI_ex by fast\n  then show \"rep H \\<in> H\" using H rep_def by auto\nqed\n\ntext \\<open>\nThe final lemma about representatives shows that it does not matter which element of the coset\nis picked, i.e. all representatives are equivalent.\n\\<close>\nlemma rep_equivalent:\n  assumes H:\"H \\<in> carrier (G LMod stabiliser x)\" and\n    gH:\"g \\<in> H\"\n  shows \"H = g <# (stabiliser x)\"\nproof -\n  fix h\n  from H obtain h where hG:\"h \\<in> carrier G\" and H2:\"H = h <# (stabiliser x)\"\n    unfolding LFactGroup_def LCOSETS_def by auto\n  with H gH have gh:\"g \\<in> h <# (stabiliser x)\" by simp\n  from l_repr_independence have \"h <# stabiliser x = g <# stabiliser x\"\n    using hG gh stabiliser_subgroup by simp\n  with H2 have \"H = g <# (stabiliser x)\" by simp\n  then show ?thesis by simp\nqed\n\nsection \"Orbit-Stabiliser Theorem\"\n\ntext \\<open>\n  We can now establish the bijection between orbit(x) and the quotient group G/(stabiliser(x))\n\n  The idea for this bijection is from \\<^cite>\\<open>orbitstab\\<close>\n\\<close>\ntheorem orbit_stabiliser_bij:\n  \"bij_betw (\\<lambda>H. rep H \\<odot> x) (carrier (G LMod (stabiliser x))) (orbit x) \"\nproof (rule bij_betw_imageI)\n  (* show the function is injective *)\n  show \"inj_on (\\<lambda>H. rep H \\<odot> x) (carrier (G LMod stabiliser x))\"\n  proof(rule inj_onI)\n    fix H H'\n    assume H:\"H \\<in> carrier (G LMod (stabiliser x))\"\n    assume H':\"H' \\<in> carrier (G LMod (stabiliser x))\"\n    obtain h h' where  h:\"h = rep H\" and h': \"h' = rep H'\" by simp\n    assume act_equal: \"(rep H) \\<odot> x = (rep H') \\<odot> x\"\n    from H h quotient_rep_ex have hH: \"h \\<in> H\" by simp\n    from H' h' quotient_rep_ex have hH': \"h' \\<in> H'\" by simp\n    from subgroup.lcosets_carrier[OF stabiliser_subgroup is_group] H have \"H \\<subseteq> carrier G\"\n      unfolding LFactGroup_def by simp\n    then have hG: \"h \\<in> carrier G\" using hH by auto\n    from subgroup.lcosets_carrier[OF stabiliser_subgroup is_group] H' have \"H' \\<subseteq> carrier G\"\n      unfolding LFactGroup_def by simp\n    then have h'G: \"h' \\<in> carrier G\" using hH' by auto\n\n        (* Apply lemma about equivalent cosets *)\n    have hh'_equiv:\"h <# (stabiliser x) = h' <# (stabiliser x)\"\n      using hG h'G h h' act_equal stabiliser_cosets_equivalent by simp\n\n    from hh'_equiv have H2:\"H = h <# (stabiliser x)\"\n      using H hH rep_equivalent by blast\n    moreover from hh'_equiv have H3:\"H' = h <# (stabiliser x)\"\n      using H' hH' rep_equivalent by blast\n    then show \"H = H'\" using H2 H3 by simp\n  qed\nnext\n  show \"(\\<lambda>H. rep H \\<odot> x) ` carrier (G LMod stabiliser x) = orbit x\"\n  proof(auto)\n    show \"\\<And>H. H \\<in> carrier (G LMod stabiliser x) \\<Longrightarrow> rep H \\<odot> x \\<in> orbit x\"\n    proof -\n      fix H\n      assume H:\"H \\<in> carrier (G LMod (stabiliser x))\"\n      obtain h where h:\"h = rep H\" by simp\n      from H h quotient_rep_ex have hH: \"h \\<in> H\" by simp\n      have stab_sub: \"(stabiliser x) \\<subseteq> carrier G\" using stabiliser_def by auto\n      from subgroup.lcosets_carrier[OF stabiliser_subgroup is_group] H have \"H \\<subseteq> carrier G\"\n        unfolding LFactGroup_def by simp\n      with hH have \"h \\<in> carrier G\" by auto\n      then show \"(rep H) \\<odot> x \\<in> orbit x\" using h orbit_def mem_Collect_eq by blast\n    qed\n    show \"\\<And>y. y \\<in> orbit x \\<Longrightarrow> y \\<in> (\\<lambda>H. rep H \\<odot> x) ` carrier (G LMod stabiliser x)\"\n    proof -\n      fix y\n      assume y:\"y \\<in> orbit x\"\n      obtain g  where gG:\"g \\<in> carrier G\" and \"y = g \\<odot> x\" using y orbit_def by auto\n      obtain H where H:\"H = g <# (stabiliser x)\" by auto\n      with gG have H_carr:\"H \\<in> carrier (G LMod stabiliser x)\"\n        unfolding LFactGroup_def LCOSETS_def by auto\n      then have \"rep H \\<in> H\" using quotient_rep_ex by auto\n      then obtain h where h_stab:\"h \\<in> stabiliser x\" and gh:\"rep H = g \\<otimes> h\"\n        unfolding H l_coset_def by auto\n      have hG:\"h \\<in> carrier G\" using h_stab stabiliser_def by auto\n      from stabiliser_def h_stab have \"h \\<odot> x = x\" by auto\n      with \\<open>y = g \\<odot> x\\<close> have \"y = g \\<odot> (h \\<odot> x)\" by simp\n      then have \"y = (g \\<otimes> h) \\<odot> x\" using gG hG compat_act by auto\n      then have \"y = (rep H) \\<odot> x\" using gh by simp\n      then show \"y \\<in> (\\<lambda>H. rep H \\<odot> x) ` carrier (G LMod stabiliser x)\"\n        using H_carr by simp\n    qed\n  qed\nqed\n\n\ntext\\<open>\n  The actual orbit-stabiliser theorem is a consequence of the bijection\n   we established in the previous theorem and of Lagrange's theorem\n\\<close>\ntheorem orbit_stabiliser:\n  assumes finite: \"finite (carrier G)\"\n  shows \"order G = card (orbit x) * card (stabiliser x)\"\nproof -\n  have \"card (carrier (G LMod (stabiliser x))) = card (orbit x)\"\n    using bij_betw_same_card orbit_stabiliser_bij by auto\n  moreover have \"card (carrier (G LMod (stabiliser x))) * card (stabiliser x)  = order G\"\n    using finite stabiliser_subgroup l_lagrange unfolding LFactGroup_def by simp\n  ultimately show ?thesis by simp\nqed\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/Orbit_Stabiliser/Orbit_Stabiliser.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8289387914176258, "lm_q2_score": 0.8824278695464501, "lm_q1q2_score": 0.7314786916950647}}
{"text": "(*  Title:      HOL/Algebra/Group.thy\n    Author:     Clemens Ballarin, started 4 February 2003\n\nBased on work by Florian Kammueller, L C Paulson and Markus Wenzel.\nWith additional contributions from Martin Baillon and Paulo Em\u00edlio de Vilhena.\n*)\n\ntheory Group\nimports Complete_Lattice \"HOL-Library.FuncSet\"\nbegin\n\nsection \\<open>Monoids and Groups\\<close>\n\nsubsection \\<open>Definitions\\<close>\n\ntext \\<open>\n  Definitions follow \\<^cite>\\<open>\"Jacobson:1985\"\\<close>.\n\\<close>\n\nrecord 'a monoid =  \"'a partial_object\" +\n  mult    :: \"['a, 'a] \\<Rightarrow> 'a\" (infixl \"\\<otimes>\\<index>\" 70)\n  one     :: 'a (\"\\<one>\\<index>\")\n\ndefinition\n  m_inv :: \"('a, 'b) monoid_scheme => 'a => 'a\" (\"inv\\<index> _\" [81] 80)\n  where \"inv\\<^bsub>G\\<^esub> x = (THE y. y \\<in> carrier G \\<and> x \\<otimes>\\<^bsub>G\\<^esub> y = \\<one>\\<^bsub>G\\<^esub> \\<and> y \\<otimes>\\<^bsub>G\\<^esub> x = \\<one>\\<^bsub>G\\<^esub>)\"\n\ndefinition\n  Units :: \"_ => 'a set\"\n  \\<comment> \\<open>The set of invertible elements\\<close>\n  where \"Units G = {y. y \\<in> carrier G \\<and> (\\<exists>x \\<in> carrier G. x \\<otimes>\\<^bsub>G\\<^esub> y = \\<one>\\<^bsub>G\\<^esub> \\<and> y \\<otimes>\\<^bsub>G\\<^esub> x = \\<one>\\<^bsub>G\\<^esub>)}\"\n\nlocale monoid =\n  fixes G (structure)\n  assumes m_closed [intro, simp]:\n         \"\\<lbrakk>x \\<in> carrier G; y \\<in> carrier G\\<rbrakk> \\<Longrightarrow> x \\<otimes> y \\<in> carrier G\"\n      and m_assoc:\n         \"\\<lbrakk>x \\<in> carrier G; y \\<in> carrier G; z \\<in> carrier G\\<rbrakk>\n          \\<Longrightarrow> (x \\<otimes> y) \\<otimes> z = x \\<otimes> (y \\<otimes> z)\"\n      and one_closed [intro, simp]: \"\\<one> \\<in> carrier G\"\n      and l_one [simp]: \"x \\<in> carrier G \\<Longrightarrow> \\<one> \\<otimes> x = x\"\n      and r_one [simp]: \"x \\<in> carrier G \\<Longrightarrow> x \\<otimes> \\<one> = x\"\n\nlemma monoidI:\n  fixes G (structure)\n  assumes m_closed:\n      \"!!x y. [| x \\<in> carrier G; y \\<in> carrier G |] ==> x \\<otimes> y \\<in> carrier G\"\n    and one_closed: \"\\<one> \\<in> carrier G\"\n    and m_assoc:\n      \"!!x y z. [| x \\<in> carrier G; y \\<in> carrier G; z \\<in> carrier G |] ==>\n      (x \\<otimes> y) \\<otimes> z = x \\<otimes> (y \\<otimes> z)\"\n    and l_one: \"!!x. x \\<in> carrier G ==> \\<one> \\<otimes> x = x\"\n    and r_one: \"!!x. x \\<in> carrier G ==> x \\<otimes> \\<one> = x\"\n  shows \"monoid G\"\n  by (fast intro!: monoid.intro intro: assms)\n\nlemma (in monoid) Units_closed [dest]:\n  \"x \\<in> Units G ==> x \\<in> carrier G\"\n  by (unfold Units_def) fast\n\nlemma (in monoid) one_unique:\n  assumes \"u \\<in> carrier G\"\n    and \"\\<And>x. x \\<in> carrier G \\<Longrightarrow> u \\<otimes> x = x\"\n  shows \"u = \\<one>\"\n  using assms(2)[OF one_closed] r_one[OF assms(1)] by simp\n\nlemma (in monoid) inv_unique:\n  assumes eq: \"y \\<otimes> x = \\<one>\"  \"x \\<otimes> y' = \\<one>\"\n    and G: \"x \\<in> carrier G\"  \"y \\<in> carrier G\"  \"y' \\<in> carrier G\"\n  shows \"y = y'\"\nproof -\n  from G eq have \"y = y \\<otimes> (x \\<otimes> y')\" by simp\n  also from G have \"... = (y \\<otimes> x) \\<otimes> y'\" by (simp add: m_assoc)\n  also from G eq have \"... = y'\" by simp\n  finally show ?thesis .\nqed\n\nlemma (in monoid) Units_m_closed [simp, intro]:\n  assumes x: \"x \\<in> Units G\" and y: \"y \\<in> Units G\"\n  shows \"x \\<otimes> y \\<in> Units G\"\nproof -\n  from x obtain x' where x: \"x \\<in> carrier G\" \"x' \\<in> carrier G\" and xinv: \"x \\<otimes> x' = \\<one>\" \"x' \\<otimes> x = \\<one>\"\n    unfolding Units_def by fast\n  from y obtain y' where y: \"y \\<in> carrier G\" \"y' \\<in> carrier G\" and yinv: \"y \\<otimes> y' = \\<one>\" \"y' \\<otimes> y = \\<one>\"\n    unfolding Units_def by fast\n  from x y xinv yinv have \"y' \\<otimes> (x' \\<otimes> x) \\<otimes> y = \\<one>\" by simp\n  moreover from x y xinv yinv have \"x \\<otimes> (y \\<otimes> y') \\<otimes> x' = \\<one>\" by simp\n  moreover note x y\n  ultimately show ?thesis unfolding Units_def\n    by simp (metis m_assoc m_closed)\nqed\n\nlemma (in monoid) Units_one_closed [intro, simp]:\n  \"\\<one> \\<in> Units G\"\n  by (unfold Units_def) auto\n\nlemma (in monoid) Units_inv_closed [intro, simp]:\n  \"x \\<in> Units G ==> inv x \\<in> carrier G\"\n  apply (simp add: Units_def m_inv_def)\n  by (metis (mono_tags, lifting) inv_unique the_equality)\n\nlemma (in monoid) Units_l_inv_ex:\n  \"x \\<in> Units G ==> \\<exists>y \\<in> carrier G. y \\<otimes> x = \\<one>\"\n  by (unfold Units_def) auto\n\nlemma (in monoid) Units_r_inv_ex:\n  \"x \\<in> Units G ==> \\<exists>y \\<in> carrier G. x \\<otimes> y = \\<one>\"\n  by (unfold Units_def) auto\n\nlemma (in monoid) Units_l_inv [simp]:\n  \"x \\<in> Units G ==> inv x \\<otimes> x = \\<one>\"\n  apply (unfold Units_def m_inv_def, simp)\n  by (metis (mono_tags, lifting) inv_unique the_equality)\n\nlemma (in monoid) Units_r_inv [simp]:\n  \"x \\<in> Units G ==> x \\<otimes> inv x = \\<one>\"\n  by (metis (full_types) Units_closed Units_inv_closed Units_l_inv Units_r_inv_ex inv_unique)\n\nlemma (in monoid) inv_one [simp]:\n  \"inv \\<one> = \\<one>\"\n  by (metis Units_one_closed Units_r_inv l_one monoid.Units_inv_closed monoid_axioms)\n\nlemma (in monoid) Units_inv_Units [intro, simp]:\n  \"x \\<in> Units G ==> inv x \\<in> Units G\"\nproof -\n  assume x: \"x \\<in> Units G\"\n  show \"inv x \\<in> Units G\"\n    by (auto simp add: Units_def\n      intro: Units_l_inv Units_r_inv x Units_closed [OF x])\nqed\n\nlemma (in monoid) Units_l_cancel [simp]:\n  \"[| x \\<in> Units G; y \\<in> carrier G; z \\<in> carrier G |] ==>\n   (x \\<otimes> y = x \\<otimes> z) = (y = z)\"\nproof\n  assume eq: \"x \\<otimes> y = x \\<otimes> z\"\n    and G: \"x \\<in> Units G\"  \"y \\<in> carrier G\"  \"z \\<in> carrier G\"\n  then have \"(inv x \\<otimes> x) \\<otimes> y = (inv x \\<otimes> x) \\<otimes> z\"\n    by (simp add: m_assoc Units_closed del: Units_l_inv)\n  with G show \"y = z\" by simp\nnext\n  assume eq: \"y = z\"\n    and G: \"x \\<in> Units G\"  \"y \\<in> carrier G\"  \"z \\<in> carrier G\"\n  then show \"x \\<otimes> y = x \\<otimes> z\" by simp\nqed\n\nlemma (in monoid) Units_inv_inv [simp]:\n  \"x \\<in> Units G ==> inv (inv x) = x\"\nproof -\n  assume x: \"x \\<in> Units G\"\n  then have \"inv x \\<otimes> inv (inv x) = inv x \\<otimes> x\" by simp\n  with x show ?thesis by (simp add: Units_closed del: Units_l_inv Units_r_inv)\nqed\n\nlemma (in monoid) inv_inj_on_Units:\n  \"inj_on (m_inv G) (Units G)\"\nproof (rule inj_onI)\n  fix x y\n  assume G: \"x \\<in> Units G\"  \"y \\<in> Units G\" and eq: \"inv x = inv y\"\n  then have \"inv (inv x) = inv (inv y)\" by simp\n  with G show \"x = y\" by simp\nqed\n\nlemma (in monoid) Units_inv_comm:\n  assumes inv: \"x \\<otimes> y = \\<one>\"\n    and G: \"x \\<in> Units G\"  \"y \\<in> Units G\"\n  shows \"y \\<otimes> x = \\<one>\"\nproof -\n  from G have \"x \\<otimes> y \\<otimes> x = x \\<otimes> \\<one>\" by (auto simp add: inv Units_closed)\n  with G show ?thesis by (simp del: r_one add: m_assoc Units_closed)\nqed\n\nlemma (in monoid) carrier_not_empty: \"carrier G \\<noteq> {}\"\nby auto\n\n(* Jacobson defines submonoid here. *)\n(* Jacobson defines the order of a monoid here. *)\n\n\nsubsection \\<open>Groups\\<close>\n\ntext \\<open>\n  A group is a monoid all of whose elements are invertible.\n\\<close>\n\nlocale group = monoid +\n  assumes Units: \"carrier G <= Units G\"\n\nlemma (in group) is_group [iff]: \"group G\" by (rule group_axioms)\n\nlemma (in group) is_monoid [iff]: \"monoid G\"\n  by (rule monoid_axioms)\n\ntheorem groupI:\n  fixes G (structure)\n  assumes m_closed [simp]:\n      \"!!x y. [| x \\<in> carrier G; y \\<in> carrier G |] ==> x \\<otimes> y \\<in> carrier G\"\n    and one_closed [simp]: \"\\<one> \\<in> carrier G\"\n    and m_assoc:\n      \"!!x y z. [| x \\<in> carrier G; y \\<in> carrier G; z \\<in> carrier G |] ==>\n      (x \\<otimes> y) \\<otimes> z = x \\<otimes> (y \\<otimes> z)\"\n    and l_one [simp]: \"!!x. x \\<in> carrier G ==> \\<one> \\<otimes> x = x\"\n    and l_inv_ex: \"!!x. x \\<in> carrier G ==> \\<exists>y \\<in> carrier G. y \\<otimes> x = \\<one>\"\n  shows \"group G\"\nproof -\n  have l_cancel [simp]:\n    \"!!x y z. [| x \\<in> carrier G; y \\<in> carrier G; z \\<in> carrier G |] ==>\n    (x \\<otimes> y = x \\<otimes> z) = (y = z)\"\n  proof\n    fix x y z\n    assume eq: \"x \\<otimes> y = x \\<otimes> z\"\n      and G: \"x \\<in> carrier G\"  \"y \\<in> carrier G\"  \"z \\<in> carrier G\"\n    with l_inv_ex obtain x_inv where xG: \"x_inv \\<in> carrier G\"\n      and l_inv: \"x_inv \\<otimes> x = \\<one>\" by fast\n    from G eq xG have \"(x_inv \\<otimes> x) \\<otimes> y = (x_inv \\<otimes> x) \\<otimes> z\"\n      by (simp add: m_assoc)\n    with G show \"y = z\" by (simp add: l_inv)\n  next\n    fix x y z\n    assume eq: \"y = z\"\n      and G: \"x \\<in> carrier G\"  \"y \\<in> carrier G\"  \"z \\<in> carrier G\"\n    then show \"x \\<otimes> y = x \\<otimes> z\" by simp\n  qed\n  have r_one:\n    \"!!x. x \\<in> carrier G ==> x \\<otimes> \\<one> = x\"\n  proof -\n    fix x\n    assume x: \"x \\<in> carrier G\"\n    with l_inv_ex obtain x_inv where xG: \"x_inv \\<in> carrier G\"\n      and l_inv: \"x_inv \\<otimes> x = \\<one>\" by fast\n    from x xG have \"x_inv \\<otimes> (x \\<otimes> \\<one>) = x_inv \\<otimes> x\"\n      by (simp add: m_assoc [symmetric] l_inv)\n    with x xG show \"x \\<otimes> \\<one> = x\" by simp\n  qed\n  have inv_ex:\n    \"\\<And>x. x \\<in> carrier G \\<Longrightarrow> \\<exists>y \\<in> carrier G. y \\<otimes> x = \\<one> \\<and> x \\<otimes> y = \\<one>\"\n  proof -\n    fix x\n    assume x: \"x \\<in> carrier G\"\n    with l_inv_ex obtain y where y: \"y \\<in> carrier G\"\n      and l_inv: \"y \\<otimes> x = \\<one>\" by fast\n    from x y have \"y \\<otimes> (x \\<otimes> y) = y \\<otimes> \\<one>\"\n      by (simp add: m_assoc [symmetric] l_inv r_one)\n    with x y have r_inv: \"x \\<otimes> y = \\<one>\"\n      by simp\n    from x y show \"\\<exists>y \\<in> carrier G. y \\<otimes> x = \\<one> \\<and> x \\<otimes> y = \\<one>\"\n      by (fast intro: l_inv r_inv)\n  qed\n  then have carrier_subset_Units: \"carrier G \\<subseteq> Units G\"\n    by (unfold Units_def) fast\n  show ?thesis\n    by standard (auto simp: r_one m_assoc carrier_subset_Units)\nqed\n\nlemma (in monoid) group_l_invI:\n  assumes l_inv_ex:\n    \"!!x. x \\<in> carrier G ==> \\<exists>y \\<in> carrier G. y \\<otimes> x = \\<one>\"\n  shows \"group G\"\n  by (rule groupI) (auto intro: m_assoc l_inv_ex)\n\nlemma (in group) Units_eq [simp]:\n  \"Units G = carrier G\"\nproof\n  show \"Units G \\<subseteq> carrier G\" by fast\nnext\n  show \"carrier G \\<subseteq> Units G\" by (rule Units)\nqed\n\nlemma (in group) inv_closed [intro, simp]:\n  \"x \\<in> carrier G ==> inv x \\<in> carrier G\"\n  using Units_inv_closed by simp\n\nlemma (in group) l_inv_ex [simp]:\n  \"x \\<in> carrier G ==> \\<exists>y \\<in> carrier G. y \\<otimes> x = \\<one>\"\n  using Units_l_inv_ex by simp\n\nlemma (in group) r_inv_ex [simp]:\n  \"x \\<in> carrier G ==> \\<exists>y \\<in> carrier G. x \\<otimes> y = \\<one>\"\n  using Units_r_inv_ex by simp\n\nlemma (in group) l_inv [simp]:\n  \"x \\<in> carrier G ==> inv x \\<otimes> x = \\<one>\"\n  by simp\n\n\nsubsection \\<open>Cancellation Laws and Basic Properties\\<close>\n\nlemma (in group) inv_eq_1_iff [simp]:\n  assumes \"x \\<in> carrier G\" shows \"inv\\<^bsub>G\\<^esub> x = \\<one>\\<^bsub>G\\<^esub> \\<longleftrightarrow> x = \\<one>\\<^bsub>G\\<^esub>\"\nproof -\n  have \"x = \\<one>\" if \"inv x = \\<one>\"\n  proof -\n    have \"inv x \\<otimes> x = \\<one>\"\n      using assms l_inv by blast\n    then show \"x = \\<one>\"\n      using that assms by simp\n  qed\n  then show ?thesis\n    by auto\nqed\n\nlemma (in group) r_inv [simp]:\n  \"x \\<in> carrier G ==> x \\<otimes> inv x = \\<one>\"\n  by simp\n\nlemma (in group) right_cancel [simp]:\n  \"[| x \\<in> carrier G; y \\<in> carrier G; z \\<in> carrier G |] ==>\n   (y \\<otimes> x = z \\<otimes> x) = (y = z)\"\n  by (metis inv_closed m_assoc r_inv r_one)\n\nlemma (in group) inv_inv [simp]:\n  \"x \\<in> carrier G ==> inv (inv x) = x\"\n  using Units_inv_inv by simp\n\nlemma (in group) inv_inj:\n  \"inj_on (m_inv G) (carrier G)\"\n  using inv_inj_on_Units by simp\n\nlemma (in group) inv_mult_group:\n  \"[| x \\<in> carrier G; y \\<in> carrier G |] ==> inv (x \\<otimes> y) = inv y \\<otimes> inv x\"\nproof -\n  assume G: \"x \\<in> carrier G\"  \"y \\<in> carrier G\"\n  then have \"inv (x \\<otimes> y) \\<otimes> (x \\<otimes> y) = (inv y \\<otimes> inv x) \\<otimes> (x \\<otimes> y)\"\n    by (simp add: m_assoc) (simp add: m_assoc [symmetric])\n  with G show ?thesis by (simp del: l_inv Units_l_inv)\nqed\n\nlemma (in group) inv_comm:\n  \"[| x \\<otimes> y = \\<one>; x \\<in> carrier G; y \\<in> carrier G |] ==> y \\<otimes> x = \\<one>\"\n  by (rule Units_inv_comm) auto\n\nlemma (in group) inv_equality:\n     \"[|y \\<otimes> x = \\<one>; x \\<in> carrier G; y \\<in> carrier G|] ==> inv x = y\"\n  using inv_unique r_inv by blast\n\nlemma (in group) inv_solve_left:\n  \"\\<lbrakk> a \\<in> carrier G; b \\<in> carrier G; c \\<in> carrier G \\<rbrakk> \\<Longrightarrow> a = inv b \\<otimes> c \\<longleftrightarrow> c = b \\<otimes> a\"\n  by (metis inv_equality l_inv_ex l_one m_assoc r_inv)\n\nlemma (in group) inv_solve_left':\n  \"\\<lbrakk> a \\<in> carrier G; b \\<in> carrier G; c \\<in> carrier G \\<rbrakk> \\<Longrightarrow> inv b \\<otimes> c = a \\<longleftrightarrow> c = b \\<otimes> a\"\n  by (metis inv_equality l_inv_ex l_one m_assoc r_inv)\n\nlemma (in group) inv_solve_right:\n  \"\\<lbrakk> a \\<in> carrier G; b \\<in> carrier G; c \\<in> carrier G \\<rbrakk> \\<Longrightarrow> a = b \\<otimes> inv c \\<longleftrightarrow> b = a \\<otimes> c\"\n  by (metis inv_equality l_inv_ex l_one m_assoc r_inv)\n\nlemma (in group) inv_solve_right':\n  \"\\<lbrakk>a \\<in> carrier G; b \\<in> carrier G; c \\<in> carrier G\\<rbrakk> \\<Longrightarrow> b \\<otimes> inv c = a \\<longleftrightarrow> b = a \\<otimes> c\"\n  by (auto simp: m_assoc)\n  \n\nsubsection \\<open>Power\\<close>\n\nconsts\n  pow :: \"[('a, 'm) monoid_scheme, 'a, 'b::semiring_1] => 'a\"  (infixr \"[^]\\<index>\" 75)\n\noverloading nat_pow == \"pow :: [_, 'a, nat] => 'a\"\nbegin\n  definition \"nat_pow G a n = rec_nat \\<one>\\<^bsub>G\\<^esub> (%u b. b \\<otimes>\\<^bsub>G\\<^esub> a) n\"\nend\n\nlemma (in monoid) nat_pow_closed [intro, simp]:\n  \"x \\<in> carrier G ==> x [^] (n::nat) \\<in> carrier G\"\n  by (induct n) (simp_all add: nat_pow_def)\n\nlemma (in monoid) nat_pow_0 [simp]:\n  \"x [^] (0::nat) = \\<one>\"\n  by (simp add: nat_pow_def)\n\nlemma (in monoid) nat_pow_Suc [simp]:\n  \"x [^] (Suc n) = x [^] n \\<otimes> x\"\n  by (simp add: nat_pow_def)\n\nlemma (in monoid) nat_pow_one [simp]:\n  \"\\<one> [^] (n::nat) = \\<one>\"\n  by (induct n) simp_all\n\nlemma (in monoid) nat_pow_mult:\n  \"x \\<in> carrier G ==> x [^] (n::nat) \\<otimes> x [^] m = x [^] (n + m)\"\n  by (induct m) (simp_all add: m_assoc [THEN sym])\n\nlemma (in monoid) nat_pow_comm:\n  \"x \\<in> carrier G \\<Longrightarrow> (x [^] (n::nat)) \\<otimes> (x [^] (m :: nat)) = (x [^] m) \\<otimes> (x [^] n)\"\n  using nat_pow_mult[of x n m] nat_pow_mult[of x m n] by (simp add: add.commute)\n\nlemma (in monoid) nat_pow_Suc2:\n  \"x \\<in> carrier G \\<Longrightarrow> x [^] (Suc n) = x \\<otimes> (x [^] n)\"\n  using nat_pow_mult[of x 1 n] Suc_eq_plus1[of n]\n  by (metis One_nat_def Suc_eq_plus1_left l_one nat.rec(1) nat_pow_Suc nat_pow_def)\n\nlemma (in monoid) nat_pow_pow:\n  \"x \\<in> carrier G ==> (x [^] n) [^] m = x [^] (n * m::nat)\"\n  by (induct m) (simp, simp add: nat_pow_mult add.commute)\n\nlemma (in monoid) nat_pow_consistent:\n  \"x [^] (n :: nat) = x [^]\\<^bsub>(G \\<lparr> carrier := H \\<rparr>)\\<^esub> n\"\n  unfolding nat_pow_def by simp\n\nlemma nat_pow_0 [simp]: \"x [^]\\<^bsub>G\\<^esub> (0::nat) = \\<one>\\<^bsub>G\\<^esub>\"\n  by (simp add: nat_pow_def)\n\nlemma nat_pow_Suc [simp]: \"x [^]\\<^bsub>G\\<^esub> (Suc n) = (x [^]\\<^bsub>G\\<^esub> n)\\<otimes>\\<^bsub>G\\<^esub> x\"\n  by (simp add: nat_pow_def)\n\nlemma (in group) nat_pow_inv:\n  assumes \"x \\<in> carrier G\" shows \"(inv x) [^] (i :: nat) = inv (x [^] i)\"\nproof (induction i)\n  case 0 thus ?case by simp\nnext\n  case (Suc i)\n  have \"(inv x) [^] Suc i = ((inv x) [^] i) \\<otimes> inv x\"\n    by simp\n  also have \" ... = (inv (x [^] i)) \\<otimes> inv x\"\n    by (simp add: Suc.IH Suc.prems)\n  also have \" ... = inv (x \\<otimes> (x [^] i))\"\n    by (simp add: assms inv_mult_group)\n  also have \" ... = inv (x [^] (Suc i))\"\n    using assms nat_pow_Suc2 by auto\n  finally show ?case .\nqed\n\noverloading int_pow == \"pow :: [_, 'a, int] => 'a\"\nbegin\n  definition \"int_pow G a z =\n   (let p = rec_nat \\<one>\\<^bsub>G\\<^esub> (%u b. b \\<otimes>\\<^bsub>G\\<^esub> a)\n    in if z < 0 then inv\\<^bsub>G\\<^esub> (p (nat (-z))) else p (nat z))\"\nend\n\nlemma int_pow_int: \"x [^]\\<^bsub>G\\<^esub> (int n) = x [^]\\<^bsub>G\\<^esub> n\"\n  by(simp add: int_pow_def nat_pow_def)\n\nlemma pow_nat:\n  assumes \"i\\<ge>0\"\n  shows \"x [^]\\<^bsub>G\\<^esub> nat i = x [^]\\<^bsub>G\\<^esub> i\"\nproof (cases i rule: int_cases)\n  case (nonneg n)\n  then show ?thesis\n    by (simp add: int_pow_int)\nnext\n  case (neg n)\n  then show ?thesis\n    using assms by linarith\nqed\n\nlemma int_pow_0 [simp]: \"x [^]\\<^bsub>G\\<^esub> (0::int) = \\<one>\\<^bsub>G\\<^esub>\"\n  by (simp add: int_pow_def)\n\nlemma int_pow_def2: \"a [^]\\<^bsub>G\\<^esub> z =\n   (if z < 0 then inv\\<^bsub>G\\<^esub> (a [^]\\<^bsub>G\\<^esub> (nat (-z))) else a [^]\\<^bsub>G\\<^esub> (nat z))\"\n  by (simp add: int_pow_def nat_pow_def)\n\nlemma (in group) int_pow_one [simp]:\n  \"\\<one> [^] (z::int) = \\<one>\"\n  by (simp add: int_pow_def2)\n\nlemma (in group) int_pow_closed [intro, simp]:\n  \"x \\<in> carrier G ==> x [^] (i::int) \\<in> carrier G\"\n  by (simp add: int_pow_def2)\n\nlemma (in group) int_pow_1 [simp]:\n  \"x \\<in> carrier G \\<Longrightarrow> x [^] (1::int) = x\"\n  by (simp add: int_pow_def2)\n\nlemma (in group) int_pow_neg:\n  \"x \\<in> carrier G \\<Longrightarrow> x [^] (-i::int) = inv (x [^] i)\"\n  by (simp add: int_pow_def2)\n\nlemma (in group) int_pow_neg_int: \"x \\<in> carrier G \\<Longrightarrow> x [^] -(int n) = inv (x [^] n)\"\n  by (simp add: int_pow_neg int_pow_int)\n\nlemma (in group) int_pow_mult:\n  assumes \"x \\<in> carrier G\" shows \"x [^] (i + j::int) = x [^] i \\<otimes> x [^] j\"\nproof -\n  have [simp]: \"-i - j = -j - i\" by simp\n  show ?thesis\n    by (auto simp: assms int_pow_def2 inv_solve_left inv_solve_right nat_add_distrib [symmetric] nat_pow_mult)\nqed\n\nlemma (in group) int_pow_inv:\n  \"x \\<in> carrier G \\<Longrightarrow> (inv x) [^] (i :: int) = inv (x [^] i)\"\n  by (metis int_pow_def2 nat_pow_inv)\n\nlemma (in group) int_pow_pow:\n  assumes \"x \\<in> carrier G\"\n  shows \"(x [^] (n :: int)) [^] (m :: int) = x [^] (n * m :: int)\"\nproof (cases)\n  assume n_ge: \"n \\<ge> 0\" thus ?thesis\n  proof (cases)\n    assume m_ge: \"m \\<ge> 0\" thus ?thesis\n      using n_ge nat_pow_pow[OF assms, of \"nat n\" \"nat m\"] int_pow_def2 [where G=G]\n      by (simp add: mult_less_0_iff nat_mult_distrib)\n  next\n    assume m_lt: \"\\<not> m \\<ge> 0\" \n    with n_ge show ?thesis\n      apply (simp add: int_pow_def2 mult_less_0_iff)\n      by (metis assms mult_minus_right n_ge nat_mult_distrib nat_pow_pow)\n  qed\nnext\n  assume n_lt: \"\\<not> n \\<ge> 0\" thus ?thesis\n  proof (cases)\n    assume m_ge: \"m \\<ge> 0\" \n    have \"inv x [^] (nat m * nat (- n)) = inv x [^] nat (- (m * n))\"\n      by (metis (full_types) m_ge mult_minus_right nat_mult_distrib)\n    with m_ge n_lt show ?thesis\n      by (simp add: int_pow_def2 mult_less_0_iff assms mult.commute nat_pow_inv nat_pow_pow)\n  next\n    assume m_lt: \"\\<not> m \\<ge> 0\" thus ?thesis\n      using n_lt by (auto simp: int_pow_def2 mult_less_0_iff assms nat_mult_distrib_neg nat_pow_inv nat_pow_pow)\n  qed\nqed\n\nlemma (in group) int_pow_diff:\n  \"x \\<in> carrier G \\<Longrightarrow> x [^] (n - m :: int) = x [^] n \\<otimes> inv (x [^] m)\"\n  by(simp only: diff_conv_add_uminus int_pow_mult int_pow_neg)\n\nlemma (in group) inj_on_multc: \"c \\<in> carrier G \\<Longrightarrow> inj_on (\\<lambda>x. x \\<otimes> c) (carrier G)\"\n  by(simp add: inj_on_def)\n\nlemma (in group) inj_on_cmult: \"c \\<in> carrier G \\<Longrightarrow> inj_on (\\<lambda>x. c \\<otimes> x) (carrier G)\"\n  by(simp add: inj_on_def)\n\n\nlemma (in monoid) group_commutes_pow:\n  fixes n::nat\n  shows \"\\<lbrakk>x \\<otimes> y = y \\<otimes> x; x \\<in> carrier G; y \\<in> carrier G\\<rbrakk> \\<Longrightarrow> x [^] n \\<otimes> y = y \\<otimes> x [^] n\"\n  apply (induction n, auto)\n  by (metis m_assoc nat_pow_closed)\n\nlemma (in monoid) pow_mult_distrib:\n  assumes eq: \"x \\<otimes> y = y \\<otimes> x\" and xy: \"x \\<in> carrier G\" \"y \\<in> carrier G\"\n  shows \"(x \\<otimes> y) [^] (n::nat) = x [^] n \\<otimes> y [^] n\"\nproof (induct n)\n  case (Suc n)\n  have \"x \\<otimes> (y [^] n \\<otimes> y) = y [^] n \\<otimes> x \\<otimes> y\"\n    by (simp add: eq group_commutes_pow m_assoc xy)\n  then show ?case\n    using assms Suc.hyps m_assoc by auto\nqed auto\n\nlemma (in group) int_pow_mult_distrib:\n  assumes eq: \"x \\<otimes> y = y \\<otimes> x\" and xy: \"x \\<in> carrier G\" \"y \\<in> carrier G\"\n  shows \"(x \\<otimes> y) [^] (i::int) = x [^] i \\<otimes> y [^] i\"\nproof (cases i rule: int_cases)\n  case (nonneg n)\n  then show ?thesis\n    by (metis eq int_pow_int pow_mult_distrib xy)\nnext\n  case (neg n)\n  then show ?thesis\n    unfolding neg\n    apply (simp add: xy int_pow_neg_int del: of_nat_Suc)\n    by (metis eq inv_mult_group local.nat_pow_Suc nat_pow_closed pow_mult_distrib xy)\nqed\n\nlemma (in group) pow_eq_div2:\n  fixes m n :: nat\n  assumes x_car: \"x \\<in> carrier G\"\n  assumes pow_eq: \"x [^] m = x [^] n\"\n  shows \"x [^] (m - n) = \\<one>\"\nproof (cases \"m < n\")\n  case False\n  have \"\\<one> \\<otimes> x [^] m = x [^] m\" by (simp add: x_car)\n  also have \"\\<dots> = x [^] (m - n) \\<otimes> x [^] n\"\n    using False by (simp add: nat_pow_mult x_car)\n  also have \"\\<dots> = x [^] (m - n) \\<otimes> x [^] m\"\n    by (simp add: pow_eq)\n  finally show ?thesis\n    by (metis nat_pow_closed one_closed right_cancel x_car)\nqed simp\n\nsubsection \\<open>Submonoids\\<close>\n\nlocale submonoid = \\<^marker>\\<open>contributor \\<open>Martin Baillon\\<close>\\<close>\n  fixes H and G (structure)\n  assumes subset: \"H \\<subseteq> carrier G\"\n    and m_closed [intro, simp]: \"\\<lbrakk>x \\<in> H; y \\<in> H\\<rbrakk> \\<Longrightarrow> x \\<otimes> y \\<in> H\"\n    and one_closed [simp]: \"\\<one> \\<in> H\"\n\nlemma (in submonoid) is_submonoid: \\<^marker>\\<open>contributor \\<open>Martin Baillon\\<close>\\<close>\n  \"submonoid H G\" by (rule submonoid_axioms)\n\nlemma (in submonoid) mem_carrier [simp]: \\<^marker>\\<open>contributor \\<open>Martin Baillon\\<close>\\<close>\n  \"x \\<in> H \\<Longrightarrow> x \\<in> carrier G\"\n  using subset by blast\n\nlemma (in submonoid) submonoid_is_monoid [intro]: \\<^marker>\\<open>contributor \\<open>Martin Baillon\\<close>\\<close>\n  assumes \"monoid G\"\n  shows \"monoid (G\\<lparr>carrier := H\\<rparr>)\"\nproof -\n  interpret monoid G by fact\n  show ?thesis\n    by (simp add: monoid_def m_assoc)\nqed\n\nlemma submonoid_nonempty: \\<^marker>\\<open>contributor \\<open>Martin Baillon\\<close>\\<close>\n  \"~ submonoid {} G\"\n  by (blast dest: submonoid.one_closed)\n\nlemma (in submonoid) finite_monoid_imp_card_positive: \\<^marker>\\<open>contributor \\<open>Martin Baillon\\<close>\\<close>\n  \"finite (carrier G) ==> 0 < card H\"\nproof (rule classical)\n  assume \"finite (carrier G)\" and a: \"~ 0 < card H\"\n  then have \"finite H\" by (blast intro: finite_subset [OF subset])\n  with is_submonoid a have \"submonoid {} G\" by simp\n  with submonoid_nonempty show ?thesis by contradiction\nqed\n\n\nlemma (in monoid) monoid_incl_imp_submonoid : \\<^marker>\\<open>contributor \\<open>Martin Baillon\\<close>\\<close>\n  assumes \"H \\<subseteq> carrier G\"\nand \"monoid (G\\<lparr>carrier := H\\<rparr>)\"\nshows \"submonoid H G\"\nproof (intro submonoid.intro[OF assms(1)])\n  have ab_eq : \"\\<And> a b. a \\<in> H \\<Longrightarrow> b \\<in> H \\<Longrightarrow> a \\<otimes>\\<^bsub>G\\<lparr>carrier := H\\<rparr>\\<^esub> b = a \\<otimes> b\" using assms by simp\n  have \"\\<And>a b. a \\<in> H \\<Longrightarrow> b \\<in> H \\<Longrightarrow> a \\<otimes> b \\<in> carrier (G\\<lparr>carrier := H\\<rparr>) \"\n    using assms ab_eq unfolding group_def using monoid.m_closed by fastforce\n  thus \"\\<And>a b. a \\<in> H \\<Longrightarrow> b \\<in> H \\<Longrightarrow> a \\<otimes> b \\<in> H\" by simp\n  show \"\\<one> \\<in> H \" using monoid.one_closed[OF assms(2)] assms by simp\nqed\n\nlemma (in monoid) inv_unique': \\<^marker>\\<open>contributor \\<open>Martin Baillon\\<close>\\<close>\n  assumes \"x \\<in> carrier G\" \"y \\<in> carrier G\"\n  shows \"\\<lbrakk> x \\<otimes> y = \\<one>; y \\<otimes> x = \\<one> \\<rbrakk> \\<Longrightarrow> y = inv x\"\nproof -\n  assume \"x \\<otimes> y = \\<one>\" and l_inv: \"y \\<otimes> x = \\<one>\"\n  hence unit: \"x \\<in> Units G\"\n    using assms unfolding Units_def by auto\n  show \"y = inv x\"\n    using inv_unique[OF l_inv Units_r_inv[OF unit] assms Units_inv_closed[OF unit]] .\nqed\n\nlemma (in monoid) m_inv_monoid_consistent: \\<^marker>\\<open>contributor \\<open>Paulo Em\u00edlio de Vilhena\\<close>\\<close>\n  assumes \"x \\<in> Units (G \\<lparr> carrier := H \\<rparr>)\" and \"submonoid H G\"\n  shows \"inv\\<^bsub>(G \\<lparr> carrier := H \\<rparr>)\\<^esub> x = inv x\"\nproof -\n  have monoid: \"monoid (G \\<lparr> carrier := H \\<rparr>)\"\n    using submonoid.submonoid_is_monoid[OF assms(2) monoid_axioms] .\n  obtain y where y: \"y \\<in> H\" \"x \\<otimes> y = \\<one>\" \"y \\<otimes> x = \\<one>\"\n    using assms(1) unfolding Units_def by auto\n  have x: \"x \\<in> H\" and in_carrier: \"x \\<in> carrier G\" \"y \\<in> carrier G\"\n    using y(1) submonoid.subset[OF assms(2)] assms(1) unfolding Units_def by auto\n  show ?thesis\n    using monoid.inv_unique'[OF monoid, of x y] x y\n    using inv_unique'[OF in_carrier y(2-3)] by auto\nqed\n\nsubsection \\<open>Subgroups\\<close>\n\nlocale subgroup =\n  fixes H and G (structure)\n  assumes subset: \"H \\<subseteq> carrier G\"\n    and m_closed [intro, simp]: \"\\<lbrakk>x \\<in> H; y \\<in> H\\<rbrakk> \\<Longrightarrow> x \\<otimes> y \\<in> H\"\n    and one_closed [simp]: \"\\<one> \\<in> H\"\n    and m_inv_closed [intro,simp]: \"x \\<in> H \\<Longrightarrow> inv x \\<in> H\"\n\nlemma (in subgroup) is_subgroup:\n  \"subgroup H G\" by (rule subgroup_axioms)\n\ndeclare (in subgroup) group.intro [intro]\n\nlemma (in subgroup) mem_carrier [simp]:\n  \"x \\<in> H \\<Longrightarrow> x \\<in> carrier G\"\n  using subset by blast\n\nlemma (in subgroup) subgroup_is_group [intro]:\n  assumes \"group G\"\n  shows \"group (G\\<lparr>carrier := H\\<rparr>)\"\nproof -\n  interpret group G by fact\n  have \"Group.monoid (G\\<lparr>carrier := H\\<rparr>)\"\n    by (simp add: monoid_axioms submonoid.intro submonoid.submonoid_is_monoid subset)\n  then show ?thesis\n    by (rule monoid.group_l_invI) (auto intro: l_inv mem_carrier)\nqed\n\nlemma (in group) triv_subgroup: \"subgroup {\\<one>} G\"\n  by (auto simp: subgroup_def)\n\nlemma subgroup_is_submonoid:\n  assumes \"subgroup H G\" shows \"submonoid H G\"\n  using assms by (auto intro: submonoid.intro simp add: subgroup_def)\n\nlemma (in group) subgroup_Units:\n  assumes \"subgroup H G\" shows \"H \\<subseteq> Units (G \\<lparr> carrier := H \\<rparr>)\"\n  using group.Units[OF subgroup.subgroup_is_group[OF assms group_axioms]] by simp\n\nlemma (in group) m_inv_consistent [simp]:\n  assumes \"subgroup H G\" \"x \\<in> H\"\n  shows \"inv\\<^bsub>(G \\<lparr> carrier := H \\<rparr>)\\<^esub> x = inv x\"\n  using assms m_inv_monoid_consistent[OF _ subgroup_is_submonoid] subgroup_Units[of H] by auto\n\nlemma (in group) int_pow_consistent: \\<^marker>\\<open>contributor \\<open>Paulo Em\u00edlio de Vilhena\\<close>\\<close>\n  assumes \"subgroup H G\" \"x \\<in> H\"\n  shows \"x [^] (n :: int) = x [^]\\<^bsub>(G \\<lparr> carrier := H \\<rparr>)\\<^esub> n\"\nproof (cases)\n  assume ge: \"n \\<ge> 0\"\n  hence \"x [^] n = x [^] (nat n)\"\n    using int_pow_def2 [of G] by auto\n  also have \" ... = x [^]\\<^bsub>(G \\<lparr> carrier := H \\<rparr>)\\<^esub> (nat n)\"\n    using nat_pow_consistent by simp\n  also have \" ... = x [^]\\<^bsub>(G \\<lparr> carrier := H \\<rparr>)\\<^esub> n\"\n    by (metis ge int_nat_eq int_pow_int)\n  finally show ?thesis .\nnext\n  assume \"\\<not> n \\<ge> 0\" hence lt: \"n < 0\" by simp\n  hence \"x [^] n = inv (x [^] (nat (- n)))\"\n    using int_pow_def2 [of G] by auto\n  also have \" ... = (inv x) [^] (nat (- n))\"\n    by (metis assms nat_pow_inv subgroup.mem_carrier)\n  also have \" ... = (inv\\<^bsub>(G \\<lparr> carrier := H \\<rparr>)\\<^esub> x) [^]\\<^bsub>(G \\<lparr> carrier := H \\<rparr>)\\<^esub> (nat (- n))\"\n    using m_inv_consistent[OF assms] nat_pow_consistent by auto\n  also have \" ... = inv\\<^bsub>(G \\<lparr> carrier := H \\<rparr>)\\<^esub> (x [^]\\<^bsub>(G \\<lparr> carrier := H \\<rparr>)\\<^esub> (nat (- n)))\"\n    using group.nat_pow_inv[OF subgroup.subgroup_is_group[OF assms(1) is_group]] assms(2) by auto\n  also have \" ... = x [^]\\<^bsub>(G \\<lparr> carrier := H \\<rparr>)\\<^esub> n\"\n    by (simp add: int_pow_def2 lt)\n  finally show ?thesis .\nqed\n\ntext \\<open>\n  Since \\<^term>\\<open>H\\<close> is nonempty, it contains some element \\<^term>\\<open>x\\<close>.  Since\n  it is closed under inverse, it contains \\<open>inv x\\<close>.  Since\n  it is closed under product, it contains \\<open>x \\<otimes> inv x = \\<one>\\<close>.\n\\<close>\n\nlemma (in group) one_in_subset:\n  \"[| H \\<subseteq> carrier G; H \\<noteq> {}; \\<forall>a \\<in> H. inv a \\<in> H; \\<forall>a\\<in>H. \\<forall>b\\<in>H. a \\<otimes> b \\<in> H |]\n   ==> \\<one> \\<in> H\"\nby force\n\ntext \\<open>A characterization of subgroups: closed, non-empty subset.\\<close>\n\nlemma (in group) subgroupI:\n  assumes subset: \"H \\<subseteq> carrier G\" and non_empty: \"H \\<noteq> {}\"\n    and inv: \"!!a. a \\<in> H \\<Longrightarrow> inv a \\<in> H\"\n    and mult: \"!!a b. \\<lbrakk>a \\<in> H; b \\<in> H\\<rbrakk> \\<Longrightarrow> a \\<otimes> b \\<in> H\"\n  shows \"subgroup H G\"\nproof (simp add: subgroup_def assms)\n  show \"\\<one> \\<in> H\" by (rule one_in_subset) (auto simp only: assms)\nqed\n\nlemma (in group) subgroupE:\n  assumes \"subgroup H G\"\n  shows \"H \\<subseteq> carrier G\"\n    and \"H \\<noteq> {}\"\n    and \"\\<And>a. a \\<in> H \\<Longrightarrow> inv a \\<in> H\"\n    and \"\\<And>a b. \\<lbrakk> a \\<in> H; b \\<in> H \\<rbrakk> \\<Longrightarrow> a \\<otimes> b \\<in> H\"\n  using assms unfolding subgroup_def[of H G] by auto\n\ndeclare monoid.one_closed [iff] group.inv_closed [simp]\n  monoid.l_one [simp] monoid.r_one [simp] group.inv_inv [simp]\n\nlemma subgroup_nonempty:\n  \"\\<not> subgroup {} G\"\n  by (blast dest: subgroup.one_closed)\n\nlemma (in subgroup) finite_imp_card_positive: \"finite (carrier G) \\<Longrightarrow> 0 < card H\"\n  using subset one_closed card_gt_0_iff finite_subset by blast\n\nlemma (in subgroup) subgroup_is_submonoid : \\<^marker>\\<open>contributor \\<open>Martin Baillon\\<close>\\<close>\n  \"submonoid H G\"\n  by (simp add: submonoid.intro subset)\n\nlemma (in group) submonoid_subgroupI : \\<^marker>\\<open>contributor \\<open>Martin Baillon\\<close>\\<close>\n  assumes \"submonoid H G\"\n    and \"\\<And>a. a \\<in> H \\<Longrightarrow> inv a \\<in> H\"\n  shows \"subgroup H G\"\n  by (metis assms subgroup_def submonoid_def)\n\nlemma (in group) group_incl_imp_subgroup: \\<^marker>\\<open>contributor \\<open>Martin Baillon\\<close>\\<close>\n  assumes \"H \\<subseteq> carrier G\"\n    and \"group (G\\<lparr>carrier := H\\<rparr>)\"\n  shows \"subgroup H G\"\nproof (intro submonoid_subgroupI[OF monoid_incl_imp_submonoid[OF assms(1)]])\n  show \"monoid (G\\<lparr>carrier := H\\<rparr>)\" using group_def assms by blast\n  have ab_eq : \"\\<And> a b. a \\<in> H \\<Longrightarrow> b \\<in> H \\<Longrightarrow> a \\<otimes>\\<^bsub>G\\<lparr>carrier := H\\<rparr>\\<^esub> b = a \\<otimes> b\" using assms by simp\n  fix a  assume aH : \"a \\<in> H\"\n  have \" inv\\<^bsub>G\\<lparr>carrier := H\\<rparr>\\<^esub> a \\<in> carrier G\"\n    using assms aH group.inv_closed[OF assms(2)] by auto\n  moreover have \"\\<one>\\<^bsub>G\\<lparr>carrier := H\\<rparr>\\<^esub> = \\<one>\" using assms monoid.one_closed ab_eq one_def by simp\n  hence \"a \\<otimes>\\<^bsub>G\\<lparr>carrier := H\\<rparr>\\<^esub> inv\\<^bsub>G\\<lparr>carrier := H\\<rparr>\\<^esub> a= \\<one>\"\n    using assms ab_eq aH  group.r_inv[OF assms(2)] by simp\n  hence \"a \\<otimes> inv\\<^bsub>G\\<lparr>carrier := H\\<rparr>\\<^esub> a= \\<one>\"\n    using aH assms group.inv_closed[OF assms(2)] ab_eq by simp\n  ultimately have \"inv\\<^bsub>G\\<lparr>carrier := H\\<rparr>\\<^esub> a = inv a\"\n    by (metis aH assms(1) contra_subsetD group.inv_inv is_group local.inv_equality)\n  moreover have \"inv\\<^bsub>G\\<lparr>carrier := H\\<rparr>\\<^esub> a \\<in> H\" \n    using aH group.inv_closed[OF assms(2)] by auto\n  ultimately show \"inv a \\<in> H\" by auto\nqed\n\n\nsubsection \\<open>Direct Products\\<close>\n\ndefinition\n  DirProd :: \"_ \\<Rightarrow> _ \\<Rightarrow> ('a \\<times> 'b) monoid\" (infixr \"\\<times>\\<times>\" 80) where\n  \"G \\<times>\\<times> H =\n    \\<lparr>carrier = carrier G \\<times> carrier H,\n     mult = (\\<lambda>(g, h) (g', h'). (g \\<otimes>\\<^bsub>G\\<^esub> g', h \\<otimes>\\<^bsub>H\\<^esub> h')),\n     one = (\\<one>\\<^bsub>G\\<^esub>, \\<one>\\<^bsub>H\\<^esub>)\\<rparr>\"\n\nlemma DirProd_monoid:\n  assumes \"monoid G\" and \"monoid H\"\n  shows \"monoid (G \\<times>\\<times> H)\"\nproof -\n  interpret G: monoid G by fact\n  interpret H: monoid H by fact\n  from assms\n  show ?thesis by (unfold monoid_def DirProd_def, auto)\nqed\n\n\ntext\\<open>Does not use the previous result because it's easier just to use auto.\\<close>\nlemma DirProd_group:\n  assumes \"group G\" and \"group H\"\n  shows \"group (G \\<times>\\<times> H)\"\nproof -\n  interpret G: group G by fact\n  interpret H: group H by fact\n  show ?thesis by (rule groupI)\n     (auto intro: G.m_assoc H.m_assoc G.l_inv H.l_inv\n           simp add: DirProd_def)\nqed\n\nlemma carrier_DirProd [simp]: \"carrier (G \\<times>\\<times> H) = carrier G \\<times> carrier H\"\n  by (simp add: DirProd_def)\n\nlemma one_DirProd [simp]: \"\\<one>\\<^bsub>G \\<times>\\<times> H\\<^esub> = (\\<one>\\<^bsub>G\\<^esub>, \\<one>\\<^bsub>H\\<^esub>)\"\n  by (simp add: DirProd_def)\n\nlemma mult_DirProd [simp]: \"(g, h) \\<otimes>\\<^bsub>(G \\<times>\\<times> H)\\<^esub> (g', h') = (g \\<otimes>\\<^bsub>G\\<^esub> g', h \\<otimes>\\<^bsub>H\\<^esub> h')\"\n  by (simp add: DirProd_def)\n\nlemma mult_DirProd': \"x \\<otimes>\\<^bsub>(G \\<times>\\<times> H)\\<^esub> y = (fst x \\<otimes>\\<^bsub>G\\<^esub> fst y, snd x \\<otimes>\\<^bsub>H\\<^esub> snd y)\"\n  by (subst mult_DirProd [symmetric]) simp\n\nlemma DirProd_assoc: \"(G \\<times>\\<times> H \\<times>\\<times> I) = (G \\<times>\\<times> (H \\<times>\\<times> I))\"\n  by auto\n\nlemma inv_DirProd [simp]:\n  assumes \"group G\" and \"group H\"\n  assumes g: \"g \\<in> carrier G\"\n      and h: \"h \\<in> carrier H\"\n  shows \"m_inv (G \\<times>\\<times> H) (g, h) = (inv\\<^bsub>G\\<^esub> g, inv\\<^bsub>H\\<^esub> h)\"\nproof -\n  interpret G: group G by fact\n  interpret H: group H by fact\n  interpret Prod: group \"G \\<times>\\<times> H\"\n    by (auto intro: DirProd_group group.intro group.axioms assms)\n  show ?thesis by (simp add: Prod.inv_equality g h)\nqed\n\nlemma DirProd_subgroups :\n  assumes \"group G\"\n    and \"subgroup H G\"\n    and \"group K\"\n    and \"subgroup I K\"\n  shows \"subgroup (H \\<times> I) (G \\<times>\\<times> K)\"\nproof (intro group.group_incl_imp_subgroup[OF DirProd_group[OF assms(1)assms(3)]])\n  have \"H \\<subseteq> carrier G\" \"I \\<subseteq> carrier K\" using subgroup.subset assms by blast+\n  thus \"(H \\<times> I) \\<subseteq> carrier (G \\<times>\\<times> K)\" unfolding DirProd_def by auto\n  have \"Group.group ((G\\<lparr>carrier := H\\<rparr>) \\<times>\\<times> (K\\<lparr>carrier := I\\<rparr>))\"\n    using DirProd_group[OF subgroup.subgroup_is_group[OF assms(2)assms(1)]\n        subgroup.subgroup_is_group[OF assms(4)assms(3)]].\n  moreover have \"((G\\<lparr>carrier := H\\<rparr>) \\<times>\\<times> (K\\<lparr>carrier := I\\<rparr>)) = ((G \\<times>\\<times> K)\\<lparr>carrier := H \\<times> I\\<rparr>)\"\n    unfolding DirProd_def using assms by simp\n  ultimately show \"Group.group ((G \\<times>\\<times> K)\\<lparr>carrier := H \\<times> I\\<rparr>)\" by simp\nqed\n\nsubsection \\<open>Homomorphisms (mono and epi) and Isomorphisms\\<close>\n\ndefinition\n  hom :: \"_ => _ => ('a => 'b) set\" where\n  \"hom G H =\n    {h. h \\<in> carrier G \\<rightarrow> carrier H \\<and>\n      (\\<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\nlemma homI:\n  \"\\<lbrakk>\\<And>x. x \\<in> carrier G \\<Longrightarrow> h x \\<in> carrier H;\n    \\<And>x y. \\<lbrakk>x \\<in> carrier G; y \\<in> carrier G\\<rbrakk> \\<Longrightarrow> h (x \\<otimes>\\<^bsub>G\\<^esub> y) = h x \\<otimes>\\<^bsub>H\\<^esub> h y\\<rbrakk> \\<Longrightarrow> h \\<in> hom G H\"\n  by (auto simp: hom_def)\n\nlemma hom_carrier: \"h \\<in> hom G H \\<Longrightarrow> h ` carrier G \\<subseteq> carrier H\"\n  by (auto simp: hom_def)\n\nlemma hom_in_carrier: \"\\<lbrakk>h \\<in> hom G H; x \\<in> carrier G\\<rbrakk> \\<Longrightarrow> h x \\<in> carrier H\"\n  by (auto simp: hom_def)\n\nlemma hom_compose:\n  \"\\<lbrakk> f \\<in> hom G H; g \\<in> hom H I \\<rbrakk> \\<Longrightarrow> g \\<circ> f \\<in> hom G I\"\n  unfolding hom_def by (auto simp add: Pi_iff)\n\nlemma (in group) hom_restrict:\n  assumes \"h \\<in> hom G H\" and \"\\<And>g. g \\<in> carrier G \\<Longrightarrow> h g = t g\" shows \"t \\<in> hom G H\"\n  using assms unfolding hom_def by (auto simp add: Pi_iff)\n\nlemma (in group) hom_compose:\n  \"[|h \\<in> hom G H; i \\<in> hom H I|] ==> compose (carrier G) i h \\<in> hom G I\"\nby (fastforce simp add: hom_def compose_def)\n\nlemma (in group) restrict_hom_iff [simp]:\n  \"(\\<lambda>x. if x \\<in> carrier G then f x else g x) \\<in> hom G H \\<longleftrightarrow> f \\<in> hom G H\"\n  by (simp add: hom_def Pi_iff)\n\ndefinition iso :: \"_ => _ => ('a => 'b) set\"\n  where \"iso G H = {h. h \\<in> hom G H \\<and> bij_betw h (carrier G) (carrier H)}\"\n\ndefinition is_iso :: \"_ \\<Rightarrow> _ \\<Rightarrow> bool\" (infixr \"\\<cong>\" 60)\n  where \"G \\<cong> H = (iso G H  \\<noteq> {})\"\n\ndefinition mon where \"mon G H = {f \\<in> hom G H. inj_on f (carrier G)}\"\n\ndefinition epi where \"epi G H = {f \\<in> hom G H. f ` (carrier G) = carrier H}\"\n\nlemma isoI:\n  \"\\<lbrakk>h \\<in> hom G H; bij_betw h (carrier G) (carrier H)\\<rbrakk> \\<Longrightarrow> h \\<in> iso G H\"\n  by (auto simp: iso_def)\n\nlemma is_isoI: \"h \\<in> iso G H \\<Longrightarrow> G \\<cong> H\"\n  using is_iso_def by auto\n\nlemma epi_iff_subset:\n   \"f \\<in> epi G G' \\<longleftrightarrow> f \\<in> hom G G' \\<and> carrier G' \\<subseteq> f ` carrier G\"\n  by (auto simp: epi_def hom_def)\n\nlemma iso_iff_mon_epi: \"f \\<in> iso G H \\<longleftrightarrow> f \\<in> mon G H \\<and> f \\<in> epi G H\"\n  by (auto simp: iso_def mon_def epi_def bij_betw_def)\n\nlemma iso_set_refl: \"(\\<lambda>x. x) \\<in> iso G G\"\n  by (simp add: iso_def hom_def inj_on_def bij_betw_def Pi_def)\n\nlemma id_iso: \"id \\<in> iso G G\"\n  by (simp add: iso_def hom_def inj_on_def bij_betw_def Pi_def)\n\ncorollary iso_refl [simp]: \"G \\<cong> G\"\n  using iso_set_refl unfolding is_iso_def by auto\n\nlemma iso_iff:\n   \"h \\<in> iso G H \\<longleftrightarrow> h \\<in> hom G H \\<and> h ` (carrier G) = carrier H \\<and> inj_on h (carrier G)\"\n  by (auto simp: iso_def hom_def bij_betw_def)\n\nlemma iso_imp_homomorphism:\n   \"h \\<in> iso G H \\<Longrightarrow> h \\<in> hom G H\"\n  by (simp add: iso_iff)\n\nlemma trivial_hom:\n   \"group H \\<Longrightarrow> (\\<lambda>x. one H) \\<in> hom G H\"\n  by (auto simp: hom_def Group.group_def)\n\nlemma (in group) hom_eq:\n  assumes \"f \\<in> hom G H\" \"\\<And>x. x \\<in> carrier G \\<Longrightarrow> f' x = f x\"\n  shows \"f' \\<in> hom G H\"\n  using assms by (auto simp: hom_def)\n\nlemma (in group) iso_eq:\n  assumes \"f \\<in> iso G H\" \"\\<And>x. x \\<in> carrier G \\<Longrightarrow> f' x = f x\"\n  shows \"f' \\<in> iso G H\"\n  using assms  by (fastforce simp: iso_def inj_on_def bij_betw_def hom_eq image_iff)\n\nlemma (in group) iso_set_sym:\n  assumes \"h \\<in> iso G H\"\n  shows \"inv_into (carrier G) h \\<in> iso H G\"\nproof -\n  have h: \"h \\<in> hom G H\" \"bij_betw h (carrier G) (carrier H)\"\n    using assms by (auto simp add: iso_def bij_betw_inv_into)\n  then have HG: \"bij_betw (inv_into (carrier G) h) (carrier H) (carrier G)\"\n    by (simp add: bij_betw_inv_into)\n  have \"inv_into (carrier G) h \\<in> hom H G\"\n    unfolding hom_def\n  proof safe\n    show *: \"\\<And>x. x \\<in> carrier H \\<Longrightarrow> inv_into (carrier G) h x \\<in> carrier G\"\n      by (meson HG bij_betwE)\n    show \"inv_into (carrier G) h (x \\<otimes>\\<^bsub>H\\<^esub> y) = inv_into (carrier G) h x \\<otimes> inv_into (carrier G) h y\"\n      if \"x \\<in> carrier H\" \"y \\<in> carrier H\" for x y\n    proof (rule inv_into_f_eq)\n      show \"inj_on h (carrier G)\"\n        using bij_betw_def h(2) by blast\n      show \"inv_into (carrier G) h x \\<otimes> inv_into (carrier G) h y \\<in> carrier G\"\n        by (simp add: * that)\n      show \"h (inv_into (carrier G) h x \\<otimes> inv_into (carrier G) h y) = x \\<otimes>\\<^bsub>H\\<^esub> y\"\n        using h bij_betw_inv_into_right [of h] unfolding hom_def by (simp add: \"*\" that)\n    qed\n  qed\n  then show ?thesis\n    by (simp add: Group.iso_def bij_betw_inv_into h)\nqed\n\ncorollary (in group) iso_sym: \"G \\<cong> H \\<Longrightarrow> H \\<cong> G\"\n  using iso_set_sym unfolding is_iso_def by auto\n\nlemma iso_set_trans:\n  \"\\<lbrakk>h \\<in> Group.iso G H; i \\<in> Group.iso H I\\<rbrakk> \\<Longrightarrow> i \\<circ> h \\<in> Group.iso G I\"\n  by (force simp: iso_def hom_compose intro: bij_betw_trans)\n\ncorollary iso_trans [trans]: \"\\<lbrakk>G \\<cong> H ; H \\<cong> I\\<rbrakk> \\<Longrightarrow> G \\<cong> I\"\n  using iso_set_trans unfolding is_iso_def by blast\n\nlemma iso_same_card: \"G \\<cong> H \\<Longrightarrow> card (carrier G) = card (carrier H)\"\n  using bij_betw_same_card  unfolding is_iso_def iso_def by auto\n\nlemma iso_finite: \"G \\<cong> H \\<Longrightarrow> finite(carrier G) \\<longleftrightarrow> finite(carrier H)\"\n  by (auto simp: is_iso_def iso_def bij_betw_finite)\n\nlemma mon_compose:\n   \"\\<lbrakk>f \\<in> mon G H; g \\<in> mon H K\\<rbrakk> \\<Longrightarrow> (g \\<circ> f) \\<in> mon G K\"\n  by (auto simp: mon_def intro: hom_compose comp_inj_on inj_on_subset [OF _ hom_carrier])\n\nlemma mon_compose_rev:\n   \"\\<lbrakk>f \\<in> hom G H; g \\<in> hom H K; (g \\<circ> f) \\<in> mon G K\\<rbrakk> \\<Longrightarrow> f \\<in> mon G H\"\n  using inj_on_imageI2 by (auto simp: mon_def)\n\nlemma epi_compose:\n   \"\\<lbrakk>f \\<in> epi G H; g \\<in> epi H K\\<rbrakk> \\<Longrightarrow> (g \\<circ> f) \\<in> epi G K\"\n  using hom_compose by (force simp: epi_def hom_compose simp flip: image_image)\n\nlemma epi_compose_rev:\n   \"\\<lbrakk>f \\<in> hom G H; g \\<in> hom H K; (g \\<circ> f) \\<in> epi G K\\<rbrakk> \\<Longrightarrow> g \\<in> epi H K\"\n  by (fastforce simp: epi_def hom_def Pi_iff image_def set_eq_iff)\n\nlemma iso_compose_rev:\n   \"\\<lbrakk>f \\<in> hom G H; g \\<in> hom H K; (g \\<circ> f) \\<in> iso G K\\<rbrakk> \\<Longrightarrow> f \\<in> mon G H \\<and> g \\<in> epi H K\"\n  unfolding iso_iff_mon_epi using mon_compose_rev epi_compose_rev by blast\n\nlemma epi_iso_compose_rev:\n  assumes \"f \\<in> epi G H\" \"g \\<in> hom H K\" \"(g \\<circ> f) \\<in> iso G K\"\n  shows \"f \\<in> iso G H \\<and> g \\<in> iso H K\"\nproof\n  show \"f \\<in> iso G H\"\n    by (metis (no_types, lifting) assms epi_def iso_compose_rev iso_iff_mon_epi mem_Collect_eq)\n  then have \"f \\<in> hom G H \\<and> bij_betw f (carrier G) (carrier H)\"\n    using Group.iso_def \\<open>f \\<in> Group.iso G H\\<close> by blast\n  then have \"bij_betw g (carrier H) (carrier K)\"\n    using Group.iso_def assms(3) bij_betw_comp_iff by blast\n  then show \"g \\<in> iso H K\"\n    using Group.iso_def assms(2) by blast\nqed\n\nlemma mon_left_invertible:\n   \"\\<lbrakk>f \\<in> hom G H; \\<And>x. x \\<in> carrier G \\<Longrightarrow> g(f x) = x\\<rbrakk> \\<Longrightarrow> f \\<in> mon G H\"\n  by (simp add: mon_def inj_on_def) metis\n\nlemma epi_right_invertible:\n   \"\\<lbrakk>g \\<in> hom H G; f \\<in> carrier G \\<rightarrow> carrier H; \\<And>x. x \\<in> carrier G \\<Longrightarrow> g(f x) = x\\<rbrakk> \\<Longrightarrow> g \\<in> epi H G\"\n  by (force simp: Pi_iff epi_iff_subset image_subset_iff_funcset subset_iff)\n\nlemma (in monoid) hom_imp_img_monoid: \\<^marker>\\<open>contributor \\<open>Paulo Em\u00edlio de Vilhena\\<close>\\<close>\n  assumes \"h \\<in> hom G H\"\n  shows \"monoid (H \\<lparr> carrier := h ` (carrier G), one := h \\<one>\\<^bsub>G\\<^esub> \\<rparr>)\" (is \"monoid ?h_img\")\nproof (rule monoidI)\n  show \"\\<one>\\<^bsub>?h_img\\<^esub> \\<in> carrier ?h_img\"\n    by auto\nnext\n  fix x y z assume \"x \\<in> carrier ?h_img\" \"y \\<in> carrier ?h_img\" \"z \\<in> carrier ?h_img\"\n  then obtain g1 g2 g3\n    where g1: \"g1 \\<in> carrier G\" \"x = h g1\"\n      and g2: \"g2 \\<in> carrier G\" \"y = h g2\"\n      and g3: \"g3 \\<in> carrier G\" \"z = h g3\"\n    using image_iff[where ?f = h and ?A = \"carrier G\"] by auto\n  have aux_lemma:\n    \"\\<And>a b. \\<lbrakk> a \\<in> carrier G; b \\<in> carrier G \\<rbrakk> \\<Longrightarrow> h a \\<otimes>\\<^bsub>(?h_img)\\<^esub> h b = h (a \\<otimes> b)\"\n    using assms unfolding hom_def by auto\n\n  show \"x \\<otimes>\\<^bsub>(?h_img)\\<^esub> \\<one>\\<^bsub>(?h_img)\\<^esub> = x\"\n    using aux_lemma[OF g1(1) one_closed] g1(2) r_one[OF g1(1)] by simp\n\n  show \"\\<one>\\<^bsub>(?h_img)\\<^esub> \\<otimes>\\<^bsub>(?h_img)\\<^esub> x = x\"\n    using aux_lemma[OF one_closed g1(1)] g1(2) l_one[OF g1(1)] by simp\n\n  have \"x \\<otimes>\\<^bsub>(?h_img)\\<^esub> y = h (g1 \\<otimes> g2)\"\n    using aux_lemma g1 g2 by auto\n  thus \"x \\<otimes>\\<^bsub>(?h_img)\\<^esub> y \\<in> carrier ?h_img\"\n    using g1(1) g2(1) by simp\n\n  have \"(x \\<otimes>\\<^bsub>(?h_img)\\<^esub> y) \\<otimes>\\<^bsub>(?h_img)\\<^esub> z = h ((g1 \\<otimes> g2) \\<otimes> g3)\"\n    using aux_lemma g1 g2 g3 by auto\n  also have \" ... = h (g1 \\<otimes> (g2 \\<otimes> g3))\"\n    using m_assoc[OF g1(1) g2(1) g3(1)] by simp\n  also have \" ... = x \\<otimes>\\<^bsub>(?h_img)\\<^esub> (y \\<otimes>\\<^bsub>(?h_img)\\<^esub> z)\"\n    using aux_lemma g1 g2 g3 by auto\n  finally show \"(x \\<otimes>\\<^bsub>(?h_img)\\<^esub> y) \\<otimes>\\<^bsub>(?h_img)\\<^esub> z = x \\<otimes>\\<^bsub>(?h_img)\\<^esub> (y \\<otimes>\\<^bsub>(?h_img)\\<^esub> z)\" .\nqed\n\nlemma (in group) hom_imp_img_group: \\<^marker>\\<open>contributor \\<open>Paulo Em\u00edlio de Vilhena\\<close>\\<close>\n  assumes \"h \\<in> hom G H\"\n  shows \"group (H \\<lparr> carrier := h ` (carrier G), one := h \\<one>\\<^bsub>G\\<^esub> \\<rparr>)\" (is \"group ?h_img\")\nproof -\n  interpret monoid ?h_img\n    using hom_imp_img_monoid[OF assms] .\n\n  show ?thesis\n  proof (unfold_locales)\n    show \"carrier ?h_img \\<subseteq> Units ?h_img\"\n    proof (auto simp add: Units_def)\n      have aux_lemma:\n        \"\\<And>g1 g2. \\<lbrakk> g1 \\<in> carrier G; g2 \\<in> carrier G \\<rbrakk> \\<Longrightarrow> h g1 \\<otimes>\\<^bsub>H\\<^esub> h g2 = h (g1 \\<otimes> g2)\"\n        using assms unfolding hom_def by auto\n\n      fix g1 assume g1: \"g1 \\<in> carrier G\"\n      thus \"\\<exists>g2 \\<in> carrier G. (h g2) \\<otimes>\\<^bsub>H\\<^esub> (h g1) = h \\<one> \\<and> (h g1) \\<otimes>\\<^bsub>H\\<^esub> (h g2) = h \\<one>\"\n        using aux_lemma[OF g1 inv_closed[OF g1]]\n              aux_lemma[OF inv_closed[OF g1] g1]\n              inv_closed by auto\n    qed\n  qed\nqed\n\nlemma (in group) iso_imp_group: \\<^marker>\\<open>contributor \\<open>Paulo Em\u00edlio de Vilhena\\<close>\\<close>\n  assumes \"G \\<cong> H\" and \"monoid H\"\n  shows \"group H\"\nproof -\n  obtain \\<phi> where phi: \"\\<phi> \\<in> iso G H\" \"inv_into (carrier G) \\<phi> \\<in> iso H G\"\n    using iso_set_sym assms unfolding is_iso_def by blast\n  define \\<psi> where psi_def: \"\\<psi> = inv_into (carrier G) \\<phi>\"\n\n  have surj: \"\\<phi> ` (carrier G) = (carrier H)\" \"\\<psi> ` (carrier H) = (carrier G)\"\n   and inj: \"inj_on \\<phi> (carrier G)\" \"inj_on \\<psi> (carrier H)\"\n   and phi_hom: \"\\<And>g1 g2. \\<lbrakk> g1 \\<in> carrier G; g2 \\<in> carrier G \\<rbrakk> \\<Longrightarrow> \\<phi> (g1 \\<otimes> g2) = (\\<phi> g1) \\<otimes>\\<^bsub>H\\<^esub> (\\<phi> g2)\"\n   and psi_hom: \"\\<And>h1 h2. \\<lbrakk> h1 \\<in> carrier H; h2 \\<in> carrier H \\<rbrakk> \\<Longrightarrow> \\<psi> (h1 \\<otimes>\\<^bsub>H\\<^esub> h2) = (\\<psi> h1) \\<otimes> (\\<psi> h2)\"\n   using phi psi_def unfolding iso_def bij_betw_def hom_def by auto\n\n  have phi_one: \"\\<phi> \\<one> = \\<one>\\<^bsub>H\\<^esub>\"\n  proof -\n    have \"(\\<phi> \\<one>) \\<otimes>\\<^bsub>H\\<^esub> \\<one>\\<^bsub>H\\<^esub> = (\\<phi> \\<one>) \\<otimes>\\<^bsub>H\\<^esub> (\\<phi> \\<one>)\"\n      by (metis assms(2) image_eqI monoid.r_one one_closed phi_hom r_one surj(1))\n    thus ?thesis\n      by (metis (no_types, opaque_lifting) Units_eq Units_one_closed assms(2) f_inv_into_f imageI\n          monoid.l_one monoid.one_closed phi_hom psi_def r_one surj)\n  qed\n\n  have \"carrier H \\<subseteq> Units H\"\n  proof\n    fix h assume h: \"h \\<in> carrier H\"\n    let ?inv_h = \"\\<phi> (inv (\\<psi> h))\"\n    have \"h \\<otimes>\\<^bsub>H\\<^esub> ?inv_h = \\<phi> (\\<psi> h) \\<otimes>\\<^bsub>H\\<^esub> ?inv_h\"\n      by (simp add: f_inv_into_f h psi_def surj(1))\n    also have \" ... = \\<phi> ((\\<psi> h) \\<otimes> inv (\\<psi> h))\"\n      by (metis h imageI inv_closed phi_hom surj(2))\n    also have \" ... = \\<phi> \\<one>\"\n      by (simp add: h inv_into_into psi_def surj(1))\n    finally have 1: \"h \\<otimes>\\<^bsub>H\\<^esub> ?inv_h = \\<one>\\<^bsub>H\\<^esub>\"\n      using phi_one by simp\n\n    have \"?inv_h \\<otimes>\\<^bsub>H\\<^esub> h = ?inv_h \\<otimes>\\<^bsub>H\\<^esub> \\<phi> (\\<psi> h)\"\n      by (simp add: f_inv_into_f h psi_def surj(1))\n    also have \" ... = \\<phi> (inv (\\<psi> h) \\<otimes> (\\<psi> h))\"\n      by (metis h imageI inv_closed phi_hom surj(2))\n    also have \" ... = \\<phi> \\<one>\"\n      by (simp add: h inv_into_into psi_def surj(1))\n    finally have 2: \"?inv_h \\<otimes>\\<^bsub>H\\<^esub> h = \\<one>\\<^bsub>H\\<^esub>\"\n      using phi_one by simp\n\n    thus \"h \\<in> Units H\" unfolding Units_def using 1 2 h surj by fastforce\n  qed\n  thus ?thesis unfolding group_def group_axioms_def using assms(2) by simp\nqed\n\ncorollary (in group) iso_imp_img_group: \\<^marker>\\<open>contributor \\<open>Paulo Em\u00edlio de Vilhena\\<close>\\<close>\n  assumes \"h \\<in> iso G H\"\n  shows \"group (H \\<lparr> one := h \\<one> \\<rparr>)\"\nproof -\n  let ?h_img = \"H \\<lparr> carrier := h ` (carrier G), one := h \\<one> \\<rparr>\"\n  have \"h \\<in> iso G ?h_img\"\n    using assms unfolding iso_def hom_def bij_betw_def by auto\n  hence \"G \\<cong> ?h_img\"\n    unfolding is_iso_def by auto\n  hence \"group ?h_img\"\n    using iso_imp_group[of ?h_img] hom_imp_img_monoid[of h H] assms unfolding iso_def by simp\n  moreover have \"carrier H = carrier ?h_img\"\n    using assms unfolding iso_def bij_betw_def by simp\n  hence \"H \\<lparr> one := h \\<one> \\<rparr> = ?h_img\"\n    by simp\n  ultimately show ?thesis by simp\nqed\n\nsubsubsection \\<open>HOL Light's concept of an isomorphism pair\\<close>\n\ndefinition group_isomorphisms\n  where\n \"group_isomorphisms G H f g \\<equiv>\n        f \\<in> hom G H \\<and> g \\<in> hom H G \\<and>\n        (\\<forall>x \\<in> carrier G. g(f x) = x) \\<and>\n        (\\<forall>y \\<in> carrier H. f(g y) = y)\"\n\nlemma group_isomorphisms_sym: \"group_isomorphisms G H f g \\<Longrightarrow> group_isomorphisms H G g f\"\n  by (auto simp: group_isomorphisms_def)\n\nlemma group_isomorphisms_imp_iso: \"group_isomorphisms G H f g \\<Longrightarrow> f \\<in> iso G H\"\nby (auto simp: iso_def inj_on_def image_def group_isomorphisms_def hom_def bij_betw_def Pi_iff, metis+)\n\nlemma (in group) iso_iff_group_isomorphisms:\n  \"f \\<in> iso G H \\<longleftrightarrow> (\\<exists>g. group_isomorphisms G H f g)\"\nproof safe\n  show \"\\<exists>g. group_isomorphisms G H f g\" if \"f \\<in> Group.iso G H\"\n    unfolding group_isomorphisms_def\n  proof (intro exI conjI)\n    let ?g = \"inv_into (carrier G) f\"\n    show \"\\<forall>x\\<in>carrier G. ?g (f x) = x\"\n      by (metis (no_types, lifting) Group.iso_def bij_betw_inv_into_left mem_Collect_eq that)\n    show \"\\<forall>y\\<in>carrier H. f (?g y) = y\"\n      by (metis (no_types, lifting) Group.iso_def bij_betw_inv_into_right mem_Collect_eq that)\n  qed (use Group.iso_def iso_set_sym that in \\<open>blast+\\<close>)\nnext\n  fix g\n  assume \"group_isomorphisms G H f g\"\n  then show \"f \\<in> Group.iso G H\"\n    by (auto simp: iso_def group_isomorphisms_def hom_in_carrier intro: bij_betw_byWitness)\nqed\n\n\nsubsubsection \\<open>Involving direct products\\<close>\n\nlemma DirProd_commute_iso_set:\n  shows \"(\\<lambda>(x,y). (y,x)) \\<in> iso (G \\<times>\\<times> H) (H \\<times>\\<times> G)\"\n  by (auto simp add: iso_def hom_def inj_on_def bij_betw_def)\n\ncorollary DirProd_commute_iso :\n\"(G \\<times>\\<times> H) \\<cong> (H \\<times>\\<times> G)\"\n  using DirProd_commute_iso_set unfolding is_iso_def by blast\n\nlemma DirProd_assoc_iso_set:\n  shows \"(\\<lambda>(x,y,z). (x,(y,z))) \\<in> iso (G \\<times>\\<times> H \\<times>\\<times> I) (G \\<times>\\<times> (H \\<times>\\<times> I))\"\nby (auto simp add: iso_def hom_def inj_on_def bij_betw_def)\n\nlemma (in group) DirProd_iso_set_trans:\n  assumes \"g \\<in> iso G G2\"\n    and \"h \\<in> iso H I\"\n  shows \"(\\<lambda>(x,y). (g x, h y)) \\<in> iso (G \\<times>\\<times> H) (G2 \\<times>\\<times> I)\"\nproof-\n  have \"(\\<lambda>(x,y). (g x, h y)) \\<in> hom (G \\<times>\\<times> H) (G2 \\<times>\\<times> I)\"\n    using assms unfolding iso_def hom_def by auto\n  moreover have \" inj_on (\\<lambda>(x,y). (g x, h y)) (carrier (G \\<times>\\<times> H))\"\n    using assms unfolding iso_def DirProd_def bij_betw_def inj_on_def by auto\n  moreover have \"(\\<lambda>(x, y). (g x, h y)) ` carrier (G \\<times>\\<times> H) = carrier (G2 \\<times>\\<times> I)\"\n    using assms unfolding iso_def bij_betw_def image_def DirProd_def by fastforce\n  ultimately show \"(\\<lambda>(x,y). (g x, h y)) \\<in> iso (G \\<times>\\<times> H) (G2 \\<times>\\<times> I)\"\n    unfolding iso_def bij_betw_def by auto\nqed\n\ncorollary (in group) DirProd_iso_trans :\n  assumes \"G \\<cong> G2\" and \"H \\<cong> I\"\n  shows \"G \\<times>\\<times> H \\<cong> G2 \\<times>\\<times> I\"\n  using DirProd_iso_set_trans assms unfolding is_iso_def by blast\n\nlemma hom_pairwise: \"f \\<in> hom G (DirProd H K) \\<longleftrightarrow> (fst \\<circ> f) \\<in> hom G H \\<and> (snd \\<circ> f) \\<in> hom G K\"\n  apply (auto simp: hom_def mult_DirProd' dest: Pi_mem)\n   apply (metis Product_Type.mem_Times_iff comp_eq_dest_lhs funcset_mem)\n  by (metis mult_DirProd prod.collapse)\n\nlemma hom_paired:\n   \"(\\<lambda>x. (f x,g x)) \\<in> hom G (DirProd H K) \\<longleftrightarrow> f \\<in> hom G H \\<and> g \\<in> hom G K\"\n  by (simp add: hom_pairwise o_def)\n\nlemma hom_paired2:\n  assumes \"group G\" \"group H\"\n  shows \"(\\<lambda>(x,y). (f x,g y)) \\<in> hom (DirProd G H) (DirProd G' H') \\<longleftrightarrow> f \\<in> hom G G' \\<and> g \\<in> hom H H'\"\n  using assms\n  by (fastforce simp: hom_def Pi_def dest!: group.is_monoid)\n\nlemma iso_paired2:\n  assumes \"group G\" \"group H\"\n  shows \"(\\<lambda>(x,y). (f x,g y)) \\<in> iso (DirProd G H) (DirProd G' H') \\<longleftrightarrow> f \\<in> iso G G' \\<and> g \\<in> iso H H'\"\n  using assms\n  by (fastforce simp add: iso_def inj_on_def bij_betw_def hom_paired2 image_paired_Times\n      times_eq_iff group_def monoid.carrier_not_empty)\n\nlemma hom_of_fst:\n  assumes \"group H\"\n  shows \"(f \\<circ> fst) \\<in> hom (DirProd G H) K \\<longleftrightarrow> f \\<in> hom G K\"\nproof -\n  interpret group H\n    by (rule assms)\n  show ?thesis\n    using one_closed by (auto simp: hom_def Pi_def)\nqed\n\nlemma hom_of_snd:\n  assumes \"group G\"\n  shows \"(f \\<circ> snd) \\<in> hom (DirProd G H) K \\<longleftrightarrow> f \\<in> hom H K\"\nproof -\n  interpret group G\n    by (rule assms)\n  show ?thesis\n    using one_closed by (auto simp: hom_def Pi_def)\nqed\n\n\nsubsection\\<open>The locale for a homomorphism between two groups\\<close>\n\ntext\\<open>Basis for homomorphism proofs: we assume two groups \\<^term>\\<open>G\\<close> and\n  \\<^term>\\<open>H\\<close>, with a homomorphism \\<^term>\\<open>h\\<close> between them\\<close>\nlocale group_hom = G?: group G + H?: group H for G (structure) and H (structure) +\n  fixes h\n  assumes homh [simp]: \"h \\<in> hom G H\"\n\ndeclare group_hom.homh [simp]\n\nlemma (in group_hom) hom_mult [simp]:\n  \"[| x \\<in> carrier G; y \\<in> carrier G |] ==> h (x \\<otimes>\\<^bsub>G\\<^esub> y) = h x \\<otimes>\\<^bsub>H\\<^esub> h y\"\nproof -\n  assume \"x \\<in> carrier G\" \"y \\<in> carrier G\"\n  with homh [unfolded hom_def] show ?thesis by simp\nqed\n\nlemma (in group_hom) hom_closed [simp]:\n  \"x \\<in> carrier G ==> h x \\<in> carrier H\"\nproof -\n  assume \"x \\<in> carrier G\"\n  with homh [unfolded hom_def] show ?thesis by auto\nqed\n\nlemma (in group_hom) one_closed: \"h \\<one> \\<in> carrier H\"\n  by simp\n\nlemma (in group_hom) hom_one [simp]: \"h \\<one> = \\<one>\\<^bsub>H\\<^esub>\"\nproof -\n  have \"h \\<one> \\<otimes>\\<^bsub>H\\<^esub> \\<one>\\<^bsub>H\\<^esub> = h \\<one> \\<otimes>\\<^bsub>H\\<^esub> h \\<one>\"\n    by (simp add: hom_mult [symmetric] del: hom_mult)\n  then show ?thesis\n    by (metis H.Units_eq H.Units_l_cancel H.one_closed local.one_closed)\nqed\n\nlemma hom_one:\n  assumes \"h \\<in> hom G H\" \"group G\" \"group H\"\n  shows \"h (one G) = one H\"\n  apply (rule group_hom.hom_one)\n  by (simp add: assms group_hom_axioms_def group_hom_def)\n\nlemma hom_mult:\n  \"\\<lbrakk>h \\<in> hom G H; x \\<in> carrier G; y \\<in> carrier G\\<rbrakk> \\<Longrightarrow> h (x \\<otimes>\\<^bsub>G\\<^esub> y) = h x \\<otimes>\\<^bsub>H\\<^esub> h y\"\n  by (auto simp: hom_def)\n\nlemma (in group_hom) inv_closed [simp]:\n  \"x \\<in> carrier G ==> h (inv x) \\<in> carrier H\"\n  by simp\n\nlemma (in group_hom) hom_inv [simp]:\n  assumes \"x \\<in> carrier G\" shows \"h (inv x) = inv\\<^bsub>H\\<^esub> (h x)\"\nproof -\n  have \"h x \\<otimes>\\<^bsub>H\\<^esub> h (inv x) = h x \\<otimes>\\<^bsub>H\\<^esub> inv\\<^bsub>H\\<^esub> (h x)\" \n    using assms by (simp flip: hom_mult)\n  with assms show ?thesis by (simp del: H.r_inv H.Units_r_inv)\nqed\n\nlemma (in group) int_pow_is_hom: \\<^marker>\\<open>contributor \\<open>Joachim Breitner\\<close>\\<close>\n  \"x \\<in> carrier G \\<Longrightarrow> (([^]) x) \\<in> hom \\<lparr> carrier = UNIV, mult = (+), one = 0::int \\<rparr> G \"\n  unfolding hom_def by (simp add: int_pow_mult)\n\nlemma (in group_hom) img_is_subgroup: \"subgroup (h ` (carrier G)) H\" \\<^marker>\\<open>contributor \\<open>Paulo Em\u00edlio de Vilhena\\<close>\\<close>\n  apply (rule subgroupI)\n  apply (auto simp add: image_subsetI)\n  apply (metis G.inv_closed hom_inv image_iff)\n  by (metis G.monoid_axioms hom_mult image_eqI monoid.m_closed)\n\nlemma (in group_hom) subgroup_img_is_subgroup: \\<^marker>\\<open>contributor \\<open>Paulo Em\u00edlio de Vilhena\\<close>\\<close>\n  assumes \"subgroup I G\"\n  shows \"subgroup (h ` I) H\"\nproof -\n  have \"h \\<in> hom (G \\<lparr> carrier := I \\<rparr>) H\"\n    using G.subgroupE[OF assms] subgroup.mem_carrier[OF assms] homh\n    unfolding hom_def by auto\n  hence \"group_hom (G \\<lparr> carrier := I \\<rparr>) H h\"\n    using subgroup.subgroup_is_group[OF assms G.is_group] is_group\n    unfolding group_hom_def group_hom_axioms_def by simp\n  thus ?thesis\n    using group_hom.img_is_subgroup[of \"G \\<lparr> carrier := I \\<rparr>\" H h] by simp\nqed\n\nlemma (in subgroup) iso_subgroup: \\<^marker>\\<open>contributor \\<open>Jakob von Raumer\\<close>\\<close>\n  assumes \"group G\" \"group F\"\n  assumes \"\\<phi> \\<in> iso G F\"\n  shows \"subgroup (\\<phi> ` H) F\"\n  by (metis assms Group.iso_iff group_hom.intro group_hom_axioms_def group_hom.subgroup_img_is_subgroup subgroup_axioms)\n\nlemma (in group_hom) induced_group_hom: \\<^marker>\\<open>contributor \\<open>Paulo Em\u00edlio de Vilhena\\<close>\\<close>\n  assumes \"subgroup I G\"\n  shows \"group_hom (G \\<lparr> carrier := I \\<rparr>) (H \\<lparr> carrier := h ` I \\<rparr>) h\"\nproof -\n  have \"h \\<in> hom (G \\<lparr> carrier := I \\<rparr>) (H \\<lparr> carrier := h ` I \\<rparr>)\"\n    using homh subgroup.mem_carrier[OF assms] unfolding hom_def by auto\n  thus ?thesis\n    unfolding group_hom_def group_hom_axioms_def\n    using subgroup.subgroup_is_group[OF assms G.is_group]\n          subgroup.subgroup_is_group[OF subgroup_img_is_subgroup[OF assms] is_group] by simp\nqed\n\ntext \\<open>An isomorphism restricts to an isomorphism of subgroups.\\<close>\n\nlemma iso_restrict:\n  assumes \"\\<phi> \\<in> iso G F\"\n  assumes groups: \"group G\" \"group F\"\n  assumes HG: \"subgroup H G\"\n  shows \"(restrict \\<phi> H) \\<in> iso (G\\<lparr>carrier := H\\<rparr>) (F\\<lparr>carrier := \\<phi> ` H\\<rparr>)\"\nproof -\n  have \"\\<And>x y. \\<lbrakk>x \\<in> H; y \\<in> H; x \\<otimes>\\<^bsub>G\\<^esub> y \\<in> H\\<rbrakk> \\<Longrightarrow> \\<phi> (x \\<otimes>\\<^bsub>G\\<^esub> y) = \\<phi> x \\<otimes>\\<^bsub>F\\<^esub> \\<phi> y\"\n    by (meson assms hom_mult iso_imp_homomorphism subgroup.mem_carrier)\n  moreover have \"\\<And>x y. \\<lbrakk>x \\<in> H; y \\<in> H; x \\<otimes>\\<^bsub>G\\<^esub> y \\<notin> H\\<rbrakk> \\<Longrightarrow> \\<phi> x \\<otimes>\\<^bsub>F\\<^esub> \\<phi> y = undefined\"\n    by (simp add: HG subgroup.m_closed)\n  moreover have \"\\<And>x y. \\<lbrakk>x \\<in> H; y \\<in> H; \\<phi> x = \\<phi> y\\<rbrakk> \\<Longrightarrow> x = y\"\n    by (smt (verit, ccfv_SIG) assms group.iso_iff_group_isomorphisms group_isomorphisms_def subgroup.mem_carrier)\n  ultimately show ?thesis\n    by (auto simp: iso_def hom_def bij_betw_def inj_on_def)\nqed\n\nlemma (in group) canonical_inj_is_hom: \\<^marker>\\<open>contributor \\<open>Paulo Em\u00edlio de Vilhena\\<close>\\<close>\n  assumes \"subgroup H G\"\n  shows \"group_hom (G \\<lparr> carrier := H \\<rparr>) G id\"\n  unfolding group_hom_def group_hom_axioms_def hom_def\n  using subgroup.subgroup_is_group[OF assms is_group]\n        is_group subgroup.subset[OF assms] by auto\n\nlemma (in group_hom) hom_nat_pow: \\<^marker>\\<open>contributor \\<open>Paulo Em\u00edlio de Vilhena\\<close>\\<close>\n  \"x \\<in> carrier G \\<Longrightarrow> h (x [^] (n :: nat)) = (h x) [^]\\<^bsub>H\\<^esub> n\"\n  by (induction n) auto\n\nlemma (in group_hom) hom_int_pow: \\<^marker>\\<open>contributor \\<open>Paulo Em\u00edlio de Vilhena\\<close>\\<close>\n  \"x \\<in> carrier G \\<Longrightarrow> h (x [^] (n :: int)) = (h x) [^]\\<^bsub>H\\<^esub> n\"\n  using hom_nat_pow by (simp add: int_pow_def2)\n\nlemma hom_nat_pow:\n  \"\\<lbrakk>h \\<in> hom G H; x \\<in> carrier G; group G; group H\\<rbrakk> \\<Longrightarrow> h (x [^]\\<^bsub>G\\<^esub> (n :: nat)) = (h x) [^]\\<^bsub>H\\<^esub> n\"\n  by (simp add: group_hom.hom_nat_pow group_hom_axioms_def group_hom_def)\n\nlemma hom_int_pow:\n  \"\\<lbrakk>h \\<in> hom G H; x \\<in> carrier G; group G; group H\\<rbrakk> \\<Longrightarrow> h (x [^]\\<^bsub>G\\<^esub> (n :: int)) = (h x) [^]\\<^bsub>H\\<^esub> n\"\n  by (simp add: group_hom.hom_int_pow group_hom_axioms.intro group_hom_def)\n\nsubsection \\<open>Commutative Structures\\<close>\n\ntext \\<open>\n  Naming convention: multiplicative structures that are commutative\n  are called \\emph{commutative}, additive structures are called\n  \\emph{Abelian}.\n\\<close>\n\nlocale comm_monoid = monoid +\n  assumes m_comm: \"\\<lbrakk>x \\<in> carrier G; y \\<in> carrier G\\<rbrakk> \\<Longrightarrow> x \\<otimes> y = y \\<otimes> x\"\n\nlemma (in comm_monoid) m_lcomm:\n  \"\\<lbrakk>x \\<in> carrier G; y \\<in> carrier G; z \\<in> carrier G\\<rbrakk> \\<Longrightarrow>\n   x \\<otimes> (y \\<otimes> z) = y \\<otimes> (x \\<otimes> z)\"\nproof -\n  assume xyz: \"x \\<in> carrier G\"  \"y \\<in> carrier G\"  \"z \\<in> carrier G\"\n  from xyz have \"x \\<otimes> (y \\<otimes> z) = (x \\<otimes> y) \\<otimes> z\" by (simp add: m_assoc)\n  also from xyz have \"... = (y \\<otimes> x) \\<otimes> z\" by (simp add: m_comm)\n  also from xyz have \"... = y \\<otimes> (x \\<otimes> z)\" by (simp add: m_assoc)\n  finally show ?thesis .\nqed\n\nlemmas (in comm_monoid) m_ac = m_assoc m_comm m_lcomm\n\nlemma comm_monoidI:\n  fixes G (structure)\n  assumes m_closed:\n      \"!!x y. [| x \\<in> carrier G; y \\<in> carrier G |] ==> x \\<otimes> y \\<in> carrier G\"\n    and one_closed: \"\\<one> \\<in> carrier G\"\n    and m_assoc:\n      \"!!x y z. [| x \\<in> carrier G; y \\<in> carrier G; z \\<in> carrier G |] ==>\n      (x \\<otimes> y) \\<otimes> z = x \\<otimes> (y \\<otimes> z)\"\n    and l_one: \"!!x. x \\<in> carrier G ==> \\<one> \\<otimes> x = x\"\n    and m_comm:\n      \"!!x y. [| x \\<in> carrier G; y \\<in> carrier G |] ==> x \\<otimes> y = y \\<otimes> x\"\n  shows \"comm_monoid G\"\n  using l_one\n    by (auto intro!: comm_monoid.intro comm_monoid_axioms.intro monoid.intro\n             intro: assms simp: m_closed one_closed m_comm)\n\nlemma (in monoid) monoid_comm_monoidI:\n  assumes m_comm:\n      \"!!x y. [| x \\<in> carrier G; y \\<in> carrier G |] ==> x \\<otimes> y = y \\<otimes> x\"\n  shows \"comm_monoid G\"\n  by (rule comm_monoidI) (auto intro: m_assoc m_comm)\n\nlemma (in comm_monoid) submonoid_is_comm_monoid :\n  assumes \"submonoid H G\"\n  shows \"comm_monoid (G\\<lparr>carrier := H\\<rparr>)\"\nproof (intro monoid.monoid_comm_monoidI)\n  show \"monoid (G\\<lparr>carrier := H\\<rparr>)\"\n    using submonoid.submonoid_is_monoid assms comm_monoid_axioms comm_monoid_def by blast\n  show \"\\<And>x y. x \\<in> carrier (G\\<lparr>carrier := H\\<rparr>) \\<Longrightarrow> y \\<in> carrier (G\\<lparr>carrier := H\\<rparr>)\n        \\<Longrightarrow> x \\<otimes>\\<^bsub>G\\<lparr>carrier := H\\<rparr>\\<^esub> y = y \\<otimes>\\<^bsub>G\\<lparr>carrier := H\\<rparr>\\<^esub> x\" \n    by simp (meson assms m_comm submonoid.mem_carrier)\nqed\n\nlocale comm_group = comm_monoid + group\n\nlemma (in group) group_comm_groupI:\n  assumes m_comm: \"!!x y. [| x \\<in> carrier G; y \\<in> carrier G |] ==> x \\<otimes> y = y \\<otimes> x\"\n  shows \"comm_group G\"\n  by standard (simp_all add: m_comm)\n\nlemma comm_groupI:\n  fixes G (structure)\n  assumes m_closed:\n      \"!!x y. [| x \\<in> carrier G; y \\<in> carrier G |] ==> x \\<otimes> y \\<in> carrier G\"\n    and one_closed: \"\\<one> \\<in> carrier G\"\n    and m_assoc:\n      \"!!x y z. [| x \\<in> carrier G; y \\<in> carrier G; z \\<in> carrier G |] ==>\n      (x \\<otimes> y) \\<otimes> z = x \\<otimes> (y \\<otimes> z)\"\n    and m_comm:\n      \"!!x y. [| x \\<in> carrier G; y \\<in> carrier G |] ==> x \\<otimes> y = y \\<otimes> x\"\n    and l_one: \"!!x. x \\<in> carrier G ==> \\<one> \\<otimes> x = x\"\n    and l_inv_ex: \"!!x. x \\<in> carrier G ==> \\<exists>y \\<in> carrier G. y \\<otimes> x = \\<one>\"\n  shows \"comm_group G\"\n  by (fast intro: group.group_comm_groupI groupI assms)\n\nlemma comm_groupE:\n  fixes G (structure)\n  assumes \"comm_group G\"\n  shows \"\\<And>x y. \\<lbrakk> x \\<in> carrier G; y \\<in> carrier G \\<rbrakk> \\<Longrightarrow> x \\<otimes> y \\<in> carrier G\"\n    and \"\\<one> \\<in> carrier G\"\n    and \"\\<And>x y z. \\<lbrakk> x \\<in> carrier G; y \\<in> carrier G; z \\<in> carrier G \\<rbrakk> \\<Longrightarrow> (x \\<otimes> y) \\<otimes> z = x \\<otimes> (y \\<otimes> z)\"\n    and \"\\<And>x y. \\<lbrakk> x \\<in> carrier G; y \\<in> carrier G \\<rbrakk> \\<Longrightarrow> x \\<otimes> y = y \\<otimes> x\"\n    and \"\\<And>x. x \\<in> carrier G \\<Longrightarrow> \\<one> \\<otimes> x = x\"\n    and \"\\<And>x. x \\<in> carrier G \\<Longrightarrow> \\<exists>y \\<in> carrier G. y \\<otimes> x = \\<one>\"\n  apply (simp_all add: group.axioms assms comm_group.axioms comm_monoid.m_comm comm_monoid.m_ac(1))\n  by (simp_all add: Group.group.axioms(1) assms comm_group.axioms(2) monoid.m_closed group.r_inv_ex)\n\nlemma (in comm_group) inv_mult:\n  \"[| x \\<in> carrier G; y \\<in> carrier G |] ==> inv (x \\<otimes> y) = inv x \\<otimes> inv y\"\n  by (simp add: m_ac inv_mult_group)\n\nlemma (in comm_monoid) nat_pow_distrib:\n  fixes n::nat\n  assumes \"x \\<in> carrier G\" \"y \\<in> carrier G\"\n  shows \"(x \\<otimes> y) [^] n = x [^] n \\<otimes> y [^] n\"\n  by (simp add: assms pow_mult_distrib m_comm)\n\nlemma (in comm_group) int_pow_distrib:\n  assumes \"x \\<in> carrier G\" \"y \\<in> carrier G\"\n  shows \"(x \\<otimes> y) [^] (i::int) = x [^] i \\<otimes> y [^] i\"\n  by (simp add: assms int_pow_mult_distrib m_comm)\n\nlemma (in comm_monoid) hom_imp_img_comm_monoid: \\<^marker>\\<open>contributor \\<open>Paulo Em\u00edlio de Vilhena\\<close>\\<close>\n  assumes \"h \\<in> hom G H\"\n  shows \"comm_monoid (H \\<lparr> carrier := h ` (carrier G), one := h \\<one>\\<^bsub>G\\<^esub> \\<rparr>)\" (is \"comm_monoid ?h_img\")\nproof (rule monoid.monoid_comm_monoidI)\n  show \"monoid ?h_img\"\n    using hom_imp_img_monoid[OF assms] .\nnext\n  fix x y assume \"x \\<in> carrier ?h_img\" \"y \\<in> carrier ?h_img\"\n  then obtain g1 g2\n    where g1: \"g1 \\<in> carrier G\" \"x = h g1\"\n      and g2: \"g2 \\<in> carrier G\" \"y = h g2\"\n    by auto\n  have \"x \\<otimes>\\<^bsub>(?h_img)\\<^esub> y = h (g1 \\<otimes> g2)\"\n    using g1 g2 assms unfolding hom_def by auto\n  also have \" ... = h (g2 \\<otimes> g1)\"\n    using m_comm[OF g1(1) g2(1)] by simp\n  also have \" ... = y \\<otimes>\\<^bsub>(?h_img)\\<^esub> x\"\n    using g1 g2 assms unfolding hom_def by auto\n  finally show \"x \\<otimes>\\<^bsub>(?h_img)\\<^esub> y = y \\<otimes>\\<^bsub>(?h_img)\\<^esub> x\" .\nqed\n\nlemma (in comm_group) hom_group_mult:\n  assumes \"f \\<in> hom H G\" \"g \\<in> hom H G\"\n shows \"(\\<lambda>x. f x \\<otimes>\\<^bsub>G\\<^esub> g x) \\<in> hom H G\"\n    using assms by (auto simp: hom_def Pi_def m_ac)\n\nlemma (in comm_group) hom_imp_img_comm_group: \\<^marker>\\<open>contributor \\<open>Paulo Em\u00edlio de Vilhena\\<close>\\<close>\n  assumes \"h \\<in> hom G H\"\n  shows \"comm_group (H \\<lparr> carrier := h ` (carrier G), one := h \\<one>\\<^bsub>G\\<^esub> \\<rparr>)\"\n  unfolding comm_group_def\n  using hom_imp_img_group[OF assms] hom_imp_img_comm_monoid[OF assms] by simp\n\nlemma (in comm_group) iso_imp_img_comm_group: \\<^marker>\\<open>contributor \\<open>Paulo Em\u00edlio de Vilhena\\<close>\\<close>\n  assumes \"h \\<in> iso G H\"\n  shows \"comm_group (H \\<lparr> one := h \\<one>\\<^bsub>G\\<^esub> \\<rparr>)\"\nproof -\n  let ?h_img = \"H \\<lparr> carrier := h ` (carrier G), one := h \\<one> \\<rparr>\"\n  have \"comm_group ?h_img\"\n    using hom_imp_img_comm_group[of h H] assms unfolding iso_def by auto\n  moreover have \"carrier H = carrier ?h_img\"\n    using assms unfolding iso_def bij_betw_def by simp\n  hence \"H \\<lparr> one := h \\<one> \\<rparr> = ?h_img\"\n    by simp\n  ultimately show ?thesis by simp\nqed\n\nlemma (in comm_group) iso_imp_comm_group: \\<^marker>\\<open>contributor \\<open>Paulo Em\u00edlio de Vilhena\\<close>\\<close>\n  assumes \"G \\<cong> H\" \"monoid H\"\n  shows \"comm_group H\"\nproof -\n  obtain h where h: \"h \\<in> iso G H\"\n    using assms(1) unfolding is_iso_def by auto\n  hence comm_gr: \"comm_group (H \\<lparr> one := h \\<one> \\<rparr>)\"\n    using iso_imp_img_comm_group[of h H] by simp\n  hence \"\\<And>x. x \\<in> carrier H \\<Longrightarrow> h \\<one> \\<otimes>\\<^bsub>H\\<^esub> x = x\"\n    using monoid.l_one[of \"H \\<lparr> one := h \\<one> \\<rparr>\"] unfolding comm_group_def comm_monoid_def by simp\n  moreover have \"h \\<one> \\<in> carrier H\"\n    using h one_closed unfolding iso_def hom_def by auto\n  ultimately have \"h \\<one> = \\<one>\\<^bsub>H\\<^esub>\"\n    using monoid.one_unique[OF assms(2), of \"h \\<one>\"] by simp\n  hence \"H = H \\<lparr> one := h \\<one> \\<rparr>\"\n    by simp\n  thus ?thesis\n    using comm_gr by simp\nqed\n\n(*A subgroup of a subgroup is a subgroup of the group*)\nlemma (in group) incl_subgroup:\n  assumes \"subgroup J G\"\n    and \"subgroup I (G\\<lparr>carrier:=J\\<rparr>)\"\n  shows \"subgroup I G\" unfolding subgroup_def\nproof\n  have H1: \"I \\<subseteq> carrier (G\\<lparr>carrier:=J\\<rparr>)\" using assms(2) subgroup.subset by blast\n  also have H2: \"...\\<subseteq>J\" by simp\n  also  have \"...\\<subseteq>(carrier G)\"  by (simp add: assms(1) subgroup.subset)\n  finally have H: \"I \\<subseteq> carrier G\" by simp\n  have \"(\\<And>x y. \\<lbrakk>x \\<in> I ; y \\<in> I\\<rbrakk> \\<Longrightarrow> x \\<otimes> y \\<in> I)\" using assms(2) by (auto simp add: subgroup_def)\n  thus  \"I \\<subseteq> carrier G \\<and> (\\<forall>x y. x \\<in> I \\<longrightarrow> y \\<in> I \\<longrightarrow> x \\<otimes> y \\<in> I)\"  using H by blast\n  have K: \"\\<one> \\<in> I\" using assms(2) by (auto simp add: subgroup_def)\n  have \"(\\<And>x. x \\<in> I \\<Longrightarrow> inv x \\<in> I)\" using assms  subgroup.m_inv_closed H\n    by (metis H1 H2 m_inv_consistent subsetCE)\n  thus \"\\<one> \\<in> I \\<and> (\\<forall>x. x \\<in> I \\<longrightarrow> inv x \\<in> I)\" using K by blast\nqed\n\n(*A subgroup included in another subgroup is a subgroup of the subgroup*)\nlemma (in group) subgroup_incl:\n  assumes \"subgroup I G\" and \"subgroup J G\" and \"I \\<subseteq> J\"\n  shows \"subgroup I (G \\<lparr> carrier := J \\<rparr>)\"\n  using group.group_incl_imp_subgroup[of \"G \\<lparr> carrier := J \\<rparr>\" I]\n        assms(1-2)[THEN subgroup.subgroup_is_group[OF _ group_axioms]] assms(3) by auto\n\n\nsubsection \\<open>The Lattice of Subgroups of a Group\\<close>\n\ntext_raw \\<open>\\label{sec:subgroup-lattice}\\<close>\n\ntheorem (in group) subgroups_partial_order:\n  \"partial_order \\<lparr>carrier = {H. subgroup H G}, eq = (=), le = (\\<subseteq>)\\<rparr>\"\n  by standard simp_all\n\nlemma (in group) subgroup_self:\n  \"subgroup (carrier G) G\"\n  by (rule subgroupI) auto\n\nlemma (in group) subgroup_imp_group:\n  \"subgroup H G ==> group (G\\<lparr>carrier := H\\<rparr>)\"\n  by (erule subgroup.subgroup_is_group) (rule group_axioms)\n\nlemma (in group) subgroup_mult_equality:\n  \"\\<lbrakk> subgroup H G; h1 \\<in> H; h2 \\<in> H \\<rbrakk> \\<Longrightarrow>  h1 \\<otimes>\\<^bsub>G \\<lparr> carrier := H \\<rparr>\\<^esub> h2 = h1 \\<otimes> h2\"\n  unfolding subgroup_def by simp\n\ntheorem (in group) subgroups_Inter:\n  assumes subgr: \"(\\<And>H. H \\<in> A \\<Longrightarrow> subgroup H G)\"\n    and not_empty: \"A \\<noteq> {}\"\n  shows \"subgroup (\\<Inter>A) G\"\nproof (rule subgroupI)\n  from subgr [THEN subgroup.subset] and not_empty\n  show \"\\<Inter>A \\<subseteq> carrier G\" by blast\nnext\n  from subgr [THEN subgroup.one_closed]\n  show \"\\<Inter>A \\<noteq> {}\" by blast\nnext\n  fix x assume \"x \\<in> \\<Inter>A\"\n  with subgr [THEN subgroup.m_inv_closed]\n  show \"inv x \\<in> \\<Inter>A\" by blast\nnext\n  fix x y assume \"x \\<in> \\<Inter>A\" \"y \\<in> \\<Inter>A\"\n  with subgr [THEN subgroup.m_closed]\n  show \"x \\<otimes> y \\<in> \\<Inter>A\" by blast\nqed\n\nlemma (in group) subgroups_Inter_pair :\n  assumes \"subgroup I G\" \"subgroup J G\" shows \"subgroup (I\\<inter>J) G\" \n  using subgroups_Inter[ where ?A = \"{I,J}\"] assms by auto\n\ntheorem (in group) subgroups_complete_lattice:\n  \"complete_lattice \\<lparr>carrier = {H. subgroup H G}, eq = (=), le = (\\<subseteq>)\\<rparr>\"\n    (is \"complete_lattice ?L\")\nproof (rule partial_order.complete_lattice_criterion1)\n  show \"partial_order ?L\" by (rule subgroups_partial_order)\nnext\n  have \"greatest ?L (carrier G) (carrier ?L)\"\n    by (unfold greatest_def) (simp add: subgroup.subset subgroup_self)\n  then show \"\\<exists>G. greatest ?L G (carrier ?L)\" ..\nnext\n  fix A\n  assume L: \"A \\<subseteq> carrier ?L\" and non_empty: \"A \\<noteq> {}\"\n  then have Int_subgroup: \"subgroup (\\<Inter>A) G\"\n    by (fastforce intro: subgroups_Inter)\n  have \"greatest ?L (\\<Inter>A) (Lower ?L A)\" (is \"greatest _ ?Int _\")\n  proof (rule greatest_LowerI)\n    fix H\n    assume H: \"H \\<in> A\"\n    with L have subgroupH: \"subgroup H G\" by auto\n    from subgroupH have groupH: \"group (G \\<lparr>carrier := H\\<rparr>)\" (is \"group ?H\")\n      by (rule subgroup_imp_group)\n    from groupH have monoidH: \"monoid ?H\"\n      by (rule group.is_monoid)\n    from H have Int_subset: \"?Int \\<subseteq> H\" by fastforce\n    then show \"le ?L ?Int H\" by simp\n  next\n    fix H\n    assume H: \"H \\<in> Lower ?L A\"\n    with L Int_subgroup show \"le ?L H ?Int\"\n      by (fastforce simp: Lower_def intro: Inter_greatest)\n  next\n    show \"A \\<subseteq> carrier ?L\" by (rule L)\n  next\n    show \"?Int \\<in> carrier ?L\" by simp (rule Int_subgroup)\n  qed\n  then show \"\\<exists>I. greatest ?L I (Lower ?L A)\" ..\nqed\n\nsubsection\\<open>The units in any monoid give rise to a group\\<close>\n\ntext \\<open>Thanks to Jeremy Avigad. The file Residues.thy provides some infrastructure to use\n  facts about the unit group within the ring locale.\n\\<close>\n\ndefinition units_of :: \"('a, 'b) monoid_scheme \\<Rightarrow> 'a monoid\"\n  where \"units_of G =\n    \\<lparr>carrier = Units G, Group.monoid.mult = Group.monoid.mult G, one  = one G\\<rparr>\"\n\nlemma (in monoid) units_group: \"group (units_of G)\"\nproof -\n  have \"\\<And>x y z. \\<lbrakk>x \\<in> Units G; y \\<in> Units G; z \\<in> Units G\\<rbrakk> \\<Longrightarrow> x \\<otimes> y \\<otimes> z = x \\<otimes> (y \\<otimes> z)\"\n    by (simp add: Units_closed m_assoc)\n  moreover have \"\\<And>x. x \\<in> Units G \\<Longrightarrow> \\<exists>y\\<in>Units G. y \\<otimes> x = \\<one>\"\n    using Units_l_inv by blast\n  ultimately show ?thesis\n    unfolding units_of_def\n    by (force intro!: groupI)\nqed\n\nlemma (in comm_monoid) units_comm_group: \"comm_group (units_of G)\"\nproof -\n  have \"\\<And>x y. \\<lbrakk>x \\<in> carrier (units_of G); y \\<in> carrier (units_of G)\\<rbrakk>\n              \\<Longrightarrow> x \\<otimes>\\<^bsub>units_of G\\<^esub> y = y \\<otimes>\\<^bsub>units_of G\\<^esub> x\"\n    by (simp add: Units_closed m_comm units_of_def)\n  then show ?thesis\n    by (rule group.group_comm_groupI [OF units_group]) auto\nqed\n\nlemma units_of_carrier: \"carrier (units_of G) = Units G\"\n  by (auto simp: units_of_def)\n\nlemma units_of_mult: \"mult (units_of G) = mult G\"\n  by (auto simp: units_of_def)\n\nlemma units_of_one: \"one (units_of G) = one G\"\n  by (auto simp: units_of_def)\n\nlemma (in monoid) units_of_inv:\n  assumes \"x \\<in> Units G\"\n  shows \"m_inv (units_of G) x = m_inv G x\"\n  by (simp add: assms group.inv_equality units_group units_of_carrier units_of_mult units_of_one)\n\nlemma units_of_units [simp] : \"Units (units_of G) = Units G\"\n  unfolding units_of_def Units_def by force\n\nlemma (in group) surj_const_mult: \"a \\<in> carrier G \\<Longrightarrow> (\\<lambda>x. a \\<otimes> x) ` carrier G = carrier G\"\n  apply (auto simp add: image_def)\n  by (metis inv_closed inv_solve_left m_closed)\n\nlemma (in group) l_cancel_one [simp]: \"x \\<in> carrier G \\<Longrightarrow> a \\<in> carrier G \\<Longrightarrow> x \\<otimes> a = x \\<longleftrightarrow> a = one G\"\n  by (metis Units_eq Units_l_cancel monoid.r_one monoid_axioms one_closed)\n\nlemma (in group) r_cancel_one [simp]: \"x \\<in> carrier G \\<Longrightarrow> a \\<in> carrier G \\<Longrightarrow> a \\<otimes> x = x \\<longleftrightarrow> a = one G\"\n  by (metis monoid.l_one monoid_axioms one_closed right_cancel)\n\nlemma (in group) l_cancel_one' [simp]: \"x \\<in> carrier G \\<Longrightarrow> a \\<in> carrier G \\<Longrightarrow> x = x \\<otimes> a \\<longleftrightarrow> a = one G\"\n  using l_cancel_one by fastforce\n\nlemma (in group) r_cancel_one' [simp]: \"x \\<in> carrier G \\<Longrightarrow> a \\<in> carrier G \\<Longrightarrow> x = a \\<otimes> x \\<longleftrightarrow> a = one G\"\n  using r_cancel_one by fastforce\n\ndeclare pow_nat [simp] (*causes looping if added above, especially with int_pow_def2*)\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/Group.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267796346599, "lm_q2_score": 0.8418256512199033, "lm_q1q2_score": 0.731400669563239}}
{"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_ISortSorts\nimports \"../../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 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 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  \"ordered (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_ISortSorts.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096181702032, "lm_q2_score": 0.7981867777396212, "lm_q1q2_score": 0.7312265841835492}}
{"text": "section \\<open>Szemer\u00e9di's Regularity Lemma\\<close>\n\ntheory Szemeredi\n  imports Complex_Main \"HOL-Library.Disjoint_Sets\" \"Girth_Chromatic.Ugraphs\" \"HOL-Analysis.Convex\"\n\nbegin\n\ntext\\<open>We formalise Szemer\u00e9di's Regularity Lemma, which is a major result in the study of large graphs\n(extremal graph theory).\nWe follow Yufei Zhao's notes ``Graph Theory and Additive Combinatorics'' (MIT),\nlatest version here: \\<^url>\\<open>https://yufeizhao.com/gtacbook/\\<close>\nand W.T. Gowers's notes ``Topics in Combinatorics'' (University of Cambridge, Lent 2004, Chapter 3)\n\\<^url>\\<open>https://www.dpmms.cam.ac.uk/~par31/notes/tic.pdf\\<close>.\nWe also used an earlier version of Zhao's book: \\<^url>\\<open>https://yufeizhao.com/gtac/gtac.pdf\\<close>.\\<close>\n\n\nsubsection \\<open>Partitions\\<close>\n\nsubsubsection \\<open>Partitions indexed by integers\\<close>\n\ndefinition finite_graph_partition :: \"[uvert set, uvert set set, nat] \\<Rightarrow> bool\"\n  where \"finite_graph_partition V P n \\<equiv> partition_on V P \\<and> finite P \\<and> card P = n\"\n\nlemma finite_graph_partition_0 [iff]:\n  \"finite_graph_partition V P 0 \\<longleftrightarrow> V = {} \\<and> P = {}\"\n  by (auto simp: finite_graph_partition_def partition_on_def)\n\nlemma finite_graph_partition_empty [iff]:\n  \"finite_graph_partition {} P n \\<longleftrightarrow> P = {} \\<and> n = 0\"\n  by (auto simp: finite_graph_partition_def partition_on_def)\n\nlemma finite_graph_partition_equals:\n  \"finite_graph_partition V P n \\<Longrightarrow> (\\<Union>P) = V\"\n  by (meson finite_graph_partition_def partition_on_def)\n\nlemma finite_graph_partition_subset:\n  \"\\<lbrakk>finite_graph_partition V P n; X \\<in> P\\<rbrakk> \\<Longrightarrow> X \\<subseteq> V\"\n  using finite_graph_partition_equals by blast\n\nlemma trivial_graph_partition_exists:\n  assumes \"V \\<noteq> {}\"\n  shows \"finite_graph_partition V {V} (Suc 0)\"\n  by (simp add: assms finite_graph_partition_def partition_on_space)\n\nlemma finite_graph_partition_finite:\n  assumes \"finite_graph_partition V P k\" \"finite V\" \"X \\<in> P\"\n  shows \"finite X\"\n  by (meson assms finite_graph_partition_subset infinite_super)\n\nlemma finite_graph_partition_gt0:\n  assumes \"finite_graph_partition V P k\" \"finite V\" \"X \\<in> P\"\n  shows \"card X > 0\"\n  by (metis assms card_0_eq finite_graph_partition_def finite_graph_partition_finite gr_zeroI partition_on_def)\n\nlemma card_finite_graph_partition:\n  assumes \"finite_graph_partition V P k\" \"finite V\"\n  shows \"(\\<Sum>X\\<in>P. card X) = card V\"\n  by (metis assms finite_graph_partition_def finite_graph_partition_finite product_partition)\n\nsubsubsection \\<open>Tools to combine the refinements of the partition @{term \"P i\"} for each @{term i}\\<close>\n\ntext \\<open>These are needed to retain the ``intuitive'' idea of partitions as indexed by integers.\\<close>\n\nsubsection \\<open>Edges\\<close>\n\ntext \\<open>All edges between two sets of vertices, @{term X} and @{term Y}, in a graph, @{term G}\\<close>\n\ndefinition all_edges_between :: \"nat set \\<Rightarrow> nat set \\<Rightarrow> nat set \\<times> nat set set \\<Rightarrow> (nat \\<times> nat) set\"\n  where \"all_edges_between X Y G \\<equiv> {(x,y). x\\<in>X \\<and> y\\<in>Y \\<and> {x,y} \\<in> uedges G}\"\n\nlemma all_edges_between_subset: \"all_edges_between X Y G \\<subseteq> X\\<times>Y\"\n  by (auto simp: all_edges_between_def)\n\nlemma max_all_edges_between: \n  assumes \"finite X\" \"finite Y\"\n  shows \"card (all_edges_between X Y G) \\<le> card X * card Y\"\n  by (metis assms card_mono finite_SigmaI all_edges_between_subset card_cartesian_product)\n\nlemma all_edges_between_empty [simp]:\n  \"all_edges_between {} Z G = {}\" \"all_edges_between Z {} G = {}\"\n  by (auto simp: all_edges_between_def)\n\nlemma all_edges_between_disjnt1:\n  assumes \"disjnt X Y\"\n  shows \"disjnt (all_edges_between X Z G) (all_edges_between Y Z G)\"\n  using assms by (auto simp: all_edges_between_def disjnt_iff)\n\nlemma all_edges_between_disjnt2:\n  assumes \"disjnt Y Z\"\n  shows \"disjnt (all_edges_between X Y G) (all_edges_between X Z G)\"\n  using assms by (auto simp: all_edges_between_def disjnt_iff)\n\nlemma all_edges_between_Un1:\n  \"all_edges_between (X \\<union> Y) Z G = all_edges_between X Z G \\<union> all_edges_between Y Z G\"\n  by (auto simp: all_edges_between_def)\n\nlemma all_edges_between_Un2:\n  \"all_edges_between X (Y \\<union> Z) G = all_edges_between X Y G \\<union> all_edges_between X Z G\"\n  by (auto simp: all_edges_between_def)\n\nlemma finite_all_edges_between:\n  assumes \"finite X\" \"finite Y\"\n  shows \"finite (all_edges_between X Y G)\"\n  by (meson all_edges_between_subset assms finite_cartesian_product finite_subset)\n\nsubsection \\<open>Edge Density and Regular Pairs\\<close>\n\ntext \\<open>The edge density between two sets of vertices, @{term X} and @{term Y}, in @{term G}.\n      Authors disagree on whether the sets are assumed to be disjoint!.\n      Quite a few authors assume disjointness, e.g. Malliaris and Shelah \\<^url>\\<open>https://www.jstor.org/stable/23813167\\<close>.\\<close>\ndefinition \"edge_density X Y G \\<equiv> card(all_edges_between X Y G) / (card X * card Y)\"\n\nlemma edge_density_ge0: \"edge_density X Y G \\<ge> 0\"\n  by (auto simp: edge_density_def)\n\nlemma edge_density_le1: \"edge_density K Y G \\<le> 1\"\nproof (cases \"finite K \\<and> finite Y\")\n  case True\n  then show ?thesis \n    using of_nat_mono [OF max_all_edges_between, of K Y]\n    by (fastforce simp add: edge_density_def divide_simps)\nqed (auto simp: edge_density_def)\n\nlemma all_edges_between_swap:\n  \"all_edges_between X Y G = (\\<lambda>(x,y). (y,x)) ` (all_edges_between Y X G)\"\n  unfolding all_edges_between_def\n  by (auto simp add: insert_commute image_iff split: prod.split)\n\nlemma card_all_edges_between_commute:\n  \"card (all_edges_between X Y G) = card (all_edges_between Y X G)\"\nproof -\n  have \"inj_on (\\<lambda>(x, y). (y, x)) A\" for A :: \"(nat*nat)set\"\n    by (auto simp: inj_on_def)\n  then show ?thesis\n    by (simp add: all_edges_between_swap [of X Y] card_image)\nqed\n\nlemma edge_density_commute: \"edge_density X Y G = edge_density Y X G\"\n  by (simp add: edge_density_def card_all_edges_between_commute mult.commute)\n\n\ntext \\<open>$\\epsilon$-regular pairs, for two sets of vertices. Again, authors disagree on whether the\nsets need to be disjoint, though it seems that overlapping sets cause double-counting. Authors also\ndisagree about whether or not to use the strict subset relation here. The proofs below are easier if\nit is strict but later proofs require the non-strict version. The two definitions can be proved to\nbe equivalent under fairly mild conditions, but even those conditions turn out to be onerous.\\<close>\n\ndefinition regular_pair::  \"uvert set  \\<Rightarrow> uvert set \\<Rightarrow> ugraph \\<Rightarrow> real \\<Rightarrow> bool\"\n  where \"regular_pair X Y G \\<epsilon> \\<equiv> \n    \\<forall>A B. A \\<subseteq> X \\<and> B \\<subseteq> Y \\<and> (card A \\<ge> \\<epsilon> * card X) \\<and> (card B \\<ge> \\<epsilon> * card Y) \\<longrightarrow>\n              \\<bar>edge_density A B G - edge_density X Y G\\<bar> \\<le> \\<epsilon>\" for \\<epsilon>::real\n\nlemma regular_pair_commute: \"regular_pair X Y G \\<epsilon> \\<longleftrightarrow> regular_pair Y X G \\<epsilon>\"\n  by (metis edge_density_commute regular_pair_def)\n\nlemma edge_density_Un:\n  assumes \"disjnt X1 X2\" \"finite X1\" \"finite X2\"\n  shows \"edge_density (X1 \\<union> X2) Y G = (edge_density X1 Y G * card X1 + edge_density X2 Y G * card X2) / (card X1 + card X2)\"\nproof (cases \"finite Y\")\n  case True\n  with assms show ?thesis \n    by (simp add: edge_density_def all_edges_between_disjnt1 all_edges_between_Un1 finite_all_edges_between card_Un_disjnt card_ge_0_finite divide_simps)\nqed (simp add: edge_density_def)\n\nlemma edge_density_partition:\n  assumes \"finite_graph_partition U P n\"\n  shows \"edge_density U W G = (\\<Sum>X\\<in>P. edge_density X W G * card X) / card U\"\nproof (cases \"finite U\")\n  case True\n  have \"finite P\"\n    using assms finite_graph_partition_def by blast\n  then show ?thesis\n    using True assms\n  proof (induction P arbitrary: n U)\n    case empty\n    then show ?case\n      by (simp add: edge_density_def finite_graph_partition_def partition_on_def)\n  next\n    case (insert X P)\n    then have \"n > 0\"\n      by (metis finite_graph_partition_0 gr_zeroI insert_not_empty)\n    with insert.prems insert.hyps \n    have UX: \"finite_graph_partition (U-X) P (n-1)\"\n      by (auto simp: finite_graph_partition_def partition_on_def disjnt_iff pairwise_insert)\n    then have finU: \"finite (\\<Union>P)\"\n      by (simp add: finite_graph_partition_equals insert)\n    then have sumXP: \"card U = card X + card (\\<Union>P)\"\n      by (metis UX card_finite_graph_partition finite_graph_partition_equals insert.hyps insert.prems sum.insert)\n    have FUX: \"finite (U - X)\"\n      by (simp add: insert.prems)\n    have XUP: \"X \\<union> (\\<Union>P) = U\"\n      using finite_graph_partition_equals insert.prems(2) by auto\n    then have \"edge_density U W G = edge_density (X \\<union> \\<Union>P) W G\"\n      by auto\n    also have \"\\<dots> = (edge_density X W G * card X + edge_density (\\<Union>P) W G * card (\\<Union>P)) \n                  / (card X + card (\\<Union>P))\"\n    proof (rule edge_density_Un)\n      show \"disjnt X (\\<Union>P)\"\n        using UX disjnt_iff finite_graph_partition_equals by auto\n      show \"finite X\"\n        using XUP \\<open>finite U\\<close> by blast\n    qed (use finU in auto)\n    also have \"\\<dots> = (edge_density X W G * card X + edge_density (U-X) W G * card (\\<Union>P)) \n                  / card U\"\n      using UX card_finite_graph_partition finite_graph_partition_equals insert.prems(1) insert.prems(2) sumXP by auto\n    also have \"\\<dots> = (\\<Sum>Y \\<in> insert X P. edge_density Y W G * card Y) / card U\"\n      using UX insert.prems insert.hyps \n      apply (simp add: insert.IH [OF FUX UX] divide_simps algebra_simps finite_graph_partition_equals)\n      by (metis (no_types, lifting) Diff_eq_empty_iff finite_graph_partition_empty sum.empty)\n    finally show ?case .\n  qed\nqed (simp add: edge_density_def)\n\ntext\\<open>Let @{term P}, @{term Q} be partitions of a set of vertices @{term V}. \n  Then @{term P} refines @{term Q} if for all @{term \\<open>A \\<in> P\\<close>} there is @{term \\<open>B \\<in> Q\\<close>} \n  such that @{term \\<open>A \\<subseteq> B\\<close>}.\\<close>\n\ntext \\<open>For the sake of generality, and following Zhao's Online Lecture \n\\<^url>\\<open>https://www.youtube.com/watch?v=vcsxCFSLyP8&t=16s\\<close>\nwe do not impose disjointness: we do not include @{term \"i\\<noteq>j\"} below.\\<close>\n\ndefinition irregular_set:: \"[real, ugraph, uvert set set] \\<Rightarrow> (uvert set \\<times> uvert set) set\"\n  where \"irregular_set \\<equiv> \\<lambda>\\<epsilon>::real. \\<lambda>G P. {(R,S)|R S. R\\<in>P \\<and> S\\<in>P \\<and> \\<not> regular_pair R S G \\<epsilon>}\"\n\ntext\\<open>A regular partition may contain a few irregular pairs as long as their total size is bounded as follows.\\<close>\ndefinition regular_partition:: \"[real, ugraph, uvert set set] \\<Rightarrow> bool\"\n  where\n  \"regular_partition \\<equiv> \\<lambda>\\<epsilon>::real. \\<lambda>G P . \n     partition_on (uverts G) P \\<and>\n     (\\<Sum>(R,S) \\<in> irregular_set \\<epsilon> G P. card R * card S) \\<le> \\<epsilon> * (card (uverts G))\\<^sup>2\"\n\nlemma irregular_set_subset: \"irregular_set \\<epsilon> G P \\<subseteq> P \\<times> P\"\n  by (auto simp: irregular_set_def)\n\nlemma irregular_set_swap: \"(i,j) \\<in> irregular_set \\<epsilon> G P \\<longleftrightarrow> (j,i) \\<in> irregular_set \\<epsilon> G P\"\n  by (auto simp add: irregular_set_def regular_pair_commute)\n\nlemma finite_irregular_set [simp]: \"finite P \\<Longrightarrow> finite (irregular_set \\<epsilon> G P)\"\n  by (metis finite_SigmaI finite_subset irregular_set_subset)\n\nsubsection \\<open>Energy of a Graph\\<close>\n\ntext \\<open>Definition 3.7 (Energy), written @{term \"q(U,W)\"}\\<close>\ndefinition energy_graph_subsets:: \"[uvert set, uvert set, ugraph] \\<Rightarrow> real\" where\n  \"energy_graph_subsets U W G \\<equiv>\n     card U * card W * (edge_density U W G)\\<^sup>2 / (card (uverts G))\\<^sup>2\"\n\ntext \\<open>Definition for partitions\\<close>\ndefinition energy_graph_partitions :: \"[ugraph, uvert set set, uvert set set] \\<Rightarrow> real\"\n  where \"energy_graph_partitions G P Q \\<equiv> \\<Sum>R\\<in>P.\\<Sum>S\\<in>Q. energy_graph_subsets R S G\"\n\nlemma energy_graph_subsets_0 [simp]: \n     \"energy_graph_subsets {} B G = 0\" \"energy_graph_subsets A {} G = 0\"\n  by (auto simp: energy_graph_subsets_def)\n\nlemma energy_graph_subsets_ge0 [simp]:\n  \"energy_graph_subsets U W G \\<ge> 0\"\n  by (auto simp: energy_graph_subsets_def)\n\nlemma energy_graph_partitions_ge0 [simp]:\n  \"energy_graph_partitions G U W \\<ge> 0\"\n  by (auto simp: sum_nonneg energy_graph_partitions_def)\n\nlemma energy_graph_subsets_commute: \n  \"energy_graph_subsets U W G = energy_graph_subsets W U G\"\n  by (simp add: energy_graph_subsets_def edge_density_commute)\n\nlemma energy_graph_partitions_commute:\n  \"energy_graph_partitions G W U = energy_graph_partitions G U W\"\n  by (simp add: energy_graph_partitions_def energy_graph_subsets_commute sum.swap [where A=W])\n\ntext\\<open>Definition 3.7 (Energy of a Partition), or following Gowers, mean square density:\n a version of energy for a single partition of the vertex set. \\<close> \n\nabbreviation mean_square_density :: \"[ugraph, uvert set set] \\<Rightarrow> real\"\n  where \"mean_square_density G P \\<equiv> energy_graph_partitions G P P\"\n\nlemma mean_square_density: \n  \"mean_square_density G U \\<equiv> \n          (\\<Sum>R\\<in>U. \\<Sum>S\\<in>U. card R * card S * (edge_density R S G)\\<^sup>2) / (card (uverts G))\\<^sup>2\"\n  by (simp add: energy_graph_partitions_def energy_graph_subsets_def sum_divide_distrib)\n\ntext\\<open>Observation: the energy is between 0 and 1 because the edge density is bounded above by 1.\\<close>\n\nlemma sum_partition_le:\n  assumes \"finite_graph_partition V P k\" \"finite V\"\n  shows \"(\\<Sum>R\\<in>P. \\<Sum>S\\<in>P. real (card R * card S)) \\<le> (real(card V))\\<^sup>2\"\nproof -\n  have \"finite P\"\n    using assms finite_graph_partition_def by blast\n  then show ?thesis\n    using assms\n  proof (induction P arbitrary: V k)\n    case (insert X P)\n    have [simp]: \"finite Y\" if \"Y \\<in> insert X P\" for Y\n      by (meson finite_graph_partition_finite insert.prems that)\n    have C: \"card Y \\<le> card V\" if\"Y \\<in> insert X P\" for Y\n      by (meson card_mono finite_graph_partition_subset insert.prems that)\n    have D [simp]: \"(\\<Sum>Y\\<in>P. real (card Y)) = real (card V) - real (card X)\"\n      by (smt (verit) card_finite_graph_partition insert.hyps insert.prems of_nat_sum sum.cong sum.insert)\n    have \"disjnt X (\\<Union>P)\"\n      using insert.prems insert.hyps\n      by (auto simp add: finite_graph_partition_def disjnt_iff pairwise_insert partition_on_def)\n    with insert have *: \"(\\<Sum>R\\<in>P. \\<Sum>S\\<in>P. real (card R * card S)) \\<le> (real (card (V - X)))\\<^sup>2\"\n      unfolding finite_graph_partition_def\n      by (simp add: lessThan_Suc partition_on_insert disjoint_family_on_insert sum.distrib)\n    have [simp]: \"V \\<inter>X = X\"\n      using finite_graph_partition_equals insert.prems by blast \n    have \"(\\<Sum>R \\<in> insert X P. \\<Sum>S \\<in> insert X P. real (card R * card S)) \n      = real (card X * card X) + 2 * (card V - card X) * card X\n        + (\\<Sum>R\\<in>P. \\<Sum>S\\<in>P. real (card R * card S))\"\n      using \\<open>X \\<notin> P\\<close> \\<open>finite P\\<close>\n      by (simp add: C of_nat_diff sum.distrib algebra_simps flip: sum_distrib_right)\n    also have \"\\<dots> \\<le> real (card X * card X) + 2 * (card V - card X) * card X + (real (card (V - X)))\\<^sup>2\"\n      using * by linarith\n    also have \"\\<dots> \\<le> (real (card V))\\<^sup>2\"\n      by (simp add: of_nat_diff C card_Diff_subset_Int algebra_simps power2_eq_square)\n    finally show ?case .\n  qed auto\nqed\n\nlemma mean_square_density_bounded: \n  assumes \"finite_graph_partition (uverts G) P k\" \"finite (uverts G)\" \n  shows \"mean_square_density G P \\<le> 1\"\nproof-\n  have \"(\\<Sum>R\\<in>P. \\<Sum>S\\<in>P. real (card R * card S) * (edge_density R S G)\\<^sup>2) \n     \\<le> (\\<Sum>R\\<in>P. \\<Sum>S\\<in>P. real (card R * card S))\"\n    by (intro sum_mono mult_right_le_one_le) (auto simp: abs_square_le_1 edge_density_ge0 edge_density_le1)\n  also have \"\\<dots> \\<le> (real(card (uverts G)))\\<^sup>2\"\n    using sum_partition_le assms by blast \n  finally show ?thesis \n    by (simp add: mean_square_density divide_simps)\nqed\n\nsubsection \\<open>Partitioning and Energy\\<close>\n\ntext\\<open>See Gowers's remark after Lemma 11. \n Further partitioning of subsets of the vertex set cannot make the energy decrease. \n We follow Gowers's proof, which avoids the use of probability.\\<close>\n\nlemma sum_products_le:\n  fixes a :: \"'a \\<Rightarrow> real\"\n  assumes \"\\<And>i. i \\<in> I \\<Longrightarrow> a i \\<ge> 0\"\n  shows \"(\\<Sum>i\\<in>I. a i * b i)\\<^sup>2 \\<le> (\\<Sum>i\\<in>I. a i) * (\\<Sum>i\\<in>I. a i * (b i)\\<^sup>2)\"  (is \"?L \\<le> ?R\")\nproof -\n  have \"?L = (\\<Sum>i\\<in>I. sqrt (a i) * (sqrt (a i) * b i))\\<^sup>2\"\n    by (smt (verit, ccfv_SIG) assms mult.assoc real_sqrt_mult_self sum.cong)\n  also have \"... \\<le> (\\<Sum>i\\<in>I. (sqrt (a i))\\<^sup>2) * (\\<Sum>i\\<in>I. (sqrt (a i) * b i)\\<^sup>2)\"\n    by (rule Cauchy_Schwarz_ineq_sum)\n  also have \"... = ?R\"\n    by (smt (verit) assms mult.assoc mult.commute power2_eq_square real_sqrt_pow2 sum.cong)\n  finally show ?thesis .\nqed\n\nlemma energy_graph_partition_half:\n  assumes P: \"finite_graph_partition U P n\"\n  shows \"card U * (edge_density U W G)\\<^sup>2 \\<le> (\\<Sum>R\\<in>P. card R * (edge_density R W G)\\<^sup>2)\"\nproof (cases \"finite U\")\n  case True\n  have \\<section>: \"(\\<Sum>R\\<in>P. card R * edge_density R W G)\\<^sup>2 \n         \\<le> (sum card P) * (\\<Sum>R\\<in>P. card R * (edge_density R W G)\\<^sup>2)\"\n    by (simp add: sum_products_le)\n  have \"card U * (edge_density U W G)\\<^sup>2 = (\\<Sum>R\\<in>P. card R * (edge_density U W G)\\<^sup>2)\"\n    by (metis \\<open>finite U\\<close> P sum_distrib_right card_finite_graph_partition of_nat_sum)\n  also have \"\\<dots> = edge_density U W G * (\\<Sum>R\\<in>P. edge_density U W G * card R)\"\n    by (simp add: sum_distrib_left power2_eq_square mult_ac)\n  also have \"\\<dots> = (\\<Sum>R\\<in>P. edge_density R W G * real (card R)) * edge_density U W G\"\n  proof -\n    have \"edge_density U W G * (\\<Sum>R\\<in>P. edge_density R W G * card R) \n        = edge_density U W G * (edge_density U W G * (\\<Sum>R\\<in>P. card R))\"\n      using \\<open>finite U\\<close> assms card_finite_graph_partition  by (auto simp: edge_density_partition [OF P])\n    then show ?thesis\n      by (simp add: mult.commute sum_distrib_left)\n  qed\n  also have \"\\<dots> = (\\<Sum>R\\<in>P. card R * edge_density R W G) * edge_density U W G\"\n    by (simp add: sum_distrib_left mult_ac)\n  also have \"\\<dots> = (\\<Sum>R\\<in>P. card R * edge_density R W G)\\<^sup>2 / card U\"\n    using assms by (simp add: edge_density_partition [OF P] mult_ac flip: power2_eq_square)\n  also have \"\\<dots> \\<le> (\\<Sum>R\\<in>P. card R * (edge_density R W G)\\<^sup>2)\"\n    using \\<section> P card_finite_graph_partition \\<open>finite U\\<close> \n    by (force simp add: mult_ac divide_simps simp flip: of_nat_sum)\n  finally show ?thesis .\nqed (simp add: sum_nonneg)\n\nproposition energy_graph_partition_increase:\n  assumes P: \"finite_graph_partition U P k\" and V: \"finite_graph_partition W Q l\"\n  shows \"energy_graph_partitions G P Q \\<ge> energy_graph_subsets U W G\" \nproof -\n  have \"(card U * card W) * (edge_density U W G)\\<^sup>2 = card W * (card U * (edge_density U W G)\\<^sup>2)\"\n    by (simp add: mult_ac)\n  also have \"\\<dots> \\<le> card W * (\\<Sum>R\\<in>P. card R * (edge_density R W G)\\<^sup>2)\"\n    by (intro mult_left_mono energy_graph_partition_half) (use assms in auto)\n  also have \"\\<dots> = (\\<Sum>R\\<in>P. card R * (card W * (edge_density W R G)\\<^sup>2))\"\n    by (simp add: sum_distrib_left edge_density_commute mult_ac)\n  also have \"\\<dots> \\<le> (\\<Sum>R\\<in>P. card R * (\\<Sum>S\\<in>Q. card S * (edge_density S R G)\\<^sup>2))\"\n    by (intro mult_left_mono energy_graph_partition_half sum_mono) (use assms in auto)\n  also have \"\\<dots> \\<le> (\\<Sum>R\\<in>P. \\<Sum>S\\<in>Q. (card R * card S) * (edge_density R S G)\\<^sup>2)\"\n    by (simp add: sum_distrib_left edge_density_commute mult_ac)\n  finally\n  have \"(card U * card W) * (edge_density U W G)\\<^sup>2 \n    \\<le> (\\<Sum>R\\<in>P. \\<Sum>S\\<in>Q. (card R * card S) * (edge_density R S G)\\<^sup>2)\" .\n  then show ?thesis\n    unfolding energy_graph_partitions_def energy_graph_subsets_def\n    by (simp add: divide_simps flip: sum_divide_distrib)\nqed\n\ntext \\<open>The following is the fully general version of Gowers's Lemma 11  \nFurther partitioning of subsets of the vertex set cannot make the energy decrease.\nNote that @{term V} should be @{term \"uverts G\"} even though this more general version holds.\\<close>\n\nlemma energy_graph_partitions_increase_half:\n  assumes ref: \"refines V Q P\" and \"finite V\" and part_VP: \"partition_on V P\"\n    and U: \"{} \\<notin> U\"\n  shows \"energy_graph_partitions G Q U \\<ge> energy_graph_partitions G P U\" \n        (is \"?egQ \\<ge> ?egP\")\nproof -\n  have \"\\<exists>F. partition_on R F \\<and> F = {S\\<in>Q. S \\<subseteq> R}\" if \"R\\<in>P\" for R\n    using ref refines_obtains_subset that by blast\n  then obtain F where F: \"\\<And>R. R \\<in> P \\<Longrightarrow> partition_on R (F R) \\<and> F R = {S\\<in>Q. S \\<subseteq> R}\"\n    by fastforce\n  have injF: \"inj_on F P\"\n    by (metis F inj_on_inverseI partition_on_def)\n  have finite_P: \"finite R\" if \"R \\<in> P\" for R\n    by (metis Union_upper \\<open>finite V\\<close> part_VP finite_subset partition_on_def that)\n  then have finite_F: \"finite (F R)\" if \"R \\<in> P\" for R\n    using that by (simp add: F)\n  have dFP: \"disjoint (F ` P)\"\n    using part_VP \n    by (smt (verit, best) F Union_upper disjnt_iff disjointD le_inf_iff pairwise_imageI partition_on_def subset_empty)\n  have F_ne: \"F R \\<noteq> {}\" if \"R \\<in> P\" for R\n    by (metis F Sup_empty part_VP partition_on_def that)\n  have F_sums_Q: \"(\\<Sum>R\\<in>P. \\<Sum>U\\<in>F R. f U) = (\\<Sum>S\\<in>Q. f S)\" for f :: \"nat set \\<Rightarrow> real\"\n  proof -\n    have \"Q = (\\<Union>R \\<in> P. F R)\"\n      using ref by (force simp add: refines_def dest: F)\n    then have \"(\\<Sum>S\\<in>Q. f S) = sum f (\\<Union>R \\<in> P. F R)\"\n      by blast\n    also have \"\\<dots> = (sum \\<circ> sum) f (F ` P)\"\n      by (smt (verit, best) dFP disjnt_def finite_F image_iff pairwiseD sum.Union_disjoint)\n    also have \"\\<dots> = (\\<Sum>R \\<in> P. \\<Sum>U\\<in>F R. f U)\"\n      unfolding comp_apply by (metis injF sum.reindex_cong)\n    finally show ?thesis\n      by simp\n  qed\n  have \"?egP = (\\<Sum>R \\<in> P. \\<Sum>T\\<in>U. energy_graph_subsets R T G)\"\n    by (simp add: energy_graph_partitions_def)\n  also have \"\\<dots> \\<le> (\\<Sum>R\\<in>P. \\<Sum>T\\<in>U. energy_graph_partitions G (F R) {T})\"\n  proof -\n    have \"finite_graph_partition R (F R) (card (F R))\"\n      if \"R \\<in> P\" for R\n      by (meson F finite_F finite_graph_partition_def that) \n    moreover have \"finite_graph_partition T {T} (Suc 0)\"\n      if \"T \\<in> U\" for T\n      using U by (metis that trivial_graph_partition_exists)\n    ultimately show ?thesis\n      using finite_P by (intro sum_mono energy_graph_partition_increase) auto\n  qed\n  also have \"\\<dots> = (\\<Sum>R \\<in> P. \\<Sum>D \\<in> F R. \\<Sum>T\\<in>U. energy_graph_subsets D T G)\"\n    by (simp add: energy_graph_partitions_def sum.swap [where B = \"U\"])\n  also have \"\\<dots> = ?egQ\"\n    by (simp add: energy_graph_partitions_def F_sums_Q)\n  finally show ?thesis .\nqed\n\nproposition energy_graph_partitions_increase:\n  assumes \"refines V Q P\" \"refines V' Q' P'\" \n    and \"finite V\" \"finite V'\" \n  shows \"energy_graph_partitions G Q Q' \\<ge> energy_graph_partitions G P P'\"\nproof -\n  obtain \"{} \\<notin> P'\" \"{} \\<notin> Q\"\n    using assms unfolding refines_def partition_on_def by presburger\n  then show ?thesis\n    using assms unfolding refines_def\n    by (smt (verit, ccfv_SIG) assms energy_graph_partitions_commute energy_graph_partitions_increase_half)\nqed\n\ntext \\<open>The original version of Gowers's Lemma 11 (also in Zhao)\n      is not general enough to be used for anything.\\<close>\ncorollary mean_square_density_increase:\n  assumes \"refines V Q P\" \"finite V\"\n  shows \"mean_square_density G Q \\<ge> mean_square_density G P\"\n  using assms energy_graph_partitions_increase by presburger \n\n\ntext\\<open>The Energy Boost Lemma says that an \nirregular partition increases the energy substantially. We assume that @{term \"\\<U> \\<subseteq> uverts G\"} \nand @{term \"\\<W> \\<subseteq> uverts G\"} are not irregular, as witnessed by their subsets @{term\"U1 \\<subseteq> \\<U>\"} and @{term\"W1 \\<subseteq> \\<W>\"}.\nThe proof follows Lemma 12 of Gowers. \\<close>\n\ndefinition \"part2 X Y \\<equiv> if X \\<subset> Y then {X,Y-X} else {Y}\"\n\nlemma card_part2: \"card (part2 X Y) \\<le> 2\"\n  by (simp add: part2_def card_insert_if)\n\nlemma sum_part2: \"\\<lbrakk>X \\<subseteq> Y; f{} = 0\\<rbrakk> \\<Longrightarrow> sum f (part2 X Y) = f X + f (Y-X)\"\n  by (force simp add: part2_def sum.insert_if)\n\nlemma partition_part2:\n  assumes \"A \\<subseteq> B\" \"A \\<noteq> {}\"\n  shows \"partition_on B (part2 A B)\"\n  using assms by (auto simp add: partition_on_def part2_def disjnt_iff pairwise_insert)\n\nproposition energy_boost:\n  fixes \\<epsilon>::real and U W G\n  defines \"alpha \\<equiv> edge_density U W G\"\n  defines \"u \\<equiv> \\<lambda>X Y. edge_density X Y G - alpha\"\n  assumes \"finite U\" \"finite W\"\n    and \"U' \\<subseteq> U\" \"W' \\<subseteq> W\" \"\\<epsilon> > 0\"\n    and U': \"card U' \\<ge> \\<epsilon> * card U\" and W': \"card W' \\<ge> \\<epsilon> * card W\"\n    and gt: \"\\<bar>u U' W'\\<bar> > \\<epsilon>\"\n  shows \"(\\<Sum>A \\<in> part2 U' U. \\<Sum>B \\<in> part2 W' W. energy_graph_subsets A B G)\n         \\<ge> energy_graph_subsets U W G + \\<epsilon>^4 * (card U * card W) / (card (uverts G))\\<^sup>2\"\n          (is \"?lhs \\<ge> ?rhs\")\nproof -\n  define UF where \"UF \\<equiv> part2 U' U\"\n  define WF where \"WF \\<equiv> part2 W' W\"\n  obtain [simp]: \"finite U\" \"finite W\"\n    using assms by (meson finite_subset)\n  obtain card': \"card U' > 0\" \"card W' > 0\"\n    using gt \\<open>\\<epsilon> > 0\\<close> U' W'\n    by (force simp: u_def alpha_def edge_density_def mult_le_0_iff zero_less_mult_iff)\n  then obtain card: \"card U > 0\" \"card W > 0\"\n    using assms by fastforce\n  then obtain [simp]: \"finite U'\" \"finite W'\"\n    by (meson card' card_ge_0_finite)\n  obtain [simp]: \"W' \\<noteq> W - W'\" \"U' \\<noteq> U - U'\"\n    by (metis DiffD2 card' all_not_in_conv card.empty less_irrefl)\n  have UF_ne: \"card x \\<noteq> 0\" if \"x \\<in> UF\" for x\n    using card' assms that by (auto simp: UF_def part2_def split: if_split_asm)\n  have WF_ne: \"card x \\<noteq> 0\" if \"x \\<in> WF\" for x\n    using card' assms that by (auto simp: WF_def part2_def split: if_split_asm)\n  have cardUW: \"card U = card U' + card(U - U')\" \"card W = card W' + card(W - W')\"\n    using card card' \\<open>U' \\<subseteq> U\\<close> \\<open>W' \\<subseteq> W\\<close>\n    by (metis card_eq_0_iff card_Diff_subset card_mono le_add_diff_inverse less_le)+\n  have \"U = (U - U') \\<union> U'\" \"disjnt (U - U') U'\"\n    using \\<open>U' \\<subseteq> U\\<close> by (force simp: disjnt_iff)+\n  then have CU: \"card (all_edges_between U Z G) \n          = card (all_edges_between (U - U') Z G) + card (all_edges_between U' Z G)\" \n      if \"finite Z\" for Z \n    by (metis \\<open>finite U'\\<close> all_edges_between_Un1 all_edges_between_disjnt1 \\<open>finite U\\<close> \n        card_Un_disjnt finite_Diff finite_all_edges_between that)\n\n  have \"W = (W - W') \\<union> W'\" \"disjnt (W - W') W'\"\n    using \\<open>W' \\<subseteq> W\\<close> by (force simp: disjnt_iff)+\n  then have CW: \"card (all_edges_between Z W G) \n          = card (all_edges_between Z (W - W') G) + card (all_edges_between Z W' G)\"\n    if \"finite Z\" for Z\n    by (metis \\<open>finite W'\\<close> all_edges_between_Un2 all_edges_between_disjnt2 \\<open>finite W\\<close>\n        card_Un_disjnt finite_Diff2 finite_all_edges_between that)\n  have *: \"(\\<Sum>X\\<in>UF. \\<Sum>Y\\<in>WF. real (card (all_edges_between X Y G))) \n         = card (all_edges_between U W G)\"\n    by (simp add: UF_def WF_def cardUW CU CW sum_part2 \\<open>U' \\<subseteq> U\\<close> \\<open>W' \\<subseteq> W\\<close>)\n  have **: \"real (card U) * real (card W) = (\\<Sum>X\\<in>UF. \\<Sum>Y\\<in>WF. card X * card Y)\"\n    by (simp add: UF_def WF_def cardUW sum_part2 \\<open>U' \\<subseteq> U\\<close> \\<open>W' \\<subseteq> W\\<close> algebra_simps)\n\n  let ?S = \"\\<Sum>X\\<in>UF. \\<Sum>Y\\<in>WF. (card X * card Y) / (card U * card W) * (edge_density X Y G)\\<^sup>2\"\n  define T where \"T \\<equiv> (\\<Sum>X\\<in>UF. \\<Sum>Y\\<in>WF. (card X * card Y) / (card U * card W) * (edge_density X Y G))\"\n  have \\<section>: \"2 * T = alpha + alpha * (\\<Sum>X\\<in>UF. \\<Sum>Y\\<in>WF. (card X * card Y) / (card U * card W))\"\n    unfolding alpha_def T_def\n    by (simp add: * ** edge_density_def divide_simps sum_part2 \\<open>U' \\<subseteq> U\\<close> \\<open>W' \\<subseteq> W\\<close> UF_ne WF_ne flip: sum_divide_distrib)\n  have \"\\<epsilon> * \\<epsilon> \\<le> u U' W' * u U' W'\"\n    by (metis abs_ge_zero abs_mult_self_eq \\<open>\\<epsilon> > 0\\<close> gt less_le mult_mono)\n  then have \"(\\<epsilon>*\\<epsilon>)*(\\<epsilon>*\\<epsilon>) \\<le> (card U' * card W') / (card U * card W) * (u U' W')\\<^sup>2\"\n    using card mult_mono [OF U' W']  \\<open>\\<epsilon> > 0\\<close>\n    apply (simp add: divide_simps eval_nat_numeral)\n    by (smt (verit, del_insts) mult.assoc mult.commute mult_mono' of_nat_0_le_iff zero_le_mult_iff)\n  also have \"\\<dots> \\<le> (\\<Sum>X\\<in>UF. \\<Sum>Y\\<in>WF.  (card X * card Y) / (card U * card W) * (u X Y)\\<^sup>2)\"\n    by (simp add: UF_def WF_def sum_part2 \\<open>U' \\<subseteq> U\\<close> \\<open>W' \\<subseteq> W\\<close>)\n  also have \"\\<dots> = ?S - 2 * T * alpha\n                 + alpha\\<^sup>2 * (\\<Sum>X\\<in>UF. \\<Sum>Y\\<in>WF. (card X * card Y) / (card U * card W))\"\n    by (simp add: u_def T_def power2_diff mult_ac ring_distribs divide_simps \n          sum_distrib_left sum_distrib_right sum_subtractf sum.distrib flip: sum_divide_distrib)\n  also have \"\\<dots> = ?S - alpha\\<^sup>2\"\n    using \\<section> by (simp add: power2_eq_square algebra_simps)\n  finally have 12: \"alpha\\<^sup>2 + \\<epsilon>^4 \\<le> ?S\"\n    by (simp add: eval_nat_numeral)\n  have \"?rhs = (alpha\\<^sup>2 + \\<epsilon>^4) * (card U * card W / (card (uverts G))\\<^sup>2)\"\n    unfolding alpha_def energy_graph_subsets_def\n    by (simp add: ring_distribs divide_simps power2_eq_square)\n  also have \"\\<dots> \\<le> ?S * (card U * card W / (card (uverts G))\\<^sup>2)\"\n    by (rule mult_right_mono [OF 12]) auto\n  also have \"\\<dots> = ?lhs\"\n    using card unfolding energy_graph_subsets_def UF_def WF_def\n    by (auto simp add: algebra_simps sum_part2 \\<open>U' \\<subseteq> U\\<close> \\<open>W' \\<subseteq> W\\<close> )\n  finally show ?thesis .\nqed\n\nsubsection \\<open>Energy boost for partitions\\<close>\n\ntext\\<open>We can always find a refinement that increases the energy by a certain amount.\\<close>\n\ntext \\<open>A necessary lemma for the tower of exponentials in the result. Angeliki's proof\\<close>\nlemma le_tower_2: \"k * (2 ^ Suc k) \\<le> 2^(2^k)\"\nproof (induction k rule: less_induct)\n  case (less k)\n  show ?case \n  proof (cases \"k \\<le> Suc (Suc 0)\")\n    case False\n    define j where \"j = k - Suc 0\"\n    have kj: \"k = Suc j\"\n      using False j_def by force\n    with False have \\<section>: \"(2^j + 3) \\<le> (2::nat) ^ k\"\n      by (simp add: Suc_leI le_less_trans not_less_eq_eq numeral_3_eq_3)\n    have \"k * (2 ^ Suc k) \\<le> 6 * j * 2^j\"\n      using False by (simp add: kj)\n    also have \"\\<dots> \\<le> 6 * 2^(2^j)\"\n      using kj less.IH by force\n    also have \"\\<dots> < 2^(2^j + 3)\"\n      by (simp add: power_add) \n    also have \"\\<dots> \\<le> 2^2^k\"\n      by (simp add: \\<section>)\n    finally show ?thesis\n      by simp      \n  qed (auto simp: le_Suc_eq)\nqed\n\n\ntext \\<open>The bound $2 ^{k+1}$  comes from a different source by Zhao:\n``Graph Theory and Additive Combinatorics'', \\<^url>\\<open>https://yufeizhao.com/gtacbook/\\<close>.\nIt's needed because our @{term regular_partition} includes the diagonal; \notherwise, $k 2^k$ would work. Gowers'  version has a flatly incorrect bound.\\<close>\nproposition exists_refinement:\n  assumes fgp: \"finite_graph_partition (uverts G) P k\" and \"finite (uverts G)\" \n    and irreg: \"\\<not> regular_partition \\<epsilon> G P\" and \"\\<epsilon> > 0\"\n  obtains Q where \"refines (uverts G) Q P\"                     \n                    \"mean_square_density G Q \\<ge> mean_square_density G P + \\<epsilon>^5\" \n                    \"\\<And>R. R\\<in>P \\<Longrightarrow> card {S\\<in>Q. S \\<subseteq> R} \\<le> 2 ^ Suc k\"\n                    \"card Q \\<le> k * 2 ^ Suc k\"\nproof -\n  define sum_pp where \"sum_pp \\<equiv> (\\<Sum>(R,S) \\<in> irregular_set \\<epsilon> G P. card R * card S)\"\n  have cardP: \"card P = k\"\n    using fgp finite_graph_partition_def by force\n  then have \"k \\<noteq> 0\"\n    using assms unfolding regular_partition_def irregular_set_def finite_graph_partition_def by fastforce\n  with assms have G_nonempty: \"0 < card (uverts G)\"\n    by (metis card_gt_0_iff finite_graph_partition_empty)\n  have part_GP: \"partition_on (uverts G) P\"\n    using fgp finite_graph_partition_def by blast \n  then have finP: \"finite R\" \"R \\<noteq> {}\" if \"R\\<in>P\" for R\n    using assms that partition_onD3 finite_graph_partition_finite by blast+\n  have spp: \"sum_pp > \\<epsilon> * (card (uverts G))\\<^sup>2\"\n    by (metis irreg not_le part_GP regular_partition_def sum_pp_def)\n  then have sum_irreg_pos: \"sum_pp > 0\"\n    using \\<open>\\<epsilon> > 0\\<close> G_nonempty less_asym by fastforce\n  have \"\\<exists>X\\<subseteq>R. \\<exists>Y\\<subseteq>S. \\<epsilon> * card R \\<le> card X \\<and> \\<epsilon> * card S \\<le> card Y \\<and>\n                     \\<bar>edge_density X Y G - edge_density R S G\\<bar> > \\<epsilon>\"\n    if \"(R,S) \\<in> irregular_set \\<epsilon> G P\" for R S\n    using that fgp finite_graph_partition_subset by (simp add: irregular_set_def regular_pair_def not_le) \n  then obtain X0 Y0 \n    where XY0_psub_P: \"\\<And>R S. \\<lbrakk>(R,S) \\<in> irregular_set \\<epsilon> G P\\<rbrakk> \\<Longrightarrow> X0 R S \\<subseteq> R \\<and> Y0 R S \\<subseteq> S\"\n    and XY0_eps:\n    \"\\<And>R S. (R,S) \\<in> irregular_set \\<epsilon> G P\n        \\<Longrightarrow> \\<epsilon> * card R \\<le> card (X0 R S) \\<and> \\<epsilon> * card S \\<le> card (Y0 R S) \\<and>\n            \\<bar>edge_density (X0 R S) (Y0 R S) G - edge_density R S G\\<bar> > \\<epsilon>\"\n    by metis\n  obtain iP where iP: \"bij_betw iP P {..<k}\"\n    by (metis fgp finite_graph_partition_def to_nat_on_finite cardP)\n  define X where \"X \\<equiv> \\<lambda>R S. if iP R < iP S then Y0 S R else X0 R S\"\n  define Y where \"Y \\<equiv> \\<lambda>R S. if iP R < iP S then X0 S R else Y0 R S\"\n  have XY_psub_P: \"\\<And>R S. \\<lbrakk>(R,S) \\<in> irregular_set \\<epsilon> G P\\<rbrakk> \\<Longrightarrow> X R S \\<subseteq> R \\<and> Y R S \\<subseteq> S\"\n    using XY0_psub_P by (force simp: X_def Y_def irregular_set_swap)\n  have XY_eps:\n    \"\\<And>R S. (R,S) \\<in> irregular_set \\<epsilon> G P\n        \\<Longrightarrow> \\<epsilon> * card R \\<le> card (X R S) \\<and> \\<epsilon> * card S \\<le> card (Y R S) \\<and>\n            \\<bar>edge_density (X R S) (Y R S) G - edge_density R S G\\<bar> > \\<epsilon>\"\n    using XY0_eps by (force simp: X_def Y_def edge_density_commute irregular_set_swap)\n  have card_elem_P: \"card R > 0\" if \"R\\<in>P\" for R\n    by (metis card_eq_0_iff finP neq0_conv that)\n  have XY_nonempty: \"X R S \\<noteq> {}\" \"Y R S \\<noteq> {}\" if \"(R,S) \\<in> irregular_set \\<epsilon> G P\" for R S\n    using XY_eps [OF that] that \\<open>\\<epsilon> > 0\\<close> card_elem_P [of R] card_elem_P [of S]\n    by (auto simp: irregular_set_def mult_le_0_iff)\n\n  text\\<open>By the assumption that our partition is irregular, there are many irregular pairs.\n       For each irregular pair, find pairs of subsets that witness irregularity.\\<close>\n  define XP where \"XP R \\<equiv> ((\\<lambda>S. part2 (X R S) R) ` {S. (R,S) \\<in> irregular_set \\<epsilon> G P})\" for R\n  define YP where \"YP S \\<equiv> ((\\<lambda>R. part2 (Y R S) S) ` {R. (R,S) \\<in> irregular_set \\<epsilon> G P})\" for S\n\n  text \\<open>include degenerate partition to ensure it works whether or not there's an irregular pair\\<close>\n  define PP where \"PP \\<equiv> \\<lambda>R. insert {R} (XP R \\<union> YP R)\"\n  define QS where \"QS R \\<equiv> common_refinement (PP R)\" for R\n  define r where \"r R \\<equiv> card (QS R)\" for R\n  have \"finite P\"\n    using fgp finite_graph_partition_def by blast\n  then have finPP: \"finite (PP R)\" for R\n    by (simp add: PP_def XP_def YP_def irregular_set_def)\n  have inPP_fin: \"P \\<in> PP R \\<Longrightarrow> finite P\" for P R\n    by (auto simp: PP_def XP_def YP_def part2_def)\n  have finite_QS: \"finite (QS R)\" for R\n    by (simp add: QS_def finPP finite_common_refinement inPP_fin)\n\n  have part_QS: \"partition_on R (QS R)\" if \"R \\<in> P\" for R\n    unfolding QS_def\n  proof (intro partition_on_common_refinement partition_onI)\n    show \"\\<And>\\<A>. \\<A> \\<in> PP R \\<Longrightarrow> {} \\<notin> \\<A>\"\n      using that XY_nonempty XY_psub_P finP\n      by (fastforce simp add: PP_def XP_def YP_def part2_def)\n  qed (auto simp: disjnt_iff PP_def XP_def YP_def part2_def dest: XY_psub_P)\n\n  have part_P_QS: \"finite_graph_partition R (QS R) (r R)\" if \"R\\<in>P\" for R\n    by (simp add: finite_QS finite_graph_partition_def part_QS r_def that)\n  then have fin_SQ [simp]: \"finite (QS R)\" if \"R\\<in>P\" for R\n    using QS_def finite_QS by force\n  have QS_ne: \"{} \\<notin> QS R\" if \"R\\<in>P\" for R\n    using QS_def part_QS partition_onD3 that by blast \n  have QS_subset_P: \"q \\<in> QS R \\<Longrightarrow> q \\<subseteq> R\" if \"R\\<in>P\" for R q\n    by (meson finite_graph_partition_subset part_P_QS that)\n  then have QS_inject: \"R = R'\" \n    if \"R\\<in>P\" \"R'\\<in>P\" \"q \\<in> QS R\" \"q \\<in> QS R'\" for R R' q\n    by (metis UnionI disjnt_iff equals0I pairwiseD part_GP part_QS partition_on_def that)\n  define Q where \"Q \\<equiv> (\\<Union>R\\<in>P. QS R)\"\n  define m where \"m \\<equiv> \\<Sum>R\\<in>P. r R\"\n  show thesis\n  proof\n    show ref_QP: \"refines (uverts G) Q P\"\n      unfolding refines_def\n    proof (intro conjI strip part_GP)\n      fix X\n      assume \"X \\<in> Q\"\n      then show \"\\<exists>Y\\<in>P. X \\<subseteq> Y\"\n        by (metis QS_subset_P Q_def UN_iff)\n    next\n      show \"partition_on (uverts G) Q\"\n      proof (intro conjI partition_onI)\n        show \"\\<Union>Q = uverts G\"\n        proof\n          show \"\\<Union>Q \\<subseteq> uverts G\"\n            using QS_subset_P Q_def fgp finite_graph_partition_equals by fastforce\n          show \"uverts G \\<subseteq> \\<Union>Q\"\n            by (metis Q_def Sup_least UN_upper Union_mono part_GP part_QS partition_onD1)\n        qed\n        show \"disjnt p q\" if \"p \\<in> Q\" and \"q \\<in> Q\" and \"p \\<noteq> q\" for p q\n        proof -\n          from that \n          obtain R S where \"R\\<in>P\" \"S\\<in>P\" \n            and *: \"p \\<in> QS R\" \"q \\<in> QS S\"\n            by (auto simp: Q_def QS_def)\n          show ?thesis\n          proof (cases \"R=S\")\n            case True\n            then show ?thesis\n              using part_QS [of R]\n              by (metis \\<open>R \\<in> P\\<close> * pairwiseD partition_on_def \\<open>p \\<noteq> q\\<close>)\n          next\n            case False\n            with * show ?thesis\n              by (metis QS_subset_P \\<open>R \\<in> P\\<close> \\<open>S \\<in> P\\<close> disjnt_iff pairwiseD part_GP partition_on_def subsetD)\n          qed\n        qed\n        show \"{} \\<notin> Q\"\n          using QS_ne Q_def by blast\n      qed\n    qed \n    have disj_QSP: \"disjoint_family_on QS P\"\n      unfolding disjoint_family_on_def by (metis Int_emptyI QS_inject)\n    let ?PP = \"P \\<times> P\"\n    let ?REG = \"?PP - irregular_set \\<epsilon> G P\"\n    define sum_eps where \"sum_eps \\<equiv> (\\<Sum>(R,S) \\<in> irregular_set \\<epsilon> G P. \\<epsilon>^4 * (card R * card S) / (card (uverts G))\\<^sup>2)\"\n    have A: \"energy_graph_subsets R S G + \\<epsilon>^4 * (card R * card S) / (card (uverts G))\\<^sup>2\n          \\<le> energy_graph_partitions G (part2 (X R S) R) (part2 (Y R S) S)\"\n          (is \"?L \\<le> ?R\")\n          if *: \"(R,S) \\<in> irregular_set \\<epsilon> G P\" for R S\n    proof -\n      have \"R\\<in>P\" \"S\\<in>P\"\n        using * by (auto simp: irregular_set_def)\n      have \"?L \\<le> (\\<Sum>A \\<in> part2 (X R S) R. \\<Sum>B \\<in> part2 (Y R S) S. energy_graph_subsets A B G)\"\n        using XY_psub_P [OF *] XY_eps [OF *] assms\n        by (intro energy_boost \\<open>R \\<in> P\\<close> \\<open>S \\<in> P\\<close> finP \\<open>\\<epsilon>>0\\<close>) auto\n      also have \"\\<dots> \\<le> ?R\"\n        by (simp add: energy_graph_partitions_def)\n      finally show ?thesis .\n    qed\n    have B: \"energy_graph_partitions G (part2 (X R S) R) (part2 (Y R S) S)\n          \\<le> energy_graph_partitions G (QS R) (QS S)\"\n      if \"(R,S) \\<in> irregular_set \\<epsilon> G P\" for R S\n    proof -\n      have \"R\\<in>P\" \"S\\<in>P\" using that by (auto simp: irregular_set_def)\n      have [simp]: \"\\<not> X R S \\<subset> R \\<longleftrightarrow> X R S = R\" \"\\<not> Y R S \\<subset> S \\<longleftrightarrow> Y R S = S\"\n        using XY_psub_P that by blast+\n      have XPX: \"part2 (X R S) R \\<in> PP R\"\n        using that by (simp add: PP_def XP_def)\n      have I: \"partition_on R (QS R)\"\n        using QS_def \\<open>R \\<in> P\\<close> part_QS by force\n      moreover have \"\\<forall>q \\<in> QS R. \\<exists>b \\<in> part2 (X R S) R. q \\<subseteq> b\"\n        using common_refinement_exists [OF _ XPX] by (simp add: QS_def)\n      ultimately have ref_XP: \"refines R (QS R) (part2 (X R S) R)\"\n        by (simp add: refines_def XY_nonempty XY_psub_P that partition_part2)\n      have YPY: \"part2 (Y R S) S \\<in> PP S\"\n        using that by (simp add: PP_def YP_def)\n      have J: \"partition_on S (QS S)\"\n        using QS_def \\<open>S \\<in> P\\<close> part_QS by force\n      moreover have \"\\<forall>q \\<in> QS S. \\<exists>b \\<in> part2 (Y R S) S. q \\<subseteq> b\"\n        using common_refinement_exists [OF _ YPY] by (simp add: QS_def)\n      ultimately have ref_YP: \"refines S (QS S) (part2 (Y R S) S)\"\n        by (simp add: XY_nonempty XY_psub_P that partition_part2 refines_def)\n      show ?thesis\n        using \\<open>R \\<in> P\\<close> \\<open>S \\<in> P\\<close>\n        by (simp add: finP energy_graph_partitions_increase [OF ref_XP ref_YP])\n    qed\n    have \"mean_square_density G P + \\<epsilon>^5 \\<le> mean_square_density G P + sum_eps\"\n    proof -\n      have \"\\<epsilon>^5 = (\\<epsilon> * (card (uverts G))\\<^sup>2) * (\\<epsilon>^4 / (card (uverts G))\\<^sup>2)\"\n        using G_nonempty by (simp add: field_simps eval_nat_numeral)\n      also have \"\\<dots> \\<le> sum_pp * (sum_eps / sum_pp)\"\n      proof (rule mult_mono)\n        show \"\\<epsilon>^4 / real ((card (uverts G))\\<^sup>2) \\<le> sum_eps / sum_pp\"\n          using sum_irreg_pos sum_eps_def sum_pp_def\n          by (auto simp add: case_prod_unfold sum.neutral simp flip: sum_distrib_left sum_divide_distrib of_nat_sum of_nat_mult)\n      qed (use spp sum_nonneg in auto)\n      also have \"\\<dots> \\<le> sum_eps\"\n        by (simp add: sum_irreg_pos)\n      finally show ?thesis by simp\n    qed\n    also have \"\\<dots> = (\\<Sum>(i,j)\\<in>?REG. energy_graph_subsets i j G) \n                   + (\\<Sum>(i,j)\\<in>irregular_set \\<epsilon> G P. energy_graph_subsets i j G) + sum_eps\"\n      by (simp add: \\<open>finite P\\<close> energy_graph_partitions_def sum.cartesian_product irregular_set_subset sum.subset_diff)\n    also have \"\\<dots> \\<le> (\\<Sum>(i,j) \\<in> ?REG. energy_graph_subsets i j G)\n                   + (\\<Sum>(i,j) \\<in> irregular_set \\<epsilon> G P. energy_graph_partitions G (part2 (X i j) i) (part2 (Y i j) j))\"\n      using A unfolding sum_eps_def case_prod_unfold\n      by (force intro: sum_mono simp flip: sum.distrib)\n    also have \"\\<dots> \\<le> (\\<Sum>(i,j) \\<in> ?REG. energy_graph_partitions G (QS i) (QS j))\n                   + (\\<Sum>(i,j) \\<in> irregular_set \\<epsilon> G P. energy_graph_partitions G (part2 (X i j) i) (part2 (Y i j) j))\"\n      by (auto intro!: part_P_QS sum_mono energy_graph_partition_increase)\n    also have \"\\<dots> \\<le> (\\<Sum>(i,j) \\<in> ?REG. energy_graph_partitions G (QS i) (QS j)) \n                  + (\\<Sum>(i,j) \\<in> irregular_set \\<epsilon> G P. energy_graph_partitions G (QS i) (QS j))\"\n      using B\n    proof (intro sum_mono add_mono ordered_comm_monoid_add_class.sum_mono2)\n    qed (auto split: prod.split)\n    also have \"\\<dots> = (\\<Sum>(i,j) \\<in> ?PP. energy_graph_partitions G (QS i) (QS j))\"\n      by (metis (no_types, lifting) \\<open>finite P\\<close> finite_SigmaI irregular_set_subset sum.subset_diff)\n    also have \"\\<dots> = (\\<Sum>i\\<in>P. \\<Sum>j\\<in>P. energy_graph_partitions G (QS i) (QS j))\"\n      by (simp flip: sum.cartesian_product)\n    also have \"\\<dots> = (\\<Sum>A \\<in> Q. \\<Sum>B \\<in> Q. energy_graph_subsets A B G)\"\n      unfolding energy_graph_partitions_def Q_def\n      by (simp add: disj_QSP \\<open>finite P\\<close> sum.UNION_disjoint_family sum.swap [of _ \"P\" \"QS _\"])\n    also have \"\\<dots> = mean_square_density G Q\"\n      by (simp add: mean_square_density energy_graph_subsets_def sum_divide_distrib)\n    finally show \"mean_square_density G P + \\<epsilon> ^ 5 \\<le> mean_square_density G Q\" .\n\n    define QinP where \"QinP \\<equiv> \\<lambda>i. {j\\<in>Q. j \\<subseteq> i}\"\n    show card_QP: \"card (QinP i) \\<le> 2 ^ Suc k\"\n      if \"i \\<in> P\" for i \n    proof -\n      have less_cardP: \"iP i < k\"\n        using iP bij_betwE that by blast\n      have card_cr: \"card (QS i) \\<le> 2 ^ Suc k\"\n      proof -\n        have \"card (QS i) \\<le> prod card (PP i)\"\n          by (simp add: QS_def card_common_refinement finPP inPP_fin) \n        also have \"\\<dots> = prod card (XP i \\<union> YP i)\"\n          using finPP by (simp add: PP_def prod.insert_if)\n        also have \"\\<dots> \\<le> 2 ^ Suc k\" \n        proof (rule prod_le_power)\n          define XS where \"XS \\<equiv> (\\<Union>R \\<in> {R\\<in>P. iP R \\<le> iP i}. {part2 (X0 i R) i})\"\n          define YS where \"YS \\<equiv> (\\<Union>R \\<in> {R\\<in>P. iP R \\<ge> iP i}. {part2 (Y0 R i) i})\"\n          have 1: \"{R \\<in> P. iP R \\<le> iP i} \\<subseteq> iP -` {..iP i} \\<inter> P\"\n            by auto\n          have \"card XS \\<le> card {R \\<in> P. iP R \\<le> iP i}\"\n            by (force simp add: XS_def \\<open>finite P\\<close> intro: order_trans [OF card_UN_le])\n          also have \"\\<dots> \\<le> card (iP -` {..iP i} \\<inter> P)\"\n            using 1 by (simp add: \\<open>finite P\\<close> card_mono)\n          also have \"\\<dots> \\<le> Suc (iP i)\"\n            by (metis card_vimage_inj_on_le bij_betw_def card_atMost finite_atMost iP)\n          finally have cXS: \"card XS \\<le> Suc (iP i)\" .\n          have 2: \"{R \\<in> P. iP R \\<ge> iP i} \\<subseteq> iP -` {iP i..<k} \\<inter> P\"\n            by clarsimp (meson bij_betw_apply iP lessThan_iff nat_less_le)\n          have \"card YS \\<le> card {R \\<in> P. iP R \\<ge> iP i}\"\n            by (force simp add: YS_def \\<open>finite P\\<close> intro: order_trans [OF card_UN_le])\n          also have \"\\<dots> \\<le> card (iP -` {iP i..<k} \\<inter> P)\"\n            using 2 by (simp add: \\<open>finite P\\<close> card_mono)\n          also have \"\\<dots> \\<le> card {iP i..<k}\"\n            by (meson bij_betw_def card_vimage_inj_on_le finite_atLeastLessThan iP)\n          finally have \"card YS \\<le> k - iP i\" \n            by simp\n          with less_cardP cXS have k': \"card XS + card YS \\<le> Suc k\"\n            by linarith\n          have finXYS: \"finite (XS \\<union> YS)\"\n            unfolding XS_def YS_def using \\<open>finite P\\<close> by (auto intro: finite_vimageI) \n          have \"XP i \\<union> YP i \\<subseteq> XS \\<union> YS\"\n            apply (simp add: XP_def X_def YP_def Y_def XS_def YS_def irregular_set_def image_def subset_iff)\n            by (metis insert_iff linear not_le)\n          then have \"card (XP i \\<union> YP i) \\<le> card XS + card YS\"\n            by (meson card_Un_le card_mono finXYS order_trans)\n          then show \"card (XP i \\<union> YP i) \\<le> Suc k\"\n            using k' le_trans by blast\n          fix x\n          assume \"x \\<in> XP i \\<union> YP i\"\n          then show \"0 \\<le> card x \\<and> card x \\<le> 2\"\n            using XP_def YP_def card_part2 by force\n        qed auto\n        finally show ?thesis .\n      qed\n      have \"i' = i\" if \"q \\<subseteq> i\" \"i'\\<in>P\" \"q \\<in> QS i'\" for i' q\n        by (metis QS_ne QS_subset_P \\<open>i \\<in> P\\<close> disjnt_iff equals0I pairwiseD part_GP partition_on_def subset_eq that)\n      then have \"QinP i \\<subseteq> QS i\"\n        by (auto simp: QinP_def Q_def)\n      then have \"card (QinP i) \\<le> card (QS i)\"\n        by (simp add: card_mono that)\n      also have \"\\<dots> \\<le> 2 ^ Suc k\"\n        using QS_def card_cr by presburger\n      finally show ?thesis .\n    qed\n    have \"card Q \\<le> card (\\<Union>i\\<in>P. QinP i)\"\n      unfolding Q_def\n    proof (rule card_mono)\n      show \"(\\<Union> (QS ` P)) \\<subseteq> (\\<Union>i\\<in>P. QinP i)\"\n        using ref_QP QS_subset_P Q_def QinP_def by blast\n      show \"finite (\\<Union>i\\<in>P. QinP i)\"\n        by (simp add: Q_def QinP_def \\<open>finite P\\<close>)\n    qed \n    also have \"\\<dots> \\<le> (\\<Sum>i\\<in>P. 2 ^ Suc k)\"\n      by (smt (verit) \\<open>finite P\\<close> card_QP card_UN_le order_trans sum_mono)\n    finally show \"card Q \\<le> k * 2 ^ Suc k\" \n      by (simp add: cardP)\n  qed\nqed\n\nsubsection \\<open>The Regularity Proof Itself\\<close>\n\ntext\\<open>We start with a trivial partition (one part). If it is already $\\epsilon$-regular, we are done. If\nnot, we refine it by applying lemma @{thm[source]\"exists_refinement\"} above, which increases the\nenergy. We can repeat this step, but it cannot increase forever: by @{thm [source]\nmean_square_density_bounded} it cannot exceed~1. This defines an algorithm that must stop\nafter at most $\\epsilon^{-5}$ steps, resulting in an $\\epsilon$-regular partition.\\<close>\ntheorem Szemeredi_Regularity_Lemma:\n  assumes \"\\<epsilon> > 0\"\n  obtains M where \"\\<And>G. card (uverts G) > 0 \\<Longrightarrow> \\<exists>P. regular_partition \\<epsilon> G P \\<and> card P \\<le> M\"\nproof \n  fix G\n  assume \"card (uverts G) > 0\"\n  then obtain finG: \"finite (uverts G)\" and nonempty: \"uverts G \\<noteq> {}\"\n    by (simp add: card_gt_0_iff) \n  define \\<Phi> where \"\\<Phi> \\<equiv> \\<lambda>Q P. refines (uverts G) Q P \\<and> \n                                 mean_square_density G Q \\<ge> mean_square_density G P + \\<epsilon>^5 \\<and> \n                                 card Q \\<le> card P * 2 ^ Suc (card P)\"\n  define nxt where \"nxt \\<equiv> \\<lambda>P. if regular_partition \\<epsilon> G P then P else SOME Q. \\<Phi> Q P\"\n  define iter where \"iter \\<equiv> \\<lambda>i. (nxt ^^ i) {uverts G}\"\n  define last where \"last \\<equiv> Suc (nat\\<lceil>1 / \\<epsilon> ^ 5\\<rceil>)\"\n  have iter_Suc [simp]: \"iter (Suc i) = nxt (iter i)\" for i\n    by (simp add: iter_def)\n  have \\<Phi>: \"\\<Phi> (nxt P) P\"\n    if Pk: \"partition_on (uverts G) P\" and irreg: \"\\<not> regular_partition \\<epsilon> G P\" for P\n  proof -\n    have \"finite_graph_partition (uverts G) P (card P)\"\n      by (meson Pk finG finite_elements finite_graph_partition_def)\n    then show ?thesis\n      using that exists_refinement [OF _ finG irreg assms] irreg Pk\n      unfolding \\<Phi>_def nxt_def by (smt (verit) someI)\n  qed\n  have partition_on: \"partition_on (uverts G) (iter i)\" for i\n  proof (induction i)\n    case 0\n    then show ?case\n      by (simp add: iter_def nonempty trivial_graph_partition_exists partition_on_space)\n  next\n    case (Suc i)\n    with \\<Phi> show ?case\n      by (metis \\<Phi>_def iter_Suc nxt_def refines_def)\n  qed\n  have False if irreg: \"\\<And>i. i\\<le>last \\<Longrightarrow> \\<not> regular_partition \\<epsilon> G (iter i)\"\n  proof -\n    have \\<Phi>_loop: \"\\<Phi> (nxt (iter i)) (iter i)\" if \"i\\<le>last\" for i\n      using \\<Phi> irreg partition_on that by blast\n    have iter_grow: \"mean_square_density G (iter i) \\<ge> i * \\<epsilon>^5\" if \"i\\<le>last\" for i\n      using that\n    proof (induction i)\n      case (Suc i)\n      then show ?case\n        by (clarsimp simp: algebra_simps) (smt (verit, best) Suc_leD \\<Phi>_def \\<Phi>_loop)\n    qed (auto simp: iter_def)\n    have \"last * \\<epsilon>^5 \\<le> mean_square_density G (iter last)\"\n      by (simp add: iter_grow)\n    also have \"\\<dots> \\<le> 1\"\n      by (meson finG finite_elements finite_graph_partition_def mean_square_density_bounded partition_on)\n    finally have \"real last * \\<epsilon> ^ 5 \\<le> 1\" .\n    with assms show False\n      unfolding last_def by (meson lessI natceiling_lessD not_less pos_divide_less_eq zero_less_power)\n  qed\n  then obtain i where \"i \\<le> last\" and \"regular_partition \\<epsilon> G (iter i)\"\n    by force\n  then have reglar: \"regular_partition \\<epsilon> G (iter (i + d))\" for d\n    by (induction d) (auto simp add: nxt_def)\n  define tower where \"tower \\<equiv> \\<lambda>k. (power(2::nat) ^^ k) 2\"\n  have [simp]: \"tower (Suc k) = 2 ^ tower k\" for k\n    by (simp add: tower_def)\n  have iter_tower: \"card (iter i) \\<le> tower (2*i)\" for i\n  proof (induction i)\n    case (Suc i)\n    then have Qm: \"card (iter i) \\<le> tower (2 * i)\"\n      by simp\n    then have *: \"card (nxt (iter i)) \\<le> card (iter i) * 2 ^ Suc (card (iter i))\"\n      using \\<Phi> by (simp add: \\<Phi>_def nxt_def partition_on)\n    also have \"\\<dots> \\<le> 2 ^ 2 ^ tower (2 * i)\"\n      by (metis One_nat_def Suc.IH le_tower_2 lessI numeral_2_eq_2 order.trans power_increasing_iff)\n    finally show ?case\n      by (simp add: Qm)\n  qed (auto simp: iter_def tower_def)\n  then show \"\\<exists>P. regular_partition \\<epsilon> G P \\<and> card P \\<le> tower(2 * last)\"\n    by (metis \\<open>i \\<le> last\\<close> nat_le_iff_add reglar)\nqed \n\ntext \\<open>The actual value of the bound is visible above: a tower of exponentials of height $2(1 + \\epsilon^{-5})$.\\<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/Szemeredi_Regularity/Szemeredi.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.877476784277755, "lm_q2_score": 0.8333245953120233, "lm_q1q2_score": 0.7312229861539558}}
{"text": "theory Pascal_Property\n  imports Main Projective_Plane_Axioms Pappus_Property\nbegin\n\n(* Author: Anthony Bordg, University of Cambridge, apdb3@cam.ac.uk .*)\n\ntext \\<open>\nContents:\n\\<^item> A hexagon is pascal if its three opposite sides meet in collinear points [\\<open>is_pascal\\<close>].\n\\<^item> A plane is pascal, or has Pascal's property, if for every hexagon of that plane\nPascal property is stable under any permutation of that hexagon. \n\\<close>\n\nsection \\<open>Pascal's Property\\<close>\n\ndefinition inters :: \"Lines \\<Rightarrow> Lines \\<Rightarrow> Points set\" where\n\"inters l m \\<equiv> {P. incid P l \\<and> incid P m}\"\n\nlemma inters_is_singleton:\n  assumes \"l \\<noteq> m\" and \"P \\<in> inters l m\" and \"Q \\<in> inters l m\"\n  shows \"P = Q\"\n  using assms ax_uniqueness inters_def \n  by blast\n\ndefinition inter :: \"Lines \\<Rightarrow> Lines \\<Rightarrow> Points\" where\n\"inter l m \\<equiv> @P. P \\<in> inters l m\"\n\nlemma uniq_inter:\n  assumes \"l \\<noteq> m\" and \"incid P l\" and \"incid P m\"\n  shows \"inter l m = P\"\nproof -\n  have \"P \\<in> inters l m\"\n    by (simp add: assms(2) assms(3) inters_def)\n  have \"\\<forall>Q. Q \\<in> inters l m \\<longrightarrow> Q = P\"\n    using \\<open>P \\<in> inters l m\\<close> assms(1) inters_is_singleton \n    by blast\n  show \"inter l m = P\"\n    using \\<open>P \\<in> inters l m\\<close> assms(1) inter_def inters_is_singleton \n    by auto\nqed\n\n(* The configuration of a hexagon where the three pairs of opposite sides meet in \ncollinear points *)\ndefinition is_pascal :: \"[Points, Points, Points, Points, Points, Points] \\<Rightarrow> bool\" where\n\"is_pascal A B C D E F \\<equiv> distinct6 A B C D E F \\<longrightarrow> line B C \\<noteq> line E F \\<longrightarrow> line C D \\<noteq> line A F\n\\<longrightarrow> line A B \\<noteq> line D E \\<longrightarrow> \n(let P = inter (line B C) (line E F) in\nlet Q = inter (line C D) (line A F) in\nlet R = inter (line A B) (line D E) in \ncol P Q R)\"\n\nlemma col_rot_CW:\n  assumes \"col P Q R\"\n  shows \"col R P Q\"\n  using assms col_def \n  by auto\n\nlemma col_2cycle: \n  assumes \"col P Q R\"\n  shows \"col P R Q\"\n  using assms col_def \n  by auto\n\nlemma distinct6_rot_CW:\n  assumes \"distinct6 A B C D E F\"\n  shows \"distinct6 F A B C D E\"\n  using assms distinct6_def \n  by auto\n\nlemma lines_comm: \"lines P Q = lines Q P\"\n  using lines_def \n  by auto\n\nlemma line_comm:\n  assumes \"P \\<noteq> Q\"\n  shows \"line P Q = line Q P\"\n  by (metis ax_uniqueness incidA_lAB incidB_lAB)\n  \nlemma inters_comm: \"inters l m = inters m l\"\n  using inters_def \n  by auto\n\nlemma inter_comm: \"inter l m = inter m l\"\n  by (simp add: inter_def inters_comm)\n\nlemma inter_line_line_comm:\n  assumes \"C \\<noteq> D\"\n  shows \"inter (line A B) (line C D) = inter (line A B) (line D C)\"\n  using assms line_comm \n  by auto\n\nlemma inter_line_comm_line:\n  assumes \"A \\<noteq> B\"\n  shows \"inter (line A B) (line C D) = inter (line B A) (line C D)\"\n  using assms line_comm \n  by auto\n\nlemma inter_comm_line_line_comm:\n  assumes \"C \\<noteq> D\" and \"line A B \\<noteq> line C D\"\n  shows \"inter (line A B) (line C D) = inter (line D C) (line A B)\"\n  by (metis inter_comm line_comm)\n\n(* Pascal's property is stable under the 6-cycle [A B C D E F] *)\nlemma is_pascal_rot_CW:\n  assumes \"is_pascal A B C D E F\"\n  shows \"is_pascal F A B C D E\"\nproof -\n  define P Q R where \"P = inter (line A B) (line D E)\" and \"Q = inter (line B C) (line E F)\" and\n    \"R = inter (line F A) (line C D)\"\n  have \"col P Q R\" if \"distinct6 F A B C D E\" and \"line A B \\<noteq> line D E\" and \"line B C \\<noteq> line E F\" \n    and \"line F A \\<noteq> line C D\"\n    using P_def Q_def R_def assms col_rot_CW distinct6_def inter_comm is_pascal_def line_comm \n      that(1) that(2) that(3) that(4) \n    by auto\n  then show \"is_pascal F A B C D E\"\n    by (metis P_def Q_def R_def is_pascal_def line_comm)\nqed\n\n(* We recall that the group of permutations S_6 is generated by the 2-cycle [1 2]\nand the 6-cycle [1 2 3 4 5 6] *)\n\n(* Assuming Pappus's property, Pascal's property is stable under the 2-cycle [A B] *)\n\nlemma incid_C_AB: \n  assumes \"A \\<noteq> B\" and \"incid A l\" and \"incid B l\" and \"incid C l\"\n  shows \"incid C (line A B)\"\n  using assms ax_uniqueness incidA_lAB incidB_lAB \n  by blast\n\nlemma incid_inters_left: \n  assumes \"P \\<in> inters l m\"\n  shows \"incid P l\"\n  using assms inters_def \n  by auto\n\nlemma incid_inters_right:\n  assumes \"P \\<in> inters l m\"\n  shows \"incid P m\"\n  using assms incid_inters_left inters_comm \n  by blast\n\nlemma inter_in_inters: \"inter l m \\<in> inters l m\"\nproof -\n  have \"\\<exists>P. P \\<in> inters l m\"\n    using inters_def ax2 \n    by auto\n  show \"inter l m \\<in> inters l m\"\n    by (metis \\<open>\\<exists>P. P \\<in> inters l m\\<close> inter_def some_eq_ex)\nqed\n\nlemma incid_inter_left: \"incid (inter l m) l\"\n  using incid_inters_left inter_in_inters \n  by blast\n\nlemma incid_inter_right: \"incid (inter l m) m\"\n  using incid_inter_left inter_comm \n  by fastforce\n\nlemma col_A_B_ABl: \"col A B (inter (line A B) l)\"\n  using col_def incidA_lAB incidB_lAB incid_inter_left \n  by blast\n\nlemma col_A_B_lAB: \"col A B (inter l (line A B))\"\n  using col_A_B_ABl inter_comm \n  by auto\n\nlemma inter_is_a_intersec: \"is_a_intersec (inter (line A B) (line C D)) A B C D\"\n  by (simp add: col_A_B_ABl col_A_B_lAB col_rot_CW is_a_intersec_def)\n\ndefinition line_ext :: \"Lines \\<Rightarrow> Points set\" where\n\"line_ext l \\<equiv> {P. incid P l}\"\n\nlemma line_left_inter_1: \n  assumes \"P \\<in> line_ext l\" and \"P \\<notin> line_ext m\"\n  shows \"line (inter l m) P = l\"\n  by (metis CollectD CollectI assms(1) assms(2) incidA_lAB incidB_lAB incid_inter_left \n      incid_inter_right line_ext_def uniq_inter)\n\nlemma line_left_inter_2:\n  assumes \"P \\<in> line_ext m\" and \"P \\<notin> line_ext l\"\n  shows \"line (inter l m) P = m\"\n  using assms inter_comm line_left_inter_1 \n  by fastforce\n\nlemma line_right_inter_1:\n  assumes \"P \\<in> line_ext l\" and \"P \\<notin> line_ext m\"\n  shows \"line P (inter l m) = l\"\n  by (metis assms line_comm line_left_inter_1)\n\nlemma line_right_inter_2:\n  assumes \"P \\<in> line_ext m\" and \"P \\<notin> line_ext l\"\n  shows \"line P (inter l m) = m\"\n  by (metis assms inter_comm line_comm line_left_inter_1)\n\nlemma inter_ABC_1: \n  assumes \"line A B \\<noteq> line C A\"\n  shows \"inter (line A B) (line C A) = A\"\n  using assms ax_uniqueness incidA_lAB incidB_lAB incid_inter_left incid_inter_right \n  by blast\n\nlemma line_inter_2:\n  assumes \"inter l m \\<noteq> inter l' m\" \n  shows \"line (inter l m) (inter l' m) = m\"\n  using assms ax_uniqueness incidA_lAB incidB_lAB incid_inter_right \n  by blast\n\nlemma col_line_ext_1:\n  assumes \"col A B C\" and \"A \\<noteq> C\"\n  shows \"B \\<in> line_ext (line A C)\"\n  by (metis CollectI assms ax_uniqueness col_def incidA_lAB incidB_lAB line_ext_def)\n\nlemma inter_line_ext_1:\n  assumes \"inter l m \\<in> line_ext n\" and \"l \\<noteq> m\" and \"l \\<noteq> n\"\n  shows \"inter l m = inter l n\"\n  using assms(1) assms(3) ax_uniqueness incid_inter_left incid_inter_right line_ext_def \n  by blast\n\nlemma inter_line_ext_2:\n  assumes \"inter l m \\<in> line_ext n\" and \"l \\<noteq> m\" and \"m \\<noteq> n\"\n  shows \"inter l m = inter m n\"\n  by (metis assms inter_comm inter_line_ext_1)\n\ndefinition pascal_prop :: \"bool\" where\n\"pascal_prop \\<equiv> \\<forall>A B C D E F. is_pascal A B C D E F \\<longrightarrow> is_pascal B A C D E F\"\n\nlemma pappus_pascal:\n  assumes \"is_pappus\"\n  shows \"pascal_prop\"\nproof-\n  have \"is_pascal B A C D E F\" if \"is_pascal A B C D E F\" for A B C D E F\n  proof-\n    define X Y Z where \"X = inter (line A C) (line E F)\" and \"Y = inter (line C D) (line B F)\"\n      and \"Z = inter (line B A) (line D E)\" \n    have \"col X Y Z\" if \"distinct6 B A C D E F\" and \"line A C \\<noteq> line E F\" and \"line C D \\<noteq> line B F\" \n      and \"line B A \\<noteq> line D E\" and \"line B C = line E F\"\n      by (smt X_def Y_def ax_uniqueness col_ABA col_rot_CW distinct6_def incidB_lAB incid_inter_left \n          incid_inter_right line_comm that(1) that(2) that(3) that(5))\n    have \"col X Y Z\" if \"distinct6 B A C D E F\" and \"line A C \\<noteq> line E F\" and \"line C D \\<noteq> line B F\" \n      and \"line B A \\<noteq> line D E\" and \"line C D = line A F\"\n      by (metis X_def Y_def col_ABA col_rot_CW distinct6_def inter_ABC_1 line_comm that(1) that(2) \n          that(3) that(5))\n    have \"col X Y Z\" if \"distinct6 B A C D E F\" and \"line A C \\<noteq> line E F\" and \"line C D \\<noteq> line B F\" \n      and \"line B A \\<noteq> line D E\" and \"line B C \\<noteq> line E F\" and \"line C D \\<noteq> line A F\"\n    proof-\n      define W where \"W = inter (line A C) (line E F)\"\n      have \"col A C W\"\n        by (simp add: col_A_B_ABl W_def)\n      define P Q R where \"P = inter (line B C) (line E F)\"\n        and \"Q = inter (line A B) (line D E)\"\n        and \"R = inter (line C D) (line A F)\"\n      have \"col P Q R\"\n        using P_def Q_def R_def \\<open>is_pascal A B C D E F\\<close> col_2cycle distinct6_def is_pascal_def \n          line_comm that(1) that(4) that(5) that(6) \n        by auto\n          (* Below we take care of a few degenerate cases *)\n      have \"col X Y Z\" if \"P = Q\"\n        by (smt P_def Q_def X_def Y_def Z_def \\<open>distinct6 B A C D E F\\<close> ax_uniqueness col_ABA col_def \n            distinct6_def incidA_lAB incidB_lAB incid_inter_left inter_comm that)\n      have \"col X Y Z\" if \"P = R\"\n        by (smt P_def R_def X_def Y_def Z_def \\<open>distinct6 B A C D E F\\<close> \\<open>line A C \\<noteq> line E F\\<close> \n            \\<open>line C D \\<noteq> line B F\\<close> col_2cycle col_A_B_ABl col_rot_CW distinct6_def incidA_lAB \n            incidB_lAB incid_inter_left incid_inter_right that uniq_inter)\n      have \"col X Y Z\" if \"P = A\"\n        by (smt P_def Q_def R_def X_def Y_def Z_def \\<open>P = Q \\<Longrightarrow> col X Y Z\\<close> \\<open>P = R \\<Longrightarrow> col X Y Z\\<close> \n            \\<open>col P Q R\\<close> \\<open>line B C \\<noteq> line E F\\<close> ax_uniqueness col_def incidA_lAB incid_inter_left \n            incid_inter_right line_comm that)\n      have \"col X Y Z\" if \"P = C\"\n        by (smt P_def Q_def R_def X_def Y_def Z_def \\<open>P = R \\<Longrightarrow> col X Y Z\\<close> \\<open>col P Q R\\<close> \n            \\<open>line A C \\<noteq> line E F\\<close> ax_uniqueness col_def incidA_lAB incid_inter_left \n            incid_inter_right line_comm that)\n      have \"col X Y Z\" if \"P = W\"\n        by (smt P_def Q_def R_def W_def X_def Y_def Z_def \\<open>P = C \\<Longrightarrow> col X Y Z\\<close> \\<open>P = Q \\<Longrightarrow> col X Y Z\\<close> \n            \\<open>col P Q R\\<close> \\<open>distinct6 B A C D E F\\<close> ax_uniqueness col_def distinct6_def incidB_lAB \n            incid_inter_left incid_inter_right line_comm that) \n      have \"col X Y Z\" if \"Q = R\"\n        by (smt Q_def R_def X_def Y_def Z_def \\<open>distinct6 B A C D E F\\<close> ax_uniqueness col_A_B_lAB \n            col_rot_CW distinct6_def incidB_lAB incid_inter_right inter_comm line_comm that)\n      have \"col X Y Z\" if \"Q = A\"\n        by (smt P_def Q_def R_def X_def Y_def Z_def \\<open>col P Q R\\<close> \\<open>distinct6 B A C D E F\\<close> \n            \\<open>line C D \\<noteq> line B F\\<close> ax_uniqueness col_ABA col_def distinct6_def incidA_lAB incidB_lAB \n            incid_inter_left incid_inter_right that)\n      have \"col X Y Z\" if \"Q = C\"\n        by (metis P_def Q_def W_def \\<open>P = W \\<Longrightarrow> col X Y Z\\<close> \\<open>distinct6 B A C D E F\\<close> ax_uniqueness \n            distinct6_def incidA_lAB incid_inter_left line_comm that)\n      have \"col X Y Z\" if \"Q = W\"\n        by (metis Q_def W_def X_def Z_def col_ABA line_comm that)\n      have \"col X Y Z\" if \"R = A\"\n        by (smt P_def Q_def R_def W_def X_def Y_def \\<open>P = W \\<Longrightarrow> col X Y Z\\<close> \\<open>Q = A \\<Longrightarrow> col X Y Z\\<close> \n            \\<open>col P Q R\\<close> \\<open>distinct6 B A C D E F\\<close> ax_uniqueness col_ABA col_def col_rot_CW distinct6_def \n            incidA_lAB incidB_lAB incid_inter_right inter_comm that)\n      have \"col X Y Z\" if \"R = C\"\n        by (smt P_def Q_def R_def X_def Y_def Z_def \\<open>col P Q R\\<close> \\<open>distinct6 B A C D E F\\<close> \n            \\<open>line A C \\<noteq> line E F\\<close> ax_uniqueness col_def distinct6_def incidA_lAB incidB_lAB \n            incid_inter_left inter_comm that)\n      have \"col X Y Z\" if \"R = W\"\n        by (metis R_def W_def \\<open>R = A \\<Longrightarrow> col X Y Z\\<close> \\<open>R = C \\<Longrightarrow> col X Y Z\\<close> \\<open>line C D \\<noteq> line A F\\<close> \n            ax_uniqueness incidA_lAB incidB_lAB incid_inter_left incid_inter_right that)\n      have \"col X Y Z\" if \"A = W\"\n        by (smt P_def Q_def R_def W_def X_def Y_def Z_def \\<open>P = R \\<Longrightarrow> col X Y Z\\<close> \\<open>Q = A \\<Longrightarrow> col X Y Z\\<close> \n            \\<open>col P Q R\\<close> \\<open>distinct6 B A C D E F\\<close> ax_uniqueness col_def distinct6_def incidA_lAB \n            incidB_lAB incid_inter_left incid_inter_right that)\n      have \"col X Y Z\" if \"C = W\"\n        by (metis P_def W_def \\<open>P = C \\<Longrightarrow> col X Y Z\\<close> \\<open>line B C \\<noteq> line E F\\<close> ax_uniqueness incidB_lAB \n            incid_inter_left incid_inter_right that)\n      have f1:\"col (inter (line P C) (line A Q)) (inter (line Q W) (line C R)) \n      (inter (line P W) (line A R))\" if \"distinct6 P Q R A C W\"\n        using assms(1) is_pappus_def is_pappus2_def \\<open>distinct6 P Q R A C W\\<close> \\<open>col P Q R\\<close>\n          \\<open>col A C W\\<close> inter_is_a_intersec inter_line_line_comm \n        by metis\n      have \"col X Y Z\" if \"C \\<in> line_ext (line E F)\"\n        using P_def \\<open>P = C \\<Longrightarrow> col X Y Z\\<close> \\<open>line B C \\<noteq> line E F\\<close> incidB_lAB line_ext_def that uniq_inter \n        by auto \n      have \"col X Y Z\" if \"A \\<in> line_ext (line D E)\"\n        by (metis Q_def \\<open>Q = A \\<Longrightarrow> col X Y Z\\<close> \\<open>line B A \\<noteq> line D E\\<close> ax_uniqueness incidA_lAB \n            incid_inter_left incid_inter_right line_comm line_ext_def mem_Collect_eq that)\n      have \"col X Y Z\" if \"line B C = line A B\"\n        by (metis P_def W_def \\<open>P = W \\<Longrightarrow> col X Y Z\\<close> \\<open>distinct6 B A C D E F\\<close> ax_uniqueness \n            distinct6_def incidA_lAB incidB_lAB that)\n          (* We can resume our proof with the non-degenerate case *)\n      have f2:\"inter (line P C) (line A Q) = B\" if\n        \"C \\<notin> line_ext (line E F)\" and \"A \\<notin> line_ext (line D E)\" and \"line B C \\<noteq> line A B\"\n        by (smt CollectI P_def Q_def ax_uniqueness incidA_lAB incidB_lAB incid_inter_left \n            incid_inter_right line_ext_def that(1) that(2) that(3))\n          (* Again, we need to take care of a few particular cases *)\n      have \"col X Y Z\" if \"line E F = line A F\"\n        by (metis W_def \\<open>A = W \\<Longrightarrow> col X Y Z\\<close> \\<open>line A C \\<noteq> line E F\\<close> inter_ABC_1 inter_comm that)\n      have \"col X Y Z\" if \"A \\<in> line_ext (line C D)\"\n        using R_def \\<open>R = A \\<Longrightarrow> col X Y Z\\<close> \\<open>line C D \\<noteq> line A F\\<close> ax_uniqueness incidA_lAB \n          incid_inter_left incid_inter_right line_ext_def that \n        by blast \n      have \"col X Y Z\" if \"inter (line B C) (line E F) = inter (line A C) (line E F)\"\n        by (simp add: P_def W_def \\<open>P = W \\<Longrightarrow> col X Y Z\\<close> that)\n          (* We resume the general case *)\n      have f3:\"inter (line P W) (line A R) = F\" if \"line E F \\<noteq> line A F\" and \"A \\<notin> line_ext (line C D)\"\n        and \"inter (line B C) (line E F) \\<noteq> inter (line A C) (line E F)\"\n        by (smt CollectI P_def R_def W_def ax_uniqueness incidA_lAB incidB_lAB incid_inter_left \n            incid_inter_right line_ext_def that(1) that(2) that(3))\n          (* Once again, first we need to handle a particular case, namely C \\<in> AF, then \n            we resume the general case *)\n      have \"col X Y Z\" if \"C \\<in> line_ext (line A F)\"\n        using R_def \\<open>R = C \\<Longrightarrow> col X Y Z\\<close> \\<open>line C D \\<noteq> line A F\\<close> ax_uniqueness incidA_lAB \n          incid_inter_left incid_inter_right line_ext_def that \n        by blast\n      have f4:\"inter (line Q W) (line C R) = inter (line Q W) (line C D)\" if \"C \\<notin> line_ext (line A F)\"\n        using R_def incidA_lAB line_ext_def line_right_inter_1 that \n        by auto\n      then have \"inter (line Q W) (line C D) \\<in> line_ext (line B F)\" if \"distinct6 P Q R A C W\"\n        and  \"C \\<notin> line_ext (line E F)\" and \"A \\<notin> line_ext (line D E)\" and \"line B C \\<noteq> line A B\"\n        and \"line E F \\<noteq> line A F\" and \"A \\<notin> line_ext (line C D)\"\n        and \"inter (line B C) (line E F) \\<noteq> inter (line A C) (line E F)\"\n        by (smt R_def \\<open>distinct6 B A C D E F\\<close> ax_uniqueness col_line_ext_1 distinct6_def f1 f2 f3 \n            incidA_lAB incidB_lAB incid_inter_left that(1) that(2) that(3) that(5) that(6) that(7))\n      then have \"inter (line Q W) (line C D) = inter (line C D) (line B F)\" if \"distinct6 P Q R A C W\"\n        and  \"C \\<notin> line_ext (line E F)\" and \"A \\<notin> line_ext (line D E)\" and \"line B C \\<noteq> line A B\"\n        and \"line E F \\<noteq> line A F\" and \"A \\<notin> line_ext (line C D)\"\n        and \"inter (line B C) (line E F) \\<noteq> inter (line A C) (line E F)\"\n        by (smt W_def \\<open>distinct6 B A C D E F\\<close> \\<open>line C D \\<noteq> line B F\\<close> ax_uniqueness distinct6_def f2 \n            incidA_lAB incidB_lAB incid_inter_left incid_inter_right inter_line_ext_2 that(1) that(2) \n            that(3) that(5) that(6) that(7))\n      moreover have \"inter (line C D) (line B F) \\<in> line_ext (line Q W)\" if \"distinct6 P Q R A C W\"\n        and  \"C \\<notin> line_ext (line E F)\" and \"A \\<notin> line_ext (line D E)\" and \"line B C \\<noteq> line A B\"\n        and \"line E F \\<noteq> line A F\" and \"A \\<notin> line_ext (line C D)\"\n        and \"inter (line B C) (line E F) \\<noteq> inter (line A C) (line E F)\"\n        by (metis calculation col_2cycle col_A_B_ABl col_line_ext_1 distinct6_def that(1) that(2) \n            that(3) that(4) that(5) that(6) that(7))\n      ultimately have \"col (inter (line A C) (line E F)) (inter (line C D) (line B F))\n      (inter (line A B) (line D E))\" if \"distinct6 P Q R A C W\"\n        and  \"C \\<notin> line_ext (line E F)\" and \"A \\<notin> line_ext (line D E)\" and \"line B C \\<noteq> line A B\"\n        and \"line E F \\<noteq> line A F\" and \"A \\<notin> line_ext (line C D)\"\n        and \"inter (line B C) (line E F) \\<noteq> inter (line A C) (line E F)\"\n        by (metis Q_def W_def col_A_B_ABl col_rot_CW that(1) that(2) that(3) that(4) that(5) that(6) \n            that(7))\n      show \"col X Y Z\"\n        by (metis P_def W_def X_def Y_def Z_def \\<open>A = W \\<Longrightarrow> col X Y Z\\<close> \\<open>A \\<in> line_ext (line C D) \\<Longrightarrow> col X Y Z\\<close> \n            \\<open>A \\<in> line_ext (line D E) \\<Longrightarrow> col X Y Z\\<close> \\<open>C = W \\<Longrightarrow> col X Y Z\\<close> \\<open>C \\<in> line_ext (line E F) \\<Longrightarrow> col X Y Z\\<close> \n            \\<open>P = A \\<Longrightarrow> col X Y Z\\<close> \\<open>P = C \\<Longrightarrow> col X Y Z\\<close> \\<open>P = Q \\<Longrightarrow> col X Y Z\\<close> \\<open>P = R \\<Longrightarrow> col X Y Z\\<close> \n            \\<open>Pascal_Property.inter (line B C) (line E F) = Pascal_Property.inter (line A C) (line E F) \\<Longrightarrow> col X Y Z\\<close> \n            \\<open>Q = A \\<Longrightarrow> col X Y Z\\<close> \\<open>Q = C \\<Longrightarrow> col X Y Z\\<close> \\<open>Q = R \\<Longrightarrow> col X Y Z\\<close> \\<open>Q = W \\<Longrightarrow> col X Y Z\\<close> \\<open>R = A \\<Longrightarrow> col X Y Z\\<close> \n            \\<open>R = C \\<Longrightarrow> col X Y Z\\<close> \\<open>R = W \\<Longrightarrow> col X Y Z\\<close> \\<open>\\<lbrakk>distinct6 P Q R A C W; C \\<notin> line_ext (line E F); A \\<notin> line_ext (line D E); line B C \\<noteq> line A B; line E F \\<noteq> line A F; A \\<notin> line_ext (line C D); Pascal_Property.inter (line B C) (line E F) \\<noteq> Pascal_Property.inter (line A C) (line E F)\\<rbrakk> \\<Longrightarrow> col (Pascal_Property.inter (line A C) (line E F)) (Pascal_Property.inter (line C D) (line B F)) (Pascal_Property.inter (line A B) (line D E))\\<close> \n            \\<open>line B C = line A B \\<Longrightarrow> col X Y Z\\<close> \\<open>line E F = line A F \\<Longrightarrow> col X Y Z\\<close> distinct6_def line_comm)\n     qed\n     show \"is_pascal B A C D E F\"\n       using X_def Y_def Z_def \\<open>\\<lbrakk>distinct6 B A C D E F; line A C \\<noteq> line E F; line C D \\<noteq> line B F; line B A \\<noteq> line D E; line B C = line E F\\<rbrakk> \\<Longrightarrow> col X Y Z\\<close> \n         \\<open>\\<lbrakk>distinct6 B A C D E F; line A C \\<noteq> line E F; line C D \\<noteq> line B F; line B A \\<noteq> line D E; line B C \\<noteq> line E F; line C D \\<noteq> line A F\\<rbrakk> \\<Longrightarrow> col X Y Z\\<close> \n         \\<open>\\<lbrakk>distinct6 B A C D E F; line A C \\<noteq> line E F; line C D \\<noteq> line B F; line B A \\<noteq> line D E; line C D = line A F\\<rbrakk> \\<Longrightarrow> col X Y Z\\<close> \n         is_pascal_def \n       by force\n  qed\n  thus \"pascal_prop\" using pascal_prop_def \n    by auto\nqed\n\nlemma is_pascal_under_alternate_vertices:\n  assumes \"pascal_prop\" and \"is_pascal A B C A' B' C'\"\n  shows \"is_pascal A B' C A' B C'\"\n  using assms pascal_prop_def is_pascal_rot_CW \n  by presburger\n\nlemma col_inter:\n  assumes \"distinct6 A B C D E F\" and \"col A B C\" and \"col D E F\"\n  shows \"inter (line B C) (line E F) = inter (line A B) (line D E)\"\n  by (smt assms ax_uniqueness col_def distinct6_def incidA_lAB incidB_lAB)\n\nlemma pascal_pappus1:\n  assumes \"pascal_prop\"\n  shows \"is_pappus1 A B C A' B' C' P Q R\"\nproof-\n  define a1 a2 a3 a4 a5 a6 where \"a1 = distinct6 A B C A' B' C'\"  and \"a2 = col A B C\" and \n\"a3 = col A' B' C'\" and \"a4 = is_a_proper_intersec P A B' A' B\" and \"a5 = is_a_proper_intersec Q B C' B' C\" \nand \"a6 = is_a_proper_intersec R A C' A' C\" \n  (* i.e. we have assumed a Pappus configuration *)\n  have \"inter (line B C) (line B' C') = inter (line A B) (line A' B')\" if a1 a2 a3 a4 a5 a6\n    using a1_def a2_def a3_def col_inter that(1) that(2) that(3) \n    by blast\n  then have \"is_pascal A B C A' B' C'\" if a1 a2 a3 a4 a5 a6\n    using a1_def col_ABA is_pascal_def that(1) that(2) that(3) that(4) that(5) that(6) \n    by auto\n  then have \"is_pascal A B' C A' B C'\" if a1 a2 a3 a4 a5 a6\n    using assms is_pascal_under_alternate_vertices that(1) that(2) that(3) that(4) that(5) that(6) \n    by blast\n  then have \"col P Q R\" if a1 a2 a3 a4 a5 a6\n    by (smt a1_def a4_def a5_def a6_def ax_uniqueness col_def distinct6_def incidB_lAB incid_inter_left \n        incid_inter_right is_a_proper_intersec_def is_pascal_def line_comm that(1) that(2) that(3) \n        that(4) that(5) that(6))\n  show \"is_pappus1 A B C A' B' C' P Q R\"\n    by (simp add: \\<open>\\<lbrakk>a1; a2; a3; a4; a5; a6\\<rbrakk> \\<Longrightarrow> col P Q R\\<close> a1_def a2_def a3_def a4_def a5_def a6_def \n        is_pappus1_def)\nqed\n\nlemma pascal_pappus:\n  assumes \"pascal_prop\"\n  shows \"is_pappus\"\n  by (simp add: assms is_pappus_def pappus12 pascal_pappus1)\n\ntheorem pappus_iff_pascal: \"is_pappus = pascal_prop\"\n  using pappus_pascal pascal_pappus \n  by blast\n\nend\n\n\n\n\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/Projective_Geometry/Pascal_Property.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8774767842777551, "lm_q2_score": 0.8333245932423308, "lm_q1q2_score": 0.7312229843378487}}
{"text": "(*\nTitle:  Allen's qualitative temporal calculus\nAuthor:  Fadoua Ghourabi (fadouaghourabi@gmail.com)\nAffiliation: Ochanomizu University, Japan\n*)\n\n\n\ntheory axioms\n\nimports\n    Main  xor_cal\n\nbegin\n\n\nsection \\<open>Axioms\\<close>\n\ntext\\<open>We formalize Allen's definition of theory of time in term of intervals (Allen, 1983). \nTwo relations, namely meets and equality, are defined between intervals. Two interval meets if they  are adjacent \nA set of 5 axioms ((M1) $\\sim$ (M5)) are then defined based on relation meets.\\<close>\n\ntext\\<open>We define a class interval whose assumptions are (i) properties of relations meets  and, (ii) axioms (M1) $\\sim$ (M5).\\<close>\n\nclass interval =\n fixes\n  meets::\"'a \\<Rightarrow> 'a \\<Rightarrow> bool\"  (infixl \"\\<parallel>\" 60) and\n  \\<I>::\"'a \\<Rightarrow> bool\"\n assumes\n  meets_atrans:\"\\<lbrakk>(p\\<parallel>q);(q\\<parallel>r)\\<rbrakk> \\<Longrightarrow> \\<not>(p\\<parallel>r)\" and\n  meets_irrefl:\"\\<I> p \\<Longrightarrow> \\<not>(p\\<parallel>p)\" and\n  meets_asym:\"(p\\<parallel>q) \\<Longrightarrow> \\<not>(q\\<parallel>p)\" and\n  meets_wd:\"p\\<parallel>q \\<Longrightarrow> \\<I> p \\<and> \\<I> q\" and\n(**** Time axioms ******)\n  M1:\"\\<lbrakk>(p\\<parallel>q); (p\\<parallel>s); (r\\<parallel>q)\\<rbrakk> \\<Longrightarrow> (r\\<parallel>s)\" and\n  M2:\"\\<lbrakk>(p\\<parallel>q) ; (r\\<parallel>s)\\<rbrakk> \\<Longrightarrow> p\\<parallel>s \\<oplus> ((\\<exists>t. (p\\<parallel>t)\\<and>(t\\<parallel>s)) \\<oplus> (\\<exists>t. (r\\<parallel>t)\\<and>(t\\<parallel>q)))\" and\n  M3:\"\\<I> p \\<Longrightarrow> (\\<exists>q r. q\\<parallel>p \\<and> p\\<parallel>r)\" and\n  M4:\"\\<lbrakk>p\\<parallel>q ; q\\<parallel>s ; p\\<parallel>r ; r\\<parallel>s\\<rbrakk> \\<Longrightarrow> q = r\"  and\n  M5exist:\"p\\<parallel>q \\<Longrightarrow> (\\<exists>r s t. r\\<parallel>p \\<and> p\\<parallel>q \\<and> q\\<parallel>s \\<and> r\\<parallel>t \\<and> t\\<parallel>s)\" \n(**********)\n\nlemma  (in interval) trans2:\"\\<lbrakk>p\\<parallel>t; t\\<parallel>r; r\\<parallel>q\\<rbrakk> \\<Longrightarrow> \\<not>p\\<parallel>q\"\n  using M1 meets_asym by blast\n\n\n\nlemma (in interval) nonmeets1:\"\\<not> (u\\<parallel>r \\<and> r\\<parallel>u)\" \n  using meets_asym by blast\n\nlemma (in interval)  nonmeets2: \"\\<lbrakk>\\<I> u ; \\<I> r \\<rbrakk> \\<Longrightarrow> \\<not> (u\\<parallel>r \\<and> u = r)\" \n  using meets_irrefl by blast\n\nlemma (in interval) nonmeets3: \"\\<not> (u\\<parallel>r \\<and> (\\<exists>p. u\\<parallel>p \\<and> p\\<parallel>r))\" \n  using nontrans1 by blast\n\nlemma (in interval) nonmeets4: \"\\<not>(u\\<parallel>r \\<and> (\\<exists>p. r\\<parallel>p \\<and> p\\<parallel>u))\" \n  using nontrans2 by blast\n\nlemma (in interval) elimmeets: \"(p \\<parallel> s \\<and> (\\<exists>t. p \\<parallel> t \\<and> t \\<parallel> s) \\<and> (\\<exists>t. r \\<parallel> t \\<and> t \\<parallel> q)) = False\"\n  using meets_atrans by blast \n\nlemma (in interval) M5exist_var:\nassumes \"x\\<parallel>y\" \"y\\<parallel>z\" \"z\\<parallel>w\"\nshows \"\\<exists>t. x\\<parallel>t \\<and> t\\<parallel>w\"\nproof -\n  from assms(1,3) have a:\"x\\<parallel>w \\<oplus> (\\<exists>t. x\\<parallel>t \\<and> t\\<parallel>w) \\<oplus> (\\<exists>t. z\\<parallel>t \\<and> t\\<parallel>y)\" using M2[of x y z w] by auto\n  from assms have b1:\"\\<not>x\\<parallel>w\" using trans2 by blast\n  from assms(2) have \"\\<not> (\\<exists>t. z\\<parallel>t \\<and> t\\<parallel>y)\" by (simp add: nontrans2)\n  with b1 a have \" (\\<exists>t. x\\<parallel>t \\<and> t\\<parallel>w)\" by simp\n  thus ?thesis by simp\nqed\n\nlemma (in interval) M5exist_var2:\nassumes \"p\\<parallel>q\"\nshows \"\\<exists>r1 r2 r3 s t. r1\\<parallel>r2 \\<and> r2\\<parallel>r3 \\<and> r3\\<parallel>p \\<and> p\\<parallel>q \\<and> q\\<parallel>s \\<and> r1\\<parallel>t \\<and> t\\<parallel>s\"\nproof -\n  from assms obtain r3 k1 s  where r3p:\"r3\\<parallel>p\" and  qs:\"q\\<parallel>s\"  and  r3k1:\"r3 \\<parallel>k1\"  and  k1s:\"k1\\<parallel>s\" using M5exist by blast \n  from r3p obtain r2 where r2r3:\"r2\\<parallel>r3\" using M3[of r3] meets_wd by auto\n  from r2r3 obtain r1 where r1r2:\"r1\\<parallel>r2\" using M3[of r2] meets_wd by auto\n  with  assms  r2r3 r3p qs obtain t where r1t1:\"r1\\<parallel>t\" and t1q:\"t\\<parallel>s\" using M5exist_var by blast\n  with assms r1r2 r2r3 r3p qs show ?thesis by blast\nqed\n  \nlemma (in interval) M5exist_var3:\nassumes \"k\\<parallel>l\" and \"l\\<parallel>q\" and \"q\\<parallel>t\" and \"t\\<parallel>r\" \nshows  \"\\<exists>lqt. k\\<parallel>lqt \\<and> lqt\\<parallel>r\"\nproof -\n  from assms(1-3) obtain lq where \"k\\<parallel>lq\" and \"lq\\<parallel>t\" \n  using M5exist_var by blast \n  with assms(4) obtain lqt where \"k\\<parallel>lqt\" and \"lqt\\<parallel>r\" \n  using M5exist_var by blast\n  thus ?thesis by 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/Allen_Calculus/axioms.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8918110511888303, "lm_q2_score": 0.8198933315126791, "lm_q1q2_score": 0.7311899338390344}}
{"text": "(*  Title:      Doc/Functions/Functions.thy\n    Author:     Alexander Krauss, TU Muenchen\n\nTutorial for function definitions with the new \"function\" package.\n*)\n\ntheory Functions\nimports Main\nbegin\n\nsection \\<open>Function Definitions for Dummies\\<close>\n\ntext \\<open>\n  In most cases, defining a recursive function is just as simple as other definitions:\n\\<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>\n  The syntax is rather self-explanatory: We introduce a function by\n  giving its name, its type, \n  and a set of defining recursive equations.\n  If we leave out the type, the most general type will be\n  inferred, which can sometimes lead to surprises: Since both @{term\n  \"1::nat\"} and @{text \"+\"} are overloaded, we would end up\n  with @{text \"fib :: nat \\<Rightarrow> 'a::{one,plus}\"}.\n\\<close>\n\ntext \\<open>\n  The function always terminates, since its argument gets smaller in\n  every recursive call. \n  Since HOL is a logic of total functions, termination is a\n  fundamental requirement to prevent inconsistencies\\footnote{From the\n  \\qt{definition} @{text \"f(n) = f(n) + 1\"} we could prove \n  @{text \"0 = 1\"} by subtracting @{text \"f(n)\"} on both sides.}.\n  Isabelle tries to prove termination automatically when a definition\n  is made. In \\S\\ref{termination}, we will look at cases where this\n  fails and see what to do then.\n\\<close>\n\nsubsection \\<open>Pattern matching\\<close>\n\ntext \\<open>\\label{patmatch}\n  Like in functional programming, we can use pattern matching to\n  define functions. At the moment we will only consider \\emph{constructor\n  patterns}, which only consist of datatype constructors and\n  variables. Furthermore, patterns must be linear, i.e.\\ all variables\n  on the left hand side of an equation must be distinct. In\n  \\S\\ref{genpats} we discuss more general pattern matching.\n\n  If patterns overlap, the order of the equations is taken into\n  account. The following function inserts a fixed element between any\n  two elements of a list:\n\\<close>\n\nfun sep :: \"'a \\<Rightarrow> 'a list \\<Rightarrow> 'a list\"\nwhere\n  \"sep a (x#y#xs) = x # a # sep a (y # xs)\"\n| \"sep a xs       = xs\"\n\ntext \\<open>\n  Overlapping patterns are interpreted as \\qt{increments} to what is\n  already there: The second equation is only meant for the cases where\n  the first one does not match. Consequently, Isabelle replaces it\n  internally by the remaining cases, making the patterns disjoint:\n\\<close>\n\nthm sep.simps\n\ntext \\<open>@{thm [display] sep.simps[no_vars]}\\<close>\n\ntext \\<open>\n  \\noindent The equations from function definitions are automatically used in\n  simplification:\n\\<close>\n\nlemma \"sep 0 [1, 2, 3] = [1, 0, 2, 0, 3]\"\nby simp\n\nsubsection \\<open>Induction\\<close>\n\ntext \\<open>\n\n  Isabelle provides customized induction rules for recursive\n  functions. These rules follow the recursive structure of the\n  definition. Here is the rule @{thm [source] sep.induct} arising from the\n  above definition of @{const sep}:\n\n  @{thm [display] sep.induct}\n  \n  We have a step case for list with at least two elements, and two\n  base cases for the zero- and the one-element list. Here is a simple\n  proof about @{const sep} and @{const map}\n\\<close>\n\nlemma \"map f (sep x ys) = sep (f x) (map f ys)\"\napply (induct x ys rule: sep.induct)\n\ntext \\<open>\n  We get three cases, like in the definition.\n\n  @{subgoals [display]}\n\\<close>\n\napply auto \ndone\ntext \\<open>\n\n  With the \\cmd{fun} command, you can define about 80\\% of the\n  functions that occur in practice. The rest of this tutorial explains\n  the remaining 20\\%.\n\\<close>\n\n\nsection \\<open>fun vs.\\ function\\<close>\n\ntext \\<open>\n  The \\cmd{fun} command provides a\n  convenient shorthand notation for simple function definitions. In\n  this mode, Isabelle tries to solve all the necessary proof obligations\n  automatically. If any proof fails, the definition is\n  rejected. This can either mean that the definition is indeed faulty,\n  or that the default proof procedures are just not smart enough (or\n  rather: not designed) to handle the definition.\n\n  By expanding the abbreviation to the more verbose \\cmd{function} command, these proof obligations become visible and can be analyzed or\n  solved manually. The expansion from \\cmd{fun} to \\cmd{function} is as follows:\n\n\\end{isamarkuptext}\n\n\n\\[\\left[\\;\\begin{minipage}{0.25\\textwidth}\\vspace{6pt}\n\\cmd{fun} @{text \"f :: \\<tau>\"}\\\\%\n\\cmd{where}\\\\%\n\\hspace*{2ex}{\\it equations}\\\\%\n\\hspace*{2ex}\\vdots\\vspace*{6pt}\n\\end{minipage}\\right]\n\\quad\\equiv\\quad\n\\left[\\;\\begin{minipage}{0.48\\textwidth}\\vspace{6pt}\n\\cmd{function} @{text \"(\"}\\cmd{sequential}@{text \") f :: \\<tau>\"}\\\\%\n\\cmd{where}\\\\%\n\\hspace*{2ex}{\\it equations}\\\\%\n\\hspace*{2ex}\\vdots\\\\%\n\\cmd{by} @{text \"pat_completeness auto\"}\\\\%\n\\cmd{termination by} @{text \"lexicographic_order\"}\\vspace{6pt}\n\\end{minipage}\n\\right]\\]\n\n\\begin{isamarkuptext}\n  \\vspace*{1em}\n  \\noindent Some details have now become explicit:\n\n  \\begin{enumerate}\n  \\item The \\cmd{sequential} option enables the preprocessing of\n  pattern overlaps which we already saw. Without this option, the equations\n  must already be disjoint and complete. The automatic completion only\n  works with constructor patterns.\n\n  \\item A function definition produces a proof obligation which\n  expresses completeness and compatibility of patterns (we talk about\n  this later). The combination of the methods @{text \"pat_completeness\"} and\n  @{text \"auto\"} is used to solve this proof obligation.\n\n  \\item A termination proof follows the definition, started by the\n  \\cmd{termination} command. This will be explained in \\S\\ref{termination}.\n \\end{enumerate}\n  Whenever a \\cmd{fun} command fails, it is usually a good idea to\n  expand the syntax to the more verbose \\cmd{function} form, to see\n  what is actually going on.\n\\<close>\n\n\nsection \\<open>Termination\\<close>\n\ntext \\<open>\\label{termination}\n  The method @{text \"lexicographic_order\"} is the default method for\n  termination proofs. It can prove termination of a\n  certain class of functions by searching for a suitable lexicographic\n  combination of size measures. Of course, not all functions have such\n  a simple termination argument. For them, we can specify the termination\n  relation manually.\n\\<close>\n\nsubsection \\<open>The {\\tt relation} method\\<close>\ntext\\<open>\n  Consider the following function, which sums up natural numbers up to\n  @{text \"N\"}, using a counter @{text \"i\"}:\n\\<close>\n\nfunction sum :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\"\nwhere\n  \"sum i N = (if i > N then 0 else i + sum (Suc i) N)\"\nby pat_completeness auto\n\ntext \\<open>\n  \\noindent The @{text \"lexicographic_order\"} method fails on this example, because none of the\n  arguments decreases in the recursive call, with respect to the standard size ordering.\n  To prove termination manually, we must provide a custom wellfounded relation.\n\n  The termination argument for @{text \"sum\"} is based on the fact that\n  the \\emph{difference} between @{text \"i\"} and @{text \"N\"} gets\n  smaller in every step, and that the recursion stops when @{text \"i\"}\n  is greater than @{text \"N\"}. Phrased differently, the expression \n  @{text \"N + 1 - i\"} always decreases.\n\n  We can use this expression as a measure function suitable to prove termination.\n\\<close>\n\ntermination sum\napply (relation \"measure (\\<lambda>(i,N). N + 1 - i)\")\n\ntext \\<open>\n  The \\cmd{termination} command sets up the termination goal for the\n  specified function @{text \"sum\"}. If the function name is omitted, it\n  implicitly refers to the last function definition.\n\n  The @{text relation} method takes a relation of\n  type @{typ \"('a \\<times> 'a) set\"}, where @{typ \"'a\"} is the argument type of\n  the function. If the function has multiple curried arguments, then\n  these are packed together into a tuple, as it happened in the above\n  example.\n\n  The predefined function @{term[source] \"measure :: ('a \\<Rightarrow> nat) \\<Rightarrow> ('a \\<times> 'a) set\"} constructs a\n  wellfounded relation from a mapping into the natural numbers (a\n  \\emph{measure function}). \n\n  After the invocation of @{text \"relation\"}, we must prove that (a)\n  the relation we supplied is wellfounded, and (b) that the arguments\n  of recursive calls indeed decrease with respect to the\n  relation:\n\n  @{subgoals[display,indent=0]}\n\n  These goals are all solved by @{text \"auto\"}:\n\\<close>\n\napply auto\ndone\n\ntext \\<open>\n  Let us complicate the function a little, by adding some more\n  recursive calls: \n\\<close>\n\nfunction foo :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\"\nwhere\n  \"foo i N = (if i > N \n              then (if N = 0 then 0 else foo 0 (N - 1))\n              else i + foo (Suc i) N)\"\nby pat_completeness auto\n\ntext \\<open>\n  When @{text \"i\"} has reached @{text \"N\"}, it starts at zero again\n  and @{text \"N\"} is decremented.\n  This corresponds to a nested\n  loop where one index counts up and the other down. Termination can\n  be proved using a lexicographic combination of two measures, namely\n  the value of @{text \"N\"} and the above difference. The @{const\n  \"measures\"} combinator generalizes @{text \"measure\"} by taking a\n  list of measure functions.  \n\\<close>\n\ntermination \nby (relation \"measures [\\<lambda>(i, N). N, \\<lambda>(i,N). N + 1 - i]\") auto\n\nsubsection \\<open>How @{text \"lexicographic_order\"} works\\<close>\n\n(*fun fails :: \"nat \\<Rightarrow> nat list \\<Rightarrow> nat\"\nwhere\n  \"fails a [] = a\"\n| \"fails a (x#xs) = fails (x + a) (x # xs)\"\n*)\n\ntext \\<open>\n  To see how the automatic termination proofs work, let's look at an\n  example where it fails\\footnote{For a detailed discussion of the\n  termination prover, see @{cite bulwahnKN07}}:\n\n\\end{isamarkuptext}  \n\\cmd{fun} @{text \"fails :: \\\"nat \\<Rightarrow> nat list \\<Rightarrow> nat\\\"\"}\\\\%\n\\cmd{where}\\\\%\n\\hspace*{2ex}@{text \"\\\"fails a [] = a\\\"\"}\\\\%\n|\\hspace*{1.5ex}@{text \"\\\"fails a (x#xs) = fails (x + a) (x#xs)\\\"\"}\\\\\n\\begin{isamarkuptext}\n\n\\noindent Isabelle responds with the following error:\n\n\\begin{isabelle}\n*** Unfinished subgoals:\\newline\n*** (a, 1, <):\\newline\n*** \\ 1.~@{text \"\\<And>x. x = 0\"}\\newline\n*** (a, 1, <=):\\newline\n*** \\ 1.~False\\newline\n*** (a, 2, <):\\newline\n*** \\ 1.~False\\newline\n*** Calls:\\newline\n*** a) @{text \"(a, x # xs) -->> (x + a, x # xs)\"}\\newline\n*** Measures:\\newline\n*** 1) @{text \"\\<lambda>x. size (fst x)\"}\\newline\n*** 2) @{text \"\\<lambda>x. size (snd x)\"}\\newline\n*** Result matrix:\\newline\n*** \\ \\ \\ \\ 1\\ \\ 2  \\newline\n*** a:  ?   <= \\newline\n*** Could not find lexicographic termination order.\\newline\n*** At command \"fun\".\\newline\n\\end{isabelle}\n\\<close>\ntext \\<open>\n  The key to this error message is the matrix at the bottom. The rows\n  of that matrix correspond to the different recursive calls (In our\n  case, there is just one). The columns are the function's arguments \n  (expressed through different measure functions, which map the\n  argument tuple to a natural number). \n\n  The contents of the matrix summarize what is known about argument\n  descents: The second argument has a weak descent (@{text \"<=\"}) at the\n  recursive call, and for the first argument nothing could be proved,\n  which is expressed by @{text \"?\"}. In general, there are the values\n  @{text \"<\"}, @{text \"<=\"} and @{text \"?\"}.\n\n  For the failed proof attempts, the unfinished subgoals are also\n  printed. Looking at these will often point to a missing lemma.\n\\<close>\n\nsubsection \\<open>The @{text size_change} method\\<close>\n\ntext \\<open>\n  Some termination goals that are beyond the powers of\n  @{text lexicographic_order} can be solved automatically by the\n  more powerful @{text size_change} method, which uses a variant of\n  the size-change principle, together with some other\n  techniques. While the details are discussed\n  elsewhere @{cite krauss_phd},\n  here are a few typical situations where\n  @{text lexicographic_order} has difficulties and @{text size_change}\n  may be worth a try:\n  \\begin{itemize}\n  \\item Arguments are permuted in a recursive call.\n  \\item Several mutually recursive functions with multiple arguments.\n  \\item Unusual control flow (e.g., when some recursive calls cannot\n  occur in sequence).\n  \\end{itemize}\n\n  Loading the theory @{text Multiset} makes the @{text size_change}\n  method a bit stronger: it can then use multiset orders internally.\n\\<close>\n\nsection \\<open>Mutual Recursion\\<close>\n\ntext \\<open>\n  If two or more functions call one another mutually, they have to be defined\n  in one step. Here are @{text \"even\"} and @{text \"odd\"}:\n\\<close>\n\nfunction even :: \"nat \\<Rightarrow> bool\"\n    and odd  :: \"nat \\<Rightarrow> bool\"\nwhere\n  \"even 0 = True\"\n| \"odd 0 = False\"\n| \"even (Suc n) = odd n\"\n| \"odd (Suc n) = even n\"\nby pat_completeness auto\n\ntext \\<open>\n  To eliminate the mutual dependencies, Isabelle internally\n  creates a single function operating on the sum\n  type @{typ \"nat + nat\"}. Then, @{const even} and @{const odd} are\n  defined as projections. Consequently, termination has to be proved\n  simultaneously for both functions, by specifying a measure on the\n  sum type: \n\\<close>\n\ntermination \nby (relation \"measure (\\<lambda>x. case x of Inl n \\<Rightarrow> n | Inr n \\<Rightarrow> n)\") auto\n\ntext \\<open>\n  We could also have used @{text lexicographic_order}, which\n  supports mutual recursive termination proofs to a certain extent.\n\\<close>\n\nsubsection \\<open>Induction for mutual recursion\\<close>\n\ntext \\<open>\n\n  When functions are mutually recursive, proving properties about them\n  generally requires simultaneous induction. The induction rule @{thm [source] \"even_odd.induct\"}\n  generated from the above definition reflects this.\n\n  Let us prove something about @{const even} and @{const odd}:\n\\<close>\n\nlemma even_odd_mod2:\n  \"even n = (n mod 2 = 0)\"\n  \"odd n = (n mod 2 = 1)\"\n\ntext \\<open>\n  We apply simultaneous induction, specifying the induction variable\n  for both goals, separated by \\cmd{and}:\\<close>\n\napply (induct n and n rule: even_odd.induct)\n\ntext \\<open>\n  We get four subgoals, which correspond to the clauses in the\n  definition of @{const even} and @{const odd}:\n  @{subgoals[display,indent=0]}\n  Simplification solves the first two goals, leaving us with two\n  statements about the @{text \"mod\"} operation to prove:\n\\<close>\n\napply simp_all\n\ntext \\<open>\n  @{subgoals[display,indent=0]} \n\n  \\noindent These can be handled by Isabelle's arithmetic decision procedures.\n  \n\\<close>\n\napply arith\napply arith\ndone\n\ntext \\<open>\n  In proofs like this, the simultaneous induction is really essential:\n  Even if we are just interested in one of the results, the other\n  one is necessary to strengthen the induction hypothesis. If we leave\n  out the statement about @{const odd} and just write @{term True} instead,\n  the same proof fails:\n\\<close>\n\nlemma failed_attempt:\n  \"even n = (n mod 2 = 0)\"\n  \"True\"\napply (induct n rule: even_odd.induct)\n\ntext \\<open>\n  \\noindent Now the third subgoal is a dead end, since we have no\n  useful induction hypothesis available:\n\n  @{subgoals[display,indent=0]} \n\\<close>\n\noops\n\nsection \\<open>Elimination\\<close>\n\ntext \\<open>\n  A definition of function @{text f} gives rise to two kinds of elimination rules. Rule @{text f.cases}\n  simply describes case analysis according to the patterns used in the definition:\n\\<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\nthm list_to_option.cases\ntext \\<open>\n  @{thm[display] list_to_option.cases}\n\n  Note that this rule does not mention the function at all, but only describes the cases used for\n  defining it. In contrast, the rule @{thm[source] list_to_option.elims} also tell us what the function\n  value will be in each case:\n\\<close>\nthm list_to_option.elims\ntext \\<open>\n  @{thm[display] list_to_option.elims}\n\n  \\noindent\n  This lets us eliminate an assumption of the form @{prop \"list_to_option xs = y\"} and replace it\n  with the two cases, e.g.:\n\\<close>\n\nlemma \"list_to_option xs = y \\<Longrightarrow> P\"\nproof (erule list_to_option.elims)\n  fix x assume \"xs = [x]\" \"y = Some x\" thus P sorry\nnext\n  assume \"xs = []\" \"y = None\" thus P sorry\nnext\n  fix a b xs' assume \"xs = a # b # xs'\" \"y = None\" thus P sorry\nqed\n\n\ntext \\<open>\n  Sometimes it is convenient to derive specialized versions of the @{text elim} rules above and\n  keep them around as facts explicitly. For example, it is natural to show that if \n  @{prop \"list_to_option xs = Some y\"}, then @{term xs} must be a singleton. The command \n  \\cmd{fun\\_cases} derives such facts automatically, by instantiating and simplifying the general \n  elimination rules given some pattern:\n\\<close>\n\nfun_cases list_to_option_SomeE[elim]: \"list_to_option xs = Some y\"\n\nthm list_to_option_SomeE\ntext \\<open>\n  @{thm[display] list_to_option_SomeE}\n\\<close>\n\n\nsection \\<open>General pattern matching\\<close>\ntext\\<open>\\label{genpats}\\<close>\n\nsubsection \\<open>Avoiding automatic pattern splitting\\<close>\n\ntext \\<open>\n\n  Up to now, we used pattern matching only on datatypes, and the\n  patterns were always disjoint and complete, and if they weren't,\n  they were made disjoint automatically like in the definition of\n  @{const \"sep\"} in \\S\\ref{patmatch}.\n\n  This automatic splitting can significantly increase the number of\n  equations involved, and this is not always desirable. The following\n  example shows the problem:\n  \n  Suppose we are modeling incomplete knowledge about the world by a\n  three-valued datatype, which has values @{term \"T\"}, @{term \"F\"}\n  and @{term \"X\"} for true, false and uncertain propositions, respectively. \n\\<close>\n\ndatatype P3 = T | F | X\n\ntext \\<open>\\noindent Then the conjunction of such values can be defined as follows:\\<close>\n\nfun And :: \"P3 \\<Rightarrow> P3 \\<Rightarrow> P3\"\nwhere\n  \"And T p = p\"\n| \"And p T = p\"\n| \"And p F = F\"\n| \"And F p = F\"\n| \"And X X = X\"\n\n\ntext \\<open>\n  This definition is useful, because the equations can directly be used\n  as simplification rules. But the patterns overlap: For example,\n  the expression @{term \"And T T\"} is matched by both the first and\n  the second equation. By default, Isabelle makes the patterns disjoint by\n  splitting them up, producing instances:\n\\<close>\n\nthm And.simps\n\ntext \\<open>\n  @{thm[indent=4] And.simps}\n  \n  \\vspace*{1em}\n  \\noindent There are several problems with this:\n\n  \\begin{enumerate}\n  \\item If the datatype has many constructors, there can be an\n  explosion of equations. For @{const \"And\"}, we get seven instead of\n  five equations, which can be tolerated, but this is just a small\n  example.\n\n  \\item Since splitting makes the equations \\qt{less general}, they\n  do not always match in rewriting. While the term @{term \"And x F\"}\n  can be simplified to @{term \"F\"} with the original equations, a\n  (manual) case split on @{term \"x\"} is now necessary.\n\n  \\item The splitting also concerns the induction rule @{thm [source]\n  \"And.induct\"}. Instead of five premises it now has seven, which\n  means that our induction proofs will have more cases.\n\n  \\item In general, it increases clarity if we get the same definition\n  back which we put in.\n  \\end{enumerate}\n\n  If we do not want the automatic splitting, we can switch it off by\n  leaving out the \\cmd{sequential} option. However, we will have to\n  prove that our pattern matching is consistent\\footnote{This prevents\n  us from defining something like @{term \"f x = True\"} and @{term \"f x\n  = False\"} simultaneously.}:\n\\<close>\n\nfunction And2 :: \"P3 \\<Rightarrow> P3 \\<Rightarrow> P3\"\nwhere\n  \"And2 T p = p\"\n| \"And2 p T = p\"\n| \"And2 p F = F\"\n| \"And2 F p = F\"\n| \"And2 X X = X\"\n\ntext \\<open>\n  \\noindent Now let's look at the proof obligations generated by a\n  function definition. In this case, they are:\n\n  @{subgoals[display,indent=0]}\\vspace{-1.2em}\\hspace{3cm}\\vdots\\vspace{1.2em}\n\n  The first subgoal expresses the completeness of the patterns. It has\n  the form of an elimination rule and states that every @{term x} of\n  the function's input type must match at least one of the patterns\\footnote{Completeness could\n  be equivalently stated as a disjunction of existential statements: \n@{term \"(\\<exists>p. x = (T, p)) \\<or> (\\<exists>p. x = (p, T)) \\<or> (\\<exists>p. x = (p, F)) \\<or>\n  (\\<exists>p. x = (F, p)) \\<or> (x = (X, X))\"}, and you can use the method @{text atomize_elim} to get that form instead.}. If the patterns just involve\n  datatypes, we can solve it with the @{text \"pat_completeness\"}\n  method:\n\\<close>\n\napply pat_completeness\n\ntext \\<open>\n  The remaining subgoals express \\emph{pattern compatibility}. We do\n  allow that an input value matches multiple patterns, but in this\n  case, the result (i.e.~the right hand sides of the equations) must\n  also be equal. For each pair of two patterns, there is one such\n  subgoal. Usually this needs injectivity of the constructors, which\n  is used automatically by @{text \"auto\"}.\n\\<close>\n\nby auto\ntermination by (relation \"{}\") simp\n\n\nsubsection \\<open>Non-constructor patterns\\<close>\n\ntext \\<open>\n  Most of Isabelle's basic types take the form of inductive datatypes,\n  and usually pattern matching works on the constructors of such types. \n  However, this need not be always the case, and the \\cmd{function}\n  command handles other kind of patterns, too.\n\n  One well-known instance of non-constructor patterns are\n  so-called \\emph{$n+k$-patterns}, which are a little controversial in\n  the functional programming world. Here is the initial fibonacci\n  example with $n+k$-patterns:\n\\<close>\n\nfunction fib2 :: \"nat \\<Rightarrow> nat\"\nwhere\n  \"fib2 0 = 1\"\n| \"fib2 1 = 1\"\n| \"fib2 (n + 2) = fib2 n + fib2 (Suc n)\"\n\ntext \\<open>\n  This kind of matching is again justified by the proof of pattern\n  completeness and compatibility. \n  The proof obligation for pattern completeness states that every natural number is\n  either @{term \"0::nat\"}, @{term \"1::nat\"} or @{term \"n +\n  (2::nat)\"}:\n\n  @{subgoals[display,indent=0,goals_limit=1]}\n\n  This is an arithmetic triviality, but unfortunately the\n  @{text arith} method cannot handle this specific form of an\n  elimination rule. However, we can use the method @{text\n  \"atomize_elim\"} to do an ad-hoc conversion to a disjunction of\n  existentials, which can then be solved by the arithmetic decision procedure.\n  Pattern compatibility and termination are automatic as usual.\n\\<close>\napply atomize_elim\napply arith\napply auto\ndone\ntermination by lexicographic_order\ntext \\<open>\n  We can stretch the notion of pattern matching even more. The\n  following function is not a sensible functional program, but a\n  perfectly valid mathematical definition:\n\\<close>\n\nfunction ev :: \"nat \\<Rightarrow> bool\"\nwhere\n  \"ev (2 * n) = True\"\n| \"ev (2 * n + 1) = False\"\napply atomize_elim\nby arith+\ntermination by (relation \"{}\") simp\n\ntext \\<open>\n  This general notion of pattern matching gives you a certain freedom\n  in writing down specifications. However, as always, such freedom should\n  be used with care:\n\n  If we leave the area of constructor\n  patterns, we have effectively departed from the world of functional\n  programming. This means that it is no longer possible to use the\n  code generator, and expect it to generate ML code for our\n  definitions. Also, such a specification might not work very well together with\n  simplification. Your mileage may vary.\n\\<close>\n\n\nsubsection \\<open>Conditional equations\\<close>\n\ntext \\<open>\n  The function package also supports conditional equations, which are\n  similar to guards in a language like Haskell. Here is Euclid's\n  algorithm written with conditional patterns\\footnote{Note that the\n  patterns are also overlapping in the base case}:\n\\<close>\n\nfunction gcd :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\"\nwhere\n  \"gcd x 0 = x\"\n| \"gcd 0 y = y\"\n| \"x < y \\<Longrightarrow> gcd (Suc x) (Suc y) = gcd (Suc x) (y - x)\"\n| \"\\<not> x < y \\<Longrightarrow> gcd (Suc x) (Suc y) = gcd (x - y) (Suc y)\"\nby (atomize_elim, auto, arith)\ntermination by lexicographic_order\n\ntext \\<open>\n  By now, you can probably guess what the proof obligations for the\n  pattern completeness and compatibility look like. \n\n  Again, functions with conditional patterns are not supported by the\n  code generator.\n\\<close>\n\n\nsubsection \\<open>Pattern matching on strings\\<close>\n\ntext \\<open>\n  As strings (as lists of characters) are normal datatypes, pattern\n  matching on them is possible, but somewhat problematic. Consider the\n  following definition:\n\n\\end{isamarkuptext}\n\\noindent\\cmd{fun} @{text \"check :: \\\"string \\<Rightarrow> bool\\\"\"}\\\\%\n\\cmd{where}\\\\%\n\\hspace*{2ex}@{text \"\\\"check (''good'') = True\\\"\"}\\\\%\n@{text \"| \\\"check s = False\\\"\"}\n\\begin{isamarkuptext}\n\n  \\noindent An invocation of the above \\cmd{fun} command does not\n  terminate. What is the problem? Strings are lists of characters, and\n  characters are a datatype with a lot of constructors. Splitting the\n  catch-all pattern thus leads to an explosion of cases, which cannot\n  be handled by Isabelle.\n\n  There are two things we can do here. Either we write an explicit\n  @{text \"if\"} on the right hand side, or we can use conditional patterns:\n\\<close>\n\nfunction check :: \"string \\<Rightarrow> bool\"\nwhere\n  \"check (''good'') = True\"\n| \"s \\<noteq> ''good'' \\<Longrightarrow> check s = False\"\nby auto\ntermination by (relation \"{}\") simp\n\n\nsection \\<open>Partiality\\<close>\n\ntext \\<open>\n  In HOL, all functions are total. A function @{term \"f\"} applied to\n  @{term \"x\"} always has the value @{term \"f x\"}, and there is no notion\n  of undefinedness. \n  This is why we have to do termination\n  proofs when defining functions: The proof justifies that the\n  function can be defined by wellfounded recursion.\n\n  However, the \\cmd{function} package does support partiality to a\n  certain extent. Let's look at the following function which looks\n  for a zero of a given function f. \n\\<close>\n\nfunction (*<*)(domintros)(*>*)findzero :: \"(nat \\<Rightarrow> nat) \\<Rightarrow> nat \\<Rightarrow> nat\"\nwhere\n  \"findzero f n = (if f n = 0 then n else findzero f (Suc n))\"\nby pat_completeness auto\n\ntext \\<open>\n  \\noindent Clearly, any attempt of a termination proof must fail. And without\n  that, we do not get the usual rules @{text \"findzero.simps\"} and \n  @{text \"findzero.induct\"}. So what was the definition good for at all?\n\\<close>\n\nsubsection \\<open>Domain predicates\\<close>\n\ntext \\<open>\n  The trick is that Isabelle has not only defined the function @{const findzero}, but also\n  a predicate @{term \"findzero_dom\"} that characterizes the values where the function\n  terminates: the \\emph{domain} of the function. If we treat a\n  partial function just as a total function with an additional domain\n  predicate, we can derive simplification and\n  induction rules as we do for total functions. They are guarded\n  by domain conditions and are called @{text psimps} and @{text\n  pinduct}: \n\\<close>\n\ntext \\<open>\n  \\noindent\\begin{minipage}{0.79\\textwidth}@{thm[display,margin=85] findzero.psimps}\\end{minipage}\n  \\hfill(@{thm [source] \"findzero.psimps\"})\n  \\vspace{1em}\n\n  \\noindent\\begin{minipage}{0.79\\textwidth}@{thm[display,margin=85] findzero.pinduct}\\end{minipage}\n  \\hfill(@{thm [source] \"findzero.pinduct\"})\n\\<close>\n\ntext \\<open>\n  Remember that all we\n  are doing here is use some tricks to make a total function appear\n  as if it was partial. We can still write the term @{term \"findzero\n  (\\<lambda>x. 1) 0\"} and like any other term of type @{typ nat} it is equal\n  to some natural number, although we might not be able to find out\n  which one. The function is \\emph{underdefined}.\n\n  But it is defined enough to prove something interesting about it. We\n  can prove that if @{term \"findzero f n\"}\n  terminates, it indeed returns a zero of @{term f}:\n\\<close>\n\nlemma findzero_zero: \"findzero_dom (f, n) \\<Longrightarrow> f (findzero f n) = 0\"\n\ntext \\<open>\\noindent We apply induction as usual, but using the partial induction\n  rule:\\<close>\n\napply (induct f n rule: findzero.pinduct)\n\ntext \\<open>\\noindent This gives the following subgoals:\n\n  @{subgoals[display,indent=0]}\n\n  \\noindent The hypothesis in our lemma was used to satisfy the first premise in\n  the induction rule. However, we also get @{term\n  \"findzero_dom (f, n)\"} as a local assumption in the induction step. This\n  allows unfolding @{term \"findzero f n\"} using the @{text psimps}\n  rule, and the rest is trivial.\n\\<close>\napply (simp add: findzero.psimps)\ndone\n\ntext \\<open>\n  Proofs about partial functions are often not harder than for total\n  functions. Fig.~\\ref{findzero_isar} shows a slightly more\n  complicated proof written in Isar. It is verbose enough to show how\n  partiality comes into play: From the partial induction, we get an\n  additional domain condition hypothesis. Observe how this condition\n  is applied when calls to @{term findzero} are unfolded.\n\\<close>\n\ntext_raw \\<open>\n\\begin{figure}\n\\hrule\\vspace{6pt}\n\\begin{minipage}{0.8\\textwidth}\n\\isabellestyle{it}\n\\isastyle\\isamarkuptrue\n\\<close>\nlemma \"\\<lbrakk>findzero_dom (f, n); x \\<in> {n ..< findzero f n}\\<rbrakk> \\<Longrightarrow> f x \\<noteq> 0\"\nproof (induct rule: findzero.pinduct)\n  fix f n assume dom: \"findzero_dom (f, n)\"\n               and IH: \"\\<lbrakk>f n \\<noteq> 0; x \\<in> {Suc n ..< findzero f (Suc n)}\\<rbrakk> \\<Longrightarrow> f x \\<noteq> 0\"\n               and x_range: \"x \\<in> {n ..< findzero f n}\"\n  have \"f n \\<noteq> 0\"\n  proof \n    assume \"f n = 0\"\n    with dom have \"findzero f n = n\" by (simp add: findzero.psimps)\n    with x_range show False by auto\n  qed\n  \n  from x_range have \"x = n \\<or> x \\<in> {Suc n ..< findzero f n}\" by auto\n  thus \"f x \\<noteq> 0\"\n  proof\n    assume \"x = n\"\n    with \\<open>f n \\<noteq> 0\\<close> show ?thesis by simp\n  next\n    assume \"x \\<in> {Suc n ..< findzero f n}\"\n    with dom and \\<open>f n \\<noteq> 0\\<close> have \"x \\<in> {Suc n ..< findzero f (Suc n)}\" by (simp add: findzero.psimps)\n    with IH and \\<open>f n \\<noteq> 0\\<close>\n    show ?thesis by simp\n  qed\nqed\ntext_raw \\<open>\n\\isamarkupfalse\\isabellestyle{tt}\n\\end{minipage}\\vspace{6pt}\\hrule\n\\caption{A proof about a partial function}\\label{findzero_isar}\n\\end{figure}\n\\<close>\n\nsubsection \\<open>Partial termination proofs\\<close>\n\ntext \\<open>\n  Now that we have proved some interesting properties about our\n  function, we should turn to the domain predicate and see if it is\n  actually true for some values. Otherwise we would have just proved\n  lemmas with @{term False} as a premise.\n\n  Essentially, we need some introduction rules for @{text\n  findzero_dom}. The function package can prove such domain\n  introduction rules automatically. But since they are not used very\n  often (they are almost never needed if the function is total), this\n  functionality is disabled by default for efficiency reasons. So we have to go\n  back and ask for them explicitly by passing the @{text\n  \"(domintros)\"} option to the function package:\n\n\\vspace{1ex}\n\\noindent\\cmd{function} @{text \"(domintros) findzero :: \\\"(nat \\<Rightarrow> nat) \\<Rightarrow> nat \\<Rightarrow> nat\\\"\"}\\\\%\n\\cmd{where}\\isanewline%\n\\ \\ \\ldots\\\\\n\n  \\noindent Now the package has proved an introduction rule for @{text findzero_dom}:\n\\<close>\n\nthm findzero.domintros\n\ntext \\<open>\n  @{thm[display] findzero.domintros}\n\n  Domain introduction rules allow to show that a given value lies in the\n  domain of a function, if the arguments of all recursive calls\n  are in the domain as well. They allow to do a \\qt{single step} in a\n  termination proof. Usually, you want to combine them with a suitable\n  induction principle.\n\n  Since our function increases its argument at recursive calls, we\n  need an induction principle which works \\qt{backwards}. We will use\n  @{thm [source] inc_induct}, which allows to do induction from a fixed number\n  \\qt{downwards}:\n\n  \\begin{center}@{thm inc_induct}\\hfill(@{thm [source] \"inc_induct\"})\\end{center}\n\n  Figure \\ref{findzero_term} gives a detailed Isar proof of the fact\n  that @{text findzero} terminates if there is a zero which is greater\n  or equal to @{term n}. First we derive two useful rules which will\n  solve the base case and the step case of the induction. The\n  induction is then straightforward, except for the unusual induction\n  principle.\n\n\\<close>\n\ntext_raw \\<open>\n\\begin{figure}\n\\hrule\\vspace{6pt}\n\\begin{minipage}{0.8\\textwidth}\n\\isabellestyle{it}\n\\isastyle\\isamarkuptrue\n\\<close>\nlemma findzero_termination:\n  assumes \"x \\<ge> n\" and \"f x = 0\"\n  shows \"findzero_dom (f, n)\"\nproof - \n  have base: \"findzero_dom (f, x)\"\n    by (rule findzero.domintros) (simp add:\\<open>f x = 0\\<close>)\n\n  have step: \"\\<And>i. findzero_dom (f, Suc i) \n    \\<Longrightarrow> findzero_dom (f, i)\"\n    by (rule findzero.domintros) simp\n\n  from \\<open>x \\<ge> n\\<close> show ?thesis\n  proof (induct rule:inc_induct)\n    show \"findzero_dom (f, x)\" by (rule base)\n  next\n    fix i assume \"findzero_dom (f, Suc i)\"\n    thus \"findzero_dom (f, i)\" by (rule step)\n  qed\nqed      \ntext_raw \\<open>\n\\isamarkupfalse\\isabellestyle{tt}\n\\end{minipage}\\vspace{6pt}\\hrule\n\\caption{Termination proof for @{text findzero}}\\label{findzero_term}\n\\end{figure}\n\\<close>\n      \ntext \\<open>\n  Again, the proof given in Fig.~\\ref{findzero_term} has a lot of\n  detail in order to explain the principles. Using more automation, we\n  can also have a short proof:\n\\<close>\n\nlemma findzero_termination_short:\n  assumes zero: \"x >= n\" \n  assumes [simp]: \"f x = 0\"\n  shows \"findzero_dom (f, n)\"\nusing zero\nby (induct rule:inc_induct) (auto intro: findzero.domintros)\n    \ntext \\<open>\n  \\noindent It is simple to combine the partial correctness result with the\n  termination lemma:\n\\<close>\n\nlemma findzero_total_correctness:\n  \"f x = 0 \\<Longrightarrow> f (findzero f 0) = 0\"\nby (blast intro: findzero_zero findzero_termination)\n\nsubsection \\<open>Definition of the domain predicate\\<close>\n\ntext \\<open>\n  Sometimes it is useful to know what the definition of the domain\n  predicate looks like. Actually, @{text findzero_dom} is just an\n  abbreviation:\n\n  @{abbrev[display] findzero_dom}\n\n  The domain predicate is the \\emph{accessible part} of a relation @{const\n  findzero_rel}, which was also created internally by the function\n  package. @{const findzero_rel} is just a normal\n  inductive predicate, so we can inspect its definition by\n  looking at the introduction rules @{thm [source] findzero_rel.intros}.\n  In our case there is just a single rule:\n\n  @{thm[display] findzero_rel.intros}\n\n  The predicate @{const findzero_rel}\n  describes the \\emph{recursion relation} of the function\n  definition. The recursion relation is a binary relation on\n  the arguments of the function that relates each argument to its\n  recursive calls. In general, there is one introduction rule for each\n  recursive call.\n\n  The predicate @{term \"Wellfounded.accp findzero_rel\"} is the accessible part of\n  that relation. An argument belongs to the accessible part, if it can\n  be reached in a finite number of steps (cf.~its definition in @{text\n  \"Wellfounded.thy\"}).\n\n  Since the domain predicate is just an abbreviation, you can use\n  lemmas for @{const Wellfounded.accp} and @{const findzero_rel} directly. Some\n  lemmas which are occasionally useful are @{thm [source] accpI}, @{thm [source]\n  accp_downward}, and of course the introduction and elimination rules\n  for the recursion relation @{thm [source] \"findzero_rel.intros\"} and @{thm\n  [source] \"findzero_rel.cases\"}.\n\\<close>\n\nsection \\<open>Nested recursion\\<close>\n\ntext \\<open>\n  Recursive calls which are nested in one another frequently cause\n  complications, since their termination proof can depend on a partial\n  correctness property of the function itself. \n\n  As a small example, we define the \\qt{nested zero} function:\n\\<close>\n\nfunction nz :: \"nat \\<Rightarrow> nat\"\nwhere\n  \"nz 0 = 0\"\n| \"nz (Suc n) = nz (nz n)\"\nby pat_completeness auto\n\ntext \\<open>\n  If we attempt to prove termination using the identity measure on\n  naturals, this fails:\n\\<close>\n\ntermination\n  apply (relation \"measure (\\<lambda>n. n)\")\n  apply auto\n\ntext \\<open>\n  We get stuck with the subgoal\n\n  @{subgoals[display]}\n\n  Of course this statement is true, since we know that @{const nz} is\n  the zero function. And in fact we have no problem proving this\n  property by induction.\n\\<close>\n(*<*)oops(*>*)\nlemma nz_is_zero: \"nz_dom n \\<Longrightarrow> nz n = 0\"\n  by (induct rule:nz.pinduct) (auto simp: nz.psimps)\n\ntext \\<open>\n  We formulate this as a partial correctness lemma with the condition\n  @{term \"nz_dom n\"}. This allows us to prove it with the @{text\n  pinduct} rule before we have proved termination. With this lemma,\n  the termination proof works as expected:\n\\<close>\n\ntermination\n  by (relation \"measure (\\<lambda>n. n)\") (auto simp: nz_is_zero)\n\ntext \\<open>\n  As a general strategy, one should prove the statements needed for\n  termination as a partial property first. Then they can be used to do\n  the termination proof. This also works for less trivial\n  examples. Figure \\ref{f91} defines the 91-function, a well-known\n  challenge problem due to John McCarthy, and proves its termination.\n\\<close>\n\ntext_raw \\<open>\n\\begin{figure}\n\\hrule\\vspace{6pt}\n\\begin{minipage}{0.8\\textwidth}\n\\isabellestyle{it}\n\\isastyle\\isamarkuptrue\n\\<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\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 assume \"\\<not> 100 < n\" -- \"Assumptions for both calls\"\n\n  thus \"(n + 11, n) \\<in> ?R\" by simp -- \"Inner call\"\n\n  assume inner_trm: \"f91_dom (n + 11)\" -- \"Outer call\"\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_raw \\<open>\n\\isamarkupfalse\\isabellestyle{tt}\n\\end{minipage}\n\\vspace{6pt}\\hrule\n\\caption{McCarthy's 91-function}\\label{f91}\n\\end{figure}\n\\<close>\n\n\nsection \\<open>Higher-Order Recursion\\<close>\n\ntext \\<open>\n  Higher-order recursion occurs when recursive calls\n  are passed as arguments to higher-order combinators such as @{const\n  map}, @{term filter} etc.\n  As an example, imagine a datatype of n-ary trees:\n\\<close>\n\ndatatype 'a tree = \n  Leaf 'a \n| Branch \"'a tree list\"\n\n\ntext \\<open>\\noindent We can define a function which swaps the left and right subtrees recursively, using the \n  list functions @{const rev} and @{const map}:\\<close>\n\nfun mirror :: \"'a tree \\<Rightarrow> 'a tree\"\nwhere\n  \"mirror (Leaf n) = Leaf n\"\n| \"mirror (Branch l) = Branch (rev (map mirror l))\"\n\ntext \\<open>\n  Although the definition is accepted without problems, let us look at the termination proof:\n\\<close>\n\ntermination proof\n  text \\<open>\n\n  As usual, we have to give a wellfounded relation, such that the\n  arguments of the recursive calls get smaller. But what exactly are\n  the arguments of the recursive calls when mirror is given as an\n  argument to @{const map}? Isabelle gives us the\n  subgoals\n\n  @{subgoals[display,indent=0]} \n\n  So the system seems to know that @{const map} only\n  applies the recursive call @{term \"mirror\"} to elements\n  of @{term \"l\"}, which is essential for the termination proof.\n\n  This knowledge about @{const map} is encoded in so-called congruence rules,\n  which are special theorems known to the \\cmd{function} command. The\n  rule for @{const map} is\n\n  @{thm[display] map_cong}\n\n  You can read this in the following way: Two applications of @{const\n  map} are equal, if the list arguments are equal and the functions\n  coincide on the elements of the list. This means that for the value \n  @{term \"map f l\"} we only have to know how @{term f} behaves on\n  the elements of @{term l}.\n\n  Usually, one such congruence rule is\n  needed for each higher-order construct that is used when defining\n  new functions. In fact, even basic functions like @{const\n  If} and @{const Let} are handled by this mechanism. The congruence\n  rule for @{const If} states that the @{text then} branch is only\n  relevant if the condition is true, and the @{text else} branch only if it\n  is false:\n\n  @{thm[display] if_cong}\n  \n  Congruence rules can be added to the\n  function package by giving them the @{term fundef_cong} attribute.\n\n  The constructs that are predefined in Isabelle, usually\n  come with the respective congruence rules.\n  But if you define your own higher-order functions, you may have to\n  state and prove the required congruence rules yourself, if you want to use your\n  functions in recursive definitions. \n\\<close>\n(*<*)oops(*>*)\n\nsubsection \\<open>Congruence Rules and Evaluation Order\\<close>\n\ntext \\<open>\n  Higher order logic differs from functional programming languages in\n  that it has no built-in notion of evaluation order. A program is\n  just a set of equations, and it is not specified how they must be\n  evaluated. \n\n  However for the purpose of function definition, we must talk about\n  evaluation order implicitly, when we reason about termination.\n  Congruence rules express that a certain evaluation order is\n  consistent with the logical definition. \n\n  Consider the following function.\n\\<close>\n\nfunction f :: \"nat \\<Rightarrow> bool\"\nwhere\n  \"f n = (n = 0 \\<or> f (n - 1))\"\n(*<*)by pat_completeness auto(*>*)\n\ntext \\<open>\n  For this definition, the termination proof fails. The default configuration\n  specifies no congruence rule for disjunction. We have to add a\n  congruence rule that specifies left-to-right evaluation order:\n\n  \\vspace{1ex}\n  \\noindent @{thm disj_cong}\\hfill(@{thm [source] \"disj_cong\"})\n  \\vspace{1ex}\n\n  Now the definition works without problems. Note how the termination\n  proof depends on the extra condition that we get from the congruence\n  rule.\n\n  However, as evaluation is not a hard-wired concept, we\n  could just turn everything around by declaring a different\n  congruence rule. Then we can make the reverse definition:\n\\<close>\n\nlemma disj_cong2[fundef_cong]: \n  \"(\\<not> Q' \\<Longrightarrow> P = P') \\<Longrightarrow> (Q = Q') \\<Longrightarrow> (P \\<or> Q) = (P' \\<or> Q')\"\n  by blast\n\nfun f' :: \"nat \\<Rightarrow> bool\"\nwhere\n  \"f' n = (f' (n - 1) \\<or> n = 0)\"\n\ntext \\<open>\n  \\noindent These examples show that, in general, there is no \\qt{best} set of\n  congruence rules.\n\n  However, such tweaking should rarely be necessary in\n  practice, as most of the time, the default set of congruence rules\n  works well.\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/Doc/Functions/Functions.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.819893340314393, "lm_q2_score": 0.8918110360927155, "lm_q1q2_score": 0.7311899293112962}}
{"text": "theory Chapter3\nimports \"HOL-IMP.BExp\"\n        \"HOL-IMP.ASM\"\nbegin\n\n(*\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 a1 a2) = (case ((optimal a1),(optimal a2)) of\n      (False,_) \\<Rightarrow> False\n      |(_,False) \\<Rightarrow> False\n      |_ \\<Rightarrow> True)\"\n(*\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 rule:asimp_const.induct)\n  apply(auto split:aexp.split)\n  done\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*)\n\nlemma \"optimal (asimp_const a)\" (is \"?P a\")\nproof (induction a rule:asimp_const.induct)\n  fix n\n  let ?a = \"N n\"\n  show \"?P ?a\" by simp\nnext \n  fix x \n  let ?a = \"V x\"\n  show \"?P ?a\" by simp\nnext \n  fix a1 a2\n  assume ind1: \"optimal (asimp_const a1)\" \"optimal (asimp_const a2)\"\n  let ?a = \"Plus a1 a2\"\n  show \"?P ?a\" \n    using ind1 by (auto split : aexp.split)\nqed\n\n\n\n(*\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\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\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\n(*\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\"\n  apply(induction t)\n  apply(auto simp add : sepN_def)\n  done\n\nlemma aval_sepN_isar: \"aval (sepN t) s = aval t s\" (is \"?P t s\")\nproof (induction t arbitrary : s)\n  fix x s\n  let ?t = \"N x\" \n  have \"aval (sepN ?t) s = (aval (Plus (N (sumN ?t)) (zeroN ?t)) s)\" by (auto simp add : sepN_def)\n  also have \"(aval (Plus (N (sumN ?t)) (zeroN ?t)) s) = (aval ?t s)\" by simp\n  finally show \"?P ?t s\" by simp\nnext\n  fix x s\n  let ?t = \"V x\"\n  show \"?P ?t s\" by (simp add : sepN_def)\nnext\n  fix t1 t2 s\n  assume IH : \"\\<And>s. aval (sepN t1) s = aval t1 s\" \"\\<And>s. aval (sepN t2) s = aval t2 s\"\n  let ?t = \"Plus t1 t2\"\n  have \"aval (sepN (Plus t1 t2)) s = aval (Plus (N (sumN ?t)) (zeroN ?t)) s\" using sepN_def by simp\n  also have \"... = (+) (aval (N (sumN ?t)) s) (aval (zeroN ?t) s)\" by simp\n  also have \"... = (+) ((+) (aval (N (sumN t1)) s) (aval (N (sumN t2)) s))\n                       ((+) (aval (zeroN t1) s) (aval (zeroN t2) s))\" by simp\n  also have \"... = (+) ((+) (aval (N (sumN t1)) s) (aval (zeroN t1) s))\n                       ((+) (aval (N (sumN t2)) s) (aval (zeroN t2) s))\" by simp\n  also have \"... = (+) (aval (sepN t1) s)\n                       (aval (sepN t2) s)\" using sepN_def by simp\n  also have \"... = aval ?t s\" using IH by simp\n  finally show \"?P ?t s\" using sepN_def by auto\nqed\n\n(*\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)\n  apply(auto simp add:full_asimp_def sepN_def)\n  done\n\nlemma aval_full_asimp_isar : \"aval (full_asimp t) s = aval t s\" (is \"?P t s\")\nproof (induction t)\n  fix x \n  let ?t = \"N x\"\n  show \"?P ?t s\" by (simp add : full_asimp_def sepN_def)\nnext\n  fix x\n  let ?t = \"V x\"\n  show \"?P ?t s\" by (simp add : full_asimp_def sepN_def)\nnext\n  fix t1 t2\n  assume ind : \"aval (full_asimp t1) s = aval t1 s\" \"aval (full_asimp t2) s = aval t2 s\"\n  let ?t = \"Plus t1 t2\"\n  have \"aval (full_asimp ?t) s = aval (asimp (sepN ?t)) s\" by (simp add : full_asimp_def)\n  also have \"... = aval (asimp (Plus (N (sumN ?t)) (zeroN ?t))) s\" by (simp add : sepN_def)\n  finally show \"?P ?t s\" using ind full_asimp_def sepN_def by simp\nqed\n  \n (*\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 (V y) = (if x = y then a else V y)\"\n| \"subst _ _ (N n) = N n\"\n| \"subst x a1 (Plus a2 a3) = Plus (subst x a1 a2) (subst x a1 a3)\"\n\n(*\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\nlemma subst_lemma_isar : \"aval (subst x a e) s = aval e (s (x := aval a s))\" (is \"?P e\")\nproof (induction e)\n  fix n \n  let ?e = \"N n\"\n  show \"?P ?e\" by auto \nnext\n  fix v\n  let ?e = \"V v\"\n  show \"?P ?e\" by auto\nnext\n  fix e1 e2\n  assume ind : \"aval (subst x a e1) s = aval e1 (s(x := aval a s))\"\n               \"aval (subst x a e2) s = aval e2 (s(x := aval a s))\"\n  let ?e =\"Plus e1 e2\"\n  have \"aval (subst x a ?e) s = aval (Plus (subst x a e1) (subst x a e2)) s\" by simp\n  also have \"... = (aval (subst x a e1) s) + (aval (subst x a e2) s)\" by simp\n  also have \"... = (aval e1 (s(x := aval a s))) + (aval e2 (s(x := aval a s)))\" using ind by simp\n  also have \"... = aval (Plus e1 e2) (s (x := aval a s))\" by simp\n  (* finally show \"?P ?e\" by simp   *) (* qqq : pourquoi pas *) \n  finally show \"aval (subst x a ?e) s = aval ?e (s (x := aval a s))\" by simp\nqed\n\n(*\nAs a consequence prove that we can substitute equal expressions by equal expressions\nand obtain the same result under evaluation:\n*)\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\nlemma \"aval a1 s = aval a2 s\n  \\<Longrightarrow> aval (subst x a1 e) s = aval (subst x a2 e) s\"\nproof-\n  fix a1 a2 s\n  assume H : \"aval a1 s = aval a2 s\"\n  show \"aval (subst x a1 e) s = aval (subst x a2 e) s\" (is \"?P e\")\n  proof (induction e)\n    fix n\n    let ?e = \"N n\"\n    show \"?P ?e\" by simp\n  next\n    fix v\n    let ?e = \"V v\"\n(*    have \"aval (subst x a1 ?e) s = aval (if x = v then a1 else V v) s\" (is \"?Q = ?R\")\n      by simp\n    also have \"... = (if x = v then aval a1 s else aval (V v) s)\" by simp\n    finally show \"?P ?e\" using \\<open>aval a1 s = aval a2 s\\<close> by simp  *)\n    show \"?P ?e\" using \\<open>aval a1 s = aval a2 s\\<close> by simp\n  next\n    fix e1 e2\n    assume id : \"aval (subst x a1 e1) s = aval (subst x a2 e1) s\"\n                \"aval (subst x a1 e2) s = aval (subst x a2 e2) s\"\n    let ?e = \"Plus e1 e2\"\n    show \"?P ?e\" using H id by simp\n  qed\nqed\n    \n(*\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\ndatatype myaexp = N int | V vname | Plus myaexp myaexp | Times myaexp myaexp\n\nfun myaval :: \"myaexp \\<Rightarrow> state \\<Rightarrow> val\" where\n  \"myaval (N n) _ = n\"\n| \"myaval (V x) s = s x\"\n| \"myaval (Plus a1 a2) s = (+) (myaval a1 s) (myaval a2 s)\"\n| \"myaval (Times a1 a2) s = (*) (myaval a1 s) (myaval a2 s)\"\n\nfun myplus :: \"myaexp \\<Rightarrow> myaexp \\<Rightarrow> myaexp\" where\n  \"myplus (N n1) (N n2) = N (n1 + n2)\"\n| \"myplus (N n) a = (if n = 0 then a else (Plus (N n) a))\"\n| \"myplus a (N n) = (if n = 0 then a else (Plus a (N n)))\"\n| \"myplus a1 a2 = Plus a1 a2\"\n\nfun mytimes :: \"myaexp \\<Rightarrow> myaexp \\<Rightarrow> myaexp\" where\n  \"mytimes (N n1) (N n2) = N (n1 * n2)\"\n| \"mytimes (N n) a = (if n = 0 then N 0 else if n = 1 then a else (Times (N n) a))\"\n| \"mytimes a (N n) = (if n = 0 then N 0 else if n = 1 then a else (Times a (N n)))\"\n| \"mytimes a1 a2 = Times a1 a2\"\n\nfun myasimp :: \"myaexp \\<Rightarrow> myaexp\" where\n  \"myasimp (N x) = (N x)\"\n| \"myasimp (V x) = (V x)\"\n| \"myasimp (Plus a1 a2) = myplus (myasimp a1) (myasimp a2)\"\n| \"myasimp (Times a1 a2) = mytimes (myasimp a1) (myasimp a2)\"\n\n(*\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\n(*\n\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\n(* 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\nfun lval :: \"lexp \\<Rightarrow> state \\<Rightarrow> int\" where\n  \"lval (Nl n) _ = n\"\n| \"lval (Vl v) s = s v\"\n| \"lval (Plusl e1 e2) s = (+) (lval e1 s) (lval e2 s)\"\n| \"lval (LET x e1 e2) s = lval e2 (s (x := lval e1 s))\"\n\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 inline :: \"lexp \\<Rightarrow> aexp\" where\n  \"inline (Nl n) = (aexp.N n)\"\n| \"inline (Vl v) = (aexp.V v)\"\n| \"inline (Plusl e1 e2) = aexp.Plus (inline e1) (inline e2)\"\n| \"inline (LET x e1 e2) = subst x (inline e1) (inline e2)\"\n\n(*\nlemma \"lval e s = aval (inline e) s\"\n  apply(induction e rule:lexp.induct)\n  apply(auto split:aexp.split lexp.split)\n*)\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\n(*\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(simp add : Le_def)\n  apply(auto)\n  done\n\nlemma bval_Le_isar : \"bval (Le a1 a2) s = (aval a1 s \\<le> aval a2 s)\"\nproof-\n  fix a1 a2 s\n  have \"bval (Le a1 a2) s = bval (Not (Less a2 a1)) s\" by (simp add : Le_def)\n  also have \"... = (\\<not> bval (Less a2 a1) s)\" by simp\n  also have \"... = (\\<not> (aval a2 s) < (aval a1 s))\" by simp\n  also have \"... = ((aval a1 s) \\<le> (aval a2 s))\" by auto\n  finally show \"bval (Le a1 a2) s = (aval a1 s \\<le> aval a2 s)\" by simp\nqed\n\nlemma bval_Eq: \"bval (Eq a1 a2) s = (aval a1 s = aval a2 s)\"\n  apply(simp add : Eq_def Le_def)\n  apply(auto)\n  done\n\nlemma bval_Eq_isar: \"bval (Eq a1 a2) s = (aval a1 s = aval a2 s)\"\n  unfolding Eq_def Le_def\nproof\n  fix a1 a2 s\n  assume \"bval (And (bexp.Not (Less a2 a1)) (bexp.Not (Less a1 a2))) s\"\n  then show \"aval a1 s = aval a2 s\" by simp\nnext\n  fix a1 a2 s\n  assume \"aval a1 s = aval a2 s\"\n  then show \"bval (And (bexp.Not (Less a2 a1)) (bexp.Not (Less a1 a2))) s\" by simp\nqed\n  \n(*\nConsider an alternative type of boolean expressions featuring a conditional: \n*)\n\ndatatype ifexp = Bc2 bool | If ifexp ifexp ifexp | Less2 aexp aexp\n\n(* 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 ife1 ife2 ife3) s = (if (ifval ife1 s) then (ifval ife2 s) else (ifval ife3 s))\"\n| \"ifval (Less2 ae1 ae2) s = ((aval ae1 s) < (aval ae2 s))\"\n\ntext{* Then define two translation functions *}\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) (If (b2ifexp b2) (Bc2 True) (Bc2 False)) (Bc2 False))\"\n| \"b2ifexp (Less a1 a2) = (Less2 a1 a2)\"\n\nfun if2bexp :: \"ifexp \\<Rightarrow> bexp\" where\n  \"if2bexp (Bc2 b) = (Bc b)\"\n| \"if2bexp (If e1 e2 e3) = (Not (And (Not (And (if2bexp e1) (if2bexp e2)))\n                                     (Not (And (Not (if2bexp e1)) (if2bexp e3)))\n                                 ))\"\n| \"if2bexp (Less2 a1 a2) = (Less a1 a2)\"\n\ntext{* and prove their correctness: *}\n\nlemma \"bval (if2bexp exp) s = ifval exp s\"\n  by induction auto\n\nlemma \"bval (if2bexp exp) s = ifval exp s\" (is \"?P ?exp\")\nproof (induction)\n  fix x\n  let ?exp = \"Bc2 x\"\n  show \"bval (if2bexp ?exp) s = ifval ?exp s\" by auto\nnext\n  fix a1 a2\n  let ?exp = \"Less2 a1 a2\"\n  show \"bval (if2bexp ?exp) s = ifval ?exp s\" by auto\nnext\n  fix e1 e2 e3\n  assume ind : \"bval (if2bexp e1) s = ifval e1 s\"\n               \"bval (if2bexp e2) s = ifval e2 s\"\n               \"bval (if2bexp e3) s = ifval e3 s\"\n  let ?exp = \"If e1 e2 e3\"\n  have \"bval (if2bexp (ifexp.If e1 e2 e3)) s = \n           bval (Not (And (Not (And (if2bexp e1) (if2bexp e2)))\n                     (Not (And (Not (if2bexp e1)) (if2bexp e3)))\n                 )) s\" by simp\n  then show \"bval (if2bexp ?exp) s = ifval ?exp s\" using ind by auto\nqed\n\nlemma \"ifval (b2ifexp exp) s = bval exp s\"\n  by (induction exp) auto\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 (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 (VAR _)) = True\"\n| \"is_nnf (NOT _) = False\"\n| \"is_nnf (VAR _) = True\"\n\n(*\nNow define a function that converts a @{text bexp} into NNF by pushing\n@{const NOT} inwards as much as possible:\n*)\n\n\nfun nnf :: \"pbexp \\<Rightarrow> pbexp\" where\n  \"nnf (VAR x) = (VAR x)\"\n| \"nnf (AND e1 e2) = (AND (nnf e1) (nnf e2))\"\n| \"nnf (OR e1 e2) = (OR (nnf e1) (nnf e2))\"\n| \"nnf (NOT (NOT e)) = (nnf e)\"\n| \"nnf (NOT (VAR x)) = (NOT (VAR x))\"\n| \"nnf (NOT (AND e1 e2)) = (OR (nnf (NOT e1)) (nnf (NOT e2)))\"\n| \"nnf (NOT (OR e1 e2)) = (AND (nnf (NOT e1)) (nnf (NOT e2)))\"\n\n(*\nProve that @{const nnf} does what it is supposed to do:\n*)\n\nlemma pbval_nnf: \"pbval (nnf b) s = pbval b s\"\n  apply(induction b rule : nnf.induct)\n        apply(auto)\n  done\n\nlemma pbval_nnf_isar : \"pbval (nnf b) s = pbval b s\" (is \"?P b\")\nproof (induction b rule : nnf.induct)\n  fix x\n  let ?b = \"VAR x\"\n  show \"?P ?b\" by simp\nnext\n  fix e1 e2\n  assume ind : \"pbval (nnf e1) s = pbval e1 s\"\n                \"pbval (nnf e2) s = pbval e2 s\"\n  let ?b = \"AND e1 e2\"\n  show \"?P ?b\" using ind by simp\n\nnext \n  fix e1 e2\n  assume ind : \"pbval (nnf e1) s = pbval e1 s\"\n                \"pbval (nnf e2) s = pbval e2 s\"\n  show \"?P (OR e1 e2)\" using ind by simp\nnext \n  fix e\n  assume ind : \"pbval (nnf e) s = pbval e s\"\n  show \"?P (NOT (NOT e))\" using ind by simp\nnext \n  fix x \n  show \"?P (NOT (VAR x))\"  by simp\nnext\n  fix e1 e2\n  assume ind : \"pbval (nnf (NOT e1)) s = pbval (NOT e1) s\"\n         \"pbval (nnf (NOT e2)) s = pbval (NOT e2) s\"\n  show \"?P (NOT (AND e1 e2))\" using ind by simp\nnext \n  fix e1 e2\n  assume ind : \"pbval (nnf (NOT e1)) s = pbval (NOT e1) s\" \n               \"pbval (nnf (NOT e2)) s = pbval (NOT e2) s\"\n  show \"?P (NOT (OR e1 e2))\" using ind by simp\nqed\n\nlemma is_nnf_nnf: \"is_nnf (nnf b)\"\n  apply (induction b rule:nnf.induct)\n  apply(auto)\n  done\n\nlemma is_nnf_nnf_isar: \"is_nnf (nnf b)\" (is \"?P b\")\nproof (induction b rule : nnf.induct)\n  (* 1*)\n  fix x\n  let ?b = \"VAR x\"\n  show \"?P ?b\" by simp \nnext\n  (* 2 *)\n  fix e1 e2\n  assume ind : \"is_nnf (nnf e1)\" \"is_nnf (nnf e2)\"\n  let ?b = \"AND e1 e2\"\n  show \"?P ?b\" using ind by simp\nnext\n  (* 3 *)\n  fix e1 e2\n  assume ind : \"is_nnf (nnf e1)\" \"is_nnf (nnf e2)\"\n  let ?b = \"OR e1 e2\"\n  show \"?P ?b\" using ind by simp\nnext\n  (* 4*)\n  fix e \n  assume ind : \"is_nnf (nnf e)\"\n  let ?b = \"NOT (NOT e)\"\n  show \"?P ?b\" using ind by simp\nnext \n  (* 5 *)\n  fix x \n  let ?b =\"NOT (VAR x)\"\n  show \"?P ?b\" by simp\nnext \n  (* 6 *)\n  fix e1 e2 \n  show \"\\<lbrakk>is_nnf (nnf (NOT e1)); is_nnf (nnf (NOT e2))\\<rbrakk> \\<Longrightarrow> is_nnf (nnf (NOT (AND e1 e2)))\" by simp\nnext \n  (* 7 *)\n  fix e1 e2 \n  show \"\\<lbrakk>is_nnf (nnf (NOT e1)); is_nnf (nnf (NOT e2))\\<rbrakk> \\<Longrightarrow> is_nnf (nnf (NOT (OR e1 e2)))\" by simp\nqed\n\n(*\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\n\n\n(*\nexe: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\n\n\n\n(*\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\n(*\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 exec_mr_1 :: \"instr \\<Rightarrow> state \\<Rightarrow> rstate \\<Rightarrow> rstate\" where\n  \"exec_mr_1 (LDI i r) _ rs = rs(r:=i)\"\n| \"exec_mr_1 (LD v r) s rs = rs(r:=s v)\"\n| \"exec_mr_1 (ADD r1 r2) _ rs = rs(r1 := (rs r1) + (rs r2))\"\n\n(*\nDefine the execution @{const[source] exec} of a list of instructions as for the stack machine.\n*)\n(*The 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 comp_mr :: \"aexp \\<Rightarrow> reg \\<Rightarrow> instr list\" where\n  \"comp_mr (aexp.N n) r = [LDI n r]\"\n| \"comp_mr (aexp.V x) r = [LD x r]\"\n| \"comp_mr (aexp.Plus e1 e2) r = (comp_mr e1 r) @ (comp_mr e2 (r+1)) @ [ADD r (r + 1)]\" \n\nfun exec_mr :: \"instr list \\<Rightarrow> state \\<Rightarrow> rstate \\<Rightarrow> rstate\" where\n  \"exec_mr [] _ rs = rs\"\n| \"exec_mr (i#is) s rs = exec_mr is s (exec_mr_1 i s rs)\"\n\nlemma frame_exec1_LDI :\"r' < r \\<Longrightarrow> (exec_mr_1 (LDI n r) s rs) r' = rs r'\"\n  by simp\n\nlemma frame_exec1_LD :\"r' < r \\<Longrightarrow> (exec_mr_1 (LD v r) s rs) r' = rs r'\"\n  by simp\n\nlemma frame_exec1_ADD :\"r' < r1 \\<Longrightarrow> (exec_mr_1 (ADD r1 r2) s rs) r' = rs r'\"\n  by simp\n\nlemma correct_aux : \"exec_mr (is1 @ is2) s rs r =\n        exec_mr is2 s (exec_mr is1 s rs) r\"\n  apply(induction is1 arbitrary:s rs r)\n  apply(auto)\n  done\n\nlemma frame_exec : \"r' < r \\<Longrightarrow> exec_mr (comp_mr a r) s rs r' = rs r'\"\n  using correct_aux by (induction a arbitrary : r r' s rs) auto\n\nlemma  \"r' < r \\<Longrightarrow> exec_mr (comp_mr a r) s rs r' = rs r'\"\nproof (induction a arbitrary:r r' s rs)\n  case (N x)\n  then show ?case by auto\nnext\n  case (V x)\nthen show ?case by auto\nnext\n  case ind : (Plus a1 a2)\n  have \" exec_mr (comp_mr a1 r) s rs r' = rs r'\" using ind.IH ind.prems by auto\n  also have \" exec_mr (comp_mr a2 r) s rs r' = rs r'\" using ind.IH ind.prems by auto\n  finally show \"exec_mr (comp_mr (aexp.Plus a1 a2) r) s rs r' = rs r'\" \n    using correct_aux ind.IH ind.prems by auto\nqed\n\ntheorem correct : \"exec_mr (comp_mr a r) s rs r = aval a s\"\n  using frame_exec correct_aux by (induction a arbitrary : r s rs) auto\n\ntheorem correct_isar : \"exec_mr (comp_mr a r) s rs r = aval a s\"\nproof (induction a arbitrary : r s rs)\n  fix x r s rs\n  show \"exec_mr (comp_mr (aexp.N x) r) s rs r = aval (aexp.N x) s\" by simp\nnext\n  fix x r s rs\n  show \"exec_mr (comp_mr (aexp.V x) r) s rs r = aval (aexp.V x) s\" by simp\nnext\n  fix a1 a2 r s rs\n\n  let ?l1 = \"comp_mr a1 r\"\n  let ?l2 = \"comp_mr a2 (r+1)\"\n  let ?l3 = \"[ADD r (r+1)]\"\n  let ?rs' = \"exec_mr (comp_mr a1 r) s rs\"\n  let ?rs'' = \"exec_mr (comp_mr a2 (r+1)) s ?rs' \"\n\n  assume ind : \"\\<And>r s rs. (exec_mr (comp_mr a1 r) s rs) r = aval a1 s\" \n               \"\\<And>r s rs. (exec_mr (comp_mr a2 r) s rs) r = aval a2 s\"\n\n  have \"?rs' r = ?rs'' r\" using frame_exec by simp\n  have \"?rs'' (r+1) = aval a2 s\" using ind by simp\n\n  have \"exec_mr (comp_mr (aexp.Plus a1 a2) r) s rs r = \n    exec_mr (?l1 @ ?l2 @ ?l3) s rs r\"\n    by simp\n  also have \"... = exec_mr (?l2 @ ?l3) s ?rs' r\"\n    using correct_aux by simp\n  also have \"... = exec_mr ?l3 s ?rs'' r\" \n    using correct_aux by simp\n  also have \"... = (?rs'' r) + (?rs'' (r+1))\"\n    by simp\n  also have \"... = (aval a1 s) +(?rs'' (r+1))\" \n    using \\<open>?rs' r = ?rs'' r\\<close> ind by simp\n  also have \"... = (aval a1 s) +(aval a2 s)\" \n    using ind by simp  \n  also have \"... = aval (aexp.Plus a1 a2) s\" by simp    \n  finally show \"exec_mr (comp_mr (aexp.Plus a1 a2) r) s rs r = aval (aexp.Plus a1 a2) s\" using ind by auto\nqed\n\n(*\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\n(*\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 exec0_1 :: \"instr0 \\<Rightarrow> state \\<Rightarrow> rstate \\<Rightarrow> rstate\" where\n  \"exec0_1 (LDI0 n) _ rs = rs (0 := n)\"\n| \"exec0_1 (LD0 x) s rs = rs (0 := s x)\"\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> rstate \\<Rightarrow> rstate\" where\n  \"exec0 [] _ rs = rs\"\n| \"exec0 (i#is) s rs = exec0 is s (exec0_1 i s rs)\"\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 comp0 :: \"aexp \\<Rightarrow> reg \\<Rightarrow> instr0 list\" where\n  \"comp0 (aexp.N n) _ = [LDI0 n]\"\n| \"comp0 (aexp.V x) _ = [LD0 x]\"\n| \"comp0 (aexp.Plus a1 a2) r = (comp0 a1 (r+1)) @ [MV0 r] @ (comp0 a2 (r+1)) @ [ADD0 r]\" \n\n(*datatype instr0 = LDI0 val | LD0 vname | MV0 reg | ADD0 reg *)\n(*datatype aexp = N int | V vname | Plus aexp aexp*)\n\nlemma correct_exec0_aux : \"exec0 (is1 @ is2) s rs r =\n        exec0 is2 s (exec0 is1 s rs) r\"\n  apply(induction is1 arbitrary:s rs r)\n  apply(auto)\n  done\n(*fun exec0_1 :: \"instr0 \\<Rightarrow> state \\<Rightarrow> rstate \\<Rightarrow> rstate\" where\n  \"exec0_1 (LDI0 n) _ rs = rs (0 := n)\"\n| \"exec0_1 (LD0 x) s rs = rs (0 := s x)\"\n| \"exec0_1 (MV0 r) _ rs = rs (r := rs 0)\"\n| \"exec0_1 (ADD0 r) _ rs = rs (0 := rs 0 + rs r)\"*)\n\nlemma frame_exec0_LDI : \"r \\<noteq> 0 \\<Longrightarrow> (exec0_1 (LDI0 n) s rs) r = rs r\"\n  by simp \n\nlemma frame_exec0_LD : \"r \\<noteq> 0 \\<Longrightarrow> (exec0_1 (LD0 x) s rs) r = rs r\"\n  by simp\n\nlemma frame_exec0_MV0 : \"r' \\<noteq> r \\<Longrightarrow> (exec0_1 (MV0 r) s rs) r' = rs r'\"\n  by simp\n\nlemma frame_exec0_ADD :\"r' \\<noteq> 0 \\<Longrightarrow> (exec0_1 (ADD0 r) s rs) r' = rs r'\"\n  by simp\n\nlemma frame_exec0 : \"0 < r' \\<Longrightarrow> r' \\<le> r \\<Longrightarrow> exec_0 (comp0 a (r+1)) s rs r' = rs r'\"\n  apply(induction a arbitrary : r' r s rs)\n  apply(auto)\n\n\nproof (induction a arbitrary : r s rs)\n  fix x r s rs\n  show \"exec_0 (comp0 (aexp.N x) (r + 1)) s rs r = rs r\" by auto\n \n\ntheorem correct_exec0 : \"exec0 (comp0 a r) s rs 0 = aval a s\"\nproof (induction a arbitrary : r s rs)\n  case (N n)\n  show ?case by simp\nnext\n  case (V x) \n  show ?case by simp\nnext  \n  fix a1 a2 r s rs\n  assume ind : \"\\<And>r s rs. exec0 (comp0 a1 r) s rs 0 = aval a1 s\"\n         \"\\<And>r s rs. exec0 (comp0 a2 r) s rs 0 = aval a2 s\"\n  let ?rs' = \"exec0 (comp0 a1 (r+1)) s rs\"\n  let ?rs'' = \"?rs' (r := ?rs' 0)\"\n  let ?rs''' = \"exec0 (comp0 a2 (r+1)) s ?rs''\"\n  have \"exec0 (comp0 (aexp.Plus a1 a2) r) s rs 0 = \n        exec0 ((comp0 a1 (r+1)) @ [MV0 r] @ (comp0 a2 (r+1)) @ [ADD0 r]) s rs 0\" \n    by simp \n  also have \"... = exec0 ([MV0 r] @ (comp0 a2 (r+1)) @ [ADD0 r]) s ?rs' 0\"\n    using correct_exec0_aux by simp\n  also have \"... = exec0 ((comp0 a2 (r+1)) @ [ADD0 r]) s ?rs'' 0\" \n    using correct_exec0_aux by simp\n  also have \"... = exec0 ([ADD0 r]) s ?rs''' 0\"\n    using correct_exec0_aux by simp\n  also have \"... = (?rs''' (0 := ?rs''' r + ?rs''' 0)) 0\"\n    using correct_exec0_aux by simp\n  also have \"... = ?rs''' r + ?rs''' 0\" by simp\n  also have \"... = ?rs''' r +  aval a2 s\" using ind by simp\n  also have \"?rs''' = \n    exec0 (comp0 a2 (r+1)) s ((exec0 (comp0 a1 (r+1)) s rs) (r := (exec0 (comp0 a1 (r+1)) s rs) 0))\"\n    by simp\n  also have \"... = \n    exec0 (comp0 a2 (r+1)) s ((exec0 (comp0 a1 (r+1)) s rs) (r := aval a1 s rs))\" \n    using ind by simp\n  finally show \"exec0 (comp0 (aexp.Plus a1 a2) r) s rs 0 = aval (aexp.Plus a1 a2) s\"\n      using ind by auto\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/Chapter3.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339756938819, "lm_q2_score": 0.8705972818382005, "lm_q1q2_score": 0.7310701167062791}}
{"text": "(*  Title:      HOL/Nonstandard_Analysis/NSComplex.thy\n    Author:     Jacques D. Fleuriot, University of Edinburgh\n    Author:     Lawrence C Paulson\n*)\n\nsection \\<open>Nonstandard Complex Numbers\\<close>\n\ntheory NSComplex\n  imports NSA\nbegin\n\ntype_synonym hcomplex = \"complex star\"\n\nabbreviation hcomplex_of_complex :: \"complex \\<Rightarrow> complex star\"\n  where \"hcomplex_of_complex \\<equiv> star_of\"\n\nabbreviation hcmod :: \"complex star \\<Rightarrow> real star\"\n  where \"hcmod \\<equiv> hnorm\"\n\n\nsubsubsection \\<open>Real and Imaginary parts\\<close>\n\ndefinition hRe :: \"hcomplex \\<Rightarrow> hypreal\"\n  where \"hRe = *f* Re\"\n\ndefinition hIm :: \"hcomplex \\<Rightarrow> hypreal\"\n  where \"hIm = *f* Im\"\n\n\nsubsubsection \\<open>Imaginary unit\\<close>\n\ndefinition iii :: hcomplex\n  where \"iii = star_of \\<i>\"\n\n\nsubsubsection \\<open>Complex conjugate\\<close>\n\ndefinition hcnj :: \"hcomplex \\<Rightarrow> hcomplex\"\n  where \"hcnj = *f* cnj\"\n\n\nsubsubsection \\<open>Argand\\<close>\n\ndefinition hsgn :: \"hcomplex \\<Rightarrow> hcomplex\"\n  where \"hsgn = *f* sgn\"\n\ndefinition harg :: \"hcomplex \\<Rightarrow> hypreal\"\n  where \"harg = *f* Arg\"\n\ndefinition  \\<comment> \\<open>abbreviation for \\<open>cos a + i sin a\\<close>\\<close>\n  hcis :: \"hypreal \\<Rightarrow> hcomplex\"\n  where \"hcis = *f* cis\"\n\n\nsubsubsection \\<open>Injection from hyperreals\\<close>\n\nabbreviation hcomplex_of_hypreal :: \"hypreal \\<Rightarrow> hcomplex\"\n  where \"hcomplex_of_hypreal \\<equiv> of_hypreal\"\n\ndefinition  \\<comment> \\<open>abbreviation for \\<open>r * (cos a + i sin a)\\<close>\\<close>\n  hrcis :: \"hypreal \\<Rightarrow> hypreal \\<Rightarrow> hcomplex\"\n  where \"hrcis = *f2* rcis\"\n\n\nsubsubsection \\<open>\\<open>e ^ (x + iy)\\<close>\\<close>\n\ndefinition hExp :: \"hcomplex \\<Rightarrow> hcomplex\"\n  where \"hExp = *f* exp\"\n\ndefinition HComplex :: \"hypreal \\<Rightarrow> hypreal \\<Rightarrow> hcomplex\"\n  where \"HComplex = *f2* Complex\"\n\nlemmas hcomplex_defs [transfer_unfold] =\n  hRe_def hIm_def iii_def hcnj_def hsgn_def harg_def hcis_def\n  hrcis_def hExp_def HComplex_def\n\nlemma Standard_hRe [simp]: \"x \\<in> Standard \\<Longrightarrow> hRe x \\<in> Standard\"\n  by (simp add: hcomplex_defs)\n\nlemma Standard_hIm [simp]: \"x \\<in> Standard \\<Longrightarrow> hIm x \\<in> Standard\"\n  by (simp add: hcomplex_defs)\n\nlemma Standard_iii [simp]: \"iii \\<in> Standard\"\n  by (simp add: hcomplex_defs)\n\nlemma Standard_hcnj [simp]: \"x \\<in> Standard \\<Longrightarrow> hcnj x \\<in> Standard\"\n  by (simp add: hcomplex_defs)\n\nlemma Standard_hsgn [simp]: \"x \\<in> Standard \\<Longrightarrow> hsgn x \\<in> Standard\"\n  by (simp add: hcomplex_defs)\n\nlemma Standard_harg [simp]: \"x \\<in> Standard \\<Longrightarrow> harg x \\<in> Standard\"\n  by (simp add: hcomplex_defs)\n\nlemma Standard_hcis [simp]: \"r \\<in> Standard \\<Longrightarrow> hcis r \\<in> Standard\"\n  by (simp add: hcomplex_defs)\n\nlemma Standard_hExp [simp]: \"x \\<in> Standard \\<Longrightarrow> hExp x \\<in> Standard\"\n  by (simp add: hcomplex_defs)\n\nlemma Standard_hrcis [simp]: \"r \\<in> Standard \\<Longrightarrow> s \\<in> Standard \\<Longrightarrow> hrcis r s \\<in> Standard\"\n  by (simp add: hcomplex_defs)\n\nlemma Standard_HComplex [simp]: \"r \\<in> Standard \\<Longrightarrow> s \\<in> Standard \\<Longrightarrow> HComplex r s \\<in> Standard\"\n  by (simp add: hcomplex_defs)\n\nlemma hcmod_def: \"hcmod = *f* cmod\"\n  by (rule hnorm_def)\n\n\nsubsection \\<open>Properties of Nonstandard Real and Imaginary Parts\\<close>\n\nlemma hcomplex_hRe_hIm_cancel_iff: \"\\<And>w z. w = z \\<longleftrightarrow> hRe w = hRe z \\<and> hIm w = hIm z\"\n  by transfer (rule complex_eq_iff)\n\nlemma hcomplex_equality [intro?]: \"\\<And>z w. hRe z = hRe w \\<Longrightarrow> hIm z = hIm w \\<Longrightarrow> z = w\"\n  by transfer (rule complex_eqI)\n\nlemma hcomplex_hRe_zero [simp]: \"hRe 0 = 0\"\n  by transfer simp\n\nlemma hcomplex_hIm_zero [simp]: \"hIm 0 = 0\"\n  by transfer simp\n\nlemma hcomplex_hRe_one [simp]: \"hRe 1 = 1\"\n  by transfer simp\n\nlemma hcomplex_hIm_one [simp]: \"hIm 1 = 0\"\n  by transfer simp\n\n\nsubsection \\<open>Addition for Nonstandard Complex Numbers\\<close>\n\nlemma hRe_add: \"\\<And>x y. hRe (x + y) = hRe x + hRe y\"\n  by transfer simp\n\nlemma hIm_add: \"\\<And>x y. hIm (x + y) = hIm x + hIm y\"\n  by transfer simp\n\n\nsubsection \\<open>More Minus Laws\\<close>\n\nlemma hRe_minus: \"\\<And>z. hRe (- z) = - hRe z\"\n  by transfer (rule uminus_complex.sel)\n\nlemma hIm_minus: \"\\<And>z. hIm (- z) = - hIm z\"\n  by transfer (rule uminus_complex.sel)\n\nlemma hcomplex_add_minus_eq_minus: \"x + y = 0 \\<Longrightarrow> x = - y\"\n  for x y :: hcomplex\n  apply (drule minus_unique)\n  apply (simp add: minus_equation_iff [of x y])\n  done\n\nlemma hcomplex_i_mult_eq [simp]: \"iii * iii = - 1\"\n  by transfer (rule i_squared)\n\nlemma hcomplex_i_mult_left [simp]: \"\\<And>z. iii * (iii * z) = - z\"\n  by transfer (rule complex_i_mult_minus)\n\nlemma hcomplex_i_not_zero [simp]: \"iii \\<noteq> 0\"\n  by transfer (rule complex_i_not_zero)\n\n\nsubsection \\<open>More Multiplication Laws\\<close>\n\nlemma hcomplex_mult_minus_one: \"- 1 * z = - z\"\n  for z :: hcomplex\n  by simp\n\nlemma hcomplex_mult_minus_one_right: \"z * - 1 = - z\"\n  for z :: hcomplex\n  by simp\n\nlemma hcomplex_mult_left_cancel: \"c \\<noteq> 0 \\<Longrightarrow> c * a = c * b \\<longleftrightarrow> a = b\"\n  for a b c :: hcomplex\n  by simp\n\nlemma hcomplex_mult_right_cancel: \"c \\<noteq> 0 \\<Longrightarrow> a * c = b * c \\<longleftrightarrow> a = b\"\n  for a b c :: hcomplex\n  by simp\n\n\nsubsection \\<open>Subtraction and Division\\<close>\n\n(* TODO: delete *)\nlemma hcomplex_diff_eq_eq [simp]: \"x - y = z \\<longleftrightarrow> x = z + y\"\n  for x y z :: hcomplex\n  by (rule diff_eq_eq)\n\n\nsubsection \\<open>Embedding Properties for \\<^term>\\<open>hcomplex_of_hypreal\\<close> Map\\<close>\n\nlemma hRe_hcomplex_of_hypreal [simp]: \"\\<And>z. hRe (hcomplex_of_hypreal z) = z\"\n  by transfer (rule Re_complex_of_real)\n\nlemma hIm_hcomplex_of_hypreal [simp]: \"\\<And>z. hIm (hcomplex_of_hypreal z) = 0\"\n  by transfer (rule Im_complex_of_real)\n\nlemma hcomplex_of_epsilon_not_zero [simp]: \"hcomplex_of_hypreal \\<epsilon> \\<noteq> 0\"\n  by (simp add: epsilon_not_zero)\n\n\nsubsection \\<open>\\<open>HComplex\\<close> theorems\\<close>\n\nlemma hRe_HComplex [simp]: \"\\<And>x y. hRe (HComplex x y) = x\"\n  by transfer simp\n\nlemma hIm_HComplex [simp]: \"\\<And>x y. hIm (HComplex x y) = y\"\n  by transfer simp\n\nlemma hcomplex_surj [simp]: \"\\<And>z. HComplex (hRe z) (hIm z) = z\"\n  by transfer (rule complex_surj)\n\nlemma hcomplex_induct [case_names rect(*, induct type: hcomplex*)]:\n  \"(\\<And>x y. P (HComplex x y)) \\<Longrightarrow> P z\"\n  by (rule hcomplex_surj [THEN subst]) blast\n\n\nsubsection \\<open>Modulus (Absolute Value) of Nonstandard Complex Number\\<close>\n\nlemma hcomplex_of_hypreal_abs:\n  \"hcomplex_of_hypreal \\<bar>x\\<bar> = hcomplex_of_hypreal (hcmod (hcomplex_of_hypreal x))\"\n  by simp\n\nlemma HComplex_inject [simp]: \"\\<And>x y x' y'. HComplex x y = HComplex x' y' \\<longleftrightarrow> x = x' \\<and> y = y'\"\n  by transfer (rule complex.inject)\n\nlemma HComplex_add [simp]:\n  \"\\<And>x1 y1 x2 y2. HComplex x1 y1 + HComplex x2 y2 = HComplex (x1 + x2) (y1 + y2)\"\n  by transfer (rule complex_add)\n\nlemma HComplex_minus [simp]: \"\\<And>x y. - HComplex x y = HComplex (- x) (- y)\"\n  by transfer (rule complex_minus)\n\nlemma HComplex_diff [simp]:\n  \"\\<And>x1 y1 x2 y2. HComplex x1 y1 - HComplex x2 y2 = HComplex (x1 - x2) (y1 - y2)\"\n  by transfer (rule complex_diff)\n\nlemma HComplex_mult [simp]:\n  \"\\<And>x1 y1 x2 y2. HComplex x1 y1 * HComplex x2 y2 = HComplex (x1*x2 - y1*y2) (x1*y2 + y1*x2)\"\n  by transfer (rule complex_mult)\n\ntext \\<open>\\<open>HComplex_inverse\\<close> is proved below.\\<close>\n\nlemma hcomplex_of_hypreal_eq: \"\\<And>r. hcomplex_of_hypreal r = HComplex r 0\"\n  by transfer (rule complex_of_real_def)\n\nlemma HComplex_add_hcomplex_of_hypreal [simp]:\n  \"\\<And>x y r. HComplex x y + hcomplex_of_hypreal r = HComplex (x + r) y\"\n  by transfer (rule Complex_add_complex_of_real)\n\nlemma hcomplex_of_hypreal_add_HComplex [simp]:\n  \"\\<And>r x y. hcomplex_of_hypreal r + HComplex x y = HComplex (r + x) y\"\n  by transfer (rule complex_of_real_add_Complex)\n\nlemma HComplex_mult_hcomplex_of_hypreal:\n  \"\\<And>x y r. HComplex x y * hcomplex_of_hypreal r = HComplex (x * r) (y * r)\"\n  by transfer (rule Complex_mult_complex_of_real)\n\nlemma hcomplex_of_hypreal_mult_HComplex:\n  \"\\<And>r x y. hcomplex_of_hypreal r * HComplex x y = HComplex (r * x) (r * y)\"\n  by transfer (rule complex_of_real_mult_Complex)\n\nlemma i_hcomplex_of_hypreal [simp]: \"\\<And>r. iii * hcomplex_of_hypreal r = HComplex 0 r\"\n  by transfer (rule i_complex_of_real)\n\nlemma hcomplex_of_hypreal_i [simp]: \"\\<And>r. hcomplex_of_hypreal r * iii = HComplex 0 r\"\n  by transfer (rule complex_of_real_i)\n\n\nsubsection \\<open>Conjugation\\<close>\n\nlemma hcomplex_hcnj_cancel_iff [iff]: \"\\<And>x y. hcnj x = hcnj y \\<longleftrightarrow> x = y\"\n  by transfer (rule complex_cnj_cancel_iff)\n\nlemma hcomplex_hcnj_hcnj [simp]: \"\\<And>z. hcnj (hcnj z) = z\"\n  by transfer (rule complex_cnj_cnj)\n\nlemma hcomplex_hcnj_hcomplex_of_hypreal [simp]:\n  \"\\<And>x. hcnj (hcomplex_of_hypreal x) = hcomplex_of_hypreal x\"\n  by transfer (rule complex_cnj_complex_of_real)\n\nlemma hcomplex_hmod_hcnj [simp]: \"\\<And>z. hcmod (hcnj z) = hcmod z\"\n  by transfer (rule complex_mod_cnj)\n\nlemma hcomplex_hcnj_minus: \"\\<And>z. hcnj (- z) = - hcnj z\"\n  by transfer (rule complex_cnj_minus)\n\nlemma hcomplex_hcnj_inverse: \"\\<And>z. hcnj (inverse z) = inverse (hcnj z)\"\n  by transfer (rule complex_cnj_inverse)\n\nlemma hcomplex_hcnj_add: \"\\<And>w z. hcnj (w + z) = hcnj w + hcnj z\"\n  by transfer (rule complex_cnj_add)\n\nlemma hcomplex_hcnj_diff: \"\\<And>w z. hcnj (w - z) = hcnj w - hcnj z\"\n  by transfer (rule complex_cnj_diff)\n\nlemma hcomplex_hcnj_mult: \"\\<And>w z. hcnj (w * z) = hcnj w * hcnj z\"\n  by transfer (rule complex_cnj_mult)\n\nlemma hcomplex_hcnj_divide: \"\\<And>w z. hcnj (w / z) = hcnj w / hcnj z\"\n  by transfer (rule complex_cnj_divide)\n\nlemma hcnj_one [simp]: \"hcnj 1 = 1\"\n  by transfer (rule complex_cnj_one)\n\nlemma hcomplex_hcnj_zero [simp]: \"hcnj 0 = 0\"\n  by transfer (rule complex_cnj_zero)\n\nlemma hcomplex_hcnj_zero_iff [iff]: \"\\<And>z. hcnj z = 0 \\<longleftrightarrow> z = 0\"\n  by transfer (rule complex_cnj_zero_iff)\n\nlemma hcomplex_mult_hcnj: \"\\<And>z. z * hcnj z = hcomplex_of_hypreal ((hRe z)\\<^sup>2 + (hIm z)\\<^sup>2)\"\n  by transfer (rule complex_mult_cnj)\n\n\nsubsection \\<open>More Theorems about the Function \\<^term>\\<open>hcmod\\<close>\\<close>\n\nlemma hcmod_hcomplex_of_hypreal_of_nat [simp]:\n  \"hcmod (hcomplex_of_hypreal (hypreal_of_nat n)) = hypreal_of_nat n\"\n  by simp\n\nlemma hcmod_hcomplex_of_hypreal_of_hypnat [simp]:\n  \"hcmod (hcomplex_of_hypreal(hypreal_of_hypnat n)) = hypreal_of_hypnat n\"\n  by simp\n\nlemma hcmod_mult_hcnj: \"\\<And>z. hcmod (z * hcnj z) = (hcmod z)\\<^sup>2\"\n  by transfer (rule complex_mod_mult_cnj)\n\nlemma hcmod_triangle_ineq2 [simp]: \"\\<And>a b. hcmod (b + a) - hcmod b \\<le> hcmod a\"\n  by transfer (rule complex_mod_triangle_ineq2)\n\nlemma hcmod_diff_ineq [simp]: \"\\<And>a b. hcmod a - hcmod b \\<le> hcmod (a + b)\"\n  by transfer (rule norm_diff_ineq)\n\n\nsubsection \\<open>Exponentiation\\<close>\n\nlemma hcomplexpow_0 [simp]: \"z ^ 0 = 1\"\n  for z :: hcomplex\n  by (rule power_0)\n\nlemma hcomplexpow_Suc [simp]: \"z ^ (Suc n) = z * (z ^ n)\"\n  for z :: hcomplex\n  by (rule power_Suc)\n\nlemma hcomplexpow_i_squared [simp]: \"iii\\<^sup>2 = -1\"\n  by transfer (rule power2_i)\n\nlemma hcomplex_of_hypreal_pow: \"\\<And>x. hcomplex_of_hypreal (x ^ n) = hcomplex_of_hypreal x ^ n\"\n  by transfer (rule of_real_power)\n\nlemma hcomplex_hcnj_pow: \"\\<And>z. hcnj (z ^ n) = hcnj z ^ n\"\n  by transfer (rule complex_cnj_power)\n\nlemma hcmod_hcomplexpow: \"\\<And>x. hcmod (x ^ n) = hcmod x ^ n\"\n  by transfer (rule norm_power)\n\nlemma hcpow_minus:\n  \"\\<And>x n. (- x :: hcomplex) pow n = (if ( *p* even) n then (x pow n) else - (x pow n))\"\n  by transfer simp\n\nlemma hcpow_mult: \"(r * s) pow n = (r pow n) * (s pow n)\"\n  for r s :: hcomplex\n  by (fact hyperpow_mult)\n\nlemma hcpow_zero2 [simp]: \"\\<And>n. 0 pow (hSuc n) = (0::'a::semiring_1 star)\"\n  by transfer (rule power_0_Suc)\n\nlemma hcpow_not_zero [simp,intro]: \"\\<And>r n. r \\<noteq> 0 \\<Longrightarrow> r pow n \\<noteq> (0::hcomplex)\"\n  by (fact hyperpow_not_zero)\n\nlemma hcpow_zero_zero: \"r pow n = 0 \\<Longrightarrow> r = 0\"\n  for r :: hcomplex\n  by (blast intro: ccontr dest: hcpow_not_zero)\n\n\nsubsection \\<open>The Function \\<^term>\\<open>hsgn\\<close>\\<close>\n\nlemma hsgn_zero [simp]: \"hsgn 0 = 0\"\n  by transfer (rule sgn_zero)\n\nlemma hsgn_one [simp]: \"hsgn 1 = 1\"\n  by transfer (rule sgn_one)\n\nlemma hsgn_minus: \"\\<And>z. hsgn (- z) = - hsgn z\"\n  by transfer (rule sgn_minus)\n\nlemma hsgn_eq: \"\\<And>z. hsgn z = z / hcomplex_of_hypreal (hcmod z)\"\n  by transfer (rule sgn_eq)\n\nlemma hcmod_i: \"\\<And>x y. hcmod (HComplex x y) = ( *f* sqrt) (x\\<^sup>2 + y\\<^sup>2)\"\n  by transfer (rule complex_norm)\n\nlemma hcomplex_eq_cancel_iff1 [simp]:\n  \"hcomplex_of_hypreal xa = HComplex x y \\<longleftrightarrow> xa = x \\<and> y = 0\"\n  by (simp add: hcomplex_of_hypreal_eq)\n\nlemma hcomplex_eq_cancel_iff2 [simp]:\n  \"HComplex x y = hcomplex_of_hypreal xa \\<longleftrightarrow> x = xa \\<and> y = 0\"\n  by (simp add: hcomplex_of_hypreal_eq)\n\nlemma HComplex_eq_0 [simp]: \"\\<And>x y. HComplex x y = 0 \\<longleftrightarrow> x = 0 \\<and> y = 0\"\n  by transfer (rule Complex_eq_0)\n\nlemma HComplex_eq_1 [simp]: \"\\<And>x y. HComplex x y = 1 \\<longleftrightarrow> x = 1 \\<and> y = 0\"\n  by transfer (rule Complex_eq_1)\n\nlemma i_eq_HComplex_0_1: \"iii = HComplex 0 1\"\n  by transfer (simp add: complex_eq_iff)\n\nlemma HComplex_eq_i [simp]: \"\\<And>x y. HComplex x y = iii \\<longleftrightarrow> x = 0 \\<and> y = 1\"\n  by transfer (rule Complex_eq_i)\n\nlemma hRe_hsgn [simp]: \"\\<And>z. hRe (hsgn z) = hRe z / hcmod z\"\n  by transfer (rule Re_sgn)\n\nlemma hIm_hsgn [simp]: \"\\<And>z. hIm (hsgn z) = hIm z / hcmod z\"\n  by transfer (rule Im_sgn)\n\nlemma HComplex_inverse: \"\\<And>x y. inverse (HComplex x y) = HComplex (x / (x\\<^sup>2 + y\\<^sup>2)) (- y / (x\\<^sup>2 + y\\<^sup>2))\"\n  by transfer (rule complex_inverse)\n\nlemma hRe_mult_i_eq[simp]: \"\\<And>y. hRe (iii * hcomplex_of_hypreal y) = 0\"\n  by transfer simp\n\nlemma hIm_mult_i_eq [simp]: \"\\<And>y. hIm (iii * hcomplex_of_hypreal y) = y\"\n  by transfer simp\n\nlemma hcmod_mult_i [simp]: \"\\<And>y. hcmod (iii * hcomplex_of_hypreal y) = \\<bar>y\\<bar>\"\n  by transfer (simp add: norm_complex_def)\n\nlemma hcmod_mult_i2 [simp]: \"\\<And>y. hcmod (hcomplex_of_hypreal y * iii) = \\<bar>y\\<bar>\"\n  by transfer (simp add: norm_complex_def)\n\n\nsubsubsection \\<open>\\<open>harg\\<close>\\<close>\n\nlemma cos_harg_i_mult_zero [simp]: \"\\<And>y. y \\<noteq> 0 \\<Longrightarrow> ( *f* cos) (harg (HComplex 0 y)) = 0\"\n  by transfer (simp add: Complex_eq)\n\n\nsubsection \\<open>Polar Form for Nonstandard Complex Numbers\\<close>\n\nlemma complex_split_polar2: \"\\<forall>n. \\<exists>r a. (z n) = complex_of_real r * Complex (cos a) (sin a)\"\n  unfolding Complex_eq by (auto intro: complex_split_polar)\n\nlemma hcomplex_split_polar:\n  \"\\<And>z. \\<exists>r a. z = hcomplex_of_hypreal r * (HComplex (( *f* cos) a) (( *f* sin) a))\"\n  by transfer (simp add: Complex_eq complex_split_polar)\n\nlemma hcis_eq:\n  \"\\<And>a. hcis a = hcomplex_of_hypreal (( *f* cos) a) + iii * hcomplex_of_hypreal (( *f* sin) a)\"\n  by transfer (simp add: complex_eq_iff)\n\nlemma hrcis_Ex: \"\\<And>z. \\<exists>r a. z = hrcis r a\"\n  by transfer (rule rcis_Ex)\n\nlemma hRe_hcomplex_polar [simp]:\n  \"\\<And>r a. hRe (hcomplex_of_hypreal r * HComplex (( *f* cos) a) (( *f* sin) a)) = r * ( *f* cos) a\"\n  by transfer simp\n\nlemma hRe_hrcis [simp]: \"\\<And>r a. hRe (hrcis r a) = r * ( *f* cos) a\"\n  by transfer (rule Re_rcis)\n\nlemma hIm_hcomplex_polar [simp]:\n  \"\\<And>r a. hIm (hcomplex_of_hypreal r * HComplex (( *f* cos) a) (( *f* sin) a)) = r * ( *f* sin) a\"\n  by transfer simp\n\nlemma hIm_hrcis [simp]: \"\\<And>r a. hIm (hrcis r a) = r * ( *f* sin) a\"\n  by transfer (rule Im_rcis)\n\nlemma hcmod_unit_one [simp]: \"\\<And>a. hcmod (HComplex (( *f* cos) a) (( *f* sin) a)) = 1\"\n  by transfer (simp add: cmod_unit_one)\n\nlemma hcmod_complex_polar [simp]:\n  \"\\<And>r a. hcmod (hcomplex_of_hypreal r * HComplex (( *f* cos) a) (( *f* sin) a)) = \\<bar>r\\<bar>\"\n  by transfer (simp add: Complex_eq cmod_complex_polar)\n\nlemma hcmod_hrcis [simp]: \"\\<And>r a. hcmod(hrcis r a) = \\<bar>r\\<bar>\"\n  by transfer (rule complex_mod_rcis)\n\ntext \\<open>\\<open>(r1 * hrcis a) * (r2 * hrcis b) = r1 * r2 * hrcis (a + b)\\<close>\\<close>\n\nlemma hcis_hrcis_eq: \"\\<And>a. hcis a = hrcis 1 a\"\n  by transfer (rule cis_rcis_eq)\ndeclare hcis_hrcis_eq [symmetric, simp]\n\nlemma hrcis_mult: \"\\<And>a b r1 r2. hrcis r1 a * hrcis r2 b = hrcis (r1 * r2) (a + b)\"\n  by transfer (rule rcis_mult)\n\nlemma hcis_mult: \"\\<And>a b. hcis a * hcis b = hcis (a + b)\"\n  by transfer (rule cis_mult)\n\nlemma hcis_zero [simp]: \"hcis 0 = 1\"\n  by transfer (rule cis_zero)\n\nlemma hrcis_zero_mod [simp]: \"\\<And>a. hrcis 0 a = 0\"\n  by transfer (rule rcis_zero_mod)\n\nlemma hrcis_zero_arg [simp]: \"\\<And>r. hrcis r 0 = hcomplex_of_hypreal r\"\n  by transfer (rule rcis_zero_arg)\n\nlemma hcomplex_i_mult_minus [simp]: \"\\<And>x. iii * (iii * x) = - x\"\n  by transfer (rule complex_i_mult_minus)\n\nlemma hcomplex_i_mult_minus2 [simp]: \"iii * iii * x = - x\"\n  by simp\n\nlemma hcis_hypreal_of_nat_Suc_mult:\n  \"\\<And>a. hcis (hypreal_of_nat (Suc n) * a) = hcis a * hcis (hypreal_of_nat n * a)\"\n  by transfer (simp add: distrib_right cis_mult)\n\nlemma NSDeMoivre: \"\\<And>a. (hcis a) ^ n = hcis (hypreal_of_nat n * a)\"\n  by transfer (rule DeMoivre)\n\nlemma hcis_hypreal_of_hypnat_Suc_mult:\n  \"\\<And>a n. hcis (hypreal_of_hypnat (n + 1) * a) = hcis a * hcis (hypreal_of_hypnat n * a)\"\n  by transfer (simp add: distrib_right cis_mult)\n\nlemma NSDeMoivre_ext: \"\\<And>a n. (hcis a) pow n = hcis (hypreal_of_hypnat n * a)\"\n  by transfer (rule DeMoivre)\n\nlemma NSDeMoivre2: \"\\<And>a r. (hrcis r a) ^ n = hrcis (r ^ n) (hypreal_of_nat n * a)\"\n  by transfer (rule DeMoivre2)\n\nlemma DeMoivre2_ext: \"\\<And>a r n. (hrcis r a) pow n = hrcis (r pow n) (hypreal_of_hypnat n * a)\"\n  by transfer (rule DeMoivre2)\n\nlemma hcis_inverse [simp]: \"\\<And>a. inverse (hcis a) = hcis (- a)\"\n  by transfer (rule cis_inverse)\n\nlemma hrcis_inverse: \"\\<And>a r. inverse (hrcis r a) = hrcis (inverse r) (- a)\"\n  by transfer (simp add: rcis_inverse inverse_eq_divide [symmetric])\n\nlemma hRe_hcis [simp]: \"\\<And>a. hRe (hcis a) = ( *f* cos) a\"\n  by transfer simp\n\nlemma hIm_hcis [simp]: \"\\<And>a. hIm (hcis a) = ( *f* sin) a\"\n  by transfer simp\n\nlemma cos_n_hRe_hcis_pow_n: \"( *f* cos) (hypreal_of_nat n * a) = hRe (hcis a ^ n)\"\n  by (simp add: NSDeMoivre)\n\nlemma sin_n_hIm_hcis_pow_n: \"( *f* sin) (hypreal_of_nat n * a) = hIm (hcis a ^ n)\"\n  by (simp add: NSDeMoivre)\n\nlemma cos_n_hRe_hcis_hcpow_n: \"( *f* cos) (hypreal_of_hypnat n * a) = hRe (hcis a pow n)\"\n  by (simp add: NSDeMoivre_ext)\n\nlemma sin_n_hIm_hcis_hcpow_n: \"( *f* sin) (hypreal_of_hypnat n * a) = hIm (hcis a pow n)\"\n  by (simp add: NSDeMoivre_ext)\n\nlemma hExp_add: \"\\<And>a b. hExp (a + b) = hExp a * hExp b\"\n  by transfer (rule exp_add)\n\n\nsubsection \\<open>\\<^term>\\<open>hcomplex_of_complex\\<close>: the Injection from type \\<^typ>\\<open>complex\\<close> to to \\<^typ>\\<open>hcomplex\\<close>\\<close>\n\nlemma hcomplex_of_complex_i: \"iii = hcomplex_of_complex \\<i>\"\n  by (rule iii_def)\n\nlemma hRe_hcomplex_of_complex: \"hRe (hcomplex_of_complex z) = hypreal_of_real (Re z)\"\n  by transfer (rule refl)\n\nlemma hIm_hcomplex_of_complex: \"hIm (hcomplex_of_complex z) = hypreal_of_real (Im z)\"\n  by transfer (rule refl)\n\nlemma hcmod_hcomplex_of_complex: \"hcmod (hcomplex_of_complex x) = hypreal_of_real (cmod x)\"\n  by transfer (rule refl)\n\n\nsubsection \\<open>Numerals and Arithmetic\\<close>\n\nlemma hcomplex_of_hypreal_eq_hcomplex_of_complex:\n  \"hcomplex_of_hypreal (hypreal_of_real x) = hcomplex_of_complex (complex_of_real x)\"\n  by transfer (rule refl)\n\nlemma hcomplex_hypreal_numeral:\n  \"hcomplex_of_complex (numeral w) = hcomplex_of_hypreal(numeral w)\"\n  by transfer (rule of_real_numeral [symmetric])\n\nlemma hcomplex_hypreal_neg_numeral:\n  \"hcomplex_of_complex (- numeral w) = hcomplex_of_hypreal(- numeral w)\"\n  by transfer (rule of_real_neg_numeral [symmetric])\n\nlemma hcomplex_numeral_hcnj [simp]: \"hcnj (numeral v :: hcomplex) = numeral v\"\n  by transfer (rule complex_cnj_numeral)\n\nlemma hcomplex_numeral_hcmod [simp]: \"hcmod (numeral v :: hcomplex) = (numeral v :: hypreal)\"\n  by transfer (rule norm_numeral)\n\nlemma hcomplex_neg_numeral_hcmod [simp]: \"hcmod (- numeral v :: hcomplex) = (numeral v :: hypreal)\"\n  by transfer (rule norm_neg_numeral)\n\nlemma hcomplex_numeral_hRe [simp]: \"hRe (numeral v :: hcomplex) = numeral v\"\n  by transfer (rule complex_Re_numeral)\n\nlemma hcomplex_numeral_hIm [simp]: \"hIm (numeral v :: hcomplex) = 0\"\n  by transfer (rule complex_Im_numeral)\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/Nonstandard_Analysis/NSComplex.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8705972784807408, "lm_q2_score": 0.8397339736884711, "lm_q1q2_score": 0.7310701121410009}}
{"text": "\n(*<*) theory ex1_3 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\"\n  where \"alls f [] = True\"\n  |\"alls f (x#xs) = (f x \\<and> alls f xs)\"\n\nprimrec   exs  :: \"('a \\<Rightarrow> bool) \\<Rightarrow> 'a list \\<Rightarrow> bool\"\n  where \"exs f [] = False\"\n  |\"exs f (x#xs) = (f x \\<or> exs f 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\n  done\n\nlemma alls_1[simp]: \"alls P (x@xs) = (alls P x \\<and> (alls P xs))\"\n  apply (induct x)\n  apply auto\n  done\n\nlemma \"alls P (rev xs) = alls P xs\"\n  apply (induct xs)\n  apply (auto)\n  oops\n\nlemma \"exs (\\<lambda>x. P x \\<and> Q x) xs = (exs P xs \\<and> exs Q xs)\"\n  quickcheck oops\n\n\nlemma \"exs P (map f xs) = exs (P o f) xs\"\n  apply (induct xs)\n   apply auto\n  done\n\nlemma exs_1 [simp]:\"exs P (x @ y) = (exs P x \\<or> exs P y)\"\n  apply (induct x)\n   apply auto\n  done\n\nlemma \"exs P (rev xs) = exs P xs\"\n  apply (induct xs)\n   apply auto\n  done\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 =(exs (\\<lambda>x. P x) xs  \\<or> exs (\\<lambda>x. Q x) xs )\"\n  apply (induct xs)\n   apply auto\n  done\n\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 = (\\<not> alls (\\<lambda>x. \\<not> P x) xs)\"\n  apply(induct xs)\n   apply auto\n  done\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*}\nprimrec is_in :: \"'a \\<Rightarrow> 'a list \\<Rightarrow> bool\"\n  where \"is_in a [] = False\"\n  |\"is_in a (x#xs) = (a=x \\<or> is_in a xs)\"\n\nlemma \"is_in a xs = exs (\\<lambda> y. y=a) xs\"\n  apply(induct xs)\n   apply auto\n  done\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*}\nprimrec nodups::\" 'a list \\<Rightarrow> bool\"\n  where \"nodups [] = True\"\n  |\"nodups (x#xs) = (nodups xs \\<and> (\\<not> is_in x xs))\" \nprimrec deldups::\" 'a list \\<Rightarrow> 'a list\"\n  where \"deldups [] = []\"\n  |\"deldups (x#xs) = (if (is_in x xs) then deldups xs else (x# (deldups xs)))\" \n\nlemma \"length (deldups xs) <= length xs\"\n  apply (induct xs)\n   apply auto\n  done\n\nlemma prop1[simp]:\n  \"(is_in a (deldups xs)) = is_in a xs\"\n  apply (induct xs)\n   apply auto\n  done\n\nlemma \"nodups (deldups xs)\"\n  apply(induct xs)\n   apply auto\n  done\n\nlemma \"deldups (rev xs) = rev (deldups xs)\"\n  quickcheck\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_3.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972784807408, "lm_q2_score": 0.839733963661418, "lm_q1q2_score": 0.7310701034114757}}
{"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_07\n  imports \"../../Test_Base\" (*\"../../../src/Build_Database/Build_Database\"*)\nbegin\n\ndatatype 'a list = nil2 | cons2 \"'a\" \"'a list\"\n\ndatatype Nat = Z | S \"Nat\"\n\nfun qrev :: \"'a list => 'a list => 'a list\" where\n  \"qrev (nil2) y = y\"\n| \"qrev (cons2 z xs) y = qrev xs (cons2 z y)\"\n\nfun length :: \"'a list => Nat\" where\n  \"length (nil2) = Z\"\n| \"length (cons2 y xs) = S (length xs)\"\n\nfun t2 :: \"Nat => Nat => Nat\" where\n  \"t2 (Z) y = y\"\n| \"t2 (S z) y = S (t2 z y)\"\n\ntheorem property0 :\n  \"((length (qrev x y)) = (t2 (length x) (length y)))\"\n  apply(induct x arbitrary: y (*rule: TIP_prop_07.length.induct*))\n   apply auto[1]\n  apply(subst qrev.simps)\n    (*Note that we insert only the conclusion.*)\n  apply(subgoal_tac\n      \"length (qrev x (cons2 x1 y)) = S (length (qrev x y)) &&&\n    S (length (qrev x y)) = t2 (length (cons2 x1 x)) (length y)\")\n   apply presburger\n  apply(rule conjunctionI)\n   apply(thin_tac \"(\\<And>y. TIP_prop_07.length (qrev x y) = t2 (TIP_prop_07.length x) (TIP_prop_07.length y))\")\n   apply(rule meta_allI)\n   back\n   back\n   back\n   back\n   apply(rule meta_allI)\n   back\n   back\n   back\n   apply(induct_tac rule: TIP_prop_07.length.induct)(*Note that \"induct\" does not work here.*)\n    apply fastforce+\n  done\n\nlemma aux:\n  \"t2 (TIP_prop_07.length x) (S (TIP_prop_07.length y)) = S (t2 (TIP_prop_07.length x) (TIP_prop_07.length y))\"\n  apply (induct arbitrary: y)\n   apply auto done\n\ntheorem property:\n  \"((length (qrev x y)) = (t2 (length x) (length y)))\"\n  apply(induct x arbitrary: y)\n   apply fastforce\n  apply clarsimp\n  apply(rule aux) done (*abductive reasoning: remove_assumption.*)\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/Prod/Prod/TIP_prop_07.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339676722394, "lm_q2_score": 0.8705972583359805, "lm_q1q2_score": 0.7310700899870465}}
{"text": "(*  Title:      RealPower/Log.thy\n    Authors:    Jacques D. Fleuriot\n                University of Edinburgh, 2021          \n*)  \n\nsection\\<open>Real Logarithms (Redefined)\\<close>\n\ntheory Log\nimports RealPower\nbegin\n\ntext\\<open>We can now directly define real logarithm of @{term x} to base @{term a}.\\<close>\n\ndefinition\n    Log  :: \"[real,real] \\<Rightarrow> real\" where\n   \"Log a x = (THE y. a pow\\<^sub>\\<real> y = x)\"\n\nlemma IVT_simple: \n  \"\\<lbrakk>f (a::real) \\<le> (y::real); y \\<le> f b; a \\<le> b; \n    \\<forall>x. a \\<le> x \\<and> x \\<le> b \\<longrightarrow> isCont f x\\<rbrakk>\n   \\<Longrightarrow> \\<exists>x. f x = y\"\nby (frule IVT [of f]) auto\n\nlemma inj_on_powreal: \n   \"0 < a \\<Longrightarrow> a \\<noteq> 1 \\<Longrightarrow> inj_on (\\<lambda>x. a pow\\<^sub>\\<real> x) UNIV\"\nby (auto simp add: inj_on_def)\n\nlemma LIMSEQ_powreal_minus_nat:\n  \"a > 1 \\<Longrightarrow> (\\<lambda>n. a pow\\<^sub>\\<real> (-real n)) \\<longlonglongrightarrow> 0\"\nby (simp add: powreal_minus powreal_power_eq  \n        LIMSEQ_inverse_realpow_zero)\n\nlemma LIMSEQ_less_Ex:\n   \"\\<lbrakk> X \\<longlonglongrightarrow> (x::real); x < y \\<rbrakk> \\<Longrightarrow> \\<exists>n. X n < y\"\n  by (meson LIMSEQ_le_const not_less)\n\nlemma powreal_IVT_upper_lemma:\n  assumes \"a > (1::real)\" and \"x > 0\" \n  shows \"\\<exists>n::nat. a pow\\<^sub>\\<real> (-real n) < x\"\nproof -\n  have \"(\\<lambda>n. a pow\\<^sub>\\<real> - real n) \\<longlonglongrightarrow> 0\"\n    by (simp add: LIMSEQ_powreal_minus_nat assms(1))\n  then show ?thesis\n    using LIMSEQ_less_Ex assms(2) by blast \nqed\n\nlemma powreal_IVT_lower_lemma:\n  assumes \"a > (1::real)\" \n  and \"x > 0\" \n  shows \"\\<exists>n::nat. x < a pow\\<^sub>\\<real> (real n)\"\nproof -\n  have invx0: \"0 < inverse x\"\n    by (simp add: assms(2)) \n  then have \"\\<exists>n. a pow\\<^sub>\\<real> - real n < inverse x\"\n    using assms(1) powreal_IVT_upper_lemma by blast\n  then show ?thesis\n    using assms(1) \n    by (auto dest: inverse_less_imp_less \n         simp add: powreal_minus powreal_gt_zero )\nqed\n\nlemma powreal_surj:\n  assumes \"a > 1\" \n  and \"x > 0\" \n  shows \"\\<exists>y. a pow\\<^sub>\\<real> y = x\"\nproof -\n  obtain n where \"a pow\\<^sub>\\<real> - real n < x\"\n    using assms powreal_IVT_upper_lemma by blast \n  moreover obtain na where \"x < a pow\\<^sub>\\<real> real na\"\n    using assms powreal_IVT_lower_lemma by blast \n  moreover have \"\\<forall>x. - real n \\<le> x \\<and> x \\<le> real na \\<longrightarrow> isCont ((pow\\<^sub>\\<real>) a) x\"\n    using assms(1) isCont_powreal_exponent_gt_one by blast\n  ultimately show ?thesis \n    using IVT_simple [of _ \"-real n\" _ \"real na\"] by force\nqed\n\nlemma powreal_surj2:\n    \"\\<lbrakk> 0 < a; a < 1; x > 0 \\<rbrakk> \\<Longrightarrow> \\<exists>y. a pow\\<^sub>\\<real> y = x\"\n  using powreal_minus_base_ge_one powreal_surj real_inverse_gt_one_lemma \n  by blast\n\nlemma powreal_ex1_eq:\n  assumes \"a > 0\"\n  and \"a \\<noteq> 1\" \n  and \"x > 0\" \n  shows \"\\<exists>! y. a pow\\<^sub>\\<real> y = x\"\nproof (cases \"a < 1\")\n  case True\n  then show ?thesis \n    using assms powreal_inject powreal_surj2 by blast\nnext\n  case False\n  then show ?thesis\n    using assms(2) assms(3) powreal_surj by auto \nqed\n\nlemma powreal_Log_cancel [simp]:\n   \"\\<lbrakk> a > 0; a \\<noteq> 1; x > 0 \\<rbrakk> \\<Longrightarrow> a pow\\<^sub>\\<real> (Log a x) = x\"\nby (auto intro: the1I2 [OF powreal_ex1_eq] simp add: Log_def)\n\nlemma Log_powreal_cancel [simp]: \n  \"\\<lbrakk> 0 < a; a \\<noteq> 1 \\<rbrakk> \\<Longrightarrow> Log a (a pow\\<^sub>\\<real> y) = y\"\nby (metis powreal_ex1_eq powreal_gt_zero powreal_Log_cancel)\n\nlemma Log_mult: \n     \"\\<lbrakk> 0 < a; a \\<noteq> 1; 0 < x; 0 < y \\<rbrakk>\n      \\<Longrightarrow> Log a (x * y) = Log a x + Log a y\"\n  by (metis Log_powreal_cancel powreal_Log_cancel powreal_add)\n\nlemma Log_one [simp]: \"\\<lbrakk> 0 < a; a \\<noteq> 1 \\<rbrakk> \\<Longrightarrow> Log a 1 = 0\"\nby (metis Log_powreal_cancel powreal_zero_eq_one)\n\nlemma Log_eq_one [simp]: \"\\<lbrakk> 0 < a; a \\<noteq> 1 \\<rbrakk> \\<Longrightarrow> Log a a = 1\"\n  using powreal_inject by fastforce\n\nlemma Log_inverse:\n  \"\\<lbrakk> a > 0; a \\<noteq> 1; x > 0 \\<rbrakk> \\<Longrightarrow> Log a (inverse x) = - Log a x\"\nby (metis Log_powreal_cancel powreal_Log_cancel powreal_minus)\n\nlemma Log_divide: \n  \"\\<lbrakk> 0 < a; a \\<noteq> 1; 0 < x; 0 < y \\<rbrakk>\n   \\<Longrightarrow> Log a (x/y) = Log a x - Log a y\"\n  by (metis Log_inverse Log_mult divide_real_def \n       inverse_positive_iff_positive minus_real_def)\n\nlemma Log_less_cancel_iff [simp]:\n  assumes \"1 < a\" \n  and \"0 < x\"\n  and \"0 < y\"\nshows \"(Log a x < Log a y) = (x < y)\"\nproof\n  assume \"Log a x < Log a y\" \n  then show \"x < y\" using powreal_Log_cancel assms powreal_less_cancel_iff \n    by (metis less_irrefl real_inverse_bet_one_one_lemma \n          inverse_positive_iff_positive)\nnext\n  assume \"x < y\" \n  then show \"Log a x < Log a y\"\n    using assms(1) assms(2) powreal_less_cancel_iff by fastforce \nqed\n\nlemma Log_inj: assumes \"1 < b\" shows \"inj_on (Log b) {0 <..}\"\nproof (rule inj_onI, simp)\n  fix x y assume pos: \"0 < x\" \"0 < y\" and *: \"Log b x = Log b y\"\n  show \"x = y\"\n  proof (cases rule: linorder_cases)\n    assume \"x < y\" hence \"Log b x < Log b y\"\n      using Log_less_cancel_iff[OF \\<open>1 < b\\<close>] pos by simp\n    thus ?thesis using * by simp\n  next\n    assume \"y < x\" hence \"Log b y < Log b x\"\n      using Log_less_cancel_iff[OF \\<open>1 < b\\<close>] pos by simp\n    thus ?thesis using * by simp\n  qed simp\nqed\n\nlemma Log_le_cancel_iff [simp]:\n     \"\\<lbrakk> 1 < a; 0 < x; 0 < y \\<rbrakk> \\<Longrightarrow> (Log a x \\<le> Log a y) = (x \\<le> y)\"\nby (simp add: linorder_not_less [symmetric])\n\nlemma zero_less_Log_cancel_iff [simp]: \n  \"1 < a \\<Longrightarrow> 0 < x \\<Longrightarrow> 0 < Log a x \\<longleftrightarrow> 1 < x\"\n  using Log_less_cancel_iff[of a 1 x] by simp\n\nlemma zero_le_Log_cancel_iff[simp]: \n  \"1 < a \\<Longrightarrow> 0 < x \\<Longrightarrow> 0 \\<le> Log a x \\<longleftrightarrow> 1 \\<le> x\"\n  using Log_le_cancel_iff[of a 1 x] by simp\n\nlemma Log_less_zero_cancel_iff[simp]: \n  \"1 < a \\<Longrightarrow> 0 < x \\<Longrightarrow> Log a x < 0 \\<longleftrightarrow> x < 1\"\n  using Log_less_cancel_iff[of a x 1] by simp\n\nlemma Log_le_zero_cancel_iff[simp]: \n  \"1 < a \\<Longrightarrow> 0 < x \\<Longrightarrow> Log a x \\<le> 0 \\<longleftrightarrow> x \\<le> 1\"\n  using Log_le_cancel_iff[of a x 1] by simp\n\nlemma one_less_Log_cancel_iff[simp]: \n  \"1 < a \\<Longrightarrow> 0 < x \\<Longrightarrow> 1 < Log a x \\<longleftrightarrow> a < x\"\n  using Log_less_cancel_iff[of a a x] by simp\n\nlemma one_le_Log_cancel_iff[simp]: \n  \"1 < a \\<Longrightarrow> 0 < x \\<Longrightarrow> 1 \\<le> Log a x \\<longleftrightarrow> a \\<le> x\"\n  using Log_le_cancel_iff[of a a x] by simp\n\nlemma Log_less_one_cancel_iff[simp]: \n  \"1 < a \\<Longrightarrow> 0 < x \\<Longrightarrow> Log a x < 1 \\<longleftrightarrow> x < a\"\n  using Log_less_cancel_iff[of a x a] by simp\n\nlemma Log_le_one_cancel_iff[simp]: \n  \"1 < a \\<Longrightarrow> 0 < x \\<Longrightarrow> Log a x \\<le> 1 \\<longleftrightarrow> x \\<le> a\"\n  using Log_le_cancel_iff[of a x a] by simp\n\nlemma Log_powreal: \n  assumes \"0 < x\" \n  and \"1 < b\"\n  and \"b \\<noteq> 1\" \nshows \"Log b (x pow\\<^sub>\\<real> y) = y * Log b x\"\nproof -\n  have \"b pow\\<^sub>\\<real> (Log b x * y) = x pow\\<^sub>\\<real> y\"\n    using assms powreal_mult [symmetric] by simp\n  moreover have \"0 < x pow\\<^sub>\\<real> y\"\n    by (simp add: assms(1) powreal_gt_zero)\n  ultimately have \"b pow\\<^sub>\\<real> (y * Log b x) = b pow\\<^sub>\\<real> Log b (x pow\\<^sub>\\<real> y)\"\n    using powreal_Log_cancel assms powreal_Log_cancel\n    by (simp add: mult.commute)\n  then show ?thesis\n    using assms(2) powreal_inject_exp1 by blast \nqed\n\nlemma Log_nat_power: \n  assumes \"0 < x\" \n  and \"1 < b\" and \"b \\<noteq> 1\"\n  shows \" Log b (x ^ n) = real n * Log b x\"\nproof -\n  have \"Log b (x pow\\<^sub>\\<real> real n) = real n * Log b x\"\n    by (simp add: Log_powreal assms) \n  then show ?thesis\n    by (simp add: assms(1) powreal_power_eq) \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/Real_Power/Log.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972583359805, "lm_q2_score": 0.8397339676722393, "lm_q1q2_score": 0.7310700899870464}}
{"text": "theory tp2\nimports Main\nbegin\n\n(* 1.1 : Construction des ensembles *)\n\nfun member :: \"'a \\<Rightarrow> 'a list \\<Rightarrow> bool\" where\n  \"member _ [] = False\" |\n  \"member x (t#q) = ((x = t) \\<or> (member x q))\"\n\nfun isSet :: \"'a list \\<Rightarrow> bool\" where\n  \"isSet [] = True\"\n| \"isSet (t#q) = ((\\<not>(member t q)) \\<and> (isSet q))\"\n\nfun clean :: \"'a list \\<Rightarrow> 'a list\" where\n  \"clean [] = []\"\n| \"clean (t#q) = (if (member t q) then (clean q) else (t#(clean q)))\"\n\nlemma member_clean: \"(member x l) = (member x (clean l))\"\n  apply (induct l)\n   apply auto\n  done\n\nlemma isSet_clean: \"isSet (clean l)\"\n  apply (induct l)\n   apply simp\n   using member_clean by fastforce\n\n(* 1.2 : Suppression d'un \u00e9l\u00e9ment *)\n\nfun delete :: \"'a \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where\n  \"delete x [] = []\"\n| \"delete x (t#q) = (if (x=t) then (q) else (t#(delete x q)))\"\n\nlemma member_delete1: \"(isSet l) \\<longrightarrow> (\\<not>(member x (delete x l)))\"\n  apply (induct l)\n   apply auto\n  done\n\nlemma member_delete2: \"(isSet l) \\<longrightarrow> ((y \\<noteq> x) \\<longrightarrow> ((member y l) = (member y (delete x l))))\"\n  apply (induct l)\n   apply auto\n  done\n\n(* 1.3 : Intersection *)\nfun intersection :: \"'a list \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where\n  \"intersection [] _ = []\"\n| \"intersection (t#q) l = (if (member t l) then (t#(intersection q l)) else (intersection q l))\"\n\nlemma member_intersection: \"((member x l1) \\<and> (member x l2)) = (member x (intersection l1 l2))\"\n  apply (induct l1)\n  apply (induct l2)\n  apply simp\n  apply simp\n  apply auto\n  done\n\nlemma isSet_intersection: \"(isSet l1) \\<and> (isSet l2) \\<longrightarrow> (isSet (intersection l1 l2))\"\n  apply (induct l1)\n   apply (induct l2)\n    apply simp\n   apply simp\n  using member_intersection by force\n\n(* 1.4 : Union *)\n\nfun union :: \"'a list \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where\n  \"union [] l = l\"\n| \"union (t#q) l = (if (member t l) then (union q l) else (t#(union q l)))\"\n\nlemma member_union: \"((member x l1) \\<or> (member x l2)) = (member x (union l1 l2))\"\n  apply (induct l1)\n   apply (induct l2)\n    apply simp\n   apply simp\n  apply auto\n  done\n\nlemma isSet_union: \"(isSet l1) \\<and> (isSet l2) \\<longrightarrow> (isSet (union l1 l2))\"\n  apply (induct l1)\n   apply (induct l2)\n    apply simp\n   apply simp\n  apply auto\n  by (meson member_union)\n\n(* 1.5 : \u00c9galit\u00e9 *)\n\nfun equal :: \"'a list \\<Rightarrow> 'a list \\<Rightarrow> bool\" where\n  \"equal [] l = (l = [])\"\n| \"equal (t#q) l = ((member t l) \\<and> (equal q (delete t l)))\"\n\nlemma \"((isSet l1) \\<and> (isSet l2)) \\<longrightarrow> ((equal l1 l2) = (\\<forall>x. (member x l1) = (member x l2)))\"\n  apply (induct l1 arbitrary: l2)\n   apply (metis equal.simps(1) isSet.elims(2) tp2.member.simps(1) tp2.member.simps(2))\n  apply simp\n  apply (case_tac \"member a l2\")\n   prefer 2\n   apply auto[1]\n  apply simp\n\n\n\n\n  sorry\n\n(* I could not prove this one so I made another one here below *)\n\nfun cotains :: \"'a list \\<Rightarrow> 'a list \\<Rightarrow> bool\" where\n  \"contains l [] = True\"\n| \"contains l (t#q) = ((member t l) \\<and> (contains l q))\"\n\nfun equal2 :: \"'a list \\<Rightarrow> 'a list \\<Rightarrow> bool\" where\n  \"equal2 l1 l2 = ((contains l1 l2) \\<and> (contains l2 l1))\"\n\nlemma contains_member: \"(contains l1 l2) = (\\<forall>x. ((member x l2) \\<longrightarrow> (member x l1)))\"\n  apply (induct l2)\n  apply auto\n  done\n\nlemma \"((isSet l1) \\<and> (isSet l2)) \\<longrightarrow> ((equal2 l1 l2) = (\\<forall>x. (member x l1) = (member x l2)))\"\n  using contains_member by auto\n\nend\n", "meta": {"author": "greeghost", "repo": "TP89_ACF", "sha": "5c7f1cc177a158a6d005ad4561add25080f768a8", "save_path": "github-repos/isabelle/greeghost-TP89_ACF", "path": "github-repos/isabelle/greeghost-TP89_ACF/TP89_ACF-5c7f1cc177a158a6d005ad4561add25080f768a8/tp2.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972583359805, "lm_q2_score": 0.8397339616560072, "lm_q1q2_score": 0.7310700847493312}}
{"text": "section \\<open>Exponentiation of ordinals\\<close>\n\ntheory Ordinal_Exp\n  imports Kirby\n\nbegin\n\ntext \\<open>Source: Schl\u00f6der, Julian.  Ordinal Arithmetic; available online at\n    \\url{http://www.math.uni-bonn.de/ag/logik/teaching/2012WS/Set%20theory/oa.pdf}\\<close>\n\ndefinition oexp :: \"[V,V] \\<Rightarrow> V\" (infixr \"\\<up>\" 80)\n  where \"oexp a b \\<equiv> transrec (\\<lambda>f x. if x=0 then 1\n                                    else if Limit x then if a=0 then 0 else SUP \\<xi> \\<in> elts x. f \\<xi>\n                                    else f (\\<Squnion>(elts x)) * a) b\"\n\ntext \\<open>@{term \"0\\<up>\\<omega> = 1\"} if we don't make a special case for Limit ordinals and zero\\<close>\n\n\nlemma oexp_0_right [simp]: \"\\<alpha>\\<up>0 = 1\"\n  by (simp add: def_transrec [OF oexp_def])\n\nlemma oexp_succ [simp]: \"Ord \\<beta> \\<Longrightarrow> \\<alpha>\\<up>(succ \\<beta>) = \\<alpha>\\<up>\\<beta> * \\<alpha>\"\n  by (simp add: def_transrec [OF oexp_def])\n\nlemma oexp_Limit: \"Limit \\<beta> \\<Longrightarrow> \\<alpha>\\<up>\\<beta> = (if \\<alpha>=0 then 0 else SUP \\<xi> \\<in> elts \\<beta>. \\<alpha>\\<up>\\<xi>)\"\n  by (auto simp: def_transrec [OF oexp_def, of _ \\<beta>])\n\nlemma oexp_1_right [simp]: \"\\<alpha>\\<up>1 = \\<alpha>\"\n  using one_V_def oexp_succ by fastforce\n\nlemma oexp_1 [simp]: \"Ord \\<alpha> \\<Longrightarrow> 1\\<up>\\<alpha> = 1\"\n  by (induction rule: Ord_induct3) (use Limit_def oexp_Limit in auto)\n\nlemma oexp_0 [simp]: \"Ord \\<alpha> \\<Longrightarrow> 0\\<up>\\<alpha> = (if \\<alpha> = 0 then 1 else 0)\"\n  by (induction rule: Ord_induct3) (use Limit_def oexp_Limit in auto)\n\nlemma oexp_eq_0_iff [simp]:\n  assumes \"Ord \\<beta>\" shows \"\\<alpha>\\<up>\\<beta> = 0 \\<longleftrightarrow> \\<alpha>=0 \\<and> \\<beta>\\<noteq>0\"\n  using \\<open>Ord \\<beta>\\<close>\nproof (induction rule: Ord_induct3)\n  case (Limit \\<mu>)\n  then show ?case\n    using Limit_def oexp_Limit by auto\nqed auto\n\nlemma oexp_gt_0_iff [simp]:\n  assumes \"Ord \\<beta>\" shows \"\\<alpha>\\<up>\\<beta> > 0 \\<longleftrightarrow> \\<alpha>>0 \\<or> \\<beta>=0\"\n  by (simp add: assms less_V_def)\n\nlemma ord_of_nat_oexp: \"ord_of_nat (m^n) = ord_of_nat m\\<up>ord_of_nat n\"\nproof (induction n)\n  case (Suc n)\n  then show ?case\n    by (simp add: mult.commute [of m]) (simp add: ord_of_nat_mult)\nqed auto\n\nlemma omega_closed_oexp [intro]:\n  assumes \"\\<alpha> \\<in> elts \\<omega>\" \"\\<beta> \\<in> elts \\<omega>\" shows \"\\<alpha>\\<up>\\<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>\\<up>\\<beta> = ord_of_nat (m^n)\"\n    by (simp add: ord_of_nat_oexp)\n  then show ?thesis\n    by (simp add: \\<omega>_def)\nqed\n\n\nlemma Ord_oexp [simp]:\n  assumes \"Ord \\<alpha>\" \"Ord \\<beta>\" shows \"Ord (\\<alpha>\\<up>\\<beta>)\"\n  using \\<open>Ord \\<beta>\\<close>\nproof (induction rule: Ord_induct3)\n  case (Limit \\<alpha>)\n  then show ?case\n    by (auto simp: oexp_Limit image_iff intro: Ord_Sup)\nqed (auto intro: Ord_mult assms)\n\ntext \\<open>Lemma 3.19\\<close>\nlemma le_oexp:\n  assumes \"Ord \\<alpha>\" \"Ord \\<beta>\" \"\\<beta> \\<noteq> 0\" shows \"\\<alpha> \\<le> \\<alpha>\\<up>\\<beta>\"\n  using \\<open>Ord \\<beta>\\<close> \\<open>\\<beta> \\<noteq> 0\\<close>\nproof (induction rule: Ord_induct3)\n  case (succ \\<beta>)\n  then show ?case\n    by simp (metis \\<open>Ord \\<alpha>\\<close> le_0 le_mult mult.left_neutral oexp_0_right order_refl order_trans)\nnext\n  case (Limit \\<mu>)\n  then show ?case\n    by (metis Limit_def Limit_eq_Sup_self ZFC_in_HOL.Sup_upper eq_iff image_eqI image_ident oexp_1_right oexp_Limit replacement small_elts one_V_def)\nqed auto\n\n\ntext \\<open>Lemma 3.20\\<close>\nlemma le_oexp':\n  assumes \"Ord \\<alpha>\" \"1 < \\<alpha>\" \"Ord \\<beta>\" shows \"\\<beta> \\<le> \\<alpha>\\<up>\\<beta>\"\nproof (cases \"\\<beta> = 0\")\n  case True\n  then show ?thesis\n    by auto\nnext\n  case False\n  show ?thesis\n    using \\<open>Ord \\<beta>\\<close>\n  proof (induction rule: Ord_induct3)\n    case 0\n    then show ?case\n      by auto\n  next\n    case (succ \\<gamma>)\n    then have \"\\<alpha>\\<up>\\<gamma> * 1 < \\<alpha>\\<up>\\<gamma> * \\<alpha>\"\n      using \\<open>Ord \\<alpha>\\<close> \\<open>1 < \\<alpha>\\<close>\n      by (metis le_mult less_V_def mult.right_neutral mult_cancellation not_less_0 oexp_eq_0_iff succ.hyps)\n    then have \" \\<gamma> < \\<alpha>\\<up>succ \\<gamma>\"\n      using succ.IH succ.hyps by auto\n    then show ?case\n      using False \\<open>Ord \\<alpha>\\<close> \\<open>1 < \\<alpha>\\<close> succ\n      by (metis Ord_mem_iff_lt Ord_oexp Ord_succ elts_succ insert_subset less_eq_V_def less_imp_le)\n  next\n    case (Limit \\<mu>)\n    with False \\<open>1 < \\<alpha>\\<close> show ?case\n      by (force simp: Limit_def oexp_Limit intro: elts_succ)\n  qed\nqed\n\n\nlemma oexp_Limit_le:\n  assumes \"\\<beta> < \\<gamma>\" \"Limit \\<gamma>\" \"Ord \\<beta>\" \"\\<alpha> > 0\" shows \"\\<alpha>\\<up>\\<beta> \\<le> \\<alpha>\\<up>\\<gamma>\"\nproof -\n  have \"Ord \\<gamma>\"\n    using Limit_def assms(2) by blast\n  with assms show ?thesis\n    using Ord_mem_iff_lt ZFC_in_HOL.Sup_upper oexp_Limit by auto\nqed\n\nproposition oexp_less:\n  assumes \\<beta>: \"\\<beta> \\<in> elts \\<gamma>\" and \"Ord \\<gamma>\" and \\<alpha>: \"\\<alpha> > 1\" \"Ord \\<alpha>\" shows \"\\<alpha>\\<up>\\<beta> < \\<alpha>\\<up>\\<gamma>\"\nproof -\n  obtain \"\\<beta> < \\<gamma>\" \"Ord \\<beta>\"\n    using Ord_in_Ord OrdmemD assms by auto\n  have gt0: \"\\<alpha>\\<up>\\<beta> > 0\"\n    using \\<open>Ord \\<beta>\\<close> \\<alpha> dual_order.order_iff_strict by auto\n  show ?thesis\n    using \\<open>Ord \\<gamma>\\<close> \\<beta>\n  proof (induction rule: Ord_induct3)\n    case 0\n    then show ?case\n      by auto\n  next\n    case (succ \\<delta>)\n    then consider \"\\<beta> = \\<delta>\" | \"\\<beta> < \\<delta>\"\n      using OrdmemD elts_succ by blast\n    then show ?case\n    proof cases\n      case 1\n      then have \"(\\<alpha>\\<up>\\<beta>) * 1 < (\\<alpha>\\<up>\\<delta>) * \\<alpha>\"\n        using Ord_1 Ord_oexp \\<alpha> gt0 mult_cancel_less_iff succ.hyps by metis\n      then show ?thesis\n        by (simp add: succ.hyps)\n    next\n      case 2\n      then have \"(\\<alpha>\\<up>\\<delta>) * 1 < (\\<alpha>\\<up>\\<delta>) * \\<alpha>\"\n        by (meson Ord_1 Ord_mem_iff_lt Ord_oexp \\<open>Ord \\<beta>\\<close> \\<alpha> gt0 less_trans mult_cancel_less_iff succ)\n      with 2 show ?thesis\n        using Ord_mem_iff_lt \\<open>Ord \\<beta>\\<close> succ by auto\n    qed\n  next\n    case (Limit \\<gamma>)\n    then obtain \"Ord \\<gamma>\" \"succ \\<beta> < \\<gamma>\"\n      using Limit_def Ord_in_Ord OrdmemD assms by auto\n    have \"\\<alpha>\\<up>\\<beta> = (\\<alpha>\\<up>\\<beta>) * 1\"\n      by simp\n    also have \"\\<dots> < (\\<alpha>\\<up>\\<beta>) * \\<alpha>\"\n      using Ord_oexp \\<open>Ord \\<beta>\\<close> assms gt0 mult_cancel_less_iff by blast\n    also have \"\\<dots> = \\<alpha>\\<up>succ \\<beta>\"\n      by (simp add: \\<open>Ord \\<beta>\\<close>)\n    also have \"\\<dots> \\<le> (SUP \\<xi> \\<in> elts \\<gamma>. \\<alpha>\\<up>\\<xi>)\"\n    proof -\n      have \"succ \\<beta> \\<in> elts \\<gamma>\"\n        using Limit.hyps Limit.prems Limit_def by auto\n      then show ?thesis\n        by (simp add: ZFC_in_HOL.Sup_upper)\n    qed\n    finally\n    have \"\\<alpha>\\<up>\\<beta> < (SUP \\<xi> \\<in> elts \\<gamma>. \\<alpha>\\<up>\\<xi>)\" .\n    then show ?case\n      using Limit.hyps oexp_Limit \\<open>\\<alpha> > 1\\<close> by auto\n  qed\nqed\n\ncorollary oexp_less_iff:\n  assumes \"\\<alpha> > 0\" \"Ord \\<alpha>\" \"Ord \\<beta>\" \"Ord \\<gamma>\" shows \"\\<alpha>\\<up>\\<beta> < \\<alpha>\\<up>\\<gamma> \\<longleftrightarrow> \\<beta> \\<in> elts \\<gamma> \\<and> \\<alpha> > 1\"\nproof safe\n  show \"\\<beta> \\<in> elts \\<gamma>\" \"1 < \\<alpha>\"\n    if \"\\<alpha>\\<up>\\<beta> < \\<alpha>\\<up>\\<gamma>\"\n  proof -\n    show \"\\<alpha> > 1\"\n    proof (rule ccontr)\n      assume \"\\<not> \\<alpha> > 1\"\n      then consider \"\\<alpha>=0\" | \"\\<alpha>=1\"\n        using \\<open>Ord \\<alpha>\\<close> less_V_def mem_0_Ord by fastforce\n      then show False\n        by cases (use that \\<open>\\<alpha> > 0\\<close> \\<open>Ord \\<beta>\\<close> \\<open>Ord \\<gamma>\\<close> in \\<open>auto split: if_split_asm\\<close>)\n    qed\n    show \\<beta>: \"\\<beta> \\<in> elts \\<gamma>\"\n    proof (rule ccontr)\n      assume \"\\<beta> \\<notin> elts \\<gamma>\"\n      then have \"\\<gamma> \\<le> \\<beta>\"\n        by (meson Ord_linear_le Ord_mem_iff_lt assms less_le_not_le)\n      then consider \"\\<gamma> = \\<beta>\" | \"\\<gamma> < \\<beta>\"\n        using less_V_def by blast\n      then show False\n      proof cases\n        case 1\n        then show ?thesis\n          using that by blast\n      next\n        case 2\n        with \\<open>\\<alpha> > 1\\<close> have \"\\<alpha>\\<up>\\<gamma> < \\<alpha>\\<up>\\<beta>\"\n          by (simp add: Ord_mem_iff_lt assms oexp_less)\n        with that show ?thesis\n          by auto\n      qed\n    qed\n  qed\n  show \"\\<alpha>\\<up>\\<beta> < \\<alpha>\\<up>\\<gamma>\" if \"\\<beta> \\<in> elts \\<gamma>\" \"1 < \\<alpha>\"\n    using that by (simp add: assms oexp_less)\nqed\n\nlemma \\<omega>_oexp_iff [simp]: \"\\<lbrakk>Ord \\<alpha>; Ord \\<beta>\\<rbrakk> \\<Longrightarrow> \\<omega>\\<up>\\<alpha> = \\<omega>\\<up>\\<beta> \\<longleftrightarrow> \\<alpha>=\\<beta>\"\n  by (metis Ord_\\<omega> Ord_linear \\<omega>_gt1 less_irrefl oexp_less)\n\nlemma Limit_oexp:\n  assumes \"Limit \\<gamma>\" \"Ord \\<alpha>\" \"\\<alpha> > 1\" shows \"Limit (\\<alpha>\\<up>\\<gamma>)\"\n  unfolding Limit_def\nproof safe\n  show O\\<alpha>\\<gamma>: \"Ord (\\<alpha>\\<up>\\<gamma>)\"\n    using Limit_def Ord_oexp \\<open>Limit \\<gamma>\\<close> assms(2) by blast\n  show 0: \"0 \\<in> elts (\\<alpha>\\<up>\\<gamma>)\"\n    using Limit_def oexp_Limit \\<open>Limit \\<gamma>\\<close> \\<open>\\<alpha> > 1\\<close> by fastforce\n  have \"Ord \\<gamma>\"\n    using Limit_def \\<open>Limit \\<gamma>\\<close> by blast\n  fix x\n  assume x: \"x \\<in> elts (\\<alpha>\\<up>\\<gamma>)\"\n  with \\<open>Limit \\<gamma>\\<close> \\<open>\\<alpha> > 1\\<close>\n  obtain \\<beta> where \"\\<beta> < \\<gamma>\" \"Ord \\<beta>\" \"Ord x\" and x\\<beta>: \"x \\<in> elts (\\<alpha>\\<up>\\<beta>)\"\n    apply (simp add: oexp_Limit split: if_split_asm)\n    using Ord_in_Ord OrdmemD \\<open>Ord \\<gamma>\\<close> O\\<alpha>\\<gamma> x by blast\n  then have O\\<alpha>\\<beta>: \"Ord (\\<alpha>\\<up>\\<beta>)\"\n    using Ord_oexp assms(2) by blast\n  have \"\\<beta> \\<in> elts \\<gamma>\"\n    by (simp add: Ord_mem_iff_lt \\<open>Ord \\<beta>\\<close> \\<open>Ord \\<gamma>\\<close> \\<open>\\<beta> < \\<gamma>\\<close>)\n  moreover have \"\\<alpha> \\<noteq> 0\"\n    using \\<open>\\<alpha> > 1\\<close> by blast\n  ultimately have \\<alpha>\\<beta>\\<gamma>: \"\\<alpha>\\<up>\\<beta> \\<le> \\<alpha>\\<up>\\<gamma>\"\n    by (simp add: Sup_upper oexp_Limit \\<open>Limit \\<gamma>\\<close>)\n  have \"succ x \\<le> \\<alpha>\\<up>\\<beta>\"\n    by (simp add: OrdmemD O\\<alpha>\\<beta> \\<open>Ord x\\<close> succ_le_iff x\\<beta>)\n  then consider \"succ x < \\<alpha>\\<up>\\<beta>\" | \"succ x = \\<alpha>\\<up>\\<beta>\"\n    using le_neq_trans by blast\n  then show \"succ x \\<in> elts (\\<alpha>\\<up>\\<gamma>)\"\n  proof cases\n    case 1\n    with \\<alpha>\\<beta>\\<gamma> show ?thesis\n      using O\\<alpha>\\<beta> Ord_mem_iff_lt \\<open>Ord x\\<close> by blast\n  next\n    case 2\n    then have \"succ \\<beta> < \\<gamma>\"\n      using Limit_def OrdmemD \\<open>\\<beta> \\<in> elts \\<gamma>\\<close> assms(1) by auto\n    have ge1: \"1 \\<le> \\<alpha>\\<up>\\<beta>\"\n      by (metis \"2\" Ord_0 \\<open>Ord x\\<close> le_0 le_succ_iff one_V_def)\n    have \"succ x < succ (\\<alpha>\\<up>\\<beta>)\"\n      using \"2\" O\\<alpha>\\<beta> succ_le_iff by auto\n    also have \"\\<dots> \\<le> (\\<alpha>\\<up>\\<beta>) + (\\<alpha>\\<up>\\<beta>)\"\n      using ge1 by (simp add: succ_eq_add1)\n    also have \"\\<dots> = (\\<alpha>\\<up>\\<beta>) * succ (succ 0)\"\n      by (simp add: mult_succ)\n    also have \"\\<dots> \\<le> (\\<alpha>\\<up>\\<beta>) * \\<alpha>\"\n      using O\\<alpha>\\<beta> Ord_succ assms(2) assms(3) one_V_def succ_le_iff by auto\n    also have \"\\<dots> = \\<alpha>\\<up>succ \\<beta>\"\n      by (simp add: \\<open>Ord \\<beta>\\<close>)\n    also have \"\\<dots> \\<le> \\<alpha>\\<up>\\<gamma>\"\n      by (meson Limit_def \\<open>\\<beta> \\<in> elts \\<gamma>\\<close> assms dual_order.order_iff_strict oexp_less)\n  finally show ?thesis\n    by (simp add: \"2\" O\\<alpha>\\<beta> O\\<alpha>\\<gamma> Ord_mem_iff_lt)\n  qed\nqed\n\n\n\nlemma oexp_mono:\n  assumes \\<alpha>: \"Ord \\<alpha>\" \"\\<alpha> \\<noteq> 0\" and \\<beta>: \"Ord \\<beta>\" \"\\<gamma> \\<sqsubseteq> \\<beta>\" shows \"\\<alpha>\\<up>\\<gamma> \\<le> \\<alpha>\\<up>\\<beta>\"\n  using \\<beta>\nproof (induction rule: Ord_induct3)\n  case 0\n  then show ?case\n    by simp\nnext\n  case (succ \\<beta>)\n  with \\<alpha> le_mult show ?case\n    by (auto simp: le_TC_succ)\nnext\n  case (Limit \\<mu>)\n  then have \"\\<alpha>\\<up>\\<gamma> \\<le> \\<Squnion> ((\\<up>) \\<alpha> ` elts \\<mu>)\"\n    using Limit.hyps Ord_less_TC_mem \\<open>\\<alpha> \\<noteq> 0\\<close> le_TC_def by (auto simp: oexp_Limit Limit_def)\n  then show ?case\n    using \\<alpha> by (simp add: oexp_Limit Limit.hyps)\nqed\n\nlemma oexp_mono_le:\n  assumes \"\\<gamma> \\<le> \\<beta>\" \"\\<alpha> \\<noteq> 0\" \"Ord \\<alpha>\" \"Ord \\<beta>\" \"Ord \\<gamma>\" shows \"\\<alpha>\\<up>\\<gamma> \\<le> \\<alpha>\\<up>\\<beta>\"\n  by (simp add: assms oexp_mono vle2 vle_iff_le_Ord)\n\nlemma oexp_sup:\n  assumes \"\\<alpha> \\<noteq> 0\" \"Ord \\<alpha>\" \"Ord \\<beta>\" \"Ord \\<gamma>\" shows \"\\<alpha>\\<up>(\\<beta> \\<squnion> \\<gamma>) = \\<alpha>\\<up>\\<beta> \\<squnion> \\<alpha>\\<up>\\<gamma>\"\n  by (metis Ord_linear_le assms oexp_mono_le sup.absorb2 sup.orderE)\n\nlemma oexp_Sup:\n  assumes \\<alpha>: \"\\<alpha> \\<noteq> 0\" \"Ord \\<alpha>\" and X: \"X \\<subseteq> ON\" \"small X\" \"X \\<noteq> {}\" shows \"\\<alpha>\\<up>\\<Squnion> X = \\<Squnion> ((\\<up>) \\<alpha> ` X)\"\nproof (rule order_antisym)\n  show \"\\<Squnion> ((\\<up>) \\<alpha> ` X) \\<le> \\<alpha>\\<up>\\<Squnion> X\"\n    by (metis ON_imp_Ord Ord_Sup ZFC_in_HOL.Sup_upper assms cSUP_least oexp_mono_le)\nnext\n  have \"Ord (Sup X)\"\n    using Ord_Sup X by auto\n  then show \"\\<alpha>\\<up>\\<Squnion> X \\<le> \\<Squnion> ((\\<up>) \\<alpha> ` X)\"\n  proof (cases rule: Ord_cases)\n    case 0\n    then show ?thesis\n      using X dual_order.antisym by fastforce\n  next\n    case (succ \\<beta>)\n    then show ?thesis\n      using ZFC_in_HOL.Sup_upper X succ_in_Sup_Ord by auto\n  next\n    case limit\n    show ?thesis\n    proof (clarsimp simp: assms oexp_Limit limit)\n      fix x y z\n      assume x: \"x \\<in> elts (\\<alpha> \\<up> y)\" and \"z \\<in> X\" \"y \\<in> elts z\"\n      then have \"\\<alpha> \\<up> y \\<le> \\<alpha> \\<up> z\"\n        by (meson ON_imp_Ord Ord_in_Ord OrdmemD \\<alpha> \\<open>X \\<subseteq> ON\\<close> le_less oexp_mono_le)\n      with x have \"x \\<in> elts (\\<alpha> \\<up> z)\" by blast\n      then show \"\\<exists>u\\<in>X. x \\<in> elts (\\<alpha> \\<up> u)\"\n        using \\<open>z \\<in> X\\<close> by blast\n    qed\n  qed\nqed\n\n\nlemma omega_le_Limit:\n  assumes \"Limit \\<mu>\" shows \"\\<omega> \\<le> \\<mu>\"\nproof\n  fix \\<rho>\n  assume \"\\<rho> \\<in> elts \\<omega>\"\n  then obtain n where \"\\<rho> = ord_of_nat n\"\n    using elts_\\<omega> by auto\n  have \"ord_of_nat n \\<in> elts \\<mu>\"\n    by (induction n) (use Limit_def assms in auto)\n  then show \"\\<rho> \\<in> elts \\<mu>\"\n    using \\<open>\\<rho> = ord_of_nat n\\<close> by auto\nqed\n\nlemma finite_omega_power [simp]:\n  assumes \"1 < n\" \"n \\<in> elts \\<omega>\" shows \"n\\<up>\\<omega> = \\<omega>\"\nproof (rule order_antisym)\n  have \"\\<Squnion> ((\\<up>) (ord_of_nat k) ` elts \\<omega>) \\<le> \\<omega>\" for k\n  proof (induction k)\n    case 0\n    then show ?case\n      by auto\n  next\n    case (Suc k)\n    then show ?case\n      by (metis Ord_\\<omega> OrdmemD Sup_eq_0_iff ZFC_in_HOL.SUP_le_iff le_0 le_less omega_closed_oexp ord_of_nat_\\<omega>)\n  qed\n  then show \"n\\<up>\\<omega> \\<le> \\<omega>\"\n    using assms\n    by (simp add: elts_\\<omega> oexp_Limit) metis\n  show \"\\<omega> \\<le> n\\<up>\\<omega>\"\n    using Ord_in_Ord assms le_oexp' by blast\nqed\n\n\nproposition oexp_add:\n  assumes \"Ord \\<alpha>\" \"Ord \\<beta>\" \"Ord \\<gamma>\" shows \"\\<alpha>\\<up>(\\<beta> + \\<gamma>) = \\<alpha>\\<up>\\<beta> * \\<alpha>\\<up>\\<gamma>\"\nproof (cases \\<open>\\<alpha> = 0\\<close>)\n  case True\n  then show ?thesis\n    using assms by simp\nnext\n  case False\n  show ?thesis\n    using \\<open>Ord \\<gamma>\\<close>\n  proof (induction rule: Ord_induct3)\n    case 0\n    then show ?case\n      by auto\n  next\n    case (succ \\<xi>)\n    then show ?case\n      using \\<open>Ord \\<beta>\\<close> by (auto simp: plus_V_succ_right mult.assoc)\n  next\n    case (Limit \\<mu>)\n    have \"\\<alpha>\\<up>(\\<beta> + (SUP \\<xi>\\<in>elts \\<mu>. \\<xi>)) = (SUP \\<xi>\\<in>elts (\\<beta> + \\<mu>). \\<alpha>\\<up>\\<xi>)\"\n      by (simp add: Limit.hyps oexp_Limit assms False)\n    also have \"\\<dots> = (SUP \\<xi> \\<in> {\\<xi>. Ord \\<xi> \\<and> \\<beta> + \\<xi> < \\<beta> + \\<mu>}. \\<alpha>\\<up>(\\<beta> + \\<xi>))\"\n    proof (rule Sup_eq_Sup)\n      show \"(\\<lambda>\\<xi>. \\<alpha>\\<up>(\\<beta> + \\<xi>)) ` {\\<xi>. Ord \\<xi> \\<and> \\<beta> + \\<xi> < \\<beta> + \\<mu>} \\<subseteq> (\\<up>) \\<alpha> ` elts (\\<beta> + \\<mu>)\"\n        using Limit.hyps Limit_def Ord_mem_iff_lt imageI by blast\n      fix x\n      assume \"x \\<in> (\\<up>) \\<alpha> ` elts (\\<beta> + \\<mu>)\"\n      then obtain \\<xi> where \\<xi>: \"\\<xi> \\<in> elts (\\<beta> + \\<mu>)\" and x: \"x = \\<alpha>\\<up>\\<xi>\"\n        by auto\n      have \"\\<exists>\\<gamma>. Ord \\<gamma> \\<and> \\<gamma> < \\<mu> \\<and> \\<alpha>\\<up>\\<xi> \\<le> \\<alpha>\\<up>(\\<beta> + \\<gamma>)\"\n      proof (rule mem_plus_V_E [OF \\<xi>])\n        assume \"\\<xi> \\<in> elts \\<beta>\"\n        then have \"\\<alpha>\\<up>\\<xi> \\<le> \\<alpha>\\<up>\\<beta>\"\n          by (meson arg_subset_TC assms False le_TC_def less_TC_def oexp_mono vsubsetD)\n        with zero_less_Limit [OF \\<open>Limit \\<mu>\\<close>]\n        show \"\\<exists>\\<gamma>. Ord \\<gamma> \\<and> \\<gamma> < \\<mu> \\<and> \\<alpha>\\<up>\\<xi> \\<le> \\<alpha>\\<up>(\\<beta> + \\<gamma>)\"\n          by force\n      next\n        fix \\<delta>\n        assume \"\\<delta> \\<in> elts \\<mu>\" and \"\\<xi> = \\<beta> + \\<delta>\"\n        have \"Ord \\<delta>\"\n          using Limit.hyps Limit_def Ord_in_Ord \\<open>\\<delta> \\<in> elts \\<mu>\\<close> by blast\n        moreover have \"\\<delta> < \\<mu>\"\n          using Limit.hyps Limit_def OrdmemD \\<open>\\<delta> \\<in> elts \\<mu>\\<close> by auto\n        ultimately show \"\\<exists>\\<gamma>. Ord \\<gamma> \\<and> \\<gamma> < \\<mu> \\<and> \\<alpha>\\<up>\\<xi> \\<le> \\<alpha>\\<up>(\\<beta> + \\<gamma>)\"\n          using \\<open>\\<xi> = \\<beta> + \\<delta>\\<close> by blast\n      qed\n      then show \"\\<exists>y\\<in>(\\<lambda>\\<xi>. \\<alpha>\\<up>(\\<beta> + \\<xi>)) ` {\\<xi>. Ord \\<xi> \\<and> \\<beta> + \\<xi> < \\<beta> + \\<mu>}. x \\<le> y\"\n        using x by auto\n    qed auto\n    also have \"\\<dots> = (SUP \\<xi>\\<in>elts \\<mu>. \\<alpha>\\<up>(\\<beta> + \\<xi>))\"\n      using \\<open>Limit \\<mu>\\<close>\n      by (simp add: Ord_Collect_lt Limit_def)\n    also have \"\\<dots> = (SUP \\<xi>\\<in>elts \\<mu>. \\<alpha>\\<up>\\<beta> * \\<alpha>\\<up>\\<xi>)\"\n      using Limit.IH by auto\n    also have \"\\<dots> = \\<alpha>\\<up>\\<beta> * \\<alpha>\\<up>(SUP \\<xi>\\<in>elts \\<mu>. \\<xi>)\"\n      using \\<open>\\<alpha> \\<noteq> 0\\<close> Limit.hyps\n      by (simp add: image_image oexp_Limit mult_Sup_distrib)\n    finally show ?case .\n  qed\nqed\n\nproposition oexp_mult:\n  assumes \"Ord \\<alpha>\" \"Ord \\<beta>\" \"Ord \\<gamma>\" shows \"\\<alpha>\\<up>(\\<beta> * \\<gamma>) = (\\<alpha>\\<up>\\<beta>)\\<up>\\<gamma>\"\nproof (cases \"\\<alpha> = 0 \\<or> \\<beta> = 0\")\n  case True\n  then show ?thesis\n    by (auto simp: \\<open>Ord \\<beta>\\<close> \\<open>Ord \\<gamma>\\<close>)\nnext\n  case False\n  show ?thesis\n    using \\<open>Ord \\<gamma>\\<close>\n  proof (induction rule: Ord_induct3)\n    case 0\n    then show ?case\n      by auto\n  next\n    case succ\n    then show ?case\n      using assms by (auto simp: mult_succ oexp_add)\n  next\n    case (Limit \\<mu>)\n    have Lim: \"Limit (\\<Squnion> ((*) \\<beta> ` elts \\<mu>))\"\n      unfolding Limit_def\n    proof (intro conjI allI impI)\n      show \"Ord (\\<Squnion> ((*) \\<beta> ` elts \\<mu>))\"\n        using Limit.hyps Limit_def Ord_in_Ord \\<open>Ord \\<beta>\\<close> by (auto intro: Ord_Sup)\n      have \"succ 0 \\<in> elts \\<mu>\"\n        using Limit.hyps Limit_def by blast\n      then show \"0 \\<in> elts (\\<Squnion> ((*) \\<beta> ` elts \\<mu>))\"\n        using False \\<open>Ord \\<beta>\\<close> mem_0_Ord by force\n      show \"succ y \\<in> elts (\\<Squnion> ((*) \\<beta> ` elts \\<mu>))\"\n        if \"y \\<in> elts (\\<Squnion> ((*) \\<beta> ` elts \\<mu>))\" for y\n        using that False Limit.hyps\n        apply (clarsimp simp: Limit_def)\n        by (metis Ord_in_Ord Ord_linear Ord_mem_iff_lt Ord_mult Ord_succ assms(2) less_V_def mult_cancellation mult_succ not_add_mem_right succ_le_iff succ_ne_self)\n    qed\n    have \"\\<alpha>\\<up>(\\<beta> * (SUP \\<xi>\\<in>elts \\<mu>. \\<xi>)) = \\<alpha>\\<up>\\<Squnion> ((*) \\<beta> ` elts \\<mu>)\"\n      by (simp add: mult_Sup_distrib)\n    also have \"\\<dots> = \\<Squnion> (\\<Union>x\\<in>elts \\<mu>. (\\<up>) \\<alpha> ` elts (\\<beta> * x))\"\n      using False Lim oexp_Limit by fastforce\n    also have \"\\<dots> = (SUP x\\<in>elts \\<mu>. \\<alpha>\\<up>(\\<beta> * x))\"\n    proof (rule Sup_eq_Sup)\n      show \"(\\<lambda>x. \\<alpha>\\<up>(\\<beta> * x)) ` elts \\<mu> \\<subseteq> (\\<Union>x\\<in>elts \\<mu>. (\\<up>) \\<alpha> ` elts (\\<beta> * x))\"\n        using \\<open>Ord \\<alpha>\\<close> \\<open>Ord \\<beta>\\<close> False Limit\n        apply clarsimp\n        by (metis Limit_def elts_succ imageI insertI1 mem_0_Ord mult_add_mem_0)\n      show \"\\<exists>y\\<in>(\\<lambda>x. \\<alpha>\\<up>(\\<beta> * x)) ` elts \\<mu>. x \\<le> y\"\n        if \"x \\<in> (\\<Union>x\\<in>elts \\<mu>. (\\<up>) \\<alpha> ` elts (\\<beta> * x))\" for x\n        using that \\<open>Ord \\<alpha>\\<close> \\<open>Ord \\<beta>\\<close> False Limit\n        by clarsimp (metis Limit_def Ord_in_Ord Ord_mult VWO_TC_le mem_imp_VWO oexp_mono)\n    qed auto\n    also have \"\\<dots> = \\<Squnion> ((\\<up>) (\\<alpha>\\<up>\\<beta>) ` elts (SUP \\<xi>\\<in>elts \\<mu>. \\<xi>))\"\n      using Limit.IH Limit.hyps by auto\n    also have \"\\<dots> = (\\<alpha>\\<up>\\<beta>)\\<up>(SUP \\<xi>\\<in>elts \\<mu>. \\<xi>)\"\n      using False Limit.hyps oexp_Limit \\<open>Ord \\<beta>\\<close> by auto\n    finally show ?case .\n  qed\nqed\n\nlemma Limit_omega_oexp:\n  assumes \"Ord \\<delta>\" \"\\<delta> \\<noteq> 0\"\n  shows \"Limit (\\<omega>\\<up>\\<delta>)\"\n  using assms\nproof (cases \\<delta> rule: Ord_cases)\n  case 0\n  then show ?thesis\n    using assms(2) by blast\nnext\n  case (succ l)\n  have *: \"succ \\<beta> \\<in> elts (\\<omega>\\<up>l * n + \\<omega>\\<up>l)\"\n    if n: \"n \\<in> elts \\<omega>\" and \\<beta>: \"\\<beta> \\<in> elts (\\<omega>\\<up>l * n)\" for n \\<beta>\n  proof -\n    obtain \"Ord n\" \"Ord \\<beta>\"\n      by (meson Ord_\\<omega> Ord_in_Ord Ord_mult Ord_oexp \\<beta> n succ(1))\n    obtain oo: \"Ord (\\<omega>\\<up>l)\" \"Ord (\\<omega>\\<up>l * n)\"\n      by (simp add: \\<open>Ord n\\<close> succ(1))\n    moreover have f4: \"\\<beta> < \\<omega>\\<up>l * n\"\n      using oo Ord_mem_iff_lt \\<open>Ord \\<beta>\\<close> \\<open>\\<beta> \\<in> elts (\\<omega>\\<up>l * n)\\<close> by blast\n    moreover have f5: \"Ord (succ \\<beta>)\"\n      using \\<open>Ord \\<beta>\\<close> by blast\n    moreover have \"\\<omega>\\<up>l \\<noteq> 0\"\n      using oexp_eq_0_iff omega_nonzero succ(1) by blast\n    ultimately show ?thesis\n      by (metis add_less_cancel_left Ord_\\<omega> Ord_add Ord_mem_iff_lt OrdmemD \\<open>Ord \\<beta>\\<close> add.right_neutral dual_order.strict_trans2 oexp_gt_0_iff succ(1) succ_le_iff zero_in_omega)\n  qed\n  show ?thesis\n    using succ\n    apply (clarsimp simp: Limit_def mem_0_Ord)\n    apply (simp add: mult_Limit)\n    by (metis * mult_succ succ_in_omega)\nnext\n  case limit\n  then show ?thesis\n    by (metis Limit_oexp Ord_\\<omega> OrdmemD one_V_def succ_in_omega zero_in_omega)\nqed\n\nlemma \\<omega>_power_succ_gtr: \"Ord \\<alpha> \\<Longrightarrow> \\<omega> \\<up> \\<alpha> * ord_of_nat n < \\<omega> \\<up> succ \\<alpha>\"\n  by (simp add: OrdmemD)\n\nlemma countable_oexp:\n  assumes \\<nu>: \"\\<alpha> \\<in> elts \\<omega>1\" \n  shows \"\\<omega> \\<up> \\<alpha> \\<in> elts \\<omega>1\"\nproof -\n  have \"Ord \\<alpha>\"\n    using Ord_\\<omega>1 Ord_in_Ord assms by blast\n  then show ?thesis\n    using assms\n  proof (induction rule: Ord_induct3)\n    case 0\n    then show ?case\n      by (simp add: Ord_mem_iff_lt)\n  next\n    case (succ \\<alpha>)\n    then have \"countable (elts (\\<omega> \\<up> \\<alpha> * \\<omega>))\"\n      by (simp add: succ_in_Limit_iff countable_mult less_\\<omega>1_imp_countable)\n    then show ?case\n      using Ord_mem_iff_lt countable_iff_less_\\<omega>1 succ.hyps by auto\n  next\n    case (Limit \\<alpha>)\n    with Ord_\\<omega>1 have \"countable (\\<Union>\\<beta>\\<in>elts \\<alpha>. elts (\\<omega> \\<up> \\<beta>))\" \"Ord (\\<omega> \\<up> \\<Squnion> (elts \\<alpha>))\"\n      by (force simp: Limit_def intro: Ord_trans less_\\<omega>1_imp_countable)+\n    then have \"\\<omega> \\<up> \\<Squnion> (elts \\<alpha>) < \\<omega>1\"\n      using Limit.hyps countable_iff_less_\\<omega>1 oexp_Limit by fastforce\n    then show ?case\n      using Limit.hyps Limit_def Ord_mem_iff_lt by auto\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/Evaluation/ZFC_in_HOL/Ordinal_Exp.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9046505248181418, "lm_q2_score": 0.8080672158638528, "lm_q1q2_score": 0.7310184309195691}}
{"text": "(*by Ammer*)\ntheory VEBT_Pred imports VEBT_MinMax VEBT_Insert\nbegin\n\nsection \\<open>The Predecessor Operation\\<close>\n\ndefinition is_pred_in_set :: \"nat set \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> bool\" where\n  \"is_pred_in_set xs x y =  (y \\<in> xs \\<and> y < x \\<and> (\\<forall> z \\<in> xs. (z < x \\<longrightarrow> z \\<le> y)))\"\n\ncontext VEBT_internal begin  \n  \nsubsection \\<open>Lemmas on Sets and Predecessorship\\<close>\n\ncorollary pred_member: \"is_pred_in_set (set_vebt' t) x y = (vebt_member t y \\<and> y < x \\<and> (\\<forall> z. vebt_member t z \\<and> z < x \\<longrightarrow> z \\<le> y))\" \n  using is_pred_in_set_def set_vebt'_def by auto\n\nlemma \"finite (A:: nat set) \\<Longrightarrow> A \\<noteq> {}\\<Longrightarrow> Max A \\<in> A\"\nproof(induction A rule: finite.induct)\n  case emptyI\n  then show ?case by blast\nnext\n  case (insertI A a)\n  then show ?case \n    by (meson Max_in finite_insert)\nqed\n\nlemma obtain_set_pred: assumes \"(x::nat) > z \" and \"min_in_set A z\" and \"finite A\"  shows \"\\<exists> y. is_pred_in_set A x y\"\nproof-\n  have \"{y \\<in> A. y < x} \\<noteq> {}\"\n    using assms(1) assms(2) min_in_set_def by auto\n  hence \"Max {y \\<in> A. y < x} \\<in> {y \\<in> A. y < x}\" \n    by (metis (full_types) Max_eq_iff finite_M_bounded_by_nat)\n  moreover have \"i \\<in> A\\<Longrightarrow> i < x \\<Longrightarrow> i \\<le> Max {y \\<in> A. y < x} \" for i by simp\n  ultimately have \"is_pred_in_set A x (Max {y \\<in> A. y < x})\" \n    using is_pred_in_set_def by auto\n  then show?thesis by auto\nqed\n\nlemma pred_none_empty: assumes \"(\\<nexists> x. is_pred_in_set (xs) a x)\"  and \"finite xs\"shows \"\\<not> (\\<exists> x \\<in> xs. ord_class.less x a)\"\nproof-\n  have \"\\<exists> x \\<in> xs. ord_class.less x a \\<Longrightarrow> False\"\n  proof-\n    assume \"\\<exists> x \\<in> xs. ord_class.less x a\"\n    hence \"{x \\<in> xs. ord_class.less x  a} \\<noteq> {}\" by auto\n    hence \"Max {y \\<in> xs. y < a} \\<in> {y \\<in> xs. y < a}\"\n      by (metis (full_types) Max_eq_iff finite_M_bounded_by_nat)\n    moreover hence \"i \\<in> xs \\<Longrightarrow>  ord_class.less i  a\\<Longrightarrow> \n             ord_class.less_eq i (Max {y \\<in> xs. ord_class.less y  a}) \" for i \n      by (simp add: assms(2))\n    ultimately have \"is_pred_in_set xs a (Max {y \\<in> xs. y < a})\"\n      using is_pred_in_set_def by auto\n    then show False \n      using assms(1) by blast\n  qed\n  then show ?thesis by blast\nqed\n\nend\n\nsubsection \\<open>The actual Function for Predecessor Search\\<close>\n\ncontext begin\n  interpretation VEBT_internal .\n\nfun vebt_pred :: \"VEBT \\<Rightarrow> nat \\<Rightarrow> nat option\" where\n  \"vebt_pred (Leaf _ _) 0 = None\"|\n  \"vebt_pred (Leaf a _) (Suc 0) = (if a then Some 0 else None)\"|\n  \"vebt_pred (Leaf a b) _ = (if b then Some 1 else if a then Some 0 else None)\"|\n  \"vebt_pred (Node None _ _ _) _ = None\"|\n  \"vebt_pred (Node _ 0 _ _) _ = None\"|\n  \"vebt_pred (Node _ (Suc 0) _ _) _ = None\"|\n  \"vebt_pred (Node (Some (mi, ma)) deg treeList summary) x = (\n         if x > ma then Some ma \n         else (let l = low x (deg div 2); h = high x (deg div 2) in \n               if h < length treeList then  \n                  let minlow = vebt_mint (treeList ! h) in (\n                      if minlow \\<noteq> None \\<and> (Some l >\\<^sub>o  minlow) then \n                         Some (2^(deg div 2)) *\\<^sub>o Some h +\\<^sub>o vebt_pred (treeList ! h) l\n                      else let pr = vebt_pred summary h in\n                               if pr = None then (\n                                  if x > mi then Some mi \n                                  else None)\n                               else Some (2^(deg div 2)) *\\<^sub>o pr +\\<^sub>o vebt_maxt (treeList ! the pr) )\n               else None))\"\n\nend               \n               \ncontext VEBT_internal begin\nsubsection \\<open>Auxiliary Lemmas\\<close>\n\nlemma pred_max: \n  assumes \"deg \\<ge> 2\" and \"(x::nat) > ma\" \n  shows \"vebt_pred (Node (Some (mi, ma)) deg treeList summary) x = Some ma\"\n  by (metis VEBT_Pred.vebt_pred.simps(7) add_2_eq_Suc assms(1) assms(2) le_add_diff_inverse)\n\nlemma pred_lesseq_max: \n  assumes \"deg \\<ge> 2\" and \"(x::nat) \\<le> ma\" \n  shows \"vebt_pred (Node (Some (mi, ma)) deg treeList summary) x =  (let l = low x (deg div 2); h = high x (deg div 2) in \n                       if h < length treeList then  \n  \n                            let minlow = vebt_mint (treeList ! h) in \n                            (if minlow \\<noteq> None \\<and> (Some l >\\<^sub>o  minlow) then \n                                                    Some (2^(deg div 2)) *\\<^sub>o Some h +\\<^sub>o vebt_pred (treeList ! h) l\n                             else let pr = vebt_pred summary h in\n                             if pr = None then (if x > mi then Some mi else None)\n                             else Some (2^(deg div 2)) *\\<^sub>o pr +\\<^sub>o vebt_maxt (treeList ! the pr) )\n\n                     else None)\"\n  by (smt VEBT_Pred.vebt_pred.simps(7) add_numeral_left assms(1) assms(2) leD le_add_diff_inverse numerals(1) plus_1_eq_Suc semiring_norm(2))\n\nlemma pred_list_to_short: \n  assumes \"deg \\<ge> 2\" and \"ord_class.less_eq x ma\" and \" high x (deg div 2) \\<ge> length treeList\" \n  shows \"vebt_pred (Node (Some (mi, ma)) deg treeList summary) x = None\" \n  by (simp add: assms(1) assms(2) assms(3) leD pred_lesseq_max)\n\n\nlemma pred_less_length_list: \n  assumes \"deg \\<ge> 2\" and \"ord_class.less_eq x  ma\" and \" high x (deg div 2) < length treeList\" \n  shows\n  \"vebt_pred (Node (Some (mi, ma)) deg treeList summary) x = (let l = low x (deg div 2); h = high x (deg div 2); minlow = vebt_mint (treeList ! h) in \n                            (if minlow \\<noteq> None \\<and> (Some l >\\<^sub>o  minlow) then \n                                                    Some (2^(deg div 2)) *\\<^sub>o Some h +\\<^sub>o vebt_pred (treeList ! h) l\n                             else let pr = vebt_pred summary h in\n                             if pr = None then (if x > mi then Some mi else None)\n                             else Some (2^(deg div 2)) *\\<^sub>o pr +\\<^sub>o vebt_maxt (treeList ! the pr) ))\"\n  by (simp add: assms(1) assms(2) assms(3) pred_lesseq_max)\n\nsubsection \\<open>Correctness Proof\\<close>\n\ntheorem pred_corr: \"invar_vebt t n \\<Longrightarrow> vebt_pred t x = Some px == is_pred_in_set (set_vebt' t) x px\"\nproof(induction t n arbitrary: x px rule: invar_vebt.induct)\n  case (1 a b)\n  then show ?case \n  proof(cases x)\n    case 0\n    then show ?thesis\n      by (simp add: is_pred_in_set_def)\n  next\n    case (Suc sucX)\n    hence \"x \\<ge> 0 \\<and> x = Suc sucX\" by auto\n    then show ?thesis\n    proof(cases sucX)\n      case 0\n      then show ?thesis\n        by (simp add: Suc pred_member)\n    next\n      case (Suc nat)\n      hence \"x\\<ge> 2\" \n        by (simp add: \\<open>0 \\<le> x \\<and> x = Suc sucX\\<close>)\n      then show ?thesis\n      proof(cases b)\n        case True\n        hence \"vebt_pred (Leaf a b) x = Some 1\"\n          by (simp add: Suc \\<open>0 \\<le> x \\<and> x = Suc sucX\\<close>)\n        moreover have \"is_pred_in_set (set_vebt' (Leaf a b)) x 1\" \n          by (simp add: Suc True \\<open>0 \\<le> x \\<and> x = Suc sucX\\<close> pred_member)\n        ultimately show ?thesis\n          using pred_member by auto\n      next\n        case False\n        hence \"b = False\" by simp\n        then show ?thesis\n        proof(cases a)\n          case True\n          hence \"vebt_pred (Leaf a b) x = Some 0\" \n            by (simp add: False Suc \\<open>0 \\<le> x \\<and> x = Suc sucX\\<close>)\n          moreover have \"is_pred_in_set (set_vebt' (Leaf a b)) x 0\"\n            by (simp add: False True \\<open>0 \\<le> x \\<and> x = Suc sucX\\<close> pred_member)\n          ultimately show ?thesis \n            by (metis False VEBT_Member.vebt_member.simps(1) option.sel pred_member)\n        next\n          case False\n          then show ?thesis\n            by (simp add: Suc \\<open>0 \\<le> x \\<and> x = Suc sucX\\<close> pred_member)\n        qed\n      qed\n    qed\n  qed\nnext\n  case (2 treeList n summary m deg)\n  then show ?case\n    by (simp add: pred_member)\nnext\n  case (3 treeList n summary m deg)\n  then show ?case\n    by (simp add: pred_member)\nnext\n  case (4 treeList n summary m deg mi ma)\n  hence \"n = m\" and \"n \\<ge> 1\" and \"deg \\<ge> 2\" and \"deg = n + m\"\n       apply blast+ \n    using \"4.hyps\"(2) \"4.hyps\"(5) Suc_le_eq deg_not_0 apply auto[1]\n    using \"4.hyps\"(2) \"4.hyps\"(5) \"4.hyps\"(6) deg_not_0 apply fastforce\n    by (simp add: \"4.hyps\"(6))\n  moreover hence thisvalid:\"invar_vebt (Node (Some (mi, ma)) deg treeList summary) deg\" \n    using 4 invar_vebt.intros(4)[of treeList n summary m]  by blast\n  ultimately have \"deg div 2 =n\" and \"length treeList = 2^n\" \n    using add_self_div_2 apply blast by (simp add: \"4.hyps\"(4) \"4.hyps\"(5))\n  then show ?case\n  proof(cases \"x > ma\")\n    case True\n    hence 0: \"vebt_pred (Node (Some (mi, ma)) deg treeList summary) x = Some ma\" \n      by (simp add: \\<open>2 \\<le> deg\\<close> pred_max)\n    have 1:\"ma = the (vebt_maxt (Node (Some (mi, ma)) deg treeList summary))\" by simp\n    hence \"ma \\<in> set_vebt' (Node (Some (mi, ma)) deg treeList summary)\"\n      by (metis VEBT_Member.vebt_member.simps(5) \\<open>2 \\<le> deg\\<close> add_numeral_left arith_simps(1) le_add_diff_inverse mem_Collect_eq numerals(1) plus_1_eq_Suc set_vebt'_def)\n    hence 2:\"y \\<in> set_vebt' (Node (Some (mi, ma)) deg treeList summary) \\<Longrightarrow> y \\<le> x\" for y\n      using \"4.hyps\"(9) True member_inv set_vebt'_def by fastforce\n    hence 3: \"y \\<in> set_vebt' (Node (Some (mi, ma)) deg treeList summary) \\<Longrightarrow> (y < ma \\<Longrightarrow> y \\<le> x)\" for y by blast\n    hence 4: \"\\<forall> y \\<in> set_vebt' (Node (Some (mi, ma)) deg treeList summary). y < ma \\<longrightarrow> y \\<le> x\" by blast\n    hence \"is_pred_in_set (set_vebt' (Node (Some (mi, ma)) deg treeList summary)) x ma\" \n      by (metis \"4.hyps\"(9) True \\<open>ma \\<in> set_vebt' (Node (Some (mi, ma)) deg treeList summary)\\<close> less_or_eq_imp_le mem_Collect_eq member_inv pred_member set_vebt'_def)\n    then show ?thesis \n      by (metis \"0\" option.sel leD le_less_Suc_eq not_less_eq pred_member)\n  next\n    case False\n    hence \"x \\<le> ma\"by simp  \n    then show ?thesis \n    proof(cases \"high x (deg div 2)< length treeList \")\n      case True\n      hence \"high x n < 2^n \\<and> low x n < 2^n\"\n        by (simp add: \\<open>deg div 2 = n\\<close> \\<open>length treeList = 2 ^ n\\<close> low_def)\n      let ?l = \"low x (deg div 2)\" \n      let ?h = \"high x (deg div 2)\"\n      let ?minlow = \"vebt_mint (treeList ! ?h)\"\n      let ?pr = \"vebt_pred summary ?h\"\n      have 1:\"vebt_pred (Node (Some (mi, ma)) deg treeList summary) x = \n                           (if ?minlow \\<noteq> None \\<and> (Some ?l >\\<^sub>o  ?minlow) then \n                                                    Some (2^(deg div 2)) *\\<^sub>o Some ?h +\\<^sub>o vebt_pred (treeList ! ?h) ?l\n                             else let pr = vebt_pred summary ?h in\n                             if pr = None then (if x > mi then Some mi else None)\n                             else Some (2^(deg div 2)) *\\<^sub>o pr +\\<^sub>o vebt_maxt (treeList ! the pr) )\"\n        by (smt True \\<open>2 \\<le> deg\\<close> \\<open>x \\<le> ma\\<close> pred_less_length_list)     \n      then show ?thesis \n      proof(cases \"?minlow \\<noteq> None \\<and> (Some ?l >\\<^sub>o  ?minlow)\")\n        case True\n        then obtain minl where 00:\"(Some minl = ?minlow) \\<and> ?l > minl\" by auto\n        have 01:\"invar_vebt ((treeList ! ?h)) n \\<and> (treeList ! ?h) \\<in> set treeList \"\n          by (simp add: \"4.hyps\"(1) \"4.hyps\"(4) \"4.hyps\"(5) \\<open>deg div 2 = n\\<close> \\<open>high x n < 2 ^ n \\<and> low x n < 2 ^ n\\<close>)\n        have  02:\"vebt_member ((treeList ! ?h)) minl\" \n          using \"00\" \"01\" mint_member by auto\n        hence 03: \"\\<exists> y. y < ?l \\<and> vebt_member ((treeList ! ?h)) y\"\n          using \"00\" by blast \n        hence afinite: \"finite (set_vebt' (treeList ! ?h)) \" \n          using \"01\" set_vebt_finite by blast\n        then obtain predy where 04:\"is_pred_in_set (set_vebt' (treeList ! ?h)) ?l predy\"\n          using \"00\" \"01\" mint_corr obtain_set_pred by fastforce\n        hence 05:\"Some predy =  vebt_pred (treeList ! ?h) ?l\"  using 4(1) 01 by force\n        hence \"vebt_pred (Node (Some (mi, ma)) deg treeList summary) x  =  Some (2^(deg div 2)*  ?h + predy) \"\n          using  \"1\" True add_def mul_def option_shift.simps(3) by metis\n        hence 06: \"predy \\<in> set_vebt' (treeList ! ?h)\" \n          using \"04\" is_pred_in_set_def by blast\n        hence 07: \"predy < 2^(deg div 2) \\<and> ?h < 2^(deg div 2) \\<and> deg div 2 + deg div 2 = deg\" \n          using \"01\" \"04\" \"4.hyps\"(5) \"4.hyps\"(6) \\<open>high x n < 2 ^ n \\<and> low x n < 2 ^ n\\<close> member_bound pred_member by auto\n        let ?y = \"2^(deg div 2)*  ?h + predy\"\n        have 08: \"vebt_member (treeList ! ?h) predy\"\n          using \"06\" set_vebt'_def by auto\n        hence 09: \"both_member_options (treeList ! ?h) predy\"\n          using \"01\" both_member_options_equiv_member by blast\n        have 10: \"high ?y (deg div 2) = ?h \\<and> low ?y (deg div 2) = predy\"\n          by (simp add: \"07\" high_inv low_inv mult.commute)\n        hence 14:\"both_member_options (Node (Some (mi, ma)) deg treeList summary) ?y\" \n          by (metis \"07\" \"09\" \"4.hyps\"(4) \"4.hyps\"(5) Suc_1 \\<open>2 \\<le> deg\\<close> \\<open>deg div 2 = n\\<close> add_leD1 both_member_options_from_chilf_to_complete_tree plus_1_eq_Suc)\n        have 15: \"vebt_member (Node (Some (mi, ma)) deg treeList summary) ?y\" \n          using \"14\" thisvalid valid_member_both_member_options by blast\n        have 16: \"Some ?y = vebt_pred (Node (Some (mi, ma)) deg treeList summary) x\" \n          by (simp add: \\<open>vebt_pred (Node (Some (mi, ma)) deg treeList summary) x = Some (2 ^ (deg div 2) * high x (deg div 2) + predy)\\<close>)\n        have 17: \"x = ?h * 2^(deg div 2) + ?l\"\n          using bit_concat_def bit_split_inv by auto \n        have 18: \"x - ?y =   ?h * 2^(deg div 2) + ?l -?h * 2^(deg div 2) - predy \" \n          by (metis \"17\" diff_diff_add mult.commute)\n        hence 19: \"?y < x\" \n          using \"04\" \"17\" mult.commute nat_add_left_cancel_less pred_member by fastforce\n        have 20: \"z < x \\<Longrightarrow> vebt_member (Node (Some (mi, ma)) deg treeList summary) z \\<Longrightarrow> z\\<le> ?y \" for z \n        proof-\n          assume \"z < x\" and \"vebt_member (Node (Some (mi, ma)) deg treeList summary) z\"\n          hence \"high z (deg div 2) \\<le> high x (deg div 2)\" \n            by (simp add: div_le_mono high_def)\n          then show ?thesis \n          proof(cases \"high z (deg div 2) = high x (deg div 2)\")\n            case True\n            hence 0000: \"high z (deg div 2) = high x (deg div 2)\" by simp\n            then show ?thesis\n            proof(cases \"z = mi\")\n              case True\n              then show ?thesis\n                using \"15\" vebt_mint.simps(3) mint_corr_help thisvalid by blast\n            next\n              case False    \n              hence ad:\"vebt_member (treeList ! ?h) (low z (deg div 2))\" \n                using vebt_member.simps(5)[of mi ma \"deg-2\" treeList summary z]\n                by (metis True \\<open>vebt_member (Node (Some (mi, ma)) deg treeList summary) z\\<close> \\<open>x \\<le> ma\\<close> \\<open>z < x\\<close> leD member_inv)\n              have \"is_pred_in_set (set_vebt' (treeList ! ?h)) ?l predy\" \n                using \"04\" by blast\n              have \"low z (deg div 2) < ?l\" \n                by (metis (full_types) True \\<open>z < x\\<close> bit_concat_def bit_split_inv nat_add_left_cancel_less)\n              hence \"predy \\<ge> low z (deg div 2)\" using 04 ad unfolding is_pred_in_set_def\n                by (simp add: set_vebt'_def)\n              hence \"?y \\<ge> z\" \n                by (smt True bit_concat_def bit_split_inv diff_add_inverse diff_diff_add diff_is_0_eq mult.commute)\n              then show ?thesis by blast\n            qed\n          next\n            case False\n            hence \"high z (deg div 2) < high ?y (deg div 2)\"\n              using \"10\" \\<open>high z (deg div 2) \\<le> high x (deg div 2)\\<close> by linarith\n            then show ?thesis \n              by (metis div_le_mono high_def nat_le_linear not_le)\n          qed\n        qed\n        hence \"is_pred_in_set (set_vebt' (Node (Some (mi, ma)) deg treeList summary)) x ?y\" \n          by (simp add: \"15\" \"19\" pred_member)\n        then show ?thesis using 16\n          by (metis eq_iff option.inject pred_member)\n      next\n        case False\n        hence i1:\"?minlow =  None \\<or> \\<not> (Some ?l >\\<^sub>o  ?minlow)\" by simp\n        hence 2: \"vebt_pred (Node (Some (mi, ma)) deg treeList summary) x =  (\n                            if ?pr = None then (if x > mi \n                                                then Some mi \n                                                else None)\n                             else Some (2^(deg div 2)) *\\<^sub>o ?pr +\\<^sub>o vebt_maxt (treeList ! the ?pr))\" \n          using \"1\" by auto\n        have \" invar_vebt (treeList ! ?h) n\"\n          by (metis \"4\"(1) True inthall member_def)\n        hence 33:\"\\<nexists> u. vebt_member (treeList ! ?h) u \\<and> u < ?l\"\n        proof(cases \"?minlow = None\")\n          case True\n          then show ?thesis using mint_corr_help_empty[of \"treeList ! ?h\" n] \n            by (simp add: \\<open>invar_vebt (treeList ! high x (deg div 2)) n\\<close> set_vebt'_def)\n        next\n          case False\n          obtain minilow where \"?minlow =Some minilow\" \n            using False by blast\n          hence \"minilow \\<ge> ?l\" \n            using \"i1\" by auto\n          then show ?thesis\n            by (meson \\<open>vebt_mint (treeList ! high x (deg div 2)) = Some minilow\\<close> \\<open>invar_vebt (treeList ! high x (deg div 2)) n\\<close> leD less_le_trans mint_corr_help)\n        qed\n        then show ?thesis \n        proof(cases \"?pr= None\")\n          case True\n          hence \"vebt_pred (Node (Some (mi, ma)) deg treeList summary) x =  (if x > mi then Some mi else  None)\" \n            by (simp add: \"2\")\n          hence \"\\<nexists> i. is_pred_in_set (set_vebt' summary) ?h i\"\n            using \"4.hyps\"(3) True by force\n          hence \"\\<nexists> i. i < ?h \\<and> vebt_member summary i \" using pred_none_empty[of \"set_vebt' summary\" ?h] \n          proof -\n            { fix nn :: nat\n              have \"\\<forall>n. ((is_pred_in_set (Collect (vebt_member summary)) (high x (deg div 2)) esk1_0 \\<or> infinite (Collect (vebt_member summary))) \\<or> n \\<notin> Collect (vebt_member summary)) \\<or> \\<not> n < high x (deg div 2)\"\n                using \\<open>\\<nexists>i. is_pred_in_set (set_vebt' summary) (high x (deg div 2)) i\\<close> pred_none_empty set_vebt'_def by auto\n              then have \"\\<not> nn < high x (deg div 2) \\<or> \\<not> vebt_member summary nn\"\n                by (metis (no_types) \"4.hyps\"(2) \\<open>\\<nexists>i. is_pred_in_set (set_vebt' summary) (high x (deg div 2)) i\\<close> mem_Collect_eq set_vebt'_def set_vebt_finite) }\n            then show ?thesis\n              by blast\n          qed\n          then show ?thesis \n          proof(cases \"x > mi\")\n            case True\n            hence \"vebt_pred (Node (Some (mi, ma)) deg treeList summary) x = Some mi\" \n              by (simp add: \\<open>vebt_pred (Node (Some (mi, ma)) deg treeList summary) x = (if mi < x then Some mi else None)\\<close>)\n            have \"(vebt_member (Node (Some (mi, ma)) deg treeList summary) z  \\<and> z < x \\<and> z > mi) \\<Longrightarrow> False\" for z\n            proof-\n              assume \"vebt_member (Node (Some (mi, ma)) deg treeList summary) z  \\<and> z < x \\<and> z > mi\"\n              hence \"vebt_member ( treeList ! (high z (deg div 2))) (low z (deg div 2))\"\n                using \\<open>x \\<le> ma\\<close> member_inv not_le by blast\n              moreover hence \"high z (deg div 2) < 2^m\" \n                using \"4.hyps\"(4) \\<open>vebt_member (Node (Some (mi, ma)) deg treeList summary) z \\<and> z < x \\<and> mi < z\\<close> \\<open>x \\<le> ma\\<close> member_inv by fastforce\n              moreover hence \"invar_vebt (treeList ! (high z (deg div 2))) n\" using 4(1)\n                by (simp add: \"4.hyps\"(4))\n              ultimately have \"vebt_member summary (high z (deg div 2))\" using 4(7) \n                using \"4.hyps\"(2) both_member_options_equiv_member by blast\n              have \"(high z (deg div 2)) \\<le> ?h\" \n                by (simp add: \\<open>vebt_member (Node (Some (mi, ma)) deg treeList summary) z \\<and> z < x \\<and> mi < z\\<close> div_le_mono high_def less_or_eq_imp_le)\n              then show False \n                by (metis \"33\" \\<open>\\<not> (\\<exists>i<high x (deg div 2). vebt_member summary i)\\<close> \\<open>vebt_member (Node (Some (mi, ma)) deg treeList summary) z \\<and> z < x \\<and> mi < z\\<close> \\<open>vebt_member (treeList ! high z (deg div 2)) (low z (deg div 2))\\<close> \\<open>vebt_member summary (high z (deg div 2))\\<close> bit_concat_def bit_split_inv le_neq_implies_less nat_add_left_cancel_less)\n            qed\n            hence \"is_pred_in_set (set_vebt' ((Node (Some (mi, ma)) deg treeList summary))) x mi\" \n              by (metis VEBT_Member.vebt_member.simps(5) True \\<open>2 \\<le> deg\\<close> add_2_eq_Suc le_add_diff_inverse le_less_linear pred_member)\n            then show ?thesis \n              by (metis \\<open>vebt_pred (Node (Some (mi, ma)) deg treeList summary) x = Some mi\\<close> \\<open>x \\<le> ma\\<close> option.sel leD member_inv pred_member)\n          next\n            case False\n            hence \"vebt_pred (Node (Some (mi, ma)) deg treeList summary) x = None\"\n              by (simp add: \"2\" True)\n            then show ?thesis \n              by (metis (full_types) False less_trans member_inv option.distinct(1) pred_max pred_member)\n          qed\n        next\n          case False\n          hence fst:\"vebt_pred (Node (Some (mi, ma)) deg treeList summary) x =\n                    Some (2^(deg div 2)) *\\<^sub>o ?pr +\\<^sub>o vebt_maxt (treeList ! the ?pr)\"\n            using \"2\" by presburger \n          obtain pr where \"?pr = Some pr\" \n            using False by blast\n          hence \"is_pred_in_set (set_vebt' summary) ?h pr\"\n            using \"4.hyps\"(3) by blast\n          hence \"vebt_member summary pr\"\n            using pred_member by blast\n          hence \"both_member_options summary pr\" \n            using \"4.hyps\"(2) both_member_options_equiv_member by auto\n          hence \"pr < 2^m\" \n            using \"4.hyps\"(2) \\<open>vebt_member summary pr\\<close> member_bound by blast\n          hence \"\\<exists> maxy. both_member_options (treeList ! pr) maxy\" \n            using \"4.hyps\"(7) \\<open>both_member_options summary pr\\<close> by blast\n          hence fgh:\"set_vebt' (treeList ! pr) \\<noteq> {}\"\n            by (metis \"4.hyps\"(1) \"4.hyps\"(2) \"4.hyps\"(4) \\<open>vebt_member summary pr\\<close> empty_Collect_eq member_bound nth_mem set_vebt'_def valid_member_both_member_options)\n          hence \"invar_vebt (treeList ! the ?pr) n\"\n            by (simp add: \"4.hyps\"(1) \"4.hyps\"(4) \\<open>pr < 2 ^ m\\<close> \\<open>vebt_pred summary (high x (deg div 2)) = Some pr\\<close>)\n          then obtain maxy where \"Some maxy = vebt_maxt (treeList ! pr)\" \n            by (metis \\<open>vebt_pred summary (high x (deg div 2)) = Some pr\\<close> fgh option.sel vebt_maxt.elims maxt_corr_help_empty)\n          hence \"Some maxy = vebt_maxt (treeList ! the ?pr)\" \n            by (simp add: \\<open>vebt_pred summary (high x (deg div 2)) = Some pr\\<close>)\n          hence \"max_in_set (set_vebt' (treeList ! the ?pr)) maxy\" \n            using \\<open>invar_vebt (treeList ! the (vebt_pred summary (high x (deg div 2)))) n\\<close> maxt_corr by auto\n          hence scmem:\"vebt_member (treeList ! the ?pr) maxy\"\n            using \\<open>Some maxy = vebt_maxt (treeList ! the (vebt_pred summary (high x (deg div 2))))\\<close> \\<open>invar_vebt (treeList ! the (vebt_pred summary (high x (deg div 2)))) n\\<close> maxt_member by force\n          let ?res =  \"Some (2^(deg div 2)) *\\<^sub>o ?pr +\\<^sub>o vebt_maxt (treeList ! the ?pr)\"\n          obtain res where snd: \"res = the ?res\" by blast\n          hence \"res = 2^(deg div 2) * pr + maxy\" \n            by (metis \\<open>Some maxy = vebt_maxt (treeList ! pr)\\<close> \\<open>vebt_pred summary (high x (deg div 2)) = Some pr\\<close> add_def option.sel mul_def option_shift.simps(3))\n          have \"high res (deg div 2) = pr\" \n            by (metis \\<open>deg div 2 = n\\<close> \\<open>res = 2 ^ (deg div 2) * pr + maxy\\<close> \\<open>invar_vebt (treeList ! the ?pr) n\\<close> high_inv member_bound mult.commute scmem)\n          hence \"res < x\" \n            by (metis \\<open>is_pred_in_set (set_vebt' summary) (high x (deg div 2)) pr\\<close> div_le_mono high_def pred_member verit_comp_simplify1(3))\n          have \"both_member_options (treeList ! (high res (deg div 2))) (low res (deg div 2))\"\n            by (metis \\<open>deg div 2 = n\\<close> \\<open>high res (deg div 2) = pr\\<close> \\<open>vebt_pred summary (high x (deg div 2)) = Some pr\\<close> \\<open>res = 2 ^ (deg div 2) * pr + maxy\\<close> \\<open>invar_vebt (treeList ! the (vebt_pred summary (high x (deg div 2)))) n\\<close> both_member_options_equiv_member option.sel low_inv member_bound mult.commute scmem)\n          have \"both_member_options (Node (Some (mi, ma)) deg treeList summary) res\" \n            by (metis \"4.hyps\"(2) \"4.hyps\"(4) \"4.hyps\"(6) \\<open>1 \\<le> n\\<close> \\<open>both_member_options (treeList ! high res (deg div 2)) (low res (deg div 2))\\<close> \\<open>high res (deg div 2) = pr\\<close> \\<open>vebt_member summary pr\\<close> both_member_options_from_chilf_to_complete_tree member_bound trans_le_add1) \n          hence \"vebt_member (Node (Some (mi, ma)) deg treeList summary) res\" \n            using thisvalid valid_member_both_member_options by auto\n          hence \"res > mi\"\n            by (metis \"4.hyps\"(11) \\<open>both_member_options (treeList ! high res (deg div 2)) (low res (deg div 2))\\<close> \\<open>deg div 2 = n\\<close> \\<open>high res (deg div 2) = pr\\<close> \\<open>pr < 2 ^ m\\<close> \\<open>res < x\\<close> \\<open>x \\<le> ma\\<close> less_le_trans member_inv)\n          hence \"res < ma\"\n            using \\<open>res < x\\<close> \\<open>x \\<le> ma\\<close> less_le_trans by blast\n          have \"(vebt_member (Node (Some (mi, ma)) deg treeList summary) z \\<and> z < x) \\<Longrightarrow> z \\<le> res\" for z\n          proof-\n            fix z\n            assume \"vebt_member (Node (Some (mi, ma)) deg treeList summary) z \\<and> z < x\"\n            hence 20: \"z = mi \\<or> z = ma \\<or> (high z (deg div 2) < length treeList \n                                    \\<and> vebt_member ( treeList ! (high z (deg div 2))) (low z (deg div 2)))\" using\n              vebt_member.simps(5)[of mi ma \"deg-2\" treeList summary z] \n              using member_inv by blast\n            have \"z \\<noteq> ma\" \n              using \\<open>vebt_member (Node (Some (mi, ma)) deg treeList summary) z \\<and> z < x\\<close> \\<open>x \\<le> ma\\<close> leD by blast\n            hence \"mi \\<noteq> ma\" \n              by (metis \\<open>mi < res\\<close> \\<open>res < x\\<close> \\<open>x \\<le> ma\\<close> leD less_trans)\n            hence \"z < 2^deg\" \n              using \\<open>vebt_member (Node (Some (mi, ma)) deg treeList summary) z \\<and> z < x\\<close> member_bound thisvalid by blast\n            hence abc:\"invar_vebt (treeList ! (high z (deg div 2))) n\" \n              by (metis \"4.hyps\"(1) \"4.hyps\"(2) \"4.hyps\"(5) \"4.hyps\"(6) \\<open>deg div 2 = n\\<close> \\<open>z < 2 ^ deg\\<close> \\<open>length treeList = 2 ^ n\\<close> deg_not_0 exp_split_high_low(1) in_set_member inthall)\n            then show \"z \\<le> res\"\n            proof(cases \"z = mi\")\n              case True\n              then show ?thesis\n                using \\<open>mi < res\\<close> by auto\n            next\n              case False\n              hence abe:\"vebt_member( treeList ! (high z (deg div 2))) (low z (deg div 2))\" \n                using \"20\" \\<open>z \\<noteq> ma\\<close> by blast\n              hence abh:\"vebt_member summary (high z (deg div 2))\"\n                by (metis \"20\" \"4.hyps\"(2) \"4.hyps\"(4) \"4.hyps\"(7) False \\<open>vebt_member (Node (Some (mi, ma)) deg treeList summary) z \\<and> z < x\\<close> \\<open>x \\<le> ma\\<close> abc both_member_options_equiv_member not_le)\n              have aaa:\"(high z (deg div 2)) = (high x (deg div 2)) \\<Longrightarrow> vebt_member (treeList ! ?h) (low z (deg div 2))\"\n                using abe by auto\n              have \"high z(deg div 2) > pr \\<Longrightarrow> False\" \n              proof-\n                assume \"high z(deg div 2) > pr\"\n                hence \"vebt_member summary (high z(deg div 2))\" \n                  using abh by blast\n                have aaaa:\"?h \\<le> high z(deg div 2)\"\n                  by (meson \\<open>is_pred_in_set (set_vebt' summary) (high x (deg div 2)) pr\\<close> \\<open>pr < high z (deg div 2)\\<close> abh leD not_le_imp_less pred_member)\n                have bbbb:\"?h \\<ge> high z(deg div 2)\" \n                  by (simp add: \\<open>vebt_member (Node (Some (mi, ma)) deg treeList summary) z \\<and> z < x\\<close> div_le_mono dual_order.strict_implies_order high_def)\n                hence \"?h = high z (deg div 2)\" \n                  using aaaa eq_iff by blast\n                hence \"vebt_member (treeList ! ?h) (low z (deg div 2))\" \n                  using aaa by linarith\n                hence \"(low z (deg div 2)) < ?l\" \n                  by (metis \\<open>high x (deg div 2) = high z (deg div 2)\\<close> \\<open>vebt_member (Node (Some (mi, ma)) deg treeList summary) z \\<and> z < x\\<close> add_le_cancel_left div_mult_mod_eq high_def less_le low_def)\n                then show False \n                  using \"33\" \\<open>vebt_member (treeList ! high x (deg div 2)) (low z (deg div 2))\\<close> by blast\n              qed\n              hence \"high z(deg div 2) \\<le> pr\" \n                using not_less by blast\n              then show \" z \\<le> res\"\n              proof(cases \"high z(deg div 2) = pr\")\n                case True\n                hence \"vebt_member (treeList ! (high z(deg div 2))) (low z (deg div 2))\" \n                  using abe by blast\n                have \"low z (deg div 2) \\<le> maxy\"\n                  using True \\<open>Some maxy = vebt_maxt (treeList ! pr)\\<close> abc abe maxt_corr_help by auto\n                hence \"z \\<le> res\"\n                  by (metis True \\<open>res = 2 ^ (deg div 2) * pr + maxy\\<close> add_le_cancel_left div_mult_mod_eq high_def low_def mult.commute)\n                then show ?thesis by simp\n              next\n                case False\n                hence \"high z(deg div 2) < pr\" \n                  by (simp add: \\<open>high z (deg div 2) \\<le> pr\\<close> less_le)\n                then show ?thesis\n                  by (metis \\<open>high res (deg div 2) = pr\\<close> div_le_mono high_def leD linear)\n              qed\n            qed\n          qed\n          hence \"is_pred_in_set (set_vebt' (Node (Some (mi, ma)) deg treeList summary)) x res\"\n            using \\<open>vebt_member (Node (Some (mi, ma)) deg treeList summary) res\\<close> \\<open>res < x\\<close> pred_member by presburger \n          then show ?thesis using fst snd\n            by (metis \\<open>Some maxy = vebt_maxt (treeList ! the (vebt_pred summary (high x (deg div 2))))\\<close> \\<open>vebt_pred summary (high x (deg div 2)) = Some pr\\<close> \\<open>res = 2 ^ (deg div 2) * pr + maxy\\<close> add_shift dual_order.eq_iff mul_shift pred_member)\n        qed\n      qed\n    next\n      case False\n      then show ?thesis \n        by (metis \"4.hyps\"(10) \"4.hyps\"(5) \"4.hyps\"(6) \\<open>1 \\<le> n\\<close> \\<open>deg div 2 = n\\<close> \\<open>length treeList = 2 ^ n\\<close> \\<open>x \\<le> ma\\<close> exp_split_high_low(1) le_less_trans le_neq_implies_less not_less not_less_zero zero_neq_one)\n    qed\n  qed\nnext\n  case (5 treeList n summary m deg mi ma)\n  hence \"Suc n = m\"  and \"deg = n + m\" and \"length treeList = 2^m \\<and> invar_vebt summary m\"\n    by blast + \n  hence \"n \\<ge> 1\" \n    using \"5.hyps\"(1) set_n_deg_not_0 by blast \n  hence \"deg \\<ge> 2\" \n    by (simp add: \"5.hyps\"(5) \"5.hyps\"(6))    \n  hence \"deg div 2 =n\" \n    by (simp add: \"5.hyps\"(5) \"5.hyps\"(6))\n  moreover hence thisvalid:\"invar_vebt (Node (Some (mi, ma)) deg treeList summary) deg\" \n    using 5 invar_vebt.intros(5)[of treeList n summary m]  by blast\n  ultimately have \"deg div 2 =n\" by simp\n  then show ?case\n  proof(cases \"x > ma\")\n    case True\n    hence 0: \"vebt_pred (Node (Some (mi, ma)) deg treeList summary) x = Some ma\" \n      by (simp add: \\<open>2 \\<le> deg\\<close> pred_max)\n    have 1:\"ma = the (vebt_maxt (Node (Some (mi, ma)) deg treeList summary))\" by simp\n    hence \"ma \\<in> set_vebt' (Node (Some (mi, ma)) deg treeList summary)\"\n      by (metis VEBT_Member.vebt_member.simps(5) \\<open>2 \\<le> deg\\<close> add_numeral_left arith_simps(1) le_add_diff_inverse mem_Collect_eq numerals(1) plus_1_eq_Suc set_vebt'_def)\n    hence 2:\"y \\<in> set_vebt' (Node (Some (mi, ma)) deg treeList summary) \\<Longrightarrow> y \\<le> x\" for y\n      using \"5.hyps\"(9) True member_inv set_vebt'_def by fastforce\n    hence 3: \"y \\<in> set_vebt' (Node (Some (mi, ma)) deg treeList summary) \\<Longrightarrow> (y < ma \\<Longrightarrow> y \\<le> x)\" for y by blast\n    hence 4: \"\\<forall> y \\<in> set_vebt' (Node (Some (mi, ma)) deg treeList summary). y < ma \\<longrightarrow> y \\<le> x\" by blast\n    hence \"is_pred_in_set (set_vebt' (Node (Some (mi, ma)) deg treeList summary)) x ma\" \n      by (metis \"5.hyps\"(9) True \\<open>ma \\<in> set_vebt' (Node (Some (mi, ma)) deg treeList summary)\\<close> less_or_eq_imp_le mem_Collect_eq member_inv pred_member set_vebt'_def)\n    then show ?thesis \n      by (metis \"0\" option.sel leD le_less_Suc_eq not_less_eq pred_member)\n  next\n    case False\n    hence \"x \\<le> ma\"by simp  \n    then show ?thesis \n    proof(cases \"high x (deg div 2)< length treeList \")\n      case True\n      hence \"high x n < 2^m \\<and> low x n < 2^n\"\n        by (simp add: \\<open>deg div 2 = n\\<close> \\<open>length treeList = 2 ^ m\\<close> low_def)\n      let ?l = \"low x (deg div 2)\" \n      let ?h = \"high x (deg div 2)\"\n      let ?minlow = \"vebt_mint (treeList ! ?h)\"\n      let ?pr = \"vebt_pred summary ?h\"\n      have 1:\"vebt_pred (Node (Some (mi, ma)) deg treeList summary) x = \n                           (if ?minlow \\<noteq> None \\<and> (Some ?l >\\<^sub>o  ?minlow) then \n                                                    Some (2^(deg div 2)) *\\<^sub>o Some ?h +\\<^sub>o vebt_pred (treeList ! ?h) ?l\n                             else let pr = vebt_pred summary ?h in\n                             if pr = None then (if x > mi then Some mi else None)\n                             else Some (2^(deg div 2)) *\\<^sub>o pr +\\<^sub>o vebt_maxt (treeList ! the pr) )\"\n        by (smt True \\<open>2 \\<le> deg\\<close> \\<open>x \\<le> ma\\<close> pred_less_length_list)     \n      then show ?thesis \n      proof(cases \"?minlow \\<noteq> None \\<and> (Some ?l >\\<^sub>o  ?minlow)\")\n        case True\n        then obtain minl where 00:\"(Some minl = ?minlow) \\<and> ?l > minl\" by auto\n        have 01:\"invar_vebt ((treeList ! ?h)) n \\<and> (treeList ! ?h) \\<in> set treeList \"\n          by (metis \"5.hyps\"(1) \\<open>deg div 2 = n\\<close> \\<open>high x n < 2 ^ m \\<and> low x n < 2 ^ n\\<close> \\<open>length treeList = 2 ^ m \\<and> invar_vebt summary m\\<close> inthall member_def)\n        have  02:\"vebt_member ((treeList ! ?h)) minl\" \n          using \"00\" \"01\" mint_member by auto\n        hence 03: \"\\<exists> y. y < ?l \\<and> vebt_member ((treeList ! ?h)) y\"\n          using \"00\" by blast \n        hence afinite: \"finite (set_vebt' (treeList ! ?h)) \" \n          using \"01\" set_vebt_finite by blast\n        then obtain predy where 04:\"is_pred_in_set (set_vebt' (treeList ! ?h)) ?l predy\"\n          using \"00\" \"01\" mint_corr obtain_set_pred by fastforce\n        hence 05:\"Some predy =  vebt_pred (treeList ! ?h) ?l\"  using 5(1) 01 by force\n        hence \"vebt_pred (Node (Some (mi, ma)) deg treeList summary) x  =  Some (2^(deg div 2)*  ?h + predy) \"\n          by (metis \"1\" True add_def mul_def option_shift.simps(3))\n        hence 06: \"predy \\<in> set_vebt' (treeList ! ?h)\" \n          using \"04\" is_pred_in_set_def by blast\n        hence 07: \"predy < 2^(deg div 2) \\<and> ?h < 2^(deg div 2 +1) \\<and> deg div 2 + deg div 2 +1 = deg\"\n          using \"04\" \"5.hyps\"(5) \"5.hyps\"(6) \\<open>high x n < 2 ^ m \\<and> low x n < 2 ^ n\\<close> pred_member by force\n        let ?y = \"2^(deg div 2)*  ?h + predy\"\n        have 08: \"vebt_member (treeList ! ?h) predy\"\n          using \"06\" set_vebt'_def by auto\n        hence 09: \"both_member_options (treeList ! ?h) predy\"\n          using \"01\" both_member_options_equiv_member by blast\n        have 10: \"high ?y (deg div 2) = ?h \\<and> low ?y (deg div 2) = predy\"\n          by (simp add: \"07\" high_inv low_inv mult.commute)\n        hence 14:\"both_member_options (Node (Some (mi, ma)) deg treeList summary) ?y\"\n          using \"07\" \"09\" \"5.hyps\"(4) \\<open>deg div 2 = n\\<close> \\<open>high x n < 2 ^ m \\<and> low x n < 2 ^ n\\<close> both_member_options_from_chilf_to_complete_tree by auto\n        have 15: \"vebt_member (Node (Some (mi, ma)) deg treeList summary) ?y\"\n          using \"14\" thisvalid valid_member_both_member_options by blast\n        have 16: \"Some ?y = vebt_pred (Node (Some (mi, ma)) deg treeList summary) x\" \n          by (simp add: \\<open>vebt_pred (Node (Some (mi, ma)) deg treeList summary) x = Some (2 ^ (deg div 2) * high x (deg div 2) + predy)\\<close>)\n        have 17: \"x = ?h * 2^(deg div 2) + ?l\"\n          using bit_concat_def bit_split_inv by auto \n        have 18: \"x - ?y =   ?h * 2^(deg div 2) + ?l -?h * 2^(deg div 2) - predy \" \n          by (metis \"17\" diff_diff_add mult.commute)\n        hence 19: \"?y < x\" \n          using \"04\" \"17\" mult.commute nat_add_left_cancel_less pred_member by fastforce\n        have 20: \"z < x \\<Longrightarrow> vebt_member (Node (Some (mi, ma)) deg treeList summary) z \\<Longrightarrow> z\\<le> ?y \" for z \n        proof-\n          assume \"z < x\" and \"vebt_member (Node (Some (mi, ma)) deg treeList summary) z\"\n          hence \"high z (deg div 2) \\<le> high x (deg div 2)\" \n            by (simp add: div_le_mono high_def)\n          then show ?thesis \n          proof(cases \"high z (deg div 2) = high x (deg div 2)\")\n            case True\n            hence 0000: \"high z (deg div 2) = high x (deg div 2)\" by simp\n            then show ?thesis\n            proof(cases \"z = mi\")\n              case True\n              then show ?thesis \n                by (metis \"15\" \"5.hyps\"(9) add.left_neutral le_add2 less_imp_le_nat member_inv)\n            next\n              case False    \n              hence ad:\"vebt_member (treeList ! ?h) (low z (deg div 2))\" \n                using vebt_member.simps(5)[of mi ma \"deg-2\" treeList summary z]\n                by (metis True \\<open>vebt_member (Node (Some (mi, ma)) deg treeList summary) z\\<close> \\<open>x \\<le> ma\\<close> \\<open>z < x\\<close> leD member_inv)\n              have \"is_pred_in_set (set_vebt' (treeList ! ?h)) ?l predy\" \n                using \"04\" by blast\n              have \"low z (deg div 2) < ?l\" \n                by (metis (full_types) True \\<open>z < x\\<close> bit_concat_def bit_split_inv nat_add_left_cancel_less)\n              hence \"predy \\<ge> low z (deg div 2)\" using 04 ad unfolding is_pred_in_set_def\n                by (simp add: set_vebt'_def)\n              hence \"?y \\<ge> z\" \n                by (smt True bit_concat_def bit_split_inv diff_add_inverse diff_diff_add diff_is_0_eq mult.commute)\n              then show ?thesis by blast\n            qed\n          next\n            case False\n            hence \"high z (deg div 2) < high ?y (deg div 2)\"\n              using \"10\" \\<open>high z (deg div 2) \\<le> high x (deg div 2)\\<close> by linarith\n            then show ?thesis \n              by (metis div_le_mono high_def nat_le_linear not_le)\n          qed\n        qed\n        hence \"is_pred_in_set (set_vebt'(Node (Some (mi, ma)) deg treeList summary)) x ?y\" \n          by (simp add: \"15\" \"19\" pred_member)\n        then show ?thesis using 16\n          by (metis eq_iff option.inject pred_member)\n      next\n        case False\n        hence i1:\"?minlow =  None \\<or> \\<not> (Some ?l >\\<^sub>o  ?minlow)\" by simp\n        hence 2: \"vebt_pred (Node (Some (mi, ma)) deg treeList summary) x =  (\n                            if ?pr = None then (if x > mi \n                                                then Some mi \n                                                else None)\n                             else Some (2^(deg div 2)) *\\<^sub>o ?pr +\\<^sub>o vebt_maxt (treeList ! the ?pr))\" \n          using \"1\" by auto\n        have \" invar_vebt (treeList ! ?h) n\"\n          by (metis \"5\"(1) True inthall member_def)\n        hence 33:\"\\<nexists> u. vebt_member (treeList ! ?h) u \\<and> u < ?l\"\n        proof(cases \"?minlow = None\")\n          case True\n          then show ?thesis using mint_corr_help_empty[of \"treeList ! ?h\" n] \n            by (simp add: \\<open>invar_vebt (treeList ! high x (deg div 2)) n\\<close> set_vebt'_def)\n        next\n          case False\n          obtain minilow where \"?minlow =Some minilow\" \n            using False by blast\n          hence \"minilow \\<ge> ?l\" \n            using \"i1\" by auto\n          then show ?thesis\n            by (meson \\<open>vebt_mint (treeList ! high x (deg div 2)) = Some minilow\\<close> \\<open>invar_vebt (treeList ! high x (deg div 2)) n\\<close> leD less_le_trans mint_corr_help)\n        qed\n        then show ?thesis \n        proof(cases \"?pr= None\")\n          case True\n          hence \"vebt_pred (Node (Some (mi, ma)) deg treeList summary) x =  (if x > mi then Some mi else  None)\" \n            by (simp add: \"2\")\n          hence \"\\<nexists> i. is_pred_in_set (set_vebt' summary) ?h i\"\n            using \"5.hyps\"(3) True by force\n          hence \"\\<nexists> i. i < ?h \\<and> vebt_member summary i \" using pred_none_empty[of \"set_vebt' summary\" ?h] \n          proof -\n            { fix nn :: nat\n              have \"\\<forall>n. ((is_pred_in_set (Collect (vebt_member summary)) (high x (deg div 2)) esk1_0 \\<or> infinite (Collect (vebt_member summary))) \\<or> n \\<notin> Collect (vebt_member summary)) \\<or> \\<not> n < high x (deg div 2)\"\n                using \\<open>\\<nexists>i. is_pred_in_set (set_vebt' summary) (high x (deg div 2)) i\\<close> pred_none_empty set_vebt'_def by auto\n              then have \"\\<not> nn < high x (deg div 2) \\<or> \\<not> vebt_member summary nn\"\n                by (metis (no_types) \"5.hyps\"(2) \\<open>\\<nexists>i. is_pred_in_set (set_vebt' summary) (high x (deg div 2)) i\\<close> mem_Collect_eq set_vebt'_def set_vebt_finite) }\n            then show ?thesis\n              by blast\n          qed\n          then show ?thesis \n          proof(cases \"x > mi\")\n            case True\n            hence \"vebt_pred (Node (Some (mi, ma)) deg treeList summary) x = Some mi\" \n              by (simp add: \\<open>vebt_pred (Node (Some (mi, ma)) deg treeList summary) x = (if mi < x then Some mi else None)\\<close>)\n            have \"(vebt_member (Node (Some (mi, ma)) deg treeList summary) z  \\<and> z < x \\<and> z > mi) \\<Longrightarrow> False\" for z\n            proof-\n              assume \"vebt_member (Node (Some (mi, ma)) deg treeList summary) z  \\<and> z < x \\<and> z > mi\"\n              hence \"vebt_member ( treeList ! (high z (deg div 2))) (low z (deg div 2))\"\n                using \\<open>x \\<le> ma\\<close> member_inv not_le by blast\n              moreover hence \"high z (deg div 2) < 2^m\" \n                using \"5.hyps\"(4) \\<open>vebt_member (Node (Some (mi, ma)) deg treeList summary) z \\<and> z < x \\<and> mi < z\\<close> \\<open>x \\<le> ma\\<close> member_inv by fastforce\n              moreover hence \"invar_vebt (treeList ! (high z (deg div 2))) n\" using 5(1)\n                by (simp add: \"5.hyps\"(4))\n              ultimately have \"vebt_member summary (high z (deg div 2))\" using 5(7) \n                using \"5.hyps\"(2) both_member_options_equiv_member by blast\n              have \"(high z (deg div 2)) \\<le> ?h\" \n                by (simp add: \\<open>vebt_member (Node (Some (mi, ma)) deg treeList summary) z \\<and> z < x \\<and> mi < z\\<close> div_le_mono high_def less_or_eq_imp_le)\n              then show False \n                by (metis \"33\" \\<open>\\<not> (\\<exists>i<high x (deg div 2). vebt_member summary i)\\<close> \\<open>vebt_member (Node (Some (mi, ma)) deg treeList summary) z \\<and> z < x \\<and> mi < z\\<close> \\<open>vebt_member (treeList ! high z (deg div 2)) (low z (deg div 2))\\<close> \\<open>vebt_member summary (high z (deg div 2))\\<close> bit_concat_def bit_split_inv le_neq_implies_less nat_add_left_cancel_less)\n            qed\n            hence \"is_pred_in_set (set_vebt' ((Node (Some (mi, ma)) deg treeList summary))) x mi\" \n              by (metis VEBT_Member.vebt_member.simps(5) True \\<open>2 \\<le> deg\\<close> add_2_eq_Suc le_add_diff_inverse le_less_linear pred_member)\n            then show ?thesis \n              by (metis \\<open>vebt_pred (Node (Some (mi, ma)) deg treeList summary) x = Some mi\\<close> \\<open>x \\<le> ma\\<close> option.sel leD member_inv pred_member)\n          next\n            case False\n            hence \"vebt_pred (Node (Some (mi, ma)) deg treeList summary) x = None\"\n              by (simp add: \"2\" True)\n            then show ?thesis \n              by (metis (full_types) False less_trans member_inv option.distinct(1) pred_max pred_member)\n          qed\n        next\n          case False\n          hence fst:\"vebt_pred (Node (Some (mi, ma)) deg treeList summary) x =\n                    Some (2^(deg div 2)) *\\<^sub>o ?pr +\\<^sub>o vebt_maxt (treeList ! the ?pr)\"\n            using \"2\" by presburger \n          obtain pr where \"?pr = Some pr\" \n            using False by blast\n          hence \"is_pred_in_set (set_vebt' summary) ?h pr\"\n            using \"5.hyps\"(3) by blast\n          hence \"vebt_member summary pr\"\n            using pred_member by blast\n          hence \"both_member_options summary pr\" \n            using \"5.hyps\"(2) both_member_options_equiv_member by auto\n          hence \"pr < 2^m\" \n            using \"5.hyps\"(2) \\<open>vebt_member summary pr\\<close> member_bound by blast\n          hence \"\\<exists> maxy. both_member_options (treeList ! pr) maxy\" \n            using \"5.hyps\"(7) \\<open>both_member_options summary pr\\<close> by blast\n          hence fgh:\"set_vebt' (treeList ! pr) \\<noteq> {}\"\n            by (metis \"5.hyps\"(1) \"5.hyps\"(4) Collect_empty_eq \\<open>pr < 2 ^ m\\<close> nth_mem set_vebt'_def valid_member_both_member_options)\n          hence \"invar_vebt (treeList ! the ?pr) n\"\n            by (simp add: \"5.hyps\"(1) \"5.hyps\"(4) \\<open>pr < 2 ^ m\\<close> \\<open>vebt_pred summary (high x (deg div 2)) = Some pr\\<close>)\n          then obtain maxy where \"Some maxy = vebt_maxt (treeList ! pr)\" \n            by (metis \\<open>vebt_pred summary (high x (deg div 2)) = Some pr\\<close> fgh option.sel vebt_maxt.elims maxt_corr_help_empty)\n          hence \"Some maxy = vebt_maxt (treeList ! the ?pr)\" \n            by (simp add: \\<open>vebt_pred summary (high x (deg div 2)) = Some pr\\<close>)\n          hence \"max_in_set (set_vebt' (treeList ! the ?pr)) maxy\" \n            using \\<open>invar_vebt (treeList ! the (vebt_pred summary (high x (deg div 2)))) n\\<close> maxt_corr by auto\n          hence scmem:\"vebt_member (treeList ! the ?pr) maxy\"\n            using \\<open>Some maxy = vebt_maxt (treeList ! the (vebt_pred summary (high x (deg div 2))))\\<close> \\<open>invar_vebt (treeList ! the (vebt_pred summary (high x (deg div 2)))) n\\<close> maxt_member by force\n          let ?res =  \"Some (2^(deg div 2)) *\\<^sub>o ?pr +\\<^sub>o vebt_maxt (treeList ! the ?pr)\"\n          obtain res where snd: \"res = the ?res\" by blast\n          hence \"res = 2^(deg div 2) * pr + maxy\" \n            by (metis \\<open>Some maxy = vebt_maxt (treeList ! pr)\\<close> \\<open>vebt_pred summary (high x (deg div 2)) = Some pr\\<close> add_def option.sel mul_def option_shift.simps(3))\n          have \"high res (deg div 2) = pr\" \n            by (metis \\<open>deg div 2 = n\\<close> \\<open>res = 2 ^ (deg div 2) * pr + maxy\\<close> \\<open>invar_vebt (treeList ! the ?pr) n\\<close> high_inv member_bound mult.commute scmem)\n          hence \"res < x\" \n            by (metis \\<open>is_pred_in_set (set_vebt' summary) (high x (deg div 2)) pr\\<close> div_le_mono high_def pred_member verit_comp_simplify1(3))\n          have \"both_member_options (treeList ! (high res (deg div 2))) (low res (deg div 2))\"\n            by (metis \\<open>deg div 2 = n\\<close> \\<open>high res (deg div 2) = pr\\<close> \\<open>vebt_pred summary (high x (deg div 2)) = Some pr\\<close> \\<open>res = 2 ^ (deg div 2) * pr + maxy\\<close> \\<open>invar_vebt (treeList ! the (vebt_pred summary (high x (deg div 2)))) n\\<close> both_member_options_equiv_member option.sel low_inv member_bound mult.commute scmem)\n          have \"both_member_options (Node (Some (mi, ma)) deg treeList summary) res\" \n            by (metis \"5.hyps\"(2) \"5.hyps\"(4) \"5.hyps\"(6) \\<open>1 \\<le> n\\<close> \\<open>both_member_options (treeList ! high res (deg div 2)) (low res (deg div 2))\\<close> \\<open>high res (deg div 2) = pr\\<close> \\<open>vebt_member summary pr\\<close> both_member_options_from_chilf_to_complete_tree member_bound trans_le_add1) \n          hence \"vebt_member (Node (Some (mi, ma)) deg treeList summary) res\" \n            using thisvalid valid_member_both_member_options by auto\n          hence \"res > mi\"\n            by (metis \"5.hyps\"(11) \\<open>both_member_options (treeList ! high res (deg div 2)) (low res (deg div 2))\\<close> \\<open>deg div 2 = n\\<close> \\<open>high res (deg div 2) = pr\\<close> \\<open>pr < 2 ^ m\\<close> \\<open>res < x\\<close> \\<open>x \\<le> ma\\<close> less_le_trans member_inv)\n          hence \"res < ma\"\n            using \\<open>res < x\\<close> \\<open>x \\<le> ma\\<close> less_le_trans by blast\n          have \"(vebt_member (Node (Some (mi, ma)) deg treeList summary) z \\<and> z < x) \\<Longrightarrow> z \\<le> res\" for z\n          proof-\n            fix z\n            assume \"vebt_member (Node (Some (mi, ma)) deg treeList summary) z \\<and> z < x\"\n            hence 20: \"z = mi \\<or> z = ma \\<or> (high z (deg div 2) < length treeList \n                                    \\<and> vebt_member ( treeList ! (high z (deg div 2))) (low z (deg div 2)))\" using\n              vebt_member.simps(5)[of mi ma \"deg-2\" treeList summary z] \n              using member_inv by blast\n            have \"z \\<noteq> ma\" \n              using \\<open>vebt_member (Node (Some (mi, ma)) deg treeList summary) z \\<and> z < x\\<close> \\<open>x \\<le> ma\\<close> leD by blast\n            hence \"mi \\<noteq> ma\" \n              by (metis \\<open>mi < res\\<close> \\<open>res < x\\<close> \\<open>x \\<le> ma\\<close> leD less_trans)\n            hence \"z < 2^deg\" \n              using \\<open>vebt_member (Node (Some (mi, ma)) deg treeList summary) z \\<and> z < x\\<close> member_bound thisvalid by blast\n            hence \"(high z (deg div 2)) <2^m\" \n              by (metis \"5.hyps\"(5) \"5.hyps\"(6) \\<open>1 \\<le> n\\<close> \\<open>deg div 2 = n\\<close> exp_split_high_low(1) less_le_trans numeral_One zero_less_Suc zero_less_numeral)\n            hence abc:\"invar_vebt (treeList ! (high z (deg div 2))) n\" \n              by (simp add: \"5.hyps\"(1) \"5.hyps\"(4))\n            then show \"z \\<le> res\"\n            proof(cases \"z = mi\")\n              case True\n              then show ?thesis\n                using \\<open>mi < res\\<close> by auto\n            next\n              case False\n              hence abe:\"vebt_member( treeList ! (high z (deg div 2))) (low z (deg div 2))\" \n                using \"20\" \\<open>z \\<noteq> ma\\<close> by blast\n              hence abh:\"vebt_member summary (high z (deg div 2))\"\n                using \"5.hyps\"(7) \\<open>high z (deg div 2) < 2 ^ m\\<close> \\<open>length treeList = 2 ^ m \\<and> invar_vebt summary m\\<close> abc both_member_options_equiv_member by blast\n              have aaa:\"(high z (deg div 2)) = (high x (deg div 2)) \\<Longrightarrow> vebt_member (treeList ! ?h) (low z (deg div 2))\"\n                using abe by auto\n              have \"high z(deg div 2) > pr \\<Longrightarrow> False\" \n              proof-\n                assume \"high z(deg div 2) > pr\"\n                hence \"vebt_member summary (high z(deg div 2))\" \n                  using abh by blast\n                have aaaa:\"?h \\<le> high z(deg div 2)\"\n                  by (meson \\<open>is_pred_in_set (set_vebt' summary) (high x (deg div 2)) pr\\<close> \\<open>pr < high z (deg div 2)\\<close> abh leD not_le_imp_less pred_member)\n                have bbbb:\"?h \\<ge> high z(deg div 2)\" \n                  by (simp add: \\<open>vebt_member (Node (Some (mi, ma)) deg treeList summary) z \\<and> z < x\\<close> div_le_mono dual_order.strict_implies_order high_def)\n                hence \"?h = high z (deg div 2)\" \n                  using aaaa eq_iff by blast\n                hence \"vebt_member (treeList ! ?h) (low z (deg div 2))\" \n                  using aaa by linarith\n                hence \"(low z (deg div 2)) < ?l\" \n                  by (metis \\<open>high x (deg div 2) = high z (deg div 2)\\<close> \\<open>vebt_member (Node (Some (mi, ma)) deg treeList summary) z \\<and> z < x\\<close> add_le_cancel_left div_mult_mod_eq high_def less_le low_def)\n                then show False \n                  using \"33\" \\<open>vebt_member (treeList ! high x (deg div 2)) (low z (deg div 2))\\<close> by blast\n              qed\n              hence \"high z(deg div 2) \\<le> pr\" \n                using not_less by blast\n              then show \" z \\<le> res\"\n              proof(cases \"high z(deg div 2) = pr\")\n                case True\n                hence \"vebt_member (treeList ! (high z(deg div 2))) (low z (deg div 2))\" \n                  using abe by blast\n                have \"low z (deg div 2) \\<le> maxy\"\n                  using True \\<open>Some maxy = vebt_maxt (treeList ! pr)\\<close> abc abe maxt_corr_help by auto\n                hence \"z \\<le> res\"\n                  by (metis True \\<open>res = 2 ^ (deg div 2) * pr + maxy\\<close> add_le_cancel_left div_mult_mod_eq high_def low_def mult.commute)\n                then show ?thesis by simp\n              next\n                case False\n                hence \"high z(deg div 2) < pr\" \n                  by (simp add: \\<open>high z (deg div 2) \\<le> pr\\<close> less_le)\n                then show ?thesis\n                  by (metis \\<open>high res (deg div 2) = pr\\<close> div_le_mono high_def leD linear)\n              qed\n            qed\n          qed\n          hence \"is_pred_in_set (set_vebt' (Node (Some (mi, ma)) deg treeList summary)) x res\"\n            using \\<open>vebt_member (Node (Some (mi, ma)) deg treeList summary) res\\<close> \\<open>res < x\\<close> pred_member by presburger \n          then show ?thesis using fst snd\n            by (metis \\<open>Some maxy = vebt_maxt (treeList ! the (vebt_pred summary (high x (deg div 2))))\\<close> \\<open>vebt_pred summary (high x (deg div 2)) = Some pr\\<close> \\<open>res = 2 ^ (deg div 2) * pr + maxy\\<close> add_shift dual_order.eq_iff mul_shift pred_member)\n        qed\n      qed\n    next\n      case False\n      then show ?thesis\n        by (metis \"5.hyps\"(10) \"5.hyps\"(4) \"5.hyps\"(5) \"5.hyps\"(6) \\<open>1 \\<le> n\\<close> \\<open>deg div 2 = n\\<close> \\<open>x \\<le> ma\\<close> exp_split_high_low(1) le_0_eq le_less_trans verit_comp_simplify1(3) zero_less_Suc zero_neq_one)\n    qed\n  qed\nqed\n\ncorollary pred_empty: assumes \"invar_vebt t n \" \n  shows \" (vebt_pred t x = None) = ({y. vebt_member t y \\<and> y < x} = {})\" \nproof\n  show \" vebt_pred t x = None \\<Longrightarrow> {y. vebt_member t y \\<and> x > y} = {}\"\n  proof\n    show \"vebt_pred t x = None \\<Longrightarrow> {y. vebt_member t y \\<and> x > y} \\<subseteq> {}\"\n    proof-\n      assume \"vebt_pred t x = None\"\n      hence \"\\<nexists> y. is_pred_in_set (set_vebt' t) x y\" \n        using assms pred_corr by force\n      moreover hence \"is_pred_in_set (set_vebt' t) x y \\<Longrightarrow> vebt_member t y \\<and> x < y \" for y by auto\n      ultimately show \"{y. vebt_member t y \\<and> x > y} \\<subseteq> {}\"\n        using assms pred_none_empty set_vebt'_def set_vebt_finite by auto\n    qed\n    show \" vebt_pred t x = None \\<Longrightarrow> {} \\<subseteq> {y. vebt_member t y \\<and> x > y}\" by simp\n  qed\n  show \" {y. vebt_member t y \\<and> x > y} = {} \\<Longrightarrow> vebt_pred t x = None\"\n  proof-\n    assume \"{y. vebt_member t y \\<and> x > y} = {} \"\n    hence \"is_pred_in_set (set_vebt' t) x y \\<Longrightarrow> False\" for y \n      using pred_member by auto\n    thus \"vebt_pred t x  = None\"\n      by (meson assms option_shift.elims pred_corr)\n  qed\nqed\n\ntheorem pred_correct: \"invar_vebt t n \\<Longrightarrow> vebt_pred t x = Some sx \\<longleftrightarrow>is_pred_in_set (set_vebt t) x sx\" \n  by (simp add: pred_corr set_vebt_set_vebt'_valid)\n\nlemma helpypredd:\"invar_vebt t n \\<Longrightarrow> vebt_pred t x = Some y \\<Longrightarrow> y < 2^n\" \n  using member_bound pred_corr pred_member by blast\n\nlemma \"invar_vebt t n \\<Longrightarrow> vebt_pred t x = Some y \\<Longrightarrow> y < x\"\n  by (simp add: pred_corr pred_member)\n\nend\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/Van_Emde_Boas_Trees/VEBT_Pred.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505325302033, "lm_q2_score": 0.8080672066194946, "lm_q1q2_score": 0.7310184287885196}}
{"text": "theory GabrielaLimonta\nimports \"~~/src/HOL/IMP/AExp\"\nbegin\n(** Score: 15/10 *)\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/GabrielaLimontaFeedback.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206686206199, "lm_q2_score": 0.8104789063814617, "lm_q1q2_score": 0.7309876771464767}}
{"text": "theory GabrielaLimonta\nimports \"~~/src/HOL/IMP/Star\" Complex_Main\nbegin\n\ntext {* We build on @{theory Complex_Main} instead of @{theory Main} to access\nthe real numbers. *}\n\nsubsection \"Arithmetic Expressions\"\n\ntype_synonym val = real\n\ntype_synonym vname = string\ntype_synonym state = \"vname \\<Rightarrow> val\"\n\ntext_raw{*\\snip{aexptDef}{0}{2}{% *}\ndatatype aexp = Rc real | V vname | Plus aexp aexp | Div aexp aexp\ntext_raw{*}%endsnip*}\n\ninductive taval :: \"aexp \\<Rightarrow> state \\<Rightarrow> val \\<Rightarrow> bool\" where\n\"taval (Rc r) s r\" |\n\"taval (V x) s (s x)\" |\n\"taval a1 s r1 \\<Longrightarrow> taval a2 s r2\n  \\<Longrightarrow> taval (Plus a1 a2) s (r1+r2)\" |\n\"taval a1 s r1 \\<Longrightarrow> taval a2 s r2\n  \\<Longrightarrow> taval (Div a1 a2) s (r1 / r2)\" \n\ninductive_cases [elim!]:\n  \"taval (Rc i) s v\"\n  \"taval (V x) s v\"\n  \"taval (Plus a1 a2) s v\"\n  \"taval (Div a1 a2) s v\"\n\nsubsection \"Boolean Expressions\"\n\ndatatype bexp = Bc bool | Not bexp | And bexp bexp | Less aexp aexp\n\ninductive tbval :: \"bexp \\<Rightarrow> state \\<Rightarrow> bool \\<Rightarrow> bool\" where\n\"tbval (Bc v) s v\" |\n\"tbval b s bv \\<Longrightarrow> tbval (Not b) s (\\<not> bv)\" |\n\"tbval b1 s bv1 \\<Longrightarrow> tbval b2 s bv2 \\<Longrightarrow> tbval (And b1 b2) s (bv1 & bv2)\" |\n\"taval a1 s r1 \\<Longrightarrow> taval a2 s r2 \\<Longrightarrow> tbval (Less a1 a2) s (r1 < r2)\"\n\nsubsection \"Syntax of Commands\"\n(* a copy of Com.thy - keep in sync! *)\n\ndatatype\n  com = SKIP \n      | Assign vname aexp       (\"_ ::= _\" [1000, 61] 61)\n      | Seq    com  com         (\"_;; _\"  [60, 61] 60)\n      | If     bexp com com     (\"IF _ THEN _ ELSE _\"  [0, 0, 61] 61)\n      | While  bexp com         (\"WHILE _ DO _\"  [0, 61] 61)\n\n\nsubsection \"Small-Step Semantics of Commands\"\n\ninductive\n  small_step :: \"(com \\<times> state) \\<Rightarrow> (com \\<times> state) \\<Rightarrow> bool\" (infix \"\\<rightarrow>\" 55)\nwhere\nAssign:  \"taval a s v \\<Longrightarrow> (x ::= a, s) \\<rightarrow> (SKIP, s(x := v))\" |\n\nSeq1:   \"(SKIP;;c,s) \\<rightarrow> (c,s)\" |\nSeq2:   \"(c1,s) \\<rightarrow> (c1',s') \\<Longrightarrow> (c1;;c2,s) \\<rightarrow> (c1';;c2,s')\" |\n\nIfTrue:  \"tbval b s True \\<Longrightarrow> (IF b THEN c1 ELSE c2,s) \\<rightarrow> (c1,s)\" |\nIfFalse: \"tbval b s False \\<Longrightarrow> (IF b THEN c1 ELSE c2,s) \\<rightarrow> (c2,s)\" |\n\nWhile:   \"(WHILE b DO c,s) \\<rightarrow> (IF b THEN c;; WHILE b DO c ELSE SKIP,s)\"\n\nlemmas small_step_induct = small_step.induct[split_format(complete)]\n\nsubsection \"The Type System\"\n\ndatatype ty = Neg | Pos | Zero | Any\n\ndefinition ty_of_c :: \"real \\<Rightarrow> ty\" where\n  \"ty_of_c r = (if r = 0 then Zero else (if r > 0 then Pos else Neg))\"\n\nfun ty_of_plus :: \"ty \\<Rightarrow> ty \\<Rightarrow> ty\" where\n  \"ty_of_plus Neg Neg = Neg\" |\n  \"ty_of_plus Pos Pos = Pos\" |\n  \"ty_of_plus Neg Pos = Any\" |\n  \"ty_of_plus Pos Neg = Any\" |\n  \"ty_of_plus Any _ = Any\" |\n  \"ty_of_plus _ Any = Any\" |\n  \"ty_of_plus Zero a = a\" |\n  \"ty_of_plus a Zero = a\"\n\nfun ty_of_div :: \"ty \\<Rightarrow> ty \\<Rightarrow> ty option\" where\n  \"ty_of_div Neg Neg = Some Pos\" |\n  \"ty_of_div Pos Pos = Some Pos\" |\n  \"ty_of_div Neg Pos = Some Neg\" |\n  \"ty_of_div Pos Neg = Some Neg\" |\n  \"ty_of_div a Zero = None\" |\n  \"ty_of_div Zero a = Some Zero\" |\n  \"ty_of_div Any Pos = Some Any\" |\n  \"ty_of_div Any Neg = Some Any\" |\n  \"ty_of_div _ Any = None\"\n\ntype_synonym tyenv = \"vname \\<Rightarrow> ty\"\n\ninductive atyping :: \"tyenv \\<Rightarrow> aexp \\<Rightarrow> ty \\<Rightarrow> bool\"\n  (\"(1_/ \\<turnstile>/ (_ :/ _))\" [50,0,50] 50)\nwhere\nRc_ty: \"\\<Gamma> \\<turnstile> Rc r : ty_of_c r\" |\nV_ty: \"\\<Gamma> \\<turnstile> V x : \\<Gamma> x\" |\nPlus_ty: \"\\<Gamma> \\<turnstile> a1 : \\<tau>1 \\<Longrightarrow> \\<Gamma> \\<turnstile> a2 : \\<tau>2 \\<Longrightarrow>  \\<Gamma> \\<turnstile> Plus a1 a2 : ty_of_plus \\<tau>1 \\<tau>2\" |\nDiv_ty: \"\\<Gamma> \\<turnstile> a1 : \\<tau>1 \\<Longrightarrow> \\<Gamma> \\<turnstile> a2 : \\<tau>2 \\<Longrightarrow> ty_of_div \\<tau>1 \\<tau>2 = Some \\<tau> \\<Longrightarrow> \\<Gamma> \\<turnstile> Div a1 a2 : \\<tau>\"\n\nfun values_of_type :: \"ty \\<Rightarrow> real set\" where\n  \"values_of_type Neg = {x. x<0}\" |\n  \"values_of_type Pos = {x. x>0}\" |\n  \"values_of_type Zero = {0}\" |\n  \"values_of_type Any = {x. x<0 \\<or> x\\<ge>0}\"\n\ndeclare atyping.intros [intro!]\ninductive_cases [elim!]:\n  \"\\<Gamma> \\<turnstile> V x : \\<tau>\" \"\\<Gamma> \\<turnstile> Rc r : \\<tau>\" \"\\<Gamma> \\<turnstile> Plus a1 a2 : \\<tau>\" \"\\<Gamma> \\<turnstile> Div a1 a2 : \\<tau>\"\n\ntext{* Warning: the ``:'' notation leads to syntactic ambiguities,\ni.e. multiple parse trees, because ``:'' also stands for set membership.\nIn most situations Isabelle's type system will reject all but one parse tree,\nbut will still inform you of the potential ambiguity. *}\n\ninductive btyping :: \"tyenv \\<Rightarrow> bexp \\<Rightarrow> bool\" (infix \"\\<turnstile>\" 50)\nwhere\nB_ty: \"\\<Gamma> \\<turnstile> Bc v\" |\nNot_ty: \"\\<Gamma> \\<turnstile> b \\<Longrightarrow> \\<Gamma> \\<turnstile> Not b\" |\nAnd_ty: \"\\<Gamma> \\<turnstile> b1 \\<Longrightarrow> \\<Gamma> \\<turnstile> b2 \\<Longrightarrow> \\<Gamma> \\<turnstile> And b1 b2\" |\nLess_ty: \"\\<Gamma> \\<turnstile> a1 : \\<tau> \\<Longrightarrow> \\<Gamma> \\<turnstile> a2 : \\<tau> \\<Longrightarrow> \\<Gamma> \\<turnstile> Less a1 a2\"\n\ndeclare btyping.intros [intro!]\ninductive_cases [elim!]: \"\\<Gamma> \\<turnstile> Not b\" \"\\<Gamma> \\<turnstile> And b1 b2\" \"\\<Gamma> \\<turnstile> Less a1 a2\"\n\ninductive ctyping :: \"tyenv \\<Rightarrow> com \\<Rightarrow> bool\" (infix \"\\<turnstile>\" 50) where\nSkip_ty: \"\\<Gamma> \\<turnstile> SKIP\" |\nAssign_ty: \"\\<Gamma> \\<turnstile> a : \\<Gamma>(x) \\<Longrightarrow> \\<Gamma> \\<turnstile> x ::= a\" |\nSeq_ty: \"\\<Gamma> \\<turnstile> c1 \\<Longrightarrow> \\<Gamma> \\<turnstile> c2 \\<Longrightarrow> \\<Gamma> \\<turnstile> c1;;c2\" |\nIf_ty: \"\\<Gamma> \\<turnstile> b \\<Longrightarrow> \\<Gamma> \\<turnstile> c1 \\<Longrightarrow> \\<Gamma> \\<turnstile> c2 \\<Longrightarrow> \\<Gamma> \\<turnstile> IF b THEN c1 ELSE c2\" |\nWhile_ty: \"\\<Gamma> \\<turnstile> b \\<Longrightarrow> \\<Gamma> \\<turnstile> c \\<Longrightarrow> \\<Gamma> \\<turnstile> WHILE b DO c\"\n\ndeclare ctyping.intros [intro!]\ninductive_cases [elim!]:\n  \"\\<Gamma> \\<turnstile> x ::= a\"  \"\\<Gamma> \\<turnstile> c1;;c2\"\n  \"\\<Gamma> \\<turnstile> IF b THEN c1 ELSE c2\"\n  \"\\<Gamma> \\<turnstile> WHILE b DO c\"\n\nsubsection \"Well-typed Programs Do Not Get Stuck\"\n(*\nfun type :: \"val \\<Rightarrow> ty\" where\n\"type (Iv i) = Ity\" |\n\"type (Rv r) = Rty\"\n\n\nlemma type_eq_Rty[simp]: \"type v = Rty \\<longleftrightarrow> (\\<exists>r. v = Rv r)\"\nby (cases v) simp_all\n*)\n\ndefinition styping :: \"tyenv \\<Rightarrow> state \\<Rightarrow> bool\" (infix \"\\<turnstile>\" 50)\nwhere \"\\<Gamma> \\<turnstile> s  \\<longleftrightarrow>  (\\<forall>x. s x \\<in> values_of_type (\\<Gamma> x))\"\n\nlemma apreservation:\n  \"\\<Gamma> \\<turnstile> a : \\<tau> \\<Longrightarrow> taval a s v \\<Longrightarrow> \\<Gamma> \\<turnstile> s \\<Longrightarrow> v \\<in> (values_of_type \\<tau>)\"\nproof (induction arbitrary: v rule: atyping.induct)\n  print_cases\n  case (Rc_ty \\<Gamma> r)\n    thus ?case using ty_of_c_def by fastforce\n  next\n  case (V_ty \\<Gamma> x)\n    thus ?case\n    proof -\n      have \"s x = v\" using V_ty.prems(1) by force\n      thus \"v \\<in> values_of_type   (\\<Gamma> x)\" using V_ty.prems(2) styping_def by blast\n    qed\n  next\n  case (Plus_ty \\<Gamma> a1 \\<tau>1 a2 \\<tau>2)\n    thus ?case sorry\n  next\n  case (Div_ty \\<Gamma> a1 \\<tau>1 a2 \\<tau>2 \\<tau>)\n    thus ?case using taval.intros(4)[of a1 s r1 a2 r2] sorry\nqed\n\n(*\napply(induction arbitrary: v rule: atyping.induct)\napply (fastforce simp: styping_def)+ \ndone*)\n\n\nlemma aprogress: \"\\<Gamma> \\<turnstile> a : \\<tau> \\<Longrightarrow> \\<Gamma> \\<turnstile> s \\<Longrightarrow> \\<exists>v. taval a s v\"\nproof(induction rule: atyping.induct)\n  print_cases\n  case (Plus_ty \\<Gamma> a1 \\<tau>1 a2 \\<tau>2)\n  then obtain v1 v2 where v: \"taval a1 s v1\" \"taval a2 s v2\" by blast\n  show ?case using Plus_ty taval.intros by blast\nqed (auto intro: taval.intros)\n\nlemma bprogress: \"\\<Gamma> \\<turnstile> b \\<Longrightarrow> \\<Gamma> \\<turnstile> s \\<Longrightarrow> \\<exists>v. tbval b s v\"\nproof(induction rule: btyping.induct)\nprint_cases\n  case (Less_ty \\<Gamma> a1 t a2)\n  then obtain v1 v2 where v: \"taval a1 s v1\" \"taval a2 s v2\"\n    by (metis aprogress)\n  show ?case using tbval.intros v(1) v(2) by blast\nqed (auto intro: tbval.intros)\n\ntheorem progress:\n  \"\\<Gamma> \\<turnstile> c \\<Longrightarrow> \\<Gamma> \\<turnstile> s \\<Longrightarrow> c \\<noteq> SKIP \\<Longrightarrow> \\<exists>cs'. (c,s) \\<rightarrow> cs'\"\nproof(induction rule: ctyping.induct)\n  case Skip_ty thus ?case by simp\nnext\n  case Assign_ty \n  thus ?case by (metis Assign aprogress)\nnext\n  case Seq_ty thus ?case by simp (metis Seq1 Seq2)\nnext\n  case (If_ty \\<Gamma> b c1 c2)\n  then obtain bv where \"tbval b s bv\" by (metis bprogress)\n  show ?case\n  proof(cases bv)\n    assume \"bv\"\n    with `tbval b s bv` show ?case by simp (metis IfTrue)\n  next\n    assume \"\\<not>bv\"\n    with `tbval b s bv` show ?case by simp (metis IfFalse)\n  qed\nnext\n  case While_ty show ?case by (metis While)\nqed\n\ntheorem styping_preservation:\n  \"(c,s) \\<rightarrow> (c',s') \\<Longrightarrow> \\<Gamma> \\<turnstile> c \\<Longrightarrow> \\<Gamma> \\<turnstile> s \\<Longrightarrow> \\<Gamma> \\<turnstile> s'\"\nproof(induction rule: small_step_induct)\n  case Assign thus ?case\n    by (auto simp: styping_def) (metis Assign(1,3) apreservation)\nqed auto\n\ntheorem ctyping_preservation:\n  \"(c,s) \\<rightarrow> (c',s') \\<Longrightarrow> \\<Gamma> \\<turnstile> c \\<Longrightarrow> \\<Gamma> \\<turnstile> c'\"\nby (induct rule: small_step_induct) (auto simp: ctyping.intros)\n\nabbreviation small_steps :: \"com * state \\<Rightarrow> com * state \\<Rightarrow> bool\" (infix \"\\<rightarrow>*\" 55)\nwhere \"x \\<rightarrow>* y == star small_step x y\"\n\ntheorem type_sound:\n  \"(c,s) \\<rightarrow>* (c',s') \\<Longrightarrow> \\<Gamma> \\<turnstile> c \\<Longrightarrow> \\<Gamma> \\<turnstile> s \\<Longrightarrow> c' \\<noteq> SKIP\n   \\<Longrightarrow> \\<exists>cs''. (c',s') \\<rightarrow> cs''\"\napply(induction rule:star_induct)\napply (metis progress)\nby (metis styping_preservation ctyping_preservation)\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/GabrielaLimonta.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9073122113355091, "lm_q2_score": 0.8056321796478255, "lm_q1q2_score": 0.7309599144393147}}
{"text": "(*  Title:      HOL/Corec_Examples/Tests/Small_Concrete.thy\n    Author:     Aymeric Bouzy, Ecole polytechnique\n    Author:     Jasmin Blanchette, Inria, LORIA, MPII\n    Copyright   2015, 2016\n\nSmall concrete examples.\n*)\n\nsection \\<open>Small Concrete Examples\\<close>\n\ntheory Small_Concrete\nimports \"HOL-Library.BNF_Corec\"\nbegin\n\nsubsection \\<open>Streams of Natural Numbers\\<close>\n\ncodatatype natstream = S (head: nat) (tail: natstream)\n\ncorec (friend) incr_all where\n  \"incr_all s = S (head s + 1) (incr_all (tail s))\"\n\ncorec all_numbers where\n  \"all_numbers = S 0 (incr_all all_numbers)\"\n\ncorec all_numbers_efficient where\n  \"all_numbers_efficient n = S n (all_numbers_efficient (n + 1))\"\n\ncorec remove_multiples where\n  \"remove_multiples n s =\n    (if (head s) mod n = 0 then\n      S (head (tail s)) (remove_multiples n (tail (tail s)))\n    else\n      S (head s) (remove_multiples n (tail s)))\"\n\ncorec prime_numbers where\n  \"prime_numbers known_primes =\n    (let next_prime = head (fold (%n s. remove_multiples n s) known_primes (tail (tail all_numbers))) in\n      S next_prime (prime_numbers (next_prime # known_primes)))\"\n\nterm \"prime_numbers []\"\n\ncorec prime_numbers_more_efficient where\n  \"prime_numbers_more_efficient n remaining_numbers =\n    (let remaining_numbers = remove_multiples n remaining_numbers in\n      S (head remaining_numbers) (prime_numbers_more_efficient (head remaining_numbers) remaining_numbers))\"\n\nterm \"prime_numbers_more_efficient 0 (tail (tail all_numbers))\"\n\ncorec (friend) alternate where\n  \"alternate s1 s2 = S (head s1) (S (head s2) (alternate (tail s1) (tail s2)))\"\n\ncorec (friend) all_sums where\n  \"all_sums s1 s2 = S (head s1 + head s2) (alternate (all_sums s1 (tail s2)) (all_sums (tail s1) s2))\"\n\ncorec app_list where\n  \"app_list s l = (case l of\n    [] \\<Rightarrow> s\n  | a # r \\<Rightarrow> S a (app_list s r))\"\n\nfriend_of_corec app_list where\n  \"app_list s l = (case l of\n    [] \\<Rightarrow> (case s of S a b \\<Rightarrow> S a b)\n  | a # r \\<Rightarrow> S a (app_list s r))\"\n  sorry\n\ncorec expand_with where\n  \"expand_with f s = (let l = f (head s) in S (hd l) (app_list (expand_with f (tail s)) (tl l)))\"\n\nfriend_of_corec expand_with where\n  \"expand_with f s = (let l = f (head s) in S (hd l) (app_list (expand_with f (tail s)) (tl l)))\"\n  sorry\n\ncorec iterations where\n  \"iterations f a = S a (iterations f (f a))\"\n\ncorec exponential_iterations where\n  \"exponential_iterations f a = S (f a) (exponential_iterations (f o f) a)\"\n\ncorec (friend) alternate_list where\n  \"alternate_list l = (let heads = (map head l) in S (hd heads) (app_list (alternate_list (map tail l)) (tl heads)))\"\n\ncorec switch_one_two0 where\n  \"switch_one_two0 f a s = (case s of\n    S b r \\<Rightarrow> S b (S a (f r)))\"\n\ncorec switch_one_two where\n  \"switch_one_two s = (case s of\n    S a (S b r) \\<Rightarrow> S b (S a (switch_one_two r)))\"\n\ncorec fibonacci where\n  \"fibonacci n m = S m (fibonacci (n + m) n)\"\n\ncorec sequence2 where\n  \"sequence2 f u1 u0 = S u0 (sequence2 f (f u1 u0) u1)\"\n\ncorec (friend) alternate_with_function where\n  \"alternate_with_function f s =\n    (let f_head_s = f (head s) in S (head f_head_s) (alternate (tail f_head_s) (alternate_with_function f (tail s))))\"\n\ncorec h where\n  \"h l s = (case l of\n    [] \\<Rightarrow> s\n  | (S a s') # r \\<Rightarrow> S a (alternate s (h r s')))\"\n\nfriend_of_corec h where\n  \"h l s = (case l of\n    [] \\<Rightarrow> (case s of S a b \\<Rightarrow> S a b)\n  | (S a s') # r \\<Rightarrow> S a (alternate s (h r s')))\"\n  sorry\n\ncorec z where\n  \"z = S 0 (S 0 z)\"\n\nlemma \"\\<And>x. x = S 0 (S 0 x) \\<Longrightarrow> x = z\"\n  apply corec_unique\n  apply (rule z.code)\n  done\n\ncorec enum where\n  \"enum m = S m (enum (m + 1))\"\n\nlemma \"(\\<And>m. f m = S m (f (m + 1))) \\<Longrightarrow> f m = enum m\"\n  apply corec_unique\n  apply (rule enum.code)\n  done\n\nlemma \"(\\<forall>m. f m = S m (f (m + 1))) \\<Longrightarrow> f m = enum m\"\n  apply corec_unique\n  apply (rule enum.code)\n  done\n\n\nsubsection \\<open>Lazy Lists of Natural Numbers\\<close>\n\ncodatatype llist = LNil | LCons nat llist\n\ncorec h1 where\n  \"h1 x = (if x = 1 then\n    LNil\n  else\n    let x = if x mod 2 = 0 then x div 2 else 3 * x + 1 in\n    LCons x (h1 x))\"\n\ncorec h3 where\n  \"h3 s = (case s of\n    LNil \\<Rightarrow> LNil\n  | LCons x r \\<Rightarrow> LCons x (h3 r))\"\n\ncorec fold_map where\n  \"fold_map f a s = (let v = f a (head s) in S v (fold_map f v (tail s)))\"\n\nfriend_of_corec fold_map where\n  \"fold_map f a s = (let v = f a (head s) in S v (fold_map f v (tail s)))\"\n   apply (rule fold_map.code)\n  sorry\n\n\nsubsection \\<open>Coinductive Natural Numbers\\<close>\n\ncodatatype conat = CoZero | CoSuc conat\n\ncorec sum where\n  \"sum x y = (case x of\n      CoZero \\<Rightarrow> y\n    | CoSuc x \\<Rightarrow> CoSuc (sum x y))\"\n\nfriend_of_corec sum where\n  \"sum x y = (case x of\n      CoZero \\<Rightarrow> (case y of CoZero \\<Rightarrow> CoZero | CoSuc y \\<Rightarrow> CoSuc y)\n    | CoSuc x \\<Rightarrow> CoSuc (sum x y))\"\n  sorry\n\ncorec (friend) prod where\n  \"prod x y = (case (x, y) of\n      (CoZero, _) \\<Rightarrow> CoZero\n    | (_, CoZero) \\<Rightarrow> CoZero\n    | (CoSuc x, CoSuc y) \\<Rightarrow> CoSuc (sum (prod x y) (sum x y)))\"\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/Corec_Examples/Tests/Small_Concrete.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8558511322604134, "lm_q2_score": 0.853912760387131, "lm_q1q2_score": 0.7308222028289412}}
{"text": "theory concrete_03\n  imports Main\n\nbegin\n\n(*3.1 Arithmetic Expressions*)\ntype_synonym vname = string\ndatatype aexp = N int | V vname | Plus aexp aexp\n\nvalue \"N 5\"\nvalue \"V ''x''\"\nvalue \"Plus (V ''x'') (V ''y'')\"\nvalue \"Plus (N 2) (Plus (V ''z'') (N 3))\"\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\n(*The \\<lambda>x.0 here means a state: x \\<Rightarrow> 0*)\nvalue \"aval (Plus (N 3) (V ''x'')) (\\<lambda>x.0)\"\n(*the same: f(a := b) = (\\<lambda>x. if x = a then b else f x)*)\nvalue \"aval (Plus (N 3)(V ''x'')) (f(''x'' := 0))\"\n\n(*x + y + z + w, let x = 7, y = 3, others = 0*)\nvalue \"aval (Plus (V ''x'') (Plus (V ''y'') (Plus (V ''z'') (V ''w'')))) (((\\<lambda>x. 0)(''x'':=7))(''y'':=3))\"\n(*the same: error \\<rightarrow> how to use <''x'':=7, ''y'':=3>*)\n(*value \"aval (Plus (V ''x'') (Plus (V ''y'') (Plus (V ''z'') (V ''w'')))) <''x'':=7, ''y'':=3>\"*)\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\"\n\nlemma \"aval (asimp_const a) s = aval a s\"\n  apply(induction a)\n    (*Why the split is wrote with auto not above?*)\n    (*\\<rightarrow> The split modifier is the hint to auto to perform a case split whenever it sees a case expression over aexp.*)\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[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 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)\n(*it's so sad... I don't know where is wrong.*)\n(*it's ok after rewriting the done of aval_plus...*)\n  done\n\n(*3.2 Boolean Expressions*)\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\n(*The following is some optimizing versions of the constructors.*)\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(*why this and has parentheses? collision with the keyword and?*)\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(*Note that in the Less case we must switch from bsimp to asimp \\<rightarrow> Why?*)\n\n(*3.3 Stack Machine and Compilation*)\ndatatype instr = LOADI val | LOAD vname | ADD\ntype_synonym stack = \"val list\"\n\nabbreviation \"hd2 xs \\<equiv> hd (tl xs)\"\nabbreviation \"tl2 xs \\<equiv> tl (tl xs)\"\n\n(*It's tooooo hard for me now. Saaaaad... /TAT\\*)\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\nlemma pre_exec_1: \"exec (is1 @ is2) s stk = exec is2 s (exec is1 s stk)\"\n  apply(induction is1)\n  apply(auto)\n(*where is wrong again?*)\n\nlemma \"exec (comp a) s stk = aval a s # stk\"\n  apply(induction a)\n    apply(auto)\n\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/Concrete Semantics/concrete_03.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9099070060380482, "lm_q2_score": 0.8031738010682209, "lm_q1q2_score": 0.7308134686581838}}
{"text": "theory UteDefs\nimports \"../HOModel\"\nbegin\n\nsection {* Verification of the \\ute{} Consensus Algorithm *}\n\ntext {*\n  Algorithm \\ute{} is presented in~\\cite{biely:tolerating}. It is an\n  uncoordinated algorithm that tolerates value (a.k.a.\\ Byzantine) faults,\n  and can be understood as a variant of \\emph{UniformVoting}. The parameters\n  $T$, $E$, and $\\alpha$ appear as thresholds of the algorithm and in the\n  communication predicates. Their values can be chosen within certain bounds\n  in order to adapt the algorithm to the characteristics of different systems.\n\n  We formalize in Isabelle the correctness proof of the algorithm that\n  appears in~\\cite{biely:tolerating}, using the framework of theory\n  @{text HOModel}.\n*}\n\n\nsubsection {* Model of the Algorithm *}\n\ntext {*\n  We begin by introducing an anonymous type of processes of finite\n  cardinality that will instantiate the type variable @{text \"'proc\"}\n  of the generic HO model.\n*}\n\ntypedecl Proc -- {* the set of processes *}\naxiomatization where Proc_finite: \"OFCLASS(Proc, finite_class)\"\ninstance Proc :: finite by (rule Proc_finite)\n\nabbreviation\n  \"N \\<equiv> card (UNIV::Proc set)\"   -- {* number of processes *}\n\ntext {*\n  The algorithm proceeds in \\emph{phases} of $2$ rounds each (we call\n  \\emph{steps} the individual rounds that constitute a phase).\n  The following utility functions compute the phase and step of a round,\n  given the round number.\n*}\n\nabbreviation\n \"nSteps \\<equiv> 2\"\ndefinition phase where \"phase (r::nat) \\<equiv> r div nSteps\"\ndefinition step where \"step (r::nat) \\<equiv> r mod nSteps\"\n\nlemma phase_zero [simp]: \"phase 0 = 0\"\nby (simp add: phase_def)\n\nlemma step_zero [simp]: \"step 0 = 0\"\nby (simp add: step_def)\n\nlemma phase_step: \"(phase r * nSteps) + step r = r\"\n  by (auto simp add: phase_def step_def)\n\ntext {* The following record models the local state of a process. *}\n\nrecord 'val pstate =\n  x :: 'val                -- {* current value held by process *}\n  vote :: \"'val option\"    -- {* value the process voted for, if any *}\n  decide :: \"'val option\"  -- {* value the process has decided on, if any *}\n\ntext {* Possible messages sent during the execution of the algorithm. *}\n\ndatatype 'val msg =\n   Val \"'val\"\n | Vote \"'val option\"\n\ntext {*\n  The @{text x} field of the initial state is unconstrained, all other\n  fields are initialized appropriately.\n*}\n\ndefinition Ute_initState where\n  \"Ute_initState p st \\<equiv>\n   (vote st = None) \\<and> (decide st = None)\"\n\ntext {* \n  The following locale introduces the parameters used for the \\ute{}\n  algorithm and their constraints~\\cite{biely:tolerating}.\n*}\n\nlocale ute_parameters =\n  fixes \\<alpha>::nat and T::nat and E::nat\n  assumes majE: \"2*E \\<ge> N + 2*\\<alpha>\"\n      and majT: \"2*T \\<ge> N + 2*\\<alpha>\"\n      and EltN: \"E < N\"\n      and TltN: \"T < N\"\nbegin\n\ntext {* Simple consequences of the above parameter constraints. *}\n\nlemma alpha_lt_N: \"\\<alpha> < N\"\nusing EltN majE by auto\n\nlemma alpha_lt_T: \"\\<alpha> < T\"\nusing majT alpha_lt_N by auto\n\nlemma alpha_lt_E: \"\\<alpha> < E\"\nusing majE alpha_lt_N by auto\n\ntext {*\n  We separately define the transition predicates and the send functions\n  for each step and later combine them to define the overall next-state relation.\n*}\n\ntext {*\n  In step 0, each process sends its current @{text x}.\n  If it receives the value $v$ more than $T$ times, it votes for $v$,\n  otherwise it doesn't vote.\n*}\n\ndefinition\n  send0 :: \"nat \\<Rightarrow> Proc \\<Rightarrow> Proc \\<Rightarrow> 'val pstate \\<Rightarrow> 'val msg\"\nwhere\n  \"send0 r p q st \\<equiv> Val (x st)\"\n\ndefinition\n  next0 :: \"nat \\<Rightarrow> Proc \\<Rightarrow> 'val pstate \\<Rightarrow> (Proc \\<Rightarrow> 'val msg option) \n                \\<Rightarrow> 'val pstate \\<Rightarrow> bool\" \nwhere\n  \"next0 r p st msgs st' \\<equiv>\n     (\\<exists>v. card {q. msgs q = Some (Val v)} > T \\<and> st' = st \\<lparr> vote := Some v \\<rparr>)\n   \\<or> \\<not>(\\<exists>v. card {q. msgs q = Some (Val v)} > T) \\<and> st' = st \\<lparr> vote := None \\<rparr>\"\n\ntext {*\n  In step 1, each process sends its current @{text vote}.\n\n  If it receives more than @{text \"\\<alpha>\"} votes for a given value @{text v},\n  it sets its @{text x} field to @{text v}, else it sets @{text x} to a\n  default value.\n\n  If the process receives more than @{text E} votes for @{text v}, it decides\n  @{text v}, otherwise it leaves its decision unchanged.\n*}\n\ndefinition\n  send1 :: \"nat \\<Rightarrow> Proc \\<Rightarrow> Proc \\<Rightarrow> 'val pstate \\<Rightarrow> 'val msg\" \nwhere\n  \"send1 r p q st \\<equiv> Vote (vote st)\"\n\ndefinition\n  next1 :: \"nat \\<Rightarrow> Proc \\<Rightarrow> 'val pstate \\<Rightarrow> (Proc \\<Rightarrow> 'val msg option) \n                \\<Rightarrow> 'val pstate \\<Rightarrow> bool\" \nwhere\n  \"next1 r p st msgs st' \\<equiv>\n    ( (\\<exists>v. card {q. msgs q = Some (Vote (Some v))} > \\<alpha> \\<and> x st' = v)\n     \\<or> \\<not>(\\<exists>v. card {q. msgs q = Some (Vote (Some v))} > \\<alpha>) \n         \\<and> x st' = undefined  )\n  \\<and> ( (\\<exists>v. card {q. msgs q = Some (Vote (Some v))} > E \\<and> decide st' = Some v)\n     \\<or> \\<not>(\\<exists>v. card {q. msgs q = Some (Vote (Some v))} > E) \n         \\<and> decide st' = decide st )\n  \\<and> vote st' = None\"\n\ntext {*\n  The overall send function and next-state relation are simply obtained as\n  the composition of the individual relations defined above.\n*}\n\ndefinition \n  Ute_sendMsg :: \"nat \\<Rightarrow> Proc \\<Rightarrow> Proc \\<Rightarrow> 'val pstate \\<Rightarrow> 'val msg\" \nwhere\n  \"Ute_sendMsg (r::nat) \\<equiv> if step r = 0 then send0 r else send1 r\"\n\ndefinition \n  Ute_nextState :: \"nat \\<Rightarrow> Proc \\<Rightarrow> 'val pstate \\<Rightarrow> (Proc \\<Rightarrow> 'val msg option)\n                        \\<Rightarrow> 'val pstate \\<Rightarrow> bool\" \nwhere\n  \"Ute_nextState r \\<equiv> if step r = 0 then next0 r else next1 r\"\n\n\nsubsection {* Communication Predicate for \\ute{} *}\n\ntext {*\n  Following~\\cite{biely:tolerating}, we now define the communication predicate\n  for the \\ute{} algorithm to be correct.\n\n  The round-by-round predicate stipulates the following conditions:\n  \\begin{itemize}\n  \\item no process may receive more than @{text \"\\<alpha>\"} corrupted messages, and\n  \\item every process should receive more than @{text \"max(T, N + 2*\\<alpha> - E - 1)\"} \n    correct messages.\n  \\end{itemize}\n  \\cite{biely:tolerating} also requires that every process should receive more\n  than @{text \"\\<alpha>\"} correct messages, but this is implied, since @{text \"T > \\<alpha>\"}\n  (cf. lemma @{text alpha_lt_T}).\n*}\n\ndefinition Ute_commPerRd where\n  \"Ute_commPerRd HOrs SHOrs \\<equiv>\n   \\<forall>p. card (HOrs p - SHOrs p) \\<le> \\<alpha>\n     \\<and> card (SHOrs p \\<inter> HOrs p) > N + 2*\\<alpha> - E - 1\n     \\<and> card (SHOrs p \\<inter> HOrs p) > T\"\n\ntext {*\n  The global communication predicate requires there exists some phase\n  @{text \"\\<Phi>\"} such that:\n  \\begin{itemize}\n  \\item all HO and SHO sets of all processes are equal in the second step\n    of phase @{text \"\\<Phi>\"}, i.e.\\ all processes receive messages from the \n    same set of processes, and none of these messages is corrupted,\n  \\item every process receives more than @{text T} correct messages in\n    the first step of phase @{text \"\\<Phi>+1\"}, and\n  \\item every process receives more than @{text E} correct messages in the\n    second step of phase @{text \"\\<Phi>+1\"}.\n  \\end{itemize}\n  The predicate in the article~\\cite{biely:tolerating} requires infinitely\n  many such phases, but one is clearly enough.\n*}\n\ndefinition Ute_commGlobal where\n  \"Ute_commGlobal HOs SHOs \\<equiv>\n    \\<exists>\\<Phi>. (let r = Suc (nSteps*\\<Phi>)\n         in  (\\<exists>\\<pi>. \\<forall>p. \\<pi> = HOs r p \\<and> \\<pi> = SHOs r p)\n           \\<and> (\\<forall>p. card (SHOs (Suc r) p \\<inter> HOs (Suc r) p) > T)\n           \\<and> (\\<forall>p. card (SHOs (Suc (Suc r)) p \\<inter> HOs (Suc (Suc r)) p) > E))\"\n\n\nsubsection {* The \\ute{} Heard-Of Machine *}\n\ntext {* \n  We now define the coordinated HO machine for the \\ute{} algorithm\n  by assembling the algorithm definition and its communication-predicate.\n*}\n\ndefinition Ute_SHOMachine where\n  \"Ute_SHOMachine = \\<lparr>\n     CinitState =  (\\<lambda> p st crd. Ute_initState p st),\n     sendMsg =  Ute_sendMsg,\n     CnextState = (\\<lambda> r p st msgs crd st'. Ute_nextState r p st msgs st'),\n     SHOcommPerRd = Ute_commPerRd,\n     SHOcommGlobal = Ute_commGlobal \n   \\<rparr>\"\n\nabbreviation\n  \"Ute_M \\<equiv> (Ute_SHOMachine::(Proc, 'val pstate, 'val msg) SHOMachine)\"\n\nend   -- {* locale @{text \"ute_parameters\"} *}\n\nend   (* theory UteDefs *)\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/ute/UteDefs.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9099070133672954, "lm_q2_score": 0.8031737892899222, "lm_q1q2_score": 0.7308134638276865}}
{"text": "theory MU\n  imports Main\nbegin\n\ndatatype Symbol = M | I | U\n\ntype_synonym word = \"Symbol list\"\n\ninductive legit :: \"word \\<Rightarrow> bool\" where\n  start: \"legit [M, I]\"\n| rule1: \"\\<lbrakk> legit (w @ [I]) \\<rbrakk> \\<Longrightarrow> legit (w @ [I, U])\"\n| rule2: \"\\<lbrakk> legit (M#x) \\<rbrakk> \\<Longrightarrow> legit ((M#x) @ x)\"\n| rule3: \"\\<lbrakk> legit (w @ [I,I,I] @ w') \\<rbrakk> \\<Longrightarrow> legit (w @ [U] @ w')\"\n| rule4: \"\\<lbrakk> legit (w @ [U,U] @ w') \\<rbrakk> \\<Longrightarrow> legit (w @ w')\"\n\nsection \\<open> Examples \\<close>\n\nlemma \"legit [M,I,U] \\<Longrightarrow> legit [M,I,U,I,U]\"\n  using rule2[of \"[I,U]\"] by simp\n\nlemma \"legit [M,U,M] \\<Longrightarrow> legit [M,U,M,U,M]\"\n  using rule2[of \"[U,M]\"] by simp\n\nlemma \"legit [M,U] \\<Longrightarrow> legit [M,U,U]\"\n  using rule2[of \"[U]\"] by simp\n\nlemma \"legit [U,M,I,I,I,M,U] \\<Longrightarrow> legit [U,M,U,M,U]\"\n  using rule3[of \"[U,M]\" \"[M,U]\"] by simp\n\nlemma \"legit [M,I,I,I,I] \\<Longrightarrow> legit [M,I,U]\"\n  using rule3[of \"[M,I]\" \"[]\"] by simp \n\nlemma \"legit [M,I,I,I,I] \\<Longrightarrow>  legit [M,U,I]\"\n  using rule3[of \"[M]\" \"[I]\"] by simp\n\nlemma \"legit [U,U,U] \\<Longrightarrow> legit [U]\"\n  using rule4[of \"[U]\" \"[]\"] by simp\n\nlemma \"legit [M,U,U,U,I,I,I] \\<Longrightarrow> legit [M,U,I,I,I]\"\n  using rule4[of \"[M,U]\" \"[I,I,I]\"] by simp\n\nlemma \"legit [M,U,I,I,U]\"\nproof -\n  have \"legit [M,I]\"                by (simp add: start)\n  then have \"legit [M,I,I]\"         using rule2[of \"[I]\"] by simp\n  then have \"legit [M,I,I,I,I]\"     using rule2[of \"[I,I]\"] by simp\n  then have \"legit [M,I,I,I,I,U]\"   using rule1[of \"[M,I,I,I]\"] by simp\n  then have \"legit [M,U,I,U]\"       using rule3[of \"[M]\" \"[I,U]\"] by simp\n  then have \"legit [M,U,I,U,U,I,U]\" using rule2[of \"[U,I,U]\"] by simp\n  then have \"legit [M,U,I,I,U]\"     using rule4[of \"[M,U,I]\" \"[I,U]\"] by simp\n  then show ?thesis .\nqed\n\nsection \\<open> Meta-Theorems \\<close>\n\nlemma legit_starts_with_M: \"legit w \\<Longrightarrow> hd w = M\"\n  apply(induction rule: legit.induct)\n  apply(simp_all)\n  apply (metis hd_append list.sel(1))  \n  apply (metis Cons_eq_append_conv Symbol.distinct(2) hd_append2 list.sel(1))\n  by (metis Symbol.distinct(4) append_eq_Cons_conv hd_append2 list.sel(1))\n\ncorollary \"\\<not> legit [U]\"\n  using legit_starts_with_M by force\n\nfun number_of_I :: \"word \\<Rightarrow> nat\" where\n  \"number_of_I [] = 0\"\n| \"number_of_I (I#w) = 1 + number_of_I w\"\n| \"number_of_I (_#w) = number_of_I w\"\n\nlemma number_of_I_append: \"number_of_I (w @ v) = number_of_I w + number_of_I v\"\n  apply(induction w, simp_all)\n  by (metis (full_types) Symbol.exhaust add_Suc number_of_I.simps(2) number_of_I.simps(3) number_of_I.simps(4) plus_1_eq_Suc)\n\nlemma helper: \"(n::nat) mod 3 \\<noteq> 0 \\<Longrightarrow> (2 * n) mod 3 \\<noteq> 0\"\nproof(induction n)\n  case 0\n  then show ?case by simp\nnext\n  case (Suc n)\n  have \"(2 * (n + 1)) mod 3 = (((2 * n) mod 3) + 2) mod 3\" using mod_Suc_Suc_eq by auto\n  then show ?case\n    by (metis Suc.prems Suc_1 Suc_eq_plus1 add.left_neutral eval_nat_numeral(3) mod_add_left_eq mod_mult_self2_is_0 mult.commute semiring_normalization_rules(2))\nqed\n\nlemma invariant: \"legit w \\<Longrightarrow> (number_of_I w) mod 3 \\<noteq> 0\"\nproof(induction rule: legit.induct)\ncase start\n  then show ?case by simp\nnext\n  case (rule1 w)\n  then show ?case by (simp add: number_of_I_append)\nnext\n  case (rule2 x)\n  have \"number_of_I ((M # x) @ x) = 2 * number_of_I (M # x)\" using number_of_I_append\n    by simp\n  then show ?case using helper rule2 by simp\nnext\n  case (rule3 w w')\n  have \"number_of_I (w @ [I, I, I] @ w') = 3 + number_of_I w + number_of_I w'\" by (simp add: number_of_I_append)\n  then have \"(number_of_I (w @ [I, I, I] @ w')) mod 3 = (number_of_I (w @ w')) mod 3\"\n    by (simp add: number_of_I_append)\n  then show ?case using number_of_I_append rule3.IH by auto\nnext\n  case (rule4 w w')\n  then show ?case by (simp add: number_of_I_append)\nqed\n\ntheorem \"\\<not> legit [M,U]\"\nproof -\n  have \"number_of_I [M,U] mod 3 = 0\" by auto\n  then show ?thesis\n    using invariant by meson\nqed\n\nend", "meta": {"author": "maurobringolf", "repo": "GEB", "sha": "8706c3d1c6ea791c0fcd6ec4a99c3a87f1db9e34", "save_path": "github-repos/isabelle/maurobringolf-GEB", "path": "github-repos/isabelle/maurobringolf-GEB/GEB-8706c3d1c6ea791c0fcd6ec4a99c3a87f1db9e34/MU.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587993853654, "lm_q2_score": 0.8221891392358015, "lm_q1q2_score": 0.730727832254898}}
{"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_03\n  imports \"../../Test_Base\"\nbegin\n\ndatatype 'a list = nil2 | cons2 \"'a\" \"'a list\"\n\ndatatype Nat = Z | S \"Nat\"\n\nfun y :: \"'a list => 'a list => 'a list\" where\n  \"y (nil2) y2 = y2\"\n| \"y (cons2 z2 xs) y2 = cons2 z2 (y xs y2)\"\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 y22) = x x2 y22\"\n\nfun count :: \"Nat => Nat list => Nat\" where\n  \"count z (nil2) = Z\"\n| \"count z (cons2 z2 ys) =\n     (if x z z2 then S (count z ys) else count z ys)\"\n\nfun t2 :: \"Nat => Nat => bool\" where\n  \"t2 (Z) y2 = True\"\n| \"t2 (S z2) (Z) = False\"\n| \"t2 (S z2) (S x2) = t2 z2 x2\"\n\ntheorem property0 :\n  \"t2 (count n xs) (count n (y xs ys))\"\n  find_proof DInd\n  (*Why induction on xs?\n    Because the innermost recursively defined constant \"y\" is defined recursively on the\n    first parameter, which is \"xs\" in this case.\n    Because \"t2\" is defined recursively on the first parameter, which is \"count n xs\" here,\n    and \"count\" is defined recursively on the second parameter (\"xs\" in this case).*)\n  apply(induct xs)\n  (*auto can discharge these sub-goals.*)\n   apply(subst count.simps)\n   apply(subst t2.simps)\n   apply(rule TrueI)\n  apply(subst y.simps)\n  apply(subst count.simps)\n  apply(simp del:t2.simps)\n  apply(subst t2.simps)\n  apply(rule impI)\n  apply(thin_tac \"x n x1\")\n  apply assumption\n  done\n\ntheorem property0' :\n  \"t2 (count n xs) (count n (y xs ys))\"\n  (*\"xs\" is optional.\n    Other generalizations also work:\n    \"arbitrary: n\"\n    \"arbitrary: n ys\"\n    \"arbitrary: ys\"\n    \"arbitrary: ys n\"\n    *)\n  apply (induct xs arbitrary: n rule: TIP_prop_03.count.induct)\n  apply auto\n  done\n\ntheorem property0'' :\n  \"t2 (count n xs) (count n (y xs ys))\"\n  apply(induct n)\n  (*This is bad:\n    The first sub-goal is identical to the original goal.\n    Not really.\n   *)\n  oops\n\ntheorem property0''' :\n  \"t2 (count n xs) (count n (y xs ys))\"\n  apply(induct rule:y.induct)\n   apply fastforce\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_03.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587993853654, "lm_q2_score": 0.8221891305219504, "lm_q1q2_score": 0.7307278245103861}}
{"text": "theory P18 imports Main begin\n\ndatatype 'a tree =\n  Leaf (\"\\<langle>\\<rangle>\") |\n  Node \"'a tree\" (\"value\": 'a) \"'a tree\" (\"(1\\<langle>_,/ _,/ _\\<rangle>)\")\ndatatype_compat tree\n\nfun preOrder :: \"'a tree \\<Rightarrow> 'a list\" where\n\"preOrder \\<langle>\\<rangle> = []\" |\n\"preOrder \\<langle>l, x, r\\<rangle> = x # preOrder l @ preOrder r\"\n\nfun postOrder :: \"'a tree \\<Rightarrow> 'a list\" where\n\"postOrder \\<langle>\\<rangle> = []\" |\n\"postOrder \\<langle>l, x, r\\<rangle> = postOrder l @ postOrder r @ [x]\"\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\nfun mirror :: \"'a tree \\<Rightarrow> 'a tree\" where\n\"mirror \\<langle>\\<rangle> = \\<langle>\\<rangle>\" |\n\"mirror \\<langle>l, x, r\\<rangle> = \\<langle>mirror r, x, mirror l\\<rangle>\"\n\nlemma \"preOrder (mirror xt) = rev (preOrder xt)\"\n  nitpick\n  oops\n\nlemma \"preOrder (mirror xt) = rev (postOrder xt)\"\n  apply (induct xt)\n   apply auto\n  done\n\nlemma \"preOrder (mirror xt) = rev (inOrder xt)\"\n  nitpick\n  oops\n\nlemma \"postOrder (mirror xt) = rev (preOrder xt)\"\n  apply (induct xt)\n   apply auto\n  done\n\nlemma \"postOrder (mirror xt) = rev (postOrder xt)\"\n  nitpick\n  oops\n\nlemma \"postOrder (mirror xt) = rev (inOrder xt)\"\n  nitpick\n  oops\n\nlemma \"inOrder (mirror xt) = rev (preOrder xt)\"\n  nitpick\n  oops\n\nlemma \"inOrder (mirror xt) = rev (postOrder xt)\"\n  nitpick\n  oops\n\nlemma \"inOrder (mirror xt) = rev (inOrder xt)\"\n  apply (induct xt)\n   apply auto\n  done\n\nfun root :: \"'a tree \\<Rightarrow> 'a\" where\n\"root xt = (hd (preOrder xt))\"\n\nfun leftmost :: \"'a tree \\<Rightarrow> 'a\" where\n\"leftmost xt = (hd (inOrder xt))\"\n\nfun rightmost :: \"'a tree \\<Rightarrow> 'a\" where\n\"rightmost xt = (last (inOrder xt))\"\n\ntheorem \"last (inOrder xt) = rightmost xt\"\n  apply (induct xt)\n   apply auto\n  done\n\ntheorem \"hd (inOrder xt) = leftmost xt\"\n  apply (induct xt)\n   apply auto\n  done\n\ntheorem \"hd (preOrder xt) = last (postOrder xt)\"\n  nitpick\n  oops\n\ntheorem \"hd (preOrder xt) = root xt\"\n  apply (induct xt)\n   apply auto\n  done\n\ntheorem \"hd (inOrder xt) = root xt\"\n  nitpick\n  oops\n\ntheorem \"last (postOrder xt) = root xt\"\n  nitpick\n  oops\n\nend", "meta": {"author": "albertqjiang", "repo": "Isa100days", "sha": "a8e1069390243033f993328421526d2ff077d1ca", "save_path": "github-repos/isabelle/albertqjiang-Isa100days", "path": "github-repos/isabelle/albertqjiang-Isa100days/Isa100days-a8e1069390243033f993328421526d2ff077d1ca/P18.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.888758793492457, "lm_q2_score": 0.8221891327004133, "lm_q1q2_score": 0.7307278216014289}}
{"text": "section {* Abstract syntax for Logic. *}\n\ntheory Syntax_SL_test \n  imports  Main HOL.Real\nbegin\n\n(*Constants*)\ndatatype val = Real real     (\"Real _\" 76)\n             | String string (\"String _\" 76)\n             | Bool bool     (\"Bool _\" 76)\n| Err\n(*Expressions of HCSP language.*)\ndatatype exp = Con val (\"Con _\" 75)\n             | RVar string   (\"RVar _\" 75 )\n             | SVar string   (\"SVar _\" 75)\n             | BVar string   (\"BVar _\" 75)\n             | Add exp exp   (infixr \"[+]\" 70)\n             | Sub exp exp   (infixl  \"[-]\" 70)\n             | Mul exp exp   (infixr \"[*]\" 71)\n(*to complete all related to divide in  following functions.*)\n             | Div exp exp   (infixr \"[**]\" 71) \nML {*\n@{term \"Real a\"}\n*}\n\nML{*\n@{term \"RVar a\"}\n\n*}\n\n\nML{*\n@{term \"a [+] b\"}\n\n*}\n\n\n(*Type declarations to be used in {*proc*}*)\ndatatype typeid = R | S | B\n(*States*)\ntype_synonym state = \"string * typeid => val\"\n\n(*Evaluation of expressions*)\nprimrec evalE :: \"exp \\<Rightarrow> state => val\" where\n\"evalE (Con y) f = y\" |\n\"evalE (RVar (x)) f = f (x, R)\" |\n\"evalE (SVar (x)) f = f (x, S)\" |\n\"evalE (BVar (x)) f = f (x, B)\" |\n\"evalE (e1 [+] e2) f = (case (evalE e1 f) of Real (x) =>\n                                         (case (evalE e2 f) of Real (y) => Real (x + y) |\n                                                                          _    => Err)|\n                                                              _ => Err)\" |\n\"evalE (e1 [-] e2) f = (case (evalE e1 f) of  Real (x) =>\n                                         (case (evalE e2 f) of  Real (y) =>  Real (x - y) |\n                                                                          _    => Err)|\n                                                              _ => Err)\" |\n\"evalE (e1 [*] e2) f = (case (evalE e1 f) of  Real (x) =>\n                                         (case (evalE e2 f) of Real (y) =>  Real (x * y) |\n                                                                          _    => Err)|\n                                                              _ => Err)\"\n\n\n\n\nsection{*FOL operators*}\ntype_synonym fform = \"state  \\<Rightarrow> bool\"\ndefinition fTrue:: \"fform\" where \" fTrue == \\<lambda> s. True\"\ndefinition fFalse:: \"fform\" where \"fFalse == \\<lambda> s. False\"\ndefinition fEqual :: \"exp \\<Rightarrow> exp \\<Rightarrow> fform\"  (\"_[=]_\" 69) where\n\"e [=] f == \\<lambda> s. evalE e s = evalE f s\"\ndefinition fLess :: \"exp \\<Rightarrow> exp \\<Rightarrow> fform\"  (\"_[<]_\" 69) where\n\"e [<] f == \\<lambda> s. (case (evalE e s) of Real c \\<Rightarrow> (case (evalE f s) of Real d \\<Rightarrow> (c<d)\n                                                                    |  _ \\<Rightarrow> False)\n                                       |  _ \\<Rightarrow> False )\" \n\ndefinition fAnd :: \"fform \\<Rightarrow> fform \\<Rightarrow> fform\"  (infixl \"[&]\"  65) where\n\"P [&] Q == \\<lambda> s. P s \\<and> Q s\"\ndefinition fOr :: \"fform\\<Rightarrow> fform \\<Rightarrow> fform\"  (infixl \"[|]\" 65) where\n\"P [|] Q == \\<lambda> s. P s \\<or> Q s\"\ndefinition fNot :: \"fform \\<Rightarrow> fform\"  (\"[\\<not>]_\" 67) where\n\"[\\<not>]P == \\<lambda> s. \\<not> P s\"\ndefinition fImp :: \"fform \\<Rightarrow> fform \\<Rightarrow> fform\"  (infixl \"[\\<longrightarrow>]\" 65) where\n\"P [\\<longrightarrow>] Q == \\<lambda> s. P s \\<longrightarrow> Q s\"\n\ndefinition fLessEqual :: \"exp \\<Rightarrow> exp \\<Rightarrow> fform\"  (\"_[\\<le>]_\" 69) where\n\"e [\\<le>] f == (e [=] f) [|] (e [<] f)\"\ndefinition fGreaterEqual :: \"exp \\<Rightarrow> exp \\<Rightarrow> fform\"  (\"_[\\<ge>]_\" 69) where\n\"e [\\<ge>] f == [\\<not>](e [<] f)\"\ndefinition fGreater :: \"exp \\<Rightarrow> exp \\<Rightarrow> fform\"  (\"_[>]_\" 69) where\n\"e [>] f == [\\<not>](e [\\<le>] f)\"\n\n(*For substitution*)\ndefinition fSubForm :: \"fform \\<Rightarrow> exp \\<Rightarrow> string \\<Rightarrow> typeid \\<Rightarrow> fform\" (\"_[_,_,_]\" 70) where\n\"P [e, a, b] == (\\<lambda>s. P (\\<lambda> (x, r). (if (x = a \\<and> r = b) then (evalE e s)\n                                                            else (s (x, r)))))\"\n \n(*close() extends the formula with the boundary, used for continuous evolution.*)\nconsts close :: \"fform \\<Rightarrow> fform\"\n\naxiomatization where\nLessc[simp]: \"close (e [<] f) = e [\\<le>] f\" and\nGreatc[simp]: \"close (e [>] f) = e [\\<ge>] f\" and\nEqualc[simp]: \"close (e [=] f) = e [=] f\" and\nGreatEqual[simp] : \"close ( e [\\<ge>] f) =  e [\\<ge>] f\" and\nAndc[simp]: \"close (P [&] Q) = close (P) [&] close (Q)\" and\nOrc[simp]: \"close (P [|] Q) = close (P) [|] close (Q)\"\n\n \nlemma notLess : \"close ([\\<not>] e [<] f) = e [\\<ge>] f\"\napply (subgoal_tac \"[\\<not>] e [<] f == e [\\<ge>] f\", auto)\napply (simp add:fGreaterEqual_def fOr_def fNot_def fLess_def fEqual_def fGreater_def)\ndone\n\n\ndeclare fTrue_def [simp]\ndeclare fFalse_def [simp]\n     \n(*Types for defining HCSP*)\ntype_synonym cname = string\ntype_synonym time = real\n\n(*Communication processes of HCSP*)\ndatatype comm\n= Send \"cname\" \"exp\"         (\"_!!_\" [110,108] 100)      \n| Receive \"cname\" \"exp\"    (\"_??_\" [110,108] 100) \n\n(*HCSP processes*)\ndatatype proc\n= Cm comm\n| \"Skip\"\n| Ass \"exp\" \"exp\"          (\"_ := _\" [99, 95] 94)   \n| Seq \"proc\" \"proc\"                   (\"_; _\"        [91,90 ] 90)\n| Cond \"fform\" \"proc\"                 (\"IF _ _\"   [95,94]93)\n| CondG \"fform\" \"proc\" \"proc\"                 (\"IFELSE _ _ _\"   [95,94,94]93)\n| Pref   \"comm\" \"proc\"                  (\"_\\<rightarrow>_\"   [95,94]93)           \n| join \"proc\" \"proc\"                   (infixr \"[[\" 90)\n| meet \"proc\" \"proc\"                  (\"_<<_\" [90,90] 90)\n(*Repetition is annotated with invariant*)\n| Rep    \"proc\" \"fform\"                              (\"_*&&_\"[91] 90)\n| RepN  \"proc\" \"nat\"   (\"_* NUM _\"[91, 90] 90)\n(*Continuous evolution is annotated with invariant.*)\n| Cont  \"(string * typeid) list\" \"exp list\" \"fform\" \"fform\"               (\"<_:_&&_&_>\" [95,95,96]94)\n| Interp   \"proc\" \"proc\" (\"_[[>_\"[95,94]94)\n\n(*We assume parallel  composition only occurs in  the topmost level.*)\ndatatype procP = Par    \"proc\" \"proc\"                  (infixr \"||\" 89)\n\nend\n\n", "meta": {"author": "bzhan", "repo": "mars", "sha": "d10e489a8ddf128a4cbac13291efdece458d732d", "save_path": "github-repos/isabelle/bzhan-mars", "path": "github-repos/isabelle/bzhan-mars/mars-d10e489a8ddf128a4cbac13291efdece458d732d/lunarlander-201906/Syntax_SL_test.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587993853654, "lm_q2_score": 0.822189123986562, "lm_q1q2_score": 0.7307278187020021}}
{"text": "theory Freegroup_with_Basis\nimports UniversalProperty  Word_Problem Generators Cancellation\nbegin    \n\ntext \\<open>In this file, we provide a formalisation of a 'freegroup with basis', which \nis a group with a subset such that the group is isomorphic to a free group, and the \nisomorphism carrier the subset to the generating set of the free group. \nThis distinction about carrying subsets, is useful to provide a neccessary and \nsufficientcondition for a subgroup of a group to be free. This condition is formalised in \nthe lemma fg with basis eq cond, and is cruicial to the proof of Nielson Schreier.\\<close>\n\n\ndefinition fg_with_basis\n  where\n\"fg_with_basis (G::('a,'b) monoid_scheme) A \n    \\<equiv> (\\<exists>(S::(unit \\<times> 'a) set) \\<phi>. (\\<phi> \\<in> iso G (freegroup S)) \n              \\<and> (\\<langle>A\\<rangle>\\<^bsub>G\\<^esub> = carrier G) \\<and>(\\<phi> ` A = (liftgen S)))\"\n\n\nlemma fg_with_basis_is_free:\n  fixes G \n  fixes A\n  assumes \"(fg_with_basis G A)\"\n  shows \"is_freegroup G\" using assms unfolding fg_with_basis_def is_iso_def   \n        is_freegroup_def by auto\n\n\n\nlemma m_concat_in_span:\n  assumes \"group G\"\n  and  \"\\<forall>x \\<in> set l. x \\<in> S\"\nshows \"monoid.m_concat G l \\<in> \\<langle>S\\<rangle>\\<^bsub>G\\<^esub>\" using assms\nproof(induction l)\n  case (Cons a l)\n  have \"monoid.m_concat G (a#l) = a \\<otimes>\\<^bsub>G\\<^esub> (monoid.m_concat G l)\" by auto\n  hence \"(monoid.m_concat G l) \\<in> \\<langle>S\\<rangle>\\<^bsub>G\\<^esub>\" using Cons by force\n  moreover have \"a \\<in> \\<langle>S\\<rangle>\\<^bsub>G\\<^esub>\" using Cons(3) \n    by (simp add: gen_span.gen_gens)\n  thus ?case \n    by (simp add: calculation gen_span.gen_mult)  \nqed (simp)\n\n\ntext\\<open>We define a non-empty word w in a monoid G with a subset A to be non reducible, if it \nif the word w is obtained as a product of elements of A and their inverses,the word\n is either of length 1, or any successive elements from A occuring in the word are\n not inverses of each other. \\<close>\n\ndefinition non_reducible::\"('a,'b) monoid_scheme \\<Rightarrow> 'a set => 'a \\<Rightarrow> bool\"\n  where\n\"non_reducible G A w \\<equiv> (\\<exists>l. w = monoid.m_concat G l \\<and> (l \\<noteq> []) \n                          \\<and> (\\<forall>x \\<in> set l. x \\<in> A \\<union> m_inv G ` A) \n                          \\<and> ((length l = 1) \\<or> (\\<forall>i \\<le> (length l)-2 .\n                            l!i \\<noteq> inv\\<^bsub>G\\<^esub> (l!(i+1)))))\"\n\nlemma hom_preserves_m_concat:\n  assumes \"group G\" and \"group H\"\n and  \"\\<phi> \\<in> hom G H\"\n  and \"w = monoid.m_concat G l\"\n  and \"\\<forall>x \\<in> set l. x \\<in> carrier G\"\nshows \"\\<phi> w = monoid.m_concat H (map \\<phi> l)\"\n  using assms \nproof(induction l arbitrary: w)\n  case Nil\n  then show ?case using hom_one by force\nnext\n  case (Cons a l)\n  let ?w = \"monoid.m_concat G l\"\n  have x_in:\"\\<forall> x \\<in> set l. x \\<in> carrier G\" using Cons(6) by simp\n  hence w_in:\"?w \\<in> carrier G\" \n    by (simp add: assms(1) group.is_monoid monoid.m_concat_closed subsetI)\n  moreover have \"a \\<in> carrier G\" using Cons(6) by simp\n  moreover have \"w = a \\<otimes>\\<^bsub>G\\<^esub> ?w\"  using Cons(5) by simp\n  ultimately have \"\\<phi> w = \\<phi> a  \\<otimes>\\<^bsub>H\\<^esub> (\\<phi> ?w)\" using w_in Cons(4) unfolding hom_def by blast\n  moreover have \" \\<phi> ?w = foldr (\\<otimes>\\<^bsub>H\\<^esub>) (map \\<phi> l) \\<one>\\<^bsub>H\\<^esub>\" using  Cons(1)[OF Cons(2,3,4)] x_in \n    by blast\n  ultimately show ?case by simp\nqed\n\nlemma liftgen_subset:\"liftgen S \\<subseteq> carrier (freegroup S)\" \n  by (simp add: freegroup_def liftgen_subset_quotient)\n\ndefinition liftgen_inv\n  where\n\"liftgen_inv S = m_inv (freegroup S) ` (liftgen S)\" \n\nlemma liftgen_inv_in_carrier:\n  \"liftgen_inv S \\<subseteq> carrier (freegroup S)\"\n  using liftgen_inv_def \n  by (metis (no_types, lifting) freegroup_is_group group.inv_closed image_subset_iff liftgen_subset subset_iff)\n\n\nlemma inj_on_invset:\n  assumes \"group G\" \"group H\"\n   and \"\\<phi> \\<in> hom G H\"\n   and \"A \\<subseteq> carrier G\"\n   and \"inj_on \\<phi> A\"\n shows \"inj_on \\<phi> (m_inv G ` A)\"\nproof\n  fix x\n  fix y\n  assume x:\"x \\<in> m_inv G ` A\"\n  assume y:\"y \\<in>  m_inv G ` A\"\n  assume eq:\"\\<phi> x = \\<phi> y\"\n  obtain x' where x':\"x = inv\\<^bsub>G\\<^esub> x'\" \"x' \\<in> A\" using x by blast\n  obtain y' where y':\"y = inv\\<^bsub>G\\<^esub> y'\" \"y' \\<in> A\"  using y by blast\n  from x' have \"x \\<in> carrier G\" using x' assms(1,4) by auto\n  moreover have \"x' = inv\\<^bsub>G\\<^esub> x\" using x' assms(1,4) by fastforce\n  ultimately have map_x':\"\\<phi> (x') = inv\\<^bsub>H\\<^esub> \\<phi> x\" using  group_hom.hom_inv[of \"G\" \"H\" \\<phi> x] assms(1-3) \n     group_hom.intro group_hom_axioms.intro by blast\n  from y' have \"y \\<in> carrier G\" using assms(1,4)  by auto\n  moreover have \"y' = inv\\<^bsub>G\\<^esub> y\" using y' assms(1,4) by fastforce\n  ultimately have map_y':\"\\<phi> (y') = inv\\<^bsub>H\\<^esub> \\<phi> y\" using  group_hom.hom_inv[of \"G\" \"H\" \\<phi> y] assms(1-3) \n     group_hom.intro group_hom_axioms.intro by blast    \n  have \"\\<phi> x' = \\<phi> y'\" using map_x' eq assms(2) \n    using map_y' by force\n  hence \"x' = y'\" using x'(2) y'(2) assms(5) unfolding inj_on_def by blast\n  thus \"x = y\" using x' y' by auto\nqed\n\nlemma bij_to_invset: \n  assumes \"\\<phi> \\<in> iso G H\" \"group G\" \"group H\"\n      and \"A \\<subseteq> carrier G\"\n      and \"bij_betw \\<phi> A Y\"\n    shows \"bij_betw \\<phi> (m_inv G ` A)  (m_inv H ` Y) \"\nproof-\n  have \" inj_on \\<phi> (m_inv G ` A)\" using assms unfolding bij_betw_def     \n    by (simp add: inj_on_invset iso_imp_homomorphism)\n  moreover have \"\\<phi> ` (m_inv G ` A) = (m_inv H ` Y)\"\n  proof\n    show \"\\<phi> ` m_inv G ` A \\<subseteq> m_inv H ` Y\"\n    proof\n      fix \\<phi>_x\n      assume \"\\<phi>_x \\<in> \\<phi> ` m_inv G ` A \"\n      then obtain x where x:\"x \\<in> A\" \"\\<phi>_x = \\<phi>  (m_inv G  x)\" by blast\n      have \"\\<phi>_x = m_inv H (\\<phi> x)\" using assms unfolding iso_def \n        by (metis (no_types, lifting) \\<open>\\<phi>_x = \\<phi> (inv\\<^bsub>G\\<^esub> x)\\<close> \\<open>x \\<in> A\\<close> assms(1) group_hom.hom_inv group_hom.intro group_hom_axioms.intro in_mono iso_imp_homomorphism)\n      thus \"\\<phi>_x \\<in> m_inv H ` Y\" using assms(5) x(1) unfolding bij_betw_def by blast\n    qed\n  next\n    show \" m_inv H ` Y  \\<subseteq> \\<phi> ` m_inv G ` A\"\n    proof\n      fix \\<phi>_y\n      assume \"\\<phi>_y \\<in> m_inv H ` Y\"\n      then obtain y where y:\"y \\<in> Y\" \"\\<phi>_y = m_inv H y\" by blast\n      then obtain x where x:\"x \\<in>  A\" \"\\<phi> x = y\" using assms \n        by (meson bij_betw_apply bij_betw_the_inv_into f_the_inv_into_f_bij_betw) \n      then have \"\\<phi>_y = \\<phi> (m_inv G x)\" using assms y\n        by (metis (no_types, opaque_lifting) group_hom.hom_inv group_hom.intro group_hom_axioms.intro iso_imp_homomorphism subsetD)\n      then show \"\\<phi>_y  \\<in> \\<phi> ` m_inv G ` A\" using x(1) by fast\n    qed\n  qed\n  ultimately show ?thesis  unfolding bij_betw_def by blast\nqed\n\nlemma in_map_of_union:\n  assumes \"\\<forall>x \\<in> S. x \\<in> A \\<union> B\"\n  shows \"\\<forall>x \\<in> f ` S. x \\<in> f ` A \\<union> f ` B\"\n  using assms by blast\n\nlemma(in group) exist_of_proj:\n  assumes \"\\<forall>x \\<in> set ls. x \\<in> (liftgen S) \\<union> (liftgen_inv S)\"\n  shows \"\\<exists>l. (\\<forall> x \\<in> set l. x \\<in> S \\<times> {True, False}) \n              \\<and> (ls = map (\\<lambda> x. (reln_tuple \\<langle>S\\<rangle> `` {[x]})) l)\"\n  using assms \nproof(induction ls)\n  case (Cons a ls)\n  hence \"\\<forall>x\\<in>set ls. x \\<in> liftgen S \\<union> liftgen_inv S\" by simp\n  then obtain l where l:\"\\<forall>x \\<in> set l. x \\<in> S \\<times> {True, False}\" \"(ls = map (\\<lambda> x. (reln_tuple \\<langle>S\\<rangle> `` {[x]})) l)\"\n    using Cons(1) by auto\n  have a_in:\"a \\<in> liftgen S \\<or> a \\<in> liftgen_inv S\" using Cons(2) by auto\n  hence a_in_carrier:\"a \\<in> carrier (freegroup S)\" \n    using liftgen_inv_in_carrier liftgen_subset by blast\n  then show ?case\n  proof(cases \"a \\<in> liftgen S\")\n    case True\n    then obtain s where s:\"s \\<in> S\" \"a = reln_tuple \\<langle>S\\<rangle> `` {\\<iota> s}\" unfolding liftgen_def by blast\n    hence \"\\<forall>x \\<in> set ((\\<iota> s)@l). x \\<in> S \\<times> {True, False}\" \n      by (simp add: inclusion_def l(1))\n    moreover have \"(a#ls) =  map (\\<lambda> x. (reln_tuple \\<langle>S\\<rangle> `` {[x]})) ((\\<iota> s)@l)\"\n      using s(2) l(2) \n      by (simp add: inclusion_def)\n    ultimately show ?thesis by metis\n  next\n    case False\n    hence \"a \\<in> liftgen_inv S\" using a_in by simp\n    then obtain b where b:\"b \\<in> liftgen S\" \"a = inv \\<^bsub>freegroup S\\<^esub> b\" unfolding liftgen_inv_def \n      by blast\n    hence inv_a:\"b = inv \\<^bsub>freegroup S\\<^esub> a\" \n      by (metis (no_types, lifting) freegroup_is_group group.inv_inv liftgen_subset subsetD) \n    from b(1) have b_in_fg:\"b \\<in> carrier (freegroup S)\" \n      by (simp add: a_in_carrier freegroup_is_group inv_a)\n    then obtain s' where s':\"s' \\<in> S\" \"b = reln_tuple \\<langle>S\\<rangle> `` {\\<iota> s'}\" using b unfolding liftgen_def\n      by blast\n    then have \"wordinverse (\\<iota> s') = [(s', False)]\" unfolding inclusion_def by auto\n    moreover have \"a =  reln_tuple \\<langle>S\\<rangle> `` {wordinverse (\\<iota> s')}\" using inv_a\n       wordinverse_inv[OF b_in_fg s'(2)]  b(2) by argo\n    hence \"a =   reln_tuple \\<langle>S\\<rangle> `` {[(s', False)]}\" unfolding wordinverse_def inclusion_def by auto\n    hence \" a # ls = map (\\<lambda>x. reln_tuple \\<langle>S\\<rangle> `` {[x]}) ((s',False)#l)\" using l(2) by auto\n    moreover have \"\\<forall> x \\<in> set ((s',False)#l). x \\<in> S \\<times> {True, False}\" using l(1) \n      by (simp add: s'(1))\n    ultimately show ?thesis by metis\n  qed\nqed(simp)\n\nlemma(in group) non_reduced_projection:\n  assumes \"\\<forall>x \\<in> set ls. x \\<in> (liftgen S) \\<union> (liftgen_inv S)\"  \n    and \"ls = map (\\<lambda> x. (reln_tuple \\<langle>S\\<rangle> `` {[x]})) l\"\n    and \"length ls > 1\"\n    and   \"\\<forall>i \\<le> (length ls)-2 . ls!i \\<noteq> inv\\<^bsub>(freegroup S)\\<^esub> (ls!(i+1))\"\n  shows \"\\<forall>i \\<le> (length l)-2 . (l!i) \\<noteq> inverse (l!(i+1))\"\nproof(rule ccontr)\n  assume \"\\<not> (\\<forall>i\\<le>length l - 2. l ! i \\<noteq> FreeGroupMain.inverse (l ! (i + 1)))\"\n  then obtain i where i:\"i \\<le> length l - 2\" \"l ! i = FreeGroupMain.inverse (l ! (i + 1))\"\n    by blast\n   \n  then have \"[l!i] = wordinverse [l ! (i + 1)]\" by auto\n  hence word_inv:\"wordinverse [l!i] = [l ! (i + 1)]\" \n    by (metis wordinverse_of_wordinverse)\n  then have l_i_eq:\" ls!i = (reln_tuple \\<langle>S\\<rangle> `` {[l!i]}) \" using assms \n    by (metis (mono_tags, lifting) One_nat_def add_lessD1 diff_less i(1) le_add_diff_inverse length_greater_0_conv length_map list.size(3) nat_1_add_1 not_add_less2 nth_map plus_1_eq_Suc zero_less_Suc)\n  have len_eq:\"length ls = length l\" using assms(2) by simp\n  hence \"ls!i \\<in> set ls\" using i(1) assms(3) by simp\n  hence ls_i:\"ls!i \\<in> carrier (freegroup S)\" using assms(1) i(1) using \n    liftgen_inv_in_carrier[of S] liftgen_subset[of S]\n    by (meson Un_iff liftgen_subset subsetD)\n  have \" inv\\<^bsub>freegroup S\\<^esub> (ls!i) =  (reln_tuple \\<langle>S\\<rangle> `` {[l!(i + 1)]})\"\n    using wordinverse_inv[OF ls_i l_i_eq] word_inv by argo\n  moreover have \"(reln_tuple \\<langle>S\\<rangle> `` {[l!(i + 1)]}) = ls!(i+1)\" using assms \n    by (smt (z3) Nat.le_diff_conv2 \\<open>length ls = length l\\<close> add_lessD1 i(1) le_add_diff_inverse nat_add_left_cancel_less nat_less_le neq0_conv nth_map one_less_numeral_iff plus_1_eq_Suc semiring_norm(76) zero_less_diff)\n  ultimately have \"inv\\<^bsub>freegroup S\\<^esub>  (ls!i) = ls!(i+1)\" by auto\n  hence \"ls!i = inv\\<^bsub>freegroup S\\<^esub>  (ls!(i+1))\" \n    by (metis freegroup_is_group group.inv_inv ls_i)\n  thus False using i(1) len_eq assms(4) by auto\nqed\n\nlemma hom_to_subgp:\n assumes \"h \\<in> hom G H\"\n and \"h ` (carrier G) = H'\"\nshows \"h \\<in> hom G (H\\<lparr>carrier := H'\\<rparr>)\"\n  using assms unfolding hom_def by (simp, blast)\n\nlemma non_reducible_imp_red:\n  assumes \"\\<forall>i \\<le> (length l)-2 . (l!i) \\<noteq> inverse (l!(i+1))\"\n  shows \"reduced l\" using assms\nproof(induction l)\n  case (Cons a l)\n  hence 1:\"\\<forall>i\\<le>length l - 2. l ! i \\<noteq> FreeGroupMain.inverse (l ! (i + 1)) \\<Longrightarrow> reduced l\" by auto\n  from Cons have 2:\"\\<forall>i\\<le>length (a # l) - 2. (a # l) ! i \\<noteq> FreeGroupMain.inverse ((a # l) ! (i + 1))\"\n    by auto\n  hence red:\"reduced l\" \n    by (smt (z3) length_Cons Cons.IH Nat.le_diff_conv2 Suc_1 add.assoc add.commute add_diff_cancel_left' le_add1 nth_Cons_Suc plus_1_eq_Suc reduced.elims(3))\n  then show ?case \n  proof(cases l)\n    case (Cons b ls)\n    have \"a \\<noteq> inverse b\" using 2 Cons by fastforce\n    moreover have \"reduced (b#ls)\" using Cons red by auto\n    ultimately show ?thesis unfolding Cons by simp\n  qed(simp)\nqed (simp)\n\nlemma non_reducible_imp_non_trivial:\n  assumes \"\\<forall>i \\<le> (length l)-2 . (l!i) \\<noteq> inverse (l!(i+1))\" \"l \\<noteq> []\"\n  shows \"\\<not> (l ~ [])\"\n  using non_reducible_imp_red[OF assms(1)] assms(2) \n  using reduced.simps(1) reduced_cancel_eq reln_imp_cancels by blast \n\nlemma m_concat_singleton:\n  assumes \"x \\<in> carrier (freegroup S)\"\n  shows   \"monoid.m_concat (freegroup S) [x] = x\"\n  using assms \n  by (simp add: freegroup_is_group group.is_monoid)\n\nlemma list_in_span:\n  assumes \"\\<forall>x \\<in> set xs. x \\<in> S \\<times> {True, False}\"\n  shows \"xs \\<in> \\<langle>S\\<rangle>\"\n  using assms \nproof(induction xs)\n  case Nil\n  then show ?case \n    by (simp add: freewords_on_def words_on.empty)\nnext\n  case (Cons a xs)\n  then show ?case \n    by (metis freewords_on_def invgen_def list.set_intros(1) list.set_intros(2) words_on.gen) \nqed\n\nlemma empty_int_implies_nid:\n  assumes \"group G\"\n    \"A \\<inter> (m_inv G ` A) = {}\"\n  shows \"\\<one>\\<^bsub>G\\<^esub> \\<notin> A\"\n  using assms disjoint_iff group.is_monoid monoid.inv_one rev_image_eqI\n  by (metis)\n\nlemma assumes \"\\<not> (reduced ys)\"\n  shows \"\\<not> (reduced (xs@ys))\"\n  using assms \n  using reduced_leftappend by blast\n\nlemma inverse_in_reduced_lists:\n  assumes \"reduced l\" \"length l > 1\"\n  shows \"\\<forall>i \\<le> length l - 2.  (l!i) \\<noteq> inverse (l!(i+1))\" \nproof(rule ccontr)\n  assume \"\\<not>(\\<forall>i \\<le> length l - 2.  (l!i) \\<noteq> inverse (l!(i+1)))\"\n  then obtain i where i:\"i \\<le> length l - 2\" \"(l!i) = inverse (l!(i+1))\" by blast\n  hence \"drop (i - 1) l = (l!i)#(l!(i+1))#(drop (i+1) l)\"\n    using assms \n    by (metis Suc_leI add.right_neutral add_Suc_right add_less_le_mono inv_not_reduced inverse_of_inverse le_add_diff_inverse one_add_one plus_1_eq_Suc zero_less_one)\n  hence \"\\<not> (reduced (drop (i - 1) l))\" using i(2) by simp\n  hence \"\\<not> (reduced l)\" using i(1) assms \n    by (metis append_take_drop_id reduced_leftappend)\n  thus False using assms(1) by auto\nqed\n\nlemma inverse_in_reduced_embedlists:\n  assumes \"reduced l\" \"length l > 1\"\n  shows \"\\<forall>i \\<le> length l - 2.  [(l!i)] \\<noteq> wordinverse [ (l!(i+1))]\" \n  using inverse_in_reduced_lists assms by auto\nlemma inv_in_freegp:\n  assumes \"[x] \\<in> \\<langle>S\\<rangle>\"\n  shows \"inv\\<^bsub>freegroup S\\<^esub> (reln_tuple \\<langle>S\\<rangle> `` {[x]}) \n        = reln_tuple \\<langle>S\\<rangle> `` {wordinverse [x]}\" \n  using assms unfolding freegroup_def \n  by (metis freegroup_def freegroup_is_group group.wordinverse_inv partial_object.select_convs(1) quotientI)\n\nlemma red_imp_no_cons_inv:\n  assumes \"reduced l\" \"length l > 1\" \"l \\<in> \\<langle>S\\<rangle>\"\n  shows \"\\<forall>i \\<le> length l - 2.  reln_tuple \\<langle>S\\<rangle> `` {[(l!i)]} \n                \\<noteq> inv\\<^bsub>freegroup S\\<^esub> (reln_tuple \\<langle>S\\<rangle> `` {[(l!(i+1))]})\" \nproof(rule ccontr)\n  assume \"\\<not> (\\<forall>i \\<le> length l - 2.  reln_tuple \\<langle>S\\<rangle> `` {[(l!i)]} \\<noteq> inv\\<^bsub>freegroup S\\<^esub> (reln_tuple \\<langle>S\\<rangle> `` {[(l!(i+1))]}))\"\n  then obtain i where i:\"i \\<le> length l - 2\" \n      \"reln_tuple \\<langle>S\\<rangle> `` {[(l!i)]} = inv\\<^bsub>freegroup S\\<^esub> (reln_tuple \\<langle>S\\<rangle> `` {[(l!(i+1))]})\" by blast\n  hence l_i_in:\"[(l!i)] \\<in> \\<langle>S\\<rangle>\" using assms \n    by (metis Nat.le_diff_conv2 add.commute add_leD1 cons_span discrete freewords_on_def id_take_nth_drop one_add_one rightappend_span)\n  with i have l_Si_in:\"[(l!(i+1))] \\<in> \\<langle>S\\<rangle>\" using assms \n    by (metis (no_types, lifting) Suc_leI add.right_neutral add_Suc_right add_less_le_mono cons_span freewords_on_def id_take_nth_drop le_add_diff_inverse one_add_one one_less_numeral_iff plus_1_eq_Suc rightappend_span semiring_norm(76))\n  hence \"inv\\<^bsub>freegroup S\\<^esub> (reln_tuple \\<langle>S\\<rangle> `` {[(l!(i+1))]}) \n        = reln_tuple \\<langle>S\\<rangle> `` {wordinverse [(l!(i+1))]}\" using inv_in_freegp by blast\n  with i(2) have \"reln_tuple \\<langle>S\\<rangle> `` {[(l!i)]} = reln_tuple \\<langle>S\\<rangle> ``  {wordinverse [(l!(i+1))]}\"\n    by argo\n  hence \"[(l!i)] ~ wordinverse [(l!(i+1))]\" using l_i_in l_Si_in  unfolding reln_tuple_def \n    by (meson \\<open>reln_tuple \\<langle>S\\<rangle> `` {[l ! i]} = reln_tuple \\<langle>S\\<rangle> `` {wordinverse [l ! (i + 1)]}\\<close> span_wordinverse word_problem_not_eq)\n  hence \"(l!i) = inverse (l!(i+1))\" \n    by (metis append_Nil assms i(1) inverse_in_reduced_embedlists reduced.simps(2) reduced_cancel_eq reln_imp_cancels wordinverse.simps(1) wordinverse.simps(2))\n  moreover have \"drop (i - 1) l= (l!i)# inverse (l!(i+1))#(drop (i + 1) l)\" \n    using i(1) \n    using assms(1) assms(2) calculation inverse_in_reduced_lists by blast\n  hence \"\\<not> (reduced (drop (i - 1) l))\" \n    using assms(1) assms(2) calculation i(1) inverse_in_reduced_lists by blast \n  hence \"\\<not> (reduced l)\" using reduced_leftappend i(1) \n    by (metis append_take_drop_id)\n  thus False using assms(1) by auto\nqed\n\nlemma in_span_imp_invggen:\n  assumes \"x \\<in> set l\"\n  \"l \\<in> \\<langle>S\\<rangle>\"\nshows \"x \\<in> S \\<times> {True, False}\" using assms\nproof(induction l)\n  case (Cons a l)\n  then show ?case \n  proof(cases \"x \\<in> set l\")\n    case True\n    hence \"l \\<in> \\<langle>S\\<rangle>\" using Cons(3) \n      using freewords_on_def span_cons by blast\n    then show ?thesis using Cons True by argo\n  next\n    case False\n    hence \"[a] \\<in> \\<langle>S\\<rangle>\" using cons_span Cons freewords_on_def \n      by blast\n    hence \"a \\<in> S \\<times> {True, False}\" using freewords_on_def \n      by (metis gen_spanset invgen_def list.sel(1) list.simps(3))\n    then show ?thesis using Cons False by simp\n  qed\nqed( auto)\n\n\n\nlemma inv_in_freegrp_word:\n  assumes\"x \\<in> S\"\n  shows \" (reln_tuple \\<langle>S\\<rangle> `` {[(x, False)]}) = inv \\<^bsub>freegroup S\\<^esub> (reln_tuple \\<langle>S\\<rangle> `` {[(x, True)]})\"\n  using assms inv_in_freegp[of \"(x,True)\" S] wordinverse_def \n  by (metis append.left_neutral image_subset_iff inclusion_def inclusion_subset_spanset inverse.simps(1) wordinverse.simps(1) wordinverse.simps(2))          \n\nlemma liftgen_inv_eq:\n  \"liftgen_inv S = (\\<lambda> x. reln_tuple \\<langle>S\\<rangle> `` {[(x, False)]})  ` S\"\n   unfolding liftgen_inv_def\n   liftgen_def inclusion_def using inv_in_freegrp_word by (blast)\n\nlemma inv_liftgen_in_union:\n  assumes \"x \\<in> (liftgen S) \\<union> (liftgen_inv S)\"\n  shows \"inv \\<^bsub>freegroup S\\<^esub> x \\<in> (liftgen S) \\<union> (liftgen_inv S)\"\nproof(cases \"x \\<in>  (liftgen S)\")\n  case True\n  then show ?thesis unfolding liftgen_inv_def by simp \nnext\n  case False\n  hence \"x \\<in> (liftgen_inv S)\" using assms by force\n  hence \"inv \\<^bsub>freegroup S\\<^esub> x \\<in> (liftgen S)\" unfolding liftgen_inv_def \n    by (metis (no_types, lifting) freegroup_is_group group.inv_inv imageE liftgen_subset subset_iff)\n  then show ?thesis by blast\nqed\n\ntext \\<open>The following lemma establishes that the group generated by a subset of a \ngroup is free, if and only if every non reducible word in the span of the subset is\n not identity. This corresponds to the lemma 1.9 of Lyndon and Schupp.\\<close>\n\nlemma (in group)fg_with_basis_eq_cond:\n  assumes \" A \\<inter> (m_inv G ` A) = {}\" \"A \\<subseteq> carrier G\"\n  shows  \"(fg_with_basis (G\\<lparr>carrier := \\<langle>A\\<rangle>\\<^bsub>G\\<^esub>\\<rparr>) A) \n            \\<longleftrightarrow> (\\<forall>w \\<in> \\<langle>A\\<rangle>\\<^bsub>G\\<^esub>. non_reducible G A w \\<longrightarrow> w \\<noteq> \\<one>\\<^bsub>G\\<^esub>)\"\nproof\n  assume fg:\"fg_with_basis (G\\<lparr>carrier := \\<langle>A\\<rangle>\\<^bsub>G\\<^esub>\\<rparr>) A\"\n  have \"\\<one>\\<^bsub>G\\<^esub> \\<notin> A\" using assms(1) disjoint_iff group.is_monoid image_eqI monoid.inv_one\n    by (metis is_group)\n  define G_A where \"G_A = (G\\<lparr>carrier := \\<langle>A\\<rangle>\\<^bsub>G\\<^esub>\\<rparr>)\"\n  hence carrier_eq:\"\\<langle>A\\<rangle>\\<^bsub>G_A\\<^esub> = carrier (G_A)\" using fg \n    by (meson fg_with_basis_def)\n  then obtain \"\\<phi>\" \"S\" where \\<phi>_S:\"\\<phi> \\<in> iso G_A (freegroup (S:: (unit \\<times> 'a) set))\" \n           \"\\<phi> ` A = (liftgen S)\" using fg unfolding fg_with_basis_def G_A_def by auto\n  hence bij_to_liftset:\"bij_betw \\<phi> A (liftgen S)\" using \\<phi>_S(1) carrier_eq  bij_betw_subset \n    unfolding G_A_def\n    by (metis (no_types, lifting) Group.iso_def  gen_span.gen_gens mem_Collect_eq subsetI)  \n  have subgp:\" \\<langle>A\\<rangle>\\<^bsub>G\\<^esub> \\<le> G\" using assms(2) group.gen_subgroup_is_subgroup[of G A] is_group  \n    by blast\n  have grp:\"group (G_A)\" using subgroup.subgroup_is_group[OF subgp is_group] unfolding \n   G_A_def .\n  have A_subset:\"A \\<subseteq> carrier G_A\" using is_group unfolding G_A_def \n    by (simp add: gen_span.gen_gens subset_eq)\n  have m_inv_eq:\"m_inv G ` A = m_inv G_A ` A\"  \n  proof\n    show \" m_inv G ` A \\<subseteq> m_inv G_A ` A\"\n    proof \n      fix y\n      assume \"y \\<in> m_inv G ` A\"\n      then obtain x where \"x \\<in> A\" \"y = m_inv G x\" by blast\n      then have \"y \\<in> carrier (G_A)\" using A_subset is_group\n        by (metis G_A_def  group.incl_subgroup group.subgroup_self grp subgp subgroup.m_inv_closed subsetD)\n      then show \"y \\<in> m_inv G_A ` A \" using is_group\n        by (metis G_A_def \\<open>x \\<in> A\\<close> \\<open>y = inv\\<^bsub>G\\<^esub> x\\<close>  gen_span.intros(2) group.m_inv_consistent image_iff subgp)\n    qed\n  next\n    show \" m_inv G_A ` A \\<subseteq> m_inv G ` A\"\n    proof\n      fix y\n      assume \"y \\<in> m_inv G_A ` A\"\n      then obtain x where \"x \\<in> A\" \"y = m_inv G_A x\" by blast\n      then have \"y \\<in> carrier (G)\" using A_subset carrier_eq G_A_def is_group\n        by (metis G_A_def  gen_span.gen_gens group.inv_closed group.m_inv_consistent subgp subgroup.mem_carrier)\n      then show \"y \\<in> m_inv G ` A \" \n        by (simp add: G_A_def \\<open>x \\<in> A\\<close> \\<open>y = inv\\<^bsub>G_A\\<^esub> x\\<close> is_group gen_span.gen_gens group.m_inv_consistent subgp)\n    qed\n  qed\n  show \"\\<forall>w\\<in>\\<langle>A\\<rangle>\\<^bsub>G\\<^esub>. non_reducible G A w \\<longrightarrow> w \\<noteq> \\<one>\\<^bsub>G\\<^esub>\"\n  proof(rule ccontr)\n    assume \"\\<not> (\\<forall>w\\<in>\\<langle>A\\<rangle>\\<^bsub>G\\<^esub>. non_reducible G A w \\<longrightarrow> w \\<noteq> \\<one>\\<^bsub>G\\<^esub>)\"\n    then obtain w where w:\"w \\<in> (\\<langle>A\\<rangle>\\<^bsub>G\\<^esub>)\" \"(non_reducible G A w)\" \"(w = \\<one>\\<^bsub>G\\<^esub>)\" by simp\n    have  \"\\<exists> ls. \\<phi> w = monoid.m_concat (freegroup S) ls \\<and> ls \\<noteq> [] \\<and> \n                         (\\<forall>x \\<in> set ls. x \\<in> liftgen S \\<union> (liftgen_inv S)) \n               \\<and> ((length ls = 1) \\<or> (\\<forall>i \\<le> (length ls)-2 . ls!i \\<noteq> inv\\<^bsub>(freegroup S)\\<^esub> (ls!(i+1))))\"\n    proof-\n      obtain l where l:\"w = monoid.m_concat G l\" \"\\<forall>x \\<in> set l. x \\<in> A \\<union> (m_inv G ` A)\" \"l \\<noteq> []\"\n        \"length l = 1 \\<or> (\\<forall>i \\<le> (length l)-2 . l!i \\<noteq> inv\\<^bsub>G\\<^esub> (l!(i+1)))\"\n        using w(2) unfolding non_reducible_def by blast\n      hence \"w = monoid.m_concat  G_A l\" using carrier_eq G_A_def by simp\n      hence  mod_w:\"w = foldr (\\<otimes>\\<^bsub>G_A\\<^esub>) l \\<one>\\<^bsub>G_A\\<^esub>\" unfolding G_A_def by auto\n      have l_set_in:\"\\<forall> x \\<in> set l. x \\<in> carrier (G\\<lparr>carrier := \\<langle>A\\<rangle>\\<^bsub>G\\<^esub>\\<rparr>)\" \n        using l(2) assms(2) is_group liftgen_inv_in_carrier  carrier_eq \n        unfolding G_A_def using G_A_def\n      proof-\n         have \"A \\<subseteq> \\<langle>A\\<rangle>\\<^bsub>G\\<lparr>carrier := \\<langle>A\\<rangle>\\<rparr>\\<^esub>\" \n           using G_A_def A_subset carrier_eq by blast\n         moreover have \"m_inv G ` A \\<subseteq> \\<langle>A\\<rangle>\\<^bsub>G\\<lparr>carrier := \\<langle>A\\<rangle>\\<rparr>\\<^esub>\" \n           by (metis G_A_def carrier_eq gen_span.gen_gens group.subgroup_self grp image_subsetI incl_subgroup subgp subgroupE(3))\n         ultimately show ?thesis using l(2) \n           by (metis G_A_def Un_subset_iff carrier_eq in_mono)\n       qed\n      let ?ls = \"map \\<phi> l\"\n      have ls_nonempty:\"?ls \\<noteq> []\" using l(3) by blast\n      have hom_phi:\"\\<phi> \\<in> hom G_A (freegroup S)\" using \\<phi>_S(1) unfolding iso_def by blast\n      have \"\\<phi> w = monoid.m_concat (freegroup S) ?ls\" \n        using hom_preserves_m_concat[OF grp freegroup_is_group[of S] hom_phi mod_w] l(2) \n        using G_A_def l_set_in by fastforce\n      have loc_eq:\"set ?ls = \\<phi> ` (set l)\" by simp\n       have ls_in:\"\\<forall>x \\<in> set ?ls. x \\<in> (liftgen S) \\<union> (liftgen_inv S)\"\n       proof-\n         have \" \\<phi> ` A = liftgen S\" using bij_to_liftset unfolding bij_betw_def by argo\n         moreover have \"\\<phi> ` m_inv G_A ` A = m_inv F\\<^bsub>S\\<^esub> ` liftgen S\"\n           using bij_to_invset[OF \\<phi>_S(1) grp freegroup_is_group A_subset bij_to_liftset] \n           unfolding bij_betw_def by argo\n         ultimately show ?thesis  unfolding liftgen_inv_def \n         using in_map_of_union[of \"set l\" \"A\" \"m_inv G_A ` A\" \"\\<phi>\"] l(2) m_inv_eq unfolding loc_eq \n         by simp\n     qed\n      moreover have \"(length ?ls = 1) \\<or> (\\<forall>i \\<le> (length ?ls)-2 . ?ls!i \\<noteq> inv\\<^bsub>(freegroup S)\\<^esub> (?ls!(i+1)))\"\n      proof(cases \"length ?ls = 1\")\n        case False\n        have \"(\\<forall>i \\<le> (length ?ls)-2 . ?ls!i \\<noteq> inv\\<^bsub>(freegroup S)\\<^esub> (?ls!(i+1)))\"\n        proof(rule ccontr)\n          assume \"\\<not> (\\<forall>i\\<le>length (map \\<phi> l) - 2. map \\<phi> l ! i \\<noteq> inv\\<^bsub>(freegroup S)\\<^esub> (?ls!(i+1)))\"\n          then obtain i where i:\"i \\<le> length ?ls -2\" \"?ls!i = inv\\<^bsub>(freegroup S)\\<^esub> (?ls!(i+1))\" by blast\n          have \"i+1 \\<le> length ?ls - 1\" using i(1) ls_nonempty False \n            by (metis (no_types, lifting) One_nat_def Suc_1 Suc_eq_plus1 Suc_leI diff_diff_add le_neq_implies_less length_greater_0_conv ordered_cancel_comm_monoid_diff_class.le_diff_conv2) \n          hence ls_iSi:\"?ls!(i+1) \\<in> set ?ls\" by auto\n          have \"?ls!i \\<in> set ?ls\"  using i(1) nth_mem[of i \"?ls\"] l(3)\n            by (metis (no_types, lifting) diff_less_mono2 diff_zero le_neq_implies_less length_greater_0_conv less_trans list.map_disc_iff nat_1_add_1 plus_1_eq_Suc zero_less_Suc)\n          moreover have ls_i:\"?ls!i \\<in> carrier (freegroup S)\" using ls_in  liftgen_subset[of S] \n            using calculation  \n            by (meson Un_least liftgen_inv_in_carrier subset_iff) \n          moreover have ls_Si:\"?ls!(i+1) \\<in> carrier (freegroup S)\" using ls_in  liftgen_subset[of S]\n            using calculation ls_in ls_iSi \n            using liftgen_inv_in_carrier by blast   \n          ultimately have \"(?ls!i) \\<otimes>\\<^bsub>(freegroup S)\\<^esub> (?ls!(i+1)) =  \\<one>\\<^bsub>(freegroup S)\\<^esub>\"\n            using ls_in freegroup_is_group i(2) \n            by (metis group.l_inv)  \n          have li:\"l ! i \\<in> carrier (G_A)\" using i ls_i \\<phi>_S(1) \n            by (metis G_A_def Suc_1 diff_less l(3) l_set_in le_neq_implies_less length_greater_0_conv length_map less_trans nth_mem zero_less_Suc)\n          hence l_i_in:\" l ! i \\<in> \\<langle>A\\<rangle>\\<^bsub>G\\<^esub>\" unfolding G_A_def by simp \n          have lSi:\"l ! (i+1) \\<in> carrier (G_A)\" using i(1) ls_Si \\<phi>_S(1)\n            by (metis G_A_def One_nat_def Suc_pred \\<open>i + 1 \\<le> length (map \\<phi> l) - 1\\<close> l_set_in le_imp_less_Suc length_map length_pos_if_in_set ls_iSi nth_mem)        \n          then have \"\\<phi> (l ! i) \\<otimes>\\<^bsub>(freegroup S)\\<^esub> \\<phi> (l ! (i+1)) =  \\<one>\\<^bsub>(freegroup S)\\<^esub>\"\n            using i(1)\n            by (metis (no_types, lifting) One_nat_def Suc_eq_plus1 Suc_pred \\<open>i + 1 \\<le> length (map \\<phi> l) - 1\\<close> \\<open>map \\<phi> l ! i \\<otimes>\\<^bsub>F\\<^bsub>S\\<^esub>\\<^esub> map \\<phi> l ! (i + 1) = \\<one>\\<^bsub>F\\<^bsub>S\\<^esub>\\<^esub>\\<close> dual_order.refl le_imp_less_Suc length_map length_pos_if_in_set less_trans ls_iSi nth_map)\n          then have \"\\<phi> (l ! i \\<otimes>\\<^bsub>G_A\\<^esub> (l ! (i + 1))) = \\<one>\\<^bsub>(freegroup S)\\<^esub>\" using \\<phi>_S(1)\n            unfolding iso_def using hom_mult[of \\<phi> G_A \"F\\<^bsub>S\\<^esub>\"] li lSi by blast\n          then have \"l ! i \\<otimes>\\<^bsub>G_A\\<^esub> (l ! (i + 1)) =  \\<one>\\<^bsub>G_A\\<^esub>\"  using \\<phi>_S(1) \n            by (smt (verit) freegroup_is_group group.is_monoid group.iso_iff_group_isomorphisms group_isomorphisms_def grp hom_one lSi li monoid.m_closed)\n          then have l_i_inv:\"l ! i = inv\\<^bsub>G_A\\<^esub> (l ! (i + 1))\" \n            by (metis group.inv_equality grp lSi li)\n          hence l_i_inv_G:\"l ! i = inv\\<^bsub>G\\<^esub> (l ! (i + 1))\" unfolding G_A_def\n            using Group.group.m_inv_consistent[OF is_group subgp l_i_in] \n            by (metis G_A_def is_group group.inv_inv grp lSi l_i_in subgp subgroup.mem_carrier) \n          moreover have \"length l = length (map \\<phi> l)\" by simp\n          hence \"i \\<le> length l - 2\" \n            using i(1) by presburger\n          ultimately have \"\\<exists> i \\<le> length l - 2. l ! i  = inv\\<^bsub>G_A\\<^esub> l ! (i + 1)\" using l_i_inv\n            by blast\n          then show False using l(4) l_i_inv_G \n          using \\<open>i \\<le> length l - 2\\<close> \n          by (metis False \\<open>length l = length (map \\<phi> l)\\<close>)\n      qed\n      then show ?thesis by blast\n    qed (blast)     \n    then show ?thesis \n      using \\<open>\\<phi> w = foldr (\\<otimes>\\<^bsub>F\\<^bsub>S\\<^esub>\\<^esub>) (map \\<phi> l) \\<one>\\<^bsub>F\\<^bsub>S\\<^esub>\\<^esub>\\<close> ls_in ls_nonempty by blast\n  qed\n  then obtain ls where ls:\"\\<phi> w = monoid.m_concat (freegroup S) ls\" \"ls \\<noteq> []\" \n                         \"\\<forall>x \\<in> set ls. x \\<in> liftgen S \\<union> (liftgen_inv S)\"\n        \"length ls = 1 \\<or> (\\<forall>i \\<le> (length ls)-2 . ls!i \\<noteq> inv\\<^bsub>(freegroup S)\\<^esub> (ls!(i+1)))\" \n    by auto   \n  define w' where \"w' = \\<phi> w\"\n  hence w':\"\\<phi> w = w'\" by auto\n  then have \"\\<phi> w \\<noteq> \\<one>\\<^bsub>F\\<^bsub>S\\<^esub>\\<^esub>\" \n  proof(cases \"length ls = 1\")\n    case True\n    then obtain x  where x:\"x \\<in> liftgen S \\<or> x \\<in> liftgen_inv S\" \"ls = [x]\" using ls(3)\n      by (metis One_nat_def Un_iff length_0_conv length_Suc_conv list.set_intros(1))\n    then have \\<phi>_w_is:\"\\<phi> w = x\" using ls(1) m_concat_singleton \n      using liftgen_inv_in_carrier liftgen_subset by blast\n    then show ?thesis\n    proof(cases \"x \\<in> liftgen S\")\n      case True\n      then obtain s where s:\"x = reln_tuple \\<langle>S\\<rangle> `` {\\<iota> s}\" \"s \\<in> S\"  unfolding liftgen_def by blast\n      then have i_s:\"\\<iota> s = [(s, True)]\" unfolding inclusion_def by auto\n      then have s_in: \"\\<iota> s \\<in> \\<langle>S\\<rangle>\" \n        by (meson image_subset_iff inclusion_subset_spanset s(2))\n      moreover have \"reduced [(s, True)]\" by simp\n      hence \"\\<not>([(s, True)] ~ [])\" \n        using reduced.simps(1) reduced_cancel_eq reln_imp_cancels by blast\n      hence \"x \\<noteq> \\<one>\\<^bsub>F\\<^bsub>S\\<^esub>\\<^esub>\" using  word_problem_not_eq_id[OF s_in] i_s unfolding s(1) by simp\n      then show ?thesis  unfolding \\<phi>_w_is .\n    next\n      case False\n      then obtain y where y:\"y \\<in> liftgen S\" \"y = inv\\<^bsub>freegroup S\\<^esub> x\" using x(1) \n        by (metis (no_types, lifting) freegroup_is_group group.inv_inv imageE liftgen_inv_def liftgen_subset subsetD)\n        then obtain s where s:\"y = reln_tuple \\<langle>S\\<rangle> `` {\\<iota> s}\" \"s \\<in> S\"  unfolding liftgen_def by blast\n      then have i_s:\"\\<iota> s = [(s, True)]\" unfolding inclusion_def by auto\n      then have s_in: \"\\<iota> s \\<in> \\<langle>S\\<rangle>\" \n        by (meson image_subset_iff inclusion_subset_spanset s(2))\n      moreover have \"reduced [(s, True)]\" by simp\n      hence \"\\<not>([(s, True)] ~ [])\" \n        using reduced.simps(1) reduced_cancel_eq reln_imp_cancels by blast\n      hence \"y \\<noteq> \\<one>\\<^bsub>F\\<^bsub>S\\<^esub>\\<^esub>\" using  word_problem_not_eq_id[OF s_in] i_s unfolding s(1) by simp\n      hence \"x \\<noteq> \\<one>\\<^bsub>F\\<^bsub>S\\<^esub>\\<^esub>\" using y(2) \n        by (metis (no_types, lifting) freegroup_is_group gen_span.gen_one group.inv_eq_1_iff group.span_liftgen subset_eq)\n      then show ?thesis unfolding \\<phi>_w_is . \n    qed\n  next\n    case False\n    hence \"\\<forall>i \\<le> (length ls)-2 . ls!i \\<noteq> inv\\<^bsub>(freegroup S)\\<^esub> (ls!(i+1))\" using ls(4) by auto\n    then obtain l where l:\"(\\<forall> x \\<in> set l. x \\<in> S \\<times> {True, False})\"\n    \"(ls = map (\\<lambda> x. (reln_tuple \\<langle>S\\<rangle> `` {[x]})) l)\" using False ls(2) exist_of_proj[OF ls(3)] by auto\n    from     non_reduced_projection[OF ls(3) l(2) ] ls(2,4) False\n    have inv_cond:\"\\<forall>i\\<le>length l - 2. l ! i \\<noteq> FreeGroupMain.inverse (l ! (i + 1))\" \n      by (meson le_neq_implies_less length_0_conv less_one not_less)\n    have l_in:\"l \\<in> \\<langle>S\\<rangle>\" using list_in_span[OF l(1)] .\n    hence \"\\<not> (l ~ [])\" using non_reducible_imp_non_trivial[OF inv_cond] l(2) ls(2) by blast\n    hence \"reln_tuple \\<langle>S\\<rangle> `` {l} \\<noteq> \\<one>\\<^bsub>F\\<^bsub>S\\<^esub>\\<^esub>\" using word_problem_not_eq_id[OF l_in] \n      by argo\n    moreover have \"reln_tuple \\<langle>S\\<rangle> `` {l} = \\<phi> w \" using reln_tuple_eq[OF l_in] unfolding ls(1) l(2) .\n    ultimately show ?thesis by argo\n  qed\n  then have \"w \\<noteq> \\<one>\\<^bsub>G_A\\<^esub>\" using \\<phi>_S(1) unfolding iso_def \n    by (meson \\<phi>_S(1) freegroup_is_group grp hom_one iso_imp_homomorphism)\n  then have \"w \\<noteq> \\<one>\\<^bsub>G\\<^esub>\" using subgp unfolding G_A_def by simp\n  then show False using w(3) by argo\nqed\nnext\n  assume case_asm:\"\\<forall>w\\<in>\\<langle>A\\<rangle>\\<^bsub>G\\<^esub>. non_reducible G A w \\<longrightarrow> w \\<noteq> \\<one>\\<^bsub>G\\<^esub>\"\n  define S where \"S = {()} \\<times> A\"\n  define G_A where \"G_A = (G\\<lparr>carrier := \\<langle>A\\<rangle>\\<^bsub>G\\<^esub>\\<rparr>)\"\n  hence carrier_eq:\"carrier (G_A) = \\<langle>A\\<rangle>\\<^bsub>G\\<^esub>\" by auto\n  then have \"(\\<lambda>(x,y). y) \\<in> S \\<rightarrow> carrier G\" using assms S_def by force\n  then obtain h  where h:\"h \\<in> hom (freegroup S) G\"\n    \"\\<forall>x\\<in>S. (\\<lambda>(a,b). b)  x = h (reln_tuple \\<langle>S\\<rangle> `` {\\<iota> x})\"\n    using exists_hom  by blast\n  hence group_hom_G:\"group_hom (freegroup S) G h\" \n    by (simp add: h(1) freegroup_is_group group_hom.intro group_hom_axioms_def)\n  have subgp:\" \\<langle>A\\<rangle>\\<^bsub>G\\<^esub> \\<le> G\" using assms(2) group.gen_subgroup_is_subgroup[of G A] is_group  \n    by blast\n  have grp:\"group (G_A)\" using subgroup.subgroup_is_group[OF subgp is_group] unfolding \n   G_A_def .\n  have A_subset:\"A \\<subseteq> carrier G_A\" unfolding G_A_def using is_group \n    using subgp subgroup.subgroup_is_group \n    by (simp add: gen_span.gen_gens subsetI)\n  have \"h ` (liftgen S) = A\" using S_def h(2) unfolding liftgen_def by auto\n  hence h_to:\"h ` (carrier (freegroup S)) =  \\<langle>A\\<rangle>\\<^bsub>G\\<^esub>\" using h(1) group_hom.hom_span[OF group_hom_G] \n    by (metis liftgen_span liftgen_subset span_liftgen subset_antisym)  \n  hence h_in:\"h \\<in> hom (freegroup S) G_A\" using carrier_eq hom_to_subgp[OF h(1)] \n    unfolding G_A_def by presburger\n  hence group_hom_G_A:\"group_hom (freegroup S) G_A h\" \n    using  group_hom.intro[OF freegroup_is_group grp] group_hom_axioms_def by blast\n  then have surj:\"h ` (carrier (freegroup S)) = carrier (G_A)\" using h_to unfolding G_A_def by simp \n  have h_S_inv:\"\\<forall>x\\<in>S. inv\\<^bsub>G\\<^esub> ((\\<lambda>(a,b). b)  x) = h (reln_tuple \\<langle>S\\<rangle> `` {[(x, False)]})\"\n  proof\n    fix x\n    assume x:\"x \\<in> S\"\n    hence in_carr:\"(reln_tuple \\<langle>S\\<rangle> `` {\\<iota> x}) \\<in> carrier (freegroup S)\" unfolding freegroup_def \n      by (metis image_subset_iff inclusion_subset_spanset partial_object.select_convs(1) proj_def proj_preserves)\n    hence \" (reln_tuple \\<langle>S\\<rangle> `` {[(x, False)]}) = inv \\<^bsub>freegroup S \\<^esub> (reln_tuple \\<langle>S\\<rangle> `` {\\<iota> x})\"\n      using inv_in_freegrp_word[OF x] unfolding inclusion_def by argo\n    moreover have \"h (inv \\<^bsub>freegroup S \\<^esub> (reln_tuple \\<langle>S\\<rangle> `` {\\<iota> x})) = inv\\<^bsub>G\\<^esub> ((\\<lambda>(a,b). b)  x)\"\n      using x Group.group_hom.hom_inv[OF group_hom_G in_carr] h(2) by auto\n    ultimately show \"inv\\<^bsub>G\\<^esub> ((\\<lambda>(a,b). b)  x) = h (reln_tuple \\<langle>S\\<rangle> `` {[(x, False)]})\" by argo\n  qed\n  hence h_to:\"\\<forall>x \\<in> S \\<times> {True, False}. h (reln_tuple \\<langle>S\\<rangle> `` {[x]}) \\<in> A \\<union> (m_inv G ` A)\"\n    using h(2) unfolding S_def inclusion_def by simp\n  have bij_liftgen_A:\"bij_betw h (liftgen S) A\" \n  proof(rule bij_betwI)\n    show \"h \\<in> liftgen S \\<rightarrow> A\" using h \n      using \\<open>h ` liftgen S = A\\<close> by blast\n  next  \n    define g where \"g = (\\<lambda> x. (reln_tuple \\<langle>S\\<rangle> `` {\\<iota> ((),x)}))\"\n    hence \"g ` A \\<subseteq> liftgen S\" unfolding S_def liftgen_def by blast\n    thus \"g \\<in> A \\<rightarrow> liftgen S\" by auto\n  next\n    fix x\n    assume \"x \\<in> liftgen S\"\n    then obtain y where y:\"y \\<in> S\" \"x = reln_tuple \\<langle>S\\<rangle> `` {\\<iota> y}\" unfolding liftgen_def \n      by blast\n    hence \"h x = snd y\" using h(2) \n      by (simp add: snd_def)\n    thus \"reln_tuple \\<langle>S\\<rangle> `` {\\<iota> ((), h x)} = x\" using y unfolding S_def by auto\n  next\n    fix y\n    assume \"y \\<in> A\"\n    hence \"((),y) \\<in> S\" unfolding S_def by auto\n    thus \"h (reln_tuple \\<langle>S\\<rangle> `` {\\<iota> ((), y)}) = y\" using h(1) unfolding S_def \n      using S_def h(2) by auto\n  qed\n  have bij_liftgen_inv_A:\"bij_betw h (liftgen_inv S)  (m_inv G ` A)\" unfolding liftgen_inv_eq\n  proof(rule bij_betwI)\n    show \"h \\<in> (\\<lambda>x. reln_tuple \\<langle>S\\<rangle> `` {[(x, False)]}) ` S \\<rightarrow> m_inv G ` A\"\n      using h h_S_inv unfolding S_def by force\n  next\n    define g where \"g \\<equiv> \\<lambda> x. (reln_tuple \\<langle>S\\<rangle> `` {[(((),(inv\\<^bsub>G\\<^esub> x)), False)]})\"\n    have \"\\<forall>y \\<in> m_inv G ` A. inv\\<^bsub>G\\<^esub>  y \\<in> A\" \n      using assms(2) by auto\n    have \"g ` (m_inv G) ` A \\<subseteq>(\\<lambda>x. reln_tuple \\<langle>S\\<rangle> `` {[(x, False)]}) ` S\" \n    proof\n      fix y\n      assume y:\"y \\<in> g ` (m_inv G) ` A \"\n      then obtain x where x:\"x \\<in> A\" \"y = g (inv\\<^bsub>G\\<^esub> x)\" by blast\n      hence \"g (inv\\<^bsub>G\\<^esub> x) =  reln_tuple \\<langle>S\\<rangle> `` {[(((),x), False)]}\" \n        using assms(2) g_def by auto\n      moreover have \"((),x) \\<in> S\" using x(1) unfolding S_def by blast\n      ultimately show \"y \\<in>(\\<lambda>x. reln_tuple \\<langle>S\\<rangle> `` {[(x, False)]}) ` S\" \n        using x(2) by blast \n    qed\n    thus \"g \\<in> m_inv G ` A \\<rightarrow> (\\<lambda>x. reln_tuple \\<langle>S\\<rangle> `` {[(x, False)]}) ` S\" by fast\n  next\n    fix x\n    assume \"x \\<in> (\\<lambda>x. reln_tuple \\<langle>S\\<rangle> `` {[(x, False)]}) ` S\"\n    then obtain y where y:\"((),y) \\<in> S\" \"reln_tuple \\<langle>S\\<rangle> `` {[(((),y), False)]} = x\" \n      using S_def  by blast\n    hence \"h x = inv y\" using h_S_inv by force\n    hence \"y = inv (h x)\" \n      by (metis S_def assms(2) inv_inv mem_Sigma_iff subsetD y(1))\n    thus \"reln_tuple \\<langle>S\\<rangle> `` {[(((), inv h x), False)]} = x\" using y(2) by argo\n  next\n    fix y\n    assume \"y \\<in> m_inv G ` A \"\n    then obtain x where x:\"x \\<in> A\" \"y = inv x\" by blast\n    hence y_inv:\"x = inv y\" \n      by (metis assms(2) inv_inv subsetD)\n    hence \"((),x) \\<in> S\" using x(1) S_def by force\n    thus \"h (reln_tuple \\<langle>S\\<rangle> `` {[(((), inv y), False)]}) = y\" using h_S_inv y_inv \n      using x(2) by fastforce\n  qed\n  have bij_h:\"bij_betw h ((liftgen S) \\<union> (liftgen_inv S)) (A \\<union> (m_inv G ` A))\"\n    using  bij_betw_combine[OF bij_liftgen_A  bij_liftgen_inv_A assms(1)] . \n  moreover have \"\\<forall>w \\<in> carrier (freegroup S). w \\<noteq> \\<one>\\<^bsub>freegroup S\\<^esub> \\<longrightarrow>  h w \\<noteq> \\<one>\\<^bsub>G_A\\<^esub>\"\n  proof-\n    {fix w\n    assume in_fgp:\"w \\<in> carrier (freegroup S)\"\n    assume neq_one:\"w \\<noteq>  \\<one>\\<^bsub>freegroup S\\<^esub>\"\n    obtain ls where ls:\"w = reln_tuple  \\<langle>S\\<rangle> `` {ls}\" \"ls \\<in> \\<langle>S\\<rangle>\" using in_fgp unfolding freegroup_def \n      by (simp, meson quotientE)\n    define l where \"l = (reduce^^(length ls)) ls\"\n    have l_rel_ls:\"l ~ ls\" \n      using cancels_imp_rel iter_cancels_to l_def reln.sym by blast\n    moreover have l_not_rel:\"\\<not> (l ~ [])\" using neq_one ls word_problem_notrel[OF ls(2) ] ls(1) unfolding l_def\n      by fastforce\n    moreover have red_l:\"reduced l\" \n      by (simp add: l_def reduced_iter_length)   \n    hence \"reduce l = l\" \n      by (simp add: reduced_reduce)\n    hence iter_l:\"(reduce^^(length l)) l = l\" \n      using cancels_imp_iter l_def l_rel_ls reln_imp_cancels by blast\n    moreover have l_in_S:\"l \\<in> \\<langle>S\\<rangle>\" using ls(2) l_def \n      using cancels_to_preserves iter_cancels_to by blast\n    moreover have w_is_l:\"w = reln_tuple  \\<langle>S\\<rangle> `` {l}\" using ls l_in_S iter_l l_def \n      using word_problem_eq by blast  \n    hence w_decompose:\"w = monoid.m_concat (freegroup S) (map (\\<lambda>x.(reln_tuple \\<langle>S\\<rangle> `` {[x]})) l)\"\n      by (simp add: l_in_S reln_tuple_eq)\n    have \"h w \\<noteq> \\<one>\\<^bsub>G_A\\<^esub>\"\n    proof(cases \"length l = 1\")\n      case True                                                                          \n      then obtain s where s:\"l = [s]\" \"s \\<in> S \\<times> {True, False}\"\n        using l_in_S unfolding freewords_on_def invgen_def words_on_def \n        by (metis (no_types, lifting) length_Cons add_cancel_right_left le_zero_eq length_0_conv mem_Collect_eq not_one_le_zero words_onp.cases)\n      then obtain x where x:\"x \\<in> A\" \"fst s = ((), x)\" unfolding S_def by auto    \n      then show ?thesis\n      proof(cases \"snd s\")\n        case True\n        hence l_is_fst_s:\"l = \\<iota> (fst s)\" unfolding inclusion_def using s by force\n        hence  \"w = (reln_tuple \\<langle>S\\<rangle> `` {l})\" using w_decompose \n          using w_is_l by blast  \n        hence \"h w = x\" using l_is_fst_s x s h(2) \n          by fastforce \n        moreover have \"x \\<noteq> \\<one>\\<^bsub>G\\<^esub>\" using empty_int_implies_nid[OF is_group assms(1)] x(1) by blast\n        ultimately show ?thesis unfolding G_A_def by simp \n      next\n        case False\n        hence l_is_fst_s:\"l = wordinverse (\\<iota> (fst s))\" unfolding inclusion_def using s by force\n        hence  w_is:\"w = (reln_tuple \\<langle>S\\<rangle> `` {l})\" using w_decompose \n          using w_is_l by blast \n        define w' where \"w' = (reln_tuple \\<langle>S\\<rangle> `` {\\<iota> (fst s)})\"\n        hence w_inv_w':\"w = inv \\<^bsub>freegroup S\\<^esub> w'\" using w_is wordinverse_inv unfolding l_is_fst_s \n          by (metis freegroup_is_group group.inv_inv in_fgp wordinverse_of_wordinverse)  \n        hence \"w' =  inv \\<^bsub>freegroup S\\<^esub> w\" \n          by (metis in_fgp l_is_fst_s w'_def w_is wordinverse_inv wordinverse_of_wordinverse)\n        hence \"w' \\<in> carrier (freegroup S)\" \n          by (meson group.inv_closed group_hom.axioms(1) group_hom_G_A in_fgp)\n        hence h_eq:\"h w = inv\\<^bsub>G\\<^esub> (h w')\" using h(1) in_fgp unfolding w_inv_w' \n          by (meson group_hom.hom_inv group_hom_G)\n        hence \"h w' = x\" unfolding w'_def using l_is_fst_s x s h(2) \n          by fastforce \n        moreover have \"x \\<noteq> \\<one>\\<^bsub>G\\<^esub>\" using empty_int_implies_nid[OF is_group assms(1)] x(1) by blast\n        ultimately have \"h w \\<noteq> \\<one>\\<^bsub>G\\<^esub>\" using h_eq \n          by (metis \\<open>w' = inv\\<^bsub>F\\<^bsub>S\\<^esub>\\<^esub> w\\<close> group_hom.hom_inv group_hom_G in_fgp inv_one)\n        thus ?thesis unfolding G_A_def by simp \n      qed\n    next\n      case False\n      hence \"length l> 1\" using l_not_rel\n        using nat_neq_iff by fastforce\n      define ls0 where \"ls0 = map (\\<lambda>x. (reln_tuple \\<langle>S\\<rangle> `` {[x]})) l\"\n      have \"w = monoid.m_concat (freegroup S) ls0\" using w_decompose ls0_def by auto\n      moreover have ls0i:\"\\<forall>i \\<le> length ls0 - 2. (ls0!i) \\<noteq> inv\\<^bsub>freegroup S\\<^esub> (ls0!(i+1))\"\n        using red_imp_no_cons_inv[OF red_l] False l_in_S unfolding ls0_def \n        by (smt (verit, del_insts) One_nat_def \\<open>1 < length l\\<close> add.commute add_lessD1 diff_is_0_eq' le_add_diff_inverse2 le_neq_implies_less length_map nat_1_add_1 nat_add_left_cancel_less nat_le_linear not_add_less2 nth_map plus_1_eq_Suc zero_less_Suc)\n      have helper:\"(\\<lambda>x. reln_tuple \\<langle>S\\<rangle> `` {[x]}) ` (S \\<times> {True, False})\n                    =  (\\<lambda>x. reln_tuple \\<langle>S\\<rangle> `` {[(x, True)]}) ` S  \\<union>  (\\<lambda>x. reln_tuple \\<langle>S\\<rangle> `` {[(x, False)]}) ` S\"\n\n        proof(rule equalityI, rule subsetI)\n          fix x\n          assume \"x \\<in>  (\\<lambda>x. reln_tuple \\<langle>S\\<rangle> `` {[x]}) ` (S \\<times> {True, False})\"\n          then obtain y where y:\"y \\<in> S \\<times> {True, False}\" \"x = reln_tuple \\<langle>S\\<rangle> `` {[y]}\" by force\n          hence \"x = reln_tuple \\<langle>S\\<rangle> `` {[(fst y, True)]} \\<or>  x = reln_tuple \\<langle>S\\<rangle> `` {[(fst y, False)]}\"\n            apply(cases \"snd y\") apply force by force\n          thus \"x \\<in> (\\<lambda>x. reln_tuple \\<langle>S\\<rangle> `` {[(x, True)]}) ` S  \\<union>  (\\<lambda>x. reln_tuple \\<langle>S\\<rangle> `` {[(x, False)]}) ` S\"\n            using y(1) by force\n        next\n          show \" (\\<lambda>x. reln_tuple \\<langle>S\\<rangle> `` {[(x, True)]}) ` S \\<union> (\\<lambda>x. reln_tuple \\<langle>S\\<rangle> `` {[(x, False)]}) ` S\n                  \\<subseteq> (\\<lambda>x. reln_tuple \\<langle>S\\<rangle> `` {[x]}) ` (S \\<times> {True, False}) \"\n          proof(rule subsetI)\n            fix x \n            assume x:\"x \\<in> (\\<lambda>x. reln_tuple \\<langle>S\\<rangle> `` {[(x, True)]}) ` S \\<union> (\\<lambda>x. reln_tuple \\<langle>S\\<rangle> `` {[(x, False)]}) ` S\"\n            then obtain y where y:\"y \\<in> S\" \"x = reln_tuple \\<langle>S\\<rangle> `` {[(y, True)]} \\<or>  x = reln_tuple \\<langle>S\\<rangle> `` {[(y, False)]}\"\n              by blast\n            show \"x \\<in>(\\<lambda>x. reln_tuple \\<langle>S\\<rangle> `` {[x]}) ` (S \\<times> {True, False})\"\n            proof(cases \"x  = reln_tuple \\<langle>S\\<rangle> `` {[(y, True)]}\")\n              case True\n              hence \"x = (\\<lambda> x. reln_tuple \\<langle>S\\<rangle> `` {[x]}) (y,True)\" using y by argo\n              thus ?thesis using y(1) by auto\n            next\n              case False\n              hence \"x = (\\<lambda> x. reln_tuple \\<langle>S\\<rangle> `` {[x]}) (y,False)\" using y(2) by argo\n              then show ?thesis using y(1) by auto\n            qed\n          qed\n        qed\n        have in_ls00:\"\\<forall>i \\<le> length ls0 - 1. (ls0!i) \\<in> (liftgen S) \\<union> (liftgen_inv S)\"\n        proof-\n          {fix j\n          assume loc_j:\"j \\<le> length ls0 - 1\"\n          hence 1:\"ls0!j = reln_tuple \\<langle>S\\<rangle> `` {[l!j]}\" using ls0_def \n            using \\<open>1 < length l\\<close> by auto\n          moreover have l_j:\"l!j \\<in> S \\<times> {True, False}\" using l_in_S in_span_imp_invggen[of \"ls!j\" l S]\n            using loc_j \n            by (metis (mono_tags, lifting) One_nat_def Suc_pred \\<open>1 < length l\\<close> in_span_imp_invggen le_imp_less_Suc length_0_conv length_greater_0_conv length_map ls0_def not_add_less2 nth_mem plus_1_eq_Suc)\n          ultimately have \"reln_tuple \\<langle>S\\<rangle> `` {[l!j]} \\<in> (\\<lambda>x. reln_tuple \\<langle>S\\<rangle> `` {[x]}) ` (S \\<times> {True, False})\"\n            using loc_j by simp \n          have \" (\\<lambda>x. reln_tuple \\<langle>S\\<rangle> `` {[x]}) ` (S \\<times> {True, False}) \n                    =  (\\<lambda>x. reln_tuple \\<langle>S\\<rangle> `` {[(x, True)]}) ` S  \\<union>  (\\<lambda>x. reln_tuple \\<langle>S\\<rangle> `` {[(x, False)]}) ` S\"\n            using helper by auto\n          moreover have \"ls0!j \\<in> (\\<lambda>x. reln_tuple \\<langle>S\\<rangle> `` {[x]}) ` (S \\<times> {True, False})\"\n            using 1 l_j by force\n          ultimately have \"ls0 ! j \\<in> liftgen S \\<union> liftgen_inv S\" \n                unfolding liftgen_inv_eq liftgen_def inclusion_def  \n                by auto\n            }\n           thus ?thesis by auto\n         qed\n      have len_ls0:\"length ls0 > 1\" using False ls0_def \n        using \\<open>1 < length l\\<close> by force\n      hence in_set_ls0:\"\\<forall>l \\<in> set ls0. l \\<in> (liftgen S) \\<union> (liftgen_inv S)\" using False ls0_def in_ls00 \n        by (smt (verit) One_nat_def Suc_pred diff_commute diff_diff_cancel diff_is_0_eq'\n in_set_conv_nth less_imp_le_nat nat_le_linear zero_less_diff) \n      have non_cancel_in_ls0:\"\\<forall>i \\<le> length ls0 - 2. (h (ls0!i)) \\<noteq> inv\\<^bsub>G\\<^esub> (h (ls0!(i+1)))\"\n      proof-\n        {fix i\n        assume i_len:\"i \\<le> length ls0 - 2\"\n        hence \"i \\<le> length l - 2\" using ls0_def by simp\n        hence l_i_in_Sinvgen:\"l!i \\<in>  S\\<^sup>\\<plusminus>\" using l_in_S in_span_imp_invggen[of \"ls!i\" l S] \n          by (metis diff_less in_span_imp_invggen invgen_def l_not_rel le_neq_implies_less length_greater_0_conv less_trans nat_1_add_1 nth_mem plus_1_eq_Suc reln.refl zero_less_Suc)\n        hence  l_Si_in_Sinvgen:\"l!(i+1) \\<in>  S\\<^sup>\\<plusminus>\" using l_in_S in_span_imp_invggen[of \"ls!(i+1)\" l S] \n          by (metis One_nat_def Suc_pred \\<open>1 < length l\\<close> \\<open>i \\<le> length l - 2\\<close> diff_diff_left in_span_imp_invggen invgen_def le_imp_less_Suc less_diff_conv nat_1_add_1 nth_mem zero_less_diff)\n        hence \"h (ls0!i) \\<in> A \\<union> (m_inv G ` A)\" unfolding ls0_def using h_to l_i_in_Sinvgen unfolding invgen_def\n          by (metis (no_types, lifting) One_nat_def \\<open>1 < length l\\<close> \\<open>i \\<le> length l - 2\\<close> diff_less le_neq_implies_less less_trans nat_1_add_1 nth_map plus_1_eq_Suc zero_less_Suc)\n        hence a:\"(ls0!i) \\<in> (liftgen S) \\<union> (liftgen_inv S)\" using i_len in_ls00 by auto\n        have b:\"(ls0!(i+1)) \\<in> (liftgen S) \\<union> (liftgen_inv S)\" using in_ls00 i_len \n          using One_nat_def Suc_pred \\<open>1 < length l\\<close> add.commute add_le_cancel_left \n                diff_diff_add length_map ls0_def one_add_one plus_1_eq_Suc zero_less_diff \n          by (smt (z3))\n        have \"(h (ls0!i)) \\<noteq> inv\\<^bsub>G\\<^esub> (h (ls0!(i+1)))\"\n        proof(rule ccontr)\n          assume \" \\<not> h (ls0 ! i) \\<noteq> inv h (ls0 ! (i + 1))\"\n          hence 1:\"h (ls0 ! i) = inv h (ls0 ! (i + 1))\" by simp \n          have \"h (inv\\<^bsub>freegroup S\\<^esub> (ls0 ! (i + 1))) = inv h (ls0 ! (i + 1))\"\n            using b Group.group_hom.hom_inv[OF group_hom_G] \n            using liftgen_inv_in_carrier liftgen_subset by blast  \n          hence \"h (ls0!i) = h (inv\\<^bsub>freegroup S\\<^esub> (ls0 ! (i + 1)))\" \n            using 1 by auto\n          hence \"ls0!i = inv\\<^bsub>freegroup S\\<^esub> (ls0 ! (i + 1))\" using bij_h a inv_liftgen_in_union[OF b] \n            unfolding bij_betw_def inj_on_def \n            by meson\n          thus False using ls0i i_len by simp\n        qed\n      }\n      then show ?thesis by blast\n    qed \n    hence w_is:\"w = monoid.m_concat (freegroup S) ls0\" using w_decompose ls0_def by argo\n    hence \"h w = monoid.m_concat G (map h ls0)\" \n      using h(1) hom_preserves_m_concat[OF freegroup_is_group[of S] is_group h(1) w_is] \n       in_set_ls0 \n      by (meson Un_iff liftgen_inv_in_carrier liftgen_subset subset_iff)\n    moreover have \"\\<forall>x \\<in> set (map h ls0). x \\<in> A \\<union> m_inv G ` A\"\n      using bij_h in_ls00 in_set_ls0 \n      using bij_betw_imp_surj_on by fastforce\n    moreover have \"\\<forall>i \\<le> (length (map h ls0))-2 . (map h ls0)!i \\<noteq> inv\\<^bsub>G\\<^esub> ((map h ls0)!(i+1))\"\n      using non_cancel_in_ls0 \n      by (smt (verit) Nat.le_diff_conv2 add.commute add_2_eq_Suc' add_leD2 diff_is_0_eq' le_neq_implies_less le_numeral_extra(4) len_ls0 length_map less_numeral_extra(4) less_one less_trans nat_le_linear nth_map plus_1_eq_Suc)\n    ultimately have \"non_reducible G A (h w)\" unfolding non_reducible_def using False len_ls0 \n      by (smt (verit, ccfv_threshold) add_lessD1 le0 le_Suc_ex len_ls0 length_greater_0_conv map_is_Nil_conv)\n    hence \"h w \\<noteq> \\<one>\\<^bsub>G\\<^esub>\" using case_asm by auto\n    then show ?thesis unfolding G_A_def by simp\n  qed}\n  thus ?thesis by auto\n  qed \n  hence h_iso:\"h \\<in> iso (freegroup S) G_A\" using group_hom.group_hom_isoI[OF group_hom_G_A] surj \n    by blast\n  then obtain g where g:\"group_isomorphisms G_A (freegroup S) g h\" \n    using group.iso_iff_group_isomorphisms[OF freegroup_is_group[of S]] h_iso \n    using group_isomorphisms_sym by blast\n  hence g_iso:\"g \\<in> iso G_A (freegroup S)\" \n    using group_isomorphisms_imp_iso by blast\n  have g_map:\"g  ` A = (liftgen S)\" \n   proof\n    {fix y\n      assume \"y \\<in> g ` A\"\n      hence \"y \\<in> g ` (h ` (liftgen S))\" using bij_liftgen_A unfolding bij_betw_def by meson\n      \n      then obtain s where x:\"y = g (h s)\" \"s \\<in> liftgen S\" by blast\n      moreover then have \"g (h s) = s\" using liftgen_subset[of S] g \n        unfolding group_isomorphisms_def by fast\n      ultimately have \"y \\<in> liftgen S\" by argo}\n    thus \"g ` A \\<subseteq> liftgen S\" by blast\n  next\n    {fix y\n      assume y:\"y \\<in> liftgen S\"\n      hence \"h y \\<in> A\" using bij_liftgen_A unfolding bij_betw_def by blast\n      moreover then have \"g (h y) = y\" using g assms(2) unfolding group_isomorphisms_def G_A_def \n        by (meson liftgen_subset subsetD y)\n      ultimately have \"y \\<in> g ` A\" using y by blast}\n    thus \"liftgen S \\<subseteq> g ` A\" by auto\n  qed\n  have \"\\<langle>A\\<rangle>\\<^bsub>G\\<lparr>carrier := \\<langle>A\\<rangle>\\<rparr>\\<^esub> = carrier (G\\<lparr>carrier := \\<langle>A\\<rangle>\\<rparr>)\" \n  proof-\n    have \"\\<langle>A\\<rangle>\\<^bsub>G\\<lparr>carrier := \\<langle>A\\<rangle>\\<rparr>\\<^esub> = \\<langle>A\\<rangle>\" \n    proof\n      show  \"\\<langle>A\\<rangle>\\<^bsub>G\\<lparr>carrier := \\<langle>A\\<rangle>\\<rparr>\\<^esub> \\<subseteq> \\<langle>A\\<rangle>\" \n        using G_A_def A_subset carrier_eq group.gen_span_closed grp by blast\n    next\n      show  \"\\<langle>A\\<rangle> \\<subseteq> \\<langle>A\\<rangle>\\<^bsub>G\\<lparr>carrier := \\<langle>A\\<rangle>\\<rparr>\\<^esub>\" \n      proof\n        fix x\n        assume \"x \\<in> \\<langle>A\\<rangle>\"\n        thus \"x \\<in> \\<langle>A\\<rangle>\\<^bsub>G\\<lparr>carrier := \\<langle>A\\<rangle>\\<rparr>\\<^esub>\"\n        proof(induction x rule:gen_span.induct)\n          case gen_one\n          then show ?case using assms(2) is_group \n            by (metis G_A_def carrier_eq gen_span.gen_one group.gen_subgroup_is_subgroup group.l_cancel_one' grp subgroup.mem_carrier subgroup_mult_equality) \n        next\n          case (gen_gens x)\n          then show ?case \n            by (simp add: gen_span.gen_gens)  \n        next\n          case (gen_inv x)\n          then show ?case \n            by (metis gen_span.gen_inv m_inv_consistent subgp)\n        next\n          case (gen_mult x y)\n          then show ?case \n            by (metis gen_span.gen_mult subgp subgroup_mult_equality)\n        qed \n      qed\n    qed\n    thus ?thesis using carrier_eq unfolding G_A_def by argo\n  qed\n  thus \"fg_with_basis (G\\<lparr>carrier := \\<langle>A\\<rangle>\\<^bsub>G\\<^esub>\\<rparr>) A\"  unfolding fg_with_basis_def\n    using g_iso carrier_eq g_map unfolding G_A_def by blast\nqed\n\n\nend", "meta": {"author": "aabid-tkcs", "repo": "groupabelle", "sha": "master", "save_path": "github-repos/isabelle/aabid-tkcs-groupabelle", "path": "github-repos/isabelle/aabid-tkcs-groupabelle/groupabelle-main/Freegroup_with_Basis.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8791467770088162, "lm_q2_score": 0.8311430562234878, "lm_q1q2_score": 0.7306967391121366}}
{"text": "(*  \n  Title:    Preference_Profiles.thy\n  Author:   Manuel Eberl, TU M\u00fcnchen\n\n  Definition of (weak) preference profiles and functions for building\n  and manipulating them\n*)\n\nsection \\<open>Preference Profiles\\<close>\n\ntheory Preference_Profiles\nimports\n  Main \n  Order_Predicates \n  \"HOL-Library.Multiset\"\n  \"HOL-Library.Disjoint_Sets\"\nbegin\n\ntext \\<open>The type of preference profiles\\<close>\ntype_synonym ('agent, 'alt) pref_profile = \"'agent \\<Rightarrow> 'alt relation\"\n\nlocale preorder_family = \n  fixes dom :: \"'a set\" and carrier :: \"'b set\" and R :: \"'a \\<Rightarrow> 'b relation\"\n  assumes nonempty_dom: \"dom \\<noteq> {}\"\n  assumes in_dom [simp]: \"i \\<in> dom \\<Longrightarrow> preorder_on carrier (R i)\"\n  assumes not_in_dom [simp]: \"i \\<notin> dom \\<Longrightarrow> \\<not>R i x y\"\nbegin\n\n\n\nend\n\n\nlocale pref_profile_wf =\n  fixes agents :: \"'agent set\" and alts :: \"'alt set\" and R :: \"('agent, 'alt) pref_profile\"\n  assumes nonempty_agents [simp]: \"agents \\<noteq> {}\" and nonempty_alts [simp]: \"alts \\<noteq> {}\"\n  assumes prefs_wf [simp]: \"i \\<in> agents \\<Longrightarrow> finite_total_preorder_on alts (R i)\"\n  assumes prefs_undefined [simp]: \"i \\<notin> agents \\<Longrightarrow> \\<not>R i x y\"\nbegin\n\nlemma finite_alts [simp]: \"finite alts\"\nproof -\n  from nonempty_agents obtain i where \"i \\<in> agents\" by blast\n  then interpret finite_total_preorder_on alts \"R i\" by simp\n  show ?thesis by (rule finite_carrier)\nqed\n\nlemma prefs_wf' [simp]:\n  \"i \\<in> agents \\<Longrightarrow> total_preorder_on alts (R i)\" \"i \\<in> agents \\<Longrightarrow> preorder_on alts (R i)\"\n  using prefs_wf[of i]\n  by (simp_all add: finite_total_preorder_on_def total_preorder_on_def del: prefs_wf)\n\nlemma not_outside: \n  assumes \"x \\<preceq>[R i] y\"\n  shows   \"i \\<in> agents\" \"x \\<in> alts\" \"y \\<in> alts\"\nproof -\n  from assms show \"i \\<in> agents\" by (cases \"i \\<in> agents\") auto\n  then interpret preorder_on alts \"R i\" by simp\n  from assms show \"x \\<in> alts\" \"y \\<in> alts\" by (simp_all add: not_outside)\nqed\n\nsublocale preorder_family agents alts R\n  by (intro preorder_family.intro) simp_all\n\nlemmas prefs_undefined' = not_in_dom'\n\nlemma wf_update:\n  assumes \"i \\<in> agents\" \"total_preorder_on alts Ri'\"\n  shows   \"pref_profile_wf agents alts (R(i := Ri'))\"\nproof -\n  interpret total_preorder_on alts Ri' by fact\n  from finite_alts have \"finite_total_preorder_on alts Ri'\" by unfold_locales\n  with assms show ?thesis\n    by (auto intro!: pref_profile_wf.intro split: if_splits)\nqed\n\nlemma wf_permute_agents:\n  assumes \"\\<sigma> permutes agents\"\n  shows   \"pref_profile_wf agents alts (R \\<circ> \\<sigma>)\"\n  unfolding o_def using permutes_in_image[OF assms(1)]\n  by (intro pref_profile_wf.intro prefs_wf) simp_all\n\nlemma (in -) pref_profile_eqI:\n  assumes \"pref_profile_wf agents alts R1\" \"pref_profile_wf agents alts R2\"\n  assumes \"\\<And>x. x \\<in> agents \\<Longrightarrow> R1 x = R2 x\"\n  shows   \"R1 = R2\"\nproof\n  interpret R1: pref_profile_wf agents alts R1 by fact\n  interpret R2: pref_profile_wf agents alts R2 by fact\n  fix x show \"R1 x = R2 x\"\n    by (cases \"x \\<in> agents\"; intro ext) (simp_all add: assms(3)) \nqed\n\nend\n\n\ntext \\<open>\n  Permutes a preference profile w.r.t. alternatives in the way described in the paper.\n  This is needed for the definition of neutrality.\n\\<close>\ndefinition permute_profile where\n  \"permute_profile \\<sigma> R = (\\<lambda>i x y. R i (inv \\<sigma> x) (inv \\<sigma> y))\"\n  \nlemma permute_profile_map_relation:\n  \"permute_profile \\<sigma> R = (\\<lambda>i. map_relation (inv \\<sigma>) (R i))\"\n  by (simp add: permute_profile_def map_relation_def)\n\nlemma permute_profile_compose [simp]:\n  \"permute_profile \\<sigma> (R \\<circ> \\<pi>) = permute_profile \\<sigma> R \\<circ> \\<pi>\"\n  by (auto simp: fun_eq_iff permute_profile_def o_def)\n\nlemma permute_profile_id [simp]: \"permute_profile id R = R\"\n  by (simp add: permute_profile_def)\n\nlemma permute_profile_o:\n  assumes \"bij f\" \"bij g\"\n  shows   \"permute_profile f (permute_profile g R) = permute_profile (f \\<circ> g) R\"\n  using assms by (simp add: permute_profile_def o_inv_distrib)\n\nlemma (in pref_profile_wf) wf_permute_alts:\n  assumes \"\\<sigma> permutes alts\"\n  shows   \"pref_profile_wf agents alts (permute_profile \\<sigma> R)\"\nproof (rule pref_profile_wf.intro)\n  fix i assume \"i \\<in> agents\"\n  with assms interpret R: finite_total_preorder_on alts \"R i\" by simp\n    \n  from assms have [simp]: \"inv \\<sigma> x \\<in> alts \\<longleftrightarrow> x \\<in> alts\" for x\n    by (simp add: permutes_in_image permutes_inv)\n\n  show \"finite_total_preorder_on alts (permute_profile \\<sigma> R i)\"\n  proof\n    fix x y assume \"permute_profile \\<sigma> R i x y\"\n    thus \"x \\<in> alts\" \"y \\<in> alts\"\n      using R.not_outside[of \"inv \\<sigma> x\" \"inv \\<sigma> y\"]\n      by (auto simp: permute_profile_def)\n  next\n    fix x y z assume \"permute_profile \\<sigma> R i x y\" \"permute_profile \\<sigma> R i y z\"\n    thus \"permute_profile \\<sigma> R i x z\"\n      using R.trans[of \"inv \\<sigma> x\" \"inv \\<sigma> y\" \"inv \\<sigma> z\"] \n      by (simp_all add: permute_profile_def)\n  qed (insert R.total R.refl R.finite_carrier, simp_all add: permute_profile_def)\nqed (insert assms, simp_all add: permute_profile_def pref_profile_wf_def)\n\n\ntext \\<open>\n  This shows that the above definition is equivalent to that in the paper.  \n\\<close>\nlemma permute_profile_iff [simp]:\n  fixes R :: \"('agent, 'alt) pref_profile\"\n  assumes \"\\<sigma> permutes alts\" \"x \\<in> alts\" \"y \\<in> alts\"\n  defines \"R' \\<equiv> permute_profile \\<sigma> R\"\n  shows   \"\\<sigma> x \\<preceq>[R' i] \\<sigma> y \\<longleftrightarrow> x \\<preceq>[R i] y\"\n  using assms by (simp add: permute_profile_def permutes_inverses)\n\n\nsubsection \\<open>Pareto dominance\\<close>\n\ndefinition Pareto :: \"('agent \\<Rightarrow> 'alt relation) \\<Rightarrow> 'alt relation\" where\n  \"x \\<preceq>[Pareto(R)] y \\<longleftrightarrow> (\\<exists>j. x \\<preceq>[R j] x) \\<and> (\\<forall>i. x \\<preceq>[R i] x \\<longrightarrow> x \\<preceq>[R i] y)\"\n\ntext \\<open>\n  A Pareto loser is an alternative that is Pareto-dominated by some other alternative.\n\\<close>\ndefinition pareto_losers :: \"('agent, 'alt) pref_profile \\<Rightarrow> 'alt set\" where\n  \"pareto_losers R = {x. \\<exists>y. y \\<succ>[Pareto(R)] x}\"\n\nlemma pareto_losersI [intro?, simp]: \"y \\<succ>[Pareto(R)] x \\<Longrightarrow> x \\<in> pareto_losers R\"\n  by (auto simp: pareto_losers_def)\n\ncontext preorder_family\nbegin\n\nlemma Pareto_iff:\n  \"x \\<preceq>[Pareto(R)] y \\<longleftrightarrow> (\\<forall>i\\<in>dom. x \\<preceq>[R i] y)\"\nproof\n  assume A: \"x \\<preceq>[Pareto(R)] y\"\n  then obtain j where j: \"x \\<preceq>[R j] x\" by (auto simp: Pareto_def)\n  hence j': \"j \\<in> dom\" by (cases \"j \\<in> dom\") auto\n  then interpret preorder_on carrier \"R j\" by simp\n  from j have \"x \\<in> carrier\" by (auto simp: carrier_eq)\n  with A preorder_on.refl[OF in_dom]\n    show \"(\\<forall>i\\<in>dom. x \\<preceq>[R i] y)\" by (auto simp: Pareto_def)\nnext\n  assume A: \"(\\<forall>i\\<in>dom. x \\<preceq>[R i] y)\"\n  from nonempty_dom obtain j where j: \"j \\<in> dom\" by blast\n  then interpret preorder_on carrier \"R j\" by simp \n  from j A have \"x \\<preceq>[R j] y\" by simp\n  hence \"x \\<preceq>[R j] x\" using not_outside refl by blast\n  with A show \"x \\<preceq>[Pareto(R)] y\" by (auto simp: Pareto_def)\nqed\n\nlemma Pareto_strict_iff: \n  \"x \\<prec>[Pareto(R)] y \\<longleftrightarrow> (\\<forall>i\\<in>dom. x \\<preceq>[R i] y) \\<and> (\\<exists>i\\<in>dom. x \\<prec>[R i] y)\"\n  by (auto simp: strongly_preferred_def Pareto_iff nonempty_dom)\n\nlemma Pareto_strictI:\n  assumes \"\\<And>i. i \\<in> dom \\<Longrightarrow> x \\<preceq>[R i] y\" \"i \\<in> dom\" \"x \\<prec>[R i] y\"\n  shows   \"x \\<prec>[Pareto(R)] y\"\n  using assms by (auto simp: Pareto_strict_iff)\n\nlemma Pareto_strictI':\n  assumes \"\\<And>i. i \\<in> dom \\<Longrightarrow> x \\<preceq>[R i] y\" \"i \\<in> dom\" \"\\<not>x \\<succeq>[R i] y\"\n  shows   \"x \\<prec>[Pareto(R)] y\"\nproof -\n  from assms interpret preorder_on carrier \"R i\" by simp\n  from assms have \"x \\<prec>[R i] y\" by (simp add: strongly_preferred_def)\n  with assms show ?thesis by (auto simp: Pareto_strict_iff )\nqed\n\n\nsublocale Pareto: preorder_on carrier \"Pareto(R)\"\nproof -\n  have \"preorder_on carrier (R i)\" if \"i \\<in> dom\" for i using that by simp_all\n  note A = preorder_on.not_outside[OF this(1)] preorder_on.refl[OF this(1)]\n           preorder_on.trans[OF this(1)]\n  from nonempty_dom obtain i where i: \"i \\<in> dom\" by blast\n  show \"preorder_on carrier (Pareto R)\"\n  proof\n    fix x y assume \"x \\<preceq>[Pareto(R)] y\"\n    with A(1,2)[OF i] i show \"x \\<in> carrier\" \"y \\<in> carrier\" by (auto simp: Pareto_iff)\n  qed (auto simp: Pareto_iff intro: A)\nqed\n\nlemma pareto_loser_in_alts: \n  assumes \"x \\<in> pareto_losers R\"\n  shows   \"x \\<in> carrier\"\nproof -\n  from assms obtain y i where \"i \\<in> dom\" \"x \\<prec>[R i] y\"\n    by (auto simp: pareto_losers_def Pareto_strict_iff)\n  then interpret preorder_on carrier \"R i\" by simp\n  from \\<open>x \\<prec>[R i] y\\<close> have \"x \\<preceq>[R i] y\" by (simp add: strongly_preferred_def)\n  thus \"x \\<in> carrier\" using not_outside by simp\nqed\n\nlemma pareto_losersE:\n  assumes \"x \\<in> pareto_losers R\"\n  obtains y where \"y \\<in> carrier\" \"y \\<succ>[Pareto(R)] x\"\nproof -\n  from assms obtain y where y: \"y \\<succ>[Pareto(R)] x\" unfolding pareto_losers_def by blast\n  with Pareto.not_outside[of x y] have \"y \\<in> carrier\" \n    by (simp add: strongly_preferred_def)\n  with y show ?thesis using that by blast\nqed\n\nend\n\n\nsubsection \\<open>Preferred alternatives\\<close>\n\ncontext pref_profile_wf\nbegin\n\nlemma preferred_alts_subset_alts: \"preferred_alts (R i) x \\<subseteq> alts\" (is ?A)\n  and finite_preferred_alts [simp,intro!]: \"finite (preferred_alts (R i) x)\" (is ?B)\nproof -\n  have \"?A \\<and> ?B\"\n  proof (cases \"i \\<in> agents\")\n    assume \"i \\<in> agents\"\n    then interpret total_preorder_on alts \"R i\" by simp\n    have \"preferred_alts (R i) x \\<subseteq> alts\" using not_outside\n      by (auto simp: preferred_alts_def)\n    thus ?thesis by (auto dest: finite_subset)\n  qed (auto simp: preferred_alts_def)\n  thus ?A ?B by blast+\nqed\n\nlemma preferred_alts_altdef: \n  \"i \\<in> agents \\<Longrightarrow> preferred_alts (R i) x = {y\\<in>alts. y \\<succeq>[R i] x}\"\n  by (simp add: preorder_on.preferred_alts_altdef)  \n\nend\n\n\nsubsection \\<open>Favourite alternatives\\<close>\n\ndefinition favorites :: \"('agent, 'alt) pref_profile \\<Rightarrow> 'agent \\<Rightarrow> 'alt set\" where\n  \"favorites R i = Max_wrt (R i)\"\n\ndefinition favorite :: \"('agent, 'alt) pref_profile \\<Rightarrow> 'agent \\<Rightarrow> 'alt\" where\n  \"favorite R i = the_elem (favorites R i)\"\n\ndefinition has_unique_favorites :: \"('agent, 'alt) pref_profile \\<Rightarrow> bool\" where\n  \"has_unique_favorites R \\<longleftrightarrow> (\\<forall>i. favorites R i = {} \\<or> is_singleton (favorites R i))\"\n\ncontext pref_profile_wf\nbegin\n\nlemma favorites_altdef:\n  \"favorites R i = Max_wrt_among (R i) alts\"\nproof (cases \"i \\<in> agents\")\n  assume \"i \\<in> agents\"\n  then interpret total_preorder_on alts \"R i\" by simp\n  show ?thesis \n    by (simp add: favorites_def Max_wrt_total_preorder Max_wrt_among_total_preorder)\nqed (simp_all add: favorites_def Max_wrt_def Max_wrt_among_def pref_profile_wf_def)\n\nlemma favorites_no_agent [simp]: \"i \\<notin> agents \\<Longrightarrow> favorites R i = {}\"\n  by (auto simp: favorites_def Max_wrt_def Max_wrt_among_def)\n\nlemma favorites_altdef':\n  \"favorites R i = {x\\<in>alts. \\<forall>y\\<in>alts. x \\<succeq>[R i] y}\"\nproof (cases \"i \\<in> agents\")\n  assume \"i \\<in> agents\"\n  then interpret finite_total_preorder_on alts \"R i\" by simp\n  show ?thesis using Max_wrt_among_nonempty[of alts] Max_wrt_among_subset[of alts]\n    by (auto simp: favorites_altdef Max_wrt_among_total_preorder)\nqed simp_all\n\nlemma favorites_subset_alts: \"favorites R i \\<subseteq> alts\"\n  by (auto simp: favorites_altdef')\n\nlemma finite_favorites [simp, intro]: \"finite (favorites R i)\"\n  using favorites_subset_alts finite_alts  by (rule finite_subset)\n\nlemma favorites_nonempty: \"i \\<in> agents \\<Longrightarrow> favorites R i \\<noteq> {}\"\nproof -\n  assume \"i \\<in> agents\"\n  then interpret finite_total_preorder_on alts \"R i\" by simp\n  show ?thesis unfolding favorites_def by (intro Max_wrt_nonempty) simp_all\nqed\n\nlemma favorites_permute: \n  assumes i: \"i \\<in> agents\" and perm: \"\\<sigma> permutes alts\"\n  shows   \"favorites (permute_profile \\<sigma> R) i = \\<sigma> ` favorites R i\"\nproof -\n  from i interpret finite_total_preorder_on alts \"R i\" by simp\n  from perm show ?thesis\n  unfolding favorites_def\n    by (subst Max_wrt_map_relation_bij)\n       (simp_all add: permute_profile_def map_relation_def permutes_bij)\nqed\n\nlemma has_unique_favorites_altdef:\n  \"has_unique_favorites R \\<longleftrightarrow> (\\<forall>i\\<in>agents. is_singleton (favorites R i))\"\nproof safe\n  fix i assume \"has_unique_favorites R\" \"i \\<in> agents\"\n  thus \"is_singleton (favorites R i)\" using favorites_nonempty[of i]\n    by (auto simp: has_unique_favorites_def)\nnext\n  assume \"\\<forall>i\\<in>agents. is_singleton (favorites R i)\"\n  hence \"is_singleton (favorites R i) \\<or> favorites R i = {}\" for i\n    by (cases \"i \\<in> agents\") (simp add: favorites_nonempty, simp add: favorites_altdef')\n  thus \"has_unique_favorites R\" by (auto simp: has_unique_favorites_def)\nqed\n\nend\n\n\nlocale pref_profile_unique_favorites = pref_profile_wf agents alts R\n  for agents :: \"'agent set\" and alts :: \"'alt set\" and R +\n  assumes unique_favorites': \"has_unique_favorites R\"\nbegin\n  \nlemma unique_favorites: \"i \\<in> agents \\<Longrightarrow> favorites R i = {favorite R i}\"\n  using unique_favorites' \n  by (auto simp: favorite_def has_unique_favorites_altdef is_singleton_the_elem)\n\nlemma favorite_in_alts: \"i \\<in> agents \\<Longrightarrow> favorite R i \\<in> alts\"\n  using favorites_subset_alts[of i] by (simp add: unique_favorites)\n\nend\n\n  \n\nsubsection \\<open>Anonymous profiles\\<close>\n\ntype_synonym ('agent, 'alt) apref_profile = \"'alt set list multiset\"\n\ndefinition anonymous_profile :: \"('agent, 'alt) pref_profile \\<Rightarrow> ('agent, 'alt) apref_profile\" \n  where anonymous_profile_auxdef:\n    \"anonymous_profile R = image_mset (weak_ranking \\<circ> R) (mset_set {i. R i \\<noteq> (\\<lambda>_ _. False)})\"\n\nlemma (in pref_profile_wf) agents_eq:\n  \"agents = {i. R i \\<noteq> (\\<lambda>_ _. False)}\"\nproof safe\n  fix i assume i: \"i \\<in> agents\" and Ri: \"R i = (\\<lambda>_ _. False)\"\n  from i interpret preorder_on alts \"R i\" by simp\n  from carrier_eq Ri nonempty_alts show False by simp\nnext\n  fix i assume \"R i \\<noteq> (\\<lambda>_ _. False)\"\n  thus \"i \\<in> agents\" using prefs_undefined'[of i] by (cases \"i \\<in> agents\") auto\nqed\n\nlemma (in pref_profile_wf) anonymous_profile_def:\n  \"anonymous_profile R = image_mset (weak_ranking \\<circ> R) (mset_set agents)\"\n  by (simp only: agents_eq anonymous_profile_auxdef)\n\nlemma (in pref_profile_wf) anonymous_profile_permute:\n  assumes \"\\<sigma> permutes alts\"  \"finite agents\" \n  shows   \"anonymous_profile (permute_profile \\<sigma> R) = \n             image_mset (map ((`) \\<sigma>)) (anonymous_profile R)\"\nproof -\n  from assms(1) interpret R': pref_profile_wf agents alts \"permute_profile \\<sigma> R\"\n    by (rule wf_permute_alts)\n  have \"anonymous_profile (permute_profile \\<sigma> R) = \n          {#weak_ranking (map_relation (inv \\<sigma>) (R x)). x \\<in># mset_set agents#}\"\n    unfolding R'.anonymous_profile_def\n    by (simp add:  multiset.map_comp permute_profile_map_relation o_def)\n  also from assms have \"\\<dots> = {#map ((`) \\<sigma>) (weak_ranking (R x)). x \\<in># mset_set agents#}\"\n    by (intro image_mset_cong)\n       (simp add: finite_total_preorder_on.weak_ranking_permute[of alts])\n  also have \"\\<dots> = image_mset (map ((`) \\<sigma>)) (anonymous_profile R)\"\n    by (simp add: anonymous_profile_def multiset.map_comp o_def)\n  finally show ?thesis .\nqed\n\nlemma (in pref_profile_wf) anonymous_profile_update:\n  assumes i:  \"i \\<in> agents\" and fin [simp]: \"finite agents\" and \"total_preorder_on alts Ri'\"\n  shows   \"anonymous_profile (R(i := Ri')) =\n             anonymous_profile R - {#weak_ranking (R i)#} + {#weak_ranking Ri'#}\"\nproof -\n  from assms interpret R': pref_profile_wf agents alts \"R(i := Ri')\"\n    by (simp add: finite_total_preorder_on_iff wf_update)\n  have \"anonymous_profile (R(i := Ri')) = \n          {#weak_ranking (if x = i then Ri' else R x). x \\<in># mset_set agents#}\"\n    by (simp add: R'.anonymous_profile_def o_def)\n  also have \"\\<dots> = {#if x = i then weak_ranking Ri' else weak_ranking (R x). x \\<in># mset_set agents#}\"\n    by (intro image_mset_cong) simp_all\n  also have \"\\<dots> = {#weak_ranking Ri'. x \\<in># mset_set {x \\<in> agents. x = i}#} +\n                    {#weak_ranking (R x). x \\<in># mset_set {x \\<in> agents. x \\<noteq> i}#}\"\n    by (subst image_mset_If) ((subst filter_mset_mset_set, simp)+, rule refl)\n  also from i have \"{x \\<in> agents. x = i} = {i}\" by auto\n  also have \"{x \\<in> agents. x \\<noteq> i} = agents - {i}\" by auto\n  also have \"{#weak_ranking Ri'. x \\<in># mset_set {i}#} = {#weak_ranking Ri'#}\" by simp\n  also from i have \"mset_set (agents - {i}) = mset_set agents - {#i#}\"\n    by (simp add: mset_set_Diff)\n  also from i \n    have \"{#weak_ranking (R x). x \\<in># \\<dots>#} =\n            {#weak_ranking (R x). x \\<in># mset_set agents#} - {#weak_ranking (R i)#}\"\n      by (subst image_mset_Diff) (simp_all add: in_multiset_in_set mset_subset_eq_single)\n  also have \"{#weak_ranking Ri'#} + \\<dots> = \n               anonymous_profile R - {#weak_ranking (R i)#} + {#weak_ranking Ri'#}\"\n    by (simp add: anonymous_profile_def add_ac o_def)\n  finally show ?thesis .\nqed\n\n\nsubsection \\<open>Preference profiles from lists\\<close>\n\ndefinition prefs_from_table :: \"('agent \\<times> 'alt set list) list \\<Rightarrow> ('agent, 'alt) pref_profile\" where\n  \"prefs_from_table xss = (\\<lambda>i. case_option (\\<lambda>_ _. False) of_weak_ranking (map_of xss i))\"\n\ndefinition prefs_from_table_wf where\n  \"prefs_from_table_wf agents alts xss \\<longleftrightarrow> agents \\<noteq> {} \\<and> alts \\<noteq> {} \\<and> distinct (map fst xss) \\<and> \n       set (map fst xss) = agents \\<and> (\\<forall>xs\\<in>set (map snd xss). \\<Union>(set xs) = alts \\<and> \n       is_finite_weak_ranking xs)\"\n\nlemma prefs_from_table_wfI:\n  assumes \"agents \\<noteq> {}\" \"alts \\<noteq> {}\" \"distinct (map fst xss)\"\n  assumes \"set (map fst xss) = agents\"\n  assumes \"\\<And>xs. xs \\<in> set (map snd xss) \\<Longrightarrow> \\<Union>(set xs) = alts\"\n  assumes \"\\<And>xs. xs \\<in> set (map snd xss) \\<Longrightarrow> is_finite_weak_ranking xs\"\n  shows   \"prefs_from_table_wf agents alts xss\"\n  using assms unfolding prefs_from_table_wf_def by auto\n\nlemma prefs_from_table_wfD:\n  assumes \"prefs_from_table_wf agents alts xss\"\n  shows \"agents \\<noteq> {}\" \"alts \\<noteq> {}\" \"distinct (map fst xss)\"\n    and \"set (map fst xss) = agents\"\n    and \"\\<And>xs. xs \\<in> set (map snd xss) \\<Longrightarrow> \\<Union>(set xs) = alts\"\n    and \"\\<And>xs. xs \\<in> set (map snd xss) \\<Longrightarrow> is_finite_weak_ranking xs\"\n  using assms unfolding prefs_from_table_wf_def by auto\n       \nlemma pref_profile_from_tableI: \n  \"prefs_from_table_wf agents alts xss \\<Longrightarrow> pref_profile_wf agents alts (prefs_from_table xss)\"\nproof (intro pref_profile_wf.intro)\n  assume wf: \"prefs_from_table_wf agents alts xss\"\n  fix i assume i: \"i \\<in> agents\"\n  with wf have \"i \\<in> set (map fst xss)\" by (simp add: prefs_from_table_wf_def)\n  then obtain xs where xs: \"xs \\<in> set (map snd xss)\" \"prefs_from_table xss i = of_weak_ranking xs\"\n    by (cases \"map_of xss i\")\n       (fastforce dest: map_of_SomeD simp: prefs_from_table_def map_of_eq_None_iff)+\n  with wf show \"finite_total_preorder_on alts (prefs_from_table xss i)\"\n    by (auto simp: prefs_from_table_wf_def intro!: finite_total_preorder_of_weak_ranking)\nnext\n  assume wf: \"prefs_from_table_wf agents alts xss\"\n  fix i x y assume i: \"i \\<notin> agents\"\n  with wf have \"i \\<notin> set (map fst xss)\" by (simp add: prefs_from_table_wf_def)\n  hence \"map_of xss i = None\" by (simp add: map_of_eq_None_iff)\n  thus \"\\<not>prefs_from_table xss i x y\" by (simp add: prefs_from_table_def)\nqed (simp_all add: prefs_from_table_wf_def)\n\nlemma prefs_from_table_eqI:\n  assumes \"distinct (map fst xs)\" \"distinct (map fst ys)\" \"set xs = set ys\"\n  shows   \"prefs_from_table xs = prefs_from_table ys\"\nproof -\n  from assms have \"map_of xs = map_of ys\" by (subst map_of_inject_set) simp_all\n  thus ?thesis by (simp add: prefs_from_table_def)\nqed\n\nlemma prefs_from_table_undef:\n  assumes \"prefs_from_table_wf agents alts xss\" \"i \\<notin> agents\"\n  shows   \"prefs_from_table xss i = (\\<lambda>_ _. False)\"\nproof -\n  from assms have \"i \\<notin> fst ` set xss\"\n    by (simp add: prefs_from_table_wf_def)\n  hence \"map_of xss i = None\" by (simp add: map_of_eq_None_iff)\n  thus ?thesis by (simp add: prefs_from_table_def)\nqed\n\nlemma prefs_from_table_map_of:\n  assumes \"prefs_from_table_wf agents alts xss\" \"i \\<in> agents\"\n  shows   \"prefs_from_table xss i = of_weak_ranking (the (map_of xss i))\"\n  using assms \n  by (auto simp: prefs_from_table_def map_of_eq_None_iff prefs_from_table_wf_def\n           split: option.splits)\n\nlemma prefs_from_table_update:\n  fixes x xs\n  assumes \"i \\<in> set (map fst xs)\"\n  defines \"xs' \\<equiv> map (\\<lambda>(j,y). if j = i then (j, x) else (j, y)) xs\"\n  shows   \"(prefs_from_table xs)(i := of_weak_ranking x) =\n             prefs_from_table xs'\" (is \"?lhs = ?rhs\")\nproof\n  have xs': \"set (map fst xs') = set (map fst xs)\" by (force simp: xs'_def)  \n  fix k\n  consider \"k = i\" | \"k \\<notin> set (map fst xs)\" | \"k \\<noteq> i\" \"k \\<in> set (map fst xs)\" by blast\n  thus \"?lhs k = ?rhs k\"\n  proof cases \n    assume k: \"k = i\"\n    moreover from k have \"y = x\" if \"(i, y) \\<in> set xs'\" for y\n      using that by (auto simp: xs'_def split: if_splits)\n    ultimately show ?thesis using assms(1) k xs'\n      by (auto simp add: prefs_from_table_def map_of_eq_None_iff \n               dest!: map_of_SomeD split: option.splits)\n  next\n    assume k: \"k \\<notin> set (map fst xs)\"\n    with assms(1) have k': \"k \\<noteq> i\" by auto\n    with k xs' have \"map_of xs k = None\" \"map_of xs' k = None\"\n      by (simp_all add: map_of_eq_None_iff)\n    thus ?thesis by (simp add: prefs_from_table_def k')\n  next\n    assume k: \"k \\<noteq> i\" \"k \\<in> set (map fst xs)\"\n    with k(1) have \"map_of xs k = map_of xs' k\" unfolding xs'_def\n      by (induction xs) fastforce+\n    with k show ?thesis by (simp add: prefs_from_table_def)\n  qed\nqed\n\nlemma prefs_from_table_swap:\n  \"x \\<noteq> y \\<Longrightarrow> prefs_from_table ((x,x')#(y,y')#xs) = prefs_from_table ((y,y')#(x,x')#xs)\"\n  by (intro ext) (auto simp: prefs_from_table_def)\n\nlemma permute_prefs_from_table:\n  assumes \"\\<sigma> permutes fst ` set xs\"\n  shows   \"prefs_from_table xs \\<circ> \\<sigma> = prefs_from_table (map (\\<lambda>(x,y). (inv \\<sigma> x, y)) xs)\"\nproof\n  fix i\n  have \"(prefs_from_table xs \\<circ> \\<sigma>) i = \n          (case map_of xs (\\<sigma> i) of\n             None \\<Rightarrow> \\<lambda>_ _. False\n           | Some x \\<Rightarrow> of_weak_ranking x)\"\n    by (simp add: prefs_from_table_def o_def)\n  also have \"map_of xs (\\<sigma> i) = map_of (map (\\<lambda>(x,y). (inv \\<sigma> x, y)) xs) i\"\n    using map_of_permute[OF assms] by (simp add: o_def fun_eq_iff)\n  finally show \"(prefs_from_table xs \\<circ> \\<sigma>) i = prefs_from_table (map (\\<lambda>(x,y). (inv \\<sigma> x, y)) xs) i\"\n    by (simp only: prefs_from_table_def)\nqed\n\nlemma permute_profile_from_table:\n  assumes wf: \"prefs_from_table_wf agents alts xss\"\n  assumes perm: \"\\<sigma> permutes alts\"\n  shows   \"permute_profile \\<sigma> (prefs_from_table xss) = \n             prefs_from_table (map (\\<lambda>(x,y). (x, map ((`) \\<sigma>) y)) xss)\" (is \"?f = ?g\")\nproof\n  fix i\n  have wf': \"prefs_from_table_wf agents alts (map (\\<lambda>(x, y). (x, map ((`) \\<sigma>) y)) xss)\"\n  proof (intro prefs_from_table_wfI, goal_cases)\n    case (5 xs)\n    then obtain y where \"y \\<in> set xss\" \"xs = map ((`) \\<sigma>) (snd y)\"\n      by (auto simp add: o_def case_prod_unfold)\n    with assms show ?case\n      by (simp add: image_Union [symmetric] prefs_from_table_wf_def permutes_image o_def case_prod_unfold)\n  next\n    case (6 xs)\n    then obtain y where \"y \\<in> set xss\" \"xs = map ((`) \\<sigma>) (snd y)\"\n      by (auto simp add: o_def case_prod_unfold)\n    with assms show ?case\n      by (auto simp: is_finite_weak_ranking_def is_weak_ranking_iff prefs_from_table_wf_def\n            distinct_map permutes_inj_on inj_on_image intro!: disjoint_image)\n  qed (insert assms, simp_all add: image_Union [symmetric] prefs_from_table_wf_def permutes_image o_def case_prod_unfold)\n  show \"?f i = ?g i\"\n  proof (cases \"i \\<in> agents\")\n    assume \"i \\<notin> agents\"\n    with assms wf' show ?thesis\n      by (simp add: permute_profile_def prefs_from_table_undef)\n  next\n    assume i: \"i \\<in> agents\"\n    define xs where \"xs = the (map_of xss i)\"\n    from i wf have xs: \"map_of xss i = Some xs\"\n      by (cases \"map_of xss i\") (auto simp: prefs_from_table_wf_def xs_def)\n    have xs_in_xss: \"xs \\<in> snd ` set xss\"\n      using xs by (force dest!: map_of_SomeD)\n    with wf have set_xs: \"\\<Union>(set xs) = alts\"\n      by (simp add: prefs_from_table_wfD)\n\n    from i have \"prefs_from_table (map (\\<lambda>(x,y). (x, map ((`) \\<sigma>) y)) xss) i =\n                   of_weak_ranking (the (map_of (map (\\<lambda>(x,y). (x, map ((`) \\<sigma>) y)) xss) i))\"\n      using wf' by (intro prefs_from_table_map_of) simp_all\n    also have \"\\<dots> = of_weak_ranking (map ((`) \\<sigma>) xs)\"\n      by (subst map_of_map) (simp add: xs)\n    also have \"\\<dots> = (\\<lambda>a b. of_weak_ranking xs (inv \\<sigma> a) (inv \\<sigma> b))\"\n      by (intro ext) (simp add: of_weak_ranking_permute map_relation_def set_xs perm)\n    also have \"\\<dots> = permute_profile \\<sigma> (prefs_from_table xss) i\"\n      by (simp add: prefs_from_table_def xs permute_profile_def)\n    finally show ?thesis ..\n  qed\nqed\n\n\nsubsection \\<open>Automatic evaluation of preference profiles\\<close>\n\nlemma eval_prefs_from_table [simp]:\n  \"prefs_from_table []i = (\\<lambda>_ _. False)\"\n  \"prefs_from_table ((i, y) # xs) i = of_weak_ranking y\"\n  \"i \\<noteq> j \\<Longrightarrow> prefs_from_table ((j, y) # xs) i = prefs_from_table xs i\"\n  by (simp_all add: prefs_from_table_def)\n\nlemma eval_of_weak_ranking [simp]:\n  \"a \\<notin> \\<Union>(set xs) \\<Longrightarrow> \\<not>of_weak_ranking xs a b\"\n  \"b \\<in> x \\<Longrightarrow> a \\<in> \\<Union>(set (x#xs)) \\<Longrightarrow> of_weak_ranking (x # xs) a b\"\n  \"b \\<notin> x \\<Longrightarrow> of_weak_ranking (x # xs) a b \\<longleftrightarrow> of_weak_ranking xs a b\"\n  by (induction xs) (simp_all add: of_weak_ranking_Cons)\n\nlemma prefs_from_table_cong [cong]:\n  assumes \"prefs_from_table xs = prefs_from_table ys\"\n  shows   \"prefs_from_table (x#xs) = prefs_from_table (x#ys)\"\nproof\n  fix i\n  show \"prefs_from_table (x # xs) i = prefs_from_table (x # ys) i\"\n    using assms by (cases x, cases \"i = fst x\") simp_all\nqed\n\ndefinition of_weak_ranking_Collect_ge where\n  \"of_weak_ranking_Collect_ge xs x = {y. of_weak_ranking xs y x}\"\n\n\n\nlemma of_weak_ranking_Collect_ge_empty [simp]:\n  \"of_weak_ranking_Collect_ge [] x = {}\"\n  by (simp add: of_weak_ranking_Collect_ge_def)\n\nlemma of_weak_ranking_Collect_ge_Cons [simp]:\n  \"y \\<in> x \\<Longrightarrow> of_weak_ranking_Collect_ge (x#xs) y = \\<Union>(set (x#xs))\"\n  \"y \\<notin> x \\<Longrightarrow> of_weak_ranking_Collect_ge (x#xs) y = of_weak_ranking_Collect_ge xs y\"\n  by (auto simp: of_weak_ranking_Cons of_weak_ranking_Collect_ge_def)\n\nlemma of_weak_ranking_Collect_ge_Cons':\n  \"of_weak_ranking_Collect_ge (x#xs) = (\\<lambda>y.\n     (if y \\<in> x then \\<Union>(set (x#xs)) else of_weak_ranking_Collect_ge xs y))\"\n  by (auto simp: of_weak_ranking_Cons of_weak_ranking_Collect_ge_def fun_eq_iff)\n\nlemma anonymise_prefs_from_table:\n  assumes \"prefs_from_table_wf agents alts xs\"\n  shows   \"anonymous_profile (prefs_from_table xs) = mset (map snd xs)\"\nproof -\n  from assms interpret pref_profile_wf agents alts \"prefs_from_table xs\"\n    by (simp add: pref_profile_from_tableI) \n  from assms have agents: \"agents = fst ` set xs\"\n    by (simp add: prefs_from_table_wf_def)\n  hence [simp]: \"finite agents\" by auto\n  have \"anonymous_profile (prefs_from_table xs) = \n          {#weak_ranking (prefs_from_table xs x). x \\<in># mset_set agents#}\"\n    by (simp add: o_def anonymous_profile_def)\n  also from assms have \"\\<dots> = {#the (map_of xs i). i \\<in># mset_set agents#}\"\n  proof (intro image_mset_cong)\n    fix i assume i: \"i \\<in># mset_set agents\"\n    from i assms \n      have \"weak_ranking (prefs_from_table xs i) = \n              weak_ranking (of_weak_ranking (the (map_of xs i))) \"\n      by (simp add: prefs_from_table_map_of)\n    also from assms i have \"\\<dots> = the (map_of xs i)\"\n      by (intro weak_ranking_of_weak_ranking)\n         (auto simp: prefs_from_table_wf_def)\n    finally show \"weak_ranking (prefs_from_table xs i) = the (map_of xs i)\" .\n  qed\n  also from agents have \"mset_set agents = mset_set (set (map fst xs))\" by simp\n  also from assms have \"\\<dots> = mset (map fst xs)\"\n    by (intro mset_set_set) (simp_all add: prefs_from_table_wf_def)\n  also from assms have \"{#the (map_of xs i). i \\<in># mset (map fst xs)#} = mset (map snd xs)\"\n    by (intro image_mset_map_of) (simp_all add: prefs_from_table_wf_def)\n  finally show ?thesis .\nqed\n\nlemma prefs_from_table_agent_permutation:\n  assumes wf: \"prefs_from_table_wf agents alts xs\" \"prefs_from_table_wf agents alts ys\"\n  assumes mset_eq: \"mset (map snd xs) = mset (map snd ys)\"\n  obtains \\<pi> where \"\\<pi> permutes agents\" \"prefs_from_table xs \\<circ> \\<pi> = prefs_from_table ys\"\nproof -\n  from wf(1) have agents: \"agents = set (map fst xs)\"\n    by (simp_all add: prefs_from_table_wf_def)\n  from wf(2) have agents': \"agents = set (map fst ys)\"\n    by (simp_all add: prefs_from_table_wf_def)\n  from agents agents' wf(1) wf(2) have \"mset (map fst xs) = mset (map fst ys)\"\n    by (subst set_eq_iff_mset_eq_distinct [symmetric]) (simp_all add: prefs_from_table_wfD)\n  hence same_length: \"length xs = length ys\" by (auto dest: mset_eq_length simp del: mset_map)\n\n  from \\<open>mset (map fst xs) = mset (map fst ys)\\<close>\n    obtain g where g: \"g permutes {..<length ys}\" \"permute_list g (map fst ys) = map fst xs\"\n    by (auto elim: mset_eq_permutation simp: same_length simp del: mset_map)\n\n  from mset_eq g \n    have \"mset (map snd ys) = mset (permute_list g (map snd ys))\" by simp\n  with mset_eq obtain f \n    where f: \"f permutes {..<length xs}\" \n             \"permute_list f (permute_list g (map snd ys)) = map snd xs\"\n    by (auto elim: mset_eq_permutation simp: same_length simp del: mset_map)\n  from permutes_in_image[OF f(1)]\n  have [simp]: \"f x < length xs \\<longleftrightarrow> x < length xs\" \n                 \"f x < length ys \\<longleftrightarrow> x < length ys\" for x by (simp_all add: same_length)\n\n  define idx unidx where \"idx = index (map fst xs)\" and \"unidx i = map fst xs ! i\" for i\n  from wf(1) have \"bij_betw idx agents {0..<length xs}\" unfolding idx_def\n    by (intro bij_betw_index) (simp_all add: prefs_from_table_wf_def)\n  hence bij_betw_idx: \"bij_betw idx agents {..<length xs}\" by (simp add: atLeast0LessThan)\n  have [simp]: \"idx x < length xs\" if \"x \\<in> agents\" for x\n    using that by (simp add: idx_def agents)\n  have [simp]: \"unidx i \\<in> agents\" if \"i < length xs\" for i\n    using that by (simp add: agents unidx_def)\n\n  have unidx_idx: \"unidx (idx x) = x\" if x: \"x \\<in> agents\" for x\n    using x unfolding idx_def unidx_def using nth_index[of x \"map fst xs\"]\n    by (simp add: agents set_map [symmetric] nth_map [symmetric] del: set_map)\n  have idx_unidx: \"idx (unidx i) = i\" if i: \"i < length xs\" for i\n    unfolding idx_def unidx_def using wf(1) index_nth_id[of \"map fst xs\" i] i\n    by (simp add: prefs_from_table_wfD(3))\n \n  define \\<pi> where \"\\<pi> x = (if x \\<in> agents then (unidx \\<circ> f \\<circ> idx) x else x)\" for x\n  define \\<pi>' where \"\\<pi>' x = (if x \\<in> agents then (unidx \\<circ> inv f \\<circ> idx) x else x)\" for x\n  have \"bij_betw (unidx \\<circ> f \\<circ> idx) agents agents\" (is \"?P\") unfolding unidx_def\n    by (rule bij_betw_trans bij_betw_idx permutes_imp_bij f g bij_betw_nth)+\n       (insert wf(1) g, simp_all add: prefs_from_table_wf_def same_length)\n  also have \"?P \\<longleftrightarrow> bij_betw \\<pi> agents agents\"\n    by (intro bij_betw_cong) (simp add: \\<pi>_def)\n  finally have perm: \"\\<pi> permutes agents\"\n    by (intro bij_imp_permutes) (simp_all add: \\<pi>_def)\n\n  define h where \"h = g \\<circ> f\"\n  from f g have h: \"h permutes {..<length ys}\" unfolding h_def\n    by (intro permutes_compose) (simp_all add: same_length)\n\n  have inv_\\<pi>: \"inv \\<pi> = \\<pi>'\"\n  proof (rule permutes_invI[OF perm])\n    fix x assume \"x \\<in> agents\"\n    with f(1) show \"\\<pi>' (\\<pi> x) = x\"\n      by (simp add: \\<pi>_def \\<pi>'_def idx_unidx unidx_idx inv_f_f permutes_inj)\n  qed (simp add: \\<pi>_def \\<pi>'_def)\n  with perm have inv_\\<pi>': \"inv \\<pi>' = \\<pi>\" by (auto simp: inv_inv_eq permutes_bij)\n\n  from wf h have \"prefs_from_table ys = prefs_from_table (permute_list h ys)\"\n    by (intro prefs_from_table_eqI)\n       (simp_all add: prefs_from_table_wfD permute_list_map [symmetric])\n  also have \"permute_list h ys = permute_list h (zip (map fst ys) (map snd ys))\"\n    by (simp add: zip_map_fst_snd)\n  also from same_length f g\n    have \"permute_list h (zip (map fst ys) (map snd ys)) = \n            zip (permute_list f (map fst xs)) (map snd xs)\"\n    by (subst permute_list_zip[OF h]) (simp_all add: h_def permute_list_compose)\n  also {\n    fix i assume i: \"i < length xs\"\n    from i have \"permute_list f (map fst xs) ! i = unidx (f i)\"\n      using permutes_in_image[OF f(1)] f(1) \n      by (subst permute_list_nth) (simp_all add: same_length unidx_def)\n    also from i have \"\\<dots> = \\<pi> (unidx i)\" by (simp add: \\<pi>_def idx_unidx)\n    also from i have \"\\<dots> = map \\<pi> (map fst xs) ! i\" by (simp add: unidx_def)\n    finally have \"permute_list f (map fst xs) ! i = map \\<pi> (map fst xs) ! i\" .\n  }\n  hence \"permute_list f (map fst xs) = map \\<pi> (map fst xs)\"\n    by (intro nth_equalityI) simp_all\n  also have \"zip (map \\<pi> (map fst xs)) (map snd xs) = map (\\<lambda>(x,y). (inv \\<pi>' x, y)) xs\"\n    by (induction xs) (simp_all add: case_prod_unfold inv_\\<pi>')\n  also from permutes_inv[OF perm] inv_\\<pi> have \"prefs_from_table \\<dots> = prefs_from_table xs \\<circ> \\<pi>'\"\n    by (intro permute_prefs_from_table [symmetric]) (simp_all add: agents)\n  finally have \"prefs_from_table xs \\<circ> \\<pi>' = prefs_from_table ys\" ..\n  with that[of \\<pi>'] permutes_inv[OF perm] inv_\\<pi> show ?thesis by auto\nqed\n\nlemma permute_list_distinct:\n  assumes \"f ` {..<length xs} \\<subseteq> {..<length xs}\" \"distinct xs\"\n  shows   \"permute_list f xs = map (\\<lambda>x. xs ! f (index xs x)) xs\"\n  using assms by (intro nth_equalityI) (auto simp: index_nth_id permute_list_def)\n\nlemma image_mset_eq_permutation:\n  assumes \"{#f x. x \\<in># mset_set A#} = {#g x. x \\<in># mset_set A#}\" \"finite A\"\n  obtains \\<pi> where \"\\<pi> permutes A\" \"\\<And>x. x \\<in> A \\<Longrightarrow> g (\\<pi> x) = f x\"\nproof -\n  from assms(2) obtain xs where xs: \"A = set xs\" \"distinct xs\"\n    using finite_distinct_list by blast\n  with assms have \"mset (map f xs) = mset (map g xs)\" \n    by (simp add: mset_set_set)\n  from mset_eq_permutation[OF this] obtain \\<pi> where\n    \\<pi>: \"\\<pi> permutes {0..<length xs}\" \"permute_list \\<pi> (map g xs) = map f xs\"\n    by (auto simp: atLeast0LessThan)\n  define \\<pi>' where \"\\<pi>' x = (if x \\<in> A then ((!) xs \\<circ> \\<pi> \\<circ> index xs) x else x)\" for x\n  have \"bij_betw ((!) xs \\<circ> \\<pi> \\<circ> index xs) A A\" (is \"?P\")\n    by (rule bij_betw_trans bij_betw_index xs refl permutes_imp_bij \\<pi> bij_betw_nth)+\n       (simp_all add: atLeast0LessThan xs)\n  also have \"?P \\<longleftrightarrow> bij_betw \\<pi>' A A\"\n    by (intro bij_betw_cong) (simp_all add: \\<pi>'_def)\n  finally have \"\\<pi>' permutes A\"\n    by (rule bij_imp_permutes) (simp_all add: \\<pi>'_def)\n  moreover from \\<pi> xs(1)[symmetric] xs(2) have \"g (\\<pi>' x) = f x\" if \"x \\<in> A\" for x\n    by (simp add: permute_list_map permute_list_distinct\n          permutes_image \\<pi>'_def that atLeast0LessThan)\n  ultimately show ?thesis by (rule that)\nqed\n\nlemma anonymous_profile_agent_permutation:\n  assumes eq:  \"anonymous_profile R1 = anonymous_profile R2\"\n  assumes wf:  \"pref_profile_wf agents alts R1\" \"pref_profile_wf agents alts R2\"\n  assumes fin: \"finite agents\"\n  obtains \\<pi> where \"\\<pi> permutes agents\" \"R2 \\<circ> \\<pi> = R1\"\nproof -\n  interpret R1: pref_profile_wf agents alts R1 by fact\n  interpret R2: pref_profile_wf agents alts R2 by fact\n\n  from eq have \"{#weak_ranking (R1 x). x \\<in># mset_set agents#} = \n                  {#weak_ranking (R2 x). x \\<in># mset_set agents#}\"\n    by (simp add: R1.anonymous_profile_def R2.anonymous_profile_def o_def)\n  from image_mset_eq_permutation[OF this fin] guess \\<pi> . note \\<pi> = this\n  from \\<pi> have wf': \"pref_profile_wf agents alts (R2 \\<circ> \\<pi>)\"\n    by (intro R2.wf_permute_agents)\n  then interpret R2': pref_profile_wf agents alts \"R2 \\<circ> \\<pi>\" .\n  have \"R2 \\<circ> \\<pi> = R1\"\n  proof (intro pref_profile_eqI[OF wf' wf(1)])\n    fix x assume x: \"x \\<in> agents\"\n    with \\<pi> have \"weak_ranking ((R2 o \\<pi>) x) = weak_ranking (R1 x)\" by simp\n    with wf' wf(1) x show \"(R2 \\<circ> \\<pi>) x = R1 x\"\n      by (intro weak_ranking_eqD[of alts] R2'.prefs_wf) simp_all\n  qed\n  from \\<pi>(1) and this show ?thesis by (rule that)\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/Randomised_Social_Choice/Preference_Profiles.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8791467611766711, "lm_q2_score": 0.8311430436757313, "lm_q1q2_score": 0.7306967149220397}}
{"text": "section \\<open>Set-valued maps\\<close>\ntheory SetMap\n  imports Main\nbegin\n\ntext \\<open>\nFor the abstract semantics, we need methods to work with set-valued maps, i.e.\\ functions from a key type to sets of values. For this type, some well known operations are introduced and properties shown, either borrowing the nomenclature from finite maps (\\<open>sdom\\<close>, \\<open>sran\\<close>,...) or of sets (\\<open>{}.\\<close>, \\<open>\\<union>.\\<close>,...).\n\\<close>\n\ndefinition\n  sdom :: \"('a => 'b set) => 'a set\" where\n  \"sdom m = {a. m a ~= {}}\"\n\ndefinition\n  sran :: \"('a => 'b set) => 'b set\" where\n  \"sran m = {b. \\<exists>a. b \\<in> m a}\"\n\nlemma sranI: \"b \\<in> m a \\<Longrightarrow> b \\<in> sran m\"\n  by(auto simp: sran_def)\n\nlemma sdom_not_mem[elim]: \"a \\<notin> sdom m \\<Longrightarrow> m a = {}\"\n  by (auto simp: sdom_def)\n\ndefinition smap_empty (\"{}.\")\n where \"{}. k = {}\"\n\ndefinition smap_union :: \"('a::type \\<Rightarrow> 'b::type set)  \\<Rightarrow> ('a \\<Rightarrow> 'b set) \\<Rightarrow> ('a \\<Rightarrow> 'b set)\" (\"_ \\<union>. _\")\n where \"smap1 \\<union>. smap2 k =  smap1 k \\<union> smap2 k\"\n\nprimrec smap_Union :: \"('a::type \\<Rightarrow> 'b::type set) list \\<Rightarrow> 'a \\<Rightarrow> 'b set\" (\"\\<Union>._\")\n  where [simp]:\"\\<Union>. [] = {}.\"\n      | \"\\<Union>. (m#ms) = m  \\<union>. \\<Union>. ms\"\n\ndefinition smap_singleton :: \"'a::type \\<Rightarrow> 'b::type set \\<Rightarrow> 'a \\<Rightarrow> 'b set\" (\"{ _ := _}.\")\n  where \"{k := vs}. = {}. (k := vs)\"\n\ndefinition smap_less :: \"('a \\<Rightarrow> 'b set) \\<Rightarrow> ('a \\<Rightarrow> 'b set) \\<Rightarrow> bool\" (\"_/ \\<subseteq>. _\" [50, 51] 50)\n  where \"smap_less m1 m2 = (\\<forall>k. m1 k \\<subseteq> m2 k)\"\n\nlemma sdom_empty[simp]: \"sdom {}. = {}\"\n  unfolding sdom_def smap_empty_def by auto\n\nlemma sdom_singleton[simp]: \"sdom {k := vs}. \\<subseteq> {k}\"\n  by (auto simp add: sdom_def smap_singleton_def smap_empty_def)\n\nlemma sran_singleton[simp]: \"sran {k := vs}. = vs\"\n  by (auto simp add: sran_def smap_singleton_def smap_empty_def)\n\nlemma sran_empty[simp]: \"sran {}. = {}\"\n  unfolding sran_def smap_empty_def by auto\n\nlemma sdom_union[simp]: \"sdom (m \\<union>. n) = sdom m \\<union> sdom n\"\n  by(auto simp add:smap_union_def sdom_def)\n\nlemma sran_union[simp]: \"sran (m \\<union>. n) = sran m \\<union> sran n\"\n  by(auto simp add:smap_union_def sran_def)\n\nlemma smap_empty[simp]: \"{}. \\<subseteq>. {}.\"\n  unfolding smap_less_def by auto\n\nlemma smap_less_refl: \"m \\<subseteq>. m\"\n  unfolding smap_less_def by simp\n\nlemma smap_less_trans[trans]: \"\\<lbrakk> m1 \\<subseteq>. m2; m2 \\<subseteq>. m3 \\<rbrakk> \\<Longrightarrow> m1 \\<subseteq>. m3\"\n  unfolding smap_less_def by auto\n\nlemma smap_union_mono: \"\\<lbrakk> ve1 \\<subseteq>. ve1'; ve2 \\<subseteq>. ve2' \\<rbrakk> \\<Longrightarrow> ve1 \\<union>. ve2 \\<subseteq>. ve1' \\<union>. ve2'\"\n  by (auto simp add:smap_less_def smap_union_def)\n\nlemma smap_Union_union: \"m1 \\<union>. \\<Union>.ms = \\<Union>.(m1#ms)\"\n  by (rule ext, auto simp add: smap_union_def smap_Union_def)\n\nlemma smap_Union_mono:\n  assumes \"list_all2 smap_less ms1 ms2\"\n  shows \"\\<Union>. ms1 \\<subseteq>. \\<Union>. ms2\"\nusing assms \n  by(induct rule:list_induct2[OF list_all2_lengthD[OF assms]])\n    (auto intro:smap_union_mono)\n\nlemma smap_singleton_mono: \"v \\<subseteq> v' \\<Longrightarrow> {k := v}. \\<subseteq>. {k := v'}.\"\n by (auto simp add: smap_singleton_def smap_less_def)\n\nlemma smap_union_comm: \"m1 \\<union>. m2 = m2 \\<union>. m1\"\nby (rule ext,auto simp add:smap_union_def)\n\nlemma smap_union_empty1[simp]: \"{}. \\<union>. m = m\"\n  by(rule ext, auto simp add:smap_union_def smap_empty_def)\n\nlemma smap_union_empty2[simp]: \"m \\<union>. {}. = m\"\n  by(rule ext, auto simp add:smap_union_def smap_empty_def)\n\nlemma smap_union_assoc [simp]: \"(m1 \\<union>. m2) \\<union>. m3 = m1 \\<union>. (m2 \\<union>. m3)\"\n  by (rule ext, auto simp add:smap_union_def)\n\nlemma smap_Union_append[simp]: \"\\<Union>. (m1@m2) = (\\<Union>. m1) \\<union>. (\\<Union>. m2)\"\n  by (induct m1) auto\n\nlemma smap_Union_rev[simp]: \"\\<Union>. (rev l) = \\<Union>. l\"\n  by(induct l)(auto simp add:smap_union_comm)\n\nlemma smap_Union_map_rev[simp]: \"\\<Union>. (map f (rev l)) = \\<Union>. (map f l)\"\n  by(subst rev_map[THEN sym], subst smap_Union_rev, rule refl)\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/Shivers-CFA/SetMap.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8723473746782093, "lm_q2_score": 0.8376199673867852, "lm_q1q2_score": 0.7306955795279094}}
{"text": "(*  Title:      HOL/ex/Sqrt.thy\n    Author:     Markus Wenzel, Tobias Nipkow, TU Muenchen\n*)\n\nsection \\<open>Square roots of primes are irrational\\<close>\n\ntheory Sqrt\nimports Complex_Main \"~~/src/HOL/Number_Theory/Primes\"\nbegin\n\ntext \\<open>The square root of any prime number (including 2) is irrational.\\<close>\n\ntheorem sqrt_prime_irrational:\n  assumes \"prime (p::nat)\"\n  shows \"sqrt p \\<notin> \\<rat>\"\nproof\n  from \\<open>prime p\\<close> have p: \"1 < p\" by (simp add: prime_nat_def)\n  assume \"sqrt p \\<in> \\<rat>\"\n  then obtain m n :: nat where\n      n: \"n \\<noteq> 0\" and sqrt_rat: \"\\<bar>sqrt p\\<bar> = m / n\"\n    and gcd: \"gcd m n = 1\" 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\"\n      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 show ?thesis ..\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_nat)\n    then obtain k where \"m = p * k\" ..\n    with eq have \"p * n\\<^sup>2 = p\\<^sup>2 * k\\<^sup>2\" by (auto simp add: power2_eq_square ac_simps)\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_nat)\n  qed\n  then have \"p dvd gcd m n\" ..\n  with gcd have \"p dvd 1\" by simp\n  then have \"p \\<le> 1\" by (simp add: dvd_imp_le)\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\n\nsubsection \\<open>Variations\\<close>\n\ntext \\<open>\n  Here is an alternative version of the main proof, using mostly\n  linear forward-reasoning.  While this results in less top-down\n  structure, it is probably closer to proofs seen in mathematics.\n\\<close>\n\ntheorem\n  assumes \"prime (p::nat)\"\n  shows \"sqrt p \\<notin> \\<rat>\"\nproof\n  from \\<open>prime p\\<close> have p: \"1 < p\" by (simp add: prime_nat_def)\n  assume \"sqrt p \\<in> \\<rat>\"\n  then obtain m n :: nat where\n      n: \"n \\<noteq> 0\" and sqrt_rat: \"\\<bar>sqrt p\\<bar> = m / n\"\n    and gcd: \"gcd m n = 1\" 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\"\n    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\" ..\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_nat)\n  then obtain k where \"m = p * k\" ..\n  with eq have \"p * n\\<^sup>2 = p\\<^sup>2 * k\\<^sup>2\" by (auto simp add: power2_eq_square ac_simps)\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_nat)\n  with dvd_m have \"p dvd gcd m n\" by (rule gcd_greatest_nat)\n  with gcd have \"p dvd 1\" by simp\n  then have \"p \\<le> 1\" by (simp add: dvd_imp_le)\n  with p show False by simp\nqed\n\n\ntext \\<open>Another old chestnut, which is a consequence of the irrationality of 2.\\<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\n  assume \"sqrt 2 powr sqrt 2 \\<in> \\<rat>\"\n  then have \"?P (sqrt 2) (sqrt 2)\"\n    by (metis sqrt_2_not_rat)\n  then show ?thesis by blast\nnext\n  assume 1: \"sqrt 2 powr sqrt 2 \\<notin> \\<rat>\"\n  have \"(sqrt 2 powr sqrt 2) powr sqrt 2 = 2\"\n    using powr_realpow [of _ 2]\n    by (simp add: powr_powr power2_eq_square [symmetric])\n  then have \"?P (sqrt 2 powr sqrt 2) (sqrt 2)\"\n    by (metis 1 Rats_number_of sqrt_2_not_rat)\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/ex/Sqrt.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199754937772, "lm_q2_score": 0.8723473614033683, "lm_q1q2_score": 0.7306955754807506}}
{"text": "(* Title:      HOL/Analysis/Convex.thy\n   Author:     L C Paulson, University of Cambridge\n   Author:     Robert Himmelmann, TU Muenchen\n   Author:     Bogdan Grechuk, University of Edinburgh\n   Author:     Armin Heller, TU Muenchen\n   Author:     Johannes Hoelzl, TU Muenchen\n*)\n\nsection \\<open>Convex Sets and Functions\\<close>\n\ntheory Convex\nimports\n  Affine\n  \"HOL-Library.Set_Algebras\"\nbegin\n\nsubsection \\<open>Convex Sets\\<close>\n\ndefinition\\<^marker>\\<open>tag important\\<close> convex :: \"'a::real_vector set \\<Rightarrow> bool\"\n  where \"convex s \\<longleftrightarrow> (\\<forall>x\\<in>s. \\<forall>y\\<in>s. \\<forall>u\\<ge>0. \\<forall>v\\<ge>0. u + v = 1 \\<longrightarrow> u *\\<^sub>R x + v *\\<^sub>R y \\<in> s)\"\n\nlemma convexI:\n  assumes \"\\<And>x y u v. x \\<in> s \\<Longrightarrow> y \\<in> s \\<Longrightarrow> 0 \\<le> u \\<Longrightarrow> 0 \\<le> v \\<Longrightarrow> u + v = 1 \\<Longrightarrow> u *\\<^sub>R x + v *\\<^sub>R y \\<in> s\"\n  shows \"convex s\"\n  using assms unfolding convex_def by fast\n\nlemma convexD:\n  assumes \"convex s\" and \"x \\<in> s\" and \"y \\<in> s\" and \"0 \\<le> u\" and \"0 \\<le> v\" and \"u + v = 1\"\n  shows \"u *\\<^sub>R x + v *\\<^sub>R y \\<in> s\"\n  using assms unfolding convex_def by fast\n\nlemma convex_alt: \"convex s \\<longleftrightarrow> (\\<forall>x\\<in>s. \\<forall>y\\<in>s. \\<forall>u. 0 \\<le> u \\<and> u \\<le> 1 \\<longrightarrow> ((1 - u) *\\<^sub>R x + u *\\<^sub>R y) \\<in> s)\"\n  (is \"_ \\<longleftrightarrow> ?alt\")\nproof\n  show \"convex s\" if alt: ?alt\n  proof -\n    {\n      fix x y and u v :: real\n      assume mem: \"x \\<in> s\" \"y \\<in> s\"\n      assume \"0 \\<le> u\" \"0 \\<le> v\"\n      moreover\n      assume \"u + v = 1\"\n      then have \"u = 1 - v\" by auto\n      ultimately have \"u *\\<^sub>R x + v *\\<^sub>R y \\<in> s\"\n        using alt [rule_format, OF mem] by auto\n    }\n    then show ?thesis\n      unfolding convex_def by auto\n  qed\n  show ?alt if \"convex s\"\n    using that by (auto simp: convex_def)\nqed\n\nlemma convexD_alt:\n  assumes \"convex s\" \"a \\<in> s\" \"b \\<in> s\" \"0 \\<le> u\" \"u \\<le> 1\"\n  shows \"((1 - u) *\\<^sub>R a + u *\\<^sub>R b) \\<in> s\"\n  using assms unfolding convex_alt by auto\n\nlemma mem_convex_alt:\n  assumes \"convex S\" \"x \\<in> S\" \"y \\<in> S\" \"u \\<ge> 0\" \"v \\<ge> 0\" \"u + v > 0\"\n  shows \"((u/(u+v)) *\\<^sub>R x + (v/(u+v)) *\\<^sub>R y) \\<in> S\"\n  using assms\n  by (simp add: convex_def zero_le_divide_iff add_divide_distrib [symmetric])\n\nlemma convex_empty[intro,simp]: \"convex {}\"\n  unfolding convex_def by simp\n\nlemma convex_singleton[intro,simp]: \"convex {a}\"\n  unfolding convex_def by (auto simp: scaleR_left_distrib[symmetric])\n\nlemma convex_UNIV[intro,simp]: \"convex UNIV\"\n  unfolding convex_def by auto\n\nlemma convex_Inter: \"(\\<And>s. s\\<in>f \\<Longrightarrow> convex s) \\<Longrightarrow> convex(\\<Inter>f)\"\n  unfolding convex_def by auto\n\nlemma convex_Int: \"convex s \\<Longrightarrow> convex t \\<Longrightarrow> convex (s \\<inter> t)\"\n  unfolding convex_def by auto\n\nlemma convex_INT: \"(\\<And>i. i \\<in> A \\<Longrightarrow> convex (B i)) \\<Longrightarrow> convex (\\<Inter>i\\<in>A. B i)\"\n  unfolding convex_def by auto\n\nlemma convex_Times: \"convex s \\<Longrightarrow> convex t \\<Longrightarrow> convex (s \\<times> t)\"\n  unfolding convex_def by auto\n\nlemma convex_halfspace_le: \"convex {x. inner a x \\<le> b}\"\n  unfolding convex_def\n  by (auto simp: inner_add intro!: convex_bound_le)\n\nlemma convex_halfspace_ge: \"convex {x. inner a x \\<ge> b}\"\nproof -\n  have *: \"{x. inner a x \\<ge> b} = {x. inner (-a) x \\<le> -b}\"\n    by auto\n  show ?thesis\n    unfolding * using convex_halfspace_le[of \"-a\" \"-b\"] by auto\nqed\n\nlemma convex_halfspace_abs_le: \"convex {x. \\<bar>inner a x\\<bar> \\<le> b}\"\nproof -\n  have *: \"{x. \\<bar>inner a x\\<bar> \\<le> b} = {x. inner a x \\<le> b} \\<inter> {x. -b \\<le> inner a x}\"\n    by auto\n  show ?thesis\n    unfolding * by (simp add: convex_Int convex_halfspace_ge convex_halfspace_le)\nqed\n\nlemma convex_hyperplane: \"convex {x. inner a x = b}\"\nproof -\n  have *: \"{x. inner a x = b} = {x. inner a x \\<le> b} \\<inter> {x. inner a x \\<ge> b}\"\n    by auto\n  show ?thesis using convex_halfspace_le convex_halfspace_ge\n    by (auto intro!: convex_Int simp: *)\nqed\n\nlemma convex_halfspace_lt: \"convex {x. inner a x < b}\"\n  unfolding convex_def\n  by (auto simp: convex_bound_lt inner_add)\n\nlemma convex_halfspace_gt: \"convex {x. inner a x > b}\"\n  using convex_halfspace_lt[of \"-a\" \"-b\"] by auto\n\nlemma convex_halfspace_Re_ge: \"convex {x. Re x \\<ge> b}\"\n  using convex_halfspace_ge[of b \"1::complex\"] by simp\n\nlemma convex_halfspace_Re_le: \"convex {x. Re x \\<le> b}\"\n  using convex_halfspace_le[of \"1::complex\" b] by simp\n\nlemma convex_halfspace_Im_ge: \"convex {x. Im x \\<ge> b}\"\n  using convex_halfspace_ge[of b \\<i>] by simp\n\nlemma convex_halfspace_Im_le: \"convex {x. Im x \\<le> b}\"\n  using convex_halfspace_le[of \\<i> b] by simp\n\nlemma convex_halfspace_Re_gt: \"convex {x. Re x > b}\"\n  using convex_halfspace_gt[of b \"1::complex\"] by simp\n\nlemma convex_halfspace_Re_lt: \"convex {x. Re x < b}\"\n  using convex_halfspace_lt[of \"1::complex\" b] by simp\n\nlemma convex_halfspace_Im_gt: \"convex {x. Im x > b}\"\n  using convex_halfspace_gt[of b \\<i>] by simp\n\nlemma convex_halfspace_Im_lt: \"convex {x. Im x < b}\"\n  using convex_halfspace_lt[of \\<i> b] by simp\n\nlemma convex_real_interval [iff]:\n  fixes a b :: \"real\"\n  shows \"convex {a..}\" and \"convex {..b}\"\n    and \"convex {a<..}\" and \"convex {..<b}\"\n    and \"convex {a..b}\" and \"convex {a<..b}\"\n    and \"convex {a..<b}\" and \"convex {a<..<b}\"\nproof -\n  have \"{a..} = {x. a \\<le> inner 1 x}\"\n    by auto\n  then show 1: \"convex {a..}\"\n    by (simp only: convex_halfspace_ge)\n  have \"{..b} = {x. inner 1 x \\<le> b}\"\n    by auto\n  then show 2: \"convex {..b}\"\n    by (simp only: convex_halfspace_le)\n  have \"{a<..} = {x. a < inner 1 x}\"\n    by auto\n  then show 3: \"convex {a<..}\"\n    by (simp only: convex_halfspace_gt)\n  have \"{..<b} = {x. inner 1 x < b}\"\n    by auto\n  then show 4: \"convex {..<b}\"\n    by (simp only: convex_halfspace_lt)\n  have \"{a..b} = {a..} \\<inter> {..b}\"\n    by auto\n  then show \"convex {a..b}\"\n    by (simp only: convex_Int 1 2)\n  have \"{a<..b} = {a<..} \\<inter> {..b}\"\n    by auto\n  then show \"convex {a<..b}\"\n    by (simp only: convex_Int 3 2)\n  have \"{a..<b} = {a..} \\<inter> {..<b}\"\n    by auto\n  then show \"convex {a..<b}\"\n    by (simp only: convex_Int 1 4)\n  have \"{a<..<b} = {a<..} \\<inter> {..<b}\"\n    by auto\n  then show \"convex {a<..<b}\"\n    by (simp only: convex_Int 3 4)\nqed\n\nlemma convex_Reals: \"convex \\<real>\"\n  by (simp add: convex_def scaleR_conv_of_real)\n\n\nsubsection\\<^marker>\\<open>tag unimportant\\<close> \\<open>Explicit expressions for convexity in terms of arbitrary sums\\<close>\n\nlemma convex_sum:\n  fixes C :: \"'a::real_vector set\"\n  assumes \"finite S\"\n    and \"convex C\"\n    and \"(\\<Sum> i \\<in> S. a i) = 1\"\n  assumes \"\\<And>i. i \\<in> S \\<Longrightarrow> a i \\<ge> 0\"\n    and \"\\<And>i. i \\<in> S \\<Longrightarrow> y i \\<in> C\"\n  shows \"(\\<Sum> j \\<in> S. a j *\\<^sub>R y j) \\<in> C\"\n  using assms(1,3,4,5)\nproof (induct arbitrary: a set: finite)\n  case empty\n  then show ?case by simp\nnext\n  case (insert i S) note IH = this(3)\n  have \"a i + sum a S = 1\"\n    and \"0 \\<le> a i\"\n    and \"\\<forall>j\\<in>S. 0 \\<le> a j\"\n    and \"y i \\<in> C\"\n    and \"\\<forall>j\\<in>S. y j \\<in> C\"\n    using insert.hyps(1,2) insert.prems by simp_all\n  then have \"0 \\<le> sum a S\"\n    by (simp add: sum_nonneg)\n  have \"a i *\\<^sub>R y i + (\\<Sum>j\\<in>S. a j *\\<^sub>R y j) \\<in> C\"\n  proof (cases \"sum a S = 0\")\n    case True\n    with \\<open>a i + sum a S = 1\\<close> have \"a i = 1\"\n      by simp\n    from sum_nonneg_0 [OF \\<open>finite S\\<close> _ True] \\<open>\\<forall>j\\<in>S. 0 \\<le> a j\\<close> have \"\\<forall>j\\<in>S. a j = 0\"\n      by simp\n    show ?thesis using \\<open>a i = 1\\<close> and \\<open>\\<forall>j\\<in>S. a j = 0\\<close> and \\<open>y i \\<in> C\\<close>\n      by simp\n  next\n    case False\n    with \\<open>0 \\<le> sum a S\\<close> have \"0 < sum a S\"\n      by simp\n    then have \"(\\<Sum>j\\<in>S. (a j / sum a S) *\\<^sub>R y j) \\<in> C\"\n      using \\<open>\\<forall>j\\<in>S. 0 \\<le> a j\\<close> and \\<open>\\<forall>j\\<in>S. y j \\<in> C\\<close>\n      by (simp add: IH sum_divide_distrib [symmetric])\n    from \\<open>convex C\\<close> and \\<open>y i \\<in> C\\<close> and this and \\<open>0 \\<le> a i\\<close>\n      and \\<open>0 \\<le> sum a S\\<close> and \\<open>a i + sum a S = 1\\<close>\n    have \"a i *\\<^sub>R y i + sum a S *\\<^sub>R (\\<Sum>j\\<in>S. (a j / sum a S) *\\<^sub>R y j) \\<in> C\"\n      by (rule convexD)\n    then show ?thesis\n      by (simp add: scaleR_sum_right False)\n  qed\n  then show ?case using \\<open>finite S\\<close> and \\<open>i \\<notin> S\\<close>\n    by simp\nqed\n\nlemma convex:\n  \"convex S \\<longleftrightarrow> (\\<forall>(k::nat) u x. (\\<forall>i. 1\\<le>i \\<and> i\\<le>k \\<longrightarrow> 0 \\<le> u i \\<and> x i \\<in>S) \\<and> (sum u {1..k} = 1)\n      \\<longrightarrow> sum (\\<lambda>i. u i *\\<^sub>R x i) {1..k} \\<in> S)\"\nproof safe\n  fix k :: nat\n  fix u :: \"nat \\<Rightarrow> real\"\n  fix x\n  assume \"convex S\"\n    \"\\<forall>i. 1 \\<le> i \\<and> i \\<le> k \\<longrightarrow> 0 \\<le> u i \\<and> x i \\<in> S\"\n    \"sum u {1..k} = 1\"\n  with convex_sum[of \"{1 .. k}\" S] show \"(\\<Sum>j\\<in>{1 .. k}. u j *\\<^sub>R x j) \\<in> S\"\n    by auto\nnext\n  assume *: \"\\<forall>k u x. (\\<forall> i :: nat. 1 \\<le> i \\<and> i \\<le> k \\<longrightarrow> 0 \\<le> u i \\<and> x i \\<in> S) \\<and> sum u {1..k} = 1\n    \\<longrightarrow> (\\<Sum>i = 1..k. u i *\\<^sub>R (x i :: 'a)) \\<in> S\"\n  {\n    fix \\<mu> :: real\n    fix x y :: 'a\n    assume xy: \"x \\<in> S\" \"y \\<in> S\"\n    assume mu: \"\\<mu> \\<ge> 0\" \"\\<mu> \\<le> 1\"\n    let ?u = \"\\<lambda>i. if (i :: nat) = 1 then \\<mu> else 1 - \\<mu>\"\n    let ?x = \"\\<lambda>i. if (i :: nat) = 1 then x else y\"\n    have \"{1 :: nat .. 2} \\<inter> - {x. x = 1} = {2}\"\n      by auto\n    then have card: \"card ({1 :: nat .. 2} \\<inter> - {x. x = 1}) = 1\"\n      by simp\n    then have \"sum ?u {1 .. 2} = 1\"\n      using sum.If_cases[of \"{(1 :: nat) .. 2}\" \"\\<lambda> x. x = 1\" \"\\<lambda> x. \\<mu>\" \"\\<lambda> x. 1 - \\<mu>\"]\n      by auto\n    with *[rule_format, of \"2\" ?u ?x] have S: \"(\\<Sum>j \\<in> {1..2}. ?u j *\\<^sub>R ?x j) \\<in> S\"\n      using mu xy by auto\n    have grarr: \"(\\<Sum>j \\<in> {Suc (Suc 0)..2}. ?u j *\\<^sub>R ?x j) = (1 - \\<mu>) *\\<^sub>R y\"\n      using sum.atLeast_Suc_atMost[of \"Suc (Suc 0)\" 2 \"\\<lambda> j. (1 - \\<mu>) *\\<^sub>R y\"] by auto\n    from sum.atLeast_Suc_atMost[of \"Suc 0\" 2 \"\\<lambda> j. ?u j *\\<^sub>R ?x j\", simplified this]\n    have \"(\\<Sum>j \\<in> {1..2}. ?u j *\\<^sub>R ?x j) = \\<mu> *\\<^sub>R x + (1 - \\<mu>) *\\<^sub>R y\"\n      by auto\n    then have \"(1 - \\<mu>) *\\<^sub>R y + \\<mu> *\\<^sub>R x \\<in> S\"\n      using S by (auto simp: add.commute)\n  }\n  then show \"convex S\"\n    unfolding convex_alt by auto\nqed\n\n\nlemma convex_explicit:\n  fixes S :: \"'a::real_vector set\"\n  shows \"convex S \\<longleftrightarrow>\n    (\\<forall>t u. finite t \\<and> t \\<subseteq> S \\<and> (\\<forall>x\\<in>t. 0 \\<le> u x) \\<and> sum u t = 1 \\<longrightarrow> sum (\\<lambda>x. u x *\\<^sub>R x) t \\<in> S)\"\nproof safe\n  fix t\n  fix u :: \"'a \\<Rightarrow> real\"\n  assume \"convex S\"\n    and \"finite t\"\n    and \"t \\<subseteq> S\" \"\\<forall>x\\<in>t. 0 \\<le> u x\" \"sum u t = 1\"\n  then show \"(\\<Sum>x\\<in>t. u x *\\<^sub>R x) \\<in> S\"\n    using convex_sum[of t S u \"\\<lambda> x. x\"] by auto\nnext\n  assume *: \"\\<forall>t. \\<forall> u. finite t \\<and> t \\<subseteq> S \\<and> (\\<forall>x\\<in>t. 0 \\<le> u x) \\<and>\n    sum u t = 1 \\<longrightarrow> (\\<Sum>x\\<in>t. u x *\\<^sub>R x) \\<in> S\"\n  show \"convex S\"\n    unfolding convex_alt\n  proof safe\n    fix x y\n    fix \\<mu> :: real\n    assume **: \"x \\<in> S\" \"y \\<in> S\" \"0 \\<le> \\<mu>\" \"\\<mu> \\<le> 1\"\n    show \"(1 - \\<mu>) *\\<^sub>R x + \\<mu> *\\<^sub>R y \\<in> S\"\n    proof (cases \"x = y\")\n      case False\n      then show ?thesis\n        using *[rule_format, of \"{x, y}\" \"\\<lambda> z. if z = x then 1 - \\<mu> else \\<mu>\"] **\n        by auto\n    next\n      case True\n      then show ?thesis\n        using *[rule_format, of \"{x, y}\" \"\\<lambda> z. 1\"] **\n        by (auto simp: field_simps real_vector.scale_left_diff_distrib)\n    qed\n  qed\nqed\n\nlemma convex_finite:\n  assumes \"finite S\"\n  shows \"convex S \\<longleftrightarrow> (\\<forall>u. (\\<forall>x\\<in>S. 0 \\<le> u x) \\<and> sum u S = 1 \\<longrightarrow> sum (\\<lambda>x. u x *\\<^sub>R x) S \\<in> S)\"\n       (is \"?lhs = ?rhs\")\nproof \n  { have if_distrib_arg: \"\\<And>P f g x. (if P then f else g) x = (if P then f x else g x)\"\n      by simp\n    fix T :: \"'a set\" and u :: \"'a \\<Rightarrow> real\"\n    assume sum: \"\\<forall>u. (\\<forall>x\\<in>S. 0 \\<le> u x) \\<and> sum u S = 1 \\<longrightarrow> (\\<Sum>x\\<in>S. u x *\\<^sub>R x) \\<in> S\"\n    assume *: \"\\<forall>x\\<in>T. 0 \\<le> u x\" \"sum u T = 1\"\n    assume \"T \\<subseteq> S\"\n    then have \"S \\<inter> T = T\" by auto\n    with sum[THEN spec[where x=\"\\<lambda>x. if x\\<in>T then u x else 0\"]] * have \"(\\<Sum>x\\<in>T. u x *\\<^sub>R x) \\<in> S\"\n      by (auto simp: assms sum.If_cases if_distrib if_distrib_arg) }\n  moreover assume ?rhs\n  ultimately show ?lhs\n    unfolding convex_explicit by auto\nqed (auto simp: convex_explicit assms)\n\n\nsubsection \\<open>Convex Functions on a Set\\<close>\n\ndefinition\\<^marker>\\<open>tag important\\<close> convex_on :: \"'a::real_vector set \\<Rightarrow> ('a \\<Rightarrow> real) \\<Rightarrow> bool\"\n  where \"convex_on S f \\<longleftrightarrow>\n    (\\<forall>x\\<in>S. \\<forall>y\\<in>S. \\<forall>u\\<ge>0. \\<forall>v\\<ge>0. u + v = 1 \\<longrightarrow> f (u *\\<^sub>R x + v *\\<^sub>R y) \\<le> u * f x + v * f y)\"\n\ndefinition\\<^marker>\\<open>tag important\\<close> concave_on :: \"'a::real_vector set \\<Rightarrow> ('a \\<Rightarrow> real) \\<Rightarrow> bool\"\n  where \"concave_on S f \\<equiv> convex_on S (\\<lambda>x. - f x)\"\n\nlemma concave_on_iff:\n  \"concave_on S f \\<longleftrightarrow>\n    (\\<forall>x\\<in>S. \\<forall>y\\<in>S. \\<forall>u\\<ge>0. \\<forall>v\\<ge>0. u + v = 1 \\<longrightarrow> f (u *\\<^sub>R x + v *\\<^sub>R y) \\<ge> u * f x + v * f y)\"\n  by (auto simp: concave_on_def convex_on_def algebra_simps)\n\nlemma convex_onI [intro?]:\n  assumes \"\\<And>t x y. t > 0 \\<Longrightarrow> t < 1 \\<Longrightarrow> x \\<in> A \\<Longrightarrow> y \\<in> A \\<Longrightarrow>\n    f ((1 - t) *\\<^sub>R x + t *\\<^sub>R y) \\<le> (1 - t) * f x + t * f y\"\n  shows \"convex_on A f\"\n  unfolding convex_on_def\nproof clarify\n  fix x y\n  fix u v :: real\n  assume A: \"x \\<in> A\" \"y \\<in> A\" \"u \\<ge> 0\" \"v \\<ge> 0\" \"u + v = 1\"\n  from A(5) have [simp]: \"v = 1 - u\"\n    by (simp add: algebra_simps)\n  from A(1-4) show \"f (u *\\<^sub>R x + v *\\<^sub>R y) \\<le> u * f x + v * f y\"\n    using assms[of u y x]\n    by (cases \"u = 0 \\<or> u = 1\") (auto simp: algebra_simps)\nqed\n\nlemma convex_on_linorderI [intro?]:\n  fixes A :: \"('a::{linorder,real_vector}) set\"\n  assumes \"\\<And>t x y. t > 0 \\<Longrightarrow> t < 1 \\<Longrightarrow> x \\<in> A \\<Longrightarrow> y \\<in> A \\<Longrightarrow> x < y \\<Longrightarrow>\n    f ((1 - t) *\\<^sub>R x + t *\\<^sub>R y) \\<le> (1 - t) * f x + t * f y\"\n  shows \"convex_on A f\"\nproof\n  fix x y\n  fix t :: real\n  assume A: \"x \\<in> A\" \"y \\<in> A\" \"t > 0\" \"t < 1\"\n  with assms [of t x y] assms [of \"1 - t\" y x]\n  show \"f ((1 - t) *\\<^sub>R x + t *\\<^sub>R y) \\<le> (1 - t) * f x + t * f y\"\n    by (cases x y rule: linorder_cases) (auto simp: algebra_simps)\nqed\n\nlemma convex_onD:\n  assumes \"convex_on A f\"\n  shows \"\\<And>t x y. t \\<ge> 0 \\<Longrightarrow> t \\<le> 1 \\<Longrightarrow> x \\<in> A \\<Longrightarrow> y \\<in> A \\<Longrightarrow>\n    f ((1 - t) *\\<^sub>R x + t *\\<^sub>R y) \\<le> (1 - t) * f x + t * f y\"\n  using assms by (auto simp: convex_on_def)\n\nlemma convex_onD_Icc:\n  assumes \"convex_on {x..y} f\" \"x \\<le> (y :: _ :: {real_vector,preorder})\"\n  shows \"\\<And>t. t \\<ge> 0 \\<Longrightarrow> t \\<le> 1 \\<Longrightarrow>\n    f ((1 - t) *\\<^sub>R x + t *\\<^sub>R y) \\<le> (1 - t) * f x + t * f y\"\n  using assms(2) by (intro convex_onD [OF assms(1)]) simp_all\n\nlemma convex_on_subset: \"convex_on t f \\<Longrightarrow> S \\<subseteq> t \\<Longrightarrow> convex_on S f\"\n  unfolding convex_on_def by auto\n\nlemma convex_on_add [intro]:\n  assumes \"convex_on S f\"\n    and \"convex_on S g\"\n  shows \"convex_on S (\\<lambda>x. f x + g x)\"\nproof -\n  {\n    fix x y\n    assume \"x \\<in> S\" \"y \\<in> S\"\n    moreover\n    fix u v :: real\n    assume \"0 \\<le> u\" \"0 \\<le> v\" \"u + v = 1\"\n    ultimately\n    have \"f (u *\\<^sub>R x + v *\\<^sub>R y) + g (u *\\<^sub>R x + v *\\<^sub>R y) \\<le> (u * f x + v * f y) + (u * g x + v * g y)\"\n      using assms unfolding convex_on_def by (auto simp: add_mono)\n    then have \"f (u *\\<^sub>R x + v *\\<^sub>R y) + g (u *\\<^sub>R x + v *\\<^sub>R y) \\<le> u * (f x + g x) + v * (f y + g y)\"\n      by (simp add: field_simps)\n  }\n  then show ?thesis\n    unfolding convex_on_def by auto\nqed\n\nlemma convex_on_cmul [intro]:\n  fixes c :: real\n  assumes \"0 \\<le> c\"\n    and \"convex_on S f\"\n  shows \"convex_on S (\\<lambda>x. c * f x)\"\nproof -\n  have *: \"u * (c * fx) + v * (c * fy) = c * (u * fx + v * fy)\"\n    for u c fx v fy :: real\n    by (simp add: field_simps)\n  show ?thesis using assms(2) and mult_left_mono [OF _ assms(1)]\n    unfolding convex_on_def and * by auto\nqed\n\nlemma convex_lower:\n  assumes \"convex_on S f\"\n    and \"x \\<in> S\"\n    and \"y \\<in> S\"\n    and \"0 \\<le> u\"\n    and \"0 \\<le> v\"\n    and \"u + v = 1\"\n  shows \"f (u *\\<^sub>R x + v *\\<^sub>R y) \\<le> max (f x) (f y)\"\nproof -\n  let ?m = \"max (f x) (f y)\"\n  have \"u * f x + v * f y \\<le> u * max (f x) (f y) + v * max (f x) (f y)\"\n    using assms(4,5) by (auto simp: mult_left_mono add_mono)\n  also have \"\\<dots> = max (f x) (f y)\"\n    using assms(6) by (simp add: distrib_right [symmetric])\n  finally show ?thesis\n    using assms unfolding convex_on_def by fastforce\nqed\n\nlemma convex_on_dist [intro]:\n  fixes S :: \"'a::real_normed_vector set\"\n  shows \"convex_on S (\\<lambda>x. dist a x)\"\nproof (auto simp: convex_on_def dist_norm)\n  fix x y\n  assume \"x \\<in> S\" \"y \\<in> S\"\n  fix u v :: real\n  assume \"0 \\<le> u\"\n  assume \"0 \\<le> v\"\n  assume \"u + v = 1\"\n  have \"a = u *\\<^sub>R a + v *\\<^sub>R a\"\n    unfolding scaleR_left_distrib[symmetric] and \\<open>u + v = 1\\<close> by simp\n  then have *: \"a - (u *\\<^sub>R x + v *\\<^sub>R y) = (u *\\<^sub>R (a - x)) + (v *\\<^sub>R (a - y))\"\n    by (auto simp: algebra_simps)\n  show \"norm (a - (u *\\<^sub>R x + v *\\<^sub>R y)) \\<le> u * norm (a - x) + v * norm (a - y)\"\n    unfolding * using norm_triangle_ineq[of \"u *\\<^sub>R (a - x)\" \"v *\\<^sub>R (a - y)\"]\n    using \\<open>0 \\<le> u\\<close> \\<open>0 \\<le> v\\<close> by auto\nqed\n\n\nsubsection\\<^marker>\\<open>tag unimportant\\<close> \\<open>Arithmetic operations on sets preserve convexity\\<close>\n\nlemma convex_linear_image:\n  assumes \"linear f\"\n    and \"convex S\"\n  shows \"convex (f ` S)\"\nproof -\n  interpret f: linear f by fact\n  from \\<open>convex S\\<close> show \"convex (f ` S)\"\n    by (simp add: convex_def f.scaleR [symmetric] f.add [symmetric])\nqed\n\nlemma convex_linear_vimage:\n  assumes \"linear f\"\n    and \"convex S\"\n  shows \"convex (f -` S)\"\nproof -\n  interpret f: linear f by fact\n  from \\<open>convex S\\<close> show \"convex (f -` S)\"\n    by (simp add: convex_def f.add f.scaleR)\nqed\n\nlemma convex_scaling:\n  assumes \"convex S\"\n  shows \"convex ((\\<lambda>x. c *\\<^sub>R x) ` S)\"\nproof -\n  have \"linear (\\<lambda>x. c *\\<^sub>R x)\"\n    by (simp add: linearI scaleR_add_right)\n  then show ?thesis\n    using \\<open>convex S\\<close> by (rule convex_linear_image)\nqed\n\nlemma convex_scaled:\n  assumes \"convex S\"\n  shows \"convex ((\\<lambda>x. x *\\<^sub>R c) ` S)\"\nproof -\n  have \"linear (\\<lambda>x. x *\\<^sub>R c)\"\n    by (simp add: linearI scaleR_add_left)\n  then show ?thesis\n    using \\<open>convex S\\<close> by (rule convex_linear_image)\nqed\n\nlemma convex_negations:\n  assumes \"convex S\"\n  shows \"convex ((\\<lambda>x. - x) ` S)\"\nproof -\n  have \"linear (\\<lambda>x. - x)\"\n    by (simp add: linearI)\n  then show ?thesis\n    using \\<open>convex S\\<close> by (rule convex_linear_image)\nqed\n\nlemma convex_sums:\n  assumes \"convex S\"\n    and \"convex T\"\n  shows \"convex (\\<Union>x\\<in> S. \\<Union>y \\<in> T. {x + y})\"\nproof -\n  have \"linear (\\<lambda>(x, y). x + y)\"\n    by (auto intro: linearI simp: scaleR_add_right)\n  with assms have \"convex ((\\<lambda>(x, y). x + y) ` (S \\<times> T))\"\n    by (intro convex_linear_image convex_Times)\n  also have \"((\\<lambda>(x, y). x + y) ` (S \\<times> T)) = (\\<Union>x\\<in> S. \\<Union>y \\<in> T. {x + y})\"\n    by auto\n  finally show ?thesis .\nqed\n\nlemma convex_differences:\n  assumes \"convex S\" \"convex T\"\n  shows \"convex (\\<Union>x\\<in> S. \\<Union>y \\<in> T. {x - y})\"\nproof -\n  have \"{x - y| x y. x \\<in> S \\<and> y \\<in> T} = {x + y |x y. x \\<in> S \\<and> y \\<in> uminus ` T}\"\n    by (auto simp: diff_conv_add_uminus simp del: add_uminus_conv_diff)\n  then show ?thesis\n    using convex_sums[OF assms(1) convex_negations[OF assms(2)]] by auto\nqed\n\nlemma convex_translation:\n  \"convex ((+) a ` S)\" if \"convex S\"\nproof -\n  have \"(\\<Union> x\\<in> {a}. \\<Union>y \\<in> S. {x + y}) = (+) a ` S\"\n    by auto\n  then show ?thesis\n    using convex_sums [OF convex_singleton [of a] that] by auto\nqed\n\nlemma convex_translation_subtract:\n  \"convex ((\\<lambda>b. b - a) ` S)\" if \"convex S\"\n  using convex_translation [of S \"- a\"] that by (simp cong: image_cong_simp)\n\nlemma convex_affinity:\n  assumes \"convex S\"\n  shows \"convex ((\\<lambda>x. a + c *\\<^sub>R x) ` S)\"\nproof -\n  have \"(\\<lambda>x. a + c *\\<^sub>R x) ` S = (+) a ` (*\\<^sub>R) c ` S\"\n    by auto\n  then show ?thesis\n    using convex_translation[OF convex_scaling[OF assms], of a c] by auto\nqed\n\nlemma convex_on_sum:\n  fixes a :: \"'a \\<Rightarrow> real\"\n    and y :: \"'a \\<Rightarrow> 'b::real_vector\"\n    and f :: \"'b \\<Rightarrow> real\"\n  assumes \"finite s\" \"s \\<noteq> {}\"\n    and \"convex_on C f\"\n    and \"convex C\"\n    and \"(\\<Sum> i \\<in> s. a i) = 1\"\n    and \"\\<And>i. i \\<in> s \\<Longrightarrow> a i \\<ge> 0\"\n    and \"\\<And>i. i \\<in> s \\<Longrightarrow> y i \\<in> C\"\n  shows \"f (\\<Sum> i \\<in> s. a i *\\<^sub>R y i) \\<le> (\\<Sum> i \\<in> s. a i * f (y i))\"\n  using assms\nproof (induct s arbitrary: a rule: finite_ne_induct)\n  case (singleton i)\n  then have ai: \"a i = 1\"\n    by auto\n  then show ?case\n    by auto\nnext\n  case (insert i s)\n  then have \"convex_on C f\"\n    by simp\n  from this[unfolded convex_on_def, rule_format]\n  have conv: \"\\<And>x y \\<mu>. x \\<in> C \\<Longrightarrow> y \\<in> C \\<Longrightarrow> 0 \\<le> \\<mu> \\<Longrightarrow> \\<mu> \\<le> 1 \\<Longrightarrow>\n      f (\\<mu> *\\<^sub>R x + (1 - \\<mu>) *\\<^sub>R y) \\<le> \\<mu> * f x + (1 - \\<mu>) * f y\"\n    by simp\n  show ?case\n  proof (cases \"a i = 1\")\n    case True\n    then have \"(\\<Sum> j \\<in> s. a j) = 0\"\n      using insert by auto\n    then have \"\\<And>j. j \\<in> s \\<Longrightarrow> a j = 0\"\n      using insert by (fastforce simp: sum_nonneg_eq_0_iff)\n    then show ?thesis\n      using insert by auto\n  next\n    case False\n    from insert have yai: \"y i \\<in> C\" \"a i \\<ge> 0\"\n      by auto\n    have fis: \"finite (insert i s)\"\n      using insert by auto\n    then have ai1: \"a i \\<le> 1\"\n      using sum_nonneg_leq_bound[of \"insert i s\" a] insert by simp\n    then have \"a i < 1\"\n      using False by auto\n    then have i0: \"1 - a i > 0\"\n      by auto\n    let ?a = \"\\<lambda>j. a j / (1 - a i)\"\n    have a_nonneg: \"?a j \\<ge> 0\" if \"j \\<in> s\" for j\n      using i0 insert that by fastforce\n    have \"(\\<Sum> j \\<in> insert i s. a j) = 1\"\n      using insert by auto\n    then have \"(\\<Sum> j \\<in> s. a j) = 1 - a i\"\n      using sum.insert insert by fastforce\n    then have \"(\\<Sum> j \\<in> s. a j) / (1 - a i) = 1\"\n      using i0 by auto\n    then have a1: \"(\\<Sum> j \\<in> s. ?a j) = 1\"\n      unfolding sum_divide_distrib by simp\n    have \"convex C\" using insert by auto\n    then have asum: \"(\\<Sum> j \\<in> s. ?a j *\\<^sub>R y j) \\<in> C\"\n      using insert convex_sum [OF \\<open>finite s\\<close> \\<open>convex C\\<close> a1 a_nonneg] by auto\n    have asum_le: \"f (\\<Sum> j \\<in> s. ?a j *\\<^sub>R y j) \\<le> (\\<Sum> j \\<in> s. ?a j * f (y j))\"\n      using a_nonneg a1 insert by blast\n    have \"f (\\<Sum> j \\<in> insert i s. a j *\\<^sub>R y j) = f ((\\<Sum> j \\<in> s. a j *\\<^sub>R y j) + a i *\\<^sub>R y i)\"\n      using sum.insert[of s i \"\\<lambda> j. a j *\\<^sub>R y j\", OF \\<open>finite s\\<close> \\<open>i \\<notin> s\\<close>] insert\n      by (auto simp only: add.commute)\n    also have \"\\<dots> = f (((1 - a i) * inverse (1 - a i)) *\\<^sub>R (\\<Sum> j \\<in> s. a j *\\<^sub>R y j) + a i *\\<^sub>R y i)\"\n      using i0 by auto\n    also have \"\\<dots> = f ((1 - a i) *\\<^sub>R (\\<Sum> j \\<in> s. (a j * inverse (1 - a i)) *\\<^sub>R y j) + a i *\\<^sub>R y i)\"\n      using scaleR_right.sum[of \"inverse (1 - a i)\" \"\\<lambda> j. a j *\\<^sub>R y j\" s, symmetric]\n      by (auto simp: algebra_simps)\n    also have \"\\<dots> = f ((1 - a i) *\\<^sub>R (\\<Sum> j \\<in> s. ?a j *\\<^sub>R y j) + a i *\\<^sub>R y i)\"\n      by (auto simp: divide_inverse)\n    also have \"\\<dots> \\<le> (1 - a i) *\\<^sub>R f ((\\<Sum> j \\<in> s. ?a j *\\<^sub>R y j)) + a i * f (y i)\"\n      using conv[of \"y i\" \"(\\<Sum> j \\<in> s. ?a j *\\<^sub>R y j)\" \"a i\", OF yai(1) asum yai(2) ai1]\n      by (auto simp: add.commute)\n    also have \"\\<dots> \\<le> (1 - a i) * (\\<Sum> j \\<in> s. ?a j * f (y j)) + a i * f (y i)\"\n      using add_right_mono [OF mult_left_mono [of _ _ \"1 - a i\",\n            OF asum_le less_imp_le[OF i0]], of \"a i * f (y i)\"]\n      by simp\n    also have \"\\<dots> = (\\<Sum> j \\<in> s. (1 - a i) * ?a j * f (y j)) + a i * f (y i)\"\n      unfolding sum_distrib_left[of \"1 - a i\" \"\\<lambda> j. ?a j * f (y j)\"]\n      using i0 by auto\n    also have \"\\<dots> = (\\<Sum> j \\<in> s. a j * f (y j)) + a i * f (y i)\"\n      using i0 by auto\n    also have \"\\<dots> = (\\<Sum> j \\<in> insert i s. a j * f (y j))\"\n      using insert by auto\n    finally show ?thesis\n      by simp\n  qed\nqed\n\nlemma convex_on_alt:\n  fixes C :: \"'a::real_vector set\"\n  shows \"convex_on C f \\<longleftrightarrow>\n    (\\<forall>x \\<in> C. \\<forall> y \\<in> C. \\<forall> \\<mu> :: real. \\<mu> \\<ge> 0 \\<and> \\<mu> \\<le> 1 \\<longrightarrow>\n      f (\\<mu> *\\<^sub>R x + (1 - \\<mu>) *\\<^sub>R y) \\<le> \\<mu> * f x + (1 - \\<mu>) * f y)\"\nproof safe\n  fix x y\n  fix \\<mu> :: real\n  assume *: \"convex_on C f\" \"x \\<in> C\" \"y \\<in> C\" \"0 \\<le> \\<mu>\" \"\\<mu> \\<le> 1\"\n  from this[unfolded convex_on_def, rule_format]\n  have \"0 \\<le> u \\<Longrightarrow> 0 \\<le> v \\<Longrightarrow> u + v = 1 \\<Longrightarrow> f (u *\\<^sub>R x + v *\\<^sub>R y) \\<le> u * f x + v * f y\" for u v\n    by auto\n  from this [of \"\\<mu>\" \"1 - \\<mu>\", simplified] *\n  show \"f (\\<mu> *\\<^sub>R x + (1 - \\<mu>) *\\<^sub>R y) \\<le> \\<mu> * f x + (1 - \\<mu>) * f y\"\n    by auto\nnext\n  assume *: \"\\<forall>x\\<in>C. \\<forall>y\\<in>C. \\<forall>\\<mu>. 0 \\<le> \\<mu> \\<and> \\<mu> \\<le> 1 \\<longrightarrow>\n    f (\\<mu> *\\<^sub>R x + (1 - \\<mu>) *\\<^sub>R y) \\<le> \\<mu> * f x + (1 - \\<mu>) * f y\"\n  {\n    fix x y\n    fix u v :: real\n    assume **: \"x \\<in> C\" \"y \\<in> C\" \"u \\<ge> 0\" \"v \\<ge> 0\" \"u + v = 1\"\n    then have[simp]: \"1 - u = v\" by auto\n    from *[rule_format, of x y u]\n    have \"f (u *\\<^sub>R x + v *\\<^sub>R y) \\<le> u * f x + v * f y\"\n      using ** by auto\n  }\n  then show \"convex_on C f\"\n    unfolding convex_on_def by auto\nqed\n\nlemma convex_on_diff:\n  fixes f :: \"real \\<Rightarrow> real\"\n  assumes f: \"convex_on I f\"\n    and I: \"x \\<in> I\" \"y \\<in> I\"\n    and t: \"x < t\" \"t < y\"\n  shows \"(f x - f t) / (x - t) \\<le> (f x - f y) / (x - y)\"\n    and \"(f x - f y) / (x - y) \\<le> (f t - f y) / (t - y)\"\nproof -\n  define a where \"a \\<equiv> (t - y) / (x - y)\"\n  with t have \"0 \\<le> a\" \"0 \\<le> 1 - a\"\n    by (auto simp: field_simps)\n  with f \\<open>x \\<in> I\\<close> \\<open>y \\<in> I\\<close> have cvx: \"f (a * x + (1 - a) * y) \\<le> a * f x + (1 - a) * f y\"\n    by (auto simp: convex_on_def)\n  have \"a * x + (1 - a) * y = a * (x - y) + y\"\n    by (simp add: field_simps)\n  also have \"\\<dots> = t\"\n    unfolding a_def using \\<open>x < t\\<close> \\<open>t < y\\<close> by simp\n  finally have \"f t \\<le> a * f x + (1 - a) * f y\"\n    using cvx by simp\n  also have \"\\<dots> = a * (f x - f y) + f y\"\n    by (simp add: field_simps)\n  finally have \"f t - f y \\<le> a * (f x - f y)\"\n    by simp\n  with t show \"(f x - f t) / (x - t) \\<le> (f x - f y) / (x - y)\"\n    by (simp add: le_divide_eq divide_le_eq field_simps a_def)\n  with t show \"(f x - f y) / (x - y) \\<le> (f t - f y) / (t - y)\"\n    by (simp add: le_divide_eq divide_le_eq field_simps)\nqed\n\nlemma pos_convex_function:\n  fixes f :: \"real \\<Rightarrow> real\"\n  assumes \"convex C\"\n    and leq: \"\\<And>x y. x \\<in> C \\<Longrightarrow> y \\<in> C \\<Longrightarrow> f' x * (y - x) \\<le> f y - f x\"\n  shows \"convex_on C f\"\n  unfolding convex_on_alt\n  using assms\nproof safe\n  fix x y \\<mu> :: real\n  let ?x = \"\\<mu> *\\<^sub>R x + (1 - \\<mu>) *\\<^sub>R y\"\n  assume *: \"convex C\" \"x \\<in> C\" \"y \\<in> C\" \"\\<mu> \\<ge> 0\" \"\\<mu> \\<le> 1\"\n  then have \"1 - \\<mu> \\<ge> 0\" by auto\n  then have xpos: \"?x \\<in> C\"\n    using * unfolding convex_alt by fastforce\n  have geq: \"\\<mu> * (f x - f ?x) + (1 - \\<mu>) * (f y - f ?x) \\<ge>\n      \\<mu> * f' ?x * (x - ?x) + (1 - \\<mu>) * f' ?x * (y - ?x)\"\n    using add_mono [OF mult_left_mono [OF leq [OF xpos *(2)] \\<open>\\<mu> \\<ge> 0\\<close>]\n        mult_left_mono [OF leq [OF xpos *(3)] \\<open>1 - \\<mu> \\<ge> 0\\<close>]]\n    by auto\n  then have \"\\<mu> * f x + (1 - \\<mu>) * f y - f ?x \\<ge> 0\"\n    by (auto simp: field_simps)\n  then show \"f (\\<mu> *\\<^sub>R x + (1 - \\<mu>) *\\<^sub>R y) \\<le> \\<mu> * f x + (1 - \\<mu>) * f y\"\n    by auto\nqed\n\nlemma atMostAtLeast_subset_convex:\n  fixes C :: \"real set\"\n  assumes \"convex C\"\n    and \"x \\<in> C\" \"y \\<in> C\" \"x < y\"\n  shows \"{x .. y} \\<subseteq> C\"\nproof safe\n  fix z assume z: \"z \\<in> {x .. y}\"\n  have less: \"z \\<in> C\" if *: \"x < z\" \"z < y\"\n  proof -\n    let ?\\<mu> = \"(y - z) / (y - x)\"\n    have \"0 \\<le> ?\\<mu>\" \"?\\<mu> \\<le> 1\"\n      using assms * by (auto simp: field_simps)\n    then have comb: \"?\\<mu> * x + (1 - ?\\<mu>) * y \\<in> C\"\n      using assms iffD1[OF convex_alt, rule_format, of C y x ?\\<mu>]\n      by (simp add: algebra_simps)\n    have \"?\\<mu> * x + (1 - ?\\<mu>) * y = (y - z) * x / (y - x) + (1 - (y - z) / (y - x)) * y\"\n      by (auto simp: field_simps)\n    also have \"\\<dots> = ((y - z) * x + (y - x - (y - z)) * y) / (y - x)\"\n      using assms by (simp only: add_divide_distrib) (auto simp: field_simps)\n    also have \"\\<dots> = z\"\n      using assms by (auto simp: field_simps)\n    finally show ?thesis\n      using comb by auto\n  qed\n  show \"z \\<in> C\"\n    using z less assms by (auto simp: le_less)\nqed\n\nlemma f''_imp_f':\n  fixes f :: \"real \\<Rightarrow> real\"\n  assumes \"convex C\"\n    and f': \"\\<And>x. x \\<in> C \\<Longrightarrow> DERIV f x :> (f' x)\"\n    and f'': \"\\<And>x. x \\<in> C \\<Longrightarrow> DERIV f' x :> (f'' x)\"\n    and pos: \"\\<And>x. x \\<in> C \\<Longrightarrow> f'' x \\<ge> 0\"\n    and x: \"x \\<in> C\"\n    and y: \"y \\<in> C\"\n  shows \"f' x * (y - x) \\<le> f y - f x\"\n  using assms\nproof -\n  have less_imp: \"f y - f x \\<ge> f' x * (y - x)\" \"f' y * (x - y) \\<le> f x - f y\"\n    if *: \"x \\<in> C\" \"y \\<in> C\" \"y > x\" for x y :: real\n  proof -\n    from * have ge: \"y - x > 0\" \"y - x \\<ge> 0\"\n      by auto\n    from * have le: \"x - y < 0\" \"x - y \\<le> 0\"\n      by auto\n    then obtain z1 where z1: \"z1 > x\" \"z1 < y\" \"f y - f x = (y - x) * f' z1\"\n      using subsetD[OF atMostAtLeast_subset_convex[OF \\<open>convex C\\<close> \\<open>x \\<in> C\\<close> \\<open>y \\<in> C\\<close> \\<open>x < y\\<close>],\n          THEN f', THEN MVT2[OF \\<open>x < y\\<close>, rule_format, unfolded atLeastAtMost_iff[symmetric]]]\n      by auto\n    then have \"z1 \\<in> C\"\n      using atMostAtLeast_subset_convex \\<open>convex C\\<close> \\<open>x \\<in> C\\<close> \\<open>y \\<in> C\\<close> \\<open>x < y\\<close>\n      by fastforce\n    from z1 have z1': \"f x - f y = (x - y) * f' z1\"\n      by (simp add: field_simps)\n    obtain z2 where z2: \"z2 > x\" \"z2 < z1\" \"f' z1 - f' x = (z1 - x) * f'' z2\"\n      using subsetD[OF atMostAtLeast_subset_convex[OF \\<open>convex C\\<close> \\<open>x \\<in> C\\<close> \\<open>z1 \\<in> C\\<close> \\<open>x < z1\\<close>],\n          THEN f'', THEN MVT2[OF \\<open>x < z1\\<close>, rule_format, unfolded atLeastAtMost_iff[symmetric]]] z1\n      by auto\n    obtain z3 where z3: \"z3 > z1\" \"z3 < y\" \"f' y - f' z1 = (y - z1) * f'' z3\"\n      using subsetD[OF atMostAtLeast_subset_convex[OF \\<open>convex C\\<close> \\<open>z1 \\<in> C\\<close> \\<open>y \\<in> C\\<close> \\<open>z1 < y\\<close>],\n          THEN f'', THEN MVT2[OF \\<open>z1 < y\\<close>, rule_format, unfolded atLeastAtMost_iff[symmetric]]] z1\n      by auto\n    have \"f' y - (f x - f y) / (x - y) = f' y - f' z1\"\n      using * z1' by auto\n    also have \"\\<dots> = (y - z1) * f'' z3\"\n      using z3 by auto\n    finally have cool': \"f' y - (f x - f y) / (x - y) = (y - z1) * f'' z3\"\n      by simp\n    have A': \"y - z1 \\<ge> 0\"\n      using z1 by auto\n    have \"z3 \\<in> C\"\n      using z3 * atMostAtLeast_subset_convex \\<open>convex C\\<close> \\<open>x \\<in> C\\<close> \\<open>z1 \\<in> C\\<close> \\<open>x < z1\\<close>\n      by fastforce\n    then have B': \"f'' z3 \\<ge> 0\"\n      using assms by auto\n    from A' B' have \"(y - z1) * f'' z3 \\<ge> 0\"\n      by auto\n    from cool' this have \"f' y - (f x - f y) / (x - y) \\<ge> 0\"\n      by auto\n    from mult_right_mono_neg[OF this le(2)]\n    have \"f' y * (x - y) - (f x - f y) / (x - y) * (x - y) \\<le> 0 * (x - y)\"\n      by (simp add: algebra_simps)\n    then have \"f' y * (x - y) - (f x - f y) \\<le> 0\"\n      using le by auto\n    then have res: \"f' y * (x - y) \\<le> f x - f y\"\n      by auto\n    have \"(f y - f x) / (y - x) - f' x = f' z1 - f' x\"\n      using * z1 by auto\n    also have \"\\<dots> = (z1 - x) * f'' z2\"\n      using z2 by auto\n    finally have cool: \"(f y - f x) / (y - x) - f' x = (z1 - x) * f'' z2\"\n      by simp\n    have A: \"z1 - x \\<ge> 0\"\n      using z1 by auto\n    have \"z2 \\<in> C\"\n      using z2 z1 * atMostAtLeast_subset_convex \\<open>convex C\\<close> \\<open>z1 \\<in> C\\<close> \\<open>y \\<in> C\\<close> \\<open>z1 < y\\<close>\n      by fastforce\n    then have B: \"f'' z2 \\<ge> 0\"\n      using assms by auto\n    from A B have \"(z1 - x) * f'' z2 \\<ge> 0\"\n      by auto\n    with cool have \"(f y - f x) / (y - x) - f' x \\<ge> 0\"\n      by auto\n    from mult_right_mono[OF this ge(2)]\n    have \"(f y - f x) / (y - x) * (y - x) - f' x * (y - x) \\<ge> 0 * (y - x)\"\n      by (simp add: algebra_simps)\n    then have \"f y - f x - f' x * (y - x) \\<ge> 0\"\n      using ge by auto\n    then show \"f y - f x \\<ge> f' x * (y - x)\" \"f' y * (x - y) \\<le> f x - f y\"\n      using res by auto\n  qed\n  show ?thesis\n  proof (cases \"x = y\")\n    case True\n    with x y show ?thesis by auto\n  next\n    case False\n    with less_imp x y show ?thesis\n      by (auto simp: neq_iff)\n  qed\nqed\n\nlemma f''_ge0_imp_convex:\n  fixes f :: \"real \\<Rightarrow> real\"\n  assumes conv: \"convex C\"\n    and f': \"\\<And>x. x \\<in> C \\<Longrightarrow> DERIV f x :> (f' x)\"\n    and f'': \"\\<And>x. x \\<in> C \\<Longrightarrow> DERIV f' x :> (f'' x)\"\n    and 0: \"\\<And>x. x \\<in> C \\<Longrightarrow> f'' x \\<ge> 0\"\n  shows \"convex_on C f\"\n  using f''_imp_f'[OF conv f' f'' 0] assms pos_convex_function\n  by fastforce\n\nlemma f''_le0_imp_concave:\n  fixes f :: \"real \\<Rightarrow> real\"\n  assumes \"convex C\"\n    and \"\\<And>x. x \\<in> C \\<Longrightarrow> DERIV f x :> (f' x)\"\n    and \"\\<And>x. x \\<in> C \\<Longrightarrow> DERIV f' x :> (f'' x)\"\n    and \"\\<And>x. x \\<in> C \\<Longrightarrow> f'' x \\<le> 0\"\n  shows \"concave_on C f\"\n  unfolding concave_on_def\n  by (rule assms f''_ge0_imp_convex derivative_eq_intros | simp)+\n\nlemma log_concave:\n  fixes b :: real\n  assumes \"b > 1\"\n  shows \"concave_on {0<..} (\\<lambda> x. log b x)\"\n  using assms\n  by (intro f''_le0_imp_concave derivative_eq_intros | simp)+\n\nlemma ln_concave: \"concave_on {0<..} ln\"\n  unfolding log_ln by (simp add: log_concave)\n\nlemma minus_log_convex:\n  fixes b :: real\n  assumes \"b > 1\"\n  shows \"convex_on {0 <..} (\\<lambda> x. - log b x)\"\n  using assms concave_on_def log_concave by blast\n\nlemma powr_convex: \n  assumes \"p \\<ge> 1\" shows \"convex_on {0<..} (\\<lambda>x. x powr p)\"\n  using assms\n  by (intro f''_ge0_imp_convex derivative_eq_intros | simp)+\n\nlemma exp_convex: \"convex_on UNIV exp\"\n  by (intro f''_ge0_imp_convex derivative_eq_intros | simp)+\n\n\nsubsection\\<^marker>\\<open>tag unimportant\\<close> \\<open>Convexity of real functions\\<close>\n\nlemma convex_on_realI:\n  assumes \"connected A\"\n    and \"\\<And>x. x \\<in> A \\<Longrightarrow> (f has_real_derivative f' x) (at x)\"\n    and \"\\<And>x y. x \\<in> A \\<Longrightarrow> y \\<in> A \\<Longrightarrow> x \\<le> y \\<Longrightarrow> f' x \\<le> f' y\"\n  shows \"convex_on A f\"\nproof (rule convex_on_linorderI)\n  fix t x y :: real\n  assume t: \"t > 0\" \"t < 1\"\n  assume xy: \"x \\<in> A\" \"y \\<in> A\" \"x < y\"\n  define z where \"z = (1 - t) * x + t * y\"\n  with \\<open>connected A\\<close> and xy have ivl: \"{x..y} \\<subseteq> A\"\n    using connected_contains_Icc by blast\n\n  from xy t have xz: \"z > x\"\n    by (simp add: z_def algebra_simps)\n  have \"y - z = (1 - t) * (y - x)\"\n    by (simp add: z_def algebra_simps)\n  also from xy t have \"\\<dots> > 0\"\n    by (intro mult_pos_pos) simp_all\n  finally have yz: \"z < y\"\n    by simp\n\n  from assms xz yz ivl t have \"\\<exists>\\<xi>. \\<xi> > x \\<and> \\<xi> < z \\<and> f z - f x = (z - x) * f' \\<xi>\"\n    by (intro MVT2) (auto intro!: assms(2))\n  then obtain \\<xi> where \\<xi>: \"\\<xi> > x\" \"\\<xi> < z\" \"f' \\<xi> = (f z - f x) / (z - x)\"\n    by auto\n  from assms xz yz ivl t have \"\\<exists>\\<eta>. \\<eta> > z \\<and> \\<eta> < y \\<and> f y - f z = (y - z) * f' \\<eta>\"\n    by (intro MVT2) (auto intro!: assms(2))\n  then obtain \\<eta> where \\<eta>: \"\\<eta> > z\" \"\\<eta> < y\" \"f' \\<eta> = (f y - f z) / (y - z)\"\n    by auto\n\n  from \\<eta>(3) have \"(f y - f z) / (y - z) = f' \\<eta>\" ..\n  also from \\<xi> \\<eta> ivl have \"\\<xi> \\<in> A\" \"\\<eta> \\<in> A\"\n    by auto\n  with \\<xi> \\<eta> have \"f' \\<eta> \\<ge> f' \\<xi>\"\n    by (intro assms(3)) auto\n  also from \\<xi>(3) have \"f' \\<xi> = (f z - f x) / (z - x)\" .\n  finally have \"(f y - f z) * (z - x) \\<ge> (f z - f x) * (y - z)\"\n    using xz yz by (simp add: field_simps)\n  also have \"z - x = t * (y - x)\"\n    by (simp add: z_def algebra_simps)\n  also have \"y - z = (1 - t) * (y - x)\"\n    by (simp add: z_def algebra_simps)\n  finally have \"(f y - f z) * t \\<ge> (f z - f x) * (1 - t)\"\n    using xy by simp\n  then show \"(1 - t) * f x + t * f y \\<ge> f ((1 - t) *\\<^sub>R x + t *\\<^sub>R y)\"\n    by (simp add: z_def algebra_simps)\nqed\n\nlemma convex_on_inverse:\n  assumes \"A \\<subseteq> {0<..}\"\n  shows \"convex_on A (inverse :: real \\<Rightarrow> real)\"\nproof (rule convex_on_subset[OF _ assms], intro convex_on_realI[of _ _ \"\\<lambda>x. -inverse (x^2)\"])\n  fix u v :: real\n  assume \"u \\<in> {0<..}\" \"v \\<in> {0<..}\" \"u \\<le> v\"\n  with assms show \"-inverse (u^2) \\<le> -inverse (v^2)\"\n    by (intro le_imp_neg_le le_imp_inverse_le power_mono) (simp_all)\nqed (insert assms, auto intro!: derivative_eq_intros simp: field_split_simps power2_eq_square)\n\nlemma convex_onD_Icc':\n  assumes \"convex_on {x..y} f\" \"c \\<in> {x..y}\"\n  defines \"d \\<equiv> y - x\"\n  shows \"f c \\<le> (f y - f x) / d * (c - x) + f x\"\nproof (cases x y rule: linorder_cases)\n  case less\n  then have d: \"d > 0\"\n    by (simp add: d_def)\n  from assms(2) less have A: \"0 \\<le> (c - x) / d\" \"(c - x) / d \\<le> 1\"\n    by (simp_all add: d_def field_split_simps)\n  have \"f c = f (x + (c - x) * 1)\"\n    by simp\n  also from less have \"1 = ((y - x) / d)\"\n    by (simp add: d_def)\n  also from d have \"x + (c - x) * \\<dots> = (1 - (c - x) / d) *\\<^sub>R x + ((c - x) / d) *\\<^sub>R y\"\n    by (simp add: field_simps)\n  also have \"f \\<dots> \\<le> (1 - (c - x) / d) * f x + (c - x) / d * f y\"\n    using assms less by (intro convex_onD_Icc) simp_all\n  also from d have \"\\<dots> = (f y - f x) / d * (c - x) + f x\"\n    by (simp add: field_simps)\n  finally show ?thesis .\nqed (insert assms(2), simp_all)\n\nlemma convex_onD_Icc'':\n  assumes \"convex_on {x..y} f\" \"c \\<in> {x..y}\"\n  defines \"d \\<equiv> y - x\"\n  shows \"f c \\<le> (f x - f y) / d * (y - c) + f y\"\nproof (cases x y rule: linorder_cases)\n  case less\n  then have d: \"d > 0\"\n    by (simp add: d_def)\n  from assms(2) less have A: \"0 \\<le> (y - c) / d\" \"(y - c) / d \\<le> 1\"\n    by (simp_all add: d_def field_split_simps)\n  have \"f c = f (y - (y - c) * 1)\"\n    by simp\n  also from less have \"1 = ((y - x) / d)\"\n    by (simp add: d_def)\n  also from d have \"y - (y - c) * \\<dots> = (1 - (1 - (y - c) / d)) *\\<^sub>R x + (1 - (y - c) / d) *\\<^sub>R y\"\n    by (simp add: field_simps)\n  also have \"f \\<dots> \\<le> (1 - (1 - (y - c) / d)) * f x + (1 - (y - c) / d) * f y\"\n    using assms less by (intro convex_onD_Icc) (simp_all add: field_simps)\n  also from d have \"\\<dots> = (f x - f y) / d * (y - c) + f y\"\n    by (simp add: field_simps)\n  finally show ?thesis .\nqed (insert assms(2), simp_all)\n\nsubsection \\<open>Some inequalities\\<close>\n\nlemma Youngs_inequality_0:\n  fixes a::real\n  assumes \"0 \\<le> \\<alpha>\" \"0 \\<le> \\<beta>\" \"\\<alpha>+\\<beta> = 1\" \"a>0\" \"b>0\"\n  shows \"a powr \\<alpha> * b powr \\<beta> \\<le> \\<alpha>*a + \\<beta>*b\"\nproof -\n  have \"\\<alpha> * ln a + \\<beta> * ln b \\<le> ln (\\<alpha> * a + \\<beta> * b)\"\n    using assms ln_concave by (simp add: concave_on_iff)\n  moreover have \"0 < \\<alpha> * a + \\<beta> * b\"\n    using assms by (smt (verit) mult_pos_pos split_mult_pos_le)\n  ultimately show ?thesis\n    using assms by (simp add: powr_def mult_exp_exp flip: ln_ge_iff)\nqed\n\nlemma Youngs_inequality:\n  fixes p::real\n  assumes \"p>1\" \"q>1\" \"1/p + 1/q = 1\" \"a\\<ge>0\" \"b\\<ge>0\"\n  shows \"a * b \\<le> a powr p / p + b powr q / q\"\nproof (cases \"a=0 \\<or> b=0\")\n  case False\n  then show ?thesis \n  using Youngs_inequality_0 [of \"1/p\" \"1/q\" \"a powr p\" \"b powr q\"] assms\n  by (simp add: powr_powr)\nqed (use assms in auto)\n\nlemma Cauchy_Schwarz_ineq_sum:\n  fixes a :: \"'a \\<Rightarrow> 'b::linordered_field\"\n  shows \"(\\<Sum>i\\<in>I. a i * b i)\\<^sup>2 \\<le> (\\<Sum>i\\<in>I. (a i)\\<^sup>2) * (\\<Sum>i\\<in>I. (b i)\\<^sup>2)\"\nproof (cases \"(\\<Sum>i\\<in>I. (b i)\\<^sup>2) > 0\")\n  case False\n  then consider \"\\<And>i. i\\<in>I \\<Longrightarrow> b i = 0\" | \"infinite I\"\n    by (metis (mono_tags, lifting) sum_pos2 zero_le_power2 zero_less_power2)\n  thus ?thesis\n    by fastforce\nnext\n  case True\n  define r where \"r \\<equiv> (\\<Sum>i\\<in>I. a i * b i) / (\\<Sum>i\\<in>I. (b i)\\<^sup>2)\"\n  with True have *: \"(\\<Sum>i\\<in>I. a i * b i) = r * (\\<Sum>i\\<in>I. (b i)\\<^sup>2)\"\n    by simp\n  have \"0 \\<le> (\\<Sum>i\\<in>I. (a i - r * b i)\\<^sup>2)\"\n    by (meson sum_nonneg zero_le_power2)\n  also have \"... = (\\<Sum>i\\<in>I. (a i)\\<^sup>2) - 2 * r * (\\<Sum>i\\<in>I. a i * b i) + r\\<^sup>2 * (\\<Sum>i\\<in>I. (b i)\\<^sup>2)\"\n    by (simp add: algebra_simps power2_eq_square sum_distrib_left flip: sum.distrib)\n  also have \"\\<dots> = (\\<Sum>i\\<in>I. (a i)\\<^sup>2) - (\\<Sum>i\\<in>I. a i * b i) * r\"\n    by (simp add: * power2_eq_square)\n  also have \"\\<dots> = (\\<Sum>i\\<in>I. (a i)\\<^sup>2) - ((\\<Sum>i\\<in>I. a i * b i))\\<^sup>2 / (\\<Sum>i\\<in>I. (b i)\\<^sup>2)\"\n    by (simp add: r_def power2_eq_square)\n  finally have \"0 \\<le> (\\<Sum>i\\<in>I. (a i)\\<^sup>2) - ((\\<Sum>i\\<in>I. a i * b i))\\<^sup>2 / (\\<Sum>i\\<in>I. (b i)\\<^sup>2)\" .\n  hence \"((\\<Sum>i\\<in>I. a i * b i))\\<^sup>2 / (\\<Sum>i\\<in>I. (b i)\\<^sup>2) \\<le> (\\<Sum>i\\<in>I. (a i)\\<^sup>2)\"\n    by (simp add: le_diff_eq)\n  thus \"((\\<Sum>i\\<in>I. a i * b i))\\<^sup>2 \\<le> (\\<Sum>i\\<in>I. (a i)\\<^sup>2) * (\\<Sum>i\\<in>I. (b i)\\<^sup>2)\"\n    by (simp add: pos_divide_le_eq True)\nqed\n\nsubsection \\<open>Misc related lemmas\\<close>\n\nlemma convex_translation_eq [simp]:\n  \"convex ((+) a ` s) \\<longleftrightarrow> convex s\"\n  by (metis convex_translation translation_galois)\n\nlemma convex_translation_subtract_eq [simp]:\n  \"convex ((\\<lambda>b. b - a) ` s) \\<longleftrightarrow> convex s\"\n  using convex_translation_eq [of \"- a\"] by (simp cong: image_cong_simp)\n\nlemma convex_linear_image_eq [simp]:\n    fixes f :: \"'a::real_vector \\<Rightarrow> 'b::real_vector\"\n    shows \"\\<lbrakk>linear f; inj f\\<rbrakk> \\<Longrightarrow> convex (f ` s) \\<longleftrightarrow> convex s\"\n    by (metis (no_types) convex_linear_image convex_linear_vimage inj_vimage_image_eq)\n\nlemma vector_choose_size:\n  assumes \"0 \\<le> c\"\n  obtains x :: \"'a::{real_normed_vector, perfect_space}\" where \"norm x = c\"\nproof -\n  obtain a::'a where \"a \\<noteq> 0\"\n    using UNIV_not_singleton UNIV_eq_I set_zero singletonI by fastforce\n  then show ?thesis\n    by (rule_tac x=\"scaleR (c / norm a) a\" in that) (simp add: assms)\nqed\n\nlemma vector_choose_dist:\n  assumes \"0 \\<le> c\"\n  obtains y :: \"'a::{real_normed_vector, perfect_space}\" where \"dist x y = c\"\nby (metis add_diff_cancel_left' assms dist_commute dist_norm vector_choose_size)\n\nlemma sum_delta'':\n  fixes s::\"'a::real_vector set\"\n  assumes \"finite s\"\n  shows \"(\\<Sum>x\\<in>s. (if y = x then f x else 0) *\\<^sub>R x) = (if y\\<in>s then (f y) *\\<^sub>R y else 0)\"\nproof -\n  have *: \"\\<And>x y. (if y = x then f x else (0::real)) *\\<^sub>R x = (if x=y then (f x) *\\<^sub>R x else 0)\"\n    by auto\n  show ?thesis\n    unfolding * using sum.delta[OF assms, of y \"\\<lambda>x. f x *\\<^sub>R x\"] by auto\nqed\n\n\nsubsection \\<open>Cones\\<close>\n\ndefinition\\<^marker>\\<open>tag important\\<close> cone :: \"'a::real_vector set \\<Rightarrow> bool\"\n  where \"cone s \\<longleftrightarrow> (\\<forall>x\\<in>s. \\<forall>c\\<ge>0. c *\\<^sub>R x \\<in> s)\"\n\nlemma cone_empty[intro, simp]: \"cone {}\"\n  unfolding cone_def by auto\n\nlemma cone_univ[intro, simp]: \"cone UNIV\"\n  unfolding cone_def by auto\n\nlemma cone_Inter[intro]: \"\\<forall>s\\<in>f. cone s \\<Longrightarrow> cone (\\<Inter>f)\"\n  unfolding cone_def by auto\n\nlemma subspace_imp_cone: \"subspace S \\<Longrightarrow> cone S\"\n  by (simp add: cone_def subspace_scale)\n\n\nsubsubsection \\<open>Conic hull\\<close>\n\nlemma cone_cone_hull: \"cone (cone hull S)\"\n  unfolding hull_def by auto\n\nlemma cone_hull_eq: \"cone hull S = S \\<longleftrightarrow> cone S\"\n  by (metis cone_cone_hull hull_same)\n\nlemma mem_cone:\n  assumes \"cone S\" \"x \\<in> S\" \"c \\<ge> 0\"\n  shows \"c *\\<^sub>R x \\<in> S\"\n  using assms cone_def[of S] by auto\n\nlemma cone_contains_0:\n  assumes \"cone S\"\n  shows \"S \\<noteq> {} \\<longleftrightarrow> 0 \\<in> S\"\n  using assms mem_cone by fastforce\n\nlemma cone_0: \"cone {0}\"\n  unfolding cone_def by auto\n\nlemma cone_Union[intro]: \"(\\<forall>s\\<in>f. cone s) \\<longrightarrow> cone (\\<Union>f)\"\n  unfolding cone_def by blast\n\nlemma cone_iff:\n  assumes \"S \\<noteq> {}\"\n  shows \"cone S \\<longleftrightarrow> 0 \\<in> S \\<and> (\\<forall>c. c > 0 \\<longrightarrow> ((*\\<^sub>R) c) ` S = S)\"\nproof -\n  {\n    assume \"cone S\"\n    {\n      fix c :: real\n      assume \"c > 0\"\n      {\n        fix x\n        assume \"x \\<in> S\"\n        then have \"x \\<in> ((*\\<^sub>R) c) ` S\"\n          unfolding image_def\n          using \\<open>cone S\\<close> \\<open>c>0\\<close> mem_cone[of S x \"1/c\"]\n            exI[of \"(\\<lambda>t. t \\<in> S \\<and> x = c *\\<^sub>R t)\" \"(1 / c) *\\<^sub>R x\"]\n          by auto\n      }\n      moreover\n      {\n        fix x\n        assume \"x \\<in> ((*\\<^sub>R) c) ` S\"\n        then have \"x \\<in> S\"\n          using \\<open>0 < c\\<close> \\<open>cone S\\<close> mem_cone by fastforce\n      }\n      ultimately have \"((*\\<^sub>R) c) ` S = S\" by blast\n    }\n    then have \"0 \\<in> S \\<and> (\\<forall>c. c > 0 \\<longrightarrow> ((*\\<^sub>R) c) ` S = S)\"\n      using \\<open>cone S\\<close> cone_contains_0[of S] assms by auto\n  }\n  moreover\n  {\n    assume a: \"0 \\<in> S \\<and> (\\<forall>c. c > 0 \\<longrightarrow> ((*\\<^sub>R) c) ` S = S)\"\n    {\n      fix x\n      assume \"x \\<in> S\"\n      fix c1 :: real\n      assume \"c1 \\<ge> 0\"\n      then have \"c1 = 0 \\<or> c1 > 0\" by auto\n      then have \"c1 *\\<^sub>R x \\<in> S\" using a \\<open>x \\<in> S\\<close> by auto\n    }\n    then have \"cone S\" unfolding cone_def by auto\n  }\n  ultimately show ?thesis by blast\nqed\n\nlemma cone_hull_empty: \"cone hull {} = {}\"\n  by (metis cone_empty cone_hull_eq)\n\nlemma cone_hull_empty_iff: \"S = {} \\<longleftrightarrow> cone hull S = {}\"\n  by (metis bot_least cone_hull_empty hull_subset xtrans(5))\n\nlemma cone_hull_contains_0: \"S \\<noteq> {} \\<longleftrightarrow> 0 \\<in> cone hull S\"\n  using cone_cone_hull[of S] cone_contains_0[of \"cone hull S\"] cone_hull_empty_iff[of S]\n  by auto\n\nlemma mem_cone_hull:\n  assumes \"x \\<in> S\" \"c \\<ge> 0\"\n  shows \"c *\\<^sub>R x \\<in> cone hull S\"\n  by (metis assms cone_cone_hull hull_inc mem_cone)\n\nproposition cone_hull_expl: \"cone hull S = {c *\\<^sub>R x | c x. c \\<ge> 0 \\<and> x \\<in> S}\"\n  (is \"?lhs = ?rhs\")\nproof -\n  {\n    fix x\n    assume \"x \\<in> ?rhs\"\n    then obtain cx :: real and xx where x: \"x = cx *\\<^sub>R xx\" \"cx \\<ge> 0\" \"xx \\<in> S\"\n      by auto\n    fix c :: real\n    assume c: \"c \\<ge> 0\"\n    then have \"c *\\<^sub>R x = (c * cx) *\\<^sub>R xx\"\n      using x by (simp add: algebra_simps)\n    moreover\n    have \"c * cx \\<ge> 0\" using c x by auto\n    ultimately\n    have \"c *\\<^sub>R x \\<in> ?rhs\" using x by auto\n  }\n  then have \"cone ?rhs\"\n    unfolding cone_def by auto\n  then have \"?rhs \\<in> Collect cone\"\n    unfolding mem_Collect_eq by auto\n  {\n    fix x\n    assume \"x \\<in> S\"\n    then have \"1 *\\<^sub>R x \\<in> ?rhs\"\n      using zero_le_one by blast\n    then have \"x \\<in> ?rhs\" by auto\n  }\n  then have \"S \\<subseteq> ?rhs\" by auto\n  then have \"?lhs \\<subseteq> ?rhs\"\n    using \\<open>?rhs \\<in> Collect cone\\<close> hull_minimal[of S \"?rhs\" \"cone\"] by auto\n  moreover\n  {\n    fix x\n    assume \"x \\<in> ?rhs\"\n    then obtain cx :: real and xx where x: \"x = cx *\\<^sub>R xx\" \"cx \\<ge> 0\" \"xx \\<in> S\"\n      by auto\n    then have \"xx \\<in> cone hull S\"\n      using hull_subset[of S] by auto\n    then have \"x \\<in> ?lhs\"\n      using x cone_cone_hull[of S] cone_def[of \"cone hull S\"] by auto\n  }\n  ultimately show ?thesis by auto\nqed\n\nlemma convex_cone:\n  \"convex s \\<and> cone s \\<longleftrightarrow> (\\<forall>x\\<in>s. \\<forall>y\\<in>s. (x + y) \\<in> s) \\<and> (\\<forall>x\\<in>s. \\<forall>c\\<ge>0. (c *\\<^sub>R x) \\<in> s)\"\n  (is \"?lhs = ?rhs\")\nproof -\n  {\n    fix x y\n    assume \"x\\<in>s\" \"y\\<in>s\" and ?lhs\n    then have \"2 *\\<^sub>R x \\<in>s\" \"2 *\\<^sub>R y \\<in> s\"\n      unfolding cone_def by auto\n    then have \"x + y \\<in> s\"\n      using \\<open>?lhs\\<close>[unfolded convex_def, THEN conjunct1]\n      apply (erule_tac x=\"2*\\<^sub>R x\" in ballE)\n      apply (erule_tac x=\"2*\\<^sub>R y\" in ballE)\n      apply (erule_tac x=\"1/2\" in allE, simp)\n      apply (erule_tac x=\"1/2\" in allE, auto)\n      done\n  }\n  then show ?thesis\n    unfolding convex_def cone_def by blast\nqed\n\n\nsubsection\\<^marker>\\<open>tag unimportant\\<close> \\<open>Connectedness of convex sets\\<close>\n\nlemma convex_connected:\n  fixes S :: \"'a::real_normed_vector set\"\n  assumes \"convex S\"\n  shows \"connected S\"\nproof (rule connectedI)\n  fix A B\n  assume \"open A\" \"open B\" \"A \\<inter> B \\<inter> S = {}\" \"S \\<subseteq> A \\<union> B\"\n  moreover\n  assume \"A \\<inter> S \\<noteq> {}\" \"B \\<inter> S \\<noteq> {}\"\n  then obtain a b where a: \"a \\<in> A\" \"a \\<in> S\" and b: \"b \\<in> B\" \"b \\<in> S\" by auto\n  define f where [abs_def]: \"f u = u *\\<^sub>R a + (1 - u) *\\<^sub>R b\" for u\n  then have \"continuous_on {0 .. 1} f\"\n    by (auto intro!: continuous_intros)\n  then have \"connected (f ` {0 .. 1})\"\n    by (auto intro!: connected_continuous_image)\n  note connectedD[OF this, of A B]\n  moreover have \"a \\<in> A \\<inter> f ` {0 .. 1}\"\n    using a by (auto intro!: image_eqI[of _ _ 1] simp: f_def)\n  moreover have \"b \\<in> B \\<inter> f ` {0 .. 1}\"\n    using b by (auto intro!: image_eqI[of _ _ 0] simp: f_def)\n  moreover have \"f ` {0 .. 1} \\<subseteq> S\"\n    using \\<open>convex S\\<close> a b unfolding convex_def f_def by auto\n  ultimately show False by auto\nqed\n\ncorollary%unimportant connected_UNIV[intro]: \"connected (UNIV :: 'a::real_normed_vector set)\"\nby (simp add: convex_connected)\n\nlemma convex_prod:\n  assumes \"\\<And>i. i \\<in> Basis \\<Longrightarrow> convex {x. P i x}\"\n  shows \"convex {x. \\<forall>i\\<in>Basis. P i (x\\<bullet>i)}\"\n  using assms unfolding convex_def\n  by (auto simp: inner_add_left)\n\nlemma convex_positive_orthant: \"convex {x::'a::euclidean_space. (\\<forall>i\\<in>Basis. 0 \\<le> x\\<bullet>i)}\"\nby (rule convex_prod) (simp flip: atLeast_def)\n\nsubsection \\<open>Convex hull\\<close>\n\nlemma convex_convex_hull [iff]: \"convex (convex hull s)\"\n  unfolding hull_def\n  using convex_Inter[of \"{t. convex t \\<and> s \\<subseteq> t}\"]\n  by auto\n\nlemma convex_hull_subset:\n    \"s \\<subseteq> convex hull t \\<Longrightarrow> convex hull s \\<subseteq> convex hull t\"\n  by (simp add: subset_hull)\n\nlemma convex_hull_eq: \"convex hull s = s \\<longleftrightarrow> convex s\"\n  by (metis convex_convex_hull hull_same)\n\nsubsubsection\\<^marker>\\<open>tag unimportant\\<close> \\<open>Convex hull is \"preserved\" by a linear function\\<close>\n\nlemma convex_hull_linear_image:\n  assumes f: \"linear f\"\n  shows \"f ` (convex hull s) = convex hull (f ` s)\"\nproof\n  show \"convex hull (f ` s) \\<subseteq> f ` (convex hull s)\"\n    by (intro hull_minimal image_mono hull_subset convex_linear_image assms convex_convex_hull)\n  show \"f ` (convex hull s) \\<subseteq> convex hull (f ` s)\"\n  proof (unfold image_subset_iff_subset_vimage, rule hull_minimal)\n    show \"s \\<subseteq> f -` (convex hull (f ` s))\"\n      by (fast intro: hull_inc)\n    show \"convex (f -` (convex hull (f ` s)))\"\n      by (intro convex_linear_vimage [OF f] convex_convex_hull)\n  qed\nqed\n\nlemma in_convex_hull_linear_image:\n  assumes \"linear f\"\n    and \"x \\<in> convex hull s\"\n  shows \"f x \\<in> convex hull (f ` s)\"\n  using convex_hull_linear_image[OF assms(1)] assms(2) by auto\n\nlemma convex_hull_Times:\n  \"convex hull (s \\<times> t) = (convex hull s) \\<times> (convex hull t)\"\nproof\n  show \"convex hull (s \\<times> t) \\<subseteq> (convex hull s) \\<times> (convex hull t)\"\n    by (intro hull_minimal Sigma_mono hull_subset convex_Times convex_convex_hull)\n  have \"(x, y) \\<in> convex hull (s \\<times> t)\" if x: \"x \\<in> convex hull s\" and y: \"y \\<in> convex hull t\" for x y\n  proof (rule hull_induct [OF x], rule hull_induct [OF y])\n    fix x y assume \"x \\<in> s\" and \"y \\<in> t\"\n    then show \"(x, y) \\<in> convex hull (s \\<times> t)\"\n      by (simp add: hull_inc)\n  next\n    fix x let ?S = \"((\\<lambda>y. (0, y)) -` (\\<lambda>p. (- x, 0) + p) ` (convex hull s \\<times> t))\"\n    have \"convex ?S\"\n      by (intro convex_linear_vimage convex_translation convex_convex_hull,\n        simp add: linear_iff)\n    also have \"?S = {y. (x, y) \\<in> convex hull (s \\<times> t)}\"\n      by (auto simp: image_def Bex_def)\n    finally show \"convex {y. (x, y) \\<in> convex hull (s \\<times> t)}\" .\n  next\n    show \"convex {x. (x, y) \\<in> convex hull s \\<times> t}\"\n    proof -\n      fix y let ?S = \"((\\<lambda>x. (x, 0)) -` (\\<lambda>p. (0, - y) + p) ` (convex hull s \\<times> t))\"\n      have \"convex ?S\"\n      by (intro convex_linear_vimage convex_translation convex_convex_hull,\n        simp add: linear_iff)\n      also have \"?S = {x. (x, y) \\<in> convex hull (s \\<times> t)}\"\n        by (auto simp: image_def Bex_def)\n      finally show \"convex {x. (x, y) \\<in> convex hull (s \\<times> t)}\" .\n    qed\n  qed\n  then show \"(convex hull s) \\<times> (convex hull t) \\<subseteq> convex hull (s \\<times> t)\"\n    unfolding subset_eq split_paired_Ball_Sigma by blast\nqed\n\n\nsubsubsection\\<^marker>\\<open>tag unimportant\\<close> \\<open>Stepping theorems for convex hulls of finite sets\\<close>\n\nlemma convex_hull_empty[simp]: \"convex hull {} = {}\"\n  by (rule hull_unique) auto\n\nlemma convex_hull_singleton[simp]: \"convex hull {a} = {a}\"\n  by (rule hull_unique) auto\n\nlemma convex_hull_insert:\n  fixes S :: \"'a::real_vector set\"\n  assumes \"S \\<noteq> {}\"\n  shows \"convex hull (insert a S) =\n         {x. \\<exists>u\\<ge>0. \\<exists>v\\<ge>0. \\<exists>b. (u + v = 1) \\<and> b \\<in> (convex hull S) \\<and> (x = u *\\<^sub>R a + v *\\<^sub>R b)}\"\n  (is \"_ = ?hull\")\nproof (intro equalityI hull_minimal subsetI)\n  fix x\n  assume \"x \\<in> insert a S\"\n  then have \"\\<exists>u\\<ge>0. \\<exists>v\\<ge>0. u + v = 1 \\<and> (\\<exists>b. b \\<in> convex hull S \\<and> x = u *\\<^sub>R a + v *\\<^sub>R b)\"\n  unfolding insert_iff\n  proof\n    assume \"x = a\"\n    then show ?thesis\n      by (rule_tac x=1 in exI) (use assms hull_subset in fastforce)\n  next\n    assume \"x \\<in> S\"\n    with hull_subset[of S convex] show ?thesis\n      by force\n  qed\n  then show \"x \\<in> ?hull\"\n    by simp\nnext\n  fix x\n  assume \"x \\<in> ?hull\"\n  then obtain u v b where obt: \"u\\<ge>0\" \"v\\<ge>0\" \"u + v = 1\" \"b \\<in> convex hull S\" \"x = u *\\<^sub>R a + v *\\<^sub>R b\"\n    by auto\n  have \"a \\<in> convex hull insert a S\" \"b \\<in> convex hull insert a S\"\n    using hull_mono[of S \"insert a S\" convex] hull_mono[of \"{a}\" \"insert a S\" convex] and obt(4)\n    by auto\n  then show \"x \\<in> convex hull insert a S\"\n    unfolding obt(5) using obt(1-3)\n    by (rule convexD [OF convex_convex_hull])\nnext\n  show \"convex ?hull\"\n  proof (rule convexI)\n    fix x y u v\n    assume as: \"(0::real) \\<le> u\" \"0 \\<le> v\" \"u + v = 1\" and x: \"x \\<in> ?hull\" and y: \"y \\<in> ?hull\"\n    from x obtain u1 v1 b1 where\n      obt1: \"u1\\<ge>0\" \"v1\\<ge>0\" \"u1 + v1 = 1\" \"b1 \\<in> convex hull S\" and xeq: \"x = u1 *\\<^sub>R a + v1 *\\<^sub>R b1\"\n      by auto\n    from y obtain u2 v2 b2 where\n      obt2: \"u2\\<ge>0\" \"v2\\<ge>0\" \"u2 + v2 = 1\" \"b2 \\<in> convex hull S\" and yeq: \"y = u2 *\\<^sub>R a + v2 *\\<^sub>R b2\"\n      by auto\n    have *: \"\\<And>(x::'a) s1 s2. x - s1 *\\<^sub>R x - s2 *\\<^sub>R x = ((1::real) - (s1 + s2)) *\\<^sub>R x\"\n      by (auto simp: algebra_simps)\n    have \"\\<exists>b \\<in> convex hull S. u *\\<^sub>R x + v *\\<^sub>R y =\n      (u * u1) *\\<^sub>R a + (v * u2) *\\<^sub>R a + (b - (u * u1) *\\<^sub>R b - (v * u2) *\\<^sub>R b)\"\n    proof (cases \"u * v1 + v * v2 = 0\")\n      case True\n      have *: \"\\<And>(x::'a) s1 s2. x - s1 *\\<^sub>R x - s2 *\\<^sub>R x = ((1::real) - (s1 + s2)) *\\<^sub>R x\"\n        by (auto simp: algebra_simps)\n      have eq0: \"u * v1 = 0\" \"v * v2 = 0\"\n        using True mult_nonneg_nonneg[OF \\<open>u\\<ge>0\\<close> \\<open>v1\\<ge>0\\<close>] mult_nonneg_nonneg[OF \\<open>v\\<ge>0\\<close> \\<open>v2\\<ge>0\\<close>]\n        by arith+\n      then have \"u * u1 + v * u2 = 1\"\n        using as(3) obt1(3) obt2(3) by auto\n      then show ?thesis\n        using \"*\" eq0 as obt1(4) xeq yeq by auto\n    next\n      case False\n      have \"1 - (u * u1 + v * u2) = (u + v) - (u * u1 + v * u2)\"\n        using as(3) obt1(3) obt2(3) by (auto simp: field_simps)\n      also have \"\\<dots> = u * (v1 + u1 - u1) + v * (v2 + u2 - u2)\"\n        using as(3) obt1(3) obt2(3) by (auto simp: field_simps)\n      also have \"\\<dots> = u * v1 + v * v2\"\n        by simp\n      finally have **:\"1 - (u * u1 + v * u2) = u * v1 + v * v2\" by auto\n      let ?b = \"((u * v1) / (u * v1 + v * v2)) *\\<^sub>R b1 + ((v * v2) / (u * v1 + v * v2)) *\\<^sub>R b2\"\n      have zeroes: \"0 \\<le> u * v1 + v * v2\" \"0 \\<le> u * v1\" \"0 \\<le> u * v1 + v * v2\" \"0 \\<le> v * v2\"\n        using as(1,2) obt1(1,2) obt2(1,2) by auto\n      show ?thesis\n      proof\n        show \"u *\\<^sub>R x + v *\\<^sub>R y = (u * u1) *\\<^sub>R a + (v * u2) *\\<^sub>R a + (?b - (u * u1) *\\<^sub>R ?b - (v * u2) *\\<^sub>R ?b)\"\n          unfolding xeq yeq * **\n          using False by (auto simp: scaleR_left_distrib scaleR_right_distrib)\n        show \"?b \\<in> convex hull S\"\n          using False zeroes obt1(4) obt2(4)\n          by (auto simp: convexD [OF convex_convex_hull] scaleR_left_distrib scaleR_right_distrib  add_divide_distrib[symmetric]  zero_le_divide_iff)\n      qed\n    qed\n    then obtain b where b: \"b \\<in> convex hull S\" \n       \"u *\\<^sub>R x + v *\\<^sub>R y = (u * u1) *\\<^sub>R a + (v * u2) *\\<^sub>R a + (b - (u * u1) *\\<^sub>R b - (v * u2) *\\<^sub>R b)\" ..\n\n    have u1: \"u1 \\<le> 1\"\n      unfolding obt1(3)[symmetric] and not_le using obt1(2) by auto\n    have u2: \"u2 \\<le> 1\"\n      unfolding obt2(3)[symmetric] and not_le using obt2(2) by auto\n    have \"u1 * u + u2 * v \\<le> max u1 u2 * u + max u1 u2 * v\"\n    proof (rule add_mono)\n      show \"u1 * u \\<le> max u1 u2 * u\" \"u2 * v \\<le> max u1 u2 * v\"\n        by (simp_all add: as mult_right_mono)\n    qed\n    also have \"\\<dots> \\<le> 1\"\n      unfolding distrib_left[symmetric] and as(3) using u1 u2 by auto\n    finally have le1: \"u1 * u + u2 * v \\<le> 1\" .    \n    show \"u *\\<^sub>R x + v *\\<^sub>R y \\<in> ?hull\"\n    proof (intro CollectI exI conjI)\n      show \"0 \\<le> u * u1 + v * u2\"\n        by (simp add: as(1) as(2) obt1(1) obt2(1))\n      show \"0 \\<le> 1 - u * u1 - v * u2\"\n        by (simp add: le1 diff_diff_add mult.commute)\n    qed (use b in \\<open>auto simp: algebra_simps\\<close>)\n  qed\nqed\n\nlemma convex_hull_insert_alt:\n   \"convex hull (insert a S) =\n     (if S = {} then {a}\n      else {(1 - u) *\\<^sub>R a + u *\\<^sub>R x |x u. 0 \\<le> u \\<and> u \\<le> 1 \\<and> x \\<in> convex hull S})\"\n  apply (auto simp: convex_hull_insert)\n  using diff_eq_eq apply fastforce\n  using diff_add_cancel diff_ge_0_iff_ge by blast\n\nsubsubsection\\<^marker>\\<open>tag unimportant\\<close> \\<open>Explicit expression for convex hull\\<close>\n\nproposition convex_hull_indexed:\n  fixes S :: \"'a::real_vector set\"\n  shows \"convex hull S =\n    {y. \\<exists>k u x. (\\<forall>i\\<in>{1::nat .. k}. 0 \\<le> u i \\<and> x i \\<in> S) \\<and>\n                (sum u {1..k} = 1) \\<and> (\\<Sum>i = 1..k. u i *\\<^sub>R x i) = y}\"\n    (is \"?xyz = ?hull\")\nproof (rule hull_unique [OF _ convexI])\n  show \"S \\<subseteq> ?hull\" \n    by (clarsimp, rule_tac x=1 in exI, rule_tac x=\"\\<lambda>x. 1\" in exI, auto)\nnext\n  fix T\n  assume \"S \\<subseteq> T\" \"convex T\"\n  then show \"?hull \\<subseteq> T\"\n    by (blast intro: convex_sum)\nnext\n  fix x y u v\n  assume uv: \"0 \\<le> u\" \"0 \\<le> v\" \"u + v = (1::real)\"\n  assume xy: \"x \\<in> ?hull\" \"y \\<in> ?hull\"\n  from xy obtain k1 u1 x1 where\n    x [rule_format]: \"\\<forall>i\\<in>{1::nat..k1}. 0\\<le>u1 i \\<and> x1 i \\<in> S\" \n                      \"sum u1 {Suc 0..k1} = 1\" \"(\\<Sum>i = Suc 0..k1. u1 i *\\<^sub>R x1 i) = x\"\n    by auto\n  from xy obtain k2 u2 x2 where\n    y [rule_format]: \"\\<forall>i\\<in>{1::nat..k2}. 0\\<le>u2 i \\<and> x2 i \\<in> S\" \n                     \"sum u2 {Suc 0..k2} = 1\" \"(\\<Sum>i = Suc 0..k2. u2 i *\\<^sub>R x2 i) = y\"\n    by auto\n  have *: \"\\<And>P (x::'a) y s t i. (if P i then s else t) *\\<^sub>R (if P i then x else y) = (if P i then s *\\<^sub>R x else t *\\<^sub>R y)\"\n          \"{1..k1 + k2} \\<inter> {1..k1} = {1..k1}\" \"{1..k1 + k2} \\<inter> - {1..k1} = (\\<lambda>i. i + k1) ` {1..k2}\"\n    by auto\n  have inj: \"inj_on (\\<lambda>i. i + k1) {1..k2}\"\n    unfolding inj_on_def by auto\n  let ?uu = \"\\<lambda>i. if i \\<in> {1..k1} then u * u1 i else v * u2 (i - k1)\"\n  let ?xx = \"\\<lambda>i. if i \\<in> {1..k1} then x1 i else x2 (i - k1)\"\n  show \"u *\\<^sub>R x + v *\\<^sub>R y \\<in> ?hull\"\n  proof (intro CollectI exI conjI ballI)\n    show \"0 \\<le> ?uu i\" \"?xx i \\<in> S\" if \"i \\<in> {1..k1+k2}\" for i\n      using that by (auto simp add: le_diff_conv uv(1) x(1) uv(2) y(1))\n    show \"(\\<Sum>i = 1..k1 + k2. ?uu i) = 1\"  \"(\\<Sum>i = 1..k1 + k2. ?uu i *\\<^sub>R ?xx i) = u *\\<^sub>R x + v *\\<^sub>R y\"\n      unfolding * sum.If_cases[OF finite_atLeastAtMost[of 1 \"k1 + k2\"]]\n        sum.reindex[OF inj] Collect_mem_eq o_def\n      unfolding scaleR_scaleR[symmetric] scaleR_right.sum [symmetric] sum_distrib_left[symmetric]\n      by (simp_all add: sum_distrib_left[symmetric]  x(2,3) y(2,3) uv(3))\n  qed \nqed\n\nlemma convex_hull_finite:\n  fixes S :: \"'a::real_vector set\"\n  assumes \"finite S\"\n  shows \"convex hull S = {y. \\<exists>u. (\\<forall>x\\<in>S. 0 \\<le> u x) \\<and> sum u S = 1 \\<and> sum (\\<lambda>x. u x *\\<^sub>R x) S = y}\"\n  (is \"?HULL = _\")\nproof (rule hull_unique [OF _ convexI]; clarify)\n  fix x\n  assume \"x \\<in> S\"\n  then show \"\\<exists>u. (\\<forall>x\\<in>S. 0 \\<le> u x) \\<and> sum u S = 1 \\<and> (\\<Sum>x\\<in>S. u x *\\<^sub>R x) = x\"\n    by (rule_tac x=\"\\<lambda>y. if x=y then 1 else 0\" in exI) (auto simp: sum.delta'[OF assms] sum_delta''[OF assms])\nnext\n  fix u v :: real\n  assume uv: \"0 \\<le> u\" \"0 \\<le> v\" \"u + v = 1\"\n  fix ux assume ux [rule_format]: \"\\<forall>x\\<in>S. 0 \\<le> ux x\" \"sum ux S = (1::real)\"\n  fix uy assume uy [rule_format]: \"\\<forall>x\\<in>S. 0 \\<le> uy x\" \"sum uy S = (1::real)\"\n  have \"0 \\<le> u * ux x + v * uy x\" if \"x\\<in>S\" for x\n    by (simp add: that uv ux(1) uy(1))\n  moreover\n  have \"(\\<Sum>x\\<in>S. u * ux x + v * uy x) = 1\"\n    unfolding sum.distrib and sum_distrib_left[symmetric] ux(2) uy(2)\n    using uv(3) by auto\n  moreover\n  have \"(\\<Sum>x\\<in>S. (u * ux x + v * uy x) *\\<^sub>R x) = u *\\<^sub>R (\\<Sum>x\\<in>S. ux x *\\<^sub>R x) + v *\\<^sub>R (\\<Sum>x\\<in>S. uy x *\\<^sub>R x)\"\n    unfolding scaleR_left_distrib sum.distrib scaleR_scaleR[symmetric] scaleR_right.sum [symmetric]\n    by auto\n  ultimately\n  show \"\\<exists>uc. (\\<forall>x\\<in>S. 0 \\<le> uc x) \\<and> sum uc S = 1 \\<and>\n             (\\<Sum>x\\<in>S. uc x *\\<^sub>R x) = u *\\<^sub>R (\\<Sum>x\\<in>S. ux x *\\<^sub>R x) + v *\\<^sub>R (\\<Sum>x\\<in>S. uy x *\\<^sub>R x)\"\n    by (rule_tac x=\"\\<lambda>x. u * ux x + v * uy x\" in exI, auto)\nqed (use assms in \\<open>auto simp: convex_explicit\\<close>)\n\n\nsubsubsection\\<^marker>\\<open>tag unimportant\\<close> \\<open>Another formulation\\<close>\n\ntext \"Formalized by Lars Schewe.\"\n\nlemma convex_hull_explicit:\n  fixes p :: \"'a::real_vector set\"\n  shows \"convex hull p =\n    {y. \\<exists>S u. finite S \\<and> S \\<subseteq> p \\<and> (\\<forall>x\\<in>S. 0 \\<le> u x) \\<and> sum u S = 1 \\<and> sum (\\<lambda>v. u v *\\<^sub>R v) S = y}\"\n  (is \"?lhs = ?rhs\")\nproof -\n  {\n    fix x\n    assume \"x\\<in>?lhs\"\n    then obtain k u y where\n        obt: \"\\<forall>i\\<in>{1::nat..k}. 0 \\<le> u i \\<and> y i \\<in> p\" \"sum u {1..k} = 1\" \"(\\<Sum>i = 1..k. u i *\\<^sub>R y i) = x\"\n      unfolding convex_hull_indexed by auto\n\n    have fin: \"finite {1..k}\" by auto\n    have fin': \"\\<And>v. finite {i \\<in> {1..k}. y i = v}\" by auto\n    {\n      fix j\n      assume \"j\\<in>{1..k}\"\n      then have \"y j \\<in> p \\<and> 0 \\<le> sum u {i. Suc 0 \\<le> i \\<and> i \\<le> k \\<and> y i = y j}\"\n        using obt(1)[THEN bspec[where x=j]] and obt(2)\n        by (metis (no_types, lifting) One_nat_def atLeastAtMost_iff mem_Collect_eq obt(1) sum_nonneg)\n    }\n    moreover\n    have \"(\\<Sum>v\\<in>y ` {1..k}. sum u {i \\<in> {1..k}. y i = v}) = 1\"\n      unfolding sum.image_gen[OF fin, symmetric] using obt(2) by auto\n    moreover have \"(\\<Sum>v\\<in>y ` {1..k}. sum u {i \\<in> {1..k}. y i = v} *\\<^sub>R v) = x\"\n      using sum.image_gen[OF fin, of \"\\<lambda>i. u i *\\<^sub>R y i\" y, symmetric]\n      unfolding scaleR_left.sum using obt(3) by auto\n    ultimately\n    have \"\\<exists>S u. finite S \\<and> S \\<subseteq> p \\<and> (\\<forall>x\\<in>S. 0 \\<le> u x) \\<and> sum u S = 1 \\<and> (\\<Sum>v\\<in>S. u v *\\<^sub>R v) = x\"\n      apply (rule_tac x=\"y ` {1..k}\" in exI)\n      apply (rule_tac x=\"\\<lambda>v. sum u {i\\<in>{1..k}. y i = v}\" in exI, auto)\n      done\n    then have \"x\\<in>?rhs\" by auto\n  }\n  moreover\n  {\n    fix y\n    assume \"y\\<in>?rhs\"\n    then obtain S u where\n      obt: \"finite S\" \"S \\<subseteq> p\" \"\\<forall>x\\<in>S. 0 \\<le> u x\" \"sum u S = 1\" \"(\\<Sum>v\\<in>S. u v *\\<^sub>R v) = y\"\n      by auto\n\n    obtain f where f: \"inj_on f {1..card S}\" \"f ` {1..card S} = S\"\n      using ex_bij_betw_nat_finite_1[OF obt(1)] unfolding bij_betw_def by auto\n    {\n      fix i :: nat\n      assume \"i\\<in>{1..card S}\"\n      then have \"f i \\<in> S\"\n        using f(2) by blast\n      then have \"0 \\<le> u (f i)\" \"f i \\<in> p\" using obt(2,3) by auto\n    }\n    moreover have *: \"finite {1..card S}\" by auto\n    {\n      fix y\n      assume \"y\\<in>S\"\n      then obtain i where \"i\\<in>{1..card S}\" \"f i = y\"\n        using f using image_iff[of y f \"{1..card S}\"]\n        by auto\n      then have \"{x. Suc 0 \\<le> x \\<and> x \\<le> card S \\<and> f x = y} = {i}\"\n        using f(1) inj_onD by fastforce\n      then have \"card {x. Suc 0 \\<le> x \\<and> x \\<le> card S \\<and> f x = y} = 1\" by auto\n      then have \"(\\<Sum>x\\<in>{x \\<in> {1..card S}. f x = y}. u (f x)) = u y\"\n          \"(\\<Sum>x\\<in>{x \\<in> {1..card S}. f x = y}. u (f x) *\\<^sub>R f x) = u y *\\<^sub>R y\"\n        by (auto simp: sum_constant_scaleR)\n    }\n    then have \"(\\<Sum>x = 1..card S. u (f x)) = 1\" \"(\\<Sum>i = 1..card S. u (f i) *\\<^sub>R f i) = y\"\n      unfolding sum.image_gen[OF *(1), of \"\\<lambda>x. u (f x) *\\<^sub>R f x\" f]\n        and sum.image_gen[OF *(1), of \"\\<lambda>x. u (f x)\" f]\n      unfolding f\n      using sum.cong [of S S \"\\<lambda>y. (\\<Sum>x\\<in>{x \\<in> {1..card S}. f x = y}. u (f x) *\\<^sub>R f x)\" \"\\<lambda>v. u v *\\<^sub>R v\"]\n      using sum.cong [of S S \"\\<lambda>y. (\\<Sum>x\\<in>{x \\<in> {1..card S}. f x = y}. u (f x))\" u]\n      unfolding obt(4,5)\n      by auto\n    ultimately\n    have \"\\<exists>k u x. (\\<forall>i\\<in>{1..k}. 0 \\<le> u i \\<and> x i \\<in> p) \\<and> sum u {1..k} = 1 \\<and>\n        (\\<Sum>i::nat = 1..k. u i *\\<^sub>R x i) = y\"\n      apply (rule_tac x=\"card S\" in exI)\n      apply (rule_tac x=\"u \\<circ> f\" in exI)\n      apply (rule_tac x=f in exI, fastforce)\n      done\n    then have \"y \\<in> ?lhs\"\n      unfolding convex_hull_indexed by auto\n  }\n  ultimately show ?thesis\n    unfolding set_eq_iff by blast\nqed\n\n\nsubsubsection\\<^marker>\\<open>tag unimportant\\<close> \\<open>A stepping theorem for that expansion\\<close>\n\nlemma convex_hull_finite_step:\n  fixes S :: \"'a::real_vector set\"\n  assumes \"finite S\"\n  shows\n    \"(\\<exists>u. (\\<forall>x\\<in>insert a S. 0 \\<le> u x) \\<and> sum u (insert a S) = w \\<and> sum (\\<lambda>x. u x *\\<^sub>R x) (insert a S) = y)\n      \\<longleftrightarrow> (\\<exists>v\\<ge>0. \\<exists>u. (\\<forall>x\\<in>S. 0 \\<le> u x) \\<and> sum u S = w - v \\<and> sum (\\<lambda>x. u x *\\<^sub>R x) S = y - v *\\<^sub>R a)\"\n  (is \"?lhs = ?rhs\")\nproof (cases \"a \\<in> S\")\n  case True\n  then have *: \"insert a S = S\" by auto\n  show ?thesis\n  proof\n    assume ?lhs\n    then show ?rhs\n      unfolding * by force\n  next\n    have fin: \"finite (insert a S)\" using assms by auto\n    assume ?rhs\n    then obtain v u where uv: \"v\\<ge>0\" \"\\<forall>x\\<in>S. 0 \\<le> u x\" \"sum u S = w - v\" \"(\\<Sum>x\\<in>S. u x *\\<^sub>R x) = y - v *\\<^sub>R a\"\n      by auto\n    then show ?lhs\n      using uv True assms\n      apply (rule_tac x = \"\\<lambda>x. (if a = x then v else 0) + u x\" in exI)\n      apply (auto simp: sum_clauses scaleR_left_distrib sum.distrib sum_delta''[OF fin])\n      done\n  qed\nnext\n  case False\n  show ?thesis\n  proof\n    assume ?lhs\n    then obtain u where u: \"\\<forall>x\\<in>insert a S. 0 \\<le> u x\" \"sum u (insert a S) = w\" \"(\\<Sum>x\\<in>insert a S. u x *\\<^sub>R x) = y\"\n      by auto\n    then show ?rhs\n      using u \\<open>a\\<notin>S\\<close> by (rule_tac x=\"u a\" in exI) (auto simp: sum_clauses assms)\n  next\n    assume ?rhs\n    then obtain v u where uv: \"v\\<ge>0\" \"\\<forall>x\\<in>S. 0 \\<le> u x\" \"sum u S = w - v\" \"(\\<Sum>x\\<in>S. u x *\\<^sub>R x) = y - v *\\<^sub>R a\"\n      by auto\n    moreover\n    have \"(\\<Sum>x\\<in>S. if a = x then v else u x) = sum u S\"  \"(\\<Sum>x\\<in>S. (if a = x then v else u x) *\\<^sub>R x) = (\\<Sum>x\\<in>S. u x *\\<^sub>R x)\"\n      using False by (auto intro!: sum.cong)\n    ultimately show ?lhs\n      using False by (rule_tac x=\"\\<lambda>x. if a = x then v else u x\" in exI) (auto simp: sum_clauses(2)[OF assms])\n  qed\nqed\n\n\nsubsubsection\\<^marker>\\<open>tag unimportant\\<close> \\<open>Hence some special cases\\<close>\n\nlemma convex_hull_2: \"convex hull {a,b} = {u *\\<^sub>R a + v *\\<^sub>R b | u v. 0 \\<le> u \\<and> 0 \\<le> v \\<and> u + v = 1}\"\n       (is \"?lhs = ?rhs\")\nproof -\n  have **: \"finite {b}\" by auto\n  have \"\\<And>x v u. \\<lbrakk>0 \\<le> v; v \\<le> 1; (1 - v) *\\<^sub>R b = x - v *\\<^sub>R a\\<rbrakk>\n                \\<Longrightarrow> \\<exists>u v. x = u *\\<^sub>R a + v *\\<^sub>R b \\<and> 0 \\<le> u \\<and> 0 \\<le> v \\<and> u + v = 1\"\n    by (metis add.commute diff_add_cancel diff_ge_0_iff_ge)\n  moreover\n  have \"\\<And>u v. \\<lbrakk>0 \\<le> u; 0 \\<le> v; u + v = 1\\<rbrakk>\n               \\<Longrightarrow> \\<exists>p\\<ge>0. \\<exists>q. 0 \\<le> q b \\<and> q b = 1 - p \\<and> q b *\\<^sub>R b = u *\\<^sub>R a + v *\\<^sub>R b - p *\\<^sub>R a\"\n    apply (rule_tac x=u in exI, simp)\n    apply (rule_tac x=\"\\<lambda>x. v\" in exI, simp)\n    done\n  ultimately show ?thesis\n    using convex_hull_finite_step[OF **, of a 1]\n    by (auto simp add: convex_hull_finite)\nqed\n\nlemma convex_hull_2_alt: \"convex hull {a,b} = {a + u *\\<^sub>R (b - a) | u.  0 \\<le> u \\<and> u \\<le> 1}\"\n  unfolding convex_hull_2\nproof (rule Collect_cong)\n  have *: \"\\<And>x y ::real. x + y = 1 \\<longleftrightarrow> x = 1 - y\"\n    by auto\n  fix x\n  show \"(\\<exists>v u. x = v *\\<^sub>R a + u *\\<^sub>R b \\<and> 0 \\<le> v \\<and> 0 \\<le> u \\<and> v + u = 1) \\<longleftrightarrow>\n    (\\<exists>u. x = a + u *\\<^sub>R (b - a) \\<and> 0 \\<le> u \\<and> u \\<le> 1)\"\n    apply (simp add: *)\n    by (rule ex_cong1) (auto simp: algebra_simps)\nqed\n\nlemma convex_hull_3:\n  \"convex hull {a,b,c} = { u *\\<^sub>R a + v *\\<^sub>R b + w *\\<^sub>R c | u v w. 0 \\<le> u \\<and> 0 \\<le> v \\<and> 0 \\<le> w \\<and> u + v + w = 1}\"\nproof -\n  have fin: \"finite {a,b,c}\" \"finite {b,c}\" \"finite {c}\"\n    by auto\n  have *: \"\\<And>x y z ::real. x + y + z = 1 \\<longleftrightarrow> x = 1 - y - z\"\n    by (auto simp: field_simps)\n  show ?thesis\n    unfolding convex_hull_finite[OF fin(1)] and convex_hull_finite_step[OF fin(2)] and *\n    unfolding convex_hull_finite_step[OF fin(3)]\n    apply (rule Collect_cong, simp)\n    apply auto\n    apply (rule_tac x=va in exI)\n    apply (rule_tac x=\"u c\" in exI, simp)\n    apply (rule_tac x=\"1 - v - w\" in exI, simp)\n    apply (rule_tac x=v in exI, simp)\n    apply (rule_tac x=\"\\<lambda>x. w\" in exI, simp)\n    done\nqed\n\nlemma convex_hull_3_alt:\n  \"convex hull {a,b,c} = {a + u *\\<^sub>R (b - a) + v *\\<^sub>R (c - a) | u v.  0 \\<le> u \\<and> 0 \\<le> v \\<and> u + v \\<le> 1}\"\nproof -\n  have *: \"\\<And>x y z ::real. x + y + z = 1 \\<longleftrightarrow> x = 1 - y - z\"\n    by auto\n  show ?thesis\n    unfolding convex_hull_3\n    apply (auto simp: *)\n    apply (rule_tac x=v in exI)\n    apply (rule_tac x=w in exI)\n    apply (simp add: algebra_simps)\n    apply (rule_tac x=u in exI)\n    apply (rule_tac x=v in exI)\n    apply (simp add: algebra_simps)\n    done\nqed\n\n\nsubsection\\<^marker>\\<open>tag unimportant\\<close> \\<open>Relations among closure notions and corresponding hulls\\<close>\n\nlemma affine_imp_convex: \"affine s \\<Longrightarrow> convex s\"\n  unfolding affine_def convex_def by auto\n\nlemma convex_affine_hull [simp]: \"convex (affine hull S)\"\n  by (simp add: affine_imp_convex)\n\nlemma subspace_imp_convex: \"subspace s \\<Longrightarrow> convex s\"\n  using subspace_imp_affine affine_imp_convex by auto\n\nlemma convex_hull_subset_span: \"(convex hull s) \\<subseteq> (span s)\"\n  by (metis hull_minimal span_superset subspace_imp_convex subspace_span)\n\nlemma convex_hull_subset_affine_hull: \"(convex hull s) \\<subseteq> (affine hull s)\"\n  by (metis affine_affine_hull affine_imp_convex hull_minimal hull_subset)\n\nlemma aff_dim_convex_hull:\n  fixes S :: \"'n::euclidean_space set\"\n  shows \"aff_dim (convex hull S) = aff_dim S\"\n  using aff_dim_affine_hull[of S] convex_hull_subset_affine_hull[of S]\n    hull_subset[of S \"convex\"] aff_dim_subset[of S \"convex hull S\"]\n    aff_dim_subset[of \"convex hull S\" \"affine hull S\"]\n  by auto\n\n\nsubsection \\<open>Caratheodory's theorem\\<close>\n\nlemma convex_hull_caratheodory_aff_dim:\n  fixes p :: \"('a::euclidean_space) set\"\n  shows \"convex hull p =\n    {y. \\<exists>S u. finite S \\<and> S \\<subseteq> p \\<and> card S \\<le> aff_dim p + 1 \\<and>\n        (\\<forall>x\\<in>S. 0 \\<le> u x) \\<and> sum u S = 1 \\<and> sum (\\<lambda>v. u v *\\<^sub>R v) S = y}\"\n  unfolding convex_hull_explicit set_eq_iff mem_Collect_eq\nproof (intro allI iffI)\n  fix y\n  let ?P = \"\\<lambda>n. \\<exists>S u. finite S \\<and> card S = n \\<and> S \\<subseteq> p \\<and> (\\<forall>x\\<in>S. 0 \\<le> u x) \\<and>\n    sum u S = 1 \\<and> (\\<Sum>v\\<in>S. u v *\\<^sub>R v) = y\"\n  assume \"\\<exists>S u. finite S \\<and> S \\<subseteq> p \\<and> (\\<forall>x\\<in>S. 0 \\<le> u x) \\<and> sum u S = 1 \\<and> (\\<Sum>v\\<in>S. u v *\\<^sub>R v) = y\"\n  then obtain N where \"?P N\" by auto\n  then have \"\\<exists>n\\<le>N. (\\<forall>k<n. \\<not> ?P k) \\<and> ?P n\"\n    by (rule_tac ex_least_nat_le, auto)\n  then obtain n where \"?P n\" and smallest: \"\\<forall>k<n. \\<not> ?P k\"\n    by blast\n  then obtain S u where obt: \"finite S\" \"card S = n\" \"S\\<subseteq>p\" \"\\<forall>x\\<in>S. 0 \\<le> u x\"\n    \"sum u S = 1\"  \"(\\<Sum>v\\<in>S. u v *\\<^sub>R v) = y\" by auto\n\n  have \"card S \\<le> aff_dim p + 1\"\n  proof (rule ccontr, simp only: not_le)\n    assume \"aff_dim p + 1 < card S\"\n    then have \"affine_dependent S\"\n      using affine_dependent_biggerset[OF obt(1)] independent_card_le_aff_dim not_less obt(3)\n      by blast\n    then obtain w v where wv: \"sum w S = 0\" \"v\\<in>S\" \"w v \\<noteq> 0\" \"(\\<Sum>v\\<in>S. w v *\\<^sub>R v) = 0\"\n      using affine_dependent_explicit_finite[OF obt(1)] by auto\n    define i where \"i = (\\<lambda>v. (u v) / (- w v)) ` {v\\<in>S. w v < 0}\"\n    define t where \"t = Min i\"\n    have \"\\<exists>x\\<in>S. w x < 0\"\n    proof (rule ccontr, simp add: not_less)\n      assume as:\"\\<forall>x\\<in>S. 0 \\<le> w x\"\n      then have \"sum w (S - {v}) \\<ge> 0\"\n        by (meson Diff_iff sum_nonneg)\n      then have \"sum w S > 0\"\n        using as obt(1) sum_nonneg_eq_0_iff wv by blast\n      then show False using wv(1) by auto\n    qed\n    then have \"i \\<noteq> {}\" unfolding i_def by auto\n    then have \"t \\<ge> 0\"\n      using Min_ge_iff[of i 0] and obt(1)\n      unfolding t_def i_def\n      using obt(4)[unfolded le_less]\n      by (auto simp: divide_le_0_iff)\n    have t: \"\\<forall>v\\<in>S. u v + t * w v \\<ge> 0\"\n    proof\n      fix v\n      assume \"v \\<in> S\"\n      then have v: \"0 \\<le> u v\"\n        using obt(4)[THEN bspec[where x=v]] by auto\n      show \"0 \\<le> u v + t * w v\"\n      proof (cases \"w v < 0\")\n        case False\n        thus ?thesis using v \\<open>t\\<ge>0\\<close> by auto\n      next\n        case True\n        then have \"t \\<le> u v / (- w v)\"\n          using \\<open>v\\<in>S\\<close> obt unfolding t_def i_def by (auto intro: Min_le)\n        then show ?thesis\n          unfolding real_0_le_add_iff\n          using True neg_le_minus_divide_eq by auto\n      qed\n    qed\n    obtain a where \"a \\<in> S\" and \"t = (\\<lambda>v. (u v) / (- w v)) a\" and \"w a < 0\"\n      using Min_in[OF _ \\<open>i\\<noteq>{}\\<close>] and obt(1) unfolding i_def t_def by auto\n    then have a: \"a \\<in> S\" \"u a + t * w a = 0\" by auto\n    have *: \"\\<And>f. sum f (S - {a}) = sum f S - ((f a)::'b::ab_group_add)\"\n      unfolding sum.remove[OF obt(1) \\<open>a\\<in>S\\<close>] by auto\n    have \"(\\<Sum>v\\<in>S. u v + t * w v) = 1\"\n      unfolding sum.distrib wv(1) sum_distrib_left[symmetric] obt(5) by auto\n    moreover have \"(\\<Sum>v\\<in>S. u v *\\<^sub>R v + (t * w v) *\\<^sub>R v) - (u a *\\<^sub>R a + (t * w a) *\\<^sub>R a) = y\"\n      unfolding sum.distrib obt(6) scaleR_scaleR[symmetric] scaleR_right.sum [symmetric] wv(4)\n      using a(2) [THEN eq_neg_iff_add_eq_0 [THEN iffD2]] by simp\n    ultimately have \"?P (n - 1)\"\n      apply (rule_tac x=\"(S - {a})\" in exI)\n      apply (rule_tac x=\"\\<lambda>v. u v + t * w v\" in exI)\n      using obt(1-3) and t and a\n      apply (auto simp: * scaleR_left_distrib)\n      done\n    then show False\n      using smallest[THEN spec[where x=\"n - 1\"]] by auto\n  qed\n  then show \"\\<exists>S u. finite S \\<and> S \\<subseteq> p \\<and> card S \\<le> aff_dim p + 1 \\<and>\n      (\\<forall>x\\<in>S. 0 \\<le> u x) \\<and> sum u S = 1 \\<and> (\\<Sum>v\\<in>S. u v *\\<^sub>R v) = y\"\n    using obt by auto\nqed auto\n\nlemma caratheodory_aff_dim:\n  fixes p :: \"('a::euclidean_space) set\"\n  shows \"convex hull p = {x. \\<exists>S. finite S \\<and> S \\<subseteq> p \\<and> card S \\<le> aff_dim p + 1 \\<and> x \\<in> convex hull S}\"\n        (is \"?lhs = ?rhs\")\nproof\n  have \"\\<And>x S u. \\<lbrakk>finite S; S \\<subseteq> p; int (card S) \\<le> aff_dim p + 1; \\<forall>x\\<in>S. 0 \\<le> u x; sum u S = 1\\<rbrakk>\n                \\<Longrightarrow> (\\<Sum>v\\<in>S. u v *\\<^sub>R v) \\<in> convex hull S\"\n    by (simp add: hull_subset convex_explicit [THEN iffD1, OF convex_convex_hull])\n  then show \"?lhs \\<subseteq> ?rhs\"\n    by (subst convex_hull_caratheodory_aff_dim, auto)\nqed (use hull_mono in auto)\n\nlemma convex_hull_caratheodory:\n  fixes p :: \"('a::euclidean_space) set\"\n  shows \"convex hull p =\n            {y. \\<exists>S u. finite S \\<and> S \\<subseteq> p \\<and> card S \\<le> DIM('a) + 1 \\<and>\n              (\\<forall>x\\<in>S. 0 \\<le> u x) \\<and> sum u S = 1 \\<and> sum (\\<lambda>v. u v *\\<^sub>R v) S = y}\"\n        (is \"?lhs = ?rhs\")\nproof (intro set_eqI iffI)\n  fix x\n  assume \"x \\<in> ?lhs\" then show \"x \\<in> ?rhs\"\n    unfolding convex_hull_caratheodory_aff_dim \n    using aff_dim_le_DIM [of p] by fastforce\nqed (auto simp: convex_hull_explicit)\n\ntheorem caratheodory:\n  \"convex hull p =\n    {x::'a::euclidean_space. \\<exists>S. finite S \\<and> S \\<subseteq> p \\<and> card S \\<le> DIM('a) + 1 \\<and> x \\<in> convex hull S}\"\nproof safe\n  fix x\n  assume \"x \\<in> convex hull p\"\n  then obtain S u where \"finite S\" \"S \\<subseteq> p\" \"card S \\<le> DIM('a) + 1\"\n    \"\\<forall>x\\<in>S. 0 \\<le> u x\" \"sum u S = 1\" \"(\\<Sum>v\\<in>S. u v *\\<^sub>R v) = x\"\n    unfolding convex_hull_caratheodory by auto\n  then show \"\\<exists>S. finite S \\<and> S \\<subseteq> p \\<and> card S \\<le> DIM('a) + 1 \\<and> x \\<in> convex hull S\"\n    using convex_hull_finite by fastforce\nqed (use hull_mono in force)\n\nsubsection\\<^marker>\\<open>tag unimportant\\<close>\\<open>Some Properties of subset of standard basis\\<close>\n\nlemma affine_hull_substd_basis:\n  assumes \"d \\<subseteq> Basis\"\n  shows \"affine hull (insert 0 d) = {x::'a::euclidean_space. \\<forall>i\\<in>Basis. i \\<notin> d \\<longrightarrow> x\\<bullet>i = 0}\"\n  (is \"affine hull (insert 0 ?A) = ?B\")\nproof -\n  have *: \"\\<And>A. (+) (0::'a) ` A = A\" \"\\<And>A. (+) (- (0::'a)) ` A = A\"\n    by auto\n  show ?thesis\n    unfolding affine_hull_insert_span_gen span_substd_basis[OF assms,symmetric] * ..\nqed\n\nlemma affine_hull_convex_hull [simp]: \"affine hull (convex hull S) = affine hull S\"\n  by (metis Int_absorb1 Int_absorb2 convex_hull_subset_affine_hull hull_hull hull_mono hull_subset)\n\n\nsubsection\\<^marker>\\<open>tag unimportant\\<close> \\<open>Moving and scaling convex hulls\\<close>\n\nlemma convex_hull_set_plus:\n  \"convex hull (S + T) = convex hull S + convex hull T\"\n  unfolding set_plus_image \n  apply (subst convex_hull_linear_image [symmetric])\n  apply (simp add: linear_iff scaleR_right_distrib)\n  apply (simp add: convex_hull_Times)\n  done\n\nlemma translation_eq_singleton_plus: \"(\\<lambda>x. a + x) ` T = {a} + T\"\n  unfolding set_plus_def by auto\n\nlemma convex_hull_translation:\n  \"convex hull ((\\<lambda>x. a + x) ` S) = (\\<lambda>x. a + x) ` (convex hull S)\"\n  unfolding translation_eq_singleton_plus\n  by (simp only: convex_hull_set_plus convex_hull_singleton)\n\nlemma convex_hull_scaling:\n  \"convex hull ((\\<lambda>x. c *\\<^sub>R x) ` S) = (\\<lambda>x. c *\\<^sub>R x) ` (convex hull S)\"\n  using linear_scaleR by (rule convex_hull_linear_image [symmetric])\n\nlemma convex_hull_affinity:\n  \"convex hull ((\\<lambda>x. a + c *\\<^sub>R x) ` S) = (\\<lambda>x. a + c *\\<^sub>R x) ` (convex hull S)\"\n  by (metis convex_hull_scaling convex_hull_translation image_image)\n\n\nsubsection\\<^marker>\\<open>tag unimportant\\<close> \\<open>Convexity of cone hulls\\<close>\n\nlemma convex_cone_hull:\n  assumes \"convex S\"\n  shows \"convex (cone hull S)\"\nproof (rule convexI)\n  fix x y\n  assume xy: \"x \\<in> cone hull S\" \"y \\<in> cone hull S\"\n  then have \"S \\<noteq> {}\"\n    using cone_hull_empty_iff[of S] by auto\n  fix u v :: real\n  assume uv: \"u \\<ge> 0\" \"v \\<ge> 0\" \"u + v = 1\"\n  then have *: \"u *\\<^sub>R x \\<in> cone hull S\" \"v *\\<^sub>R y \\<in> cone hull S\"\n    using cone_cone_hull[of S] xy cone_def[of \"cone hull S\"] by auto\n  from * obtain cx :: real and xx where x: \"u *\\<^sub>R x = cx *\\<^sub>R xx\" \"cx \\<ge> 0\" \"xx \\<in> S\"\n    using cone_hull_expl[of S] by auto\n  from * obtain cy :: real and yy where y: \"v *\\<^sub>R y = cy *\\<^sub>R yy\" \"cy \\<ge> 0\" \"yy \\<in> S\"\n    using cone_hull_expl[of S] by auto\n  {\n    assume \"cx + cy \\<le> 0\"\n    then have \"u *\\<^sub>R x = 0\" and \"v *\\<^sub>R y = 0\"\n      using x y by auto\n    then have \"u *\\<^sub>R x + v *\\<^sub>R y = 0\"\n      by auto\n    then have \"u *\\<^sub>R x + v *\\<^sub>R y \\<in> cone hull S\"\n      using cone_hull_contains_0[of S] \\<open>S \\<noteq> {}\\<close> by auto\n  }\n  moreover\n  {\n    assume \"cx + cy > 0\"\n    then have \"(cx / (cx + cy)) *\\<^sub>R xx + (cy / (cx + cy)) *\\<^sub>R yy \\<in> S\"\n      using assms mem_convex_alt[of S xx yy cx cy] x y by auto\n    then have \"cx *\\<^sub>R xx + cy *\\<^sub>R yy \\<in> cone hull S\"\n      using mem_cone_hull[of \"(cx/(cx+cy)) *\\<^sub>R xx + (cy/(cx+cy)) *\\<^sub>R yy\" S \"cx+cy\"] \\<open>cx+cy>0\\<close>\n      by (auto simp: scaleR_right_distrib)\n    then have \"u *\\<^sub>R x + v *\\<^sub>R y \\<in> cone hull S\"\n      using x y by auto\n  }\n  moreover have \"cx + cy \\<le> 0 \\<or> cx + cy > 0\" by auto\n  ultimately show \"u *\\<^sub>R x + v *\\<^sub>R y \\<in> cone hull S\" by blast\nqed\n\nlemma cone_convex_hull:\n  assumes \"cone S\"\n  shows \"cone (convex hull S)\"\nproof (cases \"S = {}\")\n  case True\n  then show ?thesis by auto\nnext\n  case False\n  then have *: \"0 \\<in> S \\<and> (\\<forall>c. c > 0 \\<longrightarrow> (*\\<^sub>R) c ` S = S)\"\n    using cone_iff[of S] assms by auto\n  {\n    fix c :: real\n    assume \"c > 0\"\n    then have \"(*\\<^sub>R) c ` (convex hull S) = convex hull ((*\\<^sub>R) c ` S)\"\n      using convex_hull_scaling[of _ S] by auto\n    also have \"\\<dots> = convex hull S\"\n      using * \\<open>c > 0\\<close> by auto\n    finally have \"(*\\<^sub>R) c ` (convex hull S) = convex hull S\"\n      by auto\n  }\n  then have \"0 \\<in> convex hull S\" \"\\<And>c. c > 0 \\<Longrightarrow> ((*\\<^sub>R) c ` (convex hull S)) = (convex hull S)\"\n    using * hull_subset[of S convex] by auto\n  then show ?thesis\n    using \\<open>S \\<noteq> {}\\<close> cone_iff[of \"convex hull S\"] by auto\nqed\n\nsubsection \\<open>Radon's theorem\\<close>\n\ntext \"Formalized by Lars Schewe.\"\n\nlemma Radon_ex_lemma:\n  assumes \"finite c\" \"affine_dependent c\"\n  shows \"\\<exists>u. sum u c = 0 \\<and> (\\<exists>v\\<in>c. u v \\<noteq> 0) \\<and> sum (\\<lambda>v. u v *\\<^sub>R v) c = 0\"\nproof -\n  from assms(2)[unfolded affine_dependent_explicit]\n  obtain S u where\n      \"finite S\" \"S \\<subseteq> c\" \"sum u S = 0\" \"\\<exists>v\\<in>S. u v \\<noteq> 0\" \"(\\<Sum>v\\<in>S. u v *\\<^sub>R v) = 0\"\n    by blast\n  then show ?thesis\n    apply (rule_tac x=\"\\<lambda>v. if v\\<in>S then u v else 0\" in exI)\n    unfolding if_smult scaleR_zero_left \n    by (auto simp: Int_absorb1 sum.inter_restrict[OF \\<open>finite c\\<close>, symmetric])\nqed\n\nlemma Radon_s_lemma:\n  assumes \"finite S\"\n    and \"sum f S = (0::real)\"\n  shows \"sum f {x\\<in>S. 0 < f x} = - sum f {x\\<in>S. f x < 0}\"\nproof -\n  have *: \"\\<And>x. (if f x < 0 then f x else 0) + (if 0 < f x then f x else 0) = f x\"\n    by auto\n  show ?thesis\n    unfolding add_eq_0_iff[symmetric] and sum.inter_filter[OF assms(1)]\n      and sum.distrib[symmetric] and *\n    using assms(2)\n    by assumption\nqed\n\nlemma Radon_v_lemma:\n  assumes \"finite S\"\n    and \"sum f S = 0\"\n    and \"\\<forall>x. g x = (0::real) \\<longrightarrow> f x = (0::'a::euclidean_space)\"\n  shows \"(sum f {x\\<in>S. 0 < g x}) = - sum f {x\\<in>S. g x < 0}\"\nproof -\n  have *: \"\\<And>x. (if 0 < g x then f x else 0) + (if g x < 0 then f x else 0) = f x\"\n    using assms(3) by auto\n  show ?thesis\n    unfolding eq_neg_iff_add_eq_0 and sum.inter_filter[OF assms(1)]\n      and sum.distrib[symmetric] and *\n    using assms(2)\n    apply assumption\n    done\nqed\n\nlemma Radon_partition:\n  assumes \"finite C\" \"affine_dependent C\"\n  shows \"\\<exists>m p. m \\<inter> p = {} \\<and> m \\<union> p = C \\<and> (convex hull m) \\<inter> (convex hull p) \\<noteq> {}\"\nproof -\n  obtain u v where uv: \"sum u C = 0\" \"v\\<in>C\" \"u v \\<noteq> 0\"  \"(\\<Sum>v\\<in>C. u v *\\<^sub>R v) = 0\"\n    using Radon_ex_lemma[OF assms] by auto\n  have fin: \"finite {x \\<in> C. 0 < u x}\" \"finite {x \\<in> C. 0 > u x}\"\n    using assms(1) by auto\n  define z  where \"z = inverse (sum u {x\\<in>C. u x > 0}) *\\<^sub>R sum (\\<lambda>x. u x *\\<^sub>R x) {x\\<in>C. u x > 0}\"\n  have \"sum u {x \\<in> C. 0 < u x} \\<noteq> 0\"\n  proof (cases \"u v \\<ge> 0\")\n    case False\n    then have \"u v < 0\" by auto\n    then show ?thesis\n    proof (cases \"\\<exists>w\\<in>{x \\<in> C. 0 < u x}. u w > 0\")\n      case True\n      then show ?thesis\n        using sum_nonneg_eq_0_iff[of _ u, OF fin(1)] by auto\n    next\n      case False\n      then have \"sum u C \\<le> sum (\\<lambda>x. if x=v then u v else 0) C\"\n        by (rule_tac sum_mono, auto)\n      then show ?thesis\n        unfolding sum.delta[OF assms(1)] using uv(2) and \\<open>u v < 0\\<close> and uv(1) by auto\n    qed\n  qed (insert sum_nonneg_eq_0_iff[of _ u, OF fin(1)] uv(2-3), auto)\n\n  then have *: \"sum u {x\\<in>C. u x > 0} > 0\"\n    unfolding less_le by (metis (no_types, lifting) mem_Collect_eq sum_nonneg)\n  moreover have \"sum u ({x \\<in> C. 0 < u x} \\<union> {x \\<in> C. u x < 0}) = sum u C\"\n    \"(\\<Sum>x\\<in>{x \\<in> C. 0 < u x} \\<union> {x \\<in> C. u x < 0}. u x *\\<^sub>R x) = (\\<Sum>x\\<in>C. u x *\\<^sub>R x)\"\n    using assms(1)\n    by (rule_tac[!] sum.mono_neutral_left, auto)\n  then have \"sum u {x \\<in> C. 0 < u x} = - sum u {x \\<in> C. 0 > u x}\"\n    \"(\\<Sum>x\\<in>{x \\<in> C. 0 < u x}. u x *\\<^sub>R x) = - (\\<Sum>x\\<in>{x \\<in> C. 0 > u x}. u x *\\<^sub>R x)\"\n    unfolding eq_neg_iff_add_eq_0\n    using uv(1,4)\n    by (auto simp: sum.union_inter_neutral[OF fin, symmetric])\n  moreover have \"\\<forall>x\\<in>{v \\<in> C. u v < 0}. 0 \\<le> inverse (sum u {x \\<in> C. 0 < u x}) * - u x\"\n    using * by (fastforce intro: mult_nonneg_nonneg)\n  ultimately have \"z \\<in> convex hull {v \\<in> C. u v \\<le> 0}\"\n    unfolding convex_hull_explicit mem_Collect_eq\n    apply (rule_tac x=\"{v \\<in> C. u v < 0}\" in exI)\n    apply (rule_tac x=\"\\<lambda>y. inverse (sum u {x\\<in>C. u x > 0}) * - u y\" in exI)\n    using assms(1) unfolding scaleR_scaleR[symmetric] scaleR_right.sum [symmetric] \n    by (auto simp: z_def sum_negf sum_distrib_left[symmetric])\n  moreover have \"\\<forall>x\\<in>{v \\<in> C. 0 < u v}. 0 \\<le> inverse (sum u {x \\<in> C. 0 < u x}) * u x\"\n    using * by (fastforce intro: mult_nonneg_nonneg)\n  then have \"z \\<in> convex hull {v \\<in> C. u v > 0}\"\n    unfolding convex_hull_explicit mem_Collect_eq\n    apply (rule_tac x=\"{v \\<in> C. 0 < u v}\" in exI)\n    apply (rule_tac x=\"\\<lambda>y. inverse (sum u {x\\<in>C. u x > 0}) * u y\" in exI)\n    using assms(1)\n    unfolding scaleR_scaleR[symmetric] scaleR_right.sum [symmetric]\n    using * by (auto simp: z_def sum_negf sum_distrib_left[symmetric])\n  ultimately show ?thesis\n    apply (rule_tac x=\"{v\\<in>C. u v \\<le> 0}\" in exI)\n    apply (rule_tac x=\"{v\\<in>C. u v > 0}\" in exI, auto)\n    done\nqed\n\ntheorem Radon:\n  assumes \"affine_dependent c\"\n  obtains m p where \"m \\<subseteq> c\" \"p \\<subseteq> c\" \"m \\<inter> p = {}\" \"(convex hull m) \\<inter> (convex hull p) \\<noteq> {}\"\nproof -\n  from assms[unfolded affine_dependent_explicit]\n  obtain S u where\n      \"finite S\" \"S \\<subseteq> c\" \"sum u S = 0\" \"\\<exists>v\\<in>S. u v \\<noteq> 0\" \"(\\<Sum>v\\<in>S. u v *\\<^sub>R v) = 0\"\n    by blast\n  then have *: \"finite S\" \"affine_dependent S\" and S: \"S \\<subseteq> c\"\n    unfolding affine_dependent_explicit by auto\n  from Radon_partition[OF *]\n  obtain m p where \"m \\<inter> p = {}\" \"m \\<union> p = S\" \"convex hull m \\<inter> convex hull p \\<noteq> {}\"\n    by blast\n  with S show ?thesis\n    by (force intro: that[of p m])\nqed\n\n\nsubsection \\<open>Helly's theorem\\<close>\n\nlemma Helly_induct:\n  fixes f :: \"'a::euclidean_space set set\"\n  assumes \"card f = n\"\n    and \"n \\<ge> DIM('a) + 1\"\n    and \"\\<forall>s\\<in>f. convex s\" \"\\<forall>t\\<subseteq>f. card t = DIM('a) + 1 \\<longrightarrow> \\<Inter>t \\<noteq> {}\"\n  shows \"\\<Inter>f \\<noteq> {}\"\n  using assms\nproof (induction n arbitrary: f)\n  case 0\n  then show ?case by auto\nnext\n  case (Suc n)\n  have \"finite f\"\n    using \\<open>card f = Suc n\\<close> by (auto intro: card_ge_0_finite)\n  show \"\\<Inter>f \\<noteq> {}\"\n  proof (cases \"n = DIM('a)\")\n    case True\n    then show ?thesis\n      by (simp add: Suc.prems(1) Suc.prems(4))\n  next\n    case False\n    have \"\\<Inter>(f - {s}) \\<noteq> {}\" if \"s \\<in> f\" for s\n    proof (rule Suc.IH[rule_format])\n      show \"card (f - {s}) = n\"\n        by (simp add: Suc.prems(1) \\<open>finite f\\<close> that)\n      show \"DIM('a) + 1 \\<le> n\"\n        using False Suc.prems(2) by linarith\n      show \"\\<And>t. \\<lbrakk>t \\<subseteq> f - {s}; card t = DIM('a) + 1\\<rbrakk> \\<Longrightarrow> \\<Inter>t \\<noteq> {}\"\n        by (simp add: Suc.prems(4) subset_Diff_insert)\n    qed (use Suc in auto)\n    then have \"\\<forall>s\\<in>f. \\<exists>x. x \\<in> \\<Inter>(f - {s})\"\n      by blast\n    then obtain X where X: \"\\<And>s. s\\<in>f \\<Longrightarrow> X s \\<in> \\<Inter>(f - {s})\"\n      by metis\n    show ?thesis\n    proof (cases \"inj_on X f\")\n      case False\n      then obtain s t where \"s\\<noteq>t\" and st: \"s\\<in>f\" \"t\\<in>f\" \"X s = X t\"\n        unfolding inj_on_def by auto\n      then have *: \"\\<Inter>f = \\<Inter>(f - {s}) \\<inter> \\<Inter>(f - {t})\" by auto\n      show ?thesis\n        by (metis \"*\" X disjoint_iff_not_equal st)\n    next\n      case True\n      then obtain m p where mp: \"m \\<inter> p = {}\" \"m \\<union> p = X ` f\" \"convex hull m \\<inter> convex hull p \\<noteq> {}\"\n        using Radon_partition[of \"X ` f\"] and affine_dependent_biggerset[of \"X ` f\"]\n        unfolding card_image[OF True] and \\<open>card f = Suc n\\<close>\n        using Suc(3) \\<open>finite f\\<close> and False\n        by auto\n      have \"m \\<subseteq> X ` f\" \"p \\<subseteq> X ` f\"\n        using mp(2) by auto\n      then obtain g h where gh:\"m = X ` g\" \"p = X ` h\" \"g \\<subseteq> f\" \"h \\<subseteq> f\"\n        unfolding subset_image_iff by auto\n      then have \"f \\<union> (g \\<union> h) = f\" by auto\n      then have f: \"f = g \\<union> h\"\n        using inj_on_Un_image_eq_iff[of X f \"g \\<union> h\"] and True\n        unfolding mp(2)[unfolded image_Un[symmetric] gh]\n        by auto\n      have *: \"g \\<inter> h = {}\"\n        using gh(1) gh(2) local.mp(1) by blast\n      have \"convex hull (X ` h) \\<subseteq> \\<Inter>g\" \"convex hull (X ` g) \\<subseteq> \\<Inter>h\"\n        by (rule hull_minimal; use X * f in \\<open>auto simp: Suc.prems(3) convex_Inter\\<close>)+\n      then show ?thesis\n        unfolding f using mp(3)[unfolded gh] by blast\n    qed\n  qed \nqed\n\ntheorem Helly:\n  fixes f :: \"'a::euclidean_space set set\"\n  assumes \"card f \\<ge> DIM('a) + 1\" \"\\<forall>s\\<in>f. convex s\"\n    and \"\\<And>t. \\<lbrakk>t\\<subseteq>f; card t = DIM('a) + 1\\<rbrakk> \\<Longrightarrow> \\<Inter>t \\<noteq> {}\"\n  shows \"\\<Inter>f \\<noteq> {}\"\n  using Helly_induct assms by blast\n\nsubsection \\<open>Epigraphs of convex functions\\<close>\n\ndefinition\\<^marker>\\<open>tag important\\<close> \"epigraph S (f :: _ \\<Rightarrow> real) = {xy. fst xy \\<in> S \\<and> f (fst xy) \\<le> snd xy}\"\n\nlemma mem_epigraph: \"(x, y) \\<in> epigraph S f \\<longleftrightarrow> x \\<in> S \\<and> f x \\<le> y\"\n  unfolding epigraph_def by auto\n\nlemma convex_epigraph: \"convex (epigraph S f) \\<longleftrightarrow> convex_on S f \\<and> convex S\"\nproof safe\n  assume L: \"convex (epigraph S f)\"\n  then show \"convex_on S f\"\n    by (auto simp: convex_def convex_on_def epigraph_def)\n  show \"convex S\"\n    using L by (fastforce simp: convex_def convex_on_def epigraph_def)\nnext\n  assume \"convex_on S f\" \"convex S\"\n  then show \"convex (epigraph S f)\"\n    unfolding convex_def convex_on_def epigraph_def\n    apply safe\n     apply (rule_tac [2] y=\"u * f a + v * f aa\" in order_trans)\n      apply (auto intro!:mult_left_mono add_mono)\n    done\nqed\n\nlemma convex_epigraphI: \"convex_on S f \\<Longrightarrow> convex S \\<Longrightarrow> convex (epigraph S f)\"\n  unfolding convex_epigraph by auto\n\nlemma convex_epigraph_convex: \"convex S \\<Longrightarrow> convex_on S f \\<longleftrightarrow> convex(epigraph S f)\"\n  by (simp add: convex_epigraph)\n\n\nsubsubsection\\<^marker>\\<open>tag unimportant\\<close> \\<open>Use this to derive general bound property of convex function\\<close>\n\n\nlemma convex_on:\n  assumes \"convex S\"\n  shows \"convex_on S f \\<longleftrightarrow>\n    (\\<forall>k u x. (\\<forall>i\\<in>{1..k::nat}. 0 \\<le> u i \\<and> x i \\<in> S) \\<and> sum u {1..k} = 1 \\<longrightarrow>\n      f (sum (\\<lambda>i. u i *\\<^sub>R x i) {1..k}) \\<le> sum (\\<lambda>i. u i * f(x i)) {1..k})\"\n  (is \"?lhs = (\\<forall>k u x. ?rhs k u x)\")\nproof\n  assume ?lhs \n  then have \\<section>: \"convex {xy. fst xy \\<in> S \\<and> f (fst xy) \\<le> snd xy}\"\n    by (metis assms convex_epigraph epigraph_def)\n  show \"\\<forall>k u x. ?rhs k u x\"\n  proof (intro allI)\n    fix k u x\n    show \"?rhs k u x\"\n      using \\<section>\n      unfolding  convex mem_Collect_eq fst_sum snd_sum \n      apply safe\n      apply (drule_tac x=k in spec)\n      apply (drule_tac x=u in spec)\n      apply (drule_tac x=\"\\<lambda>i. (x i, f (x i))\" in spec)\n      apply simp\n      done\n  qed\nnext\n  assume \"\\<forall>k u x. ?rhs k u x\"\n  then show ?lhs\n  unfolding convex_epigraph_convex[OF assms] convex epigraph_def Ball_def mem_Collect_eq fst_sum snd_sum\n  using assms[unfolded convex] apply clarsimp\n  apply (rule_tac y=\"\\<Sum>i = 1..k. u i * f (fst (x i))\" in order_trans)\n  by (auto simp add: mult_left_mono intro: sum_mono)\nqed\n\n\nsubsection\\<^marker>\\<open>tag unimportant\\<close> \\<open>A bound within a convex hull\\<close>\n\nlemma convex_on_convex_hull_bound:\n  assumes \"convex_on (convex hull S) f\"\n    and \"\\<forall>x\\<in>S. f x \\<le> b\"\n  shows \"\\<forall>x\\<in> convex hull S. f x \\<le> b\"\nproof\n  fix x\n  assume \"x \\<in> convex hull S\"\n  then obtain k u v where\n    u: \"\\<forall>i\\<in>{1..k::nat}. 0 \\<le> u i \\<and> v i \\<in> S\" \"sum u {1..k} = 1\" \"(\\<Sum>i = 1..k. u i *\\<^sub>R v i) = x\"\n    unfolding convex_hull_indexed mem_Collect_eq by auto\n  have \"(\\<Sum>i = 1..k. u i * f (v i)) \\<le> b\"\n    using sum_mono[of \"{1..k}\" \"\\<lambda>i. u i * f (v i)\" \"\\<lambda>i. u i * b\"]\n    unfolding sum_distrib_right[symmetric] u(2) mult_1\n    using assms(2) mult_left_mono u(1) by blast\n  then show \"f x \\<le> b\"\n    using assms(1)[unfolded convex_on[OF convex_convex_hull], rule_format, of k u v]\n    using hull_inc u by fastforce\nqed\n\nlemma convex_set_plus:\n  assumes \"convex S\" and \"convex T\" shows \"convex (S + T)\"\nproof -\n  have \"convex (\\<Union>x\\<in> S. \\<Union>y \\<in> T. {x + y})\"\n    using assms by (rule convex_sums)\n  moreover have \"(\\<Union>x\\<in> S. \\<Union>y \\<in> T. {x + y}) = S + T\"\n    unfolding set_plus_def by auto\n  finally show \"convex (S + T)\" .\nqed\n\nlemma convex_set_sum:\n  assumes \"\\<And>i. i \\<in> A \\<Longrightarrow> convex (B i)\"\n  shows \"convex (\\<Sum>i\\<in>A. B i)\"\nproof (cases \"finite A\")\n  case True then show ?thesis using assms\n    by induct (auto simp: convex_set_plus)\nqed auto\n\nlemma finite_set_sum:\n  assumes \"finite A\" and \"\\<forall>i\\<in>A. finite (B i)\" shows \"finite (\\<Sum>i\\<in>A. B i)\"\n  using assms by (induct set: finite, simp, simp add: finite_set_plus)\n\nlemma box_eq_set_sum_Basis:\n  \"{x. \\<forall>i\\<in>Basis. x\\<bullet>i \\<in> B i} = (\\<Sum>i\\<in>Basis. (\\<lambda>x. x *\\<^sub>R i) ` (B i))\" (is \"?lhs = ?rhs\")\nproof -\n  have \"\\<And>x. \\<forall>i\\<in>Basis. x \\<bullet> i \\<in> B i \\<Longrightarrow>\n         \\<exists>s. x = sum s Basis \\<and> (\\<forall>i\\<in>Basis. s i \\<in> (\\<lambda>x. x *\\<^sub>R i) ` B i)\"\n    by (metis (mono_tags, lifting) euclidean_representation image_iff)\n  moreover\n  have \"sum f Basis \\<bullet> i \\<in> B i\" if \"i \\<in> Basis\" and f: \"\\<forall>i\\<in>Basis. f i \\<in> (\\<lambda>x. x *\\<^sub>R i) ` B i\" for i f\n  proof -\n    have \"(\\<Sum>x\\<in>Basis - {i}. f x \\<bullet> i) = 0\"\n    proof (rule sum.neutral, intro strip)\n      show \"f x \\<bullet> i = 0\" if \"x \\<in> Basis - {i}\" for x\n        using that f \\<open>i \\<in> Basis\\<close> inner_Basis that by fastforce\n    qed\n    then have \"(\\<Sum>x\\<in>Basis. f x \\<bullet> i) = f i \\<bullet> i\"\n      by (metis (no_types) \\<open>i \\<in> Basis\\<close> add.right_neutral sum.remove [OF finite_Basis])\n    then have \"(\\<Sum>x\\<in>Basis. f x \\<bullet> i) \\<in> B i\"\n      using f that(1) by auto\n    then show ?thesis\n      by (simp add: inner_sum_left)\n  qed\n  ultimately show ?thesis\n    by (subst set_sum_alt [OF finite_Basis]) auto\nqed\n\nlemma convex_hull_set_sum:\n  \"convex hull (\\<Sum>i\\<in>A. B i) = (\\<Sum>i\\<in>A. convex hull (B i))\"\nproof (cases \"finite A\")\n  assume \"finite A\" then show ?thesis\n    by (induct set: finite, simp, simp add: convex_hull_set_plus)\nqed simp\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/Analysis/Convex.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8376199552262967, "lm_q2_score": 0.8723473713594991, "lm_q1q2_score": 0.7306955661399213}}
{"text": "(*  \n  Title:    Order_Predicates.thy\n  Author:   Manuel Eberl, TU M\u00fcnchen\n\n  Locales for order relations modelled as predicates (as opposed to sets of pairs).\n*)\nsection \\<open>Order Relations as Binary Predicates\\<close>\n\ntheory Order_Predicates\nimports \n  Main\n  \"HOL-Library.Disjoint_Sets\"\n  \"HOL-Combinatorics.Permutations\"\n  \"List-Index.List_Index\"\nbegin\n\nsubsection \\<open>Basic Operations on Relations\\<close>\n\ntext \\<open>The type of binary relations\\<close>\ntype_synonym 'a relation = \"'a \\<Rightarrow> 'a \\<Rightarrow> bool\"\n\ndefinition map_relation :: \"('a \\<Rightarrow> 'b) \\<Rightarrow> 'b relation \\<Rightarrow> 'a relation\" where\n  \"map_relation f R = (\\<lambda>x y. R (f x) (f y))\"\n\ndefinition restrict_relation :: \"'a set \\<Rightarrow> 'a relation \\<Rightarrow> 'a relation\" where\n  \"restrict_relation A R = (\\<lambda>x y. x \\<in> A \\<and> y \\<in> A \\<and> R x y)\"\n\nlemma restrict_relation_restrict_relation [simp]:\n  \"restrict_relation A (restrict_relation B R) = restrict_relation (A \\<inter> B) R\"\n  by (intro ext) (auto simp add: restrict_relation_def)\n\nlemma restrict_relation_empty [simp]: \"restrict_relation {} R = (\\<lambda>_ _. False)\"\n  by (simp add: restrict_relation_def)\n\nlemma restrict_relation_UNIV [simp]: \"restrict_relation UNIV R = R\"\n  by (simp add: restrict_relation_def)\n\n\nsubsection \\<open>Preorders\\<close>\n\ntext \\<open>Preorders are reflexive and transitive binary relations.\\<close>\nlocale preorder_on =\n  fixes carrier :: \"'a set\"\n  fixes le :: \"'a relation\"\n  assumes not_outside: \"le x y \\<Longrightarrow> x \\<in> carrier\" \"le x y \\<Longrightarrow> y \\<in> carrier\"\n  assumes refl: \"x \\<in> carrier \\<Longrightarrow> le x x\"\n  assumes trans: \"le x y \\<Longrightarrow> le y z \\<Longrightarrow> le x z\"\nbegin\n\nlemma carrier_eq: \"carrier = {x. le x x}\"\n  using not_outside refl by auto\n  \nlemma preorder_on_map:\n  \"preorder_on (f -` carrier) (map_relation f le)\"\n  by unfold_locales (auto dest: not_outside simp: map_relation_def refl elim: trans)\n  \nlemma preorder_on_restrict:\n  \"preorder_on (carrier \\<inter> A) (restrict_relation A le)\"\n  by unfold_locales (auto simp: restrict_relation_def refl intro: trans not_outside)\n\nlemma preorder_on_restrict_subset:\n  \"A \\<subseteq> carrier \\<Longrightarrow> preorder_on A (restrict_relation A le)\"\n  using preorder_on_restrict[of A] by (simp add: Int_absorb1)\n\nlemma restrict_relation_carrier [simp]:\n  \"restrict_relation carrier le = le\"\n  using not_outside by (intro ext) (auto simp add: restrict_relation_def)\n\nend\n  \n\nsubsection \\<open>Total preorders\\<close>\n\ntext \\<open>Total preorders are preorders where any two elements are comparable.\\<close>\nlocale total_preorder_on = preorder_on +\n  assumes total: \"x \\<in> carrier \\<Longrightarrow> y \\<in> carrier \\<Longrightarrow> le x y \\<or> le y x\"\nbegin\n\nlemma total': \"\\<not>le x y \\<Longrightarrow> x \\<in> carrier \\<Longrightarrow> y \\<in> carrier \\<Longrightarrow> le y x\"\n  using total[of x y] by blast\n\nlemma total_preorder_on_map:\n  \"total_preorder_on (f -` carrier) (map_relation f le)\"\nproof -\n  interpret R': preorder_on \"f -` carrier\" \"map_relation f le\"\n    using preorder_on_map[of f] .\n  show ?thesis by unfold_locales (simp add: map_relation_def total)\nqed\n\nlemma total_preorder_on_restrict:\n  \"total_preorder_on (carrier \\<inter> A) (restrict_relation A le)\"\nproof -\n  interpret R': preorder_on \"carrier \\<inter> A\" \"restrict_relation A le\"\n    by (rule preorder_on_restrict)\n  from total show ?thesis\n    by unfold_locales (auto simp: restrict_relation_def)\nqed\n\nlemma total_preorder_on_restrict_subset:\n  \"A \\<subseteq> carrier \\<Longrightarrow> total_preorder_on A (restrict_relation A le)\"\n  using total_preorder_on_restrict[of A] by (simp add: Int_absorb1)\n\nend\n\n\ntext \\<open>Some fancy notation for order relations\\<close>\nabbreviation (input) weakly_preferred :: \"'a \\<Rightarrow> 'a relation \\<Rightarrow> 'a \\<Rightarrow> bool\"\n    (\"_ \\<preceq>[_] _\" [51,10,51] 60) where\n  \"a \\<preceq>[R] b \\<equiv> R a b\"\n  \ndefinition strongly_preferred (\"_ \\<prec>[_] _\" [51,10,51] 60) where\n  \"a \\<prec>[R] b \\<equiv> (a \\<preceq>[R] b) \\<and> \\<not>(b \\<preceq>[R] a)\"\n\ndefinition indifferent (\"_ \\<sim>[_] _\" [51,10,51] 60) where\n  \"a \\<sim>[R] b \\<equiv> (a \\<preceq>[R] b) \\<and> (b \\<preceq>[R] a)\"\n\nabbreviation (input) weakly_not_preferred (\"_ \\<succeq>[_] _\" [51,10,51] 60) where\n  \"a \\<succeq>[R] b \\<equiv> b \\<preceq>[R] a\"\n  term \"a \\<succeq>[R] b \\<longleftrightarrow> b \\<preceq>[R] a\"\n\nabbreviation (input) strongly_not_preferred (\"_ \\<succ>[_] _\" [51,10,51] 60) where\n  \"a \\<succ>[R] b \\<equiv> b \\<prec>[R] a\"\n\ncontext preorder_on\nbegin\n\nlemma strict_trans: \"a \\<prec>[le] b \\<Longrightarrow> b \\<prec>[le] c \\<Longrightarrow> a \\<prec>[le] c\"\n  unfolding strongly_preferred_def by (blast intro: trans)\n\nlemma weak_strict_trans: \"a \\<preceq>[le] b \\<Longrightarrow> b \\<prec>[le] c \\<Longrightarrow> a \\<prec>[le] c\"\n  unfolding strongly_preferred_def by (blast intro: trans)\n\nlemma strict_weak_trans: \"a \\<prec>[le] b \\<Longrightarrow> b \\<preceq>[le] c \\<Longrightarrow> a \\<prec>[le] c\"\n  unfolding strongly_preferred_def by (blast intro: trans)\n\nend\n  \nlemma (in total_preorder_on) not_weakly_preferred_iff:\n  \"a \\<in> carrier \\<Longrightarrow> b \\<in> carrier \\<Longrightarrow> \\<not>a \\<preceq>[le] b \\<longleftrightarrow> b \\<prec>[le] a\"\n  using total[of a b] by (auto simp: strongly_preferred_def)\n\nlemma (in total_preorder_on) not_strongly_preferred_iff:\n  \"a \\<in> carrier \\<Longrightarrow> b \\<in> carrier \\<Longrightarrow> \\<not>a \\<prec>[le] b \\<longleftrightarrow> b \\<preceq>[le] a\"\n  using total[of a b] by (auto simp: strongly_preferred_def)\n\n\n\nsubsection \\<open>Orders\\<close>\n\nlocale order_on = preorder_on +\n  assumes antisymmetric: \"le x y \\<Longrightarrow> le y x \\<Longrightarrow> x = y\"\n\nlocale linorder_on = order_on carrier le + total_preorder_on carrier le for carrier le\n\n\nsubsection \\<open>Maximal elements\\<close>\n\ntext \\<open>\n  Maximal elements are elements in a preorder for which there exists no strictly greater element.\n\\<close>\n\ndefinition Max_wrt_among :: \"'a relation \\<Rightarrow> 'a set \\<Rightarrow> 'a set\" where\n  \"Max_wrt_among R A = {x\\<in>A. R x x \\<and> (\\<forall>y\\<in>A. R x y \\<longrightarrow> R y x)}\"\n\nlemma Max_wrt_among_cong:\n  assumes \"restrict_relation A R = restrict_relation A R'\"\n  shows   \"Max_wrt_among R A = Max_wrt_among R' A\"\nproof -\n  from assms have \"R x y \\<longleftrightarrow> R' x y\" if \"x \\<in> A\" \"y \\<in> A\" for x y\n    using that by (auto simp: restrict_relation_def fun_eq_iff)\n  thus ?thesis unfolding Max_wrt_among_def by blast\nqed\n\ndefinition Max_wrt :: \"'a relation \\<Rightarrow> 'a set\" where\n  \"Max_wrt R = Max_wrt_among R UNIV\"\n  \nlemma Max_wrt_altdef: \"Max_wrt R = {x. R x x \\<and> (\\<forall>y. R x y \\<longrightarrow> R y x)}\"\n  unfolding Max_wrt_def Max_wrt_among_def by simp\n\ncontext preorder_on\nbegin\n\nlemma Max_wrt_among_preorder:\n  \"Max_wrt_among le A = {x\\<in>carrier \\<inter> A. \\<forall>y\\<in>carrier \\<inter> A. le x y \\<longrightarrow> le y x}\"\n  unfolding Max_wrt_among_def using not_outside refl by blast\n\nlemma Max_wrt_preorder:\n  \"Max_wrt le = {x\\<in>carrier. \\<forall>y\\<in>carrier. le x y \\<longrightarrow> le y x}\"\n  unfolding Max_wrt_altdef using not_outside refl by blast\n\nlemma Max_wrt_among_subset:\n  \"Max_wrt_among le A \\<subseteq> carrier\" \"Max_wrt_among le A \\<subseteq> A\"\n  unfolding Max_wrt_among_preorder by auto\n  \nlemma Max_wrt_subset:\n  \"Max_wrt le \\<subseteq> carrier\"\n  unfolding Max_wrt_preorder by auto\n\nlemma Max_wrt_among_nonempty:\n  assumes \"B \\<inter> carrier \\<noteq> {}\" \"finite (B \\<inter> carrier)\"\n  shows   \"Max_wrt_among le B \\<noteq> {}\"\nproof -\n  define A where \"A = B \\<inter> carrier\"\n  have \"A \\<subseteq> carrier\" by (simp add: A_def)\n  from assms(2,1)[folded A_def] this have \"{x\\<in>A. (\\<forall>y\\<in>A. le x y \\<longrightarrow> le y x)} \\<noteq> {}\"\n  proof (induction A rule: finite_ne_induct)\n    case (singleton x)\n    thus ?case by (auto simp: refl)\n  next\n    case (insert x A)\n    then obtain y where y: \"y \\<in> A\" \"\\<And>z. z \\<in> A \\<Longrightarrow> le y z \\<Longrightarrow> le z y\" by blast\n    thus ?case using insert.prems\n      by (cases \"le y x\") (blast intro: trans)+\n  qed\n  thus ?thesis by (simp add: A_def Max_wrt_among_preorder Int_commute)\nqed\n  \nlemma Max_wrt_nonempty:\n  \"carrier \\<noteq> {} \\<Longrightarrow> finite carrier \\<Longrightarrow> Max_wrt le \\<noteq> {}\"\n  using Max_wrt_among_nonempty[of UNIV] by (simp add: Max_wrt_def)\n\nlemma Max_wrt_among_map_relation_vimage:\n  \"f -` Max_wrt_among le A \\<subseteq> Max_wrt_among (map_relation f le) (f -` A)\"\n  by (auto simp: Max_wrt_among_def map_relation_def)\n\n\n\nlemma image_subset_vimage_the_inv_into: \n  assumes \"inj_on f A\" \"B \\<subseteq> A\"\n  shows   \"f ` B \\<subseteq> the_inv_into A f -` B\"\n  using assms by (auto simp: the_inv_into_f_f)\n\nlemma Max_wrt_among_map_relation_bij_subset:\n  assumes \"bij (f :: 'a \\<Rightarrow> 'b)\"\n  shows   \"f ` Max_wrt_among le A \\<subseteq> \n             Max_wrt_among (map_relation (inv f) le) (f ` A)\"\n  using assms Max_wrt_among_map_relation_vimage[of \"inv f\" A]\n  by (simp add: bij_imp_bij_inv inv_inv_eq bij_vimage_eq_inv_image)\n  \nlemma Max_wrt_among_map_relation_bij:\n  assumes \"bij f\"\n  shows   \"f ` Max_wrt_among le A = Max_wrt_among (map_relation (inv f) le) (f ` A)\"\nproof (intro equalityI Max_wrt_among_map_relation_bij_subset assms)\n  interpret R: preorder_on \"f ` carrier\" \"map_relation (inv f) le\"\n    using preorder_on_map[of \"inv f\"] assms \n      by (simp add: bij_imp_bij_inv bij_vimage_eq_inv_image inv_inv_eq)\n  show \"Max_wrt_among (map_relation (inv f) le) (f ` A) \\<subseteq> f ` Max_wrt_among le A\"\n    unfolding Max_wrt_among_preorder R.Max_wrt_among_preorder \n    using assms bij_is_inj[OF assms]\n    by (auto simp: map_relation_def inv_f_f image_Int [symmetric])\nqed\n\nlemma Max_wrt_map_relation_bij:\n  \"bij f \\<Longrightarrow> f ` Max_wrt le = Max_wrt (map_relation (inv f) le)\"\nproof -\n  assume bij: \"bij f\"\n  interpret R: preorder_on \"f ` carrier\" \"map_relation (inv f) le\"\n    using preorder_on_map[of \"inv f\"] bij\n      by (simp add: bij_imp_bij_inv bij_vimage_eq_inv_image inv_inv_eq)\n  from bij show ?thesis\n    unfolding R.Max_wrt_preorder Max_wrt_preorder\n    by (auto simp: map_relation_def inv_f_f bij_is_inj)\nqed\n\nlemma Max_wrt_among_mono:\n  \"le x y \\<Longrightarrow> x \\<in> Max_wrt_among le A \\<Longrightarrow> y \\<in> A \\<Longrightarrow> y \\<in> Max_wrt_among le A\"\n  using not_outside by (auto simp: Max_wrt_among_preorder intro: trans)\n\nlemma Max_wrt_mono:\n  \"le x y \\<Longrightarrow> x \\<in> Max_wrt le \\<Longrightarrow> y \\<in> Max_wrt le\"\n  unfolding Max_wrt_def using Max_wrt_among_mono[of x y UNIV] by blast\n\nend\n\n\ncontext total_preorder_on\nbegin\n\nlemma Max_wrt_among_total_preorder:\n  \"Max_wrt_among le A = {x\\<in>carrier \\<inter> A. \\<forall>y\\<in>carrier \\<inter> A. le y x}\"\n  unfolding Max_wrt_among_preorder using total by blast\n\nlemma Max_wrt_total_preorder:\n  \"Max_wrt le = {x\\<in>carrier. \\<forall>y\\<in>carrier. le y x}\"\n  unfolding Max_wrt_preorder using total by blast\n\nlemma decompose_Max:\n  assumes A: \"A \\<subseteq> carrier\"\n  defines \"M \\<equiv> Max_wrt_among le A\"\n  shows   \"restrict_relation A le = (\\<lambda>x y. x \\<in> A \\<and> y \\<in> M \\<or> (y \\<notin> M \\<and> restrict_relation (A - M) le x y))\"\n  using A by (intro ext) (auto simp: M_def Max_wrt_among_total_preorder \n                            restrict_relation_def Int_absorb1 intro: trans)\n\nend\n\n\nsubsection \\<open>Weak rankings\\<close>\n\ninductive of_weak_ranking :: \"'alt set list \\<Rightarrow> 'alt relation\" where\n  \"i \\<le> j \\<Longrightarrow> i < length xs \\<Longrightarrow> j < length xs \\<Longrightarrow> x \\<in> xs ! i \\<Longrightarrow> y \\<in> xs ! j \\<Longrightarrow> \n     x \\<succeq>[of_weak_ranking xs] y\"\n\nlemma of_weak_ranking_Nil [simp]: \"of_weak_ranking [] = (\\<lambda>_ _. False)\"\n  by (intro ext) (simp add: of_weak_ranking.simps)\n\nlemma of_weak_ranking_Nil' [code]: \"of_weak_ranking [] x y = False\"\n  by simp\n  \nlemma of_weak_ranking_Cons [code]:\n  \"x \\<succeq>[of_weak_ranking (z#zs)] y \\<longleftrightarrow> x \\<in> z \\<and> y \\<in> \\<Union>(set (z#zs)) \\<or> x \\<succeq>[of_weak_ranking zs] y\" \n      (is \"?lhs \\<longleftrightarrow> ?rhs\")\nproof \n  assume ?lhs\n  then obtain i j \n    where ij: \"i < length (z#zs)\" \"j < length (z#zs)\" \"i \\<le> j\" \"x \\<in> (z#zs) ! i\" \"y \\<in> (z#zs) ! j\"\n    by (blast elim: of_weak_ranking.cases)\n  thus ?rhs by (cases i; cases j) (force intro: of_weak_ranking.intros)+\nnext\n  assume ?rhs\n  thus ?lhs\n  proof (elim disjE conjE)\n    assume \"x \\<in> z\" \"y \\<in> \\<Union>(set (z # zs))\"\n    then obtain j where \"j < length (z # zs)\" \"y \\<in> (z # zs) ! j\" \n      by (subst (asm) set_conv_nth) auto\n    with \\<open>x \\<in> z\\<close> show \"of_weak_ranking (z # zs) y x\" \n      by (intro of_weak_ranking.intros[of 0 j]) auto\n  next\n    assume \"of_weak_ranking zs y x\"\n    then obtain i j where \"i < length zs\" \"j < length zs\" \"i \\<le> j\" \"x \\<in> zs ! i\" \"y \\<in> zs ! j\"\n      by (blast elim: of_weak_ranking.cases)\n    thus \"of_weak_ranking (z # zs) y x\"\n      by (intro of_weak_ranking.intros[of \"Suc i\" \"Suc j\"]) auto\n  qed\nqed\n\nlemma of_weak_ranking_indifference:\n  assumes \"A \\<in> set xs\" \"x \\<in> A\" \"y \\<in> A\"\n  shows   \"x \\<preceq>[of_weak_ranking xs] y\"\n  using assms by (induction xs) (auto simp: of_weak_ranking_Cons)\n\n\nlemma of_weak_ranking_map:\n  \"map_relation f (of_weak_ranking xs) = of_weak_ranking (map ((-`) f) xs)\"\n  by (intro ext, induction xs)\n     (simp_all add: map_relation_def of_weak_ranking_Cons)\n\nlemma of_weak_ranking_permute':\n  assumes \"f permutes (\\<Union>(set xs))\"\n  shows   \"map_relation f (of_weak_ranking xs) = of_weak_ranking (map ((`) (inv f)) xs)\"\nproof -\n  have \"map_relation f (of_weak_ranking xs) = of_weak_ranking (map ((-`) f) xs)\"\n    by (rule of_weak_ranking_map)\n  also from assms have \"map ((-`) f) xs = map ((`) (inv f)) xs\"\n    by (intro map_cong refl) (simp_all add: bij_vimage_eq_inv_image permutes_bij)\n  finally show ?thesis .\nqed \n\nlemma of_weak_ranking_permute:\n  assumes \"f permutes (\\<Union>(set xs))\"\n  shows   \"of_weak_ranking (map ((`) f) xs) = map_relation (inv f) (of_weak_ranking xs)\"\n  using of_weak_ranking_permute'[OF permutes_inv[OF assms]] assms\n  by (simp add: inv_inv_eq permutes_bij)\n\ndefinition is_weak_ranking where\n  \"is_weak_ranking xs \\<longleftrightarrow> ({} \\<notin> set xs) \\<and>\n     (\\<forall>i j. i < length xs \\<and> j < length xs \\<and> i \\<noteq> j \\<longrightarrow> xs ! i \\<inter> xs ! j = {})\"\n\ndefinition is_finite_weak_ranking where\n  \"is_finite_weak_ranking xs \\<longleftrightarrow> is_weak_ranking xs \\<and> (\\<forall>x\\<in>set xs. finite x)\"\n\ndefinition weak_ranking :: \"'alt relation \\<Rightarrow> 'alt set list\" where\n  \"weak_ranking R = (SOME xs. is_weak_ranking xs \\<and> R = of_weak_ranking xs)\"\n\n\n\nlemma is_weak_ranking_nonempty: \"is_weak_ranking xs \\<Longrightarrow> {} \\<notin> set xs\"\n  by (simp add: is_weak_ranking_def) \n     \n\n\nlemma is_weak_ranking_rev [simp]: \"is_weak_ranking (rev xs) \\<longleftrightarrow> is_weak_ranking xs\"\n  by (simp add: is_weak_ranking_iff)\n\nlemma is_weak_ranking_map_inj:\n  assumes \"is_weak_ranking xs\" \"inj_on f (\\<Union>(set xs))\"\n  shows   \"is_weak_ranking (map ((`) f) xs)\"\n  using assms by (auto simp: is_weak_ranking_iff distinct_map inj_on_image disjoint_image)\n\nlemma of_weak_ranking_rev [simp]:\n  \"of_weak_ranking (rev xs) (x::'a) y \\<longleftrightarrow> of_weak_ranking xs y x\"\nproof -\n  have \"of_weak_ranking (rev xs) y x\" if \"of_weak_ranking xs x y\" for xs and x y :: 'a\n  proof -\n    from that obtain i j where \"i < length xs\" \"j < length xs\" \"x \\<in> xs ! i\" \"y \\<in> xs ! j\" \"i \\<ge> j\"\n      by (elim of_weak_ranking.cases) simp_all\n    thus ?thesis\n      by (intro of_weak_ranking.intros[of \"length xs - i - 1\" \"length xs - j - 1\"] diff_le_mono2)\n         (auto simp: diff_le_mono2 rev_nth)\n  qed\n  from this[of xs y x] this[of \"rev xs\" x y] show ?thesis by (intro iffI) simp_all\nqed\n\n\nlemma is_weak_ranking_Nil [simp, code]: \"is_weak_ranking []\"\n  by (auto simp: is_weak_ranking_def)\n\nlemma is_finite_weak_ranking_Nil [simp, code]: \"is_finite_weak_ranking []\"\n  by (auto simp: is_finite_weak_ranking_def)\n\nlemma is_weak_ranking_Cons_empty [simp]:\n  \"\\<not>is_weak_ranking ({} # xs)\" by (simp add: is_weak_ranking_def)\n\nlemma is_finite_weak_ranking_Cons_empty [simp]:\n  \"\\<not>is_finite_weak_ranking ({} # xs)\" by (simp add: is_finite_weak_ranking_def)\n  \nlemma is_weak_ranking_singleton [simp]:\n  \"is_weak_ranking [x] \\<longleftrightarrow> x \\<noteq> {}\" \n  by (auto simp add: is_weak_ranking_def)\n\nlemma is_finite_weak_ranking_singleton [simp]:\n  \"is_finite_weak_ranking [x] \\<longleftrightarrow> x \\<noteq> {} \\<and> finite x\" \n  by (auto simp add: is_finite_weak_ranking_def)\n  \nlemma is_weak_ranking_append:\n  \"is_weak_ranking (xs @ ys) \\<longleftrightarrow> \n      is_weak_ranking xs \\<and> is_weak_ranking ys \\<and>\n      (set xs \\<inter> set ys = {} \\<and> \\<Union>(set xs) \\<inter> \\<Union>(set ys) = {})\"\n  by (simp only: is_weak_ranking_iff)\n     (auto dest: disjointD disjoint_unionD1 disjoint_unionD2 intro: disjoint_union)\n\nlemma is_weak_ranking_Cons [code]:\n  \"is_weak_ranking (x # xs) \\<longleftrightarrow> \n      x \\<noteq> {} \\<and> is_weak_ranking xs \\<and> x \\<inter> \\<Union>(set xs) = {}\"\n  using is_weak_ranking_append[of \"[x]\" xs] by auto\n\nlemma is_finite_weak_ranking_Cons [code]:\n  \"is_finite_weak_ranking (x # xs) \\<longleftrightarrow> \n      x \\<noteq> {} \\<and> finite x \\<and> is_finite_weak_ranking xs \\<and> x \\<inter> \\<Union>(set xs) = {}\"\n  by (auto simp add: is_finite_weak_ranking_def is_weak_ranking_Cons)\n\nprimrec is_weak_ranking_aux where\n  \"is_weak_ranking_aux A [] \\<longleftrightarrow> True\"\n| \"is_weak_ranking_aux A (x#xs) \\<longleftrightarrow> x \\<noteq> {} \\<and>\n       A \\<inter> x = {} \\<and> is_weak_ranking_aux (A \\<union> x) xs\"\n\n\nlemma is_weak_ranking_aux:\n  \"is_weak_ranking_aux A xs \\<longleftrightarrow> A \\<inter> \\<Union>(set xs) = {} \\<and> is_weak_ranking xs\"\n  by (induction xs arbitrary: A) (auto simp: is_weak_ranking_Cons)\n\nlemma is_weak_ranking_code [code]:\n  \"is_weak_ranking xs \\<longleftrightarrow> is_weak_ranking_aux {} xs\"\n  by (subst is_weak_ranking_aux) auto\n\nlemma of_weak_ranking_altdef:\n  assumes \"is_weak_ranking xs\" \"x \\<in> \\<Union>(set xs)\" \"y \\<in> \\<Union>(set xs)\"\n  shows   \"of_weak_ranking xs x y \\<longleftrightarrow> \n             find_index ((\\<in>) x) xs \\<ge> find_index ((\\<in>) y) xs\"\nproof -\n from assms \n    have A: \"find_index ((\\<in>) x) xs < length xs\" \"find_index ((\\<in>) y) xs < length xs\"\n    by (simp_all add: find_index_less_size_conv)\n from this[THEN nth_find_index] \n    have B: \"x \\<in> xs ! find_index ((\\<in>) x) xs\" \"y \\<in> xs ! find_index ((\\<in>) y) xs\" .\n  show ?thesis\n  proof\n    assume \"of_weak_ranking xs x y\"\n    then obtain i j where ij: \"j \\<le> i\" \"i < length xs\" \"j < length xs\" \"x \\<in> xs ! i\" \"y \\<in> xs !j\"\n      by (cases rule: of_weak_ranking.cases) simp_all\n    with A B have \"i = find_index ((\\<in>) x) xs\" \"j = find_index ((\\<in>) y) xs\"\n      using assms(1) unfolding is_weak_ranking_def by blast+\n    with ij show \"find_index ((\\<in>) x) xs \\<ge> find_index ((\\<in>) y) xs\" by simp\n  next\n    assume \"find_index ((\\<in>) x) xs \\<ge> find_index ((\\<in>) y) xs\"\n    from this A(2,1) B(2,1) show \"of_weak_ranking xs x y\"\n      by (rule of_weak_ranking.intros)\n  qed\nqed\n\n  \n\n\nlemma restrict_relation_of_weak_ranking_Cons:\n  assumes \"is_weak_ranking (A # As)\"\n  shows   \"restrict_relation (\\<Union>(set As)) (of_weak_ranking (A # As)) = of_weak_ranking As\"\nproof -\n  from assms interpret R: total_preorder_on \"\\<Union>(set As)\" \"of_weak_ranking As\"\n    by (intro total_preorder_of_weak_ranking)\n       (simp_all add: is_weak_ranking_Cons)\n  from assms show ?thesis using R.not_outside\n    by (intro ext) (auto simp: restrict_relation_def of_weak_ranking_Cons\n                     is_weak_ranking_Cons)\nqed\n\n\n\n\nlemmas of_weak_ranking_wf = \n  total_preorder_of_weak_ranking is_weak_ranking_code insert_commute\n\n\n(* Test *)\nlemma \"total_preorder_on {1,2,3,4::nat} (of_weak_ranking [{1,3},{2},{4}])\"\n  by (simp add: of_weak_ranking_wf)\n\n\ncontext\n  fixes x :: \"'alt set\" and xs :: \"'alt set list\"\n  assumes wf: \"is_weak_ranking (x#xs)\"\nbegin\n\ninterpretation R: total_preorder_on \"\\<Union>(set (x#xs))\" \"of_weak_ranking (x#xs)\"\n  by (intro total_preorder_of_weak_ranking) (simp_all add: wf)\n\nlemma of_weak_ranking_imp_in_set:\n  assumes \"of_weak_ranking xs a b\"\n  shows   \"a \\<in> \\<Union>(set xs)\" \"b \\<in> \\<Union>(set xs)\"\n  using assms by (fastforce elim!: of_weak_ranking.cases)+\n\nlemma of_weak_ranking_Cons':\n  assumes \"a \\<in> \\<Union>(set (x#xs))\" \"b \\<in> \\<Union>(set (x#xs))\"\n  shows   \"of_weak_ranking (x#xs) a b \\<longleftrightarrow> b \\<in> x \\<or> (a \\<notin> x \\<and> of_weak_ranking xs a b)\"\nproof\n  assume \"of_weak_ranking (x # xs) a b\"\n  with wf of_weak_ranking_imp_in_set[of a b] \n    show \"(b \\<in> x \\<or>  a \\<notin> x \\<and> of_weak_ranking xs a b)\"\n    by (auto simp: is_weak_ranking_Cons of_weak_ranking_Cons)\nnext\n  assume \"b \\<in> x \\<or> a \\<notin> x \\<and> of_weak_ranking xs a b\"\n  with assms show \"of_weak_ranking (x#xs) a b\"\n    by (fastforce simp: of_weak_ranking_Cons)\nqed\n\nlemma Max_wrt_among_of_weak_ranking_Cons1:\n  assumes \"x \\<inter> A = {}\"\n  shows   \"Max_wrt_among (of_weak_ranking (x#xs)) A = Max_wrt_among (of_weak_ranking xs) A\"\nproof -\n  from wf interpret R': total_preorder_on \"\\<Union>(set xs)\" \"of_weak_ranking xs\"\n    by (intro total_preorder_of_weak_ranking) (simp_all add: is_weak_ranking_Cons)\n  from assms show ?thesis\n    by (auto simp: R.Max_wrt_among_total_preorder\n          R'.Max_wrt_among_total_preorder of_weak_ranking_Cons)\nqed\n\nlemma Max_wrt_among_of_weak_ranking_Cons2:\n  assumes \"x \\<inter> A \\<noteq> {}\"\n  shows   \"Max_wrt_among (of_weak_ranking (x#xs)) A = x \\<inter> A\"\nproof -\n  from wf interpret R': total_preorder_on \"\\<Union>(set xs)\" \"of_weak_ranking xs\"\n    by (intro total_preorder_of_weak_ranking) (simp_all add: is_weak_ranking_Cons)\n  from assms obtain a where \"a \\<in> x \\<inter> A\" by blast\n  with wf R'.not_outside(1)[of a] show ?thesis\n    by (auto simp: R.Max_wrt_among_total_preorder is_weak_ranking_Cons\n          R'.Max_wrt_among_total_preorder of_weak_ranking_Cons)\nqed\n\nlemma Max_wrt_among_of_weak_ranking_Cons:\n  \"Max_wrt_among (of_weak_ranking (x#xs)) A =\n     (if x \\<inter> A = {} then Max_wrt_among (of_weak_ranking xs) A else x \\<inter> A)\"\n  using Max_wrt_among_of_weak_ranking_Cons1 Max_wrt_among_of_weak_ranking_Cons2 by simp\n\nlemma Max_wrt_of_weak_ranking_Cons:\n  \"Max_wrt (of_weak_ranking (x#xs)) = x\"\n  using wf by (simp add: is_weak_ranking_Cons Max_wrt_def Max_wrt_among_of_weak_ranking_Cons)\n\nend\n\nlemma Max_wrt_of_weak_ranking:\n  assumes \"is_weak_ranking xs\"\n  shows   \"Max_wrt (of_weak_ranking xs) = (if xs = [] then {} else hd xs)\"\nproof (cases xs)\n  case Nil\n  hence \"of_weak_ranking xs = (\\<lambda>_ _. False)\" by (intro ext) simp_all\n  with Nil show ?thesis by (simp add: Max_wrt_def Max_wrt_among_def)\nnext\n  case (Cons x xs')\n  with assms show ?thesis by (simp add: Max_wrt_of_weak_ranking_Cons)\nqed\n\n\nlocale finite_total_preorder_on = total_preorder_on +\n  assumes finite_carrier [intro]: \"finite carrier\"\nbegin\n\nlemma finite_total_preorder_on_map:\n  assumes \"finite (f -` carrier)\"\n  shows   \"finite_total_preorder_on (f -` carrier) (map_relation f le)\"\nproof -\n  interpret R': total_preorder_on \"f -` carrier\" \"map_relation f le\"\n    using total_preorder_on_map[of f] .\n  from assms show ?thesis by unfold_locales simp\nqed\n\nfunction weak_ranking_aux :: \"'a set \\<Rightarrow> 'a set list\" where\n  \"weak_ranking_aux {} = []\"\n| \"A \\<noteq> {} \\<Longrightarrow> A \\<subseteq> carrier \\<Longrightarrow> weak_ranking_aux A =\n     Max_wrt_among le A # weak_ranking_aux (A - Max_wrt_among le A)\"\n| \"\\<not>(A \\<subseteq> carrier) \\<Longrightarrow> weak_ranking_aux A = undefined\"\nby blast simp_all\ntermination proof (relation \"Wellfounded.measure card\")\n  fix A\n  let ?B = \"Max_wrt_among le A\"\n  assume A: \"A \\<noteq> {}\" \"A \\<subseteq> carrier\"\n  moreover from A(2) have \"finite A\" by (rule finite_subset) blast\n  moreover from A have \"?B \\<noteq> {}\" \"?B \\<subseteq> A\"\n    by (intro Max_wrt_among_nonempty Max_wrt_among_subset; force)+\n  ultimately have \"card (A - ?B) < card A\"\n    by (intro psubset_card_mono) auto\n  thus \"(A - ?B, A) \\<in> measure card\" by simp\nqed simp_all\n\nlemma weak_ranking_aux_Union:\n  \"A \\<subseteq> carrier \\<Longrightarrow> \\<Union>(set (weak_ranking_aux A)) = A\"\nproof (induction A rule: weak_ranking_aux.induct [case_names empty nonempty])\n  case (nonempty A)\n  with Max_wrt_among_subset[of A] show ?case by auto\nqed simp_all\n\nlemma weak_ranking_aux_wf:\n  \"A \\<subseteq> carrier \\<Longrightarrow> is_weak_ranking (weak_ranking_aux A)\"\nproof (induction A rule: weak_ranking_aux.induct [case_names empty nonempty])\n  case (nonempty A)\n  have \"is_weak_ranking (Max_wrt_among le A # weak_ranking_aux (A - Max_wrt_among le A))\"\n    unfolding is_weak_ranking_Cons\n  proof (intro conjI)\n    from nonempty.prems nonempty.hyps show \"Max_wrt_among le A \\<noteq> {}\"\n      by (intro Max_wrt_among_nonempty) auto\n  next\n    from nonempty.prems show \"is_weak_ranking (weak_ranking_aux (A - Max_wrt_among le A))\"\n      by (intro nonempty.IH) blast\n  next\n    from nonempty.prems nonempty.hyps have \"Max_wrt_among le A \\<noteq> {}\"\n      by (intro Max_wrt_among_nonempty) auto\n    moreover from nonempty.prems \n      have \"\\<Union>(set (weak_ranking_aux (A - Max_wrt_among le A))) = A - Max_wrt_among le A\"\n      by (intro weak_ranking_aux_Union) auto\n    ultimately show \"Max_wrt_among le A \\<inter> \\<Union>(set (weak_ranking_aux (A - Max_wrt_among le A))) = {}\"\n      by blast+\n  qed\n  with nonempty.prems nonempty.hyps show ?case by simp\nqed simp_all    \n\nlemma of_weak_ranking_weak_ranking_aux':\n  assumes \"A \\<subseteq> carrier\" \"x \\<in> A\" \"y \\<in> A\"\n  shows   \"of_weak_ranking (weak_ranking_aux A) x y \\<longleftrightarrow> restrict_relation A le x y\"\nusing assms\nproof (induction A rule: weak_ranking_aux.induct [case_names empty nonempty])\n  case (nonempty A)\n  define M where \"M = Max_wrt_among le A\"\n  from nonempty.prems nonempty.hyps have M: \"M \\<subseteq> A\" unfolding M_def\n    by (intro Max_wrt_among_subset)\n  from nonempty.prems have in_MD: \"le x y\" if \"x \\<in> A\" \"y \\<in> M\" for x y\n    using that unfolding M_def Max_wrt_among_total_preorder\n    by (auto simp: Int_absorb1)\n  from nonempty.prems have in_MI: \"x \\<in> M\" if \"y \\<in> M\" \"x \\<in> A\"  \"le y x\" for x y\n    using that unfolding M_def Max_wrt_among_total_preorder\n    by (auto simp: Int_absorb1 intro: trans)\n\n  from nonempty.prems nonempty.hyps\n    have IH: \"of_weak_ranking (weak_ranking_aux (A - M)) x y = \n                restrict_relation (A - M) le x y\" if \"x \\<notin> M\" \"y \\<notin> M\"\n       using that unfolding M_def by (intro nonempty.IH) auto\n  from nonempty.prems \n    interpret R': total_preorder_on \"A - M\" \"of_weak_ranking (weak_ranking_aux (A - M))\"\n    by (intro total_preorder_of_weak_ranking weak_ranking_aux_wf weak_ranking_aux_Union) auto\n  \n  from nonempty.prems nonempty.hyps M weak_ranking_aux_Union[of A] R'.not_outside[of x y] \n    show ?case\n    by (cases \"x \\<in> M\"; cases \"y \\<in> M\")\n       (auto simp: restrict_relation_def of_weak_ranking_Cons IH M_def [symmetric]\n             intro: in_MD dest: in_MI)\nqed simp_all\n\nlemma of_weak_ranking_weak_ranking_aux:\n  \"of_weak_ranking (weak_ranking_aux carrier) = le\"\nproof (intro ext)\n  fix x y\n  have \"is_weak_ranking (weak_ranking_aux carrier)\" by (rule weak_ranking_aux_wf) simp\n  then interpret R: total_preorder_on carrier \"of_weak_ranking (weak_ranking_aux carrier)\"\n    by (intro total_preorder_of_weak_ranking weak_ranking_aux_wf weak_ranking_aux_Union)\n       (simp_all add: weak_ranking_aux_Union)\n\n  show \"of_weak_ranking (weak_ranking_aux carrier) x y = le x y\"\n  proof (cases \"x \\<in> carrier \\<and> y \\<in> carrier\")\n    case True\n    thus ?thesis\n      using of_weak_ranking_weak_ranking_aux'[of carrier x y]  by simp\n  next\n    case False\n    with R.not_outside have \"of_weak_ranking (weak_ranking_aux carrier) x y = False\"\n      by auto\n    also from not_outside False have \"\\<dots> = le x y\" by auto\n    finally show ?thesis .\n  qed\nqed\n\nlemma weak_ranking_aux_unique':\n  assumes \"\\<Union>(set As) \\<subseteq> carrier\" \"is_weak_ranking As\"\n          \"of_weak_ranking As = restrict_relation (\\<Union>(set As)) le\"\n  shows   \"As = weak_ranking_aux (\\<Union>(set As))\"\nusing assms\nproof (induction As)\n  case (Cons A As)\n  have \"restrict_relation (\\<Union>(set As)) (of_weak_ranking (A # As)) = of_weak_ranking As\"\n    by (intro restrict_relation_of_weak_ranking_Cons Cons.prems)\n  also have eq1: \"of_weak_ranking (A # As) = restrict_relation (\\<Union>(set (A # As))) le\" by fact\n  finally have eq: \"of_weak_ranking As = restrict_relation (\\<Union>(set As)) le\"\n    by (simp add: Int_absorb2)\n  with Cons.prems have eq2: \"weak_ranking_aux (\\<Union>(set As)) = As\"\n    by (intro sym [OF Cons.IH]) (auto simp: is_weak_ranking_Cons)\n\n  from eq1 have \n    \"Max_wrt_among le (\\<Union>(set (A # As))) = \n       Max_wrt_among (of_weak_ranking (A#As)) (\\<Union>(set (A#As)))\"\n    by (intro Max_wrt_among_cong) simp_all\n  also from Cons.prems have \"\\<dots> = A\"\n    by (subst Max_wrt_among_of_weak_ranking_Cons2)\n       (simp_all add: is_weak_ranking_Cons)\n  finally have Max: \"Max_wrt_among le (\\<Union>(set (A # As))) = A\" .\n\n  moreover from Cons.prems have \"A \\<noteq> {}\" by (simp add: is_weak_ranking_Cons)\n  ultimately have \"weak_ranking_aux (\\<Union>(set (A # As))) = A # weak_ranking_aux (A \\<union> \\<Union>(set As) - A)\" \n    using Cons.prems by simp\n  also from Cons.prems have \"A \\<union> \\<Union>(set As) - A = \\<Union>(set As)\"\n    by (auto simp: is_weak_ranking_Cons)\n  also from eq2 have \"weak_ranking_aux \\<dots> = As\" .\n  finally show ?case ..\nqed simp_all\n\nlemma weak_ranking_aux_unique:\n  assumes \"is_weak_ranking As\" \"of_weak_ranking As = le\"\n  shows   \"As = weak_ranking_aux carrier\"\nproof -\n  interpret R: total_preorder_on \"\\<Union>(set As)\" \"of_weak_ranking As\"\n    by (intro total_preorder_of_weak_ranking assms) simp_all\n  from assms have \"x \\<in> \\<Union>(set As) \\<longleftrightarrow> x \\<in> carrier\" for x\n    using R.not_outside not_outside R.refl[of x] refl[of x]\n    by blast\n  hence eq: \"\\<Union>(set As) = carrier\" by blast\n  from assms eq have \"As = weak_ranking_aux (\\<Union>(set As))\"\n    by (intro weak_ranking_aux_unique') simp_all\n  with eq show ?thesis by simp\nqed\n\nlemma weak_ranking_total_preorder:\n  \"is_weak_ranking (weak_ranking le)\" \"of_weak_ranking (weak_ranking le) = le\"\nproof -\n  from weak_ranking_aux_wf[of carrier] of_weak_ranking_weak_ranking_aux\n    have \"\\<exists>x. is_weak_ranking x \\<and> le = of_weak_ranking x\" by auto\n  hence \"is_weak_ranking (weak_ranking le) \\<and> le = of_weak_ranking (weak_ranking le)\"\n    unfolding weak_ranking_def by (rule someI_ex)\n  thus \"is_weak_ranking (weak_ranking le)\" \"of_weak_ranking (weak_ranking le) = le\"\n    by simp_all\nqed\n\nlemma weak_ranking_altdef:\n  \"weak_ranking le = weak_ranking_aux carrier\"\n  by (intro weak_ranking_aux_unique weak_ranking_total_preorder)\n\nlemma weak_ranking_Union: \"\\<Union>(set (weak_ranking le)) = carrier\"\n  by (simp add: weak_ranking_altdef weak_ranking_aux_Union)\n\nlemma weak_ranking_unique:\n  assumes \"is_weak_ranking As\" \"of_weak_ranking As = le\"\n  shows   \"As = weak_ranking le\"\n  using assms unfolding weak_ranking_altdef by (rule weak_ranking_aux_unique)\n\nlemma weak_ranking_permute:\n  assumes \"f permutes carrier\"\n  shows   \"weak_ranking (map_relation (inv f) le) = map ((`) f) (weak_ranking le)\"\nproof -\n  from assms have \"inv f -` carrier = carrier\"\n    by (simp add: permutes_vimage permutes_inv)\n  then interpret R: finite_total_preorder_on \"inv f -` carrier\" \"map_relation (inv f) le\"\n    by (intro finite_total_preorder_on_map) (simp_all add: finite_carrier)\n  from assms have \"is_weak_ranking (map ((`) f) (weak_ranking le))\"\n    by (intro is_weak_ranking_map_inj) \n       (simp_all add: weak_ranking_total_preorder permutes_inj_on)\n  with assms show ?thesis\n    by (intro sym[OF R.weak_ranking_unique])\n       (simp_all add: of_weak_ranking_permute weak_ranking_Union weak_ranking_total_preorder)\nqed\n\nlemma weak_ranking_index_unique:\n  assumes \"is_weak_ranking xs\" \"i < length xs\" \"j < length xs\" \"x \\<in> xs ! i\" \"x \\<in> xs ! j\"\n  shows   \"i = j\"\n  using assms unfolding is_weak_ranking_def by auto\n\nlemma weak_ranking_index_unique':\n  assumes \"is_weak_ranking xs\" \"i < length xs\" \"x \\<in> xs ! i\"\n  shows   \"i = find_index ((\\<in>) x) xs\"\n  using assms find_index_less_size_conv nth_mem\n  by (intro weak_ranking_index_unique[OF assms(1,2) _ assms(3)]\n        nth_find_index[of \"(\\<in>) x\"]) blast+\n\nlemma weak_ranking_eqclass1:\n  assumes \"A \\<in> set (weak_ranking le)\" \"x \\<in> A\" \"y \\<in> A\"\n  shows   \"le x y\"\nproof -\n  from assms obtain i where \"weak_ranking le ! i = A\" \"i < length (weak_ranking le)\" \n    by (auto simp: set_conv_nth)\n  with assms have \"of_weak_ranking (weak_ranking le) x y\"\n    by (intro of_weak_ranking.intros[of i i]) auto\n  thus ?thesis by (simp add: weak_ranking_total_preorder)\nqed\n\nlemma weak_ranking_eqclass2:\n  assumes A: \"A \\<in> set (weak_ranking le)\" \"x \\<in> A\" and le: \"le x y\" \"le y x\"\n  shows   \"y \\<in> A\"\nproof -\n  define xs where \"xs = weak_ranking le\"\n  have wf: \"is_weak_ranking xs\" by (simp add: xs_def weak_ranking_total_preorder)\n  let ?le' = \"of_weak_ranking xs\"\n  from le have le': \"?le' x y\" \"?le' y x\" by (simp_all add: weak_ranking_total_preorder xs_def)\n  from le'(1) obtain i j\n    where ij: \"j \\<le> i\" \"i < length xs\" \"j < length xs\" \"x \\<in> xs ! i\" \"y \\<in> xs ! j\"\n    by (cases rule: of_weak_ranking.cases)\n  from le'(2) obtain i' j'\n    where i'j': \"j' \\<le> i'\" \"i' < length xs\" \"j' < length xs\" \"x \\<in> xs ! j'\" \"y \\<in> xs ! i'\"\n    by (cases rule: of_weak_ranking.cases)\n  from ij i'j' have eq: \"i = j'\" \"j = i'\"\n    by (intro weak_ranking_index_unique[OF wf]; simp)+\n  moreover from A obtain k where k: \"k < length xs\" \"A = xs ! k\" \n    by (auto simp: xs_def set_conv_nth)\n  ultimately have \"k = i\" using ij i'j' A\n    by (intro weak_ranking_index_unique[OF wf, of _ _ x]) auto\n  with ij i'j' k eq show ?thesis by (auto simp: xs_def)\nqed\n\nlemma hd_weak_ranking:\n  assumes \"x \\<in> hd (weak_ranking le)\" \"y \\<in> carrier\"\n  shows   \"le y x\"\nproof -\n  from weak_ranking_Union assms obtain i\n    where \"i < length (weak_ranking le)\" \"y \\<in> weak_ranking le ! i\"\n    by (auto simp: set_conv_nth)\n  moreover from assms(2) weak_ranking_Union have \"weak_ranking le \\<noteq> []\" by auto\n  ultimately have \"of_weak_ranking (weak_ranking le) y x\" using assms(1)\n    by (intro of_weak_ranking.intros[of 0 i]) (auto simp: hd_conv_nth)\n  thus ?thesis by (simp add: weak_ranking_total_preorder)\nqed\n\nlemma last_weak_ranking:\n  assumes \"x \\<in> last (weak_ranking le)\" \"y \\<in> carrier\"\n  shows   \"le x y\"\nproof -\n  from weak_ranking_Union assms obtain i\n    where \"i < length (weak_ranking le)\" \"y \\<in> weak_ranking le ! i\"\n    by (auto simp: set_conv_nth)\n  moreover from assms(2) weak_ranking_Union have \"weak_ranking le \\<noteq> []\" by auto\n  ultimately have \"of_weak_ranking (weak_ranking le) x y\" using assms(1)\n    by (intro of_weak_ranking.intros[of i \"length (weak_ranking le) - 1\"])\n       (auto simp: last_conv_nth)\n  thus ?thesis by (simp add: weak_ranking_total_preorder)\nqed\n\ntext \\<open>\n  The index in weak ranking of a given alternative. An element with index 0 is \n  first-ranked; larger indices correspond to less-preferred alternatives.\n\\<close>\ndefinition weak_ranking_index :: \"'a \\<Rightarrow> nat\" where\n  \"weak_ranking_index x = find_index (\\<lambda>A. x \\<in> A) (weak_ranking le)\"\n\nlemma nth_weak_ranking_index:\n  assumes \"x \\<in> carrier\"\n  shows   \"weak_ranking_index x < length (weak_ranking le)\" \n          \"x \\<in> weak_ranking le ! weak_ranking_index x\"\nproof -\n  from assms weak_ranking_Union show \"weak_ranking_index x < length (weak_ranking le)\"\n     unfolding weak_ranking_index_def by (auto simp add: find_index_less_size_conv)\n  thus \"x \\<in> weak_ranking le ! weak_ranking_index x\" unfolding weak_ranking_index_def\n    by (rule nth_find_index)\nqed\n\nlemma ranking_index_eqI:\n  \"i < length (weak_ranking le) \\<Longrightarrow> x \\<in> weak_ranking le ! i \\<Longrightarrow> weak_ranking_index x = i\"\n  using weak_ranking_index_unique'[of \"weak_ranking le\" i x]\n  by (simp add: weak_ranking_index_def weak_ranking_total_preorder)\n\nlemma ranking_index_le_iff [simp]:\n  assumes \"x \\<in> carrier\" \"y \\<in> carrier\"\n  shows   \"weak_ranking_index x \\<ge> weak_ranking_index y \\<longleftrightarrow> le x y\"\nproof -\n  have \"le x y \\<longleftrightarrow> of_weak_ranking (weak_ranking le) x y\"\n    by (simp add: weak_ranking_total_preorder)\n  also have \"\\<dots> \\<longleftrightarrow> weak_ranking_index x \\<ge> weak_ranking_index y\"\n  proof\n    assume \"weak_ranking_index x \\<ge> weak_ranking_index y\"\n    thus \"of_weak_ranking (weak_ranking le) x y\"\n      by (rule of_weak_ranking.intros) (simp_all add: nth_weak_ranking_index assms)\n  next\n    assume \"of_weak_ranking (weak_ranking le) x y\"\n    then obtain i j where \n      \"i \\<le> j\" \"i < length (weak_ranking le)\" \"j < length (weak_ranking le)\"\n      \"x \\<in> weak_ranking le ! j\" \"y \\<in> weak_ranking le ! i\"\n      by (elim of_weak_ranking.cases) blast\n    with ranking_index_eqI[of i] ranking_index_eqI[of j]\n      show \"weak_ranking_index x \\<ge> weak_ranking_index y\" by simp\n  qed\n  finally show ?thesis ..\nqed\n\nend\n\nlemma weak_ranking_False [simp]: \"weak_ranking (\\<lambda>_ _. False) = []\"\nproof -\n  interpret finite_total_preorder_on \"{}\" \"\\<lambda>_ _. False\"\n    by unfold_locales simp_all\n  have \"[] = weak_ranking (\\<lambda>_ _. False)\" by (rule weak_ranking_unique) simp_all\n  thus ?thesis ..\nqed\n\nlemmas of_weak_ranking_weak_ranking = \n  finite_total_preorder_on.weak_ranking_total_preorder(2)\n\nlemma finite_total_preorder_on_iff:\n  \"finite_total_preorder_on A R \\<longleftrightarrow> total_preorder_on A R \\<and> finite A\"\n  by (simp add: finite_total_preorder_on_def finite_total_preorder_on_axioms_def)\n\nlemma finite_total_preorder_of_weak_ranking:\n  assumes \"\\<Union>(set xs) = A\" \"is_finite_weak_ranking xs\"\n  shows   \"finite_total_preorder_on A (of_weak_ranking xs)\"\nproof -\n  from assms(2) have \"is_weak_ranking xs\" by (simp add: is_finite_weak_ranking_def)\n  from assms(1) and this interpret total_preorder_on A \"of_weak_ranking xs\"\n    by (rule total_preorder_of_weak_ranking)\n  from assms(2) show ?thesis\n    by unfold_locales (simp add: assms(1)[symmetric] is_finite_weak_ranking_def)\nqed  \n\nlemma weak_ranking_of_weak_ranking:\n  assumes \"is_finite_weak_ranking xs\"\n  shows   \"weak_ranking (of_weak_ranking xs) = xs\"\nproof -\n  from assms interpret finite_total_preorder_on \"\\<Union>(set xs)\" \"of_weak_ranking xs\"\n    by (intro finite_total_preorder_of_weak_ranking) simp_all\n  from assms show ?thesis\n    by (intro sym[OF weak_ranking_unique]) (simp_all add: is_finite_weak_ranking_def)\nqed\n\n\nlemma weak_ranking_eqD:\n  assumes \"finite_total_preorder_on alts R1\"\n  assumes \"finite_total_preorder_on alts R2\"\n  assumes \"weak_ranking R1 = weak_ranking R2\"\n  shows   \"R1 = R2\"\nproof -\n  from assms have \"of_weak_ranking (weak_ranking R1) = of_weak_ranking (weak_ranking R2)\" by simp\n  with assms(1,2) show ?thesis by (simp add: of_weak_ranking_weak_ranking)\nqed\n\nlemma weak_ranking_eq_iff:\n  assumes \"finite_total_preorder_on alts R1\"\n  assumes \"finite_total_preorder_on alts R2\"\n  shows   \"weak_ranking R1 = weak_ranking R2 \\<longleftrightarrow> R1 = R2\"\n  using assms weak_ranking_eqD by auto\n\n\ndefinition preferred_alts :: \"'alt relation \\<Rightarrow> 'alt \\<Rightarrow> 'alt set\" where\n  \"preferred_alts R x = {y. y \\<succeq>[R] x}\"\n\nlemma (in preorder_on) preferred_alts_refl [simp]: \"x \\<in> carrier \\<Longrightarrow> x \\<in> preferred_alts le x\"\n  by (simp add: preferred_alts_def refl)  \n\nlemma (in preorder_on) preferred_alts_altdef:\n  \"preferred_alts le x = {y\\<in>carrier. y \\<succeq>[le] x}\"\n  by (auto simp: preferred_alts_def intro: not_outside)\n  \nlemma (in preorder_on) preferred_alts_subset: \"preferred_alts le x \\<subseteq> carrier\"\n  unfolding preferred_alts_def using not_outside by blast\n\n\nsubsection \\<open>Rankings\\<close>\n\n(* TODO: Extend theory on rankings. Can probably mostly be based on\n   existing theory on weak rankings. *)\n\ndefinition ranking :: \"'a relation \\<Rightarrow> 'a list\" where\n  \"ranking R = map the_elem (weak_ranking R)\"\n\nlocale finite_linorder_on = linorder_on +\n  assumes finite_carrier [intro]: \"finite carrier\"\nbegin\n\nsublocale finite_total_preorder_on carrier le\n  by unfold_locales (fact finite_carrier)\n\nlemma singleton_weak_ranking:\n  assumes \"A \\<in> set (weak_ranking le)\"\n  shows   \"is_singleton A\"\nproof (rule is_singletonI')\n  from assms show \"A \\<noteq> {}\"\n    using weak_ranking_total_preorder(1) is_weak_ranking_iff by auto\nnext\n  fix x y assume \"x \\<in> A\" \"y \\<in> A\"\n  with assms \n    have \"x \\<preceq>[of_weak_ranking (weak_ranking le)] y\" \"y \\<preceq>[of_weak_ranking (weak_ranking le)] x\"\n    by (auto intro!: of_weak_ranking_indifference)\n  with weak_ranking_total_preorder(2) \n    show \"x = y\" by (intro antisymmetric) simp_all\nqed\n\nlemma weak_ranking_ranking: \"weak_ranking le = map (\\<lambda>x. {x}) (ranking le)\"\n  unfolding ranking_def map_map o_def\nproof (rule sym, rule map_idI)\n  fix A assume \"A \\<in> set (weak_ranking le)\"\n  hence \"is_singleton A\" by (rule singleton_weak_ranking)\n  thus \"{the_elem A} = A\" by (auto elim: is_singletonE)\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/Randomised_Social_Choice/Order_Predicates.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711794579723, "lm_q2_score": 0.8596637559030337, "lm_q1q2_score": 0.7306894165421719}}
{"text": "(*\n  File:     Prime_Counting_Functions.thy\n  Author:   Manuel Eberl (TU M\u00fcnchen)\n\n  Definitions and basic properties of prime-counting functions like pi, theta, and psi\n*)\nsection \\<open>Prime-Counting Functions\\<close>\ntheory Prime_Counting_Functions\n  imports Prime_Number_Theorem_Library\nbegin\n\ntext \\<open>\n  We will now define the basic prime-counting functions \\<open>\\<pi>\\<close>, \\<open>\\<theta>\\<close>, and \\<open>\\<psi>\\<close>. Additionally, we \n  shall define a function M that is related to Mertens' theorems and Newman's proof of the\n  Prime Number Theorem. Most of the results in this file are not actually required to prove \n  the Prime Number Theorem, but are still nice to have.\n\\<close>\n\nsubsection \\<open>Definitions\\<close>\n\ndefinition prime_sum_upto :: \"(nat \\<Rightarrow> 'a) \\<Rightarrow> real \\<Rightarrow> 'a :: semiring_1\" where\n  \"prime_sum_upto f x = (\\<Sum>p | prime p \\<and> real p \\<le> x. f p)\"\n\nlemma prime_sum_upto_altdef1:\n  \"prime_sum_upto f x = sum_upto (\\<lambda>p. ind prime p * f p) x\"\n  unfolding sum_upto_def prime_sum_upto_def\n  by (intro sum.mono_neutral_cong_left finite_subset[OF _ finite_Nats_le_real[of x]])\n     (auto dest: prime_gt_1_nat simp: ind_def)\n\nlemma prime_sum_upto_altdef2:\n  \"prime_sum_upto f x = (\\<Sum>p | prime p \\<and> p \\<le> nat \\<lfloor>x\\<rfloor>. f p)\"\n  unfolding sum_upto_altdef prime_sum_upto_altdef1\n  by (intro sum.mono_neutral_cong_right) (auto simp: ind_def dest: prime_gt_1_nat)\n\nlemma prime_sum_upto_altdef3:\n  \"prime_sum_upto f x = (\\<Sum>p\\<leftarrow>primes_upto (nat \\<lfloor>x\\<rfloor>). f p)\"\nproof -\n  have \"(\\<Sum>p\\<leftarrow>primes_upto (nat \\<lfloor>x\\<rfloor>). f p) = (\\<Sum>p | prime p \\<and> p \\<le> nat \\<lfloor>x\\<rfloor>. f p)\"\n    by (subst sum_list_distinct_conv_sum_set) (auto simp: set_primes_upto conj_commute)\n  thus ?thesis by (simp add: prime_sum_upto_altdef2)\nqed\n\nlemma prime_sum_upto_eqI:\n  assumes \"a \\<le> b\" \"\\<And>k. k \\<in> {nat \\<lfloor>a\\<rfloor><..nat\\<lfloor>b\\<rfloor>} \\<Longrightarrow> \\<not>prime k\"\n  shows   \"prime_sum_upto f a = prime_sum_upto f b\"\nproof -\n  have *: \"k \\<le> nat \\<lfloor>a\\<rfloor>\" if \"k \\<le> nat \\<lfloor>b\\<rfloor>\" \"prime k\" for k\n    using that assms(2)[of k] by (cases \"k \\<le> nat \\<lfloor>a\\<rfloor>\") auto\n  from assms(1) have \"nat \\<lfloor>a\\<rfloor> \\<le> nat \\<lfloor>b\\<rfloor>\" by linarith\n  hence \"(\\<Sum>p | prime p \\<and> p \\<le> nat \\<lfloor>a\\<rfloor>. f p) = (\\<Sum>p | prime p \\<and> p \\<le> nat \\<lfloor>b\\<rfloor>. f p)\"\n    using assms by (intro sum.mono_neutral_left) (auto dest: *)\n  thus ?thesis by (simp add: prime_sum_upto_altdef2)\nqed\n\nlemma prime_sum_upto_eqI':\n  assumes \"a' \\<le> nat \\<lfloor>a\\<rfloor>\" \"a \\<le> b\" \"nat \\<lfloor>b\\<rfloor> \\<le> b'\" \"\\<And>k. k \\<in> {a'<..b'} \\<Longrightarrow> \\<not>prime k\"\n  shows   \"prime_sum_upto f a = prime_sum_upto f b\"\n  by (rule prime_sum_upto_eqI) (use assms in auto)\n\nlemmas eval_prime_sum_upto = prime_sum_upto_altdef3[unfolded primes_upto_sieve]\n\nlemma of_nat_prime_sum_upto: \"of_nat (prime_sum_upto f x) = prime_sum_upto (\\<lambda>p. of_nat (f p)) x\"\n  by (simp add: prime_sum_upto_def)\n\nlemma prime_sum_upto_mono:\n  assumes \"\\<And>n. n > 0 \\<Longrightarrow> f n \\<ge> (0::real)\" \"x \\<le> y\"\n  shows   \"prime_sum_upto f x \\<le> prime_sum_upto f y\"\n  using assms unfolding prime_sum_upto_altdef1 sum_upto_altdef\n  by (intro sum_mono2) (auto simp: le_nat_iff' le_floor_iff ind_def)\n\nlemma prime_sum_upto_nonneg:\n  assumes \"\\<And>n. n > 0 \\<Longrightarrow> f n \\<ge> (0 :: real)\"\n  shows   \"prime_sum_upto f x \\<ge> 0\"\n  unfolding prime_sum_upto_altdef1 sum_upto_altdef\n  by (intro sum_nonneg) (auto simp: ind_def assms)\n\nlemma prime_sum_upto_eq_0:\n  assumes \"x < 2\"\n  shows   \"prime_sum_upto f x = 0\"\nproof -\n  from assms have \"nat \\<lfloor>x\\<rfloor> = 0 \\<or> nat \\<lfloor>x\\<rfloor> = 1\" by linarith\n  thus ?thesis by (auto simp: eval_prime_sum_upto)\nqed\n\nlemma measurable_prime_sum_upto [measurable]:\n  fixes f :: \"'a \\<Rightarrow> nat \\<Rightarrow> real\"\n  assumes [measurable]: \"\\<And>y. (\\<lambda>t. f t y) \\<in> M \\<rightarrow>\\<^sub>M borel\"\n  assumes [measurable]: \"x \\<in> M \\<rightarrow>\\<^sub>M borel\"\n  shows \"(\\<lambda>t. prime_sum_upto (f t) (x t)) \\<in> M \\<rightarrow>\\<^sub>M borel\"\n  unfolding prime_sum_upto_altdef1 by measurable\n\ntext \\<open>\n  The following theorem breaks down a sum over all prime powers no greater than\n  fixed bound into a nicer form.\n\\<close>\nlemma sum_upto_primepows:\n  fixes f :: \"nat \\<Rightarrow> 'a :: comm_monoid_add\"\n  assumes \"\\<And>n. \\<not>primepow n \\<Longrightarrow> f n = 0\" \"\\<And>p i. prime p \\<Longrightarrow> i > 0 \\<Longrightarrow> f (p ^ i) = g p i\"\n  shows   \"sum_upto f x = (\\<Sum>(p, i) | prime p \\<and> i > 0 \\<and> real (p ^ i) \\<le> x. g p i)\"\nproof -\n  let ?d = aprimedivisor\n  have g: \"g (?d n) (multiplicity (?d n) n) = f n\" if \"primepow n\" for n using that \n      by (subst assms(2) [symmetric])\n         (auto simp: primepow_decompose aprimedivisor_prime_power primepow_gt_Suc_0\n               intro!: aprimedivisor_nat multiplicity_aprimedivisor_gt_0_nat)\n  have \"sum_upto f x = (\\<Sum>n | primepow n \\<and> real n \\<le> x. f n)\"\n    unfolding sum_upto_def using assms\n    by (intro sum.mono_neutral_cong_right) (auto simp: primepow_gt_0_nat)\n  also have \"\\<dots> = (\\<Sum>(p, i) | prime p \\<and> i > 0 \\<and> real (p ^ i) \\<le> x. g p i)\" (is \"_ = sum _ ?S\")\n    by (rule sum.reindex_bij_witness[of _ \"\\<lambda>(p,i). p ^ i\" \"\\<lambda>n. (?d n, multiplicity (?d n) n)\"])\n       (auto simp: aprimedivisor_prime_power primepow_decompose primepow_gt_Suc_0 g\n             simp del: of_nat_power intro!: aprimedivisor_nat multiplicity_aprimedivisor_gt_0_nat)\n  finally show ?thesis .\nqed\n\n\ndefinition primes_pi    where \"primes_pi = prime_sum_upto (\\<lambda>p. 1 :: real)\"\ndefinition primes_theta where \"primes_theta = prime_sum_upto (\\<lambda>p. ln (real p))\"\ndefinition primes_psi   where \"primes_psi = sum_upto (mangoldt :: nat \\<Rightarrow> real)\"\ndefinition primes_M     where \"primes_M = prime_sum_upto (\\<lambda>p. ln (real p) / real p)\"\n\ntext \\<open>\n  Next, we define some nice optional notation for these functions.\n\\<close>\n\nbundle prime_counting_notation\nbegin\n\nnotation primes_pi    (\"\\<pi>\")\nnotation primes_theta (\"\\<theta>\")\nnotation primes_psi   (\"\\<psi>\")\nnotation primes_M     (\"\\<MM>\")\n\nend\n\nbundle no_prime_counting_notation\nbegin\n\nno_notation primes_pi    (\"\\<pi>\")\nno_notation primes_theta (\"\\<theta>\")\nno_notation primes_psi   (\"\\<psi>\")\nno_notation primes_M     (\"\\<MM>\")\n\nend\n\n(*<*)\nunbundle prime_counting_notation\n(*>*)\n\nlemmas \\<pi>_def = primes_pi_def\nlemmas \\<theta>_def = primes_theta_def\nlemmas \\<psi>_def = primes_psi_def\n\nlemmas eval_\\<pi> = primes_pi_def[unfolded eval_prime_sum_upto]\nlemmas eval_\\<theta> = primes_theta_def[unfolded eval_prime_sum_upto]\nlemmas eval_\\<MM> = primes_M_def[unfolded eval_prime_sum_upto]\n\n\nsubsection \\<open>Basic properties\\<close>\n\ntext \\<open>\n  The proofs in this section are mostly taken from Apostol~\\cite{apostol1976analytic}.\n\\<close>\n\nlemma measurable_\\<pi> [measurable]: \"\\<pi> \\<in> borel \\<rightarrow>\\<^sub>M borel\"\n  and measurable_\\<theta> [measurable]: \"\\<theta> \\<in> borel \\<rightarrow>\\<^sub>M borel\"\n  and measurable_\\<psi> [measurable]: \"\\<psi> \\<in> borel \\<rightarrow>\\<^sub>M borel\"\n  and measurable_primes_M [measurable]: \"\\<MM> \\<in> borel \\<rightarrow>\\<^sub>M borel\"\n  unfolding primes_M_def \\<pi>_def \\<theta>_def \\<psi>_def by measurable\n\nlemma \\<pi>_eq_0 [simp]: \"x < 2 \\<Longrightarrow> \\<pi> x = 0\"\n  and \\<theta>_eq_0 [simp]: \"x < 2 \\<Longrightarrow> \\<theta> x = 0\"\n  and primes_M_eq_0 [simp]: \"x < 2 \\<Longrightarrow> \\<MM> x = 0\"\n  unfolding primes_pi_def primes_theta_def primes_M_def\n  by (rule prime_sum_upto_eq_0; simp)+\n\nlemma \\<pi>_nat_cancel [simp]: \"\\<pi> (nat x) = \\<pi> x\"\n  and \\<theta>_nat_cancel [simp]: \"\\<theta> (nat x) = \\<theta> x\"\n  and primes_M_nat_cancel [simp]: \"\\<MM> (nat x) = \\<MM> x\"\n  and \\<psi>_nat_cancel [simp]: \"\\<psi> (nat x) = \\<psi> x\"\n  and \\<pi>_floor_cancel [simp]: \"\\<pi> (of_int \\<lfloor>y\\<rfloor>) = \\<pi> y\"\n  and \\<theta>_floor_cancel [simp]: \"\\<theta> (of_int \\<lfloor>y\\<rfloor>) = \\<theta> y\"\n  and primes_M_floor_cancel [simp]: \"\\<MM> (of_int \\<lfloor>y\\<rfloor>) = \\<MM> y\"\n  and \\<psi>_floor_cancel [simp]: \"\\<psi> (of_int \\<lfloor>y\\<rfloor>) = \\<psi> y\"\n  by (simp_all add: \\<pi>_def \\<theta>_def \\<psi>_def primes_M_def prime_sum_upto_altdef2 sum_upto_altdef)\n\nlemma \\<pi>_nonneg [intro]: \"\\<pi> x \\<ge> 0\"\n  and \\<theta>_nonneg [intro]: \"\\<theta> x \\<ge> 0\"\n  and primes_M_nonneg [intro]: \"\\<MM> x \\<ge> 0\"\n  unfolding primes_pi_def primes_theta_def primes_M_def\n  by (rule prime_sum_upto_nonneg; simp)+\n\nlemma \\<pi>_mono [intro]: \"x \\<le> y \\<Longrightarrow> \\<pi> x \\<le> \\<pi> y\"\n  and \\<theta>_mono [intro]: \"x \\<le> y \\<Longrightarrow> \\<theta> x \\<le> \\<theta> y\"\n  and primes_M_mono [intro]: \"x \\<le> y \\<Longrightarrow> \\<MM> x \\<le> \\<MM> y\"\n  unfolding primes_pi_def primes_theta_def primes_M_def\n  by (rule prime_sum_upto_mono; simp)+\n\nlemma \\<pi>_pos_iff: \"\\<pi> x > 0 \\<longleftrightarrow> x \\<ge> 2\"\nproof\n  assume x: \"x \\<ge> 2\"\n  show \"\\<pi> x > 0\"\n    by (rule less_le_trans[OF _ \\<pi>_mono[OF x]]) (auto simp: eval_\\<pi>)\nnext\n  assume \"\\<pi> x > 0\"\n  hence \"\\<not>(x < 2)\" by auto\n  thus \"x \\<ge> 2\" by simp\nqed\n\nlemma \\<pi>_pos: \"x \\<ge> 2 \\<Longrightarrow> \\<pi> x > 0\"\n  by (simp add: \\<pi>_pos_iff)\n\nlemma \\<psi>_eq_0 [simp]:\n  assumes \"x < 2\"\n  shows   \"\\<psi> x = 0\"\nproof -\n  from assms have \"nat \\<lfloor>x\\<rfloor> \\<le> 1\" by linarith\n  hence \"mangoldt n = (0 :: real)\" if \"n \\<in> {0<..nat \\<lfloor>x\\<rfloor>}\" for n\n    using that by (auto simp: mangoldt_def dest!: primepow_gt_Suc_0)\n  thus ?thesis unfolding \\<psi>_def sum_upto_altdef by (intro sum.neutral) auto\nqed\n\nlemma \\<psi>_nonneg [intro]: \"\\<psi> x \\<ge> 0\"\n  unfolding \\<psi>_def sum_upto_def by (intro sum_nonneg mangoldt_nonneg)\n\nlemma \\<psi>_mono: \"x \\<le> y \\<Longrightarrow> \\<psi> x \\<le> \\<psi> y\"\n  unfolding \\<psi>_def sum_upto_def by (intro sum_mono2 mangoldt_nonneg) auto\n\n\nsubsection \\<open>The $n$-th prime number\\<close>\n\ntext \\<open>\n  Next we define the $n$-th prime number, where counting starts from 0. In traditional\n  mathematics, it seems that counting usually starts from 1, but it is more natural to\n  start from 0 in HOL and the asymptotics of the function are the same.\n\\<close>\ndefinition nth_prime :: \"nat \\<Rightarrow> nat\" where\n  \"nth_prime n = (THE p. prime p \\<and> card {q. prime q \\<and> q < p} = n)\"\n\nlemma finite_primes_less [intro]: \"finite {q::nat. prime q \\<and> q < p}\"\n  by (rule finite_subset[of _ \"{..<p}\"]) auto\n\nlemma nth_prime_unique_aux:\n  fixes p p' :: nat\n  assumes \"prime p\"  \"card {q. prime q \\<and> q < p} = n\"\n  assumes \"prime p'\" \"card {q. prime q \\<and> q < p'} = n\"\n  shows   \"p = p'\"\n  using assms\nproof (induction p p' rule: linorder_wlog)\n  case (le p p')\n  have \"finite {q. prime q \\<and> q < p'}\" by (rule finite_primes_less)\n  moreover from le have \"{q. prime q \\<and> q < p} \\<subseteq> {q. prime q \\<and> q < p'}\"\n    by auto\n  moreover from le have \"card {q. prime q \\<and> q < p} = card {q. prime q \\<and> q < p'}\"\n    by simp\n  ultimately have \"{q. prime q \\<and> q < p} = {q. prime q \\<and> q < p'}\"\n    by (rule card_subset_eq)\n  with \\<open>prime p\\<close> have \"\\<not>(p < p')\" by blast\n  with \\<open>p \\<le> p'\\<close> show \"p = p'\" by auto\nqed auto\n\nlemma \\<pi>_smallest_prime_beyond:\n  \"\\<pi> (real (smallest_prime_beyond m)) = \\<pi> (real (m - 1)) + 1\"\nproof (cases m)\n  case 0\n  have \"smallest_prime_beyond 0 = 2\"\n    by (rule smallest_prime_beyond_eq) (auto dest: prime_gt_1_nat)\n  with 0 show ?thesis by (simp add: eval_\\<pi>)\nnext\n  case (Suc n) \n  define n' where \"n' = smallest_prime_beyond (Suc n)\"\n  have \"n < n'\"\n    using smallest_prime_beyond_le[of \"Suc n\"] unfolding n'_def by linarith\n  have \"prime n'\" by (simp add: n'_def)\n  have \"n' \\<le> p\" if \"prime p\" \"p > n\" for p\n    using that smallest_prime_beyond_smallest[of p \"Suc n\"] by (auto simp: n'_def)\n  note n' = \\<open>n < n'\\<close> \\<open>prime n'\\<close> this\n\n  have \"\\<pi> (real n') = real (card {p. prime p \\<and> p \\<le> n'})\"\n    by (simp add: \\<pi>_def prime_sum_upto_def)\n  also have \"Suc n \\<le> n'\" unfolding n'_def by (rule smallest_prime_beyond_le)\n  hence \"{p. prime p \\<and> p \\<le> n'} = {p. prime p \\<and> p \\<le> n} \\<union> {p. prime p \\<and> p \\<in> {n<..n'}}\"\n    by auto\n  also have \"real (card \\<dots>) = \\<pi> (real n) + real (card {p. prime p \\<and> p \\<in> {n<..n'}})\"\n    by (subst card_Un_disjoint) (auto simp: \\<pi>_def prime_sum_upto_def)\n  also have \"{p. prime p \\<and> p \\<in> {n<..n'}} = {n'}\"\n    using n' by (auto intro: antisym)\n  finally show ?thesis using Suc by (simp add: n'_def)\nqed\n\nlemma \\<pi>_inverse_exists: \"\\<exists>n. \\<pi> (real n) = real m\"\nproof (induction m)\n  case 0\n  show ?case by (intro exI[of _ 0]) auto\nnext\n  case (Suc m)\n  from Suc.IH obtain n where n: \"\\<pi> (real n) = real m\"\n    by auto\n  hence \"\\<pi> (real (smallest_prime_beyond (Suc n))) = real (Suc m)\"\n    by (subst \\<pi>_smallest_prime_beyond) auto\n  thus ?case by blast\nqed\n\nlemma nth_prime_exists: \"\\<exists>p::nat. prime p \\<and> card {q. prime q \\<and> q < p} = n\"\nproof -\n  from \\<pi>_inverse_exists[of n] obtain m where \"\\<pi> (real m) = real n\" by blast\n  hence card: \"card {q. prime q \\<and> q \\<le> m} = n\"\n    by (auto simp: \\<pi>_def prime_sum_upto_def)\n\n  define p where \"p = smallest_prime_beyond (Suc m)\"\n  have \"m < p\" using smallest_prime_beyond_le[of \"Suc m\"] unfolding p_def by linarith\n  have \"prime p\" by (simp add: p_def)\n  have \"p \\<le> q\" if \"prime q\" \"q > m\" for q\n    using smallest_prime_beyond_smallest[of q \"Suc m\"] that by (simp add: p_def)\n  note p = \\<open>m < p\\<close> \\<open>prime p\\<close> this\n\n  have \"{q. prime q \\<and> q < p} = {q. prime q \\<and> q \\<le> m}\"\n  proof safe\n    fix q assume \"prime q\" \"q < p\"\n    hence \"\\<not>(q > m)\" using p(1,2) p(3)[of q] by auto\n    thus \"q \\<le> m\" by simp\n  qed (insert p, auto)\n  also have \"card \\<dots> = n\" by fact\n  finally show ?thesis using \\<open>prime p\\<close> by blast\nqed\n\nlemma nth_prime_exists1: \"\\<exists>!p::nat. prime p \\<and> card {q. prime q \\<and> q < p} = n\"\n  by (intro ex_ex1I nth_prime_exists) (blast intro: nth_prime_unique_aux)\n\nlemma prime_nth_prime [intro]:    \"prime (nth_prime n)\"\n  and card_less_nth_prime [simp]: \"card {q. prime q \\<and> q < nth_prime n} = n\"\n  using theI'[OF nth_prime_exists1[of n]] by (simp_all add: nth_prime_def)\n\nlemma card_le_nth_prime [simp]: \"card {q. prime q \\<and> q \\<le> nth_prime n} = Suc n\"\nproof -\n  have \"{q. prime q \\<and> q \\<le> nth_prime n} = insert (nth_prime n) {q. prime q \\<and> q < nth_prime n}\"\n    by auto\n  also have \"card \\<dots> = Suc n\" by simp\n  finally show ?thesis .\nqed\n\nlemma \\<pi>_nth_prime [simp]: \"\\<pi> (real (nth_prime n)) = real n + 1\"\n  by (simp add: \\<pi>_def prime_sum_upto_def)\n\nlemma nth_prime_eqI:\n  assumes \"prime p\" \"card {q. prime q \\<and> q < p} = n\"\n  shows   \"nth_prime n = p\"\n  unfolding nth_prime_def\n  by (rule the1_equality[OF nth_prime_exists1]) (use assms in auto)\n\nlemma nth_prime_eqI':\n  assumes \"prime p\" \"card {q. prime q \\<and> q \\<le> p} = Suc n\"\n  shows   \"nth_prime n = p\"\nproof (rule nth_prime_eqI)\n  have \"{q. prime q \\<and> q \\<le> p} = insert p {q. prime q \\<and> q < p}\"\n    using assms by auto\n  also have \"card \\<dots> = Suc (card {q. prime q \\<and> q < p})\"\n    by simp\n  finally show \"card {q. prime q \\<and> q < p} = n\" using assms by simp\nqed (use assms in auto)\n\nlemma nth_prime_eqI'':\n  assumes \"prime p\" \"\\<pi> (real p) = real n + 1\"\n  shows   \"nth_prime n = p\"\nproof (rule nth_prime_eqI')\n  have \"real (card {q. prime q \\<and> q \\<le> p}) = \\<pi> (real p)\"\n    by (simp add: \\<pi>_def prime_sum_upto_def)\n  also have \"\\<dots> = real (Suc n)\" by (simp add: assms)\n  finally show \"card {q. prime q \\<and> q \\<le> p} = Suc n\"\n    by (simp only: of_nat_eq_iff)\nqed fact+\n\nlemma nth_prime_0 [simp]: \"nth_prime 0 = 2\"\n  by (intro nth_prime_eqI) (auto dest: prime_gt_1_nat)\n\nlemma nth_prime_Suc: \"nth_prime (Suc n) = smallest_prime_beyond (Suc (nth_prime n))\"\n  by (rule nth_prime_eqI'') (simp_all add: \\<pi>_smallest_prime_beyond)\n\nlemmas nth_prime_code [code] = nth_prime_0 nth_prime_Suc\n\nlemma strict_mono_nth_prime: \"strict_mono nth_prime\"\nproof (rule strict_monoI_Suc)\n  fix n :: nat\n  have \"Suc (nth_prime n) \\<le> smallest_prime_beyond (Suc (nth_prime n))\" by simp\n  also have \"\\<dots> = nth_prime (Suc n)\" by (simp add: nth_prime_Suc)\n  finally show \"nth_prime n < nth_prime (Suc n)\" by simp\nqed\n\nlemma nth_prime_le_iff [simp]: \"nth_prime m \\<le> nth_prime n \\<longleftrightarrow> m \\<le> n\"\n  using strict_mono_less_eq[OF strict_mono_nth_prime] by blast\n\n\n\nlemma nth_prime_eq_iff [simp]: \"nth_prime m = nth_prime n \\<longleftrightarrow> m = n\"\n  using strict_mono_eq[OF strict_mono_nth_prime] by blast\n\nlemma nth_prime_ge_2: \"nth_prime n \\<ge> 2\"\n  using nth_prime_le_iff[of 0 n] by (simp del: nth_prime_le_iff)\n\nlemma nth_prime_lower_bound: \"nth_prime n \\<ge> Suc (Suc n)\"\nproof -\n  have \"n = card {q. prime q \\<and> q < nth_prime n}\"\n    by simp\n  also have \"\\<dots> \\<le> card {2..<nth_prime n}\"\n    by (intro card_mono) (auto dest: prime_gt_1_nat)\n  also have \"\\<dots> = nth_prime n - 2\" by simp\n  finally show ?thesis using nth_prime_ge_2[of n] by linarith\nqed\n\nlemma nth_prime_at_top: \"filterlim nth_prime at_top at_top\"\nproof (rule filterlim_at_top_mono)\n  show \"filterlim (\\<lambda>n::nat. n + 2) at_top at_top\" by real_asymp\nqed (auto simp: nth_prime_lower_bound)\n\nlemma \\<pi>_at_top: \"filterlim \\<pi> at_top at_top\"\n  unfolding filterlim_at_top\nproof safe\n  fix C :: real\n  define x0 where \"x0 = real (nth_prime (nat \\<lceil>max 0 C\\<rceil>))\"\n  show \"eventually (\\<lambda>x. \\<pi> x \\<ge> C) at_top\"\n    using eventually_ge_at_top\n  proof eventually_elim\n    fix x assume \"x \\<ge> x0\"\n    have \"C \\<le> real (nat \\<lceil>max 0 C\\<rceil> + 1)\" by linarith\n    also have \"real (nat \\<lceil>max 0 C\\<rceil> + 1) = \\<pi> x0\"\n      unfolding x0_def by simp\n    also have \"\\<dots> \\<le> \\<pi> x\" by (rule \\<pi>_mono) fact\n    finally show \"\\<pi> x \\<ge> C\" .\n  qed\nqed\n\ntext\\<open>\n  An unbounded, strictly increasing sequence $a_n$ partitions $[a_0; \\infty)$ into\n  segments of the form $[a_n; a_{n+1})$.\n\\<close>\nlemma strict_mono_sequence_partition:\n  assumes \"strict_mono (f :: nat \\<Rightarrow> 'a :: {linorder, no_top})\"\n  assumes \"x \\<ge> f 0\"\n  assumes \"filterlim f at_top at_top\"\n  shows   \"\\<exists>k. x \\<in> {f k..<f (Suc k)}\"\nproof -\n  define k where \"k = (LEAST k. f (Suc k) > x)\"\n  {\n    obtain n where \"x \\<le> f n\"\n      using assms by (auto simp: filterlim_at_top eventually_at_top_linorder)\n    also have \"f n < f (Suc n)\"\n      using assms by (auto simp: strict_mono_Suc_iff)\n    finally have \"\\<exists>n. f (Suc n) > x\" by auto\n  }\n  from LeastI_ex[OF this] have \"x < f (Suc k)\"\n    by (simp add: k_def)\n  moreover have \"f k \\<le> x\"\n  proof (cases k)\n    case (Suc k')\n    have \"k \\<le> k'\" if \"f (Suc k') > x\"\n      using that unfolding k_def by (rule Least_le)\n    with Suc show \"f k \\<le> x\" by (cases \"f k \\<le> x\") (auto simp: not_le)\n  qed (use assms in auto)\n  ultimately show ?thesis by auto\nqed\n\nlemma nth_prime_partition:\n  assumes \"x \\<ge> 2\"\n  shows   \"\\<exists>k. x \\<in> {nth_prime k..<nth_prime (Suc k)}\"\n  using strict_mono_sequence_partition[OF strict_mono_nth_prime, of x] assms nth_prime_at_top\n  by simp\n\nlemma nth_prime_partition':\n  assumes \"x \\<ge> 2\"\n  shows   \"\\<exists>k. x \\<in> {real (nth_prime k)..<real (nth_prime (Suc k))}\"\n  by (rule strict_mono_sequence_partition)\n     (auto simp: strict_mono_Suc_iff assms\n           intro!: filterlim_real_sequentially filterlim_compose[OF _ nth_prime_at_top])\n\nlemma between_nth_primes_imp_nonprime:\n  assumes \"n > nth_prime k\" \"n < nth_prime (Suc k)\"\n  shows   \"\\<not>prime n\"\n  using assms by (metis Suc_leI not_le nth_prime_Suc smallest_prime_beyond_smallest)\n\nlemma nth_prime_partition'':\n  assumes \"x \\<ge> (2 :: real)\"\n  shows \"x \\<in> {real (nth_prime (nat \\<lfloor>\\<pi> x\\<rfloor> - 1))..<real (nth_prime (nat \\<lfloor>\\<pi> x\\<rfloor>))}\"\nproof -\n  obtain n where n: \"x \\<in> {nth_prime n..<nth_prime (Suc n)}\"\n    using nth_prime_partition' assms by auto\n  have \"\\<pi> (nth_prime n) = \\<pi> x\"\n    unfolding \\<pi>_def using between_nth_primes_imp_nonprime n\n    by (intro prime_sum_upto_eqI) (auto simp: le_nat_iff le_floor_iff)\n  hence \"real n = \\<pi> x - 1\"\n    by simp\n  hence n_eq: \"n = nat \\<lfloor>\\<pi> x\\<rfloor> - 1\" \"Suc n = nat \\<lfloor>\\<pi> x\\<rfloor>\"\n    by linarith+\n  with n show ?thesis \n    by simp\nqed\n\n\nsubsection \\<open>Relations between different prime-counting functions\\<close>\n\ntext \\<open>\n  The \\<open>\\<psi>\\<close> function can be expressed as a sum of \\<open>\\<theta>\\<close>.\n\\<close>\nlemma \\<psi>_altdef:\n  assumes \"x > 0\"\n  shows   \"\\<psi> x = sum_upto (\\<lambda>m. prime_sum_upto ln (root m x)) (log 2 x)\" (is \"_ = ?rhs\")\nproof -\n  have finite: \"finite {p. prime p \\<and> real p \\<le> y}\" for y\n    by (rule finite_subset[of _ \"{..nat \\<lfloor>y\\<rfloor>}\"]) (auto simp: le_nat_iff' le_floor_iff)\n  define S where \"S = (SIGMA i:{i. 0 < i \\<and> real i \\<le> log 2 x}. {p. prime p \\<and> real p \\<le> root i x})\"\n  have \"\\<psi> x = (\\<Sum>(p, i) | prime p \\<and> 0 < i \\<and> real (p ^ i) \\<le> x. ln (real p))\"  unfolding \\<psi>_def\n    by (subst sum_upto_primepows[where g = \"\\<lambda>p i. ln (real p)\"])\n       (auto simp: case_prod_unfold mangoldt_non_primepow)\n  also have \"\\<dots> = (\\<Sum>(i, p) | prime p \\<and> 0 < i \\<and> real (p ^ i) \\<le> x. ln (real p))\"\n    by (intro sum.reindex_bij_witness[of _ \"\\<lambda>(x,y). (y,x)\" \"\\<lambda>(x,y). (y,x)\"]) auto\n  also have \"{(i, p). prime p \\<and> 0 < i \\<and> real (p ^ i) \\<le> x} = S\"\n    unfolding S_def\n  proof safe\n    fix i p :: nat assume ip: \"i > 0\" \"real i \\<le> log 2 x\" \"prime p\" \"real p \\<le> root i x\"\n    hence \"real (p ^ i) \\<le> root i x ^ i\" unfolding of_nat_power by (intro power_mono) auto\n    with ip assms show \"real (p ^ i) \\<le> x\" by simp\n  next\n    fix i p assume ip: \"prime p\" \"i > 0\" \"real (p ^ i) \\<le> x\"\n    from ip have \"2 ^ i \\<le> p ^ i\" by (intro power_mono) (auto dest: prime_gt_1_nat)\n    also have \"\\<dots> \\<le> x\" using ip by simp\n    finally show \"real i \\<le> log 2 x\"\n      using assms by (simp add: le_log_iff powr_realpow)\n    have \"root i (real p ^ i) \\<le> root i x\" using ip assms\n      by (subst real_root_le_iff) auto\n    also have \"root i (real p ^ i) = real p\"\n      using assms ip by (subst real_root_pos2) auto\n    finally show \"real p \\<le> root i x\" .\n  qed\n  also have \"(\\<Sum>(i,p)\\<in>S. ln p) = sum_upto (\\<lambda>m. prime_sum_upto ln (root m x)) (log 2 x)\"\n    unfolding sum_upto_def prime_sum_upto_def S_def using finite by (subst sum.Sigma) auto\n  finally show ?thesis .\nqed\n\nlemma \\<psi>_conv_\\<theta>_sum: \"x > 0 \\<Longrightarrow> \\<psi> x = sum_upto (\\<lambda>m. \\<theta> (root m x)) (log 2 x)\"\n  by (simp add: \\<psi>_altdef \\<theta>_def)\n\nlemma \\<psi>_minus_\\<theta>:\n  assumes x: \"x \\<ge> 2\"\n  shows   \"\\<psi> x - \\<theta> x = (\\<Sum>i | 2 \\<le> i \\<and> real i \\<le> log 2 x. \\<theta> (root i x))\"\nproof -\n  have finite: \"finite {i. 2 \\<le> i \\<and> real i \\<le> log 2 x}\"\n    by (rule finite_subset[of _ \"{2..nat \\<lfloor>log 2 x\\<rfloor>}\"]) (auto simp: le_nat_iff' le_floor_iff)\n  have \"\\<psi> x = (\\<Sum>i | 0 < i \\<and> real i \\<le> log 2 x. \\<theta> (root i x))\" using x\n    by (simp add: \\<psi>_conv_\\<theta>_sum sum_upto_def)\n  also have \"{i. 0 < i \\<and> real i \\<le> log 2 x} = insert 1 {i. 2 \\<le> i \\<and> real i \\<le> log 2 x}\" using x\n    by (auto simp: le_log_iff)\n  also have \"(\\<Sum>i\\<in>\\<dots>. \\<theta> (root i x)) - \\<theta> x =\n               (\\<Sum>i | 2 \\<le> i \\<and> real i \\<le> log 2 x. \\<theta> (root i x))\" using finite\n    by (subst sum.insert) auto\n  finally show ?thesis .\nqed\n\ntext \\<open>\n  The following theorems use summation by parts to relate different prime-counting functions to\n  one another with an integral as a remainder term.\n\\<close>\nlemma \\<theta>_conv_\\<pi>_integral:\n  assumes \"x \\<ge> 2\"\n  shows   \"((\\<lambda>t. \\<pi> t / t) has_integral (\\<pi> x * ln x - \\<theta> x)) {2..x}\"\nproof (cases \"x = 2\")\n  case False\n  note [intro] = finite_vimage_real_of_nat_greaterThanAtMost\n  from False and assms have x: \"x > 2\" by simp\n  have \"((\\<lambda>t. sum_upto (ind prime) t * (1 / t)) has_integral\n          sum_upto (ind prime) x * ln x - sum_upto (ind prime) 2 * ln 2 -\n          (\\<Sum>n\\<in>real -` {2<..x}. ind prime n * ln (real n))) {2..x}\" using x\n    by (intro partial_summation_strong[where X = \"{}\"])\n       (auto intro!: continuous_intros derivative_eq_intros\n             simp flip: has_field_derivative_iff_has_vector_derivative)\n  hence \"((\\<lambda>t. \\<pi> t / t) has_integral (\\<pi> x * ln x -\n           (\\<pi> 2 * ln 2 + (\\<Sum>n\\<in>real -` {2<..x}. ind prime n * ln n)))) {2..x}\"\n    by (simp add: \\<pi>_def prime_sum_upto_altdef1 algebra_simps)\n  also have \"\\<pi> 2 * ln 2 + (\\<Sum>n\\<in>real -` {2<..x}. ind prime n * ln n) =\n               (\\<Sum>n\\<in>insert 2 (real -` {2<..x}). ind prime n * ln n)\"\n    by (subst sum.insert) (auto simp: eval_\\<pi>)\n  also have \"\\<dots> = \\<theta> x\" unfolding \\<theta>_def prime_sum_upto_def using x\n    by (intro sum.mono_neutral_cong_right) (auto simp: ind_def dest: prime_gt_1_nat)\n  finally show ?thesis .\nqed (auto simp: has_integral_refl eval_\\<pi> eval_\\<theta>)\n\nlemma \\<pi>_conv_\\<theta>_integral:\n  assumes \"x \\<ge> 2\"\n  shows   \"((\\<lambda>t. \\<theta> t / (t * ln t ^ 2)) has_integral (\\<pi> x - \\<theta> x / ln x)) {2..x}\"\nproof (cases \"x = 2\")\n  case False\n  define b where \"b = (\\<lambda>p. ind prime p * ln (real p))\"\n  note [intro] = finite_vimage_real_of_nat_greaterThanAtMost\n  from False and assms have x: \"x > 2\" by simp\n  have \"((\\<lambda>t. -(sum_upto b t * (-1 / (t * (ln t)\\<^sup>2)))) has_integral\n          -(sum_upto b x * (1 / ln x) - sum_upto b 2 * (1 / ln 2) -\n              (\\<Sum>n\\<in>real -` {2<..x}. b n * (1 / ln (real n))))) {2..x}\" using x\n    by (intro has_integral_neg partial_summation_strong[where X = \"{}\"])\n       (auto intro!: continuous_intros derivative_eq_intros\n             simp flip: has_field_derivative_iff_has_vector_derivative simp add: power2_eq_square)\n  also have \"sum_upto b = \\<theta>\"\n    by (simp add: \\<theta>_def b_def prime_sum_upto_altdef1 fun_eq_iff)\n  also have \"\\<theta> x * (1 / ln x) - \\<theta> 2 * (1 / ln 2) - \n                   (\\<Sum>n\\<in>real -` {2<..x}. b n * (1 / ln (real n))) =\n               \\<theta> x * (1 / ln x) - (\\<Sum>n\\<in>insert 2 (real -` {2<..x}). b n * (1 / ln (real n)))\"\n    by (subst sum.insert) (auto simp: b_def eval_\\<theta>)\n  also have \"(\\<Sum>n\\<in>insert 2 (real -` {2<..x}). b n * (1 / ln (real n))) = \\<pi> x\" using x\n    unfolding \\<pi>_def prime_sum_upto_altdef1 sum_upto_def\n  proof (intro sum.mono_neutral_cong_left ballI, goal_cases)\n    case (3 p)\n    hence \"p = 1\" by auto\n    thus ?case by auto\n  qed (auto simp: b_def)\n  finally show ?thesis by simp\nqed (auto simp: has_integral_refl eval_\\<pi> eval_\\<theta>)\n\nlemma integrable_weighted_\\<theta>:\n  assumes \"2 \\<le> a\" \"a \\<le> x\"\n  shows   \"((\\<lambda>t. \\<theta> t / (t * ln t ^ 2)) integrable_on {a..x})\"\nproof (cases \"a < x\")\n  case True\n  hence \"((\\<lambda>t. \\<theta> t * (1 / (t * ln t ^ 2))) integrable_on {a..x})\" using assms\n    unfolding \\<theta>_def prime_sum_upto_altdef1\n    by (intro partial_summation_integrable_strong[where X = \"{}\" and f = \"\\<lambda>x. -1 / ln x\"])\n       (auto simp flip: has_field_derivative_iff_has_vector_derivative\n             intro!: derivative_eq_intros continuous_intros simp: power2_eq_square field_simps)\n  thus ?thesis by simp\nqed (insert has_integral_refl[of _ a] assms, auto simp: has_integral_iff)\n\nlemma \\<theta>_conv_\\<MM>_integral:\n  assumes \"x \\<ge> 2\"\n  shows  \"(\\<MM> has_integral (\\<MM> x * x - \\<theta> x)) {2..x}\"\nproof (cases \"x = 2\")\n  case False\n  with assms have x: \"x > 2\" by simp\n  define b :: \"nat \\<Rightarrow> real\" where \"b = (\\<lambda>p. ind prime p * ln p / p)\"\n  note [intro] = finite_vimage_real_of_nat_greaterThanAtMost\n  have prime_le_2: \"p = 2\" if \"p \\<le> 2\" \"prime p\" for p :: nat\n    using that by (auto simp: prime_nat_iff)\n\n  have \"((\\<lambda>t. sum_upto b t * 1) has_integral sum_upto b x * x - sum_upto b 2 * 2 -\n          (\\<Sum>n\\<in>real -` {2<..x}. b n * real n)) {2..x}\" using x\n    by (intro partial_summation_strong[of \"{}\"])\n       (auto simp flip: has_field_derivative_iff_has_vector_derivative\n             intro!: derivative_eq_intros continuous_intros)\n  also have \"sum_upto b = \\<MM>\"\n    by (simp add: fun_eq_iff primes_M_def b_def prime_sum_upto_altdef1)\n  also have \"\\<MM> x * x - \\<MM> 2 * 2 - (\\<Sum>n\\<in>real -` {2<..x}. b n * real n) =\n               \\<MM> x * x - (\\<Sum>n\\<in>insert 2 (real -` {2<..x}). b n * real n)\"\n    by (subst sum.insert) (auto simp: eval_\\<MM> b_def)\n  also have \"(\\<Sum>n\\<in>insert 2 (real -` {2<..x}). b n * real n) = \\<theta> x\"\n    unfolding \\<theta>_def prime_sum_upto_def using x\n    by (intro sum.mono_neutral_cong_right) (auto simp: b_def ind_def not_less prime_le_2)\n  finally show ?thesis by simp\nqed (auto simp: eval_\\<theta> eval_\\<MM>)\n\nlemma \\<MM>_conv_\\<theta>_integral:\n  assumes \"x \\<ge> 2\"\n  shows  \"((\\<lambda>t. \\<theta> t / t\\<^sup>2) has_integral (\\<MM> x - \\<theta> x / x)) {2..x}\"\nproof (cases \"x = 2\")\n  case False\n  with assms have x: \"x > 2\" by simp\n  define b :: \"nat \\<Rightarrow> real\" where \"b = (\\<lambda>p. ind prime p * ln p)\"\n  note [intro] = finite_vimage_real_of_nat_greaterThanAtMost\n  have prime_le_2: \"p = 2\" if \"p \\<le> 2\" \"prime p\" for p :: nat\n    using that by (auto simp: prime_nat_iff)\n\n  have \"((\\<lambda>t. sum_upto b t * (1 / t^2)) has_integral\n          sum_upto b x * (-1 / x) - sum_upto b 2 * (-1 / 2) -\n          (\\<Sum>n\\<in>real -` {2<..x}. b n * (-1 / real n))) {2..x}\" using x\n    by (intro partial_summation_strong[of \"{}\"])\n       (auto simp flip: has_field_derivative_iff_has_vector_derivative simp: power2_eq_square\n             intro!: derivative_eq_intros continuous_intros)\n  also have \"sum_upto b = \\<theta>\"\n    by (simp add: fun_eq_iff \\<theta>_def b_def prime_sum_upto_altdef1)\n  also have \"\\<theta> x * (-1 / x) - \\<theta> 2 * (-1 / 2) - (\\<Sum>n\\<in>real -` {2<..x}. b n * (-1 / real n)) =\n               -(\\<theta> x / x - (\\<Sum>n\\<in>insert 2 (real -` {2<..x}). b n / real n))\"\n    by (subst sum.insert) (auto simp: eval_\\<theta> b_def sum_negf)\n  also have \"(\\<Sum>n\\<in>insert 2 (real -` {2<..x}). b n / real n) = \\<MM> x\"\n    unfolding primes_M_def prime_sum_upto_def using x\n    by (intro sum.mono_neutral_cong_right) (auto simp: b_def ind_def not_less prime_le_2)\n  finally show ?thesis by simp\nqed (auto simp: eval_\\<theta> eval_\\<MM>)\n\nlemma integrable_primes_M: \"\\<MM> integrable_on {x..y}\" if \"2 \\<le> x\" for x y :: real\nproof -\n  have \"(\\<lambda>x. \\<MM> x * 1) integrable_on {x..y}\" if \"2 \\<le> x\" \"x < y\" for x y :: real\n    unfolding primes_M_def prime_sum_upto_altdef1 using that\n    by (intro partial_summation_integrable_strong[where X = \"{}\" and f = \"\\<lambda>x. x\"])\n       (auto simp flip: has_field_derivative_iff_has_vector_derivative\n             intro!: derivative_eq_intros continuous_intros)\n  thus ?thesis using that has_integral_refl(2)[of \\<MM> x] by (cases x y rule: linorder_cases) auto\nqed\n\n\nsubsection \\<open>Bounds\\<close>\n\nlemma \\<theta>_upper_bound_coarse:\n  assumes \"x \\<ge> 1\"\n  shows   \"\\<theta> x \\<le> x * ln x\"\nproof -\n  have \"\\<theta> x \\<le> sum_upto (\\<lambda>_. ln x) x\" unfolding \\<theta>_def prime_sum_upto_altdef1 sum_upto_def\n    by (intro sum_mono) (auto simp: ind_def)\n  also have \"\\<dots> \\<le> real_of_int \\<lfloor>x\\<rfloor> * ln x\" using assms\n    by (simp add: sum_upto_altdef)\n  also have \"\\<dots> \\<le> x * ln x\" using assms by (intro mult_right_mono) auto\n  finally show ?thesis .\nqed\n\nlemma \\<theta>_le_\\<psi>: \"\\<theta> x \\<le> \\<psi> x\"\nproof (cases \"x \\<ge> 2\")\n  case False\n  hence \"nat \\<lfloor>x\\<rfloor> = 0 \\<or> nat \\<lfloor>x\\<rfloor> = 1\" by linarith\n  thus ?thesis by (auto simp: eval_\\<theta>)\nnext\n  case True\n  hence \"\\<psi> x - \\<theta> x = (\\<Sum>i | 2 \\<le> i \\<and> real i \\<le> log 2 x. \\<theta> (root i x))\"\n    by (rule \\<psi>_minus_\\<theta>)\n  also have \"\\<dots> \\<ge> 0\" by (intro sum_nonneg) auto\n  finally show ?thesis by simp\nqed\n\nlemma \\<pi>_upper_bound_coarse:\n  assumes \"x \\<ge> 0\"\n  shows   \"\\<pi> x \\<le> x / 3 + 2\"\nproof -\n  have \"{p. prime p \\<and> p \\<le> nat \\<lfloor>x\\<rfloor>} \\<subseteq> {2, 3} \\<union> {p. p \\<noteq> 1 \\<and> odd p \\<and> \\<not>3 dvd p \\<and> p \\<le> nat \\<lfloor>x\\<rfloor>}\"\n    using primes_dvd_imp_eq[of \"2 :: nat\"] primes_dvd_imp_eq[of \"3 :: nat\"] by auto\n  also have \"\\<dots> \\<subseteq> {2, 3} \\<union> ((\\<lambda>k. 6*k+1) ` {0<..<nat \\<lfloor>(x+5)/6\\<rfloor>} \\<union> (\\<lambda>k. 6*k+5) ` {..<nat \\<lfloor>(x+1)/6\\<rfloor>})\"\n    (is \"_ \\<union> ?lhs \\<subseteq> _ \\<union> ?rhs\")\n  proof (intro Un_mono subsetI)\n    fix p :: nat assume \"p \\<in> ?lhs\"\n    hence p: \"p \\<noteq> 1\" \"odd p\" \"\\<not>3 dvd p\" \"p \\<le> nat \\<lfloor>x\\<rfloor>\" by auto\n    from p (1-3) have \"(\\<exists>k. k > 0 \\<and> p = 6 * k + 1 \\<or> p = 6 * k + 5)\" by presburger\n    then obtain k where \"k > 0 \\<and> p = 6 * k + 1 \\<or> p = 6 * k + 5\" by blast\n    hence \"p = 6 * k + 1 \\<and> k > 0 \\<and> k < nat \\<lfloor>(x+5)/6\\<rfloor> \\<or> p = 6*k+5 \\<and> k < nat \\<lfloor>(x+1)/6\\<rfloor>\"\n      unfolding add_divide_distrib using p(4) by linarith\n    thus \"p \\<in> ?rhs\" by auto\n  qed\n  finally have subset: \"{p. prime p \\<and> p \\<le> nat \\<lfloor>x\\<rfloor>} \\<subseteq> \\<dots>\" (is \"_ \\<subseteq> ?A\") .\n\n  have \"\\<pi> x = real (card {p. prime p \\<and> p \\<le> nat \\<lfloor>x\\<rfloor>})\"\n    by (simp add: \\<pi>_def prime_sum_upto_altdef2)\n  also have \"card {p. prime p \\<and> p \\<le> nat \\<lfloor>x\\<rfloor>} \\<le> card ?A\"\n    by (intro card_mono subset) auto\n  also have \"\\<dots> \\<le> 2 + (nat \\<lfloor>(x+5)/6\\<rfloor> - 1 + nat \\<lfloor>(x+1)/6\\<rfloor>)\"\n    by (intro order.trans[OF card_Un_le] add_mono order.trans[OF card_image_le]) auto\n  also have \"\\<dots> \\<le> x / 3 + 2\"\n    using assms unfolding add_divide_distrib by (cases \"x \\<ge> 1\", linarith, simp)\n  finally show ?thesis by simp\nqed\n\nlemma le_numeral_iff: \"m \\<le> numeral n \\<longleftrightarrow> m = numeral n \\<or> m \\<le> pred_numeral n\"\n  using numeral_eq_Suc by presburger\n\ntext \\<open>\n  The following nice proof for the upper bound $\\theta(x) \\leq \\ln 4 \\cdot x$ is taken\n  from Otto Forster's lecture notes on Analytic Number Theory~\\cite{forsteranalytic}.\n\\<close>\nlemma prod_primes_upto_less:\n  defines \"F \\<equiv> (\\<lambda>n. (\\<Prod>{p::nat. prime p \\<and> p \\<le> n}))\"\n  shows   \"n > 0 \\<Longrightarrow> F n < 4 ^ n\"\nproof (induction n rule: less_induct)\n  case (less n)\n  have \"n = 0 \\<or> n = 1 \\<or> n = 2 \\<or> n = 3 \\<or> even n \\<and> n \\<ge> 4 \\<or> odd n \\<and> n \\<ge> 4\"\n    by presburger\n  then consider \"n = 0\" | \"n = 1\" | \"n = 2\" | \"n = 3\" | \"even n\" \"n \\<ge> 4\" | \"odd n\" \"n \\<ge> 4\"\n    by metis\n  thus ?case\n  proof cases\n    assume [simp]: \"n = 1\"\n    have *: \"{p. prime p \\<and> p \\<le> Suc 0} = {}\" by (auto dest: prime_gt_1_nat)\n    show ?thesis by (simp add: F_def *)\n  next\n    assume [simp]: \"n = 2\"\n    have *: \"{p. prime p \\<and> p \\<le> 2} = {2 :: nat}\"\n      by (auto simp: le_numeral_iff dest: prime_gt_1_nat)\n    thus ?thesis by (simp add: F_def *)\n  next\n    assume [simp]: \"n = 3\"\n    have *: \"{p. prime p \\<and> p \\<le> 3} = {2, 3 :: nat}\"\n      by (auto simp: le_numeral_iff dest: prime_gt_1_nat)\n    thus ?thesis by (simp add: F_def *)\n  next\n    assume n: \"even n\" \"n \\<ge> 4\"\n    from n have \"F (n - 1) < 4 ^ (n - 1)\" by (intro less.IH) auto\n    also have \"prime p \\<and> p \\<le> n \\<longleftrightarrow> prime p \\<and> p \\<le> n - 1\" for p\n      using n prime_odd_nat[of n] by (cases \"p = n\") auto\n    hence \"F (n - 1) = F n\" by (simp add: F_def)\n    also have \"4 ^ (n - 1) \\<le> (4 ^ n :: nat)\" by (intro power_increasing) auto\n    finally show ?case .\n  next\n    assume n: \"odd n\" \"n \\<ge> 4\"\n    then obtain k where k_eq: \"n = Suc (2 * k)\" by (auto elim: oddE)\n    from n have k: \"k \\<ge> 2\" unfolding k_eq by presburger\n    have prime_dvd: \"p dvd (n choose k)\" if p: \"prime p\" \"p \\<in> {k+1<..n}\" for p\n    proof -\n      from p k n have \"p dvd pochhammer (k + 2) k\"\n        unfolding pochhammer_prod\n        by (subst prime_dvd_prod_iff)\n           (auto intro!: bexI[of _ \"p - k - 2\"] simp: k_eq numeral_2_eq_2 Suc_diff_Suc)\n      also have \"pochhammer (real (k + 2)) k = real ((n choose k) * fact k)\"\n        by (simp add: binomial_gbinomial gbinomial_pochhammer' k_eq field_simps)\n      hence \"pochhammer (k + 2) k = (n choose k) * fact k\"\n        unfolding pochhammer_of_nat of_nat_eq_iff .\n      finally show \"p dvd (n choose k)\" using p\n        by (auto simp: prime_dvd_fact_iff prime_dvd_mult_nat)\n    qed\n\n    have \"\\<Prod>{p. prime p \\<and> p \\<in> {k+1<..n}} dvd (n choose k)\"\n    proof (rule multiplicity_le_imp_dvd, goal_cases)\n      case (2 p)\n      thus ?case\n      proof (cases \"p \\<in> {k+1<..n}\")\n        case False\n        hence \"multiplicity p (\\<Prod>{p. prime p \\<and> p \\<in> {k+1<..n}}) = 0\" using 2\n          by (subst prime_elem_multiplicity_prod_distrib) (auto simp: prime_multiplicity_other)\n        thus ?thesis by auto\n      next\n        case True\n        hence \"multiplicity p (\\<Prod>{p. prime p \\<and> p \\<in> {k+1<..n}}) =\n                 sum (multiplicity p) {p. prime p \\<and> Suc k < p \\<and> p \\<le> n}\" using 2\n          by (subst prime_elem_multiplicity_prod_distrib) auto\n        also have \"\\<dots> = sum (multiplicity p) {p}\" using True 2\n        proof (intro sum.mono_neutral_right ballI)\n          fix q :: nat assume \"q \\<in> {p. prime p \\<and> Suc k < p \\<and> p \\<le> n} - {p}\"\n          thus \"multiplicity p q = 0\" using 2\n            by (cases \"p = q\") (auto simp: prime_multiplicity_other)\n        qed auto\n        also have \"\\<dots> = 1\" using 2 by simp\n        also have \"1 \\<le> multiplicity p (n choose k)\"\n          using prime_dvd[of p] 2 True by (intro multiplicity_geI) auto\n        finally show ?thesis .\n      qed\n    qed auto\n    hence \"\\<Prod>{p. prime p \\<and> p \\<in> {k+1<..n}} \\<le> (n choose k)\"\n      by (intro dvd_imp_le) (auto simp: k_eq)\n    also have \"\\<dots> = 1 / 2 * (\\<Sum>i\\<in>{k, Suc k}. n choose i)\"\n      using central_binomial_odd[of n] by (simp add: k_eq)\n    also have \"(\\<Sum>i\\<in>{k, Suc k}. n choose i) < (\\<Sum>i\\<in>{0, k, Suc k}. n choose i)\"\n      using k by simp\n    also have \"\\<dots> \\<le> (\\<Sum>i\\<le>n. n choose i)\"\n      by (intro sum_mono2) (auto simp: k_eq)\n    also have \"\\<dots> = (1 + 1) ^ n\"\n      using binomial[of 1 1 n] by simp\n    also have \"1 / 2 * \\<dots> = real (4 ^ k)\"\n      by (simp add: k_eq power_mult)\n    finally have less: \"(\\<Prod>{p. prime p \\<and> p \\<in> {k + 1<..n}}) < 4 ^ k\"\n      unfolding of_nat_less_iff by simp\n\n    have \"F n = F (Suc k) * (\\<Prod>{p. prime p \\<and> p \\<in> {k+1<..n}})\" unfolding F_def\n      by (subst prod.union_disjoint [symmetric]) (auto intro!: prod.cong simp: k_eq)\n    also have \"\\<dots> < 4 ^ Suc k * 4 ^ k\" using n\n      by (intro mult_strict_mono less less.IH) (auto simp: k_eq)\n    also have \"\\<dots> = 4 ^ (Suc k + k)\"\n      by (simp add: power_add)\n    also have \"Suc k + k = n\" by (simp add: k_eq)\n    finally show ?case .\n  qed (insert less.prems, auto)\nqed\n\nlemma \\<theta>_upper_bound:\n  assumes x: \"x \\<ge> 1\"\n  shows   \"\\<theta> x < ln 4 * x\"\nproof -\n  have \"4 powr (\\<theta> x / ln 4) = (\\<Prod>p | prime p \\<and> p \\<le> nat \\<lfloor>x\\<rfloor>. 4 powr (log 4 (real p)))\"\n    by (simp add: \\<theta>_def powr_sum prime_sum_upto_altdef2 sum_divide_distrib log_def)\n  also have \"\\<dots> = (\\<Prod>p | prime p \\<and> p \\<le> nat \\<lfloor>x\\<rfloor>. real p)\"\n    by (intro prod.cong) (auto dest: prime_gt_1_nat)\n  also have \"\\<dots> = real (\\<Prod>p | prime p \\<and> p \\<le> nat \\<lfloor>x\\<rfloor>. p)\"\n    by simp\n  also have \"(\\<Prod>p | prime p \\<and> p \\<le> nat \\<lfloor>x\\<rfloor>. p) < 4 ^ nat \\<lfloor>x\\<rfloor>\"\n    using x by (intro prod_primes_upto_less) auto\n  also have \"\\<dots> = 4 powr real (nat \\<lfloor>x\\<rfloor>)\"\n    using x by (subst powr_realpow) auto\n  also have \"\\<dots> \\<le> 4 powr x\"\n    using x by (intro powr_mono) auto\n  finally have \"4 powr (\\<theta> x / ln 4) < 4 powr x\"\n    by simp\n  thus \"\\<theta> x < ln 4 * x\"\n    by (subst (asm) powr_less_cancel_iff) (auto simp: field_simps)\nqed\n\nlemma \\<theta>_bigo: \"\\<theta> \\<in> O(\\<lambda>x. x)\"\n  by (intro le_imp_bigo_real[of \"ln 4\"] eventually_mono[OF eventually_ge_at_top[of 1]]\n            less_imp_le[OF \\<theta>_upper_bound]) auto\n\nlemma \\<psi>_minus_\\<theta>_bound:\n  assumes x: \"x \\<ge> 2\"\n  shows   \"\\<psi> x - \\<theta> x \\<le> 2 * ln x * sqrt x\"\nproof -\n  have \"\\<psi> x - \\<theta> x = (\\<Sum>i | 2 \\<le> i \\<and> real i \\<le> log 2 x. \\<theta> (root i x))\" using x\n    by (rule \\<psi>_minus_\\<theta>)\n  also have \"\\<dots> \\<le> (\\<Sum>i | 2 \\<le> i \\<and> real i \\<le> log 2 x. ln 4 * root i x)\"\n    using x by (intro sum_mono less_imp_le[OF \\<theta>_upper_bound]) auto\n  also have \"\\<dots> \\<le> (\\<Sum>i | 2 \\<le> i \\<and> real i \\<le> log 2 x. ln 4 * root 2 x)\" using x\n    by (intro sum_mono mult_mono) (auto simp: le_log_iff powr_realpow intro!: real_root_decreasing)\n  also have \"\\<dots> = card {i. 2 \\<le> i \\<and> real i \\<le> log 2 x} * ln 4 * sqrt x\"\n    by (simp add: sqrt_def)\n  also have \"{i. 2 \\<le> i \\<and> real i \\<le> log 2 x} = {2..nat \\<lfloor>log 2 x\\<rfloor>}\"\n    by (auto simp: le_nat_iff' le_floor_iff)\n  also have \"log 2 x \\<ge> 1\" using x by (simp add: le_log_iff)\n  hence \"real (nat \\<lfloor>log 2 x\\<rfloor> - 1) \\<le> log 2 x\" using x by linarith\n  hence \"card {2..nat \\<lfloor>log 2 x\\<rfloor>} \\<le> log 2 x\" by simp\n  also have \"ln (2 * 2 :: real) = 2 * ln 2\" by (subst ln_mult) auto\n  hence \"log 2 x * ln 4 * sqrt x = 2 * ln x * sqrt x\" using x\n    by (simp add: ln_sqrt log_def power2_eq_square field_simps)\n  finally show ?thesis using x by (simp add: mult_right_mono)\nqed\n\nlemma \\<psi>_minus_\\<theta>_bigo: \"(\\<lambda>x. \\<psi> x - \\<theta> x) \\<in> O(\\<lambda>x. ln x * sqrt x)\"\nproof (intro bigoI[of _ \"2\"] eventually_mono[OF eventually_ge_at_top[of 2]])\n  fix x :: real assume \"x \\<ge> 2\"\n  thus \"norm (\\<psi> x - \\<theta> x) \\<le> 2 * norm (ln x * sqrt x)\"\n    using \\<psi>_minus_\\<theta>_bound[of x] \\<theta>_le_\\<psi>[of x] by simp\nqed\n\nlemma \\<psi>_bigo: \"\\<psi> \\<in> O(\\<lambda>x. x)\"\nproof -\n  have \"(\\<lambda>x. \\<psi> x - \\<theta> x) \\<in> O(\\<lambda>x. ln x * sqrt x)\"\n    by (rule \\<psi>_minus_\\<theta>_bigo)\n  also have \"(\\<lambda>x. ln x * sqrt x) \\<in> O(\\<lambda>x. x)\"\n    by real_asymp\n  finally have \"(\\<lambda>x. \\<psi> x - \\<theta> x + \\<theta> x) \\<in> O(\\<lambda>x. x)\"\n    by (rule sum_in_bigo) (fact \\<theta>_bigo)\n  thus ?thesis by simp\nqed\n\ntext \\<open>\n  We shall now attempt to get some more concrete bounds on the difference\n  between $\\pi(x)$ and $\\theta(x)/\\ln x$ These will be essential in showing the Prime\n  Number Theorem later.\n\n  We first need some bounds on the integral\n  \\[\\int\\nolimits_2^x \\frac{1}{\\ln^2 t}\\,\\mathrm{d}t\\]\n  in order to bound the contribution of the remainder term. This integral actually has an\n  antiderivative in terms of the logarithmic integral $\\textrm{li}(x)$, but since we do not have a\n  formalisation of it in Isabelle, we will instead use the following ad-hoc bound given by Apostol:\n\\<close>\nlemma integral_one_over_log_squared_bound:\n  assumes x: \"x \\<ge> 4\"\n  shows   \"integral {2..x} (\\<lambda>t. 1 / ln t ^ 2) \\<le> sqrt x / ln 2 ^ 2 + 4 * x / ln x ^ 2\"\nproof -\n  from x have \"x * 1 \\<le> x ^ 2\" unfolding power2_eq_square by (intro mult_left_mono) auto\n  with x have x': \"2 \\<le> sqrt x\" \"sqrt x \\<le> x\"\n    by (auto simp: real_sqrt_le_iff' intro!: real_le_rsqrt)\n  have \"integral {2..x} (\\<lambda>t. 1 / ln t ^ 2) =\n          integral {2..sqrt x} (\\<lambda>t. 1 / ln t ^ 2) + integral {sqrt x..x} (\\<lambda>t. 1 / ln t ^ 2)\"\n    (is \"_ = ?I1 + ?I2\") using x x'\n    by (intro Henstock_Kurzweil_Integration.integral_combine [symmetric] integrable_continuous_real)\n       (auto intro!: continuous_intros)\n  also have \"?I1 \\<le> integral {2..sqrt x} (\\<lambda>_. 1 / ln 2 ^ 2)\" using x\n    by (intro integral_le integrable_continuous_real divide_left_mono\n              power_mono continuous_intros) auto\n  also have \"\\<dots> \\<le> sqrt x / ln 2 ^ 2\" using x' by (simp add: field_simps)\n  also have \"?I2 \\<le> integral {sqrt x..x} (\\<lambda>t. 1 / ln (sqrt x) ^ 2)\" using x'\n    by (intro integral_le integrable_continuous_real divide_left_mono\n              power_mono continuous_intros) auto\n  also have \"\\<dots> \\<le> 4 * x / ln x ^ 2\" using x' by (simp add: ln_sqrt field_simps)\n  finally show ?thesis by simp\nqed\n\nlemma integral_one_over_log_squared_bigo:\n  \"(\\<lambda>x::real. integral {2..x} (\\<lambda>t. 1 / ln t ^ 2)) \\<in> O(\\<lambda>x. x / ln x ^ 2)\"\nproof -\n  define ub where \"ub = (\\<lambda>x::real. sqrt x / ln 2 ^ 2 + 4 * x / ln x ^ 2)\"\n  have \"eventually (\\<lambda>x. \\<bar>integral {2..x} (\\<lambda>t. 1 / (ln t)\\<^sup>2)\\<bar> \\<le> \\<bar>ub x\\<bar>) at_top\"\n    using eventually_ge_at_top[of 4]\n  proof eventually_elim\n    case (elim x)\n    hence \"\\<bar>integral {2..x} (\\<lambda>t. 1 / ln t ^ 2)\\<bar> = integral {2..x} (\\<lambda>t. 1 / ln t ^ 2)\"\n      by (intro abs_of_nonneg integral_nonneg integrable_continuous_real continuous_intros) auto\n    also have \"\\<dots> \\<le> \\<bar>ub x\\<bar>\"\n      using integral_one_over_log_squared_bound[of x] elim by (simp add: ub_def)\n    finally show ?case .\n  qed\n  hence \"(\\<lambda>x. integral {2..x} (\\<lambda>t. 1 / (ln t)\\<^sup>2)) \\<in> O(ub)\"\n    by (intro landau_o.bigI[of 1]) auto\n  also have \"ub \\<in> O(\\<lambda>x. x / ln x ^ 2)\" unfolding ub_def by real_asymp\n  finally show ?thesis .\nqed\n\nlemma \\<pi>_\\<theta>_bound:\n  assumes \"x \\<ge> (4 :: real)\"\n  defines \"ub \\<equiv> 2 / ln 2 * sqrt x + 8 * ln 2 * x / ln x ^ 2\"\n  shows   \"\\<pi> x - \\<theta> x / ln x \\<in> {0..ub}\"\nproof -\n  define r where \"r = (\\<lambda>x. integral {2..x} (\\<lambda>t. \\<theta> t / (t * ln t ^ 2)))\"\n  have integrable: \"(\\<lambda>t. c / ln t ^ 2) integrable_on {2..x}\" for c\n    by (intro integrable_continuous_real continuous_intros) auto\n\n  have \"r x \\<le> integral {2..x} (\\<lambda>t. ln 4 / ln t ^ 2)\" unfolding r_def\n    using integrable_weighted_\\<theta>[of 2 x] integrable[of \"ln 4\"] assms less_imp_le[OF \\<theta>_upper_bound]\n    by (intro integral_le divide_right_mono) (auto simp: field_simps)\n  also have \"\\<dots> = ln 4 * integral {2..x} (\\<lambda>t. 1 / ln t ^ 2)\"\n    using integrable[of 1] by (subst integral_mult) auto\n  also have \"\\<dots> \\<le> ln 4 * (sqrt x / ln 2 ^ 2 + 4 * x / ln x ^ 2)\"\n    using assms by (intro mult_left_mono integral_one_over_log_squared_bound) auto\n  also have \"ln (4 :: real) = 2 * ln 2\"\n    using ln_realpow[of 2 2] by simp\n  also have \"\\<dots> * (sqrt x / ln 2 ^ 2 + 4 * x / ln x ^ 2) = ub\"\n    using assms by (simp add: field_simps power2_eq_square ub_def)\n  finally have \"r x \\<le> \\<dots>\" .\n  moreover have \"r x \\<ge> 0\" unfolding r_def using assms\n    by (intro integral_nonneg integrable_weighted_\\<theta> divide_nonneg_pos) auto\n  ultimately have \"r x \\<in> {0..ub}\" by auto\n  with \\<pi>_conv_\\<theta>_integral[of x] assms(1) show ?thesis\n    by (simp add: r_def has_integral_iff)\nqed\n\ntext \\<open>\n  The following statement already indicates that the asymptotics of \\<open>\\<pi>\\<close> and \\<open>\\<theta>\\<close>\n  are very closely related, since through it, $\\pi(x) \\sim x / \\ln x$ and $\\theta(x) \\sim x$\n  imply each other.\n\\<close>\nlemma \\<pi>_\\<theta>_bigo: \"(\\<lambda>x. \\<pi> x - \\<theta> x / ln x) \\<in> O(\\<lambda>x. x / ln x ^ 2)\"\nproof -\n  define ub where \"ub = (\\<lambda>x. 2 / ln 2 * sqrt x + 8 * ln 2 * x / ln x ^ 2)\"\n  have \"(\\<lambda>x. \\<pi> x - \\<theta> x / ln x) \\<in> O(ub)\"\n  proof (intro le_imp_bigo_real[of 1] eventually_mono[OF eventually_ge_at_top])\n    fix x :: real assume \"x \\<ge> 4\"\n    from \\<pi>_\\<theta>_bound[OF this] show \"\\<pi> x - \\<theta> x / ln x \\<ge> 0\" and \"\\<pi> x - \\<theta> x / ln x \\<le> 1 * ub x\"\n      by (simp_all add: ub_def)\n  qed auto\n  also have \"ub \\<in> O(\\<lambda>x. x / ln x ^ 2)\"\n    unfolding ub_def by real_asymp\n  finally show ?thesis .\nqed\n\ntext \\<open>\n  As a foreshadowing of the Prime Number Theorem, we can already show\n  the following upper bound on $\\pi(x)$:\n\\<close>\nlemma \\<pi>_upper_bound:\n  assumes \"x \\<ge> (4 :: real)\"\n  shows   \"\\<pi> x < ln 4 * x / ln x  +  8 * ln 2 * x / ln x ^ 2  +  2 / ln 2 * sqrt x\"\nproof -\n  define ub where \"ub = 2 / ln 2 * sqrt x + 8 * ln 2 * x / ln x ^ 2\"\n  have \"\\<pi> x \\<le> \\<theta> x / ln x + ub\"\n    using \\<pi>_\\<theta>_bound[of x] assms unfolding ub_def by simp\n  also from assms have \"\\<theta> x / ln x < ln 4 * x / ln x\"\n    by (intro \\<theta>_upper_bound divide_strict_right_mono) auto\n  finally show ?thesis\n    using assms by (simp add: algebra_simps ub_def)\nqed\n\nlemma \\<pi>_bigo: \"\\<pi> \\<in> O(\\<lambda>x. x / ln x)\"\nproof -\n  have \"(\\<lambda>x. \\<pi> x - \\<theta> x / ln x) \\<in> O(\\<lambda>x. x / ln x ^ 2)\"\n    by (fact \\<pi>_\\<theta>_bigo)\n  also have \"(\\<lambda>x::real. x / ln x ^ 2) \\<in> O(\\<lambda>x. x / ln x)\"\n    by real_asymp\n  finally have \"(\\<lambda>x. \\<pi> x - \\<theta> x / ln x) \\<in> O(\\<lambda>x. x / ln x)\" .\n  moreover have \"eventually (\\<lambda>x::real. ln x > 0) at_top\" by real_asymp\n  hence \"eventually (\\<lambda>x::real. ln x \\<noteq> 0) at_top\" by eventually_elim auto\n  hence \"(\\<lambda>x. \\<theta> x / ln x) \\<in> O(\\<lambda>x. x / ln x)\"\n    using \\<theta>_bigo by (intro landau_o.big.divide_right)\n  ultimately have \"(\\<lambda>x. \\<pi> x - \\<theta> x / ln x + \\<theta> x / ln x) \\<in> O(\\<lambda>x. x / ln x)\"\n    by (rule sum_in_bigo)\n  thus ?thesis by simp\nqed\n\n\nsubsection \\<open>Equivalence of various forms of the Prime Number Theorem\\<close>\n\ntext \\<open>\n  In this section, we show that the following forms of the Prime Number Theorem are\n  all equivalent:\n    \\<^enum> $\\pi(x) \\sim x / \\ln x$\n    \\<^enum> $\\pi(x) \\ln \\pi(x) \\sim x$\n    \\<^enum> $p_n \\sim n \\ln n$\n    \\<^enum> $\\vartheta(x) \\sim x$\n    \\<^enum> $\\psi(x) \\sim x$\n\n  We show the following implication chains:\n    \\<^item> \\<open>(1) \\<rightarrow> (2) \\<rightarrow> (3) \\<rightarrow> (2) \\<rightarrow> (1)\\<close>\n    \\<^item> \\<open>(1) \\<rightarrow> (4) \\<rightarrow> (1)\\<close>\n    \\<^item> \\<open>(4) \\<rightarrow> (5) \\<rightarrow> (4)\\<close>\n\n  All of these proofs are taken from Apostol's book.\n\\<close>\n\nlemma PNT1_imp_PNT1':\n  assumes \"\\<pi> \\<sim>[at_top] (\\<lambda>x. x / ln x)\"\n  shows   \"(\\<lambda>x. ln (\\<pi> x)) \\<sim>[at_top] ln\"\nproof -\n  (* TODO: Tedious Landau sum reasoning *)\n  from assms have \"((\\<lambda>x. \\<pi> x / (x / ln x)) \\<longlongrightarrow> 1) at_top\"\n    by (rule asymp_equivD_strong[OF _ eventually_mono[OF eventually_gt_at_top[of 1]]]) auto\n  hence \"((\\<lambda>x. ln (\\<pi> x / (x / ln x))) \\<longlongrightarrow> ln 1) at_top\"\n    by (rule tendsto_ln) auto\n  also have \"?this \\<longleftrightarrow> ((\\<lambda>x. ln (\\<pi> x) - ln x + ln (ln x)) \\<longlongrightarrow> 0) at_top\"\n    by (intro filterlim_cong eventually_mono[OF eventually_gt_at_top[of 2]])\n       (auto simp: ln_div field_simps ln_mult \\<pi>_pos)\n  finally have \"(\\<lambda>x. ln (\\<pi> x) - ln x + ln (ln x)) \\<in> o(\\<lambda>_. 1)\"\n    by (intro smalloI_tendsto) auto\n  also have \"(\\<lambda>_::real. 1 :: real) \\<in> o(\\<lambda>x. ln x)\"\n    by real_asymp\n  finally have \"(\\<lambda>x. ln (\\<pi> x) - ln x + ln (ln x) - ln (ln x)) \\<in> o(\\<lambda>x. ln x)\"\n    by (rule sum_in_smallo) real_asymp+\n  thus *: \"(\\<lambda>x. ln (\\<pi> x)) \\<sim>[at_top] ln\"\n    by (simp add: asymp_equiv_altdef)\nqed\n\nlemma PNT1_imp_PNT2:\n  assumes \"\\<pi> \\<sim>[at_top] (\\<lambda>x. x / ln x)\"\n  shows   \"(\\<lambda>x. \\<pi> x * ln (\\<pi> x)) \\<sim>[at_top] (\\<lambda>x. x)\"\nproof -\n  have \"(\\<lambda>x. \\<pi> x * ln (\\<pi> x)) \\<sim>[at_top] (\\<lambda>x. x / ln x * ln x)\"\n    by (intro asymp_equiv_intros assms PNT1_imp_PNT1')\n  also have \"\\<dots> \\<sim>[at_top] (\\<lambda>x. x)\"\n    by (intro asymp_equiv_refl_ev eventually_mono[OF eventually_gt_at_top[of 1]])\n       (auto simp: field_simps)\n  finally show \"(\\<lambda>x. \\<pi> x * ln (\\<pi> x)) \\<sim>[at_top] (\\<lambda>x. x)\"\n    by simp\nqed\n\nlemma PNT2_imp_PNT3:\n  assumes \"(\\<lambda>x. \\<pi> x * ln (\\<pi> x)) \\<sim>[at_top] (\\<lambda>x. x)\"\n  shows   \"nth_prime \\<sim>[at_top] (\\<lambda>n. n * ln n)\"\nproof -\n  have \"(\\<lambda>n. nth_prime n) \\<sim>[at_top] (\\<lambda>n. \\<pi> (nth_prime n) * ln (\\<pi> (nth_prime n)))\"\n    using assms\n    by (rule asymp_equiv_symI [OF asymp_equiv_compose'])\n       (auto intro!: filterlim_compose[OF filterlim_real_sequentially nth_prime_at_top])\n  also have \"\\<dots> = (\\<lambda>n. real (Suc n) * ln (real (Suc n)))\"\n    by (simp add: add_ac)\n  also have \"\\<dots> \\<sim>[at_top] (\\<lambda>n. real n * ln (real n))\"\n    by real_asymp\n  finally show \"nth_prime \\<sim>[at_top] (\\<lambda>n. n * ln n)\" .\nqed\n\nlemma PNT3_imp_PNT2:\n  assumes \"nth_prime \\<sim>[at_top] (\\<lambda>n. n * ln n)\"\n  shows   \"(\\<lambda>x. \\<pi> x * ln (\\<pi> x)) \\<sim>[at_top] (\\<lambda>x. x)\"\nproof (rule asymp_equiv_symI, rule asymp_equiv_sandwich_real)\n  show \"eventually (\\<lambda>x. x \\<in> {real (nth_prime (nat \\<lfloor>\\<pi> x\\<rfloor> - 1))..real (nth_prime (nat \\<lfloor>\\<pi> x\\<rfloor>))})\n          at_top\"\n    using eventually_ge_at_top[of 2]\n  proof eventually_elim\n    case (elim x)\n    with nth_prime_partition''[of x] show ?case by auto\n  qed\nnext\n  have \"(\\<lambda>x. real (nth_prime (nat \\<lfloor>\\<pi> x\\<rfloor> - 1))) \\<sim>[at_top]\n           (\\<lambda>x. real (nat \\<lfloor>\\<pi> x\\<rfloor> - 1) * ln (real (nat \\<lfloor>\\<pi> x\\<rfloor> - 1)))\"\n    by (rule asymp_equiv_compose'[OF _ \\<pi>_at_top], rule asymp_equiv_compose'[OF assms]) real_asymp\n  also have \"\\<dots> \\<sim>[at_top] (\\<lambda>x. \\<pi> x * ln (\\<pi> x))\"\n    by (rule asymp_equiv_compose'[OF _ \\<pi>_at_top]) real_asymp\n  finally show \"(\\<lambda>x. real (nth_prime (nat \\<lfloor>\\<pi> x\\<rfloor> - 1))) \\<sim>[at_top] (\\<lambda>x. \\<pi> x * ln (\\<pi> x))\" .\nnext\n  have \"(\\<lambda>x. real (nth_prime (nat \\<lfloor>\\<pi> x\\<rfloor>))) \\<sim>[at_top]\n           (\\<lambda>x. real (nat \\<lfloor>\\<pi> x\\<rfloor>) * ln (real (nat \\<lfloor>\\<pi> x\\<rfloor>)))\"\n    by (rule asymp_equiv_compose'[OF _ \\<pi>_at_top], rule asymp_equiv_compose'[OF assms]) real_asymp\n  also have \"\\<dots> \\<sim>[at_top] (\\<lambda>x. \\<pi> x * ln (\\<pi> x))\"\n    by (rule asymp_equiv_compose'[OF _ \\<pi>_at_top]) real_asymp\n  finally show \"(\\<lambda>x. real (nth_prime (nat \\<lfloor>\\<pi> x\\<rfloor>))) \\<sim>[at_top] (\\<lambda>x. \\<pi> x * ln (\\<pi> x))\" .\nqed\n\nlemma PNT2_imp_PNT1:\n  assumes \"(\\<lambda>x. \\<pi> x * ln (\\<pi> x)) \\<sim>[at_top] (\\<lambda>x. x)\"\n  shows   \"(\\<lambda>x. ln (\\<pi> x)) \\<sim>[at_top] (\\<lambda>x. ln x)\"\n    and   \"\\<pi> \\<sim>[at_top] (\\<lambda>x. x / ln x)\"\nproof -\n   have ev: \"eventually (\\<lambda>x. \\<pi> x > 0) at_top\"\n            \"eventually (\\<lambda>x. ln (\\<pi> x) > 0) at_top\"\n            \"eventually (\\<lambda>x. ln (ln (\\<pi> x)) > 0) at_top\"\n    by (rule eventually_compose_filterlim[OF _ \\<pi>_at_top], real_asymp)+\n\n  let ?f = \"\\<lambda>x. 1 + ln (ln (\\<pi> x)) / ln (\\<pi> x) - ln x / ln (\\<pi> x)\"\n  have \"((\\<lambda>x. ln (\\<pi> x) * ?f x) \\<longlongrightarrow> ln 1) at_top\"\n  proof (rule Lim_transform_eventually)\n    from assms have \"((\\<lambda>x. \\<pi> x * ln (\\<pi> x) / x) \\<longlongrightarrow> 1) at_top\"\n      by (rule asymp_equivD_strong[OF _ eventually_mono[OF eventually_gt_at_top[of 1]]]) auto\n    then show \"((\\<lambda>x. ln (\\<pi> x * ln (\\<pi> x) / x)) \\<longlongrightarrow> ln 1) at_top\"\n      by (rule tendsto_ln) auto\n    show \"\\<forall>\\<^sub>F x in at_top. ln (\\<pi> x * ln (\\<pi> x) / x) = ln (\\<pi> x) * ?f x\"\n      using eventually_gt_at_top[of 0] ev\n      by eventually_elim (simp add: field_simps ln_mult ln_div)\n  qed\n  moreover have \"((\\<lambda>x. 1 / ln (\\<pi> x)) \\<longlongrightarrow> 0) at_top\"\n    by (rule filterlim_compose[OF _ \\<pi>_at_top]) real_asymp\n  ultimately have \"((\\<lambda>x. ln (\\<pi> x) * ?f x * (1 / ln (\\<pi> x))) \\<longlongrightarrow> ln 1 * 0) at_top\"\n    by (rule tendsto_mult)\n  moreover have \"eventually (\\<lambda>x. ln (\\<pi> x) * ?f x * (1 / ln (\\<pi> x)) = ?f x) at_top\"\n    using ev by eventually_elim auto\n  ultimately have \"(?f \\<longlongrightarrow> ln 1 * 0) at_top\"\n    by (rule Lim_transform_eventually)\n  hence \"((\\<lambda>x. 1 + ln (ln (\\<pi> x)) / ln (\\<pi> x) - ?f x) \\<longlongrightarrow> 1 + 0 - ln 1 * 0) at_top\"\n    by (intro tendsto_intros filterlim_compose[OF _ \\<pi>_at_top]) (real_asymp | simp)+\n  hence \"((\\<lambda>x. ln x / ln (\\<pi> x)) \\<longlongrightarrow> 1) at_top\"\n    by simp\n  thus *: \"(\\<lambda>x. ln (\\<pi> x)) \\<sim>[at_top] (\\<lambda>x. ln x)\"\n    by (rule asymp_equiv_symI[OF asymp_equivI'])\n\n  have \"eventually (\\<lambda>x. \\<pi> x = \\<pi> x * ln (\\<pi> x) / ln (\\<pi> x)) at_top\"\n    using ev by eventually_elim auto\n  hence \"\\<pi> \\<sim>[at_top] (\\<lambda>x. \\<pi> x * ln (\\<pi> x) / ln (\\<pi> x))\"\n    by (rule asymp_equiv_refl_ev)\n  also from assms and * have \"(\\<lambda>x. \\<pi> x * ln (\\<pi> x) / ln (\\<pi> x)) \\<sim>[at_top] (\\<lambda>x. x / ln x)\"\n    by (rule asymp_equiv_intros)\n  finally show \"\\<pi> \\<sim>[at_top] (\\<lambda>x. x / ln x)\" .\nqed\n\nlemma PNT4_imp_PNT5:\n  assumes \"\\<theta> \\<sim>[at_top] (\\<lambda>x. x)\"\n  shows   \"\\<psi> \\<sim>[at_top] (\\<lambda>x. x)\"\nproof -\n  define r where \"r = (\\<lambda>x. \\<psi> x - \\<theta> x)\"\n  have \"r \\<in> O(\\<lambda>x. ln x * sqrt x)\"\n    unfolding r_def by (fact \\<psi>_minus_\\<theta>_bigo)\n  also have \"(\\<lambda>x::real. ln x * sqrt x) \\<in> o(\\<lambda>x. x)\"\n    by real_asymp\n  finally have r: \"r \\<in> o(\\<lambda>x. x)\" .\n\n  have \"(\\<lambda>x. \\<theta> x + r x) \\<sim>[at_top] (\\<lambda>x. x)\"\n    using assms r by (subst asymp_equiv_add_right) auto\n  thus ?thesis by (simp add: r_def)\nqed\n\nlemma PNT4_imp_PNT1:\n  assumes \"\\<theta> \\<sim>[at_top] (\\<lambda>x. x)\"\n  shows   \"\\<pi> \\<sim>[at_top] (\\<lambda>x. x / ln x)\"\nproof -\n  have \"(\\<lambda>x. (\\<pi> x - \\<theta> x / ln x) + ((\\<theta> x - x) / ln x)) \\<in> o(\\<lambda>x. x / ln x)\"\n  proof (rule sum_in_smallo)\n    have \"(\\<lambda>x. \\<pi> x - \\<theta> x / ln x) \\<in> O(\\<lambda>x. x / ln x ^ 2)\"\n      by (rule \\<pi>_\\<theta>_bigo)\n    also have \"(\\<lambda>x. x / ln x ^ 2) \\<in> o(\\<lambda>x. x / ln x :: real)\"\n      by real_asymp\n    finally show \"(\\<lambda>x. \\<pi> x - \\<theta> x / ln x) \\<in> o(\\<lambda>x. x / ln x)\" .\n  next\n    have \"eventually (\\<lambda>x::real. ln x > 0) at_top\" by real_asymp\n    hence \"eventually (\\<lambda>x::real. ln x \\<noteq> 0) at_top\" by eventually_elim auto\n    thus \"(\\<lambda>x. (\\<theta> x - x) / ln x) \\<in> o(\\<lambda>x. x / ln x)\"\n      by (intro landau_o.small.divide_right asymp_equiv_imp_diff_smallo assms)\n  qed\n  thus ?thesis by (simp add: diff_divide_distrib asymp_equiv_altdef)\nqed\n\nlemma PNT1_imp_PNT4:\n  assumes \"\\<pi> \\<sim>[at_top] (\\<lambda>x. x / ln x)\"\n  shows   \"\\<theta> \\<sim>[at_top] (\\<lambda>x. x)\"\nproof -\n  have \"\\<theta> \\<sim>[at_top] (\\<lambda>x. \\<pi> x * ln x)\"\n  proof (rule smallo_imp_asymp_equiv)\n    have \"(\\<lambda>x. \\<theta> x - \\<pi> x * ln x) \\<in> \\<Theta>(\\<lambda>x. - ((\\<pi> x - \\<theta> x / ln x) * ln x))\"\n      by (intro bigthetaI_cong eventually_mono[OF eventually_gt_at_top[of 1]])\n         (auto simp: field_simps)\n    also have \"(\\<lambda>x. - ((\\<pi> x - \\<theta> x / ln x) * ln x)) \\<in> O(\\<lambda>x. x / (ln x)\\<^sup>2 * ln x)\"\n      unfolding landau_o.big.uminus_in_iff by (intro landau_o.big.mult_right \\<pi>_\\<theta>_bigo)\n    also have \"(\\<lambda>x::real. x / (ln x)\\<^sup>2 * ln x) \\<in> o(\\<lambda>x. x / ln x * ln x)\"\n      by real_asymp\n    also have \"(\\<lambda>x. x / ln x * ln x) \\<in> \\<Theta>(\\<lambda>x. \\<pi> x * ln x)\"\n      by (intro asymp_equiv_imp_bigtheta asymp_equiv_intros asymp_equiv_symI[OF assms])\n    finally show \"(\\<lambda>x. \\<theta> x - \\<pi> x * ln x) \\<in> o(\\<lambda>x. \\<pi> x * ln x)\" .\n  qed\n  also have \"\\<dots> \\<sim>[at_top] (\\<lambda>x. x / ln x * ln x)\"\n    by (intro asymp_equiv_intros assms)\n  also have \"\\<dots> \\<sim>[at_top] (\\<lambda>x. x)\"\n    by real_asymp\n  finally show ?thesis .\nqed\n\nlemma PNT5_imp_PNT4:\n  assumes \"\\<psi> \\<sim>[at_top] (\\<lambda>x. x)\"\n  shows   \"\\<theta> \\<sim>[at_top] (\\<lambda>x. x)\"\nproof -\n  define r where \"r = (\\<lambda>x. \\<theta> x - \\<psi> x)\"\n  have \"(\\<lambda>x. \\<psi> x - \\<theta> x) \\<in> O(\\<lambda>x. ln x * sqrt x)\"\n    by (fact \\<psi>_minus_\\<theta>_bigo)\n  also have \"(\\<lambda>x. \\<psi> x - \\<theta> x) = (\\<lambda>x. -r x)\"\n    by (simp add: r_def)\n  finally have \"r \\<in> O(\\<lambda>x. ln x * sqrt x)\"\n    by simp\n  also have \"(\\<lambda>x::real. ln x * sqrt x) \\<in> o(\\<lambda>x. x)\"\n    by real_asymp\n  finally have r: \"r \\<in> o(\\<lambda>x. x)\" .\n\n  have \"(\\<lambda>x. \\<psi> x + r x) \\<sim>[at_top] (\\<lambda>x. x)\"\n    using assms r by (subst asymp_equiv_add_right) auto\n  thus ?thesis by (simp add: r_def)\nqed\n\n\nsubsection \\<open>The asymptotic form of Mertens' First Theorem\\<close>\n\ntext \\<open>\n  Mertens' first theorem states that $\\mathfrak{M}(x) - \\ln x$ is bounded, i.\\,e.\\ \n  $\\mathfrak{M}(x) = \\ln x + O(1)$.\n\n  With some work, one can also show some absolute bounds for $|\\mathfrak{M}(x) - \\ln x|$, and we\n  will, in fact, do this later. However, this asymptotic form is somewhat easier to obtain and it is\n  (as we shall see) enough to prove the Prime Number Theorem, so we prove the weak form here first\n  for the sake of a smoother presentation.\n\n  First of all, we need a very weak version of Stirling's formula for the logarithm of\n  the factorial, namely:\n  \\[\\ln(\\lfloor x\\rfloor!) = \\sum\\limits_{n\\leq x} \\ln x = x \\ln x + O(x)\\]\n  We show this using summation by parts.\n\\<close>\nlemma stirling_weak:\n  assumes x: \"x \\<ge> 1\"\n  shows   \"sum_upto ln x \\<in> {x * ln x - x - ln x + 1 .. x * ln x}\"\nproof (cases \"x = 1\")\n  case True\n  have \"{0<..Suc 0} = {1}\" by auto\n  with True show ?thesis by (simp add: sum_upto_altdef)\nnext\n  case False\n  with assms have x: \"x > 1\" by simp\n  have \"((\\<lambda>t. sum_upto (\\<lambda>_. 1) t * (1 / t)) has_integral\n          sum_upto (\\<lambda>_. 1) x * ln x - sum_upto (\\<lambda>_. 1) 1 * ln 1 -\n          (\\<Sum>n\\<in>real -` {1<..x}. 1 * ln (real n))) {1..x}\" using x\n    by (intro partial_summation_strong[of \"{}\"])\n       (auto simp flip: has_field_derivative_iff_has_vector_derivative\n             intro!: derivative_eq_intros continuous_intros)\n  hence \"((\\<lambda>t. real (nat \\<lfloor>t\\<rfloor>) / t) has_integral\n           real (nat \\<lfloor>x\\<rfloor>) * ln x - (\\<Sum>n\\<in>real -` {1<..x}. ln (real n))) {1..x}\"\n    by (simp add: sum_upto_altdef)\n  also have \"(\\<Sum>n\\<in>real -` {1<..x}. ln (real n)) = sum_upto ln x\" unfolding sum_upto_def\n    by (intro sum.mono_neutral_left)\n       (auto intro!: finite_subset[OF _ finite_vimage_real_of_nat_greaterThanAtMost[of 0 x]])\n  finally have *: \"((\\<lambda>t. real (nat \\<lfloor>t\\<rfloor>) / t) has_integral \\<lfloor>x\\<rfloor> * ln x - sum_upto ln x) {1..x}\"\n    using x by simp\n\n  have \"0 \\<le> real_of_int \\<lfloor>x\\<rfloor> * ln x - sum_upto (\\<lambda>n. ln (real n)) x\"\n    using * by (rule has_integral_nonneg) auto\n  also have \"\\<dots> \\<le> x * ln x - sum_upto ln x\"\n    using x by (intro diff_mono mult_mono) auto\n  finally have upper: \"sum_upto ln x \\<le> x * ln x\" by simp\n\n  have \"(x - 1) * ln x - x + 1 \\<le> \\<lfloor>x\\<rfloor> * ln x - x + 1\"\n    using x by (intro diff_mono mult_mono add_mono) auto\n  also have \"((\\<lambda>t. 1) has_integral (x - 1)) {1..x}\"\n    using has_integral_const_real[of \"1::real\" 1 x] x by simp\n  from * and this have \"\\<lfloor>x\\<rfloor> * ln x - sum_upto ln x \\<le> x - 1\"\n    by (rule has_integral_le) auto\n  hence \"\\<lfloor>x\\<rfloor> * ln x - x + 1 \\<le> sum_upto ln x\"\n    by simp\n  finally have \"sum_upto ln x \\<ge> x * ln x - x - ln x + 1\"\n    by (simp add: algebra_simps)\n  with upper show ?thesis by simp\nqed\n\nlemma stirling_weak_bigo: \"(\\<lambda>x::real. sum_upto ln x - x * ln x) \\<in> O(\\<lambda>x. x)\"\nproof -\n  have \"(\\<lambda>x. sum_upto ln x - x * ln x) \\<in> O(\\<lambda>x. -(sum_upto ln x - x * ln x))\"\n    by (subst landau_o.big.uminus) auto\n  also have \"(\\<lambda>x. -(sum_upto ln x - x * ln x)) \\<in> O(\\<lambda>x. x + ln x - 1)\"\n  proof (intro le_imp_bigo_real[of 2] eventually_mono[OF eventually_ge_at_top[of 1]], goal_cases)\n    case (2 x)\n    thus ?case using stirling_weak[of x] by (auto simp: algebra_simps)\n  next\n    case (3 x)\n    thus ?case using stirling_weak[of x] by (auto simp: algebra_simps)\n  qed auto\n  also have \"(\\<lambda>x. x + ln x - 1) \\<in> O(\\<lambda>x::real. x)\" by real_asymp\n  finally show ?thesis .\nqed\n\nlemma floor_floor_div_eq:\n  fixes x :: real and d :: nat\n  assumes \"x \\<ge> 0\"\n  shows   \"\\<lfloor>nat \\<lfloor>x\\<rfloor> / real d\\<rfloor> = \\<lfloor>x / real d\\<rfloor>\"\nproof -\n  have \"\\<lfloor>nat \\<lfloor>x\\<rfloor> / real_of_int (int d)\\<rfloor> = \\<lfloor>x / real_of_int (int d)\\<rfloor>\" using assms\n    by (subst (1 2) floor_divide_real_eq_div) auto\n  thus ?thesis by simp\nqed\n\ntext \\<open>\n  The key to showing Mertens' first theorem is the function\n  \\[h(x) := \\sum\\limits_{n \\leq x} \\frac{\\Lambda(d)}{d}\\]\n  where $\\Lambda$ is the Mangoldt function, which is equal to $\\ln p$ for any prime power\n  $p^k$ and $0$ otherwise. As we shall see, $h(x)$ is a good approximation for $\\mathfrak M(x)$,\n  as the difference between them is bounded by a constant.\n\\<close>\nlemma sum_upto_mangoldt_over_id_minus_phi_bounded:\n    \"(\\<lambda>x. sum_upto (\\<lambda>d. mangoldt d / real d) x - \\<MM> x) \\<in> O(\\<lambda>_. 1)\"\nproof -\n  define f where \"f = (\\<lambda>d. mangoldt d / real d)\"\n  define C where \"C = (\\<Sum>p. ln (real (p + 1)) * (1 / real (p * (p - 1))))\"\n  have summable: \"summable (\\<lambda>p::nat. ln (p + 1) * (1 / (p * (p - 1))))\"\n  proof (rule summable_comparison_test_bigo)\n    show \"summable (\\<lambda>p. norm (p powr (-3/2)))\"\n      by (simp add: summable_real_powr_iff)\n  qed real_asymp\n\n  have diff_bound: \"sum_upto f x - \\<MM> x \\<in> {0..C}\" if x: \"x \\<ge> 4\" for x\n  proof -\n    define S where \"S = {(p, i). prime p \\<and> 0 < i \\<and> real (p ^ i) \\<le> x}\"\n    define S' where \"S' = (SIGMA p:{2..nat \\<lfloor>root 2 x\\<rfloor>}. {2..nat \\<lfloor>log 2 x\\<rfloor>})\"\n    have \"S \\<subseteq> {..nat \\<lfloor>x\\<rfloor>} \\<times> {..nat \\<lfloor>log 2 x\\<rfloor>}\" unfolding S_def\n      using x primepows_le_subset[of x 1] by (auto simp: Suc_le_eq)\n    hence \"finite S\" by (rule finite_subset) auto\n    note fin = finite_subset[OF _ this, unfolded S_def]\n  \n    have \"sum_upto f x = (\\<Sum>(p, i)\\<in>S. ln (real p) / real (p ^ i))\" unfolding S_def\n      by (intro sum_upto_primepows) (auto simp: f_def mangoldt_non_primepow)\n    also have \"S = {p. prime p \\<and> p \\<le> x} \\<times> {1} \\<union> {(p, i). prime p \\<and> 1 < i \\<and> real (p ^ i) \\<le> x}\"\n      by (auto simp: S_def not_less le_Suc_eq not_le intro!: Suc_lessI)\n    also have \"(\\<Sum>(p,i)\\<in>\\<dots>. ln (real p) / real (p ^ i)) =\n                 (\\<Sum>(p, i) \\<in> {p. prime p \\<and> of_nat p \\<le> x} \\<times> {1}. ln (real p) / real (p ^ i)) +\n                 (\\<Sum>(p, i) | prime p \\<and> real (p ^ i) \\<le> x \\<and> i > 1. ln (real p) / real (p ^ i))\"\n      (is \"_ = ?S1 + ?S2\")\n      by (subst sum.union_disjoint[OF fin fin]) (auto simp: conj_commute case_prod_unfold)\n    also have \"?S1 = \\<MM> x\"\n      by (subst sum.cartesian_product [symmetric]) (auto simp: primes_M_def prime_sum_upto_def)\n    finally have eq: \"sum_upto f x - \\<MM> x = ?S2\" by simp\n    have \"?S2 \\<le> (\\<Sum>(p, i)\\<in>S'. ln (real p) / real (p ^ i))\"\n      using primepows_le_subset[of x 2] x unfolding case_prod_unfold of_nat_power\n      by (intro sum_mono2 divide_nonneg_pos zero_less_power)\n         (auto simp: eval_nat_numeral Suc_le_eq S'_def subset_iff dest: prime_gt_1_nat)+\n    also have \"\\<dots> = (\\<Sum>p=2..nat \\<lfloor>sqrt x\\<rfloor>. ln p * (\\<Sum>i\\<in>{2..nat \\<lfloor>log 2 x\\<rfloor>}. (1 / real p) ^ i))\"\n      by (simp add: S'_def sum.Sigma case_prod_unfold\n                    sum_distrib_left sqrt_def field_simps)\n    also have \"\\<dots> \\<le> (\\<Sum>p=2..nat \\<lfloor>sqrt x\\<rfloor>. ln p * (1 / (p * (p - 1))))\"\n      unfolding sum_upto_def\n    proof (intro sum_mono, goal_cases)\n      case (1 p)\n      from x have \"nat \\<lfloor>log 2 x\\<rfloor> \\<ge> 2\"\n        by (auto simp: le_nat_iff' le_log_iff)\n      hence \"(\\<Sum>i\\<in>{2..nat \\<lfloor>log 2 x\\<rfloor>}. (1 / real p) ^ i) = \n               ((1 / p)\\<^sup>2 - (1 / p) ^ nat \\<lfloor>log 2 x\\<rfloor> / p) / (1 - 1 / p)\" using 1\n        by (subst sum_gp) (auto dest!: prime_gt_1_nat simp: field_simps power2_eq_square)\n      also have \"\\<dots> \\<le> ((1 / p) ^ 2 - 0) / (1 - 1 / p)\"\n        using 1 by (intro divide_right_mono diff_mono power_mono)\n                   (auto simp: field_simps dest: prime_gt_0_nat)\n      also have \"\\<dots> = 1 / (p * (p - 1))\"\n        by (auto simp: divide_simps power2_eq_square dest: prime_gt_0_nat)\n      finally show ?case\n        using 1 by (intro mult_left_mono) (auto dest: prime_gt_0_nat)\n    qed\n    also have \"\\<dots> \\<le> (\\<Sum>p=2..nat \\<lfloor>sqrt x\\<rfloor>. ln (p + 1) * (1 / (p * (p - 1))))\"\n      by (intro sum_mono mult_mono) auto\n    also have \"\\<dots> \\<le> C\" unfolding C_def\n      by (intro sum_le_suminf summable) auto\n    finally have \"?S2 \\<le> C\" by simp\n    moreover have \"?S2 \\<ge> 0\" by (intro sum_nonneg) (auto dest: prime_gt_0_nat)\n    ultimately show ?thesis using eq by simp\n  qed\n\n  from diff_bound[of 4] have \"C \\<ge> 0\" by auto\n  with diff_bound show \"(\\<lambda>x. sum_upto f x - \\<MM> x) \\<in> O(\\<lambda>_. 1)\"\n    by (intro le_imp_bigo_real[of C] eventually_mono[OF eventually_ge_at_top[of 4]]) auto\nqed\n\ntext \\<open>\n  Next, we show that our $h(x)$ itself is close to $\\ln x$, i.\\,e.:\n  \\[\\sum\\limits_{n \\leq x} \\frac{\\Lambda(d)}{d} = \\ln x + O(1)\\]\n\\<close>\nlemma sum_upto_mangoldt_over_id_asymptotics:\n  \"(\\<lambda>x. sum_upto (\\<lambda>d. mangoldt d / real d) x - ln x) \\<in> O(\\<lambda>_. 1)\"\nproof -\n  define r where \"r = (\\<lambda>n::real. sum_upto (\\<lambda>d. mangoldt d * (n / d - real_of_int \\<lfloor>n / d\\<rfloor>)) n)\"\n  have r: \"r \\<in> O(\\<psi>)\"\n  proof (intro landau_o.bigI[of 1] eventually_mono[OF eventually_ge_at_top[of 0]])\n    fix x :: real assume x: \"x \\<ge> 0\"\n    have eq: \"{1..nat \\<lfloor>x\\<rfloor>} = {0<..nat \\<lfloor>x\\<rfloor>}\" by auto\n    hence \"r x \\<ge> 0\" unfolding r_def sum_upto_def\n      by (intro sum_nonneg mult_nonneg_nonneg mangoldt_nonneg)\n         (auto simp: floor_le_iff)\n    moreover have \"x / real d \\<le> 1 + real_of_int \\<lfloor>x / real d\\<rfloor>\" for d by linarith\n    hence \"r x \\<le> sum_upto (\\<lambda>d. mangoldt d * 1) x\" unfolding sum_upto_altdef eq r_def using x\n      by (intro sum_mono mult_mono mangoldt_nonneg)\n         (auto simp:  less_imp_le[OF frac_lt_1] algebra_simps)\n    ultimately show \"norm (r x) \\<le> 1 * norm (\\<psi> x)\" by (simp add: \\<psi>_def)\n  qed auto\n  also have \"\\<psi> \\<in> O(\\<lambda>x. x)\" by (fact \\<psi>_bigo)\n  finally have r: \"r \\<in> O(\\<lambda>x. x)\" .\n\n  define r' where \"r' = (\\<lambda>x::real. sum_upto ln x - x * ln x)\"\n  have r'_bigo: \"r' \\<in> O(\\<lambda>x. x)\"\n    using stirling_weak_bigo unfolding r'_def .\n  have ln_fact: \"ln (fact n) = (\\<Sum>d=1..n. ln d)\" for n\n    by (induction n) (simp_all add: ln_mult)\n  hence r': \"sum_upto ln n = n * ln n + r' n\" for n :: real\n    unfolding r'_def sum_upto_altdef by (auto intro!: sum.cong)\n\n  have \"eventually (\\<lambda>n. sum_upto (\\<lambda>d. mangoldt d / d) n - ln n = r' n / n + r n / n) at_top\"\n    using eventually_gt_at_top\n  proof eventually_elim\n    fix x :: real assume x: \"x > 0\"\n    have \"sum_upto ln x = sum_upto (\\<lambda>n. mangoldt n * real (nat \\<lfloor>x / n\\<rfloor>)) x\"\n      unfolding sum_upto_ln_conv_sum_upto_mangoldt ..\n    also have \"\\<dots> = sum_upto (\\<lambda>d. mangoldt d * (x / d)) x - r x\"\n      unfolding sum_upto_def by (simp add: algebra_simps sum_subtractf r_def sum_upto_def)\n    also have \"sum_upto (\\<lambda>d. mangoldt d * (x / d)) x = x * sum_upto (\\<lambda>d. mangoldt d / d) x\"\n      unfolding sum_upto_def by (subst sum_distrib_left) (simp add: field_simps)\n    finally have \"x * sum_upto (\\<lambda>d. mangoldt d / real d) x = r' x + r x + x * ln x\"\n      by (simp add: r' algebra_simps)\n    thus \"sum_upto (\\<lambda>d. mangoldt d / d) x - ln x = r' x / x + r x / x\"\n      using x by (simp add: field_simps)\n  qed\n  hence \"(\\<lambda>x. sum_upto (\\<lambda>d. mangoldt d / d) x - ln x) \\<in> \\<Theta>(\\<lambda>x. r' x / x + r x / x)\"\n    by (rule bigthetaI_cong)\n  also have \"(\\<lambda>x. r' x / x + r x / x) \\<in> O(\\<lambda>_. 1)\"\n    by (intro sum_in_bigo) (insert r r'_bigo, auto simp: landau_divide_simps)\n  finally show ?thesis .\nqed\n\ntext \\<open>\n  Combining these two gives us Mertens' first theorem.\n\\<close>\ntheorem mertens_bounded: \"(\\<lambda>x. \\<MM> x - ln x) \\<in> O(\\<lambda>_. 1)\"\nproof -\n  define f where \"f = sum_upto (\\<lambda>d. mangoldt d / d)\"\n  have \"(\\<lambda>x. (f x - ln x) - (f x - \\<MM> x)) \\<in> O(\\<lambda>_. 1)\"\n    using sum_upto_mangoldt_over_id_asymptotics\n          sum_upto_mangoldt_over_id_minus_phi_bounded\n    unfolding f_def by (rule sum_in_bigo)\n  thus ?thesis by simp\nqed\n\nlemma primes_M_bigo: \"\\<MM> \\<in> O(\\<lambda>x. ln x)\"\nproof -\n  have \"(\\<lambda>x. \\<MM> x - ln x) \\<in> O(\\<lambda>_. 1)\"\n    by (rule mertens_bounded)\n  also have \"(\\<lambda>_::real. 1) \\<in> O(\\<lambda>x. ln x)\"\n    by real_asymp\n  finally have \"(\\<lambda>x. \\<MM> x - ln x + ln x) \\<in> O(\\<lambda>x. ln x)\"\n    by (rule sum_in_bigo) auto\n  thus ?thesis by simp\nqed\n\n(*<*)\nunbundle no_prime_counting_notation\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/Prime_Number_Theorem/Prime_Counting_Functions.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8596637433190939, "lm_q2_score": 0.849971175657575, "lm_q1q2_score": 0.730689402579122}}
{"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{colbournHandbookCombinatorialDesigns2007}\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{stinsonCombinatorialDesignsConstructions2004}\\<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": "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/Dual_Systems.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8499711604559846, "lm_q2_score": 0.8596637487122111, "lm_q1q2_score": 0.73068939409486}}
{"text": "theory Named\n  imports \"../00Utils/Variable\" \"../00Utils/Utils\"\nbegin\n\ndatatype nexpr = \n  NVar var\n  | NConst nat\n  | NLam var nexpr\n  | NApp nexpr nexpr\n\nprimrec all_vars :: \"nexpr \\<Rightarrow> var set\" where\n  \"all_vars (NVar x) = {x}\"\n| \"all_vars (NConst k) = {}\"\n| \"all_vars (NLam x e) = insert x (all_vars e)\"\n| \"all_vars (NApp e\\<^sub>1 e\\<^sub>2) = all_vars e\\<^sub>1 \\<union> all_vars e\\<^sub>2\"\n\nprimrec valn :: \"nexpr \\<Rightarrow> bool\" where\n  \"valn (NVar x) = False\"\n| \"valn (NConst k) = True\" \n| \"valn (NLam x e) = True\" \n| \"valn (NApp e\\<^sub>1 e\\<^sub>2) = False\" \n\nprimrec subst_var :: \"var \\<Rightarrow> var \\<Rightarrow> nexpr \\<Rightarrow> nexpr\" where\n  \"subst_var x x' (NVar y) = NVar (if x = y then x' else y)\"\n| \"subst_var x x' (NConst k) = NConst k\"\n| \"subst_var x x' (NLam y e) = NLam y (if x = y then e else subst_var x x' e)\"\n| \"subst_var x x' (NApp e\\<^sub>1 e\\<^sub>2) = NApp (subst_var x x' e\\<^sub>1) (subst_var x x' e\\<^sub>2)\"\n\n\n\nfun substn :: \"var \\<Rightarrow> nexpr \\<Rightarrow> nexpr \\<Rightarrow> nexpr\" where\n  \"substn x e' (NVar y) = (if x = y then e' else NVar y)\"\n| \"substn x e' (NConst k) = NConst k\"\n| \"substn x e' (NLam y e) = (\n    let z = fresh (all_vars e' \\<union> all_vars e \\<union> {x, y})\n    in NLam z (substn x e' (subst_var y z e)))\"\n| \"substn x e' (NApp e\\<^sub>1 e\\<^sub>2) = NApp (substn x e' e\\<^sub>1) (substn x e' e\\<^sub>2)\"\n\ninductive evaln :: \"nexpr \\<Rightarrow> nexpr \\<Rightarrow> bool\" (infix \"\\<Down>\" 50) where\n  evn_const [simp]: \"NConst k \\<Down> NConst k\"\n| evn_lam [simp]: \"NLam x e \\<Down> NLam x e\"\n| evn_app [simp]: \"e\\<^sub>1 \\<Down> NLam x e\\<^sub>1' \\<Longrightarrow> e\\<^sub>2 \\<Down> v\\<^sub>2 \\<Longrightarrow> substn x v\\<^sub>2 e\\<^sub>1' \\<Down> v \\<Longrightarrow> NApp e\\<^sub>1 e\\<^sub>2 \\<Down> v\"\n\nlemma [simp]: \"finite (all_vars e)\"\n  by (induction e) simp_all\n\n(* We, obviously, do not have safety here yet. The relevant proofs are in 03Debruijn/NameRemoval. *)\n\nlemma [simp]: \"e \\<Down> v \\<Longrightarrow> valn v\"\n  by (induction e v rule: evaln.induct) simp_all\n\nlemma val_no_evaln: \"e \\<Down> v \\<Longrightarrow> valn e \\<Longrightarrow> v = e\"\n  by (induction e v rule: evaln.induct) simp_all\n\ntheorem determinismn: \"e \\<Down> v \\<Longrightarrow> e \\<Down> v' \\<Longrightarrow> v = v'\"\nproof (induction e v arbitrary: v' rule: evaln.induct)\n  case (evn_const k)\n  thus ?case by (induction \"NConst k\" v' rule: evaln.induct) simp_all\nnext\n  case (evn_lam x e)\n  thus ?case by (induction \"NLam x e\" v' rule: evaln.induct) simp_all\nnext\n  case (evn_app e\\<^sub>1 x e\\<^sub>1' e\\<^sub>2 v\\<^sub>2 v)\n  from evn_app(7, 1, 2, 3, 4, 5, 6) show ?case \n    by (induction \"NApp e\\<^sub>1 e\\<^sub>2\" v' rule: evaln.induct) blast+\nqed\n\nend", "meta": {"author": "xtreme-james-cooper", "repo": "Lambda-RAM-Compiler", "sha": "24125435949fa71dfc5faafdb236d28a098beefc", "save_path": "github-repos/isabelle/xtreme-james-cooper-Lambda-RAM-Compiler", "path": "github-repos/isabelle/xtreme-james-cooper-Lambda-RAM-Compiler/Lambda-RAM-Compiler-24125435949fa71dfc5faafdb236d28a098beefc/01Source/Named.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513620489618, "lm_q2_score": 0.8152324826183822, "lm_q1q2_score": 0.7306532229332816}}
{"text": "section \\<open>Predicate Transformers Semantics of Invariant Diagrams\\<close>\n\ntheory Diagram\nimports Hoare\nbegin\n\ntext \\<open>\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\\<close>\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 \\<open>\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\\<close>\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 \\<open>\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\\<close>\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 \\<open>\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\\<close>\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)\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\\<open>\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\\<close>\n\ntext \\<open>\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\\<close>\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\\<in>{v. pair v i < u}. X v i :: _ :: complete_lattice)\" \n\ndefinition \n  \"SUP_LE_P X u i = (SUP v\\<in>{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 image_comp, clarify)\n  apply (rule antisym)\n  apply (rule SUP_least)\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\n  apply (simp add: SUP_LE_P_def)\n  apply (unfold 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\n  apply (rule hoare_diagram2)\n  by auto\n\ntext\\<open>\nThe following definition introduces the concept of correct Hoare triples for diagrams.\n\\<close>\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 uminus_Inf)\n  apply (case_tac \"(uminus ` range (\\<lambda>j::'b. D (i, j) \\<bottom>)) = {P::'a. \\<exists>j::'b. P = - D (i, j) \\<bottom>}\")\n  apply (auto cong del: SUP_cong_simp)\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": "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/DataRefinementIBP/Diagram.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418262465169, "lm_q2_score": 0.7905303186696747, "lm_q1q2_score": 0.7305621323986341}}
{"text": "(*<*)\ntheory TortoiseHare\nimports\n  Basis\nbegin\n\n(*>*)\nsection\\<open> The Tortoise and the Hare \\label{sec:th} \\<close>\n\ntext (in properties) \\<open>\n\nThe key to the Tortoise and Hare algorithm is that any @{term \"nu\"}\nsuch that @{term \"seq (nu + nu) = seq nu\"} must be divisible by @{term\n\"lambda\"}. Intuitively the first @{term \"nu\"} steps get us into the\nloop. If the second @{term \"nu\"} steps return us to the same value of\nthe sequence, then we must have gone around the loop one or more\ntimes.\n\n\\<close>\n\nlemma (in properties) lambda_dvd_nu:\n  assumes \"seq (i + i) = seq i\"\n  shows \"lambda dvd i\"\nproof(cases \"i = 0\")\n  case False\n  with assms have \"mu \\<le> i\" by (auto simp: properties_loops_ge_mu)\n  with assms have \"seq (i + i mod lambda) = seq i\"\n    using properties_loop[where i=\"i + i mod lambda\" and j=\"i div lambda\"] by simp\n  from properties_distinct_contrapos[OF this] show ?thesis\n    by simp (meson dvd_eq_mod_eq_0 mod_less_divisor not_less properties_lambda_gt_0)\nqed simp\n\ntext (in properties) \\<open>\n\nThe program is split into three loops; we find @{term \"nu\"}, @{term\n\"mu\"} and @{term \"lambda\"} in that order.\n\n\\<close>\n\nsubsection\\<open> Finding \\<open>nu\\<close> \\<close>\n\ntext\\<open>\n\nThe state space of the program tracks each of the variables we wish to\ndiscover, and the current positions of the Tortoise and Hare.\n\n\\<close>\n\nrecord 'a state =\n  nu :: nat \\<comment> \\<open>\\<open>\\<nu>\\<close>\\<close>\n  m :: nat  \\<comment> \\<open>\\<open>\\<mu>\\<close>\\<close>\n  l :: nat  \\<comment> \\<open>\\<open>\\<lambda>\\<close>\\<close>\n  hare :: \"'a\"\n  tortoise :: \"'a\"\n\ncontext properties\nbegin\n\ntext\\<open>\n\nThe Hare proceeds at twice the speed of the Tortoise. The program\ntracks how many steps the Tortoise has taken in @{term \"nu\"}.\n\n\\<close>\n\ndefinition (in fx0) find_nu :: \"'a state \\<Rightarrow> 'a state\" where\n  \"find_nu \\<equiv>\n    (\\<lambda>s. s\\<lparr> nu := 1, tortoise := f(x0), hare := f(f(x0)) \\<rparr>) ;;\n    while (hare \\<^bold>\\<noteq> tortoise)\n          (\\<lambda>s. s\\<lparr> nu := nu s + 1, tortoise := f(tortoise s), hare := f(f(hare s)) \\<rparr>)\"\n\ntext\\<open>\n\nIf this program terminates, we expect \\<open>seq \\<circ> (nu\n\\<^bold>+ nu) \\<^bold>= seq \\<circ> nu\\<close> to hold in the final state.\n\nThe simplest approach to showing termination is to define a suitable\n\\<open>nu\\<close> in terms of \\<open>lambda\\<close> and \\<open>mu\\<close>, which also\ngives us an upper bound on the number of calls to \\<open>f\\<close>.\n\n\\<close>\n\ndefinition nu_witness :: nat where\n  \"nu_witness \\<equiv> mu + lambda - mu mod lambda\"\n\ntext\\<open>\n\nThis constant has the following useful properties:\n\n\\<close>\n\nlemma nu_witness_properties:\n  \"mu < nu_witness\"\n  \"nu_witness \\<le> lambda + mu\"\n  \"lambda dvd nu_witness\"\n  \"mu = 0 \\<Longrightarrow> nu_witness = lambda\"\nunfolding nu_witness_def\nusing properties_lambda_gt_0\napply (simp_all add: less_diff_conv divide_simps)\napply (metis minus_mod_eq_div_mult [symmetric] dvd_def mod_add_self2 mult.commute)\ndone\n\ntext\\<open>\n\nThese demonstrate that @{term \"nu_witness\"} has the key property:\n\n\\<close>\n\nlemma nu_witness:\n  shows \"seq (nu_witness + nu_witness) = seq nu_witness\"\nusing nu_witness_properties properties_loop\nby (clarsimp simp: dvd_def field_simps)\n\ntext\\<open>\n\nTermination amounts to showing that the Tortoise gets closer to @{term\n\"nu_witness\"} on each iteration of the loop.\n\n\\<close>\n\ndefinition find_nu_measure :: \"(nat \\<times> nat) set\" where\n  \"find_nu_measure \\<equiv> measure (\\<lambda>\\<nu>. nu_witness - \\<nu>)\"\n\nlemma find_nu_measure_wellfounded:\n  \"wf find_nu_measure\"\nby (simp add: find_nu_measure_def)\n\nlemma find_nu_measure_decreases:\n  assumes \"seq (\\<nu> + \\<nu>) \\<noteq> seq \\<nu>\"\n  assumes \"\\<nu> \\<le> nu_witness\"\n  shows \"(Suc \\<nu>, \\<nu>) \\<in> find_nu_measure\"\nusing nu_witness_properties nu_witness assms\nby (auto simp: find_nu_measure_def le_eq_less_or_eq)\n\ntext\\<open>\n\nThe remainder of the Hoare proof is straightforward.\n\n\\<close>\n\nlemma find_nu:\n  \"\\<lbrace>\\<langle>True\\<rangle>\\<rbrace> find_nu \\<lbrace>nu \\<^bold>\\<in> \\<langle>{0<..lambda + mu}\\<rangle> \\<^bold>\\<and> seq \\<circ> (nu \\<^bold>+ nu) \\<^bold>= seq \\<circ> nu \\<^bold>\\<and> hare \\<^bold>= seq \\<circ> nu\\<rbrace>\"\napply (simp add: find_nu_def)\napply (rule hoare_pre)\n apply (rule whileI[where I=\"nu \\<^bold>\\<in> \\<langle>{0<..nu_witness}\\<rangle> \\<^bold>\\<and> (\\<^bold>\\<forall>i. \\<langle>0 < i\\<rangle> \\<^bold>\\<and> \\<langle>i\\<rangle> \\<^bold>< nu \\<^bold>\\<longrightarrow> \\<langle>seq (i + i) \\<noteq> seq i\\<rangle>)\n                            \\<^bold>\\<and> tortoise \\<^bold>= seq \\<circ> nu \\<^bold>\\<and> hare \\<^bold>= seq \\<circ> (nu \\<^bold>+ nu)\"\n                       and r=\"inv_image find_nu_measure nu\"]\n             wp_intro)+\n    using nu_witness_properties nu_witness\n    apply (fastforce simp: le_eq_less_or_eq elim: less_SucE)\n   apply (simp add: find_nu_measure_wellfounded)\n  apply (simp add: find_nu_measure_decreases)\n apply (rule wp_intro)\nusing nu_witness_properties\napply auto\ndone\n\n\nsubsubsection\\<open> Side observations \\<close>\n\ntext\\<open>\n\nWe can also show termination ala \\citet{Filliatre:2007}.\n\n\\<close>\n\ndefinition find_nu_measures :: \"(nat \\<times> nat) set\" where\n  \"find_nu_measures \\<equiv>\n    measures [\\<lambda>\\<nu>. mu - \\<nu>, \\<lambda>\\<nu>. LEAST i. seq (\\<nu> + \\<nu> + i) = seq \\<nu>]\"\n\nlemma find_nu_measures_wellfounded:\n  \"wf find_nu_measures\"\nby (simp add: find_nu_measures_def)\n\nlemma find_nu_measures_existence:\n  assumes \\<nu>: \"mu \\<le> \\<nu>\"\n  shows \"\\<exists>i. seq (\\<nu> + \\<nu> + i) = seq \\<nu>\"\nproof(cases \"seq (\\<nu> + \\<nu>) = seq \\<nu>\")\n case False\n from properties_lambda_gt_0 obtain k where k: \"\\<nu> \\<le> k * lambda\"\n   by (metis One_nat_def Suc_leI mult.right_neutral mult_le_mono order_refl)\n from \\<nu> k have \"seq (\\<nu> + \\<nu> + (k * lambda - \\<nu>)) = seq (mu + (\\<nu> - mu) + k * lambda)\" by (simp add: field_simps)\n also from \\<nu> properties_loop have \"\\<dots> = seq \\<nu>\" by simp\n finally show ?thesis by blast\nqed (simp add: exI[where x=0])\n\nlemma find_nu_measures_decreases:\n  assumes \\<nu>: \"seq (\\<nu> + \\<nu>) \\<noteq> seq \\<nu>\"\n  shows \"(Suc \\<nu>, \\<nu>) \\<in> find_nu_measures\"\nproof(cases \"mu \\<le> \\<nu>\")\n  case True\n  then have \"mu \\<le> Suc \\<nu>\" by simp\n  have \"(LEAST i. seq (Suc \\<nu> + Suc \\<nu> + i) = seq (Suc \\<nu>)) < (LEAST i. seq (\\<nu> + \\<nu> + i) = seq \\<nu>)\"\n  proof(rule LeastI2_wellorder_ex[OF find_nu_measures_existence[OF \\<open>mu \\<le> Suc \\<nu>\\<close>]],\n        rule LeastI2_wellorder_ex[OF find_nu_measures_existence[OF \\<open>mu \\<le> \\<nu>\\<close>]])\n    fix x y\n    assume x: \"seq (Suc \\<nu> + Suc \\<nu> + x) = seq (Suc \\<nu>)\"\n              \"\\<forall>z. seq (Suc \\<nu> + Suc \\<nu> + z) = seq (Suc \\<nu>) \\<longrightarrow> x \\<le> z\"\n    assume y: \"seq (\\<nu> + \\<nu> + y) = seq \\<nu>\"\n    from \\<nu> \\<open>mu \\<le> \\<nu>\\<close> y have \"0 < y\" by (cases y) simp_all\n    with y have \"seq (Suc \\<nu> + Suc \\<nu> + (y - 1)) = seq (Suc \\<nu>)\" by (auto elim: seq_inj)\n    with \\<open>0 < y\\<close> spec[OF x(2), where x=\"y - 1\"] y show \"x < y\" by simp\n  qed\n  with True \\<nu> show ?thesis by (simp add: find_nu_measures_def)\nqed (auto simp: find_nu_measures_def)\n\nlemma \"find_nu_Filli\u00e2tre\":\n  \"\\<lbrace>\\<langle>True\\<rangle>\\<rbrace> find_nu \\<lbrace>\\<langle>0\\<rangle> \\<^bold>< nu \\<^bold>\\<and> seq \\<circ> (nu \\<^bold>+ nu) \\<^bold>= seq \\<circ> nu \\<^bold>\\<and> hare \\<^bold>= seq \\<circ> nu\\<rbrace>\"\napply (simp add: find_nu_def)\napply (rule hoare_pre)\n apply (rule whileI[where I=\"\\<langle>0\\<rangle> \\<^bold>< nu \\<^bold>\\<and> tortoise \\<^bold>= seq \\<circ> nu \\<^bold>\\<and> hare \\<^bold>= seq \\<circ> (nu \\<^bold>+ nu)\"\n                      and r=\"inv_image find_nu_measures nu\"]\n             wp_intro)+\n    apply clarsimp\n   apply (simp add: find_nu_measures_wellfounded)\n  apply (simp add: find_nu_measures_decreases)\n apply (rule wp_intro)\napply (simp add: properties_lambda_gt_0)\ndone\n\ntext\\<open>\n\nThis approach does not provide an upper bound on \\<open>nu\\<close> however.\n\n@{cite \"Harper:PiSML:2011\"} observes (in his \\S13.5.2) that if \\<open>mu\\<close> is zero then \\<open>nu = lambda\\<close>.\n\n\\<close>\n\nlemma Harper:\n  assumes \"mu = 0\"\n  shows \"\\<lbrace>\\<langle>True\\<rangle>\\<rbrace> find_nu \\<lbrace>nu \\<^bold>= \\<langle>lambda\\<rangle>\\<rbrace>\"\nby (rule hoare_post_imp[OF find_nu]) (fastforce simp: assms dvd_def dest: lambda_dvd_nu)\n\n\nsubsection\\<open> Finding \\<open>mu\\<close> \\label{sec:th-finding-mu} \\<close>\n\ntext\\<open>\n\nWe recover \\<open>mu\\<close> from \\<open>nu\\<close> by exploiting the fact that\nlambda divides @{term \"nu\"}: the Tortoise, reset to @{term \"x0\"}\nand the Hare, both now moving at the same speed, will meet at @{term\n\"mu\"}.\n\n\\<close>\n\nlemma mu_nu:\n  assumes si: \"seq (i + i) = seq i\"\n  assumes j: \"mu \\<le> j\"\n  shows \"seq (j + i) = seq j\"\nusing lambda_dvd_nu[OF si] properties_loop[OF j]\nby (clarsimp simp: dvd_def field_simps)\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 \\<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>nu \\<^bold>\\<in> \\<langle>{0<..lambda + mu}\\<rangle> \\<^bold>\\<and> seq \\<circ> (nu \\<^bold>+ nu) \\<^bold>= seq \\<circ> nu \\<^bold>\\<and> hare \\<^bold>= seq \\<circ> nu\\<rbrace>\n     find_mu\n   \\<lbrace>nu \\<^bold>\\<in> \\<langle>{0<..lambda + mu}\\<rangle> \\<^bold>\\<and> tortoise \\<^bold>= \\<langle>seq mu\\<rangle> \\<^bold>\\<and> m \\<^bold>= \\<langle>mu\\<rangle>\\<rbrace>\"\napply (simp add: find_mu_def)\napply (rule hoare_pre)\n apply (rule whileI[where I=\"nu \\<^bold>\\<in> \\<langle>{0<..lambda + mu}\\<rangle> \\<^bold>\\<and> seq \\<circ> (nu \\<^bold>+ nu) \\<^bold>= seq \\<circ> nu \\<^bold>\\<and> m \\<^bold>\\<le> \\<langle>mu\\<rangle>\n                           \\<^bold>\\<and> tortoise \\<^bold>= seq \\<circ> m \\<^bold>\\<and> hare \\<^bold>= seq \\<circ> (m \\<^bold>+ nu)\"\n                      and r=\"measure (\\<langle>mu\\<rangle> \\<^bold>- m)\"]\n             wp_intro)+\n    using properties_loops_ge_mu\n    apply (force dest: mu_nu simp: less_eq_Suc_le[symmetric])\n   apply simp\n  apply (force dest: mu_nu simp: le_eq_less_or_eq)\n apply (rule wp_intro)\napply simp\ndone\n\n\nsubsection\\<open> Finding \\<open>lambda\\<close> \\<close>\n\ntext\\<open>\n\nWith the Tortoise parked at @{term \"mu\"}, we find \\<open>lambda\\<close> by\nwalking the Hare around the loop.\n\n\\<close>\n\ndefinition (in fx0) find_lambda :: \"'a state \\<Rightarrow> 'a state\" where\n  \"find_lambda \\<equiv>\n    (\\<lambda>s. s\\<lparr> l := 1, hare := f (tortoise s) \\<rparr>) ;;\n    while (hare \\<^bold>\\<noteq> tortoise)\n          (\\<lambda>s. s\\<lparr> hare := f (hare s), l := l s + 1 \\<rparr>)\"\n\nlemma find_lambda:\n  \"\\<lbrace>nu \\<^bold>\\<in> \\<langle>{0<..lambda + mu}\\<rangle> \\<^bold>\\<and> tortoise \\<^bold>= \\<langle>seq mu\\<rangle> \\<^bold>\\<and> m \\<^bold>= \\<langle>mu\\<rangle>\\<rbrace>\n     find_lambda\n   \\<lbrace>nu \\<^bold>\\<in> \\<langle>{0<..lambda + mu}\\<rangle> \\<^bold>\\<and> l \\<^bold>= \\<langle>lambda\\<rangle> \\<^bold>\\<and> m \\<^bold>= \\<langle>mu\\<rangle>\\<rbrace>\"\napply (simp add: find_lambda_def)\napply (rule hoare_pre)\n apply (rule whileI[where I=\"nu \\<^bold>\\<in> \\<langle>{0<..lambda + mu}\\<rangle> \\<^bold>\\<and> l \\<^bold>\\<in> \\<langle>{0<..lambda}\\<rangle>\n                           \\<^bold>\\<and> tortoise \\<^bold>= \\<langle>seq mu\\<rangle> \\<^bold>\\<and> hare \\<^bold>= seq \\<circ> (\\<langle>mu\\<rangle> \\<^bold>+ l) \\<^bold>\\<and> m \\<^bold>= \\<langle>mu\\<rangle>\"\n                      and r=\"measure (\\<langle>lambda\\<rangle> \\<^bold>- l)\"]\n             wp_intro)+\n    using properties_lambda_gt_0 properties_mod_lambda[where i=\"mu + lambda\"] properties_distinct[where i=mu]\n    apply (fastforce simp: less_eq_Suc_le[symmetric])\n   apply simp\n  using properties_mod_lambda[where i=\"mu + lambda\"]\n  apply (fastforce simp: le_eq_less_or_eq)\n apply (rule wp_intro)\nusing properties_lambda_gt_0\napply simp\ndone\n\n\nsubsection\\<open> Top level \\<close>\n\ntext\\<open>\n\nThe complete program is simply the steps composed in order.\n\n\\<close>\n\ndefinition (in fx0) tortoise_hare :: \"'a state \\<Rightarrow> 'a state\" where\n  \"tortoise_hare \\<equiv> find_nu ;; find_mu ;; find_lambda\"\n\ntheorem tortoise_hare:\n  \"\\<lbrace>\\<langle>True\\<rangle>\\<rbrace> tortoise_hare \\<lbrace>nu \\<^bold>\\<in> \\<langle>{0<..lambda + mu}\\<rangle> \\<^bold>\\<and> l \\<^bold>= \\<langle>lambda\\<rangle> \\<^bold>\\<and> m \\<^bold>= \\<langle>mu\\<rangle>\\<rbrace>\"\nunfolding tortoise_hare_def\nby (rule find_nu find_mu find_lambda wp_intro)+\n\nend\n\ncorollary tortoise_hare_correct:\n  assumes s': \"s' = fx0.tortoise_hare f x arbitrary\"\n  shows \"fx0.properties f x (l s') (m s')\"\nusing assms properties.tortoise_hare[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\ntext\\<open>\n\nIsabelle can generate code from these definitions.\n\n\\<close>\n\nschematic_goal tortoise_hare_code[code]:\n  \"fx0.tortoise_hare f x = ?code\"\nunfolding fx0.tortoise_hare_def fx0.find_nu_def fx0.find_mu_def fx0.find_lambda_def fcomp_assoc[symmetric] fcomp_comp\nby (rule refl)\n\nexport_code fx0.tortoise_hare in SML\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/TortoiseHare/TortoiseHare.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8933094088947399, "lm_q2_score": 0.817574471748733, "lm_q1q2_score": 0.7303469680852899}}
{"text": "theory Pratt_Certificate\nimports\n  Complex_Main\n  \"../Lehmer/Lehmer\"\nbegin\n\nsection {* Pratt's Primality Certificates *}\ntext_raw {* \\label{sec:pratt} *}\n\ntext {*\n  This work formalizes Pratt's proof system as described in his article\n  ``Every Prime has a Succinct Certificate''\\cite{pratt1975certificate}.\n  The proof system makes use of two types of predicates:\n  \\begin{itemize}\n    \\item $\\text{Prime}(p)$: $p$ is a prime number\n    \\item $(p, a, x)$: @{text \"\\<forall>q \\<in> prime_factors(x). [a^((p - 1) div q) \\<noteq> 1] (mod p)\"}\n  \\end{itemize}\n  We represent these predicates with the following datatype:\n*}\n\ndatatype pratt = Prime nat | Triple nat nat nat\n\ntext {*\n  Pratt describes an inference system consisting of the axiom $(p, a, 1)$\n  and the following inference rules:\n  \\begin{itemize}\n  \\item R1: If we know that $(p, a, x)$ and @{text \"[a^((p - 1) div q) \\<noteq> 1] (mod p)\"} hold for some\n              prime number $q$ we can conclude $(p, a, qx)$ from that.\n  \\item R2: If we know that $(p, a, p - 1)$ and  @{text \"[a^(p - 1) = 1] (mod p)\"} hold, we can\n              infer $\\text{Prime}(p)$.\n  \\end{itemize}\n  Both rules follow from Lehmer's theorem as we will show later on.\n\n  A list of predicates (i.e., values of type @{type pratt}) is a \\emph{certificate}, if it is\n  built according to the inference system described above. I.e., a list @{term \"x # xs :: pratt list\"}\n  is a certificate if @{term \"xs :: pratt list\"} is a certificate and @{term \"x :: pratt\"} is\n  either an axiom or all preconditions of @{term \"x :: pratt\"} occur in @{term \"xs :: pratt list\"}.\n\n  We call a certificate @{term \"xs :: pratt list\"} a \\emph{certificate for @{term p}},\n  if @{term \"Prime p\"} occurs in @{term \"xs :: pratt list\"}.\n\n  The function @{text valid_cert} checks whether a list is a certificate.\n*}\n\nfun valid_cert :: \"pratt list \\<Rightarrow> bool\" where\n  \"valid_cert [] = True\"\n| R2: \"valid_cert (Prime p#xs) \\<longleftrightarrow> 1 < p \\<and> valid_cert xs\n    \\<and> (\\<exists> a . [a^(p - 1) = 1] (mod p) \\<and> Triple p a (p - 1) \\<in> set xs)\"\n| R1: \"valid_cert (Triple p a x # xs) \\<longleftrightarrow> 0 < x  \\<and> valid_cert xs \\<and> (x=1 \\<or>\n    (\\<exists>q y. x = q * y \\<and> Prime q \\<in> set xs \\<and> Triple p a y \\<in> set xs\n      \\<and> [a^((p - 1) div q) \\<noteq> 1] (mod p)))\"\n\ntext {*\n  We define a function @{term size_cert} to measure the size of a certificate, assuming\n  a binary encoding of numbers. We will use this to show that there is a certificate for a\n  prime number $p$ such that the size of the certificate is polynomially bounded in the size\n  of the binary representation of $p$.\n*}\nfun size_pratt :: \"pratt \\<Rightarrow> real\" where\n  \"size_pratt (Prime p) = log 2 p\" |\n  \"size_pratt (Triple p a x) = log 2 p + log 2 a + log 2 x\"\n\nfun size_cert :: \"pratt list \\<Rightarrow> real\" where\n  \"size_cert [] = 0\" |\n  \"size_cert (x # xs) = 1 + size_pratt x + size_cert xs\"\n\n\nsection {* Soundness *}\n\ntext {*\n  In Section \\ref{sec:pratt} we introduced the predicates $\\text{Prime}(p)$ and $(p, a, x)$.\n  In this section we show that for a certificate every predicate occuring in this certificate\n  holds. In particular, if $\\text{Prime}(p)$ occurs in a certificate, $p$ is prime.\n*}\n\nlemma prime_factors_one[simp]: shows \"prime_factors (Suc 0) = {}\"\n  by (auto simp add:prime_factors_altdef2_nat)\n\nlemma prime_factors_prime: fixes p :: nat assumes \"prime p\" shows \"prime_factors p = {p}\"\nproof\n  have \"0 < p\" using assms by auto\n  then show \"{p} \\<subseteq> prime_factors p\" using assms by (auto simp add:prime_factors_altdef2_nat)\n  { fix q assume \"q \\<in> prime_factors p\"\n    then have \"q dvd p\" \"prime q\" using `0<p` by (auto simp add:prime_factors_altdef2_nat)\n    with assms have \"q=p\" by (auto simp: prime_nat_def)\n    }\n  then\n  show \"prime_factors p \\<subseteq> {p}\" by auto\nqed\n\ntheorem pratt_sound:\n  assumes 1: \"valid_cert c\"\n  assumes 2: \"t \\<in> set c\"\n  shows \"(t = Prime p \\<longrightarrow> prime p) \\<and>\n         (t = Triple p a x \\<longrightarrow> ((\\<forall> q \\<in> prime_factors x . [a^((p - 1) div q) \\<noteq> 1] (mod p)) \\<and> 0<x))\"\nusing assms\nproof (induction c arbitrary: p a x t)\n  case Nil then show ?case by force\n  next\n  case (Cons y ys)\n  { assume \"y=Triple p a x\" \"x=1\"\n    then have \"(\\<forall> q \\<in> prime_factors x . [a^((p - 1) div q) \\<noteq> 1] (mod p)) \\<and> 0<x\" by simp\n    }\n  moreover\n  { assume x_y: \"y=Triple p a x\" \"x~=1\"\n    hence \"x>0\" using Cons.prems by auto\n    obtain q z where \"x=q*z\" \"Prime q \\<in> set ys \\<and> Triple p a z \\<in> set ys\"\n               and cong:\"[a^((p - 1) div q) \\<noteq> 1] (mod p)\" using Cons.prems x_y by auto\n    then have factors_IH:\"(\\<forall> r \\<in> prime_factors z . [a^((p - 1) div r) \\<noteq> 1] (mod p))\" \"prime q\" \"z>0\"\n      using Cons.IH Cons.prems `x>0` `y=Triple p a x` \n      by force+\n    then have \"prime_factors x = prime_factors z \\<union> {q}\"  using `x =q*z` `x>0`\n      by (simp add:prime_factors_product_nat prime_factors_prime)\n    then have \"(\\<forall> q \\<in> prime_factors x . [a^((p - 1) div q) \\<noteq> 1] (mod p)) \\<and> 0 < x\"\n      using factors_IH cong by (simp add: `x>0`)\n    }\n  ultimately have y_Triple:\"y=Triple p a x \\<Longrightarrow> (\\<forall> q \\<in> prime_factors x .\n                                                [a^((p - 1) div q) \\<noteq> 1] (mod p)) \\<and> 0<x\" by linarith\n  { assume y: \"y=Prime p\" \"p>2\" then\n    obtain a where a:\"[a^(p - 1) = 1] (mod p)\" \"Triple p a (p - 1) \\<in> set ys\"\n      using Cons.prems by auto\n    then have Bier:\"(\\<forall>q\\<in>prime_factors (p - 1). [a^((p - 1) div q) \\<noteq> 1] (mod p))\"\n      using Cons.IH Cons.prems(1) by (simp add:y(1))\n    then have \"prime p\" using lehmers_theorem[OF _ _a(1)] `p>2` by fastforce\n    }\n  moreover\n  { assume \"y=Prime p\" \"p=2\" hence \"prime p\" by simp }\n  moreover\n  { assume \"y=Prime p\" then have \"p>1\"  using Cons.prems  by simp }\n  ultimately have y_Prime:\"y = Prime p \\<Longrightarrow> prime p\" by linarith\n\n  show ?case\n  proof (cases \"t \\<in> set ys\")\n    case True\n      show ?thesis using Cons.IH[OF _ True] Cons.prems(1) by (cases y) auto\n    next\n    case False\n      thus ?thesis using Cons.prems(2) y_Prime y_Triple by force\n  qed\nqed\n\n\n\nsection {* Completeness *}\n\ntext {*\n  In this section we show completeness of Pratt's proof system, i.e., we show that for\n  every prime number $p$ there exists a certificate for $p$. We also give an upper\n  bound for the size of a minimal certificate\n\n  The prove we give is constructive. We assume that we have certificates for all prime\n  factors of $p - 1$ and use these to build a certificate for $p$ from that. It is\n  important to note that certificates can be concatenated.\n*}\n\nlemma valid_cert_appendI:\n  assumes \"valid_cert r\"\n  assumes \"valid_cert s\"\n  shows \"valid_cert (r @ s)\"\n  using assms\nproof (induction r)\n  case (Cons y ys) then show ?case by (cases y) auto\nqed simp\n\nlemma valid_cert_concatI: \"(\\<forall>x \\<in> set xs . valid_cert x) \\<Longrightarrow> valid_cert (concat xs)\"\n  by (induction xs) (auto simp add: valid_cert_appendI)\n\nlemma size_pratt_le:\n fixes d::real\n assumes \"\\<forall> x \\<in> set c. size_pratt x \\<le> d\"\n shows \"size_cert c \\<le> length c * (1 + d)\" using assms\n by (induction c) (simp_all add: real_of_nat_def algebra_simps)\n\nfun build_fpc :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> nat list \\<Rightarrow> pratt list\" where\n  \"build_fpc p a r [] = [Triple p a r]\" |\n  \"build_fpc p a r (y # ys) = Triple p a r # build_fpc p a (r div y) ys\"\n\ntext {*\n  The function @{term build_fpc} helps us to construct a certificate for $p$ from\n  the certificates for the prime factors of $p - 1$. Called as\n  @{term \"build_fpc p a (p - 1) qs\"} where $@{term \"qs\"} = q_1 \\ldots q_n$\n  is prime decomposition of $p - 1$ such that $q_1 \\cdot \\dotsb \\cdot q_n = @{term \"p - 1 :: nat\"}$,\n  it returns the following list of predicates:\n  \\[\n  (p,a,p-1), (p,a,\\frac{p - 1}{q_1}), (p,a,\\frac{p - 1}{q_1 q_2}), \\ldots, (p,a,\\frac{p-1}{q_1 \\ldots q_n}) = (p,a,1)\n  \\]\n\n  I.e., if there is an appropriate $a$ and and a certificate @{term rs} for all\n  prime factors of $p$, then we can construct a certificate for $p$ as\n  @{term [display] \"Prime p # build_fpc p a (p - 1) qs @ rs\"}\n*}\n\ntext {*\n  The following lemma shows that @{text \"build_fpc\"} extends a certificate that\n  satisfies the preconditions described before to a correct certificate.\n*}\n\nlemma correct_fpc:\n  assumes \"valid_cert xs\"\n  assumes \"listprod qs = r\" \"r \\<noteq> 0\"\n  assumes \"\\<forall> q \\<in> set qs . Prime q \\<in> set xs\"\n  assumes \"\\<forall> q \\<in> set qs . [a^((p - 1) div q) \\<noteq> 1] (mod p)\"\n  shows \"valid_cert (build_fpc p a r qs @ xs)\"\n  using assms\nproof (induction qs arbitrary: r)\n  case Nil thus ?case by auto\nnext\n  case (Cons y ys)\n  have \"listprod ys = r div y\" using Cons.prems by auto\n  then have T_in: \"Triple p a (listprod ys) \\<in> set (build_fpc p a (r div y) ys @ xs)\"\n    by (cases ys) auto\n\n  have \"valid_cert (build_fpc p a (r div y) ys @ xs)\"\n    using Cons.prems by (intro Cons.IH) auto\n  then have \"valid_cert (Triple p a r # build_fpc p a (r div y) ys @ xs)\"\n    using `r \\<noteq> 0` T_in Cons.prems by auto\n  then show ?case by simp\nqed\n\nlemma length_fpc:\n  \"length (build_fpc p a r qs) = length qs + 1\" by (induction qs arbitrary: r) auto\n\nlemma div_gt_0:\n  fixes m n :: nat assumes \"m \\<le> n\" \"0 < m\" shows \"0 < n div m\"\nproof -\n  have \"0 < m div m\" using `0 < m` div_self by auto\n  also have \"m div m \\<le> n div m\" using `m \\<le> n` by (rule div_le_mono)\n  finally show ?thesis .\nqed\n\nlemma size_pratt_fpc:\n  assumes \"a \\<le> p\" \"r \\<le> p\" \"0 < a\" \"0 < r\" \"0 < p\" \"listprod qs = r\"\n  shows \"\\<forall>x \\<in> set (build_fpc p a r qs) . size_pratt x \\<le> 3 * log 2 p\" using assms\nproof (induction qs arbitrary: r)\n  case Nil\n  then have \"log 2 a \\<le> log 2 p\" \"log 2 r \\<le> log 2 p\" by auto\n  then show ?case by simp\nnext\n  case (Cons q qs)\n  then have \"log 2 a \\<le> log 2 p\" \"log 2 r \\<le> log 2 p\" by auto\n  then have  \"log 2 a + log 2 r \\<le> 2 * log 2 p\" by arith\n  moreover have \"r div q > 0\" using Cons.prems by (fastforce intro: div_gt_0)\n  moreover hence \"listprod qs = r div q\" using Cons.prems(6) by auto\n  moreover have \"r div q \\<le> p\" using `r\\<le>p` div_le_dividend[of r q] by linarith\n  ultimately show ?case using Cons by simp\nqed\n\nlemma concat_set:\n  assumes \"\\<forall> q \\<in> qs . \\<exists> c \\<in> set cs . Prime q \\<in> set c\"\n  shows \"\\<forall> q \\<in> qs . Prime q \\<in> set (concat cs)\"\n  using assms by (induction cs) auto\n\nlemma p_in_prime_factorsE:\n  fixes n :: nat\n  assumes \"p \\<in> prime_factors n\" \"0 < n\"\n  obtains \"2 \\<le> p\" \"p \\<le> n\" \"p dvd n\" \"prime p\"\nproof\n  from assms show \"prime p\" by auto\n  then show \"2 \\<le> p\" by (auto dest: prime_gt_1_nat)\n\n  from assms show \"p dvd n\" by (intro prime_factors_dvd_nat)\n  then show \"p \\<le> n\" using  `0 < n` by (rule dvd_imp_le)\nqed\n\nlemma prime_factors_list_prime:\n  fixes n :: nat\n  assumes \"prime n\"\n  shows \"\\<exists> qs. prime_factors n = set qs \\<and> listprod qs = n \\<and> length qs = 1\"\nproof -\n    have \"prime_factors n = set [n]\" using prime_factors_prime assms by force\n    thus ?thesis by fastforce\nqed\n\nlemma prime_factors_list:\n  fixes n :: nat assumes \"3 < n\" \"\\<not> prime n\"\n  shows \"\\<exists> qs. prime_factors n = set qs \\<and> listprod qs = n \\<and> length qs \\<ge> 2\"\n  using assms\nproof (induction n rule: less_induct)\n  case (less n)\n    obtain p where \"p \\<in> prime_factors n\" using `n > 3` prime_factors_elem by force\n    then have p':\"2 \\<le> p\" \"p \\<le> n\" \"p dvd n\" \"prime p\"\n      using `3 < n` by (auto elim: p_in_prime_factorsE)\n    { assume \"n div p > 3\" \"\\<not> prime (n div p)\"\n      then obtain qs\n        where \"prime_factors (n div p) = set qs\" \"listprod qs = (n div p)\" \"length qs \\<ge> 2\"\n        using p' by atomize_elim (auto intro: less simp: div_gt_0)\n      moreover\n      have \"prime_factors (p * (n div p)) = insert p (prime_factors (n div p))\"\n        using `3 < n` `2 \\<le> p` `p \\<le> n` `prime p`\n      by (auto simp: prime_factors_product_nat div_gt_0 prime_factors_prime)\n      ultimately\n      have \"prime_factors n = set (p # qs)\" \"listprod (p # qs) = n\" \"length (p#qs) \\<ge> 2\"\n        using `p dvd n` by (simp_all add: dvd_mult_div_cancel)\n      hence ?case by blast\n    }\n    moreover\n    { assume \"prime (n div p)\"\n      then obtain qs\n        where \"prime_factors (n div p) = set qs\" \"listprod qs = (n div p)\" \"length qs = 1\"\n        using prime_factors_list_prime by blast\n      moreover\n      have \"prime_factors (p * (n div p)) = insert p (prime_factors (n div p))\"\n        using `3 < n` `2 \\<le> p` `p \\<le> n` `prime p`\n      by (auto simp: prime_factors_product_nat div_gt_0 prime_factors_prime)\n      ultimately\n      have \"prime_factors n = set (p # qs)\" \"listprod (p # qs) = n\" \"length (p#qs) \\<ge> 2\"\n        using `p dvd n` by (simp_all add: dvd_mult_div_cancel)\n      hence ?case by blast\n    } note case_prime = this\n    moreover\n    { assume \"n div p = 1\"\n      hence \"n = p\" using `n>3`  using One_leq_div[OF `p dvd n`] p'(2) by force\n      hence ?case using `prime p` `\\<not> prime n` by auto\n    }\n    moreover\n    { assume \"n div p = 2\"\n      hence ?case using case_prime by force\n    }\n    moreover\n    { assume \"n div p = 3\"\n      hence ?case using p' case_prime by force\n    }\n    ultimately show ?case using p' div_gt_0[of p n] case_prime by fastforce\n\nqed\n\nlemma listprod_ge:\n  fixes xs::\"nat list\"\n  assumes \"\\<forall> x \\<in> set xs . x \\<ge> 1\"\n  shows \"listprod xs \\<ge> 1\" using assms by (induction xs) auto\n\nlemma listsum_log:\n  fixes b::real\n  fixes xs::\"nat list\"\n  assumes b: \"b > 0\" \"b \\<noteq> 1\"\n  assumes xs:\"\\<forall> x \\<in> set xs . x \\<ge> b\"\n  shows \"(\\<Sum>x\\<leftarrow>xs. log b x) = log b (listprod xs)\"\n  using assms\nproof (induction xs)\n  case Nil\n    thus ?case by simp\n  next\n  case (Cons y ys)\n    have \"real (listprod ys) > 0\" using listprod_ge Cons.prems by fastforce\n    thus ?case using log_mult[OF Cons.prems(1-2)] Cons by force\nqed\n\nlemma concat_length_le:\n  fixes g :: \"nat \\<Rightarrow> real\"\n  assumes \"\\<forall> x \\<in> set xs . real (length (f x)) \\<le> g x\"\n  shows \"length (concat (map f xs)) \\<le> (\\<Sum>x\\<leftarrow>xs. g x)\" using assms\n  by (induction xs) force+\n\n(* XXX move *)\nlemma powr_realpow_numeral: \"0 < x \\<Longrightarrow> x powr (numeral n :: real) = x^(numeral n)\"\n  unfolding real_of_nat_numeral[symmetric] by (rule powr_realpow)\n\nlemma prime_gt_3_impl_p_minus_one_not_prime:\n  fixes p::nat\n  assumes \"prime p\" \"p>3\"\n  shows \"\\<not> prime (p - 1)\"\nproof\n  assume \"prime (p - 1)\"\n  have \"\\<not> even p\" using assms by (simp add: prime_odd_nat)\n  hence \"2 dvd (p - 1)\" by presburger\n  hence \"2 \\<in> prime_factors (p - 1)\" using `p>3` by (auto simp: prime_factors_altdef2_nat)\n  thus False using prime_factors_prime `p>3` `prime (p - 1)` by auto\nqed\n\ntext {*\n  We now prove that Pratt's proof system is complete and derive upper bounds for\n  the length and the size of the entries of a minimal certificate.\n*}\n\ntheorem pratt_complete':\n  assumes \"prime p\"\n  shows \"\\<exists>c. Prime p \\<in> set c \\<and> valid_cert c \\<and> length c \\<le> 6*log 2 p - 4 \\<and> (\\<forall> x \\<in> set c. size_pratt x \\<le> 3 * log 2 p)\" using assms\nproof (induction p rule: less_induct)\n  case (less p)\n  { assume [simp]: \"p = 2\"\n    have \"Prime p \\<in> set [Prime 2, Triple 2 1 1]\" by simp\n    then have ?case by fastforce }\n  moreover\n  { assume [simp]: \"p = 3\"\n    let ?cert = \"[Prime 3, Triple 3 2 2, Triple 3 2 1, Prime 2, Triple 2 1 1]\"\n\n    have \"length ?cert \\<le> 6*log 2 p - 4\n          \\<longleftrightarrow> 2 powr 9 \\<le> 2 powr (log 2 p * 6)\" by auto\n    also have \"\\<dots> \\<longleftrightarrow> True\"\n      by (simp add: powr_powr[symmetric] powr_realpow_numeral)\n    finally have ?case\n      by (intro exI[where x=\"?cert\"]) (simp add: cong_nat_def)\n  }\n  moreover\n  { assume \"p > 3\"\n\n    have \"\\<forall>q \\<in> prime_factors (p - 1) . q < p\" using `prime p`\n      by (fastforce elim: p_in_prime_factorsE)\n    hence factor_certs:\"\\<forall>q \\<in> prime_factors (p - 1) . (\\<exists>c . ((Prime q \\<in> set c) \\<and> (valid_cert c)\n                                                      \\<and> length c \\<le> 6*log 2 q - 4) \\<and> (\\<forall> x \\<in> set c. size_pratt x \\<le> 3 * log 2 q))\"\n      by (auto intro: less.IH)\n    obtain a where a:\"[a^(p - 1) = 1] (mod p) \\<and> (\\<forall> q. q \\<in> prime_factors (p - 1)\n              \\<longrightarrow> [a^((p - 1) div q) \\<noteq> 1] (mod p))\" and a_size: \"a > 0\" \"a < p\"\n      using converse_lehmer[OF `prime p`] by blast\n\n    have \"\\<not> prime (p - 1)\" using `p>3` prime_gt_3_impl_p_minus_one_not_prime `prime p` by auto\n    have \"p \\<noteq> 4\" using `prime p` by auto\n    hence \"p - 1 > 3\" using `p > 3` by auto\n\n    then obtain qs where prod_qs_eq:\"listprod qs = p - 1\"\n        and qs_eq:\"set qs = prime_factors (p - 1)\" and qs_length_eq: \"length qs \\<ge> 2\"\n      using prime_factors_list[OF _ `\\<not> prime (p - 1)`] by auto\n    obtain f where f:\"\\<forall>q \\<in> prime_factors (p - 1) . \\<exists> c. f q = c\n                     \\<and> ((Prime q \\<in> set c) \\<and> (valid_cert c) \\<and> length c \\<le> 6*log 2 q - 4)\n                     \\<and> (\\<forall> x \\<in> set c. size_pratt x \\<le> 3 * log 2 q)\"\n      using factor_certs by metis\n    let ?cs = \"map f qs\"\n    have cs: \"\\<forall>q \\<in> prime_factors (p - 1) . (\\<exists>c \\<in> set ?cs . (Prime q \\<in> set c) \\<and> (valid_cert c)\n                                           \\<and> length c \\<le> 6*log 2 q - 4\n                                           \\<and> (\\<forall> x \\<in> set c. size_pratt x \\<le> 3 * log 2 q))\"\n      using f qs_eq by auto\n\n    have cs_cert_size: \"\\<forall>c \\<in> set ?cs . \\<forall> x \\<in> set c. size_pratt x \\<le> 3 * log 2 p\"\n    proof\n      fix c assume \"c \\<in> set (map f qs)\"\n      then obtain q where \"c = f q\" and \"q \\<in> set qs\" by auto\n      hence *:\"\\<forall> x \\<in> set c. size_pratt x \\<le> 3 * log 2 q\" using f qs_eq by blast\n      have \"q < p\" \"q > 0\" using `\\<forall>q \\<in> prime_factors (p - 1) . q < p` `q \\<in> set qs` qs_eq by fast+\n      show \"\\<forall> x \\<in> set c. size_pratt x \\<le> 3 * log 2 p\"\n      proof\n        fix x assume \"x \\<in> set c\"\n        hence \"size_pratt x \\<le> 3 * log 2 q\" using * by fastforce\n        also have \"\\<dots> \\<le> 3 * log 2 p\" using `q < p` `q > 0` `p > 3` by simp\n        finally show \"size_pratt x \\<le> 3 * log 2 p\" .\n      qed\n    qed\n\n    have cs_valid_all: \"\\<forall>c \\<in> set ?cs . valid_cert c\"\n      using f qs_eq by fastforce\n\n    have \"\\<forall>x \\<in> set (build_fpc p a (p - 1) qs). size_pratt x \\<le> 3 * log 2 p\"\n      using cs_cert_size a_size `p > 3` prod_qs_eq by (intro size_pratt_fpc) auto\n    hence \"\\<forall>x \\<in> set (build_fpc p a (p - 1) qs @ concat ?cs) . size_pratt x \\<le> 3 * log 2 p\"\n      using cs_cert_size by auto\n    moreover\n    have \"Triple p a (p - 1) \\<in> set (build_fpc p a (p - 1) qs @ concat ?cs)\" by (cases qs) auto\n    moreover\n    have \"valid_cert ((build_fpc p a (p - 1) qs)@ concat ?cs)\"\n    proof (rule correct_fpc)\n      show \"valid_cert (concat ?cs)\"\n        using cs_valid_all by (auto simp: valid_cert_concatI)\n      show \"listprod qs = p - 1\" by (rule prod_qs_eq)\n      show \"p - 1 \\<noteq> 0\" using prime_gt_1_nat[OF `prime p`] by arith\n      show \"\\<forall> q \\<in> set qs . Prime q \\<in> set (concat ?cs)\"\n        using concat_set[of \"prime_factors (p - 1)\"] cs qs_eq by blast\n      show \"\\<forall> q \\<in> set qs . [a^((p - 1) div q) \\<noteq> 1] (mod p)\" using qs_eq a by auto\n    qed\n    moreover\n    { let ?k = \"length qs\"\n\n      have qs_ge_2:\"\\<forall>q \\<in> set qs . q \\<ge> 2\" using qs_eq\n        by (simp add: prime_factors_prime_nat prime_ge_2_nat)\n\n      have \"\\<forall>x\\<in>set qs. real (length (f x)) \\<le> 6 * log 2 (real x) - 4\" using f qs_eq by blast\n      hence \"length (concat ?cs) \\<le> (\\<Sum>q\\<leftarrow>qs. 6*log 2 q - 4)\" using concat_length_le\n        by fast\n      hence \"length (Prime p # ((build_fpc p a (p - 1) qs)@ concat ?cs))\n            \\<le> ((\\<Sum>q\\<leftarrow>(map real qs). 6*log 2 q - 4) + ?k + 2)\"\n            by (simp add: o_def length_fpc)\n      also have \"\\<dots> = (6*(\\<Sum>q\\<leftarrow>(map real qs). log 2 q) + (-4 * real ?k) + ?k + 2)\"\n        by (simp add: o_def listsum_subtractf listsum_triv real_of_nat_def listsum_const_mult)\n      also have \"\\<dots> \\<le> 6*log 2 (p - 1) - 4\" using `?k\\<ge>2` prod_qs_eq listsum_log[of 2 qs] qs_ge_2\n        by force\n      also have \"\\<dots> \\<le> 6*log 2 p - 4\" using log_le_cancel_iff[of 2 \"p - 1\" p] `p>3` by force\n      ultimately have \"length (Prime p # ((build_fpc p a (p - 1) qs)@ concat ?cs))\n                       \\<le> 6*log 2 p - 4\" by linarith }\n    ultimately obtain c where c:\"Triple p a (p - 1) \\<in> set c\" \"valid_cert c\"\n                               \"length (Prime p #c) \\<le> 6*log 2 p - 4\"\n                               \"(\\<forall> x \\<in> set c. size_pratt x \\<le> 3 * log 2 p)\" by blast\n    hence \"Prime p \\<in> set (Prime p # c)\" \"valid_cert (Prime p # c)\"\n         \"(\\<forall> x \\<in> set (Prime p # c). size_pratt x \\<le> 3 * log 2 p)\"\n    using a `prime p` by auto\n    hence ?case using c by blast\n  }\n  moreover have \"p\\<ge>2\" using less by (simp add: prime_ge_2_nat)\n  ultimately show ?case using less by fastforce\nqed\n\ntext {*\n  We now recapitulate our results. A number $p$ is prime if and only if there\n  is a certificate for $p$. Moreover, for a prime $p$ there always is a certificate\n  whose size is polynomially bounded in the logarithm of $p$.\n*}\n\ncorollary pratt:\n  \"prime p \\<longleftrightarrow> (\\<exists>c. Prime p \\<in> set c \\<and> valid_cert c)\"\n  using pratt_complete' pratt_sound(1) by blast\n\ncorollary pratt_size:\n  assumes \"prime p\"\n  shows \"\\<exists>c. Prime p \\<in> set c \\<and> valid_cert c \\<and> size_cert c \\<le> (6 * log 2 p - 4) * (1 + 3 * log 2 p)\"\nproof -\n  obtain c where c: \"Prime p \\<in> set c\" \"valid_cert c\"\n      and len: \"length c \\<le> 6*log 2 p - 4\" and \"(\\<forall> x \\<in> set c. size_pratt x \\<le> 3 * log 2 p)\"\n    using pratt_complete' assms by blast\n  hence \"size_cert c \\<le> length c * (1 + 3 * log 2 p)\" by (simp add: size_pratt_le)\n  also have \"\\<dots> \\<le> (6*log 2 p - 4) * (1 + 3 * log 2 p)\" using len by simp\n  finally show ?thesis using c by blast\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/Pratt_Certificate/Pratt_Certificate.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8740772351648677, "lm_q2_score": 0.8354835371034368, "lm_q1q2_score": 0.7302771401371362}}
{"text": "section \"Amortized Complexity (Unary Operations)\"\n\ntheory Amortized_Framework0\nimports Complex_Main\nbegin\n\ntext\\<open>\nThis theory provides a simple amortized analysis framework where all operations\nact on a single data type, i.e. no union-like operations. This is the basis of\nthe ITP 2015 paper by Nipkow. Although it is superseded by the model in\n\\<open>Amortized_Framework\\<close> that allows arbitrarily many parameters, it is still\nof interest because of its simplicity.\\<close>\n\nlocale Amortized =\nfixes init :: \"'s\"\nfixes nxt :: \"'o \\<Rightarrow> 's \\<Rightarrow> 's\"\nfixes inv :: \"'s \\<Rightarrow> bool\"\nfixes T :: \"'o \\<Rightarrow> 's \\<Rightarrow> real\"\nfixes \\<Phi> :: \"'s \\<Rightarrow> real\"\nfixes U :: \"'o \\<Rightarrow> 's \\<Rightarrow> real\"\nassumes inv_init: \"inv init\"\nassumes inv_nxt: \"inv s \\<Longrightarrow> inv(nxt f s)\"\nassumes ppos: \"inv s \\<Longrightarrow> \\<Phi> s \\<ge> 0\"\nassumes p0: \"\\<Phi> init = 0\"\nassumes U: \"inv s \\<Longrightarrow> T f s + \\<Phi>(nxt f s) - \\<Phi> s \\<le> U f s\"\nbegin\n\nfun state :: \"(nat \\<Rightarrow> 'o) \\<Rightarrow> nat \\<Rightarrow> 's\" where\n\"state f 0 = init\" |\n\"state f (Suc n) = nxt (f n) (state f n)\"\n\nlemma inv_state: \"inv(state f n)\"\nby(induction n)(simp_all add: inv_init inv_nxt)\n\ndefinition A :: \"(nat \\<Rightarrow> 'o) \\<Rightarrow> nat \\<Rightarrow> real\" where\n\"A f i = T (f i) (state f i) + \\<Phi>(state f (i+1)) - \\<Phi>(state f i)\"\n\nlemma aeq: \"(\\<Sum>i<n. T (f i) (state f i)) = (\\<Sum>i<n. A f i) - \\<Phi>(state f n)\"\napply(induction n)\napply (simp add: p0)\napply (simp add: A_def)\ndone\n\ncorollary TA: \"(\\<Sum>i<n. T (f i) (state f i)) \\<le> (\\<Sum>i<n. A f i)\"\nby (metis add.commute aeq diff_add_cancel le_add_same_cancel2 ppos[OF inv_state])\n\nlemma aa1: \"A f i \\<le> U (f i) (state f i)\"\nby(simp add: A_def U inv_state)\n\nlemma ub: \"(\\<Sum>i<n. T (f i) (state f i)) \\<le> (\\<Sum>i<n. U (f i) (state f i))\"\nby (metis (mono_tags) aa1 order.trans sum_mono TA)\n\nend\n\n\nsubsection \"Binary Counter\"\n\nlocale BinCounter\nbegin\n\nfun incr where\n\"incr [] = [True]\" |\n\"incr (False#bs) = True # bs\" |\n\"incr (True#bs) = False # incr bs\"\n\nfun T_incr :: \"bool list \\<Rightarrow> real\" where\n\"T_incr [] = 1\" |\n\"T_incr (False#bs) = 1\" |\n\"T_incr (True#bs) = T_incr bs + 1\"\n\ndefinition \\<Phi> :: \"bool list \\<Rightarrow> real\" where\n\"\\<Phi> bs = length(filter id bs)\"\n\nlemma A_incr: \"T_incr bs + \\<Phi>(incr bs) - \\<Phi> bs = 2\"\napply(induction bs rule: incr.induct)\napply (simp_all add: \\<Phi>_def)\ndone\n\ninterpretation incr: Amortized\nwhere init = \"[]\" and nxt = \"%_. incr\" and inv = \"\\<lambda>_. True\"\nand T = \"\\<lambda>_. T_incr\" and \\<Phi> = \\<Phi> and U = \"\\<lambda>_ _. 2\"\nproof (standard, goal_cases)\n  case 1 show ?case by simp\nnext\n  case 2 show ?case by simp\nnext\n  case 3 show ?case by(simp add: \\<Phi>_def)\nnext\n  case 4 show ?case by(simp add: \\<Phi>_def)\nnext\n  case 5 show ?case by(simp add: A_incr)\nqed\n\nthm incr.ub\n\nend\n\nsubsection \"Dynamic tables: insert only\"\n\nlocale DynTable1\nbegin\n\nfun ins :: \"nat*nat \\<Rightarrow> nat*nat\" where\n\"ins (n,l) = (n+1, if n<l then l else if l=0 then 1 else 2*l)\"\n\nfun T_ins :: \"nat*nat \\<Rightarrow> real\" where\n\"T_ins (n,l) = (if n<l then 1 else n+1)\"\n\nfun invar :: \"nat*nat \\<Rightarrow> bool\" where\n\"invar (n,l) = (l/2 \\<le> n \\<and> n \\<le> l)\"\n\nfun \\<Phi> :: \"nat*nat \\<Rightarrow> real\" where\n\"\\<Phi> (n,l) = 2*(real n) - l\"\n\ninterpretation ins: Amortized\nwhere init = \"(0::nat,0::nat)\"\nand nxt = \"\\<lambda>_. ins\"\nand inv = invar\nand T = \"\\<lambda>_. T_ins\" and \\<Phi> = \\<Phi> and U = \"\\<lambda>_ _. 3\"\nproof (standard, goal_cases)\n  case 1 show ?case by auto\nnext\n  case (2 s) thus ?case by(cases s) auto\nnext\n  case (3 s) thus ?case by(cases s)(simp split: if_splits)\nnext\n  case 4 show ?case by(simp)\nnext\n  case (5 s) thus ?case by(cases s) auto\nqed\n\nend\n\nlocale table_insert = DynTable1 +\nfixes a :: real\nfixes c :: real\nassumes c1[arith]: \"c > 1\" \nassumes ac2: \"a \\<ge> c/(c - 1)\"\nbegin\n\nlemma ac: \"a \\<ge> 1/(c - 1)\"\nusing ac2 by(simp add: field_simps)\n\nlemma a0[arith]: \"a>0\"\nproof-\n  have \"1/(c - 1) > 0\" using ac by simp\n  thus ?thesis by (metis ac dual_order.strict_trans1)\nqed\n\ndefinition \"b = 1/(c - 1)\"\n\nlemma b0[arith]: \"b > 0\"\nusing ac by (simp add: b_def)\n\nfun \"ins\" :: \"nat * nat \\<Rightarrow> nat * nat\" where\n\"ins(n,l) = (n+1, if n<l then l else if l=0 then 1 else nat(ceiling(c*l)))\"\n\nfun pins :: \"nat * nat => real\" where\n\"pins(n,l) = a*n - b*l\"\n\ninterpretation ins: Amortized\nwhere init = \"(0,0)\" and nxt = \"%_. ins\"\nand inv = \"\\<lambda>(n,l). if l=0 then n=0 else n \\<le> l \\<and> (b/a)*l \\<le> n\"\nand T = \"\\<lambda>_. T_ins\" and \\<Phi> = pins and U = \"\\<lambda>_ _. a + 1\"\nproof (standard, goal_cases)\n  case 1 show ?case by auto\nnext\n  case (2 s)\n  show ?case\n  proof (cases s)\n    case [simp]: (Pair n l)\n    show ?thesis\n    proof cases\n      assume \"l=0\" thus ?thesis using 2 ac\n        by (simp add: b_def field_simps)\n    next\n      assume \"l\\<noteq>0\"\n      show ?thesis\n      proof cases\n        assume \"n<l\"\n        thus ?thesis using 2 by(simp add: algebra_simps)\n      next\n        assume \"\\<not> n<l\"\n        hence [simp]: \"n=l\" using 2 \\<open>l\\<noteq>0\\<close> by simp\n        have 1: \"(b/a) * ceiling(c * l) \\<le> real l + 1\"\n        proof-\n          have \"(b/a) * ceiling(c * l) = ceiling(c * l)/(a*(c - 1))\"\n            by(simp add: b_def)\n          also have \"ceiling(c * l) \\<le> c*l + 1\" by simp\n          also have \"\\<dots> \\<le> c*(real l+1)\" by (simp add: algebra_simps)\n          also have \"\\<dots> / (a*(c - 1)) = (c/(a*(c - 1))) * (real l + 1)\" by simp\n          also have \"c/(a*(c - 1)) \\<le> 1\" using ac2 by (simp add: field_simps)\n          finally show ?thesis by (simp add: divide_right_mono)\n        qed\n        have 2: \"real l + 1 \\<le> ceiling(c * real l)\"\n        proof-\n          have \"real l + 1 = of_int(int(l)) + 1\" by simp\n          also have \"... \\<le> ceiling(c * real l)\" using \\<open>l \\<noteq> 0\\<close>\n            by(simp only: int_less_real_le[symmetric] less_ceiling_iff)\n              (simp add: mult_less_cancel_right1)\n          finally show ?thesis .\n        qed\n        from \\<open>l\\<noteq>0\\<close> 1 2 show ?thesis by simp (simp add: not_le zero_less_mult_iff)\n      qed\n    qed\n  qed\nnext\n  case (3 s) thus ?case by(cases s)(simp add: field_simps split: if_splits)\nnext\n  case 4 show ?case by(simp)\nnext\n  case (5 s)\n  show ?case\n  proof (cases s)\n    case [simp]: (Pair n l)\n    show ?thesis\n    proof cases\n      assume \"l=0\" thus ?thesis using 5 by (simp)\n    next\n      assume [arith]: \"l\\<noteq>0\"\n      show ?thesis\n      proof cases\n        assume \"n<l\"\n        thus ?thesis using 5 ac by(simp add: algebra_simps b_def)\n      next\n        assume \"\\<not> n<l\"\n        hence [simp]: \"n=l\" using 5 by simp\n        have \"T_ins s + pins (ins s) - pins s = l + a + 1 + (- b*ceiling(c*l)) + b*l\"\n          using \\<open>l\\<noteq>0\\<close>\n          by(simp add: algebra_simps less_trans[of \"-1::real\" 0])\n        also have \"- b * ceiling(c*l) \\<le> - b * (c*l)\" by (simp add: ceiling_correct)\n        also have \"l + a + 1 + - b*(c*l) + b*l = a + 1 + l*(1 - b*(c - 1))\"\n          by (simp add: algebra_simps)\n        also have \"b*(c - 1) = 1\" by(simp add: b_def)\n        also have \"a + 1 + (real l)*(1 - 1) = a+1\" by simp\n        finally show ?thesis by simp\n      qed\n    qed\n  qed\nqed\n\nthm ins.ub\n\nend\n\nsubsection \"Stack with multipop\"\n\ndatatype 'a op\\<^sub>s\\<^sub>t\\<^sub>k = Push 'a | Pop nat\n\nfun nxt_stk :: \"'a op\\<^sub>s\\<^sub>t\\<^sub>k \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where\n\"nxt_stk (Push x) xs = x # xs\" |\n\"nxt_stk (Pop n) xs = drop n xs\"\n\nfun T_stk :: \"'a op\\<^sub>s\\<^sub>t\\<^sub>k \\<Rightarrow> 'a list \\<Rightarrow> real\" where\n\"T_stk (Push x) xs = 1\" |\n\"T_stk (Pop n) xs = min n (length xs)\"\n\n\ninterpretation stack: Amortized\nwhere init = \"[]\" and nxt = nxt_stk and inv = \"\\<lambda>_. True\"\nand T = T_stk and \\<Phi> = \"length\" and U = \"\\<lambda>f _. case f of Push _ \\<Rightarrow> 2 | Pop _ \\<Rightarrow> 0\"\nproof (standard, goal_cases)\n  case 1 show ?case by auto\nnext\n  case (2 s) thus ?case by(cases s) auto\nnext\n  case 3 thus ?case by simp\nnext\n  case 4 show ?case by(simp)\nnext\n  case (5 _ f) thus ?case by (cases f) auto\nqed\n\n\nsubsection \"Queue\"\n\ntext\\<open>See, for example, the book by Okasaki~\\<^cite>\\<open>\"Okasaki\"\\<close>.\\<close>\n\ndatatype 'a op\\<^sub>q = Enq 'a | Deq\n\ntype_synonym 'a queue = \"'a list * 'a list\"\n\nfun nxt_q :: \"'a op\\<^sub>q \\<Rightarrow> 'a queue \\<Rightarrow> 'a queue\" where\n\"nxt_q (Enq x) (xs,ys) = (x#xs,ys)\" |\n\"nxt_q Deq (xs,ys) = (if ys = [] then ([], tl(rev xs)) else (xs,tl ys))\"\n\nfun T_q :: \"'a op\\<^sub>q \\<Rightarrow> 'a queue \\<Rightarrow> real\" where\n\"T_q (Enq x) (xs,ys) = 1\" |\n\"T_q Deq (xs,ys) = (if ys = [] then length xs else 0)\"\n\n\ninterpretation queue: Amortized\nwhere init = \"([],[])\" and nxt = nxt_q and inv = \"\\<lambda>_. True\"\nand T = T_q and \\<Phi> = \"\\<lambda>(xs,ys). length xs\" and U = \"\\<lambda>f _. case f of Enq _ \\<Rightarrow> 2 | Deq \\<Rightarrow> 0\"\nproof (standard, goal_cases)\n  case 1 show ?case by auto\nnext\n  case (2 s) thus ?case by(cases s) auto\nnext\n  case (3 s) thus ?case by(cases s) auto\nnext\n  case 4 show ?case by(simp)\nnext\n  case (5 s f) thus ?case\n    apply(cases s)\n    apply(cases f)\n    by auto\nqed\n\n\nfun balance :: \"'a queue \\<Rightarrow> 'a queue\" where\n\"balance(xs,ys) = (if size xs \\<le> size ys then (xs,ys) else ([], ys @ rev xs))\"\n\nfun nxt_q2 :: \"'a op\\<^sub>q \\<Rightarrow> 'a queue \\<Rightarrow> 'a queue\" where\n\"nxt_q2 (Enq a) (xs,ys) = balance (a#xs,ys)\" |\n\"nxt_q2 Deq (xs,ys) = balance (xs, tl ys)\"\n\nfun T_q2 :: \"'a op\\<^sub>q \\<Rightarrow> 'a queue \\<Rightarrow> real\" where\n\"T_q2 (Enq _) (xs,ys) = 1 + (if size xs + 1 \\<le> size ys then 0 else size xs + 1 + size ys)\" |\n\"T_q2 Deq (xs,ys) = (if size xs \\<le> size ys - 1 then 0 else size xs + (size ys - 1))\"\n\n\ninterpretation queue2: Amortized\nwhere init = \"([],[])\" and nxt = nxt_q2\nand inv = \"\\<lambda>(xs,ys). size xs \\<le> size ys\"\nand T = T_q2 and \\<Phi> = \"\\<lambda>(xs,ys). 2 * size xs\"\nand U = \"\\<lambda>f _. case f of Enq _ \\<Rightarrow> 3 | Deq \\<Rightarrow> 0\"\nproof (standard, goal_cases)\n  case 1 show ?case by auto\nnext\n  case (2 s f) thus ?case by(cases s) (cases f, auto)\nnext\n  case (3 s) thus ?case by(cases s) auto\nnext\n  case 4 show ?case by(simp)\nnext\n  case (5 s f) thus ?case\n    apply(cases s)\n    apply(cases f)\n    by (auto simp: split: prod.splits)\nqed\n\n\nsubsection \"Dynamic tables: insert and delete\"\n\ndatatype op\\<^sub>t\\<^sub>b = Ins | Del\n\nlocale DynTable2 = DynTable1\nbegin\n\nfun del :: \"nat*nat \\<Rightarrow> nat*nat\" where\n\"del (n,l) = (n - 1, if n=1 then 0 else if 4*(n - 1)<l then l div 2 else l)\"\n\nfun T_del :: \"nat*nat \\<Rightarrow> real\" where\n\"T_del (n,l) = (if n=1 then 1 else if 4*(n - 1)<l then n else 1)\"\n\nfun nxt_tb :: \"op\\<^sub>t\\<^sub>b \\<Rightarrow> nat*nat \\<Rightarrow> nat*nat\" where\n\"nxt_tb Ins = ins\" |\n\"nxt_tb Del = del\"\n\nfun T_tb :: \"op\\<^sub>t\\<^sub>b \\<Rightarrow> nat*nat \\<Rightarrow> real\" where\n\"T_tb Ins = T_ins\" |\n\"T_tb Del = T_del\"\n\nfun invar :: \"nat*nat \\<Rightarrow> bool\" where\n\"invar (n,l) = (n \\<le> l)\"\n\nfun \\<Phi> :: \"nat*nat \\<Rightarrow> real\" where\n\"\\<Phi> (n,l) = (if n < l/2 then l/2 - n else 2*n - l)\"\n\ninterpretation tb: Amortized\nwhere init = \"(0,0)\" and nxt = nxt_tb\nand inv = invar\nand T = T_tb and \\<Phi> = \\<Phi>\nand U = \"\\<lambda>f _. case f of Ins \\<Rightarrow> 3 | Del \\<Rightarrow> 2\"\nproof (standard, goal_cases)\n  case 1 show ?case by auto\nnext\n  case (2 s f) thus ?case by(cases s, cases f) (auto)\nnext\n  case (3 s) show ?case by(cases s)(simp)\nnext\n  case 4 show ?case by(simp)\nnext\n  case (5 s f) thus ?case apply(cases s) apply(cases f)\n    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/Amortized_Complexity/Amortized_Framework0.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772318846387, "lm_q2_score": 0.8354835391516133, "lm_q1q2_score": 0.7302771391868234}}
{"text": "(*  Author: Lukas Bulwahn <lukas.bulwahn-at-gmail.com> *)\n\nsection \\<open>Functions from A to B\\<close>\n\ntheory Twelvefold_Way_Entry1\nimports Preliminaries\nbegin\n\ntext \\<open>\nNote that the cardinality theorems of both structures, lists and finite\nfunctions, are already available. Hence, this development creates the\nbijection between those two structures and transfers the one cardinality\ntheorem to the other structures and vice versa, although not strictly\nneeded as both cardinality theorems were already available.\n\\<close>\n\nsubsection \\<open>Definition of Bijections\\<close>\n\ndefinition sequence_of :: \"'a set \\<Rightarrow> (nat \\<Rightarrow> 'a) \\<Rightarrow> ('a \\<Rightarrow> 'b) \\<Rightarrow> 'b list\"\nwhere\n  \"sequence_of A enum f = map (\\<lambda>n. f (enum n)) [0..<card A]\"\n\ndefinition function_of :: \"'a set \\<Rightarrow> (nat \\<Rightarrow> 'a) \\<Rightarrow> 'b list \\<Rightarrow> ('a \\<Rightarrow> 'b)\"\nwhere\n  \"function_of A enum xs = (\\<lambda>a. if a \\<in> A then xs ! inv_into {0..<length xs} enum a else undefined)\"\n\nsubsection \\<open>Properties for Bijections\\<close>\n\nlemma nth_sequence_of:\n  assumes \"i < card A\"\n  shows \"(sequence_of A enum f) ! i = f (enum i)\"\nusing assms unfolding sequence_of_def by auto\n\nlemma nth_sequence_of_inv_into:\n  assumes \"bij_betw enum {0..<card A} A\"\n  assumes \"a \\<in> A\"\n  shows \"(sequence_of A enum f) ! (inv_into {0..<card A} enum a) = f a\"\nproof -\n  have \"inv_into {0..<card A} enum a \\<in> {0..<card A}\"\n    using assms bij_betwE bij_betw_inv_into by blast\n  from this assms show \"(sequence_of A enum f) ! (inv_into {0..<card A} enum a) = f a\"\n    unfolding sequence_of_def by (simp add: bij_betw_inv_into_right)\nqed\n\nlemma set_sequence_of:\n  assumes \"bij_betw enum {0..<card A} A\"\n  assumes \"f \\<in> A \\<rightarrow>\\<^sub>E B\"\n  shows \"set (sequence_of A enum f) \\<subseteq> B\"\nusing PiE bij_betwE assms\nunfolding sequence_of_def by fastforce\n\nlemma length_sequence_of:\n  assumes \"bij_betw enum {0..<card A} A\"\n  assumes \"f \\<in> A \\<rightarrow>\\<^sub>E B\"\n  shows \"length (sequence_of A enum f) = card A\"\nusing assms unfolding sequence_of_def by simp\n\nlemma function_of_enum:\n  assumes \"bij_betw enum {0..<card A} A\"\n  assumes \"length xs = card A\"\n  assumes \"i < card A\"\n  shows \"function_of A enum xs (enum i) = xs ! i\"\nusing assms unfolding function_of_def\nby (auto simp add: bij_betw_inv_into_left bij_betwE)\n\nlemma function_of_in_extensional_funcset:\n  assumes \"bij_betw enum {0..<card A} A\"\n  assumes \"set xs \\<subseteq> B\" \"length xs = card A\"\n  shows \"function_of A enum xs \\<in> A \\<rightarrow>\\<^sub>E B\"\nproof\n  fix x\n  assume \"x \\<in> A\"\n  have \"inv_into {0..<length xs} enum x \\<in> {0..<length xs}\"\n    using \\<open>x \\<in> A\\<close> assms(1, 3) by (metis bij_betw_def inv_into_into)\n  from this have \"xs ! inv_into {0..<length xs} enum x \\<in> set xs\" by simp\n  from this \\<open>set xs \\<subseteq> B\\<close> show \"function_of A enum xs x \\<in> B\"\n    using \\<open>x \\<in> A\\<close> unfolding function_of_def by auto\nnext\n  fix x\n  assume \"x \\<notin> A\"\n  from this show \"function_of A enum xs x = undefined\"\n    unfolding function_of_def by simp\nqed\n\nlemma sequence_of_function_of:\n  assumes \"bij_betw enum {0..<card A} A\"\n  assumes \"set xs \\<subseteq> B\" \"length xs = card A\"\n  shows \"sequence_of A enum (function_of A enum xs) = xs\"\nproof (rule nth_equalityI)\n  have \"function_of A enum xs \\<in> A \\<rightarrow>\\<^sub>E B\"\n    using assms by (rule function_of_in_extensional_funcset)\n  from this show \"length (sequence_of A enum (function_of A enum xs)) = length xs\"\n    using assms(1,3) by (simp add: length_sequence_of)\n  from this show \"\\<And>i. i < length (sequence_of A enum (function_of A enum xs)) \\<Longrightarrow> sequence_of A enum (function_of A enum xs) ! i = xs ! i\"\n    using assms by (auto simp add: nth_sequence_of function_of_enum)\nqed\n\nlemma function_of_sequence_of:\n  assumes \"bij_betw enum {0..<card A} A\"\n  assumes \"f \\<in> A \\<rightarrow>\\<^sub>E B\"\n  shows \"function_of A enum (sequence_of A enum f) = f\"\nproof\n  fix x\n  show \"function_of A enum (sequence_of A enum f) x = f x\"\n    using assms unfolding function_of_def\n    by (auto simp add: length_sequence_of nth_sequence_of_inv_into)\nqed\n\nsubsection \\<open>Bijections\\<close>\n\nlemma bij_betw_sequence_of:\n  assumes \"bij_betw enum {0..<card A} A\"\n  shows \"bij_betw (sequence_of A enum) (A \\<rightarrow>\\<^sub>E B) {xs. set xs \\<subseteq> B \\<and> length xs = card A}\"\nproof (rule bij_betw_byWitness[where f'=\"function_of A enum\"])\n  show \"\\<forall>f\\<in>A \\<rightarrow>\\<^sub>E B. function_of A enum (sequence_of A enum f) = f\"\n    using assms by (simp add: function_of_sequence_of)\n  show \"\\<forall>xs\\<in>{xs. set xs \\<subseteq> B \\<and> length xs = card A}. sequence_of A enum (function_of A enum xs) = xs\"\n    using assms by (auto simp add: sequence_of_function_of)\n  show \"sequence_of A enum ` (A \\<rightarrow>\\<^sub>E B) \\<subseteq> {xs. set xs \\<subseteq> B \\<and> length xs = card A}\"\n    using assms set_sequence_of[OF assms] length_sequence_of by auto\n  show \"function_of A enum ` {xs. set xs \\<subseteq> B \\<and> length xs = card A} \\<subseteq> A \\<rightarrow>\\<^sub>E B\"\n    using assms function_of_in_extensional_funcset by blast\nqed\n\nlemma bij_betw_function_of:\n  assumes \"bij_betw enum {0..<card A} A\"\n  shows \"bij_betw (function_of A enum) {xs. set xs \\<subseteq> B \\<and> length xs = card A} (A \\<rightarrow>\\<^sub>E B)\"\nproof (rule bij_betw_byWitness[where f'=\"sequence_of A enum\"])\n  show \"\\<forall>f\\<in>A \\<rightarrow>\\<^sub>E B. function_of A enum (sequence_of A enum f) = f\"\n    using assms by (simp add: function_of_sequence_of)\n  show \"\\<forall>xs\\<in>{xs. set xs \\<subseteq> B \\<and> length xs = card A}. sequence_of A enum (function_of A enum xs) = xs\"\n    using assms by (auto simp add: sequence_of_function_of)\n  show \"sequence_of A enum ` (A \\<rightarrow>\\<^sub>E B) \\<subseteq> {xs. set xs \\<subseteq> B \\<and> length xs = card A}\"\n    using assms set_sequence_of[OF assms] length_sequence_of by auto\n  show \"function_of A enum ` {xs. set xs \\<subseteq> B \\<and> length xs = card A} \\<subseteq> A \\<rightarrow>\\<^sub>E B\"\n    using assms function_of_in_extensional_funcset by blast\nqed\n\nsubsection \\<open>Cardinality\\<close>\n\nlemma\n  assumes \"finite A\"\n  shows \"card (A \\<rightarrow>\\<^sub>E B) = card B ^ card A\"\nproof -\n  obtain enum where \"bij_betw enum {0..<card A} A\"\n    using \\<open>finite A\\<close> ex_bij_betw_nat_finite by blast\n  have \"bij_betw (sequence_of A enum) (A \\<rightarrow>\\<^sub>E B) {xs. set xs \\<subseteq> B \\<and> length xs = card A}\"\n    using \\<open>bij_betw enum {0..<card A} A\\<close> by (rule bij_betw_sequence_of)\n  from this have \"card (A \\<rightarrow>\\<^sub>E B) = card {xs. set xs \\<subseteq> B \\<and> length xs = card A}\"\n    by (rule bij_betw_same_card)\n  also have \"card {xs. set xs \\<subseteq> B \\<and> length xs = card A} = card B ^ card A\"\n    by (rule card_lists_length_eq)\n  finally show ?thesis .\nqed\n\nlemma card_sequences:\n  assumes \"finite A\"\n  shows \"card {xs. set xs \\<subseteq> B \\<and> length xs = card A} = card B ^ card A\"\nproof -\n  obtain enum where \"bij_betw enum {0..<card A} A\"\n    using \\<open>finite A\\<close> ex_bij_betw_nat_finite by blast\n  have \"bij_betw (function_of A enum) {xs. set xs \\<subseteq> B \\<and> length xs = card A} (A \\<rightarrow>\\<^sub>E B)\"\n    using \\<open>bij_betw enum {0..<card A} A\\<close> by (rule bij_betw_function_of)\n  from this have \"card {xs. set xs \\<subseteq> B \\<and> length xs = card A} = card (A \\<rightarrow>\\<^sub>E B)\"\n    by (rule bij_betw_same_card)\n  also have \"card (A \\<rightarrow>\\<^sub>E B) = card B ^ card A\"\n    using \\<open>finite A\\<close> by (rule card_extensional_funcset)\n  finally show ?thesis .\nqed\n\nlemma\n  shows \"card {xs. set xs \\<subseteq> A \\<and> length xs = n} = card A ^ n\"\nproof -\n  have \"card {xs. set xs \\<subseteq> A \\<and> length xs = n} = card {xs. set xs \\<subseteq> A \\<and> length xs = card {0..<n}}\"\n    by auto\n  also have \"\\<dots> = card A ^ card {0..<n}\" by (subst card_sequences) auto\n  also have \"\\<dots> = card A ^ n\" 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/Twelvefold_Way/Twelvefold_Way_Entry1.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772253241802, "lm_q2_score": 0.8354835452961425, "lm_q1q2_score": 0.7302771390764613}}
{"text": "theory Words\nimports Preliminaries \nbegin\n\nsubsection \\<open> $\\omega$-words \\<close>\n\ntext \\<open>\n  Automata recognize languages, which are sets of words. For the\n  theory of $\\omega$-automata, we are mostly interested in\n  $\\omega$-words, but it is sometimes useful to reason about\n  finite words, too. We are modeling finite words as lists; this\n  lets us benefit from the existing library. Other formalizations\n  could be investigated, such as representing words as functions\n  whose domains are initial intervals of the natural numbers.\n\\<close>\n\nsubsubsection \\<open> Type declaration and elementary operations \\<close>\n\ntext \\<open>\n  We represent $\\omega$-words as functions from the natural numbers\n  to the alphabet type. Other possible formalizations include\n  a coinductive definition or a uniform encoding of finite and\n  infinite words, as studied by M\\\"uller et al.\n\\<close>\n\ntype_synonym\n  'a word = \"nat \\<Rightarrow> 'a\"\n\ndefinition\n  suffix :: \"[nat, 'a word] \\<Rightarrow> 'a word\"\n  where \"suffix k x \\<equiv> \\<lambda>n. x (k+n)\"\n\nlemma suffix_nth [simp]:\n  \"(suffix k x) n = x (k+n)\"\nby (simp add: suffix_def)\n\nlemma suffix_0 [simp]:\n  \"suffix 0 x = x\"\nby (simp add: suffix_def)\n\nlemma suffix_suffix [simp]:\n  \"suffix m (suffix k x) = suffix (k+m) x\"\nby (rule ext, simp add: suffix_def ac_simps)\n\ntext \\<open>\n  A finite part of an infinite word can be obtained as the\n  result of mapping the word over the desired index interval.\n  For now, we do not define a separate constant for this\n  construction, as it does not occur very often, and we prefer\n  to rely on the proof machinery provided by the standard library.\n  However, the standard rewriting rules include the theorem @{text upt_Suc},\n  which tends to convert, say, $[i..j]$ into $[i..j(] @ [j]$.\n  Since this is (almost) never what we want, we remove the theorem\n  from the rule base in effect for this session.\n\\<close>\ndeclare upt_Suc [simp del]\n\n\ntext \\<open>\n  We can prefix a finite word to an $\\omega$-word, and a way\n  to obtain an $\\omega$-word from a finite, non-empty word is by\n  $\\omega$-iteration.\n\\<close>\n\ndefinition\n  conc :: \"['a list, 'a word] \\<Rightarrow> 'a word\"    (\"_/ conc _\" [66,65] 65)\n  where \"w conc x == \\<lambda>n. if n < length w then w!n else x (n - length w)\"\n\ndefinition\n  iter :: \"'a list \\<Rightarrow> 'a word\"\n  where \"iter w == if w = [] then undefined else (\\<lambda>n. w!(n mod (length w)))\"\n\nsyntax (xsymbols)\n  conc :: \"['a list, 'a word] \\<Rightarrow> 'a word\"    (\"_/ \\<frown> _\" [66,65] 65)\n  iter :: \"'a list \\<Rightarrow> 'a word\"               (\"(_\\<^sup>\\<omega>)\" [1000])\n\nlemma conc_empty[simp]: \"[] \\<frown> w = w\"\n  unfolding conc_def by auto\n\nlemma conc_fst:\n  \"n < length w \\<Longrightarrow> (w \\<frown> x) n = w!n\"\nby (simp add: conc_def)\n\nlemma conc_snd:\n  \"\\<not>(n < length w) \\<Longrightarrow> (w \\<frown> x) n = x (n - length w)\"\nby (simp add: conc_def)\n\nlemma iter_nth [simp]:\n  \"0 < length w \\<Longrightarrow> w\\<^sup>\\<omega> n = w!(n mod (length w))\"\nby (simp add: iter_def)\n\nlemma conc_conc:\n  \"u \\<frown> v \\<frown> w = (u @ v) \\<frown> w\" (is \"?lhs = ?rhs\")\nproof\n  fix n\n  have u: \"n < length u \\<Longrightarrow> ?lhs n = ?rhs n\"\n    by (simp add: conc_def nth_append)\n  have v: \"\\<lbrakk> \\<not>(n < length u); n < length u + length v \\<rbrakk> \\<Longrightarrow> ?lhs n = ?rhs n\"\n    by (simp add: conc_def nth_append, arith)\n  have w: \"\\<not>(n < length u + length v) \\<Longrightarrow> ?lhs n = ?rhs n\"\n    by (simp add: conc_def nth_append, arith)\n  from u v w show \"?lhs n = ?rhs n\" by auto\nqed\n\nlemma prefix_suffix: \n  \"x = (map x [0..<n] ) \\<frown> (suffix n x)\"\nby (rule ext, simp add: conc_def)\n\nlemma iter_unroll:\n  \"0 < length w \\<Longrightarrow> w\\<^sup>\\<omega> = w \\<frown> w\\<^sup>\\<omega>\"\nby (rule ext, simp add: conc_def mod_geq)\n\nsubsubsection \\<open> The limit set of an $\\omega$-word \\<close>\n\ntext \\<open>\n  The limit set (also called infinity set) of an $\\omega$-word\n  is the set of letters that appear infinitely often in the word.\n  This set plays an important role in defining acceptance conditions\n  of $\\omega$-automata.\n\\<close>\n\ndefinition\n  limit :: \"'a word \\<Rightarrow> 'a set\"\n  where \"limit x \\<equiv> { a . \\<exists>\\<^sub>\\<infinity>n . x n = a }\"\n\nlemma limit_iff_frequent:\n  \"(a \\<in> limit x) = (\\<exists>\\<^sub>\\<infinity>n . x n = a)\"\nby (simp add: limit_def)\n\ntext \\<open>\n  The following is a different way to define the limit,\n  using the reverse image, making the laws about reverse\n  image applicable to the limit set. \n  (Might want to change the definition above?)\n\\<close>\n\nlemma limit_vimage:\n  \"(a \\<in> limit x) = infinite (x -` {a})\"\nby (simp add: limit_def Inf_many_def vimage_def)\n\nlemma two_in_limit_iff:\n  \"({a,b} \\<subseteq> limit x) = \n   ((\\<exists>n. x n =a ) \\<and> (\\<forall>n. x n = a \\<longrightarrow> (\\<exists>m>n. x m = b)) \\<and> (\\<forall>m. x m = b \\<longrightarrow> (\\<exists>n>m. x n = a)))\"\n  (is \"?lhs = (?r1 \\<and> ?r2 \\<and> ?r3)\")\nproof\n  assume lhs: \"?lhs\"\n  hence 1: \"?r1\" by (auto simp: limit_def elim: INFM_EX)\n  from lhs have \"\\<forall>n. \\<exists>m>n. x m = b\" by (auto simp: limit_def INFM_nat)\n  hence 2: \"?r2\" by simp\n  from lhs have \"\\<forall>m. \\<exists>n>m. x n = a\" by (auto simp: limit_def INFM_nat)\n  hence 3: \"?r3\" by simp\n  from 1 2 3 show \"?r1 \\<and> ?r2 \\<and> ?r3\" by simp\nnext\n  assume \"?r1 \\<and> ?r2 \\<and> ?r3\"\n  hence 1: \"?r1\" and 2: \"?r2\" and 3: \"?r3\" by simp+\n  have infa: \"\\<forall>m. \\<exists>n\\<ge>m. x n = a\"\n  proof\n    fix m\n    show \"\\<exists>n\\<ge>m. x n = a\" (is \"?A m\")\n    proof (induct m)\n      from 1 show \"?A 0\" by simp\n    next\n      fix m\n      assume ih: \"?A m\"\n      then obtain n where n: \"n \\<ge> m\" \"x n = a\" by auto\n      with 2 obtain k where k: \"k>n\" \"x k = b\" by auto\n      with 3 obtain l where l: \"l>k\" \"x l = a\" by auto\n      from n k l have \"l \\<ge> Suc m\" by auto\n      with l show \"?A (Suc m)\" by auto\n    qed\n  qed\n  hence infa': \"\\<exists>\\<^sub>\\<infinity>n. x n = a\" by (simp add: INFM_nat_le)\n  have \"\\<forall>n. \\<exists>m>n. x m = b\"\n  proof\n    fix n\n    from infa obtain k where k1: \"k\\<ge>n\" and k2: \"x k = a\" by auto\n    from 2 k2 obtain l where l1: \"l>k\" and l2: \"x l = b\" by auto\n    from k1 l1 have \"l > n\" by auto\n    with l2 show \"\\<exists>m>n. x m = b\" by auto\n  qed\n  hence \"\\<exists>\\<^sub>\\<infinity>m. x m = b\" by (simp add: INFM_nat)\n  with infa' show \"?lhs\" by (auto simp: limit_def)\nqed\n\ntext \\<open>\n  For $\\omega$-words over a finite alphabet, the limit set is\n  non-empty. Moreover, from some position onward, any such word\n  contains only letters from its limit set.\n\\<close>\n\nlemma limit_nonempty:\n  assumes fin: \"finite (range x)\"\n  shows \"\\<exists>a. a \\<in> limit x\"\nproof -\n  from fin obtain a where \"a \\<in> range x \\<and> infinite (x -` {a})\"\n    by (rule inf_img_fin_domE, auto)\n  hence \"a \\<in> limit x\"\n    by (auto simp add: limit_vimage)\n  thus ?thesis ..\nqed\n\nlemmas limit_nonemptyE = limit_nonempty[THEN exE]\n\nlemma limit_inter_INF:\n  assumes hyp: \"limit w \\<inter> S \\<noteq> {}\"\n  shows \"\\<exists>\\<^sub>\\<infinity> n. w n \\<in> S\"\nproof -\n  from hyp obtain x where \"\\<exists>\\<^sub>\\<infinity> n. w n = x\" and \"x \\<in> S\"\n    by (auto simp add: limit_def)\n  thus ?thesis\n    by (auto elim: INFM_mono)\nqed\n\ntext \\<open>\n  The reverse implication is true only if $S$ is finite.\n\\<close>\n\nlemma INF_limit_inter:\n  assumes hyp: \"\\<exists>\\<^sub>\\<infinity> n. w n \\<in>  S\" and fin: \"finite (S \\<inter> range w)\"\n  shows  \"\\<exists>a. a \\<in> limit w \\<inter> S\"\nproof (rule ccontr)\n  assume contra: \"\\<not>(\\<exists>a. a \\<in> limit w \\<inter> S)\"\n  hence \"\\<forall>a\\<in>S. finite {n. w n = a}\"\n    by (auto simp add: limit_def Inf_many_def)\n  with fin have \"finite (UN a:S \\<inter> range w. {n. w n = a})\"\n    by auto\n  moreover\n  have \"(UN a:S \\<inter> range w. {n. w n = a}) = {n. w n \\<in> S}\"\n    by auto\n  moreover\n  note hyp\n  ultimately show \"False\"\n    by (simp add: Inf_many_def)\nqed\n\nlemma fin_ex_inf_eq_limit: \"finite A \\<Longrightarrow> (\\<exists>\\<^sub>\\<infinity>i. w i \\<in> A) \\<longleftrightarrow> limit w \\<inter> A \\<noteq> {}\"\n  by (metis INF_limit_inter equals0D finite_Int limit_inter_INF)\n\nlemma limit_in_range_suffix:\n  \"limit x \\<subseteq> range (suffix k x)\"\nproof\n  fix a\n  assume \"a \\<in> limit x\"\n  then obtain l where\n    kl: \"k < l\" and xl: \"x l = a\"\n    by (auto simp add: limit_def INFM_nat)\n  from kl obtain m where \"l = k+m\"\n    by (auto simp add:  less_iff_Suc_add)\n  with xl show \"a \\<in> range (suffix k x)\"\n    by auto\nqed\n\nlemma limit_in_range: \"limit r \\<subseteq> range r\"\n  using limit_in_range_suffix[of r 0] by simp\n\nlemmas limit_in_range_suffixD = limit_in_range_suffix[THEN subsetD]\n\ntheorem limit_is_suffix:\n  assumes fin: \"finite (range x)\"\n  shows \"\\<exists>k. limit x = range (suffix k x)\"\nproof -\n  have \"\\<exists>k. range (suffix k x) \\<subseteq> limit x\"\n  proof -\n    (*\"The set of letters that are not in the limit is certainly finite.\"*)\n    from fin have \"finite (range x - limit x)\"\n      by simp\n    (* \"Moreover, any such letter occurs only finitely often\"*)\n    moreover\n    have \"\\<forall>a \\<in> range x - limit x. finite (x -` {a})\"\n      by (auto simp add: limit_vimage)\n    (* \"Thus, there are only finitely many occurrences of such letters.\"*)\n    ultimately have \"finite (UN a : range x - limit x. x -` {a})\"\n      by (blast intro: finite_UN_I)\n    (* \"Therefore these occurrences are within some initial interval.\"*)\n    then obtain k where \"(UN a : range x - limit x. x -` {a}) \\<subseteq> {..<k}\"\n      by (blast dest: finite_nat_bounded)\n    (* \"This is just the bound we are looking for.\"*)\n    hence \"\\<forall>m. k \\<le> m \\<longrightarrow> x m \\<in> limit x\"\n      by (auto simp add: limit_vimage)\n    hence \"range (suffix k x) \\<subseteq> limit x\"\n      by auto\n    thus ?thesis ..\n  qed\n  then obtain k where \"range (suffix k x) \\<subseteq> limit x\" ..\n  with limit_in_range_suffix\n  have \"limit x = range (suffix k x)\"\n    by (rule subset_antisym)\n  thus ?thesis ..\nqed\n\nlemmas limit_is_suffixE = limit_is_suffix[THEN exE]\n\n\ntext \\<open>\n  The limit set enjoys some simple algebraic laws with respect\n  to concatenation, suffixes, iteration, and renaming.\n\\<close>\n\ntheorem limit_conc [simp]:\n  \"limit (w \\<frown> x) = limit x\"\nproof (auto)\n  fix a assume a: \"a \\<in> limit (w \\<frown> x)\"\n  have \"\\<forall>m. \\<exists>n. m<n \\<and> x n = a\"\n  proof\n    fix m\n    from a obtain n where \"m + length w < n \\<and> (w \\<frown> x) n = a\"\n      by (auto simp add: limit_def Inf_many_def infinite_nat_iff_unbounded)\n    hence \"m < n - length w \\<and> x (n - length w) = a\"\n      by (auto simp add: conc_def)\n    thus \"\\<exists>n. m<n \\<and> x n = a\" ..\n  qed\n  hence \"infinite {n . x n = a}\"\n    by (simp add: infinite_nat_iff_unbounded)\n  thus \"a \\<in> limit x\"\n    by (simp add: limit_def Inf_many_def)\nnext\n  fix a assume a: \"a \\<in> limit x\"\n  have \"\\<forall>m. length w < m \\<longrightarrow> (\\<exists>n. m<n \\<and> (w \\<frown> x) n = a)\"\n  proof (clarify)\n    fix m\n    assume m: \"length w < m\"\n    with a obtain n where \"m - length w < n \\<and> x n = a\"\n      by (auto simp add: limit_def Inf_many_def infinite_nat_iff_unbounded)\n    with m have \"m < n + length w \\<and> (w \\<frown> x) (n + length w) = a\"\n      by (simp add: conc_def, arith)\n    thus \"\\<exists>n. m<n \\<and> (w \\<frown> x) n = a\" ..\n  qed\n  hence \"infinite {n . (w \\<frown> x) n = a}\"\n    by (simp add: unbounded_k_infinite)\n  thus \"a \\<in> limit (w \\<frown> x)\"\n    by (simp add: limit_def Inf_many_def)\nqed\n\ntheorem limit_suffix [simp]: \n  \"limit (suffix n x) = limit x\"\nproof -\n  have \"x = (map x [0..<n]) \\<frown> (suffix n x)\"\n    by (simp add: prefix_suffix)\n  hence \"limit x = limit ((map x [0..<n]) \\<frown> suffix n x)\"\n    by simp\n  also have \"\\<dots> = limit (suffix n x)\"\n    by (rule limit_conc)\n  finally show ?thesis\n    by (rule sym)\nqed\n\ntheorem limit_iter [simp]:\n  assumes nempty: \"0 < length w\"\n  shows \"limit w\\<^sup>\\<omega> = set w\"\nproof\n  have \"limit w\\<^sup>\\<omega> \\<subseteq> range w\\<^sup>\\<omega>\"\n    by (auto simp add: limit_def dest: INFM_EX)\n  also from nempty have \"\\<dots> \\<subseteq> set w\"\n    by auto\n  finally show \"limit w\\<^sup>\\<omega> \\<subseteq> set w\" .\nnext\n  {\n    fix a assume a: \"a \\<in> set w\"\n    then obtain k where k: \"k < length w \\<and> w!k = a\"\n      by (auto simp add: set_conv_nth)\n    \\<comment>\\<open>the following bound is terrible, but it simplifies the proof\\<close>\n    from nempty k\n    have \"\\<forall>m. w\\<^sup>\\<omega> ((Suc m)*(length w) + k) = a\"\n      by (metis iter_nth mod_less mod_mult_self3)\n      (* by (simp add: mod_add_left_eq) *)\n    moreover\n    \\<comment>\\<open>why is the following so hard to prove??\\<close>\n    have \"\\<forall>m. m < (Suc m)*(length w) + k\"\n    proof\n      fix m\n      from nempty have \"1 \\<le> length w\" by arith\n      hence \"m*1 \\<le> m*length w\" by simp\n      hence \"m \\<le> m*length w\" by simp\n      with nempty have \"m < length w + (m*length w) + k\" by arith\n      thus \"m < (Suc m)*(length w) + k\" by simp\n    qed\n    moreover note nempty\n    ultimately have \"a \\<in> limit w\\<^sup>\\<omega>\"\n      by (auto simp add: limit_iff_frequent INFM_nat)\n  }\n  then show \"set w \\<subseteq> limit w\\<^sup>\\<omega>\" by auto\nqed\n\nlemma limit_o [simp]:\n  assumes a: \"a \\<in> limit w\"\n  shows \"f a \\<in> limit (f \\<circ> w)\"\nproof -\n  from a\n  have \"\\<exists>\\<^sub>\\<infinity>n. w n = a\"\n    by (simp add: limit_iff_frequent)\n  hence \"\\<exists>\\<^sub>\\<infinity>n. f (w n) = f a\"\n    by (rule INFM_mono, simp)\n  thus \"f a \\<in> limit (f \\<circ> w)\"\n    by (simp add: limit_iff_frequent)\nqed\n\ntext \\<open>\n  The converse relation is not true in general: $f(a)$ can be in the\n  limit of $f \\circ w$ even though $a$ is not in the limit of $w$.\n  However, @{text limit} commutes with renaming if the function is\n  injective. More generally, if $f(a)$ is the image of only finitely\n  many elements, some of these must be in the limit of $w$.\n\\<close>\n\nlemma limit_o_inv:\n  assumes fin: \"finite (f -` {x})\" and x: \"x \\<in> limit (f \\<circ> w)\"\n  shows \"\\<exists>a \\<in> (f -` {x}). a \\<in> limit w\"\nproof (rule ccontr)\n  assume contra: \"\\<not>(\\<exists>a \\<in> (f -` {x}). a \\<in> limit w)\"\n  \\<comment>\\<open>hence, every element in the pre-image occurs only finitely often\\<close>\n  then have \"\\<forall>a \\<in> (f -` {x}). finite {n. w n = a}\"\n    by (simp add: limit_def Inf_many_def)\n  \\<comment>\\<open>so there are only finitely many occurrences of any such element\\<close>\n  with fin have \"finite (\\<Union> a \\<in> (f -` {x}). {n. w n = a})\"\n    by auto\n  \\<comment>\\<open>these are precisely those positions where $x$ occurs in $f \\circ w$ \\<close>\n  moreover\n  have \"(\\<Union> a \\<in> (f -` {x}). {n. w n = a}) = {n. f(w n) = x}\"\n    by auto\n  ultimately\n  \\<comment>\\<open>so $x$ can occur only finitely often in the translated word\\<close>\n  have \"finite {n. f(w n) = x}\"\n    by simp\n  \\<comment>\\<open> \\ldots\\ which yields a contradiction \\<close>\n  with x show \"False\"\n    by (simp add: limit_def Inf_many_def)\nqed\n\ntheorem limit_inj [simp]:\n  assumes inj: \"inj f\"\n  shows \"limit (f \\<circ> w) = f ` (limit w)\"\nproof\n  show \"f ` limit w \\<subseteq> limit (f \\<circ> w)\"\n    by auto\nnext\n  show \"limit (f \\<circ> w) \\<subseteq> f ` limit w\"\n  proof\n    fix x\n    assume x: \"x \\<in> limit (f \\<circ> w)\"\n    from inj have \"finite (f -` {x})\"\n      by (blast intro: finite_vimageI)\n    with x obtain a where a: \"a \\<in> (f -` {x}) \\<and> a \\<in> limit w\"\n      by (blast dest: limit_o_inv)\n    thus \"x \\<in> f ` (limit w)\"\n      by auto\n  qed\nqed\n\nsubsubsection \\<open> Index sequences and piecewise definitions \\<close>\n\ntext \\<open>\n  A word can be defined piecewise: given a sequence of words $w_0, w_1, \\ldots$\n  and a strictly increasing sequence of integers $i_0, i_1, \\ldots$ where $i_0=0$,\n  a single word is obtained by concatenating subwords of the $w_n$ as given by\n  the integers: the resulting word is\n  \\[\n    (w_0)_{i_0} \\ldots (w_0)_{i_1-1} (w_1)_{i_1} \\ldots (w_1)_{i_2-1} \\ldots\n  \\]\n  We prepare the field by proving some trivial facts about such sequences of \n  indexes.\n\\<close>\n\ndefinition\n  idx_sequence :: \"nat word \\<Rightarrow> bool\"\n  where \"idx_sequence idx \\<equiv> (idx 0 = 0) \\<and> (\\<forall>n. idx n < idx (Suc n))\"\n\nlemma idx_sequence_less:\n  assumes iseq: \"idx_sequence idx\"\n  shows \"idx n < idx (Suc(n+k))\"\nproof (induct k)\n  from iseq show \"idx n < idx (Suc (n + 0))\"\n    by (simp add: idx_sequence_def)\nnext\n  fix k\n  assume ih: \"idx n < idx (Suc(n+k))\"\n  from iseq have \"idx (Suc(n+k)) < idx (Suc(n + Suc k))\"\n    by (simp add: idx_sequence_def)\n  with ih show \"idx n < idx (Suc(n + Suc k))\"\n    by (rule less_trans)\nqed\n\nlemma idx_sequence_inj:\n  assumes iseq: \"idx_sequence idx\"\n  and eq: \"idx m = idx n\"\n  shows \"m = n\"\nproof (rule linorder_cases)\n  assume \"n<m\"\n  then obtain k where \"m = Suc(n+k)\"\n    by (auto simp add: less_iff_Suc_add)\n  with iseq have \"idx n < idx m\"\n    by (simp add: idx_sequence_less)\n  with eq show ?thesis\n    by simp\nnext\n  assume \"m<n\"\n  then obtain k where \"n = Suc(m+k)\"\n    by (auto simp add: less_iff_Suc_add)\n  with iseq have \"idx m < idx n\"\n    by (simp add: idx_sequence_less)\n  with eq show ?thesis\n    by simp\nqed (simp)\n\nlemma idx_sequence_mono:\n  assumes iseq: \"idx_sequence idx\"\n  and m: \"m \\<le> n\"\n  shows \"idx m \\<le> idx n\"\nproof (cases \"m=n\")\n  case True\n  thus ?thesis by simp\nnext\n  case False\n  with m have \"m < n\" by simp\n  then obtain k where \"n = Suc(m+k)\"\n    by (auto simp add: less_iff_Suc_add)\n  with iseq have \"idx m < idx n\"\n    by (simp add: idx_sequence_less)\n  thus ?thesis by simp\nqed\n\ntext \\<open>\n  Given an index sequence, every natural number is contained in the\n  interval defined by two adjacent indexes, and in fact this interval\n  is determined uniquely.\n\\<close>\n\nlemma idx_sequence_idx:\n  assumes \"idx_sequence idx\"\n  shows \"idx k \\<in> {idx k ..< idx (Suc k)}\"\nusing assms by (auto simp add: idx_sequence_def)\n\nlemma idx_sequence_interval:\n  assumes iseq: \"idx_sequence idx\"\n  shows \"\\<exists>k. n \\<in> {idx k ..< idx (Suc k) }\"\n    (is \"?P n\" is \"\\<exists>k. ?in n k\")\nproof (induct n)\n  from iseq have \"0 = idx 0\"\n    by (simp add: idx_sequence_def)\n  moreover\n  from iseq have \"idx 0 \\<in> {idx 0 ..< idx (Suc 0) }\"\n    by (rule idx_sequence_idx)\n  ultimately\n  show \"?P 0\" by auto\nnext\n  fix n\n  assume \"?P n\"\n  then obtain k where k: \"?in n k\" ..\n  show \"?P (Suc n)\"\n  proof (cases \"Suc n < idx (Suc k)\")\n    case True\n    with k have \"?in (Suc n) k\"\n      by simp\n    thus ?thesis ..\n  next\n    case False\n    with k have \"Suc n = idx (Suc k)\"\n      by auto\n    with iseq have \"?in (Suc n) (Suc k)\"\n      by (simp add: idx_sequence_def)\n    thus ?thesis ..\n  qed\nqed\n\nlemma idx_sequence_interval_unique:\n  assumes iseq: \"idx_sequence idx\"\n  and k: \"n \\<in> {idx k ..< idx (Suc k) }\"\n  and m: \"n \\<in> {idx m ..< idx (Suc m) }\"\n  shows \"k = m\"\nproof (rule linorder_cases)\n  assume \"k < m\"\n  hence \"Suc k \\<le> m\" by simp\n  with iseq have \"idx (Suc k) \\<le> idx m\"\n    by (rule idx_sequence_mono)\n  with m have \"idx (Suc k) \\<le> n\"\n    by auto\n  with k have \"False\"\n    by simp\n  thus ?thesis ..\nnext\n  assume \"m < k\"\n  hence \"Suc m \\<le> k\" by simp\n  with iseq have \"idx (Suc m) \\<le> idx k\"\n    by (rule idx_sequence_mono)\n  with k have \"idx (Suc m) \\<le> n\"\n    by auto\n  with m have \"False\"\n    by simp\n  thus ?thesis ..\nqed (simp)\n\nlemma idx_sequence_unique_interval:\n  assumes iseq: \"idx_sequence idx\"\n  shows \"\\<exists>! k. n \\<in> {idx k ..< idx (Suc k) }\"\nproof (rule ex_ex1I)\n  from iseq show \"\\<exists>k. n \\<in> {idx k ..< idx (Suc k)}\"\n    by (rule idx_sequence_interval)\nnext\n  fix k y\n  assume \"n \\<in> {idx k..<idx (Suc k)}\" and \"n \\<in> {idx y..<idx (Suc y)}\"\n  with iseq show \"k = y\" by (auto elim: idx_sequence_interval_unique)\nqed\n\ntext \\<open>\n  Now we can define the piecewise construction of a word using\n  an index sequence.\n\\<close>\n\ndefinition\n  merge :: \"['a word word, nat word] \\<Rightarrow> 'a word\"\n  where \"merge ws idx \\<equiv>\n           \\<lambda> n. let i = THE i. n \\<in> {idx i ..< idx (Suc i) } in ws i n\"\n\nlemma merge:\n  assumes idx: \"idx_sequence idx\"\n  and n: \"n \\<in> {idx i ..< idx (Suc i) }\"\n  shows \"merge ws idx n = ws i n\"\nproof -\n  from n have \"(THE k. n \\<in> {idx k ..< idx (Suc k) }) = i\"\n    by (rule the_equality[OF _ sym[OF idx_sequence_interval_unique[OF idx n]]]) simp\n  thus ?thesis\n    by (simp add: merge_def Let_def)\nqed\n\nlemma merge0:\n  assumes idx: \"idx_sequence idx\"\n  shows \"merge ws idx 0 = ws 0 0\"\nproof (rule merge[OF idx])\n  from idx have \"idx 0 < idx (Suc 0)\"\n    by (unfold idx_sequence_def, blast)\n  with idx show \"0 \\<in> {idx 0 ..< idx (Suc 0)}\"\n    by (simp add: idx_sequence_def)\nqed\n\nlemma merge_Suc:\n  assumes idx: \"idx_sequence idx\"\n  and n: \"n \\<in> {idx i ..< idx (Suc i) }\"\n  shows \"merge ws idx (Suc n) = \n         (if Suc n = idx (Suc i) then ws (Suc i) else ws i) (Suc n)\"\nproof (auto)\n  assume eq: \"Suc n = idx (Suc i)\"\n  from idx have \"idx (Suc i) < idx (Suc(Suc i))\"\n    by (unfold idx_sequence_def, blast)\n  with eq idx show \"merge ws idx (idx (Suc i)) = ws (Suc i) (idx (Suc i))\"\n    by (simp add: merge)\nnext\n  assume neq: \"Suc n \\<noteq> idx (Suc i)\"\n  with n have \"Suc n \\<in> {idx i ..< idx (Suc i) }\"\n    by auto\n  with idx show \"merge ws idx (Suc n) = ws i (Suc n)\"\n    by (rule merge)\nqed\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/Automata_Merz/Words.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8354835289107309, "lm_q2_score": 0.8740772384450968, "lm_q1q2_score": 0.7302771357166558}}
{"text": "(*  Title:      HOL/ex/ThreeDivides.thy\n    Author:     Benjamin Porter, 2005\n*)\n\nsection \\<open>Three Divides Theorem\\<close>\n\ntheory ThreeDivides\nimports Main \"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": "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/ThreeDivides.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619306896956, "lm_q2_score": 0.885631484383387, "lm_q1q2_score": 0.7301694434943083}}
{"text": "(*\nTitle: MoreGraph.thy\nAuthor:Wenda Li\n*)\n\ntheory MoreGraph imports Complex_Main Dijkstra_Shortest_Path.Graph\nbegin\nsection \\<open>Undirected Multigraph and undirected trails\\<close>\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 \\<open>Degrees and related properties\\<close>\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 \\<open>(v,e,v') \\<in> edges g\\<close> \\<open>(v',e,v) \\<in> edges g\\<close> \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 prod.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 \\<open>x \\<notin> {v, v'}\\<close> \n    proof -\n      have \"x\\<noteq>v \\<and> x\\<noteq> v'\" using \\<open>x\\<notin>{v,v'}\\<close>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 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 \\<open>(v1, w, v2) \\<in> E\\<close> 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 \\<open>nodes G1 \\<subseteq> nodes G2\\<close> 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 \\<open>edges G1 \\<subseteq> edges G2\\<close> 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 \\<open>(v,w,v')\\<in>edges G\\<close> 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 \\<open>finite (edges G)\\<close> 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 \\<open>finite (edges G)\\<close> 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 \\<open>finite (nodes G)\\<close> by auto\n  moreover have \"finite (odd_nodes_set G)\" using \\<open>finite (nodes G)\\<close> 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 \\<open>(v,w,v')\\<in>edges G\\<close>\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 \\<open>(v,w,v')\\<in>edges G\\<close> 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 \\<open>x3=v'\\<close> 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 \\<open>x3 = v'\\<close> 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 \\<open>x3=v'\\<close> 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 \\<open>finite E\\<close> 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 \\<open>x3 = v'\\<close> 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 \\<open>v=v'\\<close> 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 \\<open>finite E\\<close> 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 \\<open>x3 \\<noteq> v'\\<close> 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 \\<open>x3 \\<noteq> v'\\<close> 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 \\<open>x3 \\<noteq> v'\\<close>\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 \\<open>n = x3\\<close> 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 \\<open>n=x3\\<close> 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 \\<open>finite E\\<close> 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 \\<open>n = x3\\<close> 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 \\<open>n=x3\\<close> 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) \\<open>n \\<noteq> x3\\<close> 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 \\<open>n \\<noteq> x3\\<close> 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 \\<open>finite E\\<close> \\<open>finite V\\<close>, of x3] \\<open>is_trail v (x # xs) v'\\<close>\n          \\<open>even (degree v' G)\\<close> 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 \\<open>x1 \\<noteq> v'\\<close> 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 \\<open>x1 \\<noteq> v'\\<close> 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          then show ?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                    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 \\<open>finite E\\<close> \\<open>finite V\\<close>,of x3] \\<open>is_trail v (x # xs) v'\\<close>\n          \\<open>odd (degree v' G)\\<close> 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          then show ?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 \"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 \\<open>finite E\\<close> \\<open>finite V\\<close>, 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          with Cons.prems(3) x show ?thesis by auto\n        next\n          case False\n          then show ?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                    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 \\<open>x1 \\<noteq> v'\\<close> 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 \\<open>\\<not> (odd (degree x3 G) \\<and> x3 \\<noteq> v')\\<close> 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 \\<open>x1 \\<noteq> v'\\<close> 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 \\<open>odd (degree v G) \\<and> v \\<noteq> v'\\<close>)\n          hence \"card{v,v'}=2\" by auto \n          moreover have \"finite(odd_nodes_set G)\" \n            using \\<open>finite V\\<close> 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 \\<open>odd (degree v G) \\<and> v \\<noteq> v'\\<close> 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  with assms show ?thesis by auto  \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 \\<open>v = v'\\<close> by auto   \nqed\n\n\n\nsection\\<open>Connectivity\\<close>\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 \\<open>connected\\<close> \\<open>v \\<in> V\\<close> \\<open>v' \\<in> V\\<close> \\<open>v\\<noteq>v'\\<close>  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 \\<open>is_trail x3 ps' v'\\<close> 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 \\<open>is_trail x3 ps' v'\\<close> 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 \\<open>n \\<in> V\\<close> 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 \\<open>finite E\\<close>] unfolding exist_path_length_def \n    by auto\n  hence bound:\"\\<forall>y. exist_path_length n y \\<longrightarrow> y \\<le> card E\" by auto\n  ultimately have \"exist_path_length n (GREATEST x. exist_path_length n x)\"\n    using GreatestI_nat 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)\"\n   by (metis Greatest_le_nat 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 \\<open>even(card A)\\<close> 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\\<open>replace an edge (or its reverse in a path) by another path (in an undirected graph)\\<close>\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 \\<open>n\\<noteq>n'\\<close> n n' \\<open>connected\\<close> 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 \\<open>x = (v, e, v')\\<close> 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 \\<open>x = (v', e, v)\\<close> 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 subsetD)\n      hence \"degree v G=0\" unfolding degree_def using \\<open>finite E\\<close> \n        by force\n      thus False using \\<open>odd(degree v G)\\<close> 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 subsetD)\n      hence \"degree v' G=0\" unfolding degree_def using \\<open>finite E\\<close> \n        by force\n     thus False using \\<open>odd(degree v' G)\\<close> 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 \\<open>v \\<in> V\\<close> \\<open> odd (degree v G)\\<close> unfolding odd_nodes_set_def\n        by auto\n      moreover have \"v'\\<in>odd_nodes_set G\" \n        using \\<open>v' \\<in> V\\<close> \\<open>odd (degree v' G)\\<close>\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 \\<open>is_trail v0 max_path v'\\<close>]] max_path(1)\n        unfolding odd_nodes_set_def\n        by auto\n      moreover have \"card {v,v',v0}=3\" using \\<open>v0\\<noteq>v\\<close> \\<open>v\\<noteq>v'\\<close> \\<open>v0\\<noteq>v'\\<close> 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 \\<open>num_of_odd_nodes G=2\\<close> 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 \\<open>\\<forall>n\\<in>V. even(degree n G)\\<close> \\<open>finite V\\<close>\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 \\<open>even (degree v G)\\<close> del_UnEdge_even[OF \\<open>(v,e,v')\\<in>E\\<close> \\<open>finite E\\<close>] \n    unfolding odd_nodes_set_def \n    by auto\n  moreover have \"odd (degree v' (del_unEdge v e v' G))\" \n    using \\<open>even (degree v' G)\\<close> del_UnEdge_even'[OF \\<open>(v,e,v')\\<in>E\\<close> \\<open>finite E\\<close>] \n    unfolding odd_nodes_set_def \n    by auto  \n  moreover have \"finite (edges (del_unEdge v e v' G))\" \n    using \\<open>finite E\\<close> by auto\n  moreover have \"v\\<noteq>v'\" using no_id \\<open>(v,e,v')\\<in>E\\<close> 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 \\<open>connected\\<close> \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 \\<open>is_path n' (dropWhile (\\<lambda>x. x \\<noteq> (v, w, v') \\<and> x \\<noteq> (v', w, v)) nvs) v\\<close>\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 \\<open>x # xs = takeWhile (\\<lambda>x. x \\<noteq> (v, w, v') \\<and> x \\<noteq> (v', w, v)) nvs\\<close> \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 \\<open>nodes G1 \\<union> nodes G2=nodes (del_unEdge v w v' G)\\<close> 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                  \\<open>(n,e,n')\\<in>edges (del_unEdge v w v' G)\\<close>\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 \\<open>nodes G1 \\<inter> nodes G2={}\\<close> 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 \\<open>nodes G1 \\<inter> nodes G2={}\\<close> \\<open>edges G1 \\<union> edges G2=edges (del_unEdge v w v' G)\\<close>\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 \\<open>nodes G1 \\<inter> nodes G2={}\\<close> \n              \\<open>edges G1 \\<union> edges G2=edges (del_unEdge v w v' G)\\<close>\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 \\<open>nodes G1 \\<inter> nodes G2={}\\<close> \\<open>edges G1 \\<union> edges G2=edges (del_unEdge v w v' G)\\<close>\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  \\<open>nodes G1 \\<inter> nodes G2={}\\<close> \\<open>edges G1 \\<union> edges G2=edges (del_unEdge v w v' G)\\<close>\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 \\<open>nodes G1 \\<inter> nodes G2={}\\<close> \\<open>n\\<in>nodes G1\\<close>\n        by auto\n      hence \"e\\<notin>edges G2\" using valid_graph.E_validD[OF \\<open>valid_graph G2\\<close>] \\<open>fst e=n\\<close> \n        by (metis prod.exhaust fst_conv)  \n      ultimately have \"e\\<in>edges G1\" using \\<open>edges G1 \\<union> edges G2 =edges G\\<close> by auto\n      thus \"e \\<in> {e \\<in> edges G1. fst e = n}\" using \\<open>fst e=n\\<close> 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 \\<open>Adjacent nodes\\<close>\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 \\<open>finite E\\<close>, of v]  unfolding adjacent_def by auto\nqed\n\nsection\\<open>Undirected simple graph\\<close>\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 \\<open>finite V\\<close> 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'] \\<open>(v, w, u) \\<in> E\\<close> 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=\\<open>valid_unSimpGraph G\\<close>\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 \\<open>finite (edges G)\\<close> unfolding degree_def by auto\n      thus False using \\<open>0 = degree v G\\<close> 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 \\<open>valid_unSimpGraph G\\<close> 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' \\<open>valid_unSimpGraph G\\<close> by auto\n  moreover have \"n = degree v (del_unEdge v w u G)\" \n    using \\<open>Suc n = degree v G\\<close>\\<open>(v, w, u) \\<in> edges G\\<close>  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 \\<open>finite (edges G)\\<close> 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 \\<open>(v,w,u)\\<in>edges G\\<close> 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 \\<open>valid_unSimpGraph G\\<close> \\<open>(v,w,u)\\<in>edges G\\<close>]\n        by auto\n      moreover have \"finite {n. valid_unMultigraph.adjacent G v n}\" \n        using valid_unMultigraph.adjacent_finite[OF valid \\<open>finite (edges G)\\<close>] 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) \\<open>n = degree v (del_unEdge v w u G)\\<close>)\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/Koenigsberg_Friendship/MoreGraph.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314768368161, "lm_q2_score": 0.8244619285331332, "lm_q1q2_score": 0.7301694353625282}}
{"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=>i\"  where\n    \"Memrel(A)   == {z\\<in>A*A . \\<exists>x y. z=<x,y> & x\\<in>y }\"\n\ndefinition\n  Transset  :: \"i=>o\"  where\n    \"Transset(i) == \\<forall>x\\<in>i. x<=i\"\n\ndefinition\n  Ord  :: \"i=>o\"  where\n    \"Ord(i)      == Transset(i) & (\\<forall>x\\<in>i. Transset(x))\"\n\ndefinition\n  lt        :: \"[i,i] => o\"  (infixl \"<\" 50)   (*less-than on ordinals*)  where\n    \"i<j         == i\\<in>j & Ord(j)\"\n\ndefinition\n  Limit         :: \"i=>o\"  where\n    \"Limit(i)    == Ord(i) & 0<i & (\\<forall>y. y<i \\<longrightarrow> succ(y)<i)\"\n\nabbreviation\n  le  (infixl \"\\<le>\" 50) where\n  \"x \\<le> y == 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\"\napply (unfold 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    \"[| Transset(C); {a,b}: C |] ==> a\\<in>C & b\\<in>C\"\nby (unfold Transset_def, blast)\n\nlemma Transset_Pair_D:\n    \"[| Transset(C); <a,b>\\<in>C |] ==> a\\<in>C & b\\<in>C\"\napply (simp add: Pair_def)\napply (blast dest: Transset_doubleton_D)\ndone\n\nlemma Transset_includes_domain:\n    \"[| Transset(C); A*B \\<subseteq> C; b \\<in> B |] ==> A \\<subseteq> C\"\nby (blast dest: Transset_Pair_D)\n\nlemma Transset_includes_range:\n    \"[| Transset(C); A*B \\<subseteq> C; a \\<in> A |] ==> 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    \"[| Transset(i);  Transset(j) |] ==> Transset(i \\<union> j)\"\nby (unfold Transset_def, blast)\n\nlemma Transset_Int:\n    \"[| Transset(i);  Transset(j) |] ==> Transset(i \\<inter> j)\"\nby (unfold Transset_def, blast)\n\nlemma Transset_succ: \"Transset(i) ==> Transset(succ(i))\"\nby (unfold Transset_def, blast)\n\nlemma Transset_Pow: \"Transset(i) ==> Transset(Pow(i))\"\nby (unfold Transset_def, blast)\n\nlemma Transset_Union: \"Transset(A) ==> Transset(\\<Union>(A))\"\nby (unfold Transset_def, blast)\n\nlemma Transset_Union_family:\n    \"[| !!i. i\\<in>A ==> Transset(i) |] ==> Transset(\\<Union>(A))\"\nby (unfold Transset_def, blast)\n\nlemma Transset_Inter_family:\n    \"[| !!i. i\\<in>A ==> Transset(i) |] ==> Transset(\\<Inter>(A))\"\nby (unfold Inter_def Transset_def, blast)\n\nlemma Transset_UN:\n     \"(!!x. x \\<in> A ==> Transset(B(x))) ==> Transset (\\<Union>x\\<in>A. B(x))\"\nby (rule Transset_Union_family, auto)\n\nlemma Transset_INT:\n     \"(!!x. x \\<in> A ==> Transset(B(x))) ==> 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    \"[| Transset(i);  !!x. x\\<in>i ==> Transset(x) |]  ==>  Ord(i)\"\nby (simp add: Ord_def)\n\nlemma Ord_is_Transset: \"Ord(i) ==> Transset(i)\"\nby (simp add: Ord_def)\n\nlemma Ord_contains_Transset:\n    \"[| Ord(i);  j\\<in>i |] ==> Transset(j) \"\nby (unfold Ord_def, blast)\n\n\nlemma Ord_in_Ord: \"[| Ord(i);  j\\<in>i |] ==> Ord(j)\"\nby (unfold Ord_def Transset_def, blast)\n\n(*suitable for rewriting PROVIDED i has been fixed*)\nlemma Ord_in_Ord': \"[| j\\<in>i; Ord(i) |] ==> Ord(j)\"\nby (blast intro: Ord_in_Ord)\n\n(* Ord(succ(j)) ==> Ord(j) *)\nlemmas Ord_succD = Ord_in_Ord [OF _ succI1]\n\nlemma Ord_subset_Ord: \"[| Ord(i);  Transset(j);  j<=i |] ==> Ord(j)\"\nby (simp add: Ord_def Transset_def, blast)\n\nlemma OrdmemD: \"[| j\\<in>i;  Ord(i) |] ==> j<=i\"\nby (unfold Ord_def Transset_def, blast)\n\nlemma Ord_trans: \"[| i\\<in>j;  j\\<in>k;  Ord(k) |] ==> i\\<in>k\"\nby (blast dest: OrdmemD)\n\nlemma Ord_succ_subsetI: \"[| i\\<in>j;  Ord(j) |] ==> 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) ==> 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]: \"[| Ord(i); Ord(j) |] ==> Ord(i \\<union> j)\"\napply (unfold Ord_def)\napply (blast intro!: Transset_Un)\ndone\n\nlemma Ord_Int [TC]: \"[| Ord(i); Ord(j) |] ==> Ord(i \\<inter> j)\"\napply (unfold 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: \"~ (\\<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: \"[| i\\<in>j;  Ord(j) |] ==> i<j\"\nby (unfold lt_def, blast)\n\nlemma ltE:\n    \"[| i<j;  [| i\\<in>j;  Ord(i);  Ord(j) |] ==> P |] ==> P\"\napply (unfold lt_def)\napply (blast intro: Ord_in_Ord)\ndone\n\nlemma ltD: \"i<j ==> i\\<in>j\"\nby (erule ltE, assumption)\n\nlemma not_lt0 [simp]: \"~ i<0\"\nby (unfold lt_def, blast)\n\nlemma lt_Ord: \"j<i ==> Ord(j)\"\nby (erule ltE, assumption)\n\nlemma lt_Ord2: \"j<i ==> Ord(i)\"\nby (erule ltE, assumption)\n\n(* @{term\"ja \\<le> j ==> Ord(j)\"} *)\nlemmas le_Ord2 = lt_Ord2 [THEN Ord_succD]\n\n(* i<0 ==> R *)\nlemmas lt0E = not_lt0 [THEN notE, elim!]\n\nlemma lt_trans [trans]: \"[| i<j;  j<k |] ==> i<k\"\nby (blast intro!: ltI elim!: ltE intro: Ord_trans)\n\nlemma lt_not_sym: \"i<j ==> ~ (j<i)\"\napply (unfold lt_def)\napply (blast elim: mem_asym)\ndone\n\n(* [| i<j;  ~P ==> j<i |] ==> P *)\nlemmas lt_asym = lt_not_sym [THEN swap]\n\nlemma lt_irrefl [elim!]: \"i<i ==> P\"\nby (blast intro: lt_asym)\n\nlemma lt_not_refl: \"~ i<i\"\napply (rule notI)\napply (erule lt_irrefl)\ndone\n\n\ntext\\<open>Recall that  @{term\"i \\<le> j\"}  abbreviates  @{term\"i<succ(j)\"} !!\\<close>\n\nlemma le_iff: \"i \\<le> j <-> i<j | (i=j & Ord(j))\"\nby (unfold lt_def, blast)\n\n(*Equivalently, i<j ==> i < succ(j)*)\nlemma leI: \"i<j ==> i \\<le> j\"\nby (simp add: le_iff)\n\nlemma le_eqI: \"[| i=j;  Ord(j) |] ==> 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: \"(~ (i=j & Ord(j)) ==> i<j) ==> i \\<le> j\"\nby (simp add: le_iff, blast)\n\nlemma leE:\n    \"[| i \\<le> j;  i<j ==> P;  [| i=j;  Ord(j) |] ==> P |] ==> P\"\nby (simp add: le_iff, blast)\n\nlemma le_anti_sym: \"[| i \\<le> j;  j \\<le> i |] ==> 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]: \"<a,b> \\<in> Memrel(A) <-> a\\<in>b & a\\<in>A & b\\<in>A\"\nby (unfold Memrel_def, blast)\n\nlemma MemrelI [intro!]: \"[| a \\<in> b;  a \\<in> A;  b \\<in> A |] ==> <a,b> \\<in> Memrel(A)\"\nby auto\n\nlemma MemrelE [elim!]:\n    \"[| <a,b> \\<in> Memrel(A);\n        [| a \\<in> A;  b \\<in> A;  a\\<in>b |]  ==> P |]\n     ==> P\"\nby auto\n\nlemma Memrel_type: \"Memrel(A) \\<subseteq> A*A\"\nby (unfold Memrel_def, blast)\n\nlemma Memrel_mono: \"A<=B ==> 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))\"\napply (unfold wf_def)\napply (rule foundation [THEN disjE, THEN allI], erule disjI1, blast)\ndone\n\ntext\\<open>The premise @{term \"Ord(i)\"} does not suffice.\\<close>\nlemma trans_Memrel:\n    \"Ord(i) ==> 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) ==> 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) ==> <a,b> \\<in> Memrel(A) <-> a\\<in>b & 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    \"[| i \\<in> k;  Transset(k);\n        !!x.[| x \\<in> k;  \\<forall>y\\<in>x. P(y) |] ==> P(x) |]\n     ==>  P(i)\"\napply (simp add: Transset_def)\napply (erule wf_Memrel [THEN wf_induct2], blast+)\ndone\n\n(*Induction over an ordinal*)\nlemmas Ord_induct [consumes 2] = Transset_induct [rule_format, OF _ Ord_is_Transset]\n\n(*Induction over the class of ordinals -- a useful corollary of Ord_induct*)\n\nlemma trans_induct [rule_format, consumes 1, case_names step]:\n    \"[| Ord(i);\n        !!x.[| Ord(x);  \\<forall>y\\<in>x. P(y) |] ==> P(x) |]\n     ==>  P(i)\"\napply (rule Ord_succ [THEN succI1 [THEN Ord_induct]], assumption)\napply (blast intro: Ord_succ [THEN Ord_in_Ord])\ndone\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 ==> ~ i<j\"\nby (blast elim!: leE elim: lt_asym)\n\nlemma not_lt_imp_le: \"[| ~ i<j;  Ord(i);  Ord(j) |] ==> 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) ==> i\\<in>j <-> i<j\"\nby (unfold lt_def, blast)\n\nlemma not_lt_iff_le: \"[| Ord(i);  Ord(j) |] ==> ~ i<j <-> j \\<le> i\"\nby (blast dest: le_imp_not_lt not_lt_imp_le)\n\nlemma not_le_iff_lt: \"[| Ord(i);  Ord(j) |] ==> ~ 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) ==> 0 \\<le> i\"\nby (erule not_lt_iff_le [THEN iffD1], auto)\n\nlemma Ord_0_lt: \"[| Ord(i);  i\\<noteq>0 |] ==> 0<i\"\napply (erule not_le_iff_lt [THEN iffD1])\napply (rule Ord_0, blast)\ndone\n\nlemma Ord_0_lt_iff: \"Ord(i) ==> 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: \"[| j<=i;  Ord(i);  Ord(j) |] ==> 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 ==> i<=j\"\nby (blast dest: OrdmemD elim: ltE leE)\n\nlemma le_subset_iff: \"j \\<le> i <-> j<=i & Ord(i) & 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) & 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: \"[| Ord(i);  Ord(j);  !!x. x<j ==> x<i |] ==> j \\<le> i\"\nby (blast intro: not_lt_imp_le dest: lt_irrefl)\n\nsubsubsection\\<open>Transitivity Laws\\<close>\n\nlemma lt_trans1: \"[| i \\<le> j;  j<k |] ==> i<k\"\nby (blast elim!: leE intro: lt_trans)\n\nlemma lt_trans2: \"[| i<j;  j \\<le> k |] ==> i<k\"\nby (blast elim!: leE intro: lt_trans)\n\nlemma le_trans: \"[| i \\<le> j;  j \\<le> k |] ==> i \\<le> k\"\nby (blast intro: lt_trans1)\n\nlemma succ_leI: \"i<j ==> 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) ==> i<j  *)\nlemma succ_leE: \"succ(i) \\<le> j ==> 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) ==> i \\<le> j\"\nby (blast dest!: succ_leE)\n\nlemma lt_subset_trans: \"[| i \\<subseteq> j;  j<k;  Ord(i) |] ==> i<k\"\napply (rule subset_imp_le [THEN lt_trans1])\napply (blast intro: elim: ltE) +\ndone\n\nlemma lt_imp_0_lt: \"j<i ==> 0<i\"\nby (blast intro: lt_trans1 Ord_0_le [OF lt_Ord])\n\nlemma succ_lt_iff: \"succ(i) < j <-> i<j & 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) ==> 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: \"[| Ord(i); Ord(j) |] ==> i \\<le> i \\<union> j\"\nby (rule Un_upper1 [THEN subset_imp_le], auto)\n\nlemma Un_upper2_le: \"[| Ord(i); Ord(j) |] ==> 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: \"[| i<k;  j<k |] ==> 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: \"[| Ord(i); Ord(j) |] ==> i \\<union> j < k  <->  i<k & 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    \"[| Ord(i); Ord(j); Ord(k) |] ==> i \\<union> j \\<in> k  <->  i\\<in>k & 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: \"[| i<k;  j<k |] ==> 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     \"[| Ord(i); Ord(j) |] ==> 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     \"[| Ord(i); Ord(j) |] ==> 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     \"[| Ord(i); Ord(j) |] ==> 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     \"[| Ord(i); Ord(j) |] ==> 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: \"[|k < i; Ord(j)|] ==> k < i \\<union> j\"\nby (simp add: lt_Un_iff lt_Ord2)\n\nlemma Un_upper2_lt: \"[|k < j; Ord(i)|] ==> 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) ==> \\<Union>(succ(i)) = i\"\nby (blast intro: Ord_trans)\n\n\nsubsection\\<open>Results about Limits\\<close>\n\nlemma Ord_Union [intro,simp,TC]: \"[| !!i. i\\<in>A ==> Ord(i) |] ==> 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     \"[| !!x. x\\<in>A ==> Ord(B(x)) |] ==> Ord(\\<Union>x\\<in>A. B(x))\"\nby (rule Ord_Union, blast)\n\nlemma Ord_Inter [intro,simp,TC]:\n    \"[| !!i. i\\<in>A ==> Ord(i) |] ==> 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    \"[| !!x. x\\<in>A ==> Ord(B(x)) |] ==> 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    \"[| Ord(i);  !!x. x\\<in>A ==> b(x) \\<le> i |] ==> (\\<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    \"[| j<i;  !!x. x\\<in>A ==> b(x)<j |] ==> (\\<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     \"[| a\\<in>A;  i < b(a);  Ord(\\<Union>x\\<in>A. b(x)) |] ==> i < (\\<Union>x\\<in>A. b(x))\"\nby (unfold lt_def, blast)\n\nlemma UN_upper_le:\n     \"[| a \\<in> A;  i \\<le> b(a);  Ord(\\<Union>x\\<in>A. b(x)) |] ==> 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) ==> (j < \\<Union>(A)) <-> (\\<exists>i\\<in>A. j<i)\"\nby (auto simp: lt_def Ord_Union)\n\nlemma Union_upper_le:\n     \"[| j \\<in> J;  i\\<le>j;  Ord(\\<Union>(J)) |] ==> i \\<le> \\<Union>J\"\napply (subst Union_eq_UN)\napply (rule UN_upper_le, auto)\ndone\n\nlemma le_implies_UN_le_UN:\n    \"[| !!x. x\\<in>A ==> c(x) \\<le> d(x) |] ==> (\\<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) ==> (\\<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) ==> \\<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) ==> \\<Union>(i) = i\"\napply (unfold Limit_def)\napply (fast intro!: ltI elim!: ltE elim: Ord_trans)\ndone\n\nlemma Limit_is_Ord: \"Limit(i) ==> Ord(i)\"\napply (unfold Limit_def)\napply (erule conjunct1)\ndone\n\nlemma Limit_has_0: \"Limit(i) ==> 0 < i\"\napply (unfold Limit_def)\napply (erule conjunct2 [THEN conjunct1])\ndone\n\nlemma Limit_nonzero: \"Limit(i) ==> i \\<noteq> 0\"\nby (drule Limit_has_0, blast)\n\nlemma Limit_has_succ: \"[| Limit(i);  j<i |] ==> succ(j) < i\"\nby (unfold Limit_def, blast)\n\nlemma Limit_succ_lt_iff [simp]: \"Limit(i) ==> 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]: \"~ Limit(0)\"\nby (simp add: Limit_def)\n\nlemma Limit_has_1: \"Limit(i) ==> 1 < i\"\nby (blast intro: Limit_has_0 Limit_has_succ)\n\nlemma increasing_LimitI: \"[| 0<l; \\<forall>x\\<in>l. \\<exists>y\\<in>l. x<y |] ==> 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 \"~ 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)) ==> 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]: \"~ Limit(succ(i))\"\nby blast\n\nlemma Limit_le_succD: \"[| Limit(i);  i \\<le> succ(j) |] ==> 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) ==> i=0 | (\\<exists>j. Ord(j) & 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     \"[| Ord(i);\n         P(0);\n         !!x. [| Ord(x);  P(x) |] ==> P(succ(x));\n         !!x. [| Limit(x);  \\<forall>y\\<in>x. P(y) |] ==> P(x)\n      |] ==> P(i)\"\napply (erule trans_induct)\napply (erule Ord_cases, blast+)\ndone\n\nlemmas trans_induct3 = trans_induct3_raw [rule_format, case_names 0 succ limit, consumes 1]\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: \"[| !!x. x\\<in>I ==> x\\<le>j; Ord(j) |] ==> \\<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: \"[|\\<forall>x\\<in>X. Ord(x);  \\<Union>X = succ(j)|] ==> succ(j) \\<in> X\"\n  by (drule Ord_set_cases, auto)\n\nlemma Limit_Union [rule_format]: \"[| I \\<noteq> 0;  \\<forall>i\\<in>I. Limit(i) |] ==> Limit(\\<Union>I)\"\napply (simp add: Limit_def lt_def)\napply (blast intro!: equalityI)\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/Ordinal.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.885631476836816, "lm_q2_score": 0.8244619263765707, "lm_q1q2_score": 0.7301694334526085}}
{"text": "(*  Author:     Tobias Nipkow, TU M\u00fcnchen\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> x \\<ge> y)\"\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 {* The following definition of of addition is totalized\nto make it asociative and commutative. Normally the sum of plus and minus infinity is undefined. *}\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{* Numerals: *}\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": "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/Extended.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240860523328, "lm_q2_score": 0.8438951045175643, "lm_q1q2_score": 0.7301583705302475}}
{"text": "(*\n  File:     Jacobi_Symbol.thy\n  Authors:  Daniel St\u00fcwe, Manuel Eberl\n\n  The Jacobi symbol, a generalisation of the Legendre symbol.\n  This is used in the Solovay--Strassen test.\n*)\nsection \\<open>The Jacobi Symbol\\<close>\ntheory Jacobi_Symbol\nimports \n  Legendre_Symbol\n  Algebraic_Auxiliaries\nbegin\n\ntext \\<open>\n  The Jacobi symbol is a generalisation of the Legendre symbol to non-primes \\cite{Legendre_Symbol, Jacobi_Symbol}.\n  It is defined as\n  \\[\\left(\\frac{a}{n}\\right) =\n      \\left(\\frac{a}{p_1}\\right)^{k_1} \\ldots \\left(\\frac{a}{p_l}\\right)^{k_l}\\]\n  where $(\\frac{a}{p})$ denotes the Legendre symbol, \\<open>a\\<close> is an integer, \\<open>n\\<close> is an odd natural\n  number and $p_1^{k_1}\\ldots p_l^{k_l}$ is its prime factorisation.\n\n  There is, however, a fairly natural generalisation to all non-zero integers for \\<open>n\\<close>.\n  It is less clear what a good choice for \\<open>n = 0\\<close> is; Mathematica and Maxima adopt\n  the convention that $(\\frac{\\pm 1}{0}) = 1$ and $(\\frac{a}{0}) = 0$ otherwise. However,\n  we chose the slightly different convention $(\\frac{a}{0}) = 0$ for \\<^emph>\\<open>all\\<close> \\<open>a\\<close> because then\n  the Jacobi symbol is completely multiplicative in both arguments without any restrictions.\n\\<close>\ndefinition Jacobi :: \"int \\<Rightarrow> int \\<Rightarrow> int\" where\n  \"Jacobi a n = (if n = 0 then 0 else\n                  (\\<Prod>p\\<in>#prime_factorization n. Legendre a p))\"\n\nlemma Jacobi_0_right [simp]: \"Jacobi a 0 = 0\"\n  by (simp add: Jacobi_def)\n\nlemma Jacobi_mult_left [simp]: \"Jacobi (a * b) n = Jacobi a n * Jacobi b n\"\nproof (cases \"n = 0\")\n  case False\n  have *: \"{# Legendre (a * b) p          . p \\<in># prime_factorization n #} =\n           {# Legendre a p * Legendre b p . p \\<in># prime_factorization n #}\"\n    by (meson Legendre_mult in_prime_factors_imp_prime image_mset_cong)\n\n  show ?thesis using False unfolding Jacobi_def * prod_mset.distrib by auto\nqed auto\n\nlemma Jacobi_mult_right [simp]: \"Jacobi a (n * m) = Jacobi a n * Jacobi a m\"\n  by (cases \"m = 0\"; cases \"n = 0\")\n     (auto simp: Jacobi_def prime_factorization_mult)\n\nlemma prime_p_Jacobi_eq_Legendre[intro!]: \"prime p \\<Longrightarrow> Jacobi a p = Legendre a p\"\n  unfolding Jacobi_def prime_factorization_prime by simp\n\nlemma Jacobi_mod [simp]: \"Jacobi (a mod m) n = Jacobi a n\" if \"n dvd m\"\nproof -\n  have *: \"{# Legendre (a mod m) p . p \\<in># prime_factorization n #} =\n           {# Legendre a p . p \\<in># prime_factorization n #}\" using that\n    by (intro image_mset_cong, subst Legendre_mod)\n       (auto intro: dvd_trans[OF in_prime_factors_imp_dvd])\n  thus ?thesis by (simp add: Jacobi_def)\nqed\n\nlemma Jacobi_mod_cong: \"[a = b] (mod n) \\<Longrightarrow> Jacobi a n = Jacobi b n\"\n  by (metis Jacobi_mod cong_def dvd_refl)\n\nlemma Jacobi_1_eq_1 [simp]: \"p \\<noteq> 0 \\<Longrightarrow> Jacobi 1 p = 1\"\n  by (simp add: Jacobi_def in_prime_factors_imp_prime cong: image_mset_cong)\n\n\n\nlemma Jacobi_p_eq_2'[simp]: \"n > 0 \\<Longrightarrow> Jacobi a (2^n) = a mod 2\"\n  by (auto simp add: Jacobi_def prime_factorization_prime_power)\n\nlemma Jacobi_prod_mset[simp]: \"n \\<noteq> 0 \\<Longrightarrow> Jacobi (prod_mset M) n = (\\<Prod>q\\<in>#M. Jacobi q n)\"\n  by (induction M) simp_all\n\nlemma non_trivial_coprime_neq:\n  \"1 < a \\<Longrightarrow> 1 < b \\<Longrightarrow> coprime a b \\<Longrightarrow> a \\<noteq> b\" for a b :: int by auto\n\n\nlemma odd_odd_even: \n  fixes a b :: int \n  assumes \"odd a\" \"odd b\"\n  shows \"even ((a*b-1) div 2) = even ((a-1) div 2 + (b-1) div 2)\"\n  using assms by (auto elim!: oddE simp: algebra_simps)\n\nlemma prime_nonprime_wlog [case_names primes nonprime sym]:\n  assumes \"\\<And>p q. prime p \\<Longrightarrow> prime q \\<Longrightarrow> P p q\"\n  assumes \"\\<And>p q. \\<not>prime p \\<Longrightarrow> P p q\"\n  assumes \"\\<And>p q. P p q \\<Longrightarrow> P q p\"\n  shows   \"P p q\"\n  by (cases \"prime p\"; cases \"prime q\") (auto intro: assms)\n\nlemma Quadratic_Reciprocity_Jacobi:\n  fixes p q :: int\n  assumes \"coprime p q\"\n      and \"2 < p\" \"2 < q\"\n      and \"odd p\" \"odd q\"\n    shows \"Jacobi p q * Jacobi q p =\n           (- 1) ^ (nat ((p - 1) div 2 * ((q - 1) div 2)))\"\n  using assms\nproof (induction \"nat p\" \"nat q\" arbitrary: p q \n         rule: measure_induct_rule[where f = \"\\<lambda>(a, b). a + b\", split_format(complete), simplified])\n  case (1 p q)\n  thus ?case\n  proof (induction p q rule: prime_nonprime_wlog)\n    case (sym p q)\n    thus ?case by (simp only: add_ac coprime_commute mult_ac) blast\n  next\n    case (primes p q)\n    from \\<open>prime p\\<close> \\<open>prime q\\<close> have \"prime (nat p)\" \"prime (nat q)\" \"p \\<noteq> q\"\n      using prime_int_nat_transfer primes(4) non_trivial_coprime_neq prime_gt_1_int\n      by blast+\n\n    with Quadratic_Reciprocity_int and prime_p_Jacobi_eq_Legendre\n    show ?case\n      using \\<open>prime p\\<close> \\<open>prime q\\<close> primes(5-) \n      by presburger\n  next\n    case (nonprime p q)\n    from \\<open>\\<not>prime p\\<close> obtain a b where *: \"p = a * b\" \"1 < b\" \"1 < a\"\n      using \\<open>2 < p\\<close> prime_divisor_exists_strong[of p] by auto\n\n    hence odd_ab: \"odd a\" \"odd b\" using \\<open>odd p\\<close> by simp_all\n\n    moreover have \"2 < b\" and \"2 < a\" \n      using odd_ab and * by presburger+\n\n    moreover have \"coprime a q\" and \"coprime b q\" using \\<open>coprime p q\\<close> \n      unfolding * by simp_all\n\n    ultimately have IH: \"Jacobi a q * Jacobi q a = (- 1) ^ nat ((a - 1) div 2 * ((q - 1) div 2))\"\n                        \"Jacobi b q * Jacobi q b = (- 1) ^ nat ((b - 1) div 2 * ((q - 1) div 2))\"\n      by (auto simp: * nonprime)\n\n    have pos: \"0 < q\" \"0 < p\" \"0 < a\" \"0 < b\" \n      using * \\<open>2 < q\\<close> by simp_all\n\n    have \"Jacobi p q * Jacobi q p = (Jacobi a q * Jacobi q a) * (Jacobi b q * Jacobi q b)\"\n      using * by simp\n\n    also have \"... = (- 1) ^ nat ((a - 1) div 2 * ((q - 1) div 2)) *\n                     (- 1) ^ nat ((b - 1) div 2 * ((q - 1) div 2))\"\n      using IH by presburger\n\n    also from odd_odd_even[OF odd_ab]\n    have \"... = (- 1) ^ nat ((p - 1) div 2 * ((q - 1) div 2))\"\n      unfolding * minus_one_power_iff using \\<open>2 < q\\<close> *\n      by (auto simp add: even_nat_iff pos_imp_zdiv_nonneg_iff)\n\n    finally show ?case .\n  qed\nqed\n\nlemma Jacobi_values: \"Jacobi p q \\<in> {1, -1, 0}\"\nproof (cases \"q = 0\")\n  case False\n  hence \"\\<bar>Legendre p x\\<bar> = 1\" if \"x \\<in># prime_factorization q\" \"Jacobi p q \\<noteq> 0\" for x\n    using that prod_mset_zero_iff Legendre_values[of p x]\n    unfolding Jacobi_def is_unit_prod_mset_iff set_image_mset\n    by fastforce\n\n  then have \"is_unit (prod_mset (image_mset (Legendre p) (prime_factorization q)))\"\n    if \"Jacobi p q \\<noteq> 0\"\n    using that False\n    unfolding Jacobi_def is_unit_prod_mset_iff \n    by auto\n\n  thus ?thesis by (auto simp: Jacobi_def)\nqed auto\n\nlemma Quadratic_Reciprocity_Jacobi':\n  fixes p q :: int\n  assumes \"coprime p q\"\n      and \"2 < p\" \"2 < q\"\n      and \"odd p\" \"odd q\"\n    shows \"Jacobi q p = (if p mod 4 = 3 \\<and> q mod 4 = 3 then -1 else 1) * Jacobi p q\"\nproof -\n  have aux: \"a \\<in> {1, -1, 0} \\<Longrightarrow> c \\<noteq> 0 \\<Longrightarrow> a*b = c \\<Longrightarrow> b = c * a\" for b c a :: int by auto\n\n  from Quadratic_Reciprocity_Jacobi[OF assms] \n  have \"Jacobi q p = (-1) ^ nat ((p - 1) div 2 * ((q - 1) div 2)) * Jacobi p q\"\n    using Jacobi_values by (fastforce intro!: aux)\n\n  also have \"(-1 :: int) ^ nat ((p - 1) div 2 * ((q - 1) div 2)) = (if even ((p - 1) div 2) \\<or> even ((q - 1) div 2) then 1 else - 1)\"\n    unfolding minus_one_power_iff using \\<open>2 < p\\<close> \\<open>2 < q\\<close>\n    by (auto simp: even_nat_iff)\n\n  also have \"... = (if p mod 4 = 3 \\<and> q mod 4 = 3 then -1 else 1)\"\n    using \\<open>odd p\\<close> \\<open>odd q\\<close> by presburger\n\n  finally show ?thesis .\n\nqed\n\n\n\nlemma odd_odd_even': \n  fixes a b :: int \n  assumes \"odd a\" \"odd b\"\n  shows \"even (((a * b)\\<^sup>2 - 1) div 8) \\<longleftrightarrow> even (((a\\<^sup>2 - 1) div 8) + ((b\\<^sup>2 - 1) div 8))\"\nproof -\n  obtain x where [simp]: \"a = 2*x + 1\" using \\<open>odd a\\<close> by (auto elim: oddE)\n  obtain y where [simp]: \"b = 2*y + 1\" using \\<open>odd b\\<close> by (auto elim: oddE)\n  show ?thesis\n    by (cases \"even x\"; cases \"even y\"; elim oddE evenE)\n       (auto simp: power2_eq_square algebra_simps)\nqed\n\nlemma odd_odd_even_nat': \n  fixes a b :: nat \n  assumes \"odd a\" \"odd b\"\n  shows \"even (((a * b)\\<^sup>2 - 1) div 8) \\<longleftrightarrow> even (((a\\<^sup>2 - 1) div 8) + ((b\\<^sup>2 - 1) div 8))\"\nproof -\n  obtain x where [simp]: \"a = 2*x + 1\" using \\<open>odd a\\<close> by (auto elim: oddE)\n  obtain y where [simp]: \"b = 2*y + 1\" using \\<open>odd b\\<close> by (auto elim: oddE)\n  show ?thesis\n    by (cases \"even x\"; cases \"even y\"; elim oddE evenE)\n       (auto simp: power2_eq_square algebra_simps)\nqed\n\nlemma supplement2_Jacobi: \"odd p \\<Longrightarrow> p > 1 \\<Longrightarrow> Jacobi 2 p = (- 1) ^ (((nat p)\\<^sup>2 - 1) div 8)\"\nproof (induction p rule: prime_divisors_induct)\n  case (factor p x)\n\n  then have \"odd x\" by force\n\n  have \"2 < p\" \n    using \\<open>odd (p * x)\\<close> prime_gt_1_int[OF \\<open>prime p\\<close>] \n    by (cases \"p = 2\") auto\n\n  have \"odd p\" using prime_odd_int[OF \\<open>prime p\\<close> \\<open>2 < p\\<close>] .\n\n  have \"0 < x\"\n    using \\<open>1 < (p * x)\\<close> prime_gt_0_int[OF \\<open>prime p\\<close>]\n    and less_trans less_numeral_extra(1) zero_less_mult_pos by blast\n\n  have base_case : \"Jacobi 2 p = (- 1) ^ (((nat p)\\<^sup>2 - 1) div 8)\" \n    using \\<open>2 < p\\<close> \\<open>prime p\\<close> supplement2_Legendre and prime_p_Jacobi_eq_Legendre\n    by presburger\n\n  show ?case proof (cases \"x = 1\")\n    case True\n    thus ?thesis using base_case by force\n  next\n    case False\n    have \"Jacobi 2 (p * x) = Jacobi 2 p * Jacobi 2 x\"\n      using \\<open>2 < p\\<close> \\<open>0 < x\\<close> by simp\n\n    also have \"Jacobi 2 x = (- 1) ^ (((nat x)\\<^sup>2 - 1) div 8)\"\n      using \\<open>odd x\\<close> \\<open>0 < x\\<close> \\<open>x \\<noteq> 1\\<close> by (intro factor.IH) auto\n\n    also note base_case\n\n    also have \"(-1) ^ (((nat p)\\<^sup>2 - 1) div 8) * (-1) ^ (((nat x)\\<^sup>2 - 1) div 8)\n             = (-1 :: int) ^ (((nat (p * x))\\<^sup>2 - 1) div 8)\" \n      unfolding minus_one_power_iff\n      using \\<open>2 < p\\<close> \\<open>0 < x\\<close> \\<open>odd x\\<close> \\<open>odd p\\<close> and odd_odd_even_nat'\n      using [[linarith_split_limit = 0]]\n      by (force simp add: nat_mult_distrib even_nat_iff)\n\n    finally show ?thesis .\n  qed\nqed simp_all\n\n\n\nlemma mod_int_wlog [consumes 1, case_names modulo]:\n  fixes P :: \"int \\<Rightarrow> bool\"\n  assumes \"b > 0\"\n  assumes \"\\<And>k. 0 \\<le> k \\<Longrightarrow> k < b \\<Longrightarrow> n mod b = k \\<Longrightarrow> P n\"\n  shows   \"P n\"\n  using assms and pos_mod_conj by blast \n\nlemma supplement2_Jacobi':\n  assumes \"odd p\" and \"p > 1\"\n  shows \"Jacobi 2 p = (if p mod 8 = 1 \\<or> p mod 8 = 7 then 1 else -1)\"\nproof -\n  have \"0 < (4 :: nat)\" by simp\n  then have *: \"even ((p\\<^sup>2 - 1) div 8) = (p mod 8 = 1 \\<or> p mod 8 = 7)\" if \"odd p\" for p :: nat\n  proof(induction p rule: mod_nat_wlog)\n    case (modulo k)\n    then consider \"p mod 4 = 1\" | \"p mod 4 = 3\"\n      using \\<open>odd p\\<close>\n      by (metis dvd_0_right even_even_mod_4_iff even_numeral mod_exhaust_less_4)\n\n    then show ?case proof (cases)\n      case 1\n      then obtain l where l: \"p = 4 * l + 1\" using mod_natE by blast\n      have \"even l = ((4 * l + 1) mod 8 = 1 \\<or> (4 * l + 1) mod 8 = 7)\" by presburger\n      thus ?thesis by (simp add: l power2_eq_square algebra_simps)\n    next\n      case 2\n      then obtain l where l: \"p = 4 * l + 3\" using mod_natE by blast\n      have \"odd l = ((3 + l * 4) mod 8 = Suc 0 \\<or> (3 + l * 4) mod 8 = 7)\" by presburger\n      thus ?thesis by (simp add: l power2_eq_square algebra_simps)\n    qed\n  qed\n\n  have [simp]: \"nat p mod 8 = nat (p mod 8)\"\n    using \\<open>p > 1\\<close> using nat_mod_distrib[of p 8] by simp\n  from assms have \"odd (nat p)\" by (simp add: even_nat_iff)\n  show ?thesis\n    unfolding supplement2_Jacobi[OF assms]\n              minus_one_power_iff *[OF \\<open>odd (nat p)\\<close>]\n    by (simp add: nat_eq_iff)\nqed\n\ntheorem supplement1_Jacobi:\n  \"odd p \\<Longrightarrow> 1 < p \\<Longrightarrow> Jacobi (-1) p = (-1) ^ (nat ((p - 1) div 2))\"\nproof (induction p rule: prime_divisors_induct)\n  case (factor p x)\n  then have \"odd x\" by force\n\n  have \"2 < p\" \n    using \\<open>odd (p * x)\\<close> prime_gt_1_int[OF \\<open>prime p\\<close>]\n    by (cases \"p = 2\") auto\n\n  have \"prime (nat p)\"\n    using \\<open>prime p\\<close> prime_int_nat_transfer\n    by blast\n\n  have \"Jacobi (-1) p = Legendre (-1) p\"\n    using prime_p_Jacobi_eq_Legendre[OF \\<open>prime p\\<close>] .\n\n  also have \"... = (-1) ^ ((nat p - 1) div 2)\"\n    using \\<open>prime p\\<close> \\<open>2 < p\\<close> and supplement1_Legendre[of \"nat p\"]\n    by (metis int_nat_eq nat_mono_iff nat_numeral_as_int prime_gt_0_int prime_int_nat_transfer) \n\n  also have \"((nat p - 1) div 2) = nat ((p - 1) div 2)\" by force\n\n  finally have base_case: \"Jacobi (-1) p = (-1) ^ nat ((p - 1) div 2)\" .\n\n  show ?case proof (cases \"x = 1\")\n    case True\n    then show ?thesis using base_case by simp\n  next\n    case False\n    have \"0 < x\" \n      using \\<open>1 < (p * x)\\<close> prime_gt_0_int[OF \\<open>prime p\\<close>]\n      by (meson int_one_le_iff_zero_less not_less not_less_iff_gr_or_eq zero_less_mult_iff)\n  \n    have \"odd p\" using \\<open>prime p\\<close> \\<open>2 < p\\<close> by (simp add: prime_odd_int) \n\n    have \"Jacobi (-1) (p * x) = Jacobi (-1) p * Jacobi (-1) x\"\n      using \\<open>2 < p\\<close> \\<open>0 < x\\<close> by simp\n\n    also note base_case\n\n    also have \"Jacobi (-1) x = (-1) ^ nat ((x - 1) div 2)\"\n      using \\<open>0 < x\\<close> False \\<open>odd x\\<close> factor.IH \n      by fastforce\n\n    also have \"(- 1) ^ nat ((p - 1) div 2) * (- 1) ^ nat ((x - 1) div 2) =\n               (- 1 :: int) ^ nat ((p*x - 1) div 2)\"\n      unfolding minus_one_power_iff\n      using \\<open>2 < p\\<close> \\<open>0 < x\\<close> and \\<open>odd x\\<close> \\<open>odd p\\<close>\n      by (fastforce elim!: oddE simp: even_nat_iff algebra_simps)\n\n    finally show ?thesis .\n  qed\nqed simp_all\n\ntheorem supplement1_Jacobi':\n  \"odd n \\<Longrightarrow> 1 < n \\<Longrightarrow> Jacobi (-1) n = (if n mod 4 = 1 then 1 else -1)\"\n  by (simp add: even_nat_iff minus_one_power_iff supplement1_Jacobi)\n     presburger?\n\nlemma Jacobi_0_eq_0: \"\\<not>is_unit n \\<Longrightarrow> Jacobi 0 n = 0\"\n  by (cases \"prime_factorization n = {#}\")\n     (auto simp: Jacobi_def prime_factorization_empty_iff image_iff intro: Nat.gr0I)\n\nlemma is_unit_Jacobi_aux: \"is_unit x \\<Longrightarrow> Jacobi a x = 1\"\n  unfolding Jacobi_def using prime_factorization_empty_iff[of x] by auto\n\nlemma is_unit_Jacobi[simp]: \"Jacobi a 1 = 1\" \"Jacobi a (-1) = 1\"\n  using is_unit_Jacobi_aux by simp_all\n\nlemma Jacobi_neg_right [simp]:\n  \"Jacobi a (-n) = Jacobi a n\"\nproof -\n  have * : \"-n = (-1) * n\" by simp\n  show ?thesis unfolding *\n    by (subst Jacobi_mult_right) auto\nqed\n\nlemma Jacobi_neg_left:\n  assumes \"odd n\" \"1 < n\" \n  shows   \"Jacobi (-a) n = (if n mod 4 = 1 then 1 else -1) * Jacobi a n\"\nproof -\n  have * : \"-a = (-1) * a\" by simp\n  show ?thesis unfolding * Jacobi_mult_left supplement1_Jacobi'[OF assms] ..\nqed\n\nfunction jacobi_code :: \"int \\<Rightarrow> int \\<Rightarrow> int\" where\n\"jacobi_code a n = ( \n        if n = 0 then 0\n   else if n = 1 then 1\n   else if a = 1 then 1\n   else if n < 0 then jacobi_code a (-n)\n   else if even n then if even a then 0 else jacobi_code a (n div 2)\n   else if a < 0 then (if n mod 4 = 1 then 1 else -1) * jacobi_code (-a) n\n   else if a = 0 then 0\n   else if a \\<ge> n then jacobi_code (a mod n) n\n   else if even a      then (if n mod 8 \\<in> {1, 7} then 1 else -1) * jacobi_code (a div 2) n\n   else if coprime a n then (if n mod 4 = 3 \\<and> a mod 4 = 3 then -1 else 1) * jacobi_code n a\n   else 0)\"\n  by auto\ntermination\nproof (relation \"measure (\\<lambda>(a, n). nat(abs(a) + abs(n)*2) + \n                   (if n < 0 then 1 else 0) + (if a < 0 then 1 else 0))\", goal_cases)\n  case (5 a n)\n  thus ?case by (fastforce intro!: less_le_trans[OF pos_mod_bound])\nqed auto\n\nlemmas [simp del] = jacobi_code.simps\n\nlemma Jacobi_code [code]: \"Jacobi a n = jacobi_code a n\"\nproof (induction a n rule: jacobi_code.induct)\n  case (1 a n)\n  show ?case\n  proof (cases \"n = 0\")\n    case 2: False\n    then show ?thesis proof (cases \"n = 1\")\n      case 3: False\n      then show ?thesis proof (cases \"a = 1\")\n        case 4: False\n          then show ?thesis proof (cases \"n < 0\")\n            case True\n            then show ?thesis using 2 3 4 1(1) by (subst jacobi_code.simps) simp\n            next\n            case 5: False\n            then show ?thesis proof (cases \"even n\")\n              case True\n              then show ?thesis using 2 3 4 5 1(2)\n                by (elim evenE, subst jacobi_code.simps) (auto simp: prime_p_Jacobi_eq_Legendre)\n            next\n              case 6: False\n              then show ?thesis  proof (cases \"a < 0\")\n                case True\n                then show ?thesis using 2 3 4 5 6\n                  by(subst jacobi_code.simps, subst 1(3)[symmetric]) (simp_all add: Jacobi_neg_left)\n              next\n                case 7: False\n                then show ?thesis proof (cases \"a = 0\")\n                  case True\n                  have *: \"\\<not> is_unit n\" using 3 5 by simp\n                  then show ?thesis\n                    using Jacobi_0_eq_0[OF *] 2 3 4 5 7 True\n                    by (subst jacobi_code.simps) simp\n                next\n                  case 8: False\n                  then show ?thesis proof (cases \"a \\<ge> n\")\n                    case True\n                    then show ?thesis using 2 3 4 5 6 7 8 1(4)\n                      by (subst jacobi_code.simps) simp\n                  next\n                    case 9: False\n                    then show ?thesis proof (cases \"even a\")\n                      case True\n                      hence \"a = 2 * (a div 2)\" by simp\n                      also have \"Jacobi \\<dots> n = Jacobi 2 n * Jacobi (a div 2) n\"\n                        by simp\n                      also have \"Jacobi (a div 2) n = jacobi_code (a div 2) n\"\n                        using 2 3 4 5 6 7 8 9 True by (intro 1(5))\n                      also have \"Jacobi 2 n = (if n mod 8 \\<in> {1, 7} then 1 else - 1)\"\n                        using 2 3 5 supplement2_Jacobi'[OF 6] by simp\n                      also have \"\\<dots> * jacobi_code (a div 2) n = jacobi_code a n\"\n                        using 2 3 4 5 6 7 8 9 True\n                        by (subst (2) jacobi_code.simps) (simp only: if_False if_True HOL.simp_thms)\n                      finally show ?thesis .\n                    next\n                      case 10: False\n                      note foo = 1 2 3\n                      then show ?thesis proof (cases \"coprime a n\")\n                        case True\n                        note this_case = 2 3 4 5 6 7 8 9 10 True\n                        have \"2 < a\" using 10 4 7 by presburger\n                        moreover have \"2 < n\" using 3 5 6 by presburger\n                        ultimately have \"jacobi_code a n = (if n mod 4 = 3 \\<and> a mod 4 = 3 then - 1 else 1)\n                                                        * jacobi_code n a\"\n                          using this_case by (subst jacobi_code.simps) simp\n                        also have \"jacobi_code n a = Jacobi n a\"\n                          using this_case by (intro 1(6) [symmetric]) auto\n                        also have \"(if n mod 4 = 3 \\<and> a mod 4 = 3 then -1 else 1) * \\<dots> = Jacobi a n\"\n                          using this_case and \\<open>2 < a\\<close>\n                          by (intro Quadratic_Reciprocity_Jacobi' [symmetric])\n                             (auto simp: coprime_commute)\n                        finally show ?thesis ..\n                      next\n                        case False\n                        have *: \"0 < a\" \"0 < n\" using 5 7 8 9 by linarith+ \n                        show ?thesis\n                          using 1 2 3 4 5 6 7 8 9 10 False *\n                          by (subst jacobi_code.simps) (auto simp: Jacobi_eq_0_not_coprime)\n                      qed\n                    qed\n                  qed\n                qed\n              qed\n            qed\n        qed\n      qed (subst jacobi_code.simps, simp)\n    qed (subst jacobi_code.simps, simp)\n  qed (subst jacobi_code.simps, simp)\nqed\n\nlemma Jacobi_eq_0_imp_not_coprime:\n  assumes \"p \\<noteq> 0\" \"p \\<noteq> 1\"\n  shows   \"Jacobi n p = 0 \\<Longrightarrow> \\<not>coprime n p\"\n  using assms Jacobi_mod_cong coprime_iff_invertible_int by force\n\nlemma Jacobi_eq_0_iff_not_coprime:\n  assumes \"p \\<noteq> 0\" \"p \\<noteq> 1\"\n  shows \"Jacobi n p = 0 \\<longleftrightarrow> \\<not>coprime n p\"\nproof -\n  from assms and Jacobi_eq_0_imp_not_coprime \n  show ?thesis using Jacobi_eq_0_not_coprime 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/Probabilistic_Prime_Tests/Jacobi_Symbol.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.865224068675884, "lm_q2_score": 0.8438951025545426, "lm_q1q2_score": 0.7301583541678937}}
{"text": "(*  Title:    HOL/Analysis/Harmonic_Numbers.thy\n    Author:   Manuel Eberl, TU M\u00fcnchen\n*)\n\nsection \\<open>Harmonic Numbers\\<close>\n\ntheory Harmonic_Numbers\nimports\n  Complex_Transcendental\n  Summation_Tests\n  Integral_Test\nbegin\n\ntext \\<open>\n  The definition of the Harmonic Numbers and the Euler-Mascheroni constant.\n  Also provides a reasonably accurate approximation of @{term \"ln 2 :: real\"}\n  and the Euler-Mascheroni constant.\n\\<close>\n\nlemma ln_2_less_1: \"ln 2 < (1::real)\"\nproof -\n  have \"2 < 5/(2::real)\" by simp\n  also have \"5/2 \\<le> exp (1::real)\" using exp_lower_taylor_quadratic[of 1, simplified] by simp\n  finally have \"exp (ln 2) < exp (1::real)\" by simp\n  thus \"ln 2 < (1::real)\" by (subst (asm) exp_less_cancel_iff) simp\nqed\n\nlemma sum_Suc_diff':\n  fixes f :: \"nat \\<Rightarrow> 'a::ab_group_add\"\n  assumes \"m \\<le> n\"\n  shows \"(\\<Sum>i = m..<n. f (Suc i) - f i) = f n - f m\"\nusing assms by (induct n) (auto simp: le_Suc_eq)\n\n\nsubsection \\<open>The Harmonic numbers\\<close>\n\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 sum_nonneg) simp_all\n\nlemma harm_pos: \"n > 0 \\<Longrightarrow> harm n > (0 :: 'a :: {real_normed_field,linordered_field})\"\n  unfolding harm_def by (intro sum_pos) 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 0 = 0\"\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_all 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 sum_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\nlemma harm_pos_iff [simp]: \"harm n > (0 :: 'a :: {real_normed_field,linordered_field}) \\<longleftrightarrow> n > 0\"\n  by (rule iffI, cases n, simp add: harm_expand, simp, rule harm_pos)\n\nlemma ln_diff_le_inverse:\n  assumes \"x \\<ge> (1::real)\"\n  shows   \"ln (x + 1) - ln x < 1 / x\"\nproof -\n  from assms have \"\\<exists>z>x. z < x + 1 \\<and> ln (x + 1) - ln x = (x + 1 - x) * inverse z\"\n    by (intro MVT2) (auto intro!: derivative_eq_intros simp: field_simps)\n  then obtain z where z: \"z > x\" \"z < x + 1\" \"ln (x + 1) - ln x = inverse z\" by auto\n  have \"ln (x + 1) - ln x = inverse z\" by fact\n  also from z(1,2) assms have \"\\<dots> < 1 / x\" by (simp add: field_simps)\n  finally show ?thesis .\nqed\n\nlemma ln_le_harm: \"ln (real n + 1) \\<le> (harm n :: real)\"\nproof (induction n)\n  fix n assume IH: \"ln (real n + 1) \\<le> harm n\"\n  have \"ln (real (Suc n) + 1) = ln (real n + 1) + (ln (real n + 2) - ln (real n + 1))\" by simp\n  also have \"(ln (real n + 2) - ln (real n + 1)) \\<le> 1 / real (Suc n)\"\n    using ln_diff_le_inverse[of \"real n + 1\"] by (simp add: add_ac)\n  also note IH\n  also have \"harm n + 1 / real (Suc n) = harm (Suc n)\" by (simp add: harm_Suc field_simps)\n  finally show \"ln (real (Suc n) + 1) \\<le> harm (Suc n)\" by - simp\nqed (simp_all add: harm_def)\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 sum_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) \\<longlonglongrightarrow> 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))) \\<longlonglongrightarrow>\n      (euler_mascheroni :: 'a :: {real_normed_algebra_1, topological_space})\"\nproof -\n  have \"(\\<lambda>n. of_real (harm n - ln (of_nat n))) \\<longlonglongrightarrow> (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_real:\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 euler_mascheroni_sum:\n  \"(\\<lambda>n. inverse (of_nat (n+1)) + of_real (ln (of_nat (n+1))) - of_real (ln (of_nat (n+2))))\n       sums (euler_mascheroni :: 'a :: {banach, real_normed_field})\"\nproof -\n  have \"(\\<lambda>n. of_real (inverse (of_nat (n+1)) + ln (of_nat (n+1)) - ln (of_nat (n+2))))\n       sums (of_real euler_mascheroni :: 'a :: {banach, real_normed_field})\"\n    by (subst sums_of_real_iff) (rule euler_mascheroni_sum_real)\n  thus ?thesis by simp\nqed\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: sum.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 sum.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 sum.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 sum.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 sum.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                     \\<longlonglongrightarrow> 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)) \\<longlonglongrightarrow> ln 2\" by simp\n  ultimately have \"(\\<lambda>n. (\\<Sum>k<2*n. (-1)^k / real_of_nat (Suc k))) \\<longlonglongrightarrow> 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)) \\<longlonglongrightarrow> (\\<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)) \\<longlonglongrightarrow> (\\<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))) \\<longlonglongrightarrow> 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\n\nsubsection \\<open>Bounds on the Euler--Mascheroni constant\\<close>\n\n(* TODO: Move? *)\nlemma ln_inverse_approx_le:\n  assumes \"(x::real) > 0\" \"a > 0\"\n  shows   \"ln (x + a) - ln x \\<le> a * (inverse x + inverse (x + a))/2\" (is \"_ \\<le> ?A\")\nproof -\n  define f' where \"f' = (inverse (x + a) - inverse x)/a\"\n  have f'_nonpos: \"f' \\<le> 0\" using assms by (simp add: f'_def divide_simps)\n  let ?f = \"\\<lambda>t. (t - x) * f' + inverse x\"\n  let ?F = \"\\<lambda>t. (t - x)^2 * f' / 2 + t * inverse x\"\n  have diff: \"\\<forall>t\\<in>{x..x+a}. (?F has_vector_derivative ?f t)\n                               (at t within {x..x+a})\" using assms\n    by (auto intro!: derivative_eq_intros\n             simp: has_field_derivative_iff_has_vector_derivative[symmetric])\n  from assms have \"(?f has_integral (?F (x+a) - ?F x)) {x..x+a}\"\n    by (intro fundamental_theorem_of_calculus[OF _ diff])\n       (auto simp: has_field_derivative_iff_has_vector_derivative[symmetric] field_simps\n             intro!: derivative_eq_intros)\n  also have \"?F (x+a) - ?F x = (a*2 + f'*a\\<^sup>2*x) / (2*x)\" using assms by (simp add: field_simps)\n  also have \"f'*a^2 = - (a^2) / (x*(x + a))\" using assms\n    by (simp add: divide_simps f'_def power2_eq_square)\n  also have \"(a*2 + - a\\<^sup>2/(x*(x+a))*x) / (2*x) = ?A\" using assms\n    by (simp add: divide_simps power2_eq_square) (simp add: algebra_simps)\n  finally have int1: \"((\\<lambda>t. (t - x) * f' + inverse x) has_integral ?A) {x..x + a}\" .\n\n  from assms have int2: \"(inverse has_integral (ln (x + a) - ln x)) {x..x+a}\"\n    by (intro fundamental_theorem_of_calculus)\n       (auto simp: has_field_derivative_iff_has_vector_derivative[symmetric] divide_simps\n             intro!: derivative_eq_intros)\n  hence \"ln (x + a) - ln x = integral {x..x+a} inverse\" by (simp add: integral_unique)\n  also have ineq: \"\\<forall>xa\\<in>{x..x + a}. inverse xa \\<le> (xa - x) * f' + inverse x\"\n  proof\n    fix t assume t': \"t \\<in> {x..x+a}\"\n    with assms have t: \"0 \\<le> (t - x) / a\" \"(t - x) / a \\<le> 1\" by simp_all\n    have \"inverse t = inverse ((1 - (t - x) / a) *\\<^sub>R x + ((t - x) / a) *\\<^sub>R (x + a))\" (is \"_ = ?A\")\n      using assms t' by (simp add: field_simps)\n    also from assms have \"convex_on {x..x+a} inverse\" by (intro convex_on_inverse) auto\n    from convex_onD_Icc[OF this _ t] assms\n      have \"?A \\<le> (1 - (t - x) / a) * inverse x + (t - x) / a * inverse (x + a)\" by simp\n    also have \"\\<dots> = (t - x) * f' + inverse x\" using assms\n      by (simp add: f'_def divide_simps) (simp add: f'_def field_simps)\n    finally show \"inverse t \\<le> (t - x) * f' + inverse x\" .\n  qed\n  hence \"integral {x..x+a} inverse \\<le> integral {x..x+a} ?f\" using f'_nonpos assms\n    by (intro integral_le has_integral_integrable[OF int1] has_integral_integrable[OF int2] ineq)\n  also have \"\\<dots> = ?A\" using int1 by (rule integral_unique)\n  finally show ?thesis .\nqed\n\nlemma ln_inverse_approx_ge:\n  assumes \"(x::real) > 0\" \"x < y\"\n  shows   \"ln y - ln x \\<ge> 2 * (y - x) / (x + y)\" (is \"_ \\<ge> ?A\")\nproof -\n  define m where \"m = (x+y)/2\"\n  define f' where \"f' = -inverse (m^2)\"\n  from assms have m: \"m > 0\" by (simp add: m_def)\n  let ?F = \"\\<lambda>t. (t - m)^2 * f' / 2 + t / m\"\n  from assms have \"((\\<lambda>t. (t - m) * f' + inverse m) has_integral (?F y - ?F x)) {x..y}\"\n    by (intro fundamental_theorem_of_calculus)\n       (auto simp: has_field_derivative_iff_has_vector_derivative[symmetric] divide_simps\n             intro!: derivative_eq_intros)\n  also from m have \"?F y - ?F x = ((y - m)^2 - (x - m)^2) * f' / 2 + (y - x) / m\"\n    by (simp add: field_simps)\n  also have \"((y - m)^2 - (x - m)^2) = 0\" by (simp add: m_def power2_eq_square field_simps)\n  also have \"0 * f' / 2 + (y - x) / m = ?A\" by (simp add: m_def)\n  finally have int1: \"((\\<lambda>t. (t - m) * f' + inverse m) has_integral ?A) {x..y}\" .\n\n  from assms have int2: \"(inverse has_integral (ln y - ln x)) {x..y}\"\n    by (intro fundamental_theorem_of_calculus)\n       (auto simp: has_field_derivative_iff_has_vector_derivative[symmetric] divide_simps\n             intro!: derivative_eq_intros)\n  hence \"ln y - ln x = integral {x..y} inverse\" by (simp add: integral_unique)\n  also have ineq: \"\\<forall>xa\\<in>{x..y}. inverse xa \\<ge> (xa - m) * f' + inverse m\"\n  proof\n    fix t assume t: \"t \\<in> {x..y}\"\n    from t assms have \"inverse t - inverse m \\<ge> f' * (t - m)\"\n      by (intro convex_on_imp_above_tangent[of \"{0<..}\"] convex_on_inverse)\n         (auto simp: m_def interior_open f'_def power2_eq_square intro!: derivative_eq_intros)\n    thus \"(t - m) * f' + inverse m \\<le> inverse t\" by (simp add: algebra_simps)\n  qed\n  hence \"integral {x..y} inverse \\<ge> integral {x..y} (\\<lambda>t. (t - m) * f' + inverse m)\"\n    using int1 int2 by (intro integral_le has_integral_integrable)\n  also have \"integral {x..y} (\\<lambda>t. (t - m) * f' + inverse m) = ?A\"\n    using integral_unique[OF int1] by simp\n  finally show ?thesis .\nqed\n\n\nlemma euler_mascheroni_lower:\n        \"euler_mascheroni \\<ge> harm (Suc n) - ln (real_of_nat (n + 2)) + 1/real_of_nat (2 * (n + 2))\"\n  and euler_mascheroni_upper:\n        \"euler_mascheroni \\<le> harm (Suc n) - ln (real_of_nat (n + 2)) + 1/real_of_nat (2 * (n + 1))\"\nproof -\n  define D :: \"_ \\<Rightarrow> real\"\n    where \"D n = inverse (of_nat (n+1)) + ln (of_nat (n+1)) - ln (of_nat (n+2))\" for n\n  let ?g = \"\\<lambda>n. ln (of_nat (n+2)) - ln (of_nat (n+1)) - inverse (of_nat (n+1)) :: real\"\n  define inv where [abs_def]: \"inv n = inverse (real_of_nat n)\" for n\n  fix n :: nat\n  note summable = sums_summable[OF euler_mascheroni_sum_real, folded D_def]\n  have sums: \"(\\<lambda>k. (inv (Suc (k + (n+1))) - inv (Suc (Suc k + (n+1))))/2) sums ((inv (Suc (0 + (n+1))) - 0)/2)\"\n    unfolding inv_def\n    by (intro sums_divide telescope_sums' LIMSEQ_ignore_initial_segment LIMSEQ_inverse_real_of_nat)\n  have sums': \"(\\<lambda>k. (inv (Suc (k + n)) - inv (Suc (Suc k + n)))/2) sums ((inv (Suc (0 + n)) - 0)/2)\"\n    unfolding inv_def\n    by (intro sums_divide telescope_sums' LIMSEQ_ignore_initial_segment LIMSEQ_inverse_real_of_nat)\n  from euler_mascheroni_sum_real have \"euler_mascheroni = (\\<Sum>k. D k)\"\n    by (simp add: sums_iff D_def)\n  also have \"\\<dots> = (\\<Sum>k. D (k + Suc n)) + (\\<Sum>k\\<le>n. D k)\"\n    by (subst suminf_split_initial_segment[OF summable, of \"Suc n\"], \n        subst lessThan_Suc_atMost) simp\n  finally have sum: \"(\\<Sum>k\\<le>n. D k) - euler_mascheroni = -(\\<Sum>k. D (k + Suc n))\" by simp\n\n  note sum\n  also have \"\\<dots> \\<le> -(\\<Sum>k. (inv (k + Suc n + 1) - inv (k + Suc n + 2)) / 2)\"\n  proof (intro le_imp_neg_le suminf_le allI summable_ignore_initial_segment[OF summable])\n    fix k' :: nat\n    define k where \"k = k' + Suc n\"\n    hence k: \"k > 0\" by (simp add: k_def)\n    have \"real_of_nat (k+1) > 0\" by (simp add: k_def)\n    with ln_inverse_approx_le[OF this zero_less_one]\n      have \"ln (of_nat k + 2) - ln (of_nat k + 1) \\<le> (inv (k+1) + inv (k+2))/2\"\n      by (simp add: inv_def add_ac)\n    hence \"(inv (k+1) - inv (k+2))/2 \\<le> inv (k+1) + ln (of_nat (k+1)) - ln (of_nat (k+2))\"\n      by (simp add: field_simps)\n    also have \"\\<dots> = D k\" unfolding D_def inv_def ..\n    finally show \"D (k' + Suc n) \\<ge> (inv (k' + Suc n + 1) - inv (k' + Suc n + 2)) / 2\"\n      by (simp add: k_def)\n    from sums_summable[OF sums]\n      show \"summable (\\<lambda>k. (inv (k + Suc n + 1) - inv (k + Suc n + 2))/2)\" by simp\n  qed\n  also from sums have \"\\<dots> = -inv (n+2) / 2\" by (simp add: sums_iff)\n  finally have \"euler_mascheroni \\<ge> (\\<Sum>k\\<le>n. D k) + 1 / (of_nat (2 * (n+2)))\"\n    by (simp add: inv_def field_simps)\n  also have \"(\\<Sum>k\\<le>n. D k) = harm (Suc n) - (\\<Sum>k\\<le>n. ln (real_of_nat (Suc k+1)) - ln (of_nat (k+1)))\"\n    unfolding harm_altdef D_def by (subst lessThan_Suc_atMost) (simp add:  sum.distrib sum_subtractf)\n  also have \"(\\<Sum>k\\<le>n. ln (real_of_nat (Suc k+1)) - ln (of_nat (k+1))) = ln (of_nat (n+2))\"\n    by (subst atLeast0AtMost [symmetric], subst sum_Suc_diff) simp_all\n  finally show \"euler_mascheroni \\<ge> harm (Suc n) - ln (real_of_nat (n + 2)) + 1/real_of_nat (2 * (n + 2))\"\n    by simp\n\n  note sum\n  also have \"-(\\<Sum>k. D (k + Suc n)) \\<ge> -(\\<Sum>k. (inv (Suc (k + n)) - inv (Suc (Suc k + n)))/2)\"\n  proof (intro le_imp_neg_le suminf_le allI summable_ignore_initial_segment[OF summable])\n    fix k' :: nat\n    define k where \"k = k' + Suc n\"\n    hence k: \"k > 0\" by (simp add: k_def)\n    have \"real_of_nat (k+1) > 0\" by (simp add: k_def)\n    from ln_inverse_approx_ge[of \"of_nat k + 1\" \"of_nat k + 2\"]\n      have \"2 / (2 * real_of_nat k + 3) \\<le> ln (of_nat (k+2)) - ln (real_of_nat (k+1))\"\n      by (simp add: add_ac)\n    hence \"D k \\<le> 1 / real_of_nat (k+1) - 2 / (2 * real_of_nat k + 3)\"\n      by (simp add: D_def inverse_eq_divide inv_def)\n    also have \"\\<dots> = inv ((k+1)*(2*k+3))\" unfolding inv_def by (simp add: field_simps)\n    also have \"\\<dots> \\<le> inv (2*k*(k+1))\" unfolding inv_def using k\n      by (intro le_imp_inverse_le)\n         (simp add: algebra_simps, simp del: of_nat_add)\n    also have \"\\<dots> = (inv k - inv (k+1))/2\" unfolding inv_def using k\n      by (simp add: divide_simps del: of_nat_mult) (simp add: algebra_simps)\n    finally show \"D k \\<le> (inv (Suc (k' + n)) - inv (Suc (Suc k' + n)))/2\" unfolding k_def by simp\n  next\n    from sums_summable[OF sums']\n      show \"summable (\\<lambda>k. (inv (Suc (k + n)) - inv (Suc (Suc k + n)))/2)\" by simp\n  qed\n  also from sums' have \"(\\<Sum>k. (inv (Suc (k + n)) - inv (Suc (Suc k + n)))/2) = inv (n+1)/2\"\n    by (simp add: sums_iff)\n  finally have \"euler_mascheroni \\<le> (\\<Sum>k\\<le>n. D k) + 1 / of_nat (2 * (n+1))\"\n    by (simp add: inv_def field_simps)\n  also have \"(\\<Sum>k\\<le>n. D k) = harm (Suc n) - (\\<Sum>k\\<le>n. ln (real_of_nat (Suc k+1)) - ln (of_nat (k+1)))\"\n    unfolding harm_altdef D_def by (subst lessThan_Suc_atMost) (simp add:  sum.distrib sum_subtractf)\n  also have \"(\\<Sum>k\\<le>n. ln (real_of_nat (Suc k+1)) - ln (of_nat (k+1))) = ln (of_nat (n+2))\"\n    by (subst atLeast0AtMost [symmetric], subst sum_Suc_diff) simp_all\n  finally show \"euler_mascheroni \\<le> harm (Suc n) - ln (real_of_nat (n + 2)) + 1/real_of_nat (2 * (n + 1))\"\n    by simp\nqed\n\nlemma euler_mascheroni_pos: \"euler_mascheroni > (0::real)\"\n  using euler_mascheroni_lower[of 0] ln_2_less_1 by (simp add: harm_def)\n\ncontext\nbegin\n\nprivate lemma ln_approx_aux:\n  fixes n :: nat and x :: real\n  defines \"y \\<equiv> (x-1)/(x+1)\"\n  assumes x: \"x > 0\" \"x \\<noteq> 1\"\n  shows \"inverse (2*y^(2*n+1)) * (ln x - (\\<Sum>k<n. 2*y^(2*k+1) / of_nat (2*k+1))) \\<in>\n            {0..(1 / (1 - y^2) / of_nat (2*n+1))}\"\nproof -\n  from x have norm_y: \"norm y < 1\" unfolding y_def by simp\n  from power_strict_mono[OF this, of 2] have norm_y': \"norm y^2 < 1\" by simp\n\n  let ?f = \"\\<lambda>k. 2 * y ^ (2*k+1) / of_nat (2*k+1)\"\n  note sums = ln_series_quadratic[OF x(1)]\n  define c where \"c = inverse (2*y^(2*n+1))\"\n  let ?d = \"c * (ln x - (\\<Sum>k<n. ?f k))\"\n  have \"\\<forall>k. y\\<^sup>2^k / of_nat (2*(k+n)+1) \\<le> y\\<^sup>2 ^ k / of_nat (2*n+1)\"\n    by (intro allI divide_left_mono mult_right_mono mult_pos_pos zero_le_power[of \"y^2\"]) simp_all\n  moreover {\n    have \"(\\<lambda>k. ?f (k + n)) sums (ln x - (\\<Sum>k<n. ?f k))\"\n      using sums_split_initial_segment[OF sums] by (simp add: y_def)\n    hence \"(\\<lambda>k. c * ?f (k + n)) sums ?d\" by (rule sums_mult)\n    also have \"(\\<lambda>k. c * (2*y^(2*(k+n)+1) / of_nat (2*(k+n)+1))) =\n                   (\\<lambda>k. (c * (2*y^(2*n+1))) * ((y^2)^k / of_nat (2*(k+n)+1)))\"\n      by (simp only: ring_distribs power_add power_mult) (simp add: mult_ac)\n    also from x have \"c * (2*y^(2*n+1)) = 1\" by (simp add: c_def y_def)\n    finally have \"(\\<lambda>k. (y^2)^k / of_nat (2*(k+n)+1)) sums ?d\" by simp\n  } note sums' = this\n  moreover from norm_y' have \"(\\<lambda>k. (y^2)^k / of_nat (2*n+1)) sums (1 / (1 - y^2) / of_nat (2*n+1))\"\n    by (intro sums_divide geometric_sums) (simp_all add: norm_power)\n  ultimately have \"?d \\<le> (1 / (1 - y^2) / of_nat (2*n+1))\" by (rule sums_le)\n  moreover have \"c * (ln x - (\\<Sum>k<n. 2 * y ^ (2 * k + 1) / real_of_nat (2 * k + 1))) \\<ge> 0\"\n    by (intro sums_le[OF _ sums_zero sums']) simp_all\n  ultimately show ?thesis unfolding c_def by simp\nqed\n\nlemma\n  fixes n :: nat and x :: real\n  defines \"y \\<equiv> (x-1)/(x+1)\"\n  defines \"approx \\<equiv> (\\<Sum>k<n. 2*y^(2*k+1) / of_nat (2*k+1))\"\n  defines \"d \\<equiv> y^(2*n+1) / (1 - y^2) / of_nat (2*n+1)\"\n  assumes x: \"x > 1\"\n  shows   ln_approx_bounds: \"ln x \\<in> {approx..approx + 2*d}\"\n  and     ln_approx_abs:    \"abs (ln x - (approx + d)) \\<le> d\"\nproof -\n  define c where \"c = 2*y^(2*n+1)\"\n  from x have c_pos: \"c > 0\" unfolding c_def y_def\n    by (intro mult_pos_pos zero_less_power) simp_all\n  have A: \"inverse c * (ln x - (\\<Sum>k<n. 2*y^(2*k+1) / of_nat (2*k+1))) \\<in>\n              {0.. (1 / (1 - y^2) / of_nat (2*n+1))}\" using assms unfolding y_def c_def\n    by (intro ln_approx_aux) simp_all\n  hence \"inverse c * (ln x - (\\<Sum>k<n. 2*y^(2*k+1)/of_nat (2*k+1))) \\<le> (1 / (1-y^2) / of_nat (2*n+1))\"\n    by simp\n  hence \"(ln x - (\\<Sum>k<n. 2*y^(2*k+1) / of_nat (2*k+1))) / c \\<le> (1 / (1 - y^2) / of_nat (2*n+1))\"\n    by (auto simp add: divide_simps)\n  with c_pos have \"ln x \\<le> c / (1 - y^2) / of_nat (2*n+1) + approx\"\n    by (subst (asm) pos_divide_le_eq) (simp_all add: mult_ac approx_def)\n  moreover {\n    from A c_pos have \"0 \\<le> c * (inverse c * (ln x - (\\<Sum>k<n. 2*y^(2*k+1) / of_nat (2*k+1))))\"\n      by (intro mult_nonneg_nonneg[of c]) simp_all\n    also have \"\\<dots> = (c * inverse c) * (ln x - (\\<Sum>k<n. 2*y^(2*k+1) / of_nat (2*k+1)))\"\n      by (simp add: mult_ac)\n    also from c_pos have \"c * inverse c = 1\" by simp\n    finally have \"ln x \\<ge> approx\" by (simp add: approx_def)\n  }\n  ultimately show \"ln x \\<in> {approx..approx + 2*d}\" by (simp add: c_def d_def)\n  thus \"abs (ln x - (approx + d)) \\<le> d\" by auto\nqed\n\nend\n\nlemma euler_mascheroni_bounds:\n  fixes n :: nat assumes \"n \\<ge> 1\" defines \"t \\<equiv> harm n - ln (of_nat (Suc n)) :: real\"\n  shows \"euler_mascheroni \\<in> {t + inverse (of_nat (2*(n+1)))..t + inverse (of_nat (2*n))}\"\n  using assms euler_mascheroni_upper[of \"n-1\"] euler_mascheroni_lower[of \"n-1\"]\n  unfolding t_def by (cases n) (simp_all add: harm_Suc t_def inverse_eq_divide)\n\nlemma euler_mascheroni_bounds':\n  fixes n :: nat assumes \"n \\<ge> 1\" \"ln (real_of_nat (Suc n)) \\<in> {l<..<u}\"\n  shows \"euler_mascheroni \\<in>\n           {harm n - u + inverse (of_nat (2*(n+1)))<..<harm n - l + inverse (of_nat (2*n))}\"\n  using euler_mascheroni_bounds[OF assms(1)] assms(2) by auto\n\n\ntext \\<open>\n  Approximation of @{term \"ln 2\"}. The lower bound is accurate to about 0.03; the upper\n  bound is accurate to about 0.0015.\n\\<close>\nlemma ln2_ge_two_thirds: \"2/3 \\<le> ln (2::real)\"\n  and ln2_le_25_over_36: \"ln (2::real) \\<le> 25/36\"\n  using ln_approx_bounds[of 2 1, simplified, simplified eval_nat_numeral, simplified] by simp_all\n\n\ntext \\<open>\n  Approximation of the Euler--Mascheroni constant. The lower bound is accurate to about 0.0015;\n  the upper bound is accurate to about 0.015.\n\\<close>\nlemma euler_mascheroni_gt_19_over_33: \"(euler_mascheroni :: real) > 19/33\" (is ?th1)\n  and euler_mascheroni_less_13_over_22: \"(euler_mascheroni :: real) < 13/22\" (is ?th2)\nproof -\n  have \"ln (real (Suc 7)) = 3 * ln 2\" by (simp add: ln_powr [symmetric] powr_numeral)\n  also from ln_approx_bounds[of 2 3] have \"\\<dots> \\<in> {3*307/443<..<3*4615/6658}\"\n    by (simp add: eval_nat_numeral)\n  finally have \"ln (real (Suc 7)) \\<in> \\<dots>\" .\n  from euler_mascheroni_bounds'[OF _ this] have \"?th1 \\<and> ?th2\" by (simp_all add: harm_expand)\n  thus ?th1 ?th2 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/Analysis/Harmonic_Numbers.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8438950947024555, "lm_q2_score": 0.8652240686758841, "lm_q1q2_score": 0.730158347374079}}
{"text": "theory Continuum imports \"HOL-Analysis.Continuum_Not_Denumerable\" begin\n\ntext \\<open>\n  Denumerable: Capable of being assigned numbers from the natural numbers.\n\n  The empty set is denumerable because it is finite; the rational numbers are, surprisingly,\n  denumerable because every possible fraction can be assigned a number.\n\n  Synonym: Countable\n\n  \\<^url>\\<open>https://en.wiktionary.org/wiki/denumerable\\<close>\n\\<close>\n\nproposition \\<open>\\<exists>f. \\<forall>y :: nat. \\<exists>x :: nat. y = f x\\<close>\n  by iprover\n\ndefinition triangle :: \\<open>nat \\<Rightarrow> nat\\<close>\n  where \\<open>triangle n \\<equiv> (n * Suc n) div 2\\<close>\n\nlemma triangle_0 [simp]: \\<open>triangle 0 = 0\\<close>\n  unfolding triangle_def by simp\n\nlemma triangle_Suc [simp]: \\<open>triangle (Suc n) = triangle n + Suc n\\<close>\n  unfolding triangle_def by simp\n\ndefinition prod_encode :: \\<open>nat \\<times> nat \\<Rightarrow> nat\\<close>\n  where \\<open>prod_encode \\<equiv> \\<lambda>(m, n). triangle (m + n) + m\\<close>\n\nfun prod_decode_aux :: \\<open>nat \\<Rightarrow> nat \\<Rightarrow> nat \\<times> nat\\<close>\n  where \\<open>prod_decode_aux k m = (if k \\<ge> m then (m, k - m) else prod_decode_aux (Suc k) (m - Suc k))\\<close>\n\ndefinition prod_decode :: \\<open>nat \\<Rightarrow> nat \\<times> nat\\<close>\n  where \\<open>prod_decode \\<equiv> prod_decode_aux 0\\<close>\n\nlemma prod_decode_triangle_add: \\<open>prod_decode (triangle k + m) = prod_decode_aux k m\\<close>\n  unfolding prod_decode_def\n  by (induct k arbitrary: m) (simp, simp only: triangle_Suc add.assoc, simp)\n\nlemma prod_encode_inverse [simp]: \\<open>prod_decode (prod_encode x) = x\\<close>\n  unfolding prod_encode_def using prod_decode_triangle_add by (cases x) simp\n\nlemma prod_encode_prod_decode_aux: \\<open>prod_encode (prod_decode_aux k m) = triangle k + m\\<close>\n  unfolding prod_encode_def by (induct k m rule: prod_decode_aux.induct) simp\n\nlemma prod_decode_inverse [simp]: \\<open>prod_encode (prod_decode n) = n\\<close>\n  unfolding prod_decode_def by (simp add: prod_encode_prod_decode_aux del: prod_decode_aux.simps)\n\ndefinition sum_encode :: \\<open>nat + nat \\<Rightarrow> nat\\<close>\n  where \\<open>sum_encode x \\<equiv> case x of Inl a \\<Rightarrow> 2 * a | Inr b \\<Rightarrow> Suc (2 * b)\\<close>\n\ndefinition sum_decode :: \\<open>nat \\<Rightarrow> nat + nat\\<close>\n  where \\<open>sum_decode n \\<equiv> if even n then Inl (n div 2) else Inr (n div 2)\\<close>\n\nlemma sum_encode_inverse [simp]: \\<open>sum_decode (sum_encode x) = x\\<close>\n  unfolding sum_encode_def sum_decode_def by (cases x) simp_all\n\nlemma sum_decode_inverse [simp]: \\<open>sum_encode (sum_decode n) = n\\<close>\n  unfolding sum_encode_def sum_decode_def by simp\n\ndefinition int_encode :: \\<open>int \\<Rightarrow> nat\\<close>\n  where \\<open>int_encode i \\<equiv> sum_encode (if i \\<ge> 0 then Inl (nat i) else Inr (nat (- i - 1)))\\<close>\n\ndefinition int_decode :: \\<open>nat \\<Rightarrow> int\\<close>\n  where \\<open>int_decode n \\<equiv> case sum_decode n of Inl a \\<Rightarrow> int a | Inr b \\<Rightarrow> - int b - 1\\<close>\n\nlemma int_encode_inverse [simp]: \\<open>int_decode (int_encode x) = x\\<close>\n  unfolding int_encode_def int_decode_def by simp\n\nlemma int_decode_inverse [simp]: \\<open>int_encode (int_decode n) = n\\<close>\n  unfolding int_encode_def int_decode_def unfolding sum_encode_def sum_decode_def by simp\n\ntheorem int_denum: \\<open>\\<exists>f :: nat \\<Rightarrow> int. surj f\\<close>\n  unfolding surj_def using int_encode_inverse by metis\n\ncorollary \\<open>\\<exists>f. \\<forall>y :: int. \\<exists>x :: nat. y = f x\\<close>\n  using int_denum unfolding surj_def .\n\ndefinition nat_to_rat_surj :: \\<open>nat \\<Rightarrow> rat\\<close>\n  where \\<open>nat_to_rat_surj n \\<equiv> let (a, b) = prod_decode n in Fract (int_decode a) (int_decode b)\\<close>\n\nlemma surj_nat_to_rat_surj: \\<open>surj nat_to_rat_surj\\<close>\n  unfolding surj_def nat_to_rat_surj_def\n  using Rat_cases case_prod_conv int_encode_inverse prod_encode_inverse by metis\n\ntheorem rat_denum: \\<open>\\<exists>f :: nat \\<Rightarrow> rat. surj f\\<close>\n  using surj_nat_to_rat_surj by metis\n\ncorollary \\<open>\\<exists>f. \\<forall>y :: rat. \\<exists>x :: nat. y = f x\\<close>\n  using rat_denum unfolding surj_def .\n\ntext \\<open>\n  Examples of nondenumerable sets include the real, complex, irrational, and transcendental\n  numbers.\n\n  \\<^url>\\<open>http://mathworld.wolfram.com/CountablyInfinite.html\\<close>\n\\<close>\n\nproposition \\<open>\\<nexists>f. \\<forall>y :: real. \\<exists>x :: nat. y = f x\\<close>\n  using real_non_denum unfolding surj_def .\n\nend\n", "meta": {"author": "logic-tools", "repo": "continuum", "sha": "48b227920958b92587f400a1c6194543fff478b8", "save_path": "github-repos/isabelle/logic-tools-continuum", "path": "github-repos/isabelle/logic-tools-continuum/continuum-48b227920958b92587f400a1c6194543fff478b8/Continuum.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970873650401, "lm_q2_score": 0.8289388125473629, "lm_q1q2_score": 0.7301268916955522}}
{"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_MSortTDIsSort\n  imports \"../../Test_Base\"\nbegin\n\ndatatype 'a list = nil2 | cons2 \"'a\" \"'a list\"\n\nfun take :: \"int => 'a list => 'a list\" where\n  \"take x y =\n   (if x <= 0 then nil2 else\n      (case y of\n         nil2 => nil2\n         | cons2 z xs => cons2 z (take (x - 1) 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 length :: \"'a list => int\" where\n  \"length (nil2) = 0\"\n| \"length (cons2 y l) = 1 + (length l)\"\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\nfun drop :: \"int => 'a list => 'a list\" where\n  \"drop x y =\n   (if x <= 0 then y else\n      (case y of\n         nil2 => nil2\n         | cons2 z xs1 => drop (x - 1) xs1))\"\n\n(*fun did not finish the proof*)\nfunction msorttd :: \"int list => int list\" where\n  \"msorttd (nil2) = nil2\"\n| \"msorttd (cons2 y (nil2)) = cons2 y (nil2)\"\n| \"msorttd (cons2 y (cons2 x2 x3)) =\n     (let k :: int = (op div) (length (cons2 y (cons2 x2 x3))) 2\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  \"((msorttd 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_MSortTDIsSort.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.880797071719777, "lm_q2_score": 0.8289388104343892, "lm_q1q2_score": 0.7301268768654853}}
{"text": "(* original Author: Martin Desharnais\n    updated to version 2016 by Micha\u00ebl No\u00ebl Divo\n*)\n(*<*)\ntheory Typed_Arithmetic_Expressions\nimports Main\n  Untyped_Arithmetic_Expressions\nbegin\n(*>*)\n\nsection {* Typed Arithmetic Expressions *}\ntext {* \\label{sec:typed-arith-expr} *}\n\ntext {* In this section, we revisit the previously formalized arithmetic expression language\n(Section~\\ref{sec:untyped-arith-expr}) and augment it with static types. Since types are a\ncharacterization external to the definition of terms, we import the theory to reuse its definitions\nand theorems. We complete the definitions with the typing relation and prove type safety through the\nprogress and preservation theorems.\n*}\n\nsubsection {* Definitions *}\n\ntext {*\nThe language of arithmetic expressions contains two types for Booleans and natural numbers, which we\nmodel using a datatype:\n*}\n\ndatatype nbtype = Bool | Nat\n\n(* Definition 8.2.1 *)\n\ntext {*\nThe typing relation serves to assign a type to an expression. It is characterized by the following\ninference rules:\n\\setcounter{equation}{0}\n\\begin{gather}\n  \\inferrule {}{\\text{true} : \\text{Bool}} \\\\[0.8em]\n  \\inferrule {}{\\text{false} : \\text{Bool}} \\\\[0.8em]\n  \\inferrule {t_1 : \\text{Bool} \\\\ t_2 : \\text{T} \\\\ t_3 : \\text{T}}\n    {\\text{if } t_1 \\text{ then } t_2 \\text{ else } t_3 : \\text{T}} \\\\[0.8em]\n    \\inferrule {}{0 : \\text{Nat}} \\displaybreak\\\\[0.8em]\n  \\inferrule {t_1 : \\text{Nat}}{\\text{succ } t_1 : \\text{Nat}} \\\\[0.8em]\n  \\inferrule {t_1 : \\text{Nat}}{\\text{pred } t_1 : \\text{Nat}} \\\\[0.8em]\n  \\inferrule {t_1 : \\text{Nat}}{\\text{iszero } t_1 : \\text{Bool}}\n\\end{gather}\n\nThe first, second and fourth rules give the type of constants. The third rule requires that both\nbranches of a conditional have the same type and that the condition is a Boolean. The fifth and\nsixth rules state that the successor and predecessor of natural numbers are natural numbers\nthemselves. Finally, the seventh rule state that the test of equality with zero requires a natural\nnumber and leads a Boolean. We translate these rules in an inductive definition, for which we also\nprovide the @{text \"|:|\"} operator as a more conventional notation:\n*}\n\ninductive has_type :: \"nbterm \\<Rightarrow> nbtype \\<Rightarrow> bool\" (infix \"|:|\" 150) where\n  \\<comment> \\<open>Rules relating to the type of Booleans\\<close>\n  has_type_NBTrue:\n    \"NBTrue |:| Bool\" |\n  has_type_NBFalse:\n    \"NBFalse |:| Bool\" |\n  has_type_NBIf:\n    \"t1 |:| Bool \\<Longrightarrow> t2 |:| T \\<Longrightarrow> t3 |:| T \\<Longrightarrow> NBIf t1 t2 t3 |:| T\" |\n\n  \\<comment> \\<open>Rules relating to the type of natural numbers\\<close>\n  has_type_NBZero:\n    \"NBZero |:| Nat\" |\n  has_type_NBSucc:\n    \"t |:| Nat \\<Longrightarrow> NBSucc t |:| Nat\" |\n  has_type_NBPred:\n    \"t |:| Nat \\<Longrightarrow> NBPred t |:| Nat\" |\n  has_type_NBIs_zero:\n    \"t |:| Nat \\<Longrightarrow> NBIs_zero t |:| Bool\"\n\n(* Lemma 8.2.2 *)\n\ntext {*\nThe inversion of the typing relation gives us information on types for specific terms:\n*}\n\nlemma inversion_of_typing_relation:\n  \"NBTrue |:| R \\<Longrightarrow> R = Bool\"\n  \"NBFalse |:| R \\<Longrightarrow> R = Bool\"\n  \"NBIf t1 t2 t3 |:| R \\<Longrightarrow> t1 |:| Bool \\<and> t2 |:| R \\<and> t3 |:| R\"\n  \"NBZero |:| R \\<Longrightarrow> R = Nat\"\n  \"NBSucc t |:| R \\<Longrightarrow> R = Nat \\<and> t |:| Nat\"\n  \"NBPred t |:| R \\<Longrightarrow> R = Nat \\<and> t |:| Nat\"\n  \"NBIs_zero t |:| R \\<Longrightarrow> R = Bool \\<and> t |:| Nat\"\nby (auto elim: has_type.cases)\n\n(* Theorem 8.2.4 *)\n\ntext {*\nIn the typed arithmetic language, every term @{term t} has at most one type. That is, if @{term t}\nis typable, then its type is unique:\n*}\n\ntheorem uniqueness_of_types:\n  \"t |:| T \\<Longrightarrow> t |:| T' \\<Longrightarrow> T = T'\"\nby (induction t T rule: has_type.induct) (auto dest: inversion_of_typing_relation)\n\nsubsection {* Safety = Progress + Preservation *}\n\ntext {*\nThe most basic property a type system must provide is \\emph{safety}, also called \\emph{soundness}:\nthe evaluation of a well-typed term will not reach a state whose semantics is undefined. Since our\n\\emph{operational semantics} is based the of the evaluation relation and the value predicate, every\nterm that does not fit in one or the other has no defined semantics.\n\nAn example of an undefined state is @{term \"NBSucc NBTrue\"}: there is no further evaluation\nstep possible but it is not a value neither. In our current language, there is nothing we can do\nwith this term.\n*}\n\n(* Lemma 8.3.1 *)\n\ntext {*\nAnother usefull lemma is the canonical form of values which, for well typed terms, give us\ninformation on the nature of the terms:\n*}\n\nlemma canonical_form:\n  \"is_value_NB v \\<Longrightarrow> v |:| Bool \\<Longrightarrow> v = NBTrue \\<or> v = NBFalse\"\n  \"is_value_NB v \\<Longrightarrow> v |:| Nat \\<Longrightarrow> is_numeric_value_NB v\"\nby (auto elim: has_type.cases is_value_NB.cases is_numeric_value_NB.cases)\n\n(* Theorem 8.3.2 *)\n\ntext {*\nThe safety of a type system can be shown in two step: progress and preservation. Progress means that\na well-typed term is not stuck, i.e. either it is a value or it can take a step according to the\nevaluation rules.\n*}\n\ntheorem progress:\n  \"t |:| T \\<Longrightarrow> is_value_NB t \\<or> (\\<exists>t'. eval1_NB t t')\"\nproof (induction t T rule: has_type.induct)\n  case (has_type_NBPred t)\n  thus ?case\n    by (auto intro: eval1_NB.intros is_numeric_value_NB.cases dest: canonical_form)\nnext\n  case (has_type_NBIs_zero t)\n  thus ?case\n    by (auto intro: eval1_NB.intros is_numeric_value_NB.cases dest: canonical_form)\nqed (auto\n  intro: eval1_NB.intros is_value_NB.intros is_numeric_value_NB.intros\n  dest: canonical_form)\n\n(* Theorem 8.3.3 *)\n\ntext {*\nPreservation means that if a well-typed term takes a step of evaluation, then the resulting term is\nalso well-typed.\n*}\n\ntheorem preservation: \"t |:| T \\<Longrightarrow> eval1_NB t t' \\<Longrightarrow> t' |:| T\"\nproof (induction t T arbitrary: t' rule: has_type.induct)\n  case (has_type_NBIf t1 t2 T t3)\n  from has_type_NBIf.prems has_type_NBIf.IH has_type_NBIf.hyps show ?case\n    by (auto intro: has_type.intros elim: eval1_NB.cases)\nqed (auto\n  intro: has_type.intros\n  dest: inversion_of_typing_relation\n  elim: eval1_NB.cases)\n\n(*<*)\nend\n(*>*)\n", "meta": {"author": "mdesharnais", "repo": "log792-type-systems-formalization", "sha": "6b82d50845ee2603da295dfa972f45a258602a1c", "save_path": "github-repos/isabelle/mdesharnais-log792-type-systems-formalization", "path": "github-repos/isabelle/mdesharnais-log792-type-systems-formalization/log792-type-systems-formalization-6b82d50845ee2603da295dfa972f45a258602a1c/2016/Typed_Arithmetic_Expressions.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8289387914176258, "lm_q2_score": 0.8807970889295664, "lm_q1q2_score": 0.7301268743814379}}
{"text": "(*  Title:      HOL/Orderings.thy\n    Author:     Tobias Nipkow, Markus Wenzel, and Larry Paulson\n*)\n\nsection {* Abstract orderings *}\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 {* Abstract ordering *}\n\nlocale ordering =\n  fixes less_eq :: \"'a \\<Rightarrow> 'a \\<Rightarrow> bool\" (infix \"\\<preceq>\" 50)\n   and less :: \"'a \\<Rightarrow> 'a \\<Rightarrow> bool\" (infix \"\\<prec>\" 50)\n  assumes strict_iff_order: \"a \\<prec> b \\<longleftrightarrow> a \\<preceq> b \\<and> a \\<noteq> b\"\n  assumes refl: \"a \\<preceq> a\" -- {* not @{text iff}: makes problems due to multiple (dual) interpretations *}\n    and antisym: \"a \\<preceq> b \\<Longrightarrow> b \\<preceq> a \\<Longrightarrow> a = b\"\n    and trans: \"a \\<preceq> b \\<Longrightarrow> b \\<preceq> c \\<Longrightarrow> a \\<preceq> c\"\nbegin\n\nlemma strict_implies_order:\n  \"a \\<prec> b \\<Longrightarrow> a \\<preceq> b\"\n  by (simp add: strict_iff_order)\n\nlemma strict_implies_not_eq:\n  \"a \\<prec> 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 \\<preceq> b \\<Longrightarrow> a \\<prec> b\"\n  by (simp add: strict_iff_order)\n\nlemma order_iff_strict:\n  \"a \\<preceq> b \\<longleftrightarrow> a \\<prec> b \\<or> a = b\"\n  by (auto simp add: strict_iff_order refl)\n\nlemma irrefl: -- {* not @{text iff}: makes problems due to multiple (dual) interpretations *}\n  \"\\<not> a \\<prec> a\"\n  by (simp add: strict_iff_order)\n\nlemma asym:\n  \"a \\<prec> b \\<Longrightarrow> b \\<prec> a \\<Longrightarrow> False\"\n  by (auto simp add: strict_iff_order intro: antisym)\n\nlemma strict_trans1:\n  \"a \\<preceq> b \\<Longrightarrow> b \\<prec> c \\<Longrightarrow> a \\<prec> c\"\n  by (auto simp add: strict_iff_order intro: trans antisym)\n\nlemma strict_trans2:\n  \"a \\<prec> b \\<Longrightarrow> b \\<preceq> c \\<Longrightarrow> a \\<prec> c\"\n  by (auto simp add: strict_iff_order intro: trans antisym)\n\nlemma strict_trans:\n  \"a \\<prec> b \\<Longrightarrow> b \\<prec> c \\<Longrightarrow> a \\<prec> c\"\n  by (auto intro: strict_trans1 strict_implies_order)\n\nend\n\nlocale ordering_top = ordering +\n  fixes top :: \"'a\"\n  assumes extremum [simp]: \"a \\<preceq> top\"\nbegin\n\nlemma extremum_uniqueI:\n  \"top \\<preceq> a \\<Longrightarrow> a = top\"\n  by (rule antisym) auto\n\nlemma extremum_unique:\n  \"top \\<preceq> a \\<longleftrightarrow> a = top\"\n  by (auto intro: antisym)\n\nlemma extremum_strict [simp]:\n  \"\\<not> (top \\<prec> a)\"\n  using extremum [of a] by (auto simp add: order_iff_strict intro: asym irrefl)\n\nlemma not_eq_extremum:\n  \"a \\<noteq> top \\<longleftrightarrow> a \\<prec> top\"\n  by (auto simp add: order_iff_strict intro: not_eq_order_implies_strict extremum)\n\nend  \n\n\nsubsection {* Syntactic orders *}\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 <=\") and\n  less_eq  (\"(_/ <= _)\" [51, 51] 50) and\n  less  (\"op <\") and\n  less  (\"(_/ < _)\"  [51, 51] 50)\n  \nnotation (xsymbols)\n  less_eq  (\"op \\<le>\") and\n  less_eq  (\"(_/ \\<le> _)\"  [51, 51] 50)\n\nnotation (HTML output)\n  less_eq  (\"op \\<le>\") and\n  less_eq  (\"(_/ \\<le> _)\"  [51, 51] 50)\n\nabbreviation (input)\n  greater_eq  (infix \">=\" 50) where\n  \"x >= y \\<equiv> y <= x\"\n\nnotation (input)\n  greater_eq  (infix \"\\<ge>\" 50)\n\nabbreviation (input)\n  greater  (infix \">\" 50) where\n  \"x > y \\<equiv> y < x\"\n\nend\n\n\nsubsection {* Quasi orders *}\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 {* Reflexivity. *}\n\nlemma eq_refl: \"x = y \\<Longrightarrow> x \\<le> y\"\n    -- {* This form is useful with the classical reasoner. *}\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\"\nunfolding less_le_not_le by blast\n\n\ntext {* Asymmetry. *}\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 {* Transitivity. *}\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 {* Useful for simplification, but too risky to include by default. *}\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 {* Transitivity rules for calculational reasoning *}\n\nlemma less_asym': \"a < b \\<Longrightarrow> b < a \\<Longrightarrow> P\"\nby (rule less_asym)\n\n\ntext {* Dual order *}\n\nlemma dual_preorder:\n  \"class.preorder (op \\<ge>) (op >)\"\nproof qed (auto simp add: less_le_not_le intro: order_trans)\n\nend\n\n\nsubsection {* Partial orders *}\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\n  by default (auto intro: antisym order_trans simp add: less_le)\n\n\ntext {* Reflexivity. *}\n\nlemma le_less: \"x \\<le> y \\<longleftrightarrow> x < y \\<or> x = y\"\n    -- {* NOT suitable for iff, since it can cause PROOF FAILED. *}\nby (fact order.order_iff_strict)\n\nlemma le_imp_less_or_eq: \"x \\<le> y \\<Longrightarrow> x < y \\<or> x = y\"\nunfolding less_le by blast\n\n\ntext {* Useful for simplification, but too risky to include by default. *}\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 {* Transitivity rules for calculational reasoning *}\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 {* Asymmetry. *}\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 {* Least value operator *}\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\n\ntext {* Dual order *}\n\nlemma dual_order:\n  \"class.order (op \\<ge>) (op >)\"\nby (intro_locales, rule dual_preorder) (unfold_locales, rule antisym)\n\nend\n\n\ntext {* Alternative introduction rule with bias towards strict order *}\n\nlemma order_strictI:\n  fixes less (infix \"\\<sqsubset>\" 50)\n    and less_eq (infix \"\\<sqsubseteq>\" 50)\n  assumes less_eq_less: \"\\<And>a b. a \\<sqsubseteq> b \\<longleftrightarrow> a \\<sqsubset> b \\<or> a = b\"\n    assumes asym: \"\\<And>a b. a \\<sqsubset> b \\<Longrightarrow> \\<not> b \\<sqsubset> a\"\n  assumes irrefl: \"\\<And>a. \\<not> a \\<sqsubset> a\"\n  assumes trans: \"\\<And>a b c. a \\<sqsubset> b \\<Longrightarrow> b \\<sqsubset> c \\<Longrightarrow> a \\<sqsubset> c\"\n  shows \"class.order less_eq less\"\nproof\n  fix a b\n  show \"a \\<sqsubset> b \\<longleftrightarrow> a \\<sqsubseteq> b \\<and> \\<not> b \\<sqsubseteq> a\"\n    by (auto simp add: less_eq_less asym irrefl)\nnext\n  fix a\n  show \"a \\<sqsubseteq> a\"\n    by (auto simp add: less_eq_less)\nnext\n  fix a b c\n  assume \"a \\<sqsubseteq> b\" and \"b \\<sqsubseteq> c\" then show \"a \\<sqsubseteq> c\"\n    by (auto simp add: less_eq_less intro: trans)\nnext\n  fix a b\n  assume \"a \\<sqsubseteq> b\" and \"b \\<sqsubseteq> a\" then show \"a = b\"\n    by (auto simp add: less_eq_less asym)\nqed\n\n\nsubsection {* Linear (total) orders *}\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 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\n(*FIXME inappropriate name (or delete altogether)*)\nlemma not_leE: \"\\<not> y \\<le> x \\<Longrightarrow> x < y\"\nunfolding not_le .\n\ntext {* Dual order *}\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 {* Alternative introduction rule with bias towards strict order *}\n\nlemma linorder_strictI:\n  fixes less (infix \"\\<sqsubset>\" 50)\n    and less_eq (infix \"\\<sqsubseteq>\" 50)\n  assumes \"class.order less_eq less\"\n  assumes trichotomy: \"\\<And>a b. a \\<sqsubset> b \\<or> a = b \\<or> b \\<sqsubset> a\"\n  shows \"class.linorder less_eq less\"\nproof -\n  interpret order less_eq less\n    by (fact `class.order less_eq less`)\n  show ?thesis\n  proof\n    fix a b\n    show \"a \\<sqsubseteq> b \\<or> b \\<sqsubseteq> a\"\n      using trichotomy by (auto simp add: le_less)\n  qed\nqed\n\n\nsubsection {* Reasoning tools setup *}\n\nML {*\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_spec \"print_orders\"}\n    \"print order structures available to transitivity reasoner\"\n    (Scan.succeed (Toplevel.unknown_context o\n      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*}\n\nattribute_setup order = {*\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*} \"theorems controlling transitivity reasoner\"\n\nmethod_setup order = {*\n  Scan.succeed (fn ctxt => SIMPLE_METHOD' (Orders.order_tac ctxt []))\n*} \"transitivity reasoner\"\n\n\ntext {* Declarations to set up transitivity reasoner of partial and linear orders. *}\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 {*\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*}\n\nML {*\nlocal\n  fun prp t thm = Thm.prop_of thm = t;  (* FIXME proper aconv!? *)\nin\n\nfun antisym_le_simproc ctxt ct =\n  (case 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 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*}\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 {* Bounded quantifiers *}\n\nsyntax\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 (xsymbols)\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 (HOL)\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\nsyntax (HTML output)\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\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 {*\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*}\n\n\nsubsection {* Transitivity reasoning *}\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 {*\n  Note that this list of rules is in reverse order of priorities.\n*}\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 {* These support proving chains of decreasing inequalities\n    a >= b >= c ... in Isar proofs. *}\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 {* Monotonicity *}\n\ncontext order\nbegin\n\ndefinition mono :: \"('a \\<Rightarrow> 'b\\<Colon>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\\<Colon>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\\<Colon>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\\<Colon>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\\<Colon>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\\<Colon>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\\<Colon>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\\<Colon>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\\<Colon>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 `x \\<le> y` 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\\<Colon>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 `mono f` obtain \"f y \\<le> f x\" by (rule monoE)\n    with `f x < f y` 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 `f x = f y` 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 `f x = f y` 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 `f x \\<le> f y` 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 {* min and max -- fundamental *}\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\\<Colon>'a\\<Colon>order) \\<le> x \\<Longrightarrow> min x y = y\"\n  by (simp add:min_def)\n\nlemma max_absorb1: \"(y\\<Colon>'a\\<Colon>order) \\<le> x \\<Longrightarrow> max x y = x\"\n  by (simp add: max_def)\n\n\nsubsection {* (Unique) top and bottom elements *}\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 default (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 default (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 {* Dense orders *}\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 `x < y`] .\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 `x < y`] 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 `x < u` `u \\<le> w`] `w < y`\n    show \"w \\<le> z\" by (rule *)\n  next\n    assume \"w \\<le> u\"\n    from `w \\<le> u` *[OF `x < u` `u < y`]\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 `z < x`] .\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 `z < x`] 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 `z < w` le_less_trans[OF `w \\<le> u` `u < x`]\n    show \"y \\<le> w\" by (rule *)\n  next\n    assume \"u \\<le> w\"\n    from *[OF `z < u` `u < x`] `u \\<le> w`\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 {* Wellorders *}\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 `P x` have Least: \"(LEAST a. P a) = x\"\n        by (rule Least_equality)\n      with `P x` 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-- \"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 `P a` 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 not_less_Least: \"k < (LEAST x. P x) \\<Longrightarrow> \\<not> P k\"\napply (simp (no_asm_use) add: not_le [symmetric])\napply (erule contrapos_nn)\napply (erule Least_le)\ndone\n\nend\n\n\nsubsection {* Order on @{typ bool} *}\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\\<Colon>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 {* Order on @{typ \"_ \\<Rightarrow> _\"} *}\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\\<Colon>'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 {* Order on unary and binary predicates *}\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 {* Name duplicates *}\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\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/Orderings.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8902942348544448, "lm_q2_score": 0.8198933315126791, "lm_q1q2_score": 0.7299463062413423}}
{"text": "theory Submission\nimports Defs\nbegin\n\n\n(* The append lemma - gives 30% of the points.\n   Note: While this lemma gives less points, it's actually harder to prove! *)\n\nlemma rle_append: \"xs = [] \\<or> ys = [] \\<or> last xs \\<noteq> hd ys \\<Longrightarrow> rle (xs @ ys) = rle xs @ rle ys\"\n  apply (induction xs rule: rle.induct)\n  apply (auto split: if_splits)\n  subgoal by (metis (mono_tags, lifting) hd_Cons_tl takeWhile.simps(1) takeWhile.simps(2))\n  subgoal\n    by (metis (full_types) dropWhile.simps(1) dropWhile.simps(2) hd_Cons_tl)\n  subgoal\n    apply (cases ys)\n    apply auto\n    by (smt append_Nil2 last_in_set list.sel(1) rle.elims takeWhile.simps(2) takeWhile_append1 takeWhile_append2 takeWhile_eq_all_conv)\n  subgoal\n    apply (cases ys)\n    apply auto\n    by (smt append_Nil2 dropWhile_append1 dropWhile_append3 dropWhile_eq_Nil_conv last_appendR last_in_set list.sel(1) rle.elims takeWhile_dropWhile_id)\n  done\n(* Given the append lemma show the reverse lemma - gives 70% of the points.\n   Note: While this lemma gives more points, it might actually be easier to prove *)\n   \n   \n\n\nlemma TKS: \"set (takeWhile (\\<lambda>y. y = x) xs) \\<subseteq> {x}\"  \n  apply (induction xs)\n  apply simp\n  by (metis (mono_tags, lifting) set_takeWhileD singleton_iff subsetI)\n  \n   \nlemma 1: \"rle (rev xs) = rev (rle xs)\"\nproof (induction xs rule: rle.induct)\n  case 1\n  then show ?case by auto\nnext\n  case (2 x xs)\n  \n  have 1: \"[(x, Suc (length (takeWhile (\\<lambda>y. y = x) xs)))] = rle (takeWhile (\\<lambda>y. y = x) (x#xs))\"\n    apply (cases xs)\n    apply auto\n    by (metis rle.simps(1) self_append_conv takeWhile_dropWhile_id takeWhile_idem)\n    \n  have x1: \"rev (takeWhile (\\<lambda>y. y = x) xs) = takeWhile (\\<lambda>y. y = x) xs\"  \n    by (simp add: SR[OF TKS])\n    \n  have x2: \"rev (dropWhile (\\<lambda>y. y = x) xs) @ takeWhile (\\<lambda>y. y = x) (x # xs) = rev (x#xs)\"\n    apply simp\n    apply (subst (3) takeWhile_dropWhile_id[of \"(\\<lambda>y. y = x)\" xs, symmetric])\n    apply (simp del: takeWhile_dropWhile_id)\n    apply (subst x1)\n    by (simp add: TKS)\n  \n  have \"rev (rle (dropWhile (\\<lambda>y. y = x) xs)) @ [(x, Suc (length (takeWhile (\\<lambda>y. y = x) xs)))]\n    = (rle (rev (x#xs)))\n  \"\n    apply (simp only: 1 2[symmetric])\n    apply (subst rle_append[symmetric])\n    apply auto []\n    apply (metis (full_types) append_Nil2 empty_iff filter_id_conv hd_dropWhile last_rev list.set(1) takeWhile_dropWhile_id takeWhile_eq_filter)\n    apply (simp only: x2)\n    done\n    \n    \n  then show ?case\n    by simp\n  \nqed\n  \n\n   \n   \nlemma rle_rev_if_rle_append: \"(xs = [] \\<or> ys = [] \\<or> last xs \\<noteq> hd ys \\<Longrightarrow> rle (xs @ ys) = rle xs @ rle ys)\n       \\<Longrightarrow> rle (rev xs) = rev (rle xs)\"\n  using 1 by blast\n\nend\n", "meta": {"author": "maxhaslbeck", "repo": "proofground2020-solutions", "sha": "023ec2643f6aa06e60bec391e20f178c258ea1a3", "save_path": "github-repos/isabelle/maxhaslbeck-proofground2020-solutions", "path": "github-repos/isabelle/maxhaslbeck-proofground2020-solutions/proofground2020-solutions-023ec2643f6aa06e60bec391e20f178c258ea1a3/favourite_computer_game/Isabelle/lammich/Submission.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942144788076, "lm_q2_score": 0.8198933381139645, "lm_q1q2_score": 0.7299462954125794}}
{"text": "theory ex301\n  imports Main\nbegin\ndatatype 'a tree = Tip | Node \"'a tree\" 'a \"'a tree\"\n  \nvalue \"Node Tip True Tip\"\n  \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  \nvalue \"set (Node (Node (Node Tip 4 Tip) 1 (Node Tip 5 Tip)) (2::int) (Node Tip 3 Tip))\"\n  \nfun get::\"int tree \\<Rightarrow> int\" where\n  \"get Tip = 0\"|\n  \"get (Node l v r) = v\"\n  \nvalue \"get (Node Tip 7 Tip)\"\n  \nfun ord::\"int tree \\<Rightarrow> bool\" where\n  \"ord Tip = True\"|\n  \"ord (Node Tip v Tip) = True\"|\n  \"ord (Node l v Tip) = (if (ord l)\\<and>((get l) < v) then True else False)\"|\n  \"ord (Node Tip v r) = (if (ord r)\\<and>(v < (get r)) then True else False)\"|\n  \"ord (Node l v r) = (if (ord l)\\<and>(ord r)\\<and>((get l)<v)\\<and>(v<(get r)) then True else False)\"\n  \nvalue \"ord (Node (Node Tip 2 Tip) 4 Tip)\"\nvalue \"ord (Node (Node (Node Tip 1 Tip) 2 (Node Tip 6 Tip)) 5 (Node Tip 6 Tip))\"\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) = (if (x=v) then (Node l v r) else (if (x<v) then (Node (ins x l) v r) else (Node l v (ins x r))))\"\n\nvalue \"ins 3 (Node (Node Tip 2 Tip) 4 Tip)\"\n  \nlemma ex301a: \"set (ins x t) = {x} \\<union> set t\"\n  apply(induction t arbitrary: x)\n   apply(auto simp add:algebra_simps)\n  done\n    \n    \nlemma ex301b: \"ord t \\<Longrightarrow> ord (ins i t)\"\n  apply(induction t arbitrary: i)\n   apply(auto simp add:algebra_simps)\n  sorry\n    \n\n    \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/ex301.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898153067649, "lm_q2_score": 0.8056321936479701, "lm_q1q2_score": 0.7298945623283083}}
{"text": "(*  Author:  Gertrud Bauer, Tobias Nipkow  *)\n\nsection \\<open>Transitive Closure of Successor List Function\\<close>\n\ntheory RTranCl\nimports Main\nbegin\n\ntext\\<open>The reflexive transitive closure of a relation induced by a\nfunction of type @{typ\"'a \\<Rightarrow> 'a list\"}. Instead of defining the closure\nagain it would have been simpler to take @{term\"{(x,y) . y \\<in> set(f x)}\\<^sup>*\"}.\\<close>\n\nabbreviation (input)\n  in_set :: \"'a \\<Rightarrow> ('a \\<Rightarrow> 'b list) \\<Rightarrow> 'b \\<Rightarrow> bool\" (\"_ [_]\\<rightarrow> _\" [55,0,55] 50) where\n  \"g [succs]\\<rightarrow> g' == g' \\<in> set (succs g)\"\n\ninductive_set\n  RTranCl :: \"('a \\<Rightarrow> 'a list) \\<Rightarrow> ('a * 'a) set\"\n  and in_RTranCl :: \"'a \\<Rightarrow> ('a \\<Rightarrow> 'a list) \\<Rightarrow> 'a \\<Rightarrow> bool\"\n    (\"_ [_]\\<rightarrow>* _\" [55,0,55] 50)\n  for succs :: \"'a \\<Rightarrow> 'a list\"\nwhere\n  \"g [succs]\\<rightarrow>* g' \\<equiv> (g,g') \\<in> RTranCl succs\"\n| refl: \"g [succs]\\<rightarrow>* g\"\n| succs: \"g [succs]\\<rightarrow> g' \\<Longrightarrow> g' [succs]\\<rightarrow>* g'' \\<Longrightarrow> g [succs]\\<rightarrow>* g''\"\n\ninductive_cases RTranCl_elim: \"(h,h') : RTranCl succs\"\n\nlemma RTranCl_induct(*<*) [induct set: RTranCl, consumes 1, case_names refl succs] (*>*):\n \"(h, h') \\<in> RTranCl succs \\<Longrightarrow> \n  P h \\<Longrightarrow> \n  (\\<And>g g'. g' \\<in> set (succs g) \\<Longrightarrow> P g \\<Longrightarrow> P g') \\<Longrightarrow> \n  P h'\"\nproof -\n  assume s: \"\\<And>g g'. g' \\<in> set (succs g) \\<Longrightarrow> P g \\<Longrightarrow> P g'\"\n  assume \"(h, h') \\<in> RTranCl succs\" \"P h\"\n  then show \"P h'\"\n  proof (induct rule: RTranCl.induct)\n    fix g assume \"P g\" then show \"P g\" . \n  next\n    fix g g' g''\n    assume IH: \"P g' \\<Longrightarrow> P g''\"\n    assume \"g' \\<in> set(succs g)\" \"P g\"\n    then have \"P g'\" by (rule s)\n    then show \"P g''\" by (rule IH)\n  qed\nqed\n\ndefinition invariant :: \"('a \\<Rightarrow> bool) \\<Rightarrow> ('a \\<Rightarrow> 'a list) \\<Rightarrow> bool\" where\n\"invariant P succs \\<equiv> \\<forall>g g'. g' \\<in> set(succs g) \\<longrightarrow> P g \\<longrightarrow> P g'\"\n\nlemma invariantE:\n  \"invariant P succs  \\<Longrightarrow> g [succs]\\<rightarrow> g' \\<Longrightarrow> P g \\<Longrightarrow> P g'\"\nby(simp add:invariant_def)\n\nlemma inv_subset:\n \"invariant P f \\<Longrightarrow> (\\<And>g. P g \\<Longrightarrow> set(f' g) \\<subseteq> set(f g)) \\<Longrightarrow> invariant P f'\"\nby(auto simp:invariant_def)\n\nlemma RTranCl_inv:\n  \"invariant P succs \\<Longrightarrow> (g,g') \\<in> RTranCl succs \\<Longrightarrow> P g \\<Longrightarrow> P g'\"\nby (erule RTranCl_induct)(auto simp:invariant_def)\n\nlemma RTranCl_subset2:\nassumes a: \"(s,g) : RTranCl f\"\nshows \"(\\<And>g. (s,g) \\<in> RTranCl f \\<Longrightarrow> set(f g) \\<subseteq> set(h g)) \\<Longrightarrow> (s,g) : RTranCl h\"\nusing a\nproof (induct rule: RTranCl.induct)\n  case refl show ?case by(rule RTranCl.intros)\nnext\n  case succs thus ?case by(blast intro: RTranCl.intros)\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/Flyspeck-Tame/RTranCl.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357735451835, "lm_q2_score": 0.8418256532040708, "lm_q1q2_score": 0.7298929564159709}}
{"text": "(*  Title:      HOL/Induct/QuoNestedDataType.thy\n    Author:     Lawrence C Paulson, Cambridge University Computer Laboratory\n    Copyright   2004  University of Cambridge\n*)\n\nsection\\<open>Quotienting a Free Algebra Involving Nested Recursion\\<close>\n\ntext \\<open>This is the development promised in Lawrence Paulson's paper ``Defining functions on equivalence classes''\n\\emph{ACM Transactions on Computational Logic} \\textbf{7}:40 (2006), 658--675,\nillustrating bare-bones quotient constructions. Any comparison using lifting and transfer\nshould be done in a separate theory.\\<close>\n\ntheory QuoNestedDataType imports Main begin\n\nsubsection\\<open>Defining the Free Algebra\\<close>\n\ntext\\<open>Messages with encryption and decryption as free constructors.\\<close>\ndatatype\n     freeExp = VAR  nat\n             | PLUS  freeExp freeExp\n             | FNCALL  nat \"freeExp list\"\n\ndatatype_compat freeExp\n\ntext\\<open>The equivalence relation, which makes PLUS associative.\\<close>\n\ntext\\<open>The first rule is the desired equation. The next three rules\nmake the equations applicable to subterms. The last two rules are symmetry\nand transitivity.\\<close>\ninductive_set\n  exprel :: \"(freeExp * freeExp) set\"\n  and exp_rel :: \"[freeExp, freeExp] => bool\"  (infixl \"\\<sim>\" 50)\n  where\n    \"X \\<sim> Y \\<equiv> (X,Y) \\<in> exprel\"\n  | ASSOC: \"PLUS X (PLUS Y Z) \\<sim> PLUS (PLUS X Y) Z\"\n  | VAR: \"VAR N \\<sim> VAR N\"\n  | PLUS: \"\\<lbrakk>X \\<sim> X'; Y \\<sim> Y'\\<rbrakk> \\<Longrightarrow> PLUS X Y \\<sim> PLUS X' Y'\"\n  | FNCALL: \"(Xs,Xs') \\<in> listrel exprel \\<Longrightarrow> FNCALL F Xs \\<sim> FNCALL F Xs'\"\n  | SYM:   \"X \\<sim> Y \\<Longrightarrow> Y \\<sim> X\"\n  | TRANS: \"\\<lbrakk>X \\<sim> Y; Y \\<sim> Z\\<rbrakk> \\<Longrightarrow> X \\<sim> Z\"\n  monos listrel_mono\n\n\ntext\\<open>Proving that it is an equivalence relation\\<close>\n\nlemma exprel_refl: \"X \\<sim> X\"\n  and list_exprel_refl: \"(Xs,Xs) \\<in> listrel(exprel)\"\n  by (induct X and Xs rule: compat_freeExp.induct compat_freeExp_list.induct)\n    (blast intro: exprel.intros listrel.intros)+\n\ntheorem equiv_exprel: \"equiv UNIV exprel\"\nproof -\n  have \"refl exprel\" by (simp add: refl_on_def exprel_refl)\n  moreover have \"sym exprel\" by (simp add: sym_def, blast intro: exprel.SYM)\n  moreover have \"trans exprel\" by (simp add: trans_def, blast intro: exprel.TRANS)\n  ultimately show ?thesis by (simp add: equiv_def)\nqed\n\ntheorem equiv_list_exprel: \"equiv UNIV (listrel exprel)\"\n  using equiv_listrel [OF equiv_exprel] by simp\n\nlemma FNCALL_Cons:\n  \"\\<lbrakk>X \\<sim> X'; (Xs,Xs') \\<in> listrel(exprel)\\<rbrakk> \\<Longrightarrow> FNCALL F (X#Xs) \\<sim> FNCALL F (X'#Xs')\"\n  by (blast intro: exprel.intros listrel.intros) \n\n\nsubsection\\<open>Some Functions on the Free Algebra\\<close>\n\nsubsubsection\\<open>The Set of Variables\\<close>\n\ntext\\<open>A function to return the set of variables present in a message.  It will\nbe lifted to the initial algebra, to serve as an example of that process.\nNote that the \"free\" refers to the free datatype rather than to the concept\nof a free variable.\\<close>\nprimrec freevars :: \"freeExp \\<Rightarrow> nat set\" and freevars_list :: \"freeExp list \\<Rightarrow> nat set\"\n  where\n  \"freevars (VAR N) = {N}\"\n| \"freevars (PLUS X Y) = freevars X \\<union> freevars Y\"\n| \"freevars (FNCALL F Xs) = freevars_list Xs\"\n\n| \"freevars_list [] = {}\"\n| \"freevars_list (X # Xs) = freevars X \\<union> freevars_list Xs\"\n\ntext\\<open>This theorem lets us prove that the vars function respects the\nequivalence relation.  It also helps us prove that Variable\n  (the abstract constructor) is injective\\<close>\ntheorem exprel_imp_eq_freevars: \"U \\<sim> V \\<Longrightarrow> freevars U = freevars V\"\nproof (induct set: exprel)\n  case (FNCALL Xs Xs' F)\n  then show ?case\n    by (induct rule: listrel.induct) auto\nqed (simp_all add: Un_assoc)\n\n\nsubsubsection\\<open>Functions for Freeness\\<close>\n\ntext\\<open>A discriminator function to distinguish vars, sums and function calls\\<close>\nprimrec freediscrim :: \"freeExp \\<Rightarrow> int\" where\n  \"freediscrim (VAR N) = 0\"\n| \"freediscrim (PLUS X Y) = 1\"\n| \"freediscrim (FNCALL F Xs) = 2\"\n\ntheorem exprel_imp_eq_freediscrim:\n     \"U \\<sim> V \\<Longrightarrow> freediscrim U = freediscrim V\"\n  by (induct set: exprel) auto\n\n\ntext\\<open>This function, which returns the function name, is used to\nprove part of the injectivity property for FnCall.\\<close>\nprimrec freefun :: \"freeExp \\<Rightarrow> nat\" where\n  \"freefun (VAR N) = 0\"\n| \"freefun (PLUS X Y) = 0\"\n| \"freefun (FNCALL F Xs) = F\"\n\ntheorem exprel_imp_eq_freefun:\n     \"U \\<sim> V \\<Longrightarrow> freefun U = freefun V\"\n  by (induct set: exprel) (simp_all add: listrel.intros)\n\n\ntext\\<open>This function, which returns the list of function arguments, is used to\nprove part of the injectivity property for FnCall.\\<close>\nprimrec freeargs :: \"freeExp \\<Rightarrow> freeExp list\" where\n  \"freeargs (VAR N) = []\"\n| \"freeargs (PLUS X Y) = []\"\n| \"freeargs (FNCALL F Xs) = Xs\"\n\n\ntheorem exprel_imp_eqv_freeargs:\n  assumes \"U \\<sim> V\"\n  shows \"(freeargs U, freeargs V) \\<in> listrel exprel\"\n  using assms\nproof induction\n  case (FNCALL Xs Xs' F)\n  then show ?case\n    by (simp add: listrel_iff_nth)\nnext\n  case (SYM X Y)\n  then show ?case\n    by (meson equivE equiv_list_exprel symD)\nnext\n  case (TRANS X Y Z)\n  then show ?case\n    by (meson equivE equiv_list_exprel transD)\nqed (use listrel.simps in auto)\n\n\nsubsection\\<open>The Initial Algebra: A Quotiented Message Type\\<close>\n\ndefinition \"Exp = UNIV//exprel\"\n\ntypedef exp = Exp\n  morphisms Rep_Exp Abs_Exp\n  unfolding Exp_def by (auto simp add: quotient_def)\n\ntext\\<open>The abstract message constructors\\<close>\n\ndefinition\n  Var :: \"nat \\<Rightarrow> exp\" where\n  \"Var N = Abs_Exp(exprel``{VAR N})\"\n\ndefinition\n  Plus :: \"[exp,exp] \\<Rightarrow> exp\" where\n   \"Plus X Y =\n       Abs_Exp (\\<Union>U \\<in> Rep_Exp X. \\<Union>V \\<in> Rep_Exp Y. exprel``{PLUS U V})\"\n\ndefinition\n  FnCall :: \"[nat, exp list] \\<Rightarrow> exp\" where\n   \"FnCall F Xs =\n       Abs_Exp (\\<Union>Us \\<in> listset (map Rep_Exp Xs). exprel``{FNCALL F Us})\"\n\n\ntext\\<open>Reduces equality of equivalence classes to the \\<^term>\\<open>exprel\\<close> relation:\n  \\<^term>\\<open>(exprel``{x} = exprel``{y}) = ((x,y) \\<in> exprel)\\<close>\\<close>\nlemmas equiv_exprel_iff = eq_equiv_class_iff [OF equiv_exprel UNIV_I UNIV_I]\n\ndeclare equiv_exprel_iff [simp]\n\n\ntext\\<open>All equivalence classes belong to set of representatives\\<close>\nlemma exprel_in_Exp [simp]: \"exprel``{U} \\<in> Exp\"\n  by (simp add: Exp_def quotientI)\n\nlemma inj_on_Abs_Exp: \"inj_on Abs_Exp Exp\"\n  by (meson Abs_Exp_inject inj_onI)\n\ntext\\<open>Reduces equality on abstractions to equality on representatives\\<close>\ndeclare inj_on_Abs_Exp [THEN inj_on_eq_iff, simp]\n\ndeclare Abs_Exp_inverse [simp]\n\n\ntext\\<open>Case analysis on the representation of a exp as an equivalence class.\\<close>\nlemma eq_Abs_Exp [case_names Abs_Exp, cases type: exp]:\n     \"(\\<And>U. z = Abs_Exp (exprel``{U}) \\<Longrightarrow> P) \\<Longrightarrow> P\"\n  by (metis Abs_Exp_cases Exp_def quotientE)\n\n\nsubsection\\<open>Every list of abstract expressions can be expressed in terms of a\n  list of concrete expressions\\<close>\n\ndefinition\n  Abs_ExpList :: \"freeExp list => exp list\" where\n  \"Abs_ExpList Xs \\<equiv> map (\\<lambda>U. Abs_Exp(exprel``{U})) Xs\"\n\nlemma Abs_ExpList_Nil [simp]: \"Abs_ExpList [] = []\"\n  by (simp add: Abs_ExpList_def)\n\nlemma Abs_ExpList_Cons [simp]:\n  \"Abs_ExpList (X#Xs) = Abs_Exp (exprel``{X}) # Abs_ExpList Xs\"\n  by (simp add: Abs_ExpList_def)\n\nlemma ExpList_rep: \"\\<exists>Us. z = Abs_ExpList Us\"\n  by (smt (verit, del_insts) Abs_ExpList_def eq_Abs_Exp ex_map_conv)\n\n\nsubsubsection\\<open>Characteristic Equations for the Abstract Constructors\\<close>\n\nlemma Plus: \"Plus (Abs_Exp(exprel``{U})) (Abs_Exp(exprel``{V})) = \n             Abs_Exp (exprel``{PLUS U V})\"\nproof -\n  have \"(\\<lambda>U V. exprel``{PLUS U V}) respects2 exprel\"\n    by (auto simp add: congruent2_def exprel.PLUS)\n  thus ?thesis\n    by (simp add: Plus_def UN_equiv_class2 [OF equiv_exprel equiv_exprel])\nqed\n\ntext\\<open>It is not clear what to do with FnCall: it's argument is an abstraction\nof an \\<^typ>\\<open>exp list\\<close>. Is it just Nil or Cons? What seems to work best is to\nregard an \\<^typ>\\<open>exp list\\<close> as a \\<^term>\\<open>listrel exprel\\<close> equivalence class\\<close>\n\ntext\\<open>This theorem is easily proved but never used. There's no obvious way\neven to state the analogous result, \\<open>FnCall_Cons\\<close>.\\<close>\nlemma FnCall_Nil: \"FnCall F [] = Abs_Exp (exprel``{FNCALL F []})\"\n  by (simp add: FnCall_def)\n\nlemma FnCall_respects: \n     \"(\\<lambda>Us. exprel``{FNCALL F Us}) respects (listrel exprel)\"\n  by (auto simp add: congruent_def exprel.FNCALL)\n\nlemma FnCall_sing:\n     \"FnCall F [Abs_Exp(exprel``{U})] = Abs_Exp (exprel``{FNCALL F [U]})\"\nproof -\n  have \"(\\<lambda>U. exprel``{FNCALL F [U]}) respects exprel\"\n    by (auto simp add: congruent_def FNCALL_Cons listrel.intros)\n  thus ?thesis\n    by (simp add: FnCall_def UN_equiv_class [OF equiv_exprel])\nqed\n\nlemma listset_Rep_Exp_Abs_Exp:\n     \"listset (map Rep_Exp (Abs_ExpList Us)) = listrel exprel``{Us}\"\n  by (induct Us) (simp_all add: listrel_Cons Abs_ExpList_def)\n\nlemma FnCall:\n     \"FnCall F (Abs_ExpList Us) = Abs_Exp (exprel``{FNCALL F Us})\"\nproof -\n  have \"(\\<lambda>Us. exprel``{FNCALL F Us}) respects (listrel exprel)\"\n    by (auto simp add: congruent_def exprel.FNCALL)\n  thus ?thesis\n    by (simp add: FnCall_def UN_equiv_class [OF equiv_list_exprel]\n                  listset_Rep_Exp_Abs_Exp)\nqed\n\n\ntext\\<open>Establishing this equation is the point of the whole exercise\\<close>\n\n\n\n\nsubsection\\<open>The Abstract Function to Return the Set of Variables\\<close>\n\ndefinition\n  vars :: \"exp \\<Rightarrow> nat set\" where \"vars X \\<equiv> (\\<Union>U \\<in> Rep_Exp X. freevars U)\"\n\nlemma vars_respects: \"freevars respects exprel\"\nby (auto simp add: congruent_def exprel_imp_eq_freevars) \n\ntext\\<open>The extension of the function \\<^term>\\<open>vars\\<close> to lists\\<close>\nprimrec vars_list :: \"exp list \\<Rightarrow> nat set\" where\n  \"vars_list []    = {}\"\n| \"vars_list(E#Es) = vars E \\<union> vars_list Es\"\n\n\ntext\\<open>Now prove the three equations for \\<^term>\\<open>vars\\<close>\\<close>\n\nlemma vars_Variable [simp]: \"vars (Var N) = {N}\"\nby (simp add: vars_def Var_def \n              UN_equiv_class [OF equiv_exprel vars_respects]) \n \nlemma vars_Plus [simp]: \"vars (Plus X Y) = vars X \\<union> vars Y\"\nproof -\n  have \"\\<And>U V. \\<lbrakk>X = Abs_Exp (exprel``{U}); Y = Abs_Exp (exprel``{V})\\<rbrakk>\n               \\<Longrightarrow> vars (Plus X Y) = vars X \\<union> vars Y\"\n    by (simp add: vars_def Plus UN_equiv_class [OF equiv_exprel vars_respects]) \n  then show ?thesis\n    by (meson eq_Abs_Exp)\nqed\n\nlemma vars_FnCall [simp]: \"vars (FnCall F Xs) = vars_list Xs\"\nproof -\n  have \"vars (Abs_Exp (exprel``{FNCALL F Us})) = vars_list (Abs_ExpList Us)\" for Us\n    by (induct Us) (auto simp: vars_def UN_equiv_class [OF equiv_exprel vars_respects])\n  then show ?thesis\n    by (metis ExpList_rep FnCall)\nqed\n\nlemma vars_FnCall_Nil: \"vars (FnCall F Nil) = {}\" \n  by simp\n\nlemma vars_FnCall_Cons: \"vars (FnCall F (X#Xs)) = vars X \\<union> vars_list Xs\"\n  by simp\n\n\nsubsection\\<open>Injectivity Properties of Some Constructors\\<close>\n\nlemma VAR_imp_eq: \"VAR m \\<sim> VAR n \\<Longrightarrow> m = n\"\n  by (drule exprel_imp_eq_freevars, simp)\n\ntext\\<open>Can also be proved using the function \\<^term>\\<open>vars\\<close>\\<close>\nlemma Var_Var_eq [iff]: \"(Var m = Var n) = (m = n)\"\n  by (auto simp add: Var_def exprel_refl dest: VAR_imp_eq)\n\nlemma VAR_neqv_PLUS: \"VAR m \\<sim> PLUS X Y \\<Longrightarrow> False\"\n  using exprel_imp_eq_freediscrim by force\n\ntheorem Var_neq_Plus [iff]: \"Var N \\<noteq> Plus X Y\"\nproof -\n  have \"\\<And>U V. \\<lbrakk>X = Abs_Exp (exprel``{U}); Y = Abs_Exp (exprel``{V})\\<rbrakk> \\<Longrightarrow> Var N \\<noteq> Plus X Y\"\n    using Plus VAR_neqv_PLUS Var_def by force\n  then show ?thesis\n    by (meson eq_Abs_Exp)\nqed\n\ntheorem Var_neq_FnCall [iff]: \"Var N \\<noteq> FnCall F Xs\"\nproof -\n  have \"\\<And>Us. Var N \\<noteq> FnCall F (Abs_ExpList Us)\"\n    using FnCall Var_def exprel_imp_eq_freediscrim by fastforce\n  then show ?thesis\n    by (metis ExpList_rep)\nqed\n\nsubsection\\<open>Injectivity of \\<^term>\\<open>FnCall\\<close>\\<close>\n\ndefinition\n  \"fun\" :: \"exp \\<Rightarrow> nat\"\n  where \"fun X \\<equiv> the_elem (\\<Union>U \\<in> Rep_Exp X. {freefun U})\"\n\nlemma fun_respects: \"(\\<lambda>U. {freefun U}) respects exprel\"\n  by (auto simp add: congruent_def exprel_imp_eq_freefun) \n\nlemma fun_FnCall [simp]: \"fun (FnCall F Xs) = F\"\nproof -\n  have \"\\<And>Us. fun (FnCall F (Abs_ExpList Us)) = F\"\n    using FnCall UN_equiv_class [OF equiv_exprel] fun_def fun_respects by fastforce\n  then show ?thesis\n    by (metis ExpList_rep)\nqed\n\ndefinition\n  args :: \"exp \\<Rightarrow> exp list\" where\n  \"args X = the_elem (\\<Union>U \\<in> Rep_Exp X. {Abs_ExpList (freeargs U)})\"\n\ntext\\<open>This result can probably be generalized to arbitrary equivalence\nrelations, but with little benefit here.\\<close>\nlemma Abs_ExpList_eq:\n     \"(y, z) \\<in> listrel exprel \\<Longrightarrow> Abs_ExpList (y) = Abs_ExpList (z)\"\n  by (induct set: listrel) simp_all\n\nlemma args_respects: \"(\\<lambda>U. {Abs_ExpList (freeargs U)}) respects exprel\"\n  by (auto simp add: congruent_def Abs_ExpList_eq exprel_imp_eqv_freeargs) \n\nlemma args_FnCall [simp]: \"args (FnCall F Xs) = Xs\"\nproof -\n  have \"\\<And>Us. Xs = Abs_ExpList Us \\<Longrightarrow> args (FnCall F Xs) = Xs\"\n    by (simp add: FnCall args_def UN_equiv_class [OF equiv_exprel args_respects])\n  then show ?thesis\n    by (metis ExpList_rep)\nqed\n\nlemma FnCall_FnCall_eq [iff]: \"(FnCall F Xs = FnCall F' Xs') \\<longleftrightarrow> (F=F' \\<and> Xs=Xs')\"\n  by (metis args_FnCall fun_FnCall) \n\n\nsubsection\\<open>The Abstract Discriminator\\<close>\ntext\\<open>However, as \\<open>FnCall_Var_neq_Var\\<close> illustrates, we don't need this\nfunction in order to prove discrimination theorems.\\<close>\n\ndefinition\n  discrim :: \"exp \\<Rightarrow> int\" where\n  \"discrim X = the_elem (\\<Union>U \\<in> Rep_Exp X. {freediscrim U})\"\n\nlemma discrim_respects: \"(\\<lambda>U. {freediscrim U}) respects exprel\"\nby (auto simp add: congruent_def exprel_imp_eq_freediscrim) \n\ntext\\<open>Now prove the four equations for \\<^term>\\<open>discrim\\<close>\\<close>\n\nlemma discrim_Var [simp]: \"discrim (Var N) = 0\"\n  by (simp add: discrim_def Var_def UN_equiv_class [OF equiv_exprel discrim_respects]) \n\nlemma discrim_Plus [simp]: \"discrim (Plus X Y) = 1\"\nproof -\n  have \"\\<And>U V. \\<lbrakk>X = Abs_Exp (exprel``{U}); Y = Abs_Exp (exprel``{V})\\<rbrakk> \\<Longrightarrow> discrim (Plus X Y) = 1\"\n    by (simp add: discrim_def Plus  UN_equiv_class [OF equiv_exprel discrim_respects]) \n  then show ?thesis\n    by (meson eq_Abs_Exp)\nqed\n\nlemma discrim_FnCall [simp]: \"discrim (FnCall F Xs) = 2\"\nproof -\n  have \"discrim (FnCall F (Abs_ExpList Us)) = 2\" for Us\n    by (simp add: discrim_def FnCall UN_equiv_class [OF equiv_exprel discrim_respects]) \n  then show ?thesis\n    by (metis ExpList_rep)\nqed\n\ntext\\<open>The structural induction rule for the abstract type\\<close>\ntheorem exp_inducts:\n  assumes V:    \"\\<And>nat. P1 (Var nat)\"\n      and P:    \"\\<And>exp1 exp2. \\<lbrakk>P1 exp1; P1 exp2\\<rbrakk> \\<Longrightarrow> P1 (Plus exp1 exp2)\"\n      and F:    \"\\<And>nat list. P2 list \\<Longrightarrow> P1 (FnCall nat list)\"\n      and Nil:  \"P2 []\"\n      and Cons: \"\\<And>exp list. \\<lbrakk>P1 exp; P2 list\\<rbrakk> \\<Longrightarrow> P2 (exp # list)\"\n  shows \"P1 exp\" and \"P2 list\"\nproof -\n  obtain U where exp: \"exp = (Abs_Exp (exprel``{U}))\" by (cases exp)\n  obtain Us where list: \"list = Abs_ExpList Us\" by (metis ExpList_rep)\n  have \"P1 (Abs_Exp (exprel``{U}))\" and \"P2 (Abs_ExpList Us)\"\n  proof (induct U and Us rule: compat_freeExp.induct compat_freeExp_list.induct)\n    case (VAR nat)\n    with V show ?case by (simp add: Var_def) \n  next\n    case (PLUS X Y)\n    with P [of \"Abs_Exp (exprel``{X})\" \"Abs_Exp (exprel``{Y})\"]\n    show ?case by (simp add: Plus) \n  next\n    case (FNCALL nat list)\n    with F [of \"Abs_ExpList list\"]\n    show ?case by (simp add: FnCall) \n  next\n    case Nil_freeExp\n    with Nil show ?case by simp\n  next\n    case Cons_freeExp\n    with Cons show ?case by simp\n  qed\n  with exp and list show \"P1 exp\" and \"P2 list\" by (simp_all only:)\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/Induct/QuoNestedDataType.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8418256631249077, "lm_q2_score": 0.8670357512127872, "lm_q1q2_score": 0.7298929462177071}}
{"text": "(* Title:  Rtrancl_On.thy\n   Author: Lars Noschinski, TU M\u00fcnchen\n   Author: Ren\u00e9 Neumann, TU M\u00fcnchen\n*)\n\ntheory Rtrancl_On\nimports Main\nbegin\n\nsection {* Reflexive-Transitive Closure on a Domain *}\n\ntext {*\n  In this section we introduce a variant of the reflexive-transitive closure\n  of a relation which is useful to formalize the reachability relation on\n  digraphs.\n*}\n\ninductive_set\n  rtrancl_on :: \"'a set \\<Rightarrow> 'a rel \\<Rightarrow> 'a rel\"\n  for F :: \"'a set\" and r :: \"'a rel\"\nwhere\n    rtrancl_on_refl [intro!, Pure.intro!, simp]: \"a \\<in> F \\<Longrightarrow> (a, a) \\<in> rtrancl_on F r\"\n  | rtrancl_on_into_rtrancl_on [Pure.intro]:\n      \"(a, b) \\<in> rtrancl_on F r  \\<Longrightarrow> (b, c) \\<in> r \\<Longrightarrow> c \\<in> F\n      \\<Longrightarrow> (a, c) \\<in> rtrancl_on F r\"\n\ndefinition symcl :: \"'a rel \\<Rightarrow> 'a rel\" (\"(_\\<^sup>s)\" [1000] 999) where\n  \"symcl R = R \\<union> (\\<lambda>(a,b). (b,a)) ` R\"\n\nlemma in_rtrancl_on_in_F:\n  assumes \"(a,b) \\<in> rtrancl_on F r\" shows \"a \\<in> F\" \"b \\<in> F\"\n  using assms by induct auto\n\nlemma rtrancl_on_induct[consumes 1, case_names base step, induct set: rtrancl_on]:\n  assumes \"(a, b) \\<in> rtrancl_on F r\"\n    and \"a \\<in> F \\<Longrightarrow> P a\"\n        \"\\<And>y z. \\<lbrakk>(a, y) \\<in> rtrancl_on F r; (y,z) \\<in> r; y \\<in> F; z \\<in> F; P y\\<rbrakk> \\<Longrightarrow> P z\"\n  shows \"P b\"\n  using assms by (induct a b) (auto dest: in_rtrancl_on_in_F)\n\nlemma rtrancl_on_trans:\n  assumes \"(a,b) \\<in> rtrancl_on F r\" \"(b,c) \\<in> rtrancl_on F r\" shows \"(a,c) \\<in> rtrancl_on F r\"\n  using assms(2,1)\n  by induct (auto intro: rtrancl_on_into_rtrancl_on)\n\nlemma converse_rtrancl_on_into_rtrancl_on:\n  assumes \"(a,b) \\<in> r\" \"(b, c) \\<in> rtrancl_on F r\" \"a \\<in> F\" \"b \\<in> F\"\n  shows \"(a, c) \\<in> rtrancl_on F r\"\n  apply (rule rtrancl_on_trans)\n  apply (rule rtrancl_on_into_rtrancl_on)\n  apply (rule rtrancl_on_refl)\n  by fact+\n\ntheorem rtrancl_on_converseI:\n  assumes \"(y, x) \\<in> rtrancl_on F r\" shows \"(x, y) \\<in> rtrancl_on F (r\\<inverse>)\"\n  using assms\nproof induct\n  case (step a b)\n  then have \"(b,b) \\<in> rtrancl_on F (r\\<inverse>)\" \"(b,a) \\<in> r\\<inverse>\" by auto\n  then show ?case using step\n    by (metis rtrancl_on_trans rtrancl_on_into_rtrancl_on)\nqed auto\n\ntheorem rtrancl_on_converseD:\n  assumes \"(y, x) \\<in> rtrancl_on F (r\\<inverse>)\" shows \"(x, y) \\<in> rtrancl_on F r\"\n  using assms by - (drule rtrancl_on_converseI, simp)\n\nlemma converse_rtrancl_on_induct[consumes 1, case_names base step, induct set: rtrancl_on]:\n  assumes major: \"(a, b) \\<in> rtrancl_on F r\"\n    and cases: \"b \\<in> F \\<Longrightarrow> P b\"\n       \"\\<And>x y. \\<lbrakk>(x,y) \\<in> r; (y,b) \\<in> rtrancl_on F r; x \\<in> F; y \\<in> F; P y\\<rbrakk> \\<Longrightarrow> P x\"\n  shows \"P a\"\n  using rtrancl_on_converseI[OF major] cases\n  by induct (auto intro: rtrancl_on_converseD)\n\nlemma rtrancl_on_sym:\n  assumes \"sym r\" shows \"sym (rtrancl_on F r)\"\nusing assms by (auto simp: sym_conv_converse_eq intro: symI dest: rtrancl_on_converseI)\n\nlemma rtrancl_on_mono:\n  assumes \"s \\<subseteq> r\" \"F \\<subseteq> G\" \"(a,b) \\<in> rtrancl_on F s\" shows \"(a,b) \\<in> rtrancl_on G r\"\n  using assms(3,1,2)\nproof induct\n  case (step x y) show ?case\n    using step assms by (intro converse_rtrancl_on_into_rtrancl_on[OF _ step(5)]) auto\nqed auto\n\nlemma rtrancl_consistent_rtrancl_on:\n  assumes \"(a,b) \\<in> r\\<^sup>*\"\n  and \"a \\<in> F\" \"b \\<in> F\"\n  and consistent: \"\\<And>a b. \\<lbrakk> a \\<in> F; (a,b) \\<in> r \\<rbrakk> \\<Longrightarrow> b \\<in> F\"\n  shows \"(a,b) \\<in> rtrancl_on F r\"\n  using assms(1-3)\nproof (induction rule: converse_rtrancl_induct)\n  case (step y z) then have \"z \\<in> F\" by (rule_tac consistent) simp\n  with step have \"(z,b) \\<in> rtrancl_on F r\" by simp\n  with step.prems `(y,z) \\<in> r` `z \\<in> F` show ?case\n    using converse_rtrancl_on_into_rtrancl_on\n    by metis\nqed simp\n\nlemma rtrancl_on_rtranclI:\n  \"(a,b) \\<in> rtrancl_on F r \\<Longrightarrow> (a,b) \\<in> r\\<^sup>*\"\n  by (induct rule: rtrancl_on_induct) simp_all\n\nlemma rtrancl_on_sub_rtrancl:\n  \"rtrancl_on F r \\<subseteq> r^*\"\n  using rtrancl_on_rtranclI\n  by auto\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/Graph_Theory/Rtrancl_On.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8418256591565729, "lm_q2_score": 0.8670357546485407, "lm_q1q2_score": 0.7298929456693244}}
{"text": "(*\n  Authors: Asta Halkj\u00e6r From & J\u00f8rgen Villadsen, DTU Compute\n*)\n\nsection \\<open>Formalization of \u0141ukasiewicz's Axiom System from 1924 for Classical Propositional Logic\\<close>\n\nsubsection \\<open>Syntax, Semantics and Axiom System\\<close>\n\ntheory Implicational_Logic_Appendix imports Main begin\n\ndatatype form =\n  Pro nat (\\<open>\\<cdot>\\<close>) |\n  Neg form (\\<open>\\<sim>\\<close>) |\n  Imp form form (infixr \\<open>\\<rightarrow>\\<close> 55)\n\nprimrec semantics (infix \\<open>\\<Turnstile>\\<close> 50) where\n  \\<open>I \\<Turnstile> \\<cdot> n = I n\\<close> |\n  \\<open>I \\<Turnstile> \\<sim> p = (\\<not> I \\<Turnstile> p)\\<close> |\n  \\<open>I \\<Turnstile> p \\<rightarrow> q = (I \\<Turnstile> p \\<longrightarrow> I \\<Turnstile> q)\\<close>\n\ninductive Ax (\\<open>\\<turnstile> _\\<close> 50) where\n  01: \\<open>\\<turnstile> (p \\<rightarrow> q) \\<rightarrow> (q \\<rightarrow> r) \\<rightarrow> p \\<rightarrow> r\\<close> |\n  02: \\<open>\\<turnstile> (\\<sim> p \\<rightarrow> p) \\<rightarrow> p\\<close> |\n  03: \\<open>\\<turnstile> p \\<rightarrow> \\<sim> p \\<rightarrow> q\\<close> |\n  MP: \\<open>\\<turnstile> p \\<rightarrow> q \\<Longrightarrow> \\<turnstile> p \\<Longrightarrow> \\<turnstile> q\\<close>\n\nsubsection \\<open>Soundness and Derived Formulas\\<close>\n\ntheorem soundness: \\<open>\\<turnstile> p \\<Longrightarrow> I \\<Turnstile> p\\<close>\n  by (induct p rule: Ax.induct) simp_all\n\nlemma 04: \\<open>\\<turnstile> (((q \\<rightarrow> r) \\<rightarrow> p \\<rightarrow> r) \\<rightarrow> s) \\<rightarrow> (p \\<rightarrow> q) \\<rightarrow> s\\<close>\n  using MP 01 01 .\n\nlemma 05: \\<open>\\<turnstile> (p \\<rightarrow> q \\<rightarrow> r) \\<rightarrow> (s \\<rightarrow> q) \\<rightarrow> p \\<rightarrow> s \\<rightarrow> r\\<close>\n  using MP 04 04 .\n\nlemma 06: \\<open>\\<turnstile> (p \\<rightarrow> q) \\<rightarrow> ((p \\<rightarrow> r) \\<rightarrow> s) \\<rightarrow> (q \\<rightarrow> r) \\<rightarrow> s\\<close>\n  using MP 04 01 .\n\nlemma 07: \\<open>\\<turnstile> (t \\<rightarrow> (p \\<rightarrow> r) \\<rightarrow> s) \\<rightarrow> (p \\<rightarrow> q) \\<rightarrow> t \\<rightarrow> (q \\<rightarrow> r) \\<rightarrow> s\\<close>\n  using MP 05 06 .\n\nlemma 09: \\<open>\\<turnstile> ((\\<sim> p \\<rightarrow> q) \\<rightarrow> r) \\<rightarrow> p \\<rightarrow> r\\<close>\n  using MP 01 03 .\n\nlemma 10: \\<open>\\<turnstile> p \\<rightarrow> ((\\<sim> p \\<rightarrow> p) \\<rightarrow> p) \\<rightarrow> (q \\<rightarrow> p) \\<rightarrow> p\\<close>\n  using MP 09 06 .\n\nlemma 11: \\<open>\\<turnstile> (q \\<rightarrow> (\\<sim> p \\<rightarrow> p) \\<rightarrow> p) \\<rightarrow> (\\<sim> p \\<rightarrow> p) \\<rightarrow> p\\<close>\n  using MP MP 10 02 02 .\n\nlemma 12: \\<open>\\<turnstile> t \\<rightarrow> (\\<sim> p \\<rightarrow> p) \\<rightarrow> p\\<close>\n  using MP 09 11 .\n\nlemma 13: \\<open>\\<turnstile> (\\<sim> p \\<rightarrow> q) \\<rightarrow> t \\<rightarrow> (q \\<rightarrow> p) \\<rightarrow> p\\<close>\n  using MP 07 12 .\n\nlemma 14: \\<open>\\<turnstile> ((t \\<rightarrow> (q \\<rightarrow> p) \\<rightarrow> p) \\<rightarrow> r) \\<rightarrow> (\\<sim> p \\<rightarrow> q) \\<rightarrow> r\\<close>\n  using MP 01 13 .\n\nlemma 15: \\<open>\\<turnstile> (\\<sim> p \\<rightarrow> q) \\<rightarrow> (q \\<rightarrow> p) \\<rightarrow> p\\<close>\n  using MP 14 02 .\n\nlemma 16: \\<open>\\<turnstile> p \\<rightarrow> p\\<close>\n  using MP 09 02 .\n\nlemma 17: \\<open>\\<turnstile> p \\<rightarrow> (q \\<rightarrow> p) \\<rightarrow> p\\<close>\n  using MP 09 15 .\n\nlemma 18: \\<open>\\<turnstile> q \\<rightarrow> p \\<rightarrow> q\\<close>\n  using MP MP 05 17 03 .\n\nlemma 19: \\<open>\\<turnstile> ((p \\<rightarrow> q) \\<rightarrow> r) \\<rightarrow> q \\<rightarrow> r\\<close>\n  using MP 01 18 .\n\nlemma 20: \\<open>\\<turnstile> p \\<rightarrow> (p \\<rightarrow> q) \\<rightarrow> q\\<close>\n  using MP 19 15 .\n\nlemma 21: \\<open>\\<turnstile> (p \\<rightarrow> q \\<rightarrow> r) \\<rightarrow> q \\<rightarrow> p \\<rightarrow> r\\<close>\n  using MP 05 20 .\n\nlemma 22: \\<open>\\<turnstile> (q \\<rightarrow> r) \\<rightarrow> (p \\<rightarrow> q) \\<rightarrow> p \\<rightarrow> r\\<close>\n  using MP 21 01 .\n\nlemma 23: \\<open>\\<turnstile> ((q \\<rightarrow> p \\<rightarrow> r) \\<rightarrow> s) \\<rightarrow> (p \\<rightarrow> q \\<rightarrow> r) \\<rightarrow> s\\<close>\n  using MP 01 21 .\n\nlemma 24: \\<open>\\<turnstile> ((p \\<rightarrow> q) \\<rightarrow> p) \\<rightarrow> p\\<close>\n  using MP MP 23 15 03 .\n\nlemma 25: \\<open>\\<turnstile> ((p \\<rightarrow> r) \\<rightarrow> s) \\<rightarrow> (p \\<rightarrow> q) \\<rightarrow> (q \\<rightarrow> r) \\<rightarrow> s\\<close>\n  using MP 21 06 .\n\nlemma 26: \\<open>\\<turnstile> ((p \\<rightarrow> q) \\<rightarrow> r) \\<rightarrow> (r \\<rightarrow> p) \\<rightarrow> p\\<close>\n  using MP 25 24 .\n\nlemma 28: \\<open>\\<turnstile> (((r \\<rightarrow> p) \\<rightarrow> p) \\<rightarrow> s) \\<rightarrow> ((p \\<rightarrow> q) \\<rightarrow> r) \\<rightarrow> s\\<close>\n  using MP 01 26 .\n\nlemma 29: \\<open>\\<turnstile> ((p \\<rightarrow> q) \\<rightarrow> r) \\<rightarrow> (p \\<rightarrow> r) \\<rightarrow> r\\<close>\n  using MP 28 26 .\n\nlemma 31: \\<open>\\<turnstile> (p \\<rightarrow> s) \\<rightarrow> ((p \\<rightarrow> q) \\<rightarrow> r) \\<rightarrow> (s \\<rightarrow> r) \\<rightarrow> r\\<close>\n  using MP 07 29 .\n\nlemma 32: \\<open>\\<turnstile> ((p \\<rightarrow> q) \\<rightarrow> r) \\<rightarrow> (p \\<rightarrow> s) \\<rightarrow> (s \\<rightarrow> r) \\<rightarrow> r\\<close>\n  using MP 21 31 .\n\nlemma 33: \\<open>\\<turnstile> (p \\<rightarrow> s) \\<rightarrow> (s \\<rightarrow> q \\<rightarrow> p \\<rightarrow> r) \\<rightarrow> q \\<rightarrow> p \\<rightarrow> r\\<close>\n  using MP 32 18 .\n\nlemma 34: \\<open>\\<turnstile> (s \\<rightarrow> q \\<rightarrow> p \\<rightarrow> r) \\<rightarrow> (p \\<rightarrow> s) \\<rightarrow> q \\<rightarrow> p \\<rightarrow> r\\<close>\n  using MP 21 33 .\n\nlemma 35: \\<open>\\<turnstile> (p \\<rightarrow> q \\<rightarrow> r) \\<rightarrow> (p \\<rightarrow> q) \\<rightarrow> p \\<rightarrow> r\\<close>\n  using MP 34 22 .\n\nlemma 36: \\<open>\\<turnstile> \\<sim> p \\<rightarrow> p \\<rightarrow> q\\<close>\n  using MP 21 03 .\n\nlemmas\n  Tran = 01 and\n  Clavius = 02 and\n  Expl = 03 and\n  Frege' = 05 and\n  Clavius' = 15 and\n  Id = 16 and\n  Simp = 18 and\n  Swap = 21 and\n  Tran' = 22 and\n  Peirce = 24 and\n  Frege = 35 and\n  Expl' = 36\n\nlemma Neg1: \\<open>\\<turnstile> (q \\<rightarrow> s) \\<rightarrow> (\\<sim> q \\<rightarrow> s) \\<rightarrow> s\\<close>\n  using MP Clavius' Expl' Frege' Swap by meson\n\nlemma Neg2: \\<open>\\<turnstile> ((q \\<rightarrow> s) \\<rightarrow> s) \\<rightarrow> \\<sim> q \\<rightarrow> s\\<close>\n  using MP Tran MP Swap Expl .\n\nlemma Imp1: \\<open>\\<turnstile> (q \\<rightarrow> s) \\<rightarrow> ((q \\<rightarrow> r) \\<rightarrow> s) \\<rightarrow> s\\<close>\n  using MP Peirce Tran Tran' by meson\n\nlemma Imp2: \\<open>\\<turnstile> ((r \\<rightarrow> s) \\<rightarrow> s) \\<rightarrow> ((q \\<rightarrow> r) \\<rightarrow> s) \\<rightarrow> s\\<close>\n  using MP Tran MP Tran Simp .\n\nlemma Imp3: \\<open>\\<turnstile> ((q \\<rightarrow> s) \\<rightarrow> s) \\<rightarrow> (r \\<rightarrow> s) \\<rightarrow> (q \\<rightarrow> r) \\<rightarrow> s\\<close>\n  using MP Swap Tran by meson\n\nsubsection \\<open>Completeness and Main Theorem\\<close>\n\nprimrec pros where\n  \\<open>pros (\\<cdot> n) = [n]\\<close> |\n  \\<open>pros (\\<sim> p) = pros p\\<close> |\n  \\<open>pros (p \\<rightarrow> q) = remdups (pros p @ pros q)\\<close>\n\nlemma distinct_pros: \\<open>distinct (pros p)\\<close>\n  by (induct p) simp_all\n\nprimrec imply (infixr \\<open>\\<leadsto>\\<close> 56) where\n  \\<open>[] \\<leadsto> q = q\\<close> |\n  \\<open>p # ps \\<leadsto> q = p \\<rightarrow> ps \\<leadsto> q\\<close>\n\nlemma imply_append: \\<open>ps @ qs \\<leadsto> r = ps \\<leadsto> qs \\<leadsto> r\\<close>\n  by (induct ps) simp_all\n\nabbreviation Ax_assms (infix \\<open>\\<turnstile>\\<close> 50) where \\<open>ps \\<turnstile> q \\<equiv> \\<turnstile> ps \\<leadsto> q\\<close>\n\nlemma imply_Cons: \\<open>ps \\<turnstile> q \\<Longrightarrow> p # ps \\<turnstile> q\\<close>\nproof -\n  assume \\<open>ps \\<turnstile> q\\<close>\n  with MP Simp have \\<open>\\<turnstile> p \\<rightarrow> ps \\<leadsto> q\\<close> .\n  then show ?thesis\n    by simp\nqed\n\nlemma imply_head: \\<open>p # ps \\<turnstile> p\\<close>\n  by (induct ps) (use MP Frege Simp imply.simps in metis)+\n\nlemma imply_mem: \\<open>p \\<in> set ps \\<Longrightarrow> ps \\<turnstile> p\\<close>\n  by (induct ps) (use imply_Cons imply_head in auto)\n\nlemma imply_MP: \\<open>\\<turnstile> ps \\<leadsto> (p \\<rightarrow> q) \\<rightarrow> ps \\<leadsto> p \\<rightarrow> ps \\<leadsto> q\\<close>\nproof (induct ps)\n  case (Cons r ps)\n  then have \\<open>\\<turnstile> (r \\<rightarrow> ps \\<leadsto> (p \\<rightarrow> q)) \\<rightarrow> (r \\<rightarrow> ps \\<leadsto> p) \\<rightarrow> r \\<rightarrow> ps \\<leadsto> q\\<close>\n    using MP Frege Simp by meson\n  then show ?case\n    by simp\nqed (auto intro: Id)\n\nlemma MP': \\<open>ps \\<turnstile> p \\<rightarrow> q \\<Longrightarrow> ps \\<turnstile> p \\<Longrightarrow> ps \\<turnstile> q\\<close>\n  using MP imply_MP by metis\n\nlemma imply_swap_append: \\<open>ps @ qs \\<turnstile> r \\<Longrightarrow> qs @ ps \\<turnstile> r\\<close>\n  by (induct qs arbitrary: ps) (simp, metis MP' imply_append imply_Cons imply_head imply.simps(2))\n\nlemma imply_deduct: \\<open>p # ps \\<turnstile> q \\<Longrightarrow> ps \\<turnstile> p \\<rightarrow> q\\<close>\n  using imply_append imply_swap_append imply.simps by metis\n\nlemma add_imply [simp]: \\<open>\\<turnstile> p \\<Longrightarrow> ps \\<turnstile> p\\<close>\nproof -\n  note MP\n  moreover have \\<open>\\<turnstile> p \\<rightarrow> ps \\<leadsto> p\\<close>\n    using imply_head by simp\n  moreover assume \\<open>\\<turnstile> p\\<close>\n  ultimately show ?thesis .\nqed\n\nlemma imply_weaken: \\<open>ps \\<turnstile> p \\<Longrightarrow> set ps \\<subseteq> set ps' \\<Longrightarrow> ps' \\<turnstile> p\\<close>\n  by (induct ps arbitrary: p) (simp, metis MP' imply_deduct imply_mem insert_subset list.set(2))\n\nabbreviation \\<open>lift t s p \\<equiv> if t then (p \\<rightarrow> s) \\<rightarrow> s else p \\<rightarrow> s\\<close>\n\nabbreviation \\<open>lifts I s \\<equiv> map (\\<lambda>n. lift (I n) s (\\<cdot> n))\\<close>\n\nlemma lifts_weaken: \\<open>lifts I s l \\<turnstile> p \\<Longrightarrow> set l \\<subseteq> set l' \\<Longrightarrow> lifts I s l' \\<turnstile> p\\<close>\n  using imply_weaken by (metis (no_types, lifting) image_mono set_map)\n\nlemma lifts_pros_lift: \\<open>lifts I s (pros p) \\<turnstile> lift (I \\<Turnstile> p) s p\\<close>\nproof (induct p)\n  case (Neg q)\n  consider \\<open>\\<not> I \\<Turnstile> q\\<close> | \\<open>I \\<Turnstile> q\\<close>\n    by blast\n  then show ?case\n  proof cases\n    case 1\n    then have \\<open>lifts I s (pros (\\<sim> q)) \\<turnstile> q \\<rightarrow> s\\<close>\n      using Neg by simp\n    then have \\<open>lifts I s (pros (\\<sim> q)) \\<turnstile> (\\<sim> q \\<rightarrow> s) \\<rightarrow> s\\<close>\n      using MP' Neg1 add_imply by blast\n    with 1 show ?thesis\n      by simp\n  next\n    case 2\n    then have \\<open>lifts I s (pros (\\<sim> q)) \\<turnstile> (q \\<rightarrow> s) \\<rightarrow> s\\<close>\n      using Neg by simp\n    then have \\<open>lifts I s (pros (\\<sim> q)) \\<turnstile> \\<sim> q \\<rightarrow> s\\<close>\n      using MP' Neg2 add_imply by blast\n    with 2 show ?thesis\n      by simp\n  qed\nnext\n  case (Imp q r)\n  consider \\<open>\\<not> I \\<Turnstile> q\\<close> | \\<open>I \\<Turnstile> r\\<close> | \\<open>I \\<Turnstile> q\\<close> \\<open>\\<not> I \\<Turnstile> r\\<close>\n    by blast\n  then show ?case\n  proof cases\n    case 1\n    then have \\<open>lifts I s (pros (q \\<rightarrow> r)) \\<turnstile> q \\<rightarrow> s\\<close>\n      using Imp(1) lifts_weaken[where l' = \\<open>pros (q \\<rightarrow> r)\\<close>] by simp\n    then have \\<open>lifts I s (pros (q \\<rightarrow> r)) \\<turnstile> ((q \\<rightarrow> r) \\<rightarrow> s) \\<rightarrow> s\\<close>\n      using Imp1 MP' add_imply by blast\n    with 1 show ?thesis\n      by simp\n  next\n    case 2\n    then have \\<open>lifts I s (pros (q \\<rightarrow> r)) \\<turnstile> (r \\<rightarrow> s) \\<rightarrow> s\\<close>\n      using Imp(2) lifts_weaken[where l' = \\<open>pros (q \\<rightarrow> r)\\<close>] by simp\n    then have \\<open>lifts I s (pros (q \\<rightarrow> r)) \\<turnstile> ((q \\<rightarrow> r) \\<rightarrow> s) \\<rightarrow> s\\<close>\n      using Imp2 MP' add_imply by blast\n    with 2 show ?thesis\n      by simp\n  next\n    case 3\n    then have \\<open>lifts I s (pros (q \\<rightarrow> r)) \\<turnstile> (q \\<rightarrow> s) \\<rightarrow> s\\<close> \\<open>lifts I s (pros (q \\<rightarrow> r)) \\<turnstile> r \\<rightarrow> s\\<close>\n      using Imp lifts_weaken[where l' = \\<open>pros (q \\<rightarrow> r)\\<close>] by simp_all\n    then have \\<open>lifts I s (pros (q \\<rightarrow> r)) \\<turnstile> (q \\<rightarrow> r) \\<rightarrow> s\\<close>\n      using Imp3 MP' add_imply by blast\n    with 3 show ?thesis\n      by simp\n  qed\nqed (auto intro: Id)\n\nlemma lifts_pros: \\<open>I \\<Turnstile> p \\<Longrightarrow> lifts I p (pros p) \\<turnstile> p\\<close>\nproof -\n  assume \\<open>I \\<Turnstile> p\\<close>\n  then have \\<open>lifts I p (pros p) \\<turnstile> (p \\<rightarrow> p) \\<rightarrow> p\\<close>\n    using lifts_pros_lift[of I p p] by simp\n  then show ?thesis\n    using Id MP' add_imply by blast\nqed\n\ntheorem completeness: \\<open>\\<forall>I. I \\<Turnstile> p \\<Longrightarrow> \\<turnstile> p\\<close>\nproof -\n  let ?A = \\<open>\\<lambda>l I. lifts I p l \\<turnstile> p\\<close>\n  let ?B = \\<open>\\<lambda>l. \\<forall>I. ?A l I \\<and> distinct l\\<close>\n  assume \\<open>\\<forall>I. I \\<Turnstile> p\\<close>\n  moreover have \\<open>?B l \\<Longrightarrow> (\\<And>n l. ?B (n # l) \\<Longrightarrow> ?B l) \\<Longrightarrow> ?B []\\<close> for l\n    by (induct l) blast+\n  moreover have \\<open>?B (n # l) \\<Longrightarrow> ?B l\\<close> for n l\n  proof -\n    assume *: \\<open>?B (n # l)\\<close>\n    show \\<open>?B l\\<close>\n    proof\n      fix I\n      from * have \\<open>?A (n # l) (I(n := True))\\<close> \\<open>?A (n # l) (I(n := False))\\<close>\n        by blast+\n      moreover from * have \\<open>\\<forall>m \\<in> set l. \\<forall>t. (I(n := t)) m = I m\\<close>\n        by simp\n      ultimately have \\<open>((\\<cdot> n \\<rightarrow> p) \\<rightarrow> p) # lifts I p l \\<turnstile> p\\<close> \\<open>(\\<cdot> n \\<rightarrow> p) # lifts I p l \\<turnstile> p\\<close>\n        by (simp_all cong: map_cong)\n      then have \\<open>?A l I\\<close>\n        using MP' imply_deduct by blast\n      moreover from * have \\<open>distinct (n # l)\\<close>\n        by blast\n      ultimately show \\<open>?A l I \\<and> distinct l\\<close>\n        by simp\n    qed\n  qed\n  ultimately have \\<open>?B []\\<close>\n    using lifts_pros distinct_pros by blast\n  then show ?thesis\n    by simp\nqed\n\ntheorem main: \\<open>(\\<turnstile> p) = (\\<forall>I. I \\<Turnstile> p)\\<close>\n  using soundness completeness by blast\n\nsubsection \\<open>Reference\\<close>\n\ntext \\<open>Numbered lemmas are from Jan \u0141ukasiewicz: Elements of Mathematical Logic (English Tr. 1963)\\<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/Implicational_Logic/Implicational_Logic_Appendix.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357666736772, "lm_q2_score": 0.8418256472515683, "lm_q1q2_score": 0.729892945470328}}
{"text": "(*  Title:      Additional Facts about Subgroups and Normal Subgroups\n    Author:     Jakob von Raumer, Karlsruhe Institute of Technology\n    Maintainer: Jakob von Raumer <jakob.raumer@student.kit.edu>\n*)\n\ntheory SubgroupsAndNormalSubgroups\n  imports\n  Secondary_Sylow.SndSylow\n  SndIsomorphismGrp\n  \"HOL-Algebra.Coset\"\nbegin\n\nsection \\<open>Preliminary lemmas\\<close>\n\ntext \\<open>A group of order 1 is always the trivial group.\\<close>\n\n\nlemma (in group) order_one_triv_iff:\n  shows \"(order G = 1) = (carrier G = {\\<one>})\"\nproof\n  assume order:\"order G = 1\"\n  then obtain x where x:\"carrier G = {x}\" unfolding order_def by (auto simp add: card_Suc_eq)\n  hence \"\\<one> = x\" using one_closed by auto\n  with x show \"carrier G = {\\<one>}\" by simp\nnext\n  assume \"carrier G = {\\<one>}\"\n  thus \"order G = 1\" unfolding order_def by auto\nqed\n\nlemma (in group) finite_pos_order:\n  assumes finite:\"finite (carrier G)\"\n  shows \"0 < order G\"\nproof -\n  from one_closed finite show ?thesis unfolding order_def by (metis card_gt_0_iff subgroup_nonempty subgroup_self)\nqed\n\nlemma iso_order_closed:\n  assumes \"\\<phi> \\<in> iso G H\"\n  shows \"order G = order H\"\nusing assms\nunfolding order_def iso_def by (metis (no_types) bij_betw_same_card mem_Collect_eq)\n\nsection \\<open>More Facts about Subgroups\\<close>\n\nlemma (in subgroup) subgroup_of_restricted_group:\n  assumes \"subgroup U (G\\<lparr> carrier := H\\<rparr>)\"\n  shows \"U \\<subseteq> H\"\nusing assms subgroup.subset by force\n\nlemma (in subgroup) subgroup_of_subgroup:\n  assumes \"group G\"\n  assumes \"subgroup U (G\\<lparr> carrier := H\\<rparr>)\"\n  shows \"subgroup U G\"\nproof\n  from assms(2) have \"U \\<subseteq> H\" by (rule subgroup_of_restricted_group)\n  thus \"U \\<subseteq> carrier G\" by (auto simp:subset)\nnext\n  fix x y\n  have a:\"x \\<otimes> y = x \\<otimes>\\<^bsub>G\\<lparr> carrier := H\\<rparr>\\<^esub> y\" by simp\n  assume \"x \\<in> U\" \"y \\<in> U\"\n  with assms a show \" x \\<otimes> y \\<in> U\" by (metis subgroup.m_closed)\nnext\n  have \"\\<one>\\<^bsub>G\\<lparr> carrier := H\\<rparr>\\<^esub> = \\<one>\" by simp\n  with assms show \"\\<one> \\<in> U\" by (metis subgroup.one_closed)\nnext\n  have \"subgroup H G\"..\n  fix x\n  assume \"x \\<in> U\"\n  with assms(2) have \"inv\\<^bsub>G\\<lparr> carrier := H\\<rparr>\\<^esub> x \\<in> U\" by (rule subgroup.m_inv_closed)\n  moreover from assms \\<open>x \\<in> U\\<close> have \"x \\<in> H\" by (metis in_mono subgroup_of_restricted_group)\n  with assms(1) \\<open>subgroup H G\\<close> have \"inv\\<^bsub>G\\<lparr> carrier := H\\<rparr>\\<^esub> x = inv x\" by (rule group.m_inv_consistent)\n  ultimately show \"inv x \\<in> U\" by simp\nqed\n\ntext \\<open>Being a subgroup is preserved by surjective homomorphisms\\<close>\n\nlemma (in subgroup) surj_hom_subgroup:\n  assumes \\<phi>:\"group_hom G F \\<phi>\"\n  assumes \\<phi>surj:\"\\<phi> ` (carrier G) = carrier F\"\n  shows \"subgroup (\\<phi> ` H) F\"\nproof\n  from \\<phi>surj show img_subset:\"\\<phi> ` H \\<subseteq> carrier F\" unfolding iso_def bij_betw_def by auto\nnext\n  fix f f'\n  assume h:\"f \\<in> \\<phi> ` H\" and h':\"f' \\<in> \\<phi> ` H\"\n  with \\<phi>surj obtain g g' where g:\"g \\<in> H\" \"f = \\<phi> g\" and g':\"g' \\<in> H\" \"f' = \\<phi> g'\" by auto\n  hence \"g \\<otimes>\\<^bsub>G\\<^esub> g' \\<in> H\" by (metis m_closed)\n  hence \"\\<phi> (g \\<otimes>\\<^bsub>G\\<^esub> g') \\<in> \\<phi> ` H\" by simp\n  with g g' \\<phi> show \"f \\<otimes>\\<^bsub>F\\<^esub> f' \\<in> \\<phi> ` H\"  using group_hom.hom_mult by fastforce\nnext\n  have \"\\<phi> \\<one> \\<in> \\<phi> ` H\" by auto\n  with \\<phi> show  \"\\<one>\\<^bsub>F\\<^esub> \\<in> \\<phi> ` H\" by (metis group_hom.hom_one)\nnext\n  fix f\n  assume f:\"f \\<in> \\<phi> ` H\"\n  then obtain g where g:\"g \\<in> H\" \"f = \\<phi> g\" by auto\n  hence \"inv g \\<in> H\" by auto\n  hence \"\\<phi> (inv g) \\<in> \\<phi> ` H\" by auto\n  with \\<phi> g subset show \"inv\\<^bsub>F\\<^esub> f \\<in> \\<phi> ` H\" using group_hom.hom_inv by fastforce\nqed\n\ntext \\<open>... and thus of course by isomorphisms of groups.\\<close>\n\nlemma iso_subgroup:\n  assumes groups:\"group G\" \"group F\"\n  assumes HG:\"subgroup H G\"\n  assumes \\<phi>:\"\\<phi> \\<in> iso G F\"\n  shows \"subgroup (\\<phi> ` H) F\"\nproof -\n  from groups \\<phi> have \"group_hom G F \\<phi>\" unfolding group_hom_def group_hom_axioms_def iso_def by auto\n  moreover from \\<phi> have \"\\<phi> ` (carrier G) = carrier F\" unfolding iso_def bij_betw_def by simp\n  moreover note HG\n  ultimately show ?thesis by (metis subgroup.surj_hom_subgroup)\nqed\n\ntext \\<open>An isomorphism restricts to an isomorphism of subgroups.\\<close>\n\nlemma iso_restrict:\n  assumes groups:\"group G\" \"group F\"\n  assumes HG:\"subgroup H G\"\n  assumes \\<phi>:\"\\<phi> \\<in> iso G F\"\n  shows \"(restrict \\<phi> H) \\<in> iso (G\\<lparr>carrier := H\\<rparr>) (F\\<lparr>carrier := \\<phi> ` H\\<rparr>)\"\nunfolding iso_def hom_def bij_betw_def inj_on_def\nproof auto\n  fix g h\n  assume \"g \\<in> H\" \"h \\<in> H\"\n  hence \"g \\<in> carrier G\" \"h \\<in> carrier G\" by (metis HG subgroup.mem_carrier)+\n  thus \"\\<phi> (g \\<otimes>\\<^bsub>G\\<^esub> h) = \\<phi> g \\<otimes>\\<^bsub>F\\<^esub> \\<phi> h\" using \\<phi> unfolding iso_def hom_def by auto\nnext\n  fix g h\n  assume \"g \\<in> H\" \"h \\<in> H\" \"g \\<otimes>\\<^bsub>G\\<^esub> h \\<notin> H\"\n  hence \"False\" using HG unfolding subgroup_def by auto\n  thus \"undefined = \\<phi> g \\<otimes>\\<^bsub>F\\<^esub> \\<phi> h\" by auto\nnext\n  fix g h\n  assume g:\"g \\<in> H\" and h:\"h \\<in> H\" and eq:\"\\<phi> g = \\<phi> h\"\n  hence \"g \\<in> carrier G\" \"h \\<in> carrier G\" by (metis HG subgroup.mem_carrier)+\n  with eq show \"g = h\" using \\<phi> unfolding iso_def bij_betw_def inj_on_def by auto\nqed\n\ntext \\<open>The intersection of two subgroups is, again, a subgroup\\<close>\n\nlemma (in group) subgroup_intersect:\n  assumes \"subgroup H G\"\n  assumes \"subgroup H' G\"\n  shows \"subgroup (H \\<inter> H') G\"\nusing assms unfolding subgroup_def by auto\n\nsection \\<open>Facts about Normal Subgroups\\<close>\n\nlemma (in normal) is_normal:\n  shows \"H \\<lhd> G\"\nby (metis coset_eq is_subgroup normalI)\n\ntext \\<open>Being a normal subgroup is preserved by surjective homomorphisms.\\<close>\n\nlemma (in normal) surj_hom_normal_subgroup:\n  assumes \\<phi>:\"group_hom G F \\<phi>\"\n  assumes \\<phi>surj:\"\\<phi> ` (carrier G) = carrier F\"\n  shows \"(\\<phi> ` H) \\<lhd> F\"\nproof (rule group.normalI)\n  from \\<phi> show \"group F\" unfolding group_hom_def group_hom_axioms_def by simp\nnext\n  from \\<phi> \\<phi>surj show \"subgroup (\\<phi> ` H) F\" by (rule surj_hom_subgroup)\nnext\n  show \"\\<forall>x\\<in>carrier F. \\<phi> ` H #>\\<^bsub>F\\<^esub> x = x <#\\<^bsub>F\\<^esub> \\<phi> ` H\"\n  proof\n    fix f\n    assume f:\"f \\<in> carrier F\"\n    with \\<phi>surj obtain g where g:\"g \\<in> carrier G\" \"f = \\<phi> g\" by auto\n    hence \"\\<phi> ` H #>\\<^bsub>F\\<^esub> f = \\<phi> ` H #>\\<^bsub>F\\<^esub> \\<phi> g\" by simp\n    also have \"... = (\\<lambda>x. (\\<phi> x) \\<otimes>\\<^bsub>F\\<^esub> (\\<phi> g)) ` H\" unfolding r_coset_def image_def by auto\n    also have \"... = (\\<lambda>x. \\<phi> (x \\<otimes> g)) ` H\" using subset g \\<phi> group_hom.hom_mult unfolding image_def by fastforce\n    also have \"... = \\<phi> ` (H #> g)\" using \\<phi> unfolding r_coset_def by auto\n    also have \"... = \\<phi> ` (g <# H)\" by (metis coset_eq g(1))\n    also have \"... = (\\<lambda>x. \\<phi> (g \\<otimes> x)) ` H\" using \\<phi> unfolding l_coset_def by auto\n    also have \"... = (\\<lambda>x. (\\<phi> g) \\<otimes>\\<^bsub>F\\<^esub> (\\<phi> x)) ` H\" using subset g \\<phi> group_hom.hom_mult by fastforce\n    also have \"... = \\<phi> g <#\\<^bsub>F\\<^esub> \\<phi> ` H\" unfolding l_coset_def image_def by auto\n    also have \"... = f <#\\<^bsub>F\\<^esub> \\<phi> ` H\" using g by simp\n    finally show \"\\<phi> ` H #>\\<^bsub>F\\<^esub> f = f <#\\<^bsub>F\\<^esub> \\<phi> ` H\".\n  qed\nqed\n\ntext \\<open>Being a normal subgroup is preserved by group isomorphisms.\\<close>\n\nlemma iso_normal_subgroup:\n  assumes groups:\"group G\" \"group F\"\n  assumes HG:\"H \\<lhd> G\"\n  assumes \\<phi>:\"\\<phi> \\<in> iso G F\"\n  shows \"(\\<phi> ` H) \\<lhd> F\"\nproof -\n  from groups \\<phi> have \"group_hom G F \\<phi>\" unfolding group_hom_def group_hom_axioms_def iso_def by auto\n  moreover from \\<phi> have \"\\<phi> ` (carrier G) = carrier F\" unfolding iso_def bij_betw_def by simp\n  moreover note HG\n  ultimately show ?thesis using normal.surj_hom_normal_subgroup by metis\nqed\n\ntext \\<open>The trivial subgroup is a subgroup:\\<close>\n\nlemma (in group) triv_subgroup:\n  shows \"subgroup {\\<one>} G\"\nunfolding subgroup_def by auto\n\ntext \\<open>The cardinality of the right cosets of the trivial subgroup is the cardinality of the group itself:\\<close>\n\nlemma (in group) card_rcosets_triv:\n  assumes \"finite (carrier G)\"\n  shows \"card (rcosets {\\<one>}) = order G\"\nproof -\n  have \"subgroup {\\<one>} G\" by (rule triv_subgroup)\n  with assms have \"card (rcosets {\\<one>}) * card {\\<one>} = order G\"\n    using lagrange by blast\n  thus ?thesis by (auto simp:card_Suc_eq)\nqed\n\ntext \\<open>The intersection of two normal subgroups is, again, a normal subgroup.\\<close>\n\nlemma (in group) normal_subgroup_intersect:\n  assumes \"M \\<lhd> G\" and \"N \\<lhd> G\"\n  shows \"M \\<inter> N \\<lhd> G\"\nusing assms subgroup_intersect is_group normal_inv_iff by simp\n\ntext \\<open>The set product of two normal subgroups is a normal subgroup.\\<close>\n\nlemma (in group) setmult_lcos_assoc:\n     \"\\<lbrakk>H \\<subseteq> carrier G; K \\<subseteq> carrier G; x \\<in> carrier G\\<rbrakk>\n      \\<Longrightarrow> (x <# H) <#> K = x <# (H <#> K)\"\nby (force simp add: l_coset_def set_mult_def m_assoc)\n\nlemma (in group) normal_subgroup_set_mult_closed:\n  assumes \"M \\<lhd> G\" and \"N \\<lhd> G\"\n  shows \"M <#> N \\<lhd> G\"\nproof (rule normalI)\n  from assms show \"subgroup (M <#> N) G\"\n    using second_isomorphism_grp.normal_set_mult_subgroup normal_imp_subgroup\n    unfolding second_isomorphism_grp_def second_isomorphism_grp_axioms_def by force\nnext\n  show \"\\<forall>x\\<in>carrier G. M <#> N #> x = x <# (M <#> N)\"\n  proof\n    fix x\n    assume x:\"x \\<in> carrier G\"\n    have \"M <#> N #> x = M <#> (N #> x)\" by (metis assms(1,2) normal_inv_iff setmult_rcos_assoc subgroup.subset x)\n    also have \"\\<dots> = M <#> (x <# N)\" by (metis assms(2) normal.coset_eq x)\n    also have \"\\<dots> = (M #> x) <#> N\" by (metis assms(1,2) normal_imp_subgroup rcos_assoc_lcos subgroup.subset x)\n    also have \"\\<dots> = (x <# M) <#> N\" by (metis assms(1) normal.coset_eq x)\n    also have \"\\<dots> = x <# (M <#> N)\" by (metis assms(1,2) normal_imp_subgroup setmult_lcos_assoc subgroup.subset x)\n    finally show \"M <#> N #> x = x <# (M <#> N)\".\n  qed\nqed\n\ntext \\<open>The following is a very basic lemma about subgroups: If restricting the carrier of\n  a group yields a group it's a subgroup of the group we've started with.\\<close>\n\nlemma (in group) restrict_group_imp_subgroup:\n  assumes \"H \\<subseteq> carrier G\" \"group (G\\<lparr>carrier := H\\<rparr>)\"\n  shows \"subgroup H G\"\nproof\n  from assms(1) show \"H \\<subseteq> carrier G\" .\nnext\n  fix x y\n  assume \"x \\<in> H\" \"y \\<in> H\"\n  hence \"x \\<in> carrier (G\\<lparr>carrier := H\\<rparr>)\" \"y \\<in> carrier (G\\<lparr>carrier := H\\<rparr>)\" by auto\n  with assms(2) show \"x \\<otimes> y \\<in> H\" using assms(2) group.is_monoid monoid.m_closed by fastforce\nnext\n  show \"\\<one> \\<in> H\" using assms(2) group.is_monoid monoid.one_closed by fastforce\nnext\n  fix x\n  assume \"x \\<in> H\"\n  hence x:\"x \\<in> carrier (G\\<lparr>carrier := H\\<rparr>)\" by auto\n  hence \"inv\\<^bsub>G\\<lparr>carrier := H\\<rparr>\\<^esub> x \\<in> carrier (G\\<lparr>carrier := H\\<rparr>)\" using assms(2) group.inv_closed by fastforce\n  hence \"inv\\<^bsub>G\\<lparr>carrier := H\\<rparr>\\<^esub> x \\<in> carrier G\" using x assms(1) by auto\n  moreover have \"inv\\<^bsub>G\\<lparr>carrier := H\\<rparr>\\<^esub> x \\<otimes> x = \\<one>\" using assms(2) group.l_inv x by fastforce\n  moreover have \"x \\<in> carrier G\" using x assms(1) by auto\n  ultimately have \"inv\\<^bsub>G\\<lparr>carrier := H\\<rparr>\\<^esub> x = inv x\" using inv_equality[symmetric] by auto\n  thus \"inv x \\<in> H\" using assms(2) group.inv_closed x by fastforce\nqed\n\ntext \\<open>A subgroup relation survives factoring by a normal subgroup.\\<close>\n\nlemma (in group) normal_subgroup_factorize:\n  assumes \"N \\<lhd> G\" and \"N \\<subseteq> H\" and \"subgroup H G\"\n  shows \"subgroup (rcosets\\<^bsub>G\\<lparr>carrier := H\\<rparr>\\<^esub> N) (G Mod N)\"\nproof -\n  interpret GModN: group \"G Mod N\" using assms(1) by (rule normal.factorgroup_is_group)\n  have \"N \\<lhd> G\\<lparr>carrier := H\\<rparr>\" using assms by (metis normal_restrict_supergroup)\n  hence grpHN:\"group (G\\<lparr>carrier := H\\<rparr> Mod N)\" by (rule normal.factorgroup_is_group)\n  have \"(<#>\\<^bsub>G\\<lparr>carrier:=H\\<rparr>\\<^esub>) = (\\<lambda>U K. (\\<Union>h\\<in>U. \\<Union>k\\<in>K. {h \\<otimes>\\<^bsub>G\\<lparr>carrier := H\\<rparr>\\<^esub> k}))\" using set_mult_def by metis\n  moreover have \"\\<dots> = (\\<lambda>U K. (\\<Union>h\\<in>U. \\<Union>k\\<in>K. {h \\<otimes>\\<^bsub>G\\<^esub> k}))\" by auto\n  moreover have \"(<#>) = (\\<lambda>U K. (\\<Union>h\\<in>U. \\<Union>k\\<in>K. {h \\<otimes> k}))\" using set_mult_def by metis\n  ultimately have \"(<#>\\<^bsub>G\\<lparr>carrier:=H\\<rparr>\\<^esub>) = (<#>\\<^bsub>G\\<^esub>)\" by simp\n  with grpHN have \"group ((G Mod N)\\<lparr>carrier := (rcosets\\<^bsub>G\\<lparr>carrier := H\\<rparr>\\<^esub> N)\\<rparr>)\" unfolding FactGroup_def by auto\n  moreover have \"rcosets\\<^bsub>G\\<lparr>carrier := H\\<rparr>\\<^esub> N \\<subseteq> carrier (G Mod N)\" unfolding FactGroup_def RCOSETS_def r_coset_def\n    using assms(3) subgroup.subset by fastforce\n  ultimately show ?thesis using GModN.is_group group.restrict_group_imp_subgroup by auto\nqed\n\ntext \\<open>A normality relation survives factoring by a normal subgroup.\\<close>\n\nlemma (in group) normality_factorization:\n  assumes NG:\"N \\<lhd> G\" and NH:\"N \\<subseteq> H\" and HG:\"H \\<lhd> G\"\n  shows \"(rcosets\\<^bsub>G\\<lparr>carrier := H\\<rparr>\\<^esub> N) \\<lhd> (G Mod N)\"\nproof -\n  from assms(1) interpret GModN: group \"G Mod N\" by (metis normal.factorgroup_is_group)\n  show ?thesis\n  proof (auto simp: GModN.normal_inv_iff)\n    from assms show \"subgroup (rcosets\\<^bsub>G\\<lparr>carrier := H\\<rparr>\\<^esub> N) (G Mod N)\" using normal_imp_subgroup normal_subgroup_factorize by force\n  next\n    fix U V\n    assume U:\"U \\<in> carrier (G Mod N)\" and V:\"V \\<in> rcosets\\<^bsub>G\\<lparr>carrier := H\\<rparr>\\<^esub> N\"\n    then obtain g where g:\"g \\<in> carrier G\" \"U = N #> g\" unfolding FactGroup_def RCOSETS_def by auto\n    from V obtain h where h:\"h \\<in> H\" \"V = N #> h\" unfolding FactGroup_def RCOSETS_def r_coset_def by auto\n    hence hG:\"h \\<in> carrier G\" using HG normal_imp_subgroup subgroup.mem_carrier by force\n    hence ghG:\"g \\<otimes> h \\<in> carrier G\" using g m_closed by auto\n    from g h have \"g \\<otimes> h \\<otimes> inv g \\<in> H\" using HG normal_inv_iff by auto\n    moreover have \"U <#> V <#> inv\\<^bsub>G Mod N\\<^esub> U = N #> (g \\<otimes> h \\<otimes> inv g)\"\n    proof -\n      from g U have \"inv\\<^bsub>G Mod N\\<^esub> U = N #> inv g\" using NG normal.inv_FactGroup normal.rcos_inv by fastforce\n      hence \"U <#> V <#> inv\\<^bsub>G Mod N\\<^esub> U = (N #> g) <#> (N #> h) <#> (N #> inv g)\" using g h by simp\n      also have \"\\<dots> = N #> (g \\<otimes> h) <#> (N #> inv g)\" using g hG NG normal.rcos_sum by force\n      also have \"\\<dots> = N #> (g \\<otimes> h \\<otimes> inv g)\" using g inv_closed ghG NG normal.rcos_sum by force\n      finally show ?thesis .\n    qed\n    ultimately show \"U <#> V <#> inv\\<^bsub>G Mod N\\<^esub> U \\<in> rcosets\\<^bsub>G\\<lparr>carrier := H\\<rparr>\\<^esub> N\" unfolding RCOSETS_def r_coset_def by auto\n  qed\nqed\n\ntext \\<open>Factoring by a normal subgroups yields the trivial group iff the subgroup is the whole group.\\<close>\n\nlemma (in normal) fact_group_trivial_iff:\n  assumes \"finite (carrier G)\"\n  shows \"(carrier (G Mod H) = {\\<one>\\<^bsub>G Mod H\\<^esub>}) = (H = carrier G)\"\nproof\n  assume \"carrier (G Mod H) = {\\<one>\\<^bsub>G Mod H\\<^esub>}\"\n  moreover with assms lagrange have \"order (G Mod H) * card H = order G\" unfolding FactGroup_def order_def using is_subgroup by force\n  ultimately have \"card H = order G\" unfolding order_def by auto\n  thus \"H = carrier G\" using subgroup.subset is_subgroup assms card_subset_eq unfolding order_def\n    by metis\nnext\n  from assms have ordergt0:\"order G > 0\" unfolding order_def by (metis subgroup.finite_imp_card_positive subgroup_self)\n  assume \"H = carrier G\"\n  hence \"card H = order G\" unfolding order_def by simp\n  with assms is_subgroup lagrange have \"card (rcosets H) * order G = order G\" by metis\n  with ordergt0 have \"card (rcosets H) = 1\" by (metis mult_eq_self_implies_10 mult.commute neq0_conv)\n  hence \"order (G Mod H) = 1\" unfolding order_def FactGroup_def by auto\n  thus \"carrier (G Mod H) = {\\<one>\\<^bsub>G Mod H\\<^esub>}\" using factorgroup_is_group by (metis group.order_one_triv_iff)\nqed\n\ntext \\<open>Finite groups have finite quotients.\\<close>\n\nlemma (in normal) factgroup_finite:\n  assumes \"finite (carrier G)\"\n  shows \"finite (rcosets H)\"\nusing assms unfolding RCOSETS_def by auto\n\ntext \\<open>The union of all the cosets contained in a subgroup of a quotient group acts as a represenation for that subgroup.\\<close>\n\nlemma (in normal) factgroup_subgroup_union_char:\n  assumes \"subgroup A (G Mod H)\"\n  shows \"(\\<Union>A) = {x \\<in> carrier G. H #> x \\<in> A}\"\nproof\n  show \"\\<Union>A \\<subseteq> {x \\<in> carrier G. H #> x \\<in> A}\"\n  proof\n    fix x\n    assume x:\"x \\<in> \\<Union>A\"\n    then obtain a where a:\"a \\<in> A\" \"x \\<in> a\" by auto\n    with assms have xx:\"x \\<in> carrier G\" using subgroup.subset unfolding FactGroup_def RCOSETS_def r_coset_def by force\n    from assms a obtain y where y:\"y \\<in> carrier G\" \"a = H #> y\" using subgroup.subset unfolding FactGroup_def RCOSETS_def by force\n    with a have \"x \\<in> H #> y\" by simp\n    hence \"H #> y = H #> x\" using y is_subgroup repr_independence by auto\n    with y(2) a(1) have \"H #> x \\<in> A\" by auto\n    with xx show \"x \\<in> {x \\<in> carrier G. H #> x \\<in> A}\" by simp\n  qed\nnext\n  show \"{x \\<in> carrier G. H #> x \\<in> A} \\<subseteq> \\<Union>A\"\n  proof\n    fix x\n    assume x:\"x \\<in> {x \\<in> carrier G. H #> x \\<in> A}\"\n    hence xx:\"x \\<in> carrier G\" \"H #> x \\<in> A\" by auto\n    moreover have \"x \\<in> H #> x\" by (metis is_subgroup rcos_self xx(1))\n    ultimately show \"x \\<in> \\<Union>A\" by auto\n  qed\nqed\n\nlemma (in normal) factgroup_subgroup_union_subgroup:\n  assumes \"subgroup A (G Mod H)\"\n  shows \"subgroup (\\<Union>A) G\"\nproof -\n  have \"subgroup {x \\<in> carrier G. H #> x \\<in> A} G\"\n  proof\n    show \"{x \\<in> carrier G. H #> x \\<in> A} \\<subseteq> carrier G\" by auto\n  next\n    fix x y\n    assume \"x \\<in> {x \\<in> carrier G. H #> x \\<in> A}\" and \"y \\<in> {x \\<in> carrier G. H #> x \\<in> A}\"\n    hence x:\"x \\<in> carrier G\" \"H #> x \\<in> A\" and y:\"y \\<in> carrier G\" \"H #> y \\<in> A\" by auto\n    hence xyG:\"x \\<otimes> y \\<in> carrier G\" by (metis m_closed)\n    from assms x y have \"(H #> x) <#> (H #> y) \\<in> A\" using subgroup.m_closed unfolding FactGroup_def by fastforce\n    hence \"H #> (x \\<otimes> y) \\<in> A\" by (metis rcos_sum x(1) y(1))\n    with xyG show \"x \\<otimes> y \\<in> {x \\<in> carrier G. H #> x \\<in> A}\" by simp\n  next\n    have \"H #> \\<one> \\<in> A\" using assms subgroup.one_closed unfolding FactGroup_def by (metis coset_mult_one monoid.select_convs(2) subset)\n    with assms one_closed show \"\\<one> \\<in> {x \\<in> carrier G. H #> x \\<in> A}\" by simp\n  next\n    fix x\n    assume \"x \\<in> {x \\<in> carrier G. H #> x \\<in> A}\"\n    hence x:\"x \\<in> carrier G\" \"H #> x \\<in> A\" by auto\n    hence invx:\"inv x \\<in> carrier G\" using inv_closed by simp\n    from assms x have \"set_inv (H #> x) \\<in> A\" using subgroup.m_inv_closed by (metis inv_FactGroup subgroup.mem_carrier)\n    hence \"H #> (inv x) \\<in> A\" by (metis rcos_inv x(1))\n    with invx show \"inv x \\<in> {x \\<in> carrier G. H #> x \\<in> A}\" by simp\n  qed\n  with assms factgroup_subgroup_union_char show ?thesis by auto\nqed\n\nlemma (in normal) factgroup_subgroup_union_normal:\n  assumes \"A \\<lhd> (G Mod H)\"\n  shows \"\\<Union>A \\<lhd> G\"\nproof - \n  have \"{x \\<in> carrier G. H #> x \\<in> A} \\<lhd> G\"\n  unfolding normal_def normal_axioms_def\n  proof auto (*(auto del: equalityI)*)\n    from assms show \"subgroup {x \\<in> carrier G. H #> x \\<in> A} G\"\n      by (metis (full_types) factgroup_subgroup_union_char factgroup_subgroup_union_subgroup normal_imp_subgroup)\n  next\n    interpret Anormal: normal A \"(G Mod H)\" using assms by simp\n    fix x y\n    assume x:\"x \\<in> carrier G\" \"y \\<in> {x \\<in> carrier G. H #> x \\<in> A} #> x\"\n    then obtain x' where \"x' \\<in> {x \\<in> carrier G. H #> x \\<in> A}\" \"y = x' \\<otimes> x\" unfolding r_coset_def by auto\n    hence x':\"x' \\<in> carrier G\" \"H #> x' \\<in> A\" by auto\n    from x(1) have Hx:\"H #> x \\<in> carrier (G Mod H)\" unfolding FactGroup_def RCOSETS_def by force\n    with x' have \"(inv\\<^bsub>G Mod H\\<^esub> (H #> x)) \\<otimes>\\<^bsub>G Mod H\\<^esub> (H #> x') \\<otimes>\\<^bsub>G Mod H\\<^esub> (H #> x) \\<in> A\" using Anormal.inv_op_closed1 by auto\n    hence \"(set_inv (H #> x)) <#> (H #> x') <#> (H #> x) \\<in> A\" using inv_FactGroup Hx unfolding FactGroup_def by auto\n    hence \"(H #> (inv x)) <#> (H #> x') <#> (H #> x) \\<in> A\" using x(1) by (metis rcos_inv)\n    hence \"(H #> (inv x \\<otimes> x')) <#> (H #> x) \\<in> A\" by (metis inv_closed rcos_sum x'(1) x(1))\n    hence \"H #> (inv x \\<otimes> x' \\<otimes> x) \\<in> A\" by (metis inv_closed m_closed rcos_sum x'(1) x(1))\n    moreover have \"inv x \\<otimes> x' \\<otimes> x \\<in> carrier G\" using x x' by (metis inv_closed m_closed)\n    ultimately have \"inv x \\<otimes> x' \\<otimes> x \\<in> {x \\<in> carrier G. H #> x \\<in> A}\" by auto\n    hence xcoset:\"x \\<otimes> (inv x \\<otimes> x' \\<otimes> x) \\<in> x <# {x \\<in> carrier G. H #> x \\<in> A}\" unfolding l_coset_def using x(1) by auto\n    have \"x \\<otimes> (inv x \\<otimes> x' \\<otimes> x) = (x \\<otimes> inv x) \\<otimes> x' \\<otimes> x\" by (metis Units_eq Units_inv_Units m_assoc m_closed x'(1) x(1))\n    also have \"\\<dots> = x' \\<otimes> x\" by (metis l_one r_inv x'(1) x(1))\n    also have \"\\<dots> = y\" by (metis \\<open>y = x' \\<otimes> x\\<close>)\n    finally have \"x \\<otimes> (inv x \\<otimes> x' \\<otimes> x) = y\".\n    with xcoset show \"y \\<in> x <# {x \\<in> carrier G. H #> x \\<in> A}\" by auto\n  next\n    interpret Anormal: normal A \"(G Mod H)\" using assms by simp\n    fix x y\n    assume x:\"x \\<in> carrier G\" \"y \\<in> x <# {x \\<in> carrier G. H #> x \\<in> A}\"\n    then obtain x' where \"x' \\<in> {x \\<in> carrier G. H #> x \\<in> A}\" \"y = x \\<otimes> x'\" unfolding l_coset_def by auto\n    hence x':\"x' \\<in> carrier G\" \"H #> x' \\<in> A\" by auto\n    from x(1) have invx:\"inv x \\<in> carrier G\" by (rule inv_closed)\n    hence Hinvx:\"H #> (inv x) \\<in> carrier (G Mod H)\" unfolding FactGroup_def RCOSETS_def by force\n    with x' have \"(inv\\<^bsub>G Mod H\\<^esub> (H #> inv x)) \\<otimes>\\<^bsub>G Mod H\\<^esub> (H #> x') \\<otimes>\\<^bsub>G Mod H\\<^esub> (H #> inv x) \\<in> A\" using invx Anormal.inv_op_closed1 by auto\n    hence \"(set_inv (H #> inv x)) <#> (H #> x') <#> (H #> inv x) \\<in> A\" using inv_FactGroup Hinvx unfolding FactGroup_def by auto\n    hence \"(H #> inv (inv x)) <#> (H #> x') <#> (H #> inv x) \\<in> A\" using invx by (metis rcos_inv)\n    hence \"(H #> x) <#> (H #> x') <#> (H #> inv x) \\<in> A\" by (metis inv_inv x(1))\n    hence \"(H #> (x \\<otimes> x')) <#> (H #> inv x) \\<in> A\" by (metis rcos_sum x'(1) x(1))\n    hence \"H #> (x \\<otimes> x' \\<otimes> inv x) \\<in> A\" by (metis inv_closed m_closed rcos_sum x'(1) x(1))\n    moreover have \"x \\<otimes> x' \\<otimes> inv x \\<in> carrier G\" using x x' by (metis inv_closed m_closed)\n    ultimately have \"x \\<otimes> x' \\<otimes> inv x \\<in> {x \\<in> carrier G. H #> x \\<in> A}\" by auto\n    hence xcoset:\"(x \\<otimes> x' \\<otimes> inv x) \\<otimes> x \\<in> {x \\<in> carrier G. H #> x \\<in> A} #> x\" unfolding r_coset_def using invx by auto\n    have \"(x \\<otimes> x' \\<otimes> inv x) \\<otimes> x = (x \\<otimes> x') \\<otimes> (inv x \\<otimes> x)\" by (metis Units_eq Units_inv_Units m_assoc m_closed x'(1) x(1))\n    also have \"\\<dots> = x \\<otimes> x'\" using x(1) l_inv x'(1) m_closed r_one by auto\n    also have \"\\<dots> = y\" by (metis \\<open>y = x \\<otimes> x'\\<close>)\n    finally have \"x \\<otimes> x' \\<otimes> inv x \\<otimes> x = y\".\n    with xcoset show \"y \\<in> {x \\<in> carrier G. H #> x \\<in> A} #> x\" by auto\n  qed\n  with assms show ?thesis by (metis (full_types) factgroup_subgroup_union_char normal_imp_subgroup)\nqed\n\nlemma (in normal) factgroup_subgroup_union_factor:\n  assumes \"subgroup A (G Mod H)\"\n  shows \"A = rcosets\\<^bsub>G\\<lparr>carrier := \\<Union>A\\<rparr>\\<^esub> H\"\nproof -\n  have \"A = rcosets\\<^bsub>G\\<lparr>carrier := {x \\<in> carrier G. H #> x \\<in> A}\\<rparr>\\<^esub> H\"\n  proof auto\n    fix U\n    assume U:\"U \\<in> A\"\n    then obtain x' where x':\"x' \\<in> carrier G\" \"U = H #> x'\" using assms subgroup.subset unfolding FactGroup_def RCOSETS_def by force\n    with U have \"H #> x' \\<in> A\" by simp\n    with x' show \"U \\<in> rcosets\\<^bsub>G\\<lparr>carrier := {x \\<in> carrier G. H #> x \\<in> A}\\<rparr>\\<^esub> H\" unfolding RCOSETS_def r_coset_def by auto\n  next\n    fix U\n    assume U:\"U \\<in> rcosets\\<^bsub>G\\<lparr>carrier := {x \\<in> carrier G. H #> x \\<in> A}\\<rparr>\\<^esub> H\"\n    then obtain x' where x':\"x' \\<in> {x \\<in> carrier G. H #> x \\<in> A}\" \"U = H #> x'\" unfolding RCOSETS_def r_coset_def by auto\n    hence \"x' \\<in> carrier G\" \"H #> x' \\<in> A\" by auto\n    with x' show \"U \\<in> A\" by simp\n  qed\n  with assms show ?thesis using factgroup_subgroup_union_char by auto\nqed\n\n\nsection  \\<open>Flattening the type of group carriers\\<close>\n\ntext \\<open>Flattening here means to convert the type of group elements from 'a set to 'a.\nThis is possible whenever the empty set is not an element of the group.\\<close>\n\n\ndefinition flatten where\n  \"flatten (G::('a set, 'b) monoid_scheme) rep = \\<lparr>carrier=(rep ` (carrier G)),\n      monoid.mult=(\\<lambda> x y. rep ((the_inv_into (carrier G) rep x) \\<otimes>\\<^bsub>G\\<^esub> (the_inv_into (carrier G) rep y))), \n      one=rep \\<one>\\<^bsub>G\\<^esub> \\<rparr>\"\n\nlemma flatten_set_group_hom:\n  assumes group:\"group G\"\n  assumes inj:\"inj_on rep (carrier G)\"\n  shows \"rep \\<in> hom G (flatten G rep)\"\nunfolding hom_def\nproof auto\n  fix g\n  assume g:\"g \\<in> carrier G\"\n  thus \"rep g \\<in> carrier (flatten G rep)\" unfolding flatten_def by auto\nnext\n  fix g h\n  assume g:\"g \\<in> carrier G\" and h:\"h \\<in> carrier G\"\n  hence \"rep g \\<in> carrier (flatten G rep)\" \"rep h \\<in> carrier (flatten G rep)\" unfolding flatten_def by auto\n  hence \"rep g \\<otimes>\\<^bsub>flatten G rep\\<^esub> rep h\n    = rep (the_inv_into (carrier G) rep (rep g) \\<otimes>\\<^bsub>G\\<^esub> the_inv_into (carrier G) rep (rep h))\" unfolding flatten_def by auto\n  also have \"\\<dots> = rep (g \\<otimes>\\<^bsub>G\\<^esub> h)\" using inj g h by (metis the_inv_into_f_f)\n  finally show \"rep (g \\<otimes>\\<^bsub>G\\<^esub> h) = rep g \\<otimes>\\<^bsub>flatten G rep\\<^esub> rep h\"..\nqed\n\nlemma flatten_set_group:\n  assumes group:\"group G\"\n  assumes inj:\"inj_on rep (carrier G)\"\n  shows \"group (flatten G rep)\"\nproof (rule groupI)\n  fix x y\n  assume x:\"x \\<in> carrier (flatten G rep)\" and y:\"y \\<in> carrier (flatten G rep)\"\n  define g h\n    where \"g = the_inv_into (carrier G) rep x\"\n      and \"h = the_inv_into (carrier G) rep y\"\n  hence \"x \\<otimes>\\<^bsub>flatten G rep\\<^esub> y = rep (g \\<otimes>\\<^bsub>G\\<^esub> h)\" unfolding flatten_def by auto\n  moreover from g_def h_def have \"g \\<in> carrier G\" \"h \\<in> carrier G\" \n    using inj x y the_inv_into_into unfolding flatten_def by (metis partial_object.select_convs(1) subset_refl)+\n  hence \"g \\<otimes>\\<^bsub>G\\<^esub> h \\<in> carrier G\" by (metis group group.is_monoid monoid.m_closed)\n  hence \"rep (g \\<otimes>\\<^bsub>G\\<^esub> h) \\<in> carrier (flatten G rep)\" unfolding flatten_def by simp\n  ultimately show \"x \\<otimes>\\<^bsub>flatten G rep\\<^esub> y \\<in> carrier (flatten G rep)\" by simp\nnext\n  show \"\\<one>\\<^bsub>flatten G rep\\<^esub> \\<in> carrier (flatten G rep)\" unfolding flatten_def by (simp add: group group.is_monoid)\nnext\n  fix x y z\n  assume x:\"x \\<in> carrier (flatten G rep)\" and y:\"y \\<in> carrier (flatten G rep)\" and z:\"z \\<in> carrier (flatten G rep)\"\n  define g h k\n    where \"g = the_inv_into (carrier G) rep x\"\n      and \"h = the_inv_into (carrier G) rep y\"\n      and \"k = the_inv_into (carrier G) rep z\"\n  hence \"x \\<otimes>\\<^bsub>flatten G rep\\<^esub> y \\<otimes>\\<^bsub>flatten G rep\\<^esub> z = (rep (g \\<otimes>\\<^bsub>G\\<^esub> h)) \\<otimes> \\<^bsub>flatten G rep\\<^esub> z\" unfolding flatten_def by auto\n  also have \"\\<dots> = rep (the_inv_into (carrier G) rep (rep (g \\<otimes>\\<^bsub>G\\<^esub> h)) \\<otimes>\\<^bsub>G\\<^esub> k)\" using k_def unfolding flatten_def by auto\n  also from g_def h_def k_def have ghkG:\"g \\<in> carrier G\" \"h \\<in> carrier G\" \"k \\<in> carrier G\"\n    using inj x y z the_inv_into_into unfolding flatten_def by fastforce+\n  hence gh:\"g \\<otimes>\\<^bsub>G\\<^esub> h \\<in> carrier G\" and hk:\"h \\<otimes>\\<^bsub>G\\<^esub> k \\<in> carrier G\" by (metis group group.is_monoid monoid.m_closed)+\n  hence \"rep (the_inv_into (carrier G) rep (rep (g \\<otimes>\\<^bsub>G\\<^esub> h)) \\<otimes>\\<^bsub>G\\<^esub> k) = rep ((g \\<otimes>\\<^bsub>G\\<^esub> h) \\<otimes>\\<^bsub>G\\<^esub> k)\"\n    unfolding flatten_def using inj the_inv_into_f_f by fastforce\n  also have \"\\<dots> = rep (g \\<otimes>\\<^bsub>G\\<^esub> (h \\<otimes>\\<^bsub>G\\<^esub> k))\" using group group.is_monoid ghkG monoid.m_assoc by fastforce\n  also have \"\\<dots> = x \\<otimes>\\<^bsub>flatten G rep\\<^esub> (rep (h \\<otimes>\\<^bsub>G\\<^esub> k))\" unfolding g_def flatten_def using hk inj the_inv_into_f_f by fastforce\n  also have \"\\<dots> = x \\<otimes>\\<^bsub>flatten G rep\\<^esub> (y \\<otimes>\\<^bsub>flatten G rep\\<^esub> z)\" unfolding h_def k_def flatten_def using x y by force\n  finally show \"x \\<otimes>\\<^bsub>flatten G rep\\<^esub> y \\<otimes>\\<^bsub>flatten G rep\\<^esub> z = x \\<otimes>\\<^bsub>flatten G rep\\<^esub> (y \\<otimes>\\<^bsub>flatten G rep\\<^esub> z)\".\nnext\n  fix x\n  assume x:\"x \\<in> carrier (flatten G rep)\"\n  define g where \"g = the_inv_into (carrier G) rep x\"\n  hence gG:\"g \\<in> carrier G\" using inj x unfolding flatten_def using the_inv_into_into by force\n  have \"\\<one>\\<^bsub>G\\<^esub> \\<in> (carrier G)\" by (simp add: group group.is_monoid)\n  hence \"the_inv_into (carrier G) rep (\\<one>\\<^bsub>flatten G rep\\<^esub>) = \\<one>\\<^bsub>G\\<^esub>\" unfolding flatten_def using the_inv_into_f_f inj by force\n  hence \"\\<one>\\<^bsub>flatten G rep\\<^esub> \\<otimes>\\<^bsub>flatten G rep\\<^esub> x = rep (\\<one>\\<^bsub>G\\<^esub> \\<otimes>\\<^bsub>G\\<^esub> g)\" unfolding flatten_def g_def by simp\n  also have \"\\<dots> = rep g\" using gG group by (metis group.is_monoid monoid.l_one)\n  also have \"\\<dots> = x\" unfolding g_def using inj x f_the_inv_into_f unfolding flatten_def by force\n  finally show \"\\<one>\\<^bsub>flatten G rep\\<^esub> \\<otimes>\\<^bsub>flatten G rep\\<^esub> x = x\".\nnext\n  from group inj have hom:\"rep \\<in> hom G (flatten G rep)\" using flatten_set_group_hom by auto\n  fix x\n  assume x:\"x \\<in> carrier (flatten G rep)\"\n  define g where \"g = the_inv_into (carrier G) rep x\"\n  hence gG:\"g \\<in> carrier G\" using inj x unfolding flatten_def using the_inv_into_into by force\n  hence invG:\"inv\\<^bsub>G\\<^esub> g \\<in> carrier G\" by (metis group group.inv_closed)\n  hence \"rep (inv\\<^bsub>G\\<^esub> g) \\<in> carrier (flatten G rep)\" unfolding flatten_def by auto\n  moreover have \"rep (inv\\<^bsub>G\\<^esub> g) \\<otimes>\\<^bsub>flatten G rep\\<^esub> x = rep (inv\\<^bsub>G\\<^esub> g) \\<otimes>\\<^bsub>flatten G rep\\<^esub> (rep g)\"\n    unfolding g_def using f_the_inv_into_f inj x unfolding flatten_def by fastforce\n  hence \"rep (inv\\<^bsub>G\\<^esub> g) \\<otimes>\\<^bsub>flatten G rep\\<^esub> x = rep (inv\\<^bsub>G\\<^esub> g \\<otimes>\\<^bsub>G\\<^esub> g)\"\n    using hom unfolding hom_def using gG invG hom_def by auto\n  hence \"rep (inv\\<^bsub>G\\<^esub> g) \\<otimes>\\<^bsub>flatten G rep\\<^esub> x = rep \\<one>\\<^bsub>G\\<^esub>\" using invG gG by (metis group group.l_inv)\n  hence \"rep (inv\\<^bsub>G\\<^esub> g) \\<otimes>\\<^bsub>flatten G rep\\<^esub> x = \\<one>\\<^bsub>flatten G rep\\<^esub>\" unfolding flatten_def by auto\n  ultimately show \"\\<exists>y\\<in>carrier (flatten G rep). y \\<otimes>\\<^bsub>flatten G rep\\<^esub> x = \\<one>\\<^bsub>flatten G rep\\<^esub>\" by auto\nqed\n\nlemma (in normal) flatten_set_group_mod_inj:\n  shows \"inj_on (\\<lambda>U. SOME g. g \\<in> U) (carrier (G Mod H))\"\nproof (rule inj_onI)\n  fix U V\n  assume U:\"U \\<in> carrier (G Mod H)\" and V:\"V \\<in> carrier (G Mod H)\"\n  then obtain g h where g:\"U = H #> g\" \"g \\<in> carrier G\" and h:\"V = H #> h\" \"h \\<in> carrier G\"\n    unfolding FactGroup_def RCOSETS_def by auto\n  hence notempty:\"U \\<noteq> {}\" \"V \\<noteq> {}\" by (metis empty_iff is_subgroup rcos_self)+\n  assume \"(SOME g. g \\<in> U) = (SOME g. g \\<in> V)\"\n  with notempty have \"(SOME g. g \\<in> U) \\<in> U \\<inter> V\" by (metis IntI ex_in_conv someI)\n  thus \"U = V\" by (metis Int_iff g h is_subgroup repr_independence)\nqed\n\nlemma (in normal) flatten_set_group_mod:\n  shows \"group (flatten (G Mod H) (\\<lambda>U. SOME g. g \\<in> U))\"\nusing factorgroup_is_group flatten_set_group_mod_inj by (rule flatten_set_group)\n\nlemma (in normal) flatten_set_group_mod_iso:\n  shows \"(\\<lambda>U. SOME g. g \\<in> U) \\<in> iso (G Mod H) (flatten (G Mod H) (\\<lambda>U. SOME g. g \\<in> U))\"\nunfolding iso_def bij_betw_def\napply (auto)\n apply (metis flatten_set_group_mod_inj factorgroup_is_group flatten_set_group_hom)\n apply (rule flatten_set_group_mod_inj)\n unfolding flatten_def apply (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/Jordan_Hoelder/SubgroupsAndNormalSubgroups.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8670357563664174, "lm_q2_score": 0.8418256492357358, "lm_q1q2_score": 0.7298929385137566}}
{"text": "header {*Program Statements as Predicate Transformers*}\n\ntheory Statements\nimports Preliminaries\nbegin\n\ntext {*\n  Program statements are modeled as predicate transformers, functions from predicates to predicates.\n  If $\\mathit{State}$ is the type of program states, then a program $S$ is a a function from \n  $\\mathit{State}\\ \\mathit{set}$ to\n  $\\mathit{State}\\ \\mathit{set}$. If $q \\in \\mathit{State}\\ \\mathit{set}$, then the elements of \n  $S\\ q$ are the initial states from which\n  $S$ is guarantied to terminate in a state from $q$.\n\n  However, most of the time we will work with an arbitrary compleate lattice, or an arbitrary boolean algebra\n  instead of the complete boolean algebra of predicate transformers. \n\n  We will introduce in this section assert, assume, demonic choice, angelic choice, demonic update, and \n  angelic update statements. We will prove also that these statements are monotonic.\n*}\n\nlemma mono_top[simp]: \"mono top\"\n  by (simp add: mono_def top_fun_def)\n\nlemma mono_choice[simp]: \"mono S \\<Longrightarrow> mono T \\<Longrightarrow> mono (S \\<sqinter> T)\"\n  apply (simp add: mono_def inf_fun_def)\n  apply safe\n  apply (rule_tac y = \"S x\" in order_trans)\n  apply simp_all\n  apply (rule_tac y = \"T x\" in order_trans)\n  by simp_all\n\nsubsection \"Assert statement\"\n\ntext {*\nThe assert statement of a predicate $p$ when executed from a state $s$ fails\nif $s\\not\\in p$ and behaves as skip otherwise.\n*}\n\ndefinition\n  assert::\"'a::semilattice_inf \\<Rightarrow> 'a \\<Rightarrow> 'a\" (\"{. _ .}\" [0] 1000) where\n  \"{.p.} q \\<equiv>  p \\<sqinter> q\"\n\nlemma mono_assert [simp]: \"mono {.p.}\"\n  apply (simp add: assert_def mono_def, safe)\n  apply (rule_tac y = \"x\" in order_trans)\n  by simp_all\n\nsubsection \"Assume statement\"\n\ntext {*\nThe assume statement of a predicate $p$ when executed from a state $s$ is not enabled\nif $s\\not\\in p$ and behaves as skip otherwise.\n*}\n\ndefinition\n  \"assume\" :: \"'a::boolean_algebra \\<Rightarrow> 'a \\<Rightarrow> 'a\" (\"[. _ .]\" [0] 1000) where\n  \"[. p .] q \\<equiv>  -p \\<squnion> q\"\n\n\nlemma mono_assume [simp]: \"mono (assume P)\"\n  apply (simp add: assume_def mono_def)\n  apply safe\n  apply (rule_tac y = \"y\" in order_trans)\n  by simp_all\n\nsubsection \"Demonic update statement\"\n\ntext {*\nThe demonic update statement of a relation $Q: \\mathit{State} \\to \\mathit{Sate} \\to bool$,\nwhen executed in a state $s$ computes nondeterministically a new state $s'$ such \n$Q\\ s \\ s'$ is true. In order for this statement to be correct all\npossible choices of $s'$ should be correct. If there is no state $s'$\nsuch that $Q\\ s \\ s'$, then the demonic update of $Q$ is not enabled\nin $s$.\n*}\n\ndefinition\n  demonic :: \"('a \\<Rightarrow> 'b\\<Colon>ord) \\<Rightarrow> 'b\\<Colon>ord \\<Rightarrow> 'a set\" (\"[: _ :]\" [0] 1000) where\n  \"[:Q:] p = {s . Q s \\<le> p}\"\n\nlemma mono_demonic [simp]: \"mono [:Q:]\"\n  apply (simp add: mono_def demonic_def)\n  by auto\n\ntheorem demonic_bottom:\n  \"[:R:] (\\<bottom>::('a::order_bot)) = {s . (R s) = \\<bottom>}\"\n  apply (unfold demonic_def, safe, simp_all)\n  apply (rule antisym)\n  by auto\n\ntheorem demonic_bottom_top [simp]:\n  \"[:(\\<bottom>::_::order_bot):]  = \\<top>\"\n  by (simp add: fun_eq_iff inf_fun_def sup_fun_def demonic_def top_fun_def bot_fun_def)\n\ntheorem demonic_sup_inf:\n  \"[:Q \\<squnion> Q':] = [:Q:] \\<sqinter> [:Q':]\"\n  by (simp add: fun_eq_iff sup_fun_def inf_fun_def demonic_def, blast)\n\nsubsection \"Angelic update statement\"\n\ntext {*\nThe angelic update statement of a relation $Q: \\mathit{State} \\to \\mathit{State} \\to \\mathit{bool}$ is similar\nto the demonic version, except that it is enough that at least for one choice $s'$, $Q \\ s \\ s'$\nis correct. If there is no state $s'$\nsuch that $Q\\ s \\ s'$, then the angelic update of $Q$ fails in $s$.\n*}\n\ndefinition\n  angelic :: \"('a \\<Rightarrow> 'b\\<Colon>{semilattice_inf,order_bot}) \\<Rightarrow> 'b \\<Rightarrow> 'a set\" \n               (\"{: _ :}\" [0] 1000) where\n  \"{:Q:} p = {s . (Q s) \\<sqinter> p \\<noteq> \\<bottom>}\"\n\nsyntax \"_update\" :: \"patterns => patterns => logic => logic\" (\"_ \\<leadsto> _ . _\" 0)\ntranslations\n  \"_update (_patterns x xs) (_patterns y ys) t\" == \"CONST id (_abs\n           (_pattern x xs) (_Coll (_pattern y ys) t))\"\n  \"_update x y t\" == \"CONST id (_abs x (_Coll y t))\"\n\nterm \"{: y, z \\<leadsto> x, z' . P x y z z' :}\"\n\ntheorem angelic_bottom [simp]:\n  \"angelic R \\<bottom>  = {}\"\n  by (simp add: angelic_def inf_bot_bot)\n\ntheorem angelic_disjunctive [simp]:\n  \"{:(R::('a \\<Rightarrow> 'b::complete_distrib_lattice)):} \\<in> Apply.Disjunctive\"\n  by (simp add: Apply.Disjunctive_def angelic_def inf_Sup, blast)\n\n\nsubsection \"The guard of a statement\"\n\ntext {*\nThe guard of a statement $S$ is the set of iniatial states from which $S$\nis enabled or fails.\n*}\n\ndefinition\n  \"((grd S)::'a::boolean_algebra) = - (S bot)\"\n\nlemma grd_choice[simp]: \"grd (S \\<sqinter> T) = (grd S) \\<squnion> (grd T)\"\n  by (simp add: grd_def inf_fun_def)\n\nlemma grd_demonic: \"grd [:Q:] = {s . \\<exists> s' . s' \\<in> (Q s) }\" \n  apply (simp add: grd_def demonic_def)\n  by blast\n\nlemma grd_demonic_2[simp]: \"(s \\<notin> grd [:Q:]) = (\\<forall> s' . s' \\<notin>  (Q s))\" \n  by (simp add: grd_demonic)\n\ntheorem grd_angelic:\n  \"grd {:R:} = UNIV\"\n  by (simp add: grd_def)\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/DataRefinementIBP/Statements.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8670357598021707, "lm_q2_score": 0.8418256393148982, "lm_q1q2_score": 0.7298929328043409}}
{"text": "chapter \\<open> Implication Logic \\label{sec:implicational-intuitionistic-logic} \\<close>\n\ntheory Implication_Logic\n  imports Main\nbegin\n\ntext \\<open> This theory presents the pure implicational fragment of\n       intuitionistic logic. That is to say, this is the fragment of\n       intuitionistic logic containing \\<^emph>\\<open>implication only\\<close>, and no other\n       connectives nor \\<^emph>\\<open>falsum\\<close> (i.e., \\<open>\\<bottom>\\<close>). We shall refer to this logic as\n       \\<^emph>\\<open>implication logic\\<close> in future discussion. \\<close>\n\ntext \\<open> For further reference see @{cite urquhartImplicationalFormulasIntuitionistic1974}.\\<close>\n\nsection \\<open> Axiomatization \\<close>\n\ntext \\<open> Implication logic can be given by the a Hilbert-style  axiom system,\n       following Troelstra and Schwichtenberg\n       @{cite \\<open>\\S 1.3.9, pg. 33\\<close> troelstraBasicProofTheory2000}. \\<close>\n\nclass implication_logic =\n  fixes deduction :: \"'a \\<Rightarrow> bool\" (\"\\<turnstile> _\" [60] 55)\n  fixes implication :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a\" (infixr \"\\<rightarrow>\" 70)\n  assumes axiom_k: \"\\<turnstile> \\<phi> \\<rightarrow> \\<psi> \\<rightarrow> \\<phi>\"\n  assumes axiom_s: \"\\<turnstile> (\\<phi> \\<rightarrow> \\<psi> \\<rightarrow> \\<chi>) \\<rightarrow> (\\<phi> \\<rightarrow> \\<psi>) \\<rightarrow> \\<phi> \\<rightarrow> \\<chi>\"\n  assumes modus_ponens: \"\\<turnstile> \\<phi> \\<rightarrow> \\<psi> \\<Longrightarrow> \\<turnstile> \\<phi> \\<Longrightarrow> \\<turnstile> \\<psi>\"\n\nsection \\<open> Common Rules \\<close>\n\nlemma (in implication_logic) trivial_implication:\n  \"\\<turnstile> \\<phi> \\<rightarrow> \\<phi>\"\n  by (meson axiom_k axiom_s modus_ponens)\n\nlemma (in implication_logic) flip_implication:\n  \"\\<turnstile> (\\<phi> \\<rightarrow> \\<psi> \\<rightarrow> \\<chi>) \\<rightarrow> \\<psi> \\<rightarrow> \\<phi> \\<rightarrow> \\<chi>\"\n  by (meson axiom_k axiom_s modus_ponens)\n\nlemma (in implication_logic) hypothetical_syllogism:\n  \"\\<turnstile> (\\<psi> \\<rightarrow> \\<chi>) \\<rightarrow> (\\<phi> \\<rightarrow> \\<psi>) \\<rightarrow> \\<phi> \\<rightarrow> \\<chi>\"\n  by (meson axiom_k axiom_s modus_ponens)\n\nlemma (in implication_logic) flip_hypothetical_syllogism:\n  \"\\<turnstile> (\\<psi> \\<rightarrow> \\<phi>) \\<rightarrow> (\\<phi> \\<rightarrow> \\<chi>) \\<rightarrow> (\\<psi> \\<rightarrow> \\<chi>)\"\n  using modus_ponens flip_implication hypothetical_syllogism by blast\n\nlemma (in implication_logic) implication_absorption:\n  \"\\<turnstile> (\\<phi> \\<rightarrow> \\<phi> \\<rightarrow> \\<psi>) \\<rightarrow> \\<phi> \\<rightarrow> \\<psi>\"\n  by (meson axiom_k axiom_s modus_ponens)\n\nsection \\<open> Lists of Assumptions \\<close>\n\nsubsection \\<open> List Implication \\<close>\n\ntext \\<open> Implication given a list of assumptions can be expressed recursively \\<close>\n\nprimrec (in implication_logic)\n  list_implication :: \"'a list \\<Rightarrow> 'a \\<Rightarrow> 'a\" (infix \":\\<rightarrow>\" 80) where\n    \"[] :\\<rightarrow> \\<phi> = \\<phi>\"\n  | \"(\\<psi> # \\<Psi>) :\\<rightarrow> \\<phi> = \\<psi> \\<rightarrow> \\<Psi> :\\<rightarrow> \\<phi>\"\n\nsubsection \\<open> Deduction From a List of Assumptions \\label{sec:list-deduction}\\<close>\n\ntext \\<open> Deduction from a list of assumptions can be expressed in terms of\n       @{term \"(:\\<rightarrow>)\"}. \\<close>\n\ndefinition (in implication_logic) list_deduction :: \"'a list \\<Rightarrow> 'a \\<Rightarrow> bool\" (infix \":\\<turnstile>\" 60)\n  where\n    \"\\<Gamma> :\\<turnstile> \\<phi> \\<equiv> \\<turnstile> \\<Gamma> :\\<rightarrow> \\<phi>\"\n\nsubsection \\<open> List Deduction as Implication Logic \\<close>\n\ntext \\<open> The relation @{term \"(:\\<turnstile>)\"} may naturally be interpreted as a\n       @{term \"deduction\"} predicate for an instance of implication logic\n       for a fixed list of assumptions @{term \"\\<Gamma>\"}. \\<close>\n\ntext \\<open> Analogues of the two axioms of implication logic can be\n       naturally stated using list implication. \\<close>\n\nlemma (in implication_logic) list_implication_axiom_k:\n  \"\\<turnstile> \\<phi> \\<rightarrow> \\<Gamma> :\\<rightarrow> \\<phi>\"\n  by (induct \\<Gamma>, (simp, meson axiom_k axiom_s modus_ponens)+)\n\nlemma (in implication_logic) list_implication_axiom_s:\n  \"\\<turnstile> \\<Gamma> :\\<rightarrow> (\\<phi> \\<rightarrow> \\<psi>) \\<rightarrow> \\<Gamma> :\\<rightarrow> \\<phi> \\<rightarrow> \\<Gamma> :\\<rightarrow> \\<psi>\"\n  by (induct \\<Gamma>,\n      (simp, meson axiom_k axiom_s modus_ponens hypothetical_syllogism)+)\n\ntext \\<open> The lemmas @{thm list_implication_axiom_k [no_vars]} and\n       @{thm list_implication_axiom_s [no_vars]} jointly give rise to an\n       interpretation of implication logic, where a list of assumptions\n       @{term \"\\<Gamma>\"} play the role of a \\<^emph>\\<open>background theory\\<close> of @{term \"(:\\<turnstile>)\"}. \\<close>\n\ncontext implication_logic begin\ninterpretation list_deduction_logic:\n   implication_logic \"\\<lambda> \\<phi>. \\<Gamma> :\\<turnstile> \\<phi>\" \"(\\<rightarrow>)\"\nproof qed\n  (meson\n     list_deduction_def\n     axiom_k\n     axiom_s\n     modus_ponens\n     list_implication_axiom_k\n     list_implication_axiom_s)+\nend\n\ntext \\<open> The following \\<^emph>\\<open>weakening\\<close> rule can also be derived. \\<close>\n\nlemma (in implication_logic) list_deduction_weaken:\n  \"\\<turnstile> \\<phi> \\<Longrightarrow> \\<Gamma> :\\<turnstile> \\<phi>\"\n  unfolding list_deduction_def\n  using modus_ponens list_implication_axiom_k\n  by blast\n\ntext \\<open> In the case of the empty list, the converse may be established. \\<close>\n\nlemma (in implication_logic) list_deduction_base_theory [simp]:\n  \"[] :\\<turnstile> \\<phi> \\<equiv> \\<turnstile> \\<phi>\"\n  unfolding list_deduction_def\n  by simp\n\nlemma (in implication_logic) list_deduction_modus_ponens:\n  \"\\<Gamma> :\\<turnstile> \\<phi> \\<rightarrow> \\<psi> \\<Longrightarrow> \\<Gamma> :\\<turnstile> \\<phi> \\<Longrightarrow> \\<Gamma> :\\<turnstile> \\<psi>\"\n  unfolding list_deduction_def\n  using modus_ponens list_implication_axiom_s\n  by blast\n\nsection \\<open> The Deduction Theorem \\<close>\n\ntext \\<open> One result in the meta-theory of implication logic\n       is the \\<^emph>\\<open>deduction theorem\\<close>, which is a mechanism for moving\n       antecedents back and forth from collections of assumptions. \\<close>\n\ntext \\<open> To develop the deduction theorem, the following two lemmas generalize\n       @{thm \"flip_implication\" [no_vars]}. \\<close>\n\nlemma (in implication_logic) list_flip_implication1:\n  \"\\<turnstile> (\\<phi> # \\<Gamma>) :\\<rightarrow> \\<chi> \\<rightarrow> \\<Gamma> :\\<rightarrow> (\\<phi> \\<rightarrow> \\<chi>)\"\n  by (induct \\<Gamma>,\n      (simp,\n         meson\n           axiom_k\n           axiom_s\n           modus_ponens\n           flip_implication\n           hypothetical_syllogism)+)\n\nlemma (in implication_logic) list_flip_implication2:\n  \"\\<turnstile> \\<Gamma> :\\<rightarrow> (\\<phi> \\<rightarrow> \\<chi>) \\<rightarrow> (\\<phi> # \\<Gamma>) :\\<rightarrow> \\<chi>\"\n  by (induct \\<Gamma>,\n      (simp,\n         meson\n           axiom_k\n           axiom_s\n           modus_ponens\n           flip_implication\n           hypothetical_syllogism)+)\n\ntext \\<open> Together the two lemmas above suffice to prove a form of\n       the deduction theorem: \\<close>\n\ntheorem (in implication_logic) list_deduction_theorem:\n  \"(\\<phi> # \\<Gamma>) :\\<turnstile> \\<psi> = \\<Gamma> :\\<turnstile> \\<phi> \\<rightarrow> \\<psi>\"\n  unfolding list_deduction_def\n  by (metis modus_ponens list_flip_implication1 list_flip_implication2)\n\nsection \\<open> Monotonic Growth in Deductive Power \\<close>\n\ntext \\<open> In logic, for two sets of assumptions @{term \"\\<Phi>\"} and @{term \"\\<Psi>\"},\n        if @{term \"\\<Psi> \\<subseteq> \\<Phi>\"} then the latter theory @{term \"\\<Phi>\"} is\n        said to be \\<^emph>\\<open>stronger\\<close> than former theory @{term \"\\<Psi>\"}.\n        In principle, anything a weaker theory can prove a\n        stronger theory can prove. One way of saying this is\n        that deductive power increases monotonically with as the set of\n        underlying assumptions grow. \\<close>\n\ntext \\<open> The monotonic growth of deductive power can be expressed as a\n       meta-theorem in implication logic. \\<close>\n\ntext \\<open> The lemma @{thm \"list_flip_implication2\" [no_vars]} presents a means\n       of \\<^emph>\\<open>introducing\\<close> assumptions into a list of assumptions when\n       those assumptions have been arrived at by an implication. The next\n       lemma presents a means of \\<^emph>\\<open>discharging\\<close> those assumptions, which can\n       be used in the monotonic growth theorem to be proved. \\<close>\n\nlemma (in implication_logic) list_implication_removeAll:\n  \"\\<turnstile> \\<Gamma> :\\<rightarrow> \\<psi> \\<rightarrow> (removeAll \\<phi> \\<Gamma>) :\\<rightarrow> (\\<phi> \\<rightarrow> \\<psi>)\"\nproof -\n  have \"\\<forall> \\<psi>. \\<turnstile> \\<Gamma> :\\<rightarrow> \\<psi> \\<rightarrow> (removeAll \\<phi> \\<Gamma>) :\\<rightarrow> (\\<phi> \\<rightarrow> \\<psi>)\"\n  proof(induct \\<Gamma>)\n    case Nil\n    then show ?case by (simp, meson axiom_k)\n  next\n    case (Cons \\<chi> \\<Gamma>)\n    assume\n      inductive_hypothesis: \"\\<forall> \\<psi>. \\<turnstile> \\<Gamma> :\\<rightarrow> \\<psi> \\<rightarrow> removeAll \\<phi> \\<Gamma> :\\<rightarrow> (\\<phi> \\<rightarrow> \\<psi>)\"\n    moreover {\n      assume \"\\<phi> \\<noteq> \\<chi>\"\n      with inductive_hypothesis\n      have \"\\<forall> \\<psi>. \\<turnstile> (\\<chi> # \\<Gamma>) :\\<rightarrow> \\<psi> \\<rightarrow> removeAll \\<phi> (\\<chi> # \\<Gamma>) :\\<rightarrow> (\\<phi> \\<rightarrow> \\<psi>)\"\n        by (simp, meson modus_ponens hypothetical_syllogism)\n    }\n    moreover {\n      fix \\<psi>\n      assume \\<phi>_equals_\\<chi>: \"\\<phi> = \\<chi>\"\n      moreover with inductive_hypothesis\n      have \"\\<turnstile> \\<Gamma> :\\<rightarrow> (\\<chi> \\<rightarrow> \\<psi>) \\<rightarrow> removeAll \\<phi> (\\<chi> # \\<Gamma>) :\\<rightarrow> (\\<phi> \\<rightarrow> \\<chi> \\<rightarrow> \\<psi>)\" by simp\n      hence \"\\<turnstile> \\<Gamma> :\\<rightarrow> (\\<chi> \\<rightarrow> \\<psi>) \\<rightarrow> removeAll \\<phi> (\\<chi> # \\<Gamma>) :\\<rightarrow> (\\<phi> \\<rightarrow> \\<psi>)\"\n        by (metis\n              calculation\n              modus_ponens\n              implication_absorption\n              list_flip_implication1\n              list_flip_implication2\n              list_implication.simps(2))\n      ultimately have \"\\<turnstile> (\\<chi> # \\<Gamma>) :\\<rightarrow> \\<psi> \\<rightarrow> removeAll \\<phi> (\\<chi> # \\<Gamma>) :\\<rightarrow> (\\<phi> \\<rightarrow> \\<psi>)\"\n        by (simp,\n              metis\n                modus_ponens\n                hypothetical_syllogism\n                list_flip_implication1\n                list_implication.simps(2))\n    }\n    ultimately show ?case by simp\n  qed\n  thus ?thesis by blast\nqed\n\ntext \\<open> From lemma above presents what is needed to prove that deductive power\n       for lists is monotonic. \\<close>\n\ntheorem (in implication_logic) list_implication_monotonic:\n  \"set \\<Sigma> \\<subseteq> set \\<Gamma> \\<Longrightarrow> \\<turnstile> \\<Sigma> :\\<rightarrow> \\<phi> \\<rightarrow> \\<Gamma> :\\<rightarrow> \\<phi>\"\nproof -\n  assume \"set \\<Sigma> \\<subseteq> set \\<Gamma>\"\n  moreover have \"\\<forall> \\<Sigma> \\<phi>. set \\<Sigma> \\<subseteq> set \\<Gamma> \\<longrightarrow> \\<turnstile> \\<Sigma> :\\<rightarrow> \\<phi> \\<rightarrow> \\<Gamma> :\\<rightarrow> \\<phi>\"\n  proof(induct \\<Gamma>)\n    case Nil\n    then show ?case\n      by (metis\n            list_implication.simps(1)\n            list_implication_axiom_k\n            set_empty\n            subset_empty)\n  next\n    case (Cons \\<psi> \\<Gamma>)\n    assume\n      inductive_hypothesis: \"\\<forall>\\<Sigma> \\<phi>. set \\<Sigma> \\<subseteq> set \\<Gamma> \\<longrightarrow> \\<turnstile> \\<Sigma> :\\<rightarrow> \\<phi> \\<rightarrow> \\<Gamma> :\\<rightarrow> \\<phi>\"\n    {\n      fix \\<Sigma>\n      fix \\<phi>\n      assume \\<Sigma>_subset_relation: \"set \\<Sigma> \\<subseteq> set (\\<psi> # \\<Gamma>)\"\n      have \"\\<turnstile> \\<Sigma> :\\<rightarrow> \\<phi> \\<rightarrow> (\\<psi> # \\<Gamma>) :\\<rightarrow> \\<phi>\"\n      proof -\n        {\n          assume \"set \\<Sigma> \\<subseteq> set \\<Gamma>\"\n          hence ?thesis\n            by (metis\n                    inductive_hypothesis\n                    axiom_k modus_ponens\n                    flip_implication\n                    list_implication.simps(2))\n        }\n        moreover {\n          let ?\\<Delta> = \"removeAll \\<psi> \\<Sigma>\"\n          assume \"\\<not> (set \\<Sigma> \\<subseteq> set \\<Gamma>)\"\n          hence \"set ?\\<Delta> \\<subseteq> set \\<Gamma>\"\n            using \\<Sigma>_subset_relation by auto\n          hence \"\\<turnstile> ?\\<Delta> :\\<rightarrow> (\\<psi> \\<rightarrow> \\<phi>) \\<rightarrow> \\<Gamma> :\\<rightarrow> (\\<psi> \\<rightarrow> \\<phi>)\"\n            using inductive_hypothesis by auto\n          hence \"\\<turnstile> ?\\<Delta> :\\<rightarrow> (\\<psi> \\<rightarrow> \\<phi>) \\<rightarrow> (\\<psi> # \\<Gamma>) :\\<rightarrow> \\<phi>\"\n            by (metis\n                    modus_ponens\n                    flip_implication\n                    list_flip_implication2\n                    list_implication.simps(2))\n          moreover have \"\\<turnstile> \\<Sigma> :\\<rightarrow> \\<phi> \\<rightarrow> ?\\<Delta> :\\<rightarrow> (\\<psi> \\<rightarrow> \\<phi>)\"\n            by (simp add: local.list_implication_removeAll)\n          ultimately have ?thesis\n            using modus_ponens hypothetical_syllogism by blast\n        }\n        ultimately show ?thesis by blast\n     qed\n    }\n    thus ?case by simp\n  qed\n  ultimately show ?thesis by simp\nqed\n\ntext \\<open> A direct consequence is that deduction from lists of assumptions\n       is monotonic as well: \\<close>\n\ntheorem (in implication_logic) list_deduction_monotonic:\n  \"set \\<Sigma> \\<subseteq> set \\<Gamma> \\<Longrightarrow> \\<Sigma> :\\<turnstile> \\<phi> \\<Longrightarrow> \\<Gamma> :\\<turnstile> \\<phi>\"\n  unfolding list_deduction_def\n  using modus_ponens list_implication_monotonic\n  by blast\n\nsection \\<open> The Deduction Theorem Revisited \\<close>\n\ntext \\<open> The monotonic nature of deduction allows us to prove another form of\n       the deduction theorem, where the assumption being discharged is\n       completely removed from the list of assumptions. \\<close>\n\ntheorem (in implication_logic) alternate_list_deduction_theorem:\n    \"(\\<phi> # \\<Gamma>) :\\<turnstile> \\<psi> = (removeAll \\<phi> \\<Gamma>) :\\<turnstile> \\<phi> \\<rightarrow> \\<psi>\"\n  by (metis\n        list_deduction_def\n        modus_ponens\n        filter_is_subset\n        list_deduction_monotonic\n        list_deduction_theorem\n        list_implication_removeAll\n        removeAll.simps(2)\n        removeAll_filter_not_eq)\n\nsection \\<open> Reflection \\<close>\n\ntext \\<open> In logic the \\<^emph>\\<open>reflection\\<close> principle sometimes refers to when\n       a collection of assumptions can deduce any of its members. It is\n       automatically derivable from @{thm \"list_deduction_monotonic\" [no_vars]} among\n       the other rules provided. \\<close>\n\nlemma (in implication_logic) list_deduction_reflection:\n  \"\\<phi> \\<in> set \\<Gamma> \\<Longrightarrow> \\<Gamma> :\\<turnstile> \\<phi>\"\n  by (metis\n        list_deduction_def\n        insert_subset\n        list.simps(15)\n        list_deduction_monotonic\n        list_implication.simps(2)\n        list_implication_axiom_k\n        order_refl)\n\nsection \\<open> The Cut Rule \\<close>\n\ntext \\<open> \\<^emph>\\<open>Cut\\<close> is a rule commonly presented in sequent calculi, dating\n       back to Gerhard Gentzen's \\<^emph>\\<open>Investigations in Logical Deduction\\<close> (1935)\n       @{cite gentzenUntersuchungenUeberLogische1935}\\<close>\n\ntext \\<open> The cut rule is not generally necessary in sequent calculi. It can\n       often be shown that the rule can be eliminated without reducing the\n       power of the underlying logic. However, as demonstrated by George\n       Boolos' \\<^emph>\\<open>Don't Eliminate Cut\\<close> (1984) @{cite boolosDonEliminateCut1984},\n       removing the rule can often lead to very inefficient proof systems. \\<close>\n\ntext \\<open> Here the rule is presented just as a meta theorem. \\<close>\n\ntheorem (in implication_logic) list_deduction_cut_rule:\n  \"(\\<phi> # \\<Gamma>) :\\<turnstile> \\<psi> \\<Longrightarrow> \\<Delta> :\\<turnstile> \\<phi> \\<Longrightarrow> \\<Gamma> @ \\<Delta> :\\<turnstile> \\<psi>\"\n  by (metis\n        (no_types, lifting)\n        Un_upper1\n        Un_upper2\n        list_deduction_modus_ponens\n        list_deduction_monotonic\n        list_deduction_theorem\n        set_append)\n\ntext \\<open> The cut rule can also be strengthened to entire lists of propositions. \\<close>\n\ntheorem (in implication_logic) strong_list_deduction_cut_rule:\n    \"(\\<Phi> @ \\<Gamma>) :\\<turnstile> \\<psi> \\<Longrightarrow> \\<forall> \\<phi> \\<in> set \\<Phi>. \\<Delta> :\\<turnstile> \\<phi> \\<Longrightarrow> \\<Gamma> @ \\<Delta> :\\<turnstile> \\<psi>\"\nproof -\n  have \"\\<forall> \\<psi>. (\\<Phi> @ \\<Gamma> :\\<turnstile> \\<psi> \\<longrightarrow> (\\<forall> \\<phi> \\<in> set \\<Phi>. \\<Delta> :\\<turnstile> \\<phi>) \\<longrightarrow> \\<Gamma> @ \\<Delta> :\\<turnstile> \\<psi>)\"\n    proof(induct \\<Phi>)\n      case Nil\n      then show ?case\n        by (metis\n                Un_iff\n                append.left_neutral\n                list_deduction_monotonic\n                set_append\n                subsetI)\n    next\n      case (Cons \\<chi> \\<Phi>) assume inductive_hypothesis:\n         \"\\<forall> \\<psi>. \\<Phi> @ \\<Gamma> :\\<turnstile> \\<psi> \\<longrightarrow> (\\<forall>\\<phi>\\<in>set \\<Phi>. \\<Delta> :\\<turnstile> \\<phi>) \\<longrightarrow> \\<Gamma> @ \\<Delta> :\\<turnstile> \\<psi>\"\n      {\n        fix \\<psi> \\<chi>\n        assume \"(\\<chi> # \\<Phi>) @ \\<Gamma> :\\<turnstile> \\<psi>\"\n        hence A: \"\\<Phi> @ \\<Gamma> :\\<turnstile> \\<chi> \\<rightarrow> \\<psi>\" using list_deduction_theorem by auto\n        assume \"\\<forall>\\<phi> \\<in> set (\\<chi> # \\<Phi>). \\<Delta> :\\<turnstile> \\<phi>\"\n        hence B: \"\\<forall> \\<phi> \\<in> set \\<Phi>. \\<Delta> :\\<turnstile> \\<phi>\"\n          and C: \"\\<Delta> :\\<turnstile> \\<chi>\" by auto\n        from A B have \"\\<Gamma> @ \\<Delta> :\\<turnstile> \\<chi> \\<rightarrow> \\<psi>\" using inductive_hypothesis by blast\n        with C have \"\\<Gamma> @ \\<Delta> :\\<turnstile> \\<psi>\"\n          by (meson\n                list.set_intros(1)\n                list_deduction_cut_rule\n                list_deduction_modus_ponens\n                list_deduction_reflection)\n      }\n      thus ?case by simp\n    qed\n    moreover assume \"(\\<Phi> @ \\<Gamma>) :\\<turnstile> \\<psi>\"\n  moreover assume \"\\<forall> \\<phi> \\<in> set \\<Phi>. \\<Delta> :\\<turnstile> \\<phi>\"\n  ultimately show ?thesis by blast\nqed\n\nsection \\<open> Sets of Assumptions \\<close>\n\ntext \\<open> While deduction in terms of lists of assumptions is straight-forward\n       to define, deduction (and the \\<^emph>\\<open>deduction theorem\\<close>) is commonly given in\n       terms of \\<^emph>\\<open>sets\\<close> of propositions.  This formulation is suited to\n       establishing strong completeness theorems and compactness theorems. \\<close>\n\ntext \\<open> The presentation of deduction from a set follows the presentation of\n       list deduction given for \\<^term>\\<open>(:\\<turnstile>)\\<close>. \\<close>\n\nsection \\<open> Definition of Deduction \\<close>\n\ntext \\<open> Just as deduction from a list \\<^term>\\<open>(:\\<turnstile>)\\<close> can be defined in\n       terms of \\<^term>\\<open>(:\\<rightarrow>)\\<close>, deduction from a \\<^emph>\\<open>set\\<close> of assumptions\n       can be expressed in terms of \\<^term>\\<open>(:\\<turnstile>)\\<close>. \\<close>\n\ndefinition (in implication_logic) set_deduction :: \"'a set \\<Rightarrow> 'a \\<Rightarrow> bool\" (infix \"\\<tturnstile>\" 60)\n  where\n    \"\\<Gamma> \\<tturnstile> \\<phi> \\<equiv> \\<exists> \\<Psi>. set \\<Psi>  \\<subseteq> \\<Gamma> \\<and> \\<Psi> :\\<turnstile> \\<phi>\"\n\nsubsection \\<open> Interpretation as Implication Logic \\<close>\n\ntext \\<open> As in the case of @{term \"(:\\<turnstile>)\"}, the relation @{term \"(\\<tturnstile>)\"} may be\n       interpreted as @{term \"deduction\"} predicate for a fixed set of\n       assumptions @{term \"\\<Gamma>\"}. \\<close>\n\ntext \\<open> The following lemma is given in order to establish this, which asserts\n       that every implication logic tautology @{term \"\\<turnstile> \\<phi>\"}\n       is also a tautology for @{term \"\\<Gamma> \\<tturnstile> \\<phi>\"}. \\<close>\n\nlemma (in implication_logic) set_deduction_weaken:\n  \"\\<turnstile> \\<phi> \\<Longrightarrow> \\<Gamma> \\<tturnstile> \\<phi>\"\n  using list_deduction_base_theory set_deduction_def by fastforce\n\ntext \\<open> In the case of the empty set, the converse may be established. \\<close>\n\nlemma (in implication_logic) set_deduction_base_theory:\n  \"{} \\<tturnstile> \\<phi> \\<equiv> \\<turnstile> \\<phi>\"\n  using list_deduction_base_theory set_deduction_def by auto\n\ntext \\<open> Next, a form of \\<^emph>\\<open>modus ponens\\<close> is provided for @{term \"(\\<tturnstile>)\"}. \\<close>\n\nlemma (in implication_logic) set_deduction_modus_ponens:\n   \"\\<Gamma> \\<tturnstile> \\<phi> \\<rightarrow> \\<psi> \\<Longrightarrow> \\<Gamma> \\<tturnstile> \\<phi> \\<Longrightarrow> \\<Gamma> \\<tturnstile> \\<psi>\"\nproof -\n  assume \"\\<Gamma> \\<tturnstile> \\<phi> \\<rightarrow> \\<psi>\"\n  then obtain \\<Phi> where A: \"set \\<Phi> \\<subseteq> \\<Gamma>\" and B: \"\\<Phi> :\\<turnstile> \\<phi> \\<rightarrow> \\<psi>\"\n    using set_deduction_def by blast\n  assume \"\\<Gamma> \\<tturnstile> \\<phi>\"\n  then obtain \\<Psi> where C: \"set \\<Psi> \\<subseteq> \\<Gamma>\" and D: \"\\<Psi> :\\<turnstile> \\<phi>\"\n    using set_deduction_def by blast\n  from B D have \"\\<Phi> @ \\<Psi> :\\<turnstile> \\<psi>\"\n    using list_deduction_cut_rule list_deduction_theorem by blast\n  moreover from A C have \"set (\\<Phi> @ \\<Psi>) \\<subseteq> \\<Gamma>\" by simp\n  ultimately show ?thesis\n    using set_deduction_def by blast\nqed\n\ncontext implication_logic begin\ninterpretation set_deduction_logic:\n  implication_logic \"\\<lambda> \\<phi>. \\<Gamma> \\<tturnstile> \\<phi>\" \"(\\<rightarrow>)\"\nproof\n   fix \\<phi> \\<psi>\n   show \"\\<Gamma> \\<tturnstile> \\<phi> \\<rightarrow> \\<psi> \\<rightarrow> \\<phi>\"  by (metis axiom_k set_deduction_weaken)\nnext\n    fix \\<phi> \\<psi> \\<chi>\n    show \"\\<Gamma> \\<tturnstile> (\\<phi> \\<rightarrow> \\<psi> \\<rightarrow> \\<chi>) \\<rightarrow> (\\<phi> \\<rightarrow> \\<psi>) \\<rightarrow> \\<phi> \\<rightarrow> \\<chi>\"\n      by (metis axiom_s set_deduction_weaken)\nnext\n    fix \\<phi> \\<psi>\n    show \"\\<Gamma> \\<tturnstile> \\<phi> \\<rightarrow> \\<psi> \\<Longrightarrow> \\<Gamma> \\<tturnstile> \\<phi> \\<Longrightarrow> \\<Gamma> \\<tturnstile> \\<psi>\"\n      using set_deduction_modus_ponens by metis\nqed\nend\n\nsection \\<open> The Deduction Theorem \\<close>\n\ntext \\<open> The next result gives the deduction theorem for @{term \"(\\<tturnstile>)\"}. \\<close>\n\ntheorem (in implication_logic) set_deduction_theorem:\n  \"insert \\<phi> \\<Gamma> \\<tturnstile> \\<psi> = \\<Gamma> \\<tturnstile> \\<phi> \\<rightarrow> \\<psi>\"\nproof -\n  have \"\\<Gamma> \\<tturnstile> \\<phi> \\<rightarrow> \\<psi> \\<Longrightarrow> insert \\<phi> \\<Gamma> \\<tturnstile> \\<psi>\"\n    by (metis\n            set_deduction_def\n            insert_mono\n            list.simps(15)\n            list_deduction_theorem)\n  moreover {\n    assume \"insert \\<phi> \\<Gamma> \\<tturnstile> \\<psi>\"\n    then obtain \\<Phi> where \"set \\<Phi> \\<subseteq> insert \\<phi> \\<Gamma>\" and \"\\<Phi> :\\<turnstile> \\<psi>\"\n      using set_deduction_def by auto\n    hence \"set (removeAll \\<phi> \\<Phi>) \\<subseteq> \\<Gamma>\" by auto\n    moreover from \\<open>\\<Phi> :\\<turnstile> \\<psi>\\<close> have \"removeAll \\<phi> \\<Phi> :\\<turnstile> \\<phi> \\<rightarrow> \\<psi>\"\n      using modus_ponens list_implication_removeAll list_deduction_def\n      by blast\n    ultimately have \"\\<Gamma> \\<tturnstile> \\<phi> \\<rightarrow> \\<psi>\"\n      using set_deduction_def by blast\n  }\n  ultimately show \"insert \\<phi> \\<Gamma> \\<tturnstile> \\<psi> = \\<Gamma> \\<tturnstile> \\<phi> \\<rightarrow> \\<psi>\" by metis\nqed\n\nsection \\<open> Monotonic Growth in Deductive Power \\<close>\n\ntext \\<open> In contrast to the @{term \"(:\\<turnstile>)\"} relation, the proof that the\n       deductive power of @{term \"(\\<tturnstile>)\"} grows monotonically with its\n       assumptions may be fully automated. \\<close>\n\ntheorem set_deduction_monotonic:\n  \"\\<Sigma> \\<subseteq> \\<Gamma> \\<Longrightarrow> \\<Sigma> \\<tturnstile> \\<phi> \\<Longrightarrow> \\<Gamma> \\<tturnstile> \\<phi>\"\n  by (meson dual_order.trans set_deduction_def)\n\nsection \\<open> The Deduction Theorem Revisited \\<close>\n\ntext \\<open> As a consequence of the fact that @{thm \"set_deduction_monotonic\" [no_vars]}\n       is automatically provable, an alternate \\<^emph>\\<open>deduction theorem\\<close> where the\n       discharged assumption is completely removed from the set of assumptions\n       is just a consequence of the more conventional\n       @{thm \"set_deduction_theorem\" [no_vars]} rule and some basic set identities. \\<close>\n\ntheorem (in implication_logic) alternate_set_deduction_theorem:\n  \"insert \\<phi> \\<Gamma> \\<tturnstile> \\<psi> = \\<Gamma> - {\\<phi>} \\<tturnstile> \\<phi> \\<rightarrow> \\<psi>\"\n  by (metis insert_Diff_single set_deduction_theorem)\n\nsection \\<open> Reflection \\<close>\n\ntext \\<open> Just as in the case of @{term \"(:\\<turnstile>)\"}, deduction from sets of\n       assumptions makes true the \\<^emph>\\<open>reflection principle\\<close> and is\n       automatically provable. \\<close>\n\ntheorem (in implication_logic) set_deduction_reflection:\n  \"\\<phi> \\<in> \\<Gamma> \\<Longrightarrow> \\<Gamma> \\<tturnstile> \\<phi>\"\n  by (metis\n          Set.set_insert\n          list_implication.simps(1)\n          list_implication_axiom_k\n          set_deduction_theorem\n          set_deduction_weaken)\n\nsection \\<open> The Cut Rule \\<close>\n\ntext \\<open> The final principle of @{term \"(\\<tturnstile>)\"} presented is the \\<^emph>\\<open>cut rule\\<close>. \\<close>\n\ntext \\<open> First, the weak form of the rule is established. \\<close>\n\ntheorem (in implication_logic) set_deduction_cut_rule:\n  \"insert \\<phi> \\<Gamma> \\<tturnstile> \\<psi> \\<Longrightarrow> \\<Delta> \\<tturnstile> \\<phi> \\<Longrightarrow> \\<Gamma> \\<union> \\<Delta> \\<tturnstile> \\<psi>\"\nproof -\n  assume \"insert \\<phi> \\<Gamma> \\<tturnstile> \\<psi>\"\n  hence \"\\<Gamma> \\<tturnstile> \\<phi> \\<rightarrow> \\<psi>\" using set_deduction_theorem by auto\n  hence \"\\<Gamma> \\<union> \\<Delta> \\<tturnstile> \\<phi> \\<rightarrow> \\<psi>\" using set_deduction_def by auto\n  moreover assume \"\\<Delta> \\<tturnstile> \\<phi>\"\n  hence \"\\<Gamma> \\<union> \\<Delta> \\<tturnstile> \\<phi>\" using set_deduction_def by auto\n  ultimately show ?thesis using set_deduction_modus_ponens by metis\nqed\n\ntext \\<open> Another lemma is shown next in order to establish the strong form\n       of the cut rule. The lemma shows the existence of a \\<^emph>\\<open>covering list\\<close> of\n       assumptions \\<^term>\\<open>\\<Psi>\\<close> in the event some set of assumptions\n       \\<^term>\\<open>\\<Delta>\\<close> proves everything in a finite set of assumptions\n       \\<^term>\\<open>\\<Phi>\\<close>. \\<close>\n\nlemma (in implication_logic) finite_set_deduction_list_deduction:\n  assumes \"finite \\<Phi>\"\n  and \"\\<forall> \\<phi> \\<in> \\<Phi>. \\<Delta> \\<tturnstile> \\<phi>\"\n  shows \"\\<exists>\\<Psi>. set \\<Psi> \\<subseteq> \\<Delta> \\<and> (\\<forall>\\<phi> \\<in> \\<Phi>. \\<Psi> :\\<turnstile> \\<phi>)\"\n  using assms\nproof(induct \\<Phi> rule: finite_induct)\n  case empty thus ?case by (metis all_not_in_conv empty_subsetI set_empty)\nnext\n  case (insert \\<chi> \\<Phi>)\n  assume \"\\<forall>\\<phi> \\<in> \\<Phi>. \\<Delta> \\<tturnstile> \\<phi> \\<Longrightarrow> \\<exists>\\<Psi>. set \\<Psi> \\<subseteq> \\<Delta> \\<and> (\\<forall>\\<phi> \\<in> \\<Phi>. \\<Psi> :\\<turnstile> \\<phi>)\"\n     and \"\\<forall>\\<phi> \\<in> insert \\<chi> \\<Phi>. \\<Delta> \\<tturnstile> \\<phi>\"\n  hence \"\\<exists>\\<Psi>. set \\<Psi> \\<subseteq> \\<Delta> \\<and> (\\<forall>\\<phi>\\<in>\\<Phi>. \\<Psi> :\\<turnstile> \\<phi>)\" and \"\\<Delta> \\<tturnstile> \\<chi>\" by simp+\n  then obtain \\<Psi>\\<^sub>1 \\<Psi>\\<^sub>2 where\n    \"set (\\<Psi>\\<^sub>1 @ \\<Psi>\\<^sub>2) \\<subseteq> \\<Delta>\"\n    \"\\<forall>\\<phi> \\<in> \\<Phi>. \\<Psi>\\<^sub>1 :\\<turnstile> \\<phi>\"\n    \"\\<Psi>\\<^sub>2 :\\<turnstile> \\<chi>\"\n    using set_deduction_def by auto\n  moreover from this have \"\\<forall>\\<phi> \\<in> (insert \\<chi> \\<Phi>). \\<Psi>\\<^sub>1 @ \\<Psi>\\<^sub>2 :\\<turnstile> \\<phi>\"\n    by (metis\n            insert_iff\n            le_sup_iff\n            list_deduction_monotonic\n            order_refl set_append)\n  ultimately show ?case by blast\nqed\n\ntext \\<open> With @{thm finite_set_deduction_list_deduction [no_vars]} the strengthened\n       form of the cut rule can be given. \\<close>\n\ntheorem (in implication_logic) strong_set_deduction_cut_rule:\n  assumes \"\\<Phi> \\<union> \\<Gamma> \\<tturnstile> \\<psi>\"\n  and \"\\<forall> \\<phi> \\<in> \\<Phi>. \\<Delta> \\<tturnstile> \\<phi>\"\n  shows \"\\<Gamma> \\<union> \\<Delta> \\<tturnstile> \\<psi>\"\nproof -\n  obtain \\<Sigma> where\n    A: \"set \\<Sigma>  \\<subseteq> \\<Phi> \\<union> \\<Gamma>\" and\n    B: \"\\<Sigma> :\\<turnstile> \\<psi>\"\n    using assms(1) set_deduction_def\n    by auto+\n  obtain \\<Phi>' \\<Gamma>' where\n    C: \"set \\<Phi>' = set \\<Sigma> \\<inter> \\<Phi>\" and\n    D: \"set \\<Gamma>' = set \\<Sigma> \\<inter> \\<Gamma>\"\n    by (metis inf_sup_aci(1) inter_set_filter)+\n  then have \"set (\\<Phi>' @ \\<Gamma>') = set \\<Sigma>\" using A by auto\n  hence E: \"\\<Phi>' @ \\<Gamma>' :\\<turnstile> \\<psi>\" using B list_deduction_monotonic by blast\n  hence \"\\<forall> \\<phi> \\<in> set \\<Phi>'. \\<Delta> \\<tturnstile> \\<phi>\" using assms(2) C by auto\n  from this obtain \\<Delta>' where \"set \\<Delta>' \\<subseteq> \\<Delta>\" and \"\\<forall> \\<phi> \\<in> set \\<Phi>'. \\<Delta>' :\\<turnstile> \\<phi>\"\n    using finite_set_deduction_list_deduction by blast\n  with strong_list_deduction_cut_rule D E\n  have \"set (\\<Gamma>' @ \\<Delta>') \\<subseteq> \\<Gamma> \\<union> \\<Delta>\" and \"\\<Gamma>' @ \\<Delta>' :\\<turnstile> \\<psi>\" by auto\n  thus ?thesis using set_deduction_def by blast\nqed\n\nsection \\<open>Maximally Consistent Sets For Implication Logic \\label{sec:implicational-maximally-consistent-sets}\\<close>\n\ntext \\<open> \\<^emph>\\<open>Maximally Consistent Sets\\<close> are a common construction for proving\n       completeness of logical calculi.  For a classic presentation, see\n       Dirk van Dalen's \\<^emph>\\<open>Logic and Structure\\<close> (2013, \\S1.5, pgs. 42--45)\n       @{cite vandalenLogicStructure2013}. \\<close>\n\ntext \\<open> Maximally consistent sets will form the foundation of all of the\n       model theory we will employ in this text. In fact, apart from\n       classical logic semantics, conventional model theory will not be\n       used at all. \\<close>\n\ntext \\<open> The models we are centrally concerned are derived from maximally\n       consistent sets. These include probability measures used in completeness\n       theorems of probability logic found in \\S\\ref{sec:probability-logic-completeness},\n       as well as arbitrage protection and trading strategies stipulated by\n       our formulation of the \\<^emph>\\<open>Dutch Book Theorem\\<close> we present in\n       \\S\\ref{chap:dutch-book-theorem}. \\<close>\n\ntext \\<open> Since implication logic does not have \\<^emph>\\<open>falsum\\<close>, consistency is\n       defined relative to a formula \\<^term>\\<open>\\<phi>\\<close>. \\<close>\n\ndefinition (in implication_logic)\n  formula_consistent :: \"'a \\<Rightarrow> 'a set \\<Rightarrow> bool\" (\"_-consistent _\" [100] 100)\n  where\n    [simp]: \"\\<phi>-consistent \\<Gamma> \\<equiv> \\<not> (\\<Gamma> \\<tturnstile> \\<phi>)\"\n\ntext \\<open> Since consistency is defined relative to some \\<^term>\\<open>\\<phi>\\<close>,\n       \\<^emph>\\<open>maximal consistency\\<close> is presented as asserting that either\n       \\<^term>\\<open>\\<psi>\\<close> or \\<^term>\\<open>\\<psi> \\<rightarrow> \\<phi>\\<close> is in the consistent set \\<^term>\\<open>\\<Gamma>\\<close>,\n       for all \\<^term>\\<open>\\<psi>\\<close>.  This coincides with the traditional definition in\n       classical logic when \\<^term>\\<open>\\<phi>\\<close> is \\<^emph>\\<open>falsum\\<close>. \\<close>\n\ndefinition (in implication_logic)\n  formula_maximally_consistent_set_def :: \"'a \\<Rightarrow> 'a set \\<Rightarrow> bool\" (\"_-MCS _\" [100] 100)\n  where\n    [simp]: \"\\<phi>-MCS \\<Gamma> \\<equiv> (\\<phi>-consistent \\<Gamma>) \\<and> (\\<forall> \\<psi>. \\<psi> \\<in> \\<Gamma> \\<or> (\\<psi> \\<rightarrow> \\<phi>) \\<in> \\<Gamma>)\"\n\ntext \\<open> Every consistent set \\<^term>\\<open>\\<Gamma>\\<close> may be extended to a maximally\n       consistent set. \\<close>\n\ntext \\<open> However, no assumption is made regarding the cardinality of the types\n       of an instance of @{class implication_logic}. \\<close>\n\ntext \\<open> As a result, typical proofs that assume a countable domain are not\n       suitable.  Our proof leverages \\<^emph>\\<open>Zorn's lemma\\<close>. \\<close>\n\nlemma (in implication_logic) formula_consistent_extension:\n  assumes \"\\<phi>-consistent \\<Gamma>\"\n  shows \"(\\<phi>-consistent (insert \\<psi> \\<Gamma>)) \\<or> (\\<phi>-consistent (insert (\\<psi> \\<rightarrow> \\<phi>) \\<Gamma>))\"\nproof -\n  {\n    assume \"\\<not> \\<phi>-consistent insert \\<psi> \\<Gamma>\"\n    hence \"\\<Gamma> \\<tturnstile> \\<psi> \\<rightarrow> \\<phi>\"\n      using set_deduction_theorem\n      unfolding formula_consistent_def\n      by simp\n    hence \"\\<phi>-consistent insert (\\<psi> \\<rightarrow> \\<phi>) \\<Gamma>\"\n     by (metis Un_absorb assms formula_consistent_def set_deduction_cut_rule)\n  }\n  thus ?thesis by blast\nqed\n\ntheorem (in implication_logic) formula_maximally_consistent_extension:\n  assumes \"\\<phi>-consistent \\<Gamma>\"\n  shows \"\\<exists> \\<Omega>. (\\<phi>-MCS \\<Omega>) \\<and> \\<Gamma> \\<subseteq> \\<Omega>\"\nproof -\n  let ?\\<Gamma>_extensions = \"{\\<Sigma>. (\\<phi>-consistent \\<Sigma>) \\<and> \\<Gamma> \\<subseteq> \\<Sigma>}\"\n  have \"\\<exists> \\<Omega> \\<in> ?\\<Gamma>_extensions. \\<forall>\\<Sigma> \\<in> ?\\<Gamma>_extensions. \\<Omega> \\<subseteq> \\<Sigma> \\<longrightarrow> \\<Sigma> = \\<Omega>\"\n  proof (rule subset_Zorn)\n    fix \\<C> :: \"'a set set\"\n    assume subset_chain_\\<C>: \"subset.chain ?\\<Gamma>_extensions \\<C>\"\n    hence \\<C>:  \"\\<forall> \\<Sigma> \\<in> \\<C>. \\<Gamma> \\<subseteq> \\<Sigma>\" \"\\<forall> \\<Sigma> \\<in> \\<C>. \\<phi>-consistent \\<Sigma>\"\n      unfolding subset.chain_def\n      by blast+\n    show \"\\<exists> \\<Omega> \\<in> ?\\<Gamma>_extensions. \\<forall> \\<Sigma> \\<in> \\<C>. \\<Sigma> \\<subseteq> \\<Omega>\"\n    proof cases\n      assume \"\\<C> = {}\" thus ?thesis using assms by blast\n    next\n      let ?\\<Omega> = \"\\<Union> \\<C>\"\n      assume \"\\<C> \\<noteq> {}\"\n      hence \"\\<Gamma> \\<subseteq> ?\\<Omega>\" by (simp add: \\<C>(1) less_eq_Sup)\n      moreover have \"\\<phi>-consistent ?\\<Omega>\"\n      proof -\n        {\n          assume \"\\<not> \\<phi>-consistent ?\\<Omega>\"\n          then obtain \\<omega> where \\<omega>:\n            \"finite \\<omega>\"\n            \"\\<omega> \\<subseteq> ?\\<Omega>\"\n            \"\\<not> \\<phi>-consistent \\<omega>\"\n            unfolding\n              formula_consistent_def\n              set_deduction_def\n            by auto\n          from \\<omega>(1) \\<omega>(2) have \"\\<exists> \\<Sigma> \\<in> \\<C>. \\<omega> \\<subseteq> \\<Sigma>\"\n          proof (induct \\<omega> rule: finite_induct)\n            case empty thus ?case using \\<open>\\<C> \\<noteq> {}\\<close> by blast\n          next\n            case (insert \\<psi> \\<omega>)\n            from this obtain \\<Sigma>\\<^sub>1 \\<Sigma>\\<^sub>2 where\n              \\<Sigma>\\<^sub>1:\n                  \"\\<omega> \\<subseteq> \\<Sigma>\\<^sub>1\"\n                  \"\\<Sigma>\\<^sub>1 \\<in> \\<C>\"\n              and \\<Sigma>\\<^sub>2:\n                  \"\\<psi> \\<in> \\<Sigma>\\<^sub>2\"\n                  \"\\<Sigma>\\<^sub>2 \\<in> \\<C>\"\n              by auto\n            hence \"\\<Sigma>\\<^sub>1 \\<subseteq> \\<Sigma>\\<^sub>2 \\<or> \\<Sigma>\\<^sub>2 \\<subseteq> \\<Sigma>\\<^sub>1\"\n              using subset_chain_\\<C>\n              unfolding subset.chain_def\n              by blast\n            hence \"(insert \\<psi> \\<omega>) \\<subseteq> \\<Sigma>\\<^sub>1 \\<or> (insert \\<psi> \\<omega>) \\<subseteq> \\<Sigma>\\<^sub>2\"\n              using \\<Sigma>\\<^sub>1 \\<Sigma>\\<^sub>2 by blast\n            thus ?case using \\<Sigma>\\<^sub>1 \\<Sigma>\\<^sub>2 by blast\n          qed\n          hence \"\\<exists> \\<Sigma> \\<in> \\<C>. (\\<phi>-consistent \\<Sigma>) \\<and> \\<not> (\\<phi>-consistent \\<Sigma>)\"\n            using \\<C>(2) \\<omega>(3)\n            unfolding\n              formula_consistent_def\n              set_deduction_def\n            by auto\n          hence \"False\" by auto\n        }\n        thus ?thesis by blast\n      qed\n      ultimately show ?thesis by blast\n    qed\n  qed\n  then obtain \\<Omega> where \\<Omega>:\n    \"\\<Omega> \\<in> ?\\<Gamma>_extensions\"\n    \"\\<forall>\\<Sigma> \\<in> ?\\<Gamma>_extensions. \\<Omega> \\<subseteq> \\<Sigma> \\<longrightarrow> \\<Sigma> = \\<Omega>\"\n    by auto+\n  {\n    fix \\<psi>\n    have \"(\\<phi>-consistent insert \\<psi> \\<Omega>) \\<or> (\\<phi>-consistent insert (\\<psi> \\<rightarrow> \\<phi>) \\<Omega>)\"\n         \"\\<Gamma> \\<subseteq> insert \\<psi> \\<Omega>\"\n         \"\\<Gamma> \\<subseteq> insert (\\<psi> \\<rightarrow> \\<phi>) \\<Omega>\"\n      using \\<Omega>(1) formula_consistent_extension formula_consistent_def\n      by auto\n    hence \"insert \\<psi> \\<Omega> \\<in> ?\\<Gamma>_extensions\n             \\<or> insert (\\<psi> \\<rightarrow> \\<phi>) \\<Omega> \\<in> ?\\<Gamma>_extensions\"\n      by blast\n    hence \"\\<psi> \\<in> \\<Omega> \\<or> (\\<psi> \\<rightarrow> \\<phi>) \\<in> \\<Omega>\" using \\<Omega>(2) by blast\n  }\n  thus ?thesis\n    using \\<Omega>(1)\n    unfolding formula_maximally_consistent_set_def_def\n    by blast\nqed\n\ntext \\<open> Finally, maximally consistent sets contain anything that can be deduced\n       from them, and model a form of \\<^emph>\\<open>modus ponens\\<close>. \\<close>\n\nlemma (in implication_logic) formula_maximally_consistent_set_def_reflection:\n  \"\\<phi>-MCS \\<Gamma> \\<Longrightarrow> \\<psi> \\<in> \\<Gamma> = \\<Gamma> \\<tturnstile> \\<psi>\"\nproof -\n  assume \"\\<phi>-MCS \\<Gamma>\"\n  {\n    assume \"\\<Gamma> \\<tturnstile> \\<psi>\"\n    moreover from \\<open>\\<phi>-MCS \\<Gamma>\\<close> have \"\\<psi> \\<in> \\<Gamma> \\<or> (\\<psi> \\<rightarrow> \\<phi>) \\<in> \\<Gamma>\" \"\\<not> \\<Gamma> \\<tturnstile> \\<phi>\"\n      unfolding\n        formula_maximally_consistent_set_def_def\n        formula_consistent_def\n      by auto\n    ultimately have \"\\<psi> \\<in> \\<Gamma>\"\n      using set_deduction_reflection set_deduction_modus_ponens\n      by metis\n  }\n  thus \"\\<psi> \\<in> \\<Gamma> = \\<Gamma> \\<tturnstile> \\<psi>\"\n    using set_deduction_reflection\n    by metis\nqed\n\ntheorem (in implication_logic) formula_maximally_consistent_set_def_implication_elimination:\n  assumes \"\\<phi>-MCS \\<Omega>\"\n  shows \"(\\<psi> \\<rightarrow> \\<chi>) \\<in> \\<Omega> \\<Longrightarrow> \\<psi> \\<in> \\<Omega> \\<Longrightarrow> \\<chi> \\<in> \\<Omega>\"\n  using\n    assms\n    formula_maximally_consistent_set_def_reflection\n    set_deduction_modus_ponens\n  by blast\n\ntext \\<open> This concludes our introduction to implication logic. \\<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/Propositional_Logic_Class/Implication_Logic.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8670357529306639, "lm_q2_score": 0.8418256452674008, "lm_q1q2_score": 0.7298929321807628}}
{"text": "theory E4_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 cases\n  let ?l1 = \"take ((length xs div 2)) xs\"\n  let ?l2 = \"drop ((length xs div 2)) xs\"\n  assume \"even (length xs)\"\n  hence \"xs = ?l1 @ ?l2 \\<and> length ?l1 = length ?l2\" by auto\n  thus ?thesis by blast\nnext\n  let ?l1 = \"take ((length xs div 2) + 1) xs\"\n  let ?l2 = \"drop ((length xs div 2) + 1) xs\"\n  assume \"odd (length xs)\"\n  hence \"xs = ?l1 @ ?l2 \\<and> length ?l1 = length ?l2 + 1\" by (smt add.commute add_diff_cancel_right' append_take_drop_id left_add_twice length_append length_drop odd_two_times_div_two_succ)\n  thus ?thesis by blast\nqed\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/chapter4/E4_2.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9263037384317888, "lm_q2_score": 0.7879311956428947, "lm_q1q2_score": 0.7298636121510426}}
{"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>\\<open>graph\\<close> of a (real) function \\<open>f\\<close> with domain \\<open>F\\<close> as the set\n  \\begin{center}\n  \\<open>{(x, f x). x \\<in> F}\\<close>\n  \\end{center}\n  So we are modeling partial functions by specifying the domain and the\n  mapping function. We use the term ``function'' also for its 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 \\<open>h'\\<close> is an extension of \\<open>h\\<close>, iff the graph of \\<open>h\\<close> is a subset of\n  the graph of \\<open>h'\\<close>.\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 \\<open>graph\\<close> are \\<open>domain\\<close> and \\<open>funct\\<close>.\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 \\<open>g\\<close> is the graph of a function if the\n  relation induced by \\<open>g\\<close> 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 \\<open>f\\<close> on the space \\<open>F\\<close> and a seminorm \\<open>p\\<close> on \\<open>E\\<close>. The set\n  of all linear extensions of \\<open>f\\<close>, to superspaces \\<open>H\\<close> of \\<open>F\\<close>, which are\n  bounded by \\<open>p\\<close>, 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": "seL4", "repo": "isabelle", "sha": "e1ab32a3bb41728cd19541063283e37919978a4c", "save_path": "github-repos/isabelle/seL4-isabelle", "path": "github-repos/isabelle/seL4-isabelle/isabelle-e1ab32a3bb41728cd19541063283e37919978a4c/src/HOL/Hahn_Banach/Function_Order.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8757869851639066, "lm_q2_score": 0.8333245953120233, "lm_q1q2_score": 0.7298148349912494}}
{"text": "theory Environment\n  imports \"HOL-Library.Multiset\"\nbegin\n\nfun lookup :: \"'a list \\<Rightarrow> nat \\<rightharpoonup> 'a\" where\n  \"lookup [] x = None\"\n| \"lookup (a # as) 0 = Some a\"\n| \"lookup (a # as) (Suc x) = lookup as x\"\n\nfun insert_at :: \"nat \\<Rightarrow> 'a \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where\n  \"insert_at 0 a' [] = a' # []\"\n| \"insert_at 0 a' (a # as) = a' # a # as\"\n| \"insert_at (Suc x) a' [] = undefined\"\n| \"insert_at (Suc x) a' (a # as) = a # insert_at x a' as\"\n\nfun idx_of :: \"'a list \\<Rightarrow> 'a \\<rightharpoonup> nat\" where\n  \"idx_of [] a' = None\"\n| \"idx_of (a # as) a' = (if a = a' then Some 0 else map_option Suc (idx_of as a'))\"\n\nfun incr :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\" where\n  \"incr 0 y = Suc y\"\n| \"incr (Suc x) 0 = 0\"\n| \"incr (Suc x) (Suc y) = Suc (incr x y)\"\n\nfun decr :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\" where\n  \"decr x 0 = 0\"\n| \"decr 0 (Suc y) = y\"\n| \"decr (Suc x) (Suc y) = Suc (decr x y)\"\n\nabbreviation precede :: \"nat \\<Rightarrow> 'a \\<Rightarrow> 'a list \\<Rightarrow> bool\" (infix \"precedes _ in\" 50) where\n  \"x precedes a in as \\<equiv> (case idx_of as a of Some y \\<Rightarrow> x \\<le> y | None \\<Rightarrow> True)\"\n\n\n\nlemma [simp]: \"decr x (incr x y) = y\"\n  by (induction x y rule: incr.induct) simp_all\n\nlemma incr_not_eq [simp]: \"incr x y \\<noteq> x\"\n  by (induction x y rule: incr.induct) simp_all\n\nlemma incr_min: \"y < x \\<Longrightarrow> incr x y = min x y\"\n  by (induction x y rule: incr.induct) simp_all\n\nlemma [simp]: \"y \\<le> x \\<Longrightarrow> decr x y = y\"\n  by (induction x y rule: decr.induct) simp_all\n\nlemma [simp]: \"y \\<ge> x \\<Longrightarrow> decr x (Suc y) = y\"\n  by (induction x y rule: decr.induct) simp_all\n\nlemma [simp]: \"x \\<noteq> y \\<Longrightarrow> decr y x = y \\<Longrightarrow> x = Suc y\"\n  by (induction y x rule: decr.induct) simp_all\n\nlemma [simp]: \"y < decr y x \\<Longrightarrow> Suc (decr y x) = x\"\n  by (induction y x rule: decr.induct) simp_all\n\nlemma [simp]: \"y \\<le> x \\<Longrightarrow> incr y (incr x z) = incr (Suc x) (incr y z)\"\nproof (induction x z arbitrary: y rule: incr.induct)\n  case (2 x)\n  thus ?case by (induction y) simp_all\nnext\n  case (3 x z)\n  thus ?case by (induction y) simp_all\nqed simp_all\n\nlemma [simp]: \"y \\<le> x \\<Longrightarrow> incr y (decr x z) = decr (Suc x) (incr y z)\"\nproof (induction y z arbitrary: x rule: incr.induct)\n  case (3 y z)\n  thus ?case by (induction x) simp_all\nqed simp_all\n\nlemma [simp]: \"y \\<le> x \\<Longrightarrow> decr x (decr y z) = decr y (decr (Suc x) z)\"\nproof (induction y z arbitrary: x rule: decr.induct)\n  case (3 y z)\n  then show ?case by (induction x) simp_all\nqed simp_all\n\nlemma incr_le: \"y \\<le> x \\<Longrightarrow> incr y x = Suc x\"\n  by (induction y x rule: incr.induct) simp_all\n\nlemma incr_lemma': \"Suc y \\<le> incr y x \\<Longrightarrow> incr y x = Suc x\"\n  by (induction y x rule: incr.induct) simp_all\n\nlemma incr_lemma: \"y \\<le> z \\<Longrightarrow> Suc z = incr y x \\<Longrightarrow> z = x\"\nproof (induction y x rule: incr.induct)\n  case (3 y x)\n  then show ?case by simp (metis incr_lemma')\nqed simp_all\n\nlemma [simp]: \"y \\<le> x \\<Longrightarrow> y \\<noteq> z \\<Longrightarrow> x \\<noteq> decr y z \\<Longrightarrow> Suc x \\<noteq> z \\<Longrightarrow> y \\<noteq> decr (Suc x) z\"\nproof (induction y z arbitrary: x rule: decr.induct)\n  case (3 y z)\n  then show ?case by (induction x) simp_all\nqed simp_all\n\nlemma [simp]: \"x \\<le> length as \\<Longrightarrow> length (insert_at x a as) = Suc (length as)\"\n  by (induction x a as rule: insert_at.induct) simp_all\n\nlemma [simp]: \"x \\<le> length as \\<Longrightarrow> mset (insert_at x a as) = add_mset a (mset as)\"\n  by (induction x a as rule: insert_at.induct) simp_all\n\nlemma [simp]: \"x \\<ge> length as \\<Longrightarrow> lookup as x = None\"\n  by (induction as x rule: lookup.induct) simp_all\n\nlemma [simp]: \"x < length as \\<Longrightarrow> lookup as x \\<noteq> None\"\n  by (induction as x rule: lookup.induct) simp_all\n\nlemma [simp]: \"lookup as x = Some a \\<Longrightarrow> x < length as\"\n  by (induction as x rule: lookup.induct) simp_all\n\nlemma [simp]: \"lookup as x = Some a \\<Longrightarrow> \\<exists>b as'. as = b # as'\"\n  by (induction as x rule: lookup.induct) simp_all\n\nlemma [simp]: \"lookup as (Suc x) = Some a \\<Longrightarrow> x < length as\"\n  by (induction as x rule: lookup.induct) simp_all\n\nlemma [simp]: \"x < length as \\<Longrightarrow> \\<exists>a. lookup as x = Some a\"\n  by (induction as x rule: lookup.induct) simp_all\n\nlemma [simp]: \"x \\<le> length as \\<Longrightarrow> lookup (insert_at x a as) x = Some a\"\n  by (induction x a as rule: insert_at.induct) simp_all\n\nlemma [simp]: \"x \\<le> length as \\<Longrightarrow> lookup (insert_at x a as) (incr x y) = lookup as y\"\nproof (induction x a as arbitrary: y rule: insert_at.induct)\n  case (4 x a' a as)\n  then show ?case by (induction y) simp_all\nqed simp_all\n\nlemma [simp]: \"x \\<le> length as \\<Longrightarrow> x \\<noteq> y \\<Longrightarrow> lookup as (decr x y) = lookup (insert_at x a as) y\"\nproof (induction x a as arbitrary: y rule: insert_at.induct)\n  case (1 a')\n  then show ?case by (induction y) simp_all\nnext\n  case (2 a' a as)\n  then show ?case by (induction y) simp_all\nnext\n  case (4 x a' a as)\n  then show ?case by (induction y) simp_all\nqed simp_all\n\nlemma [simp]: \"lookup (map f as) x = map_option f (lookup as x)\"\n  by (induction as x rule: lookup.induct) simp_all\n\nlemma [simp]: \"x \\<le> length as \\<Longrightarrow> y \\<le> x \\<Longrightarrow> \n    insert_at y a (insert_at x b as) = insert_at (Suc x) b (insert_at y a as)\"\nproof (induction x b as arbitrary: y rule: insert_at.induct)\n  case (4 x a' a as)\n  then show ?case by (induction y) simp_all\nqed simp_all\n\nlemma [simp]: \"lookup as x = Some a \\<Longrightarrow> lookup (as @ bs) x = Some a\"\n  by (induction as x rule: lookup.induct) simp_all\n\nlemma [simp]: \"x < length as \\<Longrightarrow> lookup (as @ bs) x = lookup as x\"\n  by (induction as x rule: lookup.induct) simp_all\n\nlemma [simp]: \"lookup (as @ bs) (length as) = lookup bs 0\"\n  by (induction as) simp_all\n\nlemma lookup_append [simp]: \"lookup (as @ bs) (length as + n) = lookup bs n\"\n  by (induction as) simp_all\n\nlemma [simp]: \"x \\<le> length as \\<Longrightarrow> insert_at x a as @ bs = insert_at x a (as @ bs)\"\nproof (induction x a as rule: insert_at.induct)\n  case (1 a')\n  then show ?case by (induction bs) simp_all\nqed simp_all\n\nlemma [simp]: \"x \\<in> set as \\<Longrightarrow> \\<exists>y. idx_of as x = Some y\"\n  by (induction as x rule: idx_of.induct) auto\n\nlemma [simp]: \"idx_of as x = Some y \\<Longrightarrow> x \\<in> set as\"\n  by (induction as x arbitrary: y rule: idx_of.induct) (auto split: if_splits)\n\nlemma [simp]: \"idx_of as x = None \\<Longrightarrow> x \\<notin> set as\"\n  by (induction as x rule: idx_of.induct) (simp_all split: if_splits)\n\nlemma [simp]: \"a \\<noteq> b \\<Longrightarrow> (\\<exists>x. idx_of (remove1 b as) a = Some x) = (\\<exists>x. idx_of as a = Some x)\"\n  by (induction as) (simp_all split: if_splits)\n\nlemma [simp]: \"x \\<le> length as \\<Longrightarrow> set (insert_at x a as) = insert a (set as)\"\n  by (induction x a as rule: insert_at.induct) auto\n\nlemma [simp]: \"x \\<le> length as \\<Longrightarrow> distinct (insert_at x a as) = (a \\<notin> set as \\<and> distinct as)\"\n  by (induction x a as rule: insert_at.induct) auto\n\nlemma [simp]: \"x \\<le> length as \\<Longrightarrow> idx_of (insert_at x a as) b = \n  (case idx_of as b of \n    None \\<Rightarrow> (if a = b then Some x else None) \n  | Some y \\<Rightarrow> Some (if a = b then min x y else incr x y))\"\nproof (induction x a as rule: insert_at.induct)\n  case (4 x a' a as)\n  thus ?case by (cases \"idx_of as b\") auto\nqed (simp_all split: option.splits)\n\nlemma [simp]: \"0 precedes a in as\"\n  by (simp split: option.splits)\n\nlemma [simp]: \"lookup as x = Some a \\<Longrightarrow> a \\<in> set as\"\n  by (induction as x rule: lookup.induct) simp_all\n\nlemma [elim]: \"list_all p as \\<Longrightarrow> lookup as x = Some a \\<Longrightarrow> p a\"\n  by (induction as x rule: lookup.induct) simp_all\n\nlemma [simp]: \"list_all2 p as bs \\<Longrightarrow> p a b \\<Longrightarrow> x \\<le> length as \\<Longrightarrow> \n  list_all2 p (insert_at x a as) (insert_at x b bs)\"\nproof (induction x a as arbitrary: bs rule: insert_at.induct)\n  case (2 a' a as)\n  thus ?case by (induction bs) simp_all\nnext\n  case (4 x a' a as)\n  thus ?case by (induction bs) simp_all\nqed simp_all\n\nlemma [simp]: \"lookup as x = Some a \\<Longrightarrow> as ! x = a\"\n  by (induction as x rule: lookup.induct) simp_all\n\n(* some numeral simplification rules *)\n\nlemma [simp]: \"lookup (a # b # c # d) 2 = Some c\" by (simp add: numeral_def)\nlemma [simp]: \"lookup (a # b # c # d # e) 3 = Some d\" by (simp add: numeral_def)\nlemma [simp]: \"lookup (a # b # c # d # e # f) 4 = Some e\" by (simp add: numeral_def)\nlemma [simp]: \"lookup (a # b # c # d # e # f # g) 5 = Some f\" by (simp add: numeral_def)\nlemma [simp]: \"lookup (a # b # c # d # e # f # g # h) 6 = Some g\" by (simp add: numeral_def)\nlemma [simp]: \"lookup (a # b # c # d # e # f # g # h # i) 7 = Some h\" by (simp add: numeral_def)\nlemma [simp]: \"lookup (a # b # c # d # e # f # g # h # i # j) 8 = Some i\" by (simp add: numeral_def)\nlemma [simp]: \"lookup (a # b # c # d # e # f # g # h # i # j # k) 9 = Some j\" \n  by (simp add: numeral_def)\nlemma [simp]: \"lookup (a # b # c # d # e # f # g # h # i # j # k # l) 10 = Some k\" \n  by (simp add: numeral_def)\nlemma [simp]: \"lookup (a # b # c # d # e # f # g # h # i # j # k # l # m) 11 = Some l\" \n  by (simp add: numeral_def)\nlemma [simp]: \"lookup (a # b # c # d # e # f # g # h # i # j # k # l # m # n) 12 = Some m\" \n  by (simp add: numeral_def)\nlemma [simp]: \"lookup (a # b # c # d # e # f # g # h # i # j # k # l # m # n # p) 13 = Some n\" \n  by (simp add: numeral_def)\nlemma [simp]: \"lookup (a # b # c # d # e # f # g # h # i # j # k # l # m # n # p # q) 14 = Some p\" \n  by (simp add: numeral_def)\nlemma [simp]: \"lookup (a # b # c # d # e # f # g # h # i # j # k # l # m # n # p # q # r) 15 = \n  Some q\" by (simp add: numeral_def)\nlemma [simp]: \"lookup (a # b # c # d # e # f # g # h # i # j # k # l # m # n # p # q # r # s) 16 = \n  Some r\" by (simp add: numeral_def)\nlemma [simp]: \"lookup (a # b # c # d # e # f # g # h # i # j # k # l # m # n # p # q # r # s # t) \n  17 = Some s\" by (simp add: numeral_def)\nlemma [simp]: \"lookup (a # b # c # d # e # f # g # h # i # j # k # l # m # n # p # q # r # s # t # \n  u) 18 = Some t\" by (simp add: numeral_def)\nlemma [simp]: \"lookup (a # b # c # d # e # f # g # h # i # j # k # l # m # n # p # q # r # s # t # \n  u # v) 19 = Some u\" by (simp add: numeral_def)\nlemma [simp]: \"lookup (a # b # c # d # e # f # g # h # i # j # k # l # m # n # p # q # r # s # t # \n  u # v # w) 20 = Some v\" by (simp add: numeral_def)\nlemma [simp]: \"lookup (a # b # c # d # e # f # g # h # i # j # k # l # m # n # p # q # r # s # t # \n  u # v # w # x) 21 = Some w\" by (simp add: numeral_def)\nlemma [simp]: \"lookup (a # b # c # d # e # f # g # h # i # j # k # l # m # n # p # q # r # s # t # \n  u # v # w # x # y) 22 = Some x\" by (simp add: numeral_def)\nlemma [simp]: \"lookup (a # b # c # d # e # f # g # h # i # j # k # l # m # n # p # q # r # s # t # \n  u # v # w # x # y # z) 23 = Some y\" by (simp add: numeral_def)\n\nlemma [simp]: \"lookup (a # b # c # d # e # f) (5 + x) = lookup f x\" by (simp add: numeral_def)\nlemma [simp]: \"lookup (a # b # c # d # e # f) (6 + x) = lookup f (Suc x)\" by (simp add: numeral_def)\nlemma [simp]: \"lookup (a # b # c # d # e # f) (7 + x) = lookup f (Suc (Suc x))\" \n  by (simp add: numeral_def)\n\nend", "meta": {"author": "xtreme-james-cooper", "repo": "Lambda-RAM-Compiler", "sha": "24125435949fa71dfc5faafdb236d28a098beefc", "save_path": "github-repos/isabelle/xtreme-james-cooper-Lambda-RAM-Compiler", "path": "github-repos/isabelle/xtreme-james-cooper-Lambda-RAM-Compiler/Lambda-RAM-Compiler-24125435949fa71dfc5faafdb236d28a098beefc/00Utils/Environment.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869851639065, "lm_q2_score": 0.8333245932423308, "lm_q1q2_score": 0.7298148331786396}}
{"text": "(*  Title:       Binary Search Trees, Isar-Style\n    Author:      Viktor Kuncak, MIT CSAIL, November 2003\n    Maintainer:  Larry Paulson <Larry.Paulson at cl.cam.ac.uk>\n    License:     LGPL\n*)\n\nheader {* Isar-style Reasoning for Binary Tree Operations *}\ntheory BinaryTree imports Main begin\n\ntext {* We prove correctness of operations on \n binary search tree implementing a set.\n\n This document is LGPL.\n\n Author: Viktor Kuncak, MIT CSAIL, November 2003 *}\n\n(*============================================================*)\nsection {* Tree Definition *}\n(*============================================================*)\n\ndatatype 'a Tree = Tip | T \"'a Tree\" 'a \"'a Tree\"\n\nprimrec\n  setOf :: \"'a Tree => 'a set\" \n  -- {* set abstraction of a tree *} \nwhere\n  \"setOf Tip = {}\"\n| \"setOf (T t1 x t2) = (setOf t1) Un (setOf t2) Un {x}\"\n\ntype_synonym\n  -- {* we require index to have an irreflexive total order < *}\n  -- {* apart from that, we do not rely on index being int *}\n  index = int \n\ntype_synonym -- {* hash function type *}\n  'a hash = \"'a => index\"\n\ndefinition eqs :: \"'a hash => 'a => 'a set\" where\n  -- {* equivalence class of elements with the same hash code *}\n  \"eqs h x == {y. h y = h x}\"\n\nprimrec\n  sortedTree :: \"'a hash => 'a Tree => bool\"\n  -- {* check if a tree is sorted *}\nwhere\n  \"sortedTree h Tip = True\"\n| \"sortedTree h (T t1 x t2) = \n    (sortedTree h t1 & \n     (ALL l: setOf t1. h l < h x) &\n     (ALL r: setOf t2. h x < h r) &\n     sortedTree h t2)\"\n\nlemma sortLemmaL: \n  \"sortedTree h (T t1 x t2) ==> sortedTree h t1\" by simp\nlemma sortLemmaR: \n  \"sortedTree h (T t1 x t2) ==> sortedTree h t2\" by simp\n\n(*============================================================*)\nsection {* Tree Lookup *}\n(*============================================================*)\n\nprimrec\n  tlookup :: \"'a hash => index => 'a Tree => 'a option\"\nwhere\n  \"tlookup h k Tip = None\"\n| \"tlookup h k (T t1 x t2) = \n   (if k < h x then tlookup h k t1\n    else if h x < k then tlookup h k t2\n    else Some x)\"\n\n\n\nlemma tlookup_some:\n     \"sortedTree h t & (tlookup h k t = Some x) --> x:setOf t & h x = k\"\napply (induct t)\n  --{*Just auto will do it, but very slowly*}\napply (simp)\napply (clarify, auto)\napply (simp_all split: split_if_asm) \ndone\n\ndefinition sorted_distinct_pred :: \"'a hash => 'a => 'a => 'a Tree => bool\" where\n  -- {* No two elements have the same hash code *}\n  \"sorted_distinct_pred h a b t == sortedTree h t & \n      a:setOf t & b:setOf t & h a = h b --> \n      a = b\"\n\ndeclare sorted_distinct_pred_def [simp]\n\n-- {* for case analysis on three cases *}\nlemma cases3: \"[| C1 ==> G; C2 ==> G; C3 ==> G;\n                  C1 | C2 | C3 |] ==> G\"\nby auto\n\ntext {* @{term sorted_distinct_pred} holds for out trees: *}\n\nlemma sorted_distinct: \"sorted_distinct_pred h a b t\" (is \"?P t\")\nproof (induct t)\n  show \"?P Tip\" by simp\n  fix t1 :: \"'a Tree\" assume h1: \"?P t1\"\n  fix t2 :: \"'a Tree\" assume h2: \"?P t2\"\n  fix x :: 'a\n  show \"?P (T t1 x t2)\"\n  proof (unfold sorted_distinct_pred_def, safe)\n    assume s: \"sortedTree h (T t1 x t2)\"\n    assume adef: \"a : setOf (T t1 x t2)\"\n    assume bdef: \"b : setOf (T t1 x t2)\"\n    assume hahb: \"h a = h b\"\n    from s have s1: \"sortedTree h t1\" by auto\n    from s have s2: \"sortedTree h t2\" by auto\n    show \"a = b\"\n    -- {* We consider 9 cases for the position of a and b are in the tree *}\n    proof -\n    -- {* three cases for a *}\n    from adef have \"a : setOf t1 | a = x | a : setOf t2\" by auto\n    moreover { assume adef1: \"a : setOf t1\"\n      have ?thesis\n      proof - \n      -- {* three cases for b *}\n      from bdef have \"b : setOf t1 | b = x | b : setOf t2\" by auto\n      moreover { assume bdef1: \"b : setOf t1\"\n        from s1 adef1 bdef1 hahb h1 have ?thesis by simp }\n      moreover { assume bdef1: \"b = x\"\n        from adef1 bdef1 s have \"h a < h b\" by auto\n        from this hahb have ?thesis by simp }\n      moreover { assume bdef1: \"b : setOf t2\"\n        from adef1 s have o1: \"h a < h x\" by auto\n        from bdef1 s have o2: \"h x < h b\" by auto\n        from o1 o2 have \"h a < h b\" by simp\n        from this hahb have ?thesis by simp } -- {* case impossible *}\n      ultimately show ?thesis by blast\n      qed \n    } \n    moreover { assume adef1: \"a = x\"\n      have ?thesis \n      proof -\n      -- {* three cases for b *}\n      from bdef have \"b : setOf t1 | b = x | b : setOf t2\" by auto\n      moreover { assume bdef1: \"b : setOf t1\"\n        from this s have \"h b < h x\" by auto\n        from this adef1 have \"h b < h a\" by auto\n        from hahb this have ?thesis by simp } -- {* case impossible *}\n      moreover { assume bdef1: \"b = x\"\n        from adef1 bdef1 have ?thesis by simp }\n      moreover { assume bdef1: \"b : setOf t2\"\n        from this s have \"h x < h b\" by auto\n        from this adef1 have \"h a < h b\" by simp\n        from hahb this have ?thesis by simp } -- {* case impossible *}\n      ultimately show ?thesis by blast\n      qed\n    }\n    moreover { assume adef1: \"a : setOf t2\"\n      have ?thesis\n      proof -\n      -- {* three cases for b *}\n      from bdef have \"b : setOf t1 | b = x | b : setOf t2\" by auto\n      moreover { assume bdef1: \"b : setOf t1\"\n        from bdef1 s have o1: \"h b < h x\" by auto\n        from adef1 s have o2: \"h x < h a\" by auto\n        from o1 o2 have \"h b < h a\" by simp\n        from this hahb have ?thesis by simp } -- {* case impossible *}\n      moreover { assume bdef1: \"b = x\"\n        from adef1 bdef1 s have \"h b < h a\" by auto\n        from this hahb have ?thesis by simp } -- {* case impossible *}\n      moreover { assume bdef1: \"b : setOf t2\"\n        from s2 adef1 bdef1 hahb h2 have ?thesis by simp }\n      ultimately show ?thesis by blast\n      qed\n    }\n    ultimately show ?thesis by blast\n    qed\n  qed\nqed\n\nlemma tlookup_finds: -- {* if a node is in the tree, lookup finds it *}\n\"sortedTree h t & y:setOf t --> \n tlookup h (h y) t = Some y\"\nproof safe\n  assume s: \"sortedTree h t\"\n  assume yint: \"y : setOf t\"\n  show \"tlookup h (h y) t = Some y\"\n  proof (cases \"tlookup h (h y) t\")\n  case None note res = this    \n    from s res have \"sortedTree h t & (tlookup h (h y) t = None)\" by simp\n    from this have o1: \"ALL x:setOf t. h x ~= h y\" by (simp add: tlookup_none)\n    from o1 yint have \"h y ~= h y\" by fastforce (* auto does not work *)\n    from this show ?thesis by simp\n  next case (Some z) note res = this\n    have ls: \"sortedTree h t & (tlookup h (h y) t = Some z) -->\n              z:setOf t & h z = h y\" by (simp add: tlookup_some)\n    have sd: \"sorted_distinct_pred h y z t\" \n    by (insert sorted_distinct [of h y z t], simp) \n       (* for some reason simplifier would never guess this substitution *)\n    from s res ls have o1: \"z:setOf t & h z = h y\" by simp\n    from s yint o1 sd have \"y = z\" by auto\n    from this res show \"tlookup h (h y) t = Some y\" by simp\n  qed\nqed\n\nsubsection {* Tree membership as a special case of lookup *}\n\ndefinition memb :: \"'a hash => 'a => 'a Tree => bool\" where\n  \"memb h x t == \n   (case (tlookup h (h x) t) of\n      None => False\n    | Some z => (x=z))\"\n\nlemma assumes s: \"sortedTree h t\" \n      shows memb_spec: \"memb h x t = (x : setOf t)\"\nproof (cases \"tlookup h (h x) t\")\ncase None note tNone = this\n  from tNone have res: \"memb h x t = False\" by (simp add: memb_def)\n  from s tNone tlookup_none have o1: \"ALL y:setOf t. h y ~= h x\" by fastforce\n  have notIn: \"x ~: setOf t\"\n  proof\n    assume h: \"x : setOf t\"\n    from h o1 have \"h x ~= h x\" by fastforce\n    from this show False by simp\n  qed\n  from res notIn show ?thesis by simp\nnext case (Some z) note tSome = this\n  from s tSome tlookup_some have zin: \"z : setOf t\" by fastforce\n  show ?thesis\n  proof (cases \"x=z\")\n  case True note xez = this\n    from tSome xez have res: \"memb h x t\" by (simp add: memb_def)  \n    from res zin xez show ?thesis by simp\n  next case False note xnez = this\n    from tSome xnez have res: \"~ memb h x t\" by (simp add: memb_def)\n    have \"x ~: setOf t\"\n    proof\n      assume xin: \"x : setOf t\"\n      from s tSome tlookup_some have hzhx: \"h x = h z\" by fastforce\n      have o1: \"sorted_distinct_pred h x z t\"\n      by (insert sorted_distinct [of h x z t], simp)\n      from s xin zin hzhx o1 have \"x = z\" by fastforce\n      from this xnez show False by simp\n    qed  \n    from this res show ?thesis by simp\n  qed\nqed\n\ndeclare sorted_distinct_pred_def [simp del]\n\n(*============================================================*)\nsection {* Insertion into a Tree *}\n(*============================================================*)\n\nprimrec\n  binsert :: \"'a hash => 'a => 'a Tree => 'a Tree\"\nwhere\n  \"binsert h e Tip = (T Tip e Tip)\"\n| \"binsert h e (T t1 x t2) = (if h e < h x then\n                             (T (binsert h e t1) x t2)\n                            else\n                             (if h x < h e then\n                               (T t1 x (binsert h e t2))\n                              else (T t1 e t2)))\"\n\ntext {* A technique for proving disjointness of sets. *}\nlemma disjCond: \"[| !! x. [| x:A; x:B |] ==> False |] ==> A Int B = {}\"\nby fastforce\n\ntext {* The following is a proof that insertion correctly implements\n        the set interface.\n        Compared to @{text BinaryTree_TacticStyle}, the claim is more\n        difficult, and this time we need to assume as a hypothesis\n        that the tree is sorted. *}\n\n\n\ntext {* Using the correctness of set implementation,\n        preserving sortedness is still simple. *}\nlemma binsert_sorted: \"sortedTree h t --> sortedTree h (binsert h x t)\"\nby (induct t) (auto simp add: binsert_set)\n\ntext {* We summarize the specification of binsert as follows. *}\ncorollary binsert_spec: \"sortedTree h t -->\n                     sortedTree h (binsert h x t) &\n                     setOf (binsert h e t) = (setOf t) - (eqs h e) Un {e}\"\nby (simp add: binsert_set binsert_sorted)\n\n(*============================================================*)\nsection {* Removing an element from a tree *}\n(*============================================================*)\n\ntext {* These proofs are influenced by those in @{text BinaryTree_Tactic} *}\n\nprimrec\n  rm :: \"'a hash => 'a Tree => 'a\"\n  -- {* rightmost element of a tree *}\nwhere\n\"rm h (T t1 x t2) =\n  (if t2=Tip then x else rm h t2)\"\n\nprimrec\n  wrm :: \"'a hash => 'a Tree => 'a Tree\"\n  -- {* tree without the rightmost element *}\nwhere\n\"wrm h (T t1 x t2) =\n  (if t2=Tip then t1 else (T t1 x (wrm h t2)))\"\n\nprimrec\n  wrmrm :: \"'a hash => 'a Tree => 'a Tree * 'a\"\n  -- {* computing rightmost and removal in one pass *}\nwhere\n\"wrmrm h (T t1 x t2) =\n  (if t2=Tip then (t1,x)\n   else (T t1 x (fst (wrmrm h t2)),\n         snd (wrmrm h t2)))\"\n\nprimrec\n  remove :: \"'a hash => 'a => 'a Tree => 'a Tree\"\n   -- {* removal of an element from the tree *}\nwhere\n  \"remove h e Tip = Tip\"\n| \"remove h e (T t1 x t2) = \n    (if h e < h x then (T (remove h e t1) x t2)\n     else if h x < h e then (T t1 x (remove h e t2))\n     else (if t1=Tip then t2\n           else let (t1p,r) = wrmrm h t1\n                in (T t1p r t2)))\"\n\ntheorem wrmrm_decomp: \"t ~= Tip --> wrmrm h t = (wrm h t, rm h t)\"\napply (induct_tac t)\napply simp_all\ndone\n\nlemma rm_set: \"t ~= Tip & sortedTree h t --> rm h t : setOf t\"\napply (induct_tac t)\napply simp_all\ndone\n\nlemma wrm_set: \"t ~= Tip & sortedTree h t --> \n                setOf (wrm h t) = setOf t - {rm h t}\" (is \"?P t\")\nproof (induct t)\n  show \"?P Tip\" by simp\n  fix t1 :: \"'a Tree\" assume h1: \"?P t1\"\n  fix t2 :: \"'a Tree\" assume h2: \"?P t2\" \n  fix x :: 'a\n  show \"?P (T t1 x t2)\"\n  proof (rule impI, erule conjE)\n    assume s: \"sortedTree h (T t1 x t2)\"\n    show \"setOf (wrm h (T t1 x t2)) = \n          setOf (T t1 x t2) - {rm h (T t1 x t2)}\"\n    proof (cases \"t2 = Tip\")\n    case True note t2tip = this\n      from t2tip have rm_res: \"rm h (T t1 x t2) = x\" by simp\n      from t2tip have wrm_res: \"wrm h (T t1 x t2) = t1\" by simp\n      from s have \"x ~: setOf t1\" by auto\n      from this rm_res wrm_res t2tip show ?thesis by simp\n    next case False note t2nTip = this\n      from t2nTip have rm_res: \"rm h (T t1 x t2) = rm h t2\" by simp\n      from t2nTip have wrm_res: \"wrm h (T t1 x t2) = T t1 x (wrm h t2)\" by simp\n      from s have s2: \"sortedTree h t2\" by simp    \n      from h2 t2nTip s2 \n      have o1: \"setOf (wrm h t2) = setOf t2 - {rm h t2}\" by simp\n      show ?thesis\n      proof (simp add: rm_res wrm_res t2nTip h2 o1)\n        show \"insert x (setOf t1 Un (setOf t2 - {rm h t2})) = \n              insert x (setOf t1 Un setOf t2) - {rm h t2}\"\n        proof -\n          from s rm_set t2nTip have xOk: \"h x < h (rm h t2)\" by auto \n          have t1Ok: \"ALL l:setOf t1. h l < h (rm h t2)\"\n          proof safe\n            fix l :: 'a  assume ldef: \"l : setOf t1\"\n            from ldef s have lx: \"h l < h x\" by auto\n            from lx xOk show \"h l < h (rm h t2)\" by auto\n          qed\n          from xOk t1Ok show ?thesis by auto\n        qed\n      qed\n    qed\n  qed\nqed\n\nlemma wrm_set1: \"t ~= Tip & sortedTree h t --> setOf (wrm h t) <= setOf t\"\nby (auto simp add: wrm_set)\n\nlemma wrm_sort: \"t ~= Tip & sortedTree h t --> sortedTree h (wrm h t)\" (is \"?P t\")\nproof (induct t)\n  show \"?P Tip\" by simp  \n  fix t1 :: \"'a Tree\" assume h1: \"?P t1\"\n  fix t2 :: \"'a Tree\" assume h2: \"?P t2\" \n  fix x :: 'a\n  show \"?P (T t1 x t2)\"\n  proof safe\n    assume s: \"sortedTree h (T t1 x t2)\"\n    show \"sortedTree h (wrm h (T t1 x t2))\"\n    proof (cases \"t2 = Tip\")\n    case True note t2tip = this\n      from t2tip have res: \"wrm h (T t1 x t2) = t1\" by simp\n      from res s show ?thesis by simp\n    next case False note t2nTip = this\n      from t2nTip have res: \"wrm h (T t1 x t2) = T t1 x (wrm h t2)\" by simp\n      from s have s1: \"sortedTree h t1\" by simp\n      from s have s2: \"sortedTree h t2\" by simp\n      from s2 h2 t2nTip have o1: \"sortedTree h (wrm h t2)\" by simp\n      from s2 t2nTip wrm_set1 have o2: \"setOf (wrm h t2) <= setOf t2\" by auto\n      from s o2 have o3: \"ALL r: setOf (wrm h t2). h x < h r\" by auto\n      from s1 o1 o3 res s show \"sortedTree h (wrm h (T t1 x t2))\" by simp\n    qed\n  qed\nqed\n\nlemma wrm_less_rm: \n  \"t ~= Tip & sortedTree h t --> \n   (ALL l:setOf (wrm h t). h l < h (rm h t))\" (is \"?P t\")\nproof (induct t)\n  show \"?P Tip\" by simp\n  fix t1 :: \"'a Tree\" assume h1: \"?P t1\"\n  fix t2 :: \"'a Tree\" assume h2: \"?P t2\"\n  fix x :: 'a   \n  show \"?P (T t1 x t2)\"\n  proof safe \n    fix l :: \"'a\" assume ldef: \"l : setOf (wrm h (T t1 x t2))\"\n    assume s: \"sortedTree h (T t1 x t2)\"\n    from s have s1: \"sortedTree h t1\" by simp\n    from s have s2: \"sortedTree h t2\" by simp\n    show \"h l < h (rm h (T t1 x t2))\"\n    proof (cases \"t2 = Tip\")\n    case True note t2tip = this\n      from t2tip have rm_res: \"rm h (T t1 x t2) = x\" by simp\n      from t2tip have wrm_res: \"wrm h (T t1 x t2) = t1\" by simp\n      from ldef wrm_res have o1: \"l : setOf t1\" by simp\n      from rm_res o1 s show ?thesis by simp\n    next case False note t2nTip = this\n      from t2nTip have rm_res: \"rm h (T t1 x t2) = rm h t2\" by simp\n      from t2nTip have wrm_res: \"wrm h (T t1 x t2) = T t1 x (wrm h t2)\" by simp\n      from ldef wrm_res \n      have l_scope: \"l : {x} Un setOf t1 Un setOf (wrm h t2)\" by simp\n      have hLess: \"h l < h (rm h t2)\"\n      proof (cases \"l = x\")\n      case True note lx = this\n        from s t2nTip rm_set s2 have o1: \"h x < h (rm h t2)\" by auto\n        from lx o1 show ?thesis by simp\n      next case False note lnx = this\n        show ?thesis\n        proof (cases \"l : setOf t1\")\n        case True note l_in_t1 = this\n          from s t2nTip rm_set s2 have o1: \"h x < h (rm h t2)\" by auto\n          from l_in_t1 s have o2: \"h l < h x\" by auto\n          from o1 o2 show ?thesis by simp\n        next case False note l_notin_t1 = this\n          from l_scope lnx l_notin_t1 \n          have l_in_res: \"l : setOf (wrm h t2)\" by auto\n          from l_in_res h2 t2nTip s2 show ?thesis by auto\n        qed\n      qed\n      from rm_res hLess show ?thesis by simp\n    qed\n  qed\nqed\n\nlemma remove_set: \"sortedTree h t --> \n  setOf (remove h e t) = setOf t - eqs h e\" (is \"?P t\")\nproof (induct t)\n  show \"?P Tip\" by auto\n  fix t1 :: \"'a Tree\" assume h1: \"?P t1\"\n  fix t2 :: \"'a Tree\" assume h2: \"?P t2\"\n  fix x :: 'a\n  show \"?P (T t1 x t2)\"\n  proof \n    assume s: \"sortedTree h (T t1 x t2)\"\n    show \"setOf (remove h e (T t1 x t2)) = setOf (T t1 x t2) - eqs h e\"\n    proof (cases \"h e < h x\")\n    case True note elx = this\n      from elx have res: \"remove h e (T t1 x t2) = T (remove h e t1) x t2\" \n      by simp\n      from s have s1: \"sortedTree h t1\" by simp\n      from s1 h1 have o1: \"setOf (remove h e t1) = setOf t1 - eqs h e\" by simp\n      show ?thesis\n      proof (simp add: o1 elx)\n        show \"insert x (setOf t1 - eqs h e Un setOf t2) = \n              insert x (setOf t1 Un setOf t2) - eqs h e\"\n        proof -\n          have xOk: \"x ~: eqs h e\" \n          proof \n            assume h: \"x : eqs h e\"\n            from h have o1: \"~ (h e < h x)\" by (simp add: eqs_def)\n            from elx o1 show \"False\" by contradiction\n          qed\n          have t2Ok: \"(setOf t2) Int (eqs h e) = {}\"\n          proof (rule disjCond)\n            fix y :: 'a \n            assume y_in_t2: \"y : setOf t2\"\n            assume y_in_eq: \"y : eqs h e\"\n            from y_in_t2 s have xly: \"h x < h y\" by auto\n            from y_in_eq have eey: \"h y = h e\" by (simp add: eqs_def) (* must \"add:\" not \"from\" *)\n            from xly eey have nelx: \"~ (h e < h x)\" by simp\n            from nelx elx show False by contradiction\n          qed\n          from xOk t2Ok show ?thesis by auto\n        qed\n      qed\n    next case False note nelx = this\n      show ?thesis \n      proof (cases \"h x < h e\")\n      case True note xle = this\n        from xle have res: \"remove h e (T t1 x t2) = T t1 x (remove h e t2)\" by simp\n        from s have s2: \"sortedTree h t2\" by simp\n        from s2 h2 have o1: \"setOf (remove h e t2) = setOf t2 - eqs h e\" by simp\n        show ?thesis\n        proof (simp add: o1 xle nelx)\n          show \"insert x (setOf t1 Un (setOf t2 - eqs h e)) = \n                insert x (setOf t1 Un setOf t2) - eqs h e\"\n          proof -\n            have xOk: \"x ~: eqs h e\" \n            proof \n              assume h: \"x : eqs h e\"\n              from h have o1: \"~ (h x < h e)\" by (simp add: eqs_def)\n              from xle o1 show \"False\" by contradiction\n            qed\n            have t1Ok: \"(setOf t1) Int (eqs h e) = {}\"\n            proof (rule disjCond)\n              fix y :: 'a \n              assume y_in_t1: \"y : setOf t1\"\n              assume y_in_eq: \"y : eqs h e\"\n              from y_in_t1 s have ylx: \"h y < h x\" by auto\n              from y_in_eq have eey: \"h y = h e\" by (simp add: eqs_def)\n              from ylx eey have nxle: \"~ (h x < h e)\" by simp\n              from nxle xle show False by contradiction\n            qed\n            from xOk t1Ok show ?thesis by auto\n          qed\n        qed\n      next case False note nxle = this\n        from nelx nxle have ex: \"h e = h x\" by simp\n        have t2Ok: \"(setOf t2) Int (eqs h e) = {}\"\n        proof (rule disjCond)\n          fix y :: 'a \n          assume y_in_t2: \"y : setOf t2\"\n          assume y_in_eq: \"y : eqs h e\"\n          from y_in_t2 s have xly: \"h x < h y\" by auto\n          from y_in_eq have eey: \"h y = h e\" by (simp add: eqs_def)\n          from y_in_eq ex eey have nxly: \"~ (h x < h y)\" by simp\n          from nxly xly show False by contradiction\n        qed\n        show ?thesis \n        proof (cases \"t1 = Tip\")\n        case True note t1tip = this\n          from ex t1tip have res: \"remove h e (T t1 x t2) = t2\" by simp\n          show ?thesis\n          proof (simp add: res t1tip ex)\n            show \"setOf t2 = insert x (setOf t2) - eqs h e\"              \n            proof -\n              from ex have x_in_eqs: \"x : eqs h e\" by (simp add: eqs_def)\n              from x_in_eqs t2Ok show ?thesis by auto\n           qed\n          qed\n        next case False note t1nTip = this\n          from nelx nxle ex t1nTip\n          have res: \"remove h e (T t1 x t2) =\n                     T (wrm h t1) (rm h t1) t2\" \n          by (simp add: Let_def wrmrm_decomp)\n          from res show ?thesis\n          proof simp\n            from s have s1: \"sortedTree h t1\" by simp\n            show \"insert (rm h t1) (setOf (wrm h t1) Un setOf t2) = \n                  insert x (setOf t1 Un setOf t2) - eqs h e\"\n            proof (simp add: t1nTip s1 rm_set wrm_set)\n              show \"insert (rm h t1) (setOf t1 - {rm h t1} Un setOf t2) = \n                    insert x (setOf t1 Un setOf t2) - eqs h e\"\n              proof -\n                from t1nTip s1 rm_set\n                have o1: \"insert (rm h t1) (setOf t1 - {rm h t1} Un setOf t2) =\n                          setOf t1 Un setOf t2\" by auto\n                have o2: \"insert x (setOf t1 Un setOf t2) - eqs h e =\n                          setOf t1 Un setOf t2\" \n                proof -\n                  from ex have xOk: \"x : eqs h e\" by (simp add: eqs_def)                  \n                  have t1Ok: \"(setOf t1) Int (eqs h e) = {}\"\n                  proof (rule disjCond)\n                    fix y :: 'a \n                    assume y_in_t1: \"y : setOf t1\"\n                    assume y_in_eq: \"y : eqs h e\"\n                    from y_in_t1 s ex have o1: \"h y < h e\" by auto\n                    from y_in_eq have o2: \"~ (h y < h e)\" by (simp add: eqs_def)\n                    from o1 o2 show False by contradiction\n                  qed\n                  from xOk t1Ok t2Ok show ?thesis by auto\n                qed\n                from o1 o2 show ?thesis by simp\n              qed\n            qed\n          qed\n        qed\n      qed\n    qed\n  qed  \nqed\n\nlemma remove_sort: \"sortedTree h t --> \n                    sortedTree h (remove h e t)\" (is \"?P t\")\nproof (induct t)\n  show \"?P Tip\" by auto\n  fix t1 :: \"'a Tree\" assume h1: \"?P t1\"\n  fix t2 :: \"'a Tree\" assume h2: \"?P t2\"\n  fix x :: 'a\n  show \"?P (T t1 x t2)\"\n  proof \n    assume s: \"sortedTree h (T t1 x t2)\"\n    from s have s1: \"sortedTree h t1\" by simp\n    from s have s2: \"sortedTree h t2\" by simp\n    from h1 s1 have sr1: \"sortedTree h (remove h e t1)\" by simp\n    from h2 s2 have sr2: \"sortedTree h (remove h e t2)\" by simp   \n    show \"sortedTree h (remove h e (T t1 x t2))\"\n    proof (cases \"h e < h x\")\n    case True note elx = this\n      from elx have res: \"remove h e (T t1 x t2) = T (remove h e t1) x t2\" \n      by simp\n      show ?thesis\n      proof (simp add: s sr1 s2 elx res)\n        let ?C1 = \"ALL l:setOf (remove h e t1). h l < h x\"\n        let ?C2 = \"ALL r:setOf t2. h x < h r\"\n        have o1: \"?C1\"\n        proof -\n          from s1 have \"setOf (remove h e t1) = setOf t1 - eqs h e\" by (simp add: remove_set)\n          from s this show ?thesis by auto\n        qed\n        from o1 s show \"?C1 & ?C2\" by auto\n      qed\n    next case False note nelx = this\n      show ?thesis \n      proof (cases \"h x < h e\")\n      case True note xle = this\n        from xle have res: \"remove h e (T t1 x t2) = T t1 x (remove h e t2)\" by simp\n        show ?thesis\n        proof (simp add: s s1 sr2 xle nelx res)\n          let ?C1 = \"ALL l:setOf t1. h l < h x\"\n          let ?C2 = \"ALL r:setOf (remove h e t2). h x < h r\"\n          have o2: \"?C2\"\n          proof -\n            from s2 have \"setOf (remove h e t2) = setOf t2 - eqs h e\" by (simp add: remove_set)\n            from s this show ?thesis by auto\n          qed\n          from o2 s show \"?C1 & ?C2\" by auto\n        qed\n      next case False note nxle = this\n        from nelx nxle have ex: \"h e = h x\" by simp\n        show ?thesis \n        proof (cases \"t1 = Tip\")\n        case True note t1tip = this\n          from ex t1tip have res: \"remove h e (T t1 x t2) = t2\" by simp\n          show ?thesis by (simp add: res t1tip ex s2)\n        next case False note t1nTip = this\n          from nelx nxle ex t1nTip\n          have res: \"remove h e (T t1 x t2) =\n                     T (wrm h t1) (rm h t1) t2\" \n          by (simp add: Let_def wrmrm_decomp)\n          from res show ?thesis\n          proof simp\n            let ?C1 = \"sortedTree h (wrm h t1)\"\n            let ?C2 = \"ALL l:setOf (wrm h t1). h l < h (rm h t1)\"\n            let ?C3 = \"ALL r:setOf t2. h (rm h t1) < h r\"\n            let ?C4 = \"sortedTree h t2\"\n            from s1 t1nTip have o1: ?C1 by (simp add: wrm_sort)\n            from s1 t1nTip have o2: ?C2 by (simp add: wrm_less_rm)\n            have o3: ?C3\n            proof\n              fix r :: 'a \n              assume rt2: \"r : setOf t2\"\n              from s rm_set s1 t1nTip have o1: \"h (rm h t1) < h x\" by auto\n              from rt2 s have o2: \"h x < h r\" by auto\n              from o1 o2 show \"h (rm h t1) < h r\" by simp\n            qed\n            from o1 o2 o3 s2 show \"?C1 & ?C2 & ?C3 & ?C4\" by simp\n          qed\n        qed\n      qed\n    qed\n  qed  \nqed\n\ntext {* We summarize the specification of remove as follows. *}\ncorollary remove_spec: \"sortedTree h t --> \n     sortedTree h (remove h e t) &\n     setOf (remove h e t) = setOf t - eqs h e\"\nby (simp add: remove_sort remove_set)\n\ndefinition \"test = tlookup id 4 (remove id 3 (binsert id 4 (binsert id 3 Tip)))\"\n\nexport_code test\n  in SML module_name BinaryTree_Code file \"BinaryTree_Code.ML\"\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/BinarySearchTree/BinaryTree.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952975813454, "lm_q2_score": 0.8128673155708975, "lm_q1q2_score": 0.7297071667455662}}
{"text": "header {* \\isaheader{Examples from ITP-2010 slides (adopted to ICF v2)} *}\ntheory itp_2010\nimports \n  \"../../ICF/Collections\" \n  \"../../Lib/Code_Target_ICF\"\nbegin\n\ntext {*\n  Illustrates the various possibilities how to use the ICF in your own \n  algorithms by simple examples. The examples all use the data refinement\n  scheme, and either define a generic algorithm or fix the operations.\n*}\n\n\nsubsection \"List to Set\"\ntext {*\n  In this simple example we do conversion from a list to a set.\n  We define an abstract algorithm.\n  This is then refined by a generic algorithm using a locale and by a generic \n  algorithm fixing its operations as parameters.\n*}\n  subsubsection \"Straightforward version\"\n  -- \"Abstract algorithm\"\n  fun set_a where\n    \"set_a [] s = s\" |\n    \"set_a (a#l) s = set_a l (insert a s)\"\n\n  -- \"Correctness of aa\"\n  lemma set_a_correct: \"set_a l s = set l \\<union> s\"\n    by (induct l arbitrary: s) auto\n\n  -- \"Generic algorithm\"\n\n  setup Locale_Code.open_block -- \"Required to make definitions inside locales\n    executable\"\n  fun (in StdSetDefs) set_i where\n    \"set_i [] s = s\" |\n    \"set_i (a#l) s = set_i l (ins a s)\"\n  setup Locale_Code.close_block\n\n  -- \"Correct implementation of ca\"\n  lemma (in StdSet) set_i_impl: \"invar s \\<Longrightarrow> invar (set_i l s) \\<and> \\<alpha> (set_i l s) = set_a l (\\<alpha> s)\"\n    by (induct l arbitrary: s) (auto simp add: correct)\n\n  -- \"Instantiation\"\n  (* We need to declare a constant to make the code generator work *)\n\n  definition \"hs_seti == hs.set_i\"\n  (*declare hs.set_i.simps[folded hs_seti_def, code]*)\n\n  lemmas hs_set_i_impl = hs.set_i_impl[folded hs_seti_def]\n\nexport_code hs_seti in SML\n\n  -- \"Code generation\"\n  ML {* @{code hs_seti} *} \n  (*value \"hs_seti [1,2,3::nat] hs_empty\"*)\n\n  subsubsection \"Tail-Recursive version\"\n  -- \"Abstract algorithm\"\n  fun set_a2 where\n    \"set_a2 [] = {}\" |\n    \"set_a2 (a#l) = (insert a (set_a2 l))\"\n\n  -- \"Correctness of aa\"\n  lemma set_a2_correct: \"set_a2 l = set l\"\n    by (induct l) auto\n\n  -- \"Generic algorithm\"\n  setup Locale_Code.open_block\n  fun (in StdSetDefs) set_i2 where\n    \"set_i2 [] = empty ()\" |\n    \"set_i2 (a#l) = (ins a (set_i2 l))\"\n  setup Locale_Code.close_block\n\n  -- \"Correct implementation of ca\"\n  lemma (in StdSet) set_i2_impl: \"invar s \\<Longrightarrow> invar (set_i2 l) \\<and> \\<alpha> (set_i2 l) = set_a2 l\"\n    by (induct l) (auto simp add: correct)\n\n  -- \"Instantiation\"\n  definition \"hs_seti2 == hs.set_i2\"\n  (*declare hsr.set_i2.simps[folded hs_seti2_def, code]*)\n\n  lemmas hs_set_i2_impl = hs.set_i2_impl[folded hs_seti2_def]\n\n  -- \"Code generation\"\n  ML {* @{code hs_seti2} *} \n  (*value \"hs_seti [1,2,3::nat] hs_empty\"*)\n\nsubsubsection \"With explicit operation parameters\"\n\n  -- \"Alternative for few operation parameters\"\n  fun set_i' where\n    \"!!ins. set_i' ins [] s = s\" |\n    \"!!ins. set_i' ins (a#l) s = set_i' ins l (ins a s)\"\n\n  lemma (in StdSet) set_i'_impl:\n    \"invar s \\<Longrightarrow> invar (set_i' ins l s) \\<and> \\<alpha> (set_i' ins l s) = set_a l (\\<alpha> s)\"\n    by (induct l arbitrary: s) (auto simp add: correct)\n\n  -- \"Instantiation\"\n  definition \"hs_seti' == set_i' hs.ins\"\n  lemmas hs_set_i'_impl = hs.set_i'_impl[folded hs_seti'_def]\n\n  -- \"Code generation\"\n  ML {* @{code hs_seti'} *} \n  (*value \"hs_seti' [1,2,3::nat] hs_empty\"*)\n\n\nsubsection \"Filter Average\"\ntext {*\n  In this more complex example, we develop a function that filters from a set all\n  numbers that are above the average of the set.\n \n  First, we formulate this as a generic algorithm using a locale.\n  This solution shows how the ICF v2 overcomes some technical problems that\n  ICF v1 had: \n  \\begin{itemize}\n    \\item Iterators are now polymorphic in the type, even inside locales.\n      Hence, there is no special handling of iterators, as it was required\n      in ICF v1.\n    \\item The Locale-Code package handles code generation for the instantiated\n      locale. There is no need for lengthy boilerplate code as it was required\n      in ICF v1.\n  \\end{itemize}\n\n\n  Another possibility is to fix the used \n  implementations beforehand. Changing the implementation is still easy by\n  changing the used operations. In this example, all used operations are \n  introduced by abbbreviations, localizing the required changes to a small part\n  of the theory. This approach is more powerful, as operations are now \n  polymorphic also in the element type. However, it only allows as single \n  instantiation at a time, which is no option for generic algorithms.\n*}\n\n  abbreviation \"average S == \\<Sum>S div card S\"\n\nsubsubsection \"Generic Algorithm\"\n  locale MyContext =\n    StdSet ops for ops :: \"(nat,'s,'more) set_ops_scheme\"\n  begin\n    definition avg_aux :: \"'s \\<Rightarrow> nat\\<times>nat\" \n      where\n      \"avg_aux s == iterate s (\\<lambda>x (c,s). (c+1, s+x)) (0,0)\"\n\n    definition \"avg s == case avg_aux s of (c,s) \\<Rightarrow> s div c\"\n\n    definition \"filter_le_avg s == let a=avg s in\n      iterate s (\\<lambda>x s. if x\\<le>a then ins x s else s) (empty ())\"\n\n    lemma avg_aux_correct: \"invar s \\<Longrightarrow> avg_aux s = (card (\\<alpha> s), \\<Sum>(\\<alpha> s) )\"\n      apply (unfold avg_aux_def)\n      apply (rule_tac \n        I=\"\\<lambda>it (c,sum). c=card (\\<alpha> s - it) \\<and> sum=\\<Sum>(\\<alpha> s - it)\" \n        in iterate_rule_P)\n      apply auto\n      apply (subgoal_tac \"\\<alpha> s - (it - {x}) = insert x (\\<alpha> s - it)\")\n      apply auto\n      apply (subgoal_tac \"\\<alpha> s - (it - {x}) = insert x (\\<alpha> s - it)\")\n      apply auto\n      done\n\n    lemma avg_correct: \"invar s \\<Longrightarrow> avg s = average (\\<alpha> s)\"\n      unfolding avg_def\n      using avg_aux_correct\n      by auto\n\n    lemma filter_le_avg_correct: \n      \"invar s \\<Longrightarrow> \n        invar (filter_le_avg s) \\<and> \n        \\<alpha> (filter_le_avg s) = {x\\<in>\\<alpha> s. x\\<le>average (\\<alpha> s)}\"\n      unfolding filter_le_avg_def Let_def\n      apply (rule_tac\n        I=\"\\<lambda>it r. invar r \\<and> \\<alpha> r = {x\\<in>\\<alpha> s - it. x\\<le>average (\\<alpha> s)}\"\n        in iterate_rule_P)\n      apply (auto simp add: correct avg_correct)\n      done\n  end\n\n  setup Locale_Code.open_block\n  interpretation hs_ctx: MyContext hs_ops by unfold_locales\n  interpretation rs_ctx: MyContext rs_ops by unfold_locales\n  setup Locale_Code.close_block\n\n  definition \"hs_flt_avg_test \\<equiv> hs.to_list \n    o hs_ctx.filter_le_avg \n    o hs.from_list\"\n  definition \"rs_flt_avg_test \\<equiv> rs.to_list \n    o rs_ctx.filter_le_avg \n    o rs.from_list\"\n\n  \n  text \"Code generation\"\n  ML_val {* \n    if @{code hs_flt_avg_test} (map @{code nat_of_integer} [1,2,3,4,6,7])\n    <> @{code rs_flt_avg_test} (map @{code nat_of_integer} [1,2,3,4,6,7])\n    then error \"Oops\"\n    else ()\n    *} \n  \n\nsubsubsection \"Using abbreviations\"\n\n  type_synonym 'a my_set = \"'a hs\"\n  abbreviation \"my_\\<alpha> == hs.\\<alpha>\"\n  abbreviation \"my_invar == hs.invar\"\n  abbreviation \"my_empty == hs.empty\"\n  abbreviation \"my_ins == hs.ins\"\n  abbreviation \"my_iterate == hs.iteratei\"\n  lemmas my_correct = hs.correct\n  lemmas my_iterate_rule_P = hs.iterate_rule_P\n\n  definition avg_aux :: \"nat my_set \\<Rightarrow> nat\\<times>nat\" \n    where\n    \"avg_aux s == my_iterate s (\\<lambda>_. True) (\\<lambda>x (c,s). (c+1, s+x)) (0,0)\"\n\n  definition \"avg s == case avg_aux s of (c,s) \\<Rightarrow> s div c\"\n\n  definition \"filter_le_avg s == let a=avg s in\n    my_iterate s (\\<lambda>_. True) (\\<lambda>x s. if x\\<le>a then my_ins x s else s) (my_empty ())\"\n\n  lemma avg_aux_correct: \"my_invar s \\<Longrightarrow> avg_aux s = (card (my_\\<alpha> s), \\<Sum>(my_\\<alpha> s) )\"\n    apply (unfold avg_aux_def)\n    apply (rule_tac \n      I=\"\\<lambda>it (c,sum). c=card (my_\\<alpha> s - it) \\<and> sum=\\<Sum>(my_\\<alpha> s - it)\" \n      in my_iterate_rule_P)\n    apply auto\n    apply (subgoal_tac \"my_\\<alpha> s - (it - {x}) = insert x (my_\\<alpha> s - it)\")\n    apply auto\n    apply (subgoal_tac \"my_\\<alpha> s - (it - {x}) = insert x (my_\\<alpha> s - it)\")\n    apply auto\n    done\n\n  lemma avg_correct: \"my_invar s \\<Longrightarrow> avg s = average (my_\\<alpha> s)\"\n    unfolding avg_def\n    using avg_aux_correct\n    by auto\n\n  lemma filter_le_avg_correct: \n    \"my_invar s \\<Longrightarrow> \n    my_invar (filter_le_avg s) \\<and> \n    my_\\<alpha> (filter_le_avg s) = {x\\<in>my_\\<alpha> s. x\\<le>average (my_\\<alpha> s)}\"\n    unfolding filter_le_avg_def Let_def\n    apply (rule_tac\n      I=\"\\<lambda>it r. my_invar r \\<and> my_\\<alpha> r = {x\\<in>my_\\<alpha> s - it. x\\<le>average (my_\\<alpha> s)}\"\n      in my_iterate_rule_P)\n    apply (auto simp add: my_correct avg_correct)\n    done\n\n\n  definition \"test_set == my_ins (1::nat) (my_ins 2 (my_ins 3 (my_empty ())))\"\n\n  export_code avg_aux avg filter_le_avg test_set in SML module_name Test\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/examples/ICF/itp_2010.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673133042217, "lm_q2_score": 0.8976952907388474, "lm_q1q2_score": 0.729707159148739}}
{"text": "(*  Title:      HOL/Examples/Cantor.thy\n    Author:     Makarius\n*)\n\nsection \\<open>Cantor's Theorem\\<close>\n\ntheory Cantor\n  imports Main\nbegin\n\nsubsection \\<open>Mathematical statement and proof\\<close>\n\ntext \\<open>\n  Cantor's Theorem states that there is no surjection from\n  a set to its powerset.  The proof works by diagonalization.  E.g.\\ see\n  \\<^item> \\<^url>\\<open>http://mathworld.wolfram.com/CantorDiagonalMethod.html\\<close>\n  \\<^item> \\<^url>\\<open>https://en.wikipedia.org/wiki/Cantor's_diagonal_argument\\<close>\n\\<close>\n\ntheorem Cantor: \"\\<nexists>f :: 'a \\<Rightarrow> 'a set. \\<forall>A. \\<exists>x. A = f x\"\nproof\n  assume \"\\<exists>f :: 'a \\<Rightarrow> 'a set. \\<forall>A. \\<exists>x. A = f x\"\n  then obtain f :: \"'a \\<Rightarrow> 'a set\" where *: \"\\<forall>A. \\<exists>x. A = f x\" ..\n  let ?D = \"{x. x \\<notin> f x}\"\n  from * obtain a where \"?D = f a\" by blast\n  moreover have \"a \\<in> ?D \\<longleftrightarrow> a \\<notin> f a\" by blast\n  ultimately show False by blast\nqed\n\n\nsubsection \\<open>Automated proofs\\<close>\n\ntext \\<open>\n  These automated proofs are much shorter, but lack information why and how it\n  works.\n\\<close>\n\ntheorem \"\\<nexists>f :: 'a \\<Rightarrow> 'a set. \\<forall>A. \\<exists>x. f x = A\"\n  by best\n\ntheorem \"\\<nexists>f :: 'a \\<Rightarrow> 'a set. \\<forall>A. \\<exists>x. f x = A\"\n  by force\n\n\nsubsection \\<open>Elementary version in higher-order predicate logic\\<close>\n\ntext \\<open>\n  The subsequent formulation bypasses set notation of HOL; it uses elementary\n  \\<open>\\<lambda>\\<close>-calculus and predicate logic, with standard introduction and elimination\n  rules. This also shows that the proof does not require classical reasoning.\n\\<close>\n\nlemma iff_contradiction:\n  assumes *: \"\\<not> A \\<longleftrightarrow> A\"\n  shows False\nproof (rule notE)\n  show \"\\<not> A\"\n  proof\n    assume A\n    with * have \"\\<not> A\" ..\n    from this and \\<open>A\\<close> show False ..\n  qed\n  with * show A ..\nqed\n\ntheorem Cantor': \"\\<nexists>f :: 'a \\<Rightarrow> 'a \\<Rightarrow> bool. \\<forall>A. \\<exists>x. A = f x\"\nproof\n  assume \"\\<exists>f :: 'a \\<Rightarrow> 'a \\<Rightarrow> bool. \\<forall>A. \\<exists>x. A = f x\"\n  then obtain f :: \"'a \\<Rightarrow> 'a \\<Rightarrow> bool\" where *: \"\\<forall>A. \\<exists>x. A = f x\" ..\n  let ?D = \"\\<lambda>x. \\<not> f x x\"\n  from * have \"\\<exists>x. ?D = f x\" ..\n  then obtain a where \"?D = f a\" ..\n  then have \"?D a \\<longleftrightarrow> f a a\" by (rule arg_cong)\n  then have \"\\<not> f a a \\<longleftrightarrow> f a a\" .\n  then show False by (rule iff_contradiction)\nqed\n\n\nsubsection \\<open>Classic Isabelle/HOL example\\<close>\n\ntext \\<open>\n  The following treatment of Cantor's Theorem follows the classic example from\n  the early 1990s, e.g.\\ see the file \\<^verbatim>\\<open>92/HOL/ex/set.ML\\<close> in\n  Isabelle92 or \\<^cite>\\<open>\\<open>\\S18.7\\<close> in \"paulson-isa-book\"\\<close>. The old tactic scripts\n  synthesize key information of the proof by refinement of schematic goal\n  states. In contrast, the Isar proof needs to say explicitly what is proven.\n\n  \\<^bigskip>\n  Cantor's Theorem states that every set has more subsets than it has\n  elements. It has become a favourite basic example in pure higher-order logic\n  since it is so easily expressed:\n\n  @{text [display]\n  \\<open>\\<forall>f::\\<alpha> \\<Rightarrow> \\<alpha> \\<Rightarrow> bool. \\<exists>S::\\<alpha> \\<Rightarrow> bool. \\<forall>x::\\<alpha>. f x \\<noteq> S\\<close>}\n\n  Viewing types as sets, \\<open>\\<alpha> \\<Rightarrow> bool\\<close> represents the powerset of \\<open>\\<alpha>\\<close>. This\n  version of the theorem states that for every function from \\<open>\\<alpha>\\<close> to its\n  powerset, some subset is outside its range. The Isabelle/Isar proofs below\n  uses HOL's set theory, with the type \\<open>\\<alpha> set\\<close> and the operator \\<open>range :: (\\<alpha> \\<Rightarrow>\n  \\<beta>) \\<Rightarrow> \\<beta> set\\<close>.\n\\<close>\n\ntheorem \"\\<exists>S. S \\<notin> range (f :: 'a \\<Rightarrow> 'a set)\"\nproof\n  let ?S = \"{x. x \\<notin> f x}\"\n  show \"?S \\<notin> range f\"\n  proof\n    assume \"?S \\<in> range f\"\n    then obtain y where \"?S = f y\" ..\n    then show False\n    proof (rule equalityCE)\n      assume \"y \\<in> f y\"\n      assume \"y \\<in> ?S\"\n      then have \"y \\<notin> f y\" ..\n      with \\<open>y \\<in> f y\\<close> show ?thesis by contradiction\n    next\n      assume \"y \\<notin> ?S\"\n      assume \"y \\<notin> f y\"\n      then have \"y \\<in> ?S\" ..\n      with \\<open>y \\<notin> ?S\\<close> show ?thesis by contradiction\n    qed\n  qed\nqed\n\ntext \\<open>\n  How much creativity is required? As it happens, Isabelle can prove this\n  theorem automatically using best-first search. Depth-first search would\n  diverge, but best-first search successfully navigates through the large\n  search space. The context of Isabelle's classical prover contains rules for\n  the relevant constructs of HOL's set theory.\n\\<close>\n\ntheorem \"\\<exists>S. S \\<notin> range (f :: 'a \\<Rightarrow> 'a set)\"\n  by best\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/Cantor.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8397339756938819, "lm_q2_score": 0.8688267830311354, "lm_q1q2_score": 0.729583368704061}}
{"text": "(*  Author:      Christian Sternagel <c.sternagel@gmail.com>\n    Maintainer:  Christian Sternagel <c.sternagel@gmail.com>\n*)\ntheory Mergesort_Complexity\n  imports\n    Efficient_Sort\n    Complex_Main\nbegin\n\n(*TODO: move?*)\nlemma log2_mono:\n  \"x > 0 \\<Longrightarrow> x \\<le> y \\<Longrightarrow> log 2 x \\<le> log 2 y\"\n  by auto\n\n\nsection \\<open>Counting the Number of Comparisons\\<close>\n\ncontext\n  fixes key :: \"'a \\<Rightarrow> 'k::linorder\"\nbegin\n\nfun c_merge :: \"'a list \\<Rightarrow> 'a list \\<Rightarrow> nat\"\n  where\n    \"c_merge (x # xs) (y # ys) =\n      1 + (if key y < key x then c_merge (x # xs) ys else c_merge xs (y # ys))\"\n  | \"c_merge [] ys = 0\"\n  | \"c_merge xs [] = 0\"\n\nfun c_merge_pairs :: \"'a list list \\<Rightarrow> nat\"\n  where\n    \"c_merge_pairs (xs # ys # zss) = c_merge xs ys + c_merge_pairs zss\"\n  | \"c_merge_pairs [] = 0\"\n  | \"c_merge_pairs [x] = 0\"\n\nfun c_merge_all :: \"'a list list \\<Rightarrow> nat\"\n  where\n    \"c_merge_all [] = 0\"\n  | \"c_merge_all [x] = 0\"\n  | \"c_merge_all xss = c_merge_pairs xss + c_merge_all (merge_pairs key xss)\"\n\nfun c_sequences :: \"'a list \\<Rightarrow> nat\"\n  and c_asc :: \"'a \\<Rightarrow> 'a list \\<Rightarrow> nat\"\n  and c_desc :: \"'a \\<Rightarrow> 'a list \\<Rightarrow> nat\"\n  where\n    \"c_sequences (x # y # zs) = 1 + (if key y < key x then c_desc y zs else c_asc y zs)\"\n  | \"c_sequences [] = 0\"\n  | \"c_sequences [x] = 0\"\n  | \"c_asc x (y # ys) = 1 + (if \\<not> key y < key x then c_asc y ys else c_sequences (y # ys))\"\n  | \"c_asc x [] = 0\"\n  | \"c_desc x (y # ys) = 1 + (if key y < key x then c_desc y ys else c_sequences (y # ys))\"\n  | \"c_desc x [] = 0\"\n\nfun c_msort :: \"'a list \\<Rightarrow> nat\"\n  where\n    \"c_msort xs = c_sequences xs + c_merge_all (sequences key xs)\"\n\nlemma c_merge:\n  \"c_merge xs ys \\<le> length xs + length ys\"\n  by (induct xs ys rule: c_merge.induct) simp_all\n\nlemma c_merge_pairs:\n  \"c_merge_pairs xss \\<le> length (concat xss)\"\nproof (induct xss rule: c_merge_pairs.induct)\n  case (1 xs ys zss)\n  then show ?case using c_merge [of xs ys] by simp\nqed simp_all\n\nlemma c_merge_all:\n  \"c_merge_all xss \\<le> length (concat xss) * \\<lceil>log 2 (length xss)\\<rceil>\"\nproof (induction xss rule: c_merge_all.induct)\n  case (3 xs ys zss)\n  let ?clen = \"\\<lambda>xs. length (concat xs)\"\n  let ?xss = \"xs # ys # zss\"\n  let ?xss2 = \"merge_pairs key ?xss\"\n\n  have *: \"\\<lceil>log 2 (real n + 2)\\<rceil> = \\<lceil>log 2 (Suc n div 2 + 1)\\<rceil> + 1\" for n :: nat\n    using ceiling_log2_div2 [of \"n + 2\"] by (simp add: algebra_simps)\n\n  have \"c_merge_all ?xss = c_merge_pairs ?xss + c_merge_all ?xss2\" by simp\n  also have \"\\<dots> \\<le> ?clen ?xss + c_merge_all ?xss2\"\n    using c_merge [of xs ys] and c_merge_pairs [of ?xss] by auto\n  also have \"\\<dots> \\<le> ?clen ?xss + ?clen ?xss2 * \\<lceil>log 2 (length ?xss2)\\<rceil>\"\n    using \"3.IH\" by simp\n  also have \"\\<dots> \\<le> ?clen ?xss * \\<lceil>log 2 (length ?xss)\\<rceil>\"\n    by (auto simp: * algebra_simps)\n  finally show ?case by simp\nqed simp_all\n\nlemma\n  shows c_sequences: \"c_sequences xs \\<le> length xs - 1\"\n    and c_asc: \"c_asc x ys \\<le> length ys\"\n    and c_desc: \"c_desc x ys \\<le> length ys\"\n  by (induct xs and x ys and x ys rule: c_sequences_c_asc_c_desc.induct) simp_all\n\nlemma\n  shows length_concat_sequences [simp]: \"length (concat (sequences key xs)) = length xs\"\n    and length_concat_asc: \"ascP f \\<Longrightarrow> length (concat (asc key a f ys)) = 1 + length (f []) + length ys\"\n    and length_concat_desc: \"length (concat (desc key a xs ys)) = 1 + length xs + length ys\"\n  by (induct xs and a f ys and a xs ys rule: sequences_asc_desc.induct)\n    (auto simp: ascP_f_singleton)\n\nlemma\n  shows sequences_ne: \"xs \\<noteq> [] \\<Longrightarrow> sequences key xs \\<noteq> []\"\n    and asc_ne: \"ascP f \\<Longrightarrow> asc key a f ys \\<noteq> []\"\n    and desc_ne: \"desc key a xs ys \\<noteq> []\"\n  by (induct xs and a f ys and a xs ys taking: key rule: sequences_asc_desc.induct) simp_all\n\nlemma c_msort:\n  assumes [simp]: \"length xs = n\"\n  shows \"c_msort xs \\<le> n + n * \\<lceil>log 2 n\\<rceil>\"\nproof -\n  have [simp]: \"xs = [] \\<longleftrightarrow> length xs = 0\" by blast\n  have \"int (c_merge_all (sequences key xs)) \\<le> int n * \\<lceil>log 2 (length (sequences key xs))\\<rceil>\"\n    using c_merge_all [of \"sequences key xs\"] by simp\n  also have \"\\<dots> \\<le> int n * \\<lceil>log 2 n\\<rceil>\"\n    using length_sequences [of key xs]\n    by (cases n) (auto intro!: sequences_ne mult_mono ceiling_mono log2_mono)\n  finally have \"int (c_merge_all (sequences key xs)) \\<le> int n * \\<lceil>log 2 n\\<rceil>\" .\n  moreover have \"c_sequences xs \\<le> n\" using c_sequences [of xs] by auto\n  ultimately show ?thesis by (auto intro: add_mono)\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/Efficient-Mergesort/Mergesort_Complexity.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267830311354, "lm_q2_score": 0.8397339656668287, "lm_q1q2_score": 0.7295833599922886}}
{"text": "(*  Title:       FunctorCategory\n    Author:      Eugene W. Stark <stark@cs.stonybrook.edu>, 2016\n    Maintainer:  Eugene W. Stark <stark@cs.stonybrook.edu>\n*)\n\nchapter FunctorCategory\n\ntheory FunctorCategory\nimports ConcreteCategory BinaryFunctor\nbegin\n\n  text\\<open>\n    The functor category \\<open>[A, B]\\<close> is the category whose objects are functors\n    from @{term A} to @{term B} and whose arrows correspond to natural transformations\n    between these functors.\n\\<close>\n\n  section \"Construction\"\n\n  text\\<open>\n    Since the arrows of a functor category cannot (in the context of the present development)\n    be directly identified with natural transformations, but rather only with natural\n    transformations that have been equipped with their domain and codomain functors,\n    and since there is no natural value to serve as @{term null},\n    we use the general-purpose construction given by @{locale concrete_category} to define\n    this category.\n\\<close>\n\n  locale functor_category =\n    A: category A +\n    B: category B\n  for A :: \"'a comp\"     (infixr \"\\<cdot>\\<^sub>A\" 55)\n  and B :: \"'b comp\"     (infixr \"\\<cdot>\\<^sub>B\" 55)\n  begin\n\n    notation A.in_hom    (\"\\<guillemotleft>_ : _ \\<rightarrow>\\<^sub>A _\\<guillemotright>\")\n    notation B.in_hom    (\"\\<guillemotleft>_ : _ \\<rightarrow>\\<^sub>B _\\<guillemotright>\")\n\n    type_synonym ('aa, 'bb) arr = \"('aa \\<Rightarrow> 'bb, 'aa \\<Rightarrow> 'bb) concrete_category.arr\"\n\n    sublocale concrete_category \\<open>Collect (functor A B)\\<close>\n      \\<open>\\<lambda>F G. Collect (natural_transformation A B F G)\\<close> \\<open>\\<lambda>F. F\\<close>\n      \\<open>\\<lambda>F G H \\<tau> \\<sigma>. vertical_composite.map A B \\<sigma> \\<tau>\\<close>\n      using vcomp_assoc\n      apply (unfold_locales, simp_all)\n    proof -\n      fix F G H \\<sigma> \\<tau>\n      assume F: \"functor (\\<cdot>\\<^sub>A) (\\<cdot>\\<^sub>B) F\"\n      assume G: \"functor (\\<cdot>\\<^sub>A) (\\<cdot>\\<^sub>B) G\"\n      assume H: \"functor (\\<cdot>\\<^sub>A) (\\<cdot>\\<^sub>B) H\"\n      assume \\<sigma>: \"natural_transformation (\\<cdot>\\<^sub>A) (\\<cdot>\\<^sub>B) F G \\<sigma>\"\n      assume \\<tau>: \"natural_transformation (\\<cdot>\\<^sub>A) (\\<cdot>\\<^sub>B) G H \\<tau>\"\n      interpret F: \"functor\" A B F using F by simp\n      interpret G: \"functor\" A B G using G by simp\n      interpret H: \"functor\" A B H using H by simp\n      interpret \\<sigma>: natural_transformation A B F G \\<sigma>\n        using \\<sigma> by simp\n      interpret \\<tau>: natural_transformation A B G H \\<tau>\n        using \\<tau> by simp\n      interpret \\<tau>\\<sigma>: vertical_composite A B F G H \\<sigma> \\<tau>\n        ..\n      show \"natural_transformation (\\<cdot>\\<^sub>A) (\\<cdot>\\<^sub>B) F H (vertical_composite.map (\\<cdot>\\<^sub>A) (\\<cdot>\\<^sub>B) \\<sigma> \\<tau>)\"\n        using \\<tau>\\<sigma>.map_def \\<tau>\\<sigma>.is_natural_transformation by simp\n    qed\n\n    abbreviation comp      (infixr \"\\<cdot>\" 55)\n    where \"comp \\<equiv> COMP\"\n    notation in_hom        (\"\\<guillemotleft>_ : _ \\<rightarrow> _\\<guillemotright>\")\n\n    lemma arrI [intro]:\n    assumes \"f \\<noteq> null\" and \"natural_transformation A B (Dom f) (Cod f) (Map f)\"\n    shows \"arr f\"\n      using assms arr_char null_char\n      by (simp add: natural_transformation_def)\n\n    lemma arrE [elim]:\n    assumes \"arr f\"\n    and \"f \\<noteq> null \\<Longrightarrow> natural_transformation A B (Dom f) (Cod f) (Map f) \\<Longrightarrow> T\"\n    shows T\n      using assms arr_char null_char by simp\n\n    lemma arr_MkArr [iff]:\n    shows \"arr (MkArr F G \\<tau>) \\<longleftrightarrow> natural_transformation A B F G \\<tau>\"\n      using arr_char null_char arr_MkArr natural_transformation_def by fastforce\n\n    lemma ide_char [iff]:\n    shows \"ide t \\<longleftrightarrow> t \\<noteq> null \\<and> functor A B (Map t) \\<and> Dom t = Map t \\<and> Cod t = Map t\"\n      using ide_char null_char by fastforce\n\n  end\n\n  section \"Additional Properties\"\n\n  text\\<open>\n    In this section some additional facts are proved, which make it easier to\n    work with the @{term \"functor_category\"} locale.\n\\<close>\n\n  context functor_category\n  begin\n\n    lemma Map_comp [simp]:\n    assumes \"seq t' t\" and \"A.seq a' a\"\n    shows \"Map (t' \\<cdot> t) (a' \\<cdot>\\<^sub>A a) = Map t' a' \\<cdot>\\<^sub>B Map t a\"\n    proof -\n      interpret t: natural_transformation A B \\<open>Dom t\\<close> \\<open>Cod t\\<close> \\<open>Map t\\<close>\n        using assms(1) arr_char seq_char by blast\n      interpret t': natural_transformation A B \\<open>Cod t\\<close> \\<open>Cod t'\\<close> \\<open>Map t'\\<close>\n        using assms(1) arr_char seq_char by force \n      interpret t'ot: vertical_composite A B \\<open>Dom t\\<close> \\<open>Cod t\\<close> \\<open>Cod t'\\<close> \\<open>Map t\\<close> \\<open>Map t'\\<close> ..\n      show ?thesis\n      proof -\n        have \"Map (t' \\<cdot> t) = t'ot.map\"\n          using assms(1) seq_char t'ot.natural_transformation_axioms by simp\n        thus ?thesis\n          using assms(2) t'ot.map_simp_2 t'.preserves_comp_2 B.comp_assoc by auto\n      qed\n    qed\n\n    lemma Map_comp':\n    assumes \"seq t' t\"\n    shows \"Map (t' \\<cdot> t) = vertical_composite.map A B (Map t) (Map t')\"\n    proof -\n      interpret t: natural_transformation A B \\<open>Dom t\\<close> \\<open>Cod t\\<close> \\<open>Map t\\<close>\n        using assms(1) arr_char seq_char by blast\n      interpret t': natural_transformation A B \\<open>Cod t\\<close> \\<open>Cod t'\\<close> \\<open>Map t'\\<close>\n        using assms(1) arr_char seq_char by force \n      interpret t'ot: vertical_composite A B \\<open>Dom t\\<close> \\<open>Cod t\\<close> \\<open>Cod t'\\<close> \\<open>Map t\\<close> \\<open>Map t'\\<close> ..\n      show ?thesis\n        using assms(1) seq_char t'ot.natural_transformation_axioms by simp\n    qed\n\n    lemma MkArr_eqI [intro]:\n    assumes \"arr (MkArr F G \\<tau>)\"\n    and \"F = F'\" and \"G = G'\" and \"\\<tau> = \\<tau>'\"\n    shows \"MkArr F G \\<tau> = MkArr F' G' \\<tau>'\"\n      using assms arr_eqI by simp\n\n    lemma MkArr_eqI' [intro]:\n    assumes \"arr (MkArr F G \\<tau>)\" and \"\\<tau> = \\<tau>'\"\n    shows \"MkArr F G \\<tau> = MkArr F G \\<tau>'\"\n      using assms arr_eqI by simp\n\n    lemma iso_char [iff]:\n    shows \"iso t \\<longleftrightarrow> t \\<noteq> null \\<and> natural_isomorphism A B (Dom t) (Cod t) (Map t)\"\n    proof\n      assume t: \"iso t\"\n      show \"t \\<noteq> null \\<and> natural_isomorphism A B (Dom t) (Cod t) (Map t)\"\n      proof\n        show \"t \\<noteq> null\" using t arr_char iso_is_arr by auto\n        from t obtain t' where t': \"inverse_arrows t t'\" by blast\n        interpret \\<tau>: natural_transformation A B \\<open>Dom t\\<close> \\<open>Cod t\\<close> \\<open>Map t\\<close>\n          using t arr_char iso_is_arr by auto\n        interpret \\<tau>': natural_transformation A B \\<open>Cod t\\<close> \\<open>Dom t\\<close> \\<open>Map t'\\<close>\n          using t' arr_char dom_char seq_char\n          by (metis arrE ide_compE inverse_arrowsE)\n        interpret \\<tau>'o\\<tau>: vertical_composite A B \\<open>Dom t\\<close> \\<open>Cod t\\<close> \\<open>Dom t\\<close> \\<open>Map t\\<close> \\<open>Map t'\\<close> ..\n        interpret \\<tau>o\\<tau>': vertical_composite A B \\<open>Cod t\\<close> \\<open>Dom t\\<close> \\<open>Cod t\\<close> \\<open>Map t'\\<close> \\<open>Map t\\<close> ..\n        show \"natural_isomorphism A B (Dom t) (Cod t) (Map t)\"\n        proof\n          fix a\n          assume a: \"A.ide a\"\n          show \"B.iso (Map t a)\"\n          proof\n            have 1: \"\\<tau>'o\\<tau>.map = Dom t \\<and> \\<tau>o\\<tau>'.map = Cod t\"\n              using t t'\n              by (metis (no_types, lifting) Map_dom concrete_category.Map_comp\n                  concrete_category_axioms ide_compE inverse_arrowsE seq_char)\n            show \"B.inverse_arrows (Map t a) (Map t' a)\"\n              using a 1 \\<tau>o\\<tau>'.map_simp_ide \\<tau>'o\\<tau>.map_simp_ide \\<tau>.F.preserves_ide \\<tau>.G.preserves_ide\n              by auto\n          qed\n        qed\n      qed\n      next\n      assume t: \"t \\<noteq> null \\<and> natural_isomorphism A B (Dom t) (Cod t) (Map t)\"\n      show \"iso t\"\n      proof\n        interpret \\<tau>: natural_isomorphism A B \\<open>Dom t\\<close> \\<open>Cod t\\<close> \\<open>Map t\\<close>\n          using t by auto\n        interpret \\<tau>': inverse_transformation A B \\<open>Dom t\\<close> \\<open>Cod t\\<close> \\<open>Map t\\<close> ..\n        have 1: \"vertical_composite.map A B (Map t) \\<tau>'.map = Dom t \\<and>\n                 vertical_composite.map A B \\<tau>'.map (Map t) = Cod t\"\n          using \\<tau>.natural_isomorphism_axioms vertical_composite_inverse_iso\n                vertical_composite_iso_inverse\n          by blast\n        show \"inverse_arrows t (MkArr (Cod t) (Dom t) (\\<tau>'.map))\"\n        proof\n          show 2: \"ide (MkArr (Cod t) (Dom t) \\<tau>'.map \\<cdot> t)\"\n            using t 1\n            by (metis (no_types, lifting) MkArr_Map MkIde_Dom \\<tau>'.natural_transformation_axioms\n                \\<tau>.natural_transformation_axioms arrI arr_MkArr comp_MkArr ide_dom)\n          show \"ide (t \\<cdot> MkArr (Cod t) (Dom t) \\<tau>'.map)\"\n            using t 1 2\n            by (metis Map.simps(1) \\<tau>'.natural_transformation_axioms arr_MkArr comp_char\n                dom_MkArr dom_comp ide_char' ide_compE)\n        qed\n      qed\n    qed\n\n  end\n\n  section \"Evaluation Functor\"\n\n  text\\<open>\n    This section defines the evaluation map that applies an arrow of the functor\n    category \\<open>[A, B]\\<close> to an arrow of @{term A} to obtain an arrow of @{term B}\n    and shows that it is functorial.\n\\<close>\n\n  locale evaluation_functor =\n    A: category A +\n    B: category B +\n    A_B: functor_category A B +\n    A_BxA: product_category A_B.comp A\n  for A :: \"'a comp\"          (infixr \"\\<cdot>\\<^sub>A\" 55)\n  and B :: \"'b comp\"          (infixr \"\\<cdot>\\<^sub>B\" 55)\n  begin\n\n    notation A_B.comp         (infixr \"\\<cdot>\\<^sub>[\\<^sub>A\\<^sub>,\\<^sub>B\\<^sub>]\" 55)\n    notation A_BxA.comp       (infixr \"\\<cdot>\\<^sub>[\\<^sub>A\\<^sub>,\\<^sub>B\\<^sub>]\\<^sub>x\\<^sub>A\" 55)\n    notation A_B.in_hom       (\"\\<guillemotleft>_ : _ \\<rightarrow>\\<^sub>[\\<^sub>A\\<^sub>,\\<^sub>B\\<^sub>] _\\<guillemotright>\")\n    notation A_BxA.in_hom     (\"\\<guillemotleft>_ : _ \\<rightarrow>\\<^sub>[\\<^sub>A\\<^sub>,\\<^sub>B\\<^sub>]\\<^sub>x\\<^sub>A _\\<guillemotright>\")\n\n    definition map\n    where \"map Fg \\<equiv> if A_BxA.arr Fg then A_B.Map (fst Fg) (snd Fg) else B.null\"\n\n    lemma map_simp:\n    assumes \"A_BxA.arr Fg\"\n    shows \"map Fg = A_B.Map(fst Fg) (snd Fg)\"\n      using assms map_def by auto\n\n    lemma is_functor:\n    shows \"functor A_BxA.comp B map\"\n    proof\n      show \"\\<And>Fg. \\<not> A_BxA.arr Fg \\<Longrightarrow> map Fg = B.null\"\n        using map_def by auto\n      fix Fg\n      assume Fg: \"A_BxA.arr Fg\"\n      let ?F = \"fst Fg\" and ?g = \"snd Fg\"\n      have F: \"A_B.arr ?F\" using Fg by auto\n      have g: \"A.arr ?g\" using Fg by auto\n      have DomF: \"A_B.Dom ?F = A_B.Map (A_B.dom ?F)\" using F by simp\n      have CodF: \"A_B.Cod ?F = A_B.Map (A_B.cod ?F)\" using F by simp\n      interpret F: natural_transformation A B \\<open>A_B.Dom ?F\\<close> \\<open>A_B.Cod ?F\\<close> \\<open>A_B.Map ?F\\<close>\n        using Fg A_B.arr_char [of ?F] by blast\n      show \"B.arr (map Fg)\" using Fg map_def by auto\n      show \"B.dom (map Fg) = map (A_BxA.dom Fg)\"\n        using g Fg map_def DomF\n        by (metis (no_types, lifting) A_BxA.arr_dom A_BxA.dom_simp F.preserves_dom\n            fst_conv snd_conv)\n      show \"B.cod (map Fg) = map (A_BxA.cod Fg)\"\n        using g Fg map_def CodF\n        by (metis (no_types, lifting) A_BxA.arr_cod A_BxA.cod_simp F.preserves_cod\n            fst_conv snd_conv)\n      next\n      fix Fg Fg'\n      assume 1: \"A_BxA.seq Fg' Fg\"\n      let ?F = \"fst Fg\" and ?g = \"snd Fg\"\n      let ?F' = \"fst Fg'\" and ?g' = \"snd Fg'\"\n      have F': \"A_B.arr ?F'\" using 1 A_BxA.seqE by blast\n      have CodF: \"A_B.Cod ?F = A_B.Map (A_B.cod ?F)\"\n        using 1 by (metis A_B.Map_cod A_B.seqE A_BxA.seqE)\n      have DomF': \"A_B.Dom ?F' = A_B.Map (A_B.dom ?F')\"\n        using F' by simp\n      have seq_F'F: \"A_B.seq ?F' ?F\" using 1 by blast\n      have seq_g'g: \"A.seq ?g' ?g\" using 1 by blast\n      interpret F: natural_transformation A B \\<open>A_B.Dom ?F\\<close> \\<open>A_B.Cod ?F\\<close> \\<open>A_B.Map ?F\\<close>\n        using 1 A_B.arr_char by blast\n      interpret F': natural_transformation A B \\<open>A_B.Cod ?F\\<close> \\<open>A_B.Cod ?F'\\<close> \\<open>A_B.Map ?F'\\<close>\n        using 1 A_B.arr_char seq_F'F CodF DomF' A_B.seqE\n        by (metis mem_Collect_eq)\n      interpret F'oF: vertical_composite A B \\<open>A_B.Dom ?F\\<close> \\<open>A_B.Cod ?F\\<close> \\<open>A_B.Cod ?F'\\<close>\n                                             \\<open>A_B.Map ?F\\<close> \\<open>A_B.Map ?F'\\<close> ..\n      show \"map (Fg' \\<cdot>\\<^sub>[\\<^sub>A\\<^sub>,\\<^sub>B\\<^sub>]\\<^sub>x\\<^sub>A Fg) = map Fg' \\<cdot>\\<^sub>B map Fg\"\n        unfolding map_def\n        using 1 seq_F'F seq_g'g by auto\n    qed\n\n  end\n\n  sublocale evaluation_functor \\<subseteq> \"functor\" A_BxA.comp B map\n    using is_functor by auto\n  sublocale evaluation_functor \\<subseteq> binary_functor A_B.comp A B map ..\n\n  section \"Currying\"\n\n  text\\<open>\n    This section defines the notion of currying of a natural transformation\n    between binary functors, to obtain a natural transformation between\n    functors into a functor category, along with the inverse operation of uncurrying.\n    We have only proved here what is needed to establish the results\n    in theory \\<open>Limit\\<close> about limits in functor categories and have not\n    attempted to fully develop the functoriality and naturality properties of\n    these notions.\n\\<close>\n\n  locale currying =\n  A1: category A1 +\n  A2: category A2 +\n  B: category B\n  for A1 :: \"'a1 comp\"           (infixr \"\\<cdot>\\<^sub>A\\<^sub>1\" 55)\n  and A2 :: \"'a2 comp\"           (infixr \"\\<cdot>\\<^sub>A\\<^sub>2\" 55)\n  and B :: \"'b comp\"             (infixr \"\\<cdot>\\<^sub>B\" 55)\n  begin\n\n    interpretation A1xA2: product_category A1 A2 ..\n    interpretation A2_B: functor_category A2 B ..\n    interpretation A2_BxA2: product_category A2_B.comp A2 ..\n    interpretation E: evaluation_functor A2 B ..\n\n    notation A1xA2.comp          (infixr \"\\<cdot>\\<^sub>A\\<^sub>1\\<^sub>x\\<^sub>A\\<^sub>2\" 55)\n    notation A2_B.comp           (infixr \"\\<cdot>\\<^sub>[\\<^sub>A\\<^sub>2,\\<^sub>B\\<^sub>]\" 55)\n    notation A2_BxA2.comp        (infixr \"\\<cdot>\\<^sub>[\\<^sub>A\\<^sub>2\\<^sub>,\\<^sub>B\\<^sub>]\\<^sub>x\\<^sub>A\\<^sub>2\" 55)\n    notation A1xA2.in_hom        (\"\\<guillemotleft>_ : _ \\<rightarrow>\\<^sub>A\\<^sub>1\\<^sub>x\\<^sub>A\\<^sub>2 _\\<guillemotright>\")\n    notation A2_B.in_hom         (\"\\<guillemotleft>_ : _ \\<rightarrow>\\<^sub>[\\<^sub>A\\<^sub>2\\<^sub>,\\<^sub>B\\<^sub>] _\\<guillemotright>\")\n    notation A2_BxA2.in_hom      (\"\\<guillemotleft>_ : _ \\<rightarrow>\\<^sub>[\\<^sub>A\\<^sub>2\\<^sub>,\\<^sub>B\\<^sub>]\\<^sub>x\\<^sub>A\\<^sub>2 _\\<guillemotright>\")\n\n    text\\<open>\n      A proper definition for @{term curry} requires that it be parametrized by\n      binary functors @{term F} and @{term G} that are the domain and codomain\n      of the natural transformations to which it is being applied.\n      Similar parameters are not needed in the case of @{term uncurry}.\n\\<close>\n\n    definition curry :: \"('a1 \\<times> 'a2 \\<Rightarrow> 'b) \\<Rightarrow> ('a1 \\<times> 'a2 \\<Rightarrow> 'b) \\<Rightarrow> ('a1 \\<times> 'a2 \\<Rightarrow> 'b)\n                           \\<Rightarrow> 'a1 \\<Rightarrow> ('a2, 'b) A2_B.arr\"\n    where \"curry F G \\<tau> f1 = (if A1.arr f1 then\n                               A2_B.MkArr (\\<lambda>f2. F (A1.dom f1, f2)) (\\<lambda>f2. G (A1.cod f1, f2))\n                                          (\\<lambda>f2. \\<tau> (f1, f2))\n                             else A2_B.null)\"\n\n    definition uncurry :: \"('a1 \\<Rightarrow> ('a2, 'b) A2_B.arr) \\<Rightarrow> 'a1 \\<times> 'a2 \\<Rightarrow> 'b\"\n    where \"uncurry \\<tau> f \\<equiv> if A1xA2.arr f then E.map (\\<tau> (fst f), snd f) else B.null\"\n\n    lemma curry_simp:\n    assumes \"A1.arr f1\"\n    shows \"curry F G \\<tau> f1 = A2_B.MkArr (\\<lambda>f2. F (A1.dom f1, f2)) (\\<lambda>f2. G (A1.cod f1, f2))\n                                       (\\<lambda>f2. \\<tau> (f1, f2))\"\n      using assms curry_def by auto\n\n    lemma uncurry_simp:\n    assumes \"A1xA2.arr f\"\n    shows \"uncurry \\<tau> f = E.map (\\<tau> (fst f), snd f)\"\n      using assms uncurry_def by auto\n\n    lemma curry_in_hom:\n    assumes f1: \"A1.arr f1\"\n    and \"natural_transformation A1xA2.comp B F G \\<tau>\"\n    shows \"\\<guillemotleft>curry F G \\<tau> f1 : curry F F F (A1.dom f1) \\<rightarrow>\\<^sub>[\\<^sub>A\\<^sub>2\\<^sub>,\\<^sub>B\\<^sub>] curry G G G (A1.cod f1)\\<guillemotright>\"\n    proof -\n      interpret \\<tau>: natural_transformation A1xA2.comp B F G \\<tau> using assms by auto\n      show ?thesis\n      proof -\n        interpret F_dom_f1: \"functor\" A2 B \\<open>\\<lambda>f2. F (A1.dom f1, f2)\\<close>\n          using f1 \\<tau>.F.is_extensional apply (unfold_locales, simp_all)\n          by (metis A1xA2.comp_char A1.arr_dom_iff_arr A1.comp_arr_dom A1.dom_dom\n                    A1xA2.seqI \\<tau>.F.preserves_comp_2 fst_conv snd_conv)\n        interpret G_cod_f1: \"functor\" A2 B \\<open>\\<lambda>f2. G (A1.cod f1, f2)\\<close>\n          using f1 \\<tau>.G.is_extensional A1.arr_cod_iff_arr\n          apply (unfold_locales, simp_all)\n          using A1xA2.comp_char A1.arr_cod_iff_arr A1.comp_cod_arr\n          by (metis A1.cod_cod A1xA2.seqI \\<tau>.G.preserves_comp_2 fst_conv snd_conv)\n        have \"natural_transformation A2 B (\\<lambda>f2. F (A1.dom f1, f2)) (\\<lambda>f2. G (A1.cod f1, f2))\n                                          (\\<lambda>f2. \\<tau> (f1, f2))\"\n          using f1 \\<tau>.is_extensional apply (unfold_locales, simp_all)\n        proof -\n          fix f2\n          assume f2: \"A2.arr f2\"\n          show \"G (A1.cod f1, f2) \\<cdot>\\<^sub>B \\<tau> (f1, A2.dom f2) = \\<tau> (f1, f2)\"\n            using f1 f2 \\<tau>.preserves_comp_1 [of \"(A1.cod f1, f2)\" \"(f1, A2.dom f2)\"]\n                  A1.comp_cod_arr A2.comp_arr_dom\n            by simp\n          show \"\\<tau> (f1, A2.cod f2) \\<cdot>\\<^sub>B F (A1.dom f1, f2) = \\<tau> (f1, f2)\"\n            using f1 f2 \\<tau>.preserves_comp_2 [of \"(f1, A2.cod f2)\" \"(A1.dom f1, f2)\"]\n                  A1.comp_arr_dom A2.comp_cod_arr\n            by simp\n        qed\n        thus ?thesis\n          using f1 curry_simp by auto\n      qed\n    qed\n\n    lemma curry_preserves_functors:\n    assumes \"functor A1xA2.comp B F\"\n    shows \"functor A1 A2_B.comp (curry F F F)\"\n    proof -\n      interpret F: \"functor\" A1xA2.comp B F using assms by auto\n      interpret F: binary_functor A1 A2 B F ..\n      show ?thesis\n        using curry_def F.fixing_arr_gives_natural_transformation_1\n              A2_B.comp_char F.preserves_comp_1 curry_simp A2_B.seq_char\n        apply unfold_locales by auto\n    qed\n\n    lemma curry_preserves_transformations:\n    assumes \"natural_transformation A1xA2.comp B F G \\<tau>\"\n    shows \"natural_transformation A1 A2_B.comp (curry F F F) (curry G G G) (curry F G \\<tau>)\"\n    proof -\n      interpret \\<tau>: natural_transformation A1xA2.comp B F G \\<tau> using assms by auto\n      interpret \\<tau>: binary_functor_transformation A1 A2 B F G \\<tau> ..\n      interpret curry_F: \"functor\" A1 A2_B.comp \\<open>curry F F F\\<close>\n        using curry_preserves_functors \\<tau>.F.functor_axioms by simp\n      interpret curry_G: \"functor\" A1 A2_B.comp \\<open>curry G G G\\<close>\n        using curry_preserves_functors \\<tau>.G.functor_axioms by simp\n      show ?thesis\n      proof\n        show \"\\<And>f2. \\<not> A1.arr f2 \\<Longrightarrow> curry F G \\<tau> f2 = A2_B.null\"\n          using curry_def by simp\n        fix f1\n        assume f1: \"A1.arr f1\"\n        show \"A2_B.dom (curry F G \\<tau> f1) = curry F F F (A1.dom f1)\"\n          using assms f1 curry_in_hom by blast\n        show \"A2_B.cod (curry F G \\<tau> f1) = curry G G G (A1.cod f1)\"\n          using assms f1 curry_in_hom by blast\n        show \"curry G G G f1 \\<cdot>\\<^sub>[\\<^sub>A\\<^sub>2,\\<^sub>B\\<^sub>] curry F G \\<tau> (A1.dom f1) = curry F G \\<tau> f1\"\n        proof -\n          interpret \\<tau>_dom_f1: natural_transformation A2 B \\<open>\\<lambda>f2. F (A1.dom f1, f2)\\<close>\n                                \\<open>\\<lambda>f2. G (A1.dom f1, f2)\\<close> \\<open>\\<lambda>f2. \\<tau> (A1.dom f1, f2)\\<close>\n            using assms f1 curry_in_hom A1.ide_dom \\<tau>.fixing_ide_gives_natural_transformation_1\n            by blast\n          interpret G_f1: natural_transformation A2 B\n                                \\<open>\\<lambda>f2. G (A1.dom f1, f2)\\<close> \\<open>\\<lambda>f2. G (A1.cod f1, f2)\\<close> \\<open>\\<lambda>f2. G (f1, f2)\\<close>\n            using f1 \\<tau>.G.fixing_arr_gives_natural_transformation_1 by simp\n          interpret G_f1o\\<tau>_dom_f1: vertical_composite A2 B\n                                     \\<open>\\<lambda>f2. F (A1.dom f1, f2)\\<close> \\<open>\\<lambda>f2. G (A1.dom f1, f2)\\<close>\n                                     \\<open>\\<lambda>f2. G (A1.cod f1, f2)\\<close>\n                                     \\<open>\\<lambda>f2. \\<tau> (A1.dom f1, f2)\\<close> \\<open>\\<lambda>f2. G (f1, f2)\\<close> ..\n          have \"curry G G G f1 \\<cdot>\\<^sub>[\\<^sub>A\\<^sub>2,\\<^sub>B\\<^sub>] curry F G \\<tau> (A1.dom f1)\n                  = A2_B.MkArr (\\<lambda>f2. F (A1.dom f1, f2)) (\\<lambda>f2. G (A1.cod f1, f2)) G_f1o\\<tau>_dom_f1.map\"\n          proof -\n            have \"A2_B.seq (curry G G G f1) (curry F G \\<tau> (A1.dom f1))\"\n              using f1 curry_in_hom [of \"A1.dom f1\"] \\<tau>.natural_transformation_axioms by force\n            thus ?thesis\n              using f1 curry_simp A2_B.comp_char [of \"curry G G G f1\" \"curry F G \\<tau> (A1.dom f1)\"]\n              by simp\n          qed\n          also have \"... = A2_B.MkArr (\\<lambda>f2. F (A1.dom f1, f2)) (\\<lambda>f2. G (A1.cod f1, f2))\n                                      (\\<lambda>f2. \\<tau> (f1, f2))\"\n          proof (intro A2_B.MkArr_eqI)\n            show \"(\\<lambda>f2. F (A1.dom f1, f2)) = (\\<lambda>f2. F (A1.dom f1, f2))\" by simp\n            show \"(\\<lambda>f2. G (A1.cod f1, f2)) = (\\<lambda>f2. G (A1.cod f1, f2))\" by simp\n            show \"A2_B.arr (A2_B.MkArr (\\<lambda>f2. F (A1.dom f1, f2)) (\\<lambda>f2. G (A1.cod f1, f2))\n                                       G_f1o\\<tau>_dom_f1.map)\"\n              using G_f1o\\<tau>_dom_f1.natural_transformation_axioms by blast\n            show \"G_f1o\\<tau>_dom_f1.map = (\\<lambda>f2. \\<tau> (f1, f2))\"\n            proof\n              fix f2\n              have \"\\<not>A2.arr f2 \\<Longrightarrow> G_f1o\\<tau>_dom_f1.map f2 = (\\<lambda>f2. \\<tau> (f1, f2)) f2\"\n                using f1 G_f1o\\<tau>_dom_f1.is_extensional \\<tau>.is_extensional by simp\n              moreover have \"A2.arr f2 \\<Longrightarrow> G_f1o\\<tau>_dom_f1.map f2 = (\\<lambda>f2. \\<tau> (f1, f2)) f2\"\n              proof -\n                interpret \\<tau>_f1: natural_transformation A2 B \\<open>\\<lambda>f2. F (A1.dom f1, f2)\\<close>\n                                  \\<open>\\<lambda>f2. G (A1.cod f1, f2)\\<close> \\<open>\\<lambda>f2. \\<tau> (f1, f2)\\<close>\n                  using assms f1 curry_in_hom [of f1] curry_simp by auto\n                fix f2\n                assume f2: \"A2.arr f2\"\n                show \"G_f1o\\<tau>_dom_f1.map f2 = (\\<lambda>f2. \\<tau> (f1, f2)) f2\"\n                  using f1 f2 G_f1o\\<tau>_dom_f1.map_simp_2 B.comp_assoc \\<tau>.is_natural_1\n                  by fastforce\n              qed\n              ultimately show \"G_f1o\\<tau>_dom_f1.map f2 = (\\<lambda>f2. \\<tau> (f1, f2)) f2\" by blast\n            qed\n          qed\n          also have \"... = curry F G \\<tau> f1\" using f1 curry_def by simp\n          finally show ?thesis by blast\n        qed\n        show \"curry F G \\<tau> (A1.cod f1) \\<cdot>\\<^sub>[\\<^sub>A\\<^sub>2,\\<^sub>B\\<^sub>] curry F F F f1 = curry F G \\<tau> f1\"\n        proof -\n          interpret \\<tau>_cod_f1: natural_transformation A2 B \\<open>\\<lambda>f2. F (A1.cod f1, f2)\\<close>\n                                \\<open>\\<lambda>f2. G (A1.cod f1, f2)\\<close> \\<open>\\<lambda>f2. \\<tau> (A1.cod f1, f2)\\<close>\n            using assms f1 curry_in_hom A1.ide_cod \\<tau>.fixing_ide_gives_natural_transformation_1\n            by blast\n          interpret F_f1: natural_transformation A2 B\n                                \\<open>\\<lambda>f2. F (A1.dom f1, f2)\\<close> \\<open>\\<lambda>f2. F (A1.cod f1, f2)\\<close> \\<open>\\<lambda>f2. F (f1, f2)\\<close>\n            using f1 \\<tau>.F.fixing_arr_gives_natural_transformation_1 by simp\n          interpret \\<tau>_cod_f1oF_f1: vertical_composite A2 B\n                                     \\<open>\\<lambda>f2. F (A1.dom f1, f2)\\<close> \\<open>\\<lambda>f2. F (A1.cod f1, f2)\\<close>\n                                     \\<open>\\<lambda>f2. G (A1.cod f1, f2)\\<close>\n                                     \\<open>\\<lambda>f2. F (f1, f2)\\<close> \\<open>\\<lambda>f2. \\<tau> (A1.cod f1, f2)\\<close> ..\n          have \"curry F G \\<tau> (A1.cod f1) \\<cdot>\\<^sub>[\\<^sub>A\\<^sub>2,\\<^sub>B\\<^sub>] curry F F F f1\n                  = A2_B.MkArr (\\<lambda>f2. F (A1.dom f1, f2)) (\\<lambda>f2. G (A1.cod f1, f2)) \\<tau>_cod_f1oF_f1.map\"\n          proof -\n            have\n                 \"curry F F F f1 =\n                    A2_B.MkArr (\\<lambda>f2. F (A1.dom f1, f2)) (\\<lambda>f2. F (A1.cod f1, f2))\n                               (\\<lambda>f2. F (f1, f2)) \\<and>\n                  \\<guillemotleft>curry F F F f1 : curry F F F (A1.dom f1) \\<rightarrow>\\<^sub>[\\<^sub>A\\<^sub>2\\<^sub>,\\<^sub>B\\<^sub>] curry F F F (A1.cod f1)\\<guillemotright>\"\n              using f1 curry_F.preserves_hom curry_simp by blast\n            moreover have\n                 \"curry F G \\<tau> (A1.dom f1) =\n                    A2_B.MkArr (\\<lambda>f2. F (A1.dom f1, f2)) (\\<lambda>f2. G (A1.dom f1, f2))\n                               (\\<lambda>f2. \\<tau> (A1.dom f1, f2)) \\<and>\n                    \\<guillemotleft>curry F G \\<tau> (A1.cod f1) :\n                       curry F F F (A1.cod f1) \\<rightarrow>\\<^sub>[\\<^sub>A\\<^sub>2\\<^sub>,\\<^sub>B\\<^sub>] curry G G G (A1.cod f1)\\<guillemotright>\"\n              using assms f1 curry_in_hom [of \"A1.cod f1\"] curry_def A1.arr_cod_iff_arr by simp\n            ultimately show ?thesis\n              using f1 curry_def by fastforce\n          qed\n          also have \"... = A2_B.MkArr (\\<lambda>f2. F (A1.dom f1, f2)) (\\<lambda>f2. G (A1.cod f1, f2))\n                                      (\\<lambda>f2. \\<tau> (f1, f2))\"\n          proof (intro A2_B.MkArr_eqI)\n            show \"(\\<lambda>f2. F (A1.dom f1, f2)) = (\\<lambda>f2. F (A1.dom f1, f2))\" by simp\n            show \"(\\<lambda>f2. G (A1.cod f1, f2)) = (\\<lambda>f2. G (A1.cod f1, f2))\" by simp\n            show \"A2_B.arr (A2_B.MkArr (\\<lambda>f2. F (A1.dom f1, f2)) (\\<lambda>f2. G (A1.cod f1, f2))\n                                       \\<tau>_cod_f1oF_f1.map)\"\n              using \\<tau>_cod_f1oF_f1.natural_transformation_axioms by blast\n            show \"\\<tau>_cod_f1oF_f1.map = (\\<lambda>f2. \\<tau> (f1, f2))\"\n            proof\n              fix f2\n              have \"\\<not>A2.arr f2 \\<Longrightarrow> \\<tau>_cod_f1oF_f1.map f2 = (\\<lambda>f2. \\<tau> (f1, f2)) f2\"\n                using f1 by (simp add: \\<tau>.is_extensional \\<tau>_cod_f1oF_f1.is_extensional)\n              moreover have \"A2.arr f2 \\<Longrightarrow> \\<tau>_cod_f1oF_f1.map f2 = (\\<lambda>f2. \\<tau> (f1, f2)) f2\"\n              proof -\n                interpret \\<tau>_f1: natural_transformation A2 B \\<open>\\<lambda>f2. F (A1.dom f1, f2)\\<close>\n                                  \\<open>\\<lambda>f2. G (A1.cod f1, f2)\\<close> \\<open>\\<lambda>f2. \\<tau> (f1, f2)\\<close>\n                  using assms f1 curry_in_hom [of f1] curry_simp by auto\n                fix f2\n                assume f2: \"A2.arr f2\"\n                show \"\\<tau>_cod_f1oF_f1.map f2 = (\\<lambda>f2. \\<tau> (f1, f2)) f2\"\n                  using f1 f2 \\<tau>_cod_f1oF_f1.map_simp_1 B.comp_assoc \\<tau>.is_natural_2\n                  by fastforce\n              qed\n              ultimately show \"\\<tau>_cod_f1oF_f1.map f2 = (\\<lambda>f2. \\<tau> (f1, f2)) f2\" by blast\n            qed\n          qed\n          also have \"... = curry F G \\<tau> f1\" using f1 curry_def by simp\n          finally show ?thesis by blast\n        qed\n      qed\n    qed\n\n    lemma uncurry_preserves_functors:\n    assumes \"functor A1 A2_B.comp F\"\n    shows \"functor A1xA2.comp B (uncurry F)\"\n    proof -\n      interpret F: \"functor\" A1 A2_B.comp F using assms by auto\n      show ?thesis\n        using uncurry_def\n        apply (unfold_locales)\n            apply auto[4]\n      proof -\n        fix f g :: \"'a1 * 'a2\"\n        let ?f1 = \"fst f\"\n        let ?f2 = \"snd f\"\n        let ?g1 = \"fst g\"\n        let ?g2 = \"snd g\"\n        assume fg: \"A1xA2.seq g f\"\n        have f: \"A1xA2.arr f\" using fg A1xA2.seqE by blast\n        have f1: \"A1.arr ?f1\" using f by auto\n        have f2: \"A2.arr ?f2\" using f by auto\n        have g: \"\\<guillemotleft>g : A1xA2.cod f \\<rightarrow>\\<^sub>A\\<^sub>1\\<^sub>x\\<^sub>A\\<^sub>2 A1xA2.cod g\\<guillemotright>\"\n          using fg A1xA2.dom_char A1xA2.cod_char\n          by (elim A1xA2.seqE, intro A1xA2.in_homI, auto)\n        let ?g1 = \"fst g\"\n        let ?g2 = \"snd g\"\n        have g1: \"\\<guillemotleft>?g1 : A1.cod ?f1 \\<rightarrow>\\<^sub>A\\<^sub>1 A1.cod ?g1\\<guillemotright>\"\n          using f g by (intro A1.in_homI, auto)\n        have g2: \"\\<guillemotleft>?g2 : A2.cod ?f2 \\<rightarrow>\\<^sub>A\\<^sub>2 A2.cod ?g2\\<guillemotright>\"\n          using f g by (intro A2.in_homI, auto)\n        interpret Ff1: natural_transformation A2 B \\<open>A2_B.Dom (F ?f1)\\<close> \\<open>A2_B.Cod (F ?f1)\\<close>\n                                                   \\<open>A2_B.Map (F ?f1)\\<close>\n          using f A2_B.arr_char [of \"F ?f1\"] by auto\n        interpret Fg1: natural_transformation A2 B \\<open>A2_B.Cod (F ?f1)\\<close> \\<open>A2_B.Cod (F ?g1)\\<close>\n                                                   \\<open>A2_B.Map (F ?g1)\\<close>\n          using f1 g1 A2_B.arr_char F.preserves_arr\n                A2_B.Map_dom [of \"F ?g1\"] A2_B.Map_cod [of \"F ?f1\"]\n          by fastforce\n        interpret Fg1oFf1: vertical_composite A2 B\n                              \\<open>A2_B.Dom (F ?f1)\\<close> \\<open>A2_B.Cod (F ?f1)\\<close> \\<open>A2_B.Cod (F ?g1)\\<close>\n                              \\<open>A2_B.Map (F ?f1)\\<close> \\<open>A2_B.Map (F ?g1)\\<close> ..\n        show \"uncurry F (g \\<cdot>\\<^sub>A\\<^sub>1\\<^sub>x\\<^sub>A\\<^sub>2 f) = uncurry F g \\<cdot>\\<^sub>B uncurry F f\"\n          using f1 g1 g2 g2 f g fg E.map_simp uncurry_def by auto\n      qed\n    qed\n\n    lemma uncurry_preserves_transformations:\n    assumes \"natural_transformation A1 A2_B.comp F G \\<tau>\"\n    shows \"natural_transformation A1xA2.comp B (uncurry F) (uncurry G) (uncurry \\<tau>)\"\n    proof -\n      interpret \\<tau>: natural_transformation A1 A2_B.comp F G \\<tau> using assms by auto\n      interpret \"functor\" A1xA2.comp B \\<open>uncurry F\\<close>\n        using \\<tau>.F.functor_axioms uncurry_preserves_functors by blast\n      interpret \"functor\" A1xA2.comp B \\<open>uncurry G\\<close>\n        using \\<tau>.G.functor_axioms uncurry_preserves_functors by blast\n      show ?thesis\n      proof\n        fix f\n        show \"\\<not> A1xA2.arr f \\<Longrightarrow> uncurry \\<tau> f = B.null\"\n          using uncurry_def by auto\n        assume f: \"A1xA2.arr f\"\n        let ?f1 = \"fst f\"\n        let ?f2 = \"snd f\"\n        show \"B.dom (uncurry \\<tau> f) = uncurry F (A1xA2.dom f)\"\n          using f uncurry_def by simp\n        show \"B.cod (uncurry \\<tau> f) = uncurry G (A1xA2.cod f)\"\n          using f uncurry_def by simp\n        show \"uncurry G f \\<cdot>\\<^sub>B uncurry \\<tau> (A1xA2.dom f) = uncurry \\<tau> f\"\n          using f uncurry_def \\<tau>.is_natural_1 A2_BxA2.seq_char A2.comp_arr_dom\n                E.preserves_comp [of \"(G (fst f), snd f)\" \"(\\<tau> (A1.dom (fst f)), A2.dom (snd f))\"]\n          by auto\n        show \"uncurry \\<tau> (A1xA2.cod f) \\<cdot>\\<^sub>B uncurry F f = uncurry \\<tau> f\"\n        proof -\n          have 1: \"A1.arr ?f1 \\<and> A1.arr (fst (A1.cod ?f1, A2.cod ?f2)) \\<and>\n                   A1.cod ?f1 = A1.dom (fst (A1.cod ?f1, A2.cod ?f2)) \\<and>\n                   A2.seq (snd (A1.cod ?f1, A2.cod ?f2)) ?f2\"\n            using f A1.arr_cod_iff_arr A2.arr_cod_iff_arr by auto\n          hence 2:\n              \"?f2 = A2 (snd (\\<tau> (fst (A1xA2.cod f)), snd (A1xA2.cod f))) (snd (F ?f1, ?f2))\"\n            using f A2.comp_cod_arr by simp\n          have \"A2_B.arr (\\<tau> ?f1)\" using 1 by force\n          thus ?thesis\n            unfolding uncurry_def E.map_def\n            using f 1 2\n            apply simp\n            by (metis (no_types, lifting) A2_B.Map_comp \\<open>A2_B.arr (\\<tau> (fst f))\\<close> \\<tau>.is_natural_2)\n\n        qed\n      qed\n    qed\n\n    lemma uncurry_curry:\n    assumes \"natural_transformation A1xA2.comp B F G \\<tau>\"\n    shows \"uncurry (curry F G \\<tau>) = \\<tau>\"\n    proof\n      interpret \\<tau>: natural_transformation A1xA2.comp B F G \\<tau> using assms by auto\n      interpret curry_\\<tau>: natural_transformation A1 A2_B.comp \\<open>curry F F F\\<close> \\<open>curry G G G\\<close>\n                                                             \\<open>curry F G \\<tau>\\<close>\n        using assms curry_preserves_transformations by auto\n      fix f\n      have \"\\<not>A1xA2.arr f \\<Longrightarrow> uncurry (curry F G \\<tau>) f = \\<tau> f\"\n        using curry_def uncurry_def \\<tau>.is_extensional by auto\n      moreover have \"A1xA2.arr f \\<Longrightarrow> uncurry (curry F G \\<tau>) f = \\<tau> f\"\n      proof -\n        assume f: \"A1xA2.arr f\"\n        have 1: \"A2_B.Map (curry F G \\<tau> (fst f)) (snd f) = \\<tau> (fst f, snd f)\"\n          using f A1xA2.arr_char curry_def by simp\n        thus \"uncurry (curry F G \\<tau>) f = \\<tau> f\"\n          unfolding uncurry_def E.map_def\n          using f 1 A1xA2.arr_char [of f] by simp\n      qed\n      ultimately show \"uncurry (curry F G \\<tau>) f = \\<tau> f\" by blast\n    qed\n\n    lemma curry_uncurry:\n    assumes \"functor A1 A2_B.comp F\" and \"functor A1 A2_B.comp G\"\n    and \"natural_transformation A1 A2_B.comp F G \\<tau>\"\n    shows \"curry (uncurry F) (uncurry G) (uncurry \\<tau>) = \\<tau>\"\n    proof\n      interpret F: \"functor\" A1 A2_B.comp F using assms(1) by auto\n      interpret G: \"functor\" A1 A2_B.comp G using assms(2) by auto\n      interpret \\<tau>: natural_transformation A1 A2_B.comp F G \\<tau> using assms(3) by auto\n      interpret uncurry_F: \"functor\" A1xA2.comp B \\<open>uncurry F\\<close>\n        using F.functor_axioms uncurry_preserves_functors by auto\n      interpret uncurry_G: \"functor\" A1xA2.comp B \\<open>uncurry G\\<close>\n        using G.functor_axioms uncurry_preserves_functors by auto\n      fix f1\n      have \"\\<not>A1.arr f1 \\<Longrightarrow> curry (uncurry F) (uncurry G) (uncurry \\<tau>) f1 = \\<tau> f1\"\n        using curry_def uncurry_def \\<tau>.is_extensional by simp\n      moreover have \"A1.arr f1 \\<Longrightarrow> curry (uncurry F) (uncurry G) (uncurry \\<tau>) f1 = \\<tau> f1\"\n      proof -\n        assume f1: \"A1.arr f1\"\n        interpret uncurry_\\<tau>:\n            natural_transformation A1xA2.comp B \\<open>uncurry F\\<close> \\<open>uncurry G\\<close> \\<open>uncurry \\<tau>\\<close>\n          using \\<tau>.natural_transformation_axioms uncurry_preserves_transformations [of F G \\<tau>]\n          by simp\n        have \"curry (uncurry F) (uncurry G) (uncurry \\<tau>) f1 =\n                A2_B.MkArr (\\<lambda>f2. uncurry F (A1.dom f1, f2)) (\\<lambda>f2. uncurry G (A1.cod f1, f2))\n                           (\\<lambda>f2. uncurry \\<tau> (f1, f2))\"\n          using f1 curry_def by simp\n        also have \"... = A2_B.MkArr (\\<lambda>f2. uncurry F (A1.dom f1, f2))\n                                    (\\<lambda>f2. uncurry G (A1.cod f1, f2))\n                                    (\\<lambda>f2. E.map (\\<tau> f1, f2))\"\n        proof -\n          have \"(\\<lambda>f2. uncurry \\<tau> (f1, f2)) = (\\<lambda>f2. E.map (\\<tau> f1, f2))\"\n            using f1 uncurry_def E.is_extensional by auto\n          thus ?thesis by simp\n        qed\n        also have \"... = \\<tau> f1\"\n        proof -\n          have \"A2_B.Dom (\\<tau> f1) = (\\<lambda>f2. uncurry F (A1.dom f1, f2))\"\n          proof -\n            have \"A2_B.Dom (\\<tau> f1) = A2_B.Map (A2_B.dom (\\<tau> f1))\"\n              using f1 A2_B.ide_char A2_B.Map_dom A2_B.dom_char by auto\n            also have \"... = A2_B.Map (F (A1.dom f1))\"\n              using f1 by simp\n            also have \"... = (\\<lambda>f2. uncurry F (A1.dom f1, f2))\"\n            proof\n              fix f2\n              interpret F_dom_f1: \"functor\" A2 B \\<open>A2_B.Map (F (A1.dom f1))\\<close>\n                using f1 A2_B.ide_char F.preserves_ide by simp\n              show \"A2_B.Map (F (A1.dom f1)) f2 = uncurry F (A1.dom f1, f2)\"\n                using f1 uncurry_def E.map_simp F_dom_f1.is_extensional by auto\n            qed\n            finally show ?thesis by auto\n          qed\n          moreover have \"A2_B.Cod (\\<tau> f1) = (\\<lambda>f2. uncurry G (A1.cod f1, f2))\"\n          proof -\n            have \"A2_B.Cod (\\<tau> f1) = A2_B.Map (A2_B.cod (\\<tau> f1))\"\n              using f1 A2_B.ide_char A2_B.Map_cod A2_B.cod_char by auto\n            also have \"... = A2_B.Map (G (A1.cod f1))\"\n              using f1 by simp\n            also have \"... = (\\<lambda>f2. uncurry G (A1.cod f1, f2))\"\n            proof\n              fix f2\n              interpret G_cod_f1: \"functor\" A2 B \\<open>A2_B.Map (G (A1.cod f1))\\<close>\n                using f1 A2_B.ide_char G.preserves_ide by simp\n              show \"A2_B.Map (G (A1.cod f1)) f2 = uncurry G (A1.cod f1, f2)\"\n                using f1 uncurry_def E.map_simp G_cod_f1.is_extensional by auto\n            qed\n            finally show ?thesis by auto\n          qed\n          moreover have \"A2_B.Map (\\<tau> f1) = (\\<lambda>f2. E.map (\\<tau> f1, f2))\"\n          proof\n            fix f2\n            have \"\\<not>A2.arr f2 \\<Longrightarrow> A2_B.Map (\\<tau> f1) f2 = (\\<lambda>f2. E.map (\\<tau> f1, f2)) f2\"\n              using f1 A2_B.arrE \\<tau>.preserves_reflects_arr natural_transformation.is_extensional\n              by (metis (no_types, lifting) E.fixing_arr_gives_natural_transformation_1)\n            moreover have \"A2.arr f2 \\<Longrightarrow> A2_B.Map (\\<tau> f1) f2 = (\\<lambda>f2. E.map (\\<tau> f1, f2)) f2\"\n              using f1 E.map_simp by fastforce\n            ultimately show \"A2_B.Map (\\<tau> f1) f2 = (\\<lambda>f2. E.map (\\<tau> f1, f2)) f2\" by blast\n          qed\n          ultimately show ?thesis\n            using f1 A2_B.MkArr_Map \\<tau>.preserves_reflects_arr by metis\n        qed\n        finally show ?thesis by auto\n      qed\n      ultimately show \"curry (uncurry F) (uncurry G) (uncurry \\<tau>) f1 = \\<tau> f1\" by blast\n    qed\n\n  end\n\n  locale curried_functor =\n     currying A1 A2 B +\n     A1xA2: product_category A1 A2 +\n     A2_B: functor_category A2 B +\n     F: binary_functor A1 A2 B F\n  for A1 :: \"'a1 comp\"         (infixr \"\\<cdot>\\<^sub>A\\<^sub>1\" 55)\n  and A2 :: \"'a2 comp\"         (infixr \"\\<cdot>\\<^sub>A\\<^sub>2\" 55)\n  and B :: \"'b comp\"           (infixr \"\\<cdot>\\<^sub>B\" 55)\n  and F :: \"'a1 * 'a2 \\<Rightarrow> 'b\"\n  begin\n\n    notation A1xA2.comp        (infixr \"\\<cdot>\\<^sub>A\\<^sub>1\\<^sub>x\\<^sub>A\\<^sub>2\" 55)\n    notation A2_B.comp         (infixr \"\\<cdot>\\<^sub>[\\<^sub>A\\<^sub>2,\\<^sub>B\\<^sub>]\" 55)\n    notation A1xA2.in_hom      (\"\\<guillemotleft>_ : _ \\<rightarrow>\\<^sub>A\\<^sub>1\\<^sub>x\\<^sub>A\\<^sub>2 _\\<guillemotright>\")\n    notation A2_B.in_hom       (\"\\<guillemotleft>_ : _ \\<rightarrow>\\<^sub>[\\<^sub>A\\<^sub>2\\<^sub>,\\<^sub>B\\<^sub>] _\\<guillemotright>\")\n\n    definition map\n    where \"map \\<equiv> curry F F F\"\n\n    lemma map_simp [simp]:\n    assumes \"A1.arr f1\"\n    shows \"map f1 =\n           A2_B.MkArr (\\<lambda>f2. F (A1.dom f1, f2)) (\\<lambda>f2. F (A1.cod f1, f2)) (\\<lambda>f2. F (f1, f2))\"\n      using assms map_def curry_simp by auto\n\n    lemma is_functor:\n    shows \"functor A1 A2_B.comp map\"\n      using F.functor_axioms map_def curry_preserves_functors by simp\n\n  end\n\n  sublocale curried_functor \\<subseteq> \"functor\" A1 A2_B.comp map\n    using is_functor by auto\n\n  locale curried_functor' =\n     A1: category A1 +\n     A2: category A2 +\n     A1xA2: product_category A1 A2 +\n     currying A2 A1 B +\n     F: binary_functor A1 A2 B F +\n     A1_B: functor_category A1 B\n  for A1 :: \"'a1 comp\"         (infixr \"\\<cdot>\\<^sub>A\\<^sub>1\" 55)\n  and A2 :: \"'a2 comp\"         (infixr \"\\<cdot>\\<^sub>A\\<^sub>2\" 55)\n  and B :: \"'b comp\"           (infixr \"\\<cdot>\\<^sub>B\" 55)\n  and F :: \"'a1 * 'a2 \\<Rightarrow> 'b\"\n  begin\n\n    notation A1xA2.comp        (infixr \"\\<cdot>\\<^sub>A\\<^sub>1\\<^sub>x\\<^sub>A\\<^sub>2\" 55)\n    notation A1_B.comp         (infixr \"\\<cdot>\\<^sub>[\\<^sub>A\\<^sub>1,\\<^sub>B\\<^sub>]\" 55)\n    notation A1xA2.in_hom      (\"\\<guillemotleft>_ : _ \\<rightarrow>\\<^sub>A\\<^sub>1\\<^sub>x\\<^sub>A\\<^sub>2 _\\<guillemotright>\")\n    notation A1_B.in_hom       (\"\\<guillemotleft>_ : _ \\<rightarrow>\\<^sub>[\\<^sub>A\\<^sub>1\\<^sub>,\\<^sub>B\\<^sub>] _\\<guillemotright>\")\n\n    definition map\n    where \"map \\<equiv> curry F.sym F.sym F.sym\"\n\n    lemma map_simp [simp]:\n    assumes \"A2.arr f2\"\n    shows \"map f2 =\n           A1_B.MkArr (\\<lambda>f1. F (f1, A2.dom f2)) (\\<lambda>f1. F (f1, A2.cod f2)) (\\<lambda>f1. F (f1, f2))\"\n      using assms map_def curry_simp by simp\n\n    lemma is_functor:\n    shows \"functor A2 A1_B.comp map\"\n    proof -\n      interpret A2xA1: product_category A2 A1 ..\n      interpret F': binary_functor A2 A1 B F.sym\n        using F.sym_is_binary_functor by simp\n      have \"functor A2xA1.comp B F.sym\" ..\n      thus ?thesis using map_def curry_preserves_functors by simp\n    qed\n\n  end\n\n  sublocale curried_functor' \\<subseteq> \"functor\" A2 A1_B.comp map\n    using is_functor by auto\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/Category3/FunctorCategory.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339596505965, "lm_q2_score": 0.8688267881258485, "lm_q1q2_score": 0.7295833590434285}}
{"text": "theory Univ_RCF_Reification imports \n  Complex_Main\n  \"HOL-Library.Reflection\"\n  Preprocess_Polys\nbegin\n\nlemma list_Cons_induct[case_names Nil Cons CCons]:\n  \"\\<lbrakk>P [];\\<And>x. P [x];\\<And>x1 x2 xs. P (x2#xs) \\<Longrightarrow> P (x1 #x2 # xs)\\<rbrakk> \\<Longrightarrow> P xs\"\napply (induct xs,simp)\nby (case_tac xs,auto)\n\nsection \\<open>strict_sorted\\<close>\n\nfun strict_sorted :: \"'a::linorder list \\<Rightarrow> bool\" where\n  \"strict_sorted [] = True\" |\n  \"strict_sorted [x] = True\" |\n  \"strict_sorted (x1#x2#xs) = (x1<x2 \\<and> strict_sorted (x2#xs))\"\n\nlemma strict_sorted_sorted:\"strict_sorted xs \\<Longrightarrow> sorted xs\"\n  by (induct rule:strict_sorted.induct,auto) \n\nlemma strict_sorted_bot:\"strict_sorted (x#xs) \\<Longrightarrow> \\<forall>y\\<in>set xs. x<y\"\n  by (induct xs rule:strict_sorted.induct,auto)\n\nlemma strict_sorted_imp_distinct:\"strict_sorted xs \\<Longrightarrow> distinct xs\"\n  apply (induct xs rule:strict_sorted.induct)\n  apply auto\nby (metis not_less_iff_gr_or_eq strict_sorted_bot)\n\nlemma strict_sorted_Cons: \"strict_sorted (x#xs) = (strict_sorted xs \\<and> (\\<forall> y\\<in>set xs. x < y))\"\n  using strict_sorted_bot\n  by (cases xs,auto,fastforce)\n  \nlemma strict_sorted_append:\"strict_sorted (xs@ys) \\<Longrightarrow> strict_sorted xs \\<and> strict_sorted ys \n    \\<and> (\\<forall>x\\<in>set xs. \\<forall>y\\<in>set ys. x < y)\"\napply (induct xs rule:strict_sorted.induct,auto)\napply (cases ys)\nby (auto simp add:strict_sorted_bot)\n\nlemma strict_sorted_append':\"strict_sorted (xs@ys@zs) \\<Longrightarrow> strict_sorted (xs@zs)\"\n  apply (induct xs)\n  by (auto simp add:strict_sorted_Cons dest:strict_sorted_append)\n\nsection \\<open>Parse formulas (stratification)\\<close>\n\ndatatype num = C real | Add num num | Minus num | Mul num num | Var nat | Power num nat\n\ndatatype form = Lt num num  | Eq num num | Ge num num | NEq num num | \n    Conj form form | Disj form form | Neg form | T | F  | ExQ form | AllQ form \n\nprimrec num_interp:: \"num \\<Rightarrow> real list \\<Rightarrow> real\"\nwhere\n  num_interp_C  : \"num_interp (C i) vs = i\"\n| num_interp_Var: \"num_interp (Var v) vs = vs!v\"\n| num_interp_Add: \"num_interp (Add num1 num2) vs = num_interp num1 vs + num_interp num2 vs \"\n| num_interp_Minus: \"num_interp (Minus num) vs = - num_interp num vs \"\n| num_interp_Mul: \"num_interp (Mul num1 num2) vs = num_interp num1 vs * num_interp num2 vs \"\n| num_interp_Power: \"num_interp (Power num n) vs = (num_interp num vs)^n\"\n\nlemma num_interp_diff:\"num_interp (Add num1 (Minus num2)) vs \n    = (num_interp num1 vs) - (num_interp num2 vs)\"\n  unfolding num_interp.simps by simp\n\nlemma num_interp_number: \"num_interp (C (numeral t)) vs = numeral t\" by simp\nlemma num_interp_rat: \n  \"num_interp (C (numeral t1/numeral t2)) vs = numeral t1 / numeral t2\" \n  \"num_interp (Mul num (C (1/numeral c))) vs = num_interp num vs / numeral c\"\n  by simp_all \nlemma num_interp_01: \"num_interp (C 0) vs = 0\" \"num_interp (C 1) vs = 1\" \n    \"num_interp (C 0) vs = 0/n\" \"num_interp (C 0) vs = n/0\" \n    \"num_interp (C (1/numeral t2)) vs = 1/numeral t2\" \n    \"num_interp (C (numeral t1)) vs = numeral t1/1\"\n  by simp_all\nlemmas num_interp_eqs =  \n  num_interp_Var num_interp_Add num_interp_Mul num_interp_Minus num_interp_number num_interp_01 \n  num_interp_rat num_interp_diff num_interp_Power\n\nprimrec form_interp :: \"form \\<Rightarrow> real list \\<Rightarrow> bool\"\nwhere\n \"form_interp T vs = True\"\n| \"form_interp F vs = False\"\n| \"form_interp (Lt a b) vs = (num_interp a vs < num_interp b vs)\"\n| \"form_interp (Eq a b) vs = (num_interp a vs = num_interp b vs)\"\n| \"form_interp (Ge a b) vs = (num_interp a vs \\<ge> num_interp b vs)\"\n| \"form_interp (NEq a b) vs = (num_interp a vs \\<noteq> num_interp b vs)\"\n| \"form_interp (Neg p) vs = (\\<not> (form_interp p vs))\"\n| \"form_interp (Conj p q) vs = (form_interp p vs \\<and> form_interp q vs)\"\n| \"form_interp (Disj p q) vs = (form_interp p vs \\<or> form_interp q vs)\"\n| \"form_interp (ExQ f) vs \\<longleftrightarrow> (\\<exists>v. form_interp f (v # vs))\"\n| \"form_interp (AllQ f) vs \\<longleftrightarrow> (\\<forall>v. form_interp f (v # vs))\"\n\ndatatype norm_num = Pol \"real poly\" nat | Const real | Abnorm num\n\nfun cancel_normalize_num:: \"norm_num \\<Rightarrow> num\"  where\n \"cancel_normalize_num (Pol p v) = fold_coeffs (\\<lambda>a f x. Add (C a) (Mul x (f x))) p (\\<lambda>_.C 0) (Var v)\"|\n \"cancel_normalize_num (Const c) = C c\"|\n \"cancel_normalize_num (Abnorm num) = num\"\n\nfun add_norm_num:: \"norm_num \\<Rightarrow> norm_num \\<Rightarrow> norm_num\" where\n \"add_norm_num (Const c1) (Const c2) = Const (c1+c2)\"|\n \"add_norm_num (Pol p v) (Const c) = Pol (p+[:c:]) v\"|\n \"add_norm_num (Const c) (Pol p v)  = Pol (p+[:c:]) v\"|\n \"add_norm_num (Pol p1 v1) (Pol p2 v2) = \n    (if v1=v2 then Pol (p1+p2) v1 \n    else (Abnorm (Add (cancel_normalize_num (Pol p1 v1)) (cancel_normalize_num (Pol p2 v2)))))\" |\n \"add_norm_num norm1 norm2 =(Abnorm (Add (cancel_normalize_num norm1) (cancel_normalize_num norm2)))\"\n\nfun mult_norm_num:: \"norm_num \\<Rightarrow> norm_num \\<Rightarrow> norm_num\" where\n \"mult_norm_num (Const c1) (Const c2) = Const (c1*c2)\"|\n \"mult_norm_num (Pol p v) (Const c) = Pol (smult c p) v\"|\n \"mult_norm_num (Const c) (Pol p v)  = Pol (smult c p) v\"|\n \"mult_norm_num (Pol p1 v1) (Pol p2 v2) = \n    (if v1=v2 then Pol (p1*p2) v1 \n    else (Abnorm (Mul (cancel_normalize_num (Pol p1 v1)) (cancel_normalize_num (Pol p2 v2)))))\" |\n \"mult_norm_num norm1 norm2 =(Abnorm (Mul (cancel_normalize_num norm1) (cancel_normalize_num norm2)))\"\n\nfun minus_norm_num:: \"norm_num  \\<Rightarrow> norm_num\" where\n \"minus_norm_num (Const c)= Const (- c)\"|\n \"minus_norm_num (Pol p v)  = Pol (- p) v\"|\n \"minus_norm_num (Abnorm ab) =(Abnorm (Minus ab))\"\n\nfun power_norm_num:: \"norm_num \\<Rightarrow> nat \\<Rightarrow> norm_num\" where\n  \"power_norm_num (Const c) n = Const ( c ^ n)\"|\n  \"power_norm_num (Pol p v) n = Pol (p ^ n) v\" |\n  \"power_norm_num (Abnorm ab) n = (Abnorm (Power ab n))\"\n\nfun normalize_num:: \"num \\<Rightarrow> norm_num\" where \n  \"normalize_num (C c) = Const c\"|\n  \"normalize_num (Var v) = Pol [:0,1:] v\"|\n  \"normalize_num (Minus n1) = minus_norm_num (normalize_num n1)\"|\n  \"normalize_num (Add n1 n2) = add_norm_num (normalize_num n1) (normalize_num n2)\"|\n  \"normalize_num (Mul n1 n2) = mult_norm_num (normalize_num n1) (normalize_num n2)\"|\n  \"normalize_num (Power n1 n) = power_norm_num (normalize_num n1) n\"\n  \nfun norm_num_interp :: \"norm_num \\<Rightarrow> real list \\<Rightarrow> real\" where\n  \"norm_num_interp (Pol p v) vs = poly p (vs!v)\"|\n  \"norm_num_interp (Const c) vs = c\"|\n  \"norm_num_interp (Abnorm num) vs = num_interp num vs\"\n\nlemma cancel_norm:\"num_interp (cancel_normalize_num norm_num) = norm_num_interp norm_num\"\nproof (cases norm_num) \n  case (Const c)\n  thus ?thesis by auto\nnext\n  case (Abnorm num)\n  thus ?thesis by auto\nnext\n  case (Pol p v)\n  show ?thesis unfolding Pol\n    by (induct_tac p,auto)\nqed\n\nlemma norm_add:\n  \"norm_num_interp (add_norm_num n1 n2) vs = norm_num_interp n1 vs + norm_num_interp n2 vs\" \n  apply (induct n1 n2 rule:add_norm_num.induct)\n  by (simp_all add:cancel_norm del:cancel_normalize_num.simps ) \n\nlemma norm_mul:\n  \"norm_num_interp (mult_norm_num n1 n2) vs = norm_num_interp n1 vs * norm_num_interp n2 vs\" \n  apply (induct n1 n2 rule:mult_norm_num.induct)\n  by (simp_all add:cancel_norm del:cancel_normalize_num.simps ) \n\nlemma norm_minus:\n  \"norm_num_interp (minus_norm_num n1) vs = - norm_num_interp n1 vs\" \n  apply (induct n1 rule:minus_norm_num.induct)\n  by (simp_all add:cancel_norm del:cancel_normalize_num.simps ) \n\nlemma norm_power:\n  \"norm_num_interp (power_norm_num n1 n) vs = (norm_num_interp n1 vs) ^ n\" \n  apply (induct n1)\n  by (simp_all add:cancel_norm del:cancel_normalize_num.simps ) \n\n\nlemma normalize_num_correct:\"norm_num_interp (normalize_num num) vs = num_interp num vs\" \n  apply (induct num rule:normalize_num.induct)\n  by (simp_all add:norm_add norm_mul norm_minus norm_power)\n                              \ndatatype qf_form =  Pos norm_num | Zero norm_num | Neg qf_form \n    | Conj qf_form qf_form | Disj qf_form qf_form | T | F\n\ndatatype norm_form = QF qf_form | ExQ norm_form | AllQ norm_form\n\nfun rename_num:: \"nat \\<Rightarrow> num \\<Rightarrow> num\" where\n  \"rename_num n (Var v) = (if v\\<ge>n then Var (v+1) else Var v)\"|\n  \"rename_num _ (C c) = (C c)\" |\n  \"rename_num n (Add n1 n2) = Add (rename_num n n1) (rename_num n n2)\"|\n  \"rename_num n (Minus n1) = Minus (rename_num n n1)\"|\n  \"rename_num n (Mul n1 n2) = Mul (rename_num n n1) (rename_num n n2)\"|\n  \"rename_num n (Power n1 n') = Power (rename_num n n1) n'\"\n\nfun rename_norm_num:: \"nat \\<Rightarrow> norm_num \\<Rightarrow> norm_num\" where \n  \"rename_norm_num n (Pol p v) = (if v \\<ge> n then Pol p (v+1) else Pol p v)\"|\n  \"rename_norm_num _ (Const c) = Const c\" | \n  \"rename_norm_num n (Abnorm abn) = Abnorm (rename_num n abn)\"\n\nfun rename_qf_form:: \"nat \\<Rightarrow> qf_form \\<Rightarrow> qf_form\" where\n  \"rename_qf_form n (Pos nn) = Pos (rename_norm_num n nn)\" | \n  \"rename_qf_form n (Zero nn) = Zero (rename_norm_num n nn)\"  | \n  \"rename_qf_form n (Neg qf) = Neg (rename_qf_form n qf)\" | \n  \"rename_qf_form n (Conj qf1 qf2) = Conj (rename_qf_form n qf1) (rename_qf_form n qf2)\" | \n  \"rename_qf_form n (Disj qf1 qf2) = Disj (rename_qf_form n qf1) (rename_qf_form n qf2)\" | \n  \"rename_qf_form _ T = T\" | \n  \"rename_qf_form _ F = F\"\n\nfun rename::\"nat \\<Rightarrow> norm_form \\<Rightarrow> norm_form\" where\n  \"rename n (AllQ nf) = AllQ (rename (n+1) nf)\"|\n  \"rename n (ExQ nf) = ExQ (rename (n+1) nf)\" |\n  \"rename n (QF qf) = QF (rename_qf_form n qf)\"\n\nprimrec qf_size :: \"qf_form\\<Rightarrow> nat\"\nwhere\n  \"qf_size (Pos norm_num) = 1\"\n| \"qf_size (Zero norm_num) = 1 \"\n| \"qf_size (Neg qf) = 1 + qf_size qf\"\n| \"qf_size (Conj p q) = 1 + qf_size p + qf_size q\"\n| \"qf_size (Disj p q) = 1 + qf_size p + qf_size q\"\n| \"qf_size T = 0\"\n| \"qf_size F = 0\"\n\nprimrec nf_size :: \"norm_form \\<Rightarrow> nat\"\nwhere\n  \"nf_size (QF qf) = 1\"\n| \"nf_size (ExQ nf) = 1 + nf_size nf\"\n| \"nf_size (AllQ nf) = 1 + nf_size nf\"\n\nprimrec nf_prod_size:: \"norm_form \\<times> norm_form \\<Rightarrow> nat\" where\n  \"nf_prod_size (p1,p2) = (nf_size (p1)) + (nf_size (p2)) \"\n\nlemma [measure_function]: \"is_measure nf_prod_size\" ..\n\n\n\nfun combine_conj::\"norm_form \\<Rightarrow> norm_form \\<Rightarrow> norm_form\" where \n  \"combine_conj (QF qf1) (QF qf2) = QF (Conj qf1 qf2)\"|\n  \"combine_conj (AllQ nf1) (AllQ nf2) = AllQ (combine_conj nf1 nf2)\"|\n  \"combine_conj (AllQ nf1) nf2 = AllQ (combine_conj nf1 (rename 0 nf2))\"|\n  \"combine_conj nf1 (AllQ nf2) = AllQ (combine_conj (rename 0 nf1) nf2)\"|\n  \"combine_conj (ExQ nf1) nf2 = ExQ (combine_conj nf1 (rename 0 nf2))\"|\n  \"combine_conj nf1 (ExQ nf2) = ExQ (combine_conj (rename 0 nf1) nf2)\"\n\nfun combine_disj::\"norm_form \\<Rightarrow> norm_form \\<Rightarrow> norm_form\" where \n  \"combine_disj (QF qf1) (QF qf2) = QF (Disj qf1 qf2)\"|\n  \"combine_disj (ExQ nf1) (ExQ nf2) = ExQ (combine_disj nf1 nf2)\"|\n  \"combine_disj (AllQ nf1) nf2 = AllQ (combine_disj nf1 (rename 0 nf2))\"|\n  \"combine_disj nf1 (AllQ nf2) = AllQ (combine_disj (rename 0 nf1) nf2)\"|\n  \"combine_disj (ExQ nf1) nf2 = ExQ (combine_disj nf1 (rename 0 nf2))\"|\n  \"combine_disj nf1 (ExQ nf2) = ExQ (combine_disj (rename 0 nf1) nf2)\"\n\nfun neg_nf:: \"norm_form \\<Rightarrow> norm_form \" where\n  \"neg_nf (QF qf) = QF (Neg qf)\"|\n  \"neg_nf (AllQ nf) = ExQ (neg_nf nf)\"|\n  \"neg_nf (ExQ nf) = AllQ (neg_nf nf)\"\n\nfun normalize:: \"form \\<Rightarrow> norm_form\" where\n  \"normalize (Lt num1 num2) \n    =  (QF o Pos) (add_norm_num  (normalize_num num2) (minus_norm_num (normalize_num num1)))\"|\n  \"normalize (Eq num1 num2) \n    =  (QF o Zero) (add_norm_num  (normalize_num num1) (minus_norm_num(normalize_num num2)))\"|\n  \"normalize (Ge num1 num2) \n    = (QF o Neg o Pos) ((add_norm_num  (normalize_num num2) (minus_norm_num (normalize_num num1))))\" |\n  \"normalize (NEq num1 num2) \n    = (QF o Neg o Zero) ((add_norm_num  (normalize_num num1) (minus_norm_num (normalize_num num2))))\"|\n  \"normalize (form.Conj f1 f2) = (combine_conj (normalize f1) (normalize f2))\" |\n  \"normalize (form.Disj f1 f2) = combine_disj (normalize f1) (normalize f2)\"|\n  \"normalize (form.Neg form) = neg_nf (normalize form)\"|\n  \"normalize form.T = QF T\"|\n  \"normalize form.F = QF F\"|\n  \"normalize (form.ExQ form) = ExQ (normalize form)\"|\n  \"normalize (form.AllQ form) = AllQ (normalize form)\"\n\nfun qf_form_interp:: \"qf_form \\<Rightarrow> real list \\<Rightarrow> bool\" where \n  \"qf_form_interp (Pos norm_num) vs = (norm_num_interp norm_num vs > 0)\"|\n  \"qf_form_interp (Zero norm_num) vs = (norm_num_interp norm_num vs = 0)\"|\n  \"qf_form_interp (Neg qf_form) vs = (\\<not> qf_form_interp qf_form vs)\" |\n  \"qf_form_interp (Conj qf_form1 norm_form2) vs = (qf_form_interp qf_form1 vs\n   \\<and> qf_form_interp norm_form2 vs)\"|\n  \"qf_form_interp (Disj qf_form1 qf_form2) vs = (qf_form_interp qf_form1 vs\n   \\<or> qf_form_interp qf_form2 vs)\"|\n  \"qf_form_interp T vs = True\"|\n  \"qf_form_interp F vs = False\"\n\nfun norm_form_interp:: \"norm_form \\<Rightarrow>real list \\<Rightarrow> bool\" where\n  \"norm_form_interp (QF qf) vs = qf_form_interp qf vs\"|\n  \"norm_form_interp (ExQ norm_form) vs = (\\<exists>x. norm_form_interp norm_form (x#vs))\"|\n  \"norm_form_interp (AllQ norm_form) vs = (\\<forall>x. norm_form_interp norm_form (x#vs))\"\n\n\nlemma rename_num:\n  \"length vs'=n \\<Longrightarrow> num_interp (rename_num n num) (vs'@v#vs) = num_interp num (vs'@vs)\"\nby (induct num arbitrary: n vs vs' v ,auto simp add:nth_append)\n \nlemma rename_norm_num:\n   \"length vs'=n \\<Longrightarrow> \n   norm_num_interp (rename_norm_num n norm_num) (vs'@ v # vs) = norm_num_interp norm_num (vs'@vs)\"\nby (induct norm_num arbitrary:n vs vs' v,auto simp add:rename_num nth_append)\n\nlemma rename_qf_form:\n  \"length vs' = n \\<Longrightarrow> qf_form_interp (rename_qf_form n qf) (vs'@v # vs) = qf_form_interp qf (vs'@vs)\"\napply (induct qf)\nby (auto simp add:rename_norm_num)\n\nlemma rename:\n  \"length vs'=n \\<Longrightarrow> norm_form_interp (rename n nf) (vs'@v # vs) = norm_form_interp nf (vs'@vs)\"\napply (induct nf arbitrary:n vs' vs v)\napply (auto simp add:rename_qf_form  )\nby (metis append_Cons length_Cons)+\n\nlemma rename_inst:\n  \" norm_form_interp (rename (Suc 0) nf) (x # v # vs) = norm_form_interp nf (x # vs)\"\nusing rename[of \"[x]\" 1,simplified] .\n\nlemma combine_conj_correct:\n  \"norm_form_interp (combine_conj nf1 nf2) vs \\<longleftrightarrow> norm_form_interp nf1 vs \\<and> norm_form_interp nf2 vs\"\napply (induct arbitrary:vs rule:combine_conj.induct )\nby (auto simp add:rename_qf_form[of Nil 0,simplified] rename_inst HOL.all_conj_distrib[symmetric])\n\nlemma combine_disj_correct:\n  \"norm_form_interp (combine_disj nf1 nf2) vs \\<longleftrightarrow> norm_form_interp nf1 vs \\<or> norm_form_interp nf2 vs\"\napply (induct arbitrary:vs rule:combine_disj.induct)\nby (auto simp add:rename_inst rename_qf_form[of Nil 0,simplified] rename[of Nil 0,simplified] \n  ex_disj_distrib[symmetric])\n\nlemma neg_nf_correct:\n  \"norm_form_interp (neg_nf nf) vs \\<longleftrightarrow> \\<not> norm_form_interp nf vs\"\napply (induct arbitrary:vs rule:neg_nf.induct)\nby auto\n\nlemma norm_form_correct:\" norm_form_interp (normalize form) vs = form_interp form vs\" \napply (induct form arbitrary:vs rule:normalize.induct)\napply (auto simp add:norm_minus norm_add normalize_num_correct combine_conj_correct \n  combine_disj_correct neg_nf_correct)\ndone\n\ndatatype norm_num2 = Pol \"int poly\" nat | Const real | Abnorm num\ndatatype qf_form2 =  Pos norm_num2 | Zero norm_num2 | Neg qf_form2 \n    | Conj qf_form2 qf_form2 | Disj qf_form2 qf_form2 | T | F\ndatatype norm_form2 = QF qf_form2 | ExQ norm_form2 | AllQ norm_form2\n\ndefinition int_poly::\"real poly \\<Rightarrow> int poly\" where\n  \"int_poly p = undefined\"\n\nfun normalize_num2:: \"norm_num \\<Rightarrow> norm_num2\" where \n  \"normalize_num2 (norm_num.Pol p v) = \n    (if all_coeffs_rat p then Pol (clear_de_real p) v \n    else Abnorm (cancel_normalize_num(norm_num.Pol p v)))\" |\n  \"normalize_num2 (norm_num.Const c) = Const c\" |\n  \"normalize_num2 (norm_num.Abnorm num) = Abnorm num\"\n\nfun normalize_qf_form2:: \"qf_form \\<Rightarrow> qf_form2\" where\n  \"normalize_qf_form2 (qf_form.Pos norm_num) = Pos (normalize_num2 norm_num)\"|\n  \"normalize_qf_form2 (qf_form.Zero norm_num) = Zero (normalize_num2 norm_num)\"|\n  \"normalize_qf_form2 (qf_form.Neg qf_form) = Neg (normalize_qf_form2 qf_form)\"|\n  \"normalize_qf_form2 (qf_form.Conj qf_form qf_form') \n      = Conj (normalize_qf_form2 qf_form) (normalize_qf_form2 qf_form')\"|\n  \"normalize_qf_form2 (qf_form.Disj qf_form qf_form') \n      = Disj (normalize_qf_form2 qf_form) (normalize_qf_form2 qf_form')\"|\n  \"normalize_qf_form2 qf_form.T = T\"|\n  \"normalize_qf_form2 qf_form.F = F\"\n\nfun normalize2 :: \"norm_form \\<Rightarrow> norm_form2\" where\n  \"normalize2 (norm_form.QF qf_form) = QF (normalize_qf_form2 qf_form)\"|\n  \"normalize2 (norm_form.ExQ norm_form) = ExQ (normalize2 norm_form)\"|\n  \"normalize2 (norm_form.AllQ norm_form) = AllQ (normalize2 norm_form)\"\n  \nfun norm_num2_interp :: \"norm_num2 \\<Rightarrow> real list \\<Rightarrow> real\" where\n  \"norm_num2_interp (Pol p v) vs = poly (of_int_poly p) (vs!v)\"|\n  \"norm_num2_interp (Const c) vs = c\"|\n  \"norm_num2_interp (Abnorm num) vs = num_interp num vs\"\n\nfun qf_form2_interp:: \"qf_form2 \\<Rightarrow> real list \\<Rightarrow> bool\" where \n  \"qf_form2_interp (Pos norm_num) vs = (norm_num2_interp norm_num vs > 0)\"|\n  \"qf_form2_interp (Zero norm_num) vs = (norm_num2_interp norm_num vs = 0)\"|\n  \"qf_form2_interp (Neg qf_form) vs = (\\<not> qf_form2_interp qf_form vs)\" |\n  \"qf_form2_interp (Conj qf_form1 norm_form2) vs = (qf_form2_interp qf_form1 vs\n   \\<and> qf_form2_interp norm_form2 vs)\"|\n  \"qf_form2_interp (Disj qf_form1 qf_form2) vs = (qf_form2_interp qf_form1 vs\n   \\<or> qf_form2_interp qf_form2 vs)\"|\n  \"qf_form2_interp T vs = True\"|\n  \"qf_form2_interp F vs = False\"          \n\nfun norm_form2_interp:: \"norm_form2 \\<Rightarrow>real list \\<Rightarrow> bool\" where\n  \"norm_form2_interp (QF qf) vs = qf_form2_interp qf vs\"|\n  \"norm_form2_interp (ExQ norm_form) vs = (\\<exists>x. norm_form2_interp norm_form (x#vs))\"|\n  \"norm_form2_interp (AllQ norm_form) vs = (\\<forall>x. norm_form2_interp norm_form (x#vs))\"\n\ndeclare [[code drop:norm_form2_interp]]\n\nlemma normalize_qf_form2_correct:\n    \"qf_form2_interp (normalize_qf_form2 norm_form) vs = qf_form_interp norm_form vs\" \nproof -\n  have \"(0 < norm_num2_interp (normalize_num2 norm_num) vs) = (0 < norm_num_interp norm_num vs)\"\n      for norm_num \n    apply (induct norm_num rule:normalize_num2.induct)\n    apply (auto simp del:cancel_normalize_num.simps simp add:cancel_norm clear_de_real)\n    by (meson de_lcm_pos of_int_0_less_iff zero_less_mult_pos)\n  moreover have \"(0 = norm_num2_interp (normalize_num2 norm_num) vs) = (0 = norm_num_interp norm_num vs)\"\n      for norm_num \n    apply (induct norm_num rule:normalize_num2.induct)\n    apply (auto simp del:cancel_normalize_num.simps simp add:cancel_norm clear_de_real)\n    using de_lcm_pos by (metis less_irrefl)\n  ultimately show ?thesis  \n    apply (induct norm_form rule:normalize_qf_form2.induct)\n    by auto\nqed\n\nlemma norm_form2_correct:\" norm_form2_interp (normalize2 (normalize form)) vs = form_interp form vs\" \nproof -\n  have \"norm_form2_interp (normalize2 norm_form) vs = norm_form_interp norm_form vs\"\n    for norm_form \n    apply (induct norm_form arbitrary:vs rule:normalize2.induct)\n    by (auto simp add:normalize_qf_form2_correct)\n  thus ?thesis using norm_form_correct by auto\nqed\n\n\nsection \\<open>Efficient normalisation\\<close>\n\n\nML \\<open>\n\nfun raw_normalize2 (ctxt, ct,t) = Thm.mk_binop \\<^cterm>\\<open>Pure.eq :: norm_form2 \\<Rightarrow> norm_form2 \\<Rightarrow> prop\\<close>\n  ct (Thm.cterm_of ctxt t);\n\nval (_, normalize2_oracle) = Context.>>> (Context.map_theory_result\n  (Thm.add_oracle (\\<^binding>\\<open>normalize2\\<close>, raw_normalize2)));\n\\<close>\n\n\ndefinition \"coeffs_int = (coeffs :: _ \\<Rightarrow> int list)\"\ndefinition \"coeffs_real = (coeffs :: _ \\<Rightarrow> real list)\" \n\nML \\<open>\nfun mk_rat a b = @{const \"Rat.Fract\"} $ (HOLogic.mk_number @{typ int} a) \n                  $ (HOLogic.mk_number @{typ int} b);\nfun rat_of_rat x = (case @{code quotient_of} x of (x1,x2) \n        => mk_rat (@{code integer_of_int} x1) (@{code integer_of_int} x2)\n      );\nfun real_of_real (@{code Ratreal} x) = @{const \"Ratreal\"} $ (rat_of_rat x) \n\nfun nat_of_nat x = @{code integer_of_nat} x |> HOLogic.mk_nat\n\n(*TODO: more efficient while avoiding 'poly_of_list'?*)\nfun poly_of_poly_int x = \n        @{term \"poly_of_list :: int list \\<Rightarrow> _\"} $ (\n          (map (fn y => HOLogic.mk_number @{typ int} (@{code integer_of_int} y)) \n             (@{code coeffs_int} x))\n        |> HOLogic.mk_list @{typ \"int\"}\n        )\n\nfun poly_of_poly_real x = \n        @{term \"poly_of_list :: real list \\<Rightarrow> _\"} $ (\n          (map real_of_real (@{code coeffs_real} x))\n        |> HOLogic.mk_list @{typ \"real\"}\n        )\n\nfun num_of_num (@{code C} x) = @{term C} $ real_of_real x\n  | num_of_num (@{code Add} (nm1,nm2)) \n      = @{const Add} $ num_of_num nm1 $ num_of_num nm2\n  | num_of_num (@{code Minus} nm1) \n      = @{const Minus} $ num_of_num nm1 \n  | num_of_num (@{code Mul} (nm1,nm2)) \n      = @{const Mul} $ num_of_num nm1 $ num_of_num nm2\n  | num_of_num (@{code Var} n) \n      = @{const Var} $ nat_of_nat n \n  | num_of_num (@{code Power} (nm1,n)) \n      = @{const Power} $ num_of_num nm1 $ nat_of_nat n\n\nfun norm_num_of_norm_num (@{code norm_num.Pol} (p, n)) = \n        @{const norm_num.Pol} $ (poly_of_poly_real p) $ (nat_of_nat n)\n  | norm_num_of_norm_num (@{code norm_num.Const} x) = \n        @{const norm_num.Const} $ (real_of_real x)\n  | norm_num_of_norm_num (@{code norm_num.Abnorm} x) = \n        @{const norm_num.Abnorm} $ (num_of_num x)\n\nfun norm_num2_of_norm_num2 (@{code norm_num2.Pol} (p, n)) = \n        @{const norm_num2.Pol} $ (poly_of_poly_int p) $ (nat_of_nat n)\n  | norm_num2_of_norm_num2 (@{code norm_num2.Const} x) = \n        @{const norm_num2.Const} $ (real_of_real x)\n  | norm_num2_of_norm_num2 (@{code norm_num2.Abnorm} x) = \n        @{const norm_num2.Abnorm} $ (num_of_num x)\n\nfun qf_form2_of_qf_form2 (@{code Pos} nm) = \n        @{const Pos} $ (norm_num2_of_norm_num2 nm)\n  | qf_form2_of_qf_form2 (@{code Zero} nm) = \n        @{const Zero} $ (norm_num2_of_norm_num2 nm)\n  | qf_form2_of_qf_form2 (@{code Neg} qf) = \n        @{const Neg} $ (qf_form2_of_qf_form2 qf)\n  | qf_form2_of_qf_form2 (@{code Conj} (qf1,qf2)) =\n        @{const Conj} $ (qf_form2_of_qf_form2 qf1) $ (qf_form2_of_qf_form2 qf2)\n  | qf_form2_of_qf_form2 (@{code Disj} (qf1,qf2)) =\n        @{const Disj} $ (qf_form2_of_qf_form2 qf1) $ (qf_form2_of_qf_form2 qf2)\n  | qf_form2_of_qf_form2 (@{code T}) = @{const T}\n  | qf_form2_of_qf_form2 (@{code F}) = @{const F}\n\nfun norm_form2_of_norm_form2 (@{code QF} qf) =\n        @{const QF} $ (qf_form2_of_qf_form2 qf)\n  | norm_form2_of_norm_form2 (@{code ExQ} nf) =\n        @{const ExQ} $ (norm_form2_of_norm_form2 nf)\n  | norm_form2_of_norm_form2 (@{code AllQ} nf) =\n        @{const AllQ} $ (norm_form2_of_norm_form2 nf)\n  \n\nval comp_norm_conv = @{computation_conv norm_form2 \n    terms:\n      normalize_num2\n      normalize2\n      normalize\n\n  \n      Ratreal\n\n      \"Rat.Fract :: int \\<Rightarrow> int \\<Rightarrow> rat\"\n\n      (*int*)\n      \"0::int\"\n      \"1::int\"\n      rat_of_int\n\n      (*nat*)\n      \"0::nat\"\n      \"1::nat\"\n      \"Suc\"\n      nat_of_num\n\n      (*real*)\n      \"0::real\"\n      \"1::real\"\n      \"(/) :: _ \\<Rightarrow> _ \\<Rightarrow> real\"\n\n      (*poly*)\n    \"times::int poly \\<Rightarrow> _\" \n    \"pCons :: int \\<Rightarrow> _\" \n    \"pCons :: real \\<Rightarrow> _\"\n    \"smult::int \\<Rightarrow> _\"\n    \"HOL.equal ::int poly \\<Rightarrow> _\" \n    \"0 :: int poly\"\n    \"0 :: real poly\"\n    \"poly_of_list :: _ \\<Rightarrow> int poly\"\n\n    datatypes: norm_form2 qf_form2 qf_form form norm_form norm_num norm_num2 \n      Univ_RCF_Reification.num nat rat int \n      Num.num \"int list\"\n    } (fn ctxt => fn p => fn ct => normalize2_oracle (ctxt, ct, (norm_form2_of_norm_form2 p)))\n\\<close>\n\n\nML \\<open>\nfun check_shape ctrm = (case Thm.term_of ctrm of\n        \\<^term>\\<open>HOL.Trueprop\\<close> $ \n          (Const (\\<^const_name>\\<open>norm_form2_interp\\<close>, _) $ t $ _)\n           => true\n        |_ => false)\n\nval efficient_norm_tac' = \n      Subgoal.FOCUS (fn {context = ctxt, concl = goal, ...}\n         => let val _ = @{assert} (check_shape goal);\n                val trm_to_norm = goal |> Thm.dest_arg |> Thm.dest_arg1;\n                val rw_conv = Conv.rewr_conv (comp_norm_conv ctxt trm_to_norm)\n            in \n                HEADGOAL (CONVERSION (Conv.arg_conv (Conv.arg1_conv rw_conv)))\n                \n            end )\n\nfun efficient_norm_tac ctxt = \n        efficient_norm_tac' ctxt\n      THEN'\n        simp_tac (Raw_Simplifier.clear_simpset ctxt  \n          addsimps @{thms poly_of_list_def Poly.simps})\n\\<close>     \n\nend", "meta": {"author": "Wenda302", "repo": "RCF_Decision_Procedures", "sha": "30ef64c985403d2c9551a93dd12308e367a08f25", "save_path": "github-repos/isabelle/Wenda302-RCF_Decision_Procedures", "path": "github-repos/isabelle/Wenda302-RCF_Decision_Procedures/RCF_Decision_Procedures-30ef64c985403d2c9551a93dd12308e367a08f25/Univariate_RCF/Univ_RCF_Reification.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8688267694452331, "lm_q2_score": 0.8397339616560072, "lm_q1q2_score": 0.729583345099036}}
{"text": "theory hw2\nimports Main\n  \"HOL-Hoare.Hoare_Logic\"\n \"HOL-Library.Permutation\" \n\nbegin\n\n(*1*)\nlemma DownFact: \"VARS (z :: nat) (y :: nat) \n{True}\nz:=x;\ny:=1;\nWHILE z>0\nINV { fact x  = y * fact z }\nDO\ny := y * z; \nz := z-1\nOD\n{y = fact x}\"\n  apply vcg_simp\n  by (auto simp add: fact_reduce)\n \n\n(*2*)\n\nfunction sum :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\"\n  where \"sum i N = (if i > N then 0 else i + sum (Suc i) N)\"\n  by pat_completeness auto\ntermination sum\n  apply (relation \"measure (\\<lambda>(i,N). N + 1 - i)\")\n  apply auto\n  done\n\nvalue \"sum 1 4\"\n\nlemma SumLemma: \"VARS (s :: nat) (i :: nat) \n{b\\<ge>0}\ns:=0;\ni:=a;\nWHILE i \\<le> b\nINV { sum a b = s + sum i b }\nDO\ns := s + i; \ni := i + 1\nOD\n{s = sum a b   }\"\n  apply vcg_simp\n  done\n\nlemma \"VARS (s :: nat) (i :: nat)\n{n \\<ge> 1}\n  s := 0; \n  i := 0;\nWHILE i \\<le> n\n  INV {2 * s = ((i - 1) * i) \\<and> (i \\<le> n + 1)}\nDO\n  s := s + i;\n  i := i + 1\nOD\n{2 * s = (n * (n + 1))}\"\n  apply vcg_simp\n   apply (auto simp add: algebra_simps le_Suc_eq)\n  done\n\n\n(*fun sum_upto :: \"nat \\<Rightarrow> nat\"\n  where \"sum_upto 0 = 0\" |\n\"sum_upto (Suc a) = Suc a + (sum_upto (a))\"\n\nlemma eq_sum[simp]:\"sum 0 n =sum_upto n\"\n  apply(induct n)\n  oops\n\n\nlemma nsum[simp]:  \"(sum 0 (Suc(n))) = ((sum 0 n) + (sum (Suc(n)) (Suc(n))))\"\n  apply(induct n)\n   apply (simp)\n  oops*)\nlemma   \"(sum 0 n) = (n*(n+1))div 2\"\nproof(induct n)\n  case 0\n  then show ?case by simp\nnext\n  case (Suc n)\n  then show ?case sorry\nqed\n\n\nlemma qsum: \"(sum 0 n) = (n*(n+1))div 2\"\n  apply(induct n)\n   apply (simp)\n  quickcheck  \n                                                                                                     oops\n\n(*3*)\nlemma ll[simp]: \"length (removeAll x xs) < Suc (length xs)\"\n  apply(induct xs)\n   apply(auto)\n  done\n\nfunction perm::\"nat list \\<Rightarrow> nat list \\<Rightarrow> bool\" \n  where \"perm [] [] = True\" |\n\"perm [] (y#ys) = False\" |\n\"perm (x#xs) ys = perm (removeAll x xs) (removeAll x ys)\"\n  apply (metis list.exhaust subset_eq_mset_impl.cases)\n  by (auto)\ntermination perm\n apply (relation \"measure (\\<lambda>(xs,xy). length(xs) )\")\n   apply auto\n  done\n\n(*4*)\n\ndatatype tree0 = Node tree0 tree0 | Nil\n\nfun nodes :: \"tree0 \\<Rightarrow> nat\" where\n\"nodes Nil = 0\" |\n\"nodes (Node l r) = Suc(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\nvalue \"nodes(explode 12 (Node Nil Nil))\"\nvalue \"2^(12)*(Suc(nodes (Node Nil Nil)))-1\"\n\nlemma \"nodes(explode n t) = 2^(n)*(Suc(nodes t)) - 1 \"\n  apply(induction n arbitrary: t)\n  apply (auto)\n  by (smt add.assoc  mult.assoc  mult.commute  mult_2_right)\n\n\n(*5*)\nfun itadd::\"nat \\<Rightarrow> nat \\<Rightarrow> nat\"  where \n \"itadd 0 n = n\" |\n \"itadd (Suc m) n = itadd m (n + 1) \" \n\nfun add :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\" \n  where \"add 0 n = n \" |\n  \"add (Suc m) n = Suc (add m n)\"\n\nvalue \"itadd 14 17\"\nvalue \"add 14 17\"\n\nlemma cum_add[simp]: \"add m (Suc n) = Suc (add m n)\"\n  apply (induction m)\n   apply auto\n  done\n\nlemma addEquals : \"itadd m n = add m n\"\napply (induction m  arbitrary: n)\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/hw2.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278757303677, "lm_q2_score": 0.8267118004748677, "lm_q1q2_score": 0.7295135379342651}}
{"text": "(*\nAuthor:  Akihisa Yamada (2018-2019)\nLicense: LGPL (see file COPYING.LESSER)\n*)\nsection \\<open> Completeness of Relations \\<close>\n\ntext \\<open>Here we formalize various order-theoretic completeness conditions.\\<close>\n\ntheory Complete_Relations\n  imports HOL.Real Binary_Relations\nbegin\n\nsubsection \\<open>Completeness Conditions\\<close>\n\ntext \\<open>Order-theoretic completeness demands certain subsets of elements to admit suprema or infima.\n\nA related set $\\tp{A,\\SLE}$ is called \\emph{bounded} if there is a ``top'' element $\\top \\in A$,\na greatest element in $A$.\nNote that there might be multiple tops if $(\\SLE)$ is not antisymmetric.\\<close>\n\nlocale bounded = less_eq_syntax + assumes bounded: \"\\<exists>t. \\<forall>x. x \\<sqsubseteq> t\"\nbegin\n\nlemma ex_bound[intro!]: \"Ex (bound (\\<sqsubseteq>) X)\" using bounded by auto\n\nlemma ex_extreme_UNIV[intro!]: \"Ex (extreme (\\<sqsubseteq>) UNIV)\" using bounded by auto\n\nlemma UNIV_complete[intro!]: \"Ex (extreme_bound (\\<sqsubseteq>) UNIV)\" using bounded by blast\n\nlemma dual_empty_complete[intro!]: \"Ex (extreme_bound (\\<sqsubseteq>)\\<^sup>- {})\" by (auto simp: bound_empty)\n\nend\n\ncontext\n  fixes less_eq :: \"'a \\<Rightarrow> 'a \\<Rightarrow> bool\" (infix \"\\<sqsubseteq>\" 50)\nbegin\n\nlemma bounded_iff_extreme_UNIV: \"bounded (\\<sqsubseteq>) \\<longleftrightarrow> Ex (extreme (\\<sqsubseteq>) UNIV)\"\n  by (auto simp:bounded_def)\n\ntext\\<open>Boundedness can be also seen as a completeness condition,\nsince it is equivalent to saying that the universe has a supremum.\\<close>\n\nlemma bounded_iff_UNIV_complete: \"bounded (\\<sqsubseteq>) \\<longleftrightarrow> Ex (extreme_bound (\\<sqsubseteq>) UNIV)\"\n  by (unfold bounded_def, blast)\n\ntext \\<open>The dual notion of bounded is called ``pointed'', equivalently ensuring a supremum\nof the empty set.\\<close>\n\nlemma pointed_iff_empty_complete: \"bounded (\\<sqsubseteq>) \\<longleftrightarrow> Ex (extreme_bound (\\<sqsubseteq>)\\<^sup>- {})\"\n  by (auto simp:bounded_def)\n\nend\n\n\ntext \\<open>One of the most well-studied notion of completeness would be the semilattice condition:\nevery pair of elements $x$ and $y$ has a supremum $x \\sqcup y$\n(not necessarily unique if the underlying relation is not antisymmetric).\\<close>\n\nlocale pair_complete = less_eq_syntax +\n  assumes pair_complete: \"Ex (extreme_bound (\\<sqsubseteq>) {x,y})\"\nbegin\n\nlemma directed_UNIV[intro!]: \"directed (\\<sqsubseteq>) UNIV\"\nproof\n  fix x y :: 'a\n  from pair_complete[of x y] show \"\\<exists>z \\<in> UNIV. x \\<sqsubseteq> z \\<and> y \\<sqsubseteq> z\" by auto\nqed\n\nend\n\nsublocale total_reflexive \\<subseteq> pair_complete\nproof (unfold_locales)\n  fix x y\n  show \"Ex (extreme_bound (\\<sqsubseteq>) {x, y})\" by (cases x y rule:comparable_cases, auto)\nqed\n\ntext \\<open>The next one assumes that every nonempty finite set has a supremum.\\<close>\n\nlocale finite_complete = less_eq_syntax +\n  assumes finite_nonempty_complete: \"finite X \\<Longrightarrow> X \\<noteq> {} \\<Longrightarrow> Ex (extreme_bound (\\<sqsubseteq>) X)\"\n\nsublocale finite_complete \\<subseteq> pair_complete\n  by (unfold_locales, intro finite_nonempty_complete, auto)\n\ntext \\<open>The next one assumes that every nonempty bounded set has a supremum.\nIt is also called the Dedekind completeness.\\<close>\n\nlocale conditionally_complete = less_eq_syntax +\n  assumes bounded_nonempty_complete:\n  \"Ex (bound (\\<sqsubseteq>) X) \\<Longrightarrow> X \\<noteq> {} \\<Longrightarrow> Ex (extreme_bound (\\<sqsubseteq>) X)\"\nbegin\n\nlemma bounded_nonemptyE[elim!]:\n  assumes \"Ex (bound (\\<sqsubseteq>) X)\" and \"X \\<noteq> {}\"\n    and \"Ex (extreme_bound (\\<sqsubseteq>) X) \\<Longrightarrow> X \\<noteq> {} \\<Longrightarrow> thesis\"\n  shows thesis\n  using assms bounded_nonempty_complete by auto\n\nlemma nonempty_imp_complete_iff_bounded:\n  assumes \"X \\<noteq> {}\" shows \"Ex (extreme_bound (\\<sqsubseteq>) X) \\<longleftrightarrow> Ex (bound (\\<sqsubseteq>) X)\"\n  using assms by (auto intro: bounded_nonempty_complete)\n\nend\n\ntext \\<open>The $\\omega$-completeness condition demands a supremum for an $\\omega$-chain,\n  $a_1 \\sqsubseteq a_2 \\sqsubseteq \\dots$.\n  We model $\\omega$-chain as the range of a monotone map $f : i \\mapsto a_i$.\\<close>\n\nlocale omega_complete = less_eq_syntax +\n  assumes monotone_seq_complete:\n    \"\\<And>f :: nat \\<Rightarrow> 'a. monotone (\\<le>) (\\<sqsubseteq>) f \\<Longrightarrow> Ex (extreme_bound (\\<sqsubseteq>) (range f))\"\n\nlocale chain_complete = less_eq_syntax +\n  assumes chain_nonempty_complete: \"chain (\\<sqsubseteq>) X \\<Longrightarrow> X \\<noteq> {} \\<Longrightarrow> Ex (extreme_bound (\\<sqsubseteq>) X)\"\nbegin\n\nlemma monotone_chain_complete:\n  assumes C0: \"C \\<noteq> {}\" and chain: \"chain r C\" and mono: \"monotone r (\\<sqsubseteq>) f\"\n  shows \"Ex (extreme_bound (\\<sqsubseteq>) (f ` C))\"\n  apply (rule chain_nonempty_complete[OF monotone_chain_image[OF mono chain]])\n  using C0 by auto\n\nend\n\nsublocale chain_complete \\<subseteq> omega_complete\n  by (unfold_locales, rule monotone_chain_complete, auto intro:chainI)\n\ntext\\<open>\\emph{Directed completeness} is an important notion in domain theory~\\cite{abramski94},\nasserting that every nonempty directed set has a supremum.\nHere, a set $X$ is \\emph{directed} if any pair of two elements in $X$ has a bound in $X$.\\<close>\n\nlocale directed_complete = less_eq_syntax +\n  assumes directed_nonempty_complete: \"directed (\\<sqsubseteq>) X \\<Longrightarrow> X \\<noteq> {} \\<Longrightarrow> Ex (extreme_bound (\\<sqsubseteq>) X)\"\nbegin\n\nlemma monotone_directed_complete:\n  assumes dir: \"directed r C\" and c0: \"C \\<noteq> {}\" and mono: \"monotone r (\\<sqsubseteq>) f\"\n  shows \"Ex (extreme_bound (\\<sqsubseteq>) (f ` C))\"\n  apply (rule directed_nonempty_complete[OF monotone_directed_image[OF mono dir]])\n  using c0 by auto\n\nend\n\nsublocale directed_complete \\<subseteq> chain_complete\n  by (unfold_locales, intro directed_nonempty_complete, auto dest: chain_imp_directed)\n\ntext \\<open>The next one is quite complete, only the empty set may fail to have a supremum.\nThe terminology follows \\cite{Bergman2015},\nalthough there it is defined more generally depending on a cardinal $\\alpha$\nsuch that a nonempty set $X$ of cardinality below $\\alpha$ has a supremum.\\<close>\n\nlocale semicomplete = less_eq_syntax +\n  assumes nonempty_complete: \"X \\<noteq> {} \\<Longrightarrow> Ex (extreme_bound (\\<sqsubseteq>) X)\"\n\nsublocale semicomplete \\<subseteq> conditionally_complete + finite_complete + directed_complete\n  by (unfold_locales, auto intro!: nonempty_complete)\n\nsublocale semicomplete \\<subseteq> bounded\n  unfolding bounded_iff_UNIV_complete using nonempty_complete[of UNIV] by auto\n\nsubsection \\<open>Pointed Ones\\<close>\n\ntext \\<open>The term `pointed' refers to the dual notion of boundedness, i.e., there is a global least element.\n  This serves as the supremum of the empty set.\\<close>\n\nlocale pointed_chain_complete = chain_complete + dual: bounded \"(\\<sqsubseteq>)\\<^sup>-\"\nbegin\n\nlemma chain_complete: \"chain (\\<sqsubseteq>) X \\<Longrightarrow> Ex (extreme_bound (\\<sqsubseteq>) X)\"\n  by (cases \"X = {}\", auto intro:chain_nonempty_complete)\n\nend\n\nlemma pointed_chain_complete_def':\n  fixes less_eq (infix \"\\<sqsubseteq>\" 50)\n  shows \"pointed_chain_complete (\\<sqsubseteq>) \\<equiv> \\<forall>X. chain (\\<sqsubseteq>) X \\<longrightarrow> Ex (extreme_bound (\\<sqsubseteq>) X)\" (is \"?l \\<equiv> ?r\")\n  apply (unfold atomize_eq, intro iffI)\n  apply (force intro: pointed_chain_complete.chain_complete)\n  by (unfold_locales, auto intro!: chain_empty simp: pointed_iff_empty_complete[unfolded bounded_def])\n\nlocale pointed_directed_complete = directed_complete + dual: bounded \"(\\<sqsubseteq>)\\<^sup>-\"\nbegin\n\nlemma directed_complete: \"directed (\\<sqsubseteq>) X \\<Longrightarrow> Ex (extreme_bound (\\<sqsubseteq>) X)\"\n  by (cases \"X = {}\", auto intro: directed_nonempty_complete)\n\nsublocale pointed_chain_complete ..\n\nend\n\nlemma pointed_directed_complete_def':\n  fixes less_eq (infix \"\\<sqsubseteq>\" 50)\n  shows \"pointed_directed_complete (\\<sqsubseteq>) \\<equiv> \\<forall>X. directed (\\<sqsubseteq>) X \\<longrightarrow> Ex (extreme_bound (\\<sqsubseteq>) X)\"\n  apply (unfold atomize_eq, intro iffI)\n  apply (force intro: pointed_directed_complete.directed_complete)\n  by (unfold_locales, auto simp: pointed_iff_empty_complete[unfolded bounded_def])\n\ntext \\<open>``Bounded complete'' refers to pointed conditional complete,\nbut this notion is just the dual of semicompleteness. We prove this later.\n\nFollowing is the strongest completeness that requires any subset of elements to have suprema\nand infima.\\<close>\n\nlocale complete = less_eq_syntax + assumes complete: \"Ex (extreme_bound (\\<sqsubseteq>) X)\"\nbegin\n\nsublocale semicomplete + pointed_directed_complete\n  by (auto simp: pointed_directed_complete_def' intro: semicomplete.intro complete)\n\nend\n\nsubsection \\<open>Relations between Completeness Conditions\\<close>\n\ncontext\n  fixes less_eq :: \"'a \\<Rightarrow> 'a \\<Rightarrow> bool\" (infix \"\\<sqsubseteq>\" 50)\nbegin\n\ninterpretation less_eq_dualize.\n\ntext \\<open>Pair-completeness implies that the universe is directed. Thus, with directed completeness\nimplies boundedness.\\<close>\n\nproposition directed_complete_pair_complete_imp_bounded:\n  assumes \"directed_complete (\\<sqsubseteq>)\" and \"pair_complete (\\<sqsubseteq>)\"\n  shows \"bounded (\\<sqsubseteq>)\"\nproof-\n  from assms interpret directed_complete + pair_complete by auto\n  have \"Ex (extreme_bound (\\<sqsubseteq>) UNIV)\" by (rule directed_nonempty_complete, auto)\n  then obtain t where \"extreme_bound (\\<sqsubseteq>) UNIV t\" by auto\n  then have \"\\<forall>x. x \\<sqsubseteq> t\" by auto\n  then show ?thesis by (unfold_locales, auto)\nqed\n\ntext \\<open>Semicomplete is conditional complete and bounded.\\<close>\n\nproposition semicomplete_iff_conditionally_complete_bounded:\n  \"semicomplete (\\<sqsubseteq>) \\<longleftrightarrow> conditionally_complete (\\<sqsubseteq>) \\<and> bounded (\\<sqsubseteq>)\" (is \"?l \\<longleftrightarrow> ?r\")\nproof\n  assume ?r\n  then interpret conditionally_complete \"(\\<sqsubseteq>)\" + bounded \"(\\<sqsubseteq>)\" by auto\n  show ?l by (unfold_locales, rule bounded_nonempty_complete, auto)\nnext\n  assume ?l\n  then interpret semicomplete.\n  show ?r by (intro conjI, unfold_locales)\nqed\n\nproposition complete_iff_pointed_semicomplete:\n  \"complete (\\<sqsubseteq>) \\<longleftrightarrow> semicomplete (\\<sqsubseteq>) \\<and> bounded (\\<sqsupseteq>)\" (is \"?l \\<longleftrightarrow> ?r\")\nproof\n  assume \"complete (\\<sqsubseteq>)\"\n  then interpret complete.\n  show ?r by (intro conjI, unfold_locales)\nnext\n  assume ?r\n  then interpret semicomplete + bounded \"(\\<sqsupseteq>)\" by auto\n  show ?l\n  proof\n    fix X show \"Ex (extreme_bound (\\<sqsubseteq>) X)\" by (cases \"X = {}\", auto intro:nonempty_complete)\n  qed\nqed\n\ntext \\<open>Conditional completeness only lacks top and bottom to be complete.\\<close>\n\nproposition complete_iff_conditionally_complete_bounded_pointed:\n  \"complete (\\<sqsubseteq>) \\<longleftrightarrow> conditionally_complete (\\<sqsubseteq>) \\<and> bounded (\\<sqsubseteq>) \\<and> bounded (\\<sqsupseteq>)\"\n  unfolding complete_iff_pointed_semicomplete\n    semicomplete_iff_conditionally_complete_bounded by auto\n\nend\n\n\ntext \\<open>If the universe is directed, then every pair is bounded, and thus has a supremum.\n  On the other hand, supremum gives an upper bound, witnessing directedness.\\<close>\n\nproposition (in conditionally_complete) pair_complete_iff_directed:\n  \"pair_complete (\\<sqsubseteq>) \\<longleftrightarrow> directed (\\<sqsubseteq>) UNIV\"\nproof(intro iffI)\n  assume \"directed (\\<sqsubseteq>) UNIV\"\n  then show \"pair_complete (\\<sqsubseteq>)\"\n    by (unfold_locales, intro bounded_nonempty_complete, auto elim: directedE)\nnext\n  assume \"pair_complete (\\<sqsubseteq>)\"\n  then interpret pair_complete.\n  show \"directed (\\<sqsubseteq>) UNIV\"\n  proof (intro directedI)\n    fix x y\n    from pair_complete obtain z where \"extreme_bound (\\<sqsubseteq>) {x,y} z\" by auto\n    then show \"\\<exists>z\\<in>UNIV. x \\<sqsubseteq> z \\<and> y \\<sqsubseteq> z\" by auto\n  qed\nqed\n\n\nsubsection \\<open>Completeness Results Requiring Order-Like Properties\\<close>\n\ntext \\<open>Above results hold without any assumption on the relation.\nThis part demands some order-like properties.\\<close>\n\ntext \\<open>It is well known that in a semilattice, i.e., a pair-complete partial order,\nevery finite nonempty subset of elements has a supremum.\nWe prove the result assuming transitivity, but only that.\\<close>\n\nlocale trans_semilattice = transitive + pair_complete\n\nsublocale trans_semilattice \\<subseteq> finite_complete\n  apply (unfold_locales)\n  subgoal for X\n  proof (induct X rule:finite_induct)\n    case empty\n    then show ?case by auto\n  next\n    case (insert x X)\n    show ?case\n    proof (cases \"X = {}\")\n      case True\n      obtain x' where \"extreme_bound (\\<sqsubseteq>) {x,x} x'\" using pair_complete[of x x] by auto\n      with True show ?thesis by (auto intro!: exI[of _ x'])\n    next\n      case False\n      with insert obtain b where b: \"extreme_bound (\\<sqsubseteq>) X b\" by auto\n      from pair_complete obtain c where c: \"extreme_bound (\\<sqsubseteq>) {x,b} c\" by auto\n      show ?thesis\n      proof (intro exI extreme_boundI)\n        from c have \"x \\<sqsubseteq> c\" and \"b \\<sqsubseteq> c\" by auto\n        with b show \"xb \\<in> insert x X \\<Longrightarrow> xb \\<sqsubseteq> c\" for xb by (auto dest: trans)\n        fix d assume \"bound (\\<sqsubseteq>) (insert x X) d\"\n        with b have \"bound (\\<sqsubseteq>) {x,b} d\" by auto\n        with c show \"c \\<sqsubseteq> d\" by auto\n      qed\n    qed\n  qed\ndone\n\n\ntext \\<open>Gierz et al.~\\cite{gierz03} showed that a directed complete partial order is semicomplete\nif and only if it is also a semilattice.\nWe generalize the claim so that the underlying relation is only transitive.\\<close>\n\nproposition(in transitive) semicomplete_iff_directed_complete_pair_complete:\n  \"semicomplete (\\<sqsubseteq>) \\<longleftrightarrow> directed_complete (\\<sqsubseteq>) \\<and> pair_complete (\\<sqsubseteq>)\" (is \"?l \\<longleftrightarrow> ?r\")\nproof (intro iffI semicomplete.intro)\n  assume ?l\n  then interpret semicomplete.\n  show ?r by (intro conjI, unfold_locales)\nnext\n  assume ?r\n  then interpret directed_complete + pair_complete by auto\n  interpret trans_semilattice ..\n  fix X :: \"'a set\"\n  have 1: \"directed (\\<sqsubseteq>) {x. \\<exists>Y \\<subseteq> X. finite Y \\<and> Y \\<noteq> {} \\<and> extreme_bound (\\<sqsubseteq>) Y x}\" (is \"directed _ ?B\")\n  proof (intro directedI)\n    fix a b assume a: \"a \\<in> ?B\" and b: \"b \\<in> ?B\"\n    from a obtain A where A: \"extreme_bound (\\<sqsubseteq>) A a\" \"finite A\" \"A \\<noteq> {}\" \"A \\<subseteq> X\" by auto\n    from b obtain B where B: \"extreme_bound (\\<sqsubseteq>) B b\" \"finite B\" \"B \\<noteq> {}\" \"B \\<subseteq> X\" by auto\n    from A B have AB: \"finite (A \\<union> B)\" \"A \\<union> B \\<noteq> {}\" \"A \\<union> B \\<subseteq> X\" by auto\n    with finite_nonempty_complete have \"Ex (extreme_bound (\\<sqsubseteq>) (A \\<union> B))\" by auto\n    then obtain c where c: \"extreme_bound (\\<sqsubseteq>) (A \\<union> B) c\" by auto\n    show \"\\<exists>c \\<in> ?B. a \\<sqsubseteq> c \\<and> b \\<sqsubseteq> c\"\n    proof (intro bexI conjI)\n      from A B c show \"a \\<sqsubseteq> c\" and \"b \\<sqsubseteq> c\" by (auto simp: extreme_bound_iff)\n      from AB c show \"c \\<in> ?B\" by (auto intro!: exI[of _ \"A \\<union> B\"])\n    qed\n  qed\n  assume \"X \\<noteq> {}\"\n  then obtain x where xX: \"x \\<in> X\" by auto\n  from finite_nonempty_complete[of \"{x}\"]\n  obtain x' where \"extreme_bound (\\<sqsubseteq>) {x} x'\" by auto\n  with xX have x'B: \"x' \\<in> ?B\" by (auto intro!: exI[of _ \"{x}\"] extreme_boundI)\n  then have 2: \"?B \\<noteq> {}\" by auto\n  from directed_nonempty_complete[OF 1 2]\n  obtain b where b: \"extreme_bound (\\<sqsubseteq>) ?B b\" by auto\n  show \"Ex (extreme_bound (\\<sqsubseteq>) X)\"\n  proof (intro exI extreme_boundI UNIV_I)\n    fix x\n    assume xX: \"x \\<in> X\"\n    from finite_nonempty_complete[of \"{x}\"]\n    obtain c where c: \"extreme_bound (\\<sqsubseteq>) {x} c\" by auto\n    then have xc: \"x \\<sqsubseteq> c\" by auto\n    from c xX have cB: \"c \\<in> ?B\" by (auto intro!: exI[of _ \"{x}\"] extreme_boundI)\n    with b have cb: \"c \\<sqsubseteq> b\" by auto\n    from xc cb show \"x \\<sqsubseteq> b\" by (rule trans) text\\<open> Here transitivity is needed. \\<close>\n  next\n    fix x\n    assume Xx: \"bound (\\<sqsubseteq>) X x\"\n    have \"bound (\\<sqsubseteq>) ?B x\"\n    proof (intro boundI UNIV_I, clarify)\n      fix c Y\n      assume \"finite Y\" and YX: \"Y \\<subseteq> X\" and \"Y \\<noteq> {}\" and c: \"extreme_bound (\\<sqsubseteq>) Y c\"\n      from YX Xx have \"bound (\\<sqsubseteq>) Y x\" by auto\n      with c show \"c \\<sqsubseteq> x\" by auto\n    qed\n    with b show \"b \\<sqsubseteq> x\" by auto\n  qed\nqed\n\ntext\\<open>The last argument in the above proof requires transitivity,\nbut if we had reflexivity then $x$ itself is a supremum of $\\set{x}$\n(see @{thm reflexive.extreme_bound_singleton}) and so $x \\SLE s$ would be immediate.\nThus we can replace transitivity by reflexivity,\nbut then pair-completeness does not imply finite completeness.\nWe obtain the following result.\\<close>\n\nproposition (in reflexive) semicomplete_iff_directed_complete_finite_complete:\n  \"semicomplete (\\<sqsubseteq>) \\<longleftrightarrow> directed_complete (\\<sqsubseteq>) \\<and> finite_complete (\\<sqsubseteq>)\" (is \"?l \\<longleftrightarrow> ?r\")\nproof (intro iffI semicomplete.intro)\n  assume ?l\n  then interpret semicomplete.\n  show ?r by (safe, unfold_locales)\nnext\n  assume ?r\n  then interpret directed_complete + finite_complete by auto\n  fix X :: \"'a set\"\n  have 1: \"directed (\\<sqsubseteq>) {x. \\<exists>Y \\<subseteq> X. finite Y \\<and> Y \\<noteq> {} \\<and> extreme_bound (\\<sqsubseteq>) Y x}\" (is \"directed _ ?B\")\n  proof (intro directedI)\n    fix a b assume a: \"a \\<in> ?B\" and b: \"b \\<in> ?B\"\n    from a obtain A where A: \"extreme_bound (\\<sqsubseteq>) A a\" \"finite A\" \"A \\<noteq> {}\" \"A \\<subseteq> X\" by auto\n    from b obtain B where B: \"extreme_bound (\\<sqsubseteq>) B b\" \"finite B\" \"B \\<noteq> {}\" \"B \\<subseteq> X\" by auto\n    from A B have AB: \"finite (A \\<union> B)\" \"A \\<union> B \\<noteq> {}\" \"A \\<union> B \\<subseteq> X\" by auto\n    with finite_nonempty_complete have \"Ex (extreme_bound (\\<sqsubseteq>) (A \\<union> B))\" by auto\n    then obtain c where c: \"extreme_bound (\\<sqsubseteq>) (A \\<union> B) c\" by auto\n    show \"\\<exists>c \\<in> ?B. a \\<sqsubseteq> c \\<and> b \\<sqsubseteq> c\"\n    proof (intro bexI conjI)\n      from A B c show \"a \\<sqsubseteq> c\" and \"b \\<sqsubseteq> c\" by (auto simp: extreme_bound_iff)\n      from AB c show \"c \\<in> ?B\" by (auto intro!: exI[of _ \"A \\<union> B\"])\n    qed\n  qed\n  assume \"X \\<noteq> {}\"\n  then obtain x where xX: \"x \\<in> X\" by auto\n  then have \"extreme_bound (\\<sqsubseteq>) {x} x\" by auto\n  with xX have xB: \"x \\<in> ?B\" by (auto intro!: exI[of _ \"{x}\"])\n  then have 2: \"?B \\<noteq> {}\" by auto\n  from directed_nonempty_complete[OF 1 2]\n  obtain b where b: \"extreme_bound (\\<sqsubseteq>) ?B b\" by auto\n  show \"Ex (extreme_bound (\\<sqsubseteq>) X)\"\n  proof (intro exI extreme_boundI UNIV_I)\n    fix x\n    assume xX: \"x \\<in> X\"\n    have x: \"extreme_bound (\\<sqsubseteq>) {x} x\" by auto\n    from x xX have cB: \"x \\<in> ?B\" by (auto intro!: exI[of _ \"{x}\"])\n    with b show \"x \\<sqsubseteq> b\" by auto\n  next\n    fix x\n    assume Xx: \"bound (\\<sqsubseteq>) X x\"\n    have \"bound (\\<sqsubseteq>) ?B x\"\n    proof (intro boundI UNIV_I, clarify)\n      fix c Y\n      assume \"finite Y\" and YX: \"Y \\<subseteq> X\" and \"Y \\<noteq> {}\" and c: \"extreme_bound (\\<sqsubseteq>) Y c\"\n      from YX Xx have \"bound (\\<sqsubseteq>) Y x\" by auto\n      with c show \"c \\<sqsubseteq> x\" by auto\n    qed\n    with b show \"b \\<sqsubseteq> x\" by auto\n  qed\nqed\n\nlocale complete_attractive = complete + attractive\n\nlocale complete_antisymmetric = complete + antisymmetric\n\nsublocale complete_antisymmetric \\<subseteq> complete_attractive ..\n\ntext \\<open>Complete pseudo orders are called complete trellises~\\cite{trellis},\nbut let us reserve the name for introducing classes (in the future).\\<close>\n\nlocale complete_pseudo_order = complete + pseudo_order\n\nsublocale complete_pseudo_order \\<subseteq> complete_antisymmetric ..\n\ntext \\<open>Finally, we (re)define complete lattices as a complete partial order.\\<close>\n\nlocale complete_partial_order = complete + partial_order\n\nsublocale complete_partial_order \\<subseteq> trans_semilattice + complete_pseudo_order ..\n\nsubsection \\<open>Relating to Classes\\<close>\n\nclass ccomplete = ord + assumes \"conditionally_complete (\\<le>)\"\nbegin\n\nsublocale order: conditionally_complete using ccomplete_axioms unfolding class.ccomplete_def.\n\nend\n\nclass complete_ord = ord + assumes \"complete (\\<le>)\"\nbegin\n\ninterpretation order: complete using complete_ord_axioms unfolding class.complete_ord_def.\n\nsubclass ccomplete ..\n\nsublocale order: complete ..\n\nend\n\ntext \\<open>Isabelle's class @{class conditionally_complete_lattice} is @{class ccomplete}.\nThe other direction does not hold, since for the former,\n@{term \"Sup {}\"} and @{term \"Inf {}\"} are arbitrary even if there are top or bottom elements.\\<close>\n\nsubclass (in conditionally_complete_lattice) ccomplete\nproof\n  fix X\n  assume \"Ex (upper_bound X)\" and X0: \"X \\<noteq> {}\"\n  from this(1) have \"bdd_above X\" by auto\n  from cSup_upper[OF _ this] cSup_least[OF X0]\n  have \"supremum X (Sup X)\" by (intro extremeI boundI, auto)\n  then show \"Ex (supremum X)\" by auto\nqed\n\ntext \\<open>Isabelle's class @{class complete_lattice} is precisely @{locale complete_partial_order}.\\<close>\n\ncontext complete_lattice begin\n\ninterpretation order: complete_partial_order\n  by (unfold_locales, auto intro!: Sup_upper Sup_least Inf_lower Inf_greatest)\n\nsubclass complete_ord ..\n\nsublocale order: complete_partial_order ..\n\nend\n\n\nsubsection \\<open>Duality of Completeness Conditions\\<close>\n\ntext \\<open>Conditional completeness is symmetric.\\<close>\n\nsublocale conditionally_complete \\<subseteq> dual: conditionally_complete \"(\\<sqsubseteq>)\\<^sup>-\"\nproof\n  interpret less_eq_dualize.\n  fix X :: \"'a set\"\n  assume bound: \"Ex (bound (\\<sqsupseteq>) X)\" and nonemp: \"X \\<noteq> {}\"\n  then have \"Ex (bound (\\<sqsubseteq>) {b. bound (\\<sqsupseteq>) X b})\" and \"{b. bound (\\<sqsupseteq>) X b} \\<noteq> {}\" by auto\n  from bounded_nonempty_complete[OF this]\n  obtain s where \"extreme_bound (\\<sqsubseteq>) {b. bound (\\<sqsupseteq>) X b} s\" by auto\n  then show \"Ex (extreme_bound (\\<sqsupseteq>) X)\" by (intro exI[of _ s] extremeI, auto)\nqed\n\ntext \\<open>Full completeness is symmetric.\\<close>\n\nsublocale complete \\<subseteq> dual: complete \"(\\<sqsubseteq>)\\<^sup>-\"\nproof\n  fix X :: \"'a set\"\n  obtain s where \"extreme_bound (\\<sqsubseteq>) {b. bound (\\<sqsubseteq>)\\<^sup>- X b} s\" using complete by auto\n  then show \"Ex (extreme_bound (\\<sqsubseteq>)\\<^sup>- X)\" by (intro exI[of _ s] extreme_boundI, auto)\nqed\n\nsublocale complete_attractive \\<subseteq> dual: complete_attractive \"(\\<sqsubseteq>)\\<^sup>-\" ..\n\nsublocale complete_antisymmetric \\<subseteq> dual: complete_antisymmetric \"(\\<sqsubseteq>)\\<^sup>-\" ..\n\nsublocale complete_pseudo_order \\<subseteq> dual: complete_pseudo_order \"(\\<sqsubseteq>)\\<^sup>-\" ..\n\nsublocale complete_partial_order \\<subseteq> dual: complete_partial_order \"(\\<sqsubseteq>)\\<^sup>-\" ..\n\ntext \\<open>Now we show that bounded completeness is the dual of semicompleteness.\\<close>\n\ncontext fixes less_eq :: \"'a \\<Rightarrow> 'a \\<Rightarrow> bool\" (infix \"\\<sqsubseteq>\" 50)\nbegin\n\ninterpretation less_eq_dualize.\n\ndefinition \"bounded_complete \\<equiv> \\<forall>X. Ex (bound (\\<sqsubseteq>) X) \\<longrightarrow> Ex (extreme_bound (\\<sqsubseteq>) X)\"\n\nlemma pointed_conditionally_complete_iff_bounded_complete:\n  \"conditionally_complete (\\<sqsubseteq>) \\<and> bounded (\\<sqsupseteq>) \\<longleftrightarrow> bounded_complete\"\nproof safe\n  assume \"bounded_complete\"\n  note * = this[unfolded bounded_complete_def, rule_format]\n  from * show \"conditionally_complete (\\<sqsubseteq>)\" by (unfold_locales, auto)\n  from *[of \"{}\"] show \"bounded (\\<sqsupseteq>)\" by (unfold_locales, auto simp:bound_empty)\nnext\n  assume \"conditionally_complete (\\<sqsubseteq>)\" and \"bounded (\\<sqsupseteq>)\"\n  then interpret conditionally_complete \"(\\<sqsubseteq>)\" + dual: bounded \"(\\<sqsupseteq>)\".\n  show \"bounded_complete\" unfolding bounded_complete_def\n  proof (intro allI impI)\n    fix X\n    assume X: \"Ex (bound (\\<sqsubseteq>) X)\"\n    show \"Ex (extreme_bound (\\<sqsubseteq>) X)\"\n    proof (cases \"X = {}\")\n    case True\n    then show ?thesis by auto\n    next\n      case False\n      with bounded_nonempty_complete X show ?thesis by auto\n    qed\n  qed\nqed\n\nproposition bounded_complete_iff_dual_semicomplete:\n  \"bounded_complete \\<longleftrightarrow> semicomplete (\\<sqsupseteq>)\"\nproof (fold pointed_conditionally_complete_iff_bounded_complete, safe)\n  assume \"conditionally_complete (\\<sqsubseteq>)\" and \"bounded (\\<sqsupseteq>)\"\n  then interpret conditionally_complete + bounded \"(\\<sqsupseteq>)\".\n  from dual.conditionally_complete_axioms bounded_axioms\n    semicomplete_iff_conditionally_complete_bounded\n  show \"semicomplete (\\<sqsupseteq>)\" by auto\nnext\n  assume \"semicomplete (\\<sqsupseteq>)\"\n  then interpret semicomplete \"(\\<sqsupseteq>)\".\n  show \"conditionally_complete (\\<sqsubseteq>)\" ..\n  show \"bounded (\\<sqsupseteq>)\" ..\nqed\n\nend\n\n\nsubsection \\<open>Completeness in Function Spaces\\<close>\n\ntext \\<open>Here we lift completeness to functions. As we do not assume an operator to choose suprema,\nwe need the axiom of choice for most of the following results. In antisymmetric cases we do not\nneed the axiom but we do not formalize this fact.\\<close>\n\nlemma (in bounded) bounded_fun[intro!]: \"bounded (fun_ord (\\<sqsubseteq>))\"\nproof-\n  from bounded obtain t where \"\\<forall>x. x \\<sqsubseteq> t\" by auto\n  then have \"\\<forall>f. fun_ord (\\<sqsubseteq>) f (\\<lambda>x. t)\" by (auto intro: fun_ordI)\n  then show ?thesis by (auto intro: bounded.intro)\nqed\n\nlemma (in pair_complete) pair_complete_fun[intro!]:\n  \"pair_complete (fun_ord (\\<sqsubseteq>) :: ('i \\<Rightarrow> _) \\<Rightarrow> _)\"\nproof\n  fix f g :: \"'i \\<Rightarrow> _\"\n  from pair_complete have \"\\<forall>x. \\<exists>sx. extreme_bound (\\<sqsubseteq>) {f x, g x} sx\" by auto\n  from choice[OF this]\n  obtain s where \"\\<forall>x. extreme_bound (\\<sqsubseteq>) {f x, g x} (s x)\" by auto\n  then show \"Ex (extreme_bound (fun_ord (\\<sqsubseteq>)) {f, g})\"\n    by (unfold fun_extreme_bound_iff, intro exI[of _ s], auto 1 4)\nqed\n\nlemma (in finite_complete) finite_complete_fun[intro!]:\n  \"finite_complete (fun_ord (\\<sqsubseteq>) :: ('i \\<Rightarrow> 'a) \\<Rightarrow> _)\"\nproof\n  fix F :: \"('i \\<Rightarrow> 'a) set\"\n  assume \"finite F\" and \"F \\<noteq> {}\"\n  with finite_nonempty_complete\n  have \"\\<forall>x. \\<exists>sx. extreme_bound (\\<sqsubseteq>) {f x |. f \\<in> F} sx\" by auto\n  from choice[OF this]\n  show \"Ex (extreme_bound (fun_ord (\\<sqsubseteq>)) F)\" by (unfold fun_extreme_bound_iff, auto)\nqed\n\nlemma (in omega_complete) omega_complete_fun[intro!]:\n  \"omega_complete (fun_ord (\\<sqsubseteq>) :: ('i \\<Rightarrow> 'a) \\<Rightarrow> _)\"\nproof\n  fix ff :: \"nat \\<Rightarrow> 'i \\<Rightarrow> 'a\"\n  assume ff: \"monotone (\\<le>) (fun_ord (\\<sqsubseteq>)) ff\"\n  then have \"\\<forall>i. Ex (extreme_bound (\\<sqsubseteq>) {ff n i |. n})\"\n    by (intro allI monotone_seq_complete, auto simp: monotone_def fun_ord_def)\n  from choice[OF this]\n  obtain s where \"\\<forall>i. extreme_bound (\\<sqsubseteq>) {ff n i |. n} (s i)\" by auto\n  then have \"extreme_bound (fun_ord (\\<sqsubseteq>)) (range ff) s\"\n    by (auto simp: fun_extreme_bound_iff image_image)\n  then show \"Ex (extreme_bound (fun_ord (\\<sqsubseteq>)) (range ff))\" by auto\nqed\n\nlemma (in chain_complete) chain_complete_fun[intro!]:\n  \"chain_complete (fun_ord (\\<sqsubseteq>) :: ('i \\<Rightarrow> 'a) \\<Rightarrow> _)\"\nproof\n  fix F :: \"('i \\<Rightarrow> 'a) set\"\n  assume F: \"chain (fun_ord (\\<sqsubseteq>)) F\" and \"F \\<noteq> {}\"\n  then have \"\\<forall>i. Ex (extreme_bound (\\<sqsubseteq>) {f i |. f \\<in> F})\"\n    by (intro allI chain_nonempty_complete, auto simp: chain_def fun_ord_def)\n  from choice[OF this]\n  obtain s where \"\\<forall>i. extreme_bound (\\<sqsubseteq>) {f i |. f \\<in> F} (s i)\" by auto\n  then show \"Ex (extreme_bound (fun_ord (\\<sqsubseteq>)) F)\" by (auto simp: fun_extreme_bound_iff)\nqed\n\nlemma (in directed_complete) directed_complete_fun[intro!]:\n  \"directed_complete (fun_ord (\\<sqsubseteq>) :: ('i \\<Rightarrow> 'a) \\<Rightarrow> _)\"\nproof\n  fix F :: \"('i \\<Rightarrow> 'a) set\"\n  assume dir: \"directed (fun_ord (\\<sqsubseteq>)) F\" and F0: \"F \\<noteq> {}\"\n  have \"\\<forall>i. Ex (extreme_bound (\\<sqsubseteq>) {f i |. f \\<in> F})\"\n  proof (intro allI directed_nonempty_complete directedI, safe)\n    fix i f g assume \"f \\<in> F\" \"g \\<in> F\"\n    with dir obtain h\n      where h: \"h \\<in> F\" and \"fun_ord (\\<sqsubseteq>) f h\" and \"fun_ord (\\<sqsubseteq>) g h\" by (auto elim:directedE)\n    then have \"f i \\<sqsubseteq> h i\" and \"g i \\<sqsubseteq> h i\" by (auto dest: fun_ordD)\n    with h show \"\\<exists>hi\\<in>{f i |. f \\<in> F}. f i \\<sqsubseteq> hi \\<and> g i \\<sqsubseteq> hi\" by (intro bexI[of _ \"h i\"], auto)\n  qed (insert F0, auto)\n  from choice[OF this]\n  obtain s where \"\\<forall>i. extreme_bound (\\<sqsubseteq>) {f i |. f \\<in> F} (s i)\" by auto\n  then show \"Ex (extreme_bound (fun_ord (\\<sqsubseteq>)) F)\" by (auto simp: fun_extreme_bound_iff)\nqed\n\nlemma (in conditionally_complete) conditionally_complete_fun[intro!]:\n  \"conditionally_complete (fun_ord (\\<sqsubseteq>) :: ('i \\<Rightarrow> 'a) \\<Rightarrow> _)\"\nproof\n  fix F :: \"('i \\<Rightarrow> 'a) set\"\n  assume bF: \"Ex (bound (fun_ord (\\<sqsubseteq>)) F)\" and F: \"F \\<noteq> {}\"\n  from bF obtain b where b: \"bound (fun_ord (\\<sqsubseteq>)) F b\" by auto\n  have \"\\<forall>x. \\<exists>sx. extreme_bound (\\<sqsubseteq>) {f x |. f \\<in> F} sx\"\n  proof\n    fix x\n    from b have \"bound (\\<sqsubseteq>) {f x |. f \\<in> F} (b x)\" by (auto simp: fun_ord_def)\n    with bounded_nonempty_complete F\n    show \"Ex (extreme_bound (\\<sqsubseteq>) {f x |. f \\<in> F})\" by auto\n  qed\n  from choice[OF this]\n  show \"Ex (extreme_bound (fun_ord (\\<sqsubseteq>)) F)\" by (unfold fun_extreme_bound_iff, auto)\nqed\n\nlemma (in semicomplete) semicomplete_fun[intro!]: \"semicomplete (fun_ord (\\<sqsubseteq>))\"\n  by (auto simp: semicomplete_iff_conditionally_complete_bounded)\n\nlemma (in pointed_chain_complete) pointed_chain_complete_fun[intro!]:\n  \"pointed_chain_complete (fun_ord (\\<sqsubseteq>))\"\n  by (auto intro!: pointed_chain_complete.intro simp: dual_fun_ord)\n\nlemma (in pointed_directed_complete) pointed_directed_complete_fun[intro!]:\n  \"pointed_directed_complete (fun_ord (\\<sqsubseteq>))\"\n  by (auto intro!: pointed_directed_complete.intro simp: dual_fun_ord)\n\nlemma (in complete) complete_fun[intro!]: \"complete (fun_ord (\\<sqsubseteq>))\"\n  by (auto simp: complete_iff_pointed_semicomplete dual_fun_ord)\n\nsubsection \\<open>Interpretations\\<close>\n\ncontext complete_lattice begin\n\nlemma Sup_eq_The_supremum: \"Sup X = The (supremum X)\"\n  using order.complete[unfolded order.dual.ex_extreme_iff_ex1]\n  by (rule the1_equality[symmetric], auto intro!: Sup_upper Sup_least)\n\nlemma Inf_eq_The_infimum: \"Inf X = The (infimum X)\"\n  using order.dual.complete[unfolded order.ex_extreme_iff_ex1]\n  by (rule the1_equality[symmetric], auto intro!: Inf_lower Inf_greatest)\n\nend\n\ninstance real :: ccomplete by (intro_classes, unfold_locales)\n\ninstance \"fun\" :: (type, ccomplete) ccomplete by (intro_classes, fold fun_ord_le, auto)\n\ninstance \"fun\" :: (type, complete_ord) complete_ord by (intro_classes, fold fun_ord_le, 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/Complete_Non_Orders/Complete_Relations.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8824278788223265, "lm_q2_score": 0.8267117855317474, "lm_q1q2_score": 0.729513527304198}}
{"text": "(* From Isabelle exercsises http://isabelle.in.tum.de/exercises/ *)\ntheory TreeTraversal\nimports \"$HIPSTER_HOME/IsaHipster\"\n\nbegin\n\n\ndatatype 'a Tree = \n  Tip 'a \n  | Node 'a  \"'a Tree\" \"'a Tree\"\n\nfun preOrder :: \"'a Tree \\<Rightarrow> 'a list\" where\n  \"preOrder (Tip a)      = [a]\"\n| \"preOrder (Node a l r) = a#((preOrder l)@(preOrder r))\"\n\nfun postOrder :: \"'a Tree  \\<Rightarrow>  'a list\" where\n  \"postOrder (Tip a)      = [a]\"\n| \"postOrder (Node a l r) = (postOrder l)@(postOrder r)@[a]\"\n\nfun inOrder :: \"'a Tree  \\<Rightarrow> 'a list\" where\n  \"inOrder (Tip a)      = [a]\"\n| \"inOrder (Node a l r) = (inOrder l)@[a]@(inOrder r)\"\n\nfun mirror :: \"'a Tree => 'a Tree\"\nwhere\n  \"mirror (Tip x) = Tip x\"\n| \"mirror (Node a l r) = Node a (mirror r) (mirror l)\"\n\nhipster mirror rev preOrder postOrder inOrder\nlemma lemma_a [thy_expl]: \"mirror (mirror y) = y\"\n  apply (induct y)\n  apply simp\n  apply simp\n  done\n    \nlemma lemma_aa [thy_expl]: \"rev (inOrder y) = inOrder (mirror y)\"\n  apply (induct y)\n  apply simp\n  apply simp\n  done\n    \nlemma lemma_ab [thy_expl]: \"rev (postOrder y) = preOrder (mirror y)\"\n  apply (induct y)\n  apply simp\n  apply simp\n  done\n\nfun root :: \"'a Tree \\<Rightarrow> 'a\" where\n  \"root (Tip a)      = a\"\n| \"root (Node f x y) = f\"\n\nfun leftmost :: \"'a Tree \\<Rightarrow> 'a\" where\n  \"leftmost (Tip a)      = a\"\n| \"leftmost (Node f x y) = (leftmost x)\"\n\nfun rightmost :: \"'a Tree \\<Rightarrow> 'a\" where\n  \"rightmost (Tip a)      = a\"\n| \"rightmost (Node f x y) = (rightmost y)\"\n\n  setup Tactic_Data.set_induct_sledgehammer \nhipster root hd last leftmost rightmost inOrder\nlemma lemma_ac [thy_expl]: \"last (inOrder y) = rightmost y\"\n  apply (induct y)\n  apply simp\n  apply simp\n  apply (metis append_is_Nil_conv inOrder.simps(1) inOrder.simps(2) rightmost.elims snoc_eq_iff_butlast)\n  done\n    \nlemma lemma_ad [thy_expl]: \"hd (inOrder z @ y) = leftmost z\"\n  apply (induct z arbitrary: y)\n  apply simp\n  apply simp\n  done\n    \nlemma lemma_ae [thy_expl]: \"last (y @ inOrder z) = rightmost z\"\n  apply (induct y arbitrary: z)\n  apply simp\n  apply (simp add: TreeTraversal.lemma_ac)\n  apply simp\n  apply (metis append_is_Nil_conv inOrder.simps(1) inOrder.simps(2) list.simps(3) rightmost.elims)\n  done\n(*   \n\n(* \nWith this tactic, we don't use Sledgehammer in the \"Easy tactic\", so we get more results.\n*) \nsetup Tactic_Data.set_sledge_induct_sledge\nhipster root hd last leftmost rightmost inOrder\n\n \nlemma lemma_ac [thy_expl]: \"hd (inOrder y) = leftmost y\"\n  apply (induct y)\napply simp\napply simp\napply (metis append_is_Nil_conv hd_append2 inOrder.simps(1) inOrder.simps(2) leftmost.elims self_append_conv2 snoc_eq_iff_butlast)\ndone\n\nlemma lemma_ad [thy_expl]: \"last (inOrder y) = rightmost y\"\napply (induct y)\n  apply simp\n  apply simp\napply (metis append_is_Nil_conv inOrder.simps(1) inOrder.simps(2) rightmost.elims snoc_eq_iff_butlast)\ndone\n\nlemma lemma_ae [thy_expl]: \"hd (inOrder z @ y) = leftmost z\"\napply (metis (no_types, lifting) TreeTraversal.lemma_ac append_is_Nil_conv hd_append2 inOrder.simps(1) inOrder.simps(2) leftmost.elims snoc_eq_iff_butlast)\ndone\n\nlemma lemma_af [thy_expl]: \"last (y @ inOrder z) = rightmost z\"\napply (induct y arbitrary: z)\napply simp\napply (simp add: lemma_ad)\napply simp\napply (metis append_is_Nil_conv inOrder.simps(1) inOrder.simps(2) list.simps(3) rightmost.elims)\ndone \n*)\n\n\n", "meta": {"author": "moajohansson", "repo": "IsaHipster", "sha": "91f6ea3f1166a9de547722ece6445fe843ad89b4", "save_path": "github-repos/isabelle/moajohansson-IsaHipster", "path": "github-repos/isabelle/moajohansson-IsaHipster/IsaHipster-91f6ea3f1166a9de547722ece6445fe843ad89b4/Examples/TreeTraversal.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.88242786954645, "lm_q2_score": 0.8267117919359419, "lm_q1q2_score": 0.7295135252869613}}
{"text": "theory More_Lattices_Big\n  imports Main\nbegin\n\n\nlemma ex_max_if_finite:\n  \"\\<lbrakk> finite S; S \\<noteq> {} \\<rbrakk> \\<Longrightarrow> \\<exists>m\\<in>S. \\<not>(\\<exists>x\\<in>S. (m::'a::order) < x)\"\n  by (induction rule: finite.induct)\n     (auto intro: order.strict_trans)\n\nlemma ex_is_arg_max_if_finite: fixes f :: \"'a \\<Rightarrow> 'b :: order\"\n  shows \"\\<lbrakk> finite S; S \\<noteq> {} \\<rbrakk> \\<Longrightarrow> \\<exists>x. is_arg_max f (\\<lambda>x. x \\<in> S) x\"\n  unfolding is_arg_max_def\n  using ex_max_if_finite[of \"f ` S\"]\n  by auto\n\nlemma arg_max_SOME_Max:\n  \"finite S \\<Longrightarrow> arg_max_on f S = (SOME y. y \\<in> S \\<and> f y = Max (f ` S))\"\n  unfolding arg_max_on_def arg_max_def is_arg_max_linorder\n  by (auto intro!: arg_cong[where f = Eps] Max_eqI[symmetric] simp: fun_eq_iff)\n\nlemma arg_max_if_finite: fixes f :: \"'a \\<Rightarrow> 'b :: order\"\n  assumes \"finite S\" \"S \\<noteq> {}\"\n  shows \"arg_max_on f S \\<in> S\" and \"\\<not>(\\<exists>x\\<in>S. f (arg_max_on f S) < f x)\"\n  using ex_is_arg_max_if_finite[OF assms, of f]\n  unfolding arg_max_on_def arg_max_def is_arg_max_def\n  by (auto dest!: someI_ex)\n\nlemma arg_max_greatest: fixes f :: \"'a \\<Rightarrow> 'b :: linorder\"\n  shows \"\\<lbrakk> finite S; y \\<in> S \\<rbrakk> \\<Longrightarrow> f y \\<le> f (arg_max_on f S)\"\nproof -\n  assume \"finite S\" \"y \\<in> S\"\n  then have \"S \\<noteq> {}\"\n    by blast\n\n  from \\<open>y \\<in> S\\<close> show ?thesis\n    using arg_max_if_finite[OF \\<open>finite S\\<close> \\<open>S \\<noteq> {}\\<close>]\n    by (auto intro: leI)\nqed\n\nend", "meta": {"author": "cmadlener", "repo": "isabelle-online-matching-primal-dual", "sha": "a200eb7aa09f04b96d55b6f0f5ddedfdd239026a", "save_path": "github-repos/isabelle/cmadlener-isabelle-online-matching-primal-dual", "path": "github-repos/isabelle/cmadlener-isabelle-online-matching-primal-dual/isabelle-online-matching-primal-dual-a200eb7aa09f04b96d55b6f0f5ddedfdd239026a/More_Lattices_Big.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045817875225, "lm_q2_score": 0.8221891239865619, "lm_q1q2_score": 0.729449957896747}}
{"text": "(*  Title:      HOL/ex/BT.thy\n    Author:     Lawrence C Paulson, Cambridge University Computer Laboratory\n    Copyright   1995  University of Cambridge\n\nBinary trees\n*)\n\nsection {* Binary trees *}\n\ntheory BT imports Main begin\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 {* \\medskip BT simplification *}\n\nlemma n_leaves_reflect: \"n_leaves (reflect t) = n_leaves t\"\n  apply (induct t)\n   apply auto\n  done\n\nlemma n_nodes_reflect: \"n_nodes (reflect t) = n_nodes t\"\n  apply (induct t)\n   apply auto\n  done\n\nlemma depth_reflect: \"depth (reflect t) = depth t\"\n  apply (induct t) \n   apply auto\n  done\n\ntext {*\n  The famous relationship between the numbers of leaves and nodes.\n*}\n\nlemma n_leaves_nodes: \"n_leaves t = Suc (n_nodes t)\"\n  apply (induct t)\n   apply auto\n  done\n\nlemma reflect_reflect_ident: \"reflect (reflect t) = t\"\n  apply (induct t)\n   apply auto\n  done\n\nlemma bt_map_reflect: \"bt_map f (reflect t) = reflect (bt_map f t)\"\n  apply (induct t)\n   apply simp_all\n  done\n\nlemma preorder_bt_map: \"preorder (bt_map f t) = map f (preorder t)\"\n  apply (induct t)\n   apply simp_all\n  done\n\nlemma inorder_bt_map: \"inorder (bt_map f t) = map f (inorder t)\"\n  apply (induct t)\n   apply simp_all\n  done\n\nlemma postorder_bt_map: \"postorder (bt_map f t) = map f (postorder t)\"\n  apply (induct t)\n   apply simp_all\n  done\n\nlemma depth_bt_map [simp]: \"depth (bt_map f t) = depth t\"\n  apply (induct t)\n   apply simp_all\n  done\n\nlemma n_leaves_bt_map [simp]: \"n_leaves (bt_map f t) = n_leaves t\"\n  apply (induct t)\n   apply (simp_all add: distrib_right)\n  done\n\nlemma preorder_reflect: \"preorder (reflect t) = rev (postorder t)\"\n  apply (induct t)\n   apply simp_all\n  done\n\nlemma inorder_reflect: \"inorder (reflect t) = rev (inorder t)\"\n  apply (induct t)\n   apply simp_all\n  done\n\nlemma postorder_reflect: \"postorder (reflect t) = rev (preorder t)\"\n  apply (induct t)\n   apply simp_all\n  done\n\ntext {*\n Analogues of the standard properties of the append function for lists.\n*}\n\nlemma append_assoc [simp]:\n     \"append (append t1 t2) t3 = append t1 (append t2 t3)\"\n  apply (induct t1)\n   apply simp_all\n  done\n\nlemma append_Lf2 [simp]: \"append t Lf = t\"\n  apply (induct t)\n   apply simp_all\n  done\n\nlemma depth_append [simp]: \"depth (append t1 t2) = depth t1 + depth t2\"\n  apply (induct t1)\n   apply (simp_all add: max_add_distrib_left)\n  done\n\nlemma n_leaves_append [simp]:\n     \"n_leaves (append t1 t2) = n_leaves t1 * n_leaves t2\"\n  apply (induct t1)\n   apply (simp_all add: distrib_right)\n  done\n\nlemma bt_map_append:\n     \"bt_map f (append t1 t2) = append (bt_map f t1) (bt_map f t2)\"\n  apply (induct t1)\n   apply simp_all\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/HOL/ex/BT.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.877476800298183, "lm_q2_score": 0.8311430415844385, "lm_q1q2_score": 0.7293087367196127}}
{"text": "(* $Id$ *)\n(*<*)\ntheory HEAP1\nimports HEAP0 \nbegin\n(*>*)\nsubsection \\<open> Heap level 1 \\label{s:isa:models:level1}\\<close>\n\ntext\\<open> \n\n Firstly, we define a type type synonym for the state of the free store\n at level 1 to be a map from locations to sizes:\n\\<close>\n\ntype_synonym F1 = \"Loc \\<rightharpoonup> nat\"\n\nsubsubsection\\<open> Auxillary functions \\label{s:isa:models:level1:aux} \\<close>\n\ntext\\<open>\nNote that the size is only @{type nat} here so, as mentioned earlier, we must extend the \n@{const nat1} predicate to operate on maps and sets to ensure that the model is consistent\nwith VDM:\n\\<close>\n\ndefinition \n  nat1_map :: \"F1 \\<Rightarrow> bool\"\nwhere\n  \"nat1_map f \\<equiv> (\\<forall> x. x \\<in> dom f \\<longrightarrow> nat1 (the (f x)))\"\n\ndefinition\n  nat1_set :: \"(nat set) \\<Rightarrow> bool\"\nwhere\n  \"nat1_set S \\<equiv> (\\<forall> x. x \\<in> S \\<longrightarrow> nat1 x)\"\n\ntext\\<open> \nThe level 1 model introduces a new auxiliary function, \\emph{locs}\nthat returns the set of all free locations withing a given map. We define the \\emph{locs} \nfunction using a union over the elements in the domain of the VDM map. \nIt is wrapped inside a conditional expression, however,\nin order to ensure that the map is appropriately a @{text nat1_map}:\n\\<close>\n\ndefinition \n  locs :: \"(Loc \\<rightharpoonup> nat) \\<Rightarrow> Loc set \"\nwhere\n  \"locs sm \\<equiv> (if nat1_map sm then \n                \\<Union> s \\<in> dom sm. locs_of s (the (sm s)) \n               else \n                 undefined)\" (* TODO: or {}?*)\n\ntext\\<open> \n  It is otherwise @{term undefined}, which is a polymorphic constant in Isabelle.\n  That is, the VDM model uses a total map to @{text \"\\<nat>\\<^sub>1\"}, whereas here we can only\n  use a map to @{text \"\\<nat>\"} as a parameter. Thus, we totalise the definition of @{term locs}\n  by giving it a bottom element (as Isabelle's @{term undefined}) when the expected type fails. \n  \n  It is important to emphasise this is not VDM's notion of undefinedness. For instance, it is\n  possible to prove that @{lemma \"undefined=undefined\" by simp} in Isabelle, which is not true \n  in VDM's three-valued logic. Thus, @{term undefined} should never feature in our proofs. If it\n  does, it means we made some mistake somewhere by applying a function to the wrong type. For \n  further discussion on the subtleties of handling partial functions, see \n \\cite{Jones95e,SchmalzPhD}.\n\\<close>\n\nsubsubsection\\<open> Invariant \\<close>\ntext\\<open>\n\\noindent Recall the level 1 invariant in Section~\\ref{S-model-pp-l1}:\n\n\n\\begin{vdm}\n\\rtype{Free1}{\\mapof{Loc}{\\Nati}}{\n      (f) \\DeF \\\\\n\\forall*{l, l' \\in \\dom{f}}{l \\neq l' \\Implies is-disj(locs-of(l, f(l)), locs-of(l', f(l'))) \\And} \\\\\n\\forall{l \\in \\dom{f}}{(l + f(l) ) \\notin \\dom{f}}\n}\n\\end{vdm}\n\nIt contains two components (a conjunction):\n\\begin{itemize}\n\\item \\emph{Disjoint}: that the locations defined by each element in the \nmap are disjoint;\n\\item and, \\emph{sep}: that the locations defined by elements do not\nabut on any end.\n\\end{itemize}\n\n\\noindent We encode these as individual definitions in Isabelle: \\<close>\n(*<*)\ndefinition\n  Locs_of :: \"F1 \\<Rightarrow> Loc \\<Rightarrow> (Loc set)\"\nwhere\n  \"Locs_of f l \\<equiv> (if (l \\<in> dom f) then \n                    locs_of l (the (f l))\n                  else\n                    undefined)\"  (* TODO: or {}? *)\n\ndefinition \n  disjoint :: \"'a set \\<Rightarrow> 'a set \\<Rightarrow> bool\"\nwhere\n \"disjoint A B \\<equiv> A \\<inter> B = {}\"\n(*>*)\n\ndefinition \n  Disjoint :: \"F1 \\<Rightarrow> bool\"\nwhere\n \"Disjoint f \\<equiv> \n      (\\<forall> a \\<in> dom f. \\<forall> b \\<in> dom f . a \\<noteq> b \\<longrightarrow> disjoint (Locs_of f a) (Locs_of f b))\"\n\ndefinition \n  sep :: \"F1 \\<Rightarrow> bool\" \nwhere\n  \"sep f \\<equiv> (\\<forall> l \\<in> dom f . l + the(f l) \\<notin> dom f)\"\n\ntext\\<open>\n\\noindent where @{term \"disjoint A B\"} is the same as @{term \"A \\<inter> B = \\<emptyset>\"}, and \n@{term \"Locs_of f a\"} is the same as @{term \"locs_of a (the(f a))\"}.\n\nAlbeit trivial, this decomposition into separate concepts is invaluable in taming\nthe goal complexity during proofs (see discussion in Section~\\ref{S-TP-exp}). They\ncreate what we call ``zoom'' levels of interest/discourse. For instance, we create\nvarious lemmas about these definitions and their relationship with, say @{term locs_of}\nand @{term locs} or set theory and map operators. So, in actual POs, these issues\nof mechanisation are already distilled and resolved.  \n\nWe must also, however, have additional components to the invariant.\nThey are the implicit VDM notion of finiteness of maps and sets, and the\nsubtype checking on map range type for @{text \"\\<nat>\\<^sub>1\"}.\n\n\\begin{itemize}\n\\item \\emph{nat1\\_map}: that the state doesn't contain any \nlocations that map to size 0.\n\\item \\emph{finite domain}: that the domain of the map is finite, similarly to level 0 state.\n\\end{itemize}\n\n\\noindent Thus, the invariant definition is as follows:\n \\<close>\n\ndefinition \n  F1_inv :: \"F1 \\<Rightarrow> bool\" \nwhere\n(*<*)  [intro!]:  (*>*) \"F1_inv f \\<equiv> Disjoint f \\<and> sep f \\<and> nat1_map f \\<and> finite(dom f)\"\n\ndefinition \n  VDM_F1_inv :: \"F1 \\<Rightarrow> bool\" \nwhere\n  \"VDM_F1_inv f \\<equiv> Disjoint f \\<and> sep f \"\n \ntext\\<open>\n\\noindent We also define the VDM invariant, as we may wish to discharge the\nIsabelle parts the invariant first (finiteness etc), as they are often\nsimpler. We provide a lemma to `shape' the goal as such:\n\n%\\plannote{LF: IJW, didn't follow underline above. Isn't it the other way roung? I.e. VDM_F1_inv \n%is harder to prove than the other trivial bits?}\n%IJW: I've reworded this. I agree: I was trying to say the conditions that arise from the translation\n%is simpler.\n\\<close>\nlemma invF1_shape: \"nat1_map f \\<Longrightarrow> finite (dom f) \\<Longrightarrow> VDM_F1_inv f\\<Longrightarrow> F1_inv f\"\nunfolding F1_inv_def VDM_F1_inv_def by simp\n\ntext\\<open>\n\\noindent Such proof decomposition is again essential for automation and proof strategy reuse,\nas it informs (meta-)data collection (see Chapter~\\ref{C-why} on meta-data and \nChapter~\\ref{C-isaproofs} on Isabelle proofs).\n\nFurthermore, we define introduction and elimination rules\nto help unfold the invariant; we also provide weakening rules \nfor the case that only one part of the invariant is required\n(we only show the @{term sep} version here):\n\\<close>\n(*<*)\nlemma invVDMF1[intro!]: \"sep f \\<Longrightarrow> Disjoint f \\<Longrightarrow> VDM_F1_inv f\"\n unfolding VDM_F1_inv_def by simp\n(*>*)\nlemma invF1E[elim!]: \"F1_inv f \\<Longrightarrow> (sep f \\<Longrightarrow> Disjoint f \\<Longrightarrow> nat1_map f \\<Longrightarrow> finite (dom f) \\<Longrightarrow> R) \\<Longrightarrow> R\"\n unfolding F1_inv_def by simp\n\nlemma invF1I[intro!]: \"sep f \\<Longrightarrow> Disjoint f \\<Longrightarrow> nat1_map f \\<Longrightarrow> finite (dom f) \\<Longrightarrow> F1_inv f\"\n unfolding F1_inv_def by simp\n\nlemma invF1_sep_weaken: \"F1_inv f \\<Longrightarrow> sep f\"\n  unfolding F1_inv_def by simp\n(*<*)\nlemma invF1_Disjoint_weaken: \"F1_inv f \\<Longrightarrow> Disjoint f\"\n  unfolding F1_inv_def by simp\n\nlemma invF1_nat1_map_weaken: \"F1_inv f \\<Longrightarrow> nat1_map f\"\n  unfolding F1_inv_def by simp\n\nlemma invF1_finite_weaken: \"F1_inv f \\<Longrightarrow> finite (dom  f)\"\n  unfolding F1_inv_def by simp\n(*>*)\n(*\ntext\\<open> \n  Weakening rules are for both forward and backward reasoning and is part of our armory\n  of proof patterns. \n\n%  \\plannote{LF: I am seeing these comments on proof patterns scattered around various parts of text.\n%  This is okay, yet I am worried reader won't get a cohesive understanding of what they are about.\n%  Perhaps at least a section somewhere summarising them, and a pointer to the other TR/paper? Comments?}\n\\<close>\n*)\n(* More unnecessary stuff *)\n(*<*)\n(*------------------------------------------------------------------------*)\nsubsection \\<open> Alternative definitions \\<close>\n(*------------------------------------------------------------------------*)\n\ndefinition\n  Locs_of2 :: \"F1 \\<Rightarrow> Loc \\<Rightarrow> (Loc set)\"\nwhere\n  \"l \\<in> dom f \\<Longrightarrow> nat1 (the(f l)) \\<Longrightarrow> Locs_of2 f l \\<equiv> locs_of l (the (f l))\"\n\ndefinition \n  Disjoint2 :: \"F1 \\<Rightarrow> bool\"\nwhere\n \"Disjoint2 f \\<equiv> \n      (\\<forall> a \\<in> dom f. \\<forall> b \\<in> dom f . a \\<noteq> b \\<longrightarrow> \n        disjoint (locs_of a (the(f a))) (locs_of b (the(f b))))\"\n\n(*code_type F1(Scala)*)\n\n(*========================================================================*)\nsection \\<open> VDM function definitions \\<close>\n(*========================================================================*)\n(*>*)\n\nsubsubsection\\<open> NEW operation\\<close> \n \ntext\\<open> \nFollowing the style of level 0 in Section~\\ref{s:isa:models:level0}, we create definitions\nfor the pre and post-conditions for the operations. We split \nthe NEW post-condition into two separate definitions, corresponding to each disjunct \nin the VDM operation. Again, this is useful for proof decomposition within POs and also\nto help identify hidden case analysis, another of our proof patterns.\n\\<close>\n\ndefinition \n  new1_pre :: \"F1 \\<Rightarrow> nat \\<Rightarrow> bool\"\nwhere\n  \"new1_pre f s \\<equiv> (\\<exists> l \\<in> dom f . the(f l) \\<ge> s)\"\n\ndefinition\n   new1_post_eq :: \"F1 \\<Rightarrow> nat \\<Rightarrow> F1 \\<Rightarrow> Loc \\<Rightarrow> bool\"\nwhere\n   \"new1_post_eq f s f' r \\<equiv> r \\<in> dom f \\<and> the(f r) = s \\<and> f' = {r} -\\<triangleleft> f\"\n\ndefinition\n   new1_post_gr :: \"F1 \\<Rightarrow> nat \\<Rightarrow> F1 \\<Rightarrow> Loc \\<Rightarrow> bool\"\nwhere\n   \"new1_post_gr f s f' r \\<equiv> r \\<in> dom f \\<and> the(f r) > s \\<and> \n                            f' = ({r} -\\<triangleleft> f) \\<union>m [r + s \\<mapsto> the(f r) - s]\"\n\ndefinition\n   new1_post :: \"F1 \\<Rightarrow> nat \\<Rightarrow> F1 \\<Rightarrow> Loc \\<Rightarrow> bool\"\nwhere\n   \"new1_post f s f' r \\<equiv> new1_post_eq f s f' r \\<or> new1_post_gr f s f' r\"\n\n\nsubsubsection\\<open> DISPOSE operation \\<close>\ntext\\<open>\nBefore showing the locale definitions corresponding to the $DISPOSE1$\noperation, we create auxiliary definitions for dispose. The way these came\nabout is discussed in Section~\\ref{S-TP-exp}. First are the\ntwo auxilliary functions called \\emph{sum\\_size} and \\emph{min\\_loc}\nwhich are used in the postcondition are defined using Isabelle's operators\nfor set minimal and summation, respectively.\n\\<close>\ndefinition\n   min_loc :: \"(Loc \\<rightharpoonup> nat) \\<Rightarrow> nat\"\nwhere\n   \"min_loc sm = (if sm \\<noteq> Map.empty then \n                      Min (dom sm) \n                  else \n                      undefined)\" \n\ndefinition \n  sum_size :: \"(Loc \\<rightharpoonup> nat) \\<Rightarrow> nat\"\nwhere\n  \"sum_size sm = (if sm \\<noteq> Map.empty then \n                      (\\<Sum> x\\<in>(dom sm) . the (sm x)) \n                  else \n                      undefined)\" (*TODO: or 0? *)\ntext\\<open>\nOnce again, we used Isabelle's @{term undefined} to enable a total function over a subtype,\nas we did for @{term locs}.\n\nWe have two versions of the postconditions: the exact translation from \nthe VDM specification and a version where \\emph{above}, \\emph{below}, and \\emph{ext}\nare given as definitions. The latter definition makes proof more straightforward\nsince we can refer to the maps by name and unfold where necessary. We do, of course,\nprove both definitions equivalent. This is another example of zooming:~the use of\ndifferent levels of interest in involved operators, that is based on the problem at hand,\nand is useful in helping proof decomposition and lemma discovery for higher automation.\n\\<close>\ndefinition \n   dispose1_pre :: \"F1 \\<Rightarrow> Loc \\<Rightarrow> nat \\<Rightarrow> bool\"\nwhere\n  \"dispose1_pre f d s \\<equiv> disjoint (locs_of d s) (locs f)\"\n\ndefinition \n   dispose1_post :: \"F1 \\<Rightarrow> Loc \\<Rightarrow> nat \\<Rightarrow> F1 \\<Rightarrow> bool\"\nwhere\n   \"dispose1_post f d s f' \\<equiv> \n      (\\<exists> below above ext . \n        below = { x \\<in> dom f . x + the(f x) = d } \\<triangleleft> f \\<and>\n        above = { x \\<in> dom f . x = d + s } \\<triangleleft> f \\<and>\n        ext   = (above \\<union>m below) \\<union>m [d \\<mapsto> s] \\<and>\n        f' = ((dom below \\<union> dom above) -\\<triangleleft> f) \\<union>m ([min_loc(ext) \\<mapsto> sum_size(ext)]))\n      \"\n\n  \n(*\ntext\\<open> \nAs explained in Section~\\ref{S-TP-exp}, we modelled $DISPOSE1$ postcondition in various ways.\nWhen we came to the Isabelle representation we encountered a few problems because of the VDM\nmodel use of map comprehension for the definition of $DISPOSE1$. In Isabelle, map comprehension\nisn't directly available. Thus, to model @{text below} as in the VDM\n\n\\begin{vdm} \n\\begin{formula}\n    below= \\map{ l \\mapsto f(l) | l \\in \\dom{f} \\And l + ~{f}(l) = d}  \n\\end{formula}\n\\end{vdm}\n\n\\noindent we would need map comprehension in Isabelle. At first we tried something like this\n\n@{term \"map_of [ (x, the(f x)) . x \\<leftarrow> sorted_list_of_set (dom f), l + (the(fhook x)) = d]\"}\n\nAlthough it does represent the map comprehension we need, it is rather protracted, \nunecessarily complates proof, as well as automation. That is because of the many type jumps\nbetween generator as a set (@{term \"dom f\"}) that gets transformed into a list for the list\ncomprehension term that is given to a recursive function (@{term \"map_of\"}), which translates\na given list to an Isabelle map. \n\nThis\\footnote{And also discussion/suggestions within/from the Isabelle users mailing list} led\nus to rethink the definition using available operators and avoiding map comprehension leading to\nthe current VDM as \n\n\\begin{vdm} \n\\begin{formula}\n    below= \\set{ l | l \\in \\dom{f} \\And l + ~{f}(l) = d} \\dsub f  \n\\end{formula}\n\\end{vdm}\n\n\\noindent It avoid map comprehension and uses domain filtering (or restriction), \nwhich was easier to encode in Isabelle as: \n\\<close>     \n*)\ntext\\<open>\nIn our alternative formulation, the three existential variables are given as definitions, for example:\n\\<close>\ndefinition \n  dispose1_below :: \"F1 \\<Rightarrow> Loc \\<Rightarrow> F1\"\nwhere\n  \"dispose1_below f d \\<equiv>  { x \\<in> dom f . x + the(f x) = d } \\<triangleleft> f\" \n\ntext\\<open>\n \\noindent These encoding considerations are crucial to ensure proofs are not complicated by\n technicalities unrelated to the problem. One must not, however, fall for the temptation to \n chisel the model into whatever the theorem prover would be happier with. Our modification \n is clearly equivalent, and can be proved as such if that's the case, we we have done for the\n layered definition of dispose with respect to the original one.\n\n% \\plannote{LF: Should we prove the map comprehension version equals the one with domain restriction?}\n% Shouldn't mention it.\n\nThe other two definitions are:\n\\<close>\n\ndefinition \n  dispose1_above :: \"F1 \\<Rightarrow> Loc \\<Rightarrow> nat \\<Rightarrow> F1\"\nwhere\n  \"dispose1_above f d s \\<equiv>  { x \\<in> dom f . x = d + s } \\<triangleleft> f\" \n\ndefinition \n  dispose1_ext :: \"F1 \\<Rightarrow> Loc \\<Rightarrow> nat \\<Rightarrow> F1\"\nwhere\n  \"dispose1_ext f d s \\<equiv>  (dispose1_above f d s  \\<union>m dispose1_below f d) \\<union>m [d \\<mapsto> s] \"\n\ntext\\<open>\n\\noindent which allows us to write and prove:\n\\<close>\ndefinition \n   dispose1_post2 :: \"F1 \\<Rightarrow> Loc \\<Rightarrow> nat \\<Rightarrow> F1 \\<Rightarrow> bool\"\nwhere\n   \"dispose1_post2 f d s f' \\<equiv> \n        (f' = ((dom (dispose1_below f d) \\<union> dom (dispose1_above f d s)) -\\<triangleleft> f) \n        \\<union>m ([min_loc(dispose1_ext f d s) \\<mapsto> sum_size(dispose1_ext f d s)]))\"\n                  \n(*<*)\nlemmas F1_inv_defs = F1_inv_def Disjoint_def nat1_def\n                     Locs_of_def sep_def nat1_map_def\n                        disjoint_def locs_of_def\n\nlemmas new1_pre_defs      = new1_pre_def \nlemmas new1_post_defs     = new1_post_def new1_post_eq_def new1_post_gr_def\nlemmas dispose1_pre_defs  = dispose1_pre_def disjoint_def nat1_def\n                            locs_def nat1_map_def locs_of_def\nlemmas dispose1_post_defs = dispose1_post_def \n\nlemmas dispose1_post2_defs = dispose1_post2_def dispose1_below_def \n\t\t\t\t\t\t\t dispose1_above_def dispose1_ext_def\n(*>*)\n\nlemma dispose1_equiv:\n\t\"dispose1_post f d s f' = dispose1_post2 f d s f'\"\nunfolding dispose1_post_defs dispose1_post2_defs\nby auto\n\n\n(*========================================================================*)\nsubsubsection \\<open> VDM operation definitions and feasibility goals \\<close>\n(*========================================================================*)\n\ntext\\<open>\nFinally, we put everything together in locales and construct definitions\nrelating to the feasibility proofs. As with level 1, we encode the shared inputs,\nstate, assumptions and invariant in a separate locale:\n\\<close>\nlocale level1_basic =\n   fixes f1 :: F1 (* State  0 \\<mapsto> 12, 12 \\<mapsto> 4 *)\n   and   s1 :: nat (* Size!!! *)\n  assumes l1_input_notempty_def: \"nat1 s1\" (* Type info *)\n   and    l1_invariant_def     : \"F1_inv f1\" (* Invariant on initial state *)\n\ntext\\<open>\nThe individual operations are then specified as localte extensions and the post-conditions\nare given as definitions within the locale:\n\n\\<close>\n\nlocale level1_new = level1_basic +\n   assumes l1_new1_precondition_def: \"new1_pre f1 s1\"\n\nlocale level1_dispose = level1_basic +\n    fixes d1 :: Loc\n   assumes l1_dispose1_precondition_def: \"dispose1_pre f1 d1 s1\"\n\ndefinition (in level1_new)\n  new1_postcondition :: \"F1 \\<Rightarrow> nat \\<Rightarrow> bool\"\nwhere\n  \"new1_postcondition f' r \\<equiv> new1_post f1 s1 f' r \\<and> F1_inv f'\"\n\ndefinition (in level1_dispose)\n  dispose1_postcondition :: \"F1 \\<Rightarrow> bool\"\nwhere\n  \"dispose1_postcondition f' \\<equiv> dispose1_post f1 d1 s1 f' \\<and> F1_inv f'\"\n\ndefinition (in level1_dispose)\n  dispose1_postconditionpsg :: \"F1 \\<Rightarrow> bool\"\nwhere\n  \"dispose1_postconditionpsg f' \\<equiv> dispose1_post2 f1 d1 s1 f' \\<and> F1_inv f'\"\n\n(*<*)\nlocale level1_complete = level1_new + level1_dispose\n\n(*========================================================================*)\nsection \\<open> VDM proof obligations for level 1 \\<close>\n(*========================================================================*)\n(*>*)\n\ntext\\<open>\nAs in level 0, the feasibility proof operations are encoded as definitions as follows:\n\\<close>\ndefinition (in level1_new)\n  PO_new1_feasibility :: \"bool\"\nwhere\n  \"PO_new1_feasibility \\<equiv> (\\<exists> f' r' . new1_postcondition f' r')\"\n\ndefinition (in level1_dispose)\n  PO_dispose1_feasibility :: \"bool\"\nwhere\n  \"PO_dispose1_feasibility \\<equiv> (\\<exists> f' . dispose1_postcondition f')\"\n\ndefinition (in level1_dispose)\n  PO_dispose1_feasibilitypsg :: \"bool\"\nwhere\n  \"PO_dispose1_feasibilitypsg \\<equiv> (\\<exists> f' . dispose1_postconditionpsg f')\"\n\n\n\nsubsection\\<open> Summary \\label{s:isa:models:summary} \\<close>\n\ntext\\<open>\nThe translation from VDM to Isabelle is relatively straightforward and faithful to the \noriginal model. Operations in VDM have a fairly natural translation to Isabelle's locale\nmodule system, where definitions can be used for the post-condition. It is future work to build\na VDM package on top of Isabelle that would enable a syntactic emulation of VDM operations, thus\nreducing the chance of a human error in the translation (we, for example, forgot the invariant \non our first iteration). \n%\nWhile our strategy of packaging up preconditions, postconditions, and the invariants in \ndefinitions makes for additional proof steps, it ensures a comparmentalised proof and constructs\nexplicit `zoom' levels to have a clear domain of discourse.\n%\nAdditionally, our naming scheme makes it relatively straightforward to pick a definition `from the\nair' and have it be the right one, an oft overlooked but crucial requirement when models become \nlarge.\n%\n%\nThe next section details the Isabelle proofs of the proof obligations for the above model, \nincluding:\n\\begin{itemize}\n\\item Feasibility proofs for both operations for both levels;\n\\item Adaquecy proof for the reification;\n\\item Widen-precondition for both operations;\n\\item Narrow-postcondition for both operations;\n\\item Sanity proofs that state that, for example, $\\mathit{DISPOSE(NEW) = Id}$.\n\\end{itemize}\n\\<close>\n\n\n(*<*)\n(* EXAMPLE HERE!!! *)\n\ndefinition \n  PO_new1_fsb :: \"bool\"\nwhere\n  \"PO_new1_fsb \\<equiv> (\\<forall> f s . F1_inv f \\<and> nat1 s \\<and> new1_pre f s \\<longrightarrow> \n                        (\\<exists> f' r' . new1_post f s f' r' \\<and> F1_inv f'))\"\n\ndefinition\n  PO_dispose1_fsb :: \"bool\"\nwhere\n  \"PO_dispose1_fsb \\<equiv> (\\<forall> f d s . F1_inv f \\<and> nat1 s \\<and> dispose1_pre f d s \\<longrightarrow> \n                        (\\<exists> f' . dispose1_post f d s f' \\<and> F1_inv f'))\"\n\nunused_thms\n\n(*\nlemmX (in level1_dispose) \"False\"\nnitpick [show_all]\noops\nlemmX (in level1_new) \"False\"\nnitpick [show_all]\noops\n*)\n(* NOTE: Nitpick trick to see if any axiom involved in the locales is inconsistent.\n         i.e. if axioms are inconsistent, then we shouldn't be able to find a mode\n         for False. If we do, then the axioms are conistent (i.e. it's unprovable \n         as it should be).\n *)\n\nend\n(*>*)", "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/experiments/vdm/Heap/isa/HEAP1.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8774767746654974, "lm_q2_score": 0.831143045767024, "lm_q1q2_score": 0.7293087190853061}}
{"text": "(*File:      HOL/Analysis/Infinite_Product.thy\n  Author:    Manuel Eberl & LC Paulson\n\n  Basic results about convergence and absolute convergence of infinite products\n  and their connection to summability.\n*)\nsection \\<open>Infinite Products\\<close>\ntheory Infinite_Products\n  imports Topology_Euclidean_Space Complex_Transcendental\nbegin\n\nsubsection\\<^marker>\\<open>tag unimportant\\<close> \\<open>Preliminaries\\<close>\n\nlemma sum_le_prod:\n  fixes f :: \"'a \\<Rightarrow> 'b :: linordered_semidom\"\n  assumes \"\\<And>x. x \\<in> A \\<Longrightarrow> f x \\<ge> 0\"\n  shows   \"sum f A \\<le> (\\<Prod>x\\<in>A. 1 + f x)\"\n  using assms\nproof (induction A rule: infinite_finite_induct)\n  case (insert x A)\n  from insert.hyps have \"sum f A + f x * (\\<Prod>x\\<in>A. 1) \\<le> (\\<Prod>x\\<in>A. 1 + f x) + f x * (\\<Prod>x\\<in>A. 1 + f x)\"\n    by (intro add_mono insert mult_left_mono prod_mono) (auto intro: insert.prems)\n  with insert.hyps show ?case by (simp add: algebra_simps)\nqed simp_all\n\nlemma prod_le_exp_sum:\n  fixes f :: \"'a \\<Rightarrow> real\"\n  assumes \"\\<And>x. x \\<in> A \\<Longrightarrow> f x \\<ge> 0\"\n  shows   \"prod (\\<lambda>x. 1 + f x) A \\<le> exp (sum f A)\"\n  using assms\nproof (induction A rule: infinite_finite_induct)\n  case (insert x A)\n  have \"(1 + f x) * (\\<Prod>x\\<in>A. 1 + f x) \\<le> exp (f x) * exp (sum f A)\"\n    using insert.prems by (intro mult_mono insert prod_nonneg exp_ge_add_one_self) auto\n  with insert.hyps show ?case by (simp add: algebra_simps exp_add)\nqed simp_all\n\nlemma lim_ln_1_plus_x_over_x_at_0: \"(\\<lambda>x::real. ln (1 + x) / x) \\<midarrow>0\\<rightarrow> 1\"\nproof (rule lhopital)\n  show \"(\\<lambda>x::real. ln (1 + x)) \\<midarrow>0\\<rightarrow> 0\"\n    by (rule tendsto_eq_intros refl | simp)+\n  have \"eventually (\\<lambda>x::real. x \\<in> {-1/2<..<1/2}) (nhds 0)\"\n    by (rule eventually_nhds_in_open) auto\n  hence *: \"eventually (\\<lambda>x::real. x \\<in> {-1/2<..<1/2}) (at 0)\"\n    by (rule filter_leD [rotated]) (simp_all add: at_within_def)   \n  show \"eventually (\\<lambda>x::real. ((\\<lambda>x. ln (1 + x)) has_field_derivative inverse (1 + x)) (at x)) (at 0)\"\n    using * by eventually_elim (auto intro!: derivative_eq_intros simp: field_simps)\n  show \"eventually (\\<lambda>x::real. ((\\<lambda>x. x) has_field_derivative 1) (at x)) (at 0)\"\n    using * by eventually_elim (auto intro!: derivative_eq_intros simp: field_simps)\n  show \"\\<forall>\\<^sub>F x in at 0. x \\<noteq> 0\" by (auto simp: at_within_def eventually_inf_principal)\n  show \"(\\<lambda>x::real. inverse (1 + x) / 1) \\<midarrow>0\\<rightarrow> 1\"\n    by (rule tendsto_eq_intros refl | simp)+\nqed auto\n\nsubsection\\<open>Definitions and basic properties\\<close>\n\ndefinition\\<^marker>\\<open>tag important\\<close> raw_has_prod :: \"[nat \\<Rightarrow> 'a::{t2_space, comm_semiring_1}, nat, 'a] \\<Rightarrow> bool\" \n  where \"raw_has_prod f M p \\<equiv> (\\<lambda>n. \\<Prod>i\\<le>n. f (i+M)) \\<longlonglongrightarrow> p \\<and> p \\<noteq> 0\"\n\ntext\\<open>The nonzero and zero cases, as in \\emph{Complex Analysis} by Joseph Bak and Donald J.Newman, page 241\\<close>\ntext\\<^marker>\\<open>tag important\\<close> \\<open>%whitespace\\<close>\ndefinition\\<^marker>\\<open>tag important\\<close>\n  has_prod :: \"(nat \\<Rightarrow> 'a::{t2_space, comm_semiring_1}) \\<Rightarrow> 'a \\<Rightarrow> bool\" (infixr \"has'_prod\" 80)\n  where \"f has_prod p \\<equiv> raw_has_prod f 0 p \\<or> (\\<exists>i q. p = 0 \\<and> f i = 0 \\<and> raw_has_prod f (Suc i) q)\"\n\ndefinition\\<^marker>\\<open>tag important\\<close> convergent_prod :: \"(nat \\<Rightarrow> 'a :: {t2_space,comm_semiring_1}) \\<Rightarrow> bool\" where\n  \"convergent_prod f \\<equiv> \\<exists>M p. raw_has_prod f M p\"\n\ndefinition\\<^marker>\\<open>tag important\\<close> prodinf :: \"(nat \\<Rightarrow> 'a::{t2_space, comm_semiring_1}) \\<Rightarrow> 'a\"\n    (binder \"\\<Prod>\" 10)\n  where \"prodinf f = (THE p. f has_prod p)\"\n\nlemmas prod_defs = raw_has_prod_def has_prod_def convergent_prod_def prodinf_def\n\nlemma has_prod_subst[trans]: \"f = g \\<Longrightarrow> g has_prod z \\<Longrightarrow> f has_prod z\"\n  by simp\n\nlemma has_prod_cong: \"(\\<And>n. f n = g n) \\<Longrightarrow> f has_prod c \\<longleftrightarrow> g has_prod c\"\n  by presburger\n\nlemma raw_has_prod_nonzero [simp]: \"\\<not> raw_has_prod f M 0\"\n  by (simp add: raw_has_prod_def)\n\nlemma raw_has_prod_eq_0:\n  fixes f :: \"nat \\<Rightarrow> 'a::{semidom,t2_space}\"\n  assumes p: \"raw_has_prod f m p\" and i: \"f i = 0\" \"i \\<ge> m\"\n  shows \"p = 0\"\nproof -\n  have eq0: \"(\\<Prod>k\\<le>n. f (k+m)) = 0\" if \"i - m \\<le> n\" for n\n  proof -\n    have \"\\<exists>k\\<le>n. f (k + m) = 0\"\n      using i that by auto\n    then show ?thesis\n      by auto\n  qed\n  have \"(\\<lambda>n. \\<Prod>i\\<le>n. f (i + m)) \\<longlonglongrightarrow> 0\"\n    by (rule LIMSEQ_offset [where k = \"i-m\"]) (simp add: eq0)\n    with p show ?thesis\n      unfolding raw_has_prod_def\n    using LIMSEQ_unique by blast\nqed\n\nlemma raw_has_prod_Suc: \n  \"raw_has_prod f (Suc M) a \\<longleftrightarrow> raw_has_prod (\\<lambda>n. f (Suc n)) M a\"\n  unfolding raw_has_prod_def by auto\n\nlemma has_prod_0_iff: \"f has_prod 0 \\<longleftrightarrow> (\\<exists>i. f i = 0 \\<and> (\\<exists>p. raw_has_prod f (Suc i) p))\"\n  by (simp add: has_prod_def)\n      \nlemma has_prod_unique2: \n  fixes f :: \"nat \\<Rightarrow> 'a::{semidom,t2_space}\"\n  assumes \"f has_prod a\" \"f has_prod b\" shows \"a = b\"\n  using assms\n  by (auto simp: has_prod_def raw_has_prod_eq_0) (meson raw_has_prod_def sequentially_bot tendsto_unique)\n\nlemma has_prod_unique:\n  fixes f :: \"nat \\<Rightarrow> 'a :: {semidom,t2_space}\"\n  shows \"f has_prod s \\<Longrightarrow> s = prodinf f\"\n  by (simp add: has_prod_unique2 prodinf_def the_equality)\n\nlemma has_prod_eq_0_iff:\n  fixes f :: \"nat \\<Rightarrow> 'a :: {semidom, comm_semiring_1, t2_space}\"\n  assumes \"f has_prod P\"\n  shows   \"P = 0 \\<longleftrightarrow> 0 \\<in> range f\"\nproof\n  assume \"0 \\<in> range f\"\n  then obtain N where N: \"f N = 0\"\n    by auto\n  have \"eventually (\\<lambda>n. n > N) at_top\"\n    by (rule eventually_gt_at_top)\n  hence \"eventually (\\<lambda>n. (\\<Prod>k<n. f k) = 0) at_top\"\n    by eventually_elim (use N in auto)\n  hence \"(\\<lambda>n. \\<Prod>k<n. f k) \\<longlonglongrightarrow> 0\"\n    by (simp add: tendsto_eventually)\n  moreover have \"(\\<lambda>n. \\<Prod>k<n. f k) \\<longlonglongrightarrow> P\"\n    using assms by (metis N calculation prod_defs(2) raw_has_prod_eq_0 zero_le)\n  ultimately show \"P = 0\"\n    using tendsto_unique by force\nqed (use assms in \\<open>auto simp: has_prod_def\\<close>)\n\nlemma has_prod_0D:\n  fixes f :: \"nat \\<Rightarrow> 'a :: {semidom, comm_semiring_1, t2_space}\"\n  shows \"f has_prod 0 \\<Longrightarrow> 0 \\<in> range f\"\n  using has_prod_eq_0_iff[of f 0] by auto\n\nlemma has_prod_zeroI:\n  fixes f :: \"nat \\<Rightarrow> 'a :: {semidom, comm_semiring_1, t2_space}\"\n  assumes \"f has_prod P\" \"f n = 0\"\n  shows   \"P = 0\"\n  using assms by (auto simp: has_prod_eq_0_iff)  \n\nlemma raw_has_prod_in_Reals:\n  assumes \"raw_has_prod (complex_of_real \\<circ> z) M p\"\n  shows \"p \\<in> \\<real>\"\n  using assms by (auto simp: raw_has_prod_def real_lim_sequentially)\n\nlemma raw_has_prod_of_real_iff: \"raw_has_prod (complex_of_real \\<circ> z) M (of_real p) \\<longleftrightarrow> raw_has_prod z M p\"\n  by (auto simp: raw_has_prod_def tendsto_of_real_iff simp flip: of_real_prod)\n\nlemma convergent_prod_of_real_iff: \"convergent_prod (complex_of_real \\<circ> z) \\<longleftrightarrow> convergent_prod z\"\n  by (smt (verit, best) Reals_cases convergent_prod_def raw_has_prod_in_Reals raw_has_prod_of_real_iff)\n\nlemma convergent_prod_altdef:\n  fixes f :: \"nat \\<Rightarrow> 'a :: {t2_space,comm_semiring_1}\"\n  shows \"convergent_prod f \\<longleftrightarrow> (\\<exists>M L. (\\<forall>n\\<ge>M. f n \\<noteq> 0) \\<and> (\\<lambda>n. \\<Prod>i\\<le>n. f (i+M)) \\<longlonglongrightarrow> L \\<and> L \\<noteq> 0)\"\nproof\n  assume \"convergent_prod f\"\n  then obtain M L where *: \"(\\<lambda>n. \\<Prod>i\\<le>n. f (i+M)) \\<longlonglongrightarrow> L\" \"L \\<noteq> 0\"\n    by (auto simp: prod_defs)\n  have \"f i \\<noteq> 0\" if \"i \\<ge> M\" for i\n  proof\n    assume \"f i = 0\"\n    have **: \"eventually (\\<lambda>n. (\\<Prod>i\\<le>n. f (i+M)) = 0) sequentially\"\n      using eventually_ge_at_top[of \"i - M\"]\n    proof eventually_elim\n      case (elim n)\n      with \\<open>f i = 0\\<close> and \\<open>i \\<ge> M\\<close> show ?case\n        by (auto intro!: bexI[of _ \"i - M\"] prod_zero)\n    qed\n    have \"(\\<lambda>n. (\\<Prod>i\\<le>n. f (i+M))) \\<longlonglongrightarrow> 0\"\n      unfolding filterlim_iff\n      by (auto dest!: eventually_nhds_x_imp_x intro!: eventually_mono[OF **])\n    from tendsto_unique[OF _ this *(1)] and *(2)\n      show False by simp\n  qed\n  with * show \"(\\<exists>M L. (\\<forall>n\\<ge>M. f n \\<noteq> 0) \\<and> (\\<lambda>n. \\<Prod>i\\<le>n. f (i+M)) \\<longlonglongrightarrow> L \\<and> L \\<noteq> 0)\" \n    by blast\nqed (auto simp: prod_defs)\n\nlemma raw_has_prod_norm:\n  fixes a :: \"'a ::real_normed_field\"\n  assumes \"raw_has_prod f M a\"\n  shows \"raw_has_prod (\\<lambda>n. norm (f n)) M (norm a)\"\n  using assms by (auto simp: raw_has_prod_def prod_norm tendsto_norm)\n\nlemma has_prod_norm:\n  fixes a :: \"'a ::real_normed_field\"\n  assumes f: \"f has_prod a\" \n  shows \"(\\<lambda>n. norm (f n)) has_prod (norm a)\"\n  using f [unfolded has_prod_def]\nproof (elim disjE exE conjE)\n  assume f0: \"raw_has_prod f 0 a\"\n  then show \"(\\<lambda>n. norm (f n)) has_prod norm a\"\n    using has_prod_def raw_has_prod_norm by blast\nnext\n  fix i p\n  assume \"a = 0\" and \"f i = 0\" and p: \"raw_has_prod f (Suc i) p\"\n  then have \"Ex (raw_has_prod (\\<lambda>n. norm (f n)) (Suc i))\"\n    using raw_has_prod_norm by blast\n  then show ?thesis\n    by (metis \\<open>a = 0\\<close> \\<open>f i = 0\\<close> has_prod_0_iff norm_zero)\nqed\n\n\nsubsection\\<open>Absolutely convergent products\\<close>\n\ndefinition\\<^marker>\\<open>tag important\\<close> abs_convergent_prod :: \"(nat \\<Rightarrow> _) \\<Rightarrow> bool\" where\n  \"abs_convergent_prod f \\<longleftrightarrow> convergent_prod (\\<lambda>i. 1 + norm (f i - 1))\"\n\nlemma abs_convergent_prodI:\n  assumes \"convergent (\\<lambda>n. \\<Prod>i\\<le>n. 1 + norm (f i - 1))\"\n  shows   \"abs_convergent_prod f\"\nproof -\n  from assms obtain L where L: \"(\\<lambda>n. \\<Prod>i\\<le>n. 1 + norm (f i - 1)) \\<longlonglongrightarrow> L\"\n    by (auto simp: convergent_def)\n  have \"L \\<ge> 1\"\n  proof (rule tendsto_le)\n    show \"eventually (\\<lambda>n. (\\<Prod>i\\<le>n. 1 + norm (f i - 1)) \\<ge> 1) sequentially\"\n    proof (intro always_eventually allI)\n      fix n\n      have \"(\\<Prod>i\\<le>n. 1 + norm (f i - 1)) \\<ge> (\\<Prod>i\\<le>n. 1)\"\n        by (intro prod_mono) auto\n      thus \"(\\<Prod>i\\<le>n. 1 + norm (f i - 1)) \\<ge> 1\" by simp\n    qed\n  qed (use L in simp_all)\n  hence \"L \\<noteq> 0\" by auto\n  with L show ?thesis unfolding abs_convergent_prod_def prod_defs\n    by (intro exI[of _ \"0::nat\"] exI[of _ L]) auto\nqed\n\nlemma\n  fixes f :: \"nat \\<Rightarrow> 'a :: {topological_semigroup_mult,t2_space,idom}\"\n  assumes \"convergent_prod f\"\n  shows   convergent_prod_imp_convergent:     \"convergent (\\<lambda>n. \\<Prod>i\\<le>n. f i)\"\n    and   convergent_prod_to_zero_iff [simp]: \"(\\<lambda>n. \\<Prod>i\\<le>n. f i) \\<longlonglongrightarrow> 0  \\<longleftrightarrow>  (\\<exists>i. f i = 0)\"\nproof -\n  from assms obtain M L \n    where M: \"\\<And>n. n \\<ge> M \\<Longrightarrow> f n \\<noteq> 0\" and \"(\\<lambda>n. \\<Prod>i\\<le>n. f (i + M)) \\<longlonglongrightarrow> L\" and \"L \\<noteq> 0\"\n    by (auto simp: convergent_prod_altdef)\n  note this(2)\n  also have \"(\\<lambda>n. \\<Prod>i\\<le>n. f (i + M)) = (\\<lambda>n. \\<Prod>i=M..M+n. f i)\"\n    by (intro ext prod.reindex_bij_witness[of _ \"\\<lambda>n. n - M\" \"\\<lambda>n. n + M\"]) auto\n  finally have \"(\\<lambda>n. (\\<Prod>i<M. f i) * (\\<Prod>i=M..M+n. f i)) \\<longlonglongrightarrow> (\\<Prod>i<M. f i) * L\"\n    by (intro tendsto_mult tendsto_const)\n  also have \"(\\<lambda>n. (\\<Prod>i<M. f i) * (\\<Prod>i=M..M+n. f i)) = (\\<lambda>n. (\\<Prod>i\\<in>{..<M}\\<union>{M..M+n}. f i))\"\n    by (subst prod.union_disjoint) auto\n  also have \"(\\<lambda>n. {..<M} \\<union> {M..M+n}) = (\\<lambda>n. {..n+M})\" by auto\n  finally have lim: \"(\\<lambda>n. prod f {..n}) \\<longlonglongrightarrow> prod f {..<M} * L\" \n    by (rule LIMSEQ_offset)\n  thus \"convergent (\\<lambda>n. \\<Prod>i\\<le>n. f i)\"\n    by (auto simp: convergent_def)\n\n  show \"(\\<lambda>n. \\<Prod>i\\<le>n. f i) \\<longlonglongrightarrow> 0 \\<longleftrightarrow> (\\<exists>i. f i = 0)\"\n  proof\n    assume \"\\<exists>i. f i = 0\"\n    then obtain i where \"f i = 0\" by auto\n    moreover with M have \"i < M\" by (cases \"i < M\") auto\n    ultimately have \"(\\<Prod>i<M. f i) = 0\" by auto\n    with lim show \"(\\<lambda>n. \\<Prod>i\\<le>n. f i) \\<longlonglongrightarrow> 0\" by simp\n  next\n    assume \"(\\<lambda>n. \\<Prod>i\\<le>n. f i) \\<longlonglongrightarrow> 0\"\n    from tendsto_unique[OF _ this lim] and \\<open>L \\<noteq> 0\\<close>\n    show \"\\<exists>i. f i = 0\" by auto\n  qed\nqed\n\nlemma convergent_prod_iff_nz_lim:\n  fixes f :: \"nat \\<Rightarrow> 'a :: {topological_semigroup_mult,t2_space,idom}\"\n  assumes \"\\<And>i. f i \\<noteq> 0\"\n  shows \"convergent_prod f \\<longleftrightarrow> (\\<exists>L. (\\<lambda>n. \\<Prod>i\\<le>n. f i) \\<longlonglongrightarrow> L \\<and> L \\<noteq> 0)\"\n    (is \"?lhs \\<longleftrightarrow> ?rhs\")\nproof\n  assume ?lhs then show ?rhs\n    using assms convergentD convergent_prod_imp_convergent convergent_prod_to_zero_iff by blast\nnext\n  assume ?rhs then show ?lhs\n    unfolding prod_defs\n    by (rule_tac x=0 in exI) auto\nqed\n\nlemma\\<^marker>\\<open>tag important\\<close> convergent_prod_iff_convergent: \n  fixes f :: \"nat \\<Rightarrow> 'a :: {topological_semigroup_mult,t2_space,idom}\"\n  assumes \"\\<And>i. f i \\<noteq> 0\"\n  shows \"convergent_prod f \\<longleftrightarrow> convergent (\\<lambda>n. \\<Prod>i\\<le>n. f i) \\<and> lim (\\<lambda>n. \\<Prod>i\\<le>n. f i) \\<noteq> 0\"\n  by (force simp: convergent_prod_iff_nz_lim assms convergent_def limI)\n\nlemma bounded_imp_convergent_prod:\n  fixes a :: \"nat \\<Rightarrow> real\"\n  assumes 1: \"\\<And>n. a n \\<ge> 1\" and bounded: \"\\<And>n. (\\<Prod>i\\<le>n. a i) \\<le> B\"\n  shows \"convergent_prod a\"\nproof -\n  have \"bdd_above (range(\\<lambda>n. \\<Prod>i\\<le>n. a i))\"\n    by (meson bdd_aboveI2 bounded)\n  moreover have \"incseq (\\<lambda>n. \\<Prod>i\\<le>n. a i)\"\n    unfolding mono_def by (metis 1 prod_mono2 atMost_subset_iff dual_order.trans finite_atMost zero_le_one)\n  ultimately obtain p where p: \"(\\<lambda>n. \\<Prod>i\\<le>n. a i) \\<longlonglongrightarrow> p\"\n    using LIMSEQ_incseq_SUP by blast\n  then have \"p \\<noteq> 0\"\n    by (metis \"1\" not_one_le_zero prod_ge_1 LIMSEQ_le_const)\n  with 1 p show ?thesis\n    by (metis convergent_prod_iff_nz_lim not_one_le_zero)\nqed\n\n\nlemma abs_convergent_prod_altdef:\n  fixes f :: \"nat \\<Rightarrow> 'a :: {one,real_normed_vector}\"\n  shows  \"abs_convergent_prod f \\<longleftrightarrow> convergent (\\<lambda>n. \\<Prod>i\\<le>n. 1 + norm (f i - 1))\"\nproof\n  assume \"abs_convergent_prod f\"\n  thus \"convergent (\\<lambda>n. \\<Prod>i\\<le>n. 1 + norm (f i - 1))\"\n    by (auto simp: abs_convergent_prod_def intro!: convergent_prod_imp_convergent)\nqed (auto intro: abs_convergent_prodI)\n\nlemma Weierstrass_prod_ineq:\n  fixes f :: \"'a \\<Rightarrow> real\" \n  assumes \"\\<And>x. x \\<in> A \\<Longrightarrow> f x \\<in> {0..1}\"\n  shows   \"1 - sum f A \\<le> (\\<Prod>x\\<in>A. 1 - f x)\"\n  using assms\nproof (induction A rule: infinite_finite_induct)\n  case (insert x A)\n  from insert.hyps and insert.prems \n    have \"1 - sum f A + f x * (\\<Prod>x\\<in>A. 1 - f x) \\<le> (\\<Prod>x\\<in>A. 1 - f x) + f x * (\\<Prod>x\\<in>A. 1)\"\n    by (intro insert.IH add_mono mult_left_mono prod_mono) auto\n  with insert.hyps show ?case by (simp add: algebra_simps)\nqed simp_all\n\nlemma norm_prod_minus1_le_prod_minus1:\n  fixes f :: \"nat \\<Rightarrow> 'a :: {real_normed_div_algebra,comm_ring_1}\"  \n  shows \"norm (prod (\\<lambda>n. 1 + f n) A - 1) \\<le> prod (\\<lambda>n. 1 + norm (f n)) A - 1\"\nproof (induction A rule: infinite_finite_induct)\n  case (insert x A)\n  from insert.hyps have \n    \"norm ((\\<Prod>n\\<in>insert x A. 1 + f n) - 1) = \n       norm ((\\<Prod>n\\<in>A. 1 + f n) - 1 + f x * (\\<Prod>n\\<in>A. 1 + f n))\"\n    by (simp add: algebra_simps)\n  also have \"\\<dots> \\<le> norm ((\\<Prod>n\\<in>A. 1 + f n) - 1) + norm (f x * (\\<Prod>n\\<in>A. 1 + f n))\"\n    by (rule norm_triangle_ineq)\n  also have \"norm (f x * (\\<Prod>n\\<in>A. 1 + f n)) = norm (f x) * (\\<Prod>x\\<in>A. norm (1 + f x))\"\n    by (simp add: prod_norm norm_mult)\n  also have \"(\\<Prod>x\\<in>A. norm (1 + f x)) \\<le> (\\<Prod>x\\<in>A. norm (1::'a) + norm (f x))\"\n    by (intro prod_mono norm_triangle_ineq ballI conjI) auto\n  also have \"norm (1::'a) = 1\" by simp\n  also note insert.IH\n  also have \"(\\<Prod>n\\<in>A. 1 + norm (f n)) - 1 + norm (f x) * (\\<Prod>x\\<in>A. 1 + norm (f x)) =\n             (\\<Prod>n\\<in>insert x A. 1 + norm (f n)) - 1\"\n    using insert.hyps by (simp add: algebra_simps)\n  finally show ?case by - (simp_all add: mult_left_mono)\nqed simp_all\n\nlemma convergent_prod_imp_ev_nonzero:\n  fixes f :: \"nat \\<Rightarrow> 'a :: {t2_space,comm_semiring_1}\"\n  assumes \"convergent_prod f\"\n  shows   \"eventually (\\<lambda>n. f n \\<noteq> 0) sequentially\"\n  using assms by (auto simp: eventually_at_top_linorder convergent_prod_altdef)\n\nlemma convergent_prod_imp_LIMSEQ:\n  fixes f :: \"nat \\<Rightarrow> 'a :: {real_normed_field}\"\n  assumes \"convergent_prod f\"\n  shows   \"f \\<longlonglongrightarrow> 1\"\nproof -\n  from assms obtain M L where L: \"(\\<lambda>n. \\<Prod>i\\<le>n. f (i+M)) \\<longlonglongrightarrow> L\" \"\\<And>n. n \\<ge> M \\<Longrightarrow> f n \\<noteq> 0\" \"L \\<noteq> 0\"\n    by (auto simp: convergent_prod_altdef)\n  hence L': \"(\\<lambda>n. \\<Prod>i\\<le>Suc n. f (i+M)) \\<longlonglongrightarrow> L\" by (subst filterlim_sequentially_Suc)\n  have \"(\\<lambda>n. (\\<Prod>i\\<le>Suc n. f (i+M)) / (\\<Prod>i\\<le>n. f (i+M))) \\<longlonglongrightarrow> L / L\"\n    using L L' by (intro tendsto_divide) simp_all\n  also from L have \"L / L = 1\" by simp\n  also have \"(\\<lambda>n. (\\<Prod>i\\<le>Suc n. f (i+M)) / (\\<Prod>i\\<le>n. f (i+M))) = (\\<lambda>n. f (n + Suc M))\"\n    using assms L by (auto simp: fun_eq_iff atMost_Suc)\n  finally show ?thesis by (rule LIMSEQ_offset)\nqed\n\nlemma abs_convergent_prod_imp_summable:\n  fixes f :: \"nat \\<Rightarrow> 'a :: real_normed_div_algebra\"\n  assumes \"abs_convergent_prod f\"\n  shows \"summable (\\<lambda>i. norm (f i - 1))\"\nproof -\n  from assms have \"convergent (\\<lambda>n. \\<Prod>i\\<le>n. 1 + norm (f i - 1))\" \n    unfolding abs_convergent_prod_def by (rule convergent_prod_imp_convergent)\n  then obtain L where L: \"(\\<lambda>n. \\<Prod>i\\<le>n. 1 + norm (f i - 1)) \\<longlonglongrightarrow> L\"\n    unfolding convergent_def by blast\n  have \"convergent (\\<lambda>n. \\<Sum>i\\<le>n. norm (f i - 1))\"\n  proof (rule Bseq_monoseq_convergent)\n    have \"eventually (\\<lambda>n. (\\<Prod>i\\<le>n. 1 + norm (f i - 1)) < L + 1) sequentially\"\n      using L(1) by (rule order_tendstoD) simp_all\n    hence \"\\<forall>\\<^sub>F x in sequentially. norm (\\<Sum>i\\<le>x. norm (f i - 1)) \\<le> L + 1\"\n    proof eventually_elim\n      case (elim n)\n      have \"norm (\\<Sum>i\\<le>n. norm (f i - 1)) = (\\<Sum>i\\<le>n. norm (f i - 1))\"\n        unfolding real_norm_def by (intro abs_of_nonneg sum_nonneg) simp_all\n      also have \"\\<dots> \\<le> (\\<Prod>i\\<le>n. 1 + norm (f i - 1))\" by (rule sum_le_prod) auto\n      also have \"\\<dots> < L + 1\" by (rule elim)\n      finally show ?case by simp\n    qed\n    thus \"Bseq (\\<lambda>n. \\<Sum>i\\<le>n. norm (f i - 1))\" by (rule BfunI)\n  next\n    show \"monoseq (\\<lambda>n. \\<Sum>i\\<le>n. norm (f i - 1))\"\n      by (rule mono_SucI1) auto\n  qed\n  thus \"summable (\\<lambda>i. norm (f i - 1))\" by (simp add: summable_iff_convergent')\nqed\n\nlemma summable_imp_abs_convergent_prod:\n  fixes f :: \"nat \\<Rightarrow> 'a :: real_normed_div_algebra\"\n  assumes \"summable (\\<lambda>i. norm (f i - 1))\"\n  shows   \"abs_convergent_prod f\"\nproof (intro abs_convergent_prodI Bseq_monoseq_convergent)\n  show \"monoseq (\\<lambda>n. \\<Prod>i\\<le>n. 1 + norm (f i - 1))\"\n    by (intro mono_SucI1) \n       (auto simp: atMost_Suc algebra_simps intro!: mult_nonneg_nonneg prod_nonneg)\nnext\n  show \"Bseq (\\<lambda>n. \\<Prod>i\\<le>n. 1 + norm (f i - 1))\"\n  proof (rule Bseq_eventually_mono)\n    show \"eventually (\\<lambda>n. norm (\\<Prod>i\\<le>n. 1 + norm (f i - 1)) \\<le> \n            norm (exp (\\<Sum>i\\<le>n. norm (f i - 1)))) sequentially\"\n      by (intro always_eventually allI) (auto simp: abs_prod exp_sum intro!: prod_mono)\n  next\n    from assms have \"(\\<lambda>n. \\<Sum>i\\<le>n. norm (f i - 1)) \\<longlonglongrightarrow> (\\<Sum>i. norm (f i - 1))\"\n      using sums_def_le by blast\n    hence \"(\\<lambda>n. exp (\\<Sum>i\\<le>n. norm (f i - 1))) \\<longlonglongrightarrow> exp (\\<Sum>i. norm (f i - 1))\"\n      by (rule tendsto_exp)\n    hence \"convergent (\\<lambda>n. exp (\\<Sum>i\\<le>n. norm (f i - 1)))\"\n      by (rule convergentI)\n    thus \"Bseq (\\<lambda>n. exp (\\<Sum>i\\<le>n. norm (f i - 1)))\"\n      by (rule convergent_imp_Bseq)\n  qed\nqed\n\ntheorem abs_convergent_prod_conv_summable:\n  fixes f :: \"nat \\<Rightarrow> 'a :: real_normed_div_algebra\"\n  shows \"abs_convergent_prod f \\<longleftrightarrow> summable (\\<lambda>i. norm (f i - 1))\"\n  by (blast intro: abs_convergent_prod_imp_summable summable_imp_abs_convergent_prod)\n\nlemma abs_convergent_prod_imp_LIMSEQ:\n  fixes f :: \"nat \\<Rightarrow> 'a :: {comm_ring_1,real_normed_div_algebra}\"\n  assumes \"abs_convergent_prod f\"\n  shows   \"f \\<longlonglongrightarrow> 1\"\nproof -\n  from assms have \"summable (\\<lambda>n. norm (f n - 1))\"\n    by (rule abs_convergent_prod_imp_summable)\n  from summable_LIMSEQ_zero[OF this] have \"(\\<lambda>n. f n - 1) \\<longlonglongrightarrow> 0\"\n    by (simp add: tendsto_norm_zero_iff)\n  from tendsto_add[OF this tendsto_const[of 1]] show ?thesis by simp\nqed\n\nlemma abs_convergent_prod_imp_ev_nonzero:\n  fixes f :: \"nat \\<Rightarrow> 'a :: {comm_ring_1,real_normed_div_algebra}\"\n  assumes \"abs_convergent_prod f\"\n  shows   \"eventually (\\<lambda>n. f n \\<noteq> 0) sequentially\"\nproof -\n  from assms have \"f \\<longlonglongrightarrow> 1\" \n    by (rule abs_convergent_prod_imp_LIMSEQ)\n  hence \"eventually (\\<lambda>n. dist (f n) 1 < 1) at_top\"\n    by (auto simp: tendsto_iff)\n  thus ?thesis by eventually_elim auto\nqed\n\nsubsection\\<^marker>\\<open>tag unimportant\\<close> \\<open>Ignoring initial segments\\<close>\n\nlemma convergent_prod_offset:\n  assumes \"convergent_prod (\\<lambda>n. f (n + m))\"  \n  shows   \"convergent_prod f\"\nproof -\n  from assms obtain M L where \"(\\<lambda>n. \\<Prod>k\\<le>n. f (k + (M + m))) \\<longlonglongrightarrow> L\" \"L \\<noteq> 0\"\n    by (auto simp: prod_defs add.assoc)\n  thus \"convergent_prod f\" \n    unfolding prod_defs by blast\nqed\n\nlemma abs_convergent_prod_offset:\n  assumes \"abs_convergent_prod (\\<lambda>n. f (n + m))\"  \n  shows   \"abs_convergent_prod f\"\n  using assms unfolding abs_convergent_prod_def by (rule convergent_prod_offset)\n\n\nlemma raw_has_prod_ignore_initial_segment:\n  fixes f :: \"nat \\<Rightarrow> 'a :: real_normed_field\"\n  assumes \"raw_has_prod f M p\" \"N \\<ge> M\"\n  obtains q where  \"raw_has_prod f N q\"\nproof -\n  have p: \"(\\<lambda>n. \\<Prod>k\\<le>n. f (k + M)) \\<longlonglongrightarrow> p\" and \"p \\<noteq> 0\" \n    using assms by (auto simp: raw_has_prod_def)\n  then have nz: \"\\<And>n. n \\<ge> M \\<Longrightarrow> f n \\<noteq> 0\"\n    using assms by (auto simp: raw_has_prod_eq_0)\n  define C where \"C = (\\<Prod>k<N-M. f (k + M))\"\n  from nz have [simp]: \"C \\<noteq> 0\" \n    by (auto simp: C_def)\n\n  from p have \"(\\<lambda>i. \\<Prod>k\\<le>i + (N-M). f (k + M)) \\<longlonglongrightarrow> p\" \n    by (rule LIMSEQ_ignore_initial_segment)\n  also have \"(\\<lambda>i. \\<Prod>k\\<le>i + (N-M). f (k + M)) = (\\<lambda>n. C * (\\<Prod>k\\<le>n. f (k + N)))\"\n  proof (rule ext, goal_cases)\n    case (1 n)\n    have \"{..n+(N-M)} = {..<(N-M)} \\<union> {(N-M)..n+(N-M)}\" by auto\n    also have \"(\\<Prod>k\\<in>\\<dots>. f (k + M)) = C * (\\<Prod>k=(N-M)..n+(N-M). f (k + M))\"\n      unfolding C_def by (rule prod.union_disjoint) auto\n    also have \"(\\<Prod>k=(N-M)..n+(N-M). f (k + M)) = (\\<Prod>k\\<le>n. f (k + (N-M) + M))\"\n      by (intro ext prod.reindex_bij_witness[of _ \"\\<lambda>k. k + (N-M)\" \"\\<lambda>k. k - (N-M)\"]) auto\n    finally show ?case\n      using \\<open>N \\<ge> M\\<close> by (simp add: add_ac)\n  qed\n  finally have \"(\\<lambda>n. C * (\\<Prod>k\\<le>n. f (k + N)) / C) \\<longlonglongrightarrow> p / C\"\n    by (intro tendsto_divide tendsto_const) auto\n  hence \"(\\<lambda>n. \\<Prod>k\\<le>n. f (k + N)) \\<longlonglongrightarrow> p / C\" by simp\n  moreover from \\<open>p \\<noteq> 0\\<close> have \"p / C \\<noteq> 0\" by simp\n  ultimately show ?thesis\n    using raw_has_prod_def that by blast \nqed\n\ncorollary\\<^marker>\\<open>tag unimportant\\<close> convergent_prod_ignore_initial_segment:\n  fixes f :: \"nat \\<Rightarrow> 'a :: real_normed_field\"\n  assumes \"convergent_prod f\"\n  shows   \"convergent_prod (\\<lambda>n. f (n + m))\"\n  using assms\n  unfolding convergent_prod_def \n  apply clarify\n  apply (erule_tac N=\"M+m\" in raw_has_prod_ignore_initial_segment)\n  apply (auto simp add: raw_has_prod_def add_ac)\n  done\n\ncorollary\\<^marker>\\<open>tag unimportant\\<close> convergent_prod_ignore_nonzero_segment:\n  fixes f :: \"nat \\<Rightarrow> 'a :: real_normed_field\"\n  assumes f: \"convergent_prod f\" and nz: \"\\<And>i. i \\<ge> M \\<Longrightarrow> f i \\<noteq> 0\"\n  shows \"\\<exists>p. raw_has_prod f M p\"\n  using convergent_prod_ignore_initial_segment [OF f]\n  by (metis convergent_LIMSEQ_iff convergent_prod_iff_convergent le_add_same_cancel2 nz prod_defs(1) zero_order(1))\n\ncorollary\\<^marker>\\<open>tag unimportant\\<close> abs_convergent_prod_ignore_initial_segment:\n  assumes \"abs_convergent_prod f\"\n  shows   \"abs_convergent_prod (\\<lambda>n. f (n + m))\"\n  using assms unfolding abs_convergent_prod_def \n  by (rule convergent_prod_ignore_initial_segment)\n\nsubsection\\<open>More elementary properties\\<close>\n\ntheorem abs_convergent_prod_imp_convergent_prod:\n  fixes f :: \"nat \\<Rightarrow> 'a :: {real_normed_div_algebra,complete_space,comm_ring_1}\"\n  assumes \"abs_convergent_prod f\"\n  shows   \"convergent_prod f\"\nproof -\n  from assms have \"eventually (\\<lambda>n. f n \\<noteq> 0) sequentially\"\n    by (rule abs_convergent_prod_imp_ev_nonzero)\n  then obtain N where N: \"f n \\<noteq> 0\" if \"n \\<ge> N\" for n \n    by (auto simp: eventually_at_top_linorder)\n  let ?P = \"\\<lambda>n. \\<Prod>i\\<le>n. f (i + N)\" and ?Q = \"\\<lambda>n. \\<Prod>i\\<le>n. 1 + norm (f (i + N) - 1)\"\n\n  have \"Cauchy ?P\"\n  proof (rule CauchyI', goal_cases)\n    case (1 \\<epsilon>)\n    from assms have \"abs_convergent_prod (\\<lambda>n. f (n + N))\"\n      by (rule abs_convergent_prod_ignore_initial_segment)\n    hence \"Cauchy ?Q\"\n      unfolding abs_convergent_prod_def\n      by (intro convergent_Cauchy convergent_prod_imp_convergent)\n    from CauchyD[OF this 1] obtain M where M: \"norm (?Q m - ?Q n) < \\<epsilon>\" if \"m \\<ge> M\" \"n \\<ge> M\" for m n\n      by blast\n    show ?case\n    proof (rule exI[of _ M], safe, goal_cases)\n      case (1 m n)\n      have \"dist (?P m) (?P n) = norm (?P n - ?P m)\"\n        by (simp add: dist_norm norm_minus_commute)\n      also from 1 have \"{..n} = {..m} \\<union> {m<..n}\" by auto\n      hence \"norm (?P n - ?P m) = norm (?P m * (\\<Prod>k\\<in>{m<..n}. f (k + N)) - ?P m)\"\n        by (subst prod.union_disjoint [symmetric]) (auto simp: algebra_simps)\n      also have \"\\<dots> = norm (?P m * ((\\<Prod>k\\<in>{m<..n}. f (k + N)) - 1))\"\n        by (simp add: algebra_simps)\n      also have \"\\<dots> = (\\<Prod>k\\<le>m. norm (f (k + N))) * norm ((\\<Prod>k\\<in>{m<..n}. f (k + N)) - 1)\"\n        by (simp add: norm_mult prod_norm)\n      also have \"\\<dots> \\<le> ?Q m * ((\\<Prod>k\\<in>{m<..n}. 1 + norm (f (k + N) - 1)) - 1)\"\n        using norm_prod_minus1_le_prod_minus1[of \"\\<lambda>k. f (k + N) - 1\" \"{m<..n}\"]\n              norm_triangle_ineq[of 1 \"f k - 1\" for k]\n        by (intro mult_mono prod_mono ballI conjI norm_prod_minus1_le_prod_minus1 prod_nonneg) auto\n      also have \"\\<dots> = ?Q m * (\\<Prod>k\\<in>{m<..n}. 1 + norm (f (k + N) - 1)) - ?Q m\"\n        by (simp add: algebra_simps)\n      also have \"?Q m * (\\<Prod>k\\<in>{m<..n}. 1 + norm (f (k + N) - 1)) = \n                   (\\<Prod>k\\<in>{..m}\\<union>{m<..n}. 1 + norm (f (k + N) - 1))\"\n        by (rule prod.union_disjoint [symmetric]) auto\n      also from 1 have \"{..m}\\<union>{m<..n} = {..n}\" by auto\n      also have \"?Q n - ?Q m \\<le> norm (?Q n - ?Q m)\" by simp\n      also from 1 have \"\\<dots> < \\<epsilon>\" by (intro M) auto\n      finally show ?case .\n    qed\n  qed\n  hence conv: \"convergent ?P\" by (rule Cauchy_convergent)\n  then obtain L where L: \"?P \\<longlonglongrightarrow> L\"\n    by (auto simp: convergent_def)\n\n  have \"L \\<noteq> 0\"\n  proof\n    assume [simp]: \"L = 0\"\n    from tendsto_norm[OF L] have limit: \"(\\<lambda>n. \\<Prod>k\\<le>n. norm (f (k + N))) \\<longlonglongrightarrow> 0\" \n      by (simp add: prod_norm)\n\n    from assms have \"(\\<lambda>n. f (n + N)) \\<longlonglongrightarrow> 1\"\n      by (intro abs_convergent_prod_imp_LIMSEQ abs_convergent_prod_ignore_initial_segment)\n    hence \"eventually (\\<lambda>n. norm (f (n + N) - 1) < 1) sequentially\"\n      by (auto simp: tendsto_iff dist_norm)\n    then obtain M0 where M0: \"norm (f (n + N) - 1) < 1\" if \"n \\<ge> M0\" for n\n      by (auto simp: eventually_at_top_linorder)\n\n    {\n      fix M assume M: \"M \\<ge> M0\"\n      with M0 have M: \"norm (f (n + N) - 1) < 1\" if \"n \\<ge> M\" for n using that by simp\n\n      have \"(\\<lambda>n. \\<Prod>k\\<le>n. 1 - norm (f (k+M+N) - 1)) \\<longlonglongrightarrow> 0\"\n      proof (rule tendsto_sandwich)\n        show \"eventually (\\<lambda>n. (\\<Prod>k\\<le>n. 1 - norm (f (k+M+N) - 1)) \\<ge> 0) sequentially\"\n          using M by (intro always_eventually prod_nonneg allI ballI) (auto intro: less_imp_le)\n        have \"norm (1::'a) - norm (f (i + M + N) - 1) \\<le> norm (f (i + M + N))\" for i\n          using norm_triangle_ineq3[of \"f (i + M + N)\" 1] by simp\n        thus \"eventually (\\<lambda>n. (\\<Prod>k\\<le>n. 1 - norm (f (k+M+N) - 1)) \\<le> (\\<Prod>k\\<le>n. norm (f (k+M+N)))) at_top\"\n          using M by (intro always_eventually allI prod_mono ballI conjI) (auto intro: less_imp_le)\n        \n        define C where \"C = (\\<Prod>k<M. norm (f (k + N)))\"\n        from N have [simp]: \"C \\<noteq> 0\" by (auto simp: C_def)\n        from L have \"(\\<lambda>n. norm (\\<Prod>k\\<le>n+M. f (k + N))) \\<longlonglongrightarrow> 0\"\n          by (intro LIMSEQ_ignore_initial_segment) (simp add: tendsto_norm_zero_iff)\n        also have \"(\\<lambda>n. norm (\\<Prod>k\\<le>n+M. f (k + N))) = (\\<lambda>n. C * (\\<Prod>k\\<le>n. norm (f (k + M + N))))\"\n        proof (rule ext, goal_cases)\n          case (1 n)\n          have \"{..n+M} = {..<M} \\<union> {M..n+M}\" by auto\n          also have \"norm (\\<Prod>k\\<in>\\<dots>. f (k + N)) = C * norm (\\<Prod>k=M..n+M. f (k + N))\"\n            unfolding C_def by (subst prod.union_disjoint) (auto simp: norm_mult prod_norm)\n          also have \"(\\<Prod>k=M..n+M. f (k + N)) = (\\<Prod>k\\<le>n. f (k + N + M))\"\n            by (intro prod.reindex_bij_witness[of _ \"\\<lambda>i. i + M\" \"\\<lambda>i. i - M\"]) auto\n          finally show ?case by (simp add: add_ac prod_norm)\n        qed\n        finally have \"(\\<lambda>n. C * (\\<Prod>k\\<le>n. norm (f (k + M + N))) / C) \\<longlonglongrightarrow> 0 / C\"\n          by (intro tendsto_divide tendsto_const) auto\n        thus \"(\\<lambda>n. \\<Prod>k\\<le>n. norm (f (k + M + N))) \\<longlonglongrightarrow> 0\" by simp\n      qed simp_all\n\n      have \"1 - (\\<Sum>i. norm (f (i + M + N) - 1)) \\<le> 0\"\n      proof (rule tendsto_le)\n        show \"eventually (\\<lambda>n. 1 - (\\<Sum>k\\<le>n. norm (f (k+M+N) - 1)) \\<le> \n                                (\\<Prod>k\\<le>n. 1 - norm (f (k+M+N) - 1))) at_top\"\n          using M by (intro always_eventually allI Weierstrass_prod_ineq) (auto intro: less_imp_le)\n        show \"(\\<lambda>n. \\<Prod>k\\<le>n. 1 - norm (f (k+M+N) - 1)) \\<longlonglongrightarrow> 0\" by fact\n        show \"(\\<lambda>n. 1 - (\\<Sum>k\\<le>n. norm (f (k + M + N) - 1)))\n                  \\<longlonglongrightarrow> 1 - (\\<Sum>i. norm (f (i + M + N) - 1))\"\n          by (intro tendsto_intros summable_LIMSEQ' summable_ignore_initial_segment \n                abs_convergent_prod_imp_summable assms)\n      qed simp_all\n      hence \"(\\<Sum>i. norm (f (i + M + N) - 1)) \\<ge> 1\" by simp\n      also have \"\\<dots> + (\\<Sum>i<M. norm (f (i + N) - 1)) = (\\<Sum>i. norm (f (i + N) - 1))\"\n        by (intro suminf_split_initial_segment [symmetric] summable_ignore_initial_segment\n              abs_convergent_prod_imp_summable assms)\n      finally have \"1 + (\\<Sum>i<M. norm (f (i + N) - 1)) \\<le> (\\<Sum>i. norm (f (i + N) - 1))\" by simp\n    } note * = this\n\n    have \"1 + (\\<Sum>i. norm (f (i + N) - 1)) \\<le> (\\<Sum>i. norm (f (i + N) - 1))\"\n    proof (rule tendsto_le)\n      show \"(\\<lambda>M. 1 + (\\<Sum>i<M. norm (f (i + N) - 1))) \\<longlonglongrightarrow> 1 + (\\<Sum>i. norm (f (i + N) - 1))\"\n        by (intro tendsto_intros summable_LIMSEQ summable_ignore_initial_segment \n                abs_convergent_prod_imp_summable assms)\n      show \"eventually (\\<lambda>M. 1 + (\\<Sum>i<M. norm (f (i + N) - 1)) \\<le> (\\<Sum>i. norm (f (i + N) - 1))) at_top\"\n        using eventually_ge_at_top[of M0] by eventually_elim (use * in auto)\n    qed simp_all\n    thus False by simp\n  qed\n  with L show ?thesis by (auto simp: prod_defs)\nqed\n\nlemma raw_has_prod_cases:\n  fixes f :: \"nat \\<Rightarrow> 'a :: {idom,topological_semigroup_mult,t2_space}\"\n  assumes \"raw_has_prod f M p\"\n  obtains i where \"i<M\" \"f i = 0\" | p where \"raw_has_prod f 0 p\"\nproof -\n  have \"(\\<lambda>n. \\<Prod>i\\<le>n. f (i + M)) \\<longlonglongrightarrow> p\" \"p \\<noteq> 0\"\n    using assms unfolding raw_has_prod_def by blast+\n  then have \"(\\<lambda>n. prod f {..<M} * (\\<Prod>i\\<le>n. f (i + M))) \\<longlonglongrightarrow> prod f {..<M} * p\"\n    by (metis tendsto_mult_left)\n  moreover have \"prod f {..<M} * (\\<Prod>i\\<le>n. f (i + M)) = prod f {..n+M}\" for n\n  proof -\n    have \"{..n+M} = {..<M} \\<union> {M..n+M}\"\n      by auto\n    then have \"prod f {..n+M} = prod f {..<M} * prod f {M..n+M}\"\n      by simp (subst prod.union_disjoint; force)\n    also have \"\\<dots> = prod f {..<M} * (\\<Prod>i\\<le>n. f (i + M))\"\n      by (metis (mono_tags, lifting) add.left_neutral atMost_atLeast0 prod.shift_bounds_cl_nat_ivl)\n    finally show ?thesis by metis\n  qed\n  ultimately have \"(\\<lambda>n. prod f {..n}) \\<longlonglongrightarrow> prod f {..<M} * p\"\n    by (auto intro: LIMSEQ_offset [where k=M])\n  then have \"raw_has_prod f 0 (prod f {..<M} * p)\" if \"\\<forall>i<M. f i \\<noteq> 0\"\n    using \\<open>p \\<noteq> 0\\<close> assms that by (auto simp: raw_has_prod_def)\n  then show thesis\n    using that by blast\nqed\n\ncorollary convergent_prod_offset_0:\n  fixes f :: \"nat \\<Rightarrow> 'a :: {idom,topological_semigroup_mult,t2_space}\"\n  assumes \"convergent_prod f\" \"\\<And>i. f i \\<noteq> 0\"\n  shows \"\\<exists>p. raw_has_prod f 0 p\"\n  using assms convergent_prod_def raw_has_prod_cases by blast\n\nlemma prodinf_eq_lim:\n  fixes f :: \"nat \\<Rightarrow> 'a :: {idom,topological_semigroup_mult,t2_space}\"\n  assumes \"convergent_prod f\" \"\\<And>i. f i \\<noteq> 0\"\n  shows \"prodinf f = lim (\\<lambda>n. \\<Prod>i\\<le>n. f i)\"\n  using assms convergent_prod_offset_0 [OF assms]\n  by (simp add: prod_defs lim_def) (metis (no_types) assms(1) convergent_prod_to_zero_iff)\n\nlemma prodinf_eq_lim':\n  fixes f :: \"nat \\<Rightarrow> 'a :: {idom,topological_semigroup_mult,t2_space}\"\n  assumes \"convergent_prod f\" \"\\<And>i. f i \\<noteq> 0\"\n  shows \"prodinf f = lim (\\<lambda>n. \\<Prod>i<n. f i)\"\n  by (metis assms prodinf_eq_lim LIMSEQ_lessThan_iff_atMost convergent_prod_iff_nz_lim limI)\n\nlemma prodinf_eq_prod_lim:\n  fixes a:: \"'a :: {topological_semigroup_mult,t2_space,idom}\"\n  assumes \"(\\<lambda>n. \\<Prod>k\\<le>n. f k) \\<longlonglongrightarrow> a\" \"a \\<noteq> 0\"\n  shows\"(\\<Prod>k. f k) = a\"\n  by (metis LIMSEQ_prod_0 LIMSEQ_unique assms convergent_prod_iff_nz_lim limI prodinf_eq_lim)\n\nlemma prodinf_eq_prod_lim':\n  fixes a:: \"'a :: {topological_semigroup_mult,t2_space,idom}\"\n  assumes \"(\\<lambda>n. \\<Prod>k<n. f k) \\<longlonglongrightarrow> a\" \"a \\<noteq> 0\"\n  shows\"(\\<Prod>k. f k) = a\"\n  using LIMSEQ_lessThan_iff_atMost assms prodinf_eq_prod_lim by blast\n\nlemma has_prod_one[simp, intro]: \"(\\<lambda>n. 1) has_prod 1\"\n  unfolding prod_defs by auto\n\nlemma convergent_prod_one[simp, intro]: \"convergent_prod (\\<lambda>n. 1)\"\n  unfolding prod_defs by auto\n\nlemma prodinf_cong: \"(\\<And>n. f n = g n) \\<Longrightarrow> prodinf f = prodinf g\"\n  by presburger\n\nlemma convergent_prod_cong:\n  fixes f g :: \"nat \\<Rightarrow> 'a::{field,topological_semigroup_mult,t2_space}\"\n  assumes ev: \"eventually (\\<lambda>x. f x = g x) sequentially\" and f: \"\\<And>i. f i \\<noteq> 0\" and g: \"\\<And>i. g i \\<noteq> 0\"\n  shows \"convergent_prod f = convergent_prod 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 = (\\<Prod>k<N. f k / g k)\"\n  with g have \"C \\<noteq> 0\"\n    by (simp add: f)\n  have *: \"eventually (\\<lambda>n. prod f {..n} = C * prod g {..n}) sequentially\"\n    using eventually_ge_at_top[of N]\n  proof eventually_elim\n    case (elim n)\n    then have \"{..n} = {..<N} \\<union> {N..n}\"\n      by auto\n    also have \"prod f \\<dots> = prod f {..<N} * prod f {N..n}\"\n      by (intro prod.union_disjoint) auto\n    also from N have \"prod f {N..n} = prod g {N..n}\"\n      by (intro prod.cong) simp_all\n    also have \"prod f {..<N} * prod g {N..n} = C * (prod g {..<N} * prod g {N..n})\"\n      unfolding C_def by (simp add: g prod_dividef)\n    also have \"prod g {..<N} * prod g {N..n} = prod g ({..<N} \\<union> {N..n})\"\n      by (intro prod.union_disjoint [symmetric]) auto\n    also from elim have \"{..<N} \\<union> {N..n} = {..n}\"\n      by auto                                                                    \n    finally show \"prod f {..n} = C * prod g {..n}\" .\n  qed\n  then have cong: \"convergent (\\<lambda>n. prod f {..n}) = convergent (\\<lambda>n. C * prod g {..n})\"\n    by (rule convergent_cong)\n  show ?thesis\n  proof\n    assume cf: \"convergent_prod f\"\n    with f have \"\\<not> (\\<lambda>n. prod f {..n}) \\<longlonglongrightarrow> 0\"\n      by simp\n    then have \"\\<not> (\\<lambda>n. prod g {..n}) \\<longlonglongrightarrow> 0\"\n      using * \\<open>C \\<noteq> 0\\<close> filterlim_cong by fastforce\n    then show \"convergent_prod g\"\n      by (metis convergent_mult_const_iff \\<open>C \\<noteq> 0\\<close> cong cf convergent_LIMSEQ_iff convergent_prod_iff_convergent convergent_prod_imp_convergent g)\n  next\n    assume cg: \"convergent_prod g\"\n    have \"\\<exists>a. C * a \\<noteq> 0 \\<and> (\\<lambda>n. prod g {..n}) \\<longlonglongrightarrow> a\"\n      by (metis (no_types) \\<open>C \\<noteq> 0\\<close> cg convergent_prod_iff_nz_lim divide_eq_0_iff g nonzero_mult_div_cancel_right)\n    then show \"convergent_prod f\"\n      using \"*\" tendsto_mult_left filterlim_cong\n      by (fastforce simp add: convergent_prod_iff_nz_lim f)\n  qed\nqed\n\nlemma has_prod_finite:\n  fixes f :: \"nat \\<Rightarrow> 'a::{semidom,t2_space}\"\n  assumes [simp]: \"finite N\"\n    and f: \"\\<And>n. n \\<notin> N \\<Longrightarrow> f n = 1\"\n  shows \"f has_prod (\\<Prod>n\\<in>N. f n)\"\nproof -\n  have eq: \"prod f {..n + Suc (Max N)} = prod f N\" for n\n  proof (rule prod.mono_neutral_right)\n    show \"N \\<subseteq> {..n + Suc (Max N)}\"\n      by (auto simp: le_Suc_eq trans_le_add2)\n    show \"\\<forall>i\\<in>{..n + Suc (Max N)} - N. f i = 1\"\n      using f by blast\n  qed auto\n  show ?thesis\n  proof (cases \"\\<forall>n\\<in>N. f n \\<noteq> 0\")\n    case True\n    then have \"prod f N \\<noteq> 0\"\n      by simp\n    moreover have \"(\\<lambda>n. prod f {..n}) \\<longlonglongrightarrow> prod f N\"\n      by (rule LIMSEQ_offset[of _ \"Suc (Max N)\"]) (simp add: eq atLeast0LessThan del: add_Suc_right)\n    ultimately show ?thesis\n      by (simp add: raw_has_prod_def has_prod_def)\n  next\n    case False\n    then obtain k where \"k \\<in> N\" \"f k = 0\"\n      by auto\n    let ?Z = \"{n \\<in> N. f n = 0}\"\n    have maxge: \"Max ?Z \\<ge> n\" if \"f n = 0\" for n\n      using Max_ge [of ?Z] \\<open>finite N\\<close> \\<open>f n = 0\\<close>\n      by (metis (mono_tags) Collect_mem_eq f finite_Collect_conjI mem_Collect_eq zero_neq_one)\n    let ?q = \"prod f {Suc (Max ?Z)..Max N}\"\n    have [simp]: \"?q \\<noteq> 0\"\n      using maxge Suc_n_not_le_n le_trans by force\n    have eq: \"(\\<Prod>i\\<le>n + Max N. f (Suc (i + Max ?Z))) = ?q\" for n\n    proof -\n      have \"(\\<Prod>i\\<le>n + Max N. f (Suc (i + Max ?Z))) = prod f {Suc (Max ?Z)..n + Max N + Suc (Max ?Z)}\" \n      proof (rule prod.reindex_cong [where l = \"\\<lambda>i. i + Suc (Max ?Z)\", THEN sym])\n        show \"{Suc (Max ?Z)..n + Max N + Suc (Max ?Z)} = (\\<lambda>i. i + Suc (Max ?Z)) ` {..n + Max N}\"\n          using le_Suc_ex by fastforce\n      qed (auto simp: inj_on_def)\n      also have \"\\<dots> = ?q\"\n        by (rule prod.mono_neutral_right)\n           (use Max.coboundedI [OF \\<open>finite N\\<close>] f in \\<open>force+\\<close>)\n      finally show ?thesis .\n    qed\n    have q: \"raw_has_prod f (Suc (Max ?Z)) ?q\"\n    proof (simp add: raw_has_prod_def)\n      show \"(\\<lambda>n. \\<Prod>i\\<le>n. f (Suc (i + Max ?Z))) \\<longlonglongrightarrow> ?q\"\n        by (rule LIMSEQ_offset[of _ \"(Max N)\"]) (simp add: eq)\n    qed\n    show ?thesis\n      unfolding has_prod_def\n    proof (intro disjI2 exI conjI)      \n      show \"prod f N = 0\"\n        using \\<open>f k = 0\\<close> \\<open>k \\<in> N\\<close> \\<open>finite N\\<close> prod_zero by blast\n      show \"f (Max ?Z) = 0\"\n        using Max_in [of ?Z] \\<open>finite N\\<close> \\<open>f k = 0\\<close> \\<open>k \\<in> N\\<close> by auto\n    qed (use q in auto)\n  qed\nqed\n\ncorollary\\<^marker>\\<open>tag unimportant\\<close> has_prod_0:\n  fixes f :: \"nat \\<Rightarrow> 'a::{semidom,t2_space}\"\n  assumes \"\\<And>n. f n = 1\"\n  shows \"f has_prod 1\"\n  by (simp add: assms has_prod_cong)\n\nlemma prodinf_zero[simp]: \"prodinf (\\<lambda>n. 1::'a::real_normed_field) = 1\"\n  using has_prod_unique by force\n\nlemma convergent_prod_finite:\n  fixes f :: \"nat \\<Rightarrow> 'a::{idom,t2_space}\"\n  assumes \"finite N\" \"\\<And>n. n \\<notin> N \\<Longrightarrow> f n = 1\"\n  shows \"convergent_prod f\"\nproof -\n  have \"\\<exists>n p. raw_has_prod f n p\"\n    using assms has_prod_def has_prod_finite by blast\n  then show ?thesis\n    by (simp add: convergent_prod_def)\nqed\n\nlemma has_prod_If_finite_set:\n  fixes f :: \"nat \\<Rightarrow> 'a::{idom,t2_space}\"\n  shows \"finite A \\<Longrightarrow> (\\<lambda>r. if r \\<in> A then f r else 1) has_prod (\\<Prod>r\\<in>A. f r)\"\n  using has_prod_finite[of A \"(\\<lambda>r. if r \\<in> A then f r else 1)\"]\n  by simp\n\nlemma has_prod_If_finite:\n  fixes f :: \"nat \\<Rightarrow> 'a::{idom,t2_space}\"\n  shows \"finite {r. P r} \\<Longrightarrow> (\\<lambda>r. if P r then f r else 1) has_prod (\\<Prod>r | P r. f r)\"\n  using has_prod_If_finite_set[of \"{r. P r}\"] by simp\n\nlemma convergent_prod_If_finite_set[simp, intro]:\n  fixes f :: \"nat \\<Rightarrow> 'a::{idom,t2_space}\"\n  shows \"finite A \\<Longrightarrow> convergent_prod (\\<lambda>r. if r \\<in> A then f r else 1)\"\n  by (simp add: convergent_prod_finite)\n\nlemma convergent_prod_If_finite[simp, intro]:\n  fixes f :: \"nat \\<Rightarrow> 'a::{idom,t2_space}\"\n  shows \"finite {r. P r} \\<Longrightarrow> convergent_prod (\\<lambda>r. if P r then f r else 1)\"\n  using convergent_prod_def has_prod_If_finite has_prod_def by fastforce\n\nlemma has_prod_single:\n  fixes f :: \"nat \\<Rightarrow> 'a::{idom,t2_space}\"\n  shows \"(\\<lambda>r. if r = i then f r else 1) has_prod f i\"\n  using has_prod_If_finite[of \"\\<lambda>r. r = i\"] by simp\n\ntext \\<open>The ge1 assumption can probably be weakened, at the expense of extra work\\<close>\nlemma uniform_limit_prodinf:\n  fixes f:: \"nat \\<Rightarrow> real \\<Rightarrow> real\"\n  assumes \"uniformly_convergent_on X (\\<lambda>n x. \\<Prod>k<n. f k x)\" \n    and ge1: \"\\<And>x k . x \\<in> X \\<Longrightarrow> f k x \\<ge> 1\"\n  shows \"uniform_limit X (\\<lambda>n x. \\<Prod>k<n. f k x) (\\<lambda>x. \\<Prod>k. f k x) sequentially\"\nproof -\n  have ul: \"uniform_limit X (\\<lambda>n x. \\<Prod>k<n. f k x) (\\<lambda>x. lim (\\<lambda>n. \\<Prod>k<n. f k x)) sequentially\"\n    using assms uniformly_convergent_uniform_limit_iff by blast\n  moreover have \"(\\<Prod>k. f k x) = lim (\\<lambda>n. \\<Prod>k<n. f k x)\" if \"x \\<in> X\" for x\n  proof (intro prodinf_eq_lim')\n    have tends: \"(\\<lambda>n. \\<Prod>k<n. f k x) \\<longlonglongrightarrow> lim (\\<lambda>n. \\<Prod>k<n. f k x)\"\n      using tendsto_uniform_limitI [OF ul] that by metis\n    moreover have \"(\\<Prod>k<n. f k x) \\<ge> 1\" for n\n      using ge1 by (simp add: prod_ge_1 that)\n    ultimately have \"lim (\\<lambda>n. \\<Prod>k<n. f k x) \\<ge> 1\"\n      by (meson LIMSEQ_le_const)\n    then have \"raw_has_prod (\\<lambda>k. f k x) 0 (lim (\\<lambda>n. \\<Prod>k<n. f k x))\"\n      using LIMSEQ_lessThan_iff_atMost tends by (auto simp: raw_has_prod_def)\n    then show \"convergent_prod (\\<lambda>k. f k x)\"\n      unfolding convergent_prod_def by blast\n    show \"\\<And>k. f k x \\<noteq> 0\"\n      by (smt (verit) ge1 that)\n  qed\n  ultimately show ?thesis\n    by (metis (mono_tags, lifting) uniform_limit_cong')\nqed\n\ncontext\n  fixes f :: \"nat \\<Rightarrow> 'a :: real_normed_field\"\nbegin\n\nlemma convergent_prod_imp_has_prod: \n  assumes \"convergent_prod f\"\n  shows \"\\<exists>p. f has_prod p\"\nproof -\n  obtain M p where p: \"raw_has_prod f M p\"\n    using assms convergent_prod_def by blast\n  then have \"p \\<noteq> 0\"\n    using raw_has_prod_nonzero by blast\n  with p have fnz: \"f i \\<noteq> 0\" if \"i \\<ge> M\" for i\n    using raw_has_prod_eq_0 that by blast\n  define C where \"C = (\\<Prod>n<M. f n)\"\n  show ?thesis\n  proof (cases \"\\<forall>n\\<le>M. f n \\<noteq> 0\")\n    case True\n    then have \"C \\<noteq> 0\"\n      by (simp add: C_def)\n    then show ?thesis\n      by (meson True assms convergent_prod_offset_0 fnz has_prod_def nat_le_linear)\n  next\n    case False\n    let ?N = \"GREATEST n. f n = 0\"\n    have 0: \"f ?N = 0\"\n      using fnz False\n      by (metis (mono_tags, lifting) GreatestI_ex_nat nat_le_linear)\n    have \"f i \\<noteq> 0\" if \"i > ?N\" for i\n      by (metis (mono_tags, lifting) Greatest_le_nat fnz leD linear that)\n    then have \"\\<exists>p. raw_has_prod f (Suc ?N) p\"\n      using assms by (auto simp: intro!: convergent_prod_ignore_nonzero_segment)\n    then show ?thesis\n      unfolding has_prod_def using 0 by blast\n  qed\nqed\n\nlemma convergent_prod_has_prod [intro]:\n  shows \"convergent_prod f \\<Longrightarrow> f has_prod (prodinf f)\"\n  unfolding prodinf_def\n  by (metis convergent_prod_imp_has_prod has_prod_unique theI')\n\nlemma convergent_prod_LIMSEQ:\n  shows \"convergent_prod f \\<Longrightarrow> (\\<lambda>n. \\<Prod>i\\<le>n. f i) \\<longlonglongrightarrow> prodinf f\"\n  by (metis convergent_LIMSEQ_iff convergent_prod_has_prod convergent_prod_imp_convergent \n      convergent_prod_to_zero_iff raw_has_prod_eq_0 has_prod_def prodinf_eq_lim zero_le)\n\ntheorem has_prod_iff: \"f has_prod x \\<longleftrightarrow> convergent_prod f \\<and> prodinf f = x\"\nproof\n  assume \"f has_prod x\"\n  then show \"convergent_prod f \\<and> prodinf f = x\"\n    apply safe\n    using convergent_prod_def has_prod_def apply blast\n    using has_prod_unique by blast\nqed auto\n\nlemma convergent_prod_has_prod_iff: \"convergent_prod f \\<longleftrightarrow> f has_prod prodinf f\"\n  by (auto simp: has_prod_iff convergent_prod_has_prod)\n\nlemma prodinf_finite:\n  assumes N: \"finite N\"\n    and f: \"\\<And>n. n \\<notin> N \\<Longrightarrow> f n = 1\"\n  shows \"prodinf f = (\\<Prod>n\\<in>N. f n)\"\n  using has_prod_finite[OF assms, THEN has_prod_unique] by simp\n\nend\n\nsubsection\\<^marker>\\<open>tag unimportant\\<close> \\<open>Infinite products on ordered topological monoids\\<close>\n\ncontext\n  fixes f :: \"nat \\<Rightarrow> 'a::{linordered_semidom,linorder_topology}\"\nbegin\n\nlemma has_prod_nonzero:\n  assumes \"f has_prod a\" \"a \\<noteq> 0\"\n  shows \"f k \\<noteq> 0\"\n  using assms by (auto simp: has_prod_def raw_has_prod_def LIMSEQ_prod_0 LIMSEQ_unique)\n\nlemma has_prod_le:\n  assumes f: \"f has_prod a\" and g: \"g has_prod b\" and le: \"\\<And>n. 0 \\<le> f n \\<and> f n \\<le> g n\"\n  shows \"a \\<le> b\"\nproof (cases \"a=0 \\<or> b=0\")\n  case True\n  then show ?thesis\n  proof\n    assume [simp]: \"a=0\"\n    have \"b \\<ge> 0\"\n    proof (rule LIMSEQ_prod_nonneg)\n      show \"(\\<lambda>n. prod g {..n}) \\<longlonglongrightarrow> b\"\n        using g by (auto simp: has_prod_def raw_has_prod_def LIMSEQ_prod_0)\n    qed (use le order_trans in auto)\n    then show ?thesis\n      by auto\n  next\n    assume [simp]: \"b=0\"\n    then obtain i where \"g i = 0\"    \n      using g by (auto simp: prod_defs)\n    then have \"f i = 0\"\n      using antisym le by force\n    then have \"a=0\"\n      using f by (auto simp: prod_defs LIMSEQ_prod_0 LIMSEQ_unique)\n    then show ?thesis\n      by auto\n  qed\nnext\n  case False\n  then show ?thesis\n    using assms\n    unfolding has_prod_def raw_has_prod_def\n    by (force simp: LIMSEQ_prod_0 intro!: LIMSEQ_le prod_mono)\nqed\n\nlemma prodinf_le: \n  assumes f: \"f has_prod a\" and g: \"g has_prod b\" and le: \"\\<And>n. 0 \\<le> f n \\<and> f n \\<le> g n\"\n  shows \"prodinf f \\<le> prodinf g\"\n  using has_prod_le [OF assms] has_prod_unique f g  by blast\n\nend\n\n\nlemma prod_le_prodinf: \n  fixes f :: \"nat \\<Rightarrow> 'a::{linordered_idom,linorder_topology}\"\n  assumes \"f has_prod a\" \"\\<And>i. 0 \\<le> f i\" \"\\<And>i. i\\<ge>n \\<Longrightarrow> 1 \\<le> f i\"\n  shows \"prod f {..<n} \\<le> prodinf f\"\n  by(rule has_prod_le[OF has_prod_If_finite_set]) (use assms has_prod_unique in auto)\n\nlemma prodinf_nonneg:\n  fixes f :: \"nat \\<Rightarrow> 'a::{linordered_idom,linorder_topology}\"\n  assumes \"f has_prod a\" \"\\<And>i. 1 \\<le> f i\" \n  shows \"1 \\<le> prodinf f\"\n  using prod_le_prodinf[of f a 0] assms\n  by (metis order_trans prod_ge_1 zero_le_one)\n\nlemma prodinf_le_const:\n  fixes f :: \"nat \\<Rightarrow> real\"\n  assumes \"convergent_prod f\" \"\\<And>n. n \\<ge> N \\<Longrightarrow> prod f {..<n} \\<le> x\" \n  shows \"prodinf f \\<le> x\"\n  by (metis lessThan_Suc_atMost assms convergent_prod_LIMSEQ LIMSEQ_le_const2 atMost_iff lessThan_iff less_le)\n\nlemma prodinf_eq_one_iff [simp]: \n  fixes f :: \"nat \\<Rightarrow> real\"\n  assumes f: \"convergent_prod f\" and ge1: \"\\<And>n. 1 \\<le> f n\"\n  shows \"prodinf f = 1 \\<longleftrightarrow> (\\<forall>n. f n = 1)\"\nproof\n  assume \"prodinf f = 1\" \n  then have \"(\\<lambda>n. \\<Prod>i<n. f i) \\<longlonglongrightarrow> 1\"\n    using convergent_prod_LIMSEQ[of f] assms by (simp add: LIMSEQ_lessThan_iff_atMost)\n  then have \"\\<And>i. (\\<Prod>n\\<in>{i}. f n) \\<le> 1\"\n  proof (rule LIMSEQ_le_const)\n    have \"1 \\<le> prod f n\" for n\n      by (simp add: ge1 prod_ge_1)\n    have \"prod f {..<n} = 1\" for n\n      by (metis \\<open>\\<And>n. 1 \\<le> prod f n\\<close> \\<open>prodinf f = 1\\<close> antisym f convergent_prod_has_prod ge1 order_trans prod_le_prodinf zero_le_one)\n    then have \"(\\<Prod>n\\<in>{i}. f n) \\<le> prod f {..<n}\" if \"n \\<ge> Suc i\" for i n\n      by (metis mult.left_neutral order_refl prod.cong prod.neutral_const prod.lessThan_Suc)\n    then show \"\\<exists>N. \\<forall>n\\<ge>N. (\\<Prod>n\\<in>{i}. f n) \\<le> prod f {..<n}\" for i\n      by blast      \n  qed\n  with ge1 show \"\\<forall>n. f n = 1\"\n    by (auto intro!: antisym)\nqed (metis prodinf_zero fun_eq_iff)\n\nlemma prodinf_pos_iff:\n  fixes f :: \"nat \\<Rightarrow> real\"\n  assumes \"convergent_prod f\" \"\\<And>n. 1 \\<le> f n\"\n  shows \"1 < prodinf f \\<longleftrightarrow> (\\<exists>i. 1 < f i)\"\n  using prod_le_prodinf[of f 1] prodinf_eq_one_iff\n  by (metis convergent_prod_has_prod assms less_le prodinf_nonneg)\n\nlemma less_1_prodinf2:\n  fixes f :: \"nat \\<Rightarrow> real\"\n  assumes \"convergent_prod f\" \"\\<And>n. 1 \\<le> f n\" \"1 < f i\"\n  shows \"1 < prodinf f\"\nproof -\n  have \"1 < (\\<Prod>n<Suc i. f n)\"\n    using assms  by (intro less_1_prod2[where i=i]) auto\n  also have \"\\<dots> \\<le> prodinf f\"\n    by (intro prod_le_prodinf) (use assms order_trans zero_le_one in \\<open>blast+\\<close>)\n  finally show ?thesis .\nqed\n\nlemma less_1_prodinf:\n  fixes f :: \"nat \\<Rightarrow> real\"\n  shows \"\\<lbrakk>convergent_prod f; \\<And>n. 1 < f n\\<rbrakk> \\<Longrightarrow> 1 < prodinf f\"\n  by (intro less_1_prodinf2[where i=1]) (auto intro: less_imp_le)\n\nlemma prodinf_nonzero:\n  fixes f :: \"nat \\<Rightarrow> 'a :: {idom,topological_semigroup_mult,t2_space}\"\n  assumes \"convergent_prod f\" \"\\<And>i. f i \\<noteq> 0\"\n  shows \"prodinf f \\<noteq> 0\"\n  by (metis assms convergent_prod_offset_0 has_prod_unique raw_has_prod_def has_prod_def)\n\nlemma less_0_prodinf:\n  fixes f :: \"nat \\<Rightarrow> real\"\n  assumes f: \"convergent_prod f\" and 0: \"\\<And>i. f i > 0\"\n  shows \"0 < prodinf f\"\nproof -\n  have \"prodinf f \\<noteq> 0\"\n    by (metis assms less_irrefl prodinf_nonzero)\n  moreover have \"0 < (\\<Prod>n<i. f n)\" for i\n    by (simp add: 0 prod_pos)\n  then have \"prodinf f \\<ge> 0\"\n    using convergent_prod_LIMSEQ [OF f] LIMSEQ_prod_nonneg 0 less_le by blast\n  ultimately show ?thesis\n    by auto\nqed\n\nlemma prod_less_prodinf2:\n  fixes f :: \"nat \\<Rightarrow> real\"\n  assumes f: \"convergent_prod f\" and 1: \"\\<And>m. m\\<ge>n \\<Longrightarrow> 1 \\<le> f m\" and 0: \"\\<And>m. 0 < f m\" and i: \"n \\<le> i\" \"1 < f i\"\n  shows \"prod f {..<n} < prodinf f\"\nproof -\n  have \"prod f {..<n} \\<le> prod f {..<i}\"\n    by (rule prod_mono2) (use assms less_le in auto)\n  then have \"prod f {..<n} < f i * prod f {..<i}\"\n    using mult_less_le_imp_less[of 1 \"f i\" \"prod f {..<n}\" \"prod f {..<i}\"] assms\n    by (simp add: prod_pos)\n  moreover have \"prod f {..<Suc i} \\<le> prodinf f\"\n    using prod_le_prodinf[of f _ \"Suc i\"]\n    by (meson \"0\" \"1\" Suc_leD convergent_prod_has_prod f \\<open>n \\<le> i\\<close> le_trans less_eq_real_def)\n  ultimately show ?thesis\n    by (metis le_less_trans mult.commute not_le prod.lessThan_Suc)\nqed\n\nlemma prod_less_prodinf:\n  fixes f :: \"nat \\<Rightarrow> real\"\n  assumes f: \"convergent_prod f\" and 1: \"\\<And>m. m\\<ge>n \\<Longrightarrow> 1 < f m\" and 0: \"\\<And>m. 0 < f m\" \n  shows \"prod f {..<n} < prodinf f\"\n  by (meson \"0\" \"1\" f le_less prod_less_prodinf2)\n\nlemma raw_has_prodI_bounded:\n  fixes f :: \"nat \\<Rightarrow> real\"\n  assumes pos: \"\\<And>n. 1 \\<le> f n\"\n    and le: \"\\<And>n. (\\<Prod>i<n. f i) \\<le> x\"\n  shows \"\\<exists>p. raw_has_prod f 0 p\"\n  unfolding raw_has_prod_def add_0_right\nproof (rule exI LIMSEQ_incseq_SUP conjI)+\n  show \"bdd_above (range (\\<lambda>n. prod f {..n}))\"\n    by (metis bdd_aboveI2 le lessThan_Suc_atMost)\n  then have \"(SUP i. prod f {..i}) > 0\"\n    by (metis UNIV_I cSUP_upper less_le_trans pos prod_pos zero_less_one)\n  then show \"(SUP i. prod f {..i}) \\<noteq> 0\"\n    by auto\n  show \"incseq (\\<lambda>n. prod f {..n})\"\n    using pos order_trans [OF zero_le_one] by (auto simp: mono_def intro!: prod_mono2)\nqed\n\nlemma convergent_prodI_nonneg_bounded:\n  fixes f :: \"nat \\<Rightarrow> real\"\n  assumes \"\\<And>n. 1 \\<le> f n\" \"\\<And>n. (\\<Prod>i<n. f i) \\<le> x\"\n  shows \"convergent_prod f\"\n  using convergent_prod_def raw_has_prodI_bounded [OF assms] by blast\n\n\nsubsection\\<^marker>\\<open>tag unimportant\\<close> \\<open>Infinite products on topological spaces\\<close>\n\ncontext\n  fixes f g :: \"nat \\<Rightarrow> 'a::{t2_space,topological_semigroup_mult,idom}\"\nbegin\n\nlemma raw_has_prod_mult: \"\\<lbrakk>raw_has_prod f M a; raw_has_prod g M b\\<rbrakk> \\<Longrightarrow> raw_has_prod (\\<lambda>n. f n * g n) M (a * b)\"\n  by (force simp add: prod.distrib tendsto_mult raw_has_prod_def)\n\nlemma has_prod_mult_nz: \"\\<lbrakk>f has_prod a; g has_prod b; a \\<noteq> 0; b \\<noteq> 0\\<rbrakk> \\<Longrightarrow> (\\<lambda>n. f n * g n) has_prod (a * b)\"\n  by (simp add: raw_has_prod_mult has_prod_def)\n\nend\n\n\ncontext\n  fixes f g :: \"nat \\<Rightarrow> 'a::real_normed_field\"\nbegin\n\nlemma has_prod_mult:\n  assumes f: \"f has_prod a\" and g: \"g has_prod b\"\n  shows \"(\\<lambda>n. f n * g n) has_prod (a * b)\"\n  using f [unfolded has_prod_def]\nproof (elim disjE exE conjE)\n  assume f0: \"raw_has_prod f 0 a\"\n  show ?thesis\n    using g [unfolded has_prod_def]\n  proof (elim disjE exE conjE)\n    assume g0: \"raw_has_prod g 0 b\"\n    with f0 show ?thesis\n      by (force simp add: has_prod_def prod.distrib tendsto_mult raw_has_prod_def)\n  next\n    fix j q\n    assume \"b = 0\" and \"g j = 0\" and q: \"raw_has_prod g (Suc j) q\"\n    obtain p where p: \"raw_has_prod f (Suc j) p\"\n      using f0 raw_has_prod_ignore_initial_segment by blast\n    then have \"Ex (raw_has_prod (\\<lambda>n. f n * g n) (Suc j))\"\n      using q raw_has_prod_mult by blast\n    then show ?thesis\n      using \\<open>b = 0\\<close> \\<open>g j = 0\\<close> has_prod_0_iff by fastforce\n  qed\nnext\n  fix i p\n  assume \"a = 0\" and \"f i = 0\" and p: \"raw_has_prod f (Suc i) p\"\n  show ?thesis\n    using g [unfolded has_prod_def]\n  proof (elim disjE exE conjE)\n    assume g0: \"raw_has_prod g 0 b\"\n    obtain q where q: \"raw_has_prod g (Suc i) q\"\n      using g0 raw_has_prod_ignore_initial_segment by blast\n    then have \"Ex (raw_has_prod (\\<lambda>n. f n * g n) (Suc i))\"\n      using raw_has_prod_mult p by blast\n    then show ?thesis\n      using \\<open>a = 0\\<close> \\<open>f i = 0\\<close> has_prod_0_iff by fastforce\n  next\n    fix j q\n    assume \"b = 0\" and \"g j = 0\" and q: \"raw_has_prod g (Suc j) q\"\n    obtain p' where p': \"raw_has_prod f (Suc (max i j)) p'\"\n      by (metis raw_has_prod_ignore_initial_segment max_Suc_Suc max_def p)\n    moreover\n    obtain q' where q': \"raw_has_prod g (Suc (max i j)) q'\"\n      by (metis raw_has_prod_ignore_initial_segment max.cobounded2 max_Suc_Suc q)\n    ultimately show ?thesis\n      using \\<open>b = 0\\<close> by (simp add: has_prod_def) (metis \\<open>f i = 0\\<close> \\<open>g j = 0\\<close> raw_has_prod_mult max_def)\n  qed\nqed\n\nlemma convergent_prod_mult:\n  assumes f: \"convergent_prod f\" and g: \"convergent_prod g\"\n  shows \"convergent_prod (\\<lambda>n. f n * g n)\"\n  unfolding convergent_prod_def\nproof -\n  obtain M p N q where p: \"raw_has_prod f M p\" and q: \"raw_has_prod g N q\"\n    using convergent_prod_def f g by blast+\n  then obtain p' q' where p': \"raw_has_prod f (max M N) p'\" and q': \"raw_has_prod g (max M N) q'\"\n    by (meson raw_has_prod_ignore_initial_segment max.cobounded1 max.cobounded2)\n  then show \"\\<exists>M p. raw_has_prod (\\<lambda>n. f n * g n) M p\"\n    using raw_has_prod_mult by blast\nqed\n\nlemma prodinf_mult: \"convergent_prod f \\<Longrightarrow> convergent_prod g \\<Longrightarrow> prodinf f * prodinf g = (\\<Prod>n. f n * g n)\"\n  by (intro has_prod_unique has_prod_mult convergent_prod_has_prod)\n\nend\n\ncontext\n  fixes f :: \"'i \\<Rightarrow> nat \\<Rightarrow> 'a::real_normed_field\"\n    and I :: \"'i set\"\nbegin\n\nlemma has_prod_prod: \"(\\<And>i. i \\<in> I \\<Longrightarrow> (f i) has_prod (x i)) \\<Longrightarrow> (\\<lambda>n. \\<Prod>i\\<in>I. f i n) has_prod (\\<Prod>i\\<in>I. x i)\"\n  by (induct I rule: infinite_finite_induct) (auto intro!: has_prod_mult)\n\nlemma prodinf_prod: \"(\\<And>i. i \\<in> I \\<Longrightarrow> convergent_prod (f i)) \\<Longrightarrow> (\\<Prod>n. \\<Prod>i\\<in>I. f i n) = (\\<Prod>i\\<in>I. \\<Prod>n. f i n)\"\n  using has_prod_unique[OF has_prod_prod, OF convergent_prod_has_prod] by simp\n\nlemma convergent_prod_prod: \"(\\<And>i. i \\<in> I \\<Longrightarrow> convergent_prod (f i)) \\<Longrightarrow> convergent_prod (\\<lambda>n. \\<Prod>i\\<in>I. f i n)\"\n  using convergent_prod_has_prod_iff has_prod_prod prodinf_prod by force\n\nend\n\nsubsection\\<^marker>\\<open>tag unimportant\\<close> \\<open>Infinite summability on real normed fields\\<close>\n\ncontext\n  fixes f :: \"nat \\<Rightarrow> 'a::real_normed_field\"\nbegin\n\nlemma raw_has_prod_Suc_iff: \"raw_has_prod f M (a * f M) \\<longleftrightarrow> raw_has_prod (\\<lambda>n. f (Suc n)) M a \\<and> f M \\<noteq> 0\"\nproof -\n  have \"raw_has_prod f M (a * f M) \\<longleftrightarrow> (\\<lambda>i. \\<Prod>j\\<le>Suc i. f (j+M)) \\<longlonglongrightarrow> a * f M \\<and> a * f M \\<noteq> 0\"\n    by (subst filterlim_sequentially_Suc) (simp add: raw_has_prod_def)\n  also have \"\\<dots> \\<longleftrightarrow> (\\<lambda>i. (\\<Prod>j\\<le>i. f (Suc j + M)) * f M) \\<longlonglongrightarrow> a * f M \\<and> a * f M \\<noteq> 0\"\n    by (simp add: ac_simps atMost_Suc_eq_insert_0 image_Suc_atMost prod.atLeast1_atMost_eq lessThan_Suc_atMost\n                  del: prod.cl_ivl_Suc)\n  also have \"\\<dots> \\<longleftrightarrow> raw_has_prod (\\<lambda>n. f (Suc n)) M a \\<and> f M \\<noteq> 0\"\n  proof safe\n    assume tends: \"(\\<lambda>i. (\\<Prod>j\\<le>i. f (Suc j + M)) * f M) \\<longlonglongrightarrow> a * f M\" and 0: \"a * f M \\<noteq> 0\"\n    with tendsto_divide[OF tends tendsto_const, of \"f M\"]    \n    show \"raw_has_prod (\\<lambda>n. f (Suc n)) M a\"\n      by (simp add: raw_has_prod_def)\n  qed (auto intro: tendsto_mult_right simp:  raw_has_prod_def)\n  finally show ?thesis .\nqed\n\nlemma has_prod_Suc_iff:\n  assumes \"f 0 \\<noteq> 0\" shows \"(\\<lambda>n. f (Suc n)) has_prod a \\<longleftrightarrow> f has_prod (a * f 0)\"\nproof (cases \"a = 0\")\n  case True\n  then show ?thesis\n  proof (simp add: has_prod_def, safe)\n    fix i x\n    assume \"f (Suc i) = 0\" and \"raw_has_prod (\\<lambda>n. f (Suc n)) (Suc i) x\"\n    then obtain y where \"raw_has_prod f (Suc (Suc i)) y\"\n      by (metis (no_types) raw_has_prod_eq_0 Suc_n_not_le_n raw_has_prod_Suc_iff raw_has_prod_ignore_initial_segment raw_has_prod_nonzero linear)\n    then show \"\\<exists>i. f i = 0 \\<and> Ex (raw_has_prod f (Suc i))\"\n      using \\<open>f (Suc i) = 0\\<close> by blast\n  next\n    fix i x\n    assume \"f i = 0\" and x: \"raw_has_prod f (Suc i) x\"\n    then obtain j where j: \"i = Suc j\"\n      by (metis assms not0_implies_Suc)\n    moreover have \"\\<exists> y. raw_has_prod (\\<lambda>n. f (Suc n)) i y\"\n      using x by (auto simp: raw_has_prod_def)\n    then show \"\\<exists>i. f (Suc i) = 0 \\<and> Ex (raw_has_prod (\\<lambda>n. f (Suc n)) (Suc i))\"\n      using \\<open>f i = 0\\<close> j by blast\n  qed\nnext\n  case False\n  then show ?thesis\n    by (auto simp: has_prod_def raw_has_prod_Suc_iff assms)\nqed\n\nlemma convergent_prod_Suc_iff [simp]:\n  shows \"convergent_prod (\\<lambda>n. f (Suc n)) = convergent_prod f\"\nproof\n  assume \"convergent_prod f\"\n  then obtain M L where M_nz:\"\\<forall>n\\<ge>M. f n \\<noteq> 0\" and \n        M_L:\"(\\<lambda>n. \\<Prod>i\\<le>n. f (i + M)) \\<longlonglongrightarrow> L\" and \"L \\<noteq> 0\" \n    unfolding convergent_prod_altdef by auto\n  have \"(\\<lambda>n. \\<Prod>i\\<le>n. f (Suc (i + M))) \\<longlonglongrightarrow> L / f M\"\n  proof -\n    have \"(\\<lambda>n. \\<Prod>i\\<in>{0..Suc n}. f (i + M)) \\<longlonglongrightarrow> L\"\n      using M_L \n      apply (subst (asm) filterlim_sequentially_Suc[symmetric]) \n      using atLeast0AtMost by auto\n    then have \"(\\<lambda>n. f M * (\\<Prod>i\\<in>{0..n}. f (Suc (i + M)))) \\<longlonglongrightarrow> L\"\n      apply (subst (asm) prod.atLeast0_atMost_Suc_shift)\n      by simp\n    then have \"(\\<lambda>n. (\\<Prod>i\\<in>{0..n}. f (Suc (i + M)))) \\<longlonglongrightarrow> L/f M\"\n      apply (drule_tac tendsto_divide)\n      using M_nz[rule_format,of M,simplified] by auto\n    then show ?thesis unfolding atLeast0AtMost .\n  qed\n  then show \"convergent_prod (\\<lambda>n. f (Suc n))\" unfolding convergent_prod_altdef\n    apply (rule_tac exI[where x=M])\n    apply (rule_tac exI[where x=\"L/f M\"])\n    using M_nz \\<open>L\\<noteq>0\\<close> by auto\nnext\n  assume \"convergent_prod (\\<lambda>n. f (Suc n))\"\n  then obtain M where \"\\<exists>L. (\\<forall>n\\<ge>M. f (Suc n) \\<noteq> 0) \\<and> (\\<lambda>n. \\<Prod>i\\<le>n. f (Suc (i + M))) \\<longlonglongrightarrow> L \\<and> L \\<noteq> 0\"\n    unfolding convergent_prod_altdef by auto\n  then show \"convergent_prod f\" unfolding convergent_prod_altdef\n    apply (rule_tac exI[where x=\"Suc M\"])\n    using Suc_le_D by auto\nqed\n\nlemma raw_has_prod_inverse: \n  assumes \"raw_has_prod f M a\" shows \"raw_has_prod (\\<lambda>n. inverse (f n)) M (inverse a)\"\n  using assms unfolding raw_has_prod_def by (auto dest: tendsto_inverse simp: prod_inversef [symmetric])\n\nlemma has_prod_inverse: \n  assumes \"f has_prod a\" shows \"(\\<lambda>n. inverse (f n)) has_prod (inverse a)\"\nusing assms raw_has_prod_inverse unfolding has_prod_def by auto \n\nlemma convergent_prod_inverse:\n  assumes \"convergent_prod f\" \n  shows \"convergent_prod (\\<lambda>n. inverse (f n))\"\n  using assms unfolding convergent_prod_def  by (blast intro: raw_has_prod_inverse elim: )\n\nend\n\ncontext \n  fixes f :: \"nat \\<Rightarrow> 'a::real_normed_field\"\nbegin\n\nlemma raw_has_prod_Suc_iff': \"raw_has_prod f M a \\<longleftrightarrow> raw_has_prod (\\<lambda>n. f (Suc n)) M (a / f M) \\<and> f M \\<noteq> 0\"\n  by (metis raw_has_prod_eq_0 add.commute add.left_neutral raw_has_prod_Suc_iff raw_has_prod_nonzero le_add1 nonzero_mult_div_cancel_right times_divide_eq_left)\n\nlemma has_prod_divide: \"f has_prod a \\<Longrightarrow> g has_prod b \\<Longrightarrow> (\\<lambda>n. f n / g n) has_prod (a / b)\"\n  unfolding divide_inverse by (intro has_prod_inverse has_prod_mult)\n\nlemma convergent_prod_divide:\n  assumes f: \"convergent_prod f\" and g: \"convergent_prod g\"\n  shows \"convergent_prod (\\<lambda>n. f n / g n)\"\n  using f g has_prod_divide has_prod_iff by blast\n\nlemma prodinf_divide: \"convergent_prod f \\<Longrightarrow> convergent_prod g \\<Longrightarrow> prodinf f / prodinf g = (\\<Prod>n. f n / g n)\"\n  by (intro has_prod_unique has_prod_divide convergent_prod_has_prod)\n\nlemma prodinf_inverse: \"convergent_prod f \\<Longrightarrow> (\\<Prod>n. inverse (f n)) = inverse (\\<Prod>n. f n)\"\n  by (intro has_prod_unique [symmetric] has_prod_inverse convergent_prod_has_prod)\n\nlemma has_prod_Suc_imp: \n  assumes \"(\\<lambda>n. f (Suc n)) has_prod a\"\n  shows \"f has_prod (a * f 0)\"\nproof -\n  have \"f has_prod (a * f 0)\" when \"raw_has_prod (\\<lambda>n. f (Suc n)) 0 a\" \n    apply (cases \"f 0=0\")\n    using that unfolding has_prod_def raw_has_prod_Suc \n    by (auto simp add: raw_has_prod_Suc_iff)\n  moreover have \"f has_prod (a * f 0)\" when \n    \"(\\<exists>i q. a = 0 \\<and> f (Suc i) = 0 \\<and> raw_has_prod (\\<lambda>n. f (Suc n)) (Suc i) q)\" \n  proof -\n    from that \n    obtain i q where \"a = 0\" \"f (Suc i) = 0\" \"raw_has_prod (\\<lambda>n. f (Suc n)) (Suc i) q\"\n      by auto\n    then show ?thesis unfolding has_prod_def \n      by (auto intro!:exI[where x=\"Suc i\"] simp:raw_has_prod_Suc)\n  qed\n  ultimately show \"f has_prod (a * f 0)\" using assms unfolding has_prod_def by auto\nqed\n\nlemma has_prod_iff_shift: \n  assumes \"\\<And>i. i < n \\<Longrightarrow> f i \\<noteq> 0\"\n  shows \"(\\<lambda>i. f (i + n)) has_prod a \\<longleftrightarrow> f has_prod (a * (\\<Prod>i<n. f i))\"\n  using assms\nproof (induct n arbitrary: a)\n  case 0\n  then show ?case by simp\nnext\n  case (Suc n)\n  then have \"(\\<lambda>i. f (Suc i + n)) has_prod a \\<longleftrightarrow> (\\<lambda>i. f (i + n)) has_prod (a * f n)\"\n    by (subst has_prod_Suc_iff) auto\n  with Suc show ?case\n    by (simp add: ac_simps)\nqed\n\ncorollary\\<^marker>\\<open>tag unimportant\\<close> has_prod_iff_shift':\n  assumes \"\\<And>i. i < n \\<Longrightarrow> f i \\<noteq> 0\"\n  shows \"(\\<lambda>i. f (i + n)) has_prod (a / (\\<Prod>i<n. f i)) \\<longleftrightarrow> f has_prod a\"\n  by (simp add: assms has_prod_iff_shift)\n\nlemma has_prod_one_iff_shift:\n  assumes \"\\<And>i. i < n \\<Longrightarrow> f i = 1\"\n  shows \"(\\<lambda>i. f (i+n)) has_prod a \\<longleftrightarrow> (\\<lambda>i. f i) has_prod a\"\n  by (simp add: assms has_prod_iff_shift)\n\nlemma convergent_prod_iff_shift [simp]:\n  shows \"convergent_prod (\\<lambda>i. f (i + n)) \\<longleftrightarrow> convergent_prod f\"\n  apply safe\n  using convergent_prod_offset apply blast\n  using convergent_prod_ignore_initial_segment convergent_prod_def by blast\n\nlemma has_prod_split_initial_segment:\n  assumes \"f has_prod a\" \"\\<And>i. i < n \\<Longrightarrow> f i \\<noteq> 0\"\n  shows \"(\\<lambda>i. f (i + n)) has_prod (a / (\\<Prod>i<n. f i))\"\n  using assms has_prod_iff_shift' by blast\n\nlemma prodinf_divide_initial_segment:\n  assumes \"convergent_prod f\" \"\\<And>i. i < n \\<Longrightarrow> f i \\<noteq> 0\"\n  shows \"(\\<Prod>i. f (i + n)) = (\\<Prod>i. f i) / (\\<Prod>i<n. f i)\"\n  by (rule has_prod_unique[symmetric]) (auto simp: assms has_prod_iff_shift)\n\nlemma prodinf_split_initial_segment:\n  assumes \"convergent_prod f\" \"\\<And>i. i < n \\<Longrightarrow> f i \\<noteq> 0\"\n  shows \"prodinf f = (\\<Prod>i. f (i + n)) * (\\<Prod>i<n. f i)\"\n  by (auto simp add: assms prodinf_divide_initial_segment)\n\nlemma prodinf_split_head:\n  assumes \"convergent_prod f\" \"f 0 \\<noteq> 0\"\n  shows \"(\\<Prod>n. f (Suc n)) = prodinf f / f 0\"\n  using prodinf_split_initial_segment[of 1] assms by simp\n\nlemma has_prod_ignore_initial_segment':\n  assumes \"convergent_prod f\"\n  shows   \"f has_prod ((\\<Prod>k<n. f k) * (\\<Prod>k. f (k + n)))\"\nproof (cases \"\\<exists>k<n. f k = 0\")\n  case True\n  hence [simp]: \"(\\<Prod>k<n. f k) = 0\"\n    by (meson finite_lessThan lessThan_iff prod_zero)\n  thus ?thesis using True assms\n    by (metis convergent_prod_has_prod_iff has_prod_zeroI mult_not_zero)\nnext\n  case False\n  hence \"(\\<lambda>i. f (i + n)) has_prod (prodinf f / prod f {..<n})\"\n    using assms by (intro has_prod_split_initial_segment) (auto simp: convergent_prod_has_prod_iff)\n  hence \"prodinf f = prod f {..<n} * (\\<Prod>k. f (k + n))\"\n    using False by (simp add: has_prod_iff divide_simps mult_ac)\n  thus ?thesis\n    using assms by (simp add: convergent_prod_has_prod_iff)\nqed\n\nend\n\ncontext \n  fixes f :: \"nat \\<Rightarrow> 'a::real_normed_field\"\nbegin\n\nlemma convergent_prod_inverse_iff [simp]: \"convergent_prod (\\<lambda>n. inverse (f n)) \\<longleftrightarrow> convergent_prod f\"\n  by (auto dest: convergent_prod_inverse)\n\nlemma convergent_prod_const_iff [simp]:\n  fixes c :: \"'a :: {real_normed_field}\"\n  shows \"convergent_prod (\\<lambda>_. c) \\<longleftrightarrow> c = 1\"\nproof\n  assume \"convergent_prod (\\<lambda>_. c)\"\n  then show \"c = 1\"\n    using convergent_prod_imp_LIMSEQ LIMSEQ_unique by blast \nnext\n  assume \"c = 1\"\n  then show \"convergent_prod (\\<lambda>_. c)\"\n    by auto\nqed\n\nlemma has_prod_power: \"f has_prod a \\<Longrightarrow> (\\<lambda>i. f i ^ n) has_prod (a ^ n)\"\n  by (induction n) (auto simp: has_prod_mult)\n\nlemma convergent_prod_power: \"convergent_prod f \\<Longrightarrow> convergent_prod (\\<lambda>i. f i ^ n)\"\n  by (induction n) (auto simp: convergent_prod_mult)\n\nlemma prodinf_power: \"convergent_prod f \\<Longrightarrow> prodinf (\\<lambda>i. f i ^ n) = prodinf f ^ n\"\n  by (metis has_prod_unique convergent_prod_imp_has_prod has_prod_power)\n\nend\n\n\nsubsection\\<open>Exponentials and logarithms\\<close>\n\ncontext \n  fixes f :: \"nat \\<Rightarrow> 'a::{real_normed_field,banach}\"\nbegin\n\nlemma sums_imp_has_prod_exp: \n  assumes \"f sums s\"\n  shows \"raw_has_prod (\\<lambda>i. exp (f i)) 0 (exp s)\"\n  using assms continuous_on_exp [of UNIV \"\\<lambda>x::'a. x\"]\n  using continuous_on_tendsto_compose [of UNIV exp \"(\\<lambda>n. sum f {..n})\" s]\n  by (simp add: prod_defs sums_def_le exp_sum)\n\nlemma convergent_prod_exp: \n  assumes \"summable f\"\n  shows \"convergent_prod (\\<lambda>i. exp (f i))\"\n  using sums_imp_has_prod_exp assms unfolding summable_def convergent_prod_def  by blast\n\nlemma prodinf_exp: \n  assumes \"summable f\"\n  shows \"prodinf (\\<lambda>i. exp (f i)) = exp (suminf f)\"\nproof -\n  have \"f sums suminf f\"\n    using assms by blast\n  then have \"(\\<lambda>i. exp (f i)) has_prod exp (suminf f)\"\n    by (simp add: has_prod_def sums_imp_has_prod_exp)\n  then show ?thesis\n    by (rule has_prod_unique [symmetric])\nqed\n\nend\n\ntheorem convergent_prod_iff_summable_real:\n  fixes a :: \"nat \\<Rightarrow> real\"\n  assumes \"\\<And>n. a n > 0\"\n  shows \"convergent_prod (\\<lambda>k. 1 + a k) \\<longleftrightarrow> summable a\" (is \"?lhs = ?rhs\")\nproof\n  assume ?lhs\n  then obtain p where \"raw_has_prod (\\<lambda>k. 1 + a k) 0 p\"\n    by (metis assms add_less_same_cancel2 convergent_prod_offset_0 not_one_less_zero)\n  then have to_p: \"(\\<lambda>n. \\<Prod>k\\<le>n. 1 + a k) \\<longlonglongrightarrow> p\"\n    by (auto simp: raw_has_prod_def)\n  moreover have le: \"(\\<Sum>k\\<le>n. a k) \\<le> (\\<Prod>k\\<le>n. 1 + a k)\" for n\n    by (rule sum_le_prod) (use assms less_le in force)\n  have \"(\\<Prod>k\\<le>n. 1 + a k) \\<le> p\" for n\n  proof (rule incseq_le [OF _ to_p])\n    show \"incseq (\\<lambda>n. \\<Prod>k\\<le>n. 1 + a k)\"\n      using assms by (auto simp: mono_def order.strict_implies_order intro!: prod_mono2)\n  qed\n  with le have \"(\\<Sum>k\\<le>n. a k) \\<le> p\" for n\n    by (metis order_trans)\n  with assms bounded_imp_summable show ?rhs\n    by (metis not_less order.asym)\nnext\n  assume R: ?rhs\n  have \"(\\<Prod>k\\<le>n. 1 + a k) \\<le> exp (suminf a)\" for n\n  proof -\n    have \"(\\<Prod>k\\<le>n. 1 + a k) \\<le> exp (\\<Sum>k\\<le>n. a k)\" for n\n      by (rule prod_le_exp_sum) (use assms less_le in force)\n    moreover have \"exp (\\<Sum>k\\<le>n. a k) \\<le> exp (suminf a)\" for n\n      unfolding exp_le_cancel_iff\n      by (meson sum_le_suminf R assms finite_atMost less_eq_real_def)\n    ultimately show ?thesis\n      by (meson order_trans)\n  qed\n  then obtain L where L: \"(\\<lambda>n. \\<Prod>k\\<le>n. 1 + a k) \\<longlonglongrightarrow> L\"\n    by (metis assms bounded_imp_convergent_prod convergent_prod_iff_nz_lim le_add_same_cancel1 le_add_same_cancel2 less_le not_le zero_le_one)\n  moreover have \"L \\<noteq> 0\"\n  proof\n    assume \"L = 0\"\n    with L have \"(\\<lambda>n. \\<Prod>k\\<le>n. 1 + a k) \\<longlonglongrightarrow> 0\"\n      by simp\n    moreover have \"(\\<Prod>k\\<le>n. 1 + a k) > 1\" for n\n      by (simp add: assms less_1_prod)\n    ultimately show False\n      by (meson Lim_bounded2 not_one_le_zero less_imp_le)\n  qed\n  ultimately show ?lhs\n    using assms convergent_prod_iff_nz_lim\n    by (metis add_less_same_cancel1 less_le not_le zero_less_one)\nqed\n\nlemma exp_suminf_prodinf_real:\n  fixes f :: \"nat \\<Rightarrow> real\"\n  assumes ge0:\"\\<And>n. f n \\<ge> 0\" and ac: \"abs_convergent_prod (\\<lambda>n. exp (f n))\"\n  shows \"prodinf (\\<lambda>i. exp (f i)) = exp (suminf f)\"\nproof -\n  have \"summable f\"\n    using ac unfolding abs_convergent_prod_conv_summable\n  proof (elim summable_comparison_test')\n    fix n\n    have \"\\<bar>f n\\<bar> = f n\"\n      by (simp add: ge0)\n    also have \"\\<dots> \\<le> exp (f n) - 1\"\n      by (metis diff_diff_add exp_ge_add_one_self ge_iff_diff_ge_0)\n    finally show \"norm (f n) \\<le> norm (exp (f n) - 1)\"\n      by simp\n  qed\n  then show ?thesis\n    by (simp add: prodinf_exp)\nqed\n\nlemma has_prod_imp_sums_ln_real: \n  fixes f :: \"nat \\<Rightarrow> real\"\n  assumes \"raw_has_prod f 0 p\" and 0: \"\\<And>x. f x > 0\"\n  shows \"(\\<lambda>i. ln (f i)) sums (ln p)\"\nproof -\n  have \"p > 0\"\n    using assms unfolding prod_defs by (metis LIMSEQ_prod_nonneg less_eq_real_def)\n  then show ?thesis\n  using assms continuous_on_ln [of \"{0<..}\" \"\\<lambda>x. x\"]\n  using continuous_on_tendsto_compose [of \"{0<..}\" ln \"(\\<lambda>n. prod f {..n})\" p]\n  by (auto simp: prod_defs sums_def_le ln_prod order_tendstoD)\nqed\n\nlemma summable_ln_real: \n  fixes f :: \"nat \\<Rightarrow> real\"\n  assumes f: \"convergent_prod f\" and 0: \"\\<And>x. f x > 0\"\n  shows \"summable (\\<lambda>i. ln (f i))\"\nproof -\n  obtain M p where \"raw_has_prod f M p\"\n    using f convergent_prod_def by blast\n  then consider i where \"i<M\" \"f i = 0\" | p where \"raw_has_prod f 0 p\"\n    using raw_has_prod_cases by blast\n  then show ?thesis\n  proof cases\n    case 1\n    with 0 show ?thesis\n      by (metis less_irrefl)\n  next\n    case 2\n    then show ?thesis\n      using \"0\" has_prod_imp_sums_ln_real summable_def by blast\n  qed\nqed\n\nlemma suminf_ln_real: \n  fixes f :: \"nat \\<Rightarrow> real\"\n  assumes f: \"convergent_prod f\" and 0: \"\\<And>x. f x > 0\"\n  shows \"suminf (\\<lambda>i. ln (f i)) = ln (prodinf f)\"\nproof -\n  have \"f has_prod prodinf f\"\n    by (simp add: f has_prod_iff)\n  then have \"raw_has_prod f 0 (prodinf f)\"\n    by (metis \"0\" has_prod_def less_irrefl)\n  then have \"(\\<lambda>i. ln (f i)) sums ln (prodinf f)\"\n    using \"0\" has_prod_imp_sums_ln_real by blast\n  then show ?thesis\n    by (rule sums_unique [symmetric])\nqed\n\nlemma prodinf_exp_real: \n  fixes f :: \"nat \\<Rightarrow> real\"\n  assumes f: \"convergent_prod f\" and 0: \"\\<And>x. f x > 0\"\n  shows \"prodinf f = exp (suminf (\\<lambda>i. ln (f i)))\"\n  by (simp add: \"0\" f less_0_prodinf suminf_ln_real)\n\n\ntheorem Ln_prodinf_complex:\n  fixes z :: \"nat \\<Rightarrow> complex\"\n  assumes z: \"\\<And>j. z j \\<noteq> 0\" and \\<xi>: \"\\<xi> \\<noteq> 0\"\n  shows \"((\\<lambda>n. \\<Prod>j\\<le>n. z j) \\<longlonglongrightarrow> \\<xi>) \\<longleftrightarrow> (\\<exists>k. (\\<lambda>n. (\\<Sum>j\\<le>n. Ln (z j))) \\<longlonglongrightarrow> Ln \\<xi> + of_int k * (of_real(2*pi) * \\<i>))\" (is \"?lhs = ?rhs\")\nproof\n  assume L: ?lhs\n  have pnz: \"(\\<Prod>j\\<le>n. z j) \\<noteq> 0\" for n\n    using z by auto\n  define \\<Theta> where \"\\<Theta> \\<equiv> Arg \\<xi> + 2*pi\"\n  then have \"\\<Theta> > pi\"\n    using Arg_def mpi_less_Im_Ln by fastforce\n  have \\<xi>_eq: \"\\<xi> = cmod \\<xi> * exp (\\<i> * \\<Theta>)\"\n    using Arg_def Arg_eq \\<xi> unfolding \\<Theta>_def by (simp add: algebra_simps exp_add)\n  define \\<theta> where \"\\<theta> \\<equiv> \\<lambda>n. THE t. is_Arg (\\<Prod>j\\<le>n. z j) t \\<and> t \\<in> {\\<Theta>-pi<..\\<Theta>+pi}\"\n  have uniq: \"\\<exists>!s. is_Arg (\\<Prod>j\\<le>n. z j) s \\<and> s \\<in> {\\<Theta>-pi<..\\<Theta>+pi}\" for n\n    using Argument_exists_unique [OF pnz] by metis\n  have \\<theta>: \"is_Arg (\\<Prod>j\\<le>n. z j) (\\<theta> n)\" and \\<theta>_interval: \"\\<theta> n \\<in> {\\<Theta>-pi<..\\<Theta>+pi}\" for n\n    unfolding \\<theta>_def\n    using theI' [OF uniq] by metis+\n  have \\<theta>_pos: \"\\<And>j. \\<theta> j > 0\"\n    using \\<theta>_interval \\<open>\\<Theta> > pi\\<close> by simp (meson diff_gt_0_iff_gt less_trans)\n  have \"(\\<Prod>j\\<le>n. z j) = cmod (\\<Prod>j\\<le>n. z j) * exp (\\<i> * \\<theta> n)\" for n\n    using \\<theta> by (auto simp: is_Arg_def)\n  then have eq: \"(\\<lambda>n. \\<Prod>j\\<le>n. z j) = (\\<lambda>n. cmod (\\<Prod>j\\<le>n. z j) * exp (\\<i> * \\<theta> n))\"\n    by simp\n  then have \"(\\<lambda>n. (cmod (\\<Prod>j\\<le>n. z j)) * exp (\\<i> * (\\<theta> n))) \\<longlonglongrightarrow> \\<xi>\"\n    using L by force\n  then obtain k where k: \"(\\<lambda>j. \\<theta> j - of_int (k j) * (2 * pi)) \\<longlonglongrightarrow> \\<Theta>\"\n    using L by (subst (asm) \\<xi>_eq) (auto simp add: eq z \\<xi> polar_convergence)\n  moreover have \"\\<forall>\\<^sub>F n in sequentially. k n = 0\"\n  proof -\n    have *: \"kj = 0\" if \"dist (vj - real_of_int kj * 2) V < 1\" \"vj \\<in> {V - 1<..V + 1}\" for kj vj V\n      using that  by (auto simp: dist_norm)\n    have \"\\<forall>\\<^sub>F j in sequentially. dist (\\<theta> j - of_int (k j) * (2 * pi)) \\<Theta> < pi\"\n      using tendstoD [OF k] pi_gt_zero by blast\n    then show ?thesis\n    proof (rule eventually_mono)\n      fix j\n      assume d: \"dist (\\<theta> j - real_of_int (k j) * (2 * pi)) \\<Theta> < pi\"\n      show \"k j = 0\"\n        by (rule * [of \"\\<theta> j/pi\" _ \"\\<Theta>/pi\"])\n           (use \\<theta>_interval [of j] d in \\<open>simp_all add: divide_simps dist_norm\\<close>)\n    qed\n  qed\n  ultimately have \\<theta>to\\<Theta>: \"\\<theta> \\<longlonglongrightarrow> \\<Theta>\"\n    apply (simp only: tendsto_def)\n    apply (erule all_forward imp_forward asm_rl)+\n    apply (drule (1) eventually_conj)\n    apply (auto elim: eventually_mono)\n    done\n  then have to0: \"(\\<lambda>n. \\<bar>\\<theta> (Suc n) - \\<theta> n\\<bar>) \\<longlonglongrightarrow> 0\"\n    by (metis (full_types) diff_self filterlim_sequentially_Suc tendsto_diff tendsto_rabs_zero)\n  have \"\\<exists>k. Im (\\<Sum>j\\<le>n. Ln (z j)) - of_int k * (2*pi) = \\<theta> n\" for n\n  proof (rule is_Arg_exp_diff_2pi)\n    show \"is_Arg (exp (\\<Sum>j\\<le>n. Ln (z j))) (\\<theta> n)\"\n      using pnz \\<theta> by (simp add: is_Arg_def exp_sum prod_norm)\n  qed\n  then have \"\\<exists>k. (\\<Sum>j\\<le>n. Im (Ln (z j))) = \\<theta> n + of_int k * (2*pi)\" for n\n    by (simp add: algebra_simps)\n  then obtain k where k: \"\\<And>n. (\\<Sum>j\\<le>n. Im (Ln (z j))) = \\<theta> n + of_int (k n) * (2*pi)\"\n    by metis\n  obtain K where \"\\<forall>\\<^sub>F n in sequentially. k n = K\"\n  proof -\n    have k_le: \"(2*pi) * \\<bar>k (Suc n) - k n\\<bar> \\<le> \\<bar>\\<theta> (Suc n) - \\<theta> n\\<bar> + \\<bar>Im (Ln (z (Suc n)))\\<bar>\" for n\n    proof -\n      have \"(\\<Sum>j\\<le>Suc n. Im (Ln (z j))) - (\\<Sum>j\\<le>n. Im (Ln (z j))) = Im (Ln (z (Suc n)))\"\n        by simp\n      then show ?thesis\n        using k [of \"Suc n\"] k [of n] by (auto simp: abs_if algebra_simps)\n    qed\n    have \"z \\<longlonglongrightarrow> 1\"\n      using L \\<xi> convergent_prod_iff_nz_lim z by (blast intro: convergent_prod_imp_LIMSEQ)\n    with z have \"(\\<lambda>n. Ln (z n)) \\<longlonglongrightarrow> Ln 1\"\n      using isCont_tendsto_compose [OF continuous_at_Ln] nonpos_Reals_one_I by blast\n    then have \"(\\<lambda>n. Ln (z n)) \\<longlonglongrightarrow> 0\"\n      by simp\n    then have \"(\\<lambda>n. \\<bar>Im (Ln (z (Suc n)))\\<bar>) \\<longlonglongrightarrow> 0\"\n      by (metis LIMSEQ_unique \\<open>z \\<longlonglongrightarrow> 1\\<close> continuous_at_Ln filterlim_sequentially_Suc isCont_tendsto_compose nonpos_Reals_one_I tendsto_Im tendsto_rabs_zero_iff zero_complex.simps(2))\n    then have \"\\<forall>\\<^sub>F n in sequentially. \\<bar>Im (Ln (z (Suc n)))\\<bar> < 1\"\n      by (simp add: order_tendsto_iff)\n    moreover have \"\\<forall>\\<^sub>F n in sequentially. \\<bar>\\<theta> (Suc n) - \\<theta> n\\<bar> < 1\"\n      using to0 by (simp add: order_tendsto_iff)\n    ultimately have \"\\<forall>\\<^sub>F n in sequentially. (2*pi) * \\<bar>k (Suc n) - k n\\<bar> < 1 + 1\" \n    proof (rule eventually_elim2) \n      fix n \n      assume \"\\<bar>Im (Ln (z (Suc n)))\\<bar> < 1\" and \"\\<bar>\\<theta> (Suc n) - \\<theta> n\\<bar> < 1\"\n      with k_le [of n] show \"2 * pi * real_of_int \\<bar>k (Suc n) - k n\\<bar> < 1 + 1\"\n        by linarith\n    qed\n    then have \"\\<forall>\\<^sub>F n in sequentially. real_of_int\\<bar>k (Suc n) - k n\\<bar> < 1\" \n    proof (rule eventually_mono)\n      fix n :: \"nat\"\n      assume \"2 * pi * \\<bar>k (Suc n) - k n\\<bar> < 1 + 1\"\n      then have \"\\<bar>k (Suc n) - k n\\<bar> < 2 / (2*pi)\"\n        by (simp add: field_simps)\n      also have \"... < 1\"\n        using pi_ge_two by auto\n      finally show \"real_of_int \\<bar>k (Suc n) - k n\\<bar> < 1\" .\n    qed\n  then obtain N where N: \"\\<And>n. n\\<ge>N \\<Longrightarrow> \\<bar>k (Suc n) - k n\\<bar> = 0\"\n    using eventually_sequentially less_irrefl of_int_abs by fastforce\n  have \"k (N+i) = k N\" for i\n  proof (induction i)\n    case (Suc i)\n    with N [of \"N+i\"] show ?case\n      by auto\n  qed simp\n  then have \"\\<And>n. n\\<ge>N \\<Longrightarrow> k n = k N\"\n    using le_Suc_ex by auto\n  then show ?thesis\n    by (force simp add: eventually_sequentially intro: that)\n  qed\n  with \\<theta>to\\<Theta> have \"(\\<lambda>n. (\\<Sum>j\\<le>n. Im (Ln (z j)))) \\<longlonglongrightarrow> \\<Theta> + of_int K * (2*pi)\"\n    by (simp add: k tendsto_add tendsto_mult tendsto_eventually)\n  moreover have \"(\\<lambda>n. (\\<Sum>k\\<le>n. Re (Ln (z k)))) \\<longlonglongrightarrow> Re (Ln \\<xi>)\"\n    using assms continuous_imp_tendsto [OF isCont_ln tendsto_norm [OF L]]\n    by (simp add: o_def flip: prod_norm ln_prod)\n  ultimately show ?rhs\n    by (rule_tac x=\"K+1\" in exI) (auto simp: tendsto_complex_iff \\<Theta>_def Arg_def assms algebra_simps)\nnext\n  assume ?rhs\n  then obtain r where r: \"(\\<lambda>n. (\\<Sum>k\\<le>n. Ln (z k))) \\<longlonglongrightarrow> Ln \\<xi> + of_int r * (of_real(2*pi) * \\<i>)\" ..\n  have \"(\\<lambda>n. exp (\\<Sum>k\\<le>n. Ln (z k))) \\<longlonglongrightarrow> \\<xi>\"\n    using assms continuous_imp_tendsto [OF isCont_exp r] exp_integer_2pi [of r]\n    by (simp add: o_def exp_add algebra_simps)\n  moreover have \"exp (\\<Sum>k\\<le>n. Ln (z k)) = (\\<Prod>k\\<le>n. z k)\" for n\n    by (simp add: exp_sum add_eq_0_iff assms)\n  ultimately show ?lhs\n    by auto\nqed\n\ntext\\<open>Prop 17.2 of Bak and Newman, Complex Analysis, p.242\\<close>\nproposition convergent_prod_iff_summable_complex:\n  fixes z :: \"nat \\<Rightarrow> complex\"\n  assumes \"\\<And>k. z k \\<noteq> 0\"\n  shows \"convergent_prod (\\<lambda>k. z k) \\<longleftrightarrow> summable (\\<lambda>k. Ln (z k))\" (is \"?lhs = ?rhs\")\nproof\n  assume ?lhs\n  then obtain p where p: \"(\\<lambda>n. \\<Prod>k\\<le>n. z k) \\<longlonglongrightarrow> p\" and \"p \\<noteq> 0\"\n    using convergent_prod_LIMSEQ prodinf_nonzero add_eq_0_iff assms by fastforce\n  then show ?rhs\n    using Ln_prodinf_complex assms\n    by (auto simp: prodinf_nonzero summable_def sums_def_le)\nnext\n  assume R: ?rhs\n  have \"(\\<Prod>k\\<le>n. z k) = exp (\\<Sum>k\\<le>n. Ln (z k))\" for n\n    by (simp add: exp_sum add_eq_0_iff assms)\n  then have \"(\\<lambda>n. \\<Prod>k\\<le>n. z k) \\<longlonglongrightarrow> exp (suminf (\\<lambda>k. Ln (z k)))\"\n    using continuous_imp_tendsto [OF isCont_exp summable_LIMSEQ' [OF R]] by (simp add: o_def)\n  then show ?lhs\n    by (subst convergent_prod_iff_convergent) (auto simp: convergent_def tendsto_Lim assms add_eq_0_iff)\nqed\n\ntext\\<open>Prop 17.3 of Bak and Newman, Complex Analysis\\<close>\nproposition summable_imp_convergent_prod_complex:\n  fixes z :: \"nat \\<Rightarrow> complex\"\n  assumes z: \"summable (\\<lambda>k. norm (z k))\" and non0: \"\\<And>k. z k \\<noteq> -1\"\n  shows \"convergent_prod (\\<lambda>k. 1 + z k)\" \nproof -\n  obtain N where \"\\<And>k. k\\<ge>N \\<Longrightarrow> norm (z k) < 1/2\"\n    using summable_LIMSEQ_zero [OF z]\n    by (metis diff_zero dist_norm half_gt_zero_iff less_numeral_extra(1) lim_sequentially tendsto_norm_zero_iff)\n  then have \"summable (\\<lambda>k. Ln (1 + z k))\"\n    by (metis norm_Ln_le summable_comparison_test summable_mult z)\n  with non0 show ?thesis\n    by (simp add: add_eq_0_iff convergent_prod_iff_summable_complex)\nqed\n\ncorollary summable_imp_convergent_prod_real:\n  fixes z :: \"nat \\<Rightarrow> real\"\n  assumes z: \"summable (\\<lambda>k. \\<bar>z k\\<bar>)\" and non0: \"\\<And>k. z k \\<noteq> -1\"\n  shows \"convergent_prod (\\<lambda>k. 1 + z k)\" \nproof -\n  have \"\\<And>k. (complex_of_real \\<circ> z) k \\<noteq> - 1\"\n    by (metis non0 o_apply of_real_1 of_real_eq_iff of_real_minus)\n  with z \n  have \"convergent_prod (\\<lambda>k. 1 + (complex_of_real \\<circ> z) k)\"\n    by (auto intro: summable_imp_convergent_prod_complex)\n  then show ?thesis \n    using convergent_prod_of_real_iff [of \"\\<lambda>k. 1 + z k\"] by (simp add: o_def)\nqed\n\nlemma summable_Ln_complex:\n  fixes z :: \"nat \\<Rightarrow> complex\"\n  assumes \"convergent_prod z\" \"\\<And>k. z k \\<noteq> 0\"\n  shows \"summable (\\<lambda>k. Ln (z k))\"\n  using convergent_prod_def assms convergent_prod_iff_summable_complex by blast\n\n\nsubsection\\<^marker>\\<open>tag unimportant\\<close> \\<open>Embeddings from the reals into some complete real normed field\\<close>\n\nlemma tendsto_eq_of_real_lim:\n  assumes \"(\\<lambda>n. of_real (f n) :: 'a::{complete_space,real_normed_field}) \\<longlonglongrightarrow> q\"\n  shows \"q = of_real (lim f)\"\nproof -\n  have \"convergent (\\<lambda>n. of_real (f n) :: 'a)\"\n    using assms convergent_def by blast \n  then have \"convergent f\"\n    unfolding convergent_def\n    by (simp add: convergent_eq_Cauchy Cauchy_def)\n  then show ?thesis\n    by (metis LIMSEQ_unique assms convergentD sequentially_bot tendsto_Lim tendsto_of_real)\nqed\n\nlemma tendsto_eq_of_real:\n  assumes \"(\\<lambda>n. of_real (f n) :: 'a::{complete_space,real_normed_field}) \\<longlonglongrightarrow> q\"\n  obtains r where \"q = of_real r\"\n  using tendsto_eq_of_real_lim assms by blast\n\nlemma has_prod_of_real_iff [simp]:\n  \"(\\<lambda>n. of_real (f n) :: 'a::{complete_space,real_normed_field}) has_prod of_real c \\<longleftrightarrow> f has_prod c\"\n  (is \"?lhs = ?rhs\")\nproof\n  assume ?lhs\n  then show ?rhs\n    apply (auto simp: prod_defs LIMSEQ_prod_0 tendsto_of_real_iff simp flip: of_real_prod)\n    using tendsto_eq_of_real\n    by (metis of_real_0 tendsto_of_real_iff)\nnext\n  assume ?rhs\n  with tendsto_of_real_iff show ?lhs\n    by (fastforce simp: prod_defs simp flip: of_real_prod)\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/Analysis/Infinite_Products.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8705972684083608, "lm_q2_score": 0.8376199673867852, "lm_q1q2_score": 0.7292296555712355}}
{"text": "theory Chapter9_2\nimports \"HOL-IMP.Sec_Typing\" \"Short_Theory\"\nbegin\n\ntext\\<open>\n\\exercise\nReformulate the inductive predicate @{const sec_type}\nas a recursive function and prove the equivalence of the two formulations:\n\\<close>\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\\<open>\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\\<close>\n\ninductive sec_type2' :: \"com \\<Rightarrow> level \\<Rightarrow> bool\" (\"(\\<turnstile>'' _ : _)\" [0,0] 50) where\n(* your definition/proof here *)\n\ntext\\<open>\nProve equivalence with the bottom-up system @{prop \"\\<turnstile> c : l\"} without subsumption rule:\n\\<close>\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\\<open>\n\\endexercise\n\n\\exercise\nDefine a function that erases those parts of a command that\ncontain variables above some security level: \\<close>\n\nfun erase :: \"level \\<Rightarrow> com \\<Rightarrow> com\" where\n(* your definition/proof here *)\n\ntext\\<open>\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}: \\<close>\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\\<open> 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: \\<close>\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\\<open> Give proofs or counterexamples.\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/Chapter9_2.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8705972751232809, "lm_q2_score": 0.8376199592797929, "lm_q1q2_score": 0.7292296541378612}}
{"text": "theory Opcionales\nimports Main\nbegin\n\ntext {* (busca ps x) es el segundo elemento del primer par de ps cuyo\n  primer elemento es x y None si ning\u00fan elemento de ps tiene un primer\n  elemento igual a x. Por ejemplo,\n     busca [(1::int,2::int),(3,6)] 3 = Some 6\n     busca [(1::int,2::int),(3,6)] 2 = None\n*}\nfun busca :: \"('a \\<times> 'b) list \\<Rightarrow> 'a \\<Rightarrow> 'b option\"\nwhere\n  \"busca [] x           = None\" \n| \"busca ((a,b) # ps) x = (if a = x \n                            then Some b \n                            else busca ps x)\"\n\nvalue \"busca [(1::int,2::int),(3,6)] 3\"\nlemma \"busca [(1::int,2::int),(3,6)] 3 = Some 6\" by simp\nvalue \"busca [(1::int,2::int),(3,6)] 2\"\nlemma \"busca [(1::int,2::int),(3,6)] 2 = None\" by simp\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/Opcionales.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8705972616934406, "lm_q2_score": 0.8376199694135332, "lm_q1q2_score": 0.7292296517111655}}
{"text": "(*  Title:      FOL/ex/Classical.thy\n    Author:     Lawrence C Paulson, Cambridge University Computer Laboratory\n    Copyright   1994  University of Cambridge\n*)\n\nsection{*Classical Predicate Calculus Problems*}\n\ntheory Classical imports FOL begin\n\nlemma \"(P --> Q | R) --> (P-->Q) | (P-->R)\"\nby blast\n\ntext{*If and only if*}\n\nlemma \"(P<->Q) <-> (Q<->P)\"\nby blast\n\nlemma \"~ (P <-> ~P)\"\nby blast\n\n\ntext{*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\nThe hardest problems -- judging by experience with several theorem provers,\nincluding matrix ones -- are 34 and 43.\n*}\n\nsubsection{*Pelletier's examples*}\n\ntext{*1*}\nlemma \"(P-->Q)  <->  (~Q --> ~P)\"\nby blast\n\ntext{*2*}\nlemma \"~ ~ P  <->  P\"\nby blast\n\ntext{*3*}\nlemma \"~(P-->Q) --> (Q-->P)\"\nby blast\n\ntext{*4*}\nlemma \"(~P-->Q)  <->  (~Q --> P)\"\nby blast\n\ntext{*5*}\nlemma \"((P|Q)-->(P|R)) --> (P|(Q-->R))\"\nby blast\n\ntext{*6*}\nlemma \"P | ~ P\"\nby blast\n\ntext{*7*}\nlemma \"P | ~ ~ ~ P\"\nby blast\n\ntext{*8.  Peirce's law*}\nlemma \"((P-->Q) --> P)  -->  P\"\nby blast\n\ntext{*9*}\nlemma \"((P|Q) & (~P|Q) & (P| ~Q)) --> ~ (~P | ~Q)\"\nby blast\n\ntext{*10*}\nlemma \"(Q-->R) & (R-->P&Q) & (P-->Q|R) --> (P<->Q)\"\nby blast\n\ntext{*11.  Proved in each direction (incorrectly, says Pelletier!!)  *}\nlemma \"P<->P\"\nby blast\n\ntext{*12.  \"Dijkstra's law\"*}\nlemma \"((P <-> Q) <-> R)  <->  (P <-> (Q <-> R))\"\nby blast\n\ntext{*13.  Distributive law*}\nlemma \"P | (Q & R)  <-> (P | Q) & (P | R)\"\nby blast\n\ntext{*14*}\nlemma \"(P <-> Q) <-> ((Q | ~P) & (~Q|P))\"\nby blast\n\ntext{*15*}\nlemma \"(P --> Q) <-> (~P | Q)\"\nby blast\n\ntext{*16*}\nlemma \"(P-->Q) | (Q-->P)\"\nby blast\n\ntext{*17*}\nlemma \"((P & (Q-->R))-->S) <-> ((~P | Q | S) & (~P | ~R | S))\"\nby blast\n\nsubsection{*Classical Logic: examples with quantifiers*}\n\nlemma \"(\\<forall>x. P(x) & Q(x)) <-> (\\<forall>x. P(x))  &  (\\<forall>x. Q(x))\"\nby blast\n\nlemma \"(\\<exists>x. P-->Q(x))  <->  (P --> (\\<exists>x. Q(x)))\"\nby blast\n\nlemma \"(\\<exists>x. P(x)-->Q)  <->  (\\<forall>x. P(x)) --> Q\"\nby blast\n\nlemma \"(\\<forall>x. P(x)) | Q  <->  (\\<forall>x. P(x) | Q)\"\nby blast\n\ntext{*Discussed in Avron, Gentzen-Type Systems, Resolution and Tableaux,\n  JAR 10 (265-281), 1993.  Proof is trivial!*}\nlemma \"~((\\<exists>x.~P(x)) & ((\\<exists>x. P(x)) | (\\<exists>x. P(x) & Q(x))) & ~ (\\<exists>x. P(x)))\"\nby blast\n\nsubsection{*Problems requiring quantifier duplication*}\n\ntext{*Theorem B of Peter Andrews, Theorem Proving via General Matings, \n  JACM 28 (1981).*}\nlemma \"(\\<exists>x. \\<forall>y. P(x) <-> P(y)) --> ((\\<exists>x. P(x)) <-> (\\<forall>y. P(y)))\"\nby blast\n\ntext{*Needs multiple instantiation of ALL.*}\nlemma \"(\\<forall>x. P(x)-->P(f(x)))  &  P(d)-->P(f(f(f(d))))\"\nby blast\n\ntext{*Needs double instantiation of the quantifier*}\nlemma \"\\<exists>x. P(x) --> P(a) & P(b)\"\nby blast\n\nlemma \"\\<exists>z. P(z) --> (\\<forall>x. P(x))\"\nby blast\n\nlemma \"\\<exists>x. (\\<exists>y. P(y)) --> P(x)\"\nby blast\n\ntext{*V. Lifschitz, What Is the Inverse Method?, JAR 5 (1989), 1--23.  NOT PROVED*}\nlemma \"\\<exists>x x'. \\<forall>y. \\<exists>z z'.  \n                (~P(y,y) | P(x,x) | ~S(z,x)) &  \n                (S(x,y) | ~S(y,z) | Q(z',z'))  &  \n                (Q(x',y) | ~Q(y,z') | S(x',x'))\"\noops\n\n\n\nsubsection{*Hard examples with quantifiers*}\n\ntext{*18*}\nlemma \"\\<exists>y. \\<forall>x. P(y)-->P(x)\"\nby blast\n\ntext{*19*}\nlemma \"\\<exists>x. \\<forall>y z. (P(y)-->Q(z)) --> (P(x)-->Q(x))\"\nby blast\n\ntext{*20*}\nlemma \"(\\<forall>x y. \\<exists>z. \\<forall>w. (P(x)&Q(y)-->R(z)&S(w)))      \n    --> (\\<exists>x y. P(x) & Q(y)) --> (\\<exists>z. R(z))\"\nby blast\n\ntext{*21*}\nlemma \"(\\<exists>x. P-->Q(x)) & (\\<exists>x. Q(x)-->P) --> (\\<exists>x. P<->Q(x))\"\nby blast\n\ntext{*22*}\nlemma \"(\\<forall>x. P <-> Q(x))  -->  (P <-> (\\<forall>x. Q(x)))\"\nby blast\n\ntext{*23*}\nlemma \"(\\<forall>x. P | Q(x))  <->  (P | (\\<forall>x. Q(x)))\"\nby blast\n\ntext{*24*}\nlemma \"~(\\<exists>x. S(x)&Q(x)) & (\\<forall>x. P(x) --> Q(x)|R(x)) &   \n      (~(\\<exists>x. P(x)) --> (\\<exists>x. Q(x))) & (\\<forall>x. Q(x)|R(x) --> S(x))   \n    --> (\\<exists>x. P(x)&R(x))\"\nby blast\n\ntext{*25*}\nlemma \"(\\<exists>x. P(x)) &   \n      (\\<forall>x. L(x) --> ~ (M(x) & R(x))) &   \n      (\\<forall>x. P(x) --> (M(x) & L(x))) &    \n      ((\\<forall>x. P(x)-->Q(x)) | (\\<exists>x. P(x)&R(x)))   \n    --> (\\<exists>x. Q(x)&P(x))\"\nby blast\n\ntext{*26*}\nlemma \"((\\<exists>x. p(x)) <-> (\\<exists>x. q(x))) &  \n      (\\<forall>x. \\<forall>y. p(x) & q(y) --> (r(x) <-> s(y)))    \n  --> ((\\<forall>x. p(x)-->r(x)) <-> (\\<forall>x. q(x)-->s(x)))\"\nby blast\n\ntext{*27*}\nlemma \"(\\<exists>x. P(x) & ~Q(x)) &    \n      (\\<forall>x. P(x) --> R(x)) &    \n      (\\<forall>x. M(x) & L(x) --> P(x)) &    \n      ((\\<exists>x. R(x) & ~ Q(x)) --> (\\<forall>x. L(x) --> ~ R(x)))   \n  --> (\\<forall>x. M(x) --> ~L(x))\"\nby blast\n\ntext{*28.  AMENDED*}\nlemma \"(\\<forall>x. P(x) --> (\\<forall>x. Q(x))) &    \n        ((\\<forall>x. Q(x)|R(x)) --> (\\<exists>x. Q(x)&S(x))) &   \n        ((\\<exists>x. S(x)) --> (\\<forall>x. L(x) --> M(x)))   \n    --> (\\<forall>x. P(x) & L(x) --> M(x))\"\nby blast\n\ntext{*29.  Essentially the same as Principia Mathematica *11.71*}\nlemma \"(\\<exists>x. P(x)) & (\\<exists>y. Q(y))   \n    --> ((\\<forall>x. P(x)-->R(x)) & (\\<forall>y. Q(y)-->S(y))   <->      \n         (\\<forall>x y. P(x) & Q(y) --> R(x) & S(y)))\"\nby blast\n\ntext{*30*}\nlemma \"(\\<forall>x. P(x) | Q(x) --> ~ R(x)) &  \n      (\\<forall>x. (Q(x) --> ~ S(x)) --> P(x) & R(x))   \n    --> (\\<forall>x. S(x))\"\nby blast\n\ntext{*31*}\nlemma \"~(\\<exists>x. P(x) & (Q(x) | R(x))) &  \n        (\\<exists>x. L(x) & P(x)) &  \n        (\\<forall>x. ~ R(x) --> M(x))   \n    --> (\\<exists>x. L(x) & M(x))\"\nby blast\n\ntext{*32*}\nlemma \"(\\<forall>x. P(x) & (Q(x)|R(x))-->S(x)) &  \n      (\\<forall>x. S(x) & R(x) --> L(x)) &  \n      (\\<forall>x. M(x) --> R(x))   \n      --> (\\<forall>x. P(x) & M(x) --> L(x))\"\nby blast\n\ntext{*33*}\nlemma \"(\\<forall>x. P(a) & (P(x)-->P(b))-->P(c))  <->     \n      (\\<forall>x. (~P(a) | P(x) | P(c)) & (~P(a) | ~P(b) | P(c)))\"\nby blast\n\ntext{*34  AMENDED (TWICE!!).  Andrews's challenge*}\nlemma \"((\\<exists>x. \\<forall>y. p(x) <-> p(y))  <->                 \n       ((\\<exists>x. q(x)) <-> (\\<forall>y. p(y))))     <->         \n      ((\\<exists>x. \\<forall>y. q(x) <-> q(y))  <->                 \n       ((\\<exists>x. p(x)) <-> (\\<forall>y. q(y))))\"\nby blast\n\ntext{*35*}\nlemma \"\\<exists>x y. P(x,y) -->  (\\<forall>u v. P(u,v))\"\nby blast\n\ntext{*36*}\nlemma \"(\\<forall>x. \\<exists>y. J(x,y)) &  \n      (\\<forall>x. \\<exists>y. G(x,y)) &  \n      (\\<forall>x y. J(x,y) | G(x,y) --> (\\<forall>z. J(y,z) | G(y,z) --> H(x,z)))    \n  --> (\\<forall>x. \\<exists>y. H(x,y))\"\nby blast\n\ntext{*37*}\nlemma \"(\\<forall>z. \\<exists>w. \\<forall>x. \\<exists>y.  \n           (P(x,z)-->P(y,w)) & P(y,z) & (P(y,w) --> (\\<exists>u. Q(u,w)))) &  \n      (\\<forall>x z. ~P(x,z) --> (\\<exists>y. Q(y,z))) &  \n      ((\\<exists>x y. Q(x,y)) --> (\\<forall>x. R(x,x)))   \n      --> (\\<forall>x. \\<exists>y. R(x,y))\"\nby blast\n\ntext{*38*}\nlemma \"(\\<forall>x. p(a) & (p(x) --> (\\<exists>y. p(y) & r(x,y))) -->         \n             (\\<exists>z. \\<exists>w. p(z) & r(x,w) & r(w,z)))  <->          \n      (\\<forall>x. (~p(a) | p(x) | (\\<exists>z. \\<exists>w. p(z) & r(x,w) & r(w,z))) &     \n              (~p(a) | ~(\\<exists>y. p(y) & r(x,y)) |                           \n              (\\<exists>z. \\<exists>w. p(z) & r(x,w) & r(w,z))))\"\nby blast\n\ntext{*39*}\nlemma \"~ (\\<exists>x. \\<forall>y. F(y,x) <-> ~F(y,y))\"\nby blast\n\ntext{*40.  AMENDED*}\nlemma \"(\\<exists>y. \\<forall>x. F(x,y) <-> F(x,x)) -->   \n              ~(\\<forall>x. \\<exists>y. \\<forall>z. F(z,y) <-> ~ F(z,x))\"\nby blast\n\ntext{*41*}\nlemma \"(\\<forall>z. \\<exists>y. \\<forall>x. f(x,y) <-> f(x,z) & ~ f(x,x))         \n          --> ~ (\\<exists>z. \\<forall>x. f(x,z))\"\nby blast\n\ntext{*42*}\nlemma \"~ (\\<exists>y. \\<forall>x. p(x,y) <-> ~ (\\<exists>z. p(x,z) & p(z,x)))\"\nby blast\n\ntext{*43*}\nlemma \"(\\<forall>x. \\<forall>y. q(x,y) <-> (\\<forall>z. p(z,x) <-> p(z,y)))      \n          --> (\\<forall>x. \\<forall>y. q(x,y) <-> q(y,x))\"\nby blast\n\n(*Other proofs: Can use auto, which cheats by using rewriting!  \n  Deepen_tac alone requires 253 secs.  Or\n  by (mini_tac @{context} 1 THEN Deepen_tac 5 1) *)\n\ntext{*44*}\nlemma \"(\\<forall>x. f(x) --> (\\<exists>y. g(y) & h(x,y) & (\\<exists>y. g(y) & ~ h(x,y)))) &  \n      (\\<exists>x. j(x) & (\\<forall>y. g(y) --> h(x,y)))                    \n      --> (\\<exists>x. j(x) & ~f(x))\"\nby blast\n\ntext{*45*}\nlemma \"(\\<forall>x. f(x) & (\\<forall>y. g(y) & h(x,y) --> j(x,y))   \n                      --> (\\<forall>y. g(y) & h(x,y) --> k(y))) &     \n      ~ (\\<exists>y. l(y) & k(y)) &                                    \n      (\\<exists>x. f(x) & (\\<forall>y. h(x,y) --> l(y))                     \n                  & (\\<forall>y. g(y) & h(x,y) --> j(x,y)))           \n      --> (\\<exists>x. f(x) & ~ (\\<exists>y. g(y) & h(x,y)))\"\nby blast\n\n\ntext{*46*}\nlemma \"(\\<forall>x. f(x) & (\\<forall>y. f(y) & h(y,x) --> g(y)) --> g(x)) &       \n      ((\\<exists>x. f(x) & ~g(x)) -->                                     \n       (\\<exists>x. f(x) & ~g(x) & (\\<forall>y. f(y) & ~g(y) --> j(x,y)))) &     \n      (\\<forall>x y. f(x) & f(y) & h(x,y) --> ~j(y,x))                     \n       --> (\\<forall>x. f(x) --> g(x))\"\nby blast\n\n\nsubsection{*Problems (mainly) involving equality or functions*}\n\ntext{*48*}\nlemma \"(a=b | c=d) & (a=c | b=d) --> a=d | b=c\"\nby blast\n\ntext{*49  NOT PROVED AUTOMATICALLY.  Hard because it involves substitution\n  for Vars\n  the type constraint ensures that x,y,z have the same type as a,b,u. *}\nlemma \"(\\<exists>x y::'a. \\<forall>z. z=x | z=y) & P(a) & P(b) & a~=b  \n                --> (\\<forall>u::'a. P(u))\"\napply safe\napply (rule_tac x = a in allE, assumption)\napply (rule_tac x = b in allE, assumption, fast)\n       --{*blast's treatment of equality can't do it*}\ndone\n\ntext{*50.  (What has this to do with equality?) *}\nlemma \"(\\<forall>x. P(a,x) | (\\<forall>y. P(x,y))) --> (\\<exists>x. \\<forall>y. P(x,y))\"\nby blast\n\ntext{*51*}\nlemma \"(\\<exists>z w. \\<forall>x y. P(x,y) <->  (x=z & y=w)) -->   \n      (\\<exists>z. \\<forall>x. \\<exists>w. (\\<forall>y. P(x,y) <-> y=w) <-> x=z)\"\nby blast\n\ntext{*52*}\ntext{*Almost the same as 51. *}\nlemma \"(\\<exists>z w. \\<forall>x y. P(x,y) <->  (x=z & y=w)) -->   \n      (\\<exists>w. \\<forall>y. \\<exists>z. (\\<forall>x. P(x,y) <-> x=z) <-> y=w)\"\nby blast\n\ntext{*55*}\n\ntext{*Non-equational version, from Manthey and Bry, CADE-9 (Springer, 1988).\n  fast DISCOVERS who killed Agatha. *}\nschematic_lemma \"lives(agatha) & lives(butler) & lives(charles) &  \n   (killed(agatha,agatha) | killed(butler,agatha) | killed(charles,agatha)) &  \n   (\\<forall>x y. killed(x,y) --> hates(x,y) & ~richer(x,y)) &  \n   (\\<forall>x. hates(agatha,x) --> ~hates(charles,x)) &  \n   (hates(agatha,agatha) & hates(agatha,charles)) &  \n   (\\<forall>x. lives(x) & ~richer(x,agatha) --> hates(butler,x)) &  \n   (\\<forall>x. hates(agatha,x) --> hates(butler,x)) &  \n   (\\<forall>x. ~hates(x,agatha) | ~hates(x,butler) | ~hates(x,charles)) -->  \n    killed(?who,agatha)\"\nby fast --{*MUCH faster than blast*}\n\n\ntext{*56*}\nlemma \"(\\<forall>x. (\\<exists>y. P(y) & x=f(y)) --> P(x)) <-> (\\<forall>x. P(x) --> P(f(x)))\"\nby blast\n\ntext{*57*}\nlemma \"P(f(a,b), f(b,c)) & P(f(b,c), f(a,c)) &  \n     (\\<forall>x y z. P(x,y) & P(y,z) --> P(x,z))    -->   P(f(a,b), f(a,c))\"\nby blast\n\ntext{*58  NOT PROVED AUTOMATICALLY*}\nlemma \"(\\<forall>x y. f(x)=g(y)) --> (\\<forall>x y. f(f(x))=f(g(y)))\"\nby (slow elim: subst_context)\n\n\ntext{*59*}\nlemma \"(\\<forall>x. P(x) <-> ~P(f(x))) --> (\\<exists>x. P(x) & ~P(f(x)))\"\nby blast\n\ntext{*60*}\nlemma \"\\<forall>x. P(x,f(x)) <-> (\\<exists>y. (\\<forall>z. P(z,y) --> P(z,f(x))) & P(x,y))\"\nby blast\n\ntext{*62 as corrected in JAR 18 (1997), page 135*}\nlemma \"(\\<forall>x. p(a) & (p(x) --> p(f(x))) --> p(f(f(x))))  <->      \n      (\\<forall>x. (~p(a) | p(x) | p(f(f(x)))) &                       \n              (~p(a) | ~p(f(x)) | p(f(f(x)))))\"\nby blast\n\ntext{*From Davis, Obvious Logical Inferences, IJCAI-81, 530-531\n  fast indeed copes!*}\nlemma \"(\\<forall>x. F(x) & ~G(x) --> (\\<exists>y. H(x,y) & J(y))) &  \n              (\\<exists>x. K(x) & F(x) & (\\<forall>y. H(x,y) --> K(y))) &    \n              (\\<forall>x. K(x) --> ~G(x))  -->  (\\<exists>x. K(x) & J(x))\"\nby fast\n\ntext{*From Rudnicki, Obvious Inferences, JAR 3 (1987), 383-393.  \n  It does seem obvious!*}\nlemma \"(\\<forall>x. F(x) & ~G(x) --> (\\<exists>y. H(x,y) & J(y))) &         \n      (\\<exists>x. K(x) & F(x) & (\\<forall>y. H(x,y) --> K(y)))  &         \n      (\\<forall>x. K(x) --> ~G(x))   -->   (\\<exists>x. K(x) --> ~G(x))\"\nby fast\n\ntext{*Halting problem: Formulation of Li Dafa (AAR Newsletter 27, Oct 1994.)\n  author U. Egly*}\nlemma \"((\\<exists>x. A(x) & (\\<forall>y. C(y) --> (\\<forall>z. D(x,y,z)))) -->                \n   (\\<exists>w. C(w) & (\\<forall>y. C(y) --> (\\<forall>z. D(w,y,z)))))                   \n  &                                                                      \n  (\\<forall>w. C(w) & (\\<forall>u. C(u) --> (\\<forall>v. D(w,u,v))) -->                 \n        (\\<forall>y z.                                                        \n            (C(y) &  P(y,z) --> Q(w,y,z) & OO(w,g)) &                    \n            (C(y) & ~P(y,z) --> Q(w,y,z) & OO(w,b))))                    \n  &                                                                      \n  (\\<forall>w. C(w) &                                                         \n    (\\<forall>y z.                                                            \n        (C(y) & P(y,z) --> Q(w,y,z) & OO(w,g)) &                         \n        (C(y) & ~P(y,z) --> Q(w,y,z) & OO(w,b))) -->                     \n    (\\<exists>v. C(v) &                                                        \n          (\\<forall>y. ((C(y) & Q(w,y,y)) & OO(w,g) --> ~P(v,y)) &            \n                  ((C(y) & Q(w,y,y)) & OO(w,b) --> P(v,y) & OO(v,b)))))  \n   -->                   \n   ~ (\\<exists>x. A(x) & (\\<forall>y. C(y) --> (\\<forall>z. D(x,y,z))))\"\nby (blast 12)\n   --{*Needed because the search for depths below 12 is very slow*}\n\n\ntext{*Halting problem II: credited to M. Bruschi by Li Dafa in JAR 18(1), p.105*}\nlemma \"((\\<exists>x. A(x) & (\\<forall>y. C(y) --> (\\<forall>z. D(x,y,z)))) -->        \n   (\\<exists>w. C(w) & (\\<forall>y. C(y) --> (\\<forall>z. D(w,y,z)))))           \n  &                                                              \n  (\\<forall>w. C(w) & (\\<forall>u. C(u) --> (\\<forall>v. D(w,u,v))) -->         \n        (\\<forall>y z.                                                \n            (C(y) &  P(y,z) --> Q(w,y,z) & OO(w,g)) &           \n            (C(y) & ~P(y,z) --> Q(w,y,z) & OO(w,b))))          \n  &                                                              \n  ((\\<exists>w. C(w) & (\\<forall>y. (C(y) &  P(y,y) --> Q(w,y,y) & OO(w,g)) & \n                         (C(y) & ~P(y,y) --> Q(w,y,y) & OO(w,b))))  \n   -->                                                             \n   (\\<exists>v. C(v) & (\\<forall>y. (C(y) &  P(y,y) --> P(v,y) & OO(v,g)) &   \n                         (C(y) & ~P(y,y) --> P(v,y) & OO(v,b)))))  \n  -->                                                              \n  ((\\<exists>v. C(v) & (\\<forall>y. (C(y) &  P(y,y) --> P(v,y) & OO(v,g)) &   \n                         (C(y) & ~P(y,y) --> P(v,y) & OO(v,b))))   \n   -->                                                             \n   (\\<exists>u. C(u) & (\\<forall>y. (C(y) &  P(y,y) --> ~P(u,y)) &     \n                         (C(y) & ~P(y,y) --> P(u,y) & OO(u,b)))))  \n   -->                                                             \n   ~ (\\<exists>x. A(x) & (\\<forall>y. C(y) --> (\\<forall>z. D(x,y,z))))\"\nby blast\n\ntext{* Challenge found on info-hol *}\nlemma \"\\<forall>x. \\<exists>v w. \\<forall>y z. P(x) & Q(y) --> (P(v) | R(w)) & (R(z) --> Q(v))\"\nby blast\n\ntext{*Attributed to Lewis Carroll by S. G. Pulman.  The first or last assumption\ncan be deleted.*}\nlemma \"(\\<forall>x. honest(x) & industrious(x) --> healthy(x)) &  \n      ~ (\\<exists>x. grocer(x) & healthy(x)) &  \n      (\\<forall>x. industrious(x) & grocer(x) --> honest(x)) &  \n      (\\<forall>x. cyclist(x) --> industrious(x)) &  \n      (\\<forall>x. ~healthy(x) & cyclist(x) --> ~honest(x))   \n      --> (\\<forall>x. grocer(x) --> ~cyclist(x))\"\nby 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\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/Classical.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972650509008, "lm_q2_score": 0.8376199592797929, "lm_q1q2_score": 0.7292296457010347}}
{"text": "(*  Title:      ZF/OrdQuant.thy\n    Authors:    Krzysztof Grabczewski and L C Paulson\n*)\n\nsection \\<open>Special quantifiers\\<close>\n\ntheory OrdQuant imports Ordinal begin\n\nsubsection \\<open>Quantifiers and union operator for ordinals\\<close>\n\ndefinition\n  (* Ordinal Quantifiers *)\n  oall :: \"[i, i => o] => o\"  where\n    \"oall(A, P) == \\<forall>x. x<A \\<longrightarrow> P(x)\"\n\ndefinition\n  oex :: \"[i, i => o] => o\"  where\n    \"oex(A, P)  == \\<exists>x. x<A & P(x)\"\n\ndefinition\n  (* Ordinal Union *)\n  OUnion :: \"[i, i => i] => i\"  where\n    \"OUnion(i,B) == {z: \\<Union>x\\<in>i. B(x). Ord(i)}\"\n\nsyntax\n  \"_oall\"     :: \"[idt, i, o] => o\"        (\"(3\\<forall>_<_./ _)\" 10)\n  \"_oex\"      :: \"[idt, i, o] => o\"        (\"(3\\<exists>_<_./ _)\" 10)\n  \"_OUNION\"   :: \"[idt, i, i] => i\"        (\"(3\\<Union>_<_./ _)\" 10)\ntranslations\n  \"\\<forall>x<a. P\" \\<rightleftharpoons> \"CONST oall(a, \\<lambda>x. P)\"\n  \"\\<exists>x<a. P\" \\<rightleftharpoons> \"CONST oex(a, \\<lambda>x. P)\"\n  \"\\<Union>x<a. B\" \\<rightleftharpoons> \"CONST OUnion(a, \\<lambda>x. B)\"\n\n\nsubsubsection \\<open>simplification of the new quantifiers\\<close>\n\n\n(*MOST IMPORTANT that this is added to the simpset BEFORE Ord_atomize\n  is proved.  Ord_atomize would convert this rule to\n    x < 0 ==> P(x) == True, which causes dire effects!*)\n\n\nlemma [simp]: \"~(\\<exists>x<0. P(x))\"\nby (simp add: oex_def)\n\nlemma [simp]: \"(\\<forall>x<succ(i). P(x)) <-> (Ord(i) \\<longrightarrow> P(i) & (\\<forall>x<i. P(x)))\"\napply (simp add: oall_def le_iff)\napply (blast intro: lt_Ord2)\ndone\n\nlemma [simp]: \"(\\<exists>x<succ(i). P(x)) <-> (Ord(i) & (P(i) | (\\<exists>x<i. P(x))))\"\napply (simp add: oex_def le_iff)\napply (blast intro: lt_Ord2)\ndone\n\nsubsubsection \\<open>Union over ordinals\\<close>\n\nlemma Ord_OUN [intro,simp]:\n     \"[| !!x. x<A ==> Ord(B(x)) |] ==> Ord(\\<Union>x<A. B(x))\"\nby (simp add: OUnion_def ltI Ord_UN)\n\nlemma OUN_upper_lt:\n     \"[| a<A;  i < b(a);  Ord(\\<Union>x<A. b(x)) |] ==> i < (\\<Union>x<A. b(x))\"\nby (unfold OUnion_def lt_def, blast )\n\nlemma OUN_upper_le:\n     \"[| a<A;  i\\<le>b(a);  Ord(\\<Union>x<A. b(x)) |] ==> i \\<le> (\\<Union>x<A. b(x))\"\napply (unfold OUnion_def, auto)\napply (rule UN_upper_le )\napply (auto simp add: lt_def)\ndone\n\nlemma Limit_OUN_eq: \"Limit(i) ==> (\\<Union>x<i. x) = i\"\nby (simp add: OUnion_def Limit_Union_eq Limit_is_Ord)\n\n(* No < version of this theorem: consider that @{term\"(\\<Union>i\\<in>nat.i)=nat\"}! *)\nlemma OUN_least:\n     \"(!!x. x<A ==> B(x) \\<subseteq> C) ==> (\\<Union>x<A. B(x)) \\<subseteq> C\"\nby (simp add: OUnion_def UN_least ltI)\n\nlemma OUN_least_le:\n     \"[| Ord(i);  !!x. x<A ==> b(x) \\<le> i |] ==> (\\<Union>x<A. b(x)) \\<le> i\"\nby (simp add: OUnion_def UN_least_le ltI Ord_0_le)\n\nlemma le_implies_OUN_le_OUN:\n     \"[| !!x. x<A ==> c(x) \\<le> d(x) |] ==> (\\<Union>x<A. c(x)) \\<le> (\\<Union>x<A. d(x))\"\nby (blast intro: OUN_least_le OUN_upper_le le_Ord2 Ord_OUN)\n\nlemma OUN_UN_eq:\n     \"(!!x. x \\<in> A ==> Ord(B(x)))\n      ==> (\\<Union>z < (\\<Union>x\\<in>A. B(x)). C(z)) = (\\<Union>x\\<in>A. \\<Union>z < B(x). C(z))\"\nby (simp add: OUnion_def)\n\nlemma OUN_Union_eq:\n     \"(!!x. x \\<in> X ==> Ord(x))\n      ==> (\\<Union>z < \\<Union>(X). C(z)) = (\\<Union>x\\<in>X. \\<Union>z < x. C(z))\"\nby (simp add: OUnion_def)\n\n(*So that rule_format will get rid of this quantifier...*)\nlemma atomize_oall [symmetric, rulify]:\n     \"(!!x. x<A ==> P(x)) == Trueprop (\\<forall>x<A. P(x))\"\nby (simp add: oall_def atomize_all atomize_imp)\n\nsubsubsection \\<open>universal quantifier for ordinals\\<close>\n\nlemma oallI [intro!]:\n    \"[| !!x. x<A ==> P(x) |] ==> \\<forall>x<A. P(x)\"\nby (simp add: oall_def)\n\nlemma ospec: \"[| \\<forall>x<A. P(x);  x<A |] ==> P(x)\"\nby (simp add: oall_def)\n\nlemma oallE:\n    \"[| \\<forall>x<A. P(x);  P(x) ==> Q;  ~x<A ==> Q |] ==> Q\"\nby (simp add: oall_def, blast)\n\nlemma rev_oallE [elim]:\n    \"[| \\<forall>x<A. P(x);  ~x<A ==> Q;  P(x) ==> Q |] ==> Q\"\nby (simp add: oall_def, blast)\n\n\n(*Trival rewrite rule.  @{term\"(\\<forall>x<a.P)<->P\"} holds only if a is not 0!*)\nlemma oall_simp [simp]: \"(\\<forall>x<a. True) <-> True\"\nby blast\n\n(*Congruence rule for rewriting*)\nlemma oall_cong [cong]:\n    \"[| a=a';  !!x. x<a' ==> P(x) <-> P'(x) |]\n     ==> oall(a, %x. P(x)) <-> oall(a', %x. P'(x))\"\nby (simp add: oall_def)\n\n\nsubsubsection \\<open>existential quantifier for ordinals\\<close>\n\nlemma oexI [intro]:\n    \"[| P(x);  x<A |] ==> \\<exists>x<A. P(x)\"\napply (simp add: oex_def, blast)\ndone\n\n(*Not of the general form for such rules... *)\nlemma oexCI:\n   \"[| \\<forall>x<A. ~P(x) ==> P(a);  a<A |] ==> \\<exists>x<A. P(x)\"\napply (simp add: oex_def, blast)\ndone\n\nlemma oexE [elim!]:\n    \"[| \\<exists>x<A. P(x);  !!x. [| x<A; P(x) |] ==> Q |] ==> Q\"\napply (simp add: oex_def, blast)\ndone\n\nlemma oex_cong [cong]:\n    \"[| a=a';  !!x. x<a' ==> P(x) <-> P'(x) |]\n     ==> oex(a, %x. P(x)) <-> oex(a', %x. P'(x))\"\napply (simp add: oex_def cong add: conj_cong)\ndone\n\n\nsubsubsection \\<open>Rules for Ordinal-Indexed Unions\\<close>\n\nlemma OUN_I [intro]: \"[| a<i;  b \\<in> B(a) |] ==> b: (\\<Union>z<i. B(z))\"\nby (unfold OUnion_def lt_def, blast)\n\nlemma OUN_E [elim!]:\n    \"[| b \\<in> (\\<Union>z<i. B(z));  !!a.[| b \\<in> B(a);  a<i |] ==> R |] ==> R\"\napply (unfold OUnion_def lt_def, blast)\ndone\n\nlemma OUN_iff: \"b \\<in> (\\<Union>x<i. B(x)) <-> (\\<exists>x<i. b \\<in> B(x))\"\nby (unfold OUnion_def oex_def lt_def, blast)\n\nlemma OUN_cong [cong]:\n    \"[| i=j;  !!x. x<j ==> C(x)=D(x) |] ==> (\\<Union>x<i. C(x)) = (\\<Union>x<j. D(x))\"\nby (simp add: OUnion_def lt_def OUN_iff)\n\nlemma lt_induct:\n    \"[| i<k;  !!x.[| x<k;  \\<forall>y<x. P(y) |] ==> P(x) |]  ==>  P(i)\"\napply (simp add: lt_def oall_def)\napply (erule conjE)\napply (erule Ord_induct, assumption, blast)\ndone\n\n\nsubsection \\<open>Quantification over a class\\<close>\n\ndefinition\n  \"rall\"     :: \"[i=>o, i=>o] => o\"  where\n    \"rall(M, P) == \\<forall>x. M(x) \\<longrightarrow> P(x)\"\n\ndefinition\n  \"rex\"      :: \"[i=>o, i=>o] => o\"  where\n    \"rex(M, P) == \\<exists>x. M(x) & P(x)\"\n\nsyntax\n  \"_rall\"     :: \"[pttrn, i=>o, o] => o\"        (\"(3\\<forall>_[_]./ _)\" 10)\n  \"_rex\"      :: \"[pttrn, i=>o, o] => o\"        (\"(3\\<exists>_[_]./ _)\" 10)\ntranslations\n  \"\\<forall>x[M]. P\" \\<rightleftharpoons> \"CONST rall(M, \\<lambda>x. P)\"\n  \"\\<exists>x[M]. P\" \\<rightleftharpoons> \"CONST rex(M, \\<lambda>x. P)\"\n\n\nsubsubsection\\<open>Relativized universal quantifier\\<close>\n\nlemma rallI [intro!]: \"[| !!x. M(x) ==> P(x) |] ==> \\<forall>x[M]. P(x)\"\nby (simp add: rall_def)\n\nlemma rspec: \"[| \\<forall>x[M]. P(x); M(x) |] ==> P(x)\"\nby (simp add: rall_def)\n\n(*Instantiates x first: better for automatic theorem proving?*)\nlemma rev_rallE [elim]:\n    \"[| \\<forall>x[M]. P(x);  ~ M(x) ==> Q;  P(x) ==> Q |] ==> Q\"\nby (simp add: rall_def, blast)\n\nlemma rallE: \"[| \\<forall>x[M]. P(x);  P(x) ==> Q;  ~ M(x) ==> Q |] ==> Q\"\nby blast\n\n(*Trival rewrite rule;   (\\<forall>x[M].P)<->P holds only if A is nonempty!*)\nlemma rall_triv [simp]: \"(\\<forall>x[M]. P) \\<longleftrightarrow> ((\\<exists>x. M(x)) \\<longrightarrow> P)\"\nby (simp add: rall_def)\n\n(*Congruence rule for rewriting*)\nlemma rall_cong [cong]:\n    \"(!!x. M(x) ==> P(x) <-> P'(x)) ==> (\\<forall>x[M]. P(x)) <-> (\\<forall>x[M]. P'(x))\"\nby (simp add: rall_def)\n\n\nsubsubsection\\<open>Relativized existential quantifier\\<close>\n\nlemma rexI [intro]: \"[| P(x); M(x) |] ==> \\<exists>x[M]. P(x)\"\nby (simp add: rex_def, blast)\n\n(*The best argument order when there is only one M(x)*)\nlemma rev_rexI: \"[| M(x);  P(x) |] ==> \\<exists>x[M]. P(x)\"\nby blast\n\n(*Not of the general form for such rules... *)\nlemma rexCI: \"[| \\<forall>x[M]. ~P(x) ==> P(a); M(a) |] ==> \\<exists>x[M]. P(x)\"\nby blast\n\nlemma rexE [elim!]: \"[| \\<exists>x[M]. P(x);  !!x. [| M(x); P(x) |] ==> Q |] ==> Q\"\nby (simp add: rex_def, blast)\n\n(*We do not even have (\\<exists>x[M]. True) <-> True unless A is nonempty!!*)\nlemma rex_triv [simp]: \"(\\<exists>x[M]. P) \\<longleftrightarrow> ((\\<exists>x. M(x)) \\<and> P)\"\nby (simp add: rex_def)\n\nlemma rex_cong [cong]:\n    \"(!!x. M(x) ==> P(x) <-> P'(x)) ==> (\\<exists>x[M]. P(x)) <-> (\\<exists>x[M]. P'(x))\"\nby (simp add: rex_def cong: conj_cong)\n\nlemma rall_is_ball [simp]: \"(\\<forall>x[%z. z\\<in>A]. P(x)) <-> (\\<forall>x\\<in>A. P(x))\"\nby blast\n\nlemma rex_is_bex [simp]: \"(\\<exists>x[%z. z\\<in>A]. P(x)) <-> (\\<exists>x\\<in>A. P(x))\"\nby blast\n\nlemma atomize_rall: \"(!!x. M(x) ==> P(x)) == Trueprop (\\<forall>x[M]. P(x))\"\nby (simp add: rall_def atomize_all atomize_imp)\n\ndeclare atomize_rall [symmetric, rulify]\n\nlemma rall_simps1:\n     \"(\\<forall>x[M]. P(x) & Q)   <-> (\\<forall>x[M]. P(x)) & ((\\<forall>x[M]. False) | Q)\"\n     \"(\\<forall>x[M]. P(x) | Q)   <-> ((\\<forall>x[M]. P(x)) | Q)\"\n     \"(\\<forall>x[M]. P(x) \\<longrightarrow> Q) <-> ((\\<exists>x[M]. P(x)) \\<longrightarrow> Q)\"\n     \"(~(\\<forall>x[M]. P(x))) <-> (\\<exists>x[M]. ~P(x))\"\nby blast+\n\nlemma rall_simps2:\n     \"(\\<forall>x[M]. P & Q(x))   <-> ((\\<forall>x[M]. False) | P) & (\\<forall>x[M]. Q(x))\"\n     \"(\\<forall>x[M]. P | Q(x))   <-> (P | (\\<forall>x[M]. Q(x)))\"\n     \"(\\<forall>x[M]. P \\<longrightarrow> Q(x)) <-> (P \\<longrightarrow> (\\<forall>x[M]. Q(x)))\"\nby blast+\n\nlemmas rall_simps [simp] = rall_simps1 rall_simps2\n\nlemma rall_conj_distrib:\n    \"(\\<forall>x[M]. P(x) & Q(x)) <-> ((\\<forall>x[M]. P(x)) & (\\<forall>x[M]. Q(x)))\"\nby blast\n\nlemma rex_simps1:\n     \"(\\<exists>x[M]. P(x) & Q) <-> ((\\<exists>x[M]. P(x)) & Q)\"\n     \"(\\<exists>x[M]. P(x) | Q) <-> (\\<exists>x[M]. P(x)) | ((\\<exists>x[M]. True) & Q)\"\n     \"(\\<exists>x[M]. P(x) \\<longrightarrow> Q) <-> ((\\<forall>x[M]. P(x)) \\<longrightarrow> ((\\<exists>x[M]. True) & Q))\"\n     \"(~(\\<exists>x[M]. P(x))) <-> (\\<forall>x[M]. ~P(x))\"\nby blast+\n\nlemma rex_simps2:\n     \"(\\<exists>x[M]. P & Q(x)) <-> (P & (\\<exists>x[M]. Q(x)))\"\n     \"(\\<exists>x[M]. P | Q(x)) <-> ((\\<exists>x[M]. True) & P) | (\\<exists>x[M]. Q(x))\"\n     \"(\\<exists>x[M]. P \\<longrightarrow> Q(x)) <-> (((\\<forall>x[M]. False) | P) \\<longrightarrow> (\\<exists>x[M]. Q(x)))\"\nby blast+\n\nlemmas rex_simps [simp] = rex_simps1 rex_simps2\n\nlemma rex_disj_distrib:\n    \"(\\<exists>x[M]. P(x) | Q(x)) <-> ((\\<exists>x[M]. P(x)) | (\\<exists>x[M]. Q(x)))\"\nby blast\n\n\nsubsubsection\\<open>One-point rule for bounded quantifiers\\<close>\n\nlemma rex_triv_one_point1 [simp]: \"(\\<exists>x[M]. x=a) <-> ( M(a))\"\nby blast\n\nlemma rex_triv_one_point2 [simp]: \"(\\<exists>x[M]. a=x) <-> ( M(a))\"\nby blast\n\nlemma rex_one_point1 [simp]: \"(\\<exists>x[M]. x=a & P(x)) <-> ( M(a) & P(a))\"\nby blast\n\nlemma rex_one_point2 [simp]: \"(\\<exists>x[M]. a=x & P(x)) <-> ( M(a) & P(a))\"\nby blast\n\nlemma rall_one_point1 [simp]: \"(\\<forall>x[M]. x=a \\<longrightarrow> P(x)) <-> ( M(a) \\<longrightarrow> P(a))\"\nby blast\n\nlemma rall_one_point2 [simp]: \"(\\<forall>x[M]. a=x \\<longrightarrow> P(x)) <-> ( M(a) \\<longrightarrow> P(a))\"\nby blast\n\n\nsubsubsection\\<open>Sets as Classes\\<close>\n\ndefinition\n  setclass :: \"[i,i] => o\"       (\"##_\" [40] 40)  where\n   \"setclass(A) == %x. x \\<in> A\"\n\nlemma setclass_iff [simp]: \"setclass(A,x) <-> x \\<in> A\"\nby (simp add: setclass_def)\n\nlemma rall_setclass_is_ball [simp]: \"(\\<forall>x[##A]. P(x)) <-> (\\<forall>x\\<in>A. P(x))\"\nby auto\n\nlemma rex_setclass_is_bex [simp]: \"(\\<exists>x[##A]. P(x)) <-> (\\<exists>x\\<in>A. P(x))\"\nby auto\n\n\nML\n\\<open>\nval Ord_atomize =\n  atomize ([(@{const_name oall}, @{thms ospec}), (@{const_name rall}, @{thms rspec})] @\n    ZF_conn_pairs, ZF_mem_pairs);\n\\<close>\ndeclaration \\<open>fn _ =>\n  Simplifier.map_ss (Simplifier.set_mksimps (fn ctxt =>\n    map mk_eq o Ord_atomize o Variable.gen_all ctxt))\n\\<close>\n\ntext \\<open>Setting up the one-point-rule simproc\\<close>\n\nsimproc_setup defined_rex (\"\\<exists>x[M]. P(x) & Q(x)\") = \\<open>\n  fn _ => Quantifier1.rearrange_bex\n    (fn ctxt =>\n      unfold_tac ctxt @{thms rex_def} THEN\n      Quantifier1.prove_one_point_ex_tac ctxt)\n\\<close>\n\nsimproc_setup defined_rall (\"\\<forall>x[M]. P(x) \\<longrightarrow> Q(x)\") = \\<open>\n  fn _ => Quantifier1.rearrange_ball\n    (fn ctxt =>\n      unfold_tac ctxt @{thms rall_def} THEN\n      Quantifier1.prove_one_point_all_tac ctxt)\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/ZF/OrdQuant.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127529517043, "lm_q2_score": 0.8539127585282744, "lm_q1q2_score": 0.7291669944154627}}
{"text": "(* Author: Florian Haftmann, TU Muenchen *)\n\nsection \\<open>Lexicographic 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\" \"k' < k1 \\<Longrightarrow> f k' = g k'\" for k'\n    by (blast elim!: less_funE) \n  assume \"less_fun g f\" then obtain k2 where k2: \"g k2 < f k2\" \"k' < k2 \\<Longrightarrow> g k' = f k'\" for 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 \\<open>less_fun f g\\<close> obtain k1 where k1: \"f k1 < g k1\" \"k' < k1 \\<Longrightarrow> f k' = g k'\" for k'\n    by (blast elim!: less_funE)                          \n  from \\<open>less_fun g h\\<close> obtain k2 where k2: \"g k2 < h k2\" \"k' < k2 \\<Longrightarrow> g k' = h k'\" for 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  { define K where \"K = {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    define q where \"q = 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 \\<open>q \\<in> K\\<close> 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": "seL4", "repo": "isabelle", "sha": "e1ab32a3bb41728cd19541063283e37919978a4c", "save_path": "github-repos/isabelle/seL4-isabelle", "path": "github-repos/isabelle/seL4-isabelle/isabelle-e1ab32a3bb41728cd19541063283e37919978a4c/src/HOL/Library/Fun_Lexorder.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511469672594, "lm_q2_score": 0.8519528076067262, "lm_q1q2_score": 0.7291447875521935}}
{"text": "(*\n  File:       E_Transcendental.thy\n  Author:     Manuel Eberl <manuel@pruvisto.org>\n\n  A proof that e (Euler's number) is transcendental.\n  Could possibly be extended to a transcendence proof for pi or\n  the very general Lindemann-Weierstrass theorem.\n*)\nsection \\<open>Proof of the Transcendence of $e$\\<close>\ntheory E_Transcendental\n  imports\n    \"HOL-Complex_Analysis.Complex_Analysis\"\n    \"HOL-Number_Theory.Number_Theory\"\n    \"HOL-Computational_Algebra.Polynomial\"\nbegin\n\nhide_const (open) UnivPoly.coeff  UnivPoly.up_ring.monom \nhide_const (open) Module.smult  Coset.order\n\n(* TODO: Lots of stuff to move to the distribution *)\n  \nsubsection \\<open>Various auxiliary facts\\<close>\n\nlemma fact_dvd_pochhammer:\n  assumes \"m \\<le> n + 1\"\n  shows   \"fact m dvd pochhammer (int n - int m + 1) m\"\nproof -\n  have \"(real n gchoose m) * fact m = of_int (pochhammer (int n - int m + 1) m)\"\n    by (simp add: gbinomial_pochhammer' pochhammer_of_int [symmetric])\n  also have \"(real n gchoose m) * fact m = of_int (int (n choose m) * fact m)\"\n    by (simp add: binomial_gbinomial)\n  finally have \"int (n choose m) * fact m = pochhammer (int n - int m + 1) m\"\n    by (subst (asm) of_int_eq_iff)\n  from this [symmetric] show ?thesis by simp\nqed\n\nlemma prime_elem_int_not_dvd_neg1_power:\n  \"prime_elem (p :: int) \\<Longrightarrow> \\<not>p dvd (-1) ^ n\"\n  by (metis dvdI minus_one_mult_self unit_imp_no_prime_divisors)\n\nlemma nat_fact [simp]: \"nat (fact n) = fact n\"\n  by (metis nat_int of_nat_fact of_nat_fact)\n\nlemma prime_dvd_fact_iff_int:\n  \"p dvd fact n \\<longleftrightarrow> p \\<le> int n\" if \"prime p\"\n  using that prime_dvd_fact_iff [of \"nat \\<bar>p\\<bar>\" n]\n  by auto (simp add: prime_ge_0_int)\n\nlemma power_over_fact_tendsto_0:\n  \"(\\<lambda>n. (x :: real) ^ n / fact n) \\<longlonglongrightarrow> 0\"\n  using summable_exp[of x] by (intro summable_LIMSEQ_zero) (simp add: sums_iff field_simps)\n\nlemma power_over_fact_tendsto_0':\n  \"(\\<lambda>n. c * (x :: real) ^ n / fact n) \\<longlonglongrightarrow> 0\"\n  using tendsto_mult[OF tendsto_const[of c] power_over_fact_tendsto_0[of x]] by simp\n\n\nsubsection \\<open>Lifting integer polynomials\\<close>\n\nlift_definition of_int_poly :: \"int poly \\<Rightarrow> 'a :: comm_ring_1 poly\" is \"\\<lambda>g x. of_int (g x)\"\n  by (auto elim: eventually_mono)\n\nlemma coeff_of_int_poly [simp]: \"coeff (of_int_poly p) n = of_int (coeff p n)\"\n  by (simp add: of_int_poly.rep_eq)\n\nlemma of_int_poly_0 [simp]: \"of_int_poly 0 = 0\"\n  by transfer (simp add: fun_eq_iff)\n\nlemma of_int_poly_pCons [simp]: \"of_int_poly (pCons c p) = pCons (of_int c) (of_int_poly p)\"\n  by transfer' (simp add: fun_eq_iff split: nat.splits)\n\nlemma of_int_poly_smult [simp]: \"of_int_poly (smult c p) = smult (of_int c) (of_int_poly p)\"\n  by transfer simp\n\nlemma of_int_poly_1 [simp]: \"of_int_poly 1 = 1\"\n  by (simp add: one_pCons)\n\nlemma of_int_poly_add [simp]: \"of_int_poly (p + q) = of_int_poly p + of_int_poly q\"\n  by transfer' (simp add: fun_eq_iff)\n\nlemma of_int_poly_mult [simp]: \"of_int_poly (p * q) = (of_int_poly p * of_int_poly q)\"\n  by (induction p) simp_all\n\nlemma of_int_poly_sum [simp]: \"of_int_poly (sum f A) = sum (\\<lambda>x. of_int_poly (f x)) A\"\n  by (induction A rule: infinite_finite_induct) simp_all\n\nlemma of_int_poly_prod [simp]: \"of_int_poly (prod f A) = prod (\\<lambda>x. of_int_poly (f x)) A\"\n  by (induction A rule: infinite_finite_induct) simp_all\n\nlemma of_int_poly_power [simp]: \"of_int_poly (p ^ n) = of_int_poly p ^ n\"\n  by (induction n) simp_all\n\nlemma of_int_poly_monom [simp]: \"of_int_poly (monom c n) = monom (of_int c) n\"\n  by transfer (simp add: fun_eq_iff)\n\nlemma poly_of_int_poly [simp]: \"poly (of_int_poly p) (of_int x) = of_int (poly p x)\"\n  by (induction p) simp_all\n\nlemma poly_of_int_poly_of_nat [simp]: \"poly (of_int_poly p) (of_nat x) = of_int (poly p (int x))\"\n  by (induction p) simp_all\n\nlemma poly_of_int_poly_0 [simp]: \"poly (of_int_poly p) 0 = of_int (poly p 0)\"\n  by (induction p) simp_all\n\nlemma poly_of_int_poly_1 [simp]: \"poly (of_int_poly p) 1 = of_int (poly p 1)\"\n  by (induction p) simp_all\n\nlemma poly_of_int_poly_of_real [simp]:\n    \"poly (of_int_poly p) (of_real x) = of_real (poly (of_int_poly p) x)\"\n  by (induction p) simp_all\n\nlemma of_int_poly_eq_iff [simp]:\n  \"of_int_poly p = (of_int_poly q :: 'a :: {comm_ring_1, ring_char_0} poly) \\<longleftrightarrow> p = q\"\n  by (simp add: poly_eq_iff)\n\nlemma of_int_poly_eq_0_iff [simp]:\n  \"of_int_poly p = (0 :: 'a :: {comm_ring_1, ring_char_0} poly) \\<longleftrightarrow> p = 0\"\n  using of_int_poly_eq_iff[of p 0] by (simp del: of_int_poly_eq_iff)\n\nlemma degree_of_int_poly [simp]:\n  \"degree (of_int_poly p :: 'a :: {comm_ring_1, ring_char_0} poly) = degree p\"\n  by (simp add: degree_def)\n\nlemma pderiv_of_int_poly [simp]: \"pderiv (of_int_poly p) = of_int_poly (pderiv p)\"\n  by (induction p) (simp_all add: pderiv_pCons)\n\nlemma higher_pderiv_of_int_poly [simp]:\n  \"(pderiv ^^ n) (of_int_poly p) = of_int_poly ((pderiv ^^ n) p)\"\n  by (induction n) simp_all\n\nlemma int_polyE:\n  assumes \"\\<And>n. coeff (p :: 'a :: {comm_ring_1, ring_char_0} poly) n \\<in> \\<int>\"\n  obtains p' where \"p = of_int_poly p'\"\nproof -\n  from assms have \"\\<forall>n. \\<exists>c. coeff p n = of_int c\" by (auto simp: Ints_def)\n  hence \"\\<exists>c. \\<forall>n. of_int (c n) = coeff p n\" by (simp add: choice_iff eq_commute)\n  then obtain c where c: \"of_int (c n) = coeff p n\" for n by blast\n  have [simp]: \"coeff (Abs_poly c) = c\"\n  proof (rule poly.Abs_poly_inverse, clarify)\n    have \"eventually (\\<lambda>n. n > degree p) at_top\" by (rule eventually_gt_at_top)\n    hence \"eventually (\\<lambda>n. coeff p n = 0) at_top\"\n      by eventually_elim (simp add: coeff_eq_0)\n    thus \"eventually (\\<lambda>n. c n = 0) cofinite\"\n      by (simp add: c [symmetric] cofinite_eq_sequentially)\n  qed\n  have \"p = of_int_poly (Abs_poly c)\"\n    by (rule poly_eqI) (simp add: c)\n  thus ?thesis by (rule that)\nqed\n\n\nsubsection \\<open>General facts about polynomials\\<close>\n\nlemma pderiv_power:\n  \"pderiv (p ^ n) = smult (of_nat n) (p ^ (n - 1) * pderiv p)\"\n  by (cases n) (simp_all add: pderiv_power_Suc del: power_Suc)\n\nlemma degree_prod_sum_eq:\n  \"(\\<And>x. x \\<in> A \\<Longrightarrow> f x \\<noteq> 0) \\<Longrightarrow>\n     degree (prod f A :: 'a :: idom poly) = (\\<Sum>x\\<in>A. degree (f x))\"\n  by (induction A rule: infinite_finite_induct) (auto simp: degree_mult_eq)\n\nlemma pderiv_monom:\n  \"pderiv (monom c n) = monom (of_nat n * c) (n - 1)\"\n  by (cases n)\n     (simp_all add: monom_altdef pderiv_power_Suc pderiv_smult pderiv_pCons mult_ac del: power_Suc)\n\nlemma power_poly_const [simp]: \"[:c:] ^ n = [:c ^ n:]\"\n  by (induction n) (simp_all add: power_commutes)\n\nlemma monom_power: \"monom c n ^ k = monom (c ^ k) (n * k)\"\n  by (induction k) (simp_all add: mult_monom)\n\nlemma coeff_higher_pderiv:\n  \"coeff ((pderiv ^^ m) f) n = pochhammer (of_nat (Suc n)) m * coeff f (n + m)\"\n  by (induction m arbitrary: n) (simp_all add: coeff_pderiv pochhammer_rec algebra_simps)\n\nlemma higher_pderiv_add: \"(pderiv ^^ n) (p + q) = (pderiv ^^ n) p + (pderiv ^^ n) q\"\n  by (induction n arbitrary: p q) (simp_all del: funpow.simps add: funpow_Suc_right pderiv_add)\n\nlemma higher_pderiv_smult: \"(pderiv ^^ n) (smult c p) = smult c ((pderiv ^^ n) p)\"\n  by (induction n arbitrary: p) (simp_all del: funpow.simps add: funpow_Suc_right pderiv_smult)\n\nlemma higher_pderiv_0 [simp]: \"(pderiv ^^ n) 0 = 0\"\n  by (induction n) simp_all\n\nlemma higher_pderiv_monom:\n  \"m \\<le> n + 1 \\<Longrightarrow> (pderiv ^^ m) (monom c n) = monom (pochhammer (int n - int m + 1) m * c) (n - m)\"\nproof (induction m arbitrary: c n)\n  case (Suc m)\n  thus ?case\n    by (cases n)\n       (simp_all del: funpow.simps add: funpow_Suc_right pderiv_monom pochhammer_rec' Suc.IH)\nqed simp_all\n\nlemma higher_pderiv_monom_eq_zero:\n  \"m > n + 1 \\<Longrightarrow> (pderiv ^^ m) (monom c n) = 0\"\nproof (induction m arbitrary: c n)\n  case (Suc m)\n  thus ?case\n    by (cases n)\n       (simp_all del: funpow.simps add: funpow_Suc_right pderiv_monom pochhammer_rec' Suc.IH)\nqed simp_all\n\nlemma higher_pderiv_sum: \"(pderiv ^^ n) (sum f A) = (\\<Sum>x\\<in>A. (pderiv ^^ n) (f x))\"\n  by (induction A rule: infinite_finite_induct) (simp_all add: higher_pderiv_add)\n\nlemma fact_dvd_higher_pderiv:\n  \"[:fact n :: int:] dvd (pderiv ^^ n) p\"\nproof -\n  have \"[:fact n:] dvd (pderiv ^^ n) (monom c k)\" for c :: int and k :: nat\n    by (cases \"n \\<le> k + 1\")\n       (simp_all add: higher_pderiv_monom higher_pderiv_monom_eq_zero\n          fact_dvd_pochhammer const_poly_dvd_iff)\n  hence \"[:fact n:] dvd (pderiv ^^ n) (\\<Sum>k\\<le>degree p. monom (coeff p k) k)\"\n    by (simp_all add: higher_pderiv_sum dvd_sum)\n  thus ?thesis by (simp add: poly_as_sum_of_monoms)\nqed\n\nlemma fact_dvd_poly_higher_pderiv_aux:\n  \"(fact n :: int) dvd poly ((pderiv ^^ n) p) x\"\nproof -\n  have \"[:fact n:] dvd (pderiv ^^ n) p\" by (rule fact_dvd_higher_pderiv)\n  then obtain q where \"(pderiv ^^ n) p = [:fact n:] * q\" by (erule dvdE)\n  thus ?thesis by simp\nqed\n\nlemma fact_dvd_poly_higher_pderiv_aux':\n  \"m \\<le> n \\<Longrightarrow> (fact m :: int) dvd poly ((pderiv ^^ n) p) x\"\n  by (meson dvd_trans fact_dvd fact_dvd_poly_higher_pderiv_aux)\n\nlemma algebraicE':\n  assumes \"algebraic (x :: 'a :: field_char_0)\"\n  obtains p where \"p \\<noteq> 0\" \"poly (of_int_poly p) x = 0\"\nproof -\n  from assms obtain q where \"\\<And>i. coeff q i \\<in> \\<int>\" \"q \\<noteq> 0\" \"poly q x = 0\"\n    by (erule algebraicE)\n  moreover from this(1) obtain q' where \"q = of_int_poly q'\" by (erule int_polyE)\n  ultimately show ?thesis by (intro that[of q']) simp_all\nqed\n\nlemma algebraicE'_nonzero:\n  assumes \"algebraic (x :: 'a :: field_char_0)\" \"x \\<noteq> 0\"\n  obtains p where \"p \\<noteq> 0\" \"coeff p 0 \\<noteq> 0\" \"poly (of_int_poly p) x = 0\"\nproof -\n  from assms(1) obtain p where p: \"p \\<noteq> 0\" \"poly (of_int_poly p) x = 0\"\n    by (erule algebraicE')\n  define n :: nat where \"n = order 0 p\"\n  have \"monom 1 n dvd p\" by (simp add: monom_1_dvd_iff p n_def)\n  then obtain q where q: \"p = monom 1 n * q\" by (erule dvdE)\n  from p have \"q \\<noteq> 0\" \"poly (of_int_poly q) x = 0\" by (auto simp: q poly_monom assms(2))\n  moreover from this have \"order 0 p = n + order 0 q\" by (simp add: q order_mult)\n  hence \"order 0 q = 0\" by (simp add: n_def)\n  with \\<open>q \\<noteq> 0\\<close> have \"poly q 0 \\<noteq> 0\" by (simp add: order_root)\n  ultimately show ?thesis using that[of q] by (auto simp: poly_0_coeff_0)\nqed\n\nlemma algebraic_of_real_iff [simp]:\n   \"algebraic (of_real x :: 'a :: {real_algebra_1,field_char_0}) \\<longleftrightarrow> algebraic x\"\nproof\n  assume \"algebraic (of_real x :: 'a)\"\n  then obtain p where \"p \\<noteq> 0\" \"poly (of_int_poly p) (of_real x :: 'a) = 0\"\n    by (erule algebraicE')\n  hence \"(of_int_poly p :: real poly) \\<noteq> 0\"\n        \"poly (of_int_poly p :: real poly) x = 0\" by simp_all\n  thus \"algebraic x\" by (intro algebraicI[of \"of_int_poly p\"]) simp_all\nnext\n  assume \"algebraic x\"\n  then obtain p where \"p \\<noteq> 0\" \"poly (of_int_poly p) x = 0\" by (erule algebraicE')\n  hence \"of_int_poly p \\<noteq> (0 :: 'a poly)\" \"poly (of_int_poly p) (of_real x :: 'a) = 0\"\n    by simp_all\n  thus \"algebraic (of_real x)\" by (intro algebraicI[of \"of_int_poly p\"]) simp_all\nqed\n\n\nsubsection \\<open>Main proof\\<close>\n\nlemma lindemann_weierstrass_integral:\n  fixes u :: complex and f :: \"complex poly\"\n  defines \"df \\<equiv> \\<lambda>n. (pderiv ^^ n) f\"\n  defines \"m \\<equiv> degree f\"\n  defines \"I \\<equiv> \\<lambda>f u. exp u * (\\<Sum>j\\<le>degree f. poly ((pderiv ^^ j) f) 0) -\n                       (\\<Sum>j\\<le>degree f. poly ((pderiv ^^ j) f) u)\"\n  shows \"((\\<lambda>t. exp (u - t) * poly f t) has_contour_integral I f u) (linepath 0 u)\"\nproof -\n  note [derivative_intros] =\n    exp_scaleR_has_vector_derivative_right vector_diff_chain_within\n  let ?g = \"\\<lambda>t. 1 - t\" and ?f = \"\\<lambda>t. -exp (t *\\<^sub>R u)\"\n  have \"((\\<lambda>t. exp ((1 - t) *\\<^sub>R u) * u) has_integral\n          (?f \\<circ> ?g) 1 - (?f \\<circ> ?g) 0) {0..1}\"\n    by (rule fundamental_theorem_of_calculus)\n       (auto intro!: derivative_eq_intros simp del: o_apply)\n  hence aux_integral: \"((\\<lambda>t. exp (u - t *\\<^sub>R u) * u) has_integral exp u - 1) {0..1}\"\n    by (simp add: algebra_simps)\n\n  have \"((\\<lambda>t. exp (u - t *\\<^sub>R u) * u * poly f (t *\\<^sub>R u)) has_integral I f u) {0..1}\"\n    unfolding df_def m_def\n  proof (induction \"degree f\" arbitrary: f)\n    case 0\n    then obtain c where c: \"f = [:c:]\" by (auto elim: degree_eq_zeroE)\n    have \"((\\<lambda>t. c * (exp (u - t *\\<^sub>R u) * u)) has_integral c * (exp u - 1)) {0..1}\"\n      using aux_integral by (rule has_integral_mult_right)\n    with c show ?case by (simp add: algebra_simps I_def)\n  next\n    case (Suc m)\n    define df where \"df = (\\<lambda>j. (pderiv ^^ j) f)\"\n    show ?case\n    proof (rule integration_by_parts[OF bounded_bilinear_mult])\n      fix t :: real assume \"t \\<in> {0..1}\"\n      have \"((?f \\<circ> ?g) has_vector_derivative exp (u - t *\\<^sub>R u) * u) (at t)\"\n        by (auto intro!: derivative_eq_intros simp: algebra_simps simp del: o_apply)\n      thus \"((\\<lambda>t. -exp (u - t *\\<^sub>R u)) has_vector_derivative exp (u - t *\\<^sub>R u) * u) (at t)\"\n        by (simp add: algebra_simps o_def)\n    next\n      fix t :: real assume \"t \\<in> {0..1}\"\n      have \"(poly f \\<circ> (\\<lambda>t. t *\\<^sub>R u) has_vector_derivative u * poly (pderiv f) (t *\\<^sub>R u)) (at t)\"\n        by (rule field_vector_diff_chain_at) (auto intro!: derivative_eq_intros)\n      thus \"((\\<lambda>t. poly f (t *\\<^sub>R u)) has_vector_derivative u * poly (pderiv f) (t *\\<^sub>R u)) (at t)\"\n        by (simp add: o_def)\n    next\n      from Suc(2) have m: \"m = degree (pderiv f)\" by (simp add: degree_pderiv)\n      from Suc(1)[OF this] this\n        have \"((\\<lambda>t. exp (u - t *\\<^sub>R u) * u * poly (pderiv f) (t *\\<^sub>R u)) has_integral\n                exp u * (\\<Sum>j=0..m. poly (df (Suc j)) 0) - (\\<Sum>j=0..m. poly (df (Suc j)) u)) {0..1}\"\n        by (simp add: df_def funpow_swap1 atMost_atLeast0 I_def)\n      also have \"(\\<Sum>j=0..m. poly (df (Suc j)) 0) = (\\<Sum>j=Suc 0..Suc m. poly (df j) 0)\"\n        by (rule sum.shift_bounds_cl_Suc_ivl [symmetric])\n      also have \"\\<dots> = (\\<Sum>j=0..Suc m. poly (df j) 0) - poly f 0\"\n        by (subst (2) sum.atLeast_Suc_atMost) (simp_all add: df_def)\n      also have \"(\\<Sum>j=0..m. poly (df (Suc j)) u) = (\\<Sum>j=Suc 0..Suc m. poly (df j) u)\"\n        by (rule sum.shift_bounds_cl_Suc_ivl [symmetric])\n      also have \"\\<dots> = (\\<Sum>j=0..Suc m. poly (df j) u) - poly f u\"\n        by (subst (2) sum.atLeast_Suc_atMost) (simp_all add: df_def)\n      finally have \"((\\<lambda>t. - (exp (u - t *\\<^sub>R u) * u * poly (pderiv f) (t *\\<^sub>R u))) has_integral\n                        -(exp u * ((\\<Sum>j = 0..Suc m. poly (df j) 0) - poly f 0) -\n                                  ((\\<Sum>j = 0..Suc m. poly (df j) u) - poly f u))) {0..1}\"\n          (is \"(_ has_integral ?I) _\") by (rule has_integral_neg)\n      also have \"?I = - exp (u - 1 *\\<^sub>R u) * poly f (1 *\\<^sub>R u) -\n                       - exp (u - 0 *\\<^sub>R u) * poly f (0 *\\<^sub>R u) - I f u\"\n        by (simp add: df_def algebra_simps Suc(2) atMost_atLeast0 I_def)\n      finally show \"((\\<lambda>t. - exp (u - t *\\<^sub>R u) * (u * poly (pderiv f) (t *\\<^sub>R u)))\n                        has_integral \\<dots>) {0..1}\" by (simp add: algebra_simps)\n    qed (auto intro!: continuous_intros)\n  qed\n  thus ?thesis by (simp add: has_contour_integral_linepath algebra_simps)\nqed\n\nlocale lindemann_weierstrass_aux =\n  fixes f :: \"complex poly\"\nbegin\n\ndefinition I :: \"complex \\<Rightarrow> complex\" where\n  \"I u = exp u * (\\<Sum>j\\<le>degree f. poly ((pderiv ^^ j) f) 0) -\n                       (\\<Sum>j\\<le>degree f. poly ((pderiv ^^ j) f) u)\"\n\nlemma lindemann_weierstrass_integral_bound:\n  fixes u :: complex\n  assumes \"C \\<ge> 0\" \"\\<And>t. t \\<in> closed_segment 0 u \\<Longrightarrow> norm (poly f t) \\<le> C\"\n  shows \"norm (I u) \\<le> norm u * exp (norm u) * C\"\nproof -\n  have \"I u = contour_integral (linepath 0 u) (\\<lambda>t. exp (u - t) * poly f t)\"\n    using contour_integral_unique[OF lindemann_weierstrass_integral[of u f]] unfolding I_def ..\n  also have \"norm \\<dots> \\<le> exp (norm u) * C * norm (u - 0)\"\n  proof (intro contour_integral_bound_linepath)\n    fix t assume t: \"t \\<in> closed_segment 0 u\"\n    then obtain s where s: \"s \\<in> {0..1}\" \"t = s *\\<^sub>R u\" by (auto simp: closed_segment_def)\n    hence \"s * norm u \\<le> 1 * norm u\" by (intro mult_right_mono) simp_all\n    with s have norm_t: \"norm t \\<le> norm u\" by auto\n\n    from s have \"Re u - Re t = (1 - s) * Re u\" by (simp add: algebra_simps)\n    also have \"\\<dots> \\<le> norm u\"\n    proof (cases \"Re u \\<ge> 0\")\n      case True\n      with \\<open>s \\<in> {0..1}\\<close> have \"(1 - s) * Re u \\<le> 1 * Re u\" by (intro mult_right_mono) simp_all\n      also have \"Re u \\<le> norm u\" by (rule complex_Re_le_cmod)\n      finally show ?thesis by simp\n    next\n      case False\n      with \\<open>s \\<in> {0..1}\\<close> have \"(1 - s) * Re u \\<le> 0\" by (intro mult_nonneg_nonpos) simp_all\n      also have \"\\<dots> \\<le> norm u\" by simp\n      finally show ?thesis .\n    qed\n    finally have \"exp (Re u - Re t) \\<le> exp (norm u)\" by simp\n\n    hence \"exp (Re u - Re t) * norm (poly f t) \\<le> exp (norm u) * C\"\n      using assms t norm_t by (intro mult_mono) simp_all\n    thus \"norm (exp (u - t) * poly f t) \\<le> exp (norm u) * C\"\n      by (simp add: norm_mult exp_diff norm_divide field_simps)\n  qed (auto simp: intro!: mult_nonneg_nonneg contour_integrable_continuous_linepath\n                          continuous_intros assms)\n  finally show ?thesis by (simp add: mult_ac)\nqed\n\nend\n\nlemma poly_higher_pderiv_aux1:\n  fixes c :: \"'a :: idom\"\n  assumes \"k < n\"\n  shows   \"poly ((pderiv ^^ k) ([:-c, 1:] ^ n * p)) c = 0\"\n  using assms\nproof (induction k arbitrary: n p)\n  case (Suc k n p)\n  from Suc.prems obtain n' where n: \"n = Suc n'\" by (cases n) auto\n  from Suc.prems n have \"k < n'\" by simp\n  have \"(pderiv ^^ Suc k) ([:- c, 1:] ^ n * p) =\n          (pderiv ^^ k) ([:- c, 1:] ^ n * pderiv p + [:- c, 1:] ^ n' * smult (of_nat n) p)\"\n    by (simp only: funpow_Suc_right o_def pderiv_mult n pderiv_power_Suc,\n        simp only: n [symmetric]) (simp add: pderiv_pCons mult_ac)\n  also from Suc.prems \\<open>k < n'\\<close> have \"poly \\<dots> c = 0\"\n    by (simp add: higher_pderiv_add Suc.IH del: mult_smult_right)\n  finally show ?case .\nqed simp_all\n\nlemma poly_higher_pderiv_aux1':\n  fixes c :: \"'a :: idom\"\n  assumes \"k < n\" \"[:-c, 1:] ^ n dvd p\"\n  shows   \"poly ((pderiv ^^ k) p) c = 0\"\nproof -\n  from assms(2) obtain q where \"p = [:-c, 1:] ^ n * q\" by (elim dvdE)\n  also from assms(1) have \"poly ((pderiv ^^ k) \\<dots>) c = 0\"\n    by (rule poly_higher_pderiv_aux1)\n  finally show ?thesis .\nqed\n\nlemma poly_higher_pderiv_aux2:\n  fixes c :: \"'a :: {idom, semiring_char_0}\"\n  shows   \"poly ((pderiv ^^ n) ([:-c, 1:] ^ n * p)) c = fact n * poly p c\"\nproof (induction n arbitrary: p)\n  case (Suc n p)\n  have \"(pderiv ^^ Suc n) ([:- c, 1:] ^ Suc n * p) =\n          (pderiv ^^ n) ([:- c, 1:] ^ Suc n * pderiv p) +\n            (pderiv ^^ n) ([:- c, 1:] ^ n * smult (1 + of_nat n) p)\"\n    by (simp del: funpow.simps power_Suc add: funpow_Suc_right pderiv_mult\n          pderiv_power_Suc higher_pderiv_add pderiv_pCons mult_ac)\n  also have \"[:- c, 1:] ^ Suc n * pderiv p = [:- c, 1:] ^ n * ([:-c, 1:] * pderiv p)\"\n    by (simp add: algebra_simps)\n  finally show ?case by (simp add: Suc.IH del: mult_smult_right power_Suc)\nqed simp_all\n\nlemma poly_higher_pderiv_aux3:\n  fixes c :: \"'a :: {idom,semiring_char_0}\"\n  assumes \"k \\<ge> n\"\n  shows   \"\\<exists>q. poly ((pderiv ^^ k) ([:-c, 1:] ^ n * p)) c = fact n * poly q c\"\n  using assms\nproof (induction k arbitrary: n p)\n  case (Suc k n p)\n  show ?case\n  proof (cases n)\n    fix n' assume n: \"n = Suc n'\"\n    have \"poly ((pderiv ^^ Suc k) ([:-c, 1:] ^ n * p)) c =\n            poly ((pderiv ^^ k) ([:- c, 1:] ^ n * pderiv p)) c +\n              of_nat n * poly ((pderiv ^^ k) ([:-c, 1:] ^ n' * p)) c\"\n      by (simp del: funpow.simps power_Suc add: funpow_Suc_right pderiv_power_Suc\n            pderiv_mult n pderiv_pCons higher_pderiv_add mult_ac higher_pderiv_smult)\n    also have \"\\<exists>q1. poly ((pderiv ^^ k) ([:-c, 1:] ^ n * pderiv p)) c = fact n * poly q1 c\"\n      using Suc.prems Suc.IH[of n \"pderiv p\"]\n      by (cases \"n' = k\") (auto simp: n poly_higher_pderiv_aux1 simp del: power_Suc of_nat_Suc\n                                intro: exI[of _ \"0::'a poly\"])\n    then obtain q1\n      where \"poly ((pderiv ^^ k) ([:-c, 1:] ^ n * pderiv p)) c = fact n * poly q1 c\" ..\n    also from Suc.IH[of n' p] Suc.prems obtain q2\n      where \"poly ((pderiv ^^ k) ([:-c, 1:] ^ n' * p)) c = fact n' * poly q2 c\"\n      by (auto simp: n)\n    finally show ?case by (auto intro!: exI[of _ \"q1 + q2\"] simp: n algebra_simps)\n  qed auto\nqed auto\n\nlemma poly_higher_pderiv_aux3':\n  fixes c :: \"'a :: {idom, semiring_char_0}\"\n  assumes \"k \\<ge> n\" \"[:-c, 1:] ^ n dvd p\"\n  shows   \"fact n dvd poly ((pderiv ^^ k) p) c\"\nproof -\n  from assms(2) obtain q where \"p = [:-c, 1:] ^ n * q\" by (elim dvdE)\n  with poly_higher_pderiv_aux3[OF assms(1), of c q] show ?thesis by auto\nqed\n\nlemma e_transcendental_aux_bound:\n  obtains C where \"C \\<ge> 0\"\n    \"\\<And>x. x \\<in> closed_segment 0 (of_nat n) \\<Longrightarrow>\n        norm (\\<Prod>k\\<in>{1..n}. (x - of_nat k :: complex)) \\<le> C\"\nproof -\n  let ?f = \"\\<lambda>x. (\\<Prod>k\\<in>{1..n}. (x - of_nat k))\"\n  define C where \"C = max 0 (Sup (cmod ` ?f ` closed_segment 0 (of_nat n)))\"\n  have \"C \\<ge> 0\" by (simp add: C_def)\n  moreover {\n    fix x :: complex assume \"x \\<in> closed_segment 0 (of_nat n)\"\n    hence \"cmod (?f x) \\<le> Sup ((cmod \\<circ> ?f) ` closed_segment 0 (of_nat n))\"\n      by (intro cSup_upper bounded_imp_bdd_above compact_imp_bounded compact_continuous_image)\n         (auto intro!: continuous_intros)\n    also have \"\\<dots> \\<le> C\" by (simp add: C_def image_comp)\n    finally have \"cmod (?f x) \\<le> C\" .\n  }\n  ultimately show ?thesis by (rule that)\nqed\n\n\ntheorem e_transcendental_complex: \"\\<not> algebraic (exp 1 :: complex)\"\nproof\n  assume \"algebraic (exp 1 :: complex)\"\n  then obtain q :: \"int poly\"\n    where q: \"q \\<noteq> 0\" \"coeff q 0 \\<noteq> 0\" \"poly (of_int_poly q) (exp 1 :: complex) = 0\"\n      by (elim algebraicE'_nonzero) simp_all\n\n  define n :: nat where \"n = degree q\"\n  from q have [simp]: \"n \\<noteq> 0\" by (intro notI) (auto simp: n_def elim!: degree_eq_zeroE)\n  define qmax where \"qmax = Max (insert 0 (abs ` set (coeffs q)))\"\n  have qmax_nonneg [simp]: \"qmax \\<ge> 0\" by (simp add: qmax_def)\n  have qmax: \"\\<bar>coeff q k\\<bar> \\<le> qmax\" for k\n    by (cases \"k \\<le> degree q\")\n       (auto simp: qmax_def coeff_eq_0 coeffs_def simp del: upt_Suc intro: Max.coboundedI)\n  obtain C where C: \"C \\<ge> 0\"\n    \"\\<And>x. x \\<in> closed_segment 0 (of_nat n) \\<Longrightarrow> norm (\\<Prod>k\\<in>{1..n}. (x - of_nat k :: complex)) \\<le> C\"\n    by (erule e_transcendental_aux_bound)\n  define E where \"E = (1 + real n) * real_of_int qmax * real n * exp (real n) / real n\"\n  define F where \"F = real n * C\"\n\n  have ineq: \"fact (p - 1) \\<le> E * F ^ p\" if p: \"prime p\" \"p > n\" \"p > abs (coeff q 0)\" for p\n  proof -\n    from p(1) have p_pos: \"p > 0\" by (simp add: prime_gt_0_nat)\n    define f :: \"int poly\"\n      where \"f = monom 1 (p - 1) * (\\<Prod>k\\<in>{1..n}. [:-of_nat k, 1:] ^ p)\"\n    have poly_f: \"poly (of_int_poly f) x = x ^ (p - 1) * (\\<Prod>k\\<in>{1..n}. (x - of_nat k)) ^ p\"\n      for x :: complex by (simp add: f_def poly_prod poly_monom prod_power_distrib)\n    define m :: nat where \"m = degree f\"\n    from p_pos have m: \"m = (n + 1) * p - 1\"\n      by (simp add: m_def f_def degree_mult_eq degree_monom_eq degree_prod_sum_eq degree_linear_power)\n\n    define M :: int where \"M = (- 1) ^ (n * p) * fact n ^ p\"\n    with p have p_not_dvd_M: \"\\<not>int p dvd M\"\n      by (auto simp: M_def prime_elem_int_not_dvd_neg1_power prime_dvd_power_iff\n            prime_gt_0_nat prime_dvd_fact_iff_int prime_dvd_mult_iff)\n\n    interpret lindemann_weierstrass_aux \"of_int_poly f\" .\n    define J :: complex where \"J = (\\<Sum>k\\<le>n. of_int (coeff q k) * I (of_nat k))\"\n    define idxs where \"idxs = ({..n}\\<times>{..m}) - {(0, p - 1)}\"\n\n    hence \"J = (\\<Sum>k\\<le>n. of_int (coeff q k) * exp 1 ^ k) * (\\<Sum>n\\<le>m. of_int (poly ((pderiv ^^ n) f) 0)) -\n                 of_int (\\<Sum>k\\<le>n. \\<Sum>n\\<le>m. coeff q k * poly ((pderiv ^^ n) f) (int k))\"\n      by (simp add: J_def I_def algebra_simps sum_subtractf sum_distrib_left m_def\n                    exp_of_nat_mult [symmetric])\n    also have \"(\\<Sum>k\\<le>n. of_int (coeff q k) * exp 1 ^ k) = poly (of_int_poly q) (exp 1 :: complex)\"\n      by (simp add: poly_altdef n_def)\n    also have \"\\<dots> = 0\" by fact\n    finally have \"J = of_int (-(\\<Sum>(k,n)\\<in>{..n}\\<times>{..m}. coeff q k * poly ((pderiv ^^ n) f) (int k)))\"\n      by (simp add: sum.cartesian_product)\n    also have \"{..n}\\<times>{..m} = insert (0, p - 1) idxs\" by (auto simp: m idxs_def)\n    also have \"-(\\<Sum>(k,n)\\<in>\\<dots>. coeff q k * poly ((pderiv ^^ n) f) (int k)) =\n       - (coeff q 0 * poly ((pderiv ^^ (p - 1)) f) 0) -\n         (\\<Sum>(k, n)\\<in>idxs. coeff q k * poly ((pderiv ^^ n) f) (of_nat k))\"\n      by (subst sum.insert) (simp_all add: idxs_def)\n    also have \"coeff q 0 * poly ((pderiv ^^ (p - 1)) f) 0 = coeff q 0 * M * fact (p - 1)\"\n    proof -\n      have \"f = [:-0, 1:] ^ (p - 1) * (\\<Prod>k = 1..n. [:- of_nat k, 1:] ^ p)\"\n        by (simp add: f_def monom_altdef)\n      also have \"poly ((pderiv ^^ (p - 1)) \\<dots>) 0 =\n                   fact (p - 1) * poly (\\<Prod>k = 1..n. [:- of_nat k, 1:] ^ p) 0\"\n        by (rule poly_higher_pderiv_aux2)\n      also have \"poly (\\<Prod>k = 1..n. [:- of_nat k :: int, 1:] ^ p) 0 = (-1)^(n*p) * fact n ^ p\"\n        by (induction n) (simp_all add: prod.nat_ivl_Suc' power_mult_distrib mult_ac\n                            power_minus' power_add del: of_nat_Suc)\n      finally show ?thesis by (simp add: mult_ac M_def)\n    qed\n    also obtain N where \"(\\<Sum>(k, n)\\<in>idxs. coeff q k * poly ((pderiv ^^ n) f) (int k)) = fact p * N\"\n    proof -\n      have \"\\<forall>(k, n)\\<in>idxs. fact p dvd poly ((pderiv ^^ n) f) (of_nat k)\"\n      proof clarify\n        fix k j assume idxs: \"(k, j) \\<in> idxs\"\n        then consider \"k = 0\" \"j < p - 1\" | \"k = 0\" \"j > p - 1\" | \"k \\<noteq> 0\" \"j < p\" | \"k \\<noteq> 0\" \"j \\<ge> p\"\n          by (fastforce simp: idxs_def)\n        thus \"fact p dvd poly ((pderiv ^^ j) f) (of_nat k)\"\n        proof cases\n          case 1\n          thus ?thesis\n            by (simp add: f_def poly_higher_pderiv_aux1' monom_altdef)\n        next\n          case 2\n          thus ?thesis\n            by (simp add: f_def poly_higher_pderiv_aux3' monom_altdef fact_dvd_poly_higher_pderiv_aux')\n        next\n          case 3\n          thus ?thesis unfolding f_def\n            by (subst poly_higher_pderiv_aux1'[of _ p])\n               (insert idxs, auto simp: idxs_def intro!: dvd_mult)\n        next\n          case 4\n          thus ?thesis unfolding f_def\n            by (intro poly_higher_pderiv_aux3') (insert idxs, auto intro!: dvd_mult simp: idxs_def)\n        qed\n      qed\n      hence \"fact p dvd (\\<Sum>(k, n)\\<in>idxs. coeff q k * poly ((pderiv ^^ n) f) (int k))\"\n        by (auto intro!: dvd_sum dvd_mult simp del: of_int_fact)\n      with that show thesis\n        by blast\n    qed\n    also from p have \"- (coeff q 0 * M * fact (p - 1)) - fact p * N =\n                        - fact (p - 1) * (coeff q 0 * M + p * N)\"\n      by (subst fact_reduce[of p]) (simp_all add: algebra_simps)\n    finally have J: \"J = -of_int (fact (p - 1) * (coeff q 0 * M + p * N))\" by simp\n\n    from p q(2) have \"\\<not>p dvd coeff q 0 * M + p * N\"\n      by (auto simp: dvd_add_left_iff p_not_dvd_M prime_dvd_fact_iff_int prime_dvd_mult_iff\n               dest: dvd_imp_le_int)\n    hence \"coeff q 0 * M + p * N \\<noteq> 0\" by (intro notI) simp_all\n    hence \"abs (coeff q 0 * M + p * N) \\<ge> 1\" by simp\n    hence \"norm (of_int (coeff q 0 * M + p * N) :: complex) \\<ge> 1\" by (simp only: norm_of_int)\n    hence \"fact (p - 1) * \\<dots> \\<ge> fact (p - 1) * 1\" by (intro mult_left_mono) simp_all\n    hence J_lower: \"norm J \\<ge> fact (p - 1)\" unfolding J norm_minus_cancel of_int_mult of_int_fact\n      by (simp add: norm_mult)\n\n    have \"norm J \\<le> (\\<Sum>k\\<le>n. norm (of_int (coeff q k) * I (of_nat k)))\"\n      unfolding J_def by (rule norm_sum)\n    also have \"\\<dots> \\<le> (\\<Sum>k\\<le>n. of_int qmax * (real n * exp (real n) * real n ^ (p - 1) * C ^ p))\"\n    proof (intro sum_mono)\n      fix k assume k: \"k \\<in> {..n}\"\n      have \"n > 0\" by (rule ccontr) simp\n      {\n        fix x :: complex assume x: \"x \\<in> closed_segment 0 (of_nat k)\"\n        then obtain t where t: \"t \\<ge> 0\" \"t \\<le> 1\" \"x = of_real t * of_nat k\"\n          by (auto simp: closed_segment_def scaleR_conv_of_real)\n        hence \"norm x = t * real k\" by (simp add: norm_mult)\n        also from \\<open>t \\<le> 1\\<close> k have *: \"\\<dots> \\<le> 1 * real n\" by (intro mult_mono) simp_all\n        finally have x': \"norm x \\<le> real n\" by simp\n        from t \\<open>n > 0\\<close> * have x'': \"x \\<in> closed_segment 0 (of_nat n)\"\n          by (auto simp: closed_segment_def scaleR_conv_of_real field_simps\n                   intro!: exI[of _ \"t * real k / real n\"] )\n        have \"norm (poly (of_int_poly f) x) =\n                norm x ^ (p - 1) * cmod (\\<Prod>i = 1..n. x - i) ^ p\"\n          by (simp add: poly_f norm_mult norm_power)\n        also from x x' x'' have \"\\<dots> \\<le> of_nat n ^ (p - 1) * C ^ p\"\n          by (intro mult_mono C power_mono) simp_all\n        finally have \"norm (poly (of_int_poly f) x) \\<le> real n ^ (p - 1) * C ^ p\" .\n      } note A = this\n\n      have \"norm (I (of_nat k)) \\<le>\n                      cmod (of_nat k) * exp (cmod (of_nat k)) * (of_nat n ^ (p - 1) * C ^ p)\"\n        by (intro lindemann_weierstrass_integral_bound[OF _ A]\n              C mult_nonneg_nonneg zero_le_power) auto\n      also have \"\\<dots> \\<le> cmod (of_nat n) * exp (cmod (of_nat n)) * (of_nat n ^ (p - 1) * C ^ p)\"\n        using k by (intro mult_mono zero_le_power mult_nonneg_nonneg C) simp_all\n      finally show \"cmod (of_int (coeff q k) * I (of_nat k)) \\<le>\n                      of_int qmax * (real n * exp (real n) * real n ^ (p - 1) * C ^ p)\"\n        unfolding norm_mult\n        by (intro mult_mono) (simp_all add: qmax of_int_abs [symmetric] del: of_int_abs)\n    qed\n    also have \"\\<dots> = E * F ^ p\" using p_pos\n      by (simp add: power_diff power_mult_distrib E_def F_def)\n    finally show \"fact (p - 1) \\<le> E * F ^ p\" using J_lower by linarith\n  qed\n\n  have \"(\\<lambda>n. E * F * F ^ (n - 1) / fact (n - 1)) \\<longlonglongrightarrow> 0\" (is ?P)\n    by (intro filterlim_compose[OF power_over_fact_tendsto_0' filterlim_minus_const_nat_at_top])\n  also have \"?P \\<longleftrightarrow> (\\<lambda>n. E * F ^ n / fact (n - 1)) \\<longlonglongrightarrow> 0\"\n    by (intro filterlim_cong refl eventually_mono[OF eventually_gt_at_top[of \"0::nat\"]])\n       (auto simp: power_Suc [symmetric] simp del: power_Suc)\n  finally have \"eventually (\\<lambda>n. E * F ^ n / fact (n - 1) < 1) at_top\"\n    by (rule order_tendstoD) simp_all\n  hence \"eventually (\\<lambda>n. E * F ^ n < fact (n - 1)) at_top\" by eventually_elim simp\n  then obtain P where P: \"\\<And>n. n \\<ge> P \\<Longrightarrow> E * F ^ n < fact (n - 1)\"\n    by (auto simp: eventually_at_top_linorder)\n\n  have \"\\<exists>p. prime p \\<and> p > Max {nat (abs (coeff q 0)), n, P}\" by (rule bigger_prime)\n  then obtain p where \"prime p\" \"p > Max {nat (abs (coeff q 0)), n, P}\" by blast\n  hence \"int p > abs (coeff q 0)\" \"p > n\" \"p \\<ge> P\" by auto\n  with ineq[of p] \\<open>prime p\\<close> have \"fact (p - 1) \\<le> E * F ^ p\" by simp\n  moreover from \\<open>p \\<ge> P\\<close> have \"fact (p - 1) > E * F ^ p\" by (rule P)\n  ultimately show False by linarith\nqed\n\ncorollary e_transcendental_real: \"\\<not> algebraic (exp 1 :: real)\"\nproof -\n  have \"\\<not>algebraic (exp 1 :: complex)\" by (rule e_transcendental_complex)\n  also have \"(exp 1 :: complex) = of_real (exp 1)\" using exp_of_real[of 1] by simp\n  also have \"algebraic \\<dots> \\<longleftrightarrow> algebraic (exp 1 :: real)\" by simp\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/E_Transcendental/E_Transcendental.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8519528094861981, "lm_q2_score": 0.855851143290548, "lm_q1q2_score": 0.7291447860283571}}
{"text": "(*  \n    Title:      Gauss_Jordan_PA.thy\n    Author:     Jose Divas\u00f3n <jose.divasonm at unirioja.es>\n    Author:     Jes\u00fas Aransay <jesus-maria.aransay at unirioja.es>\n*)\n\nheader{*Obtaining explicitly the invertible matrix which transforms a matrix to its reduced row echelon form*}\n\ntheory Gauss_Jordan_PA\nimports\n Gauss_Jordan\n \"../Rank_Nullity_Theorem/Miscellaneous\"\n Linear_Maps (*Really, this file is not necessary, but it contains interesting properties about linear maps.*)\nbegin\n\nsubsection{*Definitions*}\n\ntext{*The following algorithm is similar to @{term \"Gauss_Jordan\"},\nbut in this case we will also return the P matrix which makes @{term \"Gauss_Jordan A = P ** A\"}. If A is invertible, this matrix P will be the inverse of it.*}\n\ndefinition Gauss_Jordan_in_ij_PA :: \"(('a::{semiring_1, inverse, one, uminus}^'rows::{finite, ord}^'rows::{finite, ord}) \\<times> ('a^'cols^'rows::{finite, ord})) => 'rows=>'cols\n  =>(('a^'rows::{finite, ord}^'rows::{finite, ord}) \\<times> ('a^'cols^'rows::{finite, ord}))\"\nwhere \"Gauss_Jordan_in_ij_PA A' i j = (let P=fst A'; A=snd A';\n                                        n = (LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n);\n                                        interchange_A = (interchange_rows A i n);\n                                        interchange_P = (interchange_rows P i n);\n                                        P' = mult_row interchange_P i (1/interchange_A$i$j)\n                                        in                                        \n                                       (vec_lambda(% s. if s=i then P' $ s else (row_add P' s i (-(interchange_A$s$j))) $ s), Gauss_Jordan_in_ij A i j))\"\n\ndefinition Gauss_Jordan_column_k_PA  \nwhere \"Gauss_Jordan_column_k_PA A' k =\n    (let P = fst A';\n         i = fst (snd A');\n         A = snd (snd A');\n         from_nat_i=from_nat i;\n         from_nat_k=from_nat k\n         in \n         if (\\<forall>m\\<ge>from_nat_i. A $ m $ from_nat_k = 0) \\<or> i = nrows A then (P, i, A)\n         else (let Gauss = Gauss_Jordan_in_ij_PA (P,A) (from_nat_i) (from_nat_k) in (fst Gauss, i + 1, snd Gauss)))\"\n\ndefinition \"Gauss_Jordan_upt_k_PA A k = (let foldl=(foldl Gauss_Jordan_column_k_PA (mat 1,0, A) [0..<Suc k]) in (fst foldl, snd (snd foldl)))\"\ndefinition \"Gauss_Jordan_PA A = Gauss_Jordan_upt_k_PA A (ncols A - 1)\"\n\nsubsection{*Proofs*}\n\nsubsubsection{*Properties about @{term \"Gauss_Jordan_in_ij_PA\"}*}\n\ntext{*The following lemmas are very important in order to improve the efficience of the code*}\ntext{*We define the following function to obtain an efficient code for @{term \"Gauss_Jordan_in_ij_PA A i j\"}.*}\n\ndefinition \"Gauss_Jordan_wrapper i j A B = vec_lambda(%s. if s=i then A $ s else (row_add A s i (-(B$s$j))) $ s)\"\n\nlemma Gauss_Jordan_wrapper_code[code abstract]:\n  \"vec_nth (Gauss_Jordan_wrapper i j A B) = (%s. if s=i then A $ s else (row_add A s i (-(B$s$j))) $ s)\"\n  unfolding Gauss_Jordan_wrapper_def by force\n\nlemma Gauss_Jordan_in_ij_PA_def'[code]:\n   \"Gauss_Jordan_in_ij_PA A' i j = (let P=fst A'; A=snd A';\n                                        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);\n                                        interchange_P = (interchange_rows P i n);\n                                        P' = mult_row interchange_P i (1/interchange_A$i$j)\n                                        in                                       \n                                       (Gauss_Jordan_wrapper i j P' interchange_A, \n                                        Gauss_Jordan_wrapper i j A' interchange_A))\"\nunfolding Gauss_Jordan_in_ij_PA_def Gauss_Jordan_in_ij_def Let_def Gauss_Jordan_wrapper_def by auto\n\n\ntext{*The second component is equal to @{term \"Gauss_Jordan_in_ij\"}*}\nlemma snd_Gauss_Jordan_in_ij_PA_eq[code_unfold]: \"snd (Gauss_Jordan_in_ij_PA (P,A) i j) = Gauss_Jordan_in_ij A i j\"\n  unfolding Gauss_Jordan_in_ij_PA_def Let_def snd_conv ..\n\nlemma fst_Gauss_Jordan_in_ij_PA:\nfixes A::\"'a::{field}^'cols::{mod_type}^'rows::{mod_type}\"\nassumes PB_A: \"P ** B = A\"\nshows \"fst (Gauss_Jordan_in_ij_PA (P,A) i j) ** B = snd (Gauss_Jordan_in_ij_PA (P,A) i j)\"\nproof (unfold Gauss_Jordan_in_ij_PA_def' Gauss_Jordan_wrapper_def Let_def fst_conv snd_conv, subst (1 2 3 4 5 6 7 8 9 10) interchange_rows_mat_1[symmetric], subst vec_eq_iff, auto)\nshow \"((\\<chi> s. if s = i then mult_row (interchange_rows (mat 1) i (LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n) ** P) i (1 / (interchange_rows (mat 1) i (LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n) ** A) $ i $ j) $ s\n              else row_add (mult_row (interchange_rows (mat 1) i (LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n) ** P) i (1 / (interchange_rows (mat 1) i (LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n) ** A) $ i $ j)) s i\n              (- (interchange_rows (mat 1) i (LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n) ** A) $ s $ j) $ s) ** B) $ i =\n              mult_row (interchange_rows (mat 1) i (LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n) ** A) i (1 / (interchange_rows (mat 1) i (LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n) ** A) $ i $ j) $ i\"\nproof (unfold matrix_matrix_mult_def, vector, auto)\nfix ia\nhave \"mult_row (interchange_rows (mat 1) i (LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n) ** P) i (1 / (interchange_rows (mat 1) i (LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n) ** A) $ i $ j)\n** B = mult_row (interchange_rows (mat 1) i (LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n) ** A) i (1 / (interchange_rows (mat 1) i (LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n) ** A) $ i $ j)\"\nby(subst (5) PB_A[symmetric], subst (1 2) mult_row_mat_1[symmetric], unfold matrix_mul_assoc, rule refl)\nthus \"(\\<Sum>k\\<in>UNIV. mult_row (\\<chi> ia ja. \\<Sum>k\\<in>UNIV. interchange_rows (mat 1) i (LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n) $ ia $ k * P $ k $ ja) i\n                     (1 / (\\<Sum>k\\<in>UNIV. mat 1 $ (LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n) $ k * A $ k $ j)) $ i $ k * B $ k $ ia) =\n                     mult_row (\\<chi> ia ja. \\<Sum>k\\<in>UNIV. interchange_rows (mat 1) i (LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n) $ ia $ k * A $ k $ ja) i\n                     (1 / (\\<Sum>k\\<in>UNIV. mat 1 $ (LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n) $ k * A $ k $ j)) $ i $ ia\"\nunfolding matrix_matrix_mult_def\nunfolding vec_lambda_beta unfolding interchange_rows_i using setsum.cong\nby (metis (lifting, no_types) vec_lambda_beta)\nqed\nnext\nfix ia assume ia_not_i: \"ia \\<noteq> i\"\nhave \"((\\<chi> s. if s = i then mult_row (interchange_rows (mat 1) i (LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n) ** P) i (1 / (interchange_rows (mat 1) i (LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n) ** A) $ i $ j) $\n             s else row_add (mult_row (interchange_rows (mat 1) i (LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n) ** P) i (1 / (interchange_rows (mat 1) i (LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n) ** A) $ i $ j)) s\n             i (- (interchange_rows (mat 1) i (LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n) ** A) $ s $ j) $ s) ** B) $ ia =\n((\\<chi> s. row_add (mult_row (interchange_rows (mat 1) i (LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n) ** P) i (1 / (interchange_rows (mat 1) i (LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n) ** A) $ i $ j)) s\n             i (- (interchange_rows (mat 1) i (LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n) ** A) $ s $ j) $ s) ** B) $ ia\"\nunfolding row_matrix_matrix_mult[symmetric]\nusing ia_not_i by auto\nalso have \"... = row_add (mult_row (interchange_rows (mat 1) i (LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n) ** P) i (1 / (interchange_rows (mat 1) i (LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n) ** A) $ i $ j)) ia i\n     (- (interchange_rows (mat 1) i (LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n) ** A) $ ia $ j) $ ia v* B\"\n     by (subst (3) row_matrix_matrix_mult[symmetric], simp)\nalso have \"... = row_add (mult_row (interchange_rows (mat 1) i (LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n) ** A) i (1 / (interchange_rows (mat 1) i (LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n) ** A) $ i $ j)) ia i\n             (- (interchange_rows (mat 1) i (LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n) ** A) $ ia $ j) $ ia\"\napply (subst (7) PB_A[symmetric])\napply (subst (1 2) mult_row_mat_1[symmetric])\napply (subst (1 2) row_add_mat_1[symmetric])\nunfolding matrix_mul_assoc\nunfolding row_matrix_matrix_mult ..\nfinally show \"((\\<chi> s. if s = i then mult_row (interchange_rows (mat 1) i (LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n) ** P) i (1 / (interchange_rows (mat 1) i (LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n) ** A) $ i $ j) $ s\n        else row_add (mult_row (interchange_rows (mat 1) i (LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n) ** P) i (1 / (interchange_rows (mat 1) i (LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n) ** A) $ i $ j)) s i\n              (- (interchange_rows (mat 1) i (LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n) ** A) $ s $ j) $ s) ** B) $ ia =\n  row_add (mult_row (interchange_rows (mat 1) i (LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n) ** A) i (1 / (interchange_rows (mat 1) i (LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n) ** A) $ i $ j)) ia i\n   (- (interchange_rows (mat 1) i (LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n) ** A) $ ia $ j) $ ia\" .\nqed\n\n\nsubsubsection{*Properties about @{term \"Gauss_Jordan_column_k_PA\"}*}\nlemma fst_Gauss_Jordan_column_k: \nassumes \"i\\<le>nrows A\"\nshows \"fst (Gauss_Jordan_column_k (i, A) k) \\<le> nrows A\"\nusing assms unfolding Gauss_Jordan_column_k_def Let_def by auto\n\nlemma fst_Gauss_Jordan_column_k_PA:\nfixes A::\"'a::{field}^'cols::{mod_type}^'rows::{mod_type}\"\nassumes PB_A: \"P ** B = A\"\nshows \"fst (Gauss_Jordan_column_k_PA (P,i,A) k) ** B = snd (snd (Gauss_Jordan_column_k_PA (P,i,A) k))\"\nunfolding Gauss_Jordan_column_k_PA_def unfolding Let_def\nunfolding fst_conv snd_conv by (auto intro: assms fst_Gauss_Jordan_in_ij_PA)\n\nlemma snd_snd_Gauss_Jordan_column_k_PA_eq: \nshows \"snd (snd (Gauss_Jordan_column_k_PA (P,i,A) k)) = snd (Gauss_Jordan_column_k (i,A) k)\"\nunfolding Gauss_Jordan_column_k_PA_def Gauss_Jordan_column_k_def unfolding Let_def snd_conv fst_conv unfolding snd_Gauss_Jordan_in_ij_PA_eq by auto\n\nlemma fst_snd_Gauss_Jordan_column_k_PA_eq: \nshows \"fst (snd (Gauss_Jordan_column_k_PA (P,i,A) k)) = fst (Gauss_Jordan_column_k (i,A) k)\"\nunfolding Gauss_Jordan_column_k_PA_def Gauss_Jordan_column_k_def unfolding Let_def snd_conv fst_conv by auto\n\nsubsubsection{*Properties about @{term \"Gauss_Jordan_upt_k_PA\"}*}\n\nlemma fst_Gauss_Jordan_upt_k_PA:\nfixes A::\"'a::{field}^'cols::{mod_type}^'rows::{mod_type}\"\nshows \"fst (Gauss_Jordan_upt_k_PA A k) ** A = snd (Gauss_Jordan_upt_k_PA A k)\"\nproof (induct k)\nshow \"fst (Gauss_Jordan_upt_k_PA A 0) ** A = snd (Gauss_Jordan_upt_k_PA A 0)\" unfolding Gauss_Jordan_upt_k_PA_def Let_def fst_conv snd_conv\napply auto unfolding snd_snd_Gauss_Jordan_column_k_PA_eq by (metis fst_Gauss_Jordan_column_k_PA matrix_mul_lid snd_snd_Gauss_Jordan_column_k_PA_eq)\nnext\ncase (Suc k)\nhave suc_rw: \"[0..<Suc (Suc k)] = [0..<Suc k] @ [Suc k]\" by simp\nshow ?case \nunfolding Gauss_Jordan_upt_k_PA_def Let_def fst_conv snd_conv\nunfolding suc_rw unfolding foldl_append unfolding List.foldl.simps using Suc.hyps[unfolded Gauss_Jordan_upt_k_PA_def Let_def fst_conv snd_conv]\nby (metis fst_Gauss_Jordan_column_k_PA pair_collapse)\nqed\n\nlemma snd_foldl_Gauss_Jordan_column_k_eq:\n\"snd (foldl Gauss_Jordan_column_k_PA (mat 1, 0, A) [0..<k]) = foldl Gauss_Jordan_column_k (0, A) [0..<k]\"\nproof (induct k)\ncase 0\nshow ?case by simp\ncase (Suc k)\nhave suc_rw: \"[0..<Suc k] = [0..<k] @ [k]\" by simp\nshow ?case \nunfolding suc_rw foldl_append unfolding List.foldl.simps by (metis Suc.hyps fst_snd_Gauss_Jordan_column_k_PA_eq snd_snd_Gauss_Jordan_column_k_PA_eq surjective_pairing)\nqed\n\nlemma snd_Gauss_Jordan_upt_k_PA:\nshows \"snd (Gauss_Jordan_upt_k_PA A k) = (Gauss_Jordan_upt_k A k)\"\nunfolding Gauss_Jordan_upt_k_PA_def Gauss_Jordan_upt_k_def Let_def\nusing snd_foldl_Gauss_Jordan_column_k_eq[of A \"Suc k\"] by simp\n\nsubsubsection{*Properties about @{term \"Gauss_Jordan_PA\"}*}\n\nlemma fst_Gauss_Jordan_PA:\nfixes A::\"'a::{field}^'cols::{mod_type}^'rows::{mod_type}\"\nshows \"fst (Gauss_Jordan_PA A) ** A = snd (Gauss_Jordan_PA A)\"\nunfolding Gauss_Jordan_PA_def using fst_Gauss_Jordan_upt_k_PA by simp\n\nlemma Gauss_Jordan_PA_eq:\nshows \"snd (Gauss_Jordan_PA A)= (Gauss_Jordan A)\"\nby (metis Gauss_Jordan_PA_def Gauss_Jordan_def snd_Gauss_Jordan_upt_k_PA)\n\nsubsubsection{*Proving that the transformation has been carried out by means of elementary operations*}\ntext{*This function is very similar to @{term \"row_add_iterate\"} one. It allows us to prove that @{term \"fst (Gauss_Jordan_PA A)\"} is an invertible matrix.\nConcretly, it has been defined to demonstrate that @{term \"fst (Gauss_Jordan_PA A)\"} has been obtained by means of elementary operations applied to the identity matrix*}\n\nfun row_add_iterate_PA :: \"(('a::{semiring_1, uminus}^'m::{mod_type} ^'m::{mod_type}) \\<times> ('a^'n^'m::{mod_type}))=> nat => 'm => 'n => \n    (('a^'m::{mod_type} ^'m::{mod_type}) \\<times> ('a^'n^'m::{mod_type}))\"\n    where \"row_add_iterate_PA (P,A) 0 i j = (if i=0 then (P,A) else (row_add P 0 i (-A $ 0 $ j), row_add A 0 i (-A $ 0 $ j)))\"\n         | \"row_add_iterate_PA (P,A) (Suc n) i j = (if (Suc n = to_nat i) then row_add_iterate_PA (P,A) n i j\n                  else row_add_iterate_PA ((row_add P (from_nat (Suc n)) i (- A $ (from_nat (Suc n)) $ j)), (row_add A (from_nat (Suc n)) i (- A $ (from_nat (Suc n)) $ j))) n i j)\"\n\nlemma fst_row_add_iterate_PA_preserves_greater_than_n:\n  assumes n: \"n<nrows A\"\n  and a: \"to_nat a > n\"\n  shows \"fst (row_add_iterate_PA (P,A) n i j) $ a $ b = P $ a $ b\"\n  using assms\nproof (induct n arbitrary: A P)\n  case 0\n  show ?case unfolding row_add_iterate.simps\n  proof (auto)\n    assume \"i \\<noteq> 0\"\n    hence \"a \\<noteq> 0\" by (metis \"0.prems\"(2) less_numeral_extra(3) to_nat_0)\n    thus \"row_add P 0 i (- A $ 0 $ j) $ a $ b = P $ a $ b\" unfolding row_add_def by auto\n  qed\nnext\n  case (Suc n)  \n  have row_add_iterate_A: \"fst (row_add_iterate_PA (P,A) n i j) $ a $ b = P $ a $ b\" using Suc.hyps Suc.prems by auto\n  show ?case\n  proof (cases \"Suc n = to_nat i\")\n    case True\n    show \"fst (row_add_iterate_PA (P, A) (Suc n) i j) $ a $ b = P $ a $ b\" unfolding row_add_iterate_PA.simps if_P[OF True] using row_add_iterate_A .\n  next\n    case False\n    def A' \\<equiv> \"row_add A (from_nat (Suc n)) i (- A $ from_nat (Suc n) $ j)\"\n    def P' \\<equiv> \"row_add P (from_nat (Suc n)) i (- A $ from_nat (Suc n) $ j)\"\n    have row_add_iterate_A': \"fst (row_add_iterate_PA (P',A') n i j) $ a $ b = P' $ a $ b\" using Suc.hyps Suc.prems unfolding nrows_def by auto\n    have from_nat_not_a: \"from_nat (Suc n) \\<noteq> a\" by (metis less_not_refl Suc.prems to_nat_from_nat_id nrows_def)\n    show \"fst (row_add_iterate_PA (P, A) (Suc n) i j) $ a $ b = P $ a $ b\" unfolding row_add_iterate_PA.simps if_not_P[OF False] row_add_iterate_A'[unfolded A'_def P'_def]\n      unfolding row_add_def using from_nat_not_a by simp\n  qed\nqed\n\n\n\nlemma snd_row_add_iterate_PA_eq_row_add_iterate:\nshows \"snd (row_add_iterate_PA (P,A) n i j)  = row_add_iterate A n i j\"\nproof (induct n arbitrary: P A)\ncase 0\nshow ?case unfolding row_add_iterate_PA.simps row_add_iterate.simps by simp\nnext\ncase (Suc n)\nshow ?case unfolding row_add_iterate_PA.simps row_add_iterate.simps by (simp add: Suc.hyps)\nqed\n\nlemma row_add_iterate_PA_preserves_pivot_row:\n  assumes n: \"n<nrows A\"\n  and a: \"to_nat i \\<le> n\"\n  shows \"fst (row_add_iterate_PA (P,A) n i j) $ i $ b = P $ i $ b\"\nusing assms\nproof (induct n arbitrary: P A)\ncase 0\nshow ?case by (metis \"0.prems\"(2) fst_conv le_0_eq row_add_iterate_PA.simps(1) to_nat_eq_0)\nnext\ncase (Suc n)\nshow ?case\nproof (cases \"Suc n = to_nat i\")\ncase True show ?thesis unfolding row_add_iterate_PA.simps if_P[OF True]\n  proof (rule fst_row_add_iterate_PA_preserves_greater_than_n)\n     show \"n < nrows A\" by (metis Suc.prems(1) Suc_lessD)\n     show \"n < to_nat i\" by (metis True lessI)\n  qed\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 from_nat_noteq_i: \"from_nat (Suc n) \\<noteq> i\"  using False Suc.prems(1) from_nat_not_eq unfolding nrows_def by blast\nhave hyp: \"fst (row_add_iterate_PA (P', A') n i j) $ i $ b = P' $ i $ b\"\nproof (rule Suc.hyps)\nshow \"n < nrows A'\" using Suc.prems(1) unfolding nrows_def by simp\nshow \"to_nat i \\<le> n\" using Suc.prems(2) False by simp\nqed\nshow ?thesis unfolding row_add_iterate_PA.simps unfolding if_not_P[OF False] unfolding hyp[unfolded A'_def P'_def]\nunfolding row_add_def using from_nat_noteq_i by auto\nqed\nqed\n\n\nlemma fst_row_add_iterate_PA_eq_row_add:\n  fixes A::\"'a::{ring_1}^'n^'m::{mod_type}\"\n  assumes a_not_i: \"a \\<noteq> i\"\n  and n: \"n<nrows A\"\n  and \"to_nat a \\<le> n\"\n  shows \"fst (row_add_iterate_PA (P,A) n i j) $ a $ b = (row_add P a i (- A $ a $ j)) $ a $ b\" \n  using assms\nproof (induct n arbitrary: A P)\ncase 0 show ?case by (metis \"0.prems\"(3) a_not_i fst_conv le_0_eq row_add_iterate_PA.simps(1) to_nat_eq_0)\nnext\ncase (Suc n)\nshow ?case \nproof (cases \" Suc n = to_nat i\")\ncase True\nshow ?thesis\nunfolding row_add_iterate_PA.simps if_P[OF True]\nproof (rule Suc.hyps[OF a_not_i])\nshow \"n < nrows A\" by (metis Suc.prems(2) Suc_lessD)\nshow \"to_nat a \\<le> n\" by (metis Suc.prems(3) True a_not_i le_SucE to_nat_eq)\nqed\nnext\ncase False note Suc_n_not_i=False\n    show ?thesis  \n    proof (cases \"to_nat a = Suc n\") \ncase True\nshow \"fst (row_add_iterate_PA (P, A) (Suc n) i j) $ a $ b = row_add P a i (- A $ a $ j) $ a $ b\"\nunfolding row_add_iterate_PA.simps if_not_P[OF False]\nby (metis Suc_le_lessD True dual_order.order_refl less_imp_le fst_row_add_iterate_PA_preserves_greater_than_n Suc.prems(2) to_nat_from_nat nrows_def)\nnext\ncase False\ndef A'\\<equiv>\"(row_add A (from_nat (Suc n)) i (- A $ from_nat (Suc n) $ j))\"\ndef P'\\<equiv>\"(row_add P (from_nat (Suc n)) i (- A $ from_nat (Suc n) $ j))\"\n      have rw: \"fst (row_add_iterate_PA (P',A') n i j) $ a $ b = row_add P' a i (- A' $ a $ j) $ a $ b\"\n      proof (rule Suc.hyps)\n        show \"a \\<noteq> i\" using Suc.prems(1) by simp\n        show \"n < nrows A'\" using Suc.prems(2) unfolding nrows_def by auto\n        show \"to_nat a \\<le> n\" using False Suc.prems(3) by simp\n      qed\n\n      have rw1: \"P' $ a $ b = P $ a $ b\"\n        unfolding P'_def row_add_def using False Suc.prems unfolding nrows_def by (auto simp add: to_nat_from_nat_id)\n      have rw2: \"A' $ a $ j = A $ a $ j\"\n          unfolding A'_def row_add_def using False Suc.prems unfolding nrows_def by (auto simp add: to_nat_from_nat_id)\n      have rw3: \"P' $ i $ b = P $ i $ b\"\n          unfolding P'_def row_add_def using False Suc.prems Suc_n_not_i unfolding nrows_def  by (auto simp add: to_nat_from_nat_id)\nshow \"fst (row_add_iterate_PA (P, A) (Suc n) i j) $ a $ b = row_add P a i (- A $ a $ j) $ a $ b\" \nunfolding row_add_iterate_PA.simps if_not_P[OF Suc_n_not_i] unfolding rw[unfolded P'_def A'_def]\n  unfolding A'_def[symmetric] P'_def[symmetric] unfolding row_add_def apply auto\nunfolding rw1 rw2 rw3 ..\n    qed\n  qed\nqed\n\n\n\n\nlemma fst_row_add_iterate_PA_eq_fst_Gauss_Jordan_in_ij_PA:\nfixes A::\"'a::{field}^'cols::{mod_type}^'rows::{mod_type}\"\nand i::\"'rows\" and j::\"'cols\"\nand P::\"'a::{field}^'rows::{mod_type}^'rows::{mod_type}\"\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)\"\ndefines P': \"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)\"\nshows \"fst (row_add_iterate_PA (P',A') (nrows A - 1) i j)  = fst (Gauss_Jordan_in_ij_PA (P,A) i j)\"\nproof (unfold Gauss_Jordan_in_ij_PA_def Let_def, vector, auto)\nfix ia\nhave interchange_rw: \"interchange_rows A i (LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n) $ i $ j = A $ (LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n) $ j\"\nusing interchange_rows_j[symmetric, of A \"(LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n)\"] by auto\nshow \"fst (row_add_iterate_PA (P', A') (nrows A - Suc 0) i j) $ i $ ia =\n         mult_row (interchange_rows P i (LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n)) i (1 / A $ (LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n) $ j) $ i $ ia\"\nunfolding A' P' interchange_rw\nproof (rule row_add_iterate_PA_preserves_pivot_row, unfold nrows_def)\nshow \"CARD('rows) - Suc 0 < CARD('rows)\" by auto\nshow \"to_nat i \\<le> CARD('rows) - Suc 0\" by (metis Suc_pred leD not_less_eq_eq to_nat_less_card zero_less_card_finite)\nqed\nnext\n  fix ia iaa\n have interchange_rw: \"A $ (LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n) $ j = interchange_rows A i (LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n) $ i $ j\"\n   using interchange_rows_j[symmetric, of A \"(LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n)\"] by auto\n  assume ia_not_i: \"ia \\<noteq> i\"\n  have rw: \"(- interchange_rows A i (LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n) $ ia $ j) \n    = - 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) $ ia $ j\"\n    unfolding interchange_rows_def mult_row_def using ia_not_i by auto  \nshow \"fst (row_add_iterate_PA (P', A') (nrows A - Suc 0) i j) $ ia $ iaa \n    = row_add (mult_row (interchange_rows P i (LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n)) i (1 / A $ (LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n) $ j)) ia i\n    (- interchange_rows A i (LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n) $ ia $ j) $ ia $ iaa\"  unfolding interchange_rw unfolding A' P' unfolding rw\nproof (rule fst_row_add_iterate_PA_eq_row_add, unfold nrows_def)\n show \"ia \\<noteq> i\" using ia_not_i .\n show \"CARD('rows) - Suc 0 < CARD('rows)\" using zero_less_card_finite by auto\n show \"to_nat ia \\<le> CARD('rows) - Suc 0\" by (metis Suc_pred leD not_less_eq_eq to_nat_less_card zero_less_card_finite)\nqed\nqed\n\n\nlemma invertible_fst_row_add_iterate_PA:\n  fixes A::\"'a::{ring_1}^'n^'m::{mod_type}\"\n  assumes n: \"n<nrows A\"\n  and inv_P: \"invertible P\"\n  shows \"invertible (fst (row_add_iterate_PA (P,A) n i j))\"\n  using n inv_P\n  proof (induct n arbitrary: A P)\n  case 0\n  show ?case \n    proof (unfold row_add_iterate_PA.simps, auto simp add: \"0.prems\")\n      assume i_not_0: \"i \\<noteq> 0\"\n      have \"row_add P 0 i (- A $ 0 $ j) = row_add (mat 1) 0 i (- A $ 0 $ j) ** P\" unfolding row_add_mat_1 ..\n      show \"invertible (row_add P 0 i (- A $ 0 $ j))\"\n        by (subst row_add_mat_1[symmetric], rule invertible_mult, auto simp add: invertible_row_add[of 0 i \"(- A $ 0 $ j)\"] i_not_0 \"0.prems\")\n    qed\n    next\n    case (Suc n)\n    show ?case\n      proof (cases \"Suc n = to_nat i\")\n        case True\n        show ?thesis unfolding row_add_iterate_PA.simps if_P[OF True] using Suc.hyps Suc.prems by simp\n        next\n        case False\n        show ?thesis \n          proof (unfold row_add_iterate_PA.simps if_not_P[OF False], rule Suc.hyps, unfold nrows_def)\n             show \"n < CARD('m)\" using Suc.prems(1) unfolding nrows_def by simp\n             show \"invertible (row_add P (from_nat (Suc n)) i (- A $ from_nat (Suc n) $ j))\"\n                proof (subst row_add_mat_1[symmetric], rule invertible_mult, rule invertible_row_add)\n                   show \"from_nat (Suc n) \\<noteq> i\" using False Suc.prems(1) from_nat_not_eq unfolding nrows_def by blast\n                   show \"invertible P\" using Suc.prems(2) .\n                qed\n          qed\n      qed\nqed\n\n\nlemma invertible_fst_Gauss_Jordan_in_ij_PA:\nfixes A::\"'a::{field}^'n::{mod_type}^'m::{mod_type}\"\nassumes inv_P: \"invertible P\"\nand not_all_zero: \"\\<not> (\\<forall>m\\<ge>i. A $ m $ j = 0)\"\nshows \"invertible (fst (Gauss_Jordan_in_ij_PA (P,A) i j))\" \nproof (unfold fst_row_add_iterate_PA_eq_fst_Gauss_Jordan_in_ij_PA[symmetric], rule invertible_fst_row_add_iterate_PA, simp add: nrows_def, \nsubst interchange_rows_mat_1[symmetric], subst mult_row_mat_1[symmetric], rule invertible_mult)\nshow \"invertible (mult_row (mat 1) i (1 / interchange_rows A i (LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n) $ i $ j))\"\n    proof (rule invertible_mult_row')\n      have \"interchange_rows A i (LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n) $ i $ j = A $ (LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n) $ j\" by simp\n      also have \"... \\<noteq> 0\" by (metis (lifting, mono_tags) LeastI_ex not_all_zero)\n      finally show \"1 / interchange_rows A i (LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n) $ i $ j \\<noteq> 0\"\n      unfolding inverse_eq_divide[symmetric] using nonzero_imp_inverse_nonzero by blast\n    qed\nshow \"invertible (interchange_rows (mat 1) i (LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n) ** P)\"\n  by (rule invertible_mult, rule invertible_interchange_rows, rule inv_P)\nqed\n\n\nlemma invertible_fst_Gauss_Jordan_column_k_PA:\nfixes A::\"'a::{field}^'n::{mod_type}^'m::{mod_type}\"\nassumes inv_P: \"invertible P\"\nshows \"invertible (fst (Gauss_Jordan_column_k_PA (P,i,A) k))\" \nproof (unfold Gauss_Jordan_column_k_PA_def Let_def snd_conv fst_conv, auto simp add: inv_P)\nfix m\nassume i_less_m: \"from_nat i \\<le> m\" and Amk_not_0: \"A $ m $ from_nat k \\<noteq> 0\"\nshow \"invertible (fst (Gauss_Jordan_in_ij_PA (P, A) (from_nat i) (from_nat k)))\"\nby (rule invertible_fst_Gauss_Jordan_in_ij_PA[OF inv_P], auto intro!: i_less_m Amk_not_0)\nqed\n\nlemma invertible_fst_Gauss_Jordan_upt_k_PA:\nfixes A::\"'a::{field}^'n::{mod_type}^'m::{mod_type}\"\nshows \"invertible (fst (Gauss_Jordan_upt_k_PA A k))\"\nproof (induct k)\ncase 0\nshow ?case unfolding Gauss_Jordan_upt_k_PA_def Let_def fst_conv by (simp add: invertible_fst_Gauss_Jordan_column_k_PA invertible_mat_1)\nnext\ncase (Suc k)\nhave list_rw: \"[0..<Suc (Suc k)] = [0..<Suc k] @ [Suc k]\" by simp\ndef f\\<equiv>\"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\nshow ?case unfolding Gauss_Jordan_upt_k_PA_def Let_def fst_conv\nunfolding list_rw unfolding foldl_append unfolding List.foldl.simps using invertible_fst_Gauss_Jordan_column_k_PA\nby (metis (mono_tags) Gauss_Jordan_upt_k_PA_def Suc.hyps fst_conv pair_collapse)\nqed\n\nlemma invertible_fst_Gauss_Jordan_PA:\nfixes A::\"'a::{field}^'n::{mod_type}^'m::{mod_type}\"\nshows \"invertible (fst (Gauss_Jordan_PA A))\" \nby (unfold Gauss_Jordan_PA_def, rule invertible_fst_Gauss_Jordan_upt_k_PA)\n\ndefinition \"P_Gauss_Jordan A = fst (Gauss_Jordan_PA A)\"\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/Gauss_Jordan_PA.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8918110540642805, "lm_q2_score": 0.8175744828610095, "lm_q1q2_score": 0.729121961336336}}
{"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\n  imports Main\n  abbrevs PiE = \"Pi\\<^sub>E\"\n    and PIE = \"\\<Pi>\\<^sub>E\"\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 \"\\<rightarrow>\" 60)\n  where \"A \\<rightarrow> B \\<equiv> Pi A (\\<lambda>_. B)\"\n\nsyntax\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>\\<open>Pi\\<close>\\<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 funcset_to_empty_iff: \"A \\<rightarrow> {} = (if A={} then UNIV else {})\"\n  by auto\n\nlemma Pi_eq_empty[simp]: \"(\\<Pi> x \\<in> A. B x) = {} \\<longleftrightarrow> (\\<exists>x\\<in>A. B x = {})\"\nproof -\n  have \"\\<exists>x\\<in>A. B x = {}\" if \"\\<And>f. \\<exists>y. y \\<in> A \\<and> f y \\<notin> B y\"\n    using that [of \"\\<lambda>u. SOME y. y \\<in> B u\"] some_in_eq by blast\n  then show ?thesis\n    by force\nqed\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: \"f i \\<in> A (n i) i\" if \"i \\<in> I\" for i\n    by auto\n  obtain k where k: \"n i \\<le> k\" if \"i \\<in> I\" for i\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 (metis PiE fun_upd_apply)\n  by force\n\n\nsubsection \\<open>Composition With a Restricted Domain: \\<^term>\\<open>compose\\<close>\\<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  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>\\<open>restrict\\<close>\\<close>\n\nlemma restrict_cong: \"I = J \\<Longrightarrow> (\\<And>i. i \\<in> J =simp=> f i = g i) \\<Longrightarrow> restrict f I = restrict g J\"\n  by (auto simp: restrict_def fun_eq_iff simp_implies_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 \\<longleftrightarrow> inj_on f A\"\n  by (simp add: inj_on_def restrict_def)\n\nlemma inj_on_restrict_iff: \"A \\<subseteq> B \\<Longrightarrow> inj_on (restrict f B) A \\<longleftrightarrow> inj_on f A\"\n  by (metis inj_on_cong restrict_def subset_iff)\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\nlemma sum_restrict' [simp]: \"sum' (\\<lambda>i\\<in>I. g i) I = sum' (\\<lambda>i. g i) I\"\n  by (simp add: sum.G_def conj_commute cong: conj_cong)\n\nlemma prod_restrict' [simp]: \"prod' (\\<lambda>i\\<in>I. g i) I = prod' (\\<lambda>i. g i) I\"\n  by (simp add: prod.G_def conj_commute cong: conj_cong)\n\n\nsubsection \\<open>Bijections Between Sets\\<close>\n\ntext \\<open>The definition of \\<^const>\\<open>bij_betw\\<close> is in \\<open>Fun.thy\\<close>, but most of\nthe theorems belong here, or need at least \\<^term>\\<open>Hilbert_Choice\\<close>.\\<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\"  (\"(3\\<Pi>\\<^sub>E _\\<in>_./ _)\" 10)\ntranslations\n  \"\\<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 \"\\<rightarrow>\\<^sub>E\" 60)\n  where \"A \\<rightarrow>\\<^sub>E B \\<equiv> (\\<Pi>\\<^sub>E i\\<in>A. B)\"\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]: \"Pi\\<^sub>E {} T = {\\<lambda>x. undefined}\"\n  unfolding PiE_def by simp\n\nlemma PiE_UNIV_domain: \"Pi\\<^sub>E 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> Pi\\<^sub>E 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> Pi\\<^sub>E 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> Pi\\<^sub>E S T \\<Longrightarrow> f(x := y) \\<in> Pi\\<^sub>E (insert x S) T\"\n  unfolding PiE_def extensional_def by auto\n\nlemma fun_upd_in_PiE: \"x \\<notin> S \\<Longrightarrow> f \\<in> Pi\\<^sub>E (insert x S) T \\<Longrightarrow> f(x := undefined) \\<in> Pi\\<^sub>E S T\"\n  unfolding PiE_def extensional_def by auto\n\nlemma PiE_insert_eq: \"Pi\\<^sub>E (insert x S) T = (\\<lambda>(y, g). g(x := y)) ` (T x \\<times> Pi\\<^sub>E S T)\"\nproof -\n  {\n    fix f assume \"f \\<in> Pi\\<^sub>E (insert x S) T\" \"x \\<notin> S\"\n    then have \"f \\<in> (\\<lambda>(y, g). g(x := y)) ` (T x \\<times> Pi\\<^sub>E S T)\"\n      by (auto intro!: image_eqI[where x=\"(f x, f(x := undefined))\"] intro: fun_upd_in_PiE PiE_mem)\n  }\n  moreover\n  {\n    fix f assume \"f \\<in> Pi\\<^sub>E (insert x S) T\" \"x \\<in> S\"\n    then have \"f \\<in> (\\<lambda>(y, g). g(x := y)) ` (T x \\<times> Pi\\<^sub>E S T)\"\n      by (auto intro!: image_eqI[where x=\"(f x, f)\"] intro: fun_upd_in_PiE PiE_mem simp: insert_absorb)\n  }\n  ultimately show ?thesis\n    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> Pi\\<^sub>E 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> Pi\\<^sub>E 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> Pi\\<^sub>E A B \\<subseteq> Pi\\<^sub>E A C\"\n  by auto\n\nlemma PiE_iff: \"f \\<in> Pi\\<^sub>E 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 restrict_PiE_iff: \"restrict f I \\<in> Pi\\<^sub>E I X \\<longleftrightarrow> (\\<forall>i \\<in> I. f i \\<in> X i)\"\n  by (simp add: PiE_iff)\n\nlemma ext_funcset_to_sing_iff [simp]: \"A \\<rightarrow>\\<^sub>E {a} = {\\<lambda>x\\<in>A. a}\"\n  by (auto simp: PiE_def Pi_iff extensionalityI)\n\nlemma PiE_restrict[simp]:  \"f \\<in> Pi\\<^sub>E A B \\<Longrightarrow> restrict f A = f\"\n  by (simp add: extensional_restrict PiE_def)\n\nlemma restrict_PiE[simp]: \"restrict f I \\<in> Pi\\<^sub>E 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  by (auto split: if_split_asm)\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\nlemma subset_PiE:\n   \"PiE I S \\<subseteq> PiE I T \\<longleftrightarrow> PiE I S = {} \\<or> (\\<forall>i \\<in> I. S i \\<subseteq> T i)\" (is \"?lhs \\<longleftrightarrow> _ \\<or> ?rhs\")\nproof (cases \"PiE I S = {}\")\n  case False\n  moreover have \"?lhs = ?rhs\"\n  proof\n    assume L: ?lhs\n    have \"\\<And>i. i\\<in>I \\<Longrightarrow> S i \\<noteq> {}\"\n      using False PiE_eq_empty_iff by blast\n    with L show ?rhs\n      by (simp add: PiE_Int PiE_eq_iff inf.absorb_iff2)\n  qed auto\n  ultimately show ?thesis\n    by simp\nqed simp\n\nlemma PiE_eq:\n   \"PiE I S = PiE I T \\<longleftrightarrow> PiE I S = {} \\<and> PiE I T = {} \\<or> (\\<forall>i \\<in> I. S i = T i)\"\n  by (auto simp: PiE_eq_iff PiE_eq_empty_iff)\n\nlemma PiE_UNIV [simp]: \"PiE UNIV (\\<lambda>i. UNIV) = UNIV\"\n  by blast\n\nlemma image_projection_PiE:\n  \"(\\<lambda>f. f i) ` (PiE I S) = (if PiE I S = {} then {} else if i \\<in> I then S i else {undefined})\"\nproof -\n  have \"(\\<lambda>f. f i) ` Pi\\<^sub>E I S = S i\" if \"i \\<in> I\" \"f \\<in> PiE I S\" for f\n    using that apply auto\n    by (rule_tac x=\"(\\<lambda>k. if k=i then x else f k)\" in image_eqI) auto\n  moreover have \"(\\<lambda>f. f i) ` Pi\\<^sub>E I S = {undefined}\" if \"f \\<in> PiE I S\" \"i \\<notin> I\" for f\n    using that by (blast intro: PiE_arb [OF that, symmetric])\n  ultimately show ?thesis\n    by auto\nqed\n\nlemma PiE_singleton:\n  assumes \"f \\<in> extensional A\"\n  shows   \"PiE A (\\<lambda>x. {f x}) = {f}\"\nproof -\n  {\n    fix g assume \"g \\<in> PiE A (\\<lambda>x. {f x})\"\n    hence \"g x = f x\" for x\n      using assms by (cases \"x \\<in> A\") (auto simp: extensional_def)\n    hence \"g = f\" by (simp add: fun_eq_iff)\n  }\n  thus ?thesis using assms by (auto simp: extensional_def)\nqed\n\nlemma PiE_eq_singleton: \"(\\<Pi>\\<^sub>E i\\<in>I. S i) = {\\<lambda>i\\<in>I. f i} \\<longleftrightarrow> (\\<forall>i\\<in>I. S i = {f i})\"\n  by (metis (mono_tags, lifting) PiE_eq PiE_singleton insert_not_empty restrict_apply' restrict_extensional)\n\nlemma PiE_over_singleton_iff: \"(\\<Pi>\\<^sub>E x\\<in>{a}. B x) = (\\<Union>b \\<in> B a. {\\<lambda>x \\<in> {a}. b})\"\n  apply (auto simp: PiE_iff split: if_split_asm)\n  apply (metis (no_types, lifting) extensionalityI restrict_apply' restrict_extensional singletonD)\n  done\n\nlemma all_PiE_elements:\n   \"(\\<forall>z \\<in> PiE I S. \\<forall>i \\<in> I. P i (z i)) \\<longleftrightarrow> PiE I S = {} \\<or> (\\<forall>i \\<in> I. \\<forall>x \\<in> S i. P i x)\" (is \"?lhs = ?rhs\")\nproof (cases \"PiE I S = {}\")\n  case False\n  then obtain f where f: \"\\<And>i. i \\<in> I \\<Longrightarrow> f i \\<in> S i\"\n    by fastforce\n  show ?thesis\n  proof\n    assume L: ?lhs\n    have \"P i x\"\n      if \"i \\<in> I\" \"x \\<in> S i\" for i x\n    proof -\n      have \"(\\<lambda>j \\<in> I. if j=i then x else f j) \\<in> PiE I S\"\n        by (simp add: f that(2))\n      then have \"P i ((\\<lambda>j \\<in> I. if j=i then x else f j) i)\"\n        using L that(1) by blast\n      with that show ?thesis\n        by simp\n    qed\n    then show ?rhs\n      by (simp add: False)\n  qed fastforce\nqed simp\n\nlemma PiE_ext: \"\\<lbrakk>x \\<in> PiE k s; y \\<in> PiE k s; \\<And>i. i \\<in> k \\<Longrightarrow> x i = y i\\<rbrakk> \\<Longrightarrow> x = y\"\n  by (metis ext PiE_E)\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: if_split_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>Misc properties of functions, composition and restriction from HOL Light\\<close>\n\nlemma function_factors_left_gen:\n  \"(\\<forall>x y. P x \\<and> P y \\<and> g x = g y \\<longrightarrow> f x = f y) \\<longleftrightarrow> (\\<exists>h. \\<forall>x. P x \\<longrightarrow> f x = h(g x))\"\n  (is \"?lhs = ?rhs\")\nproof\n  assume L: ?lhs\n  then show ?rhs\n    apply (rule_tac x=\"f \\<circ> inv_into (Collect P) g\" in exI)\n    unfolding o_def\n    by (metis (mono_tags, opaque_lifting) f_inv_into_f imageI inv_into_into mem_Collect_eq)\nqed auto\n\nlemma function_factors_left:\n  \"(\\<forall>x y. (g x = g y) \\<longrightarrow> (f x = f y)) \\<longleftrightarrow> (\\<exists>h. f = h \\<circ> g)\"\n  using function_factors_left_gen [of \"\\<lambda>x. True\" g f] unfolding o_def by blast\n\nlemma function_factors_right_gen:\n  \"(\\<forall>x. P x \\<longrightarrow> (\\<exists>y. g y = f x)) \\<longleftrightarrow> (\\<exists>h. \\<forall>x. P x \\<longrightarrow> f x = g(h x))\"\n  by metis\n\nlemma function_factors_right:\n  \"(\\<forall>x. \\<exists>y. g y = f x) \\<longleftrightarrow> (\\<exists>h. f = g \\<circ> h)\"\n  unfolding o_def by metis\n\nlemma restrict_compose_right:\n   \"restrict (g \\<circ> restrict f S) S = restrict (g \\<circ> f) S\"\n  by auto\n\nlemma restrict_compose_left:\n   \"f ` S \\<subseteq> T \\<Longrightarrow> restrict (restrict g T \\<circ> f) S = restrict (g \\<circ> f) S\"\n  by fastforce\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: if_split_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\nlemma card_funcsetE: \"finite A \\<Longrightarrow> card (A \\<rightarrow>\\<^sub>E B) = card B ^ card A\" \n  by (subst card_PiE, auto)\n\nlemma card_inj_on_subset_funcset: assumes finB: \"finite B\"\n  and finC: \"finite C\" \n  and AB: \"A \\<subseteq> B\" \nshows \"card {f \\<in> B \\<rightarrow>\\<^sub>E C. inj_on f A} = \n  card C^(card B - card A) * prod ((-) (card C)) {0 ..< card A}\"\nproof -\n  define D where \"D = B - A\" \n  from AB have B: \"B = A \\<union> D\" and disj: \"A \\<inter> D = {}\" unfolding D_def by auto\n  have sub: \"card B - card A = card D\" unfolding D_def using finB AB\n    by (metis card_Diff_subset finite_subset)\n  have \"finite A\" \"finite D\" using finB unfolding B by auto\n  thus ?thesis unfolding sub unfolding B using disj\n  proof (induct A rule: finite_induct)\n    case empty\n    from card_funcsetE[OF this(1), of C] show ?case by auto\n  next\n    case (insert a A)\n    have \"{f. f \\<in> insert a A \\<union> D \\<rightarrow>\\<^sub>E C \\<and> inj_on f (insert a A)}\n      = {f(a := c) | f c. f \\<in> A \\<union> D \\<rightarrow>\\<^sub>E C \\<and> inj_on f A \\<and> c \\<in> C - f ` A}\" \n      (is \"?l = ?r\")\n    proof\n      show \"?r \\<subseteq> ?l\" \n        by (auto intro: inj_on_fun_updI split: if_splits) \n      {\n        fix f\n        assume f: \"f \\<in> ?l\" \n        let ?g = \"f(a := undefined)\" \n        let ?h = \"?g(a := f a)\" \n        have mem: \"f a \\<in> C - ?g ` A\" using insert(1,2,4,5) f by auto\n        from f have f: \"f \\<in> insert a A \\<union> D \\<rightarrow>\\<^sub>E C\" \"inj_on f (insert a A)\" by auto\n        hence \"?g \\<in> A \\<union> D \\<rightarrow>\\<^sub>E C\" \"inj_on ?g A\" using \\<open>a \\<notin> A\\<close> \\<open>insert a A \\<inter> D = {}\\<close>\n          by (auto split: if_splits simp: inj_on_def)\n        with mem have \"?h \\<in> ?r\" by blast\n        also have \"?h = f\" by auto\n        finally have \"f \\<in> ?r\" .\n      }\n      thus \"?l \\<subseteq> ?r\" by auto\n    qed\n    also have \"\\<dots> = (\\<lambda> (f, c). f (a := c)) ` \n         (Sigma {f . f \\<in> A \\<union> D \\<rightarrow>\\<^sub>E C \\<and> inj_on f A} (\\<lambda> f. C - f ` A))\"\n      by auto\n    also have \"card (...) = card (Sigma {f . f \\<in> A \\<union> D \\<rightarrow>\\<^sub>E C \\<and> inj_on f A} (\\<lambda> f. C - f ` A))\" \n    proof (rule card_image, intro inj_onI, clarsimp, goal_cases) \n      case (1 f c g d)\n      let ?f = \"f(a := c, a := undefined)\" \n      let ?g = \"g(a := d, a := undefined)\" \n      from 1 have id: \"f(a := c) = g(a := d)\" by auto\n      from fun_upd_eqD[OF id] \n      have cd: \"c = d\" by auto\n      from id have \"?f = ?g\" by auto\n      also have \"?f = f\" using `f \\<in> A \\<union> D \\<rightarrow>\\<^sub>E C` insert(1,2,4,5) \n        by (intro ext, auto)\n      also have \"?g = g\" using `g \\<in> A \\<union> D \\<rightarrow>\\<^sub>E C` insert(1,2,4,5) \n        by (intro ext, auto)\n      finally show \"f = g \\<and> c = d\" using cd by auto\n    qed\n    also have \"\\<dots> = (\\<Sum>f\\<in>{f \\<in> A \\<union> D \\<rightarrow>\\<^sub>E C. inj_on f A}. card (C - f ` A))\" \n      by (rule card_SigmaI, rule finite_subset[of _ \"A \\<union> D \\<rightarrow>\\<^sub>E C\"],\n          insert \\<open>finite C\\<close> \\<open>finite D\\<close> \\<open>finite A\\<close>, auto intro!: finite_PiE)\n    also have \"\\<dots> = (\\<Sum>f\\<in>{f \\<in> A \\<union> D \\<rightarrow>\\<^sub>E C. inj_on f A}. card C - card A)\"\n      by (rule sum.cong[OF refl], subst card_Diff_subset, insert \\<open>finite A\\<close>, auto simp: card_image)\n    also have \"\\<dots> = (card C - card A) * card {f \\<in> A \\<union> D \\<rightarrow>\\<^sub>E C. inj_on f A}\" \n      by simp\n    also have \"\\<dots> = card C ^ card D * ((card C - card A) * prod ((-) (card C)) {0..<card A})\" \n      using insert by (auto simp: ac_simps)\n    also have \"(card C - card A) * prod ((-) (card C)) {0..<card A} =\n      prod ((-) (card C)) {0..<Suc (card A)}\" by simp\n    also have \"Suc (card A) = card (insert a A)\" using insert by auto\n    finally show ?case .\n  qed\nqed\n\n\nsubsection \\<open>The pigeonhole principle\\<close>\n\ntext \\<open>\n  An alternative formulation of this is that for a function mapping a finite set \\<open>A\\<close> of\n  cardinality \\<open>m\\<close> to a finite set \\<open>B\\<close> of cardinality \\<open>n\\<close>, there exists an element \\<open>y \\<in> B\\<close> that\n  is hit at least $\\lceil \\frac{m}{n}\\rceil$ times. However, since we do not have real numbers\n  or rounding yet, we state it in the following equivalent form:\n\\<close>\nlemma pigeonhole_card:\n  assumes \"f \\<in> A \\<rightarrow> B\" \"finite A\" \"finite B\" \"B \\<noteq> {}\"\n  shows   \"\\<exists>y\\<in>B. card (f -` {y} \\<inter> A) * card B \\<ge> card A\"\nproof -\n  from assms have \"card B > 0\"\n    by auto\n  define M where \"M = Max ((\\<lambda>y. card (f -` {y} \\<inter> A)) ` B)\"\n  have \"A = (\\<Union>y\\<in>B. f -` {y} \\<inter> A)\"\n    using assms by auto\n  also have \"card \\<dots> = (\\<Sum>i\\<in>B. card (f -` {i} \\<inter> A))\"\n    using assms by (subst card_UN_disjoint) auto\n  also have \"\\<dots> \\<le> (\\<Sum>i\\<in>B. M)\"\n    unfolding M_def using assms by (intro sum_mono Max.coboundedI) auto\n  also have \"\\<dots> = card B * M\"\n    by simp\n  finally have \"M * card B \\<ge> card A\"\n    by (simp add: mult_ac)\n  moreover have \"M \\<in> (\\<lambda>y. card (f -` {y} \\<inter> A)) ` B\"\n    unfolding M_def using assms \\<open>B \\<noteq> {}\\<close> by (intro Max_in) auto\n  ultimately 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/Library/FuncSet.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8577681195338728, "lm_q2_score": 0.8499711699569786, "lm_q1q2_score": 0.7290781721120033}}
{"text": "section \"Stack Machine and Compilation\"\n\ntheory ASM imports AExp begin\n\nsubsection \"Stack Machine\"\n\n(* The stack machine has three instructions: *)\ndatatype instr = LOADI val\n               | LOAD vname\n               | ADD\n\n(* The semantics:\n   + LOADI n puts the immediate n on top of the stack,\n   + LOAD x puts the value of x on top of the stack, and\n   + ADD replaces the two topmost elements by their sum. *)\n\n(* A stack: *)\ntype_synonym stack = \"val list\"\n(* The top of the stack is the head of the list *)\n\n(* An instruction is executed in the context of a state and transforms a stack into a new stack. *)\nfun exec1 :: \"instr \\<Rightarrow> state \\<Rightarrow> stack \\<Rightarrow> stack\" where\n  \"exec1 (LOADI n) _ stack = n # stack\"\n| \"exec1 (LOAD x) s stack = s x # stack\"\n| \"exec1 ADD _ (j # i # stack) = (i + j) # stack\"\n\n(* A list of instructions is executed one by one. *)\nfun exec :: \"instr list \\<Rightarrow> state \\<Rightarrow> stack \\<Rightarrow> stack\" where\n  \"exec [] _ stack = stack\"\n| \"exec (i # is) s stack = exec is s (exec1 i s stack)\"\n\nvalue \"exec [LOADI 5, LOAD ''y'', ADD]\n      <''x'' := 42, ''y'' := 43> [50]\"\n\nlemma exec_append [simp]: \"exec (is1 @ is2) s stack = exec is2 s (exec is1 s stack)\"\napply (induction is1 arbitrary: stack)\napply auto\ndone\n\nsubsection \"Compilation\"\n\n(* Compilation of arithmetic expressions: *)\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\nvalue \"comp (Plus (Plus (V ''x'') (N 1)) (V ''z''))\"\n\n(* The correctness statement says that executing a compiled expression\n   is the same as putting the value of the expression on the stack: *)\ntheorem exec_comp: \"exec (comp a) s stack = aval a s # stack\"\napply (induction a arbitrary: stack)\napply auto\ndone\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/ASM.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680977182186, "lm_q2_score": 0.8499711699569786, "lm_q1q2_score": 0.7290781535693263}}
{"text": "theory \"Static_Semantics\"\nimports\n  \"Syntax\"\n  \"Denotational_Semantics\"\nbegin\nsection \\<open>Static Semantics\\<close>\n\nsubsection \\<open>Semantically-defined Static Semantics\\<close>\nparagraph \\<open>Auxiliary notions of projection of winning conditions\\<close>\n\ntext\\<open>upward projection: \\<open>restrictto X V\\<close> is extends X to the states that agree on V with some state in X,\nso variables outside V can assume arbitrary values.\\<close>\ndefinition restrictto :: \"state set \\<Rightarrow> variable set \\<Rightarrow> state set\"\nwhere\n  \"restrictto X V = {\\<nu>. \\<exists>\\<omega>. \\<omega>\\<in>X \\<and> Vagree \\<omega> \\<nu> V}\"\n\ntext\\<open>downward projection: \\<open>selectlike X \\<nu> V\\<close> selects state \\<open>\\<nu>\\<close> on V in X,\nso all variables of V are required to remain constant\\<close>\ndefinition selectlike :: \"state set \\<Rightarrow> state \\<Rightarrow> variable set \\<Rightarrow> state set\"\n  where\n  \"selectlike X \\<nu> V = {\\<omega>\\<in>X. Vagree \\<omega> \\<nu> V}\"\n\nparagraph \\<open>Free variables, semantically characterized.\\<close>\ntext\\<open>Free variables of a term\\<close>\ndefinition FVT :: \"trm \\<Rightarrow> variable set\"\nwhere\n  \"FVT t = {x. \\<exists>I.\\<exists>\\<nu>.\\<exists>\\<omega>. Vagree \\<nu> \\<omega> (-{x}) \\<and> \\<not>(term_sem I t \\<nu> = term_sem I t \\<omega>)}\"\n\ntext\\<open>Free variables of a formula\\<close>\ndefinition FVF :: \"fml \\<Rightarrow> variable set\"\nwhere\n  \"FVF \\<phi> = {x. \\<exists>I.\\<exists>\\<nu>.\\<exists>\\<omega>. Vagree \\<nu> \\<omega> (-{x}) \\<and> \\<nu> \\<in> fml_sem I \\<phi> \\<and> \\<omega> \\<notin> fml_sem I \\<phi>}\"\n\ntext\\<open>Free variables of a hybrid game\\<close>\ndefinition FVG :: \"game \\<Rightarrow> variable set\"\nwhere\n  \"FVG \\<alpha> = {x. \\<exists>I.\\<exists>\\<nu>.\\<exists>\\<omega>.\\<exists>X. Vagree \\<nu> \\<omega> (-{x}) \\<and> \\<nu> \\<in> game_sem I \\<alpha> (restrictto X (-{x})) \\<and> \\<omega> \\<notin> game_sem I \\<alpha> (restrictto X (-{x}))}\"\n  \nparagraph \\<open>Bound variables, semantically characterized.\\<close>\ntext\\<open>Bound variables of a hybrid game\\<close>\ndefinition BVG :: \"game \\<Rightarrow> variable set\"\nwhere\n  \"BVG \\<alpha> = {x. \\<exists>I.\\<exists>\\<omega>.\\<exists>X. \\<omega> \\<in> game_sem I \\<alpha> X \\<and> \\<omega> \\<notin> game_sem I \\<alpha> (selectlike X \\<omega> {x})}\"\n\n\nsubsection \\<open>Simple Observations\\<close>\n  \nlemma BVG_elem [simp] :\"(x\\<in>BVG \\<alpha>) = (\\<exists>I \\<omega> X. \\<omega> \\<in> game_sem I \\<alpha> X \\<and> \\<omega> \\<notin> game_sem I \\<alpha> (selectlike X \\<omega> {x}))\"\n  unfolding BVG_def by simp\n\nlemma nonBVG_rule: \"(\\<And>I \\<omega> X. (\\<omega> \\<in> game_sem I \\<alpha> X) = (\\<omega> \\<in> game_sem I \\<alpha> (selectlike X \\<omega> {x})))\n  \\<Longrightarrow> x\\<notin>BVG \\<alpha>\"\n  using BVG_elem by simp\n\nlemma nonBVG_inc_rule: \"(\\<And>I \\<omega> X. (\\<omega> \\<in> game_sem I \\<alpha> X) \\<Longrightarrow> (\\<omega> \\<in> game_sem I \\<alpha> (selectlike X \\<omega> {x})))\n  \\<Longrightarrow> x\\<notin>BVG \\<alpha>\"\n  using BVG_elem by simp\n  \nlemma FVT_finite: \"finite(FVT t)\"\n  using allvars_finite by (metis finite_subset mem_Collect_eq subsetI)\nlemma FVF_finite: \"finite(FVF e)\"\n  using allvars_finite by (metis finite_subset mem_Collect_eq subsetI)\nlemma FVG_finite: \"finite(FVG a)\"\n  using allvars_finite by (metis finite_subset mem_Collect_eq subsetI)\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/Differential_Game_Logic/Static_Semantics.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.92522995296862, "lm_q2_score": 0.787931190663057, "lm_q1q2_score": 0.729017538479689}}
{"text": "section \\<open>$\\tau$-Additivity\\<close>\n\ntheory Tau_Additivity\n  imports \"HOL-Analysis.Regularity\"\nbegin\n\ntext \\<open>In this section we show $\\tau$-additivity for measures, that are compatible with a\nsecond-countable topology. This will be essential for the verification of the Scott-continuity\nof the monad morphisms. To understand the property, let us recall that for general countable chains\nof measurable sets, it is possible to deduce that the supremum\nof the measures of the sets is equal to the measure of the union of the family:\n\\[\n  \\mu \\left( \\bigcup{\\mathcal X} \\right) = \\sup_{X \\in \\mathcal X} \\mu (X)\n\\]\nthis is shown in @{thm [source] SUP_emeasure_incseq}.\n\nIt is possible to generalize that to arbitrary chains\n\\footnote{More generally families closed under pairwise unions.} of open sets for some measures\nwithout the restriction of countability, such measures are called\n$\\tau$-additive~\\cite{fremlin2000}.\n\nIn the following this property is derived for measures that are at least borel (i.e. every open\nset is measurable) in a complete second-countable topology. The result is an immediate consequence\nof inner-regularity. The latter is already verified in @{theory \"HOL-Analysis.Regularity\"}.\\<close>\n\ndefinition \"op_stable op F = (\\<forall>x y. x \\<in> F \\<and> y \\<in> F \\<longrightarrow> op x y \\<in> F)\"\n\nlemma op_stableD:\n  assumes \"op_stable op F\"\n  assumes \"x \\<in> F\" \"y \\<in> F\"\n  shows \"op x y \\<in> F\"\n  using assms unfolding op_stable_def by auto\n\nlemma tau_additivity_aux:\n  fixes M::\"'a::{second_countable_topology, complete_space} measure\"\n  assumes sb: \"sets M = sets borel\"\n  assumes fin: \"emeasure M (space M) \\<noteq> \\<infinity>\"\n  assumes of: \"\\<And>a. a \\<in> A \\<Longrightarrow> open a\"\n  assumes ud: \"op_stable (\\<union>) A\"\n  shows \"emeasure M (\\<Union>A) = (SUP a \\<in> A. emeasure M a)\" (is \"?L = ?R\")\nproof (cases \"A \\<noteq> {}\")\n  case True\n\n  have \"open (\\<Union>A)\" using of by auto\n  hence \"\\<Union>A \\<in> sets borel\" by simp\n  hence usets: \"\\<Union>A \\<in> sets M\" using assms(1) by simp\n\n  have 0:\"a \\<in> sets borel\" if \"a \\<in> A\" for a\n    using of that by simp\n\n  have 1:\"\\<Union>T \\<in> A\" if \"finite T\" \"T \\<noteq> {}\" \"T \\<subseteq> A\" for T\n    using that op_stableD[OF ud] by (induction T rule:finite_ne_induct) auto\n\n  have 2:\"emeasure M K \\<le> ?R\" if K_def: \"compact K\" \"K \\<subseteq> \\<Union>A\" for K\n  proof (cases \"K \\<noteq> {}\")\n    case True\n    obtain T where T_def: \"K \\<subseteq> \\<Union>T\" \"T \\<subseteq> A\" \"finite T\"\n      using compactE[OF K_def of] that by metis\n    have T_ne: \"T \\<noteq> {}\" using T_def(1) True by auto\n    define t where \"t = \\<Union>T\"\n    have t_in: \"t \\<in> A\"\n      unfolding t_def by (intro 1 T_ne T_def)\n    have \"K \\<subseteq> t\"\n      unfolding t_def using T_def by simp\n    hence \"emeasure M K \\<le> emeasure M t\"\n      using 0 sb t_in by (intro emeasure_mono) auto\n    also have \"... \\<le> ?R\"\n      using t_in by (intro cSup_upper) auto\n    finally show ?thesis\n      by simp\n  next\n    case False\n    hence \"K = {}\" by simp\n    thus ?thesis by simp\n  qed\n\n  have \"?L = (SUP K \\<in> {K. K \\<subseteq> \\<Union> A \\<and> compact K}. emeasure M K)\"\n    using usets unfolding sb by (intro inner_regular[OF sb fin]) auto\n  also have \"... \\<le> ?R\"\n    using 2 by (intro cSup_least) auto\n  finally have \"?L \\<le> ?R\" by simp\n  moreover have \"emeasure M a \\<le> emeasure M (\\<Union>A)\" if \"a \\<in> A\" for a\n    using that by (intro emeasure_mono usets) auto\n  hence \"?R \\<le> ?L\"\n    using True by (intro cSup_least) auto\n  ultimately show ?thesis by auto\nnext\n  case False\n  thus ?thesis by (simp add:bot_ennreal)\nqed\n\nlemma chain_imp_union_stable:\n  assumes \"Complete_Partial_Order.chain (\\<subseteq>) F\"\n  shows \"op_stable (\\<union>) F\"\nproof -\n  have \"x \\<union> y \\<in> F\" if \"x \\<in> F\" \"y \\<in> F\" for x y\n  proof (cases \"x \\<subseteq> y\")\n    case True\n    then show ?thesis using that sup.absorb2[OF True] by simp\n  next\n    case False\n    hence 0:\"y \\<subseteq> x\"\n      using assms that unfolding Complete_Partial_Order.chain_def by auto\n    then show ?thesis using that sup.absorb1[OF 0] by simp\n  qed\n  thus ?thesis\n    unfolding op_stable_def by auto\nqed\n\ntheorem tau_additivity:\n  fixes M :: \"'a::{second_countable_topology, complete_space} measure\"\n  assumes sb: \"\\<And>x. open x \\<Longrightarrow> x \\<in> sets M\"\n  assumes fin: \"emeasure M (space M) \\<noteq> \\<infinity>\"\n  assumes of: \"\\<And>a. a \\<in> A \\<Longrightarrow> open a\"\n  assumes ud: \"op_stable (\\<union>) A\"\n  shows \"emeasure M (\\<Union>A) = (SUP a \\<in> A. emeasure M a)\" (is \"?L = ?R\")\nproof -\n  have \"UNIV \\<in> sets M\"\n    using open_UNIV sb by auto\n  hence space_M[simp]:\"space M = UNIV\"\n    using sets.sets_into_space by blast\n\n  have id_borel: \"(\\<lambda>x. x) \\<in> M \\<rightarrow>\\<^sub>M borel\"\n    using sb by (intro borel_measurableI) auto\n\n  have \"open (\\<Union>A)\" using of by auto\n  hence usets: \"(\\<Union>A) \\<in> sets borel\" by simp\n\n  define N where \"N = distr M borel (\\<lambda>x. x)\"\n  have sets_N: \"sets N = sets borel\"\n    unfolding N_def by simp\n  have fin_N: \"emeasure N (space N) \\<noteq> \\<infinity>\"\n    using fin id_borel unfolding N_def\n    by (subst emeasure_distr) auto\n\n  have \"?L = emeasure N (\\<Union>A)\"\n    unfolding N_def by (subst emeasure_distr[OF id_borel usets]) auto\n  also have \"... = (SUP a \\<in> A. emeasure N a)\"\n    by (intro tau_additivity_aux sets_N of ud fin_N) auto\n  also have \"... = (SUP a\\<in>A. emeasure M ((\\<lambda>x. x) -` a \\<inter> space M))\"\n    unfolding N_def using of\n    by (intro arg_cong[where f=\"Sup\"] image_cong emeasure_distr id_borel) auto\n  also have \"... = ?R\" by simp\n  finally show ?thesis by simp\nqed\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/Tau_Additivity.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8479677737461006, "lm_q2_score": 0.859663754105328, "lm_q1q2_score": 0.7289671597389102}}
{"text": "(*\n  File:    Lambert_W.thy\n  Author:  Manuel Eberl, TU M\u00fcnchen\n\n  Definition and basic properties of the two real-valued branches of the Lambert W function,\n*)\nsection \\<open>The Lambert $W$ Function on the reals\\<close>\ntheory Lambert_W\nimports\n  Complex_Main\n  \"HOL-Library.FuncSet\"\n  \"HOL-Real_Asymp.Real_Asymp\"\nbegin\n\n(*<*)\ntext \\<open>Some lemmas about asymptotic equivalence:\\<close>\n\nlemma asymp_equiv_sandwich':\n  fixes f :: \"'a \\<Rightarrow> real\"\n  assumes \"\\<And>c'. c' \\<in> {l<..<c} \\<Longrightarrow> eventually (\\<lambda>x. f x \\<ge> c' * g x) F\"\n  assumes \"\\<And>c'. c' \\<in> {c<..<u} \\<Longrightarrow> eventually (\\<lambda>x. f x \\<le> c' * g x) F\"\n  assumes \"l < c\" \"c < u\" and [simp]: \"c \\<noteq> 0\"\n  shows   \"f \\<sim>[F] (\\<lambda>x. c * g x)\"\nproof -\n  have \"(\\<lambda>x. f x - c * g x) \\<in> o[F](g)\"\n  proof (rule landau_o.smallI)\n    fix e :: real assume e: \"e > 0\"\n    define C1 where \"C1 = min (c + e) ((c + u) / 2)\"\n    have C1: \"C1 \\<in> {c<..<u}\" \"C1 - c \\<le> e\"\n      using e assms by (auto simp: C1_def min_def)\n    define C2 where \"C2 = max (c - e) ((c + l) / 2)\"\n    have C2: \"C2 \\<in> {l<..<c}\" \"c - C2 \\<le> e\"\n      using e assms by (auto simp: C2_def max_def field_simps)\n\n    show \"eventually (\\<lambda>x. norm (f x - c * g x) \\<le> e * norm (g x)) F\"\n      using assms(2)[OF C1(1)] assms(1)[OF C2(1)]\n    proof eventually_elim\n      case (elim x)\n      show ?case\n      proof (cases \"f x \\<ge> c * g x\")\n        case True\n        hence \"norm (f x - c * g x) = f x - c * g x\"\n          by simp\n        also have \"\\<dots> \\<le> (C1 - c) * g x\"\n          using elim by (simp add: algebra_simps)\n        also have \"\\<dots> \\<le> (C1 - c) * norm (g x)\"\n          using C1 by (intro mult_left_mono) auto\n        also have \"\\<dots> \\<le> e * norm (g x)\"\n          using C1 elim by (intro mult_right_mono) auto\n        finally show ?thesis using elim by simp\n      next\n        case False\n        hence \"norm (f x - c * g x) = c * g x - f x\"\n          by simp\n        also have \"\\<dots> \\<le> (c - C2) * g x\"\n          using elim by (simp add: algebra_simps)\n        also have \"\\<dots> \\<le> (c - C2) * norm (g x)\"\n          using C2 by (intro mult_left_mono) auto\n        also have \"\\<dots> \\<le> e * norm (g x)\"\n          using C2 elim by (intro mult_right_mono) auto\n        finally show ?thesis using elim by simp\n      qed\n    qed\n  qed\n  also have \"g \\<in> O[F](\\<lambda>x. c * g x)\"\n    by simp\n  finally show ?thesis\n    unfolding asymp_equiv_altdef by blast\nqed\n\nlemma asymp_equiv_sandwich'':\n  fixes f :: \"'a \\<Rightarrow> real\"\n  assumes \"\\<And>c'. c' \\<in> {l<..<1} \\<Longrightarrow> eventually (\\<lambda>x. f x \\<ge> c' * g x) F\"\n  assumes \"\\<And>c'. c' \\<in> {1<..<u} \\<Longrightarrow> eventually (\\<lambda>x. f x \\<le> c' * g x) F\"\n  assumes \"l < 1\" \"1 < u\"\n  shows   \"f \\<sim>[F] (g)\"\n  using asymp_equiv_sandwich'[of l 1 g f F u] assms by simp\n(*>*)\n\nsubsection \\<open>Properties of the function $x\\mapsto x e^{x}$\\<close>\n\nlemma exp_times_self_gt:\n  assumes \"x \\<noteq> -1\"\n  shows   \"x * exp x > -exp (-1::real)\"\nproof -\n  define f where \"f = (\\<lambda>x::real. x * exp x)\"\n  define f' where \"f' = (\\<lambda>x::real. (x + 1) * exp x)\"\n  have \"(f has_field_derivative f' x) (at x)\" for x\n    by (auto simp: f_def f'_def intro!: derivative_eq_intros simp: algebra_simps)\n  define l r where \"l = min x (-1)\" and \"r = max x (-1)\"\n\n  have \"\\<exists>z. z > l \\<and> z < r \\<and> f r - f l = (r - l) * f' z\"\n    unfolding f_def f'_def l_def r_def using assms\n    by (intro MVT2) (auto intro!: derivative_eq_intros simp: algebra_simps)\n  then obtain z where z: \"z \\<in> {l<..<r}\" \"f r - f l = (r - l) * f' z\"\n    by auto\n  from z have \"f x = f (-1) + (x + 1) * f' z\"\n    using assms by (cases \"x \\<ge> -1\") (auto simp: l_def r_def max_def min_def algebra_simps)\n  moreover have \"sgn ((x + 1) * f' z) = 1\"\n    using z assms\n    by (cases x \"(-1) :: real\" rule: linorder_cases; cases z \"(-1) :: real\" rule: linorder_cases)\n       (auto simp: f'_def sgn_mult l_def r_def)\n  hence \"(x + 1) * f' z > 0\" using sgn_greater by fastforce\n  ultimately show ?thesis by (simp add: f_def)\nqed\n\nlemma exp_times_self_ge: \"x * exp x \\<ge> -exp (-1::real)\"\n  using exp_times_self_gt[of x] by (cases \"x = -1\") auto\n\nlemma exp_times_self_strict_mono:\n  assumes \"x \\<ge> -1\" \"x < (y :: real)\"\n  shows   \"x * exp x < y * exp y\"\n  using assms(2)\nproof (rule DERIV_pos_imp_increasing_open)\n  fix t assume t: \"x < t\" \"t < y\"\n  have \"((\\<lambda>x. x * exp x) has_real_derivative (t + 1) * exp t) (at t)\"\n    by (auto intro!: derivative_eq_intros simp: algebra_simps)\n  moreover have \"(t + 1) * exp t > 0\"\n    using t assms by (intro mult_pos_pos) auto\n  ultimately show \"\\<exists>y. ((\\<lambda>a. a * exp a) has_real_derivative y) (at t) \\<and> 0 < y\" by blast\nqed (auto intro!: continuous_intros)\n\nlemma exp_times_self_strict_antimono:\n  assumes \"y \\<le> -1\" \"x < (y :: real)\"\n  shows   \"x * exp x > y * exp y\"\nproof -\n  have \"-x * exp x < -y * exp y\"\n    using assms(2)\n  proof (rule DERIV_pos_imp_increasing_open)\n    fix t assume t: \"x < t\" \"t < y\"\n    have \"((\\<lambda>x. -x * exp x) has_real_derivative (-(t + 1)) * exp t) (at t)\"\n      by (auto intro!: derivative_eq_intros simp: algebra_simps)\n    moreover have \"(-(t + 1)) * exp t > 0\"\n      using t assms by (intro mult_pos_pos) auto\n    ultimately show \"\\<exists>y. ((\\<lambda>a. -a * exp a) has_real_derivative y) (at t) \\<and> 0 < y\" by blast\n  qed (auto intro!: continuous_intros)\n  thus ?thesis by simp\nqed\n\nlemma exp_times_self_mono:\n  assumes \"x \\<ge> -1\" \"x \\<le> (y :: real)\"\n  shows   \"x * exp x \\<le> y * exp y\"\n  using exp_times_self_strict_mono[of x y] assms by (cases \"x = y\") auto\n\nlemma exp_times_self_antimono:\n  assumes \"y \\<le> -1\" \"x \\<le> (y :: real)\"\n  shows   \"x * exp x \\<ge> y * exp y\"\n  using exp_times_self_strict_antimono[of y x] assms by (cases \"x = y\") auto\n\nlemma exp_times_self_inj: \"inj_on (\\<lambda>x::real. x * exp x) {-1..}\"\nproof\n  fix x y :: real\n  assume \"x \\<in> {-1..}\" \"y \\<in> {-1..}\" \"x * exp x = y * exp y\"\n  thus \"x = y\"\n    using exp_times_self_strict_mono[of x y] exp_times_self_strict_mono[of y x]\n    by (cases x y rule: linorder_cases) auto\nqed\n\nlemma exp_times_self_inj': \"inj_on (\\<lambda>x::real. x * exp x) {..-1}\"\nproof\n  fix x y :: real\n  assume \"x \\<in> {..-1}\" \"y \\<in> {..-1}\" \"x * exp x = y * exp y\"\n  thus \"x = y\"\n    using exp_times_self_strict_antimono[of x y] exp_times_self_strict_antimono[of y x]\n    by (cases x y rule: linorder_cases) auto\nqed\n\n\nsubsection \\<open>Definition\\<close>\n\ntext \\<open>\n  The following are the two branches $W_0(x)$ and $W_{-1}(x)$ of the Lambert $W$ function on the\n  real numbers. These are the inverse functions of the function $x\\mapsto xe^x$, i.\\,e.\\ \n  we have $W(x)e^{W(x)} = x$ for both branches wherever they are defined. The two branches\n  meet at the point $x = -\\frac{1}{e}$.\n\n  $W_0(x)$ is the principal branch, whose domain is $[-\\frac{1}{e}; \\infty)$ and whose\n  range is $[-1; \\infty)$.\n  $W_{-1}(x)$ has the domain $[-\\frac{1}{e}; 0)$ and the range $(-\\infty;-1]$.\n  Figure~\\ref{fig:lambertw} shows plots of these two branches for illustration.\n\\<close>\n\ntext \\<open>\n\\definecolor{myblue}{HTML}{3869b1}\n\\definecolor{myred}{HTML}{cc2428}\n\\begin{figure}\n\\begin{center}\n\\begin{tikzpicture}\n  \\begin{axis}[\n          xmin=-0.5, xmax=6.6, ymin=-3.8, ymax=1.5, axis lines=middle, ytick = {-3, -2, -1, 1}, xtick = {1,...,10}, yticklabel pos = right,\n          yticklabel style={right,xshift=1mm},\n          extra x tick style={tick label style={above,yshift=1mm}},\n          extra x ticks={-0.367879441},\n          extra x tick labels={$-\\frac{1}{e}$},\n          width=\\textwidth, height=0.8\\textwidth,\n          xlabel={$x$}, tick style={thin,black}\n  ] \n  \\addplot [color=black, line width=0.5pt, densely dashed, mark=none,domain=-5:0,samples=200] ({-exp(-1)}, {x}); \n  \\addplot [color=myblue, line width=1pt, mark=none,domain=-1:1.5,samples=200] ({x*exp(x)}, {x}); \n  \\addplot [color=myred, line width=1pt, mark=none,domain=-5:-1,samples=200] ({x*exp(x)}, {x}); \n  \\end{axis}\n\\end{tikzpicture}\n\\end{center}\n\\caption{The two real branches of the Lambert $W$ function: $W_0$ (blue) and $W_{-1}$ (red).}\n\\label{fig:lambertw}\n\\end{figure}\n\\<close>\n\ndefinition Lambert_W :: \"real \\<Rightarrow> real\" where\n  \"Lambert_W x = (if x < -exp(-1) then -1 else (THE w. w \\<ge> -1 \\<and> w * exp w = x))\"\n\ndefinition Lambert_W' :: \"real \\<Rightarrow> real\" where\n  \"Lambert_W' x = (if x \\<in> {-exp(-1)..<0} then (THE w. w \\<le> -1 \\<and> w * exp w = x) else -1)\"\n\nlemma Lambert_W_ex1:\n  assumes \"(x::real) \\<ge> -exp (-1)\"\n  shows   \"\\<exists>!w. w \\<ge> -1 \\<and> w * exp w = x\"\nproof (rule ex_ex1I)\n  have \"filterlim (\\<lambda>w::real. w * exp w) at_top at_top\"\n    by real_asymp\n  hence \"eventually (\\<lambda>w. w * exp w \\<ge> x) at_top\"\n    by (auto simp: filterlim_at_top)\n  hence \"eventually (\\<lambda>w. w \\<ge> 0 \\<and> w * exp w \\<ge> x) at_top\"\n    by (intro eventually_conj eventually_ge_at_top)\n  then obtain w' where w': \"w' * exp w' \\<ge> x\" \"w' \\<ge> 0\"\n    by (auto simp: eventually_at_top_linorder)\n  from w' assms have \"\\<exists>w. -1 \\<le> w \\<and> w \\<le> w' \\<and> w * exp w = x\"\n    by (intro IVT' continuous_intros) auto\n  thus \"\\<exists>w. w \\<ge> -1 \\<and> w * exp w = x\" by blast\nnext\n  fix w w' :: real\n  assume ww': \"w \\<ge> -1 \\<and> w * exp w = x\" \"w' \\<ge> -1 \\<and> w' * exp w' = x\"\n  hence \"w * exp w = w' * exp w'\" by simp\n  thus \"w = w'\"\n    using exp_times_self_strict_mono[of w w'] exp_times_self_strict_mono[of w' w] ww'\n    by (cases w w' rule: linorder_cases) auto\nqed\n\nlemma Lambert_W'_ex1:\n  assumes \"(x::real) \\<in> {-exp (-1)..<0}\"\n  shows   \"\\<exists>!w. w \\<le> -1 \\<and> w * exp w = x\"\nproof (rule ex_ex1I)\n  have \"eventually (\\<lambda>w. x \\<le> w * exp w) at_bot\"\n    using assms by real_asymp\n  hence \"eventually (\\<lambda>w. w \\<le> -1 \\<and> w * exp w \\<ge> x) at_bot\"\n    by (intro eventually_conj eventually_le_at_bot)\n  then obtain w' where w': \"w' * exp w' \\<ge> x\" \"w' \\<le> -1\"\n    by (auto simp: eventually_at_bot_linorder)\n\n  from w' assms have \"\\<exists>w. w' \\<le> w \\<and> w \\<le> -1 \\<and> w * exp w = x\"\n    by (intro IVT2' continuous_intros) auto\n  thus \"\\<exists>w. w \\<le> -1 \\<and> w * exp w = x\" by blast\nnext\n  fix w w' :: real\n  assume ww': \"w \\<le> -1 \\<and> w * exp w = x\" \"w' \\<le> -1 \\<and> w' * exp w' = x\"\n  hence \"w * exp w = w' * exp w'\" by simp\n  thus \"w = w'\"\n    using exp_times_self_strict_antimono[of w w'] exp_times_self_strict_antimono[of w' w] ww'\n    by (cases w w' rule: linorder_cases) auto\nqed\n\nlemma Lambert_W_times_exp_self: \n  assumes \"x \\<ge> -exp (-1)\"\n  shows   \"Lambert_W x * exp (Lambert_W x) = x\"\n  using theI'[OF Lambert_W_ex1[OF assms]] assms by (auto simp: Lambert_W_def)\n\nlemma Lambert_W_times_exp_self':\n  assumes \"x \\<ge> -exp (-1)\"\n  shows   \"exp (Lambert_W x) * Lambert_W x = x\"\n  using Lambert_W_times_exp_self[of x] assms by (simp add: mult_ac)\n\n\n\nlemma Lambert_W'_times_exp_self':\n  assumes \"x \\<in> {-exp (-1)..<0}\"\n  shows   \"exp (Lambert_W' x) * Lambert_W' x = x\"\n  using Lambert_W'_times_exp_self[of x] assms by (simp add: mult_ac)\n\nlemma Lambert_W_ge: \"Lambert_W x \\<ge> -1\"\n  using theI'[OF Lambert_W_ex1[of x]] by (auto simp: Lambert_W_def)\n\nlemma Lambert_W'_le: \"Lambert_W' x \\<le> -1\"\n  using theI'[OF Lambert_W'_ex1[of x]] by (auto simp: Lambert_W'_def)\n\nlemma Lambert_W_eqI:\n  assumes \"w \\<ge> -1\" \"w * exp w = x\"\n  shows   \"Lambert_W x = w\"\nproof -\n  from assms exp_times_self_ge[of w] have \"x \\<ge> -exp (-1)\"\n    by (cases \"x \\<ge> -exp (-1)\") auto\n  from Lambert_W_ex1[OF this] Lambert_W_times_exp_self[OF this] Lambert_W_ge[of x] assms\n    show ?thesis by metis\n  qed\n\nlemma Lambert_W'_eqI:\n  assumes \"w \\<le> -1\" \"w * exp w = x\"\n  shows   \"Lambert_W' x = w\"\nproof -\n  from assms exp_times_self_ge[of w] have \"x \\<ge> -exp (-1)\"\n    by (cases \"x \\<ge> -exp (-1)\") auto\n  moreover from assms have \"w * exp w < 0\"\n    by (intro mult_neg_pos) auto\n  ultimately have \"x \\<in> {-exp (-1)..<0}\"\n    using assms by auto\n\n  from Lambert_W'_ex1[OF this(1)] Lambert_W'_times_exp_self[OF this(1)] Lambert_W'_le assms\n    show ?thesis by metis\n  qed\n\ntext \\<open>\n  $W_0(x)$ and $W_{-1}(x)$ together fully cover all solutions of $we^w = x$:\n\\<close>\nlemma exp_times_self_eqD:\n  assumes \"w * exp w = x\"\n  shows   \"x \\<ge> -exp (-1)\" and \"w = Lambert_W x \\<or> x < 0 \\<and> w = Lambert_W' x\"\nproof -\n  from assms show \"x \\<ge> -exp (-1)\"\n    using exp_times_self_ge[of w] by auto\n  show \"w = Lambert_W x \\<or> x < 0 \\<and> w = Lambert_W' x\"\n  proof (cases \"w \\<ge> -1\")\n    case True\n    hence \"Lambert_W x = w\"\n      using assms by (intro Lambert_W_eqI) auto\n    thus ?thesis by auto\n  next\n    case False\n    from False have \"w * exp w < 0\"\n      by (intro mult_neg_pos) auto\n    from False have \"Lambert_W' x = w\"\n      using assms by (intro Lambert_W'_eqI) auto\n    thus ?thesis using assms \\<open>w * exp w < 0\\<close> by auto\n  qed\nqed\n\ntheorem exp_times_self_eq_iff:\n  \"w * exp w = x \\<longleftrightarrow> x \\<ge> -exp (-1) \\<and> (w = Lambert_W x \\<or> x < 0 \\<and> w = Lambert_W' x)\"\n  using exp_times_self_eqD[of w x]\n  by (auto simp: Lambert_W_times_exp_self Lambert_W'_times_exp_self)\n\nlemma Lambert_W_exp_times_self [simp]: \"x \\<ge> -1 \\<Longrightarrow> Lambert_W (x * exp x) = x\"\n  by (rule Lambert_W_eqI) auto\n\nlemma Lambert_W_exp_times_self' [simp]: \"x \\<ge> -1 \\<Longrightarrow> Lambert_W (exp x * x) = x\"\n  by (rule Lambert_W_eqI) auto\n\nlemma Lambert_W'_exp_times_self [simp]: \"x \\<le> -1 \\<Longrightarrow> Lambert_W' (x * exp x) = x\"\n  by (rule Lambert_W'_eqI) auto\n\nlemma Lambert_W'_exp_times_self' [simp]: \"x \\<le> -1 \\<Longrightarrow> Lambert_W' (exp x * x) = x\"\n  by (rule Lambert_W'_eqI) auto\n\nlemma Lambert_W_times_ln_self:\n  assumes \"x \\<ge> exp (-1)\"\n  shows   \"Lambert_W (x * ln x) = ln x\"\nproof -\n  have \"0 < exp (-1 :: real)\"\n    by simp\n  also note \\<open>\\<dots> \\<le> x\\<close>\n  finally have \"x > 0\" .\n  from assms have \"ln (exp (-1)) \\<le> ln x\"\n    using \\<open>x > 0\\<close> by (subst ln_le_cancel_iff) auto\n  hence \"Lambert_W (exp (ln x) * ln x) = ln x\"\n    by (subst Lambert_W_exp_times_self') auto\n  thus ?thesis using \\<open>x > 0\\<close> by simp\nqed\n\nlemma Lambert_W_times_ln_self':\n  assumes \"x \\<ge> exp (-1)\"\n  shows   \"Lambert_W (ln x  * x) = ln x\"\n  using Lambert_W_times_ln_self[OF assms] by (simp add: mult.commute)\n\nlemma Lambert_W_eq_minus_exp_minus1 [simp]: \"Lambert_W (-exp (-1)) = -1\"\n  by (rule Lambert_W_eqI) auto\n\nlemma Lambert_W'_eq_minus_exp_minus1 [simp]: \"Lambert_W' (-exp (-1)) = -1\"\n  by (rule Lambert_W'_eqI) auto\n\nlemma Lambert_W_0 [simp]: \"Lambert_W 0 = 0\"\n  by (rule Lambert_W_eqI) auto\n\n\nsubsection \\<open>Monotonicity properties\\<close>\n\nlemma Lambert_W_strict_mono:\n  assumes \"x \\<ge> -exp(-1)\" \"x < y\"\n  shows   \"Lambert_W x < Lambert_W y\"\nproof (rule ccontr)\n  assume \"\\<not>(Lambert_W x < Lambert_W y)\"\n  hence \"Lambert_W x * exp (Lambert_W x) \\<ge> Lambert_W y * exp (Lambert_W y)\"\n    by (intro exp_times_self_mono) (auto simp: Lambert_W_ge)\n  hence \"x \\<ge> y\"\n    using assms by (simp add: Lambert_W_times_exp_self)\n  with assms show False by simp\nqed\n\nlemma Lambert_W_mono:\n  assumes \"x \\<ge> -exp(-1)\" \"x \\<le> y\"\n  shows   \"Lambert_W x \\<le> Lambert_W y\"\n  using Lambert_W_strict_mono[of x y] assms by (cases \"x = y\") auto\n\nlemma Lambert_W_eq_iff [simp]:\n  \"x \\<ge> -exp(-1) \\<Longrightarrow> y \\<ge> -exp(-1) \\<Longrightarrow> Lambert_W x = Lambert_W y \\<longleftrightarrow> x = y\"\n  using Lambert_W_strict_mono[of x y] Lambert_W_strict_mono[of y x]\n  by (cases x y rule: linorder_cases) auto\n\nlemma Lambert_W_le_iff [simp]:\n  \"x \\<ge> -exp(-1) \\<Longrightarrow> y \\<ge> -exp(-1) \\<Longrightarrow> Lambert_W x \\<le> Lambert_W y \\<longleftrightarrow> x \\<le> y\"\n  using Lambert_W_strict_mono[of x y] Lambert_W_strict_mono[of y x]\n  by (cases x y rule: linorder_cases) auto\n\nlemma Lambert_W_less_iff [simp]:\n  \"x \\<ge> -exp(-1) \\<Longrightarrow> y \\<ge> -exp(-1) \\<Longrightarrow> Lambert_W x < Lambert_W y \\<longleftrightarrow> x < y\"\n  using Lambert_W_strict_mono[of x y] Lambert_W_strict_mono[of y x]\n  by (cases x y rule: linorder_cases) auto\n\nlemma Lambert_W_le_minus_one:\n  assumes \"x \\<le> -exp(-1)\"\n  shows   \"Lambert_W x = -1\"\nproof (cases \"x = -exp(-1)\")\n  case False\n  thus ?thesis using assms\n    by (auto simp: Lambert_W_def)\nqed auto\n\nlemma Lambert_W_pos_iff [simp]: \"Lambert_W x > 0 \\<longleftrightarrow> x > 0\"\nproof (cases \"x \\<ge> -exp (-1)\")\n  case True\n  thus ?thesis\n    using Lambert_W_less_iff[of 0 x] by (simp del: Lambert_W_less_iff)\nnext\n  case False\n  hence \"x < - exp(-1)\" by auto\n  also have \"\\<dots> \\<le> 0\" by simp\n  finally show ?thesis using False\n    by (auto simp: Lambert_W_le_minus_one)\nqed\n\nlemma Lambert_W_eq_0_iff [simp]: \"Lambert_W x = 0 \\<longleftrightarrow> x = 0\"\n  using Lambert_W_eq_iff[of x 0]\n  by (cases \"x \\<ge> -exp (-1)\") (auto simp: Lambert_W_le_minus_one simp del: Lambert_W_eq_iff)\n\n\n\nlemma Lambert_W_neg_iff [simp]: \"Lambert_W x < 0 \\<longleftrightarrow> x < 0\"\n  using Lambert_W_nonneg_iff[of x] by (auto simp del: Lambert_W_nonneg_iff)\n\nlemma Lambert_W_nonpos_iff [simp]: \"Lambert_W x \\<le> 0 \\<longleftrightarrow> x \\<le> 0\"\n  using Lambert_W_pos_iff[of x] by (auto simp del: Lambert_W_pos_iff)\n\nlemma Lambert_W_geI:\n  assumes \"y * exp y \\<le> x\"\n  shows   \"Lambert_W x \\<ge> y\"\nproof (cases \"y \\<ge> -1\")\n  case False\n  hence \"y \\<le> -1\" by simp\n  also have \"-1 \\<le> Lambert_W x\" by (rule Lambert_W_ge)\n  finally show ?thesis .\nnext\n  case True\n  have \"Lambert_W x \\<ge> Lambert_W (y * exp y)\"\n    using assms exp_times_self_ge[of y] by (intro Lambert_W_mono) auto\n  thus ?thesis using assms True by simp\nqed\n\nlemma Lambert_W_gtI:\n  assumes \"y * exp y < x\"\n  shows   \"Lambert_W x > y\"\nproof (cases \"y \\<ge> -1\")\n  case False\n  hence \"y < -1\" by simp\n  also have \"-1 \\<le> Lambert_W x\" by (rule Lambert_W_ge)\n  finally show ?thesis .\nnext\n  case True\n  have \"Lambert_W x > Lambert_W (y * exp y)\"\n    using assms exp_times_self_ge[of y] by (intro Lambert_W_strict_mono) auto\n  thus ?thesis using assms True by simp\nqed\n\nlemma Lambert_W_leI:\n  assumes \"y * exp y \\<ge> x\" \"y \\<ge> -1\" \"x \\<ge> -exp (-1)\"\n  shows   \"Lambert_W x \\<le> y\"\nproof -\n  have \"Lambert_W x \\<le> Lambert_W (y * exp y)\"\n    using assms exp_times_self_ge[of y] by (intro Lambert_W_mono) auto\n  thus ?thesis using assms by simp\nqed\n\nlemma Lambert_W_lessI:\n  assumes \"y * exp y > x\" \"y \\<ge> -1\" \"x \\<ge> -exp (-1)\"\n  shows   \"Lambert_W x < y\"\nproof -\n  have \"Lambert_W x < Lambert_W (y * exp y)\"\n    using assms exp_times_self_ge[of y] by (intro Lambert_W_strict_mono) auto\n  thus ?thesis using assms by simp\nqed\n\n\n\nlemma Lambert_W'_strict_antimono:\n  assumes \"-exp (-1) \\<le> x\" \"x < y\" \"y < 0\"\n  shows   \"Lambert_W' x > Lambert_W' y\"\nproof (rule ccontr)\n  assume \"\\<not>(Lambert_W' x > Lambert_W' y)\"\n  hence \"Lambert_W' x * exp (Lambert_W' x) \\<ge> Lambert_W' y * exp (Lambert_W' y)\"\n    using assms by (intro exp_times_self_antimono Lambert_W'_le) auto\n  hence \"x \\<ge> y\"\n    using assms by (simp add: Lambert_W'_times_exp_self)\n  with assms show False by simp\nqed\n\nlemma Lambert_W'_antimono:\n  assumes \"x \\<ge> -exp(-1)\" \"x \\<le> y\" \"y < 0\"\n  shows   \"Lambert_W' x \\<ge> Lambert_W' y\"\n  using Lambert_W'_strict_antimono[of x y] assms by (cases \"x = y\") auto\n\nlemma Lambert_W'_eq_iff [simp]:\n  \"x \\<in> {-exp(-1)..<0} \\<Longrightarrow> y \\<in> {-exp(-1)..<0} \\<Longrightarrow> Lambert_W' x = Lambert_W' y \\<longleftrightarrow> x = y\"\n  using Lambert_W'_strict_antimono[of x y] Lambert_W'_strict_antimono[of y x]\n  by (cases x y rule: linorder_cases) auto\n\nlemma Lambert_W'_le_iff [simp]:\n  \"x \\<in> {-exp(-1)..<0} \\<Longrightarrow> y \\<in> {-exp(-1)..<0} \\<Longrightarrow> Lambert_W' x \\<le> Lambert_W' y \\<longleftrightarrow> x \\<ge> y\"\n  using Lambert_W'_strict_antimono[of x y] Lambert_W'_strict_antimono[of y x]\n  by (cases x y rule: linorder_cases) auto\n\nlemma Lambert_W'_less_iff [simp]:\n  \"x \\<in> {-exp(-1)..<0} \\<Longrightarrow> y \\<in> {-exp(-1)..<0} \\<Longrightarrow> Lambert_W' x < Lambert_W' y \\<longleftrightarrow> x > y\"\n  using Lambert_W'_strict_antimono[of x y] Lambert_W'_strict_antimono[of y x]\n  by (cases x y rule: linorder_cases) auto\n\nlemma Lambert_W'_le_minus_one:\n  assumes \"x \\<le> -exp(-1)\"\n  shows   \"Lambert_W' x = -1\"\nproof (cases \"x = -exp(-1)\")\n  case False\n  thus ?thesis using assms\n    by (auto simp: Lambert_W'_def)\nqed auto\n\nlemma Lambert_W'_ge_zero: \"x \\<ge> 0 \\<Longrightarrow> Lambert_W' x = -1\"\n  by (simp add: Lambert_W'_def)\n\nlemma Lambert_W'_neg: \"Lambert_W' x < 0\"\n  by (rule le_less_trans[OF Lambert_W'_le]) auto\n\nlemma Lambert_W'_nz [simp]: \"Lambert_W' x \\<noteq> 0\"\n  using Lambert_W'_neg[of x] by simp\n\nlemma Lambert_W'_geI:\n  assumes \"y * exp y \\<ge> x\" \"y \\<le> -1\" \"x \\<ge> -exp(-1)\"\n  shows   \"Lambert_W' x \\<ge> y\"\nproof -\n  from assms have \"y * exp y < 0\"\n    by (intro mult_neg_pos) auto\n  hence \"Lambert_W' x \\<ge> Lambert_W' (y * exp y)\"\n    using assms exp_times_self_ge[of y] by (intro Lambert_W'_antimono) auto\n  thus ?thesis using assms by simp\nqed\n\nlemma Lambert_W'_gtI:\n  assumes \"y * exp y > x\" \"y \\<le> -1\" \"x \\<ge> -exp(-1)\"\n  shows   \"Lambert_W' x \\<ge> y\"\nproof -\n  from assms have \"y * exp y < 0\"\n    by (intro mult_neg_pos) auto\n  hence \"Lambert_W' x > Lambert_W' (y * exp y)\"\n    using assms exp_times_self_ge[of y] by (intro Lambert_W'_strict_antimono) auto\n  thus ?thesis using assms by simp\nqed\n\nlemma Lambert_W'_leI:\n  assumes \"y * exp y \\<le> x\" \"x < 0\"\n  shows   \"Lambert_W' x \\<le> y\"\nproof (cases \"y \\<le> -1\")\n  case True\n  have \"Lambert_W' x \\<le> Lambert_W' (y * exp y)\"\n    using assms exp_times_self_ge[of y] by (intro Lambert_W'_antimono) auto\n  thus ?thesis using assms True by simp\nnext\n  case False\n  have \"Lambert_W' x \\<le> -1\"\n    by (rule Lambert_W'_le)\n  also have \"\\<dots> < y\"\n    using False by simp\n  finally show ?thesis by simp\nqed\n\nlemma Lambert_W'_lessI:\n  assumes \"y * exp y < x\" \"x < 0\"\n  shows   \"Lambert_W' x < y\"\nproof (cases \"y \\<le> -1\")\n  case True\n  have \"Lambert_W' x < Lambert_W' (y * exp y)\"\n    using assms exp_times_self_ge[of y] by (intro Lambert_W'_strict_antimono) auto\n  thus ?thesis using assms True by simp\nnext\n  case False\n  have \"Lambert_W' x \\<le> -1\"\n    by (rule Lambert_W'_le)\n  also have \"\\<dots> < y\"\n    using False by simp\n  finally show ?thesis by simp\nqed\n\n\nlemma bij_betw_exp_times_self_atLeastAtMost:\n  fixes a b :: real\n  assumes \"a \\<ge> -1\" \"a \\<le> b\"\n  shows   \"bij_betw (\\<lambda>x. x * exp x) {a..b} {a * exp a..b * exp b}\"\n  unfolding bij_betw_def\nproof\n  show \"inj_on (\\<lambda>x. x * exp x) {a..b}\"\n    by (rule inj_on_subset[OF exp_times_self_inj]) (use assms in auto)\nnext\n  show \"(\\<lambda>x. x * exp x) ` {a..b} = {a * exp a..b * exp b}\"\n  proof safe\n    fix x assume \"x \\<in> {a..b}\"\n    thus \"x * exp x \\<in> {a * exp a..b * exp b}\"\n      using assms by (auto intro!: exp_times_self_mono)\n  next\n    fix x assume x: \"x \\<in> {a * exp a..b * exp b}\"\n    have \"(-1) * exp (-1) \\<le> a * exp a\"\n      using assms by (intro exp_times_self_mono) auto\n    also have \"\\<dots> \\<le> x\" using x by simp\n    finally have \"x \\<ge> -exp (-1)\" by simp\n\n    have \"Lambert_W x \\<in> {a..b}\"\n      using x \\<open>x \\<ge> -exp (-1)\\<close> assms by (auto intro!: Lambert_W_geI Lambert_W_leI)\n    moreover have \"Lambert_W x * exp (Lambert_W x) = x\"\n      using \\<open>x \\<ge> -exp (-1)\\<close> by (simp add: Lambert_W_times_exp_self)\n    ultimately show \"x \\<in> (\\<lambda>x. x * exp x) ` {a..b}\"\n      unfolding image_iff by metis\n  qed\nqed\n\nlemma bij_betw_exp_times_self_atLeastAtMost':\n  fixes a b :: real\n  assumes \"a \\<le> b\" \"b \\<le> -1\"\n  shows   \"bij_betw (\\<lambda>x. x * exp x) {a..b} {b * exp b..a * exp a}\"\n  unfolding bij_betw_def\nproof\n  show \"inj_on (\\<lambda>x. x * exp x) {a..b}\"\n    by (rule inj_on_subset[OF exp_times_self_inj']) (use assms in auto)\nnext\n  show \"(\\<lambda>x. x * exp x) ` {a..b} = {b * exp b..a * exp a}\"\n  proof safe\n    fix x assume \"x \\<in> {a..b}\"\n    thus \"x * exp x \\<in> {b * exp b..a * exp a}\"\n      using assms by (auto intro!: exp_times_self_antimono)\n  next\n    fix x assume x: \"x \\<in> {b * exp b..a * exp a}\"\n    from assms have \"a * exp a < 0\"\n      by (intro mult_neg_pos) auto\n    with x have \"x < 0\" by auto\n    have \"(-1) * exp (-1) \\<le> b * exp b\"\n      using assms by (intro exp_times_self_antimono) auto\n    also have \"\\<dots> \\<le> x\" using x by simp\n    finally have \"x \\<ge> -exp (-1)\" by simp\n\n    have \"Lambert_W' x \\<in> {a..b}\"\n      using x \\<open>x \\<ge> -exp (-1)\\<close> \\<open>x < 0\\<close> assms \n      by (auto intro!: Lambert_W'_geI Lambert_W'_leI)\n    moreover have \"Lambert_W' x * exp (Lambert_W' x) = x\"\n      using \\<open>x \\<ge> -exp (-1)\\<close> \\<open>x < 0\\<close> by (auto simp: Lambert_W'_times_exp_self)\n    ultimately show \"x \\<in> (\\<lambda>x. x * exp x) ` {a..b}\"\n      unfolding image_iff by metis\n  qed\nqed\n\nlemma bij_betw_exp_times_self_atLeast:\n  fixes a :: real\n  assumes \"a \\<ge> -1\"\n  shows   \"bij_betw (\\<lambda>x. x * exp x) {a..} {a * exp a..}\"\n  unfolding bij_betw_def\nproof\n  show \"inj_on (\\<lambda>x. x * exp x) {a..}\"\n    by (rule inj_on_subset[OF exp_times_self_inj]) (use assms in auto)\nnext\n  show \"(\\<lambda>x. x * exp x) ` {a..} = {a * exp a..}\"\n  proof safe\n    fix x assume \"x \\<ge> a\"\n    thus \"x * exp x \\<ge> a * exp a\"\n      using assms by (auto intro!: exp_times_self_mono)\n  next\n    fix x assume x: \"x \\<ge> a * exp a\"\n    have \"(-1) * exp (-1) \\<le> a * exp a\"\n      using assms by (intro exp_times_self_mono) auto\n    also have \"\\<dots> \\<le> x\" using x by simp\n    finally have \"x \\<ge> -exp (-1)\" by simp\n\n    have \"Lambert_W x \\<in> {a..}\"\n      using x \\<open>x \\<ge> -exp (-1)\\<close> assms by (auto intro!: Lambert_W_geI Lambert_W_leI)\n    moreover have \"Lambert_W x * exp (Lambert_W x) = x\"\n      using \\<open>x \\<ge> -exp (-1)\\<close> by (simp add: Lambert_W_times_exp_self)\n    ultimately show \"x \\<in> (\\<lambda>x. x * exp x) ` {a..}\"\n      unfolding image_iff by metis\n  qed\nqed\n\n\nsubsection \\<open>Basic identities and bounds\\<close>\n\nlemma Lambert_W_2_ln_2 [simp]: \"Lambert_W (2 * ln 2) = ln 2\"\nproof -\n  have \"-1 \\<le> (0 :: real)\"\n    by simp\n  also have \"\\<dots> \\<le> ln 2\"\n    by simp\n  finally have \"-1 \\<le> (ln 2 :: real)\" .\n  thus ?thesis\n    by (intro Lambert_W_eqI) auto\nqed\n\nlemma Lambert_W_exp_1 [simp]: \"Lambert_W (exp 1) = 1\"\n  by (rule Lambert_W_eqI) auto\n\nlemma Lambert_W_neg_ln_over_self:\n  assumes \"x \\<in> {exp (-1)..exp 1}\"\n  shows   \"Lambert_W (-ln x / x) = -ln x\"\nproof -\n  have \"0 < (exp (-1) :: real)\"\n    by simp\n  also have \"\\<dots> \\<le> x\"\n    using assms by simp\n  finally have \"x > 0\" .\n  from \\<open>x > 0\\<close> assms have \"ln x \\<le> ln (exp 1)\"\n    by (subst ln_le_cancel_iff) auto\n  also have \"ln (exp 1) = (1 :: real)\"\n    by simp\n  finally have \"ln x \\<le> 1\" .\n  show ?thesis\n    using assms \\<open>x > 0\\<close> \\<open>ln x \\<le> 1\\<close>\n    by (intro Lambert_W_eqI) (auto simp: exp_minus field_simps)\nqed\n\nlemma Lambert_W'_neg_ln_over_self:\n  assumes \"x \\<ge> exp 1\"\n  shows   \"Lambert_W' (-ln x / x) = -ln x\"\nproof (rule Lambert_W'_eqI)\n  have \"0 < (exp 1 :: real)\"\n    by simp\n  also have \"\\<dots> \\<le> x\"\n    by fact\n  finally have \"x > 0\" .\n  from assms \\<open>x > 0\\<close> have \"ln x \\<ge> ln (exp 1)\"\n    by (subst ln_le_cancel_iff) auto\n  thus \"-ln x \\<le> -1\" by simp\n  show \"-ln x * exp (-ln x) = -ln x / x\"\n    using \\<open>x > 0\\<close> by (simp add: field_simps exp_minus)\nqed\n\nlemma exp_Lambert_W: \"x \\<ge> -exp (-1) \\<Longrightarrow> x \\<noteq> 0 \\<Longrightarrow> exp (Lambert_W x) = x / Lambert_W x\"\n  using Lambert_W_times_exp_self[of x] by (auto simp add: divide_simps mult_ac)\n\nlemma exp_Lambert_W': \"x \\<in> {-exp (-1)..<0} \\<Longrightarrow> exp (Lambert_W' x) = x / Lambert_W' x\"\n  using Lambert_W'_times_exp_self[of x] by (auto simp add: divide_simps mult_ac)\n\nlemma ln_Lambert_W:\n  assumes \"x > 0\"\n  shows   \"ln (Lambert_W x) = ln x - Lambert_W x\"\nproof -\n  have \"-exp (-1) \\<le> (0 :: real)\"\n    by simp\n  also have \"\\<dots> < x\" by fact\n  finally have x: \"x > -exp(-1)\" .\n\n  have \"exp (ln (Lambert_W x)) = exp (ln x - Lambert_W x)\"\n    using assms x by (subst exp_diff) (auto simp: exp_Lambert_W)\n  thus ?thesis by (subst (asm) exp_inj_iff)\nqed\n\nlemma ln_minus_Lambert_W':\n  assumes \"x \\<in> {-exp (-1)..<0}\"\n  shows   \"ln (-Lambert_W' x) = ln (-x) - Lambert_W' x\"\nproof -\n  have \"exp (ln (-x) - Lambert_W' x) = -Lambert_W' x\"\n    using assms by (simp add: exp_diff exp_Lambert_W')\n  also have \"\\<dots> = exp (ln (-Lambert_W' x))\"\n    using Lambert_W'_neg[of x] by simp\n  finally show ?thesis by simp\nqed\n\nlemma Lambert_W_plus_Lambert_W_eq:\n  assumes \"x > 0\" \"y > 0\"\n  shows   \"Lambert_W x + Lambert_W y = Lambert_W (x * y * (1 / Lambert_W x + 1 / Lambert_W y))\"\nproof (rule sym, rule Lambert_W_eqI)\n  have \"x > -exp(-1)\" \"y > -exp (-1)\"\n    by (rule less_trans[OF _ assms(1)] less_trans[OF _ assms(2)], simp)+\n  with assms show \"(Lambert_W x + Lambert_W y) * exp (Lambert_W x + Lambert_W y) =\n                     x * y * (1 / Lambert_W x + 1 / Lambert_W y)\"\n    by (auto simp: field_simps exp_add exp_Lambert_W)\n  have \"-1 \\<le> (0 :: real)\"\n    by simp\n  also from assms have \"\\<dots> \\<le> Lambert_W x + Lambert_W y\"\n    by (intro add_nonneg_nonneg) auto\n  finally show \"\\<dots> \\<ge> -1\" .\nqed\n\nlemma Lambert_W'_plus_Lambert_W'_eq:\n  assumes \"x \\<in> {-exp(-1)..<0}\" \"y \\<in> {-exp(-1)..<0}\"\n  shows   \"Lambert_W' x + Lambert_W' y = Lambert_W' (x * y * (1 / Lambert_W' x + 1 / Lambert_W' y))\"\nproof (rule sym, rule Lambert_W'_eqI)\n  from assms show \"(Lambert_W' x + Lambert_W' y) * exp (Lambert_W' x + Lambert_W' y) =\n                     x * y * (1 / Lambert_W' x + 1 / Lambert_W' y)\"\n    by (auto simp: field_simps exp_add exp_Lambert_W')\n  have \"Lambert_W' x + Lambert_W' y \\<le> -1 + -1\"\n    by (intro add_mono Lambert_W'_le)\n  also have \"\\<dots> \\<le> -1\" by simp\n  finally show \"Lambert_W' x + Lambert_W' y \\<le> -1\" .\nqed\n\nlemma Lambert_W_gt_ln_minus_ln_ln:\n  assumes \"x > exp 1\"\n  shows   \"Lambert_W x > ln x - ln (ln x)\"\nproof (rule Lambert_W_gtI)\n  have \"x > 1\"\n    by (rule less_trans[OF _ assms]) auto\n  have \"ln x > ln (exp 1)\"\n    by (subst ln_less_cancel_iff) (use \\<open>x > 1\\<close> assms in auto)\n  thus \"(ln x - ln (ln x)) * exp (ln x - ln (ln x)) < x\"\n    using assms \\<open>x > 1\\<close> by (simp add: exp_diff field_simps)\nqed\n\nlemma Lambert_W_less_ln:\n  assumes \"x > exp 1\"\n  shows   \"Lambert_W x < ln x\"\nproof (rule Lambert_W_lessI)\n  have \"x > 0\"\n    by (rule less_trans[OF _ assms]) auto\n  have \"ln x > ln (exp 1)\"\n    by (subst ln_less_cancel_iff) (use \\<open>x > 0\\<close> assms in auto)\n  thus \"x < ln x * exp (ln x)\"\n    using \\<open>x > 0\\<close> by simp\n  show \"ln x \\<ge> -1\"\n    by (rule less_imp_le[OF le_less_trans[OF _ \\<open>ln x > _\\<close>]]) auto\n  show \"x \\<ge> -exp (-1)\"\n    by (rule less_imp_le[OF le_less_trans[OF _ \\<open>x > 0\\<close>]]) auto\nqed\n\n\nsubsection \\<open>Limits, continuity, and differentiability\\<close>\n\nlemma filterlim_Lambert_W_at_top [tendsto_intros]: \"filterlim Lambert_W at_top at_top\"\n  unfolding filterlim_at_top\nproof\n  fix C :: real\n  have \"eventually (\\<lambda>x. x \\<ge> C * exp C) at_top\"\n    by (rule eventually_ge_at_top)\n  thus \"eventually (\\<lambda>x. Lambert_W x \\<ge> C) at_top\"\n  proof eventually_elim\n    case (elim x)\n    thus ?case\n      by (intro Lambert_W_geI) auto\n  qed\nqed\n\nlemma filterlim_Lambert_W_at_left_0 [tendsto_intros]:\n  \"filterlim Lambert_W' at_bot (at_left 0)\"\n  unfolding filterlim_at_bot\nproof\n  fix C :: real\n  define C' where \"C' = min C (-1)\"\n  have \"C' < 0\" \"C' \\<le> C\"\n    by (simp_all add: C'_def)\n  have \"C' * exp C' < 0\"\n    using \\<open>C' < 0\\<close> by (intro mult_neg_pos) auto\n  hence \"eventually (\\<lambda>x. x \\<ge> C' * exp C') (at_left 0)\"\n    by real_asymp\n  moreover have \"eventually (\\<lambda>x::real. x < 0) (at_left 0)\"\n    by real_asymp\n  ultimately show \"eventually (\\<lambda>x. Lambert_W' x \\<le> C) (at_left 0)\"\n  proof eventually_elim\n    case (elim x)\n    hence \"Lambert_W' x \\<le> C'\"\n      by (intro Lambert_W'_leI) auto\n    also have \"\\<dots> \\<le> C\" by fact\n    finally show ?case .\n  qed\nqed\n\nlemma continuous_on_Lambert_W [continuous_intros]: \"continuous_on {-exp (-1)..} Lambert_W\"\nproof -\n  have *: \"continuous_on {-exp (-1)..b * exp b} Lambert_W\" if \"b \\<ge> 0\" for b\n  proof -\n    have \"continuous_on ((\\<lambda>x. x * exp x) ` {-1..b}) Lambert_W\"\n      by (rule continuous_on_inv) (auto intro!: continuous_intros)\n    also have \"(\\<lambda>x. x * exp x) ` {-1..b} = {-exp (-1)..b * exp b}\"\n      using bij_betw_exp_times_self_atLeastAtMost[of \"-1\" b] \\<open>b \\<ge> 0\\<close>\n      by (simp add: bij_betw_def)\n    finally show ?thesis .\n  qed\n\n  have \"continuous (at x) Lambert_W\" if \"x \\<ge> 0\" for x\n  proof -\n    have x: \"-exp (-1) < x\"\n      by (rule less_le_trans[OF _ that]) auto\n    \n    define b where \"b = Lambert_W x + 1\"\n    have \"b \\<ge> 0\"\n      using Lambert_W_ge[of x] by (simp add: b_def)\n    have \"x = Lambert_W x * exp (Lambert_W x)\"\n      using that x by (subst Lambert_W_times_exp_self) auto\n    also have \"\\<dots> < b * exp b\"\n      by (intro exp_times_self_strict_mono) (auto simp: b_def Lambert_W_ge)\n    finally have \"b * exp b > x\" .\n    have \"continuous_on {-exp(-1)<..<b * exp b} Lambert_W\"\n      by (rule continuous_on_subset[OF *[of b]]) (use \\<open>b \\<ge> 0\\<close> in auto)\n    moreover have \"x \\<in> {-exp(-1)<..<b * exp b}\"\n      using \\<open>b * exp b > x\\<close> x by (auto simp: )\n    ultimately show \"continuous (at x) Lambert_W\"\n      by (subst (asm) continuous_on_eq_continuous_at) auto\n  qed\n  hence \"continuous_on {0..} Lambert_W\"\n    by (intro continuous_at_imp_continuous_on) auto\n  moreover have \"continuous_on {-exp (-1)..0} Lambert_W\"\n    using *[of 0] by simp\n  ultimately have \"continuous_on ({-exp (-1)..0} \\<union> {0..}) Lambert_W\"\n    by (intro continuous_on_closed_Un) auto\n  also have \"{-exp (-1)..0} \\<union> {0..} = {-exp (-1::real)..}\"\n    using order.trans[of \"-exp (-1)::real\" 0] by auto\n  finally show ?thesis .\nqed\n\nlemma continuous_on_Lambert_W_alt [continuous_intros]:\n  assumes \"continuous_on A f\" \"\\<And>x. x \\<in> A \\<Longrightarrow> f x \\<ge> -exp (-1)\"\n  shows   \"continuous_on A (\\<lambda>x. Lambert_W (f x))\"\n  using continuous_on_compose2[OF continuous_on_Lambert_W assms(1)] assms by auto\n\nlemma continuous_on_Lambert_W' [continuous_intros]: \"continuous_on {-exp (-1)..<0} Lambert_W'\"\nproof -\n  have *: \"continuous_on {-exp (-1)..-b * exp (-b)} Lambert_W'\" if \"b \\<ge> 1\" for b\n  proof -\n    have \"continuous_on ((\\<lambda>x. x * exp x) ` {-b..-1}) Lambert_W'\"\n      by (intro continuous_on_inv ballI) (auto intro!: continuous_intros)\n    also have \"(\\<lambda>x. x * exp x) ` {-b..-1} = {-exp (-1)..-b * exp (-b)}\"\n      using bij_betw_exp_times_self_atLeastAtMost'[of \"-b\" \"-1\"] that\n      by (simp add: bij_betw_def)\n    finally show ?thesis .\n  qed\n\n  have \"continuous (at x) Lambert_W'\" if \"x > -exp (-1)\" \"x < 0\" for x\n  proof - \n    define b where \"b = Lambert_W x + 1\"\n    have \"eventually (\\<lambda>b. -b * exp (-b) > x) at_top\"\n      using that by real_asymp\n    hence \"eventually (\\<lambda>b. b \\<ge> 1 \\<and> -b * exp (-b) > x) at_top\"\n      by (intro eventually_conj eventually_ge_at_top)\n    then obtain b where b: \"b \\<ge> 1\" \"-b * exp (-b) > x\"\n      by (auto simp: eventually_at_top_linorder)\n\n    have \"continuous_on {-exp(-1)<..<-b * exp (-b)} Lambert_W'\"\n      by (rule continuous_on_subset[OF *[of b]]) (use \\<open>b \\<ge> 1\\<close> in auto)\n    moreover have \"x \\<in> {-exp(-1)<..<-b * exp (-b)}\"\n      using b that by auto\n    ultimately show \"continuous (at x) Lambert_W'\"\n      by (subst (asm) continuous_on_eq_continuous_at) auto\n  qed\n  hence **: \"continuous_on {-exp (-1)<..<0} Lambert_W'\"\n    by (intro continuous_at_imp_continuous_on) auto\n\n  show ?thesis\n    unfolding continuous_on_def\n  proof\n    fix x :: real assume x: \"x \\<in> {-exp(-1)..<0}\"\n    show \"(Lambert_W' \\<longlongrightarrow> Lambert_W' x) (at x within {-exp(-1)..<0})\"\n    proof (cases \"x = -exp(-1)\")\n      case False\n      hence \"isCont Lambert_W' x\"\n        using x ** by (auto simp: continuous_on_eq_continuous_at)\n      thus ?thesis\n        using continuous_at filterlim_within_subset by blast\n    next\n      case True\n      define a :: real where \"a = -2 * exp (-2)\"\n      have a: \"a > -exp (-1)\"\n        using exp_times_self_strict_antimono[of \"-1\" \"-2\"] by (auto simp: a_def)\n      from True have \"x \\<in> {-exp (-1)..<a}\"\n        using a by (auto simp: a_def)\n      have \"continuous_on {-exp (-1)..<a} Lambert_W'\"\n        unfolding a_def by (rule continuous_on_subset[OF *[of 2]]) auto\n      hence \"(Lambert_W' \\<longlongrightarrow> Lambert_W' x) (at x within {-exp (-1)..<a})\"\n        using \\<open>x \\<in> {-exp (-1)..<a}\\<close> by (auto simp: continuous_on_def)\n      also have \"at x within {-exp (-1)..<a} = at_right x\"\n        using a by (intro at_within_nhd[of _ \"{..<a}\"]) (auto simp: True)\n      also have \"\\<dots> = at x within {-exp (-1)..<0}\"\n        using a by (intro at_within_nhd[of _ \"{..<0}\"]) (auto simp: True)\n      finally show ?thesis .\n    qed\n  qed\nqed\n\nlemma continuous_on_Lambert_W'_alt [continuous_intros]:\n  assumes \"continuous_on A f\" \"\\<And>x. x \\<in> A \\<Longrightarrow> f x \\<in> {-exp (-1)..<0}\"\n  shows   \"continuous_on A (\\<lambda>x. Lambert_W' (f x))\"\n  using continuous_on_compose2[OF continuous_on_Lambert_W' assms(1)] assms\n  by (auto simp: subset_iff)\n\n\nlemma tendsto_Lambert_W_1:\n  assumes \"(f \\<longlongrightarrow> L) F\" \"eventually (\\<lambda>x. f x \\<ge> -exp (-1)) F\"\n  shows   \"((\\<lambda>x. Lambert_W (f x)) \\<longlongrightarrow> Lambert_W L) F\"\nproof (cases \"F = bot\")\n  case [simp]: False\n  from tendsto_lowerbound[OF assms] have \"L \\<ge> -exp (-1)\" by simp\n  thus ?thesis\n    using continuous_on_tendsto_compose[OF continuous_on_Lambert_W assms(1)] assms(2) by simp\nqed auto\n\n\n\nlemma tendsto_Lambert_W [tendsto_intros]:\n  assumes \"(f \\<longlongrightarrow> L) F\" \"eventually (\\<lambda>x. f x \\<ge> -exp (-1)) F \\<or> L > -exp (-1)\"\n  shows   \"((\\<lambda>x. Lambert_W (f x)) \\<longlongrightarrow> Lambert_W L) F\"\n  using assms(2)\nproof\n  assume \"L > -exp (-1)\"\n  from order_tendstoD(1)[OF assms(1) this] assms(1) show ?thesis\n    by (intro tendsto_Lambert_W_1) (auto elim: eventually_mono)  \nqed (use tendsto_Lambert_W_1[OF assms(1)] in auto)\n\nlemma tendsto_Lambert_W'_1:\n  assumes \"(f \\<longlongrightarrow> L) F\" \"eventually (\\<lambda>x. f x \\<ge> -exp (-1)) F\" \"L < 0\"\n  shows   \"((\\<lambda>x. Lambert_W' (f x)) \\<longlongrightarrow> Lambert_W' L) F\"\nproof (cases \"F = bot\")\n  case [simp]: False\n  from tendsto_lowerbound[OF assms(1,2)] have L_ge: \"L \\<ge> -exp (-1)\" by simp\n  from order_tendstoD(2)[OF assms(1,3)] have ev: \"eventually (\\<lambda>x. f x < 0) F\"\n    by auto\n  with assms(2) have \"eventually (\\<lambda>x. f x \\<in> {-exp (-1)..<0}) F\"\n    by eventually_elim auto\n  thus ?thesis using L_ge assms(3)\n    by (intro continuous_on_tendsto_compose[OF continuous_on_Lambert_W' assms(1)]) auto\nqed auto\n\nlemma tendsto_Lambert_W'_2:\n  assumes \"(f \\<longlongrightarrow> L) F\" \"L > -exp (-1)\" \"L < 0\"\n  shows   \"((\\<lambda>x. Lambert_W' (f x)) \\<longlongrightarrow> Lambert_W' L) F\"\n  using order_tendstoD(1)[OF assms(1,2)] assms\n  by (intro tendsto_Lambert_W'_1) (auto elim: eventually_mono)\n\nlemma tendsto_Lambert_W' [tendsto_intros]:\n  assumes \"(f \\<longlongrightarrow> L) F\" \"eventually (\\<lambda>x. f x \\<ge> -exp (-1)) F \\<or> L > -exp (-1)\" \"L < 0\"\n  shows   \"((\\<lambda>x. Lambert_W' (f x)) \\<longlongrightarrow> Lambert_W' L) F\"\n  using assms(2)\nproof\n  assume \"L > -exp (-1)\"\n  from order_tendstoD(1)[OF assms(1) this] assms(1,3) show ?thesis\n    by (intro tendsto_Lambert_W'_1) (auto elim: eventually_mono)  \nqed (use tendsto_Lambert_W'_1[OF assms(1) _ assms(3)] in auto)\n\n\nlemma continuous_Lambert_W [continuous_intros]:\n  assumes \"continuous F f\" \"f (Lim F (\\<lambda>x. x)) > -exp (-1) \\<or> eventually (\\<lambda>x. f x \\<ge> -exp (-1)) F\"\n  shows   \"continuous F (\\<lambda>x. Lambert_W (f x))\"\n  using assms unfolding continuous_def by (intro tendsto_Lambert_W) auto\n\nlemma continuous_Lambert_W' [continuous_intros]:\n  assumes \"continuous F f\" \"f (Lim F (\\<lambda>x. x)) > -exp (-1) \\<or> eventually (\\<lambda>x. f x \\<ge> -exp (-1)) F\"\n          \"f (Lim F (\\<lambda>x. x)) < 0\"\n  shows   \"continuous F (\\<lambda>x. Lambert_W' (f x))\"\n  using assms unfolding continuous_def by (intro tendsto_Lambert_W') auto\n\n\nlemma has_field_derivative_Lambert_W [derivative_intros]:\n  assumes x: \"x > -exp (-1)\"\n  shows   \"(Lambert_W has_real_derivative inverse (x + exp (Lambert_W x))) (at x within A)\"\nproof -\n  write Lambert_W (\"W\")\n  from x have \"W x > W (-exp (-1))\"\n    by (subst Lambert_W_less_iff) auto\n  hence \"W x > -1\" by simp\n\n  note [derivative_intros] = DERIV_inverse_function[where g = Lambert_W]\n  have \"((\\<lambda>x. x * exp x) has_real_derivative (1 + W x) * exp (W x)) (at (W x))\"\n    by (auto intro!: derivative_eq_intros simp: algebra_simps)\n  hence \"(W has_real_derivative inverse ((1 + W x) * exp (W x))) (at x)\"\n    by (rule DERIV_inverse_function[where a = \"-exp (-1)\" and b = \"x + 1\"])\n       (use x \\<open>W x > -1\\<close> in \\<open>auto simp: Lambert_W_times_exp_self Lim_ident_at\n                                  intro!: continuous_intros\\<close>)\n  also have \"(1 + W x) * exp (W x) = x + exp (W x)\"\n    using x by (simp add: algebra_simps Lambert_W_times_exp_self)\n  finally show ?thesis by (rule has_field_derivative_at_within)\nqed\n\nlemma has_field_derivative_Lambert_W_gen [derivative_intros]:\n  assumes \"(f has_real_derivative f') (at x within A)\" \"f x > -exp (-1)\"\n  shows   \"((\\<lambda>x. Lambert_W (f x)) has_real_derivative\n             (f' / (f x + exp (Lambert_W (f x))))) (at x within A)\"\n  using DERIV_chain2[OF has_field_derivative_Lambert_W[OF assms(2)] assms(1)]\n  by (simp add: field_simps)\n\nlemma has_field_derivative_Lambert_W' [derivative_intros]:\n  assumes x: \"x \\<in> {-exp (-1)<..<0}\"\n  shows   \"(Lambert_W' has_real_derivative inverse (x + exp (Lambert_W' x))) (at x within A)\"\nproof -\n  write Lambert_W' (\"W\")\n  from x have \"W x < W (-exp (-1))\"\n    by (subst Lambert_W'_less_iff) auto\n  hence \"W x < -1\" by simp\n\n  note [derivative_intros] = DERIV_inverse_function[where g = Lambert_W]\n  have \"((\\<lambda>x. x * exp x) has_real_derivative (1 + W x) * exp (W x)) (at (W x))\"\n    by (auto intro!: derivative_eq_intros simp: algebra_simps)\n  hence \"(W has_real_derivative inverse ((1 + W x) * exp (W x))) (at x)\"\n    by (rule DERIV_inverse_function[where a = \"-exp (-1)\" and b = \"0\"])\n       (use x \\<open>W x < -1\\<close> in \\<open>auto simp: Lambert_W'_times_exp_self Lim_ident_at\n                                        intro!: continuous_intros\\<close>)\n  also have \"(1 + W x) * exp (W x) = x + exp (W x)\"\n    using x by (simp add: algebra_simps Lambert_W'_times_exp_self)\n  finally show ?thesis by (rule has_field_derivative_at_within)\nqed\n\nlemma has_field_derivative_Lambert_W'_gen [derivative_intros]:\n  assumes \"(f has_real_derivative f') (at x within A)\" \"f x \\<in> {-exp (-1)<..<0}\"\n  shows   \"((\\<lambda>x. Lambert_W' (f x)) has_real_derivative\n             (f' / (f x + exp (Lambert_W' (f x))))) (at x within A)\"\n  using DERIV_chain2[OF has_field_derivative_Lambert_W'[OF assms(2)] assms(1)]\n  by (simp add: field_simps)\n\n\nsubsection \\<open>Asymptotic expansion\\<close>\n\ntext \\<open>\n  Lastly, we prove some more detailed asymptotic expansions of $W$ and $W'$ at their\n  singularities. First, we show that:\n  \\begin{align*}\n    W(x) &= \\log x - \\log\\log x + o(\\log\\log x) &&\\text{for}\\ x\\to\\infty\\\\\n    W'(x) &= \\log (-x) - \\log (-\\log (-x)) + o(\\log (-\\log (-x))) &&\\text{for}\\ x\\to 0^{-}\n  \\end{align*}\n\\<close>\ntheorem Lambert_W_asymp_equiv_at_top:\n  \"(\\<lambda>x. Lambert_W x - ln x) \\<sim>[at_top] (\\<lambda>x. -ln (ln x))\"\nproof -\n  have \"(\\<lambda>x. Lambert_W x - ln x) \\<sim>[at_top] (\\<lambda>x. (-1) * ln (ln x))\"\n  proof (rule asymp_equiv_sandwich')\n    fix c' :: real assume c': \"c' \\<in> {-2<..<-1}\"\n    have \"eventually (\\<lambda>x. (ln x + c' * ln (ln x)) * exp (ln x + c' * ln (ln x)) \\<le> x) at_top\"\n         \"eventually (\\<lambda>x. ln x + c' * ln (ln x) \\<ge> -1) at_top\"\n      using c' by real_asymp+\n    thus \"eventually (\\<lambda>x. Lambert_W x - ln x \\<ge> c' * ln (ln x)) at_top\"\n    proof eventually_elim\n      case (elim x)\n      hence \"Lambert_W x \\<ge> ln x + c' * ln (ln x)\"\n        by (intro Lambert_W_geI)\n      thus ?case by simp\n    qed\n  next\n    fix c' :: real assume c': \"c' \\<in> {-1<..<0}\"\n    have \"eventually (\\<lambda>x. (ln x + c' * ln (ln x)) * exp (ln x + c' * ln (ln x)) \\<ge> x) at_top\"\n         \"eventually (\\<lambda>x. ln x + c' * ln (ln x) \\<ge> -1) at_top\"\n      using c' by real_asymp+\n    thus \"eventually (\\<lambda>x. Lambert_W x - ln x \\<le> c' * ln (ln x)) at_top\"\n      using eventually_ge_at_top[of \"-exp (-1)\"]\n    proof eventually_elim\n      case (elim x)\n      hence \"Lambert_W x \\<le> ln x + c' * ln (ln x)\"\n        by (intro Lambert_W_leI)\n      thus ?case by simp\n    qed\n  qed auto\n  thus ?thesis by simp\nqed\n\nlemma Lambert_W_asymp_equiv_at_top' [asymp_equiv_intros]:\n  \"Lambert_W \\<sim>[at_top] ln\"\nproof -\n  have \"(\\<lambda>x. Lambert_W x - ln x) \\<in> \\<Theta>(\\<lambda>x. -ln (ln x))\"\n    by (intro asymp_equiv_imp_bigtheta Lambert_W_asymp_equiv_at_top)\n  also have \"(\\<lambda>x::real. -ln (ln x)) \\<in> o(ln)\"\n    by real_asymp\n  finally show ?thesis by (simp add: asymp_equiv_altdef)\nqed\n\ntheorem Lambert_W'_asymp_equiv_at_left_0:\n  \"(\\<lambda>x. Lambert_W' x - ln (-x)) \\<sim>[at_left 0] (\\<lambda>x. -ln (-ln (-x)))\"\nproof -\n  have \"(\\<lambda>x. Lambert_W' x - ln (-x)) \\<sim>[at_left 0] (\\<lambda>x. (-1) * ln (-ln (-x)))\"\n  proof (rule asymp_equiv_sandwich')\n    fix c' :: real assume c': \"c' \\<in> {-2<..<-1}\"\n    have \"eventually (\\<lambda>x. x \\<le> (ln (-x) + c' * ln (-ln (-x))) * exp (ln (-x) + c' * ln (-ln (-x)))) (at_left 0)\"\n         \"eventually (\\<lambda>x::real. ln (-x) + c' * ln (-ln (-x)) \\<le> -1) (at_left 0)\"\n         \"eventually (\\<lambda>x::real. -exp (-1) \\<le> x) (at_left 0)\"\n      using c' by real_asymp+\n    thus \"eventually (\\<lambda>x. Lambert_W' x - ln (-x) \\<ge> c' * ln (-ln (-x))) (at_left 0)\"\n    proof eventually_elim\n      case (elim x)\n      hence \"Lambert_W' x \\<ge> ln (-x) + c' * ln (-ln (-x))\"\n        by (intro Lambert_W'_geI)\n      thus ?case by simp\n    qed\n  next\n    fix c' :: real assume c': \"c' \\<in> {-1<..<0}\"\n    have \"eventually (\\<lambda>x. x \\<ge> (ln (-x) + c' * ln (-ln (-x))) * exp (ln (-x) + c' * ln (-ln (-x)))) (at_left 0)\"\n      using c' by real_asymp\n    moreover have \"eventually (\\<lambda>x::real. x < 0) (at_left 0)\"\n      by (auto simp: eventually_at intro: exI[of _ 1])\n    ultimately show \"eventually (\\<lambda>x. Lambert_W' x - ln (-x) \\<le> c' * ln (-ln (-x))) (at_left 0)\"\n    proof eventually_elim\n      case (elim x)\n      hence \"Lambert_W' x \\<le> ln (-x) + c' * ln (-ln (-x))\"\n        by (intro Lambert_W'_leI)\n      thus ?case by simp\n    qed\n  qed auto\n  thus ?thesis by simp\nqed\n\nlemma Lambert_W'_asymp_equiv'_at_left_0 [asymp_equiv_intros]:\n  \"Lambert_W' \\<sim>[at_left 0] (\\<lambda>x. ln (-x))\"\nproof -\n  have \"(\\<lambda>x. Lambert_W' x - ln (-x)) \\<in> \\<Theta>[at_left 0](\\<lambda>x. -ln (-ln (-x)))\"\n    by (intro asymp_equiv_imp_bigtheta Lambert_W'_asymp_equiv_at_left_0)\n  also have \"(\\<lambda>x::real. -ln (-ln (-x))) \\<in> o[at_left 0](\\<lambda>x. ln (-x))\"\n    by real_asymp\n  finally show ?thesis by (simp add: asymp_equiv_altdef)\nqed\n\n\ntext \\<open>\n  Next, we look at the branching point $a := \\tfrac{1}{e}$. Here, the asymptotic behaviour\n  is as follows:\n  \\begin{align*}\n    W(x) &= -1 + \\sqrt{2e}(x - a)^{\\frac{1}{2}} - \\tfrac{2}{3}e(x-a) + o(x-a) &&\\text{for} x\\to a^+\\\\\n    W'(x) &= -1 - \\sqrt{2e}(x - a)^{\\frac{1}{2}} - \\tfrac{2}{3}e(x-a) + o(x-a) &&\\text{for} x\\to a^+\n  \\end{align*}\n\\<close>\nlemma sqrt_sqrt_mult:\n  assumes \"x \\<ge> (0 :: real)\"\n  shows   \"sqrt x * (sqrt x * y) = x * y\"\n  using assms by (subst mult.assoc [symmetric]) auto\n\ntheorem Lambert_W_asymp_equiv_at_right_minus_exp_minus1:\n  defines \"e \\<equiv> exp 1\"\n  defines \"a \\<equiv> -exp (-1)\"\n  defines \"C1 \\<equiv> sqrt (2 * exp 1)\"\n  defines \"f \\<equiv> (\\<lambda>x. -1 + C1 * sqrt (x - a))\"\n  shows   \"(\\<lambda>x. Lambert_W x - f x) \\<sim>[at_right a] (\\<lambda>x. -2/3 * e * (x - a))\"\nproof -\n  define C :: \"real \\<Rightarrow> real\" where \"C = (\\<lambda>c. sqrt (2/e)/3 * (2*e+3*c))\"\n  have asymp_equiv: \"(\\<lambda>x. (f x + c * (x - a)) * exp (f x + c * (x - a)) - x)\n                       \\<sim>[at_right a] (\\<lambda>x. C c * (x - a) powr (3/2))\" if \"c \\<noteq> -2/3 * e\" for c\n  proof -\n    from that have \"C c \\<noteq> 0\"\n      by (auto simp: C_def e_def)\n    have \"(\\<lambda>x. (f x + c * (x - a)) * exp (f x + c * (x - a)) - x - C c * (x - a) powr (3/2))\n            \\<in> o[at_right a](\\<lambda>x. (x - a) powr (3/2))\"\n      unfolding f_def a_def C_def C1_def e_def\n      by (real_asymp simp: field_simps real_sqrt_mult real_sqrt_divide sqrt_sqrt_mult\n                           exp_minus simp flip: sqrt_def)\n    thus ?thesis\n      using \\<open>C c \\<noteq> 0\\<close> by (intro smallo_imp_asymp_equiv) auto\n  qed\n      \n  show ?thesis\n  proof (rule asymp_equiv_sandwich')\n    fix c' :: real assume c': \"c' \\<in> {-e<..<-2/3*e}\"\n    hence neq: \"c' \\<noteq> -2/3 * e\" by auto\n    from c' have neg: \"C c' < 0\" unfolding C_def by (auto intro!: mult_pos_neg)\n    hence \"eventually (\\<lambda>x. C c' * (x - a) powr (3 / 2) < 0) (at_right a)\"\n      by real_asymp\n    hence \"eventually (\\<lambda>x. (f x + c' * (x - a)) * exp (f x + c' * (x - a)) - x < 0) (at_right a)\"\n      using asymp_equiv_eventually_neg_iff[OF asymp_equiv[OF neq]]\n      by eventually_elim (use neg in auto)\n    thus \"eventually (\\<lambda>x. Lambert_W x - f x \\<ge> c' * (x - a)) (at_right a)\"\n    proof eventually_elim\n      case (elim x)\n      hence \"Lambert_W x \\<ge> f x + c' * (x - a)\"\n        by (intro Lambert_W_geI) auto\n      thus ?case by simp\n    qed\n  next\n    fix c' :: real assume c': \"c' \\<in> {-2/3*e<..<0}\"\n    hence neq: \"c' \\<noteq> -2/3 * e\" by auto\n    from c' have pos: \"C c' > 0\" unfolding C_def by auto\n    hence \"eventually (\\<lambda>x. C c' * (x - a) powr (3 / 2) > 0) (at_right a)\"\n      by real_asymp\n    hence \"eventually (\\<lambda>x. (f x + c' * (x - a)) * exp (f x + c' * (x - a)) - x > 0) (at_right a)\"\n      using asymp_equiv_eventually_pos_iff[OF asymp_equiv[OF neq]]\n      by eventually_elim (use pos in auto)\n    moreover have \"eventually (\\<lambda>x. - 1 \\<le> f x + c' * (x - a)) (at_right a)\"\n                  \"eventually (\\<lambda>x. x > a) (at_right a)\"\n      unfolding a_def f_def C1_def c' by real_asymp+\n    ultimately show \"eventually (\\<lambda>x. Lambert_W x - f x \\<le> c' * (x - a)) (at_right a)\"\n    proof eventually_elim\n      case (elim x)\n      hence \"Lambert_W x \\<le> f x + c' * (x - a)\"\n        by (intro Lambert_W_leI) (auto simp: a_def)\n      thus ?case by simp\n    qed\n  qed (auto simp: e_def)\nqed\n\ntheorem Lambert_W'_asymp_equiv_at_right_minus_exp_minus1:\n  defines \"e \\<equiv> exp 1\"\n  defines \"a \\<equiv> -exp (-1)\"\n  defines \"C1 \\<equiv> sqrt (2 * exp 1)\"\n  defines \"f \\<equiv> (\\<lambda>x. -1 - C1 * sqrt (x - a))\"\n  shows   \"(\\<lambda>x. Lambert_W' x - f x) \\<sim>[at_right a] (\\<lambda>x. -2/3 * e * (x - a))\"\nproof -\n  define C :: \"real \\<Rightarrow> real\" where \"C = (\\<lambda>c. -sqrt (2/e)/3 * (2*e+3*c))\"\n\n  have asymp_equiv: \"(\\<lambda>x. (f x + c * (x - a)) * exp (f x + c * (x - a)) - x)\n                       \\<sim>[at_right a] (\\<lambda>x. C c * (x - a) powr (3/2))\" if \"c \\<noteq> -2/3 * e\" for c\n  proof -\n    from that have \"C c \\<noteq> 0\"\n      by (auto simp: C_def e_def)\n    have \"(\\<lambda>x. (f x + c * (x - a)) * exp (f x + c * (x - a)) - x - C c * (x - a) powr (3/2))\n            \\<in> o[at_right a](\\<lambda>x. (x - a) powr (3/2))\"\n      unfolding f_def a_def C_def C1_def e_def\n      by (real_asymp simp: field_simps real_sqrt_mult real_sqrt_divide sqrt_sqrt_mult\n                           exp_minus simp flip: sqrt_def)\n    thus ?thesis\n      using \\<open>C c \\<noteq> 0\\<close> by (intro smallo_imp_asymp_equiv) auto\n  qed\n      \n  show ?thesis\n  proof (rule asymp_equiv_sandwich')\n    fix c' :: real assume c': \"c' \\<in> {-e<..<-2/3*e}\"\n    hence neq: \"c' \\<noteq> -2/3 * e\" by auto\n    from c' have pos: \"C c' > 0\" unfolding C_def by (auto intro!: mult_pos_neg)\n    hence \"eventually (\\<lambda>x. C c' * (x - a) powr (3 / 2) > 0) (at_right a)\"\n      by real_asymp\n    hence \"eventually (\\<lambda>x. (f x + c' * (x - a)) * exp (f x + c' * (x - a)) - x > 0) (at_right a)\"\n      using asymp_equiv_eventually_pos_iff[OF asymp_equiv[OF neq]]\n      by eventually_elim (use pos in auto)\n    moreover have \"eventually (\\<lambda>x. x > a) (at_right a)\"\n                  \"eventually (\\<lambda>x. f x + c' * (x - a) \\<le> -1) (at_right a)\"\n      unfolding a_def f_def C1_def c' by real_asymp+\n    ultimately show \"eventually (\\<lambda>x. Lambert_W' x - f x \\<ge> c' * (x - a)) (at_right a)\"\n    proof eventually_elim\n      case (elim x)\n      hence \"Lambert_W' x \\<ge> f x + c' * (x - a)\"\n        by (intro Lambert_W'_geI) (auto simp: a_def)\n      thus ?case by simp\n    qed\n  next\n    fix c' :: real assume c': \"c' \\<in> {-2/3*e<..<0}\"\n    hence neq: \"c' \\<noteq> -2/3 * e\" by auto\n    from c' have neg: \"C c' < 0\" unfolding C_def by auto\n    hence \"eventually (\\<lambda>x. C c' * (x - a) powr (3 / 2) < 0) (at_right a)\"\n      by real_asymp\n    hence \"eventually (\\<lambda>x. (f x + c' * (x - a)) * exp (f x + c' * (x - a)) - x < 0) (at_right a)\"\n      using asymp_equiv_eventually_neg_iff[OF asymp_equiv[OF neq]]\n      by eventually_elim (use neg in auto)\n    moreover have \"eventually (\\<lambda>x. x < 0) (at_right a)\"\n      unfolding a_def by real_asymp\n    ultimately show \"eventually (\\<lambda>x. Lambert_W' x - f x \\<le> c' * (x - a)) (at_right a)\"\n    proof eventually_elim\n      case (elim x)\n      hence \"Lambert_W' x \\<le> f x + c' * (x - a)\"\n        by (intro Lambert_W'_leI) auto\n      thus ?case by simp\n    qed\n  qed (auto simp: e_def)\nqed\n\n\ntext \\<open>\n  Lastly, just for fun, we derive a slightly more accurate expansion of $W_0(x)$ for $x\\to\\infty$:\n\\<close>\ntheorem Lambert_W_asymp_equiv_at_top'':\n  \"(\\<lambda>x. Lambert_W x - ln x + ln (ln x)) \\<sim>[at_top] (\\<lambda>x. ln (ln x) / ln x)\"\nproof -\n  have \"(\\<lambda>x. Lambert_W x - ln x + ln (ln x)) \\<sim>[at_top] (\\<lambda>x. 1 * (ln (ln x) / ln x))\"\n  proof (rule asymp_equiv_sandwich')\n    fix c' :: real assume c': \"c' \\<in> {0<..<1}\"\n    define a where \"a = (\\<lambda>x::real. ln x - ln (ln x) + c' * (ln (ln x) / ln x))\"\n    have \"eventually (\\<lambda>x. a x * exp (a x) \\<le> x) at_top\"\n      using c' unfolding a_def by real_asymp+\n    thus \"eventually (\\<lambda>x. Lambert_W x - ln x + ln (ln x) \\<ge> c' * (ln (ln x) / ln x)) at_top\"\n    proof eventually_elim\n      case (elim x)\n      hence \"Lambert_W x \\<ge> a x\"\n        by (intro Lambert_W_geI)\n      thus ?case by (simp add: a_def)\n    qed\n  next\n    fix c' :: real assume c': \"c' \\<in> {1<..<2}\"\n    define a where \"a = (\\<lambda>x::real. ln x - ln (ln x) + c' * (ln (ln x) / ln x))\"\n    have \"eventually (\\<lambda>x. a x * exp (a x) \\<ge> x) at_top\"\n         \"eventually (\\<lambda>x. a x \\<ge> -1) at_top\"\n      using c' unfolding a_def by real_asymp+\n    thus \"eventually (\\<lambda>x. Lambert_W x - ln x + ln (ln x) \\<le> c' * (ln (ln x) / ln x)) at_top\"\n      using eventually_ge_at_top[of \"-exp (-1)\"]\n    proof eventually_elim\n      case (elim x)\n      hence \"Lambert_W x \\<le> a x\"\n        by (intro Lambert_W_leI)\n      thus ?case by (simp add: a_def)\n    qed\n  qed auto\n  thus ?thesis 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/Lambert_W/Lambert_W.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.847967769904032, "lm_q2_score": 0.8596637487122112, "lm_q1q2_score": 0.7289671518628339}}
{"text": "text \\<open>The following proof follows the HOL-Light implementation by John Harrison at\n      https://github.com/jrh13/hol-light/blob/master/100/polyhedron.ml\\<close>\n\nsubsection \\<open>Interpret which \"side\" of a hyperplane a point is on.\\<close>\n\ndefault_sort \"real_inner\"\n\ntype_synonym 'v hyperplane = \"'v \\<times> real\"\ntype_synonym 'v arrangement = \"('v hyperplane) set\"\n\nfun hyperplane_side :: \"'v hyperplane \\<Rightarrow> 'v  \\<Rightarrow> real\" where\n  \"hyperplane_side (a, b) x = sgn (a \\<bullet> x - b)\"\n\nsubsection \\<open>Equivalence relation imposed by hyperplane arrangement.\\<close>\n\ndefinition hyperplane_equiv  :: \"'v arrangement \\<Rightarrow> 'v \\<Rightarrow> 'v \\<Rightarrow> bool\" where\n  \"hyperplane_equiv A x y \\<equiv> \\<forall>h\\<in>A. hyperplane_side h x = hyperplane_side h y\"\n\nlemma hyperplane_equiv_refl:\n  \"hyperplane_equiv A x x\"\n  by (smt hyperplane_equiv_def)\n\nlemma hyperplane_equiv_sym:\n  \"hyperplane_equiv A x y \\<equiv> hyperplane_equiv A y x\"\n  by (smt hyperplane_equiv_def)\n\nlemma hyperplane_equiv_trans:\n  \"hyperplane_equiv A x y \\<and> hyperplane_equiv A y z \\<Longrightarrow> hyperplane_equiv A x z\"\n  by (smt hyperplane_equiv_def)\n\nlemma hyperplane_equiv_union:\n  \"hyperplane_equiv (A\\<union>B) x y \\<equiv>\n   hyperplane_equiv A x y \\<and> hyperplane_equiv B x y\"\n  by (smt Un_iff hyperplane_equiv_def)\n\nsubsection \\<open>Cells of a hyperplane arrangement\\<close>\n\n\\<comment> \\<open>Harrison seems to define hyperplane_cell as a partially applied function,\n   and then immediately proves a lemma that shows it's a set. Maybe this is some\n   kind of magic thing in HOL/Light? I'll use the set definition directly and\n   hope for the best.\\<close>\n\ndefinition hyperplane_cell :: \"'v arrangement \\<Rightarrow> ('v set) \\<Rightarrow> bool\" where\n  \"hyperplane_cell A c \\<equiv> \\<exists>x. c = {y. hyperplane_equiv A x y}\"\n\n\\<^cancel>\\<open>lemma hyperplane_cell:   \\<comment> \\<open>Do I need this?\\<close>\n  \"hyperplane_cell A c \\<equiv> (\\<exists>x. c = {y. hyperplane_equiv A x y})\"\n  by (fact hyperplane_cell_def)\\<close>\n\nlemma not_hyperplane_cell_empty: \"\\<not> hyperplane_cell A {}\"\n  using hyperplane_cell_def hyperplane_equiv_refl by fastforce\n\nlemma nonempty_hyperplane_cell: \"hyperplane_cell A c \\<Longrightarrow> \\<not>(c = {})\"\n  using hyperplane_cell_def hyperplane_equiv_refl by fastforce\n\n\\<comment> \\<open>This is saying the union of all hyperplane cells in the arrangement is the entire\n   real^N space. I am somewhat impressed that sledgehammer managed to prove this, once I\n   broke it down into sub-cases.\\<close>\nlemma unions_hyperplane_cells: \"\\<Union> {c. hyperplane_cell A c} = UNIV\"\nproof\n  show \"\\<Union> {c. hyperplane_cell A c} \\<subseteq> UNIV\" by simp\nnext\n  show \"UNIV \\<subseteq> \\<Union> {c. hyperplane_cell A c}\"\n    by (metis (mono_tags, hide_lams) UnionI hyperplane_cell_def hyperplane_equiv_refl mem_Collect_eq subsetI)\nqed\n\nlemma disjoint_hyperplane_cells:\n  assumes \"hyperplane_cell A c1\" and \"hyperplane_cell A c2\" and \"\\<not>(c1=c2)\"\n  shows \"disjoint {c1, c2}\"\n  sorry\n\nlemma disjoint_hyperplane_cells_eq:\n  \"hyperplane_cell A c1 \\<and> hyperplane_cell A c2 \\<Longrightarrow> (disjoint {c1,c2} \\<equiv> \\<not>(c1=c2))\"\n  sorry\n\nlemma hyperplane_cell_empty: \"hyperplane_cell {} c \\<equiv> c = UNIV\"\n  by (simp add: hyperplane_cell_def hyperplane_equiv_def)\n\nlemma hyperplane_cell_sing_cases:\n  assumes \"hyperplane_cell {(a,b)} c\"\n  shows \"c = {x. a \\<bullet> x = b} \\<or>\n         c = {x. a \\<bullet> x < b} \\<or>\n         c = {x. a \\<bullet> x > b}\"\n  sorry\n\n\\<^cancel>\\<open>\nlet HYPERPLANE_CELL_SING = prove\n (`!a b c.\n        hyperplane_cell {(a,b)} c <=>\n        if a = vec 0 then c = (:real^N)\n        else c = {x | a dot x = b} \\/\n             c = {x | a dot x < b} \\/\n             c = {x | a dot x > b}`,\n\nlet HYPERPLANE_CELL_UNION = prove\n (`!A B c:real^N->bool.\n        hyperplane_cell (A UNION B) c <=>\n        ~(c = {}) /\\\n        ?c1 c2. hyperplane_cell A c1 /\\\n                hyperplane_cell B c2 /\\\n                c = c1 INTER c2`,\n\nlet FINITE_HYPERPLANE_CELLS = prove\n (`!A. FINITE A ==> FINITE {c:real^N->bool | hyperplane_cell A c}`,\n\nlet FINITE_RESTRICT_HYPERPLANE_CELLS = prove\n (`!P A. FINITE A ==> FINITE {c:real^N->bool | hyperplane_cell A c /\\ P c}`,\n\nlet FINITE_SET_OF_HYPERPLANE_CELLS = prove\n (`!A C. FINITE A /\\ (!c:real^N->bool. c IN C ==> hyperplane_cell A c)\n         ==> FINITE C`,\n\nlet PAIRWISE_DISJOINT_HYPERPLANE_CELLS = prove\n (`!A C. (!c. c IN C ==> hyperplane_cell A c)\n         ==> pairwise DISJOINT C`,\n\nlet HYPERPLANE_CELL_INTER_OPEN_AFFINE = prove\n (`!A c:real^N->bool.\n        FINITE A /\\ hyperplane_cell A c\n        ==> ?s t. open s /\\ affine t /\\ c = s INTER t`,\n\nlet HYPERPLANE_CELL_RELATIVELY_OPEN = prove\n (`!A c:real^N->bool.\n        FINITE A /\\ hyperplane_cell A c\n        ==> open_in (subtopology euclidean (affine hull c)) c`,\n\nlet HYPERPLANE_CELL_RELATIVE_INTERIOR = prove\n (`!A c:real^N->bool.\n        FINITE A /\\ hyperplane_cell A c\n        ==> relative_interior c = c`,\n\nlet HYPERPLANE_CELL_CONVEX = prove\n (`!A c:real^N->bool. hyperplane_cell A c ==> convex c`,\n\nlet HYPERPLANE_CELL_INTERS = prove\n (`!A C. (!c:real^N->bool. c IN C ==> hyperplane_cell A c) /\\\n         ~(C = {}) /\\ ~(INTERS C = {})\n         ==> hyperplane_cell A (INTERS C)`,\n\nlet HYPERPLANE_CELL_INTER = prove\n (`!A s t:real^N->bool.\n        hyperplane_cell A s /\\ hyperplane_cell A t /\\ ~(s INTER t = {})\n        ==> hyperplane_cell A (s INTER t)`,\n\\<close>\n\n\nsubsection \\<open>A cell complex is considered to be a union of such cells\\<close>\n\n\\<^cancel>\\<open>\nlet hyperplane_cellcomplex = new_definition\n `hyperplane_cellcomplex A s <=>\n        ?t. (!c. c IN t ==> hyperplane_cell A c) /\\\n            s = UNIONS t`;;\n\n\nlet HYPERPLANE_CELLCOMPLEX_EMPTY = prove\n (`!A:real^N#real->bool. hyperplane_cellcomplex A {}`,\n\nlet HYPERPLANE_CELL_CELLCOMPLEX = prove\n (`!A c:real^N->bool. hyperplane_cell A c ==> hyperplane_cellcomplex A c`,\n\nlet HYPERPLANE_CELLCOMPLEX_UNIONS = prove\n (`!A C. (!s:real^N->bool. s IN C ==> hyperplane_cellcomplex A s)\n         ==> hyperplane_cellcomplex A (UNIONS C)`\n\nlet HYPERPLANE_CELLCOMPLEX_UNION = prove\n (`!A s t.\n        hyperplane_cellcomplex A s /\\ hyperplane_cellcomplex A t\n        ==> hyperplane_cellcomplex A (s UNION t)`\n\nlet HYPERPLANE_CELLCOMPLEX_UNIV = prove\n (`!A. hyperplane_cellcomplex A (:real^N)`\n\nlet HYPERPLANE_CELLCOMPLEX_INTERS = prove\n (`!A C. (!s:real^N->bool. s IN C ==> hyperplane_cellcomplex A s)\n         ==> hyperplane_cellcomplex A (INTERS C)`,\n\nlet HYPERPLANE_CELLCOMPLEX_INTER = prove\n (`!A s t.\n        hyperplane_cellcomplex A s /\\ hyperplane_cellcomplex A t\n        ==> hyperplane_cellcomplex A (s INTER t)`\n\nlet HYPERPLANE_CELLCOMPLEX_COMPL = prove\n (`!A s. hyperplane_cellcomplex A s\n         ==> hyperplane_cellcomplex A ((:real^N) DIFF s)`,\n\nlet HYPERPLANE_CELLCOMPLEX_DIFF = prove\n (`!A s t.\n        hyperplane_cellcomplex A s /\\ hyperplane_cellcomplex A t\n        ==> hyperplane_cellcomplex A (s DIFF t)`,\n\nlet HYPERPLANE_CELLCOMPLEX_MONO = prove\n (`!A B s:real^N->bool.\n        hyperplane_cellcomplex A s /\\ A SUBSET B\n        ==> hyperplane_cellcomplex B s`,\n\nlet FINITE_HYPERPLANE_CELLCOMPLEXES = prove\n (`!A. FINITE A ==> FINITE {c:real^N->bool | hyperplane_cellcomplex A c}`,\n\nlet FINITE_RESTRICT_HYPERPLANE_CELLCOMPLEXES = prove\n (`!P A. FINITE A\n         ==> FINITE {c:real^N->bool | hyperplane_cellcomplex A c /\\ P c}`,\n\nlet FINITE_SET_OF_HYPERPLANE_CELLS = prove\n (`!A C. FINITE A /\\ (!c:real^N->bool. c IN C ==> hyperplane_cellcomplex A c)\n         ==> FINITE C`,\n\nlet CELL_SUBSET_CELLCOMPLEX = prove\n (`!A s c:real^N->bool.\n        hyperplane_cell A c /\\ hyperplane_cellcomplex A s\n        ==> (c SUBSET s <=> ~(DISJOINT c s))`,\n\\<close>\n\nsubsection \\<open>Euler Characteristic\\<close>\n\n\\<^cancel>\\<open>\nlet euler_characteristic = new_definition\n `euler_characteristic A (s:real^N->bool) =\n        sum {c | hyperplane_cell A c /\\ c SUBSET s}\n            (\\c. (-- &1) pow (num_of_int(aff_dim c)))`;;\n\nlet EULER_CHARACTERISTIC_EMPTY = prove\n (`euler_characteristic A {} = &0`,\n\nlet EULER_CHARACTERISTIC_CELL_UNIONS = prove\n (`!A C. (!c:real^N->bool. c IN C ==> hyperplane_cell A c)\n         ==> euler_characteristic A (UNIONS C) =\n             sum C (\\c. (-- &1) pow (num_of_int(aff_dim c)))`\n\nlet EULER_CHARACTERISTIC_CELL = prove\n (`!A c. hyperplane_cell A c\n         ==> euler_characteristic A c =  (-- &1) pow (num_of_int(aff_dim c))`,\n\nlet EULER_CHARACTERISTIC_CELLCOMPLEX_UNION = prove\n (`!A s t:real^N->bool.\n        FINITE A /\\\n        hyperplane_cellcomplex A s /\\\n        hyperplane_cellcomplex A t /\\\n        DISJOINT s t\n        ==> euler_characteristic A (s UNION t) =\n            euler_characteristic A s + euler_characteristic A t`,\n\nlet EULER_CHARACTERISTIC_CELLCOMPLEX_UNIONS = prove\n (`!A C. FINITE A /\\\n         (!c:real^N->bool. c IN C ==> hyperplane_cellcomplex A c) /\\\n         pairwise DISJOINT C\n         ==> euler_characteristic A (UNIONS C) =\n             sum C (\\c. euler_characteristic A c)`,\n\nlet EULER_CHARACTERISTIC = prove\n (`!A s:real^N->bool.\n        FINITE A\n        ==> euler_characteristic A s =\n            sum (0..dimindex(:N))\n                (\\d. (-- &1) pow d *\n                     &(CARD {c | hyperplane_cell A c /\\ c SUBSET s /\\\n                                 aff_dim c = &d}))`,\n\\<close>\n\nsubsection \\<open>Show that the characteristic is invariant w.r.t. hyperplane arrangement.\\<close>\n\n\\<^cancel>\\<open>\nlet HYPERPLANE_CELLS_DISTINCT_LEMMA = prove\n (`!a b. {x | a dot x = b} INTER {x | a dot x < b} = {} /\\\n         {x | a dot x = b} INTER {x | a dot x > b} = {} /\\\n         {x | a dot x < b} INTER {x | a dot x = b} = {} /\\\n         {x | a dot x < b} INTER {x | a dot x > b} = {} /\\\n         {x | a dot x > b} INTER {x | a dot x = b} = {} /\\\n         {x | a dot x > b} INTER {x | a dot x < b} = {}`,\n  REWRITE_TAC[EXTENSION; IN_INTER; IN_ELIM_THM; NOT_IN_EMPTY] THEN\n  REAL_ARITH_TAC);;\n\nlet EULER_CHARACTERSTIC_LEMMA = prove\n (`!A h s:real^N->bool.\n        FINITE A /\\ hyperplane_cellcomplex A s\n        ==> euler_characteristic (h INSERT A) s = euler_characteristic A s`,\n\n\nlet EULER_CHARACTERSTIC_INVARIANT = prove\n (`!A B h s:real^N->bool.\n        FINITE A /\\ FINITE B /\\\n        hyperplane_cellcomplex A s /\\ hyperplane_cellcomplex B s\n        ==> euler_characteristic A s = euler_characteristic B s`,\n  SUBGOAL_THEN\n   `!A s:real^N->bool.\n        FINITE A /\\ hyperplane_cellcomplex A s\n        ==> !B. FINITE B\n                ==> euler_characteristic (A UNION B) s =\n                    euler_characteristic A s`\n\nlet EULER_CHARACTERISTIC_INCLUSION_EXCLUSION = prove\n (`!A s:(real^N->bool)->bool.\n        FINITE A /\\ FINITE s /\\ (!k. k IN s ==> hyperplane_cellcomplex A k)\n        ==> euler_characteristic A (UNIONS s) =\n            sum {t | t SUBSET s /\\ ~(t = {})}\n                (\\t. (-- &1) pow (CARD t + 1) *\n                     euler_characteristic A (INTERS t))`,\n\\<close>\n\nsubsection \\<open>Euler-type relation for full-dimensional proper polyhedral cones.\\<close>\n\n\\<^cancel>\\<open>\n\nlet EULER_POLYHEDRAL_CONE = prove\n (`!s. polyhedron s /\\ conic s /\\ ~(interior s = {}) /\\ ~(s = (:real^N))\n       ==> sum (0..dimindex(:N))\n               (\\d. (-- &1) pow d *\n                    &(CARD {f | f face_of s /\\ aff_dim f = &d })) = &0`,\n\n\\<comment> \\<open> ! HOL/Light proof is gigantic...\\<close>\\<close>\n\n\n\n\nsubsection \\<open>Euler-Poincare relation for special (n-1)-dimensional polytope.\\<close>\n\n\\<^cancel>\\<open>let EULER_POINCARE_LEMMA = prove\n (`!p:real^N->bool.\n        2 <= dimindex(:N) /\\ polytope p /\\ affine hull p = {x | x$1 = &1}\n        ==> sum (0..dimindex(:N)-1)\n               (\\d. (-- &1) pow d *\n                    &(CARD {f | f face_of p /\\ aff_dim f = &d })) = &1`,\n\\<comment> \\<open>another gigantic proof\\<close>\n\nlet EULER_POINCARE_SPECIAL = prove\n (`!p:real^N->bool.\n        2 <= dimindex(:N) /\\ polytope p /\\ affine hull p = {x | x$1 = &0}\n        ==> sum (0..dimindex(:N)-1)\n               (\\d. (-- &1) pow d *\n                    &(CARD {f | f face_of p /\\ aff_dim f = &d })) = &1`,\n\\<close>\n\n\nlemma euler_poincare_lemma:\n  assumes \"polytope p\" and \"aff_dim p \\<le> 2\"\n      and \"affine hull p = {x. x$1 =1 }\"\n  shows \"euler_char p = 1\"\n  sorry\n\nlemma euser_poincare_special:\n  assumes \"polytope p\" and \"aff_dim p \\<le> 2\"\n     and \"affine hull p = {x. x$1 = 0}\"\n  shows \"euler_char p = 1\"\n  sorry\n\n\n\nsection \\<open>Euler characteristic\\<close>\n", "meta": {"author": "tangentstorm", "repo": "tangentlabs", "sha": "49d7a335221e1ae67e8de0203a3f056bc4ab1d00", "save_path": "github-repos/isabelle/tangentstorm-tangentlabs", "path": "github-repos/isabelle/tangentstorm-tangentlabs/tangentlabs-49d7a335221e1ae67e8de0203a3f056bc4ab1d00/isar/hol-light-polyhedron.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8479677622198946, "lm_q2_score": 0.8596637541053281, "lm_q1q2_score": 0.7289671498302488}}
{"text": "(* Author: Tobias Nipkow *)\n\nsection {* Lists Sorted wrt $<$ *}\n\ntheory Sorted_Less\nimports Less_False\nbegin\n\nhide_const sorted\n\ntext \\<open>Is a list sorted without duplicates, i.e., wrt @{text\"<\"}?\nCould go into theory List under a name like @{term sorted_less}.\\<close>\n\nfun sorted :: \"'a::linorder list \\<Rightarrow> bool\" where\n\"sorted [] = True\" |\n\"sorted [x] = True\" |\n\"sorted (x#y#zs) = (x < y \\<and> sorted(y#zs))\"\n\nlemma sorted_Cons_iff:\n  \"sorted(x # xs) = (sorted xs \\<and> (\\<forall>y \\<in> set xs. x < y))\"\nby(induction xs rule: sorted.induct) auto\n\nlemma sorted_snoc_iff:\n  \"sorted(xs @ [x]) = (sorted xs \\<and> (\\<forall>y \\<in> set xs. y < x))\"\nby(induction xs rule: sorted.induct) auto\n\nlemma sorted_cons: \"sorted (x#xs) \\<Longrightarrow> sorted xs\"\nby(simp add: sorted_Cons_iff)\n\nlemma sorted_cons': \"ASSUMPTION (sorted (x#xs)) \\<Longrightarrow> sorted xs\"\nby(rule ASSUMPTION_D [THEN sorted_cons])\n\nlemma sorted_snoc: \"sorted (xs @ [y]) \\<Longrightarrow> sorted xs\"\nby(simp add: sorted_snoc_iff)\n\nlemma sorted_snoc': \"ASSUMPTION (sorted (xs @ [y])) \\<Longrightarrow> sorted xs\"\nby(rule ASSUMPTION_D [THEN sorted_snoc])\n\nlemma sorted_mid_iff:\n  \"sorted(xs @ y # ys) = (sorted(xs @ [y]) \\<and> sorted(y # ys))\"\nby(induction xs rule: sorted.induct) auto\n\nlemma sorted_mid_iff2:\n  \"sorted(x # xs @ y # ys) =\n  (sorted(x # xs) \\<and> x < y \\<and> sorted(xs @ [y]) \\<and> sorted(y # ys))\"\nby(induction xs rule: sorted.induct) auto\n\nlemma sorted_mid_iff': \"NO_MATCH [] ys \\<Longrightarrow>\n  sorted(xs @ y # ys) = (sorted(xs @ [y]) \\<and> sorted(y # ys))\"\nby(rule sorted_mid_iff)\n\nlemmas sorted_lems = sorted_mid_iff' sorted_mid_iff2 sorted_cons' sorted_snoc'\n\ntext\\<open>Splay trees need two additional @{const sorted} lemmas:\\<close>\n\nlemma sorted_snoc_le:\n  \"ASSUMPTION(sorted(xs @ [x])) \\<Longrightarrow> x \\<le> y \\<Longrightarrow> sorted (xs @ [y])\"\nby (auto simp add: Sorted_Less.sorted_snoc_iff ASSUMPTION_def)\n\nlemma sorted_Cons_le:\n  \"ASSUMPTION(sorted(x # xs)) \\<Longrightarrow> y \\<le> x \\<Longrightarrow> sorted (y # xs)\"\nby (auto simp add: Sorted_Less.sorted_Cons_iff ASSUMPTION_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/Sorted_Less.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8596637469145054, "lm_q2_score": 0.847967764140929, "lm_q1q2_score": 0.7289671453841066}}
{"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 @{text \"equiv < partial_equiv\"} and a type constructor\n  @{text \"'a quot\"} 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 @{text partial_equiv} models partial equivalence\n  relations (PERs) using the polymorphic @{text \"\\<sim> :: 'a \\<Rightarrow> 'a \\<Rightarrow>\n  bool\"} 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 @{text \\<sim>} 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.\\ @{text \"\\<sim>\n  :: 'a \\<Rightarrow> 'a \\<Rightarrow> bool\"} 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 @{text \"'a quot\"} consists of all\n  \\emph{equivalence classes} over elements of the base type @{typ 'a}.\n\\<close>\n\ndefinition \"quot = {{x. a \\<sim> x}| a::'a::partial_equiv. True}\"\n\ntypedef '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": "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/PER.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637433190939, "lm_q2_score": 0.8479677526147223, "lm_q1q2_score": 0.7289671324266516}}
{"text": "section {* Unrestriction *}\n\ntheory utp_unrest\n  imports utp_expr\nbegin\n\ntext {* Unrestriction is an encoding of semantic freshness, that allows us to reason about the\n        presence of variables in predicates without being concerned with abstract syntax trees.\n        An expression $p$ is unrestricted by variable $x$, written $x \\mathop{\\sharp} p$, if\n        altering the value of $x$ has no effect on the valuation of $p$. This is a sufficient\n        notion to prove many laws that would ordinarily rely on an \\emph{fv} function. *}\n\nconsts\n  unrest :: \"'a \\<Rightarrow> 'b \\<Rightarrow> bool\"\n\nsyntax\n  \"_unrest\" :: \"salpha \\<Rightarrow> logic \\<Rightarrow> logic \\<Rightarrow> logic\" (infix \"\\<sharp>\" 20)\n\ntranslations\n  \"_unrest x p\" == \"CONST unrest x p\"\n\nnamed_theorems unrest\n\nmethod unrest_tac = (simp add: unrest)?\n\nlift_definition unrest_upred :: \"('a, '\\<alpha>) uvar \\<Rightarrow> ('b, '\\<alpha>) uexpr \\<Rightarrow> bool\"\nis \"\\<lambda> x e. \\<forall> b v. e (put\\<^bsub>x\\<^esub> b v) = e b\" .\n\nadhoc_overloading\n  unrest unrest_upred\n\nlemma unrest_var_comp [unrest]:\n  \"\\<lbrakk> x \\<sharp> P; y \\<sharp> P \\<rbrakk> \\<Longrightarrow> x;y \\<sharp> P\"\n  by (transfer, simp add: lens_defs)\n\nlemma unrest_lit [unrest]: \"x \\<sharp> \\<guillemotleft>v\\<guillemotright>\"\n  by (transfer, simp)\n\ntext {* The following law demonstrates why we need variable independence: a variable\n        expression is unrestricted by another variable only when the two variables are independent. *}\n\nlemma unrest_var [unrest]: \"\\<lbrakk> vwb_lens x; x \\<bowtie> y \\<rbrakk> \\<Longrightarrow> y \\<sharp> var x\"\n  by (transfer, auto)\n\nlemma unrest_iuvar [unrest]: \"\\<lbrakk> vwb_lens x; x \\<bowtie> y \\<rbrakk> \\<Longrightarrow> $y \\<sharp> $x\"\n  by (metis in_var_indep in_var_uvar unrest_var)\n\nlemma unrest_ouvar [unrest]: \"\\<lbrakk> vwb_lens x; x \\<bowtie> y \\<rbrakk> \\<Longrightarrow> $y\\<acute> \\<sharp> $x\\<acute>\"\n  by (metis out_var_indep out_var_uvar unrest_var)\n\nlemma unrest_iuvar_ouvar [unrest]:\n  fixes x :: \"('a, '\\<alpha>) uvar\"\n  assumes \"vwb_lens y\"\n  shows \"$x \\<sharp> $y\\<acute>\"\n  by (metis prod.collapse unrest_upred.rep_eq var.rep_eq var_lookup_out var_update_in)\n\nlemma unrest_ouvar_iuvar [unrest]:\n  fixes x :: \"('a, '\\<alpha>) uvar\"\n  assumes \"vwb_lens y\"\n  shows \"$x\\<acute> \\<sharp> $y\"\n  by (metis prod.collapse unrest_upred.rep_eq var.rep_eq var_lookup_in var_update_out)\n\nlemma unrest_uop [unrest]: \"x \\<sharp> e \\<Longrightarrow> x \\<sharp> uop f e\"\n  by (transfer, simp)\n\nlemma unrest_bop [unrest]: \"\\<lbrakk> x \\<sharp> u; x \\<sharp> v \\<rbrakk> \\<Longrightarrow> x \\<sharp> bop f u v\"\n  by (transfer, simp)\n\nlemma unrest_trop [unrest]: \"\\<lbrakk> x \\<sharp> u; x \\<sharp> v; x \\<sharp> w \\<rbrakk> \\<Longrightarrow> x \\<sharp> trop f u v w\"\n  by (transfer, simp)\n\nlemma unrest_qtop [unrest]: \"\\<lbrakk> x \\<sharp> u; x \\<sharp> v; x \\<sharp> w; x \\<sharp> y \\<rbrakk> \\<Longrightarrow> x \\<sharp> qtop f u v w y\"\n  by (transfer, simp)\n\nlemma unrest_eq [unrest]: \"\\<lbrakk> x \\<sharp> u; x \\<sharp> v \\<rbrakk> \\<Longrightarrow> x \\<sharp> u =\\<^sub>u v\"\n  by (simp add: eq_upred_def, transfer, simp)\n\nlemma unrest_zero [unrest]: \"x \\<sharp> 0\"\n  by (simp add: unrest_lit zero_uexpr_def)\n\nlemma unrest_one [unrest]: \"x \\<sharp> 1\"\n  by (simp add: one_uexpr_def unrest_lit)\n\nlemma unrest_numeral [unrest]: \"x \\<sharp> (numeral n)\"\n  by (simp add: numeral_uexpr_simp unrest_lit)\n\nlemma unrest_sgn [unrest]: \"x \\<sharp> u \\<Longrightarrow> x \\<sharp> sgn u\"\n  by (simp add: sgn_uexpr_def unrest_uop)\n\nlemma unrest_abs [unrest]: \"x \\<sharp> u \\<Longrightarrow> x \\<sharp> abs u\"\n  by (simp add: abs_uexpr_def unrest_uop)\n\nlemma unrest_plus [unrest]: \"\\<lbrakk> x \\<sharp> u; x \\<sharp> v \\<rbrakk> \\<Longrightarrow> x \\<sharp> u + v\"\n  by (simp add: plus_uexpr_def unrest)\n\nlemma unrest_uminus [unrest]: \"x \\<sharp> u \\<Longrightarrow> x \\<sharp> - u\"\n  by (simp add: uminus_uexpr_def unrest)\n\nlemma unrest_minus [unrest]: \"\\<lbrakk> x \\<sharp> u; x \\<sharp> v \\<rbrakk> \\<Longrightarrow> x \\<sharp> u - v\"\n  by (simp add: minus_uexpr_def unrest)\n\nlemma unrest_times [unrest]: \"\\<lbrakk> x \\<sharp> u; x \\<sharp> v \\<rbrakk> \\<Longrightarrow> x \\<sharp> u * v\"\n  by (simp add: times_uexpr_def unrest)\n\nlemma unrest_divide [unrest]: \"\\<lbrakk> x \\<sharp> u; x \\<sharp> v \\<rbrakk> \\<Longrightarrow> x \\<sharp> u / v\"\n  by (simp add: divide_uexpr_def unrest)\n\nlemma unrest_ulambda [unrest]:\n  \"\\<lbrakk> \\<And> x. v \\<sharp> F x \\<rbrakk> \\<Longrightarrow> v \\<sharp> (\\<lambda> x \\<bullet> F x)\"\n  by (transfer, simp)\nend", "meta": {"author": "git-vt", "repo": "orca", "sha": "92bda0f9cfe5cc680b9c405fc38f07a960087a36", "save_path": "github-repos/isabelle/git-vt-orca", "path": "github-repos/isabelle/git-vt-orca/orca-92bda0f9cfe5cc680b9c405fc38f07a960087a36/Archive/Programming-Languages-Semantics/WP11-C-semantics/src/IMP-Lenses/utp/utp_unrest.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637433190938, "lm_q2_score": 0.8479677526147222, "lm_q1q2_score": 0.7289671324266513}}
{"text": "section \"Semantics and type soundness for System F\"\n\ntheory SystemF\n  imports Main \"HOL-Library.FSet\" \nbegin\n\nsubsection \"Syntax and values\"\n  \ntype_synonym name = nat\n\ndatatype ty = TVar nat | TNat | Fun ty ty (infix \"\\<rightarrow>\" 60) | Forall ty \n\ndatatype exp = EVar name | ENat nat | ELam ty exp | EApp exp exp\n  | EAbs exp  | EInst exp ty | EFix ty exp \n\ndatatype val = VNat nat | Fun \"(val \\<times> val) fset\" | Abs \"val option\" | Wrong\n\nfun val_le :: \"val \\<Rightarrow> val \\<Rightarrow> bool\" (infix \"\\<sqsubseteq>\" 52) where\n  \"(VNat n) \\<sqsubseteq> (VNat n') = (n = n')\" |\n  \"(Fun f) \\<sqsubseteq> (Fun f') = (fset f \\<subseteq> fset f')\" |\n  \"(Abs None) \\<sqsubseteq> (Abs None) = True\" |\n  \"Abs (Some v) \\<sqsubseteq> Abs (Some v') = v \\<sqsubseteq> v'\" |\n  \"Wrong \\<sqsubseteq> Wrong = True\" |\n  \"(v::val) \\<sqsubseteq> v' = False\"  \n\nsubsection \"Set monad\"\n\ndefinition set_bind :: \"'a set \\<Rightarrow> ('a \\<Rightarrow> 'b set) \\<Rightarrow> 'b set\" where\n  \"set_bind m f \\<equiv> { v. \\<exists> v'. v' \\<in> m \\<and> v \\<in> f v' }\"\ndeclare set_bind_def[simp]\n\nsyntax \"_set_bind\" :: \"[pttrns,'a set,'b] \\<Rightarrow> 'c\" (\"(_ \\<leftarrow> _;//_)\" 0)\ntranslations \"P \\<leftarrow> E; F\" \\<rightleftharpoons> \"CONST set_bind E (\\<lambda>P. F)\"\n\ndefinition errset_bind :: \"val set \\<Rightarrow> (val \\<Rightarrow> val set) \\<Rightarrow> val set\" where\n  \"errset_bind m f \\<equiv> { v. \\<exists> v'. v' \\<in> m \\<and> v' \\<noteq> Wrong \\<and> v \\<in> f v' } \\<union> {v. v = Wrong \\<and> Wrong \\<in> m }\"\ndeclare errset_bind_def[simp]\n\nsyntax \"_errset_bind\" :: \"[pttrns,val set,val] \\<Rightarrow> 'c\" (\"(_ := _;//_)\" 0)\ntranslations \"P := E; F\" \\<rightleftharpoons> \"CONST errset_bind E (\\<lambda>P. F)\"\n\ndefinition return :: \"val \\<Rightarrow> val set\" where\n  \"return v \\<equiv> {v'. v' \\<sqsubseteq> v }\"\ndeclare return_def[simp]\n\nsubsection \"Denotational semantics\"\n\ntype_synonym tyenv = \"(val set) list\" \ntype_synonym env = \"val list\"\n\ninductive iterate :: \"(env \\<Rightarrow> val set) \\<Rightarrow> env \\<Rightarrow> val \\<Rightarrow> bool\" where\n  iterate_none[intro!]: \"iterate Ee \\<rho> (Fun {||})\" |\n  iterate_again[intro!]: \"\\<lbrakk> iterate Ee \\<rho> f; f' \\<in> Ee (f#\\<rho>) \\<rbrakk> \\<Longrightarrow> iterate Ee \\<rho> f'\"\n\nabbreviation apply_fun :: \"val set \\<Rightarrow> val set \\<Rightarrow> val set\" where\n  \"apply_fun V1 V2 \\<equiv> (v1 := V1; v2 := V2;\n                       case v1 of Fun f \\<Rightarrow> \n                          (v2',v3') \\<leftarrow> fset f;\n                          if v2' \\<sqsubseteq> v2 then return v3' else {}\n                       | _ \\<Rightarrow> return Wrong)\"  \n\nfun E :: \"exp \\<Rightarrow> env \\<Rightarrow> val set\" where\n  Enat: \"E (ENat n) \\<rho> = return (VNat n)\" |\n  Evar: \"E (EVar n) \\<rho> = return (\\<rho>!n)\" |\n  Elam: \"E (ELam \\<tau> e) \\<rho> = {v. \\<exists> f. v = Fun f \\<and> (\\<forall> v1 v2'. (v1,v2') \\<in> fset f \\<longrightarrow>\n      (\\<exists> v2. v2 \\<in> E e (v1#\\<rho>) \\<and> v2' \\<sqsubseteq> v2)) }\" |\n  Eapp: \"E (EApp e1 e2) \\<rho> = apply_fun (E e1 \\<rho>) (E e2 \\<rho>)\" |\n  Efix: \"E (EFix \\<tau> e) \\<rho> = { v. iterate (E e) \\<rho> v }\" | \n  Eabs: \"E (EAbs e) \\<rho> = {v. (\\<exists> v'. v = Abs (Some v') \\<and> v' \\<in> E e \\<rho>) \n                               \\<or> (v = Abs None \\<and> E e \\<rho> = {}) }\" | \n  Einst: \"E (EInst e \\<tau>) \\<rho> = \n       (v := E e \\<rho>;\n        case v of\n          Abs None \\<Rightarrow> {}\n        | Abs (Some v') \\<Rightarrow> return v'\n        | _ \\<Rightarrow> return Wrong)\"\n  \nsubsection \"Types: substitution and semantics\"\n  \nfun shift :: \"nat \\<Rightarrow> nat \\<Rightarrow> ty \\<Rightarrow> ty\" where\n  \"shift k c TNat = TNat\" |\n  \"shift k c (TVar n) = (if c \\<le> n then TVar (n + k) else TVar n)\" |\n  \"shift k c (\\<sigma> \\<rightarrow> \\<sigma>') = (shift k c \\<sigma>) \\<rightarrow> (shift k c \\<sigma>')\" |\n  \"shift k c (Forall \\<sigma>) = Forall (shift k (Suc c) \\<sigma>)\"\n\nfun subst :: \"nat \\<Rightarrow> ty \\<Rightarrow> ty \\<Rightarrow> ty\" where\n  \"subst k \\<tau> TNat = TNat\" |\n  \"subst k \\<tau> (TVar n) = (if k = n then \\<tau>\n                         else if k < n then TVar (n - 1) \n                         else TVar n)\" |\n  \"subst k \\<tau> (\\<sigma> \\<rightarrow> \\<sigma>') = (subst k \\<tau> \\<sigma>) \\<rightarrow> (subst k \\<tau> \\<sigma>')\" |\n  \"subst k \\<tau> (Forall \\<sigma>) = Forall (subst (Suc k) (shift (Suc 0) 0 \\<tau>) \\<sigma>)\"\n\nfun T :: \"ty \\<Rightarrow> tyenv \\<Rightarrow> val set\" where\n Tnat: \"T TNat \\<rho> = {v. \\<exists> n. v = VNat n }\" |\n Tvar: \"T (TVar n) \\<rho> = (if n < length \\<rho> then\n                         {v. \\<exists> v'. v'\\<in>\\<rho>!n \\<and> v \\<sqsubseteq> v' \\<and> v \\<noteq> Wrong}\n                        else {})\" |\n Tfun: \"T (\\<sigma> \\<rightarrow> \\<tau>) \\<rho> = {v. \\<exists> f. v = Fun f \\<and> \n                        (\\<forall> v1 v2'.(v1,v2')\\<in>fset f \\<longrightarrow>\n                          v1\\<in>T \\<sigma> \\<rho>\\<longrightarrow>(\\<exists> v2. v2 \\<in> T \\<tau> \\<rho> \\<and> v2' \\<sqsubseteq> v2))}\" |\n Tall: \"T (Forall \\<tau>) \\<rho> = {v. (\\<exists>v'. v = Abs (Some v') \\<and> (\\<forall> V. v' \\<in> T \\<tau> (V#\\<rho>)))\n                           \\<or> v = Abs None }\"\n\nsubsection \"Type system\"\n  \ntype_synonym tyctx = \"(ty \\<times> nat) list \\<times> nat\"\n\ndefinition wf_tyvar :: \"tyctx \\<Rightarrow> nat \\<Rightarrow> bool\" where\n  \"wf_tyvar \\<Gamma> n \\<equiv> n < snd \\<Gamma>\"\ndefinition push_ty :: \"ty \\<Rightarrow> tyctx \\<Rightarrow> tyctx\" where\n  \"push_ty \\<tau> \\<Gamma> \\<equiv> ((\\<tau>,snd \\<Gamma>) # fst \\<Gamma>, snd \\<Gamma>)\"\ndefinition push_tyvar :: \"tyctx \\<Rightarrow> tyctx\" where\n  \"push_tyvar \\<Gamma> \\<equiv> (fst \\<Gamma>, Suc (snd \\<Gamma>))\"\n\ndefinition good_ctx :: \"tyctx \\<Rightarrow> bool\" where\n  \"good_ctx \\<Gamma> \\<equiv> \\<forall> n. n < length (fst \\<Gamma>) \\<longrightarrow> snd ((fst \\<Gamma>) ! n) \\<le> snd \\<Gamma>\"\n\ndefinition lookup :: \"tyctx \\<Rightarrow> nat \\<Rightarrow> ty option\" where\n  \"lookup \\<Gamma> n \\<equiv> (if n < length (fst \\<Gamma>) then\n                    let k = snd \\<Gamma> - snd ((fst \\<Gamma>)!n) in\n                    Some (shift k 0 (fst ((fst \\<Gamma>)!n)))\n                  else None)\"\n\ninductive well_typed :: \"tyctx \\<Rightarrow> exp \\<Rightarrow> ty \\<Rightarrow> bool\" (\"_ \\<turnstile> _ : _\" [55,55,55] 54) where\n  wtnat[intro!]: \"\\<Gamma> \\<turnstile> ENat n : TNat\" |\n  wtvar[intro!]: \"\\<lbrakk> lookup \\<Gamma> n = Some \\<tau> \\<rbrakk> \\<Longrightarrow> \\<Gamma> \\<turnstile> EVar n : \\<tau>\" |\n  wtapp[intro!]: \"\\<lbrakk> \\<Gamma> \\<turnstile> e : \\<sigma> \\<rightarrow> \\<tau>; \\<Gamma> \\<turnstile> e' : \\<sigma> \\<rbrakk> \\<Longrightarrow> \\<Gamma> \\<turnstile> EApp e e' : \\<tau>\" |\n  wtlam[intro!]: \"\\<lbrakk> push_ty \\<sigma> \\<Gamma> \\<turnstile> e : \\<tau> \\<rbrakk> \\<Longrightarrow> \\<Gamma> \\<turnstile> ELam \\<sigma> e : \\<sigma> \\<rightarrow> \\<tau>\" |\n  wtfix[intro!]: \"\\<lbrakk> push_ty (\\<sigma>\\<rightarrow>\\<tau>) \\<Gamma> \\<turnstile> e : \\<sigma>\\<rightarrow>\\<tau> \\<rbrakk> \\<Longrightarrow> \\<Gamma> \\<turnstile> EFix (\\<sigma> \\<rightarrow> \\<tau>) e : \\<sigma> \\<rightarrow> \\<tau>\" |\n  wtabs[intro!]: \"\\<lbrakk> push_tyvar \\<Gamma> \\<turnstile> e : \\<tau> \\<rbrakk> \\<Longrightarrow> \\<Gamma> \\<turnstile> EAbs e : Forall \\<tau>\" |\n  wtinst[intro!]: \"\\<lbrakk> \\<Gamma> \\<turnstile> e : Forall \\<tau> \\<rbrakk> \\<Longrightarrow> \\<Gamma> \\<turnstile> EInst e \\<sigma> : (subst 0 \\<sigma> \\<tau>)\"\n\ninductive wfenv :: \"env \\<Rightarrow> tyenv \\<Rightarrow> tyctx \\<Rightarrow> bool\" (\"\\<turnstile> _,_ : _\" [55,55,55] 54) where\n  wfnil[intro!]: \"\\<turnstile> [],[] : ([],0)\" |\n  wfvbind[intro!]: \"\\<lbrakk> \\<turnstile> \\<rho>,\\<eta> : \\<Gamma>; v \\<in> T \\<tau> \\<eta> \\<rbrakk> \\<Longrightarrow> \\<turnstile>  (v#\\<rho>),\\<eta> : push_ty \\<tau> \\<Gamma>\" |\n  wftbind[intro!]: \"\\<lbrakk> \\<turnstile> \\<rho>,\\<eta> : \\<Gamma> \\<rbrakk> \\<Longrightarrow> \\<turnstile> \\<rho>, (V#\\<eta>) : push_tyvar \\<Gamma>\"\n\ninductive_cases\n  wtnat_inv[elim!]: \"\\<Gamma> \\<turnstile> ENat n : \\<tau>\" and\n  wtvar_inv[elim!]: \"\\<Gamma> \\<turnstile> EVar n : \\<tau>\" and\n  wtapp_inv[elim!]: \"\\<Gamma> \\<turnstile> EApp e e' : \\<tau>\" and\n  wtlam_inv[elim!]: \"\\<Gamma> \\<turnstile> ELam \\<sigma> e : \\<tau>\" and\n  wtfix_inv[elim!]: \"\\<Gamma> \\<turnstile> EFix \\<sigma> e : \\<tau>\" and\n  wtabs_inv[elim!]: \"\\<Gamma> \\<turnstile> EAbs e : \\<tau>\" and\n  wtinst_inv[elim!]: \"\\<Gamma> \\<turnstile> EInst e \\<sigma> : \\<tau>\"\n\nlemma wfenv_good_ctx: \"\\<turnstile> \\<rho>,\\<eta> : \\<Gamma> \\<Longrightarrow> good_ctx \\<Gamma>\"\nproof (induction rule: wfenv.induct)\n  case wfnil\n  then show ?case by (force simp: good_ctx_def)\nnext\n  case (wfvbind \\<rho> \\<eta> \\<Gamma> v \\<tau>)\n  then show ?case \n    apply (simp add: good_ctx_def push_ty_def) apply (cases \\<Gamma>) apply simp\n    apply clarify apply (rename_tac n) apply (case_tac n) apply force apply force done\nnext\n  case (wftbind \\<rho> \\<eta> \\<Gamma> V)\n  then show ?case \n    apply (simp add: good_ctx_def push_tyvar_def) apply (cases \\<Gamma>) apply simp\n    apply clarify apply (rename_tac n) apply (case_tac n) apply auto done\nqed\n\nsubsection \"Well-typed Programs don't go wrong\"\n\nlemma nth_append1[simp]: \"n < length \\<rho>1 \\<Longrightarrow> (\\<rho>1@\\<rho>2)!n = \\<rho>1!n\"\nproof (induction \\<rho>1 arbitrary: \\<rho>2 n)\n  case Nil\n  then show ?case by auto\nnext\n  case (Cons a \\<rho>1)\n  then show ?case by (cases n) auto\nqed\n\nlemma nth_append2[simp]: \"n \\<ge> length \\<rho>1 \\<Longrightarrow> (\\<rho>1@\\<rho>2)!n = \\<rho>2!(n - length \\<rho>1)\"\nproof (induction \\<rho>1 arbitrary: \\<rho>2 n)\n  case Nil\n  then show ?case by auto\nnext\n  case (Cons a \\<rho>1)\n  then show ?case by (cases n) auto\nqed\n\nlemma shift_append_preserves_T_aux: \n  shows \"T \\<tau> (\\<rho>1@\\<rho>3) = T (shift (length \\<rho>2) (length \\<rho>1) \\<tau>) (\\<rho>1@\\<rho>2@\\<rho>3)\" \nproof (induction \\<tau> arbitrary: \\<rho>1 \\<rho>2 \\<rho>3)\n  case (Forall \\<tau>)\n  then show ?case \n    apply simp\n    apply (rule equalityI) apply (rule subsetI) apply (simp only: mem_Collect_eq)\n     apply (erule disjE) apply (erule exE) apply (erule conjE) apply (rule disjI1)\n      apply (rename_tac x v')\n      apply (rule_tac x=v' in exI) apply simp apply clarify \n      apply (rename_tac V)\n      apply (erule_tac x=V in allE) \n      apply (subgoal_tac \"T \\<tau> ((V#\\<rho>1) @ \\<rho>3) =\n       T (shift (length \\<rho>2) (length (V#\\<rho>1)) \\<tau>) ((V#\\<rho>1) @ \\<rho>2 @ \\<rho>3)\")\n       prefer 2 apply blast apply force \n     apply (rule disjI2) apply force\n    apply (rule subsetI) apply (simp only: mem_Collect_eq)\n    apply (erule disjE) apply (erule exE) apply (erule conjE) apply (rule disjI1)\n     apply (rename_tac x v')\n     apply (rule_tac x=v' in exI) apply simp apply clarify \n     apply (rename_tac V)\n     apply (erule_tac x=V in allE) \n     apply (subgoal_tac \"T \\<tau> ((V#\\<rho>1) @ \\<rho>3) =\n       T (shift (length \\<rho>2) (length (V#\\<rho>1)) \\<tau>) ((V#\\<rho>1) @ \\<rho>2 @ \\<rho>3)\")\n      prefer 2 apply blast apply force \n    apply (rule disjI2) apply force done\nqed force+\n    \nlemma shift_append_preserves_T: shows \"T \\<tau> \\<rho>3 = T (shift (length \\<rho>2) 0 \\<tau>) (\\<rho>2@\\<rho>3)\"\n    using shift_append_preserves_T_aux[of \\<tau> \"[]\" \\<rho>3 \\<rho>2] by auto\n\nlemma drop_shift_preserves_T: \n  assumes k: \"k \\<le> length \\<rho>\" shows \"T \\<tau> (drop k \\<rho>) = T (shift k 0 \\<tau>) \\<rho>\"\nproof -\n  let ?r2 = \"take k \\<rho>\" and ?r3 = \"drop k \\<rho>\"\n  have 1: \"T \\<tau> (?r3) = T (shift (length ?r2) 0 \\<tau>) (?r2@?r3)\"\n    using shift_append_preserves_T_aux[of \\<tau> \"[]\" ?r3 ?r2] by simp  \n  have 2: \"?r2@?r3 = \\<rho>\" by simp\n  from k have 3: \"length ?r2 = k\" by simp \n  from 1 2 3 show ?thesis by simp \nqed\n\nlemma shift_cons_preserves_T: shows \"T \\<tau> \\<rho> = T (shift (Suc 0) 0 \\<tau>) (b#\\<rho>)\"\n  using drop_shift_preserves_T[of \"Suc 0\" \"b#\\<rho>\" \\<tau>] by simp \n    \nlemma compose_shift: shows \"shift (j+k) c \\<tau> = shift j c (shift k c \\<tau>)\"\n  by (induction \\<tau> arbitrary: j k c) auto\n    \nlemma shift_zero_id[simp]: \"shift 0 c \\<tau> = \\<tau>\"\n  by (induction \\<tau> arbitrary: c) auto \n    \nlemma lookup_wfenv: assumes r_g: \"\\<turnstile> \\<rho>,\\<eta> : \\<Gamma>\" and ln: \"lookup \\<Gamma> n = Some \\<tau>\"\n  shows \"\\<exists> v. \\<rho>!n = v \\<and> v \\<in> T \\<tau> \\<eta>\"\n  using r_g ln\nproof (induction \\<rho> \\<eta> \\<Gamma> arbitrary: n \\<tau> rule: wfenv.induct)\n  case wfnil\n  then show ?case unfolding lookup_def by force\nnext\n  case (wfvbind \\<rho> \\<eta> \\<Gamma> v \\<tau>')\n  from wfvbind(2) have vtp: \"v \\<in> T \\<tau>' \\<eta>\" .\n  show ?case\n  proof (cases n)\n    case 0\n    from 0 wfvbind(4) have t: \"\\<tau> =  shift 0 0 \\<tau>'\" unfolding lookup_def by (simp add: push_ty_def) \n    from 0 vtp t show ?thesis by simp \n  next\n    case (Suc n')\n    let ?G = \"push_ty \\<tau>' \\<Gamma>\" \n    from wfvbind(4) Suc obtain \\<sigma> k where gnp: \"(fst \\<Gamma>)!n' = (\\<sigma>,k)\" and t: \"\\<tau> = shift (snd \\<Gamma> - k) 0 \\<sigma>\" \n      and npg: \"n' < length (fst \\<Gamma>)\"\n      unfolding lookup_def push_ty_def apply (cases \"n' < length (fst \\<Gamma>)\") apply auto\n      apply (cases \"fst \\<Gamma> ! n'\") apply auto done  \n    from gnp Suc npg t have ln: \"lookup \\<Gamma> n' = Some \\<tau>\" unfolding lookup_def by auto \n    from wfvbind(3) ln obtain v' where rnp: \"\\<rho>!n' = v'\" and vt: \"v' \\<in> T \\<tau> \\<eta>\" by blast\n    from Suc rnp vt show ?thesis by simp  \n  qed\nnext\n  case (wftbind \\<rho> \\<eta> \\<Gamma> V)\n  let ?a = \"fst \\<Gamma>\" and ?b = \"snd \\<Gamma>\"\n  obtain \\<sigma> k where s: \"\\<sigma> = fst (fst \\<Gamma> ! n)\" and k: \"k = snd (fst \\<Gamma> ! n)\" by auto \n  from wftbind(3) s k have t: \"\\<tau> = shift (Suc ?b - k) 0 \\<sigma>\" and nl: \"n < length (fst \\<Gamma>)\"\n    unfolding push_tyvar_def lookup_def apply auto \n     apply (case_tac \"n < length (fst \\<Gamma>)\", auto)+ done\n  let ?t = \"shift (?b - k) 0 (fst (?a ! n))\"\n  from wftbind(3) k have ln: \"lookup \\<Gamma> n = Some ?t\"\n    unfolding push_tyvar_def lookup_def\n    apply (cases \\<Gamma>) apply (rename_tac k' G) apply simp apply (case_tac \"n < length k'\") by auto \n  from wftbind(2) ln obtain v' where rn_vp: \"\\<rho> ! n = v'\" and vp_t: \"v' \\<in> T ?t \\<eta>\" by blast\n  from vp_t have \"v' \\<in> T (shift (Suc 0) 0 ?t) (V # \\<eta>)\" using shift_cons_preserves_T by auto \n  hence vp_t2: \"v' \\<in> T (shift (Suc 0 + (?b - k)) 0 (fst (?a!n))) (V # \\<eta>)\"\n    using compose_shift[of \"Suc 0\" \"?b - k\" 0 \"fst (?a!n)\"] by simp\n  from wftbind(1) have \"good_ctx \\<Gamma>\" using wfenv_good_ctx by blast\n  from this k nl have \"?b \\<ge> k\" unfolding good_ctx_def by auto\n  from this have \"Suc 0 + (?b - k) = Suc ?b - k\" by simp\n  from this vp_t2 have vp_t3: \"v' \\<in> T (shift (Suc ?b - k) 0 (fst (?a!n))) (V # \\<eta>)\" by simp\n  from rn_vp vp_t3 t s show ?case by auto \nqed\n\nlemma less_wrong[elim!]: \"\\<lbrakk> v \\<sqsubseteq> Wrong; v = Wrong \\<Longrightarrow> P \\<rbrakk> \\<Longrightarrow> P\"\n  by (case_tac v) auto\n\nlemma less_nat[elim!]: \"\\<lbrakk> v \\<sqsubseteq> VNat n; v = VNat n \\<Longrightarrow> P \\<rbrakk> \\<Longrightarrow> P\"\n  by (case_tac v) auto \n    \nlemma less_fun[elim!]: \"\\<lbrakk> v \\<sqsubseteq> Fun f; \\<And> f'. \\<lbrakk> v = Fun f'; fset f' \\<subseteq> fset f \\<rbrakk> \\<Longrightarrow> P \\<rbrakk> \\<Longrightarrow> P\"\n  by (case_tac v) auto\n    \nlemma less_refl[simp]: \"v \\<sqsubseteq> v\"\nproof (induction v)\n    case (Abs v')\n    then show ?case by (cases v') auto\nqed force+\n  \nlemma less_trans: fixes v1::val and v2::val and v3::val\n  shows \"\\<lbrakk> v1 \\<sqsubseteq> v2; v2 \\<sqsubseteq> v3 \\<rbrakk> \\<Longrightarrow> v1 \\<sqsubseteq> v3\"\nproof (induction v2 arbitrary: v1 v3)\n  case (VNat n)\n  then show ?case by (cases v1) auto \nnext\n  case (Fun t)\n  then show ?case\n    apply (cases v1)\n       apply force \n      apply simp \n      apply (cases v3)\n         apply auto done\nnext\n  case (Abs v)\n  then show ?case \n    apply (cases v1) apply force apply force apply (case_tac v3) apply force apply force\n      apply (rename_tac v' v3') apply simp apply (cases v) apply (case_tac v')\n        apply force apply force \n      apply (case_tac v3') apply force apply simp apply (case_tac v') \n       apply force+ done\nnext\n  case Wrong\n  then show ?case by auto\nqed\n    \nlemma T_down_closed: assumes vt: \"v \\<in> T \\<tau> \\<eta>\" and vp_v: \"v' \\<sqsubseteq> v\"\n  shows \"v' \\<in> T \\<tau> \\<eta>\"\n  using vt vp_v\nproof (induction \\<tau> arbitrary: v v' \\<eta>)\n  case (TVar x v v' \\<eta>)\n  then show ?case \n    apply simp apply (case_tac \"x < length \\<eta>\")\n     apply simp apply clarify \n     apply (rule_tac x=v' in exI)\n     apply simp apply (rule conjI) \n      apply (rule less_trans) apply blast apply blast \n     apply (case_tac v')\n        apply (case_tac v)\n           apply force+ \n      apply (case_tac v)\n         apply force+ done\nnext\n  case TNat\n  then show ?case by auto\nnext\n  case (Fun \\<tau>1 \\<tau>2)\n  then show ?case apply simp apply clarify apply (rule_tac x=f' in exI) apply fastforce done\nnext\n  case (Forall \\<tau> v v' \\<eta>)\n  then show ?case \n    apply simp apply (erule disjE) apply clarify apply (cases v') apply force apply force\n      apply simp apply (rename_tac v'') apply (case_tac v'') apply simp apply simp apply clarify\n      apply (erule_tac x=V in allE) apply blast \n     apply force\n    apply simp\n    apply (case_tac v') apply auto done\nqed\n \nlemma wrong_not_in_T: \"Wrong \\<notin> T \\<tau> \\<eta>\"\n  by (induction \\<tau>) auto\n    \nlemma fun_app: assumes vmn: \"V \\<subseteq> T (m \\<rightarrow> n) \\<eta>\" and v2s: \"V' \\<subseteq> T m \\<eta>\" \n  shows \"apply_fun V V' \\<subseteq> T n \\<eta>\"\n  using vmn v2s apply simp apply (rule conjI)\n   prefer 2 apply force \n  apply clarify\n  apply (erule disjE)\n   prefer 2 using wrong_not_in_T apply blast \n  apply clarify apply (rename_tac v'') apply (case_tac v') apply auto\n  apply (rename_tac v1 v2) apply (case_tac \"v1 \\<sqsubseteq> v''\") apply auto \n  apply (subgoal_tac \"\\<forall>v1 v2'.\n                (v1, v2') \\<in> fset x2 \\<longrightarrow> v1 \\<in> T m \\<eta> \\<longrightarrow> (\\<exists>v2. v2 \\<in> T n \\<eta> \\<and> v2' \\<sqsubseteq> v2)\")\n   prefer 2 apply blast \n  apply (rename_tac v1 v2)\n  apply (erule_tac x=v1 in allE) apply (erule_tac x=v2 in allE) apply (erule impE) apply simp\n  apply (erule impE) using T_down_closed apply blast \n  apply clarify  using T_down_closed apply blast\n  done   \n    \nlemma T_eta: \"{v. \\<exists>v'. v' \\<in> T \\<sigma> (\\<eta>) \\<and> v \\<sqsubseteq> v' \\<and> v \\<noteq> Wrong} = T \\<sigma> \\<eta>\"\n  apply auto\n   using T_down_closed apply blast\n  apply (rename_tac v)\n  apply (rule_tac x=v in exI)\n  apply simp\n  using wrong_not_in_T apply blast done\n   \nlemma compositionality: \"T \\<tau> (\\<eta>1 @ (T \\<sigma> (\\<eta>1@\\<eta>2)) # \\<eta>2) = T (subst (length \\<eta>1) \\<sigma> \\<tau>) (\\<eta>1@\\<eta>2)\"\nproof (induction \\<tau> arbitrary: \\<sigma> \\<eta>1 \\<eta>2)\n  case (TVar x)\n  then show ?case \n    apply (case_tac \"length \\<eta>1 = x\") apply simp using T_eta apply blast\n    apply (case_tac \"length \\<eta>1 < x\") apply (subgoal_tac \"\\<exists> x'. x = Suc x'\") prefer 2 \n      apply (cases x) \n       apply force+\n    done\nnext\n  case TNat\n  then show ?case by auto\nnext\n  case (Fun \\<tau>1 \\<tau>2)\n  then show ?case by auto\nnext\n  case (Forall \\<tau>)\n  show \"T (Forall \\<tau>) (\\<eta>1 @ T \\<sigma> (\\<eta>1 @ \\<eta>2) # \\<eta>2) =\n        T (subst (length \\<eta>1) \\<sigma> (Forall \\<tau>)) (\\<eta>1 @ \\<eta>2)\"\n    apply simp\n    apply (rule equalityI) apply (rule subsetI) apply (simp only: mem_Collect_eq)\n     apply (erule disjE) prefer 2 apply force apply (erule exE) apply (erule conjE) apply (rule disjI1)\n     apply (rule_tac x=v' in exI) apply simp apply clarify \n     apply (erule_tac x=\"V\" in allE) \n     prefer 2 apply (rule subsetI) apply (simp only: mem_Collect_eq)\n     apply (erule disjE) prefer 2 apply force apply (erule exE) apply (erule conjE) apply (rule disjI1)\n     apply (rule_tac x=v' in exI) apply simp apply clarify \n     apply (erule_tac x=\"V\" in allE) \n     defer\n  proof -\n    fix x v' V\n    let ?L1 = \"length \\<eta>1\" and ?R1 = \"V#\\<eta>1\" and ?s = \"shift (Suc 0) 0 \\<sigma>\"\n    assume 1: \"v' \\<in> T \\<tau> (V # (\\<eta>1 @ T \\<sigma> (\\<eta>1 @ \\<eta>2) # \\<eta>2))\"\n    from 1 have a: \"v' \\<in> T \\<tau> (?R1 @ T \\<sigma> (\\<eta>1@\\<eta>2) # \\<eta>2)\" by simp\n        \n    have b: \"T \\<sigma> (\\<eta>1@\\<eta>2) = T ?s (V#(\\<eta>1@\\<eta>2))\" by (rule shift_cons_preserves_T)\n    from a b have c: \"v' \\<in> T \\<tau> (?R1 @ T ?s (?R1 @ \\<eta>2) # \\<eta>2)\" by simp\n    from Forall[of ?R1 ?s \\<eta>2] have 2: \"T \\<tau> (?R1 @ T ?s (?R1 @ \\<eta>2) # \\<eta>2) =\n                                  T (subst (length ?R1) ?s \\<tau>) (?R1 @ \\<eta>2)\" by simp\n    from c 2 show \"v' \\<in> T (subst (Suc ?L1) ?s \\<tau>) (V # (\\<eta>1 @ \\<eta>2))\" by simp\n  next\n    fix x v' V\n    let ?L1 = \"length \\<eta>1\" and ?R1 = \"V#\\<eta>1\" and ?s = \"shift (Suc 0) 0 \\<sigma>\"\n    assume 1: \"v' \\<in> T (subst (Suc (length \\<eta>1)) (shift (Suc 0) 0 \\<sigma>) \\<tau>) (V # \\<eta>1 @ \\<eta>2)\"\n    from Forall[of ?R1 ?s \\<eta>2] have 2: \"T \\<tau> (?R1 @ T ?s (?R1 @ \\<eta>2) # \\<eta>2) =\n                                  T (subst (length ?R1) ?s \\<tau>) (?R1 @ \\<eta>2)\" by simp\n    from 1 2 have 3: \"v' \\<in> T \\<tau> (?R1 @ T ?s (?R1 @ \\<eta>2) # \\<eta>2)\" by simp\n    have b: \"T \\<sigma> (\\<eta>1@\\<eta>2) = T ?s (V#(\\<eta>1@\\<eta>2))\" by (rule shift_cons_preserves_T)\n    from 3 b have a: \"v' \\<in> T \\<tau> (?R1 @ T \\<sigma> (\\<eta>1@\\<eta>2) # \\<eta>2)\" by simp\n    from this show \"v' \\<in> T \\<tau> (V # \\<eta>1 @ T \\<sigma> (\\<eta>1 @ \\<eta>2) # \\<eta>2)\" by simp\n  qed\nqed\n\nlemma iterate_sound:\n  assumes it: \"iterate Ee \\<rho> v\" \n    and IH: \"\\<forall> v. v \\<in> T (\\<sigma>\\<rightarrow>\\<tau>) \\<eta> \\<longrightarrow> Ee (v#\\<rho>) \\<subseteq> T (\\<sigma>\\<rightarrow>\\<tau>) \\<eta>\"\n  shows \"v \\<in> T (\\<sigma>\\<rightarrow>\\<tau>) \\<eta>\" using it IH\nproof (induction rule: iterate.induct)\n  case (iterate_none Ee \\<rho>)\n  then show ?case by auto \nnext\n  case (iterate_again Ee \\<rho> f f')\n  from iterate_again have f_st: \"f \\<in> T (\\<sigma>\\<rightarrow>\\<tau>) \\<eta>\" by blast\n  from iterate_again f_st have \"Ee (f#\\<rho>) \\<subseteq> T (\\<sigma>\\<rightarrow>\\<tau>) \\<eta>\" by blast\n  from this iterate_again show ?case by auto\nqed\n  \ntheorem welltyped_dont_go_wrong:\n  assumes wte: \"\\<Gamma> \\<turnstile> e : \\<tau>\" and wfr: \"\\<turnstile> \\<rho>,\\<eta> : \\<Gamma>\"\n  shows \"E e \\<rho> \\<subseteq> T \\<tau> \\<eta>\"\n  using wte wfr\nproof (induction \\<Gamma> e \\<tau> arbitrary: \\<rho> \\<eta> rule: well_typed.induct)\n  case (wtnat \\<Gamma> n \\<rho> \\<eta>)\n  then show ?case by auto\nnext\n  case (wtvar \\<Gamma> n \\<tau> \\<rho> \\<eta>)\n  from wtvar obtain v where lx: \"\\<rho> ! n = v\" and vt: \"v \\<in> T \\<tau> \\<eta>\"using lookup_wfenv by blast\n  from lx vt show ?case apply auto using T_down_closed[of \"\\<rho>!n\" \\<tau> \"\\<eta>\"] by blast\nnext\n  case (wtapp \\<Gamma> e \\<sigma> \\<tau> e' \\<rho> \\<eta>)\n  from wtapp have Ee: \"E e \\<rho> \\<subseteq> T (\\<sigma> \\<rightarrow> \\<tau>) \\<eta>\" by blast \n  from wtapp have Eep: \"E e' \\<rho> \\<subseteq> T \\<sigma> \\<eta>\" by blast  \n  from Ee Eep show ?case using fun_app by simp\nnext\n  case (wtlam \\<sigma> \\<Gamma> e \\<tau> \\<rho> \\<eta>)\n  show ?case\n    apply simp apply (rule subsetI) apply clarify apply (rule_tac x=f in exI) apply simp\n    apply clarify apply (erule_tac x=v1 in allE) apply (erule_tac x=v2' in allE) apply clarify \n  proof -\n    fix f v1 v2' v2\n    assume v1_T: \"v1 \\<in> T \\<sigma> \\<eta>\" and v2_E: \"v2 \\<in> E e (v1#\\<rho>)\" and v2p_v2: \"v2' \\<sqsubseteq> v2\"\n    let ?r = \"v1#\\<rho>\"\n    from wtlam(3) v1_T have 1: \"\\<turnstile> v1#\\<rho>,\\<eta> : push_ty \\<sigma> \\<Gamma>\" by blast\n    from wtlam(2) 1 have IH: \"E e (v1#\\<rho>) \\<subseteq> T \\<tau> \\<eta>\" by blast\n    from IH v2_E have v2_T: \"v2 \\<in> T \\<tau> \\<eta>\" by blast\n    from v2_T have v2_Tb: \"v2 \\<in> T \\<tau> \\<eta>\" by simp\n    from v2_Tb v2p_v2 show \"\\<exists>v2. v2 \\<in> T \\<tau> \\<eta> \\<and> v2' \\<sqsubseteq> v2 \" by blast\n  qed\nnext\n  case (wtfix \\<sigma> \\<tau> \\<Gamma> e \\<rho> \\<eta>)\n  have \"\\<forall> v. iterate (E e) \\<rho> v \\<longrightarrow> v \\<in> T (\\<sigma> \\<rightarrow> \\<tau>) \\<eta>\"\n  proof clarify\n    fix v assume it: \"iterate (E e) \\<rho> v\"\n    have 1: \" \\<forall>v. v \\<in> T (\\<sigma> \\<rightarrow> \\<tau>) \\<eta> \\<longrightarrow> E e (v#\\<rho>) \\<subseteq> T (\\<sigma> \\<rightarrow> \\<tau>) \\<eta>\" \n    proof clarify\n      fix v' v'' assume 2: \"v' \\<in> T (\\<sigma>\\<rightarrow>\\<tau>) \\<eta>\" and 3: \"v'' \\<in> E e (v'#\\<rho>)\"\n      from wtfix(3) 2 have \"\\<turnstile> (v'#\\<rho>),\\<eta> : push_ty (\\<sigma> \\<rightarrow> \\<tau>) \\<Gamma>\" by blast\n      from wtfix(2) this have IH: \"E e (v'#\\<rho>) \\<subseteq> T (\\<sigma>\\<rightarrow>\\<tau>) \\<eta>\" by blast\n      from 3 IH have \"v'' \\<in> T (\\<sigma>\\<rightarrow>\\<tau>)  \\<eta>\" by blast\n      from this show \"v'' \\<in> T (\\<sigma> \\<rightarrow> \\<tau>) \\<eta>\" by simp \n    qed\n    from it 1 show \"v \\<in> T (\\<sigma> \\<rightarrow> \\<tau>) \\<eta>\" using iterate_sound[of \"E e\" \\<rho> v \\<sigma> \\<tau>] by blast\n  qed\n  from this show ?case by auto \nnext\n  case (wtabs \\<Gamma> e \\<tau> \\<rho> \\<eta>)\n  show ?case apply simp apply (rule subsetI) apply (simp only: mem_Collect_eq)\n    apply (erule disjE) apply (erule exE) apply (erule conjE) apply (rule disjI1)\n     apply (rule_tac x=v' in exI) apply simp apply clarify prefer 2 apply (rule disjI2)\n     apply force\n  proof -\n    fix x v' V assume 2: \"v' \\<in> E e \\<rho>\"\n    from wtabs(3) have 3: \" \\<turnstile> \\<rho>,(V#\\<eta>) : push_tyvar \\<Gamma>\" by blast\n    from wtabs(2) 3 have IH: \"E e \\<rho> \\<subseteq> T \\<tau> (V#\\<eta>)\" by blast \n    from 2 IH show \"v' \\<in> T \\<tau> (V#\\<eta>)\" by (case_tac \\<rho>) auto\n  qed\nnext\n  case (wtinst \\<Gamma> e \\<tau> \\<sigma> \\<rho> \\<eta>)\n  from wtinst(2) wtinst(3) have IH: \"E e \\<rho> \\<subseteq> T (Forall \\<tau>) \\<eta>\" by blast\n  show ?case\n    apply simp apply (rule conjI) \n     apply (rule subsetI) apply (simp only: mem_Collect_eq) apply (erule exE)\n     apply (erule conjE)+\n  proof -\n    fix x v' assume vp_E: \"v' \\<in> E e \\<rho>\" and vp_w: \"v' \\<noteq> Wrong\" and \n      x: \"x \\<in> (case v' of Abs None \\<Rightarrow> {} | Abs (Some xa) \\<Rightarrow> return xa\n             | _ \\<Rightarrow> {v'. v' \\<sqsubseteq> Wrong})\" \n    from IH vp_E have vp_T: \"v' \\<in> T (Forall \\<tau>) \\<eta>\" by blast\n    from vp_T have \"(\\<exists>v''. v' = Abs (Some v'') \\<and> (\\<forall> V. v'' \\<in> T \\<tau> (V#\\<eta>)))\n                           \\<or> v' = Abs None\" by simp\n    from this show \"x \\<in> T (subst 0 \\<sigma> \\<tau>) \\<eta>\" \n    proof\n      assume \"\\<exists>v''. v' = Abs (Some v'') \\<and> (\\<forall> V. v'' \\<in> T \\<tau> (V#\\<eta>))\"\n      from this obtain v'' where vp: \"v' = Abs (Some v'')\" and \n        vpp_T: \"\\<forall> V. v'' \\<in> T \\<tau> (V#\\<eta>)\" by blast\n      from vp x have x_vpp: \"x \\<sqsubseteq> v''\" by auto\n      let ?V = \"T \\<sigma> \\<eta>\"\n      from vpp_T have \"v'' \\<in> T \\<tau> (?V#\\<eta>)\" by blast\n      from this have \"v'' \\<in> T (subst 0 \\<sigma> \\<tau>) \\<eta>\" using compositionality[of \\<tau> \"[]\" \\<sigma>] by simp\n      from this x_vpp show \"x \\<in> T (subst 0 \\<sigma> \\<tau>) \\<eta>\" using T_down_closed by blast\n    next\n      assume vp: \"v' = Abs None\"\n      from vp x show \"x \\<in> T (subst 0 \\<sigma> \\<tau>) \\<eta>\" by simp\n    qed\n  next\n    from IH show \"{v. v = Wrong \\<and> Wrong \\<in> E e \\<rho>} \\<subseteq> T (subst 0 \\<sigma> \\<tau>) \\<eta>\" \n      using wrong_not_in_T by auto\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/Decl_Sem_Fun_PL/SystemF.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8840392909114835, "lm_q2_score": 0.8244619220634456, "lm_q1q2_score": 0.7288567329644872}}
{"text": "(******************************************************************************)\n(* Project: Isabelle/UTP: Unifying Theories of Programming in Isabelle/HOL    *)\n(* File: cardinals.thy                                                        *)\n(* Author: Frank Zeyda, University of York (UK)                               *)\n(******************************************************************************)\n(* LAST REVIEWED: 27 March 2014 *)\n\nsection \\<open> Lightweight Cardinals \\<close>\n\ntheory Lightweight_Cardinals\nimports\n  Main \"HOL.Real\"\n  \"HOL-Library.Countable_Set\"\n  \"HOL-Cardinals.Cardinals\"\n  \"Z_Toolkit.Infinity\" UNIV_TYPE\nbegin\n\nsubsection \\<open> Cardinal Order \\<close>\n\ndefinition leq_card :: \"'a set \\<Rightarrow> 'b set \\<Rightarrow> bool\" (infix \"\\<preceq>\\<^sub>c\" 50) where\n\"(A \\<preceq>\\<^sub>c B) \\<longleftrightarrow> (\\<exists> f . (inj_on f A) \\<and> (f ` A) \\<subseteq> B)\"\n\ndefinition equal_card :: \"'a set \\<Rightarrow> 'b set \\<Rightarrow> bool\" (infix \"\\<equiv>\\<^sub>c\" 50) where\n\"(A \\<equiv>\\<^sub>c B) \\<longleftrightarrow> (A \\<preceq>\\<^sub>c B) \\<and> (B \\<preceq>\\<^sub>c A)\"\n\ndefinition less_card :: \"'a set \\<Rightarrow> 'b set \\<Rightarrow> bool\" (infix \"\\<prec>\\<^sub>c\" 50) where\n\"(A \\<prec>\\<^sub>c B) \\<longleftrightarrow> (A \\<preceq>\\<^sub>c B) \\<and> \\<not> (A \\<equiv>\\<^sub>c B)\"\n\nlemmas card_ord_defs =\n  leq_card_def\n  equal_card_def\n  less_card_def\n\nsubsection \\<open>  Constructors \\<close>\n\ndefinition fin_card :: \"nat \\<Rightarrow> nat set\" (\"c\\<^sub>f\") where\n\"c\\<^sub>f n = {1..n}\"\n\ndefinition type_card :: \"'a itself \\<Rightarrow> 'a set\" (\"c\\<^sub>\\<T>\") where\n\"c\\<^sub>\\<T> (t :: 'a itself) = UNIV_T('a)\"\n\ndefinition bool_card :: \"bool set\" (\"c\\<^sub>\\<bool>\") where\n\"c\\<^sub>\\<bool> = c\\<^sub>\\<T> TYPE(bool)\"\n\ndefinition nat_card :: \"nat set\" (\"c\\<^sub>\\<nat>\") where\n\"c\\<^sub>\\<nat> = c\\<^sub>\\<T> TYPE(nat)\"\n\ndefinition real_card :: \"real set\" (\"c\\<^sub>\\<real>\") where\n\"c\\<^sub>\\<real> = c\\<^sub>\\<T> TYPE(real)\"\n\nlemmas card_defs =\n  fin_card_def\n  type_card_def\n  bool_card_def\n  nat_card_def\n  real_card_def\n\nsubsection \\<open> Theorems \\<close>\n\nsubsubsection \\<open> Library Link \\<close>\n\ntheorem ordLess_lemma :\n\"(A <o B) \\<longleftrightarrow> (A \\<le>o B) \\<and> \\<not> (A =o B)\"\napply (metis not_ordLess_ordIso ordLeq_iff_ordLess_or_ordIso)\ndone\n\nsection \\<open> Transfer Rules \\<close>\n\ntheorem leq_card_iff_ordLeq :\n\"c1 \\<preceq>\\<^sub>c c2 \\<longleftrightarrow> |c1| \\<le>o |c2|\"\napply (fold card_of_ordLeq)\napply (unfold leq_card_def)\napply (simp)\ndone\n\ntheorem equal_card_iff_ordIso :\n\"c1 \\<equiv>\\<^sub>c c2 \\<longleftrightarrow> |c1| =o |c2|\"\napply (unfold equal_card_def)\napply (unfold leq_card_iff_ordLeq)\napply (unfold ordIso_iff_ordLeq)\napply (rule refl)\ndone\n\ntheorem less_card_iff_ordLess :\n\"c1 \\<prec>\\<^sub>c c2 \\<longleftrightarrow> |c1| <o |c2|\"\napply (unfold less_card_def equal_card_def)\napply (unfold leq_card_iff_ordLeq)\napply (unfold ordLess_lemma ordIso_iff_ordLeq)\napply (rule refl)\ndone\n\nlemmas card_transfer =\n  leq_card_iff_ordLeq\n  equal_card_iff_ordIso\n  less_card_iff_ordLess\n\nsection \\<open> Introduction Rules \\<close>\n\ntheorem leq_card_intro [intro] :\n\"|c1| \\<le>o |c2| \\<Longrightarrow> c1 \\<preceq>\\<^sub>c c2\"\napply (simp add: leq_card_iff_ordLeq)\ndone\n\ntheorem equal_card_intro [intro] :\n\"|c1| =o |c2| \\<Longrightarrow> c1 \\<equiv>\\<^sub>c c2\"\napply (simp add: equal_card_iff_ordIso)\ndone\n\ntheorem less_card_intro [intro] :\n\"|c1| <o |c2| \\<Longrightarrow> c1 \\<prec>\\<^sub>c c2\"\napply (simp add: less_card_iff_ordLess)\ndone\n\nsection \\<open> Destruction Rules \\<close>\n\ntheorem leq_card_dest [dest] :\n\"c1 \\<preceq>\\<^sub>c c2 \\<Longrightarrow> |c1| \\<le>o |c2|\"\napply (simp add: leq_card_iff_ordLeq)\ndone\n\ntheorem equal_card_dest [dest] :\n\"c1 \\<equiv>\\<^sub>c c2 \\<Longrightarrow> |c1| =o |c2|\"\napply (simp add: equal_card_iff_ordIso)\ndone\n\ntheorem less_card_dest [dest] :\n\"c1 \\<prec>\\<^sub>c c2 \\<Longrightarrow> |c1| <o |c2|\"\napply (simp add: less_card_iff_ordLess)\ndone\n\nsubsubsection \\<open> Theorems for @{term \"(\\<preceq>\\<^sub>c)\"} \\<close>\n\ntheorem leq_card_refl :\n\"(A \\<preceq>\\<^sub>c A)\"\napply (unfold leq_card_def)\napply (rule_tac x = \"id\" in exI)\napply (simp)\ndone\n\ntheorem leq_card_antisym :\n\"\\<lbrakk>(A \\<preceq>\\<^sub>c B); (B \\<preceq>\\<^sub>c A)\\<rbrakk> \\<Longrightarrow> (A \\<equiv>\\<^sub>c B)\"\napply (unfold equal_card_def)\napply (simp)\ndone\n\ntheorem leq_card_trans :\n\"\\<lbrakk>(A \\<preceq>\\<^sub>c B); (B \\<preceq>\\<^sub>c C)\\<rbrakk> \\<Longrightarrow> (A \\<preceq>\\<^sub>c C)\"\napply (unfold leq_card_def)\napply (clarify)\napply (rename_tac f g)\napply (rule_tac x = \"g \\<circ> f\" in exI)\napply (rule conjI)\n\\<comment> \\<open> Subgoal 1 \\<close>\napply (rule comp_inj_on)\napply (assumption)\napply (erule subset_inj_on)\n  apply (assumption)\n\\<comment> \\<open> Subgoal 2 \\<close>\napply (simp add: image_comp[THEN sym])\napply blast\ndone\n\ntheorem leq_card_linear :\n\"(A \\<preceq>\\<^sub>c B) \\<or> (B \\<preceq>\\<^sub>c A)\"\napply (unfold leq_card_def)\napply (metis one_set_greater)\ndone\n\ntheorem not_leq_card_dest :\n\"\\<not> (A \\<preceq>\\<^sub>c B) \\<Longrightarrow> (B \\<preceq>\\<^sub>c A)\"\napply (metis leq_card_linear)\ndone\n\ntheorem leq_card_empty :\n\"{} \\<preceq>\\<^sub>c C\"\napply (unfold leq_card_def)\napply (simp)\ndone\n\ntheorem leq_card_subset :\n\"A \\<subseteq> B \\<Longrightarrow> A \\<preceq>\\<^sub>c B\"\napply (unfold leq_card_def)\napply (rule_tac x = \"id\" in exI)\napply (simp)\ndone\n\ntheorem leq_image_mono :\n\"A \\<preceq>\\<^sub>c C \\<Longrightarrow> (f ` A) \\<preceq>\\<^sub>c C\"\napply (unfold leq_card_def)\napply (clarify)\napply (rename_tac g)\napply (rule_tac x = \"g o (inv_into A f)\" in exI)\n  apply (rule conjI)\n\\<comment> \\<open> Subgoal 1 \\<close>\napply (rule comp_inj_on)\napply (rule inj_on_inv_into)\napply (simp)\napply (erule subset_inj_on)\napply (rule image_subsetI)\napply (erule inv_into_into)\n\\<comment> \\<open> Subgoal 2 \\<close>\napply (rule image_subsetI)\napply (unfold comp_def)\napply (metis image_eqI in_mono inv_into_into)\ndone\n\nsubsubsection \\<open> Theorems for @{term \"(\\<equiv>\\<^sub>c)\"} \\<close>\n\ntheorem equal_card_bij_betw :\n\"(A \\<equiv>\\<^sub>c B) \\<longleftrightarrow> (\\<exists> f . bij_betw f A B)\"\napply (unfold equal_card_def leq_card_def)\napply (safe)\n\\<comment> \\<open> Subgoal 1 \\<close>\napply (rename_tac f g)\napply (rule Schroeder_Bernstein)\napply (assumption)+\n\\<comment> \\<open> Subgoal 2 \\<close>\napply (unfold bij_betw_def)\napply (rule_tac x = \"f\" in exI)\napply (clarsimp)\n\\<comment> \\<open> Subgoal 3 \\<close>\napply (rule_tac x = \"inv_into A f\" in exI)\napply (clarsimp)\napply (rule inj_on_inv_into)\napply (simp)\ndone\n\ntheorem equal_card_refl :\n\"(A \\<equiv>\\<^sub>c A)\"\napply (unfold equal_card_def)\napply (simp add: leq_card_refl)\ndone\n\ntheorem equal_card_sym :\n\"(A \\<equiv>\\<^sub>c B) \\<longleftrightarrow> (B \\<equiv>\\<^sub>c A)\"\napply (unfold equal_card_def)\napply (safe)\ndone\n\ntheorem equal_card_trans :\n\"\\<lbrakk>(A \\<equiv>\\<^sub>c B); (B \\<equiv>\\<^sub>c C)\\<rbrakk> \\<Longrightarrow> (A \\<equiv>\\<^sub>c C)\"\napply (unfold equal_card_def)\napply (clarsimp)\napply (rule conjI)\napply (erule leq_card_trans)\napply (assumption)\napply (erule leq_card_trans)\napply (assumption)\ndone\n\nsubsubsection \\<open> Theorems for @{term \"(\\<prec>\\<^sub>c)\"} \\<close>\n\ntheorem le_imp_leq_card :\n\"(A \\<prec>\\<^sub>c B) \\<Longrightarrow> (A \\<preceq>\\<^sub>c B)\"\napply (unfold less_card_def)\napply (clarify)\ndone\n\ntheorem le_card_iff :\n\"(A \\<prec>\\<^sub>c B) \\<longleftrightarrow> \\<not> (B \\<preceq>\\<^sub>c A)\"\napply (unfold less_card_def equal_card_def)\napply (metis leq_card_linear)\ndone\n\ntheorem le_card_cases :\n\"(A \\<prec>\\<^sub>c B) \\<or> (B \\<prec>\\<^sub>c A) \\<or> (A \\<equiv>\\<^sub>c B)\"\napply (simp add: le_card_iff)\napply (simp add: equal_card_def)\ndone\n\ntheorem le_card_trans :\n\"\\<lbrakk>(A \\<prec>\\<^sub>c B); (B \\<prec>\\<^sub>c C)\\<rbrakk> \\<Longrightarrow> (A \\<prec>\\<^sub>c C)\"\napply (simp add: le_card_iff)\napply (metis leq_card_linear leq_card_trans)\ndone\n\nsubsubsection \\<open> Theorems for @{term \"c\\<^sub>f\"} \\<close>\n\ntheorem fin_card_mono :\n\"n \\<le> m \\<Longrightarrow> c\\<^sub>f n \\<preceq>\\<^sub>c c\\<^sub>f m\"\napply (unfold fin_card_def)\napply (unfold leq_card_def)\napply (rule_tac x = \"id\" in exI)\napply (clarsimp)\ndone\n\ntheorem fin_le_nat_card :\n\"c\\<^sub>f n \\<prec>\\<^sub>c c\\<^sub>\\<nat>\"\napply (subst le_card_iff)\napply (unfold card_defs)\napply (unfold leq_card_def)\napply (simp add: UNIV_TYPE_def)\napply (clarify)\napply (drule range_inj_infinite)\napply (drule infinite_super)\napply (assumption)\napply (simp)\ndone\n\ntheorem fin_leq_nat_card :\n\"c\\<^sub>f n \\<preceq>\\<^sub>c c\\<^sub>\\<nat>\"\napply (rule le_imp_leq_card)\napply (rule fin_le_nat_card)\ndone\n\nsubsubsection \\<open> Theorems for @{term \"c\\<^sub>\\<bool>\"} \\<close>\n\ntheorem bool_eq_fin_card :\n\"c\\<^sub>\\<bool> \\<equiv>\\<^sub>c c\\<^sub>f 2\"\napply (unfold equal_card_def leq_card_def)\napply (unfold card_defs)\napply (simp add: UNIV_TYPE_def)\napply (safe)\n\\<comment> \\<open> Subgoal 1 \\<close>\napply (rule_tac x = \"(\\<lambda> b . if b then 1 else 2)\" in exI)\napply (rule conjI)\n\\<comment> \\<open> Subgoal 1.1 \\<close>\napply (rule injI)\napply (simp only: atomize_imp)\napply (induct_tac x)\napply (induct_tac y)\napply (simp_all)\n\\<comment> \\<open> Subgoal 1.2 \\<close>\napply (auto) [1]\n\\<comment> \\<open> Subgoal 2 \\<close>\napply (rule_tac x = \"(\\<lambda> n . n = 1)\" in exI)\napply (rule inj_onI)\napply (clarsimp)\napply (case_tac \"x = 1\")\napply (simp_all)\ndone\n\nsubsubsection \\<open> Theorems for @{term \"c\\<^sub>\\<nat>\"} \\<close>\n\ntheorem countable_leq_nat_card :\n\"countable c \\<Longrightarrow> c \\<preceq>\\<^sub>c c\\<^sub>\\<nat>\"\napply (unfold nat_card_def type_card_def)\napply (unfold UNIV_TYPE_def)\napply (unfold leq_card_def)\napply (simp add: countable_def)\ndone\n\ntheorem infinite_nat_card_leq :\n\"infinite c \\<Longrightarrow> c\\<^sub>\\<nat> \\<preceq>\\<^sub>c c\"\napply (unfold nat_card_def type_card_def)\napply (unfold UNIV_TYPE_def)\napply (unfold leq_card_def)\napply (erule infinite_countable_subset)\ndone\n\ntheorem countable_infinite_eq_nat_card :\n\"countable c \\<Longrightarrow> infinite c \\<Longrightarrow> c \\<equiv>\\<^sub>c c\\<^sub>\\<nat>\"\napply (drule countable_leq_nat_card)\napply (drule infinite_nat_card_leq)\napply (simp add: equal_card_def)\ndone\n\ntheorem leq_type_card_inj :\n\"c\\<^sub>\\<T> TYPE('a) \\<preceq>\\<^sub>c c\\<^sub>\\<T> TYPE('b) \\<longleftrightarrow> (\\<exists> f :: 'a \\<Rightarrow> 'b . inj f)\"\napply (unfold type_card_def)\napply (unfold UNIV_TYPE_def)\napply (simp add: leq_card_def)\ndone\n\ntheorem eq_type_card_bij :\n\"c\\<^sub>\\<T> TYPE('a) \\<equiv>\\<^sub>c c\\<^sub>\\<T> TYPE('b) \\<longleftrightarrow> (\\<exists> f :: 'a \\<Rightarrow> 'b . bij f)\"\napply (unfold type_card_def)\napply (unfold UNIV_TYPE_def)\napply (simp add: equal_card_bij_betw)\ndone\n\ntheorem countable_infinite_inj_ex :\n\"countable (c\\<^sub>\\<T> TYPE('a)) \\<Longrightarrow>\n infinite (c\\<^sub>\\<T> TYPE('b)) \\<Longrightarrow>\n (\\<exists> f :: 'a \\<Rightarrow> 'b . inj f)\"\napply (fold leq_type_card_inj)\napply (drule countable_leq_nat_card)\napply (drule infinite_nat_card_leq)\napply (metis leq_card_trans)\ndone\n\ntheorem countable_infinite_bij_ex :\n\"countable (c\\<^sub>\\<T> TYPE('a)) \\<Longrightarrow> infinite (c\\<^sub>\\<T> TYPE('a)) \\<Longrightarrow>\n countable (c\\<^sub>\\<T> TYPE('b)) \\<Longrightarrow> infinite (c\\<^sub>\\<T> TYPE('b)) \\<Longrightarrow>\n (\\<exists> f :: 'a \\<Rightarrow> 'b . bij f)\"\napply (fold eq_type_card_bij)\napply (drule countable_infinite_eq_nat_card)\napply (assumption)\napply (drule countable_infinite_eq_nat_card)\napply (assumption)\napply (metis equal_card_sym equal_card_trans)\ndone\n\ntheorem countable_type_leq_nat_card [simp] :\n\"(c :: 'a::countable set) \\<preceq>\\<^sub>c c\\<^sub>\\<nat>\"\napply (rule countable_leq_nat_card)\napply (rule countableI_type)\ndone\n\ntheorem countable_infinite_type_inj_ex :\n\"(\\<exists> f :: 'a::countable \\<Rightarrow> 'b::infinite . inj f)\"\napply (rule countable_infinite_inj_ex)\napply (unfold type_card_def)\napply (unfold UNIV_TYPE_def)\napply (simp_all)\ndone\n\ntheorem countable_infinite_type_bij_ex :\n\"(\\<exists> f :: 'a::{countable,infinite} \\<Rightarrow> 'b::{countable,infinite} . bij f)\"\napply (rule countable_infinite_bij_ex)\napply (unfold type_card_def)\napply (unfold UNIV_TYPE_def)\napply (simp_all)\ndone\n\ntheorem Nats_countable: \"\\<nat> \\<preceq>\\<^sub>c c\\<^sub>\\<T> TYPE(nat)\"\n  by (metis Nats_def UNIV_TYPE_def leq_card_refl leq_image_mono type_card_def)\n\ntext \\<open> We construct bijective versions of @{const to_nat} and @{const from_nat} \\<close>\n\ndefinition to_nat_bij :: \"'a::{countable, infinite} \\<Rightarrow> nat\" where\n\"to_nat_bij = (SOME f. bij f)\"\n\nlemma to_nat_bij:\n  \"bij to_nat_bij\"\nproof -\n  obtain f :: \"'a::{countable, infinite} \\<Rightarrow> nat\" where \"bij f\"\n    using countable_infinite_type_bij_ex by blast\n  thus ?thesis\n    by (auto simp add: to_nat_bij_def intro: someI[of bij])\nqed\n\ndefinition from_nat_bij :: \"nat \\<Rightarrow> 'a::{countable, infinite}\" where\n\"from_nat_bij = inv to_nat_bij\"\n\nlemma from_nat_bij_inv [simp]: \"to_nat_bij (from_nat_bij x) = x\"\n  by (simp add: bij_is_surj from_nat_bij_def surj_f_inv_f to_nat_bij)\n\nlemma to_nat_bij_inv [simp]: \"from_nat_bij (to_nat_bij x) = x\"\n  by (metis UNIV_I bij_betw_inv_into_left from_nat_bij_def to_nat_bij)\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/Lightweight_Cardinals.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8840392786908831, "lm_q2_score": 0.8244619242200082, "lm_q1q2_score": 0.7288567247955535}}
{"text": "(*  Title:      Filtration.thy\n    Author:     Mnacho Echenim, Univ. Grenoble Alpes\n*)\n\nsection \\<open>Filtrations\\<close>\n\ntext \\<open>This theory introduces basic notions about filtrations, which permit to define adaptable processes\nand predictable processes in the case where the filtration is indexed by natural numbers.\\<close>\n\ntheory Filtration imports \"HOL-Probability.Probability\"\nbegin\nsubsection \\<open>Basic definitions\\<close>\nclass linorder_bot = linorder + bot\ninstantiation nat::linorder_bot\nbegin\ninstance proof qed\nend\n\n\ndefinition filtration :: \"'a measure \\<Rightarrow> ('i::linorder_bot \\<Rightarrow> 'a measure) \\<Rightarrow> bool\" where\n  \"filtration M F \\<longleftrightarrow>\n    (\\<forall>t. subalgebra M (F t))  \\<and>\n    (\\<forall> s t. s \\<le> t \\<longrightarrow> subalgebra (F t) (F s))\"\n\nlemma filtrationI:\n  assumes \"\\<forall>t. subalgebra M (F t)\"\n  and \"\\<forall>s t. s \\<le> t \\<longrightarrow> subalgebra (F t) (F s)\"\nshows \"filtration M F\" unfolding filtration_def using assms by simp\n\nlemma filtrationE1:\n  assumes \"filtration M F\"\n  shows \"subalgebra M (F t)\" using assms unfolding filtration_def by simp\n\nlemma filtrationE2:\n  assumes \"filtration M F\"\n  shows \"s\\<le> t \\<Longrightarrow> subalgebra (F t) (F s)\" using assms unfolding filtration_def by simp\n\nlocale filtrated_prob_space = prob_space +\n  fixes F\n  assumes filtration: \"filtration M F\"\n\nlemma (in filtrated_prob_space) filtration_space:\n  assumes \"s \\<le> t\"\n  shows \"space (F s) = space (F t)\" by (metis filtration filtration_def subalgebra_def)\n\nlemma (in filtrated_prob_space) filtration_measurable:\n  assumes \"f\\<in> measurable (F t) N\"\nshows \"f\\<in> measurable M N\" unfolding measurable_def\nproof\n  show \"f \\<in> space M \\<rightarrow> space N \\<and> (\\<forall>y\\<in>sets N. f -` y \\<inter> space M \\<in> sets M)\"\n  proof (intro conjI ballI)\n    have \"space (F t) = space M\" using assms filtration unfolding filtration_def subalgebra_def by auto\n    thus \"f\\<in> space M \\<rightarrow> space N\" using assms unfolding measurable_def by simp\n    fix y\n    assume \"y\\<in> sets N\"\n    hence \"f -`y\\<inter> space M \\<in> sets (F t)\" using assms unfolding measurable_def\n      using \\<open>space (F t) = space M\\<close> by auto\n    thus \"f -`y\\<inter> space M \\<in> sets M\"  using assms filtration unfolding filtration_def subalgebra_def by auto\n  qed\nqed\n\n\nlemma (in filtrated_prob_space) increasing_measurable_info:\n  assumes \"f\\<in> measurable (F s) N\"\n  and \"s \\<le> t\"\n  shows \"f\\<in> measurable (F t) N\"\nproof (rule measurableI)\n  have inc: \"sets (F s) \\<subseteq> sets (F t)\"\n    using assms(2) filtration by (simp add: filtration_def subalgebra_def)\n  have sp: \"space (F s) = space (F t)\" by (metis filtration filtration_def subalgebra_def)\n  thus \"\\<And>x. x \\<in> space (F t) \\<Longrightarrow> f x \\<in> space N\" using assms by (simp add: measurable_space)\n  show \"\\<And>A. A \\<in> sets N \\<Longrightarrow> f -` A \\<inter> space (F t) \\<in> sets (F t)\"\n  proof -\n    fix A\n    assume \"A\\<in> sets N\"\n    hence \"f -` A \\<inter> space (F s) \\<in> sets (F s)\" using assms using measurable_sets by blast\n    hence \"f -` A \\<inter> space (F s) \\<in> sets (F t)\" using subsetD[of \"F s\" \"F t\"] inc by blast\n    thus \"f -` A \\<inter> space (F t) \\<in> sets (F t)\" using sp by simp\n  qed\nqed\n\n\n\ndefinition disc_filtr :: \"'a measure \\<Rightarrow> (nat \\<Rightarrow> 'a measure) \\<Rightarrow> bool\" where\n  \"disc_filtr M F \\<longleftrightarrow>\n    (\\<forall>n. subalgebra M (F n))  \\<and>\n    (\\<forall> n m. n \\<le> m \\<longrightarrow> subalgebra (F m) (F n))\"\n\n\nlocale disc_filtr_prob_space = prob_space +\n  fixes F\n  assumes discrete_filtration: \"disc_filtr M F\"\n\nlemma (in disc_filtr_prob_space) subalgebra_filtration:\n  assumes \"subalgebra N M\"\n  and \"filtration M F\"\nshows \"filtration N F\"\nproof (rule filtrationI)\n  show \"\\<forall>s t. s \\<le> t \\<longrightarrow> subalgebra (F t) (F s)\" using assms unfolding filtration_def by simp\n  show \"\\<forall>t. subalgebra N (F t)\"\n  proof\n    fix t\n    have \"subalgebra M (F t)\" using assms unfolding filtration_def by auto\n    thus \"subalgebra N (F t)\" using assms by (metis subalgebra_def subsetCE subsetI)\n  qed\nqed\n\n\n\nsublocale disc_filtr_prob_space \\<subseteq>  filtrated_prob_space\nproof unfold_locales\n  show \"filtration M F\"\n    using  discrete_filtration by (simp add: filtration_def disc_filtr_def)\nqed\n\n\n\nsubsection \\<open>Stochastic processes\\<close>\n\ntext  \\<open>Stochastic processes are collections of measurable functions. Those of a particular interest when\nthere is a filtration are the adapted stochastic processes.\\<close>\n\ndefinition stoch_procs where\n  \"stoch_procs M N = {X. \\<forall>t. (X t) \\<in> measurable M N}\"\n\nsubsubsection \\<open>Adapted stochastic processes\\<close>\n\ndefinition adapt_stoch_proc where\n  \"(adapt_stoch_proc F X N) \\<longleftrightarrow> (\\<forall>t. (X t) \\<in> measurable (F t) N)\"\n\n\nabbreviation \"borel_adapt_stoch_proc F X \\<equiv> adapt_stoch_proc F X borel\"\n\nlemma (in filtrated_prob_space) adapted_is_dsp:\n  assumes \"adapt_stoch_proc F X N\"\n  shows \"X \\<in> stoch_procs M N\"\n  unfolding  stoch_procs_def\n  by (intro CollectI, (meson adapt_stoch_proc_def assms filtration filtration_def measurable_from_subalg))\n\n\nlemma (in filtrated_prob_space) adapt_stoch_proc_borel_measurable:\n  assumes \"adapt_stoch_proc F X N\"\n  shows \"\\<forall>n. (X n) \\<in> measurable M N\"\nproof\n  fix n\n  have \"X n \\<in> measurable (F n) N\" using assms unfolding  adapt_stoch_proc_def by simp\n  moreover have \"subalgebra M (F n)\" using filtration unfolding filtration_def by simp\n  ultimately show \"X n \\<in> measurable M N\" by (simp add:measurable_from_subalg)\nqed\n\nlemma (in filtrated_prob_space) borel_adapt_stoch_proc_borel_measurable:\n  assumes \"borel_adapt_stoch_proc F X\"\n  shows \"\\<forall>n. (X n) \\<in> borel_measurable M\"\nproof\n  fix n\n  have \"X n \\<in> borel_measurable (F n)\" using assms unfolding  adapt_stoch_proc_def by simp\n  moreover have \"subalgebra M (F n)\" using filtration unfolding filtration_def by simp\n  ultimately show \"X n \\<in> borel_measurable M\" by (simp add:measurable_from_subalg)\nqed\n\n\nlemma (in filtrated_prob_space) constant_process_borel_adapted:\n  shows \"borel_adapt_stoch_proc F (\\<lambda> n w. c)\"\nunfolding  adapt_stoch_proc_def\nproof\n  fix t\n  show \"(\\<lambda>w. c) \\<in> borel_measurable (F t)\" using borel_measurable_const by blast\nqed\n\n\nlemma (in filtrated_prob_space) borel_adapt_stoch_proc_add:\n  fixes X::\"'b \\<Rightarrow> 'a \\<Rightarrow> ('c::{second_countable_topology, topological_monoid_add})\"\n  assumes \"borel_adapt_stoch_proc F X\"\n  and \"borel_adapt_stoch_proc F Y\"\nshows \"borel_adapt_stoch_proc F (\\<lambda>t w. X t w + Y t w)\" unfolding adapt_stoch_proc_def\nproof\n  fix t\n  have \"X t \\<in> borel_measurable (F t)\" using assms unfolding adapt_stoch_proc_def by simp\n  moreover have \"Y t \\<in> borel_measurable (F t)\" using assms unfolding adapt_stoch_proc_def by simp\n  ultimately show \"(\\<lambda>w. X t w + Y t w) \\<in> borel_measurable (F t)\" by simp\nqed\n\n\nlemma (in filtrated_prob_space) borel_adapt_stoch_proc_sum:\n  fixes A::\"'d \\<Rightarrow> 'b \\<Rightarrow> 'a \\<Rightarrow> ('c::{second_countable_topology, topological_comm_monoid_add})\"\n  assumes \"\\<And>i. i\\<in> S \\<Longrightarrow> borel_adapt_stoch_proc F (A i)\"\nshows \"borel_adapt_stoch_proc F (\\<lambda> t w. (\\<Sum> i\\<in> S. A i t w))\" unfolding adapt_stoch_proc_def\nproof\n  fix t\n  have \"\\<And>i. i\\<in> S\\<Longrightarrow> A i t \\<in> borel_measurable (F t)\" using assms unfolding adapt_stoch_proc_def by simp\n  thus \"(\\<lambda> w. (\\<Sum> i\\<in> S. A i t w)) \\<in> borel_measurable (F t)\" by (simp add:borel_measurable_sum)\nqed\n\nlemma (in filtrated_prob_space) borel_adapt_stoch_proc_times:\n  fixes X::\"'b \\<Rightarrow> 'a \\<Rightarrow> ('c::{second_countable_topology, real_normed_algebra})\"\n  assumes \"borel_adapt_stoch_proc F X\"\n  and \"borel_adapt_stoch_proc F Y\"\nshows \"borel_adapt_stoch_proc F (\\<lambda>t w. X t w * Y t w)\" unfolding adapt_stoch_proc_def\nproof\n  fix t\n  have \"X t \\<in> borel_measurable (F t)\" using assms unfolding adapt_stoch_proc_def by simp\n  moreover have \"Y t \\<in> borel_measurable (F t)\" using assms unfolding adapt_stoch_proc_def by simp\n  ultimately show \"(\\<lambda>w. X t w * Y t w) \\<in> borel_measurable (F t)\" by simp\nqed\n\nlemma (in filtrated_prob_space) borel_adapt_stoch_proc_prod:\n  fixes A::\"'d \\<Rightarrow> 'b \\<Rightarrow> 'a \\<Rightarrow> ('c::{second_countable_topology, real_normed_field})\"\n  assumes \"\\<And>i. i\\<in> S \\<Longrightarrow> borel_adapt_stoch_proc F (A i)\"\nshows \"borel_adapt_stoch_proc F (\\<lambda> t w. (\\<Prod> i\\<in> S. A i t w))\" unfolding adapt_stoch_proc_def\nproof\n  fix t\n  have \"\\<And>i. i\\<in> S\\<Longrightarrow> A i t \\<in> borel_measurable (F t)\" using assms unfolding adapt_stoch_proc_def by simp\n  thus \"(\\<lambda> w. (\\<Prod> i\\<in> S. A i t w)) \\<in> borel_measurable (F t)\" by simp\nqed\n\n\nsubsubsection \\<open>Predictable stochastic processes\\<close>\n\ndefinition predict_stoch_proc where\n  \"(predict_stoch_proc F X N) \\<longleftrightarrow> (X 0 \\<in> measurable (F 0) N \\<and> (\\<forall>n. (X (Suc n)) \\<in> measurable (F n) N))\"\n\n\nabbreviation  \"borel_predict_stoch_proc F X \\<equiv> predict_stoch_proc F X borel\"\n\nlemma (in disc_filtr_prob_space) predict_imp_adapt:\n  assumes \"predict_stoch_proc F X N\"\n  shows \"adapt_stoch_proc F X N\" unfolding adapt_stoch_proc_def\nproof\n  fix n\n  show \"X n \\<in> measurable (F n) N\"\n  proof (cases \"n = 0\")\n    case True\n    thus ?thesis using assms unfolding predict_stoch_proc_def by auto\n  next\n    case False\n    thus ?thesis using assms unfolding predict_stoch_proc_def\n      by (metis Suc_n_not_le_n increasing_measurable_info nat_le_linear not0_implies_Suc)\n  qed\nqed\n\n\nlemma (in disc_filtr_prob_space) predictable_is_dsp:\n  assumes \"predict_stoch_proc F X N\"\n  shows \"X \\<in> stoch_procs M N\"\nunfolding  stoch_procs_def\nproof\n  show \"\\<forall>n. random_variable N (X n)\"\n  proof\n    fix n\n    show \"random_variable N (X n)\"\n    proof (cases \"n=0\")\n      case True\n      thus ?thesis using assms unfolding predict_stoch_proc_def\n        using filtration filtration_def measurable_from_subalg by blast\n    next\n      case False\n      thus ?thesis using assms unfolding predict_stoch_proc_def\n        by (metis filtration filtration_def measurable_from_subalg not0_implies_Suc)\n    qed\n  qed\nqed\n\n\n\nlemma (in disc_filtr_prob_space) borel_predict_stoch_proc_borel_measurable:\n  assumes \"borel_predict_stoch_proc F X\"\n  shows \"\\<forall>n. (X n) \\<in> borel_measurable M\" using assms predictable_is_dsp unfolding stoch_procs_def by auto\n\n\n\nlemma (in disc_filtr_prob_space) constant_process_borel_predictable:\n  shows \"borel_predict_stoch_proc F (\\<lambda> n w. c)\"\nunfolding  predict_stoch_proc_def\nproof\n  show \"(\\<lambda>w. c) \\<in> borel_measurable (F 0)\" using borel_measurable_const by blast\nnext\n  show \"\\<forall>n. (\\<lambda>w. c) \\<in> borel_measurable (F n)\" using borel_measurable_const by blast\nqed\n\nlemma (in disc_filtr_prob_space) borel_predict_stoch_proc_add:\n  fixes X::\"nat \\<Rightarrow> 'a \\<Rightarrow> ('c::{second_countable_topology, topological_monoid_add})\"\n  assumes \"borel_predict_stoch_proc F X\"\n  and \"borel_predict_stoch_proc F Y\"\nshows \"borel_predict_stoch_proc F (\\<lambda>t w. X t w + Y t w)\" unfolding predict_stoch_proc_def\nproof\n  show \"(\\<lambda>w. X 0 w + Y 0 w) \\<in> borel_measurable (F 0)\"\n    using assms(1) assms(2) borel_measurable_add predict_stoch_proc_def by blast\nnext\n  show \"\\<forall>n. (\\<lambda>w. X (Suc n) w + Y (Suc n) w) \\<in> borel_measurable (F n)\"\n  proof\n    fix n\n    have \"X (Suc n) \\<in> borel_measurable (F n)\" using assms unfolding predict_stoch_proc_def by simp\n    moreover have \"Y (Suc n) \\<in> borel_measurable (F n)\" using assms unfolding predict_stoch_proc_def by simp\n    ultimately show \"(\\<lambda>w. X (Suc n) w + Y (Suc n) w) \\<in> borel_measurable (F n)\" by simp\n  qed\nqed\n\n\n\nlemma (in disc_filtr_prob_space) borel_predict_stoch_proc_sum:\n  fixes A::\"'d \\<Rightarrow> nat \\<Rightarrow> 'a \\<Rightarrow> ('c::{second_countable_topology, topological_comm_monoid_add})\"\n  assumes \"\\<And>i. i\\<in> S \\<Longrightarrow> borel_predict_stoch_proc F (A i)\"\nshows \"borel_predict_stoch_proc F (\\<lambda> t w. (\\<Sum> i\\<in> S. A i t w))\" unfolding predict_stoch_proc_def\nproof\n  show \"(\\<lambda>w. \\<Sum>i\\<in>S. A i 0 w) \\<in> borel_measurable (F 0)\"\n  proof\n    have \"\\<And>i. i\\<in> S\\<Longrightarrow> A i 0 \\<in> borel_measurable (F 0)\" using assms unfolding predict_stoch_proc_def by simp\n    thus \"(\\<lambda> w. (\\<Sum> i\\<in> S. A i 0 w)) \\<in> borel_measurable (F 0)\" by (simp add:borel_measurable_sum)\n  qed simp\nnext\n  show \"\\<forall>n. (\\<lambda>w. \\<Sum>i\\<in>S. A i (Suc n) w) \\<in> borel_measurable (F n)\"\n  proof\n    fix n\n    have \"\\<And>i. i\\<in> S\\<Longrightarrow> A i (Suc n) \\<in> borel_measurable (F n)\" using assms unfolding predict_stoch_proc_def by simp\n    thus \"(\\<lambda> w. (\\<Sum> i\\<in> S. A i (Suc n) w)) \\<in> borel_measurable (F n)\" by (simp add:borel_measurable_sum)\n  qed\nqed\n\n\nlemma (in disc_filtr_prob_space) borel_predict_stoch_proc_times:\n  fixes X::\"nat \\<Rightarrow> 'a \\<Rightarrow> ('c::{second_countable_topology, real_normed_algebra})\"\n  assumes \"borel_predict_stoch_proc F X\"\n  and \"borel_predict_stoch_proc F Y\"\nshows \"borel_predict_stoch_proc F (\\<lambda>t w. X t w * Y t w)\" unfolding predict_stoch_proc_def\nproof\n  show \"(\\<lambda>w. X 0 w * Y 0 w) \\<in> borel_measurable (F 0)\"\n  proof -\n    have \"X 0 \\<in> borel_measurable (F 0)\" using assms unfolding predict_stoch_proc_def by simp\n    moreover have \"Y 0 \\<in> borel_measurable (F 0)\" using assms unfolding predict_stoch_proc_def by simp\n    ultimately show \"(\\<lambda>w. X 0 w * Y 0 w) \\<in> borel_measurable (F 0)\" by simp\n  qed\nnext\n  show \"\\<forall>n. (\\<lambda>w. X (Suc n) w * Y (Suc n) w) \\<in> borel_measurable (F n)\"\n  proof\n    fix n\n    have \"X (Suc n) \\<in> borel_measurable (F n)\" using assms unfolding predict_stoch_proc_def by simp\n    moreover have \"Y (Suc n) \\<in> borel_measurable (F n)\" using assms unfolding predict_stoch_proc_def by simp\n    ultimately show \"(\\<lambda>w. X (Suc n) w * Y (Suc n) w) \\<in> borel_measurable (F n)\" by simp\n  qed\nqed\n\nlemma (in disc_filtr_prob_space) borel_predict_stoch_proc_prod:\n  fixes A::\"'d \\<Rightarrow> nat \\<Rightarrow> 'a \\<Rightarrow> ('c::{second_countable_topology, real_normed_field})\"\n  assumes \"\\<And>i. i\\<in> S \\<Longrightarrow> borel_predict_stoch_proc F (A i)\"\nshows \"borel_predict_stoch_proc F (\\<lambda> t w. (\\<Prod> i\\<in> S. A i t w))\" unfolding predict_stoch_proc_def\nproof\n  show \"(\\<lambda>w. \\<Prod>i\\<in>S. A i 0 w) \\<in> borel_measurable (F 0)\"\n  proof -\n    have \"\\<And>i. i\\<in> S\\<Longrightarrow> A i 0 \\<in> borel_measurable (F 0)\" using assms unfolding predict_stoch_proc_def by simp\n    thus \"(\\<lambda> w. (\\<Prod> i\\<in> S. A i 0 w)) \\<in> borel_measurable (F 0)\" by simp\n  qed\nnext\n  show \"\\<forall>n. (\\<lambda>w. \\<Prod>i\\<in>S. A i (Suc n) w) \\<in> borel_measurable (F n)\"\n  proof\n    fix n\n    have \"\\<And>i. i\\<in> S\\<Longrightarrow> A i (Suc n) \\<in> borel_measurable (F n)\" using assms unfolding predict_stoch_proc_def by simp\n    thus \"(\\<lambda> w. (\\<Prod> i\\<in> S. A i (Suc n) w)) \\<in> borel_measurable (F n)\" by simp\n  qed\nqed\n\n\ndefinition (in prob_space) constant_image where\n  \"constant_image f = (if \\<exists> c::'b::{t2_space}. \\<forall>x\\<in> space M. f x = c then\n    SOME c. \\<forall>x \\<in> space M. f x = c else undefined)\"\n\nlemma (in prob_space) constant_imageI:\n  assumes \"\\<exists>c::'b::{t2_space}. \\<forall>x\\<in> space M. f x = c\"\n  shows \"\\<forall>x\\<in> space M. f x = (constant_image f)\"\nproof\n  fix x\n  assume \"x\\<in> space M\"\n  let ?c = \"SOME c. \\<forall>x\\<in> space M. f x = c\"\n  have \"f x = ?c\" using \\<open>x\\<in> space M\\<close> someI_ex[of \"\\<lambda>c. \\<forall>x\\<in> space M. f x = c\"] assms by blast\n  thus \"f x = (constant_image f)\" by (simp add: assms prob_space.constant_image_def prob_space_axioms)\nqed\n\nlemma (in prob_space) constant_image_pos:\n  assumes \"\\<forall>x\\<in> space M. (0::real) < f x\"\n  and \"\\<exists>c::real. \\<forall>x\\<in> space M. f x = c\"\nshows \"0 < (constant_image f)\"\nproof -\n  {\n    fix x\n    assume \"x\\<in> space M\"\n    hence \"0 < f x\" using assms by simp\n    also have \"... = constant_image f\" using assms constant_imageI \\<open>x\\<in> space M\\<close> by auto\n    finally have ?thesis .\n  }\n  thus ?thesis using subprob_not_empty by auto\nqed\n\ndefinition open_except where\n\"open_except x y = (if x = y then {} else SOME A. open A \\<and> x\\<in> A \\<and> y\\<notin> A)\"\n\n\nlemma open_exceptI:\n  assumes \"(x::'b::{t1_space}) \\<noteq> y\"\n  shows \"open (open_except x y)\" and \"x\\<in> open_except x y\" and  \"y\\<notin> open_except x y\"\nproof-\n  have ex:\"\\<exists>U. open U \\<and> x \\<in> U \\<and> y \\<notin> U\" using \\<open>x\\<noteq> y\\<close> by (simp add:t1_space)\n  let ?V = \"SOME A. open A \\<and> x\\<in> A \\<and> y\\<notin> A\"\n  have vprop: \"open ?V \\<and> x \\<in> ?V \\<and> y \\<notin> ?V\" using someI_ex[of \"\\<lambda>U. open U \\<and> x \\<in> U \\<and> y \\<notin> U\"] ex by blast\n  show \"open (open_except x y)\" by (simp add: open_except_def vprop)\n  show \"x\\<in> open_except x y\" by (metis (full_types) open_except_def vprop)\n  show \"y\\<notin> open_except x y\" by (metis (full_types) open_except_def vprop)\nqed\n\nlemma open_except_set:\n  assumes \"finite A\"\n  and \"(x::'b::{t1_space}) \\<notin> A\"\nshows \"\\<exists>U. open U \\<and> x\\<in> U \\<and> U\\<inter> A = {}\"\nproof(intro exI conjI)\n  have \"\\<forall>y\\<in> A. x\\<noteq> y\" using assms by auto\n  let ?U = \"\\<Inter> y \\<in> A. open_except x y\"\n  show \"open ?U\"\n  proof (intro open_INT ballI, (simp add: assms))\n    fix y\n    assume \"y\\<in> A\"\n    show \"open (open_except x y)\" using \\<open>\\<forall>y\\<in> A. x\\<noteq> y\\<close> by (simp add: \\<open>y \\<in> A\\<close> open_exceptI)\n  qed\n  show \"x \\<in> (\\<Inter>y\\<in>A. open_except x y)\"\n  proof\n    fix y\n    assume \"y\\<in> A\"\n    show \"x\\<in>open_except x y\" using \\<open>\\<forall>y\\<in> A. x\\<noteq> y\\<close> by (simp add: \\<open>y \\<in> A\\<close> open_exceptI)\n  qed\n  have \"\\<forall>y\\<in>A. y\\<notin> ?U\" using \\<open>\\<forall>y\\<in> A. x\\<noteq> y\\<close> open_exceptI(3) by auto\n  thus \"(\\<Inter>y\\<in>A. open_except x y) \\<inter> A = {}\" by auto\nqed\n\ndefinition open_exclude_set where\n\"open_exclude_set x A = (if (\\<exists>U. open U \\<and> U\\<inter> A = {x}) then SOME U. open U \\<and> U \\<inter> A = {x} else {})\"\n\nlemma open_exclude_setI:\n  assumes \"\\<exists>U. open U \\<and> U\\<inter> A = {x}\"\nshows \"open (open_exclude_set x A)\" and \"(open_exclude_set x A) \\<inter> A = {x}\"\nproof -\n  let ?V = \"SOME U. open U \\<and> U \\<inter> A = {x}\"\n  have vprop: \"open ?V \\<and> ?V \\<inter> A = {x}\" using someI_ex[of \"\\<lambda>U. open U \\<and> U \\<inter> A = {x}\"] assms by blast\n  show \"open (open_exclude_set x A)\" by (simp add: open_exclude_set_def vprop)\n  show \"open_exclude_set x A \\<inter> A = {x}\" by (metis (mono_tags, lifting) open_exclude_set_def vprop)\nqed\n\nlemma open_exclude_finite:\n  assumes \"finite A\"\n  and \"(x::'b::{t1_space})\\<in> A\"\nshows open_set: \"open (open_exclude_set x A)\" and inter_x:\"(open_exclude_set x A) \\<inter> A = {x}\"\nproof -\n  have \"\\<exists>U. open U \\<and> U\\<inter> A = {x}\"\n  proof -\n    have \"\\<exists>U. open U \\<and> x\\<in> U \\<and> U\\<inter> (A-{x}) = {}\"\n    proof (rule open_except_set)\n      show \"finite (A -{x})\" using assms by auto\n      show \"x\\<notin> A -{x}\" by simp\n    qed\n    thus ?thesis using assms by auto\n  qed\n  thus \"open (open_exclude_set x A)\" and \"(open_exclude_set x A) \\<inter> A = {x}\" by (auto simp add: open_exclude_setI)\nqed\n\nsubsection \\<open>Initially trivial filtrations\\<close>\ntext \\<open>Intuitively, these are filtrations that can be used to denote the fact that there is no information at the start.\\<close>\n\ndefinition init_triv_filt::\"'a measure \\<Rightarrow> ('i::linorder_bot \\<Rightarrow> 'a measure) \\<Rightarrow> bool\" where\n  \"init_triv_filt M F \\<longleftrightarrow> filtration M F \\<and> sets (F bot) = {{}, space M}\"\n\nlemma triv_measurable_cst:\n  fixes f::\"'a\\<Rightarrow>'b::{t2_space}\"\n  assumes \"space N = space M\"\n  and \"space M \\<noteq> {}\"\n  and \"sets N = {{}, space M}\"\n  and \"f\\<in> measurable N borel\"\nshows \"\\<exists> c::'b. \\<forall>x\\<in> space N. f x = c\"\nproof -\n  have \"f `(space N) \\<noteq> {}\" using assms by (simp add: assms)\n  hence \"\\<exists> c. c\\<in> f`(space N)\" by auto\n  from this obtain c where \"c\\<in> f`(space N)\" by auto\n  have \"\\<forall>x \\<in> space N. f x = c\"\n  proof\n    fix x\n    assume \"x\\<in> space N\"\n    show \"f x = c\"\n    proof (rule ccontr)\n      assume \"f x \\<noteq> c\"\n      hence \"(\\<exists>U V. open U \\<and> open V \\<and> (f x) \\<in> U \\<and> c \\<in> V \\<and> U \\<inter> V = {})\" by (simp add: separation_t2)\n      from this obtain U and V where \"open U\" and \"open V\" and \"(f x) \\<in> U\" and \"c \\<in> V\" and \"U \\<inter> V = {}\" by blast\n      have \"(f -`V) \\<inter> space N = space N\"\n      proof -\n        have \"V\\<in> sets borel\" using \\<open>open V\\<close> unfolding borel_def by simp\n        hence \"(f -`V) \\<inter> space N \\<in> sets N\" using assms unfolding measurable_def by simp\n        show \"(f -`V) \\<inter> space N = space N\"\n        proof (rule ccontr)\n          assume \"(f -`V) \\<inter> space N \\<noteq> space N\"\n          hence \"(f -`V) \\<inter> space N = {}\" using assms \\<open>(f -`V) \\<inter> space N \\<in> sets N\\<close> by simp\n          thus False using \\<open>c\\<in>V\\<close> using \\<open>c \\<in> f ` space N\\<close> by blast\n        qed\n      qed\n      have \"((f-`U)\\<inter> space N) \\<inter> ((f-`V) \\<inter> space N) = {}\" using \\<open>U\\<inter>V = {}\\<close> by auto\n      moreover have \"(f -`U) \\<inter> space N \\<in> sets N\" using assms \\<open>open U\\<close> unfolding measurable_def by simp\n      ultimately have \"(f -`U) \\<inter> space N = {}\" using assms \\<open>(f -`V) \\<inter> space N = space N\\<close> by simp\n      thus False using \\<open>f x \\<in> U\\<close> \\<open>x \\<in> space N\\<close> by blast\n    qed\n  qed\n  thus \"\\<exists> c. \\<forall>x\\<in> space N. f x = c\" by auto\nqed\n\nlocale trivial_init_filtrated_prob_space = prob_space +\n  fixes F\n  assumes info_filtration: \"init_triv_filt M F\"\n\nsublocale trivial_init_filtrated_prob_space \\<subseteq> filtrated_prob_space\n  using info_filtration unfolding init_triv_filt_def by (unfold_locales, simp)\n\n\nlocale triv_init_disc_filtr_prob_space = prob_space +\n  fixes F\n  assumes info_disc_filtr: \"disc_filtr M F \\<and> sets (F bot) = {{}, space M}\"\n\nsublocale triv_init_disc_filtr_prob_space \\<subseteq> trivial_init_filtrated_prob_space\nproof unfold_locales\n  show \"init_triv_filt M F\" using info_disc_filtr bot_nat_def unfolding init_triv_filt_def disc_filtr_def\n    by (simp add: filtrationI)\n\nqed\n\n\nsublocale triv_init_disc_filtr_prob_space \\<subseteq> disc_filtr_prob_space\nproof unfold_locales\n  show \"disc_filtr M F\" using info_disc_filtr by simp\nqed\n\nlemma (in triv_init_disc_filtr_prob_space) adapted_init:\n  assumes \"borel_adapt_stoch_proc F x\"\n  shows \"\\<exists>c. \\<forall>w \\<in> space M. ((x 0 w)::real) = c\"\nproof -\n  have \"space M = space (F 0)\" using filtration\n    by (simp add: filtration_def subalgebra_def)\n  moreover have \"\\<exists>c. \\<forall>w \\<in> space (F 0). x 0 w = c\"\n  proof (rule triv_measurable_cst)\n    show \"space (F 0) = space M\" using \\<open>space M = space (F 0)\\<close> ..\n    show \"sets (F 0) = {{}, space M}\" using info_disc_filtr\n      by (simp add: init_triv_filt_def bot_nat_def)\n    show \"x 0 \\<in> borel_measurable (F 0)\" using assms by (simp add: adapt_stoch_proc_def)\n    show \"space M \\<noteq> {}\" by (simp add:not_empty)\n  qed\n  ultimately show ?thesis by simp\nqed\n\nsubsection \\<open>Filtration-equivalent measure spaces\\<close>\ntext \\<open>This is a relaxation of the notion of equivalent probability spaces, where equivalence is tested modulo a\nfiltration. Equivalent measure spaces agree on events that have a zero probability of occurring; here, filtration-equivalent\nmeasure spaces agree on such events when they belong to the filtration under consideration.\\<close>\n\ndefinition filt_equiv where\n\"filt_equiv F M N \\<longleftrightarrow> sets M = sets N \\<and> filtration M F  \\<and> (\\<forall> t A. A \\<in> sets (F t) \\<longrightarrow> (emeasure M A = 0) \\<longleftrightarrow> (emeasure N A = 0))\"\n\n\nlemma filt_equiv_space:\n  assumes \"filt_equiv F M N\"\n  shows \"space M = space N\" using assms unfolding filt_equiv_def\n filtration_def subalgebra_def by (meson sets_eq_imp_space_eq)\n\nlemma filt_equiv_sets:\n  assumes \"filt_equiv F M N\"\n  shows \"sets M = sets N\" using assms unfolding filt_equiv_def by simp\n\n\n\nlemma filt_equiv_filtration:\n  assumes \"filt_equiv F M N\"\n  shows \"filtration N F\" using assms unfolding filt_equiv_def filtration_def subalgebra_def\n  by (metis sets_eq_imp_space_eq)\n\n\n\n\nlemma (in filtrated_prob_space) AE_borel_eq:\nfixes f::\"'a\\<Rightarrow>real\"\nassumes \"f\\<in> borel_measurable (F t)\"\nand \"g\\<in> borel_measurable (F t)\"\nand \"AE w in M. f w = g w\"\nshows \"{w\\<in> space M. f w \\<noteq> g w} \\<in> sets (F t) \\<and> emeasure M {w\\<in> space M. f w \\<noteq> g w} = 0\"\nproof\n  show \"{w \\<in> space M. f w \\<noteq> g w} \\<in> sets (F t)\"\n  proof -\n    define minus where \"minus = (\\<lambda>w. (f w) - (g w))\"\n    have \"minus \\<in> borel_measurable (F t)\" unfolding minus_def using assms by simp\n    hence \"{w\\<in> space (F t). 0 < minus w} \\<in> sets (F t)\" using borel_measurable_iff_greater by auto\n    moreover have \"{w\\<in> space (F t). minus w < 0} \\<in> sets (F t)\" using borel_measurable_iff_less\n      \\<open>minus \\<in> borel_measurable (F t)\\<close> by auto\n    ultimately have \"{w\\<in> space (F t). 0 < minus w} \\<union> {w\\<in> space (F t). minus w < 0} \\<in> sets (F t)\" by simp\n    moreover have \"{w\\<in> space (F t). f w \\<noteq> g w} = {w\\<in> space (F t). 0 < minus w} \\<union> {w\\<in> space (F t). minus w < 0}\"\n    proof\n      show \"{w \\<in> space (F t). f w \\<noteq> g w} \\<subseteq> {w \\<in> space (F t). 0 < minus w} \\<union> {w \\<in> space (F t). minus w < 0}\"\n      proof\n        fix w\n        assume \"w \\<in> {w \\<in> space (F t). f w \\<noteq> g w}\"\n        hence \"w\\<in> space (F t)\" and \"f w \\<noteq> g w\" by auto\n        thus \"w\\<in> {w \\<in> space (F t). 0 < minus w} \\<union> {w \\<in> space (F t). minus w < 0}\" unfolding minus_def\n          by (cases \"f w < g w\") auto\n      qed\n      have \"{w \\<in> space (F t). 0 < minus w} \\<subseteq> {w \\<in> space (F t). f w \\<noteq> g w}\" unfolding minus_def by auto\n      moreover have \"{w \\<in> space (F t). minus w < 0} \\<subseteq> {w \\<in> space (F t). f w \\<noteq> g w}\" unfolding minus_def by auto\n      ultimately show \"{w \\<in> space (F t). 0 < minus w} \\<union> {w \\<in> space (F t). minus w < 0} \\<subseteq> {w \\<in> space (F t). f w \\<noteq> g w}\"\n        by simp\n    qed\n    moreover have \"space (F t) = space M\" using filtration unfolding filtration_def subalgebra_def by simp\n    ultimately show ?thesis by simp\n  qed\n  show \"emeasure M {w\\<in> space M. f w \\<noteq> g w} = 0\" by (metis (no_types) AE_iff_measurable assms(3) emeasure_notin_sets)\nqed\n\n\nlemma (in prob_space) filt_equiv_borel_AE_eq:\n  fixes f::\"'a\\<Rightarrow> real\"\n  assumes \"filt_equiv F M N\"\nand \"f\\<in> borel_measurable (F t)\"\nand \"g\\<in> borel_measurable (F t)\"\nand \"AE w in M. f w = g w\"\nshows \"AE w in N. f w = g w\"\nproof -\n  have set0: \"{w\\<in> space M. f w \\<noteq> g w} \\<in> sets (F t) \\<and> emeasure M {w\\<in> space M. f w \\<noteq> g w} = 0\"\n  proof (rule filtrated_prob_space.AE_borel_eq, (auto simp add: assms))\n    show \"filtrated_prob_space M F\" using assms unfolding filt_equiv_def\n      by (simp add: filtrated_prob_space_axioms.intro filtrated_prob_space_def prob_space_axioms)\n  qed\n  hence \"emeasure N {w\\<in> space M. f w \\<noteq> g w} = 0\" using assms unfolding filt_equiv_def by auto\n  moreover have \"{w\\<in> space M. f w \\<noteq> g w} \\<in> sets N\" using set0 assms unfolding filt_equiv_def\n    filtration_def subalgebra_def by auto\n  ultimately show ?thesis\n  proof -\n  have \"space M = space N\"\n    by (metis assms(1) filt_equiv_space)\n    then have \"\\<forall>p. almost_everywhere N p \\<or> {a \\<in> space N. \\<not> p a} \\<noteq> {a \\<in> space N. f a \\<noteq> g a}\"\n      using AE_iff_measurable \\<open>emeasure N {w \\<in> space M. f w \\<noteq> g w} = 0\\<close> \\<open>{w \\<in> space M. f w \\<noteq> g w} \\<in> sets N\\<close>\n      by auto\n    then show ?thesis\n      by metis\n  qed\nqed\n\nlemma filt_equiv_prob_space_subalgebra:\n  assumes \"prob_space N\"\n  and \"filt_equiv F M N\"\n  and \"sigma_finite_subalgebra M G\"\nshows \"sigma_finite_subalgebra N G\" unfolding sigma_finite_subalgebra_def\nproof\n  show \"subalgebra N G\"\n    by (metis assms(2) assms(3) filt_equiv_space filt_equiv_def sigma_finite_subalgebra_def subalgebra_def)\n  show \"sigma_finite_measure (restr_to_subalg N G)\" unfolding restr_to_subalg_def\n    by (metis \\<open>subalgebra N G\\<close> assms(1) finite_measure_def finite_measure_restr_to_subalg prob_space_def restr_to_subalg_def)\nqed\n\n\nlemma filt_equiv_measurable:\n  assumes \"filt_equiv F M N\"\n  and \"f\\<in> measurable M P\"\nshows \"f\\<in> measurable N P\" using assms unfolding filt_equiv_def measurable_def\nproof -\n  assume a1: \"sets M = sets N \\<and> Filtration.filtration M F \\<and> (\\<forall>t A. A \\<in> sets (F t) \\<longrightarrow> (emeasure M A = 0) = (emeasure N A = 0))\"\n  assume a2: \"f \\<in> {f \\<in> space M \\<rightarrow> space P. \\<forall>y\\<in>sets P. f -` y \\<inter> space M \\<in> sets M}\"\n  have \"space N = space M\"\n    using a1 by (metis (lifting) sets_eq_imp_space_eq)\n  then show \"f \\<in> {f \\<in> space N \\<rightarrow> space P. \\<forall>C\\<in>sets P. f -` C \\<inter> space N \\<in> sets N}\"\n    using a2 a1 by force\nqed\n\n\nlemma filt_equiv_imp_subalgebra:\n  assumes \"filt_equiv F M N\"\nshows \"subalgebra N M\" unfolding subalgebra_def\n  using assms filt_equiv_space filt_equiv_def by blast\n\n\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/DiscretePricing/Filtration.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8723473746782093, "lm_q2_score": 0.8354835411997897, "lm_q1q2_score": 0.7288318737524901}}
{"text": "(*  Title:      HOL/Multivariate_Analysis/Finite_Cartesian_Product.thy\n    Author:     Amine Chaieb, University of Cambridge\n*)\n\nsection {* Definition of finite Cartesian product types. *}\n\ntheory Finite_Cartesian_Product\nimports\n  Euclidean_Space\n  L2_Norm\n  \"~~/src/HOL/Library/Numeral_Type\"\nbegin\n\nsubsection {* Finite Cartesian products, with indexing and lambdas. *}\n\ntypedef ('a, 'b) vec = \"UNIV :: (('b::finite) \\<Rightarrow> 'a) set\"\n  morphisms vec_nth vec_lambda ..\n\nnotation\n  vec_nth (infixl \"$\" 90) and\n  vec_lambda (binder \"\\<chi>\" 10)\n\n(*\n  Translate \"'b ^ 'n\" into \"'b ^ ('n :: finite)\". When 'n has already more than\n  the finite type class write \"vec 'b 'n\"\n*)\n\nsyntax \"_finite_vec\" :: \"type \\<Rightarrow> type \\<Rightarrow> type\" (\"(_ ^/ _)\" [15, 16] 15)\n\nparse_translation {*\n  let\n    fun vec t u = Syntax.const @{type_syntax vec} $ t $ u;\n    fun finite_vec_tr [t, u] =\n      (case Term_Position.strip_positions u of\n        v as Free (x, _) =>\n          if Lexicon.is_tid x then\n            vec t (Syntax.const @{syntax_const \"_ofsort\"} $ v $\n              Syntax.const @{class_syntax finite})\n          else vec t u\n      | _ => vec t u)\n  in\n    [(@{syntax_const \"_finite_vec\"}, K finite_vec_tr)]\n  end\n*}\n\nlemma vec_eq_iff: \"(x = y) \\<longleftrightarrow> (\\<forall>i. x$i = y$i)\"\n  by (simp add: vec_nth_inject [symmetric] fun_eq_iff)\n\nlemma vec_lambda_beta [simp]: \"vec_lambda g $ i = g i\"\n  by (simp add: vec_lambda_inverse)\n\nlemma vec_lambda_unique: \"(\\<forall>i. f$i = g i) \\<longleftrightarrow> vec_lambda g = f\"\n  by (auto simp add: vec_eq_iff)\n\nlemma vec_lambda_eta: \"(\\<chi> i. (g$i)) = g\"\n  by (simp add: vec_eq_iff)\n\n\nsubsection {* Group operations and class instances *}\n\ninstantiation vec :: (zero, finite) zero\nbegin\n  definition \"0 \\<equiv> (\\<chi> i. 0)\"\n  instance ..\nend\n\ninstantiation vec :: (plus, finite) plus\nbegin\n  definition \"op + \\<equiv> (\\<lambda> x y. (\\<chi> i. x$i + y$i))\"\n  instance ..\nend\n\ninstantiation vec :: (minus, finite) minus\nbegin\n  definition \"op - \\<equiv> (\\<lambda> x y. (\\<chi> i. x$i - y$i))\"\n  instance ..\nend\n\ninstantiation vec :: (uminus, finite) uminus\nbegin\n  definition \"uminus \\<equiv> (\\<lambda> x. (\\<chi> i. - (x$i)))\"\n  instance ..\nend\n\nlemma zero_index [simp]: \"0 $ i = 0\"\n  unfolding zero_vec_def by simp\n\nlemma vector_add_component [simp]: \"(x + y)$i = x$i + y$i\"\n  unfolding plus_vec_def by simp\n\nlemma vector_minus_component [simp]: \"(x - y)$i = x$i - y$i\"\n  unfolding minus_vec_def by simp\n\nlemma vector_uminus_component [simp]: \"(- x)$i = - (x$i)\"\n  unfolding uminus_vec_def by simp\n\ninstance vec :: (semigroup_add, finite) semigroup_add\n  by default (simp add: vec_eq_iff add.assoc)\n\ninstance vec :: (ab_semigroup_add, finite) ab_semigroup_add\n  by default (simp add: vec_eq_iff add.commute)\n\ninstance vec :: (monoid_add, finite) monoid_add\n  by default (simp_all add: vec_eq_iff)\n\ninstance vec :: (comm_monoid_add, finite) comm_monoid_add\n  by default (simp add: vec_eq_iff)\n\ninstance vec :: (cancel_semigroup_add, finite) cancel_semigroup_add\n  by default (simp_all add: vec_eq_iff)\n\ninstance vec :: (cancel_ab_semigroup_add, finite) cancel_ab_semigroup_add\n  by default (simp add: vec_eq_iff)\n\ninstance vec :: (cancel_comm_monoid_add, finite) cancel_comm_monoid_add ..\n\ninstance vec :: (group_add, finite) group_add\n  by default (simp_all add: vec_eq_iff)\n\ninstance vec :: (ab_group_add, finite) ab_group_add\n  by default (simp_all add: vec_eq_iff)\n\n\nsubsection {* Real vector space *}\n\ninstantiation vec :: (real_vector, finite) real_vector\nbegin\n\ndefinition \"scaleR \\<equiv> (\\<lambda> r x. (\\<chi> i. scaleR r (x$i)))\"\n\nlemma vector_scaleR_component [simp]: \"(scaleR r x)$i = scaleR r (x$i)\"\n  unfolding scaleR_vec_def by simp\n\ninstance\n  by default (simp_all add: vec_eq_iff scaleR_left_distrib scaleR_right_distrib)\n\nend\n\n\nsubsection {* Topological space *}\n\ninstantiation vec :: (topological_space, finite) topological_space\nbegin\n\ndefinition\n  \"open (S :: ('a ^ 'b) set) \\<longleftrightarrow>\n    (\\<forall>x\\<in>S. \\<exists>A. (\\<forall>i. open (A i) \\<and> x$i \\<in> A i) \\<and>\n      (\\<forall>y. (\\<forall>i. y$i \\<in> A i) \\<longrightarrow> y \\<in> S))\"\n\ninstance proof\n  show \"open (UNIV :: ('a ^ 'b) set)\"\n    unfolding open_vec_def by auto\nnext\n  fix S T :: \"('a ^ 'b) set\"\n  assume \"open S\" \"open T\" thus \"open (S \\<inter> T)\"\n    unfolding open_vec_def\n    apply clarify\n    apply (drule (1) bspec)+\n    apply (clarify, rename_tac Sa Ta)\n    apply (rule_tac x=\"\\<lambda>i. Sa i \\<inter> Ta i\" in exI)\n    apply (simp add: open_Int)\n    done\nnext\n  fix K :: \"('a ^ 'b) set set\"\n  assume \"\\<forall>S\\<in>K. open S\" thus \"open (\\<Union>K)\"\n    unfolding open_vec_def\n    apply clarify\n    apply (drule (1) bspec)\n    apply (drule (1) bspec)\n    apply clarify\n    apply (rule_tac x=A in exI)\n    apply fast\n    done\nqed\n\nend\n\nlemma open_vector_box: \"\\<forall>i. open (S i) \\<Longrightarrow> open {x. \\<forall>i. x $ i \\<in> S i}\"\n  unfolding open_vec_def by auto\n\nlemma open_vimage_vec_nth: \"open S \\<Longrightarrow> open ((\\<lambda>x. x $ i) -` S)\"\n  unfolding open_vec_def\n  apply clarify\n  apply (rule_tac x=\"\\<lambda>k. if k = i then S else UNIV\" in exI, simp)\n  done\n\nlemma closed_vimage_vec_nth: \"closed S \\<Longrightarrow> closed ((\\<lambda>x. x $ i) -` S)\"\n  unfolding closed_open vimage_Compl [symmetric]\n  by (rule open_vimage_vec_nth)\n\nlemma closed_vector_box: \"\\<forall>i. closed (S i) \\<Longrightarrow> closed {x. \\<forall>i. x $ i \\<in> S i}\"\nproof -\n  have \"{x. \\<forall>i. x $ i \\<in> S i} = (\\<Inter>i. (\\<lambda>x. x $ i) -` S i)\" by auto\n  thus \"\\<forall>i. closed (S i) \\<Longrightarrow> closed {x. \\<forall>i. x $ i \\<in> S i}\"\n    by (simp add: closed_INT closed_vimage_vec_nth)\nqed\n\nlemma tendsto_vec_nth [tendsto_intros]:\n  assumes \"((\\<lambda>x. f x) ---> a) net\"\n  shows \"((\\<lambda>x. f x $ i) ---> a $ i) net\"\nproof (rule topological_tendstoI)\n  fix S assume \"open S\" \"a $ i \\<in> S\"\n  then have \"open ((\\<lambda>y. y $ i) -` S)\" \"a \\<in> ((\\<lambda>y. y $ i) -` S)\"\n    by (simp_all add: open_vimage_vec_nth)\n  with assms have \"eventually (\\<lambda>x. f x \\<in> (\\<lambda>y. y $ i) -` S) net\"\n    by (rule topological_tendstoD)\n  then show \"eventually (\\<lambda>x. f x $ i \\<in> S) net\"\n    by simp\nqed\n\nlemma isCont_vec_nth [simp]: \"isCont f a \\<Longrightarrow> isCont (\\<lambda>x. f x $ i) a\"\n  unfolding isCont_def by (rule tendsto_vec_nth)\n\nlemma vec_tendstoI:\n  assumes \"\\<And>i. ((\\<lambda>x. f x $ i) ---> a $ i) net\"\n  shows \"((\\<lambda>x. f x) ---> a) net\"\nproof (rule topological_tendstoI)\n  fix S assume \"open S\" and \"a \\<in> S\"\n  then obtain A where A: \"\\<And>i. open (A i)\" \"\\<And>i. a $ i \\<in> A i\"\n    and S: \"\\<And>y. \\<forall>i. y $ i \\<in> A i \\<Longrightarrow> y \\<in> S\"\n    unfolding open_vec_def by metis\n  have \"\\<And>i. eventually (\\<lambda>x. f x $ i \\<in> A i) net\"\n    using assms A by (rule topological_tendstoD)\n  hence \"eventually (\\<lambda>x. \\<forall>i. f x $ i \\<in> A i) net\"\n    by (rule eventually_all_finite)\n  thus \"eventually (\\<lambda>x. f x \\<in> S) net\"\n    by (rule eventually_elim1, simp add: S)\nqed\n\nlemma tendsto_vec_lambda [tendsto_intros]:\n  assumes \"\\<And>i. ((\\<lambda>x. f x i) ---> a i) net\"\n  shows \"((\\<lambda>x. \\<chi> i. f x i) ---> (\\<chi> i. a i)) net\"\n  using assms by (simp add: vec_tendstoI)\n\nlemma open_image_vec_nth: assumes \"open S\" shows \"open ((\\<lambda>x. x $ i) ` S)\"\nproof (rule openI)\n  fix a assume \"a \\<in> (\\<lambda>x. x $ i) ` S\"\n  then obtain z where \"a = z $ i\" and \"z \\<in> S\" ..\n  then obtain A where A: \"\\<forall>i. open (A i) \\<and> z $ i \\<in> A i\"\n    and S: \"\\<forall>y. (\\<forall>i. y $ i \\<in> A i) \\<longrightarrow> y \\<in> S\"\n    using `open S` unfolding open_vec_def by auto\n  hence \"A i \\<subseteq> (\\<lambda>x. x $ i) ` S\"\n    by (clarsimp, rule_tac x=\"\\<chi> j. if j = i then x else z $ j\" in image_eqI,\n      simp_all)\n  hence \"open (A i) \\<and> a \\<in> A i \\<and> A i \\<subseteq> (\\<lambda>x. x $ i) ` S\"\n    using A `a = z $ i` by simp\n  then show \"\\<exists>T. open T \\<and> a \\<in> T \\<and> T \\<subseteq> (\\<lambda>x. x $ i) ` S\" by - (rule exI)\nqed\n\ninstance vec :: (perfect_space, finite) perfect_space\nproof\n  fix x :: \"'a ^ 'b\" show \"\\<not> open {x}\"\n  proof\n    assume \"open {x}\"\n    hence \"\\<forall>i. open ((\\<lambda>x. x $ i) ` {x})\" by (fast intro: open_image_vec_nth)   \n    hence \"\\<forall>i. open {x $ i}\" by simp\n    thus \"False\" by (simp add: not_open_singleton)\n  qed\nqed\n\n\nsubsection {* Metric space *}\n\ninstantiation vec :: (metric_space, finite) metric_space\nbegin\n\ndefinition\n  \"dist x y = setL2 (\\<lambda>i. dist (x$i) (y$i)) UNIV\"\n\nlemma dist_vec_nth_le: \"dist (x $ i) (y $ i) \\<le> dist x y\"\n  unfolding dist_vec_def by (rule member_le_setL2) simp_all\n\ninstance proof\n  fix x y :: \"'a ^ 'b\"\n  show \"dist x y = 0 \\<longleftrightarrow> x = y\"\n    unfolding dist_vec_def\n    by (simp add: setL2_eq_0_iff vec_eq_iff)\nnext\n  fix x y z :: \"'a ^ 'b\"\n  show \"dist x y \\<le> dist x z + dist y z\"\n    unfolding dist_vec_def\n    apply (rule order_trans [OF _ setL2_triangle_ineq])\n    apply (simp add: setL2_mono dist_triangle2)\n    done\nnext\n  fix S :: \"('a ^ 'b) set\"\n  show \"open S \\<longleftrightarrow> (\\<forall>x\\<in>S. \\<exists>e>0. \\<forall>y. dist y x < e \\<longrightarrow> y \\<in> S)\"\n  proof\n    assume \"open S\" show \"\\<forall>x\\<in>S. \\<exists>e>0. \\<forall>y. dist y x < e \\<longrightarrow> y \\<in> S\"\n    proof\n      fix x assume \"x \\<in> S\"\n      obtain A where A: \"\\<forall>i. open (A i)\" \"\\<forall>i. x $ i \\<in> A i\"\n        and S: \"\\<forall>y. (\\<forall>i. y $ i \\<in> A i) \\<longrightarrow> y \\<in> S\"\n        using `open S` and `x \\<in> S` unfolding open_vec_def by metis\n      have \"\\<forall>i\\<in>UNIV. \\<exists>r>0. \\<forall>y. dist y (x $ i) < r \\<longrightarrow> y \\<in> A i\"\n        using A unfolding open_dist by simp\n      hence \"\\<exists>r. \\<forall>i\\<in>UNIV. 0 < r i \\<and> (\\<forall>y. dist y (x $ i) < r i \\<longrightarrow> y \\<in> A i)\"\n        by (rule finite_set_choice [OF finite])\n      then obtain r where r1: \"\\<forall>i. 0 < r i\"\n        and r2: \"\\<forall>i y. dist y (x $ i) < r i \\<longrightarrow> y \\<in> A i\" by fast\n      have \"0 < Min (range r) \\<and> (\\<forall>y. dist y x < Min (range r) \\<longrightarrow> y \\<in> S)\"\n        by (simp add: r1 r2 S le_less_trans [OF dist_vec_nth_le])\n      thus \"\\<exists>e>0. \\<forall>y. dist y x < e \\<longrightarrow> y \\<in> S\" ..\n    qed\n  next\n    assume *: \"\\<forall>x\\<in>S. \\<exists>e>0. \\<forall>y. dist y x < e \\<longrightarrow> y \\<in> S\" show \"open S\"\n    proof (unfold open_vec_def, rule)\n      fix x assume \"x \\<in> S\"\n      then obtain e where \"0 < e\" and S: \"\\<forall>y. dist y x < e \\<longrightarrow> y \\<in> S\"\n        using * by fast\n      def r \\<equiv> \"\\<lambda>i::'b. e / sqrt (of_nat CARD('b))\"\n      from `0 < e` have r: \"\\<forall>i. 0 < r i\"\n        unfolding r_def by simp_all\n      from `0 < e` have e: \"e = setL2 r UNIV\"\n        unfolding r_def by (simp add: setL2_constant)\n      def A \\<equiv> \"\\<lambda>i. {y. dist (x $ i) y < r i}\"\n      have \"\\<forall>i. open (A i) \\<and> x $ i \\<in> A i\"\n        unfolding A_def by (simp add: open_ball r)\n      moreover have \"\\<forall>y. (\\<forall>i. y $ i \\<in> A i) \\<longrightarrow> y \\<in> S\"\n        by (simp add: A_def S dist_vec_def e setL2_strict_mono dist_commute)\n      ultimately show \"\\<exists>A. (\\<forall>i. open (A i) \\<and> x $ i \\<in> A i) \\<and>\n        (\\<forall>y. (\\<forall>i. y $ i \\<in> A i) \\<longrightarrow> y \\<in> S)\" by metis\n    qed\n  qed\nqed\n\nend\n\nlemma Cauchy_vec_nth:\n  \"Cauchy (\\<lambda>n. X n) \\<Longrightarrow> Cauchy (\\<lambda>n. X n $ i)\"\n  unfolding Cauchy_def by (fast intro: le_less_trans [OF dist_vec_nth_le])\n\nlemma vec_CauchyI:\n  fixes X :: \"nat \\<Rightarrow> 'a::metric_space ^ 'n\"\n  assumes X: \"\\<And>i. Cauchy (\\<lambda>n. X n $ i)\"\n  shows \"Cauchy (\\<lambda>n. X n)\"\nproof (rule metric_CauchyI)\n  fix r :: real assume \"0 < r\"\n  hence \"0 < r / of_nat CARD('n)\" (is \"0 < ?s\") by simp\n  def N \\<equiv> \"\\<lambda>i. LEAST N. \\<forall>m\\<ge>N. \\<forall>n\\<ge>N. dist (X m $ i) (X n $ i) < ?s\"\n  def M \\<equiv> \"Max (range N)\"\n  have \"\\<And>i. \\<exists>N. \\<forall>m\\<ge>N. \\<forall>n\\<ge>N. dist (X m $ i) (X n $ i) < ?s\"\n    using X `0 < ?s` by (rule metric_CauchyD)\n  hence \"\\<And>i. \\<forall>m\\<ge>N i. \\<forall>n\\<ge>N i. dist (X m $ i) (X n $ i) < ?s\"\n    unfolding N_def by (rule LeastI_ex)\n  hence M: \"\\<And>i. \\<forall>m\\<ge>M. \\<forall>n\\<ge>M. dist (X m $ i) (X n $ i) < ?s\"\n    unfolding M_def by simp\n  {\n    fix m n :: nat\n    assume \"M \\<le> m\" \"M \\<le> n\"\n    have \"dist (X m) (X n) = setL2 (\\<lambda>i. dist (X m $ i) (X n $ i)) UNIV\"\n      unfolding dist_vec_def ..\n    also have \"\\<dots> \\<le> setsum (\\<lambda>i. dist (X m $ i) (X n $ i)) UNIV\"\n      by (rule setL2_le_setsum [OF zero_le_dist])\n    also have \"\\<dots> < setsum (\\<lambda>i::'n. ?s) UNIV\"\n      by (rule setsum_strict_mono, simp_all add: M `M \\<le> m` `M \\<le> n`)\n    also have \"\\<dots> = r\"\n      by simp\n    finally have \"dist (X m) (X n) < r\" .\n  }\n  hence \"\\<forall>m\\<ge>M. \\<forall>n\\<ge>M. dist (X m) (X n) < r\"\n    by simp\n  then show \"\\<exists>M. \\<forall>m\\<ge>M. \\<forall>n\\<ge>M. dist (X m) (X n) < r\" ..\nqed\n\ninstance vec :: (complete_space, finite) complete_space\nproof\n  fix X :: \"nat \\<Rightarrow> 'a ^ 'b\" assume \"Cauchy X\"\n  have \"\\<And>i. (\\<lambda>n. X n $ i) ----> lim (\\<lambda>n. X n $ i)\"\n    using Cauchy_vec_nth [OF `Cauchy X`]\n    by (simp add: Cauchy_convergent_iff convergent_LIMSEQ_iff)\n  hence \"X ----> vec_lambda (\\<lambda>i. lim (\\<lambda>n. X n $ i))\"\n    by (simp add: vec_tendstoI)\n  then show \"convergent X\"\n    by (rule convergentI)\nqed\n\n\nsubsection {* Normed vector space *}\n\ninstantiation vec :: (real_normed_vector, finite) real_normed_vector\nbegin\n\ndefinition \"norm x = setL2 (\\<lambda>i. norm (x$i)) UNIV\"\n\ndefinition \"sgn (x::'a^'b) = scaleR (inverse (norm x)) x\"\n\ninstance proof\n  fix a :: real and x y :: \"'a ^ 'b\"\n  show \"norm x = 0 \\<longleftrightarrow> x = 0\"\n    unfolding norm_vec_def\n    by (simp add: setL2_eq_0_iff vec_eq_iff)\n  show \"norm (x + y) \\<le> norm x + norm y\"\n    unfolding norm_vec_def\n    apply (rule order_trans [OF _ setL2_triangle_ineq])\n    apply (simp add: setL2_mono norm_triangle_ineq)\n    done\n  show \"norm (scaleR a x) = \\<bar>a\\<bar> * norm x\"\n    unfolding norm_vec_def\n    by (simp add: setL2_right_distrib)\n  show \"sgn x = scaleR (inverse (norm x)) x\"\n    by (rule sgn_vec_def)\n  show \"dist x y = norm (x - y)\"\n    unfolding dist_vec_def norm_vec_def\n    by (simp add: dist_norm)\nqed\n\nend\n\nlemma norm_nth_le: \"norm (x $ i) \\<le> norm x\"\nunfolding norm_vec_def\nby (rule member_le_setL2) simp_all\n\nlemma bounded_linear_vec_nth: \"bounded_linear (\\<lambda>x. x $ i)\"\napply default\napply (rule vector_add_component)\napply (rule vector_scaleR_component)\napply (rule_tac x=\"1\" in exI, simp add: norm_nth_le)\ndone\n\ninstance vec :: (banach, finite) banach ..\n\n\nsubsection {* Inner product space *}\n\ninstantiation vec :: (real_inner, finite) real_inner\nbegin\n\ndefinition \"inner x y = setsum (\\<lambda>i. inner (x$i) (y$i)) UNIV\"\n\ninstance proof\n  fix r :: real and x y z :: \"'a ^ 'b\"\n  show \"inner x y = inner y x\"\n    unfolding inner_vec_def\n    by (simp add: inner_commute)\n  show \"inner (x + y) z = inner x z + inner y z\"\n    unfolding inner_vec_def\n    by (simp add: inner_add_left setsum.distrib)\n  show \"inner (scaleR r x) y = r * inner x y\"\n    unfolding inner_vec_def\n    by (simp add: setsum_right_distrib)\n  show \"0 \\<le> inner x x\"\n    unfolding inner_vec_def\n    by (simp add: setsum_nonneg)\n  show \"inner x x = 0 \\<longleftrightarrow> x = 0\"\n    unfolding inner_vec_def\n    by (simp add: vec_eq_iff setsum_nonneg_eq_0_iff)\n  show \"norm x = sqrt (inner x x)\"\n    unfolding inner_vec_def norm_vec_def setL2_def\n    by (simp add: power2_norm_eq_inner)\nqed\n\nend\n\n\nsubsection {* Euclidean space *}\n\ntext {* Vectors pointing along a single axis. *}\n\ndefinition \"axis k x = (\\<chi> i. if i = k then x else 0)\"\n\nlemma axis_nth [simp]: \"axis i x $ i = x\"\n  unfolding axis_def by simp\n\nlemma axis_eq_axis: \"axis i x = axis j y \\<longleftrightarrow> x = y \\<and> i = j \\<or> x = 0 \\<and> y = 0\"\n  unfolding axis_def vec_eq_iff by auto\n\nlemma inner_axis_axis:\n  \"inner (axis i x) (axis j y) = (if i = j then inner x y else 0)\"\n  unfolding inner_vec_def\n  apply (cases \"i = j\")\n  apply clarsimp\n  apply (subst setsum.remove [of _ j], simp_all)\n  apply (rule setsum.neutral, simp add: axis_def)\n  apply (rule setsum.neutral, simp add: axis_def)\n  done\n\nlemma setsum_single:\n  assumes \"finite A\" and \"k \\<in> A\" and \"f k = y\"\n  assumes \"\\<And>i. i \\<in> A \\<Longrightarrow> i \\<noteq> k \\<Longrightarrow> f i = 0\"\n  shows \"(\\<Sum>i\\<in>A. f i) = y\"\n  apply (subst setsum.remove [OF assms(1,2)])\n  apply (simp add: setsum.neutral assms(3,4))\n  done\n\nlemma inner_axis: \"inner x (axis i y) = inner (x $ i) y\"\n  unfolding inner_vec_def\n  apply (rule_tac k=i in setsum_single)\n  apply simp_all\n  apply (simp add: axis_def)\n  done\n\ninstantiation vec :: (euclidean_space, finite) euclidean_space\nbegin\n\ndefinition \"Basis = (\\<Union>i. \\<Union>u\\<in>Basis. {axis i u})\"\n\ninstance proof\n  show \"(Basis :: ('a ^ 'b) set) \\<noteq> {}\"\n    unfolding Basis_vec_def by simp\nnext\n  show \"finite (Basis :: ('a ^ 'b) set)\"\n    unfolding Basis_vec_def by simp\nnext\n  fix u v :: \"'a ^ '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_vec_def\n    by (auto simp add: inner_axis_axis axis_eq_axis inner_Basis)\nnext\n  fix x :: \"'a ^ 'b\"\n  show \"(\\<forall>u\\<in>Basis. inner x u = 0) \\<longleftrightarrow> x = 0\"\n    unfolding Basis_vec_def\n    by (simp add: inner_axis euclidean_all_zero_iff vec_eq_iff)\nqed\n\nlemma DIM_cart[simp]: \"DIM('a^'b) = CARD('b) * DIM('a)\"\n  apply (simp add: Basis_vec_def)\n  apply (subst card_UN_disjoint)\n     apply simp\n    apply simp\n   apply (auto simp: axis_eq_axis) [1]\n  apply (subst card_UN_disjoint)\n     apply (auto simp: axis_eq_axis)\n  done\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/Multivariate_Analysis/Finite_Cartesian_Product.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473713594991, "lm_q2_score": 0.8354835371034368, "lm_q1q2_score": 0.7288318674063197}}
{"text": "theory OneThirdRuleDefs\nimports \"../HOModel\"\nbegin\n\nsection {* Verification of the \\emph{One-Third Rule} Consensus Algorithm *}\n\ntext {*\n  We now apply the framework introduced so far to the verification of\n  concrete algorithms, starting with algorithm \\emph{One-Third Rule},\n  which is one of the simplest algorithms presented in~\\cite{charron:heardof}.\n  Nevertheless, the algorithm has some interesting characteristics:\n  it ensures safety (i.e., the Integrity and Agreement) properties in the\n  presence of arbitrary benign faults, and if everything works perfectly,\n  it terminates in just two rounds. \\emph{One-Third Rule} is an uncoordinated\n  algorithm tolerating benign faults, hence SHO or coordinator sets do not\n  play a role in its definition.\n*}\n\n\nsubsection {* Model of the Algorithm *}\n\ntext {*\n  We begin by introducing an anonymous type of processes of finite\n  cardinality that will instantiate the type variable @{text \"'proc\"}\n  of the generic HO model.\n*}\n\ntypedecl Proc -- {* the set of processes *}\naxiomatization where Proc_finite: \"OFCLASS(Proc, finite_class)\"\ninstance Proc :: finite by (rule Proc_finite)\n\nabbreviation\n  \"N \\<equiv> card (UNIV::Proc set)\"\n\ntext {*\n  The state of each process consists of two fields: @{text x} holds\n  the current value proposed by the process and @{text decide} the\n  value (if any, hence the option type) it has decided.\n*}\n\nrecord 'val pstate =\n  x :: \"'val\"\n  decide :: \"'val option\"\n\ntext {*\n  The initial value of field @{text x} is unconstrained, but no decision\n  has been taken initially.\n*}\n\ndefinition OTR_initState where\n  \"OTR_initState p st \\<equiv> decide st = None\"\n\ntext {*\n  Given a vector @{text msgs} of values (possibly null) received from \n  each process, @{term \"HOV msgs v\"} denotes the set of processes from\n  which value @{text v} was received.\n*}\n\ndefinition HOV :: \"(Proc \\<Rightarrow> 'val option) \\<Rightarrow> 'val \\<Rightarrow> Proc set\" where\n  \"HOV msgs v \\<equiv> { q . msgs q = Some v }\"\n\ntext {*\n  @{term \"MFR msgs v\"} (``most frequently received'') holds for\n  vector @{text msgs} if no value has been received more frequently\n  than @{text v}.\n\n  Some such value always exists, since there is only a finite set of\n  processes and thus a finite set of possible cardinalities of the\n  sets @{term \"HOV msgs v\"}.\n*}\n\ndefinition MFR :: \"(Proc \\<Rightarrow> 'val option) \\<Rightarrow> 'val \\<Rightarrow> bool\" where\n  \"MFR msgs v \\<equiv> \\<forall>w. card (HOV msgs w) \\<le> card (HOV msgs v)\"\n\nlemma MFR_exists: \"\\<exists>v. MFR msgs v\"\nproof -\n  let ?cards = \"{ card (HOV msgs v) | v . True }\"\n  let ?mfr = \"Max ?cards\"\n  have \"\\<forall>v. card (HOV msgs v) \\<le> N\" by (auto intro: card_mono)\n  hence \"?cards \\<subseteq> { 0 .. N }\" by auto\n  hence fin: \"finite ?cards\" by (metis atLeast0AtMost finite_atMost finite_subset)\n  hence \"?mfr \\<in> ?cards\" by (rule Max_in) auto\n  then obtain v where v: \"?mfr = card (HOV msgs v)\" by auto\n  have \"MFR msgs v\"\n  proof (auto simp: MFR_def)\n    fix w\n    from fin have \"card (HOV msgs w) \\<le> ?mfr\" by (rule Max_ge) auto\n    thus \"card (HOV msgs w) \\<le> card (HOV msgs v)\" by (unfold v)\n  qed\n  thus ?thesis ..\nqed\n\ntext {*\n  Also, if a process has heard from at least one other process,\n  the most frequently received values are among the received messages.\n*}\n\nlemma MFR_in_msgs:\n  assumes HO:\"HOs m p \\<noteq> {}\"\n      and v: \"MFR (HOrcvdMsgs OTR_M m p (HOs m p) (rho m)) v\"\n             (is \"MFR ?msgs v\")\n  shows \"\\<exists>q \\<in> HOs m p. v = the (?msgs q)\"\nproof -\n  from HO obtain q where q: \"q \\<in> HOs m p\"\n    by auto\n  with v have \"HOV ?msgs (the (?msgs q)) \\<noteq> {}\"\n    by (auto simp: HOV_def HOrcvdMsgs_def)\n  hence HOp: \"0 < card (HOV ?msgs (the (?msgs q)))\"\n    by auto\n  also from v have \"\\<dots> \\<le> card (HOV ?msgs v)\"\n    by (simp add: MFR_def)\n  finally have \"HOV ?msgs v \\<noteq> {}\"\n    by auto\n  thus ?thesis\n    by (auto simp: HOV_def HOrcvdMsgs_def)\nqed\n\ntext {*\n  @{term \"TwoThirds msgs v\"} holds if value @{text v} has been\n  received from more than $2/3$ of all processes.\n*}\n\ndefinition TwoThirds where\n  \"TwoThirds msgs v \\<equiv> (2*N) div 3 < card (HOV msgs v)\"\n\ntext {*\n  The next-state relation of algorithm \\emph{One-Third Rule} for every process\n  is defined as follows:\n  if the process has received values from more than $2/3$ of all processes,\n  the @{text x} field is set to the smallest among the most frequently received\n  values, and the process decides value $v$ if it received $v$ from more than\n  $2/3$ of all processes. If @{text p} hasn't heard from more than $2/3$ of\n  all processes, the state remains unchanged.\n  (Note that @{text Some} is the constructor of the option datatype, whereas\n  @{text \"\\<some>\"} is Hilbert's choice operator.)\n  We require the type of values to be linearly ordered so that the minimum\n  is guaranteed to be well-defined.\n*}\n\ndefinition OTR_nextState where\n  \"OTR_nextState r p (st::('val::linorder) pstate) msgs st' \\<equiv> \n   if (2*N) div 3 < card {q. msgs q \\<noteq> None}\n   then st' = \\<lparr> x = Min {v . MFR msgs v},\n          decide = (if (\\<exists>v. TwoThirds msgs v)\n                    then Some (\\<some>v. TwoThirds msgs v)\n                    else decide st) \\<rparr>\n   else st' = st\"\n\ntext {*\n  The message sending function is very simple: at every round, every process\n  sends its current proposal (field @{text x} of its local state) to all \n  processes.\n*}\n\ndefinition OTR_sendMsg where\n  \"OTR_sendMsg r p q st \\<equiv> x st\"\n\nsubsection {* Communication Predicate for \\emph{One-Third Rule} *}\n\ntext {*\n  We now define the communication predicate for the \\emph{One-Third Rule}\n  algorithm to be correct.\n  It requires that, infinitely often, there is a round where all processes\n  receive messages from the same set @{text \"\\<Pi>\"} of processes where @{text \"\\<Pi>\"}\n  contains more than two thirds of all processes.\n  The ``per-round'' part of the communication predicate is trivial.\n*}\n\ndefinition OTR_commPerRd where\n  \"OTR_commPerRd HOrs \\<equiv> True\"\n\ndefinition OTR_commGlobal where\n  \"OTR_commGlobal HOs \\<equiv>\n    \\<forall>r. \\<exists>r0 \\<Pi>. r0 \\<ge> r \\<and> (\\<forall>p. HOs r0 p = \\<Pi>) \\<and> card \\<Pi> > (2*N) div 3\"\n\nsubsection {* The \\emph{One-Third Rule} Heard-Of Machine *}\n\ntext {*\n  We now define the HO machine for the \\emph{One-Third Rule} algorithm\n  by assembling the algorithm definition and its communication-predicate.\n  Because this is an uncoordinated algorithm, the @{text crd} arguments\n  of the initial- and next-state predicates are unused.\n*}\n\ndefinition OTR_HOMachine where\n  \"OTR_HOMachine =\n    \\<lparr> CinitState =  (\\<lambda> p st crd. OTR_initState p st),\n     sendMsg =  OTR_sendMsg,\n     CnextState = (\\<lambda> r p st msgs crd st'. OTR_nextState r p st msgs st'),\n     HOcommPerRd = OTR_commPerRd,\n     HOcommGlobal = OTR_commGlobal \\<rparr>\"\n\nabbreviation \"OTR_M \\<equiv> OTR_HOMachine::(Proc, 'val::linorder pstate, 'val) HOMachine\"\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/Heard_Of/otr/OneThirdRuleDefs.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8723473614033683, "lm_q2_score": 0.8354835452961425, "lm_q1q2_score": 0.7288318662350215}}
{"text": "theory Variable\n  imports Main\nbegin\n\ndatatype var = V nat\n\nprimrec fresh' :: \"var set \\<Rightarrow> nat \\<Rightarrow> nat\" where\n  \"fresh' xs 0 = 0\"\n| \"fresh' xs (Suc x) = (if V (Suc x) \\<in> xs then fresh' (xs - {V (Suc x)}) x else Suc x)\"\n\ndefinition fresh :: \"var set \\<Rightarrow> var\" where\n  \"fresh xs = V (fresh' xs (card xs))\"\n\nabbreviation extend_set :: \"var set \\<Rightarrow> var set\" where\n  \"extend_set vs \\<equiv> insert (fresh vs) vs\"\n\n\n\nlemma [simp]: \"finite xs \\<Longrightarrow> fresh' xs x \\<noteq> Suc x\"\nproof -\n  assume \"finite xs\"\n  hence \"fresh' xs x < Suc x\" by simp\n  thus ?thesis by simp\nqed\n\nlemma [simp]: \"finite xs \\<Longrightarrow> x = card xs \\<Longrightarrow> V (fresh' xs x) \\<notin> xs\"\nproof (induction x arbitrary: xs)\n  case (Suc x)\n  moreover hence \"finite (xs - {V (Suc x)})\" by simp\n  moreover from Suc have \"V (Suc x) \\<in> xs \\<Longrightarrow> x = card (xs - {V (Suc x)})\" by simp\n  ultimately have \"V (Suc x) \\<in> xs \\<Longrightarrow> V (fresh' (xs - {V (Suc x)}) x) \\<notin> xs - {V (Suc x)}\" by metis\n  moreover from Suc(2) have \"fresh' (xs - {V (Suc x)}) x \\<noteq> Suc x\" by simp\n  ultimately show ?case by simp\nqed simp_all\n\nlemma fresh_is_fresh [simp]: \"finite xs \\<Longrightarrow> fresh xs \\<notin> xs\"\n  by (simp add: fresh_def)\n\nend", "meta": {"author": "xtreme-james-cooper", "repo": "Lambda-RAM-Compiler", "sha": "24125435949fa71dfc5faafdb236d28a098beefc", "save_path": "github-repos/isabelle/xtreme-james-cooper-Lambda-RAM-Compiler", "path": "github-repos/isabelle/xtreme-james-cooper-Lambda-RAM-Compiler/Lambda-RAM-Compiler-24125435949fa71dfc5faafdb236d28a098beefc/00Utils/Variable.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505351008906, "lm_q2_score": 0.8056321889812553, "lm_q1q2_score": 0.7288155908563944}}
{"text": "theory classical_axioms imports FOL\nbegin\n\nlemma ax1:\\<open>A\\<longrightarrow>(B\\<longrightarrow>A)\\<close>\n  apply (rule impI)\n  apply (rule impI)\n  apply assumption\n  done\n\nlemma ax2:\\<open>(A\\<longrightarrow>(B\\<longrightarrow>C))\\<longrightarrow>((A\\<longrightarrow>B)\\<longrightarrow>(A\\<longrightarrow>C))\\<close>\n  apply (rule impI)\n  apply (rule impI)\n  apply (rule impI)\n  apply (rule mp)\n  apply (rule mp)\n    apply assumption\n apply assumption\n  apply (rule mp)\n   apply assumption\n apply assumption\n done\n\nlemma ax3:\\<open>(A\\<and>B)\\<longrightarrow>A\\<close>\n  apply (rule impI)\n  apply (rule conjE)\n   apply assumption\n  apply assumption\n  done\n\nlemma ax4:\\<open>(A\\<and>B)\\<longrightarrow>B\\<close>\n  apply (rule impI)\n  apply (rule conjE)\n   apply assumption\n  apply assumption\n  done\n\nlemma ax5:\\<open>A\\<longrightarrow>(B\\<longrightarrow>(A\\<and>B))\\<close>\n  apply (rule impI)\n  apply (rule impI)\n  apply (rule conjI)\n   apply assumption\n   apply assumption\n  done\n\nlemma ax6:\\<open>A\\<longrightarrow>(A\\<or>B)\\<close>\n  apply (rule impI)\n  apply (rule disjI1)\n  apply assumption\n  done\n\nlemma ax7:\\<open>B\\<longrightarrow>(A\\<or>B)\\<close>\n  apply (rule impI)\n  apply (rule disjI2)\n  apply assumption\n  done\n\nlemma ax8:\\<open>(A\\<longrightarrow>C)\\<longrightarrow>(B\\<longrightarrow>C)\\<longrightarrow>(A\\<or>B\\<longrightarrow>C)\\<close>\nproof\n  assume q:\"(A\\<longrightarrow>C)\"\n  show \"(B \\<longrightarrow> C) \\<longrightarrow> A \\<or> B \\<longrightarrow> C\"\n  proof\n    assume q2: \"B \\<longrightarrow> C\"\n    show \"A \\<or> B \\<longrightarrow> C\"\n    apply (rule impI)\n    apply (erule disjE)\n    apply (rule mp ) (*[THEN swap]*)\n    apply (rule q)\n    apply assumption\n    apply (rule mp )\n    apply (rule q2)\n    apply assumption\n    done\n  qed\nqed\n\nlemma ax9: \"(A\\<longrightarrow>B)\\<longrightarrow>(A\\<longrightarrow>~B)\\<longrightarrow>~A\"\napply (rule impI)\n  apply (rule impI)\n(*  apply (unfold not_def) *)\n  apply (rule notI)\n  apply (rule notE)\n  apply (rule mp)\n   apply assumption\n   apply assumption\n  apply (rule mp)\n   apply assumption\n   apply assumption\n  done\n\nlemma ax10: \"A\\<longrightarrow>~A\\<longrightarrow>B\"\napply (rule impI)\n  apply (rule impI)\n  apply (rule notE)\n   apply assumption\n  apply assumption\n  done\n\nlemma ax11: \"A\\<or>~A\"\n  apply (rule disjCI)\n  apply (rule notnotD)\n  apply assumption\n  done\n\nlemma ax12: \\<open>(\\<forall>x. A(x)) \\<longrightarrow> A(q)\\<close>\nproof\n  assume r: \"\\<forall>x. A(x)\"\n  show \"A(q)\"\n    apply(rule_tac x=\"q\" in allE)\n    apply(rule r)\n    apply assumption\n    done\nqed\n\nlemma ax13: \\<open>A(q) \\<longrightarrow> (\\<exists>x. A(x))\\<close>\n  apply(rule impI)\n  apply(rule_tac x=\"q\" in exI)\n  apply assumption\n  done\n\nlemma B1: \\<open>(\\<forall>x. (A\\<longrightarrow>B(x)))\\<Longrightarrow>(A\\<longrightarrow>(\\<forall>x. B(x)))\\<close>\n  apply(rule impI)\n  apply(rule allI)\n  apply (rule mp)\n  apply(rule allE)\n  apply assumption\n  apply assumption\n  apply assumption\n  done\n\nlemma axB1: \\<open>(\\<forall>x. (A\\<longrightarrow>B(x)))\\<longrightarrow>(A\\<longrightarrow>(\\<forall>x. B(x)))\\<close>\n  apply(rule impI)\n  apply(rule B1)\n  apply assumption\n  done\n\nlemma B2: \\<open>(\\<forall>x. (B(x)\\<longrightarrow>A))\\<Longrightarrow>((\\<exists>x. B(x))\\<longrightarrow>A)\\<close>\n  apply(rule impI)\n  apply(rule exE)\n  apply assumption\n  apply (rule mp)\n  apply(rule allE)\n  apply assumption\n  apply assumption\n  apply assumption\n  done\n\nlemma axB2: \\<open>(\\<forall>x. (B(x)\\<longrightarrow>A))\\<longrightarrow>((\\<exists>x. B(x))\\<longrightarrow>A)\\<close>\n  apply(rule impI)\n  apply(rule B2)\n  apply assumption\n  done\n\nlemma rB1: \\<open>(\\<And>z. (R \\<longrightarrow> S(z))) \\<Longrightarrow> (R \\<longrightarrow> (\\<forall>x. S(x)))\\<close>\n  (*apply auto*)\n  apply(rule impI)\n  apply(rule allI)\n  apply(rule mp)\n   apply assumption\n   apply assumption\n  done\n\nlemma rB2: \\<open>(\\<And>x. (S(x) \\<longrightarrow> R)) \\<Longrightarrow> ((\\<exists>x. S(x)) \\<longrightarrow> R)\\<close>\n  (*apply auto*)\n  apply(rule impI)\n  apply(rule exE)\n   apply assumption\n  apply(rule mp)\n  apply assumption\n  apply assumption\n  done\n\nend", "meta": {"author": "georgydunaev", "repo": "JechExercises", "sha": "3ccce3c880a8b965c34f8ca364f38bd53cfb9fdd", "save_path": "github-repos/isabelle/georgydunaev-JechExercises", "path": "github-repos/isabelle/georgydunaev-JechExercises/JechExercises-3ccce3c880a8b965c34f8ca364f38bd53cfb9fdd/classical_axioms.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505376715775, "lm_q2_score": 0.8056321796478255, "lm_q1q2_score": 0.7288155844839304}}
{"text": "(*\n    $Id: ex.thy,v 1.4 2012/01/04 14:35:44 webertj Exp $\n    Author: Farhad Mehta\n*)\n\nheader \\<open> Recursive Functions and Induction: Zip \\<close>\n\ntheory Zip\n  imports Main\nbegin\n\ntext \\<open>\nRead the chapter about total recursive functions in the ``Tutorial on\nIsabelle/HOL'' (@{text fun}, Chapter 3.5).\n\\<close>\n\ntext \\<open>\nIn this exercise you will define a function @{text Zip} that merges two lists\nby interleaving.\n Examples:\n@{text \"Zip [a1, a2, a3]  [b1, b2, b3] = [a1, b1, a2, b2, a3, b3]\"} \n and\n@{text \"Zip [a1] [b1, b2, b3] = [a1, b1, b2, b3]\"}.\n\nUse three different approaches to define @{text Zip}:\n\\begin{enumerate}\n\\item by primitive recursion on the first list,\n\\item by primitive recursion on the second list,\n\\item by total recursion (using @{text fun}).\n\\end{enumerate}\n\\<close>\n\n\nprimrec zip1 :: \"'a list \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where\n\"zip1 [] ys = ys\" |\n\"zip1 (x#xs) ys = (if (0 < length ys)\n                   then x#hd ys#zip1 xs (tl ys)\n                   else (x#xs))\"\n\nlemma zip1_empty_ys_empty[simp]:\"zip1 xs [] = xs\"\n  apply (induction xs) by auto\n\nprimrec zip2 :: \"'a list \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where\n\"zip2 xs [] = xs\" |\n\"zip2 xs (y#ys) = (case xs of\n                    []     \\<Rightarrow> (y#ys) |\n                    (x#xs) \\<Rightarrow> x#y#zip2 xs ys)\"\n\nlemma zip2_empty_xs_empty[simp]:\"zip2 [] ys = ys\"\n  apply (induction ys) by auto\n\nfun zipr :: \"'a list \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where\n\"zipr [] ys = ys\" |\n\"zipr xs [] = xs\" |\n\"zipr (x#xs) (y#ys) = x#y#zipr xs ys\"\n\nlemma zipr_xs_empty_xs[simp]:\"zipr xs [] = xs\"\n  by (metis list.exhaust zipr.simps(1) zipr.simps(2))\n\ntext \\<open>\nShow that all three versions of @{text Zip} are equivalent.\n\\<close>\n\nlemma zip2_eq_zipr:\"zip2 xs ys = zipr xs ys\"\n  apply (induction xs arbitrary: ys)\n   apply simp_all\n  apply (case_tac ys) by auto\n\nlemma zip1_eq_zipr:\"zip1 xs ys = zipr xs ys\"\n  apply (induction ys arbitrary: xs)\n   apply simp_all\n  apply (case_tac xs) by auto\n\n\ntext \\<open>\nShow that @{text zipr} distributes over @{text append}.\n\\<close>\n\nlemma \"\\<lbrakk>length p = length u; length q = length v\\<rbrakk> \\<Longrightarrow> \n  zipr (p@q) (u@v) = zipr p u @ zipr q v\"\n  apply (induction p arbitrary: q u v)\n   apply auto\n  apply (case_tac u) by auto  \n\n\ntext \\<open>\n{\\bf Note:} For @{text fun}, the order of your equations is relevant.\nIf equations overlap, they will be disambiguated before they are added\nto the logic.  You can have a look at these equations using @{text\n\"thm zipr.simps\"}.\n\\<close>\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/Zip.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8080672227971211, "lm_q2_score": 0.9019206719160033, "lm_q1q2_score": 0.7288125325384782}}
{"text": "theory Pow\n  imports Main\nbegin\n\nsection {* Pow *}\n\nfun pow :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\" where\n  \"pow _ 0 = 1\"\n  | \"pow a (Suc n') = a * pow a n'\"\n\nlemma test_pow: \"pow x 0 = 1\" by auto\n\ntheorem pow_0: \"\\<forall>x :: nat. pow x 0 = 1\" by simp\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/Pow.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9019206870747657, "lm_q2_score": 0.8080672066194946, "lm_q1q2_score": 0.7288125301968412}}
{"text": "theory Ch1InClass\nimports Main \nbegin\n\nprimrec repeat :: \"(nat \\<Rightarrow> nat) \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> nat\" where\n  \"repeat f 0 x = x\" |\n  \"repeat f (Suc n) x = repeat f n (f x)\"\n\nabbreviation rep :: \"(nat \\<Rightarrow> nat) \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> nat\"\n  (\"_^_ _\" [90,90,90] 89) where\n    \"f^n x \\<equiv> repeat f n x\"\n\nlemma repeat_add[rule_format]:\n  \"\\<forall> x. f^(a + b) x = f^b (f^a x)\" (is \"?P a\")\nproof (induction a)\n  case 0\n  show \"?P 0\"\n  proof\n    fix x\n    show \"f^(0 + b) x = f^b (f^0 x)\" by simp\n  qed\nnext\n  case (Suc a')\n  from Suc have IH: \"\\<forall> y. f^(a' + b) y = f^b (f^a' y)\" .\n  show \"?P (Suc a')\"\n  proof\n    fix x\n    have \"f^((Suc a') + b) x = f^(Suc (a' + b)) x\" by simp\n    also have \"... = f^(a' + b) (f x)\" by simp\n    also from IH have \"... = f^b (f^a' (f x))\" ..\n    also have \"... = f^b (f^Suc a' x)\" by simp\n    finally show \"f^(Suc a' + b) x = f^b (f^Suc a' x)\" .\n  qed\nqed\n\ntheorem repeat_cycle: \"f^n x = x \\<longrightarrow> f^(m * n) x = x\" (is \"?P m\")\nproof (induction m)\n  case 0\n  show \"?P 0\"\n  proof\n    assume fnx: \"f^n x = x\"\n    show \"f^(0 * n) x = x\" by simp\n  qed\nnext\n  case (Suc m') -- \"case where m = Suc m'\"\n  show \"?P (Suc m')\"\n  proof\n    assume fnx: \"f^n x = x\"\n    from Suc fnx have IH: \"f^(m' * n) x = x\" ..\n    have \"f^((Suc m') * n) x = f^(n + (m' * n)) x\" by simp\n    also have \"... = f^(m' * n) (f^n x)\" by (rule repeat_add)\n    also from fnx have \"... = f^(m' * n) x\" by simp\n    also from IH have \"... = x\" .\n    finally show \"f^(Suc m' * n) x = x\" .\n  qed\nqed\n\n  \nprimrec multirember :: \"'a \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where\n  \"multirember a [] = []\" |\n  \"multirember a (b#ls) = (if a = b then multirember a ls\n                           else b#(multirember a ls))\"\n\nvalue \"multirember (1::nat) [1,2]\"\n\nlemma multirember_not_member: \n  \"a \\<notin> set (multirember a ls)\" (is \"?P ls\")\nproof (induction ls)\n  case Nil\n  show \"?P []\" by simp\nnext\n  case (Cons x xs)\n  show \"?P (Cons x xs)\"\n  proof (cases \"a = x\")\n    assume ax: \"a = x\"\n    from ax \n    have 1: \"multirember a (x#xs) = multirember a xs\" by simp\n    from Cons have IH: \"a \\<notin> set (multirember a xs)\" .\n    from 1 IH show \"a \\<notin> set (multirember a (x # xs))\" by simp\n  next\n    assume ax: \"a \\<noteq> x\"\n    from ax\n    have 2: \"multirember a (x#xs) = x#(multirember a xs)\" by simp\n    from Cons ax have 3: \"a \\<notin> set (x#multirember a xs)\" by simp\n    from 2 3 show \"a \\<notin> set (multirember a (x # xs))\" by simp\n  qed\nqed\n\ndatatype 'a tree = Leaf | Node \"'a tree\" 'a \"'a tree\"\n\nprimrec height :: \"'a tree \\<Rightarrow> nat\" where\n  \"height Leaf = 0\" |\n  \"height (Node L x R) = 1 + max (height L) (height R)\"\n\nprimrec leaves :: \"'a tree \\<Rightarrow> nat\" where\n  \"leaves Leaf = 1\" |\n  \"leaves (Node L x R) = leaves L + leaves R\"\n\n(* Finished here on 1/15/2014 *) \n\ntheorem height_less_leaves: \"height t + 1 \\<le> leaves t\" \nproof (induction t)\n  case Leaf\n  show \"height Leaf + 1 \\<le> leaves Leaf\" sorry\nnext\n  case (Node T1 a T2)\n  show \"height (Node T1 a T2) + 1 \\<le> leaves (Node T1 a T2)\" sorry\nqed\n\nprimrec keys :: \"nat tree \\<Rightarrow> nat set\" where\n  \"keys Leaf = {}\" |\n  \"keys (Node L x R) = keys L \\<union> {x} \\<union> keys R\"\n\ninductive_set BST :: \"(nat tree) set\" where\n  bst_leaf[intro!]: \"Leaf \\<in> BST\" |\n  bst_node[intro!]: \"\\<lbrakk> \\<forall> y \\<in> keys L. y \\<le> x; \\<forall> z \\<in> keys R. x \\<le> z; \n                        L \\<in> BST; R \\<in> BST \\<rbrakk>\n                        \\<Longrightarrow> (Node L x R) \\<in> BST\"\n\nthm BST.induct\n\ninductive_cases inv_bst_node[elim!]: \"(Node L y R) \\<in> BST\"\n\nthm inv_bst_node\n\n(* hi there, this doesn't show up in latex *)\ntext{*\n  this shows up in the latex output\n*}\n\nprimrec bst_insert :: \"nat \\<Rightarrow> nat tree \\<Rightarrow> nat tree\" where\n  \"bst_insert x Leaf = Node Leaf x Leaf\" |\n  \"bst_insert x (Node L y R) = \n     (if x < y then Node (bst_insert x L) y R\n      else if y < x then Node L y (bst_insert x R)\n      else Node L y R)\"\n\nthm tree.induct\nthm BST.induct\n\ntheorem insert_bst: \n  assumes tbst: \"T \\<in> BST\" shows \"bst_insert x T \\<in> BST\" \nusing tbst\nproof (induction rule: BST.induct)\n  case bst_leaf\n  show \"bst_insert x Leaf \\<in> BST\" by auto\nnext\n  case (bst_node L x' R)\n  from bst_node\n  oops\n\nend\n", "meta": {"author": "keyz", "repo": "OhIsabelle", "sha": "3af467370750c827b0fdd258c60d4088b2565f9c", "save_path": "github-repos/isabelle/keyz-OhIsabelle", "path": "github-repos/isabelle/keyz-OhIsabelle/OhIsabelle-3af467370750c827b0fdd258c60d4088b2565f9c/code-from-class/Ch1InClass.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424295406088, "lm_q2_score": 0.861538211208597, "lm_q1q2_score": 0.7288117275318707}}
{"text": "theory Ex023\n  imports Main \nbegin \n     \n  \nlemma \"(A \\<longrightarrow> B)  \\<longleftrightarrow> (\\<not>A \\<or> B)\" \nproof -\n  {\n    assume a:\"A \\<longrightarrow> B\"\n    {\n      assume b:\"\\<not>(\\<not>A \\<or> B)\"\n      {\n        assume A \n        with a have B by (rule mp)\n        hence \"\\<not>A \\<or> B\" by (rule disjI2)\n        with b have False by contradiction\n      }\n      hence \"\\<not>A\" by (rule notI)\n      hence \"\\<not>A \\<or> B\" by (rule disjI1)\n      with b have False by contradiction\n    }\n    hence \"\\<not>\\<not>(\\<not>A \\<or> B)\" by (rule notI)\n    hence \"\\<not>A \\<or> B\" by (rule notnotD)\n  }\n  moreover\n  {\n    assume c:\"\\<not>A \\<or> B\" \n    {\n      assume d:\"\\<not>(A \\<longrightarrow> B)\"\n      {\n        assume e:A \n        {\n          assume \"\\<not>A\"\n          with e have False by contradiction\n        }\n        note f=this\n        {\n          assume g:B \n          {\n            assume A\n            have B by (rule g)\n          }\n          hence \"A \\<longrightarrow> B\" by (rule impI)\n          with d have False by contradiction\n        }\n        with c and f have False by (rule disjE)\n        hence B by (rule FalseE)\n      }\n      hence \"A \\<longrightarrow> B\" by (rule impI)\n      with d have False by contradiction\n    }\n    hence \"\\<not>\\<not>(A \\<longrightarrow> B)\" by (rule notI)\n    hence \"A \\<longrightarrow> B\" by (rule notnotD)\n  }\n  ultimately show ?thesis by (rule iffI)\nqed\n  \n        \n          \n          \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/Ex023.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218370002787, "lm_q2_score": 0.7905303112671295, "lm_q1q2_score": 0.7288071567677942}}
{"text": "(*\n    File:     Finite_Product_Extend.thy\n    Author:   Joseph Thommes, TU M\u00fcnchen; Manuel Eberl, TU M\u00fcnchen\n*)\nsection \\<open>Finite Product\\<close>\n\ntheory Finite_Product_Extend\n  imports IDirProds\nbegin\n\ntext \\<open>In this section, some general facts about \\<open>finprod\\<close> as well as some tailored for the rest of\nthis entry are proven.\\<close>\n\ntext \\<open>It is often needed to split a product in a single factor and the rest. Thus these two lemmas.\\<close>\n\nlemma (in comm_group) finprod_minus:\n  assumes \"a \\<in> A\" \"f \\<in> A \\<rightarrow> carrier G\" \"finite A\"\n  shows \"finprod G f A = f a \\<otimes> finprod G f (A - {a})\"\nproof -\n  from assms have \"A = insert a (A - {a})\" by blast\n  then have \"finprod G f A = finprod G f (insert a (A - {a}))\" by simp\n  also have \"\\<dots> = f a \\<otimes> finprod G f (A - {a})\" using assms by (intro finprod_insert, auto)\n  finally show ?thesis .\nqed\n\nlemma (in comm_group) finprod_minus_symm:\n  assumes \"a \\<in> A\" \"f \\<in> A \\<rightarrow> carrier G\" \"finite A\"\n  shows \"finprod G f A = finprod G f (A - {a}) \\<otimes> f a\"\nproof -\n  from assms have \"A = insert a (A - {a})\" by blast\n  then have \"finprod G f A = finprod G f (insert a (A - {a}))\" by simp\n  also have \"\\<dots> = f a \\<otimes> finprod G f (A - {a})\" using assms by (intro finprod_insert, auto)\n  also have \"\\<dots> = finprod G f (A - {a}) \\<otimes> f a\"\n    by (intro m_comm, use assms in blast, intro finprod_closed, use assms in blast)\n  finally show ?thesis .\nqed\n\ntext \\<open>This makes it very easy to show the following trivial fact.\\<close>\n\nlemma (in comm_group) finprod_singleton:\n  assumes \"f x \\<in> carrier G\" \"finprod G f {x} = a\"\n  shows \"f x = a\"\nproof -\n  have \"finprod G f {x} = f x \\<otimes> finprod G f {}\" using finprod_minus[of x \"{x}\" f] assms by auto\n  thus ?thesis using assms by simp\nqed\n\ntext \\<open>The finite product is consistent and closed concerning subgroups.\\<close>\n\nlemma (in comm_group) finprod_subgroup:\n  assumes \"f \\<in> S \\<rightarrow> H\" \"subgroup H G\"\n  shows \"finprod G f S = finprod (G\\<lparr>carrier := H\\<rparr>) f S\"\nproof (cases \"finite S\")\n  case True\n  interpret H: comm_group \"G\\<lparr>carrier := H\\<rparr>\" using subgroup_is_comm_group[OF assms(2)] .\n  show ?thesis using True assms\n  proof (induction S rule: finite_induct)\n    case empty\n    then show ?case using finprod_empty H.finprod_empty by simp\n  next\n    case i: (insert x F)\n    then have \"finprod G f F = finprod (G\\<lparr>carrier := H\\<rparr>) f F\" by blast\n    moreover have \"finprod G f (insert x F) = f x \\<otimes> finprod G f F\"\n    proof(intro finprod_insert[OF i(1, 2), of f])\n      show \"f \\<in> F \\<rightarrow> carrier G\" \"f x \\<in> carrier G\" using i(4) subgroup.subset[OF i(5)] by blast+\n    qed\n    ultimately have \"finprod G f (insert x F) = f x \\<otimes>\\<^bsub>G\\<lparr>carrier := H\\<rparr>\\<^esub> finprod (G\\<lparr>carrier := H\\<rparr>) f F\"\n      by auto\n    moreover have \"finprod (G\\<lparr>carrier := H\\<rparr>) f (insert x F) = \\<dots>\"\n    proof(intro H.finprod_insert[OF i(1, 2)])\n      show \"f \\<in> F \\<rightarrow> carrier (G\\<lparr>carrier := H\\<rparr>)\" \"f x \\<in> carrier (G\\<lparr>carrier := H\\<rparr>)\" using i(4) by auto\n    qed\n    ultimately show ?case by simp\n  qed\nnext\n  case False\n  then show ?thesis unfolding finprod_def by simp\nqed\n\nlemma (in comm_group) finprod_closed_subgroup:\n  assumes \"subgroup H G\" \"f \\<in> A \\<rightarrow> H\"\n  shows \"finprod G f A \\<in> H\"\n  using assms(2)\nproof (induct A rule: infinite_finite_induct)\ncase (infinite A)\nthen show ?case using subgroup.one_closed[OF assms(1)] by auto\nnext\n  case empty\n  then show ?case using subgroup.one_closed[OF assms(1)] by auto\nnext\n  case i: (insert x F)\n  from finprod_insert[OF i(1, 2), of f] i have fi: \"finprod G f (insert x F) = f x \\<otimes> finprod G f F\"\n    using subgroup.subset[OF assms(1)] by blast\n  from i have \"finprod G f F \\<in> H\" \"f x \\<in> H\" by blast+\n  with fi show ?case using subgroup.m_closed[OF assms(1)] by presburger \nqed\n\ntext \\<open>It also does not matter if we exponentiate all elements taking part in the product or the\nresult of the product.\\<close>\n\nlemma (in comm_group) finprod_exp:\n  assumes \"A \\<subseteq> carrier G\" \"f \\<in> A \\<rightarrow> carrier G\"\n  shows \"(finprod G f A) [^] (k::int) = finprod G ((\\<lambda>a. a [^] k) \\<circ> f) A\"\n  using assms\nproof(induction A rule: infinite_finite_induct)\n  case i: (insert x F)\n  hence ih: \"finprod G f F [^] k = finprod G ((\\<lambda>a. a [^] k) \\<circ> f) F\" by blast\n  have fpc: \"finprod G f F \\<in> carrier G\" by (intro finprod_closed, use i in auto)\n  have fxc: \"f x \\<in> carrier G\" using i by auto\n  have \"finprod G f (insert x F) = f x \\<otimes> finprod G f F\" by (intro finprod_insert, use i in auto)\n  hence \"finprod G f (insert x F) [^] k = (f x \\<otimes> finprod G f F) [^] k\" by simp\n  also have \"\\<dots> = f x [^] k \\<otimes> finprod G f F [^] k\" using fpc fxc int_pow_distrib by blast\n  also have \"\\<dots> = ((\\<lambda>a. a [^] k) \\<circ> f) x \\<otimes> finprod G ((\\<lambda>a. a [^] k) \\<circ> f) F\" using ih by simp\n  also have \"\\<dots> = finprod G ((\\<lambda>a. a [^] k) \\<circ> f) (insert x F)\"\n    by (intro finprod_insert[symmetric], use i in auto)\n  finally show ?case .\nqed auto\n\ntext \\<open>Some lemmas concerning different combinations of functions in the usage of \\<open>finprod\\<close>.\\<close>\n\nlemma (in comm_group) finprod_cong_split:\n  assumes \"\\<And>a. a \\<in> A \\<Longrightarrow> f a \\<otimes> g a = h a\"\n  and \"f \\<in> A \\<rightarrow> carrier G\" \"g \\<in> A \\<rightarrow> carrier G\" \"h \\<in> A \\<rightarrow> carrier G\"\n  shows \"finprod G h A = finprod G f A \\<otimes> finprod G g A\" using assms\nproof(induct A rule: infinite_finite_induct)\n  case (infinite A)\n  then show ?case by simp\nnext\n  case empty\n  then show ?case by simp\nnext\n  case i: (insert x F)\n  then have iH: \"finprod G h F = finprod G f F \\<otimes> finprod G g F\" by fast\n  have f: \"finprod G f (insert x F) = f x \\<otimes> finprod G f F\"\n    by (intro finprod_insert[OF i(1, 2), of f]; use i(5) in simp)\n  have g: \"finprod G g (insert x F) = g x \\<otimes> finprod G g F\"\n    by (intro finprod_insert[OF i(1, 2), of g]; use i(6) in simp)\n  have h: \"finprod G h (insert x F) = h x \\<otimes> finprod G h F\"\n    by (intro finprod_insert[OF i(1, 2), of h]; use i(7) in simp)  \n  also have \"\\<dots> = h x \\<otimes> (finprod G f F \\<otimes> finprod G g F)\" using iH by argo\n  also have \"\\<dots> = f x \\<otimes> g x \\<otimes> (finprod G f F \\<otimes> finprod G g F)\" using i(4) by simp\n  also have \"\\<dots> = f x \\<otimes> finprod G f F \\<otimes> (g x \\<otimes> finprod G g F)\" using m_comm m_assoc i(5-7) by simp\n  also have \"\\<dots> = finprod G f (insert x F) \\<otimes> finprod G g (insert x F)\" using f g by argo\n  finally show ?case .\nqed\n\nlemma (in comm_group) finprod_comp:\n  assumes \"inj_on g A\" \"(f \\<circ> g) ` A \\<subseteq> carrier G\"\n  shows \"finprod G f (g ` A) = finprod G (f \\<circ> g) A\"\n  using finprod_reindex[OF _ assms(1), of f] using assms(2) unfolding comp_def by blast\n\ntext \\<open>The subgroup generated by a set of generators (in an abelian group) is exactly the set of\nelements that can be written as a finite product using only powers of these elements.\\<close>\n\nlemma (in comm_group) generate_eq_finprod_PiE_image:\n  assumes \"finite gs\" \"gs \\<subseteq> carrier G\"\n  shows \"generate G gs = (\\<lambda>x. finprod G x gs) ` Pi\\<^sub>E gs (\\<lambda>a. generate G {a})\" (is \"?g = ?fp\")\nproof\n  show \"?g \\<subseteq> ?fp\"\n  proof\n    fix x\n    assume x: \"x \\<in> ?g\"\n    thus \"x \\<in> ?fp\"\n    proof (induction rule: generate.induct)\n      case one\n      show ?case\n      proof\n        let ?r = \"restrict (\\<lambda>_. \\<one>) gs\"\n        show \"?r \\<in> (\\<Pi>\\<^sub>E a\\<in>gs. generate G {a})\" using generate.one by auto\n        show \"\\<one> = finprod G ?r gs\" by(intro finprod_one_eqI[symmetric], simp)\n      qed\n    next\n      case g: (incl g)\n      show ?case\n      proof\n        let ?r = \"restrict ((\\<lambda>_. \\<one>)(g := g)) gs\"\n        show \"?r \\<in> (\\<Pi>\\<^sub>E a\\<in>gs. generate G {a})\" using generate.one generate.incl[of g \"{g}\" G]\n          by fastforce\n        show \"g = finprod G ?r gs\"\n        proof -\n          have \"finprod G ?r gs = ?r g \\<otimes> finprod G ?r (gs - {g})\"\n            by (intro finprod_minus, use assms g in auto)\n          moreover have \"?r g = g\" using g by simp\n          moreover have \"finprod G ?r (gs - {g}) = \\<one>\" by(rule finprod_one_eqI; use g in simp)\n          ultimately show ?thesis using assms g by auto\n        qed\n      qed\n    next\n      case g: (inv g)\n      show ?case\n      proof\n        let ?r = \"restrict ((\\<lambda>_. \\<one>)(g := inv g)) gs\"\n        show \"?r \\<in> (\\<Pi>\\<^sub>E a\\<in>gs. generate G {a})\" using generate.one generate.inv[of g \"{g}\" G]\n          by fastforce\n        show \"inv g = finprod G ?r gs\"\n        proof -\n          have \"finprod G ?r gs = ?r g \\<otimes> finprod G ?r (gs - {g})\"\n            by (intro finprod_minus, use assms g in auto)\n          moreover have \"?r g = inv g\" using g by simp\n          moreover have \"finprod G ?r (gs - {g}) = \\<one>\" by(rule finprod_one_eqI; use g in simp)\n          ultimately show ?thesis using assms g by auto\n        qed\n      qed\n    next\n      case gh: (eng g h)\n      from gh obtain i where i: \"i \\<in> (\\<Pi>\\<^sub>E a\\<in>gs. generate G {a})\" \"g = finprod G i gs\" by blast\n      from gh obtain j where j: \"j \\<in> (\\<Pi>\\<^sub>E a\\<in>gs. generate G {a})\" \"h = finprod G j gs\" by blast\n      from i j have \"g \\<otimes> h = finprod G i gs \\<otimes> finprod G j gs\" by blast\n      also have \"\\<dots> = finprod G (\\<lambda>a. i a \\<otimes> j a) gs\"\n      proof(intro finprod_multf[symmetric]; rule)\n        fix x\n        assume x: \"x \\<in> gs\"\n        have \"i x \\<in> generate G {x}\" \"j x \\<in> generate G {x}\"using i(1) j(1) x by blast+\n        thus \"i x \\<in> carrier G\" \"j x \\<in> carrier G\" using generate_incl[of \"{x}\"] x assms(2) by blast+\n      qed\n      also have \"\\<dots> = finprod G (restrict (\\<lambda>a. i a \\<otimes> j a) gs) gs\"\n      proof(intro finprod_cong)\n        have ip: \"i g \\<in> generate G {g}\" if \"g \\<in> gs\" for g using i that by auto\n        have jp: \"j g \\<in> generate G {g}\" if \"g \\<in> gs\" for g using j that by auto\n        have \"i g \\<otimes> j g \\<in> generate G {g}\" if \"g \\<in> gs\" for g\n          using generate.eng[OF ip[OF that] jp[OF that]] .\n        thus \"((\\<lambda>a. i a \\<otimes> j a) \\<in> gs \\<rightarrow> carrier G) = True\" using generate_incl assms(2) by blast\n      qed auto\n      finally have \"g \\<otimes> h = finprod G (restrict (\\<lambda>a. i a \\<otimes> j a) gs) gs\" .\n      moreover have \"(restrict (\\<lambda>a. i a \\<otimes> j a) gs) \\<in> (\\<Pi>\\<^sub>E a\\<in>gs. generate G {a})\"\n      proof -\n        have ip: \"i g \\<in> generate G {g}\" if \"g \\<in> gs\" for g using i that by auto\n        have jp: \"j g \\<in> generate G {g}\" if \"g \\<in> gs\" for g using j that by auto\n        have \"i g \\<otimes> j g \\<in> generate G {g}\" if \"g \\<in> gs\" for g\n          using generate.eng[OF ip[OF that] jp[OF that]] .\n        thus ?thesis by auto\n      qed\n      ultimately show ?case using i j by blast\n    qed\n  qed\n  show \"?fp \\<subseteq> ?g\"\n  proof\n    fix x\n    assume x: \"x \\<in> ?fp\"\n    then obtain f where f: \"f \\<in> (Pi\\<^sub>E gs (\\<lambda>a. generate G {a}))\" \"x = finprod G f gs\" by blast\n    have sg: \"subgroup ?g G\" by(intro generate_is_subgroup, fact)\n    have \"finprod G f gs \\<in> ?g\"\n    proof(intro finprod_closed_subgroup[OF sg])\n      have \"f g \\<in> generate G gs\" if \"g \\<in> gs\" for g\n      proof -\n        have \"f g \\<in> generate G {g}\" using f(1) that by auto\n        moreover have \"generate G {g} \\<subseteq> generate G gs\" by(intro mono_generate, use that in simp)\n        ultimately show ?thesis by fast\n      qed\n      thus \"f \\<in> gs \\<rightarrow> generate G gs\" by simp\n    qed\n    thus \"x \\<in> ?g\" using f by blast\n  qed\nqed\n\nlemma (in comm_group) generate_eq_finprod_Pi_image:\n  assumes \"finite gs\" \"gs \\<subseteq> carrier G\"\n  shows \"generate G gs = (\\<lambda>x. finprod G x gs) ` Pi gs (\\<lambda>a. generate G {a})\" (is \"?g = ?fp\")\nproof -\n  have \"(\\<lambda>x. finprod G x gs) ` Pi\\<^sub>E gs (\\<lambda>a. generate G {a})\n      = (\\<lambda>x. finprod G x gs) ` Pi gs (\\<lambda>a. generate G {a})\"\n  proof\n    have \"Pi\\<^sub>E gs (\\<lambda>a. generate G {a}) \\<subseteq> Pi gs (\\<lambda>a. generate G {a})\" by blast\n    thus \"(\\<lambda>x. finprod G x gs) ` Pi\\<^sub>E gs (\\<lambda>a. generate G {a})\n        \\<subseteq> (\\<lambda>x. finprod G x gs) ` Pi gs (\\<lambda>a. generate G {a})\" by blast\n    show \"(\\<lambda>x. finprod G x gs) ` Pi gs (\\<lambda>a. generate G {a})\n        \\<subseteq> (\\<lambda>x. finprod G x gs) ` Pi\\<^sub>E gs (\\<lambda>a. generate G {a})\"\n    proof\n      fix x\n      assume x: \"x \\<in> (\\<lambda>x. finprod G x gs) ` Pi gs (\\<lambda>a. generate G {a})\"\n      then obtain f where f: \"x = finprod G f gs\" \"f \\<in> Pi gs (\\<lambda>a. generate G {a})\" by blast\n      moreover have \"finprod G f gs = finprod G (restrict f gs) gs\"\n      proof(intro finprod_cong)\n        have \"f g \\<in> carrier G\" if \"g \\<in> gs\" for g\n          using that f(2) mono_generate[of \"{g}\" gs] generate_incl[OF assms(2)] by fast\n        thus \"(f \\<in> gs \\<rightarrow> carrier G) = True\" by blast\n      qed auto        \n      moreover have \"restrict f gs \\<in> Pi\\<^sub>E gs (\\<lambda>a. generate G {a})\" using f(2) by simp\n      ultimately show \"x \\<in> (\\<lambda>x. finprod G x gs) ` Pi\\<^sub>E gs (\\<lambda>a. generate G {a})\" by blast\n    qed\n  qed\n  with generate_eq_finprod_PiE_image[OF assms] show ?thesis by auto\nqed\n\nlemma (in comm_group) generate_eq_finprod_Pi_int_image:\n  assumes \"finite gs\" \"gs \\<subseteq> carrier G\"\n  shows \"generate G gs = (\\<lambda>x. finprod G (\\<lambda>g. g [^] x g) gs) ` Pi gs (\\<lambda>_. (UNIV::int set))\"\nproof -\n  from generate_eq_finprod_Pi_image[OF assms]\n  have \"generate G gs = (\\<lambda>x. finprod G x gs) ` (\\<Pi> a\\<in>gs. generate G {a})\" .\n  also have \"\\<dots> = (\\<lambda>x. finprod G (\\<lambda>g. g [^] x g) gs) ` Pi gs (\\<lambda>_. (UNIV::int set))\"\n  proof(rule; rule)\n    fix x\n    assume x: \"x \\<in> (\\<lambda>x. finprod G x gs) ` (\\<Pi> a\\<in>gs. generate G {a})\"\n    then obtain f where f: \"f \\<in> (\\<Pi> a\\<in>gs. generate G {a})\" \"x = finprod G f gs\" by blast\n    hence \"\\<exists>k::int. f a = a [^] k\" if \"a \\<in> gs\" for a using generate_pow[of a] that assms(2) by blast\n    hence \"\\<exists>(h::'a \\<Rightarrow> int). \\<forall>a\\<in>gs. f a = a [^] h a\" by meson\n    then obtain h where h: \"\\<forall>a\\<in>gs. f a = a [^] h a\" \"h \\<in> gs \\<rightarrow> (UNIV :: int set)\" by auto\n    have \"finprod G (\\<lambda>g. g [^] h g) gs = finprod G f gs\"\n      by (intro finprod_cong, use int_pow_closed h assms(2) in auto)\n    with f have \"x = finprod G (\\<lambda>g. g [^] h g) gs\" by argo\n    with h(2) show \"x \\<in> (\\<lambda>x. finprod G (\\<lambda>g. g [^] x g) gs) ` (gs \\<rightarrow> (UNIV::int set))\" by auto\n  next\n    fix x\n    assume x: \"x \\<in> (\\<lambda>x. finprod G (\\<lambda>g. g [^] x g) gs) ` (gs \\<rightarrow> (UNIV::int set))\"\n    then obtain h where h: \"x = finprod G (\\<lambda>g. g [^] h g) gs\" \"h \\<in> gs \\<rightarrow> (UNIV :: int set)\" by blast\n    hence \"\\<exists>k\\<in>generate G {a}. a [^] h a = k\" if \"a \\<in> gs\" for a\n      using generate_pow[of a] that assms(2) by blast\n    then obtain f where f: \"\\<forall>a\\<in>gs. a [^] h a = f a\" \"f \\<in> (\\<Pi> a\\<in>gs. generate G {a})\" by fast\n    have \"finprod G f gs = finprod G (\\<lambda>g. g [^] h g) gs\"\n    proof(intro finprod_cong)\n      have \"f a \\<in> carrier G\" if \"a \\<in> gs\" for a\n        using generate_incl[of \"{a}\"] assms(2) that f(2) by fast\n      thus \"(f \\<in> gs \\<rightarrow> carrier G) = True\" by blast\n    qed (use f in auto)\n    with h have \"x = finprod G f gs\" by argo\n    with f(2) show \"x \\<in> (\\<lambda>x. finprod G x gs) ` (\\<Pi> a\\<in>gs. generate G {a})\" by blast\n  qed\n  finally show ?thesis .\nqed\n\n\nlemma (in comm_group) IDirProds_eq_finprod_PiE:\n  assumes \"finite I\" \"\\<And>i. i \\<in> I \\<Longrightarrow> subgroup (S i) G\"\n  shows \"IDirProds G S I = (\\<lambda>x. finprod G x I) ` (Pi\\<^sub>E I S)\" (is \"?DP = ?fp\")\nproof\n  show \"?fp \\<subseteq> ?DP\"\n  proof\n    fix x\n    assume x: \"x \\<in> ?fp\"\n    then obtain f where f: \"f \\<in> (Pi\\<^sub>E I S)\" \"x = finprod G f I\" by blast\n    have sDP: \"subgroup ?DP G\"\n      by (intro IDirProds_is_subgroup; use subgroup.subset[OF assms(2)] in blast)\n    have \"finprod G f I \\<in> ?DP\"\n    proof(intro finprod_closed_subgroup[OF sDP])\n      have \"f i \\<in> IDirProds G S I\" if \"i \\<in> I\" for i\n      proof\n        show \"f i \\<in> (S i)\" using f(1) that by auto\n        show \"(S i) \\<subseteq> IDirProds G S I\" by (intro IDirProds_incl[OF that])\n      qed\n      thus \"f \\<in> I \\<rightarrow> IDirProds G S I\" by simp\n    qed\n    thus \"x \\<in> ?DP\" using f by blast\n  qed\n  show \"?DP \\<subseteq> ?fp\"\n  proof(unfold IDirProds_def; rule subsetI)\n    fix x\n    assume x: \"x \\<in> generate G (\\<Union>(S ` I))\"\n    thus \"x \\<in> ?fp\" using assms\n    proof (induction rule: generate.induct)\n      case one\n      define g where g: \"g = (\\<lambda>x. if x \\<in> I then \\<one> else undefined)\"\n      then have \"g \\<in> Pi\\<^sub>E I S\"\n        using subgroup.one_closed[OF one(2)] by auto\n      moreover have \"finprod G g I = \\<one>\" by (intro finprod_one_eqI; use g in simp)\n      ultimately show ?case unfolding image_def by (auto; metis)\n    next\n      case i: (incl h)\n      from i obtain j where j: \"j \\<in> I\" \"h \\<in> (S j)\" by blast\n      define hf where \"hf = (\\<lambda>x. (if x \\<in> I then \\<one> else undefined))(j := h)\"\n      with j have \"hf \\<in> Pi\\<^sub>E I S\"\n        using subgroup.one_closed[OF i(3)] by force\n      moreover have \"finprod G hf I = h\"\n      proof -\n        have \"finprod G hf I = hf j \\<otimes> finprod G hf (I - {j})\"\n          by (intro finprod_minus, use assms hf_def subgroup.subset[OF i(3)[OF j(1)]] j in auto)\n        moreover have \"hf j = h\" using hf_def by simp\n        moreover have \"finprod G hf (I - {j}) = \\<one>\" by (rule finprod_one_eqI; use hf_def in simp)\n        ultimately show ?thesis using subgroup.subset[OF i(3)[OF j(1)]] j(2) by auto\n      qed\n      ultimately show ?case unfolding image_def by (auto; metis)\n    next\n      case i: (inv h)\n      from i obtain j where j: \"j \\<in> I\" \"h \\<in> (S j)\" by blast\n      have ih: \"inv h \\<in> (S j)\" using subgroup.m_inv_closed[OF i(3)[OF j(1)] j(2)] .\n      define hf where \"hf = (\\<lambda>x. (if x \\<in> I then \\<one> else undefined))(j := inv h)\"\n      with j ih have \"hf \\<in> Pi\\<^sub>E I S\"\n        using subgroup.one_closed[OF i(3)] by force\n      moreover have \"finprod G hf I = inv h\"\n      proof -\n        have \"finprod G hf I = hf j \\<otimes> finprod G hf (I - {j})\"\n          by (intro finprod_minus, use assms hf_def subgroup.subset[OF i(3)[OF j(1)]] j in auto)\n        moreover have \"hf j = inv h\" using hf_def by simp\n        moreover have \"finprod G hf (I - {j}) = \\<one>\" by (rule finprod_one_eqI; use hf_def in simp)\n        ultimately show ?thesis using subgroup.subset[OF i(3)[OF j(1)]] j(2) by auto\n      qed\n      ultimately show ?case unfolding image_def by (auto; metis)\n    next\n      case e: (eng a b)\n      from e obtain f where f: \"f \\<in> Pi\\<^sub>E I S\" \"a = finprod G f I\" by blast\n      from e obtain g where g: \"g \\<in> Pi\\<^sub>E I S\" \"b = finprod G g I\" by blast\n      from f g have \"a \\<otimes> b = finprod G f I \\<otimes> finprod G g I\" by blast\n      also have \"\\<dots> = finprod G (\\<lambda>a. f a \\<otimes> g a) I\"\n      proof(intro finprod_multf[symmetric])\n        have \"\\<Union>(S ` I) \\<subseteq> carrier G\" using subgroup.subset[OF e(6)] by blast\n        thus \"f \\<in> I \\<rightarrow> carrier G\" \"g \\<in> I \\<rightarrow> carrier G\"\n          using f(1) g(1) unfolding PiE_def Pi_def by auto\n      qed\n      also have \"\\<dots> = finprod G (restrict (\\<lambda>a. f a \\<otimes> g a) I) I\"\n      proof(intro finprod_cong)\n        show \"I = I\" by simp\n        show \"\\<And>i. i \\<in> I =simp=> f i \\<otimes> g i = (\\<lambda>a\\<in>I. f a \\<otimes> g a) i\" by simp\n        have fp: \"f i \\<in> (S i)\" if \"i \\<in> I\" for i using f that by auto\n        have gp: \"g i \\<in> (S i)\" if \"i \\<in> I\" for i using g that by auto\n        have \"f i \\<otimes> g i \\<in> (S i)\" if \"i \\<in> I\" for i\n          using subgroup.m_closed[OF e(6)[OF that] fp[OF that] gp[OF that]] .\n        thus \"((\\<lambda>a. f a \\<otimes> g a) \\<in> I \\<rightarrow> carrier G) = True\" using subgroup.subset[OF e(6)] by auto\n      qed\n      finally have \"a \\<otimes> b = finprod G (restrict (\\<lambda>a. f a \\<otimes> g a) I) I\" .\n      moreover have \"(restrict (\\<lambda>a. f a \\<otimes> g a) I) \\<in> Pi\\<^sub>E I S\"\n      proof -\n        have fp: \"f i \\<in> (S i)\" if \"i \\<in> I\" for i using f that by auto\n        have gp: \"g i \\<in> (S i)\" if \"i \\<in> I\" for i using g that by auto\n        have \"f i \\<otimes> g i \\<in> (S i)\" if \"i \\<in> I\" for i\n          using subgroup.m_closed[OF e(6)[OF that] fp[OF that] gp[OF that]] .\n        thus ?thesis by auto\n      qed\n      ultimately show ?case using f g by blast\n    qed\n  qed\nqed\n\nlemma (in comm_group) IDirProds_eq_finprod_Pi:\n  assumes \"finite I\" \"\\<And>i. i \\<in> I \\<Longrightarrow> subgroup (S i) G\"\n  shows \"IDirProds G S I = (\\<lambda>x. finprod G x I) ` (Pi I S)\" (is \"?DP = ?fp\")\nproof -\n  have \"(\\<lambda>x. finprod G x I) ` (Pi I S) = (\\<lambda>x. finprod G x I) ` (Pi\\<^sub>E I S)\"\n  proof\n    have \"Pi\\<^sub>E I S \\<subseteq> Pi I S\" by blast\n    thus \"(\\<lambda>x. finprod G x I) ` Pi\\<^sub>E I S \\<subseteq> (\\<lambda>x. finprod G x I) ` Pi I S\" by blast\n    show \"(\\<lambda>x. finprod G x I) ` Pi I S \\<subseteq> (\\<lambda>x. finprod G x I) ` Pi\\<^sub>E I S\"\n    proof\n      fix x\n      assume x: \"x \\<in> (\\<lambda>x. finprod G x I) ` Pi I S\"\n      then obtain f where f: \"x = finprod G f I\" \"f \\<in> Pi I S\" by blast\n      moreover have \"finprod G f I = finprod G (restrict f I) I\"\n        by (intro finprod_cong; use f(2) subgroup.subset[OF assms(2)] in fastforce)\n      moreover have \"restrict f I \\<in> Pi\\<^sub>E I S\" using f(2) by simp\n      ultimately show \"x \\<in> (\\<lambda>x. finprod G x I) ` Pi\\<^sub>E I S\" by blast\n    qed\n  qed\n  with IDirProds_eq_finprod_PiE[OF assms] show ?thesis by auto\nqed\n\ntext \\<open>If we switch one element from a set of generators, the generated set stays the same if both\nelements can be generated from the others together with the switched element respectively.\\<close>\n\nlemma (in comm_group) generate_one_switched_exp_eqI:\n  assumes \"A \\<subseteq> carrier G\" \"a \\<in> A\" \"B = (A - {a}) \\<union> {b}\"\n  and \"f \\<in> A \\<rightarrow> (UNIV::int set)\" \"g \\<in> B \\<rightarrow> (UNIV::int set)\"\n  and \"a = finprod G (\\<lambda>x. x [^] g x) B\" \"b = finprod G (\\<lambda>x. x [^] f x) A\"\n  shows \"generate G A = generate G B\"\nproof(intro generate_one_switched_eqI[OF assms(1, 2, 3)]; cases \"finite A\")\n  case True\n  hence fB: \"finite B\" using assms(3) by blast\n  have cB: \"B \\<subseteq> carrier G\"\n  proof -\n    have \"b \\<in> carrier G\"\n      by (subst assms(7), intro finprod_closed, use assms(1, 4) int_pow_closed in fast)\n    thus ?thesis using assms(1, 3) by blast\n  qed\n  show \"a \\<in> generate G B\"\n  proof(subst generate_eq_finprod_Pi_image[OF fB cB], rule)\n    show \"a = finprod G (\\<lambda>x. x [^] g x) B\" by fact\n    have \"x [^] g x \\<in> generate G {x}\" if \"x \\<in> B\" for x using generate_pow[of x] cB that by blast\n    thus \"(\\<lambda>x. x [^] g x) \\<in> (\\<Pi> a\\<in>B. generate G {a})\" unfolding Pi_def by blast\n  qed\n  show \"b \\<in> generate G A\"\n  proof(subst generate_eq_finprod_Pi_image[OF True assms(1)], rule)\n    show \"b = finprod G (\\<lambda>x. x [^] f x) A\" by fact\n    have \"x [^] f x \\<in> generate G {x}\" if \"x \\<in> A\" for x\n      using generate_pow[of x] assms(1) that by blast\n    thus \"(\\<lambda>x. x [^] f x) \\<in> (\\<Pi> a\\<in>A. generate G {a})\" unfolding Pi_def by blast\n  qed\nnext\n  case False\n  hence b: \"b = \\<one>\" using assms(7) unfolding finprod_def by simp\n  from False assms(3) have \"infinite B\" by simp\n  hence a: \"a = \\<one>\" using assms(6) unfolding finprod_def by simp\n  show \"a \\<in> generate G B\" using generate.one a by blast\n  show \"b \\<in> generate G A\" using generate.one b by blast\nqed\n\ntext \\<open>We can characterize a complementary family of subgroups when the only way to form the neutral\nelement as a product of picked elements from each subgroup is to pick the neutral element from each\nsubgroup.\\<close>\n\nlemma (in comm_group) compl_fam_imp_triv_finprod:\n  assumes \"compl_fam S I\" \"finite I\" \"\\<And>i. i \\<in> I \\<Longrightarrow> subgroup (S i) G\"\n  and \"finprod G f I = \\<one>\" \"f \\<in> Pi I S\"\n  shows \"\\<forall>i\\<in>I. f i = \\<one>\"\nproof (rule ccontr; clarify)\n  from assms(5) have f: \"f i \\<in> (S i)\" if \"i \\<in> I\" for i using that by fastforce\n  fix i\n  assume i: \"i \\<in> I\"\n  have si: \"subgroup (S i) G\" using assms(3)[OF i] .\n  consider (triv) \"(S i) = {\\<one>}\" | (not_triv) \"(S i) \\<noteq> {\\<one>}\" by blast\n  thus \"f i = \\<one>\"\n  proof (cases)\n    case triv\n    then show ?thesis using f[OF i] by blast\n  next\n    case not_triv\n    show ?thesis\n    proof (rule ccontr)\n      have fc: \"f i \\<in> carrier G\" using f[OF i] subgroup.subset[OF si] by blast\n      assume no: \"f i \\<noteq> \\<one>\"\n      have fH: \"f i \\<in> (S i)\" using f[OF i] .\n      from subgroup.m_inv_closed[OF si this] have ifi: \"inv (f i) \\<in> (S i)\" .\n      moreover have \"inv (f i) \\<noteq> \\<one>\" using no fc by simp\n      moreover have \"inv (f i) = finprod G f (I - {i})\"\n      proof -\n        have \"\\<one> = finprod G f I\" using assms(4) by simp\n        also have \"\\<dots> = finprod G f (insert i (I - {i}))\"\n        proof -\n          have \"I = insert i (I - {i})\" using i by fast\n          thus ?thesis by simp\n        qed\n        also have \"\\<dots> = f i \\<otimes> finprod G f (I - {i})\"\n        proof(intro finprod_insert)\n          show \"finite (I - {i})\" using assms(2) by blast\n          show \"i \\<notin> I - {i}\" by blast\n          show \"f \\<in> I - {i} \\<rightarrow> carrier G\" using assms(3) f subgroup.subset by blast\n          show \"f i \\<in> carrier G\" by fact\n        qed\n        finally have o: \"\\<one> = f i \\<otimes> finprod G f (I - {i})\" .\n        show ?thesis\n        proof(intro inv_equality)\n          show \"f i \\<in> carrier G\" by fact\n          show \"finprod G f (I - {i}) \\<in> carrier G\"\n            by (intro finprod_closed; use assms(3) f subgroup.subset in blast)\n          from m_comm[OF this fc] o show \"finprod G f (I - {i}) \\<otimes> f i = \\<one>\" by simp\n        qed\n      qed\n      moreover have \"finprod G f (I - {i}) \\<in> IDirProds G S (I - {i})\"\n      proof (intro finprod_closed_subgroup IDirProds_is_subgroup)\n        show \"\\<Union> (S ` (I - {i})) \\<subseteq> carrier G\" using assms(3) subgroup.subset by auto\n        have \"f j \\<in> (IDirProds G S (I - {i}))\" if \"j \\<in> (I - {i})\" for j\n          using IDirProds_incl[OF that] f that by blast\n        thus \"f \\<in> I - {i} \\<rightarrow> IDirProds G S (I - {i})\" by blast\n      qed\n      ultimately have \"\\<not>complementary (S i) (IDirProds G S (I - {i}))\"\n        unfolding complementary_def by auto\n      thus False using assms(1) i unfolding compl_fam_def by blast\n    qed\n  qed\nqed\n\nlemma (in comm_group) triv_finprod_imp_compl_fam:\n  assumes \"finite I\" \"\\<And>i. i \\<in> I \\<Longrightarrow> subgroup (S i) G\"\n  and \"\\<forall>f \\<in> Pi I S. finprod G f I = \\<one> \\<longrightarrow> (\\<forall>i\\<in>I. f i = \\<one>)\"\n  shows \"compl_fam S I\"\nproof (unfold compl_fam_def; rule)\n  fix k\n  assume k: \"k \\<in> I\"\n  let ?DP = \"IDirProds G S (I - {k})\"\n  show \"complementary (S k) ?DP\"\n  proof (rule ccontr; unfold complementary_def)\n    have sk: \"subgroup (S k) G\" using assms(2)[OF k] .\n    have sDP: \"subgroup ?DP G\"\n      by (intro IDirProds_is_subgroup; use subgroup.subset[OF assms(2)] in blast)\n    assume a: \"(S k) \\<inter> IDirProds G S (I - {k}) \\<noteq> {\\<one>}\"\n    then obtain x where x: \"x \\<in> (S k)\" \"x \\<in> IDirProds G S (I - {k})\" \"x \\<noteq> \\<one>\"\n      using subgroup.one_closed sk sDP by blast\n    then have \"x \\<in> (\\<lambda>x. finprod G x (I - {k})) ` (Pi (I - {k}) S)\"\n      using IDirProds_eq_finprod_Pi[of \"(I - {k})\"] assms(1, 2) by blast\n    then obtain ht where ht: \"finprod G ht (I - {k}) = x\" \"ht \\<in> Pi (I - {k}) S\" by blast\n    define h where h: \"h = (ht(k := inv x))\"\n    then have hPi: \"h \\<in> Pi I S\" using ht subgroup.m_inv_closed[OF assms(2)[OF k] x(1)] by auto\n    have \"finprod G h (I - {k}) = x\"\n    proof (subst ht(1)[symmetric], intro finprod_cong)\n      show \"I - {k} = I - {k}\" by simp\n      show \"(h \\<in> I - {k} \\<rightarrow> carrier G) = True\" using h ht(2) subgroup.subset[OF assms(2)]\n        unfolding Pi_def id_def by auto\n      show \"\\<And>i. i \\<in> I - {k} =simp=> h i = ht i\" using ht(2) h by simp\n    qed\n    moreover have \"finprod G h I = h k \\<otimes> finprod G h (I - {k})\"\n      by (intro finprod_minus; use k assms hPi subgroup.subset[OF assms(2)] Pi_def in blast)\n    ultimately have \"finprod G h I = inv x \\<otimes> x\" using h by simp\n    then have \"finprod G h I = \\<one>\" using subgroup.subset[OF sk] x(1) by auto\n    moreover have \"h k \\<noteq> \\<one>\" using h x(3) subgroup.subset[OF sk] x(1) by force\n    ultimately show False using assms(3) k hPi by blast\n  qed\nqed\n\nlemma (in comm_group) triv_finprod_iff_compl_fam_Pi:\n  assumes \"finite I\" \"\\<And>i. i \\<in> I \\<Longrightarrow> subgroup (S i) G\"\n  shows \"compl_fam S I \\<longleftrightarrow> (\\<forall>f \\<in> Pi I S. finprod G f I = \\<one> \\<longrightarrow> (\\<forall>i\\<in>I. f i = \\<one>))\"\n  using compl_fam_imp_triv_finprod triv_finprod_imp_compl_fam assms by blast\n\nlemma (in comm_group) triv_finprod_iff_compl_fam_PiE:\n  assumes \"finite I\" \"\\<And>i. i \\<in> I \\<Longrightarrow> subgroup (S i) G\"\n  shows \"compl_fam S I \\<longleftrightarrow> (\\<forall>f \\<in> Pi\\<^sub>E I S. finprod G f I = \\<one> \\<longrightarrow> (\\<forall>i\\<in>I. f i = \\<one>))\"\nproof\n  show \"compl_fam S I \\<Longrightarrow> \\<forall>f\\<in>Pi\\<^sub>E I S. finprod G f I = \\<one> \\<longrightarrow> (\\<forall>i\\<in>I. f i = \\<one>)\"\n    using triv_finprod_iff_compl_fam_Pi[OF assms] by auto\n  have \"\\<forall>f\\<in>Pi\\<^sub>E I S. finprod G f I = \\<one> \\<longrightarrow> (\\<forall>i\\<in>I. f i = \\<one>)\n    \\<Longrightarrow> \\<forall>f\\<in>Pi I S. finprod G f I = \\<one> \\<longrightarrow> (\\<forall>i\\<in>I. f i = \\<one>)\"\n  proof(rule+)\n    fix f i\n    assume f: \"f \\<in> Pi I S\" \"finprod G f I = \\<one>\" and i: \"i \\<in> I\"\n    assume allf: \"\\<forall>f\\<in>Pi\\<^sub>E I S. finprod G f I = \\<one> \\<longrightarrow> (\\<forall>i\\<in>I. f i = \\<one>)\"\n    have \"f i = restrict f I i\" using i by simp\n    moreover have \"finprod G (restrict f I) I = finprod G f I\"\n      using f subgroup.subset[OF assms(2)] unfolding Pi_def by (intro finprod_cong; auto)\n    moreover have \"restrict f I \\<in> Pi\\<^sub>E I S\" using f by simp\n    ultimately show \"f i = \\<one>\" using allf f i by metis\n  qed\n  thus \"\\<forall>f\\<in>Pi\\<^sub>E I S. finprod G f I = \\<one> \\<longrightarrow> (\\<forall>i\\<in>I. f i = \\<one>) \\<Longrightarrow> compl_fam S I\"\n    using triv_finprod_iff_compl_fam_Pi[OF assms] by presburger\nqed\n\ntext \\<open>The finite product also distributes when nested.\\<close>\n\n(* Manuel Eberl, TODO: move to library *)\nlemma (in comm_monoid) finprod_Sigma:\n  assumes \"finite A\" \"\\<And>x. x \\<in> A \\<Longrightarrow> finite (B x)\"\n  assumes \"\\<And>x y. x \\<in> A \\<Longrightarrow> y \\<in> B x \\<Longrightarrow> g x y \\<in> carrier G\"\n  shows   \"(\\<Otimes>x\\<in>A. \\<Otimes>y\\<in>B x. g x y) = (\\<Otimes>z\\<in>Sigma A B. case z of (x, y) \\<Rightarrow> g x y)\"\n  using assms\nproof (induction A rule: finite_induct)\n  case (insert x A)\n  have \"(\\<Otimes>z\\<in>Sigma (insert x A) B. case z of (x, y) \\<Rightarrow> g x y) =\n          (\\<Otimes>z\\<in>Pair x ` B x. case z of (x, y) \\<Rightarrow> g x y) \\<otimes> (\\<Otimes>z\\<in>Sigma A B. case z of (x, y) \\<Rightarrow> g x y)\"\n    unfolding Sigma_insert using insert.prems insert.hyps\n    by (subst finprod_Un_disjoint) auto\n  also have \"(\\<Otimes>z\\<in>Sigma A B. case z of (x, y) \\<Rightarrow> g x y) = (\\<Otimes>x\\<in>A. \\<Otimes>y\\<in>B x. g x y)\"\n    using insert.prems insert.hyps by (subst insert.IH [symmetric]) auto\n  also have \"(\\<Otimes>z\\<in>Pair x ` B x. case z of (x, y) \\<Rightarrow> g x y) = (\\<Otimes>y\\<in>B x. g x y)\"\n    using insert.prems insert.hyps by (subst finprod_reindex) (auto intro: inj_onI)\n  finally show ?case\n    using insert.hyps insert.prems by simp\nqed auto\n\ntext \\<open>With the now proven facts, we are able to provide criterias to inductively construct a\ngroup that is the internal direct product of a set of generators.\\<close>\n\n(* belongs to IDirProd, but uses finprod stuff *)\nlemma (in comm_group) idirprod_generate_ind:\n  assumes \"finite gs\" \"gs \\<subseteq> carrier G\" \"g \\<in> carrier G\"\n          \"is_idirprod (generate G gs) (\\<lambda>g. generate G {g}) gs\"\n          \"complementary (generate G {g}) (generate G gs)\"\n  shows \"is_idirprod (generate G (gs \\<union> {g})) (\\<lambda>g. generate G {g}) (gs \\<union> {g})\"\nproof(cases \"g \\<in> gs\")\n  case True\n  hence \"gs = (gs \\<union> {g})\" by blast\n  thus ?thesis using assms(4) by auto \nnext\n  case gngs: False\n  show ?thesis\n  proof (intro is_idirprod_subgroup_suffices)\n    have gsgc: \"gs \\<union> {g} \\<subseteq> carrier G\" using assms(2, 3) by blast\n    thus \"generate G (gs \\<union> {g}) = IDirProds G (\\<lambda>g. generate G {g}) (gs \\<union> {g})\"\n      unfolding IDirProds_def using generate_idem_Un by presburger\n    show \"\\<forall>i\\<in>gs \\<union> {g}. subgroup (generate G {i}) G\" using generate_is_subgroup gsgc by auto\n    have sg: \"subgroup (generate G {g}) G\" by (intro generate_is_subgroup, use assms(3) in blast)\n    from assms(4) is_idirprod_def have ih: \"\\<forall>x. x \\<in> gs \\<longrightarrow> generate G {x} \\<lhd> G\"\n                                           \"compl_fam (\\<lambda>g. generate G {g}) gs\"\n      by fastforce+\n    hence ca: \"complementary (generate G {a}) (generate G (gs - {a}))\" if \"a \\<in> gs\" for a\n      unfolding compl_fam_def IDirProds_def\n      using gsgc generate_idem_Un[of \"gs - {a}\"] that by fastforce\n    have aux: \"gs \\<union> {g} - {i} \\<subseteq> carrier G\" for i using gsgc by blast\n    show \"compl_fam (\\<lambda>g. generate G {g}) (gs \\<union> {g})\"\n    proof(unfold compl_fam_def IDirProds_def, subst generate_idem_Un[OF aux],\n          rule, rule ccontr)\n      fix h\n      assume h: \"h \\<in> gs \\<union> {g}\"\n      assume c: \"\\<not> complementary (generate G {h}) (generate G (gs \\<union> {g} - {h}))\"\n      show \"False\"\n      proof (cases \"h = g\")\n        case True\n        with c have \"\\<not> complementary (generate G {g}) (generate G (gs - {g}))\" by auto\n        moreover have \"complementary (generate G {g}) (generate G (gs - {g}))\"\n          by (rule subgroup_subset_complementary[OF generate_is_subgroup generate_is_subgroup[of gs]\n                   generate_is_subgroup mono_generate], use assms(2, 3, 5) in auto)\n        ultimately show False by blast\n      next\n        case hng: False\n        hence h: \"h \\<in> gs\" \"h \\<noteq> g\" using h by blast+\n        hence \"gs \\<union> {g} - {h} = gs - {h} \\<union> {g}\" by blast\n        with c have c: \"\\<not> complementary (generate G {h}) (generate G (gs - {h} \\<union> {g}))\" by argo\n        then obtain k where k: \"k \\<in> generate G {h}\" \"k \\<in> generate G (gs - {h} \\<union> {g})\" \"k \\<noteq> \\<one>\"\n          unfolding complementary_def using generate.one by blast \n        with ca have kngh: \"k \\<notin> generate G (gs - {h})\" using h unfolding complementary_def by blast\n        from k(2) generate_eq_finprod_PiE_image[of \"gs - {h} \\<union> {g}\"] assms(1) gsgc\n        obtain f where f:\n          \"k = finprod G f (gs - {h} \\<union> {g})\" \"f \\<in> (\\<Pi>\\<^sub>E a\\<in>gs - {h} \\<union> {g}. generate G {a})\"\n          by blast\n        have fg: \"f a \\<in> generate G {a}\" if \"a \\<in> (gs - {h} \\<union> {g})\" for a using that f(2) by blast\n        have fc: \"f a \\<in> carrier G\" if \"a \\<in> (gs - {h} \\<union> {g})\" for a\n        proof -\n          have \"generate G {a} \\<subseteq> carrier G\" if \"a \\<in> (gs - {h} \\<union> {g})\" for a\n            using that generate_incl[of \"{a}\"] gsgc by blast\n          thus \"f a \\<in> carrier G\" using that fg by auto\n        qed\n        have kp: \"k = f g \\<otimes> finprod G f (gs - {h})\"\n        proof -\n          have \"(gs - {h} \\<union> {g}) = insert g (gs - {h})\" by fast\n          moreover have \"finprod G f (insert g (gs - {h})) = f g \\<otimes> finprod G f (gs - {h})\"\n            by (intro finprod_insert, use fc assms(1) gngs in auto)\n          ultimately show ?thesis using f(1) by argo\n        qed\n        have fgsh: \"finprod G f (gs - {h}) \\<in> generate G (gs - {h})\"\n        proof(intro finprod_closed_subgroup[OF generate_is_subgroup])\n          show \"gs - {h} \\<subseteq> carrier G\" using gsgc by blast\n          have \"f a \\<in> generate G (gs - {h})\" if \"a \\<in> (gs - {h})\" for a\n            using mono_generate[of \"{a}\" \"gs - {h}\"] fg that by blast\n          thus \"f \\<in> gs - {h} \\<rightarrow> generate G (gs - {h})\" by blast\n        qed\n        have \"f g \\<otimes> finprod G f (gs - {h}) \\<notin> generate G gs\"\n        proof\n          assume fpgs: \"f g \\<otimes> finprod G f (gs - {h}) \\<in> generate G gs\"\n          from fgsh have fgsgs: \"finprod G f (gs - {h}) \\<in> generate G gs\"\n            using mono_generate[of \"gs - {h}\" gs] by blast\n          have fPi: \"f \\<in> (\\<Pi> a\\<in>(gs - {h}). generate G {a})\" using f by blast\n          have gI: \"generate G (gs - {h})\n                  = (\\<lambda>x. finprod G x (gs - {h})) ` (\\<Pi> a\\<in>gs - {h}. generate G {a})\"\n            using generate_eq_finprod_Pi_image[of \"gs - {h}\"] assms(1, 2) by blast\n          have fgno: \"f g \\<noteq> \\<one>\"\n          proof (rule ccontr)\n            assume o: \"\\<not> f g \\<noteq> \\<one>\"\n            hence kf: \"k = finprod G f (gs - {h})\" using kp finprod_closed fc by auto\n            hence \"k \\<in> generate G (gs - {h})\" using fPi gI by blast\n            thus False using k ca h unfolding complementary_def by blast\n          qed\n          from fpgs have \"f g \\<in> generate G gs\"\n            using subgroup.mult_in_cancel_right[OF generate_is_subgroup[OF assms(2)] fc[of g] fgsgs]\n            by blast\n          with fgno assms(5) fg[of g] show \"False\" unfolding complementary_def by blast\n        qed\n        moreover have \"k \\<in> generate G gs\" using k(1) mono_generate[of \"{h}\" gs] h(1) by blast\n        ultimately show False using kp by blast\n      qed\n    qed\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/Finitely_Generated_Abelian_Groups/Finite_Product_Extend.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8289388167733099, "lm_q2_score": 0.8791467690927438, "lm_q1q2_score": 0.7287588825418174}}
{"text": "(* Author: Tobias Nipkow *)\n\nsection \"AVL Tree with Balance Factors (1)\"\n\ntheory AVL_Bal_Set\nimports\n  Cmp\n  Isin2\nbegin\n\ntext \\<open>This version detects height increase/decrease from above via the change in balance factors.\\<close>\n\ndatatype bal = Lh | Bal | Rh\n\ntype_synonym 'a tree_bal = \"('a * bal) tree\"\n\ntext \\<open>Invariant:\\<close>\n\nfun avl :: \"'a tree_bal \\<Rightarrow> bool\" where\n\"avl Leaf = True\" |\n\"avl (Node l (a,b) r) =\n  ((case b of\n    Bal \\<Rightarrow> height r = height l |\n    Lh \\<Rightarrow> height l = height r + 1 |\n    Rh \\<Rightarrow> height r = height l + 1)\n  \\<and> avl l \\<and> avl r)\"\n\n\nsubsection \\<open>Code\\<close>\n\nfun is_bal where\n\"is_bal (Node l (a,b) r) = (b = Bal)\"\n\nfun incr where\n\"incr t t' = (t = Leaf \\<or> is_bal t \\<and> \\<not> is_bal t')\"\n\nfun rot2 where\n\"rot2 A a B c C = (case B of\n  (Node B\\<^sub>1 (b, bb) B\\<^sub>2) \\<Rightarrow>\n    let b\\<^sub>1 = if bb = Rh then Lh else Bal;\n        b\\<^sub>2 = if bb = Lh then Rh else Bal\n    in Node (Node A (a,b\\<^sub>1) B\\<^sub>1) (b,Bal) (Node B\\<^sub>2 (c,b\\<^sub>2) C))\"\n\nfun balL :: \"'a tree_bal \\<Rightarrow> 'a \\<Rightarrow> bal \\<Rightarrow> 'a tree_bal \\<Rightarrow> 'a tree_bal\" where\n\"balL AB c bc C = (case bc of\n     Bal \\<Rightarrow> Node AB (c,Lh) C |\n     Rh \\<Rightarrow> Node AB (c,Bal) C |\n     Lh \\<Rightarrow> (case AB of\n       Node A (a,Lh) B \\<Rightarrow> Node A (a,Bal) (Node B (c,Bal) C) |\n       Node A (a,Bal) B \\<Rightarrow> Node A (a,Rh) (Node B (c,Lh) C) |\n       Node A (a,Rh) B \\<Rightarrow> rot2 A a B c C))\"\n\nfun balR :: \"'a tree_bal \\<Rightarrow> 'a \\<Rightarrow> bal \\<Rightarrow> 'a tree_bal \\<Rightarrow> 'a tree_bal\" where\n\"balR A a ba BC = (case ba of\n     Bal \\<Rightarrow> Node A (a,Rh) BC |\n     Lh \\<Rightarrow> Node A (a,Bal) BC |\n     Rh \\<Rightarrow> (case BC of\n       Node B (c,Rh) C \\<Rightarrow> Node (Node A (a,Bal) B) (c,Bal) C |\n       Node B (c,Bal) C \\<Rightarrow> Node (Node A (a,Rh) B) (c,Lh) C |\n       Node B (c,Lh) C \\<Rightarrow> rot2 A a B c C))\"\n\nfun insert :: \"'a::linorder \\<Rightarrow> 'a tree_bal \\<Rightarrow> 'a tree_bal\" where\n\"insert x Leaf = Node Leaf (x, Bal) Leaf\" |\n\"insert x (Node l (a, b) r) = (case cmp x a of\n   EQ \\<Rightarrow> Node l (a, b) r |\n   LT \\<Rightarrow> let l' = insert x l in if incr l l' then balL l' a b r else Node l' (a,b) r |\n   GT \\<Rightarrow> let r' = insert x r in if incr r r' then balR l a b r' else Node l (a,b) r')\"\n\nfun decr where\n\"decr t t' = (t \\<noteq> Leaf \\<and> (t' = Leaf \\<or> \\<not> is_bal t \\<and> is_bal t'))\"\n\nfun split_max :: \"'a tree_bal \\<Rightarrow> 'a tree_bal * 'a\" where\n\"split_max (Node l (a, ba) r) =\n  (if r = Leaf then (l,a)\n   else let (r',a') = split_max r;\n            t' = if decr r r' then balL l a ba r' else Node l (a,ba) r'\n        in (t', a'))\"\n\nfun delete :: \"'a::linorder \\<Rightarrow> 'a tree_bal \\<Rightarrow> 'a tree_bal\" where\n\"delete _ Leaf = Leaf\" |\n\"delete x (Node l (a, ba) r) =\n  (case cmp x a of\n     EQ \\<Rightarrow> if l = Leaf then r\n           else let (l', a') = split_max l in\n                if decr l l' then balR l' a' ba r else Node l' (a',ba) r |\n     LT \\<Rightarrow> let l' = delete x l in if decr l l' then balR l' a ba r else Node l' (a,ba) r |\n     GT \\<Rightarrow> let r' = delete x r in if decr r r' then balL l a ba r' else Node l (a,ba) r')\"\n\n\nsubsection \\<open>Proofs\\<close>\n\nlemmas split_max_induct = split_max.induct[case_names Node Leaf]\n\nlemmas splits = if_splits tree.splits bal.splits\n\ndeclare Let_def [simp]\n\nsubsubsection \"Proofs about insertion\"\n\nlemma avl_insert: \"avl t \\<Longrightarrow>\n  avl(insert x t) \\<and>\n  height(insert x t) = height t + (if incr t (insert x t) then 1 else 0)\"\napply(induction x t rule: insert.induct)\napply(auto split!: splits)\ndone\n\ntext \\<open>The following two auxiliary lemma merely simplify the proof of \\<open>inorder_insert\\<close>.\\<close>\n\n\n\nlemma [simp]: \"avl t \\<Longrightarrow> insert x t \\<noteq> \\<langle>l, (a, Rh), \\<langle>\\<rangle>\\<rangle> \\<and> insert x t \\<noteq> \\<langle>\\<langle>\\<rangle>, (a, Lh), r\\<rangle>\"\nby(drule avl_insert[of _ x]) (auto split: splits)\n\ntheorem inorder_insert:\n  \"\\<lbrakk> avl t;  sorted(inorder t) \\<rbrakk> \\<Longrightarrow> inorder(insert x t) = ins_list x (inorder t)\"\napply(induction t)\napply (auto simp: ins_list_simps split!: splits)\ndone\n\n\nsubsubsection \"Proofs about deletion\"\n\nlemma inorder_balR:\n  \"\\<lbrakk> ba = Rh \\<longrightarrow> r \\<noteq> Leaf; avl r \\<rbrakk>\n  \\<Longrightarrow> inorder (balR l a ba r) = inorder l @ a # inorder r\"\nby (auto split: splits)\n\nlemma inorder_balL:\n  \"\\<lbrakk> ba = Lh \\<longrightarrow> l \\<noteq> Leaf; avl l \\<rbrakk>\n   \\<Longrightarrow> inorder (balL l a ba r) = inorder l @ a # inorder r\"\nby (auto split: splits)\n\nlemma height_1_iff: \"avl t \\<Longrightarrow> height t = Suc 0 \\<longleftrightarrow> (\\<exists>x. t = Node Leaf (x,Bal) Leaf)\"\nby(cases t) (auto split: splits prod.splits)\n\nlemma avl_split_max:\n  \"\\<lbrakk> split_max t = (t',a); avl t; t \\<noteq> Leaf \\<rbrakk> \\<Longrightarrow>\n   avl t' \\<and> height t = height t' + (if decr t t' then 1 else 0)\"\napply(induction t arbitrary: t' a rule: split_max_induct)\n apply(auto simp: max_absorb1 max_absorb2 height_1_iff split!: splits prod.splits)\ndone\n\nlemma avl_delete: \"avl t \\<Longrightarrow>\n  avl (delete x t) \\<and>\n  height t = height (delete x t) + (if decr t (delete x t) then 1 else 0)\"\napply(induction x t rule: delete.induct)\n apply(auto simp: max_absorb1 max_absorb2 height_1_iff dest: avl_split_max split!: splits prod.splits)\ndone\n\nlemma inorder_split_maxD:\n  \"\\<lbrakk> split_max t = (t',a); t \\<noteq> Leaf; avl t \\<rbrakk> \\<Longrightarrow>\n   inorder t' @ [a] = inorder t\"\napply(induction t arbitrary: t' rule: split_max.induct)\n apply(fastforce split!: splits prod.splits)\napply simp\ndone\n\nlemma neq_Leaf_if_height_neq_0: \"height t \\<noteq> 0 \\<Longrightarrow> t \\<noteq> Leaf\"\nby auto\n\nlemma split_max_Leaf: \"\\<lbrakk> t \\<noteq> Leaf; avl t \\<rbrakk> \\<Longrightarrow> split_max t = (\\<langle>\\<rangle>, x) \\<longleftrightarrow> t = Node Leaf (x,Bal) Leaf\"\nby(cases t) (auto split: splits prod.splits)\n\ntheorem inorder_delete:\n  \"\\<lbrakk> avl t; sorted(inorder t) \\<rbrakk>  \\<Longrightarrow> inorder (delete x t) = del_list x (inorder t)\"\napply(induction t rule: tree2_induct)\napply(auto simp: del_list_simps inorder_balR inorder_balL avl_delete inorder_split_maxD\n                 split_max_Leaf neq_Leaf_if_height_neq_0\n           simp del: balL.simps balR.simps split!: splits prod.splits)\ndone\n\n\nsubsubsection \\<open>Set Implementation\\<close>\n\ninterpretation S: Set_by_Ordered\nwhere empty = Leaf and isin = isin\n  and insert = insert\n  and delete = delete\n  and inorder = inorder and inv = avl\nproof (standard, goal_cases)\n  case 1 show ?case by (simp)\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)\nnext\n  case 6 thus ?case by (simp add: avl_insert)\nnext\n  case 7 thus ?case by (simp add: avl_delete)\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_Bal_Set.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467675095292, "lm_q2_score": 0.8289388083214156, "lm_q1q2_score": 0.7287588737989739}}
{"text": "section\\<open>Lindel\\\"of 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 meson\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": "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/Lindelof_Spaces.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467675095294, "lm_q2_score": 0.828938806208442, "lm_q1q2_score": 0.7287588719413599}}
{"text": "(*  Author:     Tobias Nipkow, 2002  *)\n\nsection \"Arrow's Theorem for Utility Functions\"\n\ntheory Arrow_Utility imports Complex_Main\nbegin\n\ntext\\<open>This theory formalizes the first proof due to\nGeanakoplos~\\cite{Geanakoplos05}.  In contrast to the standard model\nof preferences as linear orders, we model preferences as \\emph{utility\nfunctions} mapping each alternative to a real number. The type of\nalternatives and voters is assumed to be finite.\\<close>\n\ntypedecl alt\ntypedecl indi\n\naxiomatization where\n  alt3: \"\\<exists>a b c::alt. distinct[a,b,c]\" and\n  finite_alt: \"finite(UNIV:: alt set)\" and\n\n  finite_indi: \"finite(UNIV:: indi set)\"\n\nlemma third_alt: \"a \\<noteq> b \\<Longrightarrow> \\<exists>c::alt. distinct[a,b,c]\"\nusing alt3 by simp metis\n\nlemma alt2: \"\\<exists>b::alt. b \\<noteq> a\"\nusing alt3 by simp metis\n\ntype_synonym pref = \"alt \\<Rightarrow> real\"\ntype_synonym prof = \"indi \\<Rightarrow> pref\"\n\ndefinition\n top :: \"pref \\<Rightarrow> alt \\<Rightarrow> bool\" (infixr \"<\\<cdot>\" 60) where\n\"p <\\<cdot> b  \\<equiv>  \\<forall>a. a \\<noteq> b \\<longrightarrow> p a < p b\"\n\ndefinition\n bot :: \"alt \\<Rightarrow> pref \\<Rightarrow> bool\" (infixr \"\\<cdot><\" 60) where\n\"b \\<cdot>< p  \\<equiv>  \\<forall>a. a \\<noteq> b \\<longrightarrow> p b < p a\"\n\ndefinition\n extreme :: \"pref \\<Rightarrow> alt \\<Rightarrow> bool\" where\n\"extreme p b  \\<equiv>  b \\<cdot>< p \\<or> p <\\<cdot> b\"\n\nabbreviation\n\"Extreme P b == \\<forall>i. extreme (P i) b\"\n\n\n\nlemma less_if_bot[simp]: \"\\<lbrakk> b \\<cdot>< p; x \\<noteq> b \\<rbrakk> \\<Longrightarrow> p b < p x\"\nby(simp add:bot_def)\n\nlemma [simp]: \"\\<lbrakk> p <\\<cdot> b; x \\<noteq> b \\<rbrakk> \\<Longrightarrow> p x < p b\"\nby(simp add:top_def)\n\nlemma [simp]: assumes top: \"p <\\<cdot> b\" shows \"\\<not> p b < p c\"\nproof (cases)\n  assume \"b = c\" thus ?thesis by simp\nnext\n  assume \"b \\<noteq> c\"\n  with top have \"p c < p b\" by (simp add:eq_sym_conv)\n  thus ?thesis by simp\nqed\n\nlemma not_less_if_bot[simp]:\n  assumes bot: \"b \\<cdot>< p\" shows \"\\<not> p c < p b\"\nproof (cases)\n  assume \"b = c\" thus ?thesis by simp\nnext\n  assume \"b \\<noteq> c\"\n  with bot have \"p b < p c\" by (simp add:eq_sym_conv)\n  thus ?thesis by simp\nqed\n\nlemma top_impl_not_bot[simp]: \"p <\\<cdot> b \\<Longrightarrow> \\<not> b \\<cdot>< p\"\nby(unfold bot_def, simp add:alt2)\n\nlemma [simp]: \"extreme p b \\<Longrightarrow> (\\<not> p <\\<cdot> b) = (b \\<cdot>< p)\"\napply(unfold extreme_def)\napply(fastforce dest:top_impl_not_bot)\ndone\n\nlemma [simp]: \"extreme p b \\<Longrightarrow> (\\<not> b \\<cdot>< p) = (p <\\<cdot> b)\"\napply(unfold extreme_def)\napply(fastforce dest:top_impl_not_bot)\ndone\n\ntext\\<open>Auxiliary construction to hide details of preference model.\\<close>\n\ndefinition\n mktop :: \"pref \\<Rightarrow> alt \\<Rightarrow> pref\" where\n\"mktop p b \\<equiv> p(b := Max(range p) + 1)\"\n\ndefinition\n mkbot :: \"pref \\<Rightarrow> alt \\<Rightarrow> pref\" where\n\"mkbot p b \\<equiv> p(b := Min(range p) - 1)\"\n\ndefinition\n between :: \"pref \\<Rightarrow> alt \\<Rightarrow> alt \\<Rightarrow> alt \\<Rightarrow> pref\" where\n\"between p a b c \\<equiv> p(b := (p a + p c)/2)\"\n\ntext\\<open>To make things simpler:\\<close>\ndeclare between_def[simp]\n\nlemma [simp]: \"a \\<noteq> b \\<Longrightarrow> mktop p b a = p a\"\nby(simp add:mktop_def)\n\nlemma [simp]: \"a \\<noteq> b \\<Longrightarrow> mkbot p b a = p a\"\nby(simp add:mkbot_def)\n\nlemma [simp]: \"a \\<noteq> b \\<Longrightarrow> p a < mktop p b b\"\nby(simp add:mktop_def finite_alt)\n\nlemma [simp]: \"a \\<noteq> b \\<Longrightarrow> mkbot p b b < p a\"\nby(simp add:mkbot_def finite_alt)\n\nlemma [simp]: \"mktop p b <\\<cdot> b\"\nby(simp add:mktop_def top_def finite_alt)\n\nlemma [simp]: \"\\<not> b \\<cdot>< mktop p b\"\nby(simp add:mktop_def bot_def alt2 finite_alt)\n\nlemma [simp]: \"a \\<noteq> b \\<Longrightarrow> \\<not> P p a < mkbot (P p) b b\"\nproof (simp add:mkbot_def finite_alt)\n  have \"\\<not> P p a + 1 < P p a\" by simp\n  thus \"\\<exists>x. \\<not> P p a + 1 < P p x\" ..\nqed\n\ntext\\<open>The proof starts here.\\<close>\n\nlocale arrow =\nfixes F :: \"prof \\<Rightarrow> pref\"\nassumes unanimity: \"(\\<And>i. P i a < P i b) \\<Longrightarrow> F P a < F P b\"\nand IIA:\n\"(\\<And>i. (P i a < P i b) = (P' i a < P' i b)) \\<Longrightarrow>\n (F P a < F P b) = (F P' a < F P' b)\"\nbegin\n\nlemmas IIA' = IIA[THEN iffD1]\n\ndefinition\n dictates :: \"indi \\<Rightarrow> alt \\<Rightarrow> alt \\<Rightarrow> bool\" (\"_ dictates _ < _\") where\n\"(i dictates a < b)  \\<equiv>  \\<forall>P. P i a < P i b \\<longrightarrow> F P a < F P b\"\ndefinition\n dictates2 :: \"indi \\<Rightarrow> alt \\<Rightarrow> alt \\<Rightarrow> bool\" (\"_ dictates _,_\") where\n\"(i dictates a,b)  \\<equiv>  (i dictates a < b) \\<and> (i dictates b < a)\"\ndefinition\n dictatesx:: \"indi \\<Rightarrow> alt \\<Rightarrow> bool\" (\"_ dictates'_except _\") where\n\"(i dictates_except c)  \\<equiv>  \\<forall>a b. c \\<notin> {a,b} \\<longrightarrow> (i dictates a<b)\"\ndefinition\n dictator :: \"indi \\<Rightarrow> bool\" where\n\"dictator i  \\<equiv>  \\<forall>a b. (i dictates a<b)\"\n\ndefinition\n pivotal :: \"indi \\<Rightarrow> alt \\<Rightarrow> bool\" where\n\"pivotal i b \\<equiv>\n \\<exists>P. Extreme P b  \\<and>  b \\<cdot>< P i  \\<and>  b \\<cdot>< F P  \\<and>\n     F (P(i := mktop (P i) b)) <\\<cdot> b\"\n\nlemma all_top[simp]: \"\\<forall>i. P i <\\<cdot> b \\<Longrightarrow> F P <\\<cdot> b\"\nby (unfold top_def) (simp add: unanimity)\n\nlemma not_extreme:\n  assumes nex: \"\\<not> extreme p b\"\n  shows \"\\<exists>a c. distinct[a,b,c] \\<and> \\<not> p a < p b \\<and> \\<not> p b < p c\"\nproof -\n  obtain a c where abc: \"a \\<noteq> b \\<and> \\<not> p a < p b\" \"b \\<noteq> c \\<and> \\<not> p b < p c\"\n    using nex by (unfold extreme_def top_def bot_def) fastforce\n  show ?thesis\n  proof (cases \"a = c\")\n    assume \"a \\<noteq> c\" thus ?thesis using abc by simp blast\n  next\n    assume ac: \"a = c\"\n    obtain d where d: \"distinct[a,b,d]\" using abc third_alt by blast\n    show ?thesis\n    proof (cases \"p b < p d\")\n      case False thus ?thesis using abc d by blast\n    next\n      case True\n      hence db: \"\\<not> p d < p b\" by arith\n      from d have \"distinct[d,b,c]\" by(simp add:ac eq_sym_conv)\n      thus ?thesis using abc db by blast\n    qed\n  qed\nqed\n\nlemma extremal:\n  assumes extremes: \"Extreme P b\" shows \"extreme (F P) b\"\nproof (rule ccontr)\n  assume nec: \"\\<not> extreme (F P) b\"\n  hence \"\\<exists>a c. distinct[a,b,c] \\<and> \\<not> F P a < F P b \\<and> \\<not> F P b < F P c\"\n    by(rule not_extreme)\n  then obtain a c where d: \"distinct[a,b,c]\" and\n    ab: \"\\<not> F P a < F P b\" and bc: \"\\<not> F P b < F P c\" by blast\n  let ?P = \"\\<lambda>i. if P i <\\<cdot> b then between (P i) a c b\n                else (P i)(c := P i a + 1)\"\n  have \"\\<not> F ?P a < F ?P b\"\n    using extremes d by(simp add:IIA[of _ _ _ P] ab)\n  moreover have \"\\<not> F ?P b < F ?P c\"\n    using extremes d by(simp add:IIA[of _ _ _ P] bc eq_sym_conv)\n  moreover have \"F ?P a < F ?P c\" by(rule unanimity)(insert d, simp)\n  ultimately show False by arith\nqed\n\n\nlemma pivotal_ind: assumes fin: \"finite D\"\n  shows \"\\<And>P. \\<lbrakk> D = {i. b \\<cdot>< P i}; Extreme P b; b \\<cdot>< F P \\<rbrakk>\n  \\<Longrightarrow> \\<exists>i. pivotal i b\" (is \"\\<And>P. ?D D P \\<Longrightarrow> ?E P \\<Longrightarrow> ?B P \\<Longrightarrow> _\")\nusing fin\nproof (induct)\n  case (empty P)\n  from empty(1,2) have \"\\<forall>i. P i <\\<cdot> b\" by simp\n  hence \"F P <\\<cdot> b\" by simp\n  hence False using empty by(blast dest:top_impl_not_bot)\n  thus ?case ..\nnext\n  fix D i P\n  assume IH: \"\\<And>P. ?D D P \\<Longrightarrow> ?E P \\<Longrightarrow> ?B P \\<Longrightarrow> \\<exists>i. pivotal i b\"\n    and \"?E P\" and \"?B P\" and insert: \"insert i D = {i. b \\<cdot>< P i}\" and \"i \\<notin> D\"\n  from insert have \"b \\<cdot>< P i\" by blast\n  let ?P = \"P(i := mktop (P i) b)\"\n  show \"\\<exists>i. pivotal i b\"\n  proof (cases \"F ?P <\\<cdot> b\")\n    case True\n    have \"pivotal i b\"\n    proof -\n      from \\<open>?E P\\<close> \\<open>?B P\\<close> \\<open>b \\<cdot>< P i\\<close> True\n      show ?thesis by(unfold pivotal_def, blast)\n    qed\n    thus ?thesis ..\n  next\n    case False\n    have \"D = {i. b \\<cdot>< ?P i}\"\n      by (rule set_eqI) (simp add:\\<open>i \\<notin> D\\<close>, insert insert, blast)\n    moreover have \"Extreme ?P b\"\n      using \\<open>?E P\\<close> by (simp add:extreme_def)\n    moreover have \"b \\<cdot>< F ?P\"\n      using extremal[OF \\<open>Extreme ?P b\\<close>] False by(simp del:fun_upd_apply)\n    ultimately show ?thesis by(rule IH)\n  qed\nqed\n\nlemma pivotal_exists: \"\\<exists>i. pivotal i b\"\nproof -\n  let ?P = \"(\\<lambda>_ a. if a=b then 0 else 1)::prof\"\n  have \"Extreme ?P b\" by(simp add:extreme_def bot_def)\n  moreover have \"b \\<cdot>< F ?P\"\n    by(simp add:bot_def unanimity del: less_if_bot not_less_if_bot)\n  ultimately show \"\\<exists>i. pivotal i b\"\n    by (rule pivotal_ind[OF finite_subset[OF subset_UNIV finite_indi] refl])\nqed\n\n\nlemma pivotal_xdictates: assumes pivo: \"pivotal i b\"\n  shows \"i dictates_except b\"\nproof -\n  have \"\\<And>a c. \\<lbrakk> a \\<noteq> b; b \\<noteq> c \\<rbrakk> \\<Longrightarrow> i dictates a < c\"\n  proof (unfold dictates_def, intro allI impI)\n    fix a c and P::prof\n    assume abc: \"a \\<noteq> b\" \"b \\<noteq> c\" and\n           ac: \"P i a < P i c\"\n    show \"F P a < F P c\"\n    proof -\n      obtain P1 P2 where\n        \"Extreme P1 b\" and \"b \\<cdot>< F P1\" and \"b \\<cdot>< P1 i\" and \"F P2 <\\<cdot> b\" and\n        [simp]: \"P2 = P1(i := mktop (P1 i) b)\"\n        using pivo by (unfold pivotal_def) fast\n      let ?P = \"\\<lambda>j. if j=i then between (P j) a b c\n                    else if P1 j <\\<cdot> b then mktop (P j) b else mkbot (P j) b\"\n      have eq: \"(F P a < F P c) = (F ?P a < F ?P c)\"\n        using abc by - (rule IIA, auto)\n      have \"F ?P a < F ?P b\"\n      proof (rule IIA')\n        fix j show \"(P2 j a < P2 j b) = (?P j a < ?P j b)\"\n          using \\<open>Extreme P1 b\\<close> by(simp add: ac)\n      next\n        show \"F P2 a < F P2 b\"\n          using \\<open>F P2 <\\<cdot> b\\<close> abc by(simp add: eq_sym_conv)\n      qed\n      also have \"\\<dots> < F ?P c\"\n      proof (rule IIA')\n        fix j show \"(P1 j b < P1 j c) = (?P j b < ?P j c)\"\n          using \\<open>Extreme P1 b\\<close> \\<open>b \\<cdot>< P1 i\\<close> by(simp add: ac)\n      next\n        show \"F P1 b < F P1 c\"\n          using \\<open>b \\<cdot>< F P1\\<close> abc by(simp add: eq_sym_conv)\n      qed\n      finally show ?thesis by(simp add:eq)\n    qed\n  qed\n  thus ?thesis  by(unfold dictatesx_def) fast\nqed\n\nlemma pivotal_is_dictator:\n  assumes pivo: \"pivotal i b\" and ab: \"a \\<noteq> b\" and d: \"j dictates a,b\"\n  shows \"i = j\"\nproof (rule ccontr)\n  assume pd: \"i \\<noteq> j\"\n  obtain P1 P2 where \"Extreme P1 b\" and \"b \\<cdot>< F P1\" and \"F P2 <\\<cdot> b\" and\n    P2: \"P2 = P1(i := mktop (P1 i) b)\"\n    using pivo by (unfold pivotal_def) fast\n  have \"~(P1 j a < P1 j b)\" (is \"~ ?ab\")\n  proof\n    assume \"?ab\"\n    hence \"F P1 a < F P1 b\" using d by(simp add: dictates_def dictates2_def)\n    with \\<open>b \\<cdot>< F P1\\<close> show False by simp\n  qed\n  hence \"P1 j b < P1 j a\" using \\<open>Extreme P1 b\\<close>[THEN spec, of j] ab\n    unfolding extreme_def top_def bot_def by metis\n  hence \"P2 j b < P2 j a\" using pd by (simp add:P2)\n  hence \"F P2 b < F P2 a\" using d by(simp add: dictates_def dictates2_def)\n  with \\<open>F P2 <\\<cdot> b\\<close> show False by simp\nqed\n\n\ntheorem dictator: \"\\<exists>i. dictator i\"\nproof-\n  from pivotal_exists[of b] obtain i where pivo: \"pivotal i b\" ..\n  { fix a assume neq: \"a \\<noteq> b\" have \"i dictates a,b\"\n    proof -\n      obtain c where dist: \"distinct[a,b,c]\"\n        using neq third_alt by blast\n      obtain j where \"pivotal j c\" using pivotal_exists by fast\n      hence \"j dictates_except c\" by(rule pivotal_xdictates)\n      hence b: \"j dictates a,b\" \n        using dist by(simp add:dictatesx_def dictates2_def eq_sym_conv)\n      with pivo neq have \"i = j\" by(rule pivotal_is_dictator)\n      thus ?thesis using b by simp\n    qed\n  }\n  with pivotal_xdictates[OF pivo] have \"dictator i\"\n    by(simp add: dictates_def dictatesx_def dictates2_def dictator_def)\n      (metis less_le)\n  thus ?thesis ..\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/ArrowImpossibilityGS/Thys/Arrow_Utility.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122163480666, "lm_q2_score": 0.8031738034238807, "lm_q1q2_score": 0.7287294036972275}}
{"text": "theory RelyGuarantee3\n  imports Language\nbegin\n\n\n\ndatatype 'a act = Act \"'a set\" \"'a rel\"\n\nfun eval_word :: \"'a act list \\<Rightarrow> 'a set \\<Rightarrow> 'a set\" where\n  \"eval_word [] p = p\"\n| \"eval_word (Act q x # xs) p = (if p \\<subseteq> q then eval_word xs (x `` p) else {})\"\n\nlemma eval_word_empty [simp]: \"eval_word xs {} = {}\"\nproof (induct xs)\n  case Nil show ?case by simp\nnext\n  case (Cons x xs) thus ?case by (cases x) simp\nqed\n\nlemma eval_append_word: \"eval_word (xs @ ys) h = eval_word ys (eval_word xs h)\"\nproof (induct xs arbitrary: h)\n  case Nil show ?case by simp\nnext\n  case (Cons x xs) thus ?case\n    by (cases x) simp\nqed\n\nlemma Image_continuous: \"x `` (\\<Union>X) = \\<Union>Image x ` X\"\n  by auto\n\nlemma eval_word_continuous: \"eval_word w (\\<Union>X) \\<subseteq> \\<Union>(eval_word w ` X)\"\nproof (induct w arbitrary: X)\n  case Nil show ?case by simp\nnext\n  case (Cons x xs)\n  show ?case\n  proof (induct x)\n    fix p x\n    {\n      assume \"\\<Union>X \\<subseteq> p\"\n      hence \"eval_word (Act p x # xs) (\\<Union>X) \\<subseteq> \\<Union> (eval_word (Act p x # xs) ` X)\"\n        apply (simp add: image_def)\n        apply (subst Image_continuous)\n        apply (rule order_trans[OF Cons.hyps])\n        by auto\n    }\n    moreover\n    {\n      assume \"\\<not> (\\<Union>X \\<subseteq> p)\"\n      hence \"eval_word (Act p x # xs) (\\<Union>X) \\<subseteq> Sup (eval_word (Act p x # xs) ` X)\"\n        by simp\n    }\n    ultimately show \"eval_word (Act p x # xs) (\\<Union>X) \\<subseteq> Sup (eval_word (Act p x # xs) ` X)\"\n      by blast\n  qed\nqed\n\ndefinition module :: \"'a act lan \\<Rightarrow> 'a set \\<Rightarrow> 'a set\" (infix \"\\<Colon>\" 60) where\n  \"x \\<Colon> h = Sup {eval_word w h|w. w \\<in> x}\"\n\nlemma (in complete_lattice) Sup_comp_mono [intro]: \"(\\<And>x. P x \\<Longrightarrow> f x \\<le> g x) \\<Longrightarrow> Sup {f x |x. P x} \\<le> Sup {g x |x. P x}\"\n  by (auto intro: Sup_mono)\n\nlemma (in complete_lattice) Sup_comp_conj: \"Sup {f x y |x y. P x \\<and> Q y} = Sup {Sup {f x y |x. P x} |y. Q y}\"\n  apply (rule antisym)\n  apply (simp_all add: Sup_le_iff)\n  apply auto\n  defer\n  apply (rule Sup_mono)\n  apply auto\n  apply (subgoal_tac \"f x y \\<le> Sup {f x y |y. Q y}\")\n  apply (erule order_trans)\n  defer\n  apply (metis (lifting, full_types) Sup_upper mem_Collect_eq)\n  apply (rule Sup_comp_mono)\n  by (metis (lifting, full_types) Sup_upper mem_Collect_eq)\n\nlemma mod_mult: \"y \\<Colon> (x \\<Colon> h) \\<subseteq> x \\<cdot> y \\<Colon> h\"\nproof -\n  have \"y \\<Colon> (x \\<Colon> h) = \\<Union>{eval_word yw (x \\<Colon> h)|yw. yw \\<in> y}\"\n    by (simp add: module_def)\n  also have \"... = \\<Union>{eval_word yw (\\<Union>{eval_word xw h|xw. xw \\<in> x})|yw. yw \\<in> y}\"\n    by (simp add: module_def)\n  also have \"... \\<subseteq> \\<Union>{\\<Union>{eval_word yw (eval_word xw h)|xw. xw \\<in> x}|yw. yw \\<in> y}\"\n    apply (rule Sup_comp_mono)\n    apply (rule order_trans[OF eval_word_continuous])\n    by (auto simp add: image_def)\n  also have \"... = \\<Union>{eval_word yw (eval_word xw h)|xw yw. xw \\<in> x \\<and> yw \\<in> y}\"\n    by blast\n  also have \"... = \\<Union>{eval_word (xw @ yw) h|xw yw. xw \\<in> x \\<and> yw \\<in> y}\"\n    by (simp add: eval_append_word)\n  also have \"... = \\<Union>{eval_word w h|w. w \\<in> x \\<cdot> y}\"\n    by (auto simp add: l_prod_def complex_product_def)\n  also have \"... = x \\<cdot> y \\<Colon> h\"\n    by (simp add: module_def)\n  finally show ?thesis .\nqed\n\nlemma mod_one [simp]: \"{[]} \\<Colon> h = h\"\n  by (simp add: module_def)\n\nlemma mod_zero [simp]: \"{} \\<Colon> h = {}\"\n  by (simp add: module_def)\n\nlemma mod_empty [simp]: \"x \\<Colon> {} = {}\"\n  by (simp add: module_def)\n\nlemma mod_distl: \"(x \\<union> y) \\<Colon> h = (x \\<Colon> h) \\<union> (y \\<Colon> h)\"\nproof -\n  have \"(x \\<union> y) \\<Colon> h = \\<Union>{eval_word w h|w. w \\<in> x \\<union> y}\"\n    by (simp add: module_def)\n  also have \"... = \\<Union>{eval_word w h|w. w \\<in> x \\<or> w \\<in> y}\"\n    by blast\n  also have \"... = \\<Union>{eval_word w h|w. w \\<in> x} \\<union> \\<Union>{eval_word w h|w. w \\<in> y}\"\n    by blast\n  also have \"... = (x \\<Colon> h) \\<union> (y \\<Colon> h)\"\n    by (simp add: module_def)\n  finally show ?thesis .\nqed\n\nfind_theorems \"op ``\" \"op \\<union>\"\n\nlemma eval_word_union: \"eval_word w (h \\<union> g) \\<subseteq> eval_word w h \\<union> eval_word w g\"\nproof (induct w arbitrary: h g)\n  case Nil show ?case by simp\nnext\n  case (Cons w ws) thus ?case\n    by (cases w) (simp add: Image_Un)\nqed\n\nlemma mod_distr: \"x \\<Colon> (h \\<union> g) \\<subseteq> (x \\<Colon> h) \\<union> (x \\<Colon> g)\"\nproof -\n  have \"x \\<Colon> (h \\<union> g) = \\<Union>{eval_word w (h \\<union> g)|w. w \\<in> x}\"\n    by (simp add: module_def)\n  also have \"... \\<subseteq> \\<Union>{eval_word w h \\<union> eval_word w g|w. w \\<in> x}\"\n    by (rule Sup_comp_mono) (rule eval_word_union)\n  also have \"... = \\<Union>{eval_word w h|w. w \\<in> x} \\<union> \\<Union>{eval_word w g|w. w \\<in> x}\"\n    by blast\n  also have \"... = (x \\<Colon> h) \\<union> (x \\<Colon> g)\"\n    by (simp add: module_def)\n  finally show ?thesis .\nqed\n\nlemma mod_isol: \"x \\<subseteq> y \\<Longrightarrow> x \\<Colon> p \\<subseteq> y \\<Colon> p\"\n  by (auto simp add: module_def)\n\ndefinition triple :: \"'a set \\<Rightarrow> 'a act lan \\<Rightarrow> 'a set \\<Rightarrow> bool\"\n  (\"\\<lbrace>_\\<rbrace> _ \\<lbrace>_\\<rbrace>\" [20,20,20] 100) where\n  \"\\<lbrace>p\\<rbrace> c \\<lbrace>q\\<rbrace> \\<equiv> c \\<Colon> p \\<subseteq> q\"\n\nlemma \"\\<lbrace>p\\<rbrace> c1 \\<lbrace>q\\<rbrace> \\<Longrightarrow> \\<lbrace>q\\<rbrace> c2 \\<lbrace>r\\<rbrace> \\<Longrightarrow> \\<lbrace>p\\<rbrace> c1 \\<cdot> c2 \\<lbrace>r\\<rbrace>\"\n  apply (simp add: triple_def)\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/Finite/RelyGuarantee3.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122163480667, "lm_q2_score": 0.8031738010682209, "lm_q1q2_score": 0.7287294015599087}}
{"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 :: \"term\" ..\n\naxiomatization\n  Zero :: nat    (\"0\") and\n  Suc :: \"nat => nat\" and\n  rec :: \"[nat, 'a, [nat, 'a] => 'a] => 'a\"\nwhere\n  induct [case_names 0 Suc, induct type: nat]:\n    \"P(0) ==> (!!x. P(x) ==> P(Suc(x))) ==> P(n)\" and\n  Suc_inject: \"Suc(m) = Suc(n) ==> m = n\" and\n  Suc_neq_0: \"Suc(m) = 0 ==> R\" and\n  rec_0: \"rec(0, a, f) = a\" and\n  rec_Suc: \"rec(Suc(m), a, f) = f(m, rec(m, a, f))\"\n\nlemma Suc_n_not_n: \"Suc(k) \\<noteq> k\"\nproof (induct k)\n  show \"Suc(0) \\<noteq> 0\"\n  proof\n    assume \"Suc(0) = 0\"\n    then show False by (rule Suc_neq_0)\n  qed\nnext\n  fix n assume hyp: \"Suc(n) \\<noteq> n\"\n  show \"Suc(Suc(n)) \\<noteq> Suc(n)\"\n  proof\n    assume \"Suc(Suc(n)) = Suc(n)\"\n    then have \"Suc(n) = n\" by (rule Suc_inject)\n    with hyp show False by contradiction\n  qed\nqed\n\n\ndefinition add :: \"nat => nat => nat\"    (infixl \"+\" 60)\n  where \"m + n = rec(m, n, \\<lambda>x y. Suc(y))\"\n\nlemma add_0 [simp]: \"0 + n = n\"\n  unfolding add_def by (rule rec_0)\n\nlemma add_Suc [simp]: \"Suc(m) + n = Suc(m + n)\"\n  unfolding add_def by (rule rec_Suc)\n\n\n\nlemma add_0_right: \"m + 0 = m\"\n  by (induct m) simp_all\n\nlemma add_Suc_right: \"m + Suc(n) = Suc(m + n)\"\n  by (induct m) simp_all\n\nlemma\n  assumes \"!!n. f(Suc(n)) = Suc(f(n))\"\n  shows \"f(i + j) = i + f(j)\"\n  using assms by (induct i) simp_all\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/Natural_Numbers.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.899121388082479, "lm_q2_score": 0.8104789155369048, "lm_q1q2_score": 0.728718927549124}}
{"text": "(*  Title:      ZF/Order.thy\n    Author:     Lawrence C Paulson, Cambridge University Computer Laboratory\n    Copyright   1994  University of Cambridge\n\nResults from the book \"Set Theory: an Introduction to Independence Proofs\"\n        by Kenneth Kunen.  Chapter 1, section 6.\nAdditional definitions and lemmas for reflexive orders.\n*)\n\nsection\\<open>Partial and Total Orderings: Basic Definitions and Properties\\<close>\n\ntheory Order imports WF Perm begin\n\ntext \\<open>We adopt the following convention: \\<open>ord\\<close> is used for\n  strict orders and \\<open>order\\<close> is used for their reflexive\n  counterparts.\\<close>\n\ndefinition\n  part_ord :: \"[i,i]=>o\"                (*Strict partial ordering*)  where\n   \"part_ord(A,r) == irrefl(A,r) & trans[A](r)\"\n\ndefinition\n  linear   :: \"[i,i]=>o\"                (*Strict total ordering*)  where\n   \"linear(A,r) == (\\<forall>x\\<in>A. \\<forall>y\\<in>A. <x,y>:r | x=y | <y,x>:r)\"\n\ndefinition\n  tot_ord  :: \"[i,i]=>o\"                (*Strict total ordering*)  where\n   \"tot_ord(A,r) == part_ord(A,r) & linear(A,r)\"\n\ndefinition\n  \"preorder_on(A, r) \\<equiv> refl(A, r) \\<and> trans[A](r)\"\n\ndefinition                              (*Partial ordering*)\n  \"partial_order_on(A, r) \\<equiv> preorder_on(A, r) \\<and> antisym(r)\"\n\nabbreviation\n  \"Preorder(r) \\<equiv> preorder_on(field(r), r)\"\n\nabbreviation\n  \"Partial_order(r) \\<equiv> partial_order_on(field(r), r)\"\n\ndefinition\n  well_ord :: \"[i,i]=>o\"                (*Well-ordering*)  where\n   \"well_ord(A,r) == tot_ord(A,r) & wf[A](r)\"\n\ndefinition\n  mono_map :: \"[i,i,i,i]=>i\"            (*Order-preserving maps*)  where\n   \"mono_map(A,r,B,s) ==\n              {f \\<in> A->B. \\<forall>x\\<in>A. \\<forall>y\\<in>A. <x,y>:r \\<longrightarrow> <f`x,f`y>:s}\"\n\ndefinition\n  ord_iso  :: \"[i,i,i,i]=>i\"  (\"(\\<langle>_, _\\<rangle> \\<cong>/ \\<langle>_, _\\<rangle>)\" 51)  (*Order isomorphisms*)  where\n   \"\\<langle>A,r\\<rangle> \\<cong> \\<langle>B,s\\<rangle> ==\n              {f \\<in> bij(A,B). \\<forall>x\\<in>A. \\<forall>y\\<in>A. <x,y>:r \\<longleftrightarrow> <f`x,f`y>:s}\"\n\ndefinition\n  pred     :: \"[i,i,i]=>i\"              (*Set of predecessors*)  where\n   \"pred(A,x,r) == {y \\<in> A. <y,x>:r}\"\n\ndefinition\n  ord_iso_map :: \"[i,i,i,i]=>i\"         (*Construction for linearity theorem*)  where\n   \"ord_iso_map(A,r,B,s) ==\n     \\<Union>x\\<in>A. \\<Union>y\\<in>B. \\<Union>f \\<in> ord_iso(pred(A,x,r), r, pred(B,y,s), s). {<x,y>}\"\n\ndefinition\n  first :: \"[i, i, i] => o\"  where\n    \"first(u, X, R) == u \\<in> X & (\\<forall>v\\<in>X. v\\<noteq>u \\<longrightarrow> <u,v> \\<in> R)\"\n\nsubsection\\<open>Immediate Consequences of the Definitions\\<close>\n\nlemma part_ord_Imp_asym:\n    \"part_ord(A,r) ==> asym(r \\<inter> A*A)\"\nby (unfold part_ord_def irrefl_def trans_on_def asym_def, blast)\n\nlemma linearE:\n    \"[| linear(A,r);  x \\<in> A;  y \\<in> A;\n        <x,y>:r ==> P;  x=y ==> P;  <y,x>:r ==> P |]\n     ==> P\"\nby (simp add: linear_def, blast)\n\n\n(** General properties of well_ord **)\n\nlemma well_ordI:\n    \"[| wf[A](r); linear(A,r) |] ==> well_ord(A,r)\"\napply (simp add: irrefl_def part_ord_def tot_ord_def\n                 trans_on_def well_ord_def wf_on_not_refl)\napply (fast elim: linearE wf_on_asym wf_on_chain3)\ndone\n\nlemma well_ord_is_wf:\n    \"well_ord(A,r) ==> wf[A](r)\"\nby (unfold well_ord_def, safe)\n\nlemma well_ord_is_trans_on:\n    \"well_ord(A,r) ==> trans[A](r)\"\nby (unfold well_ord_def tot_ord_def part_ord_def, safe)\n\nlemma well_ord_is_linear: \"well_ord(A,r) ==> linear(A,r)\"\nby (unfold well_ord_def tot_ord_def, blast)\n\n\n(** Derived rules for pred(A,x,r) **)\n\nlemma pred_iff: \"y \\<in> pred(A,x,r) \\<longleftrightarrow> <y,x>:r & y \\<in> A\"\nby (unfold pred_def, blast)\n\nlemmas predI = conjI [THEN pred_iff [THEN iffD2]]\n\nlemma predE: \"[| y \\<in> pred(A,x,r);  [| y \\<in> A; <y,x>:r |] ==> P |] ==> P\"\nby (simp add: pred_def)\n\nlemma pred_subset_under: \"pred(A,x,r) \\<subseteq> r -`` {x}\"\nby (simp add: pred_def, blast)\n\nlemma pred_subset: \"pred(A,x,r) \\<subseteq> A\"\nby (simp add: pred_def, blast)\n\nlemma pred_pred_eq:\n    \"pred(pred(A,x,r), y, r) = pred(A,x,r) \\<inter> pred(A,y,r)\"\nby (simp add: pred_def, blast)\n\nlemma trans_pred_pred_eq:\n    \"[| trans[A](r);  <y,x>:r;  x \\<in> A;  y \\<in> A |]\n     ==> pred(pred(A,x,r), y, r) = pred(A,y,r)\"\nby (unfold trans_on_def pred_def, blast)\n\n\nsubsection\\<open>Restricting an Ordering's Domain\\<close>\n\n(** The ordering's properties hold over all subsets of its domain\n    [including initial segments of the form pred(A,x,r) **)\n\n(*Note: a relation s such that s<=r need not be a partial ordering*)\nlemma part_ord_subset:\n    \"[| part_ord(A,r);  B<=A |] ==> part_ord(B,r)\"\nby (unfold part_ord_def irrefl_def trans_on_def, blast)\n\nlemma linear_subset:\n    \"[| linear(A,r);  B<=A |] ==> linear(B,r)\"\nby (unfold linear_def, blast)\n\nlemma tot_ord_subset:\n    \"[| tot_ord(A,r);  B<=A |] ==> tot_ord(B,r)\"\napply (unfold tot_ord_def)\napply (fast elim!: part_ord_subset linear_subset)\ndone\n\nlemma well_ord_subset:\n    \"[| well_ord(A,r);  B<=A |] ==> well_ord(B,r)\"\napply (unfold well_ord_def)\napply (fast elim!: tot_ord_subset wf_on_subset_A)\ndone\n\n\n(** Relations restricted to a smaller domain, by Krzysztof Grabczewski **)\n\nlemma irrefl_Int_iff: \"irrefl(A,r \\<inter> A*A) \\<longleftrightarrow> irrefl(A,r)\"\nby (unfold irrefl_def, blast)\n\nlemma trans_on_Int_iff: \"trans[A](r \\<inter> A*A) \\<longleftrightarrow> trans[A](r)\"\nby (unfold trans_on_def, blast)\n\nlemma part_ord_Int_iff: \"part_ord(A,r \\<inter> A*A) \\<longleftrightarrow> part_ord(A,r)\"\napply (unfold part_ord_def)\napply (simp add: irrefl_Int_iff trans_on_Int_iff)\ndone\n\nlemma linear_Int_iff: \"linear(A,r \\<inter> A*A) \\<longleftrightarrow> linear(A,r)\"\nby (unfold linear_def, blast)\n\nlemma tot_ord_Int_iff: \"tot_ord(A,r \\<inter> A*A) \\<longleftrightarrow> tot_ord(A,r)\"\napply (unfold tot_ord_def)\napply (simp add: part_ord_Int_iff linear_Int_iff)\ndone\n\nlemma wf_on_Int_iff: \"wf[A](r \\<inter> A*A) \\<longleftrightarrow> wf[A](r)\"\napply (unfold wf_on_def wf_def, fast) (*10 times faster than blast!*)\ndone\n\nlemma well_ord_Int_iff: \"well_ord(A,r \\<inter> A*A) \\<longleftrightarrow> well_ord(A,r)\"\napply (unfold well_ord_def)\napply (simp add: tot_ord_Int_iff wf_on_Int_iff)\ndone\n\n\nsubsection\\<open>Empty and Unit Domains\\<close>\n\n(*The empty relation is well-founded*)\nlemma wf_on_any_0: \"wf[A](0)\"\nby (simp add: wf_on_def wf_def, fast)\n\nsubsubsection\\<open>Relations over the Empty Set\\<close>\n\nlemma irrefl_0: \"irrefl(0,r)\"\nby (unfold irrefl_def, blast)\n\nlemma trans_on_0: \"trans[0](r)\"\nby (unfold trans_on_def, blast)\n\nlemma part_ord_0: \"part_ord(0,r)\"\napply (unfold part_ord_def)\napply (simp add: irrefl_0 trans_on_0)\ndone\n\nlemma linear_0: \"linear(0,r)\"\nby (unfold linear_def, blast)\n\nlemma tot_ord_0: \"tot_ord(0,r)\"\napply (unfold tot_ord_def)\napply (simp add: part_ord_0 linear_0)\ndone\n\nlemma wf_on_0: \"wf[0](r)\"\nby (unfold wf_on_def wf_def, blast)\n\nlemma well_ord_0: \"well_ord(0,r)\"\napply (unfold well_ord_def)\napply (simp add: tot_ord_0 wf_on_0)\ndone\n\n\nsubsubsection\\<open>The Empty Relation Well-Orders the Unit Set\\<close>\n\ntext\\<open>by Grabczewski\\<close>\n\nlemma tot_ord_unit: \"tot_ord({a},0)\"\nby (simp add: irrefl_def trans_on_def part_ord_def linear_def tot_ord_def)\n\nlemma well_ord_unit: \"well_ord({a},0)\"\napply (unfold well_ord_def)\napply (simp add: tot_ord_unit wf_on_any_0)\ndone\n\n\nsubsection\\<open>Order-Isomorphisms\\<close>\n\ntext\\<open>Suppes calls them \"similarities\"\\<close>\n\n(** Order-preserving (monotone) maps **)\n\nlemma mono_map_is_fun: \"f \\<in> mono_map(A,r,B,s) ==> f \\<in> A->B\"\nby (simp add: mono_map_def)\n\nlemma mono_map_is_inj:\n    \"[| linear(A,r);  wf[B](s);  f \\<in> mono_map(A,r,B,s) |] ==> f \\<in> inj(A,B)\"\napply (unfold mono_map_def inj_def, clarify)\napply (erule_tac x=w and y=x in linearE, assumption+)\napply (force intro: apply_type dest: wf_on_not_refl)+\ndone\n\nlemma ord_isoI:\n    \"[| f \\<in> bij(A, B);\n        !!x y. [| x \\<in> A; y \\<in> A |] ==> <x, y> \\<in> r \\<longleftrightarrow> <f`x, f`y> \\<in> s |]\n     ==> f \\<in> ord_iso(A,r,B,s)\"\nby (simp add: ord_iso_def)\n\nlemma ord_iso_is_mono_map:\n    \"f \\<in> ord_iso(A,r,B,s) ==> f \\<in> mono_map(A,r,B,s)\"\napply (simp add: ord_iso_def mono_map_def)\napply (blast dest!: bij_is_fun)\ndone\n\nlemma ord_iso_is_bij:\n    \"f \\<in> ord_iso(A,r,B,s) ==> f \\<in> bij(A,B)\"\nby (simp add: ord_iso_def)\n\n(*Needed?  But ord_iso_converse is!*)\nlemma ord_iso_apply:\n    \"[| f \\<in> ord_iso(A,r,B,s);  <x,y>: r;  x \\<in> A;  y \\<in> A |] ==> <f`x, f`y> \\<in> s\"\nby (simp add: ord_iso_def)\n\nlemma ord_iso_converse:\n    \"[| f \\<in> ord_iso(A,r,B,s);  <x,y>: s;  x \\<in> B;  y \\<in> B |]\n     ==> <converse(f) ` x, converse(f) ` y> \\<in> r\"\napply (simp add: ord_iso_def, clarify)\napply (erule bspec [THEN bspec, THEN iffD2])\napply (erule asm_rl bij_converse_bij [THEN bij_is_fun, THEN apply_type])+\napply (auto simp add: right_inverse_bij)\ndone\n\n\n(** Symmetry and Transitivity Rules **)\n\n(*Reflexivity of similarity*)\nlemma ord_iso_refl: \"id(A): ord_iso(A,r,A,r)\"\nby (rule id_bij [THEN ord_isoI], simp)\n\n(*Symmetry of similarity*)\nlemma ord_iso_sym: \"f \\<in> ord_iso(A,r,B,s) ==> converse(f): ord_iso(B,s,A,r)\"\napply (simp add: ord_iso_def)\napply (auto simp add: right_inverse_bij bij_converse_bij\n                      bij_is_fun [THEN apply_funtype])\ndone\n\n(*Transitivity of similarity*)\nlemma mono_map_trans:\n    \"[| g \\<in> mono_map(A,r,B,s);  f \\<in> mono_map(B,s,C,t) |]\n     ==> (f O g): mono_map(A,r,C,t)\"\napply (unfold mono_map_def)\napply (auto simp add: comp_fun)\ndone\n\n(*Transitivity of similarity: the order-isomorphism relation*)\nlemma ord_iso_trans:\n    \"[| g \\<in> ord_iso(A,r,B,s);  f \\<in> ord_iso(B,s,C,t) |]\n     ==> (f O g): ord_iso(A,r,C,t)\"\napply (unfold ord_iso_def, clarify)\napply (frule bij_is_fun [of f])\napply (frule bij_is_fun [of g])\napply (auto simp add: comp_bij)\ndone\n\n(** Two monotone maps can make an order-isomorphism **)\n\nlemma mono_ord_isoI:\n    \"[| f \\<in> mono_map(A,r,B,s);  g \\<in> mono_map(B,s,A,r);\n        f O g = id(B);  g O f = id(A) |] ==> f \\<in> ord_iso(A,r,B,s)\"\napply (simp add: ord_iso_def mono_map_def, safe)\napply (intro fg_imp_bijective, auto)\napply (subgoal_tac \"<g` (f`x), g` (f`y) > \\<in> r\")\napply (simp add: comp_eq_id_iff [THEN iffD1])\napply (blast intro: apply_funtype)\ndone\n\nlemma well_ord_mono_ord_isoI:\n     \"[| well_ord(A,r);  well_ord(B,s);\n         f \\<in> mono_map(A,r,B,s);  converse(f): mono_map(B,s,A,r) |]\n      ==> f \\<in> ord_iso(A,r,B,s)\"\napply (intro mono_ord_isoI, auto)\napply (frule mono_map_is_fun [THEN fun_is_rel])\napply (erule converse_converse [THEN subst], rule left_comp_inverse)\napply (blast intro: left_comp_inverse mono_map_is_inj well_ord_is_linear\n                    well_ord_is_wf)+\ndone\n\n\n(** Order-isomorphisms preserve the ordering's properties **)\n\nlemma part_ord_ord_iso:\n    \"[| part_ord(B,s);  f \\<in> ord_iso(A,r,B,s) |] ==> part_ord(A,r)\"\napply (simp add: part_ord_def irrefl_def trans_on_def ord_iso_def)\napply (fast intro: bij_is_fun [THEN apply_type])\ndone\n\nlemma linear_ord_iso:\n    \"[| linear(B,s);  f \\<in> ord_iso(A,r,B,s) |] ==> linear(A,r)\"\napply (simp add: linear_def ord_iso_def, safe)\napply (drule_tac x1 = \"f`x\" and x = \"f`y\" in bspec [THEN bspec])\napply (safe elim!: bij_is_fun [THEN apply_type])\napply (drule_tac t = \"op ` (converse (f))\" in subst_context)\napply (simp add: left_inverse_bij)\ndone\n\nlemma wf_on_ord_iso:\n    \"[| wf[B](s);  f \\<in> ord_iso(A,r,B,s) |] ==> wf[A](r)\"\napply (simp add: wf_on_def wf_def ord_iso_def, safe)\napply (drule_tac x = \"{f`z. z \\<in> Z \\<inter> A}\" in spec)\napply (safe intro!: equalityI)\napply (blast dest!: equalityD1 intro: bij_is_fun [THEN apply_type])+\ndone\n\nlemma well_ord_ord_iso:\n    \"[| well_ord(B,s);  f \\<in> ord_iso(A,r,B,s) |] ==> well_ord(A,r)\"\napply (unfold well_ord_def tot_ord_def)\napply (fast elim!: part_ord_ord_iso linear_ord_iso wf_on_ord_iso)\ndone\n\n\nsubsection\\<open>Main results of Kunen, Chapter 1 section 6\\<close>\n\n(*Inductive argument for Kunen's Lemma 6.1, etc.\n  Simple proof from Halmos, page 72*)\nlemma well_ord_iso_subset_lemma:\n     \"[| well_ord(A,r);  f \\<in> ord_iso(A,r, A',r);  A'<= A;  y \\<in> A |]\n      ==> ~ <f`y, y>: r\"\napply (simp add: well_ord_def ord_iso_def)\napply (elim conjE CollectE)\napply (rule_tac a=y in wf_on_induct, assumption+)\napply (blast dest: bij_is_fun [THEN apply_type])\ndone\n\n(*Kunen's Lemma 6.1 \\<in> there's no order-isomorphism to an initial segment\n                     of a well-ordering*)\nlemma well_ord_iso_predE:\n     \"[| well_ord(A,r);  f \\<in> ord_iso(A, r, pred(A,x,r), r);  x \\<in> A |] ==> P\"\napply (insert well_ord_iso_subset_lemma [of A r f \"pred(A,x,r)\" x])\napply (simp add: pred_subset)\n(*Now we know  f`x < x *)\napply (drule ord_iso_is_bij [THEN bij_is_fun, THEN apply_type], assumption)\n(*Now we also know @{term\"f`x \\<in> pred(A,x,r)\"}: contradiction! *)\napply (simp add: well_ord_def pred_def)\ndone\n\n(*Simple consequence of Lemma 6.1*)\nlemma well_ord_iso_pred_eq:\n     \"[| well_ord(A,r);  f \\<in> ord_iso(pred(A,a,r), r, pred(A,c,r), r);\n         a \\<in> A;  c \\<in> A |] ==> a=c\"\napply (frule well_ord_is_trans_on)\napply (frule well_ord_is_linear)\napply (erule_tac x=a and y=c in linearE, assumption+)\napply (drule ord_iso_sym)\n(*two symmetric cases*)\napply (auto elim!: well_ord_subset [OF _ pred_subset, THEN well_ord_iso_predE]\n            intro!: predI\n            simp add: trans_pred_pred_eq)\ndone\n\n(*Does not assume r is a wellordering!*)\nlemma ord_iso_image_pred:\n     \"[|f \\<in> ord_iso(A,r,B,s);  a \\<in> A|] ==> f `` pred(A,a,r) = pred(B, f`a, s)\"\napply (unfold ord_iso_def pred_def)\napply (erule CollectE)\napply (simp (no_asm_simp) add: image_fun [OF bij_is_fun Collect_subset])\napply (rule equalityI)\napply (safe elim!: bij_is_fun [THEN apply_type])\napply (rule RepFun_eqI)\napply (blast intro!: right_inverse_bij [symmetric])\napply (auto simp add: right_inverse_bij  bij_is_fun [THEN apply_funtype])\ndone\n\nlemma ord_iso_restrict_image:\n     \"[| f \\<in> ord_iso(A,r,B,s);  C<=A |]\n      ==> restrict(f,C) \\<in> ord_iso(C, r, f``C, s)\"\napply (simp add: ord_iso_def)\napply (blast intro: bij_is_inj restrict_bij)\ndone\n\n(*But in use, A and B may themselves be initial segments.  Then use\n  trans_pred_pred_eq to simplify the pred(pred...) terms.  See just below.*)\nlemma ord_iso_restrict_pred:\n   \"[| f \\<in> ord_iso(A,r,B,s);   a \\<in> A |]\n    ==> restrict(f, pred(A,a,r)) \\<in> ord_iso(pred(A,a,r), r, pred(B, f`a, s), s)\"\napply (simp add: ord_iso_image_pred [symmetric])\napply (blast intro: ord_iso_restrict_image elim: predE)\ndone\n\n(*Tricky; a lot of forward proof!*)\nlemma well_ord_iso_preserving:\n     \"[| well_ord(A,r);  well_ord(B,s);  <a,c>: r;\n         f \\<in> ord_iso(pred(A,a,r), r, pred(B,b,s), s);\n         g \\<in> ord_iso(pred(A,c,r), r, pred(B,d,s), s);\n         a \\<in> A;  c \\<in> A;  b \\<in> B;  d \\<in> B |] ==> <b,d>: s\"\napply (frule ord_iso_is_bij [THEN bij_is_fun, THEN apply_type], (erule asm_rl predI predE)+)\napply (subgoal_tac \"b = g`a\")\napply (simp (no_asm_simp))\napply (rule well_ord_iso_pred_eq, auto)\napply (frule ord_iso_restrict_pred, (erule asm_rl predI)+)\napply (simp add: well_ord_is_trans_on trans_pred_pred_eq)\napply (erule ord_iso_sym [THEN ord_iso_trans], assumption)\ndone\n\n(*See Halmos, page 72*)\nlemma well_ord_iso_unique_lemma:\n     \"[| well_ord(A,r);\n         f \\<in> ord_iso(A,r, B,s);  g \\<in> ord_iso(A,r, B,s);  y \\<in> A |]\n      ==> ~ <g`y, f`y> \\<in> s\"\napply (frule well_ord_iso_subset_lemma)\napply (rule_tac f = \"converse (f) \" and g = g in ord_iso_trans)\napply auto\napply (blast intro: ord_iso_sym)\napply (frule ord_iso_is_bij [of f])\napply (frule ord_iso_is_bij [of g])\napply (frule ord_iso_converse)\napply (blast intro!: bij_converse_bij\n             intro: bij_is_fun apply_funtype)+\napply (erule notE)\napply (simp add: left_inverse_bij bij_is_fun comp_fun_apply [of _ A B])\ndone\n\n\n(*Kunen's Lemma 6.2: Order-isomorphisms between well-orderings are unique*)\nlemma well_ord_iso_unique: \"[| well_ord(A,r);\n         f \\<in> ord_iso(A,r, B,s);  g \\<in> ord_iso(A,r, B,s) |] ==> f = g\"\napply (rule fun_extension)\napply (erule ord_iso_is_bij [THEN bij_is_fun])+\napply (subgoal_tac \"f`x \\<in> B & g`x \\<in> B & linear(B,s)\")\n apply (simp add: linear_def)\n apply (blast dest: well_ord_iso_unique_lemma)\napply (blast intro: ord_iso_is_bij bij_is_fun apply_funtype\n                    well_ord_is_linear well_ord_ord_iso ord_iso_sym)\ndone\n\nsubsection\\<open>Towards Kunen's Theorem 6.3: Linearity of the Similarity Relation\\<close>\n\nlemma ord_iso_map_subset: \"ord_iso_map(A,r,B,s) \\<subseteq> A*B\"\nby (unfold ord_iso_map_def, blast)\n\nlemma domain_ord_iso_map: \"domain(ord_iso_map(A,r,B,s)) \\<subseteq> A\"\nby (unfold ord_iso_map_def, blast)\n\nlemma range_ord_iso_map: \"range(ord_iso_map(A,r,B,s)) \\<subseteq> B\"\nby (unfold ord_iso_map_def, blast)\n\nlemma converse_ord_iso_map:\n    \"converse(ord_iso_map(A,r,B,s)) = ord_iso_map(B,s,A,r)\"\napply (unfold ord_iso_map_def)\napply (blast intro: ord_iso_sym)\ndone\n\nlemma function_ord_iso_map:\n    \"well_ord(B,s) ==> function(ord_iso_map(A,r,B,s))\"\napply (unfold ord_iso_map_def function_def)\napply (blast intro: well_ord_iso_pred_eq ord_iso_sym ord_iso_trans)\ndone\n\nlemma ord_iso_map_fun: \"well_ord(B,s) ==> ord_iso_map(A,r,B,s)\n           \\<in> domain(ord_iso_map(A,r,B,s)) -> range(ord_iso_map(A,r,B,s))\"\nby (simp add: Pi_iff function_ord_iso_map\n                 ord_iso_map_subset [THEN domain_times_range])\n\nlemma ord_iso_map_mono_map:\n    \"[| well_ord(A,r);  well_ord(B,s) |]\n     ==> ord_iso_map(A,r,B,s)\n           \\<in> mono_map(domain(ord_iso_map(A,r,B,s)), r,\n                      range(ord_iso_map(A,r,B,s)), s)\"\napply (unfold mono_map_def)\napply (simp (no_asm_simp) add: ord_iso_map_fun)\napply safe\napply (subgoal_tac \"x \\<in> A & ya:A & y \\<in> B & yb:B\")\n apply (simp add: apply_equality [OF _  ord_iso_map_fun])\n apply (unfold ord_iso_map_def)\n apply (blast intro: well_ord_iso_preserving, blast)\ndone\n\nlemma ord_iso_map_ord_iso:\n    \"[| well_ord(A,r);  well_ord(B,s) |] ==> ord_iso_map(A,r,B,s)\n           \\<in> ord_iso(domain(ord_iso_map(A,r,B,s)), r,\n                      range(ord_iso_map(A,r,B,s)), s)\"\napply (rule well_ord_mono_ord_isoI)\n   prefer 4\n   apply (rule converse_ord_iso_map [THEN subst])\n   apply (simp add: ord_iso_map_mono_map\n                    ord_iso_map_subset [THEN converse_converse])\napply (blast intro!: domain_ord_iso_map range_ord_iso_map\n             intro: well_ord_subset ord_iso_map_mono_map)+\ndone\n\n\n(*One way of saying that domain(ord_iso_map(A,r,B,s)) is downwards-closed*)\nlemma domain_ord_iso_map_subset:\n     \"[| well_ord(A,r);  well_ord(B,s);\n         a \\<in> A;  a \\<notin> domain(ord_iso_map(A,r,B,s)) |]\n      ==>  domain(ord_iso_map(A,r,B,s)) \\<subseteq> pred(A, a, r)\"\napply (unfold ord_iso_map_def)\napply (safe intro!: predI)\n(*Case analysis on  xa vs a in r *)\napply (simp (no_asm_simp))\napply (frule_tac A = A in well_ord_is_linear)\napply (rename_tac b y f)\napply (erule_tac x=b and y=a in linearE, assumption+)\n(*Trivial case: b=a*)\napply clarify\napply blast\n(*Harder case: <a, xa>: r*)\napply (frule ord_iso_is_bij [THEN bij_is_fun, THEN apply_type],\n       (erule asm_rl predI predE)+)\napply (frule ord_iso_restrict_pred)\n apply (simp add: pred_iff)\napply (simp split: split_if_asm\n          add: well_ord_is_trans_on trans_pred_pred_eq domain_UN domain_Union, blast)\ndone\n\n(*For the 4-way case analysis in the main result*)\nlemma domain_ord_iso_map_cases:\n     \"[| well_ord(A,r);  well_ord(B,s) |]\n      ==> domain(ord_iso_map(A,r,B,s)) = A |\n          (\\<exists>x\\<in>A. domain(ord_iso_map(A,r,B,s)) = pred(A,x,r))\"\napply (frule well_ord_is_wf)\napply (unfold wf_on_def wf_def)\napply (drule_tac x = \"A-domain (ord_iso_map (A,r,B,s))\" in spec)\napply safe\n(*The first case: the domain equals A*)\napply (rule domain_ord_iso_map [THEN equalityI])\napply (erule Diff_eq_0_iff [THEN iffD1])\n(*The other case: the domain equals an initial segment*)\napply (blast del: domainI subsetI\n             elim!: predE\n             intro!: domain_ord_iso_map_subset\n             intro: subsetI)+\ndone\n\n(*As above, by duality*)\nlemma range_ord_iso_map_cases:\n    \"[| well_ord(A,r);  well_ord(B,s) |]\n     ==> range(ord_iso_map(A,r,B,s)) = B |\n         (\\<exists>y\\<in>B. range(ord_iso_map(A,r,B,s)) = pred(B,y,s))\"\napply (rule converse_ord_iso_map [THEN subst])\napply (simp add: domain_ord_iso_map_cases)\ndone\n\ntext\\<open>Kunen's Theorem 6.3: Fundamental Theorem for Well-Ordered Sets\\<close>\ntheorem well_ord_trichotomy:\n   \"[| well_ord(A,r);  well_ord(B,s) |]\n    ==> ord_iso_map(A,r,B,s) \\<in> ord_iso(A, r, B, s) |\n        (\\<exists>x\\<in>A. ord_iso_map(A,r,B,s) \\<in> ord_iso(pred(A,x,r), r, B, s)) |\n        (\\<exists>y\\<in>B. ord_iso_map(A,r,B,s) \\<in> ord_iso(A, r, pred(B,y,s), s))\"\napply (frule_tac B = B in domain_ord_iso_map_cases, assumption)\napply (frule_tac B = B in range_ord_iso_map_cases, assumption)\napply (drule ord_iso_map_ord_iso, assumption)\napply (elim disjE bexE)\n   apply (simp_all add: bexI)\napply (rule wf_on_not_refl [THEN notE])\n  apply (erule well_ord_is_wf)\n apply assumption\napply (subgoal_tac \"<x,y>: ord_iso_map (A,r,B,s) \")\n apply (drule rangeI)\n apply (simp add: pred_def)\napply (unfold ord_iso_map_def, blast)\ndone\n\n\nsubsection\\<open>Miscellaneous Results by Krzysztof Grabczewski\\<close>\n\n(** Properties of converse(r) **)\n\nlemma irrefl_converse: \"irrefl(A,r) ==> irrefl(A,converse(r))\"\nby (unfold irrefl_def, blast)\n\nlemma trans_on_converse: \"trans[A](r) ==> trans[A](converse(r))\"\nby (unfold trans_on_def, blast)\n\nlemma part_ord_converse: \"part_ord(A,r) ==> part_ord(A,converse(r))\"\napply (unfold part_ord_def)\napply (blast intro!: irrefl_converse trans_on_converse)\ndone\n\nlemma linear_converse: \"linear(A,r) ==> linear(A,converse(r))\"\nby (unfold linear_def, blast)\n\nlemma tot_ord_converse: \"tot_ord(A,r) ==> tot_ord(A,converse(r))\"\napply (unfold tot_ord_def)\napply (blast intro!: part_ord_converse linear_converse)\ndone\n\n\n(** By Krzysztof Grabczewski.\n    Lemmas involving the first element of a well ordered set **)\n\nlemma first_is_elem: \"first(b,B,r) ==> b \\<in> B\"\nby (unfold first_def, blast)\n\nlemma well_ord_imp_ex1_first:\n        \"[| well_ord(A,r); B<=A; B\\<noteq>0 |] ==> (\\<exists>!b. first(b,B,r))\"\napply (unfold well_ord_def wf_on_def wf_def first_def)\napply (elim conjE allE disjE, blast)\napply (erule bexE)\napply (rule_tac a = x in ex1I, auto)\napply (unfold tot_ord_def linear_def, blast)\ndone\n\nlemma the_first_in:\n     \"[| well_ord(A,r); B<=A; B\\<noteq>0 |] ==> (THE b. first(b,B,r)) \\<in> B\"\napply (drule well_ord_imp_ex1_first, assumption+)\napply (rule first_is_elem)\napply (erule theI)\ndone\n\n\nsubsection \\<open>Lemmas for the Reflexive Orders\\<close>\n\nlemma subset_vimage_vimage_iff:\n  \"[| Preorder(r); A \\<subseteq> field(r); B \\<subseteq> field(r) |] ==>\n  r -`` A \\<subseteq> r -`` B \\<longleftrightarrow> (\\<forall>a\\<in>A. \\<exists>b\\<in>B. <a, b> \\<in> r)\"\n  apply (auto simp: subset_def preorder_on_def refl_def vimage_def image_def)\n   apply blast\n  unfolding trans_on_def\n  apply (erule_tac P = \"(\\<lambda>x. \\<forall>y\\<in>field(r).\n          \\<forall>z\\<in>field(r). \\<langle>x, y\\<rangle> \\<in> r \\<longrightarrow> \\<langle>y, z\\<rangle> \\<in> r \\<longrightarrow> \\<langle>x, z\\<rangle> \\<in> r)\" for r in rev_ballE)\n    (* instance obtained from proof term generated by best *)\n   apply best\n  apply blast\n  done\n\nlemma subset_vimage1_vimage1_iff:\n  \"[| Preorder(r); a \\<in> field(r); b \\<in> field(r) |] ==>\n  r -`` {a} \\<subseteq> r -`` {b} \\<longleftrightarrow> <a, b> \\<in> r\"\n  by (simp add: subset_vimage_vimage_iff)\n\nlemma Refl_antisym_eq_Image1_Image1_iff:\n  \"[| refl(field(r), r); antisym(r); a \\<in> field(r); b \\<in> field(r) |] ==>\n  r `` {a} = r `` {b} \\<longleftrightarrow> a = b\"\n  apply rule\n   apply (frule equality_iffD)\n   apply (drule equality_iffD)\n   apply (simp add: antisym_def refl_def)\n   apply best\n  apply (simp add: antisym_def refl_def)\n  done\n\nlemma Partial_order_eq_Image1_Image1_iff:\n  \"[| Partial_order(r); a \\<in> field(r); b \\<in> field(r) |] ==>\n  r `` {a} = r `` {b} \\<longleftrightarrow> a = b\"\n  by (simp add: partial_order_on_def preorder_on_def\n    Refl_antisym_eq_Image1_Image1_iff)\n\nlemma Refl_antisym_eq_vimage1_vimage1_iff:\n  \"[| refl(field(r), r); antisym(r); a \\<in> field(r); b \\<in> field(r) |] ==>\n  r -`` {a} = r -`` {b} \\<longleftrightarrow> a = b\"\n  apply rule\n   apply (frule equality_iffD)\n   apply (drule equality_iffD)\n   apply (simp add: antisym_def refl_def)\n   apply best\n  apply (simp add: antisym_def refl_def)\n  done\n\nlemma Partial_order_eq_vimage1_vimage1_iff:\n  \"[| Partial_order(r); a \\<in> field(r); b \\<in> field(r) |] ==>\n  r -`` {a} = r -`` {b} \\<longleftrightarrow> a = b\"\n  by (simp add: partial_order_on_def preorder_on_def\n    Refl_antisym_eq_vimage1_vimage1_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/ZF/Order.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8991213691605412, "lm_q2_score": 0.8104789040926008, "lm_q1q2_score": 0.7287189019234742}}
{"text": "(*  Author:     Gertrud Bauer, Tobias Nipkow\n*)\n\nheader \"Summation Over Lists\"\n\ntheory ListSum\nimports ListAux\nbegin\n\nprimrec ListSum :: \"'b list \\<Rightarrow> ('b \\<Rightarrow> 'a::comm_monoid_add) \\<Rightarrow> 'a::comm_monoid_add\"  where\n  \"ListSum [] f = 0\"\n| \"ListSum (l#ls) f = f l + ListSum ls f\"\n\nsyntax \"_ListSum\" :: \"idt \\<Rightarrow> 'b list \\<Rightarrow> ('a::comm_monoid_add) \\<Rightarrow> \n  ('a::comm_monoid_add)\"    (\"\\<Sum>\\<^bsub>_\\<in>_\\<^esub> _\" [0, 0, 10] 10)\ntranslations \"\\<Sum>\\<^bsub>x\\<in>xs\\<^esub> f\" == \"CONST ListSum xs (\\<lambda>x. f)\" \n\n\n\nlemma ListSum_compl1: \n  \"(\\<Sum>\\<^bsub>x \\<in> [x\\<leftarrow>xs. \\<not> P x]\\<^esub> f x) + (\\<Sum>\\<^bsub>x \\<in> [x\\<leftarrow>xs. P x]\\<^esub> f x) = (\\<Sum>\\<^bsub>x \\<in> xs\\<^esub> (f x::nat))\" \n by (induct xs) simp_all\n\nlemma ListSum_compl2: \n  \"(\\<Sum>\\<^bsub>x \\<in>  [x\\<leftarrow>xs. P x]\\<^esub> f x) + (\\<Sum>\\<^bsub>x \\<in>  [x\\<leftarrow>xs. \\<not> P x]\\<^esub> f x) = (\\<Sum>\\<^bsub>x \\<in> xs\\<^esub> (f x::nat))\" \n by (induct xs) simp_all\n\nlemmas ListSum_compl = ListSum_compl1 ListSum_compl2\n\n\nlemma ListSum_conv_setsum:\n \"distinct xs \\<Longrightarrow> ListSum xs f =  setsum f (set xs)\"\nby(induct xs) simp_all\n\n\nlemma listsum_cong:\n \"\\<lbrakk> xs = ys; \\<And>y. y \\<in> set ys ==> f y = g y \\<rbrakk>\n  \\<Longrightarrow> ListSum xs f = ListSum ys g\"\napply simp\napply(erule thin_rl)\nby (induct ys) simp_all\n\n\nlemma strong_listsum_cong[cong]:\n \"\\<lbrakk> xs = ys; \\<And>y. y \\<in> set ys =simp=> f y = g y \\<rbrakk>\n  \\<Longrightarrow> ListSum xs f = ListSum ys g\"\nby(auto simp:simp_implies_def intro!:listsum_cong)\n\n\nlemma ListSum_eq [trans]: \n  \"(\\<And>v. v \\<in> set V \\<Longrightarrow> f v = g v) \\<Longrightarrow> (\\<Sum>\\<^bsub>v \\<in> V\\<^esub> f v) = (\\<Sum>\\<^bsub>v \\<in> V\\<^esub> g v)\" \nby(auto intro!:listsum_cong)\n\n\nlemma ListSum_disj_union: \n  \"distinct A \\<Longrightarrow> distinct B \\<Longrightarrow> distinct C \\<Longrightarrow> \n  set C = set A \\<union> set B  \\<Longrightarrow> \n  set A \\<inter> set B = {} \\<Longrightarrow>\n  (\\<Sum>\\<^bsub>a \\<in> C\\<^esub> (f a)) = (\\<Sum>\\<^bsub>a \\<in> A\\<^esub> f a) + (\\<Sum>\\<^bsub>a \\<in> B\\<^esub> (f a::nat))\"\nby (simp add: ListSum_conv_setsum setsum.union_disjoint)\n\n\nlemma listsum_const[simp]: \n  \"(\\<Sum>\\<^bsub>x \\<in> xs\\<^esub> k) = length xs * k\"\nby (induct xs) (simp_all add: ring_distribs)\n\nlemma ListSum_add: \n  \"(\\<Sum>\\<^bsub>x \\<in> V\\<^esub> f x) + (\\<Sum>\\<^bsub>x \\<in> V\\<^esub> g x) = (\\<Sum>\\<^bsub>x \\<in> V\\<^esub> (f x + (g x::nat)))\" \n  by (induct V) auto\n\nlemma ListSum_le: \n  \"(\\<And>v. v \\<in> set V \\<Longrightarrow> f v \\<le> g v) \\<Longrightarrow> (\\<Sum>\\<^bsub>v \\<in> V\\<^esub> f v) \\<le> (\\<Sum>\\<^bsub>v \\<in> V\\<^esub> (g v::nat))\"\nproof (induct V)\n  case Nil then show ?case by simp\nnext\n  case (Cons v V) then have \"(\\<Sum>\\<^bsub>v \\<in> V\\<^esub> f v) \\<le> (\\<Sum>\\<^bsub>v \\<in> V\\<^esub> g v)\" by simp\n  moreover from Cons have \"f v \\<le> g v\" by simp\n  ultimately show ?case by simp\nqed\n\nlemma ListSum1_bound:\n \"a \\<in> set F \\<Longrightarrow> (d a::nat)\\<le> (\\<Sum>\\<^bsub>f \\<in> F\\<^esub> d f)\"\nby (induct F) 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/Flyspeck-Tame/ListSum.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887588023318196, "lm_q2_score": 0.8198933381139646, "lm_q1q2_score": 0.7286874212220048}}
{"text": "theory Sorted\nimports Main\n        \"$HIPSTER_HOME/IsaHipster\"\n\nbegin\n\n  datatype 'a list = Nil | Cons \"'a\" \"'a list\"\n  datatype Nat = Z | S \"Nat\"\n\n  fun le :: \"Nat => Nat => bool\" where\n    \"le Z y = True\"\n  | \"le (S x) Z = False\"\n  | \"le (S x) (S x2) = le x x2\"\n\n  fun sorted :: \"Nat list => bool\" where\n    \"sorted Nil = True\"\n  | \"sorted (Cons y Nil) = True\"\n  | \"sorted (Cons y (Cons y2 ys)) =\n       (if le y y2 then sorted (Cons y2 ys) else False)\"\n\n  fun insert :: \"Nat => Nat list => Nat list\" where\n    \"insert x Nil = Cons x Nil\"\n  | \"insert x (Cons z xs) =\n       (if le x z then Cons x (Cons z xs) else Cons z (insert x xs))\"\n\n  fun sort :: \"Nat list => Nat list\" where\n  \"sort Nil = Nil\"\n  | \"sort (Cons y xs) = insert y (sort xs)\"\n\n(* First: explore the most simple function, ie: that which is defined in terms of itself alone *)\n(*hipster le*)\nlemma lemma_a [thy_expl]: \"le x2 x2 = True\"\nby (hipster_induct_schemes le.simps)\n\nlemma lemma_aa [thy_expl]: \"le x2 (S x2) = True\"\nby (hipster_induct_schemes le.simps)\n\nlemma lemma_ab [thy_expl]: \"le (S x2) x2 = False\"\nby (hipster_induct_schemes le.simps)\n\n(* We might need conditionals: we explore those with up to two conjuncts in the premise *)\n(*hipster_cond le*)\nlemma lemma_ac [thy_expl]: \"le x2 y2 \\<Longrightarrow> le x2 (S y2) = True\"\nby (hipster_induct_schemes le.simps)\n\nlemma lemma_ad [thy_expl]: \"le y2 x2 \\<Longrightarrow> le (S x2) y2 = False\"\nby (hipster_induct_schemes le.simps)\n\nlemma lemma_ae [thy_expl]: \"le y x \\<and> le x y \\<Longrightarrow> x = y\"\nby (hipster_induct_schemes le.simps Nat.exhaust)\n\nlemma lemma_af [thy_expl]: \"le z y \\<and> le x z \\<Longrightarrow> le x y = True\"\nby (hipster_induct_schemes le.simps Nat.exhaust)\n\n(* We proceed on to explore other functions in the theory, and we find some properties we\n    cannot prove yet *)\n(*hipster sorted insert le*)\nlemma lemma_ag [thy_expl]: \"insert Z (insert x19 y19) = insert x19 (insert Z y19)\"\nby (hipster_induct_schemes sorted.simps insert.simps le.simps list.exhaust Nat.exhaust)\n\nlemma lemma_ah [thy_expl]: \"sorted (insert Z x4) = sorted x4\"\nby (hipster_induct_schemes sorted.simps insert.simps le.simps list.exhaust Nat.exhaust)\n\nlemma unknown [thy_expl]: \"insert x (insert y z) = insert y (insert x z)\"\noops\n\nlemma unknown [thy_expl]: \"sorted (insert x y) = sorted y\"\noops\n\n(* Neither when considering conditionals with the predicate _sorted_ *)\n(*hipster_cond sorted insert le *)\nlemma unknown [thy_expl]: \"insert x (insert y z) = insert y (insert x z)\"\noops\n\nlemma unknown [thy_expl]: \"sorted (insert x y) = sorted y\"\noops\n\nlemma unknown [thy_expl]: \"sorted y \\<Longrightarrow> sorted (insert x y) = True\"\noops\n\n\n(* So we might think about exploring the negation of some predicate, namely of that which\n    defines branching in our sorting functions. Right now, we need to define it separately\n    for exploration purposes *)\nfun notle:: \"Nat \\<Rightarrow> Nat \\<Rightarrow> bool\" where\n  \"notle x y = (\\<not> le x y)\"\n\n(* And we finally explore conditional properties for it *)\n(*hipster_cond notle*)\nlemma lemma_ai [thy_expl]: \"notle (S x2) y2 = le y2 x2\"\nby (hipster_induct_schemes notle.simps Nat.exhaust)\n\nlemma lemma_aj [thy_expl]: \"notle x2 y2 \\<Longrightarrow> notle x2 Z = True\"\nby (hipster_induct_schemes notle.simps Nat.exhaust)\n\n\n(* If we now revisit one of the lemmas discovered about _sorted_ and _insert_, we will be able\n    to prove after prior modification of the options: using full_types in metis and increasing\n    the timeout for proof search (namely that for metis) *)\nsetup\\<open>Hip_Tac_Ops.toggle_full_types @{context} ;\\<close>\nsetup\\<open>Hip_Tac_Ops.set_metis_to @{context} 3500;\\<close>\n\n(*hipster_cond sorted (*sort*) insert le notle*)\nlemma lemma_ak [thy_expl]: \"insert x30 (insert y30 z30) = insert y30 (insert x30 z30)\"\nby (hipster_induct_schemes sorted.simps insert.simps le.simps notle.simps list.exhaust Nat.exhaust)\n\nlemma lemma_al [thy_expl]: \"sorted y31 \\<Longrightarrow> sorted (insert x31 y31) = True\"\nby (hipster_induct_schemes sorted.simps insert.simps le.simps notle.simps list.exhaust Nat.exhaust)\n\nlemma unknown [thy_expl]: \"sorted (insert x y) = sorted y\"\noops\n\n\n(* We can finally immediately prove our target theorem! *)\n  theorem x0 :\n    \"sorted (sort xs)\"\n    by hipster_induct_schemes\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/Examples/201509/Sorted.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8887587875995482, "lm_q2_score": 0.8198933337131076, "lm_q1q2_score": 0.7286874052318133}}
{"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\"\nwhere\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::nat) = 1\"\n  by (metis One_nat_def fib1)\n\nlemma fib_2 [simp]: \"fib (2::nat) = 1\"\n  using fib.simps(3) [of 0]\n  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 simp add: )\n\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 fib} 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\" 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 (induction 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 (induction 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::nat)) (fib (Suc n))\"\n  apply (induct n rule: fib.induct)\n  apply auto\n  apply (metis gcd_add1 add.commute)\n  done\n\nlemma gcd_fib_add: \"gcd (fib m) (fib (n + m)) = gcd (fib m) (fib n)\"\n  apply (simp add: gcd.commute [of \"fib m\"])\n  apply (cases m)\n  apply (auto simp add: fib_add)\n  apply (metis gcd.commute mult.commute coprime_fib_Suc_nat\n    gcd_add_mult gcd_mult_cancel gcd.commute)\n  done\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 pos_n: \"0 < n\" by auto\n    with \\<open>0 < m\\<close> \\<open>m < n\\<close> have diff: \"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]) (insert \\<open>m < n\\<close>, auto)\n    also have \"\\<dots> = gcd (fib m)  (fib (n - m))\"\n      by (simp add: less.hyps diff \\<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)\"\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  defines \"\\<phi> \\<equiv> (1 + sqrt 5) / (2::real)\" and \"\\<psi> \\<equiv> (1 - sqrt 5) / (2::real)\"\n  shows   \"of_nat (fib n) = (\\<phi> ^ n - \\<psi> ^ n) / sqrt 5\"\nproof (induction 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 \"... = (\\<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  defines \"\\<phi> \\<equiv> (1 + sqrt 5) / (2 :: real)\" and \"\\<psi> \\<equiv> (1 - sqrt 5) / (2 :: real)\"\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 \"... < 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  defines \"\\<phi> \\<equiv> (1 + sqrt 5) / (2 :: real)\"\n  shows   \"(\\<lambda>n. real (fib n) / (\\<phi> ^ n / sqrt 5)) \\<longlonglongrightarrow> 1\"\nproof -\n  define \\<psi> where \"\\<psi> \\<equiv> (1 - sqrt 5) / (2 :: real)\"\n  have \"\\<phi> > 1\" by (simp add: \\<phi>_def)\n  hence A: \"\\<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  hence \"(\\<lambda>n. 1 - (\\<psi> / \\<phi>) ^ n) \\<longlonglongrightarrow> 1 - 0\" by (intro tendsto_diff tendsto_const)\n  with A show ?thesis\n    by (simp add: divide_simps fib_closed_form [folded \\<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  defines \"\\<phi> \\<equiv> (1 + sqrt 5) / (2 :: real)\" and \"\\<psi> \\<equiv> (1 - sqrt 5) / (2 :: real)\"\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 have \"(\\<phi> ^ n - \\<psi> ^ n)\\<^sup>2 + (\\<phi> * \\<phi> ^ n - \\<psi> * \\<psi> ^ n)\\<^sup>2 = \n    \\<phi>^(2*n) + \\<psi>^(2*n) - 2*(\\<phi>*\\<psi>)^n + \\<phi>^(2*n+2) + \\<psi>^(2*n+2) - 2*(\\<phi>*\\<psi>)^(n+1)\" (is \"_ = ?A\")\n      by (simp add: power2_eq_square algebra_simps power_mult power_mult_distrib)\n  also have \"\\<phi> * \\<psi> = -1\" by (simp add: \\<phi>_def \\<psi>_def field_simps)\n  hence \"?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\" by (auto intro: add_pos_pos)\n  hence \"\\<phi> + inverse \\<phi> = sqrt 5\" by (simp add: \\<phi>_def field_simps)\n  also have \"\\<psi> + inverse \\<psi> = -sqrt 5\" 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)\" by (simp add: field_simps)\n  also have \"sqrt 5 / 5 = inverse (sqrt 5)\" by (simp add: field_simps)\n  also have \"(\\<phi> ^ (2*n+1) - \\<psi> ^ (2*n+1)) * ... = of_nat (fib (Suc (2*n)))\"\n    by (simp add: fib_closed_form[folded \\<phi>_def \\<psi>_def] divide_inverse)\n  finally show ?thesis 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 (induction n)\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 ...) = ?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 + ... = (?rfib (Suc n) + 2 * ?rfib n) * ?rfib (Suc n)\"\n    by (simp add: algebra_simps power2_eq_square)\n  also have \"... = 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 simp\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 = (if n = 0 then 0 else if n = 1 then 1 else\n            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)) = (\\<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> = (\\<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) +\n                   (\\<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\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/Fib.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950868503682, "lm_q2_score": 0.8633916152464016, "lm_q1q2_score": 0.7286119421342417}}
{"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 lattice_syntax\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_iff_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_iff_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_norm_square: \\<open>(ell2_norm x)\\<^sup>2 = (\\<Sum>\\<^sub>\\<infinity>i. (cmod (x i))\\<^sup>2)\\<close>\n  unfolding ell2_norm_def\n  apply (subst real_sqrt_pow2)\n  by (simp_all add: infsum_nonneg)\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 \\<longleftrightarrow> 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 intro_classes\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\nlemma sum_ell2_transfer[transfer_rule]:\n  includes lifting_syntax\n  shows \\<open>(((=) ===> pcr_ell2 (=)) ===> rel_set (=) ===> pcr_ell2 (=)) \n          (\\<lambda>f X x. sum (\\<lambda>y. f y x) X) sum\\<close>\nproof (intro rel_funI, rename_tac f f' X X')\n  fix f and f' :: \\<open>'a \\<Rightarrow> 'b ell2\\<close> \n  assume [transfer_rule]: \\<open>((=) ===> pcr_ell2 (=)) f f'\\<close>\n  fix X X' :: \\<open>'a set\\<close>\n  assume \\<open>rel_set (=) X X'\\<close>\n  then have [simp]: \\<open>X' = X\\<close>\n    by (simp add: rel_set_eq)\n  show \\<open>pcr_ell2 (=) (\\<lambda>x. \\<Sum>y\\<in>X. f y x) (sum f' X')\\<close>\n    unfolding \\<open>X' = X\\<close>\n  proof (induction X rule: infinite_finite_induct)\n    case (infinite X)\n    show ?case\n      apply (simp add: infinite)\n      by transfer_prover\n  next\n    case empty\n    show ?case\n      apply (simp add: empty)\n      by transfer_prover\n  next\n    case (insert x F)\n    note [transfer_rule] = insert.IH\n    show ?case\n      apply (simp add: insert)\n      by transfer_prover\n  qed\nqed\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 trunc_ell2_UNIV[simp]: \\<open>trunc_ell2 UNIV \\<psi> = \\<psi>\\<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>((trunc_ell2 S x) \\<bullet>\\<^sub>C (x - trunc_ell2 S x)) = 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\nlemma trunc_ell2_norm_mono: \\<open>M \\<subseteq> N \\<Longrightarrow> norm (trunc_ell2 M \\<psi>) \\<le> norm (trunc_ell2 N \\<psi>)\\<close>\nproof (rule power2_le_imp_le[rotated], force, transfer)\n  fix M N :: \\<open>'a set\\<close> and \\<psi> :: \\<open>'a \\<Rightarrow> complex\\<close>\n  assume \\<open>M \\<subseteq> N\\<close> and \\<open>has_ell2_norm \\<psi>\\<close>\n  have \\<open>(ell2_norm (\\<lambda>i. if i \\<in> M then \\<psi> i else 0))\\<^sup>2 = (\\<Sum>\\<^sub>\\<infinity>i\\<in>M. (cmod (\\<psi> i))\\<^sup>2)\\<close>\n    unfolding ell2_norm_square\n    apply (rule infsum_cong_neutral)\n    by auto\n  also have \\<open>\\<dots> \\<le> (\\<Sum>\\<^sub>\\<infinity>i\\<in>N. (cmod (\\<psi> i))\\<^sup>2)\\<close>\n    apply (rule infsum_mono2)\n    using \\<open>has_ell2_norm \\<psi>\\<close> \\<open>M \\<subseteq> N\\<close>\n    by (auto simp add: ell2_norm_square has_ell2_norm_def simp flip: norm_power intro: summable_on_subset_banach)\n  also have \\<open>\\<dots> = (ell2_norm (\\<lambda>i. if i \\<in> N then \\<psi> i else 0))\\<^sup>2\\<close>\n    unfolding ell2_norm_square\n    apply (rule infsum_cong_neutral)\n    by auto\n  finally show \\<open>(ell2_norm (\\<lambda>i. if i \\<in> M then \\<psi> i else 0))\\<^sup>2 \\<le> (ell2_norm (\\<lambda>i. if i \\<in> N then \\<psi> i else 0))\\<^sup>2\\<close>\n    by -\nqed\n\nlemma trunc_ell2_reduces_norm: \\<open>norm (trunc_ell2 M \\<psi>) \\<le> norm \\<psi>\\<close>\n  by (metis subset_UNIV trunc_ell2_UNIV trunc_ell2_norm_mono)\n\nlemma trunc_ell2_twice[simp]: \\<open>trunc_ell2 M (trunc_ell2 N \\<psi>) = trunc_ell2 (M\\<inter>N) \\<psi>\\<close>\n  apply transfer by auto\n\nlemma trunc_ell2_union: \\<open>trunc_ell2 (M \\<union> N) \\<psi> = trunc_ell2 M \\<psi> + trunc_ell2 N \\<psi> - trunc_ell2 (M\\<inter>N) \\<psi>\\<close>\n  apply transfer by auto\n\nlemma trunc_ell2_union_disjoint: \\<open>M\\<inter>N = {} \\<Longrightarrow> trunc_ell2 (M \\<union> N) \\<psi> = trunc_ell2 M \\<psi> + trunc_ell2 N \\<psi>\\<close>\n  by (simp add: trunc_ell2_union)\n\nlemma trunc_ell2_union_Diff: \\<open>M \\<subseteq> N \\<Longrightarrow> trunc_ell2 (N-M) \\<psi> = trunc_ell2 N \\<psi> - trunc_ell2 M \\<psi>\\<close>\n  using trunc_ell2_union_disjoint[where M=\\<open>N-M\\<close> and N=M and \\<psi>=\\<psi>]\n  by (simp add: Un_commute inf.commute le_iff_sup)\n\nlemma trunc_ell2_add: \\<open>trunc_ell2 M (\\<psi> + \\<phi>) = trunc_ell2 M \\<psi> + trunc_ell2 M \\<phi>\\<close>\n  apply transfer by auto\n\nlemma trunc_ell2_scaleC: \\<open>trunc_ell2 M (c *\\<^sub>C \\<psi>) = c *\\<^sub>C trunc_ell2 M \\<psi>\\<close>\n  apply transfer by auto\n\nlemma bounded_clinear_trunc_ell2[bounded_clinear]: \\<open>bounded_clinear (trunc_ell2 M)\\<close>\n  by (auto intro!: bounded_clinearI[where K=1] trunc_ell2_reduces_norm\n      simp: trunc_ell2_add trunc_ell2_scaleC)\n\nlemma trunc_ell2_lim: \\<open>((\\<lambda>S. trunc_ell2 S \\<psi>) \\<longlongrightarrow> trunc_ell2 M \\<psi>) (finite_subsets_at_top M)\\<close>\nproof -\n  have \\<open>((\\<lambda>S. trunc_ell2 S (trunc_ell2 M \\<psi>)) \\<longlongrightarrow> trunc_ell2 M \\<psi>) (finite_subsets_at_top UNIV)\\<close>\n    using trunc_ell2_lim_at_UNIV by blast\n  then have \\<open>((\\<lambda>S. trunc_ell2 (S\\<inter>M) \\<psi>) \\<longlongrightarrow> trunc_ell2 M \\<psi>) (finite_subsets_at_top UNIV)\\<close>\n    by simp\n  then show \\<open>((\\<lambda>S. trunc_ell2 S \\<psi>) \\<longlongrightarrow> trunc_ell2 M \\<psi>) (finite_subsets_at_top M)\\<close>\n    unfolding filterlim_def\n    apply (subst (asm) filtermap_filtermap[where g=\\<open>\\<lambda>S. S\\<inter>M\\<close>, symmetric])\n    apply (subst (asm) finite_subsets_at_top_inter[where A=M and B=UNIV])\n    by auto\nqed\n\nlemma trunc_ell2_lim_general:\n  assumes big: \\<open>\\<And>G. finite G \\<Longrightarrow> G \\<subseteq> M \\<Longrightarrow> (\\<forall>\\<^sub>F H in F. H \\<supseteq> G)\\<close>\n  assumes small: \\<open>\\<forall>\\<^sub>F H in F. H \\<subseteq> M\\<close>\n  shows \\<open>((\\<lambda>S. trunc_ell2 S \\<psi>) \\<longlongrightarrow> trunc_ell2 M \\<psi>) F\\<close>\nproof (rule tendstoI)\n  fix e :: real assume \\<open>e > 0\\<close>\n  from trunc_ell2_lim[THEN tendsto_iff[THEN iffD1], rule_format, OF \\<open>e > 0\\<close>, where M=M and \\<psi>=\\<psi>]\n  obtain G where \\<open>finite G\\<close> and \\<open>G \\<subseteq> M\\<close> and \n    close: \\<open>dist (trunc_ell2 G \\<psi>) (trunc_ell2 M \\<psi>) < e\\<close>\n    apply atomize_elim\n    unfolding eventually_finite_subsets_at_top\n    by blast\n  from \\<open>finite G\\<close> \\<open>G \\<subseteq> M\\<close> and big\n  have \\<open>\\<forall>\\<^sub>F H in F. H \\<supseteq> G\\<close>\n    by -\n  with small have \\<open>\\<forall>\\<^sub>F H in F. H \\<subseteq> M \\<and> H \\<supseteq> G\\<close>\n    by (simp add: eventually_conj_iff)\n  then show \\<open>\\<forall>\\<^sub>F H in F. dist (trunc_ell2 H \\<psi>) (trunc_ell2 M \\<psi>) < e\\<close>\n  proof (rule eventually_mono)\n    fix H assume GHM: \\<open>H \\<subseteq> M \\<and> H \\<supseteq> G\\<close>\n    have \\<open>dist (trunc_ell2 H \\<psi>) (trunc_ell2 M \\<psi>) = norm (trunc_ell2 (M-H) \\<psi>)\\<close>\n      by (simp add: GHM dist_ell2_def norm_minus_commute trunc_ell2_union_Diff)\n    also have \\<open>\\<dots> \\<le> norm (trunc_ell2 (M-G) \\<psi>)\\<close>\n      by (simp add: Diff_mono GHM trunc_ell2_norm_mono)\n    also have \\<open>\\<dots>  = dist (trunc_ell2 G \\<psi>) (trunc_ell2 M \\<psi>)\\<close>\n      by (simp add: \\<open>G \\<subseteq> M\\<close> dist_ell2_def norm_minus_commute trunc_ell2_union_Diff)\n    also have \\<open>\\<dots> < e\\<close>\n      using close by simp\n    finally show \\<open>dist (trunc_ell2 H \\<psi>) (trunc_ell2 M \\<psi>) < e\\<close>\n      by -\n  qed\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>(ket i \\<bullet>\\<^sub>C \\<psi>) = 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>(\\<psi> \\<bullet>\\<^sub>C ket i) = 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>(ket i \\<bullet>\\<^sub>C ket i) = 1\\<close>\nproof-\n  have \\<open>norm (ket i) = 1\\<close>\n    by simp\n  hence \\<open>sqrt (cmod (ket i \\<bullet>\\<^sub>C ket i)) = 1\\<close>\n    by (metis norm_eq_sqrt_cinner)\n  hence \\<open>cmod (ket i \\<bullet>\\<^sub>C ket i) = 1\\<close>\n    using real_sqrt_eq_1_iff by blast\n  moreover have \\<open>(ket i \\<bullet>\\<^sub>C ket i) = cmod (ket i \\<bullet>\\<^sub>C ket i)\\<close>\n  proof-\n    have \\<open>(ket i \\<bullet>\\<^sub>C ket i) \\<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>(ket i \\<bullet>\\<^sub>C ket j) = (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\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\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. A *\\<^sub>V ket x = B *\\<^sub>V 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. (F *\\<^sub>V ket i) \\<bullet>\\<^sub>C ket j = ket i \\<bullet>\\<^sub>C (G *\\<^sub>V ket j)\"\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\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\nlemma bounded_clinear_equal_ket:\n  fixes f g :: \\<open>'a ell2 \\<Rightarrow> _\\<close>\n  assumes \\<open>bounded_clinear f\\<close>\n  assumes \\<open>bounded_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 bounded_clinear_eq_on[of f g \\<open>range ket\\<close>])\n  using assms by auto\n\nlemma bounded_antilinear_equal_ket:\n  fixes f g :: \\<open>'a ell2 \\<Rightarrow> _\\<close>\n  assumes \\<open>bounded_antilinear f\\<close>\n  assumes \\<open>bounded_antilinear 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 bounded_antilinear_eq_on[of f g \\<open>range ket\\<close>])\n  using assms by auto\n\nlemma is_onb_ket[simp]: \\<open>is_onb (range ket)\\<close>\n  by (auto simp: is_onb_def)\n\nlemma ell2_sum_ket: \\<open>\\<psi> = (\\<Sum>i\\<in>UNIV. Rep_ell2 \\<psi> i *\\<^sub>C ket i)\\<close> for \\<psi> :: \\<open>_::finite ell2\\<close>\n  apply transfer apply (rule ext)\n  apply (subst sum_single)\n  by auto\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 :: (CARD_1) one begin\nlift_definition one_ell2 :: \"'a ell2\" is \"\\<lambda>_. 1\" by simp\ninstance..\nend\n\nlemma ket_CARD_1_is_1: \\<open>ket x = 1\\<close> for x :: \\<open>'a::CARD_1\\<close>\n  apply transfer by simp\n\ninstantiation ell2 :: (CARD_1) times begin\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..\nend\n\ninstantiation ell2 :: (CARD_1) divide 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   \ninstance..\nend\n\ninstantiation ell2 :: (CARD_1) inverse begin\nlift_definition inverse_ell2 :: \"'a ell2 \\<Rightarrow> 'a ell2\" is \"\\<lambda>a x. inverse (a x)\"\n  by simp\ninstance..\nend\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 intro_classes\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    apply transfer\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\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\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 \n  assumes \"inj_map \\<pi>\"\n  shows classical_operator_exists_inj: \"classical_operator_exists \\<pi>\"\n    and classical_operator_norm_inj: \\<open>norm (classical_operator \\<pi>) \\<le> 1\\<close>\nproof -\n  have \\<open>is_orthogonal (case \\<pi> x of None \\<Rightarrow> 0 | Some x' \\<Rightarrow> ket x')\n                      (case \\<pi> y of None \\<Rightarrow> 0 | Some y' \\<Rightarrow> ket y')\\<close>\n    if \\<open>x \\<noteq> y\\<close> for x y\n    apply (cases \\<open>\\<pi> x\\<close>; cases \\<open>\\<pi> y\\<close>)\n    using that assms\n    by (auto simp add: inj_map_def)\n  then have 1: \\<open>is_orthogonal (case \\<pi> (inv ket x) of None \\<Rightarrow> 0 | Some x' \\<Rightarrow> ket x')\n                      (case \\<pi> (inv ket y) of None \\<Rightarrow> 0 | Some y' \\<Rightarrow> ket y')\\<close>\n    if \\<open>x \\<in> range ket\\<close> and \\<open>y \\<in> range ket\\<close> and \\<open>x \\<noteq> y\\<close> for x y\n    using that by auto\n\n  have \\<open>norm (case \\<pi> x of None \\<Rightarrow> 0 | Some x \\<Rightarrow> ket x) \\<le> 1 * norm (ket x)\\<close> for x\n    apply (cases \\<open>\\<pi> x\\<close>) by auto\n  then have 2: \\<open>norm (case \\<pi> (inv ket x) of None \\<Rightarrow> 0 | Some x \\<Rightarrow> ket x) \\<le> 1 * norm x\\<close>\n    if \\<open>x \\<in> range ket\\<close> for x\n    using that by auto\n\n  show \\<open>classical_operator_exists \\<pi>\\<close>\n    unfolding classical_operator_exists_def\n    using _ _ 1 2 apply (rule cblinfun_extension_exists_ortho)\n    by simp_all\n\n  show \\<open>norm (classical_operator \\<pi>) \\<le> 1\\<close>\n    unfolding classical_operator_def Let_def\n    using _ _ 1 2 apply (rule cblinfun_extension_exists_ortho_norm)\n    by simp_all\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 \"(F *\\<^sub>V ket i) \\<bullet>\\<^sub>C ket j = ket i \\<bullet>\\<^sub>C (G *\\<^sub>V ket j)\" 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 \"(F *\\<^sub>V ket i) \\<bullet>\\<^sub>C ket j = (classical_operator (inv_map \\<pi>) *\\<^sub>V ket i) \\<bullet>\\<^sub>C ket j\"\n      unfolding F_def by blast\n    also have \"\\<dots> = ((case inv_map \\<pi> i of Some k \\<Rightarrow> ket k | None \\<Rightarrow> 0) \\<bullet>\\<^sub>C ket j)\"\n      using w1 by simp\n    also have \"\\<dots> = (ket i \\<bullet>\\<^sub>C (case \\<pi> j of Some k \\<Rightarrow> ket k | None \\<Rightarrow> 0))\"\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 \"(case inv_map \\<pi> i of None \\<Rightarrow> 0| Some a \\<Rightarrow> ket a) \\<bullet>\\<^sub>C ket j\n           = ket i \\<bullet>\\<^sub>C (case \\<pi> j of None \\<Rightarrow> 0 | Some a \\<Rightarrow> ket a)\" \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 \"(ket d \\<bullet>\\<^sub>C ket j) = (ket i \\<bullet>\\<^sub>C ket c)\"\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 \"(case Some d of None \\<Rightarrow> 0 | Some a \\<Rightarrow> ket a) \\<bullet>\\<^sub>C ket j\n             = ket i \\<bullet>\\<^sub>C (case Some c of None \\<Rightarrow> 0 | Some a \\<Rightarrow> ket a)\"\n          by simp          \n        thus \"(case inv_map \\<pi> i of None \\<Rightarrow> 0 | Some a \\<Rightarrow> ket a) \\<bullet>\\<^sub>C ket j\n             = ket i \\<bullet>\\<^sub>C (case \\<pi> j of None \\<Rightarrow> 0 | Some a \\<Rightarrow> ket a)\"\n          by (simp add: Some.hyps s1)          \n      qed\n    qed\n    also have \"\\<dots> = ket i \\<bullet>\\<^sub>C (classical_operator \\<pi> *\\<^sub>V ket j)\"\n      by (simp add: w2)\n    also have \"\\<dots> = ket i \\<bullet>\\<^sub>C (G *\\<^sub>V ket j)\"\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\nunbundle no_lattice_syntax\nunbundle no_cblinfun_notation\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/Complex_Bounded_Operators/Complex_L2.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916029436189, "lm_q2_score": 0.8438950947024556, "lm_q1q2_score": 0.7286119385314103}}
{"text": "theory \"HOLCF-Meet\"\nimports \"HOLCF\"\nbegin\n\ntext {*\nThis theory defines the $\\sqcap$ operator on HOLCF domains, and introduces a type class for domains\nwhere all finite meets exist.\n*}\n\nsubsubsection {* Towards meets: Lower bounds *}\n\ncontext po\nbegin\ndefinition is_lb :: \"'a set \\<Rightarrow> 'a \\<Rightarrow> bool\" (infix \">|\" 55) where\n  \"S >| x <-> (\\<forall>y\\<in>S. x \\<sqsubseteq> y)\"\n\nlemma is_lbI: \"(!!x. x \\<in> S ==> l \\<sqsubseteq> x) ==> S >| l\"\n  by (simp add: is_lb_def)\n\nlemma is_lbD: \"[|S >| l; x \\<in> S|] ==> l \\<sqsubseteq> x\"\n  by (simp add: is_lb_def)\n\nlemma is_lb_empty [simp]: \"{} >| l\"\n  unfolding is_lb_def by fast\n\nlemma is_lb_insert [simp]: \"(insert x A) >| y = (y \\<sqsubseteq> x \\<and> A >| y)\"\n  unfolding is_lb_def by fast\n\nlemma is_lb_downward: \"[|S >| l; y \\<sqsubseteq> l|] ==> S >| y\"\n  unfolding is_lb_def by (fast intro: below_trans)\n\nsubsubsection {* Greatest lower bounds *}\n\ndefinition is_glb :: \"'a set \\<Rightarrow> 'a \\<Rightarrow> bool\" (infix \">>|\" 55) where\n  \"S >>| x <-> S >| x \\<and> (\\<forall>u. S >| u --> u \\<sqsubseteq> x)\"\n\ndefinition glb :: \"'a set \\<Rightarrow> 'a\" (\"\\<Sqinter>_\" [60]60) where\n  \"glb S = (THE x. S >>| x)\" \n\ntext {* Access to the definition as inference rule *}\n\nlemma is_glbD1: \"S >>| x ==> S >| x\"\n  unfolding is_glb_def by fast\n\nlemma is_glbD2: \"[|S >>| x; S >| u|] ==> u \\<sqsubseteq> x\"\n  unfolding is_glb_def by fast\n\nlemma (in po) is_glbI: \"[|S >| x; !!u. S >| u ==> u \\<sqsubseteq> x|] ==> S >>| x\"\n  unfolding is_glb_def by fast\n\nlemma is_glb_above_iff: \"S >>| x ==> u \\<sqsubseteq> x <-> S >| u\"\n  unfolding is_glb_def is_lb_def by (metis below_trans)\n\ntext {* glbs are unique *}\n\nlemma is_glb_unique: \"[|S >>| x; S >>| y|] ==> x = y\"\n  unfolding is_glb_def is_lb_def by (blast intro: below_antisym)\n\ntext {* technical lemmas about @{term glb} and @{term is_glb} *}\n\nlemma is_glb_glb: \"M >>| x ==> M >>| glb M\"\n  unfolding glb_def by (rule theI [OF _ is_glb_unique])\n\nlemma glb_eqI: \"M >>| l ==> glb M = l\"\n  by (rule is_glb_unique [OF is_glb_glb])\n\nlemma is_glb_singleton: \"{x} >>| x\"\n  by (simp add: is_glb_def)\n\nlemma glb_singleton [simp]: \"glb {x} = x\"\n  by (rule is_glb_singleton [THEN glb_eqI])\n\nlemma is_glb_bin: \"x \\<sqsubseteq> y ==> {x, y} >>| x\"\n  by (simp add: is_glb_def)\n\nlemma glb_bin: \"x \\<sqsubseteq> y ==> glb {x, y} = x\"\n  by (rule is_glb_bin [THEN glb_eqI])\n\nlemma is_glb_maximal: \"[|S >| x; x \\<in> S|] ==> S >>| x\"\n  by (erule is_glbI, erule (1) is_lbD)\n\nlemma glb_maximal: \"[|S >| x; x \\<in> S|] ==> glb S = x\"\n  by (rule is_glb_maximal [THEN glb_eqI])\n\nlemma glb_above: \"S >>| z \\<Longrightarrow> x \\<sqsubseteq> glb S \\<longleftrightarrow> S >| x\"\n  by (metis glb_eqI is_glb_above_iff)\nend\n\nlemma (in cpo) Meet_insert: \"S >>| l \\<Longrightarrow> {x, l} >>| l2 \\<Longrightarrow> insert x S >>| l2\"\n  apply (rule is_glbI)\n  apply (metis is_glb_above_iff is_glb_def is_lb_insert)\n  by (metis is_glb_above_iff is_glb_def is_glb_singleton is_lb_insert)\n\ntext {* Binary, hence finite meets. *}\n\nclass Finite_Meet_cpo = cpo +\n  assumes binary_meet_exists: \"\\<exists> l. l \\<sqsubseteq> x \\<and> l \\<sqsubseteq> y \\<and> (\\<forall> z. z \\<sqsubseteq> x \\<longrightarrow> z \\<sqsubseteq> y \\<longrightarrow> z \\<sqsubseteq> l)\"\nbegin\n\n  lemma binary_meet_exists': \"\\<exists>l. {x, y} >>| l\"\n    using binary_meet_exists[of x y]\n    unfolding is_glb_def is_lb_def\n    by auto\n\n  lemma finite_meet_exists:\n    assumes \"S \\<noteq> {}\"\n    and \"finite S\"\n    shows \"\\<exists>x. S >>| x\"\n  using `S \\<noteq> {}`\n  apply (induct rule: finite_induct[OF `finite S`])\n  apply (erule notE, rule refl)[1]\n  apply (case_tac \"F = {}\")\n  apply (metis is_glb_singleton)\n  apply (metis Meet_insert binary_meet_exists')\n  done\nend\n\ndefinition meet :: \"'a::cpo \\<Rightarrow> 'a \\<Rightarrow> 'a\" (infix \"\\<sqinter>\" 80) where\n  \"x \\<sqinter> y = (if \\<exists> z. {x, y} >>| z then glb {x, y} else x)\"\n\nlemma meet_def': \"(x::'a::Finite_Meet_cpo) \\<sqinter> y = glb {x, y}\"\n  unfolding meet_def by (metis binary_meet_exists')\n\n\n\nlemma meet_bot1[simp]:\n  fixes y :: \"'a :: {Finite_Meet_cpo,pcpo}\"\n  shows \"(\\<bottom> \\<sqinter> y) = \\<bottom>\" unfolding meet_def' by (metis minimal po_class.glb_bin)\nlemma meet_bot2[simp]:\n  fixes x :: \"'a :: {Finite_Meet_cpo,pcpo}\"\n  shows \"(x \\<sqinter> \\<bottom>) = \\<bottom>\" by (metis meet_bot1 meet_comm)\n\nlemma meet_below1[intro]:\n  fixes x y :: \"'a :: Finite_Meet_cpo\"\n  assumes \"x \\<sqsubseteq> z\"\n  shows \"(x \\<sqinter> y) \\<sqsubseteq> z\" unfolding meet_def' by (metis assms binary_meet_exists' below_trans glb_eqI is_glbD1 is_lb_insert)\nlemma meet_below2[intro]:\n  fixes x y :: \"'a :: Finite_Meet_cpo\"\n  assumes \"y \\<sqsubseteq> z\"\n  shows \"(x \\<sqinter> y) \\<sqsubseteq> z\" unfolding meet_def' by (metis assms binary_meet_exists' below_trans glb_eqI is_glbD1 is_lb_insert)\n\nlemma meet_above_iff:\n  fixes x y z :: \"'a :: Finite_Meet_cpo\"\n  shows \"z \\<sqsubseteq> x \\<sqinter> y \\<longleftrightarrow> z \\<sqsubseteq> x \\<and> z \\<sqsubseteq> y\"\nproof-\n  obtain g where \"{x,y} >>| g\" by (metis binary_meet_exists')\n  thus ?thesis\n  unfolding meet_def' by (simp add: glb_above)\nqed\n\nlemma meet_aboveI:\n  fixes x y z :: \"'a :: Finite_Meet_cpo\"\n  shows \"z \\<sqsubseteq> x \\<Longrightarrow> z \\<sqsubseteq> y \\<Longrightarrow> z \\<sqsubseteq> x \\<sqinter> y\" by (simp add: meet_above_iff)\n\nlemma is_meetI:\n  fixes x y z :: \"'a :: Finite_Meet_cpo\"\n  assumes \"z \\<sqsubseteq> x\"\n  assumes \"z \\<sqsubseteq> y\"\n  assumes \"\\<And> a. \\<lbrakk> a \\<sqsubseteq> x ; a \\<sqsubseteq> y \\<rbrakk> \\<Longrightarrow> a \\<sqsubseteq> z\"\n  shows \"x \\<sqinter> y = z\"\nby (metis assms below_antisym meet_above_iff below_refl)\n\nlemma meet_assoc[simp]: \"((x::'a::Finite_Meet_cpo) \\<sqinter> y) \\<sqinter> z = x \\<sqinter> (y \\<sqinter> z)\"\n  apply (rule is_meetI)\n  apply (metis below_refl meet_above_iff)\n  apply (metis below_refl meet_below2)\n  apply (metis meet_above_iff)\n  done\n\nlemma meet_self[simp]: \"r \\<sqinter> r = (r::'a::Finite_Meet_cpo)\"\n  by (metis below_refl is_meetI)\n\n\n\nlemma meet_monofun1:\n  fixes y :: \"'a :: Finite_Meet_cpo\"\n  shows \"monofun (\\<lambda>x. (x \\<sqinter> y))\"\n  by (rule monofunI)(auto simp add: meet_above_iff)\n\nlemma chain_meet1:\n  fixes y :: \"'a :: Finite_Meet_cpo\"\n  assumes \"chain Y\"\n  shows \"chain (\\<lambda> i. Y i \\<sqinter> y)\"\nby (rule chainI) (auto simp add: meet_above_iff intro: chainI chainE[OF assms])\n\nclass cont_binary_meet = Finite_Meet_cpo +\n  assumes meet_cont': \"chain Y \\<Longrightarrow> (\\<Squnion> i. Y i) \\<sqinter> y = (\\<Squnion> i. Y i \\<sqinter> y)\"\n\nlemma meet_cont1:\n  fixes y :: \"'a :: cont_binary_meet\"\n  shows \"cont (\\<lambda>x. (x \\<sqinter> y))\"\n  by (rule contI2[OF meet_monofun1]) (simp add: meet_cont')\n\nlemma meet_cont2: \n  fixes x :: \"'a :: cont_binary_meet\"\n  shows \"cont (\\<lambda>y. (x \\<sqinter> y))\" by (subst meet_comm, rule meet_cont1)\n\nlemma meet_cont[cont2cont,simp]:\"cont f \\<Longrightarrow> cont g \\<Longrightarrow> cont (\\<lambda>x. (f x \\<sqinter> (g x::'a::cont_binary_meet)))\"\n  apply (rule cont2cont_case_prod[where g = \"\\<lambda> x. (f x, g x)\" and f = \"\\<lambda> p x y . x \\<sqinter> y\", simplified])\n  apply (rule meet_cont1)\n  apply (rule meet_cont2)\n  apply (metis cont2cont_Pair)\n  done\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/HOLCF-Meet.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.863391599428538, "lm_q2_score": 0.8438950966654772, "lm_q1q2_score": 0.7286119372599071}}
{"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.*)\n  theory TIP_prop_11\n  imports \"../../Test_Base\"\nbegin\n\ndatatype 'a list = nil2 | cons2 \"'a\" \"'a list\"\n\ndatatype Nat = Z | S \"Nat\"\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 Z xs) = xs)\"\n  find_proof DInd\n  (*Why not \"(induct rule:drop.induct)\"?\n    Because of the constant \"Z\" in \"drop Z xs\"(?)\n    Because the resulting sub-goal \n    \"\\<And>z x2 x3. TIP_prop_11.\n       drop z x3 = x3 \\<Longrightarrow> \n       TIP_prop_11.drop (S z) (cons2 x2 x3) = cons2 x2 x3\" is non-theorem.*)\n  apply (induct xs rule:list.induct)\n    (*\"rule:list.induct\" is optional:\n   \"induct xs\" returns the same result with only different names of a variable.*)\n   apply auto[1]\n  apply(subst drop.simps(1))\n  apply(rule_tac HOL.refl)\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/Isaplanner/Isaplanner/TIP_prop_11.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391595913457, "lm_q2_score": 0.8438950966654774, "lm_q1q2_score": 0.7286119342935476}}
{"text": "(*  Title:      ZF/UNITY/Monotonicity.thy\n    Author:     Sidi O Ehmety, Cambridge University Computer Laboratory\n    Copyright   2002  University of Cambridge\n\nMonotonicity of an operator (meta-function) with respect to arbitrary\nset relations.\n*)\n\nsection\\<open>Monotonicity of an Operator WRT a Relation\\<close>\n\ntheory Monotonicity imports GenPrefix MultisetSum\nbegin\n\ndefinition\n  mono1 :: \"[i, i, i, i, i=>i] => o\"  where\n  \"mono1(A, r, B, s, f) ==\n    (\\<forall>x \\<in> A. \\<forall>y \\<in> A. <x,y> \\<in> r \\<longrightarrow> <f(x), f(y)> \\<in> s) & (\\<forall>x \\<in> A. f(x) \\<in> B)\"\n\n  (* monotonicity of a 2-place meta-function f *)\n\ndefinition\n  mono2 :: \"[i, i, i, i, i, i, [i,i]=>i] => o\"  where\n  \"mono2(A, r, B, s, C, t, f) == \n    (\\<forall>x \\<in> A. \\<forall>y \\<in> A. \\<forall>u \\<in> B. \\<forall>v \\<in> B.\n              <x,y> \\<in> r & <u,v> \\<in> s \\<longrightarrow> <f(x,u), f(y,v)> \\<in> t) &\n    (\\<forall>x \\<in> A. \\<forall>y \\<in> B. f(x,y) \\<in> C)\"\n\n (* Internalized relations on sets and multisets *)\n\ndefinition\n  SetLe :: \"i =>i\"  where\n  \"SetLe(A) == {<x,y> \\<in> Pow(A)*Pow(A). x \\<subseteq> y}\"\n\ndefinition\n  MultLe :: \"[i,i] =>i\"  where\n  \"MultLe(A, r) == multirel(A, r - id(A)) \\<union> id(Mult(A))\"\n\n\nlemma mono1D: \n  \"[| mono1(A, r, B, s, f); <x, y> \\<in> r; x \\<in> A; y \\<in> A |] ==> <f(x), f(y)> \\<in> s\"\nby (unfold mono1_def, auto)\n\nlemma mono2D: \n     \"[| mono2(A, r, B, s, C, t, f);  \n         <x, y> \\<in> r; <u,v> \\<in> s; x \\<in> A; y \\<in> A; u \\<in> B; v \\<in> B |] \n      ==> <f(x, u), f(y,v)> \\<in> t\"\nby (unfold mono2_def, auto)\n\n\n(** Monotonicity of take **)\n\nlemma take_mono_left_lemma:\n     \"[| i \\<le> j; xs \\<in> list(A); i \\<in> nat; j \\<in> nat |] \n      ==> <take(i, xs), take(j, xs)> \\<in> prefix(A)\"\napply (case_tac \"length (xs) \\<le> i\")\n apply (subgoal_tac \"length (xs) \\<le> j\")\n  apply (simp)\n apply (blast intro: le_trans)\napply (drule not_lt_imp_le, auto)\napply (case_tac \"length (xs) \\<le> j\")\n apply (auto simp add: take_prefix)\napply (drule not_lt_imp_le, auto)\napply (drule_tac m = i in less_imp_succ_add, auto)\napply (subgoal_tac \"i #+ k \\<le> length (xs) \")\n apply (simp add: take_add prefix_iff take_type drop_type)\napply (blast intro: leI)\ndone\n\nlemma take_mono_left:\n     \"[| i \\<le> j; xs \\<in> list(A); j \\<in> nat |]\n      ==> <take(i, xs), take(j, xs)> \\<in> prefix(A)\"\nby (blast intro: le_in_nat take_mono_left_lemma) \n\nlemma take_mono_right:\n     \"[| <xs,ys> \\<in> prefix(A); i \\<in> nat |] \n      ==> <take(i, xs), take(i, ys)> \\<in> prefix(A)\"\nby (auto simp add: prefix_iff)\n\nlemma take_mono:\n     \"[| i \\<le> j; <xs, ys> \\<in> prefix(A); j \\<in> nat |]\n      ==> <take(i, xs), take(j, ys)> \\<in> prefix(A)\"\napply (rule_tac b = \"take (j, xs) \" in prefix_trans)\napply (auto dest: prefix_type [THEN subsetD] intro: take_mono_left take_mono_right)\ndone\n\nlemma mono_take [iff]:\n     \"mono2(nat, Le, list(A), prefix(A), list(A), prefix(A), take)\"\napply (unfold mono2_def Le_def, auto)\napply (blast intro: take_mono)\ndone\n\n(** Monotonicity of length **)\n\nlemmas length_mono = prefix_length_le\n\nlemma mono_length [iff]:\n     \"mono1(list(A), prefix(A), nat, Le, length)\"\napply (unfold mono1_def)\napply (auto dest: prefix_length_le simp add: Le_def)\ndone\n\n(** Monotonicity of \\<union> **)\n\nlemma mono_Un [iff]: \n     \"mono2(Pow(A), SetLe(A), Pow(A), SetLe(A), Pow(A), SetLe(A), op Un)\"\nby (unfold mono2_def SetLe_def, auto)\n\n(* Monotonicity of multiset union *)\n\nlemma mono_munion [iff]: \n     \"mono2(Mult(A), MultLe(A,r), Mult(A), MultLe(A, r), Mult(A), MultLe(A, r), munion)\"\napply (unfold mono2_def MultLe_def)\napply (auto simp add: Mult_iff_multiset)\napply (blast intro: munion_multirel_mono munion_multirel_mono1 munion_multirel_mono2 multiset_into_Mult)+\ndone\n\nlemma mono_succ [iff]: \"mono1(nat, Le, nat, Le, succ)\"\nby (unfold mono1_def Le_def, auto)\n\nend", "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/UNITY/Monotonicity.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802350995703, "lm_q2_score": 0.7931059511841119, "lm_q1q2_score": 0.7284521405024514}}
{"text": "(*  Title:      ZF/equalities.thy\n    Author:     Lawrence C Paulson, Cambridge University Computer Laboratory\n    Copyright   1992  University of Cambridge\n*)\n\nsection\\<open>Basic Equalities and Inclusions\\<close>\n\ntheory Equalities imports Ordered_Pair begin\n\ntext\\<open>These cover union, intersection, converse, domain, range, etc.  Philippe\nde Groote proved many of the inclusions.\\<close>\n\nlemma in_mono: \"A\\<subseteq>B ==> x\\<in>A \\<longrightarrow> x\\<in>B\"\nby blast\n\nlemma the_eq_0 [simp]: \"(THE x. False) = 0\"\nby (blast intro: the_0)\n\nsubsection\\<open>Bounded Quantifiers\\<close>\ntext \\<open>\\medskip\n\n  The following are not added to the default simpset because\n  (a) they duplicate the body and (b) there are no similar rules for \\<open>Int\\<close>.\\<close>\n\nlemma ball_Un: \"(\\<forall>x \\<in> A\\<union>B. P(x)) \\<longleftrightarrow> (\\<forall>x \\<in> A. P(x)) & (\\<forall>x \\<in> B. P(x))\"\n  by blast\n\nlemma bex_Un: \"(\\<exists>x \\<in> A\\<union>B. P(x)) \\<longleftrightarrow> (\\<exists>x \\<in> A. P(x)) | (\\<exists>x \\<in> B. P(x))\"\n  by blast\n\nlemma ball_UN: \"(\\<forall>z \\<in> (\\<Union>x\\<in>A. B(x)). 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>x\\<in>A. B(x)). P(z)) \\<longleftrightarrow> (\\<exists>x\\<in>A. \\<exists>z\\<in>B(x). P(z))\"\n  by blast\n\nsubsection\\<open>Converse of a Relation\\<close>\n\nlemma converse_iff [simp]: \"<a,b>\\<in> converse(r) \\<longleftrightarrow> <b,a>\\<in>r\"\nby (unfold converse_def, blast)\n\nlemma converseI [intro!]: \"<a,b>\\<in>r ==> <b,a>\\<in>converse(r)\"\nby (unfold converse_def, blast)\n\nlemma converseD: \"<a,b> \\<in> converse(r) ==> <b,a> \\<in> r\"\nby (unfold converse_def, blast)\n\nlemma converseE [elim!]:\n    \"[| yx \\<in> converse(r);\n        !!x y. [| yx=<y,x>;  <x,y>\\<in>r |] ==> P |]\n     ==> P\"\nby (unfold converse_def, blast)\n\nlemma converse_converse: \"r \\<subseteq> Sigma A B ==> converse (converse r) = r\"\nby blast\n\nlemma converse_type: \"r\\<subseteq>A*B ==> converse(r)\\<subseteq>B*A\"\nby blast\n\nlemma converse_prod [simp]: \"converse(A*B) = B*A\"\nby blast\n\nlemma converse_empty [simp]: \"converse(0) = 0\"\nby blast\n\nlemma converse_subset_iff:\n     \"A \\<subseteq> Sigma X Y ==> converse(A) \\<subseteq> converse(B) \\<longleftrightarrow> A \\<subseteq> B\"\nby blast\n\n\nsubsection\\<open>Finite Set Constructions Using @{term cons}\\<close>\n\nlemma cons_subsetI: \"[| a\\<in>C; B\\<subseteq>C |] ==> cons a B \\<subseteq> C\"\nby blast\n\nlemma subset_consI: \"B \\<subseteq> cons a B\"\nby blast\n\nlemma cons_subset_iff [iff]: \"cons a B \\<subseteq>C \\<longleftrightarrow> a\\<in>C & B\\<subseteq>C\"\nby blast\n\n(*A safe special case of subset elimination, adding no new variables\n  [| cons(a,B) \\<subseteq> C; [| a \\<in> C; B \\<subseteq> C |] ==> R |] ==> R *)\nlemmas cons_subsetE = cons_subset_iff [THEN iffD1, THEN conjE]\n\nlemma subset_empty_iff: \"A\\<subseteq>0 \\<longleftrightarrow> A=0\"\nby blast\n\nlemma subset_cons_iff: \"C\\<subseteq>cons a B \\<longleftrightarrow> C\\<subseteq>B | (a\\<in>C & C-{a} \\<subseteq> B)\"\nby blast\n\n(* cons_def refers to Upair; reversing the equality LOOPS in rewriting!*)\nlemma cons_eq: \"{a} \\<union> B = cons a B\"\nby blast\n\nlemma cons_commute: \"cons a (cons b C) = cons b (cons a C)\"\nby blast\n\nlemma cons_absorb: \"a: B ==> cons a B = B\"\nby blast\n\nlemma cons_Diff: \"a: B ==> cons a (B-{a}) = B\"\nby blast\n\nlemma Diff_cons_eq: \"cons a B - C = (if a\\<in>C then B-C else cons a (B-C))\"\nby auto\n\nlemma equal_singleton [rule_format]: \"[| a: C;  \\<forall>y\\<in>C. y=b |] ==> C = {b}\"\nby blast\n\n\n\n(** singletons **)\n\nlemma singleton_subsetI: \"a\\<in>C ==> {a} \\<subseteq> C\"\nby blast\n\nlemma singleton_subsetD: \"{a} \\<subseteq> C  ==>  a\\<in>C\"\nby blast\n\n\n(** succ **)\n\nlemma subset_succI: \"i \\<subseteq> succ(i)\"\nby blast\n\n(*But if j is an ordinal or is transitive, then @{term\"i\\<in>j\"} implies @{term\"i\\<subseteq>j\"}!\n  See @{text\"Ord_succ_subsetI}*)\nlemma succ_subsetI: \"[| i\\<in>j;  i\\<subseteq>j |] ==> succ(i)\\<subseteq>j\"\nby (unfold succ_def, blast)\n\nlemma succ_subsetE:\n    \"[| succ(i) \\<subseteq> j;  [| i\\<in>j;  i\\<subseteq>j |] ==> P |] ==> P\"\nby (unfold succ_def, blast)\n\nlemma succ_subset_iff: \"succ(a) \\<subseteq> B \\<longleftrightarrow> (a \\<subseteq> B & a \\<in> B)\"\nby (unfold succ_def, blast)\n\n\nsubsection\\<open>Binary Intersection\\<close>\n\n(** Intersection is the greatest lower bound of two sets **)\n\nlemma Int_subset_iff: \"C \\<subseteq> A \\<inter> B \\<longleftrightarrow> C \\<subseteq> A & C \\<subseteq> B\"\nby blast\n\nlemma Int_lower1: \"A \\<inter> B \\<subseteq> A\"\nby blast\n\nlemma Int_lower2: \"A \\<inter> B \\<subseteq> B\"\nby blast\n\nlemma Int_greatest: \"[| C\\<subseteq>A;  C\\<subseteq>B |] ==> C \\<subseteq> A \\<inter> B\"\nby blast\n\nlemma Int_cons: \"cons a B \\<inter> C \\<subseteq> cons a (B \\<inter> C)\"\nby blast\n\nlemma Int_absorb [simp]: \"A \\<inter> A = A\"\nby blast\n\nlemma Int_left_absorb: \"A \\<inter> (A \\<inter> B) = A \\<inter> B\"\nby blast\n\nlemma Int_commute: \"A \\<inter> B = B \\<inter> A\"\nby blast\n\nlemma Int_left_commute: \"A \\<inter> (B \\<inter> C) = B \\<inter> (A \\<inter> C)\"\nby blast\n\nlemma Int_assoc: \"(A \\<inter> B) \\<inter> C  =  A \\<inter> (B \\<inter> C)\"\nby blast\n\n(*Intersection is an AC-operator*)\nlemmas Int_ac= Int_assoc Int_left_absorb Int_commute Int_left_commute\n\nlemma Int_absorb1: \"B \\<subseteq> A ==> A \\<inter> B = B\"\n  by blast\n\nlemma Int_absorb2: \"A \\<subseteq> B ==> A \\<inter> B = A\"\n  by blast\n\nlemma Int_Un_distrib: \"A \\<inter> (B \\<union> C) = (A \\<inter> B) \\<union> (A \\<inter> C)\"\nby blast\n\nlemma Int_Un_distrib2: \"(B \\<union> C) \\<inter> A = (B \\<inter> A) \\<union> (C \\<inter> A)\"\nby blast\n\nlemma subset_Int_iff: \"A\\<subseteq>B \\<longleftrightarrow> A \\<inter> B = A\"\nby (blast elim!: equalityE)\n\nlemma subset_Int_iff2: \"A\\<subseteq>B \\<longleftrightarrow> B \\<inter> A = A\"\nby (blast elim!: equalityE)\n\nlemma Int_Diff_eq: \"C\\<subseteq>A ==> (A-B) \\<inter> C = C-B\"\nby blast\n\nlemma Int_cons_left:\n     \"cons a A \\<inter> B = (if a \\<in> B then cons a (A \\<inter> B) else A \\<inter> B)\"\nby auto\n\nlemma Int_cons_right:\n     \"A \\<inter> cons a B = (if a \\<in> A then cons a (A \\<inter> B) else A \\<inter> B)\"\nby auto\n\nlemma cons_Int_distrib: \"cons x (A \\<inter> B) = cons x A \\<inter> cons x B\"\nby auto\n\nsubsection\\<open>Binary Union\\<close>\n\n(** Union is the least upper bound of two sets *)\n\nlemma Un_subset_iff: \"A \\<union> B \\<subseteq> C \\<longleftrightarrow> A \\<subseteq> C & B \\<subseteq> C\"\nby blast\n\nlemma Un_upper1: \"A \\<subseteq> A \\<union> B\"\nby blast\n\nlemma Un_upper2: \"B \\<subseteq> A \\<union> B\"\nby blast\n\nlemma Un_least: \"[| A\\<subseteq>C;  B\\<subseteq>C |] ==> A \\<union> B \\<subseteq> C\"\nby blast\n\nlemma Un_cons: \"cons a B \\<union> C = cons a (B \\<union> C)\"\nby blast\n\nlemma Un_absorb [simp]: \"A \\<union> A = A\"\nby blast\n\nlemma Un_left_absorb: \"A \\<union> (A \\<union> B) = A \\<union> B\"\nby blast\n\nlemma Un_commute: \"A \\<union> B = B \\<union> A\"\nby blast\n\nlemma Un_left_commute: \"A \\<union> (B \\<union> C) = B \\<union> (A \\<union> C)\"\nby blast\n\nlemma Un_assoc: \"(A \\<union> B) \\<union> C  =  A \\<union> (B \\<union> C)\"\nby blast\n\n(*Union is an AC-operator*)\nlemmas Un_ac = Un_assoc Un_left_absorb Un_commute Un_left_commute\n\nlemma Un_absorb1: \"A \\<subseteq> B ==> A \\<union> B = B\"\n  by blast\n\nlemma Un_absorb2: \"B \\<subseteq> A ==> A \\<union> B = A\"\n  by blast\n\nlemma Un_Int_distrib: \"(A \\<inter> B) \\<union> C  =  (A \\<union> C) \\<inter> (B \\<union> C)\"\nby blast\n\nlemma subset_Un_iff: \"A\\<subseteq>B \\<longleftrightarrow> A \\<union> B = B\"\nby (blast elim!: equalityE)\n\nlemma subset_Un_iff2: \"A\\<subseteq>B \\<longleftrightarrow> B \\<union> A = B\"\nby (blast elim!: equalityE)\n\nlemma Un_empty [iff]: \"(A \\<union> B = 0) \\<longleftrightarrow> (A = 0 & B = 0)\"\nby blast\n\nlemma Un_eq_Union: \"A \\<union> B = \\<Union>({A, B})\"\nby blast\n\nsubsection\\<open>Set Difference\\<close>\n\nlemma Diff_subset: \"A-B \\<subseteq> A\"\nby blast\n\nlemma Diff_contains: \"[| C\\<subseteq>A;  C \\<inter> B = 0 |] ==> C \\<subseteq> A-B\"\nby blast\n\nlemma subset_Diff_cons_iff: \"B \\<subseteq> A - cons c C  \\<longleftrightarrow>  B\\<subseteq>A-C & c \\<notin> B\"\nby blast\n\nlemma Diff_cancel: \"A - A = 0\"\nby blast\n\nlemma Diff_triv: \"A  \\<inter> B = 0 ==> A - B = A\"\nby blast\n\nlemma empty_Diff [simp]: \"0 - A = 0\"\nby blast\n\nlemma Diff_0 [simp]: \"A - 0 = A\"\nby blast\n\nlemma Diff_eq_0_iff: \"A - B = 0 \\<longleftrightarrow> A \\<subseteq> B\"\nby (blast elim: equalityE)\n\n(*NOT SUITABLE FOR REWRITING since {a} == cons(a,0)*)\nlemma Diff_cons: \"A - cons a B = A - B - {a}\"\nby blast\n\n(*NOT SUITABLE FOR REWRITING since {a} == cons(a,0)*)\nlemma Diff_cons2: \"A - cons a B = A - {a} - B\"\nby blast\n\nlemma Diff_disjoint: \"A \\<inter> (B-A) = 0\"\nby blast\n\nlemma Diff_partition: \"A\\<subseteq>B ==> A \\<union> (B-A) = B\"\nby blast\n\nlemma subset_Un_Diff: \"A \\<subseteq> B \\<union> (A - B)\"\nby blast\n\nlemma double_complement: \"[| A\\<subseteq>B; B\\<subseteq>C |] ==> B-(C-A) = A\"\nby blast\n\nlemma double_complement_Un: \"(A \\<union> B) - (B-A) = A\"\nby blast\n\nlemma Un_Int_crazy:\n \"(A \\<inter> B) \\<union> (B \\<inter> C) \\<union> (C \\<inter> A) = (A \\<union> B) \\<inter> (B \\<union> C) \\<inter> (C \\<union> A)\"\napply blast\ndone\n\nlemma Diff_Un: \"A - (B \\<union> C) = (A-B) \\<inter> (A-C)\"\nby blast\n\nlemma Diff_Int: \"A - (B \\<inter> C) = (A-B) \\<union> (A-C)\"\nby blast\n\nlemma Un_Diff: \"(A \\<union> B) - C = (A - C) \\<union> (B - C)\"\nby blast\n\nlemma Int_Diff: \"(A \\<inter> B) - C = A \\<inter> (B - C)\"\nby blast\n\nlemma Diff_Int_distrib: \"C \\<inter> (A-B) = (C \\<inter> A) - (C \\<inter> B)\"\nby blast\n\nlemma Diff_Int_distrib2: \"(A-B) \\<inter> C = (A \\<inter> C) - (B \\<inter> C)\"\nby blast\n\n(*Halmos, Naive Set Theory, page 16.*)\nlemma Un_Int_assoc_iff: \"(A \\<inter> B) \\<union> C = A \\<inter> (B \\<union> C)  \\<longleftrightarrow>  C\\<subseteq>A\"\nby (blast elim!: equalityE)\n\n\nsubsection\\<open>Big Union and Intersection\\<close>\n\n(** Big Union is the least upper bound of a set  **)\n\nlemma Union_subset_iff: \"\\<Union>(A) \\<subseteq> C \\<longleftrightarrow> (\\<forall>x\\<in>A. x \\<subseteq> C)\"\nby blast\n\nlemma Union_upper: \"B\\<in>A ==> B \\<subseteq> \\<Union>(A)\"\nby blast\n\nlemma Union_least: \"[| !!x. x\\<in>A ==> x\\<subseteq>C |] ==> \\<Union>(A) \\<subseteq> C\"\nby blast\n\nlemma Union_cons [simp]: \"\\<Union>(cons a B) = a \\<union> \\<Union>(B)\"\nby blast\n\nlemma Union_Un_distrib: \"\\<Union>(A \\<union> B) = \\<Union>(A) \\<union> \\<Union>(B)\"\nby blast\n\nlemma Union_Int_subset: \"\\<Union>(A \\<inter> B) \\<subseteq> \\<Union>(A) \\<inter> \\<Union>(B)\"\nby blast\n\nlemma Union_disjoint: \"\\<Union>(C) \\<inter> A = 0 \\<longleftrightarrow> (\\<forall>B\\<in>C. B \\<inter> A = 0)\"\nby (blast elim!: equalityE)\n\nlemma Union_empty_iff: \"\\<Union>(A) = 0 \\<longleftrightarrow> (\\<forall>B\\<in>A. B=0)\"\nby blast\n\nlemma Int_Union2: \"\\<Union>(B) \\<inter> A = (\\<Union>C\\<in>B. C \\<inter> A)\"\nby blast\n\n(** Big Intersection is the greatest lower bound of a nonempty set **)\n\nlemma Inter_subset_iff: \"A\\<noteq>0  ==>  C \\<subseteq> \\<Inter>(A) \\<longleftrightarrow> (\\<forall>x\\<in>A. C \\<subseteq> x)\"\nby blast\n\nlemma Inter_lower: \"B\\<in>A ==> \\<Inter>(A) \\<subseteq> B\"\nby blast\n\nlemma Inter_greatest: \"[| A\\<noteq>0;  !!x. x\\<in>A ==> C\\<subseteq>x |] ==> C \\<subseteq> \\<Inter>(A)\"\nby blast\n\n(** Intersection of a family of sets  **)\n\nlemma INT_lower: \"x\\<in>A ==> (\\<Inter>x\\<in>A. B(x)) \\<subseteq> B(x)\"\nby blast\n\nlemma INT_greatest: \"[| A\\<noteq>0;  !!x. x\\<in>A ==> C\\<subseteq>B(x) |] ==> C \\<subseteq> (\\<Inter>x\\<in>A. B(x))\"\nby force\n\nlemma Inter_0 [simp]: \"\\<Inter>(0) = 0\"\nby (unfold Inter_def, blast)\n\nlemma Inter_Un_subset:\n     \"[| z\\<in>A; z\\<in>B |] ==> \\<Inter>(A) \\<union> \\<Inter>(B) \\<subseteq> \\<Inter>(A \\<inter> B)\"\nby blast\n\n(* A good challenge: Inter is ill-behaved on the empty set *)\nlemma Inter_Un_distrib:\n     \"[| A\\<noteq>0;  B\\<noteq>0 |] ==> \\<Inter>(A \\<union> B) = \\<Inter>(A) \\<inter> \\<Inter>(B)\"\nby blast\n\nlemma Union_singleton: \"\\<Union>({b}) = b\"\nby blast\n\nlemma Inter_singleton: \"\\<Inter>({b}) = b\"\nby blast\n\nlemma Inter_cons [simp]:\n     \"\\<Inter>(cons a B) = (if B=0 then a else a \\<inter> \\<Inter>(B))\"\nby force\n\nsubsection\\<open>Unions and Intersections of Families\\<close>\n\nlemma subset_UN_iff_eq: \"A \\<subseteq> (\\<Union>i\\<in>I. B(i)) \\<longleftrightarrow> A = (\\<Union>i\\<in>I. A \\<inter> B(i))\"\nby (blast elim!: equalityE)\n\nlemma UN_subset_iff: \"(\\<Union>x\\<in>A. B(x)) \\<subseteq> C \\<longleftrightarrow> (\\<forall>x\\<in>A. B(x) \\<subseteq> C)\"\nby blast\n\nlemma UN_upper: \"x\\<in>A ==> B(x) \\<subseteq> (\\<Union>x\\<in>A. B(x))\"\nby (erule RepFunI [THEN Union_upper])\n\nlemma UN_least: \"[| !!x. x\\<in>A ==> B(x)\\<subseteq>C |] ==> (\\<Union>x\\<in>A. B(x)) \\<subseteq> C\"\nby blast\n\nlemma Union_eq_UN: \"\\<Union>(A) = (\\<Union>x\\<in>A. x)\"\nby blast\n\nlemma Inter_eq_INT: \"\\<Inter>(A) = (\\<Inter>x\\<in>A. x)\"\nby (unfold Inter_def, blast)\n\nlemma UN_0 [simp]: \"(\\<Union>i\\<in>0. A(i)) = 0\"\nby blast\n\nlemma UN_singleton: \"(\\<Union>x\\<in>A. {x}) = A\"\nby blast\n\nlemma UN_Un: \"(\\<Union>i\\<in> A \\<union> B. C(i)) = (\\<Union>i\\<in> A. C(i)) \\<union> (\\<Union>i\\<in>B. C(i))\"\nby blast\n\nlemma INT_Un: \"(\\<Inter>i\\<in>I \\<union> J. A(i)) =\n               (if I=0 then \\<Inter>j\\<in>J. A(j)\n                       else if J=0 then \\<Inter>i\\<in>I. A(i)\n                       else ((\\<Inter>i\\<in>I. A(i)) \\<inter>  (\\<Inter>j\\<in>J. A(j))))\"\nby (simp, blast intro!: equalityI)\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))\"\nby blast\n\n(*Halmos, Naive Set Theory, page 35.*)\nlemma Int_UN_distrib: \"B \\<inter> (\\<Union>i\\<in>I. A(i)) = (\\<Union>i\\<in>I. B \\<inter> A(i))\"\nby blast\n\nlemma Un_INT_distrib: \"I\\<noteq>0 ==> B \\<union> (\\<Inter>i\\<in>I. A(i)) = (\\<Inter>i\\<in>I. B \\<union> A(i))\"\nby auto\n\nlemma Int_UN_distrib2:\n     \"(\\<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))\"\nby blast\n\nlemma Un_INT_distrib2: \"[| I\\<noteq>0;  J\\<noteq>0 |] ==>\n      (\\<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))\"\nby auto\n\nlemma UN_constant [simp]: \"(\\<Union>y\\<in>A. c) = (if A=0 then 0 else c)\"\nby force\n\nlemma INT_constant [simp]: \"(\\<Inter>y\\<in>A. c) = (if A=0 then 0 else c)\"\nby force\n\nlemma UN_RepFun [simp]: \"(\\<Union>y\\<in> RepFun A f. B(y)) = (\\<Union>x\\<in>A. B(f(x)))\"\nby blast\n\nlemma INT_RepFun [simp]: \"(\\<Inter>x\\<in>RepFun A f. B(x)) = (\\<Inter>a\\<in>A. B(f(a)))\"\nby (auto simp add: Inter_def)\n\nlemma INT_Union_eq:\n     \"0 \\<notin> A ==> (\\<Inter>x\\<in> \\<Union>(A). B(x)) = (\\<Inter>y\\<in>A. \\<Inter>x\\<in>y. B(x))\"\napply (subgoal_tac \"\\<forall>x\\<in>A. x\\<noteq>0\")\n prefer 2 apply blast\napply (force simp add: Inter_def ball_conj_distrib)\ndone\n\nlemma INT_UN_eq:\n     \"(\\<forall>x\\<in>A. B(x) \\<noteq> 0)\n      ==> (\\<Inter>z\\<in> (\\<Union>x\\<in>A. B(x)). C(z)) = (\\<Inter>x\\<in>A. \\<Inter>z\\<in> B(x). C(z))\"\napply (subst INT_Union_eq, blast)\napply (simp add: Inter_def)\ndone\n\n\n(** Devlin, Fundamentals of Contemporary Set Theory, page 12, exercise 5:\n    Union of a family of unions **)\n\nlemma UN_Un_distrib:\n     \"(\\<Union>i\\<in>I. A(i) \\<union> B(i)) = (\\<Union>i\\<in>I. A(i))  \\<union>  (\\<Union>i\\<in>I. B(i))\"\nby blast\n\nlemma INT_Int_distrib:\n     \"I\\<noteq>0 ==> (\\<Inter>i\\<in>I. A(i) \\<inter> B(i)) = (\\<Inter>i\\<in>I. A(i)) \\<inter> (\\<Inter>i\\<in>I. B(i))\"\nby (blast elim!: not_emptyE)\n\nlemma UN_Int_subset:\n     \"(\\<Union>z\\<in>I \\<inter> J. A(z)) \\<subseteq> (\\<Union>z\\<in>I. A(z)) \\<inter> (\\<Union>z\\<in>J. A(z))\"\nby blast\n\n(** Devlin, page 12, exercise 5: Complements **)\n\nlemma Diff_UN: \"I\\<noteq>0 ==> B - (\\<Union>i\\<in>I. A(i)) = (\\<Inter>i\\<in>I. B - A(i))\"\nby (blast elim!: not_emptyE)\n\nlemma Diff_INT: \"I\\<noteq>0 ==> B - (\\<Inter>i\\<in>I. A(i)) = (\\<Union>i\\<in>I. B - A(i))\"\nby (blast elim!: not_emptyE)\n\n\n(** Unions and Intersections with General Sum **)\n\n(*Not suitable for rewriting: LOOPS!*)\nlemma Sigma_cons1: \"Sigma (cons a B) C = ({a}*C(a)) \\<union> Sigma B C\"\nby blast\n\n(*Not suitable for rewriting: LOOPS!*)\nlemma Sigma_cons2: \"A * cons b B = A*{b} \\<union> A*B\"\nby blast\n\nlemma Sigma_succ1: \"Sigma (succ A) B = ({A}*B(A)) \\<union> Sigma A B\"\nby blast\n\nlemma Sigma_succ2: \"A * succ(B) = A*{B} \\<union> A*B\"\nby blast\n\nlemma SUM_UN_distrib1:\n     \"(\\<Sum>x \\<in> (\\<Union>y\\<in>A. C(y)). B(x)) = (\\<Union>y\\<in>A. \\<Sum>x\\<in>C(y). B(x))\"\nby blast\n\nlemma SUM_UN_distrib2:\n     \"(\\<Sum>i\\<in>I. \\<Union>j\\<in>J. C i j) = (\\<Union>j\\<in>J. \\<Sum>i\\<in>I. C i j)\"\nby blast\n\nlemma SUM_Un_distrib1:\n     \"(\\<Sum>i\\<in>I \\<union> J. C(i)) = (\\<Sum>i\\<in>I. C(i)) \\<union> (\\<Sum>j\\<in>J. C(j))\"\nby blast\n\nlemma SUM_Un_distrib2:\n     \"(\\<Sum>i\\<in>I. A(i) \\<union> B(i)) = (\\<Sum>i\\<in>I. A(i)) \\<union> (\\<Sum>i\\<in>I. B(i))\"\nby blast\n\n(*First-order version of the above, for rewriting*)\nlemma prod_Un_distrib2: \"I * (A \\<union> B) = I*A \\<union> I*B\"\nby (rule SUM_Un_distrib2)\n\nlemma SUM_Int_distrib1:\n     \"(\\<Sum>i\\<in>I \\<inter> J. C(i)) = (\\<Sum>i\\<in>I. C(i)) \\<inter> (\\<Sum>j\\<in>J. C(j))\"\nby blast\n\nlemma SUM_Int_distrib2:\n     \"(\\<Sum>i\\<in>I. A(i) \\<inter> B(i)) = (\\<Sum>i\\<in>I. A(i)) \\<inter> (\\<Sum>i\\<in>I. B(i))\"\nby blast\n\n(*First-order version of the above, for rewriting*)\nlemma prod_Int_distrib2: \"I * (A \\<inter> B) = I*A \\<inter> I*B\"\nby (rule SUM_Int_distrib2)\n\n(*Cf Aczel, Non-Well-Founded Sets, page 115*)\nlemma SUM_eq_UN: \"(\\<Sum>i\\<in>I. A(i)) = (\\<Union>i\\<in>I. {i} * A(i))\"\nby blast\n\nlemma times_subset_iff:\n     \"(A'*B' \\<subseteq> A*B) \\<longleftrightarrow> (A' = 0 | B' = 0 | (A'\\<subseteq>A) & (B'\\<subseteq>B))\"\nby blast\n\nlemma Int_Sigma_eq:\n     \"(\\<Sum>x \\<in> A'. B'(x)) \\<inter> (\\<Sum>x \\<in> A. B(x)) = (\\<Sum>x \\<in> A' \\<inter> A. B'(x) \\<inter> B(x))\"\nby blast\n\n(** Domain **)\n\nlemma domain_iff: \"a: domain(r) \\<longleftrightarrow> (\\<exists>y. <a,y>\\<in> r)\"\nby (unfold domain_def, blast)\n\nlemma domainI [intro]: \"<a,b>\\<in> r ==> a: domain(r)\"\nby (unfold domain_def, blast)\n\nlemma domainE [elim!]:\n    \"[| a \\<in> domain(r);  !!y. <a,y>\\<in> r ==> P |] ==> P\"\nby (unfold domain_def, blast)\n\nlemma domain_subset: \"domain (Sigma A B) \\<subseteq> A\"\nby blast\n\nlemma domain_of_prod: \"b\\<in>B ==> domain(A*B) = A\"\nby blast\n\nlemma domain_0 [simp]: \"domain(0) = 0\"\nby blast\n\nlemma domain_cons [simp]: \"domain (cons <a,b> r) = cons a (domain r)\"\nby blast\n\nlemma domain_Un_eq [simp]: \"domain(A \\<union> B) = domain(A) \\<union> domain(B)\"\nby blast\n\nlemma domain_Int_subset: \"domain(A \\<inter> B) \\<subseteq> domain(A) \\<inter> domain(B)\"\nby blast\n\nlemma domain_Diff_subset: \"domain(A) - domain(B) \\<subseteq> domain(A - B)\"\nby blast\n\nlemma domain_UN: \"domain(\\<Union>x\\<in>A. B(x)) = (\\<Union>x\\<in>A. domain(B(x)))\"\nby blast\n\nlemma domain_Union: \"domain(\\<Union>(A)) = (\\<Union>x\\<in>A. domain(x))\"\nby blast\n\n\n(** Range **)\n\nlemma rangeI [intro]: \"<a,b>\\<in> r ==> b \\<in> range(r)\"\napply (unfold range_def)\napply (erule converseI [THEN domainI])\ndone\n\nlemma rangeE [elim!]: \"[| b \\<in> range(r);  !!x. <x,b>\\<in> r ==> P |] ==> P\"\nby (unfold range_def, blast)\n\nlemma range_subset: \"range(A*B) \\<subseteq> B\"\napply (unfold range_def)\napply (subst converse_prod)\napply (rule domain_subset)\ndone\n\nlemma range_of_prod: \"a\\<in>A ==> range(A*B) = B\"\nby blast\n\nlemma range_0 [simp]: \"range(0) = 0\"\nby blast\n\nlemma range_cons [simp]: \"range (cons <a,b> r) = cons b (range r)\"\nby blast\n\nlemma range_Un_eq [simp]: \"range(A \\<union> B) = range(A) \\<union> range(B)\"\nby blast\n\nlemma range_Int_subset: \"range(A \\<inter> B) \\<subseteq> range(A) \\<inter> range(B)\"\nby blast\n\nlemma range_Diff_subset: \"range(A) - range(B) \\<subseteq> range(A - B)\"\nby blast\n\nlemma domain_converse [simp]: \"domain(converse(r)) = range(r)\"\nby blast\n\nlemma range_converse [simp]: \"range(converse(r)) = domain(r)\"\nby blast\n\n\n(** Field **)\n\nlemma fieldI1: \"<a,b>\\<in> r ==> a \\<in> field(r)\"\nby (unfold field_def, blast)\n\nlemma fieldI2: \"<a,b>\\<in> r ==> b \\<in> field(r)\"\nby (unfold field_def, blast)\n\nlemma fieldCI [intro]:\n    \"(~ <c,a>\\<in>r ==> <a,b>\\<in> r) ==> a \\<in> field(r)\"\napply (unfold field_def, blast)\ndone\n\nlemma fieldE [elim!]:\n     \"[| a \\<in> field(r);\n         !!x. <a,x>\\<in> r ==> P;\n         !!x. <x,a>\\<in> r ==> P        |] ==> P\"\nby (unfold field_def, blast)\n\nlemma field_subset: \"field(A*B) \\<subseteq> A \\<union> B\"\nby blast\n\nlemma domain_subset_field: \"domain(r) \\<subseteq> field(r)\"\napply (unfold field_def)\napply (rule Un_upper1)\ndone\n\nlemma range_subset_field: \"range(r) \\<subseteq> field(r)\"\napply (unfold field_def)\napply (rule Un_upper2)\ndone\n\nlemma domain_times_range: \"r \\<subseteq> Sigma A B ==> r \\<subseteq> domain r * range r\"\nby blast\n\nlemma field_times_field: \"r \\<subseteq> Sigma A B ==> r \\<subseteq> field r * field r\"\nby blast\n\nlemma relation_field_times_field: \"relation(r) ==> r \\<subseteq> field(r)*field(r)\"\nby (simp add: relation_def, blast)\n\nlemma field_of_prod: \"field(A*A) = A\"\nby blast\n\nlemma field_0 [simp]: \"field(0) = 0\"\nby blast\n\nlemma field_cons [simp]: \"field (cons <a,b> r) = cons a (cons b (field r))\"\nby blast\n\nlemma field_Un_eq [simp]: \"field(A \\<union> B) = field(A) \\<union> field(B)\"\nby blast\n\nlemma field_Int_subset: \"field(A \\<inter> B) \\<subseteq> field(A) \\<inter> field(B)\"\nby blast\n\nlemma field_Diff_subset: \"field(A) - field(B) \\<subseteq> field(A - B)\"\nby blast\n\nlemma field_converse [simp]: \"field(converse(r)) = field(r)\"\nby blast\n\n(** The Union of a set of relations is a relation -- Lemma for fun_Union **)\nlemma rel_Union: \"(\\<forall>x\\<in>S. \\<exists>A B. x \\<subseteq> A*B) ==>\n                  \\<Union>(S) \\<subseteq> domain(\\<Union>(S)) * range(\\<Union>(S))\"\nby blast\n\n(** The Union of 2 relations is a relation (Lemma for fun_Un)  **)\nlemma rel_Un: \"[| r \\<subseteq> A*B;  s \\<subseteq> C*D |] ==> (r \\<union> s) \\<subseteq> (A \\<union> C) * (B \\<union> D)\"\nby blast\n\nlemma domain_Diff_eq: \"[| <a,c> \\<in> r; c\\<noteq>b |] ==> domain(r-{<a,b>}) = domain(r)\"\nby blast\n\nlemma range_Diff_eq: \"[| <c,b> \\<in> r; c\\<noteq>a |] ==> range(r-{<a,b>}) = range(r)\"\nby blast\n\n\nsubsection\\<open>Image of a Set under a Function or Relation\\<close>\n\nlemma image_iff: \"b \\<in> r``A \\<longleftrightarrow> (\\<exists>x\\<in>A. <x,b>\\<in>r)\"\nby (unfold image_def, blast)\n\nlemma image_singleton_iff: \"b \\<in> r``{a} \\<longleftrightarrow> <a,b>\\<in>r\"\nby (rule image_iff [THEN iff_trans], blast)\n\nlemma imageI [intro]: \"[| <a,b>\\<in> r;  a\\<in>A |] ==> b \\<in> r``A\"\nby (unfold image_def, blast)\n\nlemma imageE [elim!]:\n    \"[| b: r``A;  !!x.[| <x,b>\\<in> r;  x\\<in>A |] ==> P |] ==> P\"\nby (unfold image_def, blast)\n\nlemma image_subset: \"r \\<subseteq> A*B ==> r``C \\<subseteq> B\"\nby blast\n\nlemma image_0 [simp]: \"r``0 = 0\"\nby blast\n\nlemma image_Un [simp]: \"r``(A \\<union> B) = (r``A) \\<union> (r``B)\"\nby blast\n\nlemma image_UN: \"r `` (\\<Union>x\\<in>A. B(x)) = (\\<Union>x\\<in>A. r `` B(x))\"\nby blast\n\nlemma Collect_image_eq:\n     \"{z \\<in> Sigma A B. P z} `` C = (\\<Union>x \\<in> A. {y \\<in> B x. x \\<in> C & P <x,y>})\"\nby blast\n\nlemma image_Int_subset: \"r``(A \\<inter> B) \\<subseteq> (r``A) \\<inter> (r``B)\"\nby blast\n\nlemma image_Int_square_subset: \"(r \\<inter> A*A)``B \\<subseteq> (r``B) \\<inter> A\"\nby blast\n\nlemma image_Int_square: \"B\\<subseteq>A ==> (r \\<inter> A*A)``B = (r``B) \\<inter> A\"\nby blast\n\n\n(*Image laws for special relations*)\nlemma image_0_left [simp]: \"0``A = 0\"\nby blast\n\nlemma image_Un_left: \"(r \\<union> s)``A = (r``A) \\<union> (s``A)\"\nby blast\n\nlemma image_Int_subset_left: \"(r \\<inter> s)``A \\<subseteq> (r``A) \\<inter> (s``A)\"\nby blast\n\n\nsubsection\\<open>Inverse Image of a Set under a Function or Relation\\<close>\n\nlemma vimage_iff:\n    \"a \\<in> r-``B \\<longleftrightarrow> (\\<exists>y\\<in>B. <a,y>\\<in>r)\"\nby (unfold vimage_def image_def converse_def, blast)\n\nlemma vimage_singleton_iff: \"a \\<in> r-``{b} \\<longleftrightarrow> <a,b>\\<in>r\"\nby (rule vimage_iff [THEN iff_trans], blast)\n\nlemma vimageI [intro]: \"[| <a,b>\\<in> r;  b\\<in>B |] ==> a \\<in> r-``B\"\nby (unfold vimage_def, blast)\n\nlemma vimageE [elim!]:\n    \"[| a: r-``B;  !!x.[| <a,x>\\<in> r;  x\\<in>B |] ==> P |] ==> P\"\napply (unfold vimage_def, blast)\ndone\n\nlemma vimage_subset: \"r \\<subseteq> A*B ==> r-``C \\<subseteq> A\"\napply (unfold vimage_def)\napply (erule converse_type [THEN image_subset])\ndone\n\nlemma vimage_0 [simp]: \"r-``0 = 0\"\nby blast\n\nlemma vimage_Un [simp]: \"r-``(A \\<union> B) = (r-``A) \\<union> (r-``B)\"\nby blast\n\nlemma vimage_Int_subset: \"r-``(A \\<inter> B) \\<subseteq> (r-``A) \\<inter> (r-``B)\"\nby blast\n\n(*NOT suitable for rewriting*)\nlemma vimage_eq_UN: \"f -``B = (\\<Union>y\\<in>B. f-``{y})\"\nby blast\n\nlemma function_vimage_Int:\n     \"function(f) ==> f-``(A \\<inter> B) = (f-``A)  \\<inter>  (f-``B)\"\nby (unfold function_def, blast)\n\nlemma function_vimage_Diff: \"function(f) ==> f-``(A-B) = (f-``A) - (f-``B)\"\nby (unfold function_def, blast)\n\nlemma function_image_vimage: \"function(f) ==> f `` (f-`` A) \\<subseteq> A\"\nby (unfold function_def, blast)\n\nlemma vimage_Int_square_subset: \"(r \\<inter> A*A)-``B \\<subseteq> (r-``B) \\<inter> A\"\nby blast\n\nlemma vimage_Int_square: \"B\\<subseteq>A ==> (r \\<inter> A*A)-``B = (r-``B) \\<inter> A\"\nby blast\n\n\n\n(*Invese image laws for special relations*)\nlemma vimage_0_left [simp]: \"0-``A = 0\"\nby blast\n\nlemma vimage_Un_left: \"(r \\<union> s)-``A = (r-``A) \\<union> (s-``A)\"\nby blast\n\nlemma vimage_Int_subset_left: \"(r \\<inter> s)-``A \\<subseteq> (r-``A) \\<inter> (s-``A)\"\nby blast\n\n\n(** Converse **)\n\nlemma converse_Un [simp]: \"converse(A \\<union> B) = converse(A) \\<union> converse(B)\"\nby blast\n\nlemma converse_Int [simp]: \"converse(A \\<inter> B) = converse(A) \\<inter> converse(B)\"\nby blast\n\nlemma converse_Diff [simp]: \"converse(A - B) = converse(A) - converse(B)\"\nby blast\n\nlemma converse_UN [simp]: \"converse(\\<Union>x\\<in>A. B(x)) = (\\<Union>x\\<in>A. converse(B(x)))\"\nby blast\n\n(*Unfolding Inter avoids using excluded middle on A=0*)\nlemma converse_INT [simp]:\n     \"converse(\\<Inter>x\\<in>A. B(x)) = (\\<Inter>x\\<in>A. converse(B(x)))\"\napply (unfold Inter_def, blast)\ndone\n\n\nsubsection\\<open>Powerset Operator\\<close>\n\nlemma Pow_0 [simp]: \"Pow(0) = {0}\"\nby blast\n\nlemma Pow_insert: \"Pow (cons a A) = Pow(A) \\<union> {cons a X . X: Pow(A)}\"\napply (rule equalityI, safe)\napply (erule swap)\napply (rule_tac a = \"x-{a}\" in RepFun_eqI, auto)\ndone\n\nlemma Un_Pow_subset: \"Pow(A) \\<union> Pow(B) \\<subseteq> Pow(A \\<union> B)\"\nby blast\n\nlemma UN_Pow_subset: \"(\\<Union>x\\<in>A. Pow(B(x))) \\<subseteq> Pow(\\<Union>x\\<in>A. B(x))\"\nby blast\n\nlemma subset_Pow_Union: \"A \\<subseteq> Pow(\\<Union>(A))\"\nby blast\n\nlemma Union_Pow_eq [simp]: \"\\<Union>(Pow(A)) = A\"\nby blast\n\nlemma Union_Pow_iff: \"\\<Union>(A) \\<in> Pow(B) \\<longleftrightarrow> A \\<in> Pow(Pow(B))\"\nby blast\n\nlemma Pow_Int_eq [simp]: \"Pow(A \\<inter> B) = Pow(A) \\<inter> Pow(B)\"\nby blast\n\nlemma Pow_INT_eq: \"A\\<noteq>0 ==> Pow(\\<Inter>x\\<in>A. B(x)) = (\\<Inter>x\\<in>A. Pow(B(x)))\"\nby (blast elim!: not_emptyE)\n\n\nsubsection\\<open>RepFun\\<close>\n\nlemma RepFun_subset: \"[| !!x. x\\<in>A ==> f(x) \\<in> B |] ==> {f(x). x\\<in>A} \\<subseteq> B\"\nby blast\n\nlemma RepFun_eq_0_iff [simp]: \"{f(x).x\\<in>A}=0 \\<longleftrightarrow> A=0\"\nby blast\n\nlemma RepFun_constant [simp]: \"{c. x\\<in>A} = (if A=0 then 0 else {c})\"\nby force\n\n\nsubsection\\<open>Collect\\<close>\n\nlemma Collect_subset: \"Collect A P \\<subseteq> A\"\nby blast\n\nlemma Collect_Un: \"Collect (A \\<union> B) P = Collect A P \\<union> Collect B P\"\nby blast\n\nlemma Collect_Int: \"Collect (A \\<inter> B) P = Collect A P \\<inter> Collect B P\"\nby blast\n\nlemma Collect_Diff: \"Collect (A - B) P = Collect A P - Collect B P\"\nby blast\n\nlemma Collect_cons: \"{x\\<in>cons a B. P x} =\n      (if P(a) then cons a {x\\<in>B. P(x)} else {x\\<in>B. P(x)})\"\nby (simp, blast)\n\nlemma Int_Collect_self_eq: \"A \\<inter> Collect A P = Collect A P\"\nby blast\n\nlemma Collect_Collect_eq [simp]:\n     \"Collect (Collect A P) Q = Collect A (%x. P(x) & Q(x))\"\nby blast\n\nlemma Collect_Int_Collect_eq:\n     \"Collect A P \\<inter> Collect A Q = Collect A (%x. P(x) & Q(x))\"\nby blast\n\nlemma Collect_Union_eq [simp]:\n     \"Collect (\\<Union>x\\<in>A. B(x)) P = (\\<Union>x\\<in>A. Collect (B x) P)\"\nby blast\n\nlemma Collect_Int_left: \"{x\\<in>A. P(x)} \\<inter> B = {x \\<in> A \\<inter> B. P(x)}\"\nby blast\n\nlemma Collect_Int_right: \"A \\<inter> {x\\<in>B. P(x)} = {x \\<in> A \\<inter> B. P(x)}\"\nby blast\n\nlemma Collect_disj_eq: \"{x\\<in>A. P(x) | Q(x)} = Collect A P \\<union> Collect A Q\"\nby blast\n\nlemma Collect_conj_eq: \"{x\\<in>A. P(x) & Q(x)} = Collect A P \\<inter> Collect A Q\"\nby blast\n\nlemmas subset_SIs = subset_refl cons_subsetI subset_consI\n                    Union_least UN_least Un_least\n                    Inter_greatest Int_greatest RepFun_subset\n                    Un_upper1 Un_upper2 Int_lower1 Int_lower2\n\nML \\<open>\nval subset_cs =\n  claset_of (@{context}\n    delrules [@{thm subsetI}, @{thm subsetCE}]\n    addSIs @{thms subset_SIs}\n    addIs  [@{thm Union_upper}, @{thm Inter_lower}]\n    addSEs [@{thm cons_subsetE}]);\n\nval ZF_cs = claset_of (@{context} delrules [@{thm equalityI}]);\n\\<close>\n\nend\n\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/Equalities.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8740772384450967, "lm_q2_score": 0.8333245994514082, "lm_q1q2_score": 0.7283900646168532}}
{"text": "section \"Arithmetic and Boolean Expressions\"\n\ntheory AExpTimes 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 | Times 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\" |\n\"aval (Times a\\<^sub>1 a\\<^sub>2) s = aval a\\<^sub>1 s * aval a\\<^sub>2 s\"\ntext_raw{*}%endsnip*}\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\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\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\"\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{*\\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)\" |\n\"asimp (Times a\\<^sub>1 a\\<^sub>2) = times (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  \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/AExpTimes.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772318846386, "lm_q2_score": 0.8333245973817158, "lm_q1q2_score": 0.7283900573407911}}
{"text": "theory Space_Vectors\n\nimports Module\nbegin\n\ninductive_set\n  Span :: \"('a, 'b) ring_scheme \\<Rightarrow> ('a, 'c, 'd) module_scheme \\<Rightarrow> 'c set \\<Rightarrow> 'c set\"\n  for R and M and H where\n    zero:  \"\\<zero>\\<^bsub>M\\<^esub> \\<in> Span R M H\"\n  | incl: \"h \\<in> H \\<Longrightarrow> h \\<in> Span R M H\"\n  | a_inv : \"h \\<in> (Span R M H) \\<Longrightarrow> a_inv M h \\<in> Span R M H\"\n  | eng_add : \"h1 \\<in> Span R M H \\<Longrightarrow> h2 \\<in> Span R M H \\<Longrightarrow> h1 \\<oplus>\\<^bsub>M\\<^esub> h2 \\<in> Span R M H\"\n  | eng_smult:  \"h1 \\<in> carrier R \\<Longrightarrow> h2 \\<in> Span R M H \\<Longrightarrow> h1 \\<odot>\\<^bsub>M\\<^esub> h2 \\<in> Span R M H\"\n\nsubsection\\<open>Basic Properties of Generated Fields - First Part\\<close>\n\nlemma (in module) Span_in_carrier:\n  assumes \"H \\<subseteq> carrier M\"\n  shows \"h \\<in> Span R M H \\<Longrightarrow> h \\<in> carrier M\"\nproof (induction rule: Span.induct)\n  case zero\n  then show ?case\n    using a_comm_group monoid.one_closed[of M] unfolding comm_group_def comm_monoid_def by auto \n  next\n  case (incl h)\n  then show ?case using assms by auto\n  next\n  case (a_inv h)\n  then show ?case using a_comm_group group.inv_closed unfolding comm_group_def by auto\n  next\n  case (eng_add h1 h2)\n  then show ?case using a_comm_group monoid.m_closed\n    unfolding comm_group_def comm_monoid_def by auto\n  next\n  case (eng_smult h1 h2)\n  then show ?case using module_axioms unfolding module_def module_axioms_def by auto\nqed\n\nlemma (in module) Span_empty :\n\"Span R M {} = {\\<zero>\\<^bsub>M\\<^esub>}\"\nproof\n  show \"{\\<zero>\\<^bsub>M\\<^esub>} \\<subseteq> Span R M {}\" using Span.zero[of M R \"{}\"] by auto\n  show \"Span R M {} \\<subseteq> {\\<zero>\\<^bsub>M\\<^esub>} \"\n  proof\n    fix x assume x_def : \"x \\<in> Span R M {}\"\n    show \"x \\<in> {\\<zero>\\<^bsub>M\\<^esub>} \" using x_def\n      apply (induction x rule : Span.induct)\n      by simp_all\n  qed\nqed\n\n\nlemma (in module) Span_singleton :\n  assumes \"x \\<in> carrier M\"\n  shows \"Span R M {x} = {k \\<odot>\\<^bsub>M\\<^esub> x | k. k \\<in> carrier R}\"\nproof\n  show \"{k \\<odot>\\<^bsub>M\\<^esub> x |k. k \\<in> carrier R} \\<subseteq> Span R M {x}\"\n    using Span.eng_smult[of _ R x M \"{x}\"] Span.incl[of x \"{x}\" R M] by blast\n  show \"Span R M {x} \\<subseteq> {k \\<odot>\\<^bsub>M\\<^esub> x |k. k \\<in> carrier R}\"\n  proof\n    fix xa assume xa_def : \"xa \\<in> Span R M {x}\"\n    show \"xa \\<in> {k \\<odot>\\<^bsub>M\\<^esub> x |k. k \\<in> carrier R}\" using xa_def\n    proof (induction rule : Span.induct)\n      case zero\n      then show ?case using smult_l_null assms by force\n    next\n      case (incl h)\n      then show ?case using smult_one assms by force\n    next\n      case (a_inv h)\n      then show ?case\n        by (smt assms cring_simprules(3) mem_Collect_eq module_axioms module_def smult_l_minus)\n    next\n      case (eng_add h1 h2)\n      then show ?case using smult_l_distr[OF _ _ assms]\n        by (smt R.add.m_closed mem_Collect_eq)\n    next\n      case (eng_smult h1 h2)\n      then show ?case using m_closed[of h1]\n        by (smt assms mem_Collect_eq smult_assoc1) \n    qed\n  qed\nqed\n\n\nlemma (in module) Span_is_add_subgroup :\n  assumes \"H \\<subseteq> carrier M\"\n  shows \"subgroup (Span R M H) (add_monoid (M))\"\n using zero[of M R H] Span_in_carrier assms eng_add[of _ R M H] a_inv[of _ R M H] a_inv_def[of M]\n  by (auto intro! : subgroup.intro) \n\n\nlemma (in module) Span_is_submodule :\n  assumes \"H \\<subseteq> (carrier M)\"\n  shows \"submodule (Span R M H) R M\"\nproof (intro submoduleI)\n  show \"Span R M H \\<subseteq> carrier M\" using Span_in_carrier assms by auto\n  show \"\\<zero>\\<^bsub>M\\<^esub> \\<in> Span R M H\" using zero assms by auto\n  show \"\\<And>a. a \\<in> Span R M H \\<Longrightarrow> \\<ominus>\\<^bsub>M\\<^esub> a \\<in> Span R M H\" using a_inv[of _ R M H] assms by auto \n  show \"\\<And>a b. a \\<in> Span R M H \\<Longrightarrow> b \\<in> Span R M H \\<Longrightarrow> a \\<oplus>\\<^bsub>M\\<^esub> b \\<in> Span R M H\"\n    using eng_add[of _ R M H] by auto\n  show \"\\<And>a x. a \\<in> carrier R \\<Longrightarrow> x \\<in> Span R M H \\<Longrightarrow> a \\<odot>\\<^bsub>M\\<^esub> x \\<in> Span R M H\"\n    using eng_smult[of _ R _ M H]  by auto\nqed\n\nlemma (in module) Span_is_module :\n  assumes \"H \\<subseteq> carrier M\"\n  shows \"module R (M\\<lparr>carrier := Span R M H\\<rparr>)\"\n  by (intro submodule.submodule_is_module[OF Span_is_submodule[OF assms] module_axioms])\n\n\nlemma (in module) Span_min_submodule1:\n  assumes \"H \\<subseteq> carrier M\"\n    and \"submodule E R M\" \"H \\<subseteq> E\"\n  shows \"Span R M H \\<subseteq> E\"\nproof\n  fix h show \"h \\<in> Span R M H \\<Longrightarrow> h \\<in> E\"\n  proof (induct rule: Span.induct)\n    case zero thus ?case\n      using assms(2) subgroup.one_closed[of E \"add_monoid M\"] submodule.axioms(1) by auto\n  next\n    case incl thus ?case using assms(3) by blast\n  next\n    case a_inv thus ?case using assms(2)  submoduleE(3) by auto\n  next\n    case eng_add thus ?case\n      using submoduleE(5)[OF assms(2)] by auto\n  next\n    case (eng_smult h1 h2) thus ?case\n      using submoduleE(4)[OF assms(2)] by auto\n  qed\nqed\n\nlemma (in module) SpanI:\n  assumes \"H \\<subseteq> carrier M\"\n    and \"submodule E R M\" \"H \\<subseteq> E\"\n    and \"\\<And>K. \\<lbrakk> submodule K R M; H \\<subseteq> K \\<rbrakk> \\<Longrightarrow> E \\<subseteq> K\"\n  shows \"E = Span R M H\"\nproof\n  show \"E \\<subseteq> Span R M H\"\n    using assms Span_is_submodule Span.incl by (metis subset_iff)\n  show \"Span R M H \\<subseteq> E\"\n    using Span_min_submodule1[OF assms(1-3)] by simp\nqed\n\nlemma (in module) SpanE:\n  assumes \"H \\<subseteq> carrier M\" and \"E = Span R M H\"\n  shows \"submodule E R M\" and \"H \\<subseteq> E\" and \"\\<And>K. \\<lbrakk> submodule K R M; H \\<subseteq> K \\<rbrakk> \\<Longrightarrow> E \\<subseteq> K\"\nproof -\n  show \"submodule E R M\" using assms Span_is_submodule by simp\n  show \"H \\<subseteq> E\" using assms(2) by (simp add: Span.incl subsetI)\n  show \"\\<And>K. submodule K R M \\<Longrightarrow> H \\<subseteq> K \\<Longrightarrow> E \\<subseteq> K\"\n    using assms Span_min_submodule1 by auto\nqed\n\nlemma (in module) Span_min_submodule2:\n  assumes \"H \\<subseteq> carrier M\"\n  shows \"Span R M H = \\<Inter>{K. submodule K R M \\<and> H \\<subseteq> K}\"\nproof\n  have \"submodule (Span R M H) R M \\<and> H \\<subseteq> Span R M H\"\n    by (simp add: assms SpanE(2) Span_is_submodule)\n  thus \"\\<Inter>{K. submodule K R M \\<and> H \\<subseteq> K} \\<subseteq> Span R M H\" by blast\nnext\n  have \"\\<And>K. submodule K R M \\<and> H \\<subseteq> K \\<Longrightarrow> Span R M H \\<subseteq> K\"\n    by (simp add: assms Span_min_submodule1)\n  thus \"Span R M H \\<subseteq> \\<Inter>{K. submodule K R M \\<and> H \\<subseteq> K}\" by blast\nqed\n\nlemma (in module) Span_idem :\n  assumes \"I \\<subseteq> carrier M\"\n  shows \"Span R M (Span R M I) = Span R M I\"\nproof\n  show \"Span R M I \\<subseteq> Span R M (Span R M I)\" using Span.incl by auto\n  show \"Span R M (Span R M I) \\<subseteq> Span R M I\"\n    using Span_min_submodule1[of \"Span R M I\" \"Span R M I\"] assms\n            Span_in_carrier Span_is_submodule[OF assms] by blast\nqed\n\nlemma (in module) Span_mono:\n  assumes \"I \\<subseteq> J\" \"J \\<subseteq> carrier M\"\n  shows \"Span R M I \\<subseteq> Span R M J\"\nproof-\n  have \"I \\<subseteq> Span R M J\"\n    using assms SpanE(2) by blast\n  thus \"Span R M I \\<subseteq> Span R M J\"\n    using Span_min_submodule1[of I \"Span R M J\"] assms Span_is_submodule[OF assms(2)]\n    by blast\nqed\n\nlemma (in module) elt_in_Span_imp_Span_idem :\n  assumes \"A \\<subseteq> carrier M\"\n    and \"x \\<in> Span R M A\"\n  shows \"Span R M (insert x A) = Span R M A\"\nproof\n  have x_M : \"x \\<in> carrier M\" using Span_in_carrier assms by auto\n  thus \"Span R M A \\<subseteq> Span R M (insert x A)\" using Span_mono[of A \"insert x A\"] assms by auto\n  have \"insert x A \\<subseteq> Span R M A\" using assms Span.incl by auto\n  hence \"Span R M (insert x A) \\<subseteq> Span R M (Span R M A)\"\n    using Span_mono[of \"insert x A\" \"Span R M A\"] assms Span.incl[of _ \"insert x A\" R M]\n          Span_in_carrier[OF assms(1)] by auto\n  thus \"Span R M (insert x A) \\<subseteq> Span R M A \"\n    using Span_idem[OF assms(1)] by auto\nqed\n\n\nlemma (in module) Span_union :\n  assumes \"Span R M I = Span R M J\"\n    and \"I \\<subseteq> carrier M\"\n    and \"J \\<subseteq> carrier M\"\n    and \"K \\<subseteq> carrier M\"\n  shows \"Span R M (I \\<union> K) = Span R M (J \\<union> K)\"\nproof-\n  {fix H L assume HL : \"H \\<subseteq> carrier M\" \"L \\<subseteq> carrier M\" \"Span R M H = Span R M L\"\n    have \"Span R M (H \\<union> K) \\<subseteq> Span R M (L \\<union> K)\"\n    proof-\n      have \"H \\<subseteq> Span R M L\" using HL Span.incl[of _ H R M] by auto\n      also have \"Span R M L \\<subseteq> Span R M (L \\<union> K)\" using Span_mono HL assms(4) by auto\n      finally have H : \"H \\<subseteq> Span R M (L \\<union> K)\" by simp\n      have \"K \\<subseteq> Span R M K\" using Span.incl by auto\n      also have \"Span R M K \\<subseteq> Span R M (L \\<union> K)\" using Span_mono HL(2) assms(4) by auto\n      finally have \"K \\<subseteq> Span R M (L \\<union> K)\" by simp\n      hence \"(H \\<union> K) \\<subseteq> Span R M (L \\<union> K)\"\n        using Span.incl[of _ H R M] H by auto\n      hence \"Span R M (H \\<union> K) \\<subseteq> Span R M (Span R M (L \\<union> K))\"\n        using Span_mono[of \"H \\<union> K\" \"Span R M (L \\<union> K)\"] Span_in_carrier HL(2) assms(4) by blast\n      thus \"Span R M (H \\<union> K) \\<subseteq> Span R M (L \\<union> K)\"\n        using Span_idem[of \"L \\<union> K\"] HL assms(4) by auto\n    qed}\n  thus \"Span R M (I \\<union> K) = Span R M (J \\<union> K)\" using assms by auto\nqed\n\nlemma (in module) submodule_gen_incl :\n  assumes \"submodule H R M\"\n    and  \"submodule K R M\"\n    and \"I \\<subseteq> H\"\n    and \"I \\<subseteq> K\"\n  shows \"Span R (M\\<lparr>carrier := K\\<rparr>) I \\<subseteq> Span R (M\\<lparr>carrier := H\\<rparr>) I\"\nproof\n  {fix J assume J_def : \"submodule J R M\" \"I \\<subseteq> J\"\n    have \"Span R (M \\<lparr>carrier := J\\<rparr>) I \\<subseteq> J\"\n      using module.Span_mono[of R \"(M\\<lparr>carrier := J\\<rparr>)\" I J ] submodule.submodule_is_module[OF J_def(1)]\n          module.Span_in_carrier[of R \"M\\<lparr>carrier := J\\<rparr>\"]  module_axioms J_def(2)\n      by auto}\n  note incl_HK = this\n  {fix x have \"x \\<in> Span R (M\\<lparr>carrier := K\\<rparr>) I \\<Longrightarrow> x \\<in> Span R (M\\<lparr>carrier := H\\<rparr>) I\" \n    proof (induction  rule : Span.induct)\n      case zero\n        have \"\\<zero>\\<^bsub>M\\<lparr>carrier := H\\<rparr>\\<^esub> \\<oplus>\\<^bsub>M\\<^esub> \\<zero>\\<^bsub>M\\<lparr>carrier := K\\<rparr>\\<^esub> = \\<zero>\\<^bsub>M\\<lparr>carrier := H\\<rparr>\\<^esub>\" by simp\n        moreover have \"\\<zero>\\<^bsub>M\\<lparr>carrier := H\\<rparr>\\<^esub> \\<oplus>\\<^bsub>M\\<^esub> \\<zero>\\<^bsub>M\\<lparr>carrier := K\\<rparr>\\<^esub> = \\<zero>\\<^bsub>M\\<lparr>carrier := K\\<rparr>\\<^esub>\" by simp\n        ultimately show ?case using assms Span.zero by metis\n    next\n      case (incl h) thus ?case using Span.incl by force\n    next\n      case (a_inv h)\n      note hyp = this\n      have \"a_inv (M\\<lparr>carrier := K\\<rparr>) h = a_inv M h\" \n        using assms group.m_inv_consistent[of \"add_monoid M\" K] a_comm_group incl_HK[of K] hyp\n        unfolding submodule_def comm_group_def a_inv_def  by auto\n      moreover have \"a_inv (M\\<lparr>carrier := H\\<rparr>) h = a_inv M h\"\n        using assms group.m_inv_consistent[of \"add_monoid M\" H] a_comm_group incl_HK[of H] hyp\n        unfolding submodule_def comm_group_def a_inv_def by auto\n      ultimately show ?case using Span.a_inv a_inv.IH by fastforce\n    next\n      case (eng_add h1 h2)\n      thus ?case using incl_HK assms Span.eng_add by force\n    next\n      case (eng_smult h1 h2)\n      thus ?case using Span.eng_smult by force\n    qed}\n  thus \"\\<And>x. x \\<in> Span R (M\\<lparr>carrier := K\\<rparr>) I \\<Longrightarrow> x \\<in> Span R (M\\<lparr>carrier := H\\<rparr>) I\"\n    by auto\nqed\n\nlemma (in module) submodule_gen_equality:\n  assumes \"submodule H R M\" \"K \\<subseteq> H\"\n  shows \"Span R M K = Span R (M \\<lparr> carrier := H \\<rparr>) K\"\n  using submodule_gen_incl[OF assms(1)carrier_is_submodule assms(2)] assms submoduleE(1)\n        submodule_gen_incl[OF carrier_is_submodule assms(1) _ assms(2)]\n  by force\n\nlocale vector_space = module + field R\n\n\ndefinition\ngenerator :: \"('a, 'b) ring_scheme \\<Rightarrow> ('a, 'c, 'd) module_scheme \\<Rightarrow> 'c set \\<Rightarrow> 'c set \\<Rightarrow> bool\"\n  where \"generator R M A K \\<equiv> A \\<subseteq> (carrier M) \\<and> Span R M A = K\"\n\ndefinition finite_dim :: \"('a, 'b) ring_scheme \\<Rightarrow> ('a, 'c, 'd) module_scheme \\<Rightarrow> 'c set \\<Rightarrow> bool\"\n  where \"finite_dim R M S \\<equiv> \\<exists> A. finite A \\<and> generator R M A S\"\n\nabbreviation lin_dep :: \"('a, 'b) ring_scheme \\<Rightarrow> ('a, 'c, 'd) module_scheme \\<Rightarrow> 'c set \\<Rightarrow> bool\"\n  where \"lin_dep R M A \\<equiv> A \\<subseteq> carrier M \\<and> (\\<exists> S. (S \\<subset> A) \\<and> Span R M S = Span R M A)\" \n\nabbreviation lin_indep :: \"('a, 'b) ring_scheme \\<Rightarrow> ('a, 'c, 'd) module_scheme \\<Rightarrow> 'c set \\<Rightarrow> bool\"\n  where \"lin_indep R M A \\<equiv> A \\<subseteq> carrier M \\<and> (\\<forall> S. (S \\<subset> A) \\<longrightarrow> Span R M S \\<subset> Span R M A)\"\n\ndefinition base :: \"('a, 'b) ring_scheme \\<Rightarrow> ('a, 'c, 'd) module_scheme \\<Rightarrow> 'c set \\<Rightarrow> 'c set \\<Rightarrow> bool\"\n  where \"base R M A K \\<equiv> lin_indep R M A \\<and> generator R M A K\"\n\ndefinition (in vector_space) dim :: \"'c set \\<Rightarrow> nat\"\n  where \"dim K \\<equiv> LEAST n. (\\<exists> A. finite A \\<and> card A = n  \\<and>  generator R M A K)\"\n\nlemma (in vector_space) lin_indep_not_dep:\n  assumes \"A \\<subseteq> carrier M\"\n  shows \"lin_dep R M A \\<longleftrightarrow> \\<not>lin_indep R M A\" \nproof\n  assume \"lin_dep R M A\"\n  hence \"\\<not> (\\<forall> S. (S \\<subset> A) \\<longrightarrow> Span R M S \\<subset> Span R M A)\" using assms\n    by blast\n  thus \"\\<not>lin_indep R M A\" by auto\nnext\n  assume \"\\<not> lin_indep R M A\"\n  from this obtain S where S_def : \"(S \\<subset> A)\" \"\\<not> (Span R M S \\<subset> Span R M A)\" using assms by blast\n  moreover have \"Span R M S \\<subseteq> Span R M A\" using S_def(1) Span_mono[of S A] assms by auto\n  ultimately show \"lin_dep R M A\" using assms  by blast\nqed\n\n\nlemma (in vector_space) zero_imp_dep :\n  assumes \"\\<zero>\\<^bsub>M\\<^esub> \\<in> A\"\n    and \"A \\<subseteq> carrier M\"\n  shows \"lin_dep R M A\" using assms(2)\nproof\n  have \"A - {\\<zero>\\<^bsub>M\\<^esub>} \\<subset> A\" using assms by auto\n  moreover have \"\\<zero>\\<^bsub>M\\<^esub> \\<in> Span R M (A - {\\<zero>\\<^bsub>M\\<^esub>})\" using Span.zero by auto\n  hence \"Span R M (A - {\\<zero>\\<^bsub>M\\<^esub>}) = Span R M A\"\n    using elt_in_Span_imp_Span_idem[of \"A - {\\<zero>\\<^bsub>M\\<^esub>}\" \"\\<zero>\\<^bsub>M\\<^esub>\"] assms\n    by (metis insert_Diff insert_subset)\n  ultimately show \"\\<exists>S\\<subset>A. Span R M S = Span R M A \" by auto\nqed\n\n\nlemma (in vector_space) h_in_finite_Span :\n  assumes \"A \\<subseteq> carrier M\" and \"h \\<in> Span R M A\"\n  shows \"\\<exists>S \\<subseteq> A. finite S \\<and> h \\<in> Span R M S\" using assms(2)\nproof (induction rule : Span.induct)\n  case zero\n  then show ?case\n    using Span.zero by auto \nnext\n  case (incl h)\n  then show ?case using Span.incl[of h \"{h}\"]\n    by auto\nnext\n  case (a_inv h)\n  then show ?case by (meson Span.a_inv)\nnext\n  case (eng_add h1 h2)\n  from this obtain S1 S2 where S1_def : \"S1 \\<subseteq>A \\<and> finite S1 \\<and> h1 \\<in> Span R M S1\"\n                and S2_def : \"S2 \\<subseteq> A \\<and> finite S2 \\<and> h2 \\<in> Span R M S2\" by auto\n  then show ?case\n    using Span.eng_add[of _ R M \"S1 \\<union> S2\"] Span_mono[of _ \"S1 \\<union> S2\"]assms Span_mono[of _ \"S1 \\<union> S2\"]\n    by (smt finite_UnI le_supI subsetCE subset_trans sup_ge1 sup_ge2)\nnext\n  case (eng_smult h1 h2)\n  then show ?case using Span.eng_smult[of h1 R h2 M] by auto\nqed\n\nlemma (in vector_space) linear_combinations_finite_incl :\n  assumes \"finite A\" and \"A \\<subseteq> carrier M\" \n  shows \"h \\<in> Span R M A \\<Longrightarrow> h \\<in> { \\<Oplus>\\<^bsub>M\\<^esub>s \\<in> A. (f s) \\<odot>\\<^bsub>M\\<^esub>  s | f. f: A \\<rightarrow> carrier R }\"\nproof (induction rule : Span.induct)\n  have \"\\<And>v. v \\<in> A \\<Longrightarrow> (\\<lambda>v. \\<zero>) v \\<odot>\\<^bsub>M\\<^esub> v = \\<zero>\\<^bsub>M\\<^esub>\" using assms smult_l_null by auto\n  hence sum_zero : \"(\\<Oplus>\\<^bsub>M\\<^esub>i\\<in>A. \\<zero>\\<^bsub>M\\<^esub>) = (\\<Oplus>\\<^bsub>M\\<^esub>v\\<in>A. ((\\<lambda>v. \\<zero>) v) \\<odot>\\<^bsub>M\\<^esub> v) \"\n  proof (induct A rule: infinite_finite_induct)\n    case (infinite A)\n    then show ?case using assms by auto\n  next\n    case empty\n    then show ?case by auto\n  next\n    case (insert x F)\n    then show ?case by (metis M.finsum_cong' Pi_I M.zero_closed)\n  qed\n  case zero\n  have \"(\\<lambda>v. \\<zero>) \\<in> A \\<rightarrow> carrier R\" by auto\n  thus ?case\n    using finsum_zero sum_zero by auto\nnext\n  case (incl h)\n  note hyp = this\n  have \"(\\<lambda>x. ((\\<lambda>v. if v = h then \\<one> else \\<zero>) x) \\<odot>\\<^bsub>M\\<^esub> x) \\<in> A \\<rightarrow> carrier M\"\n    using smult_closed assms by auto\n  moreover have \"(if h = h then \\<one> else \\<zero>) \\<odot>\\<^bsub>M\\<^esub> h \\<in> carrier M\"\n    using assms smult_closed one_closed hyp by auto\n  moreover have null : \"\\<And>x. x\\<in> (A - {h}) \\<Longrightarrow> (\\<lambda>v. if v = h then \\<one> else \\<zero>) x = (\\<lambda>v. \\<zero>) x\" by auto\n  hence \"\\<And>x. x\\<in> (A - {h}) \\<Longrightarrow> (\\<lambda>y. ((\\<lambda>v. if v = h then \\<one> else \\<zero>) y) \\<odot>\\<^bsub>M\\<^esub> y) x = (\\<lambda>v. \\<zero>\\<^bsub>M\\<^esub>) x\"\n    using smult_l_null assms by auto\n  hence \"(\\<Oplus>\\<^bsub>M\\<^esub>v\\<in>(A - {h}). ((\\<lambda>v. if v = h then \\<one> else \\<zero>) v) \\<odot>\\<^bsub>M\\<^esub> v) = \\<zero>\\<^bsub>M\\<^esub>\"\n    using  M.finsum_cong'[of \"A - {h}\" \"A - {h}\" \"\\<lambda>x. ((\\<lambda>v. if v = h then \\<one> else \\<zero>) x) \\<odot>\\<^bsub>M\\<^esub> x\"\n           \"\\<lambda>v. \\<zero>\\<^bsub>M\\<^esub>\"] finsum_zero[of \"A - {h}\"]\n    by (metis (no_types, lifting) M.zero_closed Pi_I)\n  ultimately  have \"(\\<Oplus>\\<^bsub>M\\<^esub>v\\<in>A. ((\\<lambda>v. if v = h then \\<one> else \\<zero>) v) \\<odot>\\<^bsub>M\\<^esub> v) = h\"\n    using finsum_insert[of \"A - {h}\" h \"\\<lambda>x. ((\\<lambda>v. if v = h then \\<one> else \\<zero>) x) \\<odot>\\<^bsub>M\\<^esub> x\"]\n    by (smt M.r_zero Pi_split_insert_domain assms finite_Diff incl.hyps insert_Diff null\n        smult_one subsetCE zero_not_one)\n  moreover have \"(\\<lambda>v. if v = h then \\<one> else \\<zero>) \\<in> A \\<rightarrow> carrier R\" by auto\n  ultimately have  \"(\\<lambda>v. if v = h then \\<one> else \\<zero>) \\<in> A \\<rightarrow> carrier R \\<and>\n                    h = (\\<Oplus>\\<^bsub>M\\<^esub>v\\<in>A. (\\<lambda>v. if v = h then \\<one> else \\<zero>) v \\<odot>\\<^bsub>M\\<^esub> v)\"  using hyp by auto\n  thus ?case by fastforce\n  next\n    case (a_inv h)\n    note hyp = this\n    from this obtain a where a_def : \"a \\<in> A \\<rightarrow> carrier R\" \" h = (\\<Oplus>\\<^bsub>M\\<^esub>v\\<in>A. a v \\<odot>\\<^bsub>M\\<^esub> v)\" by auto\n  define f where f_def : \"f =(\\<lambda>v. \\<ominus> \\<one> \\<otimes> a v)\"\n  have \" (\\<Oplus>\\<^bsub>M\\<^esub>v\\<in>A. (\\<ominus> \\<one>) \\<odot>\\<^bsub>M\\<^esub> ((a v) \\<odot>\\<^bsub>M\\<^esub> v)) = (\\<ominus>\\<one>) \\<odot>\\<^bsub>M\\<^esub> h\"\n    using module.finsum_smult_ldistr[OF module_axioms assms(1), of \"(\\<ominus>\\<one>)\" \"\\<lambda>v. a v \\<odot>\\<^bsub>M\\<^esub> v\"] a_def\n    by (smt Pi_def R.add.inv_closed assms(2) mem_Collect_eq one_closed smult_closed subsetCE)\n  also have \"... = \\<ominus>\\<^bsub>M\\<^esub> h\"\n    using smult_l_minus smult_one Span_in_carrier hyp assms by auto\n  finally have \"(\\<Oplus>\\<^bsub>M\\<^esub>v\\<in>A. (\\<ominus> \\<one>) \\<odot>\\<^bsub>M\\<^esub> ((a v) \\<odot>\\<^bsub>M\\<^esub> v)) =  \\<ominus>\\<^bsub>M\\<^esub> h\" by auto\n  moreover have \"\\<And>v. v \\<in> A \\<Longrightarrow> (\\<ominus> \\<one>) \\<odot>\\<^bsub>M\\<^esub> ((a v) \\<odot>\\<^bsub>M\\<^esub> v) =  (f v \\<odot>\\<^bsub>M\\<^esub> v) \"\n    using one_closed a_def assms(2) unfolding f_def\n    by (metis (no_types, lifting) PiE R.add.inv_closed smult_assoc1 subsetCE)\n  hence \"(\\<Oplus>\\<^bsub>M\\<^esub>v\\<in>A. (\\<ominus> \\<one>) \\<odot>\\<^bsub>M\\<^esub> ((a v) \\<odot>\\<^bsub>M\\<^esub> v)) = (\\<Oplus>\\<^bsub>M\\<^esub>v\\<in>A. (f v \\<odot>\\<^bsub>M\\<^esub> v))\"\n    using M.finsum_cong'[of A A \"\\<lambda>v. \\<ominus> \\<one> \\<odot>\\<^bsub>M\\<^esub> (a v \\<odot>\\<^bsub>M\\<^esub> v)\" \"\\<lambda>v. (f v \\<odot>\\<^bsub>M\\<^esub> v)\"]\n           smult_closed a_def one_closed R.add.inv_closed unfolding f_def\n    by (smt PiE Pi_I assms(2) subsetCE)\n  ultimately have \"(\\<Oplus>\\<^bsub>M\\<^esub>v\\<in>A. f v \\<odot>\\<^bsub>M\\<^esub> v) = \\<ominus>\\<^bsub>M\\<^esub> h\" by auto\n  moreover have \"f \\<in> A \\<rightarrow> carrier R\"\n    using f_def a_def(1) m_closed[of \"\\<ominus> \\<one>\"] R.add.inv_closed[OF one_closed]\n    by blast\n  ultimately show ?case\n    using Pi_iff by fastforce\nnext\n  case (eng_add h1 h2)\n  note hyp = this\n  from hyp obtain a1 where a1_def : \"a1 \\<in> A \\<rightarrow> carrier R\" \"h1 = (\\<Oplus>\\<^bsub>M\\<^esub>v\\<in>A. a1 v \\<odot>\\<^bsub>M\\<^esub> v)\" by auto\n  hence a1_M : \"(\\<lambda>v. a1 v \\<odot>\\<^bsub>M\\<^esub> v) \\<in> A \\<rightarrow> carrier M\"\n    using smult_closed assms by blast\n  from hyp obtain a2 where a2_def : \"a2 \\<in> A \\<rightarrow> carrier R\" \"h2 = (\\<Oplus>\\<^bsub>M\\<^esub>v\\<in>A. a2 v \\<odot>\\<^bsub>M\\<^esub> v)\" by auto\n  hence a2_M : \"(\\<lambda>v. a2 v \\<odot>\\<^bsub>M\\<^esub> v) \\<in> A \\<rightarrow> carrier M\"\n    using smult_closed assms by blast\n  define f where f_def : \"f =(\\<lambda>v. (a1 v \\<oplus> a2 v))\"\n  from this have fprop : \"f \\<in> A \\<rightarrow> carrier R\" using a1_def a2_def R.a_closed by auto\n  hence f_M : \"(\\<lambda>v. f v \\<odot>\\<^bsub>M\\<^esub> v) \\<in> A \\<rightarrow> carrier M\"\n    using smult_closed assms(2) by blast\n  moreover have \"\\<And>i. i \\<in> A \\<Longrightarrow> (a1 i \\<odot>\\<^bsub>M\\<^esub> i \\<oplus>\\<^bsub>M\\<^esub> a2 i \\<odot>\\<^bsub>M\\<^esub> i) = (f i \\<odot>\\<^bsub>M\\<^esub> i) \"\n    unfolding f_def using smult_l_distr a1_def a2_def assms(2)\n    by (smt Pi_iff restrict_ext subsetCE) \n  hence \"(\\<Oplus>\\<^bsub>M\\<^esub>v\\<in>A. f v \\<odot>\\<^bsub>M\\<^esub> v) = (\\<Oplus>\\<^bsub>M\\<^esub>v\\<in>A. a1 v \\<odot>\\<^bsub>M\\<^esub> v \\<oplus>\\<^bsub>M\\<^esub> a2 v \\<odot>\\<^bsub>M\\<^esub> v)\"\n    by (metis (mono_tags, lifting) M.finsum_cong' f_M)\n  moreover have \"(\\<Oplus>\\<^bsub>M\\<^esub>v\\<in>A. a1 v \\<odot>\\<^bsub>M\\<^esub> v \\<oplus>\\<^bsub>M\\<^esub> a2 v \\<odot>\\<^bsub>M\\<^esub> v) =\n                 (\\<Oplus>\\<^bsub>M\\<^esub>v\\<in>A. a1 v \\<odot>\\<^bsub>M\\<^esub> v) \\<oplus>\\<^bsub>M\\<^esub> (\\<Oplus>\\<^bsub>M\\<^esub>v\\<in>A. a2 v \\<odot>\\<^bsub>M\\<^esub> v)\"\n    using finsum_addf[OF a1_M a2_M ] restrict_Pi_cancel by auto\n  ultimately have \"(\\<Oplus>\\<^bsub>M\\<^esub>v\\<in>A. f v \\<odot>\\<^bsub>M\\<^esub> v) = (\\<Oplus>\\<^bsub>M\\<^esub>v\\<in>A. a1 v \\<odot>\\<^bsub>M\\<^esub> v) \\<oplus>\\<^bsub>M\\<^esub> (\\<Oplus>\\<^bsub>M\\<^esub>v\\<in>A. a2 v \\<odot>\\<^bsub>M\\<^esub> v)\"\n    by auto\n  hence \"(\\<Oplus>\\<^bsub>M\\<^esub>v\\<in>A. f v \\<odot>\\<^bsub>M\\<^esub> v) = h1 \\<oplus>\\<^bsub>M\\<^esub> h2\" using a1_def a2_def by auto\n  then show ?case\n    using fprop Pi_iff by fastforce\nnext\n  case (eng_smult h1 h2)\n  note hyp = this\n  from this obtain a where a_def : \" a \\<in> A \\<rightarrow> carrier R\" \"h2 = (\\<Oplus>\\<^bsub>M\\<^esub>v\\<in>A. a v \\<odot>\\<^bsub>M\\<^esub> v)\" by auto\n  hence a_M : \"(\\<lambda>v. a v \\<odot>\\<^bsub>M\\<^esub> v) \\<in> A \\<rightarrow> carrier M\"\n    using smult_closed assms by blast\n  hence \"h1 \\<odot>\\<^bsub>M\\<^esub> h2 = (\\<Oplus>\\<^bsub>M\\<^esub>v\\<in>A. h1 \\<odot>\\<^bsub>M\\<^esub> (a v \\<odot>\\<^bsub>M\\<^esub> v))\"\n    using finsum_smult_ldistr[OF assms(1) hyp(1) a_M] a_def(2) by blast\n  moreover have \"\\<And>v. v \\<in> A \\<Longrightarrow> h1 \\<odot>\\<^bsub>M\\<^esub> (a v \\<odot>\\<^bsub>M\\<^esub> v) = ((h1 \\<otimes> a v) \\<odot>\\<^bsub>M\\<^esub> v)\"\n    using smult_assoc1[OF hyp(1)] a_def(1) assms(2)\n    by (simp add: Pi_iff subset_eq) \n  hence \"(\\<Oplus>\\<^bsub>M\\<^esub>v\\<in>A. h1 \\<odot>\\<^bsub>M\\<^esub> (a v \\<odot>\\<^bsub>M\\<^esub> v)) = (\\<Oplus>\\<^bsub>M\\<^esub>v\\<in>A. ((h1 \\<otimes> a v) \\<odot>\\<^bsub>M\\<^esub> v))\"\n    using finsum_cong'[of A A] a_M\n    by (smt Pi_iff local.eng_smult(1) smult_closed)\n  ultimately have \"h1 \\<odot>\\<^bsub>M\\<^esub> h2 = (\\<Oplus>\\<^bsub>M\\<^esub>v\\<in>A. h1 \\<otimes> a v \\<odot>\\<^bsub>M\\<^esub> v)\" by auto\n  moreover have \"(\\<lambda>v. h1 \\<otimes> a v) \\<in> A \\<rightarrow> carrier R\"\n    using a_def(1) smult_closed m_closed hyp assms\n    by fastforce \n  ultimately show ?case by auto\nqed\n\nlemma (in vector_space) linear_combinations_incl :\n  assumes \"A \\<subseteq> carrier M\"\n  shows \"Span R M A  \\<subseteq> { \\<Oplus>\\<^bsub>M\\<^esub>s \\<in> S. (a s) \\<odot>\\<^bsub>M\\<^esub>  s | a S. a \\<in> S \\<rightarrow> carrier R \\<and> finite S \\<and> S \\<subseteq> A}\"\nproof\n  fix h assume h_def : \"h \\<in> Span R M A\"\n  obtain S where S_def : \"S \\<subseteq> A\" \"finite S\" \"h \\<in> Span R M S\"\n    using h_in_finite_Span[OF assms h_def] by auto\n  from this obtain a where a_def : \" a \\<in> S \\<rightarrow> carrier R \\<and> ( h = (\\<Oplus>\\<^bsub>M\\<^esub>v\\<in>S. a v \\<odot>\\<^bsub>M\\<^esub> v))\"\n    using linear_combinations_finite_incl[OF S_def(2) _ S_def(3)] assms S_def by auto\n  thus \" h \\<in> {\\<Oplus>\\<^bsub>M\\<^esub>s \\<in> S. (a s) \\<odot>\\<^bsub>M\\<^esub>  s | a S. a \\<in> S \\<rightarrow> carrier R \\<and> finite S \\<and> S \\<subseteq> A}\"\n    using S_def by auto\nqed\n\n\nlemma (in vector_space) linear_combinations_finite_incl2 :\n  assumes \"finite A\" and \"A \\<subseteq> carrier M\" \n  shows \"{ \\<Oplus>\\<^bsub>M\\<^esub>s \\<in> A. (a s) \\<odot>\\<^bsub>M\\<^esub>  s | a. a: A \\<rightarrow> carrier R } \\<subseteq>  Span R M A\"\n        (is \" { ?sum M A a  |a. a \\<in> ?A_to_R } \\<subseteq> Span R M A \")\nproof\n  fix x assume x_def : \"x \\<in> {\\<Oplus>\\<^bsub>M\\<^esub>s\\<in>A. a s \\<odot>\\<^bsub>M\\<^esub> s |a. a \\<in> A \\<rightarrow> carrier R}\"\n  from this obtain a where a_def : \"a \\<in> ?A_to_R\" \"x = ?sum M A a\" by auto\n  show \"x \\<in> Span R M A\" using assms a_def\n  proof (induction A arbitrary : x a)\n    case empty\n    then show ?case using finsum_empty Span.zero[of M R \"{}\"]\n      by simp \n  next\n    case (insert xa F)\n    define y z where y_def : \"y = ?sum M F a\" and z_def : \"z = a xa \\<odot>\\<^bsub>M\\<^esub> xa\"\n    from insert(5) have \"a \\<in> F \\<rightarrow> carrier R \" by auto\n    hence \"y \\<in> Span R M F\" using y_def insert by auto\n    hence \"y \\<in> Span R M (insert xa F)\" using Span_mono insert by blast \n    moreover have \"z \\<in> Span R M (insert xa F)\"\n      using Span.eng_smult Span.incl[of xa \"insert xa F\" R M] insert(5) z_def  by auto\n    moreover have \"x = y \\<oplus>\\<^bsub>M\\<^esub> z\"\n      unfolding y_def z_def using insert finsum_insert[OF insert(1)insert(2)]\n      by (simp add: M.add.m_comm Pi_iff subset_eq)\n    ultimately show ?case using Span.eng_add[of y R M \"insert xa F\" z] by auto\n  qed\nqed\n\nlemma (in vector_space) linear_combinations_incl2 :\n  assumes \"A \\<subseteq> carrier M\" \n  shows \"{ \\<Oplus>\\<^bsub>M\\<^esub>s \\<in> S. (a s) \\<odot>\\<^bsub>M\\<^esub>  s | a S. a \\<in> S \\<rightarrow> carrier R \\<and> finite S \\<and> S \\<subseteq> A } \\<subseteq>  Span R M A\"\n        (is \" ?X \\<subseteq> Span R M A \")\nproof\n  fix h assume h_def : \"h \\<in> ?X\"\n  obtain S a where S_a : \"S \\<subseteq> A\" \"finite S\" \"h = (\\<Oplus>\\<^bsub>M\\<^esub>s \\<in> S. (a s) \\<odot>\\<^bsub>M\\<^esub>  s)\" \"a \\<in> S \\<rightarrow> carrier R\"\n    using h_def by blast\n  have \"h \\<in> { \\<Oplus>\\<^bsub>M\\<^esub>s \\<in> S. (a s) \\<odot>\\<^bsub>M\\<^esub>  s | a. a \\<in> S \\<rightarrow> carrier R}\"\n    using S_a by auto\n  hence \"h \\<in> Span R M S\" using linear_combinations_finite_incl2 assms S_a by blast\n  thus \"h \\<in> Span R M A\" using Span_mono S_a assms by blast\nqed\n\nproposition (in vector_space) Span_as_linear_combinations :\n  assumes \"A \\<subseteq> carrier M\"\n  shows \"{ \\<Oplus>\\<^bsub>M\\<^esub>s \\<in> S. (a s) \\<odot>\\<^bsub>M\\<^esub>  s | a S. a \\<in> S \\<rightarrow> carrier R \\<and> finite S \\<and> S \\<subseteq> A } = Span R M A\"\n  using linear_combinations_incl2 linear_combinations_incl assms\n  by blast\n\nlemma (in vector_space) lin_indep_trunc :\n  assumes \"lin_indep R M A\"\n  shows \"lin_indep R M (A - K)\"\nproof-\n  {\n  fix K assume K_def : \"K \\<subseteq> A\"\n  have \"lin_indep R M (A - K)\"\n  proof (rule ccontr)\n    assume \"\\<not> lin_indep R M (A - K)\"\n    from this have dep : \"lin_dep R M (A - K)\"\n      using lin_indep_not_dep[of \"A - K\"] assms by auto\n    from this obtain S where S_def : \"(S \\<subset> (A - K))\"  \"Span R M S = Span R M (A - K)\"\n      by auto\n    hence \"(S \\<union> K) \\<subset> A\" using K_def by auto\n    moreover have \"Span R M (S \\<union> K) = Span R M ((A - K) \\<union> K)\"\n      using Span_union[OF S_def(2)] S_def assms K_def dep by auto\n    hence \"Span R M (S \\<union> K) = Span R M A\"\n      by (simp add: K_def Un_absorb2) \n    ultimately show False using assms\n      by (metis psubsetE)\n  qed}\n  note aux_lemma = this\n  show ?thesis\n  proof (cases \"K \\<subseteq> A\")\n    case True\n    thus ?thesis using aux_lemma by auto\n  next\n    case False\n   have \"A - K = A - (A \\<inter> K)\" using False by auto\n   thus ?thesis using aux_lemma[of \"A \\<inter> K\"] by auto\n qed\nqed\n\ncorollary (in vector_space) lin_indep_incl :\n  assumes \"lin_indep R M A\"\n    and \"S \\<subseteq> A\"\n  shows \"lin_indep R M S\"\n  using lin_indep_trunc[OF assms(1), of \"A - S\"] assms\n  by (simp add: double_diff)\n\nlemma (in vector_space) vector_in_Span_imp_dep :\n  assumes \"A \\<subseteq> carrier M\"\n    and \"x \\<in> Span R M A\"\n    and \"x \\<notin> A\"\n  shows \"lin_dep R M (insert x A)\"\nproof\n  show \"insert x A \\<subseteq> carrier M\"\n    using assms(1) Span_in_carrier[OF assms(1-2)] by simp\n  have \"Span R M A = Span R M (insert x A)\"\n    using elt_in_Span_imp_Span_idem[OF assms(1-2)] by auto\n  thus \"\\<exists>S\\<subset>insert x A. Span R M S = Span R M (insert x A)\" using assms by auto\nqed\n\nlemma (in vector_space) add_vector_lin_dep :\n  assumes \"lin_indep R M A\"\n    and \"x \\<in> carrier M\"\n    and \"S \\<subset> (insert x A)\"\n    and \"S \\<inter> A \\<subset> A\"\n    and \"Span R M S = Span R M (insert x A)\"\n  shows \"x \\<in> S\"\nproof (rule ccontr)\n  assume \"x \\<notin> S\"\n  hence S_incl : \"S \\<subset> A \"using assms by auto\n  hence \"Span R M S \\<subseteq> Span R M A\" using Span_mono[of S A] assms by auto\n  hence \"Span R M (insert x A) \\<subseteq> Span R M A\" using assms by auto\n  moreover have \"Span R M A \\<subseteq> Span R M (insert x A)\"\n    using Span_mono[of A \"insert x A\"] assms by auto\n  ultimately have \"Span R M A = Span R M (insert x A)\" by auto\n  thus False using S_incl assms(5) assms(1) by blast\nqed\n\nlemma (in vector_space) not_in_every_Span :\n  assumes \"lin_indep R M A\"\n    and \"x \\<in> Span R M A\"\n    and \"x \\<noteq> \\<zero>\\<^bsub>M\\<^esub>\"\n  shows \"\\<exists> S. S \\<subseteq> A \\<and> x \\<notin> Span R M S\"\nproof\n  have \"{} \\<subseteq> A\" by auto\n  moreover have \"Span R M {} \\<subseteq> {\\<zero>\\<^bsub>M\\<^esub>}\"\n  proof\n    fix x assume \"x \\<in> Span R M {}\"\n    from this show \"x \\<in> {\\<zero>\\<^bsub>M\\<^esub>}\" apply (induction x rule : Span.induct) by simp_all\n  qed\n  hence \"x \\<notin> Span R M {}\" using assms by auto\n  ultimately show \"{} \\<subseteq> A \\<and> x \\<notin> Span R M {}\" by auto\nqed\n\nlemma (in vector_space) not_in_Span_imp_no_Span_inter :\n  assumes \"A \\<subseteq> carrier M\"\n    and \"x \\<in> carrier M\"\n    and \"x \\<notin> Span R M A\"\n  shows \"(Span R M A) \\<inter> (Span R M {x}) = {\\<zero>\\<^bsub>M\\<^esub>} \"\nproof\n  have \"{\\<zero>\\<^bsub>M\\<^esub>} \\<subseteq> Span R M A\" using Span.zero by auto\n  moreover have \"{\\<zero>\\<^bsub>M\\<^esub>} \\<subseteq> Span R M {x}\" using Span.zero by auto\n  ultimately show \"{\\<zero>\\<^bsub>M\\<^esub>} \\<subseteq> Span R M A \\<inter> Span R M {x}\" by auto\n  show \"Span R M A \\<inter> Span R M {x} \\<subseteq> {\\<zero>\\<^bsub>M\\<^esub>}\"\n  proof (rule ccontr)\n    assume \"\\<not> Span R M A \\<inter> Span R M {x} \\<subseteq> {\\<zero>\\<^bsub>M\\<^esub>}\"\n    hence \"\\<exists> y. y \\<in> Span R M A \\<inter> Span R M {x} \\<and> y \\<notin> {\\<zero>\\<^bsub>M\\<^esub>}\" by auto\n    from this obtain y where y_def : \"y \\<in> Span R M A \\<inter> Span R M {x} \\<and> y \\<notin> {\\<zero>\\<^bsub>M\\<^esub>}\" by auto\n    hence not_zero : \"y \\<noteq> \\<zero>\\<^bsub>M\\<^esub>\" by auto\n    have \"y \\<in> {k \\<odot>\\<^bsub>M\\<^esub> x | k. k \\<in> carrier R}\"\n      using Span_singleton assms y_def by auto\n    from this obtain k where k_def : \"k \\<in> carrier R\" \"k \\<odot>\\<^bsub>M\\<^esub> x = y\" by blast\n    have \"k \\<odot>\\<^bsub>M\\<^esub> x \\<in> Span R M A\" using y_def k_def by auto\n    moreover have \"k \\<noteq> \\<zero>\" using k_def(2) not_zero smult_l_null y_def assms(2) by auto\n    hence inv_R : \"inv k \\<in> carrier R\"\n      by (simp add: k_def(1) local.field_Units)\n    ultimately have \"inv k \\<odot>\\<^bsub>M\\<^esub> (k \\<odot>\\<^bsub>M\\<^esub> x) \\<in> Span R M A\"\n      using Span.eng_smult[of \"inv k\" R \"k \\<odot>\\<^bsub>M\\<^esub> x\" M A] by auto\n    hence \"(inv k \\<otimes> k) \\<odot>\\<^bsub>M\\<^esub> x \\<in> Span R M A\"\n      using smult_assoc1[of \"inv k\" k x] using k_def\n      by (simp add: inv_R assms(2))\n    hence \"x \\<in> Span R M A\"\n      by (simp add: \\<open>k \\<noteq> \\<zero>\\<close> assms(2) k_def(1) local.field_Units)\n    thus False using assms by auto\n  qed\nqed\n      \nlemma (in vector_space) vector_indep :\n  assumes \"x \\<in> carrier M\"\n    and \"x \\<noteq> \\<zero>\\<^bsub>M\\<^esub>\"\n  shows \"lin_indep R M {x}\"\nproof\n  show \"{x} \\<subseteq> carrier M\" using assms by auto\n  show \"\\<forall>S\\<subset>{x}. Span R M S \\<subset> Span R M {x}\"\n  proof-\n    {fix S assume S_def : \"S \\<subset> {x}\" have \"Span R M S \\<subset> Span R M {x}\"\n      proof-\n        from S_def have S_empty : \"S = {}\" by auto\n        hence \"S \\<subseteq> {\\<zero>\\<^bsub>M\\<^esub>}\" by auto\n        moreover have \"Span R M {\\<zero>\\<^bsub>M\\<^esub>} = {k \\<odot>\\<^bsub>M\\<^esub> \\<zero>\\<^bsub>M\\<^esub> |k. k \\<in> carrier R}\"\n          using Span_singleton[OF M.zero_closed] by auto\n        moreover have \"{k \\<odot>\\<^bsub>M\\<^esub> \\<zero>\\<^bsub>M\\<^esub> |k. k \\<in> carrier R} \\<subseteq> {\\<zero>\\<^bsub>M\\<^esub>}\" using smult_r_null\n          by blast\n        ultimately have \"Span R M S \\<subseteq> {\\<zero>\\<^bsub>M\\<^esub>}\"\n          using Span_mono[of S \"{\\<zero>\\<^bsub>M\\<^esub>}\"] M.zero_closed by blast\n        moreover have \"x \\<in> Span R M {x}\" using Span.incl[of x] by auto\n        ultimately show \"Span R M S \\<subset> Span R M {x}\" using assms\n          using Span_mono S_empty by blast\n      qed}\n    thus \"\\<forall>S\\<subset>{x}. Span R M S \\<subset> Span R M {x}\" by blast\n  qed\nqed\n\n\nlemma (in vector_space) vector_decomposition :\n  assumes \"A \\<subseteq> carrier M\"\n    and \"B \\<subseteq> carrier M\"\n    and \"x \\<in> Span R M (A \\<union> B)\"\n  shows \"\\<exists> x1 x2. x1 \\<in> Span R M A \\<and> x2 \\<in> Span R M B \\<and> x1 \\<oplus>\\<^bsub>M\\<^esub> x2 = x\" using assms(3)\nproof (induction rule : Span.induct)\n  case zero\n  then show ?case using Span.zero M.r_zero by blast\nnext\n  case (incl h)\n  then show ?case \n  proof\n    assume \"h \\<in> A\"\n    thus ?case using M.r_zero[of h] Span.incl[of h A R M] Span.zero[of M R B] assms by blast\n  next\n    assume \"h \\<in> B\"\n    thus ?case using M.l_zero[of h] Span.incl[of h B R M] Span.zero[of M R A] assms by blast\n  qed\nnext\n  case (a_inv h)\n  from this obtain x1 x2 where x1x2 : \"x1 \\<in> Span R M A\" \"x2 \\<in> Span R M B\" \"x1 \\<oplus>\\<^bsub>M\\<^esub> x2 = h\" by auto\n  hence \"\\<ominus>\\<^bsub>M\\<^esub> x1 \\<in> Span R M A\"\n    using smult_l_minus[of \"\\<one>\" x1] assms(1) smult_one[of x1] by (simp add: Span.a_inv)\n  moreover have \"\\<ominus>\\<^bsub>M\\<^esub> x2 \\<in> Span R M B\"\n    using Span.a_inv x1x2 by auto\n  moreover have \"\\<ominus>\\<^bsub>M\\<^esub> x1 \\<oplus>\\<^bsub>M\\<^esub> \\<ominus>\\<^bsub>M\\<^esub> x2 = \\<ominus>\\<^bsub>M\\<^esub> h\"\n    using x1x2 a_inv(1) smult_l_minus[of \"\\<one>\" \"x1 \\<oplus>\\<^bsub>M\\<^esub> x2\" ] smult_r_distr[of \"\\<one>\" x1 x2]\n         Span_in_carrier[OF assms(1) x1x2(1)] Span_in_carrier[OF assms(2) x1x2(2)]\n    using M.minus_add by auto\n  ultimately show ?case  by auto\nnext\n  case (eng_add h1 h2)\n  from this obtain x1 x2 where x1x2 : \"x1 \\<in> Span R M A\" \"x2 \\<in> Span R M B\" \"x1 \\<oplus>\\<^bsub>M\\<^esub> x2 = h1\"\n    by auto\n  from eng_add obtain y1 y2 where y1y2 : \"y1 \\<in> Span R M A\" \"y2 \\<in> Span R M B\" \"y1 \\<oplus>\\<^bsub>M\\<^esub> y2 = h2\"\n    by auto\n  have \"h1 \\<oplus>\\<^bsub>M\\<^esub> h2 = x1 \\<oplus>\\<^bsub>M\\<^esub> x2 \\<oplus>\\<^bsub>M\\<^esub> y1 \\<oplus>\\<^bsub>M\\<^esub> y2\"\n    using x1x2 y1y2 assms Span_in_carrier M.add.m_assoc by auto \n  also have \"... = x1 \\<oplus>\\<^bsub>M\\<^esub> y1 \\<oplus>\\<^bsub>M\\<^esub> x2 \\<oplus>\\<^bsub>M\\<^esub> y2\"\n    using x1x2 y1y2 assms Span_in_carrier M.add.m_comm M.add.m_lcomm by auto\n  finally have \"h1 \\<oplus>\\<^bsub>M\\<^esub> h2 =  (x1 \\<oplus>\\<^bsub>M\\<^esub> y1) \\<oplus>\\<^bsub>M\\<^esub> (x2 \\<oplus>\\<^bsub>M\\<^esub> y2)\"\n    using x1x2 y1y2 assms Span_in_carrier M.add.m_assoc by auto\n  moreover have \"(x1 \\<oplus>\\<^bsub>M\\<^esub> y1) \\<in> Span R M A\" using x1x2 y1y2 Span.eng_add by auto\n  moreover have \"(x2 \\<oplus>\\<^bsub>M\\<^esub> y2) \\<in> Span R M B\" using x1x2 y1y2 Span.eng_add by auto\n  ultimately show ?case by auto\nnext\n  case (eng_smult h1 h2)\n  then show ?case using smult_r_distr[of h1] Span_in_carrier assms\n    by (metis Span.intros(5))\nqed\n\n\nlemma (in vector_space) two_vectors_exchange_Span :\n  assumes \"A \\<subseteq> carrier M\"\n    and \"x \\<in> carrier M\"\n    and \"y \\<in> Span R M (insert x A)\"\n    and \"y \\<notin> Span R M A\"\n  shows \"x \\<in> Span R M (insert y A)\"\nproof-\n  have \"\\<exists> x1 x2. x1 \\<in> Span R M A \\<and> x2 \\<in> Span R M {x} \\<and> x1 \\<oplus>\\<^bsub>M\\<^esub> x2 = y\"\n    using vector_decomposition[of A \"{x}\" y] assms by auto\n  from this obtain x1 x2 where x1x2 : \"x1 \\<in> Span R M A \\<and> x2 \\<in> Span R M {x} \\<and> x1 \\<oplus>\\<^bsub>M\\<^esub> x2 = y\"\n    by auto\n  have not_null : \"x2 \\<noteq> \\<zero>\\<^bsub>M\\<^esub>\"\n  proof\n    assume x_zero : \"x2 = \\<zero>\\<^bsub>M\\<^esub>\"\n    hence \"y = x1\" using x1x2 M.r_zero assms Span_in_carrier by auto\n    thus False using assms x1x2 by auto\n  qed\n  moreover have \"x2 \\<in> {k \\<odot>\\<^bsub>M\\<^esub> x | k. k \\<in> carrier R}\"\n    using Span_singleton x1x2 assms by auto\n  from this obtain k where k_def : \"k \\<in> carrier R\" \"x2 = k \\<odot>\\<^bsub>M\\<^esub> x\" by auto\n  hence k_prop : \"k \\<noteq> \\<zero>\"\n    using not_null smult_l_null[of x2] x1x2 Span_in_carrier assms by auto \n  ultimately have \"inv k \\<odot>\\<^bsub>M\\<^esub>(\\<ominus>\\<^bsub>M\\<^esub> x1 \\<oplus>\\<^bsub>M\\<^esub> y) = inv k \\<odot>\\<^bsub>M\\<^esub>\\<ominus>\\<^bsub>M\\<^esub> x1 \\<oplus>\\<^bsub>M\\<^esub> inv k \\<odot>\\<^bsub>M\\<^esub> y\"\n    using smult_r_distr[of \"inv k\" x1 y] using assms Span_in_carrier x1x2 k_def field_Units\n    by (metis Diff_iff M.add.inv_closed M.add.m_closed Units_inv_closed module.smult_closed\n        module.smult_r_distr module_axioms singletonD)\n  also have \"... = inv k \\<odot>\\<^bsub>M\\<^esub>\\<ominus>\\<^bsub>M\\<^esub> x1 \\<oplus>\\<^bsub>M\\<^esub> inv k \\<odot>\\<^bsub>M\\<^esub> (x1 \\<oplus>\\<^bsub>M\\<^esub> x2)\"\n    using x1x2 Span_in_carrier assms by auto\n  also have \"... = inv k \\<odot>\\<^bsub>M\\<^esub>\\<ominus>\\<^bsub>M\\<^esub> x1 \\<oplus>\\<^bsub>M\\<^esub> inv k \\<odot>\\<^bsub>M\\<^esub> x1 \\<oplus>\\<^bsub>M\\<^esub> inv k \\<odot>\\<^bsub>M\\<^esub> x2\"\n    using x1x2 Span_in_carrier assms smult_r_distr[of \"inv k\" x1 x2] M.a_assoc\n          k_prop k_def field_Units by auto \n  also have \"... = inv k \\<odot>\\<^bsub>M\\<^esub> (\\<ominus>\\<^bsub>M\\<^esub> x1 \\<oplus>\\<^bsub>M\\<^esub> x1) \\<oplus>\\<^bsub>M\\<^esub> inv k \\<odot>\\<^bsub>M\\<^esub> x2\"\n    using smult_r_distr x1x2 k_def Span_in_carrier assms k_prop field_Units by auto\n  also have \"... = inv k \\<odot>\\<^bsub>M\\<^esub> (\\<zero>\\<^bsub>M\\<^esub>) \\<oplus>\\<^bsub>M\\<^esub> inv k \\<odot>\\<^bsub>M\\<^esub> x2\"\n    using x1x2 k_def Span_in_carrier assms M.l_neg by auto \n  also have \"... = inv k \\<odot>\\<^bsub>M\\<^esub> x2\"\n    using smult_r_null[of \"inv k\"] x1x2 k_def Span_in_carrier assms M.l_zero M.r_neg1 calculation\n    by auto\n  also have \"... = inv k \\<odot>\\<^bsub>M\\<^esub> (k \\<odot>\\<^bsub>M\\<^esub> x)\" using k_def by auto\n  finally have \"inv k \\<odot>\\<^bsub>M\\<^esub>(\\<ominus>\\<^bsub>M\\<^esub> x1 \\<oplus>\\<^bsub>M\\<^esub> y) = x\"\n    using smult_assoc1[of \"inv k\" k x] assms k_def\n    by (simp add: k_prop local.field_Units)\n  moreover have \"x1 \\<in> Span R M (insert y A)\"\n    using x1x2 Span_mono[of A \"insert y A\"] assms Span_in_carrier by blast\n  hence  \"inv k \\<odot>\\<^bsub>M\\<^esub>(\\<ominus>\\<^bsub>M\\<^esub> x1 \\<oplus>\\<^bsub>M\\<^esub> y) \\<in> Span R M (insert y A)\"\n    using Span.eng_add[of \"\\<ominus>\\<^bsub>M\\<^esub> x1\" R M \"insert y A\" y] Span.a_inv[of x1 R M \"insert y A\"]\n          Span.eng_smult[of \"inv k\" R \"\\<ominus>\\<^bsub>M\\<^esub> x1 \\<oplus>\\<^bsub>M\\<^esub> y\" M \"insert y A\"] k_def k_prop x1x2\n    by (simp add: Span.incl field_Units)\n  ultimately show \"x \\<in> Span R M (insert y A)\" by auto\nqed\n\nlemma (in vector_space) aux_lemma_for_replacement :\n  assumes \"lin_indep R M A\"\n    and \"finite A\"\n    and \"y \\<in> Span R M A\"\n    and \"y \\<noteq> \\<zero>\\<^bsub>M\\<^esub>\"\n  shows \"\\<exists> z \\<in> carrier M. y \\<notin> Span R M (A - {z})\" using assms(2) assms(1,3)\nproof (induction A)\n  case empty\n  then show ?case using assms\n    using empty_Diff not_in_every_Span not_psubset_empty by force\nnext\n  case (insert x F)\n  have indep : \"lin_indep R M F\" using insert lin_indep_trunc[of \"insert x F\" \"{x}\"]  by simp\n  show ?case\n  proof (cases \"y \\<in> Span R M F\")\n    case True\n    from this obtain z where z_def : \"z \\<in> carrier M\"\"y \\<notin> Span R M (F - {z})\"\n      using insert indep by auto\n    have \"y \\<notin> Span R M (insert x F - {z})\"\n    proof\n      assume hyp : \"y \\<in> Span R M (insert x F - {z})\"\n      from True obtain z1 z2\n        where z1z2 : \"z1 \\<in> Span R M (F - {z})\" \"z2 \\<in> Span R M {z}\" \"z1 \\<oplus>\\<^bsub>M\\<^esub> z2 = y\"\n        using vector_decomposition[of \"F - {z}\" \"{z}\" y] insert(4) insert_is_Un[of z \"F-{z}\"]z_def\n        by (metis (no_types, lifting) Diff_empty Diff_insert0 Un_commute empty_subsetI insert_Diff\n           insert_subset)\n      have z1_insert : \"z1 \\<in> Span R M (insert x (F - {z}))\"\n        using z1z2 Span_mono[of \"F - {z}\" \"insert x (F - {z})\"] insert insert_subset\n        by (metis (no_types, lifting) Diff_empty Diff_insert0 insert_Diff subset_insertI)\n      have z20 : \"z2 \\<noteq> \\<zero>\\<^bsub>M\\<^esub>\"\n      proof\n        assume \"z2 = \\<zero>\\<^bsub>M\\<^esub>\"\n        then have \"y = z1\" using z1z2 Span_in_carrier insert(4) z_def\n          by (meson Span.eng_add Span.zero)\n        thus False using z1z2(1) z_def by auto\n      qed\n      have \"z2 \\<in> {k \\<odot>\\<^bsub>M\\<^esub> z |k. k \\<in> carrier R}\"\n        using Span_singleton[OF z_def(1)] z1z2(2) by auto\n      from this obtain k where k_def : \"k \\<in> carrier R\" \"z2 = k \\<odot>\\<^bsub>M\\<^esub> z\" by auto\n      hence k0 : \"k \\<noteq> \\<zero>\"\n        using z20 smult_l_null[OF z_def(1)] by auto\n      hence inv : \"inv k \\<in> carrier R\" using field_Units k_def by blast\n      hence \"inv k \\<odot>\\<^bsub>M\\<^esub> (\\<ominus>\\<^bsub>M\\<^esub> z1 \\<oplus>\\<^bsub>M\\<^esub> y) \\<in> Span R M (insert x (F - {z}))\"\n        using hyp z1z2(1) Span.a_inv[OF z1_insert] Span.eng_add[OF _ hyp, of \"\\<ominus>\\<^bsub>M\\<^esub> z1\"]\n              Span.eng_smult[OF inv, of \"(\\<ominus>\\<^bsub>M\\<^esub> z1 \\<oplus>\\<^bsub>M\\<^esub> y)\"]\n        by (smt insert_Diff_if z_def(2)) \n      moreover have \"inv k \\<odot>\\<^bsub>M\\<^esub> (\\<ominus>\\<^bsub>M\\<^esub> z1 \\<oplus>\\<^bsub>M\\<^esub> y) = inv k \\<odot>\\<^bsub>M\\<^esub> (\\<zero>\\<^bsub>M\\<^esub> \\<oplus>\\<^bsub>M\\<^esub> z2)\"\n        using z1z2 M.l_neg M.l_zero M.r_neg1 Span_in_carrier smult_closed z_def(1) insert_subset\n        by (metis (no_types, lifting) Diff_empty Diff_insert0 insert.prems(1) insert_Diff k_def) \n      hence \"inv k \\<odot>\\<^bsub>M\\<^esub> (\\<ominus>\\<^bsub>M\\<^esub> z1 \\<oplus>\\<^bsub>M\\<^esub> y) = inv k \\<odot>\\<^bsub>M\\<^esub> (k \\<odot>\\<^bsub>M\\<^esub> z)\"\n        using M.l_zero k_def Span_in_carrier z_def(1) smult_closed[OF k_def(1) z_def(1)] by auto\n      hence \"inv k \\<odot>\\<^bsub>M\\<^esub> (\\<ominus>\\<^bsub>M\\<^esub> z1 \\<oplus>\\<^bsub>M\\<^esub> y) = z\"\n        using smult_assoc1[OF inv k_def(1)] by (simp add: k0 k_def(1)field_Units z_def(1)) \n      ultimately have \"z \\<in> Span R M (insert x (F - {z}))\" by auto\n      moreover have \"insert x (F - {z}) \\<subseteq> carrier M\"\n        using insert(4) by blast\n      ultimately have \"lin_dep R M (insert z (insert x (F - {z})))\"\n        using vector_in_Span_imp_dep[of \"(insert x (F - {z}))\" z]True insert(2) z_def by fastforce\n      hence \"lin_dep R M (insert x F)\" using True z_def\n        by (metis (no_types, lifting) Diff_empty Diff_insert0 insert_Diff insert_commute)\n      thus False using insert(4) by auto\n    qed\n    then show ?thesis using z_def by auto\n  next\n    case False\n    then have \"y \\<notin> Span R M (insert x F - {x})\"\n      by (simp add: insert.hyps(2))\n    then show ?thesis using insert(4) by blast\n  qed\nqed\n\n\n\nlemma (in vector_space) non_null_decomposition :\n  assumes \"A \\<subseteq> carrier M\"\n    and \"x \\<in> Span R M A\"\n    and \"x \\<noteq> \\<zero>\\<^bsub>M\\<^esub>\"\n  shows \"\\<exists> y \\<in> A. \\<exists> z \\<in> Span R M (A - {y}). \\<exists> y2 \\<in> Span R M {y}. y2 \\<noteq> \\<zero>\\<^bsub>M\\<^esub> \\<and> z \\<oplus>\\<^bsub>M\\<^esub> y2 = x\"\nproof-\n    {fix I x assume Ix : \"x \\<in> Span R M I\" \"finite I\" \"x \\<noteq>\\<zero>\\<^bsub>M\\<^esub>\" \"I \\<subseteq> carrier M\"\n    have \"\\<exists> y \\<in> I. \\<exists> z \\<in> Span R M (I - {y}). \\<exists> y2 \\<in> Span R M {y}. y2 \\<noteq> \\<zero>\\<^bsub>M\\<^esub> \\<and> z \\<oplus>\\<^bsub>M\\<^esub> y2 = x\"\n      using Ix(2,1,3,4)\n    proof(induction I rule : finite.induct)\n      case emptyI\n      then have \"x = \\<zero>\\<^bsub>M\\<^esub>\"\n        using aux_lemma_for_replacement by fastforce\n      then show ?case using emptyI by auto\n    next\n      case (insertI A a)\n      then have inM : \"x \\<in> carrier M\" \"a \\<in> carrier M\" using Span_in_carrier by blast+\n      show ?case\n      proof (cases \"x \\<in> Span R M A\")\n        case True\n        hence \"\\<exists>y\\<in>A. \\<exists>z\\<in>Span R M (A - {y}). \\<exists>y2\\<in>Span R M {y}. y2 \\<noteq> \\<zero>\\<^bsub>M\\<^esub> \\<and> z \\<oplus>\\<^bsub>M\\<^esub> y2 = x\"\n          using insertI by auto\n        then obtain y z y2 \n          where yz : \"y \\<in> A\" \"z\\<in>Span R M (A - {y})\" \"y2\\<in>Span R M {y}\" \"y2 \\<noteq> \\<zero>\\<^bsub>M\\<^esub>\"\"z \\<oplus>\\<^bsub>M\\<^esub> y2 = x\"\n          by auto\n        then have \"y \\<in> insert a A\" by auto\n        moreover have \"z\\<in>Span R M ((insert a A) - {y})\"\n          using Span_mono[of \"A - {y}\" \"insert a A - {y}\"] insertI yz by blast\n        ultimately show ?thesis using yz\n          by blast \n      next\n        case False\n        from insertI obtain x1 x2\n          where x1x2 : \"x1 \\<in> Span R M ((insert a A) - {a})\" \"x2 \\<in> Span R M {a}\" \"x1 \\<oplus>\\<^bsub>M\\<^esub> x2 = x\"\n          using vector_decomposition[of \"(insert a A) - {a}\" \"{a}\"] insert_is_Un insert_absorb\n          by (smt Diff_insert_absorb False Un_commute empty_subsetI insert_subset)\n        have x20 : \"x2 \\<noteq> \\<zero>\\<^bsub>M\\<^esub>\"\n        proof\n          assume \"x2 = \\<zero>\\<^bsub>M\\<^esub>\"\n          then have \"x = x1\" using x1x2 Span_in_carrier[of \"insert a A - {a}\"] inM insertI\n            by fastforce\n          thus False using x1x2(1) False insertI\n            by (metis Diff_insert_absorb insert_absorb)\n        qed\n        then show ?thesis \n          using x1x2(1) x1x2(2) x1x2(3) by blast\n      qed\n    qed}\n  note existence = this\n  obtain S where S_def :  \"S \\<subseteq> A\" \"finite S\" \"x \\<in> Span R M S\"\n    using h_in_finite_Span assms by meson \n  hence \"\\<exists>y\\<in>S. \\<exists>z\\<in>Span R M (S - {y}). \\<exists>y2\\<in>Span R M {y}. y2 \\<noteq> \\<zero>\\<^bsub>M\\<^esub> \\<and> z \\<oplus>\\<^bsub>M\\<^esub> y2 = x\"\n    using S_def existence assms(1) assms(3) by blast\n  from this obtain y z y2\n    where aux : \"y\\<in>S\" \"z\\<in>Span R M (S - {y})\" \"y2\\<in>Span R M {y}\" \"y2 \\<noteq> \\<zero>\\<^bsub>M\\<^esub>\" \"z \\<oplus>\\<^bsub>M\\<^esub> y2 = x\"\n    by auto\n  have \"y \\<in> A\" using aux S_def by auto\n  moreover have \"z\\<in>Span R M (A - {y})\"\n    using Span_mono[of \"S - {y}\" \"A- {y}\"] assms(1) aux(2) S_def(1) by blast\n  ultimately show ?thesis using aux by auto\nqed\n\n\nlemma (in vector_space) inter_null_imp_indep :\n  assumes \"lin_indep R M A\"\n    and \"lin_indep R M B\"\n    and \"Span R M A \\<inter> Span R M B = {\\<zero>\\<^bsub>M\\<^esub>}\"\n  shows \"lin_indep R M (A \\<union> B)\" \nproof\n  show carrier : \"A \\<union> B \\<subseteq> carrier M\" using assms by auto\n  {fix S I J x\n    assume hyp : \"S \\<subset> I \\<union> J\" \"lin_indep R M I\" \"lin_indep R M J\" \"Span R M I \\<inter> Span R M J = {\\<zero>\\<^bsub>M\\<^esub>}\"\n                 \"x \\<in> I - S\" \"x \\<in> Span R M S\" have False\n    proof-\n      have not0 : \"\\<zero>\\<^bsub>M\\<^esub> \\<notin> I\" using zero_imp_dep[of I] hyp(2,5) lin_indep_not_dep by blast\n      hence xnot0 : \"x \\<noteq> \\<zero>\\<^bsub>M\\<^esub>\" using hyp(5) by auto\n      have \"I \\<inter> J \\<subseteq> {}\" using Span.incl[of _ \"I \\<inter> J\" R M] Span_mono[of \"I \\<inter> J\"] not0 hyp(2,3,4)\n        by (smt Diff_disjoint Diff_insert_absorb IntI Int_lower1 Int_lower2 set_rev_mp subsetI)\n      hence S_decomp : \"S = (S - I) \\<union> (S - J)\" by blast\n      from vector_decomposition[of \"S - I\" \"S - J\" x] hyp(1,2,3,6) this obtain x1 x2\n        where x1x2 :\"x1 \\<in> Span R M (S - I)\" \"x2 \\<in> Span R M (S - J)\" \"x1 \\<oplus>\\<^bsub>M\\<^esub> x2 = x\"\n        by (metis (no_types, lifting) Diff_subset_conv psubset_imp_subset\n            sup.absorb_iff1 sup.absorb_iff2 sup_left_commute)\n      have \"x \\<in> carrier M\" using hyp(1,2,3,5) by auto\n      hence allM : \"x \\<in> carrier M\"\"x1 \\<in> carrier M\"\"x2 \\<in> carrier M\" apply simp\n        using x1x2 Span_in_carrier[of \"S - I\" x1]Span_in_carrier[of \"S - J\" x2] hyp(1,2,3)\n         by (metis Diff_subset_conv psubset_imp_subset subset_trans sup_commute)+\n       hence \"x \\<oplus>\\<^bsub>M\\<^esub> \\<ominus>\\<^bsub>M\\<^esub> x2 = x1\" using x1x2 by (metis M.add.inv_solve_right)\n       moreover have \"x \\<oplus>\\<^bsub>M\\<^esub> \\<ominus>\\<^bsub>M\\<^esub> x2 \\<in> Span R M I\"\n         using x1x2(2) hyp(5) Span.incl[of x I R M] Span.a_inv[of x2 R M I] S_decomp hyp(1,2)\n               Span.eng_add[of x R M I\"\\<ominus>\\<^bsub>M\\<^esub> x2\"] Span_mono[of \"S - J\" I] by blast\n       moreover have \"x1 \\<in> Span R M J\"\n         using x1x2(1) S_decomp hyp(1,3) Span_mono[of \"S - I\" J] insert_Diff by blast\n       ultimately have \"x1 \\<in> Span R M I \\<inter> Span R M J\" by simp\n       hence \"x1 = \\<zero>\\<^bsub>M\\<^esub>\" using hyp(4) by auto\n       hence \"x = x2\" using x1x2(3) allM M.l_zero by auto\n       hence \"x \\<in> Span R M (S \\<inter> I)\"\n         using x1x2(2) S_decomp hyp(1,2) Span_mono[of \"S - J\"\"S \\<inter> I\"] by blast \n       moreover have \"lin_indep R M (insert x (S \\<inter> I))\"\n         using lin_indep_incl[OF hyp(2), of \"(insert x (S \\<inter> I))\"] hyp(5) by auto\n       ultimately show False\n         by (metis Diff_iff Int_iff hyp(5) insert_subset psubsetE vector_in_Span_imp_dep) \n     qed}\n   note aux = this\n   show \"\\<forall>S\\<subset>A \\<union> B. Span R M S \\<subset> Span R M (A \\<union> B)\"\n   proof-\n     {fix S assume S_def : \"S \\<subset> A \\<union> B\" have \"Span R M S \\<subset> Span R M (A \\<union> B)\"\n       proof\n         show  \"Span R M S \\<subseteq> Span R M (A \\<union> B)\" using Span_mono assms S_def by auto\n         show\"Span R M S \\<noteq> Span R M (A \\<union> B)\"\n         proof\n           assume hyp : \"Span R M S = Span R M (A \\<union> B)\"\n           from S_def obtain x where x_def : \"x \\<in> (A \\<union> B) - S\" by auto\n           show False\n           proof (cases \"x \\<in> A\")\n             case True\n             then show ?thesis\n               using aux[OF S_def assms(1,2,3)] x_def hyp Span.incl[of x \"A \\<union> B\" R M] by blast\n           next\n             case False\n             hence \"x \\<in> B\" using x_def by auto\n             then show ?thesis\n               using aux[of S B A, OF _ assms(2,1)] S_def assms x_def hyp Span.incl[of x \"A \\<union> B\" R]\n               by (metis Diff_iff Un_commute inf_commute)\n           qed\n         qed\n       qed}\n     thus ?thesis by auto\n   qed\nqed\n\n\nlemma (in vector_space) indep_inter_null :\n  assumes  \"lin_indep R M (A \\<union> B)\"\n    and \"A \\<inter> B = {}\"\n  shows \"Span R M A \\<inter> Span R M B = {\\<zero>\\<^bsub>M\\<^esub>}\"\nproof\n  show \"{\\<zero>\\<^bsub>M\\<^esub>} \\<subseteq> Span R M A \\<inter> Span R M B\" using Span.zero by auto\n  have indA : \"lin_indep R M A\" using lin_indep_incl[OF assms(1)] by auto\n  show \"Span R M A \\<inter> Span R M B \\<subseteq> {\\<zero>\\<^bsub>M\\<^esub>}\" using assms indA\n  proof(induction A arbitrary : B rule : infinite_finite_induct)\n    case (infinite A)\n    show ?case apply auto apply (rule ccontr) \n    proof-\n      fix x assume x_def : \"x \\<in>Span R M A\" \"x \\<in> Span R M B\" \"x \\<noteq> \\<zero>\\<^bsub>M\\<^esub>\"\n      from non_null_decomposition[of A x] x_def infinite obtain y z y2\n        where hyp : \"y\\<in>A\" \"z\\<in>Span R M (A - {y})\" \"y2\\<in>Span R M {y}\" \"y2 \\<noteq> \\<zero>\\<^bsub>M\\<^esub>\" \"z \\<oplus>\\<^bsub>M\\<^esub> y2 = x\"\n        by auto\n      have \"\\<ominus>\\<^bsub>M\\<^esub>z\\<oplus>\\<^bsub>M\\<^esub>x = y2\" using hyp a_comm_group infinite Span_in_carrier\n        by (metis (no_types, lifting) M.r_neg1  empty_subsetI insert_Diff insert_subset)\n      moreover have indep : \"lin_indep R M ((A - {y})\\<union> B)\"\n        using infinite lin_indep_incl[of \"(A \\<union> B)\"\"((A - {y})\\<union> B)\"] by fastforce\n      then have \"z\\<in>Span R M ((A - {y})\\<union> B)\"\"x\\<in>Span R M ((A - {y})\\<union> B)\"\n        using x_def(2) hyp(2) Span_mono[of B \"((A - {y})\\<union> B)\"] Span_mono[of\"A - {y}\" \"(A - {y})\\<union> B\"]\n        by auto\n      then have \"\\<ominus>\\<^bsub>M\\<^esub>z\\<oplus>\\<^bsub>M\\<^esub>x \\<in> Span R M ((A - {y})\\<union> B)\"\n        using Span.eng_add[of \"\\<ominus>\\<^bsub>M\\<^esub>z\" R M \"((A - {y})\\<union> B)\" x] Span.a_inv[of z R M \"((A - {y})\\<union> B)\"]\n        by blast\n      ultimately have y2 : \"y2 \\<in> Span R M ((A - {y})\\<union> B)\" by auto\n      hence \"y2 \\<in> Span R M (A - {y} \\<union> B) \\<inter> Span R M {y}\" using hyp by auto\n      moreover have \"insert y (A - {y} \\<union> B) = A \\<union> B\" using hyp(1) by auto\n      moreover have \"y \\<in> carrier M\" using infinite hyp(1) by auto\n      ultimately show  False using vector_in_Span_imp_dep[of \"A - {y} \\<union> B\" y] hyp(1,4) infinite(2)\n                        not_in_Span_imp_no_Span_inter[of \"A - {y} \\<union> B\" y]\n        by (metis DiffE IntI UnE empty_iff indep infinite.prems(2) less_le singletonD singletonI)\n    qed\n  next\n    case empty\n    then show ?case using Span_empty by auto\n  next\n    case (insert a F)\n    show ?case\n    proof (cases \"a \\<in> Span R M B\")\n      case True\n      then have \"a \\<in> Span R M (F \\<union> B)\"\n        using Span_mono[of B \"(F \\<union> B)\"] insert lin_indep_incl[of \"(F \\<union> B)\" \"(insert a F \\<union> B)\"]\n        by auto\n      moreover have \"a \\<notin> B\" using insert by auto\n      ultimately have  \"lin_dep R M (insert a F \\<union> B)\"\n        using vector_in_Span_imp_dep[of \"(F\\<union>B)\" a] insert lin_indep_incl[OF insert(4), of \"(F \\<union> B)\"]\n        by auto\n      then show ?thesis using insert(4) lin_indep_not_dep\n        by meson\n    next\n      case False\n      then have indep : \"lin_indep R M (F \\<union> insert a B)\"\n        using insert by (simp add: insert.IH)\n      moreover have \"F \\<inter> insert a B = {}\" using insert by auto\n      ultimately have inter : \"Span R M F \\<inter> Span R M (insert a B) \\<subseteq> {\\<zero>\\<^bsub>M\\<^esub>}\"\n        using insert(3)[of \"insert a B\"] lin_indep_incl[OF insert(4),of F] by auto       \n      show ?thesis \n      proof\n        fix x assume x_def : \"x \\<in> Span R M (insert a F) \\<inter> Span R M B\"\n        from this have xincl : \"x \\<in> Span R M (insert a F)\"  by auto\n        from this vector_decomposition[of F \"{a}\" x] insert obtain x1 x2\n          where x1x2 : \"x1 \\<in> Span R M F\" \"x2 \\<in> Span R M {a}\" \"x1 \\<oplus>\\<^bsub>M\\<^esub> x2 = x\" by auto\n        moreover have \"x \\<in> Span R M (insert a B)\"\n          using Span_mono[of B \"insert a B\"] lin_indep_incl[OF indep, of \"insert a B\"] x_def by auto\n        hence \"x \\<oplus>\\<^bsub>M\\<^esub> \\<ominus>\\<^bsub>M\\<^esub> x2 \\<in> Span R M (insert a B)\"\n          using x1x2(2) Span_mono[of \"{a}\" \"insert a B\"] lin_indep_incl[OF indep, of \"insert a B\"]\n                Span.a_inv[of x2 R M] Span.eng_add[of x R M \"insert a B\"\"\\<ominus>\\<^bsub>M\\<^esub> x2 \"]\n          by (metis Int_lower2 Un_upper2 insert.prems(2) insert_Diff insert_mono insert_subset)\n        hence \"x1 \\<in> Span R M (insert a B)\"\n          using x1x2 M.add.inv_solve_right[of x1 x x2] Span_in_carrier x_def\n          by (metis xincl empty_subsetI insert.prems(3) insert_subset)\n        ultimately have \"x1 =\\<zero>\\<^bsub>M\\<^esub> \" using inter  by blast\n        hence \"x = x2\" using x1x2 Span_in_carrier[of \"{a}\" x2] M.l_zero[of x2] insert by blast\n        hence \"x \\<in>Span R M {a} \\<inter> Span R M B\" using x1x2 x_def by auto\n        moreover have \"Span R M {a} \\<inter> Span R M B = {\\<zero>\\<^bsub>M\\<^esub>}\"\n          using not_in_Span_imp_no_Span_inter[of B, OF _ _ False] lin_indep_incl[OF indep, of B]\n                insert by auto\n        ultimately show \"x \\<in> {\\<zero>\\<^bsub>M\\<^esub>}\" by auto\n      qed\n    qed\n  qed\nqed\n\nlemma (in vector_space) indep_eq_inter_null :\n  assumes \"lin_indep R M A\"\n    and \"lin_indep R M B\"\n    and \"A\\<inter>B = {}\"\n  shows \"(lin_indep R M (A \\<union> B)) = ((Span R M A) \\<inter> (Span R M B) = {\\<zero>\\<^bsub>M\\<^esub>})\"\n  using indep_inter_null[OF _ assms(3)] inter_null_imp_indep[OF assms(1,2)]\n  by meson\n\n\nlemma (in vector_space) add_vector_indep :\n  assumes \"lin_indep R M A\"\n    and \"y \\<in> carrier M\"\n    and \"y \\<notin> Span R M A\"\n  shows \"lin_indep R M (insert y A)\"\n  using not_in_Span_imp_no_Span_inter[OF _ assms(2,3)] assms Span.zero[of M R A]\n       inter_null_imp_indep[OF assms(1) vector_indep[OF assms(2)]]\n  by (metis Un_insert_right sup_bot.right_neutral)\n\n\nproposition (in vector_space) replacement_theorem :\n  assumes \"lin_indep R M A\"\n    and \"lin_indep R M (insert x B)\"\n  shows \"\\<exists>y. lin_indep R M (insert x (A - {y}))\"\nproof (cases \"x \\<in> Span R M A\")\n  case True\n  have not0 : \"x \\<noteq> \\<zero>\\<^bsub>M\\<^esub>\" using assms(2) zero_imp_dep[of \"insert x B\"]\n    by (meson insert_iff lin_indep_not_dep)\n  obtain S where S_def : \"S \\<subseteq> A\"\"finite S\" \"x \\<in> Span R M S\"\n    using h_in_finite_Span[of A, OF _ True] assms by auto\n  hence \"\\<exists>z\\<in>carrier M. x \\<notin> Span R M (S - {z})\"\n    using aux_lemma_for_replacement[OF _ S_def(2,3) not0] lin_indep_trunc[OF assms(1), of \"A - S\"]\n    by (simp add: double_diff) \n  then obtain y where y_def : \"y \\<in> carrier M\" \"x \\<notin> Span R M (S - {y})\" by auto\n  have \"x \\<notin> Span R M (A - {y})\"\n  proof\n    assume hyp : \"x \\<in> Span R M (A - {y})\"\n    obtain y1 y2\n      where y1y2 : \"y1 \\<in> Span R M (S - {y})\" \"y2 \\<in> Span R M {y}\" \"y1 \\<oplus>\\<^bsub>M\\<^esub> y2 = x\"\n      using vector_decomposition[of \"S - {y}\" \"{y}\" x] insert_is_Un insert_absorb S_def y_def assms\n      by (smt Diff_empty Diff_insert0 Un_Diff_cancel Un_commute empty_subsetI insert_subset\n              subset_trans)\n    have allM : \"x \\<in> carrier M\"\"y1 \\<in> carrier M\"\"y2 \\<in> carrier M\"\n      using assms y1y2(1,2) y_def(1) Span_in_carrier[of \"S- {y}\" y1] Span_in_carrier[of \"{y}\" y2]\n             S_def(1)\n      by fastforce+\n    have y20 : \"y2 \\<noteq> \\<zero>\\<^bsub>M\\<^esub>\"\n    proof\n      assume \"y2 = \\<zero>\\<^bsub>M\\<^esub>\"\n      then have \"x = y1\" using y1y2 Span_in_carrier y_def\n        by (meson Span.eng_add Span.zero)\n      thus False using y1y2(1) y_def by auto\n    qed\n    have \"\\<ominus>\\<^bsub>M\\<^esub>y1 \\<oplus>\\<^bsub>M\\<^esub> x = y2\" using allM y1y2(3) M.r_neg1 by blast\n    moreover have \"y1 \\<in> Span R M (A - {y})\"\n      using S_def y1y2(1) Span_mono[of \"S - {y}\"\"(A - {y})\"] assms by auto\n    hence \"\\<ominus>\\<^bsub>M\\<^esub>y1 \\<oplus>\\<^bsub>M\\<^esub> x \\<in> Span R M (A - {y})\"by (simp add: Span.a_inv Span.eng_add hyp)\n    ultimately have \"y2 \\<in> Span R M (A - {y})\" by auto\n    hence \"y2 \\<in> Span R M (A - {y}) \\<inter> Span R M {y}\" using y1y2 by auto\n    moreover have \"(A - {y}) \\<inter> {y} = {}\" by blast\n    moreover have \"lin_indep R M (A - {y} \\<union> {y})\"\n      using assms(1) S_def calculation(2) y_def(2) Diff_insert0 Un_Diff_Int\n      by (metis (no_types, lifting) Diff_empty Diff_idemp Un_insert_right insert_Diff subsetCE)\n    ultimately show False using indep_inter_null[of \"A - {y}\"\"{y}\"] y20 assms(1) by blast\n  qed\n    then show ?thesis\n      using add_vector_indep[of \"A - {y}\" x] assms lin_indep_trunc by auto\nnext\n  case False\n  then show ?thesis\n    using add_vector_indep[OF assms(1) _ False] assms lin_indep_trunc[of \"insert x A\"]\n    by (metis Diff_idemp Diff_insert_absorb insert_subset lin_indep_not_dep zero_imp_dep)\nqed\n\nlemma (in vector_space) vector_unique_decomposition_aux :\n  assumes \"lin_indep R M(A \\<union> B)\"\n    and \"A \\<inter> B = {}\"\n    and \"x \\<in> Span R M (A \\<union> B)\"\nshows \"\\<exists>! x1. \\<exists>! x2. x1 \\<in> Span R M A \\<and> x2 \\<in> Span R M B \\<and> x1 \\<oplus>\\<^bsub>M\\<^esub> x2 = x\"\nproof-\n  have AM : \"A \\<subseteq> carrier M\" using assms(1) by auto\n  have BM : \"B \\<subseteq> carrier M\" using assms(1) by auto\n  from vector_decomposition[of A B x] obtain x1 x2\n    where x1x2 : \"x1 \\<in> Span R M A\" \"x2 \\<in> Span R M B\" \"x1 \\<oplus>\\<^bsub>M\\<^esub> x2 = x\" using assms AM BM by auto\n  show ?thesis\n  proof\n    show  \"\\<exists>!x2. x1 \\<in> Span R M A \\<and> x2 \\<in> Span R M B \\<and> x1 \\<oplus>\\<^bsub>M\\<^esub> x2 = x\"\n    proof\n      show \"x1 \\<in> Span R M A \\<and> x2 \\<in> Span R M B \\<and> x1 \\<oplus>\\<^bsub>M\\<^esub> x2 = x\" using x1x2 by auto\n      { fix xb assume xb : \"xb \\<in> Span R M B\" \"x1 \\<oplus>\\<^bsub>M\\<^esub> xb = x\" have \"xb = x2\"\n        proof-\n          from xb have \"\\<ominus>\\<^bsub>M\\<^esub>x1 \\<oplus>\\<^bsub>M\\<^esub> x1 \\<oplus>\\<^bsub>M\\<^esub> xb = xb\"\n            using x1x2 xb assms Span_in_carrier M.l_neg by auto\n          moreover have \"\\<ominus>\\<^bsub>M\\<^esub>x1 \\<oplus>\\<^bsub>M\\<^esub> x1 \\<oplus>\\<^bsub>M\\<^esub> xb = \\<ominus>\\<^bsub>M\\<^esub>x1 \\<oplus>\\<^bsub>M\\<^esub> x\"\n            using x1x2 xb assms Span_in_carrier M.l_neg AM BM M.add.inv_solve_left by force\n          moreover have \"\\<ominus>\\<^bsub>M\\<^esub>x1 \\<oplus>\\<^bsub>M\\<^esub> x = x2\"\n            using x1x2 assms Span_in_carrier AM BM M.l_neg  M.r_neg1 by auto \n          ultimately show  \"xb = x2\" by auto\n        qed}\n      thus \"\\<And>x2a. x1 \\<in> Span R M A \\<and> x2a \\<in> Span R M B \\<and> x1 \\<oplus>\\<^bsub>M\\<^esub> x2a = x \\<Longrightarrow> x2a = x2\" by auto\n    qed\n    {fix xa assume xa : \"\\<exists>!x2. xa \\<in> Span R M A \\<and> x2 \\<in> Span R M B \\<and> xa \\<oplus>\\<^bsub>M\\<^esub> x2 = x\"\n      have \"xa = x1\"\n      proof-\n        from xa obtain xb where xb : \"xa \\<in> Span R M A \\<and> xb \\<in> Span R M B \\<and> xa \\<oplus>\\<^bsub>M\\<^esub> xb = x\" by auto\n        hence \"xa \\<oplus>\\<^bsub>M\\<^esub> xb = x1 \\<oplus>\\<^bsub>M\\<^esub> x2\"\n          using x1x2 by auto\n        hence \"\\<ominus>\\<^bsub>M\\<^esub>x1 \\<oplus>\\<^bsub>M\\<^esub> xa \\<oplus>\\<^bsub>M\\<^esub> xb = x2\"\n          using AM BM xb Span_in_carrier M.l_neg M.add.m_assoc M.r_neg1 x1x2 by auto\n        hence eq : \"\\<ominus>\\<^bsub>M\\<^esub>x1 \\<oplus>\\<^bsub>M\\<^esub> xa = x2 \\<ominus>\\<^bsub>M\\<^esub>xb\" \n          using AM BM xb Span_in_carrier M.r_neg M.add.m_assoc M.r_neg1 x1x2\n          by (metis M.add.inv_solve_right M.a_closed M.minus_eq M.a_inv_closed) \n        moreover have \"\\<ominus>\\<^bsub>M\\<^esub>x1 \\<oplus>\\<^bsub>M\\<^esub> xa \\<in> Span R M A\"\n          using x1x2 xb by (simp add: Span.a_inv Span.eng_add)\n        moreover have \"x2 \\<ominus>\\<^bsub>M\\<^esub>xb \\<in> Span R M B\"\n          using x1x2 xb by (metis BM M.minus_eq Span.a_inv Span.eng_add Span_in_carrier)\n        moreover have \"Span R M A \\<inter> Span R M B = {\\<zero>\\<^bsub>M\\<^esub>}\" using indep_inter_null[OF assms(1,2)].\n        ultimately have \"x2 \\<ominus>\\<^bsub>M\\<^esub> xb = \\<zero>\\<^bsub>M\\<^esub>\" by auto\n        thus \"xa = x1\" using eq xb x1x2(1) Span_in_carrier[of A] lin_indep_incl[OF assms(1), of A]\n          by (metis AM M.minus_unique M.r_neg Span.a_inv)\n      qed}\n    thus \"\\<And>x1a. \\<exists>!x2. x1a \\<in> Span R M A \\<and> x2 \\<in> Span R M B \\<and> x1a \\<oplus>\\<^bsub>M\\<^esub> x2 = x \\<Longrightarrow> x1a = x1\" by auto\n  qed\nqed\n\ncorollary (in vector_space) vector_unique_decomposition :\n  assumes \"lin_indep R M(A \\<union> B)\"\n    and \"A \\<inter> B = {}\"\n    and \"x \\<in> Span R M (A \\<union> B)\"\n  shows \"\\<exists> x1 x2. x1 \\<in> Span R M A \\<and> x2 \\<in> Span R M B \\<and> x1 \\<oplus>\\<^bsub>M\\<^esub> x2 = x \\<and>\n        (\\<forall> y z. (y \\<in> Span R M A \\<and> z \\<in> Span R M B \\<and> y \\<oplus>\\<^bsub>M\\<^esub> z = x) \\<longrightarrow> y = x1 \\<and> z = x2)\"\n  apply simp using vector_unique_decomposition_aux[OF assms]\n  unfolding Ex1_def apply simp using assms Span_in_carrier\n  by (metis (no_types, lifting) abelian_group.r_neg1 le_sup_iff module_axioms module_def)\n\nlemma (in vector_space) extended_replacement_theorem :\n  assumes \"finite I\"\n    and \"lin_indep R M I\"\n    and \"lin_indep R M J\"\n    and \"card J \\<ge> card I\"\n  shows \"\\<forall> S \\<subseteq> I. \\<exists> V \\<subseteq> J. finite V \\<and> (card V = card S) \\<and> S \\<inter> (J-V) = {}\n                            \\<and>lin_indep R M (S \\<union> (J - V))\"\n  using assms\nproof(induction I arbitrary : J rule : finite_induct)\n  case empty then  \n  then show ?case using  Diff_empty Un_empty_left  finite.emptyI\n    by (metis Diff_disjoint empty_subsetI subset_empty) \nnext\n  case (insert x F)\n  have indepF : \"lin_indep R M F\"\n    using insert(4) lin_indep_trunc[of \"insert x F\" \"{x}\"]by (simp add: insert.hyps(2))\n  have xnot0 : \"x \\<noteq> \\<zero>\\<^bsub>M\\<^esub>\"\n    using zero_imp_dep[of \"insert x F\"] insert(4) by (meson insert_iff lin_indep_not_dep)\n  {fix S assume S_def : \"S \\<subseteq> insert x F\"\n    have \"(\\<exists>V \\<subseteq> J. finite V \\<and> card V = card S \\<and> S \\<inter> (J-V) = {} \\<and> lin_indep R M (S \\<union> (J - V)))\"\n          (is \"?P S J\")\n    proof (cases \"S \\<subseteq> F\")\n      case True\n      then show ?thesis using insert(3)[OF indepF insert(5)] insert by auto\n    next\n      case False\n      hence \"x \\<in> S\" using S_def by auto\n      from this obtain V where V_def : \"x \\<notin> V\"\"S = insert x V\" by (meson Set.set_insert)\n      hence inclF : \"V \\<subseteq> F\" using S_def by auto\n      have indep : \"lin_indep R M S\" using insert lin_indep_incl[OF insert(4) S_def] by simp\n      hence indep2 : \"lin_indep R M V\"\n        using lin_indep_incl[OF indep, of V] V_def  by (simp add: subset_insertI) \n      have notx : \"x \\<notin> Span R M V\"\n        using indep vector_in_Span_imp_dep[of V x] indep2 V_def indep2 by (meson lin_indep_not_dep)\n      have \"?P V J\"\n        using insert(3)[OF lin_indep_incl[OF insert(4)]lin_indep_incl[OF insert(5), of J]]inclF\n        by (meson card_insert_le le_trans insert(1,6) order_refl subset_insertI)\n      from this obtain L\n        where L_def : \"L\\<subseteq>J\"\"lin_indep R M (V \\<union> (J - L))\" \"card L = card V\"\n                      \"finite L\" \"V \\<inter> (J-L) = {}\" \n        by auto\n      show ?thesis\n      proof (cases \"x \\<in> Span R M (J-V-L)\")\n        case True\n        from non_null_decomposition[OF _ True xnot0] insert(5) obtain y z y2\n          where yz : \"y\\<in>J-V-L\"\"z\\<in>Span R M (J-V-L-{y})\"\"y2\\<in>Span R M {y}\"\"y2 \\<noteq> \\<zero>\\<^bsub>M\\<^esub>\"\"z \\<oplus>\\<^bsub>M\\<^esub> y2 = x\"\n          by auto\n        have \"x \\<notin> Span R M (V \\<union> (J - V - L - {y}))\"\n        proof\n          assume hyp : \"x \\<in> Span R M (V \\<union> (J - V - L - {y}))\"\n          have \"V \\<union> (J - V-L - {y}) \\<subseteq> carrier M\" using indep2 insert(5) by blast\n          moreover have \"J - V - L - {y} \\<subseteq> V \\<union> (J - L - {y})\" by blast\n          hence \"\\<ominus>\\<^bsub>M\\<^esub>z \\<in> Span R M (V \\<union> (J - V-L - {y}))\"\n            using  yz(2)Span.a_inv[of z R M \"(J - V - L - {y})\"]calculation\n            by (metis Span_mono insert_Diff insert_subset sup_ge2)\n          ultimately have \"\\<ominus>\\<^bsub>M\\<^esub>z \\<oplus>\\<^bsub>M\\<^esub> x \\<in> Span R M (V \\<union> (J - V-L - {y}))\"\n            using Span.eng_add[OF _ hyp, of \"\\<ominus>\\<^bsub>M\\<^esub>z\"] by metis\n          moreover have \"\\<ominus>\\<^bsub>M\\<^esub>z \\<oplus>\\<^bsub>M\\<^esub> x = y2\"\n            using Span_in_carrier yz M.r_neg1[of z y2]\n            by (meson Diff_subset empty_subsetI insert.prems(2) insert_subset subset_trans)\n          ultimately have \"y2 \\<in> Span R M (V \\<union> (J - V-L - {y}))\" by auto\n          moreover have \"V \\<union> (J - V-L - {y}) \\<union>  {y} = V \\<union> (J - L)\" using yz(1) by auto\n          moreover have \"(V \\<union> (J - V - L - {y})) \\<inter> {y} = {}\"\n            using yz(1) by blast\n          ultimately show False\n            using L_def(2) indep_inter_null[of \"V \\<union> (J - V-L - {y})\" \"{y}\"] yz(1,3,4) by auto\n        qed\n        moreover have \"(V \\<union> (J - V - L - {y})) = (V \\<union> (J  - L - {y}))\" by blast\n        ultimately have xSpan : \"x \\<notin> Span R M (V \\<union> (J - L - {y}))\" by auto\n        hence \"x \\<notin> ((V \\<union> (J - L - {y})))\" using Span.incl[of x \"(V \\<union> (J - L - {y}))\"] by auto\n        hence inter : \"S \\<inter> (J - L - {y}) = {}\"\n          using V_def L_def(5) by blast\n        have \"(insert x V) \\<union> (J - L - {y}) = insert x (V \\<union> (J - L - {y}))\" by blast\n        hence \"lin_indep R M ((insert x V) \\<union> (J - L - {y}))\"\n          using add_vector_indep[OF lin_indep_incl[OF L_def(2),of \"(V \\<union> (J - L - {y}))\"], of x] insert(4)\n                 subsetCE xSpan by force\n        hence \"lin_indep R M (S \\<union> (J - L - {y}))\" using V_def by auto\n        moreover have \"y \\<notin> L\" using yz(1) by auto\n        hence \"card (insert y L) = card V + 1\" using L_def(3,4) by auto\n        hence \"card (insert y L) = card S\"\n          using V_def finite_subset[OF S_def] insert(1) by simp\n        moreover have \"finite (insert y L)\" using L_def(4) by auto\n        moreover have \"(S \\<union> (J - (insert y L))) = (S \\<union> (J - L - {y}))\"by auto\n        ultimately show ?thesis using inter L_def(1) yz(1)\n          by (metis DiffD1 Diff_insert insert_subset) \n      next\n        case False\n        note F = this\n        show ?thesis\n        proof (cases \"x \\<in> Span R M (V\\<union>(J-L-V))\")\n          case True\n          have \"(V\\<union>(J-L-V)) = (V\\<union>(J-L))\" by simp\n          hence indep3 : \"lin_indep R M (V\\<union>(J-L-V))\" using L_def(2) by auto\n          from vector_unique_decomposition[OF indep3 _ True] obtain x1 x2\n            where x1x2 : \"x1 \\<in> Span R M V\"  \"x2 \\<in> Span R M (J - L - V)\" \"x1 \\<oplus>\\<^bsub>M\\<^esub> x2 = x\"\n           \"(\\<forall>y z. y \\<in> Span R M V \\<and> z \\<in> Span R M (J - L - V) \\<and> y \\<oplus>\\<^bsub>M\\<^esub> z = x \\<longrightarrow> y = x1 \\<and> z = x2)\"\n            by auto\n          have carrier : \"x \\<in> carrier M\"\"x1 \\<in> carrier M\"\"x2 \\<in> carrier M\"\n            using insert(4,5) Span_in_carrier x1x2(1,2) indep2 Span_mono[of \"J-L-V\" J]\n            by auto+           \n          have x20 : \"x2 \\<noteq> \\<zero>\\<^bsub>M\\<^esub>\"\n          proof\n            assume hyp : \"x2 = \\<zero>\\<^bsub>M\\<^esub>\"\n            hence \"x = x1\" using carrier x1x2(3) M.l_zero[of x1] by auto\n            thus False using x1x2(1)notx indep by auto\n          qed\n          from non_null_decomposition[OF _ x1x2(2) x20] insert(5) obtain y z y2\n            where yz : \"y\\<in>J-L-V\" \"z\\<in>Span R M (J-L-V-{y})\" \"y2\\<in>Span R M {y}\"\n                       \"y2 \\<noteq> \\<zero>\\<^bsub>M\\<^esub>\" \"z \\<oplus>\\<^bsub>M\\<^esub> y2 = x2\"\n            by auto\n          have x2_not_incl : \"x2 \\<notin> Span R M (J-L-V-{y})\"\n          proof\n            assume hyp : \"x2 \\<in> Span R M (J - L - V-{y})\"\n            hence \"\\<ominus>\\<^bsub>M\\<^esub>z \\<oplus>\\<^bsub>M\\<^esub> x2 \\<in> Span R M (J-L-V-{y})\"\n              using yz(2) Span.a_inv[OF yz(2)] Span.eng_add[of \"\\<ominus>\\<^bsub>M\\<^esub>z\", OF _ hyp] by auto\n            moreover have \"\\<ominus>\\<^bsub>M\\<^esub>z \\<oplus>\\<^bsub>M\\<^esub> x2 = y2\"\n              using carrier(3) yz Span_mono Span_in_carrier M.r_neg1[of z y2]\n              by (meson Diff_subset  empty_subsetI insert.prems(2) insert_subset subset_trans)\n            ultimately have \"y2 \\<in> Span R M (J - L - V - {y}) \\<inter> Span R M {y}\" using yz(3) by auto\n            moreover have \"(J - L - V - {y} \\<union> {y}) = (J - L - V)\" using yz(1) by blast\n            hence \"lin_indep R M (J - L - V - {y} \\<union> {y})\"\n              using lin_indep_trunc[OF lin_indep_trunc[OF insert(5), of L]] by auto\n            ultimately show False using yz(4) using indep_inter_null[of \"(J - L - V - {y})\"\"{y}\"]\n              by auto\n          qed\n          have xSpan :  \"x \\<notin> Span R M (V \\<union> (J - L - {y}))\"\n          proof\n            assume hyp : \"x \\<in> Span R M (V \\<union> (J - L - {y}))\"\n            hence hyp2 : \"x \\<in> Span R M (V \\<union> (J - L - V - {y}))\"\n              by (metis Diff_insert Diff_insert2 Un_Diff_cancel)\n            from vector_decomposition[OF _ _ hyp2] indep2 lin_indep_incl[OF insert(5)] obtain z1 z2 \n              where z1z2 : \"z1 \\<in> Span R M V\"  \"z2 \\<in> Span R M (J-L-V-{y})\" \"z1 \\<oplus>\\<^bsub>M\\<^esub> z2 = x\"\n              by auto\n            hence \"z2 \\<in> Span R M (J-L-V)\"\n              using Span_mono[of \"J-L-V-{y}\" \"J-L-V\"] lin_indep_incl[OF L_def(2), of \"J-L\"] by auto \n            hence \"z2 = x2\" using x1x2(4) z1z2 by auto      \n            thus False using z1z2(2) x2_not_incl by auto\n          qed\n          hence\"lin_indep R M (insert x (V \\<union> (J - L - {y})))\"\n            using add_vector_indep[OF lin_indep_incl[OF L_def(2),of \"V \\<union> (J-L-{y})\"],of x] carrier\n            by fastforce\n          moreover from xSpan have \"x \\<notin> (V \\<union> (J - L - {y}))\"\n            using Span.incl[of x \"V \\<union> (J - L - {y})\"] by auto\n          hence \"S \\<inter> (J - L - {y}) = {}\"\n            using V_def L_def(5) by blast\n          moreover have \"y \\<notin> L\" using yz(1) by auto\n          hence \"card (insert y L) = card V + 1\" using L_def(3,4) by auto\n          hence \"card (insert y L) = card S\"\n            using V_def finite_subset[OF S_def] finite_insert[of F] insert(1) by auto\n          moreover have \"finite (insert y L)\" using L_def(4) finite_insert by auto\n          moreover have \"(insert y L) \\<subseteq> J\" using L_def(1) yz(1) by auto\n          moreover have \"V \\<union> (J - L - {y}) = V \\<union> (J - insert y L)\" by blast\n          hence \"insert x (V \\<union> (J - L - {y})) = S \\<union> (J - insert y L)\"\n            using yz(1) V_def by blast\n          ultimately show ?thesis by (metis Diff_insert)\n        next\n          case False\n          have \"(V \\<union> (J - L - V)) = (V \\<union> (J - L))\" by blast\n          hence \"x \\<notin> Span R M (V \\<union> (J - L))\" using False by auto\n          hence \"lin_indep R M (insert x (V \\<union> (J - L)))\"\n            using add_vector_indep[OF L_def(2), of x] insert(4) by auto\n          moreover have \"insert x (V \\<union> (J - L)) = insert x V \\<union> (J - L)\" by blast\n          hence \"insert x (V \\<union> (J - L)) = S \\<union> (J - L)\"\n            using V_def by auto\n          ultimately have \"lin_indep R M (S \\<union> (J - L))\" by auto\n          moreover have \"\\<exists> y. y \\<in> (J-L)\"\n            using insert(1,6) L_def(3,4) inclF card_insert_le[OF insert(1), of x]\n            by (metis Diff_subset_conv L_def(1) Un_absorb1 Un_absorb2 card_seteq\n                finite_insert insert.hyps(2) insertI1 subsetI subset_Diff_insert)\n          from this obtain y where y : \"y \\<in> J-L\" by auto\n          ultimately have \"lin_indep R M (S \\<union> (J - insert y L))\"\n            using lin_indep_incl[of \"(S \\<union> (J - L))\" \"(S \\<union> (J - insert y L))\"] by fastforce\n          moreover have  \"y \\<notin> L\" using y by simp\n          hence \"card (insert y L) = card V + 1\" using L_def(3,4) by auto\n          hence \"card (insert y L) = card S\"\n            using V_def finite_subset[OF S_def] finite_insert[of F] insert(1) by auto\n          moreover have \"finite (insert y L)\" using L_def(4) finite_insert by auto\n          moreover have \"(insert y L) \\<subseteq> J\" using L_def(1) y by auto\n          moreover from False have \"x \\<notin> (V \\<union> (J - L)) \"\n            using Span.incl[of x \"(V \\<union> (J - L - V)) \"] by auto\n          hence \"S \\<inter> (J - (insert y L)) = {}\"\n            using L_def(5) V_def by blast\n          ultimately show ?thesis by blast\n        qed\n      qed\n    qed}\n  thus ?case by auto\nqed\n\nlemma (in vector_space) finite_dim_imp_finite_base :\n  assumes \"finite_dim R M K\"\n    and \"base R M S K\"\n    and \"dim K = n\"\n  shows \"finite S\"\nproof (rule ccontr)\n  assume infinity : \"infinite S\"\n  have n_def : \"n = (LEAST n. (\\<exists> A. finite A \\<and> card A = n  \\<and>  generator R M A K))\" using assms\n    by (simp add: dim_def)\n  moreover have \"(\\<exists> A. finite A \\<and>  generator R M A K)\"\n    using assms(1) unfolding finite_dim_def by simp\n  ultimately have \"(\\<exists> A. finite A \\<and> card A = n \\<and> generator R M A K)\" using assms\n    by (smt LeastI)\n  from this obtain A where A_def : \"finite A\" \"card A = n\" \"generator R M A K\" by auto\n  have indep_A :\"lin_indep R M A\"\n  proof\n    show \"A \\<subseteq> carrier M\" using A_def unfolding generator_def by auto\n    {fix I assume I_def : \"I \\<subset> A\" have \"Span R M I \\<subset> Span R M A\"\n      proof\n        show \"Span R M I \\<subseteq> Span R M A\"\n          using Span_mono[of I A] I_def A_def(3) unfolding generator_def by auto\n        show \"Span R M I \\<noteq> Span R M A \"\n        proof\n          assume hyp : \"Span R M I = Span R M A\"\n          hence \"Span R M I = K\" using A_def unfolding generator_def by auto\n          moreover have \"card I < n\" using I_def A_def\n            using psubset_card_mono by blast\n          moreover have \"finite I\" using A_def I_def infinite_super by blast\n          ultimately show False using n_def A_def(3) unfolding generator_def\n            by (smt I_def not_less_Least psubsetE psubset_subset_trans)\n        qed\n      qed}\n    thus \"\\<forall>S\\<subset>A. Span R M S \\<subset> Span R M A\" by simp\n  qed\n  from infinity obtain S2\n    where S2 :\"finite S2\"\"S2 \\<subseteq> S\"\"card S2 \\<ge> (n + n + 1)\"\n    by (metis infinite_arbitrarily_large order_refl)\n  hence \"card S2 \\<ge> n\" by auto\n  from this S2(1,2) obtain V where V_def : \"finite V\"\"card V = card A\" \"lin_indep R M (A \\<union> (S2 - V))\"\n    using extended_replacement_theorem[OF A_def(1), of S2]lin_indep_incl[OF _ S2(2)] A_def(2) indep_A\n            assms(2) unfolding base_def by auto\n  have \"card (A \\<union> V) \\<le> n + n\" using A_def(1,2) V_def(1,2)\n    by (metis card_Un_le)\n  hence \"S2 - (A \\<union> V) \\<noteq> {} \"\n    using S2  A_def(1) V_def(1) card_seteq  diff_is_0_eq' Diff_eq_empty_iff diff_add_inverse\n    by (metis One_nat_def add.right_neutral add_Suc_right finite_UnI le_SucI le_trans nat.simps(3))\n  moreover have \"(A \\<union> (S2 - (A \\<union> V))) = (A \\<union> (S2 - V))\" by blast\n  ultimately have \"A \\<subset> (A \\<union> (S2 - V))\"  by blast\n  moreover have \"Span R M (A \\<union>(S2 - V)) \\<subseteq> K\"\n    using assms A_def S2(2) unfolding generator_def base_def\n    by (smt Diff_subset SpanE(2) Span_is_submodule Span_min_submodule1 Un_least subset_trans) \n    \n  ultimately show False using V_def(2,3) A_def(3) unfolding generator_def by blast    \nqed\n\nproposition (in vector_space) dimension_unique :\n  assumes \"finite_dim R M K\"\n    and \"base R M S K\"\n    and \"dim K = n\"\n  shows \"card S = n\"\nproof (rule ccontr)\n  assume hyp : \"card S \\<noteq> n\"\n  have finite : \"finite S\" using assms finite_dim_imp_finite_base by auto\n  have n_def : \"n = (LEAST n. (\\<exists> A. finite A \\<and> card A = n  \\<and>  generator R M A K))\" using assms\n    by (simp add: dim_def)\n  moreover have \"(\\<exists> A. finite A \\<and>  generator R M A K)\"\n    using assms(1) unfolding finite_dim_def by simp\n  ultimately have \"(\\<exists> A. finite A \\<and> card A = n \\<and> generator R M A K)\" using assms\n    by (smt LeastI)\n  from this obtain A where A_def : \"finite A\" \"card A = n\" \"generator R M A K\" by auto\n  have indep_A :\"lin_indep R M A\"\n  proof\n    {fix I assume I_def : \"I \\<subset> A\" have \"Span R M I \\<subset> Span R M A\"\n      proof\n        show \"Span R M I \\<subseteq> Span R M A\"\n          using Span_mono[of I A] I_def A_def(3) unfolding generator_def by auto\n        show \"Span R M I \\<noteq> Span R M A \"\n        proof\n          assume hyp : \"Span R M I = Span R M A\"\n          hence \"Span R M I = K\" using A_def unfolding generator_def by auto\n          moreover have \"card I < n\" using I_def A_def\n            using psubset_card_mono by blast\n          moreover have \"finite I\" using A_def I_def infinite_super by blast\n          ultimately show False using n_def A_def(3) unfolding generator_def\n            by (smt I_def not_less_Least psubsetE psubset_subset_trans)\n        qed\n      qed}\n    thus \"\\<forall>S\\<subset>A. Span R M S \\<subset> Span R M A\" by simp\n    show \"A \\<subseteq> carrier M\" using A_def unfolding generator_def by auto\n  qed\n  show False\n  proof (cases \"card S \\<ge> n\")\n    case True\n    from this extended_replacement_theorem[OF A_def(1)indep_A, of S]\n    obtain V\n      where V_def : \"V\\<subseteq>S\" \"finite V\" \"card V = card A\" \"A \\<inter> (S - V) = {}\"\n                    \"lin_indep R M (A \\<union> (S - V))\"\n      using A_def(2) assms(2) unfolding base_def by force\n    have \"S-V \\<noteq> {}\" using V_def(1,3) True A_def(2) hyp by auto\n    hence \"A \\<subset> (A \\<union> (S - V))\"\n      using V_def(3,4) by auto\n    moreover have \"Span R M (A \\<union>(S - V)) \\<subseteq> K\"\n      using assms A_def V_def(1) Span_union unfolding generator_def base_def\n      by (smt Diff_partition Un_subset_iff set_eq_subset sup.right_idem)\n    ultimately show ?thesis\n      using assms(2) A_def(3) V_def(5) unfolding base_def\n      by (metis generator_def psubsetE)\n  next\n    case False\n    define m where m : \"m = card S\"\n    hence \"m < n\" using False by linarith\n    moreover have \"finite S \\<and> card S = m \\<and> generator R M S K\"\n      using assms(2) m finite unfolding base_def by auto\n    ultimately show False using assms(3) not_less_Least unfolding dim_def by auto\n  qed\nqed\n\n\n      \n\n\n\n\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/Space_Vectors.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8740772286044094, "lm_q2_score": 0.8333245891029457, "lm_q1q2_score": 0.728390047371011}}
{"text": "(*  Title:       Examples of hybrid systems verifications\n    Author:      Jonathan Juli\u00e1n Huerta y Munive, 2019\n    Maintainer:  Jonathan Juli\u00e1n Huerta y Munive <jjhuertaymunive1@sheffield.ac.uk>\n*)\n\nsubsection \\<open> Examples \\<close>\n\ntext \\<open> We prove partial correctness specifications of some hybrid systems with our\nrecently described verification components.\\<close>\n\ntheory HS_VC_PT_Examples\n  imports HS_VC_PT\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 by providing the dynamics\\<close>\n\nlemma pendulum_dyn: \"{s. r\\<^sup>2 = (s$1)\\<^sup>2 + (s$2)\\<^sup>2} \\<le> fb\\<^sub>\\<F> (EVOL \\<phi> G T) {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: \"{s. r\\<^sup>2 = (s$1)\\<^sup>2 + (s$2)\\<^sup>2} \\<le> fb\\<^sub>\\<F> (x\\<acute>= f & G) {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: \"{s. r\\<^sup>2 = (s$1)\\<^sup>2 + (s$2)\\<^sup>2} \\<le> fb\\<^sub>\\<F> (x\\<acute>= f & G) {s. r\\<^sup>2 = (s$1)\\<^sup>2 + (s$2)\\<^sup>2}\"\n  by (force simp: local_flow.ffb_g_ode[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 assigntment that\nflips the velocity, thus it is a completely elastic collision with the ground. We use @{text \"s$1\"}\nto ball's height and @{text \"s$2\"} for its velocity. We prove that the ball remains above ground\nand 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 bouncing_ball_inv: \"g < 0 \\<Longrightarrow> h \\<ge> 0 \\<Longrightarrow>\n  {s. s$1 = h \\<and> s$2 = 0} \\<le> fb\\<^sub>\\<F>\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  {s. 0 \\<le> s$1 \\<and> s$1 \\<le> h}\"\n  apply(rule ffb_loopI, simp_all)\n    apply(force, force simp: bb_real_arith)\n  apply(rule ffb_g_odei)\n  by (auto intro!: diff_invariant_rules poly_derivatives simp: bb_real_arith)\n\n\\<comment> \\<open>Verified by providing the 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> * (g * \\<tau> + v) + 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, hide_lams) 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, hide_lams) 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> * (g * \\<tau> + v) + 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  {s. s$1 = h \\<and> s$2 = 0} \\<le> fb\\<^sub>\\<F>\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  {s. 0 \\<le> s$1 \\<and> s$1 \\<le> h}\"\n  by (rule ffb_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  {s. s$1 = h \\<and> s$2 = 0} \\<le> fb\\<^sub>\\<F>\n  (LOOP (\n    (x\\<acute>=(f g) & (\\<lambda> s. s$1 \\<ge> 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  {s. 0 \\<le> s$1 \\<and> s$1 \\<le> h}\"\n  by (rule ffb_loopI) (auto simp: bb_real_arith local_flow.ffb_g_ode[OF local_flow_ball])\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_all 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 ffb_temp_dyn = local_flow.ffb_g_ode_ivl[OF local_flow_temp _ UNIV_I]\n\nlemma thermostat:\n  assumes \"a > 0\" and \"0 \\<le> t\" and \"0 < Tmin\" and \"Tmax < L\"\n  shows \"{s. Tmin \\<le> s$1 \\<and> s$1 \\<le> Tmax \\<and> s$4 = 0} \\<le> fb\\<^sub>\\<F>\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) on {0..t} UNIV @ 0)\n    ELSE (x\\<acute>=(f a L) & (\\<lambda>s. s$2 \\<le> - (ln ((L-Tmax)/(L-s$3)))/a) on {0..t} UNIV @ 0)) )\n  INV (\\<lambda>s. Tmin \\<le>s$1 \\<and> s$1 \\<le> Tmax \\<and> (s$4 = 0 \\<or> s$4 = 1)))\n  {s. Tmin \\<le> s$1 \\<and> s$1 \\<le> Tmax}\"\n  apply(rule ffb_loopI, simp_all add: ffb_temp_dyn[OF assms(1,2)] le_fun_def, safe)\n  using temp_dyn_up_real_arith[OF assms(1) _ _ assms(4), of Tmin]\n    and temp_dyn_down_real_arith[OF assms(1,3), of _ Tmax] by auto\n\nno_notation temp_vec_field (\"f\")\n        and temp_flow (\"\\<phi>\")\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/Hybrid_Systems_VCs/PredicateTransformers/HS_VC_PT_Examples.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8418256591565729, "lm_q2_score": 0.8652240947405564, "lm_q1q2_score": 0.728367843873118}}
{"text": "(*  Title:      HOL/Topological_Spaces.thy\n    Author:     Brian Huffman\n    Author:     Johannes H\u00f6lzl\n*)\n\nsection \\<open>Topological Spaces\\<close>\n\ntheory Topological_Spaces\n  imports Main\nbegin\n\nnamed_theorems continuous_intros \"structural introduction rules for continuity\"\n\nsubsection \\<open>Topological space\\<close>\n\nclass \"open\" =\n  fixes \"open\" :: \"'a set \\<Rightarrow> bool\"\n\nclass topological_space = \"open\" +\n  assumes open_UNIV [simp, intro]: \"open UNIV\"\n  assumes open_Int [intro]: \"open S \\<Longrightarrow> open T \\<Longrightarrow> open (S \\<inter> T)\"\n  assumes open_Union [intro]: \"\\<forall>S\\<in>K. open S \\<Longrightarrow> open (\\<Union>K)\"\nbegin\n\ndefinition closed :: \"'a set \\<Rightarrow> bool\"\n  where \"closed S \\<longleftrightarrow> open (- S)\"\n\nlemma open_empty [continuous_intros, intro, simp]: \"open {}\"\n  using open_Union [of \"{}\"] by simp\n\nlemma open_Un [continuous_intros, intro]: \"open S \\<Longrightarrow> open T \\<Longrightarrow> open (S \\<union> T)\"\n  using open_Union [of \"{S, T}\"] by simp\n\nlemma open_UN [continuous_intros, intro]: \"\\<forall>x\\<in>A. open (B x) \\<Longrightarrow> open (\\<Union>x\\<in>A. B x)\"\n  using open_Union [of \"B ` A\"] by simp\n\nlemma open_Inter [continuous_intros, intro]: \"finite S \\<Longrightarrow> \\<forall>T\\<in>S. open T \\<Longrightarrow> open (\\<Inter>S)\"\n  by (induct set: finite) auto\n\nlemma open_INT [continuous_intros, intro]: \"finite A \\<Longrightarrow> \\<forall>x\\<in>A. open (B x) \\<Longrightarrow> open (\\<Inter>x\\<in>A. B x)\"\n  using open_Inter [of \"B ` A\"] by simp\n\nlemma openI:\n  assumes \"\\<And>x. x \\<in> S \\<Longrightarrow> \\<exists>T. open T \\<and> x \\<in> T \\<and> T \\<subseteq> S\"\n  shows \"open S\"\nproof -\n  have \"open (\\<Union>{T. open T \\<and> T \\<subseteq> S})\" by auto\n  moreover have \"\\<Union>{T. open T \\<and> T \\<subseteq> S} = S\" by (auto dest!: assms)\n  ultimately show \"open S\" by simp\nqed\n\nlemma open_subopen: \"open S \\<longleftrightarrow> (\\<forall>x\\<in>S. \\<exists>T. open T \\<and> x \\<in> T \\<and> T \\<subseteq> S)\"\nby (auto intro: openI)\n\nlemma closed_empty [continuous_intros, intro, simp]: \"closed {}\"\n  unfolding closed_def by simp\n\nlemma closed_Un [continuous_intros, intro]: \"closed S \\<Longrightarrow> closed T \\<Longrightarrow> closed (S \\<union> T)\"\n  unfolding closed_def by auto\n\nlemma closed_UNIV [continuous_intros, intro, simp]: \"closed UNIV\"\n  unfolding closed_def by simp\n\nlemma closed_Int [continuous_intros, intro]: \"closed S \\<Longrightarrow> closed T \\<Longrightarrow> closed (S \\<inter> T)\"\n  unfolding closed_def by auto\n\nlemma closed_INT [continuous_intros, intro]: \"\\<forall>x\\<in>A. closed (B x) \\<Longrightarrow> closed (\\<Inter>x\\<in>A. B x)\"\n  unfolding closed_def by auto\n\nlemma closed_Inter [continuous_intros, intro]: \"\\<forall>S\\<in>K. closed S \\<Longrightarrow> closed (\\<Inter>K)\"\n  unfolding closed_def uminus_Inf by auto\n\nlemma closed_Union [continuous_intros, intro]: \"finite S \\<Longrightarrow> \\<forall>T\\<in>S. closed T \\<Longrightarrow> closed (\\<Union>S)\"\n  by (induct set: finite) auto\n\nlemma closed_UN [continuous_intros, intro]:\n  \"finite A \\<Longrightarrow> \\<forall>x\\<in>A. closed (B x) \\<Longrightarrow> closed (\\<Union>x\\<in>A. B x)\"\n  using closed_Union [of \"B ` A\"] by simp\n\nlemma open_closed: \"open S \\<longleftrightarrow> closed (- S)\"\n  by (simp add: closed_def)\n\nlemma closed_open: \"closed S \\<longleftrightarrow> open (- S)\"\n  by (rule closed_def)\n\nlemma open_Diff [continuous_intros, intro]: \"open S \\<Longrightarrow> closed T \\<Longrightarrow> open (S - T)\"\n  by (simp add: closed_open Diff_eq open_Int)\n\nlemma closed_Diff [continuous_intros, intro]: \"closed S \\<Longrightarrow> open T \\<Longrightarrow> closed (S - T)\"\n  by (simp add: open_closed Diff_eq closed_Int)\n\nlemma open_Compl [continuous_intros, intro]: \"closed S \\<Longrightarrow> open (- S)\"\n  by (simp add: closed_open)\n\nlemma closed_Compl [continuous_intros, intro]: \"open S \\<Longrightarrow> closed (- S)\"\n  by (simp add: open_closed)\n\nlemma open_Collect_neg: \"closed {x. P x} \\<Longrightarrow> open {x. \\<not> P x}\"\n  unfolding Collect_neg_eq by (rule open_Compl)\n\nlemma open_Collect_conj:\n  assumes \"open {x. P x}\" \"open {x. Q x}\"\n  shows \"open {x. P x \\<and> Q x}\"\n  using open_Int[OF assms] by (simp add: Int_def)\n\nlemma open_Collect_disj:\n  assumes \"open {x. P x}\" \"open {x. Q x}\"\n  shows \"open {x. P x \\<or> Q x}\"\n  using open_Un[OF assms] by (simp add: Un_def)\n\nlemma open_Collect_ex: \"(\\<And>i. open {x. P i x}) \\<Longrightarrow> open {x. \\<exists>i. P i x}\"\n  using open_UN[of UNIV \"\\<lambda>i. {x. P i x}\"] unfolding Collect_ex_eq by simp\n\nlemma open_Collect_imp: \"closed {x. P x} \\<Longrightarrow> open {x. Q x} \\<Longrightarrow> open {x. P x \\<longrightarrow> Q x}\"\n  unfolding imp_conv_disj by (intro open_Collect_disj open_Collect_neg)\n\nlemma open_Collect_const: \"open {x. P}\"\n  by (cases P) auto\n\nlemma closed_Collect_neg: \"open {x. P x} \\<Longrightarrow> closed {x. \\<not> P x}\"\n  unfolding Collect_neg_eq by (rule closed_Compl)\n\nlemma closed_Collect_conj:\n  assumes \"closed {x. P x}\" \"closed {x. Q x}\"\n  shows \"closed {x. P x \\<and> Q x}\"\n  using closed_Int[OF assms] by (simp add: Int_def)\n\nlemma closed_Collect_disj:\n  assumes \"closed {x. P x}\" \"closed {x. Q x}\"\n  shows \"closed {x. P x \\<or> Q x}\"\n  using closed_Un[OF assms] by (simp add: Un_def)\n\nlemma closed_Collect_all: \"(\\<And>i. closed {x. P i x}) \\<Longrightarrow> closed {x. \\<forall>i. P i x}\"\n  using closed_INT[of UNIV \"\\<lambda>i. {x. P i x}\"] by (simp add: Collect_all_eq)\n\nlemma closed_Collect_imp: \"open {x. P x} \\<Longrightarrow> closed {x. Q x} \\<Longrightarrow> closed {x. P x \\<longrightarrow> Q x}\"\n  unfolding imp_conv_disj by (intro closed_Collect_disj closed_Collect_neg)\n\nlemma closed_Collect_const: \"closed {x. P}\"\n  by (cases P) auto\n\nend\n\n\nsubsection \\<open>Hausdorff and other separation properties\\<close>\n\nclass t0_space = topological_space +\n  assumes t0_space: \"x \\<noteq> y \\<Longrightarrow> \\<exists>U. open U \\<and> \\<not> (x \\<in> U \\<longleftrightarrow> y \\<in> U)\"\n\nclass t1_space = topological_space +\n  assumes t1_space: \"x \\<noteq> y \\<Longrightarrow> \\<exists>U. open U \\<and> x \\<in> U \\<and> y \\<notin> U\"\n\ninstance t1_space \\<subseteq> t0_space\n  by standard (fast dest: t1_space)\n\ncontext t1_space begin\n\nlemma separation_t1: \"x \\<noteq> y \\<longleftrightarrow> (\\<exists>U. open U \\<and> x \\<in> U \\<and> y \\<notin> U)\"\n  using t1_space[of x y] by blast\n\nlemma closed_singleton [iff]: \"closed {a}\"\nproof -\n  let ?T = \"\\<Union>{S. open S \\<and> a \\<notin> S}\"\n  have \"open ?T\"\n    by (simp add: open_Union)\n  also have \"?T = - {a}\"\n    by (auto simp add: set_eq_iff separation_t1)\n  finally show \"closed {a}\"\n    by (simp only: closed_def)\nqed\n\nlemma closed_insert [continuous_intros, simp]:\n  assumes \"closed S\"\n  shows \"closed (insert a S)\"\nproof -\n  from closed_singleton assms have \"closed ({a} \\<union> S)\"\n    by (rule closed_Un)\n  then show \"closed (insert a S)\"\n    by simp\nqed\n\nlemma finite_imp_closed: \"finite S \\<Longrightarrow> closed S\"\n  by (induct pred: finite) simp_all\n\nend\n\ntext \\<open>T2 spaces are also known as Hausdorff spaces.\\<close>\n\nclass t2_space = topological_space +\n  assumes hausdorff: \"x \\<noteq> y \\<Longrightarrow> \\<exists>U V. open U \\<and> open V \\<and> x \\<in> U \\<and> y \\<in> V \\<and> U \\<inter> V = {}\"\n\ninstance t2_space \\<subseteq> t1_space\n  by standard (fast dest: hausdorff)\n\nlemma (in t2_space) separation_t2: \"x \\<noteq> y \\<longleftrightarrow> (\\<exists>U V. open U \\<and> open V \\<and> x \\<in> U \\<and> y \\<in> V \\<and> U \\<inter> V = {})\"\n  using hausdorff [of x y] by blast\n\nlemma (in t0_space) separation_t0: \"x \\<noteq> y \\<longleftrightarrow> (\\<exists>U. open U \\<and> \\<not> (x \\<in> U \\<longleftrightarrow> y \\<in> U))\"\n  using t0_space [of x y] by blast\n\n\ntext \\<open>A classical separation axiom for topological space, the T3 axiom -- also called regularity:\nif a point is not in a closed set, then there are open sets separating them.\\<close>\n\nclass t3_space = t2_space +\n  assumes t3_space: \"closed S \\<Longrightarrow> y \\<notin> S \\<Longrightarrow> \\<exists>U V. open U \\<and> open V \\<and> y \\<in> U \\<and> S \\<subseteq> V \\<and> U \\<inter> V = {}\"\n\ntext \\<open>A classical separation axiom for topological space, the T4 axiom -- also called normality:\nif two closed sets are disjoint, then there are open sets separating them.\\<close>\n\nclass t4_space = t2_space +\n  assumes t4_space: \"closed S \\<Longrightarrow> closed T \\<Longrightarrow> S \\<inter> T = {} \\<Longrightarrow> \\<exists>U V. open U \\<and> open V \\<and> S \\<subseteq> U \\<and> T \\<subseteq> V \\<and> U \\<inter> V = {}\"\n\ntext \\<open>T4 is stronger than T3, and weaker than metric.\\<close>\n\ninstance t4_space \\<subseteq> t3_space\nproof\n  fix S and y::'a assume \"closed S\" \"y \\<notin> S\"\n  then show \"\\<exists>U V. open U \\<and> open V \\<and> y \\<in> U \\<and> S \\<subseteq> V \\<and> U \\<inter> V = {}\"\n    using t4_space[of \"{y}\" S] by auto\nqed\n\ntext \\<open>A perfect space is a topological space with no isolated points.\\<close>\n\nclass perfect_space = topological_space +\n  assumes not_open_singleton: \"\\<not> open {x}\"\n\nlemma (in perfect_space) UNIV_not_singleton: \"UNIV \\<noteq> {x}\"\n  for x::'a\n  by (metis (no_types) open_UNIV not_open_singleton)\n\n\nsubsection \\<open>Generators for toplogies\\<close>\n\ninductive generate_topology :: \"'a set set \\<Rightarrow> 'a set \\<Rightarrow> bool\" for S :: \"'a set set\"\n  where\n    UNIV: \"generate_topology S UNIV\"\n  | Int: \"generate_topology S (a \\<inter> b)\" if \"generate_topology S a\" and \"generate_topology S b\"\n  | UN: \"generate_topology S (\\<Union>K)\" if \"(\\<And>k. k \\<in> K \\<Longrightarrow> generate_topology S k)\"\n  | Basis: \"generate_topology S s\" if \"s \\<in> S\"\n\nhide_fact (open) UNIV Int UN Basis\n\nlemma generate_topology_Union:\n  \"(\\<And>k. k \\<in> I \\<Longrightarrow> generate_topology S (K k)) \\<Longrightarrow> generate_topology S (\\<Union>k\\<in>I. K k)\"\n  using generate_topology.UN [of \"K ` I\"] by auto\n\nlemma topological_space_generate_topology: \"class.topological_space (generate_topology S)\"\n  by standard (auto intro: generate_topology.intros)\n\n\nsubsection \\<open>Order topologies\\<close>\n\nclass order_topology = order + \"open\" +\n  assumes open_generated_order: \"open = generate_topology (range (\\<lambda>a. {..< a}) \\<union> range (\\<lambda>a. {a <..}))\"\nbegin\n\nsubclass topological_space\n  unfolding open_generated_order\n  by (rule topological_space_generate_topology)\n\nlemma open_greaterThan [continuous_intros, simp]: \"open {a <..}\"\n  unfolding open_generated_order by (auto intro: generate_topology.Basis)\n\nlemma open_lessThan [continuous_intros, simp]: \"open {..< a}\"\n  unfolding open_generated_order by (auto intro: generate_topology.Basis)\n\nlemma open_greaterThanLessThan [continuous_intros, simp]: \"open {a <..< b}\"\n   unfolding greaterThanLessThan_eq by (simp add: open_Int)\n\nend\n\nclass linorder_topology = linorder + order_topology\n\nlemma closed_atMost [continuous_intros, simp]: \"closed {..a}\"\n  for a :: \"'a::linorder_topology\"\n  by (simp add: closed_open)\n\nlemma closed_atLeast [continuous_intros, simp]: \"closed {a..}\"\n  for a :: \"'a::linorder_topology\"\n  by (simp add: closed_open)\n\nlemma closed_atLeastAtMost [continuous_intros, simp]: \"closed {a..b}\"\n  for a b :: \"'a::linorder_topology\"\nproof -\n  have \"{a .. b} = {a ..} \\<inter> {.. b}\"\n    by auto\n  then show ?thesis\n    by (simp add: closed_Int)\nqed\n\nlemma (in order) less_separate:\n  assumes \"x < y\"\n  shows \"\\<exists>a b. x \\<in> {..< a} \\<and> y \\<in> {b <..} \\<and> {..< a} \\<inter> {b <..} = {}\"\nproof (cases \"\\<exists>z. x < z \\<and> z < y\")\n  case True\n  then obtain z where \"x < z \\<and> z < y\" ..\n  then have \"x \\<in> {..< z} \\<and> y \\<in> {z <..} \\<and> {z <..} \\<inter> {..< z} = {}\"\n    by auto\n  then show ?thesis by blast\nnext\n  case False\n  with \\<open>x < y\\<close> have \"x \\<in> {..< y}\" \"y \\<in> {x <..}\" \"{x <..} \\<inter> {..< y} = {}\"\n    by auto\n  then show ?thesis by blast\nqed\n\ninstance linorder_topology \\<subseteq> t2_space\nproof\n  fix x y :: 'a\n  show \"x \\<noteq> y \\<Longrightarrow> \\<exists>U V. open U \\<and> open V \\<and> x \\<in> U \\<and> y \\<in> V \\<and> U \\<inter> V = {}\"\n    using less_separate [of x y] less_separate [of y x]\n    by (elim neqE; metis open_lessThan open_greaterThan Int_commute)\nqed\n\nlemma (in linorder_topology) open_right:\n  assumes \"open S\" \"x \\<in> S\"\n    and gt_ex: \"x < y\"\n  shows \"\\<exists>b>x. {x ..< b} \\<subseteq> S\"\n  using assms unfolding open_generated_order\nproof induct\n  case UNIV\n  then show ?case by blast\nnext\n  case (Int A B)\n  then obtain a b where \"a > x\" \"{x ..< a} \\<subseteq> A\"  \"b > x\" \"{x ..< b} \\<subseteq> B\"\n    by auto\n  then show ?case\n    by (auto intro!: exI[of _ \"min a b\"])\nnext\n  case UN\n  then show ?case by blast\nnext\n  case Basis\n  then show ?case\n    by (fastforce intro: exI[of _ y] gt_ex)\nqed\n\nlemma (in linorder_topology) open_left:\n  assumes \"open S\" \"x \\<in> S\"\n    and lt_ex: \"y < x\"\n  shows \"\\<exists>b<x. {b <.. x} \\<subseteq> S\"\n  using assms unfolding open_generated_order\nproof induction\n  case UNIV\n  then show ?case by blast\nnext\n  case (Int A B)\n  then obtain a b where \"a < x\" \"{a <.. x} \\<subseteq> A\"  \"b < x\" \"{b <.. x} \\<subseteq> B\"\n    by auto\n  then show ?case\n    by (auto intro!: exI[of _ \"max a b\"])\nnext\n  case UN\n  then show ?case by blast\nnext\n  case Basis\n  then show ?case\n    by (fastforce intro: exI[of _ y] lt_ex)\nqed\n\n\nsubsection \\<open>Setup some topologies\\<close>\n\nsubsubsection \\<open>Boolean is an order topology\\<close>\n\nclass discrete_topology = topological_space +\n  assumes open_discrete: \"\\<And>A. open A\"\n\ninstance discrete_topology < t2_space\nproof\n  fix x y :: 'a\n  assume \"x \\<noteq> y\"\n  then show \"\\<exists>U V. open U \\<and> open V \\<and> x \\<in> U \\<and> y \\<in> V \\<and> U \\<inter> V = {}\"\n    by (intro exI[of _ \"{_}\"]) (auto intro!: open_discrete)\nqed\n\ninstantiation bool :: linorder_topology\nbegin\n\ndefinition open_bool :: \"bool set \\<Rightarrow> bool\"\n  where \"open_bool = generate_topology (range (\\<lambda>a. {..< a}) \\<union> range (\\<lambda>a. {a <..}))\"\n\ninstance\n  by standard (rule open_bool_def)\n\nend\n\ninstance bool :: discrete_topology\nproof\n  fix A :: \"bool set\"\n  have *: \"{False <..} = {True}\" \"{..< True} = {False}\"\n    by auto\n  have \"A = UNIV \\<or> A = {} \\<or> A = {False <..} \\<or> A = {..< True}\"\n    using subset_UNIV[of A] unfolding UNIV_bool * by blast\n  then show \"open A\"\n    by auto\nqed\n\ninstantiation nat :: linorder_topology\nbegin\n\ndefinition open_nat :: \"nat set \\<Rightarrow> bool\"\n  where \"open_nat = generate_topology (range (\\<lambda>a. {..< a}) \\<union> range (\\<lambda>a. {a <..}))\"\n\ninstance\n  by standard (rule open_nat_def)\n\nend\n\ninstance nat :: discrete_topology\nproof\n  fix A :: \"nat set\"\n  have \"open {n}\" for n :: nat\n  proof (cases n)\n    case 0\n    moreover have \"{0} = {..<1::nat}\"\n      by auto\n    ultimately show ?thesis\n       by auto\n  next\n    case (Suc n')\n    then have \"{n} = {..<Suc n} \\<inter> {n' <..}\"\n      by auto\n    with Suc show ?thesis\n      by (auto intro: open_lessThan open_greaterThan)\n  qed\n  then have \"open (\\<Union>a\\<in>A. {a})\"\n    by (intro open_UN) auto\n  then show \"open A\"\n    by simp\nqed\n\ninstantiation int :: linorder_topology\nbegin\n\ndefinition open_int :: \"int set \\<Rightarrow> bool\"\n  where \"open_int = generate_topology (range (\\<lambda>a. {..< a}) \\<union> range (\\<lambda>a. {a <..}))\"\n\ninstance\n  by standard (rule open_int_def)\n\nend\n\ninstance int :: discrete_topology\nproof\n  fix A :: \"int set\"\n  have \"{..<i + 1} \\<inter> {i-1 <..} = {i}\" for i :: int\n    by auto\n  then have \"open {i}\" for i :: int\n    using open_Int[OF open_lessThan[of \"i + 1\"] open_greaterThan[of \"i - 1\"]] by auto\n  then have \"open (\\<Union>a\\<in>A. {a})\"\n    by (intro open_UN) auto\n  then show \"open A\"\n    by simp\nqed\n\n\nsubsubsection \\<open>Topological filters\\<close>\n\ndefinition (in topological_space) nhds :: \"'a \\<Rightarrow> 'a filter\"\n  where \"nhds a = (INF S\\<in>{S. open S \\<and> a \\<in> S}. principal S)\"\n\ndefinition (in topological_space) at_within :: \"'a \\<Rightarrow> 'a set \\<Rightarrow> 'a filter\"\n    (\"at (_)/ within (_)\" [1000, 60] 60)\n  where \"at a within s = inf (nhds a) (principal (s - {a}))\"\n\nabbreviation (in topological_space) at :: \"'a \\<Rightarrow> 'a filter\"  (\"at\")\n  where \"at x \\<equiv> at x within (CONST UNIV)\"\n\nabbreviation (in order_topology) at_right :: \"'a \\<Rightarrow> 'a filter\"\n  where \"at_right x \\<equiv> at x within {x <..}\"\n\nabbreviation (in order_topology) at_left :: \"'a \\<Rightarrow> 'a filter\"\n  where \"at_left x \\<equiv> at x within {..< x}\"\n\nlemma (in topological_space) nhds_generated_topology:\n  \"open = generate_topology T \\<Longrightarrow> nhds x = (INF S\\<in>{S\\<in>T. x \\<in> S}. principal S)\"\n  unfolding nhds_def\nproof (safe intro!: antisym INF_greatest)\n  fix S\n  assume \"generate_topology T S\" \"x \\<in> S\"\n  then show \"(INF S\\<in>{S \\<in> T. x \\<in> S}. principal S) \\<le> principal S\"\n    by induct\n      (auto intro: INF_lower order_trans simp: inf_principal[symmetric] simp del: inf_principal)\nqed (auto intro!: INF_lower intro: generate_topology.intros)\n\nlemma (in topological_space) eventually_nhds:\n  \"eventually P (nhds a) \\<longleftrightarrow> (\\<exists>S. open S \\<and> a \\<in> S \\<and> (\\<forall>x\\<in>S. P x))\"\n  unfolding nhds_def by (subst eventually_INF_base) (auto simp: eventually_principal)\n\nlemma eventually_eventually:\n  \"eventually (\\<lambda>y. eventually P (nhds y)) (nhds x) = eventually P (nhds x)\"\n  by (auto simp: eventually_nhds)\n\nlemma (in topological_space) eventually_nhds_in_open:\n  \"open s \\<Longrightarrow> x \\<in> s \\<Longrightarrow> eventually (\\<lambda>y. y \\<in> s) (nhds x)\"\n  by (subst eventually_nhds) blast\n\nlemma (in topological_space) eventually_nhds_x_imp_x: \"eventually P (nhds x) \\<Longrightarrow> P x\"\n  by (subst (asm) eventually_nhds) blast\n\nlemma (in topological_space) nhds_neq_bot [simp]: \"nhds a \\<noteq> bot\"\n  by (simp add: trivial_limit_def eventually_nhds)\n\nlemma (in t1_space) t1_space_nhds: \"x \\<noteq> y \\<Longrightarrow> (\\<forall>\\<^sub>F x in nhds x. x \\<noteq> y)\"\n  by (drule t1_space) (auto simp: eventually_nhds)\n\nlemma (in topological_space) nhds_discrete_open: \"open {x} \\<Longrightarrow> nhds x = principal {x}\"\n  by (auto simp: nhds_def intro!: antisym INF_greatest INF_lower2[of \"{x}\"])\n\nlemma (in discrete_topology) nhds_discrete: \"nhds x = principal {x}\"\n  by (simp add: nhds_discrete_open open_discrete)\n\nlemma (in discrete_topology) at_discrete: \"at x within S = bot\"\n  unfolding at_within_def nhds_discrete by simp\n\nlemma (in discrete_topology) tendsto_discrete:\n  \"filterlim (f :: 'b \\<Rightarrow> 'a) (nhds y) F \\<longleftrightarrow> eventually (\\<lambda>x. f x = y) F\"\n  by (auto simp: nhds_discrete filterlim_principal)\n\nlemma (in topological_space) at_within_eq:\n  \"at x within s = (INF S\\<in>{S. open S \\<and> x \\<in> S}. principal (S \\<inter> s - {x}))\"\n  unfolding nhds_def at_within_def\n  by (subst INF_inf_const2[symmetric]) (auto simp: Diff_Int_distrib)\n\nlemma (in topological_space) eventually_at_filter:\n  \"eventually P (at a within s) \\<longleftrightarrow> eventually (\\<lambda>x. x \\<noteq> a \\<longrightarrow> x \\<in> s \\<longrightarrow> P x) (nhds a)\"\n  by (simp add: at_within_def eventually_inf_principal imp_conjL[symmetric] conj_commute)\n\nlemma (in topological_space) at_le: \"s \\<subseteq> t \\<Longrightarrow> at x within s \\<le> at x within t\"\n  unfolding at_within_def by (intro inf_mono) auto\n\nlemma (in topological_space) eventually_at_topological:\n  \"eventually P (at a within s) \\<longleftrightarrow> (\\<exists>S. open S \\<and> a \\<in> S \\<and> (\\<forall>x\\<in>S. x \\<noteq> a \\<longrightarrow> x \\<in> s \\<longrightarrow> P x))\"\n  by (simp add: eventually_nhds eventually_at_filter)\n\nlemma (in topological_space) at_within_open: \"a \\<in> S \\<Longrightarrow> open S \\<Longrightarrow> at a within S = at a\"\n  unfolding filter_eq_iff eventually_at_topological by (metis open_Int Int_iff UNIV_I)\n\nlemma (in topological_space) at_within_open_NO_MATCH:\n  \"a \\<in> s \\<Longrightarrow> open s \\<Longrightarrow> NO_MATCH UNIV s \\<Longrightarrow> at a within s = at a\"\n  by (simp only: at_within_open)\n\nlemma (in topological_space) at_within_open_subset:\n  \"a \\<in> S \\<Longrightarrow> open S \\<Longrightarrow> S \\<subseteq> T \\<Longrightarrow> at a within T = at a\"\n  by (metis at_le at_within_open dual_order.antisym subset_UNIV)\n\nlemma (in topological_space) at_within_nhd:\n  assumes \"x \\<in> S\" \"open S\" \"T \\<inter> S - {x} = U \\<inter> S - {x}\"\n  shows \"at x within T = at x within U\"\n  unfolding filter_eq_iff eventually_at_filter\nproof (intro allI eventually_subst)\n  have \"eventually (\\<lambda>x. x \\<in> S) (nhds x)\"\n    using \\<open>x \\<in> S\\<close> \\<open>open S\\<close> by (auto simp: eventually_nhds)\n  then show \"\\<forall>\\<^sub>F n in nhds x. (n \\<noteq> x \\<longrightarrow> n \\<in> T \\<longrightarrow> P n) = (n \\<noteq> x \\<longrightarrow> n \\<in> U \\<longrightarrow> P n)\" for P\n    by eventually_elim (insert \\<open>T \\<inter> S - {x} = U \\<inter> S - {x}\\<close>, blast)\nqed\n\nlemma (in topological_space) at_within_empty [simp]: \"at a within {} = bot\"\n  unfolding at_within_def by simp\n\nlemma (in topological_space) at_within_union:\n  \"at x within (S \\<union> T) = sup (at x within S) (at x within T)\"\n  unfolding filter_eq_iff eventually_sup eventually_at_filter\n  by (auto elim!: eventually_rev_mp)\n\nlemma (in topological_space) at_eq_bot_iff: \"at a = bot \\<longleftrightarrow> open {a}\"\n  unfolding trivial_limit_def eventually_at_topological\n  apply safe\n   apply (case_tac \"S = {a}\")\n    apply simp\n   apply fast\n  apply fast\n  done\n\nlemma (in perfect_space) at_neq_bot [simp]: \"at a \\<noteq> bot\"\n  by (simp add: at_eq_bot_iff not_open_singleton)\n\nlemma (in order_topology) nhds_order:\n  \"nhds x = inf (INF a\\<in>{x <..}. principal {..< a}) (INF a\\<in>{..< x}. principal {a <..})\"\nproof -\n  have 1: \"{S \\<in> range lessThan \\<union> range greaterThan. x \\<in> S} =\n      (\\<lambda>a. {..< a}) ` {x <..} \\<union> (\\<lambda>a. {a <..}) ` {..< x}\"\n    by auto\n  show ?thesis\n    by (simp only: nhds_generated_topology[OF open_generated_order] INF_union 1 INF_image comp_def)\nqed\n\nlemma (in topological_space) filterlim_at_within_If:\n  assumes \"filterlim f G (at x within (A \\<inter> {x. P x}))\"\n    and \"filterlim g G (at x within (A \\<inter> {x. \\<not>P x}))\"\n  shows \"filterlim (\\<lambda>x. if P x then f x else g x) G (at x within A)\"\nproof (rule filterlim_If)\n  note assms(1)\n  also have \"at x within (A \\<inter> {x. P x}) = inf (nhds x) (principal (A \\<inter> Collect P - {x}))\"\n    by (simp add: at_within_def)\n  also have \"A \\<inter> Collect P - {x} = (A - {x}) \\<inter> Collect P\"\n    by blast\n  also have \"inf (nhds x) (principal \\<dots>) = inf (at x within A) (principal (Collect P))\"\n    by (simp add: at_within_def inf_assoc)\n  finally show \"filterlim f G (inf (at x within A) (principal (Collect P)))\" .\nnext\n  note assms(2)\n  also have \"at x within (A \\<inter> {x. \\<not> P x}) = inf (nhds x) (principal (A \\<inter> {x. \\<not> P x} - {x}))\"\n    by (simp add: at_within_def)\n  also have \"A \\<inter> {x. \\<not> P x} - {x} = (A - {x}) \\<inter> {x. \\<not> P x}\"\n    by blast\n  also have \"inf (nhds x) (principal \\<dots>) = inf (at x within A) (principal {x. \\<not> P x})\"\n    by (simp add: at_within_def inf_assoc)\n  finally show \"filterlim g G (inf (at x within A) (principal {x. \\<not> P x}))\" .\nqed\n\nlemma (in topological_space) filterlim_at_If:\n  assumes \"filterlim f G (at x within {x. P x})\"\n    and \"filterlim g G (at x within {x. \\<not>P x})\"\n  shows \"filterlim (\\<lambda>x. if P x then f x else g x) G (at x)\"\n  using assms by (intro filterlim_at_within_If) simp_all\nlemma (in linorder_topology) at_within_order:\n  assumes \"UNIV \\<noteq> {x}\"\n  shows \"at x within s =\n    inf (INF a\\<in>{x <..}. principal ({..< a} \\<inter> s - {x}))\n        (INF a\\<in>{..< x}. principal ({a <..} \\<inter> s - {x}))\"\nproof (cases \"{x <..} = {}\" \"{..< x} = {}\" rule: case_split [case_product case_split])\n  case True_True\n  have \"UNIV = {..< x} \\<union> {x} \\<union> {x <..}\"\n    by auto\n  with assms True_True show ?thesis\n    by auto\nqed (auto simp del: inf_principal simp: at_within_def nhds_order Int_Diff\n      inf_principal[symmetric] INF_inf_const2 inf_sup_aci[where 'a=\"'a filter\"])\n\nlemma (in linorder_topology) at_left_eq:\n  \"y < x \\<Longrightarrow> at_left x = (INF a\\<in>{..< x}. principal {a <..< x})\"\n  by (subst at_within_order)\n     (auto simp: greaterThan_Int_greaterThan greaterThanLessThan_eq[symmetric] min.absorb2 INF_constant\n           intro!: INF_lower2 inf_absorb2)\n\nlemma (in linorder_topology) eventually_at_left:\n  \"y < x \\<Longrightarrow> eventually P (at_left x) \\<longleftrightarrow> (\\<exists>b<x. \\<forall>y>b. y < x \\<longrightarrow> P y)\"\n  unfolding at_left_eq\n  by (subst eventually_INF_base) (auto simp: eventually_principal Ball_def)\n\nlemma (in linorder_topology) at_right_eq:\n  \"x < y \\<Longrightarrow> at_right x = (INF a\\<in>{x <..}. principal {x <..< a})\"\n  by (subst at_within_order)\n     (auto simp: lessThan_Int_lessThan greaterThanLessThan_eq[symmetric] max.absorb2 INF_constant Int_commute\n           intro!: INF_lower2 inf_absorb1)\n\nlemma (in linorder_topology) eventually_at_right:\n  \"x < y \\<Longrightarrow> eventually P (at_right x) \\<longleftrightarrow> (\\<exists>b>x. \\<forall>y>x. y < b \\<longrightarrow> P y)\"\n  unfolding at_right_eq\n  by (subst eventually_INF_base) (auto simp: eventually_principal Ball_def)\n\nlemma eventually_at_right_less: \"\\<forall>\\<^sub>F y in at_right (x::'a::{linorder_topology, no_top}). x < y\"\n  using gt_ex[of x] eventually_at_right[of x] by auto\n\nlemma trivial_limit_at_right_top: \"at_right (top::_::{order_top,linorder_topology}) = bot\"\n  by (auto simp: filter_eq_iff eventually_at_topological)\n\nlemma trivial_limit_at_left_bot: \"at_left (bot::_::{order_bot,linorder_topology}) = bot\"\n  by (auto simp: filter_eq_iff eventually_at_topological)\n\nlemma trivial_limit_at_left_real [simp]: \"\\<not> trivial_limit (at_left x)\"\n  for x :: \"'a::{no_bot,dense_order,linorder_topology}\"\n  using lt_ex [of x]\n  by safe (auto simp add: trivial_limit_def eventually_at_left dest: dense)\n\nlemma trivial_limit_at_right_real [simp]: \"\\<not> trivial_limit (at_right x)\"\n  for x :: \"'a::{no_top,dense_order,linorder_topology}\"\n  using gt_ex[of x]\n  by safe (auto simp add: trivial_limit_def eventually_at_right dest: dense)\n\nlemma (in linorder_topology) at_eq_sup_left_right: \"at x = sup (at_left x) (at_right x)\"\n  by (auto simp: eventually_at_filter filter_eq_iff eventually_sup\n      elim: eventually_elim2 eventually_mono)\n\nlemma (in linorder_topology) eventually_at_split:\n  \"eventually P (at x) \\<longleftrightarrow> eventually P (at_left x) \\<and> eventually P (at_right x)\"\n  by (subst at_eq_sup_left_right) (simp add: eventually_sup)\n\nlemma (in order_topology) eventually_at_leftI:\n  assumes \"\\<And>x. x \\<in> {a<..<b} \\<Longrightarrow> P x\" \"a < b\"\n  shows   \"eventually P (at_left b)\"\n  using assms unfolding eventually_at_topological by (intro exI[of _ \"{a<..}\"]) auto\n\nlemma (in order_topology) eventually_at_rightI:\n  assumes \"\\<And>x. x \\<in> {a<..<b} \\<Longrightarrow> P x\" \"a < b\"\n  shows   \"eventually P (at_right a)\"\n  using assms unfolding eventually_at_topological by (intro exI[of _ \"{..<b}\"]) auto\n\nlemma eventually_filtercomap_nhds:\n  \"eventually P (filtercomap f (nhds x)) \\<longleftrightarrow> (\\<exists>S. open S \\<and> x \\<in> S \\<and> (\\<forall>x. f x \\<in> S \\<longrightarrow> P x))\"\n  unfolding eventually_filtercomap eventually_nhds by auto\n\nlemma eventually_filtercomap_at_topological:\n  \"eventually P (filtercomap f (at A within B)) \\<longleftrightarrow> \n     (\\<exists>S. open S \\<and> A \\<in> S \\<and> (\\<forall>x. f x \\<in> S \\<inter> B - {A} \\<longrightarrow> P x))\" (is \"?lhs = ?rhs\")\n  unfolding at_within_def filtercomap_inf eventually_inf_principal filtercomap_principal \n          eventually_filtercomap_nhds eventually_principal by blast\n\nlemma eventually_at_right_field:\n  \"eventually P (at_right x) \\<longleftrightarrow> (\\<exists>b>x. \\<forall>y>x. y < b \\<longrightarrow> P y)\"\n  for x :: \"'a::{linordered_field, linorder_topology}\"\n  using linordered_field_no_ub[rule_format, of x]\n  by (auto simp: eventually_at_right)\n\nlemma eventually_at_left_field:\n  \"eventually P (at_left x) \\<longleftrightarrow> (\\<exists>b<x. \\<forall>y>b. y < x \\<longrightarrow> P y)\"\n  for x :: \"'a::{linordered_field, linorder_topology}\"\n  using linordered_field_no_lb[rule_format, of x]\n  by (auto simp: eventually_at_left)\n\n\nsubsubsection \\<open>Tendsto\\<close>\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\nlemma (in topological_space) tendsto_eq_rhs: \"(f \\<longlongrightarrow> x) F \\<Longrightarrow> x = y \\<Longrightarrow> (f \\<longlongrightarrow> y) F\"\n  by simp\n\nnamed_theorems tendsto_intros \"introduction rules for tendsto\"\nsetup \\<open>\n  Global_Theory.add_thms_dynamic (\\<^binding>\\<open>tendsto_eq_intros\\<close>,\n    fn context =>\n      Named_Theorems.get (Context.proof_of context) \\<^named_theorems>\\<open>tendsto_intros\\<close>\n      |> map_filter (try (fn thm => @{thm tendsto_eq_rhs} OF [thm])))\n\\<close>\n\ncontext topological_space begin\n\nlemma tendsto_def:\n   \"(f \\<longlongrightarrow> l) F \\<longleftrightarrow> (\\<forall>S. open S \\<longrightarrow> l \\<in> S \\<longrightarrow> eventually (\\<lambda>x. f x \\<in> S) F)\"\n   unfolding nhds_def filterlim_INF filterlim_principal by auto\n\nlemma tendsto_cong: \"(f \\<longlongrightarrow> c) F \\<longleftrightarrow> (g \\<longlongrightarrow> c) F\" if \"eventually (\\<lambda>x. f x = g x) F\"\n  by (rule filterlim_cong [OF refl refl that])\n\nlemma tendsto_mono: \"F \\<le> F' \\<Longrightarrow> (f \\<longlongrightarrow> l) F' \\<Longrightarrow> (f \\<longlongrightarrow> l) F\"\n  unfolding tendsto_def le_filter_def by fast\n\nlemma tendsto_ident_at [tendsto_intros, simp, intro]: \"((\\<lambda>x. x) \\<longlongrightarrow> a) (at a within s)\"\n  by (auto simp: tendsto_def eventually_at_topological)\n\nlemma tendsto_const [tendsto_intros, simp, intro]: \"((\\<lambda>x. k) \\<longlongrightarrow> k) F\"\n  by (simp add: tendsto_def)\n\nlemma filterlim_at:\n  \"(LIM x F. f x :> at b within s) \\<longleftrightarrow> eventually (\\<lambda>x. f x \\<in> s \\<and> f x \\<noteq> b) F \\<and> (f \\<longlongrightarrow> b) F\"\n  by (simp add: at_within_def filterlim_inf filterlim_principal conj_commute)\n\nlemma (in -)\n  assumes \"filterlim f (nhds L) F\"\n  shows tendsto_imp_filterlim_at_right:\n          \"eventually (\\<lambda>x. f x > L) F \\<Longrightarrow> filterlim f (at_right L) F\"\n    and tendsto_imp_filterlim_at_left:\n          \"eventually (\\<lambda>x. f x < L) F \\<Longrightarrow> filterlim f (at_left L) F\"\n  using assms by (auto simp: filterlim_at elim: eventually_mono)\n\nlemma  filterlim_at_withinI:\n  assumes \"filterlim f (nhds c) F\"\n  assumes \"eventually (\\<lambda>x. f x \\<in> A - {c}) F\"\n  shows   \"filterlim f (at c within A) F\"\n  using assms by (simp add: filterlim_at)\n\nlemma filterlim_atI:\n  assumes \"filterlim f (nhds c) F\"\n  assumes \"eventually (\\<lambda>x. f x \\<noteq> c) F\"\n  shows   \"filterlim f (at c) F\"\n  using assms by (intro filterlim_at_withinI) simp_all\n\nlemma topological_tendstoI:\n  \"(\\<And>S. open S \\<Longrightarrow> l \\<in> S \\<Longrightarrow> eventually (\\<lambda>x. f x \\<in> S) F) \\<Longrightarrow> (f \\<longlongrightarrow> l) F\"\n  by (auto simp: tendsto_def)\n\nlemma topological_tendstoD:\n  \"(f \\<longlongrightarrow> l) F \\<Longrightarrow> open S \\<Longrightarrow> l \\<in> S \\<Longrightarrow> eventually (\\<lambda>x. f x \\<in> S) F\"\n  by (auto simp: tendsto_def)\n\nlemma tendsto_bot [simp]: \"(f \\<longlongrightarrow> a) bot\"\n  by (simp add: tendsto_def)\n\nlemma tendsto_eventually: \"eventually (\\<lambda>x. f x = l) net \\<Longrightarrow> ((\\<lambda>x. f x) \\<longlongrightarrow> l) net\"\n  by (rule topological_tendstoI) (auto elim: eventually_mono)\n\nend\n\nlemma (in topological_space) filterlim_within_subset:\n  \"filterlim f l (at x within S) \\<Longrightarrow> T \\<subseteq> S \\<Longrightarrow> filterlim f l (at x within T)\"\n  by (blast intro: filterlim_mono at_le)\n\nlemmas tendsto_within_subset = filterlim_within_subset\n\nlemma (in order_topology) order_tendsto_iff:\n  \"(f \\<longlongrightarrow> x) F \\<longleftrightarrow> (\\<forall>l<x. eventually (\\<lambda>x. l < f x) F) \\<and> (\\<forall>u>x. eventually (\\<lambda>x. f x < u) F)\"\n  by (auto simp: nhds_order filterlim_inf filterlim_INF filterlim_principal)\n\nlemma (in order_topology) order_tendstoI:\n  \"(\\<And>a. a < y \\<Longrightarrow> eventually (\\<lambda>x. a < f x) F) \\<Longrightarrow> (\\<And>a. y < a \\<Longrightarrow> eventually (\\<lambda>x. f x < a) F) \\<Longrightarrow>\n    (f \\<longlongrightarrow> y) F\"\n  by (auto simp: order_tendsto_iff)\n\nlemma (in order_topology) order_tendstoD:\n  assumes \"(f \\<longlongrightarrow> y) F\"\n  shows \"a < y \\<Longrightarrow> eventually (\\<lambda>x. a < f x) F\"\n    and \"y < a \\<Longrightarrow> eventually (\\<lambda>x. f x < a) F\"\n  using assms by (auto simp: order_tendsto_iff)\n\nlemma (in linorder_topology) tendsto_max[tendsto_intros]:\n  assumes X: \"(X \\<longlongrightarrow> x) net\"\n    and Y: \"(Y \\<longlongrightarrow> y) net\"\n  shows \"((\\<lambda>x. max (X x) (Y x)) \\<longlongrightarrow> max x y) net\"\nproof (rule order_tendstoI)\n  fix a\n  assume \"a < max x y\"\n  then show \"eventually (\\<lambda>x. a < max (X x) (Y x)) net\"\n    using order_tendstoD(1)[OF X, of a] order_tendstoD(1)[OF Y, of a]\n    by (auto simp: less_max_iff_disj elim: eventually_mono)\nnext\n  fix a\n  assume \"max x y < a\"\n  then show \"eventually (\\<lambda>x. max (X x) (Y x) < a) net\"\n    using order_tendstoD(2)[OF X, of a] order_tendstoD(2)[OF Y, of a]\n    by (auto simp: eventually_conj_iff)\nqed\n\nlemma (in linorder_topology) tendsto_min[tendsto_intros]:\n  assumes X: \"(X \\<longlongrightarrow> x) net\"\n    and Y: \"(Y \\<longlongrightarrow> y) net\"\n  shows \"((\\<lambda>x. min (X x) (Y x)) \\<longlongrightarrow> min x y) net\"\nproof (rule order_tendstoI)\n  fix a\n  assume \"a < min x y\"\n  then show \"eventually (\\<lambda>x. a < min (X x) (Y x)) net\"\n    using order_tendstoD(1)[OF X, of a] order_tendstoD(1)[OF Y, of a]\n    by (auto simp: eventually_conj_iff)\nnext\n  fix a\n  assume \"min x y < a\"\n  then show \"eventually (\\<lambda>x. min (X x) (Y x) < a) net\"\n    using order_tendstoD(2)[OF X, of a] order_tendstoD(2)[OF Y, of a]\n    by (auto simp: min_less_iff_disj elim: eventually_mono)\nqed\n\nlemma (in order_topology)\n  assumes \"a < b\"\n  shows at_within_Icc_at_right: \"at a within {a..b} = at_right a\"\n    and at_within_Icc_at_left:  \"at b within {a..b} = at_left b\"\n  using order_tendstoD(2)[OF tendsto_ident_at assms, of \"{a<..}\"]\n  using order_tendstoD(1)[OF tendsto_ident_at assms, of \"{..<b}\"]\n  by (auto intro!: order_class.antisym filter_leI\n      simp: eventually_at_filter less_le\n      elim: eventually_elim2)\n\nlemma (in order_topology) at_within_Icc_at: \"a < x \\<Longrightarrow> x < b \\<Longrightarrow> at x within {a..b} = at x\"\n  by (rule at_within_open_subset[where S=\"{a<..<b}\"]) auto\n\nlemma (in t2_space) tendsto_unique:\n  assumes \"F \\<noteq> bot\"\n    and \"(f \\<longlongrightarrow> a) F\"\n    and \"(f \\<longlongrightarrow> b) F\"\n  shows \"a = b\"\nproof (rule ccontr)\n  assume \"a \\<noteq> b\"\n  obtain U V where \"open U\" \"open V\" \"a \\<in> U\" \"b \\<in> V\" \"U \\<inter> V = {}\"\n    using hausdorff [OF \\<open>a \\<noteq> b\\<close>] by fast\n  have \"eventually (\\<lambda>x. f x \\<in> U) F\"\n    using \\<open>(f \\<longlongrightarrow> a) F\\<close> \\<open>open U\\<close> \\<open>a \\<in> U\\<close> by (rule topological_tendstoD)\n  moreover\n  have \"eventually (\\<lambda>x. f x \\<in> V) F\"\n    using \\<open>(f \\<longlongrightarrow> b) F\\<close> \\<open>open V\\<close> \\<open>b \\<in> V\\<close> by (rule topological_tendstoD)\n  ultimately\n  have \"eventually (\\<lambda>x. False) F\"\n  proof eventually_elim\n    case (elim x)\n    then have \"f x \\<in> U \\<inter> V\" by simp\n    with \\<open>U \\<inter> V = {}\\<close> show ?case by simp\n  qed\n  with \\<open>\\<not> trivial_limit F\\<close> show \"False\"\n    by (simp add: trivial_limit_def)\nqed\n\nlemma (in t2_space) tendsto_const_iff:\n  fixes a b :: 'a\n  assumes \"\\<not> trivial_limit F\"\n  shows \"((\\<lambda>x. a) \\<longlongrightarrow> b) F \\<longleftrightarrow> a = b\"\n  by (auto intro!: tendsto_unique [OF assms tendsto_const])\n\nlemma (in t2_space) tendsto_unique':\n assumes \"F \\<noteq> bot\"\n shows \"\\<exists>\\<^sub>\\<le>\\<^sub>1l. (f \\<longlongrightarrow> l) F\"\n using Uniq_def assms local.tendsto_unique by fastforce\n\nlemma Lim_in_closed_set:\n  assumes \"closed S\" \"eventually (\\<lambda>x. f(x) \\<in> S) F\" \"F \\<noteq> bot\" \"(f \\<longlongrightarrow> l) F\"\n  shows \"l \\<in> S\"\nproof (rule ccontr)\n  assume \"l \\<notin> S\"\n  with \\<open>closed S\\<close> have \"open (- S)\" \"l \\<in> - S\"\n    by (simp_all add: open_Compl)\n  with assms(4) have \"eventually (\\<lambda>x. f x \\<in> - S) F\"\n    by (rule topological_tendstoD)\n  with assms(2) have \"eventually (\\<lambda>x. False) F\"\n    by (rule eventually_elim2) simp\n  with assms(3) show \"False\"\n    by (simp add: eventually_False)\nqed\n\nlemma (in t3_space) nhds_closed:\n  assumes \"x \\<in> A\" and \"open A\"\n  shows   \"\\<exists>A'. x \\<in> A' \\<and> closed A' \\<and> A' \\<subseteq> A \\<and> eventually (\\<lambda>y. y \\<in> A') (nhds x)\"\nproof -\n  from assms have \"\\<exists>U V. open U \\<and> open V \\<and> x \\<in> U \\<and> - A \\<subseteq> V \\<and> U \\<inter> V = {}\"\n    by (intro t3_space) auto\n  then obtain U V where UV: \"open U\" \"open V\" \"x \\<in> U\" \"-A \\<subseteq> V\" \"U \\<inter> V = {}\"\n    by auto\n  have \"eventually (\\<lambda>y. y \\<in> U) (nhds x)\"\n    using \\<open>open U\\<close> and \\<open>x \\<in> U\\<close> by (intro eventually_nhds_in_open)\n  hence \"eventually (\\<lambda>y. y \\<in> -V) (nhds x)\"\n    by eventually_elim (use UV in auto)\n  with UV show ?thesis by (intro exI[of _ \"-V\"]) auto\nqed\n\nlemma (in order_topology) increasing_tendsto:\n  assumes bdd: \"eventually (\\<lambda>n. f n \\<le> l) F\"\n    and en: \"\\<And>x. x < l \\<Longrightarrow> eventually (\\<lambda>n. x < f n) F\"\n  shows \"(f \\<longlongrightarrow> l) F\"\n  using assms by (intro order_tendstoI) (auto elim!: eventually_mono)\n\nlemma (in order_topology) decreasing_tendsto:\n  assumes bdd: \"eventually (\\<lambda>n. l \\<le> f n) F\"\n    and en: \"\\<And>x. l < x \\<Longrightarrow> eventually (\\<lambda>n. f n < x) F\"\n  shows \"(f \\<longlongrightarrow> l) F\"\n  using assms by (intro order_tendstoI) (auto elim!: eventually_mono)\n\nlemma (in order_topology) tendsto_sandwich:\n  assumes ev: \"eventually (\\<lambda>n. f n \\<le> g n) net\" \"eventually (\\<lambda>n. g n \\<le> h n) net\"\n  assumes lim: \"(f \\<longlongrightarrow> c) net\" \"(h \\<longlongrightarrow> c) net\"\n  shows \"(g \\<longlongrightarrow> c) net\"\nproof (rule order_tendstoI)\n  fix a\n  show \"a < c \\<Longrightarrow> eventually (\\<lambda>x. a < g x) net\"\n    using order_tendstoD[OF lim(1), of a] ev by (auto elim: eventually_elim2)\nnext\n  fix a\n  show \"c < a \\<Longrightarrow> eventually (\\<lambda>x. g x < a) net\"\n    using order_tendstoD[OF lim(2), of a] ev by (auto elim: eventually_elim2)\nqed\n\nlemma (in t1_space) limit_frequently_eq:\n  assumes \"F \\<noteq> bot\"\n    and \"frequently (\\<lambda>x. f x = c) F\"\n    and \"(f \\<longlongrightarrow> d) F\"\n  shows \"d = c\"\nproof (rule ccontr)\n  assume \"d \\<noteq> c\"\n  from t1_space[OF this] obtain U where \"open U\" \"d \\<in> U\" \"c \\<notin> U\"\n    by blast\n  with assms have \"eventually (\\<lambda>x. f x \\<in> U) F\"\n    unfolding tendsto_def by blast\n  then have \"eventually (\\<lambda>x. f x \\<noteq> c) F\"\n    by eventually_elim (insert \\<open>c \\<notin> U\\<close>, blast)\n  with assms(2) show False\n    unfolding frequently_def by contradiction\nqed\n\nlemma (in t1_space) tendsto_imp_eventually_ne:\n  assumes  \"(f \\<longlongrightarrow> c) F\" \"c \\<noteq> c'\"\n  shows \"eventually (\\<lambda>z. f z \\<noteq> c') F\"\nproof (cases \"F=bot\")\n  case True\n  thus ?thesis by auto\nnext\n  case False\n  show ?thesis\n  proof (rule ccontr)\n    assume \"\\<not> eventually (\\<lambda>z. f z \\<noteq> c') F\"\n    then have \"frequently (\\<lambda>z. f z = c') F\"\n      by (simp add: frequently_def)\n    from limit_frequently_eq[OF False this \\<open>(f \\<longlongrightarrow> c) F\\<close>] and \\<open>c \\<noteq> c'\\<close> show False\n      by contradiction\n  qed\nqed\n\nlemma (in linorder_topology) tendsto_le:\n  assumes F: \"\\<not> trivial_limit F\"\n    and x: \"(f \\<longlongrightarrow> x) F\"\n    and y: \"(g \\<longlongrightarrow> y) F\"\n    and ev: \"eventually (\\<lambda>x. g x \\<le> f x) F\"\n  shows \"y \\<le> x\"\nproof (rule ccontr)\n  assume \"\\<not> y \\<le> x\"\n  with less_separate[of x y] obtain a b where xy: \"x < a\" \"b < y\" \"{..<a} \\<inter> {b<..} = {}\"\n    by (auto simp: not_le)\n  then have \"eventually (\\<lambda>x. f x < a) F\" \"eventually (\\<lambda>x. b < g x) F\"\n    using x y by (auto intro: order_tendstoD)\n  with ev have \"eventually (\\<lambda>x. False) F\"\n    by eventually_elim (insert xy, fastforce)\n  with F show False\n    by (simp add: eventually_False)\nqed\n\nlemma (in linorder_topology) tendsto_lowerbound:\n  assumes x: \"(f \\<longlongrightarrow> x) F\"\n      and ev: \"eventually (\\<lambda>i. a \\<le> f i) F\"\n      and F: \"\\<not> trivial_limit F\"\n  shows \"a \\<le> x\"\n  using F x tendsto_const ev by (rule tendsto_le)\n\nlemma (in linorder_topology) tendsto_upperbound:\n  assumes x: \"(f \\<longlongrightarrow> x) F\"\n      and ev: \"eventually (\\<lambda>i. a \\<ge> f i) F\"\n      and F: \"\\<not> trivial_limit F\"\n  shows \"a \\<ge> x\"\n  by (rule tendsto_le [OF F tendsto_const x ev])\n\nlemma filterlim_at_within_not_equal:\n  fixes f::\"'a \\<Rightarrow> 'b::t2_space\"\n  assumes \"filterlim f (at a within s) F\"\n  shows \"eventually (\\<lambda>w. f w\\<in>s \\<and> f w \\<noteq>b) F\"\nproof (cases \"a=b\")\n  case True\n  then show ?thesis using assms by (simp add: filterlim_at)\nnext\n  case False\n  from hausdorff[OF this] obtain U V where UV:\"open U\" \"open V\" \"a \\<in> U\" \"b \\<in> V\" \"U \\<inter> V = {}\"\n    by auto  \n  have \"(f \\<longlongrightarrow> a) F\" using assms filterlim_at by auto\n  then have \"\\<forall>\\<^sub>F x in F. f x \\<in> U\" using UV unfolding tendsto_def by auto\n  moreover have  \"\\<forall>\\<^sub>F x in F. f x \\<in> s \\<and> f x\\<noteq>a\" using assms filterlim_at by auto\n  ultimately show ?thesis \n    apply eventually_elim\n    using UV by auto\nqed\n\nsubsubsection \\<open>Rules about \\<^const>\\<open>Lim\\<close>\\<close>\n\nlemma tendsto_Lim: \"\\<not> trivial_limit net \\<Longrightarrow> (f \\<longlongrightarrow> l) net \\<Longrightarrow> Lim net f = l\"\n  unfolding Lim_def using tendsto_unique [of net f] by auto\n\nlemma Lim_ident_at: \"\\<not> trivial_limit (at x within s) \\<Longrightarrow> Lim (at x within s) (\\<lambda>x. x) = x\"\n  by (rule tendsto_Lim[OF _ tendsto_ident_at]) auto\n\nlemma eventually_Lim_ident_at:\n  \"(\\<forall>\\<^sub>F y in at x within X. P (Lim (at x within X) (\\<lambda>x. x)) y) \\<longleftrightarrow>\n    (\\<forall>\\<^sub>F y in at x within X. P x y)\" for x::\"'a::t2_space\"\n  by (cases \"at x within X = bot\") (auto simp: Lim_ident_at)\n\nlemma filterlim_at_bot_at_right:\n  fixes f :: \"'a::linorder_topology \\<Rightarrow> 'b::linorder\"\n  assumes mono: \"\\<And>x y. Q x \\<Longrightarrow> Q y \\<Longrightarrow> x \\<le> y \\<Longrightarrow> f x \\<le> f y\"\n    and bij: \"\\<And>x. P x \\<Longrightarrow> f (g x) = x\" \"\\<And>x. P x \\<Longrightarrow> Q (g x)\"\n    and Q: \"eventually Q (at_right a)\"\n    and bound: \"\\<And>b. Q b \\<Longrightarrow> a < b\"\n    and P: \"eventually P at_bot\"\n  shows \"filterlim f at_bot (at_right a)\"\nproof -\n  from P obtain x where x: \"\\<And>y. y \\<le> x \\<Longrightarrow> P y\"\n    unfolding eventually_at_bot_linorder by auto\n  show ?thesis\n  proof (intro filterlim_at_bot_le[THEN iffD2] allI impI)\n    fix z\n    assume \"z \\<le> x\"\n    with x have \"P z\" by auto\n    have \"eventually (\\<lambda>x. x \\<le> g z) (at_right a)\"\n      using bound[OF bij(2)[OF \\<open>P z\\<close>]]\n      unfolding eventually_at_right[OF bound[OF bij(2)[OF \\<open>P z\\<close>]]]\n      by (auto intro!: exI[of _ \"g z\"])\n    with Q show \"eventually (\\<lambda>x. f x \\<le> z) (at_right a)\"\n      by eventually_elim (metis bij \\<open>P z\\<close> mono)\n  qed\nqed\n\nlemma filterlim_at_top_at_left:\n  fixes f :: \"'a::linorder_topology \\<Rightarrow> 'b::linorder\"\n  assumes mono: \"\\<And>x y. Q x \\<Longrightarrow> Q y \\<Longrightarrow> x \\<le> y \\<Longrightarrow> f x \\<le> f y\"\n    and bij: \"\\<And>x. P x \\<Longrightarrow> f (g x) = x\" \"\\<And>x. P x \\<Longrightarrow> Q (g x)\"\n    and Q: \"eventually Q (at_left a)\"\n    and bound: \"\\<And>b. Q b \\<Longrightarrow> b < a\"\n    and P: \"eventually P at_top\"\n  shows \"filterlim f at_top (at_left a)\"\nproof -\n  from P obtain x where x: \"\\<And>y. x \\<le> y \\<Longrightarrow> P y\"\n    unfolding eventually_at_top_linorder by auto\n  show ?thesis\n  proof (intro filterlim_at_top_ge[THEN iffD2] allI impI)\n    fix z\n    assume \"x \\<le> z\"\n    with x have \"P z\" by auto\n    have \"eventually (\\<lambda>x. g z \\<le> x) (at_left a)\"\n      using bound[OF bij(2)[OF \\<open>P z\\<close>]]\n      unfolding eventually_at_left[OF bound[OF bij(2)[OF \\<open>P z\\<close>]]]\n      by (auto intro!: exI[of _ \"g z\"])\n    with Q show \"eventually (\\<lambda>x. z \\<le> f x) (at_left a)\"\n      by eventually_elim (metis bij \\<open>P z\\<close> mono)\n  qed\nqed\n\nlemma filterlim_split_at:\n  \"filterlim f F (at_left x) \\<Longrightarrow> filterlim f F (at_right x) \\<Longrightarrow>\n    filterlim f F (at x)\"\n  for x :: \"'a::linorder_topology\"\n  by (subst at_eq_sup_left_right) (rule filterlim_sup)\n\nlemma filterlim_at_split:\n  \"filterlim f F (at x) \\<longleftrightarrow> filterlim f F (at_left x) \\<and> filterlim f F (at_right x)\"\n  for x :: \"'a::linorder_topology\"\n  by (subst at_eq_sup_left_right) (simp add: filterlim_def filtermap_sup)\n\nlemma eventually_nhds_top:\n  fixes P :: \"'a :: {order_top,linorder_topology} \\<Rightarrow> bool\"\n    and b :: 'a\n  assumes \"b < top\"\n  shows \"eventually P (nhds top) \\<longleftrightarrow> (\\<exists>b<top. (\\<forall>z. b < z \\<longrightarrow> P z))\"\n  unfolding eventually_nhds\nproof safe\n  fix S :: \"'a set\"\n  assume \"open S\" \"top \\<in> S\"\n  note open_left[OF this \\<open>b < top\\<close>]\n  moreover assume \"\\<forall>s\\<in>S. P s\"\n  ultimately show \"\\<exists>b<top. \\<forall>z>b. P z\"\n    by (auto simp: subset_eq Ball_def)\nnext\n  fix b\n  assume \"b < top\" \"\\<forall>z>b. P z\"\n  then show \"\\<exists>S. open S \\<and> top \\<in> S \\<and> (\\<forall>xa\\<in>S. P xa)\"\n    by (intro exI[of _ \"{b <..}\"]) auto\nqed\n\nlemma tendsto_at_within_iff_tendsto_nhds:\n  \"(g \\<longlongrightarrow> g l) (at l within S) \\<longleftrightarrow> (g \\<longlongrightarrow> g l) (inf (nhds l) (principal S))\"\n  unfolding tendsto_def eventually_at_filter eventually_inf_principal\n  by (intro ext all_cong imp_cong) (auto elim!: eventually_mono)\n\n\nsubsection \\<open>Limits on sequences\\<close>\n\nabbreviation (in topological_space)\n  LIMSEQ :: \"[nat \\<Rightarrow> 'a, 'a] \\<Rightarrow> bool\"  (\"((_)/ \\<longlonglongrightarrow> (_))\" [60, 60] 60)\n  where \"X \\<longlonglongrightarrow> L \\<equiv> (X \\<longlongrightarrow> L) sequentially\"\n\nabbreviation (in t2_space) lim :: \"(nat \\<Rightarrow> 'a) \\<Rightarrow> 'a\"\n  where \"lim X \\<equiv> Lim sequentially X\"\n\ndefinition (in topological_space) convergent :: \"(nat \\<Rightarrow> 'a) \\<Rightarrow> bool\"\n  where \"convergent X = (\\<exists>L. X \\<longlonglongrightarrow> L)\"\n\nlemma lim_def: \"lim X = (THE L. X \\<longlonglongrightarrow> L)\"\n  unfolding Lim_def ..\n\nlemma lim_explicit:\n  \"f \\<longlonglongrightarrow> f0 \\<longleftrightarrow> (\\<forall>S. open S \\<longrightarrow> f0 \\<in> S \\<longrightarrow> (\\<exists>N. \\<forall>n\\<ge>N. f n \\<in> S))\"\n  unfolding tendsto_def eventually_sequentially by auto\n\n\nsubsection \\<open>Monotone sequences and subsequences\\<close>\n\ntext \\<open>\n  Definition of monotonicity.\n  The use of disjunction here complicates proofs considerably.\n  One alternative is to add a Boolean argument to indicate the direction.\n  Another is to develop the notions of increasing and decreasing first.\n\\<close>\ndefinition monoseq :: \"(nat \\<Rightarrow> 'a::order) \\<Rightarrow> bool\"\n  where \"monoseq X \\<longleftrightarrow> (\\<forall>m. \\<forall>n\\<ge>m. X m \\<le> X n) \\<or> (\\<forall>m. \\<forall>n\\<ge>m. X n \\<le> X m)\"\n\nabbreviation incseq :: \"(nat \\<Rightarrow> 'a::order) \\<Rightarrow> bool\"\n  where \"incseq X \\<equiv> mono X\"\n\nlemma incseq_def: \"incseq X \\<longleftrightarrow> (\\<forall>m. \\<forall>n\\<ge>m. X n \\<ge> X m)\"\n  unfolding mono_def ..\n\nabbreviation decseq :: \"(nat \\<Rightarrow> 'a::order) \\<Rightarrow> bool\"\n  where \"decseq X \\<equiv> antimono X\"\n\nlemma decseq_def: \"decseq X \\<longleftrightarrow> (\\<forall>m. \\<forall>n\\<ge>m. X n \\<le> X m)\"\n  unfolding antimono_def ..\n\nsubsubsection \\<open>Definition of subsequence.\\<close>\n\n(* For compatibility with the old \"subseq\" *)\nlemma strict_mono_leD: \"strict_mono r \\<Longrightarrow> m \\<le> n \\<Longrightarrow> r m \\<le> r n\"\n  by (erule (1) monoD [OF strict_mono_mono])\n\nlemma strict_mono_id: \"strict_mono id\"\n  by (simp add: strict_mono_def)\n\nlemma incseq_SucI: \"(\\<And>n. X n \\<le> X (Suc n)) \\<Longrightarrow> incseq X\"\n  using lift_Suc_mono_le[of X] by (auto simp: incseq_def)\n\nlemma incseqD: \"incseq f \\<Longrightarrow> i \\<le> j \\<Longrightarrow> f i \\<le> f j\"\n  by (auto simp: incseq_def)\n\nlemma incseq_SucD: \"incseq A \\<Longrightarrow> A i \\<le> A (Suc i)\"\n  using incseqD[of A i \"Suc i\"] by auto\n\nlemma incseq_Suc_iff: \"incseq f \\<longleftrightarrow> (\\<forall>n. f n \\<le> f (Suc n))\"\n  by (auto intro: incseq_SucI dest: incseq_SucD)\n\nlemma incseq_const[simp, intro]: \"incseq (\\<lambda>x. k)\"\n  unfolding incseq_def by auto\n\nlemma decseq_SucI: \"(\\<And>n. X (Suc n) \\<le> X n) \\<Longrightarrow> decseq X\"\n  using order.lift_Suc_mono_le[OF dual_order, of X] by (auto simp: decseq_def)\n\nlemma decseqD: \"decseq f \\<Longrightarrow> i \\<le> j \\<Longrightarrow> f j \\<le> f i\"\n  by (auto simp: decseq_def)\n\nlemma decseq_SucD: \"decseq A \\<Longrightarrow> A (Suc i) \\<le> A i\"\n  using decseqD[of A i \"Suc i\"] by auto\n\nlemma decseq_Suc_iff: \"decseq f \\<longleftrightarrow> (\\<forall>n. f (Suc n) \\<le> f n)\"\n  by (auto intro: decseq_SucI dest: decseq_SucD)\n\nlemma decseq_const[simp, intro]: \"decseq (\\<lambda>x. k)\"\n  unfolding decseq_def by auto\n\nlemma monoseq_iff: \"monoseq X \\<longleftrightarrow> incseq X \\<or> decseq X\"\n  unfolding monoseq_def incseq_def decseq_def ..\n\nlemma monoseq_Suc: \"monoseq X \\<longleftrightarrow> (\\<forall>n. X n \\<le> X (Suc n)) \\<or> (\\<forall>n. X (Suc n) \\<le> X n)\"\n  unfolding monoseq_iff incseq_Suc_iff decseq_Suc_iff ..\n\nlemma monoI1: \"\\<forall>m. \\<forall>n \\<ge> m. X m \\<le> X n \\<Longrightarrow> monoseq X\"\n  by (simp add: monoseq_def)\n\nlemma monoI2: \"\\<forall>m. \\<forall>n \\<ge> m. X n \\<le> X m \\<Longrightarrow> monoseq X\"\n  by (simp add: monoseq_def)\n\nlemma mono_SucI1: \"\\<forall>n. X n \\<le> X (Suc n) \\<Longrightarrow> monoseq X\"\n  by (simp add: monoseq_Suc)\n\nlemma mono_SucI2: \"\\<forall>n. X (Suc n) \\<le> X n \\<Longrightarrow> monoseq X\"\n  by (simp add: monoseq_Suc)\n\nlemma monoseq_minus:\n  fixes a :: \"nat \\<Rightarrow> 'a::ordered_ab_group_add\"\n  assumes \"monoseq a\"\n  shows \"monoseq (\\<lambda> n. - a n)\"\nproof (cases \"\\<forall>m. \\<forall>n \\<ge> m. a m \\<le> a n\")\n  case True\n  then have \"\\<forall>m. \\<forall>n \\<ge> m. - a n \\<le> - a m\" by auto\n  then show ?thesis by (rule monoI2)\nnext\n  case False\n  then have \"\\<forall>m. \\<forall>n \\<ge> m. - a m \\<le> - a n\"\n    using \\<open>monoseq a\\<close>[unfolded monoseq_def] by auto\n  then show ?thesis by (rule monoI1)\nqed\n\n\nsubsubsection \\<open>Subsequence (alternative definition, (e.g. Hoskins)\\<close>\n\nlemma strict_mono_Suc_iff: \"strict_mono f \\<longleftrightarrow> (\\<forall>n. f n < f (Suc n))\"\nproof (intro iffI strict_monoI)\n  assume *: \"\\<forall>n. f n < f (Suc n)\"\n  fix m n :: nat assume \"m < n\"\n  thus \"f m < f n\"\n    by (induction rule: less_Suc_induct) (use * in auto)\nqed (auto simp: strict_mono_def)\n\nlemma strict_mono_add: \"strict_mono (\\<lambda>n::'a::linordered_semidom. n + k)\"\n  by (auto simp: strict_mono_def)\n\ntext \\<open>For any sequence, there is a monotonic subsequence.\\<close>\nlemma seq_monosub:\n  fixes s :: \"nat \\<Rightarrow> 'a::linorder\"\n  shows \"\\<exists>f. strict_mono f \\<and> monoseq (\\<lambda>n. (s (f n)))\"\nproof (cases \"\\<forall>n. \\<exists>p>n. \\<forall>m\\<ge>p. s m \\<le> s p\")\n  case True\n  then have \"\\<exists>f. \\<forall>n. (\\<forall>m\\<ge>f n. s m \\<le> s (f n)) \\<and> f n < f (Suc n)\"\n    by (intro dependent_nat_choice) (auto simp: conj_commute)\n  then obtain f :: \"nat \\<Rightarrow> nat\" \n    where f: \"strict_mono f\" and mono: \"\\<And>n m. f n \\<le> m \\<Longrightarrow> s m \\<le> s (f n)\"\n    by (auto simp: strict_mono_Suc_iff)\n  then have \"incseq f\"\n    unfolding strict_mono_Suc_iff incseq_Suc_iff by (auto intro: less_imp_le)\n  then have \"monoseq (\\<lambda>n. s (f n))\"\n    by (auto simp add: incseq_def intro!: mono monoI2)\n  with f show ?thesis\n    by auto\nnext\n  case False\n  then obtain N where N: \"p > N \\<Longrightarrow> \\<exists>m>p. s p < s m\" for p\n    by (force simp: not_le le_less)\n  have \"\\<exists>f. \\<forall>n. N < f n \\<and> f n < f (Suc n) \\<and> s (f n) \\<le> s (f (Suc n))\"\n  proof (intro dependent_nat_choice)\n    fix x\n    assume \"N < x\" with N[of x]\n    show \"\\<exists>y>N. x < y \\<and> s x \\<le> s y\"\n      by (auto intro: less_trans)\n  qed auto\n  then show ?thesis\n    by (auto simp: monoseq_iff incseq_Suc_iff strict_mono_Suc_iff)\nqed\n\nlemma seq_suble:\n  assumes sf: \"strict_mono (f :: nat \\<Rightarrow> nat)\"\n  shows \"n \\<le> f n\"\nproof (induct n)\n  case 0\n  show ?case by simp\nnext\n  case (Suc n)\n  with sf [unfolded strict_mono_Suc_iff, rule_format, of n] have \"n < f (Suc n)\"\n     by arith\n  then show ?case by arith\nqed\n\nlemma eventually_subseq:\n  \"strict_mono r \\<Longrightarrow> eventually P sequentially \\<Longrightarrow> eventually (\\<lambda>n. P (r n)) sequentially\"\n  unfolding eventually_sequentially by (metis seq_suble le_trans)\n\nlemma not_eventually_sequentiallyD:\n  assumes \"\\<not> eventually P sequentially\"\n  shows \"\\<exists>r::nat\\<Rightarrow>nat. strict_mono r \\<and> (\\<forall>n. \\<not> P (r n))\"\nproof -\n  from assms have \"\\<forall>n. \\<exists>m\\<ge>n. \\<not> P m\"\n    unfolding eventually_sequentially by (simp add: not_less)\n  then obtain r where \"\\<And>n. r n \\<ge> n\" \"\\<And>n. \\<not> P (r n)\"\n    by (auto simp: choice_iff)\n  then show ?thesis\n    by (auto intro!: exI[of _ \"\\<lambda>n. r (((Suc \\<circ> r) ^^ Suc n) 0)\"]\n             simp: less_eq_Suc_le strict_mono_Suc_iff)\nqed\n\nlemma sequentially_offset: \n  assumes \"eventually (\\<lambda>i. P i) sequentially\"\n  shows \"eventually (\\<lambda>i. P (i + k)) sequentially\"\n  using assms by (rule eventually_sequentially_seg [THEN iffD2])\n\nlemma seq_offset_neg: \n  \"(f \\<longlongrightarrow> l) sequentially \\<Longrightarrow> ((\\<lambda>i. f(i - k)) \\<longlongrightarrow> l) sequentially\"\n  apply (erule filterlim_compose)\n  apply (simp add: filterlim_def le_sequentially eventually_filtermap eventually_sequentially, arith)\n  done\n\nlemma filterlim_subseq: \"strict_mono f \\<Longrightarrow> filterlim f sequentially sequentially\"\n  unfolding filterlim_iff by (metis eventually_subseq)\n\nlemma strict_mono_o: \"strict_mono r \\<Longrightarrow> strict_mono s \\<Longrightarrow> strict_mono (r \\<circ> s)\"\n  unfolding strict_mono_def by simp\n\nlemma strict_mono_compose: \"strict_mono r \\<Longrightarrow> strict_mono s \\<Longrightarrow> strict_mono (\\<lambda>x. r (s x))\"\n  using strict_mono_o[of r s] by (simp add: o_def)\n\nlemma incseq_imp_monoseq:  \"incseq X \\<Longrightarrow> monoseq X\"\n  by (simp add: incseq_def monoseq_def)\n\nlemma decseq_imp_monoseq:  \"decseq X \\<Longrightarrow> monoseq X\"\n  by (simp add: decseq_def monoseq_def)\n\nlemma decseq_eq_incseq: \"decseq X = incseq (\\<lambda>n. - X n)\"\n  for X :: \"nat \\<Rightarrow> 'a::ordered_ab_group_add\"\n  by (simp add: decseq_def incseq_def)\n\nlemma INT_decseq_offset:\n  assumes \"decseq F\"\n  shows \"(\\<Inter>i. F i) = (\\<Inter>i\\<in>{n..}. F i)\"\nproof safe\n  fix x i\n  assume x: \"x \\<in> (\\<Inter>i\\<in>{n..}. F i)\"\n  show \"x \\<in> F i\"\n  proof cases\n    from x have \"x \\<in> F n\" by auto\n    also assume \"i \\<le> n\" with \\<open>decseq F\\<close> have \"F n \\<subseteq> F i\"\n      unfolding decseq_def by simp\n    finally show ?thesis .\n  qed (insert x, simp)\nqed auto\n\nlemma LIMSEQ_const_iff: \"(\\<lambda>n. k) \\<longlonglongrightarrow> l \\<longleftrightarrow> k = l\"\n  for k l :: \"'a::t2_space\"\n  using trivial_limit_sequentially by (rule tendsto_const_iff)\n\nlemma LIMSEQ_SUP: \"incseq X \\<Longrightarrow> X \\<longlonglongrightarrow> (SUP i. X i :: 'a::{complete_linorder,linorder_topology})\"\n  by (intro increasing_tendsto)\n    (auto simp: SUP_upper less_SUP_iff incseq_def eventually_sequentially intro: less_le_trans)\n\nlemma LIMSEQ_INF: \"decseq X \\<Longrightarrow> X \\<longlonglongrightarrow> (INF i. X i :: 'a::{complete_linorder,linorder_topology})\"\n  by (intro decreasing_tendsto)\n    (auto simp: INF_lower INF_less_iff decseq_def eventually_sequentially intro: le_less_trans)\n\nlemma LIMSEQ_ignore_initial_segment: \"f \\<longlonglongrightarrow> a \\<Longrightarrow> (\\<lambda>n. f (n + k)) \\<longlonglongrightarrow> a\"\n  unfolding tendsto_def by (subst eventually_sequentially_seg[where k=k])\n\nlemma LIMSEQ_offset: \"(\\<lambda>n. f (n + k)) \\<longlonglongrightarrow> a \\<Longrightarrow> f \\<longlonglongrightarrow> a\"\n  unfolding tendsto_def\n  by (subst (asm) eventually_sequentially_seg[where k=k])\n\nlemma LIMSEQ_Suc: \"f \\<longlonglongrightarrow> l \\<Longrightarrow> (\\<lambda>n. f (Suc n)) \\<longlonglongrightarrow> l\"\n  by (drule LIMSEQ_ignore_initial_segment [where k=\"Suc 0\"]) simp\n\nlemma LIMSEQ_imp_Suc: \"(\\<lambda>n. f (Suc n)) \\<longlonglongrightarrow> l \\<Longrightarrow> f \\<longlonglongrightarrow> l\"\n  by (rule LIMSEQ_offset [where k=\"Suc 0\"]) simp\n\nlemma LIMSEQ_lessThan_iff_atMost:\n  shows \"(\\<lambda>n. f {..<n}) \\<longlonglongrightarrow> x \\<longleftrightarrow> (\\<lambda>n. f {..n}) \\<longlonglongrightarrow> x\"\n  apply (subst filterlim_sequentially_Suc [symmetric])\n  apply (simp only: lessThan_Suc_atMost)\n  done\n\nlemma (in t2_space) LIMSEQ_Uniq: \"\\<exists>\\<^sub>\\<le>\\<^sub>1l. X \\<longlonglongrightarrow> l\"\n by (simp add: tendsto_unique')\n\nlemma (in t2_space) LIMSEQ_unique: \"X \\<longlonglongrightarrow> a \\<Longrightarrow> X \\<longlonglongrightarrow> b \\<Longrightarrow> a = b\"\n  using trivial_limit_sequentially by (rule tendsto_unique)\n\nlemma LIMSEQ_le_const: \"X \\<longlonglongrightarrow> x \\<Longrightarrow> \\<exists>N. \\<forall>n\\<ge>N. a \\<le> X n \\<Longrightarrow> a \\<le> x\"\n  for a x :: \"'a::linorder_topology\"\n  by (simp add: eventually_at_top_linorder tendsto_lowerbound)\n\nlemma LIMSEQ_le: \"X \\<longlonglongrightarrow> x \\<Longrightarrow> Y \\<longlonglongrightarrow> y \\<Longrightarrow> \\<exists>N. \\<forall>n\\<ge>N. X n \\<le> Y n \\<Longrightarrow> x \\<le> y\"\n  for x y :: \"'a::linorder_topology\"\n  using tendsto_le[of sequentially Y y X x] by (simp add: eventually_sequentially)\n\nlemma LIMSEQ_le_const2: \"X \\<longlonglongrightarrow> x \\<Longrightarrow> \\<exists>N. \\<forall>n\\<ge>N. X n \\<le> a \\<Longrightarrow> x \\<le> a\"\n  for a x :: \"'a::linorder_topology\"\n  by (rule LIMSEQ_le[of X x \"\\<lambda>n. a\"]) auto\n\nlemma Lim_bounded: \"f \\<longlonglongrightarrow> l \\<Longrightarrow> \\<forall>n\\<ge>M. f n \\<le> C \\<Longrightarrow> l \\<le> C\"\n  for l :: \"'a::linorder_topology\"\n  by (intro LIMSEQ_le_const2) auto\n\nlemma Lim_bounded2:\n  fixes f :: \"nat \\<Rightarrow> 'a::linorder_topology\"\n  assumes lim:\"f \\<longlonglongrightarrow> l\" and ge: \"\\<forall>n\\<ge>N. f n \\<ge> C\"\n  shows \"l \\<ge> C\"\n  using ge\n  by (intro tendsto_le[OF trivial_limit_sequentially lim tendsto_const])\n     (auto simp: eventually_sequentially)\n\nlemma lim_mono:\n  fixes X Y :: \"nat \\<Rightarrow> 'a::linorder_topology\"\n  assumes \"\\<And>n. N \\<le> n \\<Longrightarrow> X n \\<le> Y n\"\n    and \"X \\<longlonglongrightarrow> x\"\n    and \"Y \\<longlonglongrightarrow> y\"\n  shows \"x \\<le> y\"\n  using assms(1) by (intro LIMSEQ_le[OF assms(2,3)]) auto\n\nlemma Sup_lim:\n  fixes a :: \"'a::{complete_linorder,linorder_topology}\"\n  assumes \"\\<And>n. b n \\<in> s\"\n    and \"b \\<longlonglongrightarrow> a\"\n  shows \"a \\<le> Sup s\"\n  by (metis Lim_bounded assms complete_lattice_class.Sup_upper)\n\nlemma Inf_lim:\n  fixes a :: \"'a::{complete_linorder,linorder_topology}\"\n  assumes \"\\<And>n. b n \\<in> s\"\n    and \"b \\<longlonglongrightarrow> a\"\n  shows \"Inf s \\<le> a\"\n  by (metis Lim_bounded2 assms complete_lattice_class.Inf_lower)\n\nlemma SUP_Lim:\n  fixes X :: \"nat \\<Rightarrow> 'a::{complete_linorder,linorder_topology}\"\n  assumes inc: \"incseq X\"\n    and l: \"X \\<longlonglongrightarrow> l\"\n  shows \"(SUP n. X n) = l\"\n  using LIMSEQ_SUP[OF inc] tendsto_unique[OF trivial_limit_sequentially l]\n  by simp\n\nlemma INF_Lim:\n  fixes X :: \"nat \\<Rightarrow> 'a::{complete_linorder,linorder_topology}\"\n  assumes dec: \"decseq X\"\n    and l: \"X \\<longlonglongrightarrow> l\"\n  shows \"(INF n. X n) = l\"\n  using LIMSEQ_INF[OF dec] tendsto_unique[OF trivial_limit_sequentially l]\n  by simp\n\nlemma convergentD: \"convergent X \\<Longrightarrow> \\<exists>L. X \\<longlonglongrightarrow> L\"\n  by (simp add: convergent_def)\n\nlemma convergentI: \"X \\<longlonglongrightarrow> L \\<Longrightarrow> convergent X\"\n  by (auto simp add: convergent_def)\n\nlemma convergent_LIMSEQ_iff: \"convergent X \\<longleftrightarrow> X \\<longlonglongrightarrow> lim X\"\n  by (auto intro: theI LIMSEQ_unique simp add: convergent_def lim_def)\n\nlemma convergent_const: \"convergent (\\<lambda>n. c)\"\n  by (rule convergentI) (rule tendsto_const)\n\nlemma monoseq_le:\n  \"monoseq a \\<Longrightarrow> a \\<longlonglongrightarrow> x \\<Longrightarrow>\n    (\\<forall>n. a n \\<le> x) \\<and> (\\<forall>m. \\<forall>n\\<ge>m. a m \\<le> a n) \\<or>\n    (\\<forall>n. x \\<le> a n) \\<and> (\\<forall>m. \\<forall>n\\<ge>m. a n \\<le> a m)\"\n  for x :: \"'a::linorder_topology\"\n  by (metis LIMSEQ_le_const LIMSEQ_le_const2 decseq_def incseq_def monoseq_iff)\n\nlemma LIMSEQ_subseq_LIMSEQ: \"X \\<longlonglongrightarrow> L \\<Longrightarrow> strict_mono f \\<Longrightarrow> (X \\<circ> f) \\<longlonglongrightarrow> L\"\n  unfolding comp_def by (rule filterlim_compose [of X, OF _ filterlim_subseq])\n\nlemma convergent_subseq_convergent: \"convergent X \\<Longrightarrow> strict_mono f \\<Longrightarrow> convergent (X \\<circ> f)\"\n  by (auto simp: convergent_def intro: LIMSEQ_subseq_LIMSEQ)\n\nlemma limI: \"X \\<longlonglongrightarrow> L \\<Longrightarrow> lim X = L\"\n  by (rule tendsto_Lim) (rule trivial_limit_sequentially)\n\nlemma lim_le: \"convergent f \\<Longrightarrow> (\\<And>n. f n \\<le> x) \\<Longrightarrow> lim f \\<le> x\"\n  for x :: \"'a::linorder_topology\"\n  using LIMSEQ_le_const2[of f \"lim f\" x] by (simp add: convergent_LIMSEQ_iff)\n\nlemma lim_const [simp]: \"lim (\\<lambda>m. a) = a\"\n  by (simp add: limI)\n\n\nsubsubsection \\<open>Increasing and Decreasing Series\\<close>\n\nlemma incseq_le: \"incseq X \\<Longrightarrow> X \\<longlonglongrightarrow> L \\<Longrightarrow> X n \\<le> L\"\n  for L :: \"'a::linorder_topology\"\n  by (metis incseq_def LIMSEQ_le_const)\n\nlemma decseq_ge: \"decseq X \\<Longrightarrow> X \\<longlonglongrightarrow> L \\<Longrightarrow> L \\<le> X n\"\n  for L :: \"'a::linorder_topology\"\n  by (metis decseq_def LIMSEQ_le_const2)\n\n\nsubsection \\<open>First countable topologies\\<close>\n\nclass first_countable_topology = topological_space +\n  assumes first_countable_basis:\n    \"\\<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))\"\n\nlemma (in first_countable_topology) countable_basis_at_decseq:\n  obtains A :: \"nat \\<Rightarrow> 'a set\" where\n    \"\\<And>i. open (A i)\" \"\\<And>i. x \\<in> (A i)\"\n    \"\\<And>S. open S \\<Longrightarrow> x \\<in> S \\<Longrightarrow> eventually (\\<lambda>i. A i \\<subseteq> S) sequentially\"\nproof atomize_elim\n  from first_countable_basis[of x] obtain A :: \"nat \\<Rightarrow> 'a set\"\n    where nhds: \"\\<And>i. open (A i)\" \"\\<And>i. x \\<in> A i\"\n      and incl: \"\\<And>S. open S \\<Longrightarrow> x \\<in> S \\<Longrightarrow> \\<exists>i. A i \\<subseteq> S\"\n    by auto\n  define F where \"F n = (\\<Inter>i\\<le>n. A i)\" for n\n  show \"\\<exists>A. (\\<forall>i. open (A i)) \\<and> (\\<forall>i. x \\<in> A i) \\<and>\n    (\\<forall>S. open S \\<longrightarrow> x \\<in> S \\<longrightarrow> eventually (\\<lambda>i. A i \\<subseteq> S) sequentially)\"\n  proof (safe intro!: exI[of _ F])\n    fix i\n    show \"open (F i)\"\n      using nhds(1) by (auto simp: F_def)\n    show \"x \\<in> F i\"\n      using nhds(2) by (auto simp: F_def)\n  next\n    fix S\n    assume \"open S\" \"x \\<in> S\"\n    from incl[OF this] obtain i where \"F i \\<subseteq> S\"\n      unfolding F_def by auto\n    moreover have \"\\<And>j. i \\<le> j \\<Longrightarrow> F j \\<subseteq> F i\"\n      by (simp add: Inf_superset_mono F_def image_mono)\n    ultimately show \"eventually (\\<lambda>i. F i \\<subseteq> S) sequentially\"\n      by (auto simp: eventually_sequentially)\n  qed\nqed\n\nlemma (in first_countable_topology) nhds_countable:\n  obtains X :: \"nat \\<Rightarrow> 'a set\"\n  where \"decseq X\" \"\\<And>n. open (X n)\" \"\\<And>n. x \\<in> X n\" \"nhds x = (INF n. principal (X n))\"\nproof -\n  from first_countable_basis obtain A :: \"nat \\<Rightarrow> 'a set\"\n    where *: \"\\<And>n. x \\<in> A n\" \"\\<And>n. open (A n)\" \"\\<And>S. open S \\<Longrightarrow> x \\<in> S \\<Longrightarrow> \\<exists>i. A i \\<subseteq> S\"\n    by metis\n  show thesis\n  proof\n    show \"decseq (\\<lambda>n. \\<Inter>i\\<le>n. A i)\"\n      by (simp add: antimono_iff_le_Suc atMost_Suc)\n    show \"x \\<in> (\\<Inter>i\\<le>n. A i)\" \"\\<And>n. open (\\<Inter>i\\<le>n. A i)\" for n\n      using * by auto\n    show \"nhds x = (INF n. principal (\\<Inter>i\\<le>n. A i))\"\n      using *\n      unfolding nhds_def\n      apply -\n      apply (rule INF_eq)\n       apply simp_all\n       apply fastforce\n      apply (intro exI [of _ \"\\<Inter>i\\<le>n. A i\" for n] conjI open_INT)\n         apply auto\n      done\n  qed\nqed\n\nlemma (in first_countable_topology) countable_basis:\n  obtains A :: \"nat \\<Rightarrow> 'a set\" where\n    \"\\<And>i. open (A i)\" \"\\<And>i. x \\<in> A i\"\n    \"\\<And>F. (\\<forall>n. F n \\<in> A n) \\<Longrightarrow> F \\<longlonglongrightarrow> x\"\nproof atomize_elim\n  obtain A :: \"nat \\<Rightarrow> 'a set\" where *:\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 (rule countable_basis_at_decseq) blast\n  have \"eventually (\\<lambda>n. F n \\<in> S) sequentially\"\n    if \"\\<forall>n. F n \\<in> A n\" \"open S\" \"x \\<in> S\" for F S\n    using *(3)[of S] that by (auto elim: eventually_mono simp: subset_eq)\n  with * show \"\\<exists>A. (\\<forall>i. open (A i)) \\<and> (\\<forall>i. x \\<in> A i) \\<and> (\\<forall>F. (\\<forall>n. F n \\<in> A n) \\<longrightarrow> F \\<longlonglongrightarrow> x)\"\n    by (intro exI[of _ A]) (auto simp: tendsto_def)\nqed\n\nlemma (in first_countable_topology) sequentially_imp_eventually_nhds_within:\n  assumes \"\\<forall>f. (\\<forall>n. f n \\<in> s) \\<and> f \\<longlonglongrightarrow> a \\<longrightarrow> eventually (\\<lambda>n. P (f n)) sequentially\"\n  shows \"eventually P (inf (nhds a) (principal s))\"\nproof (rule ccontr)\n  obtain A :: \"nat \\<Rightarrow> 'a set\" where *:\n    \"\\<And>i. open (A i)\"\n    \"\\<And>i. a \\<in> A i\"\n    \"\\<And>F. \\<forall>n. F n \\<in> A n \\<Longrightarrow> F \\<longlonglongrightarrow> a\"\n    by (rule countable_basis) blast\n  assume \"\\<not> ?thesis\"\n  with * have \"\\<exists>F. \\<forall>n. F n \\<in> s \\<and> F n \\<in> A n \\<and> \\<not> P (F n)\"\n    unfolding eventually_inf_principal eventually_nhds\n    by (intro choice) fastforce\n  then obtain F where F: \"\\<forall>n. F n \\<in> s\" and \"\\<forall>n. F n \\<in> A n\" and F': \"\\<forall>n. \\<not> P (F n)\"\n    by blast\n  with * have \"F \\<longlonglongrightarrow> a\"\n    by auto\n  then have \"eventually (\\<lambda>n. P (F n)) sequentially\"\n    using assms F by simp\n  then show False\n    by (simp add: F')\nqed\n\nlemma (in first_countable_topology) eventually_nhds_within_iff_sequentially:\n  \"eventually P (inf (nhds a) (principal s)) \\<longleftrightarrow>\n    (\\<forall>f. (\\<forall>n. f n \\<in> s) \\<and> f \\<longlonglongrightarrow> a \\<longrightarrow> eventually (\\<lambda>n. P (f n)) sequentially)\"\nproof (safe intro!: sequentially_imp_eventually_nhds_within)\n  assume \"eventually P (inf (nhds a) (principal s))\"\n  then obtain S where \"open S\" \"a \\<in> S\" \"\\<forall>x\\<in>S. x \\<in> s \\<longrightarrow> P x\"\n    by (auto simp: eventually_inf_principal eventually_nhds)\n  moreover\n  fix f\n  assume \"\\<forall>n. f n \\<in> s\" \"f \\<longlonglongrightarrow> a\"\n  ultimately show \"eventually (\\<lambda>n. P (f n)) sequentially\"\n    by (auto dest!: topological_tendstoD elim: eventually_mono)\nqed\n\nlemma (in first_countable_topology) eventually_nhds_iff_sequentially:\n  \"eventually P (nhds a) \\<longleftrightarrow> (\\<forall>f. f \\<longlonglongrightarrow> a \\<longrightarrow> eventually (\\<lambda>n. P (f n)) sequentially)\"\n  using eventually_nhds_within_iff_sequentially[of P a UNIV] by simp\n\n(*Thanks to S\u00e9bastien Gou\u00ebzel*)\nlemma Inf_as_limit:\n  fixes A::\"'a::{linorder_topology, first_countable_topology, complete_linorder} set\"\n  assumes \"A \\<noteq> {}\"\n  shows \"\\<exists>u. (\\<forall>n. u n \\<in> A) \\<and> u \\<longlonglongrightarrow> Inf A\"\nproof (cases \"Inf A \\<in> A\")\n  case True\n  show ?thesis\n    by (rule exI[of _ \"\\<lambda>n. Inf A\"], auto simp add: True)\nnext\n  case False\n  obtain y where \"y \\<in> A\" using assms by auto\n  then have \"Inf A < y\" using False Inf_lower less_le by auto\n  obtain F :: \"nat \\<Rightarrow> 'a set\" where F: \"\\<And>i. open (F i)\" \"\\<And>i. Inf A \\<in> F i\"\n                                       \"\\<And>u. (\\<forall>n. u n \\<in> F n) \\<Longrightarrow> u \\<longlonglongrightarrow> Inf A\"\n    by (metis first_countable_topology_class.countable_basis)\n  define u where \"u = (\\<lambda>n. SOME z. z \\<in> F n \\<and> z \\<in> A)\"\n  have \"\\<exists>z. z \\<in> U \\<and> z \\<in> A\" if \"Inf A \\<in> U\" \"open U\" for U\n  proof -\n    obtain b where \"b > Inf A\" \"{Inf A ..<b} \\<subseteq> U\"\n      using open_right[OF \\<open>open U\\<close> \\<open>Inf A \\<in> U\\<close> \\<open>Inf A < y\\<close>] by auto\n    obtain z where \"z < b\" \"z \\<in> A\"\n      using \\<open>Inf A < b\\<close> Inf_less_iff by auto\n    then have \"z \\<in> {Inf A ..<b}\"\n      by (simp add: Inf_lower)\n    then show ?thesis using \\<open>z \\<in> A\\<close> \\<open>{Inf A ..<b} \\<subseteq> U\\<close> by auto\n  qed\n  then have *: \"u n \\<in> F n \\<and> u n \\<in> A\" for n\n    using \\<open>Inf A \\<in> F n\\<close> \\<open>open (F n)\\<close> unfolding u_def by (metis (no_types, lifting) someI_ex)\n  then have \"u \\<longlonglongrightarrow> Inf A\" using F(3) by simp\n  then show ?thesis using * by auto\nqed\n\nlemma tendsto_at_iff_sequentially:\n  \"(f \\<longlongrightarrow> a) (at x within s) \\<longleftrightarrow> (\\<forall>X. (\\<forall>i. X i \\<in> s - {x}) \\<longrightarrow> X \\<longlonglongrightarrow> x \\<longrightarrow> ((f \\<circ> X) \\<longlonglongrightarrow> a))\"\n  for f :: \"'a::first_countable_topology \\<Rightarrow> _\"\n  unfolding filterlim_def[of _ \"nhds a\"] le_filter_def eventually_filtermap\n    at_within_def eventually_nhds_within_iff_sequentially comp_def\n  by metis\n\nlemma approx_from_above_dense_linorder:\n  fixes x::\"'a::{dense_linorder, linorder_topology, first_countable_topology}\"\n  assumes \"x < y\"\n  shows \"\\<exists>u. (\\<forall>n. u n > x) \\<and> (u \\<longlonglongrightarrow> x)\"\nproof -\n  obtain A :: \"nat \\<Rightarrow> 'a set\" where A: \"\\<And>i. open (A i)\" \"\\<And>i. x \\<in> A i\"\n                                      \"\\<And>F. (\\<forall>n. F n \\<in> A n) \\<Longrightarrow> F \\<longlonglongrightarrow> x\"\n    by (metis first_countable_topology_class.countable_basis)\n  define u where \"u = (\\<lambda>n. SOME z. z \\<in> A n \\<and> z > x)\"\n  have \"\\<exists>z. z \\<in> U \\<and> x < z\" if \"x \\<in> U\" \"open U\" for U\n    using open_right[OF \\<open>open U\\<close> \\<open>x \\<in> U\\<close> \\<open>x < y\\<close>]\n    by (meson atLeastLessThan_iff dense less_imp_le subset_eq)\n  then have *: \"u n \\<in> A n \\<and> x < u n\" for n\n    using \\<open>x \\<in> A n\\<close> \\<open>open (A n)\\<close> unfolding u_def by (metis (no_types, lifting) someI_ex)\n  then have \"u \\<longlonglongrightarrow> x\" using A(3) by simp\n  then show ?thesis using * by auto\nqed\n\nlemma approx_from_below_dense_linorder:\n  fixes x::\"'a::{dense_linorder, linorder_topology, first_countable_topology}\"\n  assumes \"x > y\"\n  shows \"\\<exists>u. (\\<forall>n. u n < x) \\<and> (u \\<longlonglongrightarrow> x)\"\nproof -\n  obtain A :: \"nat \\<Rightarrow> 'a set\" where A: \"\\<And>i. open (A i)\" \"\\<And>i. x \\<in> A i\"\n                                      \"\\<And>F. (\\<forall>n. F n \\<in> A n) \\<Longrightarrow> F \\<longlonglongrightarrow> x\"\n    by (metis first_countable_topology_class.countable_basis)\n  define u where \"u = (\\<lambda>n. SOME z. z \\<in> A n \\<and> z < x)\"\n  have \"\\<exists>z. z \\<in> U \\<and> z < x\" if \"x \\<in> U\" \"open U\" for U\n    using open_left[OF \\<open>open U\\<close> \\<open>x \\<in> U\\<close> \\<open>x > y\\<close>]\n    by (meson dense greaterThanAtMost_iff less_imp_le subset_eq)\n  then have *: \"u n \\<in> A n \\<and> u n < x\" for n\n    using \\<open>x \\<in> A n\\<close> \\<open>open (A n)\\<close> unfolding u_def by (metis (no_types, lifting) someI_ex)\n  then have \"u \\<longlonglongrightarrow> x\" using A(3) by simp\n  then show ?thesis using * by auto\nqed\n\n\nsubsection \\<open>Function limit at a point\\<close>\n\nabbreviation LIM :: \"('a::topological_space \\<Rightarrow> 'b::topological_space) \\<Rightarrow> 'a \\<Rightarrow> 'b \\<Rightarrow> bool\"\n    (\"((_)/ \\<midarrow>(_)/\\<rightarrow> (_))\" [60, 0, 60] 60)\n  where \"f \\<midarrow>a\\<rightarrow> L \\<equiv> (f \\<longlongrightarrow> L) (at a)\"\n\nlemma tendsto_within_open: \"a \\<in> S \\<Longrightarrow> open S \\<Longrightarrow> (f \\<longlongrightarrow> l) (at a within S) \\<longleftrightarrow> (f \\<midarrow>a\\<rightarrow> l)\"\n  by (simp add: tendsto_def at_within_open[where S = S])\n\nlemma tendsto_within_open_NO_MATCH:\n  \"a \\<in> S \\<Longrightarrow> NO_MATCH UNIV S \\<Longrightarrow> open S \\<Longrightarrow> (f \\<longlongrightarrow> l)(at a within S) \\<longleftrightarrow> (f \\<longlongrightarrow> l)(at a)\"\n  for f :: \"'a::topological_space \\<Rightarrow> 'b::topological_space\"\n  using tendsto_within_open by blast\n\nlemma LIM_const_not_eq[tendsto_intros]: \"k \\<noteq> L \\<Longrightarrow> \\<not> (\\<lambda>x. k) \\<midarrow>a\\<rightarrow> L\"\n  for a :: \"'a::perfect_space\" and k L :: \"'b::t2_space\"\n  by (simp add: tendsto_const_iff)\n\nlemmas LIM_not_zero = LIM_const_not_eq [where L = 0]\n\nlemma LIM_const_eq: \"(\\<lambda>x. k) \\<midarrow>a\\<rightarrow> L \\<Longrightarrow> k = L\"\n  for a :: \"'a::perfect_space\" and k L :: \"'b::t2_space\"\n  by (simp add: tendsto_const_iff)\n\nlemma LIM_unique: \"f \\<midarrow>a\\<rightarrow> L \\<Longrightarrow> f \\<midarrow>a\\<rightarrow> M \\<Longrightarrow> L = M\"\n  for a :: \"'a::perfect_space\" and L M :: \"'b::t2_space\"\n  using at_neq_bot by (rule tendsto_unique)\n\nlemma LIM_Uniq: \"\\<exists>\\<^sub>\\<le>\\<^sub>1L::'b::t2_space. f \\<midarrow>a\\<rightarrow> L\"\n  for a :: \"'a::perfect_space\"\n by (auto simp add: Uniq_def LIM_unique)\n\n\ntext \\<open>Limits are equal for functions equal except at limit point.\\<close>\nlemma LIM_equal: \"\\<forall>x. x \\<noteq> a \\<longrightarrow> f x = g x \\<Longrightarrow> (f \\<midarrow>a\\<rightarrow> l) \\<longleftrightarrow> (g \\<midarrow>a\\<rightarrow> l)\"\n  by (simp add: tendsto_def eventually_at_topological)\n\nlemma LIM_cong: \"a = b \\<Longrightarrow> (\\<And>x. x \\<noteq> b \\<Longrightarrow> f x = g x) \\<Longrightarrow> l = m \\<Longrightarrow> (f \\<midarrow>a\\<rightarrow> l) \\<longleftrightarrow> (g \\<midarrow>b\\<rightarrow> m)\"\n  by (simp add: LIM_equal)\n\nlemma tendsto_cong_limit: \"(f \\<longlongrightarrow> l) F \\<Longrightarrow> k = l \\<Longrightarrow> (f \\<longlongrightarrow> k) F\"\n  by simp\n\nlemma tendsto_at_iff_tendsto_nhds: \"g \\<midarrow>l\\<rightarrow> g l \\<longleftrightarrow> (g \\<longlongrightarrow> g l) (nhds l)\"\n  unfolding tendsto_def eventually_at_filter\n  by (intro ext all_cong imp_cong) (auto elim!: eventually_mono)\n\nlemma tendsto_compose: \"g \\<midarrow>l\\<rightarrow> g l \\<Longrightarrow> (f \\<longlongrightarrow> l) F \\<Longrightarrow> ((\\<lambda>x. g (f x)) \\<longlongrightarrow> g l) F\"\n  unfolding tendsto_at_iff_tendsto_nhds by (rule filterlim_compose[of g])\n\nlemma tendsto_compose_eventually:\n  \"g \\<midarrow>l\\<rightarrow> m \\<Longrightarrow> (f \\<longlongrightarrow> l) F \\<Longrightarrow> eventually (\\<lambda>x. f x \\<noteq> l) F \\<Longrightarrow> ((\\<lambda>x. g (f x)) \\<longlongrightarrow> m) F\"\n  by (rule filterlim_compose[of g _ \"at l\"]) (auto simp add: filterlim_at)\n\nlemma LIM_compose_eventually:\n  assumes \"f \\<midarrow>a\\<rightarrow> b\"\n    and \"g \\<midarrow>b\\<rightarrow> c\"\n    and \"eventually (\\<lambda>x. f x \\<noteq> b) (at a)\"\n  shows \"(\\<lambda>x. g (f x)) \\<midarrow>a\\<rightarrow> c\"\n  using assms(2,1,3) by (rule tendsto_compose_eventually)\n\nlemma tendsto_compose_filtermap: \"((g \\<circ> f) \\<longlongrightarrow> T) F \\<longleftrightarrow> (g \\<longlongrightarrow> T) (filtermap f F)\"\n  by (simp add: filterlim_def filtermap_filtermap comp_def)\n\nlemma tendsto_compose_at:\n  assumes f: \"(f \\<longlongrightarrow> y) F\" and g: \"(g \\<longlongrightarrow> z) (at y)\" and fg: \"eventually (\\<lambda>w. f w = y \\<longrightarrow> g y = z) F\"\n  shows \"((g \\<circ> f) \\<longlongrightarrow> z) F\"\nproof -\n  have \"(\\<forall>\\<^sub>F a in F. f a \\<noteq> y) \\<or> g y = z\"\n    using fg by force\n  moreover have \"(g \\<longlongrightarrow> z) (filtermap f F) \\<or> \\<not> (\\<forall>\\<^sub>F a in F. f a \\<noteq> y)\"\n    by (metis (no_types) filterlim_atI filterlim_def tendsto_mono f g)\n  ultimately show ?thesis\n    by (metis (no_types) f filterlim_compose filterlim_filtermap g tendsto_at_iff_tendsto_nhds tendsto_compose_filtermap)\nqed\n\n\nsubsubsection \\<open>Relation of \\<open>LIM\\<close> and \\<open>LIMSEQ\\<close>\\<close>\n\nlemma (in first_countable_topology) sequentially_imp_eventually_within:\n  \"(\\<forall>f. (\\<forall>n. f n \\<in> s \\<and> f n \\<noteq> a) \\<and> f \\<longlonglongrightarrow> a \\<longrightarrow> eventually (\\<lambda>n. P (f n)) sequentially) \\<Longrightarrow>\n    eventually P (at a within s)\"\n  unfolding at_within_def\n  by (intro sequentially_imp_eventually_nhds_within) auto\n\nlemma (in first_countable_topology) sequentially_imp_eventually_at:\n  \"(\\<forall>f. (\\<forall>n. f n \\<noteq> a) \\<and> f \\<longlonglongrightarrow> a \\<longrightarrow> eventually (\\<lambda>n. P (f n)) sequentially) \\<Longrightarrow> eventually P (at a)\"\n  using sequentially_imp_eventually_within [where s=UNIV] by simp\n\nlemma LIMSEQ_SEQ_conv1:\n  fixes f :: \"'a::topological_space \\<Rightarrow> 'b::topological_space\"\n  assumes f: \"f \\<midarrow>a\\<rightarrow> l\"\n  shows \"\\<forall>S. (\\<forall>n. S n \\<noteq> a) \\<and> S \\<longlonglongrightarrow> a \\<longrightarrow> (\\<lambda>n. f (S n)) \\<longlonglongrightarrow> l\"\n  using tendsto_compose_eventually [OF f, where F=sequentially] by simp\n\nlemma LIMSEQ_SEQ_conv2:\n  fixes f :: \"'a::first_countable_topology \\<Rightarrow> 'b::topological_space\"\n  assumes \"\\<forall>S. (\\<forall>n. S n \\<noteq> a) \\<and> S \\<longlonglongrightarrow> a \\<longrightarrow> (\\<lambda>n. f (S n)) \\<longlonglongrightarrow> l\"\n  shows \"f \\<midarrow>a\\<rightarrow> l\"\n  using assms unfolding tendsto_def [where l=l] by (simp add: sequentially_imp_eventually_at)\n\nlemma LIMSEQ_SEQ_conv: \"(\\<forall>S. (\\<forall>n. S n \\<noteq> a) \\<and> S \\<longlonglongrightarrow> a \\<longrightarrow> (\\<lambda>n. X (S n)) \\<longlonglongrightarrow> L) \\<longleftrightarrow> X \\<midarrow>a\\<rightarrow> L\"\n  for a :: \"'a::first_countable_topology\" and L :: \"'b::topological_space\"\n  using LIMSEQ_SEQ_conv2 LIMSEQ_SEQ_conv1 ..\n\nlemma sequentially_imp_eventually_at_left:\n  fixes a :: \"'a::{linorder_topology,first_countable_topology}\"\n  assumes b[simp]: \"b < a\"\n    and *: \"\\<And>f. (\\<And>n. b < f n) \\<Longrightarrow> (\\<And>n. f n < a) \\<Longrightarrow> incseq f \\<Longrightarrow> f \\<longlonglongrightarrow> a \\<Longrightarrow>\n      eventually (\\<lambda>n. P (f n)) sequentially\"\n  shows \"eventually P (at_left a)\"\nproof (safe intro!: sequentially_imp_eventually_within)\n  fix X\n  assume X: \"\\<forall>n. X n \\<in> {..< a} \\<and> X n \\<noteq> a\" \"X \\<longlonglongrightarrow> a\"\n  show \"eventually (\\<lambda>n. P (X n)) sequentially\"\n  proof (rule ccontr)\n    assume neg: \"\\<not> ?thesis\"\n    have \"\\<exists>s. \\<forall>n. (\\<not> P (X (s n)) \\<and> b < X (s n)) \\<and> (X (s n) \\<le> X (s (Suc n)) \\<and> Suc (s n) \\<le> s (Suc n))\"\n      (is \"\\<exists>s. ?P s\")\n    proof (rule dependent_nat_choice)\n      have \"\\<not> eventually (\\<lambda>n. b < X n \\<longrightarrow> P (X n)) sequentially\"\n        by (intro not_eventually_impI neg order_tendstoD(1) [OF X(2) b])\n      then show \"\\<exists>x. \\<not> P (X x) \\<and> b < X x\"\n        by (auto dest!: not_eventuallyD)\n    next\n      fix x n\n      have \"\\<not> eventually (\\<lambda>n. Suc x \\<le> n \\<longrightarrow> b < X n \\<longrightarrow> X x < X n \\<longrightarrow> P (X n)) sequentially\"\n        using X\n        by (intro not_eventually_impI order_tendstoD(1)[OF X(2)] eventually_ge_at_top neg) auto\n      then show \"\\<exists>n. (\\<not> P (X n) \\<and> b < X n) \\<and> (X x \\<le> X n \\<and> Suc x \\<le> n)\"\n        by (auto dest!: not_eventuallyD)\n    qed\n    then obtain s where \"?P s\" ..\n    with X have \"b < X (s n)\"\n      and \"X (s n) < a\"\n      and \"incseq (\\<lambda>n. X (s n))\"\n      and \"(\\<lambda>n. X (s n)) \\<longlonglongrightarrow> a\"\n      and \"\\<not> P (X (s n))\"\n      for n\n      by (auto simp: strict_mono_Suc_iff Suc_le_eq incseq_Suc_iff\n          intro!: LIMSEQ_subseq_LIMSEQ[OF \\<open>X \\<longlonglongrightarrow> a\\<close>, unfolded comp_def])\n    from *[OF this(1,2,3,4)] this(5) show False\n      by auto\n  qed\nqed\n\nlemma tendsto_at_left_sequentially:\n  fixes a b :: \"'b::{linorder_topology,first_countable_topology}\"\n  assumes \"b < a\"\n  assumes *: \"\\<And>S. (\\<And>n. S n < a) \\<Longrightarrow> (\\<And>n. b < S n) \\<Longrightarrow> incseq S \\<Longrightarrow> S \\<longlonglongrightarrow> a \\<Longrightarrow>\n    (\\<lambda>n. X (S n)) \\<longlonglongrightarrow> L\"\n  shows \"(X \\<longlongrightarrow> L) (at_left a)\"\n  using assms by (simp add: tendsto_def [where l=L] sequentially_imp_eventually_at_left)\n\nlemma sequentially_imp_eventually_at_right:\n  fixes a b :: \"'a::{linorder_topology,first_countable_topology}\"\n  assumes b[simp]: \"a < b\"\n  assumes *: \"\\<And>f. (\\<And>n. a < f n) \\<Longrightarrow> (\\<And>n. f n < b) \\<Longrightarrow> decseq f \\<Longrightarrow> f \\<longlonglongrightarrow> a \\<Longrightarrow>\n    eventually (\\<lambda>n. P (f n)) sequentially\"\n  shows \"eventually P (at_right a)\"\nproof (safe intro!: sequentially_imp_eventually_within)\n  fix X\n  assume X: \"\\<forall>n. X n \\<in> {a <..} \\<and> X n \\<noteq> a\" \"X \\<longlonglongrightarrow> a\"\n  show \"eventually (\\<lambda>n. P (X n)) sequentially\"\n  proof (rule ccontr)\n    assume neg: \"\\<not> ?thesis\"\n    have \"\\<exists>s. \\<forall>n. (\\<not> P (X (s n)) \\<and> X (s n) < b) \\<and> (X (s (Suc n)) \\<le> X (s n) \\<and> Suc (s n) \\<le> s (Suc n))\"\n      (is \"\\<exists>s. ?P s\")\n    proof (rule dependent_nat_choice)\n      have \"\\<not> eventually (\\<lambda>n. X n < b \\<longrightarrow> P (X n)) sequentially\"\n        by (intro not_eventually_impI neg order_tendstoD(2) [OF X(2) b])\n      then show \"\\<exists>x. \\<not> P (X x) \\<and> X x < b\"\n        by (auto dest!: not_eventuallyD)\n    next\n      fix x n\n      have \"\\<not> eventually (\\<lambda>n. Suc x \\<le> n \\<longrightarrow> X n < b \\<longrightarrow> X n < X x \\<longrightarrow> P (X n)) sequentially\"\n        using X\n        by (intro not_eventually_impI order_tendstoD(2)[OF X(2)] eventually_ge_at_top neg) auto\n      then show \"\\<exists>n. (\\<not> P (X n) \\<and> X n < b) \\<and> (X n \\<le> X x \\<and> Suc x \\<le> n)\"\n        by (auto dest!: not_eventuallyD)\n    qed\n    then obtain s where \"?P s\" ..\n    with X have \"a < X (s n)\"\n      and \"X (s n) < b\"\n      and \"decseq (\\<lambda>n. X (s n))\"\n      and \"(\\<lambda>n. X (s n)) \\<longlonglongrightarrow> a\"\n      and \"\\<not> P (X (s n))\"\n      for n\n      by (auto simp: strict_mono_Suc_iff Suc_le_eq decseq_Suc_iff\n          intro!: LIMSEQ_subseq_LIMSEQ[OF \\<open>X \\<longlonglongrightarrow> a\\<close>, unfolded comp_def])\n    from *[OF this(1,2,3,4)] this(5) show False\n      by auto\n  qed\nqed\n\nlemma tendsto_at_right_sequentially:\n  fixes a :: \"_ :: {linorder_topology, first_countable_topology}\"\n  assumes \"a < b\"\n    and *: \"\\<And>S. (\\<And>n. a < S n) \\<Longrightarrow> (\\<And>n. S n < b) \\<Longrightarrow> decseq S \\<Longrightarrow> S \\<longlonglongrightarrow> a \\<Longrightarrow>\n      (\\<lambda>n. X (S n)) \\<longlonglongrightarrow> L\"\n  shows \"(X \\<longlongrightarrow> L) (at_right a)\"\n  using assms by (simp add: tendsto_def [where l=L] sequentially_imp_eventually_at_right)\n\n\nsubsection \\<open>Continuity\\<close>\n\nsubsubsection \\<open>Continuity on a set\\<close>\n\ndefinition continuous_on :: \"'a set \\<Rightarrow> ('a::topological_space \\<Rightarrow> 'b::topological_space) \\<Rightarrow> bool\"\n  where \"continuous_on s f \\<longleftrightarrow> (\\<forall>x\\<in>s. (f \\<longlongrightarrow> f x) (at x within s))\"\n\nlemma continuous_on_cong [cong]:\n  \"s = t \\<Longrightarrow> (\\<And>x. x \\<in> t \\<Longrightarrow> f x = g x) \\<Longrightarrow> continuous_on s f \\<longleftrightarrow> continuous_on t g\"\n  unfolding continuous_on_def\n  by (intro ball_cong filterlim_cong) (auto simp: eventually_at_filter)\n\nlemma continuous_on_cong_simp:\n  \"s = t \\<Longrightarrow> (\\<And>x. x \\<in> t =simp=> f x = g x) \\<Longrightarrow> continuous_on s f \\<longleftrightarrow> continuous_on t g\"\n  unfolding simp_implies_def by (rule continuous_on_cong)\n\nlemma continuous_on_topological:\n  \"continuous_on s f \\<longleftrightarrow>\n    (\\<forall>x\\<in>s. \\<forall>B. open B \\<longrightarrow> f x \\<in> B \\<longrightarrow> (\\<exists>A. open A \\<and> x \\<in> A \\<and> (\\<forall>y\\<in>s. y \\<in> A \\<longrightarrow> f y \\<in> B)))\"\n  unfolding continuous_on_def tendsto_def eventually_at_topological by metis\n\nlemma continuous_on_open_invariant:\n  \"continuous_on s f \\<longleftrightarrow> (\\<forall>B. open B \\<longrightarrow> (\\<exists>A. open A \\<and> A \\<inter> s = f -` B \\<inter> s))\"\nproof safe\n  fix B :: \"'b set\"\n  assume \"continuous_on s f\" \"open B\"\n  then have \"\\<forall>x\\<in>f -` B \\<inter> s. (\\<exists>A. open A \\<and> x \\<in> A \\<and> s \\<inter> A \\<subseteq> f -` B)\"\n    by (auto simp: continuous_on_topological subset_eq Ball_def imp_conjL)\n  then obtain A where \"\\<forall>x\\<in>f -` B \\<inter> s. open (A x) \\<and> x \\<in> A x \\<and> s \\<inter> A x \\<subseteq> f -` B\"\n    unfolding bchoice_iff ..\n  then show \"\\<exists>A. open A \\<and> A \\<inter> s = f -` B \\<inter> s\"\n    by (intro exI[of _ \"\\<Union>x\\<in>f -` B \\<inter> s. A x\"]) auto\nnext\n  assume B: \"\\<forall>B. open B \\<longrightarrow> (\\<exists>A. open A \\<and> A \\<inter> s = f -` B \\<inter> s)\"\n  show \"continuous_on s f\"\n    unfolding continuous_on_topological\n  proof safe\n    fix x B\n    assume \"x \\<in> s\" \"open B\" \"f x \\<in> B\"\n    with B obtain A where A: \"open A\" \"A \\<inter> s = f -` B \\<inter> s\"\n      by auto\n    with \\<open>x \\<in> s\\<close> \\<open>f x \\<in> B\\<close> show \"\\<exists>A. open A \\<and> x \\<in> A \\<and> (\\<forall>y\\<in>s. y \\<in> A \\<longrightarrow> f y \\<in> B)\"\n      by (intro exI[of _ A]) auto\n  qed\nqed\n\nlemma continuous_on_open_vimage:\n  \"open s \\<Longrightarrow> continuous_on s f \\<longleftrightarrow> (\\<forall>B. open B \\<longrightarrow> open (f -` B \\<inter> s))\"\n  unfolding continuous_on_open_invariant\n  by (metis open_Int Int_absorb Int_commute[of s] Int_assoc[of _ _ s])\n\ncorollary continuous_imp_open_vimage:\n  assumes \"continuous_on s f\" \"open s\" \"open B\" \"f -` B \\<subseteq> s\"\n  shows \"open (f -` B)\"\n  by (metis assms continuous_on_open_vimage le_iff_inf)\n\ncorollary open_vimage[continuous_intros]:\n  assumes \"open s\"\n    and \"continuous_on UNIV f\"\n  shows \"open (f -` s)\"\n  using assms by (simp add: continuous_on_open_vimage [OF open_UNIV])\n\nlemma continuous_on_closed_invariant:\n  \"continuous_on s f \\<longleftrightarrow> (\\<forall>B. closed B \\<longrightarrow> (\\<exists>A. closed A \\<and> A \\<inter> s = f -` B \\<inter> s))\"\nproof -\n  have *: \"(\\<And>A. P A \\<longleftrightarrow> Q (- A)) \\<Longrightarrow> (\\<forall>A. P A) \\<longleftrightarrow> (\\<forall>A. Q A)\"\n    for P Q :: \"'b set \\<Rightarrow> bool\"\n    by (metis double_compl)\n  show ?thesis\n    unfolding continuous_on_open_invariant\n    by (intro *) (auto simp: open_closed[symmetric])\nqed\n\nlemma continuous_on_closed_vimage:\n  \"closed s \\<Longrightarrow> continuous_on s f \\<longleftrightarrow> (\\<forall>B. closed B \\<longrightarrow> closed (f -` B \\<inter> s))\"\n  unfolding continuous_on_closed_invariant\n  by (metis closed_Int Int_absorb Int_commute[of s] Int_assoc[of _ _ s])\n\ncorollary closed_vimage_Int[continuous_intros]:\n  assumes \"closed s\"\n    and \"continuous_on t f\"\n    and t: \"closed t\"\n  shows \"closed (f -` s \\<inter> t)\"\n  using assms by (simp add: continuous_on_closed_vimage [OF t])\n\ncorollary closed_vimage[continuous_intros]:\n  assumes \"closed s\"\n    and \"continuous_on UNIV f\"\n  shows \"closed (f -` s)\"\n  using closed_vimage_Int [OF assms] by simp\n\nlemma continuous_on_empty [simp]: \"continuous_on {} f\"\n  by (simp add: continuous_on_def)\n\nlemma continuous_on_sing [simp]: \"continuous_on {x} f\"\n  by (simp add: continuous_on_def at_within_def)\n\nlemma continuous_on_open_Union:\n  \"(\\<And>s. s \\<in> S \\<Longrightarrow> open s) \\<Longrightarrow> (\\<And>s. s \\<in> S \\<Longrightarrow> continuous_on s f) \\<Longrightarrow> continuous_on (\\<Union>S) f\"\n  unfolding continuous_on_def\n  by safe (metis open_Union at_within_open UnionI)\n\nlemma continuous_on_open_UN:\n  \"(\\<And>s. s \\<in> S \\<Longrightarrow> open (A s)) \\<Longrightarrow> (\\<And>s. s \\<in> S \\<Longrightarrow> continuous_on (A s) f) \\<Longrightarrow>\n    continuous_on (\\<Union>s\\<in>S. A s) f\"\n  by (rule continuous_on_open_Union) auto\n\nlemma continuous_on_open_Un:\n  \"open s \\<Longrightarrow> open t \\<Longrightarrow> continuous_on s f \\<Longrightarrow> continuous_on t f \\<Longrightarrow> continuous_on (s \\<union> t) f\"\n  using continuous_on_open_Union [of \"{s,t}\"] by auto\n\nlemma continuous_on_closed_Un:\n  \"closed s \\<Longrightarrow> closed t \\<Longrightarrow> continuous_on s f \\<Longrightarrow> continuous_on t f \\<Longrightarrow> continuous_on (s \\<union> t) f\"\n  by (auto simp add: continuous_on_closed_vimage closed_Un Int_Un_distrib)\n\nlemma continuous_on_closed_Union:\n  assumes \"finite I\"\n    \"\\<And>i. i \\<in> I \\<Longrightarrow> closed (U i)\"\n    \"\\<And>i. i \\<in> I \\<Longrightarrow> continuous_on (U i) f\"\n  shows \"continuous_on (\\<Union> i \\<in> I. U i) f\"\n  using assms\n  by (induction I) (auto intro!: continuous_on_closed_Un)\n\nlemma continuous_on_If:\n  assumes closed: \"closed s\" \"closed t\"\n    and cont: \"continuous_on s f\" \"continuous_on t g\"\n    and P: \"\\<And>x. x \\<in> s \\<Longrightarrow> \\<not> P x \\<Longrightarrow> f x = g x\" \"\\<And>x. x \\<in> t \\<Longrightarrow> P x \\<Longrightarrow> f x = g x\"\n  shows \"continuous_on (s \\<union> t) (\\<lambda>x. if P x then f x else g x)\"\n    (is \"continuous_on _ ?h\")\nproof-\n  from P have \"\\<forall>x\\<in>s. f x = ?h x\" \"\\<forall>x\\<in>t. g x = ?h x\"\n    by auto\n  with cont have \"continuous_on s ?h\" \"continuous_on t ?h\"\n    by simp_all\n  with closed show ?thesis\n    by (rule continuous_on_closed_Un)\nqed\n\nlemma continuous_on_cases:\n  \"closed s \\<Longrightarrow> closed t \\<Longrightarrow> continuous_on s f \\<Longrightarrow> continuous_on t g \\<Longrightarrow>\n    \\<forall>x. (x\\<in>s \\<and> \\<not> P x) \\<or> (x \\<in> t \\<and> P x) \\<longrightarrow> f x = g x \\<Longrightarrow>\n    continuous_on (s \\<union> t) (\\<lambda>x. if P x then f x else g x)\"\n  by (rule continuous_on_If) auto\n\nlemma continuous_on_id[continuous_intros,simp]: \"continuous_on s (\\<lambda>x. x)\"\n  unfolding continuous_on_def by fast\n\nlemma continuous_on_id'[continuous_intros,simp]: \"continuous_on s id\"\n  unfolding continuous_on_def id_def by fast\n\nlemma continuous_on_const[continuous_intros,simp]: \"continuous_on s (\\<lambda>x. c)\"\n  unfolding continuous_on_def by auto\n\nlemma continuous_on_subset: \"continuous_on s f \\<Longrightarrow> t \\<subseteq> s \\<Longrightarrow> continuous_on t f\"\n  unfolding continuous_on_def\n  by (metis subset_eq tendsto_within_subset)\n\nlemma continuous_on_compose[continuous_intros]:\n  \"continuous_on s f \\<Longrightarrow> continuous_on (f ` s) g \\<Longrightarrow> continuous_on s (g \\<circ> f)\"\n  unfolding continuous_on_topological by simp metis\n\nlemma continuous_on_compose2:\n  \"continuous_on t g \\<Longrightarrow> continuous_on s f \\<Longrightarrow> f ` s \\<subseteq> t \\<Longrightarrow> continuous_on s (\\<lambda>x. g (f x))\"\n  using continuous_on_compose[of s f g] continuous_on_subset by (force simp add: comp_def)\n\nlemma continuous_on_generate_topology:\n  assumes *: \"open = generate_topology X\"\n    and **: \"\\<And>B. B \\<in> X \\<Longrightarrow> \\<exists>C. open C \\<and> C \\<inter> A = f -` B \\<inter> A\"\n  shows \"continuous_on A f\"\n  unfolding continuous_on_open_invariant\nproof safe\n  fix B :: \"'a set\"\n  assume \"open B\"\n  then show \"\\<exists>C. open C \\<and> C \\<inter> A = f -` B \\<inter> A\"\n    unfolding *\n  proof induct\n    case (UN K)\n    then obtain C where \"\\<And>k. k \\<in> K \\<Longrightarrow> open (C k)\" \"\\<And>k. k \\<in> K \\<Longrightarrow> C k \\<inter> A = f -` k \\<inter> A\"\n      by metis\n    then show ?case\n      by (intro exI[of _ \"\\<Union>k\\<in>K. C k\"]) blast\n  qed (auto intro: **)\nqed\n\nlemma continuous_onI_mono:\n  fixes f :: \"'a::linorder_topology \\<Rightarrow> 'b::{dense_order,linorder_topology}\"\n  assumes \"open (f`A)\"\n    and mono: \"\\<And>x y. x \\<in> A \\<Longrightarrow> y \\<in> A \\<Longrightarrow> x \\<le> y \\<Longrightarrow> f x \\<le> f y\"\n  shows \"continuous_on A f\"\nproof (rule continuous_on_generate_topology[OF open_generated_order], safe)\n  have monoD: \"\\<And>x y. x \\<in> A \\<Longrightarrow> y \\<in> A \\<Longrightarrow> f x < f y \\<Longrightarrow> x < y\"\n    by (auto simp: not_le[symmetric] mono)\n  have \"\\<exists>x. x \\<in> A \\<and> f x < b \\<and> a < x\" if a: \"a \\<in> A\" and fa: \"f a < b\" for a b\n  proof -\n    obtain y where \"f a < y\" \"{f a ..< y} \\<subseteq> f`A\"\n      using open_right[OF \\<open>open (f`A)\\<close>, of \"f a\" b] a fa\n      by auto\n    obtain z where z: \"f a < z\" \"z < min b y\"\n      using dense[of \"f a\" \"min b y\"] \\<open>f a < y\\<close> \\<open>f a < b\\<close> by auto\n    then obtain c where \"z = f c\" \"c \\<in> A\"\n      using \\<open>{f a ..< y} \\<subseteq> f`A\\<close>[THEN subsetD, of z] by (auto simp: less_imp_le)\n    with a z show ?thesis\n      by (auto intro!: exI[of _ c] simp: monoD)\n  qed\n  then show \"\\<exists>C. open C \\<and> C \\<inter> A = f -` {..<b} \\<inter> A\" for b\n    by (intro exI[of _ \"(\\<Union>x\\<in>{x\\<in>A. f x < b}. {..< x})\"])\n       (auto intro: le_less_trans[OF mono] less_imp_le)\n\n  have \"\\<exists>x. x \\<in> A \\<and> b < f x \\<and> x < a\" if a: \"a \\<in> A\" and fa: \"b < f a\" for a b\n  proof -\n    note a fa\n    moreover\n    obtain y where \"y < f a\" \"{y <.. f a} \\<subseteq> f`A\"\n      using open_left[OF \\<open>open (f`A)\\<close>, of \"f a\" b]  a fa\n      by auto\n    then obtain z where z: \"max b y < z\" \"z < f a\"\n      using dense[of \"max b y\" \"f a\"] \\<open>y < f a\\<close> \\<open>b < f a\\<close> by auto\n    then obtain c where \"z = f c\" \"c \\<in> A\"\n      using \\<open>{y <.. f a} \\<subseteq> f`A\\<close>[THEN subsetD, of z] by (auto simp: less_imp_le)\n    with a z show ?thesis\n      by (auto intro!: exI[of _ c] simp: monoD)\n  qed\n  then show \"\\<exists>C. open C \\<and> C \\<inter> A = f -` {b <..} \\<inter> A\" for b\n    by (intro exI[of _ \"(\\<Union>x\\<in>{x\\<in>A. b < f x}. {x <..})\"])\n       (auto intro: less_le_trans[OF _ mono] less_imp_le)\nqed\n\nlemma continuous_on_IccI:\n  \"\\<lbrakk>(f \\<longlongrightarrow> f a) (at_right a);\n    (f \\<longlongrightarrow> f b) (at_left b);\n    (\\<And>x. a < x \\<Longrightarrow> x < b \\<Longrightarrow> f \\<midarrow>x\\<rightarrow> f x); a < b\\<rbrakk> \\<Longrightarrow>\n    continuous_on {a .. b} f\"\n  for a::\"'a::linorder_topology\"\n  using at_within_open[of _ \"{a<..<b}\"]\n  by (auto simp: continuous_on_def at_within_Icc_at_right at_within_Icc_at_left le_less\n      at_within_Icc_at)\n\nlemma\n  fixes a b::\"'a::linorder_topology\"\n  assumes \"continuous_on {a .. b} f\" \"a < b\"\n  shows continuous_on_Icc_at_rightD: \"(f \\<longlongrightarrow> f a) (at_right a)\"\n    and continuous_on_Icc_at_leftD: \"(f \\<longlongrightarrow> f b) (at_left b)\"\n  using assms\n  by (auto simp: at_within_Icc_at_right at_within_Icc_at_left continuous_on_def\n      dest: bspec[where x=a] bspec[where x=b])\n\nlemma continuous_on_discrete [simp]:\n  \"continuous_on A (f :: 'a :: discrete_topology \\<Rightarrow> _)\"\n  by (auto simp: continuous_on_def at_discrete)\n\nsubsubsection \\<open>Continuity at a point\\<close>\n\ndefinition continuous :: \"'a::t2_space filter \\<Rightarrow> ('a \\<Rightarrow> 'b::topological_space) \\<Rightarrow> bool\"\n  where \"continuous F f \\<longleftrightarrow> (f \\<longlongrightarrow> f (Lim F (\\<lambda>x. x))) F\"\n\nlemma continuous_bot[continuous_intros, simp]: \"continuous bot f\"\n  unfolding continuous_def by auto\n\nlemma continuous_trivial_limit: \"trivial_limit net \\<Longrightarrow> continuous net f\"\n  by simp\n\nlemma continuous_within: \"continuous (at x within s) f \\<longleftrightarrow> (f \\<longlongrightarrow> f x) (at x within s)\"\n  by (cases \"trivial_limit (at x within s)\") (auto simp add: Lim_ident_at continuous_def)\n\nlemma continuous_within_topological:\n  \"continuous (at x within s) f \\<longleftrightarrow>\n    (\\<forall>B. open B \\<longrightarrow> f x \\<in> B \\<longrightarrow> (\\<exists>A. open A \\<and> x \\<in> A \\<and> (\\<forall>y\\<in>s. y \\<in> A \\<longrightarrow> f y \\<in> B)))\"\n  unfolding continuous_within tendsto_def eventually_at_topological by metis\n\nlemma continuous_within_compose[continuous_intros]:\n  \"continuous (at x within s) f \\<Longrightarrow> continuous (at (f x) within f ` s) g \\<Longrightarrow>\n    continuous (at x within s) (g \\<circ> f)\"\n  by (simp add: continuous_within_topological) metis\n\nlemma continuous_within_compose2:\n  \"continuous (at x within s) f \\<Longrightarrow> continuous (at (f x) within f ` s) g \\<Longrightarrow>\n    continuous (at x within s) (\\<lambda>x. g (f x))\"\n  using continuous_within_compose[of x s f g] by (simp add: comp_def)\n\nlemma continuous_at: \"continuous (at x) f \\<longleftrightarrow> f \\<midarrow>x\\<rightarrow> f x\"\n  using continuous_within[of x UNIV f] by simp\n\nlemma continuous_ident[continuous_intros, simp]: \"continuous (at x within S) (\\<lambda>x. x)\"\n  unfolding continuous_within by (rule tendsto_ident_at)\n\nlemma continuous_id[continuous_intros, simp]: \"continuous (at x within S) id\"\n  by (simp add: id_def)\n\nlemma continuous_const[continuous_intros, simp]: \"continuous F (\\<lambda>x. c)\"\n  unfolding continuous_def by (rule tendsto_const)\n\nlemma continuous_on_eq_continuous_within:\n  \"continuous_on s f \\<longleftrightarrow> (\\<forall>x\\<in>s. continuous (at x within s) f)\"\n  unfolding continuous_on_def continuous_within ..\n\nlemma continuous_discrete [simp]:\n  \"continuous (at x within A) (f :: 'a :: discrete_topology \\<Rightarrow> _)\"\n  by (auto simp: continuous_def at_discrete)\n\nabbreviation isCont :: \"('a::t2_space \\<Rightarrow> 'b::topological_space) \\<Rightarrow> 'a \\<Rightarrow> bool\"\n  where \"isCont f a \\<equiv> continuous (at a) f\"\n\nlemma isCont_def: \"isCont f a \\<longleftrightarrow> f \\<midarrow>a\\<rightarrow> f a\"\n  by (rule continuous_at)\n\nlemma isContD: \"isCont f x \\<Longrightarrow> f \\<midarrow>x\\<rightarrow> f x\"\n  by (simp add: isCont_def)\n\nlemma isCont_cong:\n  assumes \"eventually (\\<lambda>x. f x = g x) (nhds x)\"\n  shows \"isCont f x \\<longleftrightarrow> isCont g x\"\nproof -\n  from assms have [simp]: \"f x = g x\"\n    by (rule eventually_nhds_x_imp_x)\n  from assms have \"eventually (\\<lambda>x. f x = g x) (at x)\"\n    by (auto simp: eventually_at_filter elim!: eventually_mono)\n  with assms have \"isCont f x \\<longleftrightarrow> isCont g x\" unfolding isCont_def\n    by (intro filterlim_cong) (auto elim!: eventually_mono)\n  with assms show ?thesis by simp\nqed\n\nlemma continuous_at_imp_continuous_at_within: \"isCont f x \\<Longrightarrow> continuous (at x within s) f\"\n  by (auto intro: tendsto_mono at_le simp: continuous_at continuous_within)\n\nlemma continuous_on_eq_continuous_at: \"open s \\<Longrightarrow> continuous_on s f \\<longleftrightarrow> (\\<forall>x\\<in>s. isCont f x)\"\n  by (simp add: continuous_on_def continuous_at at_within_open[of _ s])\n\nlemma continuous_within_open: \"a \\<in> A \\<Longrightarrow> open A \\<Longrightarrow> continuous (at a within A) f \\<longleftrightarrow> isCont f a\"\n  by (simp add: at_within_open_NO_MATCH)\n\nlemma continuous_at_imp_continuous_on: \"\\<forall>x\\<in>s. isCont f x \\<Longrightarrow> continuous_on s f\"\n  by (auto intro: continuous_at_imp_continuous_at_within simp: continuous_on_eq_continuous_within)\n\nlemma isCont_o2: \"isCont f a \\<Longrightarrow> isCont g (f a) \\<Longrightarrow> isCont (\\<lambda>x. g (f x)) a\"\n  unfolding isCont_def by (rule tendsto_compose)\n\nlemma continuous_at_compose[continuous_intros]: \"isCont f a \\<Longrightarrow> isCont g (f a) \\<Longrightarrow> isCont (g \\<circ> f) a\"\n  unfolding o_def by (rule isCont_o2)\n\nlemma isCont_tendsto_compose: \"isCont g l \\<Longrightarrow> (f \\<longlongrightarrow> l) F \\<Longrightarrow> ((\\<lambda>x. g (f x)) \\<longlongrightarrow> g l) F\"\n  unfolding isCont_def by (rule tendsto_compose)\n\nlemma continuous_on_tendsto_compose:\n  assumes f_cont: \"continuous_on s f\"\n    and g: \"(g \\<longlongrightarrow> l) F\"\n    and l: \"l \\<in> s\"\n    and ev: \"\\<forall>\\<^sub>Fx in F. g x \\<in> s\"\n  shows \"((\\<lambda>x. f (g x)) \\<longlongrightarrow> f l) F\"\nproof -\n  from f_cont l have f: \"(f \\<longlongrightarrow> f l) (at l within s)\"\n    by (simp add: continuous_on_def)\n  have i: \"((\\<lambda>x. if g x = l then f l else f (g x)) \\<longlongrightarrow> f l) F\"\n    by (rule filterlim_If)\n       (auto intro!: filterlim_compose[OF f] eventually_conj tendsto_mono[OF _ g]\n             simp: filterlim_at eventually_inf_principal eventually_mono[OF ev])\n  show ?thesis\n    by (rule filterlim_cong[THEN iffD1[OF _ i]]) auto\nqed\n\nlemma continuous_within_compose3:\n  \"isCont g (f x) \\<Longrightarrow> continuous (at x within s) f \\<Longrightarrow> continuous (at x within s) (\\<lambda>x. g (f x))\"\n  using continuous_at_imp_continuous_at_within continuous_within_compose2 by blast\n\nlemma filtermap_nhds_open_map:\n  assumes cont: \"isCont f a\"\n    and open_map: \"\\<And>S. open S \\<Longrightarrow> open (f`S)\"\n  shows \"filtermap f (nhds a) = nhds (f a)\"\n  unfolding filter_eq_iff\nproof safe\n  fix P\n  assume \"eventually P (filtermap f (nhds a))\"\n  then obtain S where \"open S\" \"a \\<in> S\" \"\\<forall>x\\<in>S. P (f x)\"\n    by (auto simp: eventually_filtermap eventually_nhds)\n  then show \"eventually P (nhds (f a))\"\n    unfolding eventually_nhds by (intro exI[of _ \"f`S\"]) (auto intro!: open_map)\nqed (metis filterlim_iff tendsto_at_iff_tendsto_nhds isCont_def eventually_filtermap cont)\n\nlemma continuous_at_split:\n  \"continuous (at x) f \\<longleftrightarrow> continuous (at_left x) f \\<and> continuous (at_right x) f\"\n  for x :: \"'a::linorder_topology\"\n  by (simp add: continuous_within filterlim_at_split)\n\nlemma continuous_on_max [continuous_intros]:\n  fixes f g :: \"'a::topological_space \\<Rightarrow> 'b::linorder_topology\"\n  shows \"continuous_on A f \\<Longrightarrow> continuous_on A g \\<Longrightarrow> continuous_on A (\\<lambda>x. max (f x) (g x))\"\n  by (auto simp: continuous_on_def intro!: tendsto_max)\n\nlemma continuous_on_min [continuous_intros]:\n  fixes f g :: \"'a::topological_space \\<Rightarrow> 'b::linorder_topology\"\n  shows \"continuous_on A f \\<Longrightarrow> continuous_on A g \\<Longrightarrow> continuous_on A (\\<lambda>x. min (f x) (g x))\"\n  by (auto simp: continuous_on_def intro!: tendsto_min)\n\nlemma continuous_max [continuous_intros]:\n  fixes f :: \"'a::t2_space \\<Rightarrow> 'b::linorder_topology\"\n  shows \"\\<lbrakk>continuous F f; continuous F g\\<rbrakk> \\<Longrightarrow> continuous F (\\<lambda>x. (max (f x) (g x)))\"\n  by (simp add: tendsto_max continuous_def)\n\nlemma continuous_min [continuous_intros]:\n  fixes f :: \"'a::t2_space \\<Rightarrow> 'b::linorder_topology\"\n  shows \"\\<lbrakk>continuous F f; continuous F g\\<rbrakk> \\<Longrightarrow> continuous F (\\<lambda>x. (min (f x) (g x)))\"\n  by (simp add: tendsto_min continuous_def)\n\ntext \\<open>\n  The following open/closed Collect lemmas are ported from\n  S\u00e9bastien Gou\u00ebzel's \\<open>Ergodic_Theory\\<close>.\n\\<close>\nlemma open_Collect_neq:\n  fixes f g :: \"'a::topological_space \\<Rightarrow> 'b::t2_space\"\n  assumes f: \"continuous_on UNIV f\" and g: \"continuous_on UNIV g\"\n  shows \"open {x. f x \\<noteq> g x}\"\nproof (rule openI)\n  fix t\n  assume \"t \\<in> {x. f x \\<noteq> g x}\"\n  then obtain U V where *: \"open U\" \"open V\" \"f t \\<in> U\" \"g t \\<in> V\" \"U \\<inter> V = {}\"\n    by (auto simp add: separation_t2)\n  with open_vimage[OF \\<open>open U\\<close> f] open_vimage[OF \\<open>open V\\<close> g]\n  show \"\\<exists>T. open T \\<and> t \\<in> T \\<and> T \\<subseteq> {x. f x \\<noteq> g x}\"\n    by (intro exI[of _ \"f -` U \\<inter> g -` V\"]) auto\nqed\n\nlemma closed_Collect_eq:\n  fixes f g :: \"'a::topological_space \\<Rightarrow> 'b::t2_space\"\n  assumes f: \"continuous_on UNIV f\" and g: \"continuous_on UNIV g\"\n  shows \"closed {x. f x = g x}\"\n  using open_Collect_neq[OF f g] by (simp add: closed_def Collect_neg_eq)\n\nlemma open_Collect_less:\n  fixes f g :: \"'a::topological_space \\<Rightarrow> 'b::linorder_topology\"\n  assumes f: \"continuous_on UNIV f\" and g: \"continuous_on UNIV g\"\n  shows \"open {x. f x < g x}\"\nproof (rule openI)\n  fix t\n  assume t: \"t \\<in> {x. f x < g x}\"\n  show \"\\<exists>T. open T \\<and> t \\<in> T \\<and> T \\<subseteq> {x. f x < g x}\"\n  proof (cases \"\\<exists>z. f t < z \\<and> z < g t\")\n    case True\n    then obtain z where \"f t < z \\<and> z < g t\" by blast\n    then show ?thesis\n      using open_vimage[OF _ f, of \"{..< z}\"] open_vimage[OF _ g, of \"{z <..}\"]\n      by (intro exI[of _ \"f -` {..<z} \\<inter> g -` {z<..}\"]) auto\n  next\n    case False\n    then have *: \"{g t ..} = {f t <..}\" \"{..< g t} = {.. f t}\"\n      using t by (auto intro: leI)\n    show ?thesis\n      using open_vimage[OF _ f, of \"{..< g t}\"] open_vimage[OF _ g, of \"{f t <..}\"] t\n      apply (intro exI[of _ \"f -` {..< g t} \\<inter> g -` {f t<..}\"])\n      apply (simp add: open_Int)\n      apply (auto simp add: *)\n      done\n  qed\nqed\n\nlemma closed_Collect_le:\n  fixes f g :: \"'a :: topological_space \\<Rightarrow> 'b::linorder_topology\"\n  assumes f: \"continuous_on UNIV f\"\n    and g: \"continuous_on UNIV g\"\n  shows \"closed {x. f x \\<le> g x}\"\n  using open_Collect_less [OF g f]\n  by (simp add: closed_def Collect_neg_eq[symmetric] not_le)\n\n\nsubsubsection \\<open>Open-cover compactness\\<close>\n\ncontext topological_space\nbegin\n\ndefinition compact :: \"'a set \\<Rightarrow> bool\" where\ncompact_eq_Heine_Borel:  (* This name is used for backwards compatibility *)\n    \"compact S \\<longleftrightarrow> (\\<forall>C. (\\<forall>c\\<in>C. open c) \\<and> S \\<subseteq> \\<Union>C \\<longrightarrow> (\\<exists>D\\<subseteq>C. finite D \\<and> S \\<subseteq> \\<Union>D))\"\n\nlemma compactI:\n  assumes \"\\<And>C. \\<forall>t\\<in>C. open t \\<Longrightarrow> s \\<subseteq> \\<Union>C \\<Longrightarrow> \\<exists>C'. C' \\<subseteq> C \\<and> finite C' \\<and> s \\<subseteq> \\<Union>C'\"\n  shows \"compact s\"\n  unfolding compact_eq_Heine_Borel using assms by metis\n\nlemma compact_empty[simp]: \"compact {}\"\n  by (auto intro!: compactI)\n\nlemma compactE: (*related to COMPACT_IMP_HEINE_BOREL in HOL Light*)\n  assumes \"compact S\" \"S \\<subseteq> \\<Union>\\<T>\" \"\\<And>B. B \\<in> \\<T> \\<Longrightarrow> open B\"\n  obtains \\<T>' where \"\\<T>' \\<subseteq> \\<T>\" \"finite \\<T>'\" \"S \\<subseteq> \\<Union>\\<T>'\"\n  by (meson assms compact_eq_Heine_Borel)\n\nlemma compactE_image:\n  assumes \"compact S\"\n    and opn: \"\\<And>T. T \\<in> C \\<Longrightarrow> open (f T)\"\n    and S: \"S \\<subseteq> (\\<Union>c\\<in>C. f c)\"\n  obtains C' where \"C' \\<subseteq> C\" and \"finite C'\" and \"S \\<subseteq> (\\<Union>c\\<in>C'. f c)\"\n    apply (rule compactE[OF \\<open>compact S\\<close> S])\n    using opn apply force\n    by (metis finite_subset_image)\n\nlemma compact_Int_closed [intro]:\n  assumes \"compact S\"\n    and \"closed T\"\n  shows \"compact (S \\<inter> T)\"\nproof (rule compactI)\n  fix C\n  assume C: \"\\<forall>c\\<in>C. open c\"\n  assume cover: \"S \\<inter> T \\<subseteq> \\<Union>C\"\n  from C \\<open>closed T\\<close> have \"\\<forall>c\\<in>C \\<union> {- T}. open c\"\n    by auto\n  moreover from cover have \"S \\<subseteq> \\<Union>(C \\<union> {- T})\"\n    by auto\n  ultimately have \"\\<exists>D\\<subseteq>C \\<union> {- T}. finite D \\<and> S \\<subseteq> \\<Union>D\"\n    using \\<open>compact S\\<close> unfolding compact_eq_Heine_Borel by auto\n  then obtain D where \"D \\<subseteq> C \\<union> {- T} \\<and> finite D \\<and> S \\<subseteq> \\<Union>D\" ..\n  then show \"\\<exists>D\\<subseteq>C. finite D \\<and> S \\<inter> T \\<subseteq> \\<Union>D\"\n    by (intro exI[of _ \"D - {-T}\"]) auto\nqed\n\nlemma compact_diff: \"\\<lbrakk>compact S; open T\\<rbrakk> \\<Longrightarrow> compact(S - T)\"\n  by (simp add: Diff_eq compact_Int_closed open_closed)\n\nlemma inj_setminus: \"inj_on uminus (A::'a set set)\"\n  by (auto simp: inj_on_def)\n\n\nsubsection \\<open>Finite intersection property\\<close>\n\nlemma compact_fip:\n  \"compact U \\<longleftrightarrow>\n    (\\<forall>A. (\\<forall>a\\<in>A. closed a) \\<longrightarrow> (\\<forall>B \\<subseteq> A. finite B \\<longrightarrow> U \\<inter> \\<Inter>B \\<noteq> {}) \\<longrightarrow> U \\<inter> \\<Inter>A \\<noteq> {})\"\n  (is \"_ \\<longleftrightarrow> ?R\")\nproof (safe intro!: compact_eq_Heine_Borel[THEN iffD2])\n  fix A\n  assume \"compact U\"\n  assume A: \"\\<forall>a\\<in>A. closed a\" \"U \\<inter> \\<Inter>A = {}\"\n  assume fin: \"\\<forall>B \\<subseteq> A. finite B \\<longrightarrow> U \\<inter> \\<Inter>B \\<noteq> {}\"\n  from A have \"(\\<forall>a\\<in>uminus`A. open a) \\<and> U \\<subseteq> \\<Union>(uminus`A)\"\n    by auto\n  with \\<open>compact U\\<close> obtain B where \"B \\<subseteq> A\" \"finite (uminus`B)\" \"U \\<subseteq> \\<Union>(uminus`B)\"\n    unfolding compact_eq_Heine_Borel by (metis subset_image_iff)\n  with fin[THEN spec, of B] show False\n    by (auto dest: finite_imageD intro: inj_setminus)\nnext\n  fix A\n  assume ?R\n  assume \"\\<forall>a\\<in>A. open a\" \"U \\<subseteq> \\<Union>A\"\n  then have \"U \\<inter> \\<Inter>(uminus`A) = {}\" \"\\<forall>a\\<in>uminus`A. closed a\"\n    by auto\n  with \\<open>?R\\<close> obtain B where \"B \\<subseteq> A\" \"finite (uminus`B)\" \"U \\<inter> \\<Inter>(uminus`B) = {}\"\n    by (metis subset_image_iff)\n  then show \"\\<exists>T\\<subseteq>A. finite T \\<and> U \\<subseteq> \\<Union>T\"\n    by (auto intro!: exI[of _ B] inj_setminus dest: finite_imageD)\nqed\n\nlemma compact_imp_fip:\n  assumes \"compact S\"\n    and \"\\<And>T. T \\<in> F \\<Longrightarrow> closed T\"\n    and \"\\<And>F'. finite F' \\<Longrightarrow> F' \\<subseteq> F \\<Longrightarrow> S \\<inter> (\\<Inter>F') \\<noteq> {}\"\n  shows \"S \\<inter> (\\<Inter>F) \\<noteq> {}\"\n  using assms unfolding compact_fip by auto\n\nlemma compact_imp_fip_image:\n  assumes \"compact s\"\n    and P: \"\\<And>i. i \\<in> I \\<Longrightarrow> closed (f i)\"\n    and Q: \"\\<And>I'. finite I' \\<Longrightarrow> I' \\<subseteq> I \\<Longrightarrow> (s \\<inter> (\\<Inter>i\\<in>I'. f i) \\<noteq> {})\"\n  shows \"s \\<inter> (\\<Inter>i\\<in>I. f i) \\<noteq> {}\"\nproof -\n  note \\<open>compact s\\<close>\n  moreover from P have \"\\<forall>i \\<in> f ` I. closed i\"\n    by blast\n  moreover have \"\\<forall>A. finite A \\<and> A \\<subseteq> f ` I \\<longrightarrow> (s \\<inter> (\\<Inter>A) \\<noteq> {})\"\n    apply rule\n    apply rule\n    apply (erule conjE)\n  proof -\n    fix A :: \"'a set set\"\n    assume \"finite A\" and \"A \\<subseteq> f ` I\"\n    then obtain B where \"B \\<subseteq> I\" and \"finite B\" and \"A = f ` B\"\n      using finite_subset_image [of A f I] by blast\n    with Q [of B] show \"s \\<inter> \\<Inter>A \\<noteq> {}\"\n      by simp\n  qed\n  ultimately have \"s \\<inter> (\\<Inter>(f ` I)) \\<noteq> {}\"\n    by (metis compact_imp_fip)\n  then show ?thesis by simp\nqed\n\nend\n\nlemma (in t2_space) compact_imp_closed:\n  assumes \"compact s\"\n  shows \"closed s\"\n  unfolding closed_def\nproof (rule openI)\n  fix y\n  assume \"y \\<in> - s\"\n  let ?C = \"\\<Union>x\\<in>s. {u. open u \\<and> x \\<in> u \\<and> eventually (\\<lambda>y. y \\<notin> u) (nhds y)}\"\n  have \"s \\<subseteq> \\<Union>?C\"\n  proof\n    fix x\n    assume \"x \\<in> s\"\n    with \\<open>y \\<in> - s\\<close> have \"x \\<noteq> y\" by clarsimp\n    then have \"\\<exists>u v. open u \\<and> open v \\<and> x \\<in> u \\<and> y \\<in> v \\<and> u \\<inter> v = {}\"\n      by (rule hausdorff)\n    with \\<open>x \\<in> s\\<close> show \"x \\<in> \\<Union>?C\"\n      unfolding eventually_nhds by auto\n  qed\n  then obtain D where \"D \\<subseteq> ?C\" and \"finite D\" and \"s \\<subseteq> \\<Union>D\"\n    by (rule compactE [OF \\<open>compact s\\<close>]) auto\n  from \\<open>D \\<subseteq> ?C\\<close> have \"\\<forall>x\\<in>D. eventually (\\<lambda>y. y \\<notin> x) (nhds y)\"\n    by auto\n  with \\<open>finite D\\<close> have \"eventually (\\<lambda>y. y \\<notin> \\<Union>D) (nhds y)\"\n    by (simp add: eventually_ball_finite)\n  with \\<open>s \\<subseteq> \\<Union>D\\<close> have \"eventually (\\<lambda>y. y \\<notin> s) (nhds y)\"\n    by (auto elim!: eventually_mono)\n  then show \"\\<exists>t. open t \\<and> y \\<in> t \\<and> t \\<subseteq> - s\"\n    by (simp add: eventually_nhds subset_eq)\nqed\n\nlemma compact_continuous_image:\n  assumes f: \"continuous_on s f\"\n    and s: \"compact s\"\n  shows \"compact (f ` s)\"\nproof (rule compactI)\n  fix C\n  assume \"\\<forall>c\\<in>C. open c\" and cover: \"f`s \\<subseteq> \\<Union>C\"\n  with f have \"\\<forall>c\\<in>C. \\<exists>A. open A \\<and> A \\<inter> s = f -` c \\<inter> s\"\n    unfolding continuous_on_open_invariant by blast\n  then obtain A where A: \"\\<forall>c\\<in>C. open (A c) \\<and> A c \\<inter> s = f -` c \\<inter> s\"\n    unfolding bchoice_iff ..\n  with cover have \"\\<And>c. c \\<in> C \\<Longrightarrow> open (A c)\" \"s \\<subseteq> (\\<Union>c\\<in>C. A c)\"\n    by (fastforce simp add: subset_eq set_eq_iff)+\n  from compactE_image[OF s this] obtain D where \"D \\<subseteq> C\" \"finite D\" \"s \\<subseteq> (\\<Union>c\\<in>D. A c)\" .\n  with A show \"\\<exists>D \\<subseteq> C. finite D \\<and> f`s \\<subseteq> \\<Union>D\"\n    by (intro exI[of _ D]) (fastforce simp add: subset_eq set_eq_iff)+\nqed\n\nlemma continuous_on_inv:\n  fixes f :: \"'a::topological_space \\<Rightarrow> 'b::t2_space\"\n  assumes \"continuous_on s f\"\n    and \"compact s\"\n    and \"\\<forall>x\\<in>s. g (f x) = x\"\n  shows \"continuous_on (f ` s) g\"\n  unfolding continuous_on_topological\nproof (clarsimp simp add: assms(3))\n  fix x :: 'a and B :: \"'a set\"\n  assume \"x \\<in> s\" and \"open B\" and \"x \\<in> B\"\n  have 1: \"\\<forall>x\\<in>s. f x \\<in> f ` (s - B) \\<longleftrightarrow> x \\<in> s - B\"\n    using assms(3) by (auto, metis)\n  have \"continuous_on (s - B) f\"\n    using \\<open>continuous_on s f\\<close> Diff_subset\n    by (rule continuous_on_subset)\n  moreover have \"compact (s - B)\"\n    using \\<open>open B\\<close> and \\<open>compact s\\<close>\n    unfolding Diff_eq by (intro compact_Int_closed closed_Compl)\n  ultimately have \"compact (f ` (s - B))\"\n    by (rule compact_continuous_image)\n  then have \"closed (f ` (s - B))\"\n    by (rule compact_imp_closed)\n  then have \"open (- f ` (s - B))\"\n    by (rule open_Compl)\n  moreover have \"f x \\<in> - f ` (s - B)\"\n    using \\<open>x \\<in> s\\<close> and \\<open>x \\<in> B\\<close> by (simp add: 1)\n  moreover have \"\\<forall>y\\<in>s. f y \\<in> - f ` (s - B) \\<longrightarrow> y \\<in> B\"\n    by (simp add: 1)\n  ultimately show \"\\<exists>A. open A \\<and> f x \\<in> A \\<and> (\\<forall>y\\<in>s. f y \\<in> A \\<longrightarrow> y \\<in> B)\"\n    by fast\nqed\n\nlemma continuous_on_inv_into:\n  fixes f :: \"'a::topological_space \\<Rightarrow> 'b::t2_space\"\n  assumes s: \"continuous_on s f\" \"compact s\"\n    and f: \"inj_on f s\"\n  shows \"continuous_on (f ` s) (the_inv_into s f)\"\n  by (rule continuous_on_inv[OF s]) (auto simp: the_inv_into_f_f[OF f])\n\nlemma (in linorder_topology) compact_attains_sup:\n  assumes \"compact S\" \"S \\<noteq> {}\"\n  shows \"\\<exists>s\\<in>S. \\<forall>t\\<in>S. t \\<le> s\"\nproof (rule classical)\n  assume \"\\<not> (\\<exists>s\\<in>S. \\<forall>t\\<in>S. t \\<le> s)\"\n  then obtain t where t: \"\\<forall>s\\<in>S. t s \\<in> S\" and \"\\<forall>s\\<in>S. s < t s\"\n    by (metis not_le)\n  then have \"\\<And>s. s\\<in>S \\<Longrightarrow> open {..< t s}\" \"S \\<subseteq> (\\<Union>s\\<in>S. {..< t s})\"\n    by auto\n  with \\<open>compact S\\<close> obtain C where \"C \\<subseteq> S\" \"finite C\" and C: \"S \\<subseteq> (\\<Union>s\\<in>C. {..< t s})\"\n    by (metis compactE_image)\n  with \\<open>S \\<noteq> {}\\<close> have Max: \"Max (t`C) \\<in> t`C\" and \"\\<forall>s\\<in>t`C. s \\<le> Max (t`C)\"\n    by (auto intro!: Max_in)\n  with C have \"S \\<subseteq> {..< Max (t`C)}\"\n    by (auto intro: less_le_trans simp: subset_eq)\n  with t Max \\<open>C \\<subseteq> S\\<close> show ?thesis\n    by fastforce\nqed\n\nlemma (in linorder_topology) compact_attains_inf:\n  assumes \"compact S\" \"S \\<noteq> {}\"\n  shows \"\\<exists>s\\<in>S. \\<forall>t\\<in>S. s \\<le> t\"\nproof (rule classical)\n  assume \"\\<not> (\\<exists>s\\<in>S. \\<forall>t\\<in>S. s \\<le> t)\"\n  then obtain t where t: \"\\<forall>s\\<in>S. t s \\<in> S\" and \"\\<forall>s\\<in>S. t s < s\"\n    by (metis not_le)\n  then have \"\\<And>s. s\\<in>S \\<Longrightarrow> open {t s <..}\" \"S \\<subseteq> (\\<Union>s\\<in>S. {t s <..})\"\n    by auto\n  with \\<open>compact S\\<close> obtain C where \"C \\<subseteq> S\" \"finite C\" and C: \"S \\<subseteq> (\\<Union>s\\<in>C. {t s <..})\"\n    by (metis compactE_image)\n  with \\<open>S \\<noteq> {}\\<close> have Min: \"Min (t`C) \\<in> t`C\" and \"\\<forall>s\\<in>t`C. Min (t`C) \\<le> s\"\n    by (auto intro!: Min_in)\n  with C have \"S \\<subseteq> {Min (t`C) <..}\"\n    by (auto intro: le_less_trans simp: subset_eq)\n  with t Min \\<open>C \\<subseteq> S\\<close> show ?thesis\n    by fastforce\nqed\n\nlemma continuous_attains_sup:\n  fixes f :: \"'a::topological_space \\<Rightarrow> 'b::linorder_topology\"\n  shows \"compact s \\<Longrightarrow> s \\<noteq> {} \\<Longrightarrow> continuous_on s f \\<Longrightarrow> (\\<exists>x\\<in>s. \\<forall>y\\<in>s.  f y \\<le> f x)\"\n  using compact_attains_sup[of \"f ` s\"] compact_continuous_image[of s f] by auto\n\nlemma continuous_attains_inf:\n  fixes f :: \"'a::topological_space \\<Rightarrow> 'b::linorder_topology\"\n  shows \"compact s \\<Longrightarrow> s \\<noteq> {} \\<Longrightarrow> continuous_on s f \\<Longrightarrow> (\\<exists>x\\<in>s. \\<forall>y\\<in>s. f x \\<le> f y)\"\n  using compact_attains_inf[of \"f ` s\"] compact_continuous_image[of s f] by auto\n\n\nsubsection \\<open>Connectedness\\<close>\n\ncontext topological_space\nbegin\n\ndefinition \"connected S \\<longleftrightarrow>\n  \\<not> (\\<exists>A B. open A \\<and> open B \\<and> S \\<subseteq> A \\<union> B \\<and> A \\<inter> B \\<inter> S = {} \\<and> A \\<inter> S \\<noteq> {} \\<and> B \\<inter> S \\<noteq> {})\"\n\nlemma connectedI:\n  \"(\\<And>A B. open A \\<Longrightarrow> open B \\<Longrightarrow> A \\<inter> U \\<noteq> {} \\<Longrightarrow> B \\<inter> U \\<noteq> {} \\<Longrightarrow> A \\<inter> B \\<inter> U = {} \\<Longrightarrow> U \\<subseteq> A \\<union> B \\<Longrightarrow> False)\n  \\<Longrightarrow> connected U\"\n  by (auto simp: connected_def)\n\nlemma connected_empty [simp]: \"connected {}\"\n  by (auto intro!: connectedI)\n\nlemma connected_sing [simp]: \"connected {x}\"\n  by (auto intro!: connectedI)\n\nlemma connectedD:\n  \"connected A \\<Longrightarrow> open U \\<Longrightarrow> open V \\<Longrightarrow> U \\<inter> V \\<inter> A = {} \\<Longrightarrow> A \\<subseteq> U \\<union> V \\<Longrightarrow> U \\<inter> A = {} \\<or> V \\<inter> A = {}\"\n  by (auto simp: connected_def)\n\nend\n\nlemma connected_closed:\n  \"connected s \\<longleftrightarrow>\n    \\<not> (\\<exists>A B. closed A \\<and> closed B \\<and> s \\<subseteq> A \\<union> B \\<and> A \\<inter> B \\<inter> s = {} \\<and> A \\<inter> s \\<noteq> {} \\<and> B \\<inter> s \\<noteq> {})\"\n  apply (simp add: connected_def del: ex_simps, safe)\n   apply (drule_tac x=\"-A\" in spec)\n   apply (drule_tac x=\"-B\" in spec)\n   apply (fastforce simp add: closed_def [symmetric])\n  apply (drule_tac x=\"-A\" in spec)\n  apply (drule_tac x=\"-B\" in spec)\n  apply (fastforce simp add: open_closed [symmetric])\n  done\n\nlemma connected_closedD:\n  \"\\<lbrakk>connected s; A \\<inter> B \\<inter> s = {}; s \\<subseteq> A \\<union> B; closed A; closed B\\<rbrakk> \\<Longrightarrow> A \\<inter> s = {} \\<or> B \\<inter> s = {}\"\n  by (simp add: connected_closed)\n\nlemma connected_Union:\n  assumes cs: \"\\<And>s. s \\<in> S \\<Longrightarrow> connected s\"\n    and ne: \"\\<Inter>S \\<noteq> {}\"\n  shows \"connected(\\<Union>S)\"\nproof (rule connectedI)\n  fix A B\n  assume A: \"open A\" and B: \"open B\" and Alap: \"A \\<inter> \\<Union>S \\<noteq> {}\" and Blap: \"B \\<inter> \\<Union>S \\<noteq> {}\"\n    and disj: \"A \\<inter> B \\<inter> \\<Union>S = {}\" and cover: \"\\<Union>S \\<subseteq> A \\<union> B\"\n  have disjs:\"\\<And>s. s \\<in> S \\<Longrightarrow> A \\<inter> B \\<inter> s = {}\"\n    using disj by auto\n  obtain sa where sa: \"sa \\<in> S\" \"A \\<inter> sa \\<noteq> {}\"\n    using Alap by auto\n  obtain sb where sb: \"sb \\<in> S\" \"B \\<inter> sb \\<noteq> {}\"\n    using Blap by auto\n  obtain x where x: \"\\<And>s. s \\<in> S \\<Longrightarrow> x \\<in> s\"\n    using ne by auto\n  then have \"x \\<in> \\<Union>S\"\n    using \\<open>sa \\<in> S\\<close> by blast\n  then have \"x \\<in> A \\<or> x \\<in> B\"\n    using cover by auto\n  then show False\n    using cs [unfolded connected_def]\n    by (metis A B IntI Sup_upper sa sb disjs x cover empty_iff subset_trans)\nqed\n\nlemma connected_Un: \"connected s \\<Longrightarrow> connected t \\<Longrightarrow> s \\<inter> t \\<noteq> {} \\<Longrightarrow> connected (s \\<union> t)\"\n  using connected_Union [of \"{s,t}\"] by auto\n\nlemma connected_diff_open_from_closed:\n  assumes st: \"s \\<subseteq> t\"\n    and tu: \"t \\<subseteq> u\"\n    and s: \"open s\"\n    and t: \"closed t\"\n    and u: \"connected u\"\n    and ts: \"connected (t - s)\"\n  shows \"connected(u - s)\"\nproof (rule connectedI)\n  fix A B\n  assume AB: \"open A\" \"open B\" \"A \\<inter> (u - s) \\<noteq> {}\" \"B \\<inter> (u - s) \\<noteq> {}\"\n    and disj: \"A \\<inter> B \\<inter> (u - s) = {}\"\n    and cover: \"u - s \\<subseteq> A \\<union> B\"\n  then consider \"A \\<inter> (t - s) = {}\" | \"B \\<inter> (t - s) = {}\"\n    using st ts tu connectedD [of \"t-s\" \"A\" \"B\"] by auto\n  then show False\n  proof cases\n    case 1\n    then have \"(A - t) \\<inter> (B \\<union> s) \\<inter> u = {}\"\n      using disj st by auto\n    moreover have \"u \\<subseteq> (A - t) \\<union> (B \\<union> s)\"\n      using 1 cover by auto\n    ultimately show False\n      using connectedD [of u \"A - t\" \"B \\<union> s\"] AB s t 1 u by auto\n  next\n    case 2\n    then have \"(A \\<union> s) \\<inter> (B - t) \\<inter> u = {}\"\n      using disj st by auto\n    moreover have \"u \\<subseteq> (A \\<union> s) \\<union> (B - t)\"\n      using 2 cover by auto\n    ultimately show False\n      using connectedD [of u \"A \\<union> s\" \"B - t\"] AB s t 2 u by auto\n  qed\nqed\n\nlemma connected_iff_const:\n  fixes S :: \"'a::topological_space set\"\n  shows \"connected S \\<longleftrightarrow> (\\<forall>P::'a \\<Rightarrow> bool. continuous_on S P \\<longrightarrow> (\\<exists>c. \\<forall>s\\<in>S. P s = c))\"\nproof safe\n  fix P :: \"'a \\<Rightarrow> bool\"\n  assume \"connected S\" \"continuous_on S P\"\n  then have \"\\<And>b. \\<exists>A. open A \\<and> A \\<inter> S = P -` {b} \\<inter> S\"\n    unfolding continuous_on_open_invariant by (simp add: open_discrete)\n  from this[of True] this[of False]\n  obtain t f where \"open t\" \"open f\" and *: \"f \\<inter> S = P -` {False} \\<inter> S\" \"t \\<inter> S = P -` {True} \\<inter> S\"\n    by meson\n  then have \"t \\<inter> S = {} \\<or> f \\<inter> S = {}\"\n    by (intro connectedD[OF \\<open>connected S\\<close>])  auto\n  then show \"\\<exists>c. \\<forall>s\\<in>S. P s = c\"\n  proof (rule disjE)\n    assume \"t \\<inter> S = {}\"\n    then show ?thesis\n      unfolding * by (intro exI[of _ False]) auto\n  next\n    assume \"f \\<inter> S = {}\"\n    then show ?thesis\n      unfolding * by (intro exI[of _ True]) auto\n  qed\nnext\n  assume P: \"\\<forall>P::'a \\<Rightarrow> bool. continuous_on S P \\<longrightarrow> (\\<exists>c. \\<forall>s\\<in>S. P s = c)\"\n  show \"connected S\"\n  proof (rule connectedI)\n    fix A B\n    assume *: \"open A\" \"open B\" \"A \\<inter> S \\<noteq> {}\" \"B \\<inter> S \\<noteq> {}\" \"A \\<inter> B \\<inter> S = {}\" \"S \\<subseteq> A \\<union> B\"\n    have \"continuous_on S (\\<lambda>x. x \\<in> A)\"\n      unfolding continuous_on_open_invariant\n    proof safe\n      fix C :: \"bool set\"\n      have \"C = UNIV \\<or> C = {True} \\<or> C = {False} \\<or> C = {}\"\n        using subset_UNIV[of C] unfolding UNIV_bool by auto\n      with * show \"\\<exists>T. open T \\<and> T \\<inter> S = (\\<lambda>x. x \\<in> A) -` C \\<inter> S\"\n        by (intro exI[of _ \"(if True \\<in> C then A else {}) \\<union> (if False \\<in> C then B else {})\"]) auto\n    qed\n    from P[rule_format, OF this] obtain c where \"\\<And>s. s \\<in> S \\<Longrightarrow> (s \\<in> A) = c\"\n      by blast\n    with * show False\n      by (cases c) auto\n  qed\nqed\n\nlemma connectedD_const: \"connected S \\<Longrightarrow> continuous_on S P \\<Longrightarrow> \\<exists>c. \\<forall>s\\<in>S. P s = c\"\n  for P :: \"'a::topological_space \\<Rightarrow> bool\"\n  by (auto simp: connected_iff_const)\n\nlemma connectedI_const:\n  \"(\\<And>P::'a::topological_space \\<Rightarrow> bool. continuous_on S P \\<Longrightarrow> \\<exists>c. \\<forall>s\\<in>S. P s = c) \\<Longrightarrow> connected S\"\n  by (auto simp: connected_iff_const)\n\nlemma connected_local_const:\n  assumes \"connected A\" \"a \\<in> A\" \"b \\<in> A\"\n    and *: \"\\<forall>a\\<in>A. eventually (\\<lambda>b. f a = f b) (at a within A)\"\n  shows \"f a = f b\"\nproof -\n  obtain S where S: \"\\<And>a. a \\<in> A \\<Longrightarrow> a \\<in> S a\" \"\\<And>a. a \\<in> A \\<Longrightarrow> open (S a)\"\n    \"\\<And>a x. a \\<in> A \\<Longrightarrow> x \\<in> S a \\<Longrightarrow> x \\<in> A \\<Longrightarrow> f a = f x\"\n    using * unfolding eventually_at_topological by metis\n  let ?P = \"\\<Union>b\\<in>{b\\<in>A. f a = f b}. S b\" and ?N = \"\\<Union>b\\<in>{b\\<in>A. f a \\<noteq> f b}. S b\"\n  have \"?P \\<inter> A = {} \\<or> ?N \\<inter> A = {}\"\n    using \\<open>connected A\\<close> S \\<open>a\\<in>A\\<close>\n    by (intro connectedD) (auto, metis)\n  then show \"f a = f b\"\n  proof\n    assume \"?N \\<inter> A = {}\"\n    then have \"\\<forall>x\\<in>A. f a = f x\"\n      using S(1) by auto\n    with \\<open>b\\<in>A\\<close> show ?thesis by auto\n  next\n    assume \"?P \\<inter> A = {}\" then show ?thesis\n      using \\<open>a \\<in> A\\<close> S(1)[of a] by auto\n  qed\nqed\n\nlemma (in linorder_topology) connectedD_interval:\n  assumes \"connected U\"\n    and xy: \"x \\<in> U\" \"y \\<in> U\"\n    and \"x \\<le> z\" \"z \\<le> y\"\n  shows \"z \\<in> U\"\nproof -\n  have eq: \"{..<z} \\<union> {z<..} = - {z}\"\n    by auto\n  have \"\\<not> connected U\" if \"z \\<notin> U\" \"x < z\" \"z < y\"\n    using xy that\n    apply (simp only: connected_def simp_thms)\n    apply (rule_tac exI[of _ \"{..< z}\"])\n    apply (rule_tac exI[of _ \"{z <..}\"])\n    apply (auto simp add: eq)\n    done\n  with assms show \"z \\<in> U\"\n    by (metis less_le)\nqed\n\nlemma (in linorder_topology) not_in_connected_cases:\n  assumes conn: \"connected S\"\n  assumes nbdd: \"x \\<notin> S\"\n  assumes ne: \"S \\<noteq> {}\"\n  obtains \"bdd_above S\" \"\\<And>y. y \\<in> S \\<Longrightarrow> x \\<ge> y\" | \"bdd_below S\" \"\\<And>y. y \\<in> S \\<Longrightarrow> x \\<le> y\"\nproof -\n  obtain s where \"s \\<in> S\" using ne by blast\n  {\n    assume \"s \\<le> x\"\n    have \"False\" if \"x \\<le> y\" \"y \\<in> S\" for y\n      using connectedD_interval[OF conn \\<open>s \\<in> S\\<close> \\<open>y \\<in> S\\<close> \\<open>s \\<le> x\\<close> \\<open>x \\<le> y\\<close>] \\<open>x \\<notin> S\\<close>\n      by simp\n    then have wit: \"y \\<in> S \\<Longrightarrow> x \\<ge> y\" for y\n      using le_cases by blast\n    then have \"bdd_above S\"\n      by (rule local.bdd_aboveI)\n    note this wit\n  } moreover {\n    assume \"x \\<le> s\"\n    have \"False\" if \"x \\<ge> y\" \"y \\<in> S\" for y\n      using connectedD_interval[OF conn \\<open>y \\<in> S\\<close> \\<open>s \\<in> S\\<close> \\<open>x \\<ge> y\\<close> \\<open>s \\<ge> x\\<close> ] \\<open>x \\<notin> S\\<close>\n      by simp\n    then have wit: \"y \\<in> S \\<Longrightarrow> x \\<le> y\" for y\n      using le_cases by blast\n    then have \"bdd_below S\"\n      by (rule bdd_belowI)\n    note this wit\n  } ultimately show ?thesis\n    by (meson le_cases that)\nqed\n\nlemma connected_continuous_image:\n  assumes *: \"continuous_on s f\"\n    and \"connected s\"\n  shows \"connected (f ` s)\"\nproof (rule connectedI_const)\n  fix P :: \"'b \\<Rightarrow> bool\"\n  assume \"continuous_on (f ` s) P\"\n  then have \"continuous_on s (P \\<circ> f)\"\n    by (rule continuous_on_compose[OF *])\n  from connectedD_const[OF \\<open>connected s\\<close> this] show \"\\<exists>c. \\<forall>s\\<in>f ` s. P s = c\"\n    by auto\nqed\n\n\nsection \\<open>Linear Continuum Topologies\\<close>\n\nclass linear_continuum_topology = linorder_topology + linear_continuum\nbegin\n\nlemma Inf_notin_open:\n  assumes A: \"open A\"\n    and bnd: \"\\<forall>a\\<in>A. x < a\"\n  shows \"Inf A \\<notin> A\"\nproof\n  assume \"Inf A \\<in> A\"\n  then obtain b where \"b < Inf A\" \"{b <.. Inf A} \\<subseteq> A\"\n    using open_left[of A \"Inf A\" x] assms by auto\n  with dense[of b \"Inf A\"] obtain c where \"c < Inf A\" \"c \\<in> A\"\n    by (auto simp: subset_eq)\n  then show False\n    using cInf_lower[OF \\<open>c \\<in> A\\<close>] bnd\n    by (metis not_le less_imp_le bdd_belowI)\nqed\n\nlemma Sup_notin_open:\n  assumes A: \"open A\"\n    and bnd: \"\\<forall>a\\<in>A. a < x\"\n  shows \"Sup A \\<notin> A\"\nproof\n  assume \"Sup A \\<in> A\"\n  with assms obtain b where \"Sup A < b\" \"{Sup A ..< b} \\<subseteq> A\"\n    using open_right[of A \"Sup A\" x] by auto\n  with dense[of \"Sup A\" b] obtain c where \"Sup A < c\" \"c \\<in> A\"\n    by (auto simp: subset_eq)\n  then show False\n    using cSup_upper[OF \\<open>c \\<in> A\\<close>] bnd\n    by (metis less_imp_le not_le bdd_aboveI)\nqed\n\nend\n\ninstance linear_continuum_topology \\<subseteq> perfect_space\nproof\n  fix x :: 'a\n  obtain y where \"x < y \\<or> y < x\"\n    using ex_gt_or_lt [of x] ..\n  with Inf_notin_open[of \"{x}\" y] Sup_notin_open[of \"{x}\" y] show \"\\<not> open {x}\"\n    by auto\nqed\n\nlemma connectedI_interval:\n  fixes U :: \"'a :: linear_continuum_topology set\"\n  assumes *: \"\\<And>x y z. x \\<in> U \\<Longrightarrow> y \\<in> U \\<Longrightarrow> x \\<le> z \\<Longrightarrow> z \\<le> y \\<Longrightarrow> z \\<in> U\"\n  shows \"connected U\"\nproof (rule connectedI)\n  {\n    fix A B\n    assume \"open A\" \"open B\" \"A \\<inter> B \\<inter> U = {}\" \"U \\<subseteq> A \\<union> B\"\n    fix x y\n    assume \"x < y\" \"x \\<in> A\" \"y \\<in> B\" \"x \\<in> U\" \"y \\<in> U\"\n\n    let ?z = \"Inf (B \\<inter> {x <..})\"\n\n    have \"x \\<le> ?z\" \"?z \\<le> y\"\n      using \\<open>y \\<in> B\\<close> \\<open>x < y\\<close> by (auto intro: cInf_lower cInf_greatest)\n    with \\<open>x \\<in> U\\<close> \\<open>y \\<in> U\\<close> have \"?z \\<in> U\"\n      by (rule *)\n    moreover have \"?z \\<notin> B \\<inter> {x <..}\"\n      using \\<open>open B\\<close> by (intro Inf_notin_open) auto\n    ultimately have \"?z \\<in> A\"\n      using \\<open>x \\<le> ?z\\<close> \\<open>A \\<inter> B \\<inter> U = {}\\<close> \\<open>x \\<in> A\\<close> \\<open>U \\<subseteq> A \\<union> B\\<close> by auto\n    have \"\\<exists>b\\<in>B. b \\<in> A \\<and> b \\<in> U\" if \"?z < y\"\n    proof -\n      obtain a where \"?z < a\" \"{?z ..< a} \\<subseteq> A\"\n        using open_right[OF \\<open>open A\\<close> \\<open>?z \\<in> A\\<close> \\<open>?z < y\\<close>] by auto\n      moreover obtain b where \"b \\<in> B\" \"x < b\" \"b < min a y\"\n        using cInf_less_iff[of \"B \\<inter> {x <..}\" \"min a y\"] \\<open>?z < a\\<close> \\<open>?z < y\\<close> \\<open>x < y\\<close> \\<open>y \\<in> B\\<close>\n        by auto\n      moreover have \"?z \\<le> b\"\n        using \\<open>b \\<in> B\\<close> \\<open>x < b\\<close>\n        by (intro cInf_lower) auto\n      moreover have \"b \\<in> U\"\n        using \\<open>x \\<le> ?z\\<close> \\<open>?z \\<le> b\\<close> \\<open>b < min a y\\<close>\n        by (intro *[OF \\<open>x \\<in> U\\<close> \\<open>y \\<in> U\\<close>]) (auto simp: less_imp_le)\n      ultimately show ?thesis\n        by (intro bexI[of _ b]) auto\n    qed\n    then have False\n      using \\<open>?z \\<le> y\\<close> \\<open>?z \\<in> A\\<close> \\<open>y \\<in> B\\<close> \\<open>y \\<in> U\\<close> \\<open>A \\<inter> B \\<inter> U = {}\\<close>\n      unfolding le_less by blast\n  }\n  note not_disjoint = this\n\n  fix A B assume AB: \"open A\" \"open B\" \"U \\<subseteq> A \\<union> B\" \"A \\<inter> B \\<inter> U = {}\"\n  moreover assume \"A \\<inter> U \\<noteq> {}\" then obtain x where x: \"x \\<in> U\" \"x \\<in> A\" by auto\n  moreover assume \"B \\<inter> U \\<noteq> {}\" then obtain y where y: \"y \\<in> U\" \"y \\<in> B\" by auto\n  moreover note not_disjoint[of B A y x] not_disjoint[of A B x y]\n  ultimately show False\n    by (cases x y rule: linorder_cases) auto\nqed\n\nlemma connected_iff_interval: \"connected U \\<longleftrightarrow> (\\<forall>x\\<in>U. \\<forall>y\\<in>U. \\<forall>z. x \\<le> z \\<longrightarrow> z \\<le> y \\<longrightarrow> z \\<in> U)\"\n  for U :: \"'a::linear_continuum_topology set\"\n  by (auto intro: connectedI_interval dest: connectedD_interval)\n\nlemma connected_UNIV[simp]: \"connected (UNIV::'a::linear_continuum_topology set)\"\n  by (simp add: connected_iff_interval)\n\nlemma connected_Ioi[simp]: \"connected {a<..}\"\n  for a :: \"'a::linear_continuum_topology\"\n  by (auto simp: connected_iff_interval)\n\nlemma connected_Ici[simp]: \"connected {a..}\"\n  for a :: \"'a::linear_continuum_topology\"\n  by (auto simp: connected_iff_interval)\n\nlemma connected_Iio[simp]: \"connected {..<a}\"\n  for a :: \"'a::linear_continuum_topology\"\n  by (auto simp: connected_iff_interval)\n\nlemma connected_Iic[simp]: \"connected {..a}\"\n  for a :: \"'a::linear_continuum_topology\"\n  by (auto simp: connected_iff_interval)\n\nlemma connected_Ioo[simp]: \"connected {a<..<b}\"\n  for a b :: \"'a::linear_continuum_topology\"\n  unfolding connected_iff_interval by auto\n\nlemma connected_Ioc[simp]: \"connected {a<..b}\"\n  for a b :: \"'a::linear_continuum_topology\"\n  by (auto simp: connected_iff_interval)\n\nlemma connected_Ico[simp]: \"connected {a..<b}\"\n  for a b :: \"'a::linear_continuum_topology\"\n  by (auto simp: connected_iff_interval)\n\nlemma connected_Icc[simp]: \"connected {a..b}\"\n  for a b :: \"'a::linear_continuum_topology\"\n  by (auto simp: connected_iff_interval)\n\nlemma connected_contains_Ioo:\n  fixes A :: \"'a :: linorder_topology set\"\n  assumes \"connected A\" \"a \\<in> A\" \"b \\<in> A\" shows \"{a <..< b} \\<subseteq> A\"\n  using connectedD_interval[OF assms] by (simp add: subset_eq Ball_def less_imp_le)\n\nlemma connected_contains_Icc:\n  fixes A :: \"'a::linorder_topology set\"\n  assumes \"connected A\" \"a \\<in> A\" \"b \\<in> A\"\n  shows \"{a..b} \\<subseteq> A\"\nproof\n  fix x assume \"x \\<in> {a..b}\"\n  then have \"x = a \\<or> x = b \\<or> x \\<in> {a<..<b}\"\n    by auto\n  then show \"x \\<in> A\"\n    using assms connected_contains_Ioo[of A a b] by auto\nqed\n\n\nsubsection \\<open>Intermediate Value Theorem\\<close>\n\nlemma IVT':\n  fixes f :: \"'a::linear_continuum_topology \\<Rightarrow> 'b::linorder_topology\"\n  assumes y: \"f a \\<le> y\" \"y \\<le> f b\" \"a \\<le> b\"\n    and *: \"continuous_on {a .. b} f\"\n  shows \"\\<exists>x. a \\<le> x \\<and> x \\<le> b \\<and> f x = y\"\nproof -\n  have \"connected {a..b}\"\n    unfolding connected_iff_interval by auto\n  from connected_continuous_image[OF * this, THEN connectedD_interval, of \"f a\" \"f b\" y] y\n  show ?thesis\n    by (auto simp add: atLeastAtMost_def atLeast_def atMost_def)\nqed\n\nlemma IVT2':\n  fixes f :: \"'a :: linear_continuum_topology \\<Rightarrow> 'b :: linorder_topology\"\n  assumes y: \"f b \\<le> y\" \"y \\<le> f a\" \"a \\<le> b\"\n    and *: \"continuous_on {a .. b} f\"\n  shows \"\\<exists>x. a \\<le> x \\<and> x \\<le> b \\<and> f x = y\"\nproof -\n  have \"connected {a..b}\"\n    unfolding connected_iff_interval by auto\n  from connected_continuous_image[OF * this, THEN connectedD_interval, of \"f b\" \"f a\" y] y\n  show ?thesis\n    by (auto simp add: atLeastAtMost_def atLeast_def atMost_def)\nqed\n\nlemma IVT:\n  fixes f :: \"'a::linear_continuum_topology \\<Rightarrow> 'b::linorder_topology\"\n  shows \"f a \\<le> y \\<Longrightarrow> y \\<le> f b \\<Longrightarrow> a \\<le> b \\<Longrightarrow> (\\<forall>x. a \\<le> x \\<and> x \\<le> b \\<longrightarrow> isCont f x) \\<Longrightarrow>\n    \\<exists>x. a \\<le> x \\<and> x \\<le> b \\<and> f x = y\"\n  by (rule IVT') (auto intro: continuous_at_imp_continuous_on)\n\nlemma IVT2:\n  fixes f :: \"'a::linear_continuum_topology \\<Rightarrow> 'b::linorder_topology\"\n  shows \"f b \\<le> y \\<Longrightarrow> y \\<le> f a \\<Longrightarrow> a \\<le> b \\<Longrightarrow> (\\<forall>x. a \\<le> x \\<and> x \\<le> b \\<longrightarrow> isCont f x) \\<Longrightarrow>\n    \\<exists>x. a \\<le> x \\<and> x \\<le> b \\<and> f x = y\"\n  by (rule IVT2') (auto intro: continuous_at_imp_continuous_on)\n\nlemma continuous_inj_imp_mono:\n  fixes f :: \"'a::linear_continuum_topology \\<Rightarrow> 'b::linorder_topology\"\n  assumes x: \"a < x\" \"x < b\"\n    and cont: \"continuous_on {a..b} f\"\n    and inj: \"inj_on f {a..b}\"\n  shows \"(f a < f x \\<and> f x < f b) \\<or> (f b < f x \\<and> f x < f a)\"\nproof -\n  note I = inj_on_eq_iff[OF inj]\n  {\n    assume \"f x < f a\" \"f x < f b\"\n    then obtain s t where \"x \\<le> s\" \"s \\<le> b\" \"a \\<le> t\" \"t \\<le> x\" \"f s = f t\" \"f x < f s\"\n      using IVT'[of f x \"min (f a) (f b)\" b] IVT2'[of f x \"min (f a) (f b)\" a] x\n      by (auto simp: continuous_on_subset[OF cont] less_imp_le)\n    with x I have False by auto\n  }\n  moreover\n  {\n    assume \"f a < f x\" \"f b < f x\"\n    then obtain s t where \"x \\<le> s\" \"s \\<le> b\" \"a \\<le> t\" \"t \\<le> x\" \"f s = f t\" \"f s < f x\"\n      using IVT'[of f a \"max (f a) (f b)\" x] IVT2'[of f b \"max (f a) (f b)\" x] x\n      by (auto simp: continuous_on_subset[OF cont] less_imp_le)\n    with x I have False by auto\n  }\n  ultimately show ?thesis\n    using I[of a x] I[of x b] x less_trans[OF x]\n    by (auto simp add: le_less less_imp_neq neq_iff)\nqed\n\nlemma continuous_at_Sup_mono:\n  fixes f :: \"'a::{linorder_topology,conditionally_complete_linorder} \\<Rightarrow>\n    'b::{linorder_topology,conditionally_complete_linorder}\"\n  assumes \"mono f\"\n    and cont: \"continuous (at_left (Sup S)) f\"\n    and S: \"S \\<noteq> {}\" \"bdd_above S\"\n  shows \"f (Sup S) = (SUP s\\<in>S. f s)\"\nproof (rule antisym)\n  have f: \"(f \\<longlongrightarrow> f (Sup S)) (at_left (Sup S))\"\n    using cont unfolding continuous_within .\n  show \"f (Sup S) \\<le> (SUP s\\<in>S. f s)\"\n  proof cases\n    assume \"Sup S \\<in> S\"\n    then show ?thesis\n      by (rule cSUP_upper) (auto intro: bdd_above_image_mono S \\<open>mono f\\<close>)\n  next\n    assume \"Sup S \\<notin> S\"\n    from \\<open>S \\<noteq> {}\\<close> obtain s where \"s \\<in> S\"\n      by auto\n    with \\<open>Sup S \\<notin> S\\<close> S have \"s < Sup S\"\n      unfolding less_le by (blast intro: cSup_upper)\n    show ?thesis\n    proof (rule ccontr)\n      assume \"\\<not> ?thesis\"\n      with order_tendstoD(1)[OF f, of \"SUP s\\<in>S. f s\"] obtain b where \"b < Sup S\"\n        and *: \"\\<And>y. b < y \\<Longrightarrow> y < Sup S \\<Longrightarrow> (SUP s\\<in>S. f s) < f y\"\n        by (auto simp: not_le eventually_at_left[OF \\<open>s < Sup S\\<close>])\n      with \\<open>S \\<noteq> {}\\<close> obtain c where \"c \\<in> S\" \"b < c\"\n        using less_cSupD[of S b] by auto\n      with \\<open>Sup S \\<notin> S\\<close> S have \"c < Sup S\"\n        unfolding less_le by (blast intro: cSup_upper)\n      from *[OF \\<open>b < c\\<close> \\<open>c < Sup S\\<close>] cSUP_upper[OF \\<open>c \\<in> S\\<close> bdd_above_image_mono[of f]]\n      show False\n        by (auto simp: assms)\n    qed\n  qed\nqed (intro cSUP_least \\<open>mono f\\<close>[THEN monoD] cSup_upper S)\n\nlemma continuous_at_Sup_antimono:\n  fixes f :: \"'a::{linorder_topology,conditionally_complete_linorder} \\<Rightarrow>\n    'b::{linorder_topology,conditionally_complete_linorder}\"\n  assumes \"antimono f\"\n    and cont: \"continuous (at_left (Sup S)) f\"\n    and S: \"S \\<noteq> {}\" \"bdd_above S\"\n  shows \"f (Sup S) = (INF s\\<in>S. f s)\"\nproof (rule antisym)\n  have f: \"(f \\<longlongrightarrow> f (Sup S)) (at_left (Sup S))\"\n    using cont unfolding continuous_within .\n  show \"(INF s\\<in>S. f s) \\<le> f (Sup S)\"\n  proof cases\n    assume \"Sup S \\<in> S\"\n    then show ?thesis\n      by (intro cINF_lower) (auto intro: bdd_below_image_antimono S \\<open>antimono f\\<close>)\n  next\n    assume \"Sup S \\<notin> S\"\n    from \\<open>S \\<noteq> {}\\<close> obtain s where \"s \\<in> S\"\n      by auto\n    with \\<open>Sup S \\<notin> S\\<close> S have \"s < Sup S\"\n      unfolding less_le by (blast intro: cSup_upper)\n    show ?thesis\n    proof (rule ccontr)\n      assume \"\\<not> ?thesis\"\n      with order_tendstoD(2)[OF f, of \"INF s\\<in>S. f s\"] obtain b where \"b < Sup S\"\n        and *: \"\\<And>y. b < y \\<Longrightarrow> y < Sup S \\<Longrightarrow> f y < (INF s\\<in>S. f s)\"\n        by (auto simp: not_le eventually_at_left[OF \\<open>s < Sup S\\<close>])\n      with \\<open>S \\<noteq> {}\\<close> obtain c where \"c \\<in> S\" \"b < c\"\n        using less_cSupD[of S b] by auto\n      with \\<open>Sup S \\<notin> S\\<close> S have \"c < Sup S\"\n        unfolding less_le by (blast intro: cSup_upper)\n      from *[OF \\<open>b < c\\<close> \\<open>c < Sup S\\<close>] cINF_lower[OF bdd_below_image_antimono, of f S c] \\<open>c \\<in> S\\<close>\n      show False\n        by (auto simp: assms)\n    qed\n  qed\nqed (intro cINF_greatest \\<open>antimono f\\<close>[THEN antimonoD] cSup_upper S)\n\nlemma continuous_at_Inf_mono:\n  fixes f :: \"'a::{linorder_topology,conditionally_complete_linorder} \\<Rightarrow>\n    'b::{linorder_topology,conditionally_complete_linorder}\"\n  assumes \"mono f\"\n    and cont: \"continuous (at_right (Inf S)) f\"\n    and S: \"S \\<noteq> {}\" \"bdd_below S\"\n  shows \"f (Inf S) = (INF s\\<in>S. f s)\"\nproof (rule antisym)\n  have f: \"(f \\<longlongrightarrow> f (Inf S)) (at_right (Inf S))\"\n    using cont unfolding continuous_within .\n  show \"(INF s\\<in>S. f s) \\<le> f (Inf S)\"\n  proof cases\n    assume \"Inf S \\<in> S\"\n    then show ?thesis\n      by (rule cINF_lower[rotated]) (auto intro: bdd_below_image_mono S \\<open>mono f\\<close>)\n  next\n    assume \"Inf S \\<notin> S\"\n    from \\<open>S \\<noteq> {}\\<close> obtain s where \"s \\<in> S\"\n      by auto\n    with \\<open>Inf S \\<notin> S\\<close> S have \"Inf S < s\"\n      unfolding less_le by (blast intro: cInf_lower)\n    show ?thesis\n    proof (rule ccontr)\n      assume \"\\<not> ?thesis\"\n      with order_tendstoD(2)[OF f, of \"INF s\\<in>S. f s\"] obtain b where \"Inf S < b\"\n        and *: \"\\<And>y. Inf S < y \\<Longrightarrow> y < b \\<Longrightarrow> f y < (INF s\\<in>S. f s)\"\n        by (auto simp: not_le eventually_at_right[OF \\<open>Inf S < s\\<close>])\n      with \\<open>S \\<noteq> {}\\<close> obtain c where \"c \\<in> S\" \"c < b\"\n        using cInf_lessD[of S b] by auto\n      with \\<open>Inf S \\<notin> S\\<close> S have \"Inf S < c\"\n        unfolding less_le by (blast intro: cInf_lower)\n      from *[OF \\<open>Inf S < c\\<close> \\<open>c < b\\<close>] cINF_lower[OF bdd_below_image_mono[of f] \\<open>c \\<in> S\\<close>]\n      show False\n        by (auto simp: assms)\n    qed\n  qed\nqed (intro cINF_greatest \\<open>mono f\\<close>[THEN monoD] cInf_lower \\<open>bdd_below S\\<close> \\<open>S \\<noteq> {}\\<close>)\n\nlemma continuous_at_Inf_antimono:\n  fixes f :: \"'a::{linorder_topology,conditionally_complete_linorder} \\<Rightarrow>\n    'b::{linorder_topology,conditionally_complete_linorder}\"\n  assumes \"antimono f\"\n    and cont: \"continuous (at_right (Inf S)) f\"\n    and S: \"S \\<noteq> {}\" \"bdd_below S\"\n  shows \"f (Inf S) = (SUP s\\<in>S. f s)\"\nproof (rule antisym)\n  have f: \"(f \\<longlongrightarrow> f (Inf S)) (at_right (Inf S))\"\n    using cont unfolding continuous_within .\n  show \"f (Inf S) \\<le> (SUP s\\<in>S. f s)\"\n  proof cases\n    assume \"Inf S \\<in> S\"\n    then show ?thesis\n      by (rule cSUP_upper) (auto intro: bdd_above_image_antimono S \\<open>antimono f\\<close>)\n  next\n    assume \"Inf S \\<notin> S\"\n    from \\<open>S \\<noteq> {}\\<close> obtain s where \"s \\<in> S\"\n      by auto\n    with \\<open>Inf S \\<notin> S\\<close> S have \"Inf S < s\"\n      unfolding less_le by (blast intro: cInf_lower)\n    show ?thesis\n    proof (rule ccontr)\n      assume \"\\<not> ?thesis\"\n      with order_tendstoD(1)[OF f, of \"SUP s\\<in>S. f s\"] obtain b where \"Inf S < b\"\n        and *: \"\\<And>y. Inf S < y \\<Longrightarrow> y < b \\<Longrightarrow> (SUP s\\<in>S. f s) < f y\"\n        by (auto simp: not_le eventually_at_right[OF \\<open>Inf S < s\\<close>])\n      with \\<open>S \\<noteq> {}\\<close> obtain c where \"c \\<in> S\" \"c < b\"\n        using cInf_lessD[of S b] by auto\n      with \\<open>Inf S \\<notin> S\\<close> S have \"Inf S < c\"\n        unfolding less_le by (blast intro: cInf_lower)\n      from *[OF \\<open>Inf S < c\\<close> \\<open>c < b\\<close>] cSUP_upper[OF \\<open>c \\<in> S\\<close> bdd_above_image_antimono[of f]]\n      show False\n        by (auto simp: assms)\n    qed\n  qed\nqed (intro cSUP_least \\<open>antimono f\\<close>[THEN antimonoD] cInf_lower S)\n\n\nsubsection \\<open>Uniform spaces\\<close>\n\nclass uniformity =\n  fixes uniformity :: \"('a \\<times> 'a) filter\"\nbegin\n\nabbreviation uniformity_on :: \"'a set \\<Rightarrow> ('a \\<times> 'a) filter\"\n  where \"uniformity_on s \\<equiv> inf uniformity (principal (s\\<times>s))\"\n\nend\n\nlemma uniformity_Abort:\n  \"uniformity =\n    Filter.abstract_filter (\\<lambda>u. Code.abort (STR ''uniformity is not executable'') (\\<lambda>u. uniformity))\"\n  by simp\n\nclass open_uniformity = \"open\" + uniformity +\n  assumes open_uniformity:\n    \"\\<And>U. open U \\<longleftrightarrow> (\\<forall>x\\<in>U. eventually (\\<lambda>(x', y). x' = x \\<longrightarrow> y \\<in> U) uniformity)\"\nbegin\n\nsubclass topological_space\n  by standard (force elim: eventually_mono eventually_elim2 simp: split_beta' open_uniformity)+\n\nend\n\nclass uniform_space = open_uniformity +\n  assumes uniformity_refl: \"eventually E uniformity \\<Longrightarrow> E (x, x)\"\n    and uniformity_sym: \"eventually E uniformity \\<Longrightarrow> eventually (\\<lambda>(x, y). E (y, x)) uniformity\"\n    and uniformity_trans:\n      \"eventually E uniformity \\<Longrightarrow>\n        \\<exists>D. eventually D uniformity \\<and> (\\<forall>x y z. D (x, y) \\<longrightarrow> D (y, z) \\<longrightarrow> E (x, z))\"\nbegin\n\nlemma uniformity_bot: \"uniformity \\<noteq> bot\"\n  using uniformity_refl by auto\n\nlemma uniformity_trans':\n  \"eventually E uniformity \\<Longrightarrow>\n    eventually (\\<lambda>((x, y), (y', z)). y = y' \\<longrightarrow> E (x, z)) (uniformity \\<times>\\<^sub>F uniformity)\"\n  by (drule uniformity_trans) (auto simp add: eventually_prod_same)\n\nlemma uniformity_transE:\n  assumes \"eventually E uniformity\"\n  obtains D where \"eventually D uniformity\" \"\\<And>x y z. D (x, y) \\<Longrightarrow> D (y, z) \\<Longrightarrow> E (x, z)\"\n  using uniformity_trans [OF assms] by auto\n\nlemma eventually_nhds_uniformity:\n  \"eventually P (nhds x) \\<longleftrightarrow> eventually (\\<lambda>(x', y). x' = x \\<longrightarrow> P y) uniformity\"\n  (is \"_ \\<longleftrightarrow> ?N P x\")\n  unfolding eventually_nhds\nproof safe\n  assume *: \"?N P x\"\n  have \"?N (?N P) x\" if \"?N P x\" for x\n  proof -\n    from that obtain D where ev: \"eventually D uniformity\"\n      and D: \"D (a, b) \\<Longrightarrow> D (b, c) \\<Longrightarrow> case (a, c) of (x', y) \\<Rightarrow> x' = x \\<longrightarrow> P y\" for a b c\n      by (rule uniformity_transE) simp\n    from ev show ?thesis\n      by eventually_elim (insert ev D, force elim: eventually_mono split: prod.split)\n  qed\n  then have \"open {x. ?N P x}\"\n    by (simp add: open_uniformity)\n  then show \"\\<exists>S. open S \\<and> x \\<in> S \\<and> (\\<forall>x\\<in>S. P x)\"\n    by (intro exI[of _ \"{x. ?N P x}\"]) (auto dest: uniformity_refl simp: *)\nqed (force simp add: open_uniformity elim: eventually_mono)\n\n\nsubsubsection \\<open>Totally bounded sets\\<close>\n\ndefinition totally_bounded :: \"'a set \\<Rightarrow> bool\"\n  where \"totally_bounded S \\<longleftrightarrow>\n    (\\<forall>E. eventually E uniformity \\<longrightarrow> (\\<exists>X. finite X \\<and> (\\<forall>s\\<in>S. \\<exists>x\\<in>X. E (x, s))))\"\n\nlemma totally_bounded_empty[iff]: \"totally_bounded {}\"\n  by (auto simp add: totally_bounded_def)\n\nlemma totally_bounded_subset: \"totally_bounded S \\<Longrightarrow> T \\<subseteq> S \\<Longrightarrow> totally_bounded T\"\n  by (fastforce simp add: totally_bounded_def)\n\nlemma totally_bounded_Union[intro]:\n  assumes M: \"finite M\" \"\\<And>S. S \\<in> M \\<Longrightarrow> totally_bounded S\"\n  shows \"totally_bounded (\\<Union>M)\"\n  unfolding totally_bounded_def\nproof safe\n  fix E\n  assume \"eventually E uniformity\"\n  with M obtain X where \"\\<forall>S\\<in>M. finite (X S) \\<and> (\\<forall>s\\<in>S. \\<exists>x\\<in>X S. E (x, s))\"\n    by (metis totally_bounded_def)\n  with \\<open>finite M\\<close> show \"\\<exists>X. finite X \\<and> (\\<forall>s\\<in>\\<Union>M. \\<exists>x\\<in>X. E (x, s))\"\n    by (intro exI[of _ \"\\<Union>S\\<in>M. X S\"]) force\nqed\n\n\nsubsubsection \\<open>Cauchy filter\\<close>\n\ndefinition cauchy_filter :: \"'a filter \\<Rightarrow> bool\"\n  where \"cauchy_filter F \\<longleftrightarrow> F \\<times>\\<^sub>F F \\<le> uniformity\"\n\ndefinition Cauchy :: \"(nat \\<Rightarrow> 'a) \\<Rightarrow> bool\"\n  where Cauchy_uniform: \"Cauchy X = cauchy_filter (filtermap X sequentially)\"\n\nlemma Cauchy_uniform_iff:\n  \"Cauchy X \\<longleftrightarrow> (\\<forall>P. eventually P uniformity \\<longrightarrow> (\\<exists>N. \\<forall>n\\<ge>N. \\<forall>m\\<ge>N. P (X n, X m)))\"\n  unfolding Cauchy_uniform cauchy_filter_def le_filter_def eventually_prod_same\n    eventually_filtermap eventually_sequentially\nproof safe\n  let ?U = \"\\<lambda>P. eventually P uniformity\"\n  {\n    fix P\n    assume \"?U P\" \"\\<forall>P. ?U P \\<longrightarrow> (\\<exists>Q. (\\<exists>N. \\<forall>n\\<ge>N. Q (X n)) \\<and> (\\<forall>x y. Q x \\<longrightarrow> Q y \\<longrightarrow> P (x, y)))\"\n    then obtain Q N where \"\\<And>n. n \\<ge> N \\<Longrightarrow> Q (X n)\" \"\\<And>x y. Q x \\<Longrightarrow> Q y \\<Longrightarrow> P (x, y)\"\n      by metis\n    then show \"\\<exists>N. \\<forall>n\\<ge>N. \\<forall>m\\<ge>N. P (X n, X m)\"\n      by blast\n  next\n    fix P\n    assume \"?U P\" and P: \"\\<forall>P. ?U P \\<longrightarrow> (\\<exists>N. \\<forall>n\\<ge>N. \\<forall>m\\<ge>N. P (X n, X m))\"\n    then obtain Q where \"?U Q\" and Q: \"\\<And>x y z. Q (x, y) \\<Longrightarrow> Q (y, z) \\<Longrightarrow> P (x, z)\"\n      by (auto elim: uniformity_transE)\n    then have \"?U (\\<lambda>x. Q x \\<and> (\\<lambda>(x, y). Q (y, x)) x)\"\n      unfolding eventually_conj_iff by (simp add: uniformity_sym)\n    from P[rule_format, OF this]\n    obtain N where N: \"\\<And>n m. n \\<ge> N \\<Longrightarrow> m \\<ge> N \\<Longrightarrow> Q (X n, X m) \\<and> Q (X m, X n)\"\n      by auto\n    show \"\\<exists>Q. (\\<exists>N. \\<forall>n\\<ge>N. Q (X n)) \\<and> (\\<forall>x y. Q x \\<longrightarrow> Q y \\<longrightarrow> P (x, y))\"\n    proof (safe intro!: exI[of _ \"\\<lambda>x. \\<forall>n\\<ge>N. Q (x, X n) \\<and> Q (X n, x)\"] exI[of _ N] N)\n      fix x y\n      assume \"\\<forall>n\\<ge>N. Q (x, X n) \\<and> Q (X n, x)\" \"\\<forall>n\\<ge>N. Q (y, X n) \\<and> Q (X n, y)\"\n      then have \"Q (x, X N)\" \"Q (X N, y)\" by auto\n      then show \"P (x, y)\"\n        by (rule Q)\n    qed\n  }\nqed\n\nlemma nhds_imp_cauchy_filter:\n  assumes *: \"F \\<le> nhds x\"\n  shows \"cauchy_filter F\"\nproof -\n  have \"F \\<times>\\<^sub>F F \\<le> nhds x \\<times>\\<^sub>F nhds x\"\n    by (intro prod_filter_mono *)\n  also have \"\\<dots> \\<le> uniformity\"\n    unfolding le_filter_def eventually_nhds_uniformity eventually_prod_same\n  proof safe\n    fix P\n    assume \"eventually P uniformity\"\n    then obtain Ql where ev: \"eventually Ql uniformity\"\n      and \"Ql (x, y) \\<Longrightarrow> Ql (y, z) \\<Longrightarrow> P (x, z)\" for x y z\n      by (rule uniformity_transE) simp\n    with ev[THEN uniformity_sym]\n    show \"\\<exists>Q. eventually (\\<lambda>(x', y). x' = x \\<longrightarrow> Q y) uniformity \\<and>\n        (\\<forall>x y. Q x \\<longrightarrow> Q y \\<longrightarrow> P (x, y))\"\n      by (rule_tac exI[of _ \"\\<lambda>y. Ql (y, x) \\<and> Ql (x, y)\"]) (fastforce elim: eventually_elim2)\n  qed\n  finally show ?thesis\n    by (simp add: cauchy_filter_def)\nqed\n\nlemma LIMSEQ_imp_Cauchy: \"X \\<longlonglongrightarrow> x \\<Longrightarrow> Cauchy X\"\n  unfolding Cauchy_uniform filterlim_def by (intro nhds_imp_cauchy_filter)\n\nlemma Cauchy_subseq_Cauchy:\n  assumes \"Cauchy X\" \"strict_mono f\"\n  shows \"Cauchy (X \\<circ> f)\"\n  unfolding Cauchy_uniform comp_def filtermap_filtermap[symmetric] cauchy_filter_def\n  by (rule order_trans[OF _ \\<open>Cauchy X\\<close>[unfolded Cauchy_uniform cauchy_filter_def]])\n     (intro prod_filter_mono filtermap_mono filterlim_subseq[OF \\<open>strict_mono f\\<close>, unfolded filterlim_def])\n\nlemma convergent_Cauchy: \"convergent X \\<Longrightarrow> Cauchy X\"\n  unfolding convergent_def by (erule exE, erule LIMSEQ_imp_Cauchy)\n\ndefinition complete :: \"'a set \\<Rightarrow> bool\"\n  where complete_uniform: \"complete S \\<longleftrightarrow>\n    (\\<forall>F \\<le> principal S. F \\<noteq> bot \\<longrightarrow> cauchy_filter F \\<longrightarrow> (\\<exists>x\\<in>S. F \\<le> nhds x))\"\n\nend\n\n\nsubsubsection \\<open>Uniformly continuous functions\\<close>\n\ndefinition uniformly_continuous_on :: \"'a set \\<Rightarrow> ('a::uniform_space \\<Rightarrow> 'b::uniform_space) \\<Rightarrow> bool\"\n  where uniformly_continuous_on_uniformity: \"uniformly_continuous_on s f \\<longleftrightarrow>\n    (LIM (x, y) (uniformity_on s). (f x, f y) :> uniformity)\"\n\nlemma uniformly_continuous_onD:\n  \"uniformly_continuous_on s f \\<Longrightarrow> eventually E uniformity \\<Longrightarrow>\n    eventually (\\<lambda>(x, y). x \\<in> s \\<longrightarrow> y \\<in> s \\<longrightarrow> E (f x, f y)) uniformity\"\n  by (simp add: uniformly_continuous_on_uniformity filterlim_iff\n      eventually_inf_principal split_beta' mem_Times_iff imp_conjL)\n\nlemma uniformly_continuous_on_const[continuous_intros]: \"uniformly_continuous_on s (\\<lambda>x. c)\"\n  by (auto simp: uniformly_continuous_on_uniformity filterlim_iff uniformity_refl)\n\nlemma uniformly_continuous_on_id[continuous_intros]: \"uniformly_continuous_on s (\\<lambda>x. x)\"\n  by (auto simp: uniformly_continuous_on_uniformity filterlim_def)\n\nlemma uniformly_continuous_on_compose[continuous_intros]:\n  \"uniformly_continuous_on s g \\<Longrightarrow> uniformly_continuous_on (g`s) f \\<Longrightarrow>\n    uniformly_continuous_on s (\\<lambda>x. f (g x))\"\n  using filterlim_compose[of \"\\<lambda>(x, y). (f x, f y)\" uniformity\n      \"uniformity_on (g`s)\"  \"\\<lambda>(x, y). (g x, g y)\" \"uniformity_on s\"]\n  by (simp add: split_beta' uniformly_continuous_on_uniformity\n      filterlim_inf filterlim_principal eventually_inf_principal mem_Times_iff)\n\nlemma uniformly_continuous_imp_continuous:\n  assumes f: \"uniformly_continuous_on s f\"\n  shows \"continuous_on s f\"\n  by (auto simp: filterlim_iff eventually_at_filter eventually_nhds_uniformity continuous_on_def\n           elim: eventually_mono dest!: uniformly_continuous_onD[OF f])\n\n\nsection \\<open>Product Topology\\<close>\n\nsubsection \\<open>Product is a topological space\\<close>\n\ninstantiation prod :: (topological_space, topological_space) topological_space\nbegin\n\ndefinition open_prod_def[code del]:\n  \"open (S :: ('a \\<times> 'b) set) \\<longleftrightarrow>\n    (\\<forall>x\\<in>S. \\<exists>A B. open A \\<and> open B \\<and> x \\<in> A \\<times> B \\<and> A \\<times> B \\<subseteq> S)\"\n\nlemma open_prod_elim:\n  assumes \"open S\" and \"x \\<in> S\"\n  obtains A B where \"open A\" and \"open B\" and \"x \\<in> A \\<times> B\" and \"A \\<times> B \\<subseteq> S\"\n  using assms unfolding open_prod_def by fast\n\nlemma open_prod_intro:\n  assumes \"\\<And>x. x \\<in> S \\<Longrightarrow> \\<exists>A B. open A \\<and> open B \\<and> x \\<in> A \\<times> B \\<and> A \\<times> B \\<subseteq> S\"\n  shows \"open S\"\n  using assms unfolding open_prod_def by fast\n\ninstance\nproof\n  show \"open (UNIV :: ('a \\<times> 'b) set)\"\n    unfolding open_prod_def by auto\nnext\n  fix S T :: \"('a \\<times> 'b) set\"\n  assume \"open S\" \"open T\"\n  show \"open (S \\<inter> T)\"\n  proof (rule open_prod_intro)\n    fix x\n    assume x: \"x \\<in> S \\<inter> T\"\n    from x have \"x \\<in> S\" by simp\n    obtain Sa Sb where A: \"open Sa\" \"open Sb\" \"x \\<in> Sa \\<times> Sb\" \"Sa \\<times> Sb \\<subseteq> S\"\n      using \\<open>open S\\<close> and \\<open>x \\<in> S\\<close> by (rule open_prod_elim)\n    from x have \"x \\<in> T\" by simp\n    obtain Ta Tb where B: \"open Ta\" \"open Tb\" \"x \\<in> Ta \\<times> Tb\" \"Ta \\<times> Tb \\<subseteq> T\"\n      using \\<open>open T\\<close> and \\<open>x \\<in> T\\<close> by (rule open_prod_elim)\n    let ?A = \"Sa \\<inter> Ta\" and ?B = \"Sb \\<inter> Tb\"\n    have \"open ?A \\<and> open ?B \\<and> x \\<in> ?A \\<times> ?B \\<and> ?A \\<times> ?B \\<subseteq> S \\<inter> T\"\n      using A B by (auto simp add: open_Int)\n    then show \"\\<exists>A B. open A \\<and> open B \\<and> x \\<in> A \\<times> B \\<and> A \\<times> B \\<subseteq> S \\<inter> T\"\n      by fast\n  qed\nnext\n  fix K :: \"('a \\<times> 'b) set set\"\n  assume \"\\<forall>S\\<in>K. open S\"\n  then show \"open (\\<Union>K)\"\n    unfolding open_prod_def by fast\nqed\n\nend\n\ndeclare [[code abort: \"open :: ('a::topological_space \\<times> 'b::topological_space) set \\<Rightarrow> bool\"]]\n\nlemma open_Times: \"open S \\<Longrightarrow> open T \\<Longrightarrow> open (S \\<times> T)\"\n  unfolding open_prod_def by auto\n\nlemma fst_vimage_eq_Times: \"fst -` S = S \\<times> UNIV\"\n  by auto\n\nlemma snd_vimage_eq_Times: \"snd -` S = UNIV \\<times> S\"\n  by auto\n\nlemma open_vimage_fst: \"open S \\<Longrightarrow> open (fst -` S)\"\n  by (simp add: fst_vimage_eq_Times open_Times)\n\nlemma open_vimage_snd: \"open S \\<Longrightarrow> open (snd -` S)\"\n  by (simp add: snd_vimage_eq_Times open_Times)\n\nlemma closed_vimage_fst: \"closed S \\<Longrightarrow> closed (fst -` S)\"\n  unfolding closed_open vimage_Compl [symmetric]\n  by (rule open_vimage_fst)\n\nlemma closed_vimage_snd: \"closed S \\<Longrightarrow> closed (snd -` S)\"\n  unfolding closed_open vimage_Compl [symmetric]\n  by (rule open_vimage_snd)\n\nlemma closed_Times: \"closed S \\<Longrightarrow> closed T \\<Longrightarrow> closed (S \\<times> T)\"\nproof -\n  have \"S \\<times> T = (fst -` S) \\<inter> (snd -` T)\"\n    by auto\n  then show \"closed S \\<Longrightarrow> closed T \\<Longrightarrow> closed (S \\<times> T)\"\n    by (simp add: closed_vimage_fst closed_vimage_snd closed_Int)\nqed\n\nlemma subset_fst_imageI: \"A \\<times> B \\<subseteq> S \\<Longrightarrow> y \\<in> B \\<Longrightarrow> A \\<subseteq> fst ` S\"\n  unfolding image_def subset_eq by force\n\nlemma subset_snd_imageI: \"A \\<times> B \\<subseteq> S \\<Longrightarrow> x \\<in> A \\<Longrightarrow> B \\<subseteq> snd ` S\"\n  unfolding image_def subset_eq by force\n\nlemma open_image_fst:\n  assumes \"open S\"\n  shows \"open (fst ` S)\"\nproof (rule openI)\n  fix x\n  assume \"x \\<in> fst ` S\"\n  then obtain y where \"(x, y) \\<in> S\"\n    by auto\n  then obtain A B where \"open A\" \"open B\" \"x \\<in> A\" \"y \\<in> B\" \"A \\<times> B \\<subseteq> S\"\n    using \\<open>open S\\<close> unfolding open_prod_def by auto\n  from \\<open>A \\<times> B \\<subseteq> S\\<close> \\<open>y \\<in> B\\<close> have \"A \\<subseteq> fst ` S\"\n    by (rule subset_fst_imageI)\n  with \\<open>open A\\<close> \\<open>x \\<in> A\\<close> have \"open A \\<and> x \\<in> A \\<and> A \\<subseteq> fst ` S\"\n    by simp\n  then show \"\\<exists>T. open T \\<and> x \\<in> T \\<and> T \\<subseteq> fst ` S\" ..\nqed\n\nlemma open_image_snd:\n  assumes \"open S\"\n  shows \"open (snd ` S)\"\nproof (rule openI)\n  fix y\n  assume \"y \\<in> snd ` S\"\n  then obtain x where \"(x, y) \\<in> S\"\n    by auto\n  then obtain A B where \"open A\" \"open B\" \"x \\<in> A\" \"y \\<in> B\" \"A \\<times> B \\<subseteq> S\"\n    using \\<open>open S\\<close> unfolding open_prod_def by auto\n  from \\<open>A \\<times> B \\<subseteq> S\\<close> \\<open>x \\<in> A\\<close> have \"B \\<subseteq> snd ` S\"\n    by (rule subset_snd_imageI)\n  with \\<open>open B\\<close> \\<open>y \\<in> B\\<close> have \"open B \\<and> y \\<in> B \\<and> B \\<subseteq> snd ` S\"\n    by simp\n  then show \"\\<exists>T. open T \\<and> y \\<in> T \\<and> T \\<subseteq> snd ` S\" ..\nqed\n\nlemma nhds_prod: \"nhds (a, b) = nhds a \\<times>\\<^sub>F nhds b\"\n  unfolding nhds_def\nproof (subst prod_filter_INF, auto intro!: antisym INF_greatest simp: principal_prod_principal)\n  fix S T\n  assume \"open S\" \"a \\<in> S\" \"open T\" \"b \\<in> T\"\n  then show \"(INF x \\<in> {S. open S \\<and> (a, b) \\<in> S}. principal x) \\<le> principal (S \\<times> T)\"\n    by (intro INF_lower) (auto intro!: open_Times)\nnext\n  fix S'\n  assume \"open S'\" \"(a, b) \\<in> S'\"\n  then obtain S T where \"open S\" \"a \\<in> S\" \"open T\" \"b \\<in> T\" \"S \\<times> T \\<subseteq> S'\"\n    by (auto elim: open_prod_elim)\n  then show \"(INF x \\<in> {S. open S \\<and> a \\<in> S}. INF y \\<in> {S. open S \\<and> b \\<in> S}.\n      principal (x \\<times> y)) \\<le> principal S'\"\n    by (auto intro!: INF_lower2)\nqed\n\n\nsubsubsection \\<open>Continuity of operations\\<close>\n\nlemma tendsto_fst [tendsto_intros]:\n  assumes \"(f \\<longlongrightarrow> a) F\"\n  shows \"((\\<lambda>x. fst (f x)) \\<longlongrightarrow> fst a) F\"\nproof (rule topological_tendstoI)\n  fix S\n  assume \"open S\" and \"fst a \\<in> S\"\n  then have \"open (fst -` S)\" and \"a \\<in> fst -` S\"\n    by (simp_all add: open_vimage_fst)\n  with assms have \"eventually (\\<lambda>x. f x \\<in> fst -` S) F\"\n    by (rule topological_tendstoD)\n  then show \"eventually (\\<lambda>x. fst (f x) \\<in> S) F\"\n    by simp\nqed\n\nlemma tendsto_snd [tendsto_intros]:\n  assumes \"(f \\<longlongrightarrow> a) F\"\n  shows \"((\\<lambda>x. snd (f x)) \\<longlongrightarrow> snd a) F\"\nproof (rule topological_tendstoI)\n  fix S\n  assume \"open S\" and \"snd a \\<in> S\"\n  then have \"open (snd -` S)\" and \"a \\<in> snd -` S\"\n    by (simp_all add: open_vimage_snd)\n  with assms have \"eventually (\\<lambda>x. f x \\<in> snd -` S) F\"\n    by (rule topological_tendstoD)\n  then show \"eventually (\\<lambda>x. snd (f x) \\<in> S) F\"\n    by simp\nqed\n\nlemma tendsto_Pair [tendsto_intros]:\n  assumes \"(f \\<longlongrightarrow> a) F\" and \"(g \\<longlongrightarrow> b) F\"\n  shows \"((\\<lambda>x. (f x, g x)) \\<longlongrightarrow> (a, b)) F\"\n  unfolding nhds_prod using assms by (rule filterlim_Pair)\n\nlemma continuous_fst[continuous_intros]: \"continuous F f \\<Longrightarrow> continuous F (\\<lambda>x. fst (f x))\"\n  unfolding continuous_def by (rule tendsto_fst)\n\nlemma continuous_snd[continuous_intros]: \"continuous F f \\<Longrightarrow> continuous F (\\<lambda>x. snd (f x))\"\n  unfolding continuous_def by (rule tendsto_snd)\n\nlemma continuous_Pair[continuous_intros]:\n  \"continuous F f \\<Longrightarrow> continuous F g \\<Longrightarrow> continuous F (\\<lambda>x. (f x, g x))\"\n  unfolding continuous_def by (rule tendsto_Pair)\n\nlemma continuous_on_fst[continuous_intros]:\n  \"continuous_on s f \\<Longrightarrow> continuous_on s (\\<lambda>x. fst (f x))\"\n  unfolding continuous_on_def by (auto intro: tendsto_fst)\n\nlemma continuous_on_snd[continuous_intros]:\n  \"continuous_on s f \\<Longrightarrow> continuous_on s (\\<lambda>x. snd (f x))\"\n  unfolding continuous_on_def by (auto intro: tendsto_snd)\n\nlemma continuous_on_Pair[continuous_intros]:\n  \"continuous_on s f \\<Longrightarrow> continuous_on s g \\<Longrightarrow> continuous_on s (\\<lambda>x. (f x, g x))\"\n  unfolding continuous_on_def by (auto intro: tendsto_Pair)\n\nlemma continuous_on_swap[continuous_intros]: \"continuous_on A prod.swap\"\n  by (simp add: prod.swap_def continuous_on_fst continuous_on_snd\n      continuous_on_Pair continuous_on_id)\n\nlemma continuous_on_swap_args:\n  assumes \"continuous_on (A\\<times>B) (\\<lambda>(x,y). d x y)\"\n    shows \"continuous_on (B\\<times>A) (\\<lambda>(x,y). d y x)\"\nproof -\n  have \"(\\<lambda>(x,y). d y x) = (\\<lambda>(x,y). d x y) \\<circ> prod.swap\"\n    by force\n  then show ?thesis\n    by (metis assms continuous_on_compose continuous_on_swap product_swap)\nqed\n\nlemma isCont_fst [simp]: \"isCont f a \\<Longrightarrow> isCont (\\<lambda>x. fst (f x)) a\"\n  by (fact continuous_fst)\n\nlemma isCont_snd [simp]: \"isCont f a \\<Longrightarrow> isCont (\\<lambda>x. snd (f x)) a\"\n  by (fact continuous_snd)\n\nlemma isCont_Pair [simp]: \"\\<lbrakk>isCont f a; isCont g a\\<rbrakk> \\<Longrightarrow> isCont (\\<lambda>x. (f x, g x)) a\"\n  by (fact continuous_Pair)\n\nlemma continuous_on_compose_Pair:\n  assumes f: \"continuous_on (Sigma A B) (\\<lambda>(a, b). f a b)\"\n  assumes g: \"continuous_on C g\"\n  assumes h: \"continuous_on C h\"\n  assumes subset: \"\\<And>c. c \\<in> C \\<Longrightarrow> g c \\<in> A\" \"\\<And>c. c \\<in> C \\<Longrightarrow> h c \\<in> B (g c)\"\n  shows \"continuous_on C (\\<lambda>c. f (g c) (h c))\"\n  using continuous_on_compose2[OF f continuous_on_Pair[OF g h]] subset\n  by auto\n\n\nsubsubsection \\<open>Connectedness of products\\<close>\n\nproposition connected_Times:\n  assumes S: \"connected S\" and T: \"connected T\"\n  shows \"connected (S \\<times> T)\"\nproof (rule connectedI_const)\n  fix P::\"'a \\<times> 'b \\<Rightarrow> bool\"\n  assume P[THEN continuous_on_compose2, continuous_intros]: \"continuous_on (S \\<times> T) P\"\n  have \"continuous_on S (\\<lambda>s. P (s, t))\" if \"t \\<in> T\" for t\n    by (auto intro!: continuous_intros that)\n  from connectedD_const[OF S this]\n  obtain c1 where c1: \"\\<And>s t. t \\<in> T \\<Longrightarrow> s \\<in> S \\<Longrightarrow> P (s, t) = c1 t\"\n    by metis\n  moreover\n  have \"continuous_on T (\\<lambda>t. P (s, t))\" if \"s \\<in> S\" for s\n    by (auto intro!: continuous_intros that)\n  from connectedD_const[OF T this]\n  obtain c2 where \"\\<And>s t. t \\<in> T \\<Longrightarrow> s \\<in> S \\<Longrightarrow> P (s, t) = c2 s\"\n    by metis\n  ultimately show \"\\<exists>c. \\<forall>s\\<in>S \\<times> T. P s = c\"\n    by auto\nqed\n\ncorollary connected_Times_eq [simp]:\n   \"connected (S \\<times> T) \\<longleftrightarrow> S = {} \\<or> T = {} \\<or> connected S \\<and> connected T\"  (is \"?lhs = ?rhs\")\nproof\n  assume L: ?lhs\n  show ?rhs\n  proof cases\n    assume \"S \\<noteq> {} \\<and> T \\<noteq> {}\"\n    moreover\n    have \"connected (fst ` (S \\<times> T))\" \"connected (snd ` (S \\<times> T))\"\n      using continuous_on_fst continuous_on_snd continuous_on_id\n      by (blast intro: connected_continuous_image [OF _ L])+\n    ultimately show ?thesis\n      by auto\n  qed auto\nqed (auto simp: connected_Times)\n\n\nsubsubsection \\<open>Separation axioms\\<close>\n\ninstance prod :: (t0_space, t0_space) t0_space\nproof\n  fix x y :: \"'a \\<times> 'b\"\n  assume \"x \\<noteq> y\"\n  then have \"fst x \\<noteq> fst y \\<or> snd x \\<noteq> snd y\"\n    by (simp add: prod_eq_iff)\n  then show \"\\<exists>U. open U \\<and> (x \\<in> U) \\<noteq> (y \\<in> U)\"\n    by (fast dest: t0_space elim: open_vimage_fst open_vimage_snd)\nqed\n\ninstance prod :: (t1_space, t1_space) t1_space\nproof\n  fix x y :: \"'a \\<times> 'b\"\n  assume \"x \\<noteq> y\"\n  then have \"fst x \\<noteq> fst y \\<or> snd x \\<noteq> snd y\"\n    by (simp add: prod_eq_iff)\n  then show \"\\<exists>U. open U \\<and> x \\<in> U \\<and> y \\<notin> U\"\n    by (fast dest: t1_space elim: open_vimage_fst open_vimage_snd)\nqed\n\ninstance prod :: (t2_space, t2_space) t2_space\nproof\n  fix x y :: \"'a \\<times> 'b\"\n  assume \"x \\<noteq> y\"\n  then have \"fst x \\<noteq> fst y \\<or> snd x \\<noteq> snd y\"\n    by (simp add: prod_eq_iff)\n  then show \"\\<exists>U V. open U \\<and> open V \\<and> x \\<in> U \\<and> y \\<in> V \\<and> U \\<inter> V = {}\"\n    by (fast dest: hausdorff elim: open_vimage_fst open_vimage_snd)\nqed\n\nlemma isCont_swap[continuous_intros]: \"isCont prod.swap a\"\n  using continuous_on_eq_continuous_within continuous_on_swap by blast\n\nlemma open_diagonal_complement:\n  \"open {(x,y) |x y. x \\<noteq> (y::('a::t2_space))}\"\nproof -\n  have \"open {(x, y). x \\<noteq> (y::'a)}\"\n    unfolding split_def by (intro open_Collect_neq continuous_intros)\n  also have \"{(x, y). x \\<noteq> (y::'a)} = {(x, y) |x y. x \\<noteq> (y::'a)}\"\n    by auto\n  finally show ?thesis .\nqed\n\nlemma closed_diagonal:\n  \"closed {y. \\<exists> x::('a::t2_space). y = (x,x)}\"\nproof -\n  have \"{y. \\<exists> x::'a. y = (x,x)} = UNIV - {(x,y) | x y. x \\<noteq> y}\" by auto\n  then show ?thesis using open_diagonal_complement closed_Diff by auto\nqed\n\nlemma open_superdiagonal:\n  \"open {(x,y) | x y. x > (y::'a::{linorder_topology})}\"\nproof -\n  have \"open {(x, y). x > (y::'a)}\"\n    unfolding split_def by (intro open_Collect_less continuous_intros)\n  also have \"{(x, y). x > (y::'a)} = {(x, y) |x y. x > (y::'a)}\"\n    by auto\n  finally show ?thesis .\nqed\n\nlemma closed_subdiagonal:\n  \"closed {(x,y) | x y. x \\<le> (y::'a::{linorder_topology})}\"\nproof -\n  have \"{(x,y) | x y. x \\<le> (y::'a)} = UNIV - {(x,y) | x y. x > (y::'a)}\" by auto\n  then show ?thesis using open_superdiagonal closed_Diff by auto\nqed\n\nlemma open_subdiagonal:\n  \"open {(x,y) | x y. x < (y::'a::{linorder_topology})}\"\nproof -\n  have \"open {(x, y). x < (y::'a)}\"\n    unfolding split_def by (intro open_Collect_less continuous_intros)\n  also have \"{(x, y). x < (y::'a)} = {(x, y) |x y. x < (y::'a)}\"\n    by auto\n  finally show ?thesis .\nqed\n\nlemma closed_superdiagonal:\n  \"closed {(x,y) | x y. x \\<ge> (y::('a::{linorder_topology}))}\"\nproof -\n  have \"{(x,y) | x y. x \\<ge> (y::'a)} = UNIV - {(x,y) | x y. x < y}\" by auto\n  then show ?thesis using open_subdiagonal closed_Diff by auto\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/Topological_Spaces.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8652240930029118, "lm_q2_score": 0.8418256472515683, "lm_q1q2_score": 0.7283678321098274}}
{"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 Lattice_Locale\n \nimports \n  Order_Locale\n\nbegin\n\ntext {*\n\nA lattice is non-empty set @{text X} with operators \n@{text \"\\<sqinter>\"} ({\\em meet}) and @{text \"\\<squnion>\"} ({\\em join}) that\nare idempotent, commutative, associative and which satisfy the absorption\nlaw.\n\n*}\n\nno_notation Lattices.inf (infixl \"\\<sqinter>\" 70)\nno_notation Lattices.sup (infixl \"\\<squnion>\" 65)\n\nno_notation Complete_Lattices.Inf (\"\\<Sqinter>_\" [900] 900)\n\nno_notation Complete_Lattices.Sup (\"\\<Squnion>_\" [900] 900)\n\nlocale lattice_sig =\n  carrier_sig X \n  for \n    X :: \"'a set\" +\n  fixes\n    BS_sqcap ::\"['a, 'a] \\<rightarrow> 'a\" (infixl \"\\<sqinter>\" 70) and\n    BS_sqcup ::\"['a, 'a] \\<rightarrow> 'a\" (infixl \"\\<squnion>\" 65)\n\nlocale pure_lattice = \n  carrier + \n  lattice_sig +\nassumes\n  meetR [simp]: \"\\<lbrakk> x \\<in> X; y \\<in> X \\<rbrakk> \\<turnstile> x \\<sqinter> y \\<in> X\" and\n  meetID: \"x \\<in> X \\<turnstile> x \\<sqinter> x = x\" and\n  meetC: \"\\<lbrakk> x \\<in> X; y \\<in> X \\<rbrakk> \\<turnstile> x \\<sqinter> y = y \\<sqinter> x\" and\n  meetA: \"\\<lbrakk> x \\<in> X; y \\<in> X; z \\<in> X \\<rbrakk> \\<turnstile> (x \\<sqinter> y) \\<sqinter> z = x \\<sqinter> (y \\<sqinter> z)\" and\n  meetAB: \"\\<lbrakk> x \\<in> X; y \\<in> X \\<rbrakk> \\<turnstile> x \\<sqinter> (x \\<squnion> y) = x\" and\n  joinR [simp]: \"\\<lbrakk> x \\<in> X; y \\<in> X \\<rbrakk> \\<turnstile> x \\<squnion> y \\<in> X\" and\n  joinID: \"x \\<in> X \\<turnstile> x \\<squnion> x = x\" and\n  joinC: \"\\<lbrakk> x \\<in> X; y \\<in> X \\<rbrakk> \\<turnstile> x \\<squnion> y = y \\<squnion> x\" and\n  joinA: \"\\<lbrakk> x \\<in> X; y \\<in> X; z \\<in> X \\<rbrakk> \\<turnstile> (x \\<squnion> y) \\<squnion> z = x \\<squnion> (y \\<squnion> z)\" and\n  joinAB: \"\\<lbrakk> x \\<in> X; y \\<in> X \\<rbrakk> \\<turnstile> x \\<squnion> (x \\<sqinter> y) = x\"\n\nbegin\n\nlemmas pure_lattice_carrier = carrier\n\nend\n\nnotation (zed)\n  pure_lattice (\"\\<^purelat>{:_:}{:_:}{:_:}\")\n\nlemma (in pure_lattice) pure_lattice:\n    \"\\<^purelat>{:X:}{:BS_sqcap:}{:BS_sqcup:}\"\n  by (intro_locales)\n\n\nlemma (in pure_lattice) meetLC:\n  assumes \n    a1: \"x \\<in> X\" \"y \\<in> X\" \"z \\<in> X\"\n  shows \n    \"x \\<sqinter> (y \\<sqinter> z) = y \\<sqinter> (x \\<sqinter> z)\"\n  apply (rule AC_LC' [of \"BS_sqcap\"])\n  apply (auto intro!: meetA meetC a1)\n  done \n\nlemma (in pure_lattice) joinLC:\n  assumes \n    a1: \"x \\<in> X\" \"y \\<in> X\" \"z \\<in> X\"\n  shows \n    \"x \\<squnion> (y \\<squnion> z) = y \\<squnion> (x \\<squnion> z)\"\n  apply (rule AC_LC' [of \"BS_sqcup\"])\n  apply (auto intro: joinA joinC a1)\n  done\n                                                                         \ntext {* \n\nThe default ordering on a lattice is generated by relating all pairs,\n@{text x} and @{text y}\nfor which @{text \"x \\<sqinter> y = x\"} (or equivalently for which @{text \"y \\<squnion> x = y\"}). \nUnder this order, the lattice forms a poset.\n\n*}\n\ncontext lattice_sig\n\nbegin\n\ndefinition\n  meet_order :: \"['a, 'a] \\<rightarrow> \\<bool>\"\nwhere\n  meet_order_def: \"meet_order \\<defs> (\\<olambda> x y \\<bullet> \\<lch> x, y \\<chIn> X \\<rch> \\<and> x \\<sqinter> y = x)\"\n\nnotation (xsymbols)\n  meet_order (infixl \"\\<sqsubseteq>\\<^sub>\\<sqinter>\" 50)\n\ndefinition\n  join_order :: \"['a, 'a] \\<rightarrow> \\<bool>\"\nwhere\n  join_order_def: \"join_order \\<defs> (\\<olambda> x y \\<bullet> \\<lch> x, y \\<chIn> X \\<rch> \\<and> y \\<squnion> x = y)\"\n\nnotation (xsymbols)\n  join_order (infixl \"\\<sqsubseteq>\\<^sub>\\<squnion>\" 50)\n\nend\n\nlemma (in pure_lattice) order_equiv: \n    \"(op \\<sqsubseteq>\\<^sub>\\<sqinter>) = (op \\<sqsubseteq>\\<^sub>\\<squnion>)\"\nproof (simp add: meet_order_def join_order_def fun_eq_def, intro allI, mauto(wind))\n  fix x y \n  assume \n    b1: \"x \\<in> X\" \"y \\<in> X\" \n  show \n      \"x \\<sqinter> y = x \\<Leftrightarrow> y \\<squnion> x = y\"\n  proof (msafe(inference))\n    assume \n        \"x \\<sqinter> y = x\"\n    then have \n        \"y \\<squnion> x\n        = y \\<squnion> (x \\<sqinter> y)\"\n      by (simp)\n    also have \"\\<dots>\n        =  y \\<squnion> (y \\<sqinter> x)\"\n      by (simp add: b1 meetC)\n    also have \"\\<dots>\n        = y\"\n      by (simp add: b1 joinAB)\n    finally show \n        \"y \\<squnion> x = y\"\n      by (this)\n  next\n    assume \n        \"y \\<squnion> x = y\"\n    then have \n        \"x \\<sqinter> y\n        = x \\<sqinter> (y \\<squnion> x)\"\n      by (simp)\n    also have \"\\<dots>\n        =  x \\<sqinter> (x \\<squnion> y)\"\n      by (simp add: b1 joinC)\n    also have \"\\<dots>\n        = x\"\n      by (simp add: b1 meetAB)\n    finally show \n        \"x \\<sqinter> y = x\" \n      by (this)\n  qed\nqed\n\nlocale po_lattice = \n  pure_lattice X BS_sqcap BS_sqcup + \n  setrel_sig X r\n\nfor \n  X :: \"'a set\" and\n  r :: \"'a orderT\" and\n  BS_sqcap ::\"['a, 'a] \\<rightarrow> 'a\" (infixl \"\\<sqinter>\" 70) and\n  BS_sqcup ::\"['a, 'a] \\<rightarrow> 'a\" (infixl \"\\<squnion>\" 65) +\nassumes\n  r_def: \"r \\<defs> (op \\<sqsubseteq>\\<^sub>\\<sqinter>)\"\n\nbegin\n\nnotation\n r (infixl \"\\<sqsubseteq>\" 50)\n\nlemmas po_lattice_pure_lattice = pure_lattice\n\nend\n\nnotation (zed)\n  po_lattice (\"\\<^polat>{:_:}{:_:}{:_:}{:_:}\")\n\nlemma (in po_lattice) po_lattice:\n    \"\\<^polat>{:X:}{:(op \\<sqsubseteq>):}{:BS_sqcap:}{:BS_sqcup:}\"\n  by (unfold_locales)\n\nsublocale po_lattice \\<subseteq> lpo: partial_order\n  apply (intro_locales)\n  apply (simp_all add: setrel_axioms_def reflexive_axioms_def transitive_axioms_def antisymmetric_axioms_def r_def meet_order_def)\n  apply (msafe(inference))\nproof -\n  show \n      \"\\<^oprel>{:(\\<olambda> x y \\<bullet> x \\<in> X \\<and> y \\<in> X \\<and> x \\<sqinter> y = x):} \\<in> X \\<zrel> X\"\n    by (auto simp add: rel_def op2rel_def)\nnext\n  fix x assume \n    b1: \"x \\<in> X\"\n  then show \n      \"x \\<sqinter> x = x\"\n    by (rule meetID)\nnext \n  fix x y z \n  assume \n    c1: \"x \\<in> X\" \"y \\<in> X\" \"z \\<in> X\" and \n    c2: \"x \\<sqinter> y = x\" and \n    c3: \"y \\<sqinter> z = y\" \n  have \n      \"x \\<sqinter> z\n      = (x \\<sqinter> y) \\<sqinter> z\"\n    by (simp add: c2)\n  also have \"\\<dots>\n      = x \\<sqinter> (y \\<sqinter> z)\"\n    by (simp add: c1 meetA)\n  also have \"\\<dots> \n      = x \\<sqinter> y\"\n    by (simp add: c3)\n  also have \"\\<dots>\n      = x\"\n    by (simp add: c2)\n  finally show \n      \"x \\<sqinter> z = x\"  \n    by (this)\nnext\n  fix x y\n  assume \n      \"x \\<in> X\" \n      \"y \\<in> X\" \n      \"x \\<sqinter> y = x\" \n      \"y \\<sqinter> x = y\"\n  then show \n      \"x = y\"\n    by (auto simp add: meetC)\nqed\n\nlemmas (in po_lattice) po_lattice_partial_order = lpo.partial_order\n\ntext {*\n\nThe meet and join operators are then pairwise glb and lub respectively.\n\n*}\n\ncontext po_lattice \n\nbegin\n\nlemma meet_glb:\n  assumes \n    a1: \"x \\<in> X\" \"y \\<in> X\"\n  shows   \n    \"is_glb {x, y} (x \\<sqinter> y)\"\nproof (rule is_glbI)\n  show \n      \"x \\<sqinter> y \\<in> X\"\n    by (simp add: a1 meetR)\nnext\n  fix a assume \n    b1: \"a \\<in> {x, y}\"\n  then show \n      \"x \\<sqinter> y \\<sqsubseteq> a\"\n  proof (cases \"a = x\", simp_all)\n    have \n        \"(x \\<sqinter> y) \\<sqinter> x\n        = (x \\<sqinter> x) \\<sqinter> y\"\n      by (simp add: a1 meetC meetA meetLC)\n    also have \"\\<dots> \n        = x \\<sqinter> y\"\n      by (simp add: a1 meetID)\n    finally show \n        \"(x \\<sqinter> y) \\<sqsubseteq> x\"\n      by (simp add: a1 r_def meet_order_def)\n  next\n    have \n        \"(x \\<sqinter> y) \\<sqinter> y\n        = x \\<sqinter> (y \\<sqinter> y)\"\n      by (simp add: a1 meetC meetA meetLC)\n    also have \"\\<dots> \n        = x \\<sqinter> y\"\n      by (simp add: a1 meetID)\n    finally show \n        \"(x \\<sqinter> y) \\<sqsubseteq> y\"\n      by (simp add: a1 r_def meet_order_def)\n  qed\nnext\n  fix b\n  assume \n    b1: \"b \\<in> X\" and \n    b2: \"\\<forall> z \\<bullet> z \\<in> {x, y} \\<Rightarrow> b \\<sqsubseteq> z\"\n  from b2 have \n    b3: \"b \\<sqinter> x = b\"\n    by (simp add: a1 r_def meet_order_def)\n  from b2 have \n    b4: \"b \\<sqinter> y = b\"\n    by (simp add: a1 r_def meet_order_def)\n  have \n      \"b \\<sqinter> (x \\<sqinter> y) \n      = (b \\<sqinter> x) \\<sqinter> y\"\n    by (simp add: b1 a1 meetC meetA meetLC)\n  also have \"\\<dots>\n      = b \\<sqinter> y\"\n    by (simp add: b3)\n  also have \"\\<dots>\n      = b\"\n    by (simp add: b4)\n  finally show \n      \"b \\<sqsubseteq> (x \\<sqinter> y)\"\n    by (simp add: b1 a1 r_def meet_order_def)\nqed\n\nlemma join_lub:\n  assumes \n    a1: \"x \\<in> X\" \"y \\<in> X\"\n  shows\n    \"is_lub {x, y} (x \\<squnion> y)\"\nproof (rule is_lubI)\n  show \n      \"x \\<squnion> y \\<in> X\"\n    by (simp add: a1)\nnext\n  fix a assume \n    b1: \"a \\<in> {x, y}\"\n  then show \n      \"a \\<sqsubseteq> (x \\<squnion> y)\"\n  proof (cases \"a = x\", simp_all)\n    have \n        \"(x \\<squnion> y) \\<squnion> x\n        = (x \\<squnion> x) \\<squnion> y\"\n      by (simp add: a1 joinC joinA joinLC)\n    also have \"\\<dots> \n        = x \\<squnion> y\"\n      by (simp add: a1 joinID)\n    finally show \n        \"x \\<sqsubseteq> (x \\<squnion> y)\"\n      by (simp add: a1 r_def order_equiv join_order_def)\n  next\n    have \n        \"(x \\<squnion> y) \\<squnion> y\n        = x \\<squnion> (y \\<squnion> y)\"\n      by (simp add: a1 joinC joinA joinLC)\n    also have \"\\<dots> \n        = x \\<squnion> y\"\n      by (simp add: a1 joinID)\n    finally show \n        \"y \\<sqsubseteq> (x \\<squnion> y)\"\n      by (simp add: a1 r_def order_equiv join_order_def)\n  qed\nnext\n  fix b\n  assume \n    b1: \"b \\<in> X\" and \n    b2: \"\\<forall> z \\<bullet> z \\<in> {x, y} \\<Rightarrow> z \\<sqsubseteq> b\"\n  from b2 have \n    b3: \"b \\<squnion> x = b\"\n    by (simp add: b1 a1 r_def order_equiv join_order_def joinC)\n  from b2 have \n    b4: \"b \\<squnion> y = b\"\n    by (simp add: b1 a1 r_def order_equiv join_order_def joinC)\n  have \n      \"b \\<squnion> (x \\<squnion> y) \n      = (b \\<squnion> x) \\<squnion> y\"\n    by (simp add: b1 a1 joinC joinA joinLC)\n  also have \"\\<dots>\n      = b \\<squnion> y\"\n    by (simp add: b3)\n  also have \"\\<dots>\n      = b\"\n    by (simp add: b4)\n  finally show \n      \"(x \\<squnion> y) \\<sqsubseteq> b\"\n    by (simp add: b1 a1 r_def order_equiv join_order_def joinC)\nqed\n\nend\n\ntext {*\n\nIn fact these properties of meet and join can be used to induce a lattice\nstructure on any poset with pairwise glb lub, thus giving an order-centric\ndevelopment of lattice theory.\n\n*}\n\ndefinition\n  meet :: \"['a, 'a set, 'a orderT, 'a] \\<rightarrow> 'a\"\nwhere\n  meet_def: \"meet \\<defs> (\\<olambda> x X r y \\<bullet> (\\<mu> a | \\<^glbp>{:X:}{:r:} {x, y} a))\"\n\ndefinition\n  join :: \"['a, 'a set, 'a orderT, 'a] \\<rightarrow> 'a\"\nwhere\n  join_def: \"join \\<defs> (\\<olambda> x X r y \\<bullet> (\\<mu> a | \\<^lubp>{:X:}{:r:} {x, y} a))\"\n\nnotation (xsymbols output)\n  meet (\"_ \\<sqinter>\\<^bsub>_, _\\<^esub> _\" [70, 0, 0, 71] 70) and\n  join (\"_ \\<squnion>\\<^bsub>_, _\\<^esub> _\" [65, 0, 0, 66] 65)\n\nnotation (zed)\n  meet (\"_ \\<^meet>{:_:}{:_:} _\" [70, 0, 0, 71] 70) and\n  meet (\"_ \\<^meeta>{:_:}{:_:} _\" [70, 0, 0, 71] 70) and\n  join (\"_ \\<^join>{:_:}{:_:} _\" [65, 0, 0, 66] 65) and\n  join (\"_ \\<^joina>{:_:}{:_:} _\" [65, 0, 0, 66] 65)\n\ndefinition\n  meet_op :: \"['a set, 'a orderT, 'a, 'a] \\<rightarrow> 'a\"\nwhere\n  meet_op_def [simp]: \"meet_op \\<defs> (\\<olambda> X r x y \\<bullet> x \\<^meet>{:X:}{:r:} y)\"\n\ndefinition\n  join_op :: \"['a set, 'a orderT, 'a, 'a] \\<rightarrow> 'a\"\nwhere\n  join_op_def [simp]: \"join_op \\<defs> (\\<olambda> X r x y \\<bullet> x \\<^join>{:X:}{:r:} y)\"\n\nnotation (xsymbols output)\n  meet_op (\"op \\<sqinter>\\<^bsub>_, _\\<^esub>\" 0) and\n  join_op (\"op \\<squnion>\\<^bsub>_, _\\<^esub>\" 0)\n\nnotation (zed)\n  meet_op (\"\\<^meetop>{:_:}{:_:}\") and\n  join_op (\"\\<^joinop>{:_:}{:_:}\")\n\ncontext setrel_sig\n\nbegin\n\nabbreviation\n  meet :: \"['a, 'a] \\<rightarrow> 'a\"\nwhere\n  \"meet \\<defs> (\\<olambda> x y \\<bullet> x \\<^meet>{:X:}{:(op \\<hookrightarrow>):} y)\"\n\nabbreviation\n  join :: \"['a, 'a] \\<rightarrow> 'a\"\nwhere\n  \"join \\<defs> (\\<olambda> x y \\<bullet> x \\<^join>{:X:}{:(op \\<hookrightarrow>):} y)\"\n\nnotation\n  meet (infixl \"\\<sqinter>\" 70) and\n  join (infixl \"\\<squnion>\" 65)\n\nend\n\ncontext partial_order\n\nbegin\n\nlemma meet_unique:\n  assumes \n    a1:\"is_glb {x, y} a\"\n  shows\n    \"a = x \\<sqinter> y\"\n  apply (unfold meet_def)\n  apply (rule the_equality [symmetric])\n  apply (rule a1)\n  apply (rule glb_unique)\n  apply (rule a1)\n  apply (assumption)\n  done\n\nlemma join_unique:\n  assumes \n    a1:\"is_lub {x, y} a\"\n  shows\n    \"a = x \\<squnion> y\"\n  apply (unfold join_def)\n  apply (rule the_equality [symmetric])\n  apply (rule a1)\n  apply (rule lub_unique)\n  apply (rule a1)\n  apply (assumption)\n  done\n\nend\n\nlocale lattice = \n  partial_order +\nassumes\n  ex_glb2: \"\\<And> x y \\<bullet> \\<lbrakk> x \\<in> X; y \\<in> X \\<rbrakk> \\<turnstile> (\\<exists> a \\<bullet> is_glb {x, y} a)\" and\n  ex_lub2: \"\\<And> x y \\<bullet> \\<lbrakk> x \\<in> X; y \\<in> X \\<rbrakk> \\<turnstile> (\\<exists> a \\<bullet> is_lub {x, y} a)\"\n\nbegin\n\nnotation\n r (infixl \"\\<sqsubseteq>\" 50)\n\nlemmas lattice_partial_order = partial_order\n\nend\n\nnotation (zed)\n  lattice (\"\\<^lattice>{:_:}{:_:}\")\n\ncontext lattice\n\nbegin\n\nlemma lattice:\n    \"\\<^lattice>{:X:}{:op \\<sqsubseteq>:}\"\n  by (intro_locales)\n\nlemma meet_glb:\n  assumes \n    a1: \"x \\<in> X\" \"y \\<in> X\"\n  shows\n    \"is_glb {x, y} (x \\<sqinter> y)\"\nproof -\n  from a1 have \n      \"(\\<exists> a \\<bullet> is_glb {x, y} a)\" \n    by (rule ex_glb2)\n  then obtain a where \n    b1: \"is_glb {x, y} a\" \n    by (auto)\n  show\n      \"is_glb {x, y} (x \\<sqinter> y)\"\n    apply (unfold meet_def)\n    apply (rule theI)\n    apply (rule b1)\n  proof -\n    fix b \n    assume \n      c1: \"is_glb {x, y} b\"\n    from b1 c1 show \n        \"b = a\" \n      by (rule glb_unique)\n  qed\nqed\n\nlemma join_lub:\n  assumes\n    a1: \"x \\<in> X\" \"y \\<in> X\"\n  shows\n    \"is_lub {x, y} (x \\<squnion> y)\"\nproof -\n  from a1 have \n      \"(\\<exists> a \\<bullet> is_lub {x, y} a)\" \n    by (rule ex_lub2)\n  then obtain a where \n    b1: \"is_lub {x, y} a\" \n    by (auto)\n  show\n      \"is_lub {x, y} (x \\<squnion> y)\"\n    apply (unfold join_def)\n    apply (rule theI)\n    apply (rule b1)\n  proof -\n    fix b \n    assume \n      c1: \"is_lub {x, y} b\"\n    from b1 c1 show \n        \"b = a\" \n      by (rule lub_unique)\n  qed\nqed\n\nend\n\nsublocale lattice \\<subseteq> pure_lattice X \"(op \\<sqinter>)\" \"(op \\<squnion>)\"\n  apply (intro_locales)\n  apply (rule pure_lattice_axioms.intro)\nproof -\n  fix x y z assume \n    b1: \"x \\<in> X\"  and \n    b2: \"y \\<in> X\" and \n    b3: \"z \\<in> X\"\n  {\n    fix x y assume \n      \"x \\<in> X\" \"y \\<in> X\"\n    with meet_glb [simplified is_glb_def] have \n        \"(x \\<sqinter> y) \\<in> X\"\n      by (auto intro: greatest_elt)\n  } note b4 = this\n  with b1 b2 show \n      \"(x \\<sqinter> y) \\<in> X\" -- range\n    by (simp)\n  {\n    fix x y \n    assume \n        \"x \\<in> X\" \"y \\<in> X\"\n    with join_lub [simplified is_lub_def] have \n        \"x \\<squnion> y \\<in> X\"\n      by (auto intro: least_elt)\n  } note b5 = this\n  with b1 b2 show \n      \"x \\<squnion> y \\<in> X\" -- range\n    by (simp)\n  have \"is_glb {x, x} x\"\n    apply (rule is_glbI)\n    apply (auto simp add: b1 refl)\n    done\n  with meet_glb [OF b1 b1] \n  show \n      \"x \\<sqinter> x = x\" -- idempotent\n    by (rule glb_unique [THEN sym])\n  have \n      \"is_lub {x, x} x\"\n    apply (rule is_lubI)\n    apply (auto simp add: b1 refl)\n    done\n  with join_lub [OF b1 b1] show \n      \"x \\<squnion> x = x\" -- idempotent\n    by (rule lub_unique [THEN sym])\n  from meet_glb [OF b2 b1] meet_glb [OF b1 b2] show \n    b6: \"x \\<sqinter> y = y \\<sqinter> x\" -- commutative \n    by (auto intro!: glb_unique)\n  from join_lub [OF b2 b1] join_lub [OF b1 b2] show \n    b7: \"x \\<squnion> y = y \\<squnion> x\" -- commutative\n    by (auto intro!: lub_unique)\n  show \n      \"(x \\<sqinter> y) \\<sqinter> z = x \\<sqinter> (y \\<sqinter> z)\" -- associative\n  proof (auto intro!: glb_unique meet_glb simp add: b1 b2 b3 b4 b5)\n    show \"is_glb {x, y \\<sqinter> z} ((x \\<sqinter> y) \\<sqinter> z)\"\n    proof (rule is_glbI, simp_all add: b1 b2 b3 b4 all_conj_distrib, msafe(inference), simp_all)\n      from meet_glb [OF b4 [OF b1 b2] b3] have \n          \"(x \\<sqinter> y) \\<sqinter> z \n          \\<sqsubseteq> x \\<sqinter> y\"\n        by (simp add: is_glb_def is_greatest_def is_lb_def split_beta)\n      also from meet_glb [OF b1 b2] have \"\\<dots> \n          \\<sqsubseteq> x\"\n        by (simp add: is_glb_def is_greatest_def is_lb_def split_beta)\n      finally show \n          \"(x \\<sqinter> y) \\<sqinter> z \\<sqsubseteq> x\"\n        by (this)\n    next\n      from meet_glb [OF b4 [OF b1 b2] b3] have \n          \"(x \\<sqinter> y) \\<sqinter> z \n          \\<sqsubseteq> x \\<sqinter> y\"\n        by (simp add: is_glb_def is_greatest_def is_lb_def split_beta)\n      also from meet_glb [OF b1 b2] have \"\\<dots> \n          \\<sqsubseteq> y\"\n        by (simp add: is_glb_def is_greatest_def is_lb_def split_beta)\n      finally have \n        d1: \"(x \\<sqinter> y) \\<sqinter> z \\<sqsubseteq> y\"\n        by (this)\n      from meet_glb [OF b4 [OF b1 b2] b3] have \n        d2: \"(x \\<sqinter> y) \\<sqinter> z \\<sqsubseteq> z\"\n        by (simp add: is_glb_def is_greatest_def is_lb_def split_beta)\n      from b1 b2 b3 b4 d1 d2 meet_glb [OF b2 b3] show \n          \"(x \\<sqinter> y) \\<sqinter> z \\<sqsubseteq> y \\<sqinter> z\"\n        by (simp add: is_glb_def is_greatest_def is_lb_def split_beta)\n    next\n      fix b\n      assume \n        d1: \"b \\<in> X\" and\n        d2: \"b \\<sqsubseteq> x\" and\n        d3: \"b \\<sqsubseteq> y \\<sqinter> z\"\n      note d3\n      also from meet_glb [OF b2 b3] have \n          \"y \\<sqinter> z \\<sqsubseteq> y\"\n        by (simp add: is_glb_def is_greatest_def is_lb_def split_beta all_conj_distrib)\n      finally have \n        d4: \"b \\<sqsubseteq> y\" \n        by (this)\n      note d3\n      also from meet_glb [OF b2 b3] have \n          \"y \\<sqinter> z \\<sqsubseteq> z\"\n        by (simp add: is_glb_def is_greatest_def is_lb_def split_beta)\n      finally have \n        d5: \"b \\<sqsubseteq> z\" \n        by (this)\n      from d1 d2 d4 meet_glb [OF b1 b2] have \n        d6: \"b \\<sqsubseteq> x \\<sqinter> y\"\n        by (simp add: is_glb_def is_greatest_def is_lb_def split_beta)      \n      from d1 meet_glb [OF b4 [OF b1 b2] b3] d5 d6 show \n          \"b \\<sqsubseteq> (x \\<sqinter> y) \\<sqinter> z\"\n        by (simp add: is_glb_def is_greatest_def is_lb_def split_beta)\n    qed\n  qed\n  show \n      \"(x \\<squnion> y) \\<squnion> z = x \\<squnion> (y \\<squnion> z)\" -- associative\n  proof (auto intro!: lub_unique join_lub simp add: b1 b2 b3 b4 b5)\n    show \n        \"is_lub {x, y \\<squnion> z} ((x \\<squnion> y) \\<squnion> z)\"\n    proof (rule is_lubI, simp_all add: b1 b2 b3 b5 all_conj_distrib, msafe(inference), simp_all)\n      from join_lub [OF b1 b2]\n      have \n          \"x \n          \\<sqsubseteq> x \\<squnion> y\"\n        by (simp add: is_lub_def is_least_def is_ub_def split_beta)\n      also from join_lub [OF b5 [OF b1 b2] b3] have \"\\<dots> \n          \\<sqsubseteq> (x \\<squnion> y) \\<squnion> z\"\n        by (simp add: is_lub_def is_least_def is_ub_def split_beta)\n      finally show \n          \"x \\<sqsubseteq> (x \\<squnion> y) \\<squnion> z\"\n        by (this)\n    next\n      from join_lub [OF b1 b2]\n      have \n          \"y \n          \\<sqsubseteq> x \\<squnion> y\"\n        by (simp add: is_lub_def is_least_def is_ub_def split_beta)\n      also from join_lub [OF b5 [OF b1 b2] b3] have \"\\<dots> \n          \\<sqsubseteq> (x \\<squnion> y) \\<squnion> z\"\n        by (simp add: is_lub_def is_least_def is_ub_def split_beta)\n      finally have \n        d1: \"y \\<sqsubseteq> (x \\<squnion> y) \\<squnion> z\"\n        by (this)\n      from join_lub [OF b5 [OF b1 b2] b3] have \n        d2: \"z \\<sqsubseteq> (x \\<squnion> y) \\<squnion> z\"\n        by (simp add: is_lub_def is_least_def is_ub_def split_beta)\n      from b1 b2 b3 b5 d1 d2 join_lub [OF b2 b3]\n      show \n          \"y \\<squnion> z \\<sqsubseteq> (x \\<squnion> y) \\<squnion> z\"\n        by (simp add: is_lub_def is_least_def is_ub_def split_beta)\n    next\n      fix b\n      assume \n        d1: \"b \\<in> X\" and\n        d2: \"x \\<sqsubseteq> b\" and\n        d3: \"y \\<squnion> z \\<sqsubseteq> b\"\n      from join_lub [OF b2 b3] have \n          \"y \n          \\<sqsubseteq> y \\<squnion> z\"\n        by (simp add: is_lub_def is_least_def is_ub_def split_beta all_conj_distrib)\n      also note d3\n      finally have \n        d4: \"y \\<sqsubseteq> b\" \n        by (this)\n      from join_lub [OF b2 b3] have \n          \"z \\<sqsubseteq> y \\<squnion> z\"\n        by (simp add: is_lub_def is_least_def is_ub_def split_beta all_conj_distrib)\n      also note d3\n      finally have \n        d5: \"z \\<sqsubseteq> b\" \n        by (this)\n      from d1 d2 d4 join_lub [OF b1 b2] have \n        d6: \"x \\<squnion> y \\<sqsubseteq> b\"\n        by (simp add: is_lub_def is_least_def is_ub_def split_beta)\n      from d1 join_lub [OF b5 [OF b1 b2] b3] d5 d6 show \n          \"(x \\<squnion> y) \\<squnion> z \\<sqsubseteq> b\"\n        by (simp add: is_lub_def is_least_def is_ub_def split_beta)\n    qed\n  qed\n  from meet_glb [OF b1 b5 [OF b1 b2]] show \n    \"x \\<sqinter> (x \\<squnion> y) = x\"\n  proof (rule glb_unique [THEN sym])\n    from b1 refl join_lub [OF b1 b2] show \n        \"is_glb {x, x \\<squnion> y} x\"\n      by (auto intro!: is_glbI simp add: is_lub_def is_least_def is_ub_def split_beta)\n  qed\n  from join_lub [OF b1 b4 [OF b1 b2]] show \n      \"x \\<squnion> (x \\<sqinter> y) = x\"\n  proof (rule lub_unique [THEN sym])\n    from b1 refl meet_glb [OF b1 b2] show \n        \"is_lub {x, x \\<sqinter> y} x\"\n      by (auto intro!: is_lubI simp add: is_glb_def is_greatest_def is_lb_def split_beta)\n  qed\nqed\n\nlemmas (in lattice) lattice_pure_lattice = pure_lattice\n\ntext {*\n\nHaving established this correspondence between a pure view of lattices\nand a partial order view, we find it convenient to finally adopt\na view of lattice that is order oriented. An important factor in this\nconsideration is the degree of freedom in the action of meet and join\noff the carrier set in the pure view.\n\n*}\n\ncontext lattice\n\nbegin\n\nlemma order_fixed:\n  \"lattice_sig.meet_order X (op \\<sqinter>) = (op \\<sqsubseteq>)\"\nproof (auto simp add: meet_order_def fun_eq_def relD1 relD2)\n  fix x y \n  assume \n    b1: \"x \\<sqsubseteq> y\"\n  from b1 have \n    b2: \"is_glb {x, y} x\"\n    by (auto intro!: is_glbI relD1 reflD)\n  from b1 meet_glb have \n    b3: \"is_glb {x, y} (x \\<sqinter> y)\"\n    by (simp add: relD1 relD2)\n  from b2 b3 show \n      \"x \\<sqinter> y = x\"\n    by (rule glb_unique)\nnext\n  fix x y \n  assume\n    b1: \"x \\<in> X\" \"y \\<in> X\" and \n    b2: \"x \\<sqinter> y = x\"\n  from b1 b2 meet_glb [of x y] have \n    b3: \"is_glb {x, y} x\"\n    by (simp)\n  then show \n      \"x \\<sqsubseteq> y\"\n    by (simp add: is_glbD1')\nqed\n\nlemma meet_order:\n    \"x \\<sqsubseteq> y \\<Leftrightarrow> x \\<in> X \\<and> y \\<in> X \\<and> x \\<sqinter> y = x\"\nproof -\n  have \n      \"x \\<sqsubseteq> y \n      \\<Leftrightarrow> \\<^infopa>{:x:}{:lattice_sig.meet_order X (op \\<sqinter>):}{:y:}\"\n    by (simp add: order_fixed)\n  also have \"\\<dots> \n      \\<Leftrightarrow> x \\<in> X \\<and> y \\<in> X \\<and> x \\<sqinter> y = x\"\n    by (simp add: meet_order_def)  \n  finally show \n      ?thesis \n    by (this)\nqed\n\nlemma join_order:\n    \"x \\<sqsubseteq> y \\<Leftrightarrow> x \\<in> X \\<and> y \\<in> X \\<and> y \\<squnion> x = y\"\nproof -\n  have \n      \"x \\<preceq> y \n      \\<Leftrightarrow> \\<^infopa>{:x:}{:lattice_sig.join_order X (op \\<squnion>):}{:y:}\"\n    by (simp add: order_fixed order_equiv [THEN sym])\n  also have \"\\<dots> \n      \\<Leftrightarrow> x \\<in> X \\<and> y \\<in> X \\<and> y \\<squnion> x = y\"\n    by (simp add: join_order_def)  \n  finally show ?thesis by (this)\nqed\n\nend\n\nlemma (in partial_order) latticeI:\n  \"\\<lbrakk> \n    (\\<And> x y \\<bullet> \\<lbrakk> x \\<in> X; y \\<in> X \\<rbrakk> \\<turnstile> (\\<exists> a \\<bullet> is_glb {x, y} a)); \n    (\\<And> x y \\<bullet> \\<lbrakk> x \\<in> X; y \\<in> X \\<rbrakk> \\<turnstile> (\\<exists> a \\<bullet> is_lub {x, y} a)) \n   \\<rbrakk> \\<turnstile> \\<^lattice>{:X:}{:(op \\<preceq>):}\"\n  apply (intro_locales)\n  apply (auto simp add: lattice_axioms_def)\n  done\n    \ntext {*\n\nFinally some reasoning rules for calculating with meets and joins.\n\n*}\n\ncontext lattice\n\nbegin\n\nlemma meet_lbD1: \n    \"\\<lbrakk> x \\<in> X; y \\<in> X \\<rbrakk> \\<turnstile> x \\<sqinter> y \\<sqsubseteq> x\"\n  by (auto intro!: is_glbD1' [OF meet_glb])\n\nlemma meet_lbD2: \n    \"\\<lbrakk> x \\<in> X; y \\<in> X \\<rbrakk> \\<turnstile> x \\<sqinter> y \\<sqsubseteq> y\"\n  by (auto intro!: is_glbD1' [OF meet_glb])\n\nlemma meet_glbD:\n    \"\\<lbrakk> z \\<preceq> x; z \\<preceq> y \\<rbrakk> \\<turnstile> z \\<sqsubseteq> x \\<sqinter> y\"\n  by (auto intro: is_glbD2' [OF meet_glb] relD1 relD2)\n\nlemma join_ubD1: \n    \"\\<lbrakk> x \\<in> X; y \\<in> X \\<rbrakk> \\<turnstile> x \\<sqsubseteq> x \\<squnion> y\"\n  by (auto intro!: is_lubD1' [OF join_lub])\n\nlemma join_ubD2: \n    \"\\<lbrakk> x \\<in> X; y \\<in> X \\<rbrakk> \\<turnstile> y \\<sqsubseteq> x \\<squnion> y\"\n  by (auto intro!: is_lubD1' [OF join_lub])\n\nlemma  join_lubD:\n    \"\\<lbrakk> x \\<preceq> z; y \\<preceq> z \\<rbrakk> \\<turnstile> x \\<squnion> y \\<sqsubseteq> z\"\n  by (auto intro: is_lubD2' [OF join_lub] relD1 relD2)\n\nlemma meet_mono:\n  assumes \n    a1: \"x \\<sqsubseteq> x'\" and \n    a2: \"y \\<sqsubseteq> y'\"\n  shows\n    \"x \\<sqinter> y \\<sqsubseteq> x' \\<sqinter> y'\"\nproof -\n  from a1 a2 have \n    b1 [simplified]: \"\\<lch> x, y, x', y' \\<chIn> X \\<rch>\"\n    by (auto simp add: relD1 relD2)\n  have \n      \"x \\<sqinter> y \n      \\<sqsubseteq> x\"\n    by (rule meet_lbD1, auto simp add: b1)\n  also have \"\\<dots> \n      \\<sqsubseteq> x'\"\n    by (rule a1)\n  finally have \n    b2: \"x \\<sqinter> y \\<sqsubseteq> x'\"\n    by (this)\n  have \n      \"x \\<sqinter> y \n      \\<sqsubseteq> y\"\n    by (rule meet_lbD2, auto simp add: b1)\n  also have \"\\<dots> \n      \\<sqsubseteq> y'\"\n    by (rule a2)\n  finally have \n    b3: \"x \\<sqinter> y \\<sqsubseteq> y'\"\n    by (this)\n  from b2 b3 show \n      \"x \\<sqinter> y \\<sqsubseteq> x' \\<sqinter> y'\"\n    by (auto intro!: meet_glbD simp add: b1)\nqed\n\nlemma join_mono:\n  assumes\n    a1: \"x \\<sqsubseteq> x'\" and \n    a2: \"y \\<sqsubseteq> y'\"\n  shows\n    \"x \\<squnion> y \\<sqsubseteq> x' \\<squnion> y'\"\nproof -\n  from a1 a2 have \n    b1 [simplified]: \n      \"\\<lch> x, y, x', y' \\<chIn> X \\<rch>\"\n    by (auto simp add: relD1 relD2)\n  have \n      \"x \n      \\<sqsubseteq> x'\"\n    by (rule a1)\n  also have \"\\<dots>  \n      \\<sqsubseteq> x' \\<squnion> y'\"\n    by (rule join_ubD1, auto simp add: b1)\n  finally have \n    b2: \"x \\<sqsubseteq> x' \\<squnion> y'\"\n    by (this)\n  have \n      \"y\n      \\<sqsubseteq> y'\"\n    by (rule a2)\n  also have \"\\<dots> \n      \\<sqsubseteq> x' \\<squnion> y'\"\n    by (rule join_ubD2, auto simp add: b1)\n  finally have \n    b3: \"y \\<sqsubseteq> x' \\<squnion> y'\"\n    by (this)\n  from b2 b3 show \n      \"x \\<squnion> y \\<sqsubseteq> x' \\<squnion> y'\"\n    by (auto intro!: join_lubD simp add: b1)\nqed\n\nend\n\n\nsection {* Complete lattices *}\n\ntext {*\n\nThe existence of pairwise meets and joins in a lattice also ensures the\nexistence of arbitrary finite (nonempty) meets and joins.\n\n*}\n\ncontext lattice\n\nbegin\n\nlemma finite_glb:\n  assumes \n    a1: \"Y \\<subseteq> X\" and \n    a2: \"finite Y\" and \n    a3: \"Y \\<noteq> \\<emptyset>\"\n  shows \n    \"\\<exists> a \\<bullet> is_glb Y a\"\nproof -\n  from a2 have \n      \"Y \\<subseteq> X \\<and> Y \\<noteq> \\<emptyset> \\<Rightarrow> (\\<exists> a \\<bullet> is_glb Y a)\"\n  proof (induct rule: finite_induct, simp, msafe(inference))\n    fix x Y\n    assume \n      c1: \"finite Y\" and \n      c2: \"x \\<notin> Y\" and \n      c3: \"insert x Y \\<subseteq> X\" and\n      c4: \"Y \\<subseteq> X \\<and> Y \\<noteq> \\<emptyset> \\<Rightarrow> (\\<exists> a \\<bullet> is_glb Y a)\"\n    from c3 have \n      c5: \"x \\<in> X\" \n      by (auto)\n    from c3 have \n      c6: \"Y \\<subseteq> X\" \n      by (auto)\n    show \"\\<exists> a \\<bullet> is_glb (insert x Y) a\"\n    proof (cases \"Y = \\<emptyset>\")\n      assume \n        d1: \"Y = \\<emptyset>\"\n      with c5 have \n          \"is_glb (insert x Y) x\"\n        by (auto intro!: is_glbI reflD)\n      then show \n          ?thesis \n        by (auto)\n    next\n      assume \n        d1: \"Y \\<noteq> \\<emptyset>\"\n      with c6 c4 have \n        d2: \"\\<exists> a \\<bullet> is_glb Y a\"\n        by (simp)\n      then obtain a where \n        d3: \"is_glb Y a\" \n        by (auto)\n      from d3 have \n        d4: \"a \\<in> X\"\n        by (rule glb_elt)\n      with c5 have \n        d5: \"x \\<sqinter> a \\<in> X\"\n        by (rule meetR)\n      then have \n        d6: \"is_glb (insert x Y) (x \\<sqinter> a)\"\n      proof (rule is_glbI)\n        fix y assume \n          e1: \"y \\<in> insert x Y\"\n        then show \n            \"x \\<sqinter> a \\<sqsubseteq> y\"\n        proof (auto)\n          from c5 d4 show \n              \"x \\<sqinter> a \\<sqsubseteq> x\"\n            by (rule meet_lbD1)\n        next\n          assume \n            f1: \"y \\<in> Y\"\n          from c5 d4 have \n              \"x \\<sqinter> a \n              \\<sqsubseteq> a\"\n            by (rule meet_lbD2)\n          also from d3 f1 have \"\\<dots>\n              \\<sqsubseteq> y\"\n            by (rule is_glbD1')\n          finally show \n              \"x \\<sqinter> a \\<sqsubseteq> y\"\n            by (this)\n        qed\n      next\n        fix b assume \n          e1: \"b \\<in> X\" and \n          e2: \"(\\<forall> y | y \\<in> insert x Y \\<bullet> b \\<sqsubseteq> y)\"\n        from e2 have \n          e3: \"b \\<preceq> x\"\n          by (auto)\n        from e2 have \n          e4: \"(\\<forall> y | y \\<in> Y \\<bullet> b \\<sqsubseteq> y)\"\n          by (auto)\n        from d3 e1 have \n          e5: \"b \\<sqsubseteq> a\"\n          apply (rule is_glbD2')\n          apply (auto simp add: e4)\n          done\n        from e3 e5 show \n          \"b \\<sqsubseteq> x \\<sqinter> a\"\n          by (rule meet_glbD)\n      qed\n      then show \n          ?thesis \n        by (auto)\n    qed\n  qed\n  with a1 a3 show \n      ?thesis\n    by (auto)\nqed\n\nlemma  finite_lub:\n  assumes\n    a1: \"Y \\<subseteq> X\" and \n    a2: \"finite Y\" and \n    a3: \"Y \\<noteq> \\<emptyset>\"\n  shows\n      \"(\\<exists> a \\<bullet> is_lub Y a)\"\nproof -\n  from a2 have \n      \"Y \\<subseteq> X \\<and> Y \\<noteq> \\<emptyset> \\<Rightarrow> (\\<exists> a \\<bullet> is_lub Y a)\"\n  proof (induct rule: finite_induct, simp, msafe(inference))\n    fix x Y\n    assume \n      c1: \"finite Y\" and \n      c2: \"x \\<notin> Y\" and \n      c3: \"insert x Y \\<subseteq> X\" and\n      c4: \"Y \\<subseteq> X \\<and> Y \\<noteq> \\<emptyset> \\<Rightarrow> (\\<exists> a \\<bullet> is_lub Y a)\"\n    from c3 have \n      c5: \"x \\<in> X\" by (auto)\n    from c3 have \n      c6: \"Y \\<subseteq> X\" by (auto)\n    show \n        \"(\\<exists> a \\<bullet> is_lub (insert x Y) a)\"\n    proof (cases \"Y = \\<emptyset>\")\n      assume \n        d1: \"Y = \\<emptyset>\"\n      with c5 have \n          \"is_lub (insert x Y) x\"\n        by (auto intro!: is_lubI reflD)\n      then show \n          ?thesis \n        by (auto)\n    next\n      assume \n        d1: \"Y \\<noteq> \\<emptyset>\"\n      with c6 c4 have \n        d2: \"(\\<exists> a \\<bullet> is_lub Y a)\"\n        by (simp)\n      then obtain a where \n        d3: \"is_lub Y a\" \n        by (auto)\n      from d3 have \n        d4: \"a \\<in> X\"\n        by (rule lub_elt)\n      with c5 have \n        d5: \"x \\<squnion> a \\<in> X\"\n        by (rule joinR)\n      then have \n        d6: \"is_lub (insert x Y) (x \\<squnion> a)\"\n      proof (rule is_lubI)\n        fix y assume \n          e1: \"y \\<in> insert x Y\"\n        then show \n            \"y \\<sqsubseteq> x \\<squnion> a\"\n        proof (auto)\n          from c5 d4 show \n              \"x \\<sqsubseteq> x \\<squnion> a\"\n            by (rule join_ubD1)\n        next\n          assume \n            f1: \"y \\<in> Y\"\n          from d3 f1 have \n              \"y \n              \\<sqsubseteq> a\"\n            by (rule is_lubD1')\n          also from c5 d4 have \"\\<dots>\n              \\<sqsubseteq> x \\<squnion> a\"\n            by (rule join_ubD2)\n          finally show \n              \"y \\<sqsubseteq> x \\<squnion> a\"\n            by (this)\n        qed\n      next\n        fix b assume \n          e1: \"b \\<in> X\" and \n          e2: \"(\\<forall> y | y \\<in> insert x Y \\<bullet> y \\<preceq> b)\"\n        from e2 have \n          e3: \"x \\<sqsubseteq> b\"\n          by (auto)\n        from e2 have \n          e4: \"(\\<forall> y | y \\<in> Y \\<bullet> y \\<sqsubseteq> b)\"\n          by (auto)\n        from d3 e1 have \n          e5: \"a \\<sqsubseteq> b\"\n          apply (rule is_lubD2')\n          apply (auto simp add: e4)\n          done\n        from e3 e5 show \n            \"x \\<squnion> a \\<sqsubseteq> b\"\n          by (rule join_lubD)\n      qed\n      then show ?thesis by (auto)\n    qed\n  qed\n  with a1 a3 show ?thesis\n    by (auto)\nqed\n\nend\n\ntext {*\n\nA complete lattice is a partial order that has extremals for every\nsubset.\n\nThe existence of extremals allows us to introduce generalised meet and join\noperators on complete lattices.\n\n*}\n\ndefinition\n  Meet :: \"['a set, 'a orderT, 'a set] \\<rightarrow> 'a\"\nwhere\n  Meet_def: \"Meet \\<defs> (\\<olambda> X r Y \\<bullet> (\\<mu> a | \\<^glbp>{:X:}{:r:} Y a))\"\n\ndefinition\n  Join :: \"['a set, 'a orderT, 'a set] \\<rightarrow> 'a\"\nwhere\n  Join_def: \"Join \\<defs> (\\<olambda> X r Y \\<bullet> (\\<mu> a | \\<^lubp>{:X:}{:r:} Y a))\"\n\nnotation (xsymbols output)\n  Meet (\"\\<Sqinter>\\<^bsub>_, _\\<^esub>_\") and\n  Join (\"\\<Squnion>\\<^bsub>_, _\\<^esub>_\")\n\nnotation (zed)\n  Meet (\"\\<^Meet>{:_:}{:_:}\") and\n  Join (\"\\<^Join>{:_:}{:_:}\")\n\ncontext setrel_sig\n\nbegin\n\nabbreviation\n  Meet :: \"'a set \\<rightarrow> 'a\"\nwhere\n  \"Meet \\<defs> \\<^Meet>{:X:}{:r:}\"\n\nabbreviation\n  Join :: \"'a set \\<rightarrow> 'a\"\nwhere\n  \"Join \\<defs> \\<^Join>{:X:}{:r:}\"\n\nnotation\n  Meet (\"\\<Sqinter>_\") and\n  Join (\"\\<Squnion>_\")\n\nend\n\ncontext partial_order\n\nbegin\n\nlemma Meet_unique:\n  assumes \n    a1: \"is_glb S a\"\n  shows\n      \"a = \\<Sqinter>S\"\n  apply (unfold Meet_def)\n  apply (rule the_equality [symmetric])\n  apply (rule a1)\n  apply (rule glb_unique)\n  apply (rule a1)\n  apply (assumption)\n  done\n\nlemma Join_unique:\n  assumes \n    a1: \"is_lub S a\"\n  shows\n      \"a = \\<Squnion>S\"\n  apply (unfold Join_def)\n  apply (rule the_equality [symmetric])\n  apply (rule a1)\n  apply (rule lub_unique)\n  apply (rule a1)\n  apply (assumption)\n  done\n\nend\n\nno_notation Orderings.bot (\"\\<bottom>\")\nno_notation Orderings.top (\"\\<top>\")\n\ndefinition\n  Bottom :: \"['a set, 'a orderT] \\<rightarrow> 'a\"\nwhere\n  Bottom_def: \"Bottom \\<defs> (\\<olambda> X r \\<bullet> \\<^Meet>{:X:}{:r:}X)\"\n\ndefinition\n  Top :: \"['a set, 'a orderT] \\<rightarrow> 'a\"\nwhere\n  Top_def: \"Top \\<defs> (\\<olambda> X r \\<bullet> \\<^Join>{:X:}{:r:}X)\"\n\nnotation (zed)\n  Bottom (\"\\<^Bottom>{:_:}{:_:}\") and\n  Top (\"\\<^Top>{:_:}{:_:}\")\n\ncontext setrel_sig\n\nbegin\n\nabbreviation\n  Bottom :: \"'a\" (\"\\<bottom>\")\nwhere\n  \"\\<bottom> \\<defs> \\<^Bottom>{:X:}{:r:}\"\n\nabbreviation\n  Top :: \"'a\" (\"\\<top>\")\nwhere\n  \"\\<top> \\<defs> \\<^Top>{:X:}{:r:}\"\n\nend\n\ncontext partial_order\n\nbegin\n\nlemma Bottom_unique:\n  assumes \n    a1:\"is_glb X a\"\n  shows\n      \"a = \\<bottom>\"\n  apply (unfold Bottom_def)\n  apply (rule Meet_unique)\n  apply (rule a1)\n  done\n\nlemma Top_unique:\n  assumes \n    a1:\"is_lub X a\"\n  shows\n      \"a = \\<top>\"\n  apply (unfold Top_def)\n  apply (rule Join_unique)\n  apply (rule a1)\n  done\n  \nlemma Bottom_eq:\n    \"\\<lbrakk> y \\<in> X; (\\<forall> x | x \\<in> X \\<bullet> y \\<preceq> x) \\<rbrakk> \\<turnstile> \\<bottom> = y\"\n  apply (unfold Bottom_def)\n  apply (rule Meet_unique [symmetric])\n  apply (rule is_glbI)\n  apply (auto)\n  done\n  \nlemma Top_eq:\n  \"\\<lbrakk> y \\<in> X; (\\<forall> x | x \\<in> X \\<bullet> x \\<preceq> y) \\<rbrakk> \\<turnstile> \\<top> = y\"\n  apply (unfold Top_def)\n  apply (rule Join_unique [symmetric])\n  apply (rule is_lubI)\n  apply (auto)\n  done\n\nend\n\nlocale clattice_sig = \n  carrier_sig X \n  for \n    X :: \"'a set\" +\n  fixes\n    BS_bigsqcap :: \"'a set \\<rightarrow> 'a\" and\n    BS_bigsqcup :: \"'a set \\<rightarrow> 'a\" and\n    BS_bot :: \"'a\" and\n    BS_top :: \"'a\"\n\nlocale clattice = \n  partial_order +\nassumes\n  ex_glb: \"\\<And> Y \\<bullet> Y \\<subseteq> X \\<turnstile> (\\<exists> a \\<bullet> is_glb Y a)\" and\n  ex_lub: \"\\<And> Y \\<bullet> Y \\<subseteq> X \\<turnstile> (\\<exists> a \\<bullet> is_lub Y a)\"\n\nsublocale clattice \\<subseteq> lattice\n  apply (unfold_locales)\n  apply (auto intro!: ex_glb ex_lub)\n  done\n\ncontext clattice\n\nbegin\n\nlemmas clattice_lattice = lattice\n\nend\n\nnotation (zed)\n  clattice (\"\\<^clattice>{:_:}{:_:}\")\n\nlemma (in clattice) clattice:\n    \"\\<^clattice>{:X:}{:(op \\<preceq>):}\"\n  by (intro_locales)\n\ntext {*\n\nA complete lattice is a lattice.\n\n*}\n\nlemma (in partial_order) clatticeI:\n  \"\\<lbrakk> \n    (\\<And> Y \\<bullet> Y \\<subseteq> X \\<turnstile> (\\<exists> a \\<bullet> is_glb Y a)); \n    (\\<And> Y \\<bullet> Y \\<subseteq> X \\<turnstile> (\\<exists> a \\<bullet> is_lub Y a)) \n   \\<rbrakk> \\<turnstile> \\<^clattice>{:X:}{:(op \\<preceq>):}\"\n  apply (rule clattice.intro)\n  apply (rule partial_order)\n  apply (simp_all add: clattice_axioms_def)\n  done\n\nlemma (in partial_order) ex_Meet_glb:\n  assumes\n    a1: \"A \\<subseteq> X\" and \n    a2: \"(\\<exists> a \\<bullet> is_glb A a)\"\n  shows\n      \"is_glb A (\\<Sqinter>A)\" \nproof -\n  from a2 a1 obtain a where \n    b1: \"is_glb A a\" \n    by (auto)\n  show ?thesis\n    apply (simp add: Meet_def)\n    apply (rule theI [of \"is_glb A\" \"a\", OF b1])\n    apply (auto intro: glb_unique [OF b1])\n    done\nqed\n\nlemma (in lattice) fin_Meet_glb:\n    \"\\<lbrakk> A \\<subseteq> X; finite A; A \\<noteq> \\<emptyset> \\<rbrakk> \n    \\<turnstile> is_glb A (\\<Sqinter>A)\"\n  by (intro ex_Meet_glb finite_glb)\n\nlemma (in clattice) Meet_glb:\n    \"A \\<subseteq> X \\<turnstile> is_glb A (\\<Sqinter>A)\"\n  by (intro ex_Meet_glb ex_glb)\n\nlemmas (in clattice) MeetR = glb_elt [OF Meet_glb]\n\nlemma (in partial_order) ex_Join_lub:\n  assumes\n    a1: \"A \\<subseteq> X\" and \n    a2: \"(\\<exists> a \\<bullet> is_lub A a)\"\n  shows\n      \"is_lub A (\\<Squnion>A)\"\nproof -\n  from a2 a1 obtain a where \n    b1: \"is_lub A a\" \n    by (auto)\n  show \n      ?thesis\n    apply (simp add: Join_def)\n    apply (rule theI [of \"is_lub A\" a, OF b1])\n    apply (auto intro: lub_unique [OF b1])\n    done\nqed\n\nlemma (in lattice) fin_Join_lub:\n    \"\\<lbrakk> A \\<subseteq> X; finite A; A \\<noteq> \\<emptyset> \\<rbrakk> \n    \\<turnstile> is_lub A (\\<Squnion>A)\"\n  by (intro ex_Join_lub finite_lub)\n\nlemma (in clattice) Join_lub:\n    \"A \\<subseteq> X \\<turnstile> is_lub A (\\<Squnion>A)\"\n  by (intro ex_Join_lub ex_lub)\n\nlemmas (in clattice) JoinR = lub_elt [OF Join_lub]\n\ntext {*\n\nThe general meet and join operators satisfy similar rules to the pair-wise\nversions.\n\n*}\n\ncontext clattice\n\nbegin\n\nlemma Meet_lbD:\n    \"\\<lbrakk> A \\<subseteq> X; a \\<in> A \\<rbrakk> \n    \\<turnstile> (\\<Sqinter>A) \\<sqsubseteq> a\"\n  apply (rule is_glbD1')\n  apply (rule Meet_glb)\n  apply (assumption+)\n  done\n\nlemma Join_ubD:\n  \"\\<lbrakk> A \\<subseteq> X; a \\<in> A \\<rbrakk> \n  \\<turnstile> a \\<sqsubseteq> (\\<Squnion>A)\"\n  apply (rule is_lubD1')\n  apply (rule Join_lub)\n  apply (assumption+)\n  done\n\nlemma Meet_glbD:\n  \"\\<lbrakk> A \\<subseteq> X; a \\<in> X; (\\<forall> x \\<bullet> x \\<in> A \\<Rightarrow> a \\<sqsubseteq> x) \\<rbrakk> \n  \\<turnstile> a \\<sqsubseteq> (\\<Sqinter>A)\"\n  apply (rule is_glbD2')\n  apply (rule Meet_glb)\n  apply (auto)\n  done \n\nlemma Join_lubD:\n  \"\\<lbrakk> A \\<subseteq> X; a \\<in> X; (\\<forall> x \\<bullet> x \\<in> A \\<Rightarrow> x \\<sqsubseteq> a) \\<rbrakk> \n  \\<turnstile> (\\<Squnion>A) \\<sqsubseteq> a\"\n  apply (rule is_lubD2')\n  apply (rule Join_lub)\n  apply (auto)\n  done\n\nlemmas Meet_unique = glb_unique [OF Meet_glb, OF _ is_glbI]\n\nlemmas Join_unique = lub_unique [OF Join_lub, OF _ is_lubI]\n\nlemma Meet_sub:\n  assumes\n    a1: \"\\<lch> Z \\<chSubseteq> Y \\<chSubseteq> X \\<rch>\"\n  shows\n      \"(\\<Sqinter>Y) \\<sqsubseteq> (\\<Sqinter>Z)\"\nproof -\n  from a1 have \n    b1: \"Z \\<subseteq> X\" \n    by (auto)\n  from a1 b1 show \n        ?thesis\n    apply (intro Meet_glbD)\n    apply (auto simp add: MeetR Meet_lbD)\n    done\nqed\n\nlemma Join_sub:\n  assumes\n    a1: \"\\<lch> Z \\<chSubseteq> Y \\<chSubseteq> X \\<rch>\"\n  shows\n      \"(\\<Squnion>Z) \\<sqsubseteq> (\\<Squnion>Y)\"\nproof -\n  from a1 have \n    b1: \"Z \\<subseteq> X\" \n    by (auto)\n  from a1 b1 show \n      ?thesis\n    apply (intro Join_lubD)\n    apply (auto intro!: Join_ubD simp add: JoinR)\n    done\nqed\n\nlemma Meet_dom:\n  assumes\n    a1: \"f\\<lparr>{y | P y}\\<rparr> \\<subseteq> X\" and\n    a2: \"g\\<lparr>{y | P y}\\<rparr> \\<subseteq> X\" and\n    a3: \"(\\<And> y \\<bullet> P y \\<turnstile> f y \\<sqsubseteq> g y)\"\n  shows\n      \"(\\<Sqinter>{y | P y \\<bullet> f y}) \\<sqsubseteq> (\\<Sqinter>{y | P y \\<bullet> g y})\"\n  apply (rule Meet_glbD)\n  using a1 a2 a3\n  apply (auto intro!: MeetR simp add: eind_def)\n  apply (rule transD)\n  apply (rule Meet_lbD)\n  apply (auto intro!: MeetR)\n  done\n\nlemma Join_dom:\n  assumes\n    a1: \"f\\<lparr>{y | P y}\\<rparr> \\<subseteq> X\" and\n    a2: \"g\\<lparr>{y | P y}\\<rparr> \\<subseteq> X\" and\n    a3: \"(\\<And> y \\<bullet> P y \\<turnstile> f y \\<sqsubseteq> g y)\"\n  shows\n      \"(\\<Squnion>{y | P y \\<bullet> f y}) \\<sqsubseteq> (\\<Squnion>{y | P y \\<bullet> g y})\"\n  apply (rule Join_lubD)\n  using a1 a2 a3\n  apply (auto intro!: JoinR simp add: eind_def)\n  apply (rule transD)\n  defer 1\n  apply (rule Join_ubD)\n  apply (auto intro!: JoinR)\n  done\n\ntext {*\n\nThe pairwise meet and join are special case of general meet and join.\n\n*}\n\nlemma meet_Meet:\n  \"\\<lbrakk> x \\<in> X; y \\<in> X \\<rbrakk> \\<turnstile> x \\<sqinter> y = (\\<Sqinter>{x, y})\"\n  apply (rule glb_unique [OF Meet_glb meet_glb])\n  apply (auto)\n  done\n\nlemma join_Join:\n  \"\\<lbrakk> x \\<in> X; y \\<in> X \\<rbrakk> \\<turnstile> x \\<squnion> y = (\\<Squnion>{x, y})\"\n  apply (rule lub_unique [OF Join_lub join_lub])\n  apply (auto)\n  done  \n\ntext {*\n\nThe meet and join of the entire space are called bottom and top respectively.\n\n*}\n\nlemma Bottom_Join:\n  \"\\<bottom> = (\\<Squnion>\\<emptyset>)\"\n  apply (rule Join_unique)\n  apply (auto intro: MeetR Meet_lbD Meet_glbD simp add: Bottom_def)\n  done\n\nlemma BottomR: \n  \"\\<bottom> \\<in> X\"\n  by (auto simp add: Bottom_def MeetR)\n\nlemma Bottom_lb:\n  assumes\n    a1: \"x \\<in> X\"\n  shows\n      \"\\<bottom> \\<sqsubseteq> x\"\nproof -\n  have \"(\\<Sqinter>X) \\<sqsubseteq> x\"\n    apply (rule Meet_lbD [OF _ a1])\n    apply (simp)\n    done\n  then show \n      ?thesis \n    by (simp add: Bottom_def)\nqed\n\nlemma Bottom_min:\n  assumes \n    a1: \"x \\<in> X\"\n  shows\n    \"x \\<sqsubseteq> \\<bottom> \\<Leftrightarrow> x = \\<bottom>\"\n  apply (auto intro!: Bottom_eq [symmetric] a1)\n  apply (rule transD)\n  apply (assumption)\n  apply (rule Bottom_lb)\n  apply (assumption)\n  apply (rule reflD)\n  apply (rule BottomR)\n  done\n\nlemma Top_Meet:\n    \"\\<top> = (\\<Sqinter>\\<emptyset>)\"\n  apply (rule Meet_unique)\n  apply (auto intro: JoinR Join_ubD Join_lubD simp add: Top_def)\n  done\n\nlemma TopR: \n    \"\\<top> \\<in> X\"\n  by (auto simp add: Top_def JoinR)\n\nlemma Top_ub:\n  assumes\n    a1: \"x \\<in> X\"\n  shows\n      \"x \\<sqsubseteq> \\<top>\"\nproof -\n  have \"x \\<sqsubseteq> (\\<Squnion>X)\"\n    apply (rule Join_ubD [OF _ a1])\n    apply (simp)\n    done\n  then show \n      ?thesis \n    by (simp add: Top_def)\nqed\n\nlemma  Top_max:\n  assumes \n    a1: \"x \\<in> X\"\n  shows\n      \"\\<top> \\<sqsubseteq> x \\<Leftrightarrow> x = \\<top>\"\n  apply (auto intro!: Top_eq [symmetric] a1)\n  apply (rule transD)\n  apply (rule Top_ub)\n  apply (assumption)\n  apply (assumption)\n  apply (rule reflD)\n  apply (rule TopR)\n  done\n\nend\n\nsection {* Distributive lattices *}\n\ntext {*\n\nA lattice in which the meet and join operators distribute is\ncalled a distributive lattice.\n\n*}\n\nlocale dlattice = \n  lattice +\n  \nassumes\n  meet_dist: \"\\<lbrakk> x \\<in> X; y \\<in> X; z \\<in> X \\<rbrakk> \\<turnstile> x \\<squnion> (y \\<sqinter> z) = (x \\<squnion> y) \\<sqinter> (x \\<squnion> z)\" and\n  join_dist: \"\\<lbrakk> x \\<in> X; y \\<in> X; z \\<in> X \\<rbrakk> \\<turnstile> x \\<sqinter> (y \\<squnion> z) = (x \\<sqinter> y) \\<squnion> (x \\<sqinter> z)\"\n\nbegin \n\nlemmas dlattice_lattice = lattice\n\nend\n\nnotation (zed)\n  dlattice (\"\\<^dlattice>{:_:}{:_:}\")\n\nlemma (in dlattice) dlattice:\n    \"\\<^dlattice>{:X:}{:(op \\<sqsubseteq>):}\"\n  by (intro_locales)\n\nlemma (in lattice) dlatticeI:\n  assumes\n    a1: \"(\\<forall> x y z | \\<lch> x, y, z \\<chIn> X \\<rch> \\<bullet> x \\<squnion> (y \\<sqinter> z) = (x \\<squnion> y) \\<sqinter> (x \\<squnion> z))\" and\n    a2: \"(\\<forall> x y z | \\<lch> x, y, z \\<chIn> X \\<rch> \\<bullet> x \\<sqinter> (y \\<squnion> z) = (x \\<sqinter> y) \\<squnion> (x \\<sqinter> z))\"\n  shows \n    \"\\<^dlattice>{:X:}{:(op \\<sqsubseteq>):}\"\n  apply (rule dlattice.intro)\n  apply (rule lattice)\n  apply (unfold dlattice_axioms_def)\n  apply (msafe(inference))\n  apply (rule a1 [rule_format])\n  apply (simp)\n  apply (rule a2 [rule_format])\n  apply (simp)\n  done\n\nlocale dclattice = \n  clattice +\n  \nassumes\n  Meet_dist: \"\\<lbrakk> x \\<in> X; Y \\<subseteq> X \\<rbrakk> \\<turnstile> x \\<squnion> (\\<Sqinter>Y) = (\\<Sqinter>{y | y \\<in> Y \\<bullet> (x \\<squnion> y)})\" and\n  Join_dist: \"\\<lbrakk> x \\<in> X; Y \\<subseteq> X \\<rbrakk> \\<turnstile> x \\<sqinter> (\\<Squnion>Y) = (\\<Squnion>{y | y \\<in> Y \\<bullet> (x \\<sqinter> y)})\"\n\nbegin\n\nlemmas dclattice_clattice = clattice\n\nend\n\nnotation (zed)\n  dclattice (\"\\<^dclattice>{:_:}{:_:}\")\n\nlemma (in dclattice) dclattice:\n  \"\\<^dclattice>{:X:}{:(op \\<sqsubseteq>):}\"\n  by (intro_locales)\n\nlemma (in clattice) dclatticeI:\n  \"\\<lbrakk> \n    (\\<forall> x Y | x \\<in> X \\<and> Y \\<subseteq> X \\<bullet> x \\<squnion> (\\<Sqinter>Y) = (\\<Sqinter>{y | y \\<in> Y \\<bullet> (x \\<squnion> y)}));\n    (\\<forall> x Y | x \\<in> X \\<and> Y \\<subseteq> X \\<bullet> x \\<sqinter> (\\<Squnion>Y) = (\\<Squnion>{y | y \\<in> Y \\<bullet> (x \\<sqinter> y)}))\n  \\<rbrakk> \\<turnstile> \\<^dclattice>{:X:}{:(op \\<preceq>):}\"\n  apply (rule dclattice.intro)\n  apply (auto intro: carrier_axioms setrel_axioms reflexive_axioms transitive_axioms \n    antisymmetric_axioms clattice_axioms)\n  apply (rule dclattice_axioms.intro)\n  apply (auto)\n  done\n\ncontext dclattice\n\nbegin\n\nlemma  Meet_distD:\n    \"\\<lbrakk> x \\<in> X; Y \\<subseteq> X \\<rbrakk> \\<turnstile> (\\<Sqinter>{y | y \\<in> Y \\<bullet> x \\<squnion> y}) = x \\<squnion> (\\<Sqinter>Y)\"\n  by (insert Meet_dist, auto)\n\nlemma Meet_distD':\n  assumes\n    a1: \"x \\<in> X\" \"Y \\<subseteq> X\"\n  shows\n      \"(\\<Sqinter>{y | y \\<in> Y \\<bullet> y \\<squnion> x}) = (\\<Sqinter>Y) \\<squnion> x\" \nproof -\n  from a1 have \n      \"(\\<Sqinter>Y) \\<squnion> x\n      = x \\<squnion> (\\<Sqinter>Y)\"\n    by (simp add: joinC MeetR)\n  also from a1 have \"\\<dots>\n      = (\\<Sqinter>{y | y \\<in> Y \\<bullet> x \\<squnion> y})\"\n    by (simp add: Meet_distD)\n  also from a1 have \n      \"{y | y \\<in> Y \\<bullet> x \\<squnion> y}\n      = {y | y \\<in> Y \\<bullet> y \\<squnion> x}\"\n    apply (mauto(wind))\n    apply (auto simp add: joinC)\n    done\n  finally show \n      ?thesis \n    by (simp)\nqed\n\nlemma Join_distD:\n    \"\\<lbrakk> x \\<in> X; Y \\<subseteq> X \\<rbrakk> \\<turnstile> (\\<Squnion>{y | y \\<in> Y \\<bullet> x \\<sqinter> y}) = x \\<sqinter> (\\<Squnion>Y)\"\n  by (insert Join_dist, auto)\n\nlemma Join_distD':\n  assumes \n    a1: \"x \\<in> X\" \"Y \\<subseteq> X\"\n  shows\n      \"(\\<Squnion>{y | y \\<in> Y \\<bullet> y \\<sqinter> x}) = (\\<Squnion>Y) \\<sqinter> x\" \nproof -\n  from a1 have \"\n      (\\<Squnion>Y) \\<sqinter> x\n      = x \\<sqinter> (\\<Squnion>Y)\"\n    by (simp add: meetC JoinR)\n  also from a1 have \"\\<dots>\n      = (\\<Squnion>{y | y \\<in> Y \\<bullet> x \\<sqinter> y})\"\n    by (simp add: Join_distD)\n  also from a1 have \n      \"{y | y \\<in> Y \\<bullet> x \\<sqinter> y}\n      = {y | y \\<in> Y \\<bullet> y \\<sqinter> x}\"\n    apply (mauto(wind))\n    apply (auto simp add: meetC)\n    done\n  finally show \n      ?thesis \n    by (simp)\nqed\n\nend\n\nsublocale dclattice \\<subseteq> dlattice\n  apply (intro_locales)\n  apply (rule dlattice_axioms.intro)\n  apply (simp add: meet_Meet Meet_dist eind_def)\n  apply (rule arg_cong [where f = \"Meet\"])\n  apply (fast)\n  apply (simp add: join_Join Join_dist eind_def)\n  apply (rule arg_cong [where f = \"Join\"])\n  apply (fast)\n  done\n\nlemmas (in dclattice) dclattice_dlattice = dlattice\n\nsection {* Boolean lattices *}\n\ntext {*\n\nFollowing the general analogy of the lattice as abstraction for the booleans,\na negation or complement operator can be introduced, resulting in a boolean\nlattice or algebra.\n\n*}\n\ndefinition\n  complement :: \"['a set, 'a orderT, 'a] \\<rightarrow> 'a\"\nwhere\n  complement_def: \"complement \\<defs> (\\<olambda> X r x \\<bullet> (\\<mu> y | y \\<in> X \\<and> x \\<^meet>{:X:}{:r:} y = \\<^Bottom>{:X:}{:r:} \\<and> x \\<^join>{:X:}{:r:} y = \\<^Top>{:X:}{:r:}))\"\n\ncontext setrel_sig \n\nbegin\n\nabbreviation\n  complement :: \"'a \\<rightarrow> 'a\" (\"\\<sim>_\" [90] 90)\nwhere\n  \"complement \\<defs> Lattice_Locale.complement X r\"\n\nend\n\nlemma (in dclattice) complement_unique:\n  assumes\n    a1: \"x \\<in> X\" \"y \\<in> X\" and\n    a2: \"x \\<sqinter> y = \\<bottom>\" and\n    a3: \"x \\<squnion> y = \\<top>\"\n  shows\n    \"y = \\<sim>x\"\n  apply (simp add: complement_def)\n  apply (rule the_equality [symmetric])\n  using a1 a2 a3\n  apply (auto)\n  apply (simp add: a2 a3)\nproof -\n  fix y'\n  assume \n    b1: \"y' \\<in> X\" and\n    b2: \"x \\<sqinter> y' = \\<bottom>\" and\n    b3: \"x \\<squnion> y' = \\<top>\"\n  show\n      \"y' = y\"\n  proof (rule antisymD)\n    txt {*\n    Following the reasoning of Davey~\\cite[p 143]{Davey:Lattice}.\n    *}\n    from a1 have \n        \"y \\<sqsubseteq> \\<top>\"\n      by (simp add: Top_ub)\n    then have \n        \"y \n        = y \\<sqinter> \\<top>\"\n      by (simp add: meet_order)\n    also have \"\\<dots> \n        = y \\<sqinter> (x \\<squnion> y')\"\n      by (simp add: b3)\n    also from a1 b1 have \"\\<dots> \n        = (x \\<sqinter> y) \\<squnion> (y \\<sqinter> y')\"\n      by (simp add: join_dist meetC)\n    also from a1 b1 a2 a3 b2 b3 Bottom_lb [of \"y \\<sqinter> y'\"]\n    have \" \\<dots> \n        = y \\<sqinter> y'\"\n      by (simp add: join_order MeetR Bottom_def joinC meetR)\n    finally show \n        \"y \\<sqsubseteq> y'\"\n      by (simp add: meet_order a1 b1)\n    from b1 have \n        \"y' \\<sqsubseteq> \\<top>\"\n      by (simp add: Top_ub)\n    then have \n        \"y' \n        = y' \\<sqinter> \\<top>\"\n      by (simp add: meet_order)\n    also have \"\\<dots> \n        = y' \\<sqinter> (x \\<squnion> y)\"\n      by (simp add: a3)\n    also from a1 b1 have \"\\<dots> \n        = (x \\<sqinter> y') \\<squnion> (y' \\<sqinter> y)\"\n      by (simp add: join_dist meetC)\n    also from a1 b1 a2 a3 b2 b3 Bottom_lb [of \"y' \\<sqinter> y\"] have \" \\<dots> \n        = y' \\<sqinter> y\"\n      by (simp add: join_order Bottom_def MeetR joinC meetR)\n    finally show \n        \"y' \\<sqsubseteq> y\"\n      by (simp add: meet_order a1 b1)\n  qed\nqed\n\nlocale bool_lattice_sig =\n\nfixes\n  lcomp :: \"'a \\<rightarrow> 'a\" (\"\\<sim>_\" [1000] 999)\n\nlocale bool_lattice = \n  dclattice +\n  \nassumes\n  ex_complement: \n    \"(\\<forall> x | x \\<in> X \\<bullet> (\\<exists> y | y \\<in> X \\<bullet> x \\<sqinter> y = \\<bottom> \\<and> x \\<squnion> y = \\<top>))\"\n\nbegin\n\nlemmas bool_lattice_dclattice = dclattice\n\nend\n\nnotation (zed)\n  bool_lattice (\"\\<^bllattice>{:_:}{:_:}\")\n\nlemma (in bool_lattice) bool_lattice:\n  \"\\<^bllattice>{:X:}{:(op \\<sqsubseteq>):}\"\n  by (intro_locales)\n\nlemma (in dclattice) bool_latticeI:\n  \"(\\<forall> x | x \\<in> X \\<bullet> (\\<exists> y | y \\<in> X \\<bullet> x \\<sqinter> y = \\<bottom> \\<and> x \\<squnion> y = \\<top>))\n  \\<turnstile> \\<^bllattice>{:X:}{:(op \\<sqsubseteq>):}\"\n  apply (rule bool_lattice.intro)\n  apply (auto intro: carrier_axioms setrel_axioms reflexive_axioms transitive_axioms \n    antisymmetric_axioms clattice_axioms dclattice_axioms)\n  apply (rule bool_lattice_axioms.intro)\n  apply (assumption)\n  done\n\ncontext bool_lattice\n\nbegin\n\nlemma ex1_complement:\n  assumes\n    a1: \"x \\<in> X\"\n  shows\n      \"(\\<exists>\\<subone> y | y \\<in> X \\<bullet> x \\<sqinter> y = \\<bottom> \\<and> x \\<squnion> y = \\<top>)\"\n  apply (rule ex_ex1I [OF ex_complement [rule_format]])\n  apply (msafe(inference))\n  apply (rule a1)\nproof -\n  fix y y'\n  assume\n    b1a: \"y \\<in> X\" and b1b: \"y' \\<in> X\" and\n    b2a: \"x \\<sqinter> y = \\<bottom>\" and b2b: \"x \\<sqinter> y' = \\<bottom>\" and\n    b3a: \"x \\<squnion> y = \\<top>\" and b3b: \"x \\<squnion> y' = \\<top>\"\n  show \"y = y'\"\n    by (simp add: complement_unique [OF a1 b1a b2a b3a] complement_unique [OF a1 b1b b2b b3b])\nqed\n\nlemma compR [simp]:\n  \"x \\<in> X \\<turnstile> \\<sim>x \\<in> X\"\n  using ex1_complement [THEN theI']\n  by (simp add: complement_def )\n\nlemma compD1:\n  \"x \\<in> X \\<turnstile> x \\<sqinter> \\<sim>x = \\<bottom>\"\n  using ex1_complement [THEN theI']\n  by (simp add: complement_def)\n\nlemma compD2:\n  \"x \\<in> X \\<turnstile> x \\<squnion> \\<sim>x = \\<top>\"\n  by (simp add: complement_def ex1_complement [THEN theI'])\n\nlemma deMorgan_Meet:\n  assumes \n    a1: \"Y \\<subseteq> X\"\n  shows\n      \"\\<sim>(\\<Sqinter>Y) = (\\<Squnion>{ y | y \\<in> Y \\<bullet> \\<sim>y})\"\n  apply (rule complement_unique [symmetric])\n  using a1\n  apply (auto intro!: MeetR JoinR compR)\nproof -\n  from a1 [THEN subsetD] have \n    b1: \"{y | y \\<in> Y \\<bullet> \\<sim>y} \\<subseteq> X\"\n    by (auto simp add: compR)\n{ from a1 b1 Join_distD [OF MeetR [OF a1] b1, THEN sym] have \n      \"(\\<Sqinter>Y) \\<sqinter> (\\<Squnion>{ y | y \\<in> Y \\<bullet> \\<sim>y})\n      = (\\<Squnion>{ y | y \\<in> Y \\<bullet> (\\<Sqinter>Y) \\<sqinter> \\<sim>y})\"\n    by (auto intro!: set_eqI arg_cong [of _ _ \"Join\"] simp add: eind_comp)\n  also from a1 have \"\\<dots> \n      \\<sqsubseteq> (\\<Squnion>{ y | y \\<in> Y \\<bullet> y \\<sqinter> \\<sim>y})\"\n    apply (intro Join_dom)\n    apply (auto intro!: compR meetR MeetR JoinR)\n    apply (rule meet_mono)\n    apply (rule Meet_lbD)\n    apply (auto)\n    apply (rule reflD)\n    apply (auto)\n    done\n  also from a1 subsetD have \"\\<dots> \n      \\<sqsubseteq> \\<bottom>\"\n    by (auto intro!: Join_lubD reflD simp add: BottomR meetR compR compD1 [OF subsetD])\n  finally show \n      \"(\\<Sqinter>Y) \\<sqinter> (\\<Squnion>{ y | y \\<in> Y \\<bullet> \\<sim>y}) = \\<bottom>\"\n    using a1 b1\n    by (auto intro!: antisymD Bottom_lb meetR compR MeetR JoinR simp add: a1 [THEN subsetD])\nnext\n  from a1 have \n      \"\\<top> \n      = (\\<Sqinter>{y | y \\<in> Y \\<bullet> y \\<squnion> \\<sim>y})\"\n    by (auto intro!: Meet_unique joinR compR TopR reflD Top_ub simp add: compD2 [OF subsetD])\n  also from a1 have \"\\<dots> \n      \\<sqsubseteq> (\\<Sqinter>{y | y \\<in> Y \\<bullet> y \\<squnion> (\\<Squnion>{y | y \\<in> Y \\<bullet> \\<sim>y})})\"\n    apply (auto intro!: Meet_glbD joinR compR JoinR MeetR simp add: subsetD [OF a1] )\n    apply (rule transD)\n    apply (auto intro!: Meet_lbD join_mono reflD Join_ubD joinR compR JoinR MeetR)\n    done\n  also from a1 b1 have \"\\<dots> \n      = (\\<Sqinter>Y) \\<squnion> (\\<Squnion>{y | y \\<in> Y \\<bullet> \\<sim>y})\"\n    by (simp add: Meet_distD'[OF JoinR a1] compR)\n  finally show \n      \"(\\<Sqinter>Y) \\<squnion> (\\<Squnion>{y | y \\<in> Y \\<bullet> \\<sim>y}) = \\<top>\"\n    using a1 b1\n    by (auto intro!: antisymD Top_ub joinR compR JoinR MeetR) }\nqed\n\nend\n\n\nsection {* Atomic lattices *}\n\ntext {*\n\nIn a complete lattice, an element is called an atom if and only if it\nhas no lower bounds but bottom and itself.\n\n*}\n\ncontext clattice\n\nbegin\n\ndefinition\n  atoms :: \"'a set\" (\"\\<atoms>\")\nwhere\n  atoms_def: \"\\<atoms> \\<defs> { x | x \\<noteq> \\<bottom> \\<and> (\\<forall> y \\<bullet> y \\<sqsubseteq> x \\<Rightarrow> y = \\<top> \\<or> y = x)}\"\n\ndefinition\n    basis_set :: \"'a \\<rightarrow> 'a set\" (\"\\<^basis>{:_:}\")\nwhere\n    basis_set_def: \"\\<^basis>{:y:} \\<defs> {b | b \\<in> \\<atoms> \\<and> b \\<sqsubseteq> y}\"\n\nend\n\nnotation (zed)\n  clattice.atoms (\"\\<^atom>{:_:}{:_:}\") and\n  clattice.atoms (\"\\<^atoma>{:_:}{:_:}\")\n\ntext {*\n\nA lattice is atomic if every element can be expressed as a join of atomic\nelements.\n\n*}\n\nlocale atomic_lattice =\n  clattice + \n  \nassumes\n  atom_decomp: \"(\\<forall> x | x \\<in> X \\<bullet> x = (\\<Squnion>{y | y \\<in> \\<atoms> \\<and> y \\<sqsubseteq> x}))\"\n\nbegin\n\nlemmas atomic_lattice_clattice = clattice \n\nend\n\nnotation (zed)\n  atomic_lattice (\"\\<^alattice>{:_:}{:_:}\")\n\nlemma (in atomic_lattice) atomic_lattice:\n    \"\\<^alattice>{:X:}{:(op \\<sqsubseteq>):}\"\n  by (intro_locales)\n\nsection {* Dual lattices *}\n\ntext {*\n\nThe notions of meet and join are dual and so the dual of a \n(complete) lattice is also a\n(complete) lattice.\n\n*}\n\ncontext setrel_sig\n\nbegin\n\nlemma meet_dual:\n    \"x \\<^meet>{:X:}{:(op \\<hookleftarrow>):} y = x \\<squnion> y\"\n  by (simp add: meet_def join_def is_glb_dual)\n\nlemma join_dual:\n    \"x \\<^join>{:X:}{:(op \\<hookleftarrow>):} y = x \\<sqinter> y\"\n  by (simp add: meet_def join_def is_lub_dual)\n\nlemma Meet_dual:\n    \"\\<^Meet>{:X:}{:(op \\<hookleftarrow>):}Y = \\<Squnion>Y\"\n  by (simp add: Meet_def Join_def is_glb_dual)\n\nlemma Join_dual:\n    \"\\<^Join>{:X:}{:(op \\<hookleftarrow>):}Y = \\<Sqinter>Y\"\n  by (simp add: Meet_def Join_def is_lub_dual)\n\nlemma Bottom_dual:\n    \"\\<^Bottom>{:X:}{:(op \\<hookleftarrow>):} = \\<top>\"\n  by (simp add: Bottom_def Top_def Meet_dual Join_dual)\n\nlemma Top_dual:\n    \"\\<^Top>{:X:}{:(op \\<hookleftarrow>):} = \\<bottom>\"\n  by (simp add: Bottom_def Top_def Meet_dual Join_dual)\n\nlemma complement_dual:\n    \"Lattice_Locale.complement X (op \\<hookleftarrow>) = complement\"\n  by (auto \n        intro!: arg_cong [of _ _ \"The\"] \n        simp add: complement_def fun_eq_def meet_dual join_dual Bottom_dual Top_dual)\n\nend\n\n(*\ninterpretation lattice [\"X\" \"\\<^dualord>{:BS_leq:}\"]\n  apply (rule partial_order.latticeI [OF dual_poI])\n  apply (simp_all add: is_glb_dual is_lub_dual ex_glb2 ex_lub2)\n  done\n\nlemma (in dlattic) dual_dlatticeI:\n  \"dlattice X \\<^dualord>{:BS_leq:}\"\n  apply (rule lattice.dlatticeI [OF dual_latticeI])\n  apply (fold BS_sqcap_def)\n  apply (simp_all add: meet_dual join_dual meet_dist join_dist)\n  done\n\nlemma (in clattice) dual_clatticeI:\n  \"clattice X \\<^dualord>{:BS_leq:}\"\n  apply (rule partial_order.clatticeI [OF dual_poI])\n  apply (simp_all add: is_glb_dual is_lub_dual ex_glb ex_lub)\n  done\n\nlemma (in dclattice) dual_dclatticeI:\n  \"dclattice X \\<^dualord>{:BS_leq:}\"\n  apply (rule clattice.dclatticeI [OF dual_clatticeI])\n  apply (simp_all add: \n    Meet_dual Join_dual \n    join_dual meet_dual\n    Meet_distD Join_distD)\n  done\n\nlemma (in bool_lattice) dual_bool_latticeI:\n  \"bool_lattice X \\<^dualord>{:BS_leq:}\"\n  apply (rule dclattice.bool_latticeI [OF dual_dclatticeI])\n  apply (insert ex_complement)\n  apply (auto simp add: \n    join_dual meet_dual\n    Bottom_dual Top_dual)\n  done\n\ntext {*\n\nThis leads to a duality principle for lattice properties.\n\n*}\n\nlemma dual_lattice_principle:\n  fixes P::\"['a set, ['a, 'a] \\<rightarrow> 'a, ['a, 'a] \\<rightarrow> 'a] \\<rightarrow> \\<bool>\"\n  assumes a1: \"\\<forall> X BS_leq | lattice X BS_leq \\<bullet> P X (meet X BS_leq) (join X BS_leq)\"\n  shows \"\\<forall> X BS_leq | lattice X BS_leq \\<bullet> P X (join X BS_leq) (meet X BS_leq)\"\nproof (auto)\n  fix X::\"'a set\" and BS_leq::\"['a, 'a] \\<rightarrow> \\<bool>\"\n  assume b1: \"lattice X BS_leq\"\n  then have \"lattice X \\<^dualord>{:BS_leq:}\"\n    by (rule lattice.dual_latticeI)\n  with a1 have \"P X (meet X \\<^dualord>{:BS_leq:}) (join X \\<^dualord>{:BS_leq:})\"\n    by (auto)\n  then show \"P X (join X BS_leq) (meet X BS_leq)\"\n    by (simp add: meet_dual join_dual)\nqed\n\nlemma dual_clattice_principle:\n  fixes P::\"['a set, 'a set \\<rightarrow> 'a, 'a set \\<rightarrow> 'a] \\<rightarrow> \\<bool>\"\n  assumes a1: \"\\<forall> X BS_leq | clattice X BS_leq \\<bullet> P X (Meet X BS_leq) (Join X BS_leq)\"\n  shows \"\\<forall> X BS_leq | clattice X BS_leq \\<bullet> P X (Join X BS_leq) (Meet X BS_leq)\"\nproof (auto)\n  fix X::\"'a set\" and BS_leq::\"['a, 'a] \\<rightarrow> \\<bool>\"\n  assume b1: \"clattice X BS_leq\"\n  then have \"clattice X \\<^dualord>{:BS_leq:}\"\n    by (rule clattice.dual_clatticeI)\n  with a1 have \"P X (Meet X \\<^dualord>{:BS_leq:}) (Join X \\<^dualord>{:BS_leq:})\"\n    by (auto)\n  then show \"P X (Join X BS_leq) (Meet X BS_leq)\"\n    by (simp add: Meet_dual Join_dual)\nqed\n\nlemma dual_bool_lattice_principle:\n  fixes P::\"['a set, 'a set \\<rightarrow> 'a, 'a set \\<rightarrow> 'a, 'a \\<rightarrow> 'a] \\<rightarrow> \\<bool>\"\n  assumes a1: \"\\<forall> X BS_leq | bool_lattice X BS_leq \\<bullet> P X (Meet X BS_leq) (Join X BS_leq) (complement X BS_leq)\"\n  shows \"\\<forall> X BS_leq | bool_lattice X BS_leq \\<bullet> P X (Join X BS_leq) (Meet X BS_leq) (complement X BS_leq)\"\nproof (auto)\n  fix X::\"'a set\" and BS_leq::\"['a, 'a] \\<rightarrow> \\<bool>\"\n  assume b1: \"bool_lattice X BS_leq\"\n  then have \"bool_lattice X \\<^dualord>{:BS_leq:}\"\n    by (rule bool_lattice.dual_bool_latticeI)\n  with a1 have \"P X (Meet X \\<^dualord>{:BS_leq:}) (Join X \\<^dualord>{:BS_leq:}) (complement X \\<^dualord>{:BS_leq:})\"\n    by (auto)\n  then show \"P X (Join X BS_leq) (Meet X BS_leq) (complement X BS_leq)\"\n    by (simp add: Meet_dual Join_dual complement_dual)\nqed\n\ntext {*\n\nA an example in the use of the dual principle we consider de Morgan's law for\njoins.\n\n*}\n\n\nlemma (in bool_lattice) deMorgan_Join:\n  assumes a1: \"Y \\<subseteq> X\"\n  shows \"\\<^lcomp>{:X:}{:BS_leq:}{:\\<^Join>{:X:}{:BS_leq:}{:Y:}:} = \\<^Meet>{:X:}{:BS_leq:}{:{ y | y \\<in> Y \\<bullet> \\<^lcomp>{:X:}{:BS_leq:}{:y:}}:}\"\nproof -\n  have \"Y \\<subseteq> X \\<Rightarrow> \\<^lcomp>{:X:}{:BS_leq:}{:\\<^Join>{:X:}{:BS_leq:}{:Y:}:} = \\<^Meet>{:X:}{:BS_leq:}{:{ y | y \\<in> Y \\<bullet> \\<^lcomp>{:X:}{:BS_leq:}{:y:}}:}\"\n    apply (rule dual_bool_lattice_principle [rule_format])\n    apply (inference)\n    apply (rule bool_lattice.deMorgan_Meet)\n    apply (insert a1, auto ! simp add: bool_lattice_def)\n    done\n  with a1 show ?thesis\n    by (auto)\nqed\n*)\n\nsection {* Sub-lattices *}\n\ntext {*\n\nIf the sub-order @{text \"(Y, \\<^subord>{:Y:}{:BS_leq:})\"}, \n@{text \"Y \\<subseteq> X\"}, forms a lattice we say that it is a {\\em sub-lattice}\nof @{text \"(X, BS_leq)\"}. A sub order need not be a sub-lattice, since\nmeets and joins may not always exist in the sub-order. Even where they\ndo exist, they may not be the same as for the super-lattice. However,\nwhen a sub-order is closed under meets and joins, it\ndoes indeed form a sub-lattice.\n\n*}  \n\nlocale X_lattice =\n  X: lattice X r\nfor \n  X::\"'a set\" and\n  r::\"'a orderT\"\n\nbegin\n\nnotation\n  r (infixl \"\\<sqsubseteq>\\<^sub>X\" 50)\n\nnotation\n  X.meet (infixl \"\\<sqinter>\\<^sub>X\" 70) and\n  X.join (infixl \"\\<squnion>\\<^sub>X\" 65)\n\nend\n\nsublocale X_lattice \\<subseteq> X_partial_order\n  by (unfold_locales)\n\nlocale Y_lattice =\n  Y: lattice Y s\nfor \n  Y::\"'a set\" and\n  s::\"'a orderT\"\n\nbegin\n\nnotation\n  s (infixl \"\\<sqsubseteq>\\<^sub>Y\" 50)\n\nnotation\n  Y.meet (infixl \"\\<sqinter>\\<^sub>Y\" 70) and\n  Y.join (infixl \"\\<squnion>\\<^sub>Y\" 65)\n\nend\n\nsublocale Y_lattice \\<subseteq> Y_partial_order\n  by (unfold_locales)\n\nlocale sub_lattice =\n  sub_partial_order +\n  X_lattice \n\nbegin\n\nlemmas sub_lattice_X_lattice = X.lattice\n\nlemmas sub_lattice_Y_poI = Y_poI\n\nlemma sublatticeI:\n  assumes\n    ex_glb: \"(\\<And> x y \\<bullet> \\<lbrakk> x \\<in> Y; y \\<in> Y \\<rbrakk> \\<turnstile> (\\<exists> a \\<bullet> is_glb\\<^sub>Y {x, y} a))\" and\n    ex_lub: \"(\\<And> x y \\<bullet> \\<lbrakk> x \\<in> Y; y \\<in> Y \\<rbrakk> \\<turnstile> (\\<exists> a \\<bullet> is_lub\\<^sub>Y {x, y} a))\"\n  shows\n      \"\\<^lattice>{:Y:}{:(op \\<preceq>\\<^sub>Y):}\"\n  using Y.latticeI ex_glb ex_lub\n  by (auto)\n\nlemma submeetI:\n  assumes\n    a1: \"(\\<forall> x y | x \\<in> Y \\<and> y \\<in> Y \\<bullet> x \\<sqinter>\\<^sub>X y \\<in> Y)\" and\n    b1: \"x \\<in> Y\" and b2: \"y \\<in> Y\"\n  shows \n      \"is_glb\\<^sub>Y {x, y} (x \\<sqinter>\\<^sub>X y)\"\nproof -\n  from subset_Y b1 b2 have \n    b3: \"is_glb\\<^sub>X {x, y} (x \\<sqinter>\\<^sub>X y)\"\n    by (auto intro!: meet_glb)\n  show \n      \"is_glb\\<^sub>Y {x, y} (x \\<sqinter>\\<^sub>X y)\"\n    apply (intro Y.is_glbI)\n    apply (auto simp add: subset_order_def op2rel_def rel2op_def b1 b2 a1 [rule_format])\n  proof -\n    show \"x \\<sqinter>\\<^sub>X y \\<sqsubseteq>\\<^sub>X x\"\n      apply (rule X.is_glbD1' [OF b3])\n      apply (simp)\n      done\n    show \"x \\<sqinter>\\<^sub>X y \\<sqsubseteq>\\<^sub>X y\"\n      apply (rule X.is_glbD1' [OF b3])\n      apply (simp)\n      done\n    fix \n      b \n    assume \n        \"b \\<in> Y\" \"b \\<sqsubseteq>\\<^sub>X x\" \"b \\<sqsubseteq>\\<^sub>X y\"\n    with subset_Y show \n        \"b \\<sqsubseteq>\\<^sub>X x \\<sqinter>\\<^sub>X y\"\n      apply (intro X.is_glbD2' [OF b3])\n      apply (auto)\n      done\n  qed\nqed\n\nlemma subjoinI:\n  assumes\n    a1: \"\\<forall> x y | x \\<in> Y \\<and> y \\<in> Y \\<bullet> x \\<squnion>\\<^sub>X y \\<in> Y\" and\n    b1: \"x \\<in> Y\" and b2: \"y \\<in> Y\"\n  shows \n      \"is_lub\\<^sub>Y {x, y} (x \\<squnion>\\<^sub>X y)\"\nproof -\n  from subset_Y b1 b2 have \n    b3: \"is_lub\\<^sub>X {x, y} (x \\<squnion>\\<^sub>X y)\"\n    by (auto intro!: join_lub)\n  show \n      \"is_lub\\<^sub>Y {x, y} (x \\<squnion>\\<^sub>X y)\"\n    apply (intro Y.is_lubI)\n    apply (auto simp add: subset_order_def op2rel_def rel2op_def b1 b2 a1 [rule_format])\n  proof -\n    show \"x \\<sqsubseteq>\\<^sub>X x \\<squnion>\\<^sub>X y\"\n      apply (rule X.is_lubD1' [OF b3])\n      apply (simp)\n      done\n    show \"y \\<sqsubseteq>\\<^sub>X x \\<squnion>\\<^sub>X y\"\n      apply (rule X.is_lubD1' [OF b3])\n      apply (simp)\n      done\n    fix b \n    assume \n      \"b \\<in> Y\" \"x \\<sqsubseteq>\\<^sub>X b\" \"y \\<sqsubseteq>\\<^sub>X b\"\n    with subset_Y show \n        \"x \\<squnion>\\<^sub>X y \\<sqsubseteq>\\<^sub>X b\"\n      apply (intro X.is_lubD2' [OF b3])\n      apply (auto)\n      done\n  qed\nqed\n\nlemma sublatticeI':\n  assumes\n    a1: \"(\\<forall> x y | x \\<in> Y \\<and> y \\<in> Y \\<bullet> x \\<sqinter>\\<^sub>X y \\<in> Y \\<and> x \\<squnion>\\<^sub>X y \\<in> Y)\"\n  shows\n      \"\\<^lattice>{:Y:}{:(op \\<preceq>\\<^sub>Y):}\"\n  apply (rule Y.latticeI)\n  apply (auto intro!: exI submeetI subjoinI simp add: subset_Y a1 [rule_format])\n  done\n\nend\n\nlocale X_clattice =\n  X: clattice X r\nfor \n  X::\"'a set\" and\n  r::\"'a orderT\"\n\nbegin\n\nnotation\n  X.Meet (\"\\<Sqinter>\\<^sub>X_\") and\n  X.Join (\"\\<Squnion>\\<^sub>X_\")\n\nnotation\n  X.Bottom (\"\\<bottom>\\<^sub>X\") and\n  X.Top (\"\\<top>\\<^sub>X\")\n\nend\n\nsublocale X_clattice \\<subseteq> X_lattice\n  by (unfold_locales)\n\nlocale Y_clattice =\n  Y: clattice Y s\nfor \n  Y::\"'a set\" and\n  s::\"'a orderT\"\n\nbegin\n\nnotation\n  Y.Meet (\"\\<Sqinter>\\<^sub>Y_\") and\n  Y.Join (\"\\<Squnion>\\<^sub>Y_\")\n\nnotation\n  Y.Bottom (\"\\<bottom>\\<^sub>Y\") and\n  Y.Top (\"\\<top>\\<^sub>Y\")\n\nend\n\nsublocale Y_clattice \\<subseteq> Y_lattice\n  by (unfold_locales)\n\nlocale sub_clattice =\n  sub_partial_order +\n  X_clattice \n\nbegin\n\nlemmas sub_clattice_lattice = X.clattice\n\nlemmas sub_clattice_Y_poI = Y_poI\n\nlemma subclatticeI:\n  assumes\n    ex_glb: \"\\<And> A \\<bullet> A \\<subseteq> Y \\<turnstile> (\\<exists> a \\<bullet> is_glb\\<^sub>Y A a)\" and\n    ex_lub: \"\\<And> A \\<bullet> A \\<subseteq> Y \\<turnstile> (\\<exists> a \\<bullet> is_lub\\<^sub>Y A a)\"\n  shows\n      \"clattice Y (op \\<preceq>\\<^sub>Y)\"\n  using Y.clatticeI ex_glb ex_lub subset_Y\n  by (auto)\n\nlemma subMeetI:\n  assumes\n    a1: \"\\<forall> A | A \\<subseteq> Y \\<bullet> (\\<Sqinter>\\<^sub>XA) \\<in> Y\" and\n    b1: \"A \\<subseteq> Y\"\n  shows\n      \"is_glb\\<^sub>Y A (\\<Sqinter>\\<^sub>XA)\"\nproof -\n  from subset_Y a1 b1 have \n    b3: \"is_glb\\<^sub>X A (\\<Sqinter>\\<^sub>XA)\"\n    by (auto intro!: Meet_glb)\n  show \n      \"is_glb\\<^sub>Y A (\\<Sqinter>\\<^sub>XA)\" \n  proof (rule Y.is_glbI)\n    from a1 b1 show \n        \"(\\<Sqinter>\\<^sub>XA) \\<in> Y\"\n      by (auto)\n  next\n    fix \n      x \n    assume \n      c1: \"x \\<in> A\"\n    from c1 b1 subset_Y have \n        \"(\\<Sqinter>\\<^sub>XA) \\<sqsubseteq>\\<^sub>X x\"\n      apply (intro Meet_lbD)\n      apply (auto)\n      done\n    with c1 b1 a1 subset_Y show \n        \"(\\<Sqinter>\\<^sub>XA) \\<preceq>\\<^sub>Y x\"\n      by (auto simp add: subset_order_def op2rel_def rel2op_def)\n  next\n    fix a \n    assume \n      c1: \"a \\<in> Y\" and \n      c2: \"\\<forall> x | x \\<in> A \\<bullet> a \\<preceq>\\<^sub>Y x\"\n    from c2 have \n      c3: \"\\<forall> x | x \\<in> A \\<bullet> a \\<preceq> x\"\n      by (auto simp add: subset_order_def op2rel_def rel2op_def) \n    with c1 b1 subset_Y have \n        \"a \\<sqsubseteq>\\<^sub>X (\\<Sqinter>\\<^sub>XA)\"\n      apply (intro Meet_glbD)\n      apply (auto simp add: subset_order_def op2rel_def rel2op_def) \n      done\n    with c1 b1 a1 show \n        \"a \\<preceq>\\<^sub>Y (\\<Sqinter>\\<^sub>XA)\"\n      by (simp add: subset_order_def op2rel_def rel2op_def) \n  qed\nqed\n\nlemma subJoinI:\n  assumes\n    a1: \"(\\<forall> A | A \\<subseteq> Y \\<bullet> (\\<Squnion>\\<^sub>XA) \\<in> Y)\" and\n    b1: \"A \\<subseteq> Y\"\n  shows\n      \"is_lub\\<^sub>Y A (\\<Squnion>\\<^sub>XA)\"\nproof -\n  from b1 subset_Y have \n    b3: \"is_lub\\<^sub>X A (\\<Squnion>\\<^sub>XA)\"\n    by (auto intro!: Join_lub)\n  show \n      \"is_lub\\<^sub>Y A (\\<Squnion>\\<^sub>XA)\" \n  proof (rule Y.is_lubI)\n    from b1 a1 show \n        \"(\\<Squnion>\\<^sub>XA) \\<in> Y\"\n      by (auto)\n  next\n    fix \n      x \n    assume \n      c1: \"x \\<in> A\"\n    from c1 b1 subset_Y have \n        \"x \\<sqsubseteq>\\<^sub>X (\\<Squnion>\\<^sub>XA)\"\n      apply (intro Join_ubD)\n      apply (auto)\n      done\n    with c1 b1 a1 subset_Y show \n        \"x \\<preceq>\\<^sub>Y (\\<Squnion>\\<^sub>XA)\"\n      by (auto simp add: subset_order_def op2rel_def rel2op_def)\n  next\n    fix a \n    assume \n      c1: \"a \\<in> Y\" and \n      c2: \"(\\<forall> x | x \\<in> A \\<bullet> x \\<preceq>\\<^sub>Y a)\"\n    from c2 have \n      c3: \"(\\<forall> x | x \\<in> A \\<bullet> x \\<sqsubseteq>\\<^sub>X a)\"\n      by (auto simp add: subset_order_def op2rel_def rel2op_def) \n    with c1 b1 subset_Y have \n        \"(\\<Squnion>\\<^sub>XA) \\<sqsubseteq>\\<^sub>X a\"\n      apply (intro Join_lubD)\n      apply (auto) \n      done\n    with c1 b1 a1 show \n        \"(\\<Squnion>\\<^sub>XA) \\<preceq>\\<^sub>Y a\"\n      by (simp add: subset_order_def op2rel_def rel2op_def) \n  qed\nqed\n\nlemma subclatticeI':\n  assumes\n    a3: \"(\\<And> A \\<bullet> A \\<subseteq> Y \\<turnstile> (\\<Sqinter>\\<^sub>XA) \\<in> Y)\" and\n    a4: \"(\\<And> A \\<bullet> A \\<subseteq> Y \\<turnstile> (\\<Squnion>\\<^sub>XA) \\<in> Y)\"\n  shows\n    \"\\<^clattice>{:Y:}{:(op \\<preceq>\\<^sub>Y):}\"\n  apply (rule Y.clatticeI)\n  apply (auto intro!: exI subJoinI subMeetI a3 a4)\n  done\n\nend (* locale clattice_subset *)\n\nend (* theory Lattice_Locale*)\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/Lattice_Locale.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240756264639, "lm_q2_score": 0.8418256532040708, "lm_q1q2_score": 0.7283678226321363}}
{"text": "(*\n    File:     Generated_Groups_Extend.thy\n    Author:   Joseph Thommes, TU M\u00fcnchen\n*)\nsection \\<open>Generated Groups\\<close>\n\ntheory Generated_Groups_Extend\n  imports Miscellaneous_Groups\nbegin\n\ntext \\<open>This section extends the lemmas and facts about \\<open>generate\\<close>. Starting with a basic fact.\\<close>\n\nlemma (in group) generate_sincl:\n  \"A \\<subseteq> generate G A\"\n  using generate.incl by fast\n\ntext \\<open>The following lemmas reflect some of the idempotence characteristics of \\<open>generate\\<close> and have\nproved useful at several occasions.\\<close>\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))\"\n      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_idem'_right:\n  assumes \"A \\<subseteq> carrier G\" \"B \\<subseteq> carrier G\"\n  shows \"generate G (A \\<union> generate G B) = generate G (A \\<union> B)\"\n  using generate_idem'[OF assms(2) assms(1)] by (simp add: sup_commute)\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  hence \"(\\<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\"\n    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  hence \"(\\<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)\"\n    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})\"\n    using generate_idem_fUn[of f] assms by blast\n  then have \"generate G (\\<Union>S \\<in> A. generate G (f S))\n           = 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)\"]\n            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))\"\n    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))\"\n      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)))\"\n      using mono_generate by meson\n    thus \"generate G (\\<Union>S\\<in>A. generate G (f S)) \\<subseteq>  generate G (\\<Union> (f ` A))\"\n      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]\n  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))\n             \\<subseteq> generate G (\\<Union> {generate G {x} |x. x \\<in> \\<Union> (f ` A)})\" by blast\nqed\n\ntext \\<open>The following two rules allow for convenient proving of the equality of two generated sets.\\<close>\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  using assms generate_idem by (metis generate_idem' inf_sup_aci(5) sup.absorb2)\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(intro generate_eqI)\n  show \"A \\<subseteq> carrier G\" by fact\n  show \"B \\<subseteq> carrier G\" using assms generate_incl by blast\n  show \"A \\<subseteq> generate G B\" using assms generate_sincl[of B] by blast\n  show \"B \\<subseteq> generate G A\" using assms generate_sincl[of A] by blast\nqed\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\ntext \\<open>Some smaller lemmas about \\<open>generate\\<close>.\\<close>\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_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_inv_eq:\n  assumes \"a \\<in> carrier G\"\n  shows \"generate G {a} = generate G {inv a}\"\n  by (intro generate_eqI;\n      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\n\ntext \\<open>The neutral element does not play a role when generating a subgroup.\\<close>\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(rule subsetI)\n    show \"x \\<in> generate G A\" if \"x \\<in> generate G (A \\<union> {\\<one>})\" for x using that\n      by (induction rule: generate.induct;\n          use generate.one generate.incl generate.inv generate.eng in auto)\n  qed\nqed\n\nlemma (in group) generate_one_irrel':\n  \"generate G A = generate G (A - {\\<one>})\"\n  using generate_one_irrel by (metis Un_Diff_cancel2)\n\ntext \\<open>Also, we can express the subgroup generated by a singleton with finite order using just its\npowers up to its order.\\<close>\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}}\"\n  using assms generate_pow_nat ord_elems_inf_carrier by auto\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}\"\n        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\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/Finitely_Generated_Abelian_Groups/Generated_Groups_Extend.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8418256393148982, "lm_q2_score": 0.8652240895276223, "lm_q1q2_score": 0.7283678223172414}}
{"text": "(*  Title:      ZF/equalities.thy\n    Author:     Lawrence C Paulson, Cambridge University Computer Laboratory\n    Copyright   1992  University of Cambridge\n*)\n\nsection\\<open>Basic Equalities and Inclusions\\<close>\n\ntheory equalities imports pair begin\n\ntext\\<open>These cover union, intersection, converse, domain, range, etc.  Philippe\nde Groote proved many of the inclusions.\\<close>\n\nlemma in_mono: \"A\\<subseteq>B ==> x\\<in>A \\<longrightarrow> x\\<in>B\"\nby blast\n\nlemma the_eq_0 [simp]: \"(THE x. False) = 0\"\nby (blast intro: the_0)\n\nsubsection\\<open>Bounded Quantifiers\\<close>\ntext \\<open>\\medskip\n\n  The following are not added to the default simpset because\n  (a) they duplicate the body and (b) there are no similar rules for \\<open>Int\\<close>.\\<close>\n\nlemma ball_Un: \"(\\<forall>x \\<in> A\\<union>B. P(x)) \\<longleftrightarrow> (\\<forall>x \\<in> A. P(x)) & (\\<forall>x \\<in> B. P(x))\"\n  by blast\n\nlemma bex_Un: \"(\\<exists>x \\<in> A\\<union>B. P(x)) \\<longleftrightarrow> (\\<exists>x \\<in> A. P(x)) | (\\<exists>x \\<in> B. P(x))\"\n  by blast\n\nlemma ball_UN: \"(\\<forall>z \\<in> (\\<Union>x\\<in>A. B(x)). 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>x\\<in>A. B(x)). P(z)) \\<longleftrightarrow> (\\<exists>x\\<in>A. \\<exists>z\\<in>B(x). P(z))\"\n  by blast\n\nsubsection\\<open>Converse of a Relation\\<close>\n\nlemma converse_iff [simp]: \"<a,b>\\<in> converse(r) \\<longleftrightarrow> <b,a>\\<in>r\"\nby (unfold converse_def, blast)\n\nlemma converseI [intro!]: \"<a,b>\\<in>r ==> <b,a>\\<in>converse(r)\"\nby (unfold converse_def, blast)\n\nlemma converseD: \"<a,b> \\<in> converse(r) ==> <b,a> \\<in> r\"\nby (unfold converse_def, blast)\n\nlemma converseE [elim!]:\n    \"[| yx \\<in> converse(r);\n        !!x y. [| yx=<y,x>;  <x,y>\\<in>r |] ==> P |]\n     ==> P\"\nby (unfold converse_def, blast)\n\nlemma converse_converse: \"r\\<subseteq>Sigma(A,B) ==> converse(converse(r)) = r\"\nby blast\n\nlemma converse_type: \"r\\<subseteq>A*B ==> converse(r)\\<subseteq>B*A\"\nby blast\n\nlemma converse_prod [simp]: \"converse(A*B) = B*A\"\nby blast\n\nlemma converse_empty [simp]: \"converse(0) = 0\"\nby blast\n\nlemma converse_subset_iff:\n     \"A \\<subseteq> Sigma(X,Y) ==> converse(A) \\<subseteq> converse(B) \\<longleftrightarrow> A \\<subseteq> B\"\nby blast\n\n\nsubsection\\<open>Finite Set Constructions Using @{term cons}\\<close>\n\nlemma cons_subsetI: \"[| a\\<in>C; B\\<subseteq>C |] ==> cons(a,B) \\<subseteq> C\"\nby blast\n\nlemma subset_consI: \"B \\<subseteq> cons(a,B)\"\nby blast\n\nlemma cons_subset_iff [iff]: \"cons(a,B)\\<subseteq>C \\<longleftrightarrow> a\\<in>C & B\\<subseteq>C\"\nby blast\n\n(*A safe special case of subset elimination, adding no new variables\n  [| cons(a,B) \\<subseteq> C; [| a \\<in> C; B \\<subseteq> C |] ==> R |] ==> R *)\nlemmas cons_subsetE = cons_subset_iff [THEN iffD1, THEN conjE]\n\nlemma subset_empty_iff: \"A\\<subseteq>0 \\<longleftrightarrow> A=0\"\nby blast\n\nlemma subset_cons_iff: \"C\\<subseteq>cons(a,B) \\<longleftrightarrow> C\\<subseteq>B | (a\\<in>C & C-{a} \\<subseteq> B)\"\nby blast\n\n(* cons_def refers to Upair; reversing the equality LOOPS in rewriting!*)\nlemma cons_eq: \"{a} \\<union> B = cons(a,B)\"\nby blast\n\nlemma cons_commute: \"cons(a, cons(b, C)) = cons(b, cons(a, C))\"\nby blast\n\nlemma cons_absorb: \"a: B ==> cons(a,B) = B\"\nby blast\n\nlemma cons_Diff: \"a: B ==> cons(a, B-{a}) = B\"\nby blast\n\nlemma Diff_cons_eq: \"cons(a,B) - C = (if a\\<in>C then B-C else cons(a,B-C))\"\nby auto\n\nlemma equal_singleton [rule_format]: \"[| a: C;  \\<forall>y\\<in>C. y=b |] ==> C = {b}\"\nby blast\n\n\n\n(** singletons **)\n\nlemma singleton_subsetI: \"a\\<in>C ==> {a} \\<subseteq> C\"\nby blast\n\nlemma singleton_subsetD: \"{a} \\<subseteq> C  ==>  a\\<in>C\"\nby blast\n\n\n(** succ **)\n\nlemma subset_succI: \"i \\<subseteq> succ(i)\"\nby blast\n\n(*But if j is an ordinal or is transitive, then @{term\"i\\<in>j\"} implies @{term\"i\\<subseteq>j\"}!\n  See @{text\"Ord_succ_subsetI}*)\nlemma succ_subsetI: \"[| i\\<in>j;  i\\<subseteq>j |] ==> succ(i)\\<subseteq>j\"\nby (unfold succ_def, blast)\n\nlemma succ_subsetE:\n    \"[| succ(i) \\<subseteq> j;  [| i\\<in>j;  i\\<subseteq>j |] ==> P |] ==> P\"\nby (unfold succ_def, blast)\n\nlemma succ_subset_iff: \"succ(a) \\<subseteq> B \\<longleftrightarrow> (a \\<subseteq> B & a \\<in> B)\"\nby (unfold succ_def, blast)\n\n\nsubsection\\<open>Binary Intersection\\<close>\n\n(** Intersection is the greatest lower bound of two sets **)\n\nlemma Int_subset_iff: \"C \\<subseteq> A \\<inter> B \\<longleftrightarrow> C \\<subseteq> A & C \\<subseteq> B\"\nby blast\n\nlemma Int_lower1: \"A \\<inter> B \\<subseteq> A\"\nby blast\n\nlemma Int_lower2: \"A \\<inter> B \\<subseteq> B\"\nby blast\n\nlemma Int_greatest: \"[| C\\<subseteq>A;  C\\<subseteq>B |] ==> C \\<subseteq> A \\<inter> B\"\nby blast\n\nlemma Int_cons: \"cons(a,B) \\<inter> C \\<subseteq> cons(a, B \\<inter> C)\"\nby blast\n\nlemma Int_absorb [simp]: \"A \\<inter> A = A\"\nby blast\n\nlemma Int_left_absorb: \"A \\<inter> (A \\<inter> B) = A \\<inter> B\"\nby blast\n\nlemma Int_commute: \"A \\<inter> B = B \\<inter> A\"\nby blast\n\nlemma Int_left_commute: \"A \\<inter> (B \\<inter> C) = B \\<inter> (A \\<inter> C)\"\nby blast\n\nlemma Int_assoc: \"(A \\<inter> B) \\<inter> C  =  A \\<inter> (B \\<inter> C)\"\nby blast\n\n(*Intersection is an AC-operator*)\nlemmas Int_ac= Int_assoc Int_left_absorb Int_commute Int_left_commute\n\nlemma Int_absorb1: \"B \\<subseteq> A ==> A \\<inter> B = B\"\n  by blast\n\nlemma Int_absorb2: \"A \\<subseteq> B ==> A \\<inter> B = A\"\n  by blast\n\nlemma Int_Un_distrib: \"A \\<inter> (B \\<union> C) = (A \\<inter> B) \\<union> (A \\<inter> C)\"\nby blast\n\nlemma Int_Un_distrib2: \"(B \\<union> C) \\<inter> A = (B \\<inter> A) \\<union> (C \\<inter> A)\"\nby blast\n\nlemma subset_Int_iff: \"A\\<subseteq>B \\<longleftrightarrow> A \\<inter> B = A\"\nby (blast elim!: equalityE)\n\nlemma subset_Int_iff2: \"A\\<subseteq>B \\<longleftrightarrow> B \\<inter> A = A\"\nby (blast elim!: equalityE)\n\nlemma Int_Diff_eq: \"C\\<subseteq>A ==> (A-B) \\<inter> C = C-B\"\nby blast\n\nlemma Int_cons_left:\n     \"cons(a,A) \\<inter> B = (if a \\<in> B then cons(a, A \\<inter> B) else A \\<inter> B)\"\nby auto\n\nlemma Int_cons_right:\n     \"A \\<inter> cons(a, B) = (if a \\<in> A then cons(a, A \\<inter> B) else A \\<inter> B)\"\nby auto\n\nlemma cons_Int_distrib: \"cons(x, A \\<inter> B) = cons(x, A) \\<inter> cons(x, B)\"\nby auto\n\nsubsection\\<open>Binary Union\\<close>\n\n(** Union is the least upper bound of two sets *)\n\nlemma Un_subset_iff: \"A \\<union> B \\<subseteq> C \\<longleftrightarrow> A \\<subseteq> C & B \\<subseteq> C\"\nby blast\n\nlemma Un_upper1: \"A \\<subseteq> A \\<union> B\"\nby blast\n\nlemma Un_upper2: \"B \\<subseteq> A \\<union> B\"\nby blast\n\nlemma Un_least: \"[| A\\<subseteq>C;  B\\<subseteq>C |] ==> A \\<union> B \\<subseteq> C\"\nby blast\n\nlemma Un_cons: \"cons(a,B) \\<union> C = cons(a, B \\<union> C)\"\nby blast\n\nlemma Un_absorb [simp]: \"A \\<union> A = A\"\nby blast\n\nlemma Un_left_absorb: \"A \\<union> (A \\<union> B) = A \\<union> B\"\nby blast\n\nlemma Un_commute: \"A \\<union> B = B \\<union> A\"\nby blast\n\nlemma Un_left_commute: \"A \\<union> (B \\<union> C) = B \\<union> (A \\<union> C)\"\nby blast\n\nlemma Un_assoc: \"(A \\<union> B) \\<union> C  =  A \\<union> (B \\<union> C)\"\nby blast\n\n(*Union is an AC-operator*)\nlemmas Un_ac = Un_assoc Un_left_absorb Un_commute Un_left_commute\n\nlemma Un_absorb1: \"A \\<subseteq> B ==> A \\<union> B = B\"\n  by blast\n\nlemma Un_absorb2: \"B \\<subseteq> A ==> A \\<union> B = A\"\n  by blast\n\nlemma Un_Int_distrib: \"(A \\<inter> B) \\<union> C  =  (A \\<union> C) \\<inter> (B \\<union> C)\"\nby blast\n\nlemma subset_Un_iff: \"A\\<subseteq>B \\<longleftrightarrow> A \\<union> B = B\"\nby (blast elim!: equalityE)\n\nlemma subset_Un_iff2: \"A\\<subseteq>B \\<longleftrightarrow> B \\<union> A = B\"\nby (blast elim!: equalityE)\n\nlemma Un_empty [iff]: \"(A \\<union> B = 0) \\<longleftrightarrow> (A = 0 & B = 0)\"\nby blast\n\nlemma Un_eq_Union: \"A \\<union> B = \\<Union>({A, B})\"\nby blast\n\nsubsection\\<open>Set Difference\\<close>\n\nlemma Diff_subset: \"A-B \\<subseteq> A\"\nby blast\n\nlemma Diff_contains: \"[| C\\<subseteq>A;  C \\<inter> B = 0 |] ==> C \\<subseteq> A-B\"\nby blast\n\nlemma subset_Diff_cons_iff: \"B \\<subseteq> A - cons(c,C)  \\<longleftrightarrow>  B\\<subseteq>A-C & c \\<notin> B\"\nby blast\n\nlemma Diff_cancel: \"A - A = 0\"\nby blast\n\nlemma Diff_triv: \"A  \\<inter> B = 0 ==> A - B = A\"\nby blast\n\nlemma empty_Diff [simp]: \"0 - A = 0\"\nby blast\n\nlemma Diff_0 [simp]: \"A - 0 = A\"\nby blast\n\nlemma Diff_eq_0_iff: \"A - B = 0 \\<longleftrightarrow> A \\<subseteq> B\"\nby (blast elim: equalityE)\n\n(*NOT SUITABLE FOR REWRITING since {a} == cons(a,0)*)\nlemma Diff_cons: \"A - cons(a,B) = A - B - {a}\"\nby blast\n\n(*NOT SUITABLE FOR REWRITING since {a} == cons(a,0)*)\nlemma Diff_cons2: \"A - cons(a,B) = A - {a} - B\"\nby blast\n\nlemma Diff_disjoint: \"A \\<inter> (B-A) = 0\"\nby blast\n\nlemma Diff_partition: \"A\\<subseteq>B ==> A \\<union> (B-A) = B\"\nby blast\n\nlemma subset_Un_Diff: \"A \\<subseteq> B \\<union> (A - B)\"\nby blast\n\nlemma double_complement: \"[| A\\<subseteq>B; B\\<subseteq>C |] ==> B-(C-A) = A\"\nby blast\n\nlemma double_complement_Un: \"(A \\<union> B) - (B-A) = A\"\nby blast\n\nlemma Un_Int_crazy:\n \"(A \\<inter> B) \\<union> (B \\<inter> C) \\<union> (C \\<inter> A) = (A \\<union> B) \\<inter> (B \\<union> C) \\<inter> (C \\<union> A)\"\napply blast\ndone\n\nlemma Diff_Un: \"A - (B \\<union> C) = (A-B) \\<inter> (A-C)\"\nby blast\n\nlemma Diff_Int: \"A - (B \\<inter> C) = (A-B) \\<union> (A-C)\"\nby blast\n\nlemma Un_Diff: \"(A \\<union> B) - C = (A - C) \\<union> (B - C)\"\nby blast\n\nlemma Int_Diff: \"(A \\<inter> B) - C = A \\<inter> (B - C)\"\nby blast\n\nlemma Diff_Int_distrib: \"C \\<inter> (A-B) = (C \\<inter> A) - (C \\<inter> B)\"\nby blast\n\nlemma Diff_Int_distrib2: \"(A-B) \\<inter> C = (A \\<inter> C) - (B \\<inter> C)\"\nby blast\n\n(*Halmos, Naive Set Theory, page 16.*)\nlemma Un_Int_assoc_iff: \"(A \\<inter> B) \\<union> C = A \\<inter> (B \\<union> C)  \\<longleftrightarrow>  C\\<subseteq>A\"\nby (blast elim!: equalityE)\n\n\nsubsection\\<open>Big Union and Intersection\\<close>\n\n(** Big Union is the least upper bound of a set  **)\n\nlemma Union_subset_iff: \"\\<Union>(A) \\<subseteq> C \\<longleftrightarrow> (\\<forall>x\\<in>A. x \\<subseteq> C)\"\nby blast\n\nlemma Union_upper: \"B\\<in>A ==> B \\<subseteq> \\<Union>(A)\"\nby blast\n\nlemma Union_least: \"[| !!x. x\\<in>A ==> x\\<subseteq>C |] ==> \\<Union>(A) \\<subseteq> C\"\nby blast\n\nlemma Union_cons [simp]: \"\\<Union>(cons(a,B)) = a \\<union> \\<Union>(B)\"\nby blast\n\nlemma Union_Un_distrib: \"\\<Union>(A \\<union> B) = \\<Union>(A) \\<union> \\<Union>(B)\"\nby blast\n\nlemma Union_Int_subset: \"\\<Union>(A \\<inter> B) \\<subseteq> \\<Union>(A) \\<inter> \\<Union>(B)\"\nby blast\n\nlemma Union_disjoint: \"\\<Union>(C) \\<inter> A = 0 \\<longleftrightarrow> (\\<forall>B\\<in>C. B \\<inter> A = 0)\"\nby (blast elim!: equalityE)\n\nlemma Union_empty_iff: \"\\<Union>(A) = 0 \\<longleftrightarrow> (\\<forall>B\\<in>A. B=0)\"\nby blast\n\nlemma Int_Union2: \"\\<Union>(B) \\<inter> A = (\\<Union>C\\<in>B. C \\<inter> A)\"\nby blast\n\n(** Big Intersection is the greatest lower bound of a nonempty set **)\n\nlemma Inter_subset_iff: \"A\\<noteq>0  ==>  C \\<subseteq> \\<Inter>(A) \\<longleftrightarrow> (\\<forall>x\\<in>A. C \\<subseteq> x)\"\nby blast\n\nlemma Inter_lower: \"B\\<in>A ==> \\<Inter>(A) \\<subseteq> B\"\nby blast\n\nlemma Inter_greatest: \"[| A\\<noteq>0;  !!x. x\\<in>A ==> C\\<subseteq>x |] ==> C \\<subseteq> \\<Inter>(A)\"\nby blast\n\n(** Intersection of a family of sets  **)\n\nlemma INT_lower: \"x\\<in>A ==> (\\<Inter>x\\<in>A. B(x)) \\<subseteq> B(x)\"\nby blast\n\nlemma INT_greatest: \"[| A\\<noteq>0;  !!x. x\\<in>A ==> C\\<subseteq>B(x) |] ==> C \\<subseteq> (\\<Inter>x\\<in>A. B(x))\"\nby force\n\nlemma Inter_0 [simp]: \"\\<Inter>(0) = 0\"\nby (unfold Inter_def, blast)\n\nlemma Inter_Un_subset:\n     \"[| z\\<in>A; z\\<in>B |] ==> \\<Inter>(A) \\<union> \\<Inter>(B) \\<subseteq> \\<Inter>(A \\<inter> B)\"\nby blast\n\n(* A good challenge: Inter is ill-behaved on the empty set *)\nlemma Inter_Un_distrib:\n     \"[| A\\<noteq>0;  B\\<noteq>0 |] ==> \\<Inter>(A \\<union> B) = \\<Inter>(A) \\<inter> \\<Inter>(B)\"\nby blast\n\nlemma Union_singleton: \"\\<Union>({b}) = b\"\nby blast\n\nlemma Inter_singleton: \"\\<Inter>({b}) = b\"\nby blast\n\nlemma Inter_cons [simp]:\n     \"\\<Inter>(cons(a,B)) = (if B=0 then a else a \\<inter> \\<Inter>(B))\"\nby force\n\nsubsection\\<open>Unions and Intersections of Families\\<close>\n\nlemma subset_UN_iff_eq: \"A \\<subseteq> (\\<Union>i\\<in>I. B(i)) \\<longleftrightarrow> A = (\\<Union>i\\<in>I. A \\<inter> B(i))\"\nby (blast elim!: equalityE)\n\nlemma UN_subset_iff: \"(\\<Union>x\\<in>A. B(x)) \\<subseteq> C \\<longleftrightarrow> (\\<forall>x\\<in>A. B(x) \\<subseteq> C)\"\nby blast\n\nlemma UN_upper: \"x\\<in>A ==> B(x) \\<subseteq> (\\<Union>x\\<in>A. B(x))\"\nby (erule RepFunI [THEN Union_upper])\n\nlemma UN_least: \"[| !!x. x\\<in>A ==> B(x)\\<subseteq>C |] ==> (\\<Union>x\\<in>A. B(x)) \\<subseteq> C\"\nby blast\n\nlemma Union_eq_UN: \"\\<Union>(A) = (\\<Union>x\\<in>A. x)\"\nby blast\n\nlemma Inter_eq_INT: \"\\<Inter>(A) = (\\<Inter>x\\<in>A. x)\"\nby (unfold Inter_def, blast)\n\nlemma UN_0 [simp]: \"(\\<Union>i\\<in>0. A(i)) = 0\"\nby blast\n\nlemma UN_singleton: \"(\\<Union>x\\<in>A. {x}) = A\"\nby blast\n\nlemma UN_Un: \"(\\<Union>i\\<in> A \\<union> B. C(i)) = (\\<Union>i\\<in> A. C(i)) \\<union> (\\<Union>i\\<in>B. C(i))\"\nby blast\n\nlemma INT_Un: \"(\\<Inter>i\\<in>I \\<union> J. A(i)) =\n               (if I=0 then \\<Inter>j\\<in>J. A(j)\n                       else if J=0 then \\<Inter>i\\<in>I. A(i)\n                       else ((\\<Inter>i\\<in>I. A(i)) \\<inter>  (\\<Inter>j\\<in>J. A(j))))\"\nby (simp, blast intro!: equalityI)\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))\"\nby blast\n\n(*Halmos, Naive Set Theory, page 35.*)\nlemma Int_UN_distrib: \"B \\<inter> (\\<Union>i\\<in>I. A(i)) = (\\<Union>i\\<in>I. B \\<inter> A(i))\"\nby blast\n\nlemma Un_INT_distrib: \"I\\<noteq>0 ==> B \\<union> (\\<Inter>i\\<in>I. A(i)) = (\\<Inter>i\\<in>I. B \\<union> A(i))\"\nby auto\n\nlemma Int_UN_distrib2:\n     \"(\\<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))\"\nby blast\n\nlemma Un_INT_distrib2: \"[| I\\<noteq>0;  J\\<noteq>0 |] ==>\n      (\\<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))\"\nby auto\n\nlemma UN_constant [simp]: \"(\\<Union>y\\<in>A. c) = (if A=0 then 0 else c)\"\nby force\n\nlemma INT_constant [simp]: \"(\\<Inter>y\\<in>A. c) = (if A=0 then 0 else c)\"\nby force\n\nlemma UN_RepFun [simp]: \"(\\<Union>y\\<in> RepFun(A,f). B(y)) = (\\<Union>x\\<in>A. B(f(x)))\"\nby blast\n\nlemma INT_RepFun [simp]: \"(\\<Inter>x\\<in>RepFun(A,f). B(x))    = (\\<Inter>a\\<in>A. B(f(a)))\"\nby (auto simp add: Inter_def)\n\nlemma INT_Union_eq:\n     \"0 \\<notin> A ==> (\\<Inter>x\\<in> \\<Union>(A). B(x)) = (\\<Inter>y\\<in>A. \\<Inter>x\\<in>y. B(x))\"\napply (subgoal_tac \"\\<forall>x\\<in>A. x\\<noteq>0\")\n prefer 2 apply blast\napply (force simp add: Inter_def ball_conj_distrib)\ndone\n\nlemma INT_UN_eq:\n     \"(\\<forall>x\\<in>A. B(x) \\<noteq> 0)\n      ==> (\\<Inter>z\\<in> (\\<Union>x\\<in>A. B(x)). C(z)) = (\\<Inter>x\\<in>A. \\<Inter>z\\<in> B(x). C(z))\"\napply (subst INT_Union_eq, blast)\napply (simp add: Inter_def)\ndone\n\n\n(** Devlin, Fundamentals of Contemporary Set Theory, page 12, exercise 5:\n    Union of a family of unions **)\n\nlemma UN_Un_distrib:\n     \"(\\<Union>i\\<in>I. A(i) \\<union> B(i)) = (\\<Union>i\\<in>I. A(i))  \\<union>  (\\<Union>i\\<in>I. B(i))\"\nby blast\n\nlemma INT_Int_distrib:\n     \"I\\<noteq>0 ==> (\\<Inter>i\\<in>I. A(i) \\<inter> B(i)) = (\\<Inter>i\\<in>I. A(i)) \\<inter> (\\<Inter>i\\<in>I. B(i))\"\nby (blast elim!: not_emptyE)\n\nlemma UN_Int_subset:\n     \"(\\<Union>z\\<in>I \\<inter> J. A(z)) \\<subseteq> (\\<Union>z\\<in>I. A(z)) \\<inter> (\\<Union>z\\<in>J. A(z))\"\nby blast\n\n(** Devlin, page 12, exercise 5: Complements **)\n\nlemma Diff_UN: \"I\\<noteq>0 ==> B - (\\<Union>i\\<in>I. A(i)) = (\\<Inter>i\\<in>I. B - A(i))\"\nby (blast elim!: not_emptyE)\n\nlemma Diff_INT: \"I\\<noteq>0 ==> B - (\\<Inter>i\\<in>I. A(i)) = (\\<Union>i\\<in>I. B - A(i))\"\nby (blast elim!: not_emptyE)\n\n\n(** Unions and Intersections with General Sum **)\n\n(*Not suitable for rewriting: LOOPS!*)\nlemma Sigma_cons1: \"Sigma(cons(a,B), C) = ({a}*C(a)) \\<union> Sigma(B,C)\"\nby blast\n\n(*Not suitable for rewriting: LOOPS!*)\nlemma Sigma_cons2: \"A * cons(b,B) = A*{b} \\<union> A*B\"\nby blast\n\nlemma Sigma_succ1: \"Sigma(succ(A), B) = ({A}*B(A)) \\<union> Sigma(A,B)\"\nby blast\n\nlemma Sigma_succ2: \"A * succ(B) = A*{B} \\<union> A*B\"\nby blast\n\nlemma SUM_UN_distrib1:\n     \"(\\<Sum>x \\<in> (\\<Union>y\\<in>A. C(y)). B(x)) = (\\<Union>y\\<in>A. \\<Sum>x\\<in>C(y). B(x))\"\nby blast\n\nlemma SUM_UN_distrib2:\n     \"(\\<Sum>i\\<in>I. \\<Union>j\\<in>J. C(i,j)) = (\\<Union>j\\<in>J. \\<Sum>i\\<in>I. C(i,j))\"\nby blast\n\nlemma SUM_Un_distrib1:\n     \"(\\<Sum>i\\<in>I \\<union> J. C(i)) = (\\<Sum>i\\<in>I. C(i)) \\<union> (\\<Sum>j\\<in>J. C(j))\"\nby blast\n\nlemma SUM_Un_distrib2:\n     \"(\\<Sum>i\\<in>I. A(i) \\<union> B(i)) = (\\<Sum>i\\<in>I. A(i)) \\<union> (\\<Sum>i\\<in>I. B(i))\"\nby blast\n\n(*First-order version of the above, for rewriting*)\nlemma prod_Un_distrib2: \"I * (A \\<union> B) = I*A \\<union> I*B\"\nby (rule SUM_Un_distrib2)\n\nlemma SUM_Int_distrib1:\n     \"(\\<Sum>i\\<in>I \\<inter> J. C(i)) = (\\<Sum>i\\<in>I. C(i)) \\<inter> (\\<Sum>j\\<in>J. C(j))\"\nby blast\n\nlemma SUM_Int_distrib2:\n     \"(\\<Sum>i\\<in>I. A(i) \\<inter> B(i)) = (\\<Sum>i\\<in>I. A(i)) \\<inter> (\\<Sum>i\\<in>I. B(i))\"\nby blast\n\n(*First-order version of the above, for rewriting*)\nlemma prod_Int_distrib2: \"I * (A \\<inter> B) = I*A \\<inter> I*B\"\nby (rule SUM_Int_distrib2)\n\n(*Cf Aczel, Non-Well-Founded Sets, page 115*)\nlemma SUM_eq_UN: \"(\\<Sum>i\\<in>I. A(i)) = (\\<Union>i\\<in>I. {i} * A(i))\"\nby blast\n\nlemma times_subset_iff:\n     \"(A'*B' \\<subseteq> A*B) \\<longleftrightarrow> (A' = 0 | B' = 0 | (A'\\<subseteq>A) & (B'\\<subseteq>B))\"\nby blast\n\nlemma Int_Sigma_eq:\n     \"(\\<Sum>x \\<in> A'. B'(x)) \\<inter> (\\<Sum>x \\<in> A. B(x)) = (\\<Sum>x \\<in> A' \\<inter> A. B'(x) \\<inter> B(x))\"\nby blast\n\n(** Domain **)\n\nlemma domain_iff: \"a: domain(r) \\<longleftrightarrow> (\\<exists>y. <a,y>\\<in> r)\"\nby (unfold domain_def, blast)\n\nlemma domainI [intro]: \"<a,b>\\<in> r ==> a: domain(r)\"\nby (unfold domain_def, blast)\n\nlemma domainE [elim!]:\n    \"[| a \\<in> domain(r);  !!y. <a,y>\\<in> r ==> P |] ==> P\"\nby (unfold domain_def, blast)\n\nlemma domain_subset: \"domain(Sigma(A,B)) \\<subseteq> A\"\nby blast\n\nlemma domain_of_prod: \"b\\<in>B ==> domain(A*B) = A\"\nby blast\n\nlemma domain_0 [simp]: \"domain(0) = 0\"\nby blast\n\nlemma domain_cons [simp]: \"domain(cons(<a,b>,r)) = cons(a, domain(r))\"\nby blast\n\nlemma domain_Un_eq [simp]: \"domain(A \\<union> B) = domain(A) \\<union> domain(B)\"\nby blast\n\nlemma domain_Int_subset: \"domain(A \\<inter> B) \\<subseteq> domain(A) \\<inter> domain(B)\"\nby blast\n\nlemma domain_Diff_subset: \"domain(A) - domain(B) \\<subseteq> domain(A - B)\"\nby blast\n\nlemma domain_UN: \"domain(\\<Union>x\\<in>A. B(x)) = (\\<Union>x\\<in>A. domain(B(x)))\"\nby blast\n\nlemma domain_Union: \"domain(\\<Union>(A)) = (\\<Union>x\\<in>A. domain(x))\"\nby blast\n\n\n(** Range **)\n\nlemma rangeI [intro]: \"<a,b>\\<in> r ==> b \\<in> range(r)\"\napply (unfold range_def)\napply (erule converseI [THEN domainI])\ndone\n\nlemma rangeE [elim!]: \"[| b \\<in> range(r);  !!x. <x,b>\\<in> r ==> P |] ==> P\"\nby (unfold range_def, blast)\n\nlemma range_subset: \"range(A*B) \\<subseteq> B\"\napply (unfold range_def)\napply (subst converse_prod)\napply (rule domain_subset)\ndone\n\nlemma range_of_prod: \"a\\<in>A ==> range(A*B) = B\"\nby blast\n\nlemma range_0 [simp]: \"range(0) = 0\"\nby blast\n\nlemma range_cons [simp]: \"range(cons(<a,b>,r)) = cons(b, range(r))\"\nby blast\n\nlemma range_Un_eq [simp]: \"range(A \\<union> B) = range(A) \\<union> range(B)\"\nby blast\n\nlemma range_Int_subset: \"range(A \\<inter> B) \\<subseteq> range(A) \\<inter> range(B)\"\nby blast\n\nlemma range_Diff_subset: \"range(A) - range(B) \\<subseteq> range(A - B)\"\nby blast\n\nlemma domain_converse [simp]: \"domain(converse(r)) = range(r)\"\nby blast\n\nlemma range_converse [simp]: \"range(converse(r)) = domain(r)\"\nby blast\n\n\n(** Field **)\n\nlemma fieldI1: \"<a,b>\\<in> r ==> a \\<in> field(r)\"\nby (unfold field_def, blast)\n\nlemma fieldI2: \"<a,b>\\<in> r ==> b \\<in> field(r)\"\nby (unfold field_def, blast)\n\nlemma fieldCI [intro]:\n    \"(~ <c,a>\\<in>r ==> <a,b>\\<in> r) ==> a \\<in> field(r)\"\napply (unfold field_def, blast)\ndone\n\nlemma fieldE [elim!]:\n     \"[| a \\<in> field(r);\n         !!x. <a,x>\\<in> r ==> P;\n         !!x. <x,a>\\<in> r ==> P        |] ==> P\"\nby (unfold field_def, blast)\n\nlemma field_subset: \"field(A*B) \\<subseteq> A \\<union> B\"\nby blast\n\nlemma domain_subset_field: \"domain(r) \\<subseteq> field(r)\"\napply (unfold field_def)\napply (rule Un_upper1)\ndone\n\nlemma range_subset_field: \"range(r) \\<subseteq> field(r)\"\napply (unfold field_def)\napply (rule Un_upper2)\ndone\n\nlemma domain_times_range: \"r \\<subseteq> Sigma(A,B) ==> r \\<subseteq> domain(r)*range(r)\"\nby blast\n\nlemma field_times_field: \"r \\<subseteq> Sigma(A,B) ==> r \\<subseteq> field(r)*field(r)\"\nby blast\n\nlemma relation_field_times_field: \"relation(r) ==> r \\<subseteq> field(r)*field(r)\"\nby (simp add: relation_def, blast)\n\nlemma field_of_prod: \"field(A*A) = A\"\nby blast\n\nlemma field_0 [simp]: \"field(0) = 0\"\nby blast\n\nlemma field_cons [simp]: \"field(cons(<a,b>,r)) = cons(a, cons(b, field(r)))\"\nby blast\n\nlemma field_Un_eq [simp]: \"field(A \\<union> B) = field(A) \\<union> field(B)\"\nby blast\n\nlemma field_Int_subset: \"field(A \\<inter> B) \\<subseteq> field(A) \\<inter> field(B)\"\nby blast\n\nlemma field_Diff_subset: \"field(A) - field(B) \\<subseteq> field(A - B)\"\nby blast\n\nlemma field_converse [simp]: \"field(converse(r)) = field(r)\"\nby blast\n\n(** The Union of a set of relations is a relation -- Lemma for fun_Union **)\nlemma rel_Union: \"(\\<forall>x\\<in>S. \\<exists>A B. x \\<subseteq> A*B) ==>\n                  \\<Union>(S) \\<subseteq> domain(\\<Union>(S)) * range(\\<Union>(S))\"\nby blast\n\n(** The Union of 2 relations is a relation (Lemma for fun_Un)  **)\nlemma rel_Un: \"[| r \\<subseteq> A*B;  s \\<subseteq> C*D |] ==> (r \\<union> s) \\<subseteq> (A \\<union> C) * (B \\<union> D)\"\nby blast\n\nlemma domain_Diff_eq: \"[| <a,c> \\<in> r; c\\<noteq>b |] ==> domain(r-{<a,b>}) = domain(r)\"\nby blast\n\nlemma range_Diff_eq: \"[| <c,b> \\<in> r; c\\<noteq>a |] ==> range(r-{<a,b>}) = range(r)\"\nby blast\n\n\nsubsection\\<open>Image of a Set under a Function or Relation\\<close>\n\nlemma image_iff: \"b \\<in> r``A \\<longleftrightarrow> (\\<exists>x\\<in>A. <x,b>\\<in>r)\"\nby (unfold image_def, blast)\n\nlemma image_singleton_iff: \"b \\<in> r``{a} \\<longleftrightarrow> <a,b>\\<in>r\"\nby (rule image_iff [THEN iff_trans], blast)\n\nlemma imageI [intro]: \"[| <a,b>\\<in> r;  a\\<in>A |] ==> b \\<in> r``A\"\nby (unfold image_def, blast)\n\nlemma imageE [elim!]:\n    \"[| b: r``A;  !!x.[| <x,b>\\<in> r;  x\\<in>A |] ==> P |] ==> P\"\nby (unfold image_def, blast)\n\nlemma image_subset: \"r \\<subseteq> A*B ==> r``C \\<subseteq> B\"\nby blast\n\nlemma image_0 [simp]: \"r``0 = 0\"\nby blast\n\nlemma image_Un [simp]: \"r``(A \\<union> B) = (r``A) \\<union> (r``B)\"\nby blast\n\nlemma image_UN: \"r `` (\\<Union>x\\<in>A. B(x)) = (\\<Union>x\\<in>A. r `` B(x))\"\nby blast\n\nlemma Collect_image_eq:\n     \"{z \\<in> Sigma(A,B). P(z)} `` C = (\\<Union>x \\<in> A. {y \\<in> B(x). x \\<in> C & P(<x,y>)})\"\nby blast\n\nlemma image_Int_subset: \"r``(A \\<inter> B) \\<subseteq> (r``A) \\<inter> (r``B)\"\nby blast\n\nlemma image_Int_square_subset: \"(r \\<inter> A*A)``B \\<subseteq> (r``B) \\<inter> A\"\nby blast\n\nlemma image_Int_square: \"B\\<subseteq>A ==> (r \\<inter> A*A)``B = (r``B) \\<inter> A\"\nby blast\n\n\n(*Image laws for special relations*)\nlemma image_0_left [simp]: \"0``A = 0\"\nby blast\n\nlemma image_Un_left: \"(r \\<union> s)``A = (r``A) \\<union> (s``A)\"\nby blast\n\nlemma image_Int_subset_left: \"(r \\<inter> s)``A \\<subseteq> (r``A) \\<inter> (s``A)\"\nby blast\n\n\nsubsection\\<open>Inverse Image of a Set under a Function or Relation\\<close>\n\nlemma vimage_iff:\n    \"a \\<in> r-``B \\<longleftrightarrow> (\\<exists>y\\<in>B. <a,y>\\<in>r)\"\nby (unfold vimage_def image_def converse_def, blast)\n\nlemma vimage_singleton_iff: \"a \\<in> r-``{b} \\<longleftrightarrow> <a,b>\\<in>r\"\nby (rule vimage_iff [THEN iff_trans], blast)\n\nlemma vimageI [intro]: \"[| <a,b>\\<in> r;  b\\<in>B |] ==> a \\<in> r-``B\"\nby (unfold vimage_def, blast)\n\nlemma vimageE [elim!]:\n    \"[| a: r-``B;  !!x.[| <a,x>\\<in> r;  x\\<in>B |] ==> P |] ==> P\"\napply (unfold vimage_def, blast)\ndone\n\nlemma vimage_subset: \"r \\<subseteq> A*B ==> r-``C \\<subseteq> A\"\napply (unfold vimage_def)\napply (erule converse_type [THEN image_subset])\ndone\n\nlemma vimage_0 [simp]: \"r-``0 = 0\"\nby blast\n\nlemma vimage_Un [simp]: \"r-``(A \\<union> B) = (r-``A) \\<union> (r-``B)\"\nby blast\n\nlemma vimage_Int_subset: \"r-``(A \\<inter> B) \\<subseteq> (r-``A) \\<inter> (r-``B)\"\nby blast\n\n(*NOT suitable for rewriting*)\nlemma vimage_eq_UN: \"f -``B = (\\<Union>y\\<in>B. f-``{y})\"\nby blast\n\nlemma function_vimage_Int:\n     \"function(f) ==> f-``(A \\<inter> B) = (f-``A)  \\<inter>  (f-``B)\"\nby (unfold function_def, blast)\n\nlemma function_vimage_Diff: \"function(f) ==> f-``(A-B) = (f-``A) - (f-``B)\"\nby (unfold function_def, blast)\n\nlemma function_image_vimage: \"function(f) ==> f `` (f-`` A) \\<subseteq> A\"\nby (unfold function_def, blast)\n\nlemma vimage_Int_square_subset: \"(r \\<inter> A*A)-``B \\<subseteq> (r-``B) \\<inter> A\"\nby blast\n\nlemma vimage_Int_square: \"B\\<subseteq>A ==> (r \\<inter> A*A)-``B = (r-``B) \\<inter> A\"\nby blast\n\n\n\n(*Invese image laws for special relations*)\nlemma vimage_0_left [simp]: \"0-``A = 0\"\nby blast\n\nlemma vimage_Un_left: \"(r \\<union> s)-``A = (r-``A) \\<union> (s-``A)\"\nby blast\n\nlemma vimage_Int_subset_left: \"(r \\<inter> s)-``A \\<subseteq> (r-``A) \\<inter> (s-``A)\"\nby blast\n\n\n(** Converse **)\n\nlemma converse_Un [simp]: \"converse(A \\<union> B) = converse(A) \\<union> converse(B)\"\nby blast\n\nlemma converse_Int [simp]: \"converse(A \\<inter> B) = converse(A) \\<inter> converse(B)\"\nby blast\n\nlemma converse_Diff [simp]: \"converse(A - B) = converse(A) - converse(B)\"\nby blast\n\nlemma converse_UN [simp]: \"converse(\\<Union>x\\<in>A. B(x)) = (\\<Union>x\\<in>A. converse(B(x)))\"\nby blast\n\n(*Unfolding Inter avoids using excluded middle on A=0*)\nlemma converse_INT [simp]:\n     \"converse(\\<Inter>x\\<in>A. B(x)) = (\\<Inter>x\\<in>A. converse(B(x)))\"\napply (unfold Inter_def, blast)\ndone\n\n\nsubsection\\<open>Powerset Operator\\<close>\n\nlemma Pow_0 [simp]: \"Pow(0) = {0}\"\nby blast\n\nlemma Pow_insert: \"Pow (cons(a,A)) = Pow(A) \\<union> {cons(a,X) . X: Pow(A)}\"\napply (rule equalityI, safe)\napply (erule swap)\napply (rule_tac a = \"x-{a}\" in RepFun_eqI, auto)\ndone\n\nlemma Un_Pow_subset: \"Pow(A) \\<union> Pow(B) \\<subseteq> Pow(A \\<union> B)\"\nby blast\n\nlemma UN_Pow_subset: \"(\\<Union>x\\<in>A. Pow(B(x))) \\<subseteq> Pow(\\<Union>x\\<in>A. B(x))\"\nby blast\n\nlemma subset_Pow_Union: \"A \\<subseteq> Pow(\\<Union>(A))\"\nby blast\n\nlemma Union_Pow_eq [simp]: \"\\<Union>(Pow(A)) = A\"\nby blast\n\nlemma Union_Pow_iff: \"\\<Union>(A) \\<in> Pow(B) \\<longleftrightarrow> A \\<in> Pow(Pow(B))\"\nby blast\n\nlemma Pow_Int_eq [simp]: \"Pow(A \\<inter> B) = Pow(A) \\<inter> Pow(B)\"\nby blast\n\nlemma Pow_INT_eq: \"A\\<noteq>0 ==> Pow(\\<Inter>x\\<in>A. B(x)) = (\\<Inter>x\\<in>A. Pow(B(x)))\"\nby (blast elim!: not_emptyE)\n\n\nsubsection\\<open>RepFun\\<close>\n\nlemma RepFun_subset: \"[| !!x. x\\<in>A ==> f(x) \\<in> B |] ==> {f(x). x\\<in>A} \\<subseteq> B\"\nby blast\n\nlemma RepFun_eq_0_iff [simp]: \"{f(x).x\\<in>A}=0 \\<longleftrightarrow> A=0\"\nby blast\n\nlemma RepFun_constant [simp]: \"{c. x\\<in>A} = (if A=0 then 0 else {c})\"\nby force\n\n\nsubsection\\<open>Collect\\<close>\n\nlemma Collect_subset: \"Collect(A,P) \\<subseteq> A\"\nby blast\n\nlemma Collect_Un: \"Collect(A \\<union> B, P) = Collect(A,P) \\<union> Collect(B,P)\"\nby blast\n\nlemma Collect_Int: \"Collect(A \\<inter> B, P) = Collect(A,P) \\<inter> Collect(B,P)\"\nby blast\n\nlemma Collect_Diff: \"Collect(A - B, P) = Collect(A,P) - Collect(B,P)\"\nby blast\n\nlemma Collect_cons: \"{x\\<in>cons(a,B). P(x)} =\n      (if P(a) then cons(a, {x\\<in>B. P(x)}) else {x\\<in>B. P(x)})\"\nby (simp, blast)\n\nlemma Int_Collect_self_eq: \"A \\<inter> Collect(A,P) = Collect(A,P)\"\nby blast\n\nlemma Collect_Collect_eq [simp]:\n     \"Collect(Collect(A,P), Q) = Collect(A, %x. P(x) & Q(x))\"\nby blast\n\nlemma Collect_Int_Collect_eq:\n     \"Collect(A,P) \\<inter> Collect(A,Q) = Collect(A, %x. P(x) & Q(x))\"\nby blast\n\nlemma Collect_Union_eq [simp]:\n     \"Collect(\\<Union>x\\<in>A. B(x), P) = (\\<Union>x\\<in>A. Collect(B(x), P))\"\nby blast\n\nlemma Collect_Int_left: \"{x\\<in>A. P(x)} \\<inter> B = {x \\<in> A \\<inter> B. P(x)}\"\nby blast\n\nlemma Collect_Int_right: \"A \\<inter> {x\\<in>B. P(x)} = {x \\<in> A \\<inter> B. P(x)}\"\nby blast\n\nlemma Collect_disj_eq: \"{x\\<in>A. P(x) | Q(x)} = Collect(A, P) \\<union> Collect(A, Q)\"\nby blast\n\nlemma Collect_conj_eq: \"{x\\<in>A. P(x) & Q(x)} = Collect(A, P) \\<inter> Collect(A, Q)\"\nby blast\n\nlemmas subset_SIs = subset_refl cons_subsetI subset_consI\n                    Union_least UN_least Un_least\n                    Inter_greatest Int_greatest RepFun_subset\n                    Un_upper1 Un_upper2 Int_lower1 Int_lower2\n\nML \\<open>\nval subset_cs =\n  claset_of (@{context}\n    delrules [@{thm subsetI}, @{thm subsetCE}]\n    addSIs @{thms subset_SIs}\n    addIs  [@{thm Union_upper}, @{thm Inter_lower}]\n    addSEs [@{thm cons_subsetE}]);\n\nval ZF_cs = claset_of (@{context} delrules [@{thm equalityI}]);\n\\<close>\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/ZF/equalities.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8652240825770433, "lm_q2_score": 0.8418256412990658, "lm_q1q2_score": 0.7283678181828154}}
{"text": "section \\<open> thy \\<close>\n\ntheory Poset\nimports Main Function\n\nbegin\n\n(* Poset type *)\n\nrecord 'a Poset =\n  el :: \"'a set\"\n  le_rel :: \"('a \\<times> 'a) set\"\n\ndefinition \"Poset_le_undefined_arg_not_in_domain a a' \\<equiv> undefined\"\n\nabbreviation le :: \"'a Poset \\<Rightarrow> ('a \\<Rightarrow> 'a \\<Rightarrow> bool)\" where\n\"le P a a' \\<equiv>\n  if a \\<in> el P \\<and> a' \\<in> el P\n  then (a, a') \\<in> le_rel P\n  else Poset_le_undefined_arg_not_in_domain a a'\"\n\n(*\nabbreviation le_P :: \"'a \\<Rightarrow> 'a Poset \\<Rightarrow> 'a \\<Rightarrow> bool\" (\"_ \\<sqsubseteq>\\<langle>_\\<rangle> _\") where\n\"le_P a P a' \\<equiv> (a, a') \\<in> le_rel P\"\n*)\n\ndefinition valid :: \"'a Poset \\<Rightarrow> bool\" where\n  \"valid P \\<equiv>\n    let\n      welldefined = \\<forall>x y. (x,y) \\<in> le_rel P \\<longrightarrow> x \\<in> el P \\<and> y \\<in> el P;\n      reflexivity = \\<forall>x. x \\<in> el P \\<longrightarrow> (x,x) \\<in> le_rel P;\n      antisymmetry = \\<forall>x y. x \\<in> el P \\<longrightarrow> y \\<in> el P  \\<longrightarrow>  (x,y) \\<in> le_rel P \\<longrightarrow> (y,x) \\<in> le_rel P  \\<longrightarrow> x = y;\n      transitivity = \\<forall>x y z. x \\<in> el P \\<longrightarrow> y \\<in> el P \\<longrightarrow> z \\<in> el P \\<longrightarrow> (x,y) \\<in> le_rel P \\<longrightarrow> (y,z) \\<in> le_rel P\\<longrightarrow> (x,z) \\<in> le_rel P\n    in\n      welldefined \\<and> reflexivity \\<and> antisymmetry \\<and> transitivity\"\n\n(* PosetMap type (monotone function *)\n\nrecord ('a, 'b) PosetMap =\n  dom :: \"'a Poset\"\n  cod :: \"'b Poset\"\n  func ::\"('a \\<times>'b) set\"\n\ndefinition \"Poset_app_undefined_arg_not_in_domain a \\<equiv> undefined\"\n\n(* Map application *)\n\ndefinition app :: \"('a, 'b) PosetMap \\<Rightarrow> 'a \\<Rightarrow> 'b\" (infixr \"\\<star>\" 997) where\n\"app f a \\<equiv>\n  if a \\<in> el (dom f)\n  then (THE b. (a, b) \\<in> func f)\n  else Poset_app_undefined_arg_not_in_domain a\"\n\ndefinition valid_map :: \"('a, 'b) PosetMap \\<Rightarrow> bool\" where\n\"valid_map f \\<equiv>\n  let\n      le_dom = le (dom f);\n      le_cod = le (cod f);\n      e_dom = el (dom f);\n      e_cod = el (cod f);\n      welldefined = valid (dom f) \\<and> valid (cod f) \\<and> (\\<forall>a b. (a, b) \\<in> func f \\<longrightarrow> a \\<in> e_dom \\<and> b \\<in> e_cod);\n      deterministic = (\\<forall>a b b'. (a, b) \\<in> func f \\<and> (a, b') \\<in> func f \\<longrightarrow> b = b');\n      total = (\\<forall>a. a \\<in> e_dom \\<longrightarrow> (\\<exists>b. (a, b) \\<in> func f));\n      monotone = (\\<forall>a a'. a \\<in> e_dom \\<and> a' \\<in> e_dom \\<and> le_dom a a' \\<longrightarrow> le_cod (f \\<star> a) (f \\<star> a'))\n\n  in welldefined \\<and> deterministic \\<and> total \\<and> monotone\"\n\n(* Validity *)\n\nlemma validI [intro]:\n  fixes P :: \"'a Poset\"\n  assumes welldefined : \"(\\<And>x y. (x,y) \\<in> le_rel P \\<Longrightarrow> x \\<in> el P \\<and> y \\<in> el P)\"\n  and reflexivity : \"(\\<And>x. x \\<in> el P \\<Longrightarrow> le P x x)\"\n  and antisymmetry : \"(\\<And>x y. x \\<in> el P \\<Longrightarrow> y \\<in> el P \\<Longrightarrow>  le P x y \\<Longrightarrow> le P y x \\<Longrightarrow> x = y)\"\n  and transitivity : \"(\\<And>x y z. x \\<in> el P \\<Longrightarrow> y \\<in> el P \\<Longrightarrow> z \\<in> el P \\<Longrightarrow> le P x y \\<Longrightarrow> le P y z \\<Longrightarrow> le P x z)\"\n    shows \"valid P\"\n  by (smt (verit, best) antisymmetry reflexivity transitivity valid_def welldefined)\n\nlemma valid_welldefined : \"valid P \\<Longrightarrow> (x,y) \\<in> le_rel P \\<Longrightarrow> x \\<in> el P \\<and> y \\<in> el P\"\n  by (smt (verit) valid_def)\n\nlemma valid_reflexivity : \"valid P \\<Longrightarrow> x \\<in> el P \\<Longrightarrow> le P x x\"\n  by (smt (verit) valid_def)\n\nlemma valid_transitivity : \"valid P \\<Longrightarrow> x \\<in> el P \\<Longrightarrow> y \\<in> el P \\<Longrightarrow> z \\<in> el P \\<Longrightarrow> le P x y \\<Longrightarrow> le P y z \\<Longrightarrow> le P x z\"\n  by (smt (verit, ccfv_threshold) valid_def)\n\nlemma valid_antisymmetry : \"valid P \\<Longrightarrow> x \\<in> el P\\<Longrightarrow> y \\<in> el P\\<Longrightarrow> le P x y \\<Longrightarrow> le P y x \\<Longrightarrow> x = y\"\n  by (smt (verit, ccfv_threshold) valid_def)\n\n\nlemma valid_mapI [intro] : \"valid (dom f) \\<Longrightarrow> valid (cod f)  \\<Longrightarrow> (\\<And>a b. (a, b) \\<in> func f \\<Longrightarrow>  a \\<in> el (dom f) \\<and> b \\<in> el (cod f)) \\<Longrightarrow>\n                   (\\<And>a b b'. (a, b) \\<in> func f \\<Longrightarrow> (a, b') \\<in> func f \\<Longrightarrow> b = b') \\<Longrightarrow>\n                   (\\<And>a. a \\<in> el (dom f) \\<Longrightarrow> (\\<exists>b. (a, b) \\<in> func f)) \\<Longrightarrow>\n                   (\\<And>a a'. a \\<in> el (dom f) \\<Longrightarrow> a' \\<in> el (dom f) \\<Longrightarrow> le (dom f) a a' \\<Longrightarrow> le (cod f) (f \\<star> a) (f \\<star> a'))\n  \\<Longrightarrow> valid_map f \" unfolding valid_map_def\n  by auto\n\nlemma valid_map_welldefined_dom : \"valid_map f \\<Longrightarrow> valid (dom f)\"\n  apply (subst (asm) valid_map_def)\n  by (clarsimp simp: Let_unfold)\n\nlemma valid_map_welldefined_cod : \"valid_map f \\<Longrightarrow> valid (cod f)\"\n  apply (subst (asm) valid_map_def)\n  by (clarsimp simp: Let_unfold)\n\nlemma valid_map_welldefined_func : \"valid_map f \\<Longrightarrow> (a, b) \\<in> func f \\<Longrightarrow> a \\<in> el (dom f) \\<and> b \\<in> el (cod f)\"\n  unfolding valid_map_def\n  by (simp add: Let_def)\n\nlemma valid_map_welldefined : \"valid_map f \\<Longrightarrow> valid (dom f) \\<and> valid (cod f) \\<and> (\\<forall>a b. (a, b) \\<in> func f \\<longrightarrow> a \\<in>\n el (dom f) \\<and> b \\<in> el (cod f))\"\n  by (simp add: valid_map_welldefined_cod valid_map_welldefined_dom valid_map_welldefined_func)\n\nlemma valid_map_dom: \"valid_map f \\<Longrightarrow> (a, b) \\<in> func f \\<Longrightarrow> a \\<in> el (dom f)\"\n  by (meson valid_map_welldefined)\n\nlemma valid_map_cod: \"valid_map f \\<Longrightarrow> (a, b) \\<in> func f \\<Longrightarrow> b \\<in> el (cod f)\"\n  by (meson valid_map_welldefined)\n\nlemma valid_map_deterministic : \"valid_map f \\<Longrightarrow> (a, b) \\<in> func f \\<Longrightarrow> (a, b') \\<in> func f \\<Longrightarrow> b = b'\"\n  unfolding valid_map_def\n  by (simp add: Let_def)\n\nlemma valid_map_total : \"valid_map f \\<Longrightarrow> a \\<in> el (dom f) \\<Longrightarrow> \\<exists>b. (a, b) \\<in> func f\"\n  unfolding valid_map_def\n  by (simp add: Let_def)\n\nlemma valid_map_monotone : \"valid_map f \\<Longrightarrow> a \\<in> el (dom f) \\<Longrightarrow> a' \\<in> el (dom f) \\<Longrightarrow> le (dom f) a a' \\<Longrightarrow> le (cod f) (f \\<star> a) (f \\<star> a')\"\nunfolding valid_map_def\n  by metis\n\nlemma valid_map_eqI: \"cod f = cod g \\<Longrightarrow> dom f = dom g \\<Longrightarrow> func f = func g \\<Longrightarrow> (f :: ('a, 'b) PosetMap) = g\"\n  by simp\n\n(* Map application *)\n\nlemma fun_app : \"valid_map f \\<Longrightarrow> a \\<in> el (dom f) \\<Longrightarrow> (a, f \\<star> a) \\<in> func f\"\n  by (metis app_def the_equality valid_map_deterministic valid_map_total)\n\nlemma fun_app2 : \"valid_map f \\<Longrightarrow> a \\<in> el (dom f) \\<Longrightarrow> f \\<star> a \\<in> el (cod f)\"\n  by (meson fun_app valid_map_welldefined)\n\nlemma fun_app3 [simp] : \"valid_map f \\<Longrightarrow> a \\<in> el (dom f) \\<Longrightarrow> f \\<star> a = (THE b. (a, b) \\<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>a. a \\<in> el (dom f) \\<Longrightarrow> f \\<star> a = g \\<star> a) \\<Longrightarrow> func f = func g\"\n  by (metis Poset.fun_app pred_equals_eq2 valid_map_deterministic valid_map_welldefined_func)\n\nlemma fun_ext : \"valid_map f \\<Longrightarrow> valid_map g \\<Longrightarrow> dom f = dom g \\<Longrightarrow> cod f = cod g \\<Longrightarrow> (\\<And> a . a \\<in> el (dom f) \\<Longrightarrow> f \\<star> a = g \\<star> a) \\<Longrightarrow> f = g\"\n  by (meson Poset.fun_ext_raw valid_map_eqI)\n\nlemma fun_app_iff  : \"valid_map f \\<Longrightarrow> (a, b) \\<in> func f \\<Longrightarrow> (f \\<star> a) = b\"\n  by (meson fun_app valid_map_deterministic valid_map_welldefined)\n\n(* Map composition *)\n\ndefinition \"Poset_compose_undefined_incomposable g f \\<equiv> undefined\"\n\ndefinition compose :: \"('b, 'c) PosetMap \\<Rightarrow> ('a, 'b) PosetMap \\<Rightarrow> ('a, 'c) PosetMap\" (infixl \"\\<diamondop>\" 55) where\n  \"compose g f \\<equiv>\n  if dom g = cod f\n  then \\<lparr> dom = dom f, cod = cod g, func = relcomp (func f) (func g) \\<rparr>\n  else Poset_compose_undefined_incomposable g f\"\n\nlemma compose_welldefined_cod : \"valid_map g \\<Longrightarrow> valid_map f \\<Longrightarrow> dom g = cod f \\<Longrightarrow> (a, b) \\<in> func (g \\<diamondop> f) \\<Longrightarrow> b \\<in> el (cod g)\"\n  unfolding compose_def\n  using Poset.valid_map_welldefined by auto               \n\nlemma compose_welldefined_dom : \"valid_map g \\<Longrightarrow> valid_map f \\<Longrightarrow> dom g = cod f \\<Longrightarrow> (a, b) \\<in> func (g \\<diamondop> f) \\<Longrightarrow> a \\<in> el (dom f)\"\n  unfolding compose_def\n  using Poset.valid_map_welldefined by auto               \n\nlemma compose_welldefined : \"valid_map f \\<Longrightarrow> valid_map g \\<Longrightarrow> dom g = cod f \\<Longrightarrow> (a, b) \\<in> func (g \\<diamondop> f) \\<Longrightarrow> a \\<in> el (dom f) \\<and> b \\<in> el (cod g)\"\n  by (metis Poset.valid_map_welldefined PosetMap.select_convs(3) compose_def relcomp.cases)\n\nlemma compose_deterministic : \"valid_map f \\<Longrightarrow> valid_map g \\<Longrightarrow> dom g = cod f \\<Longrightarrow> (a, b) \\<in> func (g \\<diamondop> f) \\<Longrightarrow> (a, b') \\<in> func (g \\<diamondop> f) \\<Longrightarrow> b = b'\"\n  by (metis (no_types, opaque_lifting) Poset.valid_map_deterministic PosetMap.select_convs(3) compose_def relcomp.cases)\n\nlemma compose_total : \"valid_map f \\<Longrightarrow> valid_map g \\<Longrightarrow> dom g = cod f \\<Longrightarrow> a \\<in> el (dom f) \\<Longrightarrow> \\<exists>b. (a, b) \\<in> func (g \\<diamondop> f)\"\n  unfolding compose_def\n  by (smt (z3) Poset.fun_app Poset.fun_app2 PosetMap.select_convs(3) relcomp.relcompI)\n\nlemma dom_compose [simp] : \"valid_map f \\<Longrightarrow> valid_map g \\<Longrightarrow> dom g = cod f \\<Longrightarrow> dom (g \\<diamondop> f) = dom f\"\n  unfolding compose_def\n  by (simp add: Let_def)\n\nlemma cod_compose [simp] : \"valid_map f \\<Longrightarrow> valid_map g \\<Longrightarrow> dom g = cod f \\<Longrightarrow> cod (g \\<diamondop> f) = cod g\"\n  unfolding compose_def\n  by (simp add: Let_def)\n\nlemma compose_app_assoc: \"valid_map f \\<Longrightarrow> valid_map g \\<Longrightarrow> a \\<in> el (dom f) \\<Longrightarrow> dom g = cod f \\<Longrightarrow> (g \\<diamondop> f) \\<star> a = g \\<star> (f \\<star> a)\"\n  apply (clarsimp simp: app_def, safe; clarsimp?)\n  apply (smt (z3) Poset.fun_app PosetMap.select_convs(3) compose_def compose_deterministic fun_app_iff relcomp.relcompI theI')\n  by (metis app_def fun_app2)\n                   \nlemma compose_monotone :\n  fixes f :: \"('a,'b) PosetMap\" and g :: \"('b,'c) PosetMap\" and a a' :: \"'a\"\n  assumes f_valid : \"valid_map f\" and g_valid : \"valid_map g\"\n  and a_elem : \"a \\<in> el (dom f)\" and a'_elem : \"a' \\<in> el (dom f)\"\n  and le_aa' : \"le (dom f) a a'\"\n  and dom_cod : \"dom g = cod f\"\nshows \"le (cod g) ((g \\<diamondop> f) \\<star> a) ((g \\<diamondop> f) \\<star> a')\"\nproof -\n  have \"le (cod f) (f \\<star> a) (f \\<star> a')\" using valid_map_monotone\n    by (metis a'_elem a_elem f_valid le_aa')\n  moreover have  \"le (cod g) (g \\<star> (f \\<star> a)) (g \\<star> (f \\<star> a'))\" using valid_map_monotone\n    by (metis a'_elem a_elem calculation dom_cod f_valid fun_app2 g_valid)\n  ultimately show ?thesis using compose_app_assoc\n    by (metis a'_elem a_elem dom_cod f_valid g_valid)\nqed\n\nlemma compose_valid : \"valid_map f \\<Longrightarrow> valid_map g \\<Longrightarrow> dom g = cod f \\<Longrightarrow> valid_map (g \\<diamondop> f)\"\nproof (intro valid_mapI, safe, goal_cases)\n  case 1\n  then show ?case\n    by (simp add: Poset.valid_map_welldefined_dom) \nnext\n  case 2\n  then show ?case\n    by (simp add: Poset.valid_map_welldefined_cod) \nnext\n  case (3 a b)\n  then show ?case\n    by (simp add: Poset.compose_welldefined_dom) \nnext\n  case (4 a b)\n  then show ?case\n    by (simp add: Poset.compose_welldefined_cod) \nnext\n  case (5 a b b')\n  then show ?case\n    by (meson Poset.compose_deterministic) \nnext\n  case (6 a)\n  then show ?case\n    by (simp add: Poset.compose_total) \nnext\n  case (7 a a')\n  then show ?case\n    by (simp add: compose_monotone) \nqed\n\nlemma compose_app [simp] : \"valid_map f \\<Longrightarrow> valid_map g \\<Longrightarrow> (a, b) \\<in> func f \\<Longrightarrow> dom g = cod f \\<Longrightarrow>\n                (b, c) \\<in> func g \\<Longrightarrow> (g \\<diamondop> f) \\<star> a = c\"\n  apply (rule fun_app_iff)\n  using compose_valid apply blast\n  by (simp add: compose_def relcomp.relcompI)\n\nlemma compose_assoc : \"valid_map f \\<Longrightarrow> valid_map g \\<Longrightarrow> valid_map h \\<Longrightarrow> dom g = cod f \\<Longrightarrow> dom h = cod g \n\\<Longrightarrow> (h \\<diamondop> g) \\<diamondop> f = h \\<diamondop> (g \\<diamondop> f)\"\n  by (smt (verit) Poset.cod_compose Poset.compose_app_assoc Poset.compose_valid Poset.dom_compose Poset.fun_app2 Poset.fun_ext) \n\n(* Properties *)\n\nabbreviation is_surjective :: \"('a, 'b) PosetMap \\<Rightarrow> bool\" where\n\"is_surjective f \\<equiv> \\<forall> b . b \\<in> el (cod f) \\<longrightarrow> (\\<exists> a . a \\<in> el (dom f) \\<and> f \\<star> a = b)\"\n\nabbreviation is_injective :: \"('a, 'b) PosetMap \\<Rightarrow> bool\" where\n\"is_injective f \\<equiv> \\<forall>a a' . a \\<in> el (dom f) \\<longrightarrow> a' \\<in> el (dom f) \\<longrightarrow> f \\<star> a = f \\<star> a' \\<longrightarrow> a = a'\"\n\nabbreviation is_bijective :: \"('a, 'b) PosetMap \\<Rightarrow> bool\" where\n\"is_bijective f \\<equiv> is_surjective f \\<and> is_injective f\"\n\nlemma surjection_is_right_cancellative : \"valid_map f \\<Longrightarrow> is_surjective f \\<Longrightarrow>\n  valid_map g \\<Longrightarrow> valid_map h \\<Longrightarrow> cod f = dom g \\<Longrightarrow> cod f = dom h \\<Longrightarrow>  g \\<diamondop> f = h \\<diamondop> f \\<Longrightarrow> g = h\"\n  by (metis cod_compose compose_app_assoc fun_ext )\n\nlemma injection_is_left_cancellative : \"valid_map f \\<Longrightarrow> is_injective f \\<Longrightarrow>\n  valid_map g \\<Longrightarrow> valid_map h \\<Longrightarrow> cod g = dom f \\<Longrightarrow> cod h = dom f \\<Longrightarrow>  f \\<diamondop> g = f \\<diamondop> h \\<Longrightarrow> g = h\"\n  by (smt (verit, best) compose_app_assoc dom_compose fun_app2 fun_ext)\n\n(* Identity maps *)\n\ndefinition ident :: \"'a Poset \\<Rightarrow> ('a, 'a) PosetMap\" where\n\"ident P \\<equiv> \\<lparr> dom = P, cod = P, func = Id_on (el P) \\<rparr>\"\n\nlemma ident_valid  : \"valid P \\<Longrightarrow> valid_map (ident P)\"\n  unfolding valid_map_def  ident_def app_def\n  apply ( simp add: Let_unfold Id_on_def )\n  by blast\n\nlemma ident_dom [simp] : \"dom (ident P) = P\"\n  by (simp add: Poset.ident_def)\n\nlemma ident_cod [simp] : \"cod (ident P) = P\"\n  by (simp add: Poset.ident_def)\n\nlemma ident_app [simp] :\n  fixes a :: \"'a\" and P :: \"'a Poset\"\n  assumes \"valid P\" and \"a \\<in> el P\"\n  shows \"ident P \\<star> a = a\"\n  by (metis Id_onI Poset.fun_app_iff Poset.ident_def Poset.ident_valid PosetMap.select_convs(3) assms(1) assms(2))\n\nlemma compose_ident_left [simp]  : \"valid_map f \\<Longrightarrow> ident (cod f) \\<diamondop> f = f\"\n  by (smt (verit, best) Poset.cod_compose Poset.compose_app_assoc Poset.compose_valid Poset.dom_compose Poset.fun_app2 Poset.fun_ext Poset.ident_app Poset.ident_cod Poset.ident_dom Poset.ident_valid valid_map_welldefined_cod) \n\nlemma compose_ident_right [simp] : \"valid_map f  \\<Longrightarrow> f \\<diamondop> ident (dom f) = f\"\n  by (smt (verit, ccfv_SIG) Poset.cod_compose Poset.compose_app_assoc Poset.compose_valid Poset.dom_compose Poset.fun_ext Poset.ident_app Poset.ident_cod Poset.ident_dom Poset.ident_valid valid_map_welldefined_dom)\n\n(* Constant maps *)\n\ndefinition \"PosetMap_const_undefined_arg_not_in_codomain b \\<equiv> undefined\"\n\ndefinition const :: \"'a Poset \\<Rightarrow>  'b Poset  \\<Rightarrow> 'b \\<Rightarrow>  ('a, 'b) PosetMap\" where\n\"const P Q q \\<equiv>\n  if q \\<in> el Q\n  then  \\<lparr> dom = P, cod = Q,  func = { (p, q) | p . p \\<in> el P } \\<rparr>\n  else PosetMap_const_undefined_arg_not_in_codomain q\"\n\nlemma const_dom [simp] : \"q \\<in> el Q \\<Longrightarrow> dom (const P Q q) = P\"\n  by (simp add: const_def)\n\nlemma const_cod [simp] : \"q \\<in> el Q \\<Longrightarrow> cod (const P Q q) = Q\"\n  by (simp add: const_def)\n\nlemma const_app [simp] : \"valid P \\<Longrightarrow> valid Q \\<Longrightarrow> p \\<in> el P \\<Longrightarrow> q \\<in> el Q \\<Longrightarrow> ((const P Q q) \\<star> p) = q\"\n  unfolding const_def app_def\n  by auto\n\nlemma const_valid : \"valid P \\<Longrightarrow> valid Q \\<Longrightarrow> q \\<in> el Q \\<Longrightarrow> valid_map (const P Q q)\"\nproof (intro valid_mapI,goal_cases)\n  case 1\n  then show ?case\n    by simp \nnext\n  case 2\n  then show ?case\n    by simp \nnext\n  case (3 a b)\n  then show ?case\n    by (simp add: Poset.const_def) \nnext\n  case (4 a b b')\n  then show ?case\n    by (simp add: Poset.const_def) \nnext\n  case (5 a)\n  then show ?case by (simp add: const_def)\nnext\n  case (6 a a')\n  then show ?case\n    by (simp add: valid_reflexivity) \nqed\n\n(* Cartesian product of posets *)\n\ndefinition product :: \"'a Poset \\<Rightarrow> 'b Poset \\<Rightarrow> ('a \\<times> 'b) Poset\" (infixl \"\\<times>\\<times>\" 55) where\n\"product P Q \\<equiv> \\<lparr> el = el P \\<times> el Q, le_rel =\n {(x, y). fst x \\<in> el P \\<and> snd x \\<in> el Q \\<and> fst y \\<in> el P \\<and> snd y \\<in> el Q \\<and> (fst x, fst y) \\<in> le_rel P \\<and> (snd x, snd y) \\<in> le_rel Q} \\<rparr>\"\n\nlemma product_valid : \"valid P \\<Longrightarrow> valid Q \\<Longrightarrow> valid (P \\<times>\\<times> Q)\"\n  unfolding valid_def product_def\n  by (smt (verit) Poset.Poset.select_convs(1) Poset.Poset.select_convs(2) Product_Type.Collect_case_prodD SigmaE SigmaI case_prodI fst_conv mem_Collect_eq prod.collapse snd_conv)\n\nlemma product_el_1 : \"(a,b) \\<in> el (P \\<times>\\<times> Q) \\<Longrightarrow> a \\<in> el P\"\n  by (simp add: Poset.product_def)\n\nlemma product_el_2 : \"(a,b) \\<in> el (P \\<times>\\<times> Q) \\<Longrightarrow> b \\<in> el Q\"\n  by (simp add: Poset.product_def)\n\nlemma product_le_1 : \"valid P \\<Longrightarrow> valid Q \\<Longrightarrow> ((a, b),(a', b')) \\<in> le_rel (P \\<times>\\<times> Q) \\<Longrightarrow> (a,a') \\<in> le_rel P\"\n  by (simp add: Poset.product_def) \n                                               \nlemma product_le_2 : \"valid P \\<Longrightarrow> valid Q \\<Longrightarrow> ((a, b),(a', b')) \\<in> le_rel (P \\<times>\\<times> Q) \\<Longrightarrow> (b,b') \\<in> le_rel Q\"\n  by (simp add: Poset.product_def) \n\n(* Discrete poset *)\n\ndefinition discrete :: \"'a Poset\" where\n  \"discrete \\<equiv> \\<lparr>  el = UNIV , le_rel = {x. fst x = snd x} \\<rparr>\"\n\nlemma discrete_valid : \"valid discrete\"\n  by (simp add: discrete_def valid_def)\n\n(* Infima and suprema *)\n\ndefinition is_inf :: \"'a Poset \\<Rightarrow> 'a set \\<Rightarrow> 'a \\<Rightarrow> bool\" where\n\"is_inf P U i \\<equiv>  U \\<subseteq> el P \\<and> i \\<in> el P \\<and>  ((\\<forall>u\\<in>U. le P i u) \\<and> (\\<forall>z \\<in> el P. (\\<forall>u\\<in>U. le P z u) \\<longrightarrow> le P z i))\"\n\ndefinition is_sup :: \"'a Poset \\<Rightarrow> 'a set \\<Rightarrow> 'a \\<Rightarrow> bool\" where\n\"is_sup P U s \\<equiv> U \\<subseteq> el P \\<and> s \\<in> el P \\<and>  (s \\<in> el P \\<and> (\\<forall>u\\<in>U. le P u s) \\<and> (\\<forall>z \\<in> el P. (\\<forall>u\\<in>U. le P u z) \\<longrightarrow> le P s z))\"\n\nabbreviation is_bot :: \"'a Poset \\<Rightarrow> 'a \\<Rightarrow> bool\" where\n\"is_bot P b \\<equiv> b \\<in> el P \\<and> (\\<forall>p \\<in> el P. le P b p)\"\n\nabbreviation is_top :: \"'a Poset \\<Rightarrow> 'a \\<Rightarrow> bool\" where\n\"is_top P t \\<equiv> t \\<in> el P \\<and> (\\<forall>p \\<in> el P. le P p t)\"\n\ndefinition inf :: \"'a Poset \\<Rightarrow> 'a set \\<Rightarrow> 'a option\" where\n\"inf P U \\<equiv> if (\\<exists>i. i \\<in> el P \\<and> is_inf P U i) then Some (SOME i. i \\<in> el P \\<and> is_inf P U i) else None\"\n\ndefinition sup :: \"'a Poset \\<Rightarrow> 'a set \\<Rightarrow> 'a option\" where\n\"sup P U \\<equiv> if (\\<exists>s. s \\<in> el P \\<and> is_sup P U s) then Some (SOME s. s \\<in> el P \\<and> is_sup P U s) else None\"\n\nabbreviation is_complete :: \"'a Poset \\<Rightarrow> bool\" where\n\"is_complete P \\<equiv> valid P \\<and> (\\<forall>U. U \\<subseteq> el P \\<longrightarrow> (\\<exists>i. is_inf P U i))\"\n\nabbreviation is_cocomplete :: \"'a Poset \\<Rightarrow> bool\" where\n\"is_cocomplete P \\<equiv> valid P \\<and> (\\<forall>U. U \\<subseteq> el P \\<longrightarrow> (\\<exists>s. is_sup P U s))\"\n\nlemma inf_unique : \"valid P \\<Longrightarrow> U \\<subseteq> el P \\<Longrightarrow> i \\<in> el P\\<Longrightarrow> i' \\<in> el P \\<Longrightarrow> is_inf P U i \\<Longrightarrow> is_inf P U i' \\<Longrightarrow> i = i'\"\n  unfolding is_inf_def\n  by (metis valid_antisymmetry)\n\nlemma sup_unique : \"valid P  \\<Longrightarrow> U \\<subseteq> el P \\<Longrightarrow> s \\<in> el P\\<Longrightarrow> s' \\<in> el P \\<Longrightarrow> is_sup P U s \\<Longrightarrow> is_sup P U s' \\<Longrightarrow> s = s'\"\n  unfolding is_sup_def\n  by (metis valid_antisymmetry)\n\nlemma inf_is_glb : \"valid P  \\<Longrightarrow> U \\<subseteq> el P  \\<Longrightarrow> z \\<in> el P \\<Longrightarrow> i \\<in> el P \\<Longrightarrow> is_inf P U i\n\\<Longrightarrow> \\<forall>u\\<in>U. le P z u \\<Longrightarrow> le P z i\"\n  by (simp add: is_inf_def)\n\nlemma sup_is_lub : \"valid P  \\<Longrightarrow> U \\<subseteq> el P  \\<Longrightarrow> z \\<in> el P \\<Longrightarrow> s \\<in> el P \\<Longrightarrow> is_sup P U s\n\\<Longrightarrow> \\<forall>u\\<in>U. le P u z \\<Longrightarrow> le P s z\"\n  by (simp add: is_sup_def)\n\nlemma inf_smaller : \"valid P  \\<Longrightarrow> U \\<subseteq> el P  \\<Longrightarrow> i \\<in> el P \\<Longrightarrow> is_inf P U i \\<Longrightarrow> \\<forall> u \\<in> U. le P i u\"\n  unfolding is_inf_def\n  by blast\n\nlemma sup_greater : \"valid P  \\<Longrightarrow> U \\<subseteq> el P \\<Longrightarrow> s \\<in> el P  \\<Longrightarrow> is_sup P U s \\<Longrightarrow> \\<forall> u \\<in> U. le P u s\"\n  unfolding is_sup_def\n  by blast\n\nlemma some_inf_is_inf : \"valid P \\<Longrightarrow> U \\<subseteq> el P \\<Longrightarrow> i \\<in> el P \\<Longrightarrow> inf P U = Some i \\<Longrightarrow> is_inf P U i\"\n  unfolding inf_def\n  by (metis (no_types, lifting) option.distinct(1) option.inject someI_ex)\n\nlemma some_sup_is_sup : \"valid P\\<Longrightarrow> U \\<subseteq> el P \\<Longrightarrow> sup P U = Some s \\<Longrightarrow> is_sup P U s\"\n  unfolding sup_def\n  by (metis (no_types, lifting) sup_unique option.distinct(1) option.inject some_equality)\n\nlemma complete_inf_not_none : \"valid P \\<Longrightarrow> U \\<subseteq> el P \\<Longrightarrow> is_complete P \\<Longrightarrow> inf P U \\<noteq> None\"\n  by (simp add: inf_def is_inf_def)\n\nlemma cocomplete_sup_not_none : \"valid P \\<Longrightarrow> U \\<subseteq> el P \\<Longrightarrow> is_cocomplete P \\<Longrightarrow> sup P U \\<noteq> None\"\n  by (simp add: is_sup_def sup_def)\n\nlemma complete_equiv_cocomplete : \"is_complete P \\<longleftrightarrow> is_cocomplete P\"\nproof\n  assume \"is_complete P\"\n  fix U\n  define \"s\" where \"s = inf P {a \\<in> el P . (\\<forall> u \\<in> U . le P u a)}\"\n  have \"s = sup P U\"\n    oops\n\n(* Powerset and direct image *)\n\ndefinition powerset :: \"'a set \\<Rightarrow> ('a set) Poset\" where\n\"powerset X \\<equiv> \\<lparr> el = Pow X, le_rel = {(U, V). U \\<in> Pow X \\<and> V \\<in> Pow X \\<and> U \\<subseteq> V} \\<rparr>\"\n\ndefinition direct_image :: \"('a, 'b) Function \\<Rightarrow> ('a set, 'b set) PosetMap\" where\n\"direct_image f \\<equiv> \\<lparr>\n        dom = powerset (Function.dom f),\n        cod = powerset (Function.cod f),\n        func = {(p, {f \\<cdot> x | x . x \\<in> p}) | p . p \\<subseteq> Function.dom f}\n \\<rparr>\"\n\nlemma powerset_valid : \"valid (powerset A)\"\n  by (smt (verit) Poset.Poset.select_convs(1) Poset.Poset.select_convs(2) Product_Type.Collect_case_prodD case_prodI dual_order.refl fst_conv mem_Collect_eq order_trans powerset_def snd_conv subset_antisym valid_def)\n\nlemma powerset_le : \"a \\<in> el (powerset A) \\<Longrightarrow> a' \\<in> el (powerset A) \\<Longrightarrow> le (powerset A) a a' = (a \\<subseteq> a')\"\n  by (simp add: powerset_def)\n\nlemma powerset_el : \"(a \\<in> el (powerset A)) = (a \\<subseteq> A)\"\n  by (simp add: powerset_def)\n\nlemma direct_image_dom : \"dom (direct_image f) = powerset (Function.dom f)\"\n  by (simp add: direct_image_def)\n\nlemma direct_image_cod : \"cod (direct_image f) = powerset (Function.cod f)\"\n  by (simp add: direct_image_def)\n\nlemma direct_image_app : \"Function.valid_map f \\<Longrightarrow> a \\<subseteq> Function.dom f \\<Longrightarrow> (direct_image f) \\<star> a = {f \\<cdot> x | x . x \\<in> a}\"\n  unfolding Function.valid_map_def app_def direct_image_def\n  apply (simp add: Let_def)\n  by (simp add: powerset_def)\n\nlemma direct_image_mono_raw: \"Function.valid_map f \\<Longrightarrow> a \\<subseteq> Function.dom f \\<Longrightarrow> a' \\<subseteq> Function.dom f\n \\<Longrightarrow> a \\<subseteq> a' \\<Longrightarrow> (direct_image f) \\<star> a \\<subseteq> (direct_image f) \\<star> a'\"\n  unfolding Function.valid_map_def app_def direct_image_def\n  apply (simp add: Let_def)\n  by (smt (verit, del_insts) Collect_mono_iff Poset.Poset.select_convs(1) PowI powerset_def subset_eq)\n\nlemma direct_image_valid :\n  fixes f :: \"('a,'b) Function\"\n  assumes f_valid : \"Function.valid_map f\"\n  defines \"X \\<equiv> Function.dom f\" and \"Y \\<equiv> Function.cod f\"\n  shows \"valid_map (direct_image f)\"\nproof (intro valid_mapI, safe, goal_cases)\n  case 1\n  then show ?case\n    by (simp add: direct_image_dom powerset_valid) \nnext\n  case 2\n  then show ?case\n    by (simp add: direct_image_cod powerset_valid) \nnext\n  case (3 a b)\n  then show ?case\n    by (simp add: direct_image_def powerset_def) \nnext\n  case (4 a b)\n  then show ?case\n    by (smt (verit) Function.fun_app2 Poset.Poset.select_convs(1) PosetMap.select_convs(3) PowI direct_image_cod direct_image_def f_valid mem_Collect_eq powerset_def snd_conv subset_eq) \nnext\n  case (5 a b b' x)\n  then show ?case\n    by (simp add: direct_image_def) \nnext\n  case (6 a b b' x)\n  then show ?case\n    by (smt (z3) CollectD PosetMap.select_convs(3) direct_image_def fst_conv snd_conv) \nnext\n  case (7 a)\n  then show ?case\n    by (simp add: direct_image_def powerset_def) \nnext\n  case (8 a a')\n  then show ?case \n  proof -\n    fix a a'\n    assume \"a \\<in> el (PosetMap.dom (direct_image f))\"\n    assume \"a'\\<in> el (PosetMap.dom (direct_image f))\"\n    assume \"le (PosetMap.dom (direct_image f)) a a'\"\n\n    have \"(direct_image f) \\<star> a = {f \\<cdot> x | x . x \\<in> a}\" using direct_image_def [where ?f=f] app_def\n        [where ?f=\"direct_image f\" and ?a=a]\n      by (metis (mono_tags, lifting) Poset.Poset.select_convs(1) PowD \\<open>a \\<in> el (PosetMap.dom (direct_image f))\\<close> direct_image_app direct_image_dom f_valid powerset_def)\n    moreover have \"(direct_image f) \\<star> a' = {f \\<cdot> x | x . x \\<in> a'}\" using direct_image_def [where ?f=f] app_def\n        [where ?f=\"direct_image f\" and ?a=a']\n      by (metis (mono_tags, lifting) Poset.Poset.select_convs(1) PosetMap.select_convs(1) Pow_iff \\<open>a' \\<in> el (PosetMap.dom (direct_image f))\\<close> direct_image_app f_valid powerset_def)\n    moreover have \"{f \\<cdot> x | x . x \\<in> a} \\<subseteq> {f \\<cdot> x | x . x \\<in> a'}\" using direct_image_def [where ?f=f]\n        calculation\n      by (smt (verit) Poset.Poset.select_convs(2) Pow_iff \\<open>a \\<in> el (PosetMap.dom (direct_image f))\\<close> \\<open>a' \\<in> el (PosetMap.dom (direct_image f))\\<close> \\<open>le (PosetMap.dom (direct_image f)) a a'\\<close> case_prod_unfold direct_image_dom direct_image_mono_raw f_valid fst_conv mem_Collect_eq powerset_def snd_conv)\n\n    ultimately show \"le (PosetMap.cod (direct_image f)) (direct_image f \\<star> a) (direct_image f \\<star>\n      a')\" using direct_image_def [where ?f=f] powerset_def [where ?X=\"Function.cod f\"]\n      by (smt (verit) Function.fun_app2 Poset.Poset.select_convs(1) Poset.Poset.select_convs(2) PosetMap.select_convs(1) PosetMap.select_convs(2) Pow_iff \\<open>a' \\<in> el (PosetMap.dom (direct_image f))\\<close> case_prodI f_valid mem_Collect_eq powerset_def subsetD subsetI)\n  qed\nqed\n\nlemma direct_image_mono:\n  fixes f :: \"('a, 'b) Function\" and a a' :: \"'a set\"\n  defines \"pf \\<equiv> direct_image f\"\n  assumes f_valid : \"Function.valid_map f\"\n  and a_el : \"a \\<in> el (dom pf)\" and a'_el : \"a' \\<in> el (dom pf)\" and a_le_a' : \"le (dom pf) a a'\"\nshows \"le (cod pf) (pf \\<star> a) (pf \\<star> a')\"\n  by (metis a'_el a_el a_le_a' direct_image_valid f_valid pf_def valid_map_monotone)\n\nlemma direct_image_ident : \"direct_image (Function.ident X) = ident (powerset X)\"\nproof -\n  fix X :: \"'a set\"\n  have \" {(p, p) |p . p \\<subseteq> X} =  Id_on (Pow X)\" using Id_on_def [where ?A=\"Pow X\"]   Pow_def\n      [where ?A=X] set_eqI [where ?A=\"Id_on (Pow X)\" and ?B=\"{(p, p) |p. p \\<subseteq> X}\"]\n    by blast\n\n  moreover have \"func (ident (powerset X)) = {(p, p) |p . p \\<subseteq> X}\"\n    by (simp add: Poset.ident_def calculation powerset_def)\n  moreover have \"dom (direct_image (Function.ident X)) = powerset X\"\n    by (simp add: direct_image_dom)\n  moreover have \"cod (direct_image (Function.ident X)) = powerset X\"\n    by (simp add: Function.ident_def direct_image_cod)\n\n  moreover have \"\\<forall> p . p \\<subseteq> X \\<longrightarrow> {Function.ident X \\<cdot> x |x. x \\<in> p} = p\" using Function.ident_app [where\n        ?X=X]\n    by (smt (verit, ccfv_threshold) Collect_cong Collect_mem_eq in_mono)\n  moreover have \"func (direct_image (Function.ident X)) = {(p, p) |p . p \\<subseteq> X}\" using calculation\n      direct_image_def\n    [where ?f=\"Function.ident X\"] Function.ident_app [where ?X=X]\n    by force\n   ultimately show \"direct_image (Function.ident X) = ident (powerset X)\"\n     by (simp add: Poset.ident_def)\n qed\n\nlemma direct_image_trans :\n  fixes g :: \"('b, 'c) Function\" and f :: \"('a , 'b) Function\"\n  assumes f_valid : \"Function.valid_map f\"\n  and g_valid : \"Function.valid_map g\"\n  and \"Function.cod f = Function.dom g\"\nshows \"direct_image g \\<diamondop> direct_image f = direct_image (g \\<bullet> f)\"\nproof (rule fun_ext, goal_cases)\n  case 1\n  then show ?case\n    by (simp add: Poset.compose_valid assms(3) direct_image_cod direct_image_dom direct_image_valid f_valid g_valid) \nnext\n  case 2\n  then show ?case\n    using Function.compose_valid assms(3) direct_image_valid f_valid g_valid by blast \nnext\n  case 3\n  then show ?case\n    by (simp add: assms(3) direct_image_cod direct_image_dom direct_image_valid f_valid g_valid) \nnext\n  case 4\n  then show ?case\n    by (simp add: assms(3) direct_image_cod direct_image_dom direct_image_valid f_valid g_valid)\nnext\n  case (5 a)\n  then show ?case \n    proof -\n    fix a\n    assume \"a \\<in> el (PosetMap.dom (direct_image g \\<diamondop> direct_image f))\"\n    have \"a \\<subseteq> Function.dom f\"\n      by (metis (no_types, lifting) Poset.Poset.select_convs(1) Poset.dom_compose PowD \\<open>a \\<in> el (PosetMap.dom (direct_image g \\<diamondop> direct_image f))\\<close> assms(3) direct_image_cod direct_image_dom direct_image_valid f_valid g_valid powerset_def) \n    have \"(a, {f \\<cdot> x |x. x \\<in> a}) \\<in> {(b, {f \\<cdot> x |x. x \\<in> b}) |b. b \\<subseteq> Function.dom f} \"\n      using \\<open>a \\<subseteq> Function.dom f\\<close> by blast\n    moreover have \"{f \\<cdot> x |x. x \\<in> a} \\<subseteq> Function.cod f\"\n      using Function.fun_app2 \\<open>a \\<subseteq> Function.dom f\\<close> f_valid by fastforce\n    moreover have \"({f \\<cdot> x |x. x \\<in> a}, {g \\<cdot> (f \\<cdot> x) |x. x \\<in> a}) \\<in> {(b, {g \\<cdot> x |x. x \\<in> b}) |b. b \\<subseteq>\n      Function.cod f}\"\n      using calculation(2) by blast\n    moreover have \"(a, {g \\<cdot> (f \\<cdot> x) |x. x \\<in> a}) \\<in>\n  {(p, {f \\<cdot> x |x. x \\<in> p}) |p. p \\<subseteq> Function.dom f} O {(p, {g \\<cdot> x |x. x \\<in> p}) |p. p  \\<subseteq> Function.cod f}\"\n      using calculation(1) calculation(3) by auto\n    ultimately show \"(direct_image g \\<diamondop> direct_image f) \\<star> a = direct_image (g \\<bullet> f) \\<star> a\"\n      by (smt (verit) CollectD Collect_cong Function.compose_app_assoc Function.compose_valid Function.dom_compose Poset.compose_app_assoc Poset.dom_compose \\<open>a \\<in> el (PosetMap.dom (direct_image g \\<diamondop> direct_image f))\\<close> assms(3) direct_image_app direct_image_cod direct_image_dom direct_image_valid f_valid fst_conv g_valid snd_conv subset_eq)\n  qed\nqed\n\nlemma surj_imp_direct_image_surj :\n  fixes f :: \"('a, 'b) Function\"\n  assumes f_valid : \"Function.valid_map f\"\n  and f_surj : \"Function.is_surjective f\"\n  shows \"Poset.is_surjective (direct_image f)\"\nproof safe\n  fix b\n  define \"X\" where \"X = Function.dom f\"\n  define \"Y\" where \"Y = Function.cod f\"\n\n  assume \"b \\<in> el (PosetMap.cod (direct_image f))\"\n  have \"b \\<subseteq> Y\"\n    by (metis (no_types, lifting) Poset.Poset.select_convs(1) PowD Y_def \\<open>b \\<in> el (PosetMap.cod (direct_image f))\\<close> direct_image_cod powerset_def)\n  moreover have \"\\<forall> y \\<in> b . (\\<exists> x . x \\<in> X \\<and> f \\<cdot> x = y)\"\n    using X_def Y_def calculation f_surj by auto\n  define \"pre\" where \"pre = (\\<lambda> y. (SOME x. (y \\<in> b) \\<longrightarrow> (f \\<cdot> x = y \\<and> x \\<in> X) ))\"\n  moreover have \"\\<forall> y . (y \\<in> b \\<longrightarrow> f \\<cdot> (pre y) = y)\"\n    by (smt (verit, best) \\<open>\\<forall>y\\<in>b. \\<exists>x. x \\<in> X \\<and> f \\<cdot> x = y\\<close> pre_def someI_ex)\n  moreover have \"\\<forall> y . y \\<in> b \\<longrightarrow> pre y \\<in> X\"\n    by (smt (verit) \\<open>\\<forall>y\\<in>b. \\<exists>x. x \\<in> X \\<and> f \\<cdot> x = y\\<close> pre_def someI)\n  define \"a\" where \"a = { pre y | y . y \\<in> b }\"\n  moreover have \"a \\<subseteq> X\"\n    using \\<open>\\<forall>y. y \\<in> b \\<longrightarrow> pre y \\<in> X\\<close> a_def by fastforce\n  moreover have \"a \\<in> el (PosetMap.dom (direct_image f))\"\n    by (metis (no_types, lifting) Poset.Poset.select_convs(1) PowI X_def calculation(5) direct_image_dom powerset_def)\n  moreover have \"\\<forall> y . (y \\<in> b \\<longrightarrow> ( y = f \\<cdot>  (pre y)))\" using calculation\n  by presburger\n  moreover have \"\\<forall> y . (y \\<in> b \\<longrightarrow> (\\<exists> x \\<in> a . y = f \\<cdot> x))\" using calculation\n    by blast\n  moreover have \"((\\<cdot>) f) ` a = b\" using a_def pre_def using calculation\n    by (smt (verit, ccfv_threshold) image_Collect_subsetI image_iff subsetI subset_antisym)\n  show \"\\<exists>a. a \\<in> el (PosetMap.dom (direct_image f)) \\<and> direct_image f \\<star> a = b\"\n    by (metis Setcompr_eq_image X_def \\<open>(\\<cdot>) f ` a = b\\<close> calculation(5) calculation(6) direct_image_app f_valid)\n  qed\n\nlemma fibre_from_image :\n  fixes f :: \"('a, 'b) Function\" and a :: \"'a set\"\n  assumes f_valid : \"Function.valid_map f\"\n  and a_el : \"a \\<subseteq> Function.dom f\"\n  and t_el : \"t \\<in> (direct_image f) \\<star> a\"\n  shows \"\\<exists> t' . t' \\<in> a \\<and> f \\<cdot> t' = t\"\n  using a_el direct_image_app f_valid t_el by fastforce\n\n(* Forgetful functor from Pos to Set *)\n\ndefinition forget_map ::  \"('a, 'b) PosetMap \\<Rightarrow> ('a, 'b) Function\" where\n\"forget_map f \\<equiv> \\<lparr> Function.cod = el (cod f), func = func f \\<rparr>\" \n\nlemma forget_map_valid : \"valid_map f \\<Longrightarrow> Function.valid_map (forget_map f)\"\n  unfolding valid_map_def forget_map_def\n  apply (simp add:Let_def)\n  by (smt (verit) CollectD Function.dom_def Function.select_convs(1) Function.select_convs(2) Function.valid_map_def) \n\n(* Examples *)\n\ndefinition naturals :: \"nat Poset\" where\n  \"naturals \\<equiv> \\<lparr>  el = UNIV , le_rel = {(x,y). x \\<le> y}  \\<rparr>\"\n\nlemma naturals_valid : \"valid naturals\"\n  by (smt (verit, best) Poset.Poset.select_convs(1) Poset.Poset.select_convs(2) Product_Type.Collect_case_prodD UNIV_I case_prodI naturals_def fst_conv linorder_linear mem_Collect_eq order_antisym order_trans snd_conv validI)\n\ndefinition divisibility :: \"nat Poset\" where\n  \"divisibility \\<equiv> \\<lparr>  el = UNIV , le_rel = {(x,y). x dvd y }  \\<rparr>\"\n\nlemma divisibility_valid : \"valid divisibility\"\n  by (smt (verit, del_insts) Poset.Poset.select_convs(1) Poset.Poset.select_convs(2) Product_Type.Collect_case_prodD UNIV_I case_prodI dvd_antisym divisibility_def fst_conv gcd_nat.refl gcd_nat.trans mem_Collect_eq snd_conv valid_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/Poset.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8933094117351309, "lm_q2_score": 0.8152324915965392, "lm_q1q2_score": 0.7282548574954695}}
{"text": "theory Part_1 imports Main\nbegin\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\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 n) = V n\" |\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[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\n(* 3.1 *)\n\nfun optimal :: \"aexp \\<Rightarrow> bool\" where\n\"optimal (N a) = True\" |\n\"optimal (V x) = True\" |\n\"optimal (Plus (N i) (N j)) = False\" |\n\"optimal (Plus a b) = ((optimal a) \\<and> (optimal b))\"\n\nlemma is_optimal : \"optimal (asimp_const a)\"\n  apply(induction a)\n    apply(auto simp add: aexp.split)\n  done\n\n(* 3.2 *)\n\nfun sumN :: \"aexp \\<Rightarrow> int\" where\n\"sumN (N a) = a\" |\n\"sumN (V x) = 0\" |\n\"sumN (Plus a b) = sumN a + sumN b\"\n\nfun zeroN :: \"aexp \\<Rightarrow> aexp\" where\n\"zeroN (N a) = N 0\" |\n\"zeroN (V x) = V x\" |\n\"zeroN (Plus a b) = Plus (zeroN a) (zeroN b)\"\n\nfun 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\"\n  apply(induction t)\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\nfun 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)\n    apply(auto)\n  done\n\n(* 3.3 *)\n\nfun subst :: \"vname \\<Rightarrow> aexp \\<Rightarrow> aexp \\<Rightarrow> aexp\" where\n\"subst x a (V v) = (if x = v then a else (V v))\" |\n\"subst x a (Plus m n) = Plus (subst x a m) (subst x a n)\" |\n\"subst _ _ (N v) = N v\"\n\nlemma subst_lemma [simp] : \"aval (subst x a e) s = aval e (s(x := aval a s))\"\n  apply(induction e arbitrary: a)\n    apply(auto simp add: aexp.split)\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(auto)\n  done\n\n(* 3.4 *)\n\ndatatype aexp2 = N2 int | V2 vname | Plus2 aexp2 aexp2 | Times aexp2 aexp2\n\nfun aval2 :: \"aexp2 \\<Rightarrow> state \\<Rightarrow> val\" where\n\"aval2 (N2 a) s = a\" |\n\"aval2 (V2 x) s = s x\" |\n\"aval2 (Plus2 a b) s = (aval2 a s) + (aval2 b s)\" |\n\"aval2 (Times a b) s = (aval2 a s) * (aval2 b s)\"\n\nfun plus2 :: \"aexp2 \\<Rightarrow> aexp2 \\<Rightarrow> aexp2\" where\n\"plus2 (N2 i\\<^sub>1) (N2 i\\<^sub>2) = N2 (i\\<^sub>1 + i\\<^sub>2)\" |\n\"plus2 (N2 i) a = (if i = 0 then a else Plus2 (N2 i) a)\" |\n\"plus2 a (N2 i) = (if i = 0 then a else Plus2 a (N2 i))\" |\n\"plus2 a\\<^sub>1 a\\<^sub>2 = Plus2 a\\<^sub>1 a\\<^sub>2\"\n\nfun mult :: \"aexp2 \\<Rightarrow> aexp2 \\<Rightarrow> aexp2\" where\n\"mult (N2 i\\<^sub>1) (N2 i\\<^sub>2) = N2 (i\\<^sub>1*i\\<^sub>2)\" |\n\"mult (N2 i) a = \n  (if i=1 then a else if i=0 then (N2 0) else Times (N2 i) a)\" |\n\"mult a (N2 i) = (if i=0 then (N2 0) else if i = 1 then a else Times a (N2 i))\" |\n\"mult a\\<^sub>1 a\\<^sub>2 = Times a\\<^sub>1 a\\<^sub>2\"\n\nfun asimp2 :: \"aexp2 \\<Rightarrow> aexp2\" where\n\"asimp2 (N2 n) = N2 n\" |\n\"asimp2 (V2 x) = V2 x\" |\n\"asimp2 (Plus2 a\\<^sub>1 a\\<^sub>2) = plus2 (asimp2 a\\<^sub>1) (asimp2 a\\<^sub>2)\" |\n\"asimp2 (Times a\\<^sub>1 a\\<^sub>2) = mult (asimp2 a\\<^sub>1) (asimp2 a\\<^sub>2)\"\n\nlemma aval2_plus [simp] : \"aval2 (plus2 a\\<^sub>1 a\\<^sub>2) s = aval2 a\\<^sub>1 s + aval2 a\\<^sub>2 s\"\n  apply(induction a\\<^sub>1 a\\<^sub>2 rule: plus2.induct)\n    apply(auto)\n  done\n\nlemma aval2_mult [simp] : \"aval2 (mult a\\<^sub>1 a\\<^sub>2) s = (aval2 a\\<^sub>1) s * (aval2 a\\<^sub>2) s\"\n  apply(induction a\\<^sub>1 a\\<^sub>2 rule: mult.induct)\n    apply(auto)\n  done\n\nlemma aval2_asimp [simp] : \"aval2 (asimp2 a) s = aval2 a s\"\n  apply(induction a)\n     apply(auto simp add: aexp2.split)\n  done\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) _ = a\" |\n\"lval (Vl x) s = s x\" |\n\"lval (Plusl a\\<^sub>1 a\\<^sub>2) s = (lval a\\<^sub>1 s) + (lval a\\<^sub>2 s)\" |\n\"lval (LET x a\\<^sub>1 a\\<^sub>2) s = lval a\\<^sub>2 (s(x := lval a\\<^sub>1 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 x a b) = subst x (inline a) (inline b)\"\n\nlemma \"aval (inline a) s = lval a s\"\n  apply(induction a arbitrary: s)\n     apply(auto)\n  done\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 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 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 b\\<^sub>1 b\\<^sub>2 = And b\\<^sub>1 b\\<^sub>2\"\n\nfun less :: \"aexp \\<Rightarrow> aexp \\<Rightarrow> bexp\" where\n\"less (N a) (N b) = Bc (a < b)\" |\n\"less a b = Less a b\"\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 a b) s = (aval a s =  aval b s)\"\n  apply(induction a)\n    apply(induction b)\n      apply(auto)\n  done\n\nlemma \"bval (Le a b) s = (aval a s \\<le> aval b s)\"\n  apply(induction a)\n    apply(induction b)\n      apply(auto)\n  done\n\n(* 3.8 *)\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 a b) s = (aval a s < aval b s)\"\n\nfun b2ifexp :: \"bexp \\<Rightarrow> ifexp\" where\n\"b2ifexp (Bc a) = Bc2 a\" |\n\"b2ifexp (Less a b) = Less2 a 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\n\nfun if2bexp :: \"ifexp \\<Rightarrow> bexp\" where\n\"if2bexp (Bc2 v) = Bc v\" |\n\"if2bexp (If a b c) = Not (And (Not (And (if2bexp a) (if2bexp b))) (Not (And (Not (if2bexp a)) (if2bexp c))))\" |\n\"if2bexp (Less2 a b) = Less a b\"\n\nlemma \"bval (if2bexp exp) s = ifval exp s\"\n  apply(induction rule: if2bexp.induct)\n    apply(auto)\n  done\n\nlemma \"ifval (b2ifexp exp) s = bval exp s\"\n  apply(induction rule: b2ifexp.induct)\n     apply(auto)\n  done\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 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 (NOT (VAR _)) = True\" |\n\"is_nnf (NOT _) = False\" |\n\"is_nnf (VAR x) = True\" |\n\"is_nnf (AND a b) = (is_nnf a \\<and> is_nnf b)\" |\n\"is_nnf (OR a b) = (is_nnf a \\<and> is_nnf b)\"\n\nfun nnf :: \"pbexp \\<Rightarrow> pbexp\" where\n\"nnf (NOT (AND a b)) = OR (nnf (NOT a)) (nnf (NOT b))\" |\n\"nnf (NOT (OR a b)) = AND (nnf (NOT a)) (nnf (NOT b))\" |\n\"nnf (NOT (NOT a)) = nnf a\" |\n\"nnf (AND a b) = AND (nnf a) (nnf b)\" |\n\"nnf (OR a b) = OR (nnf a) (nnf b)\" |\n\"nnf (NOT (VAR x)) = NOT (VAR x)\" |\n\"nnf (VAR x) = VAR x\"\n\nlemma pbval_nnf : \"pbval (nnf b) s = pbval b s\"\n  apply(induction rule: nnf.induct)\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\nfun or_below_and :: \"pbexp \\<Rightarrow> bool\" where\n\"or_below_and (VAR x) = True\" |\n\"or_below_and (NOT a) = or_below_and a\" |\n\"or_below_and (OR a b) = (or_below_and a \\<and> or_below_and b)\" |\n\"or_below_and (AND (OR _ _) _) = False\" |\n\"or_below_and (AND _ (OR _ _)) = False\" |\n\"or_below_and (AND a b) = (or_below_and a \\<and> or_below_and b)\"\n\nfun is_dnf :: \"pbexp \\<Rightarrow> bool\" where\n\"is_dnf a = (is_nnf a \\<and> or_below_and a)\"\n\nfun dist_AND :: \"pbexp \\<Rightarrow> pbexp \\<Rightarrow> pbexp\" where\n\"dist_AND (OR a\\<^sub>1 a\\<^sub>2) b = OR (dist_AND a\\<^sub>1 b) (dist_AND a\\<^sub>2 b)\" |\n\"dist_AND a (OR b\\<^sub>1 b\\<^sub>2) = OR (dist_AND a b\\<^sub>1) (dist_AND a b\\<^sub>2)\" |\n\"dist_AND a b = AND a b\"\n\nlemma pbval_dist [simp] : \"pbval (dist_AND b\\<^sub>1 b\\<^sub>2) s = pbval (AND b\\<^sub>1 b\\<^sub>2) s\"\n  apply(induction b\\<^sub>1 b\\<^sub>2 rule: dist_AND.induct)\n     apply(auto)\n  done\n\nlemma is_dnf_dist [simp] : \"is_dnf a \\<Longrightarrow> is_dnf b \\<Longrightarrow> is_dnf (dist_AND a b)\"\n  apply(induction a b rule: dist_AND.induct)\n    apply(auto)\n  done\n\nfun dnf_of_nnf :: \"pbexp \\<Rightarrow> pbexp\" where\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\"dnf_of_nnf (VAR x) = VAR x\" |\n\"dnf_of_nnf (NOT a) = NOT (dnf_of_nnf a)\"\n\nlemma \"pbval (dnf_of_nnf b) s = pbval b s\"\n  apply(induction b arbitrary: s)\n     apply(auto)\n  done\n\nlemma \"is_nnf b \\<Longrightarrow> is_dnf (dnf_of_nnf b)\"\n  apply(induction b)\n     apply simp\n    apply (metis dnf_of_nnf.simps(3) dnf_of_nnf.simps(4) is_dnf.simps is_nnf.elims(2) nnf.simps(3) nnf.simps(7) or_below_and.simps(1) or_below_and.simps(2) pbexp.distinct(1) pbexp.distinct(10) pbexp.distinct(8))\n  using is_dnf_dist apply auto[1]\n  apply (simp add: is_nnf.simps(7) or_below_and.simps(3))\n  done\n\n(* 3.10 *)\n\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 _ [a] = 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 a \\<Rightarrow> exec is s a |\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 a \\<Longrightarrow> exec (is\\<^sub>1 @ is\\<^sub>2) s stk = exec is\\<^sub>2 s a\"\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 a) s stk = Some (aval a s # stk)\"\n  apply(induction a arbitrary: stk)\n    apply(auto)\n  done\n\n(* 3.11 *)\n\ntype_synonym reg = nat\n\ndatatype instr2 = LDI val reg | LD vname reg | ADD reg reg\n\n(* TODO *)", "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-3/Part_1.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094060543488, "lm_q2_score": 0.8152324960856175, "lm_q1q2_score": 0.7282548568744472}}
{"text": "(* Title:  Weighted_Graph.thy\n   Author: Lars Noschinski, TU M\u00fcnchen\n*)\n\ntheory Weighted_Graph\nimports\n  Digraph\n  Arc_Walk\n  Complex_Main\nbegin\n\nsection {* Weighted Graphs *}\n\ntype_synonym 'b weight_fun = \"'b \\<Rightarrow> real\"\n\ncontext wf_digraph begin\n\ndefinition awalk_cost :: \"'b weight_fun \\<Rightarrow> 'b awalk \\<Rightarrow> real\" where\n  \"awalk_cost f es = listsum (map f es)\"\n\nlemma awalk_cost_Nil[simp]: \"awalk_cost f [] = 0\"\n  unfolding awalk_cost_def by simp\n\nlemma awalk_cost_Cons[simp]: \"awalk_cost f (x # xs) = f x + awalk_cost  f xs\"\n  unfolding awalk_cost_def by simp\n\nlemma awalk_cost_append[simp]:\n  \"awalk_cost f (xs @ ys) = awalk_cost f xs + awalk_cost f ys\"\n  unfolding awalk_cost_def by simp\n\nend\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/Graph_Theory/Weighted_Graph.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8933094060543488, "lm_q2_score": 0.815232489352, "lm_q1q2_score": 0.7282548508592434}}
{"text": "theory Ex4_4\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 4.4:\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 \"star r x y \\<Longrightarrow>  (\\<exists> n. iter r n x y)\"\n  apply(induction rule: star.induct)\n  apply(metis iter.zero)\n  apply(metis iter.step)\ndone\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/Ex4_4.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094032139576, "lm_q2_score": 0.815232489352, "lm_q1q2_score": 0.7282548485436642}}
{"text": "theory Girth_Chromatic\nimports\n  Ugraphs\n  Girth_Chromatic_Misc\n  \"HOL-Probability.Probability\"\n  \"HOL-Decision_Procs.Approximation\"\nbegin\n\nsection \\<open>Probability Space on Sets of Edges\\<close>\n\ndefinition cylinder :: \"'a set \\<Rightarrow> 'a set \\<Rightarrow> 'a set \\<Rightarrow> 'a set set\" where\n  \"cylinder S A B = {T \\<in> Pow S. A \\<subseteq> T \\<and> B \\<inter> T = {}}\"\n\nlemma full_sum:\n  fixes p :: real\n  assumes \"finite S\"\n  shows \"(\\<Sum>A\\<in>Pow S. p^card A * (1 - p)^card (S - A)) = 1\"\nusing assms\nproof induct\n  case (insert s S)\n  have \"inj_on (insert s) (Pow S)\"\n      and \"\\<And>x. S - insert s x = S - x\"\n      and \"Pow S \\<inter> insert s ` Pow S = {}\"\n      and \"\\<And>x. x \\<in> Pow S \\<Longrightarrow> card (insert s S - x) = Suc (card (S - x))\"\n    using insert(1-2) by (auto simp: insert_Diff_if intro!: inj_onI)\n  moreover have \"\\<And>x. x \\<subseteq> S \\<Longrightarrow> card (insert s x) = Suc (card x)\"\n    using insert(1-2) by (subst card.insert) (auto dest: finite_subset)\n  ultimately show ?case\n    by (simp add: sum.reindex sum_distrib_left[symmetric] ac_simps\n                  insert.hyps sum.union_disjoint Pow_insert)\nqed simp\n\ntext \\<open>Definition of the probability space on edges:\\<close>\nlocale edge_space =\n  fixes n :: nat and p :: real\n  assumes p_prob: \"0 \\<le> p\" \"p \\<le> 1\"\nbegin\n\ndefinition S_verts :: \"nat set\" where\n  \"S_verts \\<equiv> {1..n}\"\n\ndefinition S_edges :: \"uedge set\" where\n  \"S_edges = all_edges S_verts\"\n\ndefinition edge_ugraph :: \"uedge set \\<Rightarrow> ugraph\" where\n  \"edge_ugraph es \\<equiv> (S_verts, es \\<inter> S_edges)\"\n\ndefinition \"P = point_measure (Pow S_edges) (\\<lambda>s. p^card s * (1 - p)^card (S_edges - s))\"\n\nlemma finite_verts[intro!]: \"finite S_verts\"\n  by (auto simp: S_verts_def)\n\nlemma finite_edges[intro!]: \"finite S_edges\"\n  by (auto simp: S_edges_def all_edges_def finite_verts)\n\nlemma finite_graph[intro!]: \"finite (uverts (edge_ugraph es))\"\n  unfolding edge_ugraph_def by auto\n\nlemma uverts_edge_ugraph[simp]: \"uverts (edge_ugraph es) = S_verts\"\n  by (simp add: edge_ugraph_def)\n\nlemma uedges_edge_ugraph[simp]: \"uedges (edge_ugraph es) = es \\<inter> S_edges\"\n  unfolding edge_ugraph_def by simp\n\nlemma space_eq: \"space P = Pow S_edges\" by (simp add: P_def space_point_measure)\n\nlemma sets_eq: \"sets P = Pow (Pow S_edges)\" by (simp add: P_def sets_point_measure)\n\nlemma emeasure_eq:\n  \"emeasure P A = (if A \\<subseteq> Pow S_edges then (\\<Sum>edges\\<in>A. p^card edges * (1 - p)^card (S_edges - edges)) else 0)\"\n  using finite_edges p_prob\n  by (simp add: P_def space_point_measure emeasure_point_measure_finite\n    sets_point_measure emeasure_notin_sets)\n\nlemma integrable_P[intro, simp]: \"integrable P (f::_ \\<Rightarrow> real)\"\n  using finite_edges by (simp add: integrable_point_measure_finite P_def)\n\nlemma borel_measurable_P[measurable]: \"f \\<in> borel_measurable P\"\n  unfolding P_def by simp\n\nlemma prob_space_P: \"prob_space P\"\nproof\n  show \"emeasure P (space P) = 1\" \\<comment> \\<open>Sum of probabilities equals 1\\<close>\n    using finite_edges by (simp add: emeasure_eq full_sum one_ereal_def space_eq)\nqed\n\nend\n\nsublocale edge_space \\<subseteq> prob_space P\n  by (rule prob_space_P)\n\ncontext edge_space\nbegin\n\nlemma prob_eq:\n  \"prob A = (if A \\<subseteq> Pow S_edges then (\\<Sum>edges\\<in>A. p^card edges * (1 - p)^card (S_edges - edges)) else 0)\"\n  using emeasure_eq[of A] p_prob unfolding emeasure_eq_measure by (simp add: sum_nonneg)\n\nlemma integral_finite_singleton: \"integral\\<^sup>L P f = (\\<Sum>x\\<in>Pow S_edges. f x * measure P {x})\"\n  using p_prob prob_eq unfolding P_def\n  by (subst lebesgue_integral_point_measure_finite) (auto intro!: sum.cong)\n\ntext \\<open>Probability of cylinder sets:\\<close>\nlemma cylinder_prob:\n  assumes \"A \\<subseteq> S_edges\" \"B \\<subseteq> S_edges\" \"A \\<inter> B = {}\"\n  shows \"prob (cylinder S_edges A B) = p ^ (card A) * (1 - p) ^ (card B)\" (is \"_ = ?pp A B\")\nproof -\n  have \"Pow S_edges \\<inter> cylinder S_edges A B = cylinder S_edges A B\"\n       \"\\<And>x. x \\<in> cylinder S_edges A B \\<Longrightarrow> A \\<union> x = x\"\n       \"\\<And>x. x \\<in> cylinder S_edges A B \\<Longrightarrow> finite x\"\n       \"\\<And>x. x \\<in> cylinder S_edges A B \\<Longrightarrow> B \\<inter> (S_edges - B - x) = {}\"\n       \"\\<And>x. x \\<in> cylinder S_edges A B \\<Longrightarrow> B \\<union> (S_edges - B - x) = S_edges - x\"\n       \"finite A\" \"finite B\"\n    using assms by (auto simp add: cylinder_def intro: finite_subset)\n  then have \"(\\<Sum>T\\<in>cylinder S_edges A B. ?pp T (S_edges - T))\n      = (\\<Sum>T \\<in> cylinder S_edges A B. p^(card A + card (T - A)) * (1 - p)^(card B + card ((S_edges - B) - T)))\"\n    using finite_edges by (simp add: card_Un_Int)\n  also have \"\\<dots> = ?pp A B * (\\<Sum>T\\<in>cylinder S_edges A B. ?pp (T - A) (S_edges - B - T))\"\n    by (simp add: power_add sum_distrib_left ac_simps)\n  also have \"\\<dots> = ?pp A B\"\n  proof -\n    have \"\\<And>T. T \\<in> cylinder S_edges A B \\<Longrightarrow> S_edges - B - T = (S_edges - A) - B - (T - A)\"\n         \"Pow (S_edges - A - B) = (\\<lambda>x. x - A) ` cylinder S_edges A B\"\n         \"inj_on (\\<lambda>x. x - A) (cylinder S_edges A B)\"\n         \"finite (S_edges - A - B)\"\n      using assms by (auto simp: cylinder_def intro!: inj_onI)\n    with full_sum[of \"S_edges - A - B\"] show ?thesis by (simp add: sum.reindex)\n  qed\n  finally show ?thesis by (auto simp add: prob_eq cylinder_def)\nqed\n\nlemma Markov_inequality:\n  fixes a :: real and X :: \"uedge set \\<Rightarrow> real\"\n  assumes \"0 < c\" \"\\<And>x. 0 \\<le> f x\"\n  shows \"prob {x \\<in> space P. c \\<le> f x} \\<le> (\\<integral>x. f x \\<partial> P) / c\"\nproof -\n  from assms have \"(\\<integral>\\<^sup>+ x. ennreal (f x) \\<partial>P) = (\\<integral>x. f x \\<partial>P)\"\n    by (intro nn_integral_eq_integral) auto\n  with assms show ?thesis\n    using nn_integral_Markov_inequality[of f P \"space P\" \"1 / c\"]\n    by (simp cong: nn_integral_cong add: emeasure_eq_measure ennreal_mult[symmetric])\nqed\n\nend\n\nsubsection \\<open>Graph Probabilities outside of @{term Edge_Space} locale\\<close>\n\ntext \\<open>\n These abbreviations allow a compact expression of probabilities about random\n graphs outside of the @{term Edge_Space} locale. We also transfer a few of the lemmas\n we need from the locale into the toplevel theory.\n\\<close>\n\nabbreviation MGn :: \"(nat \\<Rightarrow> real) \\<Rightarrow> nat \\<Rightarrow> (uedge set) measure\" where\n  \"MGn p n \\<equiv> (edge_space.P n (p n))\"\nabbreviation probGn :: \"(nat \\<Rightarrow> real) \\<Rightarrow> nat \\<Rightarrow> (uedge set \\<Rightarrow> bool) \\<Rightarrow> real\" where\n  \"probGn p n P \\<equiv> measure (MGn p n) {es \\<in> space (MGn p n). P es}\"\n\nlemma probGn_le:\n  assumes p_prob: \"0 < p n\" \"p n < 1\"\n  assumes sub: \"\\<And>n es. es \\<in> space (MGn p n) \\<Longrightarrow> P n es \\<Longrightarrow> Q n es\"\n  shows \"probGn p n (P n) \\<le> probGn p n (Q n)\"\nproof -\n  from p_prob interpret E: edge_space n \"p n\" by unfold_locales auto\n  show ?thesis\n    by (auto intro!: E.finite_measure_mono sub simp: E.space_eq E.sets_eq)\nqed\n\nsection \\<open>Short cycles\\<close>\n\ndefinition short_cycles :: \"ugraph \\<Rightarrow> nat \\<Rightarrow> uwalk set\" where\n  \"short_cycles G k \\<equiv> {p \\<in> ucycles G. uwalk_length p \\<le> k}\"\n\ntext \\<open>obtains a vertex in a short cycle:\\<close>\ndefinition choose_v :: \"ugraph \\<Rightarrow> nat \\<Rightarrow> uvert\" where\n  \"choose_v G k \\<equiv> SOME u. \\<exists>p. p \\<in> short_cycles G k \\<and> u \\<in> set p\"\n\npartial_function (tailrec) kill_short :: \"ugraph \\<Rightarrow> nat \\<Rightarrow> ugraph\" where\n  \"kill_short G k = (if short_cycles G k = {} then G else (kill_short (G -- (choose_v G k)) k))\"\n\nlemma ksc_simps[simp]:\n  \"short_cycles G k = {} \\<Longrightarrow> kill_short G k = G\"\n  \"short_cycles G k \\<noteq> {}  \\<Longrightarrow> kill_short G k = kill_short (G -- (choose_v G k)) k\"\n  by (auto simp: kill_short.simps)\n\nlemma\n  assumes \"short_cycles G k \\<noteq> {}\"\n  shows choose_v__in_uverts: \"choose_v G k \\<in> uverts G\" (is ?t1)\n    and choose_v__in_short: \"\\<exists>p. p \\<in> short_cycles G k \\<and> choose_v G k \\<in> set p\" (is ?t2)\nproof -\n  from assms obtain p where \"p \\<in> ucycles G\" \"uwalk_length p \\<le> k\"\n    unfolding short_cycles_def by auto\n  moreover\n  then obtain u where \"u \\<in> set p\" unfolding ucycles_def\n    by (cases p) (auto simp: uwalk_length_conv)\n  ultimately have \"\\<exists>u p. p \\<in> short_cycles G k \\<and> u \\<in> set p\"\n    by (auto simp: short_cycles_def)\n  then show ?t2 by (auto simp: choose_v_def intro!: someI_ex)\n  then show ?t1 by (auto simp: short_cycles_def ucycles_def uwalks_def)\nqed\n\nlemma kill_step_smaller:\n  assumes \"short_cycles G k \\<noteq> {}\"\n  shows \"short_cycles (G -- (choose_v G k)) k \\<subset> short_cycles G k\"\nproof -\n  let ?cv = \"choose_v G k\"\n  from assms obtain p where \"p \\<in> short_cycles G k\" \"?cv \\<in> set p\"\n    by atomize_elim (rule choose_v__in_short)\n\n  have \"short_cycles (G -- ?cv) k \\<subseteq> short_cycles G k\"\n  proof\n    fix p assume \"p \\<in> short_cycles (G -- ?cv) k\"\n    then show \"p \\<in> short_cycles G k\"\n      unfolding short_cycles_def ucycles_def uwalks_def\n      using edges_Gu[of G ?cv] by (auto simp: verts_Gu)\n  qed\n  moreover have \"p \\<notin> short_cycles (G -- ?cv) k\"\n    using \\<open>?cv \\<in> set p\\<close> by (auto simp: short_cycles_def ucycles_def uwalks_def verts_Gu)\n  ultimately show ?thesis using \\<open>p \\<in> short_cycles G k\\<close> by auto\nqed\n\ntext \\<open>Induction rule for @{term kill_short}:\\<close>\nlemma kill_short_induct[consumes 1, case_names empty kill_vert]:\n  assumes fin: \"finite (uverts G)\"\n  assumes a_empty: \"\\<And>G. short_cycles G k = {} \\<Longrightarrow> P G k\"\n  assumes a_kill: \"\\<And>G. finite (short_cycles G k) \\<Longrightarrow> short_cycles G k \\<noteq> {}\n    \\<Longrightarrow> P (G -- (choose_v G k)) k \\<Longrightarrow> P G k\"\n  shows \"P G k\"\nproof -\n  have \"finite (short_cycles G k)\"\n    using finite_ucycles[OF fin] by (auto simp: short_cycles_def)\n  then show ?thesis\n    by (induct \"short_cycles G k\" arbitrary: G rule: finite_psubset_induct)\n      (metis kill_step_smaller a_kill a_empty)\nqed\n\ntext \\<open>Large Girth (after @{term kill_short}):\\<close>\nlemma kill_short_large_girth:\n  assumes \"finite (uverts G)\"\n  shows \"k < girth (kill_short G k)\"\nusing assms\nproof (induct G k rule: kill_short_induct)\n  case (empty G)\n  then have \"\\<And>p. p \\<in> ucycles G \\<Longrightarrow> k < enat (uwalk_length p)\"\n    by (auto simp: short_cycles_def)\n  with empty show ?case by (auto simp: girth_def intro: enat_less_INF_I)\nqed simp\n\ntext \\<open>Order of graph (after @{term kill_short}):\\<close>\nlemma kill_short_order_of_graph:\n  assumes \"finite (uverts G)\"\n  shows \"card (uverts G) - card (short_cycles G k) \\<le> card (uverts (kill_short G k))\"\nusing assms assms\nproof (induct G k rule: kill_short_induct)\n  case (kill_vert G)\n  let ?oG = \"G -- (choose_v G k)\"\n\n  have \"finite (uverts ?oG)\"\n    using kill_vert by (auto simp: remove_vertex_def)\n  moreover\n  have \"uverts (kill_short G k) = uverts (kill_short ?oG k)\"\n    using kill_vert by simp\n  moreover\n  have \"card (uverts G) = Suc (card (uverts ?oG))\"\n    using choose_v__in_uverts kill_vert\n    by (simp add: remove_vertex_def card_Suc_Diff1 del: card_Diff_insert)\n  moreover\n  have \"card (short_cycles ?oG k) < card (short_cycles G k)\"\n    by (intro psubset_card_mono kill_vert.hyps kill_step_smaller)\n  ultimately show ?case using kill_vert.hyps by presburger\nqed simp\n\ntext \\<open>Independence number (after @{term kill_short}):\\<close>\nlemma kill_short_\\<alpha>:\n  assumes \"finite (uverts G)\"\n  shows \"\\<alpha> (kill_short G k) \\<le> \\<alpha> G\"\nusing assms\nproof (induct G k rule: kill_short_induct)\n  case (kill_vert G)\n  note kill_vert(3)\n  also have \"\\<alpha> (G -- (choose_v G k)) \\<le> \\<alpha> G\" by (rule \\<alpha>_remove_le)\n  finally show ?case using kill_vert by simp\nqed simp\n\ntext \\<open>Wellformedness (after @{term kill_short}):\\<close>\nlemma kill_short_uwellformed:\n  assumes \"finite (uverts G)\" \"uwellformed G\"\n  shows \"uwellformed (kill_short G k)\"\nusing assms\nproof (induct G k rule: kill_short_induct)\n  case (kill_vert G)\n  from kill_vert.prems have \"uwellformed (G -- (choose_v G k))\"\n    by (auto simp: uwellformed_def remove_vertex_def)\n  with kill_vert.hyps show ?case by simp\nqed simp\n\n\nsection \\<open>The Chromatic-Girth Theorem\\<close>\n\ntext \\<open>Probability of Independent Edges:\\<close>\nlemma (in edge_space) random_prob_independent:\n  assumes \"n \\<ge> k\" \"k \\<ge> 2\"\n  shows \"prob {es \\<in> space P. k \\<le> \\<alpha> (edge_ugraph es)}\n    \\<le> (n choose k)*(1-p)^(k choose 2)\"\nproof -\n  let \"?k_sets\" = \"{vs. vs \\<subseteq> S_verts \\<and> card vs = k}\"\n\n  { fix vs assume A: \"vs \\<in> ?k_sets\"\n    then have B: \"all_edges vs \\<subseteq> S_edges\"\n      unfolding all_edges_def S_edges_def by blast\n\n    have \"{es \\<in> space P. vs \\<in> independent_sets (edge_ugraph es)}\n        = cylinder S_edges {} (all_edges vs)\" (is \"?L = _\")\n      using A by (auto simp: independent_sets_def edge_ugraph_def space_eq cylinder_def)\n    then have \"prob ?L = (1-p)^(k choose 2)\"\n      using A B finite by (auto simp: cylinder_prob card_all_edges dest: finite_subset)\n  }\n  note prob_k_indep = this\n    \\<comment> \\<open>probability that a fixed set of k vertices is independent in a random graph\\<close>\n\n  have \"{es \\<in> space P. k \\<in> card ` independent_sets (edge_ugraph es)}\n    = (\\<Union>vs \\<in> ?k_sets. {es \\<in> space P. vs \\<in> independent_sets (edge_ugraph es)})\" (is \"?L = ?R\")\n    unfolding image_def space_eq independent_sets_def by auto\n  then have \"prob ?L \\<le> (\\<Sum>vs \\<in> ?k_sets. prob {es \\<in> space P. vs \\<in> independent_sets (edge_ugraph es)})\"\n    by (auto intro!: finite_measure_subadditive_finite simp: space_eq sets_eq)\n  also have \"\\<dots> = (n choose k)*((1 - p) ^ (k choose 2))\"\n    by (simp add: prob_k_indep S_verts_def n_subsets)\n  finally show ?thesis using \\<open>k \\<ge> 2\\<close> by (simp add: le_\\<alpha>_iff)\nqed\n\ntext \\<open>Almost never many independent edges:\\<close>\nlemma almost_never_le_\\<alpha>:\n  fixes k :: nat\n    and p :: \"nat \\<Rightarrow> real\"\n  assumes p_prob: \"\\<forall>\\<^sup>\\<infinity> n. 0 < p n \\<and> p n < 1\"\n  assumes [arith]: \"k > 0\"\n  assumes N_prop: \"\\<forall>\\<^sup>\\<infinity> n. (6 * k * ln n)/n \\<le> p n\"\n  shows \"(\\<lambda>n. probGn p n (\\<lambda>es. 1/2*n/k \\<le> \\<alpha> (edge_space.edge_ugraph n es))) \\<longlonglongrightarrow> 0\"\n    (is \"(\\<lambda>n. ?prob_fun n) \\<longlonglongrightarrow> 0\")\nproof -\n  let \"?prob_fun_raw n\" = \"probGn p n (\\<lambda>es. nat(ceiling (1/2*n/k)) \\<le> \\<alpha> (edge_space.edge_ugraph n es))\"\n\n  define r where \"r n = 1 / 2 * n / k\" for n :: nat\n  let ?nr = \"\\<lambda>n. nat(ceiling (r n))\"\n\n  have r_pos: \"\\<And>n. 0 < n \\<Longrightarrow> 0 < r n \" by (auto simp: r_def field_simps)\n\n  have nr_bounds: \"\\<forall>\\<^sup>\\<infinity> n. 2 \\<le> ?nr n \\<and> ?nr n \\<le> n\"\n    by (intro eventually_sequentiallyI[of \"4 * k\"])\n       (simp add: r_def nat_ceiling_le_eq le_natceiling_iff field_simps)\n\n  from nr_bounds p_prob have ev_prob_fun_raw_le:\n    \"\\<forall>\\<^sup>\\<infinity> n. probGn p n (\\<lambda>es. ?nr n\\<le> \\<alpha> (edge_space.edge_ugraph n es))\n      \\<le> (n * exp (- p n * (real (?nr n) - 1) / 2)) powr ?nr n\"\n    (is \"\\<forall>\\<^sup>\\<infinity> n. ?prob_fun_raw_le n\")\n  proof (rule eventually_elim2)\n    fix n :: nat assume A: \"2 \\<le> ?nr n \\<and> ?nr n \\<le> n\" \"0 < p n \\<and>p n < 1\"\n    then interpret pG: edge_space n \"p n\" by unfold_locales auto\n\n    have r: \"real (?nr n - Suc 0) = real (?nr n) - Suc 0\" using A by auto\n\n    have [simp]: \"n>0\" using A by linarith\n    have \"probGn p n (\\<lambda>es. ?nr n \\<le> \\<alpha> (edge_space.edge_ugraph n es))\n        \\<le> (n choose ?nr n) * (1 - p n)^(?nr n choose 2)\"\n      using A by (auto intro: pG.random_prob_independent)\n    also have \"\\<dots> \\<le> n powr ?nr n * (1 - p n) powr (?nr n choose 2)\"\n      using A  by (simp add: powr_realpow of_nat_power [symmetric] binomial_le_pow  del: of_nat_power)\n    also have \"\\<dots> = n powr ?nr n * (1 - p n) powr (?nr n * (?nr n - 1) / 2)\"\n      by (cases \"even (?nr n - 1)\")\n        (auto simp add: n_choose_2_nat real_of_nat_div)\n    also have \"\\<dots> = n powr ?nr n * ((1 - p n) powr ((?nr n - 1) / 2)) powr ?nr n\"\n      by (auto simp add: powr_powr r ac_simps)\n    also have \"\\<dots> \\<le> (n * exp (- p n * (?nr n - 1) / 2)) powr ?nr n\"\n    proof -\n      have \"(1 - p n) powr ((?nr n - 1) / 2) \\<le> exp (- p n) powr ((?nr n - 1) / 2)\"\n        using A by (auto simp: powr_mono2 diff_conv_add_uminus simp del: add_uminus_conv_diff)\n      also have \"\\<dots> = exp (- p n * (?nr n - 1) / 2)\" by (auto simp: powr_def)\n      finally show ?thesis\n        using A by (auto simp: powr_mono2 powr_mult)\n    qed\n    finally show \"probGn p n (\\<lambda>es. ?nr n \\<le> \\<alpha> (edge_space.edge_ugraph n es))\n      \\<le> (n * exp (- p n * (real (?nr n) - 1) / 2)) powr ?nr n\"\n      using A r by simp\n  qed\n\n  from p_prob N_prop\n  have ev_expr_bound: \"\\<forall>\\<^sup>\\<infinity> n. n * exp (-p n * (real (?nr n) - 1) / 2) \\<le> (exp 1 / n) powr (1 / 2)\"\n  proof (elim eventually_rev_mp, intro eventually_sequentiallyI conjI impI)\n    fix n assume n_bound[arith]: \"2 \\<le> n\"\n      and p_bound: \"0 < p n \\<and> p n < 1\" \"(6 * k * ln n) / n \\<le> p n\"\n    have r_bound: \"r n \\<le> ?nr n\" by (rule real_nat_ceiling_ge)\n\n    have \"n * exp (-p n * (real (?nr n)- 1) / 2) \\<le> n * exp (- 3 / 2 * ln n + p n / 2)\"\n    proof -\n      have \"0 < ln n\" using \"n_bound\" by auto\n      then have \"(3 / 2) * ln n \\<le> ((6 * k * ln n) / n) * (?nr n / 2)\"\n        using r_bound le_of_int_ceiling[of \"n/2*k\"]\n        by (simp add: r_def field_simps del: le_of_int_ceiling)\n      also have \"\\<dots> \\<le> p n * (?nr n / 2)\"\n        using n_bound p_bound r_bound r_pos[of n] by (auto simp: field_simps)\n      finally show ?thesis using r_bound by (auto simp: field_simps)\n    qed\n    also have \"\\<dots> \\<le> n * n powr (- 3 / 2) * exp 1 powr (1 / 2)\"\n      using p_bound by (simp add: powr_def exp_add [symmetric])\n    also have \"\\<dots> \\<le> n powr (-1 / 2) * exp 1 powr (1 / 2)\" by (simp add: powr_mult_base)\n    also have \"\\<dots> = (exp 1 / n) powr (1/2)\"\n      by (simp add: powr_divide powr_minus_divide)\n    finally show \"n * exp (- p n * (real (?nr n) - 1) / 2) \\<le> (exp 1 / n) powr (1 / 2)\" .\n  qed\n\n  have ceil_bound: \"\\<And>G n. 1/2*n/k \\<le> \\<alpha> G \\<longleftrightarrow> nat(ceiling (1/2*n/k)) \\<le> \\<alpha> G\"\n    by (case_tac \"\\<alpha> G\") (auto simp: nat_ceiling_le_eq)\n\n  show ?thesis\n  proof (unfold ceil_bound, rule real_tendsto_sandwich)\n    show \"(\\<lambda>n. 0) \\<longlonglongrightarrow> 0\"\n        \"(\\<lambda>n. (exp 1 / n) powr (1 / 2)) \\<longlonglongrightarrow> 0\"\n        \"\\<forall>\\<^sup>\\<infinity> n. 0 \\<le> ?prob_fun_raw n\"\n      using p_prob by (auto intro: measure_nonneg LIMSEQ_inv_powr elim: eventually_mono)\n  next\n    from nr_bounds ev_expr_bound ev_prob_fun_raw_le\n    show \"\\<forall>\\<^sup>\\<infinity> n. ?prob_fun_raw n \\<le> (exp 1 / n) powr (1 / 2)\"\n    proof (elim eventually_rev_mp, intro eventually_sequentiallyI impI conjI)\n      fix n assume A: \"3 \\<le> n\"\n        and nr_bounds: \"2 \\<le> ?nr n \\<and> ?nr n \\<le> n\"\n        and prob_fun_raw_le: \"?prob_fun_raw_le n\"\n        and expr_bound: \"n * exp (- p n * (real (nat(ceiling (r n))) - 1) / 2) \\<le> (exp 1 / n) powr (1 / 2)\"\n\n      have \"exp 1 < (3 :: real)\" by (approximation 6)\n      then have \"(exp 1 / n) powr (1 / 2) \\<le> 1 powr (1 / 2)\"\n        using A by (intro powr_mono2) (auto simp: field_simps)\n      then have ep_bound: \"(exp 1 / n) powr (1 / 2) \\<le> 1\" by simp\n\n      have \"?prob_fun_raw n \\<le> (n * exp (- p n * (real (?nr n) - 1) / 2)) powr (?nr n)\"\n        using prob_fun_raw_le by (simp add: r_def)\n      also have \"\\<dots> \\<le> ((exp 1 / n) powr (1 / 2)) powr ?nr n\"\n        using expr_bound A by (auto simp: powr_mono2)\n      also have \"\\<dots> \\<le> ((exp 1 / n) powr (1 / 2))\"\n        using nr_bounds ep_bound A by (auto simp: powr_le_one_le)\n      finally show \"?prob_fun_raw n \\<le> (exp 1 / n) powr (1 / 2)\" .\n    qed\n  qed\nqed\n\ntext \\<open>Mean number of k-cycles in a graph. (Or rather of paths describing a circle of length @{term k}):\\<close>\nlemma (in edge_space) mean_k_cycles:\n  assumes \"3 \\<le> k\" \"k < n\"\n  shows \"(\\<integral>es. card {c \\<in> ucycles (edge_ugraph es). uwalk_length c = k} \\<partial> P)\n    = of_nat (fact n div fact (n - k)) * p ^ k\"\nproof -\n  let ?k_cycle = \"\\<lambda>es c k. c \\<in> ucycles (edge_ugraph es) \\<and> uwalk_length c = k\"\n  define C where \"C k = {c. ?k_cycle S_edges c k}\" for k\n    \\<comment> \\<open>@{term \"C k\"} is the set of all possible cycles of size @{term k} in @{term \"edge_ugraph S_edges\"}\\<close>\n  define XG  where \"XG es = {c. ?k_cycle es c k}\" for es\n    \\<comment> \\<open>@{term \"XG es\"} is the set of cycles contained in a @{term \"edge_ugraph es\"}\\<close>\n  define XC where \"XC c = {es \\<in> space P. ?k_cycle es c k}\" for c\n    \\<comment> \\<open>\"@{term \"XC c\"} is the set of graphs (edge sets) containing a cycle c\"\\<close>\n  then have XC_in_sets: \"\\<And>c. XC c \\<in> sets P\"\n      and XC_cyl: \"\\<And>c. c \\<in> C k \\<Longrightarrow> XC c = cylinder S_edges (set (uwalk_edges c)) {}\"\n    by (auto simp: ucycles_def space_eq uwalks_def C_def cylinder_def sets_eq)\n\n  have \"(\\<integral>es. card {c \\<in> ucycles (edge_ugraph es). uwalk_length c = k} \\<partial> P)\n      =  (\\<Sum>x\\<in>space P. card (XG x) * prob {x})\"\n    by (simp add: XG_def integral_finite_singleton space_eq)\n  also have \"\\<dots> = (\\<Sum>c\\<in>C k. prob (cylinder S_edges (set (uwalk_edges c)) {}))\"\n  proof -\n    have XG_Int_C: \"\\<And>s. s \\<in> space P \\<Longrightarrow> C k \\<inter> XG s = XG s\"\n      unfolding XG_def C_def ucycles_def uwalks_def edge_ugraph_def by auto\n    have fin_XC: \"\\<And>k. finite (XC k)\" and fin_C: \"finite (C k)\"\n      unfolding C_def XC_def by (auto simp: finite_edges space_eq intro!: finite_ucycles)\n\n    have \"(\\<Sum>x\\<in>space P. card (XG x) * prob {x}) = (\\<Sum>x\\<in>space P. (\\<Sum>c \\<in> XG x. prob {x}))\"\n      by simp\n    also have \"\\<dots> = (\\<Sum>x\\<in>space P. (\\<Sum>c \\<in> C k. if c \\<in> XG x then prob {x} else 0))\"\n      using fin_C by (simp add: sum.If_cases) (simp add: XG_Int_C)\n    also have \"\\<dots> = (\\<Sum>c \\<in> C k. (\\<Sum> x \\<in> space P \\<inter> XC c. prob {x}))\"\n      using finite_edges by (subst sum.swap) (simp add: sum.inter_restrict XG_def XC_def space_eq)\n    also have \"\\<dots> = (\\<Sum>c \\<in> C k. prob (XC c))\"\n      using fin_XC XC_in_sets\n      by (auto simp add: prob_eq sets_eq space_eq intro!: sum.cong)\n    finally show ?thesis by (simp add: XC_cyl)\n  qed\n  also have \"\\<dots> = (\\<Sum>c\\<in>C k. p ^ k)\"\n  proof -\n    have \"\\<And>x. x \\<in> C k \\<Longrightarrow> card (set (uwalk_edges x)) = uwalk_length x\"\n      by (auto simp: uwalk_length_def C_def ucycles_distinct_edges intro: distinct_card)\n    then show ?thesis by (auto simp: C_def ucycles_def uwalks_def cylinder_prob)\n  qed\n  also have \"\\<dots> = of_nat (fact n div fact (n - k)) * p ^ k\"\n  proof -\n    have inj_last_Cons: \"\\<And>A. inj_on (\\<lambda>es. last es # es) A\" by (rule inj_onI) simp\n    { fix xs A assume \"3 \\<le> length xs - Suc 0\" \"hd xs = last xs\"\n      then have \"xs \\<in> (\\<lambda>xs. last xs # xs) ` A \\<longleftrightarrow> tl xs \\<in> A\"\n        by (cases xs) (auto simp: inj_image_mem_iff[OF inj_last_Cons] split: if_split_asm) }\n    note image_mem_iff_inst = this\n\n    { fix xs have \"xs \\<in> uwalks (edge_ugraph S_edges) \\<Longrightarrow> set (tl xs) \\<subseteq> S_verts\"\n        unfolding uwalks_def by (induct xs) auto }\n    moreover\n    { fix xs assume \"set xs \\<subseteq> S_verts\" \"2 \\<le> length xs\" \"distinct xs\"\n      then have \"(last xs # xs) \\<in> uwalks (edge_ugraph S_edges)\"\n      proof (induct xs rule: uwalk_edges.induct)\n        case (3 x y ys)\n        have S_edges_memI: \"\\<And>x y. x \\<in> S_verts \\<Longrightarrow> y \\<in> S_verts \\<Longrightarrow> x \\<noteq> y \\<Longrightarrow> {x, y} \\<in> S_edges\"\n          unfolding S_edges_def all_edges_def image_def by auto\n\n        have \"ys \\<noteq> [] \\<Longrightarrow> set ys \\<subseteq> S_verts \\<Longrightarrow> last ys \\<in> S_verts\"  by auto\n        with 3 show ?case\n          by (auto simp add: uwalks_def Suc_le_eq intro: S_edges_memI)\n      qed simp_all}\n    moreover note \\<open>3 \\<le> k\\<close>\n    ultimately\n    have \"C k = (\\<lambda>xs. last xs # xs) ` {xs. length xs = k \\<and> distinct xs \\<and> set xs \\<subseteq> S_verts}\"\n      by (auto simp: C_def ucycles_def uwalk_length_conv image_mem_iff_inst)\n    moreover have \"card S_verts = n\" by (simp add: S_verts_def)\n    ultimately have \"card (C k) = fact n div fact (n - k)\"\n      using \\<open>k < n\\<close>\n      by (simp add: card_image[OF inj_last_Cons] card_lists_distinct_length_eq' fact_div_fact)\n    then show ?thesis by simp\n  qed\n  finally show ?thesis by simp\nqed\n\ntext \\<open>Girth-Chromatic number theorem:\\<close>\ntheorem girth_chromatic:\n  fixes l :: nat\n  shows \"\\<exists>G. uwellformed G \\<and> l < girth G \\<and> l < chromatic_number G\"\nproof -\n  define k where \"k = max 3 l\"\n  define \\<epsilon> where \"\\<epsilon> = 1 / (2 * k)\"\n  define p where \"p n = real n powr (\\<epsilon> - 1)\" for n :: nat\n\n  let ?ug = edge_space.edge_ugraph\n\n  define short_count where \"short_count g = card (short_cycles g k)\" for g\n    \\<comment> \\<open>This random variable differs from the one used in the proof of theorem 11.2.2,\n          as we count the number of paths describing a circle, not the circles themselves\\<close>\n\n  from k_def have \"3 \\<le> k\" \"l \\<le> k\" by auto\n  from \\<open>3 \\<le> k\\<close> have \\<epsilon>_props: \"0 < \\<epsilon>\" \"\\<epsilon> < 1 / k\" \"\\<epsilon> < 1\" by (auto simp: \\<epsilon>_def field_simps)\n\n  have ev_p: \"\\<forall>\\<^sup>\\<infinity> n. 0 < p n \\<and> p n < 1\"\n  proof (rule eventually_sequentiallyI)\n    fix n :: nat assume \"2 \\<le> n\"\n    with \\<open>\\<epsilon> < 1\\<close> have \"n powr (\\<epsilon> - 1) < 1\" by (auto intro!: powr_less_one)\n    then show \"0 < p n \\<and> p n < 1\" using \\<open>2 \\<le> n\\<close>\n      by (auto simp: p_def)\n  qed\n  then\n  have prob_short_count_le: \"\\<forall>\\<^sup>\\<infinity> n. probGn p n (\\<lambda>es. (real n/2) \\<le> short_count (?ug n es))\n      \\<le> 2 * (k - 2) * n powr (\\<epsilon> * k - 1)\"  (is \"\\<forall>\\<^sup>\\<infinity> n. ?P n\")\n  proof (elim eventually_rev_mp, intro eventually_sequentiallyI impI)\n    fix n :: nat assume A: \"Suc k \\<le> n\" \"0 < p n \\<and> p n < 1\"\n    then interpret pG: edge_space n \"p n\" by unfold_locales auto\n    have \"1 \\<le> n\" using A by auto\n\n    define mean_short_count where \"mean_short_count = (\\<integral>es. short_count (?ug n es) \\<partial> pG.P)\"\n\n    have mean_short_count_le: \"mean_short_count \\<le> (k - 2) * n powr (\\<epsilon> * k)\"\n    proof -\n      have small_empty: \"\\<And>es k. k \\<le> 2 \\<Longrightarrow> short_cycles (edge_space.edge_ugraph n es) k = {}\"\n          by (auto simp add: short_cycles_def ucycles_def)\n      have short_count_conv: \"\\<And>es. short_count (?ug n es) = (\\<Sum>i=3..k. real (card {c \\<in> ucycles (?ug n es). uwalk_length c = i}))\"\n      proof (unfold short_count_def, induct k)\n        case 0 with small_empty show ?case by auto\n      next\n        case (Suc k)\n        show ?case proof (cases \"Suc k \\<le> 2\")\n          case True with small_empty show ?thesis by auto\n        next\n          case False\n          have \"{c \\<in> ucycles (?ug n es). uwalk_length c \\<le> Suc k}\n              = {c \\<in> ucycles (?ug n es). uwalk_length c \\<le> k} \\<union> {c \\<in> ucycles (?ug n es). uwalk_length c = Suc k}\"\n            by auto\n          moreover\n          have \"finite (uverts (edge_space.edge_ugraph n es))\" by auto\n          ultimately\n          have \"card {c \\<in> ucycles (?ug n es). uwalk_length c \\<le> Suc k}\n            = card {c \\<in> ucycles (?ug n es). uwalk_length c \\<le> k} + card {c \\<in> ucycles (?ug n es). uwalk_length c = Suc k}\"\n            using finite_ucycles by (subst card_Un_disjoint[symmetric]) auto\n          then show ?thesis\n            using Suc False unfolding short_cycles_def by (auto simp: not_le)\n        qed\n      qed\n\n      have \"mean_short_count = (\\<Sum>i=3..k. \\<integral>es. card {c \\<in> ucycles (?ug n es). uwalk_length c = i} \\<partial> pG.P)\"\n        unfolding mean_short_count_def short_count_conv\n        by (subst Bochner_Integration.integral_sum) (auto intro: pG.integral_finite_singleton)\n      also have \"\\<dots> = (\\<Sum>i\\<in>{3..k}. of_nat (fact n div fact (n - i)) * p n ^ i)\"\n        using A by (simp add: pG.mean_k_cycles)\n      also have \"\\<dots> \\<le> (\\<Sum> i\\<in>{3..k}. n ^ i * p n ^ i)\"\n        apply (rule sum_mono)\n        by (meson A fact_div_fact_le_pow  Suc_leD atLeastAtMost_iff of_nat_le_iff order_trans real_mult_le_cancel_iff1 zero_less_power)\n      also have \"... \\<le> (\\<Sum> i\\<in>{3..k}. n powr (\\<epsilon> * k))\"\n        using \\<open>1 \\<le> n\\<close> \\<open>0 < \\<epsilon>\\<close> A\n        by (intro sum_mono) (auto simp: p_def field_simps powr_mult_base powr_powr\n          powr_realpow[symmetric] powr_mult[symmetric] powr_add[symmetric])\n      finally show ?thesis by simp\n    qed\n\n    have \"pG.prob {es \\<in> space pG.P. n/2 \\<le> short_count (?ug n es)} \\<le> mean_short_count / (n/2)\"\n      unfolding mean_short_count_def using \\<open>1 \\<le> n\\<close>\n      by (intro pG.Markov_inequality) (auto simp: short_count_def)\n    also have \"\\<dots> \\<le> 2 * (k - 2) * n powr (\\<epsilon> * k - 1)\"\n    proof -\n      have \"mean_short_count / (n / 2) \\<le> 2 * (k - 2) * (1 / n powr 1) * n powr (\\<epsilon> * k)\"\n        using mean_short_count_le \\<open>1 \\<le> n\\<close> by (simp add: field_simps)\n      then show ?thesis by (simp add: powr_diff algebra_simps)\n    qed\n    finally show \"?P n\" .\n  qed\n\n  define pf_short_count pf_\\<alpha>\n    where \"pf_short_count n = probGn p n (\\<lambda>es. n/2 \\<le> short_count (?ug n es))\"\n      and \"pf_\\<alpha> n = probGn p n (\\<lambda>es. 1/2 * n/k \\<le> \\<alpha> (edge_space.edge_ugraph n es))\"\n    for n\n\n  have ev_short_count_le: \"\\<forall>\\<^sup>\\<infinity> n. pf_short_count n < 1 / 2\"\n  proof -\n    have \"\\<epsilon> * k - 1 < 0\"\n      using \\<epsilon>_props \\<open>3 \\<le> k\\<close> by (auto simp: field_simps)\n    then have \"(\\<lambda>n. 2 * (k - 2) * n powr (\\<epsilon> * k - 1)) \\<longlonglongrightarrow> 0\" (is \"?bound \\<longlonglongrightarrow> 0\")\n      by (intro tendsto_mult_right_zero LIMSEQ_neg_powr)\n    then have \"\\<forall>\\<^sup>\\<infinity> n. dist (?bound n) 0  < 1 / 2\"\n      by (rule tendstoD) simp\n    with prob_short_count_le show ?thesis\n      by (rule eventually_elim2) (auto simp: dist_real_def pf_short_count_def)\n  qed\n\n  have lim_\\<alpha>: \"pf_\\<alpha> \\<longlonglongrightarrow> 0\"\n  proof -\n    have \"0 < k\" using \\<open>3 \\<le> k\\<close> by simp\n\n    have \"\\<forall>\\<^sup>\\<infinity> n. (6*k) * ln n / n \\<le> p n \\<longleftrightarrow> (6*k) * ln n * n powr - \\<epsilon> \\<le> 1\"\n    proof (rule eventually_sequentiallyI)\n     fix n :: nat assume \"1 \\<le> n\"\n      then have \"(6 * k) * ln n / n \\<le> p n \\<longleftrightarrow> (6*k) * ln n * (n powr - 1) \\<le> n powr (\\<epsilon> - 1)\"\n        by  (subst powr_minus) (simp add: divide_inverse p_def)\n      also have \"\\<dots> \\<longleftrightarrow> (6*k) * ln n * ((n powr - 1) / (n powr (\\<epsilon> - 1))) \\<le> n powr (\\<epsilon> - 1) / (n powr (\\<epsilon> - 1))\"\n        using \\<open>1 \\<le> n\\<close> by (auto simp: field_simps)\n      also have \"\\<dots> \\<longleftrightarrow> (6*k) * ln n * n powr - \\<epsilon> \\<le> 1\"\n        by (simp add: powr_diff [symmetric] )\n      finally show \"(6*k) * ln n / n \\<le> p n \\<longleftrightarrow> (6*k) * ln n * n powr - \\<epsilon> \\<le> 1\" .\n    qed\n    then have \"(\\<forall>\\<^sup>\\<infinity> n. (6 * k) * ln n / real n \\<le> p n)\n        \\<longleftrightarrow> (\\<forall>\\<^sup>\\<infinity> n. (6*k) * ln n * n powr - \\<epsilon> \\<le> 1)\"\n      by (rule eventually_subst)\n    also have \"\\<forall>\\<^sup>\\<infinity> n. (6*k) * ln n * n powr - \\<epsilon> \\<le> 1\"\n    proof -\n      { fix n :: nat assume \"0 < n\"\n        have \"ln (real n) \\<le> n powr (\\<epsilon>/2) / (\\<epsilon>/2)\"\n          using \\<open>0 < n\\<close> \\<open>0 < \\<epsilon>\\<close> by (intro ln_powr_bound) auto\n        also have \"\\<dots> \\<le> 2/\\<epsilon> * n powr (\\<epsilon>/2)\" by (auto simp: field_simps)\n        finally have \"(6*k) * ln n * (n powr - \\<epsilon>)  \\<le> (6*k) * (2/\\<epsilon> * n powr (\\<epsilon>/2)) * (n powr - \\<epsilon>)\"\n          using \\<open>0 < n\\<close> \\<open>0 < k\\<close> by (intro mult_right_mono mult_left_mono) auto\n        also have \"\\<dots> = 12*k/\\<epsilon> * n powr (-\\<epsilon>/2)\"\n          unfolding divide_inverse\n          by (auto simp: field_simps powr_minus[symmetric] powr_add[symmetric])\n        finally have \"(6*k) * ln n * (n powr - \\<epsilon>) \\<le> 12*k/\\<epsilon> * n powr (-\\<epsilon>/2)\" .\n      }\n      then have \"\\<forall>\\<^sup>\\<infinity> n. (6*k) * ln n * (n powr - \\<epsilon>) \\<le> 12*k/\\<epsilon> * n powr (-\\<epsilon>/2)\"\n        by (intro eventually_sequentiallyI[of 1]) auto\n      also have \"\\<forall>\\<^sup>\\<infinity> n. 12*k/\\<epsilon> * n powr (-\\<epsilon>/2) \\<le> 1\"\n      proof -\n        have \"(\\<lambda>n. 12*k/\\<epsilon> * n powr (-\\<epsilon>/2)) \\<longlonglongrightarrow> 0\"\n          using \\<open>0 < \\<epsilon>\\<close> by (intro tendsto_mult_right_zero LIMSEQ_neg_powr) auto\n        then show ?thesis\n          using \\<open>0 < \\<epsilon>\\<close> by - (drule tendstoD[where e=1], auto elim: eventually_mono)\n      qed\n      finally (eventually_le_le) show ?thesis .\n    qed\n    finally have \"\\<forall>\\<^sup>\\<infinity> n. real (6 * k) * ln (real n) / real n \\<le> p n\" .\n    with ev_p \\<open>0 < k\\<close> show ?thesis unfolding pf_\\<alpha>_def by (rule almost_never_le_\\<alpha>)\n  qed\n\n  from ev_short_count_le lim_\\<alpha>[THEN tendstoD, of \"1/2\"] ev_p\n  have \"\\<forall>\\<^sup>\\<infinity> n. 0 < p n \\<and> p n < 1 \\<and> pf_short_count n < 1/2 \\<and> pf_\\<alpha> n < 1/2\"\n    by simp (elim eventually_rev_mp, auto simp: eventually_sequentially dist_real_def)\n  then obtain n where \"0 < p n\" \"p n < 1\" and [arith]: \"0 < n\"\n      and probs: \"pf_short_count n < 1/2\" \"pf_\\<alpha> n < 1/2\"\n    by (auto simp: eventually_sequentially)\n  then interpret ES: edge_space n \"(p n)\" by unfold_locales auto\n\n  have rest_compl: \"\\<And>A P. A - {x\\<in>A. P x} = {x\\<in>A. \\<not>P x}\" by blast\n\n  from probs have \"ES.prob ({es \\<in> space ES.P. n/2 \\<le> short_count (?ug n es)}\n      \\<union> {es \\<in> space ES.P. 1/2 * n/k \\<le> \\<alpha> (?ug n es)}) \\<le> pf_short_count n + pf_\\<alpha> n\"\n    unfolding pf_short_count_def pf_\\<alpha>_def  by (subst ES.finite_measure_subadditive) auto\n  also have \"\\<dots> < 1\" using probs by auto\n  finally have \"0 < ES.prob (space ES.P - ({es \\<in> space ES.P. n/2 \\<le> short_count (?ug n es)}\n      \\<union> {es \\<in> space ES.P. 1/2 * n/k \\<le> \\<alpha> (?ug n es)}))\" (is \"0 < ES.prob ?S\")\n    by (subst ES.prob_compl) auto\n  also have \"?S = {es \\<in> space ES.P. short_count (?ug n es) < n/2 \\<and> \\<alpha> (?ug n es) < 1/2* n/k}\" (is \"\\<dots> = ?C\")\n    by (auto simp: not_less rest_compl)\n  finally have \"?C \\<noteq> {}\" by (intro notI) (simp only:, auto)\n  then obtain es where es_props: \"es \\<in> space ES.P\"\n      \"short_count (?ug n es) < n/2\" \"\\<alpha> (?ug n es) < 1/2 * n/k\"\n    by auto\n    \\<comment> \\<open>now we obtained a high colored graph (few independent nodes) with almost no short cycles\\<close>\n\n  define G where \"G = ?ug n es\"\n  define H where \"H = kill_short G k\"\n\n  have G_props: \"uverts G = {1..n}\" \"finite (uverts G)\" \"short_count G < n/2\" \"\\<alpha> G < 1/2 * n/k\"\n    unfolding G_def using es_props by (auto simp: ES.S_verts_def)\n\n  have \"uwellformed G\" by (auto simp: G_def uwellformed_def all_edges_def ES.S_edges_def)\n  with G_props have T1: \"uwellformed H\" unfolding H_def by (intro kill_short_uwellformed)\n\n  have \"enat l \\<le> enat k\" using \\<open>l \\<le> k\\<close> by simp\n  also have \"\\<dots> < girth H\" using G_props by (auto simp: kill_short_large_girth H_def)\n  finally have T2: \"l < girth H\" .\n\n  have card_H: \"n/2 \\<le> card (uverts H)\"\n    using G_props es_props kill_short_order_of_graph[of G k] by (simp add: short_count_def H_def)\n\n  then have uverts_H: \"uverts H \\<noteq> {}\" \"0 < card (uverts H)\" by auto\n  then have \"0 < \\<alpha> H\" using zero_less_\\<alpha> uverts_H by auto\n\n  have \\<alpha>_HG: \"\\<alpha> H \\<le> \\<alpha> G\"\n    unfolding H_def G_def by (auto intro: kill_short_\\<alpha>)\n\n  have \"enat l \\<le> ereal k\" using \\<open>l \\<le> k\\<close> by auto\n  also have \"\\<dots> < (n/2) / \\<alpha> G\" using G_props \\<open>3 \\<le> k\\<close>\n    by (cases \"\\<alpha> G\") (auto simp: field_simps)\n  also have \"\\<dots> \\<le> (n/2) / \\<alpha> H\" using \\<alpha>_HG \\<open>0 < \\<alpha> H\\<close>\n    by (auto simp: ereal_of_enat_pushout intro!: ereal_divide_left_mono)\n  also have \"\\<dots> \\<le> card (uverts H) / \\<alpha> H\" using card_H \\<open>0 < \\<alpha> H\\<close>\n    by (auto intro!: ereal_divide_right_mono)\n  also have \"\\<dots> \\<le> chromatic_number H\" using uverts_H T1 by (intro chromatic_lb) auto\n  finally have T3: \"l < chromatic_number H\"\n    by (simp del: ereal_of_enat_simps)\n\n  from T1 T2 T3 show ?thesis by fast\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/Girth_Chromatic/Girth_Chromatic.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8807970842359877, "lm_q2_score": 0.826711791935942, "lm_q1q2_score": 0.7281653358406862}}
{"text": "section \\<open>\\isaheader{Orderings By Comparison Operator}\\<close>\ntheory Intf_Comp\nimports \n  \"../../../Automatic_Refinement/Automatic_Refinement\"\nbegin\n\nsubsection \\<open>Basic Definitions\\<close>\n\ndatatype comp_res = LESS | EQUAL | GREATER\n\nconsts i_comp_res :: interface\nabbreviation \"comp_res_rel \\<equiv> Id :: (comp_res \\<times> _) set\"\nlemmas [autoref_rel_intf] = REL_INTFI[of comp_res_rel i_comp_res]\n\ndefinition \"comp2le cmp a b \\<equiv> \n  case cmp a b of LESS \\<Rightarrow> True | EQUAL \\<Rightarrow> True | GREATER \\<Rightarrow> False\"\n\ndefinition \"comp2lt cmp a b \\<equiv> \n  case cmp a b of LESS \\<Rightarrow> True | EQUAL \\<Rightarrow> False | GREATER \\<Rightarrow> False\"\n\ndefinition \"comp2eq cmp a b \\<equiv> \n  case cmp a b of LESS \\<Rightarrow> False | EQUAL \\<Rightarrow> True | GREATER \\<Rightarrow> False\"\n\nlocale linorder_on =\n  fixes D :: \"'a set\"\n  fixes cmp :: \"'a \\<Rightarrow> 'a \\<Rightarrow> comp_res\"\n  assumes lt_eq: \"\\<lbrakk>x\\<in>D; y\\<in>D\\<rbrakk> \\<Longrightarrow> cmp x y = LESS \\<longleftrightarrow> (cmp y x = GREATER)\"\n  assumes refl[simp, intro!]: \"x\\<in>D \\<Longrightarrow> cmp x x = EQUAL\"\n  assumes trans[trans]: \n    \"\\<lbrakk> x\\<in>D; y\\<in>D; z\\<in>D; cmp x y = LESS; cmp y z = LESS\\<rbrakk> \\<Longrightarrow> cmp x z = LESS\"\n    \"\\<lbrakk> x\\<in>D; y\\<in>D; z\\<in>D; cmp x y = LESS; cmp y z = EQUAL\\<rbrakk> \\<Longrightarrow> cmp x z = LESS\"\n    \"\\<lbrakk> x\\<in>D; y\\<in>D; z\\<in>D; cmp x y = EQUAL; cmp y z = LESS\\<rbrakk> \\<Longrightarrow> cmp x z = LESS\"\n    \"\\<lbrakk> x\\<in>D; y\\<in>D; z\\<in>D; cmp x y = EQUAL; cmp y z = EQUAL\\<rbrakk> \\<Longrightarrow> cmp x z = EQUAL\"\nbegin\n  abbreviation \"le \\<equiv> comp2le cmp\"\n  abbreviation \"lt \\<equiv> comp2lt cmp\"\n\n  lemma eq_sym: \"\\<lbrakk>x\\<in>D; y\\<in>D\\<rbrakk> \\<Longrightarrow> cmp x y = EQUAL \\<Longrightarrow> cmp y x = EQUAL\"\n    apply (cases \"cmp y x\")\n    using lt_eq lt_eq[symmetric]\n    by auto\nend\n\nabbreviation \"linorder \\<equiv> linorder_on UNIV\"\n\nlemma linorder_to_class:\n  assumes \"linorder cmp\" \n  assumes [simp]: \"\\<And>x y. cmp x y = EQUAL \\<Longrightarrow> x=y\"\n  shows \"class.linorder (comp2le cmp) (comp2lt cmp)\"\nproof -\n  interpret linorder_on UNIV cmp by fact\n  show ?thesis\n    apply (unfold_locales)\n    unfolding comp2le_def comp2lt_def\n    apply (auto split: comp_res.split comp_res.split_asm)\n    using lt_eq apply simp\n    using lt_eq apply simp\n    using lt_eq[symmetric] apply simp\n    apply (drule (1) trans[rotated 3], simp_all) []\n    apply (drule (1) trans[rotated 3], simp_all) []\n    apply (drule (1) trans[rotated 3], simp_all) []\n    apply (drule (1) trans[rotated 3], simp_all) []\n    using lt_eq apply simp\n    using lt_eq apply simp\n    using lt_eq[symmetric] apply simp\n    done\nqed\n\ndefinition \"dflt_cmp le lt a b \\<equiv> \n  if lt a b then LESS \n  else if le a b then EQUAL \n  else GREATER\"\n\nlemma (in linorder) class_to_linorder:\n  \"linorder (dflt_cmp (\\<le>) (<))\"\n  apply (unfold_locales)\n  unfolding dflt_cmp_def\n  by (auto split: if_split_asm)\n\nlemma restrict_linorder: \"\\<lbrakk>linorder_on D cmp ; D'\\<subseteq>D\\<rbrakk> \\<Longrightarrow> linorder_on D' cmp\"\n  apply (rule linorder_on.intro)\n  apply (drule (1) rev_subsetD)+\n  apply (erule (2) linorder_on.lt_eq)\n  apply (drule (1) rev_subsetD)+\n  apply (erule (1) linorder_on.refl)\n  apply (drule (1) rev_subsetD)+\n  apply (erule (5) linorder_on.trans)\n  apply (drule (1) rev_subsetD)+\n  apply (erule (5) linorder_on.trans)\n  apply (drule (1) rev_subsetD)+\n  apply (erule (5) linorder_on.trans)\n  apply (drule (1) rev_subsetD)+\n  apply (erule (5) linorder_on.trans)\n  done\n\nsubsection \\<open>Operations on Linear Orderings\\<close>\n\ntext \\<open>Map with injective function\\<close>\ndefinition cmp_img where \"cmp_img f cmp a b \\<equiv> cmp (f a) (f b)\"\n\nlemma img_linorder[intro?]: \n  assumes LO: \"linorder_on (f`D) cmp\"\n  shows \"linorder_on D (cmp_img f cmp)\"\n  apply unfold_locales\n  unfolding cmp_img_def\n  apply (rule linorder_on.lt_eq[OF LO], auto) []\n  apply (rule linorder_on.refl[OF LO], auto) []\n  apply (erule (1) linorder_on.trans[OF LO, rotated -2], auto) []\n  apply (erule (1) linorder_on.trans[OF LO, rotated -2], auto) []\n  apply (erule (1) linorder_on.trans[OF LO, rotated -2], auto) []\n  apply (erule (1) linorder_on.trans[OF LO, rotated -2], auto) []\n  done\n\ntext \\<open>Combine\\<close>\ndefinition \"cmp_combine D1 cmp1 D2 cmp2 a b \\<equiv> \n  if a\\<in>D1 \\<and> b\\<in>D1 then cmp1 a b\n  else if a\\<in>D1 \\<and> b\\<in>D2 then LESS\n  else if a\\<in>D2 \\<and> b\\<in>D1 then GREATER\n  else cmp2 a b\n\"\n\n(* TODO: Move *)\nlemma UnE': \n  assumes \"x\\<in>A\\<union>B\"\n  obtains \"x\\<in>A\" | \"x\\<notin>A\" \"x\\<in>B\"\n  using assms by blast\n\nlemma combine_linorder[intro?]:\n  assumes \"linorder_on D1 cmp1\"\n  assumes \"linorder_on D2 cmp2\"\n  assumes \"D = D1\\<union>D2\"\n  shows \"linorder_on D (cmp_combine D1 cmp1 D2 cmp2)\"\n  apply unfold_locales\n  unfolding cmp_combine_def\n  using assms apply -\n  apply (simp only:)\n  apply (elim UnE)\n  apply (auto dest: linorder_on.lt_eq) [4]\n\n  apply (simp only:)\n  apply (elim UnE)\n  apply (auto dest: linorder_on.refl) [2]\n\n  apply (simp only:)\n  apply (elim UnE')\n  apply simp_all [8]\n  apply (erule (5) linorder_on.trans)\n  apply (erule (5) linorder_on.trans)\n\n  apply (simp only:)\n  apply (elim UnE')\n  apply simp_all [8]\n  apply (erule (5) linorder_on.trans)\n  apply (erule (5) linorder_on.trans)\n\n  apply (simp only:)\n  apply (elim UnE')\n  apply simp_all [8]\n  apply (erule (5) linorder_on.trans)\n  apply (erule (5) linorder_on.trans)\n\n  apply (simp only:)\n  apply (elim UnE')\n  apply simp_all [8]\n  apply (erule (5) linorder_on.trans)\n  apply (erule (5) linorder_on.trans)\n  done\n\nsubsection \\<open>Universal Linear Ordering\\<close>\ntext \\<open>With Zorn's Lemma, we get a universal linear (even wf) ordering\\<close>\n\ndefinition \"univ_order_rel \\<equiv> (SOME r. well_order_on UNIV r)\"\ndefinition \"univ_cmp x y \\<equiv> \n  if x=y then EQUAL \n  else if (x,y)\\<in>univ_order_rel then LESS\n  else GREATER\"\n\nlemma univ_wo: \"well_order_on UNIV univ_order_rel\"\n  unfolding univ_order_rel_def\n  using well_order_on[of UNIV]\n  ..\n\nlemma univ_linorder[intro?]: \"linorder univ_cmp\"\n  apply unfold_locales\n  unfolding univ_cmp_def \n  apply (auto split: if_split_asm)\n  using univ_wo\n  apply -\n  unfolding well_order_on_def linear_order_on_def partial_order_on_def\n    preorder_on_def\n  apply (auto simp add: antisym_def) []\n  apply (unfold total_on_def, fast) []\n  apply (unfold trans_def, fast) []\n  apply (auto simp add: antisym_def) []\n  done\n\ntext \\<open>Extend any linear order to a universal order\\<close>\ndefinition \"cmp_extend D cmp \\<equiv> \n  cmp_combine D cmp UNIV univ_cmp\"\n\nlemma extend_linorder[intro?]: \n  \"linorder_on D cmp \\<Longrightarrow> linorder (cmp_extend D cmp)\"\n  unfolding cmp_extend_def\n  apply rule\n  apply assumption\n  apply rule\n  by simp\n\nsubsubsection \\<open>Lexicographic Order on Lists\\<close>  \n\nfun cmp_lex where\n  \"cmp_lex cmp [] [] = EQUAL\"\n| \"cmp_lex cmp [] _ = LESS\"\n| \"cmp_lex cmp _ [] = GREATER\"\n| \"cmp_lex cmp (a#l) (b#m) = (\n    case cmp a b of\n      LESS \\<Rightarrow> LESS\n    | EQUAL \\<Rightarrow> cmp_lex cmp l m\n    | GREATER \\<Rightarrow> GREATER)\"\n\nprimrec cmp_lex' where\n  \"cmp_lex' cmp [] m = (case m of [] \\<Rightarrow> EQUAL | _ \\<Rightarrow> LESS)\"\n| \"cmp_lex' cmp (a#l) m = (case m of [] \\<Rightarrow> GREATER | (b#m) \\<Rightarrow> \n    (case cmp a b of\n      LESS \\<Rightarrow> LESS\n    | EQUAL \\<Rightarrow> cmp_lex' cmp l m\n    | GREATER \\<Rightarrow> GREATER\n  ))\"\n\nlemma cmp_lex_alt: \"cmp_lex cmp l m = cmp_lex' cmp l m\"\n  apply (induct l arbitrary: m)\n  apply (auto split: comp_res.split list.split)\n  done\n\nlemma (in linorder_on) lex_linorder[intro?]:\n  \"linorder_on (lists D) (cmp_lex cmp)\"\nproof\n  fix l m\n  assume \"l\\<in>lists D\" \"m\\<in>lists D\"\n  thus \"(cmp_lex cmp l m = LESS) = (cmp_lex cmp m l = GREATER)\"\n    apply (induct cmp\\<equiv>cmp l m rule: cmp_lex.induct)\n    apply (auto split: comp_res.split simp: lt_eq)\n    apply (auto simp: lt_eq[symmetric])\n    done\nnext\n  fix x\n  assume \"x\\<in>lists D\"\n  thus \"cmp_lex cmp x x = EQUAL\"\n    by (induct x) auto\nnext\n  fix x y z\n  assume M: \"x\\<in>lists D\" \"y\\<in>lists D\" \"z\\<in>lists D\"\n\n  {\n    assume \"cmp_lex cmp x y = LESS\" \"cmp_lex cmp y z = LESS\"\n    thus \"cmp_lex cmp x z = LESS\"\n      using M\n      apply (induct cmp\\<equiv>cmp x y arbitrary: z rule: cmp_lex.induct)\n      apply (auto split: comp_res.split_asm comp_res.split)\n      apply (case_tac z, auto) []\n      apply (case_tac z,\n        auto split: comp_res.split_asm comp_res.split,\n        (drule (4) trans, simp)+\n      ) []\n      apply (case_tac z,\n        auto split: comp_res.split_asm comp_res.split,\n        (drule (4) trans, simp)+\n      ) []\n      done\n  }\n\n  {\n    assume \"cmp_lex cmp x y = LESS\" \"cmp_lex cmp y z = EQUAL\"\n    thus \"cmp_lex cmp x z = LESS\"\n      using M\n      apply (induct cmp\\<equiv>cmp x y arbitrary: z rule: cmp_lex.induct)\n      apply (auto split: comp_res.split_asm comp_res.split)\n      apply (case_tac z, auto) []\n      apply (case_tac z,\n        auto split: comp_res.split_asm comp_res.split,\n        (drule (4) trans, simp)+\n      ) []\n      apply (case_tac z,\n        auto split: comp_res.split_asm comp_res.split,\n        (drule (4) trans, simp)+\n      ) []\n      done\n  }\n\n  {\n    assume \"cmp_lex cmp x y = EQUAL\" \"cmp_lex cmp y z = LESS\"\n    thus \"cmp_lex cmp x z = LESS\"\n      using M\n      apply (induct cmp\\<equiv>cmp x y arbitrary: z rule: cmp_lex.induct)\n      apply (auto split: comp_res.split_asm comp_res.split)\n      apply (case_tac z,\n        auto split: comp_res.split_asm comp_res.split,\n        (drule (4) trans, simp)+\n      ) []\n      done\n  }\n\n  {\n    assume \"cmp_lex cmp x y = EQUAL\" \"cmp_lex cmp y z = EQUAL\"\n    thus \"cmp_lex cmp x z = EQUAL\"\n      using M\n      apply (induct cmp\\<equiv>cmp x y arbitrary: z rule: cmp_lex.induct)\n      apply (auto split: comp_res.split_asm comp_res.split)\n      apply (case_tac z)\n      apply (auto split: comp_res.split_asm comp_res.split)\n      apply (drule (4) trans, simp)+\n      done\n  }\nqed\n\nsubsubsection \\<open>Lexicographic Order on Pairs\\<close>  \n\nfun cmp_prod where \n  \"cmp_prod cmp1 cmp2 (a1,a2) (b1,b2) \n  = (\n    case cmp1 a1 b1 of\n      LESS \\<Rightarrow> LESS\n    | EQUAL \\<Rightarrow> cmp2 a2 b2\n    | GREATER \\<Rightarrow> GREATER)\"\n\nlemma cmp_prod_alt: \"cmp_prod = (\\<lambda>cmp1 cmp2 (a1,a2) (b1,b2). (\n    case cmp1 a1 b1 of\n      LESS \\<Rightarrow> LESS\n    | EQUAL \\<Rightarrow> cmp2 a2 b2\n    | GREATER \\<Rightarrow> GREATER))\"\n  by (auto intro!: ext)\n\n\n\n  show ?thesis\n    apply unfold_locales\n    apply (auto split: comp_res.split comp_res.split_asm,\n      simp_all add: A.lt_eq B.lt_eq,\n      simp_all add: A.lt_eq[symmetric]\n      ) []\n\n    apply (auto split: comp_res.split comp_res.split_asm) []\n\n    apply (auto split: comp_res.split comp_res.split_asm) []\n    apply (drule (4) A.trans B.trans, simp)+\n\n    apply (auto split: comp_res.split comp_res.split_asm) []\n    apply (drule (4) A.trans B.trans, simp)+\n\n    apply (auto split: comp_res.split comp_res.split_asm) []\n    apply (drule (4) A.trans B.trans, simp)+\n\n    apply (auto split: comp_res.split comp_res.split_asm) []\n    apply (drule (4) A.trans B.trans, simp)+\n    done\nqed\n\nsubsection \\<open>Universal Ordering for Sets that is Effective for Finite Sets\\<close>\n\nsubsubsection \\<open>Sorted Lists of Sets\\<close>\ntext \\<open>Some more results about sorted lists of finite sets\\<close>\n\nlemma set_to_map_set_is_map_of: \n  \"distinct (map fst l) \\<Longrightarrow> set_to_map (set l) = map_of l\"\n  apply (induct l)\n  apply (auto simp: set_to_map_insert)\n  done\n\ncontext linorder begin\n\n  lemma sorted_list_of_set_eq_nil2[simp]:\n    assumes \"finite A\" \n    shows \"[] = sorted_list_of_set A \\<longleftrightarrow> A={}\"\n    using assms\n    by (auto dest: sym)\n\n  lemma set_insort[simp]: \"set (insort x l) = insert x (set l)\"\n    by (induct l) auto\n\n  lemma sorted_list_of_set_inj_aux:\n    fixes A B :: \"'a set\"\n    assumes \"finite A\" \n    assumes \"finite B\" \n    assumes \"sorted_list_of_set A = sorted_list_of_set B\"\n    shows \"A=B\"\n    using assms\n  proof -\n    from \\<open>finite B\\<close> have \"B = set (sorted_list_of_set B)\" by simp\n    also from assms have \"\\<dots> = set (sorted_list_of_set (A))\"\n      by simp\n    also from \\<open>finite A\\<close> \n    have \"set (sorted_list_of_set (A)) = A\"\n      by simp\n    finally show ?thesis by simp\n  qed\n\n  lemma sorted_list_of_set_inj: \"inj_on sorted_list_of_set (Collect finite)\"\n    apply (rule inj_onI)\n    using sorted_list_of_set_inj_aux\n    by blast\n \n  definition \"sorted_list_of_map m \\<equiv> \n    map (\\<lambda>k. (k, the (m k))) (sorted_list_of_set (dom m))\"\n\n  lemma the_sorted_list_of_map:\n    assumes \"distinct (map fst l)\"\n    assumes \"sorted (map fst l)\"\n    shows \"sorted_list_of_map (map_of l) = l\"\n  proof -\n    have \"dom (map_of l) = set (map fst l)\" by (induct l) force+\n    hence \"sorted_list_of_set (dom (map_of l)) = map fst l\"\n      using sorted_list_of_set.idem_if_sorted_distinct[OF assms(2,1)] by simp\n    hence \"sorted_list_of_map (map_of l) \n      = map (\\<lambda>k. (k, the (map_of l k))) (map fst l)\"\n      unfolding sorted_list_of_map_def by simp\n    also have \"\\<dots> = l\" using \\<open>distinct (map fst l)\\<close>\n    proof (induct l)\n      case Nil thus ?case by simp\n    next\n      case (Cons a l) \n      hence \n        1: \"distinct (map fst l)\" \n        and 2: \"fst a\\<notin>fst`set l\" \n        and 3: \"map (\\<lambda>k. (k, the (map_of l k))) (map fst l) = l\" \n        by simp_all\n\n      from 2 have [simp]: \"\\<not>(\\<exists>x\\<in>set l. fst x = fst a)\"\n        by (auto simp: image_iff)\n\n      show ?case\n        apply simp\n        apply (subst (3) 3[symmetric])\n        apply simp\n        done\n    qed\n    finally show ?thesis .\n  qed\n\n  lemma map_of_sorted_list_of_map[simp]:\n    assumes FIN: \"finite (dom m)\" \n    shows \"map_of (sorted_list_of_map m) = m\"\n    unfolding sorted_list_of_map_def\n  proof -\n    have \"set (sorted_list_of_set (dom m)) = dom m\"\n      and DIST: \"distinct (sorted_list_of_set (dom m))\"\n      by (simp_all add: FIN) \n\n    have [simp]: \"(fst \\<circ> (\\<lambda>k. (k, the (m k)))) = id\" by auto\n\n    have [simp]: \"(\\<lambda>k. (k, the (m k))) ` dom m = map_to_set m\"\n      by (auto simp: map_to_set_def)\n\n    show \"map_of (map (\\<lambda>k. (k, the (m k))) (sorted_list_of_set (dom m))) = m\"\n      apply (subst set_to_map_set_is_map_of[symmetric])\n      apply (simp add: DIST)\n      apply (subst set_map)\n      apply (simp add: FIN map_to_set_inverse)\n      done\n  qed\n\n  lemma sorted_list_of_map_inj_aux:\n    fixes A B :: \"'a\\<rightharpoonup>'b\"\n    assumes [simp]: \"finite (dom A)\" \n    assumes [simp]: \"finite (dom B)\" \n    assumes E: \"sorted_list_of_map A = sorted_list_of_map B\"\n    shows \"A=B\"\n    using assms\n  proof -\n    have \"A = map_of (sorted_list_of_map A)\" by simp\n    also note E\n    also have \"map_of (sorted_list_of_map B) = B\" by simp\n    finally show ?thesis .\n  qed\n\n  lemma sorted_list_of_map_inj: \n    \"inj_on sorted_list_of_map (Collect (finite o dom))\"\n    apply (rule inj_onI)\n    using sorted_list_of_map_inj_aux\n    by auto\nend\n\ndefinition \"cmp_set cmp \\<equiv> \n  cmp_extend (Collect finite) (\n    cmp_img\n      (linorder.sorted_list_of_set (comp2le cmp)) \n      (cmp_lex cmp)\n  )\"\n\nthm img_linorder\n\nlemma set_ord_linear[intro?]: \n  \"linorder cmp \\<Longrightarrow> linorder (cmp_set cmp)\"\n  unfolding cmp_set_def\n  apply rule\n  apply rule\n  apply (rule restrict_linorder)\n  apply (erule linorder_on.lex_linorder)\n  apply simp\n  done\n\ndefinition \"cmp_map cmpk cmpv \\<equiv>\n  cmp_extend (Collect (finite o dom)) (\n    cmp_img\n      (linorder.sorted_list_of_map (comp2le cmpk))\n      (cmp_lex (cmp_prod cmpk cmpv))\n  )\n\"\n\nlemma map_to_set_inj[intro!]: \"inj map_to_set\"\n  apply (rule inj_onI)\n  unfolding map_to_set_def\n  apply (rule ext)\n  apply (case_tac \"x xa\")\n  apply (case_tac [!] \"y xa\")\n  apply force+\n  done\n\ncorollary map_to_set_inj'[intro!]: \"inj_on map_to_set S\"\n  by (metis map_to_set_inj subset_UNIV subset_inj_on)\n  \nlemma map_ord_linear[intro?]: \n  assumes A: \"linorder cmpk\" \n  assumes B: \"linorder cmpv\" \n  shows \"linorder (cmp_map cmpk cmpv)\"\nproof -\n  interpret lk: linorder_on UNIV cmpk by fact\n  interpret lv: linorder_on UNIV cmpv by fact\n  \n  show ?thesis\n    unfolding cmp_map_def\n    apply rule\n    apply rule\n    apply (rule restrict_linorder)\n    apply (rule linorder_on.lex_linorder)\n    apply (rule)\n    apply fact\n    apply fact\n    apply simp\n    done\nqed\n  \n  \nlocale eq_linorder_on = linorder_on +\n  assumes cmp_imp_equal: \"\\<lbrakk>x\\<in>D; y\\<in>D\\<rbrakk> \\<Longrightarrow> cmp x y = EQUAL \\<Longrightarrow> x = y\"\nbegin\n  lemma cmp_eq[simp]: \"\\<lbrakk>x\\<in>D; y\\<in>D\\<rbrakk> \\<Longrightarrow> cmp x y = EQUAL \\<longleftrightarrow> x = y\"\n    by (auto simp: cmp_imp_equal)\nend\n  \nabbreviation \"eq_linorder \\<equiv> eq_linorder_on UNIV\"\n\nlemma dflt_cmp_2inv[simp]: \n  \"dflt_cmp (comp2le cmp) (comp2lt cmp) = cmp\"\n  unfolding dflt_cmp_def[abs_def] comp2le_def[abs_def] comp2lt_def[abs_def]\n  apply (auto split: comp_res.splits intro!: ext)\n  done\n\nlemma (in linorder) dflt_cmp_inv2[simp]:\n  shows \n  \"(comp2le (dflt_cmp (\\<le>) (<)))= (\\<le>)\"\n  \"(comp2lt (dflt_cmp (\\<le>) (<)))= (<)\"\nproof -\n  show \"(comp2lt (dflt_cmp (\\<le>) (<)))= (<)\"\n    unfolding dflt_cmp_def[abs_def] comp2le_def[abs_def] comp2lt_def[abs_def]\n    apply (auto split: comp_res.splits intro!: ext)\n    done\n\n  show \"(comp2le (dflt_cmp (\\<le>) (<))) = (\\<le>)\"\n    unfolding dflt_cmp_def[abs_def] comp2le_def[abs_def] comp2lt_def[abs_def]\n    apply (auto split: comp_res.splits intro!: ext)\n    done\n\nqed\n    \nlemma eq_linorder_class_conv:\n  \"eq_linorder cmp \\<longleftrightarrow> class.linorder (comp2le cmp) (comp2lt cmp)\"\nproof\n  assume \"eq_linorder cmp\"\n  then interpret eq_linorder_on UNIV cmp .\n  have \"linorder cmp\" by unfold_locales\n  show \"class.linorder (comp2le cmp) (comp2lt cmp)\"\n    apply (rule linorder_to_class)\n    apply fact\n    by simp\nnext\n  assume \"class.linorder (comp2le cmp) (comp2lt cmp)\"\n  then interpret linorder \"comp2le cmp\" \"comp2lt cmp\" .\n  \n  from class_to_linorder interpret linorder_on UNIV cmp\n    by simp\n  show \"eq_linorder cmp\"\n  proof\n    fix x y\n    assume \"cmp x y = EQUAL\"\n    hence \"comp2le cmp x y\" \"\\<not>comp2lt cmp x y\"\n      by (auto simp: comp2le_def comp2lt_def)\n    thus \"x=y\" by simp\n  qed\nqed\n  \nlemma (in linorder) class_to_eq_linorder:\n  \"eq_linorder (dflt_cmp (\\<le>) (<))\"\nproof -\n  interpret linorder_on UNIV \"dflt_cmp (\\<le>) (<)\"\n    by (rule class_to_linorder)\n\n  show ?thesis\n    apply unfold_locales\n    apply (auto simp: dflt_cmp_def split: if_split_asm)\n    done\nqed\n\nlemma eq_linorder_comp2eq_eq: \n  assumes \"eq_linorder cmp\"\n  shows \"comp2eq cmp = (=)\"\nproof -\n  interpret eq_linorder_on UNIV cmp by fact\n  show ?thesis\n    apply (intro ext)\n    unfolding comp2eq_def\n    apply (auto split: comp_res.split dest: refl)\n    done\nqed\n    \nlemma restrict_eq_linorder: \n  assumes \"eq_linorder_on D cmp\" \n  assumes S: \"D'\\<subseteq>D\" \n  shows \"eq_linorder_on D' cmp\"\nproof -\n  interpret eq_linorder_on D cmp by fact\n  \n  show ?thesis\n    apply (rule eq_linorder_on.intro)\n    apply (rule restrict_linorder[where D=D])\n    apply unfold_locales []\n    apply fact\n    apply unfold_locales\n    using S\n    apply -\n    apply (drule (1) rev_subsetD)+\n    apply auto\n    done\nqed\n  \nlemma combine_eq_linorder[intro?]:\n  assumes A: \"eq_linorder_on D1 cmp1\"\n  assumes B: \"eq_linorder_on D2 cmp2\"\n  assumes EQ: \"D=D1\\<union>D2\"\n  shows \"eq_linorder_on D (cmp_combine D1 cmp1 D2 cmp2)\"\nproof -\n  interpret A: eq_linorder_on D1 cmp1 by fact\n  interpret B: eq_linorder_on D2 cmp2 by fact\n  interpret linorder_on \"(D1 \\<union> D2)\" \"(cmp_combine D1 cmp1 D2 cmp2)\"\n    apply rule\n    apply unfold_locales\n    by simp\n  \n  show ?thesis\n    apply (simp only: EQ)\n    apply unfold_locales\n    unfolding cmp_combine_def\n    by (auto split: if_split_asm)\nqed\n\nlemma img_eq_linorder[intro?]:\n  assumes A: \"eq_linorder_on (f`D) cmp\"\n  assumes INJ: \"inj_on f D\"\n  shows \"eq_linorder_on D (cmp_img f cmp)\"\nproof -\n  interpret eq_linorder_on \"f`D\" cmp by fact\n  interpret L: linorder_on \"(D)\" \"(cmp_img f cmp)\"\n    apply rule\n    apply unfold_locales\n    done\n  \n  show ?thesis\n    apply unfold_locales\n    unfolding cmp_img_def\n    using INJ\n    apply (auto dest: inj_onD)\n    done\nqed\n\nlemma univ_eq_linorder[intro?]:\n  shows \"eq_linorder univ_cmp\"\n  apply (rule eq_linorder_on.intro)\n  apply rule\n  apply unfold_locales\n  unfolding univ_cmp_def\n  apply (auto split: if_split_asm)\n  done\n  \nlemma extend_eq_linorder[intro?]:\n  assumes \"eq_linorder_on D cmp\"\n  shows \"eq_linorder (cmp_extend D cmp)\"\nproof -\n  interpret eq_linorder_on D cmp by fact\n  show ?thesis\n    unfolding cmp_extend_def\n    apply (rule)\n    apply fact\n    apply rule\n    by simp\nqed\n  \nlemma lex_eq_linorder[intro?]:\n  assumes \"eq_linorder_on D cmp\"\n  shows \"eq_linorder_on (lists D) (cmp_lex cmp)\"\nproof -\n  interpret eq_linorder_on D cmp by fact\n  show ?thesis\n    apply (rule eq_linorder_on.intro)\n    apply rule\n    apply unfold_locales\n    subgoal for l m\n      apply (induct cmp\\<equiv>cmp l m rule: cmp_lex.induct)\n      apply (auto split: comp_res.splits)\n      done\n    done\nqed\n\nlemma prod_eq_linorder[intro?]:\n  assumes \"eq_linorder_on D1 cmp1\"\n  assumes \"eq_linorder_on D2 cmp2\"\n  shows \"eq_linorder_on (D1\\<times>D2) (cmp_prod cmp1 cmp2)\"\nproof -\n  interpret A: eq_linorder_on D1 cmp1 by fact\n  interpret B: eq_linorder_on D2 cmp2 by fact\n  show ?thesis\n    apply (rule eq_linorder_on.intro)\n    apply rule\n    apply unfold_locales\n    apply (auto split: comp_res.splits)\n    done\nqed\n\nlemma set_ord_eq_linorder[intro?]: \n  \"eq_linorder cmp \\<Longrightarrow> eq_linorder (cmp_set cmp)\"\n  unfolding cmp_set_def\n  apply rule\n  apply rule\n  apply (rule restrict_eq_linorder)\n  apply rule\n  apply assumption\n  apply simp\n\n  apply (rule linorder.sorted_list_of_set_inj)\n  apply (subst (asm) eq_linorder_class_conv)\n  .\n\nlemma map_ord_eq_linorder[intro?]: \n  \"\\<lbrakk>eq_linorder cmpk; eq_linorder cmpv\\<rbrakk> \\<Longrightarrow> eq_linorder (cmp_map cmpk cmpv)\"\n  unfolding cmp_map_def\n  apply rule\n  apply rule\n  apply (rule restrict_eq_linorder)\n  apply rule\n  apply rule\n  apply assumption\n  apply assumption\n  apply simp\n\n  apply (rule linorder.sorted_list_of_map_inj)\n  apply (subst (asm) eq_linorder_class_conv)\n  .\n\ndefinition cmp_unit :: \"unit \\<Rightarrow> unit \\<Rightarrow> comp_res\" \n  where [simp]: \"cmp_unit u v \\<equiv> EQUAL\"\n\nlemma cmp_unit_eq_linorder:\n  \"eq_linorder cmp_unit\"\n  by unfold_locales simp_all\n  \nsubsection \\<open>Parametricity\\<close>  \n  \nlemma param_cmp_extend[param]:\n  assumes \"(cmp,cmp')\\<in>R \\<rightarrow> R \\<rightarrow> Id\"\n  assumes \"Range R \\<subseteq> D\"\n  shows \"(cmp,cmp_extend D cmp') \\<in> R \\<rightarrow> R \\<rightarrow> Id\"\n  unfolding cmp_extend_def cmp_combine_def[abs_def]\n  using assms\n  apply clarsimp\n  by (blast dest!: fun_relD)\n\nlemma param_cmp_img[param]: \n  \"(cmp_img,cmp_img) \\<in> (Ra\\<rightarrow>Rb) \\<rightarrow> (Rb\\<rightarrow>Rb\\<rightarrow>Rc) \\<rightarrow> Ra \\<rightarrow> Ra \\<rightarrow> Rc\"\n  unfolding cmp_img_def[abs_def]\n  by parametricity\n\nlemma param_comp_res[param]:\n  \"(LESS,LESS)\\<in>Id\"\n  \"(EQUAL,EQUAL)\\<in>Id\"\n  \"(GREATER,GREATER)\\<in>Id\"\n  \"(case_comp_res,case_comp_res)\\<in>Ra\\<rightarrow>Ra\\<rightarrow>Ra\\<rightarrow>Id\\<rightarrow>Ra\"\n  by (auto split: comp_res.split)\n\nterm cmp_lex\nlemma param_cmp_lex[param]:\n  \"(cmp_lex,cmp_lex)\\<in>(Ra\\<rightarrow>Rb\\<rightarrow>Id)\\<rightarrow>\\<langle>Ra\\<rangle>list_rel\\<rightarrow>\\<langle>Rb\\<rangle>list_rel\\<rightarrow>Id\"\n  unfolding cmp_lex_alt[abs_def] cmp_lex'_def\n  by (parametricity)\n\nterm cmp_prod\nlemma param_cmp_prod[param]:\n  \"(cmp_prod,cmp_prod)\\<in>\n  (Ra\\<rightarrow>Rb\\<rightarrow>Id)\\<rightarrow>(Rc\\<rightarrow>Rd\\<rightarrow>Id)\\<rightarrow>\\<langle>Ra,Rc\\<rangle>prod_rel\\<rightarrow>\\<langle>Rb,Rd\\<rangle>prod_rel\\<rightarrow>Id\"\n  unfolding cmp_prod_alt\n  by (parametricity)\n\nlemma param_cmp_unit[param]: \n  \"(cmp_unit,cmp_unit)\\<in>Id\\<rightarrow>Id\\<rightarrow>Id\" \n  by auto\n\nlemma param_comp2eq[param]: \"(comp2eq,comp2eq)\\<in>(R\\<rightarrow>R\\<rightarrow>Id)\\<rightarrow>R\\<rightarrow>R\\<rightarrow>Id\"\n  unfolding comp2eq_def[abs_def]\n  by (parametricity)\n\n\n  \nlemma cmp_combine_paramD:\n  assumes \"(cmp,cmp_combine D1 cmp1 D2 cmp2)\\<in>R\\<rightarrow>R\\<rightarrow>Id\"\n  assumes \"Range R \\<subseteq> D1\"\n  shows \"(cmp,cmp1)\\<in>R\\<rightarrow>R\\<rightarrow>Id\"\n  using assms\n  unfolding cmp_combine_def[abs_def]\n  apply (intro fun_relI)\n  apply (drule_tac x=a in fun_relD, assumption)\n  apply (drule_tac x=aa in fun_relD, assumption)\n  apply (drule RangeI, drule (1) rev_subsetD)\n  apply (drule RangeI, drule (1) rev_subsetD)\n  apply simp\n  done\n\nlemma cmp_extend_paramD:\n  assumes \"(cmp,cmp_extend D cmp')\\<in>R\\<rightarrow>R\\<rightarrow>Id\"\n  assumes \"Range R \\<subseteq> D\"\n  shows \"(cmp,cmp')\\<in>R\\<rightarrow>R\\<rightarrow>Id\"\n  using assms\n  unfolding cmp_extend_def\n  apply (rule cmp_combine_paramD)\n  done\n  \n\nsubsection \\<open>Tuning of Generated Implementation\\<close>\nlemma [autoref_post_simps]: \"comp2eq (dflt_cmp (\\<le>) ((<)::_::linorder\\<Rightarrow>_)) = (=)\"\n  by (simp add: class_to_eq_linorder eq_linorder_comp2eq_eq)\n\n\n\nend\n\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/Collections/GenCF/Intf/Intf_Comp.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8807970685907242, "lm_q2_score": 0.8267117940706734, "lm_q1q2_score": 0.7281653247868275}}
{"text": "theory Pratt_Certificate\nimports\n  Complex_Main\n  Lehmer\nbegin\n\nsection {* Pratt's Primality Certificates *}\ntext_raw {* \\label{sec:pratt} *}\n\ntext {*\n  This work formalizes Pratt's proof system as described in his article\n  ``Every Prime has a Succinct Certificate''\\cite{pratt1975certificate}.\n  The proof system makes use of two types of predicates:\n  \\begin{itemize}\n    \\item $\\text{Prime}(p)$: $p$ is a prime number\n    \\item $(p, a, x)$: @{text \"\\<forall>q \\<in> prime_factors(x). [a^((p - 1) div q) \\<noteq> 1] (mod p)\"}\n  \\end{itemize}\n  We represent these predicates with the following datatype:\n*}\n\ndatatype pratt = Prime nat | Triple nat nat nat\n\ntext {*\n  Pratt describes an inference system consisting of the axiom $(p, a, 1)$\n  and the following inference rules:\n  \\begin{itemize}\n  \\item R1: If we know that $(p, a, x)$ and @{text \"[a^((p - 1) div q) \\<noteq> 1] (mod p)\"} hold for some\n              prime number $q$ we can conclude $(p, a, qx)$ from that.\n  \\item R2: If we know that $(p, a, p - 1)$ and  @{text \"[a^(p - 1) = 1] (mod p)\"} hold, we can\n              infer $\\text{Prime}(p)$.\n  \\end{itemize}\n  Both rules follow from Lehmer's theorem as we will show later on.\n\n  A list of predicates (i.e., values of type @{type pratt}) is a \\emph{certificate}, if it is\n  built according to the inference system described above. I.e., a list @{term \"x # xs :: pratt list\"}\n  is a certificate if @{term \"xs :: pratt list\"} is a certificate and @{term \"x :: pratt\"} is\n  either an axiom or all preconditions of @{term \"x :: pratt\"} occur in @{term \"xs :: pratt list\"}.\n\n  We call a certificate @{term \"xs :: pratt list\"} a \\emph{certificate for @{term p}},\n  if @{term \"Prime p\"} occurs in @{term \"xs :: pratt list\"}.\n\n  The function @{text valid_cert} checks whether a list is a certificate.\n*}\n\nfun valid_cert :: \"pratt list \\<Rightarrow> bool\" where\n  \"valid_cert [] = True\"\n| R2: \"valid_cert (Prime p#xs) \\<longleftrightarrow> 1 < p \\<and> valid_cert xs\n    \\<and> (\\<exists> a . [a^(p - 1) = 1] (mod p) \\<and> Triple p a (p - 1) \\<in> set xs)\"\n| R1: \"valid_cert (Triple p a x # xs) \\<longleftrightarrow> 0 < x  \\<and> valid_cert xs \\<and> (x=1 \\<or>\n    (\\<exists>q y. x = q * y \\<and> Prime q \\<in> set xs \\<and> Triple p a y \\<in> set xs\n      \\<and> [a^((p - 1) div q) \\<noteq> 1] (mod p)))\"\n\ntext {*\n  We define a function @{term size_cert} to measure the size of a certificate, assuming\n  a binary encoding of numbers. We will use this to show that there is a certificate for a\n  prime number $p$ such that the size of the certificate is polynomially bounded in the size\n  of the binary representation of $p$.\n*}\nfun size_pratt :: \"pratt \\<Rightarrow> real\" where\n  \"size_pratt (Prime p) = log 2 p\" |\n  \"size_pratt (Triple p a x) = log 2 p + log 2 a + log 2 x\"\n\nfun size_cert :: \"pratt list \\<Rightarrow> real\" where\n  \"size_cert [] = 0\" |\n  \"size_cert (x # xs) = 1 + size_pratt x + size_cert xs\"\n\n\nsection {* Soundness *}\n\ntext {*\n  In Section \\ref{sec:pratt} we introduced the predicates $\\text{Prime}(p)$ and $(p, a, x)$.\n  In this section we show that for a certificate every predicate occuring in this certificate\n  holds. In particular, if $\\text{Prime}(p)$ occurs in a certificate, $p$ is prime.\n*}\n\nlemma prime_factors_one[simp]: shows \"prime_factors (Suc 0) = {}\"\n  by (auto simp add:prime_factors_altdef2_nat)\n\nlemma prime_factors_prime: fixes p :: nat assumes \"prime p\" shows \"prime_factors p = {p}\"\nproof\n  have \"0 < p\" using assms by auto\n  then show \"{p} \\<subseteq> prime_factors p\" using assms by (auto simp add:prime_factors_altdef2_nat)\n  { fix q assume \"q \\<in> prime_factors p\"\n    then have \"q dvd p\" \"prime q\" using `0<p` by (auto simp add:prime_factors_altdef2_nat)\n    with assms have \"q=p\" by (auto simp: prime_nat_def)\n    }\n  then\n  show \"prime_factors p \\<subseteq> {p}\" by auto\nqed\n\ntheorem pratt_sound:\n  assumes 1: \"valid_cert c\"\n  assumes 2: \"t \\<in> set c\"\n  shows \"(t = Prime p \\<longrightarrow> prime p) \\<and>\n         (t = Triple p a x \\<longrightarrow> ((\\<forall> q \\<in> prime_factors x . [a^((p - 1) div q) \\<noteq> 1] (mod p)) \\<and> 0<x))\"\nusing assms\nproof (induction c arbitrary: p a x t)\n  case Nil then show ?case by force\n  next\n  case (Cons y ys)\n  { assume \"y=Triple p a x\" \"x=1\"\n    then have \"(\\<forall> q \\<in> prime_factors x . [a^((p - 1) div q) \\<noteq> 1] (mod p)) \\<and> 0<x\" by simp\n    }\n  moreover\n  { assume x_y: \"y=Triple p a x\" \"x~=1\"\n    hence \"x>0\" using Cons.prems by auto\n    obtain q z where \"x=q*z\" \"Prime q \\<in> set ys \\<and> Triple p a z \\<in> set ys\"\n               and cong:\"[a^((p - 1) div q) \\<noteq> 1] (mod p)\" using Cons.prems x_y by auto\n    then have factors_IH:\"(\\<forall> r \\<in> prime_factors z . [a^((p - 1) div r) \\<noteq> 1] (mod p))\" \"prime q\" \"z>0\"\n      using Cons.IH Cons.prems `x>0` `y=Triple p a x` by auto\n    then have \"prime_factors x = prime_factors z \\<union> {q}\"  using `x =q*z` `x>0`\n      by (simp add:prime_factors_product_nat prime_factors_prime)\n    then have \"(\\<forall> q \\<in> prime_factors x . [a^((p - 1) div q) \\<noteq> 1] (mod p)) \\<and> 0 < x\"\n      using factors_IH cong by (simp add: `x>0`)\n    }\n  ultimately have y_Triple:\"y=Triple p a x \\<Longrightarrow> (\\<forall> q \\<in> prime_factors x .\n                                                [a^((p - 1) div q) \\<noteq> 1] (mod p)) \\<and> 0<x\" by linarith\n  { assume y: \"y=Prime p\" \"p>2\" then\n    obtain a where a:\"[a^(p - 1) = 1] (mod p)\" \"Triple p a (p - 1) \\<in> set ys\"\n      using Cons.prems by auto\n    then have Bier:\"(\\<forall>q\\<in>prime_factors (p - 1). [a^((p - 1) div q) \\<noteq> 1] (mod p))\"\n      using Cons.IH Cons.prems(1) by (simp add:y(1))\n    then have \"prime p\" using lehmers_theorem[OF _ _a(1)] `p>2` by fastforce\n    }\n  moreover\n  { assume \"y=Prime p\" \"p=2\" hence \"prime p\" by simp }\n  moreover\n  { assume \"y=Prime p\" then have \"p>1\"  using Cons.prems  by simp }\n  ultimately have y_Prime:\"y = Prime p \\<Longrightarrow> prime p\" by linarith\n\n  show ?case\n  proof (cases \"t \\<in> set ys\")\n    case True\n      show ?thesis using Cons.IH[OF _ True] Cons.prems(1) by (cases y) auto\n    next\n    case False\n      thus ?thesis using Cons.prems(2) y_Prime y_Triple by force\n  qed\nqed\n\n\n\nsection {* Completeness *}\n\ntext {*\n  In this section we show completeness of Pratt's proof system, i.e., we show that for\n  every prime number $p$ there exists a certificate for $p$. We also give an upper\n  bound for the size of a minimal certificate\n\n  The prove we give is constructive. We assume that we have certificates for all prime\n  factors of $p - 1$ and use these to build a certificate for $p$ from that. It is\n  important to note that certificates can be concatenated.\n*}\n\nlemma valid_cert_appendI:\n  assumes \"valid_cert r\"\n  assumes \"valid_cert s\"\n  shows \"valid_cert (r @ s)\"\n  using assms\nproof (induction r)\n  case (Cons y ys) then show ?case by (cases y) auto\nqed simp\n\nlemma valid_cert_concatI: \"(\\<forall>x \\<in> set xs . valid_cert x) \\<Longrightarrow> valid_cert (concat xs)\"\n  by (induction xs) (auto simp add: valid_cert_appendI)\n\nlemma size_pratt_le:\n fixes d::real\n assumes \"\\<forall> x \\<in> set c. size_pratt x \\<le> d\"\n shows \"size_cert c \\<le> length c * (1 + d)\" using assms\n by (induction c) (simp_all add: real_of_nat_def algebra_simps)\n\nfun build_fpc :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> nat list \\<Rightarrow> pratt list\" where\n  \"build_fpc p a r [] = [Triple p a r]\" |\n  \"build_fpc p a r (y # ys) = Triple p a r # build_fpc p a (r div y) ys\"\n\ntext {*\n  The function @{term build_fpc} helps us to construct a certificate for $p$ from\n  the certificates for the prime factors of $p - 1$. Called as\n  @{term \"build_fpc p a (p - 1) qs\"} where $@{term \"qs\"} = q_1 \\ldots q_n$\n  is prime decomposition of $p - 1$ such that $q_1 \\cdot \\dotsb \\cdot q_n = @{term \"p - 1 :: nat\"}$,\n  it returns the following list of predicates:\n  \\[\n  (p,a,p-1), (p,a,\\frac{p - 1}{q_1}), (p,a,\\frac{p - 1}{q_1 q_2}), \\ldots, (p,a,\\frac{p-1}{q_1 \\ldots q_n}) = (p,a,1)\n  \\]\n\n  I.e., if there is an appropriate $a$ and and a certificate @{term rs} for all\n  prime factors of $p$, then we can construct a certificate for $p$ as\n  @{term [display] \"Prime p # build_fpc p a (p - 1) qs @ rs\"}\n*}\n\n\ndefinition \"listprod \\<equiv> \\<lambda>xs. foldr (op *) xs 1\"\n\nlemma listprod_Nil[simp]: \"listprod [] = 1\" by (simp add: listprod_def)\nlemma listprod_Cons[simp]: \"listprod (x # xs) = x * listprod xs\" by (simp add: listprod_def)\n\ntext {*\n  The following lemma shows that @{text \"build_fpc\"} extends a certificate that\n  satisfies the preconditions described before to a correct certificate.\n*}\n\nlemma correct_fpc:\n  assumes \"valid_cert xs\"\n  assumes \"listprod qs = r\" \"r \\<noteq> 0\"\n  assumes \"\\<forall> q \\<in> set qs . Prime q \\<in> set xs\"\n  assumes \"\\<forall> q \\<in> set qs . [a^((p - 1) div q) \\<noteq> 1] (mod p)\"\n  shows \"valid_cert (build_fpc p a r qs @ xs)\"\n  using assms\nproof (induction qs arbitrary: r)\n  case Nil thus ?case by auto\nnext\n  case (Cons y ys)\n  have \"listprod ys = r div y\" using Cons.prems by auto\n  then have T_in: \"Triple p a (listprod ys) \\<in> set (build_fpc p a (r div y) ys @ xs)\"\n    by (cases ys) auto\n\n  have \"valid_cert (build_fpc p a (r div y) ys @ xs)\"\n    using Cons.prems by (intro Cons.IH) auto\n  then have \"valid_cert (Triple p a r # build_fpc p a (r div y) ys @ xs)\"\n    using `r \\<noteq> 0` T_in Cons.prems by auto\n  then show ?case by simp\nqed\n\nlemma length_fpc:\n  \"length (build_fpc p a r qs) = length qs + 1\" by (induction qs arbitrary: r) auto\n\nlemma div_gt_0:\n  fixes m n :: nat assumes \"m \\<le> n\" \"0 < m\" shows \"0 < n div m\"\nproof -\n  have \"0 < m div m\" using `0 < m` div_self by auto\n  also have \"m div m \\<le> n div m\" using `m \\<le> n` by (rule div_le_mono)\n  finally show ?thesis .\nqed\n\nlemma size_pratt_fpc:\n  assumes \"a \\<le> p\" \"r \\<le> p\" \"0 < a\" \"0 < r\" \"0 < p\" \"listprod qs = r\"\n  shows \"\\<forall>x \\<in> set (build_fpc p a r qs) . size_pratt x \\<le> 3 * log 2 p\" using assms\nproof (induction qs arbitrary: r)\n  case Nil\n  then have \"log 2 a \\<le> log 2 p\" \"log 2 r \\<le> log 2 p\" by auto\n  then show ?case by simp\nnext\n  case (Cons q qs)\n  then have \"log 2 a \\<le> log 2 p\" \"log 2 r \\<le> log 2 p\" by auto\n  then have  \"log 2 a + log 2 r \\<le> 2 * log 2 p\" by arith\n  moreover have \"r div q > 0\" using Cons.prems by (fastforce intro: div_gt_0)\n  moreover hence \"listprod qs = r div q\" using Cons.prems(6) by auto\n  moreover have \"r div q \\<le> p\" using `r\\<le>p` div_le_dividend[of r q] by linarith\n  ultimately show ?case using Cons by simp\nqed\n\nlemma concat_set:\n  assumes \"\\<forall> q \\<in> qs . \\<exists> c \\<in> set cs . Prime q \\<in> set c\"\n  shows \"\\<forall> q \\<in> qs . Prime q \\<in> set (concat cs)\"\n  using assms by (induction cs) auto\n\nlemma p_in_prime_factorsE:\n  fixes n :: nat\n  assumes \"p \\<in> prime_factors n\" \"0 < n\"\n  obtains \"2 \\<le> p\" \"p \\<le> n\" \"p dvd n\" \"prime p\"\nproof\n  from assms show \"prime p\" by auto\n  then show \"2 \\<le> p\" by (auto dest: prime_gt_1_nat)\n\n  from assms show \"p dvd n\" by (intro prime_factors_dvd_nat)\n  then show \"p \\<le> n\" using  `0 < n` by (rule dvd_imp_le)\nqed\n\nlemma prime_factors_list_prime:\n  fixes n :: nat\n  assumes \"prime n\"\n  shows \"\\<exists> qs. prime_factors n = set qs \\<and> listprod qs = n \\<and> length qs = 1\"\nproof -\n    have \"prime_factors n = set [n]\" using prime_factors_prime assms by force\n    thus ?thesis by fastforce\nqed\n\nlemma prime_factors_list:\n  fixes n :: nat assumes \"3 < n\" \"\\<not> prime n\"\n  shows \"\\<exists> qs. prime_factors n = set qs \\<and> listprod qs = n \\<and> length qs \\<ge> 2\"\n  using assms\nproof (induction n rule: less_induct)\n  case (less n)\n    obtain p where \"p \\<in> prime_factors n\" using `n > 3` prime_factors_elem by force\n    then have p':\"2 \\<le> p\" \"p \\<le> n\" \"p dvd n\" \"prime p\"\n      using `3 < n` by (auto elim: p_in_prime_factorsE)\n    { assume \"n div p > 3\" \"\\<not> prime (n div p)\"\n      then obtain qs\n        where \"prime_factors (n div p) = set qs\" \"listprod qs = (n div p)\" \"length qs \\<ge> 2\"\n        using p' by atomize_elim (auto intro: less simp: div_gt_0)\n      moreover\n      have \"prime_factors (p * (n div p)) = insert p (prime_factors (n div p))\"\n        using `3 < n` `2 \\<le> p` `p \\<le> n` `prime p`\n      by (auto simp: prime_factors_product_nat div_gt_0 prime_factors_prime)\n      ultimately\n      have \"prime_factors n = set (p # qs)\" \"listprod (p # qs) = n\" \"length (p#qs) \\<ge> 2\"\n        using `p dvd n` by (simp_all add: dvd_mult_div_cancel)\n      hence ?case by blast\n    }\n    moreover\n    { assume \"prime (n div p)\"\n      then obtain qs\n        where \"prime_factors (n div p) = set qs\" \"listprod qs = (n div p)\" \"length qs = 1\"\n        using prime_factors_list_prime by blast\n      moreover\n      have \"prime_factors (p * (n div p)) = insert p (prime_factors (n div p))\"\n        using `3 < n` `2 \\<le> p` `p \\<le> n` `prime p`\n      by (auto simp: prime_factors_product_nat div_gt_0 prime_factors_prime)\n      ultimately\n      have \"prime_factors n = set (p # qs)\" \"listprod (p # qs) = n\" \"length (p#qs) \\<ge> 2\"\n        using `p dvd n` by (simp_all add: dvd_mult_div_cancel)\n      hence ?case by blast\n    } note case_prime = this\n    moreover\n    { assume \"n div p = 1\"\n      hence \"n = p\" using `n>3`  using One_leq_div[OF `p dvd n`] p'(2) by force\n      hence ?case using `prime p` `\\<not> prime n` by auto\n    }\n    moreover\n    { assume \"n div p = 2\"\n      hence ?case using case_prime by force\n    }\n    moreover\n    { assume \"n div p = 3\"\n      hence ?case using p' case_prime by force\n    }\n    ultimately show ?case using p' div_gt_0[of p n] case_prime by fastforce\n\nqed\n\nlemma listprod_ge:\n  fixes xs::\"nat list\"\n  assumes \"\\<forall> x \\<in> set xs . x \\<ge> 1\"\n  shows \"listprod xs \\<ge> 1\" using assms by (induction xs) auto\n\nlemma listsum_log:\n  fixes b::real\n  fixes xs::\"nat list\"\n  assumes b: \"b > 0\" \"b \\<noteq> 1\"\n  assumes xs:\"\\<forall> x \\<in> set xs . x \\<ge> b\"\n  shows \"(\\<Sum>x\\<leftarrow>xs. log b x) = log b (listprod xs)\"\n  using assms\nproof (induction xs)\n  case Nil\n    thus ?case by simp\n  next\n  case (Cons y ys)\n    have \"real (listprod ys) > 0\" using listprod_ge Cons.prems by fastforce\n    thus ?case using Log.log_mult[OF Cons.prems(1-2)] Cons by force\nqed\n\nlemma concat_length_le:\n  fixes g :: \"nat \\<Rightarrow> real\"\n  assumes \"\\<forall> x \\<in> set xs . real (length (f x)) \\<le> g x\"\n  shows \"length (concat (map f xs)) \\<le> (\\<Sum>x\\<leftarrow>xs. g x)\" using assms\n  by (induction xs) force+\n\n(* XXX move *)\nlemma powr_realpow_numeral: \"0 < x \\<Longrightarrow> x powr (numeral n :: real) = x^(numeral n)\"\n  unfolding real_of_nat_numeral[symmetric] by (rule powr_realpow)\n\nlemma prime_gt_3_impl_p_minus_one_not_prime:\n  fixes p::nat\n  assumes \"prime p\" \"p>3\"\n  shows \"\\<not> prime (p - 1)\"\nproof\n  assume \"prime (p - 1)\"\n  have \"\\<not> even p\" using assms by (simp add: prime_odd_nat)\n  hence \"2 dvd (p - 1)\" by presburger\n  hence \"2 \\<in> prime_factors (p - 1)\" using `p>3` by (auto simp: prime_factors_altdef2_nat)\n  thus False using prime_factors_prime `p>3` `prime (p - 1)` by auto\nqed\n\ntext {*\n  We now prove that Pratt's proof system is complete and derive upper bounds for\n  the length and the size of the entries of a minimal certificate.\n*}\n\ntheorem pratt_complete':\n  assumes \"prime p\"\n  shows \"\\<exists>c. Prime p \\<in> set c \\<and> valid_cert c \\<and> length c \\<le> 6*log 2 p - 4 \\<and> (\\<forall> x \\<in> set c. size_pratt x \\<le> 3 * log 2 p)\" using assms\nproof (induction p rule: less_induct)\n  case (less p)\n  { assume [simp]: \"p = 2\"\n    have \"Prime p \\<in> set [Prime 2, Triple 2 1 1]\" by simp\n    then have ?case by fastforce }\n  moreover\n  { assume [simp]: \"p = 3\"\n    let ?cert = \"[Prime 3, Triple 3 2 2, Triple 3 2 1, Prime 2, Triple 2 1 1]\"\n\n    have \"length ?cert \\<le> 6*log 2 p - 4\n          \\<longleftrightarrow> 2 powr 9 \\<le> 2 powr (log 2 p * 6)\" by auto\n    also have \"\\<dots> \\<longleftrightarrow> True\"\n      by (simp add: powr_powr[symmetric] powr_realpow_numeral)\n    finally have ?case\n      by (intro exI[where x=\"?cert\"]) (simp add: cong_nat_def)\n  }\n  moreover\n  { assume \"p > 3\"\n\n    have \"\\<forall>q \\<in> prime_factors (p - 1) . q < p\" using `prime p`\n      by (fastforce elim: p_in_prime_factorsE)\n    hence factor_certs:\"\\<forall>q \\<in> prime_factors (p - 1) . (\\<exists>c . ((Prime q \\<in> set c) \\<and> (valid_cert c)\n                                                      \\<and> length c \\<le> 6*log 2 q - 4) \\<and> (\\<forall> x \\<in> set c. size_pratt x \\<le> 3 * log 2 q))\"\n      by (auto intro: less.IH)\n    obtain a where a:\"[a^(p - 1) = 1] (mod p) \\<and> (\\<forall> q. q \\<in> prime_factors (p - 1)\n              \\<longrightarrow> [a^((p - 1) div q) \\<noteq> 1] (mod p))\" and a_size: \"a > 0\" \"a < p\"\n      using converse_lehmer[OF `prime p`] by blast\n\n    have \"\\<not> prime (p - 1)\" using `p>3` prime_gt_3_impl_p_minus_one_not_prime `prime p` by auto\n    have \"p \\<noteq> 4\" using `prime p` by auto\n    hence \"p - 1 > 3\" using `p > 3` by auto\n\n    then obtain qs where prod_qs_eq:\"listprod qs = p - 1\"\n        and qs_eq:\"set qs = prime_factors (p - 1)\" and qs_length_eq: \"length qs \\<ge> 2\"\n      using prime_factors_list[OF _ `\\<not> prime (p - 1)`] by auto\n    obtain f where f:\"\\<forall>q \\<in> prime_factors (p - 1) . \\<exists> c. f q = c\n                     \\<and> ((Prime q \\<in> set c) \\<and> (valid_cert c) \\<and> length c \\<le> 6*log 2 q - 4)\n                     \\<and> (\\<forall> x \\<in> set c. size_pratt x \\<le> 3 * log 2 q)\"\n      using factor_certs by metis\n    let ?cs = \"map f qs\"\n    have cs: \"\\<forall>q \\<in> prime_factors (p - 1) . (\\<exists>c \\<in> set ?cs . (Prime q \\<in> set c) \\<and> (valid_cert c)\n                                           \\<and> length c \\<le> 6*log 2 q - 4\n                                           \\<and> (\\<forall> x \\<in> set c. size_pratt x \\<le> 3 * log 2 q))\"\n      using f qs_eq by auto\n\n    have cs_cert_size: \"\\<forall>c \\<in> set ?cs . \\<forall> x \\<in> set c. size_pratt x \\<le> 3 * log 2 p\"\n    proof\n      fix c assume \"c \\<in> set (map f qs)\"\n      then obtain q where \"c = f q\" and \"q \\<in> set qs\" by auto\n      hence *:\"\\<forall> x \\<in> set c. size_pratt x \\<le> 3 * log 2 q\" using f qs_eq by blast\n      have \"q < p\" \"q > 0\" using `\\<forall>q \\<in> prime_factors (p - 1) . q < p` `q \\<in> set qs` qs_eq by fast+\n      show \"\\<forall> x \\<in> set c. size_pratt x \\<le> 3 * log 2 p\"\n      proof\n        fix x assume \"x \\<in> set c\"\n        hence \"size_pratt x \\<le> 3 * log 2 q\" using * by fastforce\n        also have \"\\<dots> \\<le> 3 * log 2 p\" using `q < p` `q > 0` `p > 3` by simp\n        finally show \"size_pratt x \\<le> 3 * log 2 p\" .\n      qed\n    qed\n\n    have cs_valid_all: \"\\<forall>c \\<in> set ?cs . valid_cert c\"\n      using f qs_eq by fastforce\n\n    have \"\\<forall>x \\<in> set (build_fpc p a (p - 1) qs). size_pratt x \\<le> 3 * log 2 p\"\n      using cs_cert_size a_size `p > 3` prod_qs_eq by (intro size_pratt_fpc) auto\n    hence \"\\<forall>x \\<in> set (build_fpc p a (p - 1) qs @ concat ?cs) . size_pratt x \\<le> 3 * log 2 p\"\n      using cs_cert_size by auto\n    moreover\n    have \"Triple p a (p - 1) \\<in> set (build_fpc p a (p - 1) qs @ concat ?cs)\" by (cases qs) auto\n    moreover\n    have \"valid_cert ((build_fpc p a (p - 1) qs)@ concat ?cs)\"\n    proof (rule correct_fpc)\n      show \"valid_cert (concat ?cs)\"\n        using cs_valid_all by (auto simp: valid_cert_concatI)\n      show \"listprod qs = p - 1\" by (rule prod_qs_eq)\n      show \"p - 1 \\<noteq> 0\" using prime_gt_1_nat[OF `prime p`] by arith\n      show \"\\<forall> q \\<in> set qs . Prime q \\<in> set (concat ?cs)\"\n        using concat_set[of \"prime_factors (p - 1)\"] cs qs_eq by blast\n      show \"\\<forall> q \\<in> set qs . [a^((p - 1) div q) \\<noteq> 1] (mod p)\" using qs_eq a by auto\n    qed\n    moreover\n    { let ?k = \"length qs\"\n\n      have qs_ge_2:\"\\<forall>q \\<in> set qs . q \\<ge> 2\" using qs_eq\n        by (simp add: prime_factors_prime_nat prime_ge_2_nat)\n\n      have \"\\<forall>x\\<in>set qs. real (length (f x)) \\<le> 6 * log 2 (real x) - 4\" using f qs_eq by blast\n      hence \"length (concat ?cs) \\<le> (\\<Sum>q\\<leftarrow>qs. 6*log 2 q - 4)\" using concat_length_le\n        by fast\n      hence \"length (Prime p # ((build_fpc p a (p - 1) qs)@ concat ?cs))\n            \\<le> ((\\<Sum>q\\<leftarrow>(map real qs). 6*log 2 q - 4) + ?k + 2)\"\n            by (simp add: o_def length_fpc)\n      also have \"\\<dots> = (6*(\\<Sum>q\\<leftarrow>(map real qs). log 2 q) + (-4 * real ?k) + ?k + 2)\"\n        by (simp add: o_def listsum_subtractf listsum_triv real_of_nat_def listsum_const_mult)\n      also have \"\\<dots> \\<le> 6*log 2 (p - 1) - 4\" using `?k\\<ge>2` prod_qs_eq listsum_log[of 2 qs] qs_ge_2\n        by force\n      also have \"\\<dots> \\<le> 6*log 2 p - 4\" using Log.log_le_cancel_iff[of 2 \"p - 1\" p] `p>3` by force\n      ultimately have \"length (Prime p # ((build_fpc p a (p - 1) qs)@ concat ?cs))\n                       \\<le> 6*log 2 p - 4\" by linarith }\n    ultimately obtain c where c:\"Triple p a (p - 1) \\<in> set c\" \"valid_cert c\"\n                               \"length (Prime p #c) \\<le> 6*log 2 p - 4\"\n                               \"(\\<forall> x \\<in> set c. size_pratt x \\<le> 3 * log 2 p)\" by blast\n    hence \"Prime p \\<in> set (Prime p # c)\" \"valid_cert (Prime p # c)\"\n         \"(\\<forall> x \\<in> set (Prime p # c). size_pratt x \\<le> 3 * log 2 p)\"\n    using a `prime p` by auto\n    hence ?case using c by blast\n  }\n  moreover have \"p\\<ge>2\" using less by (simp add: prime_ge_2_nat)\n  ultimately show ?case using less by fastforce\nqed\n\ntext {*\n  We now recapitulate our results. A number $p$ is prime if and only if there\n  is a certificate for $p$. Moreover, for a prime $p$ there always is a certificate\n  whose size is polynomially bounded in the logarithm of $p$.\n*}\n\ncorollary pratt:\n  \"prime p \\<longleftrightarrow> (\\<exists>c. Prime p \\<in> set c \\<and> valid_cert c)\"\n  using pratt_complete' pratt_sound(1) by blast\n\ncorollary pratt_size:\n  assumes \"prime p\"\n  shows \"\\<exists>c. Prime p \\<in> set c \\<and> valid_cert c \\<and> size_cert c \\<le> (6 * log 2 p - 4) * (1 + 3 * log 2 p)\"\nproof -\n  obtain c where c: \"Prime p \\<in> set c\" \"valid_cert c\"\n      and len: \"length c \\<le> 6*log 2 p - 4\" and \"(\\<forall> x \\<in> set c. size_pratt x \\<le> 3 * log 2 p)\"\n    using pratt_complete' assms by blast\n  hence \"size_cert c \\<le> length c * (1 + 3 * log 2 p)\" by (simp add: size_pratt_le)\n  also have \"\\<dots> \\<le> (6*log 2 p - 4) * (1 + 3 * log 2 p)\" using len by simp\n  finally show ?thesis using c by blast\nqed\n\nend\n", "meta": {"author": "noschinl", "repo": "pratt", "sha": "363caa7c36ad7b69796dbf3e60ae1081d5fbaec4", "save_path": "github-repos/isabelle/noschinl-pratt", "path": "github-repos/isabelle/noschinl-pratt/pratt-363caa7c36ad7b69796dbf3e60ae1081d5fbaec4/thys/Pratt_Certificate/Pratt_Certificate.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.885631470799559, "lm_q2_score": 0.8221891348788759, "lm_q1q2_score": 0.7281565727981958}}
{"text": "(* author: wzh *)\n\ntheory Chapter3 imports Main\n\nbegin\n\ntype_synonym vname = string\ndatatype aexp = N int | V vname | Plus aexp aexp\n\ntype_synonym val = int\n\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 a1 a2) s = (aval a1 s) + (aval a2 s)\"\n\nvalue \"aval (Plus (N 0) (V x)) (\\<lambda> x.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 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\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\ndatatype bexp = Bc bool | Not bexp | And bexp bexp | Less aexp aexp\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\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 v) s stk = (v # stk)\"\n| \"exec1 (LOAD name) s stk = (s name # stk)\"\n| \"exec1 ADD s (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\n\n\nlemma \"exec (comp a) s stk = aval a s # stk\"\n  apply(induction a arbitrary: stk)\n    apply(auto)\n  done\n\nend\n", "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/Chapter3.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314738181874, "lm_q2_score": 0.8221891283434877, "lm_q1q2_score": 0.7281565694921338}}
{"text": "theory HSV_chapter5 imports Main begin\n\nsection \\<open>Representing circuits (cf. worksheet Section 5.1)\\<close>\n\ntext \\<open>Defining a data structure to represent fan-out-free circuits with numbered inputs\\<close>\n\ndatatype \"circuit\" = \n  NOT \"circuit\"\n| AND \"circuit\" \"circuit\"\n| OR \"circuit\" \"circuit\"\n| TRUE\n| FALSE\n| INPUT \"int\"\n\ntext \\<open>A few example circuits\\<close>\n\ndefinition \"circuit1 == AND (INPUT 1) (INPUT 2)\"\ndefinition \"circuit2 == OR (NOT circuit1) FALSE\"\ndefinition \"circuit3 == NOT (NOT circuit2)\"\ndefinition \"circuit4 == AND circuit3 (INPUT 3)\"\n\nsection \\<open>Simulating circuits (cf. worksheet Section 5.2)\\<close>\n\ntext \\<open>Simulates a circuit given a valuation for each input wire\\<close>\n\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\ntext \\<open>A few example valuations\\<close>\n\ndefinition \"\\<rho>0 == \\<lambda>_. True\"\ndefinition \"\\<rho>1 == \\<rho>0(1 := True, 2 := False, 3 := True)\"\ndefinition \"\\<rho>2 == \\<rho>0(1 := True, 2 := True, 3 := True)\"\n\ntext \\<open>Trying out the simulator\\<close>\n\nvalue \"simulate circuit1 \\<rho>1\"\nvalue \"simulate circuit2 \\<rho>1\"\nvalue \"simulate circuit3 \\<rho>1\"\nvalue \"simulate circuit4 \\<rho>1\"\nvalue \"simulate circuit1 \\<rho>2\"\nvalue \"simulate circuit2 \\<rho>2\"\nvalue \"simulate circuit3 \\<rho>2\"\nvalue \"simulate circuit4 \\<rho>2\"\n\nsection \\<open>Structural induction on circuits (cf. worksheet Section 5.3)\\<close>\n\ntext \\<open>A function that switches each pair of wires entering an OR or AND gate\\<close>\n\nfun mirror where\n  \"mirror (NOT c) = NOT (mirror c)\"\n| \"mirror (AND c1 c2) = AND (mirror c2) (mirror c1)\"\n| \"mirror (OR c1 c2) = OR (mirror c2) (mirror c1)\"\n| \"mirror TRUE = TRUE\"\n| \"mirror FALSE = FALSE\"\n| \"mirror (INPUT i) = INPUT i\"\n\nvalue \"circuit1\"\nvalue \"mirror circuit1\"\nvalue \"circuit2\"\nvalue \"mirror circuit2\"\n\ntext \\<open>The following non-theorem is easily contradicted.\\<close>\n\ntheorem \"mirror c = c\" \n  oops\n\ntext \\<open>Proving that mirroring doesn't affect simulation behaviour.\\<close>\n\ntheorem mirror_is_sound: \"simulate (mirror c) \\<rho> = simulate c \\<rho>\"\n  by (induct c, auto)\n\nsection \\<open>A simple circuit optimiser (cf. worksheet Section 5.4)\\<close>\n\ntext \\<open>A function that optimises a circuit by removing pairs of consecutive NOT gates\\<close>\n\nfun opt_NOT where\n  \"opt_NOT (NOT (NOT c)) = opt_NOT c\"\n| \"opt_NOT (NOT c) = NOT (opt_NOT c)\"\n| \"opt_NOT (AND c1 c2) = AND (opt_NOT c1) (opt_NOT c2)\"\n| \"opt_NOT (OR c1 c2) = OR (opt_NOT c1) (opt_NOT c2)\"\n| \"opt_NOT TRUE = TRUE\"\n| \"opt_NOT FALSE = FALSE\"\n| \"opt_NOT (INPUT i) = INPUT i\"\n\ntext \\<open>Trying out the optimiser\\<close>\n\nvalue \"circuit1\"\nvalue \"opt_NOT circuit1\"\nvalue \"circuit2\"\nvalue \"opt_NOT circuit2\"\nvalue \"circuit3\"\nvalue \"opt_NOT circuit3\"\nvalue \"circuit4\"\nvalue \"opt_NOT circuit4\"\n\nsection \\<open>Rule induction (cf. worksheet Section 5.5)\\<close>\n\ntext \\<open>A Fibonacci function that demonstrates complex recursion schemes\\<close>\n\nfun f :: \"nat \\<Rightarrow> nat\" where\n  \"f (Suc (Suc n)) = f n + f (Suc n)\"\n| \"f (Suc 0) = 1\"\n| \"f 0 = 1\"\n\nthm f.induct (* rule induction theorem for f *)\n\ntext \\<open>We need to prove a stronger version of the theorem below\n  first, in order to make the inductive step work. Just like how \n  it often goes with loop invariants in Dafny!\\<close>\nlemma helper: \"f n \\<ge> n \\<and> f n \\<ge> 1\"\n  by (rule f.induct[of \"\\<lambda>n. f n \\<ge> n \\<and> f n \\<ge> 1\"], auto)\n\ntext \\<open>The nth Fibonacci number is greater than or equal to n\\<close>\ntheorem \"f n \\<ge> n\" \n  using helper by simp\n\nsection \\<open>Verifying our optimiser (cf. worksheet Section 5.6)\\<close>\n\ntext \\<open>The following non-theorem is easily contradicted.\\<close>\n\ntheorem \"opt_NOT c = c\" \n  oops\n\ntext \\<open>The following theorem says that the optimiser is sound.\\<close>\n\ntheorem opt_NOT_is_sound: \"simulate (opt_NOT c) \\<rho> = simulate c \\<rho>\"\n  by (induct rule:opt_NOT.induct, auto)\n\n\nend\n", "meta": {"author": "johnwickerson", "repo": "HSV", "sha": "54be339e0fac44ee7af8ebba9dab10d778164ea3", "save_path": "github-repos/isabelle/johnwickerson-HSV", "path": "github-repos/isabelle/johnwickerson-HSV/HSV-54be339e0fac44ee7af8ebba9dab10d778164ea3/isabelle/HSV_chapter5.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8397339676722393, "lm_q2_score": 0.867035771827307, "lm_q1q2_score": 0.7280793887903069}}
{"text": "theory Directed_Multigraph\n  imports\n    Main\nbegin\n\ntype_synonym ('a, 'b) edge = \"'a \\<times> ('b \\<times> 'b)\"\n\ntype_synonym ('a, 'b) multigraph = \"('a, 'b) edge set\"\n\ndefinition endpoints :: \"('a, 'b) edge \\<Rightarrow> 'b \\<times> 'b\" where\n  \"endpoints \\<equiv> snd\"\n\nlemma mem_endpoints_iff:\n  shows \"vs \\<in> endpoints ` G \\<longleftrightarrow> (\\<exists>\\<epsilon>. (\\<epsilon>, vs) \\<in> G)\"\n  by (force simp add: endpoints_def)\n\ndefinition head :: \"('a, 'b) edge \\<Rightarrow> 'b\" where\n  \"head e \\<equiv> snd (endpoints e)\"\n\ndefinition tail :: \"('a, 'b) edge \\<Rightarrow> 'b\" where\n  \"tail e \\<equiv> fst (endpoints e)\"\n\nlemma mem_ED:\n  assumes \"e \\<in> G\"\n  shows \"(tail e, head e) \\<in> endpoints ` G\"\n  using assms\n  by (simp add: head_def tail_def endpoints_def mem_endpoints_iff)\n\ndefinition V :: \"('a, 'b) multigraph \\<Rightarrow> 'b set\" where\n  \"V G \\<equiv> head ` G \\<union> tail ` G\"\n\nlemma head_mem_V:\n  assumes \"e \\<in> G\"\n  shows \"head e \\<in> V G\"\n  using assms\n  by (simp add: V_def)\n\nlemma head_mem_V_2:\n  assumes \"(\\<epsilon>, u, v) \\<in> G\"\n  shows \"v \\<in> V G\"\n  using assms\n  by (auto simp add: head_def endpoints_def dest: head_mem_V)\n\nlemma head_mem_V_3:\n  assumes \"(u, v) \\<in> endpoints ` G\"\n  shows \"v \\<in> V G\"\n  using assms\n  by (auto simp add: mem_endpoints_iff dest: head_mem_V_2)\n\nlemma tail_mem_V:\n  assumes \"e \\<in> G\"\n  shows \"tail e \\<in> V G\"\n  using assms\n  by (simp add: V_def)\n\nlemma tail_mem_V_2:\n  assumes \"(\\<epsilon>, u, v) \\<in> G\"\n  shows \"u \\<in> V G\"\n  using assms\n  by (auto simp add: tail_def endpoints_def dest: tail_mem_V)\n\nlemma tail_mem_V_3:\n  assumes \"(u, v) \\<in> endpoints ` G\"\n  shows \"u \\<in> V G\"\n  using assms\n  by (auto simp add: mem_endpoints_iff dest: tail_mem_V_2)\n\nlemma mem_VE:\n  assumes \"u \\<in> V G\"\n  obtains v where\n    \"(u, v) \\<in> endpoints ` G \\<or> (v, u) \\<in> endpoints ` G\"\n  using assms\n  by (force simp add: V_def head_def tail_def endpoints_def)\n\nlocale multigraph =\n  fixes G :: \"('a, 'b) multigraph\"\n\nlocale finite_multigraph = multigraph +\n  assumes finite_edges: \"finite G\"\n\nlemma (in finite_multigraph) finite_vertices:\n  shows \"finite (V G)\"\n  using finite_edges\n  by (simp add: V_def)\n\n(**)\n\ndefinition to_edge :: \"'b \\<Rightarrow> 'a \\<times> 'b \\<Rightarrow> ('a, 'b) edge\" where\n  \"to_edge v p \\<equiv> (fst p, (v, snd p))\"\n\ndefinition incidence :: \"('b \\<Rightarrow> ('a \\<times> 'b) list) \\<Rightarrow> 'b \\<Rightarrow> ('a, 'b) edge list\" where\n  \"incidence I v \\<equiv> map (to_edge v) (I v)\"\n\n(* TODO: Rename. *)\ndefinition edges_from_fun :: \"('b \\<Rightarrow> ('a \\<times> 'b) list) \\<Rightarrow> ('a, 'b) multigraph\" where\n  \"edges_from_fun I \\<equiv> \\<Union>v. set (incidence I v)\"\n\nlemma mem_edges_from_funE:\n  assumes \"e \\<in> edges_from_fun I\"\n  obtains v where\n    \"e \\<in> set (incidence I v)\"\n  using assms\n  by (auto simp add: edges_from_fun_def)\n\nlemma mem_edges_from_funI:\n  assumes \"e \\<in> set (incidence I v)\"\n  shows \"e \\<in> edges_from_fun I\"\n  using assms\n  by (auto simp add: edges_from_fun_def)\n\nlocale multigraph_2 =\n  fixes I :: \"'b \\<Rightarrow> ('a \\<times> 'b) list\"\nbegin\n\nlemma inj_to_edge:\n  shows \"inj (to_edge v)\"\n  by (auto simp add: to_edge_def intro: injI)\n\n(* TODO: Move. *)\nlemma inj_on_if_inj:\n  assumes \"inj f\"\n  shows \"inj_on f A\"\n  using assms\n  by (simp add: inj_on_def)\n\nlemma tail_eq:\n  assumes \"e \\<in> set (incidence I v)\"\n  shows \"tail e = v\"\n  using assms\n  by (auto simp add: incidence_def to_edge_def tail_def endpoints_def)\n\nlemma mem_edges_from_funD:\n  assumes \"e \\<in> edges_from_fun I\"\n  shows \"e \\<in> set (incidence I (tail e))\"\n  using assms\n  by (auto simp add: tail_eq elim: mem_edges_from_funE)\n\nsublocale multigraph \"edges_from_fun I\"\n  .\n\nend\n\nlocale finite_multigraph_2 = multigraph_2 +\n  assumes finite_domain: \"finite {v. I v \\<noteq> []}\"\nbegin\n\nlemma edges_from_fun_eq:\n  shows \"edges_from_fun I = \\<Union> ((set \\<circ> incidence I) ` {v. I v \\<noteq> []})\"\n  by (force simp add: edges_from_fun_def incidence_def)\n\nsublocale finite_multigraph \"edges_from_fun I\"\nproof (standard, goal_cases)\n  case 1\n  show ?case\n    using finite_domain\n    by (simp add: edges_from_fun_eq)\nqed\n\nend\n\nend", "meta": {"author": "mitjakrebs", "repo": "master-s-thesis", "sha": "103462c6116a90004f6c0654748bccaf4bfd67be", "save_path": "github-repos/isabelle/mitjakrebs-master-s-thesis", "path": "github-repos/isabelle/mitjakrebs-master-s-thesis/master-s-thesis-103462c6116a90004f6c0654748bccaf4bfd67be/Graph/Directed_Graph/Directed_Multigraph.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8670357701094303, "lm_q2_score": 0.8397339656668286, "lm_q1q2_score": 0.7280793856089847}}
{"text": "theory Girth_Chromatic\nimports\n  Ugraphs\n  Girth_Chromatic_Misc\n  \"~~/src/HOL/Probability/Probability\"\n\n  \"~~/src/HOL/Number_Theory/Binomial\"\n  \"~~/src/HOL/Decision_Procs/Approximation\"\nbegin\n\nsection {* Probability Space on Sets of Edges *}\n\ndefinition cylinder :: \"'a set \\<Rightarrow> 'a set \\<Rightarrow> 'a set \\<Rightarrow> 'a set set\" where\n  \"cylinder S A B = {T \\<in> Pow S. A \\<subseteq> T \\<and> B \\<inter> T = {}}\"\n\nlemma full_sum:\n  fixes p :: real\n  assumes \"finite S\"\n  shows \"(\\<Sum>A\\<in>Pow S. p^card A * (1 - p)^card (S - A)) = 1\"\nusing assms\nproof induct\n  case (insert s S)\n  have \"inj_on (insert s) (Pow S)\"\n      and \"\\<And>x. S - insert s x = S - x\"\n      and \"Pow S \\<inter> insert s ` Pow S = {}\"\n      and \"\\<And>x. x \\<in> Pow S \\<Longrightarrow> card (insert s S - x) = Suc (card (S - x))\"\n    using insert(1-2) by (auto simp: insert_Diff_if intro!: inj_onI)\n  moreover have \"\\<And>x. x \\<subseteq> S \\<Longrightarrow> card (insert s x) = Suc (card x)\"\n    using insert(1-2) by (subst card.insert) (auto dest: finite_subset)\n  ultimately show ?case\n    by (simp add: setsum.reindex setsum_right_distrib[symmetric] ac_simps\n                  insert.hyps setsum.union_disjoint Pow_insert)\nqed simp\n\ntext {* Definition of the probability space on edges: *}\nlocale edge_space =\n  fixes n :: nat and p :: real\n  assumes p_prob: \"0 \\<le> p\" \"p \\<le> 1\"\nbegin\n\ndefinition S_verts :: \"nat set\" where\n  \"S_verts \\<equiv> {1..n}\"\n\ndefinition S_edges :: \"uedge set\" where\n  \"S_edges = all_edges S_verts\"\n\ndefinition edge_ugraph :: \"uedge set \\<Rightarrow> ugraph\" where\n  \"edge_ugraph es \\<equiv> (S_verts, es \\<inter> S_edges)\"\n\ndefinition \"P = point_measure (Pow S_edges) (\\<lambda>s. p^card s * (1 - p)^card (S_edges - s))\"\n\nlemma finite_verts[intro!]: \"finite S_verts\"\n  by (auto simp: S_verts_def)\n\nlemma finite_edges[intro!]: \"finite S_edges\"\n  by (auto simp: S_edges_def all_edges_def finite_verts)\n\nlemma finite_graph[intro!]: \"finite (uverts (edge_ugraph es))\"\n  unfolding edge_ugraph_def by auto\n\nlemma uverts_edge_ugraph[simp]: \"uverts (edge_ugraph es) = S_verts\"\n  by (simp add: edge_ugraph_def)\n\nlemma uedges_edge_ugraph[simp]: \"uedges (edge_ugraph es) = es \\<inter> S_edges\"\n  unfolding edge_ugraph_def by simp\n\nlemma space_eq: \"space P = Pow S_edges\" by (simp add: P_def space_point_measure)\n\nlemma sets_eq: \"sets P = Pow (Pow S_edges)\" by (simp add: P_def sets_point_measure)\n\nlemma emeasure_eq:\n  \"emeasure P A = (if A \\<subseteq> Pow S_edges then (\\<Sum>edges\\<in>A. p^card edges * (1 - p)^card (S_edges - edges)) else 0)\"\n  using finite_edges p_prob\n  by (simp add: P_def space_point_measure emeasure_point_measure_finite zero_le_mult_iff\n                zero_le_power_iff sets_point_measure emeasure_notin_sets)\n\nlemma integrable_P[intro, simp]: \"integrable P (f::_ \\<Rightarrow> real)\"\n  using finite_edges by (simp add: integrable_point_measure_finite P_def)\n\nlemma borel_measurable_P[measurable]: \"f \\<in> borel_measurable P\"\n  unfolding P_def by simp\n  \nlemma prob_space_P: \"prob_space P\"\nproof\n  show \"emeasure P (space P) = 1\" -- {* Sum of probabilities equals 1 *}\n    using finite_edges by (simp add: emeasure_eq full_sum one_ereal_def space_eq)\nqed\n\nend\n\nsublocale edge_space \\<subseteq> prob_space P\n  by (rule prob_space_P)\n\ncontext edge_space\nbegin\n\nlemma prob_eq:\n  \"prob A = (if A \\<subseteq> Pow S_edges then (\\<Sum>edges\\<in>A. p^card edges * (1 - p)^card (S_edges - edges)) else 0)\"\n  using emeasure_eq[of A] unfolding emeasure_eq_measure by simp\n\nlemma integral_finite_singleton: \"integral\\<^sup>L P f = (\\<Sum>x\\<in>Pow S_edges. f x * measure P {x})\"\n  using p_prob prob_eq unfolding P_def\n  by (subst lebesgue_integral_point_measure_finite) (auto intro!: setsum.cong)\n\ntext {* Probability of cylinder sets: *}\nlemma cylinder_prob:\n  assumes \"A \\<subseteq> S_edges\" \"B \\<subseteq> S_edges\" \"A \\<inter> B = {}\"\n  shows \"prob (cylinder S_edges A B) = p ^ (card A) * (1 - p) ^ (card B)\" (is \"_ = ?pp A B\")\nproof -\n  have \"Pow S_edges \\<inter> cylinder S_edges A B = cylinder S_edges A B\"\n       \"\\<And>x. x \\<in> cylinder S_edges A B \\<Longrightarrow> A \\<union> x = x\"\n       \"\\<And>x. x \\<in> cylinder S_edges A B \\<Longrightarrow> finite x\"\n       \"\\<And>x. x \\<in> cylinder S_edges A B \\<Longrightarrow> B \\<inter> (S_edges - B - x) = {}\"\n       \"\\<And>x. x \\<in> cylinder S_edges A B \\<Longrightarrow> B \\<union> (S_edges - B - x) = S_edges - x\"\n       \"finite A\" \"finite B\"\n    using assms by (auto simp add: cylinder_def intro: finite_subset)\n  then have \"(\\<Sum>T\\<in>cylinder S_edges A B. ?pp T (S_edges - T))\n      = (\\<Sum>T \\<in> cylinder S_edges A B. p^(card A + card (T - A)) * (1 - p)^(card B + card ((S_edges - B) - T)))\"\n    using finite_edges by (simp add: card_Un_Int)\n  also have \"\\<dots> = ?pp A B * (\\<Sum>T\\<in>cylinder S_edges A B. ?pp (T - A) (S_edges - B - T))\"\n    by (simp add: power_add setsum_right_distrib ac_simps)\n  also have \"\\<dots> = ?pp A B\"\n  proof -\n    have \"\\<And>T. T \\<in> cylinder S_edges A B \\<Longrightarrow> S_edges - B - T = (S_edges - A) - B - (T - A)\"\n         \"Pow (S_edges - A - B) = (\\<lambda>x. x - A) ` cylinder S_edges A B\"\n         \"inj_on (\\<lambda>x. x - A) (cylinder S_edges A B)\"\n         \"finite (S_edges - A - B)\"\n      using assms by (auto simp: cylinder_def intro!: inj_onI)\n    with full_sum[of \"S_edges - A - B\"] show ?thesis by (simp add: setsum.reindex)\n  qed\n  finally show ?thesis by (auto simp add: prob_eq cylinder_def)\nqed\n\nlemma Markov_inequality:\n  fixes a :: real and X :: \"uedge set \\<Rightarrow> real\"\n  assumes \"0 < c\" \"\\<And>x. 0 \\<le> f x\"\n  shows \"prob {x \\<in> space P. c \\<le> f x} \\<le> (\\<integral>x. f x \\<partial> P) / c\"\nproof -\n  from assms have \"(\\<integral>\\<^sup>+ x. ereal (f x) \\<partial>P) = (\\<integral>x. f x \\<partial>P)\"\n    by (intro nn_integral_eq_integral) auto\n  with assms show ?thesis\n    using nn_integral_Markov_inequality[of f P \"space P\" \"1 / c\"]\n    by (simp cong: nn_integral_cong add: emeasure_eq_measure one_ereal_def)\nqed\n\nend\n\nsubsection {* Graph Probabilities outside of @{term Edge_Space} locale*}\n\ntext {*\n These abbreviations allow a compact expression of probabilities about random\n graphs outside of the @{term Edge_Space} locale. We also transfer a few of the lemmas\n we need from the locale into the toplevel theory.\n*}\n\nabbreviation MGn :: \"(nat \\<Rightarrow> real) \\<Rightarrow> nat \\<Rightarrow> (uedge set) measure\" where\n  \"MGn p n \\<equiv> (edge_space.P n (p n))\"\nabbreviation probGn :: \"(nat \\<Rightarrow> real) \\<Rightarrow> nat \\<Rightarrow> (uedge set \\<Rightarrow> bool) \\<Rightarrow> real\" where\n  \"probGn p n P \\<equiv> measure (MGn p n) {es \\<in> space (MGn p n). P es}\"\n\nlemma probGn_le:\n  assumes p_prob: \"0 < p n\" \"p n < 1\"\n  assumes sub: \"\\<And>n es. es \\<in> space (MGn p n) \\<Longrightarrow> P n es \\<Longrightarrow> Q n es\"\n  shows \"probGn p n (P n) \\<le> probGn p n (Q n)\"\nproof -\n  from p_prob interpret E: edge_space n \"p n\" by unfold_locales auto\n  show ?thesis\n    by (auto intro!: E.finite_measure_mono sub simp: E.space_eq E.sets_eq)\nqed\n\nsection {* Short cycles *}\n\ndefinition short_cycles :: \"ugraph \\<Rightarrow> nat \\<Rightarrow> uwalk set\" where\n  \"short_cycles G k \\<equiv> {p \\<in> ucycles G. uwalk_length p \\<le> k}\"\n\ntext {* obtains a vertex in a short cycle: *}\ndefinition choose_v :: \"ugraph \\<Rightarrow> nat \\<Rightarrow> uvert\" where\n  \"choose_v G k \\<equiv> SOME u. \\<exists>p. p \\<in> short_cycles G k \\<and> u \\<in> set p\"\n\npartial_function (tailrec) kill_short :: \"ugraph \\<Rightarrow> nat \\<Rightarrow> ugraph\" where\n  \"kill_short G k = (if short_cycles G k = {} then G else (kill_short (G -- (choose_v G k)) k))\"\n\nlemma ksc_simps[simp]:\n  \"short_cycles G k = {} \\<Longrightarrow> kill_short G k = G\"\n  \"short_cycles G k \\<noteq> {}  \\<Longrightarrow> kill_short G k = kill_short (G -- (choose_v G k)) k\"\n  by (auto simp: kill_short.simps)\n\nlemma\n  assumes \"short_cycles G k \\<noteq> {}\"\n  shows choose_v__in_uverts: \"choose_v G k \\<in> uverts G\" (is ?t1)\n    and choose_v__in_short: \"\\<exists>p. p \\<in> short_cycles G k \\<and> choose_v G k \\<in> set p\" (is ?t2)\nproof -\n  from assms obtain p where \"p \\<in> ucycles G\" \"uwalk_length p \\<le> k\"\n    unfolding short_cycles_def by auto\n  moreover\n  then obtain u where \"u \\<in> set p\" unfolding ucycles_def\n    by (cases p) (auto simp: uwalk_length_conv)\n  ultimately have \"\\<exists>u p. p \\<in> short_cycles G k \\<and> u \\<in> set p\"\n    by (auto simp: short_cycles_def)\n  then show ?t2 by (auto simp: choose_v_def intro!: someI_ex)\n  then show ?t1 by (auto simp: short_cycles_def ucycles_def uwalks_def)\nqed\n\nlemma kill_step_smaller:\n  assumes \"short_cycles G k \\<noteq> {}\"\n  shows \"short_cycles (G -- (choose_v G k)) k \\<subset> short_cycles G k\"\nproof -\n  let ?cv = \"choose_v G k\"\n  from assms obtain p where \"p \\<in> short_cycles G k\" \"?cv \\<in> set p\"\n    by atomize_elim (rule choose_v__in_short)\n\n  have \"short_cycles (G -- ?cv) k \\<subseteq> short_cycles G k\"\n  proof\n    fix p assume \"p \\<in> short_cycles (G -- ?cv) k\"\n    then show \"p \\<in> short_cycles G k\"\n      unfolding short_cycles_def ucycles_def uwalks_def\n      using edges_Gu[of G ?cv] by (auto simp: verts_Gu)\n  qed\n  moreover have \"p \\<notin> short_cycles (G -- ?cv) k\"\n    using `?cv \\<in> set p` by (auto simp: short_cycles_def ucycles_def uwalks_def verts_Gu)\n  ultimately show ?thesis using `p \\<in> short_cycles G k` by auto\nqed\n\ntext {* Induction rule for @{term kill_short}: *}\nlemma kill_short_induct[consumes 1, case_names empty kill_vert]:\n  assumes fin: \"finite (uverts G)\"\n  assumes a_empty: \"\\<And>G. short_cycles G k = {} \\<Longrightarrow> P G k\"\n  assumes a_kill: \"\\<And>G. finite (short_cycles G k) \\<Longrightarrow> short_cycles G k \\<noteq> {}\n    \\<Longrightarrow> P (G -- (choose_v G k)) k \\<Longrightarrow> P G k\"\n  shows \"P G k\"\nproof -\n  have \"finite (short_cycles G k)\"\n    using finite_ucycles[OF fin] by (auto simp: short_cycles_def)\n  then show ?thesis\n    by (induct \"short_cycles G k\" arbitrary: G rule: finite_psubset_induct)\n      (metis kill_step_smaller a_kill a_empty)\nqed\n\ntext {* Large Girth (after @{term kill_short}): *}\nlemma kill_short_large_girth:\n  assumes \"finite (uverts G)\"\n  shows \"k < girth (kill_short G k)\"\nusing assms\nproof (induct G k rule: kill_short_induct)\n  case (empty G)\n  then have \"\\<And>p. p \\<in> ucycles G \\<Longrightarrow> k < enat (uwalk_length p)\"\n    by (auto simp: short_cycles_def)\n  with empty show ?case by (auto simp: girth_def intro: enat_less_INF_I)\nqed simp\n\ntext {* Order of graph (after @{term kill_short}): *}\nlemma kill_short_order_of_graph:\n  assumes \"finite (uverts G)\"\n  shows \"card (uverts G) - card (short_cycles G k) \\<le> card (uverts (kill_short G k))\"\nusing assms assms\nproof (induct G k rule: kill_short_induct)\n  case (kill_vert G)\n  let ?oG = \"G -- (choose_v G k)\"\n\n  have \"finite (uverts ?oG)\"\n    using kill_vert by (auto simp: remove_vertex_def)\n  moreover\n  have \"uverts (kill_short G k) = uverts (kill_short ?oG k)\"\n    using kill_vert by simp\n  moreover\n  have \"card (uverts G) = Suc (card (uverts ?oG))\"\n    using choose_v__in_uverts kill_vert\n    by (simp add: remove_vertex_def card_Suc_Diff1 del: card_Diff_insert)\n  moreover\n  have \"card (short_cycles ?oG k) < card (short_cycles G k)\"\n    by (intro psubset_card_mono kill_vert.hyps kill_step_smaller)\n  ultimately show ?case using kill_vert.hyps by presburger\nqed simp\n\ntext {* Independence number (after @{term kill_short}): *}\nlemma kill_short_\\<alpha>:\n  assumes \"finite (uverts G)\"\n  shows \"\\<alpha> (kill_short G k) \\<le> \\<alpha> G\"\nusing assms\nproof (induct G k rule: kill_short_induct)\n  case (kill_vert G)\n  note kill_vert(3)\n  also have \"\\<alpha> (G -- (choose_v G k)) \\<le> \\<alpha> G\" by (rule \\<alpha>_remove_le)\n  finally show ?case using kill_vert by simp\nqed simp\n\ntext {* Wellformedness (after @{term kill_short}): *}\nlemma kill_short_uwellformed:\n  assumes \"finite (uverts G)\" \"uwellformed G\"\n  shows \"uwellformed (kill_short G k)\"\nusing assms\nproof (induct G k rule: kill_short_induct)\n  case (kill_vert G)\n  from kill_vert.prems have \"uwellformed (G -- (choose_v G k))\"\n    by (auto simp: uwellformed_def remove_vertex_def)\n  with kill_vert.hyps show ?case by simp\nqed simp\n\n\nsection {* The Chromatic-Girth Theorem *}\n\ntext {* Probability of Independent Edges: *}\nlemma (in edge_space) random_prob_independent:\n  assumes \"n \\<ge> k\" \"k \\<ge> 2\"\n  shows \"prob {es \\<in> space P. k \\<le> \\<alpha> (edge_ugraph es)}\n    \\<le> (n choose k)*(1-p)^(k choose 2)\"\nproof -\n  let \"?k_sets\" = \"{vs. vs \\<subseteq> S_verts \\<and> card vs = k}\"\n\n  { fix vs assume A: \"vs \\<in> ?k_sets\"\n    then have B: \"all_edges vs \\<subseteq> S_edges\"\n      unfolding all_edges_def S_edges_def by blast\n\n    have \"{es \\<in> space P. vs \\<in> independent_sets (edge_ugraph es)}\n        = cylinder S_edges {} (all_edges vs)\" (is \"?L = _\")\n      using A by (auto simp: independent_sets_def edge_ugraph_def space_eq cylinder_def)\n    then have \"prob ?L = (1-p)^(k choose 2)\"\n      using A B finite by (auto simp: cylinder_prob card_all_edges dest: finite_subset)\n  }\n  note prob_k_indep = this\n    -- \"probability that a fixed set of k vertices is independent in a random graph\"\n\n  have \"{es \\<in> space P. k \\<in> card ` independent_sets (edge_ugraph es)}\n    = (\\<Union>vs \\<in> ?k_sets. {es \\<in> space P. vs \\<in> independent_sets (edge_ugraph es)})\" (is \"?L = ?R\")\n    unfolding image_def space_eq independent_sets_def by auto\n  then have \"prob ?L \\<le> (\\<Sum>vs \\<in> ?k_sets. prob {es \\<in> space P. vs \\<in> independent_sets (edge_ugraph es)})\"\n    by (auto intro!: finite_measure_subadditive_finite simp: space_eq sets_eq)\n  also have \"\\<dots> = (n choose k)*((1 - p) ^ (k choose 2))\"\n    by (simp add: prob_k_indep real_eq_of_nat S_verts_def n_subsets)\n  finally show ?thesis using `k \\<ge> 2` by (simp add: le_\\<alpha>_iff)\nqed\n\ntext {* Almost never many independent edges: *}\nlemma almost_never_le_\\<alpha>:\n  fixes k :: nat\n    and p :: \"nat \\<Rightarrow> real\"\n  assumes p_prob: \"\\<forall>\\<^sup>\\<infinity> n. 0 < p n \\<and> p n < 1\"\n  assumes [arith]: \"k > 0\"\n  assumes N_prop: \"\\<forall>\\<^sup>\\<infinity> n. (6 * k * ln n)/n \\<le> p n\"\n  shows \"(\\<lambda>n. probGn p n (\\<lambda>es. 1/2*n/k \\<le> \\<alpha> (edge_space.edge_ugraph n es))) ----> 0\"\n    (is \"(\\<lambda>n. ?prob_fun n) ----> 0\")\nproof -\n  let \"?prob_fun_raw n\" = \"probGn p n (\\<lambda>es. natceiling (1/2*n/k) \\<le> \\<alpha> (edge_space.edge_ugraph n es))\"\n\n  def r \\<equiv> \"\\<lambda>(n :: nat). (1 / 2 * n / k)\"\n  let \"?nr n\" = \"natceiling (r n)\"\n\n  have r_pos: \"\\<And>n. 0 < n \\<Longrightarrow> 0 < r n \" by (auto simp: r_def field_simps)\n\n  have nr_bounds: \"\\<forall>\\<^sup>\\<infinity> n. 2 \\<le> ?nr n \\<and> ?nr n \\<le> n\"\n    by (intro eventually_sequentiallyI[of \"4 * k\"])\n      (simp add: r_def natceiling_le le_natceiling_iff field_simps)\n\n  from nr_bounds p_prob have ev_prob_fun_raw_le:\n    \"\\<forall>\\<^sup>\\<infinity> n. probGn p n (\\<lambda>es. ?nr n\\<le> \\<alpha> (edge_space.edge_ugraph n es))\n      \\<le> (n * exp (- p n * (real (?nr n) - 1) / 2)) powr ?nr n\"\n    (is \"\\<forall>\\<^sup>\\<infinity> n. ?prob_fun_raw_le n\")\n  proof (rule eventually_elim2)\n    fix n :: nat assume A: \"2 \\<le> ?nr n \\<and> ?nr n \\<le> n\" \"0 < p n \\<and>p n < 1\"\n    then interpret pG: edge_space n \"p n\" by unfold_locales auto\n\n    have r: \"real (?nr n - 1) = real (?nr n) - 1\" using A by auto\n\n    have \"probGn p n (\\<lambda>es. ?nr n \\<le> \\<alpha> (edge_space.edge_ugraph n es))\n        \\<le> (n choose ?nr n) * (1 - p n)^(?nr n choose 2)\"\n      using A by (auto intro: pG.random_prob_independent)\n    also have \"\\<dots> \\<le> n powr ?nr n * (1 - p n) powr (?nr n choose 2)\"\n      using A\n      by (simp add: powr_realpow power_real_of_nat binomial_le_pow del: real_of_nat_power)\n    also have \"\\<dots> = n powr ?nr n * (1 - p n) powr (?nr n * (?nr n - 1) / 2)\"\n      by (cases \"even (?nr n - 1)\")\n        (auto simp add: n_choose_2_nat real_of_nat_div)\n    also have \"\\<dots> = n powr ?nr n * ((1 - p n) powr ((?nr n - 1) / 2)) powr ?nr n\"\n      by (auto simp: powr_powr algebra_simps)\n    also have \"\\<dots> \\<le> (n * exp (- p n * (?nr n - 1) / 2)) powr ?nr n\"\n    proof -\n      have \"(1 - p n) powr ((?nr n - 1) / 2) \\<le> exp (- p n) powr ((?nr n - 1) / 2)\"\n        using A by (auto simp: powr_mono2 diff_conv_add_uminus simp del: add_uminus_conv_diff)\n      also have \"\\<dots> = exp (- p n * (?nr n - 1) / 2)\" by (auto simp: powr_def)\n      finally show ?thesis\n        using A by (auto simp: powr_mono2 powr_mult)\n    qed\n    finally show \"probGn p n (\\<lambda>es. ?nr n \\<le> \\<alpha> (edge_space.edge_ugraph n es))\n      \\<le> (n * exp (- p n * (real (?nr n) - 1) / 2)) powr ?nr n\"\n      using A r by simp\n  qed\n\n  from p_prob N_prop\n  have ev_expr_bound: \"\\<forall>\\<^sup>\\<infinity> n. n * exp (-p n * (real (?nr n) - 1) / 2) \\<le> (exp 1 / n) powr (1 / 2)\"\n  proof (elim eventually_rev_mp, intro eventually_sequentiallyI conjI impI)\n    fix n assume n_bound[arith]: \"2 \\<le> n\"\n      and p_bound: \"0 < p n \\<and> p n < 1\" \"(6 * k * ln n) / n \\<le> p n\"\n    have r_bound: \"r n \\<le> ?nr n\" by (rule real_natceiling_ge)\n\n    have \"n * exp (-p n * (real (?nr n)- 1) / 2) \\<le> n * exp (- 3 / 2 * ln n + p n / 2)\"\n    proof -\n      have \"0 < ln n\" using \"n_bound\" by auto\n      then have \"(3 / 2) * ln n \\<le> ((6 * k * ln n) / n) * (?nr n / 2)\"\n        using r_bound by (simp add: r_def field_simps del: ln_gt_zero_iff)\n      also have \"\\<dots> \\<le> p n * (?nr n / 2)\"\n        using n_bound p_bound r_bound r_pos[of n] by (auto simp: field_simps)\n      finally show ?thesis using r_bound by (auto simp: field_simps)\n    qed\n    also have \"\\<dots> \\<le> n * n powr (- 3 / 2) * exp 1 powr (1 / 2)\"\n      using p_bound by (simp add: powr_def exp_add [symmetric])\n    also have \"\\<dots> \\<le> n powr (-1 / 2) * exp 1 powr (1 / 2)\" by (simp add: powr_mult_base)\n    also have \"\\<dots> = (exp 1 / n) powr (1/2)\"\n      by (simp add: powr_divide powr_minus_divide)\n    finally show \"n * exp (- p n * (real (?nr n) - 1) / 2) \\<le> (exp 1 / n) powr (1 / 2)\" .\n  qed\n\n  have ceil_bound: \"\\<And>G n. 1/2*n/k \\<le> \\<alpha> G \\<longleftrightarrow> natceiling (1/2*n/k) \\<le> \\<alpha> G\"\n    by (case_tac \"\\<alpha> G\") (auto simp: natceiling_le_eq)\n\n  show ?thesis\n  proof (unfold ceil_bound, rule real_tendsto_sandwich)\n    show \"(\\<lambda>n. 0) ----> 0\"\n        \"(\\<lambda>n. (exp 1 / n) powr (1 / 2)) ----> 0\"\n        \"\\<forall>\\<^sup>\\<infinity> n. 0 \\<le> ?prob_fun_raw n\"\n      using p_prob by (auto intro: measure_nonneg LIMSEQ_inv_powr elim: eventually_elim1)\n  next\n    from nr_bounds ev_expr_bound ev_prob_fun_raw_le\n    show \"\\<forall>\\<^sup>\\<infinity> n. ?prob_fun_raw n \\<le> (exp 1 / n) powr (1 / 2)\"\n    proof (elim eventually_rev_mp, intro eventually_sequentiallyI impI conjI)\n      fix n assume A: \"3 \\<le> n\"\n        and nr_bounds: \"2 \\<le> ?nr n \\<and> ?nr n \\<le> n\"\n        and prob_fun_raw_le: \"?prob_fun_raw_le n\"\n        and expr_bound: \"n * exp (- p n * (real (natceiling (r n)) - 1) / 2) \\<le> (exp 1 / n) powr (1 / 2)\"\n\n      have \"exp 1 < (3 :: real)\" by (approximation 5)\n      then have \"(exp 1 / n) powr (1 / 2) \\<le> 1 powr (1 / 2)\"\n        using A by (intro powr_mono2) (auto simp: field_simps)\n      then have ep_bound: \"(exp 1 / n) powr (1 / 2) \\<le> 1\" by simp\n\n      have \"?prob_fun_raw n \\<le> (n * exp (- p n * (real (?nr n) - 1) / 2)) powr (?nr n)\"\n        using prob_fun_raw_le by (simp add: r_def)\n      also have \"\\<dots> \\<le> ((exp 1 / n) powr (1 / 2)) powr ?nr n\"\n        using expr_bound A by (auto simp: powr_mono2)\n      also have \"\\<dots> \\<le> ((exp 1 / n) powr (1 / 2))\"\n        using nr_bounds ep_bound by (auto simp: powr_le_one_le)\n      finally show \"?prob_fun_raw n \\<le> (exp 1 / n) powr (1 / 2)\" .\n    qed\n  qed\nqed\n\ntext {* Mean number of k-cycles in a graph. (Or rather of paths describing a circle of length @{term k}): *}\nlemma (in edge_space) mean_k_cycles:\n  assumes \"3 \\<le> k\" \"k < n\"\n  shows \"(\\<integral>es. card {c \\<in> ucycles (edge_ugraph es). uwalk_length c = k} \\<partial> P)\n    = (fact n div fact (n - k)) * p ^ k\"\nproof -\n  let ?k_cycle = \"\\<lambda>es c k. c \\<in> ucycles (edge_ugraph es) \\<and> uwalk_length c = k\"\n  def C \\<equiv> \"\\<lambda>k. {c. ?k_cycle S_edges c k}\"\n    -- {* @{term \"C k\"} is the set of all possible cycles of size @{term k} in @{term \"edge_ugraph S_edges\"} *}\n  def XG \\<equiv> \"\\<lambda>es. {c. ?k_cycle es c k}\"\n    -- {* @{term \"XG es\"} is the set of cycles contained in a @{term \"edge_ugraph es\"} *}\n  def XC \\<equiv> \"\\<lambda>c. {es \\<in> space P. ?k_cycle es c k}\"\n    -- {* \"@{term \"XC c\"} is the set of graphs (edge sets) containing a cycle c\" *}\n  then have XC_in_sets: \"\\<And>c. XC c \\<in> sets P\"\n      and XC_cyl: \"\\<And>c. c \\<in> C k \\<Longrightarrow> XC c = cylinder S_edges (set (uwalk_edges c)) {}\"\n    by (auto simp: ucycles_def space_eq uwalks_def C_def cylinder_def sets_eq)\n\n  have \"(\\<integral>es. card {c \\<in> ucycles (edge_ugraph es). uwalk_length c = k} \\<partial> P)\n      =  (\\<Sum>x\\<in>space P. card (XG x) * prob {x})\"\n    by (simp add: XG_def integral_finite_singleton space_eq)\n  also have \"\\<dots> = (\\<Sum>c\\<in>C k. prob (cylinder S_edges (set (uwalk_edges c)) {}))\"\n  proof -\n    have XG_Int_C: \"\\<And>s. s \\<in> space P \\<Longrightarrow> C k \\<inter> XG s = XG s\"\n      unfolding XG_def C_def ucycles_def uwalks_def edge_ugraph_def by auto\n    have fin_XC: \"\\<And>k. finite (XC k)\" and fin_C: \"finite (C k)\"\n      unfolding C_def XC_def by (auto simp: finite_edges space_eq intro!: finite_ucycles)\n\n    have \"(\\<Sum>x\\<in>space P. card (XG x) * prob {x}) = (\\<Sum>x\\<in>space P. (\\<Sum>c \\<in> XG x. prob {x}))\"\n      by (simp add: real_eq_of_nat)\n    also have \"\\<dots> = (\\<Sum>x\\<in>space P. (\\<Sum>c \\<in> C k. if c \\<in> XG x then prob {x} else 0))\"\n      using fin_C by (simp add: setsum.If_cases) (simp add: XG_Int_C)\n    also have \"\\<dots> = (\\<Sum>c \\<in> C k. (\\<Sum> x \\<in> space P \\<inter> XC c. prob {x}))\"\n      using finite_edges by (subst setsum.commute) (simp add: setsum.inter_restrict XG_def XC_def space_eq)\n    also have \"\\<dots> = (\\<Sum>c \\<in> C k. prob (XC c))\"\n      using fin_XC XC_in_sets\n      by (auto simp add: prob_eq sets_eq space_eq intro!: setsum.cong)\n    finally show ?thesis by (simp add: XC_cyl)\n  qed\n  also have \"\\<dots> = (\\<Sum>c\\<in>C k. p ^ k)\"\n  proof -\n    have \"\\<And>x. x \\<in> C k \\<Longrightarrow> card (set (uwalk_edges x)) = uwalk_length x\"\n      by (auto simp: uwalk_length_def C_def ucycles_distinct_edges intro: distinct_card)\n    then show ?thesis by (auto simp: C_def ucycles_def uwalks_def cylinder_prob)\n  qed\n  also have \"\\<dots> = (fact n div fact (n - k)) * p ^ k\"\n  proof -\n    have inj_last_Cons: \"\\<And>A. inj_on (\\<lambda>es. last es # es) A\" by (rule inj_onI) simp\n    { fix xs A assume \"3 \\<le> length xs - Suc 0\" \"hd xs = last xs\"\n      then have \"xs \\<in> (\\<lambda>xs. last xs # xs) ` A \\<longleftrightarrow> tl xs \\<in> A\"\n        by (cases xs) (auto simp: inj_image_mem_iff[OF inj_last_Cons] split: split_if_asm) }\n    note image_mem_iff_inst = this\n\n    { fix xs have \"xs \\<in> uwalks (edge_ugraph S_edges) \\<Longrightarrow> set (tl xs) \\<subseteq> S_verts\"\n        unfolding uwalks_def by (induct xs) auto }\n    moreover\n    { fix xs assume \"set xs \\<subseteq> S_verts\" \"2 \\<le> length xs\" \"distinct xs\"\n      then have \"(last xs # xs) \\<in> uwalks (edge_ugraph S_edges)\"\n      proof (induct xs rule: uwalk_edges.induct)\n        case (3 x y ys)\n        have S_edges_memI: \"\\<And>x y. x \\<in> S_verts \\<Longrightarrow> y \\<in> S_verts \\<Longrightarrow> x \\<noteq> y \\<Longrightarrow> {x, y} \\<in> S_edges\"\n          unfolding S_edges_def all_edges_def image_def by auto\n\n        have \"ys \\<noteq> [] \\<Longrightarrow> set ys \\<subseteq> S_verts \\<Longrightarrow> last ys \\<in> S_verts\"  by auto\n        with 3 show ?case\n          by (auto simp add: uwalks_def Suc_le_eq intro: S_edges_memI)\n      qed simp_all}\n    moreover note `3 \\<le> k`\n    ultimately\n    have \"C k = (\\<lambda>xs. last xs # xs) ` {xs. length xs = k \\<and> distinct xs \\<and> set xs \\<subseteq> S_verts}\"\n      by (auto simp: C_def ucycles_def uwalk_length_conv image_mem_iff_inst)\n    moreover have \"card S_verts = n\" by (simp add: S_verts_def)\n    ultimately have \"card (C k) = fact n div fact (n - k)\"\n      using `k < n`\n      by (simp add: card_image[OF inj_last_Cons] card_lists_distinct_length_eq fact_div_fact)\n    then show ?thesis by (simp add: real_eq_of_nat)\n  qed                                    \n  finally show ?thesis by simp\nqed\n\ntext {* Girth-Chromatic number theorem: *}\ntheorem girth_chromatic:\n  fixes l :: nat\n  shows \"\\<exists>G. uwellformed G \\<and> l < girth G \\<and> l < chromatic_number G\"\nproof -\n  def k \\<equiv> \"max 3 l\" \n  def \\<epsilon> \\<equiv> \"1 / (2 * k)\"\n  def p \\<equiv> \"\\<lambda>(n :: nat). real n powr (\\<epsilon> - 1)\"\n\n  let ?ug = edge_space.edge_ugraph\n\n  def short_count \\<equiv> \"\\<lambda>g. card (short_cycles g k)\"\n    -- {* This random variable differs from the one used in the proof of theorem 11.2.2,\n          as we count the number of paths describing a circle, not the circles themselves *}\n\n  from k_def have \"3 \\<le> k\" \"l \\<le> k\" by auto\n  from \\<epsilon>_def `3 \\<le> k` have \\<epsilon>_props: \"0 < \\<epsilon>\" \"\\<epsilon> < 1 / k\" \"\\<epsilon> < 1\" by (auto simp: field_simps)\n\n  have ev_p: \"\\<forall>\\<^sup>\\<infinity> n. 0 < p n \\<and> p n < 1\"\n  proof (rule eventually_sequentiallyI)\n    fix n :: nat assume \"2 \\<le> n\"\n    with `\\<epsilon> < 1` have \"n powr (\\<epsilon> - 1) < 1\" by (auto intro!: powr_less_one)\n    then show \"0 < p n \\<and> p n < 1\" by (auto simp: p_def)\n  qed\n  then\n  have prob_short_count_le: \"\\<forall>\\<^sup>\\<infinity> n. probGn p n (\\<lambda>es. (real n/2) \\<le> short_count (?ug n es))\n      \\<le> 2 * (k - 2) * n powr (\\<epsilon> * k - 1)\"  (is \"\\<forall>\\<^sup>\\<infinity> n. ?P n\")\n  proof (elim eventually_rev_mp, intro eventually_sequentiallyI impI)\n    fix n :: nat assume A: \"Suc k \\<le> n\" \"0 < p n \\<and> p n < 1\"\n    then interpret pG: edge_space n \"p n\" by unfold_locales auto\n    have \"1 \\<le> n\" using A by auto\n  \n    def mean_short_count \\<equiv> \"\\<integral>es. short_count (?ug n es) \\<partial> pG.P\"\n  \n    have mean_short_count_le: \"mean_short_count \\<le> (k - 2) * n powr (\\<epsilon> * k)\"\n    proof -\n      have small_empty: \"\\<And>es k. k \\<le> 2 \\<Longrightarrow> short_cycles (edge_space.edge_ugraph n es) k = {}\"\n          by (auto simp add: short_cycles_def ucycles_def)\n      have short_count_conv: \"\\<And>es. short_count (?ug n es) = (\\<Sum>i=3..k. real (card {c \\<in> ucycles (?ug n es). uwalk_length c = i}))\"\n      proof (unfold short_count_def, induct k)\n        case 0 with small_empty show ?case by auto\n      next\n        case (Suc k)\n        show ?case proof (cases \"Suc k \\<le> 2\")\n          case True with small_empty show ?thesis by auto\n        next\n          case False\n          have \"{c \\<in> ucycles (?ug n es). uwalk_length c \\<le> Suc k}\n              = {c \\<in> ucycles (?ug n es). uwalk_length c \\<le> k} \\<union> {c \\<in> ucycles (?ug n es). uwalk_length c = Suc k}\"\n            by auto\n          moreover\n          have \"finite (uverts (edge_space.edge_ugraph n es))\" by auto\n          ultimately\n          have \"card {c \\<in> ucycles (?ug n es). uwalk_length c \\<le> Suc k}\n            = card {c \\<in> ucycles (?ug n es). uwalk_length c \\<le> k} + card {c \\<in> ucycles (?ug n es). uwalk_length c = Suc k}\"\n            using finite_ucycles by (subst card_Un_disjoint[symmetric]) auto\n          then show ?thesis\n            using Suc False unfolding short_cycles_def by (auto simp: not_le)\n        qed\n      qed\n  \n      have \"mean_short_count = (\\<Sum>i=3..k. \\<integral>es. card {c \\<in> ucycles (?ug n es). uwalk_length c = i} \\<partial> pG.P)\"\n        unfolding mean_short_count_def short_count_conv\n        by (subst integral_setsum) (auto intro: pG.integral_finite_singleton)\n      also have \"\\<dots> = (\\<Sum>i\\<in>{3..k}. (fact n div fact (n - i)) * p n ^ i)\"\n        using A by (simp add: pG.mean_k_cycles)\n      also have \"\\<dots> \\<le> (\\<Sum> i\\<in>{3..k}. n ^ i * p n ^ i)\"\n        using A fact_div_fact_le_pow\n        by (auto intro: setsum_mono simp del: real_of_nat_power)\n      also have \"... \\<le> (\\<Sum> i\\<in>{3..k}. n powr (\\<epsilon> * k))\"\n        using `1 \\<le> n` `0 < \\<epsilon>` A\n        by (intro setsum_mono) (auto simp: p_def field_simps powr_mult_base powr_powr\n          powr_realpow[symmetric] powr_mult[symmetric] powr_add[symmetric])\n      finally show ?thesis by (simp add: real_eq_of_nat)\n    qed\n  \n    have \"pG.prob {es \\<in> space pG.P. n/2 \\<le> short_count (?ug n es)} \\<le> mean_short_count / (n/2)\"\n      unfolding mean_short_count_def using `1 \\<le> n`\n      by (intro pG.Markov_inequality) (auto simp: short_count_def)\n    also have \"\\<dots> \\<le> 2 * (k - 2) * n powr (\\<epsilon> * k - 1)\"\n    proof -\n      have \"mean_short_count / (n / 2) \\<le> 2 * (k - 2) * (1 / n powr 1) * n powr (\\<epsilon> * k)\"\n        using mean_short_count_le `1 \\<le> n` by (simp add: field_simps)\n      then show ?thesis by (simp add: powr_divide2[symmetric] algebra_simps)\n    qed\n    finally show \"?P n\" .\n  qed\n\n  def pf_short_count \\<equiv> \"\\<lambda>n. probGn p n (\\<lambda>es. n/2 \\<le> short_count (?ug n es))\"\n    and pf_\\<alpha> \\<equiv> \"\\<lambda>n. probGn p n (\\<lambda>es. 1/2 * n/k \\<le> \\<alpha> (edge_space.edge_ugraph n es))\"\n\n  have ev_short_count_le: \"\\<forall>\\<^sup>\\<infinity> n. pf_short_count n < 1 / 2\"\n  proof -\n    have \"\\<epsilon> * k - 1 < 0\"\n      using \\<epsilon>_props `3 \\<le> k` by (auto simp: field_simps)\n    then have \"(\\<lambda>n. 2 * (k - 2) * n powr (\\<epsilon> * k - 1)) ----> 0\" (is \"?bound ----> 0\")\n      by (intro tendsto_mult_right_zero LIMSEQ_neg_powr)\n    then have \"\\<forall>\\<^sup>\\<infinity> n. dist (?bound n) 0  < 1 / 2\"\n      by (rule tendstoD) simp\n    with prob_short_count_le show ?thesis\n      by (rule eventually_elim2) (auto simp: dist_real_def pf_short_count_def)\n  qed\n\n  have lim_\\<alpha>: \"pf_\\<alpha> ----> 0\"\n  proof -\n    have \"0 < k\" using `3 \\<le> k` by simp\n\n    have \"\\<forall>\\<^sup>\\<infinity> n. (6*k) * ln n / n \\<le> p n \\<longleftrightarrow> (6*k) * ln n * n powr - \\<epsilon> \\<le> 1\"\n    proof (rule eventually_sequentiallyI)\n     fix n :: nat assume \"1 \\<le> n\"\n      then have \"(6 * k) * ln n / n \\<le> p n \\<longleftrightarrow> (6*k) * ln n * (n powr - 1) \\<le> n powr (\\<epsilon> - 1)\"\n        by  (subst powr_minus) (simp add: divide_inverse p_def)\n      also have \"\\<dots> \\<longleftrightarrow> (6*k) * ln n * ((n powr - 1) / (n powr (\\<epsilon> - 1))) \\<le> n powr (\\<epsilon> - 1) / (n powr (\\<epsilon> - 1))\"\n        by auto\n      also have \"\\<dots> \\<longleftrightarrow> (6*k) * ln n * n powr - \\<epsilon> \\<le> 1\"\n        by (simp add: powr_divide2)\n      finally show \"(6*k) * ln n / n \\<le> p n \\<longleftrightarrow> (6*k) * ln n * n powr - \\<epsilon> \\<le> 1\" .\n    qed\n    then have \"(\\<forall>\\<^sup>\\<infinity> n. (6 * k) * ln n / real n \\<le> p n)\n        \\<longleftrightarrow> (\\<forall>\\<^sup>\\<infinity> n. (6*k) * ln n * n powr - \\<epsilon> \\<le> 1)\"\n      by (rule eventually_subst)\n    also have \"\\<forall>\\<^sup>\\<infinity> n. (6*k) * ln n * n powr - \\<epsilon> \\<le> 1\"\n    proof -\n      { fix n :: nat assume \"0 < n\"\n        have \"ln (real n) \\<le> n powr (\\<epsilon>/2) / (\\<epsilon>/2)\"\n          using `0 < n` `0 < \\<epsilon>` by (intro ln_powr_bound) auto\n        also have \"\\<dots> \\<le> 2/\\<epsilon> * n powr (\\<epsilon>/2)\" by (auto simp: field_simps)\n        finally have \"(6*k) * ln n * (n powr - \\<epsilon>)  \\<le> (6*k) * (2/\\<epsilon> * n powr (\\<epsilon>/2)) * (n powr - \\<epsilon>)\"\n          using `0 < n` `0 < k` by (intro mult_right_mono mult_left_mono) auto\n        also have \"\\<dots> = 12*k/\\<epsilon> * n powr (-\\<epsilon>/2)\"\n          unfolding divide_inverse\n          by (auto simp: field_simps powr_minus[symmetric] powr_add[symmetric])\n        finally have \"(6*k) * ln n * (n powr - \\<epsilon>) \\<le> 12*k/\\<epsilon> * n powr (-\\<epsilon>/2)\" .\n      }\n      then have \"\\<forall>\\<^sup>\\<infinity> n. (6*k) * ln n * (n powr - \\<epsilon>) \\<le> 12*k/\\<epsilon> * n powr (-\\<epsilon>/2)\"\n        by (intro eventually_sequentiallyI[of 1]) auto\n      also have \"\\<forall>\\<^sup>\\<infinity> n. 12*k/\\<epsilon> * n powr (-\\<epsilon>/2) \\<le> 1\"\n      proof -\n        have \"(\\<lambda>n. 12*k/\\<epsilon> * n powr (-\\<epsilon>/2)) ----> 0\"\n          using `0 < \\<epsilon>` by (intro tendsto_mult_right_zero LIMSEQ_neg_powr) auto\n        then show ?thesis\n          using `0 < \\<epsilon>` by (auto elim: eventually_elim1 simp: dist_real_def dest!: tendstoD[where e=1])\n      qed\n      finally (eventually_le_le) show ?thesis .\n    qed\n    finally have \"\\<forall>\\<^sup>\\<infinity> n. real (6 * k) * ln (real n) / real n \\<le> p n\" .\n    with ev_p `0 < k` show ?thesis unfolding pf_\\<alpha>_def by (rule almost_never_le_\\<alpha>)\n  qed\n\n  from ev_short_count_le lim_\\<alpha>[THEN tendstoD, of \"1/2\"] ev_p\n  have \"\\<forall>\\<^sup>\\<infinity> n. 0 < p n \\<and> p n < 1 \\<and> pf_short_count n < 1/2 \\<and> pf_\\<alpha> n < 1/2\"\n    by simp (elim eventually_rev_mp, auto simp: eventually_sequentially dist_real_def)\n  then obtain n where \"0 < p n\" \"p n < 1\" and [arith]: \"0 < n\"\n      and probs: \"pf_short_count n < 1/2\" \"pf_\\<alpha> n < 1/2\"\n    by (auto simp: eventually_sequentially)\n  then interpret ES: edge_space n \"(p n)\" by unfold_locales auto\n\n  have rest_compl: \"\\<And>A P. A - {x\\<in>A. P x} = {x\\<in>A. \\<not>P x}\" by blast\n\n  from probs have \"ES.prob ({es \\<in> space ES.P. n/2 \\<le> short_count (?ug n es)}\n      \\<union> {es \\<in> space ES.P. 1/2 * n/k \\<le> \\<alpha> (?ug n es)}) \\<le> pf_short_count n + pf_\\<alpha> n\"\n    unfolding pf_short_count_def pf_\\<alpha>_def  by (subst ES.finite_measure_subadditive) auto\n  also have \"\\<dots> < 1\" using probs by auto\n  finally have \"0 < ES.prob (space ES.P - ({es \\<in> space ES.P. n/2 \\<le> short_count (?ug n es)}\n      \\<union> {es \\<in> space ES.P. 1/2 * n/k \\<le> \\<alpha> (?ug n es)}))\" (is \"0 < ES.prob ?S\")\n    by (subst ES.prob_compl) auto\n  also have \"?S = {es \\<in> space ES.P. short_count (?ug n es) < n/2 \\<and> \\<alpha> (?ug n es) < 1/2* n/k}\" (is \"\\<dots> = ?C\")\n    by (auto simp: not_less rest_compl)\n  finally have \"?C \\<noteq> {}\" by (intro notI) (simp only:, auto)\n  then obtain es where es_props: \"es \\<in> space ES.P\"\n      \"short_count (?ug n es) < n/2\" \"\\<alpha> (?ug n es) < 1/2 * n/k\"\n    by auto\n    -- \"now we obtained a high colored graph (few independent nodes) with almost no short cycles\"\n\n  def G \\<equiv> \"?ug n es\"\n  def H \\<equiv> \"kill_short G k\"\n\n  have G_props: \"uverts G = {1..n}\" \"finite (uverts G)\" \"short_count G < n/2\" \"\\<alpha> G < 1/2 * n/k\"\n    unfolding G_def using es_props by (auto simp: ES.S_verts_def)\n\n  have \"uwellformed G\" by (auto simp: G_def uwellformed_def all_edges_def ES.S_edges_def)\n  with G_props have T1: \"uwellformed H\" unfolding H_def by (intro kill_short_uwellformed)\n\n  have \"enat l \\<le> enat k\" using `l \\<le> k` by simp\n  also have \"\\<dots> < girth H\" using G_props by (auto simp: kill_short_large_girth H_def)\n  finally have T2: \"l < girth H\" .\n\n  have card_H: \"n/2 \\<le> card (uverts H)\"\n    using G_props es_props kill_short_order_of_graph[of G k] by (simp add: short_count_def H_def)\n\n  then have uverts_H: \"uverts H \\<noteq> {}\" \"0 < card (uverts H)\" by auto\n  then have \"0 < \\<alpha> H\" using zero_less_\\<alpha> uverts_H by auto\n\n  have \\<alpha>_HG: \"\\<alpha> H \\<le> \\<alpha> G\"\n    unfolding H_def G_def by (auto intro: kill_short_\\<alpha>)\n\n  have \"enat l \\<le> ereal k\" using `l \\<le> k` by auto\n  also have \"\\<dots> < (n/2) / \\<alpha> G\" using G_props `3 \\<le> k`\n    by (cases \"\\<alpha> G\") (auto simp: real_of_nat_def[symmetric] field_simps)\n  also have \"\\<dots> \\<le> (n/2) / \\<alpha> H\" using \\<alpha>_HG `0 < \\<alpha> H`\n    by (auto simp: ereal_of_enat_pushout intro!: ereal_divide_left_mono)\n  also have \"\\<dots> \\<le> card (uverts H) / \\<alpha> H\" using card_H `0 < \\<alpha> H`\n    by (auto intro!: ereal_divide_right_mono)\n  also have \"\\<dots> \\<le> chromatic_number H\" using uverts_H T1 by (intro chromatic_lb) auto\n  finally have T3: \"l < chromatic_number H\"\n    by (simp add: ereal_of_enat_less_iff del: ereal_of_enat_simps)\n\n  from T1 T2 T3 show ?thesis by fast\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/Girth_Chromatic/Girth_Chromatic.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357666736773, "lm_q2_score": 0.8397339676722393, "lm_q1q2_score": 0.728079384462629}}
{"text": "(* \n  Author: Jeremy Dawson, NICTA\n*) \n\nsection {* Integers as implict bit strings *}\n\ntheory Bit_Representation\nimports Misc_Numeric\nbegin\n\nsubsection {* Constructors and destructors for binary integers *}\n\ndefinition Bit :: \"int \\<Rightarrow> bool \\<Rightarrow> int\" (infixl \"BIT\" 90)\nwhere\n  \"k BIT b = (if b then 1 else 0) + k + k\"\n\nlemma Bit_B0:\n  \"k BIT False = k + k\"\n   by (unfold Bit_def) simp\n\nlemma Bit_B1:\n  \"k BIT True = k + k + 1\"\n   by (unfold Bit_def) simp\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\ndefinition bin_last :: \"int \\<Rightarrow> bool\"\nwhere\n  \"bin_last w \\<longleftrightarrow> w mod 2 = 1\"\n\nlemma bin_last_odd:\n  \"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\"\nwhere\n  \"bin_rest w = w div 2\"\n\nlemma bin_rl_simp [simp]:\n  \"bin_rest w BIT bin_last w = w\"\n  unfolding bin_rest_def bin_last_def Bit_def\n  using mod_div_equality [of w 2]\n  by (cases \"w mod 2 = 0\", 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  apply (auto simp add: Bit_def)\n  apply arith\n  apply arith\n  done\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  unfolding Bit_def\n  by (simp_all del: arith_simps add_numeral_special diff_numeral_special)\n\nlemma BIT_special_simps [simp]:\n  shows \"0 BIT False = 0\" and \"0 BIT True = 1\"\n  and \"1 BIT False = 2\" and \"1 BIT True = 3\"\n  and \"(- 1) BIT False = - 2\" and \"(- 1) BIT True = - 1\"\n  unfolding Bit_def by simp_all\n\nlemma Bit_eq_0_iff: \"w BIT b = 0 \\<longleftrightarrow> w = 0 \\<and> \\<not> b\"\n  apply (auto simp add: Bit_def)\n  apply arith\n  done\n\nlemma Bit_eq_m1_iff: \"w BIT b = -1 \\<longleftrightarrow> w = -1 \\<and> b\"\n  apply (auto simp add: Bit_def)\n  apply arith\n  done\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  unfolding add_One by (simp_all add: 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  unfolding expand_BIT bin_last_BIT 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  unfolding expand_BIT bin_rest_BIT by (simp_all add: bin_rest_def zdiv_zminus1_eq_if)\n\nlemma less_Bits: \n  \"v BIT b < w BIT c \\<longleftrightarrow> v < w \\<or> v \\<le> w \\<and> \\<not> b \\<and> c\"\n  unfolding Bit_def by auto\n\nlemma le_Bits: \n  \"v BIT b \\<le> w BIT c \\<longleftrightarrow> v < w \\<or> v \\<le> w \\<and> (\\<not> b \\<or> c)\" \n  unfolding Bit_def by auto\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': \n  \"X = 2 ==> (w BIT True) mod X = 1 & (w BIT False) mod X = 0\"\n  apply (simp (no_asm) only: Bit_B0 Bit_B1)\n  apply simp\n  done\n\nlemma bin_ex_rl: \"EX w b. w BIT b = bin\"\n  by (metis bin_rl_simp)\n\nlemma bin_exhaust:\n  assumes Q: \"\\<And>x b. bin = x BIT b \\<Longrightarrow> Q\"\n  shows \"Q\"\n  apply (insert bin_ex_rl [of bin])  \n  apply (erule exE)+\n  apply (rule Q)\n  apply force\n  done\n\nprimrec bin_nth 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_abs_lem:\n  \"bin = (w BIT b) ==> bin ~= -1 --> bin ~= 0 -->\n    nat (abs w) < nat (abs bin)\"\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: \"!!bin bit. P bin ==> P (bin BIT bit)\"\n  shows \"P bin\"\n  apply (rule_tac P=P and a=bin and f1=\"nat o abs\" \n                  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_nth_eq_iff:\n  \"bin_nth x = bin_nth y \\<longleftrightarrow> x = y\"\nproof -\n  have bin_nth_lem [rule_format]: \"ALL y. bin_nth x = bin_nth y --> 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, \n            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, \n           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\" in fun_cong, force)\n    done\n  show ?thesis\n  by (auto elim: bin_nth_lem)\nqed\n\nlemmas bin_eqI = ext [THEN bin_nth_eq_iff [THEN iffD1]]\n\nlemma bin_eq_iff:\n  \"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 ==> bin_nth (w BIT b) n = bin_nth w (n - 1)\"\n  by (cases n) auto\n\nlemma bin_nth_numeral:\n  \"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\n\nsubsection {* Truncating binary integers *}\n\ndefinition bin_sign :: \"int \\<Rightarrow> int\"\nwhere\n  bin_sign_def: \"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  unfolding bin_sign_def Bit_def\n  by simp_all\n\nlemma bin_sign_rest [simp]: \n  \"bin_sign (bin_rest w) = bin_sign w\"\n  by (cases w rule: bin_exhaust) auto\n\nprimrec bintrunc :: \"nat \\<Rightarrow> int \\<Rightarrow> int\" 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 => int => int\" 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 sign_bintr: \"bin_sign (bintrunc n w) = 0\"\n  by (induct n arbitrary: w) auto\n\nlemma bintrunc_mod2p: \"bintrunc n w = (w mod 2 ^ n)\"\n  apply (induct n arbitrary: w, clarsimp)\n  apply (simp add: bin_last_def bin_rest_def Bit_def zmod_zmult2_eq)\n  done\n\nlemma sbintrunc_mod2p: \"sbintrunc n w = (w + 2 ^ n) mod 2 ^ (Suc n) - 2 ^ n\"\n  apply (induct n arbitrary: w)\n   apply simp\n   apply (subst mod_add_left_eq)\n   apply (simp add: bin_last_def)\n   apply arith\n  apply (simp add: bin_last_def bin_rest_def Bit_def)\n  apply (clarsimp simp: mod_mult_mult1 [symmetric] \n         zmod_zdiv_equality [THEN diff_eq_eq [THEN iffD2 [THEN sym]]])\n  apply (rule trans [symmetric, OF _ emep1])\n  apply auto\n  done\n\nsubsection \"Simplifications for (s)bintrunc\"\n\nlemma bintrunc_n_0 [simp]: \"bintrunc n 0 = 0\"\n  by (induct n) auto\n\nlemma sbintrunc_n_0 [simp]: \"sbintrunc n 0 = 0\"\n  by (induct n) auto\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)) =\n    bintrunc n (- numeral w) BIT False\"\n  \"bintrunc (Suc n) (- numeral (Num.Bit1 w)) =\n    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)) =\n    sbintrunc n (numeral w) BIT False\"\n  \"sbintrunc (Suc n) (numeral (Num.Bit1 w)) =\n    sbintrunc n (numeral w) BIT True\"\n  \"sbintrunc (Suc n) (- numeral (Num.Bit0 w)) =\n    sbintrunc n (- numeral w) BIT False\"\n  \"sbintrunc (Suc n) (- numeral (Num.Bit1 w)) =\n    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 = (n < m & 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:\n  \"bin_nth (sbintrunc m w) n = \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:\n  \"bin_nth (w BIT b) n = (n = 0 & b | (EX m. n = Suc m & 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  \"n <= m ==> (bintrunc m (bintrunc n w) = bintrunc n w)\"\n  by (rule bin_eqI) (auto simp add : nth_bintr)\n\nlemma sbintrunc_sbintrunc_l:\n  \"n <= m ==> (sbintrunc m (sbintrunc n w) = sbintrunc n w)\"\n  by (rule bin_eqI) (auto simp: nth_sbintr)\n\nlemma bintrunc_bintrunc_ge:\n  \"n <= m ==> (bintrunc n (bintrunc m w) = bintrunc n w)\"\n  by (rule bin_eqI) (auto simp: nth_bintr)\n\nlemma bintrunc_bintrunc_min [simp]:\n  \"bintrunc m (bintrunc n w) = bintrunc (min m n) w\"\n  apply (rule bin_eqI)\n  apply (auto simp: nth_bintr)\n  done\n\nlemma sbintrunc_sbintrunc_min [simp]:\n  \"sbintrunc m (sbintrunc n w) = sbintrunc (min m n) w\"\n  apply (rule bin_eqI)\n  apply (auto simp: nth_sbintr min.absorb1 min.absorb2)\n  done\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\", \n               simplified bin_last_numeral_simps bin_rest_numeral_simps]\n\nlemmas sbintrunc_Min = \n  sbintrunc.Z [where bin=\"-1\",\n               simplified bin_last_numeral_simps bin_rest_numeral_simps]\n\nlemmas sbintrunc_0_BIT_B0 [simp] = \n  sbintrunc.Z [where bin=\"w BIT False\", \n               simplified bin_last_numeral_simps bin_rest_numeral_simps] for w\n\nlemmas sbintrunc_0_BIT_B1 [simp] = \n  sbintrunc.Z [where bin=\"w BIT True\", \n               simplified bin_last_BIT bin_rest_numeral_simps] 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:\n  \"0 < n ==> bintrunc (Suc (n - 1)) w = bintrunc n w\"\n  by auto\n\nlemma sbintrunc_minus:\n  \"0 < n ==> 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 = \"%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:\n  \"bintrunc (Suc n) x = y ==> m = Suc n ==> 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:\n  \"sbintrunc (Suc n) x = y ==> m = Suc n ==> 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:\n  \"m > n ==> sbintrunc n (bintrunc m w) = sbintrunc n w\"\n  by (rule bin_eqI) (auto simp: nth_sbintr nth_bintr)\n\nlemma bintrunc_sbintrunc_le:\n  \"m <= Suc n ==> bintrunc m (sbintrunc n w) = bintrunc m w\"\n  apply (rule bin_eqI)\n  apply (auto simp: nth_sbintr nth_bintr)\n   apply (subgoal_tac \"x=n\", safe, arith+)[1]\n  apply (subgoal_tac \"x=n\", safe, arith+)[1]\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]:\n  \"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]:\n  \"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: \n  \"bintrunc (Suc n) x = bintrunc (Suc n) y <-> \n   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 <-> \n            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 =\n    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 =\n    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)) =\n    bintrunc (pred_numeral k) (numeral w) BIT False\"\n  \"bintrunc (numeral k) (numeral (Num.Bit1 w)) =\n    bintrunc (pred_numeral k) (numeral w) BIT True\"\n  \"bintrunc (numeral k) (- numeral (Num.Bit0 w)) =\n    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)) =\n    sbintrunc (pred_numeral k) (numeral w) BIT False\"\n  \"sbintrunc (numeral k) (numeral (Num.Bit1 w)) =\n    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 <= i & i < 2 ^ n}\"\n  apply (unfold no_bintr_alt1)\n  apply (auto simp add: image_iff)\n  apply (rule exI)\n  apply (auto intro: int_mod_lem [THEN iffD1, symmetric])\n  done\n\nlemma no_sbintr_alt2: \n  \"sbintrunc n = (%w. (w + 2 ^ n) mod 2 ^ Suc n - 2 ^ n :: int)\"\n  by (rule ext) (simp add : sbintrunc_mod2p)\n\nlemma range_sbintrunc: \n  \"range (sbintrunc n) = {i. - (2 ^ n) <= i & i < 2 ^ n}\"\n  apply (unfold no_sbintr_alt2)\n  apply (auto simp add: image_iff eq_diff_eq)\n  apply (rule exI)\n  apply (auto intro: int_mod_lem [THEN iffD1, symmetric])\n  done\n\nlemma sb_inc_lem:\n  \"(a::int) + 2^k < 0 \\<Longrightarrow> a + 2^k + 2^(Suc k) <= (a + 2^k) mod 2^(Suc k)\"\n  apply (erule int_mod_ge' [where n = \"2 ^ (Suc k)\" and b = \"a + 2 ^ k\", simplified zless2p])\n  apply (rule TrueI)\n  done\n\nlemma sb_inc_lem':\n  \"(a::int) < - (2^k) \\<Longrightarrow> a + 2^k + 2^(Suc k) <= (a + 2^k) mod 2^(Suc k)\"\n  by (rule sb_inc_lem) simp\n\nlemma sbintrunc_inc:\n  \"x < - (2^n) ==> x + 2^(Suc n) <= sbintrunc n x\"\n  unfolding no_sbintr_alt2 by (drule sb_inc_lem') simp\n\nlemma sb_dec_lem:\n  \"(0::int) \\<le> - (2 ^ k) + a \\<Longrightarrow> (a + 2 ^ k) mod (2 * 2 ^ k) \\<le> - (2 ^ k) + a\"\n  using int_mod_le'[where n = \"2 ^ (Suc k)\" and b = \"a + 2 ^ k\"] by simp\n\nlemma sb_dec_lem':\n  \"(2::int) ^ k \\<le> a \\<Longrightarrow> (a + 2 ^ k) mod (2 * 2 ^ k) \\<le> - (2 ^ k) + a\"\n  by (rule sb_dec_lem) simp\n\nlemma sbintrunc_dec:\n  \"x >= (2 ^ n) ==> x - 2 ^ (Suc n) >= sbintrunc n x\"\n  unfolding no_sbintr_alt2 by (drule sb_dec_lem') simp\n\nlemmas zmod_uminus' = zminus_zmod [where m=c] for c\nlemmas zpower_zmod' = power_mod [where b=c and n=k] for c k\n\nlemmas brdmod1s' [symmetric] =\n  mod_add_left_eq mod_add_right_eq\n  mod_diff_left_eq mod_diff_right_eq\n  mod_mult_left_eq mod_mult_right_eq\n\nlemmas brdmods' [symmetric] = \n  zpower_zmod' [symmetric]\n  trans [OF mod_add_left_eq mod_add_right_eq] \n  trans [OF mod_diff_left_eq mod_diff_right_eq] \n  trans [OF mod_mult_right_eq mod_mult_left_eq] \n  zmod_uminus' [symmetric]\n  mod_add_left_eq [where b = \"1::int\"]\n  mod_diff_left_eq [where b = \"1::int\"]\n\nlemmas bintr_arith1s =\n  brdmod1s' [where c=\"2^n::int\", folded bintrunc_mod2p] for n\nlemmas bintr_ariths =\n  brdmods' [where c=\"2^n::int\", folded bintrunc_mod2p] for n\n\nlemmas m2pths = pos_mod_sign pos_mod_bound [OF zless2p]\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: \n  \"(bin_sign bin = 0) = (bin >= (0 :: int))\"\n  unfolding bin_sign_def by simp\n\nlemma sign_Min_lt_0: \n  \"(bin_sign bin = -1) = (bin < (0 :: int))\"\n  unfolding bin_sign_def by simp\n\nlemma bin_rest_trunc:\n  \"(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) = \n    bintrunc (n - k) ((bin_rest ^^ k) bin)\"\n  by (induct k) (auto simp: bin_rest_trunc)\n\nlemma bin_rest_trunc_i:\n  \"bintrunc n (bin_rest bin) = bin_rest (bintrunc (Suc n) bin)\"\n  by auto\n\nlemma bin_rest_strunc:\n  \"bin_rest (sbintrunc (Suc n) bin) = sbintrunc n (bin_rest bin)\"\n  by (induct n arbitrary: bin) auto\n\nlemma bintrunc_rest [simp]: \n  \"bintrunc n (bin_rest (bintrunc n bin)) = bin_rest (bintrunc n bin)\"\n  apply (induct n arbitrary: bin, simp)\n  apply (case_tac bin rule: bin_exhaust)\n  apply (auto simp: bintrunc_bintrunc_l)\n  done\n\nlemma sbintrunc_rest [simp]:\n  \"sbintrunc n (bin_rest (sbintrunc n bin)) = bin_rest (sbintrunc n bin)\"\n  apply (induct n arbitrary: bin, 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':\n  \"bintrunc n o bin_rest o bintrunc n = bin_rest o bintrunc n\"\n  by (rule ext) auto\n\nlemma sbintrunc_rest' :\n  \"sbintrunc n o bin_rest o sbintrunc n = bin_rest o sbintrunc n\"\n  by (rule ext) auto\n\nlemma rco_lem:\n  \"f o g o f = g o f ==> f o (g o f) ^^ n = g ^^ n o 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 {* Splitting and concatenation *}\n\nprimrec bin_split :: \"nat \\<Rightarrow> int \\<Rightarrow> int \\<times> int\" where\n  Z: \"bin_split 0 w = (w, 0)\"\n  | Suc: \"bin_split (Suc n) w = (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\" 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\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/Word/Bit_Representation.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357598021707, "lm_q2_score": 0.8397339736884712, "lm_q1q2_score": 0.7280793839086798}}
{"text": "(*  \n  Title:    Order_Predicates.thy\n  Author:   Manuel Eberl, TU M\u00fcnchen\n\n  Locales for order relations modelled as predicates (as opposed to sets of pairs).\n*)\nsection \\<open>Order Relations as Binary Predicates\\<close>\n\ntheory Order_Predicates\nimports \n  Main\n  \"HOL-Library.Disjoint_Sets\"\n  \"HOL-Library.Permutations\"\n  \"List-Index.List_Index\"\nbegin\n\n\n\nsubsection \\<open>Basic Operations on Relations\\<close>\n\ntext \\<open>The type of binary relations\\<close>\ntype_synonym 'a relation = \"'a \\<Rightarrow> 'a \\<Rightarrow> bool\"\n\ndefinition map_relation :: \"('a \\<Rightarrow> 'b) \\<Rightarrow> 'b relation \\<Rightarrow> 'a relation\" where\n  \"map_relation f R = (\\<lambda>x y. R (f x) (f y))\"\n\ndefinition restrict_relation :: \"'a set \\<Rightarrow> 'a relation \\<Rightarrow> 'a relation\" where\n  \"restrict_relation A R = (\\<lambda>x y. x \\<in> A \\<and> y \\<in> A \\<and> R x y)\"\n\nlemma restrict_relation_restrict_relation [simp]:\n  \"restrict_relation A (restrict_relation B R) = restrict_relation (A \\<inter> B) R\"\n  by (intro ext) (auto simp add: restrict_relation_def)\n\nlemma restrict_relation_empty [simp]: \"restrict_relation {} R = (\\<lambda>_ _. False)\"\n  by (simp add: restrict_relation_def)\n\nlemma restrict_relation_UNIV [simp]: \"restrict_relation UNIV R = R\"\n  by (simp add: restrict_relation_def)\n\n\nsubsection \\<open>Preorders\\<close>\n\ntext \\<open>Preorders are reflexive and transitive binary relations.\\<close>\nlocale preorder_on =\n  fixes carrier :: \"'a set\"\n  fixes le :: \"'a relation\"\n  assumes not_outside: \"le x y \\<Longrightarrow> x \\<in> carrier\" \"le x y \\<Longrightarrow> y \\<in> carrier\"\n  assumes refl: \"x \\<in> carrier \\<Longrightarrow> le x x\"\n  assumes trans: \"le x y \\<Longrightarrow> le y z \\<Longrightarrow> le x z\"\nbegin\n\nlemma carrier_eq: \"carrier = {x. le x x}\"\n  using not_outside refl by auto\n  \nlemma preorder_on_map:\n  \"preorder_on (f -` carrier) (map_relation f le)\"\n  by unfold_locales (auto dest: not_outside simp: map_relation_def refl elim: trans)\n  \nlemma preorder_on_restrict:\n  \"preorder_on (carrier \\<inter> A) (restrict_relation A le)\"\n  by unfold_locales (auto simp: restrict_relation_def refl intro: trans not_outside)\n\nlemma preorder_on_restrict_subset:\n  \"A \\<subseteq> carrier \\<Longrightarrow> preorder_on A (restrict_relation A le)\"\n  using preorder_on_restrict[of A] by (simp add: Int_absorb1)\n\nlemma restrict_relation_carrier [simp]:\n  \"restrict_relation carrier le = le\"\n  using not_outside by (intro ext) (auto simp add: restrict_relation_def)\n\nend\n  \n\nsubsection \\<open>Total preorders\\<close>\n\ntext \\<open>Total preorders are preorders where any two elements are comparable.\\<close>\nlocale total_preorder_on = preorder_on +\n  assumes total: \"x \\<in> carrier \\<Longrightarrow> y \\<in> carrier \\<Longrightarrow> le x y \\<or> le y x\"\nbegin\n\nlemma total': \"\\<not>le x y \\<Longrightarrow> x \\<in> carrier \\<Longrightarrow> y \\<in> carrier \\<Longrightarrow> le y x\"\n  using total[of x y] by blast\n\nlemma total_preorder_on_map:\n  \"total_preorder_on (f -` carrier) (map_relation f le)\"\nproof -\n  interpret R': preorder_on \"f -` carrier\" \"map_relation f le\"\n    using preorder_on_map[of f] .\n  show ?thesis by unfold_locales (simp add: map_relation_def total)\nqed\n\nlemma total_preorder_on_restrict:\n  \"total_preorder_on (carrier \\<inter> A) (restrict_relation A le)\"\nproof -\n  interpret R': preorder_on \"carrier \\<inter> A\" \"restrict_relation A le\"\n    by (rule preorder_on_restrict)\n  from total show ?thesis\n    by unfold_locales (auto simp: restrict_relation_def)\nqed\n\nlemma total_preorder_on_restrict_subset:\n  \"A \\<subseteq> carrier \\<Longrightarrow> total_preorder_on A (restrict_relation A le)\"\n  using total_preorder_on_restrict[of A] by (simp add: Int_absorb1)\n\nend\n\n\ntext \\<open>Some fancy notation for order relations\\<close>\nabbreviation (input) weakly_preferred :: \"'a \\<Rightarrow> 'a relation \\<Rightarrow> 'a \\<Rightarrow> bool\"\n    (\"_ \\<preceq>[_] _\" [51,10,51] 60) where\n  \"a \\<preceq>[R] b \\<equiv> R a b\"\n  \ndefinition strongly_preferred (\"_ \\<prec>[_] _\" [51,10,51] 60) where\n  \"a \\<prec>[R] b \\<equiv> (a \\<preceq>[R] b) \\<and> \\<not>(b \\<preceq>[R] a)\"\n\ndefinition indifferent (\"_ \\<sim>[_] _\" [51,10,51] 60) where\n  \"a \\<sim>[R] b \\<equiv> (a \\<preceq>[R] b) \\<and> (b \\<preceq>[R] a)\"\n\nabbreviation (input) weakly_not_preferred (\"_ \\<succeq>[_] _\" [51,10,51] 60) where\n  \"a \\<succeq>[R] b \\<equiv> b \\<preceq>[R] a\"\n  term \"a \\<succeq>[R] b \\<longleftrightarrow> b \\<preceq>[R] a\"\n\nabbreviation (input) strongly_not_preferred (\"_ \\<succ>[_] _\" [51,10,51] 60) where\n  \"a \\<succ>[R] b \\<equiv> b \\<prec>[R] a\"\n\ncontext preorder_on\nbegin\n\nlemma strict_trans: \"a \\<prec>[le] b \\<Longrightarrow> b \\<prec>[le] c \\<Longrightarrow> a \\<prec>[le] c\"\n  unfolding strongly_preferred_def by (blast intro: trans)\n\nlemma weak_strict_trans: \"a \\<preceq>[le] b \\<Longrightarrow> b \\<prec>[le] c \\<Longrightarrow> a \\<prec>[le] c\"\n  unfolding strongly_preferred_def by (blast intro: trans)\n\nlemma strict_weak_trans: \"a \\<prec>[le] b \\<Longrightarrow> b \\<preceq>[le] c \\<Longrightarrow> a \\<prec>[le] c\"\n  unfolding strongly_preferred_def by (blast intro: trans)\n\nend\n  \nlemma (in total_preorder_on) not_weakly_preferred_iff:\n  \"a \\<in> carrier \\<Longrightarrow> b \\<in> carrier \\<Longrightarrow> \\<not>a \\<preceq>[le] b \\<longleftrightarrow> b \\<prec>[le] a\"\n  using total[of a b] by (auto simp: strongly_preferred_def)\n\nlemma (in total_preorder_on) not_strongly_preferred_iff:\n  \"a \\<in> carrier \\<Longrightarrow> b \\<in> carrier \\<Longrightarrow> \\<not>a \\<prec>[le] b \\<longleftrightarrow> b \\<preceq>[le] a\"\n  using total[of a b] by (auto simp: strongly_preferred_def)\n\n\n\nsubsection \\<open>Orders\\<close>\n\nlocale order_on = preorder_on +\n  assumes antisymmetric: \"le x y \\<Longrightarrow> le y x \\<Longrightarrow> x = y\"\n\nlocale linorder_on = order_on carrier le + total_preorder_on carrier le for carrier le\n\n\nsubsection \\<open>Maximal elements\\<close>\n\ntext \\<open>\n  Maximal elements are elements in a preorder for which there exists no strictly greater element.\n\\<close>\n\ndefinition Max_wrt_among :: \"'a relation \\<Rightarrow> 'a set \\<Rightarrow> 'a set\" where\n  \"Max_wrt_among R A = {x\\<in>A. R x x \\<and> (\\<forall>y\\<in>A. R x y \\<longrightarrow> R y x)}\"\n\nlemma Max_wrt_among_cong:\n  assumes \"restrict_relation A R = restrict_relation A R'\"\n  shows   \"Max_wrt_among R A = Max_wrt_among R' A\"\nproof -\n  from assms have \"R x y \\<longleftrightarrow> R' x y\" if \"x \\<in> A\" \"y \\<in> A\" for x y\n    using that by (auto simp: restrict_relation_def fun_eq_iff)\n  thus ?thesis unfolding Max_wrt_among_def by blast\nqed\n\ndefinition Max_wrt :: \"'a relation \\<Rightarrow> 'a set\" where\n  \"Max_wrt R = Max_wrt_among R UNIV\"\n  \nlemma Max_wrt_altdef: \"Max_wrt R = {x. R x x \\<and> (\\<forall>y. R x y \\<longrightarrow> R y x)}\"\n  unfolding Max_wrt_def Max_wrt_among_def by simp\n\ncontext preorder_on\nbegin\n\nlemma Max_wrt_among_preorder:\n  \"Max_wrt_among le A = {x\\<in>carrier \\<inter> A. \\<forall>y\\<in>carrier \\<inter> A. le x y \\<longrightarrow> le y x}\"\n  unfolding Max_wrt_among_def using not_outside refl by blast\n\nlemma Max_wrt_preorder:\n  \"Max_wrt le = {x\\<in>carrier. \\<forall>y\\<in>carrier. le x y \\<longrightarrow> le y x}\"\n  unfolding Max_wrt_altdef using not_outside refl by blast\n\nlemma Max_wrt_among_subset:\n  \"Max_wrt_among le A \\<subseteq> carrier\" \"Max_wrt_among le A \\<subseteq> A\"\n  unfolding Max_wrt_among_preorder by auto\n  \nlemma Max_wrt_subset:\n  \"Max_wrt le \\<subseteq> carrier\"\n  unfolding Max_wrt_preorder by auto\n\nlemma Max_wrt_among_nonempty:\n  assumes \"B \\<inter> carrier \\<noteq> {}\" \"finite (B \\<inter> carrier)\"\n  shows   \"Max_wrt_among le B \\<noteq> {}\"\nproof -\n  define A where \"A = B \\<inter> carrier\"\n  have \"A \\<subseteq> carrier\" by (simp add: A_def)\n  from assms(2,1)[folded A_def] this have \"{x\\<in>A. (\\<forall>y\\<in>A. le x y \\<longrightarrow> le y x)} \\<noteq> {}\"\n  proof (induction A rule: finite_ne_induct)\n    case (singleton x)\n    thus ?case by (auto simp: refl)\n  next\n    case (insert x A)\n    then obtain y where y: \"y \\<in> A\" \"\\<And>z. z \\<in> A \\<Longrightarrow> le y z \\<Longrightarrow> le z y\" by blast\n    thus ?case using insert.prems\n      by (cases \"le y x\") (blast intro: trans)+\n  qed\n  thus ?thesis by (simp add: A_def Max_wrt_among_preorder Int_commute)\nqed\n  \nlemma Max_wrt_nonempty:\n  \"carrier \\<noteq> {} \\<Longrightarrow> finite carrier \\<Longrightarrow> Max_wrt le \\<noteq> {}\"\n  using Max_wrt_among_nonempty[of UNIV] by (simp add: Max_wrt_def)\n\nlemma Max_wrt_among_map_relation_vimage:\n  \"f -` Max_wrt_among le A \\<subseteq> Max_wrt_among (map_relation f le) (f -` A)\"\n  by (auto simp: Max_wrt_among_def map_relation_def)\n\n\n\nlemma image_subset_vimage_the_inv_into: \n  assumes \"inj_on f A\" \"B \\<subseteq> A\"\n  shows   \"f ` B \\<subseteq> the_inv_into A f -` B\"\n  using assms by (auto simp: the_inv_into_f_f)\n\nlemma Max_wrt_among_map_relation_bij_subset:\n  assumes \"bij (f :: 'a \\<Rightarrow> 'b)\"\n  shows   \"f ` Max_wrt_among le A \\<subseteq> \n             Max_wrt_among (map_relation (inv f) le) (f ` A)\"\n  using assms Max_wrt_among_map_relation_vimage[of \"inv f\" A]\n  by (simp add: bij_imp_bij_inv inv_inv_eq bij_vimage_eq_inv_image)\n  \nlemma Max_wrt_among_map_relation_bij:\n  assumes \"bij f\"\n  shows   \"f ` Max_wrt_among le A = Max_wrt_among (map_relation (inv f) le) (f ` A)\"\nproof (intro equalityI Max_wrt_among_map_relation_bij_subset assms)\n  interpret R: preorder_on \"f ` carrier\" \"map_relation (inv f) le\"\n    using preorder_on_map[of \"inv f\"] assms \n      by (simp add: bij_imp_bij_inv bij_vimage_eq_inv_image inv_inv_eq)\n  show \"Max_wrt_among (map_relation (inv f) le) (f ` A) \\<subseteq> f ` Max_wrt_among le A\"\n    unfolding Max_wrt_among_preorder R.Max_wrt_among_preorder \n    using assms bij_is_inj[OF assms]\n    by (auto simp: map_relation_def inv_f_f image_Int [symmetric])\nqed\n\nlemma Max_wrt_map_relation_bij:\n  \"bij f \\<Longrightarrow> f ` Max_wrt le = Max_wrt (map_relation (inv f) le)\"\nproof -\n  assume bij: \"bij f\"\n  interpret R: preorder_on \"f ` carrier\" \"map_relation (inv f) le\"\n    using preorder_on_map[of \"inv f\"] bij\n      by (simp add: bij_imp_bij_inv bij_vimage_eq_inv_image inv_inv_eq)\n  from bij show ?thesis\n    unfolding R.Max_wrt_preorder Max_wrt_preorder\n    by (auto simp: map_relation_def inv_f_f bij_is_inj)\nqed\n\nlemma Max_wrt_among_mono:\n  \"le x y \\<Longrightarrow> x \\<in> Max_wrt_among le A \\<Longrightarrow> y \\<in> A \\<Longrightarrow> y \\<in> Max_wrt_among le A\"\n  using not_outside by (auto simp: Max_wrt_among_preorder intro: trans)\n\nlemma Max_wrt_mono:\n  \"le x y \\<Longrightarrow> x \\<in> Max_wrt le \\<Longrightarrow> y \\<in> Max_wrt le\"\n  unfolding Max_wrt_def using Max_wrt_among_mono[of x y UNIV] by blast\n\nend\n\n\ncontext total_preorder_on\nbegin\n\nlemma Max_wrt_among_total_preorder:\n  \"Max_wrt_among le A = {x\\<in>carrier \\<inter> A. \\<forall>y\\<in>carrier \\<inter> A. le y x}\"\n  unfolding Max_wrt_among_preorder using total by blast\n\nlemma Max_wrt_total_preorder:\n  \"Max_wrt le = {x\\<in>carrier. \\<forall>y\\<in>carrier. le y x}\"\n  unfolding Max_wrt_preorder using total by blast\n\nlemma decompose_Max:\n  assumes A: \"A \\<subseteq> carrier\"\n  defines \"M \\<equiv> Max_wrt_among le A\"\n  shows   \"restrict_relation A le = (\\<lambda>x y. x \\<in> A \\<and> y \\<in> M \\<or> (y \\<notin> M \\<and> restrict_relation (A - M) le x y))\"\n  using A by (intro ext) (auto simp: M_def Max_wrt_among_total_preorder \n                            restrict_relation_def Int_absorb1 intro: trans)\n\nend\n\n\nsubsection \\<open>Weak rankings\\<close>\n\ninductive of_weak_ranking :: \"'alt set list \\<Rightarrow> 'alt relation\" where\n  \"i \\<le> j \\<Longrightarrow> i < length xs \\<Longrightarrow> j < length xs \\<Longrightarrow> x \\<in> xs ! i \\<Longrightarrow> y \\<in> xs ! j \\<Longrightarrow> \n     x \\<succeq>[of_weak_ranking xs] y\"\n\nlemma of_weak_ranking_Nil [simp]: \"of_weak_ranking [] = (\\<lambda>_ _. False)\"\n  by (intro ext) (simp add: of_weak_ranking.simps)\n\nlemma of_weak_ranking_Nil' [code]: \"of_weak_ranking [] x y = False\"\n  by simp\n  \nlemma of_weak_ranking_Cons [code]:\n  \"x \\<succeq>[of_weak_ranking (z#zs)] y \\<longleftrightarrow> x \\<in> z \\<and> y \\<in> \\<Union>(set (z#zs)) \\<or> x \\<succeq>[of_weak_ranking zs] y\" \n      (is \"?lhs \\<longleftrightarrow> ?rhs\")\nproof \n  assume ?lhs\n  then obtain i j \n    where ij: \"i < length (z#zs)\" \"j < length (z#zs)\" \"i \\<le> j\" \"x \\<in> (z#zs) ! i\" \"y \\<in> (z#zs) ! j\"\n    by (blast elim: of_weak_ranking.cases)\n  thus ?rhs by (cases i; cases j) (force intro: of_weak_ranking.intros)+\nnext\n  assume ?rhs\n  thus ?lhs\n  proof (elim disjE conjE)\n    assume \"x \\<in> z\" \"y \\<in> \\<Union>(set (z # zs))\"\n    then obtain j where \"j < length (z # zs)\" \"y \\<in> (z # zs) ! j\" \n      by (subst (asm) set_conv_nth) auto\n    with \\<open>x \\<in> z\\<close> show \"of_weak_ranking (z # zs) y x\" \n      by (intro of_weak_ranking.intros[of 0 j]) auto\n  next\n    assume \"of_weak_ranking zs y x\"\n    then obtain i j where \"i < length zs\" \"j < length zs\" \"i \\<le> j\" \"x \\<in> zs ! i\" \"y \\<in> zs ! j\"\n      by (blast elim: of_weak_ranking.cases)\n    thus \"of_weak_ranking (z # zs) y x\"\n      by (intro of_weak_ranking.intros[of \"Suc i\" \"Suc j\"]) auto\n  qed\nqed\n\nlemma of_weak_ranking_indifference:\n  assumes \"A \\<in> set xs\" \"x \\<in> A\" \"y \\<in> A\"\n  shows   \"x \\<preceq>[of_weak_ranking xs] y\"\n  using assms by (induction xs) (auto simp: of_weak_ranking_Cons)\n\n\nlemma of_weak_ranking_map:\n  \"map_relation f (of_weak_ranking xs) = of_weak_ranking (map ((-`) f) xs)\"\n  by (intro ext, induction xs)\n     (simp_all add: map_relation_def of_weak_ranking_Cons)\n\nlemma of_weak_ranking_permute':\n  assumes \"f permutes (\\<Union>(set xs))\"\n  shows   \"map_relation f (of_weak_ranking xs) = of_weak_ranking (map ((`) (inv f)) xs)\"\nproof -\n  have \"map_relation f (of_weak_ranking xs) = of_weak_ranking (map ((-`) f) xs)\"\n    by (rule of_weak_ranking_map)\n  also from assms have \"map ((-`) f) xs = map ((`) (inv f)) xs\"\n    by (intro map_cong refl) (simp_all add: bij_vimage_eq_inv_image permutes_bij)\n  finally show ?thesis .\nqed \n\nlemma of_weak_ranking_permute:\n  assumes \"f permutes (\\<Union>(set xs))\"\n  shows   \"of_weak_ranking (map ((`) f) xs) = map_relation (inv f) (of_weak_ranking xs)\"\n  using of_weak_ranking_permute'[OF permutes_inv[OF assms]] assms\n  by (simp add: inv_inv_eq permutes_bij)\n\ndefinition is_weak_ranking where\n  \"is_weak_ranking xs \\<longleftrightarrow> ({} \\<notin> set xs) \\<and>\n     (\\<forall>i j. i < length xs \\<and> j < length xs \\<and> i \\<noteq> j \\<longrightarrow> xs ! i \\<inter> xs ! j = {})\"\n\ndefinition is_finite_weak_ranking where\n  \"is_finite_weak_ranking xs \\<longleftrightarrow> is_weak_ranking xs \\<and> (\\<forall>x\\<in>set xs. finite x)\"\n\ndefinition weak_ranking :: \"'alt relation \\<Rightarrow> 'alt set list\" where\n  \"weak_ranking R = (SOME xs. is_weak_ranking xs \\<and> R = of_weak_ranking xs)\"\n\n\n\nlemma is_weak_ranking_nonempty: \"is_weak_ranking xs \\<Longrightarrow> {} \\<notin> set xs\"\n  by (simp add: is_weak_ranking_def) \n     \n\n\nlemma is_weak_ranking_rev [simp]: \"is_weak_ranking (rev xs) \\<longleftrightarrow> is_weak_ranking xs\"\n  by (simp add: is_weak_ranking_iff)\n\nlemma is_weak_ranking_map_inj:\n  assumes \"is_weak_ranking xs\" \"inj_on f (\\<Union>(set xs))\"\n  shows   \"is_weak_ranking (map ((`) f) xs)\"\n  using assms by (auto simp: is_weak_ranking_iff distinct_map inj_on_image disjoint_image)\n\nlemma of_weak_ranking_rev [simp]:\n  \"of_weak_ranking (rev xs) (x::'a) y \\<longleftrightarrow> of_weak_ranking xs y x\"\nproof -\n  have \"of_weak_ranking (rev xs) y x\" if \"of_weak_ranking xs x y\" for xs and x y :: 'a\n  proof -\n    from that obtain i j where \"i < length xs\" \"j < length xs\" \"x \\<in> xs ! i\" \"y \\<in> xs ! j\" \"i \\<ge> j\"\n      by (elim of_weak_ranking.cases) simp_all\n    thus ?thesis\n      by (intro of_weak_ranking.intros[of \"length xs - i - 1\" \"length xs - j - 1\"] diff_le_mono2)\n         (auto simp: diff_le_mono2 rev_nth)\n  qed\n  from this[of xs y x] this[of \"rev xs\" x y] show ?thesis by (intro iffI) simp_all\nqed\n\n\nlemma is_weak_ranking_Nil [simp, code]: \"is_weak_ranking []\"\n  by (auto simp: is_weak_ranking_def)\n\nlemma is_finite_weak_ranking_Nil [simp, code]: \"is_finite_weak_ranking []\"\n  by (auto simp: is_finite_weak_ranking_def)\n\nlemma is_weak_ranking_Cons_empty [simp]:\n  \"\\<not>is_weak_ranking ({} # xs)\" by (simp add: is_weak_ranking_def)\n\nlemma is_finite_weak_ranking_Cons_empty [simp]:\n  \"\\<not>is_finite_weak_ranking ({} # xs)\" by (simp add: is_finite_weak_ranking_def)\n  \nlemma is_weak_ranking_singleton [simp]:\n  \"is_weak_ranking [x] \\<longleftrightarrow> x \\<noteq> {}\" \n  by (auto simp add: is_weak_ranking_def)\n\nlemma is_finite_weak_ranking_singleton [simp]:\n  \"is_finite_weak_ranking [x] \\<longleftrightarrow> x \\<noteq> {} \\<and> finite x\" \n  by (auto simp add: is_finite_weak_ranking_def)\n  \nlemma is_weak_ranking_append:\n  \"is_weak_ranking (xs @ ys) \\<longleftrightarrow> \n      is_weak_ranking xs \\<and> is_weak_ranking ys \\<and>\n      (set xs \\<inter> set ys = {} \\<and> \\<Union>(set xs) \\<inter> \\<Union>(set ys) = {})\"\n  by (simp only: is_weak_ranking_iff)\n     (auto dest: disjointD disjoint_unionD1 disjoint_unionD2 intro: disjoint_union)\n\nlemma is_weak_ranking_Cons [code]:\n  \"is_weak_ranking (x # xs) \\<longleftrightarrow> \n      x \\<noteq> {} \\<and> is_weak_ranking xs \\<and> x \\<inter> \\<Union>(set xs) = {}\"\n  using is_weak_ranking_append[of \"[x]\" xs] by auto\n\nlemma is_finite_weak_ranking_Cons [code]:\n  \"is_finite_weak_ranking (x # xs) \\<longleftrightarrow> \n      x \\<noteq> {} \\<and> finite x \\<and> is_finite_weak_ranking xs \\<and> x \\<inter> \\<Union>(set xs) = {}\"\n  by (auto simp add: is_finite_weak_ranking_def is_weak_ranking_Cons)\n\nprimrec is_weak_ranking_aux where\n  \"is_weak_ranking_aux A [] \\<longleftrightarrow> True\"\n| \"is_weak_ranking_aux A (x#xs) \\<longleftrightarrow> x \\<noteq> {} \\<and>\n       A \\<inter> x = {} \\<and> is_weak_ranking_aux (A \\<union> x) xs\"\n\n\nlemma is_weak_ranking_aux:\n  \"is_weak_ranking_aux A xs \\<longleftrightarrow> A \\<inter> \\<Union>(set xs) = {} \\<and> is_weak_ranking xs\"\n  by (induction xs arbitrary: A) (auto simp: is_weak_ranking_Cons)\n\nlemma is_weak_ranking_code [code]:\n  \"is_weak_ranking xs \\<longleftrightarrow> is_weak_ranking_aux {} xs\"\n  by (subst is_weak_ranking_aux) auto\n\nlemma of_weak_ranking_altdef:\n  assumes \"is_weak_ranking xs\" \"x \\<in> \\<Union>(set xs)\" \"y \\<in> \\<Union>(set xs)\"\n  shows   \"of_weak_ranking xs x y \\<longleftrightarrow> \n             find_index ((\\<in>) x) xs \\<ge> find_index ((\\<in>) y) xs\"\nproof -\n from assms \n    have A: \"find_index ((\\<in>) x) xs < length xs\" \"find_index ((\\<in>) y) xs < length xs\"\n    by (simp_all add: find_index_less_size_conv)\n from this[THEN nth_find_index] \n    have B: \"x \\<in> xs ! find_index ((\\<in>) x) xs\" \"y \\<in> xs ! find_index ((\\<in>) y) xs\" .\n  show ?thesis\n  proof\n    assume \"of_weak_ranking xs x y\"\n    then obtain i j where ij: \"j \\<le> i\" \"i < length xs\" \"j < length xs\" \"x \\<in> xs ! i\" \"y \\<in> xs !j\"\n      by (cases rule: of_weak_ranking.cases) simp_all\n    with A B have \"i = find_index ((\\<in>) x) xs\" \"j = find_index ((\\<in>) y) xs\"\n      using assms(1) unfolding is_weak_ranking_def by blast+\n    with ij show \"find_index ((\\<in>) x) xs \\<ge> find_index ((\\<in>) y) xs\" by simp\n  next\n    assume \"find_index ((\\<in>) x) xs \\<ge> find_index ((\\<in>) y) xs\"\n    from this A(2,1) B(2,1) show \"of_weak_ranking xs x y\"\n      by (rule of_weak_ranking.intros)\n  qed\nqed\n\n  \n\n\nlemma restrict_relation_of_weak_ranking_Cons:\n  assumes \"is_weak_ranking (A # As)\"\n  shows   \"restrict_relation (\\<Union>(set As)) (of_weak_ranking (A # As)) = of_weak_ranking As\"\nproof -\n  from assms interpret R: total_preorder_on \"\\<Union>(set As)\" \"of_weak_ranking As\"\n    by (intro total_preorder_of_weak_ranking)\n       (simp_all add: is_weak_ranking_Cons)\n  from assms show ?thesis using R.not_outside\n    by (intro ext) (auto simp: restrict_relation_def of_weak_ranking_Cons\n                     is_weak_ranking_Cons)\nqed\n\n\n\n\nlemmas of_weak_ranking_wf = \n  total_preorder_of_weak_ranking is_weak_ranking_code insert_commute\n\n\n(* Test *)\nlemma \"total_preorder_on {1,2,3,4::nat} (of_weak_ranking [{1,3},{2},{4}])\"\n  by (simp add: of_weak_ranking_wf)\n\n\ncontext\n  fixes x :: \"'alt set\" and xs :: \"'alt set list\"\n  assumes wf: \"is_weak_ranking (x#xs)\"\nbegin\n\ninterpretation R: total_preorder_on \"\\<Union>(set (x#xs))\" \"of_weak_ranking (x#xs)\"\n  by (intro total_preorder_of_weak_ranking) (simp_all add: wf)\n\nlemma of_weak_ranking_imp_in_set:\n  assumes \"of_weak_ranking xs a b\"\n  shows   \"a \\<in> \\<Union>(set xs)\" \"b \\<in> \\<Union>(set xs)\"\n  using assms by (fastforce elim!: of_weak_ranking.cases)+\n\nlemma of_weak_ranking_Cons':\n  assumes \"a \\<in> \\<Union>(set (x#xs))\" \"b \\<in> \\<Union>(set (x#xs))\"\n  shows   \"of_weak_ranking (x#xs) a b \\<longleftrightarrow> b \\<in> x \\<or> (a \\<notin> x \\<and> of_weak_ranking xs a b)\"\nproof\n  assume \"of_weak_ranking (x # xs) a b\"\n  with wf of_weak_ranking_imp_in_set[of a b] \n    show \"(b \\<in> x \\<or>  a \\<notin> x \\<and> of_weak_ranking xs a b)\"\n    by (auto simp: is_weak_ranking_Cons of_weak_ranking_Cons)\nnext\n  assume \"b \\<in> x \\<or> a \\<notin> x \\<and> of_weak_ranking xs a b\"\n  with assms show \"of_weak_ranking (x#xs) a b\"\n    by (fastforce simp: of_weak_ranking_Cons)\nqed\n\nlemma Max_wrt_among_of_weak_ranking_Cons1:\n  assumes \"x \\<inter> A = {}\"\n  shows   \"Max_wrt_among (of_weak_ranking (x#xs)) A = Max_wrt_among (of_weak_ranking xs) A\"\nproof -\n  from wf interpret R': total_preorder_on \"\\<Union>(set xs)\" \"of_weak_ranking xs\"\n    by (intro total_preorder_of_weak_ranking) (simp_all add: is_weak_ranking_Cons)\n  from assms show ?thesis\n    by (auto simp: R.Max_wrt_among_total_preorder\n          R'.Max_wrt_among_total_preorder of_weak_ranking_Cons)\nqed\n\nlemma Max_wrt_among_of_weak_ranking_Cons2:\n  assumes \"x \\<inter> A \\<noteq> {}\"\n  shows   \"Max_wrt_among (of_weak_ranking (x#xs)) A = x \\<inter> A\"\nproof -\n  from wf interpret R': total_preorder_on \"\\<Union>(set xs)\" \"of_weak_ranking xs\"\n    by (intro total_preorder_of_weak_ranking) (simp_all add: is_weak_ranking_Cons)\n  from assms obtain a where \"a \\<in> x \\<inter> A\" by blast\n  with wf R'.not_outside(1)[of a] show ?thesis\n    by (auto simp: R.Max_wrt_among_total_preorder is_weak_ranking_Cons\n          R'.Max_wrt_among_total_preorder of_weak_ranking_Cons)\nqed\n\nlemma Max_wrt_among_of_weak_ranking_Cons:\n  \"Max_wrt_among (of_weak_ranking (x#xs)) A =\n     (if x \\<inter> A = {} then Max_wrt_among (of_weak_ranking xs) A else x \\<inter> A)\"\n  using Max_wrt_among_of_weak_ranking_Cons1 Max_wrt_among_of_weak_ranking_Cons2 by simp\n\nlemma Max_wrt_of_weak_ranking_Cons:\n  \"Max_wrt (of_weak_ranking (x#xs)) = x\"\n  using wf by (simp add: is_weak_ranking_Cons Max_wrt_def Max_wrt_among_of_weak_ranking_Cons)\n\nend\n\nlemma Max_wrt_of_weak_ranking:\n  assumes \"is_weak_ranking xs\"\n  shows   \"Max_wrt (of_weak_ranking xs) = (if xs = [] then {} else hd xs)\"\nproof (cases xs)\n  case Nil\n  hence \"of_weak_ranking xs = (\\<lambda>_ _. False)\" by (intro ext) simp_all\n  with Nil show ?thesis by (simp add: Max_wrt_def Max_wrt_among_def)\nnext\n  case (Cons x xs')\n  with assms show ?thesis by (simp add: Max_wrt_of_weak_ranking_Cons)\nqed\n\n\nlocale finite_total_preorder_on = total_preorder_on +\n  assumes finite_carrier [intro]: \"finite carrier\"\nbegin\n\nlemma finite_total_preorder_on_map:\n  assumes \"finite (f -` carrier)\"\n  shows   \"finite_total_preorder_on (f -` carrier) (map_relation f le)\"\nproof -\n  interpret R': total_preorder_on \"f -` carrier\" \"map_relation f le\"\n    using total_preorder_on_map[of f] .\n  from assms show ?thesis by unfold_locales simp\nqed\n\nfunction weak_ranking_aux :: \"'a set \\<Rightarrow> 'a set list\" where\n  \"weak_ranking_aux {} = []\"\n| \"A \\<noteq> {} \\<Longrightarrow> A \\<subseteq> carrier \\<Longrightarrow> weak_ranking_aux A =\n     Max_wrt_among le A # weak_ranking_aux (A - Max_wrt_among le A)\"\n| \"\\<not>(A \\<subseteq> carrier) \\<Longrightarrow> weak_ranking_aux A = undefined\"\nby blast simp_all\ntermination proof (relation \"Wellfounded.measure card\")\n  fix A\n  let ?B = \"Max_wrt_among le A\"\n  assume A: \"A \\<noteq> {}\" \"A \\<subseteq> carrier\"\n  moreover from A(2) have \"finite A\" by (rule finite_subset) blast\n  moreover from A have \"?B \\<noteq> {}\" \"?B \\<subseteq> A\"\n    by (intro Max_wrt_among_nonempty Max_wrt_among_subset; force)+\n  ultimately have \"card (A - ?B) < card A\"\n    by (intro psubset_card_mono) auto\n  thus \"(A - ?B, A) \\<in> measure card\" by simp\nqed simp_all\n\nlemma weak_ranking_aux_Union:\n  \"A \\<subseteq> carrier \\<Longrightarrow> \\<Union>(set (weak_ranking_aux A)) = A\"\nproof (induction A rule: weak_ranking_aux.induct [case_names empty nonempty])\n  case (nonempty A)\n  with Max_wrt_among_subset[of A] show ?case by auto\nqed simp_all\n\nlemma weak_ranking_aux_wf:\n  \"A \\<subseteq> carrier \\<Longrightarrow> is_weak_ranking (weak_ranking_aux A)\"\nproof (induction A rule: weak_ranking_aux.induct [case_names empty nonempty])\n  case (nonempty A)\n  have \"is_weak_ranking (Max_wrt_among le A # weak_ranking_aux (A - Max_wrt_among le A))\"\n    unfolding is_weak_ranking_Cons\n  proof (intro conjI)\n    from nonempty.prems nonempty.hyps show \"Max_wrt_among le A \\<noteq> {}\"\n      by (intro Max_wrt_among_nonempty) auto\n  next\n    from nonempty.prems show \"is_weak_ranking (weak_ranking_aux (A - Max_wrt_among le A))\"\n      by (intro nonempty.IH) blast\n  next\n    from nonempty.prems nonempty.hyps have \"Max_wrt_among le A \\<noteq> {}\"\n      by (intro Max_wrt_among_nonempty) auto\n    moreover from nonempty.prems \n      have \"\\<Union>(set (weak_ranking_aux (A - Max_wrt_among le A))) = A - Max_wrt_among le A\"\n      by (intro weak_ranking_aux_Union) auto\n    ultimately show \"Max_wrt_among le A \\<inter> \\<Union>(set (weak_ranking_aux (A - Max_wrt_among le A))) = {}\"\n      by blast+\n  qed\n  with nonempty.prems nonempty.hyps show ?case by simp\nqed simp_all    \n\nlemma of_weak_ranking_weak_ranking_aux':\n  assumes \"A \\<subseteq> carrier\" \"x \\<in> A\" \"y \\<in> A\"\n  shows   \"of_weak_ranking (weak_ranking_aux A) x y \\<longleftrightarrow> restrict_relation A le x y\"\nusing assms\nproof (induction A rule: weak_ranking_aux.induct [case_names empty nonempty])\n  case (nonempty A)\n  define M where \"M = Max_wrt_among le A\"\n  from nonempty.prems nonempty.hyps have M: \"M \\<subseteq> A\" unfolding M_def\n    by (intro Max_wrt_among_subset)\n  from nonempty.prems have in_MD: \"le x y\" if \"x \\<in> A\" \"y \\<in> M\" for x y\n    using that unfolding M_def Max_wrt_among_total_preorder\n    by (auto simp: Int_absorb1)\n  from nonempty.prems have in_MI: \"x \\<in> M\" if \"y \\<in> M\" \"x \\<in> A\"  \"le y x\" for x y\n    using that unfolding M_def Max_wrt_among_total_preorder\n    by (auto simp: Int_absorb1 intro: trans)\n\n  from nonempty.prems nonempty.hyps\n    have IH: \"of_weak_ranking (weak_ranking_aux (A - M)) x y = \n                restrict_relation (A - M) le x y\" if \"x \\<notin> M\" \"y \\<notin> M\"\n       using that unfolding M_def by (intro nonempty.IH) auto\n  from nonempty.prems \n    interpret R': total_preorder_on \"A - M\" \"of_weak_ranking (weak_ranking_aux (A - M))\"\n    by (intro total_preorder_of_weak_ranking weak_ranking_aux_wf weak_ranking_aux_Union) auto\n  \n  from nonempty.prems nonempty.hyps M weak_ranking_aux_Union[of A] R'.not_outside[of x y] \n    show ?case\n    by (cases \"x \\<in> M\"; cases \"y \\<in> M\")\n       (auto simp: restrict_relation_def of_weak_ranking_Cons IH M_def [symmetric]\n             intro: in_MD dest: in_MI)\nqed simp_all\n\nlemma of_weak_ranking_weak_ranking_aux:\n  \"of_weak_ranking (weak_ranking_aux carrier) = le\"\nproof (intro ext)\n  fix x y\n  have \"is_weak_ranking (weak_ranking_aux carrier)\" by (rule weak_ranking_aux_wf) simp\n  then interpret R: total_preorder_on carrier \"of_weak_ranking (weak_ranking_aux carrier)\"\n    by (intro total_preorder_of_weak_ranking weak_ranking_aux_wf weak_ranking_aux_Union)\n       (simp_all add: weak_ranking_aux_Union)\n\n  show \"of_weak_ranking (weak_ranking_aux carrier) x y = le x y\"\n  proof (cases \"x \\<in> carrier \\<and> y \\<in> carrier\")\n    case True\n    thus ?thesis\n      using of_weak_ranking_weak_ranking_aux'[of carrier x y]  by simp\n  next\n    case False\n    with R.not_outside have \"of_weak_ranking (weak_ranking_aux carrier) x y = False\"\n      by auto\n    also from not_outside False have \"\\<dots> = le x y\" by auto\n    finally show ?thesis .\n  qed\nqed\n\nlemma weak_ranking_aux_unique':\n  assumes \"\\<Union>(set As) \\<subseteq> carrier\" \"is_weak_ranking As\"\n          \"of_weak_ranking As = restrict_relation (\\<Union>(set As)) le\"\n  shows   \"As = weak_ranking_aux (\\<Union>(set As))\"\nusing assms\nproof (induction As)\n  case (Cons A As)\n  have \"restrict_relation (\\<Union>(set As)) (of_weak_ranking (A # As)) = of_weak_ranking As\"\n    by (intro restrict_relation_of_weak_ranking_Cons Cons.prems)\n  also have eq1: \"of_weak_ranking (A # As) = restrict_relation (\\<Union>(set (A # As))) le\" by fact\n  finally have eq: \"of_weak_ranking As = restrict_relation (\\<Union>(set As)) le\"\n    by (simp add: Int_absorb2)\n  with Cons.prems have eq2: \"weak_ranking_aux (\\<Union>(set As)) = As\"\n    by (intro sym [OF Cons.IH]) (auto simp: is_weak_ranking_Cons)\n\n  from eq1 have \n    \"Max_wrt_among le (\\<Union>(set (A # As))) = \n       Max_wrt_among (of_weak_ranking (A#As)) (\\<Union>(set (A#As)))\"\n    by (intro Max_wrt_among_cong) simp_all\n  also from Cons.prems have \"\\<dots> = A\"\n    by (subst Max_wrt_among_of_weak_ranking_Cons2)\n       (simp_all add: is_weak_ranking_Cons)\n  finally have Max: \"Max_wrt_among le (\\<Union>(set (A # As))) = A\" .\n\n  moreover from Cons.prems have \"A \\<noteq> {}\" by (simp add: is_weak_ranking_Cons)\n  ultimately have \"weak_ranking_aux (\\<Union>(set (A # As))) = A # weak_ranking_aux (A \\<union> \\<Union>(set As) - A)\" \n    using Cons.prems by simp\n  also from Cons.prems have \"A \\<union> \\<Union>(set As) - A = \\<Union>(set As)\"\n    by (auto simp: is_weak_ranking_Cons)\n  also from eq2 have \"weak_ranking_aux \\<dots> = As\" .\n  finally show ?case ..\nqed simp_all\n\nlemma weak_ranking_aux_unique:\n  assumes \"is_weak_ranking As\" \"of_weak_ranking As = le\"\n  shows   \"As = weak_ranking_aux carrier\"\nproof -\n  interpret R: total_preorder_on \"\\<Union>(set As)\" \"of_weak_ranking As\"\n    by (intro total_preorder_of_weak_ranking assms) simp_all\n  from assms have \"x \\<in> \\<Union>(set As) \\<longleftrightarrow> x \\<in> carrier\" for x\n    using R.not_outside not_outside R.refl[of x] refl[of x]\n    by blast\n  hence eq: \"\\<Union>(set As) = carrier\" by blast\n  from assms eq have \"As = weak_ranking_aux (\\<Union>(set As))\"\n    by (intro weak_ranking_aux_unique') simp_all\n  with eq show ?thesis by simp\nqed\n\nlemma weak_ranking_total_preorder:\n  \"is_weak_ranking (weak_ranking le)\" \"of_weak_ranking (weak_ranking le) = le\"\nproof -\n  from weak_ranking_aux_wf[of carrier] of_weak_ranking_weak_ranking_aux\n    have \"\\<exists>x. is_weak_ranking x \\<and> le = of_weak_ranking x\" by auto\n  hence \"is_weak_ranking (weak_ranking le) \\<and> le = of_weak_ranking (weak_ranking le)\"\n    unfolding weak_ranking_def by (rule someI_ex)\n  thus \"is_weak_ranking (weak_ranking le)\" \"of_weak_ranking (weak_ranking le) = le\"\n    by simp_all\nqed\n\nlemma weak_ranking_altdef:\n  \"weak_ranking le = weak_ranking_aux carrier\"\n  by (intro weak_ranking_aux_unique weak_ranking_total_preorder)\n\nlemma weak_ranking_Union: \"\\<Union>(set (weak_ranking le)) = carrier\"\n  by (simp add: weak_ranking_altdef weak_ranking_aux_Union)\n\nlemma weak_ranking_unique:\n  assumes \"is_weak_ranking As\" \"of_weak_ranking As = le\"\n  shows   \"As = weak_ranking le\"\n  using assms unfolding weak_ranking_altdef by (rule weak_ranking_aux_unique)\n\nlemma weak_ranking_permute:\n  assumes \"f permutes carrier\"\n  shows   \"weak_ranking (map_relation (inv f) le) = map ((`) f) (weak_ranking le)\"\nproof -\n  from assms have \"inv f -` carrier = carrier\"\n    by (simp add: permutes_vimage permutes_inv)\n  then interpret R: finite_total_preorder_on \"inv f -` carrier\" \"map_relation (inv f) le\"\n    by (intro finite_total_preorder_on_map) (simp_all add: finite_carrier)\n  from assms have \"is_weak_ranking (map ((`) f) (weak_ranking le))\"\n    by (intro is_weak_ranking_map_inj) \n       (simp_all add: weak_ranking_total_preorder permutes_inj_on)\n  with assms show ?thesis\n    by (intro sym[OF R.weak_ranking_unique])\n       (simp_all add: of_weak_ranking_permute weak_ranking_Union weak_ranking_total_preorder)\nqed\n\nlemma weak_ranking_index_unique:\n  assumes \"is_weak_ranking xs\" \"i < length xs\" \"j < length xs\" \"x \\<in> xs ! i\" \"x \\<in> xs ! j\"\n  shows   \"i = j\"\n  using assms unfolding is_weak_ranking_def by auto\n\nlemma weak_ranking_index_unique':\n  assumes \"is_weak_ranking xs\" \"i < length xs\" \"x \\<in> xs ! i\"\n  shows   \"i = find_index ((\\<in>) x) xs\"\n  using assms find_index_less_size_conv nth_mem\n  by (intro weak_ranking_index_unique[OF assms(1,2) _ assms(3)]\n        nth_find_index[of \"(\\<in>) x\"]) blast+\n\nlemma weak_ranking_eqclass1:\n  assumes \"A \\<in> set (weak_ranking le)\" \"x \\<in> A\" \"y \\<in> A\"\n  shows   \"le x y\"\nproof -\n  from assms obtain i where \"weak_ranking le ! i = A\" \"i < length (weak_ranking le)\" \n    by (auto simp: set_conv_nth)\n  with assms have \"of_weak_ranking (weak_ranking le) x y\"\n    by (intro of_weak_ranking.intros[of i i]) auto\n  thus ?thesis by (simp add: weak_ranking_total_preorder)\nqed\n\nlemma weak_ranking_eqclass2:\n  assumes A: \"A \\<in> set (weak_ranking le)\" \"x \\<in> A\" and le: \"le x y\" \"le y x\"\n  shows   \"y \\<in> A\"\nproof -\n  define xs where \"xs = weak_ranking le\"\n  have wf: \"is_weak_ranking xs\" by (simp add: xs_def weak_ranking_total_preorder)\n  let ?le' = \"of_weak_ranking xs\"\n  from le have le': \"?le' x y\" \"?le' y x\" by (simp_all add: weak_ranking_total_preorder xs_def)\n  from le'(1) obtain i j\n    where ij: \"j \\<le> i\" \"i < length xs\" \"j < length xs\" \"x \\<in> xs ! i\" \"y \\<in> xs ! j\"\n    by (cases rule: of_weak_ranking.cases)\n  from le'(2) obtain i' j'\n    where i'j': \"j' \\<le> i'\" \"i' < length xs\" \"j' < length xs\" \"x \\<in> xs ! j'\" \"y \\<in> xs ! i'\"\n    by (cases rule: of_weak_ranking.cases)\n  from ij i'j' have eq: \"i = j'\" \"j = i'\"\n    by (intro weak_ranking_index_unique[OF wf]; simp)+\n  moreover from A obtain k where k: \"k < length xs\" \"A = xs ! k\" \n    by (auto simp: xs_def set_conv_nth)\n  ultimately have \"k = i\" using ij i'j' A\n    by (intro weak_ranking_index_unique[OF wf, of _ _ x]) auto\n  with ij i'j' k eq show ?thesis by (auto simp: xs_def)\nqed\n\nlemma hd_weak_ranking:\n  assumes \"x \\<in> hd (weak_ranking le)\" \"y \\<in> carrier\"\n  shows   \"le y x\"\nproof -\n  from weak_ranking_Union assms obtain i\n    where \"i < length (weak_ranking le)\" \"y \\<in> weak_ranking le ! i\"\n    by (auto simp: set_conv_nth)\n  moreover from assms(2) weak_ranking_Union have \"weak_ranking le \\<noteq> []\" by auto\n  ultimately have \"of_weak_ranking (weak_ranking le) y x\" using assms(1)\n    by (intro of_weak_ranking.intros[of 0 i]) (auto simp: hd_conv_nth)\n  thus ?thesis by (simp add: weak_ranking_total_preorder)\nqed\n\nlemma last_weak_ranking:\n  assumes \"x \\<in> last (weak_ranking le)\" \"y \\<in> carrier\"\n  shows   \"le x y\"\nproof -\n  from weak_ranking_Union assms obtain i\n    where \"i < length (weak_ranking le)\" \"y \\<in> weak_ranking le ! i\"\n    by (auto simp: set_conv_nth)\n  moreover from assms(2) weak_ranking_Union have \"weak_ranking le \\<noteq> []\" by auto\n  ultimately have \"of_weak_ranking (weak_ranking le) x y\" using assms(1)\n    by (intro of_weak_ranking.intros[of i \"length (weak_ranking le) - 1\"])\n       (auto simp: last_conv_nth)\n  thus ?thesis by (simp add: weak_ranking_total_preorder)\nqed\n\ntext \\<open>\n  The index in weak ranking of a given alternative. An element with index 0 is \n  first-ranked; larger indices correspond to less-preferred alternatives.\n\\<close>\ndefinition weak_ranking_index :: \"'a \\<Rightarrow> nat\" where\n  \"weak_ranking_index x = find_index (\\<lambda>A. x \\<in> A) (weak_ranking le)\"\n\nlemma nth_weak_ranking_index:\n  assumes \"x \\<in> carrier\"\n  shows   \"weak_ranking_index x < length (weak_ranking le)\" \n          \"x \\<in> weak_ranking le ! weak_ranking_index x\"\nproof -\n  from assms weak_ranking_Union show \"weak_ranking_index x < length (weak_ranking le)\"\n     unfolding weak_ranking_index_def by (auto simp add: find_index_less_size_conv)\n  thus \"x \\<in> weak_ranking le ! weak_ranking_index x\" unfolding weak_ranking_index_def\n    by (rule nth_find_index)\nqed\n\nlemma ranking_index_eqI:\n  \"i < length (weak_ranking le) \\<Longrightarrow> x \\<in> weak_ranking le ! i \\<Longrightarrow> weak_ranking_index x = i\"\n  using weak_ranking_index_unique'[of \"weak_ranking le\" i x]\n  by (simp add: weak_ranking_index_def weak_ranking_total_preorder)\n\nlemma ranking_index_le_iff [simp]:\n  assumes \"x \\<in> carrier\" \"y \\<in> carrier\"\n  shows   \"weak_ranking_index x \\<ge> weak_ranking_index y \\<longleftrightarrow> le x y\"\nproof -\n  have \"le x y \\<longleftrightarrow> of_weak_ranking (weak_ranking le) x y\"\n    by (simp add: weak_ranking_total_preorder)\n  also have \"\\<dots> \\<longleftrightarrow> weak_ranking_index x \\<ge> weak_ranking_index y\"\n  proof\n    assume \"weak_ranking_index x \\<ge> weak_ranking_index y\"\n    thus \"of_weak_ranking (weak_ranking le) x y\"\n      by (rule of_weak_ranking.intros) (simp_all add: nth_weak_ranking_index assms)\n  next\n    assume \"of_weak_ranking (weak_ranking le) x y\"\n    then obtain i j where \n      \"i \\<le> j\" \"i < length (weak_ranking le)\" \"j < length (weak_ranking le)\"\n      \"x \\<in> weak_ranking le ! j\" \"y \\<in> weak_ranking le ! i\"\n      by (elim of_weak_ranking.cases) blast\n    with ranking_index_eqI[of i] ranking_index_eqI[of j]\n      show \"weak_ranking_index x \\<ge> weak_ranking_index y\" by simp\n  qed\n  finally show ?thesis ..\nqed\n\nend\n\nlemma weak_ranking_False [simp]: \"weak_ranking (\\<lambda>_ _. False) = []\"\nproof -\n  interpret finite_total_preorder_on \"{}\" \"\\<lambda>_ _. False\"\n    by unfold_locales simp_all\n  have \"[] = weak_ranking (\\<lambda>_ _. False)\" by (rule weak_ranking_unique) simp_all\n  thus ?thesis ..\nqed\n\nlemmas of_weak_ranking_weak_ranking = \n  finite_total_preorder_on.weak_ranking_total_preorder(2)\n\nlemma finite_total_preorder_on_iff:\n  \"finite_total_preorder_on A R \\<longleftrightarrow> total_preorder_on A R \\<and> finite A\"\n  by (simp add: finite_total_preorder_on_def finite_total_preorder_on_axioms_def)\n\nlemma finite_total_preorder_of_weak_ranking:\n  assumes \"\\<Union>(set xs) = A\" \"is_finite_weak_ranking xs\"\n  shows   \"finite_total_preorder_on A (of_weak_ranking xs)\"\nproof -\n  from assms(2) have \"is_weak_ranking xs\" by (simp add: is_finite_weak_ranking_def)\n  from assms(1) and this interpret total_preorder_on A \"of_weak_ranking xs\"\n    by (rule total_preorder_of_weak_ranking)\n  from assms(2) show ?thesis\n    by unfold_locales (simp add: assms(1)[symmetric] is_finite_weak_ranking_def)\nqed  \n\nlemma weak_ranking_of_weak_ranking:\n  assumes \"is_finite_weak_ranking xs\"\n  shows   \"weak_ranking (of_weak_ranking xs) = xs\"\nproof -\n  from assms interpret finite_total_preorder_on \"\\<Union>(set xs)\" \"of_weak_ranking xs\"\n    by (intro finite_total_preorder_of_weak_ranking) simp_all\n  from assms show ?thesis\n    by (intro sym[OF weak_ranking_unique]) (simp_all add: is_finite_weak_ranking_def)\nqed\n\n\nlemma weak_ranking_eqD:\n  assumes \"finite_total_preorder_on alts R1\"\n  assumes \"finite_total_preorder_on alts R2\"\n  assumes \"weak_ranking R1 = weak_ranking R2\"\n  shows   \"R1 = R2\"\nproof -\n  from assms have \"of_weak_ranking (weak_ranking R1) = of_weak_ranking (weak_ranking R2)\" by simp\n  with assms(1,2) show ?thesis by (simp add: of_weak_ranking_weak_ranking)\nqed\n\nlemma weak_ranking_eq_iff:\n  assumes \"finite_total_preorder_on alts R1\"\n  assumes \"finite_total_preorder_on alts R2\"\n  shows   \"weak_ranking R1 = weak_ranking R2 \\<longleftrightarrow> R1 = R2\"\n  using assms weak_ranking_eqD by auto\n\n\ndefinition preferred_alts :: \"'alt relation \\<Rightarrow> 'alt \\<Rightarrow> 'alt set\" where\n  \"preferred_alts R x = {y. y \\<succeq>[R] x}\"\n\nlemma (in preorder_on) preferred_alts_refl [simp]: \"x \\<in> carrier \\<Longrightarrow> x \\<in> preferred_alts le x\"\n  by (simp add: preferred_alts_def refl)  \n\nlemma (in preorder_on) preferred_alts_altdef:\n  \"preferred_alts le x = {y\\<in>carrier. y \\<succeq>[le] x}\"\n  by (auto simp: preferred_alts_def intro: not_outside)\n  \nlemma (in preorder_on) preferred_alts_subset: \"preferred_alts le x \\<subseteq> carrier\"\n  unfolding preferred_alts_def using not_outside by blast\n\n\nsubsection \\<open>Rankings\\<close>\n\n(* TODO: Extend theory on rankings. Can probably mostly be based on\n   existing theory on weak rankings. *)\n\ndefinition ranking :: \"'a relation \\<Rightarrow> 'a list\" where\n  \"ranking R = map the_elem (weak_ranking R)\"\n\nlocale finite_linorder_on = linorder_on +\n  assumes finite_carrier [intro]: \"finite carrier\"\nbegin\n\nsublocale finite_total_preorder_on carrier le\n  by unfold_locales (fact finite_carrier)\n\nlemma singleton_weak_ranking:\n  assumes \"A \\<in> set (weak_ranking le)\"\n  shows   \"is_singleton A\"\nproof (rule is_singletonI')\n  from assms show \"A \\<noteq> {}\"\n    using weak_ranking_total_preorder(1) is_weak_ranking_iff by auto\nnext\n  fix x y assume \"x \\<in> A\" \"y \\<in> A\"\n  with assms \n    have \"x \\<preceq>[of_weak_ranking (weak_ranking le)] y\" \"y \\<preceq>[of_weak_ranking (weak_ranking le)] x\"\n    by (auto intro!: of_weak_ranking_indifference)\n  with weak_ranking_total_preorder(2) \n    show \"x = y\" by (intro antisymmetric) simp_all\nqed\n\nlemma weak_ranking_ranking: \"weak_ranking le = map (\\<lambda>x. {x}) (ranking le)\"\n  unfolding ranking_def map_map o_def\nproof (rule sym, rule map_idI)\n  fix A assume \"A \\<in> set (weak_ranking le)\"\n  hence \"is_singleton A\" by (rule singleton_weak_ranking)\n  thus \"{the_elem A} = A\" by (auto elim: is_singletonE)\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/Order_Predicates.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8670357598021707, "lm_q2_score": 0.8397339616560072, "lm_q1q2_score": 0.7280793734761031}}
{"text": "(*  Title:    HOL/Library/Periodic_Fun.thy\n    Author:   Manuel Eberl, TU M\u00fcnchen\n*)\n\nsection \\<open>Periodic Functions\\<close>\n\ntheory Periodic_Fun\nimports Complex_Main\nbegin\n\ntext \\<open>\n  A locale for periodic functions. The idea is that one proves $f(x + p) = f(x)$\n  for some period $p$ and gets derived results like $f(x - p) = f(x)$ and $f(x + 2p) = f(x)$\n  for free.\n\n  @{term g} and @{term gm} are ``plus/minus k periods'' functions. \n  @{term g1} and @{term gn1} are ``plus/minus one period'' functions.\n  This is useful e.g. if the period is one; the lemmas one gets are then \n  @{term \"f (x + 1) = f x\"} instead of @{term \"f (x + 1 * 1) = f x\"} etc.\n\\<close>\nlocale periodic_fun = \n  fixes f :: \"('a :: {ring_1}) \\<Rightarrow> 'b\" and g gm :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a\" and g1 gn1 :: \"'a \\<Rightarrow> 'a\"\n  assumes plus_1: \"f (g1 x) = f x\"\n  assumes periodic_arg_plus_0: \"g x 0 = x\"\n  assumes periodic_arg_plus_distrib: \"g x (of_int (m + n)) = g (g x (of_int n)) (of_int m)\"\n  assumes plus_1_eq: \"g x 1 = g1 x\" and minus_1_eq: \"g x (-1) = gn1 x\" \n          and minus_eq: \"g x (-y) = gm x y\"\nbegin\n\nlemma plus_of_nat: \"f (g x (of_nat n)) = f x\"\n  by (induction n) (insert periodic_arg_plus_distrib[of _ 1 \"int n\" for n], \n                    simp_all add: plus_1 periodic_arg_plus_0 plus_1_eq)\n\nlemma minus_of_nat: \"f (gm x (of_nat n)) = f x\"\nproof -\n  have \"f (g x (- of_nat n)) = f (g (g x (- of_nat n)) (of_nat n))\"\n    by (rule plus_of_nat[symmetric])\n  also have \"\\<dots> = f (g (g x (of_int (- of_nat n))) (of_int (of_nat n)))\" by simp\n  also have \"\\<dots> = f x\" \n    by (subst periodic_arg_plus_distrib [symmetric]) (simp add: periodic_arg_plus_0)\n  finally show ?thesis by (simp add: minus_eq)\nqed\n\nlemma plus_of_int: \"f (g x (of_int n)) = f x\"\n  by (induction n) (simp_all add: plus_of_nat minus_of_nat minus_eq del: of_nat_Suc)\n\nlemma minus_of_int: \"f (gm x (of_int n)) = f x\"\n  using plus_of_int[of x \"of_int (-n)\"] by (simp add: minus_eq)\n\nlemma plus_numeral: \"f (g x (numeral n)) = f x\"\n  by (subst of_nat_numeral[symmetric], subst plus_of_nat) (rule refl)\n\nlemma minus_numeral: \"f (gm x (numeral n)) = f x\"\n  by (subst of_nat_numeral[symmetric], subst minus_of_nat) (rule refl)\n\nlemma minus_1: \"f (gn1 x) = f x\"\n  using minus_of_nat[of x 1] by (simp add: minus_1_eq minus_eq[symmetric])\n\nlemmas periodic_simps = plus_of_nat minus_of_nat plus_of_int minus_of_int \n                        plus_numeral minus_numeral plus_1 minus_1\n\nend\n\n\ntext \\<open>\n  Specialised case of the @{term periodic_fun} locale for periods that are not 1.\n  Gives lemmas @{term \"f (x - period) = f x\"} etc.\n\\<close>\nlocale periodic_fun_simple = \n  fixes f :: \"('a :: {ring_1}) \\<Rightarrow> 'b\" and period :: 'a\n  assumes plus_period: \"f (x + period) = f x\"\nbegin\nsublocale periodic_fun f \"\\<lambda>z x. z + x * period\" \"\\<lambda>z x. z - x * period\" \n  \"\\<lambda>z. z + period\" \"\\<lambda>z. z - period\"\n  by standard (simp_all add: ring_distribs plus_period)\nend\n\n\ntext \\<open>\n  Specialised case of the @{term periodic_fun} locale for period 1.\n  Gives lemmas @{term \"f (x - 1) = f x\"} etc.\n\\<close>\nlocale periodic_fun_simple' = \n  fixes f :: \"('a :: {ring_1}) \\<Rightarrow> 'b\"\n  assumes plus_period: \"f (x + 1) = f x\"\nbegin\nsublocale periodic_fun f \"\\<lambda>z x. z + x\" \"\\<lambda>z x. z - x\" \"\\<lambda>z. z + 1\" \"\\<lambda>z. z - 1\"\n  by standard (simp_all add: ring_distribs plus_period)\n\nlemma of_nat: \"f (of_nat n) = f 0\" using plus_of_nat[of 0 n] by simp\nlemma uminus_of_nat: \"f (-of_nat n) = f 0\" using minus_of_nat[of 0 n] by simp\nlemma of_int: \"f (of_int n) = f 0\" using plus_of_int[of 0 n] by simp\nlemma uminus_of_int: \"f (-of_int n) = f 0\" using minus_of_int[of 0 n] by simp\nlemma of_numeral: \"f (numeral n) = f 0\" using plus_numeral[of 0 n] by simp\nlemma of_neg_numeral: \"f (-numeral n) = f 0\" using minus_numeral[of 0 n] by simp\nlemma of_1: \"f 1 = f 0\" using plus_of_nat[of 0 1] by simp\nlemma of_neg_1: \"f (-1) = f 0\" using minus_of_nat[of 0 1] by simp\n\nlemmas periodic_simps' = \n  of_nat uminus_of_nat of_int uminus_of_int of_numeral of_neg_numeral of_1 of_neg_1\n\nend\n\nlemma sin_plus_pi: \"sin ((z :: 'a :: {real_normed_field,banach}) + of_real pi) = - sin z\"\n  by (simp add: sin_add)\n  \nlemma cos_plus_pi: \"cos ((z :: 'a :: {real_normed_field,banach}) + of_real pi) = - cos z\"\n  by (simp add: cos_add)\n\ninterpretation sin: periodic_fun_simple sin \"2 * of_real pi :: 'a :: {real_normed_field,banach}\"\nproof\n  fix z :: 'a\n  have \"sin (z + 2 * of_real pi) = sin (z + of_real pi + of_real pi)\" by (simp add: ac_simps)\n  also have \"\\<dots> = sin z\" by (simp only: sin_plus_pi) simp\n  finally show \"sin (z + 2 * of_real pi) = sin z\" .\nqed\n\ninterpretation cos: periodic_fun_simple cos \"2 * of_real pi :: 'a :: {real_normed_field,banach}\"\nproof\n  fix z :: 'a\n  have \"cos (z + 2 * of_real pi) = cos (z + of_real pi + of_real pi)\" by (simp add: ac_simps)\n  also have \"\\<dots> = cos z\" by (simp only: cos_plus_pi) simp\n  finally show \"cos (z + 2 * of_real pi) = cos z\" .\nqed\n\ninterpretation tan: periodic_fun_simple tan \"2 * of_real pi :: 'a :: {real_normed_field,banach}\"\n  by standard (simp only: tan_def [abs_def] sin.plus_1 cos.plus_1)\n\ninterpretation cot: periodic_fun_simple cot \"2 * of_real pi :: 'a :: {real_normed_field,banach}\"\n  by standard (simp only: cot_def [abs_def] sin.plus_1 cos.plus_1)\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/Periodic_Fun.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339676722393, "lm_q2_score": 0.8670357477770337, "lm_q1q2_score": 0.7280793685944754}}
{"text": "header{*An Application: Finite Automata*}\n\ntheory Finite_Automata imports Ordinal\nbegin\n\ntext {*The point of this example is that the HF sets are closed under disjoint sums and Cartesian products,\n allowing the theory of finite state machines to be developed without issues of polymorphism \n or any tricky encodings of states.*}\n\nrecord 'a fsm = states :: hf \n                init :: hf \n                final :: hf\n                nxt :: \"hf \\<Rightarrow> 'a \\<Rightarrow> hf \\<Rightarrow> bool\"\n\ninductive reaches :: \"['a fsm, hf, 'a list, hf] \\<Rightarrow> bool\"\nwhere\n    Nil:  \"st <: states fsm \\<Longrightarrow> reaches fsm st [] st\"\n  | Cons: \"\\<lbrakk>nxt fsm st x st''; reaches fsm st'' xs st'; st <: states fsm\\<rbrakk> \\<Longrightarrow> reaches fsm st (x#xs) st'\"\n\ndeclare reaches.intros [intro]\ninductive_simps reaches_Nil [simp]:  \"reaches fsm st [] st'\"\ninductive_simps reaches_Cons [simp]: \"reaches fsm st (x#xs) st'\"\n\nlemma reaches_imp_states: \"reaches fsm st xs st' \\<Longrightarrow> st <: states fsm \\<and> st' <: states fsm\"\n  by (induct xs arbitrary: st st', auto)\n\nlemma reaches_append_iff:\n     \"reaches fsm st (xs@ys) st' \\<longleftrightarrow> (\\<exists>st''. reaches fsm st xs st'' \\<and> reaches fsm st'' ys st')\"\n  by (induct xs arbitrary: ys st st') (auto simp: reaches_imp_states)\n\ndefinition accepts :: \"'a fsm \\<Rightarrow> 'a list \\<Rightarrow> bool\"  where\n  \"accepts fsm xs \\<equiv> \\<exists>st st'. reaches fsm st xs st' \\<and> st <: init fsm \\<and> st' <: final fsm\"\n\ndefinition regular :: \"'a list set \\<Rightarrow> bool\" where\n  \"regular S \\<equiv> \\<exists>fsm. S = {xs. accepts fsm xs}\"\n\ndefinition Null where\n  \"Null = \\<lparr>states = 0, init = 0, final = 0, nxt = \\<lambda>st x st'. False\\<rparr>\"\n\ntheorem regular_empty:  \"regular {}\"\n  by (auto simp: regular_def accepts_def) (metis hempty_iff simps(2))\n\nabbreviation NullStr where\n  \"NullStr \\<equiv> \\<lparr>states = 1, init = 1, final = 1, nxt = \\<lambda>st x st'. False\\<rparr>\"\n\ntheorem regular_emptystr:  \"regular {[]}\"\n  apply (auto simp: regular_def accepts_def) \n  apply (rule exI [where x = NullStr], auto)\n  apply (case_tac x, auto)\n  done\n\nabbreviation SingStr where\n  \"SingStr a \\<equiv> \\<lparr>states = {|0, 1|}, init = {|0|}, final = {|1|}, nxt = \\<lambda>st x st'. st=0 \\<and> x=a \\<and> st'=1\\<rparr>\"\n\ntheorem regular_singstr: \"regular {[a]}\"\n  apply (auto simp: regular_def accepts_def) \n  apply (rule exI [where x = \"SingStr a\"], auto)\n  apply (case_tac x, auto)\n  apply (case_tac list, auto)\n  done\n\ndefinition Reverse where\n  \"Reverse fsm = \\<lparr>states = states fsm, init = final fsm, final = init fsm,\n                  nxt = \\<lambda>st x st'. nxt fsm st' x st\\<rparr>\"\n\nlemma Reverse_Reverse_ident [simp]: \"Reverse (Reverse fsm) = fsm\"\n  by (simp add: Reverse_def)\n\nlemma reaches_Reverse_iff [simp]: \n     \"reaches (Reverse fsm) st (rev xs) st' \\<longleftrightarrow> reaches fsm st' xs st\" \n  by (induct xs arbitrary: st st') (auto simp add: Reverse_def reaches_append_iff reaches_imp_states)\n\nlemma reaches_Reverse_iff2 [simp]: \n     \"reaches (Reverse fsm) st' xs st \\<longleftrightarrow> reaches fsm st (rev xs) st'\" \n  by (metis reaches_Reverse_iff rev_rev_ident)     \n\n\n\nlemma [simp]: \"final (Reverse fsm) = init fsm\"\n  by (simp add: Reverse_def)\n\ntheorem regular_rev: \"regular S \\<Longrightarrow> regular (rev ` S)\"\n  apply (auto simp: regular_def accepts_def) \n  apply (rule_tac x=\"Reverse fsm\" in exI, force+)\n  done\n\ndefinition Times where\n  \"Times fsm1 fsm2 = \\<lparr>states = states fsm1 * states fsm2, \n                      init = init fsm1 * init fsm2, \n                      final = final fsm1 * final fsm2,\n                      nxt = \\<lambda>st x st'. (\\<exists>st1 st2 st1' st2'. st = \\<langle>st1,st2\\<rangle> \\<and> st' = \\<langle>st1',st2'\\<rangle> \\<and> \n                                      nxt fsm1 st1 x st1' \\<and> nxt fsm2 st2 x st2')\\<rparr>\"\n\nlemma states_Times [simp]: \"states (Times fsm1 fsm2) = states fsm1 * states fsm2\"                      \n  by (simp add: Times_def)\n\nlemma init_Times [simp]: \"init (Times fsm1 fsm2) = init fsm1 * init fsm2\"                      \n  by (simp add: Times_def)\n\nlemma final_Times [simp]: \"final (Times fsm1 fsm2) = final fsm1 * final fsm2\"                      \n  by (simp add: Times_def)\n\nlemma nxt_Times: \"nxt (Times fsm1 fsm2) \\<langle>st1,st2\\<rangle> x st' \\<longleftrightarrow> \n    (\\<exists>st1' st2'. st' = \\<langle>st1',st2'\\<rangle> \\<and> nxt fsm1 st1 x st1' \\<and> nxt fsm2 st2 x st2')\"\n  by (simp add: Times_def)\n\nlemma reaches_Times_iff [simp]: \n     \"reaches (Times fsm1 fsm2) \\<langle>st1,st2\\<rangle> xs \\<langle>st1',st2'\\<rangle> \\<longleftrightarrow> \n      reaches fsm1 st1 xs st1' \\<and> reaches fsm2 st2 xs st2'\" \napply (induct xs arbitrary: st1 st2 st1' st2', force)\napply (force simp add: nxt_Times Times_def reaches.Cons)\ndone\n\nlemma accepts_Times_iff [simp]: \n     \"accepts (Times fsm1 fsm2) xs \\<longleftrightarrow> \n      accepts fsm1 xs \\<and> accepts fsm2 xs\"\n  by (force simp add: accepts_def)\n\ntheorem regular_Int: \n  assumes S: \"regular S\" and T: \"regular T\" shows \"regular (S \\<inter> T)\"\nproof -\n  obtain fsmS fsmT where \"S = {xs. accepts fsmS xs}\" \"T = {xs. accepts fsmT xs}\" using S T \n    by (auto simp: regular_def)\n  hence \"S \\<inter> T = {xs. accepts (Times fsmS fsmT) xs}\"\n    by (auto simp: accepts_Times_iff [of fsmS fsmT])\n  thus ?thesis\n    by (metis regular_def)\nqed\n\ndefinition Plus where\n  \"Plus fsm1 fsm2 = \\<lparr>states = states fsm1 + states fsm2, \n                      init = init fsm1 + init fsm2, \n                      final = final fsm1 + final fsm2,\n                      nxt = \\<lambda>st x st'. (\\<exists>st1 st1'. st = Inl st1 \\<and> st' = Inl st1' \\<and> nxt fsm1 st1 x st1') \\<or>\n                                       (\\<exists>st2 st2'. st = Inr st2 \\<and> st' = Inr st2' \\<and> nxt fsm2 st2 x st2')\\<rparr>\"\n\nlemma states_Plus [simp]: \"states (Plus fsm1 fsm2) = states fsm1 + states fsm2\"       \n  by (simp add: Plus_def)\n\nlemma init_Plus [simp]: \"init (Plus fsm1 fsm2) = init fsm1 + init fsm2\"           \n  by (simp add: Plus_def)\n\nlemma final_Plus [simp]: \"final (Plus fsm1 fsm2) = final fsm1 + final fsm2\"                      \n  by (simp add: Plus_def)\n\nlemma nxt_Plus1: \"nxt (Plus fsm1 fsm2) (Inl st1) x st' \\<longleftrightarrow> (\\<exists>st1'. st' = Inl st1' \\<and> nxt fsm1 st1 x st1')\"\n  by (simp add: Plus_def)\n\nlemma nxt_Plus2: \"nxt (Plus fsm1 fsm2) (Inr st2) x st' \\<longleftrightarrow> (\\<exists>st2'. st' = Inr st2' \\<and> nxt fsm2 st2 x st2')\"\n  by (simp add: Plus_def)\n\nlemma reaches_Plus_iff1 [simp]: \n     \"reaches (Plus fsm1 fsm2) (Inl st1) xs st' \\<longleftrightarrow> \n      (\\<exists>st1'. st' = Inl st1' \\<and> reaches fsm1 st1 xs st1')\" \napply (induct xs arbitrary: st1, force)\napply (force simp add: nxt_Plus1 reaches.Cons)\ndone\n\nlemma reaches_Plus_iff2 [simp]: \n     \"reaches (Plus fsm1 fsm2) (Inr st2) xs st' \\<longleftrightarrow> \n      (\\<exists>st2'. st' = Inr st2' \\<and> reaches fsm2 st2 xs st2')\" \napply (induct xs arbitrary: st2, force)\napply (force simp add: nxt_Plus2 reaches.Cons)\ndone\n\nlemma reaches_Plus_iff [simp]: \n     \"reaches (Plus fsm1 fsm2) st xs st' \\<longleftrightarrow> \n      (\\<exists>st1 st1'. st = Inl st1 \\<and> st' = Inl st1' \\<and> reaches fsm1 st1 xs st1') \\<or>\n      (\\<exists>st2 st2'. st = Inr st2 \\<and> st' = Inr st2' \\<and> reaches fsm2 st2 xs st2')\"\napply (induct xs arbitrary: st st', auto)\napply (force simp add: nxt_Plus1 nxt_Plus2 Plus_def reaches.Cons)\napply (auto simp: Plus_def)\ndone\n\nlemma accepts_Plus_iff [simp]: \n     \"accepts (Plus fsm1 fsm2) xs \\<longleftrightarrow> accepts fsm1 xs \\<or> accepts fsm2 xs\"\n  by (auto simp: accepts_def) (metis sum_iff)\n\nlemma regular_Un: \n  assumes S: \"regular S\" and T: \"regular T\" shows \"regular (S \\<union> T)\"\nproof -\n  obtain fsmS fsmT where \"S = {xs. accepts fsmS xs}\" \"T = {xs. accepts fsmT xs}\" using S T \n    by (auto simp: regular_def)\n  hence \"S \\<union> T = {xs. accepts (Plus fsmS fsmT) xs}\"\n    by (auto simp: accepts_Plus_iff [of fsmS fsmT])\n  thus ?thesis\n    by (metis regular_def)\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/HereditarilyFinite/Finite_Automata.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.867035752930664, "lm_q2_score": 0.8397339596505965, "lm_q1q2_score": 0.7280793659671028}}
{"text": "theory Submission\n  imports Defs\nbegin\n\nlemma set_of_altdef_aux: \"fold (\\<union>) (map set_of_i xs) A  = \\<Union> (set_of_i ` set xs) \\<union> A\"\n  unfolding set_of_def\n  by (induction xs arbitrary: A) auto\n\nlemma set_of_altdef: \"set_of xs = (\\<Union>ivl\\<in>set xs. set_of_i ivl)\"\n  unfolding set_of_def by (simp add: set_of_altdef_aux)\n\nlemma set_of_Nil [simp]: \"set_of [] = {}\"\n  by (simp add: set_of_altdef)\n\nlemma set_of_append [simp]: \"set_of (xs @ ys) = set_of xs \\<union> set_of ys\"\n  by (simp add: set_of_altdef)\n\nlemma set_of_Cons [simp]: \"set_of (x # xs) = set_of_i x \\<union> set_of xs\"\n  by (simp add: set_of_altdef)\n\nfun compl_aux :: \"nat \\<Rightarrow> intervals \\<Rightarrow> intervals\" where\n  \"compl_aux a [] = [[a, \\<infinity>)]\"\n| \"compl_aux a ([l, enat u) # ivls) = (if a = l then [] else [[a, enat l)]) @ compl_aux u ivls\"\n| \"compl_aux a [[l, \\<infinity>)] = (if a = l then [] else [[a, enat l)])\"\n\nlemma inv'_mono:\n  assumes \"inv' a ivls\" \"b \\<le> a\"\n  shows   \"inv' b ivls\"\n  using assms\n  by (induction a ivls rule: inv'.induct) auto\n\nlemma inv'_subset:\n  assumes \"inv' u ivls\"\n  shows   \"set_of ivls \\<subseteq> {u..}\"\n  using assms by (induction u ivls rule: inv'.induct) auto\n\nlemma inv'_compl_aux:\n  fixes ivls :: intervals\n  assumes \"inv' a ivls\" \"\\<forall>x\\<in>set_of ivls. x \\<ge> a\"\n  shows   \"inv' a (compl_aux a ivls)\"\n  using assms\nproof (induction a ivls rule: compl_aux.induct)\n  case (2 a l u ivls)\n  have IH: \"inv' u (compl_aux u ivls)\"\n    using 2 inv'_mono[of \"Suc u\" ivls u] inv'_subset\n    by (intro \"2.IH\") auto\n  show ?case\n    using IH \"2.prems\" by (auto intro: inv'_mono)\nqed (auto simp: atLeast_def)\n\nlemma set_of_compl_aux:\n  fixes ivls :: intervals\n  assumes \"inv' a ivls\"\n  shows   \"set_of (compl_aux a ivls) = {a..} - set_of ivls\"\n  using assms\nproof (induction a ivls rule: compl_aux.induct)\n  case (2 a l u ivls)\n  have \"set_of (compl_aux u ivls) = {u..} - set_of ivls\"\n    using \"2.prems\" inv'_mono by (intro \"2.IH\") force+\n  thus ?case using \"2.prems\"  inv'_subset[of \"Suc u\" ivls] by force\nqed auto\n\n\ndefinition compl :: \"intervals \\<Rightarrow> intervals\" where\n  \"compl x = compl_aux 0 x\"\n\ntheorem compl_inv:\n  assumes \"inv ins\"\n  shows \"inv (compl ins)\"\n  unfolding compl_def inv_def\n  using assms by (intro inv'_compl_aux) (auto simp: inv_def)\n\ntheorem compl_set_of:\n  assumes \"inv ins\"\n  shows \"set_of (compl ins) = -set_of ins\"\n  using assms unfolding compl_def by (subst set_of_compl_aux) (auto simp: inv_def)\n\n\ntext \\<open>\n  And for good measure: Intersection of interval lists.\n\\<close>\nfun inter :: \"intervals \\<Rightarrow> intervals \\<Rightarrow> intervals\" where\n  \"inter [] ivls2 = []\"\n| \"inter ivls1 [] = []\"\n| \"inter [[l1, \\<infinity>)] [[l2, \\<infinity>)] = [[max l1 l2, \\<infinity>)]\"\n| \"inter ([l1, enat u1) # ivls1) [[l2, \\<infinity>)] =\n     (if u1 > l2 then [[max l1 l2, u1)] else []) @ inter ivls1 [[l2, \\<infinity>)]\"\n| \"inter [[l1, \\<infinity>)] ([l2, enat u2) # ivls2) =\n     (if u2 > l1 then [[max l1 l2, u2)] else []) @ inter [[l1, \\<infinity>)] ivls2\"\n| \"inter ([l1, enat u1) # ivls1) ([l2, enat u2) # ivls2) =\n     (if u1 \\<le> l2 then inter ivls1 ([l2, u2) # ivls2)\n      else if u2 \\<le> l1 then inter ([l1, u1) # ivls1) ivls2\n      else [max l1 l2, min u1 u2) #\n             (if u1 \\<le> u2 then inter ivls1 ([l2, u2) # ivls2)\n              else inter ([l1, u1) # ivls1) ivls2))\"\n\nlemma inv'_inter:\n  assumes \"inv' a ivls1\" \"inv' b ivls2\" \"max a b \\<ge> c\"\n  shows   \"inv' c (inter ivls1 ivls2)\"\n  using assms by (induction ivls1 ivls2 arbitrary: a b c rule: inter.induct) auto\n\nlemma inv_inter:\n  assumes \"inv ivls1\" \"inv ivls2\"\n  shows   \"inv (inter ivls1 ivls2)\"\n  using assms unfolding inv_def by (intro inv'_inter[where a = 0 and b = 0]) auto\n\nlemma set_of_inter_aux:\n  assumes \"inv' a ivls1\" \"inv' b ivls2\"\n  shows   \"set_of (inter ivls1 ivls2) = set_of ivls1 \\<inter> set_of ivls2\"\n  using assms\nproof (induction ivls1 ivls2 arbitrary: a b rule: inter.induct)\n  case (6 l1 u1 ivls1 l2 u2 ivls2 a b)\n  show ?case\n  proof (cases \"u1 \\<le> l2\")\n    case True\n    thus ?thesis using \"6.prems\" inv'_subset\n      apply simp\n      apply (subst \"6.IH\"(1)[where a = \"Suc u1\" and b = b])\n         apply force+\n      done\n  next\n    case not_le: False\n    show ?thesis\n    proof (cases \"u2 \\<le> l1\")\n      case True\n      thus ?thesis using not_le inv'_subset \"6.prems\"\n        apply simp\n        apply (subst \"6.IH\"(2)[where a = \"a\" and b = \"Suc u2\"])\n            apply force+\n        done\n    next\n      case not_le': False\n      show ?thesis\n      proof (cases \"u1 \\<le> u2\")\n        case True\n        thus ?thesis using not_le not_le' \"6.prems\" inv'_subset\n          apply (simp)\n          apply (subst \"6.IH\"(3)[where a = \"Suc u1\" and b = b])\n               apply force+\n          done\n      next\n        case False\n        thus ?thesis using not_le not_le' \"6.prems\" inv'_subset\n          apply (simp)\n          apply (subst \"6.IH\"(4)[where a = a and b = \"Suc u2\"])\n               apply force+\n          done\n      qed\n    qed\n  qed\nqed auto\n\nlemma set_of_inter:\n  assumes \"inv ivls1\" \"inv ivls2\"\n  shows   \"set_of (inter ivls1 ivls2) = set_of ivls1 \\<inter> set_of ivls2\"\n  using assms unfolding inv_def by (intro set_of_inter_aux[where a = 0 and b = 0]) auto\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/interval-lists/isabelle/eberlm/Submission.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9149009480320036, "lm_q2_score": 0.7956581024858786, "lm_q1q2_score": 0.7279483522736755}}
{"text": "theory Demo3 imports Main begin\n\nsection {* Example 1 *}\n\nlocale semi =\n  fixes prod :: \"['a, 'a] => 'a\" (infixl \"\\<cdot>\" 70)\n  assumes assoc: \"(x \\<cdot> y) \\<cdot> z = x \\<cdot> (y \\<cdot> z)\"\n\nlocale group = semi +\n  fixes one and inv\n  assumes l_one: \"one \\<cdot> x = x\"\n    and r_one: \"x \\<cdot> one = x\"\n    and l_inv: \"inv x \\<cdot> x = one\"\n    and r_inv: \"x \\<cdot> inv x = one\"\n\nlemma (in group) l_cancel: \"(x \\<cdot> y = x \\<cdot> z) = (y = z)\"\nproof\n  assume \"x \\<cdot> y = x \\<cdot> z\"\n  then have \"(inv x \\<cdot> x) \\<cdot> y = (inv x \\<cdot> x) \\<cdot> z\" by (simp add: assoc)\n  then show \"y = z\" by (simp add: l_one l_inv)\nnext\n  assume \"y = z\"\n  then show \"x \\<cdot> y = x \\<cdot> z\" by simp\nqed\n\nsubsection {* Export *}\n\nthm semi.assoc group.l_cancel\n\nsubsection {* Definitions *}\n\nlocale semi2 = semi +\n  fixes rprod (infixl \"\\<odot>\" 70)\n  defines rprod_def: \"rprod x y \\<equiv> y \\<cdot> x \"\n\nlemma (in semi2) r_assoc:\n  \"(x \\<odot> y) \\<odot> z = x \\<odot> (y \\<odot> z)\"\n  by (simp only: rprod_def assoc)\n\nthm semi2.r_assoc\n\nsection {* Example 2 *}\n\nlocale group_hom = group sum zero minus + group +\n  fixes hom\n  assumes hom_mult: \"hom (sum x y) = hom x \\<cdot> hom y\"\n\nlemma (in group_hom) hom_one: \"hom zero = one\"\nproof -\n  have \"hom zero \\<cdot> one = hom zero \\<cdot> hom zero\"\n    by (simp add: hom_mult [symmetric]\n      sum_zero_minus.l_one prod_one_inv.r_one)\n    -- {* Or add @{text l_one} to simpset right away. *}\n  then show ?thesis by (simp add: l_cancel)\nqed\n\nsection {* Example 3 *}\n\nlemma int_semi:\n  \"semi (op +::[int, int]=>int)\"\n  by (auto intro!: semi.intro)\n\nlemma int_group:\n  \"group (op +) (0::int) uminus\"\n  by (auto intro!: group.intro semi.intro group_axioms.intro)\n\ntext {* Manual interpretation possible with the OF attribute. *}\n\nthm semi.assoc [OF int_semi]\nthm group.l_cancel [OF int_group]\n\ntext {* Automatic interpretation *}\n\nlemma bla: True\nproof -\n  from int_group interpret my: group [\"op +\" \"0::int\" \"uminus\"]\n    by (auto intro: group.axioms)\n  thm my.assoc my.l_cancel\noops\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/IJCAR04/S3Demo3.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869948899665, "lm_q2_score": 0.8311430415844384, "lm_q1q2_score": 0.7279042667129417}}
{"text": "(*\nTitle: Uniqueness of the representation of a prime as a sum of two squares\nAuthor: Jose Manuel Rodriguez Caballero\n\nRoelof Oosterhuis [SumSquares-AFP] mechanized the so-called Fermat's Christmas Theorem: \nany prime number having the form p = 4k+1 can be represented as a sum of two squares of natural\nnumbers. In the present development, we contribute to the subject of representation of integers\nas a sum of two squares by means of the following uniqueness result: the representation of\na prime p = 4k+1 as a sum of two squares of natural numbers is unique up a to permutation of the\nsquares. \n\nOur approach will be like in the proof of Theorem 13.4 in [nathanson2008elementary]. The original\nproof involves subtractions, but we attained the same goal using additions and cancellations.\n\n\nReferences.\n\n@book{nathanson2008elementary,\n  title={Elementary methods in number theory},\n  author={Nathanson, Melvyn B},\n  volume={195},\n  year={2008},\n  publisher={Springer Science & Business Media}\n}\n\n@article{SumSquares-AFP,\n  author  = {Roelof Oosterhuis},\n  title   = {Sums of Two and Four Squares},\n  journal = {Archive of Formal Proofs},\n  month   = aug,\n  year    = 2007,\n  note    = {\\url{http://isa-afp.org/entries/SumSquares.html},\n            Formal proof development},\n  ISSN    = {2150-914x},\n}\n\n(This code was verified in Isabelle2018)\n\n*)\n\ntheory SumOfSquaresUniqueness\n\nimports Complex_Main \"HOL-Number_Theory.Number_Theory\"\n\nbegin\n\nlemma DiophantusIdentityNat : \n  fixes a b c d :: nat\n  assumes kdef: \"k + b*d = a*c\"\n  shows \"(a^2 + b^2)*(c^2 + d^2) = k^2 + (a*d + b*c)^2\"\nproof -\n  from kdef have \"a^2*c^2 = k^2 + 2*k*b*d + b^2*d^2\" by (metis (mono_tags, lifting) power2_sum semiring_normalization_rules(18) semiring_normalization_rules(23) semiring_normalization_rules(30))\n  hence \"a^2*(c^2 + d^2) = k^2 + 2*k*b*d + b^2*d^2 + a^2*d^2\" by (simp add: distrib_left)\n  hence \"a^2*(c^2 + d^2)+b^2*(c^2 + d^2) = k^2 + 2*k*b*d + b^2*d^2 + a^2*d^2 + b^2*c^2 + b^2*d^2\" by (simp add: distrib_left)\n  hence \"(a^2 + b^2)*(c^2 + d^2) = k^2 + 2*k*b*d + a^2*d^2 + b^2*c^2 + 2* b^2*d^2\" by (simp add: semiring_normalization_rules(1))\n  hence  \"(a^2 + b^2)*(c^2 + d^2) = k^2 + 2*b*d* (k + b*d) + a^2*d^2 + b^2*c^2\" by (smt add_mult_distrib2 mult.commute power2_eq_square semiring_normalization_rules(16) semiring_normalization_rules(23) semiring_normalization_rules(25))\n  hence  \"(a^2 + b^2)*(c^2 + d^2) = k^2 + 2*b*d*a*c + a^2*d^2 + b^2*c^2\" using kdef by simp\n  thus ?thesis by (simp add: power2_sum power_mult_distrib)\nqed\n\n\nlemma  FermatChristmasUniquenessLem :\n  fixes p a\\<^sub>1 b\\<^sub>1 a\\<^sub>2 b\\<^sub>2 :: nat\n  assumes a1la2: \"a\\<^sub>1 < a\\<^sub>2\"\n    and podd: \"odd p\"\n    and sumofsq1: \"p = a\\<^sub>1^2 + b\\<^sub>1^2\"\n    and a1odd: \"odd a\\<^sub>1\"\n    and sumofsq2: \"p = a\\<^sub>2^2 + b\\<^sub>2^2\"\n    and a2odd: \"odd a\\<^sub>2\"\n  shows \"\\<not>  prime p\"\nproof -\n  have  b1lb2: \"b\\<^sub>1 > b\\<^sub>2\"\n  proof-  \n    from a1la2 have a1la2sq: \"a\\<^sub>1^2 < a\\<^sub>2^2\" by (simp add: power_strict_mono)\n    from sumofsq1 sumofsq2 have \"a\\<^sub>1^2 + b\\<^sub>1^2 =a\\<^sub>2^2 + b\\<^sub>2^2\" by simp\n    then   have \"b\\<^sub>1^2 > b\\<^sub>2^2\" using  a1la2sq by linarith\n    thus ?thesis using power_less_imp_less_base by blast\n  qed\n\n  from podd sumofsq1 a1odd have b1eveb: \"even b\\<^sub>1\" by simp\n  from podd sumofsq2 a1odd have b2eveb: \"even b\\<^sub>2\" by (simp add: a2odd )\n\n  have \"\\<exists> x::nat. a\\<^sub>2 = a\\<^sub>1 + 2*x\" \n  proof -\n    from a1la2 obtain U::nat where a2eqa1plusU: \"a\\<^sub>2 = a\\<^sub>1 + U\" using less_imp_add_positive by blast\n    from a2eqa1plusU a1odd a2odd have \"even U\" using even_add by blast\n    then obtain u::nat where Ux: \"U = 2*u\" using evenE by blast\n    from Ux a2eqa1plusU show ?thesis  by blast\n  qed\n  then obtain x :: nat where xdef: \"a\\<^sub>2 = a\\<^sub>1 + 2*x\"  by blast\n  have \"\\<exists> y::nat. b\\<^sub>1 = b\\<^sub>2 + 2*y\"\n  proof -\n    from b1lb2 obtain V::nat where b1eqb2plusV: \"b\\<^sub>1 = b\\<^sub>2 + V\" using less_imp_add_positive by blast\n    from b1eqb2plusV have \"even V\" using even_add  using b1eveb b2eveb by blast\n    then obtain v::nat where Vy: \"V = 2*v\" using evenE by blast\n    from Vy b1eqb2plusV show ?thesis  by blast\n  qed\n  then obtain y::nat where ydef: \"b\\<^sub>1 = b\\<^sub>2 + 2*y\" by blast\n  obtain d::nat where ddef: \"d = gcd x y\" by simp\n  from a1la2 xdef have x0: \"x \\<noteq> 0\"  by simp \n  from b1lb2 ydef have y0: \"y \\<noteq> 0\"  by simp \n  from ddef have d0: \"d \\<noteq> 0\"  using x0  by auto\n  from ddef obtain X::nat where Xdef: \"x = d*X\" using dvdE by blast\n  from ddef obtain Y::nat where Ydef: \"y = d*Y\" using dvdE by blast\n  from x0 Xdef d0 have X0: \"X \\<noteq> 0\" by simp \n  from y0 Ydef d0 have Y0: \"Y \\<noteq> 0\" by simp \n  from ddef d0 Xdef Ydef have gcdXY: \"gcd X Y = 1\" by (metis gcd_mult_distrib_nat mult_eq_self_implies_10)\n  have b1y: \"b\\<^sub>1*Y = (a\\<^sub>1 + x)*X + y*Y\"\n  proof -\n    from xdef have xsq: \"a\\<^sub>2^2 = a\\<^sub>1^2 + 4*x*a\\<^sub>1 + 4*x^2\" \n    proof -\n      show ?thesis\n        by (simp add: power2_sum xdef)\n    qed\n    from ydef have ysq: \"b\\<^sub>2^2 + 4*y*b\\<^sub>2 + 4*y^2 = b\\<^sub>1^2\"\n    proof -\n      show ?thesis\n        by (simp add: power2_sum ydef)\n    qed\n    from xsq ysq  have  \"(a\\<^sub>2^2 + b\\<^sub>2^2) + 4*y*b\\<^sub>2 + 4*y^2 = (a\\<^sub>1^2 + b\\<^sub>1^2) + 4*x*a\\<^sub>1 + 4*x^2\"  by (simp add: semiring_normalization_rules(21))\n    hence \"p + 4*y*b\\<^sub>2 + 4*y^2 = p + 4*x*a\\<^sub>1 + 4*x^2\" using sumofsq1 sumofsq2 by simp\n    hence \"y*b\\<^sub>2 + y^2 = x*a\\<^sub>1 + x^2\" by simp\n    hence \"y*(b\\<^sub>2 + 2*y) = x*a\\<^sub>1 + x^2 + y^2\"  by (smt add.commute add_mult_distrib2 left_add_mult_distrib mult_2 power2_eq_square semiring_normalization_rules(1))      \n    hence \"b\\<^sub>1*y = a\\<^sub>1*x + x^2 + y^2\" using ydef by (simp add: semiring_normalization_rules(7))\n    hence \"d*b\\<^sub>1*Y = d*a\\<^sub>1*X + d*x*X + d*y*Y\" using Xdef Ydef by (metis mult.left_commute power2_eq_square semiring_normalization_rules(18))\n    hence \"d*b\\<^sub>1*Y = d*(a\\<^sub>1*X + x*X + y*Y)\" by (simp add: distrib_left)\n    hence \"b\\<^sub>1*Y = a\\<^sub>1*X + x*X + y*Y\" using d0 by simp\n    thus ?thesis by (simp add: add_mult_distrib)\n  qed\n  have  rdef: \"\\<exists> r::nat. r*Y = a\\<^sub>1 + d*X\"\n  proof -\n    from b1y have \"Y dvd (a\\<^sub>1 + x)*X\"  by (metis dvd_add_times_triv_right_iff dvd_triv_right)\n    hence \"Y dvd (a\\<^sub>1 + x)\" using gcdXY \n      by (metis (no_types, lifting) division_decomp dvd_triv_right  gcd_greatest_iff mult.right_neutral mult_dvd_mono)\n    thus ?thesis by (metis Xdef dvdE semiring_normalization_rules(7))\n  qed\n\n  from rdef obtain r::nat where rdef: \"r*Y = a\\<^sub>1 + d*X\" by auto\n  from  rdef b1y Xdef Ydef Y0  have  randb1: \"b\\<^sub>1 = r*X + d*Y\"  by (metis add_mult_distrib mult_cancel_right semiring_normalization_rules(16))\n  have rd2: \"r^2 + d^2 \\<ge> 2\" by (smt One_nat_def Suc_1 Suc_leI Y0 Ydef add_cancel_left_left add_gr_0 d0 le_add1 le_add2 le_add_same_cancel1 le_antisym le_less mult.commute mult_2_right mult_eq_0_iff power_eq_0_iff randb1 ydef)\n  have XY2: \"X^2 + Y^2 \\<ge> 2\" by (metis One_nat_def Suc_leI X0 Y0 add_mono neq0_conv numeral_Bit0 numeral_code(1) power_not_zero)\n  from rdef randb1  have \"(r^2 + d^2)*(X^2 + Y^2) = a\\<^sub>1^2 + b\\<^sub>1^2\"  by (metis DiophantusIdentityNat add.commute) \n  hence prod2sq: \"(r^2 + d^2)*(X^2 + Y^2) = p\" using sumofsq1 by blast\n  from prod2sq rd2 XY2 show ?thesis by (metis add_diff_cancel_left' diff_is_0_eq' dvd_triv_left mult.right_neutral mult_eq_0_iff nat_mult_eq_cancel_disj numeral_Bit0 numeral_One prime_nat_iff prime_prime_factor_sqrt)\nqed\n\nlemma  FermatChristmasUniquenessUpPermOneIsOdd :\n  fixes p a\\<^sub>1 b\\<^sub>1 :: nat\n  assumes\n    sumofsq1: \"p = a\\<^sub>1^2 + b\\<^sub>1^2\"\n    and podd: \"odd p\"\n  shows \\<open>odd a\\<^sub>1 \\<or> odd b\\<^sub>1\\<close>\n  using podd sumofsq1 by auto\n\n\ntheorem  FermatChristmasUniqueness:\n  fixes p a\\<^sub>1 b\\<^sub>1 a\\<^sub>2 b\\<^sub>2 :: nat\n  assumes pprime: \"prime p\"\n    and podd: \"odd p\"\n    and sumofsq1: \"p = a\\<^sub>1^2 + b\\<^sub>1^2\"\n    and a1odd: \"odd a\\<^sub>1\"\n    and sumofsq2: \"p = a\\<^sub>2^2 + b\\<^sub>2^2\"\n    and a2odd: \"odd a\\<^sub>2\"\n  shows \"a\\<^sub>1 = a\\<^sub>2 \\<and> b\\<^sub>1 = b\\<^sub>2\"\nproof-\n  from pprime podd sumofsq1 a1odd sumofsq2 a2odd  have a12: \"a\\<^sub>1 \\<ge> a\\<^sub>2\" \n    using FermatChristmasUniquenessLem leI by blast\n  from pprime podd sumofsq1 a1odd sumofsq2 a2odd  have a21: \"a\\<^sub>2 \\<ge> a\\<^sub>1\"\n    using FermatChristmasUniquenessLem leI by blast\n  from a12 a21 have a1eqa2: \"a\\<^sub>1 = a\\<^sub>2\" using le_antisym by blast \n  from sumofsq1 sumofsq2 a1eqa2 have b1eqb2: \"b\\<^sub>1 = b\\<^sub>2\" by auto\n  from a1eqa2 b1eqb2 show ?thesis by simp\nqed\n\n\ncorollary  FermatChristmasUniquenessUpPermPOdd :\n  fixes p a\\<^sub>1 b\\<^sub>1 a\\<^sub>2 b\\<^sub>2 :: nat\n  assumes pprime: \"prime p\"\n    and podd: \"odd p\"\n    and sumofsq1: \"p = a\\<^sub>1^2 + b\\<^sub>1^2\"\n    and sumofsq2: \"p = a\\<^sub>2^2 + b\\<^sub>2^2\"\n  shows \"(a\\<^sub>1 = a\\<^sub>2 \\<and> b\\<^sub>1 = b\\<^sub>2) \\<or> (a\\<^sub>1 = b\\<^sub>2 \\<and> b\\<^sub>1 = a\\<^sub>2)\"\n  by (metis FermatChristmasUniqueness FermatChristmasUniquenessUpPermOneIsOdd add.commute podd pprime sumofsq1 sumofsq2)\n\nend", "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/SumOfSquaresUniqueness.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8757869851639066, "lm_q2_score": 0.8311430457670241, "lm_q1q2_score": 0.7279042622922489}}
{"text": "theory Abs_Qr\n\nimports Mod_Plus_Minus\n        Kyber_spec\n\nbegin\ntext \\<open>Auxiliary lemmas\\<close>\n\nlemma finite_range_plus: \n  assumes \"finite (range f)\"\n          \"finite (range g)\"\n  shows \"finite (range (\\<lambda>x. f x + g x))\"\nproof -\n  have subs: \"range (\\<lambda>x. (f x, g x)) \\<subseteq> range f \\<times> range g\" by auto\n  have cart: \"finite (range f \\<times> range g)\" using assms by auto\n  have finite: \"finite (range (\\<lambda>x. (f x, g x)))\" \n    using rev_finite_subset[OF cart subs] .\n  have \"range (\\<lambda>x. f x + g x) = (\\<lambda>(a,b). a+b) ` range (\\<lambda>x. (f x, g x))\"\n    using range_composition[of \"(\\<lambda>(a,b). a+b)\" \"(\\<lambda>x. (f x, g x))\"] \n    by auto\n  then show ?thesis \n    using finite finite_image_set[where f = \"(\\<lambda>(a,b). a+b)\"] \n    by auto\nqed\n\nlemma all_impl_Max: \n  assumes \"\\<forall>x. f x \\<ge> (a::int)\"\n          \"finite (range f)\"\n  shows \"(MAX x. f x) \\<ge> a\"\nby (simp add: Max_ge_iff assms(1) assms(2))\n\nlemma Max_mono':\n  assumes \"\\<forall>x. f x \\<le> g x\"\n          \"finite (range f)\"\n          \"finite (range g)\"\n  shows \"(MAX x. f x) \\<le> (MAX x. g x)\"\nusing assms \nby (metis (no_types, lifting) Max_ge_iff Max_in UNIV_not_empty \n  image_is_empty rangeE rangeI)  \n\nlemma Max_mono_plus:\n  assumes \"finite (range (f::_\\<Rightarrow>_::ordered_ab_semigroup_add))\" \n          \"finite (range g)\"\n  shows \"(MAX x. f x + g x) \\<le> (MAX x. f x) + (MAX x. g x)\"\nproof -\n  obtain xmax where xmax_def: \"f xmax + g xmax = (MAX x. f x + g x)\" \n    using finite_range_plus[OF assms] Max_in by fastforce\n  have \"(MAX x. f x + g x) = f xmax + g xmax\" using xmax_def by auto\n  also have \"\\<dots> \\<le> (MAX x. f x) + g xmax\" \n    using Max_ge[OF assms(1), of \"f xmax\"] \n    by (auto simp add: add_right_mono[of \"f xmax\"]) \n  also have \"\\<dots> \\<le> (MAX x. f x) + (MAX x. g x)\" \n    using Max_ge[OF assms(2), of \"g xmax\"]\n    by (auto simp add: add_left_mono[of \"g xmax\"])\n  finally show ?thesis by auto\nqed\n\n\n\ntext \\<open>Lemmas for porting to \\<open>qr\\<close>.\\<close>\n\nlemma of_qr_mult:\n  \"of_qr (a * b) = of_qr a * of_qr b mod qr_poly\"\nby (metis of_qr_to_qr to_qr_mult to_qr_of_qr)\n\nlemma of_qr_scale:\n  \"of_qr (to_module s * b) = \n  Polynomial.smult (of_int_mod_ring s) (of_qr b)\"\nunfolding to_module_def\n  by (auto simp add: of_qr_mult[of \"to_qr [:of_int_mod_ring s:]\" \"b\"] \n  of_qr_to_qr) (simp add: mod_mult_left_eq mod_smult_left of_qr.rep_eq)\n\nlemma to_module_mult:\n  \"poly.coeff (of_qr (to_module s * a)) x1 = \n   of_int_mod_ring (s) * poly.coeff (of_qr a) x1\"\nusing of_qr_scale[of s a] by simp\n\ntext \\<open>Lemmas on \\<open>round\\<close> and \\<open>floor\\<close>.\\<close>\nlemma odd_round_up:\nassumes \"odd x\"\nshows \"round (real_of_int x / 2) = (x+1) div 2\"\nproof -\n  have \"round (real_of_int x / 2) = round (real_of_int (x+1) /2)\"\n    using assms unfolding round_def \n    by (metis (no_types, opaque_lifting) add.commute \n      add_divide_distrib even_add even_succ_div_2 \n      floor_divide_of_int_eq odd_one of_int_add \n      of_int_hom.hom_one of_int_numeral)\n  also have \"\\<dots> = (x+1) div 2\"\n    by (metis add_divide_distrib calculation \n    floor_divide_of_int_eq of_int_add of_int_hom.hom_one \n    of_int_numeral round_def)\n  finally show ?thesis by blast\nqed\n\nlemma floor_unique:\nassumes \"real_of_int a \\<le> x\" \"x < a+1\"\nshows \"floor x = a\"\n  using assms(1) assms(2) by linarith\n\nlemma same_floor:\nassumes \"real_of_int a \\<le> x\" \"real_of_int a \\<le> y\" \n  \"x < a+1\" \"y < a+1\"\nshows \"floor x = floor y\"\nusing assms floor_unique  by presburger\n\nlemma one_mod_four_round:\nassumes \"x mod 4 = 1\"\nshows \"round (real_of_int x / 4) = (x-1) div 4\"\nproof -\n  have leq: \"(x-1) div 4 \\<le> real_of_int x / 4  + 1 / 2\"\n    using assms by linarith \n  have gr: \"real_of_int x / 4  + 1 / 2 < (x-1) div 4 + 1\" \n  proof -\n    have \"x+2 < 4 * ((x-1) div 4 + 1)\" \n    proof -\n      have *:  \"(x-1) div 4 + 1 = (x+3) div 4\" by auto\n      have \"4 dvd x + 3\" using assms by presburger\n      then have \"4 * ((x+3) div 4) = x+3\" \n        by (subst dvd_imp_mult_div_cancel_left, auto)\n      then show ?thesis unfolding * by auto\n    qed\n    then show ?thesis by auto\n  qed\n  show \"round (real_of_int x / 4) = (x-1) div 4\"\n    using floor_unique[OF leq gr] unfolding round_def by auto\nqed\n\nlemma odd_half_floor:\nassumes \"odd x\"\nshows \"\\<lfloor>real_of_int x / 2\\<rfloor> = (x-1) div 2\"\nusing assms by (metis add.commute diff_add_cancel even_add \n even_succ_div_2 floor_divide_of_int_eq odd_one of_int_numeral)\n\n\nsection \\<open>Re-centered \"Norm\" Function\\<close>\n\ncontext module_spec\nbegin \ntext \\<open>We want to show that \\<open>abs_infty_q\\<close> is a function induced by the \n  Euclidean norm on the \\<open>mod_ring\\<close> using a re-centered representative via \\<open>mod+-\\<close>.\n\n  \\<open>abs_infty_poly\\<close> is the induced norm by \\<open>abs_infty_q\\<close> on polynomials over the polynomial \n  ring over the \\<open>mod_ring\\<close>. \n\n  Unfortunately this is not a norm per se, as the homogeneity only holds in \n  inequality, not equality. Still, it fulfils its purpose, since we only \n  need the triangular inequality.\\<close>\n\ndefinition abs_infty_q :: \"('a mod_ring) \\<Rightarrow> int\" where\n  \"abs_infty_q p = abs ((to_int_mod_ring p) mod+- q)\"\n\ndefinition abs_infty_poly :: \"'a qr \\<Rightarrow> int\" where\n  \"abs_infty_poly p = Max (range (abs_infty_q \\<circ> poly.coeff (of_qr p)))\"\n\ntext \\<open>Helping lemmas and properties of \\<open>Max\\<close>, \\<open>range\\<close> and \\<open>finite\\<close>.\\<close>\n\nlemma to_int_mod_ring_range: \n  \"range (to_int_mod_ring :: 'a mod_ring \\<Rightarrow> int) = {0 ..< q}\"\nusing CARD_a by (simp add: range_to_int_mod_ring)\n\nlemma finite_Max:\n  \"finite (range (\\<lambda>xa. abs_infty_q (poly.coeff (of_qr x) xa)))\"\nproof -\n  have finite_range: \"finite (range (\\<lambda>xa. (poly.coeff (of_qr x) xa)))\" \n  using MOST_coeff_eq_0[of \"of_qr x\"] by auto\n  have \"range (\\<lambda>xa. \\<bar>to_int_mod_ring (poly.coeff (of_qr x) xa) mod+- q\\<bar>)\n    = (\\<lambda>z. \\<bar>to_int_mod_ring z mod+- q\\<bar>) ` range (poly.coeff (of_qr x))\"\n  using range_composition[of \"(\\<lambda>z. abs (to_int_mod_ring z mod+- q))\" \n    \"poly.coeff (of_qr x)\"] by auto\n  then show ?thesis \n    using finite_range finite_image_set[where \n      f = \"(\\<lambda>z. abs (to_int_mod_ring z) mod+- q)\"] \n    by (auto simp add: abs_infty_q_def)\nqed\n\nlemma finite_Max_scale:\n  \"finite (range (\\<lambda>xa. abs_infty_q (of_int_mod_ring s *\n    poly.coeff (of_qr x) xa)))\"\nproof -\n  have \"of_int_mod_ring s * poly.coeff (of_qr x) xa = \n    poly.coeff (of_qr (to_module s * x)) xa\" for xa\n  by (metis coeff_smult of_qr_to_qr_smult to_qr_of_qr \n    to_qr_smult_to_module to_module_def)\n  then show ?thesis\n  using finite_Max by presburger\nqed\n\nlemma finite_Max_sum: \n  \"finite (range (\\<lambda>xa. abs_infty_q \n    (poly.coeff (of_qr x) xa + poly.coeff (of_qr y) xa)))\"\nproof -\n  have finite_range: \"finite (range (\\<lambda>xa. (poly.coeff (of_qr x) xa + \n    poly.coeff (of_qr y) xa)))\" \n  using MOST_coeff_eq_0[of \"of_qr x\"] by auto\n  have \"range (\\<lambda>xa. \\<bar>to_int_mod_ring (poly.coeff (of_qr x) xa + \n    poly.coeff (of_qr y) xa) mod+- q\\<bar>) = \n    (\\<lambda>z. \\<bar>to_int_mod_ring z mod+- q\\<bar>) ` \n    range (\\<lambda>xa. poly.coeff (of_qr x) xa + poly.coeff (of_qr y) xa)\"\n  using range_composition[of \"(\\<lambda>z. abs (to_int_mod_ring z mod+- q))\" \n    \"(\\<lambda>xa. poly.coeff (of_qr x) xa + poly.coeff (of_qr y) xa)\"] \n  by auto\n  then show ?thesis \n    using finite_range finite_image_set[where \n      f = \"(\\<lambda>z. abs (to_int_mod_ring z) mod+- q)\" ] \n    by (auto simp add: abs_infty_q_def)\nqed\n\n\nlemma finite_Max_sum':\n  \"finite (range\n     (\\<lambda>xa. abs_infty_q (poly.coeff (of_qr x) xa) + \n      abs_infty_q (poly.coeff (of_qr y) xa)))\"\nproof -\n  have finite_range_x: \n    \"finite (range (\\<lambda>xa. abs_infty_q (poly.coeff (of_qr x) xa)))\" \n    using finite_Max[of x] by auto\n  have finite_range_y: \n    \"finite (range (\\<lambda>xa. abs_infty_q (poly.coeff (of_qr y) xa)))\" \n    using finite_Max[of y] by auto\n  show ?thesis \n    using finite_range_plus[OF finite_range_x finite_range_y] by auto\nqed\n\n\n\n\nlemma Max_scale:\n\"(MAX xa. \\<bar>s\\<bar> * abs_infty_q (poly.coeff (of_qr x) xa)) =\n    \\<bar>s\\<bar> * (MAX xa. abs_infty_q (poly.coeff (of_qr x) xa))\"\nproof -\n  have \"(MAX xa. \\<bar>s\\<bar> * abs_infty_q (poly.coeff (of_qr x) xa)) =\n    (Max (range (\\<lambda>xa. \\<bar>s\\<bar> * abs_infty_q (poly.coeff (of_qr x) xa))))\"\n    by auto\n  moreover have \"\\<dots> = (Max ((\\<lambda>a. \\<bar>s\\<bar> * a) `\n    (range (\\<lambda>xa. abs_infty_q (poly.coeff (of_qr x) xa)))))\"\n    by (metis range_composition)\n  moreover have \"\\<dots> = \\<bar>s\\<bar> * (Max (range \n    (\\<lambda>xa. abs_infty_q (poly.coeff (of_qr x) xa))))\"\n    by (subst mono_Max_commute[symmetric])\n       (auto simp add: finite_Max Rings.mono_mult)\n  moreover have \"\\<dots> =  \\<bar>s\\<bar> * \n    (MAX xa. abs_infty_q (poly.coeff (of_qr x) xa))\"\n    by auto\n  ultimately show ?thesis by auto\nqed\n\n\n\ntext \\<open>Show that \\<open>abs_infty_q\\<close> is definite, positive and fulfils the triangle inequality.\\<close>\n\nlemma abs_infty_q_definite:\n  \"abs_infty_q x = 0 \\<longleftrightarrow> x = 0\"\nproof (auto simp add: abs_infty_q_def \n  mod_plus_minus_zero'[OF q_gt_zero q_odd])\n  assume \"to_int_mod_ring x mod+- q = 0\"\n  then have \"to_int_mod_ring x mod q = 0\" \n    using mod_plus_minus_zero[of \"to_int_mod_ring x\" q] \n    by auto\n  then have \"to_int_mod_ring x = 0\" \n    using to_int_mod_ring_range CARD_a\n    by (metis mod_rangeE range_eqI)\n  then show \"x = 0\" by force\nqed\n\nlemma abs_infty_q_pos:\n  \"abs_infty_q x \\<ge> 0\"\nby (auto simp add: abs_infty_q_def) \n\n\nlemma abs_infty_q_minus:\n  \"abs_infty_q (- x) = abs_infty_q x\"\nproof (cases \"x=0\")\ncase True\n  then show ?thesis by auto\nnext\ncase False\n  have minus_x: \"to_int_mod_ring (-x) = q - to_int_mod_ring x\"\n  proof -\n    have \"to_int_mod_ring (-x) = to_int_mod_ring (-x) mod q\"\n      by (metis CARD_a Rep_mod_ring_mod to_int_mod_ring.rep_eq)\n    also have \"\\<dots> = (- to_int_mod_ring x) mod q\" \n      by (metis (no_types, opaque_lifting) CARD_a diff_eq_eq \n        mod_add_right_eq plus_mod_ring.rep_eq to_int_mod_ring.rep_eq \n        uminus_add_conv_diff)\n    also have \"\\<dots> = q - to_int_mod_ring x\" \n    proof -\n      have \"- to_int_mod_ring x \\<in> {-q<..<0}\"\n      using CARD_a range_to_int_mod_ring False \n        by (smt (verit, best) Rep_mod_ring_mod greaterThanLessThan_iff \n          q_gt_zero to_int_mod_ring.rep_eq to_int_mod_ring_hom.eq_iff \n          to_int_mod_ring_hom.hom_zero zmod_trivial_iff)\n      then have \"q-to_int_mod_ring x\\<in>{0<..<q}\" by auto\n      then show ?thesis \n        using minus_mod_self1 mod_rangeE\n        by (simp add: to_int_mod_ring.rep_eq zmod_zminus1_eq_if)\n    qed\n    finally show ?thesis by auto\n  qed\n  then have \"\\<bar>to_int_mod_ring (- x) mod+- q\\<bar> = \n    \\<bar>(q - (to_int_mod_ring x)) mod+- q\\<bar>\" \n    by auto\n  also have \"\\<dots> = \\<bar> (- to_int_mod_ring x) mod+- q\\<bar>\" \n    unfolding mod_plus_minus_def by (smt (z3) mod_add_self2)\n  also have \"\\<dots> = \\<bar> - (to_int_mod_ring x mod+- q)\\<bar>\" \n    using neg_mod_plus_minus[OF q_odd q_gt_zero, \n      of \"to_int_mod_ring x\"] by simp\n  also have \"\\<dots> = \\<bar>to_int_mod_ring x mod+- q\\<bar>\" by auto\n  finally show ?thesis unfolding abs_infty_q_def by auto\nqed\n\n\n\nlemma to_int_mod_ring_mult:\n  \"to_int_mod_ring (a*b) =  to_int_mod_ring (a::'a mod_ring) * \n    to_int_mod_ring (b::'a mod_ring) mod q\"\nby (metis (no_types, lifting) CARD_a of_int_hom.hom_mult \n  of_int_mod_ring.rep_eq of_int_mod_ring_to_int_mod_ring \n  of_int_of_int_mod_ring to_int_mod_ring.rep_eq)\n\n\n\ntext \\<open>Scaling only with inequality not equality! This causes a problem in proof of the \n  Kyber scheme. Needed to add $q\\equiv 1 \\mod 4$ to change proof.\\<close>\nlemma mod_plus_minus_leq_mod: \n  \"\\<bar>x mod+- q\\<bar> \\<le> \\<bar>x\\<bar>\"\nby (smt (verit, best) atLeastAtMost_iff mod_plus_minus_range_odd\n  mod_plus_minus_rangeE q_gt_zero q_odd)\n\nlemma abs_infty_q_scale_pos:\n  assumes \"s\\<ge>0\"\n  shows \"abs_infty_q ((of_int_mod_ring s :: 'a mod_ring) * x) \\<le> \n    \\<bar>s\\<bar> * (abs_infty_q x)\"\nproof -\n  have \"\\<bar>to_int_mod_ring (of_int_mod_ring s * x) mod+- q\\<bar> = \n        \\<bar>(to_int_mod_ring (of_int_mod_ring s ::'a mod_ring) * \n          to_int_mod_ring x mod q) mod+- q\\<bar>\"\n    using to_int_mod_ring_mult[of \"of_int_mod_ring s\" x] by simp\n  also have \"\\<dots> = \\<bar>(s mod q * to_int_mod_ring x) mod+- q\\<bar>\"\n  by (simp add: CARD_a mod_plus_minus_def of_int_mod_ring.rep_eq to_int_mod_ring.rep_eq)\n  also have \"\\<dots> \\<le> \\<bar>s mod q\\<bar> * \\<bar>to_int_mod_ring x mod+- q\\<bar>\" \n  proof -\n    have \"\\<bar>s mod q * to_int_mod_ring x mod+- q\\<bar> = \n          \\<bar>(s mod q mod+- q) * (to_int_mod_ring x mod+- q) mod+- q\\<bar>\"\n      using mod_plus_minus_mult by auto\n    also have \"\\<dots> \\<le> \\<bar>(s mod q mod+- q) * (to_int_mod_ring x mod+- q)\\<bar>\" \n      using mod_plus_minus_leq_mod by blast\n    also have \"\\<dots> \\<le> \\<bar>s mod q mod+- q\\<bar> * \\<bar>(to_int_mod_ring x mod+- q)\\<bar>\" \n      by (simp add: abs_mult)\n    also have \"\\<dots> \\<le> \\<bar>s mod q\\<bar> * \\<bar>(to_int_mod_ring x mod+- q)\\<bar>\"\n      using mod_plus_minus_leq_mod[of \"s mod q\"] \n      by (simp add: mult_right_mono)\n    finally show ?thesis by auto\n  qed \n  also have \"\\<dots> \\<le> \\<bar>s\\<bar> * \\<bar>to_int_mod_ring x mod+- q\\<bar>\" using assms\n    by (simp add: mult_mono' q_gt_zero zmod_le_nonneg_dividend)\n  finally show ?thesis unfolding abs_infty_q_def by auto\nqed\n\nlemma abs_infty_q_scale_neg:\n  assumes \"s<0\"\n  shows \"abs_infty_q ((of_int_mod_ring s :: 'a mod_ring) * x) \\<le> \n    \\<bar>s\\<bar> * (abs_infty_q x)\"\nusing abs_infty_q_minus abs_infty_q_scale_pos \nby (smt (verit, best) mult_minus_left of_int_minus of_int_of_int_mod_ring)\n\nlemma abs_infty_q_scale:\n  \"abs_infty_q ((of_int_mod_ring s :: 'a mod_ring) * x) \\<le> \n    \\<bar>s\\<bar> * (abs_infty_q x)\"\napply (cases \"s\\<ge>0\") \nusing abs_infty_q_scale_pos apply presburger \nusing abs_infty_q_scale_neg by force\n\n\ntext \\<open>Triangle inequality for \\<open>abs_infty_q\\<close>.\\<close>\n\nlemma abs_infty_q_triangle_ineq:\n  \"abs_infty_q (x+y) \\<le> abs_infty_q x + abs_infty_q y\"\nproof -\n  have \"to_int_mod_ring (x + y) mod+- q = \n        (to_int_mod_ring x + to_int_mod_ring y) mod q mod+-q\"\n    by (simp add: to_int_mod_ring_def CARD_a plus_mod_ring.rep_eq)\n  also have \"\\<dots> = (to_int_mod_ring x + to_int_mod_ring y) mod+-q\"\n    unfolding mod_plus_minus_def by auto\n  also have \"\\<dots> = (to_int_mod_ring x mod+- q + \n    to_int_mod_ring y mod+- q) mod+- q\"\n    unfolding mod_plus_minus_def \n    by (smt (verit, ccfv_threshold) minus_mod_self2 mod_add_eq)\n  finally have rewrite:\"to_int_mod_ring (x + y) mod+- q = \n    (to_int_mod_ring x mod+- q + to_int_mod_ring y mod+- q) mod+- q\" .\n  then have \"\\<bar>to_int_mod_ring (x + y) mod+- q\\<bar>\n    \\<le> \\<bar>to_int_mod_ring x mod+- q\\<bar> + \\<bar>to_int_mod_ring y mod+- q\\<bar>\"\n    proof (cases \n    \"(to_int_mod_ring x mod+- q + to_int_mod_ring y mod+- q) \\<in> \n       {-\\<lfloor>real_of_int q/2\\<rfloor>..<\\<lfloor>real_of_int q/2\\<rfloor>}\")\n    case True\n      then have True': \"to_int_mod_ring x mod+- q + to_int_mod_ring y mod+- q\n        \\<in> {- \\<lfloor>real_of_int q / 2\\<rfloor>..\\<lfloor>real_of_int q / 2\\<rfloor>}\" by auto\n      then have \"(to_int_mod_ring x mod+- q + \n        to_int_mod_ring y mod+- q) mod+- q\n       = to_int_mod_ring x mod+- q + to_int_mod_ring y mod+- q\" \n        using mod_plus_minus_rangeE[OF True' q_odd q_gt_zero] by auto \n      then show ?thesis by (simp add: rewrite)\n    next\n    case False\n      then have \"\\<bar>(to_int_mod_ring x mod+- q + \n        to_int_mod_ring y mod+- q)\\<bar> \\<ge> \\<lfloor>real_of_int q /2\\<rfloor>\" \n        by auto\n      then have \"\\<bar>(to_int_mod_ring x mod+- q + \n        to_int_mod_ring y mod+- q)\\<bar> \\<ge> \\<bar>(to_int_mod_ring x mod+- q +\n        to_int_mod_ring y mod+- q) mod+- q\\<bar>\"\n      using mod_plus_minus_range_odd[OF q_gt_zero q_odd, \n        of \"(to_int_mod_ring x mod+- q + to_int_mod_ring y mod+- q)\"]\n      by auto\n      then show ?thesis by (simp add: rewrite)\n    qed\n  then show ?thesis \n    by (auto simp add: abs_infty_q_def mod_plus_minus_def)\nqed\n\ntext \\<open>Show that \\<open>abs_infty_poly\\<close> is definite, positive and fulfils the triangle inequality.\\<close>\n\nlemma abs_infty_poly_definite:\n  \"abs_infty_poly x = 0 \\<longleftrightarrow> x = 0\"\nproof (auto simp add: abs_infty_poly_def abs_infty_q_definite)\n  assume \"(MAX xa. abs_infty_q (poly.coeff (of_qr x) xa)) = 0\"\n  then have abs_le_zero: \"abs_infty_q (poly.coeff (of_qr x) xa) \\<le> 0\"\n    for xa\n    using Max_ge[OF finite_Max[of x], \n      of \"abs_infty_q (poly.coeff (of_qr x) xa)\"]\n    by (auto simp add: Max_ge[OF finite_Max])\n  have \"abs_infty_q (poly.coeff (of_qr x) xa) = 0\" for xa \n    using abs_infty_q_pos[of \"poly.coeff (of_qr x) xa\"] \n    abs_le_zero[of xa] by auto\n  then have \"poly.coeff (of_qr x) xa = 0\" for xa\n    by (auto simp add: abs_infty_q_definite)\n  then show \"x = 0\" \n    using leading_coeff_0_iff of_qr_eq_0_iff by blast\nqed\n\n\nlemma abs_infty_poly_pos:\n  \"abs_infty_poly x \\<ge> 0\"\nproof (auto simp add: abs_infty_poly_def)\n  have f_ge_zero: \"\\<forall>xa. abs_infty_q (poly.coeff (of_qr x) xa) \\<ge> 0\"\n    by (auto simp add: abs_infty_q_pos)\n  then show \" 0 \\<le> (MAX xa. abs_infty_q (poly.coeff (of_qr x) xa))\"\n    using all_impl_Max[OF f_ge_zero finite_Max] by auto\nqed\n\n\ntext \\<open>Again, homogeneity is only true for inequality not necessarily equality! \n  Need to add $q\\equiv 1\\mod 4$ such that proof of crypto scheme works out.\\<close>\nlemma abs_infty_poly_scale:\n  \"abs_infty_poly ((to_module s) * x) \\<le> (abs s) * (abs_infty_poly x)\"\nproof -\n  have fin1: \"finite (range (\\<lambda>xa. abs_infty_q (of_int_mod_ring s *\n    poly.coeff (of_qr x) xa)))\"\n    using finite_Max_scale by auto\n  have fin2: \"finite (range (\\<lambda>xa. \\<bar>s\\<bar> *\n     abs_infty_q (poly.coeff (of_qr x) xa)))\"\n    by (metis finite_Max finite_imageI range_composition)\n  have \"abs_infty_poly (to_module s * x) = \n        (MAX xa. abs_infty_q\n         ((of_int_mod_ring s) * poly.coeff (of_qr x) xa))\"\n  using abs_infty_poly_def to_module_mult\n    by (metis (mono_tags, lifting) comp_apply image_cong)   \n  also have \"\\<dots> \\<le> (MAX xa. \\<bar>s\\<bar> * abs_infty_q (poly.coeff (of_qr x) xa))\"\n    using abs_infty_q_scale fin1 fin2 by (subst Max_mono', auto)\n  also have \"\\<dots> = \\<bar>s\\<bar> * abs_infty_poly x\"\n    unfolding abs_infty_poly_def comp_def using Max_scale by auto\n  finally show ?thesis by blast\nqed\n\n\ntext \\<open>Triangle inequality for \\<open>abs_infty_poly\\<close>.\\<close>\nlemma abs_infty_poly_triangle_ineq:\n  \"abs_infty_poly (x+y) \\<le> abs_infty_poly x + abs_infty_poly y\"\nproof -\n  have \"abs_infty_q (poly.coeff (of_qr x) xa + \n    poly.coeff (of_qr y) xa) \\<le> \n    abs_infty_q (poly.coeff (of_qr x) xa) + \n    abs_infty_q (poly.coeff (of_qr y) xa)\"\n    for xa\n    using abs_infty_q_triangle_ineq[of \n      \"poly.coeff (of_qr x) xa\" \"poly.coeff (of_qr y) xa\"]\n    by auto\n  then have abs_q_triang: \"\\<forall>xa. \n    abs_infty_q (poly.coeff (of_qr x) xa + poly.coeff (of_qr y) xa) \\<le>\n    abs_infty_q (poly.coeff (of_qr x) xa) + \n    abs_infty_q (poly.coeff (of_qr y) xa)\"\n    by auto\n  have \"(MAX xa. abs_infty_q (poly.coeff (of_qr x) xa + \n      poly.coeff (of_qr y) xa))\n    \\<le> (MAX xa. abs_infty_q (poly.coeff (of_qr x) xa) + \n      abs_infty_q (poly.coeff (of_qr y) xa))\"\n    using Max_mono'[OF abs_q_triang finite_Max_sum finite_Max_sum'] \n    by auto\n  also have \"\\<dots> \\<le> (MAX xa. abs_infty_q (poly.coeff (of_qr x) xa)) +\n       (MAX xb. abs_infty_q (poly.coeff (of_qr y) xb))\" \n    using Max_mono_plus[OF finite_Max[of x] finite_Max[of y]] \n    by auto\n  finally have \"(MAX xa. abs_infty_q (poly.coeff (of_qr x) xa + \n      poly.coeff (of_qr y) xa))\n    \\<le> (MAX xa. abs_infty_q (poly.coeff (of_qr x) xa)) +\n       (MAX xb. abs_infty_q (poly.coeff (of_qr y) xb))\"\n    by auto\n  then show ?thesis \n    by (auto simp add: abs_infty_poly_def)\nqed\n\nend\n\ntext \\<open>Estimation inequality using message bit.\\<close>\n\nlemma(in kyber_spec) abs_infty_poly_ineq_pm_1:\nassumes \"\\<exists>x. poly.coeff (of_qr a) x \\<in> {of_int_mod_ring (-1),1}\"\nshows \"abs_infty_poly (to_module (round((real_of_int q)/2)) * a) \\<ge> \n              2 * round (real_of_int q / 4)\"\nproof -\n  let ?x = \"to_module (round((real_of_int q)/2)) * a\"\n  obtain x1 where x1_def: \n    \"poly.coeff (of_qr a) x1 \\<in> {of_int_mod_ring(-1),1}\" \n    using assms by auto\n  have \"abs_infty_poly (to_module (round((real_of_int q)/2)) * a)\n    \\<ge> abs_infty_q (poly.coeff (of_qr (to_module \n      (round (real_of_int q / 2)) * a)) x1)\" \n    unfolding abs_infty_poly_def using x1_def \n    by (simp add: finite_Max)\n  also have \"abs_infty_q (poly.coeff (of_qr (to_module \n    (round (real_of_int q / 2)) * a)) x1)\n  = abs_infty_q (of_int_mod_ring (round (real_of_int q / 2))\n    * (poly.coeff (of_qr a) x1))\" \n    using to_module_mult[of \"round (real_of_int q / 2)\" a] \n    by simp\n  also have \"\\<dots> = abs_infty_q (of_int_mod_ring \n    (round (real_of_int q / 2)))\" \n  proof -\n    consider \"poly.coeff (of_qr a) x1=1\" | \n      \"poly.coeff (of_qr a) x1 = of_int_mod_ring (-1)\" \n      using x1_def by auto\n    then show ?thesis \n    proof (cases)\n      case 2\n      then show ?thesis\n      by (metis abs_infty_q_minus mult.right_neutral mult_minus_right\n          of_int_hom.hom_one of_int_minus of_int_of_int_mod_ring)\n    qed (auto)\n  qed\n  also have \"\\<dots> = \\<bar>round (real_of_int q / 2) mod+- q\\<bar>\" \n    unfolding abs_infty_q_def \n    using to_int_mod_ring_of_int_mod_ring \n    by (simp add: CARD_a mod_add_left_eq mod_plus_minus_def \n      of_int_mod_ring.rep_eq to_int_mod_ring.rep_eq)\n  also have \"\\<dots> = \\<bar>((q + 1) div 2) mod+- q\\<bar>\" \n    using odd_round_up[OF q_odd] by auto \n  also have \"\\<dots> = \\<bar>((2 * q) div 2) mod q - (q - 1) div 2\\<bar>\" \n  proof -\n    have \"(q + 1) div 2 mod q = (q + 1) div 2\" using q_gt_two by auto\n    moreover have \"(q + 1) div 2 - q = - ((q - 1) div 2)\" by (simp add: q_odd)\n    ultimately show ?thesis\n    unfolding mod_plus_minus_def odd_half_floor[OF q_odd] \n    by (split if_splits) simp\n  qed\n  also have \"\\<dots> = \\<bar>(q-1) div 2\\<bar>\" using q_odd \n    by (subst nonzero_mult_div_cancel_left[of 2 q], simp) \n       (simp add: abs_div abs_minus_commute)\n  also have \"\\<dots> = 2 * ((q-1) div 4)\" \n  proof -\n    from q_gt_two have \"(q-1) div 2 > 0\" by simp\n    then have \"\\<bar>(q-1) div 2\\<bar> = (q-1) div 2\" by auto\n    also have \"\\<dots> = 2 * ((q-1) div 4)\" \n      by (subst div_mult_swap) (use q_mod_4 in \n      \\<open>metis dvd_minus_mod\\<close>, force)\n    finally show ?thesis by blast\n  qed\n  also have \"\\<dots> = 2 * round (real_of_int q / 4)\" \n    unfolding odd_round_up[OF q_odd] one_mod_four_round[OF q_mod_4] \n    by (simp add: round_def)\n  finally show ?thesis unfolding abs_infty_poly_def by simp\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/CRYSTALS-Kyber/Abs_Qr.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8902942319436397, "lm_q2_score": 0.8175744695262777, "lm_q1q2_score": 0.727881834403626}}
{"text": "(*\n  File:     Carmichael_Numbers.thy\n  Authors:  Daniel St\u00fcwe\n\n  Definition and basic properties of Carmichael numbers\n*)\nsection \\<open>Carmichael Numbers\\<close>\ntheory Carmichael_Numbers\nimports\n  Residues_Nat\nbegin\n\ntext \\<open>\n  A Carmichael number is a composite number \\<open>n\\<close> that Fermat's test incorrectly labels\n  as primes no matter which witness \\<open>a\\<close> is chosen (except in the case that \\<open>a\\<close> shares a\n  factor with \\<open>n\\<close>). \\<^cite>\\<open>\"Carmichael_numbers\" and \"wiki:Carmichael_number\"\\<close>\n\\<close>\ndefinition Carmichael_number :: \"nat \\<Rightarrow> bool\" where\n  \"Carmichael_number n \\<longleftrightarrow> n > 1 \\<and> \\<not>prime n \\<and> (\\<forall>a. coprime a n \\<longrightarrow> [a ^ (n - 1) = 1] (mod n))\"\n\nlemma Carmichael_number_0[simp, intro]: \"\\<not>Carmichael_number 0\"\n  unfolding Carmichael_number_def by simp\n\nlemma Carmichael_number_1[simp, intro]: \"\\<not>Carmichael_number 1\"\n  by (auto simp: Carmichael_number_def)\n\nlemma Carmichael_number_Suc_0[simp, intro]: \"\\<not>Carmichael_number (Suc 0)\"\n  by (auto simp: Carmichael_number_def)\n\nlemma Carmichael_number_not_prime: \"Carmichael_number n \\<Longrightarrow> \\<not>prime n\"\n  by (auto simp: Carmichael_number_def)\n\nlemma Carmichael_number_gt_3: \"Carmichael_number n \\<Longrightarrow> n > 3\"\nproof -\n  assume *: \"Carmichael_number n\"\n  hence \"n > 1\" by (auto simp: Carmichael_number_def)\n  {\n    assume \"\\<not>(n > 3)\"\n    with \\<open>n > 1\\<close> have \"n = 2 \\<or> n = 3\" by auto\n    with * and Carmichael_number_not_prime[of n] have False by auto\n  }\n  thus \"n > 3\" by auto\nqed\n\ntext \\<open>\n  The proofs are inspired by \\<^cite>\\<open>\"Carmichael_numbers\" and \"Carmichael_number_square_free\"\\<close>.\n\\<close>\nlemma Carmichael_number_imp_squarefree_aux:\n  assumes \"Carmichael_number n\"\n  assumes n: \"n = p^r * l\" and \"prime p\" \"\\<not>p dvd l\"\n  assumes \"r > 1\"\n  shows False\nproof -\n  have \"\\<not> prime n\" using \\<open>Carmichael_number n\\<close> unfolding Carmichael_number_def by blast\n\n  have * : \"[a^(n-1) = 1] (mod n)\" if \"coprime a n\" for a\n    using \\<open>Carmichael_number n\\<close> that\n    unfolding Carmichael_number_def\n    by blast\n\n  have \"1 \\<le> n\"\n    unfolding n using \\<open>prime p\\<close> \\<open>\\<not> p dvd l\\<close>\n    by (auto intro: gre1I_nat)\n\n  have \"2 \\<le> n\"\n  proof(cases \"n = 1\")\n    case True\n    then show ?thesis\n      unfolding n using \\<open>1 < r\\<close> prime_gt_1_nat[OF \\<open>prime p\\<close>]\n      by simp\n  next\n    case False\n    then show ?thesis using \\<open>1 \\<le> n\\<close> by linarith\n  qed\n\n  have \"p < p^r\"\n    using prime_gt_1_nat[OF \\<open>prime p\\<close>] \\<open>1 < r\\<close>\n    by (metis power_one_right power_strict_increasing_iff)\n\n  hence \"p < n\" using \\<open>1 \\<le> n\\<close> less_le_trans n by fastforce \n\n  then have [simp]: \"{..n} - {0..Suc 0} = {2..n}\" by auto\n\n  obtain a where a: \"[a = p + 1] (mod p^r)\" \"[a = 1] (mod l)\"\n    using binary_chinese_remainder_nat[of \"p^r\" l \"p + 1\" 1] \n    and \\<open>prime p\\<close> prime_imp_coprime_nat coprime_power_left_iff \\<open>\\<not>p dvd l\\<close>\n    by blast\n\n  hence \"coprime a n\"\n    using lucas_coprime_lemma[of 1 a l] cong_imp_coprime[of \"p+1\" a \"p^r\"] \n      and coprime_add_one_left cong_sym \n    unfolding \\<open>n = p ^ r * l\\<close> coprime_mult_right_iff coprime_power_right_iff power_one_right\n    by blast\n\n  hence \"[a ^ (n - 1) = 1] (mod n)\"\n    using * by blast\n\n  hence \"[a ^ (n - 1) = 1] (mod p^r)\"\n    using n cong_modulus_mult_nat by blast\n\n  hence A: \"[a ^ n = a] (mod p^r)\"\n    using cong_scalar_right[of \"a^(n-1)\" 1 \"p^r\" a] \\<open>1 \\<le> n\\<close>\n    unfolding power_Suc2[symmetric]\n    by simp\n\n  have \"r = Suc (Suc (r - 2))\"\n    using \\<open>1 < r\\<close> by linarith\n\n  then have \"p^r = p^2 * p^(r-2)\"\n    by (simp add: algebra_simps flip: power_add power_Suc)\n   \n  hence \"[a ^ n = a] (mod p^2)\" \"[a = p + 1] (mod p^2)\"\n    using \\<open>1 < r\\<close> A cong_modulus_mult_nat \\<open>[a = p + 1] (mod p^r)\\<close>\n    by algebra+\n\n  hence 1: \"[(p + 1) ^ n = (p + 1)] (mod p^2)\"\n    by (metis (mono_tags) cong_def power_mod)\n\n  have \"[(p + 1) ^ n = (\\<Sum>k\\<le>n. of_nat (n choose k) * p ^ k * 1 ^ (n - k))] (mod p^2)\"\n    using binomial[of p 1 n] by simp\n\n  also have \"(\\<Sum>k\\<le>n. of_nat (n choose k) * p ^ k * 1 ^ (n - k)) =\n             (\\<Sum>k = 0..1. (n choose k) * p ^ k) + (\\<Sum>k\\<in> {2..n}. of_nat (n choose k) * p ^ k * 1 ^ (n - k))\"\n    using \\<open>2 \\<le> n\\<close> finite_atMost[of n]\n    by (subst sum.subset_diff[where B = \"{0..1}\"]) auto\n\n  also have \"[(\\<Sum>k = 0..1. (n choose k) * p ^ k) = 1] (mod p^2)\"\n    by (simp add: cong_altdef_nat \\<open>p ^ r = p\\<^sup>2 * p ^ (r - 2)\\<close> n)\n\n  also have \"[(\\<Sum>k\\<in> {2..n}. of_nat (n choose k) * p ^ k * 1 ^ (n - k)) = 0] (mod p^2)\"\n    by (rule cong_eq_0_I) (clarsimp simp: cong_0_iff le_imp_power_dvd)\n\n  finally have 2: \"[(p + 1) ^ n = 1] (mod p^2)\" by simp\n\n  from cong_trans[OF cong_sym[OF 1] 2] \n  show ?thesis\n    using prime_gt_1_nat[OF \\<open>prime p\\<close>]\n    by (auto dest: residue_one_dvd[unfolded One_nat_def] simp add: cong_def numeral_2_eq_2)\nqed\n\ntheorem Carmichael_number_imp_squarefree:\n  assumes \"Carmichael_number n\"\n  shows \"squarefree n\"\nproof(rule squarefreeI, rule ccontr)\n  fix x :: nat\n  assume \"x\\<^sup>2 dvd n\"\n  from assms have \"n > 0\" using Carmichael_number_gt_3[of n] by auto\n  from \\<open>x\\<^sup>2 dvd n\\<close> and \\<open>0 < n\\<close> have \"0 < x\" by auto\n\n  assume \"\\<not> is_unit x\"\n  then obtain p where \"prime p\" \"p dvd x\"\n    using prime_divisor_exists[of x] \\<open>0 < x\\<close>\n    by blast\n\n  with \\<open>x\\<^sup>2 dvd n\\<close> have \"p^2 dvd n\"\n    by auto\n\n  obtain l where n: \"n = p ^ multiplicity p n * l\"\n    using multiplicity_dvd[of p n] by blast\n\n  then have \"\\<not> p dvd l\"\n    using multiplicity_decompose'[where x = n and p = p]\n    using \\<open>prime p\\<close> \\<open>0 < n\\<close>\n    by (metis nat_dvd_1_iff_1 nat_mult_eq_cancel1 neq0_conv prime_prime_factor_sqrt zero_less_power)\n\n  have \"2 \\<le> multiplicity p n\"\n    using \\<open>p\\<^sup>2 dvd n\\<close> \\<open>0 < n\\<close> prime_gt_1_nat[OF \\<open>prime p\\<close>]\n    by (auto intro!: multiplicity_geI simp: power2_eq_square)\n    \n  then show False \n    using Carmichael_number_imp_squarefree_aux[OF \\<open>Carmichael_number n\\<close> n] \\<open>prime p\\<close> \\<open>\\<not> p dvd l\\<close>\n    by auto\nqed\n\ncorollary Carmichael_not_primepow:\n  assumes \"Carmichael_number n\"\n  shows   \"\\<not>primepow n\"\n  using Carmichael_number_imp_squarefree[of n] Carmichael_number_not_prime[of n] assms\n        primepow_gt_0_nat[of n] by (auto simp: not_squarefree_primepow)\n\nlemma Carmichael_number_imp_squarefree_alt_weak:\n  assumes \"Carmichael_number n\"\n  shows \"\\<exists>p l. (n = p * l) \\<and> prime p \\<and> \\<not>p dvd l\"\nproof -\n  from assms have \"n > 1\"\n    using Carmichael_number_gt_3[of n] by simp\n  have \"squarefree n\"\n    using Carmichael_number_imp_squarefree assms \n    by blast\n\n  obtain p l where \"p * l = n\" \"prime p\" \"1 < p\"\n    using assms prime_divisor_exists_strong_nat prime_gt_1_nat\n    unfolding Carmichael_number_def by blast\n\n  then have \"multiplicity p n = 1\"\n    using \\<open>1 < n\\<close> \\<open>squarefree n\\<close> and multiplicity_eq_zero_iff[of n p] squarefree_factorial_semiring''[of n]\n    by auto\n\n  then have \"\\<not>p dvd l\"\n    using \\<open>1 < n\\<close> \\<open>prime p\\<close> \\<open>p * l = n\\<close> multiplicity_decompose'[of n p]\n    by force\n\n  show ?thesis \n    using \\<open>p * l = n\\<close> \\<open>prime p\\<close> \\<open>\\<not>p dvd l\\<close>\n    by blast\nqed\n\ntheorem Carmichael_number_odd:\n  assumes \"Carmichael_number n\"\n  shows   \"odd n\"\nproof (rule ccontr)\n  assume \"\\<not> odd n\"\n  hence \"even n\" by simp\n  from assms have \"n \\<ge> 4\" using Carmichael_number_gt_3[of n] by simp\n  have \"[(n - 1) ^ (n - 1) = n - 1] (mod n)\"\n    using \\<open>even n\\<close> and \\<open>n \\<ge> 4\\<close> by (intro odd_pow_cong) auto\n\n  then have \"[(n - 1) ^ (n - 1) \\<noteq> 1] (mod n)\"\n    using cong_trans[of 1 \"(n - 1) ^ (n - 1)\" n \"n-1\", OF cong_sym] \\<open>4 \\<le> n\\<close>\n    by (auto simp: cong_def)\n\n  moreover have \"coprime (n - 1) n\"\n    using \\<open>n \\<ge> 4\\<close> coprime_diff_one_left_nat[of n] by auto\n\n  ultimately show False\n    using assms unfolding Carmichael_number_def by blast\nqed\n\nlemma Carmichael_number_imp_squarefree_alt:\n  assumes \"Carmichael_number n\"\n  shows \"\\<exists>p l. (n = p * l) \\<and> prime p \\<and> \\<not>p dvd l \\<and> 2 < l\"\nproof -\n  obtain p l where [simp]: \"(n = p * l)\" and \"prime p\" \"\\<not>p dvd l\"\n    using Carmichael_number_imp_squarefree_alt_weak and assms by blast\n\n  moreover have \"odd n\" using Carmichael_number_odd and assms by blast\n\n  consider \"l = 0 \\<or> l = 2\" | \"l = 1\" | \"2 < l\"\n    by fastforce\n\n  then have \"2 < l\" \n  proof cases\n    case 1\n    then show ?thesis\n      using \\<open>odd n\\<close> by auto\n  next\n    case 2\n    then show ?thesis\n      using \\<open>n = p * l\\<close> \\<open>prime p\\<close> \\<open>Carmichael_number n\\<close>\n      unfolding Carmichael_number_def by simp\n  qed simp\n\n  ultimately show ?thesis by blast\nqed\n\nlemma Carmichael_number_imp_dvd:\n  fixes n :: nat\n  assumes Carmichael_number: \"Carmichael_number n\" and \"prime p\" \"p dvd n\"\n  shows \"p - 1 dvd n - 1\"\nproof -\n  have \"\\<not>prime n\" using Carmichael_number unfolding Carmichael_number_def by blast\n  obtain u where \"n = p * u\" using \\<open>p dvd n\\<close> by blast\n  have \"squarefree n\" using Carmichael_number_imp_squarefree assms by blast\n  then have \"\\<not>p dvd u\"\n    using \\<open>prime p\\<close> not_prime_unit[of p]\n    unfolding power2_eq_square squarefree_def \\<open>n = p * u\\<close>\n    by fastforce\n\n  define R where \"R = Residues_nat p\"\n  interpret residues_nat_prime p R\n    by unfold_locales (simp_all only: \\<open>prime p\\<close> R_def)\n  \n  obtain a where a: \"a \\<in> {0<..<p}\" \"units.ord a = p - 1\"\n    using residues_prime_cyclic' \\<open>prime p\\<close> by metis\n  from a have \"a \\<in> totatives p\" by (auto simp: totatives_prime \\<open>prime p\\<close>)\n\n  have \"coprime p u\"\n    using \\<open>prime p\\<close> \\<open>\\<not> p dvd u\\<close>\n    by (simp add: prime_imp_coprime_nat) \n\n  then obtain x where \"[x = a] (mod p)\" \"[x = 1] (mod u)\" \n    using binary_chinese_remainder_nat[of p u a 1] by blast\n\n  have \"coprime x p\"\n    using \\<open>a \\<in> totatives p\\<close> and cong_imp_coprime[OF cong_sym[OF \\<open>[x = a] (mod p)\\<close>]]\n    by (simp add: coprime_commute totatives_def)\n  moreover have \"coprime x u\" \n    using coprime_1_left and cong_imp_coprime[OF cong_sym[OF \\<open>[x = 1] (mod u)\\<close>]] by blast\n  ultimately have \"coprime x n\"\n    by (simp add: \\<open>n = p * u\\<close>)\n\n  have \"[a ^ (n - 1) = x ^ (n - 1)] (mod p)\"\n    using \\<open>[x = a] (mod p)\\<close> by (intro cong_pow) (auto simp: cong_sym_eq)\n  also have \"[x ^ (n - 1) = 1] (mod n)\"\n    using Carmichael_number \\<open>coprime x n\\<close> unfolding Carmichael_number_def by blast\n  then have \"[x ^ (n - 1) = 1] (mod p)\"\n    using \\<open>n = p * u\\<close> cong_modulus_mult_nat by blast \n  finally have \"ord p a dvd n - 1\"\n    by (simp add: ord_divides [symmetric])\n  also have \"ord p a = p - 1\"\n    using a \\<open>a \\<in> totatives p\\<close> by (simp add: units.ord_residue_mult_group)\n  finally show ?thesis .    \nqed\n\ntext \\<open>\n  The following lemma is also called Korselt's criterion.\n\\<close>\nlemma Carmichael_numberI:\n  fixes n :: nat\n  assumes \"\\<not> prime n\" \"squarefree n\" \"1 < n\" and\n          DIV: \"\\<And>p. p \\<in> prime_factors n \\<Longrightarrow> p - 1 dvd n - 1\"\n  shows   \"Carmichael_number n\"\n  unfolding Carmichael_number_def\nproof (intro assms conjI allI impI)\n  fix a :: nat assume \"coprime a n\"\n\n  have n: \"n = \\<Prod>(prime_factors n)\"\n    using prime_factorization_nat and squarefree_factorial_semiring'[of n] \\<open>1 < n\\<close> \\<open>squarefree n\\<close>\n    by fastforce\n\n  have \"x \\<in># prime_factorization n \\<Longrightarrow> y \\<in># prime_factorization n \\<Longrightarrow> x \\<noteq> y \\<Longrightarrow> coprime x y\" for x y\n    using in_prime_factors_imp_prime primes_coprime\n    by blast\n\n  moreover {\n    fix p \n    assume p: \"p \\<in># prime_factorization n\"\n\n    have \"\\<not>p dvd a\"\n      using \\<open>coprime a n\\<close> p coprime_common_divisor_nat[of a n p]\n      by (auto simp: in_prime_factors_iff)\n    with p have \"[a ^ (p - 1) = 1] (mod p)\"\n      by (intro fermat_theorem) auto\n    hence \"ord p a dvd p - 1\"\n      by (subst (asm) ord_divides)\n    also from p have \"p - 1 dvd n - 1\"\n      by (rule DIV)\n    finally have \"[a ^ (n - 1) = 1] (mod p)\"\n      by (subst ord_divides)\n  }\n\n  ultimately show \"[a ^ (n - 1) = 1] (mod n)\"\n    using n coprime_cong_prod_nat by metis\nqed\n\ntheorem Carmichael_number_iff:\n  \"Carmichael_number n \\<longleftrightarrow>\n     n \\<noteq> 1 \\<and> \\<not>prime n \\<and> squarefree n \\<and> (\\<forall>p\\<in>prime_factors n. p - 1 dvd n - 1)\"\nproof -\n  consider \"n = 0\" | \"n = 1\" | \"n > 1\" by force\n  thus ?thesis using Carmichael_numberI[of n] Carmichael_number_imp_dvd[of n]\n    by cases (auto simp: Carmichael_number_not_prime Carmichael_number_imp_squarefree)\nqed\n\ntext \\<open>\n  Every Carmichael number has at least three distinct prime factors.\n\\<close>\ntheorem Carmichael_number_card_prime_factors:\n  assumes \"Carmichael_number n\"\n  shows   \"card (prime_factors n) \\<ge> 3\"\nproof (rule ccontr)\n  from assms have \"n > 3\"\n    using Carmichael_number_gt_3[of n] by simp\n  assume \"\\<not>(card (prime_factors n) \\<ge> 3)\"\n  moreover have \"card (prime_factors n) \\<noteq> 0\"\n    using assms Carmichael_number_gt_3[of n] by (auto simp: prime_factorization_empty_iff)\n  moreover have \"card (prime_factors n) \\<noteq> 1\"\n    using assms by (auto simp: one_prime_factor_iff_primepow Carmichael_not_primepow)\n  ultimately have \"card (prime_factors n) = 2\"\n    by linarith\n  then obtain p q where pq: \"prime_factors n = {p, q}\" \"p \\<noteq> q\"\n    by (auto simp: card_Suc_eq numeral_2_eq_2)\n  hence \"prime p\" \"prime q\" by (auto simp: in_prime_factors_iff)\n\n  have \"n = \\<Prod>(prime_factors n)\"\n    using assms by (subst squarefree_imp_prod_prime_factors_eq)\n                   (auto simp: Carmichael_number_imp_squarefree)\n  with pq have n_eq: \"n = p * q\" by simp\n\n  have \"p - 1 dvd n - 1\" and \"q - 1 dvd n - 1\" using assms pq\n    unfolding Carmichael_number_iff by blast+\n  with \\<open>prime p\\<close> \\<open>prime q\\<close> \\<open>n = p * q\\<close> \\<open>p \\<noteq> q\\<close> show False\n  proof (induction p q rule: linorder_wlog)\n    case (le p q)\n    hence \"p < q\" by auto\n    have \"[q = 1] (mod q - 1)\"\n      using prime_gt_1_nat[of q] \\<open>prime q\\<close> by (simp add: cong_def le_mod_geq)\n    hence \"[p * q - 1 = p * 1 - 1] (mod q - 1)\"\n      using le prime_gt_1_nat[of p] by (intro cong_diff_nat cong_mult) auto\n    hence \"[p - 1 = n - 1] (mod q - 1)\"\n      by (simp add: \\<open>n = p * q\\<close> cong_sym_eq)\n    also have \"[n - 1 = 0] (mod q - 1)\"\n      using le by (simp add: cong_def)\n    finally have \"(p - 1) mod (q - 1) = 0\"\n      by (simp add: cong_def)\n    also have \"(p - 1) mod (q - 1) = p - 1\"\n      using prime_gt_1_nat[of p] \\<open>prime p\\<close> \\<open>p < q\\<close> by (intro mod_less) auto\n    finally show False\n      using prime_gt_1_nat[of p] \\<open>prime p\\<close> by simp\n  qed (simp_all add: mult.commute)\nqed\n\nlemma Carmichael_number_iff':\n  fixes n :: nat\n  defines \"P \\<equiv> prime_factorization n\"\n  shows \"Carmichael_number n \\<longleftrightarrow>\n           n > 1 \\<and> size P \\<noteq> 1 \\<and> (\\<forall>p\\<in>#P. count P p = 1 \\<and> p - 1 dvd n - 1)\"\n  unfolding Carmichael_number_iff\n  by (cases \"n = 0\") (auto simp: P_def squarefree_factorial_semiring' count_prime_factorization)\n\ntext \\<open>\n  The smallest Carmichael number is 561, and it was found and proven so by\n  Carmichael in 1910~\\<^cite>\\<open>\"carmichael1910note\"\\<close>.\n\\<close>\nlemma Carmichael_number_561: \"Carmichael_number 561\" (is \"Carmichael_number ?n\")\nproof -\n  have [simp]: \"prime_factorization (561 :: nat) = {#3, 11, 17#}\"\n    by (rule prime_factorization_eqI) auto\n  show ?thesis by (subst Carmichael_number_iff') 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/Probabilistic_Prime_Tests/Carmichael_Numbers.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267796346598, "lm_q2_score": 0.8376199673867852, "lm_q1q2_score": 0.7277466588223493}}
{"text": "(*\n    $Id: ex.thy,v 1.2 2004/11/23 15:14:34 webertj Exp $\n    Author: Gerwin Klein\n*)\n\nheader {* Sorting with Lists and Trees *}\n\n(*<*) theory ex 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\nconsts \n  insort :: \"nat \\<Rightarrow> nat list \\<Rightarrow> nat list\"\n  sort   :: \"nat list \\<Rightarrow> nat list\"\n  le     :: \"nat \\<Rightarrow> nat list \\<Rightarrow> bool\"\n  sorted :: \"nat list \\<Rightarrow> bool\"\n\ntext {*\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\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\ntheorem \"sorted (sort xs)\"\n(*<*) oops (*>*)\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\n\ntext {*\n  Show that\n*}\n\ntheorem \"count (sort xs) x = count xs x\"\n(*<*) oops (*>*)\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\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\n\ntext {*\n  Show\n*}\n\ntheorem [simp]: \"tsorted (tree_of xs)\"\n(*<*) oops (*>*)\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\n\ntext {*\n  Show\n*}\n\ntheorem \"tcount (tree_of xs) x = count xs x\"\n(*<*) oops (*>*)\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\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/advanced/sorting/ex.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8688267796346599, "lm_q2_score": 0.8376199552262967, "lm_q1q2_score": 0.7277466482569914}}
{"text": "(*  Title:      HOL/Algebra/Sylow.thy\n    Author:     Florian Kammueller, with new proofs by L C Paulson\n*)\n\ntheory Sylow\nimports Coset Exponent\nbegin\n\ntext \\<open>\n  See also @{cite \"Kammueller-Paulson:1999\"}.\n\\<close>\n\ntext\\<open>The combinatorial argument is in theory Exponent\\<close>\n\nlemma le_extend_mult: \n  fixes c::nat shows \"\\<lbrakk>0 < c; a \\<le> b\\<rbrakk> \\<Longrightarrow> a \\<le> b * c\"\nby (metis divisors_zero dvd_triv_left leI less_le_trans nat_dvd_not_less zero_less_iff_neq_zero)\n\nlocale sylow = group +\n  fixes p and a and m and calM and RelM\n  assumes prime_p:   \"prime p\"\n      and order_G:   \"order(G) = (p^a) * m\"\n      and finite_G [iff]:  \"finite (carrier G)\"\n  defines \"calM == {s. s \\<subseteq> carrier(G) & card(s) = p^a}\"\n      and \"RelM == {(N1,N2). N1 \\<in> calM & N2 \\<in> calM &\n                             (\\<exists>g \\<in> carrier(G). N1 = (N2 #> g) )}\"\nbegin\n\nlemma RelM_refl_on: \"refl_on calM RelM\"\napply (auto simp add: refl_on_def RelM_def calM_def)\napply (blast intro!: coset_mult_one [symmetric])\ndone\n\nlemma RelM_sym: \"sym RelM\"\nproof (unfold sym_def RelM_def, clarify)\n  fix y g\n  assume   \"y \\<in> calM\"\n    and g: \"g \\<in> carrier G\"\n  hence \"y = y #> g #> (inv g)\" by (simp add: coset_mult_assoc calM_def)\n  thus \"\\<exists>g'\\<in>carrier G. y = y #> g #> g'\" by (blast intro: g)\nqed\n\nlemma RelM_trans: \"trans RelM\"\nby (auto simp add: trans_def RelM_def calM_def coset_mult_assoc)\n\nlemma RelM_equiv: \"equiv calM RelM\"\napply (unfold equiv_def)\napply (blast intro: RelM_refl_on RelM_sym RelM_trans)\ndone\n\nlemma M_subset_calM_prep: \"M' \\<in> calM // RelM  ==> M' \\<subseteq> calM\"\napply (unfold RelM_def)\napply (blast elim!: quotientE)\ndone\n\nend\n\nsubsection\\<open>Main Part of the Proof\\<close>\n\nlocale sylow_central = sylow +\n  fixes H and M1 and M\n  assumes M_in_quot:  \"M \\<in> calM // RelM\"\n      and not_dvd_M:  \"~(p ^ Suc(multiplicity p m) dvd card(M))\"\n      and M1_in_M:    \"M1 \\<in> M\"\n  defines \"H == {g. g\\<in>carrier G & M1 #> g = M1}\"\n\nbegin\n\nlemma M_subset_calM: \"M \\<subseteq> calM\"\n  by (rule M_in_quot [THEN M_subset_calM_prep])\n\nlemma card_M1: \"card(M1) = p^a\"\n  using M1_in_M M_subset_calM calM_def by blast\n \nlemma exists_x_in_M1: \"\\<exists>x. x \\<in> M1\"\nusing prime_p [THEN prime_gt_Suc_0_nat] card_M1\nby (metis Suc_lessD card_eq_0_iff empty_subsetI equalityI gr_implies_not0 nat_zero_less_power_iff subsetI)\n\nlemma M1_subset_G [simp]: \"M1 \\<subseteq> carrier G\"\n  using M1_in_M  M_subset_calM calM_def mem_Collect_eq subsetCE by blast\n\nlemma M1_inj_H: \"\\<exists>f \\<in> H\\<rightarrow>M1. inj_on f H\"\nproof -\n  from exists_x_in_M1 obtain m1 where m1M: \"m1 \\<in> M1\"..\n  have m1G: \"m1 \\<in> carrier G\" by (simp add: m1M M1_subset_G [THEN subsetD])\n  show ?thesis\n  proof\n    show \"inj_on (\\<lambda>z\\<in>H. m1 \\<otimes> z) H\"\n      by (simp add: inj_on_def l_cancel [of m1 x y, THEN iffD1] H_def m1G)\n    show \"restrict (op \\<otimes> m1) H \\<in> H \\<rightarrow> M1\"\n    proof (rule restrictI)\n      fix z assume zH: \"z \\<in> H\"\n      show \"m1 \\<otimes> z \\<in> M1\"\n      proof -\n        from zH\n        have zG: \"z \\<in> carrier G\" and M1zeq: \"M1 #> z = M1\"\n          by (auto simp add: H_def)\n        show ?thesis\n          by (rule subst [OF M1zeq], simp add: m1M zG rcosI)\n      qed\n    qed\n  qed\nqed\n\nend\n\nsubsection\\<open>Discharging the Assumptions of \\<open>sylow_central\\<close>\\<close>\n\ncontext sylow\nbegin\n\nlemma EmptyNotInEquivSet: \"{} \\<notin> calM // RelM\"\nby (blast elim!: quotientE dest: RelM_equiv [THEN equiv_class_self])\n\nlemma existsM1inM: \"M \\<in> calM // RelM ==> \\<exists>M1. M1 \\<in> M\"\n  using RelM_equiv equiv_Eps_in by blast\n\nlemma zero_less_o_G: \"0 < order(G)\"\n  by (simp add: order_def card_gt_0_iff carrier_not_empty)\n\nlemma zero_less_m: \"m > 0\"\n  using zero_less_o_G by (simp add: order_G)\n\nlemma card_calM: \"card(calM) = (p^a) * m choose p^a\"\nby (simp add: calM_def n_subsets order_G [symmetric] order_def)\n\nlemma zero_less_card_calM: \"card calM > 0\"\nby (simp add: card_calM zero_less_binomial le_extend_mult zero_less_m)\n\nlemma max_p_div_calM:\n     \"~ (p ^ Suc(multiplicity p m) dvd card(calM))\"\nproof\n  assume \"p ^ Suc (multiplicity p m) dvd card calM\"\n  with zero_less_card_calM prime_p \n  have \"Suc (multiplicity p m) \\<le> multiplicity p (card calM)\"\n    by (intro multiplicity_geI) auto\n  hence \"multiplicity p m < multiplicity p (card calM)\" by simp\n  also have \"multiplicity p m = multiplicity p (card calM)\"\n    by (simp add: const_p_fac prime_p zero_less_m card_calM)\n  finally show False by simp\nqed\n\nlemma finite_calM: \"finite calM\"\n  unfolding calM_def\n  by (rule_tac B = \"Pow (carrier G) \" in finite_subset) auto\n\nlemma lemma_A1:\n     \"\\<exists>M \\<in> calM // RelM. ~ (p ^ Suc(multiplicity p m) dvd card(M))\"\n  using RelM_equiv equiv_imp_dvd_card finite_calM max_p_div_calM by blast\n\nend\n\nsubsubsection\\<open>Introduction and Destruct Rules for @{term H}\\<close>\n\nlemma (in sylow_central) H_I: \"[|g \\<in> carrier G; M1 #> g = M1|] ==> g \\<in> H\"\nby (simp add: H_def)\n\nlemma (in sylow_central) H_into_carrier_G: \"x \\<in> H ==> x \\<in> carrier G\"\nby (simp add: H_def)\n\nlemma (in sylow_central) in_H_imp_eq: \"g : H ==> M1 #> g = M1\"\nby (simp add: H_def)\n\nlemma (in sylow_central) H_m_closed: \"[| x\\<in>H; y\\<in>H|] ==> x \\<otimes> y \\<in> H\"\napply (unfold H_def)\napply (simp add: coset_mult_assoc [symmetric])\ndone\n\nlemma (in sylow_central) H_not_empty: \"H \\<noteq> {}\"\napply (simp add: H_def)\napply (rule exI [of _ \\<one>], simp)\ndone\n\nlemma (in sylow_central) H_is_subgroup: \"subgroup H G\"\napply (rule subgroupI)\napply (rule subsetI)\napply (erule H_into_carrier_G)\napply (rule H_not_empty)\napply (simp add: H_def, clarify)\napply (erule_tac P = \"%z. lhs(z) = M1\" for lhs in subst)\napply (simp add: coset_mult_assoc )\napply (blast intro: H_m_closed)\ndone\n\n\nlemma (in sylow_central) rcosetGM1g_subset_G:\n     \"[| g \\<in> carrier G; x \\<in> M1 #>  g |] ==> x \\<in> carrier G\"\nby (blast intro: M1_subset_G [THEN r_coset_subset_G, THEN subsetD])\n\nlemma (in sylow_central) finite_M1: \"finite M1\"\nby (rule finite_subset [OF M1_subset_G finite_G])\n\nlemma (in sylow_central) finite_rcosetGM1g: \"g\\<in>carrier G ==> finite (M1 #> g)\"\n  using rcosetGM1g_subset_G finite_G M1_subset_G cosets_finite rcosetsI by blast\n\nlemma (in sylow_central) M1_cardeq_rcosetGM1g:\n     \"g \\<in> carrier G ==> card(M1 #> g) = card(M1)\"\nby (simp (no_asm_simp) add: card_cosets_equal rcosetsI)\n\nlemma (in sylow_central) M1_RelM_rcosetGM1g:\n     \"g \\<in> carrier G ==> (M1, M1 #> g) \\<in> RelM\"\napply (simp add: RelM_def calM_def card_M1)\napply (rule conjI)\n apply (blast intro: rcosetGM1g_subset_G)\napply (simp add: card_M1 M1_cardeq_rcosetGM1g)\napply (metis M1_subset_G coset_mult_assoc coset_mult_one r_inv_ex)\ndone\n\n\nsubsection\\<open>Equal Cardinalities of @{term M} and the Set of Cosets\\<close>\n\ntext\\<open>Injections between @{term M} and @{term \"rcosets\\<^bsub>G\\<^esub> H\"} show that\n their cardinalities are equal.\\<close>\n\nlemma ElemClassEquiv:\n     \"[| equiv A r; C \\<in> A // r |] ==> \\<forall>x \\<in> C. \\<forall>y \\<in> C. (x,y)\\<in>r\"\nby (unfold equiv_def quotient_def sym_def trans_def, blast)\n\nlemma (in sylow_central) M_elem_map:\n     \"M2 \\<in> M ==> \\<exists>g. g \\<in> carrier G & M1 #> g = M2\"\napply (cut_tac M1_in_M M_in_quot [THEN RelM_equiv [THEN ElemClassEquiv]])\napply (simp add: RelM_def)\napply (blast dest!: bspec)\ndone\n\nlemmas (in sylow_central) M_elem_map_carrier =\n        M_elem_map [THEN someI_ex, THEN conjunct1]\n\nlemmas (in sylow_central) M_elem_map_eq =\n        M_elem_map [THEN someI_ex, THEN conjunct2]\n\nlemma (in sylow_central) M_funcset_rcosets_H:\n     \"(%x:M. H #> (SOME g. g \\<in> carrier G & M1 #> g = x)) \\<in> M \\<rightarrow> rcosets H\"\n  by (metis (lifting) H_is_subgroup M_elem_map_carrier rcosetsI restrictI subgroup_imp_subset)\n\nlemma (in sylow_central) inj_M_GmodH: \"\\<exists>f \\<in> M \\<rightarrow> rcosets H. inj_on f M\"\napply (rule bexI)\napply (rule_tac [2] M_funcset_rcosets_H)\napply (rule inj_onI, simp)\napply (rule trans [OF _ M_elem_map_eq])\nprefer 2 apply assumption\napply (rule M_elem_map_eq [symmetric, THEN trans], assumption)\napply (rule coset_mult_inv1)\napply (erule_tac [2] M_elem_map_carrier)+\napply (rule_tac [2] M1_subset_G)\napply (rule coset_join1 [THEN in_H_imp_eq])\napply (rule_tac [3] H_is_subgroup)\nprefer 2 apply (blast intro: M_elem_map_carrier)\napply (simp add: coset_mult_inv2 H_def M_elem_map_carrier subset_eq)\ndone\n\n\nsubsubsection\\<open>The Opposite Injection\\<close>\n\nlemma (in sylow_central) H_elem_map:\n     \"H1 \\<in> rcosets H ==> \\<exists>g. g \\<in> carrier G & H #> g = H1\"\nby (auto simp add: RCOSETS_def)\n\nlemmas (in sylow_central) H_elem_map_carrier =\n        H_elem_map [THEN someI_ex, THEN conjunct1]\n\nlemmas (in sylow_central) H_elem_map_eq =\n        H_elem_map [THEN someI_ex, THEN conjunct2]\n\nlemma (in sylow_central) rcosets_H_funcset_M:\n  \"(\\<lambda>C \\<in> rcosets H. M1 #> (@g. g \\<in> carrier G \\<and> H #> g = C)) \\<in> rcosets H \\<rightarrow> M\"\napply (simp add: RCOSETS_def)\napply (fast intro: someI2\n            intro!: M1_in_M in_quotient_imp_closed [OF RelM_equiv M_in_quot _  M1_RelM_rcosetGM1g])\ndone\n\ntext\\<open>close to a duplicate of \\<open>inj_M_GmodH\\<close>\\<close>\nlemma (in sylow_central) inj_GmodH_M:\n     \"\\<exists>g \\<in> rcosets H\\<rightarrow>M. inj_on g (rcosets H)\"\napply (rule bexI)\napply (rule_tac [2] rcosets_H_funcset_M)\napply (rule inj_onI)\napply (simp)\napply (rule trans [OF _ H_elem_map_eq])\nprefer 2 apply assumption\napply (rule H_elem_map_eq [symmetric, THEN trans], assumption)\napply (rule coset_mult_inv1)\napply (erule_tac [2] H_elem_map_carrier)+\napply (rule_tac [2] H_is_subgroup [THEN subgroup.subset])\napply (rule coset_join2)\napply (blast intro: H_elem_map_carrier)\napply (rule H_is_subgroup)\napply (simp add: H_I coset_mult_inv2 H_elem_map_carrier)\ndone\n\nlemma (in sylow_central) calM_subset_PowG: \"calM \\<subseteq> Pow(carrier G)\"\nby (auto simp add: calM_def)\n\n\nlemma (in sylow_central) finite_M: \"finite M\"\nby (metis M_subset_calM finite_calM rev_finite_subset)\n\nlemma (in sylow_central) cardMeqIndexH: \"card(M) = card(rcosets H)\"\napply (insert inj_M_GmodH inj_GmodH_M)\napply (blast intro: card_bij finite_M H_is_subgroup\n             rcosets_subset_PowG [THEN finite_subset]\n             finite_Pow_iff [THEN iffD2])\ndone\n\nlemma (in sylow_central) index_lem: \"card(M) * card(H) = order(G)\"\nby (simp add: cardMeqIndexH lagrange H_is_subgroup)\n\nlemma (in sylow_central) lemma_leq1: \"p^a \\<le> card(H)\"\napply (rule dvd_imp_le)\n apply (rule div_combine [OF prime_imp_prime_elem[OF prime_p] not_dvd_M])\n prefer 2 apply (blast intro: subgroup.finite_imp_card_positive H_is_subgroup)\napply (simp add: index_lem order_G power_add mult_dvd_mono multiplicity_dvd\n                 zero_less_m)\ndone\n\nlemma (in sylow_central) lemma_leq2: \"card(H) \\<le> p^a\"\napply (subst card_M1 [symmetric])\napply (cut_tac M1_inj_H)\napply (blast intro!: M1_subset_G intro:\n             card_inj H_into_carrier_G finite_subset [OF _ finite_G])\ndone\n\nlemma (in sylow_central) card_H_eq: \"card(H) = p^a\"\nby (blast intro: le_antisym lemma_leq1 lemma_leq2)\n\nlemma (in sylow) sylow_thm: \"\\<exists>H. subgroup H G & card(H) = p^a\"\napply (cut_tac lemma_A1, clarify)\napply (frule existsM1inM, clarify)\napply (subgoal_tac \"sylow_central G p a m M1 M\")\n apply (blast dest:  sylow_central.H_is_subgroup sylow_central.card_H_eq)\napply (simp add: sylow_central_def sylow_central_axioms_def sylow_axioms calM_def RelM_def)\ndone\n\ntext\\<open>Needed because the locale's automatic definition refers to\n   @{term \"semigroup G\"} and @{term \"group_axioms G\"} rather than\n  simply to @{term \"group G\"}.\\<close>\nlemma sylow_eq: \"sylow G p a m = (group G & sylow_axioms G p a m)\"\nby (simp add: sylow_def group_def)\n\n\nsubsection \\<open>Sylow's Theorem\\<close>\n\ntheorem sylow_thm:\n     \"[| prime p;  group(G);  order(G) = (p^a) * m; finite (carrier G)|]\n      ==> \\<exists>H. subgroup H G & card(H) = p^a\"\napply (rule sylow.sylow_thm [of G p a m])\napply (simp add: sylow_eq sylow_axioms_def)\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/Algebra/Sylow.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267626522814, "lm_q2_score": 0.8376199714402812, "lm_q1q2_score": 0.727746648119356}}
{"text": "(* Author: Tobias Nipkow *)\n(* Todo:\n (min_)height of balanced trees via floorlog\n minimal path_len of balanced trees\n*)\n\nsection \\<open>Binary Tree\\<close>\n\ntheory Tree\nimports Main\nbegin\n\ndatatype 'a tree =\n  is_Leaf: Leaf (\"\\<langle>\\<rangle>\") |\n  Node (left: \"'a tree\") (val: 'a) (right: \"'a tree\") (\"(1\\<langle>_,/ _,/ _\\<rangle>)\")\n  where\n    \"left Leaf = Leaf\"\n  | \"right Leaf = Leaf\"\ndatatype_compat tree\n\ntext\\<open>Can be seen as counting the number of leaves rather than nodes:\\<close>\n\ndefinition size1 :: \"'a tree \\<Rightarrow> nat\" where\n\"size1 t = size t + 1\"\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\nfun mirror :: \"'a tree \\<Rightarrow> 'a tree\" where\n\"mirror \\<langle>\\<rangle> = Leaf\" |\n\"mirror \\<langle>l,x,r\\<rangle> = \\<langle>mirror r, x, mirror l\\<rangle>\"\n\nclass height = fixes height :: \"'a \\<Rightarrow> nat\"\n\ninstantiation tree :: (type)height\nbegin\n\nfun height_tree :: \"'a tree => nat\" where\n\"height Leaf = 0\" |\n\"height (Node t1 a t2) = max (height t1) (height t2) + 1\"\n\ninstance ..\n\nend\n\nfun min_height :: \"'a tree \\<Rightarrow> nat\" where\n\"min_height Leaf = 0\" |\n\"min_height (Node l _ r) = min (min_height l) (min_height r) + 1\"\n\nfun complete :: \"'a tree \\<Rightarrow> bool\" where\n\"complete Leaf = True\" |\n\"complete (Node l x r) = (complete l \\<and> complete r \\<and> height l = height r)\"\n\ndefinition balanced :: \"'a tree \\<Rightarrow> bool\" where\n\"balanced t = (height t - min_height t \\<le> 1)\"\n\ntext \\<open>Weight balanced:\\<close>\nfun wbalanced :: \"'a tree \\<Rightarrow> bool\" where\n\"wbalanced Leaf = True\" |\n\"wbalanced (Node l x r) = (abs(int(size l) - int(size r)) \\<le> 1 \\<and> wbalanced l \\<and> wbalanced r)\"\n\ntext \\<open>Internal path length:\\<close>\nfun path_len :: \"'a tree \\<Rightarrow> nat\" where\n\"path_len Leaf = 0 \" |\n\"path_len (Node l _ r) = path_len l + size l + path_len r + size r\"\n\nfun preorder :: \"'a tree \\<Rightarrow> 'a list\" where\n\"preorder \\<langle>\\<rangle> = []\" |\n\"preorder \\<langle>l, x, r\\<rangle> = x # preorder l @ preorder r\"\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\ntext\\<open>A linear version avoiding append:\\<close>\nfun inorder2 :: \"'a tree \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where\n\"inorder2 \\<langle>\\<rangle> xs = xs\" |\n\"inorder2 \\<langle>l, x, r\\<rangle> xs = inorder2 l (x # inorder2 r xs)\"\n\ntext\\<open>Binary Search Tree:\\<close>\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\ntext\\<open>Binary Search Tree with duplicates:\\<close>\nfun (in linorder) bst_eq :: \"'a tree \\<Rightarrow> bool\" where\n\"bst_eq \\<langle>\\<rangle> \\<longleftrightarrow> True\" |\n\"bst_eq \\<langle>l,a,r\\<rangle> \\<longleftrightarrow>\n bst_eq l \\<and> bst_eq r \\<and> (\\<forall>x\\<in>set_tree l. x \\<le> a) \\<and> (\\<forall>x\\<in>set_tree r. a \\<le> x)\"\n\nfun (in linorder) heap :: \"'a 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\nsubsection \\<open>@{const size}\\<close>\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 size1_ge0[simp]: \"0 < size1 t\"\nby (simp add: size1_def)\n\nlemma size_0_iff_Leaf: \"size t = 0 \\<longleftrightarrow> t = Leaf\"\nby(cases t) auto\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\nlemma size_map_tree[simp]: \"size (map_tree f t) = size t\"\nby (induction t) auto\n\nlemma size1_map_tree[simp]: \"size1 (map_tree f t) = size1 t\"\nby (simp add: size1_def)\n\n\nsubsection \\<open>@{const subtrees}\\<close>\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 \\<open>@{const height} and @{const min_height}\\<close>\n\nlemma height_0_iff_Leaf: \"height t = 0 \\<longleftrightarrow> t = Leaf\"\nby(cases t) auto\n\nlemma height_map_tree[simp]: \"height (map_tree f t) = height t\"\nby (induction t) auto\n\nlemma height_le_size_tree: \"height t \\<le> size (t::'a tree)\"\nby (induction t) auto\n\nlemma size1_height: \"size t + 1 \\<le> 2 ^ height (t::'a tree)\"\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\ncorollary size_height: \"size t \\<le> 2 ^ height (t::'a tree) - 1\"\nusing size1_height[of t] by(arith)\n\nlemma height_subtrees: \"s \\<in> subtrees t \\<Longrightarrow> height s \\<le> height t\"\nby (induction t) auto\n\n\nlemma min_hight_le_height: \"min_height t \\<le> height t\"\nby(induction t) auto\n\nlemma min_height_map_tree[simp]: \"min_height (map_tree f t) = min_height t\"\nby (induction t) auto\n\nlemma min_height_le_size1: \"2 ^ min_height t \\<le> size t + 1\"\nproof(induction t)\n  case (Node l a r)\n  have \"(2::nat) ^ min_height (Node l a r) \\<le> 2 ^ min_height l + 2 ^ min_height r\"\n    by (simp add: min_def)\n  also have \"\\<dots> \\<le> size(Node l a r) + 1\" using Node.IH by simp\n  finally show ?case .\nqed simp\n\n\nsubsection \\<open>@{const complete}\\<close>\n\nlemma complete_iff_height: \"complete t \\<longleftrightarrow> (min_height t = height t)\"\napply(induction t)\n apply simp\napply (simp add: min_def max_def)\nby (metis le_antisym le_trans min_hight_le_height)\n\nlemma size1_if_complete: \"complete t \\<Longrightarrow> size1 t = 2 ^ height t\"\nby (induction t) auto\n\nlemma size_if_complete: \"complete t \\<Longrightarrow> size t = 2 ^ height t - 1\"\nusing size1_if_complete[simplified size1_def] by fastforce\n\nlemma complete_if_size: \"size t = 2 ^ height t - 1 \\<Longrightarrow> complete t\"\nproof (induct \"height t\" arbitrary: t)\n  case 0 thus ?case by (simp add: size_0_iff_Leaf)\nnext\n  case (Suc h)\n  hence \"t \\<noteq> Leaf\" by auto\n  then obtain l a r where [simp]: \"t = Node l a r\"\n    by (auto simp: neq_Leaf_iff)\n  have 1: \"height l \\<le> h\" and 2: \"height r \\<le> h\" using Suc(2) by(auto)\n  have 3: \"~ height l < h\"\n  proof\n    assume 0: \"height l < h\"\n    have \"size t = size l + (size r + 1)\" by simp\n    also note size_height[of l]\n    also note size1_height[of r]\n    also have \"(2::nat) ^ height l - 1 < 2 ^ h - 1\"\n        using 0 by (simp add: diff_less_mono)\n    also have \"(2::nat) ^ height r \\<le> 2 ^ h\" using 2 by simp\n    also have \"(2::nat) ^ h - 1 + 2 ^ h = 2 ^ (Suc h) - 1\" by (simp)\n    also have \"\\<dots> = size t\" using Suc(2,3) by simp\n    finally show False by (simp add: diff_le_mono)\n  qed\n  have 4: \"~ height r < h\"\n  proof\n    assume 0: \"height r < h\"\n    have \"size t = (size l + 1) + size r\" by simp\n    also note size_height[of r]\n    also note size1_height[of l]\n    also have \"(2::nat) ^ height r - 1 < 2 ^ h - 1\"\n        using 0 by (simp add: diff_less_mono)\n    also have \"(2::nat) ^ height l \\<le> 2 ^ h\" using 1 by simp\n    also have \"(2::nat) ^ h + (2 ^ h - 1) = 2 ^ (Suc h) - 1\" by (simp)\n    also have \"\\<dots> = size t\" using Suc(2,3) by simp\n    finally show False by (simp add: diff_le_mono)\n  qed\n  from 1 2 3 4 have *: \"height l = h\" \"height r = h\" by linarith+\n  hence \"size l = 2 ^ height l - 1\" \"size r = 2 ^ height r - 1\"\n    using Suc(3) size_height[of l] size_height[of r] by (auto)\n  with * Suc(1) show ?case by simp\nqed\n\nlemma complete_iff_size: \"complete t \\<longleftrightarrow> size t = 2 ^ height t - 1\"\nusing complete_if_size size_if_complete by blast\n\ntext\\<open>A better lower bound for incomplete trees:\\<close>\n\nlemma min_height_le_size_if_incomplete:\n  \"\\<not> complete t \\<Longrightarrow> 2 ^ min_height t \\<le> size t\"\nproof(induction t)\n  case Leaf thus ?case by simp\nnext\n  case (Node l a r)\n  show ?case (is \"?l \\<le> ?r\")\n  proof (cases \"complete l\")\n    case l: True thus ?thesis\n    proof (cases \"complete r\")\n      case r: True\n      have \"height l \\<noteq> height r\" using Node.prems l r by simp\n      hence \"?l < 2 ^ min_height l + 2 ^ min_height r\"\n        using l r by (simp add: min_def complete_iff_height)\n      also have \"\\<dots> = (size l + 1) + (size r + 1)\"\n        using l r size_if_complete[where ?'a = 'a]\n        by (simp add: complete_iff_height)\n      also have \"\\<dots> \\<le> ?r + 1\" by simp\n      finally show ?thesis by arith\n    next\n      case r: False\n      have \"?l \\<le> 2 ^ min_height l + 2 ^ min_height r\" by (simp add: min_def)\n      also have \"\\<dots> \\<le> size l + 1 + size r\"\n        using Node.IH(2)[OF r] l size_if_complete[where ?'a = 'a]\n        by (simp add: complete_iff_height)\n      also have \"\\<dots> = ?r\" by simp\n      finally show ?thesis .\n    qed\n  next\n    case l: False thus ?thesis\n    proof (cases \"complete r\")\n      case r: True\n      have \"?l \\<le> 2 ^ min_height l + 2 ^ min_height r\" by (simp add: min_def)\n      also have \"\\<dots> \\<le> size l + (size r + 1)\"\n        using Node.IH(1)[OF l] r size_if_complete[where ?'a = 'a]\n        by (simp add: complete_iff_height)\n      also have \"\\<dots> = ?r\" by simp\n      finally show ?thesis .\n    next\n      case r: False\n      have \"?l \\<le> 2 ^ min_height l + 2 ^ min_height r\"\n        by (simp add: min_def)\n      also have \"\\<dots> \\<le> size l + size r\"\n        using Node.IH(1)[OF l] Node.IH(2)[OF r] by (simp)\n      also have \"\\<dots> \\<le> ?r\" by simp\n      finally show ?thesis .\n    qed\n  qed\nqed\n\n\nsubsection \\<open>@{const balanced}\\<close>\n\nlemma balanced_subtreeL: \"balanced (Node l x r) \\<Longrightarrow> balanced l\"\nby(simp add: balanced_def)\n\nlemma balanced_subtreeR: \"balanced (Node l x r) \\<Longrightarrow> balanced r\"\nby(simp add: balanced_def)\n\nlemma balanced_subtrees: \"\\<lbrakk> balanced t; s \\<in> subtrees t \\<rbrakk> \\<Longrightarrow> balanced s\"\nusing [[simp_depth_limit=1]]\nby(induction t arbitrary: s)\n  (auto simp add: balanced_subtreeL balanced_subtreeR)\n\ntext\\<open>Balanced trees have optimal height:\\<close>\n\nlemma balanced_optimal:\nfixes t :: \"'a tree\" and t' :: \"'b tree\"\nassumes \"balanced t\" \"size t \\<le> size t'\" shows \"height t \\<le> height t'\"\nproof (cases \"complete t\")\n  case True\n  have \"(2::nat) ^ height t - 1 \\<le> 2 ^ height t' - 1\"\n  proof -\n    have \"(2::nat) ^ height t - 1 = size t\"\n      using True by (simp add: complete_iff_height size_if_complete)\n    also note assms(2)\n    also have \"size t' \\<le> 2 ^ height t' - 1\" by (rule size_height)\n    finally show ?thesis .\n  qed\n  thus ?thesis by (simp add: le_diff_iff)\nnext\n  case False\n  have \"(2::nat) ^ min_height t < 2 ^ height t'\"\n  proof -\n    have \"(2::nat) ^ min_height t \\<le> size t\"\n      by(rule min_height_le_size_if_incomplete[OF False])\n    also note assms(2)\n    also have \"size t' \\<le> 2 ^ height t' - 1\"  by(rule size_height)\n    finally show ?thesis\n      using power_eq_0_iff[of \"2::nat\" \"height t'\"] by linarith\n  qed\n  hence *: \"min_height t < height t'\" by simp\n  have \"min_height t + 1 = height t\"\n    using min_hight_le_height[of t] assms(1) False\n    by (simp add: complete_iff_height balanced_def)\n  with * show ?thesis by arith\nqed\n\n\nsubsection \\<open>@{const wbalanced}\\<close>\n\nlemma wbalanced_subtrees: \"\\<lbrakk> wbalanced t; s \\<in> subtrees t \\<rbrakk> \\<Longrightarrow> wbalanced s\"\nusing [[simp_depth_limit=1]] by(induction t arbitrary: s) auto\n\n(* show wbalanced \\<Longrightarrow> balanced and use that in Balanced.thy *)\n\n\nsubsection \\<open>@{const path_len}\\<close>\n\ntext \\<open>The internal path length of a tree:\\<close>\n\nlemma path_len_if_bal: \"complete t\n  \\<Longrightarrow> path_len t = (let n = height t in 2 + n*2^n - 2^(n+1))\"\nproof(induction t)\n  case (Node l x r)\n  have *: \"2^(n+1) \\<le> 2 + n*2^n\" for n :: nat\n    by(induction n) auto\n  have **: \"(0::nat) < 2^n\" for n :: nat by simp\n  let ?h = \"height r\"\n  show ?case using Node *[of ?h] **[of ?h] by (simp add: size_if_complete Let_def)\nqed simp\n\n\nsubsection \"List of entries\"\n\nlemma set_inorder[simp]: \"set (inorder t) = set_tree t\"\nby (induction t) auto\n\nlemma set_preorder[simp]: \"set (preorder t) = set_tree t\"\nby (induction t) auto\n\nlemma length_preorder[simp]: \"length (preorder t) = size t\"\nby (induction t) auto\n\nlemma length_inorder[simp]: \"length (inorder t) = size t\"\nby (induction t) auto\n\nlemma preorder_map: \"preorder (map_tree f t) = map f (preorder t)\"\nby (induction t) auto\n\nlemma inorder_map: \"inorder (map_tree f t) = map f (inorder t)\"\nby (induction t) auto\n\nlemma inorder2_inorder: \"inorder2 t xs = inorder t @ xs\"\nby (induction t arbitrary: xs) auto\n\n\nsubsection \\<open>Binary Search Tree\\<close>\n\nlemma (in linorder) bst_eq_if_bst: \"bst t \\<Longrightarrow> bst_eq t\"\nby (induction t) (auto)\n\nlemma (in linorder) bst_eq_imp_sorted: \"bst_eq t \\<Longrightarrow> sorted (inorder t)\"\napply (induction t)\n apply(simp)\nby (fastforce simp: sorted_append sorted_Cons intro: less_imp_le less_trans)\n\nlemma (in linorder) distinct_preorder_if_bst: \"bst t \\<Longrightarrow> distinct (preorder t)\"\napply (induction t)\n apply simp\napply(fastforce elim: order.asym)\ndone\n\nlemma (in linorder) distinct_inorder_if_bst: \"bst t \\<Longrightarrow> distinct (inorder t)\"\napply (induction t)\n apply simp\napply(fastforce elim: order.asym)\ndone\n\n\nsubsection \\<open>@{const heap}\\<close>\n\n\nsubsection \\<open>@{const mirror}\\<close>\n\nlemma mirror_Leaf[simp]: \"mirror t = \\<langle>\\<rangle> \\<longleftrightarrow> t = \\<langle>\\<rangle>\"\nby (induction t) simp_all\n\nlemma size_mirror[simp]: \"size(mirror t) = size t\"\nby (induction t) simp_all\n\nlemma size1_mirror[simp]: \"size1(mirror t) = size1 t\"\nby (simp add: size1_def)\n\nlemma height_mirror[simp]: \"height(mirror t) = height t\"\nby (induction t) simp_all\n\nlemma inorder_mirror: \"inorder(mirror t) = rev(inorder t)\"\nby (induction t) simp_all\n\nlemma map_mirror: \"map_tree f (mirror t) = mirror (map_tree f t)\"\nby (induction t) simp_all\n\nlemma mirror_mirror[simp]: \"mirror(mirror t) = t\"\nby (induction t) simp_all\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/Tree.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8688267762381843, "lm_q2_score": 0.8376199572530448, "lm_q1q2_score": 0.7277466471729287}}
{"text": "(* Title:      Kleene Algebra\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\nheader {* Dioids *}\n\ntheory Dioid\nimports Signatures\nbegin\n\nsubsection {* Join Semilattices *}\n\ntext {* 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~@{text\n\"+\"} 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*}\n\nclass join_semilattice = plus_ord +\n  assumes add_assoc' [simp]: \"(x + y) + z = x + (y + z)\"\n  and add_comm [simp]: \"x + y = y + x\"\n  and add_idem [simp]: \"x + x = x\"\nbegin\n\nlemma add_left_comm [simp]:\n  \"b + (a + c) = a + (b + c)\"\n  unfolding add_assoc' [symmetric] by simp\n\nlemma add_left_idem [simp]:\n  \"a + (a + b) = a + b\"\n  unfolding add_assoc' [symmetric] by simp\n\ntext {* 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. *}\n\nsubclass order\nproof\n  fix x y z :: 'a\n  show \"x < y \\<longleftrightarrow> x \\<le> y \\<and> \\<not> y \\<le> x\"\n    by (metis add_comm less_def less_eq_def)\n  show \"x \\<le> x\"\n    by (metis add_idem 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 (metis add_comm less_eq_def)\nqed\n\ntext {* Next we show that joins are least upper bounds. *}\n\nlemma add_ub1 [simp]: \"x \\<le> x + y\"\n  by (metis add_assoc' add_idem less_eq_def)\n\nlemma add_ub2 [simp]: \"y \\<le> x + y\"\n  by (metis add_assoc' add_comm add_idem less_eq_def)\n\nlemma add_lub_var: \"x \\<le> z \\<longrightarrow> y \\<le> z \\<longrightarrow> x + y \\<le> z\"\n  by (metis add_assoc' less_eq_def)\n\nlemma add_lub: \"x + y \\<le> z \\<longleftrightarrow> x \\<le> z \\<and> y \\<le> z\"\n  by (metis add_lub_var add_ub1 add_ub2 order_trans)\n\ntext {* Next we prove that joins are isotone (order preserving). *}\n\nlemma add_iso: \"x \\<le> y \\<longrightarrow> x + z \\<le> y + z\"\n  by (metis add_lub add_ub2 less_eq_def)\n\nlemma add_iso_var: \"x \\<le> y \\<longrightarrow> u \\<le> v \\<longrightarrow> x + u \\<le> y + v\"\n  by (metis add_comm add_iso add_lub)\n\ntext {* The next lemma links the definition of order as @{term \"x \\<le> y\n\\<longleftrightarrow> x + y = y\"}\nwith a perhaps more conventional one known, e.g., from\narithmetics. *}\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 (metis 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  also have \"x + c \\<le> y\"\n    by (metis calculation eq_refl)\n  thus \"x \\<le> y\"\n    by (metis add_ub1 calculation)\nqed\n\nend (* join_semilattice *)\n\n\n\nsubsection {* Join Semilattices with an Additive Unit *}\n\ntext {* We now expand join semilattices by an additive unit~$0$. Is\nthe least element with respect to the order, and therefore often\ndenoted by~@{text \\<bottom>}. Semilattices with a least element are often\ncalled \\emph{bounded}. *}\n\nclass join_semilattice_zero = join_semilattice + zero +\n  assumes add_zero_l [simp]: \"0 + x = x\"\nbegin\n\nsubclass comm_monoid_add\n  apply unfold_locales\n  apply auto\n  apply (metis add_comm add_zero_l)\n  done\n\nlemma zero_least [simp]: \"0 \\<le> x\"\n  by (metis add_zero_l less_eq_def)\n\nlemma add_zero_r [simp]: \"x + 0 = x\"\n  by (metis add_comm add_zero_l)\n\nlemma zero_unique [simp]: \"x \\<le> 0 \\<longleftrightarrow> x = 0\"\n  by (metis zero_least eq_iff)\n\nlemma no_trivial_inverse: \"x \\<noteq> 0 \\<longrightarrow> \\<not>(\\<exists>y. x + y = 0)\"\n  by (metis zero_unique order_prop)\n\nend (* join_semilattice_zero *)\n\n\n\nsubsection {* Near Semirings *}\n\ntext {* \\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}. *}\n\nclass ab_near_semiring = ab_semigroup_add + semigroup_mult +\n  assumes distrib_right': \"(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\n\nsubsection {* Variants of Dioids *}\n\ntext {* 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}. *}\n\nclass near_dioid = ab_near_semiring + plus_ord +\n  assumes add_idem' [simp]: \"x + x = x\"\nbegin\n\ntext {* 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. *}\n\nsubclass join_semilattice\nby unfold_locales (auto simp add: add.commute add.left_commute)\n\ntext {* It follows that multiplication is right-isotone (but not\nnecessarily left-isotone). *}\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 (metis less_eq_def)\n  also have \"x \\<cdot> z + y \\<cdot> z = (x + y) \\<cdot> z\"\n    by (metis distrib_right')\n  moreover have \"... = y \\<cdot> z\"\n    by (metis calculation)\n  thus \"x \\<cdot> z \\<le> y \\<cdot> z\"\n    by (metis calculation 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 {* The next lemma states that, in every near dioid, left\nisotonicity and left subdistributivity are equivalent. *}\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 add_ub1 less_eq_def)\n\nend (* near_dioid *)\n\ntext {* 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. *}\n\nclass pre_dioid = near_dioid +\n  assumes subdistl: \"z \\<cdot> x \\<le> z \\<cdot> (x + y)\"\nbegin\n\ntext {* Now, obviously, left isotonicity follows from left\nsubdistributivity. *}\n\nlemma subdistl_var: \"z \\<cdot> x + z \\<cdot> y \\<le> z \\<cdot> (x + y)\"\n  by (metis add.commute add_lub 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 (metis less_eq_def)\n  also have \"z \\<cdot> x + z \\<cdot> y \\<le> z \\<cdot> (x + y)\"\n    by (metis subdistl_var)\n  moreover have \"... = z \\<cdot> y\"\n    by (metis calculation)\n  thus \"z \\<cdot> x \\<le> z \\<cdot> y\"\n    by (metis add_ub1 calculation order_trans)\nqed\n\nlemma mult_isol_var: \"u \\<le> x \\<and> v \\<le> y \\<longrightarrow> u \\<cdot> v \\<le> x \\<cdot> y\"\n  by (metis mult_isol mult_isor order_trans)\n\nlemma mult_double_iso: \"x \\<le> y \\<longrightarrow> w \\<cdot> x \\<cdot> z \\<le> w \\<cdot> y \\<cdot> z\"\n  by (metis mult_isol mult_isor)\n\nend (* pre_dioid *)\n\ntext {* 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. *}\n\nclass dioid = near_dioid + semiring\n\nsubclass (in dioid) pre_dioid\n  by (unfold_locales, metis order_prop distrib_left)\n\n\nsubsection {* Families of Nearsemirings with a Multiplicative Unit *}\n\ntext {* 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. *}\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\"\nbegin\n\nsubclass monoid_mult\nby (unfold_locales, simp_all)\n\nend (* ab_near_semiring_one *)\n\nclass near_dioid_one = near_dioid + ab_near_semiring_one\n\ntext {* 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*}\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 {* Families of Nearsemirings with Additive Units *}\n\ntext {*\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*}\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 (* ab_near_semiring_one_zerol *)\n\ntext {* Note that we do not require~$0 \\neq 1$.  *}\n\nlemma add_zeror [simp]: \"x + 0 = x\"\n  by (metis add.commute add_zerol)\n\nend (* ab_near_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, metis add_zerol)\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 {* We now make zero also a right annihilator. *}\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\n\nsubsection {* Duality by Opposition *}\n\ntext {*\nSwapping the order of multiplication in a semiring (or dioid) gives\nanother semiring (or dioid), called its \\emph{dual} or\n\\emph{opposite}.\n*}\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 (op \\<odot>) (op +) 0\"\nby 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 (op +) (op \\<odot>) 1 0 (op \\<le>) (op <)\"\nby unfold_locales (auto simp add: opp_mult_def mult.assoc distrib_right distrib_left)\n\nsubsection {* Selective Near Semirings *}\n\ntext {* 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. *}\n\nclass selective_near_semiring = ab_near_semiring + plus_ord +\n  assumes select: \"x + y = x \\<or> x + y = y\"\nbegin\n\nlemma select_alt: \"x + y \\<in> {x,y}\"\n  by (metis insert_iff select)\n\ntext {* It follows immediately that every selective near semiring is a\nnear dioid. *}\n\nsubclass near_dioid\n  by (unfold_locales, metis select)\n\ntext {* Moreover, the order in a selective near semiring is obviously\nlinear. *}\n\nsubclass linorder\n  by (unfold_locales, metis add.commute add_ub1 select)\n\nend (*selective_near_semiring*)\n\nclass selective_semiring = selective_near_semiring + semiring_one_zero\nbegin\n\nsubclass dioid_one_zero ..\n\nend (* selective_semiring *)\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/Kleene_Algebra/Dioid.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199552262967, "lm_q2_score": 0.8688267660487572, "lm_q1q2_score": 0.7277466368771682}}
{"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_20\n  imports \"../../Test_Base\"\nbegin\n\ndatatype 'a list = nil2 | cons2 \"'a\" \"'a list\"\n\ndatatype Nat = Z | S \"Nat\"\n\nfun len :: \"'a list => Nat\" where\n  \"len (nil2) = Z\"\n| \"len (cons2 y xs) = S (len xs)\"\n\nfun t2 :: \"Nat => Nat => bool\" where\n  \"t2 (Z) y = True\"\n| \"t2 (S z) (Z) = False\"\n| \"t2 (S z) (S x2) = t2 z x2\"\n\nfun insort :: \"Nat => Nat list => Nat list\" where\n  \"insort x (nil2) = cons2 x (nil2)\"\n| \"insort x (cons2 z xs) =\n     (if t2 x z then cons2 x (cons2 z xs) else cons2 z (insort x xs))\"\n\nfun sort :: \"Nat list => Nat list\" where\n  \"sort (nil2) = nil2\"\n| \"sort (cons2 y xs) = insort y (sort xs)\"\n\ntheorem property0 :\n  \"((len (sort xs)) = (len xs))\"\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_20.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898203834278, "lm_q2_score": 0.8031737892899222, "lm_q1q2_score": 0.7276672770954538}}
{"text": "section\\<open>Cardinal Arithmetic under Choice\\label{sec:cardinal-lib}\\<close>\n\ntheory Cardinal_Library\n  imports\n    ZF_Library\n    ZF.Cardinal_AC\n\nbegin\n\ntext\\<open>This theory includes results on cardinalities that depend on $\\AC$\\<close>\n\n\nsubsection\\<open>Results on cardinal exponentiation\\<close>\n\ntext\\<open>Non trivial instances of cardinal exponentiation require that\n     the relevant function spaces are well-ordered, hence this \n     implies a strong use of choice.\\<close>\n\nlemma cexp_eqpoll_cong:\n  assumes\n    \"A \\<approx> A'\" \"B \\<approx> B'\"\n  shows\n    \"A\\<^bsup>\\<up>B\\<^esup> = A'\\<^bsup>\\<up>B'\\<^esup>\"\n  unfolding cexp_def using cardinal_eqpoll_iff\n    function_space_eqpoll_cong assms\n  by simp\n\nlemma cexp_cexp_cmult: \"(\\<kappa>\\<^bsup>\\<up>\\<nu>1\\<^esup>)\\<^bsup>\\<up>\\<nu>2\\<^esup> = \\<kappa>\\<^bsup>\\<up>\\<nu>2 \\<otimes> \\<nu>1\\<^esup>\"\nproof -\n  have \"(\\<kappa>\\<^bsup>\\<up>\\<nu>1\\<^esup>)\\<^bsup>\\<up>\\<nu>2\\<^esup> = (\\<nu>1 \\<rightarrow> \\<kappa>)\\<^bsup>\\<up>\\<nu>2\\<^esup>\"\n    using cardinal_eqpoll\n    by (intro cexp_eqpoll_cong) (simp_all add:cexp_def)\n  also\n  have \" \\<dots> = \\<kappa>\\<^bsup>\\<up>\\<nu>2 \\<times> \\<nu>1\\<^esup>\"\n    unfolding cexp_def using curry_eqpoll cardinal_cong by blast\n  also\n  have \" \\<dots> = \\<kappa>\\<^bsup>\\<up>\\<nu>2 \\<otimes> \\<nu>1\\<^esup>\"\n    using cardinal_eqpoll[THEN eqpoll_sym]\n    unfolding cmult_def by (intro cexp_eqpoll_cong) (simp)\n  finally\n  show ?thesis  .\nqed\n\nlemma cardinal_Pow: \"|Pow(X)| = 2\\<^bsup>\\<up>X\\<^esup>\" \\<comment> \\<open>Perhaps it's better with |X|\\<close>\n  using cardinal_eqpoll_iff[THEN iffD2, OF Pow_eqpoll_function_space]\n  unfolding cexp_def by simp\n\nlemma cantor_cexp:\n  assumes \"Card(\\<nu>)\"\n  shows \"\\<nu> < 2\\<^bsup>\\<up>\\<nu>\\<^esup>\"\n  using assms Card_is_Ord Card_cexp\nproof (intro not_le_iff_lt[THEN iffD1] notI)\n  assume \"2\\<^bsup>\\<up>\\<nu>\\<^esup> \\<le> \\<nu>\"\n  then\n  have \"|Pow(\\<nu>)| \\<le> \\<nu>\"\n    using cardinal_Pow by simp\n  with assms\n  have \"Pow(\\<nu>) \\<lesssim> \\<nu>\"\n    using cardinal_eqpoll_iff Card_le_imp_lepoll Card_cardinal_eq\n    by auto\n  then\n  obtain g where \"g \\<in> inj(Pow(\\<nu>), \\<nu>)\"\n    by blast\n  then\n  show \"False\"\n    using cantor_inj by simp\nqed simp\n\nlemma cexp_left_mono:\n  assumes \"\\<kappa>1 \\<le> \\<kappa>2\"\n  shows \"\\<kappa>1\\<^bsup>\\<up>\\<nu>\\<^esup> \\<le> \\<kappa>2\\<^bsup>\\<up>\\<nu>\\<^esup>\"\n    (* \\<comment> \\<open>short, unreadable proof: \\<close>\n  unfolding cexp_def\n  using subset_imp_lepoll[THEN lepoll_imp_cardinal_le]\n    assms le_subset_iff[THEN iffD1, OF assms]\n    Pi_weaken_type[of _ _ \"\\<lambda>_. \\<kappa>1\" \"\\<lambda>_. \\<kappa>2\"] by auto *)\nproof -\n  from assms\n  have \"\\<kappa>1 \\<subseteq> \\<kappa>2\"\n    using le_subset_iff by simp\n  then\n  have \"\\<nu> \\<rightarrow> \\<kappa>1  \\<subseteq> \\<nu> \\<rightarrow> \\<kappa>2\"\n    using Pi_weaken_type by auto\n  then\n  show ?thesis unfolding cexp_def\n    using lepoll_imp_cardinal_le subset_imp_lepoll by simp\nqed\n\nlemma cantor_cexp':\n  assumes \"2 \\<le> \\<kappa>\" \"Card(\\<nu>)\"\n  shows \"\\<nu> < \\<kappa>\\<^bsup>\\<up>\\<nu>\\<^esup>\"\n  using cexp_left_mono assms cantor_cexp lt_trans2 by blast\n\nlemma InfCard_cexp:\n  assumes \"2 \\<le> \\<kappa>\" \"InfCard(\\<nu>)\"\n  shows \"InfCard(\\<kappa>\\<^bsup>\\<up>\\<nu>\\<^esup>)\"\n  using assms cantor_cexp'[THEN leI] le_trans Card_cexp\n  unfolding InfCard_def by auto\n\nlemmas InfCard_cexp' = InfCard_cexp[OF nats_le_InfCard, simplified]\n  \\<comment> \\<open>\\<^term>\\<open>InfCard(\\<kappa>) \\<Longrightarrow> InfCard(\\<nu>) \\<Longrightarrow> InfCard(\\<kappa>\\<^bsup>\\<up>\\<nu>\\<^esup>)\\<close>\\<close>\n\n\nsubsection\\<open>Miscellaneous\\<close>\n\nlemma cardinal_RepFun_le: \"|{f(a) . a\\<in>A}| \\<le> |A|\"\nproof -\n  have \"(\\<lambda>x\\<in>A. f(x)) \\<in> surj(A, {f(a) . a\\<in>A})\"\n    unfolding surj_def using lam_funtype by auto\n  then\n  show ?thesis\n    using  surj_implies_cardinal_le by blast\nqed\n\nlemma subset_imp_le_cardinal: \"A \\<subseteq> B \\<Longrightarrow> |A| \\<le> |B|\"\n  using subset_imp_lepoll[THEN lepoll_imp_cardinal_le] .\n\nlemma lt_cardinal_imp_not_subset: \"|A| < |B| \\<Longrightarrow> \\<not> B \\<subseteq> A\"\n  using subset_imp_le_cardinal le_imp_not_lt by blast\n\nlemma cardinal_lt_csucc_iff: \"Card(K) \\<Longrightarrow> |K'| < K\\<^sup>+ \\<longleftrightarrow> |K'| \\<le> K\"\n  by (simp add: Card_lt_csucc_iff)\n\nlemma cardinal_UN_le_nat:\n  \"(\\<And>i. i\\<in>\\<omega> \\<Longrightarrow> |X(i)| \\<le> \\<omega>) \\<Longrightarrow> |\\<Union>i\\<in>\\<omega>. X(i)| \\<le> \\<omega>\"\n  by (simp add: cardinal_UN_le InfCard_nat)\n\nlemma lepoll_imp_cardinal_UN_le:\n  notes [dest] = InfCard_is_Card Card_is_Ord\n  assumes \"InfCard(K)\" \"J \\<lesssim> K\" \"\\<And>i. i\\<in>J \\<Longrightarrow> |X(i)| \\<le> K\"\n  shows \"|\\<Union>i\\<in>J. X(i)| \\<le> K\"\nproof -\n  from \\<open>J \\<lesssim> K\\<close>\n  obtain f where \"f \\<in> inj(J,K)\" by blast\n  define Y where \"Y(k) \\<equiv> if k\\<in>range(f) then X(converse(f)`k) else 0\" for k\n  have \"i\\<in>J \\<Longrightarrow> f`i \\<in> K\" for i\n    using inj_is_fun[OF \\<open>f \\<in> inj(J,K)\\<close>] by auto\n  have \"(\\<Union>i\\<in>J. X(i)) \\<subseteq> (\\<Union>i\\<in>K. Y(i))\"\n  proof (standard, elim UN_E)\n    fix x i\n    assume \"i\\<in>J\" \"x\\<in>X(i)\"\n    with \\<open>f \\<in> inj(J,K)\\<close> \\<open>i\\<in>J \\<Longrightarrow> f`i \\<in> K\\<close>\n    have \"x \\<in> Y(f`i)\" \"f`i \\<in> K\"\n      unfolding Y_def\n      using inj_is_fun[OF \\<open>f \\<in> inj(J,K)\\<close>]\n        right_inverse apply_rangeI by auto\n    then\n    show \"x \\<in> (\\<Union>i\\<in>K. Y(i))\" by auto\n  qed\n  then\n  have \"|\\<Union>i\\<in>J. X(i)| \\<le> |\\<Union>i\\<in>K. Y(i)|\"\n    unfolding Y_def using subset_imp_le_cardinal by simp\n  with assms \\<open>\\<And>i. i\\<in>J \\<Longrightarrow> f`i \\<in> K\\<close>\n  show \"|\\<Union>i\\<in>J. X(i)| \\<le> K\"\n    using inj_converse_fun[OF \\<open>f \\<in> inj(J,K)\\<close>] unfolding Y_def\n    by (rule_tac le_trans[OF _ cardinal_UN_le]) (auto intro:Ord_0_le)+\nqed\n\n\\<comment> \\<open>For backwards compatibility\\<close>\nlemmas leqpoll_imp_cardinal_UN_le = lepoll_imp_cardinal_UN_le\n\nlemma cardinal_lt_csucc_iff':\n  includes Ord_dests\n  assumes \"Card(\\<kappa>)\"\n  shows \"\\<kappa> < |X| \\<longleftrightarrow> \\<kappa>\\<^sup>+ \\<le> |X|\"\n  using assms cardinal_lt_csucc_iff[of \\<kappa> X] Card_csucc[of \\<kappa>]\n    not_le_iff_lt[of \"\\<kappa>\\<^sup>+\" \"|X|\"] not_le_iff_lt[of \"|X|\" \\<kappa>]\n  by blast\n\nlemma lepoll_imp_subset_bij: \"X \\<lesssim> Y \\<longleftrightarrow> (\\<exists>Z. Z \\<subseteq> Y \\<and> Z \\<approx> X)\"\nproof\n  assume \"X \\<lesssim> Y\"\n  then\n  obtain j where  \"j \\<in> inj(X,Y)\"\n    by blast\n  then\n  have \"range(j) \\<subseteq> Y\" \"j \\<in> bij(X,range(j))\"\n    using inj_bij_range inj_is_fun range_fun_subset_codomain\n    by blast+\n  then\n  show \"\\<exists>Z. Z \\<subseteq> Y \\<and> Z \\<approx> X\"\n    using eqpoll_sym unfolding eqpoll_def\n    by force\nnext\n  assume \"\\<exists>Z. Z \\<subseteq> Y \\<and> Z \\<approx> X\"\n  then\n  obtain Z f where \"f \\<in> bij(Z,X)\" \"Z \\<subseteq> Y\"\n    unfolding eqpoll_def by force\n  then\n  have \"converse(f) \\<in> inj(X,Y)\"\n    using bij_is_inj inj_weaken_type bij_converse_bij by blast\n  then\n  show \"X \\<lesssim> Y\" by blast\nqed\n\ntext\\<open>The following result proves to be very useful when combining\n     \\<^term>\\<open>cardinal\\<close> and \\<^term>\\<open>eqpoll\\<close> in a calculation.\\<close>\n\nlemma cardinal_Card_eqpoll_iff: \"Card(\\<kappa>) \\<Longrightarrow> |X| = \\<kappa> \\<longleftrightarrow> X \\<approx> \\<kappa>\"\n  using Card_cardinal_eq[of \\<kappa>] cardinal_eqpoll_iff[of X \\<kappa>] by auto\n    \\<comment> \\<open>Compare @{thm [source] \"le_Card_iff\"}\\<close>\n\nlemma lepoll_imp_lepoll_cardinal: assumes \"X \\<lesssim> Y\" shows \"X \\<lesssim> |Y|\"\n  using assms cardinal_Card_eqpoll_iff[of \"|Y|\" Y]\n    lepoll_eq_trans[of _ _ \"|Y|\"] by simp\n\nlemma lepoll_Un:\n  assumes \"InfCard(\\<kappa>)\" \"A \\<lesssim> \\<kappa>\" \"B \\<lesssim> \\<kappa>\"\n  shows \"A \\<union> B \\<lesssim> \\<kappa>\"\nproof -\n  have \"A \\<union> B \\<lesssim> sum(A,B)\"\n    using Un_lepoll_sum .\n  moreover\n  note assms\n  moreover from this\n  have \"|sum(A,B)| \\<le> \\<kappa> \\<oplus> \\<kappa>\"\n    using sum_lepoll_mono[of A \\<kappa> B \\<kappa>] lepoll_imp_cardinal_le\n    unfolding cadd_def by auto\n  ultimately\n  show ?thesis\n    using InfCard_cdouble_eq Card_cardinal_eq\n      InfCard_is_Card Card_le_imp_lepoll[of \"sum(A,B)\" \\<kappa>]\n      lepoll_trans[of \"A\\<union>B\"]\n    by auto\nqed\n\nlemma cardinal_Un_le:\n  assumes \"InfCard(\\<kappa>)\" \"|A| \\<le> \\<kappa>\" \"|B| \\<le> \\<kappa>\"\n  shows \"|A \\<union> B| \\<le> \\<kappa>\"\n  using assms lepoll_Un le_Card_iff InfCard_is_Card by auto\n\ntext\\<open>This is the unconditional version under choice of \n     @{thm [source] Cardinal.Finite_cardinal_iff}.\\<close>\nlemma Finite_cardinal_iff': \"Finite(|i|) \\<longleftrightarrow> Finite(i)\"\n  using cardinal_eqpoll_iff eqpoll_imp_Finite_iff by fastforce\n\nlemma cardinal_subset_of_Card:\n  assumes \"Card(\\<gamma>)\" \"a \\<subseteq> \\<gamma>\"\n  shows \"|a| < \\<gamma> \\<or> |a| = \\<gamma>\"\nproof -\n  from assms\n  have \"|a| < |\\<gamma>| \\<or> |a| = |\\<gamma>|\"\n    using subset_imp_le_cardinal le_iff by simp\n  with assms\n  show ?thesis\n    using Card_cardinal_eq by simp\nqed\n\nlemma cardinal_cases:\n  includes Ord_dests\n  shows \"Card(\\<gamma>) \\<Longrightarrow> |X| < \\<gamma> \\<longleftrightarrow> \\<not> |X| \\<ge> \\<gamma>\"\n  using not_le_iff_lt\n  by auto\n\n\nsubsection\\<open>Countable and uncountable sets\\<close>\n\nlemma countable_iff_cardinal_le_nat: \"countable(X) \\<longleftrightarrow> |X| \\<le> \\<omega>\"\n  using le_Card_iff[of \\<omega> X] Card_nat\n  unfolding countable_def by simp\n\nlemma lepoll_countable: \"X \\<lesssim> Y \\<Longrightarrow> countable(Y) \\<Longrightarrow> countable(X)\"\n  using lepoll_trans[of X Y] by blast\n\n\\<comment> \\<open>Next lemma can be proved without using AC\\<close>\nlemma surj_countable: \"countable(X) \\<Longrightarrow> f \\<in> surj(X,Y) \\<Longrightarrow> countable(Y)\"\n  using surj_implies_cardinal_le[of f X Y, THEN le_trans]\n    countable_iff_cardinal_le_nat by simp\n\nlemma Finite_imp_countable: \"Finite(X) \\<Longrightarrow> countable(X)\"\n  unfolding Finite_def\n  by (auto intro:InfCard_nat nats_le_InfCard[of _ \\<omega>,\n        THEN le_imp_lepoll] dest!:eq_lepoll_trans[of X _ \\<omega>])\n\nlemma countable_imp_countable_UN:\n  assumes \"countable(J)\" \"\\<And>i. i\\<in>J \\<Longrightarrow> countable(X(i))\"\n  shows \"countable(\\<Union>i\\<in>J. X(i))\"\n  using assms lepoll_imp_cardinal_UN_le[of \\<omega> J X] InfCard_nat\n    countable_iff_cardinal_le_nat\n  by auto\n\nlemma countable_union_countable:\n  assumes \"\\<And>x. x \\<in> C \\<Longrightarrow> countable(x)\" \"countable(C)\"\n  shows \"countable(\\<Union>C)\"\n  using assms countable_imp_countable_UN[of C \"\\<lambda>x. x\"] by simp\n\nabbreviation\n  uncountable :: \"i\\<Rightarrow>o\" where\n  \"uncountable(X) \\<equiv> \\<not> countable(X)\"\n\nlemma uncountable_iff_nat_lt_cardinal:\n  \"uncountable(X) \\<longleftrightarrow> \\<omega> < |X|\"\n  using countable_iff_cardinal_le_nat not_le_iff_lt by simp\n\nlemma uncountable_not_empty: \"uncountable(X) \\<Longrightarrow> X \\<noteq> 0\"\n  using empty_lepollI by auto\n\nlemma uncountable_imp_Infinite: \"uncountable(X) \\<Longrightarrow> Infinite(X)\"\n  using uncountable_iff_nat_lt_cardinal[of X] lepoll_nat_imp_Infinite[of X]\n    cardinal_le_imp_lepoll[of \\<omega> X] leI\n  by simp\n\nlemma uncountable_not_subset_countable:\n  assumes \"countable(X)\" \"uncountable(Y)\"\n  shows \"\\<not> (Y \\<subseteq> X)\"\n  using assms lepoll_trans subset_imp_lepoll[of Y X]\n  by blast\n\n\nsubsection\\<open>Results on Alephs\\<close>\n\nlemma nat_lt_Aleph1: \"\\<omega> < \\<aleph>\\<^bsub>1\\<^esub>\"\n  by (simp add: Aleph_def lt_csucc)\n\nlemma zero_lt_Aleph1: \"0 < \\<aleph>\\<^bsub>1\\<^esub>\"\n  by (rule lt_trans[of _ \"\\<omega>\"], auto simp add: ltI nat_lt_Aleph1)\n\nlemma le_aleph1_nat: \"Card(k) \\<Longrightarrow> k<\\<aleph>\\<^bsub>1\\<^esub> \\<Longrightarrow> k \\<le> \\<omega>\"\n  by (simp add: Aleph_def Card_lt_csucc_iff Card_nat)\n\nlemma Aleph_succ: \"\\<aleph>\\<^bsub>succ(\\<alpha>)\\<^esub> = \\<aleph>\\<^bsub>\\<alpha>\\<^esub>\\<^sup>+\"\n  unfolding Aleph_def by simp\n\nlemma lesspoll_aleph_plus_one:\n  assumes \"Ord(\\<alpha>)\"\n  shows \"d \\<prec> \\<aleph>\\<^bsub>succ(\\<alpha>)\\<^esub> \\<longleftrightarrow> d \\<lesssim> \\<aleph>\\<^bsub>\\<alpha>\\<^esub>\"\n  using assms lesspoll_csucc Aleph_succ Card_is_Ord by simp\n\nlemma cardinal_Aleph [simp]: \"Ord(\\<alpha>) \\<Longrightarrow> |\\<aleph>\\<^bsub>\\<alpha>\\<^esub>| = \\<aleph>\\<^bsub>\\<alpha>\\<^esub>\"\n  using Card_cardinal_eq by simp\n\n\\<comment> \\<open>Could be proved without using AC\\<close>\nlemma Aleph_lesspoll_increasing:\n  includes Aleph_intros\n  shows \"a < b \\<Longrightarrow> \\<aleph>\\<^bsub>a\\<^esub> \\<prec> \\<aleph>\\<^bsub>b\\<^esub>\"\n  using cardinal_lt_iff_lesspoll[of \"\\<aleph>\\<^bsub>a\\<^esub>\" \"\\<aleph>\\<^bsub>b\\<^esub>\"] Card_cardinal_eq[of \"\\<aleph>\\<^bsub>b\\<^esub>\"]\n    lt_Ord lt_Ord2 Card_Aleph[THEN Card_is_Ord] by auto\n\nlemma uncountable_iff_subset_eqpoll_Aleph1:\n  includes Ord_dests\n  notes Aleph_zero_eq_nat[simp] Card_nat[simp] Aleph_succ[simp]\n  shows \"uncountable(X) \\<longleftrightarrow> (\\<exists>S. S \\<subseteq> X \\<and> S \\<approx> \\<aleph>\\<^bsub>1\\<^esub>)\"\nproof\n  assume \"uncountable(X)\"\n  then\n  have \"\\<aleph>\\<^bsub>1\\<^esub> \\<lesssim> X\"\n    using uncountable_iff_nat_lt_cardinal cardinal_lt_csucc_iff'\n      cardinal_le_imp_lepoll by force\n  then\n  obtain S where \"S \\<subseteq> X\" \"S \\<approx> \\<aleph>\\<^bsub>1\\<^esub>\"\n    using lepoll_imp_subset_bij by auto\n  then\n  show \"\\<exists>S. S \\<subseteq> X \\<and> S \\<approx> \\<aleph>\\<^bsub>1\\<^esub>\"\n    using cardinal_cong Card_csucc[of \\<omega>] Card_cardinal_eq by auto\nnext\n  assume \"\\<exists>S. S \\<subseteq> X \\<and> S \\<approx> \\<aleph>\\<^bsub>1\\<^esub>\"\n  then\n  have \"\\<aleph>\\<^bsub>1\\<^esub> \\<lesssim> X\"\n    using subset_imp_lepoll[THEN [2] eq_lepoll_trans, of \"\\<aleph>\\<^bsub>1\\<^esub>\" _ X,\n        OF eqpoll_sym] by auto\n  then\n  show \"uncountable(X)\"\n    using Aleph_lesspoll_increasing[of 0 1, THEN [2] lesspoll_trans1,\n        of \"\\<aleph>\\<^bsub>1\\<^esub>\"] lepoll_trans[of \"\\<aleph>\\<^bsub>1\\<^esub>\" X \\<omega>]\n    by auto\nqed\n\nlemma lt_Aleph_imp_cardinal_UN_le_nat: \"function(G) \\<Longrightarrow> domain(G) \\<lesssim> \\<omega> \\<Longrightarrow>\n   \\<forall>n\\<in>domain(G). |G`n|<\\<aleph>\\<^bsub>1\\<^esub> \\<Longrightarrow> |\\<Union>n\\<in>domain(G). G`n|\\<le>\\<omega>\"\nproof -\n  assume \"function(G)\"\n  let ?N=\"domain(G)\" and ?R=\"\\<Union>n\\<in>domain(G). G`n\"\n  assume \"?N \\<lesssim> \\<omega>\"\n  assume Eq1: \"\\<forall>n\\<in>?N. |G`n|<\\<aleph>\\<^bsub>1\\<^esub>\"\n  {\n    fix n\n    assume \"n\\<in>?N\"\n    with Eq1 have \"|G`n| \\<le> \\<omega>\"\n      using le_aleph1_nat by simp\n  }\n  then\n  have \"n\\<in>?N \\<Longrightarrow> |G`n| \\<le> \\<omega>\" for n .\n  with \\<open>?N \\<lesssim> \\<omega>\\<close>\n  show ?thesis\n    using InfCard_nat lepoll_imp_cardinal_UN_le by simp\nqed\n\nlemma Aleph1_eq_cardinal_vimage: \"f:\\<aleph>\\<^bsub>1\\<^esub>\\<rightarrow>\\<omega> \\<Longrightarrow> \\<exists>n\\<in>\\<omega>. |f-``{n}| = \\<aleph>\\<^bsub>1\\<^esub>\"\nproof -\n  assume \"f:\\<aleph>\\<^bsub>1\\<^esub>\\<rightarrow>\\<omega>\"\n  then\n  have \"function(f)\" \"domain(f) = \\<aleph>\\<^bsub>1\\<^esub>\" \"range(f)\\<subseteq>\\<omega>\"\n    by (simp_all add: domain_of_fun fun_is_function range_fun_subset_codomain)\n  let ?G=\"\\<lambda>n\\<in>range(f). f-``{n}\"\n  from \\<open>f:\\<aleph>\\<^bsub>1\\<^esub>\\<rightarrow>\\<omega>\\<close>\n  have \"range(f) \\<subseteq> \\<omega>\" by (simp add: range_fun_subset_codomain)\n  then\n  have \"domain(?G) \\<lesssim> \\<omega>\"\n    using subset_imp_lepoll by simp\n  have \"function(?G)\" by (simp add:function_lam)\n  from \\<open>f:\\<aleph>\\<^bsub>1\\<^esub>\\<rightarrow>\\<omega>\\<close>\n  have \"n\\<in>\\<omega> \\<Longrightarrow> f-``{n} \\<subseteq> \\<aleph>\\<^bsub>1\\<^esub>\" for n\n    using Pi_vimage_subset by simp\n  with \\<open>range(f) \\<subseteq> \\<omega>\\<close>\n  have \"\\<aleph>\\<^bsub>1\\<^esub> = (\\<Union>n\\<in>range(f). f-``{n})\"\n  proof (intro equalityI, intro subsetI)\n    fix x\n    assume \"x \\<in> \\<aleph>\\<^bsub>1\\<^esub>\"\n    with \\<open>f:\\<aleph>\\<^bsub>1\\<^esub>\\<rightarrow>\\<omega>\\<close> \\<open>function(f)\\<close> \\<open>domain(f) = \\<aleph>\\<^bsub>1\\<^esub>\\<close>\n    have \"x \\<in> f-``{f`x}\" \"f`x \\<in> range(f)\"\n      using function_apply_Pair vimage_iff apply_rangeI by simp_all\n    then\n    show \"x \\<in> (\\<Union>n\\<in>range(f). f-``{n})\" by auto\n  qed auto\n  {\n    assume \"\\<forall>n\\<in>range(f). |f-``{n}| < \\<aleph>\\<^bsub>1\\<^esub>\"\n    then\n    have \"\\<forall>n\\<in>domain(?G). |?G`n| < \\<aleph>\\<^bsub>1\\<^esub>\"\n      using zero_lt_Aleph1 by (auto)\n    with \\<open>function(?G)\\<close> \\<open>domain(?G) \\<lesssim> \\<omega>\\<close>\n    have \"|\\<Union>n\\<in>domain(?G). ?G`n|\\<le>\\<omega>\"\n      using lt_Aleph_imp_cardinal_UN_le_nat by blast\n    then\n    have \"|\\<Union>n\\<in>range(f). f-``{n}|\\<le>\\<omega>\" by simp\n    with \\<open>\\<aleph>\\<^bsub>1\\<^esub> = _\\<close>\n    have \"|\\<aleph>\\<^bsub>1\\<^esub>| \\<le> \\<omega>\" by simp\n    then\n    have \"\\<aleph>\\<^bsub>1\\<^esub> \\<le> \\<omega>\"\n      using Card_Aleph Card_cardinal_eq\n      by simp\n    then\n    have \"False\"\n      using nat_lt_Aleph1 by (blast dest:lt_trans2)\n  }\n  with \\<open>range(f)\\<subseteq>\\<omega>\\<close>\n  obtain n where \"n\\<in>\\<omega>\" \"\\<not>(|f -`` {n}| < \\<aleph>\\<^bsub>1\\<^esub>)\"\n    by blast\n  moreover from this\n  have \"\\<aleph>\\<^bsub>1\\<^esub> \\<le> |f-``{n}|\"\n    using not_lt_iff_le Card_is_Ord by auto\n  moreover\n  note \\<open>n\\<in>\\<omega> \\<Longrightarrow> f-``{n} \\<subseteq> \\<aleph>\\<^bsub>1\\<^esub>\\<close>\n  ultimately\n  show ?thesis\n    using subset_imp_le_cardinal[THEN le_anti_sym, of _ \"\\<aleph>\\<^bsub>1\\<^esub>\"]\n      Card_Aleph Card_cardinal_eq by auto\nqed\n\n\\<comment> \\<open>There is some asymmetry between assumptions and conclusion\n    (\\<^term>\\<open>(\\<approx>)\\<close> versus \\<^term>\\<open>cardinal\\<close>)\\<close>\nlemma eqpoll_Aleph1_cardinal_vimage:\n  assumes \"X \\<approx> \\<aleph>\\<^bsub>1\\<^esub>\" \"f : X \\<rightarrow> \\<omega>\"\n  shows \"\\<exists>n\\<in>\\<omega>. |f-``{n}| = \\<aleph>\\<^bsub>1\\<^esub>\"\nproof -\n  from assms\n  obtain g where \"g\\<in>bij(\\<aleph>\\<^bsub>1\\<^esub>,X)\"\n    using eqpoll_sym by blast\n  with \\<open>f : X \\<rightarrow> \\<omega>\\<close>\n  have \"f O g : \\<aleph>\\<^bsub>1\\<^esub> \\<rightarrow> \\<omega>\" \"converse(g) \\<in> bij(X, \\<aleph>\\<^bsub>1\\<^esub>)\"\n    using bij_is_fun comp_fun bij_converse_bij by blast+\n  then\n  obtain n where \"n\\<in>\\<omega>\" \"|(f O g)-``{n}| = \\<aleph>\\<^bsub>1\\<^esub>\"\n    using Aleph1_eq_cardinal_vimage by auto\n  then\n  have \"\\<aleph>\\<^bsub>1\\<^esub> = |converse(g) `` (f -``{n})|\"\n    using image_comp converse_comp\n    unfolding vimage_def by simp\n  also from \\<open>converse(g) \\<in> bij(X, \\<aleph>\\<^bsub>1\\<^esub>)\\<close> \\<open>f: X\\<rightarrow> \\<omega>\\<close>\n  have \"\\<dots> = |f -``{n}|\"\n    using range_of_subset_eqpoll[of \"converse(g)\" X  _ \"f -``{n}\"]\n      bij_is_inj cardinal_cong bij_is_fun eqpoll_sym Pi_vimage_subset\n    by fastforce\n  finally\n  show ?thesis using \\<open>n\\<in>\\<omega>\\<close> by auto\nqed\n\n\nsubsection\\<open>Applications of transfinite recursive constructions\\<close>\n\ntext\\<open>The next lemma is an application of recursive constructions.\n     It works under the assumption that whenever the already constructed\n     subsequence is small enough, another element can be added.\\<close>\n\nlemma bounded_cardinal_selection:\n  includes Ord_dests\n  assumes\n    \"\\<And>X. |X| < \\<gamma> \\<Longrightarrow> X \\<subseteq> G \\<Longrightarrow> \\<exists>a\\<in>G. \\<forall>s\\<in>X. Q(s,a)\" \"b\\<in>G\" \"Card(\\<gamma>)\"\n  shows\n    \"\\<exists>S. S : \\<gamma> \\<rightarrow> G \\<and> (\\<forall>\\<alpha> \\<in> \\<gamma>. \\<forall>\\<beta> \\<in> \\<gamma>.  \\<alpha><\\<beta> \\<longrightarrow> Q(S`\\<alpha>,S`\\<beta>))\"\nproof -\n  let ?cdlt\\<gamma>=\"{X\\<in>Pow(G) . |X|<\\<gamma>}\" \\<comment> \\<open>``cardinal less than \\<^term>\\<open>\\<gamma>\\<close>''\\<close>\n    and ?inQ=\"\\<lambda>Y.{a\\<in>G. \\<forall>s\\<in>Y. Q(s,a)}\"\n  from assms\n  have \"\\<forall>Y \\<in> ?cdlt\\<gamma>. \\<exists>a. a \\<in> ?inQ(Y)\"\n    by blast\n  then\n  have \"\\<exists>f. f \\<in> Pi(?cdlt\\<gamma>,?inQ)\"\n    using AC_ball_Pi[of ?cdlt\\<gamma> ?inQ] by simp\n  then\n  obtain f where f_type:\"f \\<in> Pi(?cdlt\\<gamma>,?inQ)\"\n    by auto\n  moreover\n  define Cb where \"Cb \\<equiv> \\<lambda>_\\<in>Pow(G)-?cdlt\\<gamma>. b\"\n  moreover from \\<open>b\\<in>G\\<close>\n  have \"Cb \\<in> Pow(G)-?cdlt\\<gamma> \\<rightarrow> G\"\n    unfolding Cb_def by simp\n  moreover\n  note \\<open>Card(\\<gamma>)\\<close>\n  ultimately\n  have \"f \\<union> Cb : (\\<Prod>x\\<in>Pow(G). ?inQ(x) \\<union> G)\" using\n      fun_Pi_disjoint_Un[ of f ?cdlt\\<gamma>  ?inQ Cb \"Pow(G)-?cdlt\\<gamma>\" \"\\<lambda>_.G\"]\n      Diff_partition[of \"{X\\<in>Pow(G). |X|<\\<gamma>}\" \"Pow(G)\", OF Collect_subset]\n    by auto\n  moreover\n  have \"?inQ(x) \\<union> G = G\" for x by auto\n  ultimately\n  have \"f \\<union> Cb : Pow(G) \\<rightarrow> G\" by simp\n  define S where \"S\\<equiv>\\<lambda>\\<alpha>\\<in>\\<gamma>. rec_constr(f \\<union> Cb, \\<alpha>)\"\n  from \\<open>f \\<union> Cb: Pow(G) \\<rightarrow> G\\<close> \\<open>Card(\\<gamma>)\\<close>\n  have \"S : \\<gamma> \\<rightarrow> G\"\n    using Ord_in_Ord unfolding S_def\n    by (intro lam_type rec_constr_type) auto\n  moreover\n  have \"\\<forall>\\<alpha>\\<in>\\<gamma>. \\<forall>\\<beta>\\<in>\\<gamma>. \\<alpha> < \\<beta> \\<longrightarrow> Q(S ` \\<alpha>, S ` \\<beta>)\"\n  proof (intro ballI impI)\n    fix \\<alpha> \\<beta>\n    assume \"\\<beta>\\<in>\\<gamma>\"\n    with \\<open>Card(\\<gamma>)\\<close>\n    have \"{rec_constr(f \\<union> Cb, x) . x\\<in>\\<beta>} = {S`x . x \\<in> \\<beta>}\"\n      using Ord_trans[OF _ _ Card_is_Ord, of _ \\<beta> \\<gamma>]\n      unfolding S_def\n      by auto\n    moreover from \\<open>\\<beta>\\<in>\\<gamma>\\<close> \\<open>S : \\<gamma> \\<rightarrow> G\\<close> \\<open>Card(\\<gamma>)\\<close>\n    have \"{S`x . x \\<in> \\<beta>} \\<subseteq> G\"\n      using Ord_trans[OF _ _ Card_is_Ord, of _ \\<beta> \\<gamma>]\n        apply_type[of S \\<gamma> \"\\<lambda>_. G\"] by auto\n    moreover from \\<open>Card(\\<gamma>)\\<close> \\<open>\\<beta>\\<in>\\<gamma>\\<close>\n    have \"|{S`x . x \\<in> \\<beta>}| < \\<gamma>\"\n      using cardinal_RepFun_le[of \\<beta>]  Ord_in_Ord\n        lt_trans1[of \"|{S`x . x \\<in> \\<beta>}|\" \"|\\<beta>|\" \\<gamma>]\n        Card_lt_iff[THEN iffD2, of \\<beta> \\<gamma>, OF _ _ ltI]\n      by force\n    moreover\n    have \"\\<forall>x\\<in>\\<beta>. Q(S`x, f ` {S`x . x \\<in> \\<beta>})\"\n    proof -\n      from calculation and f_type\n      have \"f ` {S`x . x \\<in> \\<beta>} \\<in> {a\\<in>G. \\<forall>x\\<in>\\<beta>. Q(S`x,a)}\"\n        using apply_type[of f ?cdlt\\<gamma> ?inQ \"{S`x . x \\<in> \\<beta>}\"]\n        by blast\n      then\n      show ?thesis by simp\n    qed\n    moreover\n    assume \"\\<alpha>\\<in>\\<gamma>\" \"\\<alpha> < \\<beta>\"\n    moreover\n    note \\<open>\\<beta>\\<in>\\<gamma>\\<close> \\<open>Cb \\<in> Pow(G)-?cdlt\\<gamma> \\<rightarrow> G\\<close>\n    ultimately\n    show \"Q(S ` \\<alpha>, S ` \\<beta>)\"\n      using fun_disjoint_apply1[of \"{S`x . x \\<in> \\<beta>}\" Cb f]\n        domain_of_fun[of Cb] ltD[of \\<alpha> \\<beta>]\n      by (subst (2) S_def, auto) (subst rec_constr_unfold, auto)\n  qed\n  ultimately\n  show ?thesis by blast\nqed\n\ntext\\<open>The following basic result can, in turn, be proved by a\n     bounded-cardinal selection.\\<close>\nlemma Infinite_iff_lepoll_nat: \"Infinite(X) \\<longleftrightarrow> \\<omega> \\<lesssim> X\"\nproof\n  assume \"Infinite(X)\"\n  then\n  obtain b where \"b\\<in>X\"\n    using Infinite_not_empty by auto\n  {\n    fix Y\n    assume \"|Y| < \\<omega>\"\n    then\n    have \"Finite(Y)\"\n      using Finite_cardinal_iff' ltD nat_into_Finite by blast\n    with \\<open>Infinite(X)\\<close>\n    have \"X \\<noteq> Y\" by auto\n  }\n  with \\<open>b\\<in>X\\<close>\n  obtain S where \"S : \\<omega> \\<rightarrow> X\"  \"\\<forall>\\<alpha>\\<in>\\<omega>. \\<forall>\\<beta>\\<in>\\<omega>. \\<alpha> < \\<beta> \\<longrightarrow> S`\\<alpha> \\<noteq> S`\\<beta>\"\n    using bounded_cardinal_selection[of \\<omega> X \"\\<lambda>x y. x\\<noteq>y\"]\n      Card_nat by blast\n  moreover from this\n  have \"\\<alpha> \\<in> \\<omega> \\<Longrightarrow> \\<beta> \\<in> \\<omega> \\<Longrightarrow> \\<alpha>\\<noteq>\\<beta> \\<Longrightarrow> S`\\<alpha> \\<noteq> S`\\<beta>\" for \\<alpha> \\<beta>\n    by (rule_tac lt_neq_symmetry[of \"\\<omega>\" \"\\<lambda>\\<alpha> \\<beta>. S`\\<alpha> \\<noteq> S`\\<beta>\"])\n      auto\n  ultimately\n  show \"\\<omega> \\<lesssim> X\"\n    unfolding lepoll_def inj_def by blast\nqed (intro lepoll_nat_imp_Infinite)\n\nlemma Infinite_InfCard_cardinal: \"Infinite(X) \\<Longrightarrow> InfCard(|X|)\"\n  using lepoll_eq_trans eqpoll_sym lepoll_nat_imp_Infinite\n    Infinite_iff_lepoll_nat Inf_Card_is_InfCard cardinal_eqpoll\n  by simp\n\nlemma Finite_to_one_surj_imp_cardinal_eq:\n  assumes \"F \\<in> Finite_to_one(X,Y) \\<inter> surj(X,Y)\" \"Infinite(X)\"\n  shows \"|Y| = |X|\"\nproof -\n  from \\<open>F \\<in> Finite_to_one(X,Y) \\<inter> surj(X,Y)\\<close>\n  have \"X = (\\<Union>y\\<in>Y. {x\\<in>X . F`x = y})\"\n    using apply_type by fastforce\n  show ?thesis\n  proof (cases \"Finite(Y)\")\n    case True\n    with \\<open>X = (\\<Union>y\\<in>Y. {x\\<in>X . F`x = y})\\<close> and assms\n    show ?thesis\n      using Finite_RepFun[THEN [2] Finite_Union, of Y \"\\<lambda>y. {x\\<in>X . F`x = y}\"]\n      by auto\n  next\n    case False\n    moreover from this\n    have \"Y \\<lesssim> |Y|\"\n      using cardinal_eqpoll eqpoll_sym eqpoll_imp_lepoll by simp\n    moreover\n    note assms\n    moreover from calculation\n    have \"y \\<in> Y \\<Longrightarrow> |{x\\<in>X . F`x = y}| \\<le> |Y|\" for y\n      using Infinite_imp_nats_lepoll[THEN lepoll_imp_cardinal_le, of Y\n          \"|{x\\<in>X . F`x = y}|\"] cardinal_idem by auto\n    ultimately\n    have \"|\\<Union>y\\<in>Y. {x\\<in>X . F`x = y}| \\<le> |Y|\"\n      using lepoll_imp_cardinal_UN_le[of \"|Y|\" Y]\n        Infinite_InfCard_cardinal[of Y] by simp\n    moreover from \\<open>F \\<in> Finite_to_one(X,Y) \\<inter> surj(X,Y)\\<close>\n    have \"|Y| \\<le> |X|\"\n      using surj_implies_cardinal_le by auto\n    moreover\n    note \\<open>X = (\\<Union>y\\<in>Y. {x\\<in>X . F`x = y})\\<close>\n    ultimately\n    show ?thesis\n      using le_anti_sym by auto\n  qed\nqed\n\nlemma cardinal_map_Un:\n  assumes \"Infinite(X)\" \"Finite(b)\"\n  shows \"|{a \\<union> b . a \\<in> X}| = |X|\"\nproof -\n  have \"(\\<lambda>a\\<in>X. a \\<union> b) \\<in> Finite_to_one(X,{a \\<union> b . a \\<in> X})\"\n    \"(\\<lambda>a\\<in>X. a \\<union> b) \\<in>  surj(X,{a \\<union> b . a \\<in> X})\"\n    unfolding surj_def\n  proof\n    fix d\n    have \"Finite({a \\<in> X . a \\<union> b = d})\" (is \"Finite(?Y(b,d))\")\n      using \\<open>Finite(b)\\<close>\n    proof (induct arbitrary:d)\n      case 0\n      have \"{a \\<in> X . a \\<union> 0 = d} = (if d\\<in>X then {d} else 0)\"\n        by auto\n      then\n      show ?case by simp\n    next\n      case (cons c b)\n      from \\<open>c \\<notin> b\\<close>\n      have \"?Y(cons(c,b),d) \\<subseteq> (if c\\<in>d then ?Y(b,d) \\<union> ?Y(b,d-{c}) else 0)\"\n        by auto\n      with cons\n      show ?case\n        using subset_Finite\n        by simp\n    qed\n    moreover\n    assume \"d \\<in> {x \\<union> b . x \\<in> X}\"\n    ultimately\n    show \"Finite({a \\<in> X . (\\<lambda>x\\<in>X. x \\<union> b) ` a = d})\"\n      by simp\n  qed (auto intro:lam_funtype)\n  with assms\n  show ?thesis\n    using Finite_to_one_surj_imp_cardinal_eq by fast\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/Delta_System_Lemma/Cardinal_Library.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8976952866333483, "lm_q2_score": 0.8104789063814616, "lm_q1q2_score": 0.7275630941743888}}
{"text": "(*  Title:      FOLP/ex/Nat.thy\n    Author:     Lawrence C Paulson, Cambridge University Computer Laboratory\n    Copyright   1992  University of Cambridge\n*)\n\nsection {* Theory of the natural numbers: Peano's axioms, primitive recursion *}\n\ntheory Nat\nimports FOLP\nbegin\n\ntypedecl nat\ninstance nat :: \"term\" ..\n\naxiomatization\n  Zero :: nat    (\"0\") and\n  Suc :: \"nat => nat\" and\n  rec :: \"[nat, 'a, [nat, 'a] => 'a] => 'a\" and\n\n  (*Proof terms*)\n  nrec :: \"[nat, p, [nat, p] => p] => p\" and\n  ninj :: \"p => p\" and\n  nneq :: \"p => p\" and\n  rec0 :: \"p\" and\n  recSuc :: \"p\"\nwhere\n  induct:     \"[| b:P(0); !!x u. u:P(x) ==> c(x,u):P(Suc(x))\n              |] ==> nrec(n,b,c):P(n)\" and\n\n  Suc_inject: \"p:Suc(m)=Suc(n) ==> ninj(p) : m=n\" and\n  Suc_neq_0:  \"p:Suc(m)=0      ==> nneq(p) : R\" and\n  rec_0:      \"rec0 : rec(0,a,f) = a\" and\n  rec_Suc:    \"recSuc : rec(Suc(m), a, f) = f(m, rec(m,a,f))\" and\n  nrecB0:     \"b: A ==> nrec(0,b,c) = b : A\" and\n  nrecBSuc:   \"c(n,nrec(n,b,c)) : A ==> nrec(Suc(n),b,c) = c(n,nrec(n,b,c)) : A\"\n\ndefinition add :: \"[nat, nat] => nat\"    (infixl \"+\" 60)\n  where \"m + n == rec(m, n, %x y. Suc(y))\"\n\n\nsubsection {* Proofs about the natural numbers *}\n\nschematic_lemma Suc_n_not_n: \"?p : ~ (Suc(k) = k)\"\napply (rule_tac n = k in induct)\napply (rule notI)\napply (erule Suc_neq_0)\napply (rule notI)\napply (erule notE)\napply (erule Suc_inject)\ndone\n\nschematic_lemma \"?p : (k+m)+n = k+(m+n)\"\napply (rule induct)\nback\nback\nback\nback\nback\nback\noops\n\nschematic_lemma add_0 [simp]: \"?p : 0+n = n\"\napply (unfold add_def)\napply (rule rec_0)\ndone\n\nschematic_lemma add_Suc [simp]: \"?p : Suc(m)+n = Suc(m+n)\"\napply (unfold add_def)\napply (rule rec_Suc)\ndone\n\n\nschematic_lemma Suc_cong: \"p : x = y \\<Longrightarrow> ?p : Suc(x) = Suc(y)\"\n  apply (erule subst)\n  apply (rule refl)\n  done\n\nschematic_lemma Plus_cong: \"[| p : a = x;  q: b = y |] ==> ?p : a + b = x + y\"\n  apply (erule subst, erule subst, rule refl)\n  done\n\nlemmas nat_congs = Suc_cong Plus_cong\n\nML {*\n  val add_ss = FOLP_ss addcongs @{thms nat_congs} addrews [@{thm add_0}, @{thm add_Suc}]\n*}\n\nschematic_\n\nschematic_lemma add_0_right: \"?p : m+0 = m\"\napply (rule_tac n = m in induct)\napply (tactic {* SIMP_TAC add_ss 1 *})\napply (tactic {* ASM_SIMP_TAC add_ss 1 *})\ndone\n\nschematic_lemma add_Suc_right: \"?p : m+Suc(n) = Suc(m+n)\"\napply (rule_tac n = m in induct)\napply (tactic {* ALLGOALS (ASM_SIMP_TAC add_ss) *})\ndone\n\n(*mk_typed_congs appears not to work with FOLP's version of subst*)\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/FOLP/ex/Nat.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278726384089, "lm_q2_score": 0.8244619242200082, "lm_q1q2_score": 0.7275281818608309}}
{"text": "section \"Arithmetic and Boolean Expressions\"\n\ntheory LExp \nimports \"~~/src/HOL/IMP/BExp\"\n        \"~~/src/HOL/IMP/ASM\"\nbegin\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 x) s = s x\" |\n\"lval (Plusl a\\<^sub>1 a\\<^sub>2) s = (lval a\\<^sub>1 s) + (lval a\\<^sub>2 s)\" |\n\"lval (LET x a\\<^sub>1 a\\<^sub>2) s = (let e = lval a\\<^sub>1 s in lval a\\<^sub>2 (s(x := e)))\"\n\nvalue \"lval (Plusl (Vl ''x'') (Nl 5)) (\\<lambda>x. if x = ''x'' then 7 else 0)\"\nvalue \"lval (Plusl (Vl ''x'') (Nl 5)) ((\\<lambda>x. 0) (''x'':= 7))\"\nvalue \"lval (Plusl (Vl ''x'') (Nl 5)) <''x'':= 7>\"\nvalue \"lval (Plusl (Vl ''x'') (Nl 5)) <''y'':= 7>\"\nvalue \"lval (Plusl (Vl ''x'') (Nl 5)) <''x'':= 7, ''x'' := 5>\"\nvalue \"lval (LET ''y'' (Nl 3) (Plusl (Vl ''y'') (Vl ''x''))) ((\\<lambda>x. 0) (''x'':= 7))\"\n\nfun asubst :: \"vname \\<Rightarrow> aexp \\<Rightarrow> aexp \\<Rightarrow> aexp\" where\n\"asubst x a (N n) = N n\" |\n\"asubst x a (V y) = (if x = y then a else V y)\" |\n\"asubst x a (Plus e1 e2) = Plus (asubst x a e1) (asubst x a e2)\"\n\nvalue \"asubst ''x'' (N 3) (Plus (V ''x'' ) (V ''y''))\"\n\nfun lsubst :: \"vname \\<Rightarrow> lexp \\<Rightarrow> lexp \\<Rightarrow> lexp\" where\n\"lsubst x a (Nl n) = Nl n\" |\n\"lsubst x a (Vl y) = (if x = y then a else Vl y)\" |\n\"lsubst x a (Plusl e1 e2) = Plusl (lsubst x a e1) (lsubst x a e2)\" |\n\"lsubst x a (LET y e1 e2) = LET y (lsubst x a e1) (lsubst x a e2)\"\n  \nfun inline :: \"lexp \\<Rightarrow> aexp\" where\n\"inline (Nl n) = N n\" |\n\"inline (Vl x) = V x\" |\n\"inline (Plusl e1 e2) = Plus (inline e1) (inline e2)\" |\n\"inline (LET x e1 e2) = \n    (let a1 = inline e1 in\n     let a2 = inline e2 in\n     asubst x a1 a2)\"\n\nvalue \"inline (Nl 2)\"\nvalue \"inline (Vl ''x'')\"\nvalue \"inline (LET ''x'' (Nl 1) (Vl ''x''))\"\nvalue \"inline (LET ''x'' (Nl 1) (Plusl (Vl ''y'') (Vl ''x'')))\"\nvalue \"inline (LET ''x'' (Nl 1) (Plusl (Vl ''x'') (Vl ''x'')))\"\n\nlemma aval_subst [simp]:\"aval (asubst x a1 a2) s = aval a2 (s(x := aval a1 s))\"\napply(induction a2)\napply(auto)\ndone\n\nlemma \"lval a s = aval (inline a) s\"\napply(induction a arbitrary: s)\napply(auto)\ndone\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/LExp.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278664544912, "lm_q2_score": 0.8244619285331332, "lm_q1q2_score": 0.7275281805684479}}
{"text": "(* Title:      Residuated Boolean Algebras\n   Author:     Victor Gomes <vborgesferreiragomes1 at sheffield.ac.uk>\n   Maintainer: Georg Struth <g.struth@sheffield.ac.uk> \n*)\n\nsection \\<open>Residuated Boolean Algebras\\<close>\n\ntheory Residuated_Boolean_Algebras\n  imports Residuated_Lattices\nbegin\n\nsubsection \\<open>Conjugation on Boolean Algebras\\<close>\n\ntext \\<open>\n  Similarly, as in the previous section, we define the conjugation for\n  arbitrary residuated functions on boolean algebras.\n\\<close>\n\ncontext boolean_algebra\nbegin\n\nlemma inf_bot_iff_le: \"x \\<sqinter> y = \\<bottom> \\<longleftrightarrow> x \\<le> -y\"\n  by (metis le_iff_inf inf_sup_distrib1 inf_top_right sup_bot.left_neutral sup_compl_top compl_inf_bot inf.assoc inf_bot_right)\n\nlemma le_iff_inf_bot: \"x \\<le> y \\<longleftrightarrow> x \\<sqinter> -y = \\<bottom>\"\n  by (metis inf_bot_iff_le compl_le_compl_iff inf_commute)\n  \nlemma indirect_eq: \"(\\<And>z. x \\<le> z \\<longleftrightarrow> y \\<le> z) \\<Longrightarrow> x = y\"\n  by (metis eq_iff)\n\ntext \\<open>\n  Let $B$ be a boolean algebra. The maps $f$ and $g$ on $B$ are\n  a pair of conjugates if and only if for all $x, y \\in B$,\n  $f(x) \\sqcap y = \\bot \\Leftrightarrow x \\sqcap g(t) = \\bot$.\n\\<close>\n  \ndefinition conjugation_pair :: \"('a \\<Rightarrow> 'a) \\<Rightarrow> ('a \\<Rightarrow> 'a) \\<Rightarrow> bool\" where\n  \"conjugation_pair f g \\<equiv> \\<forall>x y. f(x) \\<sqinter> y = \\<bottom> \\<longleftrightarrow> x \\<sqinter> g(y) = \\<bottom>\"\n\nlemma conjugation_pair_commute: \"conjugation_pair f g \\<Longrightarrow> conjugation_pair g f\"\n  by (auto simp: conjugation_pair_def inf_commute)\n  \nlemma conjugate_iff_residuated: \"conjugation_pair f g = residuated_pair f (\\<lambda>x. -g(-x))\"\n  apply (clarsimp simp: conjugation_pair_def residuated_pair_def inf_bot_iff_le)\n  by (metis double_compl)\n\nlemma conjugate_residuated: \"conjugation_pair f g \\<Longrightarrow> residuated_pair f (\\<lambda>x. -g(-x))\"\n  by (metis conjugate_iff_residuated)\n  \nlemma residuated_iff_conjugate: \"residuated_pair f g = conjugation_pair f (\\<lambda>x. -g(-x))\"\n  apply (clarsimp simp: conjugation_pair_def residuated_pair_def inf_bot_iff_le)\n  by (metis double_compl)\n\ntext \\<open>\n  A map $f$ has a conjugate pair if and only if it is residuated.\n\\<close>\n  \nlemma conj_residuatedI1: \"\\<exists>g. conjugation_pair f g \\<Longrightarrow> residuated f\"\n  by (metis conjugate_iff_residuated residuated_def)\n  \nlemma conj_residuatedI2: \"\\<exists>g. conjugation_pair g f \\<Longrightarrow> residuated f\"\n  by (metis conj_residuatedI1 conjugation_pair_commute)\n  \nlemma exist_conjugateI[intro]: \"residuated f \\<Longrightarrow> \\<exists>g. conjugation_pair f g\"\n  by (metis residuated_def residuated_iff_conjugate)\n  \nlemma exist_conjugateI2[intro]: \"residuated f \\<Longrightarrow> \\<exists>g. conjugation_pair g f\"\n  by (metis exist_conjugateI conjugation_pair_commute)\n\ntext \\<open>\n  The conjugate of a residuated function $f$ is unique.\n\\<close>\n\nlemma unique_conjugate[intro]: \"residuated f \\<Longrightarrow> \\<exists>!g. conjugation_pair f g\"\nproof - \n  {\n    fix g h x assume \"conjugation_pair f g\" and \"conjugation_pair f h\"\n    hence \"g = h\"\n      apply (unfold conjugation_pair_def)\n      apply (rule ext)\n      apply (rule antisym)\n      by (metis le_iff_inf_bot inf_commute inf_compl_bot)+\n  } \n  moreover assume \"residuated f\"\n  ultimately show ?thesis by force\nqed\n  \nlemma unique_conjugate2[intro]: \"residuated f \\<Longrightarrow> \\<exists>!g. conjugation_pair g f\"\n  by (metis unique_conjugate conjugation_pair_commute)\n\ntext \\<open>\n  Since the conjugate of a residuated map is unique, we define a\n  conjugate operation.\n\\<close>\n  \ndefinition conjugate :: \"('a \\<Rightarrow> 'a) \\<Rightarrow> ('a \\<Rightarrow> 'a)\" where\n  \"conjugate f \\<equiv> THE g. conjugation_pair g f\"\n\nlemma conjugate_iff_def: \"residuated f \\<Longrightarrow> f(x) \\<sqinter> y = \\<bottom> \\<longleftrightarrow> x \\<sqinter> conjugate f y = \\<bottom>\"\n  apply (clarsimp simp: conjugate_def dest!: unique_conjugate)\n  apply (subgoal_tac \"(THE g. conjugation_pair g f) = g\")\n  apply (clarsimp simp add: conjugation_pair_def)\n  apply (rule the1_equality)\n  by (auto intro: conjugation_pair_commute)\n    \nlemma conjugateI1: \"residuated f \\<Longrightarrow> f(x) \\<sqinter> y = \\<bottom> \\<Longrightarrow> x \\<sqinter> conjugate f y = \\<bottom>\"\n  by (metis conjugate_iff_def)\n  \nlemma conjugateI2: \"residuated f \\<Longrightarrow> x \\<sqinter> conjugate f y = \\<bottom> \\<Longrightarrow> f(x) \\<sqinter> y = \\<bottom>\"\n  by (metis conjugate_iff_def)\n\ntext \\<open>\n  Few more lemmas about conjugation follow.\n\\<close>\n  \nlemma residuated_conj1: \"residuated f \\<Longrightarrow> conjugation_pair f (conjugate f)\"\n  using conjugateI1 conjugateI2 conjugation_pair_def by auto\n  \nlemma residuated_conj2: \"residuated f \\<Longrightarrow> conjugation_pair (conjugate f) f\"\n  using conjugateI1 conjugateI2 conjugation_pair_def inf_commute by auto\n  \nlemma conj_residuated: \"residuated f \\<Longrightarrow> residuated (conjugate f)\"\n  by (force dest!: residuated_conj2 intro: conj_residuatedI1)\n  \nlemma conj_involution: \"residuated f \\<Longrightarrow> conjugate (conjugate f) = f\"\n  by (metis conj_residuated residuated_conj1 residuated_conj2 unique_conjugate)\n  \nlemma residual_conj_eq: \"residuated f \\<Longrightarrow> residual (conjugate f) = (\\<lambda>x. -f(-x))\"\n  apply (unfold residual_def)\n  apply (rule the1_equality)\n  apply (rule residual_unique)\n  apply (auto intro: conj_residuated conjugate_residuated residuated_conj2)\ndone\n  \nlemma residual_conj_eq_ext: \"residuated f \\<Longrightarrow> residual (conjugate f) x = -f(-x)\"\n  by (metis residual_conj_eq)\n  \nlemma conj_iso: \"residuated f \\<Longrightarrow> x \\<le> y \\<Longrightarrow> conjugate f x \\<le> conjugate f y\"\n  by (metis conj_residuated res_iso)\n  \nlemma conjugate_strict: \"residuated f \\<Longrightarrow> conjugate f \\<bottom> = \\<bottom>\"\n  by (metis conj_residuated residuated_strict)\n\nlemma conjugate_sup: \"residuated f \\<Longrightarrow> conjugate f (x \\<squnion> y) = conjugate f x \\<squnion> conjugate f y\"\n  by (metis conj_residuated residuated_sup)\n\nlemma conjugate_subinf: \"residuated f \\<Longrightarrow> conjugate f (x \\<sqinter> y) \\<le> conjugate f x \\<sqinter> conjugate f y\"\n  by (auto simp: conj_iso)\n \ntext \\<open>\n  Next we prove some lemmas from Maddux's article. Similar lemmas have been proved in AFP entry\n  for relation algebras. They should be consolidated in the future.\n\\<close>\n\nlemma maddux1: \"residuated f \\<Longrightarrow> f(x \\<sqinter> - conjugate f(y)) \\<le> f(x) \\<sqinter> -y\"\nproof -\n  assume assm: \"residuated f\"\n  hence \"f(x \\<sqinter> - conjugate f(y)) \\<le> f x\"\n    by (metis inf_le1 res_iso)\n  moreover have \"f(x \\<sqinter> - conjugate f (y)) \\<sqinter> y = \\<bottom>\"\n    by (metis assm conjugateI2 inf_bot_iff_le inf_le2)\n  ultimately show ?thesis\n    by (metis inf_bot_iff_le le_inf_iff)\nqed\n\nlemma maddux1': \"residuated f \\<Longrightarrow> conjugate f(x \\<sqinter> -f(y)) \\<le> conjugate f(x) \\<sqinter> -y\"\n  by (metis conj_involution conj_residuated maddux1)\n  \nlemma maddux2: \"residuated f \\<Longrightarrow> f(x) \\<sqinter> y \\<le> f(x \\<sqinter> conjugate f y)\"\nproof -\n  assume resf: \"residuated f\"\n  obtain z where z_def: \"z = f(x \\<sqinter> conjugate f y)\" by auto\n  hence \"f(x \\<sqinter> conjugate f y) \\<sqinter> -z = \\<bottom>\"\n    by (metis inf_compl_bot)\n  hence \"x \\<sqinter> conjugate f y \\<sqinter> conjugate f (-z) = \\<bottom>\"\n    by (metis conjugate_iff_def resf)\n  hence \"x \\<sqinter> conjugate f (y \\<sqinter> -z) = \\<bottom>\"\n    apply (subgoal_tac \"conjugate f (y \\<sqinter> -z) \\<le> conjugate f y \\<sqinter> conjugate f (-z)\")\n    apply (metis (no_types, hide_lams) dual_order.trans inf.commute inf_bot_iff_le inf_left_commute)\n    by (metis conj_iso inf_le2 inf_top.left_neutral le_inf_iff resf)\n  hence \"f(x) \\<sqinter> y \\<sqinter> -z = \\<bottom>\"\n    by (metis conjugateI2 inf.assoc resf)\n  thus ?thesis\n    by (metis double_compl inf_bot_iff_le z_def)\nqed\n\nlemma maddux2': \"residuated f \\<Longrightarrow> conjugate f(x) \\<sqinter> y \\<le> conjugate f(x \\<sqinter> f y)\"\n  by (metis conj_involution conj_residuated maddux2)\n  \nlemma residuated_conjugate_ineq: \"residuated f \\<Longrightarrow> conjugate f x \\<le> y \\<longleftrightarrow> x \\<le> -f(-y)\"\n  by (metis conj_residuated residual_galois residual_conj_eq)\n\nlemma residuated_comp_closed: \"residuated f \\<Longrightarrow> residuated g \\<Longrightarrow> residuated (f o g)\"\n  by (auto simp add: residuated_def residuated_pair_def)\n  \nlemma conjugate_comp: \"residuated f \\<Longrightarrow> residuated g \\<Longrightarrow> conjugate (f o g) = conjugate g o conjugate f\"\nproof (rule ext, rule indirect_eq)\n  fix x y\n  assume assms: \"residuated f\" \"residuated g\" \n  have \"conjugate (f o g) x \\<le> y \\<longleftrightarrow> x \\<le> -f(g(-y))\"\n    apply (subst residuated_conjugate_ineq)\n    using assms by (auto intro!: residuated_comp_closed)\n  also have \"... \\<longleftrightarrow> conjugate g (conjugate f x) \\<le> y\"\n    using assms by (simp add: residuated_conjugate_ineq)\n  finally show \"(conjugate (f \\<circ> g) x \\<le> y) = ((conjugate g \\<circ> conjugate f) x \\<le> y)\"   \n    by auto\nqed \n\nlemma conjugate_comp_ext: \"residuated f \\<Longrightarrow> residuated g \\<Longrightarrow> conjugate (\\<lambda>x. f (g x)) x = conjugate g (conjugate f x)\"\n  using conjugate_comp by (simp add: comp_def)\n  \nend (* boolean_algebra *)\n\ncontext complete_boolean_algebra begin\n\ntext \\<open>\n  On a complete boolean algebra, it is possible to give an explicit\n  definition of conjugation.\n\\<close>\n\nlemma conjugate_eq: \"residuated f \\<Longrightarrow> conjugate f y = \\<Sqinter>{x. y \\<le> -f(-x)}\"\nproof -\n  assume assm: \"residuated f\" obtain g where g_def: \"g = conjugate f\" by auto\n  have \"g y = \\<Sqinter>{x. x \\<ge> g y}\"\n    by (auto intro!: antisym Inf_lower Inf_greatest)\n  also have \"... = \\<Sqinter>{x. -x \\<sqinter> g y = \\<bottom>}\"\n    by (simp add: inf_bot_iff_le)\n  also have \"... = \\<Sqinter>{x. f(-x) \\<sqinter> y = \\<bottom>}\"\n    by (metis conjugate_iff_def assm g_def)\n  finally show ?thesis\n    by (simp add: g_def le_iff_inf_bot inf_commute)\nqed\n\nend (* complete_boolean_algebra *)\n\nsubsection \\<open>Residuated Boolean Structures\\<close>\n\ntext \\<open>\n  In this section, we present various residuated structures based on\n  boolean algebras.\n  The left and right conjugation of the multiplicative operation is\n  defined, and a number of facts is derived.\n\\<close>\n\nclass residuated_boolean_algebra = boolean_algebra + residuated_pogroupoid\nbegin\n\nsubclass residuated_lgroupoid ..\n\ndefinition conjugate_l :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a\" (infixl \"\\<lhd>\" 60) where\n  \"x \\<lhd> y \\<equiv> -(-x \\<leftarrow> y)\"\n\ndefinition conjugate_r :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a\" (infixl \"\\<rhd>\" 60) where\n  \"x \\<rhd> y \\<equiv> -(x \\<rightarrow> -y)\"\n  \nlemma residual_conjugate_r: \"x \\<rightarrow> y = -(x \\<rhd> -y)\"\n  by (metis conjugate_r_def double_compl)\n  \nlemma residual_conjugate_l: \"x \\<leftarrow> y = -(-x \\<lhd> y)\"\n  by (metis conjugate_l_def double_compl)\n  \nlemma conjugation_multl: \"x\\<cdot>y \\<sqinter> z = \\<bottom> \\<longleftrightarrow> x \\<sqinter> (z \\<lhd> y) = \\<bottom>\"\n  by (metis conjugate_l_def double_compl le_iff_inf_bot resl_galois)\n\nlemma conjugation_multr: \"x\\<cdot>y \\<sqinter> z = \\<bottom> \\<longleftrightarrow> y \\<sqinter> (x \\<rhd> z) = \\<bottom>\"\n  by (metis conjugate_r_def inf_bot_iff_le le_iff_inf_bot resr_galois)\n  \nlemma conjugation_conj: \"(x \\<lhd> y) \\<sqinter> z = \\<bottom> \\<longleftrightarrow> y \\<sqinter> (z \\<rhd> x) = \\<bottom>\"\n  by (metis inf_commute conjugation_multr conjugation_multl)\n\nlemma conjugation_pair_multl [simp]: \"conjugation_pair (\\<lambda>x. x\\<cdot>y) (\\<lambda>x. x \\<lhd> y)\"\n  by (simp add: conjugation_pair_def conjugation_multl)\n  \nlemma conjugation_pair_multr [simp]: \"conjugation_pair (\\<lambda>x. y\\<cdot>x) (\\<lambda>x. y \\<rhd> x)\"\n  by (simp add: conjugation_pair_def conjugation_multr)\n  \nlemma conjugation_pair_conj [simp]: \"conjugation_pair (\\<lambda>x. y \\<lhd> x) (\\<lambda>x. x \\<rhd> y)\"\n  by (simp add: conjugation_pair_def conjugation_conj)\n  \nlemma residuated_conjl1 [simp]: \"residuated (\\<lambda>x. x \\<lhd> y)\" \n  by (metis conj_residuatedI2 conjugation_pair_multl)\n  \nlemma residuated_conjl2 [simp]: \"residuated (\\<lambda>x. y \\<lhd> x)\" \n  by (metis conj_residuatedI1 conjugation_pair_conj)\n  \nlemma residuated_conjr1 [simp]: \"residuated (\\<lambda>x. y \\<rhd> x)\" \n  by (metis conj_residuatedI2 conjugation_pair_multr)\n  \nlemma residuated_conjr2 [simp]: \"residuated (\\<lambda>x. x \\<rhd> y)\" \n  by (metis conj_residuatedI2 conjugation_pair_conj)\n  \nlemma conjugate_multr [simp]: \"conjugate (\\<lambda>x. y\\<cdot>x) = (\\<lambda>x. y \\<rhd> x)\"\n  by (metis conjugation_pair_multr residuated_conj1 residuated_multr unique_conjugate)\n  \nlemma conjugate_conjr1 [simp]: \"conjugate (\\<lambda>x. y \\<rhd> x) = (\\<lambda>x. y\\<cdot>x)\"\n  by (metis conjugate_multr conj_involution residuated_multr)\n  \nlemma conjugate_multl [simp]: \"conjugate (\\<lambda>x. x\\<cdot>y) = (\\<lambda>x. x \\<lhd> y)\"\n  by (metis conjugation_pair_multl residuated_conj1 residuated_multl unique_conjugate)\n \nlemma conjugate_conjl1 [simp]: \"conjugate (\\<lambda>x. x \\<lhd> y) = (\\<lambda>x. x\\<cdot>y)\"\nproof -\n  have \"conjugate (conjugate (\\<lambda>x. x\\<cdot>y)) = conjugate (\\<lambda>x. x \\<lhd> y)\" by simp\n  thus ?thesis\n    by (metis conj_involution[OF residuated_multl])\nqed\n\nlemma conjugate_conjl2[simp]: \"conjugate (\\<lambda>x. y \\<lhd> x) = (\\<lambda>x. x \\<rhd> y)\"\n  by (metis conjugation_pair_conj unique_conjugate residuated_conj1 residuated_conjl2)\n\nlemma conjugate_conjr2[simp]: \"conjugate (\\<lambda>x. x \\<rhd> y) = (\\<lambda>x. y \\<lhd> x)\"\nproof -\n  have \"conjugate (conjugate (\\<lambda>x. y \\<lhd> x)) = conjugate (\\<lambda>x. x \\<rhd> y)\" by simp\n  thus ?thesis\n    by (metis conj_involution[OF residuated_conjl2])\nqed\n\nlemma conjl1_iso: \"x \\<le> y \\<Longrightarrow> x \\<lhd> z \\<le> y \\<lhd> z\"\n  by (metis conjugate_l_def compl_mono resl_iso)\n\nlemma conjl2_iso: \"x \\<le> y \\<Longrightarrow> z \\<lhd> x \\<le> z \\<lhd> y\"\n  by (metis res_iso residuated_conjl2)\n\nlemma conjr1_iso: \"x \\<le> y \\<Longrightarrow> z \\<rhd> x \\<le> z \\<rhd> y\"\n  by (metis res_iso residuated_conjr1)\n\nlemma conjr2_iso: \"x \\<le> y \\<Longrightarrow> x \\<rhd> z \\<le> y \\<rhd> z\"\n  by (metis conjugate_r_def compl_mono resr_antitonel)\n\nlemma conjl1_sup: \"z \\<lhd> (x \\<squnion> y) = (z \\<lhd> x) \\<squnion> (z \\<lhd> y)\"\n  by (metis conjugate_l_def compl_inf resl_distr)\n\nlemma conjl2_sup: \"(x \\<squnion> y) \\<lhd> z = (x \\<lhd> z) \\<squnion> (y \\<lhd> z)\"\n  by (metis (poly_guards_query) residuated_sup residuated_conjl1)\n\nlemma conjr1_sup: \"z \\<rhd> (x \\<squnion> y) = (z \\<rhd> x) \\<squnion> (z \\<rhd> y)\"\n  by (metis residuated_sup residuated_conjr1)\n\nlemma conjr2_sup: \"(x \\<squnion> y) \\<rhd> z = (x \\<rhd> z) \\<squnion> (y \\<rhd> z)\"\n  by (metis conjugate_r_def compl_inf resr_distl)\n\nlemma conjl1_strict: \"\\<bottom> \\<lhd> x = \\<bottom>\"\n  by (metis residuated_strict residuated_conjl1)\n\nlemma conjl2_strict: \"x \\<lhd> \\<bottom> = \\<bottom>\"\n  by (metis residuated_strict residuated_conjl2)\n\nlemma conjr1_strict: \"\\<bottom> \\<rhd> x = \\<bottom>\"\n  by (metis residuated_strict residuated_conjr2)\n\nlemma conjr2_strict: \"x \\<rhd> \\<bottom> = \\<bottom>\"\n  by (metis residuated_strict residuated_conjr1)\n\nlemma conjl1_iff: \"x \\<lhd> y \\<le> z \\<longleftrightarrow> x \\<le> -(-z\\<cdot>y)\"\n  by (metis conjugate_l_def compl_le_swap1 compl_le_swap2 resl_galois)\n\nlemma conjl2_iff: \"x \\<lhd> y \\<le> z \\<longleftrightarrow> y \\<le> -(-z \\<rhd> x)\"\n  by (metis conjl1_iff conjugate_r_def compl_le_swap2 double_compl resr_galois)\n\nlemma conjr1_iff: \"x \\<rhd> y \\<le> z \\<longleftrightarrow> y \\<le> -(x\\<cdot>-z)\"\n  by (metis conjugate_r_def compl_le_swap1 double_compl resr_galois)\n\nlemma conjr2_iff: \"x \\<rhd> y \\<le> z \\<longleftrightarrow> x \\<le> -(y \\<lhd> -z)\"\n  by (metis conjugation_conj double_compl inf.commute le_iff_inf_bot)\n\ntext \\<open>\n  We apply Maddux's lemmas regarding conjugation of an arbitrary residuated function \n  for each of the 6 functions.\n\\<close>\n  \nlemma maddux1a: \"a\\<cdot>(x \\<sqinter> -(a \\<rhd> y)) \\<le> a\\<cdot>x\"\n  by (insert maddux1 [of \"\\<lambda>x. a\\<cdot>x\"]) simp\n  \nlemma maddux1a': \"a\\<cdot>(x \\<sqinter> -(a \\<rhd> y)) \\<le> -y\"\n  by (insert maddux1 [of \"\\<lambda>x. a\\<cdot>x\"]) simp\n  \nlemma maddux1b: \"(x \\<sqinter> -(y \\<lhd> a))\\<cdot>a \\<le> x\\<cdot>a\"\n  by (insert maddux1 [of \"\\<lambda>x. x\\<cdot>a\"]) simp\n  \nlemma maddux1b': \"(x \\<sqinter> -(y \\<lhd> a))\\<cdot>a \\<le> -y\"\n  by (insert maddux1 [of \"\\<lambda>x. x\\<cdot>a\"]) simp\n  \nlemma maddux1c: \" a \\<lhd> x \\<sqinter> -(y \\<rhd> a) \\<le> a \\<lhd> x\"\n  by (insert maddux1 [of \"\\<lambda>x. a \\<lhd> x\"]) simp\n  \nlemma maddux1c': \"a \\<lhd> x \\<sqinter> -(y \\<rhd> a) \\<le> -y\"\n  by (insert maddux1 [of \"\\<lambda>x. a \\<lhd> x\"]) simp\n  \nlemma maddux1d: \"a \\<rhd> x \\<sqinter> -(a\\<cdot>y) \\<le> a \\<rhd> x\"\n  by (insert maddux1 [of \"\\<lambda>x. a \\<rhd> x\"]) simp\n  \nlemma maddux1d': \"a \\<rhd> x \\<sqinter> -(a\\<cdot>y) \\<le> -y\"\n  by (insert maddux1 [of \"\\<lambda>x. a \\<rhd> x\"]) simp\n\nlemma maddux1e: \"x \\<sqinter> -(y\\<cdot>a) \\<lhd> a \\<le> x \\<lhd> a\"\n  by (insert maddux1 [of \"\\<lambda>x. x \\<lhd> a\"]) simp\n  \nlemma maddux1e': \"x \\<sqinter> -(y\\<cdot>a) \\<lhd> a \\<le> -y\"\n  by (insert maddux1 [of \"\\<lambda>x. x \\<lhd> a\"]) simp\n  \nlemma maddux1f: \"x \\<sqinter> -(a \\<lhd> y) \\<rhd> a \\<le> x \\<rhd> a\"\n  by (insert maddux1 [of \"\\<lambda>x. x \\<rhd> a\"]) simp\n  \nlemma maddux1f': \"x \\<sqinter> -(a \\<lhd> y) \\<rhd> a \\<le> -y\"\n  by (insert maddux1 [of \"\\<lambda>x. x \\<rhd> a\"]) simp\n\nlemma maddux2a: \"a\\<cdot>x \\<sqinter> y \\<le> a\\<cdot>(x \\<sqinter> (a \\<rhd> y))\"\n  by (insert maddux2 [of \"\\<lambda>x. a\\<cdot>x\"]) simp\n  \nlemma maddux2b: \"x\\<cdot>a \\<sqinter> y \\<le> (x \\<sqinter> (y \\<lhd> a))\\<cdot>a\"\n  by (insert maddux2 [of \"\\<lambda>x. x\\<cdot>a\"]) simp\n  \nlemma maddux2c: \"(a \\<lhd> x) \\<sqinter> y \\<le> a \\<lhd> (x \\<sqinter> (y \\<rhd> a))\"\n  by (insert maddux2 [of \"\\<lambda>x. a \\<lhd> x\"]) simp\n  \nlemma maddux2d: \"(a \\<rhd> x) \\<sqinter> y \\<le> a \\<rhd> (x \\<sqinter> a\\<cdot>y)\"\n  by (insert maddux2 [of \"\\<lambda>x. a \\<rhd> x\"]) simp\n\nlemma maddux2e: \"(x \\<lhd> a) \\<sqinter> y \\<le> (x \\<sqinter> y\\<cdot>a) \\<lhd> a\"\n  by (insert maddux2 [of \"\\<lambda>x. x \\<lhd> a\"]) simp\n  \nlemma maddux2f: \"(x \\<rhd> a) \\<sqinter> y \\<le> (x \\<sqinter> (a \\<lhd> y)) \\<rhd> a\"\n  by (insert maddux2 [of \"\\<lambda>x. x \\<rhd> a\"]) simp\n  \ntext \\<open>\n  The multiplicative operation $\\cdot$ on a residuated boolean algebra is generally not\n  associative. We prove some equivalences related to associativity.\n\\<close>\n\nlemma res_assoc_iff1: \"(\\<forall>x y z. x\\<cdot>(y\\<cdot>z) = (x\\<cdot>y)\\<cdot>z) \\<longleftrightarrow> (\\<forall>x y z. x \\<rhd> (y \\<rhd> z) = y\\<cdot>x \\<rhd> z)\"\nproof safe\n  fix x y z assume \"\\<forall>x y z. x\\<cdot>(y\\<cdot>z) = (x\\<cdot>y)\\<cdot>z\"\n  thus \"x \\<rhd> (y \\<rhd> z) = y \\<cdot> x \\<rhd> z\"\n    using conjugate_comp_ext[of \"\\<lambda>z. y\\<cdot>z\" \"\\<lambda>z. x\\<cdot>z\"] by auto\nnext\n  fix x y z assume \"\\<forall>x y z. x \\<rhd> (y \\<rhd> z) = y\\<cdot>x \\<rhd> z\"\n  thus \"x\\<cdot>(y\\<cdot>z) = (x\\<cdot>y)\\<cdot>z\"\n    using conjugate_comp_ext[of \"\\<lambda>z. y \\<rhd> z\" \"\\<lambda>z. x \\<rhd> z\"] by auto\nqed\n\nlemma res_assoc_iff2: \"(\\<forall>x y z. x\\<cdot>(y\\<cdot>z) = (x\\<cdot>y)\\<cdot>z) \\<longleftrightarrow> (\\<forall>x y z. x \\<lhd> (y \\<cdot> z) = (x \\<lhd> z) \\<lhd> y)\"\nproof safe\n  fix x y z assume \"\\<forall>x y z. x\\<cdot>(y\\<cdot>z) = (x\\<cdot>y)\\<cdot>z\"\n  hence \"\\<forall>x y z. (x\\<cdot>y)\\<cdot>z = x\\<cdot>(y\\<cdot>z)\" by simp\n  thus \"x \\<lhd> (y \\<cdot> z) = (x \\<lhd> z) \\<lhd> y\"\n    using conjugate_comp_ext[of \"\\<lambda>x. x\\<cdot>z\" \"\\<lambda>x. x\\<cdot>y\"] by auto\nnext\n  fix x y z assume \"\\<forall>x y z. x \\<lhd> (y \\<cdot> z) = (x \\<lhd> z) \\<lhd> y\"\n  hence \"\\<forall>x y z. (x \\<lhd> z) \\<lhd> y = x \\<lhd> (y \\<cdot> z)\" by simp\n  thus \"x\\<cdot>(y\\<cdot>z) = (x\\<cdot>y)\\<cdot>z\" \n    using conjugate_comp_ext[of \"\\<lambda>z. z \\<lhd> y\" \"\\<lambda>x. x \\<lhd> z\"] by auto\nqed\n  \nlemma res_assoc_iff3: \"(\\<forall>x y z. x\\<cdot>(y\\<cdot>z) = (x\\<cdot>y)\\<cdot>z) \\<longleftrightarrow> (\\<forall>x y z. (x \\<rhd> y) \\<lhd> z = x \\<rhd> (y \\<lhd> z))\"\nproof safe\n  fix x y z assume \"\\<forall>x y z. x\\<cdot>(y\\<cdot>z) = (x\\<cdot>y)\\<cdot>z\"\n  thus \"(x \\<rhd> y) \\<lhd> z = x \\<rhd> (y \\<lhd> z)\"\n    using conjugate_comp_ext[of \"\\<lambda>u. x\\<cdot>u\" \"\\<lambda>u. u\\<cdot>z\"] and\n    conjugate_comp_ext[of \"\\<lambda>u. u\\<cdot>z\" \"\\<lambda>u. x\\<cdot>u\", symmetric]\n    by auto\nnext\n  fix x y z assume \"\\<forall>x y z. (x \\<rhd> y) \\<lhd> z = x \\<rhd> (y \\<lhd> z)\"\n  thus \"x\\<cdot>(y\\<cdot>z) = (x\\<cdot>y)\\<cdot>z\"\n    using conjugate_comp_ext[of \"\\<lambda>u. x \\<rhd> u\" \"\\<lambda>u. u \\<lhd> z\"] and\n    conjugate_comp_ext[of \"\\<lambda>u. u \\<lhd> z\" \"\\<lambda>u. x \\<rhd> u\", symmetric]\n    by auto\nqed\n\nend (* residuated_boolean_algebra *)\n\nclass unital_residuated_boolean = residuated_boolean_algebra + one +\n  assumes mult_onel [simp]: \"x\\<cdot>1 = x\"\n  and mult_oner [simp]: \"1\\<cdot>x = x\"\nbegin\n\ntext \\<open>\n  The following equivalences are taken from J{\\'o}sson and Tsinakis.\n\\<close>\n\nlemma jonsson1a: \"(\\<exists>f. \\<forall>x y. x \\<rhd> y = f(x)\\<cdot>y) \\<longleftrightarrow> (\\<forall>x y. x \\<rhd> y = (x \\<rhd> 1)\\<cdot>y)\"\n  apply standard\n  apply force\n  apply (rule_tac x=\"\\<lambda>x. x \\<rhd> 1\" in exI)\n  apply force\n  done\n  \nlemma jonsson1b: \"(\\<forall>x y. x \\<rhd> y = (x \\<rhd> 1)\\<cdot>y) \\<longleftrightarrow> (\\<forall>x y. x\\<cdot>y = (x \\<rhd> 1) \\<rhd> y)\"\nproof safe\n  fix x y\n  assume \"\\<forall>x y. x \\<rhd> y = (x \\<rhd> 1)\\<cdot>y\"\n  hence \"conjugate (\\<lambda>y. x \\<rhd> y) = conjugate (\\<lambda>y. (x \\<rhd> 1)\\<cdot>y)\" by metis\n  thus \"x\\<cdot>y = (x \\<rhd> 1) \\<rhd> y\" by simp\nnext\n  fix x y\n  assume \"\\<forall>x y. x \\<cdot> y = x \\<rhd> 1 \\<rhd> y\"\n  thus \"x \\<rhd> y = (x \\<rhd> 1) \\<cdot> y\"\n    by (metis mult_onel)\nqed\n\nlemma jonsson1c: \"(\\<forall>x y. x \\<rhd> y = (x \\<rhd> 1)\\<cdot>y) \\<longleftrightarrow> (\\<forall>x y. y \\<lhd> x = 1 \\<lhd> (x \\<lhd> y))\"\nproof safe\n  fix x y\n  assume \"\\<forall>x y. x \\<rhd> y = (x \\<rhd> 1)\\<cdot>y\"\n  hence \"(\\<lambda>x. x \\<rhd> y) = (\\<lambda>x. (x \\<rhd> 1)\\<cdot>y)\" by metis\n  hence \"(\\<lambda>x. x \\<rhd> y) = (\\<lambda>x. x\\<cdot>y) o (\\<lambda>x. x \\<rhd> 1)\" by force\n  hence \"conjugate (\\<lambda>x. y \\<lhd> x) = (\\<lambda>x. x\\<cdot>y) o conjugate (\\<lambda>x. 1 \\<lhd> x)\" by simp\n  hence \"conjugate (conjugate (\\<lambda>x. y \\<lhd> x)) = conjugate ((\\<lambda>x. x\\<cdot>y) o conjugate (\\<lambda>x. 1 \\<lhd> x))\" by simp\n  hence \"(\\<lambda>x. y \\<lhd> x) = conjugate ((\\<lambda>x. x\\<cdot>y) o conjugate (\\<lambda>x. 1 \\<lhd> x))\" by simp\n  also have \"... = conjugate (conjugate (\\<lambda>x. 1 \\<lhd> x)) o conjugate (\\<lambda>x. x\\<cdot>y)\"\n    by (subst conjugate_comp[symmetric]) simp_all\n  finally show \"y \\<lhd> x = 1 \\<lhd> (x \\<lhd> y)\" by simp\nnext\n  fix x y\n  assume \"\\<forall>x y. y \\<lhd> x = 1 \\<lhd> (x \\<lhd> y)\"\n  hence \"(\\<lambda>x. y \\<lhd> x) = (\\<lambda>x. 1 \\<lhd> (x \\<lhd> y))\" by metis\n  hence \"(\\<lambda>x. y \\<lhd> x) = (\\<lambda>x. 1 \\<lhd> x) o conjugate (\\<lambda>x. x\\<cdot>y)\" by force\n  hence \"conjugate (\\<lambda>x. y \\<lhd> x) = conjugate ((\\<lambda>x. 1 \\<lhd> x) o conjugate (\\<lambda>x. x\\<cdot>y))\" by metis\n  also have \"... = conjugate (conjugate (\\<lambda>x. x\\<cdot>y)) o conjugate (\\<lambda>x. 1 \\<lhd> x)\"\n    by (subst conjugate_comp[symmetric]) simp_all\n  finally have \"(\\<lambda>x. x \\<rhd> y) = (\\<lambda>x. x\\<cdot>y) o (\\<lambda>x. x \\<rhd> 1)\" by simp\n  hence \"(\\<lambda>x. x \\<rhd> y) = (\\<lambda>x. (x \\<rhd> 1) \\<cdot> y)\" by (simp add: comp_def)\n  thus \"x \\<rhd> y = (x \\<rhd> 1) \\<cdot> y\" by metis\nqed\n\nlemma jonsson2a: \"(\\<exists>g. \\<forall>x y. x \\<lhd> y = x\\<cdot>g(y)) \\<longleftrightarrow> (\\<forall>x y. x \\<lhd> y = x\\<cdot>(1 \\<lhd> y))\"\n  apply standard\n  apply force\n  apply (rule_tac x=\"\\<lambda>x. 1 \\<lhd> x\" in exI)\n  apply force\n  done\n  \nlemma jonsson2b: \"(\\<forall>x y. x \\<lhd> y = x\\<cdot>(1 \\<lhd> y)) \\<longleftrightarrow> (\\<forall>x y. x\\<cdot>y = x \\<lhd> (1 \\<lhd> y))\"\nproof safe\n  fix x y\n  assume \"\\<forall>x y. x \\<lhd> y = x\\<cdot>(1 \\<lhd> y)\"\n  hence \"conjugate (\\<lambda>x. x \\<lhd> y) = conjugate (\\<lambda>x. x\\<cdot>(1 \\<lhd> y))\" by metis\n  thus \"x\\<cdot>y = x \\<lhd> (1 \\<lhd> y)\" by simp metis\nnext\n  fix x y\n  assume \"\\<forall>x y. x\\<cdot>y = x \\<lhd> (1 \\<lhd> y)\"\n  hence \"(\\<lambda>x. x\\<cdot>y) = (\\<lambda>x. x \\<lhd> (1 \\<lhd> y))\" by metis\n  hence \"conjugate (\\<lambda>x. x\\<cdot>y) = conjugate (\\<lambda>x. x \\<lhd> (1 \\<lhd> y))\" by metis\n  thus \"x \\<lhd> y = x \\<cdot> (1 \\<lhd> y)\" by simp metis\nqed\n\nlemma jonsson2c: \"(\\<forall>x y. x \\<lhd> y = x\\<cdot>(1 \\<lhd> y)) \\<longleftrightarrow> (\\<forall>x y. y \\<rhd> x = (x \\<rhd> y) \\<rhd> 1)\"\nproof safe\n  fix x y\n  assume \"\\<forall>x y. x \\<lhd> y = x\\<cdot>(1 \\<lhd> y)\"\n  hence \"(\\<lambda>y. x \\<lhd> y) = (\\<lambda>y. x\\<cdot>(1 \\<lhd> y))\" by metis\n  hence \"(\\<lambda>y. x \\<lhd> y) = (\\<lambda>y. x\\<cdot>y) o (\\<lambda>y. 1 \\<lhd> y)\" by force\n  hence \"conjugate (\\<lambda>y. y \\<rhd> x) = (\\<lambda>y. x\\<cdot>y) o conjugate (\\<lambda>y. y \\<rhd> 1)\" by force\n  hence \"conjugate (conjugate (\\<lambda>y. y \\<rhd> x)) = conjugate ((\\<lambda>y. x\\<cdot>y) o conjugate (\\<lambda>y. y \\<rhd> 1))\" by metis\n  hence \"(\\<lambda>y. y \\<rhd> x) = conjugate ((\\<lambda>y. x\\<cdot>y) o conjugate (\\<lambda>y. y \\<rhd> 1))\" by simp\n  also have \"... = conjugate (conjugate (\\<lambda>y. y \\<rhd> 1)) o conjugate (\\<lambda>y. x\\<cdot>y)\"\n    by (subst conjugate_comp[symmetric]) simp_all\n  finally have \"(\\<lambda>y. y \\<rhd> x) = (\\<lambda>y. x \\<rhd> y \\<rhd> 1)\" by (simp add: comp_def)\n  thus \"y \\<rhd> x = x \\<rhd> y \\<rhd> 1\" by metis \nnext\n  fix x y\n  assume \"\\<forall>x y. y \\<rhd> x = x \\<rhd> y \\<rhd> 1\"\n  hence \"(\\<lambda>y. y \\<rhd> x) = (\\<lambda>y. x \\<rhd> y \\<rhd> 1)\" by force\n  hence \"(\\<lambda>y. y \\<rhd> x) = (\\<lambda>y. y \\<rhd> 1) o conjugate (\\<lambda>y. x\\<cdot>y)\" by force\n  hence \"conjugate (\\<lambda>y. y \\<rhd> x) = conjugate ((\\<lambda>y. y \\<rhd> 1) o conjugate (\\<lambda>y. x\\<cdot>y))\" by metis\n  also have \"... = conjugate (conjugate (\\<lambda>y. x\\<cdot>y)) o conjugate (\\<lambda>y. y \\<rhd> 1)\"\n    by (subst conjugate_comp[symmetric]) simp_all\n  finally have \"(\\<lambda>y. x \\<lhd> y) = (\\<lambda>y. x\\<cdot>y) o (\\<lambda>y. 1 \\<lhd> y)\"\n    by (metis conjugate_conjr1 conjugate_conjr2 conjugate_multr)\n  thus \"x \\<lhd> y = x \\<cdot> (1 \\<lhd> y)\" by (simp add: comp_def)\nqed\n\nlemma jonsson3a: \"(\\<forall>x. (x \\<rhd> 1) \\<rhd> 1 = x) \\<longleftrightarrow> (\\<forall>x. 1 \\<lhd> (1 \\<lhd> x) = x)\"\nproof safe\n  fix x assume \"\\<forall>x. x \\<rhd> 1 \\<rhd> 1 = x\"\n  thus \"1 \\<lhd> (1 \\<lhd> x) = x\"\n    by (metis compl_le_swap1 compl_le_swap2 conjr2_iff eq_iff)\nnext\n  fix x assume \"\\<forall>x. 1 \\<lhd> (1 \\<lhd> x) = x\"\n  thus \"x \\<rhd> 1 \\<rhd> 1 = x\"\n    by (metis conjugate_l_def conjugate_r_def double_compl jipsen2r)\nqed\n\nlemma jonsson3b: \"(\\<forall>x. (x \\<rhd> 1) \\<rhd> 1 = x) \\<Longrightarrow> (x \\<sqinter> y) \\<rhd> 1 = (x \\<rhd> 1) \\<sqinter> (y \\<rhd> 1)\"\nproof (rule antisym, auto simp: conjr2_iso)\n  assume assm: \"\\<forall>x. (x \\<rhd> 1) \\<rhd> 1 = x\"\n  hence \"(x \\<rhd> 1) \\<sqinter> (y \\<rhd> 1) \\<rhd> 1 = x \\<sqinter> (((x \\<rhd> 1) \\<sqinter> (y \\<rhd> 1) \\<rhd> 1) \\<sqinter> y)\"\n    by (metis (no_types) conjr2_iso inf.cobounded2 inf.commute inf.orderE)\n  hence \"(x \\<rhd> 1) \\<sqinter> (y \\<rhd> 1) \\<rhd> 1 \\<le> x \\<sqinter> y\" \n    using inf.orderI inf_left_commute by presburger\n  thus \"(x \\<rhd> 1) \\<sqinter> (y \\<rhd> 1) \\<le> x \\<sqinter> y \\<rhd> 1\" \n    using assm by (metis (no_types) conjr2_iso)\nqed\n\nlemma jonsson3c: \"\\<forall>x. (x \\<rhd> 1) \\<rhd> 1 = x \\<Longrightarrow> x \\<rhd> 1 = 1 \\<lhd> x\"\nproof (rule indirect_eq)\n  fix z\n  assume assms: \"\\<forall>x. (x \\<rhd> 1) \\<rhd> 1 = x\"\n  hence \"(x \\<rhd> 1) \\<sqinter> -z = \\<bottom> \\<longleftrightarrow> ((x \\<rhd> 1) \\<sqinter> -z) \\<rhd> 1 = \\<bottom>\"\n    by (metis compl_sup conjugation_conj double_compl inf_bot_right sup_bot.left_neutral)\n  also have \"... \\<longleftrightarrow> -z\\<cdot>x \\<sqinter> 1 = \\<bottom>\"\n    by (metis assms jonsson3b conjugation_multr)\n  finally have \"(x \\<rhd> 1) \\<sqinter> -z = \\<bottom> \\<longleftrightarrow> (1 \\<lhd> x) \\<sqinter> -z = \\<bottom>\"\n    by (metis conjugation_multl inf.commute)\n  thus \"(x \\<rhd> 1 \\<le> z) \\<longleftrightarrow> (1 \\<lhd> x \\<le> z)\"\n    by (metis le_iff_inf_bot)\nqed \n\nend (* unital_residuated_boolean *)\n\nclass residuated_boolean_semigroup = residuated_boolean_algebra + semigroup_mult\nbegin\n\nsubclass residuated_boolean_algebra ..\n\ntext \\<open>\n  The following lemmas hold trivially, since they are equivalent to associativity.\n\\<close>\n\nlemma res_assoc1: \"x \\<rhd> (y \\<rhd> z) = y\\<cdot>x \\<rhd> z\"\n  by (metis res_assoc_iff1 mult_assoc)\n\nlemma res_assoc2: \"x \\<lhd> (y \\<cdot> z) = (x \\<lhd> z) \\<lhd> y\"\n  by (metis res_assoc_iff2 mult_assoc)\n\nlemma res_assoc3: \"(x \\<rhd> y) \\<lhd> z = x \\<rhd> (y \\<lhd> z)\"\n  by (metis res_assoc_iff3 mult_assoc)\n\nend (*residuated_boolean_semigroup *)\n\nclass residuated_boolean_monoid = residuated_boolean_algebra + monoid_mult\nbegin\n\nsubclass unital_residuated_boolean\n  by standard auto\n\nsubclass residuated_lmonoid ..\n\nlemma jonsson4: \"(\\<forall>x y. x \\<lhd> y = x\\<cdot>(1 \\<lhd> y)) \\<longleftrightarrow> (\\<forall>x y. x \\<rhd> y = (x \\<rhd> 1)\\<cdot>y)\"\nproof safe\n  fix x y assume assms: \"\\<forall>x y. x \\<lhd> y = x\\<cdot>(1 \\<lhd> y)\"\n  have \"x \\<rhd> y = (y \\<rhd> x) \\<rhd> 1\"\n    by (metis assms jonsson2c)\n  also have \"... = (y \\<rhd> ((x \\<rhd> 1) \\<rhd> 1)) \\<rhd> 1\"\n    by (metis assms jonsson2b jonsson3a mult_oner)\n  also have \"... = (((x \\<rhd> 1)\\<cdot>y) \\<rhd> 1) \\<rhd> 1\"\n    by (metis conjugate_r_def double_compl resr3)\n  also have \"... = (x \\<rhd> 1)\\<cdot>y\"\n    by (metis assms jonsson2b jonsson3a mult_oner)\n  finally show \"x \\<rhd> y = (x \\<rhd> 1)\\<cdot>y\" .\nnext\n  fix x y assume assms: \"\\<forall>x y. x \\<rhd> y = (x \\<rhd> 1)\\<cdot>y\"\n  have \"y \\<lhd> x = 1 \\<lhd> (x \\<lhd> y)\"\n    by (metis assms jonsson1c)\n  also have \"... = 1 \\<lhd> ((1 \\<lhd> (1 \\<lhd> x)) \\<lhd> y)\"\n    by (metis assms conjugate_l_def double_compl jonsson1c mult_1_right resl3)\n  also have \"... = 1 \\<lhd> (1 \\<lhd> (y\\<cdot>(1 \\<lhd> x)))\"\n    by (metis conjugate_l_def double_compl resl3)\n  also have \"... = y\\<cdot>(1 \\<lhd> x)\"\n    by (metis assms jonsson1b jonsson1c jonsson3c mult_onel)\n  finally show \"y \\<lhd> x = y\\<cdot>(1 \\<lhd> x)\".\nqed\n\nend (* residuated_boolean_monoid *)\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/Residuated_Boolean_Algebras.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278602705731, "lm_q2_score": 0.8244619199068831, "lm_q1q2_score": 0.7275281678579995}}
{"text": "(*\n    Author:     Lawrence C Paulson, Cambridge University Computer Laboratory\n                Tobias Nipkow, TUM\n*)\n\ntheory Tilings imports Main begin\n\nsection\\<open>Inductive Tiling\\<close>\n\n\ninductive_set\n  tiling :: \"'a set set \\<Rightarrow> 'a set set\"\n  for A :: \"'a set set\" where\nempty [simp, intro]: \"{} \\<in> tiling A\" |\nUn [simp, intro]:    \"\\<lbrakk> a \\<in> A; t \\<in> tiling A; a \\<inter> t = {} \\<rbrakk>\n                         \\<Longrightarrow> a \\<union> t \\<in> tiling A\"\n\n\nlemma tiling_UnI [intro]:\n  \"\\<lbrakk> t \\<in> tiling A; u \\<in> tiling A; t \\<inter> u = {} \\<rbrakk> \\<Longrightarrow>  t \\<union> u \\<in> tiling A\"\napply (induct set: tiling)\napply (auto simp add: Un_assoc)\ndone\n\nlemma tiling_Diff1E:\nassumes \"t-a \\<in> tiling A\" and \"a \\<in> A\" and \"a \\<subseteq> t\"\nshows \"t \\<in> tiling A\"\nproof -\n  from assms(2-3) have  \"\\<exists>r. t = r Un a & r Int a = {}\"\n    by (metis Diff_disjoint Int_commute Un_Diff_cancel Un_absorb1 Un_commute)\n  thus ?thesis using assms(1,2)\n    by (auto simp:Un_Diff)\n       (metis Compl_Diff_eq Diff_Compl Diff_empty Int_commute Un_Diff_cancel\n              Un_commute double_complement tiling.Un)\nqed\n\nlemma tiling_finite:\n  assumes \"\\<And>a. a \\<in> A \\<Longrightarrow> finite a\"\n  shows \"t \\<in> tiling A \\<Longrightarrow> finite t\"\napply (induct set: tiling)\nusing assms apply auto\ndone\n\n\nsection\\<open>The Mutilated Chess Board Cannot be Tiled by Dominoes\\<close>\n\ntext \\<open>The originator of this problem is Max Black, according to J A\nRobinson. It was popularized as the \\emph{Mutilated Checkerboard Problem} by\nJ McCarthy.\\<close>\n\ninductive_set domino :: \"(nat \\<times> nat) set set\" where\nhoriz [simp]: \"{(i, j), (i, Suc j)} \\<in> domino\" |\nvertl [simp]: \"{(i, j), (Suc i, j)} \\<in> domino\"\n\nlemma domino_finite: \"d \\<in> domino \\<Longrightarrow> finite d\"\nby (erule domino.cases, auto)\n\ndeclare tiling_finite[OF domino_finite, simp]\n\ntext \\<open>\\medskip Sets of squares of the given colour\\<close>\n\ndefinition\n  coloured :: \"nat \\<Rightarrow> (nat \\<times> nat) set\" where\n  \"coloured b = {(i, j). (i + j) mod 2 = b}\"\n\nabbreviation\n  whites  :: \"(nat \\<times> nat) set\" where\n  \"whites \\<equiv> coloured 0\"\n\nabbreviation\n  blacks  :: \"(nat \\<times> nat) set\" where\n  \"blacks \\<equiv> coloured (Suc 0)\"\n\n\ntext \\<open>\\medskip Chess boards\\<close>\n\nlemma Sigma_Suc1 [simp]:\n  \"{0..< Suc n} \\<times> B = ({n} \\<times> B) \\<union> ({0..<n} \\<times> B)\"\nby auto\n\nlemma Sigma_Suc2 [simp]:\n  \"A \\<times> {0..< Suc n} = (A \\<times> {n}) \\<union> (A \\<times> {0..<n})\"\nby auto\n\nlemma dominoes_tile_row [intro!]: \"{i} \\<times> {0..< 2*n} \\<in> tiling domino\"\napply (induct n)\napply (simp_all del:Un_insert_left add: Un_assoc [symmetric])\ndone\n\nlemma dominoes_tile_matrix: \"{0..<m} \\<times> {0..< 2*n} \\<in> tiling domino\"\nby (induct m) auto\n\n\ntext \\<open>\\medskip @{term coloured} and Dominoes\\<close>\n\nlemma coloured_insert [simp]:\n  \"coloured b \\<inter> (insert (i, j) t) =\n   (if (i + j) mod 2 = b then insert (i, j) (coloured b \\<inter> t)\n    else coloured b \\<inter> t)\"\nby (auto simp add: coloured_def)\n\nlemma domino_singletons:\n  \"d \\<in> domino \\<Longrightarrow>\n   (\\<exists>i j. whites \\<inter> d = {(i, j)}) \\<and>\n   (\\<exists>m n. blacks \\<inter> d = {(m, n)})\"\napply (erule domino.cases)\n apply (auto simp add: mod_Suc)\ndone\n\n\ntext \\<open>\\medskip Tilings of dominoes\\<close>\n\ndeclare\n  Int_Un_distrib [simp]\n  Diff_Int_distrib [simp]\n\nlemma tiling_domino_0_1:\n  \"t \\<in> tiling domino ==> card(whites \\<inter> t) = card(blacks \\<inter> t)\"\napply (induct set: tiling)\n apply (drule_tac [2] domino_singletons)\n apply (auto)\napply (subgoal_tac \"\\<forall>p C. C \\<inter> a = {p} --> p \\<notin> t\")\n  \\<comment> \\<open>this lemma tells us that both ``inserts'' are non-trivial\\<close>\n apply (simp (no_asm_simp))\napply blast\ndone\n\n\ntext \\<open>\\medskip Final argument is surprisingly complex\\<close>\n\ntheorem gen_mutil_not_tiling:\n  \"t \\<in> tiling domino ==>\n  (i + j) mod 2 = 0 ==> (m + n) mod 2 = 0 ==>\n  {(i, j), (m, n)} \\<subseteq> t\n  ==> (t - {(i,j)} - {(m,n)}) \\<notin> tiling domino\"\napply (rule notI)\napply (subgoal_tac\n  \"card (whites \\<inter> (t - {(i,j)} - {(m,n)})) <\n   card (blacks \\<inter> (t - {(i,j)} - {(m,n)}))\")\n apply (force simp only: tiling_domino_0_1)\napply (simp add: tiling_domino_0_1 [symmetric])\napply (simp add: coloured_def card_Diff2_less)\ndone\n\ntext \\<open>Apply the general theorem to the well-known case\\<close>\n\ntheorem mutil_not_tiling:\n  \"t = {0..< 2 * Suc m} \\<times> {0..< 2 * Suc n}\n   ==> t - {(0,0)} - {(Suc(2 * m), Suc(2 * n))} \\<notin> tiling domino\"\napply (rule gen_mutil_not_tiling)\n apply (blast intro!: dominoes_tile_matrix)\napply auto\ndone\n\n\nsection\\<open>The Mutilated Chess Board Can be Tiled by Ls\\<close>\n\ntext\\<open>Remove a arbitrary square from a chess board of size $2^n \\times 2^n$.\nThe result can be tiled by L-shaped tiles:\n\\begin{picture}(8,8)\n\\put(0,0){\\framebox(4,4){}}\n\\put(4,0){\\framebox(4,4){}}\n\\put(0,4){\\framebox(4,4){}}\n\\end{picture}.\nThe four possible L-shaped tiles are obtained by dropping\none of the four squares from $\\{(x,y),(x+1,y),(x,y+1),(x+1,y+1)\\}$:\\<close>\n\ndefinition \"L2 (x::nat) (y::nat) = {(x,y), (x+1,y), (x, y+1)}\"\ndefinition \"L3 (x::nat) (y::nat) = {(x,y), (x+1,y), (x+1, y+1)}\"\ndefinition \"L0 (x::nat) (y::nat) = {(x+1,y), (x,y+1), (x+1, y+1)}\"\ndefinition \"L1 (x::nat) (y::nat) = {(x,y), (x,y+1), (x+1, y+1)}\"\n\ntext\\<open>All tiles:\\<close>\n\ndefinition Ls :: \"(nat * nat) set set\" where\n\"Ls \\<equiv> { L0 x y | x y. True} \\<union> { L1 x y | x y. True} \\<union>\n      { L2 x y | x y. True} \\<union> { L3 x y | x y. True}\"\n\nlemma LinLs: \"L0 i j : Ls & L1 i j : Ls & L2 i j : Ls & L3 i j : Ls\"\nby(fastforce simp:Ls_def)\n\n\ntext\\<open>Square $2^n \\times 2^n$ grid, shifted by $i$ and $j$:\\<close>\n\ndefinition \"square2 (n::nat) (i::nat) (j::nat) = {i..< 2^n+i} \\<times> {j..< 2^n+j}\"\n\nlemma in_square2[simp]:\n  \"(a,b) : square2 n i j \\<longleftrightarrow> i\\<le>a \\<and> a<2^n+i \\<and> j\\<le>b \\<and> b<2^n+j\"\nby(simp add:square2_def)\n\nlemma square2_Suc: \"square2 (Suc n) i j =\n  square2 n i j \\<union> square2 n (2^n + i) j \\<union> square2 n i (2^n + j) \\<union>\n  square2 n (2^n + i) (2^n + j)\"\nby(auto simp:square2_def)\n\nlemma square2_disj: \"square2 n i j \\<inter> square2 n x y = {} \\<longleftrightarrow>\n  (2^n+i \\<le> x \\<or> 2^n+x \\<le> i) \\<or> (2^n+j \\<le> y \\<or> 2^n+y \\<le> j)\" (is \"?A = ?B\")\nproof-\n  { assume ?B hence ?A by(auto simp:square2_def) }\n  moreover\n  { assume \"\\<not> ?B\"\n    hence \"(max i x, max j y) : square2 n i j \\<inter> square2 n x y\" by simp\n    hence \"\\<not> ?A\" by blast }\n  ultimately show ?thesis by blast\nqed\n\ntext\\<open>Some specific lemmas:\\<close>\n\nlemma pos_pow2: \"(0::nat) < 2^(n::nat)\"\nby simp\n\ndeclare nat_zero_less_power_iff[simp del] zero_less_power[simp del]\n\nlemma Diff_insert_if: shows\n  \"B \\<noteq> {} \\<Longrightarrow> a:A \\<Longrightarrow> A - insert a B = (A-B - {a})\" and\n  \"B \\<noteq> {} \\<Longrightarrow> a ~: A \\<Longrightarrow> A - insert a B = A-B\"\nby auto\n\nlemma DisjI1: \"A Int B = {} \\<Longrightarrow> (A-X) Int B = {}\"\nby blast\nlemma DisjI2: \"A Int B = {} \\<Longrightarrow> A Int (B-X) = {}\"\nby blast\n\ntext\\<open>The main theorem:\\<close>\n\ntheorem Ls_can_tile: \"i \\<le> a \\<Longrightarrow> a < 2^n + i \\<Longrightarrow> j \\<le> b \\<Longrightarrow> b < 2^n + j\n  \\<Longrightarrow> square2 n i j - {(a,b)} : tiling Ls\"\nproof(induct n arbitrary: a b i j)\n  case 0 thus ?case by (simp add:square2_def)\nnext\n  case (Suc n) note IH = Suc(1) and a = Suc(2-3) and b = Suc(4-5)\n  hence \"a<2^n+i \\<and> b<2^n+j \\<or>\n         2^n+i\\<le>a \\<and> a<2^(n+1)+i \\<and> b<2^n+j \\<or>\n         a<2^n+i \\<and> 2^n+j\\<le>b \\<and> b<2^(n+1)+j \\<or>\n         2^n+i\\<le>a \\<and> a<2^(n+1)+i \\<and> 2^n+j\\<le>b \\<and> b<2^(n+1)+j\" (is \"?A|?B|?C|?D\")\n    by simp arith\n  moreover\n  { assume \"?A\"\n    hence \"square2 n i j - {(a,b)} : tiling Ls\" using IH a b by auto\n    moreover have \"square2 n (2^n+i) j - {(2^n+i,2^n+j - 1)} : tiling Ls\"\n      by(rule IH)(insert pos_pow2[of n], auto)\n    moreover have \"square2 n i (2^n+j) - {(2^n+i - 1, 2^n+j)} : tiling Ls\"\n      by(rule IH)(insert pos_pow2[of n], auto)\n    moreover have \"square2 n (2^n+i) (2^n+j) - {(2^n+i, 2^n+j)} : tiling Ls\"\n      by(rule IH)(insert pos_pow2[of n], auto)\n    ultimately\n    have \"square2 (n+1) i j - {(a,b)} - L0 (2^n+i - 1) (2^n+j - 1) \\<in> tiling Ls\"\n      using  a b \\<open>?A\\<close>\n      by (clarsimp simp: square2_Suc L0_def Un_Diff Diff_insert_if)\n         (fastforce intro!: tiling_UnI DisjI1 DisjI2 square2_disj[THEN iffD2]\n                   simp:Int_Un_distrib2)\n  } moreover\n  { assume \"?B\"\n    hence \"square2 n (2^n+i) j - {(a,b)} : tiling Ls\" using IH a b by auto\n    moreover have \"square2 n i j - {(2^n+i - 1,2^n+j - 1)} : tiling Ls\"\n      by(rule IH)(insert pos_pow2[of n], auto)\n    moreover have \"square2 n i (2^n+j) - {(2^n+i - 1, 2^n+j)} : tiling Ls\"\n      by(rule IH)(insert pos_pow2[of n], auto)\n    moreover have \"square2 n (2^n+i) (2^n+j) - {(2^n+i, 2^n+j)} : tiling Ls\"\n      by(rule IH)(insert pos_pow2[of n], auto)\n    ultimately\n    have \"square2 (n+1) i j - {(a,b)} - L1 (2^n+i - 1) (2^n+j - 1) \\<in> tiling Ls\"\n      using  a b \\<open>?B\\<close>\n      by (simp add: square2_Suc L1_def Un_Diff Diff_insert_if le_diff_conv2)\n         (fastforce intro!: tiling_UnI DisjI1 DisjI2 square2_disj[THEN iffD2]\n                   simp:Int_Un_distrib2)\n  } moreover\n  { assume \"?C\"\n    hence \"square2 n i (2^n+j) - {(a,b)} : tiling Ls\" using IH a b by auto\n    moreover have \"square2 n i j - {(2^n+i - 1,2^n+j - 1)} : tiling Ls\"\n      by(rule IH)(insert pos_pow2[of n], auto)\n    moreover have \"square2 n (2^n+i) j - {(2^n+i, 2^n+j - 1)} : tiling Ls\"\n      by(rule IH)(insert pos_pow2[of n], auto)\n    moreover have \"square2 n (2^n+i) (2^n+j) - {(2^n+i, 2^n+j)} : tiling Ls\"\n      by(rule IH)(insert pos_pow2[of n], auto)\n    ultimately\n    have \"square2 (n+1) i j - {(a,b)} - L3 (2^n+i - 1) (2^n+j - 1) \\<in> tiling Ls\"\n      using  a b \\<open>?C\\<close>\n      by (simp add: square2_Suc L3_def Un_Diff Diff_insert_if le_diff_conv2)\n         (fastforce intro!: tiling_UnI DisjI1 DisjI2 square2_disj[THEN iffD2]\n                   simp:Int_Un_distrib2)\n  } moreover\n  { assume \"?D\"\n    hence \"square2 n (2^n+i) (2^n+j) -{(a,b)} : tiling Ls\" using IH a b by auto\n    moreover have \"square2 n i j - {(2^n+i - 1,2^n+j - 1)} : tiling Ls\"\n      by(rule IH)(insert pos_pow2[of n], auto)\n    moreover have \"square2 n (2^n+i) j - {(2^n+i, 2^n+j - 1)} : tiling Ls\"\n      by(rule IH)(insert pos_pow2[of n], auto)\n    moreover have \"square2 n i (2^n+j) - {(2^n+i - 1, 2^n+j)} : tiling Ls\"\n      by(rule IH)(insert pos_pow2[of n], auto)\n    ultimately\n    have \"square2 (n+1) i j - {(a,b)} - L2 (2^n+i - 1) (2^n+j - 1) \\<in> tiling Ls\"\n      using  a b \\<open>?D\\<close>\n      by (simp add: square2_Suc L2_def Un_Diff Diff_insert_if le_diff_conv2)\n         (fastforce intro!: tiling_UnI DisjI1 DisjI2 square2_disj[THEN iffD2]\n                   simp:Int_Un_distrib2)\n  } moreover\n  have \"?A \\<Longrightarrow> L0 (2^n + i - 1) (2^n + j - 1) \\<subseteq> square2 (n+1) i j - {(a, b)}\"\n    using a b by(simp add:L0_def) arith moreover\n  have \"?B \\<Longrightarrow> L1 (2^n + i - 1) (2^n + j - 1) \\<subseteq> square2 (n+1) i j - {(a, b)}\"\n    using a b by(simp add:L1_def) arith moreover\n  have \"?C \\<Longrightarrow> L3 (2^n + i - 1) (2^n + j - 1) \\<subseteq> square2 (n+1) i j - {(a, b)}\"\n    using a b by(simp add:L3_def) arith moreover\n  have \"?D \\<Longrightarrow> L2 (2^n + i - 1) (2^n + j - 1) \\<subseteq> square2 (n+1) i j - {(a, b)}\"\n    using a b by(simp add:L2_def) arith\n  ultimately show ?case by simp (metis LinLs tiling_Diff1E)\nqed\n\ncorollary Ls_can_tile00:\n  \"a < 2^n \\<Longrightarrow> b < 2^n \\<Longrightarrow> square2 n 0 0 - {(a, b)} \\<in> tiling Ls\"\nby(rule Ls_can_tile) 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/FunWithTilings/Tilings.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9173026528034426, "lm_q2_score": 0.7931059487389968, "lm_q1q2_score": 0.7275181907324729}}
{"text": "theory hw05\n  imports\n    Complex_Main\n    \"HOL-Library.Tree\"\nbegin\n\nvalue \"(0::nat) div 0\"\n\nlemma\n  assumes \"n\\<ge>0\"\n  shows \"\\<exists>ys zs. length ys = length xs div n \\<and> xs=ys@zs\"\nproof (intro exI)\n  let ?n = \"length xs div n\"\n  let ?ys = \"take ?n xs\"\n  let ?zs = \"drop ?n xs\"\n  show \"length ?ys = length xs div n \\<and> xs = ?ys @ ?zs\"  by(simp add:min.absorb2)\nqed\n\n\nfun a :: \"nat \\<Rightarrow> int\" where\n  \"a 0 = 0\"\n| \"a (Suc n) = a n ^ 2 + 1\"\n\nthm power_mono[where n = 2]\n\nfind_theorems \"(_-_)^2\"\nfind_theorems \"(_ + _) > _\"\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    from IH have azer:\"0 \\<le> a n\" by (smt a.elims power2_less_eq_zero_iff zero_eq_power2)\n   \n    from IH  have \"a (Suc n) = (a n)^2 +1\" by simp\n    also have \"(a n)^2 \\<le> (2 ^ 2 ^ n - 1) ^ 2\" using power_mono[where n = 2] IH azer by blast\n    also have \"... \\<le> (2 ^ 2 ^ (n + 1)) + 1 - 2*2^(2^(n))\" by (simp add: power2_diff power_even_eq)\n    also have \"... \\<le> 2 ^ 2 ^ Suc n - 2 \" by (smt Suc.IH Suc_eq_plus1 a.elims power.simps(1) power2_less_eq_zero_iff power_one_right zero_eq_power2)\n    finally show ?thesis by auto\n    \n  qed\nqed\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/05/hw05.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.853912760387131, "lm_q2_score": 0.8519528076067261, "lm_q1q2_score": 0.7274933736630258}}
{"text": "theory Chapter3\n  imports Main\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 t1 a t2) = set t1 \\<union> {a} \\<union> set t2\"\n\nfun ord :: \"int tree \\<Rightarrow> bool\" where\n  \"ord Tip = True\"\n| \"ord (Node t1 a t2) = (ord t1 \\<and> ord t2 \\<and> (\\<forall>x. x \\<in> set t1 \\<longrightarrow> x < a) \\<and> (\\<forall>x. x \\<in> set t2 \\<longrightarrow> a \\<le> x))\"\n(* parentheses are necessary around (\\<forall>x. ...)*)\n\nfun ins :: \"int \\<Rightarrow> int tree \\<Rightarrow> int tree\" where\n  \"ins x Tip = Node Tip x Tip\"\n| \"ins x (Node t1 a t2) = (if x < a then Node (ins x t1) a t2 else Node t1 a (ins x t2))\"\n\ntheorem ins_correct_1 : \"set (ins x t) = {x} \\<union> set t\"\n  apply (induction t)\n   apply (auto)\n  done\n\ntheorem ins_correct_2 : \"ord t \\<Longrightarrow> ord (ins i t)\"\n  apply (induction t)\n   apply (auto simp add:ins_correct_1)\n  done\n\n(*** 3.3 Proof Automation ***)\nlemma \"\\<forall>x. \\<exists>y. x = y\" by auto\nlemma \"A \\<subseteq> B \\<inter> C \\<Longrightarrow> A \\<subseteq> B \\<union> C\" by auto\n\n(* fastforce can handle quantifiers *)\nlemma \"\\<lbrakk> \\<forall>xs \\<in> A. \\<exists>ys. xs = ys @ ys; us \\<in> A \\<rbrakk> \\<Longrightarrow> \\<exists>n. length us = n + n\" by fastforce\n\n(* blast is strong in first-order logic, sets and relations, but weak in equality *)\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> \\<Longrightarrow> \\<forall> x y. A x y \\<longrightarrow> T x y\" by blast\n\n(* sledgehammer *)\nlemma \"\\<lbrakk> xs @ ys = ys @ xs; length xs = length ys \\<rbrakk> \\<Longrightarrow> xs = ys\"\n  using append_eq_append_conv by blast\n\n(* arith *)\nlemma \"\\<lbrakk> (a :: nat) \\<le> x + b; 2 * x < c \\<rbrakk> \\<Longrightarrow> 2 * a + 1 \\<le> 2 * b + c\"\n  by arith\n\n(* 3.4 Single Step Proofs *)\nlemma \"\\<lbrakk> (a :: nat) \\<le> b; b \\<le> c; c \\<le> d; d \\<le> e \\<rbrakk> \\<Longrightarrow> a \\<le> e\"\n  by (auto intro:le_trans)\n\nthm conjI[OF refl[of \"a\"] refl[of \"b\"]] (* a = a \\<and> b = b *)\n\nlemma \"Suc(Suc(Suc a)) \\<le> b \\<Longrightarrow> a \\<le> b\" by (auto dest:Suc_leD)\n\n(* 3.5 Inductive Deifnitions *)\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> ev (m - 2)\"\n  apply (induction rule:ev.induct)\n  by (simp_all add:ev0 evSS)\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  by (simp_all add:ev0 evSS)\n\n(* makes ev a simplification and introduction rule permanently *)\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) (* induction over star r x y (first matching assumption) *)\n   apply (assumption)\n  apply (metis step)\n  done\n\n(* Exercise 3.2 *)\ninductive palindrome :: \"'a list \\<Rightarrow> bool\" where\n  pEmpty: \"palindrome []\"\n| pSingle: \"palindrome [x]\"\n| pStep: \"palindrome xs \\<Longrightarrow> palindrome (a # xs @ [a])\"\n\ntheorem palindrome_spec : \"palindrome xs \\<Longrightarrow> rev xs = xs\"\n  apply (induction rule:palindrome.induct)\n    apply (auto)\n  done\n\n(* Exercise 3.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\ntheorem star'_is_star : \"star' r x y \\<Longrightarrow> star r x y\"\n  apply (induction rule:star'.induct)\n   apply (auto simp add:refl step star_trans)\n  done\n\nlemma star'_trans' : \"star' r y z \\<Longrightarrow> star' r x y \\<Longrightarrow> star' r x z\"\n  apply (induction rule:star'.induct)\n   apply (assumption)\n  apply (simp add:step')\n  done\n\ntheorem star_is_star' : \"star r x y \\<Longrightarrow> star' r x y\"\n  apply (induction rule:star.induct)\n   apply (simp add:refl' step')\n  apply (blast intro:refl' step' star'_trans')\n  done\n\n(* Exercise 3.4 *)\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\ntheorem star_iter : \"star r x y \\<Longrightarrow> \\<exists>n. iter r n x y\"\n  apply (induction rule:star.induct)\n  apply (rule exI[of _ 0]) \n   apply (auto simp add:iter_zero iter_succ)\n  apply (rule_tac x=\"Suc n\" in exI)\n  apply (auto simp add:iter_zero iter_succ)\n  done\n\n(* Exercise 3.5 *)\ndatatype alpha = a | b\n\ninductive S :: \"alpha list \\<Rightarrow> bool\" where\n  S_0: \"S []\"\n| S_1: \"S w \\<Longrightarrow> S (a # w @ [b])\"\n| S_2: \"S w \\<Longrightarrow> S w' \\<Longrightarrow> S (w @ w')\"\n\ninductive T :: \"alpha list \\<Rightarrow> bool\" where\n  T_0: \"T []\"\n| T_1: \"T w \\<Longrightarrow> T w' \\<Longrightarrow> T (w @ a # w' @ [b])\"\n\nlemma S_includes_T : \"T w \\<Longrightarrow> S w\"\n  apply (induction rule:T.induct)\n   apply (auto simp add:S_0 S_1 S_2)\n  done\n\nlemma append_Nil_r : \"l = [] @ l\"\n  apply (induction l)\n   apply (auto)\n  done\n\n(* I'm not happy with having to prepare these lemmas... *)\nlemma T_complies_S_1' : \"T w \\<Longrightarrow> T ([] @ a # w @ [b])\"\n  apply (rule T_1)\n   apply (auto simp add:T_0)\n  done\n\nlemma T_complies_S_1'' : \"T ([] @ a # w @ [b]) \\<Longrightarrow> T(a # w @ [b])\"\n  apply (auto)\n  done\n\nlemma T_complies_S_1 : \"T w \\<Longrightarrow> T (a # w @ [b])\"\n  apply (rule T_complies_S_1'')\n  apply (rule T_complies_S_1')\n  apply (auto)\n  done\n\nlemma T_complies_S_2 : \"S w' \\<Longrightarrow> T w' \\<Longrightarrow> T w \\<Longrightarrow> T (w @ w')\"\n  apply (induction rule:S.induct)\n    apply (auto)\n\n\n\nlemma T_includes_S : \"S w \\<Longrightarrow> T w\"\n  apply (induction rule:S.induct)\n    apply (rule T_0)\n   apply (auto simp add:T_complies_S_1)\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/Chapter3.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127641048443, "lm_q2_score": 0.8519528038477824, "lm_q1q2_score": 0.7274933736205321}}
{"text": "(*  Title:      HOL/Parity.thy\n    Author:     Jeremy Avigad\n    Author:     Jacques D. Fleuriot\n*)\n\nsection {* Parity in rings and semirings *}\n\ntheory Parity\nimports Nat_Transfer\nbegin\n\nsubsection {* Ring structures with parity and @{text even}/@{text odd} predicates *}\n\nclass semiring_parity = semiring_dvd + semiring_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\nabbreviation even :: \"'a \\<Rightarrow> bool\"\nwhere\n  \"even a \\<equiv> 2 dvd a\"\n\nabbreviation odd :: \"'a \\<Rightarrow> bool\"\nwhere\n  \"odd a \\<equiv> \\<not> 2 dvd a\"\n\nlemma even_zero [simp]:\n  \"even 0\"\n  by (fact dvd_0_right)\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 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]:\n  \"even (a * b) \\<longleftrightarrow> even a \\<or> even b\"\n  by (auto dest: even_multD)\n\nlemma even_numeral [simp]:\n  \"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]:\n  \"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  with dvd_add_times_triv_left_iff [of 2 \"numeral n\" 1]\n    have \"2 dvd 1\"\n    by simp\n  then show False by simp\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_power [simp]:\n  \"even (a ^ n) \\<longleftrightarrow> even a \\<and> n > 0\"\n  by (induct n) auto\n\nend\n\nclass ring_parity = comm_ring_1 + semiring_parity\nbegin\n\nlemma even_minus [simp]:\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 {* Instances for @{typ nat} and @{typ int} *}\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]:\n  \"even (Suc n) \\<longleftrightarrow> odd n\"\n  by (induct n) auto\n\nlemma even_diff_nat [simp]:\n  fixes m n :: nat\n  shows \"even (m - n) \\<longleftrightarrow> m < n \\<or> even (m + n)\"\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 even_diff_iff [simp]:\n  fixes k l :: int\n  shows \"even (k - l) \\<longleftrightarrow> even (k + l)\"\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]:\n  fixes k l :: int\n  shows \"even (\\<bar>k\\<bar> + l) \\<longleftrightarrow> even (k + l)\"\n  by (cases \"k \\<ge> 0\") (simp_all add: ac_simps)\n\nlemma even_add_abs_iff [simp]:\n  fixes k l :: int\n  shows \"even (k + \\<bar>l\\<bar>) \\<longleftrightarrow> even (k + l)\"\n  using even_abs_add_iff [of l k] by (simp add: ac_simps)\n\ninstance nat :: semiring_parity\nproof\n  show \"odd (1 :: nat)\"\n    by (rule notI, erule dvdE) simp\nnext\n  fix m n :: nat\n  assume \"odd m\"\n  moreover assume \"odd n\"\n  ultimately have *: \"even (Suc m) \\<and> even (Suc n)\"\n    by simp\n  then have \"even (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 \"even (m + n)\"\n    using dvd_add_triv_right_iff [of 2 \"m + n\"] by simp\nnext\n  fix m n :: nat\n  assume *: \"even (m * n)\"\n  show \"even m \\<or> even n\"\n  proof (rule disjCI)\n    assume \"odd n\"\n    then have \"even (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)\" by (simp add: algebra_simps)\n    then have \"m = 2 * (m * r - s)\" by simp\n    then show \"even m\" ..\n  qed\nnext\n  fix n :: nat\n  assume \"odd n\"\n  then show \"\\<exists>m. n = m + 1\"\n    by (cases n) simp_all\nqed\n\nlemma odd_pos: \n  \"odd (n :: nat) \\<Longrightarrow> 0 < n\"\n  by (auto elim: oddE)\n  \ninstance int :: ring_parity\nproof\n  show \"odd (1 :: int)\" by (simp add: dvd_int_unfold_dvd_nat)\n  fix k l :: int\n  assume \"odd k\"\n  moreover assume \"odd l\"\n  ultimately have \"even (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 \"even (\\<bar>k\\<bar> + \\<bar>l\\<bar>)\"\n    by (simp add: dvd_int_unfold_dvd_nat nat_add_distrib)\n  then show \"even (k + l)\"\n    by simp\nnext\n  fix k l :: int\n  assume \"even (k * l)\"\n  then show \"even k \\<or> even 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]:\n  \"even (int n) \\<longleftrightarrow> even n\"\n  by (simp add: dvd_int_iff)\n\nlemma even_nat_iff:\n  \"0 \\<le> k \\<Longrightarrow> even (nat k) \\<longleftrightarrow> even k\"\n  by (simp add: even_int_iff [symmetric])\n\n\nsubsection {* Parity and powers *}\n\ncontext comm_ring_1\nbegin\n\nlemma power_minus_even [simp]:\n  \"even n \\<Longrightarrow> (- a) ^ n = a ^ n\"\n  by (auto elim: evenE)\n\nlemma power_minus_odd [simp]:\n  \"odd n \\<Longrightarrow> (- a) ^ n = - (a ^ n)\"\n  by (auto elim: oddE)\n\nlemma neg_one_even_power [simp]:\n  \"even n \\<Longrightarrow> (- 1) ^ n = 1\"\n  by simp\n\nlemma neg_one_odd_power [simp]:\n  \"odd n \\<Longrightarrow> (- 1) ^ n = - 1\"\n  by simp\n\nend  \n\ncontext linordered_idom\nbegin\n\nlemma zero_le_even_power:\n  \"even n \\<Longrightarrow> 0 \\<le> a ^ n\"\n  by (auto elim: evenE)\n\nlemma zero_le_odd_power:\n  \"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:\n  \"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:\n  \"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]:\n  \"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:\n  \"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:\n  \"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 `\\<bar>a\\<bar> \\<le> \\<bar>b\\<bar>`\n  have \"\\<bar>a\\<bar> ^ n \\<le> \\<bar>b\\<bar> ^ n\" by (rule power_mono)\n  with `even n` show ?thesis 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 with `a \\<le> b` have \"- b \\<le> - a\" and \"0 \\<le> - b\" by auto\n  hence \"(- b) ^ n \\<le> (- a) ^ n\" by (rule power_mono)\n  with `odd n` show ?thesis by simp\nnext\n  case False then have \"0 \\<le> b\" by auto\n  show ?thesis\n  proof (cases \"a < 0\")\n    case True then have \"n \\<noteq> 0\" and \"a \\<le> 0\" using `odd n` [THEN odd_pos] by auto\n    then have \"a ^ n \\<le> 0\" unfolding power_le_zero_eq using `odd n` by auto\n    moreover\n    from `0 \\<le> b` have \"0 \\<le> b ^ n\" by auto\n    ultimately show ?thesis by auto\n  next\n    case False then have \"0 \\<le> a\" by auto\n    with `a \\<le> b` show ?thesis using power_mono by auto\n  qed\nqed\n \ntext {* Simplify, when the exponent is a numeral *}\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> numeral w = (0 :: nat)\n    \\<or> even (numeral w :: nat) \\<and> a \\<noteq> 0 \\<or> 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> (0 :: nat) < numeral w\n    \\<and> (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 {* Tools setup *}\n\ndeclare transfer_morphism_int_nat [transfer add return:\n  even_int_iff\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/Parity.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511616741041, "lm_q2_score": 0.849971175657575, "lm_q1q2_score": 0.7274488180760396}}
{"text": "(*\n  File:     More_Algebraic_Numbers_HLW.thy\n  Author:   Manuel Eberl, TU M\u00fcnchen\n*)\nsection \\<open>More facts about algebraic numbers\\<close>\ntheory More_Algebraic_Numbers_HLW\n  imports \"Algebraic_Numbers.Algebraic_Numbers\"\nbegin\n\nsubsection \\<open>Miscellaneous\\<close>\n\n(* TODO: Move! All of this belongs in Algebraic_Numbers *)\n\nlemma in_Ints_imp_algebraic [simp, intro]: \"x \\<in> \\<int> \\<Longrightarrow> algebraic x\"\n  by (intro algebraic_int_imp_algebraic int_imp_algebraic_int)\n\nlemma in_Rats_imp_algebraic [simp, intro]: \"x \\<in> \\<rat> \\<Longrightarrow> algebraic x\"\n  by (auto elim!: Rats_cases' intro: algebraic_div)\n\nlemma algebraic_uminus_iff [simp]: \"algebraic (-x) \\<longleftrightarrow> algebraic x\"\n  using algebraic_uminus[of x] algebraic_uminus[of \"-x\"] by auto\n\nlemma algebraic_0 [simp]: \"algebraic (0 :: 'a :: field_char_0)\"\n  and algebraic_1 [simp]: \"algebraic (1 :: 'a :: field_char_0)\"\n  by auto  \n\nlemma algebraic_sum_mset [intro]:\n  \"(\\<And>x. x \\<in># A \\<Longrightarrow> algebraic x) \\<Longrightarrow> algebraic (sum_mset A)\"\n  by (induction A) (auto intro!: algebraic_plus)\n\nlemma algebraic_prod_mset [intro]:\n  \"(\\<And>x. x \\<in># A \\<Longrightarrow> algebraic x) \\<Longrightarrow> algebraic (prod_mset A)\"\n  by (induction A) (auto intro!: algebraic_times)\n\nlemma algebraic_power [intro]: \"algebraic x \\<Longrightarrow> algebraic (x ^ n)\"\n  by (induction n) (auto intro: algebraic_times)\n\nlemma algebraic_csqrt [intro]: \"algebraic x \\<Longrightarrow> algebraic (csqrt x)\"\n  by (rule algebraic_nth_root[of 2 x]) auto\n\nlemma algebraic_csqrt_iff [simp]: \"algebraic (csqrt x) \\<longleftrightarrow> algebraic x\"\nproof\n  assume \"algebraic (csqrt x)\"\n  hence \"algebraic (csqrt x ^ 2)\"\n    by (rule algebraic_power)\n  also have \"csqrt x ^ 2 = x\"\n    by simp\n  finally show \"algebraic x\" .\nqed auto\n\nlemmas [intro] = algebraic_plus algebraic_times algebraic_uminus algebraic_div\n\nlemma algebraic_power_iff [simp]:\n  assumes \"n > 0\"\n  shows   \"algebraic (x ^ n) \\<longleftrightarrow> algebraic x\"\n  using algebraic_nth_root[of n \"x ^ n\" x] assms by auto\n\nlemma algebraic_ii [simp]: \"algebraic \\<i>\"\n  by (intro algebraic_int_imp_algebraic) auto\n\nlemma algebraic_int_fact [simp, intro]: \"algebraic_int (fact n)\"\n  by (intro int_imp_algebraic_int fact_in_Ints)\n\nlemma algebraic_minus [intro]: \"algebraic x \\<Longrightarrow> algebraic y \\<Longrightarrow> algebraic (x - y)\"\n  using algebraic_plus[of x \"-y\"] by simp\n\nlemma algebraic_add_cancel_left [simp]:\n  assumes \"algebraic x\"\n  shows   \"algebraic (x + y) \\<longleftrightarrow> algebraic y\"\nproof\n  assume \"algebraic (x + y)\"\n  hence \"algebraic (x + y - x)\"\n    using assms by (intro algebraic_minus) auto\n  thus \"algebraic y\" by simp\nqed (auto intro: algebraic_plus assms)\n\nlemma algebraic_add_cancel_right [simp]:\n  assumes \"algebraic y\"\n  shows   \"algebraic (x + y) \\<longleftrightarrow> algebraic x\"\n  using algebraic_add_cancel_left[of y x] assms\n  by (simp add: add.commute del: algebraic_add_cancel_left)\n\nlemma algebraic_diff_cancel_left [simp]:\n  assumes \"algebraic x\"\n  shows   \"algebraic (x - y) \\<longleftrightarrow> algebraic y\"\n  using algebraic_add_cancel_left[of x \"-y\"] assms by (simp del: algebraic_add_cancel_left)\n\nlemma algebraic_diff_cancel_right [simp]:\n  assumes \"algebraic y\"\n  shows   \"algebraic (x - y) \\<longleftrightarrow> algebraic x\"\n  using algebraic_add_cancel_right[of \"-y\" x] assms by (simp del: algebraic_add_cancel_right)\n\nlemma algebraic_mult_cancel_left [simp]:\n  assumes \"algebraic x\" \"x \\<noteq> 0\"\n  shows   \"algebraic (x * y) \\<longleftrightarrow> algebraic y\"\nproof\n  assume \"algebraic (x * y)\"\n  hence \"algebraic (x * y / x)\"\n    using assms by (intro algebraic_div) auto\n  also have \"x * y / x = y\"\n    using assms by auto\n  finally show \"algebraic y\" .\nqed (auto intro: algebraic_times assms)\n\nlemma algebraic_mult_cancel_right [simp]:\n  assumes \"algebraic y\" \"y \\<noteq> 0\"\n  shows   \"algebraic (x * y) \\<longleftrightarrow> algebraic x\"\n  using algebraic_mult_cancel_left[of y x] assms\n  by (simp add: mult.commute del: algebraic_mult_cancel_left)\n\nlemma algebraic_inverse_iff [simp]: \"algebraic (inverse y) \\<longleftrightarrow> algebraic y\"\nproof\n  assume \"algebraic (inverse y)\"\n  hence \"algebraic (inverse (inverse y))\"\n    by (rule algebraic_inverse)\n  thus \"algebraic y\" by simp\nqed (auto intro: algebraic_inverse)\n\nlemma algebraic_divide_cancel_left [simp]:\n  assumes \"algebraic x\" \"x \\<noteq> 0\"\n  shows   \"algebraic (x / y) \\<longleftrightarrow> algebraic y\"\nproof -\n  have \"algebraic (x * inverse y) \\<longleftrightarrow> algebraic (inverse y)\"\n    by (intro algebraic_mult_cancel_left assms)\n  also have \"\\<dots> \\<longleftrightarrow> algebraic y\"\n    by (intro algebraic_inverse_iff)\n  finally show ?thesis by (simp add: field_simps)\nqed\n\nlemma algebraic_divide_cancel_right [simp]:\n  assumes \"algebraic y\" \"y \\<noteq> 0\"\n  shows   \"algebraic (x / y) \\<longleftrightarrow> algebraic x\"\nproof -\n  have \"algebraic (x * inverse y) \\<longleftrightarrow> algebraic x\"\n    using assms by (intro algebraic_mult_cancel_right) auto\n  thus ?thesis by (simp add: field_simps)\nqed\n\n\nsubsection \\<open>Turning an algebraic number into an algebraic integer\\<close>\n\nsubsection \\<open>\n  Multiplying an algebraic number with a suitable integer turns it into an algebraic integer.\n\\<close>\n\nlemma algebraic_imp_algebraic_int:\n  fixes x :: \"'a :: field_char_0\"\n  assumes \"ipoly p x = 0\" \"p \\<noteq> 0\"\n  defines \"c \\<equiv> Polynomial.lead_coeff p\"\n  shows   \"algebraic_int (of_int c * x)\"\nproof -\n  define n where \"n = Polynomial.degree p\"\n  define p' where \"p' = Abs_poly (\\<lambda>i. if i = n then 1 else c ^ (n - i - 1) * poly.coeff p i)\"\n  have \"n > 0\"\n    using assms unfolding n_def by (intro Nat.gr0I) (auto elim!: degree_eq_zeroE)\n\n  have coeff_p': \"poly.coeff p' i =\n                    (if i = n then 1 else c ^ (n - i - 1) * poly.coeff p i)\"\n    (is \"_ = ?f i\") for i unfolding p'_def\n  proof (subst poly.Abs_poly_inverse)\n    have \"eventually (\\<lambda>i. poly.coeff p i = 0) cofinite\"\n      using MOST_coeff_eq_0 by blast\n    hence \"eventually (\\<lambda>i. ?f i = 0) cofinite\"\n      by eventually_elim (use assms in \\<open>auto simp: n_def\\<close>)\n    thus \"?f \\<in> {f. eventually (\\<lambda>i. f i = 0) cofinite}\" by simp\n  qed auto\n\n  have deg_p': \"Polynomial.degree p' = n\"\n  proof -\n    from assms have \"(\\<lambda>n. \\<forall>i>n. poly.coeff p' i = 0) = (\\<lambda>n. \\<forall>i>n. poly.coeff p i = 0)\"\n      by (auto simp: coeff_p' fun_eq_iff n_def)\n    thus ?thesis\n      by (simp add: Polynomial.degree_def n_def)\n  qed\n\n  have lead_coeff_p': \"Polynomial.lead_coeff p' = 1\"\n    by (simp add: coeff_p' deg_p')\n\n  have \"0 = of_int (c ^ (n - 1)) * (\\<Sum>i\\<le>n. of_int (poly.coeff p i) * x ^ i)\"\n    using assms unfolding n_def poly_altdef by simp\n  also have \"\\<dots> = (\\<Sum>i\\<le>n. of_int (c ^ (n - 1) * poly.coeff p i) * x ^ i)\"\n    by (simp add: sum_distrib_left sum_distrib_right mult_ac)\n  also have \"\\<dots> = (\\<Sum>i\\<le>n. of_int (poly.coeff p' i) * (of_int c * x) ^ i)\"\n  proof (intro sum.cong, goal_cases)\n    case (2 i)\n    have \"of_int (poly.coeff p' i) * (of_int c * x) ^ i =\n          of_int (c ^ i * poly.coeff p' i) * x ^ i\"\n      by (simp add: algebra_simps)\n    also have \"c ^ i * poly.coeff p' i = c ^ (n - 1) * poly.coeff p i\"\n    proof (cases \"i = n\")\n      case True\n      hence \"c ^ i * poly.coeff p' i = c ^ n\"\n        by (auto simp: coeff_p' simp flip: power_Suc)\n      also have \"n = Suc (n - 1)\"\n        using \\<open>n > 0\\<close> by simp\n      also have \"c ^ \\<dots> = c * c ^ (n - 1)\"\n        by simp\n      finally show ?thesis\n        using True by (simp add: c_def n_def)\n    next\n      case False\n      thus ?thesis using 2\n        by (auto simp: coeff_p' simp flip: power_add)\n    qed\n    finally show ?case ..\n  qed auto\n  also have \"\\<dots> = ipoly p' (of_int c * x)\"\n    by (simp add: poly_altdef n_def deg_p')\n  finally have \"ipoly p' (of_int c * x) = 0\" ..\n\n  with lead_coeff_p' show ?thesis\n    unfolding algebraic_int_altdef_ipoly by blast\nqed\n\nlemma algebraic_imp_algebraic_int':\n  fixes x :: \"'a :: field_char_0\"\n  assumes \"ipoly p x = 0\" \"p \\<noteq> 0\" \"Polynomial.lead_coeff p dvd c\"\n  shows   \"algebraic_int (of_int c * x)\"\nproof -\n  from assms(3) obtain c' where c_eq: \"c = Polynomial.lead_coeff p * c'\"\n    by auto\n  have \"algebraic_int (of_int c' * (of_int (Polynomial.lead_coeff p) * x))\"\n    by (rule algebraic_int_times[OF _ algebraic_imp_algebraic_int]) (use assms in auto)\n  also have \"of_int c' * (of_int (Polynomial.lead_coeff p) * x) = of_int c * x\"\n    by (simp add: c_eq mult_ac)\n  finally show ?thesis .\nqed\n\nend", "meta": {"author": "pruvisto", "repo": "Hermite_Lindemann", "sha": "fd5a3e09209f0f1a98d1e5e70d27d4a00c19af2e", "save_path": "github-repos/isabelle/pruvisto-Hermite_Lindemann", "path": "github-repos/isabelle/pruvisto-Hermite_Lindemann/Hermite_Lindemann-fd5a3e09209f0f1a98d1e5e70d27d4a00c19af2e/More_Algebraic_Numbers_HLW.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711832583695, "lm_q2_score": 0.8558511469672594, "lm_q1q2_score": 0.7274488120807941}}
{"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 n) = True\" |\n\"optimal (V x) = True\" |\n\"optimal (Plus (N i) (N j)) = False\" |\n\"optimal (Plus l r) = (optimal l & optimal r)\"\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 l r) = sumN l + sumN r\"\n\nfun zeroN :: \"aexp \\<Rightarrow> aexp\" where\n\"zeroN (N n) = N 0\" |\n\"zeroN (V x) = V x\" |\n\"zeroN (Plus l r) = Plus (zeroN l) (zeroN r)\"\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 exp = Plus (zeroN exp)  (N (sumN exp))\"\n\nlemma aval_sepN: \"aval (sepN t) s = aval t s\"\n  apply(simp add: sepN_def)\n  apply(induction t)\n    apply(auto)\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 exp = asimp (sepN exp)\"\n\nlemma aval_full_asimp: \"aval (full_asimp t) s = aval t s\"\n  apply(simp add: full_asimp_def aval_sepN)\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 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 l r) = Plus (subst x a l) (subst x a r)\"\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(simp add: subst_lemma)\n  done\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\ndatatype aexp2 =\n    Const int \n  | Var vname\n  | PlusOp aexp2 aexp2\n  | IncOp vname\n  | DivOp aexp2 aexp2\n\nfun aval2 :: \"aexp2 \\<Rightarrow> state \\<Rightarrow> (val \\<times> state) option\" \n  where\n    \"aval2 (Const n) s = Some (n, s)\"\n  | \"aval2 (Var x) s = Some (s x, s)\"\n  | \"aval2 (PlusOp l r) s =\n      Option.bind (aval2 l s) (\\<lambda> (lval, s\\<^sub>1). \n        Option.bind (aval2 r s\\<^sub>1) (\\<lambda> (rval, s\\<^sub>2).\n          Some (lval + rval, s\\<^sub>2)))\"\n  | \"aval2 (IncOp x) s = Some (s x, s(x := s x + 1))\"\n  | \"aval2 (DivOp l r) s =\n      Option.bind (aval2 l s) (\\<lambda> (lval, s\\<^sub>1). \n        Option.bind (aval2 r s\\<^sub>1) (\\<lambda> (rval, s\\<^sub>2).\n          if rval = 0 then None else Some (lval div rval, s\\<^sub>2)))\"\n\nvalue \"aval2 (PlusOp (IncOp ''x'') (DivOp (Const 5) (Var ''x''))) (<''x'' := -1>)\"\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\nfun lval :: \"lexp \\<Rightarrow> state \\<Rightarrow> int\"\n  where\n    \"lval (Nl n) s = n\"\n  | \"lval (Vl x) s = s x\"\n  | \"lval (Plusl l r) s = lval l s + lval r s\"\n  | \"lval (LET x e\\<^sub>1 e\\<^sub>2) s = lval e\\<^sub>2 (s(x := lval e\\<^sub>1 s))\"\n\nvalue \"lval \n        (LET ''x'' (Nl 5)\n          (Plusl (Vl ''x'') (Nl 5))) <>\"\n\nfun inline :: \"lexp \\<Rightarrow> aexp\"\n  where\n    \"inline (Nl n) = N n\"\n  | \"inline (Vl x) = V x\"\n  | \"inline (Plusl l r) = Plus (inline l) (inline r)\"\n  | \"inline (LET x e\\<^sub>1 e\\<^sub>2) = subst x (inline e\\<^sub>1) (inline e\\<^sub>2)\"\n\nlemma \"lval e s = aval (inline e) s\"\n  apply(induction e arbitrary: s)\n     apply(auto simp add: subst_lemma)\n  done\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 Or :: \"bexp \\<Rightarrow> bexp \\<Rightarrow> bexp\" where\n\"Or e\\<^sub>1 e\\<^sub>2 = Not (And (Not e\\<^sub>1) (Not e\\<^sub>2))\"\n\ndefinition Eq :: \"aexp \\<Rightarrow> aexp \\<Rightarrow> bexp\" where\n\"Eq e\\<^sub>1 e\\<^sub>2 = And (Not (Less e\\<^sub>1 e\\<^sub>2)) (Not (Less e\\<^sub>2 e\\<^sub>1))\"\n\nvalue \"bval (Eq (N 5) (Plus (N 3) (V ''x''))) <''x'' := 2>\"\n\ndefinition Le :: \"aexp \\<Rightarrow> aexp \\<Rightarrow> bexp\" where\n\"Le e\\<^sub>1 e\\<^sub>2 = Or (Eq e\\<^sub>1 e\\<^sub>2) (Less e\\<^sub>1 e\\<^sub>2)\"\n\nvalue \"bval (Le (N 5) (Plus (N 3) (V ''x''))) <''x'' := 3>\"\n\ntext{*\nand prove that they do what they are supposed to:\n*}\n\nlemma bval_Eq: \"bval (Eq a1 a2) s = (aval a1 s = aval a2 s)\"\n  apply(simp add: Eq_def)\n  apply(auto)\n  done\n\nlemma bval_Le: \"bval (Le a1 a2) s = (aval a1 s \\<le> aval a2 s)\"\n  apply(simp add: Le_def Eq_def Or_def)\n  apply(auto)\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\" \n  where\n    \"ifval (Bc2 b) s = b\"\n  | \"ifval (If e\\<^sub>1 e\\<^sub>2 e\\<^sub>3) s = \n      (if ifval e\\<^sub>1 s then \n         ifval e\\<^sub>2 s \n       else \n         ifval e\\<^sub>3 s)\"\n  | \"ifval (Less2 a\\<^sub>1 a\\<^sub>2) s = (aval a\\<^sub>1 s < aval a\\<^sub>2 s)\"\n\ntext{* Then define two translation functions *}\n\nfun b2ifexp :: \"bexp \\<Rightarrow> ifexp\" \n  where\n    \"b2ifexp (Bc b) = Bc2 b\"\n  | \"b2ifexp (Not e) = (If (b2ifexp e) (Bc2 False) (Bc2 True))\"\n  | \"b2ifexp (And e\\<^sub>1 e\\<^sub>2) =\n      (If (b2ifexp e\\<^sub>1) \n        (If (b2ifexp e\\<^sub>2) \n          (Bc2 True) \n          (Bc2 False)) \n        (Bc2 False))\"\n  | \"b2ifexp (Less a\\<^sub>1 a\\<^sub>2) = Less2 a\\<^sub>1 a\\<^sub>2\"\n\n(* if a then b else c \\<equiv> (a \\<and> b) \\<or> (\\<not>a \\<and> c) *)\nfun if2bexp :: \"ifexp \\<Rightarrow> bexp\" \n  where\n    \"if2bexp (Bc2 b) = Bc b\"\n  | \"if2bexp (If e\\<^sub>1 e\\<^sub>2 e\\<^sub>3) = \n      (let be\\<^sub>1 = if2bexp e\\<^sub>1 in\n        Or (And      be\\<^sub>1  (if2bexp e\\<^sub>2)) \n           (And (Not be\\<^sub>1) (if2bexp e\\<^sub>3)))\"\n  | \"if2bexp (Less2 a\\<^sub>1 a\\<^sub>2) = Less a\\<^sub>1 a\\<^sub>2\"\n\ntext{* and prove their correctness: *}\n\nlemma \"bval (if2bexp exp) s = ifval exp s\"\n  apply(induction exp arbitrary: s)\n    apply(auto simp add: Let_def Or_def)\n  done\n\nlemma \"ifval (b2ifexp exp) s = bval exp s\"\n  apply(induction exp arbitrary: s)\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\"\n  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 expression 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\" \n  where\n    \"is_nnf (VAR x) = True\"\n  | \"is_nnf (NOT (VAR x)) = True\"\n  | \"is_nnf (NOT b) = False\"\n  | \"is_nnf (AND b\\<^sub>1 b\\<^sub>2) = (is_nnf b\\<^sub>1 & is_nnf b\\<^sub>2)\"\n  | \"is_nnf (OR b\\<^sub>1 b\\<^sub>2) = (is_nnf b\\<^sub>1 & is_nnf b\\<^sub>2)\" \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\" \n  where\n    \"nnf (VAR x) = VAR x\"\n  | \"nnf (NOT (AND b\\<^sub>1 b\\<^sub>2)) = OR (nnf (NOT b\\<^sub>1)) (nnf (NOT b\\<^sub>2))\"\n  | \"nnf (NOT (OR b\\<^sub>1 b\\<^sub>2)) = AND (nnf (NOT b\\<^sub>1)) (nnf (NOT b\\<^sub>2))\"\n  | \"nnf (NOT (NOT b)) = nnf b\"\n  | \"nnf (AND b\\<^sub>1 b\\<^sub>2) = AND (nnf b\\<^sub>1) (nnf b\\<^sub>2)\"\n  | \"nnf (OR b\\<^sub>1 b\\<^sub>2) = OR (nnf b\\<^sub>1) (nnf b\\<^sub>2)\"\n  | \"nnf b = b\"\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  apply(induction b arbitrary:s rule:nnf.induct)\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 is_dnf :: \"pbexp \\<Rightarrow> bool\" \n  where\n    \"is_dnf (AND (OR _ _) _) = False\"\n  | \"is_dnf (AND _ (OR _ _)) = False\"\n  | \"is_dnf (AND b\\<^sub>1 b\\<^sub>2) = (is_dnf b\\<^sub>1 & is_dnf b\\<^sub>2)\"\n  | \"is_dnf (OR b\\<^sub>1 b\\<^sub>2) = (is_dnf b\\<^sub>1 & is_dnf b\\<^sub>2)\"\n  | \"is_dnf b = is_nnf b\"\n\nvalue \"is_dnf (OR (AND (VAR ''A'') (VAR ''B'')) (NOT (VAR ''A'')))\"\nvalue \"is_dnf (NOT (OR (VAR ''A'') (VAR ''B'')))\"\nvalue \"is_dnf (OR (VAR ''A'') \n                  (AND (VAR ''B'') \n                       (OR (VAR ''C'') \n                           (VAR ''D''))))\"\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\" \n  where\n    \"dist_AND b (OR c\\<^sub>1 c\\<^sub>2) = OR (dist_AND b c\\<^sub>1) (dist_AND b c\\<^sub>2)\"\n  | \"dist_AND (OR b\\<^sub>1 b\\<^sub>2) c = OR (dist_AND b\\<^sub>1 c) (dist_AND b\\<^sub>2 c)\"\n  | \"dist_AND b c = AND b c\"\n\nvalue \"dist_AND (OR (VAR ''A1'') (VAR ''A2''))\n                (OR (VAR ''B1'') (VAR ''B2''))\"\n\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  apply(induction b1 b2 arbitrary:s 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\"\n  where\n    \"dnf_of_nnf (AND b\\<^sub>1 b\\<^sub>2) = dist_AND (dnf_of_nnf b\\<^sub>1) (dnf_of_nnf b\\<^sub>2)\"\n  | \"dnf_of_nnf (OR b\\<^sub>1 b\\<^sub>2) = OR (dnf_of_nnf b\\<^sub>1) (dnf_of_nnf b\\<^sub>2)\"\n  | \"dnf_of_nnf b = b\"\n\ntext {* Prove the correctness of your function: *}\n\nlemma \"pbval (dnf_of_nnf b) s = pbval b s\"\n  apply(induction b arbitrary:s rule:dnf_of_nnf.induct)\n    apply(auto simp add:pbval_dist)\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:is_dnf_dist)\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 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\" \n  where\n    \"exec1 (LDI v r) _ rs = rs(r := v)\"\n  | \"exec1 (LD vn r) s rs = rs(r := s vn)\"\n  | \"exec1 (ADD r\\<^sub>1 r\\<^sub>2) _ rs = rs(r\\<^sub>1 := rs r\\<^sub>1 + rs r\\<^sub>2)\"\n\ntext{*\nDefine the execution @{const[source] exec} of a list of instructions as for the stack machine.*}\n\nfun exec :: \"instr list \\<Rightarrow> state \\<Rightarrow> rstate \\<Rightarrow> rstate\"\n  where\n    \"exec [] _ rs = rs\"\n  | \"exec (x#xs) s rs = exec xs s (exec1 x s rs)\"\n\nvalue \"exec [LDI 2 0, LDI 2 1, ADD 0 1] <> <> 0\"\nvalue \"exec [LDI 2 0, LD ''x'' 1, ADD 0 1] <''x'' := 3> <> 0\"\n\ntext{* \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 comp :: \"aexp \\<Rightarrow> reg \\<Rightarrow> instr list\" \n  where\n    \"comp (N n) r = [LDI n r]\"\n  | \"comp (V x) r = [LD x r]\"\n  | \"comp (Plus e\\<^sub>1 e\\<^sub>2) r = comp e\\<^sub>1 r @ comp e\\<^sub>2 (r+1) @ [ADD r (r+1)]\"\n\nvalue \"comp (Plus (N 2) (N 2)) 0\"\nvalue \"comp (Plus (Plus (N 1) (N 2)) (Plus (N 1) (N 0))) 0\"\n\nvalue \"exec (comp \n              (Plus (Plus (N 2) (N 2)) (Plus (N 1) (N 5)))\n              0)\n            <>\n            <>\n            0\"\n\nlemma exec_append: \"exec (p\\<^sub>1 @ p\\<^sub>2) s rs = exec p\\<^sub>2 s (exec p\\<^sub>1 s rs)\"\n  apply(induction p\\<^sub>1 arbitrary: rs)\n   apply(auto)\n  done\n\nlemma exec_safe: \"rn > r \\<Longrightarrow> exec (comp a rn) s rs r = rs r\"\n  apply(induction a arbitrary: r rn rs)\n    apply(auto simp add: 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: exec_append exec_safe)\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\"\n  where\n    \"exec01 (LDI0 n) s rs = rs(0 := n)\"\n  | \"exec01 (LD0 vn) s rs = rs(0 := s vn)\"\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> rstate\"\n  where\n    \"exec0 [] s rs = rs\"\n  | \"exec0 (x#xs) s rs = exec0 xs s (exec01 x s rs)\"\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 comp0 :: \"aexp \\<Rightarrow> reg \\<Rightarrow> instr0 list\"\n  where\n    \"comp0 (N n) r = [LDI0 n]\"\n  | \"comp0 (V x) r = [LD0 x]\"\n  | \"comp0 (Plus e\\<^sub>1 e\\<^sub>2) r = comp0 e\\<^sub>1 r @ [MV0 (r+1)] @ comp0 e\\<^sub>2 (r+1) @ [ADD0 (r+1)]\"\n\nlemma comp0_append: \"exec0 (p\\<^sub>1 @ p\\<^sub>2) s rs = exec0 p\\<^sub>2 s (exec0 p\\<^sub>1 s rs)\"\n  apply(induction p\\<^sub>1 arbitrary: rs)\n   apply(auto)\n  done\n\nlemma comp0_safe: \"\\<lbrakk>r \\<noteq> 0 \\<and> rn \\<ge> r\\<rbrakk> \\<Longrightarrow> exec0 (comp0 a rn) s rs r = rs r\"\n  apply(induction a arbitrary: r rn rs)\n    apply(auto simp add: comp0_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: comp0_append comp0_safe)\n  done\n\ntext{*\n\\endexercise\n*}\n\nend\n\n", "meta": {"author": "gsomix", "repo": "concrete-semantics-solutions", "sha": "de38182f1e4c6c70d5fb544808f5566e92899bfd", "save_path": "github-repos/isabelle/gsomix-concrete-semantics-solutions", "path": "github-repos/isabelle/gsomix-concrete-semantics-solutions/concrete-semantics-solutions-de38182f1e4c6c70d5fb544808f5566e92899bfd/Chapter3.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8558511469672594, "lm_q2_score": 0.849971175657575, "lm_q1q2_score": 0.7274488055756454}}
{"text": "(* Author: Tobias Nipkow *)\n\nsection \"Join-Based Implementation of Sets\"\n\ntheory Set2_Join\nimports\n  Isin2\nbegin\n\ntext \\<open>This theory implements the set operations \\<open>insert\\<close>, \\<open>delete\\<close>,\n\\<open>union\\<close>, \\<open>inter\\<close>section and \\<open>diff\\<close>erence. The implementation is based on binary search trees.\nAll operations are reduced to a single operation \\<open>join l x r\\<close> that joins two BSTs \\<open>l\\<close> and \\<open>r\\<close>\nand an element \\<open>x\\<close> such that \\<open>l < x < r\\<close>.\n\nThe theory is based on theory \\<^theory>\\<open>HOL-Data_Structures.Tree2\\<close> where nodes have an additional field.\nThis field is ignored here but it means that this theory can be instantiated\nwith red-black trees (see theory \\<^file>\\<open>Set2_Join_RBT.thy\\<close>) and other balanced trees.\nThis approach is very concrete and fixes the type of trees.\nAlternatively, one could assume some abstract type \\<^typ>\\<open>'t\\<close> of trees with suitable decomposition\nand recursion operators on it.\\<close>\n\nlocale Set2_Join =\nfixes join :: \"('a::linorder*'b) tree \\<Rightarrow> 'a \\<Rightarrow> ('a*'b) tree \\<Rightarrow> ('a*'b) tree\"\nfixes inv :: \"('a*'b) tree \\<Rightarrow> bool\"\nassumes set_join: \"set_tree (join l a r) = set_tree l \\<union> {a} \\<union> set_tree r\"\nassumes bst_join: \"bst (Node l (a, b) r) \\<Longrightarrow> bst (join l a r)\"\nassumes inv_Leaf: \"inv \\<langle>\\<rangle>\"\nassumes inv_join: \"\\<lbrakk> inv l; inv r \\<rbrakk> \\<Longrightarrow> inv (join l a r)\"\nassumes inv_Node: \"\\<lbrakk> inv (Node l (a,b) r) \\<rbrakk> \\<Longrightarrow> inv l \\<and> inv r\"\nbegin\n\ndeclare set_join [simp] Let_def[simp]\n\nsubsection \"\\<open>split_min\\<close>\"\n\nfun split_min :: \"('a*'b) tree \\<Rightarrow> 'a \\<times> ('a*'b) tree\" where\n\"split_min (Node l (a, _) r) =\n  (if l = Leaf then (a,r) else let (m,l') = split_min l in (m, join l' a r))\"\n\nlemma split_min_set:\n  \"\\<lbrakk> split_min t = (m,t');  t \\<noteq> Leaf \\<rbrakk> \\<Longrightarrow> m \\<in> set_tree t \\<and> set_tree t = {m} \\<union> set_tree t'\"\nproof(induction t arbitrary: t' rule: tree2_induct)\n  case Node thus ?case by(auto split: prod.splits if_splits dest: inv_Node)\nnext\n  case Leaf thus ?case by simp\nqed\n\nlemma split_min_bst:\n  \"\\<lbrakk> split_min t = (m,t');  bst t;  t \\<noteq> Leaf \\<rbrakk> \\<Longrightarrow>  bst t' \\<and> (\\<forall>x \\<in> set_tree t'. m < x)\"\nproof(induction t arbitrary: t' rule: tree2_induct)\n  case Node thus ?case by(fastforce simp: split_min_set bst_join split: prod.splits if_splits)\nnext\n  case Leaf thus ?case by simp\nqed\n\nlemma split_min_inv:\n  \"\\<lbrakk> split_min t = (m,t');  inv t;  t \\<noteq> Leaf \\<rbrakk> \\<Longrightarrow>  inv t'\"\nproof(induction t arbitrary: t' rule: tree2_induct)\n  case Node thus ?case by(auto simp: inv_join split: prod.splits if_splits dest: inv_Node)\nnext\n  case Leaf thus ?case by simp\nqed\n\n\nsubsection \"\\<open>join2\\<close>\"\n\nfun join2 :: \"('a*'b) tree \\<Rightarrow> ('a*'b) tree \\<Rightarrow> ('a*'b) tree\" where\n\"join2 l \\<langle>\\<rangle> = l\" |\n\"join2 l r = (let (m,r') = split_min r in join l m r')\"\n\nlemma set_join2[simp]: \"set_tree (join2 l r) = set_tree l \\<union> set_tree r\"\nby(cases r)(simp_all add: split_min_set split: prod.split)\n\nlemma bst_join2: \"\\<lbrakk> bst l; bst r; \\<forall>x \\<in> set_tree l. \\<forall>y \\<in> set_tree r. x < y \\<rbrakk>\n  \\<Longrightarrow> bst (join2 l r)\"\nby(cases r)(simp_all add: bst_join split_min_set split_min_bst split: prod.split)\n\nlemma inv_join2: \"\\<lbrakk> inv l; inv r \\<rbrakk> \\<Longrightarrow> inv (join2 l r)\"\nby(cases r)(simp_all add: inv_join split_min_set split_min_inv split: prod.split)\n\n\nsubsection \"\\<open>split\\<close>\"\n\nfun split :: \"('a*'b)tree \\<Rightarrow> 'a \\<Rightarrow> ('a*'b)tree \\<times> bool \\<times> ('a*'b)tree\" where\n\"split Leaf k = (Leaf, False, Leaf)\" |\n\"split (Node l (a, _) r) x =\n  (case cmp x a of\n     LT \\<Rightarrow> let (l1,b,l2) = split l x in (l1, b, join l2 a r) |\n     GT \\<Rightarrow> let (r1,b,r2) = split r x in (join l a r1, b, r2) |\n     EQ \\<Rightarrow> (l, True, r))\"\n\nlemma split: \"split t x = (l,b,r) \\<Longrightarrow> bst t \\<Longrightarrow>\n  set_tree l = {a \\<in> set_tree t. a < x} \\<and> set_tree r = {a \\<in> set_tree t. x < a}\n  \\<and> (b = (x \\<in> set_tree t)) \\<and> bst l \\<and> bst r\"\nproof(induction t arbitrary: l b r rule: tree2_induct)\n  case Leaf thus ?case by simp\nnext\n  case (Node y a b z l c r)\n  consider (LT) l1 xin l2 where \"(l1,xin,l2) = split y x\" \n    and \"split \\<langle>y, (a, b), z\\<rangle> x = (l1, xin, join l2 a z)\" and \"cmp x a = LT\"\n  | (GT) r1 xin r2 where \"(r1,xin,r2) = split z x\" \n    and \"split \\<langle>y, (a, b), z\\<rangle> x = (join y a r1, xin, r2)\" and \"cmp x a = GT\"\n  | (EQ) \"split \\<langle>y, (a, b), z\\<rangle> x = (y, True, z)\" and \"cmp x a = EQ\"\n    by (force split: cmp_val.splits prod.splits if_splits)\n\n  thus ?case \n  proof cases\n    case (LT l1 xin l2)\n    with Node.IH(1)[OF \\<open>(l1,xin,l2) = split y x\\<close>[symmetric]] Node.prems\n    show ?thesis by (force intro!: bst_join)\n  next\n    case (GT r1 xin r2)\n    with Node.IH(2)[OF \\<open>(r1,xin,r2) = split z x\\<close>[symmetric]] Node.prems\n    show ?thesis by (force intro!: bst_join)\n  next\n    case EQ\n    with Node.prems show ?thesis by auto\n  qed\nqed\n\nlemma split_inv: \"split t x = (l,b,r) \\<Longrightarrow> inv t \\<Longrightarrow> inv l \\<and> inv r\"\nproof(induction t arbitrary: l b r rule: tree2_induct)\n  case Leaf thus ?case by simp\nnext\n  case Node\n  thus ?case by(force simp: inv_join split!: prod.splits if_splits dest!: inv_Node)\nqed\n\ndeclare split.simps[simp del]\n\n\nsubsection \"\\<open>insert\\<close>\"\n\ndefinition insert :: \"'a \\<Rightarrow> ('a*'b) tree \\<Rightarrow> ('a*'b) tree\" where\n\"insert x t = (let (l,_,r) = split t x in join l x r)\"\n\nlemma set_tree_insert: \"bst t \\<Longrightarrow> set_tree (insert x t) = {x} \\<union> set_tree t\"\nby(auto simp add: insert_def split split: prod.split)\n\nlemma bst_insert: \"bst t \\<Longrightarrow> bst (insert x t)\"\nby(auto simp add: insert_def bst_join dest: split split: prod.split)\n\nlemma inv_insert: \"inv t \\<Longrightarrow> inv (insert x t)\"\nby(force simp: insert_def inv_join dest: split_inv split: prod.split)\n\n\nsubsection \"\\<open>delete\\<close>\"\n\ndefinition delete :: \"'a \\<Rightarrow> ('a*'b) tree \\<Rightarrow> ('a*'b) tree\" where\n\"delete x t = (let (l,_,r) = split t x in join2 l r)\"\n\nlemma set_tree_delete: \"bst t \\<Longrightarrow> set_tree (delete x t) = set_tree t - {x}\"\nby(auto simp: delete_def split split: prod.split)\n\nlemma bst_delete: \"bst t \\<Longrightarrow> bst (delete x t)\"\nby(force simp add: delete_def intro: bst_join2 dest: split split: prod.split)\n\nlemma inv_delete: \"inv t \\<Longrightarrow> inv (delete x t)\"\nby(force simp: delete_def inv_join2 dest: split_inv split: prod.split)\n\n\nsubsection \"\\<open>union\\<close>\"\n\nfun union :: \"('a*'b)tree \\<Rightarrow> ('a*'b)tree \\<Rightarrow> ('a*'b)tree\" where\n\"union t1 t2 =\n  (if t1 = Leaf then t2 else\n   if t2 = Leaf then t1 else\n   case t1 of Node l1 (a, _) r1 \\<Rightarrow>\n   let (l2,_ ,r2) = split t2 a;\n       l' = union l1 l2; r' = union r1 r2\n   in join l' a r')\"\n\ndeclare union.simps [simp del]\n\nlemma set_tree_union: \"bst t2 \\<Longrightarrow> set_tree (union t1 t2) = set_tree t1 \\<union> set_tree t2\"\nproof(induction t1 t2 rule: union.induct)\n  case (1 t1 t2)\n  then show ?case\n    by (auto simp: union.simps[of t1 t2] split split: tree.split prod.split)\nqed\n\nlemma bst_union: \"\\<lbrakk> bst t1; bst t2 \\<rbrakk> \\<Longrightarrow> bst (union t1 t2)\"\nproof(induction t1 t2 rule: union.induct)\n  case (1 t1 t2)\n  thus ?case\n    by(fastforce simp: union.simps[of t1 t2] set_tree_union split intro!: bst_join \n        split: tree.split prod.split)\nqed\n\nlemma inv_union: \"\\<lbrakk> inv t1; inv t2 \\<rbrakk> \\<Longrightarrow> inv (union t1 t2)\"\nproof(induction t1 t2 rule: union.induct)\n  case (1 t1 t2)\n  thus ?case\n    by(auto simp:union.simps[of t1 t2] inv_join split_inv\n        split!: tree.split prod.split dest: inv_Node)\nqed\n\nsubsection \"\\<open>inter\\<close>\"\n\nfun inter :: \"('a*'b)tree \\<Rightarrow> ('a*'b)tree \\<Rightarrow> ('a*'b)tree\" where\n\"inter t1 t2 =\n  (if t1 = Leaf then Leaf else\n   if t2 = Leaf then Leaf else\n   case t1 of Node l1 (a, _) r1 \\<Rightarrow>\n   let (l2,b,r2) = split t2 a;\n       l' = inter l1 l2; r' = inter r1 r2\n   in if b then join l' a r' else join2 l' r')\"\n\ndeclare inter.simps [simp del]\n\nlemma set_tree_inter:\n  \"\\<lbrakk> bst t1; bst t2 \\<rbrakk> \\<Longrightarrow> set_tree (inter t1 t2) = set_tree t1 \\<inter> set_tree t2\"\nproof(induction t1 t2 rule: inter.induct)\n  case (1 t1 t2)\n  show ?case\n  proof (cases t1 rule: tree2_cases)\n    case Leaf thus ?thesis by (simp add: inter.simps)\n  next\n    case [simp]: (Node l1 a _ r1)\n    show ?thesis\n    proof (cases \"t2 = Leaf\")\n      case True thus ?thesis by (simp add: inter.simps)\n    next\n      case False\n      let ?L1 = \"set_tree l1\" let ?R1 = \"set_tree r1\"\n      have *: \"a \\<notin> ?L1 \\<union> ?R1\" using \\<open>bst t1\\<close> by (fastforce)\n      obtain l2 b r2 where sp: \"split t2 a = (l2,b,r2)\" using prod_cases3 by blast\n      let ?L2 = \"set_tree l2\" let ?R2 = \"set_tree r2\" let ?A = \"if b then {a} else {}\"\n      have t2: \"set_tree t2 = ?L2 \\<union> ?R2 \\<union> ?A\" and\n           **: \"?L2 \\<inter> ?R2 = {}\" \"a \\<notin> ?L2 \\<union> ?R2\" \"?L1 \\<inter> ?R2 = {}\" \"?L2 \\<inter> ?R1 = {}\"\n        using split[OF sp] \\<open>bst t1\\<close> \\<open>bst t2\\<close> by (force, force, force, force, force)\n      have IHl: \"set_tree (inter l1 l2) = set_tree l1 \\<inter> set_tree l2\"\n        using \"1.IH\"(1)[OF _ False _ _ sp[symmetric]] \"1.prems\"(1,2) split[OF sp] by simp\n      have IHr: \"set_tree (inter r1 r2) = set_tree r1 \\<inter> set_tree r2\"\n        using \"1.IH\"(2)[OF _ False _ _ sp[symmetric]] \"1.prems\"(1,2) split[OF sp] by simp\n      have \"set_tree t1 \\<inter> set_tree t2 = (?L1 \\<union> ?R1 \\<union> {a}) \\<inter> (?L2 \\<union> ?R2 \\<union> ?A)\"\n        by(simp add: t2)\n      also have \"\\<dots> = (?L1 \\<inter> ?L2) \\<union> (?R1 \\<inter> ?R2) \\<union> ?A\"\n        using * ** by auto\n      also have \"\\<dots> = set_tree (inter t1 t2)\"\n      using IHl IHr sp inter.simps[of t1 t2] False by(simp)\n      finally show ?thesis by simp\n    qed\n  qed\nqed\n\nlemma bst_inter: \"\\<lbrakk> bst t1; bst t2 \\<rbrakk> \\<Longrightarrow> bst (inter t1 t2)\"\nproof(induction t1 t2 rule: inter.induct)\n  case (1 t1 t2)\n  thus ?case\n    by(fastforce simp: inter.simps[of t1 t2] set_tree_inter split\n        intro!: bst_join bst_join2 split: tree.split prod.split)\nqed\n\nlemma inv_inter: \"\\<lbrakk> inv t1; inv t2 \\<rbrakk> \\<Longrightarrow> inv (inter t1 t2)\"\nproof(induction t1 t2 rule: inter.induct)\n  case (1 t1 t2)\n  thus ?case\n    by(auto simp: inter.simps[of t1 t2] inv_join inv_join2 split_inv\n        split!: tree.split prod.split dest: inv_Node)\nqed\n\nsubsection \"\\<open>diff\\<close>\"\n\nfun diff :: \"('a*'b)tree \\<Rightarrow> ('a*'b)tree \\<Rightarrow> ('a*'b)tree\" where\n\"diff t1 t2 =\n  (if t1 = Leaf then Leaf else\n   if t2 = Leaf then t1 else\n   case t2 of Node l2 (a, _) r2 \\<Rightarrow>\n   let (l1,_,r1) = split t1 a;\n       l' = diff l1 l2; r' = diff r1 r2\n   in join2 l' r')\"\n\ndeclare diff.simps [simp del]\n\nlemma set_tree_diff:\n  \"\\<lbrakk> bst t1; bst t2 \\<rbrakk> \\<Longrightarrow> set_tree (diff t1 t2) = set_tree t1 - set_tree t2\"\nproof(induction t1 t2 rule: diff.induct)\n  case (1 t1 t2)\n  show ?case\n  proof (cases t2 rule: tree2_cases)\n    case Leaf thus ?thesis by (simp add: diff.simps)\n  next\n    case [simp]: (Node l2 a _ r2)\n    show ?thesis\n    proof (cases \"t1 = Leaf\")\n      case True thus ?thesis by (simp add: diff.simps)\n    next\n      case False\n      let ?L2 = \"set_tree l2\" let ?R2 = \"set_tree r2\"\n      obtain l1 b r1 where sp: \"split t1 a = (l1,b,r1)\" using prod_cases3 by blast\n      let ?L1 = \"set_tree l1\" let ?R1 = \"set_tree r1\" let ?A = \"if b then {a} else {}\"\n      have t1: \"set_tree t1 = ?L1 \\<union> ?R1 \\<union> ?A\" and\n           **: \"a \\<notin> ?L1 \\<union> ?R1\" \"?L1 \\<inter> ?R2 = {}\" \"?L2 \\<inter> ?R1 = {}\"\n        using split[OF sp] \\<open>bst t1\\<close> \\<open>bst t2\\<close> by (force, force, force, force)\n      have IHl: \"set_tree (diff l1 l2) = set_tree l1 - set_tree l2\"\n        using \"1.IH\"(1)[OF False _ _ _ sp[symmetric]] \"1.prems\"(1,2) split[OF sp] by simp\n      have IHr: \"set_tree (diff r1 r2) = set_tree r1 - set_tree r2\"\n        using \"1.IH\"(2)[OF False _ _ _ sp[symmetric]] \"1.prems\"(1,2) split[OF sp] by simp\n      have \"set_tree t1 - set_tree t2 = (?L1 \\<union> ?R1) - (?L2 \\<union> ?R2  \\<union> {a})\"\n        by(simp add: t1)\n      also have \"\\<dots> = (?L1 - ?L2) \\<union> (?R1 - ?R2)\"\n        using ** by auto\n      also have \"\\<dots> = set_tree (diff t1 t2)\"\n      using IHl IHr sp diff.simps[of t1 t2] False by(simp)\n      finally show ?thesis by simp\n    qed\n  qed\nqed\n\nlemma bst_diff: \"\\<lbrakk> bst t1; bst t2 \\<rbrakk> \\<Longrightarrow> bst (diff t1 t2)\"\nproof(induction t1 t2 rule: diff.induct)\n  case (1 t1 t2)\n  thus ?case\n    by(fastforce simp: diff.simps[of t1 t2] set_tree_diff split\n        intro!: bst_join bst_join2 split: tree.split prod.split)\nqed\n\nlemma inv_diff: \"\\<lbrakk> inv t1; inv t2 \\<rbrakk> \\<Longrightarrow> inv (diff t1 t2)\"\nproof(induction t1 t2 rule: diff.induct)\n  case (1 t1 t2)\n  thus ?case\n    by(auto simp: diff.simps[of t1 t2] inv_join inv_join2 split_inv\n        split!: tree.split prod.split dest: inv_Node)\nqed\n\ntext \\<open>Locale \\<^locale>\\<open>Set2_Join\\<close> implements locale \\<^locale>\\<open>Set2\\<close>:\\<close>\n\nsublocale Set2\nwhere empty = Leaf and insert = insert and delete = delete and isin = isin\nand union = union and inter = inter and diff = diff\nand set = set_tree and invar = \"\\<lambda>t. inv t \\<and> bst t\"\nproof (standard, goal_cases)\n  case 1 show ?case by (simp)\nnext\n  case 2 thus ?case by(simp add: isin_set_tree)\nnext\n  case 3 thus ?case by (simp add: set_tree_insert)\nnext\n  case 4 thus ?case by (simp add: set_tree_delete)\nnext\n  case 5 thus ?case by (simp add: inv_Leaf)\nnext\n  case 6 thus ?case by (simp add: bst_insert inv_insert)\nnext\n  case 7 thus ?case by (simp add: bst_delete inv_delete)\nnext\n  case 8 thus ?case by(simp add: set_tree_union)\nnext\n  case 9 thus ?case by(simp add: set_tree_inter)\nnext\n  case 10 thus ?case by(simp add: set_tree_diff)\nnext\n  case 11 thus ?case by (simp add: bst_union inv_union)\nnext\n  case 12 thus ?case by (simp add: bst_inter inv_inter)\nnext\n  case 13 thus ?case by (simp add: bst_diff inv_diff)\nqed\n\nend\n\ninterpretation unbal: Set2_Join\nwhere join = \"\\<lambda>l x r. Node l (x, ()) r\" and inv = \"\\<lambda>t. True\"\nproof (standard, goal_cases)\n  case 1 show ?case by simp\nnext\n  case 2 thus ?case by simp\nnext\n  case 3 thus ?case by simp\nnext\n  case 4 thus ?case by simp\nnext\n  case 5 thus ?case by simp\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/Data_Structures/Set2_Join.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8499711680567799, "lm_q2_score": 0.8558511451289038, "lm_q1q2_score": 0.727448797507947}}
{"text": "(*\n    File:      Multiplicative_Characters.thy\n    Author:    Manuel Eberl, TU M\u00fcnchen\n*)\nsection \\<open>Multiplicative Characters of Finite Abelian Groups\\<close>\ntheory Multiplicative_Characters\n  imports\n  Complex_Main\n  Fundamental\nbegin\n\nsubsection \\<open>Definition of characters\\<close>\n\ntext \\<open>\n  A (multiplicative) character is a completely multiplicative function from a group to the\n  complex numbers. For simplicity, we restrict this to finite abelian groups here, which is\n  the most interesting case.\n\n  Characters form a group where the identity is the \\emph{principal} character that maps all\n  elements to $1$, multiplication is point-wise multiplication of the characters, and the inverse\n  is the point-wise complex conjugate.\n\n  This group is often called the \\emph{Pontryagin dual} group and is isomorphic to the original\n  group (in a non-natural way) while the double-dual group \\<^emph>\\<open>is\\<close> naturally isomorphic to the\n  original group.\n\n  To get extensionality of the characters, we also require characters to map anything that is\n  not in the group to $0$.\n\\<close>\n\ndefinition principal_char :: \"('a, 'b) monoid_scheme \\<Rightarrow> 'a \\<Rightarrow> complex\" where\n  \"principal_char G a = (if a \\<in> carrier G then 1 else 0)\"\n\ndefinition inv_character where\n  \"inv_character \\<chi> = (\\<lambda>a. cnj (\\<chi> a))\"\n\nlemma inv_character_principal [simp]: \"inv_character (principal_char G) = principal_char G\"\n  by (simp add: inv_character_def principal_char_def fun_eq_iff)\n\nlemma inv_character_inv_character [simp]: \"inv_character (inv_character \\<chi>) = \\<chi>\"\n  by (simp add: inv_character_def)\n\nlemma eval_inv_character: \"inv_character \\<chi> j = cnj (\\<chi> j)\"\n  by (simp add: inv_character_def)\n\n\nbundle character_syntax\nbegin\nnotation principal_char (\"\\<chi>\\<^sub>0\\<index>\")\nend\n\nlocale character = finite_comm_group +\n  fixes \\<chi> :: \"'a \\<Rightarrow> complex\"\n  assumes char_one_nz: \"\\<chi> \\<one> \\<noteq> 0\"\n  assumes char_eq_0:   \"a \\<notin> carrier G \\<Longrightarrow> \\<chi> a = 0\"\n  assumes char_mult [simp]: \"a \\<in> carrier G \\<Longrightarrow> b \\<in> carrier G \\<Longrightarrow> \\<chi> (a \\<otimes> b) = \\<chi> a * \\<chi> b\"\nbegin\n\n\nsubsection \\<open>Basic properties\\<close>\n\nlemma char_one [simp]: \"\\<chi> \\<one> = 1\"\nproof-\n  from char_mult[of \\<one> \\<one>] have \"\\<chi> \\<one> * (\\<chi> \\<one> - 1) = 0\"\n    by (auto simp del: char_mult)\n  with char_one_nz show ?thesis by simp\nqed\n\nlemma char_power [simp]: \"a \\<in> carrier G \\<Longrightarrow> \\<chi> (a [^] k) = \\<chi> a ^ k\"\n  by (induction k) auto\n\nlemma char_root:\n  assumes \"a \\<in> carrier G\"\n  shows   \"\\<chi> a ^ ord a = 1\"\nproof -\n  from assms have \"\\<chi> a ^ ord a = \\<chi> (a [^] ord a)\"\n    by (subst char_power) auto\n  also from fin and assms have \"a [^] ord a = \\<one>\" by (intro pow_ord_eq_1) auto\n  finally show ?thesis by simp\nqed\n\nlemma char_root':\n  assumes \"a \\<in> carrier G\"\n  shows   \"\\<chi> a ^ order G = 1\"\nproof -\n  from assms have \"\\<chi> a ^ order G = \\<chi> (a [^] order G)\" by simp\n  also from fin and assms have \"a [^] order G = \\<one>\" by (intro pow_order_eq_1) auto\n  finally show ?thesis by simp\nqed\n\nlemma norm_char: \"norm (\\<chi> a) = (if a \\<in> carrier G then 1 else 0)\"\nproof (cases \"a \\<in> carrier G\")\n  case True\n  have \"norm (\\<chi> a) ^ order G = norm (\\<chi> a ^ order G)\" by (simp add: norm_power)\n  also from True have \"\\<chi> a ^ order G = 1\" by (rule char_root')\n  finally have \"norm (\\<chi> a) ^ order G = 1 ^ order G\" by simp\n  hence \"norm (\\<chi> a) = 1\" by (subst (asm) power_eq_iff_eq_base) auto\n  with True show ?thesis by auto\nnext\n  case False\n  thus ?thesis by (auto simp: char_eq_0)\nqed\n\nlemma char_eq_0_iff: \"\\<chi> a = 0 \\<longleftrightarrow> a \\<notin> carrier G\"\nproof -\n  have \"\\<chi> a = 0 \\<longleftrightarrow> norm (\\<chi> a) = 0\" by simp\n  also have \"\\<dots> \\<longleftrightarrow> a \\<notin> carrier G\" by (subst norm_char) auto\n  finally show ?thesis .\nqed\n\nlemma inv_character: \"character G (inv_character \\<chi>)\"\n  by standard (auto simp: inv_character_def char_eq_0)\n\nlemma mult_inv_character: \"\\<chi> k * inv_character \\<chi> k = principal_char G k\"\nproof -\n  have \"\\<chi> k * inv_character \\<chi> k = of_real (norm (\\<chi> k) ^ 2)\"\n    by (subst complex_norm_square) (simp add: inv_character_def)\n  also have \"\\<dots> = principal_char G k\"\n    by (simp add: principal_char_def norm_char)\n  finally show ?thesis .\nqed\n\nlemma\n  assumes \"a \\<in> carrier G\"\n  shows    char_inv: \"\\<chi> (inv a) = cnj (\\<chi> a)\" and char_inv': \"\\<chi> (inv a) = inverse (\\<chi> a)\"\nproof -\n  from assms have \"inv a \\<otimes> a = \\<one>\" by simp\n  also have \"\\<chi> \\<dots> = 1\" by simp\n  also from assms have \"\\<chi> (inv a \\<otimes> a) = \\<chi> (inv a) * \\<chi> a\"\n    by (intro char_mult) auto\n  finally have *: \"\\<chi> (inv a) * \\<chi> a = 1\" .\n  thus \"\\<chi> (inv a) = inverse (\\<chi> a)\" by (auto simp: divide_simps)\n  also from mult_inv_character[of a] and assms have \"inverse (\\<chi> a) = cnj (\\<chi> a)\"\n    by (auto simp add: inv_character_def principal_char_def divide_simps mult.commute)\n  finally show \"\\<chi> (inv a) = cnj (\\<chi> a)\" .\nqed\n\nend\n\nlemma (in finite_comm_group) character_principal [simp, intro]: \"character G (principal_char G)\"\n  by standard (auto simp: principal_char_def)\n\nlemmas [simp,intro] = finite_comm_group.character_principal\n\nlemma character_ext:\n  assumes \"character G \\<chi>\" \"character G \\<chi>'\" \"\\<And>x. x \\<in> carrier G \\<Longrightarrow> \\<chi> x = \\<chi>' x\"\n  shows   \"\\<chi> = \\<chi>'\"\nproof\n  fix x :: 'a\n  show \"\\<chi> x = \\<chi>' x\"\n    using assms by (cases \"x \\<in> carrier G\") (auto simp: character.char_eq_0)\nqed\n\nlemma character_mult [intro]: \n  assumes \"character G \\<chi>\" \"character G \\<chi>'\"\n  shows   \"character G (\\<lambda>x. \\<chi> x * \\<chi>' x)\"\nproof -\n  interpret \\<chi>: character G \\<chi> by fact\n  interpret \\<chi>': character G \\<chi>' by fact\n  show ?thesis by standard (auto simp: \\<chi>.char_eq_0)\nqed\n \n\nlemma character_inv_character_iff [simp]: \"character G (inv_character \\<chi>) \\<longleftrightarrow> character G \\<chi>\"\nproof\n  assume \"character G (inv_character \\<chi>)\"\n  from character.inv_character [OF this] show \"character G \\<chi>\" by simp\nqed (auto simp: character.inv_character)\n\n\ndefinition characters :: \"('a, 'b) monoid_scheme \\<Rightarrow> ('a \\<Rightarrow> complex) set\"  where\n  \"characters G = {\\<chi>. character G \\<chi>}\"\n\n\nsubsection \\<open>The Character group\\<close>\n\ntext \\<open>\n  The characters of a finite abelian group $G$ form another group $\\widehat{G}$, which is called\n  its Pontryagin dual group. This generalises to the more general setting of locally compact\n  abelian groups, but we restrict ourselves to the finite setting because it is much easier.\n\\<close>\ndefinition Characters :: \"('a, 'b) monoid_scheme \\<Rightarrow> ('a \\<Rightarrow> complex) monoid\"\n  where \"Characters G = \\<lparr> carrier = characters G, monoid.mult = (\\<lambda>\\<chi>\\<^sub>1 \\<chi>\\<^sub>2 k. \\<chi>\\<^sub>1 k * \\<chi>\\<^sub>2 k),\n                          one = principal_char G \\<rparr>\"\n\nlemma carrier_Characters: \"carrier (Characters G) = characters G\"\n  by (simp add: Characters_def)\n\nlemma one_Characters: \"one (Characters G) = principal_char G\"\n  by (simp add: Characters_def)\n\nlemma mult_Characters: \"monoid.mult (Characters G) \\<chi>\\<^sub>1 \\<chi>\\<^sub>2 = (\\<lambda>a. \\<chi>\\<^sub>1 a * \\<chi>\\<^sub>2 a)\"\n  by (simp add: Characters_def)\n\ncontext finite_comm_group\nbegin\n\nsublocale principal: character G \"principal_char G\" ..\n\nlemma finite_characters [intro]: \"finite (characters G)\"\nproof (rule finite_subset)\n  show \"characters G \\<subseteq> (\\<lambda>f x. if x \\<in> carrier G then f x else 0) ` \n                          Pi\\<^sub>E (carrier G) (\\<lambda>_. {z. z ^ order G = 1})\" (is \"_ \\<subseteq> ?h ` ?Chars\")\n  proof (intro subsetI, goal_cases)\n    case (1 \\<chi>)\n    then interpret \\<chi>: character G \\<chi> by (simp add: characters_def)\n    have \"?h (restrict \\<chi> (carrier G)) \\<in> ?h ` ?Chars\"\n      by (intro imageI) (auto simp: \\<chi>.char_root')\n    also have \"?h (restrict \\<chi> (carrier G)) = \\<chi>\" by (simp add: fun_eq_iff \\<chi>.char_eq_0)\n    finally show ?case .\n  qed\n  show \"finite (?h ` ?Chars)\"\n    by (intro finite_imageI finite_PiE finite_roots_unity) (auto simp: Suc_le_eq)\nqed\n\nlemma finite_comm_group_Characters [intro]: \"finite_comm_group (Characters G)\"\nproof\n  fix \\<chi> \\<chi>' assume *: \"\\<chi> \\<in> carrier (Characters G)\" \"\\<chi>' \\<in> carrier (Characters G)\"\n  from * interpret \\<chi>: character G \\<chi> by (simp_all add: characters_def carrier_Characters)\n  from * interpret \\<chi>': character G \\<chi>' by (simp_all add: characters_def  carrier_Characters)\n  have \"character G (\\<lambda>k. \\<chi> k * \\<chi>' k)\"\n    by standard (insert *, simp_all add: \\<chi>.char_eq_0 one_Characters \n                                         mult_Characters characters_def  carrier_Characters)\n  thus \"\\<chi> \\<otimes>\\<^bsub>Characters G\\<^esub> \\<chi>' \\<in> carrier (Characters G)\"\n    by (simp add: characters_def one_Characters mult_Characters  carrier_Characters)\nnext\n  have \"character G (principal_char G)\" ..\n  thus \"\\<one>\\<^bsub>Characters G\\<^esub> \\<in> carrier (Characters G)\"\n    by (simp add: characters_def one_Characters mult_Characters  carrier_Characters)\nnext\n  fix \\<chi> assume *: \"\\<chi> \\<in> carrier (Characters G)\"\n  from * interpret \\<chi>: character G \\<chi> by (simp_all add: characters_def carrier_Characters)\n  show \"\\<one>\\<^bsub>Characters G\\<^esub> \\<otimes>\\<^bsub>Characters G\\<^esub> \\<chi> = \\<chi>\" and \"\\<chi> \\<otimes>\\<^bsub>Characters G\\<^esub> \\<one>\\<^bsub>Characters G\\<^esub> = \\<chi>\"\n    by (simp_all add: principal_char_def fun_eq_iff \\<chi>.char_eq_0 one_Characters mult_Characters)\nnext\n  have \"\\<chi> \\<in> Units (Characters G)\" if \"\\<chi> \\<in> carrier (Characters G)\" for \\<chi>\n  proof -\n    from that interpret \\<chi>: character G \\<chi> by (simp add: characters_def carrier_Characters)\n    have \"\\<chi> \\<otimes>\\<^bsub>Characters G\\<^esub> inv_character \\<chi> = \\<one>\\<^bsub>Characters G\\<^esub>\" and \n         \"inv_character \\<chi> \\<otimes>\\<^bsub>Characters G\\<^esub> \\<chi> = \\<one>\\<^bsub>Characters G\\<^esub>\"\n      by (simp_all add: \\<chi>.mult_inv_character mult_ac one_Characters mult_Characters)\n    moreover from that have \"inv_character \\<chi> \\<in> carrier (Characters G)\"\n      by (simp add: characters_def carrier_Characters)\n    ultimately show ?thesis using that unfolding Units_def by blast\n  qed\n  thus \"carrier (Characters G) \\<subseteq> Units (Characters G)\" ..\nqed (auto simp: principal_char_def one_Characters mult_Characters carrier_Characters)\n\nend\n\nlemma (in character) character_in_order_1:\n  assumes \"order G = 1\"\n  shows   \"\\<chi> = principal_char G\"\nproof -\n  from assms have \"card (carrier G - {\\<one>}) = 0\"\n    by (subst card_Diff_subset) (auto simp: order_def)\n  hence \"carrier G - {\\<one>} = {}\"\n    by (subst (asm) card_0_eq) auto\n  hence \"carrier G = {\\<one>}\" by auto\n  thus ?thesis\n    by (intro ext) (simp_all add: principal_char_def char_eq_0)\nqed\n\nlemma (in finite_comm_group) characters_in_order_1:\n  assumes \"order G = 1\"\n  shows   \"characters G = {principal_char G}\"\n  using character.character_in_order_1 [OF _ assms] by (auto simp: characters_def)\n\nlemma (in character) inv_Characters: \"inv\\<^bsub>Characters G\\<^esub> \\<chi> = inv_character \\<chi>\"\nproof -\n  interpret Characters: finite_comm_group \"Characters G\" ..\n  have \"character G \\<chi>\" ..\n  thus ?thesis\n    by (intro Characters.inv_equality) \n       (auto simp: characters_def mult_inv_character mult_ac \n                   carrier_Characters one_Characters mult_Characters)\nqed\n\nlemma (in finite_comm_group) inv_Characters': \n  \"\\<chi> \\<in> characters G \\<Longrightarrow> inv\\<^bsub>Characters G\\<^esub> \\<chi> = inv_character \\<chi>\"\n  by (intro character.inv_Characters) (auto simp: characters_def)\n\nlemmas (in finite_comm_group) Characters_simps = \n  carrier_Characters mult_Characters one_Characters inv_Characters'\n\nlemma inv_Characters': \"\\<chi> \\<in> characters G \\<Longrightarrow> inv\\<^bsub>Characters G\\<^esub> \\<chi> = inv_character \\<chi>\"\n  using character.inv_Characters[of G \\<chi>] by (simp add: characters_def)\n\n(* From here on: Joseph *)\nlemma (in finite_cyclic_group)\n  defines ic: \"induce_char \\<equiv> (\\<lambda>c::complex. (\\<lambda>a. if a\\<in>carrier G then c powi get_exp gen a else 0))\"\n  shows order_Characters: \"order (Characters G) = order G\"\n  and   gen_fixes_char: \"\\<lbrakk>character G a; character G b; a gen = b gen\\<rbrakk> \\<Longrightarrow> a = b\"\n  and   unity_root_induce_char: \"z ^ order G = 1 \\<Longrightarrow> character G (induce_char z)\"\nproof -\n  interpret C: finite_comm_group \"Characters G\" using finite_comm_group_Characters . \n  define n where \"n = order G\"\n  hence n: \"n > 0\" using order_gt_0 by presburger\n  from n_def have nog: \"n = ord gen\" using ord_gen_is_group_order by simp\n  have xnz: \"x \\<noteq> 0\" if \"x ^ n = 1\" for x::complex using n(1) that by (metis zero_neq_one zero_power)\n  have m: \"x powi m = x powi (m mod n)\" if \"x ^ n = 1\" for x::complex and m::int\n    using powi_mod[OF that n] .\n  show cf: \"character G (induce_char x)\" if x: \"x ^ n = 1\" for x\n  proof\n    show \"induce_char x \\<one> \\<noteq> 0\" using xnz[OF that] unfolding ic by auto\n    show \"induce_char x a = 0\" if \"a \\<notin> carrier G\" for a using that unfolding ic by simp\n    show \"induce_char x (a \\<otimes> b) = induce_char x a * induce_char x b\" if \"a \\<in> carrier G\" \"b \\<in> carrier G\" for a b\n    proof -\n      have \"x powi get_exp gen (a \\<otimes> b) = x powi get_exp gen a * x powi get_exp gen b\"\n      proof -\n        have \"x powi get_exp gen (a \\<otimes> b) = x powi ((get_exp gen a + get_exp gen b) mod n)\"\n          using m[OF x] get_exp_mult_mod[OF that] n_def ord_gen_is_group_order by metis\n        also have \"\\<dots> = x powi (get_exp gen a + get_exp gen b)\" using m[OF x] by presburger\n        finally show ?thesis by (simp add: power_int_add xnz[OF x])\n      qed\n      thus ?thesis using that unfolding ic by simp\n    qed\n  qed\n  define get_c where gc: \"get_c = (\\<lambda>c::'a \\<Rightarrow> complex. c gen)\"\n  have biji: \"bij_betw induce_char {z. z ^ n = 1} (characters G)\" and bijg: \"bij_betw get_c (characters G) {z. z ^ n = 1}\"\n  proof (intro bij_betwI[of _ _ _ get_c])\n    show iin: \"induce_char \\<in> {z. z ^ n = 1} \\<rightarrow> characters G\" using cf unfolding characters_def by blast\n    show gi: \"get_c (induce_char x) = x\" if \"x \\<in> {z. z ^ n = 1}\" for x\n    proof (cases \"n = 1\")\n      case True\n      with that have \"x = 1\" by force\n      thus ?thesis unfolding ic gc by simp\n    next\n      case False\n      have x: \"x ^ n = 1\" using that by blast\n      have \"x powi get_exp gen gen = x\"\n      proof -\n        have \"x powi get_exp gen gen = x powi (get_exp gen gen mod n)\" using m[OF x] by blast\n        moreover have \"(get_exp gen gen mod n) = 1\"\n        proof -\n          have \"1 = 1 mod int n\" using False n by auto\n          also have \"\\<dots> = get_exp gen gen mod n\"\n            by (unfold nog, intro pow_eq_int_mod[OF gen_closed], use get_exp_fulfills[OF gen_closed] in auto)\n          finally show ?thesis by argo\n        qed\n        ultimately show \"x powi get_exp gen gen = x\" by simp\n      qed\n      thus ?thesis unfolding ic gc by simp\n    qed\n    show gin: \"get_c \\<in> characters G \\<rightarrow> {z. z ^ n = 1}\"\n    proof -\n      have \"False\" if \"get_c c ^ n \\<noteq> 1\" \"character G c\" for c\n      proof -\n        interpret character G c by fact\n        show False using that(1)[unfolded gc] by (simp add: char_root' n_def)\n      qed\n      thus ?thesis unfolding characters_def by blast\n    qed\n    show ig: \"induce_char (get_c y) = y\" if y: \"y \\<in> characters G\" for y\n    proof (cases \"n = 1\")\n      case True\n      hence \"y = principal_char G\" using y n_def character.character_in_order_1 characters_def by auto\n      thus ?thesis unfolding ic gc principal_char_def by force\n    next\n      case False\n      have yc: \"y \\<in> carrier (Characters G)\" using y[unfolded carrier_Characters[symmetric]] .\n      interpret character G y using that unfolding characters_def by simp\n      have ygo: \"y gen ^ n = 1\" using char_root'[OF gen_closed] n_def by blast\n      have \"y gen powi get_exp gen a = y a\" if \"a \\<in> carrier G\" for a using that\n      proof(induction rule: generator_induct1)\n        case gen\n        have \"y gen powi get_exp gen gen = y gen powi (get_exp gen gen mod n)\" using m[OF ygo] by blast\n        also have \"\\<dots> = y gen powi ((1::int) mod n)\" using get_exp_self[OF gen_closed] nog by argo\n        also have \"\\<dots> = y gen powi 1\" using False n by simp\n        finally have yg: \"y gen powi get_exp gen gen = y gen\" by simp\n        thus ?case .\n        case (step x)\n        have \"y gen powi get_exp gen (x \\<otimes> gen) = y gen powi (get_exp gen (x \\<otimes> gen) mod n)\" using m[OF ygo] by blast\n        also have \"\\<dots> = y gen powi ((get_exp gen x + get_exp gen gen) mod n)\"\n          using get_exp_mult_mod[OF step(1) gen_closed, unfolded nog[symmetric]] by argo\n        also have \"\\<dots> = y gen powi (get_exp gen x + get_exp gen gen)\" using m[OF ygo] by presburger\n        also have \"\\<dots> = y gen powi get_exp gen x * y gen powi get_exp gen gen\" by (simp add: char_eq_0_iff power_int_add)\n        also have \"\\<dots> = y x * y gen\" using yg step(2) by argo\n        also have \"\\<dots> = y (x \\<otimes> gen)\" using step(1) by simp\n        finally show ?case .\n      qed\n      thus \"induce_char (get_c y) = y\" unfolding ic gc using char_eq_0 by auto\n    qed\n    show \"bij_betw get_c (characters G) {z. z ^ n = 1}\" using ig gi iin gin by (auto intro: bij_betwI)\n  qed\n  with card_roots_unity_eq[OF n] n_def show \"order (Characters G) = order G\" unfolding order_def\n    by (metis bij_betw_same_card carrier_Characters)\n  assume assm: \"character G a\" \"character G b\" \"a gen = b gen\"\n  with bijg[unfolded gc characters_def bij_betw_def inj_on_def] show \"a = b\" by auto\nqed\n\nlemma (in finite_cyclic_group) finite_cyclic_group_Characters:\n  obtains \\<chi> where \"finite_cyclic_group (Characters G) \\<chi>\"\nproof -\n  interpret C: finite_comm_group \"Characters G\" by (rule finite_comm_group_Characters)\n  define n where n: \"n = order G\"\n  hence nnz: \"n \\<noteq> 0\" by blast\n  from n have nog: \"n = ord gen\" using ord_gen_is_group_order by simp\n  obtain x::complex where x: \"x ^ n = 1\" \"\\<And>m. \\<lbrakk>0<m; m<n\\<rbrakk> \\<Longrightarrow> x ^ m \\<noteq> 1\" using true_nth_unity_root by blast\n  have xnz: \"x \\<noteq> 0\" using x n by (metis order_gt_0 zero_neq_one zero_power)\n  have m: \"x powi m = x powi (m mod n)\" for m::int\n    using powi_mod[OF x(1)] nnz by blast\n  let ?f = \"(\\<lambda>a. if a \\<in> carrier G then x powi (get_exp gen a) else 0)\"\n  have cf: \"character G ?f\" using unity_root_induce_char[OF x(1)[unfolded n]] .\n  have fpow: \"(?f [^]\\<^bsub>Characters G\\<^esub> m) a = x powi ((get_exp gen a) * m)\" if \"a \\<in> carrier G\" for a::'a and m::nat\n    using that\n  proof(unfold Characters_def principal_char_def, induction m)\n    case s: (Suc m)\n    have \"x powi (get_exp gen a * int m) * x powi get_exp gen a = x powi (get_exp gen a * (1 + int m))\"\n    proof -\n      fix ma :: nat\n      have \"x powi ((1 + int ma) * get_exp gen a) = x powi (get_exp gen a + int ma * get_exp gen a) \\<and> 0 \\<noteq> x\"\n        by (simp add: comm_semiring_class.distrib xnz)\n      then show \"x powi (get_exp gen a * int ma) * x powi get_exp gen a = x powi (get_exp gen a * (1 + int ma))\"\n        by (simp add: mult.commute power_int_add)\n    qed\n    thus ?case using s by simp\n  qed simp\n  interpret cyclic_group \"Characters G\" ?f\n  proof (intro C.element_ord_generates_cyclic)\n    show fc: \"?f \\<in> carrier (Characters G)\" using cf carrier_Characters[of G] characters_def by fast\n    from x nnz have fno: \"?f [^]\\<^bsub>Characters G\\<^esub> m \\<noteq> \\<one>\\<^bsub>Characters G\\<^esub>\" if \"0 < m\" \"m < n\" for m\n    proof (cases \"n = 1\")\n      case False\n      have \"\\<one>\\<^bsub>Characters G\\<^esub> gen = 1\" unfolding Characters_def principal_char_def using that by simp\n      moreover have \"(?f [^]\\<^bsub>Characters G\\<^esub> m) gen \\<noteq> 1\"\n      proof -\n        have \"(?f [^]\\<^bsub>Characters G\\<^esub> m) gen = x powi ((get_exp gen gen) * m)\" using fpow by blast\n        also have \"\\<dots> = (x powi (get_exp gen gen)) ^ m\" by (simp add: power_int_mult)\n        also have \"\\<dots> = x ^ m\"\n        proof -\n          have \"x powi (get_exp gen gen) = x powi ((get_exp gen gen) mod n)\" using m by blast\n          moreover have \"((get_exp gen gen) mod n) = 1\"\n          proof -\n            have \"1 = 1 mod int n\" using False nnz by simp\n            also have \"\\<dots> = get_exp gen gen mod n\"\n              by (unfold nog, intro pow_eq_int_mod[OF gen_closed], use get_exp_fulfills[OF gen_closed] in auto)\n            finally show ?thesis by argo\n          qed\n          ultimately have \"x powi (get_exp gen gen) = x\" by simp\n          thus ?thesis by simp\n        qed\n        finally show ?thesis using x(2)[OF that] by argo\n      qed\n      ultimately show ?thesis by fastforce\n    qed (use that in blast)\n    have \"C.ord ?f = n\"\n    proof -\n      from nnz have \"C.ord ?f \\<le> n\" unfolding n\n        using C.ord_dvd_group_order[OF fc] order_Characters dvd_nat_bounds by auto\n      with C.ord_conv_Least[OF fc] C.pow_order_eq_1[OF fc] n nnz show \"C.ord ?f = n\"\n        by (metis (no_types, lifting) C.ord_pos C.pow_ord_eq_1 fc fno le_neq_implies_less)\n    qed\n    thus \"C.ord ?f = order (Characters G)\" using n order_Characters by argo\n  qed\n  have \"finite_cyclic_group (Characters G) ?f\" by unfold_locales\n  with that show ?thesis by blast\nqed\n\nlemma (in finite_cyclic_group) Characters_iso:\n  \"G \\<cong> Characters G\"\nproof -\n  from finite_cyclic_group_Characters obtain f where f: \"finite_cyclic_group (Characters G) f\" .\n  then interpret C: finite_cyclic_group \"Characters G\" f .\n  have \"cyclic_group (Characters G) f\" by unfold_locales\n  from iso_cyclic_groups_same_order[OF this order_Characters[symmetric]] show ?thesis .\nqed\n\nlemma (in finite_comm_group) iso_imp_iso_chars:\n  assumes \"G \\<cong> H\" \"group H\"\n  shows \"Characters G \\<cong> Characters H\"\nproof -\n  interpret H: finite_comm_group H by (rule iso_imp_finite_comm[OF assms])\n  from assms have \"H \\<cong> G\" using iso_sym by auto\n  then obtain g where g: \"g \\<in> iso H G\" unfolding is_iso_def by blast\n  then interpret ggh: group_hom H G g by (unfold_locales, unfold iso_def, simp)\n  let ?f = \"(\\<lambda>c a. if a \\<in> carrier H then (c \\<circ> g) a else 0)\"\n  have \"?f \\<in> iso (Characters G) (Characters H)\"\n  proof (intro isoI)\n    interpret CG: finite_comm_group \"Characters G\" by (intro finite_comm_group_Characters)\n    interpret CH: finite_comm_group \"Characters H\" by (intro H.finite_comm_group_Characters)\n    have f_in: \"?f x \\<in> carrier (Characters H)\" if \"x \\<in> carrier (Characters G)\" for x\n    proof (unfold carrier_Characters characters_def, rule, unfold_locales)\n      interpret character G x using that characters_def carrier_Characters by blast\n      show \"(if \\<one>\\<^bsub>H\\<^esub> \\<in> carrier H then (x \\<circ> g) \\<one>\\<^bsub>H\\<^esub> else 0) \\<noteq> 0\" using g iso_iff by auto\n      show \"\\<And>a. a \\<notin> carrier H \\<Longrightarrow> (if a \\<in> carrier H then (x \\<circ> g) a else 0) = 0\" by simp\n      show \"?f x (a \\<otimes>\\<^bsub>H\\<^esub> b) = ?f x a * ?f x b\" if \"a \\<in> carrier H\" \"b \\<in> carrier H\" for a b using that by auto\n    qed\n    show \"?f \\<in> hom (Characters G) (Characters H)\"\n    proof (intro homI)\n      show \"?f x \\<in> carrier (Characters H)\" if \"x \\<in> carrier (Characters G)\" for x using f_in[OF that] .\n      show \"?f (x \\<otimes>\\<^bsub>Characters G\\<^esub> y) = ?f x \\<otimes>\\<^bsub>Characters H\\<^esub> ?f y\"\n        if \"x \\<in> carrier (Characters G)\" \"y \\<in> carrier (Characters G)\" for x y\n      proof -\n        interpret x: character G x using that characters_def carrier_Characters by blast\n        interpret y: character G y using that characters_def carrier_Characters by blast\n        show ?thesis using that mult_Characters[of G] mult_Characters[of H] by auto\n      qed\n    qed\n    show \"bij_betw ?f (carrier (Characters G)) (carrier (Characters H))\"\n    proof(intro bij_betwI)\n      define f where \"f = inv_into (carrier H) g\"\n      hence f: \"f \\<in> iso G H\" using H.iso_set_sym[OF g] by simp\n      then interpret fgh: group_hom G H f by (unfold_locales, unfold iso_def, simp)\n      let ?g = \"(\\<lambda>c a. if a \\<in> carrier G then (c \\<circ> f) a else 0)\"\n      show \"?f \\<in> carrier (Characters G) \\<rightarrow> carrier (Characters H)\" using f_in by fast\n      show \"?g \\<in> carrier (Characters H) \\<rightarrow> carrier (Characters G)\"\n      proof -\n        have g_in: \"?g x \\<in> carrier (Characters G)\" if \"x \\<in> carrier (Characters H)\" for x\n        proof (unfold carrier_Characters characters_def, rule, unfold_locales)\n          interpret character H x using that characters_def carrier_Characters by blast\n          show \"(if \\<one>\\<^bsub>G\\<^esub> \\<in> carrier G then (x \\<circ> f) \\<one>\\<^bsub>G\\<^esub> else 0) \\<noteq> 0\" using f iso_iff by auto\n          show \"\\<And>a. a \\<notin> carrier G \\<Longrightarrow> (if a \\<in> carrier G then (x \\<circ> f) a else 0) = 0\" by simp\n          show \"?g x (a \\<otimes>\\<^bsub>G\\<^esub> b) = ?g x a * ?g x b\" if \"a \\<in> carrier G\" \"b \\<in> carrier G\" for a b using that by auto\n        qed\n        thus ?thesis by simp\n      qed\n      show \"?f (?g x) = x\" if x: \"x \\<in> carrier (Characters H)\" for x\n      proof -\n        interpret character H x using x characters_def carrier_Characters by blast\n        have \"?f (?g x) a = x a\" if a: \"a \\<notin> carrier H\" for a using a char_eq_0[OF a] by auto\n        moreover have \"?f (?g x) a = x a\" if a: \"a \\<in> carrier H\" for a\n        proof -\n          from a have \"inv_into (carrier H) g (g a) = a\" by (simp add: g ggh.inj_iff_trivial_ker ggh.iso_kernel)\n          thus ?thesis using a f_def by auto\n        qed\n        ultimately show ?thesis by fast\n      qed\n      show \"?g (?f x) = x\" if x: \"x \\<in> carrier (Characters G)\" for x\n      proof -\n        interpret character G x using x characters_def carrier_Characters by blast\n        have \"?g (?f x) a = x a\" if a: \"a \\<notin> carrier G\" for a using a char_eq_0[OF a] by auto\n        moreover have \"?g (?f x) a = x a\" if a: \"a \\<in> carrier G\" for a using a f_def\n        proof -\n          from a have \"g (inv_into (carrier H) g a) = a\" by (meson f_inv_into_f g ggh.iso_iff subset_iff)\n          thus ?thesis using a f_def fgh.hom_closed by auto\n        qed\n        ultimately show ?thesis by fast\n      qed\n    qed\n  qed\n  thus ?thesis unfolding is_iso_def by blast\nqed\n\nlemma DirProds_subchar:\n  assumes \"finite_comm_group (DirProds Gs I)\" and x: \"x \\<in> carrier (Characters (DirProds Gs I))\" and i: \"i \\<in> I\" and I: \"finite I\"\n  defines g: \"g \\<equiv> (\\<lambda>c. (\\<lambda>i\\<in>I. (\\<lambda>a. c ((\\<lambda>i\\<in>I. \\<one>\\<^bsub>Gs i\\<^esub>)(i:=a)))))\"\n  shows \"character (Gs i) (g x i)\"\nproof -\n  interpret DP: finite_comm_group \"DirProds Gs I\" by fact\n  interpret xc: character \"DirProds Gs I\" x using x unfolding Characters_def characters_def by auto\n  interpret Gi: finite_comm_group \"Gs i\" using i DirProds_finite_comm_group_iff[OF I] DP.finite_comm_group_axioms by blast\n  have allg: \"\\<And>i. i\\<in>I \\<Longrightarrow> group (Gs i)\" using DirProds_group_imp_groups[OF DP.is_group] .\n  show ?thesis\n  proof(unfold_locales)\n    have \"(\\<lambda>i\\<in>I. \\<one>\\<^bsub>Gs i\\<^esub>) = (\\<lambda>i\\<in>I. \\<one>\\<^bsub>Gs i\\<^esub>)(i := \\<one>\\<^bsub>Gs i\\<^esub>)\" using i by force\n    thus \"g x i \\<one>\\<^bsub>Gs i\\<^esub> \\<noteq> 0\" using i g DirProds_one''[of Gs I] xc.char_one_nz by auto\n    show \"g x i a = 0\" if a: \"a \\<notin> carrier (Gs i)\" for a\n    proof -\n      from a i have \"((\\<lambda>i\\<in>I. \\<one>\\<^bsub>Gs i\\<^esub>)(i := a)) \\<notin> carrier (DirProds Gs I)\" unfolding DirProds_def by force\n      from xc.char_eq_0[OF this] show ?thesis using i g by auto\n    qed\n    show \"g x i (a \\<otimes>\\<^bsub>Gs i\\<^esub> b) = g x i a * g x i b\" if ab: \"a \\<in> carrier (Gs i)\" \"b \\<in> carrier (Gs i)\" for a b\n    proof -\n      have \"g x i (a \\<otimes>\\<^bsub>Gs i\\<^esub> b) = x ((\\<lambda>i\\<in>I. \\<one>\\<^bsub>Gs i\\<^esub>)(i := a) \\<otimes>\\<^bsub>DirProds Gs I\\<^esub> (\\<lambda>i\\<in>I. \\<one>\\<^bsub>Gs i\\<^esub>)(i := b))\"\n      proof -\n        have \"((\\<lambda>i\\<in>I. \\<one>\\<^bsub>Gs i\\<^esub>)(i := a) \\<otimes>\\<^bsub>DirProds Gs I\\<^esub> (\\<lambda>i\\<in>I. \\<one>\\<^bsub>Gs i\\<^esub>)(i := b)) = ((\\<lambda>i\\<in>I. \\<one>\\<^bsub>Gs i\\<^esub>)(i := (a \\<otimes>\\<^bsub>Gs i\\<^esub> b)))\"\n        proof -\n          have \"((\\<lambda>i\\<in>I. \\<one>\\<^bsub>Gs i\\<^esub>)(i := a) \\<otimes>\\<^bsub>DirProds Gs I\\<^esub> (\\<lambda>i\\<in>I. \\<one>\\<^bsub>Gs i\\<^esub>)(i := b)) j = ((\\<lambda>i\\<in>I. \\<one>\\<^bsub>Gs i\\<^esub>)(i := (a \\<otimes>\\<^bsub>Gs i\\<^esub> b))) j\"\n            for j\n          proof (cases \"j \\<in> I\")\n            case True\n            from allg[OF True] interpret Gj: group \"Gs j\" .\n            show ?thesis using ab True i unfolding DirProds_mult by simp\n          next\n            case False\n            then show ?thesis unfolding DirProds_mult using i by fastforce\n          qed\n          thus ?thesis by fast\n        qed\n        thus ?thesis using i g by auto\n      qed \n      also have \"\\<dots> = x ((\\<lambda>i\\<in>I. \\<one>\\<^bsub>Gs i\\<^esub>)(i := a)) * x ((\\<lambda>i\\<in>I. \\<one>\\<^bsub>Gs i\\<^esub>)(i := b))\"\n      proof -\n        have ac: \"((\\<lambda>i\\<in>I. \\<one>\\<^bsub>Gs i\\<^esub>)(i := a)) \\<in> carrier (DirProds Gs I)\"\n          unfolding DirProds_def using ab i monoid.one_closed[OF group.is_monoid[OF allg]] by force\n        have bc: \"((\\<lambda>i\\<in>I. \\<one>\\<^bsub>Gs i\\<^esub>)(i := b)) \\<in> carrier (DirProds Gs I)\"\n          unfolding DirProds_def using ab i monoid.one_closed[OF group.is_monoid[OF allg]] by force\n        from xc.char_mult[OF ac bc] show ?thesis .\n      qed\n      also have \"\\<dots> = g x i a * g x i b\" using i g by auto\n      finally show ?thesis .\n    qed\n  qed\nqed\n\nlemma Characters_DirProds_single_prod:\n  assumes \"finite_comm_group (DirProds Gs I)\" and x: \"x \\<in> carrier (Characters (DirProds Gs I))\" and I: \"finite I\"\n  defines g: \"g \\<equiv> (\\<lambda>I. (\\<lambda>c. (\\<lambda>i\\<in>I. (\\<lambda>a. c ((\\<lambda>i\\<in>I. \\<one>\\<^bsub>Gs i\\<^esub>)(i:=a))))))\"\n  shows \"(\\<lambda>e. if e\\<in>carrier(DirProds Gs I) then \\<Prod>i\\<in>I. (g I x i) (e i) else 0) = x\" (is \"?g x = x\")\nproof\n  show \"?g x e = x e\" for e\n  proof (cases \"e \\<in> carrier (DirProds Gs I)\")\n    case True\n    show ?thesis using I x assms(1) True unfolding g\n    proof(induction I arbitrary: x e rule: finite_induct)\n      case empty\n      interpret DP: finite_comm_group \"DirProds Gs {}\" by fact\n      from DirProds_empty[of Gs] have \"order (DirProds Gs {}) = 1\" unfolding order_def by simp\n      with DP.characters_in_order_1[OF this] empty(1) show ?case\n        using DirProds_empty[of Gs] unfolding Characters_def principal_char_def by auto\n    next\n      case j: (insert j I)\n      interpret DP: finite_comm_group \"DirProds Gs (insert j I)\" by fact\n      interpret DP2: finite_comm_group \"DirProds Gs I\"\n      proof -\n        from DirProds_finite_comm_group_iff[of \"insert j I\" Gs] DP.finite_comm_group_axioms j\n        have \"(\\<forall>i\\<in>(insert j I). finite_comm_group (Gs i))\" by blast\n        with DirProds_finite_comm_group_iff[OF j(1), of Gs] show \"finite_comm_group (DirProds Gs I)\" by blast\n      qed\n      interpret xc: character \"DirProds Gs (insert j I)\" x using j(4) unfolding Characters_def characters_def by simp\n      have allg: \"\\<And>i. i\\<in>(insert j I) \\<Longrightarrow> group (Gs i)\" using DirProds_group_imp_groups[OF DP.is_group] .\n      have e1c: \"e(j:= \\<one>\\<^bsub>Gs j\\<^esub>) \\<in> carrier (DirProds Gs (insert j I))\"\n        using j(6) monoid.one_closed[OF group.is_monoid[OF allg[of j]]] unfolding DirProds_def PiE_def Pi_def by simp\n      have e2c: \"(\\<lambda>i\\<in>(insert j I). \\<one>\\<^bsub>Gs i\\<^esub>)(j := e j) \\<in> carrier (DirProds Gs (insert j I))\"\n        unfolding DirProds_def PiE_def Pi_def using monoid.one_closed[OF group.is_monoid[OF allg]] comp_in_carr[OF j(6)] by auto\n      have \"e = e(j:= \\<one>\\<^bsub>Gs j\\<^esub>) \\<otimes>\\<^bsub>DirProds Gs (insert j I)\\<^esub> (\\<lambda>i\\<in>(insert j I). \\<one>\\<^bsub>Gs i\\<^esub>)(j := e j)\"\n      proof -\n        have \"e k = (e(j:= \\<one>\\<^bsub>Gs j\\<^esub>) \\<otimes>\\<^bsub>DirProds Gs (insert j I)\\<^esub> (\\<lambda>i\\<in>(insert j I). \\<one>\\<^bsub>Gs i\\<^esub>)(j := e j)) k\" for k\n        proof(cases \"k\\<in>(insert j I)\")\n          case k: True\n          from allg[OF k] interpret Gk: group \"Gs k\" .\n          from allg[of j] interpret Gj: group \"Gs j\" by simp\n          from k show ?thesis unfolding comp_mult[OF k] using comp_in_carr[OF j(6) k] by auto\n        next\n          case False\n          then show ?thesis using j(6) unfolding DirProds_def by auto\n        qed\n        thus ?thesis by blast\n      qed\n      hence \"x e = x (e(j:= \\<one>\\<^bsub>Gs j\\<^esub>)) * x ((\\<lambda>i\\<in>(insert j I). \\<one>\\<^bsub>Gs i\\<^esub>)(j := e j))\" using xc.char_mult[OF e1c e2c] by argo\n      also have \"\\<dots> = (\\<Prod>i\\<in>I. g (insert j I) x i (e i)) * g (insert j I) x j (e j)\"\n      proof -\n        have \"x (e(j:= \\<one>\\<^bsub>Gs j\\<^esub>)) = (\\<Prod>i\\<in>I. g (insert j I) x i (e i))\"\n        proof -\n          have eu: \"e(j:=undefined) \\<in> carrier (DirProds Gs I)\" using j(2, 6)\n            unfolding DirProds_def PiE_def Pi_def extensional_def by fastforce\n          let ?x = \"\\<lambda>p. if p\\<in>carrier(DirProds Gs I) then x (p(j:= \\<one>\\<^bsub>Gs j\\<^esub>)) else 0\"\n          have cx2: \"character (DirProds Gs I) ?x\"\n          proof\n            show \"?x \\<one>\\<^bsub>DirProds Gs I\\<^esub> \\<noteq> 0\"\n            proof -\n              have \"\\<one>\\<^bsub>DirProds Gs I\\<^esub>(j := \\<one>\\<^bsub>Gs j\\<^esub>) = \\<one>\\<^bsub>DirProds Gs (insert j I)\\<^esub>\" unfolding DirProds_one'' by force\n              thus ?thesis by simp\n            qed\n            show \"?x a = 0\" if a: \"a \\<notin> carrier (DirProds Gs I)\" for a using a by argo\n            show \"?x (a \\<otimes>\\<^bsub>DirProds Gs I\\<^esub> b) = ?x a * ?x b\"\n              if ab: \"a \\<in> carrier (DirProds Gs I)\" \"b \\<in> carrier (DirProds Gs I)\" for a b\n            proof -\n              have ac: \"a(j := \\<one>\\<^bsub>Gs j\\<^esub>) \\<in> carrier (DirProds Gs (insert j I))\"\n                using ab monoid.one_closed[OF group.is_monoid[OF allg[of j]]]\n                unfolding DirProds_def PiE_def Pi_def by simp\n              have bc: \"b(j := \\<one>\\<^bsub>Gs j\\<^esub>) \\<in> carrier (DirProds Gs (insert j I))\"\n                using ab monoid.one_closed[OF group.is_monoid[OF allg[of j]]]\n                unfolding DirProds_def PiE_def Pi_def by simp\n              have m: \"((a \\<otimes>\\<^bsub>DirProds Gs I\\<^esub> b)(j := \\<one>\\<^bsub>Gs j\\<^esub>)) = (a(j := \\<one>\\<^bsub>Gs j\\<^esub>) \\<otimes>\\<^bsub>DirProds Gs (insert j I)\\<^esub> b(j := \\<one>\\<^bsub>Gs j\\<^esub>))\"\n              proof -\n                have \"((a \\<otimes>\\<^bsub>DirProds Gs I\\<^esub> b)(j := \\<one>\\<^bsub>Gs j\\<^esub>)) h = (a(j := \\<one>\\<^bsub>Gs j\\<^esub>) \\<otimes>\\<^bsub>DirProds Gs (insert j I)\\<^esub> b(j := \\<one>\\<^bsub>Gs j\\<^esub>)) h\"\n                  if h: \"h\\<in>(insert j I)\" for h\n                proof(cases \"h=j\")\n                  case True\n                  interpret Gj: group \"Gs j\" using allg[of j] by blast\n                  from True comp_mult[OF h, of Gs \"a(j := \\<one>\\<^bsub>Gs j\\<^esub>)\" \"b(j := \\<one>\\<^bsub>Gs j\\<^esub>)\"] show ?thesis by auto\n                next\n                  case False\n                  interpret Gj: group \"Gs h\" using allg[OF h] .\n                  from False h comp_mult[OF h, of Gs \"a(j := \\<one>\\<^bsub>Gs j\\<^esub>)\" \"b(j := \\<one>\\<^bsub>Gs j\\<^esub>)\"] comp_mult[of h I Gs a b]\n                  show ?thesis by auto\n                qed\n                moreover have \"((a \\<otimes>\\<^bsub>DirProds Gs I\\<^esub> b)(j := \\<one>\\<^bsub>Gs j\\<^esub>)) h = (a(j := \\<one>\\<^bsub>Gs j\\<^esub>) \\<otimes>\\<^bsub>DirProds Gs (insert j I)\\<^esub> b(j := \\<one>\\<^bsub>Gs j\\<^esub>)) h\"\n                  if h: \"h\\<notin>(insert j I)\" for h using h unfolding DirProds_def PiE_def by simp\n                ultimately show ?thesis by blast\n              qed\n              have \"x ((a \\<otimes>\\<^bsub>DirProds Gs I\\<^esub> b)(j := \\<one>\\<^bsub>Gs j\\<^esub>)) = x (a(j := \\<one>\\<^bsub>Gs j\\<^esub>)) * x (b(j := \\<one>\\<^bsub>Gs j\\<^esub>))\"\n                by (unfold m, intro xc.char_mult[OF ac bc])\n              thus ?thesis using ab by auto\n            qed\n          qed\n          then interpret cx2: character \"DirProds Gs I\" ?x .\n          from cx2 have cx3:\"?x \\<in> carrier (Characters (DirProds Gs I))\" unfolding Characters_def characters_def by simp\n          from j(3)[OF cx3 DP2.finite_comm_group_axioms eu] have\n           \"(if e(j:=undefined) \\<in> carrier (DirProds Gs I) then \\<Prod>i\\<in>I. g I ?x i ((e(j:=undefined)) i) else 0) = ?x (e(j:=undefined))\"\n            using eu j(2) unfolding g by fast\n          with eu have \"(\\<Prod>i\\<in>I. g I (\\<lambda>p. if p \\<in> carrier (DirProds Gs I) then x (p(j := \\<one>\\<^bsub>Gs j\\<^esub>)) else 0) i ((e(j := undefined)) i)) = x (e(j := \\<one>\\<^bsub>Gs j\\<^esub>))\"\n            by simp\n          moreover have \"g I (\\<lambda>a. if a \\<in> carrier (DirProds Gs I) then x (a(j := \\<one>\\<^bsub>Gs j\\<^esub>)) else 0) i ((e(j := undefined)) i) = g (insert j I) x i (e i)\"\n            if i: \"i\\<in>I\" for i\n          proof -\n            have \"(\\<lambda>i\\<in>I. \\<one>\\<^bsub>Gs i\\<^esub>)(i := e i) \\<in> carrier (DirProds Gs I)\"\n              unfolding DirProds_def PiE_def Pi_def extensional_def\n              using monoid.one_closed[OF group.is_monoid[OF allg]] comp_in_carr[OF j(6)] i by simp\n            moreover have \"((\\<lambda>i\\<in>I. \\<one>\\<^bsub>Gs i\\<^esub>)(i := e i, j := \\<one>\\<^bsub>Gs j\\<^esub>)) = ((\\<lambda>i\\<in>insert j I. \\<one>\\<^bsub>Gs i\\<^esub>)(i := e i))\" using i j(2) by auto\n            ultimately show ?thesis using i j(2, 4, 6) unfolding g by auto\n          qed\n          ultimately show ?thesis by simp\n        qed\n        moreover have \"x ((\\<lambda>i\\<in>(insert j I). \\<one>\\<^bsub>Gs i\\<^esub>)(j := e j)) = g (insert j I) x j (e j)\"\n          unfolding g by simp\n        ultimately show ?thesis by argo\n      qed  \n      finally show ?case using j unfolding g by auto\n    qed \n  next\n    case False\n    interpret xc: character \"DirProds Gs I\" x using x unfolding Characters_def characters_def by simp\n    from xc.char_eq_0[OF False] False show ?thesis by argo\n  qed\nqed\n\nlemma (in finite_comm_group) Characters_DirProds_iso:\n  assumes \"DirProds Gs I \\<cong> G\" \"group (DirProds Gs I)\" \"finite I\"\n  shows \"DirProds (Characters \\<circ> Gs) I \\<cong> Characters G\"\nproof -\n  interpret DP: group \"DirProds Gs I\" by fact\n  interpret DP: finite_comm_group \"DirProds Gs I\" by (intro iso_imp_finite_comm[OF DP.iso_sym[OF assms(1)]], unfold_locales)\n  interpret DPC: finite_comm_group \"DirProds (Characters \\<circ> Gs) I\"\n    using DirProds_finite_comm_group_iff[OF assms(3), of \"Characters \\<circ> Gs\"] DirProds_finite_comm_group_iff[OF assms(3), of Gs]\n      DP.finite_comm_group_axioms finite_comm_group.finite_comm_group_Characters by auto\n  interpret CDP: finite_comm_group \"Characters (DirProds Gs I)\" using DP.finite_comm_group_Characters .\n  interpret C: finite_comm_group \"Characters G\" using finite_comm_group_Characters .\n  have allg: \"\\<And>i. i\\<in>I \\<Longrightarrow> group (Gs i)\" using DirProds_group_imp_groups[OF assms(2)] .\n  let ?f = \"(\\<lambda>cp. (\\<lambda>e. (if e\\<in>carrier (DirProds Gs I) then \\<Prod>i\\<in>I. cp i (e i) else 0)))\"\n  have f_in: \"?f x \\<in> carrier (Characters (DirProds Gs I))\" if x: \"x \\<in> carrier (DirProds (Characters \\<circ> Gs) I)\" for x\n  proof(unfold carrier_Characters characters_def, safe, unfold_locales)\n    show \"?f x \\<one>\\<^bsub>DirProds Gs I\\<^esub> \\<noteq> 0\"\n    proof -\n      have \"x i (\\<one>\\<^bsub>DirProds Gs I\\<^esub> i) \\<noteq> 0\" if i: \"i \\<in> I\" for i\n      proof -\n        interpret Gi: finite_comm_group \"Gs i\"\n          using DirProds_finite_comm_group_iff[OF assms(3)] DP.finite_comm_group_axioms i by blast\n        interpret xi: character \"Gs i\" \"x i\" using i x unfolding DirProds_def Characters_def characters_def by auto\n        show ?thesis using DirProds_one'[OF i, of Gs] by simp\n      qed\n      thus ?thesis by (simp add: assms(3))\n    qed\n    show \"?f x a = 0\" if \"a \\<notin> carrier (DirProds Gs I)\" for a using that by simp\n    show \"?f x (a \\<otimes>\\<^bsub>DirProds Gs I\\<^esub> b) = ?f x a * ?f x b\"\n      if ab: \"a \\<in> carrier (DirProds Gs I)\" \"b \\<in> carrier (DirProds Gs I)\" for a b\n    proof -\n      have \"a \\<otimes>\\<^bsub>DirProds Gs I\\<^esub> b \\<in> carrier (DirProds Gs I)\" using that by blast\n      moreover have \"(\\<Prod>i\\<in>I. x i ((a \\<otimes>\\<^bsub>DirProds Gs I\\<^esub> b) i)) = (\\<Prod>i\\<in>I. x i (a i)) * (\\<Prod>i\\<in>I. x i (b i))\"\n      proof -\n        have \"x i ((a \\<otimes>\\<^bsub>DirProds Gs I\\<^esub> b) i) = x i (a i) * x i (b i)\" if i: \"i\\<in>I\" for i\n        proof -\n          interpret xi: character \"Gs i\" \"x i\" using i x unfolding DirProds_def Characters_def characters_def by auto\n          show ?thesis using ab comp_mult[OF i, of Gs a b] by(auto simp: comp_in_carr[OF _ i])\n        qed\n        thus ?thesis using prod.distrib by force\n      qed\n      ultimately show ?thesis using that by auto\n    qed\n  qed\n  have \"?f \\<in> iso (DirProds (Characters \\<circ> Gs) I) (Characters (DirProds Gs I))\"\n  proof (intro isoI)\n    show \"?f \\<in> hom (DirProds (Characters \\<circ> Gs) I) (Characters (DirProds Gs I))\"\n    proof (intro homI)\n      show \"?f x \\<in> carrier (Characters (DirProds Gs I))\" if x: \"x \\<in> carrier (DirProds (Characters \\<circ> Gs) I)\" for x using f_in[OF that] .\n      show \"?f (x \\<otimes>\\<^bsub>DirProds (Characters \\<circ> Gs) I\\<^esub> y) = ?f x \\<otimes>\\<^bsub>Characters (DirProds Gs I)\\<^esub> ?f y\"\n        if \"x \\<in> carrier (DirProds (Characters \\<circ> Gs) I)\" \"y \\<in> carrier (DirProds (Characters \\<circ> Gs) I)\" for x y\n      proof -\n        have \"?f x \\<otimes>\\<^bsub>Characters (DirProds Gs I)\\<^esub> ?f y = (\\<lambda>e. if e \\<in> carrier (DirProds Gs I) then (\\<Prod>i\\<in>I. x i (e i)) * (\\<Prod>i\\<in>I. y i (e i)) else 0)\"\n          unfolding Characters_def by auto\n        also have \"\\<dots> = ?f (x \\<otimes>\\<^bsub>DirProds (Characters \\<circ> Gs) I\\<^esub> y)\"\n        proof -\n          have \"(\\<Prod>i\\<in>I. x i (e i)) * (\\<Prod>i\\<in>I. y i (e i)) = (\\<Prod>i\\<in>I. (x \\<otimes>\\<^bsub>DirProds (Characters \\<circ> Gs) I\\<^esub> y) i (e i))\" for e\n            unfolding DirProds_def Characters_def by (auto simp: prod.distrib)\n          thus ?thesis by presburger\n        qed\n        finally show ?thesis by argo\n      qed\n    qed\n    then interpret fgh: group_hom \"DirProds (Characters \\<circ> Gs) I\" \"Characters (DirProds Gs I)\" ?f by (unfold_locales, simp)\n    show \"bij_betw ?f (carrier (DirProds (Characters \\<circ> Gs) I)) (carrier (Characters (DirProds Gs I)))\"\n    proof (intro bij_betwI)\n      let ?g = \"(\\<lambda>c. (\\<lambda>i\\<in>I. (\\<lambda>a. c ((\\<lambda>i\\<in>I. \\<one>\\<^bsub>Gs i\\<^esub>)(i:=a)))))\"\n      have allc: \"character (Gs i) (?g x i)\" if x: \"x \\<in> carrier (Characters (DirProds Gs I))\" and  i: \"i \\<in> I\" for x i\n        using DirProds_subchar[OF DP.finite_comm_group_axioms x i assms(3)] .\n      have g_in: \"?g x \\<in> carrier (DirProds (Characters \\<circ> Gs) I)\" if x: \"x \\<in> carrier (Characters (DirProds Gs I))\" for x\n        using allc[OF x] unfolding DirProds_def Characters_def characters_def by simp\n      show fi: \"?f \\<in> carrier (DirProds (Characters \\<circ> Gs) I) \\<rightarrow> carrier (Characters (DirProds Gs I))\" using f_in by fast\n      show gi: \"?g \\<in> carrier (Characters (DirProds Gs I)) \\<rightarrow> carrier (DirProds (Characters \\<circ> Gs) I)\" using g_in by fast\n      show \"?f (?g x) = x\" if x: \"x \\<in> carrier (Characters (DirProds Gs I))\" for x\n      proof -\n        from x interpret x: character \"DirProds Gs I\" x unfolding Characters_def characters_def by auto\n        from f_in[OF g_in[OF x]] interpret character \"DirProds Gs I\" \"?f (?g x)\" unfolding Characters_def characters_def by simp\n        have \"(\\<Prod>i\\<in>I. (\\<lambda>i\\<in>I. \\<lambda>a. x ((\\<lambda>i\\<in>I. \\<one>\\<^bsub>Gs i\\<^esub>)(i := a))) i (e i)) = x e\" if e: \"e \\<in> carrier (DirProds Gs I)\" for e\n        proof -\n          define y where y: \"y = (\\<lambda>e. if e \\<in> carrier (DirProds Gs I) then \\<Prod>i\\<in>I. (\\<lambda>i\\<in>I. \\<lambda>a. x ((\\<lambda>i\\<in>I. \\<one>\\<^bsub>Gs i\\<^esub>)(i := a))) i (e i) else 0)\"\n          from Characters_DirProds_single_prod[OF DP.finite_comm_group_axioms x assms(3)]\n          have \"y = x\" using y by force\n          hence \"y e = x e\" by blast\n          thus ?thesis using e unfolding y by argo\n        qed\n        with x.char_eq_0 show ?thesis by force\n      qed\n      show \"?g (?f x) = x\" if x: \"x \\<in> carrier (DirProds (Characters \\<circ> Gs) I)\" for x\n      proof(intro eq_parts_imp_eq[OF g_in[OF f_in[OF x]] x])\n        show \"?g (?f x) i = x i\" if i: \"i\\<in>I\" for i\n        proof -\n          interpret xi: character \"Gs i\" \"x i\" using x i unfolding DirProds_def Characters_def characters_def by auto \n          have \"?g (?f x) i a = x i a\" if a: \"a\\<notin>carrier (Gs i)\" for a\n          proof -\n            have \"(\\<lambda>i\\<in>I. \\<one>\\<^bsub>Gs i\\<^esub>)(i := a) \\<notin> carrier (DirProds Gs I)\" using a i unfolding DirProds_def PiE_def Pi_def by auto\n            with xi.char_eq_0[OF a] a i show ?thesis by auto\n          qed\n          moreover have \"?g (?f x) i a = x i a\" if a: \"a\\<in>carrier (Gs i)\" for a\n          proof -\n            have \"(\\<lambda>i\\<in>I. \\<one>\\<^bsub>Gs i\\<^esub>)(i := a) \\<in> carrier (DirProds Gs I)\"\n              using a i monoid.one_closed[OF group.is_monoid[OF allg]] unfolding DirProds_def by force\n            moreover have \"(\\<Prod>j\\<in>I. x j (((\\<lambda>i\\<in>I. \\<one>\\<^bsub>Gs i\\<^esub>)(i := a)) j)) = x i a\"\n            proof -\n              have \"(\\<Prod>j\\<in>I. x j (((\\<lambda>i\\<in>I. \\<one>\\<^bsub>Gs i\\<^esub>)(i := a)) j)) = x i (((\\<lambda>i\\<in>I. \\<one>\\<^bsub>Gs i\\<^esub>)(i := a)) i) * (\\<Prod>j\\<in>I-{i}. x j (((\\<lambda>i\\<in>I. \\<one>\\<^bsub>Gs i\\<^esub>)(i := a)) j))\"\n                by (meson assms(3) i prod.remove)\n              moreover have \"x j (((\\<lambda>i\\<in>I. \\<one>\\<^bsub>Gs i\\<^esub>)(i := a)) j) = 1\" if j: \"j\\<in>I\" \"j \\<noteq> i\" for j\n              proof -\n                interpret xj: character \"Gs j\" \"x j\" using j(1) x unfolding DirProds_def Characters_def characters_def by auto\n                show ?thesis using j by auto\n              qed\n              moreover have \"x i (((\\<lambda>i\\<in>I. \\<one>\\<^bsub>Gs i\\<^esub>)(i := a)) i) = x i a\" by simp\n              ultimately show ?thesis by auto\n            qed\n            ultimately show ?thesis using a i by simp\n          qed\n          ultimately show ?thesis by blast\n        qed\n      qed\n    qed\n  qed\n  hence \"DirProds (Characters \\<circ> Gs) I \\<cong> Characters (DirProds Gs I)\" unfolding is_iso_def by blast\n  moreover have \"Characters (DirProds Gs I) \\<cong> Characters G\" using DP.iso_imp_iso_chars[OF assms(1) is_group] .\n  ultimately show ?thesis using iso_trans by blast\nqed\n\nlemma (in finite_comm_group) Characters_iso:\n  shows \"G \\<cong> Characters G\"\nproof -\n  from cyclic_product obtain ns where ns: \"DirProds (\\<lambda>n. Z (ns ! n)) {..<length ns} \\<cong> G\" \"\\<forall>n\\<in>set ns. n \\<noteq> 0\" .\n  interpret DP: group \"DirProds (\\<lambda>n. Z (ns ! n)) {..<length ns}\"\n    by (intro DirProds_is_group, auto)\n  have \"G \\<cong> DirProds (\\<lambda>n. Z (ns ! n)) {..<length ns}\" using DP.iso_sym[OF ns(1)] .\n  moreover have \"DirProds (Characters \\<circ> (\\<lambda>n. Z (ns ! n))) {..<length ns} \\<cong> Characters G\"\n    by (intro Characters_DirProds_iso[OF ns(1) DirProds_is_group], auto)\n  moreover have \"DirProds (\\<lambda>n. Z (ns ! n)) {..<length ns} \\<cong> DirProds (Characters \\<circ> (\\<lambda>n. Z (ns ! n))) {..<length ns}\"\n  proof (intro DirProds_iso1)\n    fix i assume i: \"i \\<in> {..<length ns}\"\n    obtain a where \"cyclic_group (Z (ns!i)) a\" using Zn_cyclic_group .\n    then interpret Zi: cyclic_group \"Z (ns!i)\" a .\n    interpret Zi: finite_cyclic_group \"Z (ns!i)\" a\n    proof\n      have \"order (Z (ns ! i)) \\<noteq> 0\" using ns(2) i Zn_order by simp\n      thus \"finite (carrier (Z (ns ! i)))\" unfolding order_def by (simp add: card_eq_0_iff)\n    qed\n    show \"Group.group ((Characters \\<circ> (\\<lambda>n. Z (ns ! n))) i)\" \"Group.group (Z (ns ! i))\" \"Z (ns ! i) \\<cong> (Characters \\<circ> (\\<lambda>n. Z (ns ! n))) i\"\n      using Zi.Characters_iso Zi.finite_comm_group_Characters comm_group_def finite_comm_group_def by auto\n  qed\n  ultimately show ?thesis by (auto elim: iso_trans)\nqed\n\nlemma (in finite_comm_group) order_Characters:\n  \"order (Characters G) = order G\"\n  using iso_same_card[OF Characters_iso] unfolding order_def by argo\n\n(* Manuel *)\ncorollary (in finite_comm_group) card_characters: \"card (characters G) = order G\"\n  using order_Characters unfolding order_def Characters_def by simp\n\n(* Manuel *)\nlemma (in finite_comm_group) iso_Characters_FactGroup:\n  assumes H: \"subgroup H G\"\n  shows \"(\\<lambda>\\<chi> x. if x \\<in> carrier G then \\<chi> (H #> x) else 0) \\<in>\n           iso (Characters (G Mod H)) ((Characters G)\\<lparr>carrier := {\\<chi>\\<in>characters G. \\<forall>x\\<in>H. \\<chi> x = 1}\\<rparr>)\"\nproof -\n  interpret H: normal H G using subgroup_imp_normal[OF H] .\n  interpret Chars: finite_comm_group \"Characters G\"\n    by (rule finite_comm_group_Characters)\n  interpret Fact: comm_group \"G Mod H\"\n    by (simp add: H.subgroup_axioms comm_group.abelian_FactGroup comm_group_axioms)\n  interpret Fact: finite_comm_group \"G Mod H\"\n    by unfold_locales (auto simp: carrier_FactGroup)\n\n  define C :: \"('a \\<Rightarrow> complex) set\" where \"C = {\\<chi>\\<in>characters G. \\<forall>x\\<in>H. \\<chi> x = 1}\"\n  interpret C: subgroup C \"Characters G\"\n  proof (unfold_locales, goal_cases)\n    case 1\n    thus ?case\n      by (auto simp: C_def one_Characters mult_Characters carrier_Characters characters_def)\n  next\n    case 2\n    thus ?case\n      by (auto simp: C_def one_Characters mult_Characters carrier_Characters characters_def)\n  next\n    case 3\n    thus ?case\n      by (auto simp: C_def one_Characters mult_Characters carrier_Characters characters_def principal_char_def)\n  next\n    case (4 \\<chi>)\n    hence \"inv\\<^bsub>Characters G\\<^esub> \\<chi> = inv_character \\<chi>\"\n      by (subst inv_Characters') (auto simp: C_def carrier_Characters)\n    moreover have \"inv_character \\<chi> \\<in> characters G\"\n      using 4 by (auto simp: C_def characters_def)\n    moreover have \"\\<forall>x\\<in>H. inv_character \\<chi> x = 1\"\n      using 4 by (auto simp: C_def inv_character_def)\n    ultimately show ?case\n      by (auto simp: C_def)\n  qed\n\n  define f :: \"('a set \\<Rightarrow> complex) \\<Rightarrow> ('a \\<Rightarrow> complex)\"\n    where \"f = (\\<lambda>\\<chi> x. if x \\<in> carrier G then \\<chi> (H #> x) else 0)\"\n\n  have [intro]: \"character G (f \\<chi>)\" if \"character (G Mod H) \\<chi>\" for \\<chi>\n  proof -\n    interpret character \"G Mod H\" \\<chi> by fact\n    show ?thesis\n    proof (unfold_locales, goal_cases)\n      case 1\n      thus ?case by (auto simp: f_def char_eq_0_iff carrier_FactGroup)\n    next\n      case (2 x)\n      thus ?case by (auto simp: f_def)\n    next\n      case (3 x y)\n      have \"\\<chi> (H #> x) * \\<chi> (H #> y) = \\<chi> ((H #> x) \\<otimes>\\<^bsub>G Mod H\\<^esub> (H #> y))\"\n        using 3 by (intro char_mult [symmetric]) (auto simp: carrier_FactGroup)\n      also have \"(H #> x) \\<otimes>\\<^bsub>G Mod H\\<^esub> (H #> y) = H #> (x \\<otimes> y)\"\n        using 3 by (simp add: H.rcos_sum)\n      finally show ?case\n        using 3 by (simp add: f_def)\n    qed\n  qed\n\n  have [intro]: \"f \\<chi> \\<in> C\" if \"character (G Mod H) \\<chi>\" for \\<chi>\n  proof -\n    interpret \\<chi>: character \"G Mod H\" \\<chi>\n      by fact\n    have \"character G (f \\<chi>)\"\n      using \\<chi>.character_axioms by auto\n    moreover have \"\\<chi> (H #> x) = 1\" if \"x \\<in> H\" for x\n      using that H.rcos_const \\<chi>.char_one by force\n    ultimately show ?thesis\n      by (auto simp: carrier_Characters C_def characters_def f_def)\n  qed\n\n  show \"f \\<in> iso (Characters (G Mod H)) ((Characters G)\\<lparr>carrier := C\\<rparr>)\"\n  proof (rule isoI)\n    show \"f \\<in> hom (Characters (G Mod H)) (Characters G\\<lparr>carrier := C\\<rparr>)\"\n    proof (rule homI, goal_cases)\n      case (1 \\<chi>)\n      thus ?case\n        by (auto simp: carrier_Characters characters_def)\n    qed (auto simp: f_def carrier_Characters fun_eq_iff mult_Characters)\n  next\n    have \"bij_betw f (characters (G Mod H)) C\"\n      unfolding bij_betw_def\n    proof\n      show inj: \"inj_on f (characters (G Mod H))\"\n      proof (rule inj_onI, goal_cases)\n        case (1 \\<chi>1 \\<chi>2)\n        interpret \\<chi>1: character \"G Mod H\" \\<chi>1\n          using 1 by (auto simp: characters_def)\n        interpret \\<chi>2: character \"G Mod H\" \\<chi>2\n          using 1 by (auto simp: characters_def)\n\n        have \"\\<chi>1 H' = \\<chi>2 H'\" for H'\n        proof (cases \"H' \\<in> carrier (G Mod H)\")\n          case False\n          thus ?thesis by (simp add: \\<chi>1.char_eq_0 \\<chi>2.char_eq_0)\n        next\n          case True\n          then obtain x where x: \"x \\<in> carrier G\" \"H' = H #> x\"\n            by (auto simp: carrier_FactGroup)\n          from 1 have \"f \\<chi>1 x = f \\<chi>2 x\"\n            by simp\n          with x show ?thesis\n            by (auto simp: f_def)\n        qed\n        thus \"\\<chi>1 = \\<chi>2\" by force\n      qed\n    \n      have \"f ` characters (G Mod H) \\<subseteq> C\"\n        by (auto simp: characters_def)\n      moreover have \"C \\<subseteq> f ` characters (G Mod H)\"\n      proof safe\n        fix \\<chi> assume \\<chi>: \"\\<chi> \\<in> C\"\n        from \\<chi> interpret character G \\<chi>\n          by (auto simp: C_def characters_def)\n        have [simp]: \"\\<chi> x = 1\" if \"x \\<in> H\" for x\n          using \\<chi> that by (auto simp: C_def)\n\n        have \"\\<forall>H'\\<in>carrier (G Mod H). \\<exists>x\\<in>carrier G. H' = H #> x\"\n          by (auto simp: carrier_FactGroup)\n        then obtain h where h: \"h H' \\<in> carrier G\" \"H' = H #> h H'\" if \"H' \\<in> carrier (G Mod H)\" for H'\n          by metis\n        define \\<chi>' where \"\\<chi>' = (\\<lambda>H'. if H' \\<in> carrier (G Mod H) then \\<chi> (h H') else 0)\"\n\n        have \\<chi>_cong: \"\\<chi> x = \\<chi> y\" if \"H #> x = H #> y\" \"x \\<in> carrier G\" \"y \\<in> carrier G\" for x y\n        proof -\n          have \"x \\<in> H #> x\"\n            by (simp add: H.subgroup_axioms rcos_self that(2))\n          also have \"\\<dots> = H #> y\"\n            by fact\n          finally obtain z where z: \"z \\<in> H\" \"x = z \\<otimes> y\"\n            unfolding r_coset_def by auto\n          thus ?thesis\n            using z H.subset that by simp\n        qed\n\n        have \"character (G Mod H) \\<chi>'\"\n        proof (unfold_locales, goal_cases)\n          case 1\n          have H: \"H \\<in> carrier (G Mod H)\"\n            using Fact.one_closed unfolding one_FactGroup .\n          with h[of H] have \"h H \\<in> carrier G\"\n            by blast\n          thus ?case using H\n            by (auto simp: char_eq_0_iff \\<chi>'_def)\n        next\n          case (2 H')\n          thus ?case by (auto simp: \\<chi>'_def)\n        next\n          case (3 H1 H2)\n          from 3 have H12: \"H1 <#> H2 \\<in> carrier (G Mod H)\"\n            using Fact.m_closed by force\n          have \"\\<chi> (h (H1 <#> H2)) = \\<chi> (h H1 \\<otimes> h H2)\"\n          proof (rule \\<chi>_cong)\n            show \"H #> h (H1 <#> H2) = H #> (h H1 \\<otimes> h H2)\"\n              by (metis \"3\" H.rcos_sum H12 h)\n          qed (use 3 h[of H1] h[of H2] h[OF H12] in auto)\n          thus ?case\n            using 3 H12 h[of H1] h[of H2] by (auto simp: \\<chi>'_def)\n        qed\n\n        moreover have \"f \\<chi>' x = \\<chi> x\" for x\n        proof (cases \"x \\<in> carrier G\")\n          case False\n          thus ?thesis\n            by (auto simp: f_def \\<chi>'_def char_eq_0_iff)\n        next\n          case True\n          hence *: \"H #> x \\<in> carrier (G Mod H)\"\n            by (auto simp: carrier_FactGroup)\n          have \"\\<chi> (h (H #> x)) = \\<chi> x\"\n            using True * h[of \"H #> x\"] by (intro \\<chi>_cong) auto\n          thus ?thesis\n            using True * by (auto simp: f_def fun_eq_iff \\<chi>'_def)\n        qed\n        hence \"f \\<chi>' = \\<chi>\" by force\n\n        ultimately show \"\\<chi> \\<in> f ` characters (G Mod H)\"\n          unfolding characters_def by blast\n      qed\n\n      ultimately show \"f ` characters (G Mod H) = C\"\n        by blast\n\n    qed\n    thus \"bij_betw f (carrier (Characters (G Mod H))) (carrier (Characters G\\<lparr>carrier := C\\<rparr>))\"\n      by (simp add: carrier_Characters)\n  qed \nqed\n\n(* Manuel *)\nlemma (in finite_comm_group) is_iso_Characters_FactGroup:\n  assumes H: \"subgroup H G\"\n  shows \"Characters (G Mod H) \\<cong> (Characters G)\\<lparr>carrier := {\\<chi>\\<in>characters G. \\<forall>x\\<in>H. \\<chi> x = 1}\\<rparr>\"\n  using iso_Characters_FactGroup[OF assms] unfolding is_iso_def by blast\n\nsubsection \\<open>Non-trivial facts about characters\\<close>\n\ndefinition restrict_char::\"'a set \\<Rightarrow> ('a \\<Rightarrow> complex) \\<Rightarrow> ('a \\<Rightarrow> complex) \" where\n\"restrict_char H \\<chi> = (\\<lambda>e. if e\\<in>H then \\<chi> e else 0)\"\n\nlemma (in finite_comm_group) restrict_char_hom:\n  assumes \"subgroup H G\"\n  shows \"group_hom (Characters G) (Characters (G\\<lparr>carrier := H\\<rparr>)) (restrict_char H)\"\nproof -\n  let ?CG = \"Characters G\"\n  let ?H = \"G\\<lparr>carrier := H\\<rparr>\"\n  let ?CH = \"Characters ?H\" \n  interpret H: subgroup H G by fact\n  interpret H: finite_comm_group ?H by (simp add: assms subgroup_imp_finite_comm_group)\n  interpret CG: finite_comm_group ?CG using finite_comm_group_Characters .\n  interpret CH: finite_comm_group ?CH using H.finite_comm_group_Characters .\n  show ?thesis\n  proof(unfold_locales, intro homI)\n    show \"restrict_char H x \\<in> carrier ?CH\" if x: \"x \\<in> carrier ?CG\" for x\n    proof -\n      interpret xc: character G x using x unfolding Characters_def characters_def by simp\n      have \"character ?H (restrict_char H x)\"\n        by (unfold restrict_char_def, unfold_locales, auto)\n      thus ?thesis unfolding Characters_def characters_def by simp\n    qed\n    show \"restrict_char H (x \\<otimes>\\<^bsub>?CG\\<^esub> y) = restrict_char H x \\<otimes>\\<^bsub>?CH\\<^esub> restrict_char H y\"\n      if x: \"x \\<in> carrier ?CG\" and y: \"y \\<in> carrier ?CG\" for x y\n    proof -\n      interpret xc: character G x using x unfolding Characters_def characters_def by simp\n      interpret yc: character G y using y unfolding Characters_def characters_def by simp\n      show ?thesis unfolding Characters_def restrict_char_def by auto\n    qed\n  qed\nqed\n\nlemma (in finite_comm_group) restrict_char_kernel:\n  assumes \"subgroup H G\"\n  shows \"kernel (Characters G) (Characters (G\\<lparr>carrier := H\\<rparr>)) (restrict_char H) = {\\<chi>\\<in>characters G. \\<forall>x\\<in>H. \\<chi> x = 1}\"\n  by (unfold restrict_char_def kernel_def one_Characters carrier_Characters principal_char_def characters_def, simp, metis)\n\nlemma (in finite_comm_group) restrict_char_image:\n  assumes \"subgroup H G\"\n  shows \"restrict_char H ` (carrier (Characters G)) = carrier (Characters (G\\<lparr>carrier := H\\<rparr>))\"\nproof -\n  interpret H: subgroup H G by fact\n  interpret H: finite_comm_group \"G\\<lparr>carrier := H\\<rparr>\" using subgroup_imp_finite_comm_group[OF assms] .\n  interpret r: group_hom \"Characters G\" \"Characters (G\\<lparr>carrier := H\\<rparr>)\" \"restrict_char H\" using restrict_char_hom[OF assms] .\n  interpret Mod: finite_comm_group \"G Mod H\" using finite_comm_FactGroup[OF assms] .\n  interpret CG: finite_comm_group \"Characters G\" using finite_comm_group_Characters .\n  have c1: \"order (Characters (G\\<lparr>carrier := H\\<rparr>)) = card H\" using H.order_Characters unfolding order_def by simp\n  \n  have \"card H * card (kernel (Characters G) (Characters (G\\<lparr>carrier := H\\<rparr>)) (restrict_char H)) = order G\"\n    using restrict_char_kernel[OF assms] iso_same_card[OF is_iso_Characters_FactGroup[OF assms]]\n          Mod.order_Characters lagrange[OF assms] unfolding order_def FactGroup_def by (force simp: algebra_simps)\n  moreover have \"card (kernel (Characters G) (Characters (G\\<lparr>carrier := H\\<rparr>)) (restrict_char H)) \\<noteq> 0\"\n    using r.one_in_kernel unfolding kernel_def CG.fin by auto\n  ultimately have c2: \"card H = card (restrict_char H ` carrier (Characters G))\"\n    using r.image_kernel_product[unfolded order_Characters] by (metis mult_right_cancel)\n\n  have \"restrict_char H ` (carrier (Characters G)) \\<subseteq> carrier (Characters (G\\<lparr>carrier := H\\<rparr>))\"\n    by auto\n  with c2 H.fin show ?thesis\n    by (auto, metis H.finite_imp_card_positive c1 card_subset_eq fin_gen order_def r.H.order_gt_0_iff_finite)\nqed\n\nlemma (in finite_comm_group) character_restrict_card: \n  assumes \"subgroup H G\" \"character G a\" \"character G b\"\n  shows   \"card {\\<chi>'\\<in>characters G. \\<forall>x\\<in>H. \\<chi>' x = a x} = card {\\<chi>'\\<in>characters G. \\<forall>x\\<in>H. \\<chi>' x = b x}\"\nproof -\n  interpret H: subgroup H G by fact\n  interpret H: finite_comm_group \"G\\<lparr>carrier := H\\<rparr>\" using assms(1) by (simp add: subgroup_imp_finite_comm_group)\n  interpret CG: finite_comm_group \"Characters G\" using finite_comm_group_Characters .\n  interpret a: character G a by fact\n  interpret b: character G b by fact\n  have ac: \"a \\<in> carrier (Characters G)\" unfolding Characters_def characters_def using assms by simp\n  have bc: \"b \\<in> carrier (Characters G)\" unfolding Characters_def characters_def using assms by simp\n  define f where f: \"f = (\\<lambda>c. b \\<otimes>\\<^bsub>Characters G\\<^esub> inv\\<^bsub>Characters G\\<^esub> a \\<otimes>\\<^bsub>Characters G\\<^esub> c)\"\n  define g where g: \"g = (\\<lambda>c. a \\<otimes>\\<^bsub>Characters G\\<^esub> inv\\<^bsub>Characters G\\<^esub> b \\<otimes>\\<^bsub>Characters G\\<^esub> c)\"\n  let ?A = \"{\\<chi>'\\<in>characters G. \\<forall>x\\<in>H. \\<chi>' x = a x}\"\n  let ?B = \"{\\<chi>'\\<in>characters G. \\<forall>x\\<in>H. \\<chi>' x = b x}\"\n  have \"bij_betw f ?A ?B\"\n  proof(intro bij_betwI[of _ _ _ g])\n    show \"f \\<in> ?A \\<rightarrow> ?B\"\n    proof\n      show \"f x \\<in> ?B\" if x: \"x \\<in> ?A\" for x\n      proof -\n        interpret xc: character G x using x unfolding characters_def by blast\n        have xc: \"x \\<in> carrier (Characters G)\" using x unfolding Characters_def by simp\n        have \"f x y = b y\" if y: \"y \\<in> H\" for y\n        proof -\n          have \"(inv\\<^bsub>Characters G\\<^esub> a) y * a y =  1\"\n            by (simp add: a.inv_Characters a.mult_inv_character mult.commute principal_char_def y)\n          thus ?thesis unfolding f mult_Characters using x y by fastforce\n        qed\n        thus \"f x \\<in> ?B\" unfolding f carrier_Characters[symmetric] using ac bc xc by blast\n      qed\n    qed\n    show \"g \\<in> ?B \\<rightarrow> ?A\"\n    proof\n      show \"g x \\<in> ?A\" if x: \"x \\<in> ?B\" for x\n      proof -\n        interpret xc: character G x using x unfolding characters_def by blast\n        have xc: \"x \\<in> carrier (Characters G)\" using x unfolding Characters_def by simp\n        have \"g x y = a y\" if y: \"y \\<in> H\" for y\n        proof -\n          have \"(inv\\<^bsub>Characters G\\<^esub> b) y * x y = 1\" using x y\n            by (simp add: b.inv_Characters b.mult_inv_character mult.commute principal_char_def)\n          thus ?thesis unfolding g mult_Characters by simp\n        qed\n        thus \"g x \\<in> ?A\" unfolding g carrier_Characters[symmetric] using ac bc xc by blast\n      qed\n    qed\n    show \"g (f x) = x\" if x: \"x \\<in> ?A\" for x\n    proof -\n      have xc: \"x \\<in> carrier (Characters G)\" using x unfolding Characters_def by force\n      with ac bc show ?thesis unfolding f g\n        by (auto simp: CG.m_assoc[symmetric], metis CG.inv_closed CG.inv_comm CG.l_inv CG.m_assoc CG.r_one)\n    qed\n    show \"f (g x) = x\" if x: \"x \\<in> ?B\" for x\n    proof -\n      have xc: \"x \\<in> carrier (Characters G)\" using x unfolding Characters_def by force\n      with ac bc show ?thesis unfolding f g\n        by (auto simp: CG.m_assoc[symmetric], metis CG.inv_closed CG.inv_comm CG.l_inv CG.m_assoc CG.r_one)\n    qed\n  qed\n  thus ?thesis using bij_betw_same_card by blast\nqed\n\ntheorem (in finite_comm_group) card_character_extensions:\n  assumes \"subgroup H G\" \"character (G\\<lparr>carrier := H\\<rparr>) \\<chi>\"\n  shows   \"card {\\<chi>'\\<in>characters G. \\<forall>x\\<in>H. \\<chi>' x = \\<chi> x} * card H = order G\"\nproof -\n  interpret H: subgroup H G by fact\n  interpret H: finite_comm_group \"G\\<lparr>carrier := H\\<rparr>\" using subgroup_imp_finite_comm_group[OF assms(1)] .\n  interpret chi: character \"G\\<lparr>carrier := H\\<rparr>\" \\<chi> by fact\n  interpret C: finite_comm_group \"Characters G\" using finite_comm_group_Characters .\n  interpret Mod: finite_comm_group \"G Mod H\" using finite_comm_FactGroup[OF assms(1)] .\n  obtain a where a: \"a \\<in> carrier (Characters G)\" \"restrict_char H a = \\<chi>\"\n  proof -\n    have \"\\<exists>a\\<in>carrier (Characters G). restrict_char H a = \\<chi>\"\n      using restrict_char_image[OF assms(1)] assms(2) unfolding carrier_Characters characters_def image_def by force\n    thus ?thesis using that by blast\n  qed\n  show ?thesis\n  proof -\n    have p: \"{\\<chi>\\<in>characters G. \\<forall>x\\<in>H. \\<chi> x = 1} = {\\<chi>\\<in>characters G. \\<forall>x\\<in>H. \\<chi> x = principal_char G x}\"\n      unfolding principal_char_def by force\n    have ac: \"{\\<chi>'\\<in>characters G. \\<forall>x\\<in>H. \\<chi>' x = \\<chi> x} = {\\<chi>'\\<in>characters G. \\<forall>x\\<in>H. \\<chi>' x = a x}\" using a(2) unfolding restrict_char_def by force\n    have \"card {\\<chi>\\<in>characters G. \\<forall>x\\<in>H. \\<chi> x = 1} = card {\\<chi>'\\<in>characters G. \\<forall>x\\<in>H. \\<chi>' x = \\<chi> x}\"\n      by (unfold ac p; intro character_restrict_card[OF assms(1)], use a[unfolded Characters_def characters_def] in auto)\n    moreover have \"card {\\<chi>\\<in>characters G. \\<forall>x\\<in>H. \\<chi> x = 1} = card (carrier (G Mod H))\"\n      using iso_same_card[OF is_iso_Characters_FactGroup[OF assms(1)]] Mod.order_Characters[unfolded order_def] by force\n    moreover have \"card (carrier (G Mod H)) * card H = order G\" using lagrange[OF assms(1)] unfolding FactGroup_def by simp\n    ultimately show ?thesis by argo\n  qed\nqed\n\ntext \\<open>\n  It also follows as a simple corollary that any character on \\<open>H\\<close> \\<^emph>\\<open>can\\<close> be extended\n  to a character on \\<open>G\\<close>.\n\\<close>\n\ncorollary (in finite_comm_group) character_extension_exists:\n  assumes \"subgroup H G\" \"character (G\\<lparr>carrier := H\\<rparr>) \\<chi>\"\n  obtains \\<chi>' where \"character G \\<chi>'\" and \"\\<And>x. x \\<in> H \\<Longrightarrow> \\<chi>' x = \\<chi> x\"\nproof -\n  have \"card {\\<chi>'\\<in>characters G. \\<forall>x\\<in>H. \\<chi>' x = \\<chi> x} * card H = order G\"\n    by (intro card_character_extensions assms)\n  hence \"card {\\<chi>'\\<in>characters G. \\<forall>x\\<in>H. \\<chi>' x = \\<chi> x} \\<noteq> 0\"\n    using order_gt_0 by (intro notI) auto\n  hence \"{\\<chi>'\\<in>characters G. \\<forall>x\\<in>H. \\<chi>' x = \\<chi> x} \\<noteq> {}\"\n    by (intro notI) simp\n  then obtain \\<chi>' where \"character G \\<chi>'\" and \"\\<And>x. x \\<in> H \\<Longrightarrow> \\<chi>' x = \\<chi> x\"\n    unfolding characters_def by blast\n  thus ?thesis using that[of \\<chi>'] by blast\nqed\n\ntext \\<open>\n  Lastly, we can also show that for each $x\\in H$ of order $n > 1$ and each \\<open>n\\<close>-th root of\n  unity \\<open>z\\<close>, there exists a character \\<open>\\<chi>\\<close> on \\<open>G\\<close> such that $\\chi(x) = z$.\n\\<close>\n\ncorollary (in finite_comm_group) character_with_value_exists:\n  assumes \"x \\<in> carrier G\" and \"x \\<noteq> \\<one>\" and \"z ^ ord x = 1\"\n  obtains \\<chi> where \"character G \\<chi>\" and \"\\<chi> x = z\"\nproof -\n  interpret H: subgroup \"generate G {x}\" G using generate_is_subgroup assms(1) by simp\n  interpret H: finite_comm_group \"G\\<lparr>carrier := generate G {x}\\<rparr>\" using subgroup_imp_finite_comm_group[OF H.subgroup_axioms] . \n  interpret H: finite_cyclic_group \"G\\<lparr>carrier := generate G {x}\\<rparr>\" x\n  proof(unfold finite_cyclic_group_def, safe)\n    show \"finite_group (G\\<lparr>carrier := generate G {x}\\<rparr>)\" by unfold_locales\n    show \"cyclic_group (G\\<lparr>carrier := generate G {x}\\<rparr>) x\"\n    proof(intro H.cyclic_groupI0)\n      show \"x \\<in> carrier (G\\<lparr>carrier := generate G {x}\\<rparr>)\" using generate.incl[of x \"{x}\" G] by simp\n      show \"carrier (G\\<lparr>carrier := generate G {x}\\<rparr>) = generate (G\\<lparr>carrier := generate G {x}\\<rparr>) {x}\"\n        using generate_consistent[OF generate_sincl H.subgroup_axioms] by simp\n    qed\n  qed\n  have ox: \"H.ord x = ord x\" using H.gen_closed H.subgroup_axioms subgroup_ord_eq by auto\n  have ogt1: \"ord x > 1\" using ord_pos by (metis assms(1, 2) less_one nat_neq_iff ord_eq_1)\n  from assms H.unity_root_induce_char[unfolded H.ord_gen_is_group_order[symmetric] ox, OF assms(3)]\n  obtain c where c: \"character (G\\<lparr>carrier := generate G {x}\\<rparr>) c\"\n                    \"c = (\\<lambda>a. if a \\<in> carrier (G\\<lparr>carrier := generate G {x}\\<rparr>) then z powi H.get_exp x a else 0)\" by blast\n  have cx: \"c x = z\" unfolding c(2) using H.powi_get_exp_self[OF assms(3) _ ox ogt1] generate_sincl[of \"{x}\"] by simp\n  obtain f where f: \"character G f\" \"\\<And>y. y \\<in> (generate G {x}) \\<Longrightarrow> f y = c y\"\n    using character_extension_exists[OF H.subgroup_axioms c(1)] by blast\n  show ?thesis by (intro that[OF f(1)], use cx f(2) generate_sincl in blast)\nqed\n(* until here: Joseph *)\n\ntext \\<open>\n  In particular, for any \\<open>x\\<close> that is not the identity element, there exists a character \\<open>\\<chi>\\<close>\n  such that $\\chi(x)\\neq 1$.\n\\<close>\ncorollary (in finite_comm_group) character_neq_1_exists:\n  assumes \"x \\<in> carrier G\" and \"x \\<noteq> \\<one>\"\n  obtains \\<chi> where \"character G \\<chi>\" and \"\\<chi> x \\<noteq> 1\"\nproof -\n  define z where \"z = cis (2 * pi / ord x)\"\n  have z_pow_h: \"z ^ ord x = 1\"\n    by (auto simp: z_def DeMoivre)\n\n  from assms have \"ord x \\<ge> 1\" by (intro ord_ge_1) auto\n  moreover have \"ord x \\<noteq> 1\"\n    using pow_ord_eq_1[of x] assms fin by (intro notI) simp_all\n  ultimately have \"ord x > 1\" by linarith\n\n  have [simp]: \"z \\<noteq> 1\"\n  proof\n    assume \"z = 1\"\n    have \"bij_betw (\\<lambda>k. cis (2 * pi * real k / real (ord x))) {..<ord x} {z. z ^ ord x = 1}\"\n      using \\<open>ord x > 1\\<close> by (intro bij_betw_roots_unity) auto\n    hence inj: \"inj_on (\\<lambda>k. cis (2 * pi * real k / real (ord x))) {..<ord x}\"\n      by (auto simp: bij_betw_def)\n    have \"0 = (1 :: nat)\"\n      using \\<open>z = 1\\<close> and \\<open>ord x > 1\\<close> by (intro inj_onD[OF inj]) (auto simp: z_def)\n    thus False by simp\n  qed\n\n  obtain \\<chi> where \"character G \\<chi>\" and \"\\<chi> x = z\"\n    using character_with_value_exists[OF assms z_pow_h] .\n  thus ?thesis using that[of \\<chi>] by simp\nqed\n\nsubsection \\<open>The first orthogonality relation\\<close>\n\ntext \\<open>\n  The entries of any non-principal character sum to 0.\n\\<close>\ntheorem (in character) sum_character:\n  \"(\\<Sum>x\\<in>carrier G. \\<chi> x) = (if \\<chi> = principal_char G then of_nat (order G) else 0)\"\nproof (cases \"\\<chi> = principal_char G\")\n  case True\n  hence \"(\\<Sum>x\\<in>carrier G. \\<chi> x) = (\\<Sum>x\\<in>carrier G. 1)\"\n    by (intro sum.cong) (auto simp: principal_char_def)\n  also have \"\\<dots> = order G\" by (simp add: order_def)\n  finally show ?thesis using True by simp\nnext\n  case False\n  define S where \"S = (\\<Sum>x\\<in>carrier G. \\<chi> x)\"\n  from False obtain y where y: \"y \\<in> carrier G\" \"\\<chi> y \\<noteq> 1\"\n    by (auto simp: principal_char_def fun_eq_iff char_eq_0_iff split: if_splits)\n  from y have \"S = (\\<Sum>x\\<in>carrier G. \\<chi> (y \\<otimes> x))\" unfolding S_def\n    by (intro sum.reindex_bij_betw [symmetric] bij_betw_mult_left)\n  also have \"\\<dots> = (\\<Sum>x\\<in>carrier G. \\<chi> y * \\<chi> x)\"\n    by (intro sum.cong refl char_mult y)\n  also have \"\\<dots> = \\<chi> y * S\" by (simp add: S_def sum_distrib_left)\n  finally have \"(\\<chi> y - 1) * S = 0\" by (simp add: algebra_simps)\n  with y have \"S = 0\" by simp\n  with False show ?thesis by (simp add: S_def)\nqed\n\ncorollary (in finite_comm_group) character_orthogonality1:\n  assumes \"character G \\<chi>\" and \"character G \\<chi>'\"\n  shows   \"(\\<Sum>x\\<in>carrier G. \\<chi> x * cnj (\\<chi>' x)) = (if \\<chi> = \\<chi>' then of_nat (order G) else 0)\"\nproof -\n  define C where [simp]: \"C = Characters G\"\n  interpret C: finite_comm_group C unfolding C_def\n    by (rule finite_comm_group_Characters)\n  let ?\\<chi> = \"\\<lambda>x. \\<chi> x * inv_character \\<chi>' x\"\n  interpret character G \"\\<lambda>x. \\<chi> x * inv_character \\<chi>' x\"\n    by (intro character_mult character.inv_character assms)\n  have \"(\\<Sum>x\\<in>carrier G. \\<chi> x * cnj (\\<chi>' x)) = (\\<Sum>x\\<in>carrier G. ?\\<chi> x)\"\n    by (intro sum.cong) (auto simp: inv_character_def)\n  also have \"\\<dots> = (if ?\\<chi> = principal_char G then of_nat (order G) else 0)\"\n    by (rule sum_character)\n  also have \"?\\<chi> = principal_char G \\<longleftrightarrow> \\<chi> \\<otimes>\\<^bsub>C\\<^esub> inv\\<^bsub>C\\<^esub> \\<chi>' = \\<one>\\<^bsub>C\\<^esub>\"\n    using assms by (simp add: Characters_simps characters_def)\n  also have \"\\<dots> \\<longleftrightarrow> \\<chi> = \\<chi>'\"\n  proof\n    assume \"\\<chi> \\<otimes>\\<^bsub>C\\<^esub> inv\\<^bsub>C\\<^esub> \\<chi>' = \\<one>\\<^bsub>C\\<^esub>\"\n    from C.inv_equality [OF this] and assms show \"\\<chi> = \\<chi>'\"\n      by (auto simp: characters_def Characters_simps)\n  next\n    assume *: \"\\<chi> = \\<chi>'\"\n    from assms show \"\\<chi> \\<otimes>\\<^bsub>C\\<^esub> inv\\<^bsub>C\\<^esub> \\<chi>' = \\<one>\\<^bsub>C\\<^esub>\" \n      by (subst *, intro C.r_inv) (auto simp: carrier_Characters characters_def)\n  qed\n  finally show ?thesis .\nqed\n\n\nsubsection \\<open>The isomorphism between a group and its double dual\\<close>\n\ntext \\<open>\n  Lastly, we show that the double dual of a finite abelian group is naturally isomorphic\n  to the original group via the obvious isomorphism $x\\mapsto (\\chi\\mapsto \\chi(x))$.\n  It is easy to see that this is a homomorphism and that it is injective. The fact \n  $|\\widehat{\\widehat{G}}| = |\\widehat{G}| = |G|$ then shows that it is also surjective.\n\\<close>\ncontext finite_comm_group\nbegin\n\ndefinition double_dual_iso :: \"'a \\<Rightarrow> ('a \\<Rightarrow> complex) \\<Rightarrow> complex\" where\n  \"double_dual_iso x = (\\<lambda>\\<chi>. if character G \\<chi> then \\<chi> x else 0)\"\n\nlemma double_dual_iso_apply [simp]: \"character G \\<chi> \\<Longrightarrow> double_dual_iso x \\<chi> = \\<chi> x\"\n  by (simp add: double_dual_iso_def)\n\nlemma character_double_dual_iso [intro]:\n  assumes x: \"x \\<in> carrier G\"\n  shows   \"character (Characters G) (double_dual_iso x)\"\nproof -\n  interpret G': finite_comm_group \"Characters G\"\n    by (rule finite_comm_group_Characters)\n  show \"character (Characters G) (double_dual_iso x)\"\n    using x by unfold_locales (auto simp: double_dual_iso_def characters_def Characters_def\n                                              principal_char_def character.char_eq_0)\nqed\n\nlemma double_dual_iso_mult [simp]:\n  assumes \"x \\<in> carrier G\" \"y \\<in> carrier G\"\n  shows   \"double_dual_iso (x \\<otimes> y) =\n             double_dual_iso x \\<otimes>\\<^bsub>Characters (Characters G)\\<^esub> double_dual_iso y\"\n  using assms by (auto simp: double_dual_iso_def Characters_def fun_eq_iff character.char_mult)\n\nlemma double_dual_iso_one [simp]:\n  \"double_dual_iso \\<one> = principal_char (Characters G)\"\n  by (auto simp: fun_eq_iff double_dual_iso_def principal_char_def\n                 carrier_Characters characters_def character.char_one)\n\nlemma inj_double_dual_iso: \"inj_on double_dual_iso (carrier G)\"\nproof -\n  interpret G': finite_comm_group \"Characters G\"\n    by (rule finite_comm_group_Characters)\n  interpret G'': finite_comm_group \"Characters (Characters G)\"\n    by (rule G'.finite_comm_group_Characters)\n  have hom: \"double_dual_iso \\<in> hom G (Characters (Characters G))\"\n    by (rule homI) (auto simp: carrier_Characters characters_def)\n  have inj_aux: \"x = \\<one>\"\n    if x: \"x \\<in> carrier G\" \"double_dual_iso x = \\<one>\\<^bsub>Characters (Characters G)\\<^esub>\" for x\n  proof (rule ccontr)\n    assume \"x \\<noteq> \\<one>\"\n    obtain \\<chi> where \\<chi>: \"character G \\<chi>\" \"\\<chi> x \\<noteq> 1\"\n      using character_neq_1_exists[OF x(1) \\<open>x \\<noteq> \\<one>\\<close>] .\n    from x have \"\\<forall>\\<chi>. (if \\<chi> \\<in> characters G then \\<chi> x else 0) = (if \\<chi> \\<in> characters G then 1 else 0)\"\n      by (auto simp: double_dual_iso_def Characters_def fun_eq_iff\n                     principal_char_def characters_def)\n    hence eq1: \"\\<forall>\\<chi>\\<in>characters G. \\<chi> x = 1\" by metis\n    with \\<chi> show False unfolding characters_def by auto\n  qed\n  thus ?thesis\n    using inj_aux hom is_group G''.is_group by (subst inj_on_one_iff') auto\nqed\n\nlemma double_dual_iso_eq_iff [simp]:\n  \"x \\<in> carrier G \\<Longrightarrow> y \\<in> carrier G \\<Longrightarrow> double_dual_iso x = double_dual_iso y \\<longleftrightarrow> x = y\"\n  by (auto dest: inj_onD[OF inj_double_dual_iso])\n\ntheorem double_dual_iso: \"double_dual_iso \\<in> iso G (Characters (Characters G))\"\nproof (rule isoI)\n  interpret G': finite_comm_group \"Characters G\"\n    by (rule finite_comm_group_Characters)\n  interpret G'': finite_comm_group \"Characters (Characters G)\"\n    by (rule G'.finite_comm_group_Characters)\n\n  show hom: \"double_dual_iso \\<in> hom G (Characters (Characters G))\"\n    by (rule homI) (auto simp: carrier_Characters characters_def)\n\n  show \"bij_betw double_dual_iso (carrier G) (carrier (Characters (Characters G)))\"\n    unfolding bij_betw_def\n  proof\n    show \"inj_on double_dual_iso (carrier G)\" by (fact inj_double_dual_iso)\n  next\n    show \"double_dual_iso ` carrier G = carrier (Characters (Characters G))\"\n    proof (rule card_subset_eq)\n      show \"finite (carrier (Characters (Characters G)))\"\n        by (fact G''.fin)\n    next\n      have \"card (carrier (Characters (Characters G))) = card (carrier G)\"\n        by (simp add: carrier_Characters G'.card_characters card_characters order_def)\n      also have \"\\<dots> = card (double_dual_iso ` carrier G)\"\n        by (intro card_image [symmetric] inj_double_dual_iso)\n      finally show \"card (double_dual_iso ` carrier G) =\n                      card (carrier (Characters (Characters G)))\" ..\n    next\n      show \"double_dual_iso ` carrier G \\<subseteq> carrier (Characters (Characters G))\"\n        using hom by (auto simp: hom_def)\n    qed\n  qed\nqed\n\nlemma double_dual_is_iso: \"Characters (Characters G) \\<cong> G\"\n  by (rule iso_sym) (use double_dual_iso in \\<open>auto simp: is_iso_def\\<close>)\n\ntext \\<open>\n  The second orthogonality relation follows from the first one via Pontryagin duality:\n\\<close>\ntheorem sum_characters:\n  assumes x: \"x \\<in> carrier G\"\n  shows   \"(\\<Sum>\\<chi>\\<in>characters G. \\<chi> x) = (if x = \\<one> then of_nat (order G) else 0)\"\nproof -\n  interpret G': finite_comm_group \"Characters G\"\n    by (rule finite_comm_group_Characters)\n  interpret x: character \"Characters G\" \"double_dual_iso x\"\n    using x by auto\n  from x.sum_character show ?thesis using double_dual_iso_eq_iff[of x \\<one>] x\n    by (auto simp: characters_def carrier_Characters order_Characters simp del: double_dual_iso_eq_iff)\nqed\n\ncorollary character_orthogonality2:\n  assumes \"x \\<in> carrier G\" \"y \\<in> carrier G\"\n  shows   \"(\\<Sum>\\<chi>\\<in>characters G. \\<chi> x * cnj (\\<chi> y)) = (if x = y then of_nat (order G) else 0)\"\nproof -\n  from assms have \"(\\<Sum>\\<chi>\\<in>characters G. \\<chi> x * cnj (\\<chi> y)) = (\\<Sum>\\<chi>\\<in>characters G. \\<chi> (x \\<otimes> inv y))\"\n    by (intro sum.cong) (simp_all add: character.char_inv character.char_mult characters_def)\n  also from assms have \"\\<dots> = (if x \\<otimes> inv y = \\<one> then of_nat (order G) else 0)\"\n    by (intro sum_characters) auto\n  also from assms have \"x \\<otimes> inv y = \\<one> \\<longleftrightarrow> x = y\"\n    using inv_equality[of x \"inv y\"] by auto\n  finally show ?thesis .\nqed\n\nend\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/Multiplicative_Characters.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8558511322604134, "lm_q2_score": 0.8499711680567799, "lm_q1q2_score": 0.7274487865701011}}
{"text": "theory interior_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>Interior algebra\\<close>\n(**We define a topological Boolean algebra taking the interior operator as primitive and verify some properties.*)\n\n(**Declares a primitive (unconstrained) interior operation and defines others from it.*)\nconsts \\<I>::\"\\<sigma>\\<Rightarrow>\\<sigma>\"\nabbreviation \"\\<C> \\<equiv> \\<I>\\<^sup>d\" (**closure*)\nabbreviation \"\\<B> \\<equiv> \\<B>\\<^sub>I \\<I>\" (**border*)\nabbreviation \"\\<F> \\<equiv> \\<F>\\<^sub>I \\<I>\" (**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\" using dual_symm equal_op_def by auto\nlemma IB_rel: \"Int_2 \\<I> \\<Longrightarrow> \\<I> \\<^bold>\\<equiv> \\<I>\\<^sub>B \\<B>\" by (smt Br_int_def Int_br_def dEXP_def diff_def equal_op_def)\nlemma IF_rel: \"Int_2 \\<I> \\<Longrightarrow> \\<I> \\<^bold>\\<equiv> \\<I>\\<^sub>F \\<F>\" using EXP_def EXP_dual2 Fr_int_def IB_rel Int_br_def Int_fr_def compl_def diff_def equal_op_def meet_def by fastforce  \n\n\n(**Fixed-point and other operators are interestingly related.*)\nlemma fp1: \"Int_2 \\<I> \\<Longrightarrow> \\<I>\\<^sup>f\\<^sup>p \\<^bold>\\<equiv> \\<B>\\<^sup>c\" by (smt Br_int_def IB_rel Int_br_def compl_def diff_def dimp_def equal_op_def)\nlemma fp2: \"Int_2 \\<I> \\<Longrightarrow> \\<B>\\<^sup>f\\<^sup>p \\<^bold>\\<equiv> \\<I>\\<^sup>c\" using fp1 unfolding compl_def dimp_def equal_op_def by smt\nlemma fp3: \"Int_2 \\<I> \\<Longrightarrow> \\<C>\\<^sup>f\\<^sup>p \\<^bold>\\<equiv> \\<B>\\<^sup>d\" by (metis (no_types) dual_comp eq_ext' fp2 ofp_c ofp_d ofp_invol)\nlemma fp4: \"Int_2 \\<I> \\<Longrightarrow> (\\<B>\\<^sup>d)\\<^sup>f\\<^sup>p \\<^bold>\\<equiv> \\<C>\" by (smt dimp_def equal_op_def fp3)\nlemma fp5: \"Int_2 \\<I> \\<Longrightarrow> \\<F>\\<^sup>f\\<^sup>p \\<^bold>\\<equiv> \\<B> \\<^bold>\\<squnion> (\\<C>\\<^sup>c)\" by (smt BC_rel Br_cl_def CF_rel Cl_fr_def FI2 Fr_2_def compl_def dimp_def eq_ext' equal_op_def join_def meet_def)\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: \"Int_4 \\<I> \\<Longrightarrow> \\<forall>A. Op(\\<I> A)\" by (simp add: IDEM_def)\nlemma Cl_Closed: \"Int_4 \\<I> \\<Longrightarrow> \\<forall>A. Cl(\\<C> A)\" using IC4 IDEM_def by blast\nlemma Br_Border: \"Int_1a \\<I> \\<Longrightarrow> \\<forall>A. Br(\\<B> A)\" by (metis Br_int_def MONO_MULTa MONO_def diff_def)\n(**In contrast, there is no analogous fixed-point result for frontier:*)\nlemma \"\\<II> \\<I> \\<Longrightarrow> \\<forall>A. Fr(\\<F> A)\" nitpick oops (*counterexample even if assuming all interior conditions*)\n\nlemma OpCldual: \"\\<forall>A. Cl A \\<longleftrightarrow> Op(\\<^bold>\\<midarrow>A)\" by (simp add: fp_d)\nlemma ClOpdual: \"\\<forall>A. Op A \\<longleftrightarrow> Cl(\\<^bold>\\<midarrow>A)\" by (simp add: compl_def dual_def)\nlemma Fr_ClBr: \"Int_2 \\<I> \\<Longrightarrow> \\<forall>A. Fr(A) = (Cl(A) \\<and> Br(A))\" using BF_rel Br_fr_def CF_rel Cl_fr_def eq_ext' join_def meet_def by fastforce\nlemma Cl_F: \"Int_1a \\<I> \\<Longrightarrow> Int_2 \\<I> \\<Longrightarrow> Int_4 \\<I> \\<Longrightarrow> \\<forall>A. Cl(\\<F> A)\" by (metis CF_rel Cl_fr_def FI4 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/interior_algebra.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8872045937171067, "lm_q2_score": 0.819893340314393, "lm_q1q2_score": 0.7274131378849925}}
{"text": "(*  Title:       Adjunction\n    Author:      Eugene W. Stark <stark@cs.stonybrook.edu>, 2016\n    Maintainer:  Eugene W. Stark <stark@cs.stonybrook.edu>\n*)\n\nchapter Adjunction\n\ntheory Adjunction\nimports Yoneda\nbegin\n\n  text\\<open>\n    This theory defines the notions of adjoint functor and adjunction in various\n    ways and establishes their equivalence.\n    The notions ``left adjoint functor'' and ``right adjoint functor'' are defined\n    in terms of universal arrows.\n    ``Meta-adjunctions'' are defined in terms of natural bijections between hom-sets,\n    where the notion of naturality is axiomatized directly.\n    ``Hom-adjunctions'' formalize the notion of adjunction in terms of natural\n    isomorphisms of hom-functors.\n    ``Unit-counit adjunctions'' define adjunctions in terms of functors equipped\n    with unit and counit natural transformations that satisfy the usual\n    ``triangle identities.''\n    The \\<open>adjunction\\<close> locale is defined as the grand unification of all the\n    definitions, and includes formulas that connect the data from each of them.\n    It is shown that each of the definitions induces an interpretation of the\n    \\<open>adjunction\\<close> locale, so that all the definitions are essentially equivalent.\n    Finally, it is shown that right adjoint functors are unique up to natural\n    isomorphism.\n\n    The reference \\<^cite>\\<open>\"Wikipedia-Adjoint-Functors\"\\<close> was useful in constructing this theory.\n\\<close>\n\n  section \"Left Adjoint Functor\"\n\n  text\\<open>\n    ``@{term e} is an arrow from @{term \"F x\"} to @{term y}.''\n\\<close>\n\n  locale arrow_from_functor =\n    C: category C +\n    D: category D +\n    F: \"functor\" D C F\n    for D :: \"'d comp\"     (infixr \"\\<cdot>\\<^sub>D\" 55)\n    and C :: \"'c comp\"     (infixr \"\\<cdot>\\<^sub>C\" 55)\n    and F :: \"'d \\<Rightarrow> 'c\"\n    and x :: 'd\n    and y :: 'c\n    and e :: 'c +\n    assumes arrow: \"D.ide x \\<and> C.in_hom e (F x) y\"\n  begin\n\n    notation C.in_hom      (\"\\<guillemotleft>_ : _ \\<rightarrow>\\<^sub>C _\\<guillemotright>\")\n    notation D.in_hom      (\"\\<guillemotleft>_ : _ \\<rightarrow>\\<^sub>D _\\<guillemotright>\")\n\n    text\\<open>\n      ``@{term g} is a @{term[source=true] D}-coextension of @{term f} along @{term e}.''\n\\<close>\n\n    definition is_coext :: \"'d \\<Rightarrow> 'c \\<Rightarrow> 'd \\<Rightarrow> bool\"\n    where \"is_coext x' f g \\<equiv> \\<guillemotleft>g : x' \\<rightarrow>\\<^sub>D x\\<guillemotright> \\<and> f = e \\<cdot>\\<^sub>C F g\"\n\n  end\n\n  text\\<open>\n    ``@{term e} is a terminal arrow from @{term \"F x\"} to @{term y}.''\n\\<close>\n\n  locale terminal_arrow_from_functor =\n    arrow_from_functor D C F x y e\n    for D :: \"'d comp\"     (infixr \"\\<cdot>\\<^sub>D\" 55)\n    and C :: \"'c comp\"     (infixr \"\\<cdot>\\<^sub>C\" 55)\n    and F :: \"'d \\<Rightarrow> 'c\"\n    and x :: 'd\n    and y :: 'c\n    and e :: 'c +\n    assumes is_terminal: \"arrow_from_functor D C F x' y f \\<Longrightarrow> (\\<exists>!g. is_coext x' f g)\"\n  begin\n\n    definition the_coext :: \"'d \\<Rightarrow> 'c \\<Rightarrow> 'd\"\n    where \"the_coext x' f = (THE g. is_coext x' f g)\"\n\n    lemma the_coext_prop:\n    assumes \"arrow_from_functor D C F x' y f\"\n    shows \"\\<guillemotleft>the_coext x' f : x' \\<rightarrow>\\<^sub>D x\\<guillemotright>\" and \"f = e \\<cdot>\\<^sub>C F (the_coext x' f)\"\n      by (metis assms is_coext_def is_terminal the_coext_def the_equality)+\n\n    lemma the_coext_unique:\n    assumes \"arrow_from_functor D C F x' y f\" and \"is_coext x' f g\"\n    shows \"g = the_coext x' f\"\n      using assms is_terminal the_coext_def the_equality by metis\n\n  end\n\n  text\\<open>\n    A left adjoint functor is a functor \\<open>F: D \\<rightarrow> C\\<close>\n    that enjoys the following universal coextension property: for each object\n    @{term y} of @{term C} there exists an object @{term x} of @{term D} and an\n    arrow \\<open>e \\<in> C.hom (F x) y\\<close> such that for any arrow\n    \\<open>f \\<in> C.hom (F x') y\\<close> there exists a unique \\<open>g \\<in> D.hom x' x\\<close>\n    such that @{term \"f = C e (F g)\"}.\n\\<close>\n\n  locale left_adjoint_functor =\n    C: category C +\n    D: category D +\n    \"functor\" D C F\n    for D :: \"'d comp\"     (infixr \"\\<cdot>\\<^sub>D\" 55)\n    and C :: \"'c comp\"     (infixr \"\\<cdot>\\<^sub>C\" 55)\n    and F :: \"'d \\<Rightarrow> 'c\" +\n    assumes ex_terminal_arrow: \"C.ide y \\<Longrightarrow> (\\<exists>x e. terminal_arrow_from_functor D C F x y e)\"\n  begin\n\n    notation C.in_hom      (\"\\<guillemotleft>_ : _ \\<rightarrow>\\<^sub>C _\\<guillemotright>\")\n    notation D.in_hom      (\"\\<guillemotleft>_ : _ \\<rightarrow>\\<^sub>D _\\<guillemotright>\")\n\n  end\n\n  section \"Right Adjoint Functor\"\n\n  text\\<open>\n    ``@{term e} is an arrow from @{term x} to @{term \"G y\"}.''\n\\<close>\n\n  locale arrow_to_functor =\n    C: category C +\n    D: category D +\n    G: \"functor\" C D G\n    for C :: \"'c comp\"     (infixr \"\\<cdot>\\<^sub>C\" 55)\n    and D :: \"'d comp\"     (infixr \"\\<cdot>\\<^sub>D\" 55)\n    and G :: \"'c \\<Rightarrow> 'd\"\n    and x :: 'd\n    and y :: 'c\n    and e :: 'd +\n    assumes arrow: \"C.ide y \\<and> D.in_hom e x (G y)\"\n  begin\n\n    notation C.in_hom      (\"\\<guillemotleft>_ : _ \\<rightarrow>\\<^sub>C _\\<guillemotright>\")\n    notation D.in_hom      (\"\\<guillemotleft>_ : _ \\<rightarrow>\\<^sub>D _\\<guillemotright>\")\n\n    text\\<open>\n      ``@{term f} is a @{term[source=true] C}-extension of @{term g} along @{term e}.''\n\\<close>\n\n    definition is_ext :: \"'c \\<Rightarrow> 'd \\<Rightarrow> 'c \\<Rightarrow> bool\"\n    where \"is_ext y' g f \\<equiv> \\<guillemotleft>f : y \\<rightarrow>\\<^sub>C y'\\<guillemotright> \\<and> g = G f \\<cdot>\\<^sub>D e\"\n\n  end\n\n  text\\<open>\n    ``@{term e} is an initial arrow from @{term x} to @{term \"G y\"}.''\n\\<close>\n\n  locale initial_arrow_to_functor =\n    arrow_to_functor C D G x y e\n    for C :: \"'c comp\"     (infixr \"\\<cdot>\\<^sub>C\" 55)\n    and D :: \"'d comp\"     (infixr \"\\<cdot>\\<^sub>D\" 55)\n    and G :: \"'c \\<Rightarrow> 'd\"\n    and x :: 'd\n    and y :: 'c\n    and e :: 'd +\n    assumes is_initial: \"arrow_to_functor C D G x y' g \\<Longrightarrow> (\\<exists>!f. is_ext y' g f)\"\n  begin\n\n    definition the_ext :: \"'c \\<Rightarrow> 'd \\<Rightarrow> 'c\"\n    where \"the_ext y' g = (THE f. is_ext y' g f)\"\n\n    lemma the_ext_prop:\n    assumes \"arrow_to_functor C D G x y' g\"\n    shows \"\\<guillemotleft>the_ext y' g : y \\<rightarrow>\\<^sub>C y'\\<guillemotright>\" and \"g = G (the_ext y' g) \\<cdot>\\<^sub>D e\"\n      by (metis assms is_initial is_ext_def the_equality the_ext_def)+\n\n    lemma the_ext_unique:\n    assumes \"arrow_to_functor C D G x y' g\" and \"is_ext y' g f\"\n    shows \"f = the_ext y' g\"\n      using assms is_initial the_ext_def the_equality by metis\n\n  end\n\n  text\\<open>\n    A right adjoint functor is a functor \\<open>G: C \\<rightarrow> D\\<close>\n    that enjoys the following universal extension property:\n    for each object @{term x} of @{term D} there exists an object @{term y} of @{term C}\n    and an arrow \\<open>e \\<in> D.hom x (G y)\\<close> such that for any arrow\n    \\<open>g \\<in> D.hom x (G y')\\<close> there exists a unique \\<open>f \\<in> C.hom y y'\\<close>\n    such that @{term \"h = D e (G f)\"}.\n\\<close>\n\n  locale right_adjoint_functor =\n    C: category C +\n    D: category D +\n    \"functor\" C D G\n    for C :: \"'c comp\"     (infixr \"\\<cdot>\\<^sub>C\" 55)\n    and D :: \"'d comp\"     (infixr \"\\<cdot>\\<^sub>D\" 55)\n    and G :: \"'c \\<Rightarrow> 'd\" +\n    assumes initial_arrows_exist: \"D.ide x \\<Longrightarrow> (\\<exists>y e. initial_arrow_to_functor C D G x y e)\"\n  begin\n\n    notation C.in_hom      (\"\\<guillemotleft>_ : _ \\<rightarrow>\\<^sub>C _\\<guillemotright>\")\n    notation D.in_hom      (\"\\<guillemotleft>_ : _ \\<rightarrow>\\<^sub>D _\\<guillemotright>\")\n\n  end\n\n  section \"Various Definitions of Adjunction\"\n\n  subsection \"Meta-Adjunction\"\n\n  text\\<open>\n    A ``meta-adjunction'' consists of a functor \\<open>F: D \\<rightarrow> C\\<close>,\n    a functor \\<open>G: C \\<rightarrow> D\\<close>, and for each object @{term x}\n    of @{term C} and @{term y} of @{term D} a bijection between\n    \\<open>C.hom (F y) x\\<close> to \\<open>D.hom y (G x)\\<close> which is natural in @{term x}\n    and @{term y}.  The naturality is easy to express at the meta-level without having\n    to resort to the formal baggage of ``set category,'' ``hom-functor,''\n    and ``natural isomorphism,'' hence the name.\n\\<close>\n\n  locale meta_adjunction =\n    C: category C +\n    D: category D +\n    F: \"functor\" D C F +\n    G: \"functor\" C D G\n    for C :: \"'c comp\"     (infixr \"\\<cdot>\\<^sub>C\" 55)\n    and D :: \"'d comp\"     (infixr \"\\<cdot>\\<^sub>D\" 55)\n    and F :: \"'d \\<Rightarrow> 'c\"\n    and G :: \"'c \\<Rightarrow> 'd\"\n    and \\<phi> :: \"'d \\<Rightarrow> 'c \\<Rightarrow> 'd\"\n    and \\<psi> :: \"'c \\<Rightarrow> 'd \\<Rightarrow> 'c\" +\n    assumes \\<phi>_in_hom: \"\\<lbrakk> D.ide y; C.in_hom f (F y) x \\<rbrakk> \\<Longrightarrow> D.in_hom (\\<phi> y f) y (G x)\"\n    and \\<psi>_in_hom: \"\\<lbrakk> C.ide x; D.in_hom g y (G x) \\<rbrakk> \\<Longrightarrow> C.in_hom (\\<psi> x g) (F y) x\"\n    and \\<psi>_\\<phi>: \"\\<lbrakk> D.ide y; C.in_hom f (F y) x \\<rbrakk> \\<Longrightarrow> \\<psi> x (\\<phi> y f) = f\"\n    and \\<phi>_\\<psi>: \"\\<lbrakk> C.ide x; D.in_hom g y (G x) \\<rbrakk> \\<Longrightarrow> \\<phi> y (\\<psi> x g) = g\"\n    and \\<phi>_naturality: \"\\<lbrakk> C.in_hom f x x'; D.in_hom g y' y; C.in_hom h (F y) x \\<rbrakk> \\<Longrightarrow>\n                         \\<phi> y' (f \\<cdot>\\<^sub>C h \\<cdot>\\<^sub>C F g) = G f \\<cdot>\\<^sub>D \\<phi> y h \\<cdot>\\<^sub>D g\"\n  begin\n\n    notation C.in_hom (\"\\<guillemotleft>_ : _ \\<rightarrow>\\<^sub>C _\\<guillemotright>\")\n    notation D.in_hom (\"\\<guillemotleft>_ : _ \\<rightarrow>\\<^sub>D _\\<guillemotright>\")\n\n    text\\<open>\n      The naturality of @{term \\<psi>} is a consequence of the naturality of @{term \\<phi>}\n      and the other assumptions.\n\\<close>\n\n    lemma \\<psi>_naturality:\n    assumes f: \"\\<guillemotleft>f : x \\<rightarrow>\\<^sub>C x'\\<guillemotright>\" and g: \"\\<guillemotleft>g : y' \\<rightarrow>\\<^sub>D y\\<guillemotright>\" and h: \"\\<guillemotleft>h : y \\<rightarrow>\\<^sub>D G x\\<guillemotright>\"\n    shows \"f \\<cdot>\\<^sub>C \\<psi> x h \\<cdot>\\<^sub>C F g = \\<psi> x' (G f \\<cdot>\\<^sub>D h \\<cdot>\\<^sub>D g)\"\n      using f g h \\<phi>_naturality \\<psi>_in_hom C.ide_dom D.ide_dom D.in_homE \\<phi>_\\<psi> \\<psi>_\\<phi>\n      by (metis C.comp_in_homI' F.preserves_hom C.in_homE D.in_homE)\n\n    lemma respects_natural_isomorphism:\n    assumes \"natural_isomorphism D C F' F \\<tau>\" and \"natural_isomorphism C D G G' \\<mu>\"\n    shows \"meta_adjunction C D F' G'\n             (\\<lambda>y f. \\<mu> (C.cod f) \\<cdot>\\<^sub>D \\<phi> y (f \\<cdot>\\<^sub>C inverse_transformation.map D C F \\<tau> y))\n             (\\<lambda>x g. \\<psi> x ((inverse_transformation.map C D G' \\<mu> x) \\<cdot>\\<^sub>D g) \\<cdot>\\<^sub>C \\<tau> (D.dom g))\"\n    proof -\n      interpret \\<tau>: natural_isomorphism D C F' F \\<tau>\n        using assms(1) by simp\n      interpret \\<tau>': inverse_transformation D C F' F \\<tau>\n        ..\n      interpret \\<mu>: natural_isomorphism C D G G' \\<mu>\n        using assms(2) by simp\n      interpret \\<mu>': inverse_transformation C D G G' \\<mu>\n        ..\n      let ?\\<phi>' = \"\\<lambda>y f. \\<mu> (C.cod f) \\<cdot>\\<^sub>D \\<phi> y (f \\<cdot>\\<^sub>C \\<tau>'.map y)\"\n      let ?\\<psi>' = \"\\<lambda>x g. \\<psi> x (\\<mu>'.map x \\<cdot>\\<^sub>D g) \\<cdot>\\<^sub>C \\<tau> (D.dom g)\"\n      show \"meta_adjunction C D F' G' ?\\<phi>' ?\\<psi>'\"\n      proof\n        show \"\\<And>y f x. \\<lbrakk>D.ide y; \\<guillemotleft>f : F' y \\<rightarrow>\\<^sub>C x\\<guillemotright>\\<rbrakk>\n                         \\<Longrightarrow> \\<guillemotleft>\\<mu> (C.cod f) \\<cdot>\\<^sub>D \\<phi> y (f \\<cdot>\\<^sub>C \\<tau>'.map y) : y \\<rightarrow>\\<^sub>D G' x\\<guillemotright>\"\n        proof -\n          fix x y f\n          assume y: \"D.ide y\" and f: \"\\<guillemotleft>f : F' y \\<rightarrow>\\<^sub>C x\\<guillemotright>\"\n          show \"\\<guillemotleft>\\<mu> (C.cod f) \\<cdot>\\<^sub>D \\<phi> y (f \\<cdot>\\<^sub>C \\<tau>'.map y) : y \\<rightarrow>\\<^sub>D G' x\\<guillemotright>\"\n          proof (intro D.comp_in_homI)\n            show \"\\<guillemotleft>\\<mu> (C.cod f) : G x \\<rightarrow>\\<^sub>D G' x\\<guillemotright>\"\n              using f by fastforce\n            show \"\\<guillemotleft>\\<phi> y (f \\<cdot>\\<^sub>C \\<tau>'.map y) : y \\<rightarrow>\\<^sub>D G x\\<guillemotright>\"\n              using f y \\<phi>_in_hom by auto\n          qed\n        qed\n        show \"\\<And>x g y. \\<lbrakk>C.ide x; \\<guillemotleft>g : y \\<rightarrow>\\<^sub>D G' x\\<guillemotright>\\<rbrakk>\n                         \\<Longrightarrow> \\<guillemotleft>\\<psi> x (\\<mu>'.map x \\<cdot>\\<^sub>D g) \\<cdot>\\<^sub>C \\<tau> (D.dom g) : F' y \\<rightarrow>\\<^sub>C x\\<guillemotright>\"\n        proof -\n          fix x y g\n          assume x: \"C.ide x\" and g: \"\\<guillemotleft>g : y \\<rightarrow>\\<^sub>D G' x\\<guillemotright>\"\n          show \"\\<guillemotleft>\\<psi> x (\\<mu>'.map x \\<cdot>\\<^sub>D g) \\<cdot>\\<^sub>C \\<tau> (D.dom g) : F' y \\<rightarrow>\\<^sub>C x\\<guillemotright>\"\n          proof (intro C.comp_in_homI)\n            show \"\\<guillemotleft>\\<tau> (D.dom g) : F' y \\<rightarrow>\\<^sub>C F y\\<guillemotright>\"\n              using g by fastforce\n            show \"\\<guillemotleft>\\<psi> x (\\<mu>'.map x \\<cdot>\\<^sub>D g) : F y \\<rightarrow>\\<^sub>C x\\<guillemotright>\"\n              using x g \\<psi>_in_hom by auto\n          qed\n        qed\n        show \"\\<And>y f x. \\<lbrakk>D.ide y; \\<guillemotleft>f : F' y \\<rightarrow>\\<^sub>C x\\<guillemotright>\\<rbrakk>\n                          \\<Longrightarrow> \\<psi> x (\\<mu>'.map x \\<cdot>\\<^sub>D \\<mu> (C.cod f) \\<cdot>\\<^sub>D \\<phi> y (f \\<cdot>\\<^sub>C \\<tau>'.map y)) \\<cdot>\\<^sub>C\n                                \\<tau> (D.dom (\\<mu> (C.cod f) \\<cdot>\\<^sub>D \\<phi> y (f \\<cdot>\\<^sub>C \\<tau>'.map y))) =\n                              f\"\n        proof -\n          fix x y f\n          assume y: \"D.ide y\" and f: \"\\<guillemotleft>f : F' y \\<rightarrow>\\<^sub>C x\\<guillemotright>\"\n          have 1: \"\\<guillemotleft>\\<phi> y (f \\<cdot>\\<^sub>C \\<tau>'.map y) : y \\<rightarrow>\\<^sub>D G x\\<guillemotright>\"\n            using f y \\<phi>_in_hom by auto\n          show \"\\<psi> x (\\<mu>'.map x \\<cdot>\\<^sub>D \\<mu> (C.cod f) \\<cdot>\\<^sub>D \\<phi> y (f \\<cdot>\\<^sub>C \\<tau>'.map y)) \\<cdot>\\<^sub>C\n                  \\<tau> (D.dom (\\<mu> (C.cod f) \\<cdot>\\<^sub>D \\<phi> y (f \\<cdot>\\<^sub>C \\<tau>'.map y))) =\n                f\"\n          proof -\n            have \"\\<psi> x (\\<mu>'.map x \\<cdot>\\<^sub>D \\<mu> (C.cod f) \\<cdot>\\<^sub>D \\<phi> y (f \\<cdot>\\<^sub>C \\<tau>'.map y)) \\<cdot>\\<^sub>C\n                    \\<tau> (D.dom (\\<mu> (C.cod f) \\<cdot>\\<^sub>D \\<phi> y (f \\<cdot>\\<^sub>C \\<tau>'.map y))) =\n                  \\<psi> x ((\\<mu>'.map x \\<cdot>\\<^sub>D \\<mu> (C.cod f)) \\<cdot>\\<^sub>D \\<phi> y (f \\<cdot>\\<^sub>C \\<tau>'.map y)) \\<cdot>\\<^sub>C\n                    \\<tau> (D.dom (\\<mu> (C.cod f) \\<cdot>\\<^sub>D \\<phi> y (f \\<cdot>\\<^sub>C \\<tau>'.map y)))\"\n              using D.comp_assoc by simp\n            also have \"... = \\<psi> x (\\<phi> y (f \\<cdot>\\<^sub>C \\<tau>'.map y)) \\<cdot>\\<^sub>C \\<tau> y\"\n              by (metis \"1\" C.arr_cod C.dom_cod C.ide_cod C.in_homE D.comp_ide_arr D.dom_comp\n                  D.ide_compE D.in_homE D.inverse_arrowsE \\<mu>'.inverts_components \\<mu>.preserves_dom\n                  \\<mu>.preserves_reflects_arr category.seqI f meta_adjunction_axioms\n                  meta_adjunction_def)\n            also have \"... = f\"\n              using f y \\<psi>_\\<phi> C.comp_assoc \\<tau>'.inverts_components [of y] C.comp_arr_dom\n              by fastforce\n            finally show ?thesis by blast\n          qed\n        qed\n        show \"\\<And>x g y. \\<lbrakk>C.ide x; \\<guillemotleft>g : y \\<rightarrow>\\<^sub>D G' x\\<guillemotright>\\<rbrakk>\n                         \\<Longrightarrow> \\<mu> (C.cod (\\<psi> x (\\<mu>'.map x \\<cdot>\\<^sub>D g) \\<cdot>\\<^sub>C \\<tau> (D.dom g))) \\<cdot>\\<^sub>D\n                               \\<phi> y ((\\<psi> x (\\<mu>'.map x \\<cdot>\\<^sub>D g) \\<cdot>\\<^sub>C \\<tau> (D.dom g)) \\<cdot>\\<^sub>C \\<tau>'.map y) =\n                             g\"\n        proof -\n          fix x y g\n          assume x: \"C.ide x\" and g: \"\\<guillemotleft>g : y \\<rightarrow>\\<^sub>D G' x\\<guillemotright>\"\n          have 1: \"\\<guillemotleft>\\<psi> x (\\<mu>'.map x \\<cdot>\\<^sub>D g) : F y \\<rightarrow>\\<^sub>C x\\<guillemotright>\"\n            using x g \\<psi>_in_hom by auto\n          show \"\\<mu> (C.cod (\\<psi> x (\\<mu>'.map x \\<cdot>\\<^sub>D g) \\<cdot>\\<^sub>C \\<tau> (D.dom g))) \\<cdot>\\<^sub>D\n                  \\<phi> y ((\\<psi> x (\\<mu>'.map x \\<cdot>\\<^sub>D g) \\<cdot>\\<^sub>C \\<tau> (D.dom g)) \\<cdot>\\<^sub>C \\<tau>'.map y) =\n                g\"\n          proof -\n            have \"\\<mu> (C.cod (\\<psi> x (\\<mu>'.map x \\<cdot>\\<^sub>D g) \\<cdot>\\<^sub>C \\<tau> (D.dom g))) \\<cdot>\\<^sub>D\n                    \\<phi> y ((\\<psi> x (\\<mu>'.map x \\<cdot>\\<^sub>D g) \\<cdot>\\<^sub>C \\<tau> (D.dom g)) \\<cdot>\\<^sub>C \\<tau>'.map y) =\n                  \\<mu> (C.cod (\\<psi> x (\\<mu>'.map x \\<cdot>\\<^sub>D g) \\<cdot>\\<^sub>C \\<tau> (D.dom g))) \\<cdot>\\<^sub>D\n                    \\<phi> y (\\<psi> x (\\<mu>'.map x \\<cdot>\\<^sub>D g) \\<cdot>\\<^sub>C \\<tau> (D.dom g) \\<cdot>\\<^sub>C \\<tau>'.map y)\"\n              using C.comp_assoc by simp\n            also have \"... = \\<mu> x \\<cdot>\\<^sub>D \\<phi> y (\\<psi> x (\\<mu>'.map x \\<cdot>\\<^sub>D g))\"\n              using 1 C.comp_arr_dom C.comp_arr_inv' g by fastforce\n            also have \"... = (\\<mu> x \\<cdot>\\<^sub>D \\<mu>'.map x) \\<cdot>\\<^sub>D g\"\n              using x g \\<phi>_\\<psi> D.comp_assoc by auto\n            also have \"... = g\"\n              using x g \\<mu>'.inverts_components [of x] D.comp_cod_arr by fastforce\n            finally show ?thesis by blast\n          qed\n        qed\n        show \"\\<And>f x x' g y' y h. \\<lbrakk>\\<guillemotleft>f : x \\<rightarrow>\\<^sub>C x'\\<guillemotright>; \\<guillemotleft>g : y' \\<rightarrow>\\<^sub>D y\\<guillemotright>; \\<guillemotleft>h : F' y \\<rightarrow>\\<^sub>C x\\<guillemotright>\\<rbrakk>\n                  \\<Longrightarrow> \\<mu> (C.cod (f \\<cdot>\\<^sub>C h \\<cdot>\\<^sub>C F' g)) \\<cdot>\\<^sub>D \\<phi> y' ((f \\<cdot>\\<^sub>C h \\<cdot>\\<^sub>C F' g) \\<cdot>\\<^sub>C \\<tau>'.map y') =\n                      G' f \\<cdot>\\<^sub>D (\\<mu> (C.cod h) \\<cdot>\\<^sub>D \\<phi> y (h \\<cdot>\\<^sub>C \\<tau>'.map y)) \\<cdot>\\<^sub>D g\"\n        proof -\n          fix x y x' y' f g h\n          assume f: \"\\<guillemotleft>f : x \\<rightarrow>\\<^sub>C x'\\<guillemotright>\" and g: \"\\<guillemotleft>g : y' \\<rightarrow>\\<^sub>D y\\<guillemotright>\" and h: \"\\<guillemotleft>h : F' y \\<rightarrow>\\<^sub>C x\\<guillemotright>\"\n          show \"\\<mu> (C.cod (f \\<cdot>\\<^sub>C h \\<cdot>\\<^sub>C F' g)) \\<cdot>\\<^sub>D \\<phi> y' ((f \\<cdot>\\<^sub>C h \\<cdot>\\<^sub>C F' g) \\<cdot>\\<^sub>C \\<tau>'.map y') =\n                G' f \\<cdot>\\<^sub>D (\\<mu> (C.cod h) \\<cdot>\\<^sub>D \\<phi> y (h \\<cdot>\\<^sub>C \\<tau>'.map y)) \\<cdot>\\<^sub>D g\"\n          proof -\n            have \"\\<mu> (C.cod (f \\<cdot>\\<^sub>C h \\<cdot>\\<^sub>C F' g)) \\<cdot>\\<^sub>D \\<phi> y' ((f \\<cdot>\\<^sub>C h \\<cdot>\\<^sub>C F' g) \\<cdot>\\<^sub>C \\<tau>'.map y') =\n                  \\<mu> x' \\<cdot>\\<^sub>D \\<phi> y' ((f \\<cdot>\\<^sub>C h \\<cdot>\\<^sub>C F' g) \\<cdot>\\<^sub>C \\<tau>'.map y')\"\n              using f g h by fastforce\n            also have \"... = \\<mu> x' \\<cdot>\\<^sub>D \\<phi> y' (f \\<cdot>\\<^sub>C (h \\<cdot>\\<^sub>C \\<tau>'.map y) \\<cdot>\\<^sub>C F g)\"\n              using g \\<tau>'.naturality C.comp_assoc by auto\n            also have \"... = (\\<mu> x' \\<cdot>\\<^sub>D G f) \\<cdot>\\<^sub>D \\<phi> y (h \\<cdot>\\<^sub>C \\<tau>'.map y) \\<cdot>\\<^sub>D g\"\n              using f g h \\<phi>_naturality [of f x x' g y' y \"h \\<cdot>\\<^sub>C \\<tau>'.map y\"] D.comp_assoc\n              by fastforce\n            also have \"... = (G' f \\<cdot>\\<^sub>D \\<mu> x) \\<cdot>\\<^sub>D \\<phi> y (h \\<cdot>\\<^sub>C \\<tau>'.map y) \\<cdot>\\<^sub>D g\"\n              using f \\<mu>.naturality by auto\n            also have \"... = G' f \\<cdot>\\<^sub>D (\\<mu> (C.cod h) \\<cdot>\\<^sub>D \\<phi> y (h \\<cdot>\\<^sub>C \\<tau>'.map y)) \\<cdot>\\<^sub>D g\"\n              using h D.comp_assoc by auto\n            finally show ?thesis by blast\n          qed\n        qed\n      qed\n    qed\n\n  end\n\n  subsection \"Hom-Adjunction\"\n\n  text\\<open>\n    The bijection between hom-sets that defines an adjunction can be represented\n    formally as a natural isomorphism of hom-functors.  However, stating the definition\n    this way is more complex than was the case for \\<open>meta_adjunction\\<close>.\n    One reason is that we need to have a ``set category'' that is suitable as\n    a target category for the hom-functors, and since the arrows of the categories\n    @{term C} and @{term D} will in general have distinct types, we need a set category\n    that simultaneously embeds both.  Another reason is that we simply have to formally\n    construct the various categories and functors required to express the definition.\n\n    This is a good place to point out that I have often included more sublocales\n    in a locale than are strictly required.  The main reason for this is the fact that\n    the locale system in Isabelle only gives one name to each entity introduced by\n    a locale: the name that it has in the first locale in which it occurs.\n    This means that entities that make their first appearance deeply nested in sublocales\n    will have to be referred to by long qualified names that can be difficult to\n    understand, or even to discover.  To counteract this, I have typically introduced\n    sublocales before the superlocales that contain them to ensure that the entities\n    in the sublocales can be referred to by short meaningful (and predictable) names.\n    In my opinion, though, it would be better if the locale system would make entities\n    that occur in multiple locales accessible by \\emph{all} possible qualified names,\n    so that the most perspicuous name could be used in any particular context.\n\\<close>\n\n  locale hom_adjunction =\n    C: category C +\n    D: category D +\n    S: set_category S setp +\n    Cop: dual_category C +\n    Dop: dual_category D +\n    CopxC: product_category Cop.comp C +\n    DopxD: product_category Dop.comp D +\n    DopxC: product_category Dop.comp C +\n    F: \"functor\" D C F +\n    G: \"functor\" C D G +\n    HomC: hom_functor C S setp \\<phi>C +\n    HomD: hom_functor D S setp \\<phi>D +\n    Fop: dual_functor Dop.comp Cop.comp F +\n    FopxC: product_functor Dop.comp C Cop.comp C Fop.map C.map +\n    DopxG: product_functor Dop.comp C Dop.comp D Dop.map G +\n    Hom_FopxC: composite_functor DopxC.comp CopxC.comp S FopxC.map HomC.map +\n    Hom_DopxG: composite_functor DopxC.comp DopxD.comp S DopxG.map HomD.map +\n    Hom_FopxC: set_valued_functor DopxC.comp S setp Hom_FopxC.map +\n    Hom_DopxG: set_valued_functor DopxC.comp S setp Hom_DopxG.map +\n    \\<Phi>: set_valued_transformation DopxC.comp S setp Hom_FopxC.map Hom_DopxG.map \\<Phi> +\n    \\<Psi>: set_valued_transformation DopxC.comp S setp Hom_DopxG.map Hom_FopxC.map \\<Psi> +\n    \\<Phi>\\<Psi>: inverse_transformations DopxC.comp S Hom_FopxC.map Hom_DopxG.map \\<Phi> \\<Psi>\n    for C :: \"'c comp\"     (infixr \"\\<cdot>\\<^sub>C\" 55)\n    and D :: \"'d comp\"     (infixr \"\\<cdot>\\<^sub>D\" 55)\n    and S :: \"'s comp\"     (infixr \"\\<cdot>\\<^sub>S\" 55)\n    and setp :: \"'s set \\<Rightarrow> bool\"\n    and \\<phi>C :: \"'c * 'c \\<Rightarrow> 'c \\<Rightarrow> 's\"\n    and \\<phi>D :: \"'d * 'd \\<Rightarrow> 'd \\<Rightarrow> 's\"\n    and F :: \"'d \\<Rightarrow> 'c\"\n    and G :: \"'c \\<Rightarrow> 'd\"\n    and \\<Phi> :: \"'d * 'c \\<Rightarrow> 's\"\n    and \\<Psi> :: \"'d * 'c \\<Rightarrow> 's\"\n  begin\n\n    notation C.in_hom      (\"\\<guillemotleft>_ : _ \\<rightarrow>\\<^sub>C _\\<guillemotright>\")\n    notation D.in_hom      (\"\\<guillemotleft>_ : _ \\<rightarrow>\\<^sub>D _\\<guillemotright>\")\n\n    abbreviation \\<psi>C :: \"'c * 'c \\<Rightarrow> 's \\<Rightarrow> 'c\"\n    where \"\\<psi>C \\<equiv> HomC.\\<psi>\"\n\n    abbreviation \\<psi>D :: \"'d * 'd \\<Rightarrow> 's \\<Rightarrow> 'd\"\n    where \"\\<psi>D \\<equiv> HomD.\\<psi>\"\n\n  end\n\n  subsection \"Unit/Counit Adjunction\"\n\n  text\\<open>\n    Expressed in unit/counit terms, an adjunction consists of functors\n    \\<open>F: D \\<rightarrow> C\\<close> and \\<open>G: C \\<rightarrow> D\\<close>, equipped with natural transformations\n    \\<open>\\<eta>: 1 \\<rightarrow> GF\\<close> and \\<open>\\<epsilon>: FG \\<rightarrow> 1\\<close> satisfying certain ``triangle identities''.\n\\<close>\n\n  locale unit_counit_adjunction =\n    C: category C +\n    D: category D +\n    F: \"functor\" D C F +\n    G: \"functor\" C D G +\n    GF: composite_functor D C D F G +\n    FG: composite_functor C D C G F +\n    FGF: composite_functor D C C F \\<open>F o G\\<close> +\n    GFG: composite_functor C D D G \\<open>G o F\\<close> +\n    \\<eta>: natural_transformation D D D.map \\<open>G o F\\<close> \\<eta> +\n    \\<epsilon>: natural_transformation C C \\<open>F o G\\<close> C.map \\<epsilon> +\n    F\\<eta>: natural_transformation D C F \\<open>F o G o F\\<close> \\<open>F o \\<eta>\\<close> +\n    \\<eta>G: natural_transformation C D G \\<open>G o F o G\\<close> \\<open>\\<eta> o G\\<close> +\n    \\<epsilon>F: natural_transformation D C \\<open>F o G o F\\<close> F \\<open>\\<epsilon> o F\\<close> +\n    G\\<epsilon>: natural_transformation C D \\<open>G o F o G\\<close> G \\<open>G o \\<epsilon>\\<close> +\n    \\<epsilon>FoF\\<eta>: vertical_composite D C F \\<open>F o G o F\\<close> F \\<open>F o \\<eta>\\<close> \\<open>\\<epsilon> o F\\<close> +\n    G\\<epsilon>o\\<eta>G: vertical_composite C D G \\<open>G o F o G\\<close> G \\<open>\\<eta> o G\\<close> \\<open>G o \\<epsilon>\\<close>\n    for C :: \"'c comp\"     (infixr \"\\<cdot>\\<^sub>C\" 55)\n    and D :: \"'d comp\"     (infixr \"\\<cdot>\\<^sub>D\" 55)\n    and F :: \"'d \\<Rightarrow> 'c\"\n    and G :: \"'c \\<Rightarrow> 'd\"\n    and \\<eta> :: \"'d \\<Rightarrow> 'd\"\n    and \\<epsilon> :: \"'c \\<Rightarrow> 'c\" +\n    assumes triangle_F: \"\\<epsilon>FoF\\<eta>.map = F\"\n    and triangle_G: \"G\\<epsilon>o\\<eta>G.map = G\"\n  begin\n\n    notation C.in_hom      (\"\\<guillemotleft>_ : _ \\<rightarrow>\\<^sub>C _\\<guillemotright>\")\n    notation D.in_hom      (\"\\<guillemotleft>_ : _ \\<rightarrow>\\<^sub>D _\\<guillemotright>\")\n\n  end\n\n  lemma unit_determines_counit:\n  assumes \"unit_counit_adjunction C D F G \\<eta> \\<epsilon>\"\n  and \"unit_counit_adjunction C D F G \\<eta> \\<epsilon>'\"\n  shows \"\\<epsilon> = \\<epsilon>'\"\n  proof -\n    (* IDEA:  \\<epsilon>' = \\<epsilon>'FG o (FG\\<epsilon> o F\\<eta>G) = \\<epsilon>'\\<epsilon> o F\\<eta>G = \\<epsilon>FG o (\\<epsilon>'FG o F\\<eta>G) = \\<epsilon> *)\n    interpret Adj: unit_counit_adjunction C D F G \\<eta> \\<epsilon> using assms(1) by auto\n    interpret Adj': unit_counit_adjunction C D F G \\<eta> \\<epsilon>' using assms(2) by auto\n    interpret FGFG: composite_functor C D C G \\<open>F o G o F\\<close> ..\n    interpret FG\\<epsilon>: natural_transformation C C \\<open>(F o G) o (F o G)\\<close> \\<open>F o G\\<close> \\<open>(F o G) o \\<epsilon>\\<close>\n      using Adj.\\<epsilon>.natural_transformation_axioms Adj.FG.as_nat_trans.natural_transformation_axioms\n            horizontal_composite\n      by fastforce\n    interpret F\\<eta>G: natural_transformation C C \\<open>F o G\\<close> \\<open>F o G o F o G\\<close> \\<open>F o \\<eta> o G\\<close>\n      using Adj.\\<eta>.natural_transformation_axioms Adj.F\\<eta>.natural_transformation_axioms\n            Adj.G.as_nat_trans.natural_transformation_axioms horizontal_composite\n      by blast\n    interpret \\<epsilon>'\\<epsilon>: natural_transformation C C \\<open>F o G o F o G\\<close> Adj.C.map \\<open>\\<epsilon>' o \\<epsilon>\\<close>\n    proof -\n      have \"natural_transformation C C ((F o G) o (F o G)) Adj.C.map (\\<epsilon>' o \\<epsilon>)\"\n        using Adj.\\<epsilon>.natural_transformation_axioms Adj'.\\<epsilon>.natural_transformation_axioms\n              horizontal_composite Adj.C.is_functor comp_functor_identity\n        by (metis (no_types, lifting))\n      thus \"natural_transformation C C (F o G o F o G) Adj.C.map (\\<epsilon>' o \\<epsilon>)\"\n        using o_assoc by metis\n    qed\n    interpret \\<epsilon>'\\<epsilon>oF\\<eta>G: vertical_composite\n                         C C \\<open>F o G\\<close> \\<open>F o G o F o G\\<close> Adj.C.map \\<open>F o \\<eta> o G\\<close> \\<open>\\<epsilon>' o \\<epsilon>\\<close> ..\n    have \"\\<epsilon>' = vertical_composite.map C C (F o Adj.G\\<epsilon>o\\<eta>G.map) \\<epsilon>'\"\n      using vcomp_ide_dom [of C C \"F o G\" Adj.C.map \\<epsilon>'] Adj.triangle_G\n      by (simp add: Adj'.\\<epsilon>.natural_transformation_axioms)\n    also have \"... = vertical_composite.map C C\n                       (vertical_composite.map C C (F o \\<eta> o G) (F o G o \\<epsilon>)) \\<epsilon>'\"\n      using whisker_left Adj.F.functor_axioms Adj.G\\<epsilon>.natural_transformation_axioms\n            Adj.\\<eta>G.natural_transformation_axioms o_assoc\n      by (metis (no_types, lifting))\n    also have \"... = vertical_composite.map C C\n                       (vertical_composite.map C C (F o \\<eta> o G) (\\<epsilon>' o F o G)) \\<epsilon>\"\n    proof -\n      have \"vertical_composite.map C C\n              (vertical_composite.map C C (F o \\<eta> o G) (F o G o \\<epsilon>)) \\<epsilon>'\n              = vertical_composite.map C C (F o \\<eta> o G)\n                  (vertical_composite.map C C (F o G o \\<epsilon>) \\<epsilon>')\"\n        using vcomp_assoc\n        by (metis (no_types, lifting) Adj'.\\<epsilon>.natural_transformation_axioms\n            FG\\<epsilon>.natural_transformation_axioms F\\<eta>G.natural_transformation_axioms o_assoc)\n      also have \"... = vertical_composite.map C C (F o \\<eta> o G)\n                         (vertical_composite.map C C (\\<epsilon>' o F o G) \\<epsilon>)\"\n        using Adj'.\\<epsilon>.natural_transformation_axioms Adj.\\<epsilon>.natural_transformation_axioms\n              interchange_spc [of C C \"F o G\" Adj.C.map \\<epsilon> C \"F o G\" Adj.C.map \\<epsilon>']\n        by (metis hcomp_ide_cod hcomp_ide_dom o_assoc)\n      also have \"... = vertical_composite.map C C\n                         (vertical_composite.map C C (F o \\<eta> o G) (\\<epsilon>' o F o G)) \\<epsilon>\"\n        using vcomp_assoc\n        by (metis Adj'.\\<epsilon>F.natural_transformation_axioms\n            Adj.G.as_nat_trans.natural_transformation_axioms\n            Adj.\\<epsilon>.natural_transformation_axioms F\\<eta>G.natural_transformation_axioms\n            horizontal_composite)\n      finally show ?thesis by simp\n    qed\n    also have \"... = vertical_composite.map C C\n                       (vertical_composite.map D C (F o \\<eta>) (\\<epsilon>' o F) o G) \\<epsilon>\"\n      using whisker_right Adj'.\\<epsilon>F.natural_transformation_axioms\n            Adj.F\\<eta>.natural_transformation_axioms Adj.G.functor_axioms\n      by metis\n    also have \"... = \\<epsilon>\"\n      using Adj'.triangle_F vcomp_ide_cod Adj.\\<epsilon>.natural_transformation_axioms by simp\n    finally show ?thesis by simp\n  qed\n\n  \n\n  subsection \"Adjunction\"\n\n  text\\<open>\n    The grand unification of everything to do with an adjunction.\n\\<close>\n\n  locale adjunction =\n    C: category C +\n    D: category D +\n    S: set_category S setp +\n    Cop: dual_category C +\n    Dop: dual_category D +\n    CopxC: product_category Cop.comp C +\n    DopxD: product_category Dop.comp D +\n    DopxC: product_category Dop.comp C +\n    idDop: identity_functor Dop.comp +\n    HomC: hom_functor C S setp \\<phi>C +\n    HomD: hom_functor D S setp \\<phi>D +\n    F: left_adjoint_functor D C F +\n    G: right_adjoint_functor C D G +\n    GF: composite_functor D C D F G +\n    FG: composite_functor C D C G F +\n    FGF: composite_functor D C C F FG.map +\n    GFG: composite_functor C D D G GF.map +\n    Fop: dual_functor Dop.comp Cop.comp F +\n    FopxC: product_functor Dop.comp C Cop.comp C Fop.map C.map +\n    DopxG: product_functor Dop.comp C Dop.comp D Dop.map G +\n    Hom_FopxC: composite_functor DopxC.comp CopxC.comp S FopxC.map HomC.map +\n    Hom_DopxG: composite_functor DopxC.comp DopxD.comp S DopxG.map HomD.map +\n    Hom_FopxC: set_valued_functor DopxC.comp S setp Hom_FopxC.map +\n    Hom_DopxG: set_valued_functor DopxC.comp S setp Hom_DopxG.map +\n    \\<eta>: natural_transformation D D D.map GF.map \\<eta> +\n    \\<epsilon>: natural_transformation C C FG.map C.map \\<epsilon> +\n    F\\<eta>: natural_transformation D C F \\<open>F o G o F\\<close> \\<open>F o \\<eta>\\<close> +\n    \\<eta>G: natural_transformation C D G \\<open>G o F o G\\<close> \\<open>\\<eta> o G\\<close> +\n    \\<epsilon>F: natural_transformation D C \\<open>F o G o F\\<close> F \\<open>\\<epsilon> o F\\<close> +\n    G\\<epsilon>: natural_transformation C D \\<open>G o F o G\\<close> G \\<open>G o \\<epsilon>\\<close> +\n    \\<epsilon>FoF\\<eta>: vertical_composite D C F FGF.map F \\<open>F o \\<eta>\\<close> \\<open>\\<epsilon> o F\\<close> +\n    G\\<epsilon>o\\<eta>G: vertical_composite C D G GFG.map G \\<open>\\<eta> o G\\<close> \\<open>G o \\<epsilon>\\<close> +\n    \\<phi>\\<psi>: meta_adjunction C D F G \\<phi> \\<psi> +\n    \\<eta>\\<epsilon>: unit_counit_adjunction C D F G \\<eta> \\<epsilon> +\n    \\<Phi>\\<Psi>: hom_adjunction C D S setp \\<phi>C \\<phi>D F G \\<Phi> \\<Psi>\n    for C :: \"'c comp\"     (infixr \"\\<cdot>\\<^sub>C\" 55)\n    and D :: \"'d comp\"     (infixr \"\\<cdot>\\<^sub>D\" 55)\n    and S :: \"'s comp\"     (infixr \"\\<cdot>\\<^sub>S\" 55)\n    and setp :: \"'s set \\<Rightarrow> bool\"\n    and \\<phi>C :: \"'c * 'c \\<Rightarrow> 'c \\<Rightarrow> 's\"\n    and \\<phi>D :: \"'d * 'd \\<Rightarrow> 'd \\<Rightarrow> 's\"\n    and F :: \"'d \\<Rightarrow> 'c\"\n    and G :: \"'c \\<Rightarrow> 'd\"\n    and \\<phi> :: \"'d \\<Rightarrow> 'c \\<Rightarrow> 'd\"\n    and \\<psi> :: \"'c \\<Rightarrow> 'd \\<Rightarrow> 'c\"\n    and \\<eta> :: \"'d \\<Rightarrow> 'd\"\n    and \\<epsilon> :: \"'c \\<Rightarrow> 'c\"\n    and \\<Phi> :: \"'d * 'c \\<Rightarrow> 's\"\n    and \\<Psi> :: \"'d * 'c \\<Rightarrow> 's\" +\n    assumes \\<phi>_in_terms_of_\\<eta>: \"\\<lbrakk> D.ide y; \\<guillemotleft>f : F y \\<rightarrow>\\<^sub>C x\\<guillemotright> \\<rbrakk> \\<Longrightarrow> \\<phi> y f = G f \\<cdot>\\<^sub>D \\<eta> y\"\n    and \\<psi>_in_terms_of_\\<epsilon>: \"\\<lbrakk> C.ide x; \\<guillemotleft>g : y \\<rightarrow>\\<^sub>D G x\\<guillemotright> \\<rbrakk> \\<Longrightarrow> \\<psi> x g = \\<epsilon> x \\<cdot>\\<^sub>C F g\"\n    and \\<eta>_in_terms_of_\\<phi>: \"D.ide y \\<Longrightarrow> \\<eta> y = \\<phi> y (F y)\"\n    and \\<epsilon>_in_terms_of_\\<psi>: \"C.ide x \\<Longrightarrow> \\<epsilon> x = \\<psi> x (G x)\"\n    and \\<phi>_in_terms_of_\\<Phi>: \"\\<lbrakk> D.ide y; \\<guillemotleft>f : F y \\<rightarrow>\\<^sub>C x\\<guillemotright> \\<rbrakk> \\<Longrightarrow>\n                              \\<phi> y f = (\\<Phi>\\<Psi>.\\<psi>D (y, G x) o S.Fun (\\<Phi> (y, x)) o \\<phi>C (F y, x)) f\"\n    and \\<psi>_in_terms_of_\\<Psi>: \"\\<lbrakk> C.ide x; \\<guillemotleft>g : y \\<rightarrow>\\<^sub>D G x\\<guillemotright> \\<rbrakk> \\<Longrightarrow>\n                              \\<psi> x g = (\\<Phi>\\<Psi>.\\<psi>C (F y, x) o S.Fun (\\<Psi> (y, x)) o \\<phi>D (y, G x)) g\"\n    and \\<Phi>_in_terms_of_\\<phi>:\n           \"\\<lbrakk> C.ide x; D.ide y \\<rbrakk> \\<Longrightarrow>\n                \\<Phi> (y, x) = S.mkArr (HomC.set (F y, x)) (HomD.set (y, G x))\n                                    (\\<phi>D (y, G x) o \\<phi> y o \\<Phi>\\<Psi>.\\<psi>C (F y, x))\"\n    and \\<Psi>_in_terms_of_\\<psi>:\n           \"\\<lbrakk> C.ide x; D.ide y \\<rbrakk> \\<Longrightarrow>\n                \\<Psi> (y, x) = S.mkArr (HomD.set (y, G x)) (HomC.set (F y, x))\n                                    (\\<phi>C (F y, x) o \\<psi> x o \\<Phi>\\<Psi>.\\<psi>D (y, G x))\"\n\n  section \"Meta-Adjunctions Induce Unit/Counit Adjunctions\"\n\n  context meta_adjunction\n  begin\n\n    interpretation GF: composite_functor D C D F G ..\n    interpretation FG: composite_functor C D C G F ..\n    interpretation FGF: composite_functor D C C F FG.map ..\n    interpretation GFG: composite_functor C D D G GF.map ..\n\n    definition \\<eta>o :: \"'d \\<Rightarrow> 'd\"\n    where \"\\<eta>o y = \\<phi> y (F y)\"\n\n    lemma \\<eta>o_in_hom:\n    assumes \"D.ide y\"\n    shows \"\\<guillemotleft>\\<eta>o y : y \\<rightarrow>\\<^sub>D G (F y)\\<guillemotright>\"\n      using assms D.ide_in_hom \\<eta>o_def \\<phi>_in_hom by force\n\n    lemma \\<phi>_in_terms_of_\\<eta>o:\n    assumes \"D.ide y\" and \"\\<guillemotleft>f : F y \\<rightarrow>\\<^sub>C x\\<guillemotright>\"\n    shows \"\\<phi> y f = G f \\<cdot>\\<^sub>D \\<eta>o y\"\n    proof (unfold \\<eta>o_def)\n      have 1: \"\\<guillemotleft>F y : F y \\<rightarrow>\\<^sub>C F y\\<guillemotright>\"\n        using assms(1) D.ide_in_hom by blast\n      hence \"\\<phi> y (F y) = \\<phi> y (F y) \\<cdot>\\<^sub>D y\"\n        by (metis assms(1) D.in_homE \\<phi>_in_hom D.comp_arr_dom)\n      thus \"\\<phi> y f = G f \\<cdot>\\<^sub>D \\<phi> y (F y)\"\n        using assms 1 D.ide_in_hom by (metis C.comp_arr_dom C.in_homE \\<phi>_naturality)\n    qed\n\n    lemma \\<phi>_F_char:\n    assumes \"\\<guillemotleft>g : y' \\<rightarrow>\\<^sub>D y\\<guillemotright>\"\n    shows \"\\<phi> y' (F g) = \\<eta>o y \\<cdot>\\<^sub>D g\"\n      using assms \\<eta>o_def \\<phi>_in_hom [of y \"F y\" \"F y\"]\n            D.comp_cod_arr [of \"D (\\<phi> y (F y)) g\" \"G (F y)\"]\n            \\<phi>_naturality [of \"F y\" \"F y\" \"F y\" g y' y \"F y\"]\n      by (metis C.ide_in_hom D.arr_cod_iff_arr D.arr_dom D.cod_cod D.cod_dom D.comp_ide_arr\n          D.comp_ide_self D.ide_cod D.in_homE F.as_nat_trans.is_natural_2 F.functor_axioms\n          F.preserves_section_retraction \\<phi>_in_hom functor.preserves_hom)\n\n    interpretation \\<eta>: transformation_by_components D D D.map GF.map \\<eta>o\n    proof\n      show \"\\<And>a. D.ide a \\<Longrightarrow> \\<guillemotleft>\\<eta>o a : D.map a \\<rightarrow>\\<^sub>D GF.map a\\<guillemotright>\"\n        using \\<eta>o_def \\<phi>_in_hom D.ide_in_hom by force\n      fix f\n      assume f: \"D.arr f\"\n      show \"\\<eta>o (D.cod f) \\<cdot>\\<^sub>D D.map f = GF.map f \\<cdot>\\<^sub>D \\<eta>o (D.dom f)\"\n        using f \\<phi>_F_char [of \"D.map f\" \"D.dom f\" \"D.cod f\"]\n              \\<phi>_in_terms_of_\\<eta>o [of \"D.dom f\" \"F f\" \"F (D.cod f)\"]\n        by force\n    qed\n\n    lemma \\<eta>_map_simp:\n    assumes \"D.ide y\"\n    shows \"\\<eta>.map y = \\<phi> y (F y)\"\n      using assms \\<eta>.map_simp_ide \\<eta>o_def by simp\n\n    definition \\<epsilon>o :: \"'c \\<Rightarrow> 'c\"\n    where \"\\<epsilon>o x = \\<psi> x (G x)\"\n\n    lemma \\<epsilon>o_in_hom:\n    assumes \"C.ide x\"\n    shows \"\\<guillemotleft>\\<epsilon>o x : F (G x) \\<rightarrow>\\<^sub>C x\\<guillemotright>\"\n      using assms C.ide_in_hom \\<epsilon>o_def \\<psi>_in_hom by force\n\n    lemma \\<psi>_in_terms_of_\\<epsilon>o:\n    assumes \"C.ide x\" and \"\\<guillemotleft>g : y \\<rightarrow>\\<^sub>D G x\\<guillemotright>\"\n    shows \"\\<psi> x g = \\<epsilon>o x \\<cdot>\\<^sub>C F g\"\n    proof -\n      have \"\\<epsilon>o x \\<cdot>\\<^sub>C F g = x \\<cdot>\\<^sub>C \\<psi> x (G x) \\<cdot>\\<^sub>C F g\"\n        using assms \\<epsilon>o_def \\<psi>_in_hom [of x \"G x\" \"G x\"]\n              C.comp_cod_arr [of \"\\<psi> x (G x) \\<cdot>\\<^sub>C F g\" x]\n        by fastforce\n      also have \"... = \\<psi> x (G x \\<cdot>\\<^sub>D G x \\<cdot>\\<^sub>D g)\"\n        using assms \\<psi>_naturality [of x x x g y \"G x\" \"G x\"] by force\n      also have \"... = \\<psi> x g\"\n        using assms D.comp_cod_arr by fastforce\n      finally show ?thesis by simp\n    qed\n\n    \n\n    interpretation \\<epsilon>: transformation_by_components C C FG.map C.map \\<epsilon>o\n      apply unfold_locales\n      using \\<epsilon>o_in_hom\n       apply simp\n      using \\<psi>_G_char \\<psi>_in_terms_of_\\<epsilon>o\n      by (metis C.arr_iff_in_hom C.ide_cod C.map_simp G.preserves_hom comp_apply)\n\n    lemma \\<epsilon>_map_simp:\n    assumes \"C.ide x\"\n    shows \"\\<epsilon>.map x = \\<psi> x (G x)\"\n      using assms \\<epsilon>o_def by simp\n\n    interpretation FD: composite_functor D D C D.map F ..\n    interpretation CF: composite_functor D C C F C.map ..\n    interpretation GC: composite_functor C C D C.map G ..\n    interpretation DG: composite_functor C D D G D.map ..\n\n    interpretation F\\<eta>: natural_transformation D C F \\<open>F o G o F\\<close> \\<open>F o \\<eta>.map\\<close>\n      by (metis (no_types, lifting) F.as_nat_trans.natural_transformation_axioms\n          F.functor_axioms \\<eta>.natural_transformation_axioms comp_functor_identity\n          horizontal_composite o_assoc)\n\n    interpretation \\<epsilon>F: natural_transformation D C \\<open>F o G o F\\<close> F \\<open>\\<epsilon>.map o F\\<close>\n      using \\<epsilon>.natural_transformation_axioms F.as_nat_trans.natural_transformation_axioms\n            horizontal_composite\n      by fastforce\n\n    interpretation \\<eta>G: natural_transformation C D G \\<open>G o F o G\\<close> \\<open>\\<eta>.map o G\\<close>\n      using \\<eta>.natural_transformation_axioms G.as_nat_trans.natural_transformation_axioms\n            horizontal_composite\n      by fastforce\n\n    interpretation G\\<epsilon>: natural_transformation C D \\<open>G o F o G\\<close> G \\<open>G o \\<epsilon>.map\\<close>\n      by (metis (no_types, lifting) G.as_nat_trans.natural_transformation_axioms\n          G.functor_axioms \\<epsilon>.natural_transformation_axioms comp_functor_identity\n          horizontal_composite o_assoc)\n\n    interpretation \\<epsilon>FoF\\<eta>: vertical_composite D C F \\<open>F o G o F\\<close> F \\<open>F o \\<eta>.map\\<close> \\<open>\\<epsilon>.map o F\\<close>\n      ..\n    interpretation G\\<epsilon>o\\<eta>G: vertical_composite C D G \\<open>G o F o G\\<close> G \\<open>\\<eta>.map o G\\<close> \\<open>G o \\<epsilon>.map\\<close>\n      ..\n\n    lemma unit_counit_F:\n    assumes \"D.ide y\"\n    shows \"F y = \\<epsilon>o (F y) \\<cdot>\\<^sub>C F (\\<eta>o y)\"\n      using assms \\<psi>_in_terms_of_\\<epsilon>o \\<eta>o_def \\<psi>_\\<phi> \\<eta>o_in_hom F.preserves_ide C.ide_in_hom by metis\n\n    lemma unit_counit_G:\n    assumes \"C.ide x\"\n    shows \"G x = G (\\<epsilon>o x) \\<cdot>\\<^sub>D \\<eta>o (G x)\"\n      using assms \\<phi>_in_terms_of_\\<eta>o \\<epsilon>o_def \\<phi>_\\<psi> \\<epsilon>o_in_hom G.preserves_ide D.ide_in_hom by metis\n\n    lemma induces_unit_counit_adjunction':\n    shows \"unit_counit_adjunction C D F G \\<eta>.map \\<epsilon>.map\"\n    proof\n      show \"\\<epsilon>FoF\\<eta>.map = F\"\n        using \\<epsilon>FoF\\<eta>.is_natural_transformation \\<epsilon>FoF\\<eta>.map_simp_ide unit_counit_F\n              F.as_nat_trans.natural_transformation_axioms\n        by (intro NaturalTransformation.eqI) auto\n      show \"G\\<epsilon>o\\<eta>G.map = G\"\n        using G\\<epsilon>o\\<eta>G.is_natural_transformation G\\<epsilon>o\\<eta>G.map_simp_ide unit_counit_G\n              G.as_nat_trans.natural_transformation_axioms\n        by (intro NaturalTransformation.eqI) auto\n    qed\n\n    definition \\<eta> :: \"'d \\<Rightarrow> 'd\" where \"\\<eta> \\<equiv> \\<eta>.map\"\n    definition \\<epsilon> :: \"'c \\<Rightarrow> 'c\" where \"\\<epsilon> \\<equiv> \\<epsilon>.map\"\n\n    \n\n    lemma \\<eta>_is_natural_transformation:\n    shows \"natural_transformation D D D.map GF.map \\<eta>\"\n      unfolding \\<eta>_def ..\n\n    \n\n    text\\<open>\n      From the defined @{term \\<eta>} and @{term \\<epsilon>} we can recover the original @{term \\<phi>} and @{term \\<psi>}.\n\\<close>\n\n    lemma \\<phi>_in_terms_of_\\<eta>:\n    assumes \"D.ide y\" and \"\\<guillemotleft>f : F y \\<rightarrow>\\<^sub>C x\\<guillemotright>\"\n    shows \"\\<phi> y f = G f \\<cdot>\\<^sub>D \\<eta> y\"\n      using assms \\<eta>_def by (simp add: \\<phi>_in_terms_of_\\<eta>o)\n\n    lemma \\<psi>_in_terms_of_\\<epsilon>:\n    assumes \"C.ide x\" and \"\\<guillemotleft>g : y \\<rightarrow>\\<^sub>D G x\\<guillemotright>\"\n    shows \"\\<psi> x g = \\<epsilon> x \\<cdot>\\<^sub>C F g\"\n      using assms \\<epsilon>_def by (simp add: \\<psi>_in_terms_of_\\<epsilon>o)\n\n  end\n\n  section \"Meta-Adjunctions Induce Left and Right Adjoint Functors\"\n\n  context meta_adjunction\n  begin\n\n    interpretation unit_counit_adjunction C D F G \\<eta> \\<epsilon>\n      using induces_unit_counit_adjunction \\<eta>_def \\<epsilon>_def by auto\n\n    lemma has_terminal_arrows_from_functor:\n    assumes x: \"C.ide x\"\n    shows \"terminal_arrow_from_functor D C F (G x) x (\\<epsilon> x)\"\n    and \"\\<And>y' f. arrow_from_functor D C F y' x f\n                   \\<Longrightarrow> terminal_arrow_from_functor.the_coext D C F (G x) (\\<epsilon> x) y' f = \\<phi> y' f\"\n    proof -\n      interpret \\<epsilon>x: arrow_from_functor D C F \\<open>G x\\<close> x \\<open>\\<epsilon> x\\<close>\n        using x \\<epsilon>.preserves_hom G.preserves_ide by unfold_locales auto\n      have 1: \"\\<And>y' f. arrow_from_functor D C F y' x f \\<Longrightarrow>\n                      \\<epsilon>x.is_coext y' f (\\<phi> y' f) \\<and> (\\<forall>g'. \\<epsilon>x.is_coext y' f g' \\<longrightarrow> g' = \\<phi> y' f)\"\n        using x\n        by (metis (full_types) \\<epsilon>x.is_coext_def \\<phi>_\\<psi> \\<psi>_in_terms_of_\\<epsilon> arrow_from_functor.arrow\n            \\<phi>_in_hom \\<psi>_\\<phi>)\n      interpret \\<epsilon>x: terminal_arrow_from_functor D C F \\<open>G x\\<close> x \\<open>\\<epsilon> x\\<close>\n        using 1 by unfold_locales blast\n      show \"terminal_arrow_from_functor D C F (G x) x (\\<epsilon> x)\" ..\n      show \"\\<And>y' f. arrow_from_functor D C F y' x f \\<Longrightarrow> \\<epsilon>x.the_coext y' f = \\<phi> y' f\"\n        using 1 \\<epsilon>x.the_coext_def by auto\n    qed\n\n    lemma has_left_adjoint_functor:\n    shows \"left_adjoint_functor D C F\"\n      apply unfold_locales using has_terminal_arrows_from_functor by auto\n\n    lemma has_initial_arrows_to_functor:\n    assumes y: \"D.ide y\"\n    shows \"initial_arrow_to_functor C D G y (F y) (\\<eta> y)\"\n    and \"\\<And>x' g. arrow_to_functor C D G y x' g \\<Longrightarrow>\n                  initial_arrow_to_functor.the_ext C D G (F y) (\\<eta> y) x' g = \\<psi> x' g\"\n    proof -\n      interpret \\<eta>y: arrow_to_functor C D G y \\<open>F y\\<close> \\<open>\\<eta> y\\<close>\n        using y by unfold_locales auto\n      have 1: \"\\<And>x' g. arrow_to_functor C D G y x' g \\<Longrightarrow>\n                         \\<eta>y.is_ext x' g (\\<psi> x' g) \\<and> (\\<forall>f'. \\<eta>y.is_ext x' g f' \\<longrightarrow> f' = \\<psi> x' g)\"\n        using y\n        by (metis (full_types) \\<eta>y.is_ext_def \\<psi>_\\<phi> \\<phi>_in_terms_of_\\<eta> arrow_to_functor.arrow\n            \\<psi>_in_hom \\<phi>_\\<psi>)\n      interpret \\<eta>y: initial_arrow_to_functor C D G y \\<open>F y\\<close> \\<open>\\<eta> y\\<close>\n        apply unfold_locales using 1 by blast\n      show \"initial_arrow_to_functor C D G y (F y) (\\<eta> y)\" ..\n      show \"\\<And>x' g. arrow_to_functor C D G y x' g \\<Longrightarrow> \\<eta>y.the_ext x' g = \\<psi> x' g\"\n        using 1 \\<eta>y.the_ext_def by auto\n    qed\n\n    lemma has_right_adjoint_functor:\n    shows \"right_adjoint_functor C D G\"\n      apply unfold_locales using has_initial_arrows_to_functor by auto\n\n  end\n\n  section \"Unit/Counit Adjunctions Induce Meta-Adjunctions\"\n\n  context unit_counit_adjunction\n  begin\n\n    definition \\<phi> :: \"'d \\<Rightarrow> 'c \\<Rightarrow> 'd\"\n    where \"\\<phi> y h = G h \\<cdot>\\<^sub>D \\<eta> y\"\n\n    definition \\<psi> :: \"'c \\<Rightarrow> 'd \\<Rightarrow> 'c\"\n    where \"\\<psi> x h = \\<epsilon> x \\<cdot>\\<^sub>C F h\"\n\n    interpretation meta_adjunction C D F G \\<phi> \\<psi>\n    proof\n      fix x :: 'c and y :: 'd and f :: 'c\n      assume y: \"D.ide y\" and f: \"\\<guillemotleft>f : F y \\<rightarrow>\\<^sub>C x\\<guillemotright>\"\n      show 0: \"\\<guillemotleft>\\<phi> y f : y \\<rightarrow>\\<^sub>D G x\\<guillemotright>\"\n        using f y G.preserves_hom \\<eta>.preserves_hom \\<phi>_def D.ide_in_hom by auto\n      show \"\\<psi> x (\\<phi> y f) = f\"\n      proof -\n        have \"\\<psi> x (\\<phi> y f) = (\\<epsilon> x \\<cdot>\\<^sub>C F (G f)) \\<cdot>\\<^sub>C F (\\<eta> y)\"\n          using y f \\<phi>_def \\<psi>_def C.comp_assoc by auto\n        also have \"... = (f \\<cdot>\\<^sub>C \\<epsilon> (F y)) \\<cdot>\\<^sub>C F (\\<eta> y)\"\n          using y f \\<epsilon>.naturality by auto\n        also have \"... = f\"\n          using y f \\<epsilon>FoF\\<eta>.map_simp_2 triangle_F C.comp_arr_dom D.ide_in_hom C.comp_assoc\n          by fastforce\n        finally show ?thesis by auto\n      qed\n      next\n      fix x :: 'c and y :: 'd and g :: 'd\n      assume x: \"C.ide x\" and g: \"\\<guillemotleft>g : y \\<rightarrow>\\<^sub>D G x\\<guillemotright>\"\n      show \"\\<guillemotleft>\\<psi> x g : F y \\<rightarrow>\\<^sub>C x\\<guillemotright>\" using g x \\<psi>_def by fastforce\n      show \"\\<phi> y (\\<psi> x g) = g\"\n      proof -\n        have \"\\<phi> y (\\<psi> x g) = (G (\\<epsilon> x) \\<cdot>\\<^sub>D \\<eta> (G x)) \\<cdot>\\<^sub>D g\"\n          using g x \\<phi>_def \\<psi>_def \\<eta>.naturality [of g] D.comp_assoc by auto\n        also have \"... = g\"\n          using x g triangle_G D.comp_ide_arr G\\<epsilon>o\\<eta>G.map_simp_ide by auto\n        finally show ?thesis by auto\n      qed\n      next\n      fix f :: 'c and g :: 'd and h :: 'c and x :: 'c and x' :: 'c and y :: 'd and y' :: 'd\n      assume f: \"\\<guillemotleft>f : x \\<rightarrow>\\<^sub>C x'\\<guillemotright>\" and g: \"\\<guillemotleft>g : y' \\<rightarrow>\\<^sub>D y\\<guillemotright>\" and h: \"\\<guillemotleft>h : F y \\<rightarrow>\\<^sub>C x\\<guillemotright>\"\n      show \"\\<phi> y' (f \\<cdot>\\<^sub>C h \\<cdot>\\<^sub>C F g) = G f \\<cdot>\\<^sub>D \\<phi> y h \\<cdot>\\<^sub>D g\"\n        using \\<phi>_def f g h \\<eta>.naturality D.comp_assoc by fastforce\n    qed\n\n    theorem induces_meta_adjunction:\n    shows \"meta_adjunction C D F G \\<phi> \\<psi>\" ..\n\n    text\\<open>\n      From the defined @{term \\<phi>} and @{term \\<psi>} we can recover the original @{term \\<eta>} and @{term \\<epsilon>}.\n\\<close>\n\n    lemma \\<eta>_in_terms_of_\\<phi>:\n    assumes \"D.ide y\"\n    shows \"\\<eta> y = \\<phi> y (F y)\"\n      using assms \\<phi>_def D.comp_cod_arr by auto\n\n    lemma \\<epsilon>_in_terms_of_\\<psi>:\n    assumes \"C.ide x\"\n    shows \"\\<epsilon> x = \\<psi> x (G x)\"\n      using assms \\<psi>_def C.comp_arr_dom by auto\n\n  end\n\n  section \"Left and Right Adjoint Functors Induce Meta-Adjunctions\"\n\n  text\\<open>\n    A left adjoint functor induces a meta-adjunction, modulo the choice of a\n    right adjoint and counit.\n\\<close>\n\n  context left_adjoint_functor\n  begin\n\n    definition Go :: \"'c \\<Rightarrow> 'd\"\n    where \"Go a = (SOME b. \\<exists>e. terminal_arrow_from_functor D C F b a e)\"\n\n    definition \\<epsilon>o :: \"'c \\<Rightarrow> 'c\"\n    where \"\\<epsilon>o a = (SOME e. terminal_arrow_from_functor D C F (Go a) a e)\"\n\n    lemma Go_\\<epsilon>o_terminal:\n    assumes \"\\<exists>b e. terminal_arrow_from_functor D C F b a e\"\n    shows \"terminal_arrow_from_functor D C F (Go a) a (\\<epsilon>o a)\"\n      using assms Go_def \\<epsilon>o_def\n            someI_ex [of \"\\<lambda>b. \\<exists>e. terminal_arrow_from_functor D C F b a e\"]\n            someI_ex [of \"\\<lambda>e. terminal_arrow_from_functor D C F (Go a) a e\"]\n      by simp\n\n    text\\<open>\n      The right adjoint @{term G} to @{term F} takes each arrow @{term f} of\n      @{term[source=true] C} to the unique @{term[source=true] D}-coextension of\n      @{term \"C f (\\<epsilon>o (C.dom f))\"} along @{term \"\\<epsilon>o (C.cod f)\"}.\n\\<close>\n\n    definition G :: \"'c \\<Rightarrow> 'd\"\n    where \"G f = (if C.arr f then\n                     terminal_arrow_from_functor.the_coext D C F (Go (C.cod f)) (\\<epsilon>o (C.cod f))\n                                  (Go (C.dom f)) (f \\<cdot>\\<^sub>C \\<epsilon>o (C.dom f))\n                  else D.null)\"\n\n    lemma G_ide:\n    assumes \"C.ide x\"\n    shows \"G x = Go x\"\n    proof -\n      interpret terminal_arrow_from_functor D C F \\<open>Go x\\<close> x \\<open>\\<epsilon>o x\\<close>\n        using assms ex_terminal_arrow Go_\\<epsilon>o_terminal by blast\n      have 1: \"arrow_from_functor D C F (Go x) x (\\<epsilon>o x)\" ..\n      have \"is_coext (Go x) (\\<epsilon>o x) (Go x)\"\n        using arrow is_coext_def C.in_homE C.comp_arr_dom by auto\n      hence \"Go x = the_coext (Go x) (\\<epsilon>o x)\" using 1 the_coext_unique by blast\n      moreover have \"\\<epsilon>o x = C x (\\<epsilon>o (C.dom x))\"\n        using assms arrow C.comp_ide_arr C.seqI' C.ide_in_hom C.in_homE by metis\n      ultimately show ?thesis using assms G_def C.cod_dom C.ide_in_hom C.in_homE by metis\n    qed\n\n    lemma G_is_functor:\n    shows \"functor C D G\"\n    proof\n      fix f :: 'c\n      assume \"\\<not>C.arr f\"\n      thus \"G f = D.null\" using G_def by auto\n      next\n      fix f :: 'c\n      assume f: \"C.arr f\"\n      let ?x = \"C.dom f\"\n      let ?x' = \"C.cod f\"\n      interpret x\\<epsilon>: terminal_arrow_from_functor D C F \\<open>Go ?x\\<close> \\<open>?x\\<close> \\<open>\\<epsilon>o ?x\\<close>\n        using f ex_terminal_arrow Go_\\<epsilon>o_terminal by simp\n      interpret x'\\<epsilon>: terminal_arrow_from_functor D C F \\<open>Go ?x'\\<close> \\<open>?x'\\<close> \\<open>\\<epsilon>o ?x'\\<close>\n        using f ex_terminal_arrow Go_\\<epsilon>o_terminal by simp\n      have 1: \"arrow_from_functor D C F (Go ?x) ?x' (C f (\\<epsilon>o ?x))\"\n        using f x\\<epsilon>.arrow by (unfold_locales, auto)\n      have \"G f = x'\\<epsilon>.the_coext (Go ?x) (C f (\\<epsilon>o ?x))\" using f G_def by simp\n      hence Gf: \"\\<guillemotleft>G f : Go ?x \\<rightarrow>\\<^sub>D Go ?x'\\<guillemotright> \\<and> f \\<cdot>\\<^sub>C \\<epsilon>o ?x = \\<epsilon>o ?x' \\<cdot>\\<^sub>C F (G f)\"\n        using 1 x'\\<epsilon>.the_coext_prop by simp\n      show \"D.arr (G f)\" using Gf by auto\n      show \"D.dom (G f) = G ?x\" using f Gf G_ide by auto\n      show \"D.cod (G f) = G ?x'\" using f Gf G_ide by auto\n      next\n      fix f f' :: 'c\n      assume ff': \"C.arr (C f' f)\"\n      have f: \"C.arr f\" using ff' by auto\n      let ?x = \"C.dom f\"\n      let ?x' = \"C.cod f\"\n      let ?x'' = \"C.cod f'\"\n      interpret x\\<epsilon>: terminal_arrow_from_functor D C F \\<open>Go ?x\\<close> \\<open>?x\\<close> \\<open>\\<epsilon>o ?x\\<close>\n        using f ex_terminal_arrow Go_\\<epsilon>o_terminal by simp\n      interpret x'\\<epsilon>: terminal_arrow_from_functor D C F \\<open>Go ?x'\\<close> \\<open>?x'\\<close> \\<open>\\<epsilon>o ?x'\\<close>\n        using f ex_terminal_arrow Go_\\<epsilon>o_terminal by simp\n      interpret x''\\<epsilon>: terminal_arrow_from_functor D C F \\<open>Go ?x''\\<close> \\<open>?x''\\<close> \\<open>\\<epsilon>o ?x''\\<close>\n        using ff' ex_terminal_arrow Go_\\<epsilon>o_terminal by auto\n      have 1: \"arrow_from_functor D C F (Go ?x) ?x' (f \\<cdot>\\<^sub>C \\<epsilon>o ?x)\"\n         using f x\\<epsilon>.arrow by (unfold_locales, auto)\n      have 2: \"arrow_from_functor D C F (Go ?x') ?x'' (f' \\<cdot>\\<^sub>C \\<epsilon>o ?x')\"\n         using ff' x'\\<epsilon>.arrow by (unfold_locales, auto)\n      have \"G f = x'\\<epsilon>.the_coext (Go ?x) (C f (\\<epsilon>o ?x))\"\n        using f G_def by simp\n      hence Gf: \"D.in_hom (G f) (Go ?x) (Go ?x') \\<and> f \\<cdot>\\<^sub>C \\<epsilon>o ?x = \\<epsilon>o ?x' \\<cdot>\\<^sub>C F (G f)\"\n        using 1 x'\\<epsilon>.the_coext_prop by simp\n      have \"G f' = x''\\<epsilon>.the_coext (Go ?x') (f' \\<cdot>\\<^sub>C \\<epsilon>o ?x')\"\n        using ff' G_def by auto\n      hence Gf': \"\\<guillemotleft>G f' : Go (C.cod f) \\<rightarrow>\\<^sub>D Go (C.cod f')\\<guillemotright> \\<and> f' \\<cdot>\\<^sub>C \\<epsilon>o ?x' = \\<epsilon>o ?x'' \\<cdot>\\<^sub>C F (G f')\"\n        using 2 x''\\<epsilon>.the_coext_prop by simp\n      show \"G (f' \\<cdot>\\<^sub>C f) = G f' \\<cdot>\\<^sub>D G f\"\n      proof -\n        have \"x''\\<epsilon>.is_coext (Go ?x) ((f' \\<cdot>\\<^sub>C f) \\<cdot>\\<^sub>C \\<epsilon>o ?x) (G f' \\<cdot>\\<^sub>D G f)\"\n        proof -\n          have 3: \"\\<guillemotleft>G f' \\<cdot>\\<^sub>D G f : Go (C.dom f) \\<rightarrow>\\<^sub>D Go (C.cod f')\\<guillemotright>\" using 1 2 Gf Gf' by auto\n          moreover have \"(f' \\<cdot>\\<^sub>C f) \\<cdot>\\<^sub>C \\<epsilon>o ?x = \\<epsilon>o ?x'' \\<cdot>\\<^sub>C F (G f' \\<cdot>\\<^sub>D G f)\"\n            by (metis 3 C.comp_assoc D.in_homE Gf Gf' preserves_comp)\n          ultimately show ?thesis using x''\\<epsilon>.is_coext_def by auto\n        qed\n        moreover have \"arrow_from_functor D C F (Go ?x) ?x'' ((f' \\<cdot>\\<^sub>C f) \\<cdot>\\<^sub>C \\<epsilon>o ?x)\"\n           using ff' x\\<epsilon>.arrow by unfold_locales blast\n        ultimately show ?thesis\n          using ff' G_def x''\\<epsilon>.the_coext_unique C.seqE C.cod_comp C.dom_comp by auto\n      qed\n    qed\n\n    interpretation G: \"functor\" C D G using G_is_functor by auto\n\n    lemma G_simp:\n    assumes \"C.arr f\"\n    shows \"G f = terminal_arrow_from_functor.the_coext D C F (Go (C.cod f)) (\\<epsilon>o (C.cod f))\n                                                             (Go (C.dom f)) (f \\<cdot>\\<^sub>C \\<epsilon>o (C.dom f))\"\n      using assms G_def by simp\n\n    interpretation idC: identity_functor C ..\n    interpretation GF: composite_functor C D C G F ..\n\n    interpretation \\<epsilon>: transformation_by_components C C GF.map C.map \\<epsilon>o\n    proof\n      fix x :: 'c\n      assume x: \"C.ide x\"\n      show \"\\<guillemotleft>\\<epsilon>o x : GF.map x \\<rightarrow>\\<^sub>C C.map x\\<guillemotright>\"\n      proof -\n        interpret terminal_arrow_from_functor D C F \\<open>Go x\\<close> x \\<open>\\<epsilon>o x\\<close>\n          using x Go_\\<epsilon>o_terminal ex_terminal_arrow by simp\n        show ?thesis using x G_ide arrow by auto\n      qed\n      next\n      fix f :: 'c\n      assume f: \"C.arr f\"\n      show \"\\<epsilon>o (C.cod f) \\<cdot>\\<^sub>C GF.map f = C.map f \\<cdot>\\<^sub>C \\<epsilon>o (C.dom f)\"\n      proof -\n        let ?x = \"C.dom f\"\n        let ?x' = \"C.cod f\"\n        interpret x\\<epsilon>: terminal_arrow_from_functor D C F \\<open>Go ?x\\<close> ?x \\<open>\\<epsilon>o ?x\\<close>\n          using f Go_\\<epsilon>o_terminal ex_terminal_arrow by simp\n        interpret x'\\<epsilon>: terminal_arrow_from_functor D C F \\<open>Go ?x'\\<close> ?x' \\<open>\\<epsilon>o ?x'\\<close>\n          using f Go_\\<epsilon>o_terminal ex_terminal_arrow by simp\n        have 1: \"arrow_from_functor D C F (Go ?x) ?x' (C f (\\<epsilon>o ?x))\"\n           using f x\\<epsilon>.arrow by unfold_locales auto\n        have \"G f = x'\\<epsilon>.the_coext (Go ?x) (f \\<cdot>\\<^sub>C \\<epsilon>o ?x)\"\n          using f G_simp by blast\n        hence \"x'\\<epsilon>.is_coext (Go ?x) (f \\<cdot>\\<^sub>C \\<epsilon>o ?x) (G f)\"\n          using 1 x'\\<epsilon>.the_coext_prop x'\\<epsilon>.is_coext_def by auto\n        thus ?thesis\n          using f x'\\<epsilon>.is_coext_def by simp\n      qed\n    qed\n\n    definition \\<psi>\n    where \"\\<psi> x h = C (\\<epsilon>.map x) (F h)\"\n\n    lemma \\<psi>_in_hom:\n    assumes \"C.ide x\" and \"\\<guillemotleft>g : y \\<rightarrow>\\<^sub>D G x\\<guillemotright>\"\n    shows \"\\<guillemotleft>\\<psi> x g : F y \\<rightarrow>\\<^sub>C x\\<guillemotright>\"\n      unfolding \\<psi>_def using assms \\<epsilon>.maps_ide_in_hom by auto\n\n    lemma \\<psi>_natural:\n    assumes f: \"\\<guillemotleft>f : x \\<rightarrow>\\<^sub>C x'\\<guillemotright>\" and g: \"\\<guillemotleft>g : y' \\<rightarrow>\\<^sub>D y\\<guillemotright>\" and h: \"\\<guillemotleft>h : y \\<rightarrow>\\<^sub>D G x\\<guillemotright>\"\n    shows \"f \\<cdot>\\<^sub>C \\<psi> x h \\<cdot>\\<^sub>C F g = \\<psi> x' ((G f \\<cdot>\\<^sub>D h) \\<cdot>\\<^sub>D g)\"\n    proof -\n      have \"f \\<cdot>\\<^sub>C \\<psi> x h \\<cdot>\\<^sub>C F g = f \\<cdot>\\<^sub>C (\\<epsilon>.map x \\<cdot>\\<^sub>C F h) \\<cdot>\\<^sub>C F g\"\n        unfolding \\<psi>_def by auto\n      also have \"... = (f \\<cdot>\\<^sub>C \\<epsilon>.map x) \\<cdot>\\<^sub>C F h \\<cdot>\\<^sub>C F g\"\n        using C.comp_assoc by fastforce\n      also have \"... = (f \\<cdot>\\<^sub>C \\<epsilon>.map x) \\<cdot>\\<^sub>C F (h \\<cdot>\\<^sub>D g)\"\n        using g h by fastforce\n      also have \"... = (\\<epsilon>.map x' \\<cdot>\\<^sub>C F (G f)) \\<cdot>\\<^sub>C F (h \\<cdot>\\<^sub>D g)\"\n        using f \\<epsilon>.naturality by auto\n      also have \"... = \\<epsilon>.map x' \\<cdot>\\<^sub>C F ((G f \\<cdot>\\<^sub>D h) \\<cdot>\\<^sub>D g)\"\n        using f g h C.comp_assoc by fastforce\n      also have \"... = \\<psi> x' ((G f \\<cdot>\\<^sub>D h) \\<cdot>\\<^sub>D g)\"\n        unfolding \\<psi>_def by auto\n      finally show ?thesis by auto\n    qed\n\n    lemma \\<psi>_inverts_coext:\n    assumes x: \"C.ide x\" and g: \"\\<guillemotleft>g : y \\<rightarrow>\\<^sub>D G x\\<guillemotright>\"\n    shows \"arrow_from_functor.is_coext D C F (G x) (\\<epsilon>.map x) y (\\<psi> x g) g\"\n    proof -\n      interpret x\\<epsilon>: arrow_from_functor D C F \\<open>G x\\<close> x \\<open>\\<epsilon>.map x\\<close>\n        using x \\<epsilon>.maps_ide_in_hom by unfold_locales auto\n      show \"x\\<epsilon>.is_coext y (\\<psi> x g) g\"\n        using x g \\<psi>_def x\\<epsilon>.is_coext_def G_ide by blast\n    qed\n\n    lemma \\<psi>_invertible:\n    assumes y: \"D.ide y\" and f: \"\\<guillemotleft>f : F y \\<rightarrow>\\<^sub>C x\\<guillemotright>\"\n    shows \"\\<exists>!g. \\<guillemotleft>g : y \\<rightarrow>\\<^sub>D G x\\<guillemotright> \\<and> \\<psi> x g = f\"\n    proof\n      have x: \"C.ide x\" using f by auto\n      interpret x\\<epsilon>: terminal_arrow_from_functor D C F \\<open>Go x\\<close> x \\<open>\\<epsilon>o x\\<close>\n        using x ex_terminal_arrow Go_\\<epsilon>o_terminal by auto\n      have 1: \"arrow_from_functor D C F y x f\"\n        using y f by (unfold_locales, auto)\n      let ?g = \"x\\<epsilon>.the_coext y f\"\n      have \"\\<psi> x ?g = f\"\n        using 1 x y \\<psi>_def x\\<epsilon>.the_coext_prop G_ide \\<psi>_inverts_coext x\\<epsilon>.is_coext_def by simp\n      thus \"\\<guillemotleft>?g : y \\<rightarrow>\\<^sub>D G x\\<guillemotright> \\<and> \\<psi> x ?g = f\"\n        using 1 x x\\<epsilon>.the_coext_prop G_ide by simp\n      show \"\\<And>g'. \\<guillemotleft>g' : y \\<rightarrow>\\<^sub>D G x\\<guillemotright> \\<and> \\<psi> x g' = f \\<Longrightarrow> g' = ?g\"\n        using 1 x y \\<psi>_inverts_coext G_ide x\\<epsilon>.the_coext_unique by force\n    qed\n\n    definition \\<phi>\n    where \"\\<phi> y f = (THE g. \\<guillemotleft>g : y \\<rightarrow>\\<^sub>D G (C.cod f)\\<guillemotright> \\<and> \\<psi> (C.cod f) g = f)\"\n\n    lemma \\<phi>_in_hom:\n    assumes \"D.ide y\" and \"\\<guillemotleft>f : F y \\<rightarrow>\\<^sub>C x\\<guillemotright>\"\n    shows \"\\<guillemotleft>\\<phi> y f : y \\<rightarrow>\\<^sub>D G x\\<guillemotright>\"\n      using assms \\<psi>_invertible \\<phi>_def theI' [of \"\\<lambda>g. \\<guillemotleft>g : y \\<rightarrow>\\<^sub>D G x\\<guillemotright> \\<and> \\<psi> x g = f\"]\n      by auto\n\n    lemma \\<phi>_\\<psi>:\n    assumes \"C.ide x\" and \"\\<guillemotleft>g : y \\<rightarrow>\\<^sub>D G x\\<guillemotright>\"\n    shows \"\\<phi> y (\\<psi> x g) = g\"\n    proof -\n      have \"\\<phi> y (\\<psi> x g) = (THE g'. \\<guillemotleft>g' : y \\<rightarrow>\\<^sub>D G x\\<guillemotright> \\<and> \\<psi> x g' = \\<psi> x g)\"\n      proof -\n        have \"C.cod (\\<psi> x g) = x\"\n          using assms \\<psi>_in_hom by auto\n        thus ?thesis\n          using \\<phi>_def by auto\n      qed\n      moreover have \"\\<exists>!g'. \\<guillemotleft>g' : y \\<rightarrow>\\<^sub>D G x\\<guillemotright> \\<and> \\<psi> x g' = \\<psi> x g\"\n        using assms \\<psi>_in_hom \\<psi>_invertible D.ide_dom by blast\n      ultimately show \"\\<phi> y (\\<psi> x g) = g\"\n        using assms(2) by auto\n    qed\n\n    lemma \\<psi>_\\<phi>:\n    assumes \"D.ide y\" and \"\\<guillemotleft>f : F y \\<rightarrow>\\<^sub>C x\\<guillemotright>\"\n    shows \"\\<psi> x (\\<phi> y f) = f\"\n      using assms \\<psi>_invertible \\<phi>_def theI' [of \"\\<lambda>g. \\<guillemotleft>g : y \\<rightarrow>\\<^sub>D G x\\<guillemotright> \\<and> \\<psi> x g = f\"]\n      by auto\n\n    lemma \\<phi>_natural:\n    assumes \"\\<guillemotleft>f : x \\<rightarrow>\\<^sub>C x'\\<guillemotright>\" and \"\\<guillemotleft>g : y' \\<rightarrow>\\<^sub>D y\\<guillemotright>\" and \"\\<guillemotleft>h : F y \\<rightarrow>\\<^sub>C x\\<guillemotright>\"\n    shows \"\\<phi> y' (f \\<cdot>\\<^sub>C h \\<cdot>\\<^sub>C F g) = (G f \\<cdot>\\<^sub>D \\<phi> y h) \\<cdot>\\<^sub>D g\"\n    proof -\n      have \"C.ide x' \\<and> D.ide y \\<and> D.in_hom (\\<phi> y h) y (G x)\"\n        using assms \\<phi>_in_hom by auto\n      thus ?thesis\n        using assms D.comp_in_homI G.preserves_hom \\<psi>_natural [of f x x' g y' y \"\\<phi> y h\"] \\<phi>_\\<psi> \\<psi>_\\<phi>\n        by auto\n    qed\n\n    theorem induces_meta_adjunction:\n    shows \"meta_adjunction C D F G \\<phi> \\<psi>\"\n      using \\<phi>_in_hom \\<psi>_in_hom \\<phi>_\\<psi> \\<psi>_\\<phi> \\<phi>_natural D.comp_assoc\n      by unfold_locales auto\n\n  end\n\n  text\\<open>\n    A right adjoint functor induces a meta-adjunction, modulo the choice of a\n    left adjoint and unit.\n\\<close>\n\n  context right_adjoint_functor\n  begin\n\n    definition Fo :: \"'d \\<Rightarrow> 'c\"\n    where \"Fo y = (SOME x. \\<exists>u. initial_arrow_to_functor C D G y x u)\"\n\n    definition \\<eta>o :: \"'d \\<Rightarrow> 'd\"\n    where \"\\<eta>o y = (SOME u. initial_arrow_to_functor C D G y (Fo y) u)\"\n\n    lemma Fo_\\<eta>o_initial:\n    assumes \"\\<exists>x u. initial_arrow_to_functor C D G y x u\"\n    shows \"initial_arrow_to_functor C D G y (Fo y) (\\<eta>o y)\"\n      using assms Fo_def \\<eta>o_def\n            someI_ex [of \"\\<lambda>x. \\<exists>u. initial_arrow_to_functor C D G y x u\"]\n            someI_ex [of \"\\<lambda>u. initial_arrow_to_functor C D G y (Fo y) u\"]\n      by simp\n\n    text\\<open>\n      The left adjoint @{term F} to @{term g} takes each arrow @{term g} of\n      @{term[source=true] D} to the unique @{term[source=true] C}-extension of\n      @{term \"D (\\<eta>o (D.cod g)) g\"} along @{term \"\\<eta>o (D.dom g)\"}.\n\\<close>\n\n    definition F :: \"'d \\<Rightarrow> 'c\"\n    where \"F g = (if D.arr g then\n                     initial_arrow_to_functor.the_ext C D G (Fo (D.dom g)) (\\<eta>o (D.dom g))\n                                  (Fo (D.cod g)) (\\<eta>o (D.cod g) \\<cdot>\\<^sub>D g)\n                  else C.null)\"\n\n    lemma F_ide:\n    assumes \"D.ide y\"\n    shows \"F y = Fo y\"\n    proof -\n      interpret initial_arrow_to_functor C D G y \\<open>Fo y\\<close> \\<open>\\<eta>o y\\<close>\n        using assms initial_arrows_exist Fo_\\<eta>o_initial by blast\n      have 1: \"arrow_to_functor C D G y (Fo y) (\\<eta>o y)\" ..\n      have \"is_ext (Fo y) (\\<eta>o y) (Fo y)\"\n        unfolding is_ext_def using arrow D.comp_ide_arr [of \"G (Fo y)\" \"\\<eta>o y\"] by force\n      hence \"Fo y = the_ext (Fo y) (\\<eta>o y)\"\n        using 1 the_ext_unique by blast\n      moreover have \"\\<eta>o y = D (\\<eta>o (D.cod y)) y\"\n        using assms arrow D.comp_arr_ide D.comp_arr_dom by auto\n      ultimately show ?thesis\n        using assms F_def D.dom_cod D.in_homE D.ide_in_hom by metis\n    qed\n\n    \n\n    interpretation F: \"functor\" D C F using F_is_functor by auto\n\n    \n\n    interpretation FG: composite_functor D C D F G ..\n\n    interpretation \\<eta>: transformation_by_components D D D.map FG.map \\<eta>o\n    proof\n      fix y :: 'd\n      assume y: \"D.ide y\"\n      show \"\\<guillemotleft>\\<eta>o y : D.map y \\<rightarrow>\\<^sub>D FG.map y\\<guillemotright>\"\n      proof -\n        interpret initial_arrow_to_functor C D G y \\<open>Fo y\\<close> \\<open>\\<eta>o y\\<close>\n          using y Fo_\\<eta>o_initial initial_arrows_exist by simp\n        show ?thesis using y F_ide arrow by auto\n      qed\n      next\n      fix g :: 'd\n      assume g: \"D.arr g\"\n      show \"\\<eta>o (D.cod g) \\<cdot>\\<^sub>D D.map g = FG.map g \\<cdot>\\<^sub>D \\<eta>o (D.dom g)\"\n      proof -\n        let ?y = \"D.dom g\"\n        let ?y' = \"D.cod g\"\n        interpret y\\<eta>: initial_arrow_to_functor C D G ?y \\<open>Fo ?y\\<close> \\<open>\\<eta>o ?y\\<close>\n          using g Fo_\\<eta>o_initial initial_arrows_exist by simp\n        interpret y'\\<eta>: initial_arrow_to_functor C D G ?y' \\<open>Fo ?y'\\<close> \\<open>\\<eta>o ?y'\\<close>\n          using g Fo_\\<eta>o_initial initial_arrows_exist by simp\n        have \"arrow_to_functor C D G ?y (Fo ?y') (\\<eta>o ?y' \\<cdot>\\<^sub>D g)\"\n          using g y'\\<eta>.arrow by unfold_locales auto\n        moreover have \"F g = y\\<eta>.the_ext (Fo ?y') (\\<eta>o ?y' \\<cdot>\\<^sub>D g)\"\n          using g F_simp by blast\n        ultimately have \"y\\<eta>.is_ext (Fo ?y') (\\<eta>o ?y' \\<cdot>\\<^sub>D g) (F g)\"\n          using y\\<eta>.the_ext_prop y\\<eta>.is_ext_def by auto\n        thus ?thesis\n          using g y\\<eta>.is_ext_def by simp\n      qed\n    qed\n\n    definition \\<phi>\n    where \"\\<phi> y h = D (G h) (\\<eta>.map y)\"\n\n    lemma \\<phi>_in_hom:\n    assumes y: \"D.ide y\" and f: \"\\<guillemotleft>f : F y \\<rightarrow>\\<^sub>C x\\<guillemotright>\"\n    shows \"\\<guillemotleft>\\<phi> y f : y \\<rightarrow>\\<^sub>D G x\\<guillemotright>\"\n      unfolding \\<phi>_def using assms \\<eta>.maps_ide_in_hom by auto\n\n    lemma \\<phi>_natural:\n    assumes f: \"\\<guillemotleft>f : x \\<rightarrow>\\<^sub>C x'\\<guillemotright>\" and g: \"\\<guillemotleft>g : y' \\<rightarrow>\\<^sub>D y\\<guillemotright>\" and h: \"\\<guillemotleft>h : F y \\<rightarrow>\\<^sub>C x\\<guillemotright>\"\n    shows \"\\<phi> y' (f \\<cdot>\\<^sub>C h \\<cdot>\\<^sub>C F g) = (G f \\<cdot>\\<^sub>D \\<phi> y h) \\<cdot>\\<^sub>D g\"\n    proof -\n      have \"(G f \\<cdot>\\<^sub>D \\<phi> y h) \\<cdot>\\<^sub>D g = (G f \\<cdot>\\<^sub>D G h \\<cdot>\\<^sub>D \\<eta>.map y) \\<cdot>\\<^sub>D g\"\n        unfolding \\<phi>_def by auto\n      also have \"... = (G f \\<cdot>\\<^sub>D G h) \\<cdot>\\<^sub>D \\<eta>.map y \\<cdot>\\<^sub>D g\"\n        using D.comp_assoc by fastforce\n      also have \"... = G (f \\<cdot>\\<^sub>C h) \\<cdot>\\<^sub>D G (F g) \\<cdot>\\<^sub>D \\<eta>.map y'\"\n        using f g h \\<eta>.naturality by fastforce\n      also have \"... = (G (f \\<cdot>\\<^sub>C h) \\<cdot>\\<^sub>D G (F g)) \\<cdot>\\<^sub>D \\<eta>.map y'\"\n        using D.comp_assoc by fastforce\n      also have \"... = G (f \\<cdot>\\<^sub>C h \\<cdot>\\<^sub>C F g) \\<cdot>\\<^sub>D \\<eta>.map y'\"\n        using f g h D.comp_assoc by fastforce\n      also have \"... = \\<phi> y' (f \\<cdot>\\<^sub>C h \\<cdot>\\<^sub>C F g)\"\n        unfolding \\<phi>_def by auto\n      finally show ?thesis by auto\n    qed\n\n    lemma \\<phi>_inverts_ext:\n    assumes y: \"D.ide y\" and f: \"\\<guillemotleft>f : F y \\<rightarrow>\\<^sub>C x\\<guillemotright>\"\n    shows \"arrow_to_functor.is_ext C D G (F y) (\\<eta>.map y) x (\\<phi> y f) f\"\n    proof -\n      interpret y\\<eta>: arrow_to_functor C D G y \\<open>F y\\<close> \\<open>\\<eta>.map y\\<close>\n        using y \\<eta>.maps_ide_in_hom by unfold_locales auto\n      show \"y\\<eta>.is_ext x (\\<phi> y f) f\"\n        using f y \\<phi>_def y\\<eta>.is_ext_def F_ide by blast\n    qed\n\n    lemma \\<phi>_invertible:\n    assumes x: \"C.ide x\" and g: \"\\<guillemotleft>g : y \\<rightarrow>\\<^sub>D G x\\<guillemotright>\"\n    shows \"\\<exists>!f. \\<guillemotleft>f : F y \\<rightarrow>\\<^sub>C x\\<guillemotright> \\<and> \\<phi> y f = g\"\n    proof\n      have y: \"D.ide y\" using g by auto\n      interpret y\\<eta>: initial_arrow_to_functor C D G y \\<open>Fo y\\<close> \\<open>\\<eta>o y\\<close>\n        using y initial_arrows_exist Fo_\\<eta>o_initial by auto\n      have 1: \"arrow_to_functor C D G y x g\"\n        using x g by (unfold_locales, auto)\n      let ?f = \"y\\<eta>.the_ext x g\"\n      have \"\\<phi> y ?f = g\"\n        using \\<phi>_def y\\<eta>.the_ext_prop 1 F_ide x y \\<phi>_inverts_ext y\\<eta>.is_ext_def by fastforce\n      moreover have \"\\<guillemotleft>?f : F y \\<rightarrow>\\<^sub>C x\\<guillemotright>\"\n        using 1 y y\\<eta>.the_ext_prop F_ide by simp\n      ultimately show \"\\<guillemotleft>?f : F y \\<rightarrow>\\<^sub>C x\\<guillemotright> \\<and> \\<phi> y ?f = g\" by auto\n      show \"\\<And>f'. \\<guillemotleft>f' : F y \\<rightarrow>\\<^sub>C x\\<guillemotright> \\<and> \\<phi> y f' = g \\<Longrightarrow> f' = ?f\"\n        using 1 y \\<phi>_inverts_ext y\\<eta>.the_ext_unique F_ide by force\n    qed\n\n    definition \\<psi>\n    where \"\\<psi> x g = (THE f. \\<guillemotleft>f : F (D.dom g) \\<rightarrow>\\<^sub>C x\\<guillemotright> \\<and> \\<phi> (D.dom g) f = g)\"\n\n    lemma \\<psi>_in_hom:\n    assumes \"C.ide x\" and \"\\<guillemotleft>g : y \\<rightarrow>\\<^sub>D G x\\<guillemotright>\"\n    shows \"C.in_hom (\\<psi> x g) (F y) x\"\n      using assms \\<phi>_invertible \\<psi>_def theI' [of \"\\<lambda>f. \\<guillemotleft>f : F y \\<rightarrow>\\<^sub>C x\\<guillemotright> \\<and> \\<phi> y f = g\"]\n      by auto\n\n    lemma \\<psi>_\\<phi>:\n    assumes \"D.ide y\" and \"\\<guillemotleft>f : F y \\<rightarrow>\\<^sub>C x\\<guillemotright>\"\n    shows \"\\<psi> x (\\<phi> y f) = f\"\n    proof -\n      have \"D.dom (\\<phi> y f) = y\" using assms \\<phi>_in_hom by blast\n      hence \"\\<psi> x (\\<phi> y f) = (THE f'. \\<guillemotleft>f' : F y \\<rightarrow>\\<^sub>C x\\<guillemotright> \\<and> \\<phi> y f' = \\<phi> y f)\"\n        using \\<psi>_def by auto\n      moreover have \"\\<exists>!f'. \\<guillemotleft>f' : F y \\<rightarrow>\\<^sub>C x\\<guillemotright> \\<and> \\<phi> y f' = \\<phi> y f\"\n        using assms \\<phi>_in_hom \\<phi>_invertible C.ide_cod by blast\n      ultimately show ?thesis using assms(2) by auto\n    qed\n\n    lemma \\<phi>_\\<psi>:\n    assumes \"C.ide x\" and \"\\<guillemotleft>g : y \\<rightarrow>\\<^sub>D G x\\<guillemotright>\"\n    shows \"\\<phi> y (\\<psi> x g) = g\"\n      using assms \\<phi>_invertible \\<psi>_def theI' [of \"\\<lambda>f. \\<guillemotleft>f : F y \\<rightarrow>\\<^sub>C x\\<guillemotright> \\<and> \\<phi> y f = g\"]\n      by auto\n\n    theorem induces_meta_adjunction:\n    shows \"meta_adjunction C D F G \\<phi> \\<psi>\"\n      using \\<phi>_in_hom \\<psi>_in_hom \\<phi>_\\<psi> \\<psi>_\\<phi> \\<phi>_natural D.comp_assoc\n      by (unfold_locales, auto)\n\n  end\n\n  section \"Meta-Adjunctions Induce Hom-Adjunctions\"\n\n  text\\<open>\n    To obtain a hom-adjunction from a meta-adjunction, we need to exhibit hom-functors\n    from @{term C} and @{term D} to a common set category @{term S}, so it is necessary\n    to apply an actual concrete construction of such a category.\n    We use the replete set category generated by the disjoint sum\n    @{typ \"('c+'d)\"} of the arrow types of @{term C} and @{term D}.\n\\<close>\n\n  context meta_adjunction\n  begin\n\n    interpretation S: replete_setcat \\<open>undefined :: 'c+'d\\<close> .\n\n    definition inC :: \"'c \\<Rightarrow> ('c+'d) setcat.arr\"\n    where \"inC \\<equiv> S.UP o Inl\"\n\n    definition inD :: \"'d \\<Rightarrow> ('c+'d) setcat.arr\"\n    where \"inD \\<equiv> S.UP o Inr\"\n\n    interpretation S: replete_setcat \\<open>undefined :: ('c+'d)\\<close> .\n    interpretation Cop: dual_category C ..\n    interpretation Dop: dual_category D ..\n    interpretation CopxC: product_category Cop.comp C ..\n    interpretation DopxD: product_category Dop.comp D ..\n    interpretation DopxC: product_category Dop.comp C ..\n    interpretation HomC: hom_functor C S.comp S.setp \\<open>\\<lambda>_. inC\\<close>\n    proof\n      show \"\\<And>f. C.arr f \\<Longrightarrow> inC f \\<in> S.Univ\"\n        unfolding inC_def using S.UP_mapsto by auto\n      thus \"\\<And>b a. \\<lbrakk>C.ide b; C.ide a\\<rbrakk> \\<Longrightarrow> inC ` C.hom b a \\<subseteq> S.Univ\"\n        by blast\n      show \"\\<And>b a. \\<lbrakk>C.ide b; C.ide a\\<rbrakk> \\<Longrightarrow> inj_on inC (C.hom b a)\"\n        unfolding inC_def\n        using S.inj_UP\n        by (metis injD inj_Inl inj_compose inj_on_def)\n    qed\n    interpretation HomD: hom_functor D S.comp S.setp \\<open>\\<lambda>_. inD\\<close>\n    proof\n      show \"\\<And>f. D.arr f \\<Longrightarrow> inD f \\<in> S.Univ\"\n        unfolding inD_def using S.UP_mapsto by auto\n      thus \"\\<And>b a. \\<lbrakk>D.ide b; D.ide a\\<rbrakk> \\<Longrightarrow> inD ` D.hom b a \\<subseteq> S.Univ\"\n        by blast\n      show \"\\<And>b a. \\<lbrakk>D.ide b; D.ide a\\<rbrakk> \\<Longrightarrow> inj_on inD (D.hom b a)\"\n        unfolding inD_def\n        using S.inj_UP\n        by (metis injD inj_Inr inj_compose inj_on_def)\n    qed\n    interpretation Fop: dual_functor D C F ..\n    interpretation FopxC: product_functor Dop.comp C Cop.comp C Fop.map C.map ..\n    interpretation DopxG: product_functor Dop.comp C Dop.comp D Dop.map G ..\n    interpretation Hom_FopxC: composite_functor DopxC.comp CopxC.comp S.comp\n                                                FopxC.map HomC.map ..\n    interpretation Hom_DopxG: composite_functor DopxC.comp DopxD.comp S.comp\n                                                DopxG.map HomD.map ..\n\n    lemma inC_\\<psi> [simp]:\n    assumes \"C.ide b\" and \"C.ide a\" and \"x \\<in> inC ` C.hom b a\"\n    shows \"inC (HomC.\\<psi> (b, a) x) = x\"\n      using assms by auto\n\n    lemma \\<psi>_inC [simp]:\n    assumes \"C.arr f\"\n    shows \"HomC.\\<psi> (C.dom f, C.cod f) (inC f) = f\"\n      using assms HomC.\\<psi>_\\<phi> by blast\n\n    lemma inD_\\<psi> [simp]:\n    assumes \"D.ide b\" and \"D.ide a\" and \"x \\<in> inD ` D.hom b a\"\n    shows \"inD (HomD.\\<psi> (b, a) x) = x\"\n      using assms by auto\n\n    lemma \\<psi>_inD [simp]:\n    assumes \"D.arr f\"\n    shows \"HomD.\\<psi> (D.dom f, D.cod f) (inD f) = f\"\n      using assms HomD.\\<psi>_\\<phi> by blast\n\n    lemma Hom_FopxC_simp:\n    assumes \"DopxC.arr gf\"\n    shows \"Hom_FopxC.map gf =\n              S.mkArr (HomC.set (F (D.cod (fst gf)), C.dom (snd gf)))\n                      (HomC.set (F (D.dom (fst gf)), C.cod (snd gf)))\n                      (inC \\<circ> (\\<lambda>h. snd gf \\<cdot>\\<^sub>C h \\<cdot>\\<^sub>C F (fst gf))\n                           \\<circ> HomC.\\<psi> (F (D.cod (fst gf)), C.dom (snd gf)))\"\n      using assms HomC.map_def by simp\n\n    lemma Hom_DopxG_simp:\n    assumes \"DopxC.arr gf\"\n    shows \"Hom_DopxG.map gf =\n              S.mkArr (HomD.set (D.cod (fst gf), G (C.dom (snd gf))))\n                      (HomD.set (D.dom (fst gf), G (C.cod (snd gf))))\n                      (inD \\<circ> (\\<lambda>h. G (snd gf) \\<cdot>\\<^sub>D h \\<cdot>\\<^sub>D fst gf)\n                           \\<circ> HomD.\\<psi> (D.cod (fst gf), G (C.dom (snd gf))))\"\n      using assms HomD.map_def by simp\n                      \n    definition \\<Phi>o\n    where \"\\<Phi>o yx = S.mkArr (HomC.set (F (fst yx), snd yx))\n                           (HomD.set (fst yx, G (snd yx)))\n                           (inD o \\<phi> (fst yx) o HomC.\\<psi> (F (fst yx), snd yx))\"\n\n    lemma \\<Phi>o_in_hom:\n    assumes yx: \"DopxC.ide yx\"\n    shows \"\\<guillemotleft>\\<Phi>o yx : Hom_FopxC.map yx \\<rightarrow>\\<^sub>S Hom_DopxG.map yx\\<guillemotright>\"\n    proof -\n      have \"Hom_FopxC.map yx = S.mkIde (HomC.set (F (fst yx), snd yx))\"\n        using yx HomC.map_ide by auto\n      moreover have \"Hom_DopxG.map yx = S.mkIde (HomD.set (fst yx, G (snd yx)))\"\n        using yx HomD.map_ide by auto\n      moreover have\n          \"\\<guillemotleft>S.mkArr (HomC.set (F (fst yx), snd yx)) (HomD.set (fst yx, G (snd yx)))\n                    (inD \\<circ> \\<phi> (fst yx) \\<circ> HomC.\\<psi> (F (fst yx), snd yx)) :\n              S.mkIde (HomC.set (F (fst yx), snd yx))\n                 \\<rightarrow>\\<^sub>S S.mkIde (HomD.set (fst yx, G (snd yx)))\\<guillemotright>\"\n      proof (intro S.mkArr_in_hom)\n        show \"HomC.set (F (fst yx), snd yx) \\<subseteq> S.Univ\" using yx HomC.set_subset_Univ by simp\n        show \"HomD.set (fst yx, G (snd yx)) \\<subseteq> S.Univ\" using yx HomD.set_subset_Univ by simp\n        show \"inD o \\<phi> (fst yx) o HomC.\\<psi> (F (fst yx), snd yx)\n                 \\<in> HomC.set (F (fst yx), snd yx) \\<rightarrow> HomD.set (fst yx, G (snd yx))\"\n        proof\n          fix x\n          assume x: \"x \\<in> HomC.set (F (fst yx), snd yx)\"\n          show \"(inD o \\<phi> (fst yx) o HomC.\\<psi> (F (fst yx), snd yx)) x\n                  \\<in> HomD.set (fst yx, G (snd yx))\"\n            using x yx HomC.\\<psi>_mapsto [of \"F (fst yx)\" \"snd yx\"]\n                  \\<phi>_in_hom [of \"fst yx\"] HomD.\\<phi>_mapsto [of \"fst yx\" \"G (snd yx)\"]\n            by auto\n        qed\n      qed\n      ultimately show ?thesis using \\<Phi>o_def by auto\n    qed\n\n    interpretation \\<Phi>: transformation_by_components\n                        DopxC.comp S.comp Hom_FopxC.map Hom_DopxG.map \\<Phi>o\n    proof\n      fix yx\n      assume yx: \"DopxC.ide yx\"\n      show \"\\<guillemotleft>\\<Phi>o yx : Hom_FopxC.map yx \\<rightarrow>\\<^sub>S Hom_DopxG.map yx\\<guillemotright>\"\n        using yx \\<Phi>o_in_hom by auto\n      next\n      fix gf\n      assume gf: \"DopxC.arr gf\"\n      show \"S.comp (\\<Phi>o (DopxC.cod gf)) (Hom_FopxC.map gf)\n                = S.comp (Hom_DopxG.map gf) (\\<Phi>o (DopxC.dom gf))\"\n      proof -\n        let ?g = \"fst gf\"\n        let ?f = \"snd gf\"\n        let ?x = \"C.dom ?f\"\n        let ?x' = \"C.cod ?f\"\n        let ?y = \"D.cod ?g\"\n        let ?y' = \"D.dom ?g\"\n        let ?Fy = \"F ?y\"\n        let ?Fy' = \"F ?y'\"\n        let ?Fg = \"F ?g\"\n        let ?Gx = \"G ?x\"\n        let ?Gx' = \"G ?x'\"\n        let ?Gf = \"G ?f\"\n        have 1: \"S.arr (Hom_FopxC.map gf) \\<and>\n                 Hom_FopxC.map gf = S.mkArr (HomC.set (?Fy, ?x)) (HomC.set (?Fy', ?x'))\n                                            (inC o (\\<lambda>h. ?f \\<cdot>\\<^sub>C h \\<cdot>\\<^sub>C ?Fg) o HomC.\\<psi> (?Fy, ?x))\"\n          using gf Hom_FopxC.preserves_arr Hom_FopxC_simp by blast\n        have 2: \"S.arr (\\<Phi>o (DopxC.cod gf)) \\<and>\n                 \\<Phi>o (DopxC.cod gf) = S.mkArr (HomC.set (?Fy', ?x')) (HomD.set (?y', ?Gx'))\n                                             (inD o \\<phi> ?y' o HomC.\\<psi> (?Fy', ?x'))\"\n          using gf \\<Phi>o_in_hom [of \"DopxC.cod gf\"] \\<Phi>o_def [of \"DopxC.cod gf\"] \\<phi>_in_hom\n          by auto\n        have 3: \"S.arr (\\<Phi>o (DopxC.dom gf)) \\<and>\n                 \\<Phi>o (DopxC.dom gf) = S.mkArr (HomC.set (?Fy, ?x)) (HomD.set (?y, ?Gx))\n                                             (inD o \\<phi> ?y o HomC.\\<psi> (?Fy, ?x))\"\n          using gf \\<Phi>o_in_hom [of \"DopxC.dom gf\"] \\<Phi>o_def [of \"DopxC.dom gf\"] \\<phi>_in_hom\n          by auto\n        have 4: \"S.arr (Hom_DopxG.map gf) \\<and>\n                 Hom_DopxG.map gf = S.mkArr (HomD.set (?y, ?Gx)) (HomD.set (?y', ?Gx'))\n                                            (inD o (\\<lambda>h. ?Gf \\<cdot>\\<^sub>D h \\<cdot>\\<^sub>D ?g) o HomD.\\<psi> (?y, ?Gx))\"\n          using gf Hom_DopxG.preserves_arr Hom_DopxG_simp by blast\n        have 5: \"S.seq (\\<Phi>o (DopxC.cod gf)) (Hom_FopxC.map gf) \\<and>\n                 S.comp (\\<Phi>o (DopxC.cod gf)) (Hom_FopxC.map gf)\n                     = S.mkArr (HomC.set (?Fy, ?x)) (HomD.set (?y', ?Gx'))\n                               ((inD o \\<phi> ?y' o HomC.\\<psi> (?Fy', ?x'))\n                                 o (inC o (\\<lambda>h. ?f \\<cdot>\\<^sub>C h \\<cdot>\\<^sub>C ?Fg) o HomC.\\<psi> (?Fy, ?x)))\"\n          by (metis gf 1 2 DopxC.arr_iff_in_hom DopxC.ide_cod Hom_FopxC.preserves_hom\n                    S.comp_mkArr S.seqI' \\<Phi>o_in_hom)\n        have 6: \"S.comp (Hom_DopxG.map gf) (\\<Phi>o (DopxC.dom gf))\n                  = S.mkArr (HomC.set (?Fy, ?x)) (HomD.set (?y', ?Gx'))\n                            ((inD o (\\<lambda>h. ?Gf \\<cdot>\\<^sub>D h \\<cdot>\\<^sub>D ?g) o HomD.\\<psi> (?y, ?Gx))\n                              o (inD o \\<phi> ?y o HomC.\\<psi> (?Fy, ?x)))\"\n          by (metis 3 4 S.comp_mkArr)\n        have 7:\n          \"restrict ((inD o \\<phi> ?y' o HomC.\\<psi> (?Fy', ?x'))\n                      o (inC o (\\<lambda>h. ?f \\<cdot>\\<^sub>C h \\<cdot>\\<^sub>C ?Fg) o HomC.\\<psi> (?Fy, ?x))) (HomC.set (?Fy, ?x))\n             = restrict ((inD o (\\<lambda>h. ?Gf \\<cdot>\\<^sub>D h \\<cdot>\\<^sub>D ?g) o HomD.\\<psi> (?y, ?Gx))\n                          o (inD o \\<phi> ?y o HomC.\\<psi> (?Fy, ?x))) (HomC.set (?Fy, ?x))\"\n        proof (intro restrict_ext)\n          show \"\\<And>h. h \\<in> HomC.set (?Fy, ?x) \\<Longrightarrow>\n                     ((inD o \\<phi> ?y' o HomC.\\<psi> (?Fy', ?x'))\n                       o (inC o (\\<lambda>h. ?f \\<cdot>\\<^sub>C h \\<cdot>\\<^sub>C ?Fg) o HomC.\\<psi> (?Fy, ?x))) h\n                       = ((inD o (\\<lambda>h. ?Gf \\<cdot>\\<^sub>D h \\<cdot>\\<^sub>D ?g) o HomD.\\<psi> (?y, ?Gx))\n                           o (inD o \\<phi> ?y o HomC.\\<psi> (?Fy, ?x))) h\"\n          proof -\n            fix h\n            assume h: \"h \\<in> HomC.set (?Fy, ?x)\"\n            have \\<psi>h: \"\\<guillemotleft>HomC.\\<psi> (?Fy, ?x) h : ?Fy \\<rightarrow>\\<^sub>C ?x\\<guillemotright>\"\n              using gf h HomC.\\<psi>_mapsto [of ?Fy ?x] CopxC.ide_char by auto\n            show \"((inD o \\<phi> ?y' o HomC.\\<psi> (?Fy', ?x'))\n                       o (inC o (\\<lambda>h. ?f \\<cdot>\\<^sub>C h \\<cdot>\\<^sub>C ?Fg) o HomC.\\<psi> (?Fy, ?x))) h\n                       = ((inD o (\\<lambda>h. ?Gf \\<cdot>\\<^sub>D h \\<cdot>\\<^sub>D ?g) o HomD.\\<psi> (?y, ?Gx))\n                           o (inD o \\<phi> ?y o HomC.\\<psi> (?Fy, ?x))) h\"\n            proof -\n              have\n                \"((inD o \\<phi> ?y' o HomC.\\<psi> (?Fy', ?x'))\n                   o (inC o (\\<lambda>h. ?f \\<cdot>\\<^sub>C h \\<cdot>\\<^sub>C ?Fg) o HomC.\\<psi> (?Fy, ?x))) h\n                   = inD (\\<phi> ?y' (?f \\<cdot>\\<^sub>C HomC.\\<psi> (?Fy, ?x) h \\<cdot>\\<^sub>C ?Fg))\"\n                using gf \\<psi>h HomC.\\<phi>_mapsto HomC.\\<psi>_mapsto \\<phi>_in_hom\n                      \\<psi>_inC [of \"?f \\<cdot>\\<^sub>C HomC.\\<psi> (?Fy, ?x) h \\<cdot>\\<^sub>C ?Fg\"]\n                by auto\n              also have \"... = inD (D ?Gf (D (\\<phi> ?y (HomC.\\<psi> (?Fy, ?x) h)) ?g))\"\n                by (metis (no_types, lifting) C.arr_cod C.arr_dom_iff_arr C.arr_iff_in_hom\n                    C.in_homE D.arr_cod_iff_arr D.arr_iff_in_hom F.preserves_reflects_arr\n                    \\<phi>_naturality \\<psi>h)\n              also have \"... = ((inD o (\\<lambda>h. ?Gf \\<cdot>\\<^sub>D h \\<cdot>\\<^sub>D ?g) o HomD.\\<psi> (?y, ?Gx))\n                                o (inD o \\<phi> ?y o HomC.\\<psi> (?Fy, ?x))) h\"\n                using gf \\<psi>h \\<phi>_in_hom by simp\n              finally show ?thesis by auto\n            qed\n          qed\n        qed\n        have 8: \"S.mkArr (HomC.set (?Fy, ?x)) (HomD.set (?y', ?Gx'))\n                         ((inD o \\<phi> ?y' o HomC.\\<psi> (?Fy', ?x'))\n                           o (inC o (\\<lambda>h. ?f \\<cdot>\\<^sub>C h \\<cdot>\\<^sub>C ?Fg) o HomC.\\<psi> (?Fy, ?x)))\n                    = S.mkArr (HomC.set (?Fy, ?x)) (HomD.set (?y', ?Gx'))\n                              ((inD o (\\<lambda>h. ?Gf \\<cdot>\\<^sub>D h \\<cdot>\\<^sub>D ?g) o HomD.\\<psi> (?y, ?Gx))\n                                o (inD o \\<phi> ?y o HomC.\\<psi> (?Fy, ?x)))\"\n          using 5 7 by force\n        show ?thesis using 5 6 8 by auto\n      qed\n    qed\n\n    lemma \\<Phi>_simp:\n    assumes YX: \"DopxC.ide yx\"\n    shows \"\\<Phi>.map yx =\n           S.mkArr (HomC.set (F (fst yx), snd yx)) (HomD.set (fst yx, G (snd yx)))\n                   (inD o \\<phi> (fst yx) o HomC.\\<psi> (F (fst yx), snd yx))\"\n      using YX \\<Phi>o_def by simp\n      \n    abbreviation \\<Psi>o\n    where \"\\<Psi>o yx \\<equiv> S.mkArr (HomD.set (fst yx, G (snd yx))) (HomC.set (F (fst yx), snd yx))\n                            (inC o \\<psi> (snd yx) o HomD.\\<psi> (fst yx, G (snd yx)))\"\n\n    lemma \\<Psi>o_in_hom:\n    assumes yx: \"DopxC.ide yx\"\n    shows \"\\<guillemotleft>\\<Psi>o yx : Hom_DopxG.map yx \\<rightarrow>\\<^sub>S Hom_FopxC.map yx\\<guillemotright>\"\n    proof -\n      have \"Hom_FopxC.map yx = S.mkIde (HomC.set (F (fst yx), snd yx))\"\n        using yx HomC.map_ide by auto\n      moreover have \"Hom_DopxG.map yx = S.mkIde (HomD.set (fst yx, G (snd yx)))\"\n        using yx HomD.map_ide by auto\n      moreover have \"\\<guillemotleft>\\<Psi>o yx : S.mkIde (HomD.set (fst yx, G (snd yx)))\n                                 \\<rightarrow>\\<^sub>S S.mkIde (HomC.set (F (fst yx), snd yx))\\<guillemotright>\"\n      proof (intro S.mkArr_in_hom)\n        show \"HomC.set (F (fst yx), snd yx) \\<subseteq> S.Univ\" using yx HomC.set_subset_Univ by simp\n        show \"HomD.set (fst yx, G (snd yx)) \\<subseteq> S.Univ\" using yx HomD.set_subset_Univ by simp\n        show \"inC o \\<psi> (snd yx) o HomD.\\<psi> (fst yx, G (snd yx))\n                 \\<in> HomD.set (fst yx, G (snd yx)) \\<rightarrow> HomC.set (F (fst yx), snd yx)\"\n        proof\n          fix x\n          assume x: \"x \\<in> HomD.set (fst yx, G (snd yx))\"\n          show \"(inC o \\<psi> (snd yx) o HomD.\\<psi> (fst yx, G (snd yx))) x\n                  \\<in> HomC.set (F (fst yx), snd yx)\"\n            using x yx HomD.\\<psi>_mapsto [of \"fst yx\" \"G (snd yx)\"] \\<psi>_in_hom [of \"snd yx\"]\n                  HomC.\\<phi>_mapsto [of \"F (fst yx)\" \"snd yx\"]\n            by auto\n        qed\n      qed\n      ultimately show ?thesis by auto\n    qed\n\n    lemma \\<Phi>_inv:\n    assumes yx: \"DopxC.ide yx\"\n    shows \"S.inverse_arrows (\\<Phi>.map yx) (\\<Psi>o yx)\"\n    proof -\n      have 1: \"\\<guillemotleft>\\<Phi>.map yx : Hom_FopxC.map yx \\<rightarrow>\\<^sub>S Hom_DopxG.map yx\\<guillemotright>\"\n        using yx \\<Phi>.preserves_hom [of yx yx yx] DopxC.ide_in_hom by blast\n      have 2: \"\\<guillemotleft>\\<Psi>o yx : Hom_DopxG.map yx \\<rightarrow>\\<^sub>S Hom_FopxC.map yx\\<guillemotright>\"\n        using yx \\<Psi>o_in_hom by simp\n      have 3: \"\\<Phi>.map yx = S.mkArr (HomC.set (F (fst yx), snd yx))\n                                   (HomD.set (fst yx, G (snd yx)))\n                                   (inD o \\<phi> (fst yx) o HomC.\\<psi> (F (fst yx), snd yx))\"\n        using yx \\<Phi>_simp by blast\n      have antipar: \"S.antipar (\\<Phi>.map yx) (\\<Psi>o yx)\"\n        using 1 2 by blast\n      moreover have \"S.ide (S.comp (\\<Psi>o yx) (\\<Phi>.map yx))\"\n      proof -\n        have \"S.comp (\\<Psi>o yx) (\\<Phi>.map yx) =\n                  S.mkArr (HomC.set (F (fst yx), snd yx)) (HomC.set (F (fst yx), snd yx))\n                          ((inC o \\<psi> (snd yx) o HomD.\\<psi> (fst yx, G (snd yx)))\n                            o (inD o \\<phi> (fst yx) o HomC.\\<psi> (F (fst yx), snd yx)))\"\n          using 1 2 3 antipar S.comp_mkArr by auto\n        also have\n          \"... = S.mkArr (HomC.set (F (fst yx), snd yx)) (HomC.set (F (fst yx), snd yx))\n                         (\\<lambda>x. x)\"\n        proof -\n          have\n            \"S.mkArr (HomC.set (F (fst yx), snd yx)) (HomC.set (F (fst yx), snd yx)) (\\<lambda>x. x)\n               = ...\"\n          proof\n            show\n              \"S.arr (S.mkArr (HomC.set (F (fst yx), snd yx)) (HomC.set (F (fst yx), snd yx))\n                     (\\<lambda>x. x))\"\n              using yx HomC.set_subset_Univ by simp\n            show \"\\<And>x. x \\<in> HomC.set (F (fst yx), snd yx) \\<Longrightarrow>\n                        x = ((inC o \\<psi> (snd yx) o HomD.\\<psi> (fst yx, G (snd yx)))\n                             o (inD o \\<phi> (fst yx) o HomC.\\<psi> (F (fst yx), snd yx))) x\"\n            proof -\n              fix x\n              assume x: \"x \\<in> HomC.set (F (fst yx), snd yx)\"\n              have \"((inC o \\<psi> (snd yx) o HomD.\\<psi> (fst yx, G (snd yx)))\n                             o (inD o \\<phi> (fst yx) o HomC.\\<psi> (F (fst yx), snd yx))) x\n                      = inC (\\<psi> (snd yx) (HomD.\\<psi> (fst yx, G (snd yx))\n                              (inD (\\<phi> (fst yx) (HomC.\\<psi> (F (fst yx), snd yx) x)))))\"\n                by simp\n              also have \"... = inC (\\<psi> (snd yx) (\\<phi> (fst yx) (HomC.\\<psi> (F (fst yx), snd yx) x)))\"\n                using x yx HomC.\\<psi>_mapsto [of \"F (fst yx)\" \"snd yx\"] \\<phi>_in_hom by force\n              also have \"... = inC (HomC.\\<psi> (F (fst yx), snd yx) x)\"\n                using x yx HomC.\\<psi>_mapsto [of \"F (fst yx)\" \"snd yx\"] \\<psi>_\\<phi> by force\n              also have \"... = x\" using x yx inC_\\<psi> by simp\n              finally show \"x = ((inC o \\<psi> (snd yx) o HomD.\\<psi> (fst yx, G (snd yx)))\n                                   o (inD o \\<phi> (fst yx) o HomC.\\<psi> (F (fst yx), snd yx))) x\"\n                by auto\n            qed\n          qed\n          thus ?thesis by auto\n        qed\n        also have \"... = S.mkIde (HomC.set (F (fst yx), snd yx))\"\n          using yx S.mkIde_as_mkArr HomC.set_subset_Univ by force\n        finally have\n            \"S.comp (\\<Psi>o yx) (\\<Phi>.map yx) = S.mkIde (HomC.set (F (fst yx), snd yx))\"\n          by auto\n        thus ?thesis using yx HomC.set_subset_Univ S.ide_mkIde by simp\n      qed\n      moreover have \"S.ide (S.comp (\\<Phi>.map yx) (\\<Psi>o yx))\"\n      proof -\n        have \"S.comp (\\<Phi>.map yx) (\\<Psi>o yx) =\n                  S.mkArr (HomD.set (fst yx, G (snd yx))) (HomD.set (fst yx, G (snd yx)))\n                          ((inD o \\<phi> (fst yx) o HomC.\\<psi> (F (fst yx), snd yx))\n                            o (inC o \\<psi> (snd yx) o HomD.\\<psi> (fst yx, G (snd yx))))\"\n          using 1 2 3 S.comp_mkArr antipar by fastforce\n        also\n          have \"... = S.mkArr (HomD.set (fst yx, G (snd yx))) (HomD.set (fst yx, G (snd yx)))\n                              (\\<lambda>x. x)\"\n        proof -\n          have\n            \"S.mkArr (HomD.set (fst yx, G (snd yx))) (HomD.set (fst yx, G (snd yx))) (\\<lambda>x. x)\n                = ...\"\n          proof\n            show\n              \"S.arr (S.mkArr (HomD.set (fst yx, G (snd yx))) (HomD.set (fst yx, G (snd yx)))\n                     (\\<lambda>x. x))\"\n              using yx HomD.set_subset_Univ by simp\n            show \"\\<And>x. x \\<in> (HomD.set (fst yx, G (snd yx))) \\<Longrightarrow>\n                        x = ((inD o \\<phi> (fst yx) o HomC.\\<psi> (F (fst yx), snd yx))\n                            o (inC o \\<psi> (snd yx) o HomD.\\<psi> (fst yx, G (snd yx)))) x\"\n            proof -\n              fix x\n              assume x: \"x \\<in> HomD.set (fst yx, G (snd yx))\"\n              have \"((inD o \\<phi> (fst yx) o HomC.\\<psi> (F (fst yx), snd yx))\n                          o (inC o \\<psi> (snd yx) o HomD.\\<psi> (fst yx, G (snd yx)))) x\n                       = inD (\\<phi> (fst yx) (HomC.\\<psi> (F (fst yx), snd yx)\n                            (inC (\\<psi> (snd yx) (HomD.\\<psi> (fst yx, G (snd yx)) x)))))\"\n                by simp\n              also have \"... = inD (\\<phi> (fst yx) (\\<psi> (snd yx) (HomD.\\<psi> (fst yx, G (snd yx)) x)))\"\n              proof -\n                have \"\\<guillemotleft>\\<psi> (snd yx) (HomD.\\<psi> (fst yx, G (snd yx)) x) : F (fst yx) \\<rightarrow> snd yx\\<guillemotright>\"\n                  using x yx HomD.\\<psi>_mapsto [of \"fst yx\" \"G (snd yx)\"] \\<psi>_in_hom by auto\n                thus ?thesis by simp\n              qed\n              also have \"... = inD (HomD.\\<psi> (fst yx, G (snd yx)) x)\"\n                using x yx HomD.\\<psi>_mapsto [of \"fst yx\" \"G (snd yx)\"] \\<phi>_\\<psi> by force\n              also have \"... = x\" using x yx inD_\\<psi> by simp\n              finally show \"x = ((inD o \\<phi> (fst yx) o HomC.\\<psi> (F (fst yx), snd yx))\n                                   o (inC o \\<psi> (snd yx) o HomD.\\<psi> (fst yx, G (snd yx)))) x\"\n                by auto\n            qed\n          qed\n          thus ?thesis by auto\n        qed\n        also have \"... = S.mkIde (HomD.set (fst yx, G (snd yx)))\"\n          using yx S.mkIde_as_mkArr HomD.set_subset_Univ by force\n        finally have\n            \"S.comp (\\<Phi>.map yx) (\\<Psi>o yx) = S.mkIde (HomD.set (fst yx, G (snd yx)))\"\n          by auto\n        thus ?thesis using yx HomD.set_subset_Univ S.ide_mkIde by simp\n      qed\n      ultimately show ?thesis by auto\n    qed\n\n    interpretation \\<Phi>: natural_isomorphism DopxC.comp S.comp\n                                          Hom_FopxC.map Hom_DopxG.map \\<Phi>.map\n      using \\<Phi>_inv by unfold_locales blast\n\n    interpretation \\<Psi>: inverse_transformation DopxC.comp S.comp\n                           Hom_FopxC.map Hom_DopxG.map \\<Phi>.map ..\n\n    interpretation \\<Phi>\\<Psi>: inverse_transformations DopxC.comp S.comp\n                           Hom_FopxC.map Hom_DopxG.map \\<Phi>.map \\<Psi>.map\n      using \\<Psi>.inverts_components by unfold_locales simp\n\n    abbreviation \\<Phi> where \"\\<Phi> \\<equiv> \\<Phi>.map\"\n    abbreviation \\<Psi> where \"\\<Psi> \\<equiv> \\<Psi>.map\"\n\n    abbreviation HomC where \"HomC \\<equiv> HomC.map\"\n    abbreviation \\<phi>C where \"\\<phi>C \\<equiv> \\<lambda>_. inC\"\n    abbreviation HomD where \"HomD \\<equiv> HomD.map\"\n    abbreviation \\<phi>D where \"\\<phi>D \\<equiv> \\<lambda>_. inD\"\n\n    theorem induces_hom_adjunction: \"hom_adjunction C D S.comp S.setp \\<phi>C \\<phi>D F G \\<Phi> \\<Psi>\"\n      using F.is_extensional by unfold_locales auto\n\n    lemma \\<Psi>_simp:\n    assumes yx: \"DopxC.ide yx\"\n    shows \"\\<Psi> yx = S.mkArr (HomD.set (fst yx, G (snd yx))) (HomC.set (F (fst yx), snd yx))\n                          (inC o \\<psi> (snd yx) o HomD.\\<psi> (fst yx, G (snd yx)))\"\n      using assms \\<Phi>o_def \\<Phi>_inv S.inverse_unique by simp\n\n    text\\<open>\n      The original @{term \\<phi>} and @{term \\<psi>} can be recovered from @{term \\<Phi>} and @{term \\<Psi>}.\n\\<close>\n\n    interpretation \\<Phi>: set_valued_transformation DopxC.comp S.comp S.setp\n                                                Hom_FopxC.map Hom_DopxG.map \\<Phi>.map ..\n     \n    interpretation \\<Psi>: set_valued_transformation DopxC.comp S.comp S.setp\n                                                Hom_DopxG.map Hom_FopxC.map \\<Psi>.map ..\n\n    lemma \\<phi>_in_terms_of_\\<Phi>':\n    assumes y: \"D.ide y\" and f: \"\\<guillemotleft>f: F y \\<rightarrow>\\<^sub>C x\\<guillemotright>\"\n    shows \"\\<phi> y f = (HomD.\\<psi> (y, G x) o \\<Phi>.FUN (y, x) o inC) f\"\n    proof -\n      have x: \"C.ide x\" using f by auto\n      have \"(HomD.\\<psi> (y, G x) o \\<Phi>.FUN (y, x) o inC) f =\n              HomD.\\<psi> (y, G x)\n                     (restrict (inD o \\<phi> y o HomC.\\<psi> (F y, x)) (HomC.set (F y, x)) (inC f))\"\n      proof -\n        have \"S.arr (\\<Phi> (y, x))\" using x y by fastforce\n        thus ?thesis\n          using x y \\<Phi>o_def by simp\n      qed\n      also have \"... = \\<phi> y f\"\n        using x y f HomC.\\<phi>_mapsto \\<phi>_in_hom HomC.\\<psi>_mapsto C.ide_in_hom D.ide_in_hom\n        by auto\n      finally show ?thesis by auto\n    qed\n\n    lemma \\<psi>_in_terms_of_\\<Psi>':\n    assumes x: \"C.ide x\" and g: \"\\<guillemotleft>g : y \\<rightarrow>\\<^sub>D G x\\<guillemotright>\"\n    shows \"\\<psi> x g = (HomC.\\<psi> (F y, x) o \\<Psi>.FUN (y, x) o inD) g\"\n    proof -\n      have y: \"D.ide y\" using g by auto\n      have \"(HomC.\\<psi> (F y, x) o \\<Psi>.FUN (y, x) o inD) g =\n              HomC.\\<psi> (F y, x)\n                     (restrict (inC o \\<psi> x o HomD.\\<psi> (y, G x)) (HomD.set (y, G x)) (inD g))\"\n      proof -\n        have \"S.arr (\\<Psi> (y, x))\"\n          using x y \\<Psi>.preserves_reflects_arr [of \"(y, x)\"] by simp\n        thus ?thesis\n          using x y \\<Psi>_simp by simp\n      qed\n      also have \"... = \\<psi> x g\"\n        using x y g HomD.\\<phi>_mapsto \\<psi>_in_hom HomD.\\<psi>_mapsto C.ide_in_hom D.ide_in_hom\n        by auto\n      finally show ?thesis by auto\n    qed\n\n  end\n\n  section \"Hom-Adjunctions Induce Meta-Adjunctions\"\n\n  context hom_adjunction\n  begin\n\n    definition \\<phi> :: \"'d \\<Rightarrow> 'c \\<Rightarrow> 'd\"\n    where\n      \"\\<phi> y h = (HomD.\\<psi> (y, G (C.cod h)) o \\<Phi>.FUN (y, C.cod h) o \\<phi>C (F y, C.cod h)) h\"\n    \n    definition \\<psi> :: \"'c \\<Rightarrow> 'd \\<Rightarrow> 'c\"\n    where\n      \"\\<psi> x h = (HomC.\\<psi> (F (D.dom h), x) o \\<Psi>.FUN (D.dom h, x) o \\<phi>D (D.dom h, G x)) h\"\n\n    lemma Hom_FopxC_map_simp:\n    assumes \"DopxC.arr gf\"\n    shows \"Hom_FopxC.map gf =\n              S.mkArr (HomC.set (F (D.cod (fst gf)), C.dom (snd gf)))\n                      (HomC.set (F (D.dom (fst gf)), C.cod (snd gf)))            \n                      (\\<phi>C (F (D.dom (fst gf)), C.cod (snd gf))\n                           o (\\<lambda>h. snd gf \\<cdot>\\<^sub>C h \\<cdot>\\<^sub>C F (fst gf))\n                           o HomC.\\<psi> (F (D.cod (fst gf)), C.dom (snd gf)))\"\n      using assms HomC.map_def by simp\n\n    lemma Hom_DopxG_map_simp:\n    assumes \"DopxC.arr gf\"\n    shows \"Hom_DopxG.map gf =\n              S.mkArr (HomD.set (D.cod (fst gf), G (C.dom (snd gf))))\n                      (HomD.set (D.dom (fst gf), G (C.cod (snd gf))))           \n                      (\\<phi>D (D.dom (fst gf), G (C.cod (snd gf)))\n                           o (\\<lambda>h. G (snd gf) \\<cdot>\\<^sub>D h \\<cdot>\\<^sub>D fst gf)\n                           o HomD.\\<psi> (D.cod (fst gf), G (C.dom (snd gf))))\"\n      using assms HomD.map_def by simp\n                      \n    lemma \\<Phi>_Fun_mapsto:\n    assumes \"D.ide y\" and \"\\<guillemotleft>f : F y \\<rightarrow>\\<^sub>C x\\<guillemotright>\"\n    shows \"\\<Phi>.FUN (y, x) \\<in> HomC.set (F y, x) \\<rightarrow> HomD.set (y, G x)\"\n    proof -\n      have \"S.arr (\\<Phi> (y, x)) \\<and> \\<Phi>.DOM (y, x) = HomC.set (F y, x) \\<and>\n                                \\<Phi>.COD (y, x) = HomD.set (y, G x)\"\n        using assms HomC.set_map HomD.set_map by auto\n      thus ?thesis using S.Fun_mapsto by blast\n    qed\n\n    lemma \\<phi>_mapsto:\n    assumes y: \"D.ide y\"\n    shows \"\\<phi> y \\<in> C.hom (F y) x \\<rightarrow> D.hom y (G x)\"\n    proof\n      fix h\n      assume h: \"h \\<in> C.hom (F y) x\"\n      hence 1: \" \\<guillemotleft>h : F y \\<rightarrow>\\<^sub>C x\\<guillemotright>\" by simp\n      show \"\\<phi> y h \\<in> D.hom y (G x)\"\n      proof -\n        have \"\\<phi>C (F y, x) h \\<in> HomC.set (F y, x)\"\n          using y h 1 HomC.\\<phi>_mapsto [of \"F y\" x] by fastforce\n        hence \"\\<Phi>.FUN (y, x) (\\<phi>C (F y, x) h) \\<in> HomD.set (y, G x)\"\n          using h y \\<Phi>_Fun_mapsto by auto\n        thus ?thesis\n          using y h 1 \\<phi>_def HomC.\\<phi>_mapsto HomD.\\<psi>_mapsto [of y \"G x\"] by fastforce\n      qed\n    qed\n\n    lemma \\<Phi>_simp:\n    assumes \"D.ide y\" and \"C.ide x\"\n    shows \"S.arr (\\<Phi> (y, x))\"\n    and \"\\<Phi> (y, x) = S.mkArr (HomC.set (F y, x)) (HomD.set (y, G x))\n                            (\\<phi>D (y, G x) o \\<phi> y o \\<psi>C (F y, x))\"\n    proof -\n      show 1: \"S.arr (\\<Phi> (y, x))\" using assms by auto\n      hence \"\\<Phi> (y, x) = S.mkArr (\\<Phi>.DOM (y, x)) (\\<Phi>.COD (y, x)) (\\<Phi>.FUN (y, x))\"\n        using S.mkArr_Fun by metis\n      also have \"... = S.mkArr (HomC.set (F y, x)) (HomD.set (y, G x)) (\\<Phi>.FUN (y, x))\"\n        using assms HomC.set_map HomD.set_map by fastforce\n      also have \"... = S.mkArr (HomC.set (F y, x)) (HomD.set (y, G x))\n                               (\\<phi>D (y, G x) o \\<phi> y o \\<psi>C (F y, x))\"\n      proof (intro S.mkArr_eqI')\n        show 2: \"S.arr (S.mkArr (HomC.set (F y, x)) (HomD.set (y, G x)) (\\<Phi>.FUN (y, x)))\"\n          using 1 calculation by argo\n        show \"\\<And>h. h \\<in> HomC.set (F y, x) \\<Longrightarrow>\n                    \\<Phi>.FUN (y, x) h = (\\<phi>D (y, G x) o \\<phi> y o \\<psi>C (F y, x)) h\"\n        proof -\n          fix h\n          assume h: \"h \\<in> HomC.set (F y, x)\"\n          have \"(\\<phi>D (y, G x) o \\<phi> y o HomC.\\<psi> (F y, x)) h =\n                   \\<phi>D (y, G x) (\\<psi>D (y, G x) (\\<Phi>.FUN (y, x) (\\<phi>C (F y, x) (\\<psi>C (F y, x) h))))\"\n          proof -\n            have \"\\<guillemotleft>\\<psi>C (F y, x) h : F y \\<rightarrow>\\<^sub>C x\\<guillemotright>\"\n              using assms h HomC.\\<psi>_mapsto [of \"F y\" x] by auto\n            thus ?thesis\n              using h \\<phi>_def by auto\n          qed\n          also have \"... = \\<phi>D (y, G x) (\\<psi>D (y, G x) (\\<Phi>.FUN (y, x) h))\"\n            using assms h HomC.\\<phi>_\\<psi> \\<Phi>_Fun_mapsto by simp\n          also have \"... = \\<Phi>.FUN (y, x) h\"\n            using assms h \\<Phi>_Fun_mapsto [of y \"\\<psi>C (F y, x) h\"] HomC.\\<psi>_mapsto\n                  HomD.\\<phi>_\\<psi> [of y \"G x\"] C.ide_in_hom D.ide_in_hom\n            by blast\n          finally show \"\\<Phi>.FUN (y, x) h = (\\<phi>D (y, G x) o \\<phi> y o \\<psi>C (F y, x)) h\" by auto\n        qed\n      qed\n      finally show \"\\<Phi> (y, x) = S.mkArr (HomC.set (F y, x)) (HomD.set (y, G x))\n                                       (\\<phi>D (y, G x) o \\<phi> y o \\<psi>C (F y, x))\"\n        by force\n    qed\n\n    lemma \\<Psi>_Fun_mapsto:\n    assumes \"C.ide x\" and \"\\<guillemotleft>g : y \\<rightarrow>\\<^sub>D G x\\<guillemotright>\"\n    shows \"\\<Psi>.FUN (y, x) \\<in> HomD.set (y, G x) \\<rightarrow> HomC.set (F y, x)\"\n    proof -\n      have \"S.arr (\\<Psi> (y, x)) \\<and> \\<Psi>.COD (y, x) = HomC.set (F y, x) \\<and>\n                                \\<Psi>.DOM (y, x) = HomD.set (y, G x)\"\n        using assms HomC.set_map HomD.set_map by auto\n      thus ?thesis using S.Fun_mapsto by fast\n    qed\n\n    lemma \\<psi>_mapsto:\n    assumes x: \"C.ide x\"\n    shows \"\\<psi> x \\<in> D.hom y (G x) \\<rightarrow> C.hom (F y) x\"\n    proof\n      fix h\n      assume h: \"h \\<in> D.hom y (G x)\"\n      hence 1: \"\\<guillemotleft>h : y \\<rightarrow>\\<^sub>D G x\\<guillemotright>\" by auto\n      show \"\\<psi> x h \\<in> C.hom (F y) x\"\n      proof -\n        have \"\\<Psi>.FUN (y, x) (\\<phi>D (y, G x) h) \\<in> HomC.set (F y, x)\"\n        proof -\n          have \"\\<phi>D (y, G x) h \\<in> HomD.set (y, G x)\"\n            using x h 1 HomD.\\<phi>_mapsto [of y \"G x\"] by fastforce\n          thus ?thesis\n            using h x \\<Psi>_Fun_mapsto by auto\n        qed\n        thus ?thesis\n          using x h 1 \\<psi>_def HomD.\\<phi>_mapsto HomC.\\<psi>_mapsto [of \"F y\" x] by fastforce\n      qed\n    qed\n\n    lemma \\<Psi>_simp:\n    assumes \"D.ide y\" and \"C.ide x\"\n    shows \"S.arr (\\<Psi> (y, x))\"\n    and \"\\<Psi> (y, x) = S.mkArr (HomD.set (y, G x)) (HomC.set (F y, x))\n                            (\\<phi>C (F y, x) o \\<psi> x o \\<psi>D (y, G x))\"\n    proof -\n      show 1: \"S.arr (\\<Psi> (y, x))\" using assms by auto\n      hence \"\\<Psi> (y, x) = S.mkArr (\\<Psi>.DOM (y, x)) (\\<Psi>.COD (y, x)) (\\<Psi>.FUN (y, x))\"\n        using S.mkArr_Fun by metis\n      also have \"... = S.mkArr (HomD.set (y, G x)) (HomC.set (F y, x)) (\\<Psi>.FUN (y, x))\"\n        using assms HomC.set_map HomD.set_map by auto\n      also have \"... = S.mkArr (HomD.set (y, G x)) (HomC.set (F y, x))\n                               (\\<phi>C (F y, x) o \\<psi> x o \\<psi>D (y, G x))\"\n      proof (intro S.mkArr_eqI')\n        show \"S.arr (S.mkArr (HomD.set (y, G x)) (HomC.set (F y, x)) (\\<Psi>.FUN (y, x)))\"\n          using 1 calculation by argo\n        show \"\\<And>h. h \\<in> HomD.set (y, G x) \\<Longrightarrow>\n                    \\<Psi>.FUN (y, x) h = (\\<phi>C (F y, x) o \\<psi> x o \\<psi>D (y, G x)) h\"\n        proof -\n          fix h\n          assume h: \"h \\<in> HomD.set (y, G x)\"\n          have \"(\\<phi>C (F y, x) o \\<psi> x o HomD.\\<psi> (y, G x)) h =\n                   \\<phi>C (F y, x) (\\<psi>C (F y, x) (\\<Psi>.FUN (y, x) (\\<phi>D (y, G x) (\\<psi>D (y, G x) h))))\"\n          proof -\n            have \"\\<guillemotleft>\\<psi>D (y, G x) h : y \\<rightarrow>\\<^sub>D G x\\<guillemotright>\"\n              using assms h HomD.\\<psi>_mapsto [of y \"G x\"] by auto\n            thus ?thesis\n              using h \\<psi>_def by auto\n          qed\n          also have \"... = \\<phi>C (F y, x) (\\<psi>C (F y, x) (\\<Psi>.FUN (y, x) h))\"\n            using assms h HomD.\\<phi>_\\<psi> \\<Psi>_Fun_mapsto by simp\n          also have \"... = \\<Psi>.FUN (y, x) h\"\n            using assms h \\<Psi>_Fun_mapsto HomD.\\<psi>_mapsto [of y \"G x\"] HomC.\\<phi>_\\<psi> [of \"F y\" x]\n                  C.ide_in_hom D.ide_in_hom\n            by blast\n          finally show \"\\<Psi>.FUN (y, x) h = (\\<phi>C (F y, x) o \\<psi> x o HomD.\\<psi> (y, G x)) h\" by auto\n        qed\n      qed\n      finally show \"\\<Psi> (y, x) = S.mkArr (HomD.set (y, G x)) (HomC.set (F y, x))\n                                       (\\<phi>C (F y, x) o \\<psi> x o \\<psi>D (y, G x))\"\n        by force\n    qed\n\n    text\\<open>\n      The length of the next proof stems from having to use properties of composition\n      of arrows in @{term[source=true] S} to infer properties of the composition of the\n      corresponding functions.\n\\<close>\n\n    interpretation \\<phi>\\<psi>: meta_adjunction C D F G \\<phi> \\<psi>\n    proof\n      fix y :: 'd and x :: 'c and h :: 'c\n      assume y: \"D.ide y\" and h: \"\\<guillemotleft>h : F y \\<rightarrow>\\<^sub>C x\\<guillemotright>\"\n      have x: \"C.ide x\" using h by auto\n      show \"\\<guillemotleft>\\<phi> y h : y \\<rightarrow>\\<^sub>D G x\\<guillemotright>\"\n      proof -\n        have \"\\<Phi>.FUN (y, x) \\<in> HomC.set (F y, x) \\<rightarrow> HomD.set (y, G x)\"\n          using y h \\<Phi>_Fun_mapsto by blast\n        thus ?thesis\n          using x y h \\<phi>_def HomD.\\<psi>_mapsto [of y \"G x\"] HomC.\\<phi>_mapsto [of \"F y\" x] by auto\n      qed\n      show \"\\<psi> x (\\<phi> y h) = h\"\n      proof -\n        have 0: \"restrict (\\<lambda>h. h) (HomC.set (F y, x))\n                   = restrict (\\<phi>C (F y, x) o (\\<psi> x o \\<phi> y) o \\<psi>C (F y, x)) (HomC.set (F y, x))\"\n        proof -\n          have 1: \"S.ide (\\<Psi> (y, x) \\<cdot>\\<^sub>S \\<Phi> (y, x))\"\n            using x y \\<Phi>\\<Psi>.inv [of \"(y, x)\"] by auto\n          hence 6: \"S.seq (\\<Psi> (y, x)) (\\<Phi> (y, x))\" by auto\n          have 2: \"\\<Phi> (y, x) = S.mkArr (HomC.set (F y, x)) (HomD.set (y, G x))\n                                      (\\<phi>D (y, G x) o \\<phi> y o \\<psi>C (F y, x)) \\<and>\n                   \\<Psi> (y, x) = S.mkArr (HomD.set (y, G x)) (HomC.set (F y, x))\n                                      (\\<phi>C (F y, x) o \\<psi> x o \\<psi>D (y, G x))\"\n            using x y \\<Phi>_simp \\<Psi>_simp by force\n          have 3: \"S (\\<Psi> (y, x)) (\\<Phi> (y, x))\n                    = S.mkArr (HomC.set (F y, x)) (HomC.set (F y, x))\n                              (\\<phi>C (F y, x) o (\\<psi> x o \\<phi> y) o \\<psi>C (F y, x))\"\n          proof -\n            have 4: \"S.arr (\\<Psi> (y, x) \\<cdot>\\<^sub>S \\<Phi> (y, x))\" using 1 by auto\n            hence \"S (\\<Psi> (y, x)) (\\<Phi> (y, x))\n                     = S.mkArr (HomC.set (F y, x)) (HomC.set (F y, x))\n                               ((\\<phi>C (F y, x) o \\<psi> x o \\<psi>D (y, G x))\n                                  o (\\<phi>D (y, G x) o \\<phi> y o \\<psi>C (F y, x)))\"\n              using 1 2 S.ide_in_hom S.comp_mkArr by fastforce\n            also have \"... = S.mkArr (HomC.set (F y, x)) (HomC.set (F y, x))\n                                     (\\<phi>C (F y, x) o (\\<psi> x o \\<phi> y) o \\<psi>C (F y, x))\"\n            proof (intro S.mkArr_eqI')\n              show \"S.arr (S.mkArr (HomC.set (F y, x)) (HomC.set (F y, x))\n                                   ((\\<phi>C (F y, x) o \\<psi> x o \\<psi>D (y, G x))\n                                     o (\\<phi>D (y, G x) o \\<phi> y o \\<psi>C (F y, x))))\"\n                using 4 calculation by simp\n              show \"\\<And>h. h \\<in> HomC.set (F y, x) \\<Longrightarrow>\n                          ((\\<phi>C (F y, x) o \\<psi> x o \\<psi>D (y, G x))\n                            o (\\<phi>D (y, G x) o \\<phi> y o \\<psi>C (F y, x))) h =\n                          (\\<phi>C (F y, x) o (\\<psi> x o \\<phi> y) o \\<psi>C (F y, x)) h\"\n              proof -\n                fix h\n                assume h: \"h \\<in> HomC.set (F y, x)\"\n                hence \"\\<guillemotleft>\\<phi> y (\\<psi>C (F y, x) h) : y \\<rightarrow>\\<^sub>D G x\\<guillemotright>\"\n                  using x y h HomC.\\<psi>_mapsto [of \"F y\" x] \\<phi>_mapsto by auto\n                thus \"((\\<phi>C (F y, x) o \\<psi> x o \\<psi>D (y, G x))\n                            o (\\<phi>D (y, G x) o \\<phi> y o \\<psi>C (F y, x))) h =\n                      (\\<phi>C (F y, x) o (\\<psi> x o \\<phi> y) o \\<psi>C (F y, x)) h\"\n                  using x y 1 \\<phi>_mapsto HomD.\\<psi>_\\<phi> by simp\n              qed\n            qed\n            finally show ?thesis by simp\n          qed\n          moreover have \"\\<Psi> (y, x) \\<cdot>\\<^sub>S \\<Phi> (y, x)\n                             = S.mkArr (HomC.set (F y, x)) (HomC.set (F y, x)) (\\<lambda>h. h)\"\n            using 1 2 6 calculation S.mkIde_as_mkArr S.arr_mkArr S.dom_mkArr S.ideD(2)\n            by metis\n          ultimately have 4: \"S.mkArr (HomC.set (F y, x)) (HomC.set (F y, x))\n                                      (\\<phi>C (F y, x) o (\\<psi> x o \\<phi> y) o \\<psi>C (F y, x))\n                                = S.mkArr (HomC.set (F y, x)) (HomC.set (F y, x)) (\\<lambda>h. h)\"\n            by auto\n          have 5: \"S.arr (S.mkArr (HomC.set (F y, x)) (HomC.set (F y, x))\n                                  (\\<phi>C (F y, x) o (\\<psi> x o \\<phi> y) o \\<psi>C (F y, x)))\"\n            using 1 3 6 by presburger\n          hence \"restrict (\\<phi>C (F y, x) o (\\<psi> x o \\<phi> y) o \\<psi>C (F y, x)) (HomC.set (F y, x))\n                  = S.Fun (S.mkArr (HomC.set (F y, x)) (HomC.set (F y, x))\n                         (\\<phi>C (F y, x) o (\\<psi> x o \\<phi> y) o \\<psi>C (F y, x)))\"\n            by auto\n          also have \"... = restrict (\\<lambda>h. h) (HomC.set (F y, x))\"\n            using 4 5 by auto\n          finally show ?thesis by auto\n        qed\n        moreover have \"\\<phi>C (F y, x) h \\<in> HomC.set (F y, x)\"\n          using x y h HomC.\\<phi>_mapsto [of \"F y\" x] by auto\n        ultimately have\n            \"\\<phi>C (F y, x) h = (\\<phi>C (F y, x) o (\\<psi> x o \\<phi> y) o \\<psi>C (F y, x)) (\\<phi>C (F y, x) h)\"\n          using x y h HomC.\\<phi>_mapsto [of \"F y\" x] by fast\n        hence \"\\<psi>C (F y, x) (\\<phi>C (F y, x) h) =\n                 \\<psi>C (F y, x) ((\\<phi>C (F y, x) o (\\<psi> x o \\<phi> y) o \\<psi>C (F y, x)) (\\<phi>C (F y, x) h))\"\n          by simp\n        hence \"h = \\<psi>C (F y, x) (\\<phi>C (F y, x) (\\<psi> x (\\<phi> y (\\<psi>C (F y, x) (\\<phi>C (F y, x) h)))))\"\n          using x y h HomC.\\<psi>_\\<phi> [of \"F y\" x] by simp\n        also have \"... = \\<psi> x (\\<phi> y h)\"\n          using x y h HomC.\\<psi>_\\<phi> HomC.\\<psi>_\\<phi> \\<phi>_mapsto \\<psi>_mapsto\n          by (metis PiE mem_Collect_eq)\n        finally show ?thesis by auto\n      qed\n      next\n      fix x :: 'c and h :: 'd and y :: 'd\n      assume x: \"C.ide x\" and h: \"\\<guillemotleft>h : y \\<rightarrow>\\<^sub>D G x\\<guillemotright>\"\n      have y: \"D.ide y\" using h by auto\n      show \"\\<guillemotleft>\\<psi> x h : F y \\<rightarrow>\\<^sub>C x\\<guillemotright>\" using x y h \\<psi>_mapsto [of x y] by auto\n      show \"\\<phi> y (\\<psi> x h) = h\"\n      proof -\n        have 0: \"restrict (\\<lambda>h. h) (HomD.set (y, G x))\n                   = restrict (\\<phi>D (y, G x) o (\\<phi> y o \\<psi> x) o \\<psi>D (y, G x)) (HomD.set (y, G x))\"\n        proof -\n          have 1: \"S.ide (S (\\<Phi> (y, x)) (\\<Psi> (y, x)))\"\n            using x y \\<Phi>\\<Psi>.inv by force\n          hence 6: \"S.seq (\\<Phi> (y, x)) (\\<Psi> (y, x))\" by auto\n          have 2: \"\\<Phi> (y, x) = S.mkArr (HomC.set (F y, x)) (HomD.set (y, G x))\n                                      (\\<phi>D (y, G x) o \\<phi> y o \\<psi>C (F y, x)) \\<and>\n                   \\<Psi> (y, x) = S.mkArr (HomD.set (y, G x)) (HomC.set (F y, x))\n                                       (\\<phi>C (F y, x) o \\<psi> x o \\<psi>D (y, G x))\"\n            using x h \\<Phi>_simp \\<Psi>_simp by auto\n          have 3: \"S (\\<Phi> (y, x)) (\\<Psi> (y, x))\n                     = S.mkArr (HomD.set (y, G x)) (HomD.set (y, G x))\n                               (\\<phi>D (y, G x) o (\\<phi> y o \\<psi> x) o \\<psi>D (y, G x))\"\n          proof -\n            have 4: \"S.seq (\\<Phi> (y, x)) (\\<Psi> (y, x))\" using 1 by auto\n            hence \"S (\\<Phi> (y, x)) (\\<Psi> (y, x))\n                     = S.mkArr (HomD.set (y, G x)) (HomD.set (y, G x))\n                               ((\\<phi>D (y, G x) o \\<phi> y o \\<psi>C (F y, x))\n                                 o (\\<phi>C (F y, x) o \\<psi> x o \\<psi>D (y, G x)))\"\n              using 1 2 6 S.ide_in_hom S.comp_mkArr by fastforce\n            also have \"... = S.mkArr (HomD.set (y, G x)) (HomD.set (y, G x))\n                                     (\\<phi>D (y, G x) o (\\<phi> y o \\<psi> x) o \\<psi>D (y, G x))\"\n            proof\n              show \"S.arr (S.mkArr (HomD.set (y, G x)) (HomD.set (y, G x))\n                                   ((\\<phi>D (y, G x) o \\<phi> y o \\<psi>C (F y, x))\n                                     o (\\<phi>C (F y, x) o \\<psi> x o \\<psi>D (y, G x))))\"\n                using 4 calculation by simp\n              show \"\\<And>h. h \\<in> HomD.set (y, G x) \\<Longrightarrow>\n                          ((\\<phi>D (y, G x) o \\<phi> y o \\<psi>C (F y, x))\n                            o (\\<phi>C (F y, x) o \\<psi> x o \\<psi>D (y, G x))) h =\n                          (\\<phi>D (y, G x) o (\\<phi> y o \\<psi> x) o \\<psi>D (y, G x)) h\"\n              proof -\n                fix h\n                assume h: \"h \\<in> HomD.set (y, G x)\"\n                hence \"\\<guillemotleft>\\<psi> x (\\<psi>D (y, G x) h) : F y \\<rightarrow>\\<^sub>C x\\<guillemotright>\"\n                  using x y HomD.\\<psi>_mapsto [of y \"G x\"] \\<psi>_mapsto by auto\n                thus \"((\\<phi>D (y, G x) o \\<phi> y o \\<psi>C (F y, x))\n                            o (\\<phi>C (F y, x) o \\<psi> x o \\<psi>D (y, G x))) h =\n                      (\\<phi>D (y, G x) o (\\<phi> y o \\<psi> x) o \\<psi>D (y, G x)) h\"\n                  using x y HomC.\\<psi>_\\<phi> by simp\n              qed\n            qed\n            finally show ?thesis by auto\n          qed\n          moreover have \"\\<Phi> (y, x) \\<cdot>\\<^sub>S \\<Psi> (y, x) =\n                           S.mkArr (HomD.set (y, G x)) (HomD.set (y, G x)) (\\<lambda>h. h)\"\n            using 1 2 6 calculation\n            by (metis S.arr_mkArr S.cod_mkArr S.ide_in_hom S.mkIde_as_mkArr S.in_homE)\n          ultimately have 4: \"S.mkArr (HomD.set (y, G x)) (HomD.set (y, G x))\n                                      (\\<phi>D (y, G x) o (\\<phi> y o \\<psi> x) o \\<psi>D (y, G x))\n                                = S.mkArr (HomD.set (y, G x)) (HomD.set (y, G x)) (\\<lambda>h. h)\"\n            by auto\n          have 5: \"S.arr (S.mkArr (HomD.set (y, G x)) (HomD.set (y, G x))\n                                  (\\<phi>D (y, G x) o (\\<phi> y o \\<psi> x) o \\<psi>D (y, G x)))\"\n            using 1 3 by fastforce\n          hence \"restrict (\\<phi>D (y, G x) o (\\<phi> y o \\<psi> x) o \\<psi>D (y, G x)) (HomD.set (y, G x))\n                  = S.Fun (S.mkArr (HomD.set (y, G x)) (HomD.set (y, G x))\n                         (\\<phi>D (y, G x) o (\\<phi> y o \\<psi> x) o \\<psi>D (y, G x)))\"\n            by auto\n          also have \"... = restrict (\\<lambda>h. h) (HomD.set (y, G x))\"\n            using 4 5 by auto\n          finally show ?thesis by auto\n        qed\n        moreover have \"\\<phi>D (y, G x) h \\<in> HomD.set (y, G x)\"\n          using x y h HomD.\\<phi>_mapsto [of y \"G x\"] by auto\n        ultimately have\n            \"\\<phi>D (y, G x) h = (\\<phi>D (y, G x) o (\\<phi> y o \\<psi> x) o \\<psi>D (y, G x)) (\\<phi>D (y, G x) h)\"\n          by fast\n        hence \"\\<psi>D (y, G x) (\\<phi>D (y, G x) h) =\n                \\<psi>D (y, G x) ((\\<phi>D (y, G x) o (\\<phi> y o \\<psi> x) o \\<psi>D (y, G x)) (\\<phi>D (y, G x) h))\"\n          by simp\n        hence \"h = \\<psi>D (y, G x) (\\<phi>D (y, G x) (\\<phi> y (\\<psi> x (\\<psi>D (y, G x) (\\<phi>D (y, G x) h)))))\"\n          using x y h HomD.\\<psi>_\\<phi> by simp\n        also have \"... = \\<phi> y (\\<psi> x h)\"\n          using x y h HomD.\\<psi>_\\<phi> HomD.\\<psi>_\\<phi> [of \"\\<phi> y (\\<psi> x h)\" y \"G x\"] \\<phi>_mapsto \\<psi>_mapsto\n          by fastforce\n        finally show ?thesis by auto\n      qed\n      next\n      fix x :: 'c and x' :: 'c and y :: 'd and y' :: 'd\n      and f :: 'c and g :: 'd and h :: 'c\n      assume f: \"\\<guillemotleft>f : x \\<rightarrow>\\<^sub>C x'\\<guillemotright>\" and g: \"\\<guillemotleft>g : y' \\<rightarrow>\\<^sub>D y\\<guillemotright>\" and h: \"\\<guillemotleft>h : F y \\<rightarrow>\\<^sub>C x\\<guillemotright>\"\n      have x: \"C.ide x\" using f by auto\n      have y: \"D.ide y\" using g by auto\n      have x': \"C.ide x'\" using f by auto\n      have y': \"D.ide y'\" using g by auto\n      show \"\\<phi> y' (f \\<cdot>\\<^sub>C h \\<cdot>\\<^sub>C F g) = G f \\<cdot>\\<^sub>D \\<phi> y h \\<cdot>\\<^sub>D g\"\n      proof -\n        have 0: \"restrict ((\\<phi>D (y', G x') o (\\<lambda>h. G f \\<cdot>\\<^sub>D h \\<cdot>\\<^sub>D g) o \\<psi>D (y, G x))\n                           o (\\<phi>D (y, G x) o \\<phi> y o \\<psi>C (F y, x)))\n                       (HomC.set (F y, x))\n                = restrict ((\\<phi>D (y', G x') o \\<phi> y' o \\<psi>C (F y', x'))\n                             o (\\<phi>C (F y', x') o (\\<lambda>h. f \\<cdot>\\<^sub>C h \\<cdot>\\<^sub>C F g)) o \\<psi>C (F y, x))\n                           (HomC.set (F y, x))\"\n        proof -\n          have 1: \"S.arr (\\<Phi> (y, x)) \\<and>\n                   \\<Phi> (y, x) = S.mkArr (HomC.set (F y, x)) (HomD.set (y, G x))\n                                      (\\<phi>D (y, G x) o \\<phi> y o \\<psi>C (F y, x))\"\n                using x y \\<Phi>_simp [of y x] by auto\n          have 2: \"S.arr (\\<Phi> (y', x')) \\<and>\n                   \\<Phi> (y', x') = S.mkArr (HomC.set (F y', x')) (HomD.set (y', G x'))\n                                        (\\<phi>D (y', G x') o \\<phi> y' o \\<psi>C (F y', x'))\"\n                using x' y' \\<Phi>_simp [of y' x'] by auto\n          have 3: \"S.arr (S.mkArr (HomC.set (F y, x)) (HomD.set (y', G x'))\n                                  ((\\<phi>D (y', G x') o (\\<lambda>h. G f \\<cdot>\\<^sub>D h \\<cdot>\\<^sub>D g) o \\<psi>D (y, G x))\n                                    o (\\<phi>D (y, G x) o \\<phi> y o \\<psi>C (F y, x))))\n                   \\<and> S.mkArr (HomC.set (F y, x)) (HomD.set (y', G x'))\n                             ((\\<phi>D (y', G x') o (\\<lambda>h. G f \\<cdot>\\<^sub>D h \\<cdot>\\<^sub>D g) o \\<psi>D (y, G x))\n                               o (\\<phi>D (y, G x) o \\<phi> y o \\<psi>C (F y, x)))\n                     = S (S.mkArr (HomD.set (y, G x)) (HomD.set (y', G x'))\n                                  (\\<phi>D (y', G x') o (\\<lambda>h. G f \\<cdot>\\<^sub>D h \\<cdot>\\<^sub>D g) o \\<psi>D (y, G x)))\n                         (S.mkArr (HomC.set (F y, x)) (HomD.set (y, G x))\n                                  (\\<phi>D (y, G x) o \\<phi> y o \\<psi>C (F y, x)))\"\n          proof -\n            have 1: \"S.seq (S.mkArr (HomD.set (y, G x)) (HomD.set (y', G x'))\n                                  (\\<phi>D (y', G x') o (\\<lambda>h. G f \\<cdot>\\<^sub>D h \\<cdot>\\<^sub>D g) o \\<psi>D (y, G x)))\n                           (S.mkArr (HomC.set (F y, x)) (HomD.set (y, G x))\n                                  (\\<phi>D (y, G x) o \\<phi> y o \\<psi>C (F y, x)))\"\n            proof -\n              have \"S.arr (Hom_DopxG.map (g, f)) \\<and>\n                    Hom_DopxG.map (g, f)\n                        = S.mkArr (HomD.set (y, G x)) (HomD.set (y', G x'))\n                                  (\\<phi>D (y', G x') o (\\<lambda>h. G f \\<cdot>\\<^sub>D h \\<cdot>\\<^sub>D g) o \\<psi>D (y, G x))\"\n                using f g Hom_DopxG.preserves_arr Hom_DopxG_map_simp by fastforce\n              thus ?thesis\n                using 1 S.cod_mkArr S.dom_mkArr S.seqI by metis\n            qed\n            have \"S.seq (S.mkArr (HomD.set (y, G x)) (HomD.set (y', G x'))\n                                 (\\<phi>D (y', G x') o (\\<lambda>h. G f \\<cdot>\\<^sub>D h \\<cdot>\\<^sub>D g) o \\<psi>D (y, G x)))\n                        (S.mkArr (HomC.set (F y, x)) (HomD.set (y, G x))\n                                 (\\<phi>D (y, G x) o \\<phi> y o \\<psi>C (F y, x)))\"\n              using 1 by (intro S.seqI', auto)\n            moreover have \"S.mkArr (HomC.set (F y, x)) (HomD.set (y', G x'))\n                             ((\\<phi>D (y', G x') o (\\<lambda>h. G f \\<cdot>\\<^sub>D h \\<cdot>\\<^sub>D g) o \\<psi>D (y, G x))\n                               o (\\<phi>D (y, G x) o \\<phi> y o \\<psi>C (F y, x)))\n                             = S (S.mkArr (HomD.set (y, G x)) (HomD.set (y', G x'))\n                                          (\\<phi>D (y', G x') o (\\<lambda>h. G f \\<cdot>\\<^sub>D h \\<cdot>\\<^sub>D g) o \\<psi>D (y, G x)))\n                                 (S.mkArr (HomC.set (F y, x)) (HomD.set (y, G x))\n                                          (\\<phi>D (y, G x) o \\<phi> y o \\<psi>C (F y, x)))\"\n              using 1 S.comp_mkArr by fastforce\n            ultimately show ?thesis by auto\n          qed\n          moreover have\n             4: \"S.arr (S.mkArr (HomC.set (F y, x)) (HomD.set (y', G x'))\n                                ((\\<phi>D (y', G x') o \\<phi> y' o \\<psi>C (F y', x'))\n                                  o (\\<phi>C (F y', x') o (\\<lambda>h. f \\<cdot>\\<^sub>C h \\<cdot>\\<^sub>C F g) o \\<psi>C (F y, x))))\n                 \\<and> S.mkArr (HomC.set (F y, x)) (HomD.set (y', G x'))\n                           ((\\<phi>D (y', G x') o \\<phi> y' o \\<psi>C (F y', x'))\n                             o (\\<phi>C (F y', x') o (\\<lambda>h. f \\<cdot>\\<^sub>C h \\<cdot>\\<^sub>C F g) o \\<psi>C (F y, x)))\n                     = S (S.mkArr (HomC.set (F y', x')) (HomD.set (y', G x')) \n                                  (\\<phi>D (y', G x') o \\<phi> y' o \\<psi>C (F y', x')))\n                         (S.mkArr (HomC.set (F y, x)) (HomC.set (F y', x'))\n                                  (\\<phi>C (F y', x') o (\\<lambda>h. f \\<cdot>\\<^sub>C h \\<cdot>\\<^sub>C F g) o \\<psi>C (F y, x)))\"\n          proof -\n            have 5: \"S.seq (S.mkArr (HomC.set (F y', x')) (HomD.set (y', G x'))\n                                    (\\<phi>D (y', G x') o \\<phi> y' o \\<psi>C (F y', x')))\n                           (S.mkArr (HomC.set (F y, x)) (HomC.set (F y', x'))\n                                    (\\<phi>C (F y', x') o (\\<lambda>h. f \\<cdot>\\<^sub>C h \\<cdot>\\<^sub>C F g) o \\<psi>C (F y, x)))\"\n            proof -\n              have \"S.arr (Hom_FopxC.map (g, f)) \\<and>\n                    Hom_FopxC.map (g, f)\n                          = S.mkArr (HomC.set (F y, x)) (HomC.set (F y', x'))\n                                    (\\<phi>C (F y', x') o (\\<lambda>h. f \\<cdot>\\<^sub>C h \\<cdot>\\<^sub>C F g) o \\<psi>C (F y, x))\"\n                using f g Hom_FopxC.preserves_arr Hom_FopxC_map_simp by fastforce\n              thus ?thesis using 2 S.cod_mkArr S.dom_mkArr S.seqI by metis\n            qed\n            have \"S.seq (S.mkArr (HomC.set (F y', x')) (HomD.set (y', G x'))\n                                 (\\<phi>D (y', G x') o \\<phi> y' o \\<psi>C (F y', x')))\n                        (S.mkArr (HomC.set (F y, x)) (HomC.set (F y', x'))\n                                 (\\<phi>C (F y', x') o (\\<lambda>h. f \\<cdot>\\<^sub>C h \\<cdot>\\<^sub>C F g) o \\<psi>C (F y, x)))\"\n              using 5 by (intro S.seqI', auto)\n            moreover have \"S.mkArr (HomC.set (F y, x)) (HomD.set (y', G x'))\n                                   ((\\<phi>D (y', G x') o \\<phi> y' o \\<psi>C (F y', x'))\n                                     o (\\<phi>C (F y', x') o (\\<lambda>h. f \\<cdot>\\<^sub>C h \\<cdot>\\<^sub>C F g) o \\<psi>C (F y, x)))\n                             = S (S.mkArr (HomC.set (F y', x')) (HomD.set (y', G x'))\n                                          (\\<phi>D (y', G x') o \\<phi> y' o \\<psi>C (F y', x')))\n                                 (S.mkArr (HomC.set (F y, x)) (HomC.set (F y', x'))\n                                          (\\<phi>C (F y', x') o (\\<lambda>h. f \\<cdot>\\<^sub>C h \\<cdot>\\<^sub>C F g) o \\<psi>C (F y, x)))\"\n              using 5 S.comp_mkArr by fastforce\n            ultimately show ?thesis by argo\n          qed\n          moreover have 2:\n              \"S.mkArr (HomC.set (F y, x)) (HomD.set (y', G x'))\n                       ((\\<phi>D (y', G x') o (\\<lambda>h. G f \\<cdot>\\<^sub>D h \\<cdot>\\<^sub>D g) o \\<psi>D (y, G x))\n                         o (\\<phi>D (y, G x) o \\<phi> y o \\<psi>C (F y, x)))\n                  = S.mkArr (HomC.set (F y, x)) (HomD.set (y', G x'))\n                            ((\\<phi>D (y', G x') o \\<phi> y' o \\<psi>C (F y', x'))\n                              o (\\<phi>C (F y', x') o (\\<lambda>h. f \\<cdot>\\<^sub>C h \\<cdot>\\<^sub>C F g) o \\<psi>C (F y, x)))\"\n          proof -\n            have\n              \"S (Hom_DopxG.map (g, f)) (\\<Phi> (y, x)) = S (\\<Phi> (y', x')) (Hom_FopxC.map (g, f))\"\n              using f g \\<Phi>.is_natural_1 \\<Phi>.is_natural_2 by fastforce\n            moreover have \"Hom_DopxG.map (g, f)\n                             = S.mkArr (HomD.set (y, G x)) (HomD.set (y', G x'))\n                                       (\\<phi>D (y', G x') o (\\<lambda>h. G f \\<cdot>\\<^sub>D h \\<cdot>\\<^sub>D g) o \\<psi>D (y, G x))\"\n              using f g Hom_DopxG_map_simp [of \"(g, f)\"] by fastforce\n            moreover have \"Hom_FopxC.map (g, f)\n                             = S.mkArr (HomC.set (F y, x)) (HomC.set (F y', x'))\n                                       (\\<phi>C (F y', x') o (\\<lambda>h. f \\<cdot>\\<^sub>C h \\<cdot>\\<^sub>C F g) o \\<psi>C (F y, x))\"\n              using f g Hom_FopxC_map_simp [of \"(g, f)\"] by fastforce\n            ultimately show ?thesis using 1 2 3 4 by simp\n          qed\n          ultimately have 6: \"S.arr (S.mkArr (HomC.set (F y, x)) (HomD.set (y', G x'))\n                                             ((\\<phi>D (y', G x') o (\\<lambda>h. G f \\<cdot>\\<^sub>D h \\<cdot>\\<^sub>D g) o \\<psi>D (y, G x))\n                                               o (\\<phi>D (y, G x) o \\<phi> y o \\<psi>C (F y, x))))\"\n            by fast\n          hence \"restrict ((\\<phi>D (y', G x') o (\\<lambda>h. D (G f) (D h g)) o \\<psi>D (y, G x))\n                            o (\\<phi>D (y, G x) o \\<phi> y o \\<psi>C (F y, x)))\n                          (HomC.set (F y, x))\n                  = S.Fun (S.mkArr (HomC.set (F y, x)) (HomD.set (y', G x'))\n                                  ((\\<phi>D (y', G x') o (\\<lambda>h. G f \\<cdot>\\<^sub>D h \\<cdot>\\<^sub>D g) o \\<psi>D (y, G x))\n                                    o (\\<phi>D (y, G x) o \\<phi> y o \\<psi>C (F y, x))))\"\n            by simp\n          also have \"... = S.Fun (S.mkArr (HomC.set (F y, x)) (HomD.set (y', G x'))\n                                       ((\\<phi>D (y', G x') o \\<phi> y' o \\<psi>C (F y', x'))\n                                         o (\\<phi>C (F y', x') o (\\<lambda>h. f \\<cdot>\\<^sub>C h \\<cdot>\\<^sub>C F g) o \\<psi>C (F y, x))))\"\n            using 2 by argo\n          also have \"... = restrict ((\\<phi>D (y', G x') o \\<phi> y' o \\<psi>C (F y', x'))\n                                      o (\\<phi>C (F y', x') o (\\<lambda>h. f \\<cdot>\\<^sub>C h \\<cdot>\\<^sub>C F g) o \\<psi>C (F y, x)))\n                                    (HomC.set (F y, x))\"\n            using 4 S.Fun_mkArr by meson\n          finally show ?thesis by auto\n        qed\n        hence 5: \"((\\<phi>D (y', G x') \\<circ> (\\<lambda>h. G f \\<cdot>\\<^sub>D h \\<cdot>\\<^sub>D g) \\<circ> \\<psi>D (y, G x))\n                    \\<circ> (\\<phi>D (y, G x) \\<circ> \\<phi> y \\<circ> \\<psi>C (F y, x))) (\\<phi>C (F y, x) h) =\n                   (\\<phi>D (y', G x') \\<circ> \\<phi> y' \\<circ> \\<psi>C (F y', x')\n                     \\<circ> (\\<phi>C (F y', x') \\<circ> (\\<lambda>h. f \\<cdot>\\<^sub>C h \\<cdot>\\<^sub>C F g)) \\<circ> \\<psi>C (F y, x)) (\\<phi>C (F y, x) h)\"\n        proof -\n          have \"\\<phi>C (F y, x) h \\<in> HomC.set (F y, x)\"\n            using x y h HomC.\\<phi>_mapsto [of \"F y\" x] by auto\n          thus ?thesis\n            using 0 h restr_eqE [of \"(\\<phi>D (y', G x') \\<circ> (\\<lambda>h. G f \\<cdot>\\<^sub>D h \\<cdot>\\<^sub>D g) \\<circ> \\<psi>D (y, G x))\n                                      \\<circ> (\\<phi>D (y, G x) \\<circ> \\<phi> y \\<circ> \\<psi>C (F y, x))\"\n                                    \"HomC.set (F y, x)\"\n                                    \"(\\<phi>D (y', G x') \\<circ> \\<phi> y' \\<circ> \\<psi>C (F y', x'))\n                                       \\<circ> (\\<phi>C (F y', x') \\<circ> (\\<lambda>h. f \\<cdot>\\<^sub>C h \\<cdot>\\<^sub>C F g) o \\<psi>C (F y, x))\"]\n            by fast\n        qed\n        show ?thesis\n        proof -\n          have \"\\<phi> y' (C f (C h (F g))) =\n                  \\<psi>D (y', G x') (\\<phi>D (y', G x') (\\<phi> y' (\\<psi>C (F y', x') (\\<phi>C (F y', x')\n                     (C f (C (\\<psi>C (F y, x) (\\<phi>C (F y, x) h)) (F g)))))))\"\n          proof -\n            have \"\\<psi>D (y', G x') (\\<phi>D (y', G x') (\\<phi> y' (\\<psi>C (F y', x') (\\<phi>C (F y', x')\n                     (C f (C (\\<psi>C (F y, x) (\\<phi>C (F y, x) h)) (F g)))))))\n                    = \\<psi>D (y', G x') (\\<phi>D (y', G x') (\\<phi> y' (\\<psi>C (F y', x') (\\<phi>C (F y', x')\n                         (C f (C h (F g)))))))\"\n              using x y h HomC.\\<psi>_\\<phi> by simp\n            also have \"... = \\<psi>D (y', G x') (\\<phi>D (y', G x') (\\<phi> y' (C f (C h (F g)))))\"\n              using f g h HomC.\\<psi>_\\<phi> [of \"C f (C h (F g))\"] by fastforce\n            also have \"... = \\<phi> y' (C f (C h (F g)))\"\n            proof -\n              have \"\\<guillemotleft>\\<phi> y' (f \\<cdot>\\<^sub>C h \\<cdot>\\<^sub>C F g) : y' \\<rightarrow>\\<^sub>D G x'\\<guillemotright>\"\n                using f g h y' x' \\<phi>_mapsto [of y' x'] by auto\n              thus ?thesis by simp\n            qed\n            finally show ?thesis by auto\n          qed\n          also have\n             \"... = \\<psi>D (y', G x')\n                       (\\<phi>D (y', G x')\n                           (G f \\<cdot>\\<^sub>D \\<psi>D (y, G x) (\\<phi>D (y, G x) (\\<phi> y (\\<psi>C (F y, x) (\\<phi>C (F y, x) h))))\n                                \\<cdot>\\<^sub>D g))\"\n            using 5 by force\n          also have \"... = D (G f) (D (\\<phi> y h) g)\"\n          proof -\n            have \\<phi>yh: \"\\<guillemotleft>\\<phi> y h : y \\<rightarrow>\\<^sub>D G x\\<guillemotright>\"\n              using x y h \\<phi>_mapsto by auto\n            have \"\\<psi>D (y', G x')\n                     (\\<phi>D (y', G x')\n                         (G f \\<cdot>\\<^sub>D \\<psi>D (y, G x) (\\<phi>D (y, G x) (\\<phi> y (\\<psi>C (F y, x) (\\<phi>C (F y, x) h))))\n                              \\<cdot>\\<^sub>D g)) =\n                  \\<psi>D (y', G x') (\\<phi>D (y', G x') (G f \\<cdot>\\<^sub>D \\<psi>D (y, G x) (\\<phi>D (y, G x) (\\<phi> y h)) \\<cdot>\\<^sub>D g))\"\n              using x y f g h by auto\n            also have \"... = \\<psi>D (y', G x') (\\<phi>D (y', G x') (G f \\<cdot>\\<^sub>D \\<phi> y h \\<cdot>\\<^sub>D g))\"\n              using \\<phi>yh x' y' f g by simp\n            also have \"... = G f \\<cdot>\\<^sub>D \\<phi> y h \\<cdot>\\<^sub>D g\"\n              using \\<phi>yh f g by fastforce\n            finally show ?thesis by auto\n          qed\n          finally show ?thesis by auto\n        qed\n      qed\n    qed\n\n    theorem induces_meta_adjunction:\n    shows \"meta_adjunction C D F G \\<phi> \\<psi>\" ..\n\n  end\n\n  section \"Putting it All Together\"\n\n  text\\<open>\n    Combining the above results, an interpretation of any one of the locales:\n    \\<open>left_adjoint_functor\\<close>, \\<open>right_adjoint_functor\\<close>, \\<open>meta_adjunction\\<close>,\n    \\<open>hom_adjunction\\<close>, and \\<open>unit_counit_adjunction\\<close> extends to an interpretation\n    of \\<open>adjunction\\<close>.\n\\<close>\n\n  context meta_adjunction\n  begin\n\n    interpretation S: replete_setcat .\n    interpretation F: left_adjoint_functor D C F using has_left_adjoint_functor by auto\n    interpretation G: right_adjoint_functor C D G using has_right_adjoint_functor by auto\n\n    interpretation \\<eta>\\<epsilon>: unit_counit_adjunction C D F G \\<eta> \\<epsilon>\n      using induces_unit_counit_adjunction \\<eta>_def \\<epsilon>_def by auto\n    interpretation \\<Phi>\\<Psi>: hom_adjunction C D S.comp S.setp \\<phi>C \\<phi>D F G \\<Phi> \\<Psi>\n      using induces_hom_adjunction by auto\n\n    theorem induces_adjunction:\n    shows \"adjunction C D S.comp S.setp \\<phi>C \\<phi>D F G \\<phi> \\<psi> \\<eta> \\<epsilon> \\<Phi> \\<Psi>\"\n      using \\<epsilon>_map_simp \\<eta>_map_simp \\<phi>_in_terms_of_\\<eta> \\<phi>_in_terms_of_\\<Phi>' \\<psi>_in_terms_of_\\<epsilon>\n            \\<psi>_in_terms_of_\\<Psi>' \\<Phi>_simp \\<Psi>_simp \\<eta>_def \\<epsilon>_def\n      by unfold_locales auto\n\n  end\n\n  context unit_counit_adjunction\n  begin\n\n    interpretation \\<phi>\\<psi>: meta_adjunction C D F G \\<phi> \\<psi> using induces_meta_adjunction by auto\n\n    interpretation S: replete_setcat .\n    interpretation F: left_adjoint_functor D C F using \\<phi>\\<psi>.has_left_adjoint_functor by auto\n    interpretation G: right_adjoint_functor C D G using \\<phi>\\<psi>.has_right_adjoint_functor by auto\n\n    interpretation \\<Phi>\\<Psi>: hom_adjunction C D S.comp S.setp\n                          \\<phi>\\<psi>.\\<phi>C \\<phi>\\<psi>.\\<phi>D F G \\<phi>\\<psi>.\\<Phi> \\<phi>\\<psi>.\\<Psi>\n      using \\<phi>\\<psi>.induces_hom_adjunction by auto\n\n    theorem induces_adjunction:\n    shows \"adjunction C D S.comp S.setp \\<phi>\\<psi>.\\<phi>C \\<phi>\\<psi>.\\<phi>D F G \\<phi> \\<psi> \\<eta> \\<epsilon> \\<phi>\\<psi>.\\<Phi> \\<phi>\\<psi>.\\<Psi>\"\n      using \\<epsilon>_in_terms_of_\\<psi> \\<eta>_in_terms_of_\\<phi> \\<phi>\\<psi>.\\<phi>_in_terms_of_\\<Phi>' \\<psi>_def \\<phi>\\<psi>.\\<psi>_in_terms_of_\\<Psi>'\n            \\<phi>\\<psi>.\\<Phi>_simp \\<phi>\\<psi>.\\<Psi>_simp \\<phi>_def\n      by unfold_locales auto\n\n  end\n\n  context hom_adjunction\n  begin\n   \n    interpretation \\<phi>\\<psi>: meta_adjunction C D F G \\<phi> \\<psi>\n      using induces_meta_adjunction by auto\n    interpretation F: left_adjoint_functor D C F using \\<phi>\\<psi>.has_left_adjoint_functor by auto\n    interpretation G: right_adjoint_functor C D G using \\<phi>\\<psi>.has_right_adjoint_functor by auto\n    interpretation \\<eta>\\<epsilon>: unit_counit_adjunction C D F G \\<phi>\\<psi>.\\<eta> \\<phi>\\<psi>.\\<epsilon>\n      using \\<phi>\\<psi>.induces_unit_counit_adjunction \\<phi>\\<psi>.\\<eta>_def \\<phi>\\<psi>.\\<epsilon>_def by auto\n\n    theorem induces_adjunction:\n    shows \"adjunction C D S setp \\<phi>C \\<phi>D F G \\<phi> \\<psi> \\<phi>\\<psi>.\\<eta> \\<phi>\\<psi>.\\<epsilon> \\<Phi> \\<Psi>\"\n    proof\n      fix x\n      assume \"C.ide x\"\n      thus \"\\<phi>\\<psi>.\\<epsilon> x = \\<psi> x (G x)\"\n        using \\<phi>\\<psi>.\\<epsilon>_map_simp \\<phi>\\<psi>.\\<epsilon>_def by simp\n      next\n      fix y\n      assume \"D.ide y\"\n      thus \"\\<phi>\\<psi>.\\<eta> y = \\<phi> y (F y)\"\n        using \\<phi>\\<psi>.\\<eta>_map_simp \\<phi>\\<psi>.\\<eta>_def by simp\n      fix x y f\n      assume y: \"D.ide y\" and f: \"\\<guillemotleft>f : F y \\<rightarrow>\\<^sub>C x\\<guillemotright>\"\n      show \"\\<phi> y f = G f \\<cdot>\\<^sub>D \\<phi>\\<psi>.\\<eta> y\"\n        using y f \\<phi>\\<psi>.\\<phi>_in_terms_of_\\<eta> \\<phi>\\<psi>.\\<eta>_def by simp\n      show \"\\<phi> y f = (\\<psi>D (y, G x) \\<circ> \\<Phi>.FUN (y, x) \\<circ> \\<phi>C (F y, x)) f\"\n        using y f \\<phi>_def by auto\n      next\n      fix x y g\n      assume x: \"C.ide x\" and g: \"\\<guillemotleft>g : y \\<rightarrow>\\<^sub>D G x\\<guillemotright>\"\n      show \"\\<psi> x g = \\<phi>\\<psi>.\\<epsilon> x \\<cdot>\\<^sub>C F g\"\n        using x g \\<phi>\\<psi>.\\<psi>_in_terms_of_\\<epsilon> \\<phi>\\<psi>.\\<epsilon>_def by simp\n      show \"\\<psi> x g = (\\<psi>C (F y, x) \\<circ> \\<Psi>.FUN (y, x) \\<circ> \\<phi>D (y, G x)) g\"\n        using x g \\<psi>_def by fast\n      next\n      fix x y\n      assume x: \"C.ide x\" and y: \"D.ide y\"\n      show \"\\<Phi> (y, x) = S.mkArr (HomC.set (F y, x)) (HomD.set (y, G x))\n                               (\\<phi>D (y, G x) o \\<phi> y o \\<psi>C (F y, x))\"\n        using x y \\<Phi>_simp by simp\n      show \"\\<Psi> (y, x) = S.mkArr (HomD.set (y, G x)) (HomC.set (F y, x))\n                                (\\<phi>C (F y, x) o \\<psi> x o \\<psi>D (y, G x))\"\n        using x y \\<Psi>_simp by simp\n    qed\n\n  end\n\n  context left_adjoint_functor\n  begin\n\n    interpretation \\<phi>\\<psi>: meta_adjunction C D F G \\<phi> \\<psi>\n      using induces_meta_adjunction by auto\n    interpretation S: replete_setcat .\n\n    theorem induces_adjunction:\n    shows \"adjunction C D S.comp S.setp \\<phi>\\<psi>.\\<phi>C \\<phi>\\<psi>.\\<phi>D F G \\<phi> \\<psi> \\<phi>\\<psi>.\\<eta> \\<phi>\\<psi>.\\<epsilon> \\<phi>\\<psi>.\\<Phi> \\<phi>\\<psi>.\\<Psi>\"\n      using \\<phi>\\<psi>.induces_adjunction by auto\n\n  end\n\n  context right_adjoint_functor\n  begin\n\n    interpretation \\<phi>\\<psi>: meta_adjunction C D F G \\<phi> \\<psi>\n      using induces_meta_adjunction by auto\n    interpretation S: replete_setcat .\n\n    theorem induces_adjunction:\n    shows \"adjunction C D S.comp S.setp \\<phi>\\<psi>.\\<phi>C \\<phi>\\<psi>.\\<phi>D F G \\<phi> \\<psi> \\<phi>\\<psi>.\\<eta> \\<phi>\\<psi>.\\<epsilon> \\<phi>\\<psi>.\\<Phi> \\<phi>\\<psi>.\\<Psi>\"\n      using \\<phi>\\<psi>.induces_adjunction by auto\n\n  end\n\n  definition adjoint_functors\n  where \"adjoint_functors C D F G = (\\<exists>\\<phi> \\<psi>. meta_adjunction C D F G \\<phi> \\<psi>)\"\n\n  lemma adjoint_functors_respects_naturally_isomorphic:\n  assumes \"adjoint_functors C D F G\"\n  and \"naturally_isomorphic D C F' F\" and \"naturally_isomorphic C D G G'\"\n  shows \"adjoint_functors C D F' G'\"\n  proof -\n    obtain \\<phi> \\<psi> where \\<phi>\\<psi>: \"meta_adjunction C D F G \\<phi> \\<psi>\"\n      using assms(1) adjoint_functors_def by blast\n    interpret \\<phi>\\<psi>: meta_adjunction C D F G \\<phi> \\<psi>\n      using \\<phi>\\<psi> by simp\n    obtain \\<tau> where \\<tau>: \"natural_isomorphism D C F' F \\<tau>\"\n      using assms(2) naturally_isomorphic_def by blast\n    obtain \\<mu> where \\<mu>: \"natural_isomorphism C D G G' \\<mu>\"\n      using assms(3) naturally_isomorphic_def by blast\n    show ?thesis\n      using adjoint_functors_def \\<tau> \\<mu> \\<phi>\\<psi>.respects_natural_isomorphism by blast\n  qed\n\n  lemma left_adjoint_functor_respects_naturally_isomorphic:\n  assumes \"left_adjoint_functor D C F\"\n  and \"naturally_isomorphic D C F F'\"\n  shows \"left_adjoint_functor D C F'\"\n  proof -\n    interpret F: left_adjoint_functor D C F\n      using assms(1) by simp\n    have 1: \"meta_adjunction C D F F.G F.\\<phi> F.\\<psi>\"\n      using F.induces_meta_adjunction by simp\n    interpret \\<phi>\\<psi>: meta_adjunction C D F F.G F.\\<phi> F.\\<psi>\n      using 1 by simp\n    have \"adjoint_functors C D F F.G\"\n      using 1 adjoint_functors_def by blast\n    hence 2: \"adjoint_functors C D F' F.G\"\n      using assms(2) adjoint_functors_respects_naturally_isomorphic [of C D F F.G F' F.G]\n            naturally_isomorphic_reflexive naturally_isomorphic_symmetric\n            \\<phi>\\<psi>.G.functor_axioms\n      by blast\n    obtain \\<phi>' \\<psi>' where \\<phi>'\\<psi>': \"meta_adjunction C D F' F.G \\<phi>' \\<psi>'\"\n      using 2 adjoint_functors_def by blast\n    interpret \\<phi>'\\<psi>': meta_adjunction C D F' F.G \\<phi>' \\<psi>'\n      using \\<phi>'\\<psi>' by simp\n    show ?thesis\n      using \\<phi>'\\<psi>'.has_left_adjoint_functor by simp\n  qed\n\n  lemma right_adjoint_functor_respects_naturally_isomorphic:\n  assumes \"right_adjoint_functor C D G\"\n  and \"naturally_isomorphic C D G G'\"\n  shows \"right_adjoint_functor C D G'\"\n  proof -\n    interpret G: right_adjoint_functor C D G\n      using assms(1) by simp\n    have 1: \"meta_adjunction C D G.F G G.\\<phi> G.\\<psi>\"\n      using G.induces_meta_adjunction by simp\n    interpret \\<phi>\\<psi>: meta_adjunction C D G.F G G.\\<phi> G.\\<psi>\n      using 1 by simp\n    have \"adjoint_functors C D G.F G\"\n      using 1 adjoint_functors_def by blast\n    hence 2: \"adjoint_functors C D G.F G'\"\n      using assms(2) adjoint_functors_respects_naturally_isomorphic\n            naturally_isomorphic_reflexive naturally_isomorphic_symmetric\n            \\<phi>\\<psi>.F.functor_axioms\n      by blast\n    obtain \\<phi>' \\<psi>' where \\<phi>'\\<psi>': \"meta_adjunction C D G.F G' \\<phi>' \\<psi>'\"\n      using 2 adjoint_functors_def by blast\n    interpret \\<phi>'\\<psi>': meta_adjunction C D G.F G' \\<phi>' \\<psi>'\n      using \\<phi>'\\<psi>' by simp\n    show ?thesis\n      using \\<phi>'\\<psi>'.has_right_adjoint_functor by simp\n  qed\n\n  section \"Inverse Functors are Adjoints\"\n\n  (* TODO: This really should show that inverse functors induce an adjoint equivalence. *)\n\n  lemma inverse_functors_induce_meta_adjunction:\n  assumes \"inverse_functors C D F G\"\n  shows \"meta_adjunction C D F G (\\<lambda>x. G) (\\<lambda>y. F)\"\n  proof -\n    interpret inverse_functors C D F G using assms by auto\n    interpret meta_adjunction C D F G \\<open>\\<lambda>x. G\\<close> \\<open>\\<lambda>y. F\\<close>\n    proof -\n      have 1: \"\\<And>y. B.arr y \\<Longrightarrow> G (F y) = y\"\n        by (metis B.map_simp comp_apply inv)\n      have 2: \"\\<And>x. A.arr x \\<Longrightarrow> F (G x) = x\"\n        by (metis A.map_simp comp_apply inv')\n      show \"meta_adjunction C D F G (\\<lambda>x. G) (\\<lambda>y. F)\"\n      proof\n        fix y f x\n        assume y: \"B.ide y\" and f: \"\\<guillemotleft>f : F y \\<rightarrow>\\<^sub>A x\\<guillemotright>\"\n        show \"\\<guillemotleft>G f : y \\<rightarrow>\\<^sub>B G x\\<guillemotright>\"\n          using y f 1 G.preserves_hom by (elim A.in_homE, auto)\n        show \"F (G f) = f\"\n          using f 2 by auto\n        next\n        fix x g y\n        assume x: \"A.ide x\" and g: \"\\<guillemotleft>g : y \\<rightarrow>\\<^sub>B G x\\<guillemotright>\"\n        show \"\\<guillemotleft>F g : F y \\<rightarrow>\\<^sub>A x\\<guillemotright>\"\n          using x g 2 F.preserves_hom by (elim B.in_homE, auto)\n        show \"G (F g) = g\" using g 1 A.map_def by blast\n        next\n        fix f x x' g y' y h\n        assume f: \"\\<guillemotleft>f : x \\<rightarrow>\\<^sub>A x'\\<guillemotright>\" and g: \"\\<guillemotleft>g : y' \\<rightarrow>\\<^sub>B y\\<guillemotright>\" and h: \"\\<guillemotleft>h : F y \\<rightarrow>\\<^sub>A x\\<guillemotright>\"\n        show \"G (C f (C h (F g))) = D (G f) (D (G h) g)\"\n          using f g h 1 2 inv inv' A.map_def B.map_def by (elim A.in_homE B.in_homE, auto)\n      qed\n    qed\n    show ?thesis ..\n  qed\n\n  lemma inverse_functors_are_adjoints:\n  assumes \"inverse_functors A B F G\"\n  shows \"adjoint_functors A B F G\"\n    using assms inverse_functors_induce_meta_adjunction adjoint_functors_def by fast\n\n  context inverse_functors\n  begin\n\n    lemma \\<eta>_char:\n    shows \"meta_adjunction.\\<eta> B F (\\<lambda>x. G) = identity_functor.map B\"\n    proof (intro eqI)\n      interpret meta_adjunction A B F G \\<open>\\<lambda>y. G\\<close> \\<open>\\<lambda>x. F\\<close>\n        using inverse_functors_induce_meta_adjunction inverse_functors_axioms by auto\n      interpret S: replete_setcat .\n      interpret adjunction A B S.comp S.setp \\<phi>C \\<phi>D F G \\<open>\\<lambda>y. G\\<close> \\<open>\\<lambda>x. F\\<close> \\<eta> \\<epsilon> \\<Phi> \\<Psi>\n        using induces_adjunction by force\n      show \"natural_transformation B B B.map GF.map \\<eta>\"\n        using \\<eta>.natural_transformation_axioms by auto\n      show \"natural_transformation B B B.map GF.map B.map\"\n        by (simp add: B.as_nat_trans.natural_transformation_axioms inv)\n      show \"\\<And>b. B.ide b \\<Longrightarrow> \\<eta> b = B.map b\"\n        using \\<eta>_in_terms_of_\\<phi> \\<eta>o_def \\<eta>o_in_hom by fastforce\n    qed\n\n    lemma \\<epsilon>_char:\n    shows \"meta_adjunction.\\<epsilon> A F G (\\<lambda>y. F) = identity_functor.map A\"\n    proof (intro eqI)\n      interpret meta_adjunction A B F G \\<open>\\<lambda>y. G\\<close> \\<open>\\<lambda>x. F\\<close>\n        using inverse_functors_induce_meta_adjunction inverse_functors_axioms by auto\n      interpret S: replete_setcat .\n      interpret adjunction A B S.comp S.setp \\<phi>C \\<phi>D F G \\<open>\\<lambda>y. G\\<close> \\<open>\\<lambda>x. F\\<close> \\<eta> \\<epsilon> \\<Phi> \\<Psi>\n        using induces_adjunction by force\n      show \"natural_transformation A A FG.map A.map \\<epsilon>\"\n        using \\<epsilon>.natural_transformation_axioms by auto\n      show \"natural_transformation A A FG.map A.map A.map\"\n        by (simp add: A.as_nat_trans.natural_transformation_axioms inv')\n      show \"\\<And>a. A.ide a \\<Longrightarrow> \\<epsilon> a = A.map a\"\n        using \\<epsilon>_in_terms_of_\\<psi> \\<epsilon>o_def \\<epsilon>o_in_hom by fastforce\n    qed\n\n  end\n\n  section \"Composition of Adjunctions\"\n\n  locale composite_adjunction =\n    A: category A +\n    B: category B +\n    C: category C +\n    F: \"functor\" B A F +\n    G: \"functor\" A B G +\n    F': \"functor\" C B F' +\n    G': \"functor\" B C G' +\n    FG: meta_adjunction A B F G \\<phi> \\<psi> +\n    F'G': meta_adjunction B C F' G' \\<phi>' \\<psi>'\n  for A :: \"'a comp\"     (infixr \"\\<cdot>\\<^sub>A\" 55)\n  and B :: \"'b comp\"     (infixr \"\\<cdot>\\<^sub>B\" 55)\n  and C :: \"'c comp\"     (infixr \"\\<cdot>\\<^sub>C\" 55)\n  and F :: \"'b \\<Rightarrow> 'a\"\n  and G :: \"'a \\<Rightarrow> 'b\"\n  and F' :: \"'c \\<Rightarrow> 'b\"\n  and G' :: \"'b \\<Rightarrow> 'c\"\n  and \\<phi> :: \"'b \\<Rightarrow> 'a \\<Rightarrow> 'b\"\n  and \\<psi> :: \"'a \\<Rightarrow> 'b \\<Rightarrow> 'a\"\n  and \\<phi>' :: \"'c \\<Rightarrow> 'b \\<Rightarrow> 'c\"\n  and \\<psi>' :: \"'b \\<Rightarrow> 'c \\<Rightarrow> 'b\"\n  begin\n\n    interpretation S: replete_setcat .\n    interpretation FG: adjunction A B S.comp S.setp\n                           FG.\\<phi>C FG.\\<phi>D F G \\<phi> \\<psi> FG.\\<eta> FG.\\<epsilon> FG.\\<Phi> FG.\\<Psi>\n      using FG.induces_adjunction by simp\n    interpretation F'G': adjunction B C S.comp S.setp F'G'.\\<phi>C F'G'.\\<phi>D F' G' \\<phi>' \\<psi>'\n                           F'G'.\\<eta> F'G'.\\<epsilon> F'G'.\\<Phi> F'G'.\\<Psi>\n      using F'G'.induces_adjunction by simp\n\n    (* Notation for C.in_hom is inherited here somehow, but I don't know from where. *)\n\n    lemma is_meta_adjunction:\n    shows \"meta_adjunction A C (F o F') (G' o G) (\\<lambda>z. \\<phi>' z o \\<phi> (F' z)) (\\<lambda>x. \\<psi> x o \\<psi>' (G x))\"\n    proof -\n      interpret G'oG: composite_functor A B C G G' ..\n      interpret FoF': composite_functor C B A F' F ..\n      show ?thesis\n      proof\n        fix y f x\n        assume y: \"C.ide y\" and f: \"\\<guillemotleft>f : FoF'.map y \\<rightarrow>\\<^sub>A x\\<guillemotright>\"\n        show \"\\<guillemotleft>(\\<phi>' y \\<circ> \\<phi> (F' y)) f : y \\<rightarrow>\\<^sub>C G'oG.map x\\<guillemotright>\"\n          using y f FG.\\<phi>_in_hom F'G'.\\<phi>_in_hom by simp\n        show \"(\\<psi> x \\<circ> \\<psi>' (G x)) ((\\<phi>' y \\<circ> \\<phi> (F' y)) f) = f\"\n          using y f FG.\\<phi>_in_hom F'G'.\\<phi>_in_hom FG.\\<psi>_\\<phi> F'G'.\\<psi>_\\<phi> by simp\n        next\n        fix x g y\n        assume x: \"A.ide x\" and g: \"\\<guillemotleft>g : y \\<rightarrow>\\<^sub>C G'oG.map x\\<guillemotright>\"\n        show \"\\<guillemotleft>(\\<psi> x \\<circ> \\<psi>' (G x)) g : FoF'.map y \\<rightarrow>\\<^sub>A x\\<guillemotright>\"\n          using x g FG.\\<psi>_in_hom F'G'.\\<psi>_in_hom by auto\n        show \"(\\<phi>' y \\<circ> \\<phi> (F' y)) ((\\<psi> x \\<circ> \\<psi>' (G x)) g) = g\"\n          using x g FG.\\<psi>_in_hom F'G'.\\<psi>_in_hom FG.\\<phi>_\\<psi> F'G'.\\<phi>_\\<psi> by simp\n        next\n        fix f x x' g y' y h\n        assume f: \"\\<guillemotleft>f : x \\<rightarrow>\\<^sub>A x'\\<guillemotright>\" and g: \"\\<guillemotleft>g : y' \\<rightarrow>\\<^sub>C y\\<guillemotright>\" and h: \"\\<guillemotleft>h : FoF'.map y \\<rightarrow>\\<^sub>A x\\<guillemotright>\"\n        show \"(\\<phi>' y' \\<circ> \\<phi> (F' y')) (f \\<cdot>\\<^sub>A h \\<cdot>\\<^sub>A FoF'.map g) =\n              G'oG.map f \\<cdot>\\<^sub>C (\\<phi>' y \\<circ> \\<phi> (F' y)) h \\<cdot>\\<^sub>C g\"\n          using f g h FG.\\<phi>_naturality [of f x x' \"F' g\" \"F' y'\" \"F' y\" h]\n                F'G'.\\<phi>_naturality [of \"G f\" \"G x\" \"G x'\" g y' y \"\\<phi> (F' y) h\"]\n                FG.\\<phi>_in_hom\n          by fastforce\n      qed\n    qed\n\n    interpretation K\\<eta>H: natural_transformation C C \\<open>G' o F'\\<close> \\<open>G' o G o F o F'\\<close>\n                          \\<open>G' o FG.\\<eta> o F'\\<close>\n    proof -\n      interpret \\<eta>F': natural_transformation C B F' \\<open>(G o F) o F'\\<close> \\<open>FG.\\<eta> o F'\\<close>\n        using FG.\\<eta>_is_natural_transformation F'.as_nat_trans.natural_transformation_axioms\n              horizontal_composite\n        by fastforce\n      interpret G'\\<eta>F': natural_transformation C C \\<open>G' o F'\\<close> \\<open>G' o (G o F o F')\\<close>\n                         \\<open>G' o (FG.\\<eta> o F')\\<close>\n        using \\<eta>F'.natural_transformation_axioms G'.as_nat_trans.natural_transformation_axioms\n              horizontal_composite\n        by blast\n      show \"natural_transformation C C (G' o F') (G' o G o F o F') (G' o FG.\\<eta> o F')\"\n        using G'\\<eta>F'.natural_transformation_axioms o_assoc by metis\n    qed\n    interpretation G'\\<eta>F'o\\<eta>': vertical_composite C C C.map \\<open>G' o F'\\<close> \\<open>G' o G o F o F'\\<close>\n                             F'G'.\\<eta> \\<open>G' o FG.\\<eta> o F'\\<close> ..\n\n    interpretation F\\<epsilon>G: natural_transformation A A \\<open>F o F' o G' o G\\<close> \\<open>F o G\\<close>\n                          \\<open>F o F'G'.\\<epsilon> o G\\<close>\n    proof -\n      interpret F\\<epsilon>': natural_transformation B A \\<open>F o (F' o G')\\<close> F \\<open>F o F'G'.\\<epsilon>\\<close>\n        using F'G'.\\<epsilon>.natural_transformation_axioms F.as_nat_trans.natural_transformation_axioms\n              horizontal_composite\n        by fastforce\n      interpret F\\<epsilon>'G: natural_transformation A A \\<open>F o (F' o G') o G\\<close> \\<open>F o G\\<close> \\<open>F o F'G'.\\<epsilon> o G\\<close>\n        using F\\<epsilon>'.natural_transformation_axioms G.as_nat_trans.natural_transformation_axioms\n              horizontal_composite\n        by blast\n      show \"natural_transformation A A (F o F' o G' o G) (F o G) (F o F'G'.\\<epsilon> o G)\"\n        using F\\<epsilon>'G.natural_transformation_axioms o_assoc by metis\n    qed\n    interpretation \\<epsilon>oF\\<epsilon>'G: vertical_composite A A \\<open>F \\<circ> F' \\<circ> G' \\<circ> G\\<close> \\<open>F o G\\<close> A.map\n                             \\<open>F o F'G'.\\<epsilon> o G\\<close> FG.\\<epsilon> ..\n\n    interpretation meta_adjunction A C \\<open>F o F'\\<close> \\<open>G' o G\\<close>\n                                   \\<open>\\<lambda>z. \\<phi>' z o \\<phi> (F' z)\\<close> \\<open>\\<lambda>x. \\<psi> x o \\<psi>' (G x)\\<close>\n      using is_meta_adjunction by auto\n    interpretation S: replete_setcat .\n    interpretation adjunction A C S.comp S.setp \\<phi>C \\<phi>D \\<open>F \\<circ> F'\\<close> \\<open>G' \\<circ> G\\<close>\n                     \\<open>\\<lambda>z. \\<phi>' z \\<circ> \\<phi> (F' z)\\<close> \\<open>\\<lambda>x. \\<psi> x \\<circ> \\<psi>' (G x)\\<close> \\<eta> \\<epsilon> \\<Phi> \\<Psi>\n      using induces_adjunction by simp\n\n    lemma \\<eta>_char:\n    shows \"\\<eta> = G'\\<eta>F'o\\<eta>'.map\"\n    proof (intro NaturalTransformation.eqI)\n      show \"natural_transformation C C C.map (G' o G o F o F') G'\\<eta>F'o\\<eta>'.map\" ..\n      show \"natural_transformation C C C.map (G' o G o F o F') \\<eta>\"\n        by (metis (no_types, lifting) \\<eta>_is_natural_transformation o_assoc)\n      fix a\n      assume a: \"C.ide a\"\n      show \"\\<eta> a = G'\\<eta>F'o\\<eta>'.map a\"\n        unfolding \\<eta>_def\n        using a G'\\<eta>F'o\\<eta>'.map_def FG.\\<eta>.preserves_hom [of \"F' a\" \"F' a\" \"F' a\"]\n              F'G'.\\<phi>_in_terms_of_\\<eta> FG.\\<eta>_map_simp \\<eta>_map_simp [of a] C.ide_in_hom\n              F'G'.\\<eta>_def FG.\\<eta>_def\n        by auto\n    qed\n\n    lemma \\<epsilon>_char:\n    shows \"\\<epsilon> = \\<epsilon>oF\\<epsilon>'G.map\"\n    proof (intro NaturalTransformation.eqI)\n      show \"natural_transformation A A (F o F' o G' o G) A.map \\<epsilon>\"\n        by (metis (no_types, lifting) \\<epsilon>_is_natural_transformation o_assoc)\n      show \"natural_transformation A A (F \\<circ> F' \\<circ> G' \\<circ> G) A.map \\<epsilon>oF\\<epsilon>'G.map\" ..\n      fix a\n      assume a: \"A.ide a\"\n      show \"\\<epsilon> a = \\<epsilon>oF\\<epsilon>'G.map a\"\n      proof -\n        have \"\\<epsilon> a = \\<psi> a (\\<psi>' (G a) (G' (G a)))\"\n          using a \\<epsilon>_in_terms_of_\\<psi> by simp\n        also have \"... = FG.\\<epsilon> a \\<cdot>\\<^sub>A F (F'G'.\\<epsilon> (G a) \\<cdot>\\<^sub>B F' (G' (G a)))\"\n          by (metis F'G'.\\<epsilon>_in_terms_of_\\<psi> F'G'.\\<epsilon>o_def F'G'.\\<epsilon>o_in_hom F'G'.\\<eta>\\<epsilon>.\\<epsilon>_in_terms_of_\\<psi>\n              F'G'.\\<eta>\\<epsilon>.\\<psi>_def FG.G\\<epsilon>.natural_transformation_axioms FG.\\<psi>_in_terms_of_\\<epsilon> a\n              functor.preserves_ide natural_transformation_def)\n        also have \"... = \\<epsilon>oF\\<epsilon>'G.map a\"\n          using a B.comp_arr_dom \\<epsilon>oF\\<epsilon>'G.map_def by simp\n        finally show ?thesis by blast\n      qed\n    qed\n\n  end\n\n  section \"Right Adjoints are Unique up to Natural Isomorphism\"\n\n  text\\<open>\n    As an example of the use of the of the foregoing development, we show that two right adjoints\n    to the same functor are naturally isomorphic.\n\\<close>\n\n  theorem two_right_adjoints_naturally_isomorphic:\n  assumes \"adjoint_functors C D F G\" and \"adjoint_functors C D F G'\"\n  shows \"naturally_isomorphic C D G G'\"\n  proof -\n    text\\<open>\n      For any object @{term x} of @{term C}, we have that \\<open>\\<epsilon> x \\<in> C.hom (F (G x)) x\\<close>\n      is a terminal arrow from @{term F} to @{term x}, and similarly for \\<open>\\<epsilon>' x\\<close>.\n      We may therefore obtain the unique coextension \\<open>\\<tau> x \\<in> D.hom (G x) (G' x)\\<close>\n      of \\<open>\\<epsilon> x\\<close> along \\<open>\\<epsilon>' x\\<close>.\n      An explicit formula for \\<open>\\<tau> x\\<close> is \\<open>D (G' (\\<epsilon> x)) (\\<eta>' (G x))\\<close>.\n      Similarly, we obtain \\<open>\\<tau>' x = D (G (\\<epsilon>' x)) (\\<eta> (G' x)) \\<in> D.hom (G' x) (G x)\\<close>.\n      We show these are the components of inverse natural transformations between\n      @{term G} and @{term G'}.\n\\<close>\n    obtain \\<phi> \\<psi> where \\<phi>\\<psi>: \"meta_adjunction C D F G \\<phi> \\<psi>\"\n      using assms adjoint_functors_def by blast\n    obtain \\<phi>' \\<psi>' where \\<phi>'\\<psi>': \"meta_adjunction C D F G' \\<phi>' \\<psi>'\"\n      using assms adjoint_functors_def by blast\n    interpret Adj: meta_adjunction C D F G \\<phi> \\<psi> using \\<phi>\\<psi> by auto\n    interpret S: replete_setcat .\n    interpret Adj: adjunction C D S.comp S.setp Adj.\\<phi>C Adj.\\<phi>D\n                              F G \\<phi> \\<psi> Adj.\\<eta> Adj.\\<epsilon> Adj.\\<Phi> Adj.\\<Psi>\n      using Adj.induces_adjunction by auto\n    interpret Adj': meta_adjunction C D F G' \\<phi>' \\<psi>' using \\<phi>'\\<psi>' by auto\n    interpret Adj': adjunction C D S.comp S.setp Adj'.\\<phi>C Adj'.\\<phi>D\n                               F G' \\<phi>' \\<psi>' Adj'.\\<eta> Adj'.\\<epsilon> Adj'.\\<Phi> Adj'.\\<Psi>\n      using Adj'.induces_adjunction by auto\n    write C (infixr \"\\<cdot>\\<^sub>C\" 55)\n    write D (infixr \"\\<cdot>\\<^sub>D\" 55)\n    write Adj.C.in_hom (\"\\<guillemotleft>_ : _ \\<rightarrow>\\<^sub>C _\\<guillemotright>\")\n    write Adj.D.in_hom (\"\\<guillemotleft>_ : _ \\<rightarrow>\\<^sub>D _\\<guillemotright>\")\n    let ?\\<tau>o = \"\\<lambda>a. G' (Adj.\\<epsilon> a) \\<cdot>\\<^sub>D Adj'.\\<eta> (G a)\"\n    interpret \\<tau>: transformation_by_components C D G G' ?\\<tau>o\n    proof\n      show \"\\<And>a. Adj.C.ide a \\<Longrightarrow> \\<guillemotleft>G' (Adj.\\<epsilon> a) \\<cdot>\\<^sub>D Adj'.\\<eta> (G a) : G a \\<rightarrow>\\<^sub>D G' a\\<guillemotright>\"\n        by fastforce\n      show \"\\<And>f. Adj.C.arr f \\<Longrightarrow>\n                   (G' (Adj.\\<epsilon> (Adj.C.cod f)) \\<cdot>\\<^sub>D Adj'.\\<eta> (G (Adj.C.cod f))) \\<cdot>\\<^sub>D G f =\n                   G' f \\<cdot>\\<^sub>D G' (Adj.\\<epsilon> (Adj.C.dom f)) \\<cdot>\\<^sub>D Adj'.\\<eta> (G (Adj.C.dom f))\"\n      proof -\n        fix f\n        assume f: \"Adj.C.arr f\"\n        let ?x = \"Adj.C.dom f\"\n        let ?x' = \"Adj.C.cod f\"\n        have \"(G' (Adj.\\<epsilon> (Adj.C.cod f)) \\<cdot>\\<^sub>D Adj'.\\<eta> (G (Adj.C.cod f))) \\<cdot>\\<^sub>D G f =\n              G' (Adj.\\<epsilon> (Adj.C.cod f) \\<cdot>\\<^sub>C F (G f)) \\<cdot>\\<^sub>D Adj'.\\<eta> (G (Adj.C.dom f))\"\n          using f Adj'.\\<eta>.naturality [of \"G f\"] Adj.D.comp_assoc by simp\n        also have \"... = G' (f \\<cdot>\\<^sub>C Adj.\\<epsilon> (Adj.C.dom f)) \\<cdot>\\<^sub>D Adj'.\\<eta> (G (Adj.C.dom f))\"\n          using f Adj.\\<epsilon>.naturality by simp\n        also have \"... = G' f \\<cdot>\\<^sub>D G' (Adj.\\<epsilon> (Adj.C.dom f)) \\<cdot>\\<^sub>D Adj'.\\<eta> (G (Adj.C.dom f))\"\n          using f Adj.D.comp_assoc by simp\n        finally show \"(G' (Adj.\\<epsilon> (Adj.C.cod f)) \\<cdot>\\<^sub>D Adj'.\\<eta> (G (Adj.C.cod f))) \\<cdot>\\<^sub>D G f =\n                      G' f \\<cdot>\\<^sub>D G' (Adj.\\<epsilon> (Adj.C.dom f)) \\<cdot>\\<^sub>D Adj'.\\<eta> (G (Adj.C.dom f))\"\n          by auto\n      qed\n    qed\n    interpret natural_isomorphism C D G G' \\<tau>.map\n    proof\n      fix a\n      assume a: \"Adj.C.ide a\"\n      show \"Adj.D.iso (\\<tau>.map a)\"\n      proof\n        show \"Adj.D.inverse_arrows (\\<tau>.map a) (\\<phi> (G' a) (Adj'.\\<epsilon> a))\"\n        proof\n          text\\<open>\n            The proof that the two composites are identities is a modest diagram chase.\n            This is a good example of the inference rules for the \\<open>category\\<close>,\n            \\<open>functor\\<close>, and \\<open>natural_transformation\\<close> locales in action.\n            Isabelle is able to use the single hypothesis that \\<open>a\\<close> is an identity to\n            implicitly fill in all the details that the various quantities are in fact arrows\n            and that the indicated composites are all well-defined, as well as to apply\n            associativity of composition.  In most cases, this is done by auto or simp without\n            even mentioning any of the rules that are used.\n$$\\xymatrix{\n        {G' a} \\ar[dd]_{\\eta'(G'a)} \\ar[rr]^{\\tau' a} \\ar[dr]_{\\eta(G'a)}\n           && {G a} \\ar[rr]^{\\tau a} \\ar[dr]_{\\eta'(Ga)} && {G' a}                     \\\\\n        & {GFG'a} \\rrtwocell\\omit{\\omit(2)} \\ar[ur]_{G(\\epsilon' a)} \\ar[dr]_{\\eta'(GFG'a)}\n           && {G'FGa} \\drtwocell\\omit{\\omit(3)} \\ar[ur]_{G'(\\epsilon a)} &            \\\\\n        {G'FG'a} \\urtwocell\\omit{\\omit(1)} \\ar[rr]_{G'F\\eta(G'a)} \\ar@/_8ex/[rrrr]_{G'FG'a}\n           && {G'FGFG'a} \\dtwocell\\omit{\\omit(4)} \\ar[ru]_{G'FG(\\epsilon' a)} \\ar[rr]_{G'(\\epsilon(FG'a))}\n           && {G'FG'a} \\ar[uu]_{G'(\\epsilon' a)}                                       \\\\\n           &&&&\n}$$\n\\<close>\n          show \"Adj.D.ide (\\<tau>.map a \\<cdot>\\<^sub>D \\<phi> (G' a) (Adj'.\\<epsilon> a))\"\n          proof -\n            have \"\\<tau>.map a \\<cdot>\\<^sub>D \\<phi> (G' a) (Adj'.\\<epsilon> a) = G' a\"\n            proof -\n              have \"\\<tau>.map a \\<cdot>\\<^sub>D \\<phi> (G' a) (Adj'.\\<epsilon> a) =\n                    G' (Adj.\\<epsilon> a) \\<cdot>\\<^sub>D (Adj'.\\<eta> (G a) \\<cdot>\\<^sub>D G (Adj'.\\<epsilon> a)) \\<cdot>\\<^sub>D Adj.\\<eta> (G' a)\"\n                using a \\<tau>.map_simp_ide Adj.\\<phi>_in_terms_of_\\<eta> Adj'.\\<phi>_in_terms_of_\\<eta>\n                      Adj'.\\<epsilon>.preserves_hom [of a a a] Adj.C.ide_in_hom Adj.D.comp_assoc\n                      Adj.\\<epsilon>_def Adj.\\<eta>_def\n                by simp\n              also have \"... = G' (Adj.\\<epsilon> a) \\<cdot>\\<^sub>D (G' (F (G (Adj'.\\<epsilon> a))) \\<cdot>\\<^sub>D Adj'.\\<eta> (G (F (G' a)))) \\<cdot>\\<^sub>D\n                               Adj.\\<eta> (G' a)\"\n                using a Adj'.\\<eta>.naturality [of \"G (Adj'.\\<epsilon> a)\"] by auto\n              also have \"... = (G' (Adj.\\<epsilon> a) \\<cdot>\\<^sub>D G' (F (G (Adj'.\\<epsilon> a)))) \\<cdot>\\<^sub>D G' (F (Adj.\\<eta> (G' a))) \\<cdot>\\<^sub>D\n                               Adj'.\\<eta> (G' a)\"\n                using a Adj'.\\<eta>.naturality [of \"Adj.\\<eta> (G' a)\"] Adj.D.comp_assoc by auto\n              also have\n                  \"... = G' (Adj'.\\<epsilon> a) \\<cdot>\\<^sub>D (G' (Adj.\\<epsilon> (F (G' a))) \\<cdot>\\<^sub>D G' (F (Adj.\\<eta> (G' a)))) \\<cdot>\\<^sub>D\n                         Adj'.\\<eta> (G' a)\"\n              proof -\n                have\n                   \"G' (Adj.\\<epsilon> a) \\<cdot>\\<^sub>D G' (F (G (Adj'.\\<epsilon> a))) = G' (Adj'.\\<epsilon> a) \\<cdot>\\<^sub>D G' (Adj.\\<epsilon> (F (G' a)))\"\n                proof -\n                  have \"G' (Adj.\\<epsilon> a \\<cdot>\\<^sub>C F (G (Adj'.\\<epsilon> a))) = G' (Adj'.\\<epsilon> a \\<cdot>\\<^sub>C Adj.\\<epsilon> (F (G' a)))\"\n                    using a Adj.\\<epsilon>.naturality [of \"Adj'.\\<epsilon> a\"] by auto\n                  thus ?thesis using a by force\n                qed\n                thus ?thesis using Adj.D.comp_assoc by auto\n              qed\n              also have \"... = G' (Adj'.\\<epsilon> a) \\<cdot>\\<^sub>D Adj'.\\<eta> (G' a)\"\n              proof -\n                have \"G' (Adj.\\<epsilon> (F (G' a))) \\<cdot>\\<^sub>D G' (F (Adj.\\<eta> (G' a))) = G' (F (G' a))\"\n                proof -\n                  have\n                      \"G' (Adj.\\<epsilon> (F (G' a))) \\<cdot>\\<^sub>D G' (F (Adj.\\<eta> (G' a))) = G' (Adj.\\<epsilon>FoF\\<eta>.map (G' a))\"\n                    using a Adj.\\<epsilon>FoF\\<eta>.map_simp_1 by auto\n                  moreover have \"Adj.\\<epsilon>FoF\\<eta>.map (G' a) = F (G' a)\"\n                    using a by (simp add: Adj.\\<eta>\\<epsilon>.triangle_F)\n                  ultimately show ?thesis by auto\n                qed\n                thus ?thesis\n                  using a Adj.D.comp_cod_arr [of \"Adj'.\\<eta> (G' a)\"] by auto\n              qed\n              also have \"... = G' a\"\n                using a Adj'.\\<eta>\\<epsilon>.triangle_G Adj'.G\\<epsilon>o\\<eta>G.map_simp_1 [of a] by auto\n              finally show ?thesis by auto\n            qed\n            thus ?thesis using a by simp\n          qed\n          show \"Adj.D.ide (\\<phi> (G' a) (Adj'.\\<epsilon> a) \\<cdot>\\<^sub>D \\<tau>.map a)\"\n          proof -\n            have \"\\<phi> (G' a) (Adj'.\\<epsilon> a) \\<cdot>\\<^sub>D \\<tau>.map a = G a\"\n            proof -\n              have \"\\<phi> (G' a) (Adj'.\\<epsilon> a) \\<cdot>\\<^sub>D \\<tau>.map a =\n                    G (Adj'.\\<epsilon> a) \\<cdot>\\<^sub>D (Adj.\\<eta> (G' a) \\<cdot>\\<^sub>D G' (Adj.\\<epsilon> a)) \\<cdot>\\<^sub>D Adj'.\\<eta> (G a)\"\n                using a \\<tau>.map_simp_ide Adj.\\<phi>_in_terms_of_\\<eta> Adj'.\\<epsilon>.preserves_hom [of a a a]\n                      Adj.C.ide_in_hom Adj.D.comp_assoc Adj.\\<eta>_def\n                by auto\n              also have\n                \"... = G (Adj'.\\<epsilon> a) \\<cdot>\\<^sub>D (G (F (G' (Adj.\\<epsilon> a))) \\<cdot>\\<^sub>D Adj.\\<eta> (G' (F (G a)))) \\<cdot>\\<^sub>D\n                       Adj'.\\<eta> (G a)\"\n                using a Adj.\\<eta>.naturality [of \"G' (Adj.\\<epsilon> a)\"] by auto\n              also have\n                \"... = (G (Adj'.\\<epsilon> a) \\<cdot>\\<^sub>D G (F (G' (Adj.\\<epsilon> a)))) \\<cdot>\\<^sub>D G (F (Adj'.\\<eta> (G a))) \\<cdot>\\<^sub>D\n                       Adj.\\<eta> (G a)\"\n                using a Adj.\\<eta>.naturality [of \"Adj'.\\<eta> (G a)\"] Adj.D.comp_assoc by auto\n              also have\n                \"... = G (Adj.\\<epsilon> a) \\<cdot>\\<^sub>D (G (Adj'.\\<epsilon> (F (G a))) \\<cdot>\\<^sub>D G (F (Adj'.\\<eta> (G a)))) \\<cdot>\\<^sub>D\n                       Adj.\\<eta> (G a)\"\n              proof -\n                have \"G (Adj'.\\<epsilon> a) \\<cdot>\\<^sub>D G (F (G' (Adj.\\<epsilon> a))) = G (Adj.\\<epsilon> a) \\<cdot>\\<^sub>D G (Adj'.\\<epsilon> (F (G a)))\"\n                proof -\n                  have \"G (Adj'.\\<epsilon> a \\<cdot>\\<^sub>C F (G' (Adj.\\<epsilon> a))) = G (Adj.\\<epsilon> a \\<cdot>\\<^sub>C Adj'.\\<epsilon> (F (G a)))\"\n                    using a Adj'.\\<epsilon>.naturality [of \"Adj.\\<epsilon> a\"] by auto\n                  thus ?thesis using a by force\n                qed\n                thus ?thesis using Adj.D.comp_assoc by auto\n              qed\n              also have \"... = G (Adj.\\<epsilon> a) \\<cdot>\\<^sub>D Adj.\\<eta> (G a)\"\n              proof -\n                have \"G (Adj'.\\<epsilon> (F (G a))) \\<cdot>\\<^sub>D G (F (Adj'.\\<eta> (G a))) = G (F (G a))\"\n                proof -\n                  have\n                    \"G (Adj'.\\<epsilon> (F (G a))) \\<cdot>\\<^sub>D G (F (Adj'.\\<eta> (G a))) = G (Adj'.\\<epsilon>FoF\\<eta>.map (G a))\"\n                    using a Adj'.\\<epsilon>FoF\\<eta>.map_simp_1 [of \"G a\"] by auto\n                  moreover have \"Adj'.\\<epsilon>FoF\\<eta>.map (G a) = F (G a)\"\n                    using a by (simp add: Adj'.\\<eta>\\<epsilon>.triangle_F)\n                  ultimately show ?thesis by auto\n                qed\n                thus ?thesis\n                  using a Adj.D.comp_cod_arr by auto\n              qed\n              also have \"... = G a\"\n                using a Adj.\\<eta>\\<epsilon>.triangle_G Adj.G\\<epsilon>o\\<eta>G.map_simp_1 [of a] by auto\n              finally show ?thesis by auto\n            qed\n            thus ?thesis using a by auto\n          qed\n        qed\n      qed\n    qed\n    have \"natural_isomorphism C D G G' \\<tau>.map\" ..\n    thus \"naturally_isomorphic C D G G'\"\n      using naturally_isomorphic_def by blast\n  qed\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/Category3/Adjunction.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8872045877523147, "lm_q2_score": 0.8198933403143929, "lm_q1q2_score": 0.7274131329944992}}
{"text": "(* Title: Interval\n   Author: Christoph Traut, TU Muenchen\n           Fabian Immler, TU Muenchen\n*)\nsection \\<open>Interval Type\\<close>\ntheory Interval\n  imports\n    Complex_MainRLT\n    Lattice_Algebras\n    Set_Algebras\nbegin\n\ntext \\<open>A type of non-empty, closed intervals.\\<close>\n\ntypedef (overloaded) 'a interval =\n  \"{(a::'a::preorder, b). a \\<le> b}\"\n  morphisms bounds_of_interval Interval\n  by auto\n\nsetup_lifting type_definition_interval\n\nlift_definition lower::\"('a::preorder) interval \\<Rightarrow> 'a\" is fst .\n\nlift_definition upper::\"('a::preorder) interval \\<Rightarrow> 'a\" is snd .\n\nlemma interval_eq_iff: \"a = b \\<longleftrightarrow> lower a = lower b \\<and> upper a = upper b\"\n  by transfer auto\n\nlemma interval_eqI: \"lower a = lower b \\<Longrightarrow> upper a = upper b \\<Longrightarrow> a = b\"\n  by (auto simp: interval_eq_iff)\n\nlemma lower_le_upper[simp]: \"lower i \\<le> upper i\"\n  by transfer auto\n\nlift_definition set_of :: \"'a::preorder interval \\<Rightarrow> 'a set\" is \"\\<lambda>x. {fst x .. snd x}\" .\n\nlemma set_of_eq: \"set_of x = {lower x .. upper x}\"\n  by transfer simp\n\ncontext notes [[typedef_overloaded]] begin\n\nlift_definition(code_dt) Interval'::\"'a::preorder \\<Rightarrow> 'a::preorder \\<Rightarrow> 'a interval option\"\n  is \"\\<lambda>a b. if a \\<le> b then Some (a, b) else None\"\n  by auto\n\nlemma Interval'_split:\n  \"P (Interval' a b) \\<longleftrightarrow>\n    (\\<forall>ivl. a \\<le> b \\<longrightarrow> lower ivl = a \\<longrightarrow> upper ivl = b \\<longrightarrow> P (Some ivl)) \\<and> (\\<not>a\\<le>b \\<longrightarrow> P None)\"\n  by transfer auto\n\nlemma Interval'_split_asm:\n  \"P (Interval' a b) \\<longleftrightarrow>\n    \\<not>((\\<exists>ivl. a \\<le> b \\<and> lower ivl = a \\<and> upper ivl = b \\<and> \\<not>P (Some ivl)) \\<or> (\\<not>a\\<le>b \\<and> \\<not>P None))\"\n  unfolding Interval'_split\n  by auto\n\nlemmas Interval'_splits = Interval'_split Interval'_split_asm\n\nlemma Interval'_eq_Some: \"Interval' a b = Some i \\<Longrightarrow> lower i = a \\<and> upper i = b\"\n  by (simp split: Interval'_splits)\n\nend\n\ninstantiation \"interval\" :: (\"{preorder,equal}\") equal\nbegin\n\ndefinition \"equal_class.equal a b \\<equiv> (lower a = lower b) \\<and> (upper a = upper b)\"\n\ninstance proof qed (simp add: equal_interval_def interval_eq_iff)\nend\n\ninstantiation interval :: (\"preorder\") ord begin\n\ndefinition less_eq_interval :: \"'a interval \\<Rightarrow> 'a interval \\<Rightarrow> bool\"\n  where \"less_eq_interval a b \\<longleftrightarrow> lower b \\<le> lower a \\<and> upper a \\<le> upper b\"\n\ndefinition less_interval :: \"'a interval \\<Rightarrow> 'a interval \\<Rightarrow> bool\"\n  where  \"less_interval x y = (x \\<le> y \\<and> \\<not> y \\<le> x)\"\n\ninstance proof qed\nend\n\ninstantiation interval :: (\"lattice\") semilattice_sup\nbegin\n\nlift_definition sup_interval :: \"'a interval \\<Rightarrow> 'a interval \\<Rightarrow> 'a interval\"\n  is \"\\<lambda>(a, b) (c, d). (inf a c, sup b d)\"\n  by (auto simp: le_infI1 le_supI1)\n\nlemma lower_sup[simp]: \"lower (sup A B) = inf (lower A) (lower B)\"\n  by transfer auto\n\nlemma upper_sup[simp]: \"upper (sup A B) = sup (upper A) (upper B)\"\n  by transfer auto\n\ninstance proof qed (auto simp: less_eq_interval_def less_interval_def interval_eq_iff)\nend\n\nlemma set_of_interval_union: \"set_of A \\<union> set_of B \\<subseteq> set_of (sup A B)\" for A::\"'a::lattice interval\"\n  by (auto simp: set_of_eq)\n\nlemma interval_union_commute: \"sup A B = sup B A\" for A::\"'a::lattice interval\"\n  by (auto simp add: interval_eq_iff inf.commute sup.commute)\n\nlemma interval_union_mono1: \"set_of a \\<subseteq> set_of (sup a A)\" for A :: \"'a::lattice interval\"\n  using set_of_interval_union by blast\n\nlemma interval_union_mono2: \"set_of A \\<subseteq> set_of (sup a A)\" for A :: \"'a::lattice interval\"\n  using set_of_interval_union by blast\n\nlift_definition interval_of :: \"'a::preorder \\<Rightarrow> 'a interval\" is \"\\<lambda>x. (x, x)\"\n  by auto\n\nlemma lower_interval_of[simp]: \"lower (interval_of a) = a\"\n  by transfer auto\n\nlemma upper_interval_of[simp]: \"upper (interval_of a) = a\"\n  by transfer auto\n\ndefinition width :: \"'a::{preorder,minus} interval \\<Rightarrow> 'a\"\n  where \"width i = upper i - lower i\"\n\n\ninstantiation \"interval\" :: (\"ordered_ab_semigroup_add\") ab_semigroup_add\nbegin\n\nlift_definition plus_interval::\"'a interval \\<Rightarrow> 'a interval \\<Rightarrow> 'a interval\"\n  is \"\\<lambda>(a, b). \\<lambda>(c, d). (a + c, b + d)\"\n  by (auto intro!: add_mono)\nlemma lower_plus[simp]: \"lower (plus A B) = plus (lower A) (lower B)\"\n  by transfer auto\nlemma upper_plus[simp]: \"upper (plus A B) = plus (upper A) (upper B)\"\n  by transfer auto\n\ninstance proof qed (auto simp: interval_eq_iff less_eq_interval_def ac_simps)\nend\n\ninstance \"interval\" :: (\"{ordered_ab_semigroup_add, lattice}\") ordered_ab_semigroup_add\nproof qed (auto simp: less_eq_interval_def intro!: add_mono)\n\ninstantiation \"interval\" :: (\"{preorder,zero}\") zero\nbegin\n\nlift_definition zero_interval::\"'a interval\" is \"(0, 0)\" by auto\nlemma lower_zero[simp]: \"lower 0 = 0\"\n  by transfer auto\nlemma upper_zero[simp]: \"upper 0 = 0\"\n  by transfer auto\ninstance proof qed\nend\n\ninstance \"interval\" :: (\"{ordered_comm_monoid_add}\") comm_monoid_add\nproof qed (auto simp: interval_eq_iff)\n\ninstance \"interval\" :: (\"{ordered_comm_monoid_add,lattice}\") ordered_comm_monoid_add ..\n\ninstantiation \"interval\" :: (\"{ordered_ab_group_add}\") uminus\nbegin\n\nlift_definition uminus_interval::\"'a interval \\<Rightarrow> 'a interval\" is \"\\<lambda>(a, b). (-b, -a)\" by auto\nlemma lower_uminus[simp]: \"lower (- A) = - upper A\"\n  by transfer auto\nlemma upper_uminus[simp]: \"upper (- A) = - lower A\"\n  by transfer auto\ninstance ..\nend\n\ninstantiation \"interval\" :: (\"{ordered_ab_group_add}\") minus\nbegin\n\ndefinition minus_interval::\"'a interval \\<Rightarrow> 'a interval \\<Rightarrow> 'a interval\"\n  where \"minus_interval a b = a + - b\"\nlemma lower_minus[simp]: \"lower (minus A B) = minus (lower A) (upper B)\"\n  by (auto simp: minus_interval_def)\nlemma upper_minus[simp]: \"upper (minus A B) = minus (upper A) (lower B)\"\n  by (auto simp: minus_interval_def)\n\ninstance ..\nend\n\ninstantiation \"interval\" :: (linordered_semiring) times\nbegin\n\nlift_definition times_interval :: \"'a interval \\<Rightarrow> 'a interval \\<Rightarrow> 'a interval\"\n  is \"\\<lambda>(a1, a2). \\<lambda>(b1, b2).\n    (let x1 = a1 * b1; x2 = a1 * b2; x3 = a2 * b1; x4 = a2 * b2\n    in (min x1 (min x2 (min x3 x4)), max x1 (max x2 (max x3 x4))))\"\n  by (auto simp: Let_def intro!: min.coboundedI1 max.coboundedI1)\n\nlemma lower_times:\n  \"lower (times A B) = Min {lower A * lower B, lower A * upper B, upper A * lower B, upper A * upper B}\"\n  by transfer (auto simp: Let_def)\n\nlemma upper_times:\n  \"upper (times A B) = Max {lower A * lower B, lower A * upper B, upper A * lower B, upper A * upper B}\"\n  by transfer (auto simp: Let_def)\n\ninstance ..\nend\n\nlemma interval_eq_set_of_iff: \"X = Y \\<longleftrightarrow> set_of X = set_of Y\" for X Y::\"'a::order interval\"\n  by (auto simp: set_of_eq interval_eq_iff)\n\n\nsubsection \\<open>Membership\\<close>\n\nabbreviation (in preorder) in_interval (\"(_/ \\<in>\\<^sub>i _)\" [51, 51] 50)\n  where \"in_interval x X \\<equiv> x \\<in> set_of X\"\n\nlemma in_interval_to_interval[intro!]: \"a \\<in>\\<^sub>i interval_of a\"\n  by (auto simp: set_of_eq)\n\nlemma plus_in_intervalI:\n  fixes x y :: \"'a :: ordered_ab_semigroup_add\"\n  shows \"x \\<in>\\<^sub>i X \\<Longrightarrow> y \\<in>\\<^sub>i Y \\<Longrightarrow> x + y \\<in>\\<^sub>i X + Y\"\n  by (simp add: add_mono_thms_linordered_semiring(1) set_of_eq)\n\nlemma connected_set_of[intro, simp]:\n  \"connected (set_of X)\" for X::\"'a::linear_continuum_topology interval\"\n  by (auto simp: set_of_eq )\n\nlemma ex_sum_in_interval_lemma: \"\\<exists>xa\\<in>{la .. ua}. \\<exists>xb\\<in>{lb .. ub}. x = xa + xb\"\n  if \"la \\<le> ua\" \"lb \\<le> ub\" \"la + lb \\<le> x\" \"x \\<le> ua + ub\"\n    \"ua - la \\<le> ub - lb\"\n  for la b c d::\"'a::linordered_ab_group_add\"\nproof -\n  define wa where \"wa = ua - la\"\n  define wb where \"wb = ub - lb\"\n  define w where \"w = wa + wb\"\n  define d where \"d = x - la - lb\"\n  define da where \"da = max 0 (min wa (d - wa))\"\n  define db where \"db = d - da\"\n  from that have nonneg: \"0 \\<le> wa\" \"0 \\<le> wb\" \"0 \\<le> w\" \"0 \\<le> d\" \"d \\<le> w\"\n    by (auto simp add: wa_def wb_def w_def d_def add.commute le_diff_eq)\n  have \"0 \\<le> db\"\n    by (auto simp: da_def nonneg db_def intro!: min.coboundedI2)\n  have \"x = (la + da) + (lb + db)\"\n    by (simp add: da_def db_def d_def)\n  moreover\n  have \"x - la - ub \\<le> da\"\n    using that\n    unfolding da_def\n    by (intro max.coboundedI2) (auto simp: wa_def d_def diff_le_eq diff_add_eq)\n  then have \"db \\<le> wb\"\n    by (auto simp: db_def d_def wb_def algebra_simps)\n  with \\<open>0 \\<le> db\\<close> that nonneg have \"lb + db \\<in> {lb..ub}\"\n    by (auto simp: wb_def algebra_simps)\n  moreover\n  have \"da \\<le> wa\"\n    by (auto simp: da_def nonneg)\n  then have \"la + da \\<in> {la..ua}\"\n    by (auto simp: da_def wa_def algebra_simps)\n  ultimately show ?thesis\n    by force\nqed\n\n\nlemma ex_sum_in_interval: \"\\<exists>xa\\<ge>la. xa \\<le> ua \\<and> (\\<exists>xb\\<ge>lb. xb \\<le> ub \\<and> x = xa + xb)\"\n  if a: \"la \\<le> ua\" and b: \"lb \\<le> ub\" and x: \"la + lb \\<le> x\" \"x \\<le> ua + ub\"\n  for la b c d::\"'a::linordered_ab_group_add\"\nproof -\n  from linear consider \"ua - la \\<le> ub - lb\" | \"ub - lb \\<le> ua - la\"\n    by blast\n  then show ?thesis\n  proof cases\n    case 1\n    from ex_sum_in_interval_lemma[OF that 1]\n    show ?thesis by auto\n  next\n    case 2\n    from x have \"lb + la \\<le> x\" \"x \\<le> ub + ua\" by (simp_all add: ac_simps)\n    from ex_sum_in_interval_lemma[OF b a this 2]\n    show ?thesis by auto\n  qed\nqed\n\nlemma Icc_plus_Icc:\n  \"{a .. b} + {c .. d} = {a + c .. b + d}\"\n  if \"a \\<le> b\" \"c \\<le> d\"\n  for a b c d::\"'a::linordered_ab_group_add\"\n  using ex_sum_in_interval[OF that]\n  by (auto intro: add_mono simp: atLeastAtMost_iff Bex_def set_plus_def)\n\nlemma set_of_plus:\n  fixes A :: \"'a::linordered_ab_group_add interval\"\n  shows \"set_of (A + B) = set_of A + set_of B\"\n  using Icc_plus_Icc[of \"lower A\" \"upper A\" \"lower B\" \"upper B\"]\n  by (auto simp: set_of_eq)\n\nlemma plus_in_intervalE:\n  fixes xy :: \"'a :: linordered_ab_group_add\"\n  assumes \"xy \\<in>\\<^sub>i X + Y\"\n  obtains x y where \"xy = x + y\" \"x \\<in>\\<^sub>i X\" \"y \\<in>\\<^sub>i Y\"\n  using assms\n  unfolding set_of_plus set_plus_def\n  by auto\n\nlemma set_of_uminus: \"set_of (-X) = {- x | x. x \\<in> set_of X}\"\n  for X :: \"'a :: ordered_ab_group_add interval\"\n  by (auto simp: set_of_eq simp: le_minus_iff minus_le_iff\n      intro!: exI[where x=\"-x\" for x])\n\nlemma uminus_in_intervalI:\n  fixes x :: \"'a :: ordered_ab_group_add\"\n  shows \"x \\<in>\\<^sub>i X \\<Longrightarrow> -x \\<in>\\<^sub>i -X\"\n  by (auto simp: set_of_uminus)\n\nlemma uminus_in_intervalD:\n  fixes x :: \"'a :: ordered_ab_group_add\"\n  shows \"x \\<in>\\<^sub>i - X \\<Longrightarrow> - x \\<in>\\<^sub>i X\"\n  by (auto simp: set_of_uminus)\n\nlemma minus_in_intervalI:\n  fixes x y :: \"'a :: ordered_ab_group_add\"\n  shows \"x \\<in>\\<^sub>i X \\<Longrightarrow> y \\<in>\\<^sub>i Y \\<Longrightarrow> x - y \\<in>\\<^sub>i X - Y\"\n  by (metis diff_conv_add_uminus minus_interval_def plus_in_intervalI uminus_in_intervalI)\n\nlemma set_of_minus: \"set_of (X - Y) = {x - y | x y . x \\<in> set_of X \\<and> y \\<in> set_of Y}\"\n  for X Y :: \"'a :: linordered_ab_group_add interval\"\n  unfolding minus_interval_def set_of_plus set_of_uminus set_plus_def\n  by force\n\nlemma times_in_intervalI:\n  fixes x y::\"'a::linordered_ring\"\n  assumes \"x \\<in>\\<^sub>i X\" \"y \\<in>\\<^sub>i Y\"\n  shows \"x * y \\<in>\\<^sub>i X * Y\"\nproof -\n  define X1 where \"X1 \\<equiv> lower X\"\n  define X2 where \"X2 \\<equiv> upper X\"\n  define Y1 where \"Y1 \\<equiv> lower Y\"\n  define Y2 where \"Y2 \\<equiv> upper Y\"\n  from assms have assms: \"X1 \\<le> x\" \"x \\<le> X2\" \"Y1 \\<le> y\" \"y \\<le> Y2\"\n    by (auto simp: X1_def X2_def Y1_def Y2_def set_of_eq)\n  have \"(X1 * Y1 \\<le> x * y \\<or> X1 * Y2 \\<le> x * y \\<or> X2 * Y1 \\<le> x * y \\<or> X2 * Y2 \\<le> x * y) \\<and>\n        (X1 * Y1 \\<ge> x * y \\<or> X1 * Y2 \\<ge> x * y \\<or> X2 * Y1 \\<ge> x * y \\<or> X2 * Y2 \\<ge> x * y)\"\n  proof (cases x \"0::'a\" rule: linorder_cases)\n    case x0: less\n    show ?thesis\n    proof (cases \"y < 0\")\n      case y0: True\n      from y0 x0 assms have \"x * y \\<le> X1 * y\" by (intro mult_right_mono_neg, auto)\n      also from x0 y0 assms have \"X1 * y \\<le> X1 * Y1\" by (intro mult_left_mono_neg, auto)\n      finally have 1: \"x * y \\<le> X1 * Y1\".\n      show ?thesis proof(cases \"X2 \\<le> 0\")\n        case True\n        with assms have \"X2 * Y2 \\<le> X2 * y\" by (auto intro: mult_left_mono_neg)\n        also from assms y0 have \"... \\<le> x * y\" by (auto intro: mult_right_mono_neg)\n        finally have \"X2 * Y2 \\<le> x * y\".\n        with 1 show ?thesis by auto\n      next\n        case False\n        with assms have \"X2 * Y1 \\<le> X2 * y\" by (auto intro: mult_left_mono)\n        also from assms y0 have \"... \\<le> x * y\" by (auto intro: mult_right_mono_neg)\n        finally have \"X2 * Y1 \\<le> x * y\".\n        with 1 show ?thesis by auto\n      qed\n    next\n      case False\n      then have y0: \"y \\<ge> 0\" by auto\n      from x0 y0 assms have \"X1 * Y2 \\<le> x * Y2\" by (intro mult_right_mono, auto)\n      also from y0 x0 assms have \"... \\<le> x * y\" by (intro mult_left_mono_neg, auto)\n      finally have 1: \"X1 * Y2 \\<le> x * y\".\n      show ?thesis\n      proof(cases \"X2 \\<le> 0\")\n        case X2: True\n        from assms y0 have \"x * y \\<le> X2 * y\" by (intro mult_right_mono)\n        also from assms X2 have \"... \\<le> X2 * Y1\" by (auto intro: mult_left_mono_neg)\n        finally have \"x * y \\<le> X2 * Y1\".\n        with 1 show ?thesis by auto\n      next\n        case X2: False\n        from assms y0 have \"x * y \\<le> X2 * y\" by (intro mult_right_mono)\n        also from assms X2 have \"... \\<le> X2 * Y2\" by (auto intro: mult_left_mono)\n        finally have \"x * y \\<le> X2 * Y2\".\n        with 1 show ?thesis by auto\n      qed\n    qed\n  next\n    case [simp]: equal\n    with assms show ?thesis by (cases \"Y2 \\<le> 0\", auto intro:mult_sign_intros)\n  next\n    case x0: greater\n    show ?thesis\n    proof (cases \"y < 0\")\n      case y0: True\n      from x0 y0 assms have \"X2 * Y1 \\<le> X2 * y\" by (intro mult_left_mono, auto)\n      also from y0 x0 assms have \"X2 * y \\<le> x * y\" by (intro mult_right_mono_neg, auto)\n      finally have 1: \"X2 * Y1 \\<le> x * y\".\n      show ?thesis\n      proof(cases \"Y2 \\<le> 0\")\n        case Y2: True\n        from x0 assms have \"x * y \\<le> x * Y2\" by (auto intro: mult_left_mono)\n        also from assms Y2 have \"... \\<le> X1 * Y2\" by (auto intro: mult_right_mono_neg)\n        finally have \"x * y \\<le> X1 * Y2\".\n        with 1 show ?thesis by auto\n      next\n        case Y2: False\n        from x0 assms have \"x * y \\<le> x * Y2\" by (auto intro: mult_left_mono)\n        also from assms Y2 have \"... \\<le> X2 * Y2\" by (auto intro: mult_right_mono)\n        finally have \"x * y \\<le> X2 * Y2\".\n        with 1 show ?thesis by auto\n      qed\n    next\n      case y0: False\n      from x0 y0 assms have \"x * y \\<le> X2 * y\" by (intro mult_right_mono, auto)\n      also from y0 x0 assms have \"... \\<le> X2 * Y2\" by (intro mult_left_mono, auto)\n      finally have 1: \"x * y \\<le> X2 * Y2\".\n      show ?thesis\n      proof(cases \"X1 \\<le> 0\")\n        case True\n        with assms have \"X1 * Y2 \\<le> X1 * y\" by (auto intro: mult_left_mono_neg)\n        also from assms y0 have \"... \\<le> x * y\" by (auto intro: mult_right_mono)\n        finally have \"X1 * Y2 \\<le> x * y\".\n        with 1 show ?thesis by auto\n      next\n        case False\n        with assms have \"X1 * Y1 \\<le> X1 * y\" by (auto intro: mult_left_mono)\n        also from assms y0 have \"... \\<le> x * y\" by (auto intro: mult_right_mono)\n        finally have \"X1 * Y1 \\<le> x * y\".\n        with 1 show ?thesis by auto\n      qed\n    qed\n  qed\n  hence min:\"min (X1 * Y1) (min (X1 * Y2) (min (X2 * Y1) (X2 * Y2))) \\<le> x * y\"\n    and max:\"x * y \\<le> max (X1 * Y1) (max (X1 * Y2) (max (X2 * Y1) (X2 * Y2)))\"\n    by (auto simp:min_le_iff_disj le_max_iff_disj)\n  show ?thesis using min max\n    by (auto simp: Let_def X1_def X2_def Y1_def Y2_def set_of_eq lower_times upper_times)\nqed\n\nlemma times_in_intervalE:\n  fixes xy :: \"'a :: {linordered_semiring, real_normed_algebra, linear_continuum_topology}\"\n    \\<comment> \\<open>TODO: linear continuum topology is pretty strong\\<close>\n  assumes \"xy \\<in>\\<^sub>i X * Y\"\n  obtains x y where \"xy = x * y\" \"x \\<in>\\<^sub>i X\" \"y \\<in>\\<^sub>i Y\"\nproof -\n  let ?mult = \"\\<lambda>(x, y). x * y\"\n  let ?XY = \"set_of X \\<times> set_of Y\"\n  have cont: \"continuous_on ?XY ?mult\"\n    by (auto intro!: tendsto_eq_intros simp: continuous_on_def split_beta')\n  have conn: \"connected (?mult ` ?XY)\"\n    by (rule connected_continuous_image[OF cont]) auto\n  have \"lower (X * Y) \\<in> ?mult ` ?XY\" \"upper (X * Y) \\<in> ?mult ` ?XY\"\n    by (auto simp: set_of_eq lower_times upper_times min_def max_def split: if_splits)\n  from connectedD_interval[OF conn this, of xy] assms\n  obtain x y where \"xy = x * y\" \"x \\<in>\\<^sub>i X\" \"y \\<in>\\<^sub>i Y\" by (auto simp: set_of_eq)\n  then show ?thesis ..\nqed\n\nlemma set_of_times: \"set_of (X * Y) = {x * y | x y. x \\<in> set_of X \\<and> y \\<in> set_of Y}\"\n  for X Y::\"'a :: {linordered_ring, real_normed_algebra, linear_continuum_topology} interval\"\n  by (auto intro!: times_in_intervalI elim!: times_in_intervalE)\n\ninstance \"interval\" :: (linordered_idom) cancel_semigroup_add\nproof qed (auto simp: interval_eq_iff)\n\nlemma interval_mul_commute: \"A * B = B * A\" for A B:: \"'a::linordered_idom interval\"\n  by (simp add: interval_eq_iff lower_times upper_times ac_simps)\n\nlemma interval_times_zero_right[simp]: \"A * 0 = 0\" for A :: \"'a::linordered_ring interval\"\n  by (simp add: interval_eq_iff lower_times upper_times ac_simps)\n\nlemma interval_times_zero_left[simp]:\n  \"0 * A = 0\" for A :: \"'a::linordered_ring interval\"\n  by (simp add: interval_eq_iff lower_times upper_times ac_simps)\n\ninstantiation \"interval\" :: (\"{preorder,one}\") one\nbegin\n\nlift_definition one_interval::\"'a interval\" is \"(1, 1)\" by auto\nlemma lower_one[simp]: \"lower 1 = 1\"\n  by transfer auto\nlemma upper_one[simp]: \"upper 1 = 1\"\n  by transfer auto\ninstance proof qed\nend\n\ninstance interval :: (\"{one, preorder, linordered_semiring}\") power\nproof qed\n\nlemma set_of_one[simp]: \"set_of (1::'a::{one, order} interval) = {1}\"\n  by (auto simp: set_of_eq)\n\ninstance \"interval\" ::\n  (\"{linordered_idom,linordered_ring, real_normed_algebra, linear_continuum_topology}\") monoid_mult\n  apply standard\n  unfolding interval_eq_set_of_iff set_of_times\n  subgoal\n    by (auto simp: interval_eq_set_of_iff set_of_times; metis mult.assoc)\n  by auto\n\nlemma one_times_ivl_left[simp]: \"1 * A = A\" for A :: \"'a::linordered_idom interval\"\n  by (simp add: interval_eq_iff lower_times upper_times ac_simps min_def max_def)\n\nlemma one_times_ivl_right[simp]: \"A * 1 = A\" for A :: \"'a::linordered_idom interval\"\n  by (metis interval_mul_commute one_times_ivl_left)\n\nlemma set_of_power_mono: \"a^n \\<in> set_of (A^n)\" if \"a \\<in> set_of A\"\n  for a :: \"'a::linordered_idom\"\n  using that\n  by (induction n) (auto intro!: times_in_intervalI)\n\nlemma set_of_add_cong:\n  \"set_of (A + B) = set_of (A' + B')\"\n  if \"set_of A = set_of A'\" \"set_of B = set_of B'\"\n  for A :: \"'a::linordered_ab_group_add interval\"\n  unfolding set_of_plus that ..\n\nlemma set_of_add_inc_left:\n  \"set_of (A + B) \\<subseteq> set_of (A' + B)\"\n  if \"set_of A \\<subseteq> set_of A'\"\n  for A :: \"'a::linordered_ab_group_add interval\"\n  unfolding set_of_plus using that by (auto simp: set_plus_def)\n\nlemma set_of_add_inc_right:\n  \"set_of (A + B) \\<subseteq> set_of (A + B')\"\n  if \"set_of B \\<subseteq> set_of B'\"\n  for A :: \"'a::linordered_ab_group_add interval\"\n  using set_of_add_inc_left[OF that]\n  by (simp add: add.commute)\n\nlemma set_of_add_inc:\n  \"set_of (A + B) \\<subseteq> set_of (A' + B')\"\n  if \"set_of A \\<subseteq> set_of A'\" \"set_of B \\<subseteq> set_of B'\"\n  for A :: \"'a::linordered_ab_group_add interval\"\n  using set_of_add_inc_left[OF that(1)] set_of_add_inc_right[OF that(2)]\n  by auto\n\nlemma set_of_neg_inc:\n  \"set_of (-A) \\<subseteq> set_of (-A')\"\n  if \"set_of A \\<subseteq> set_of A'\"\n  for A :: \"'a::ordered_ab_group_add interval\"\n  using that\n  unfolding set_of_uminus\n  by auto\n\nlemma set_of_sub_inc_left:\n  \"set_of (A - B) \\<subseteq> set_of (A' - B)\"\n  if \"set_of A \\<subseteq> set_of A'\"\n  for A :: \"'a::linordered_ab_group_add interval\"\n  using that\n  unfolding set_of_minus\n  by auto\n\nlemma set_of_sub_inc_right:\n  \"set_of (A - B) \\<subseteq> set_of (A - B')\"\n  if \"set_of B \\<subseteq> set_of B'\"\n  for A :: \"'a::linordered_ab_group_add interval\"\n  using that\n  unfolding set_of_minus\n  by auto\n\nlemma set_of_sub_inc:\n  \"set_of (A - B) \\<subseteq> set_of (A' - B')\"\n  if \"set_of A \\<subseteq> set_of A'\" \"set_of B \\<subseteq> set_of B'\"\n  for A :: \"'a::linordered_idom interval\"\n  using set_of_sub_inc_left[OF that(1)] set_of_sub_inc_right[OF that(2)]\n  by auto\n\nlemma set_of_mul_inc_right:\n  \"set_of (A * B) \\<subseteq> set_of (A * B')\"\n  if \"set_of B \\<subseteq> set_of B'\"\n  for A :: \"'a::linordered_ring interval\"\n  using that\n  apply transfer\n  apply (clarsimp simp add: Let_def)\n  apply (intro conjI)\n         apply (metis linear min.coboundedI1 min.coboundedI2 mult_left_mono mult_left_mono_neg order_trans)\n        apply (metis linear min.coboundedI1 min.coboundedI2 mult_left_mono mult_left_mono_neg order_trans)\n       apply (metis linear min.coboundedI1 min.coboundedI2 mult_left_mono mult_left_mono_neg order_trans)\n      apply (metis linear min.coboundedI1 min.coboundedI2 mult_left_mono mult_left_mono_neg order_trans)\n     apply (metis linear max.coboundedI1 max.coboundedI2 mult_left_mono mult_left_mono_neg order_trans)\n    apply (metis linear max.coboundedI1 max.coboundedI2 mult_left_mono mult_left_mono_neg order_trans)\n   apply (metis linear max.coboundedI1 max.coboundedI2 mult_left_mono mult_left_mono_neg order_trans)\n  apply (metis linear max.coboundedI1 max.coboundedI2 mult_left_mono mult_left_mono_neg order_trans)\n  done\n\nlemma set_of_distrib_left:\n  \"set_of (B * (A1 + A2)) \\<subseteq> set_of (B * A1 + B * A2)\"\n  for A1 :: \"'a::linordered_ring interval\"\n  apply transfer\n  apply (clarsimp simp: Let_def distrib_left distrib_right)\n  apply (intro conjI)\n         apply (metis add_mono min.cobounded1 min.left_commute)\n        apply (metis add_mono min.cobounded1 min.left_commute)\n       apply (metis add_mono min.cobounded1 min.left_commute)\n      apply (metis add_mono min.assoc min.cobounded2)\n     apply (meson add_mono order.trans max.cobounded1 max.cobounded2)\n    apply (meson add_mono order.trans max.cobounded1 max.cobounded2)\n   apply (meson add_mono order.trans max.cobounded1 max.cobounded2)\n  apply (meson add_mono order.trans max.cobounded1 max.cobounded2)\n  done\n\nlemma set_of_distrib_right:\n  \"set_of ((A1 + A2) * B) \\<subseteq> set_of (A1 * B + A2 * B)\"\n  for A1 A2 B :: \"'a::{linordered_ring, real_normed_algebra, linear_continuum_topology} interval\"\n  unfolding set_of_times set_of_plus set_plus_def\n  apply clarsimp\n  subgoal for b a1 a2\n    apply (rule exI[where x=\"a1 * b\"])\n    apply (rule conjI)\n    subgoal by force\n    subgoal\n      apply (rule exI[where x=\"a2 * b\"])\n      apply (rule conjI)\n      subgoal by force\n      subgoal by (simp add: algebra_simps)\n      done\n    done\n  done\n\nlemma set_of_mul_inc_left:\n  \"set_of (A * B) \\<subseteq> set_of (A' * B)\"\n  if \"set_of A \\<subseteq> set_of A'\"\n  for A :: \"'a::{linordered_ring, real_normed_algebra, linear_continuum_topology} interval\"\n  using that\n  unfolding set_of_times\n  by auto\n\nlemma set_of_mul_inc:\n  \"set_of (A * B) \\<subseteq> set_of (A' * B')\"\n  if \"set_of A \\<subseteq> set_of A'\" \"set_of B \\<subseteq> set_of B'\"\n  for A :: \"'a::{linordered_ring, real_normed_algebra, linear_continuum_topology} interval\"\n  using that unfolding set_of_times by auto\n\nlemma set_of_pow_inc:\n  \"set_of (A^n) \\<subseteq> set_of (A'^n)\"\n  if \"set_of A \\<subseteq> set_of A'\"\n  for A :: \"'a::{linordered_idom, real_normed_algebra, linear_continuum_topology} interval\"\n  using that\n  by (induction n, simp_all add: set_of_mul_inc)\n\nlemma set_of_distrib_right_left:\n  \"set_of ((A1 + A2) * (B1 + B2)) \\<subseteq> set_of (A1 * B1 + A1 * B2 + A2 * B1 + A2 * B2)\"\n  for A1 :: \"'a::{linordered_idom, real_normed_algebra, linear_continuum_topology} interval\"\nproof-\n  have \"set_of ((A1 + A2) * (B1 + B2)) \\<subseteq> set_of (A1 * (B1 + B2) + A2 * (B1 + B2))\"\n    by (rule set_of_distrib_right)\n  also have \"... \\<subseteq> set_of ((A1 * B1 + A1 * B2) + A2 * (B1 + B2))\"\n    by (rule set_of_add_inc_left[OF set_of_distrib_left])\n  also have \"... \\<subseteq> set_of ((A1 * B1 + A1 * B2) + (A2 * B1 + A2 * B2))\"\n    by (rule set_of_add_inc_right[OF set_of_distrib_left])\n  finally show ?thesis\n    by (simp add: add.assoc)\nqed\n\nlemma mult_bounds_enclose_zero1:\n  \"min (la * lb) (min (la * ub) (min (lb * ua) (ua * ub))) \\<le> 0\"\n  \"0 \\<le> max (la * lb) (max (la * ub) (max (lb * ua) (ua * ub)))\"\n  if \"la \\<le> 0\" \"0 \\<le> ua\"\n  for la lb ua ub:: \"'a::linordered_idom\"\n  subgoal by (metis (no_types, opaque_lifting) that eq_iff min_le_iff_disj mult_zero_left mult_zero_right\n        zero_le_mult_iff)\n  subgoal by (metis that le_max_iff_disj mult_zero_right order_refl zero_le_mult_iff)\n  done\n\nlemma mult_bounds_enclose_zero2:\n  \"min (la * lb) (min (la * ub) (min (lb * ua) (ua * ub))) \\<le> 0\"\n  \"0 \\<le> max (la * lb) (max (la * ub) (max (lb * ua) (ua * ub)))\"\n  if \"lb \\<le> 0\" \"0 \\<le> ub\"\n  for la lb ua ub:: \"'a::linordered_idom\"\n  using mult_bounds_enclose_zero1[OF that, of la ua]\n  by (simp_all add: ac_simps)\n\nlemma set_of_mul_contains_zero:\n  \"0 \\<in> set_of (A * B)\"\n  if \"0 \\<in> set_of A \\<or> 0 \\<in> set_of B\"\n  for A :: \"'a::linordered_idom interval\"\n  using that\n  by (auto simp: set_of_eq lower_times upper_times algebra_simps mult_le_0_iff\n      mult_bounds_enclose_zero1 mult_bounds_enclose_zero2)\n\ninstance \"interval\" :: (linordered_semiring) mult_zero\n  apply standard\n  subgoal by transfer auto\n  subgoal by transfer auto\n  done\n\nlift_definition min_interval::\"'a::linorder interval \\<Rightarrow> 'a interval \\<Rightarrow> 'a interval\" is\n  \"\\<lambda>(l1, u1). \\<lambda>(l2, u2). (min l1 l2, min u1 u2)\"\n  by (auto simp: min_def)\nlemma lower_min_interval[simp]: \"lower (min_interval x y) = min (lower x) (lower y)\"\n  by transfer auto\nlemma upper_min_interval[simp]: \"upper (min_interval x y) = min (upper x) (upper y)\"\n  by transfer auto\n\nlemma min_intervalI:\n  \"a \\<in>\\<^sub>i A \\<Longrightarrow> b \\<in>\\<^sub>i B \\<Longrightarrow> min a b \\<in>\\<^sub>i min_interval A B\"\n  by (auto simp: set_of_eq min_def)\n\nlift_definition max_interval::\"'a::linorder interval \\<Rightarrow> 'a interval \\<Rightarrow> 'a interval\" is\n  \"\\<lambda>(l1, u1). \\<lambda>(l2, u2). (max l1 l2, max u1 u2)\"\n  by (auto simp: max_def)\nlemma lower_max_interval[simp]: \"lower (max_interval x y) = max (lower x) (lower y)\"\n  by transfer auto\nlemma upper_max_interval[simp]: \"upper (max_interval x y) = max (upper x) (upper y)\"\n  by transfer auto\n\nlemma max_intervalI:\n  \"a \\<in>\\<^sub>i A \\<Longrightarrow> b \\<in>\\<^sub>i B \\<Longrightarrow> max a b \\<in>\\<^sub>i max_interval A B\"\n  by (auto simp: set_of_eq max_def)\n\nlift_definition abs_interval::\"'a::linordered_idom interval \\<Rightarrow> 'a interval\" is\n  \"(\\<lambda>(l,u). (if l < 0 \\<and> 0 < u then 0 else min \\<bar>l\\<bar> \\<bar>u\\<bar>, max \\<bar>l\\<bar> \\<bar>u\\<bar>))\"\n  by auto\n\nlemma lower_abs_interval[simp]:\n  \"lower (abs_interval x) = (if lower x < 0 \\<and> 0 < upper x then 0 else min \\<bar>lower x\\<bar> \\<bar>upper x\\<bar>)\"\n  by transfer auto\nlemma upper_abs_interval[simp]: \"upper (abs_interval x) = max \\<bar>lower x\\<bar> \\<bar>upper x\\<bar>\"\n  by transfer auto\n\nlemma in_abs_intervalI1:\n  \"lx < 0 \\<Longrightarrow> 0 < ux \\<Longrightarrow> 0 \\<le> xa \\<Longrightarrow> xa \\<le> max (- lx) (ux) \\<Longrightarrow> xa \\<in> abs ` {lx..ux}\"\n  for xa::\"'a::linordered_idom\"\n  by (metis abs_minus_cancel abs_of_nonneg atLeastAtMost_iff image_eqI le_less le_max_iff_disj\n      le_minus_iff neg_le_0_iff_le order_trans)\n\nlemma in_abs_intervalI2:\n  \"min (\\<bar>lx\\<bar>) \\<bar>ux\\<bar> \\<le> xa \\<Longrightarrow> xa \\<le> max \\<bar>lx\\<bar> \\<bar>ux\\<bar> \\<Longrightarrow> lx \\<le> ux \\<Longrightarrow> 0 \\<le> lx \\<or> ux \\<le> 0 \\<Longrightarrow>\n    xa \\<in> abs ` {lx..ux}\"\n  for xa::\"'a::linordered_idom\"\n  by (force intro: image_eqI[where x=\"-xa\"] image_eqI[where x=\"xa\"])\n\nlemma set_of_abs_interval: \"set_of (abs_interval x) = abs ` set_of x\"\n  by (auto simp: set_of_eq not_less intro: in_abs_intervalI1 in_abs_intervalI2 cong del: image_cong_simp)\n\nfun split_domain :: \"('a::preorder interval \\<Rightarrow> 'a interval list) \\<Rightarrow> 'a interval list \\<Rightarrow> 'a interval list list\"\n  where \"split_domain split [] = [[]]\"\n  | \"split_domain split (I#Is) = (\n         let S = split I;\n             D = split_domain split Is\n         in concat (map (\\<lambda>d. map (\\<lambda>s. s # d) S) D)\n       )\"\n\ncontext notes [[typedef_overloaded]] begin\nlift_definition(code_dt) split_interval::\"'a::linorder interval \\<Rightarrow> 'a \\<Rightarrow> ('a interval \\<times> 'a interval)\"\n  is \"\\<lambda>(l, u) x. ((min l x, max l x), (min u x, max u x))\"\n  by (auto simp: min_def)\nend\n\nlemma split_domain_nonempty:\n  assumes \"\\<And>I. split I \\<noteq> []\"\n  shows \"split_domain split I \\<noteq> []\"\n  using last_in_set assms\n  by (induction I, auto)\n\nlemma lower_split_interval1: \"lower (fst (split_interval X m)) = min (lower X) m\"\n  and lower_split_interval2: \"lower (snd (split_interval X m)) = min (upper X) m\"\n  and upper_split_interval1: \"upper (fst (split_interval X m)) = max (lower X) m\"\n  and upper_split_interval2: \"upper (snd (split_interval X m)) = max (upper X) m\"\n  subgoal by transfer auto\n  subgoal by transfer (auto simp: min.commute)\n  subgoal by transfer (auto simp: )\n  subgoal by transfer (auto simp: )\n  done\n\nlemma split_intervalD: \"split_interval X x = (A, B) \\<Longrightarrow> set_of X \\<subseteq> set_of A \\<union> set_of B\"\n  unfolding set_of_eq\n  by transfer (auto simp: min_def max_def split: if_splits)\n\ninstantiation interval :: (\"{topological_space, preorder}\") topological_space\nbegin\n\ndefinition open_interval_def[code del]: \"open (X::'a interval set) =\n  (\\<forall>x\\<in>X.\n      \\<exists>A B.\n         open A \\<and>\n         open B \\<and>\n         lower x \\<in> A \\<and> upper x \\<in> B \\<and> Interval ` (A \\<times> B) \\<subseteq> X)\"\n\ninstance\nproof\n  show \"open (UNIV :: ('a interval) set)\"\n    unfolding open_interval_def by auto\nnext\n  fix S T :: \"('a interval) set\"\n  assume \"open S\" \"open T\"\n  show \"open (S \\<inter> T)\"\n    unfolding open_interval_def\n  proof (safe)\n    fix x assume \"x \\<in> S\" \"x \\<in> T\"\n    from \\<open>x \\<in> S\\<close> \\<open>open S\\<close> obtain Sl Su where S:\n      \"open Sl\" \"open Su\" \"lower x \\<in> Sl\" \"upper x \\<in> Su\" \"Interval ` (Sl \\<times> Su) \\<subseteq> S\"\n      by (auto simp: open_interval_def)\n    from \\<open>x \\<in> T\\<close> \\<open>open T\\<close> obtain Tl Tu where T:\n      \"open Tl\" \"open Tu\" \"lower x \\<in> Tl\" \"upper x \\<in> Tu\" \"Interval ` (Tl \\<times> Tu) \\<subseteq> T\"\n      by (auto simp: open_interval_def)\n\n    let ?L = \"Sl \\<inter> Tl\" and ?U = \"Su \\<inter> Tu\" \n    have \"open ?L \\<and> open ?U \\<and> lower x \\<in> ?L \\<and> upper x \\<in> ?U \\<and> Interval ` (?L \\<times> ?U) \\<subseteq> S \\<inter> T\"\n      using S T by (auto simp add: open_Int)\n    then show \"\\<exists>A B. open A \\<and> open B \\<and> lower x \\<in> A \\<and> upper x \\<in> B \\<and> Interval ` (A \\<times> B) \\<subseteq> S \\<inter> T\"\n      by fast\n  qed\nqed (unfold open_interval_def, fast)\n\nend\n\n\nsubsection \\<open>Quickcheck\\<close>\n\nlift_definition Ivl::\"'a \\<Rightarrow> 'a::preorder \\<Rightarrow> 'a interval\" is \"\\<lambda>a b. (min a b, b)\"\n  by (auto simp: min_def)\n\ninstantiation interval :: (\"{exhaustive,preorder}\") exhaustive\nbegin\n\ndefinition exhaustive_interval::\"('a interval \\<Rightarrow> (bool \\<times> term list) option)\n     \\<Rightarrow> natural \\<Rightarrow> (bool \\<times> term list) option\"\n  where\n    \"exhaustive_interval f d =\n    Quickcheck_Exhaustive.exhaustive (\\<lambda>x. Quickcheck_Exhaustive.exhaustive (\\<lambda>y. f (Ivl x y)) d) d\"\n\ninstance ..\n\nend\n\ncontext\n  includes term_syntax\nbegin\n\ndefinition [code_unfold]:\n  \"valtermify_interval x y = Code_Evaluation.valtermify (Ivl::'a::{preorder,typerep}\\<Rightarrow>_) {\\<cdot>} x {\\<cdot>} y\"\n\nend\n\ninstantiation interval :: (\"{full_exhaustive,preorder,typerep}\") full_exhaustive\nbegin\n\ndefinition full_exhaustive_interval::\n  \"('a interval \\<times> (unit \\<Rightarrow> term) \\<Rightarrow> (bool \\<times> term list) option)\n     \\<Rightarrow> natural \\<Rightarrow> (bool \\<times> term list) option\" where\n  \"full_exhaustive_interval f d =\n    Quickcheck_Exhaustive.full_exhaustive\n      (\\<lambda>x. Quickcheck_Exhaustive.full_exhaustive (\\<lambda>y. f (valtermify_interval x y)) d) d\"\n\ninstance ..\n\nend\n\ninstantiation interval :: (\"{random,preorder,typerep}\") random\nbegin\n\ndefinition random_interval ::\n  \"natural\n  \\<Rightarrow> natural \\<times> natural\n     \\<Rightarrow> ('a interval \\<times> (unit \\<Rightarrow> term)) \\<times> natural \\<times> natural\" where\n  \"random_interval i =\n  scomp (Quickcheck_Random.random i)\n    (\\<lambda>man. scomp (Quickcheck_Random.random i) (\\<lambda>exp. Pair (valtermify_interval man exp)))\"\n\ninstance ..\n\nend\n\nlifting_update interval.lifting\nlifting_forget interval.lifting\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/Interval.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045966995028, "lm_q2_score": 0.8198933293122506, "lm_q1q2_score": 0.7274131305690879}}
{"text": "(*  Title:      Doc/Functions/Functions.thy\n    Author:     Alexander Krauss, TU Muenchen\n\nTutorial for function definitions with the new \"function\" package.\n*)\n\ntheory Functions\nimports Main\nbegin\n\nsection \\<open>Function Definitions for Dummies\\<close>\n\ntext \\<open>\n  In most cases, defining a recursive function is just as simple as other definitions:\n\\<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>\n  The syntax is rather self-explanatory: We introduce a function by\n  giving its name, its type, \n  and a set of defining recursive equations.\n  If we leave out the type, the most general type will be\n  inferred, which can sometimes lead to surprises: Since both \\<^term>\\<open>1::nat\\<close> and \\<open>+\\<close> are overloaded, we would end up\n  with \\<open>fib :: nat \\<Rightarrow> 'a::{one,plus}\\<close>.\n\\<close>\n\ntext \\<open>\n  The function always terminates, since its argument gets smaller in\n  every recursive call. \n  Since HOL is a logic of total functions, termination is a\n  fundamental requirement to prevent inconsistencies\\footnote{From the\n  \\qt{definition} \\<open>f(n) = f(n) + 1\\<close> we could prove \n  \\<open>0 = 1\\<close> by subtracting \\<open>f(n)\\<close> on both sides.}.\n  Isabelle tries to prove termination automatically when a definition\n  is made. In \\S\\ref{termination}, we will look at cases where this\n  fails and see what to do then.\n\\<close>\n\nsubsection \\<open>Pattern matching\\<close>\n\ntext \\<open>\\label{patmatch}\n  Like in functional programming, we can use pattern matching to\n  define functions. At the moment we will only consider \\emph{constructor\n  patterns}, which only consist of datatype constructors and\n  variables. Furthermore, patterns must be linear, i.e.\\ all variables\n  on the left hand side of an equation must be distinct. In\n  \\S\\ref{genpats} we discuss more general pattern matching.\n\n  If patterns overlap, the order of the equations is taken into\n  account. The following function inserts a fixed element between any\n  two elements of a list:\n\\<close>\n\nfun sep :: \"'a \\<Rightarrow> 'a list \\<Rightarrow> 'a list\"\nwhere\n  \"sep a (x#y#xs) = x # a # sep a (y # xs)\"\n| \"sep a xs       = xs\"\n\ntext \\<open>\n  Overlapping patterns are interpreted as \\qt{increments} to what is\n  already there: The second equation is only meant for the cases where\n  the first one does not match. Consequently, Isabelle replaces it\n  internally by the remaining cases, making the patterns disjoint:\n\\<close>\n\nthm sep.simps\n\ntext \\<open>@{thm [display] sep.simps[no_vars]}\\<close>\n\ntext \\<open>\n  \\noindent The equations from function definitions are automatically used in\n  simplification:\n\\<close>\n\nlemma \"sep 0 [1, 2, 3] = [1, 0, 2, 0, 3]\"\nby simp\n\nsubsection \\<open>Induction\\<close>\n\ntext \\<open>\n\n  Isabelle provides customized induction rules for recursive\n  functions. These rules follow the recursive structure of the\n  definition. Here is the rule @{thm [source] sep.induct} arising from the\n  above definition of \\<^const>\\<open>sep\\<close>:\n\n  @{thm [display] sep.induct}\n  \n  We have a step case for list with at least two elements, and two\n  base cases for the zero- and the one-element list. Here is a simple\n  proof about \\<^const>\\<open>sep\\<close> and \\<^const>\\<open>map\\<close>\n\\<close>\n\nlemma \"map f (sep x ys) = sep (f x) (map f ys)\"\napply (induct x ys rule: sep.induct)\n\ntext \\<open>\n  We get three cases, like in the definition.\n\n  @{subgoals [display]}\n\\<close>\n\napply auto \ndone\ntext \\<open>\n\n  With the \\cmd{fun} command, you can define about 80\\% of the\n  functions that occur in practice. The rest of this tutorial explains\n  the remaining 20\\%.\n\\<close>\n\n\nsection \\<open>fun vs.\\ function\\<close>\n\ntext \\<open>\n  The \\cmd{fun} command provides a\n  convenient shorthand notation for simple function definitions. In\n  this mode, Isabelle tries to solve all the necessary proof obligations\n  automatically. If any proof fails, the definition is\n  rejected. This can either mean that the definition is indeed faulty,\n  or that the default proof procedures are just not smart enough (or\n  rather: not designed) to handle the definition.\n\n  By expanding the abbreviation to the more verbose \\cmd{function} command, these proof obligations become visible and can be analyzed or\n  solved manually. The expansion from \\cmd{fun} to \\cmd{function} is as follows:\n\n\\end{isamarkuptext}\n\n\n\\[\\left[\\;\\begin{minipage}{0.25\\textwidth}\\vspace{6pt}\n\\cmd{fun} \\<open>f :: \\<tau>\\<close>\\\\%\n\\cmd{where}\\\\%\n\\hspace*{2ex}{\\it equations}\\\\%\n\\hspace*{2ex}\\vdots\\vspace*{6pt}\n\\end{minipage}\\right]\n\\quad\\equiv\\quad\n\\left[\\;\\begin{minipage}{0.48\\textwidth}\\vspace{6pt}\n\\cmd{function} \\<open>(\\<close>\\cmd{sequential}\\<open>) f :: \\<tau>\\<close>\\\\%\n\\cmd{where}\\\\%\n\\hspace*{2ex}{\\it equations}\\\\%\n\\hspace*{2ex}\\vdots\\\\%\n\\cmd{by} \\<open>pat_completeness auto\\<close>\\\\%\n\\cmd{termination by} \\<open>lexicographic_order\\<close>\\vspace{6pt}\n\\end{minipage}\n\\right]\\]\n\n\\begin{isamarkuptext}\n  \\vspace*{1em}\n  \\noindent Some details have now become explicit:\n\n  \\begin{enumerate}\n  \\item The \\cmd{sequential} option enables the preprocessing of\n  pattern overlaps which we already saw. Without this option, the equations\n  must already be disjoint and complete. The automatic completion only\n  works with constructor patterns.\n\n  \\item A function definition produces a proof obligation which\n  expresses completeness and compatibility of patterns (we talk about\n  this later). The combination of the methods \\<open>pat_completeness\\<close> and\n  \\<open>auto\\<close> is used to solve this proof obligation.\n\n  \\item A termination proof follows the definition, started by the\n  \\cmd{termination} command. This will be explained in \\S\\ref{termination}.\n \\end{enumerate}\n  Whenever a \\cmd{fun} command fails, it is usually a good idea to\n  expand the syntax to the more verbose \\cmd{function} form, to see\n  what is actually going on.\n\\<close>\n\n\nsection \\<open>Termination\\<close>\n\ntext \\<open>\\label{termination}\n  The method \\<open>lexicographic_order\\<close> is the default method for\n  termination proofs. It can prove termination of a\n  certain class of functions by searching for a suitable lexicographic\n  combination of size measures. Of course, not all functions have such\n  a simple termination argument. For them, we can specify the termination\n  relation manually.\n\\<close>\n\nsubsection \\<open>The {\\tt relation} method\\<close>\ntext\\<open>\n  Consider the following function, which sums up natural numbers up to\n  \\<open>N\\<close>, using a counter \\<open>i\\<close>:\n\\<close>\n\nfunction sum :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\"\nwhere\n  \"sum i N = (if i > N then 0 else i + sum (Suc i) N)\"\nby pat_completeness auto\n\ntext \\<open>\n  \\noindent The \\<open>lexicographic_order\\<close> method fails on this example, because none of the\n  arguments decreases in the recursive call, with respect to the standard size ordering.\n  To prove termination manually, we must provide a custom wellfounded relation.\n\n  The termination argument for \\<open>sum\\<close> is based on the fact that\n  the \\emph{difference} between \\<open>i\\<close> and \\<open>N\\<close> gets\n  smaller in every step, and that the recursion stops when \\<open>i\\<close>\n  is greater than \\<open>N\\<close>. Phrased differently, the expression \n  \\<open>N + 1 - i\\<close> always decreases.\n\n  We can use this expression as a measure function suitable to prove termination.\n\\<close>\n\ntermination sum\napply (relation \"measure (\\<lambda>(i,N). N + 1 - i)\")\n\ntext \\<open>\n  The \\cmd{termination} command sets up the termination goal for the\n  specified function \\<open>sum\\<close>. If the function name is omitted, it\n  implicitly refers to the last function definition.\n\n  The \\<open>relation\\<close> method takes a relation of\n  type \\<^typ>\\<open>('a \\<times> 'a) set\\<close>, where \\<^typ>\\<open>'a\\<close> is the argument type of\n  the function. If the function has multiple curried arguments, then\n  these are packed together into a tuple, as it happened in the above\n  example.\n\n  The predefined function @{term[source] \"measure :: ('a \\<Rightarrow> nat) \\<Rightarrow> ('a \\<times> 'a) set\"} constructs a\n  wellfounded relation from a mapping into the natural numbers (a\n  \\emph{measure function}). \n\n  After the invocation of \\<open>relation\\<close>, we must prove that (a)\n  the relation we supplied is wellfounded, and (b) that the arguments\n  of recursive calls indeed decrease with respect to the\n  relation:\n\n  @{subgoals[display,indent=0]}\n\n  These goals are all solved by \\<open>auto\\<close>:\n\\<close>\n\napply auto\ndone\n\ntext \\<open>\n  Let us complicate the function a little, by adding some more\n  recursive calls: \n\\<close>\n\nfunction foo :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\"\nwhere\n  \"foo i N = (if i > N \n              then (if N = 0 then 0 else foo 0 (N - 1))\n              else i + foo (Suc i) N)\"\nby pat_completeness auto\n\ntext \\<open>\n  When \\<open>i\\<close> has reached \\<open>N\\<close>, it starts at zero again\n  and \\<open>N\\<close> is decremented.\n  This corresponds to a nested\n  loop where one index counts up and the other down. Termination can\n  be proved using a lexicographic combination of two measures, namely\n  the value of \\<open>N\\<close> and the above difference. The \\<^const>\\<open>measures\\<close> combinator generalizes \\<open>measure\\<close> by taking a\n  list of measure functions.  \n\\<close>\n\ntermination \nby (relation \"measures [\\<lambda>(i, N). N, \\<lambda>(i,N). N + 1 - i]\") auto\n\nsubsection \\<open>How \\<open>lexicographic_order\\<close> works\\<close>\n\n(*fun fails :: \"nat \\<Rightarrow> nat list \\<Rightarrow> nat\"\nwhere\n  \"fails a [] = a\"\n| \"fails a (x#xs) = fails (x + a) (x # xs)\"\n*)\n\ntext \\<open>\n  To see how the automatic termination proofs work, let's look at an\n  example where it fails\\footnote{For a detailed discussion of the\n  termination prover, see \\<^cite>\\<open>bulwahnKN07\\<close>}:\n\n\\end{isamarkuptext}  \n\\cmd{fun} \\<open>fails :: \"nat \\<Rightarrow> nat list \\<Rightarrow> nat\"\\<close>\\\\%\n\\cmd{where}\\\\%\n\\hspace*{2ex}\\<open>\"fails a [] = a\"\\<close>\\\\%\n|\\hspace*{1.5ex}\\<open>\"fails a (x#xs) = fails (x + a) (x#xs)\"\\<close>\\\\\n\\begin{isamarkuptext}\n\n\\noindent Isabelle responds with the following error:\n\n\\begin{isabelle}\n*** Unfinished subgoals:\\newline\n*** (a, 1, <):\\newline\n*** \\ 1.~\\<open>\\<And>x. x = 0\\<close>\\newline\n*** (a, 1, <=):\\newline\n*** \\ 1.~False\\newline\n*** (a, 2, <):\\newline\n*** \\ 1.~False\\newline\n*** Calls:\\newline\n*** a) \\<open>(a, x # xs) -->> (x + a, x # xs)\\<close>\\newline\n*** Measures:\\newline\n*** 1) \\<open>\\<lambda>x. size (fst x)\\<close>\\newline\n*** 2) \\<open>\\<lambda>x. size (snd x)\\<close>\\newline\n*** Result matrix:\\newline\n*** \\ \\ \\ \\ 1\\ \\ 2  \\newline\n*** a:  ?   <= \\newline\n*** Could not find lexicographic termination order.\\newline\n*** At command \"fun\".\\newline\n\\end{isabelle}\n\\<close>\ntext \\<open>\n  The key to this error message is the matrix at the bottom. The rows\n  of that matrix correspond to the different recursive calls (In our\n  case, there is just one). The columns are the function's arguments \n  (expressed through different measure functions, which map the\n  argument tuple to a natural number). \n\n  The contents of the matrix summarize what is known about argument\n  descents: The second argument has a weak descent (\\<open><=\\<close>) at the\n  recursive call, and for the first argument nothing could be proved,\n  which is expressed by \\<open>?\\<close>. In general, there are the values\n  \\<open><\\<close>, \\<open><=\\<close> and \\<open>?\\<close>.\n\n  For the failed proof attempts, the unfinished subgoals are also\n  printed. Looking at these will often point to a missing lemma.\n\\<close>\n\nsubsection \\<open>The \\<open>size_change\\<close> method\\<close>\n\ntext \\<open>\n  Some termination goals that are beyond the powers of\n  \\<open>lexicographic_order\\<close> can be solved automatically by the\n  more powerful \\<open>size_change\\<close> method, which uses a variant of\n  the size-change principle, together with some other\n  techniques. While the details are discussed\n  elsewhere \\<^cite>\\<open>krauss_phd\\<close>,\n  here are a few typical situations where\n  \\<open>lexicographic_order\\<close> has difficulties and \\<open>size_change\\<close>\n  may be worth a try:\n  \\begin{itemize}\n  \\item Arguments are permuted in a recursive call.\n  \\item Several mutually recursive functions with multiple arguments.\n  \\item Unusual control flow (e.g., when some recursive calls cannot\n  occur in sequence).\n  \\end{itemize}\n\n  Loading the theory \\<open>Multiset\\<close> makes the \\<open>size_change\\<close>\n  method a bit stronger: it can then use multiset orders internally.\n\\<close>\n\nsubsection \\<open>Configuring simplification rules for termination proofs\\<close>\n\ntext \\<open>\n  Since both \\<open>lexicographic_order\\<close> and \\<open>size_change\\<close> rely on the simplifier internally,\n  there can sometimes be the need for adding additional simp rules to them.\n  This can be done either as arguments to the methods themselves, or globally via the\n  theorem attribute \\<open>termination_simp\\<close>, which is useful in rare cases.\n\\<close>\n\nsection \\<open>Mutual Recursion\\<close>\n\ntext \\<open>\n  If two or more functions call one another mutually, they have to be defined\n  in one step. Here are \\<open>even\\<close> and \\<open>odd\\<close>:\n\\<close>\n\nfunction even :: \"nat \\<Rightarrow> bool\"\n    and odd  :: \"nat \\<Rightarrow> bool\"\nwhere\n  \"even 0 = True\"\n| \"odd 0 = False\"\n| \"even (Suc n) = odd n\"\n| \"odd (Suc n) = even n\"\nby pat_completeness auto\n\ntext \\<open>\n  To eliminate the mutual dependencies, Isabelle internally\n  creates a single function operating on the sum\n  type \\<^typ>\\<open>nat + nat\\<close>. Then, \\<^const>\\<open>even\\<close> and \\<^const>\\<open>odd\\<close> are\n  defined as projections. Consequently, termination has to be proved\n  simultaneously for both functions, by specifying a measure on the\n  sum type: \n\\<close>\n\ntermination \nby (relation \"measure (\\<lambda>x. case x of Inl n \\<Rightarrow> n | Inr n \\<Rightarrow> n)\") auto\n\ntext \\<open>\n  We could also have used \\<open>lexicographic_order\\<close>, which\n  supports mutual recursive termination proofs to a certain extent.\n\\<close>\n\nsubsection \\<open>Induction for mutual recursion\\<close>\n\ntext \\<open>\n\n  When functions are mutually recursive, proving properties about them\n  generally requires simultaneous induction. The induction rule @{thm [source] \"even_odd.induct\"}\n  generated from the above definition reflects this.\n\n  Let us prove something about \\<^const>\\<open>even\\<close> and \\<^const>\\<open>odd\\<close>:\n\\<close>\n\nlemma even_odd_mod2:\n  \"even n = (n mod 2 = 0)\"\n  \"odd n = (n mod 2 = 1)\"\n\ntext \\<open>\n  We apply simultaneous induction, specifying the induction variable\n  for both goals, separated by \\cmd{and}:\\<close>\n\napply (induct n and n rule: even_odd.induct)\n\ntext \\<open>\n  We get four subgoals, which correspond to the clauses in the\n  definition of \\<^const>\\<open>even\\<close> and \\<^const>\\<open>odd\\<close>:\n  @{subgoals[display,indent=0]}\n  Simplification solves the first two goals, leaving us with two\n  statements about the \\<open>mod\\<close> operation to prove:\n\\<close>\n\napply simp_all\n\ntext \\<open>\n  @{subgoals[display,indent=0]} \n\n  \\noindent These can be handled by Isabelle's arithmetic decision procedures.\n  \n\\<close>\n\napply arith\napply arith\ndone\n\ntext \\<open>\n  In proofs like this, the simultaneous induction is really essential:\n  Even if we are just interested in one of the results, the other\n  one is necessary to strengthen the induction hypothesis. If we leave\n  out the statement about \\<^const>\\<open>odd\\<close> and just write \\<^term>\\<open>True\\<close> instead,\n  the same proof fails:\n\\<close>\n\nlemma failed_attempt:\n  \"even n = (n mod 2 = 0)\"\n  \"True\"\napply (induct n rule: even_odd.induct)\n\ntext \\<open>\n  \\noindent Now the third subgoal is a dead end, since we have no\n  useful induction hypothesis available:\n\n  @{subgoals[display,indent=0]} \n\\<close>\n\noops\n\nsection \\<open>Elimination\\<close>\n\ntext \\<open>\n  A definition of function \\<open>f\\<close> gives rise to two kinds of elimination rules. Rule \\<open>f.cases\\<close>\n  simply describes case analysis according to the patterns used in the definition:\n\\<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\nthm list_to_option.cases\ntext \\<open>\n  @{thm[display] list_to_option.cases}\n\n  Note that this rule does not mention the function at all, but only describes the cases used for\n  defining it. In contrast, the rule @{thm[source] list_to_option.elims} also tell us what the function\n  value will be in each case:\n\\<close>\nthm list_to_option.elims\ntext \\<open>\n  @{thm[display] list_to_option.elims}\n\n  \\noindent\n  This lets us eliminate an assumption of the form \\<^prop>\\<open>list_to_option xs = y\\<close> and replace it\n  with the two cases, e.g.:\n\\<close>\n\nlemma \"list_to_option xs = y \\<Longrightarrow> P\"\nproof (erule list_to_option.elims)\n  fix x assume \"xs = [x]\" \"y = Some x\" thus P sorry\nnext\n  assume \"xs = []\" \"y = None\" thus P sorry\nnext\n  fix a b xs' assume \"xs = a # b # xs'\" \"y = None\" thus P sorry\nqed\n\n\ntext \\<open>\n  Sometimes it is convenient to derive specialized versions of the \\<open>elim\\<close> rules above and\n  keep them around as facts explicitly. For example, it is natural to show that if \n  \\<^prop>\\<open>list_to_option xs = Some y\\<close>, then \\<^term>\\<open>xs\\<close> must be a singleton. The command \n  \\cmd{fun\\_cases} derives such facts automatically, by instantiating and simplifying the general \n  elimination rules given some pattern:\n\\<close>\n\nfun_cases list_to_option_SomeE[elim]: \"list_to_option xs = Some y\"\n\nthm list_to_option_SomeE\ntext \\<open>\n  @{thm[display] list_to_option_SomeE}\n\\<close>\n\n\nsection \\<open>General pattern matching\\<close>\ntext\\<open>\\label{genpats}\\<close>\n\nsubsection \\<open>Avoiding automatic pattern splitting\\<close>\n\ntext \\<open>\n\n  Up to now, we used pattern matching only on datatypes, and the\n  patterns were always disjoint and complete, and if they weren't,\n  they were made disjoint automatically like in the definition of\n  \\<^const>\\<open>sep\\<close> in \\S\\ref{patmatch}.\n\n  This automatic splitting can significantly increase the number of\n  equations involved, and this is not always desirable. The following\n  example shows the problem:\n  \n  Suppose we are modeling incomplete knowledge about the world by a\n  three-valued datatype, which has values \\<^term>\\<open>T\\<close>, \\<^term>\\<open>F\\<close>\n  and \\<^term>\\<open>X\\<close> for true, false and uncertain propositions, respectively. \n\\<close>\n\ndatatype P3 = T | F | X\n\ntext \\<open>\\noindent Then the conjunction of such values can be defined as follows:\\<close>\n\nfun And :: \"P3 \\<Rightarrow> P3 \\<Rightarrow> P3\"\nwhere\n  \"And T p = p\"\n| \"And p T = p\"\n| \"And p F = F\"\n| \"And F p = F\"\n| \"And X X = X\"\n\n\ntext \\<open>\n  This definition is useful, because the equations can directly be used\n  as simplification rules. But the patterns overlap: For example,\n  the expression \\<^term>\\<open>And T T\\<close> is matched by both the first and\n  the second equation. By default, Isabelle makes the patterns disjoint by\n  splitting them up, producing instances:\n\\<close>\n\nthm And.simps\n\ntext \\<open>\n  @{thm[indent=4] And.simps}\n  \n  \\vspace*{1em}\n  \\noindent There are several problems with this:\n\n  \\begin{enumerate}\n  \\item If the datatype has many constructors, there can be an\n  explosion of equations. For \\<^const>\\<open>And\\<close>, we get seven instead of\n  five equations, which can be tolerated, but this is just a small\n  example.\n\n  \\item Since splitting makes the equations \\qt{less general}, they\n  do not always match in rewriting. While the term \\<^term>\\<open>And x F\\<close>\n  can be simplified to \\<^term>\\<open>F\\<close> with the original equations, a\n  (manual) case split on \\<^term>\\<open>x\\<close> is now necessary.\n\n  \\item The splitting also concerns the induction rule @{thm [source]\n  \"And.induct\"}. Instead of five premises it now has seven, which\n  means that our induction proofs will have more cases.\n\n  \\item In general, it increases clarity if we get the same definition\n  back which we put in.\n  \\end{enumerate}\n\n  If we do not want the automatic splitting, we can switch it off by\n  leaving out the \\cmd{sequential} option. However, we will have to\n  prove that our pattern matching is consistent\\footnote{This prevents\n  us from defining something like \\<^term>\\<open>f x = True\\<close> and \\<^term>\\<open>f x\n  = False\\<close> simultaneously.}:\n\\<close>\n\nfunction And2 :: \"P3 \\<Rightarrow> P3 \\<Rightarrow> P3\"\nwhere\n  \"And2 T p = p\"\n| \"And2 p T = p\"\n| \"And2 p F = F\"\n| \"And2 F p = F\"\n| \"And2 X X = X\"\n\ntext \\<open>\n  \\noindent Now let's look at the proof obligations generated by a\n  function definition. In this case, they are:\n\n  @{subgoals[display,indent=0]}\\vspace{-1.2em}\\hspace{3cm}\\vdots\\vspace{1.2em}\n\n  The first subgoal expresses the completeness of the patterns. It has\n  the form of an elimination rule and states that every \\<^term>\\<open>x\\<close> of\n  the function's input type must match at least one of the patterns\\footnote{Completeness could\n  be equivalently stated as a disjunction of existential statements: \n\\<^term>\\<open>(\\<exists>p. x = (T, p)) \\<or> (\\<exists>p. x = (p, T)) \\<or> (\\<exists>p. x = (p, F)) \\<or>\n  (\\<exists>p. x = (F, p)) \\<or> (x = (X, X))\\<close>, and you can use the method \\<open>atomize_elim\\<close> to get that form instead.}. If the patterns just involve\n  datatypes, we can solve it with the \\<open>pat_completeness\\<close>\n  method:\n\\<close>\n\napply pat_completeness\n\ntext \\<open>\n  The remaining subgoals express \\emph{pattern compatibility}. We do\n  allow that an input value matches multiple patterns, but in this\n  case, the result (i.e.~the right hand sides of the equations) must\n  also be equal. For each pair of two patterns, there is one such\n  subgoal. Usually this needs injectivity of the constructors, which\n  is used automatically by \\<open>auto\\<close>.\n\\<close>\n\nby auto\ntermination by (relation \"{}\") simp\n\n\nsubsection \\<open>Non-constructor patterns\\<close>\n\ntext \\<open>\n  Most of Isabelle's basic types take the form of inductive datatypes,\n  and usually pattern matching works on the constructors of such types. \n  However, this need not be always the case, and the \\cmd{function}\n  command handles other kind of patterns, too.\n\n  One well-known instance of non-constructor patterns are\n  so-called \\emph{$n+k$-patterns}, which are a little controversial in\n  the functional programming world. Here is the initial fibonacci\n  example with $n+k$-patterns:\n\\<close>\n\nfunction fib2 :: \"nat \\<Rightarrow> nat\"\nwhere\n  \"fib2 0 = 1\"\n| \"fib2 1 = 1\"\n| \"fib2 (n + 2) = fib2 n + fib2 (Suc n)\"\n\ntext \\<open>\n  This kind of matching is again justified by the proof of pattern\n  completeness and compatibility. \n  The proof obligation for pattern completeness states that every natural number is\n  either \\<^term>\\<open>0::nat\\<close>, \\<^term>\\<open>1::nat\\<close> or \\<^term>\\<open>n +\n  (2::nat)\\<close>:\n\n  @{subgoals[display,indent=0,goals_limit=1]}\n\n  This is an arithmetic triviality, but unfortunately the\n  \\<open>arith\\<close> method cannot handle this specific form of an\n  elimination rule. However, we can use the method \\<open>atomize_elim\\<close> to do an ad-hoc conversion to a disjunction of\n  existentials, which can then be solved by the arithmetic decision procedure.\n  Pattern compatibility and termination are automatic as usual.\n\\<close>\napply atomize_elim\napply arith\napply auto\ndone\ntermination by lexicographic_order\ntext \\<open>\n  We can stretch the notion of pattern matching even more. The\n  following function is not a sensible functional program, but a\n  perfectly valid mathematical definition:\n\\<close>\n\nfunction ev :: \"nat \\<Rightarrow> bool\"\nwhere\n  \"ev (2 * n) = True\"\n| \"ev (2 * n + 1) = False\"\napply atomize_elim\nby arith+\ntermination by (relation \"{}\") simp\n\ntext \\<open>\n  This general notion of pattern matching gives you a certain freedom\n  in writing down specifications. However, as always, such freedom should\n  be used with care:\n\n  If we leave the area of constructor\n  patterns, we have effectively departed from the world of functional\n  programming. This means that it is no longer possible to use the\n  code generator, and expect it to generate ML code for our\n  definitions. Also, such a specification might not work very well together with\n  simplification. Your mileage may vary.\n\\<close>\n\n\nsubsection \\<open>Conditional equations\\<close>\n\ntext \\<open>\n  The function package also supports conditional equations, which are\n  similar to guards in a language like Haskell. Here is Euclid's\n  algorithm written with conditional patterns\\footnote{Note that the\n  patterns are also overlapping in the base case}:\n\\<close>\n\nfunction gcd :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\"\nwhere\n  \"gcd x 0 = x\"\n| \"gcd 0 y = y\"\n| \"x < y \\<Longrightarrow> gcd (Suc x) (Suc y) = gcd (Suc x) (y - x)\"\n| \"\\<not> x < y \\<Longrightarrow> gcd (Suc x) (Suc y) = gcd (x - y) (Suc y)\"\nby (atomize_elim, auto, arith)\ntermination by lexicographic_order\n\ntext \\<open>\n  By now, you can probably guess what the proof obligations for the\n  pattern completeness and compatibility look like. \n\n  Again, functions with conditional patterns are not supported by the\n  code generator.\n\\<close>\n\n\nsubsection \\<open>Pattern matching on strings\\<close>\n\ntext \\<open>\n  As strings (as lists of characters) are normal datatypes, pattern\n  matching on them is possible, but somewhat problematic. Consider the\n  following definition:\n\n\\end{isamarkuptext}\n\\noindent\\cmd{fun} \\<open>check :: \"string \\<Rightarrow> bool\"\\<close>\\\\%\n\\cmd{where}\\\\%\n\\hspace*{2ex}\\<open>\"check (''good'') = True\"\\<close>\\\\%\n\\<open>| \"check s = False\"\\<close>\n\\begin{isamarkuptext}\n\n  \\noindent An invocation of the above \\cmd{fun} command does not\n  terminate. What is the problem? Strings are lists of characters, and\n  characters are a datatype with a lot of constructors. Splitting the\n  catch-all pattern thus leads to an explosion of cases, which cannot\n  be handled by Isabelle.\n\n  There are two things we can do here. Either we write an explicit\n  \\<open>if\\<close> on the right hand side, or we can use conditional patterns:\n\\<close>\n\nfunction check :: \"string \\<Rightarrow> bool\"\nwhere\n  \"check (''good'') = True\"\n| \"s \\<noteq> ''good'' \\<Longrightarrow> check s = False\"\nby auto\ntermination by (relation \"{}\") simp\n\n\nsection \\<open>Partiality \\label{sec:partiality}\\<close>\n\ntext \\<open>\n  In HOL, all functions are total. A function \\<^term>\\<open>f\\<close> applied to\n  \\<^term>\\<open>x\\<close> always has the value \\<^term>\\<open>f x\\<close>, and there is no notion\n  of undefinedness. \n  This is why we have to do termination\n  proofs when defining functions: The proof justifies that the\n  function can be defined by wellfounded recursion.\n\n  However, the \\cmd{function} package does support partiality to a\n  certain extent. Let's look at the following function which looks\n  for a zero of a given function f. \n\\<close>\n\nfunction (*<*)(domintros)(*>*)findzero :: \"(nat \\<Rightarrow> nat) \\<Rightarrow> nat \\<Rightarrow> nat\"\nwhere\n  \"findzero f n = (if f n = 0 then n else findzero f (Suc n))\"\nby pat_completeness auto\n\ntext \\<open>\n  \\noindent Clearly, any attempt of a termination proof must fail. And without\n  that, we do not get the usual rules \\<open>findzero.simps\\<close> and \n  \\<open>findzero.induct\\<close>. So what was the definition good for at all?\n\\<close>\n\nsubsection \\<open>Domain predicates\\<close>\n\ntext \\<open>\n  The trick is that Isabelle has not only defined the function \\<^const>\\<open>findzero\\<close>, but also\n  a predicate \\<^term>\\<open>findzero_dom\\<close> that characterizes the values where the function\n  terminates: the \\emph{domain} of the function. If we treat a\n  partial function just as a total function with an additional domain\n  predicate, we can derive simplification and\n  induction rules as we do for total functions. They are guarded\n  by domain conditions and are called \\<open>psimps\\<close> and \\<open>pinduct\\<close>: \n\\<close>\n\ntext \\<open>\n  \\noindent\\begin{minipage}{0.79\\textwidth}@{thm[display,margin=85] findzero.psimps}\\end{minipage}\n  \\hfill(@{thm [source] \"findzero.psimps\"})\n  \\vspace{1em}\n\n  \\noindent\\begin{minipage}{0.79\\textwidth}@{thm[display,margin=85] findzero.pinduct}\\end{minipage}\n  \\hfill(@{thm [source] \"findzero.pinduct\"})\n\\<close>\n\ntext \\<open>\n  Remember that all we\n  are doing here is use some tricks to make a total function appear\n  as if it was partial. We can still write the term \\<^term>\\<open>findzero\n  (\\<lambda>x. 1) 0\\<close> and like any other term of type \\<^typ>\\<open>nat\\<close> it is equal\n  to some natural number, although we might not be able to find out\n  which one. The function is \\emph{underdefined}.\n\n  But it is defined enough to prove something interesting about it. We\n  can prove that if \\<^term>\\<open>findzero f n\\<close>\n  terminates, it indeed returns a zero of \\<^term>\\<open>f\\<close>:\n\\<close>\n\nlemma findzero_zero: \"findzero_dom (f, n) \\<Longrightarrow> f (findzero f n) = 0\"\n\ntext \\<open>\\noindent We apply induction as usual, but using the partial induction\n  rule:\\<close>\n\napply (induct f n rule: findzero.pinduct)\n\ntext \\<open>\\noindent This gives the following subgoals:\n\n  @{subgoals[display,indent=0]}\n\n  \\noindent The hypothesis in our lemma was used to satisfy the first premise in\n  the induction rule. However, we also get \\<^term>\\<open>findzero_dom (f, n)\\<close> as a local assumption in the induction step. This\n  allows unfolding \\<^term>\\<open>findzero f n\\<close> using the \\<open>psimps\\<close>\n  rule, and the rest is trivial.\n\\<close>\napply (simp add: findzero.psimps)\ndone\n\ntext \\<open>\n  Proofs about partial functions are often not harder than for total\n  functions. Fig.~\\ref{findzero_isar} shows a slightly more\n  complicated proof written in Isar. It is verbose enough to show how\n  partiality comes into play: From the partial induction, we get an\n  additional domain condition hypothesis. Observe how this condition\n  is applied when calls to \\<^term>\\<open>findzero\\<close> are unfolded.\n\\<close>\n\ntext_raw \\<open>\n\\begin{figure}\n\\hrule\\vspace{6pt}\n\\begin{minipage}{0.8\\textwidth}\n\\isabellestyle{it}\n\\isastyle\\isamarkuptrue\n\\<close>\nlemma \"\\<lbrakk>findzero_dom (f, n); x \\<in> {n ..< findzero f n}\\<rbrakk> \\<Longrightarrow> f x \\<noteq> 0\"\nproof (induct rule: findzero.pinduct)\n  fix f n assume dom: \"findzero_dom (f, n)\"\n               and IH: \"\\<lbrakk>f n \\<noteq> 0; x \\<in> {Suc n ..< findzero f (Suc n)}\\<rbrakk> \\<Longrightarrow> f x \\<noteq> 0\"\n               and x_range: \"x \\<in> {n ..< findzero f n}\"\n  have \"f n \\<noteq> 0\"\n  proof \n    assume \"f n = 0\"\n    with dom have \"findzero f n = n\" by (simp add: findzero.psimps)\n    with x_range show False by auto\n  qed\n  \n  from x_range have \"x = n \\<or> x \\<in> {Suc n ..< findzero f n}\" by auto\n  thus \"f x \\<noteq> 0\"\n  proof\n    assume \"x = n\"\n    with \\<open>f n \\<noteq> 0\\<close> show ?thesis by simp\n  next\n    assume \"x \\<in> {Suc n ..< findzero f n}\"\n    with dom and \\<open>f n \\<noteq> 0\\<close> have \"x \\<in> {Suc n ..< findzero f (Suc n)}\" by (simp add: findzero.psimps)\n    with IH and \\<open>f n \\<noteq> 0\\<close>\n    show ?thesis by simp\n  qed\nqed\ntext_raw \\<open>\n\\isamarkupfalse\\isabellestyle{tt}\n\\end{minipage}\\vspace{6pt}\\hrule\n\\caption{A proof about a partial function}\\label{findzero_isar}\n\\end{figure}\n\\<close>\n\nsubsection \\<open>Partial termination proofs\\<close>\n\ntext \\<open>\n  Now that we have proved some interesting properties about our\n  function, we should turn to the domain predicate and see if it is\n  actually true for some values. Otherwise we would have just proved\n  lemmas with \\<^term>\\<open>False\\<close> as a premise.\n\n  Essentially, we need some introduction rules for \\<open>findzero_dom\\<close>. The function package can prove such domain\n  introduction rules automatically. But since they are not used very\n  often (they are almost never needed if the function is total), this\n  functionality is disabled by default for efficiency reasons. So we have to go\n  back and ask for them explicitly by passing the \\<open>(domintros)\\<close> option to the function package:\n\n\\vspace{1ex}\n\\noindent\\cmd{function} \\<open>(domintros) findzero :: \"(nat \\<Rightarrow> nat) \\<Rightarrow> nat \\<Rightarrow> nat\"\\<close>\\\\%\n\\cmd{where}\\isanewline%\n\\ \\ \\ldots\\\\\n\n  \\noindent Now the package has proved an introduction rule for \\<open>findzero_dom\\<close>:\n\\<close>\n\nthm findzero.domintros\n\ntext \\<open>\n  @{thm[display] findzero.domintros}\n\n  Domain introduction rules allow to show that a given value lies in the\n  domain of a function, if the arguments of all recursive calls\n  are in the domain as well. They allow to do a \\qt{single step} in a\n  termination proof. Usually, you want to combine them with a suitable\n  induction principle.\n\n  Since our function increases its argument at recursive calls, we\n  need an induction principle which works \\qt{backwards}. We will use\n  @{thm [source] inc_induct}, which allows to do induction from a fixed number\n  \\qt{downwards}:\n\n  \\begin{center}@{thm inc_induct}\\hfill(@{thm [source] \"inc_induct\"})\\end{center}\n\n  Figure \\ref{findzero_term} gives a detailed Isar proof of the fact\n  that \\<open>findzero\\<close> terminates if there is a zero which is greater\n  or equal to \\<^term>\\<open>n\\<close>. First we derive two useful rules which will\n  solve the base case and the step case of the induction. The\n  induction is then straightforward, except for the unusual induction\n  principle.\n\n\\<close>\n\ntext_raw \\<open>\n\\begin{figure}\n\\hrule\\vspace{6pt}\n\\begin{minipage}{0.8\\textwidth}\n\\isabellestyle{it}\n\\isastyle\\isamarkuptrue\n\\<close>\nlemma findzero_termination:\n  assumes \"x \\<ge> n\" and \"f x = 0\"\n  shows \"findzero_dom (f, n)\"\nproof - \n  have base: \"findzero_dom (f, x)\"\n    by (rule findzero.domintros) (simp add:\\<open>f x = 0\\<close>)\n\n  have step: \"\\<And>i. findzero_dom (f, Suc i) \n    \\<Longrightarrow> findzero_dom (f, i)\"\n    by (rule findzero.domintros) simp\n\n  from \\<open>x \\<ge> n\\<close> show ?thesis\n  proof (induct rule:inc_induct)\n    show \"findzero_dom (f, x)\" by (rule base)\n  next\n    fix i assume \"findzero_dom (f, Suc i)\"\n    thus \"findzero_dom (f, i)\" by (rule step)\n  qed\nqed      \ntext_raw \\<open>\n\\isamarkupfalse\\isabellestyle{tt}\n\\end{minipage}\\vspace{6pt}\\hrule\n\\caption{Termination proof for \\<open>findzero\\<close>}\\label{findzero_term}\n\\end{figure}\n\\<close>\n      \ntext \\<open>\n  Again, the proof given in Fig.~\\ref{findzero_term} has a lot of\n  detail in order to explain the principles. Using more automation, we\n  can also have a short proof:\n\\<close>\n\nlemma findzero_termination_short:\n  assumes zero: \"x >= n\" \n  assumes [simp]: \"f x = 0\"\n  shows \"findzero_dom (f, n)\"\nusing zero\nby (induct rule:inc_induct) (auto intro: findzero.domintros)\n    \ntext \\<open>\n  \\noindent It is simple to combine the partial correctness result with the\n  termination lemma:\n\\<close>\n\nlemma findzero_total_correctness:\n  \"f x = 0 \\<Longrightarrow> f (findzero f 0) = 0\"\nby (blast intro: findzero_zero findzero_termination)\n\nsubsection \\<open>Definition of the domain predicate\\<close>\n\ntext \\<open>\n  Sometimes it is useful to know what the definition of the domain\n  predicate looks like. Actually, \\<open>findzero_dom\\<close> is just an\n  abbreviation:\n\n  @{abbrev[display] findzero_dom}\n\n  The domain predicate is the \\emph{accessible part} of a relation \\<^const>\\<open>findzero_rel\\<close>, which was also created internally by the function\n  package. \\<^const>\\<open>findzero_rel\\<close> is just a normal\n  inductive predicate, so we can inspect its definition by\n  looking at the introduction rules @{thm [source] findzero_rel.intros}.\n  In our case there is just a single rule:\n\n  @{thm[display] findzero_rel.intros}\n\n  The predicate \\<^const>\\<open>findzero_rel\\<close>\n  describes the \\emph{recursion relation} of the function\n  definition. The recursion relation is a binary relation on\n  the arguments of the function that relates each argument to its\n  recursive calls. In general, there is one introduction rule for each\n  recursive call.\n\n  The predicate \\<^term>\\<open>Wellfounded.accp findzero_rel\\<close> is the accessible part of\n  that relation. An argument belongs to the accessible part, if it can\n  be reached in a finite number of steps (cf.~its definition in \\<open>Wellfounded.thy\\<close>).\n\n  Since the domain predicate is just an abbreviation, you can use\n  lemmas for \\<^const>\\<open>Wellfounded.accp\\<close> and \\<^const>\\<open>findzero_rel\\<close> directly. Some\n  lemmas which are occasionally useful are @{thm [source] accpI}, @{thm [source]\n  accp_downward}, and of course the introduction and elimination rules\n  for the recursion relation @{thm [source] \"findzero_rel.intros\"} and @{thm\n  [source] \"findzero_rel.cases\"}.\n\\<close>\n\nsection \\<open>Nested recursion\\<close>\n\ntext \\<open>\n  Recursive calls which are nested in one another frequently cause\n  complications, since their termination proof can depend on a partial\n  correctness property of the function itself. \n\n  As a small example, we define the \\qt{nested zero} function:\n\\<close>\n\nfunction nz :: \"nat \\<Rightarrow> nat\"\nwhere\n  \"nz 0 = 0\"\n| \"nz (Suc n) = nz (nz n)\"\nby pat_completeness auto\n\ntext \\<open>\n  If we attempt to prove termination using the identity measure on\n  naturals, this fails:\n\\<close>\n\ntermination\n  apply (relation \"measure (\\<lambda>n. n)\")\n  apply auto\n\ntext \\<open>\n  We get stuck with the subgoal\n\n  @{subgoals[display]}\n\n  Of course this statement is true, since we know that \\<^const>\\<open>nz\\<close> is\n  the zero function. And in fact we have no problem proving this\n  property by induction.\n\\<close>\n(*<*)oops(*>*)\nlemma nz_is_zero: \"nz_dom n \\<Longrightarrow> nz n = 0\"\n  by (induct rule:nz.pinduct) (auto simp: nz.psimps)\n\ntext \\<open>\n  We formulate this as a partial correctness lemma with the condition\n  \\<^term>\\<open>nz_dom n\\<close>. This allows us to prove it with the \\<open>pinduct\\<close> rule before we have proved termination. With this lemma,\n  the termination proof works as expected:\n\\<close>\n\ntermination\n  by (relation \"measure (\\<lambda>n. n)\") (auto simp: nz_is_zero)\n\ntext \\<open>\n  As a general strategy, one should prove the statements needed for\n  termination as a partial property first. Then they can be used to do\n  the termination proof. This also works for less trivial\n  examples. Figure \\ref{f91} defines the 91-function, a well-known\n  challenge problem due to John McCarthy, and proves its termination.\n\\<close>\n\ntext_raw \\<open>\n\\begin{figure}\n\\hrule\\vspace{6pt}\n\\begin{minipage}{0.8\\textwidth}\n\\isabellestyle{it}\n\\isastyle\\isamarkuptrue\n\\<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\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 assume \"\\<not> 100 < n\" \\<comment> \\<open>Assumptions for both calls\\<close>\n\n  thus \"(n + 11, n) \\<in> ?R\" by simp \\<comment> \\<open>Inner call\\<close>\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_raw \\<open>\n\\isamarkupfalse\\isabellestyle{tt}\n\\end{minipage}\n\\vspace{6pt}\\hrule\n\\caption{McCarthy's 91-function}\\label{f91}\n\\end{figure}\n\\<close>\n\n\nsection \\<open>Higher-Order Recursion\\<close>\n\ntext \\<open>\n  Higher-order recursion occurs when recursive calls\n  are passed as arguments to higher-order combinators such as \\<^const>\\<open>map\\<close>, \\<^term>\\<open>filter\\<close> etc.\n  As an example, imagine a datatype of n-ary trees:\n\\<close>\n\ndatatype 'a tree = \n  Leaf 'a \n| Branch \"'a tree list\"\n\n\ntext \\<open>\\noindent We can define a function which swaps the left and right subtrees recursively, using the \n  list functions \\<^const>\\<open>rev\\<close> and \\<^const>\\<open>map\\<close>:\\<close>\n\nfun mirror :: \"'a tree \\<Rightarrow> 'a tree\"\nwhere\n  \"mirror (Leaf n) = Leaf n\"\n| \"mirror (Branch l) = Branch (rev (map mirror l))\"\n\ntext \\<open>\n  Although the definition is accepted without problems, let us look at the termination proof:\n\\<close>\n\ntermination proof\n  text \\<open>\n\n  As usual, we have to give a wellfounded relation, such that the\n  arguments of the recursive calls get smaller. But what exactly are\n  the arguments of the recursive calls when mirror is given as an\n  argument to \\<^const>\\<open>map\\<close>? Isabelle gives us the\n  subgoals\n\n  @{subgoals[display,indent=0]} \n\n  So the system seems to know that \\<^const>\\<open>map\\<close> only\n  applies the recursive call \\<^term>\\<open>mirror\\<close> to elements\n  of \\<^term>\\<open>l\\<close>, which is essential for the termination proof.\n\n  This knowledge about \\<^const>\\<open>map\\<close> is encoded in so-called congruence rules,\n  which are special theorems known to the \\cmd{function} command. The\n  rule for \\<^const>\\<open>map\\<close> is\n\n  @{thm[display] map_cong}\n\n  You can read this in the following way: Two applications of \\<^const>\\<open>map\\<close> are equal, if the list arguments are equal and the functions\n  coincide on the elements of the list. This means that for the value \n  \\<^term>\\<open>map f l\\<close> we only have to know how \\<^term>\\<open>f\\<close> behaves on\n  the elements of \\<^term>\\<open>l\\<close>.\n\n  Usually, one such congruence rule is\n  needed for each higher-order construct that is used when defining\n  new functions. In fact, even basic functions like \\<^const>\\<open>If\\<close> and \\<^const>\\<open>Let\\<close> are handled by this mechanism. The congruence\n  rule for \\<^const>\\<open>If\\<close> states that the \\<open>then\\<close> branch is only\n  relevant if the condition is true, and the \\<open>else\\<close> branch only if it\n  is false:\n\n  @{thm[display] if_cong}\n  \n  Congruence rules can be added to the\n  function package by giving them the \\<^term>\\<open>fundef_cong\\<close> attribute.\n\n  The constructs that are predefined in Isabelle, usually\n  come with the respective congruence rules.\n  But if you define your own higher-order functions, you may have to\n  state and prove the required congruence rules yourself, if you want to use your\n  functions in recursive definitions. \n\\<close>\n(*<*)oops(*>*)\n\nsubsection \\<open>Congruence Rules and Evaluation Order\\<close>\n\ntext \\<open>\n  Higher order logic differs from functional programming languages in\n  that it has no built-in notion of evaluation order. A program is\n  just a set of equations, and it is not specified how they must be\n  evaluated. \n\n  However for the purpose of function definition, we must talk about\n  evaluation order implicitly, when we reason about termination.\n  Congruence rules express that a certain evaluation order is\n  consistent with the logical definition. \n\n  Consider the following function.\n\\<close>\n\nfunction f :: \"nat \\<Rightarrow> bool\"\nwhere\n  \"f n = (n = 0 \\<or> f (n - 1))\"\n(*<*)by pat_completeness auto(*>*)\n\ntext \\<open>\n  For this definition, the termination proof fails. The default configuration\n  specifies no congruence rule for disjunction. We have to add a\n  congruence rule that specifies left-to-right evaluation order:\n\n  \\vspace{1ex}\n  \\noindent @{thm disj_cong}\\hfill(@{thm [source] \"disj_cong\"})\n  \\vspace{1ex}\n\n  Now the definition works without problems. Note how the termination\n  proof depends on the extra condition that we get from the congruence\n  rule.\n\n  However, as evaluation is not a hard-wired concept, we\n  could just turn everything around by declaring a different\n  congruence rule. Then we can make the reverse definition:\n\\<close>\n\nlemma disj_cong2[fundef_cong]: \n  \"(\\<not> Q' \\<Longrightarrow> P = P') \\<Longrightarrow> (Q = Q') \\<Longrightarrow> (P \\<or> Q) = (P' \\<or> Q')\"\n  by blast\n\nfun f' :: \"nat \\<Rightarrow> bool\"\nwhere\n  \"f' n = (f' (n - 1) \\<or> n = 0)\"\n\ntext \\<open>\n  \\noindent These examples show that, in general, there is no \\qt{best} set of\n  congruence rules.\n\n  However, such tweaking should rarely be necessary in\n  practice, as most of the time, the default set of congruence rules\n  works well.\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/Doc/Functions/Functions.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8289388125473628, "lm_q2_score": 0.8774767922879693, "lm_q1q2_score": 0.7273745702370582}}
{"text": "(* File: boolexp.thy *)\n\ntheory boolexp\nimports Main\nbegin\n\nsection{* Basic Type and Evaluation Function\n         for Boolean Expressions *}\n\ntext{*\n The following type mirrors the BNF grammar\nwe gave in for boolean expressions.  We will use\nonly prefixed connectives here\n*}\n\ndatatype 'a boolexp =\n   TRUE | FALSE |Var 'a | Not \"'a boolexp\"\n  | And \"'a boolexp\" \"'a boolexp\"\n  | Or \"'a boolexp\" \"'a boolexp\"\n  | Implies \"'a boolexp\" \"'a boolexp\"\n\ntext{*\nThe following is a recursive definition of the function for evaluating\nboolean expressions. It is the same as the definition\nof \\textit{models} given in class. \n*}\n\nfun boolexp_eval \nwhere\n   \"boolexp_eval env TRUE = True\"\n | \"boolexp_eval env FALSE = False\"\n | \"boolexp_eval env (Var x) = env x\"\n | \"boolexp_eval env (Not b) = (\\<not> (boolexp_eval env b))\"\n | \"boolexp_eval env (And a b) =\n    ((boolexp_eval env a) \\<and> (boolexp_eval env b))\"\n | \"boolexp_eval env (Or a b) =\n    ((boolexp_eval env a) \\<or> (boolexp_eval env b))\"\n | \"boolexp_eval env (Implies a b) =\n    ((\\<not> (boolexp_eval env a))\\<or> (boolexp_eval env b))\"\n\ntext{*\nBecause all our definition have been purely\ncomputational, we may use \\tettt{value} to evaluate\nexpressions using the type \\texttt{boolexp} and the term\nboolexp_eval.\n*}\n\n(*\nvalue \"boolexp_eval\n(\\<lambda> x. case x of ''a'' \\<Rightarrow> True | _ \\<Rightarrow> False)\n (Implies (Var ''b'') (Var ''a''))\"\n*)\n\n\nvalue \"boolexp_eval\n(\\<lambda> x. case x of (0::nat) \\<Rightarrow> True | _ \\<Rightarrow> False)\n (Implies (Var (1::nat)) (Var (0::nat)))\"\n\n\ntext{*\nOur objective is to build a function that will tell\nus all the ways a boolean expression can be satisfied.\nOur approach is to put the boolean expression in\ndisjunctive normal form.\nWe start by eliminating implies.\n*}\n\nfun remove_implies where\n   \"remove_implies TRUE = TRUE\"\n | \"remove_implies FALSE = FALSE\"\n | \"remove_implies (Var x) = Var x\"\n | \"remove_implies (Not a) = Not (remove_implies a)\"\n | \"remove_implies (And a b) =\n    And (remove_implies a) (remove_implies b)\"\n | \"remove_implies (Or a b) =\n    Or (remove_implies a) (remove_implies b)\"\n | \"remove_implies (Implies a b) =\n    (Or (Not (remove_implies a)) (remove_implies b))\"\n\nthm boolexp.induct\n\nlemma remove_implies_same_eval [simp]:\n\"boolexp_eval env (remove_implies a) =\n boolexp_eval env a\"\napply (induct \"a\")\nby simp_all\n(*\nby (induct \"a\", auto)\n*)\n\nfun number_of_implies where\n   \"number_of_implies TRUE = (0::nat)\"\n | \"number_of_implies FALSE = 0\"\n | \"number_of_implies (Var x) = 0\"\n | \"number_of_implies (Not a) = number_of_implies a\"\n | \"number_of_implies (And a b) =\n   (number_of_implies a) + (number_of_implies b)\"\n | \"number_of_implies (Or a b) =\n   (number_of_implies a) + (number_of_implies b)\"\n | \"number_of_implies (Implies a b) =\n   (number_of_implies a) + (number_of_implies b) + 1\" \n\nlemma number_of_implies_remove_implies_0 [simp]:\n\"number_of_implies (remove_implies a) = 0\"\nby (induct \"a\", auto)\n\n\nfun push_not where   \n   \"push_not TRUE = TRUE\"\n | \"push_not FALSE = FALSE\"\n | \"push_not (Var x) = Var x\"          \n | \"push_not (Not TRUE) = FALSE\"\n | \"push_not (Not FALSE) = TRUE\"\n | \"push_not (Not (Var x)) = Not (Var x)\"\n | \"push_not (Not (Not a)) = push_not a\"\n | \"push_not (Not (And a b)) =\n    (Or (push_not (Not a)) (push_not (Not b)))\"\n | \"push_not (Not (Or a b)) =\n    (And (push_not (Not a)) (push_not (Not b)))\"\n | \"push_not (Not (Implies a b)) =\n   (And (push_not a) (push_not (Not b)))\"\n | \"push_not (And a b) =\n   (And (push_not a) (push_not b))\"      \n | \"push_not (Or a b) =\n   (Or (push_not a) (push_not b))\"      \n | \"push_not (Implies a b) =\n    (Implies (push_not a) (push_not b))\"\n\nlemma push_not_same_eval [simp]:\n \"(boolexp_eval env (push_not (Not a))\n   = (\\<not> (boolexp_eval env (push_not a)))) \\<and>\n  (boolexp_eval env (push_not a) = boolexp_eval env a)\"\nby (induct \"a\", auto)\n\nlemma push_not_preserves_no_implies_helper:\n\"number_of_implies a = 0 \\<Longrightarrow>\n (number_of_implies (push_not a) = 0) \\<and>\n (number_of_implies (push_not (Not a)) = 0)\"\nby (induct \"a\", auto)\n\nlemma push_not_preserves_no_implies:\n\"number_of_implies a = 0 \\<Longrightarrow>\n (number_of_implies (push_not a) = 0)\"\nby (auto simp add: push_not_preserves_no_implies_helper)\n\nlemma push_not_remove_implies_no_implies [simp]:\n\"number_of_implies (push_not (remove_implies a)) = 0\"\napply (rule push_not_preserves_no_implies)\napply (rule number_of_implies_remove_implies_0)\ndone\n\n\nexport_code boolexp_eval push_not remove_implies\nin OCaml\n module_name Boolexp file \"boolexp.ml\"\n\n\ndatatype 'a boolexp_no_imp =\n      TRUE_ni | FALSE_ni |Var_ni 'a\n    | Not_ni \"'a boolexp_no_imp\"\n    | And_ni \"'a boolexp_no_imp\" \"'a boolexp_no_imp\"\n    | Or_ni \"'a boolexp_no_imp\" \"'a boolexp_no_imp\"\n\nfun boolexp_no_imp_eval where\n   \"boolexp_no_imp_eval env TRUE_ni = True\"\n | \"boolexp_no_imp_eval env FALSE_ni = False\"\n | \"boolexp_no_imp_eval env (Var_ni x) = env x\"\n | \"boolexp_no_imp_eval env (Not_ni a) =\n    (\\<not> (boolexp_no_imp_eval env a))\"\n | \"boolexp_no_imp_eval env (And_ni a b) =\n    ((boolexp_no_imp_eval env a) \\<and>\n     (boolexp_no_imp_eval env b))\"\n | \"boolexp_no_imp_eval env (Or_ni a b) =\n    ((boolexp_no_imp_eval env a) \\<or>\n     (boolexp_no_imp_eval env b))\"\n\n\nfun remove_implies_ni where\n   \"remove_implies_ni TRUE = TRUE_ni\"\n | \"remove_implies_ni FALSE = FALSE_ni\"\n | \"remove_implies_ni (Var x) = Var_ni x\"\n | \"remove_implies_ni (Not a) =\n    Not_ni (remove_implies_ni a)\"\n | \"remove_implies_ni (And a b) =\n    And_ni (remove_implies_ni a) (remove_implies_ni b)\"\n | \"remove_implies_ni (Or a b) =\n    Or_ni (remove_implies_ni a) (remove_implies_ni b)\"\n | \"remove_implies_ni (Implies a b) =\n    (Or_ni (Not_ni (remove_implies_ni a))\n           (remove_implies_ni b))\"\n\nlemma remove_implies_ni_same_eval:\n  \"boolexp_no_imp_eval env (remove_implies_ni a) =\n   boolexp_eval env (remove_implies a)\"\nby (induct_tac a, auto)\n\ndatatype 'a boolexp_nipn =\n    TRUE_nipn | FALSE_nipn |Var_nipn 'a\n    | Not_Var_nipn 'a\n    | And_nipn \"'a boolexp_nipn\" \"'a boolexp_nipn\"\n    | Or_nipn \"'a boolexp_nipn\" \"'a boolexp_nipn\"\n\nfun push_not_pn where\n   \"push_not_pn TRUE_ni = TRUE_nipn\"\n | \"push_not_pn FALSE_ni = FALSE_nipn\"\n | \"push_not_pn (Var_ni x) = Var_nipn x\"      \n | \"push_not_pn (Not_ni TRUE_ni) = FALSE_nipn\"\n | \"push_not_pn (Not_ni FALSE_ni) = TRUE_nipn\"\n | \"push_not_pn (Not_ni (Var_ni x)) = Not_Var_nipn x\"\n | \"push_not_pn (Not_ni (Not_ni a)) = push_not_pn a\"\n | \"push_not_pn (Not_ni (And_ni a b)) =\n    (Or_nipn (push_not_pn (Not_ni a))\n             (push_not_pn (Not_ni b)))\"\n | \"push_not_pn (Not_ni (Or_ni a b)) =\n    (And_nipn (push_not_pn (Not_ni a))\n              (push_not_pn (Not_ni b)))\"\n | \"push_not_pn (And_ni a b) = \n   (And_nipn (push_not_pn a) (push_not_pn b))\"    \n | \"push_not_pn (Or_ni a b) =\n   (Or_nipn (push_not_pn a) (push_not_pn b))\"\n\nfun boolexp_nipn_eval where\n   \"boolexp_nipn_eval env TRUE_nipn = True\"\n | \"boolexp_nipn_eval env FALSE_nipn = False\"\n | \"boolexp_nipn_eval env (Var_nipn x) = env x\"\n | \"boolexp_nipn_eval env (Not_Var_nipn a) =\n    (\\<not> (env a))\"\n | \"boolexp_nipn_eval env (And_nipn a b) =\n    ((boolexp_nipn_eval env a) \\<and>\n     (boolexp_nipn_eval env b))\"\n | \"boolexp_nipn_eval env (Or_nipn a b) =\n    ((boolexp_nipn_eval env a) \\<or>\n     (boolexp_nipn_eval env b))\"\n\nlemma push_not_pn_same_eval [simp]:\n\"(boolexp_nipn_eval env (push_not_pn (Not_ni b)) =\n  (\\<not> (boolexp_no_imp_eval env b))) \\<and>\n (boolexp_nipn_eval env (push_not_pn b) =\n  boolexp_no_imp_eval env b)\"\nby (induct_tac b, auto)\n\nfun node_count where     \n   \"node_count TRUE = (1::nat)\"\n | \"node_count FALSE = 1\"\n | \"node_count (Var x) = 1\"\n | \"node_count (Not x) = 1 + node_count x\"\n | \"node_count (And a b) =\n    1 + (node_count a) + (node_count b)\"\n | \"node_count (Or a b) =\n    1 + (node_count a) + (node_count b)\"\n | \"node_count (Implies a b) =\n    1 + (node_count a) + (node_count b)\" \n \nlemma node_count_non_zero [simp]:\n\"0 < node_count b\"\nby (induct_tac b, auto)\n\nfunction push_not_elim_imp where   \n   \"push_not_elim_imp TRUE = TRUE_nipn\"\n | \"push_not_elim_imp FALSE = FALSE_nipn\"\n | \"push_not_elim_imp (Var x) = Var_nipn x\"          \n | \"push_not_elim_imp (Not TRUE) = FALSE_nipn\"\n | \"push_not_elim_imp (Not FALSE) = TRUE_nipn\"\n | \"push_not_elim_imp (Not (Var x)) = Not_Var_nipn x\"\n | \"push_not_elim_imp (Not (Not b)) =\n    push_not_elim_imp b\"\n | \"push_not_elim_imp (Not (And a b)) =\n    (Or_nipn (push_not_elim_imp (Not a))\n             (push_not_elim_imp (Not b)))\"\n | \"push_not_elim_imp (Not (Or a b)) =\n    (And_nipn (push_not_elim_imp (Not a))\n              (push_not_elim_imp (Not b)))\"\n | \"push_not_elim_imp (Not (Implies a b)) =\n   (And_nipn (push_not_elim_imp a)\n             (push_not_elim_imp (Not b)))\"\n | \"push_not_elim_imp (And a b) =\n   (And_nipn (push_not_elim_imp a)\n             (push_not_elim_imp b))\"      \n | \"push_not_elim_imp (Or a b) =\n   (Or_nipn (push_not_elim_imp a)\n            (push_not_elim_imp b))\"      \n | \"push_not_elim_imp (Implies a b) =\n    (Or_nipn (push_not_elim_imp (Not a))\n             (push_not_elim_imp b))\"                   \nby (pat_completeness, auto)\nterm \"op <*mlex*>\"\ntermination\nby (relation \"measures [node_count]\", auto)\n\nlemma push_not_elim_imp_push_not_pn_remove_implies_ni [simp]:\n\"(push_not_elim_imp (boolexp.Not a) =\n  push_not_pn (Not_ni (remove_implies_ni a))) \\<and>\n (push_not_elim_imp a =\n  push_not_pn (remove_implies_ni a))\"\nby (induct_tac a, auto)\n\nlemma push_not_elim_imp_same_eval [simp]:\n\"(boolexp_nipn_eval env (push_not_elim_imp (Not a)) =\n  (\\<not>(boolexp_eval env a))) \\<and>\n (boolexp_nipn_eval env (push_not_elim_imp a) =\n  boolexp_eval env a)\"\nby (induct_tac a, auto)\n\ndatatype 'a bool_atom =\n   TRUE_at | FALSE_at |Var_at 'a | Not_Var_at 'a\n   \nfun bool_atom_eval where\n   \"bool_atom_eval env TRUE_at = True\"\n | \"bool_atom_eval env FALSE_at = False\"\n | \"bool_atom_eval env (Var_at x) = env x\"\n | \"bool_atom_eval env (Not_Var_at x) = (\\<not>(env x))\"\n \ndatatype 'a bool_conj =\n   Atom \"'a bool_atom\"\n | And_conj \"'a bool_atom\" \"'a bool_conj\"\n\nfun bool_conj_eval where\n   \"bool_conj_eval env (Atom a) = bool_atom_eval env a\"\n | \"bool_conj_eval env (And_conj a b) =\n    ((bool_atom_eval env a) \\<and>\n     (bool_conj_eval env b))\"\n     \nfun conj_and where\n   \"conj_and (Atom a) b = And_conj a b\"\n | \"conj_and (And_conj a b) c =\n    And_conj a (conj_and b c)\"\n    \nlemma conj_and_eval [simp]:\n\"bool_conj_eval env (conj_and a b) =\n ((bool_conj_eval env a) \\<and> (bool_conj_eval env b))\"\nby (induct_tac a, auto)\n\ndatatype 'a bool_dnf =\n   Conj \"'a bool_conj\"\n | Or_dnf \"'a bool_conj\" \"'a bool_dnf\"\n\nfun bool_dnf_eval where\n   \"bool_dnf_eval env (Conj c) = bool_conj_eval env c\"\n | \"bool_dnf_eval env (Or_dnf a b) =\n    ((bool_conj_eval env a) \\<or> (bool_dnf_eval env b))\"\n\nfun dnf_or where\n   \"dnf_or (Conj a) b = Or_dnf a b\"\n | \"dnf_or (Or_dnf a b) c = Or_dnf a (dnf_or b c)\"\n \nlemma dnf_or_eval [simp]:\n\"bool_dnf_eval env (dnf_or a b) =\n  ((bool_dnf_eval env a) \\<or> (bool_dnf_eval env b))\"\nby (induct_tac \"a\", auto)\n\nfun conj_or where\n   \"conj_or a (Conj b) = Conj (conj_and a b)\"\n | \"conj_or a (Or_dnf b c) =\n    Or_dnf(conj_and a b) (conj_or a c)\"\n\nlemma conj_or_eval [simp]:\n\"bool_dnf_eval env (conj_or a b) =\n  ((bool_conj_eval env a) \\<and> (bool_dnf_eval env b))\"\nby (induct_tac \"b\", auto)\n\nfun dist_and_or where\n   \"dist_and_or (Conj a) b = conj_or a b\"\n | \"dist_and_or (Or_dnf a b) c =\n    dnf_or (conj_or a c) (dist_and_or b c)\"\n\nlemma dist_and_or_and_eval [simp]:\n\"bool_dnf_eval env (dist_and_or a b) =\n ((bool_dnf_eval env a) \\<and> (bool_dnf_eval env b))\"\nby (induct_tac a, auto)\n\nfun basic_dnf where\n   \"basic_dnf TRUE_nipn = Conj(Atom TRUE_at)\"\n | \"basic_dnf FALSE_nipn = Conj(Atom FALSE_at)\"\n | \"basic_dnf (Var_nipn x) = Conj(Atom (Var_at x))\"\n | \"basic_dnf (Not_Var_nipn x) =\n    Conj(Atom (Not_Var_at x))\"\n | \"basic_dnf (And_nipn a b) =\n    dist_and_or (basic_dnf a) (basic_dnf b)\"\n | \"basic_dnf (Or_nipn a b) =\n    dnf_or (basic_dnf a) (basic_dnf b)\"\n    \nlemma basic_dnv_eval [simp]:\n\"bool_dnf_eval env (basic_dnf a) =\n boolexp_nipn_eval env a\"\nby (induct_tac a, auto)\n\ndefinition dnf where\n\"dnf a = basic_dnf (push_not_elim_imp a)\"\n\nlemma dnf_eval [simp]:\n\"boolexp_eval env a = bool_dnf_eval env (dnf a)\"\nby (auto simp only: dnf_def push_not_elim_imp_same_eval basic_dnv_eval)\n\nfun sat_bool_atom where\n   \"sat_bool_atom TRUE_at = Some (None)\"\n | \"sat_bool_atom FALSE_at = None\"\n | \"sat_bool_atom (Var_at x) = Some(Some(x,True))\"\n | \"sat_bool_atom (Not_Var_at x) = Some(Some(x,False))\"\n\nlemma sat_bool_atom_no_sat [simp]:\n\"sat_bool_atom a = None \\<Longrightarrow> \\<not>(bool_atom_eval env a)\"\nby (case_tac \"a\", simp_all)\n\nlemma sat_bool_atom_sound [simp]:\n\"\\<lbrakk> sat_bool_atom a = Some l;\n   (l = None) \\<or> l = Some (y, env y) \\<rbrakk> \\<Longrightarrow>\n bool_atom_eval env a\"\nby (induct a, auto)\n\nlemma sat_bool_atom_complete [simp]:\n\"bool_atom_eval env a \\<Longrightarrow>\n\\<exists> l y. ((sat_bool_atom a = Some l) \\<and> \n     ((l = None) \\<or> l = Some(y, env y)))\"\napply (case_tac \"sat_bool_atom a\", auto)\nby (induct a, auto)\n\nfun member where\n   \"member x [] = False\"\n | \"member x (y#ys) = ((x = y) \\<or> (member x ys))\"\n \nfun sat_conj where\n   \"sat_conj (Atom a) = \n    (case sat_bool_atom a of None \\<Rightarrow> None\n        | Some None \\<Rightarrow> Some []\n        | Some (Some (y,t)) \\<Rightarrow> Some[(y,t)])\"\n | \"sat_conj (And_conj a b) =\n    (case sat_bool_atom a of None \\<Rightarrow> None\n        | Some None \\<Rightarrow> sat_conj b\n        | Some (Some (y,t)) \\<Rightarrow>\n         (case sat_conj b of None \\<Rightarrow> None\n             | Some l \\<Rightarrow>\n               (if member (y,\\<not>t) l then None\n                else if member (y,t) l then Some l\n                else Some ((y,t)#l))))\"\n\nfun sat_to_env where\n   \"sat_to_env [] = {env. True}\"\n | \"sat_to_env ((y,b)#l) = {env. env y = b} \\<inter> (sat_to_env l)\"\n\n(*\nlemma sat_conj_sound:\n\"\\<lbrakk> sat_conj a = Some l; env \\<in> sat_to_env l \\<rbrakk> \\<Longrightarrow> bool_conj_eval env a\"\napply (induct \"a\", simp_all)  \napply (case_tac \"bool_atom\", simp_all)\napply auto\n*)\n\nfun sat_dnf where\n    \"sat_dnf (Conj a) =\n     (case sat_conj a of None \\<Rightarrow> []\n         | Some l \\<Rightarrow> [l])\"\n | \"sat_dnf (Or_dnf a b) =\n    (case sat_conj a of None \\<Rightarrow> sat_dnf b\n        | Some l => l# (sat_dnf b))\"\n\n        \ndefinition sat where\n\"sat a \\<equiv> sat_dnf (dnf a)\"\n\nexport_code sat\nin OCaml\n module_name Sat file \"sat.ml\"\n\n\nend\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/other/boolexp.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767938900121, "lm_q2_score": 0.8289388083214156, "lm_q1q2_score": 0.727374567856883}}
{"text": "section \\<open>Propositional Formulas and CNFs\\<close>\n\ntext \\<open>We provide a straight-forward definition of propositional formulas, defined as arbitray formulas\n  using variables, negations, conjunctions and disjunctions. CNFs are represented as lists of lists of \n  literals and then converted into formulas.\\<close>\n\ntheory Propositional_Formula\n  imports Main\nbegin\n\nsubsection \\<open>Propositional Formulas\\<close>\n\ndatatype 'a formula = \n  Prop 'a | \n  Conj \"'a formula list\" | \n  Disj \"'a formula list\" | \n  Neg \"'a formula\" |\n  Impl \"'a formula\" \"'a formula\" |\n  Equiv \"'a formula\" \"'a formula\" \n\nfun eval :: \"('a \\<Rightarrow> bool) \\<Rightarrow> 'a formula \\<Rightarrow> bool\" where\n  \"eval v (Prop x) = v x\" \n| \"eval v (Neg f) = (\\<not> eval v f)\" \n| \"eval v (Conj fs) = (\\<forall> f \\<in> set fs. eval v f)\"  \n| \"eval v (Disj fs) = (\\<exists> f \\<in> set fs. eval v f)\"  \n| \"eval v (Impl f g) = (eval v f \\<longrightarrow> eval v g)\"  \n| \"eval v (Equiv f g) = (eval v f \\<longleftrightarrow> eval v g)\"  \n\ntext \\<open>Definition of propositional formula size: number of connectives\\<close>\n\nfun size_pf :: \"'a formula \\<Rightarrow> nat\" where\n  \"size_pf (Prop x) = 1\" \n| \"size_pf (Neg f) = 1 + size_pf f\" \n| \"size_pf (Conj fs) = 1 + sum_list (map size_pf fs)\"  \n| \"size_pf (Disj fs) = 1 + sum_list (map size_pf fs)\"  \n| \"size_pf (Impl f g) = 1 + size_pf f + size_pf g\"  \n| \"size_pf (Equiv f g) = 1 + size_pf f + size_pf g\"  \n\nsubsection \\<open>Conjunctive Normal Forms\\<close>\n\ntype_synonym 'a clause = \"('a \\<times> bool) list\" \ntype_synonym 'a cnf = \"'a clause list\" \n\nfun formula_of_lit :: \"'a \\<times> bool \\<Rightarrow> 'a formula\" where\n  \"formula_of_lit (x,True) = Prop x\" \n| \"formula_of_lit (x,False) = Neg (Prop x)\" \n\ndefinition formula_of_cnf :: \"'a cnf \\<Rightarrow> 'a formula\" where\n  \"formula_of_cnf = (Conj o map (Disj o map formula_of_lit))\" \n\ndefinition eval_cnf :: \"('a \\<Rightarrow> bool) \\<Rightarrow> 'a cnf \\<Rightarrow> bool\" where\n  \"eval_cnf \\<alpha> cnf = eval \\<alpha> (formula_of_cnf cnf)\" \n\nlemma eval_cnf_alt_def: \"eval_cnf \\<alpha> cnf = Ball (set cnf) (\\<lambda> c. Bex (set c) (\\<lambda> l. \\<alpha> (fst l) = snd l))\" \n  unfolding eval_cnf_def formula_of_cnf_def o_def eval.simps set_map Ball_image_comp bex_simps\n  apply (intro ball_cong bex_cong refl)\n  subgoal for c l by (cases l; cases \"snd l\", auto) \n  done\n\n\ntext \\<open>The size of a CNF is the number of literals + the number of clauses, i.e., \n  the sum of the lengths of all clauses + the length.\\<close>\n\ndefinition size_cnf :: \"'a cnf \\<Rightarrow> nat\" where\n  \"size_cnf cnf = sum_list (map length cnf) + length cnf\"\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/Multiset_Ordering_NPC/Propositional_Formula.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767874818408, "lm_q2_score": 0.8289388104343892, "lm_q1q2_score": 0.7273745643989864}}
{"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 \"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": "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/Knaster_Tarski.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8354835493924954, "lm_q2_score": 0.8705972717658209, "lm_q1q2_score": 0.727369698706331}}
{"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=>i\"  where\n    \"Memrel(A)   == {z\\<in>A*A . \\<exists>x y. z=<x,y> & x\\<in>y }\"\n\ndefinition\n  Transset  :: \"i=>o\"  where\n    \"Transset(i) == \\<forall>x\\<in>i. x<=i\"\n\ndefinition\n  Ord  :: \"i=>o\"  where\n    \"Ord(i)      == Transset(i) & (\\<forall>x\\<in>i. Transset(x))\"\n\ndefinition\n  lt        :: \"[i,i] => o\"  (infixl \\<open><\\<close> 50)   (*less-than on ordinals*)  where\n    \"i<j         == i\\<in>j & Ord(j)\"\n\ndefinition\n  Limit         :: \"i=>o\"  where\n    \"Limit(i)    == Ord(i) & 0<i & (\\<forall>y. y<i \\<longrightarrow> succ(y)<i)\"\n\nabbreviation\n  le  (infixl \\<open>\\<le>\\<close> 50) where\n  \"x \\<le> y == 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\"\napply (unfold 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    \"[| Transset(C); {a,b}: C |] ==> a\\<in>C & b\\<in>C\"\nby (unfold Transset_def, blast)\n\nlemma Transset_Pair_D:\n    \"[| Transset(C); <a,b>\\<in>C |] ==> a\\<in>C & b\\<in>C\"\napply (simp add: Pair_def)\napply (blast dest: Transset_doubleton_D)\ndone\n\nlemma Transset_includes_domain:\n    \"[| Transset(C); A*B \\<subseteq> C; b \\<in> B |] ==> A \\<subseteq> C\"\nby (blast dest: Transset_Pair_D)\n\nlemma Transset_includes_range:\n    \"[| Transset(C); A*B \\<subseteq> C; a \\<in> A |] ==> 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    \"[| Transset(i);  Transset(j) |] ==> Transset(i \\<union> j)\"\nby (unfold Transset_def, blast)\n\nlemma Transset_Int:\n    \"[| Transset(i);  Transset(j) |] ==> Transset(i \\<inter> j)\"\nby (unfold Transset_def, blast)\n\nlemma Transset_succ: \"Transset(i) ==> Transset(succ(i))\"\nby (unfold Transset_def, blast)\n\nlemma Transset_Pow: \"Transset(i) ==> Transset(Pow(i))\"\nby (unfold Transset_def, blast)\n\nlemma Transset_Union: \"Transset(A) ==> Transset(\\<Union>(A))\"\nby (unfold Transset_def, blast)\n\nlemma Transset_Union_family:\n    \"[| !!i. i\\<in>A ==> Transset(i) |] ==> Transset(\\<Union>(A))\"\nby (unfold Transset_def, blast)\n\nlemma Transset_Inter_family:\n    \"[| !!i. i\\<in>A ==> Transset(i) |] ==> Transset(\\<Inter>(A))\"\nby (unfold Inter_def Transset_def, blast)\n\nlemma Transset_UN:\n     \"(!!x. x \\<in> A ==> Transset(B(x))) ==> Transset (\\<Union>x\\<in>A. B(x))\"\nby (rule Transset_Union_family, auto)\n\nlemma Transset_INT:\n     \"(!!x. x \\<in> A ==> Transset(B(x))) ==> 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    \"[| Transset(i);  !!x. x\\<in>i ==> Transset(x) |]  ==>  Ord(i)\"\nby (simp add: Ord_def)\n\nlemma Ord_is_Transset: \"Ord(i) ==> Transset(i)\"\nby (simp add: Ord_def)\n\nlemma Ord_contains_Transset:\n    \"[| Ord(i);  j\\<in>i |] ==> Transset(j) \"\nby (unfold Ord_def, blast)\n\n\nlemma Ord_in_Ord: \"[| Ord(i);  j\\<in>i |] ==> Ord(j)\"\nby (unfold Ord_def Transset_def, blast)\n\n(*suitable for rewriting PROVIDED i has been fixed*)\nlemma Ord_in_Ord': \"[| j\\<in>i; Ord(i) |] ==> Ord(j)\"\nby (blast intro: Ord_in_Ord)\n\n(* Ord(succ(j)) ==> Ord(j) *)\nlemmas Ord_succD = Ord_in_Ord [OF _ succI1]\n\nlemma Ord_subset_Ord: \"[| Ord(i);  Transset(j);  j<=i |] ==> Ord(j)\"\nby (simp add: Ord_def Transset_def, blast)\n\nlemma OrdmemD: \"[| j\\<in>i;  Ord(i) |] ==> j<=i\"\nby (unfold Ord_def Transset_def, blast)\n\nlemma Ord_trans: \"[| i\\<in>j;  j\\<in>k;  Ord(k) |] ==> i\\<in>k\"\nby (blast dest: OrdmemD)\n\nlemma Ord_succ_subsetI: \"[| i\\<in>j;  Ord(j) |] ==> 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) ==> 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]: \"[| Ord(i); Ord(j) |] ==> Ord(i \\<union> j)\"\napply (unfold Ord_def)\napply (blast intro!: Transset_Un)\ndone\n\nlemma Ord_Int [TC]: \"[| Ord(i); Ord(j) |] ==> Ord(i \\<inter> j)\"\napply (unfold 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: \"~ (\\<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: \"[| i\\<in>j;  Ord(j) |] ==> i<j\"\nby (unfold lt_def, blast)\n\nlemma ltE:\n    \"[| i<j;  [| i\\<in>j;  Ord(i);  Ord(j) |] ==> P |] ==> P\"\napply (unfold lt_def)\napply (blast intro: Ord_in_Ord)\ndone\n\nlemma ltD: \"i<j ==> i\\<in>j\"\nby (erule ltE, assumption)\n\nlemma not_lt0 [simp]: \"~ i<0\"\nby (unfold lt_def, blast)\n\nlemma lt_Ord: \"j<i ==> Ord(j)\"\nby (erule ltE, assumption)\n\nlemma lt_Ord2: \"j<i ==> Ord(i)\"\nby (erule ltE, assumption)\n\n(* @{term\"ja \\<le> j ==> Ord(j)\"} *)\nlemmas le_Ord2 = lt_Ord2 [THEN Ord_succD]\n\n(* i<0 ==> R *)\nlemmas lt0E = not_lt0 [THEN notE, elim!]\n\nlemma lt_trans [trans]: \"[| i<j;  j<k |] ==> i<k\"\nby (blast intro!: ltI elim!: ltE intro: Ord_trans)\n\nlemma lt_not_sym: \"i<j ==> ~ (j<i)\"\napply (unfold lt_def)\napply (blast elim: mem_asym)\ndone\n\n(* [| i<j;  ~P ==> j<i |] ==> P *)\nlemmas lt_asym = lt_not_sym [THEN swap]\n\nlemma lt_irrefl [elim!]: \"i<i ==> P\"\nby (blast intro: lt_asym)\n\nlemma lt_not_refl: \"~ 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 & Ord(j))\"\nby (unfold lt_def, blast)\n\n(*Equivalently, i<j ==> i < succ(j)*)\nlemma leI: \"i<j ==> i \\<le> j\"\nby (simp add: le_iff)\n\nlemma le_eqI: \"[| i=j;  Ord(j) |] ==> 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: \"(~ (i=j & Ord(j)) ==> i<j) ==> i \\<le> j\"\nby (simp add: le_iff, blast)\n\nlemma leE:\n    \"[| i \\<le> j;  i<j ==> P;  [| i=j;  Ord(j) |] ==> P |] ==> P\"\nby (simp add: le_iff, blast)\n\nlemma le_anti_sym: \"[| i \\<le> j;  j \\<le> i |] ==> 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]: \"<a,b> \\<in> Memrel(A) <-> a\\<in>b & a\\<in>A & b\\<in>A\"\nby (unfold Memrel_def, blast)\n\nlemma MemrelI [intro!]: \"[| a \\<in> b;  a \\<in> A;  b \\<in> A |] ==> <a,b> \\<in> Memrel(A)\"\nby auto\n\nlemma MemrelE [elim!]:\n    \"[| <a,b> \\<in> Memrel(A);\n        [| a \\<in> A;  b \\<in> A;  a\\<in>b |]  ==> P |]\n     ==> P\"\nby auto\n\nlemma Memrel_type: \"Memrel(A) \\<subseteq> A*A\"\nby (unfold Memrel_def, blast)\n\nlemma Memrel_mono: \"A<=B ==> 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))\"\napply (unfold 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) ==> 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) ==> 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) ==> <a,b> \\<in> Memrel(A) <-> a\\<in>b & 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    \"[| i \\<in> k;  Transset(k);\n        !!x.[| x \\<in> k;  \\<forall>y\\<in>x. P(y) |] ==> P(x) |]\n     ==>  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 ==> ~ i<j\"\nby (blast elim!: leE elim: lt_asym)\n\nlemma not_lt_imp_le: \"[| ~ i<j;  Ord(i);  Ord(j) |] ==> 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) ==> i\\<in>j <-> i<j\"\nby (unfold lt_def, blast)\n\nlemma not_lt_iff_le: \"[| Ord(i);  Ord(j) |] ==> ~ i<j <-> j \\<le> i\"\nby (blast dest: le_imp_not_lt not_lt_imp_le)\n\nlemma not_le_iff_lt: \"[| Ord(i);  Ord(j) |] ==> ~ 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) ==> 0 \\<le> i\"\nby (erule not_lt_iff_le [THEN iffD1], auto)\n\nlemma Ord_0_lt: \"[| Ord(i);  i\\<noteq>0 |] ==> 0<i\"\napply (erule not_le_iff_lt [THEN iffD1])\napply (rule Ord_0, blast)\ndone\n\nlemma Ord_0_lt_iff: \"Ord(i) ==> 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: \"[| j<=i;  Ord(i);  Ord(j) |] ==> 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 ==> i<=j\"\nby (blast dest: OrdmemD elim: ltE leE)\n\nlemma le_subset_iff: \"j \\<le> i <-> j<=i & Ord(i) & 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) & 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: \"[| Ord(i);  Ord(j);  !!x. x<j ==> x<i |] ==> j \\<le> i\"\nby (blast intro: not_lt_imp_le dest: lt_irrefl)\n\nsubsubsection\\<open>Transitivity Laws\\<close>\n\nlemma lt_trans1: \"[| i \\<le> j;  j<k |] ==> i<k\"\nby (blast elim!: leE intro: lt_trans)\n\nlemma lt_trans2: \"[| i<j;  j \\<le> k |] ==> i<k\"\nby (blast elim!: leE intro: lt_trans)\n\nlemma le_trans: \"[| i \\<le> j;  j \\<le> k |] ==> i \\<le> k\"\nby (blast intro: lt_trans1)\n\nlemma succ_leI: \"i<j ==> 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) ==> i<j  *)\nlemma succ_leE: \"succ(i) \\<le> j ==> 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) ==> i \\<le> j\"\nby (blast dest!: succ_leE)\n\nlemma lt_subset_trans: \"[| i \\<subseteq> j;  j<k;  Ord(i) |] ==> i<k\"\napply (rule subset_imp_le [THEN lt_trans1])\napply (blast intro: elim: ltE) +\ndone\n\nlemma lt_imp_0_lt: \"j<i ==> 0<i\"\nby (blast intro: lt_trans1 Ord_0_le [OF lt_Ord])\n\nlemma succ_lt_iff: \"succ(i) < j <-> i<j & 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) ==> 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: \"[| Ord(i); Ord(j) |] ==> i \\<le> i \\<union> j\"\nby (rule Un_upper1 [THEN subset_imp_le], auto)\n\nlemma Un_upper2_le: \"[| Ord(i); Ord(j) |] ==> 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: \"[| i<k;  j<k |] ==> 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: \"[| Ord(i); Ord(j) |] ==> i \\<union> j < k  <->  i<k & 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    \"[| Ord(i); Ord(j); Ord(k) |] ==> i \\<union> j \\<in> k  <->  i\\<in>k & 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: \"[| i<k;  j<k |] ==> 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     \"[| Ord(i); Ord(j) |] ==> 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     \"[| Ord(i); Ord(j) |] ==> 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     \"[| Ord(i); Ord(j) |] ==> 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     \"[| Ord(i); Ord(j) |] ==> 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: \"[|k < i; Ord(j)|] ==> k < i \\<union> j\"\nby (simp add: lt_Un_iff lt_Ord2)\n\nlemma Un_upper2_lt: \"[|k < j; Ord(i)|] ==> 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) ==> \\<Union>(succ(i)) = i\"\nby (blast intro: Ord_trans)\n\n\nsubsection\\<open>Results about Limits\\<close>\n\nlemma Ord_Union [intro,simp,TC]: \"[| !!i. i\\<in>A ==> Ord(i) |] ==> 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     \"[| !!x. x\\<in>A ==> Ord(B(x)) |] ==> Ord(\\<Union>x\\<in>A. B(x))\"\nby (rule Ord_Union, blast)\n\nlemma Ord_Inter [intro,simp,TC]:\n    \"[| !!i. i\\<in>A ==> Ord(i) |] ==> 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    \"[| !!x. x\\<in>A ==> Ord(B(x)) |] ==> 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    \"[| Ord(i);  !!x. x\\<in>A ==> b(x) \\<le> i |] ==> (\\<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    \"[| j<i;  !!x. x\\<in>A ==> b(x)<j |] ==> (\\<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     \"[| a\\<in>A;  i < b(a);  Ord(\\<Union>x\\<in>A. b(x)) |] ==> i < (\\<Union>x\\<in>A. b(x))\"\nby (unfold lt_def, blast)\n\nlemma UN_upper_le:\n     \"[| a \\<in> A;  i \\<le> b(a);  Ord(\\<Union>x\\<in>A. b(x)) |] ==> 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) ==> (j < \\<Union>(A)) <-> (\\<exists>i\\<in>A. j<i)\"\nby (auto simp: lt_def Ord_Union)\n\nlemma Union_upper_le:\n     \"[| j \\<in> J;  i\\<le>j;  Ord(\\<Union>(J)) |] ==> i \\<le> \\<Union>J\"\napply (subst Union_eq_UN)\napply (rule UN_upper_le, auto)\ndone\n\nlemma le_implies_UN_le_UN:\n    \"[| !!x. x\\<in>A ==> c(x) \\<le> d(x) |] ==> (\\<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) ==> (\\<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) ==> \\<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) ==> \\<Union>(i) = i\"\napply (unfold Limit_def)\napply (fast intro!: ltI elim!: ltE elim: Ord_trans)\ndone\n\nlemma Limit_is_Ord: \"Limit(i) ==> Ord(i)\"\napply (unfold Limit_def)\napply (erule conjunct1)\ndone\n\nlemma Limit_has_0: \"Limit(i) ==> 0 < i\"\napply (unfold Limit_def)\napply (erule conjunct2 [THEN conjunct1])\ndone\n\nlemma Limit_nonzero: \"Limit(i) ==> i \\<noteq> 0\"\nby (drule Limit_has_0, blast)\n\nlemma Limit_has_succ: \"[| Limit(i);  j<i |] ==> succ(j) < i\"\nby (unfold Limit_def, blast)\n\nlemma Limit_succ_lt_iff [simp]: \"Limit(i) ==> 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]: \"~ Limit(0)\"\nby (simp add: Limit_def)\n\nlemma Limit_has_1: \"Limit(i) ==> 1 < i\"\nby (blast intro: Limit_has_0 Limit_has_succ)\n\nlemma increasing_LimitI: \"[| 0<l; \\<forall>x\\<in>l. \\<exists>y\\<in>l. x<y |] ==> 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 \"~ 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)) ==> 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]: \"~ Limit(succ(i))\"\nby blast\n\nlemma Limit_le_succD: \"[| Limit(i);  i \\<le> succ(j) |] ==> 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) ==> i=0 | (\\<exists>j. Ord(j) & 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     \"[| Ord(i);\n         P(0);\n         !!x. [| Ord(x);  P(x) |] ==> P(succ(x));\n         !!x. [| Limit(x);  \\<forall>y\\<in>x. P(y) |] ==> P(x)\n      |] ==> 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: \"[| !!x. x\\<in>I ==> x\\<le>j; Ord(j) |] ==> \\<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: \"[|\\<forall>x\\<in>X. Ord(x);  \\<Union>X = succ(j)|] ==> succ(j) \\<in> X\"\n  by (drule Ord_set_cases, auto)\n\nlemma Limit_Union [rule_format]: \"[| I \\<noteq> 0;  (\\<And>i. i\\<in>I \\<Longrightarrow> Limit(i)) |] ==> Limit(\\<Union>I)\"\napply (simp add: Limit_def lt_def)\napply (blast intro!: equalityI)\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/Ordinal.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972818382005, "lm_q2_score": 0.8354835350552603, "lm_q1q2_score": 0.7273696946396805}}
{"text": "(*  Title:      HOL/ex/MergeSort.thy\n    Author:     Tobias Nipkow\n    Copyright   2002 TU Muenchen\n*)\n\nsection\\<open>Merge Sort\\<close>\n\ntheory MergeSort\nimports \"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 mset_merge [simp]:\n  \"mset (merge xs ys) = mset xs + mset 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 mset_msort:\n  \"mset (msort xs) = mset xs\"\n  by (induct xs rule: msort.induct)\n    (simp_all, metis append_take_drop_id drop_Suc_Cons mset.simps(2) mset_append take_Suc_Cons)\n\ntheorem msort_sort:\n  \"sort = msort\"\n  by (rule ext, rule properties_for_sort) (fact mset_msort sorted_msort)+\n\nend\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/MergeSort.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8705972751232809, "lm_q2_score": 0.8354835371034368, "lm_q1q2_score": 0.7273696908126126}}
{"text": "theory week04A_demo_simp imports Main begin\n\ntext {* Simplification *}\n\ntext {* \nLists: \n  @{term \"[]\"}       empty list\n  @{term \"x#xs\"}     cons (list with head x and tail xs)\n  @{term \"xs @ ys\"}  append xs and ys\n*}\n\nlemma \"ys @ [] = []\"\napply(simp)\noops \n\ndefinition\n  a :: \"nat list\"\nwhere\n  \"a \\<equiv> []\"\n\ndefinition\n  b :: \"nat list\"\nwhere\n  \"b \\<equiv> []\"\n\ntext {* simp add, rewriting with definitions *}\nlemma \"xs @ a = xs\" \n  apply (simp add: a_def)\n  done\n\ntext {* simp only *}\nlemma \"xs @ a = xs\"\n  using [[simp_trace]]\n  apply (simp only: a_def)\n  apply simp\n  done\n\n\nlemma ab [simp]: \"a = b\" by (simp add: a_def b_def)\nlemma ba [simp]: \"b = a\" by simp\n\ntext {* simp del, termination *}\nlemma \"a = []\"\n  \n  (*apply (simp add: a_def)  \n   does not terminate *)\n  apply (simp add: a_def del: ab) \n  done\n\n\ntext{* Simple assumption: *}\nlemma \"xs = [] \\<Longrightarrow> xs @ ys = ys @ xs @ ys\"\n  apply simp\n  oops\n\ntext{* Simplification in assumption: *}\nlemma \"\\<lbrakk> xs @ zs = ys @ xs; [] @ xs = [] @ [] \\<rbrakk> \\<Longrightarrow> ys = zs\"\n  apply simp\n  done\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/181127/week04A_demo_simp.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972684083609, "lm_q2_score": 0.8354835289107309, "lm_q1q2_score": 0.7273696780698601}}
{"text": "section \\<open>Library Extras\\<close>\ntext \\<open>Already added to the repository\\<close>\n\ntheory Library_Extras imports\n  \"HOL-Analysis.Analysis\" \n  \"HOL-ex.Sketch_and_Explore\"\n   \nbegin\n\ntext \\<open>In fact, strict inequality is required only at a single point within the box.\\<close>\nlemma integral_less:\n  fixes f :: \"'n::euclidean_space \\<Rightarrow> real\"\n  assumes cont: \"continuous_on (cbox a b) f\" \"continuous_on (cbox a b) g\" and \"box a b \\<noteq> {}\"\n    and fg: \"\\<And>x. x \\<in> box a b \\<Longrightarrow> f x < g x\"\n  shows \"integral (cbox a b) f < integral (cbox a b) g\"\nproof -\n  obtain int: \"f integrable_on (cbox a b)\" \"g integrable_on (cbox a b)\"\n    using cont integrable_continuous by blast\n  then have \"integral (cbox a b) f \\<le> integral (cbox a b) g\"\n    by (metis fg integrable_on_open_interval integral_le integral_open_interval less_eq_real_def)\n  moreover have \"integral (cbox a b) f \\<noteq> integral (cbox a b) g\"\n  proof (rule ccontr)\n    assume \"\\<not> integral (cbox a b) f \\<noteq> integral (cbox a b) g\"\n    then have 0: \"((\\<lambda>x. g x - f x) has_integral 0) (cbox a b)\"\n      by (metis (full_types) cancel_comm_monoid_add_class.diff_cancel has_integral_diff int integrable_integral)\n    have cgf: \"continuous_on (cbox a b) (\\<lambda>x. g x - f x)\"\n      using cont continuous_on_diff by blast\n    show False\n      using has_integral_0_cbox_imp_0 [OF cgf _ 0] assms(3) box_subset_cbox fg less_eq_real_def by fastforce\n  qed\n  ultimately show ?thesis\n    by linarith\nqed\n\nlemma integral_less_real:\n  fixes f :: \"real \\<Rightarrow> real\"\n  assumes \"continuous_on {a..b} f\" \"continuous_on {a..b} g\" and \"{a<..<b} \\<noteq> {}\"\n    and \"\\<And>x. x \\<in> {a<..<b} \\<Longrightarrow> f x < g x\"\n  shows \"integral {a..b} f < integral {a..b} g\"\n  by (metis assms box_real integral_less)\n\nlemma has_integral_UN:\n  fixes f :: \"'n::euclidean_space \\<Rightarrow> 'a::banach\"\n  assumes \"finite I\"\n    and int: \"\\<And>i. i \\<in> I \\<Longrightarrow> (f has_integral (g i)) (\\<T> i)\"\n    and neg: \"pairwise (\\<lambda>i i'. negligible (\\<T> i \\<inter> \\<T> i')) I\"\n  shows \"(f has_integral (sum g I)) (\\<Union>i\\<in>I. \\<T> i)\"\nproof -\n  let ?\\<U> = \"((\\<lambda>(a,b). \\<T> a \\<inter> \\<T> b) ` {(a,b). a \\<in> I \\<and> b \\<in> I-{a}})\"\n  have \"((\\<lambda>x. if x \\<in> (\\<Union>i\\<in>I. \\<T> i) then f x else 0) has_integral sum g I) UNIV\"\n  proof (rule has_integral_spike)\n    show \"negligible (\\<Union>?\\<U>)\"\n    proof (rule negligible_Union)\n      have \"finite (I \\<times> I)\"\n        by (simp add: \\<open>finite I\\<close>)\n      moreover have \"{(a,b). a \\<in> I \\<and> b \\<in> I-{a}} \\<subseteq> I \\<times> I\"\n        by auto\n      ultimately show \"finite ?\\<U>\"\n        by (simp add: finite_subset)\n      show \"\\<And>t. t \\<in> ?\\<U> \\<Longrightarrow> negligible t\"\n        using neg unfolding pairwise_def by auto\n    qed\n  next\n    show \"(if x \\<in> (\\<Union>i\\<in>I. \\<T> i) then f x else 0) = (\\<Sum>i\\<in>I. if x \\<in> \\<T> i then f x else 0)\"\n      if \"x \\<in> UNIV - (\\<Union>?\\<U>)\" for x\n    proof clarsimp\n      fix i assume i: \"i \\<in> I\" \"x \\<in> \\<T> i\"\n      then have \"\\<forall>j\\<in>I. x \\<in> \\<T> j \\<longleftrightarrow> j = i\"\n        using that by blast\n      with i show \"f x = (\\<Sum>i\\<in>I. if x \\<in> \\<T> i then f x else 0)\"\n        by (simp add: sum.delta[OF \\<open>finite I\\<close>])\n    qed\n  next\n    show \"((\\<lambda>x. (\\<Sum>i\\<in>I. if x \\<in> \\<T> i then f x else 0)) has_integral sum g I) UNIV\"\n      using int by (simp add: has_integral_restrict_UNIV has_integral_sum [OF \\<open>finite I\\<close>])\n  qed\n  then show ?thesis\n    using has_integral_restrict_UNIV by blast\nqed\n\nlemma has_integral_Union:\n  fixes f :: \"'n::euclidean_space \\<Rightarrow> 'a::banach\"\n  assumes \"finite \\<T>\"\n    and \"\\<And>S. S \\<in> \\<T> \\<Longrightarrow> (f has_integral (i S)) S\"\n    and \"pairwise (\\<lambda>S S'. negligible (S \\<inter> S')) \\<T>\"\n  shows \"(f has_integral (sum i \\<T>)) (\\<Union>\\<T>)\"\nproof -\n  have \"(f has_integral (sum i \\<T>)) (\\<Union>S\\<in>\\<T>. S)\"\n    by (intro has_integral_UN assms)\n  then show ?thesis\n    by force\nqed\n\ncorollary integral_cbox_eq_0_iff:\n  fixes f :: \"'a::euclidean_space \\<Rightarrow> real\"\n  assumes \"continuous_on (cbox a b) f\" and \"box a b \\<noteq> {}\"\n    and \"\\<And>x. x \\<in> (cbox a b) \\<Longrightarrow> f x \\<ge> 0\"\n  shows \"integral (cbox a b) f = 0 \\<longleftrightarrow> (\\<forall>x \\<in> (cbox a b). f x = 0)\" (is \"?lhs = ?rhs\")\nproof\n  assume int0: ?lhs\n  show ?rhs\n    using has_integral_0_cbox_imp_0 [of a b f] assms\n    by (metis box_subset_cbox eq_integralD int0 integrable_continuous subsetD) \nnext\n  assume ?rhs then show ?lhs\n    by (meson has_integral_is_0_cbox integral_unique)\nqed\n\nlemma integral_eq_0_iff:\n  fixes f :: \"real \\<Rightarrow> real\"\n  assumes contf: \"continuous_on {a..b} f\" and \"a < b\"\n    and f_ge0: \"\\<And>x. x \\<in> {a..b} \\<Longrightarrow> f x \\<ge> 0\"\n  shows \"integral {a..b} f = 0 \\<longleftrightarrow> (\\<forall>x \\<in> {a..b}. f x = 0)\"\n  using integral_cbox_eq_0_iff [of a b f] assms by simp\n\nlemma integralL_eq_0_iff:\n  fixes f :: \"real \\<Rightarrow> real\"\n  assumes contf: \"continuous_on {a..b} f\" and \"a < b\"\n    and \"\\<And>x. x \\<in> {a..b} \\<Longrightarrow> f x \\<ge> 0\"\n  shows \"integral\\<^sup>L (lebesgue_on {a..b}) f = 0 \\<longleftrightarrow> (\\<forall>x \\<in> {a..b}. f x = 0)\" \n  using integral_eq_0_iff [OF assms]\n  by (simp add: contf continuous_imp_integrable_real lebesgue_integral_eq_integral)\n\n\nlemma fact_eq_fact_times:\n  assumes \"m \\<ge> n\"\n  shows \"fact m = fact n * \\<Prod>{Suc n..m}\"\n  unfolding fact_prod\n  by (metis add.commute assms le_add1 le_add_diff_inverse of_nat_id plus_1_eq_Suc prod.ub_add_nat)\n\nlemma fact_div_fact:\n  assumes \"m \\<ge> n\"\n  shows \"fact m div fact n = \\<Prod>{n + 1..m}\"\n  by (simp add: fact_eq_fact_times [OF assms])\n\nlemma deriv_sum [simp]:\n  \"\\<lbrakk>\\<And>i. f i field_differentiable at z\\<rbrakk>\n   \\<Longrightarrow> deriv (\\<lambda>w. sum (\\<lambda>i. f i w) S) z = sum (\\<lambda>i. deriv (f i) z) S\"\n  unfolding DERIV_deriv_iff_field_differentiable[symmetric]\n  by (auto intro!: DERIV_imp_deriv derivative_intros)\n\nlemma deriv_pow: \"\\<lbrakk>f field_differentiable at z\\<rbrakk>\n   \\<Longrightarrow> deriv (\\<lambda>w. f w ^ n) z = (if n=0 then 0 else n * deriv f z * f z ^ (n - Suc 0))\"\n  unfolding DERIV_deriv_iff_field_differentiable[symmetric]\n  by (auto intro!: DERIV_imp_deriv derivative_eq_intros)\n\nlemma deriv_minus [simp]:\n  \"f field_differentiable at z \\<Longrightarrow> deriv (\\<lambda>w. - f w) z = - deriv f z\"\n  by (simp add: DERIV_deriv_iff_field_differentiable DERIV_imp_deriv Deriv.field_differentiable_minus)\n", "meta": {"author": "lawrencecpaulson", "repo": "Isabelle-experiments", "sha": "3b531a7aa352882d3688ddc74615ee8bf5d6364e", "save_path": "github-repos/isabelle/lawrencecpaulson-Isabelle-experiments", "path": "github-repos/isabelle/lawrencecpaulson-Isabelle-experiments/Isabelle-experiments-3b531a7aa352882d3688ddc74615ee8bf5d6364e/Library_Extras.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681013541613, "lm_q2_score": 0.847967764140929, "lm_q1q2_score": 0.727359699056698}}
{"text": "(*  Title:      ZF/pair.thy\n    Author:     Lawrence C Paulson, Cambridge University Computer Laboratory\n    Copyright   1992  University of Cambridge\n*)\n\nsection\\<open>Ordered Pairs\\<close>\n\ntheory pair imports upair\nbegin\n\nML_file \\<open>simpdata.ML\\<close>\n\nsetup \\<open>\n  map_theory_simpset\n    (Simplifier.set_mksimps (fn ctxt => map mk_eq o ZF_atomize o Variable.gen_all ctxt)\n      #> Simplifier.add_cong @{thm if_weak_cong})\n\\<close>\n\nML \\<open>val ZF_ss = simpset_of \\<^context>\\<close>\n\nsimproc_setup defined_Bex (\"\\<exists>x\\<in>A. P(x) \\<and> Q(x)\") = \\<open>\n  fn _ => Quantifier1.rearrange_Bex\n    (fn ctxt => unfold_tac ctxt @{thms Bex_def})\n\\<close>\n\nsimproc_setup defined_Ball (\"\\<forall>x\\<in>A. P(x) \\<longrightarrow> Q(x)\") = \\<open>\n  fn _ => Quantifier1.rearrange_Ball\n    (fn ctxt => unfold_tac ctxt @{thms Ball_def})\n\\<close>\n\n\n(** Lemmas for showing that \\<langle>a,b\\<rangle> uniquely determines a and b **)\n\nlemma singleton_eq_iff [iff]: \"{a} = {b} \\<longleftrightarrow> a=b\"\nby (rule extension [THEN iff_trans], blast)\n\nlemma doubleton_eq_iff: \"{a,b} = {c,d} \\<longleftrightarrow> (a=c \\<and> b=d) | (a=d \\<and> b=c)\"\nby (rule extension [THEN iff_trans], blast)\n\nlemma Pair_iff [simp]: \"\\<langle>a,b\\<rangle> = \\<langle>c,d\\<rangle> \\<longleftrightarrow> a=c \\<and> b=d\"\nby (simp add: Pair_def doubleton_eq_iff, blast)\n\nlemmas Pair_inject = Pair_iff [THEN iffD1, THEN conjE, elim!]\n\nlemmas Pair_inject1 = Pair_iff [THEN iffD1, THEN conjunct1]\nlemmas Pair_inject2 = Pair_iff [THEN iffD1, THEN conjunct2]\n\nlemma Pair_not_0: \"\\<langle>a,b\\<rangle> \\<noteq> 0\"\n  unfolding Pair_def\napply (blast elim: equalityE)\ndone\n\nlemmas Pair_neq_0 = Pair_not_0 [THEN notE, elim!]\n\ndeclare sym [THEN Pair_neq_0, elim!]\n\nlemma Pair_neq_fst: \"\\<langle>a,b\\<rangle>=a \\<Longrightarrow> P\"\nproof (unfold Pair_def)\n  assume eq: \"{{a, a}, {a, b}} = a\"\n  have  \"{a, a} \\<in> {{a, a}, {a, b}}\" by (rule consI1)\n  hence \"{a, a} \\<in> a\" by (simp add: eq)\n  moreover have \"a \\<in> {a, a}\" by (rule consI1)\n  ultimately show \"P\" by (rule mem_asym)\nqed\n\nlemma Pair_neq_snd: \"\\<langle>a,b\\<rangle>=b \\<Longrightarrow> P\"\nproof (unfold Pair_def)\n  assume eq: \"{{a, a}, {a, b}} = b\"\n  have  \"{a, b} \\<in> {{a, a}, {a, b}}\" by blast\n  hence \"{a, b} \\<in> b\" by (simp add: eq)\n  moreover have \"b \\<in> {a, b}\" by blast\n  ultimately show \"P\" by (rule mem_asym)\nqed\n\n\nsubsection\\<open>Sigma: Disjoint Union of a Family of Sets\\<close>\n\ntext\\<open>Generalizes Cartesian product\\<close>\n\nlemma Sigma_iff [simp]: \"\\<langle>a,b\\<rangle>: Sigma(A,B) \\<longleftrightarrow> a \\<in> A \\<and> b \\<in> B(a)\"\nby (simp add: Sigma_def)\n\nlemma SigmaI [TC,intro!]: \"\\<lbrakk>a \\<in> A;  b \\<in> B(a)\\<rbrakk> \\<Longrightarrow> \\<langle>a,b\\<rangle> \\<in> Sigma(A,B)\"\nby simp\n\nlemmas SigmaD1 = Sigma_iff [THEN iffD1, THEN conjunct1]\nlemmas SigmaD2 = Sigma_iff [THEN iffD1, THEN conjunct2]\n\n(*The general elimination rule*)\nlemma SigmaE [elim!]:\n    \"\\<lbrakk>c \\<in> Sigma(A,B);\n        \\<And>x y.\\<lbrakk>x \\<in> A;  y \\<in> B(x);  c=\\<langle>x,y\\<rangle>\\<rbrakk> \\<Longrightarrow> P\n\\<rbrakk> \\<Longrightarrow> P\"\nby (unfold Sigma_def, blast)\n\nlemma SigmaE2 [elim!]:\n    \"\\<lbrakk>\\<langle>a,b\\<rangle> \\<in> Sigma(A,B);\n        \\<lbrakk>a \\<in> A;  b \\<in> B(a)\\<rbrakk> \\<Longrightarrow> P\n\\<rbrakk> \\<Longrightarrow> P\"\nby (unfold Sigma_def, blast)\n\nlemma Sigma_cong:\n    \"\\<lbrakk>A=A';  \\<And>x. x \\<in> A' \\<Longrightarrow> B(x)=B'(x)\\<rbrakk> \\<Longrightarrow>\n     Sigma(A,B) = Sigma(A',B')\"\nby (simp add: Sigma_def)\n\n(*Sigma_cong, Pi_cong NOT given to Addcongs: they cause\n  flex-flex pairs and the \"Check your prover\" error.  Most\n  Sigmas and Pis are abbreviated as * or -> *)\n\nlemma Sigma_empty1 [simp]: \"Sigma(0,B) = 0\"\nby blast\n\nlemma Sigma_empty2 [simp]: \"A*0 = 0\"\nby blast\n\nlemma Sigma_empty_iff: \"A*B=0 \\<longleftrightarrow> A=0 | B=0\"\nby blast\n\n\nsubsection\\<open>Projections \\<^term>\\<open>fst\\<close> and \\<^term>\\<open>snd\\<close>\\<close>\n\nlemma fst_conv [simp]: \"fst(\\<langle>a,b\\<rangle>) = a\"\nby (simp add: fst_def)\n\nlemma snd_conv [simp]: \"snd(\\<langle>a,b\\<rangle>) = b\"\nby (simp add: snd_def)\n\nlemma fst_type [TC]: \"p \\<in> Sigma(A,B) \\<Longrightarrow> fst(p) \\<in> A\"\nby auto\n\nlemma snd_type [TC]: \"p \\<in> Sigma(A,B) \\<Longrightarrow> snd(p) \\<in> B(fst(p))\"\nby auto\n\nlemma Pair_fst_snd_eq: \"a \\<in> Sigma(A,B) \\<Longrightarrow> <fst(a),snd(a)> = a\"\nby auto\n\n\nsubsection\\<open>The Eliminator, \\<^term>\\<open>split\\<close>\\<close>\n\n(*A META-equality, so that it applies to higher types as well...*)\nlemma split [simp]: \"split(\\<lambda>x y. c(x,y), \\<langle>a,b\\<rangle>) \\<equiv> c(a,b)\"\nby (simp add: split_def)\n\nlemma split_type [TC]:\n    \"\\<lbrakk>p \\<in> Sigma(A,B);\n         \\<And>x y.\\<lbrakk>x \\<in> A; y \\<in> B(x)\\<rbrakk> \\<Longrightarrow> c(x,y):C(\\<langle>x,y\\<rangle>)\n\\<rbrakk> \\<Longrightarrow> split(\\<lambda>x y. c(x,y), p) \\<in> C(p)\"\nby (erule SigmaE, auto)\n\nlemma expand_split:\n  \"u \\<in> A*B \\<Longrightarrow>\n        R(split(c,u)) \\<longleftrightarrow> (\\<forall>x\\<in>A. \\<forall>y\\<in>B. u = \\<langle>x,y\\<rangle> \\<longrightarrow> R(c(x,y)))\"\nby (auto simp add: split_def)\n\n\nsubsection\\<open>A version of \\<^term>\\<open>split\\<close> for Formulae: Result Type \\<^typ>\\<open>o\\<close>\\<close>\n\nlemma splitI: \"R(a,b) \\<Longrightarrow> split(R, \\<langle>a,b\\<rangle>)\"\nby (simp add: split_def)\n\nlemma splitE:\n    \"\\<lbrakk>split(R,z);  z \\<in> Sigma(A,B);\n        \\<And>x y. \\<lbrakk>z = \\<langle>x,y\\<rangle>;  R(x,y)\\<rbrakk> \\<Longrightarrow> P\n\\<rbrakk> \\<Longrightarrow> P\"\nby (auto simp add: split_def)\n\nlemma splitD: \"split(R,\\<langle>a,b\\<rangle>) \\<Longrightarrow> R(a,b)\"\nby (simp add: split_def)\n\ntext \\<open>\n  \\bigskip Complex rules for Sigma.\n\\<close>\n\nlemma split_paired_Bex_Sigma [simp]:\n     \"(\\<exists>z \\<in> Sigma(A,B). P(z)) \\<longleftrightarrow> (\\<exists>x \\<in> A. \\<exists>y \\<in> B(x). P(\\<langle>x,y\\<rangle>))\"\nby blast\n\nlemma split_paired_Ball_Sigma [simp]:\n     \"(\\<forall>z \\<in> Sigma(A,B). P(z)) \\<longleftrightarrow> (\\<forall>x \\<in> A. \\<forall>y \\<in> B(x). P(\\<langle>x,y\\<rangle>))\"\nby blast\n\nend\n\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/ZF/pair.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680977182187, "lm_q2_score": 0.8479677526147223, "lm_q1q2_score": 0.7273596860867235}}
{"text": "theory Sorting\nimports Main \"HOL-Library.Multiset\"\nbegin\n\ninductive sorted :: \"'a::linorder list \\<Rightarrow> bool\" where\nempty: \"sorted []\" |\nsingle: \"sorted [x]\" |\ncons: \"x\\<^sub>1 \\<le> x\\<^sub>2 \\<Longrightarrow> sorted (x\\<^sub>2 # xs) \\<Longrightarrow> sorted (x\\<^sub>1 # x\\<^sub>2 # xs)\"\n\ncode_pred sorted .\n\nlemma sorted_cons_dest[dest]: \"sorted (x # xs) \\<Longrightarrow> sorted xs\"\nby (ind_cases \"sorted (x # xs)\") (auto intro: sorted.intros)\n\nlocale sorting =\n  fixes sort :: \"'a::linorder list \\<Rightarrow> 'a list\"\n  assumes sorted: \"sorted (sort xs)\" and permutation: \"mset (sort xs) = mset xs\"\n\nend\n", "meta": {"author": "larsrh", "repo": "sorting", "sha": "da6faf36458676983300f7fbf37037fa12430031", "save_path": "github-repos/isabelle/larsrh-sorting", "path": "github-repos/isabelle/larsrh-sorting/sorting-da6faf36458676983300f7fbf37037fa12430031/Sorting.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9111797075998822, "lm_q2_score": 0.7981867729389246, "lm_q1q2_score": 0.7272915903765829}}
{"text": "theory Prog_Prove_3_4\n  imports Main\nbegin\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\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_4.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9230391685381605, "lm_q2_score": 0.7879311956428947, "lm_q1q2_score": 0.7272913556914962}}
{"text": "theory Queue\n  imports Main\nbegin\n\ntype_synonym 'a queue = \"'a list\"\n\ndefinition isempty :: \"'a queue \\<Rightarrow> bool\" \nwhere \"isempty q \\<equiv> (q = [])\"\n\nabbreviation \"emptyq \\<equiv> []\"\n\nfun enqueue :: \"'a queue \\<Rightarrow> 'a \\<Rightarrow> 'a queue\" \nwhere \"enqueue xs x = x # xs\"\n\nfun dequeue :: \"'a queue \\<Rightarrow> ('a \\<times> 'a queue)\" \nwhere \"dequeue xs = (last xs, butlast xs)\"\n\nlemma \"dequeue (enqueue emptyq a) = (a, emptyq)\" by auto\n\nfun listenq :: \"'a queue \\<Rightarrow> 'a list \\<Rightarrow> 'a queue\" where\n  \"listenq q [] = q\" |\n  \"listenq q (x # xs) = listenq (enqueue q x) xs\"\n\nfun deq2list :: \"'a queue \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where\n  \"deq2list [] lst = lst\"|\n  \"deq2list q lst = \n      (let (x, xq) = dequeue(q) in \n        (deq2list xq (x # lst)))\"\n\ndefinition \"list_enqueue l \\<equiv> listenq [] l\"\ndefinition \"dequeue_list q \\<equiv> deq2list q []\"\n\nlemma listenq_rev: \"listenq q xs = (rev xs) @ q\"\nproof(induction q xs rule: listenq.induct) \n  case (1 q) (* \\<And>q. listenq q emptyq = rev emptyq @ q *)\n  thus ?case by auto\nnext\n  case (2 q x xs)  (* \\<And>q x xs. listenq (enqueue q x) xs = rev xs @ enqueue q x \n                                  \\<Longrightarrow> listenq q (x # xs) = rev (x # xs) @ q *)\n  thus ?case by simp\nqed\n\nlemma deq2list_ind: \"deq2list q xs = q @ xs\"\nproof(induction q xs rule: deq2list.induct)\n  case (1 lst)\n  show ?case by auto\nnext\n  case (2 v va lst) \n  obtain xa y where o0: \"v # va = y @ [xa]\"\n    using rev_exhaust by blast \n  hence o1: \"dequeue (v # va) = (xa, y)\" by simp\n  hence o2: \"deq2list y (xa # lst) = y @ (xa # lst)\" \n    using \"2.IH\" by auto\n  with o1 have \"deq2list (v # va) lst = deq2list y (xa # lst)\"\n    by auto\n  thus ?case\n    using o1 o2 by auto\nqed\n\nlemma deqall_expand_rev: \"deq2list (listenq [] xs) [] = rev xs\"\nproof(induction xs)\ncase Nil\n  thus ?case by auto \nnext\n  case (Cons a xs)\n  thus ?case by (simp add: deq2list_ind listenq_rev)\nqed\n\nlemma \"dequeue_list q = q\"\n  apply(simp add:dequeue_list_def)\n  using deq2list_ind[of q \"[]\"] by auto\n\ntheorem queue_cor: \"dequeue_list (list_enqueue xs) = rev xs\"\n  apply(simp add:dequeue_list_def list_enqueue_def)\n  using deqall_expand_rev by auto\n\nend", "meta": {"author": "LVPGroup", "repo": "fpp", "sha": "7e18377ea2c553bf6e57412727a4f06832d93577", "save_path": "github-repos/isabelle/LVPGroup-fpp", "path": "github-repos/isabelle/LVPGroup-fpp/fpp-7e18377ea2c553bf6e57412727a4f06832d93577/4_ds_algo/Stack_Queue/Queue.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637433190938, "lm_q2_score": 0.845942439250491, "lm_q1q2_score": 0.7272260439585622}}
{"text": "(* \n    Title:      Miscellaneous.thy\n    Author:     Jose Divas\u00f3n <jose.divasonm at unirioja.es>\n    Author:     Jes\u00fas Aransay <jesus-maria.aransay at unirioja.es>\n*)\n\nsection\\<open>Miscellaneous\\<close>\n\ntheory Miscellaneous\n  imports\n  \"HOL-Analysis.Determinants\"\n  Mod_Type\n  \"HOL-Library.Function_Algebras\"\nbegin\n\ncontext Vector_Spaces.linear begin\nsublocale vector_space_pair by unfold_locales\\<comment>\\<open>TODO: (re)move?\\<close>\nend\n\nhide_const (open) Real_Vector_Spaces.linear\nabbreviation \"linear \\<equiv> Vector_Spaces.linear\"\n\ntext\\<open>In this file, we present some basic definitions and lemmas about linear algebra and matrices.\\<close>\n\nsubsection\\<open>Definitions of number of rows and columns of a matrix\\<close>\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::ab_semigroup_mult => 'a ^'n^'m => 'a ^'n^'m\"\n    (infixl \"*k\" 70)\n  where \"k *k A \\<equiv> (\\<chi> i j. k * A $ i $ j)\"\n\nsubsection\\<open>Basic properties about matrices\\<close>\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 transpose_vector: \"x v* A = transpose A *v x\"\n  by simp\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\\<open>Theorems obtained from the AFP\\<close>\n\ntext\\<open>The following theorems and definitions have been obtained from the AFP \n@{url \"http://isa-afp.org/browser_info/current/HOL/Tarskis_Geometry/Linear_Algebra2.html\"}.\nI have removed some restrictions over the type classes.\\<close>\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: sum_distrib_left vector_space_over_itself.scale_scale)\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\"\n  by (metis transpose_scalar vector_scalar_matrix_ac vector_transpose_matrix)\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\"\n  by (simp add: Miscellaneous.scalar_matrix_vector_assoc vec.scale)\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 \\<open>card S = CARD('n)\\<close> 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 \\<open>card B = CARD('n)\\<close>\n  have \"finite B\" by simp\n  from \\<open>card B = CARD('n)\\<close>\n  have \"card B = vec.dim (UNIV :: (('a^'n) set))\" unfolding vec_dim_card .\n  with vec.card_eq_dim [of B UNIV] and \\<open>finite B\\<close> and \\<open>vec.independent B\\<close>\n  have \"vec.span B = UNIV\" by auto\n  with \\<open>vec.independent B\\<close> 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 \\<open>is_basis B\\<close> 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\\<open>Here ends the statements obtained from AFP: \n  @{url \"http://isa-afp.org/browser_info/current/HOL/Tarskis_Geometry/Linear_Algebra2.html\"}\n  which have been generalized.\\<close>\n\nsubsection\\<open>Basic properties involving span, linearity and dimensions\\<close>\n\ncontext finite_dimensional_vector_space\nbegin\n\ntext\\<open>This theorem is the reciprocal theorem of @{thm \"indep_card_eq_dim_span\"}\\<close>\n\nlemma card_eq_dim_span_indep:\n  assumes \"dim (span A) = card A\" and \"finite A\"\n  shows \"independent A\" \n  by (metis assms card_le_dim_spanning dim_subset equalityE span_superset)\n\nlemma dim_zero_eq:\n  assumes dim_A: \"dim A = 0\"\n  shows \"A = {} \\<or> A = {0}\"\n  using dim_A local.card_ge_dim_independent local.independent_empty by force\n\nlemma dim_zero_eq': \n  assumes A: \"A = {} \\<or> A = {0}\"\n  shows \"dim A = 0\"\nusing assms local.dim_span local.indep_card_eq_dim_span local.independent_empty by fastforce\n\nlemma dim_zero_subspace_eq:\n  assumes subs_A: \"subspace A\"\n  shows \"(dim A = 0) = (A = {0})\" \n  by (metis dim_zero_eq dim_zero_eq' subspace_0[OF subs_A] empty_iff)\n\n\n\nend\n\ncontext Vector_Spaces.linear\nbegin\n\nlemma linear_injective_ker_0:\n  shows \"inj f = ({x. f x = 0} = {0})\"\n  using inj_iff_eq_0 by auto\n\nend\n\nlemma snd_if_conv:\n  shows \"snd (if P then (A,B) else (C,D))=(if P then B else D)\" by simp\n\nsubsection\\<open>Basic properties about matrix multiplication\\<close>\n\nlemma row_matrix_matrix_mult:\n  fixes A::\"'a::{comm_ring_1}^'n^'m\"\n  shows \"(P $ i) v* A = (P ** A) $ i\"\n  unfolding vec_eq_iff\n  unfolding vector_matrix_mult_def unfolding matrix_matrix_mult_def\n  by (auto intro!: sum.cong)\n\ncorollary row_matrix_matrix_mult':\n  fixes A::\"'a::{comm_ring_1}^'n^'m\"\n  shows \"(row i P) v* A = row i (P ** A)\"\n  using row_matrix_matrix_mult unfolding row_def vec_nth_inverse .\n\nlemma column_matrix_matrix_mult:\n  shows \"column i (P**A) = P *v (column i A)\"\n  unfolding column_def matrix_vector_mult_def matrix_matrix_mult_def by fastforce\n\nlemma matrix_matrix_mult_inner_mult:\n  shows \"(A ** B) $ i $ j = row i A \\<bullet> column j B\"\n  unfolding 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 = sum (\\<lambda>y. f y *s y) (columns A)\"\nproof (rule exI[of _ \"\\<lambda>y. sum (\\<lambda>i. x $ i) {i. y = column i A}\"])\n  let ?f=\"\\<lambda>y. sum (\\<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_sum ..\n  also have \"... = sum (\\<lambda>i.  x $ i *s column i A) (\\<Union>(?g`(columns A)))\" unfolding union_univ ..\n  also have \"... = sum (sum ((\\<lambda>i.  x $ i *s column i A)))  (?g`(columns A))\"\n    by (rule sum.Union_disjoint[unfolded o_def], auto) \n  also have \"... = sum ((sum ((\\<lambda>i.  x $ i *s column i A))) \\<circ> ?g)  (columns A)\" \n    by (rule sum.reindex, simp add: inj)\n  also have \"... =  sum (\\<lambda>y. ?f y *s y) (columns A)\"\n  proof (rule sum.cong, unfold o_def)\n    fix xa\n    have \"sum (\\<lambda>i. x $ i *s column i A) {i. xa = column i A} \n      = sum (\\<lambda>i. x $ i *s xa) {i. xa = column i A}\" by simp\n    also have \"... = sum (\\<lambda>i. x $ i) {i. xa = column i A} *s xa\" \n      using vec.scale_sum_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\\<open>Properties about invertibility\\<close>\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 \\<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\ntext\\<open>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\"}\\<close>\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\"\n  by (metis AB BA invertible_def matrix_inv_right matrix_mul_assoc matrix_mul_lid) \n\n\nlemma matrix_vector_mult_zero_eq:\n  assumes P: \"invertible P\"\n  shows \"((P**A)*v x = 0) = (A *v x = 0)\"\nproof (rule iffI)\n  assume \"P ** A *v x = 0\" \n  hence \"matrix_inv P *v (P ** A *v x) = matrix_inv P *v 0\" by simp\n  hence \"matrix_inv P *v (P ** A *v x) =  0\" by (metis matrix_vector_mult_0_right)\n  hence \"(matrix_inv P ** P ** A) *v x =  0\" by (metis matrix_vector_mul_assoc)\n  thus \"A *v x =  0\" by (metis assms matrix_inv_left matrix_mul_lid)\nnext\n  assume \"A *v x = 0\" \n  thus \"P ** A *v x = 0\" by (metis matrix_vector_mul_assoc matrix_vector_mult_0_right)\nqed\n\nlemma independent_image_matrix_vector_mult:\n  fixes P::\"'a::{field}^'n^'m\"\n  assumes ind_B: \"vec.independent B\" and inv_P: \"invertible P\"\n  shows \"vec.independent (((*v) P)` B)\"\nproof (rule vec.independent_injective_image)\n  show \"vec.independent B\" using ind_B .\n  show \"inj_on ((*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 (((*v) P)` B)\" and inv_P: \"invertible P\"\nshows \"vec.independent B\"\nproof -\nhave \"vec.independent (((*v) (matrix_inv P))` (((*v) P)` B))\"\n  proof (rule independent_image_matrix_vector_mult)\n    show \"vec.independent ((*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 \"((*v) (matrix_inv P))` (((*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> (*v) (matrix_inv P) ` (*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\\<open>Properties about the dimension of vectors\\<close>\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\\<open>Instantiations and interpretations\\<close>\n\ntext\\<open>Functions between two real vector spaces form a real vector\\<close>\ninstantiation \"fun\" :: (real_vector, real_vector) real_vector\nbegin\n\ndefinition \"scaleR_fun a f = (\\<lambda>i. a *\\<^sub>R f i )\"\n\ninstance \n  by (intro_classes, auto simp add: fun_eq_iff scaleR_fun_def scaleR_left.add scaleR_right.add)\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\ninterpretation matrix: vector_space \"((*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\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/Rank_Nullity_Theorem/Miscellaneous.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8596637433190939, "lm_q2_score": 0.8459424334245617, "lm_q1q2_score": 0.7272260389502221}}
{"text": "(*  Title:      HOL/Proofs/Lambda/Commutation.thy\n    Author:     Tobias Nipkow\n    Copyright   1995  TU Muenchen\n*)\n\nsection {* Abstract commutation and confluence notions *}\n\ntheory Commutation\nimports Main\nbegin\n\ndeclare [[syntax_ambiguity_warning = false]]\n\n\nsubsection {* Basic definitions *}\n\ndefinition\n  square :: \"['a => 'a => bool, 'a => 'a => bool, 'a => 'a => bool, 'a => 'a => bool] => bool\" where\n  \"square R S T U =\n    (\\<forall>x y. R x y --> (\\<forall>z. S x z --> (\\<exists>u. T y u \\<and> U z u)))\"\n\ndefinition\n  commute :: \"['a => 'a => bool, 'a => 'a => bool] => bool\" where\n  \"commute R S = square R S S R\"\n\ndefinition\n  diamond :: \"('a => 'a => bool) => bool\" where\n  \"diamond R = commute R R\"\n\ndefinition\n  Church_Rosser :: \"('a => 'a => bool) => bool\" where\n  \"Church_Rosser R =\n    (\\<forall>x y. (sup R (R^--1))^** x y --> (\\<exists>z. R^** x z \\<and> R^** y z))\"\n\nabbreviation\n  confluent :: \"('a => 'a => bool) => bool\" where\n  \"confluent R == diamond (R^**)\"\n\n\nsubsection {* Basic lemmas *}\n\nsubsubsection {* @{text \"square\"} *}\n\nlemma square_sym: \"square R S T U ==> square S R U T\"\n  apply (unfold square_def)\n  apply blast\n  done\n\nlemma square_subset:\n    \"[| square R S T U; T \\<le> T' |] ==> square R S T' U\"\n  apply (unfold square_def)\n  apply (blast dest: predicate2D)\n  done\n\nlemma square_reflcl:\n    \"[| square R S T (R^==); S \\<le> T |] ==> square (R^==) S T (R^==)\"\n  apply (unfold square_def)\n  apply (blast dest: predicate2D)\n  done\n\nlemma square_rtrancl:\n    \"square R S S T ==> square (R^**) S S (T^**)\"\n  apply (unfold square_def)\n  apply (intro strip)\n  apply (erule rtranclp_induct)\n   apply blast\n  apply (blast intro: rtranclp.rtrancl_into_rtrancl)\n  done\n\nlemma square_rtrancl_reflcl_commute:\n    \"square R S (S^**) (R^==) ==> commute (R^**) (S^**)\"\n  apply (unfold commute_def)\n  apply (fastforce dest: square_reflcl square_sym [THEN square_rtrancl])\n  done\n\n\nsubsubsection {* @{text \"commute\"} *}\n\nlemma commute_sym: \"commute R S ==> commute S R\"\n  apply (unfold commute_def)\n  apply (blast intro: square_sym)\n  done\n\nlemma commute_rtrancl: \"commute R S ==> commute (R^**) (S^**)\"\n  apply (unfold commute_def)\n  apply (blast intro: square_rtrancl square_sym)\n  done\n\nlemma commute_Un:\n    \"[| commute R T; commute S T |] ==> commute (sup R S) T\"\n  apply (unfold commute_def square_def)\n  apply blast\n  done\n\n\nsubsubsection {* @{text \"diamond\"}, @{text \"confluence\"}, and @{text \"union\"} *}\n\nlemma diamond_Un:\n    \"[| diamond R; diamond S; commute R S |] ==> diamond (sup R S)\"\n  apply (unfold diamond_def)\n  apply (blast intro: commute_Un commute_sym) \n  done\n\nlemma diamond_confluent: \"diamond R ==> confluent R\"\n  apply (unfold diamond_def)\n  apply (erule commute_rtrancl)\n  done\n\nlemma square_reflcl_confluent:\n    \"square R R (R^==) (R^==) ==> confluent R\"\n  apply (unfold diamond_def)\n  apply (fast intro: square_rtrancl_reflcl_commute elim: square_subset)\n  done\n\nlemma confluent_Un:\n    \"[| confluent R; confluent S; commute (R^**) (S^**) |] ==> confluent (sup R S)\"\n  apply (rule rtranclp_sup_rtranclp [THEN subst])\n  apply (blast dest: diamond_Un intro: diamond_confluent)\n  done\n\nlemma diamond_to_confluence:\n    \"[| diamond R; T \\<le> R; R \\<le> T^** |] ==> confluent T\"\n  apply (force intro: diamond_confluent\n    dest: rtranclp_subset [symmetric])\n  done\n\n\nsubsection {* Church-Rosser *}\n\nlemma Church_Rosser_confluent: \"Church_Rosser R = confluent R\"\n  apply (unfold square_def commute_def diamond_def Church_Rosser_def)\n  apply (tactic {* safe_tac (put_claset HOL_cs @{context}) *})\n   apply (tactic {*\n     blast_tac (put_claset HOL_cs @{context} addIs\n       [@{thm sup_ge2} RS @{thm rtranclp_mono} RS @{thm predicate2D} RS @{thm rtranclp_trans},\n        @{thm rtranclp_converseI}, @{thm conversepI},\n        @{thm sup_ge1} RS @{thm rtranclp_mono} RS @{thm predicate2D}]) 1 *})\n  apply (erule rtranclp_induct)\n   apply blast\n  apply (blast del: rtranclp.rtrancl_refl intro: rtranclp_trans)\n  done\n\n\nsubsection {* Newman's lemma *}\n\ntext {* Proof by Stefan Berghofer *}\n\ntheorem newman:\n  assumes wf: \"wfP (R\\<inverse>\\<inverse>)\"\n  and lc: \"\\<And>a b c. R a b \\<Longrightarrow> R a c \\<Longrightarrow>\n    \\<exists>d. R\\<^sup>*\\<^sup>* b d \\<and> R\\<^sup>*\\<^sup>* c d\"\n  shows \"\\<And>b c. R\\<^sup>*\\<^sup>* a b \\<Longrightarrow> R\\<^sup>*\\<^sup>* a c \\<Longrightarrow>\n    \\<exists>d. R\\<^sup>*\\<^sup>* b d \\<and> R\\<^sup>*\\<^sup>* c d\"\n  using wf\nproof induct\n  case (less x b c)\n  have xc: \"R\\<^sup>*\\<^sup>* x c\" by fact\n  have xb: \"R\\<^sup>*\\<^sup>* x b\" by fact thus ?case\n  proof (rule converse_rtranclpE)\n    assume \"x = b\"\n    with xc have \"R\\<^sup>*\\<^sup>* b c\" by simp\n    thus ?thesis by iprover\n  next\n    fix y\n    assume xy: \"R x y\"\n    assume yb: \"R\\<^sup>*\\<^sup>* y b\"\n    from xc show ?thesis\n    proof (rule converse_rtranclpE)\n      assume \"x = c\"\n      with xb have \"R\\<^sup>*\\<^sup>* c b\" by simp\n      thus ?thesis by iprover\n    next\n      fix y'\n      assume y'c: \"R\\<^sup>*\\<^sup>* y' c\"\n      assume xy': \"R x y'\"\n      with xy have \"\\<exists>u. R\\<^sup>*\\<^sup>* y u \\<and> R\\<^sup>*\\<^sup>* y' u\" by (rule lc)\n      then obtain u where yu: \"R\\<^sup>*\\<^sup>* y u\" and y'u: \"R\\<^sup>*\\<^sup>* y' u\" by iprover\n      from xy have \"R\\<inverse>\\<inverse> y x\" ..\n      from this and yb yu have \"\\<exists>d. R\\<^sup>*\\<^sup>* b d \\<and> R\\<^sup>*\\<^sup>* u d\" by (rule less)\n      then obtain v where bv: \"R\\<^sup>*\\<^sup>* b v\" and uv: \"R\\<^sup>*\\<^sup>* u v\" by iprover\n      from xy' have \"R\\<inverse>\\<inverse> y' x\" ..\n      moreover from y'u and uv have \"R\\<^sup>*\\<^sup>* y' v\" by (rule rtranclp_trans)\n      moreover note y'c\n      ultimately have \"\\<exists>d. R\\<^sup>*\\<^sup>* v d \\<and> R\\<^sup>*\\<^sup>* c d\" by (rule less)\n      then obtain w where vw: \"R\\<^sup>*\\<^sup>* v w\" and cw: \"R\\<^sup>*\\<^sup>* c w\" by iprover\n      from bv vw have \"R\\<^sup>*\\<^sup>* b w\" by (rule rtranclp_trans)\n      with cw show ?thesis by iprover\n    qed\n  qed\nqed\n\ntext {*\n  Alternative version.  Partly automated by Tobias\n  Nipkow. Takes 2 minutes (2002).\n\n  This is the maximal amount of automation possible using @{text blast}.\n*}\n\ntheorem newman':\n  assumes wf: \"wfP (R\\<inverse>\\<inverse>)\"\n  and lc: \"\\<And>a b c. R a b \\<Longrightarrow> R a c \\<Longrightarrow>\n    \\<exists>d. R\\<^sup>*\\<^sup>* b d \\<and> R\\<^sup>*\\<^sup>* c d\"\n  shows \"\\<And>b c. R\\<^sup>*\\<^sup>* a b \\<Longrightarrow> R\\<^sup>*\\<^sup>* a c \\<Longrightarrow>\n    \\<exists>d. R\\<^sup>*\\<^sup>* b d \\<and> R\\<^sup>*\\<^sup>* c d\"\n  using wf\nproof induct\n  case (less x b c)\n  note IH = `\\<And>y b c. \\<lbrakk>R\\<inverse>\\<inverse> y x; R\\<^sup>*\\<^sup>* y b; R\\<^sup>*\\<^sup>* y c\\<rbrakk>\n                     \\<Longrightarrow> \\<exists>d. R\\<^sup>*\\<^sup>* b d \\<and> R\\<^sup>*\\<^sup>* c d`\n  have xc: \"R\\<^sup>*\\<^sup>* x c\" by fact\n  have xb: \"R\\<^sup>*\\<^sup>* x b\" by fact\n  thus ?case\n  proof (rule converse_rtranclpE)\n    assume \"x = b\"\n    with xc have \"R\\<^sup>*\\<^sup>* b c\" by simp\n    thus ?thesis by iprover\n  next\n    fix y\n    assume xy: \"R x y\"\n    assume yb: \"R\\<^sup>*\\<^sup>* y b\"\n    from xc show ?thesis\n    proof (rule converse_rtranclpE)\n      assume \"x = c\"\n      with xb have \"R\\<^sup>*\\<^sup>* c b\" by simp\n      thus ?thesis by iprover\n    next\n      fix y'\n      assume y'c: \"R\\<^sup>*\\<^sup>* y' c\"\n      assume xy': \"R x y'\"\n      with xy obtain u where u: \"R\\<^sup>*\\<^sup>* y u\" \"R\\<^sup>*\\<^sup>* y' u\"\n        by (blast dest: lc)\n      from yb u y'c show ?thesis\n        by (blast del: rtranclp.rtrancl_refl\n            intro: rtranclp_trans\n            dest: IH [OF conversepI, OF xy] IH [OF conversepI, OF xy'])\n    qed\n  qed\nqed\n\ntext {*\n  Using the coherent logic prover, the proof of the induction step\n  is completely automatic.\n*}\n\nlemma eq_imp_rtranclp: \"x = y \\<Longrightarrow> r\\<^sup>*\\<^sup>* x y\"\n  by simp\n\ntheorem newman'':\n  assumes wf: \"wfP (R\\<inverse>\\<inverse>)\"\n  and lc: \"\\<And>a b c. R a b \\<Longrightarrow> R a c \\<Longrightarrow>\n    \\<exists>d. R\\<^sup>*\\<^sup>* b d \\<and> R\\<^sup>*\\<^sup>* c d\"\n  shows \"\\<And>b c. R\\<^sup>*\\<^sup>* a b \\<Longrightarrow> R\\<^sup>*\\<^sup>* a c \\<Longrightarrow>\n    \\<exists>d. R\\<^sup>*\\<^sup>* b d \\<and> R\\<^sup>*\\<^sup>* c d\"\n  using wf\nproof induct\n  case (less x b c)\n  note IH = `\\<And>y b c. \\<lbrakk>R\\<inverse>\\<inverse> y x; R\\<^sup>*\\<^sup>* y b; R\\<^sup>*\\<^sup>* y c\\<rbrakk>\n                     \\<Longrightarrow> \\<exists>d. R\\<^sup>*\\<^sup>* b d \\<and> R\\<^sup>*\\<^sup>* c d`\n  show ?case\n    by (coherent\n      `R\\<^sup>*\\<^sup>* x c` `R\\<^sup>*\\<^sup>* x b`\n      refl [where 'a='a] sym\n      eq_imp_rtranclp\n      r_into_rtranclp [of R]\n      rtranclp_trans\n      lc IH [OF conversepI]\n      converse_rtranclpE)\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/Proofs/Lambda/Commutation.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382129861583, "lm_q2_score": 0.843895106480586, "lm_q1q2_score": 0.7270478819850478}}
{"text": "theory Ch2InClass\nimports Main\nbegin\n\ndatatype const = IntC int | BoolC bool\n\ndatatype primitive = Inc | Dec | Neg | IsZero | Not\n\ndatatype exp =\n    Const const\n  | Prim primitive exp \n  | IfE exp exp exp\n\nabbreviation ci :: \"int \\<Rightarrow> exp\" where \"ci n \\<equiv> Const (IntC n)\"\nabbreviation cb :: \"bool \\<Rightarrow> exp\" where \"cb b \\<equiv> Const (BoolC b)\"\n\nabbreviation p0 :: exp where \"p0 \\<equiv> ci 42\"\nabbreviation p1 :: exp where \"p1 \\<equiv> Prim Inc (ci 41)\"\nabbreviation p2 :: exp where \"p2 \\<equiv> Prim IsZero (ci 0)\"\nabbreviation p3 :: exp where \"p3 \\<equiv> IfE p2 p1 (ci 0)\"\nabbreviation p4 :: exp where \"p4 \\<equiv> Prim IsZero (ci 1)\"\nabbreviation p5 :: exp where \"p5 \\<equiv> IfE p4 (ci 0) p1\"\nabbreviation p6 :: exp where \"p6 \\<equiv> Prim Not (cb False)\"\n\ndatatype result = Res const | Error\n\nfun eval_prim :: \"primitive \\<Rightarrow> const \\<Rightarrow> result\" where\n  \"eval_prim Inc (IntC n) = Res (IntC (n + 1))\" |\n  \"eval_prim Dec (IntC n) = Res (IntC (n - 1))\" |\n  \"eval_prim Neg (IntC n) = Res (IntC (-n))\" |\n  \"eval_prim IsZero (IntC n) = Res (BoolC (n=0))\" |\n  \"eval_prim Not (BoolC b) = Res (BoolC (\\<not> b))\" |\n  \"eval_prim _ _ = Error\"\n\nprimrec eval :: \"exp \\<Rightarrow> result\" where\n  \"eval (Const c) = Res c\" |\n  \"eval (Prim p e) =\n        (case eval e  of \n          Res c \\<Rightarrow> eval_prim p c\n        | Error \\<Rightarrow> Error)\" |\n  \"eval (IfE e1 e2 e3) =\n        (case eval e1 of\n          Res (BoolC True) \\<Rightarrow> eval e2\n        | Res (BoolC False) \\<Rightarrow> eval e3\n        | _ \\<Rightarrow> Error)\"\n\ntheorem \"eval p0 = Res (IntC 42)\" by simp\ntheorem \"eval p1 = Res (IntC 42)\" by simp\ntheorem \"eval p2 = Res (BoolC True)\" by simp\ntheorem \"eval p3 = Res (IntC 42)\" by simp\ntheorem \"eval p4 = Res (BoolC False)\" by simp\ntheorem \"eval p5 = Res (IntC 42)\" by simp\ntheorem \"eval p6 = Res (BoolC True)\" by simp\n\ndatatype ty = IntT | BoolT\n\nprimrec prim_type :: \"primitive \\<Rightarrow> ty \\<times> ty\" where\n   \"prim_type Inc = (IntT, IntT)\" |\n   \"prim_type Dec = (IntT, IntT)\" |\n   \"prim_type Neg = (IntT, IntT)\" |\n   \"prim_type IsZero = (IntT, BoolT)\" |\n   \"prim_type Not = (BoolT, BoolT)\" \n\nprimrec const_type :: \"const \\<Rightarrow> ty\" where\n  \"const_type (IntC n) = IntT\" |\n  \"const_type (BoolC b) = BoolT\"\n\ninductive well_typed :: \"exp \\<Rightarrow> ty \\<Rightarrow> bool\" (\"\\<turnstile> _ : _\" [60,60] 59) where\n  wt_const[intro!]: \"\\<lbrakk> const_type c = T \\<rbrakk> \\<Longrightarrow> \\<turnstile> Const c : T\" |\n  wt_prim[intro!]: \"\\<lbrakk> \\<turnstile> e : T1; prim_type p = (T1, T2) \\<rbrakk>\n    \\<Longrightarrow> \\<turnstile> Prim p e : T2\" |\n  wt_if[intro!]: \"\\<lbrakk> \\<turnstile> e1 : BoolT; \\<turnstile> e2 : T; \\<turnstile> e3 : T \\<rbrakk>\n    \\<Longrightarrow> \\<turnstile> IfE e1 e2 e3 : T\"\n\ninductive_cases\n  inv_wt_const[elim!]: \"\\<turnstile> Const c : T\" and\n  inv_wt_prim[elim!]: \"\\<turnstile> Prim p e : T\" and\n  inv_wt_if[elim!]: \"\\<turnstile> IfE e1 e2 e3 : T\"\n\ntheorem \"\\<turnstile> p0 : IntT\" by auto\ntheorem \"\\<turnstile> p1 : IntT\" by auto\ntheorem \"\\<turnstile> p2 : BoolT\" by auto\ntheorem \"\\<turnstile> p3 : IntT\" by auto\ntheorem \"\\<turnstile> p4 : BoolT\" by auto\ntheorem \"\\<turnstile> p5 : IntT\" by auto\ntheorem \"\\<turnstile> p6 : BoolT\" by auto\n\nlemma prim_type_safe:\n  assumes pt: \"prim_type p = (T1,T2)\" and wt: \"const_type c = T1\"\n  shows \"\\<exists> c'. eval_prim p c = Res c' \\<and> const_type c' = T2\"\n  using pt wt\n  apply (case_tac p)\n  apply (case_tac c, simp, simp)+\n  done\n\ntheorem type_safety:\nassumes wt: \"\\<turnstile> e : T\" shows \"\\<exists> c. eval e = Res c \\<and> const_type c = T\" (is \"?P e T\")\nusing wt\nproof (induction e T rule: well_typed.induct)\n  case (wt_const c T)\n  from wt_const show \"?P (Const c) T\" by simp\nnext\n  case (wt_prim e T1 p T2)\n  from wt_prim obtain c where ct: \"const_type c = T1\" and\n    ec: \"eval e = Res c\" by blast\n  from wt_prim have pt: \"prim_type p = (T1,T2)\" by simp\n  from pt ct have \"\\<exists> c'. eval_prim p c = Res c' \\<and> const_type c' = T2\"\n    by (rule prim_type_safe)\n  from this obtain c' where ep: \"eval_prim p c = Res c'\"\n    and ct2: \"const_type c' = T2\" by blast\n  from ec ep have 1: \"eval (Prim p e) = Res c'\" by simp\n  from 1 ct2 show \"?P (Prim p e) T2\" by blast\n  oops\n\n\ninductive reduce :: \"exp \\<Rightarrow> exp \\<Rightarrow> bool\" (infix \"\\<longmapsto>\" 70) where\n  r_prim[intro!]: \"\\<lbrakk> eval_prim p c = Res c' \\<rbrakk>\n    \\<Longrightarrow> Prim p (Const c) \\<longmapsto> Const c'\" |\n  c_prim[intro!]: \"\\<lbrakk> e \\<longmapsto> e' \\<rbrakk> \\<Longrightarrow> Prim p e \\<longmapsto> Prim p e'\" |\n  r_if_true[intro!]: \"IfE (cb True) e2 e3 \\<longmapsto> e2\" |\n  r_if_false[intro!]: \"IfE (cb False) e2 e3 \\<longmapsto> e3\" |\n  c_if[intro!]: \"\\<lbrakk> e1 \\<longmapsto> e1' \\<rbrakk> \\<Longrightarrow> IfE e1 e2 e3 \\<longmapsto> IfE e1' e2 e3\"\n\ntheorem \"Prim Inc (Prim Inc (ci 40)) \\<longmapsto> Prim Inc (ci 41)\" by auto\ntheorem \"IfE (cb True) (ci 42) (ci 0) \\<longmapsto> ci 42\" by auto\ntheorem \"IfE (Prim IsZero (ci 1)) (ci 0) (ci 42)\n         \\<longmapsto> IfE (cb False) (ci 0) (ci 42)\" by auto\n\ninductive reduces :: \"exp \\<Rightarrow> exp \\<Rightarrow> bool\" (infix \"\\<longmapsto>*\" 70) where\n red_nil[intro!]: \"e \\<longmapsto>* e\" |\n red_cons[intro!]: \"\\<lbrakk> e1 \\<longmapsto> e2; e2 \\<longmapsto>* e3 \\<rbrakk> \\<Longrightarrow> e1 \\<longmapsto>* e3\"\n\nprimrec exp2res :: \"exp \\<Rightarrow> result\" where\n  \"exp2res (Const c) = Res c\" |\n  \"exp2res (Prim p e) = Error\" |\n  \"exp2res (IfE e1 e2 e3) = Error\"\n\nabbreviation reducible :: \"exp \\<Rightarrow> bool\" where\n  \"reducible e \\<equiv> \\<exists> e'. e \\<longmapsto> e'\"\n \ndefinition eval_red :: \"exp \\<Rightarrow> result \\<Rightarrow> bool\" where\n  \"eval_red e r \\<equiv> \\<exists> e'. e \\<longmapsto>* e'\n      \\<and> \\<not> reducible e' \\<and> exp2res e' = r\"\n\ntheorem \"eval_red (Prim Inc (Prim Inc (ci 0))) (Res (IntC 2))\" \nproof -\n  have 1: \"Prim Inc (Prim Inc (ci 0)) \\<longmapsto> Prim Inc (ci 1)\" by auto\n  have 2: \"Prim Inc (ci 1) \\<longmapsto> ci 2\" by auto\n  from 1 2 have 3: \"Prim Inc (Prim Inc (ci 0)) \\<longmapsto>* ci 2\" by blast\n  have 4: \"exp2res (ci 2) = Res (IntC 2)\" by simp\n  from 3 4 show ?thesis unfolding eval_red_def sorry\nqed\n\nlemma prim_cong: assumes re: \"e \\<longmapsto>* e'\"\nshows \"Prim p e \\<longmapsto>* Prim p e'\"\nusing re by (induction rule: reduces.induct, blast, blast) \n\nlemma if_cong: assumes re: \"e1 \\<longmapsto>* e1'\"\nshows \"IfE e1 e2 e3 \\<longmapsto>* IfE e1' e2 e3\"\nusing re by (induction rule: reduces.induct, blast, blast)\n\nlemma reduces_trans:\nfixes e1::exp and e2::exp and e3::exp\nassumes r12: \"e1 \\<longmapsto>* e2\" and r23: \"e2 \\<longmapsto>* e3\" shows \"e1 \\<longmapsto>* e3\"\nusing r12 r23\nproof (induction arbitrary: e3 rule: reduces.induct)\n  case (red_nil e e3) thus \"e \\<longmapsto>* e3\" by blast\nnext\n  case (red_cons e1 e2 e3 e3')\n  hence \"e1 \\<longmapsto> e2\" and \"e2 \\<longmapsto>* e3'\" by auto\n  thus \"e1 \\<longmapsto>* e3'\" by blast\nqed\n\nlemma eval_reduces:\n  fixes e::exp assumes ev: \"eval e = Res c\" \n  shows \"e \\<longmapsto>* Const c\"\n  using ev\nproof (induction e arbitrary: c)\n  case (Const c')\n  from Const have c: \"c' = c\" by simp\n  have 1: \"Const c \\<longmapsto>* Const c\" by (rule red_nil)\n  from c 1 show \"Const c' \\<longmapsto>* Const c\" by simp\nnext\n  case (Prim p e)\n  from Prim have 1: \"eval (Prim p e) = Res c\" by simp\n  from 1 obtain c' where ec: \"eval e = Res c'\"\n      and ep: \"eval_prim p c' = Res c\"\n    apply simp apply (case_tac \"eval e\") apply auto done\n  from Prim have IH: \"eval e = Res c' \\<Longrightarrow> e \\<longmapsto>* Const c'\" by simp\n  from ec IH have er: \"e \\<longmapsto>* Const c'\" by simp\n  from er have 1: \"Prim p e \\<longmapsto>* Prim p (Const c')\" by (rule prim_cong)\n  from ep have \"Prim p (Const c') \\<longmapsto> Const c\" by blast\n  hence 2: \"Prim p (Const c') \\<longmapsto>* Const c\" by blast\n  from 1 2 show \"Prim p e \\<longmapsto>* Const c\" by (rule reduces_trans)\n  oops\n\n\n\n", "meta": {"author": "keyz", "repo": "OhIsabelle", "sha": "3af467370750c827b0fdd258c60d4088b2565f9c", "save_path": "github-repos/isabelle/keyz-OhIsabelle", "path": "github-repos/isabelle/keyz-OhIsabelle/OhIsabelle-3af467370750c827b0fdd258c60d4088b2565f9c/code-from-class/Ch2InClass.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382165412809, "lm_q2_score": 0.8438950986284991, "lm_q1q2_score": 0.7270478782203255}}
{"text": "(* Title:      Kleene Relation Algebras\n   Author:     Walter Guttmann\n   Maintainer: Walter Guttmann <walter.guttmann at canterbury.ac.nz>\n*)\n\nsection \\<open>Kleene Relation Algebras\\<close>\n\ntext \\<open>\nThis theory combines Kleene algebras with Stone relation algebras.\nRelation algebras with transitive closure have been studied by \\cite{Ng1984}.\nThe weakening to Stone relation algebras allows us to talk about reachability in weighted graphs, for example.\n\nMany results in this theory are used in the correctness proof of Prim's minimum spanning tree algorithm.\nIn particular, they are concerned with the exchange property, preservation of parts of the invariant and with establishing parts of the postcondition.\n\\<close>\n\ntheory Kleene_Relation_Algebras\n\nimports Stone_Relation_Algebras.Relation_Algebras Kleene_Algebras\n\nbegin\n\ntext \\<open>\nWe first note that bounded distributive lattices can be expanded to Kleene algebras by reusing some of the operations.\n\\<close>\n\nsublocale bounded_distrib_lattice < comp_inf: bounded_kleene_algebra where star = \"\\<lambda>x . top\" and one = top and times = inf\n  apply unfold_locales\n  apply (simp add: inf.assoc)\n  apply simp\n  apply simp\n  apply (simp add: le_infI2)\n  apply (simp add: inf_sup_distrib2)\n  apply simp\n  apply simp\n  apply simp\n  apply simp\n  apply simp\n  apply (simp add: inf_sup_distrib1)\n  apply simp\n  apply simp\n  by (simp add: inf_assoc)\n\ntext \\<open>\nWe add the Kleene star operation to each of bounded distributive allegories, pseudocomplemented distributive allegories and Stone relation algebras.\nWe start with single-object bounded distributive allegories.\n\\<close>\n\nclass bounded_distrib_kleene_allegory = bounded_distrib_allegory + kleene_algebra\nbegin\n\nsubclass bounded_kleene_algebra ..\n\nlemma conv_star_conv:\n  \"x\\<^sup>\\<star> \\<le> x\\<^sup>T\\<^sup>\\<star>\\<^sup>T\"\nproof -\n  have \"x\\<^sup>T\\<^sup>\\<star> * x\\<^sup>T \\<le> x\\<^sup>T\\<^sup>\\<star>\"\n    by (simp add: star.right_plus_below_circ)\n  hence 1: \"x * x\\<^sup>T\\<^sup>\\<star>\\<^sup>T \\<le> x\\<^sup>T\\<^sup>\\<star>\\<^sup>T\"\n    using conv_dist_comp conv_isotone by fastforce\n  have \"1 \\<le> x\\<^sup>T\\<^sup>\\<star>\\<^sup>T\"\n    by (simp add: reflexive_conv_closed star.circ_reflexive)\n  hence \"1 \\<squnion> x * x\\<^sup>T\\<^sup>\\<star>\\<^sup>T \\<le> x\\<^sup>T\\<^sup>\\<star>\\<^sup>T\"\n    using 1 by simp\n  thus ?thesis\n    using star_left_induct by fastforce\nqed\n\ntext \\<open>\nIt follows that star and converse commute.\n\\<close>\n\nlemma conv_star_commute:\n  \"x\\<^sup>\\<star>\\<^sup>T = x\\<^sup>T\\<^sup>\\<star>\"\nproof (rule antisym)\n  show \"x\\<^sup>\\<star>\\<^sup>T \\<le> x\\<^sup>T\\<^sup>\\<star>\"\n    using conv_star_conv conv_isotone by fastforce\nnext\n  show \"x\\<^sup>T\\<^sup>\\<star> \\<le> x\\<^sup>\\<star>\\<^sup>T\"\n    by (metis conv_star_conv conv_involutive)\nqed\n\nlemma conv_plus_commute:\n  \"x\\<^sup>+\\<^sup>T = x\\<^sup>T\\<^sup>+\"\n  by (simp add: conv_dist_comp conv_star_commute star_plus)\n\nlemma reflexive_inf_star:\n  assumes \"reflexive y\"\n    shows \"y \\<sqinter> x\\<^sup>\\<star> = 1 \\<squnion> (y \\<sqinter> x\\<^sup>+)\"\n  by (simp add: assms star_left_unfold_equal sup.absorb2 sup_inf_distrib1)\n\ntext \\<open>\nThe following results are variants of a separation lemma of Kleene algebras.\n\\<close>\n\nlemma cancel_separate_2:\n  assumes \"x * y \\<le> 1\"\n    shows \"((w \\<sqinter> x) \\<squnion> (z \\<sqinter> y))\\<^sup>\\<star> = (z \\<sqinter> y)\\<^sup>\\<star> * (w \\<sqinter> x)\\<^sup>\\<star>\"\nproof -\n  have \"(w \\<sqinter> x) * (z \\<sqinter> y) \\<le> 1\"\n    by (meson assms comp_isotone order.trans inf.cobounded2)\n  thus ?thesis\n    using cancel_separate_1 sup_commute by simp\nqed\n\nlemma cancel_separate_3:\n  assumes \"x * y \\<le> 1\"\n    shows \"(w \\<sqinter> x)\\<^sup>\\<star> * (z \\<sqinter> y)\\<^sup>\\<star> = (w \\<sqinter> x)\\<^sup>\\<star> \\<squnion> (z \\<sqinter> y)\\<^sup>\\<star>\"\nproof -\n  have \"(w \\<sqinter> x) * (z \\<sqinter> y) \\<le> 1\"\n    by (meson assms comp_isotone order.trans inf.cobounded2)\n  thus ?thesis\n    by (simp add: cancel_separate_eq)\nqed\n\nlemma cancel_separate_4:\n  assumes \"z * y \\<le> 1\"\n      and \"w \\<le> y \\<squnion> z\"\n      and \"x \\<le> y \\<squnion> z\"\n    shows \"w\\<^sup>\\<star> * x\\<^sup>\\<star> = (w \\<sqinter> y)\\<^sup>\\<star> * ((w \\<sqinter> z)\\<^sup>\\<star> \\<squnion> (x \\<sqinter> y)\\<^sup>\\<star>) * (x \\<sqinter> z)\\<^sup>\\<star>\"\nproof -\n  have \"w\\<^sup>\\<star> * x\\<^sup>\\<star> = ((w \\<sqinter> y) \\<squnion> (w \\<sqinter> z))\\<^sup>\\<star> * ((x \\<sqinter> y) \\<squnion> (x \\<sqinter> z))\\<^sup>\\<star>\"\n    by (metis assms(2,3) inf.orderE inf_sup_distrib1)\n  also have \"... = (w \\<sqinter> y)\\<^sup>\\<star> * ((w \\<sqinter> z)\\<^sup>\\<star> * (x \\<sqinter> y)\\<^sup>\\<star>) * (x \\<sqinter> z)\\<^sup>\\<star>\"\n    by (metis assms(1) cancel_separate_2 sup_commute mult_assoc)\n  finally show ?thesis\n    by (simp add: assms(1) cancel_separate_3)\nqed\n\nlemma cancel_separate_5:\n  assumes \"w * z\\<^sup>T \\<le> 1\"\n    shows \"w \\<sqinter> x * (y \\<sqinter> z) \\<le> y\"\nproof -\n  have \"w \\<sqinter> x * (y \\<sqinter> z) \\<le> (x \\<sqinter> w * (y \\<sqinter> z)\\<^sup>T) * (y \\<sqinter> z)\"\n    by (metis dedekind_2 inf_commute)\n  also have \"... \\<le> w * z\\<^sup>T * (y \\<sqinter> z)\"\n    by (simp add: conv_dist_inf inf.coboundedI2 mult_left_isotone mult_right_isotone)\n  also have \"... \\<le> y \\<sqinter> z\"\n    by (metis assms mult_1_left mult_left_isotone)\n  finally show ?thesis\n    by simp\nqed\n\nlemma cancel_separate_6:\n  assumes \"z * y \\<le> 1\"\n      and \"w \\<le> y \\<squnion> z\"\n      and \"x \\<le> y \\<squnion> z\"\n      and \"v * z\\<^sup>T \\<le> 1\"\n      and \"v \\<sqinter> y\\<^sup>\\<star> = bot\"\n    shows \"v \\<sqinter> w\\<^sup>\\<star> * x\\<^sup>\\<star> \\<le> x \\<squnion> w\"\nproof -\n  have \"v \\<sqinter> (w \\<sqinter> y)\\<^sup>\\<star> * (x \\<sqinter> y)\\<^sup>\\<star> \\<le> v \\<sqinter> y\\<^sup>\\<star> * (x \\<sqinter> y)\\<^sup>\\<star>\"\n    using comp_inf.mult_right_isotone mult_left_isotone star_isotone by simp\n  also have \"... \\<le> v \\<sqinter> y\\<^sup>\\<star>\"\n    by (simp add: inf.coboundedI2 star.circ_increasing star.circ_mult_upper_bound star_right_induct_mult)\n  finally have 1: \"v \\<sqinter> (w \\<sqinter> y)\\<^sup>\\<star> * (x \\<sqinter> y)\\<^sup>\\<star> = bot\"\n    using assms(5) le_bot by simp\n  have \"v \\<sqinter> w\\<^sup>\\<star> * x\\<^sup>\\<star> = v \\<sqinter> (w \\<sqinter> y)\\<^sup>\\<star> * ((w \\<sqinter> z)\\<^sup>\\<star> \\<squnion> (x \\<sqinter> y)\\<^sup>\\<star>) * (x \\<sqinter> z)\\<^sup>\\<star>\"\n    using assms(1-3) cancel_separate_4 by simp\n  also have \"... = (v \\<sqinter> (w \\<sqinter> y)\\<^sup>\\<star> * ((w \\<sqinter> z)\\<^sup>\\<star> \\<squnion> (x \\<sqinter> y)\\<^sup>\\<star>) * (x \\<sqinter> z)\\<^sup>\\<star> * (x \\<sqinter> z)) \\<squnion> (v \\<sqinter> (w \\<sqinter> y)\\<^sup>\\<star> * ((w \\<sqinter> z)\\<^sup>\\<star> \\<squnion> (x \\<sqinter> y)\\<^sup>\\<star>))\"\n    by (metis inf_sup_distrib1 star.circ_back_loop_fixpoint)\n  also have \"... \\<le> x \\<squnion> (v \\<sqinter> (w \\<sqinter> y)\\<^sup>\\<star> * ((w \\<sqinter> z)\\<^sup>\\<star> \\<squnion> (x \\<sqinter> y)\\<^sup>\\<star>))\"\n    using assms(4) cancel_separate_5 semiring.add_right_mono by simp\n  also have \"... = x \\<squnion> (v \\<sqinter> (w \\<sqinter> y)\\<^sup>\\<star> * (w \\<sqinter> z)\\<^sup>\\<star>)\"\n    using 1 by (simp add: inf_sup_distrib1 mult_left_dist_sup sup_monoid.add_assoc)\n  also have \"... = x \\<squnion> (v \\<sqinter> (w \\<sqinter> y)\\<^sup>\\<star> * (w \\<sqinter> z)\\<^sup>\\<star> * (w \\<sqinter> z)) \\<squnion> (v \\<sqinter> (w \\<sqinter> y)\\<^sup>\\<star>)\"\n    by (metis comp_inf.semiring.distrib_left star.circ_back_loop_fixpoint sup_assoc)\n  also have \"... \\<le> x \\<squnion> w \\<squnion> (v \\<sqinter> (w \\<sqinter> y)\\<^sup>\\<star>)\"\n    using assms(4) cancel_separate_5 sup_left_isotone sup_right_isotone by simp\n  also have \"... \\<le> x \\<squnion> w \\<squnion> (v \\<sqinter> y\\<^sup>\\<star>)\"\n    using comp_inf.mult_right_isotone star_isotone sup_right_isotone by simp\n  finally show ?thesis\n    using assms(5) le_bot by simp\nqed\n\ntext \\<open>\nWe show several results about the interaction of vectors and the Kleene star.\n\\<close>\n\nlemma vector_star_1:\n  assumes \"vector x\"\n    shows \"x\\<^sup>T * (x * x\\<^sup>T)\\<^sup>\\<star> \\<le> x\\<^sup>T\"\nproof -\n  have \"x\\<^sup>T * (x * x\\<^sup>T)\\<^sup>\\<star> = (x\\<^sup>T * x)\\<^sup>\\<star> * x\\<^sup>T\"\n    by (simp add: star_slide)\n  also have \"... \\<le> top * x\\<^sup>T\"\n    by (simp add: mult_left_isotone)\n  also have \"... = x\\<^sup>T\"\n    using assms vector_conv_covector by auto\n  finally show ?thesis\n    .\nqed\n\nlemma vector_star_2:\n  \"vector x \\<Longrightarrow> x\\<^sup>T * (x * x\\<^sup>T)\\<^sup>\\<star> \\<le> x\\<^sup>T * bot\\<^sup>\\<star>\"\n  by (simp add: star_absorb vector_star_1)\n\nlemma vector_vector_star:\n  \"vector v \\<Longrightarrow> (v * v\\<^sup>T)\\<^sup>\\<star> = 1 \\<squnion> v * v\\<^sup>T\"\n  by (simp add: transitive_star vv_transitive)\n\ntext \\<open>\nThe following equivalence relation characterises the component trees of a forest.\nThis is a special case of undirected reachability in a directed graph.\n\\<close>\n\nabbreviation \"forest_components f \\<equiv> f\\<^sup>T\\<^sup>\\<star> * f\\<^sup>\\<star>\"\n\nlemma forest_components_equivalence:\n  \"injective x \\<Longrightarrow> equivalence (forest_components x)\"\n  apply (intro conjI)\n  apply (simp add: reflexive_mult_closed star.circ_reflexive)\n  apply (metis cancel_separate_1 eq_iff star.circ_transitive_equal)\n  by (simp add: conv_dist_comp conv_star_commute)\n\nlemma forest_components_increasing:\n  \"x \\<le> forest_components x\"\n  by (metis order.trans mult_left_isotone mult_left_one star.circ_increasing star.circ_reflexive)\n\nlemma forest_components_isotone:\n  \"x \\<le> y \\<Longrightarrow> forest_components x \\<le> forest_components y\"\n  by (simp add: comp_isotone conv_isotone star_isotone)\n\nlemma forest_components_idempotent:\n  \"injective x \\<Longrightarrow> forest_components (forest_components x) = forest_components x\"\n  by (metis forest_components_equivalence cancel_separate_1 star.circ_transitive_equal star_involutive)\n\nlemma forest_components_star:\n  \"injective x \\<Longrightarrow> (forest_components x)\\<^sup>\\<star> = forest_components x\"\n  using forest_components_equivalence forest_components_idempotent star.circ_transitive_equal by simp\n\ntext \\<open>\nThe following lemma shows that the nodes reachable in the graph can be reached by only using edges between reachable nodes.\n\\<close>\n\nlemma reachable_restrict:\n  assumes \"vector r\"\n    shows \"r\\<^sup>T * g\\<^sup>\\<star> = r\\<^sup>T * ((r\\<^sup>T * g\\<^sup>\\<star>)\\<^sup>T * (r\\<^sup>T * g\\<^sup>\\<star>) \\<sqinter> g)\\<^sup>\\<star>\"\nproof -\n  have 1: \"r\\<^sup>T \\<le> r\\<^sup>T * ((r\\<^sup>T * g\\<^sup>\\<star>)\\<^sup>T * (r\\<^sup>T * g\\<^sup>\\<star>) \\<sqinter> g)\\<^sup>\\<star>\"\n    using mult_right_isotone mult_1_right star.circ_reflexive by fastforce\n  have 2: \"covector (r\\<^sup>T * g\\<^sup>\\<star>)\"\n    using assms covector_mult_closed vector_conv_covector by auto\n  have \"r\\<^sup>T * ((r\\<^sup>T * g\\<^sup>\\<star>)\\<^sup>T * (r\\<^sup>T * g\\<^sup>\\<star>) \\<sqinter> g)\\<^sup>\\<star> * g \\<le> r\\<^sup>T * g\\<^sup>\\<star> * g\"\n    by (simp add: mult_left_isotone mult_right_isotone star_isotone)\n  also have \"... \\<le> r\\<^sup>T * g\\<^sup>\\<star>\"\n    by (simp add: mult_assoc mult_right_isotone star.left_plus_below_circ star_plus)\n  finally have \"r\\<^sup>T * ((r\\<^sup>T * g\\<^sup>\\<star>)\\<^sup>T * (r\\<^sup>T * g\\<^sup>\\<star>) \\<sqinter> g)\\<^sup>\\<star> * g = r\\<^sup>T * ((r\\<^sup>T * g\\<^sup>\\<star>)\\<^sup>T * (r\\<^sup>T * g\\<^sup>\\<star>) \\<sqinter> g)\\<^sup>\\<star> * g \\<sqinter> r\\<^sup>T * g\\<^sup>\\<star>\"\n    by (simp add: le_iff_inf)\n  also have \"... = r\\<^sup>T * ((r\\<^sup>T * g\\<^sup>\\<star>)\\<^sup>T * (r\\<^sup>T * g\\<^sup>\\<star>) \\<sqinter> g)\\<^sup>\\<star> * (g \\<sqinter> r\\<^sup>T * g\\<^sup>\\<star>)\"\n    using assms covector_comp_inf covector_mult_closed vector_conv_covector by auto\n  also have \"... = (r\\<^sup>T * ((r\\<^sup>T * g\\<^sup>\\<star>)\\<^sup>T * (r\\<^sup>T * g\\<^sup>\\<star>) \\<sqinter> g)\\<^sup>\\<star> \\<sqinter> r\\<^sup>T * g\\<^sup>\\<star>) * (g \\<sqinter> r\\<^sup>T * g\\<^sup>\\<star>)\"\n    by (simp add: inf.absorb2 inf_commute mult_right_isotone star_isotone)\n  also have \"... = r\\<^sup>T * ((r\\<^sup>T * g\\<^sup>\\<star>)\\<^sup>T * (r\\<^sup>T * g\\<^sup>\\<star>) \\<sqinter> g)\\<^sup>\\<star> * (g \\<sqinter> r\\<^sup>T * g\\<^sup>\\<star> \\<sqinter> (r\\<^sup>T * g\\<^sup>\\<star>)\\<^sup>T)\"\n    using 2 by (metis comp_inf_vector_1)\n  also have \"... = r\\<^sup>T * ((r\\<^sup>T * g\\<^sup>\\<star>)\\<^sup>T * (r\\<^sup>T * g\\<^sup>\\<star>) \\<sqinter> g)\\<^sup>\\<star> * ((r\\<^sup>T * g\\<^sup>\\<star>)\\<^sup>T \\<sqinter> r\\<^sup>T * g\\<^sup>\\<star> \\<sqinter> g)\"\n    using inf_commute inf_assoc by simp\n  also have \"... = r\\<^sup>T * ((r\\<^sup>T * g\\<^sup>\\<star>)\\<^sup>T * (r\\<^sup>T * g\\<^sup>\\<star>) \\<sqinter> g)\\<^sup>\\<star> * ((r\\<^sup>T * g\\<^sup>\\<star>)\\<^sup>T * (r\\<^sup>T * g\\<^sup>\\<star>) \\<sqinter> g)\"\n    using 2 by (metis covector_conv_vector inf_top.right_neutral vector_inf_comp)\n  also have \"... \\<le> r\\<^sup>T * ((r\\<^sup>T * g\\<^sup>\\<star>)\\<^sup>T * (r\\<^sup>T * g\\<^sup>\\<star>) \\<sqinter> g)\\<^sup>\\<star>\"\n    by (simp add: mult_assoc mult_right_isotone star.left_plus_below_circ star_plus)\n  finally have \"r\\<^sup>T * g\\<^sup>\\<star> \\<le> r\\<^sup>T * ((r\\<^sup>T * g\\<^sup>\\<star>)\\<^sup>T * (r\\<^sup>T * g\\<^sup>\\<star>) \\<sqinter> g)\\<^sup>\\<star>\"\n    using 1 star_right_induct by auto\n  thus ?thesis\n    by (simp add: inf.eq_iff mult_right_isotone star_isotone)\nqed\n\nlemma kruskal_acyclic_inv_1:\n  assumes \"injective f\"\n      and \"e * forest_components f * e = bot\"\n    shows \"(f \\<sqinter> top * e * f\\<^sup>T\\<^sup>\\<star>)\\<^sup>T * f\\<^sup>\\<star> * e = bot\"\nproof -\n  let ?q = \"top * e * f\\<^sup>T\\<^sup>\\<star>\"\n  let ?F = \"forest_components f\"\n  have \"(f \\<sqinter> ?q)\\<^sup>T * f\\<^sup>\\<star> * e = ?q\\<^sup>T \\<sqinter> f\\<^sup>T * f\\<^sup>\\<star> * e\"\n    by (metis (mono_tags) comp_associative conv_dist_inf covector_conv_vector inf_vector_comp vector_top_closed)\n  also have \"... \\<le> ?q\\<^sup>T \\<sqinter> ?F * e\"\n    using comp_inf.mult_right_isotone mult_left_isotone star.circ_increasing by simp\n  also have \"... = f\\<^sup>\\<star> * e\\<^sup>T * top \\<sqinter> ?F * e\"\n    by (simp add: conv_dist_comp conv_star_commute mult_assoc)\n  also have \"... \\<le> ?F * e\\<^sup>T * top \\<sqinter> ?F * e\"\n    by (metis conv_dist_comp conv_star_commute conv_top inf.sup_left_isotone star.circ_right_top star_outer_increasing mult_assoc)\n  also have \"... = ?F * (e\\<^sup>T * top \\<sqinter> ?F * e)\"\n    by (metis assms(1) forest_components_equivalence equivalence_comp_dist_inf mult_assoc)\n  also have \"... = (?F \\<sqinter> top * e) * ?F * e\"\n    by (simp add: comp_associative comp_inf_vector_1 conv_dist_comp inf_vector_comp)\n  also have \"... \\<le> top * e * ?F * e\"\n    by (simp add: mult_left_isotone)\n  also have \"... = bot\"\n    using assms(2) mult_assoc by simp\n  finally show ?thesis\n    by (simp add: bot_unique)\nqed\n\nlemma kruskal_forest_components_inf_1:\n  assumes \"f \\<le> w \\<squnion> w\\<^sup>T\"\n      and \"injective w\"\n      and \"f \\<le> forest_components g\"\n    shows \"f * forest_components (forest_components g \\<sqinter> w) \\<le> forest_components (forest_components g \\<sqinter> w)\"\nproof -\n  let ?f = \"forest_components g\"\n  let ?w = \"forest_components (?f \\<sqinter> w)\"\n  have \"f * ?w = (f \\<sqinter> (w \\<squnion> w\\<^sup>T)) * ?w\"\n    by (simp add: assms(1) inf.absorb1)\n  also have \"... = (f \\<sqinter> w) * ?w \\<squnion> (f \\<sqinter> w\\<^sup>T) * ?w\"\n    by (simp add: inf_sup_distrib1 semiring.distrib_right)\n  also have \"... \\<le> (?f \\<sqinter> w) * ?w \\<squnion> (f \\<sqinter> w\\<^sup>T) * ?w\"\n    using assms(3) inf.sup_left_isotone mult_left_isotone sup_left_isotone by simp\n  also have \"... \\<le> (?f \\<sqinter> w) * ?w \\<squnion> (?f \\<sqinter> w\\<^sup>T) * ?w\"\n    using assms(3) inf.sup_left_isotone mult_left_isotone sup_right_isotone by simp\n  also have \"... = (?f \\<sqinter> w) * ?w \\<squnion> (?f \\<sqinter> w)\\<^sup>T * ?w\"\n    by (simp add: conv_dist_comp conv_dist_inf conv_star_commute)\n  also have \"... \\<le> (?f \\<sqinter> w) * ?w \\<squnion> ?w\"\n    by (metis star.circ_loop_fixpoint sup_ge1 sup_right_isotone)\n  also have \"... = ?w \\<squnion> (?f \\<sqinter> w) * (?f \\<sqinter> w)\\<^sup>\\<star> \\<squnion> (?f \\<sqinter> w) * (?f \\<sqinter> w)\\<^sup>T\\<^sup>+ * (?f \\<sqinter> w)\\<^sup>\\<star>\"\n    by (metis comp_associative mult_left_dist_sup star.circ_loop_fixpoint sup_commute sup_assoc)\n  also have \"... \\<le> ?w \\<squnion> (?f \\<sqinter> w)\\<^sup>\\<star> \\<squnion> (?f \\<sqinter> w) * (?f \\<sqinter> w)\\<^sup>T\\<^sup>+ * (?f \\<sqinter> w)\\<^sup>\\<star>\"\n    using star.left_plus_below_circ sup_left_isotone sup_right_isotone by auto\n  also have \"... = ?w \\<squnion> (?f \\<sqinter> w) * (?f \\<sqinter> w)\\<^sup>T\\<^sup>+ * (?f \\<sqinter> w)\\<^sup>\\<star>\"\n    by (metis star.circ_loop_fixpoint sup.right_idem)\n  also have \"... \\<le> ?w \\<squnion> w * w\\<^sup>T * ?w\"\n    using comp_associative conv_dist_inf mult_isotone sup_right_isotone by simp\n  also have \"... = ?w\"\n    by (metis assms(2) coreflexive_comp_top_inf inf.cobounded2 sup.orderE)\n  finally show ?thesis\n    by simp\nqed\n\nlemma kruskal_forest_components_inf:\n  assumes \"f \\<le> w \\<squnion> w\\<^sup>T\"\n      and \"injective w\"\n    shows \"forest_components f \\<le> forest_components (forest_components f \\<sqinter> w)\"\nproof -\n  let ?f = \"forest_components f\"\n  let ?w = \"forest_components (?f \\<sqinter> w)\"\n  have 1: \"1 \\<le> ?w\"\n    by (simp add: reflexive_mult_closed star.circ_reflexive)\n  have \"f * ?w \\<le> ?w\"\n    using assms forest_components_increasing kruskal_forest_components_inf_1 by simp\n  hence 2: \"f\\<^sup>\\<star> \\<le> ?w\"\n    using 1 star_left_induct by fastforce\n  have \"f\\<^sup>T * ?w \\<le> ?w\"\n    apply (rule kruskal_forest_components_inf_1)\n    apply (metis assms(1) conv_dist_sup conv_involutive conv_isotone sup_commute)\n    apply (simp add: assms(2))\n    by (metis le_supI2 star.circ_back_loop_fixpoint star.circ_increasing)\n  thus \"?f \\<le> ?w\"\n    using 2 star_left_induct by simp\nqed\n\nend\n\ntext \\<open>\nWe next add the Kleene star to single-object pseudocomplemented distributive allegories.\n\\<close>\n\nclass pd_kleene_allegory = pd_allegory + bounded_distrib_kleene_allegory\nbegin\n\ntext \\<open>\nThe following definitions and results concern acyclic graphs and forests.\n\\<close>\n\nabbreviation acyclic :: \"'a \\<Rightarrow> bool\" where \"acyclic x \\<equiv> x\\<^sup>+ \\<le> -1\"\n\nabbreviation forest :: \"'a \\<Rightarrow> bool\" where \"forest x \\<equiv> injective x \\<and> acyclic x\"\n\nlemma forest_bot:\n  \"forest bot\"\n  by simp\n\nlemma acyclic_star_below_complement:\n  \"acyclic w \\<longleftrightarrow> w\\<^sup>T\\<^sup>\\<star> \\<le> -w\"\n  by (simp add: conv_star_commute schroeder_4_p)\n\nlemma acyclic_star_below_complement_1:\n  \"acyclic w \\<longleftrightarrow> w\\<^sup>\\<star> \\<sqinter> w\\<^sup>T = bot\"\n  using pseudo_complement schroeder_5_p by force\n\nlemma acyclic_star_inf_conv:\n  assumes \"acyclic w\"\n  shows \"w\\<^sup>\\<star> \\<sqinter> w\\<^sup>T\\<^sup>\\<star> = 1\"\nproof -\n  have \"w\\<^sup>+ \\<sqinter> w\\<^sup>T\\<^sup>\\<star> \\<le> (w \\<sqinter> w\\<^sup>T\\<^sup>\\<star>) * w\\<^sup>\\<star>\"\n    by (metis conv_star_commute dedekind_2 star.circ_transitive_equal)\n  also have \"... = bot\"\n    by (metis assms conv_star_commute p_antitone_iff pseudo_complement schroeder_4_p semiring.mult_not_zero star.circ_circ_mult star_involutive star_one)\n  finally have \"w\\<^sup>\\<star> \\<sqinter> w\\<^sup>T\\<^sup>\\<star> \\<le> 1\"\n    by (metis eq_iff le_bot mult_left_zero star.circ_plus_one star.circ_zero star_left_unfold_equal sup_inf_distrib1)\n  thus ?thesis\n    by (simp add: inf.antisym star.circ_reflexive)\nqed\n\nlemma acyclic_asymmetric:\n  \"acyclic w \\<Longrightarrow> asymmetric w\"\n  by (simp add: dual_order.trans pseudo_complement schroeder_5_p star.circ_increasing)\n\nlemma forest_separate:\n  assumes \"forest x\"\n    shows \"x\\<^sup>\\<star> * x\\<^sup>T\\<^sup>\\<star> \\<sqinter> x\\<^sup>T * x \\<le> 1\"\nproof -\n  have \"x\\<^sup>\\<star> * 1 \\<le> -x\\<^sup>T\"\n    using assms schroeder_5_p by force\n  hence 1: \"x\\<^sup>\\<star> \\<sqinter> x\\<^sup>T = bot\"\n    by (simp add: pseudo_complement)\n  have \"x\\<^sup>\\<star> \\<sqinter> x\\<^sup>T * x = (1 \\<squnion> x\\<^sup>\\<star> * x) \\<sqinter> x\\<^sup>T * x\"\n    using star.circ_right_unfold_1 by simp\n  also have \"... = (1 \\<sqinter> x\\<^sup>T * x) \\<squnion> (x\\<^sup>\\<star> * x \\<sqinter> x\\<^sup>T * x)\"\n    by (simp add: inf_sup_distrib2)\n  also have \"... \\<le> 1 \\<squnion> (x\\<^sup>\\<star> * x \\<sqinter> x\\<^sup>T * x)\"\n    using sup_left_isotone by simp\n  also have \"... = 1 \\<squnion> (x\\<^sup>\\<star> \\<sqinter> x\\<^sup>T) * x\"\n    by (simp add: assms injective_comp_right_dist_inf)\n  also have \"... = 1\"\n    using 1 by simp\n  finally have 2: \"x\\<^sup>\\<star> \\<sqinter> x\\<^sup>T * x \\<le> 1\"\n    .\n  hence 3: \"x\\<^sup>T\\<^sup>\\<star> \\<sqinter> x\\<^sup>T * x \\<le> 1\"\n    by (metis (mono_tags, lifting) conv_star_commute conv_dist_comp conv_dist_inf conv_involutive coreflexive_symmetric)\n  have \"x\\<^sup>\\<star> * x\\<^sup>T\\<^sup>\\<star> \\<sqinter> x\\<^sup>T * x \\<le> (x\\<^sup>\\<star> \\<squnion> x\\<^sup>T\\<^sup>\\<star>) \\<sqinter> x\\<^sup>T * x\"\n    using assms cancel_separate inf.sup_left_isotone by simp\n  also have \"... \\<le> 1\"\n    using 2 3 by (simp add: inf_sup_distrib2)\n  finally show ?thesis\n    .\nqed\n\ntext \\<open>\nThe following definition captures the components of undirected weighted graphs.\n\\<close>\n\nabbreviation \"components g \\<equiv> (--g)\\<^sup>\\<star>\"\n\nlemma components_equivalence:\n  \"symmetric x \\<Longrightarrow> equivalence (components x)\"\n  by (simp add: conv_star_commute conv_complement star.circ_reflexive star.circ_transitive_equal)\n\nlemma components_increasing:\n  \"x \\<le> components x\"\n  using order_trans pp_increasing star.circ_increasing by blast\n\nlemma components_isotone:\n  \"x \\<le> y \\<Longrightarrow> components x \\<le> components y\"\n  by (simp add: pp_isotone star_isotone)\n\nlemma cut_reachable:\n  assumes \"v\\<^sup>T = r\\<^sup>T * t\\<^sup>\\<star>\"\n      and \"t \\<le> g\"\n    shows \"v * -v\\<^sup>T \\<sqinter> g \\<le> (r\\<^sup>T * g\\<^sup>\\<star>)\\<^sup>T * (r\\<^sup>T * g\\<^sup>\\<star>)\"\nproof -\n  have \"v * -v\\<^sup>T \\<sqinter> g \\<le> v * top \\<sqinter> g\"\n    using inf.sup_left_isotone mult_right_isotone top_greatest by blast\n  also have \"... = (r\\<^sup>T * t\\<^sup>\\<star>)\\<^sup>T * top \\<sqinter> g\"\n    by (metis assms(1) conv_involutive)\n  also have \"... \\<le> (r\\<^sup>T * g\\<^sup>\\<star>)\\<^sup>T * top \\<sqinter> g\"\n    using assms(2) conv_isotone inf.sup_left_isotone mult_left_isotone mult_right_isotone star_isotone by auto\n  also have \"... \\<le> (r\\<^sup>T * g\\<^sup>\\<star>)\\<^sup>T * ((r\\<^sup>T * g\\<^sup>\\<star>) * g)\"\n    by (metis conv_involutive dedekind_1 inf_top.left_neutral)\n  also have \"... \\<le> (r\\<^sup>T * g\\<^sup>\\<star>)\\<^sup>T * (r\\<^sup>T * g\\<^sup>\\<star>)\"\n    by (simp add: mult_assoc mult_right_isotone star.left_plus_below_circ star_plus)\n  finally show ?thesis\n    .\nqed\n\ntext \\<open>\nThe following lemma shows that the predecessors of visited nodes in the minimum spanning tree extending the current tree have all been visited.\n\\<close>\n\nlemma predecessors_reachable:\n  assumes \"vector r\"\n      and \"injective r\"\n      and \"v\\<^sup>T = r\\<^sup>T * t\\<^sup>\\<star>\"\n      and \"forest w\"\n      and \"t \\<le> w\"\n      and \"w \\<le> (r\\<^sup>T * g\\<^sup>\\<star>)\\<^sup>T * (r\\<^sup>T * g\\<^sup>\\<star>) \\<sqinter> g\"\n      and \"r\\<^sup>T * g\\<^sup>\\<star> \\<le> r\\<^sup>T * w\\<^sup>\\<star>\"\n    shows \"w * v \\<le> v\"\nproof -\n  have \"w * r \\<le> (r\\<^sup>T * g\\<^sup>\\<star>)\\<^sup>T * (r\\<^sup>T * g\\<^sup>\\<star>) * r\"\n    using assms(6) mult_left_isotone by auto\n  also have \"... \\<le> (r\\<^sup>T * g\\<^sup>\\<star>)\\<^sup>T * top\"\n    by (simp add: mult_assoc mult_right_isotone)\n  also have \"... = (r\\<^sup>T * g\\<^sup>\\<star>)\\<^sup>T\"\n    by (simp add: assms(1) comp_associative conv_dist_comp)\n  also have \"... \\<le> (r\\<^sup>T * w\\<^sup>\\<star>)\\<^sup>T\"\n    by (simp add: assms(7) conv_isotone)\n  also have \"... = w\\<^sup>T\\<^sup>\\<star> * r\"\n    by (simp add: conv_dist_comp conv_star_commute)\n  also have \"... \\<le> -w * r\"\n    using assms(4) by (simp add: mult_left_isotone acyclic_star_below_complement)\n  also have \"... \\<le> -(w * r)\"\n    by (simp add: assms(2) comp_injective_below_complement)\n  finally have 1: \"w * r = bot\"\n    by (simp add: le_iff_inf)\n  have \"v = t\\<^sup>T\\<^sup>\\<star> * r\"\n    by (metis assms(3) conv_dist_comp conv_involutive conv_star_commute)\n  also have \"... = t\\<^sup>T * v \\<squnion> r\"\n    by (simp add: calculation star.circ_loop_fixpoint)\n  also have \"... \\<le> w\\<^sup>T * v \\<squnion> r\"\n    using assms(5) comp_isotone conv_isotone semiring.add_right_mono by auto\n  finally have \"w * v \\<le> w * w\\<^sup>T * v \\<squnion> w * r\"\n    by (simp add: comp_left_dist_sup mult_assoc mult_right_isotone)\n  also have \"... = w * w\\<^sup>T * v\"\n    using 1 by simp\n  also have \"... \\<le> v\"\n    using assms(4) by (simp add: star_left_induct_mult_iff star_sub_one)\n  finally show ?thesis\n    .\nqed\n\nsubsection \\<open>Prim's Algorithm\\<close>\n\ntext \\<open>\nThe following results are used for proving the correctness of Prim's minimum spanning tree algorithm.\n\\<close>\n\nsubsubsection \\<open>Preservation of Invariant\\<close>\n\ntext \\<open>\nWe first treat the preservation of the invariant.\nThe following lemma shows that the while-loop preserves that \\<open>v\\<close> represents the nodes of the constructed tree.\nThe remaining lemmas in this section show that \\<open>t\\<close> is a spanning tree.\nThe exchange property is treated in the following two sections.\n\\<close>\n\nlemma reachable_inv:\n  assumes \"vector v\"\n      and \"e \\<le> v * -v\\<^sup>T\"\n      and \"e * t = bot\"\n      and \"v\\<^sup>T = r\\<^sup>T * t\\<^sup>\\<star>\"\n    shows \"(v \\<squnion> e\\<^sup>T * top)\\<^sup>T = r\\<^sup>T * (t \\<squnion> e)\\<^sup>\\<star>\"\nproof -\n  have 1: \"v\\<^sup>T \\<le> r\\<^sup>T * (t \\<squnion> e)\\<^sup>\\<star>\"\n    by (simp add: assms(4) mult_right_isotone star.circ_sub_dist)\n  have 2: \"(e\\<^sup>T * top)\\<^sup>T = top * e\"\n    by (simp add: conv_dist_comp)\n  also have \"... = top * (v * -v\\<^sup>T \\<sqinter> e)\"\n    by (simp add: assms(2) inf_absorb2)\n  also have \"... \\<le> top * (v * top \\<sqinter> e)\"\n    using inf.sup_left_isotone mult_right_isotone top_greatest by blast\n  also have \"... = top * v\\<^sup>T * e\"\n    by (simp add: comp_inf_vector inf.sup_monoid.add_commute)\n  also have \"... = v\\<^sup>T * e\"\n    using assms(1) vector_conv_covector by auto\n  also have \"... \\<le> r\\<^sup>T * (t \\<squnion> e)\\<^sup>\\<star> * e\"\n    using 1 by (simp add: mult_left_isotone)\n  also have \"... \\<le> r\\<^sup>T * (t \\<squnion> e)\\<^sup>\\<star> * (t \\<squnion> e)\"\n    by (simp add: mult_right_isotone)\n  also have \"... \\<le> r\\<^sup>T * (t \\<squnion> e)\\<^sup>\\<star>\"\n    by (simp add: comp_associative mult_right_isotone star.right_plus_below_circ)\n  finally have 3: \"(v \\<squnion> e\\<^sup>T * top)\\<^sup>T \\<le> r\\<^sup>T * (t \\<squnion> e)\\<^sup>\\<star>\"\n    using 1 by (simp add: conv_dist_sup)\n  have \"r\\<^sup>T \\<le> r\\<^sup>T * t\\<^sup>\\<star>\"\n    using sup.bounded_iff star.circ_back_loop_prefixpoint by blast\n  also have \"... \\<le> (v \\<squnion> e\\<^sup>T * top)\\<^sup>T\"\n    by (metis assms(4) conv_isotone sup_ge1)\n  finally have 4: \"r\\<^sup>T \\<le> (v \\<squnion> e\\<^sup>T * top)\\<^sup>T\"\n    .\n  have \"(v \\<squnion> e\\<^sup>T * top)\\<^sup>T * (t \\<squnion> e) = (v \\<squnion> e\\<^sup>T * top)\\<^sup>T * t \\<squnion> (v \\<squnion> e\\<^sup>T * top)\\<^sup>T * e\"\n    by (simp add: mult_left_dist_sup)\n  also have \"... \\<le> (v \\<squnion> e\\<^sup>T * top)\\<^sup>T * t \\<squnion> top * e\"\n    using comp_isotone semiring.add_left_mono by auto\n  also have \"... = v\\<^sup>T * t \\<squnion> top * e * t \\<squnion> top * e\"\n    using 2 by (simp add: conv_dist_sup mult_right_dist_sup)\n  also have \"... = v\\<^sup>T * t \\<squnion> top * e\"\n    by (simp add: assms(3) comp_associative)\n  also have \"... \\<le> r\\<^sup>T * t\\<^sup>\\<star> \\<squnion> top * e\"\n    by (metis assms(4) star.circ_back_loop_fixpoint sup_ge1 sup_left_isotone)\n  also have \"... = v\\<^sup>T \\<squnion> top * e\"\n    by (simp add: assms(4))\n  finally have 5: \"(v \\<squnion> e\\<^sup>T * top)\\<^sup>T * (t \\<squnion> e) \\<le> (v \\<squnion> e\\<^sup>T * top)\\<^sup>T\"\n    using 2 by (simp add: conv_dist_sup)\n  have \"r\\<^sup>T * (t \\<squnion> e)\\<^sup>\\<star> \\<le> (v \\<squnion> e\\<^sup>T * top)\\<^sup>T * (t \\<squnion> e)\\<^sup>\\<star>\"\n    using 4 by (simp add: mult_left_isotone)\n  also have \"... \\<le> (v \\<squnion> e\\<^sup>T * top)\\<^sup>T\"\n    using 5 by (simp add: star_right_induct_mult)\n  finally show ?thesis\n    using 3 by (simp add: inf.eq_iff)\nqed\n\ntext \\<open>\nThe next result is used to show that the while-loop preserves acyclicity of the constructed tree.\n\\<close>\n\nlemma acyclic_inv:\n  assumes \"acyclic t\"\n      and \"vector v\"\n      and \"e \\<le> v * -v\\<^sup>T\"\n      and \"t \\<le> v * v\\<^sup>T\"\n    shows \"acyclic (t \\<squnion> e)\"\nproof -\n  have \"t\\<^sup>+ * e \\<le> t\\<^sup>+ * v * -v\\<^sup>T\"\n    by (simp add: assms(3) comp_associative mult_right_isotone)\n  also have \"... \\<le> v * v\\<^sup>T * t\\<^sup>\\<star> * v * -v\\<^sup>T\"\n    by (simp add: assms(4) mult_left_isotone)\n  also have \"... \\<le> v * top * -v\\<^sup>T\"\n    by (metis mult_assoc mult_left_isotone mult_right_isotone top_greatest)\n  also have \"... = v * -v\\<^sup>T\"\n    by (simp add: assms(2))\n  also have \"... \\<le> -1\"\n    by (simp add: pp_increasing schroeder_3_p)\n  finally have 1: \"t\\<^sup>+ * e \\<le> -1\"\n    .\n  have 2: \"e * t\\<^sup>\\<star> = e\"\n    using assms(2-4) et(1) star_absorb by blast\n  have \"e\\<^sup>\\<star> = 1 \\<squnion> e \\<squnion> e * e * e\\<^sup>\\<star>\"\n    by (metis star.circ_loop_fixpoint star_square_2 sup_commute)\n  also have \"... = 1 \\<squnion> e\"\n    using assms(2,3) ee comp_left_zero bot_least sup_absorb1 by simp\n  finally have 3: \"e\\<^sup>\\<star> = 1 \\<squnion> e\"\n    .\n  have \"e \\<le> v * -v\\<^sup>T\"\n    by (simp add: assms(3))\n  also have \"... \\<le> -1\"\n    by (simp add: pp_increasing schroeder_3_p)\n  finally have 4: \"t\\<^sup>+ * e \\<squnion> e \\<le> -1\"\n    using 1 by simp\n  have \"(t \\<squnion> e)\\<^sup>+ = (t \\<squnion> e) * t\\<^sup>\\<star> * (e * t\\<^sup>\\<star>)\\<^sup>\\<star>\"\n    using star_sup_1 mult_assoc by simp\n  also have \"... = (t \\<squnion> e) * t\\<^sup>\\<star> * (1 \\<squnion> e)\"\n    using 2 3 by simp\n  also have \"... = t\\<^sup>+ * (1 \\<squnion> e) \\<squnion> e * t\\<^sup>\\<star> * (1 \\<squnion> e)\"\n    by (simp add: comp_right_dist_sup)\n  also have \"... = t\\<^sup>+ * (1 \\<squnion> e) \\<squnion> e * (1 \\<squnion> e)\"\n    using 2 by simp\n  also have \"... = t\\<^sup>+ * (1 \\<squnion> e) \\<squnion> e\"\n    using 3 by (metis star_absorb assms(2,3) ee)\n  also have \"... = t\\<^sup>+ \\<squnion> t\\<^sup>+ * e \\<squnion> e\"\n    by (simp add: mult_left_dist_sup)\n  also have \"... \\<le> -1\"\n    using 4 by (metis assms(1) sup.absorb1 sup.orderI sup_assoc)\n  finally show ?thesis\n    .\nqed\n\ntext \\<open>\nThe following lemma shows that the extended tree is in the component reachable from the root.\n\\<close>\n\nlemma mst_subgraph_inv_2:\n  assumes \"regular (v * v\\<^sup>T)\"\n      and \"t \\<le> v * v\\<^sup>T \\<sqinter> --g\"\n      and \"v\\<^sup>T = r\\<^sup>T * t\\<^sup>\\<star>\"\n      and \"e \\<le> v * -v\\<^sup>T \\<sqinter> --g\"\n      and \"vector v\"\n      and \"regular ((v \\<squnion> e\\<^sup>T * top) * (v \\<squnion> e\\<^sup>T * top)\\<^sup>T)\"\n    shows \"t \\<squnion> e \\<le> (r\\<^sup>T * (--((v \\<squnion> e\\<^sup>T * top) * (v \\<squnion> e\\<^sup>T * top)\\<^sup>T \\<sqinter> g))\\<^sup>\\<star>)\\<^sup>T * (r\\<^sup>T * (--((v \\<squnion> e\\<^sup>T * top) * (v \\<squnion> e\\<^sup>T * top)\\<^sup>T \\<sqinter> g))\\<^sup>\\<star>)\"\nproof -\n  let ?v = \"v \\<squnion> e\\<^sup>T * top\"\n  let ?G = \"?v * ?v\\<^sup>T \\<sqinter> g\"\n  let ?c = \"r\\<^sup>T * (--?G)\\<^sup>\\<star>\"\n  have \"v\\<^sup>T \\<le> r\\<^sup>T * (--(v * v\\<^sup>T \\<sqinter> g))\\<^sup>\\<star>\"\n    using assms(1-3) inf_pp_commute mult_right_isotone star_isotone by auto\n  also have \"... \\<le> ?c\"\n    using comp_inf.mult_right_isotone comp_isotone conv_isotone inf.commute mult_right_isotone pp_isotone star_isotone sup.cobounded1 by presburger\n  finally have 2: \"v\\<^sup>T \\<le> ?c \\<and> v \\<le> ?c\\<^sup>T\"\n    by (metis conv_isotone conv_involutive)\n  have \"t \\<le> v * v\\<^sup>T\"\n    using assms(2) by auto\n  hence 3: \"t \\<le> ?c\\<^sup>T * ?c\"\n    using 2 order_trans mult_isotone by blast\n  have \"e \\<le> v * top \\<sqinter> --g\"\n    by (metis assms(4,5) inf.bounded_iff inf.sup_left_divisibility mult_right_isotone top.extremum)\n  hence \"e \\<le> v * top \\<sqinter> top * e \\<sqinter> --g\"\n    by (simp add: top_left_mult_increasing inf.boundedI)\n  hence \"e \\<le> v * top * e \\<sqinter> --g\"\n    by (metis comp_inf_covector inf.absorb2 mult_assoc top.extremum)\n  hence \"t \\<squnion> e \\<le> (v * v\\<^sup>T \\<sqinter> --g) \\<squnion> (v * top * e \\<sqinter> --g)\"\n    using assms(2) sup_mono by blast\n  also have \"... = v * ?v\\<^sup>T \\<sqinter> --g\"\n    by (simp add: inf_sup_distrib2 mult_assoc mult_left_dist_sup conv_dist_comp conv_dist_sup)\n  also have \"... \\<le> --?G\"\n    using assms(6) comp_left_increasing_sup inf.sup_left_isotone pp_dist_inf by auto\n  finally have 4: \"t \\<squnion> e \\<le> --?G\"\n    .\n  have \"e \\<le> e * e\\<^sup>T * e\"\n    by (simp add: ex231c)\n  also have \"... \\<le> v * -v\\<^sup>T * -v * v\\<^sup>T * e\"\n    by (metis assms(4) mult_left_isotone conv_isotone conv_dist_comp mult_assoc mult_isotone conv_involutive conv_complement inf.boundedE)\n  also have \"... \\<le> v * top * v\\<^sup>T * e\"\n    by (metis mult_assoc mult_left_isotone mult_right_isotone top.extremum)\n  also have \"... = v * r\\<^sup>T * t\\<^sup>\\<star> * e\"\n    using assms(3,5) by (simp add: mult_assoc)\n  also have \"... \\<le> v * r\\<^sup>T * (t \\<squnion> e)\\<^sup>\\<star>\"\n    by (simp add: comp_associative mult_right_isotone star.circ_mult_upper_bound star.circ_sub_dist_1 star_isotone sup_commute)\n  also have \"... \\<le> v * ?c\"\n    using 4 by (simp add: mult_assoc mult_right_isotone star_isotone)\n  also have \"... \\<le> ?c\\<^sup>T * ?c\"\n    using 2 by (simp add: mult_left_isotone)\n  finally show ?thesis\n    using 3 by simp\nqed\n\nlemma span_inv:\n  assumes \"e \\<le> v * -v\\<^sup>T\"\n      and \"vector v\"\n      and \"arc e\"\n      and \"t \\<le> (v * v\\<^sup>T) \\<sqinter> g\"\n      and \"g\\<^sup>T = g\"\n      and \"v\\<^sup>T = r\\<^sup>T * t\\<^sup>\\<star>\"\n      and \"injective r\"\n      and \"r\\<^sup>T \\<le> v\\<^sup>T\"\n      and \"r\\<^sup>T * ((v * v\\<^sup>T) \\<sqinter> g)\\<^sup>\\<star> \\<le> r\\<^sup>T * t\\<^sup>\\<star>\"\n    shows \"r\\<^sup>T * (((v \\<squnion> e\\<^sup>T * top) * (v \\<squnion> e\\<^sup>T * top)\\<^sup>T) \\<sqinter> g)\\<^sup>\\<star> \\<le> r\\<^sup>T * (t \\<squnion> e)\\<^sup>\\<star>\"\nproof -\n  let ?d = \"(v * v\\<^sup>T) \\<sqinter> g\"\n  have 1: \"(v \\<squnion> e\\<^sup>T * top) * (v \\<squnion> e\\<^sup>T * top)\\<^sup>T = v * v\\<^sup>T \\<squnion> v * v\\<^sup>T * e \\<squnion> e\\<^sup>T * v * v\\<^sup>T \\<squnion> e\\<^sup>T * e\"\n    using assms(1-3) ve_dist by simp\n  have \"t\\<^sup>T \\<le> ?d\\<^sup>T\"\n    using assms(4) conv_isotone by simp\n  also have \"... = (v * v\\<^sup>T) \\<sqinter> g\\<^sup>T\"\n    by (simp add: conv_dist_comp conv_dist_inf)\n  also have \"... = ?d\"\n    by (simp add: assms(5))\n  finally have 2: \"t\\<^sup>T \\<le> ?d\"\n    .\n  have \"v * v\\<^sup>T = (r\\<^sup>T * t\\<^sup>\\<star>)\\<^sup>T * (r\\<^sup>T * t\\<^sup>\\<star>)\"\n    by (metis assms(6) conv_involutive)\n  also have \"... = t\\<^sup>T\\<^sup>\\<star> * (r * r\\<^sup>T) * t\\<^sup>\\<star>\"\n    by (simp add: comp_associative conv_dist_comp conv_star_commute)\n  also have \"... \\<le> t\\<^sup>T\\<^sup>\\<star> * 1 * t\\<^sup>\\<star>\"\n    by (simp add: assms(7) mult_left_isotone star_right_induct_mult_iff star_sub_one)\n  also have \"... = t\\<^sup>T\\<^sup>\\<star> * t\\<^sup>\\<star>\"\n    by simp\n  also have \"... \\<le> ?d\\<^sup>\\<star> * t\\<^sup>\\<star>\"\n    using 2 by (simp add: comp_left_isotone star.circ_isotone)\n  also have \"... \\<le> ?d\\<^sup>\\<star> * ?d\\<^sup>\\<star>\"\n    using assms(4) mult_right_isotone star_isotone by simp\n  also have 3: \"... = ?d\\<^sup>\\<star>\"\n    by (simp add: star.circ_transitive_equal)\n  finally have 4: \"v * v\\<^sup>T \\<le> ?d\\<^sup>\\<star>\"\n    .\n  have 5: \"r\\<^sup>T * ?d\\<^sup>\\<star> * (v * v\\<^sup>T \\<sqinter> g) \\<le> r\\<^sup>T * ?d\\<^sup>\\<star>\"\n    by (simp add: comp_associative mult_right_isotone star.circ_plus_same star.left_plus_below_circ)\n  have \"r\\<^sup>T * ?d\\<^sup>\\<star> * (v * v\\<^sup>T * e \\<sqinter> g) \\<le> r\\<^sup>T * ?d\\<^sup>\\<star> * v * v\\<^sup>T * e\"\n    by (simp add: comp_associative comp_right_isotone)\n  also have \"... \\<le> r\\<^sup>T * ?d\\<^sup>\\<star> * e\"\n    using 3 4 by (metis comp_associative comp_isotone eq_refl)\n  finally have 6: \"r\\<^sup>T * ?d\\<^sup>\\<star> * (v * v\\<^sup>T * e \\<sqinter> g) \\<le> r\\<^sup>T * ?d\\<^sup>\\<star> * e\"\n    .\n  have 7: \"\\<forall>x . r\\<^sup>T * (1 \\<squnion> v * v\\<^sup>T) * e\\<^sup>T * x = bot\"\n  proof\n    fix x\n    have \"r\\<^sup>T * (1 \\<squnion> v * v\\<^sup>T) * e\\<^sup>T * x \\<le> r\\<^sup>T * (1 \\<squnion> v * v\\<^sup>T) * e\\<^sup>T * top\"\n      by (simp add: mult_right_isotone)\n    also have \"... = r\\<^sup>T * e\\<^sup>T * top \\<squnion> r\\<^sup>T * v * v\\<^sup>T * e\\<^sup>T * top\"\n      by (simp add: comp_associative mult_left_dist_sup mult_right_dist_sup)\n    also have \"... = r\\<^sup>T * e\\<^sup>T * top\"\n      by (metis assms(1,2) mult_assoc mult_right_dist_sup mult_right_zero sup_bot_right vTeT)\n    also have \"... \\<le> v\\<^sup>T * e\\<^sup>T * top\"\n      by (simp add: assms(8) comp_isotone)\n    also have \"... = bot\"\n      using vTeT assms(1,2) by simp\n    finally show \"r\\<^sup>T * (1 \\<squnion> v * v\\<^sup>T) * e\\<^sup>T * x = bot\"\n      by (simp add: le_bot)\n  qed\n  have \"r\\<^sup>T * ?d\\<^sup>\\<star> * (e\\<^sup>T * v * v\\<^sup>T \\<sqinter> g) \\<le> r\\<^sup>T * ?d\\<^sup>\\<star> * e\\<^sup>T * v * v\\<^sup>T\"\n    by (simp add: comp_associative comp_right_isotone)\n  also have \"... \\<le> r\\<^sup>T * (1 \\<squnion> v * v\\<^sup>T) * e\\<^sup>T * v * v\\<^sup>T\"\n    by (metis assms(2) star.circ_isotone vector_vector_star inf_le1 comp_associative comp_right_isotone comp_left_isotone)\n  also have \"... = bot\"\n    using 7 by simp\n  finally have 8: \"r\\<^sup>T * ?d\\<^sup>\\<star> * (e\\<^sup>T * v * v\\<^sup>T \\<sqinter> g) = bot\"\n    by (simp add: le_bot)\n  have \"r\\<^sup>T * ?d\\<^sup>\\<star> * (e\\<^sup>T * e \\<sqinter> g) \\<le> r\\<^sup>T * ?d\\<^sup>\\<star> * e\\<^sup>T * e\"\n    by (simp add: comp_associative comp_right_isotone)\n  also have \"... \\<le> r\\<^sup>T * (1 \\<squnion> v * v\\<^sup>T) * e\\<^sup>T * e\"\n    by (metis assms(2) star.circ_isotone vector_vector_star inf_le1 comp_associative comp_right_isotone comp_left_isotone)\n  also have \"... = bot\"\n    using 7 by simp\n  finally have 9: \"r\\<^sup>T * ?d\\<^sup>\\<star> * (e\\<^sup>T * e \\<sqinter> g) = bot\"\n    by (simp add: le_bot)\n  have \"r\\<^sup>T * ?d\\<^sup>\\<star> * ((v \\<squnion> e\\<^sup>T * top) * (v \\<squnion> e\\<^sup>T * top)\\<^sup>T \\<sqinter> g) = r\\<^sup>T * ?d\\<^sup>\\<star> * ((v * v\\<^sup>T \\<squnion> v * v\\<^sup>T * e \\<squnion> e\\<^sup>T * v * v\\<^sup>T \\<squnion> e\\<^sup>T * e) \\<sqinter> g)\"\n    using 1 by simp\n  also have \"... = r\\<^sup>T * ?d\\<^sup>\\<star> * ((v * v\\<^sup>T \\<sqinter> g) \\<squnion> (v * v\\<^sup>T * e \\<sqinter> g) \\<squnion> (e\\<^sup>T * v * v\\<^sup>T \\<sqinter> g) \\<squnion> (e\\<^sup>T * e \\<sqinter> g))\"\n    by (simp add: inf_sup_distrib2)\n  also have \"... = r\\<^sup>T * ?d\\<^sup>\\<star> * (v * v\\<^sup>T \\<sqinter> g) \\<squnion> r\\<^sup>T * ?d\\<^sup>\\<star> * (v * v\\<^sup>T * e \\<sqinter> g) \\<squnion> r\\<^sup>T * ?d\\<^sup>\\<star> * (e\\<^sup>T * v * v\\<^sup>T \\<sqinter> g) \\<squnion> r\\<^sup>T * ?d\\<^sup>\\<star> * (e\\<^sup>T * e \\<sqinter> g)\"\n    by (simp add: comp_left_dist_sup)\n  also have \"... = r\\<^sup>T * ?d\\<^sup>\\<star> * (v * v\\<^sup>T \\<sqinter> g) \\<squnion> r\\<^sup>T * ?d\\<^sup>\\<star> * (v * v\\<^sup>T * e \\<sqinter> g)\"\n    using 8 9 by simp\n  also have \"... \\<le> r\\<^sup>T * ?d\\<^sup>\\<star> \\<squnion> r\\<^sup>T * ?d\\<^sup>\\<star> * e\"\n    using 5 6 sup.mono by simp\n  also have \"... = r\\<^sup>T * ?d\\<^sup>\\<star> * (1 \\<squnion> e)\"\n    by (simp add: mult_left_dist_sup)\n  finally have 10: \"r\\<^sup>T * ?d\\<^sup>\\<star> * ((v \\<squnion> e\\<^sup>T * top) * (v \\<squnion> e\\<^sup>T * top)\\<^sup>T \\<sqinter> g) \\<le> r\\<^sup>T * ?d\\<^sup>\\<star> * (1 \\<squnion> e)\"\n    by simp\n  have \"r\\<^sup>T * ?d\\<^sup>\\<star> * e * (v * v\\<^sup>T \\<sqinter> g) \\<le> r\\<^sup>T * ?d\\<^sup>\\<star> * e * v * v\\<^sup>T\"\n    by (simp add: comp_associative comp_right_isotone)\n  also have \"... = bot\"\n    by (metis assms(1,2) comp_associative comp_right_zero ev comp_left_zero)\n  finally have 11: \"r\\<^sup>T * ?d\\<^sup>\\<star> * e * (v * v\\<^sup>T \\<sqinter> g) = bot\"\n    by (simp add: le_bot)\n  have \"r\\<^sup>T * ?d\\<^sup>\\<star> * e * (v * v\\<^sup>T * e \\<sqinter> g) \\<le> r\\<^sup>T * ?d\\<^sup>\\<star> * e * v * v\\<^sup>T * e\"\n    by (simp add: comp_associative comp_right_isotone)\n  also have \"... = bot\"\n    by (metis assms(1,2) comp_associative comp_right_zero ev comp_left_zero)\n  finally have 12: \"r\\<^sup>T * ?d\\<^sup>\\<star> * e * (v * v\\<^sup>T * e \\<sqinter> g) = bot\"\n    by (simp add: le_bot)\n  have \"r\\<^sup>T * ?d\\<^sup>\\<star> * e * (e\\<^sup>T * v * v\\<^sup>T \\<sqinter> g) \\<le> r\\<^sup>T * ?d\\<^sup>\\<star> * e * e\\<^sup>T * v * v\\<^sup>T\"\n    by (simp add: comp_associative comp_right_isotone)\n  also have \"... \\<le> r\\<^sup>T * ?d\\<^sup>\\<star> * 1 * v * v\\<^sup>T\"\n    by (metis assms(3) arc_injective comp_associative comp_left_isotone comp_right_isotone)\n  also have \"... = r\\<^sup>T * ?d\\<^sup>\\<star> * v * v\\<^sup>T\"\n    by simp\n  also have \"... \\<le> r\\<^sup>T * ?d\\<^sup>\\<star> * ?d\\<^sup>\\<star>\"\n    using 4 by (simp add: mult_right_isotone mult_assoc)\n  also have \"... = r\\<^sup>T * ?d\\<^sup>\\<star>\"\n    by (simp add: star.circ_transitive_equal comp_associative)\n  finally have 13: \"r\\<^sup>T * ?d\\<^sup>\\<star> * e * (e\\<^sup>T * v * v\\<^sup>T \\<sqinter> g) \\<le> r\\<^sup>T * ?d\\<^sup>\\<star>\"\n    .\n  have \"r\\<^sup>T * ?d\\<^sup>\\<star> * e * (e\\<^sup>T * e \\<sqinter> g) \\<le> r\\<^sup>T * ?d\\<^sup>\\<star> * e * e\\<^sup>T * e\"\n    by (simp add: comp_associative comp_right_isotone)\n  also have \"... \\<le> r\\<^sup>T * ?d\\<^sup>\\<star> * 1 * e\"\n    by (metis assms(3) arc_injective comp_associative comp_left_isotone comp_right_isotone)\n  also have \"... = r\\<^sup>T * ?d\\<^sup>\\<star> * e\"\n    by simp\n  finally have 14: \"r\\<^sup>T * ?d\\<^sup>\\<star> * e * (e\\<^sup>T * e \\<sqinter> g) \\<le> r\\<^sup>T * ?d\\<^sup>\\<star> * e\"\n    .\n  have \"r\\<^sup>T * ?d\\<^sup>\\<star> * e * ((v \\<squnion> e\\<^sup>T * top) * (v \\<squnion> e\\<^sup>T * top)\\<^sup>T \\<sqinter> g) = r\\<^sup>T * ?d\\<^sup>\\<star> * e * ((v * v\\<^sup>T \\<squnion> v * v\\<^sup>T * e \\<squnion> e\\<^sup>T * v * v\\<^sup>T \\<squnion> e\\<^sup>T * e) \\<sqinter> g)\"\n    using 1 by simp\n  also have \"... = r\\<^sup>T * ?d\\<^sup>\\<star> * e * ((v * v\\<^sup>T \\<sqinter> g) \\<squnion> (v * v\\<^sup>T * e \\<sqinter> g) \\<squnion> (e\\<^sup>T * v * v\\<^sup>T \\<sqinter> g) \\<squnion> (e\\<^sup>T * e \\<sqinter> g))\"\n    by (simp add: inf_sup_distrib2)\n  also have \"... = r\\<^sup>T * ?d\\<^sup>\\<star> * e * (v * v\\<^sup>T \\<sqinter> g) \\<squnion> r\\<^sup>T * ?d\\<^sup>\\<star> * e * (v * v\\<^sup>T * e \\<sqinter> g) \\<squnion> r\\<^sup>T * ?d\\<^sup>\\<star> * e * (e\\<^sup>T * v * v\\<^sup>T \\<sqinter> g) \\<squnion> r\\<^sup>T * ?d\\<^sup>\\<star> * e * (e\\<^sup>T * e \\<sqinter> g)\"\n    by (simp add: comp_left_dist_sup)\n  also have \"... = r\\<^sup>T * ?d\\<^sup>\\<star> * e * (e\\<^sup>T * v * v\\<^sup>T \\<sqinter> g) \\<squnion> r\\<^sup>T * ?d\\<^sup>\\<star> * e * (e\\<^sup>T * e \\<sqinter> g)\"\n    using 11 12 by simp\n  also have \"... \\<le> r\\<^sup>T * ?d\\<^sup>\\<star> \\<squnion> r\\<^sup>T * ?d\\<^sup>\\<star> * e\"\n    using 13 14 sup_mono by simp\n  also have \"... = r\\<^sup>T * ?d\\<^sup>\\<star> * (1 \\<squnion> e)\"\n    by (simp add: mult_left_dist_sup)\n  finally have 15: \"r\\<^sup>T * ?d\\<^sup>\\<star> * e * ((v \\<squnion> e\\<^sup>T * top) * (v \\<squnion> e\\<^sup>T * top)\\<^sup>T \\<sqinter> g) \\<le> r\\<^sup>T * ?d\\<^sup>\\<star> * (1 \\<squnion> e)\"\n    by simp\n  have \"r\\<^sup>T \\<le> r\\<^sup>T * ?d\\<^sup>\\<star>\"\n    using mult_right_isotone star.circ_reflexive by fastforce\n  also have \"... \\<le> r\\<^sup>T * ?d\\<^sup>\\<star> * (1 \\<squnion> e)\"\n    by (simp add: semiring.distrib_left)\n  finally have 16: \"r\\<^sup>T \\<le> r\\<^sup>T * ?d\\<^sup>\\<star> * (1 \\<squnion> e)\"\n    .\n  have \"r\\<^sup>T * ?d\\<^sup>\\<star> * (1 \\<squnion> e) * ((v \\<squnion> e\\<^sup>T * top) * (v \\<squnion> e\\<^sup>T * top)\\<^sup>T \\<sqinter> g) = r\\<^sup>T * ?d\\<^sup>\\<star> * ((v \\<squnion> e\\<^sup>T * top) * (v \\<squnion> e\\<^sup>T * top)\\<^sup>T \\<sqinter> g) \\<squnion> r\\<^sup>T * ?d\\<^sup>\\<star> * e * ((v \\<squnion> e\\<^sup>T * top) * (v \\<squnion> e\\<^sup>T * top)\\<^sup>T \\<sqinter> g)\"\n    by (simp add: semiring.distrib_left semiring.distrib_right)\n  also have \"... \\<le> r\\<^sup>T * ?d\\<^sup>\\<star> * (1 \\<squnion> e)\"\n    using 10 15 le_supI by simp\n  finally have \"r\\<^sup>T * ?d\\<^sup>\\<star> * (1 \\<squnion> e) * ((v \\<squnion> e\\<^sup>T * top) * (v \\<squnion> e\\<^sup>T * top)\\<^sup>T \\<sqinter> g) \\<le> r\\<^sup>T * ?d\\<^sup>\\<star> * (1 \\<squnion> e)\"\n    .\n  hence \"r\\<^sup>T \\<squnion> r\\<^sup>T * ?d\\<^sup>\\<star> * (1 \\<squnion> e) * ((v \\<squnion> e\\<^sup>T * top) * (v \\<squnion> e\\<^sup>T * top)\\<^sup>T \\<sqinter> g) \\<le> r\\<^sup>T * ?d\\<^sup>\\<star> * (1 \\<squnion> e)\"\n    using 16 sup_least by simp\n  hence \"r\\<^sup>T * ((v \\<squnion> e\\<^sup>T * top) * (v \\<squnion> e\\<^sup>T * top)\\<^sup>T \\<sqinter> g)\\<^sup>\\<star> \\<le> r\\<^sup>T * ?d\\<^sup>\\<star> * (1 \\<squnion> e)\"\n    by (simp add: star_right_induct)\n  also have \"... \\<le> r\\<^sup>T * t\\<^sup>\\<star> * (1 \\<squnion> e)\"\n    by (simp add: assms(9) mult_left_isotone)\n  also have \"... \\<le> r\\<^sup>T * (t \\<squnion> e)\\<^sup>\\<star>\"\n    by (simp add: star_one_sup_below)\n  finally show ?thesis\n    .\nqed\n\nsubsubsection \\<open>Exchange gives Spanning Trees\\<close>\n\ntext \\<open>\nThe following abbreviations are used in the spanning tree application using Prim's algorithm to construct the new tree for the exchange property.\nIt is obtained by replacing an edge with one that has minimal weight and reversing the path connecting these edges.\nHere, w represents a weighted graph, v represents a set of nodes and e represents an edge.\n\\<close>\n\nabbreviation prim_E :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> 'a\" where \"prim_E w v e \\<equiv> w \\<sqinter> --v * -v\\<^sup>T \\<sqinter> top * e * w\\<^sup>T\\<^sup>\\<star>\"\nabbreviation prim_P :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> 'a\" where \"prim_P w v e \\<equiv> w \\<sqinter> -v * -v\\<^sup>T \\<sqinter> top * e * w\\<^sup>T\\<^sup>\\<star>\"\nabbreviation prim_EP :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> 'a\" where \"prim_EP w v e \\<equiv> w \\<sqinter> -v\\<^sup>T \\<sqinter> top * e * w\\<^sup>T\\<^sup>\\<star>\"\nabbreviation prim_W :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> 'a\" where \"prim_W w v e \\<equiv> (w \\<sqinter> -(prim_EP w v e)) \\<squnion> (prim_P w v e)\\<^sup>T \\<squnion> e\"\n\ntext \\<open>\nThe lemmas in this section are used to show that the relation after exchange represents a spanning tree.\nThe results in the next section are used to show that it is a minimum spanning tree.\n\\<close>\n\nlemma exchange_injective_3:\n  assumes \"e \\<le> v * -v\\<^sup>T\"\n      and \"vector v\"\n    shows \"(w \\<sqinter> -(prim_EP w v e)) * e\\<^sup>T = bot\"\nproof -\n  have 1: \"top * e \\<le> -v\\<^sup>T\"\n    by (simp add: assms schroeder_4_p vTeT)\n  have \"top * e \\<le> top * e * w\\<^sup>T\\<^sup>\\<star>\"\n    using sup_right_divisibility star.circ_back_loop_fixpoint by blast\n  hence \"top * e \\<le> -v\\<^sup>T \\<sqinter> top * e * w\\<^sup>T\\<^sup>\\<star>\"\n    using 1 by simp\n  hence \"top * e \\<le> -(w \\<sqinter> -prim_EP w v e)\"\n    by (metis inf.assoc inf_import_p le_infI2 p_antitone p_antitone_iff)\n  hence \"(w \\<sqinter> -(prim_EP w v e)) * e\\<^sup>T \\<le> bot\"\n    using p_top schroeder_4_p by blast\n  thus ?thesis\n    using le_bot by simp\nqed\n\nlemma exchange_injective_6:\n  assumes \"arc e\"\n      and \"forest w\"\n    shows \"(prim_P w v e)\\<^sup>T * e\\<^sup>T = bot\"\nproof -\n  have \"e\\<^sup>T * top * e \\<le> --1\"\n    by (simp add: assms(1) p_antitone p_antitone_iff point_injective)\n  hence 1: \"e * -1 * e\\<^sup>T \\<le> bot\"\n    by (metis conv_involutive p_top triple_schroeder_p)\n  have \"(prim_P w v e)\\<^sup>T * e\\<^sup>T \\<le> (w \\<sqinter> top * e * w\\<^sup>T\\<^sup>\\<star>)\\<^sup>T * e\\<^sup>T\"\n    using comp_inf.mult_left_isotone conv_dist_inf mult_left_isotone by simp\n  also have \"... = (w\\<^sup>T \\<sqinter> w\\<^sup>T\\<^sup>\\<star>\\<^sup>T * e\\<^sup>T * top) * e\\<^sup>T\"\n    by (simp add: comp_associative conv_dist_comp conv_dist_inf)\n  also have \"... = w\\<^sup>\\<star> * e\\<^sup>T * top \\<sqinter> w\\<^sup>T * e\\<^sup>T\"\n    by (simp add: conv_star_commute inf_vector_comp)\n  also have \"... \\<le> (w\\<^sup>T \\<sqinter> w\\<^sup>\\<star> * e\\<^sup>T * top * e) * (e\\<^sup>T \\<sqinter> w\\<^sup>+ * e\\<^sup>T * top)\"\n    by (metis dedekind mult_assoc conv_involutive inf_commute)\n  also have \"... \\<le> (w\\<^sup>\\<star> * e\\<^sup>T * top * e) * (w\\<^sup>+ * e\\<^sup>T * top)\"\n    by (simp add: mult_isotone)\n  also have \"... \\<le> (top * e) * (w\\<^sup>+ * e\\<^sup>T * top)\"\n    by (simp add: mult_left_isotone)\n  also have \"... = top * e * w\\<^sup>+ * e\\<^sup>T * top\"\n    using mult_assoc by simp\n  also have \"... \\<le> top * e * -1 * e\\<^sup>T * top\"\n    using assms(2) mult_left_isotone mult_right_isotone by simp\n  also have \"... \\<le> bot\"\n    using 1 by (metis le_bot semiring.mult_not_zero mult_assoc)\n  finally show ?thesis\n    using le_bot by simp\nqed\n\ntext \\<open>\nThe graph after exchanging is injective.\n\\<close>\n\nlemma exchange_injective:\n  assumes \"arc e\"\n      and \"e \\<le> v * -v\\<^sup>T\"\n      and \"forest w\"\n      and \"vector v\"\n    shows \"injective (prim_W w v e)\"\nproof -\n  have 1: \"(w \\<sqinter> -(prim_EP w v e)) * (w \\<sqinter> -(prim_EP w v e))\\<^sup>T \\<le> 1\"\n  proof -\n    have \"(w \\<sqinter> -(prim_EP w v e)) * (w \\<sqinter> -(prim_EP w v e))\\<^sup>T \\<le> w * w\\<^sup>T\"\n      by (simp add: comp_isotone conv_isotone)\n    also have \"... \\<le> 1\"\n      by (simp add: assms(3))\n    finally show ?thesis\n      .\n  qed\n  have 2: \"(w \\<sqinter> -(prim_EP w v e)) * (prim_P w v e)\\<^sup>T\\<^sup>T \\<le> 1\"\n  proof -\n    have \"top * (prim_P w v e)\\<^sup>T = top * (w\\<^sup>T \\<sqinter> -v * -v\\<^sup>T \\<sqinter> w\\<^sup>T\\<^sup>\\<star>\\<^sup>T * e\\<^sup>T * top)\"\n      by (simp add: comp_associative conv_complement conv_dist_comp conv_dist_inf)\n    also have \"... = top * e * w\\<^sup>T\\<^sup>\\<star> * (w\\<^sup>T \\<sqinter> -v * -v\\<^sup>T)\"\n      by (metis comp_inf_vector conv_dist_comp conv_involutive inf_top_left mult_assoc)\n    also have \"... \\<le> top * e * w\\<^sup>T\\<^sup>\\<star> * (w\\<^sup>T \\<sqinter> top * -v\\<^sup>T)\"\n      using comp_inf.mult_right_isotone mult_left_isotone mult_right_isotone by simp\n    also have \"... = top * e * w\\<^sup>T\\<^sup>\\<star> * w\\<^sup>T \\<sqinter> -v\\<^sup>T\"\n      by (metis assms(4) comp_inf_covector vector_conv_compl)\n    also have \"... \\<le> -v\\<^sup>T \\<sqinter> top * e * w\\<^sup>T\\<^sup>\\<star>\"\n      by (simp add: comp_associative comp_isotone inf.coboundedI1 star.circ_plus_same star.left_plus_below_circ)\n    finally have \"top * (prim_P w v e)\\<^sup>T \\<le> -(w \\<sqinter> -prim_EP w v e)\"\n      by (metis inf.assoc inf_import_p le_infI2 p_antitone p_antitone_iff)\n    hence \"(w \\<sqinter> -(prim_EP w v e)) * (prim_P w v e)\\<^sup>T\\<^sup>T \\<le> bot\"\n      using p_top schroeder_4_p by blast\n    thus ?thesis\n      by (simp add: bot_unique)\n  qed\n  have 3: \"(w \\<sqinter> -(prim_EP w v e)) * e\\<^sup>T \\<le> 1\"\n    by (metis assms(2,4) exchange_injective_3 bot_least)\n  have 4: \"(prim_P w v e)\\<^sup>T * (w \\<sqinter> -(prim_EP w v e))\\<^sup>T \\<le> 1\"\n    using 2 conv_dist_comp coreflexive_symmetric by fastforce\n  have 5: \"(prim_P w v e)\\<^sup>T * (prim_P w v e)\\<^sup>T\\<^sup>T \\<le> 1\"\n  proof -\n    have \"(prim_P w v e)\\<^sup>T * (prim_P w v e)\\<^sup>T\\<^sup>T \\<le> (top * e * w\\<^sup>T\\<^sup>\\<star>)\\<^sup>T * (top * e * w\\<^sup>T\\<^sup>\\<star>)\"\n      by (simp add: conv_dist_inf mult_isotone)\n    also have \"... = w\\<^sup>\\<star> * e\\<^sup>T * top * top * e * w\\<^sup>T\\<^sup>\\<star>\"\n      using conv_star_commute conv_dist_comp conv_involutive conv_top mult_assoc by presburger\n    also have \"... = w\\<^sup>\\<star> * e\\<^sup>T * top * e * w\\<^sup>T\\<^sup>\\<star>\"\n      by (simp add: comp_associative)\n    also have \"... \\<le> w\\<^sup>\\<star> * 1 * w\\<^sup>T\\<^sup>\\<star>\"\n      by (metis comp_left_isotone comp_right_isotone mult_assoc assms(1) point_injective)\n    finally have \"(prim_P w v e)\\<^sup>T * (prim_P w v e)\\<^sup>T\\<^sup>T \\<le> w\\<^sup>\\<star> * w\\<^sup>T\\<^sup>\\<star> \\<sqinter> w\\<^sup>T * w\"\n      by (simp add: conv_isotone inf.left_commute inf.sup_monoid.add_commute mult_isotone)\n    also have \"... \\<le> 1\"\n      by (simp add: assms(3) forest_separate)\n    finally show ?thesis\n      .\n  qed\n  have 6: \"(prim_P w v e)\\<^sup>T * e\\<^sup>T \\<le> 1\"\n    using assms exchange_injective_6 bot_least by simp\n  have 7: \"e * (w \\<sqinter> -(prim_EP w v e))\\<^sup>T \\<le> 1\"\n    using 3 by (metis conv_dist_comp conv_involutive coreflexive_symmetric)\n  have 8: \"e * (prim_P w v e)\\<^sup>T\\<^sup>T \\<le> 1\"\n    using 6 conv_dist_comp coreflexive_symmetric by fastforce\n  have 9: \"e * e\\<^sup>T \\<le> 1\"\n    by (simp add: assms(1) arc_injective)\n  have \"(prim_W w v e) * (prim_W w v e)\\<^sup>T = (w \\<sqinter> -(prim_EP w v e)) * (w \\<sqinter> -(prim_EP w v e))\\<^sup>T \\<squnion> (w \\<sqinter> -(prim_EP w v e)) * (prim_P w v e)\\<^sup>T\\<^sup>T \\<squnion> (w \\<sqinter> -(prim_EP w v e)) * e\\<^sup>T \\<squnion> (prim_P w v e)\\<^sup>T * (w \\<sqinter> -(prim_EP w v e))\\<^sup>T \\<squnion> (prim_P w v e)\\<^sup>T * (prim_P w v e)\\<^sup>T\\<^sup>T \\<squnion> (prim_P w v e)\\<^sup>T * e\\<^sup>T  \\<squnion> e * (w \\<sqinter> -(prim_EP w v e))\\<^sup>T \\<squnion> e * (prim_P w v e)\\<^sup>T\\<^sup>T \\<squnion> e * e\\<^sup>T\"\n    using comp_left_dist_sup comp_right_dist_sup conv_dist_sup sup.assoc by simp\n  also have \"... \\<le> 1\"\n    using 1 2 3 4 5 6 7 8 9 by simp\n  finally show ?thesis\n    .\nqed\n\nlemma pv:\n  assumes \"vector v\"\n    shows \"(prim_P w v e)\\<^sup>T * v = bot\"\nproof -\n  have \"(prim_P w v e)\\<^sup>T * v \\<le> (-v * -v\\<^sup>T)\\<^sup>T * v\"\n    by (meson conv_isotone inf_le1 inf_le2 mult_left_isotone order_trans)\n  also have \"... = -v * -v\\<^sup>T * v\"\n    by (simp add: conv_complement conv_dist_comp)\n  also have \"... = bot\"\n    by (simp add: assms covector_vector_comp mult_assoc)\n  finally show ?thesis\n    by (simp add: antisym)\nqed\n\nlemma vector_pred_inv:\n  assumes \"arc e\"\n      and \"e \\<le> v * -v\\<^sup>T\"\n      and \"forest w\"\n      and \"vector v\"\n      and \"w * v \\<le> v\"\n    shows \"(prim_W w v e) * (v \\<squnion> e\\<^sup>T * top) \\<le> v \\<squnion> e\\<^sup>T * top\"\nproof -\n  have \"(prim_W w v e) * e\\<^sup>T * top = (w \\<sqinter> -(prim_EP w v e)) * e\\<^sup>T * top \\<squnion> (prim_P w v e)\\<^sup>T * e\\<^sup>T * top \\<squnion> e * e\\<^sup>T * top\"\n    by (simp add: mult_right_dist_sup)\n  also have \"... = e * e\\<^sup>T * top\"\n   using assms exchange_injective_3 exchange_injective_6 comp_left_zero by simp\n  also have \"... \\<le> v * -v\\<^sup>T * e\\<^sup>T * top\"\n    by (simp add: assms(2) comp_isotone)\n  also have \"... \\<le> v * top\"\n    by (simp add: comp_associative mult_right_isotone)\n  also have \"... = v\"\n    by (simp add: assms(4))\n  finally have 1: \"(prim_W w v e) * e\\<^sup>T * top \\<le> v\"\n    .\n  have \"(prim_W w v e) * v = (w \\<sqinter> -(prim_EP w v e)) * v \\<squnion> (prim_P w v e)\\<^sup>T * v \\<squnion> e * v\"\n    by (simp add: mult_right_dist_sup)\n  also have \"... = (w \\<sqinter> -(prim_EP w v e)) * v\"\n    by (metis assms(2,4) pv ev sup_bot_right)\n  also have \"... \\<le> w * v\"\n    by (simp add: mult_left_isotone)\n  finally have 2: \"(prim_W w v e) * v \\<le> v\"\n    using assms(5) order_trans by blast\n  have \"(prim_W w v e) * (v \\<squnion> e\\<^sup>T * top) = (prim_W w v e) * v \\<squnion> (prim_W w v e) * e\\<^sup>T * top\"\n    by (simp add: semiring.distrib_left mult_assoc)\n  also have \"... \\<le> v\"\n    using 1 2 by simp\n  also have \"... \\<le> v \\<squnion> e\\<^sup>T * top\"\n    by simp\n  finally show ?thesis\n    .\nqed\n\ntext \\<open>\nThe graph after exchanging is acyclic.\n\\<close>\n\nlemma exchange_acyclic:\n  assumes \"vector v\"\n      and \"e \\<le> v * -v\\<^sup>T\"\n      and \"w * v \\<le> v\"\n      and \"acyclic w\"\n    shows \"acyclic (prim_W w v e)\"\nproof -\n  have 1: \"(prim_P w v e)\\<^sup>T * e = bot\"\n  proof -\n    have \"(prim_P w v e)\\<^sup>T * e \\<le> (-v * -v\\<^sup>T)\\<^sup>T * e\"\n      by (meson conv_order dual_order.trans inf.cobounded1 inf.cobounded2 mult_left_isotone)\n    also have \"... = -v * -v\\<^sup>T * e\"\n      by (simp add: conv_complement conv_dist_comp)\n    also have \"... \\<le> -v * -v\\<^sup>T * v * -v\\<^sup>T\"\n      by (simp add: assms(2) comp_associative mult_right_isotone)\n    also have \"... = bot\"\n      by (simp add: assms(1) covector_vector_comp mult_assoc)\n    finally show ?thesis\n      by (simp add: bot_unique)\n  qed\n  have 2: \"e * e = bot\"\n    using assms(1,2) ee by auto\n  have 3: \"(w \\<sqinter> -(prim_EP w v e)) * (prim_P w v e)\\<^sup>T = bot\"\n  proof -\n    have \"top * (prim_P w v e) \\<le> top * (-v * -v\\<^sup>T \\<sqinter> top * e * w\\<^sup>T\\<^sup>\\<star>)\"\n      using comp_inf.mult_semi_associative mult_right_isotone by auto\n    also have \"... \\<le> top * -v * -v\\<^sup>T \\<sqinter> top * top * e * w\\<^sup>T\\<^sup>\\<star>\"\n      by (simp add: comp_inf_covector mult_assoc)\n    also have \"... \\<le> top * -v\\<^sup>T \\<sqinter> top * e * w\\<^sup>T\\<^sup>\\<star>\"\n      using mult_left_isotone top.extremum inf_mono by presburger\n    also have \"... = -v\\<^sup>T \\<sqinter> top * e * w\\<^sup>T\\<^sup>\\<star>\"\n      by (simp add: assms(1) vector_conv_compl)\n    finally have \"top * (prim_P w v e) \\<le> -(w \\<sqinter> -prim_EP w v e)\"\n      by (metis inf.assoc inf_import_p le_infI2 p_antitone p_antitone_iff)\n    hence \"(w \\<sqinter> -(prim_EP w v e)) * (prim_P w v e)\\<^sup>T \\<le> bot\"\n      using p_top schroeder_4_p by blast\n    thus ?thesis\n      using bot_unique by blast\n  qed\n  hence 4: \"(w \\<sqinter> -(prim_EP w v e)) * (prim_P w v e)\\<^sup>T\\<^sup>\\<star> = w \\<sqinter> -(prim_EP w v e)\"\n    using star_absorb by blast\n  hence 5: \"(w \\<sqinter> -(prim_EP w v e))\\<^sup>+ * (prim_P w v e)\\<^sup>T\\<^sup>\\<star> = (w \\<sqinter> -(prim_EP w v e))\\<^sup>+\"\n    by (metis star_plus mult_assoc)\n  hence 6: \"(w \\<sqinter> -(prim_EP w v e))\\<^sup>\\<star> * (prim_P w v e)\\<^sup>T\\<^sup>\\<star> = (w \\<sqinter> -(prim_EP w v e))\\<^sup>+ \\<squnion> (prim_P w v e)\\<^sup>T\\<^sup>\\<star>\"\n    by (metis star.circ_loop_fixpoint mult_assoc)\n  have 7: \"(w \\<sqinter> -(prim_EP w v e))\\<^sup>+ * e \\<le> v * top\"\n  proof -\n    have \"e \\<le> v * top\"\n      using assms(2) dual_order.trans mult_right_isotone top_greatest by blast\n    hence 8: \"e \\<squnion> w * v * top \\<le> v * top\"\n      by (simp add: assms(1,3) comp_associative)\n    have \"(w \\<sqinter> -(prim_EP w v e))\\<^sup>+ * e \\<le> w\\<^sup>+ * e\"\n      by (simp add: comp_isotone star_isotone)\n    also have \"... \\<le> w\\<^sup>\\<star> * e\"\n      by (simp add: mult_left_isotone star.left_plus_below_circ)\n    also have \"... \\<le> v * top\"\n      using 8 by (simp add: comp_associative star_left_induct)\n    finally show ?thesis\n      .\n  qed\n  have 9: \"(prim_P w v e)\\<^sup>T * (w \\<sqinter> -(prim_EP w v e))\\<^sup>+ * e = bot\"\n  proof -\n    have \"(prim_P w v e)\\<^sup>T * (w \\<sqinter> -(prim_EP w v e))\\<^sup>+ * e \\<le> (prim_P w v e)\\<^sup>T * v * top\"\n      using 7 by (simp add: mult_assoc mult_right_isotone)\n    also have \"... = bot\"\n      by (simp add: assms(1) pv)\n    finally show ?thesis\n      using bot_unique by blast\n  qed\n  have 10: \"e * (w \\<sqinter> -(prim_EP w v e))\\<^sup>+ * e = bot\"\n  proof -\n    have \"e * (w \\<sqinter> -(prim_EP w v e))\\<^sup>+ * e \\<le> e * v * top\"\n      using 7 by (simp add: mult_assoc mult_right_isotone)\n    also have \"... \\<le> v * -v\\<^sup>T * v * top\"\n      by (simp add: assms(2) mult_left_isotone)\n    also have \"... = bot\"\n      by (simp add: assms(1) covector_vector_comp mult_assoc)\n    finally show ?thesis\n      using bot_unique by blast\n  qed\n  have 11: \"e * (prim_P w v e)\\<^sup>T\\<^sup>\\<star> * (w \\<sqinter> -(prim_EP w v e))\\<^sup>\\<star> \\<le> v * -v\\<^sup>T\"\n  proof -\n    have 12: \"-v\\<^sup>T * w \\<le> -v\\<^sup>T\"\n      by (metis assms(3) conv_complement order_lesseq_imp pp_increasing schroeder_6_p)\n    have \"v * -v\\<^sup>T * (w \\<sqinter> -(prim_EP w v e)) \\<le> v * -v\\<^sup>T * w\"\n      by (simp add: comp_isotone star_isotone)\n    also have \"... \\<le> v * -v\\<^sup>T\"\n      using 12 by (simp add: comp_isotone comp_associative)\n    finally have 13: \"v * -v\\<^sup>T * (w \\<sqinter> -(prim_EP w v e)) \\<le> v * -v\\<^sup>T\"\n      .\n    have 14: \"(prim_P w v e)\\<^sup>T \\<le> -v * -v\\<^sup>T\"\n      by (metis conv_complement conv_dist_comp conv_involutive conv_order inf_le1 inf_le2 order_trans)\n    have \"e * (prim_P w v e)\\<^sup>T\\<^sup>\\<star> \\<le> v * -v\\<^sup>T * (prim_P w v e)\\<^sup>T\\<^sup>\\<star>\"\n      by (simp add: assms(2) mult_left_isotone)\n    also have \"... = v * -v\\<^sup>T \\<squnion> v * -v\\<^sup>T * (prim_P w v e)\\<^sup>T\\<^sup>+\"\n      by (metis mult_assoc star.circ_back_loop_fixpoint star_plus sup_commute)\n    also have \"... = v * -v\\<^sup>T \\<squnion> v * -v\\<^sup>T * (prim_P w v e)\\<^sup>T\\<^sup>\\<star> * (prim_P w v e)\\<^sup>T\"\n      by (simp add: mult_assoc star_plus)\n    also have \"... \\<le> v * -v\\<^sup>T \\<squnion> v * -v\\<^sup>T * (prim_P w v e)\\<^sup>T\\<^sup>\\<star> * -v * -v\\<^sup>T\"\n      using 14 mult_assoc mult_right_isotone sup_right_isotone by simp\n    also have \"... \\<le> v * -v\\<^sup>T \\<squnion> v * top * -v\\<^sup>T\"\n      by (metis top_greatest mult_right_isotone mult_left_isotone mult_assoc sup_right_isotone)\n    also have \"... = v * -v\\<^sup>T\"\n      by (simp add: assms(1))\n    finally have \"e * (prim_P w v e)\\<^sup>T\\<^sup>\\<star> * (w \\<sqinter> -(prim_EP w v e))\\<^sup>\\<star> \\<le> v * -v\\<^sup>T * (w \\<sqinter> -(prim_EP w v e))\\<^sup>\\<star>\"\n      by (simp add: mult_left_isotone)\n    also have \"... \\<le> v * -v\\<^sup>T\"\n      using 13 by (simp add: star_right_induct_mult)\n    finally show ?thesis\n      .\n  qed\n  have 15: \"(w \\<sqinter> -(prim_EP w v e))\\<^sup>+ * (prim_P w v e)\\<^sup>T\\<^sup>\\<star> * (w \\<sqinter> -(prim_EP w v e))\\<^sup>\\<star> \\<le> -1\"\n  proof -\n    have \"(w \\<sqinter> -(prim_EP w v e))\\<^sup>+ * (prim_P w v e)\\<^sup>T\\<^sup>\\<star> * (w \\<sqinter> -(prim_EP w v e))\\<^sup>\\<star> = (w \\<sqinter> -(prim_EP w v e))\\<^sup>+ * (w \\<sqinter> -(prim_EP w v e))\\<^sup>\\<star>\"\n      using 5 by simp\n    also have \"... = (w \\<sqinter> -(prim_EP w v e))\\<^sup>+\"\n      by (simp add: mult_assoc star.circ_transitive_equal)\n    also have \"... \\<le> w\\<^sup>+\"\n      by (simp add: comp_isotone star_isotone)\n    finally show ?thesis\n      using assms(4) by simp\n  qed\n  have 16: \"(prim_P w v e)\\<^sup>T * (w \\<sqinter> -(prim_EP w v e))\\<^sup>\\<star> * (prim_P w v e)\\<^sup>T\\<^sup>\\<star> * (w \\<sqinter> -(prim_EP w v e))\\<^sup>\\<star> \\<le> -1\"\n  proof -\n    have \"(w \\<sqinter> -(prim_EP w v e))\\<^sup>+ * (prim_P w v e)\\<^sup>T\\<^sup>+ \\<le> (w \\<sqinter> -(prim_EP w v e))\\<^sup>+ * (prim_P w v e)\\<^sup>T\\<^sup>\\<star>\"\n      by (simp add: mult_right_isotone star.left_plus_below_circ)\n    also have \"... = (w \\<sqinter> -(prim_EP w v e))\\<^sup>+\"\n      using 5 by simp\n    also have \"... \\<le> w\\<^sup>+\"\n      by (simp add: comp_isotone star_isotone)\n    finally have \"(w \\<sqinter> -(prim_EP w v e))\\<^sup>+ * (prim_P w v e)\\<^sup>T\\<^sup>+ \\<le> -1\"\n      using assms(4) by simp\n    hence 17: \"(prim_P w v e)\\<^sup>T\\<^sup>+ * (w \\<sqinter> -(prim_EP w v e))\\<^sup>+ \\<le> -1\"\n      by (simp add: comp_commute_below_diversity)\n    have \"(prim_P w v e)\\<^sup>T\\<^sup>+ \\<le> w\\<^sup>T\\<^sup>+\"\n      by (simp add: comp_isotone conv_dist_inf inf.left_commute inf.sup_monoid.add_commute star_isotone)\n    also have \"... = w\\<^sup>+\\<^sup>T\"\n      by (simp add: conv_dist_comp conv_star_commute star_plus)\n    also have \"... \\<le> -1\"\n      using assms(4) conv_complement conv_isotone by force\n    finally have 18: \"(prim_P w v e)\\<^sup>T\\<^sup>+ \\<le> -1\"\n      .\n    have \"(prim_P w v e)\\<^sup>T * (w \\<sqinter> -(prim_EP w v e))\\<^sup>\\<star> * (prim_P w v e)\\<^sup>T\\<^sup>\\<star> * (w \\<sqinter> -(prim_EP w v e))\\<^sup>\\<star> = (prim_P w v e)\\<^sup>T * ((w \\<sqinter> -(prim_EP w v e))\\<^sup>+ \\<squnion> (prim_P w v e)\\<^sup>T\\<^sup>\\<star>) * (w \\<sqinter> -(prim_EP w v e))\\<^sup>\\<star>\"\n      using 6 by (simp add: comp_associative)\n    also have \"... = (prim_P w v e)\\<^sup>T * (w \\<sqinter> -(prim_EP w v e))\\<^sup>+ * (w \\<sqinter> -(prim_EP w v e))\\<^sup>\\<star> \\<squnion> (prim_P w v e)\\<^sup>T\\<^sup>+ * (w \\<sqinter> -(prim_EP w v e))\\<^sup>\\<star>\"\n      by (simp add: mult_left_dist_sup mult_right_dist_sup)\n    also have \"... = (prim_P w v e)\\<^sup>T * (w \\<sqinter> -(prim_EP w v e))\\<^sup>+ \\<squnion> (prim_P w v e)\\<^sup>T\\<^sup>+ * (w \\<sqinter> -(prim_EP w v e))\\<^sup>\\<star>\"\n      by (simp add: mult_assoc star.circ_transitive_equal)\n    also have \"... = (prim_P w v e)\\<^sup>T * (w \\<sqinter> -(prim_EP w v e))\\<^sup>+ \\<squnion> (prim_P w v e)\\<^sup>T\\<^sup>+ * (1 \\<squnion> (w \\<sqinter> -(prim_EP w v e))\\<^sup>+)\"\n      using star_left_unfold_equal by simp\n    also have \"... = (prim_P w v e)\\<^sup>T * (w \\<sqinter> -(prim_EP w v e))\\<^sup>+ \\<squnion> (prim_P w v e)\\<^sup>T\\<^sup>+ * (w \\<sqinter> -(prim_EP w v e))\\<^sup>+ \\<squnion> (prim_P w v e)\\<^sup>T\\<^sup>+\"\n      by (simp add: mult_left_dist_sup sup.left_commute sup_commute)\n    also have \"... = ((prim_P w v e)\\<^sup>T \\<squnion> (prim_P w v e)\\<^sup>T\\<^sup>+) * (w \\<sqinter> -(prim_EP w v e))\\<^sup>+ \\<squnion> (prim_P w v e)\\<^sup>T\\<^sup>+\"\n      by (simp add: mult_right_dist_sup)\n    also have \"... = (prim_P w v e)\\<^sup>T\\<^sup>+ * (w \\<sqinter> -(prim_EP w v e))\\<^sup>+ \\<squnion> (prim_P w v e)\\<^sup>T\\<^sup>+\"\n      using star.circ_mult_increasing by (simp add: le_iff_sup)\n    also have \"... \\<le> -1\"\n      using 17 18 by simp\n    finally show ?thesis\n      .\n  qed\n  have 19: \"e * (w \\<sqinter> -(prim_EP w v e))\\<^sup>\\<star> * (prim_P w v e)\\<^sup>T\\<^sup>\\<star> * (w \\<sqinter> -(prim_EP w v e))\\<^sup>\\<star> \\<le> -1\"\n  proof -\n    have \"e * (w \\<sqinter> -(prim_EP w v e))\\<^sup>\\<star> * (prim_P w v e)\\<^sup>T\\<^sup>\\<star> * (w \\<sqinter> -(prim_EP w v e))\\<^sup>\\<star> = e * ((w \\<sqinter> -(prim_EP w v e))\\<^sup>+ \\<squnion> (prim_P w v e)\\<^sup>T\\<^sup>\\<star>) * (w \\<sqinter> -(prim_EP w v e))\\<^sup>\\<star>\"\n      using 6 by (simp add: mult_assoc)\n    also have \"... = e * (w \\<sqinter> -(prim_EP w v e))\\<^sup>+ * (w \\<sqinter> -(prim_EP w v e))\\<^sup>\\<star> \\<squnion> e * (prim_P w v e)\\<^sup>T\\<^sup>\\<star> * (w \\<sqinter> -(prim_EP w v e))\\<^sup>\\<star>\"\n      by (simp add: mult_left_dist_sup mult_right_dist_sup)\n    also have \"... = e * (w \\<sqinter> -(prim_EP w v e))\\<^sup>+ \\<squnion> e * (prim_P w v e)\\<^sup>T\\<^sup>\\<star> * (w \\<sqinter> -(prim_EP w v e))\\<^sup>\\<star>\"\n      by (simp add: mult_assoc star.circ_transitive_equal)\n    also have \"... \\<le> e * (prim_P w v e)\\<^sup>T\\<^sup>\\<star> * (w \\<sqinter> -(prim_EP w v e))\\<^sup>+ \\<squnion> e * (prim_P w v e)\\<^sup>T\\<^sup>\\<star> * (w \\<sqinter> -(prim_EP w v e))\\<^sup>\\<star>\"\n      by (metis mult_right_sub_dist_sup_right semiring.add_right_mono star.circ_back_loop_fixpoint)\n    also have \"... \\<le> e * (prim_P w v e)\\<^sup>T\\<^sup>\\<star> * (w \\<sqinter> -(prim_EP w v e))\\<^sup>\\<star>\"\n      using mult_right_isotone star.left_plus_below_circ by auto\n    also have \"... \\<le> v * -v\\<^sup>T\"\n      using 11 by simp\n    also have \"... \\<le> -1\"\n      by (simp add: pp_increasing schroeder_3_p)\n    finally show ?thesis\n      .\n  qed\n  have 20: \"(prim_W w v e) * (w \\<sqinter> -(prim_EP w v e))\\<^sup>\\<star> * (prim_P w v e)\\<^sup>T\\<^sup>\\<star> * (w \\<sqinter> -(prim_EP w v e))\\<^sup>\\<star> \\<le> -1\"\n    using 15 16 19 by (simp add: comp_right_dist_sup)\n  have 21: \"(w \\<sqinter> -(prim_EP w v e))\\<^sup>+ * e * (prim_P w v e)\\<^sup>T\\<^sup>\\<star> * (w \\<sqinter> -(prim_EP w v e))\\<^sup>\\<star> \\<le> -1\"\n  proof -\n    have \"(w \\<sqinter> -(prim_EP w v e)) * v * -v\\<^sup>T \\<le> w * v * -v\\<^sup>T\"\n      by (simp add: comp_isotone star_isotone)\n    also have \"... \\<le> v * -v\\<^sup>T\"\n      by (simp add: assms(3) mult_left_isotone)\n    finally have 22: \"(w \\<sqinter> -(prim_EP w v e)) * v * -v\\<^sup>T \\<le> v * -v\\<^sup>T\"\n      .\n    have \"(w \\<sqinter> -(prim_EP w v e))\\<^sup>+ * e * (prim_P w v e)\\<^sup>T\\<^sup>\\<star> * (w \\<sqinter> -(prim_EP w v e))\\<^sup>\\<star> \\<le> (w \\<sqinter> -(prim_EP w v e))\\<^sup>+ * v * -v\\<^sup>T\"\n      using 11 by (simp add: mult_right_isotone mult_assoc)\n    also have \"... \\<le> (w \\<sqinter> -(prim_EP w v e))\\<^sup>\\<star> * v * -v\\<^sup>T\"\n      using mult_left_isotone star.left_plus_below_circ by blast\n    also have \"... \\<le> v * -v\\<^sup>T\"\n      using 22 by (simp add: star_left_induct_mult mult_assoc)\n    also have \"... \\<le> -1\"\n      by (simp add: pp_increasing schroeder_3_p)\n    finally show ?thesis\n      .\n  qed\n  have 23: \"(prim_P w v e)\\<^sup>T * (w \\<sqinter> -(prim_EP w v e))\\<^sup>\\<star> * e * (prim_P w v e)\\<^sup>T\\<^sup>\\<star> * (w \\<sqinter> -(prim_EP w v e))\\<^sup>\\<star> \\<le> -1\"\n  proof -\n    have \"(prim_P w v e)\\<^sup>T * (w \\<sqinter> -(prim_EP w v e))\\<^sup>\\<star> * e = (prim_P w v e)\\<^sup>T * e \\<squnion> (prim_P w v e)\\<^sup>T * (w \\<sqinter> -(prim_EP w v e))\\<^sup>+ * e\"\n      using comp_left_dist_sup mult_assoc star.circ_loop_fixpoint sup_commute by auto\n    also have \"... = bot\"\n      using 1 9 by simp\n    finally show ?thesis\n      by simp\n  qed\n  have 24: \"e * (w \\<sqinter> -(prim_EP w v e))\\<^sup>\\<star> * e * (prim_P w v e)\\<^sup>T\\<^sup>\\<star> * (w \\<sqinter> -(prim_EP w v e))\\<^sup>\\<star> \\<le> -1\"\n  proof -\n    have \"e * (w \\<sqinter> -(prim_EP w v e))\\<^sup>\\<star> * e = e * e \\<squnion> e * (w \\<sqinter> -(prim_EP w v e))\\<^sup>+ * e\"\n      using comp_left_dist_sup mult_assoc star.circ_loop_fixpoint sup_commute by auto\n    also have \"... = bot\"\n      using 2 10 by simp\n    finally show ?thesis\n      by simp\n  qed\n  have 25: \"(prim_W w v e) * (w \\<sqinter> -(prim_EP w v e))\\<^sup>\\<star> * e * (prim_P w v e)\\<^sup>T\\<^sup>\\<star> * (w \\<sqinter> -(prim_EP w v e))\\<^sup>\\<star> \\<le> -1\"\n    using 21 23 24 by (simp add: comp_right_dist_sup)\n  have \"(prim_W w v e)\\<^sup>\\<star> = ((prim_P w v e)\\<^sup>T \\<squnion> e)\\<^sup>\\<star> * ((w \\<sqinter> -(prim_EP w v e)) * ((prim_P w v e)\\<^sup>T \\<squnion> e)\\<^sup>\\<star>)\\<^sup>\\<star>\"\n    by (metis star_sup_1 sup.left_commute sup_commute)\n  also have \"... = ((prim_P w v e)\\<^sup>T\\<^sup>\\<star> \\<squnion> e * (prim_P w v e)\\<^sup>T\\<^sup>\\<star>) * ((w \\<sqinter> -(prim_EP w v e)) * ((prim_P w v e)\\<^sup>T\\<^sup>\\<star> \\<squnion> e * (prim_P w v e)\\<^sup>T\\<^sup>\\<star>))\\<^sup>\\<star>\"\n    using 1 2 star_separate by auto\n  also have \"... = ((prim_P w v e)\\<^sup>T\\<^sup>\\<star> \\<squnion> e * (prim_P w v e)\\<^sup>T\\<^sup>\\<star>) * ((w \\<sqinter> -(prim_EP w v e)) * (1 \\<squnion> e * (prim_P w v e)\\<^sup>T\\<^sup>\\<star>))\\<^sup>\\<star>\"\n    using 4 mult_left_dist_sup by auto\n  also have \"... = (w \\<sqinter> -(prim_EP w v e))\\<^sup>\\<star> * ((prim_P w v e)\\<^sup>T\\<^sup>\\<star> \\<squnion> e * (prim_P w v e)\\<^sup>T\\<^sup>\\<star>) * (w \\<sqinter> -(prim_EP w v e))\\<^sup>\\<star>\"\n    using 3 9 10 star_separate_2 by blast\n  also have \"... = (w \\<sqinter> -(prim_EP w v e))\\<^sup>\\<star> * (prim_P w v e)\\<^sup>T\\<^sup>\\<star> * (w \\<sqinter> -(prim_EP w v e))\\<^sup>\\<star> \\<squnion> (w \\<sqinter> -(prim_EP w v e))\\<^sup>\\<star> * e * (prim_P w v e)\\<^sup>T\\<^sup>\\<star> * (w \\<sqinter> -(prim_EP w v e))\\<^sup>\\<star>\"\n    by (simp add: semiring.distrib_left semiring.distrib_right mult_assoc)\n  finally have \"(prim_W w v e)\\<^sup>+ = (prim_W w v e) * ((w \\<sqinter> -(prim_EP w v e))\\<^sup>\\<star> * (prim_P w v e)\\<^sup>T\\<^sup>\\<star> * (w \\<sqinter> -(prim_EP w v e))\\<^sup>\\<star> \\<squnion> (w \\<sqinter> -(prim_EP w v e))\\<^sup>\\<star> * e * (prim_P w v e)\\<^sup>T\\<^sup>\\<star> * (w \\<sqinter> -(prim_EP w v e))\\<^sup>\\<star>)\"\n    by simp\n  also have \"... = (prim_W w v e) * (w \\<sqinter> -(prim_EP w v e))\\<^sup>\\<star> * (prim_P w v e)\\<^sup>T\\<^sup>\\<star> * (w \\<sqinter> -(prim_EP w v e))\\<^sup>\\<star> \\<squnion> (prim_W w v e) * (w \\<sqinter> -(prim_EP w v e))\\<^sup>\\<star> * e * (prim_P w v e)\\<^sup>T\\<^sup>\\<star> * (w \\<sqinter> -(prim_EP w v e))\\<^sup>\\<star>\"\n    by (simp add: comp_left_dist_sup comp_associative)\n  also have \"... \\<le> -1\"\n    using 20 25 by simp\n  finally show ?thesis\n    .\nqed\n\ntext \\<open>\nThe following lemma shows that an edge across the cut between visited nodes and unvisited nodes does not leave the component of visited nodes.\n\\<close>\n\nlemma mst_subgraph_inv:\n  assumes \"e \\<le> v * -v\\<^sup>T \\<sqinter> g\"\n      and \"t \\<le> g\"\n      and \"v\\<^sup>T = r\\<^sup>T * t\\<^sup>\\<star>\"\n    shows \"e \\<le> (r\\<^sup>T * g\\<^sup>\\<star>)\\<^sup>T * (r\\<^sup>T * g\\<^sup>\\<star>) \\<sqinter> g\"\nproof -\n  have \"e \\<le> v * -v\\<^sup>T \\<sqinter> g\"\n    by (rule assms(1))\n  also have \"... \\<le> v * (-v\\<^sup>T \\<sqinter> v\\<^sup>T * g) \\<sqinter> g\"\n    by (simp add: dedekind_1)\n  also have \"... \\<le> v * v\\<^sup>T * g \\<sqinter> g\"\n    by (simp add: comp_associative comp_right_isotone inf_commute le_infI2)\n  also have \"... = v * (r\\<^sup>T * t\\<^sup>\\<star>) * g \\<sqinter> g\"\n    by (simp add: assms(3))\n  also have \"... = (r\\<^sup>T * t\\<^sup>\\<star>)\\<^sup>T * (r\\<^sup>T * t\\<^sup>\\<star>) * g \\<sqinter> g\"\n    by (metis assms(3) conv_involutive)\n  also have \"... \\<le> (r\\<^sup>T * t\\<^sup>\\<star>)\\<^sup>T * (r\\<^sup>T * g\\<^sup>\\<star>) * g \\<sqinter> g\"\n    using assms(2) comp_inf.mult_left_isotone comp_isotone star_isotone by auto\n  also have \"... \\<le> (r\\<^sup>T * t\\<^sup>\\<star>)\\<^sup>T * (r\\<^sup>T * g\\<^sup>\\<star>) \\<sqinter> g\"\n    using inf.sup_right_isotone inf_commute mult_assoc mult_right_isotone star.left_plus_below_circ star_plus by presburger\n  also have \"... \\<le> (r\\<^sup>T * g\\<^sup>\\<star>)\\<^sup>T * (r\\<^sup>T * g\\<^sup>\\<star>) \\<sqinter> g\"\n    using assms(2) comp_inf.mult_left_isotone conv_dist_comp conv_isotone mult_left_isotone star_isotone by auto\n  finally show ?thesis\n    .\nqed\n\ntext \\<open>\nThe following lemmas show that the tree after exchanging contains the currently constructed and tree and its extension by the chosen edge.\n\\<close>\n\nlemma mst_extends_old_tree:\n  assumes \"t \\<le> w\"\n      and \"t \\<le> v * v\\<^sup>T\"\n      and \"vector v\"\n    shows \"t \\<le> prim_W w v e\"\nproof -\n  have \"t \\<sqinter> prim_EP w v e \\<le> t \\<sqinter> -v\\<^sup>T\"\n    by (simp add: inf.coboundedI2 inf.sup_monoid.add_assoc)\n  also have \"... \\<le> v * v\\<^sup>T \\<sqinter> -v\\<^sup>T\"\n    by (simp add: assms(2) inf.coboundedI1)\n  also have \"... \\<le> bot\"\n    by (simp add: assms(3) covector_vector_comp eq_refl schroeder_2)\n  finally have \"t \\<le> -(prim_EP w v e)\"\n    using le_bot pseudo_complement by blast\n  hence \"t \\<le> w \\<sqinter> -(prim_EP w v e)\"\n    using assms(1) by simp\n  thus ?thesis\n    using le_supI1 by blast\nqed\n\nlemma mst_extends_new_tree:\n  \"t \\<le> w \\<Longrightarrow> t \\<le> v * v\\<^sup>T \\<Longrightarrow> vector v \\<Longrightarrow> t \\<squnion> e \\<le> prim_W w v e\"\n  using mst_extends_old_tree by auto\n\nlemma forests_bot_1:\n  assumes \"equivalence e\"\n      and \"forest f\"\n    shows \"(-e \\<sqinter> f) * (e \\<sqinter> f)\\<^sup>T = bot\"\nproof -\n  have \"f * f\\<^sup>T \\<le> e\"\n    using assms dual_order.trans by blast\n  hence \"f * (e \\<sqinter> f)\\<^sup>T \\<le> e\"\n    by (metis conv_dist_inf inf.boundedE inf.cobounded2 inf.orderE mult_right_isotone)\n  hence \"-e \\<sqinter> f * (e \\<sqinter> f)\\<^sup>T = bot\"\n    by (simp add: p_antitone pseudo_complement)\n  thus ?thesis\n    by (metis assms(1) comp_isotone conv_dist_inf equivalence_comp_right_complement inf.boundedI inf.cobounded1 inf.cobounded2 le_bot)\nqed\n\nlemma forests_bot_2:\n  assumes \"equivalence e\"\n      and \"forest f\"\n    shows \"(-e \\<sqinter> f\\<^sup>T) * x \\<sqinter> (e \\<sqinter> f\\<^sup>T) * y = bot\"\nproof -\n  have \"(-e \\<sqinter> f) * (e \\<sqinter> f\\<^sup>T) = bot\"\n    using assms forests_bot_1 conv_dist_inf by simp\n  thus ?thesis\n    by (smt assms(1) comp_associative comp_inf.semiring.mult_not_zero conv_complement conv_dist_comp conv_dist_inf conv_involutive dedekind_1 inf.cobounded2 inf.sup_monoid.add_commute le_bot mult_right_zero p_antitone_iff pseudo_complement semiring.mult_not_zero symmetric_top_closed top.extremum)\nqed\n\nlemma forests_bot_3:\n  assumes \"equivalence e\"\n      and \"forest f\"\n    shows \"x * (-e \\<sqinter> f) \\<sqinter> y * (e \\<sqinter> f) = bot\"\nproof -\n  have \"(e \\<sqinter> f) * (-e \\<sqinter> f\\<^sup>T) = bot\"\n    using assms forests_bot_1 conv_dist_inf conv_complement by (smt conv_dist_comp conv_involutive conv_order coreflexive_bot_closed coreflexive_symmetric)\n  hence \"y * (e \\<sqinter> f) * (-e \\<sqinter> f\\<^sup>T) = bot\"\n    by (simp add: comp_associative)\n  hence 1: \"x \\<sqinter> y * (e \\<sqinter> f) * (-e \\<sqinter> f\\<^sup>T) = bot\"\n    using comp_inf.semiring.mult_not_zero by blast\n  hence \"(x \\<sqinter> y * (e \\<sqinter> f) * (-e \\<sqinter> f\\<^sup>T)) * (-e \\<sqinter> f) = bot\"\n    using semiring.mult_not_zero by blast\n  hence \"x * (-e \\<sqinter> f\\<^sup>T)\\<^sup>T \\<sqinter> y * (e \\<sqinter> f) = bot\"\n    using 1 dedekind_2 inf_commute schroeder_2 by auto\n  thus ?thesis\n    by (simp add: assms(1) conv_complement conv_dist_inf)\nqed\n\nend\n\ntext \\<open>\nWe finally add the Kleene star to Stone relation algebras.\nKleene star and the relational operations are reasonably independent.\nThe only additional axiom we need in the generalisation to Stone-Kleene relation algebras is that star distributes over double complement.\n\\<close>\n\nclass stone_kleene_relation_algebra = stone_relation_algebra + pd_kleene_allegory +\n  assumes pp_dist_star: \"--(x\\<^sup>\\<star>) = (--x)\\<^sup>\\<star>\"\nbegin\n\nlemma regular_closed_star:\n  \"regular x \\<Longrightarrow> regular (x\\<^sup>\\<star>)\"\n  by (simp add: pp_dist_star)\n\nlemma components_idempotent:\n  \"components (components x) = components x\"\n  using pp_dist_star star_involutive by auto\n\nlemma fc_comp_eq_fc:\n  \"-forest_components (--f) = -forest_components f\"\n  by (metis conv_complement p_comp_pp p_pp_comp pp_dist_star)\n\ntext \\<open>\nThe following lemma shows that the nodes reachable in the tree after exchange contain the nodes reachable in the tree before exchange.\n\\<close>\n\nlemma mst_reachable_inv:\n  assumes \"regular (prim_EP w v e)\"\n      and \"vector r\"\n      and \"e \\<le> v * -v\\<^sup>T\"\n      and \"vector v\"\n      and \"v\\<^sup>T = r\\<^sup>T * t\\<^sup>\\<star>\"\n      and \"t \\<le> w\"\n      and \"t \\<le> v * v\\<^sup>T\"\n      and \"w * v \\<le> v\"\n    shows \"r\\<^sup>T * w\\<^sup>\\<star> \\<le> r\\<^sup>T * (prim_W w v e)\\<^sup>\\<star>\"\nproof -\n  have 1: \"r\\<^sup>T \\<le> r\\<^sup>T * (prim_W w v e)\\<^sup>\\<star>\"\n    using sup.bounded_iff star.circ_back_loop_prefixpoint by blast\n  have \"top * e * (w\\<^sup>T \\<sqinter> -v\\<^sup>T)\\<^sup>\\<star> * w\\<^sup>T \\<sqinter> -v\\<^sup>T = top * e * (w\\<^sup>T \\<sqinter> -v\\<^sup>T)\\<^sup>\\<star> * (w\\<^sup>T \\<sqinter> -v\\<^sup>T)\"\n    by (simp add: assms(4) covector_comp_inf vector_conv_compl)\n  also have \"... \\<le> top * e * (w\\<^sup>T \\<sqinter> -v\\<^sup>T)\\<^sup>\\<star>\"\n    by (simp add: comp_isotone mult_assoc star.circ_plus_same star.left_plus_below_circ)\n  finally have 2: \"top * e * (w\\<^sup>T \\<sqinter> -v\\<^sup>T)\\<^sup>\\<star> * w\\<^sup>T \\<le> top * e * (w\\<^sup>T \\<sqinter> -v\\<^sup>T)\\<^sup>\\<star> \\<squnion> --v\\<^sup>T\"\n    by (simp add: shunting_var_p)\n  have 3: \"--v\\<^sup>T * w\\<^sup>T \\<le> top * e * (w\\<^sup>T \\<sqinter> -v\\<^sup>T)\\<^sup>\\<star> \\<squnion> --v\\<^sup>T\"\n    by (metis assms(8) conv_dist_comp conv_order mult_assoc order.trans pp_comp_semi_commute pp_isotone sup.coboundedI1 sup_commute)\n  have 4: \"top * e \\<le> top * e * (w\\<^sup>T \\<sqinter> -v\\<^sup>T)\\<^sup>\\<star> \\<squnion> --v\\<^sup>T\"\n    using sup_right_divisibility star.circ_back_loop_fixpoint le_supI1 by blast\n  have \"(top * e * (w\\<^sup>T \\<sqinter> -v\\<^sup>T)\\<^sup>\\<star> \\<squnion> --v\\<^sup>T) * w\\<^sup>T = top * e * (w\\<^sup>T \\<sqinter> -v\\<^sup>T)\\<^sup>\\<star> * w\\<^sup>T \\<squnion> --v\\<^sup>T * w\\<^sup>T\"\n    by (simp add: comp_right_dist_sup)\n  also have \"... \\<le> top * e * (w\\<^sup>T \\<sqinter> -v\\<^sup>T)\\<^sup>\\<star> \\<squnion> --v\\<^sup>T\"\n    using 2 3 by simp\n  finally have \"top * e \\<squnion> (top * e * (w\\<^sup>T \\<sqinter> -v\\<^sup>T)\\<^sup>\\<star> \\<squnion> --v\\<^sup>T) * w\\<^sup>T \\<le> top * e * (w\\<^sup>T \\<sqinter> -v\\<^sup>T)\\<^sup>\\<star> \\<squnion> --v\\<^sup>T\"\n    using 4 by simp\n  hence 5: \"top * e * w\\<^sup>T\\<^sup>\\<star> \\<le> top * e * (w\\<^sup>T \\<sqinter> -v\\<^sup>T)\\<^sup>\\<star> \\<squnion> --v\\<^sup>T\"\n    by (simp add: star_right_induct)\n  have 6: \"top * e \\<le> top * e * (w\\<^sup>T \\<sqinter> -v * -v\\<^sup>T \\<sqinter> w\\<^sup>\\<star> * e\\<^sup>T * top)\\<^sup>\\<star>\"\n    using sup_right_divisibility star.circ_back_loop_fixpoint by blast\n  have \"(top * e * (w\\<^sup>T \\<sqinter> -v * -v\\<^sup>T \\<sqinter> w\\<^sup>\\<star> * e\\<^sup>T * top)\\<^sup>\\<star>)\\<^sup>T \\<le> (top * e * w\\<^sup>T\\<^sup>\\<star>)\\<^sup>T\"\n    by (simp add: star_isotone mult_right_isotone conv_isotone inf_assoc)\n  also have \"... = w\\<^sup>\\<star> * e\\<^sup>T * top\"\n    by (simp add: conv_dist_comp conv_star_commute mult_assoc)\n  finally have 7: \"(top * e * (w\\<^sup>T \\<sqinter> -v * -v\\<^sup>T \\<sqinter> w\\<^sup>\\<star> * e\\<^sup>T * top)\\<^sup>\\<star>)\\<^sup>T \\<le> w\\<^sup>\\<star> * e\\<^sup>T * top\"\n    .\n  have \"(top * e * (w\\<^sup>T \\<sqinter> -v * -v\\<^sup>T \\<sqinter> w\\<^sup>\\<star> * e\\<^sup>T * top)\\<^sup>\\<star>)\\<^sup>T \\<le> (top * e * (-v * -v\\<^sup>T)\\<^sup>\\<star>)\\<^sup>T\"\n    by (simp add: conv_isotone inf_commute mult_right_isotone star_isotone le_infI2)\n  also have \"... \\<le> (top * v * -v\\<^sup>T * (-v * -v\\<^sup>T)\\<^sup>\\<star>)\\<^sup>T\"\n    by (metis assms(3) conv_isotone mult_left_isotone mult_right_isotone mult_assoc)\n  also have \"... = (top * v * (-v\\<^sup>T * -v)\\<^sup>\\<star> * -v\\<^sup>T)\\<^sup>T\"\n    by (simp add: mult_assoc star_slide)\n  also have \"... \\<le> (top * -v\\<^sup>T)\\<^sup>T\"\n    using conv_order mult_left_isotone by auto\n  also have \"... = -v\"\n    by (simp add: assms(4) conv_complement vector_conv_compl)\n  finally have 8: \"(top * e * (w\\<^sup>T \\<sqinter> -v * -v\\<^sup>T \\<sqinter> w\\<^sup>\\<star> * e\\<^sup>T * top)\\<^sup>\\<star>)\\<^sup>T \\<le> w\\<^sup>\\<star> * e\\<^sup>T * top \\<sqinter> -v\"\n    using 7 by simp\n  have \"covector (top * e * (w\\<^sup>T \\<sqinter> -v * -v\\<^sup>T \\<sqinter> w\\<^sup>\\<star> * e\\<^sup>T * top)\\<^sup>\\<star>)\"\n    by (simp add: covector_mult_closed)\n  hence \"top * e * (w\\<^sup>T \\<sqinter> -v * -v\\<^sup>T \\<sqinter> w\\<^sup>\\<star> * e\\<^sup>T * top)\\<^sup>\\<star> * (w\\<^sup>T \\<sqinter> -v\\<^sup>T) = top * e * (w\\<^sup>T \\<sqinter> -v * -v\\<^sup>T \\<sqinter> w\\<^sup>\\<star> * e\\<^sup>T * top)\\<^sup>\\<star> * (w\\<^sup>T \\<sqinter> -v\\<^sup>T \\<sqinter> (top * e * (w\\<^sup>T \\<sqinter> -v * -v\\<^sup>T \\<sqinter> w\\<^sup>\\<star> * e\\<^sup>T * top)\\<^sup>\\<star>)\\<^sup>T)\"\n    by (metis comp_inf_vector_1 inf.idem)\n  also have \"... \\<le> top * e * (w\\<^sup>T \\<sqinter> -v * -v\\<^sup>T \\<sqinter> w\\<^sup>\\<star> * e\\<^sup>T * top)\\<^sup>\\<star> * (w\\<^sup>T \\<sqinter> -v\\<^sup>T \\<sqinter> w\\<^sup>\\<star> * e\\<^sup>T * top \\<sqinter> -v)\"\n    using 8 mult_right_isotone inf.sup_right_isotone inf_assoc by simp\n  also have \"... = top * e * (w\\<^sup>T \\<sqinter> -v * -v\\<^sup>T \\<sqinter> w\\<^sup>\\<star> * e\\<^sup>T * top)\\<^sup>\\<star> * (w\\<^sup>T \\<sqinter> (-v \\<sqinter> -v\\<^sup>T) \\<sqinter> w\\<^sup>\\<star> * e\\<^sup>T * top)\"\n    using inf_assoc inf_commute by (simp add: inf_assoc)\n  also have \"... = top * e * (w\\<^sup>T \\<sqinter> -v * -v\\<^sup>T \\<sqinter> w\\<^sup>\\<star> * e\\<^sup>T * top)\\<^sup>\\<star> * (w\\<^sup>T \\<sqinter> -v * -v\\<^sup>T \\<sqinter> w\\<^sup>\\<star> * e\\<^sup>T * top)\"\n    using assms(4) conv_complement vector_complement_closed vector_covector by fastforce\n  also have \"... \\<le> top * e * (w\\<^sup>T \\<sqinter> -v * -v\\<^sup>T \\<sqinter> w\\<^sup>\\<star> * e\\<^sup>T * top)\\<^sup>\\<star>\"\n    by (simp add: comp_associative comp_isotone star.circ_plus_same star.left_plus_below_circ)\n  finally have 9: \"top * e \\<squnion> top * e * (w\\<^sup>T \\<sqinter> -v * -v\\<^sup>T \\<sqinter> w\\<^sup>\\<star> * e\\<^sup>T * top)\\<^sup>\\<star> * (w\\<^sup>T \\<sqinter> -v\\<^sup>T) \\<le> top * e * (w\\<^sup>T \\<sqinter> -v * -v\\<^sup>T \\<sqinter> w\\<^sup>\\<star> * e\\<^sup>T * top)\\<^sup>\\<star>\"\n    using 6 by simp\n  have \"prim_EP w v e \\<le> -v\\<^sup>T \\<sqinter> top * e * w\\<^sup>T\\<^sup>\\<star>\"\n    using inf.sup_left_isotone by auto\n  also have \"... \\<le> top * e * (w\\<^sup>T \\<sqinter> -v\\<^sup>T)\\<^sup>\\<star>\"\n    using 5 by (metis inf_commute shunting_var_p)\n  also have \"... \\<le> top * e * (w\\<^sup>T \\<sqinter> -v * -v\\<^sup>T \\<sqinter> w\\<^sup>\\<star> * e\\<^sup>T * top)\\<^sup>\\<star>\"\n    using 9 by (simp add: star_right_induct)\n  finally have 10: \"prim_EP w v e \\<le> top * e * (prim_P w v e)\\<^sup>T\\<^sup>\\<star>\"\n    by (simp add: conv_complement conv_dist_comp conv_dist_inf conv_star_commute mult_assoc)\n  have \"top * e = top * (v * -v\\<^sup>T \\<sqinter> e)\"\n    by (simp add: assms(3) inf.absorb2)\n  also have \"... \\<le> top * (v * top \\<sqinter> e)\"\n    using inf.sup_right_isotone inf_commute mult_right_isotone top_greatest by presburger\n  also have \"... = (top \\<sqinter> (v * top)\\<^sup>T) * e\"\n    using assms(4) covector_inf_comp_3 by presburger\n  also have \"... = top * v\\<^sup>T * e\"\n    by (simp add: conv_dist_comp)\n  also have \"... = top * r\\<^sup>T * t\\<^sup>\\<star> * e\"\n    by (simp add: assms(5) comp_associative)\n  also have \"... \\<le> top * r\\<^sup>T * (prim_W w v e)\\<^sup>\\<star> * e\"\n    by (metis assms(4,6,7) mst_extends_old_tree star_isotone mult_left_isotone mult_right_isotone)\n  finally have 11: \"top * e \\<le> top * r\\<^sup>T * (prim_W w v e)\\<^sup>\\<star> * e\"\n    .\n  have \"r\\<^sup>T * (prim_W w v e)\\<^sup>\\<star> * (prim_EP w v e) \\<le> r\\<^sup>T * (prim_W w v e)\\<^sup>\\<star> * (top * e * (prim_P w v e)\\<^sup>T\\<^sup>\\<star>)\"\n    using 10 mult_right_isotone by blast\n  also have \"... = r\\<^sup>T * (prim_W w v e)\\<^sup>\\<star> * top * e * (prim_P w v e)\\<^sup>T\\<^sup>\\<star>\"\n    by (simp add: mult_assoc)\n  also have \"... \\<le> top * e * (prim_P w v e)\\<^sup>T\\<^sup>\\<star>\"\n    by (metis comp_associative comp_inf_covector inf.idem inf.sup_right_divisibility)\n  also have \"... \\<le> top * r\\<^sup>T * (prim_W w v e)\\<^sup>\\<star> * e * (prim_P w v e)\\<^sup>T\\<^sup>\\<star>\"\n    using 11 by (simp add: mult_left_isotone)\n  also have \"... = r\\<^sup>T * (prim_W w v e)\\<^sup>\\<star> * e * (prim_P w v e)\\<^sup>T\\<^sup>\\<star>\"\n    using assms(2) vector_conv_covector by auto\n  also have \"... \\<le> r\\<^sup>T * (prim_W w v e)\\<^sup>\\<star> * (prim_W w v e) * (prim_P w v e)\\<^sup>T\\<^sup>\\<star>\"\n    by (simp add: mult_left_isotone mult_right_isotone)\n  also have \"... \\<le> r\\<^sup>T * (prim_W w v e)\\<^sup>\\<star> * (prim_W w v e) * (prim_W w v e)\\<^sup>\\<star>\"\n    by (meson dual_order.trans mult_right_isotone star_isotone sup_ge1 sup_ge2)\n  also have \"... \\<le> r\\<^sup>T * (prim_W w v e)\\<^sup>\\<star>\"\n    by (metis mult_assoc mult_right_isotone star.circ_transitive_equal star.left_plus_below_circ)\n  finally have 12: \"r\\<^sup>T * (prim_W w v e)\\<^sup>\\<star> * (prim_EP w v e) \\<le> r\\<^sup>T * (prim_W w v e)\\<^sup>\\<star>\"\n    .\n  have \"r\\<^sup>T * (prim_W w v e)\\<^sup>\\<star> * w \\<le> r\\<^sup>T * (prim_W w v e)\\<^sup>\\<star> * (w \\<squnion> prim_EP w v e)\"\n    by (simp add: inf_assoc)\n  also have \"... = r\\<^sup>T * (prim_W w v e)\\<^sup>\\<star> * ((w \\<squnion> prim_EP w v e) \\<sqinter> (-(prim_EP w v e) \\<squnion> prim_EP w v e))\"\n    by (metis assms(1) inf_top_right stone)\n  also have \"... = r\\<^sup>T * (prim_W w v e)\\<^sup>\\<star> * ((w \\<sqinter> -(prim_EP w v e)) \\<squnion> prim_EP w v e)\"\n    by (simp add: sup_inf_distrib2)\n  also have \"... = r\\<^sup>T * (prim_W w v e)\\<^sup>\\<star> * (w \\<sqinter> -(prim_EP w v e)) \\<squnion> r\\<^sup>T * (prim_W w v e)\\<^sup>\\<star> * (prim_EP w v e)\"\n    by (simp add: comp_left_dist_sup)\n  also have \"... \\<le> r\\<^sup>T * (prim_W w v e)\\<^sup>\\<star> * (prim_W w v e) \\<squnion> r\\<^sup>T * (prim_W w v e)\\<^sup>\\<star> * (prim_EP w v e)\"\n    using mult_right_isotone sup_left_isotone by auto\n  also have \"... \\<le> r\\<^sup>T * (prim_W w v e)\\<^sup>\\<star> \\<squnion> r\\<^sup>T * (prim_W w v e)\\<^sup>\\<star> * (prim_EP w v e)\"\n    using mult_assoc mult_right_isotone star.circ_plus_same star.left_plus_below_circ sup_left_isotone by auto\n  also have \"... = r\\<^sup>T * (prim_W w v e)\\<^sup>\\<star>\"\n    using 12 sup.absorb1 by blast\n  finally have \"r\\<^sup>T \\<squnion> r\\<^sup>T * (prim_W w v e)\\<^sup>\\<star> * w \\<le> r\\<^sup>T * (prim_W w v e)\\<^sup>\\<star>\"\n    using 1 by simp\n  thus ?thesis\n    by (simp add: star_right_induct)\nqed\n\ntext \\<open>\nSome of the following lemmas already hold in pseudocomplemented distributive Kleene allegories.\n\\<close>\n\nsubsubsection \\<open>Exchange gives Minimum Spanning Trees\\<close>\n\ntext \\<open>\nThe lemmas in this section are used to show that the after exchange we obtain a minimum spanning tree.\nThe following lemmas show various interactions between the three constituents of the tree after exchange.\n\\<close>\n\nlemma epm_1:\n  \"vector v \\<Longrightarrow> prim_E w v e \\<squnion> prim_P w v e = prim_EP w v e\"\n  by (metis inf_commute inf_sup_distrib1 mult_assoc mult_right_dist_sup regular_closed_p regular_complement_top vector_conv_compl)\n\nlemma epm_2:\n  assumes \"regular (prim_EP w v e)\"\n      and \"vector v\"\n    shows \"(w \\<sqinter> -(prim_EP w v e)) \\<squnion> prim_P w v e \\<squnion> prim_E w v e = w\"\nproof -\n  have \"(w \\<sqinter> -(prim_EP w v e)) \\<squnion> prim_P w v e \\<squnion> prim_E w v e = (w \\<sqinter> -(prim_EP w v e)) \\<squnion> prim_EP w v e\"\n    using epm_1 sup_assoc sup_commute assms(2) by (simp add: inf_sup_distrib1)\n  also have \"... = w \\<squnion> prim_EP w v e\"\n    by (metis assms(1) inf_top.right_neutral regular_complement_top sup_inf_distrib2)\n  also have \"... = w\"\n    by (simp add: sup_inf_distrib1)\n  finally show ?thesis\n    .\nqed\n\nlemma epm_4:\n  assumes \"e \\<le> w\"\n      and \"injective w\"\n      and \"w * v \\<le> v\"\n      and \"e \\<le> v * -v\\<^sup>T\"\n    shows \"top * e * w\\<^sup>T\\<^sup>+ \\<le> top * v\\<^sup>T\"\nproof -\n  have \"w\\<^sup>\\<star> * v \\<le> v\"\n    by (simp add: assms(3) star_left_induct_mult)\n  hence 1: \"v\\<^sup>T * w\\<^sup>T\\<^sup>\\<star> \\<le> v\\<^sup>T\"\n    using conv_star_commute conv_dist_comp conv_isotone by fastforce\n  have \"e * w\\<^sup>T \\<le> w * w\\<^sup>T \\<sqinter> e * w\\<^sup>T\"\n    by (simp add: assms(1) mult_left_isotone)\n  also have \"... \\<le> 1 \\<sqinter> e * w\\<^sup>T\"\n    using assms(2) inf.sup_left_isotone by auto\n  also have \"... = 1 \\<sqinter> w * e\\<^sup>T\"\n    using calculation conv_dist_comp conv_involutive coreflexive_symmetric by fastforce\n  also have \"... \\<le> w * e\\<^sup>T\"\n    by simp\n  also have \"... \\<le> w * -v * v\\<^sup>T\"\n    by (metis assms(4) conv_complement conv_dist_comp conv_involutive conv_order mult_assoc mult_right_isotone)\n  also have \"... \\<le> top * v\\<^sup>T\"\n    by (simp add: mult_left_isotone)\n  finally have \"top * e * w\\<^sup>T\\<^sup>+ \\<le> top * v\\<^sup>T * w\\<^sup>T\\<^sup>\\<star>\"\n    by (metis antisym comp_associative comp_isotone dense_top_closed mult_left_isotone transitive_top_closed)\n  also have \"... \\<le> top * v\\<^sup>T\"\n    using 1 by (simp add: mult_assoc mult_right_isotone)\n  finally show ?thesis\n    .\nqed\n\nlemma epm_5:\n  assumes \"e \\<le> w\"\n      and \"injective w\"\n      and \"w * v \\<le> v\"\n      and \"e \\<le> v * -v\\<^sup>T\"\n      and \"vector v\"\n    shows \"prim_P w v e = bot\"\nproof -\n  have 1: \"e = w \\<sqinter> top * e\"\n    by (simp add: assms(1,2) epm_3)\n  have 2: \"top * e * w\\<^sup>T\\<^sup>+ \\<le> top * v\\<^sup>T\"\n    by (simp add: assms(1-4) epm_4)\n  have 3: \"-v * -v\\<^sup>T \\<sqinter> top * v\\<^sup>T = bot\"\n    by (simp add: assms(5) comp_associative covector_vector_comp inf.sup_monoid.add_commute schroeder_2)\n  have \"prim_P w v e = (w \\<sqinter> -v * -v\\<^sup>T \\<sqinter> top * e) \\<squnion> (w \\<sqinter> -v * -v\\<^sup>T \\<sqinter> top * e * w\\<^sup>T\\<^sup>+)\"\n    by (metis inf_sup_distrib1 mult_assoc star.circ_back_loop_fixpoint star_plus sup_commute)\n  also have \"... \\<le> (e \\<sqinter> -v * -v\\<^sup>T) \\<squnion> (w \\<sqinter> -v * -v\\<^sup>T \\<sqinter> top * e * w\\<^sup>T\\<^sup>+)\"\n    using 1 by (metis comp_inf.mult_semi_associative inf.sup_monoid.add_commute semiring.add_right_mono)\n  also have \"... \\<le> (e \\<sqinter> -v * -v\\<^sup>T) \\<squnion> (w \\<sqinter> -v * -v\\<^sup>T \\<sqinter> top * v\\<^sup>T)\"\n    using 2 by (metis sup_right_isotone inf.sup_right_isotone)\n  also have \"... \\<le> (e \\<sqinter> -v * -v\\<^sup>T) \\<squnion> (-v * -v\\<^sup>T \\<sqinter> top * v\\<^sup>T)\"\n    using inf.assoc le_infI2 by auto\n  also have \"... \\<le> v * -v\\<^sup>T \\<sqinter> -v * -v\\<^sup>T\"\n    using 3 assms(4) inf.sup_left_isotone by auto\n  also have \"... \\<le> v * top \\<sqinter> -v * top\"\n    using inf.sup_mono mult_right_isotone top_greatest by blast\n  also have \"... = bot\"\n    using assms(5) inf_compl_bot vector_complement_closed by auto\n  finally show ?thesis\n    by (simp add: le_iff_inf)\nqed\n\nlemma epm_6:\n  assumes \"e \\<le> w\"\n      and \"injective w\"\n      and \"w * v \\<le> v\"\n      and \"e \\<le> v * -v\\<^sup>T\"\n      and \"vector v\"\n    shows \"prim_E w v e = e\"\nproof -\n  have 1: \"e \\<le> --v * -v\\<^sup>T\"\n    using assms(4) mult_isotone order_lesseq_imp pp_increasing by blast\n  have 2: \"top * e * w\\<^sup>T\\<^sup>+ \\<le> top * v\\<^sup>T\"\n    by (simp add: assms(1-4) epm_4)\n  have 3: \"e = w \\<sqinter> top * e\"\n    by (simp add: assms(1,2) epm_3)\n  hence \"e \\<le> top * e * w\\<^sup>T\\<^sup>\\<star>\"\n    by (metis le_infI2 star.circ_back_loop_fixpoint sup.commute sup_ge1)\n  hence 4: \"e \\<le> prim_E w v e\"\n    using 1 by (simp add: assms(1))\n  have 5: \"--v * -v\\<^sup>T \\<sqinter> top * v\\<^sup>T = bot\"\n    by (simp add: assms(5) comp_associative covector_vector_comp inf.sup_monoid.add_commute schroeder_2)\n  have \"prim_E w v e = (w \\<sqinter> --v * -v\\<^sup>T \\<sqinter> top * e) \\<squnion> (w \\<sqinter> --v * -v\\<^sup>T \\<sqinter> top * e * w\\<^sup>T\\<^sup>+)\"\n    by (metis inf_sup_distrib1 mult_assoc star.circ_back_loop_fixpoint star_plus sup_commute)\n  also have \"... \\<le> (e \\<sqinter> --v * -v\\<^sup>T) \\<squnion> (w \\<sqinter> --v * -v\\<^sup>T \\<sqinter> top * e * w\\<^sup>T\\<^sup>+)\"\n    using 3 by (metis comp_inf.mult_semi_associative inf.sup_monoid.add_commute semiring.add_right_mono)\n  also have \"... \\<le> (e \\<sqinter> --v * -v\\<^sup>T) \\<squnion> (w \\<sqinter> --v * -v\\<^sup>T \\<sqinter> top * v\\<^sup>T)\"\n    using 2 by (metis sup_right_isotone inf.sup_right_isotone)\n  also have \"... \\<le> (e \\<sqinter> --v * -v\\<^sup>T) \\<squnion> (--v * -v\\<^sup>T \\<sqinter> top * v\\<^sup>T)\"\n    using inf.assoc le_infI2 by auto\n  also have \"... \\<le> e\"\n    by (simp add: \"5\")\n  finally show ?thesis\n    using 4 by (simp add: antisym)\nqed\n\nlemma epm_7:\n  \"regular (prim_EP w v e) \\<Longrightarrow> e \\<le> w \\<Longrightarrow> injective w \\<Longrightarrow> w * v \\<le> v \\<Longrightarrow> e \\<le> v * -v\\<^sup>T \\<Longrightarrow> vector v \\<Longrightarrow> prim_W w v e = w\"\n  by (metis conv_bot epm_2 epm_5 epm_6)\n\nlemma epm_8:\n  assumes \"acyclic w\"\n    shows \"(w \\<sqinter> -(prim_EP w v e)) \\<sqinter> (prim_P w v e)\\<^sup>T = bot\"\nproof -\n  have \"(w \\<sqinter> -(prim_EP w v e)) \\<sqinter> (prim_P w v e)\\<^sup>T \\<le> w \\<sqinter> w\\<^sup>T\"\n    by (meson conv_isotone inf_le1 inf_mono order_trans)\n  thus ?thesis\n    by (metis assms acyclic_asymmetric inf.commute le_bot)\nqed\n\nlemma epm_9:\n  assumes \"e \\<le> v * -v\\<^sup>T\"\n      and \"vector v\"\n    shows \"(w \\<sqinter> -(prim_EP w v e)) \\<sqinter> e = bot\"\nproof -\n  have 1: \"e \\<le> -v\\<^sup>T\"\n    by (metis assms complement_conv_sub vector_conv_covector ev p_antitone_iff p_bot)\n  have \"(w \\<sqinter> -(prim_EP w v e)) \\<sqinter> e = (w \\<sqinter> --v\\<^sup>T \\<sqinter> e) \\<squnion> (w \\<sqinter> -(top * e * w\\<^sup>T\\<^sup>\\<star>) \\<sqinter> e)\"\n    by (simp add: inf_commute inf_sup_distrib1)\n  also have \"... \\<le> (--v\\<^sup>T \\<sqinter> e) \\<squnion> (-(top * e * w\\<^sup>T\\<^sup>\\<star>) \\<sqinter> e)\"\n    using comp_inf.mult_left_isotone inf.cobounded2 semiring.add_mono by blast\n  also have \"... = -(top * e * w\\<^sup>T\\<^sup>\\<star>) \\<sqinter> e\"\n    using 1 by (metis inf.sup_relative_same_increasing inf_commute inf_sup_distrib1 maddux_3_13 regular_closed_p)\n  also have \"... = bot\"\n    by (metis inf.sup_relative_same_increasing inf_bot_right inf_commute inf_p mult_left_isotone star_outer_increasing top_greatest)\n  finally show ?thesis\n    by (simp add: le_iff_inf)\nqed\n\nlemma epm_10:\n  assumes \"e \\<le> v * -v\\<^sup>T\"\n      and \"vector v\"\n    shows \"(prim_P w v e)\\<^sup>T \\<sqinter> e = bot\"\nproof -\n  have \"(prim_P w v e)\\<^sup>T \\<le> -v * -v\\<^sup>T\"\n    by (simp add: conv_complement conv_dist_comp conv_dist_inf inf.absorb_iff1 inf.left_commute inf_commute)\n  hence \"(prim_P w v e)\\<^sup>T \\<sqinter> e \\<le> -v * -v\\<^sup>T \\<sqinter> v * -v\\<^sup>T\"\n    using assms(1) inf_mono by blast\n  also have \"... \\<le> -v * top \\<sqinter> v * top\"\n    using inf.sup_mono mult_right_isotone top_greatest by blast\n  also have \"... = bot\"\n    using assms(2) inf_compl_bot vector_complement_closed by auto\n  finally show ?thesis\n    by (simp add: le_iff_inf)\nqed\n\nlemma epm_11:\n  assumes \"vector v\"\n    shows \"(w \\<sqinter> -(prim_EP w v e)) \\<sqinter> prim_P w v e = bot\"\nproof -\n  have \"prim_P w v e \\<le> prim_EP w v e\"\n    by (metis assms comp_isotone inf.sup_left_isotone inf.sup_right_isotone order.refl top_greatest vector_conv_compl)\n  thus ?thesis\n    using inf_le2 order_trans p_antitone pseudo_complement by blast\nqed\n\nlemma epm_12:\n  assumes \"vector v\"\n    shows \"(w \\<sqinter> -(prim_EP w v e)) \\<sqinter> prim_E w v e = bot\"\nproof -\n  have \"prim_E w v e \\<le> prim_EP w v e\"\n    by (metis assms comp_isotone inf.sup_left_isotone inf.sup_right_isotone order.refl top_greatest vector_conv_compl)\n  thus ?thesis\n    using inf_le2 order_trans p_antitone pseudo_complement by blast\nqed\n\nlemma epm_13:\n  assumes \"vector v\"\n    shows \"prim_P w v e \\<sqinter> prim_E w v e = bot\"\nproof -\n  have \"prim_P w v e \\<sqinter> prim_E w v e \\<le> -v * -v\\<^sup>T \\<sqinter> --v * -v\\<^sup>T\"\n    by (meson dual_order.trans inf.cobounded1 inf.sup_mono inf_le2)\n  also have \"... \\<le> -v * top \\<sqinter> --v * top\"\n    using inf.sup_mono mult_right_isotone top_greatest by blast\n  also have \"... = bot\"\n    using assms inf_compl_bot vector_complement_closed by auto\n  finally show ?thesis\n    by (simp add: le_iff_inf)\nqed\n\ntext \\<open>\nThe following lemmas show that the relation characterising the edge across the cut is an arc.\n\\<close>\n\nlemma arc_edge_1:\n  assumes \"e \\<le> v * -v\\<^sup>T \\<sqinter> g\"\n      and \"vector v\"\n      and \"v\\<^sup>T = r\\<^sup>T * t\\<^sup>\\<star>\"\n      and \"t \\<le> g\"\n      and \"r\\<^sup>T * g\\<^sup>\\<star> \\<le> r\\<^sup>T * w\\<^sup>\\<star>\"\n    shows \"top * e \\<le> v\\<^sup>T * w\\<^sup>\\<star>\"\nproof -\n  have \"top * e \\<le> top * (v * -v\\<^sup>T \\<sqinter> g)\"\n    using assms(1) mult_right_isotone by auto\n  also have \"... \\<le> top * (v * top \\<sqinter> g)\"\n    using inf.sup_right_isotone inf_commute mult_right_isotone top_greatest by presburger\n  also have \"... = v\\<^sup>T * g\"\n    by (metis assms(2) covector_inf_comp_3 inf_top.left_neutral)\n  also have \"... = r\\<^sup>T * t\\<^sup>\\<star> * g\"\n    by (simp add: assms(3))\n  also have \"... \\<le> r\\<^sup>T * g\\<^sup>\\<star> * g\"\n    by (simp add: assms(4) mult_left_isotone mult_right_isotone star_isotone)\n  also have \"... \\<le> r\\<^sup>T * g\\<^sup>\\<star>\"\n    by (simp add: mult_assoc mult_right_isotone star.right_plus_below_circ)\n  also have \"... \\<le> r\\<^sup>T * w\\<^sup>\\<star>\"\n    by (simp add: assms(5))\n  also have \"... \\<le> v\\<^sup>T * w\\<^sup>\\<star>\"\n    by (metis assms(3) mult_left_isotone mult_right_isotone mult_1_right star.circ_reflexive)\n  finally show ?thesis\n    .\nqed\n\nlemma arc_edge_2:\n  assumes \"e \\<le> v * -v\\<^sup>T \\<sqinter> g\"\n      and \"vector v\"\n      and \"v\\<^sup>T = r\\<^sup>T * t\\<^sup>\\<star>\"\n      and \"t \\<le> g\"\n      and \"r\\<^sup>T * g\\<^sup>\\<star> \\<le> r\\<^sup>T * w\\<^sup>\\<star>\"\n      and \"w * v \\<le> v\"\n      and \"injective w\"\n    shows \"top * e * w\\<^sup>T\\<^sup>\\<star> \\<le> v\\<^sup>T * w\\<^sup>\\<star>\"\nproof -\n  have 1: \"top * e \\<le> v\\<^sup>T * w\\<^sup>\\<star>\"\n    using assms(1-5) arc_edge_1 by blast\n  have \"v\\<^sup>T * w\\<^sup>\\<star> * w\\<^sup>T = v\\<^sup>T * w\\<^sup>T \\<squnion> v\\<^sup>T * w\\<^sup>+ * w\\<^sup>T\"\n    by (metis mult_assoc mult_left_dist_sup star.circ_loop_fixpoint sup_commute)\n  also have \"... \\<le> v\\<^sup>T \\<squnion> v\\<^sup>T * w\\<^sup>+ * w\\<^sup>T\"\n    by (metis assms(6) conv_dist_comp conv_isotone sup_left_isotone)\n  also have \"... = v\\<^sup>T \\<squnion> v\\<^sup>T * w\\<^sup>\\<star> * (w * w\\<^sup>T)\"\n    by (metis mult_assoc star_plus)\n  also have \"... \\<le> v\\<^sup>T \\<squnion> v\\<^sup>T * w\\<^sup>\\<star>\"\n    by (metis assms(7) mult_right_isotone mult_1_right sup_right_isotone)\n  also have \"... = v\\<^sup>T * w\\<^sup>\\<star>\"\n    by (metis star.circ_back_loop_fixpoint sup_absorb2 sup_ge2)\n  finally show ?thesis\n    using 1 star_right_induct by auto\nqed\n\nlemma arc_edge_3:\n  assumes \"e \\<le> v * -v\\<^sup>T \\<sqinter> g\"\n      and \"vector v\"\n      and \"v\\<^sup>T = r\\<^sup>T * t\\<^sup>\\<star>\"\n      and \"t \\<le> g\"\n      and \"r\\<^sup>T * g\\<^sup>\\<star> \\<le> r\\<^sup>T * w\\<^sup>\\<star>\"\n      and \"w * v \\<le> v\"\n      and \"injective w\"\n      and \"prim_E w v e = bot\"\n    shows \"e = bot\"\nproof -\n  have \"bot = prim_E w v e\"\n    by (simp add: assms(8))\n  also have \"... = w \\<sqinter> --v * top \\<sqinter> top * -v\\<^sup>T \\<sqinter> top * e * w\\<^sup>T\\<^sup>\\<star>\"\n    by (metis assms(2) comp_inf_covector inf.assoc inf_top.left_neutral vector_conv_compl)\n  also have \"... = w \\<sqinter> top * e * w\\<^sup>T\\<^sup>\\<star> \\<sqinter> -v\\<^sup>T \\<sqinter> --v\"\n    using assms(2) inf.assoc inf.commute vector_conv_compl vector_complement_closed by (simp add: inf_assoc)\n  finally have 1: \"w \\<sqinter> top * e * w\\<^sup>T\\<^sup>\\<star> \\<sqinter> -v\\<^sup>T \\<le> -v\"\n    using shunting_1_pp by force\n  have \"w\\<^sup>\\<star> * e\\<^sup>T * top = (top * e * w\\<^sup>T\\<^sup>\\<star>)\\<^sup>T\"\n    by (simp add: conv_star_commute comp_associative conv_dist_comp)\n  also have \"... \\<le> (v\\<^sup>T * w\\<^sup>\\<star>)\\<^sup>T\"\n    using assms(1-7) arc_edge_2 by (simp add: conv_isotone)\n  also have \"... = w\\<^sup>T\\<^sup>\\<star> * v\"\n    by (simp add: conv_star_commute conv_dist_comp)\n  finally have 2: \"w\\<^sup>\\<star> * e\\<^sup>T * top \\<le> w\\<^sup>T\\<^sup>\\<star> * v\"\n    .\n  have \"(w\\<^sup>T \\<sqinter> w\\<^sup>\\<star> * e\\<^sup>T * top)\\<^sup>T * -v = (w \\<sqinter> top * e * w\\<^sup>T\\<^sup>\\<star>) * -v\"\n    by (simp add: conv_dist_comp conv_dist_inf conv_star_commute mult_assoc)\n  also have \"... = (w \\<sqinter> top * e * w\\<^sup>T\\<^sup>\\<star> \\<sqinter> -v\\<^sup>T) * top\"\n    by (metis assms(2) conv_complement covector_inf_comp_3 inf_top.right_neutral vector_complement_closed)\n  also have \"... \\<le> -v * top\"\n    using 1 by (simp add: comp_isotone)\n  also have \"... = -v\"\n    using assms(2) vector_complement_closed by auto\n  finally have \"(w\\<^sup>T \\<sqinter> w\\<^sup>\\<star> * e\\<^sup>T * top) * --v \\<le> --v\"\n    using p_antitone_iff schroeder_3_p by auto\n  hence \"w\\<^sup>\\<star> * e\\<^sup>T * top \\<sqinter> w\\<^sup>T * --v \\<le> --v\"\n    by (simp add: inf_vector_comp)\n  hence 3: \"w\\<^sup>T * --v \\<le> --v \\<squnion> -(w\\<^sup>\\<star> * e\\<^sup>T * top)\"\n    by (simp add: inf.commute shunting_p)\n  have \"w\\<^sup>T * -(w\\<^sup>\\<star> * e\\<^sup>T * top) \\<le> -(w\\<^sup>\\<star> * e\\<^sup>T * top)\"\n    by (metis mult_assoc p_antitone p_antitone_iff schroeder_3_p star.circ_loop_fixpoint sup_commute sup_right_divisibility)\n  also have \"... \\<le> --v \\<squnion> -(w\\<^sup>\\<star> * e\\<^sup>T * top)\"\n    by simp\n  finally have \"w\\<^sup>T * (--v \\<squnion> -(w\\<^sup>\\<star> * e\\<^sup>T * top)) \\<le> --v \\<squnion> -(w\\<^sup>\\<star> * e\\<^sup>T * top)\"\n    using 3 by (simp add: mult_left_dist_sup)\n  hence \"w\\<^sup>T\\<^sup>\\<star> * (--v \\<squnion> -(w\\<^sup>\\<star> * e\\<^sup>T * top)) \\<le> --v \\<squnion> -(w\\<^sup>\\<star> * e\\<^sup>T * top)\"\n    using star_left_induct_mult_iff by blast\n  hence \"w\\<^sup>T\\<^sup>\\<star> * --v \\<le> --v \\<squnion> -(w\\<^sup>\\<star> * e\\<^sup>T * top)\"\n    by (simp add: semiring.distrib_left)\n  hence \"w\\<^sup>\\<star> * e\\<^sup>T * top \\<sqinter> w\\<^sup>T\\<^sup>\\<star> * --v \\<le> --v\"\n    by (simp add: inf_commute shunting_p)\n  hence \"w\\<^sup>\\<star> * e\\<^sup>T * top \\<le> --v\"\n    using 2 by (metis inf.absorb1 p_antitone_iff p_comp_pp vector_export_comp)\n  hence 4: \"e\\<^sup>T * top \\<le> --v\"\n    by (metis mult_assoc star.circ_loop_fixpoint sup.bounded_iff)\n  have \"e\\<^sup>T * top \\<le> (v * -v\\<^sup>T)\\<^sup>T * top\"\n    using assms(1) comp_isotone conv_isotone by auto\n  also have \"... \\<le> -v * top\"\n    by (simp add: conv_complement conv_dist_comp mult_assoc mult_right_isotone)\n  also have \"... = -v\"\n    using assms(2) vector_complement_closed by auto\n  finally have \"e\\<^sup>T * top \\<le> bot\"\n    using 4 shunting_1_pp by auto\n  hence \"e\\<^sup>T = bot\"\n    using antisym bot_least top_right_mult_increasing by blast\n  thus ?thesis\n    using conv_bot by fastforce\nqed\n\nlemma arc_edge_4:\n  assumes \"e \\<le> v * -v\\<^sup>T \\<sqinter> g\"\n      and \"vector v\"\n      and \"v\\<^sup>T = r\\<^sup>T * t\\<^sup>\\<star>\"\n      and \"t \\<le> g\"\n      and \"r\\<^sup>T * g\\<^sup>\\<star> \\<le> r\\<^sup>T * w\\<^sup>\\<star>\"\n      and \"arc e\"\n    shows \"top * prim_E w v e * top = top\"\nproof -\n  have \"--v\\<^sup>T * w = (--v\\<^sup>T * w \\<sqinter> -v\\<^sup>T) \\<squnion> (--v\\<^sup>T * w \\<sqinter> --v\\<^sup>T)\"\n    by (simp add: maddux_3_11_pp)\n  also have \"... \\<le> (--v\\<^sup>T * w \\<sqinter> -v\\<^sup>T) \\<squnion> --v\\<^sup>T\"\n    using sup_right_isotone by auto\n  also have \"... = --v\\<^sup>T * (w \\<sqinter> -v\\<^sup>T) \\<squnion> --v\\<^sup>T\"\n    using assms(2) covector_comp_inf covector_complement_closed vector_conv_covector by auto\n  also have \"... \\<le> --v\\<^sup>T * (w \\<sqinter> -v\\<^sup>T) * w\\<^sup>\\<star> \\<squnion> --v\\<^sup>T\"\n    by (metis star.circ_back_loop_fixpoint sup.cobounded2 sup_left_isotone)\n  finally have 1: \"--v\\<^sup>T * w \\<le> --v\\<^sup>T * (w \\<sqinter> -v\\<^sup>T) * w\\<^sup>\\<star> \\<squnion> --v\\<^sup>T\"\n    .\n  have \"--v\\<^sup>T * (w \\<sqinter> -v\\<^sup>T) * w\\<^sup>\\<star> * w \\<le> --v\\<^sup>T * (w \\<sqinter> -v\\<^sup>T) * w\\<^sup>\\<star> \\<squnion> --v\\<^sup>T\"\n    by (simp add: le_supI1 mult_assoc mult_right_isotone star.circ_plus_same star.left_plus_below_circ)\n  hence 2: \"(--v\\<^sup>T * (w \\<sqinter> -v\\<^sup>T) * w\\<^sup>\\<star> \\<squnion> --v\\<^sup>T) * w \\<le> --v\\<^sup>T * (w \\<sqinter> -v\\<^sup>T) * w\\<^sup>\\<star> \\<squnion> --v\\<^sup>T\"\n    using 1 by (simp add: inf.orderE mult_right_dist_sup)\n  have \"v\\<^sup>T \\<le> --v\\<^sup>T * (w \\<sqinter> -v\\<^sup>T) * w\\<^sup>\\<star> \\<squnion> --v\\<^sup>T\"\n    by (simp add: pp_increasing sup.coboundedI2)\n  hence \"v\\<^sup>T * w\\<^sup>\\<star> \\<le> --v\\<^sup>T * (w \\<sqinter> -v\\<^sup>T) * w\\<^sup>\\<star> \\<squnion> --v\\<^sup>T\"\n    using 2 by (simp add: star_right_induct)\n  hence 3: \"-v\\<^sup>T \\<sqinter> v\\<^sup>T * w\\<^sup>\\<star> \\<le> --v\\<^sup>T * (w \\<sqinter> -v\\<^sup>T) * w\\<^sup>\\<star>\"\n    by (metis inf_commute shunting_var_p)\n  have \"top * e = top * e \\<sqinter> v\\<^sup>T * w\\<^sup>\\<star>\"\n    by (meson assms(1-5) arc_edge_1 inf.orderE)\n  also have \"... \\<le> top * v * -v\\<^sup>T \\<sqinter> v\\<^sup>T * w\\<^sup>\\<star>\"\n    using assms(1) inf.sup_left_isotone mult_assoc mult_right_isotone by auto\n  also have \"... \\<le> top * -v\\<^sup>T \\<sqinter> v\\<^sup>T * w\\<^sup>\\<star>\"\n    using inf.sup_left_isotone mult_left_isotone top_greatest by blast\n  also have \"... = -v\\<^sup>T \\<sqinter> v\\<^sup>T * w\\<^sup>\\<star>\"\n    by (simp add: assms(2) vector_conv_compl)\n  also have \"... \\<le> --v\\<^sup>T * (w \\<sqinter> -v\\<^sup>T) * w\\<^sup>\\<star>\"\n    using 3 by simp\n  also have \"... = (top \\<sqinter> (--v)\\<^sup>T) * (w \\<sqinter> -v\\<^sup>T) * w\\<^sup>\\<star>\"\n    by (simp add: conv_complement)\n  also have \"... = top * (w \\<sqinter> --v \\<sqinter> -v\\<^sup>T) * w\\<^sup>\\<star>\"\n    using assms(2) covector_inf_comp_3 inf_assoc inf_left_commute vector_complement_closed by presburger\n  also have \"... = top * (w \\<sqinter> --v * -v\\<^sup>T) * w\\<^sup>\\<star>\"\n    by (metis assms(2) vector_complement_closed conv_complement inf_assoc vector_covector)\n  finally have \"top * (e\\<^sup>T * top)\\<^sup>T \\<le> top * (w \\<sqinter> --v * -v\\<^sup>T) * w\\<^sup>\\<star>\"\n    by (metis conv_dist_comp conv_involutive conv_top mult_assoc top_mult_top)\n  hence \"top \\<le> top * (w \\<sqinter> --v * -v\\<^sup>T) * w\\<^sup>\\<star> * (e\\<^sup>T * top)\"\n    using assms(6) shunt_bijective by blast\n  also have \"... = top * (w \\<sqinter> --v * -v\\<^sup>T) * (top * e * w\\<^sup>\\<star>\\<^sup>T)\\<^sup>T\"\n    by (simp add: conv_dist_comp mult_assoc)\n  also have \"... = top * (w \\<sqinter> --v * -v\\<^sup>T \\<sqinter> top * e * w\\<^sup>\\<star>\\<^sup>T) * top\"\n    by (simp add: comp_inf_vector_1 mult_assoc)\n  finally show ?thesis\n    by (simp add: conv_star_commute top_le)\nqed\n\nlemma arc_edge_5:\n  assumes \"vector v\"\n      and \"w * v \\<le> v\"\n      and \"injective w\"\n      and \"arc e\"\n    shows \"(prim_E w v e)\\<^sup>T * top * prim_E w v e \\<le> 1\"\nproof -\n  have 1: \"e\\<^sup>T * top * e \\<le> 1\"\n    by (simp add: assms(4) point_injective)\n  have \"prim_E w v e \\<le> --v * top\"\n    by (simp add: inf_commute le_infI2 mult_right_isotone)\n  hence 2: \"prim_E w v e \\<le> --v\"\n    by (simp add: assms(1) vector_complement_closed)\n  have 3: \"w * --v \\<le> --v\"\n    by (simp add: assms(2) p_antitone p_antitone_iff)\n  have \"w \\<sqinter> top * prim_E w v e \\<le> w * (prim_E w v e)\\<^sup>T * prim_E w v e\"\n    by (metis dedekind_2 inf.commute inf_top.left_neutral)\n  also have \"... \\<le> w * w\\<^sup>T * prim_E w v e\"\n    by (simp add: conv_isotone le_infI1 mult_left_isotone mult_right_isotone)\n  also have \"... \\<le> prim_E w v e\"\n    by (metis assms(3) mult_left_isotone mult_left_one)\n  finally have 4: \"w \\<sqinter> top * prim_E w v e \\<le> prim_E w v e\"\n    .\n  have \"w\\<^sup>+ \\<sqinter> top * prim_E w v e = w\\<^sup>\\<star> * (w \\<sqinter> top * prim_E w v e)\"\n    by (simp add: comp_inf_covector star_plus)\n  also have \"... \\<le> w\\<^sup>\\<star> * prim_E w v e\"\n    using 4 by (simp add: mult_right_isotone)\n  also have \"... \\<le> --v\"\n    using 2 3 star_left_induct sup.bounded_iff by blast\n  finally have 5: \"w\\<^sup>+ \\<sqinter> top * prim_E w v e \\<sqinter> -v = bot\"\n    using shunting_1_pp by blast\n  hence 6: \"w\\<^sup>+\\<^sup>T \\<sqinter> (prim_E w v e)\\<^sup>T * top \\<sqinter> -v\\<^sup>T = bot\"\n    using conv_complement conv_dist_comp conv_dist_inf conv_top conv_bot by force\n  have \"(prim_E w v e)\\<^sup>T * top * prim_E w v e \\<le> (top * e * w\\<^sup>T\\<^sup>\\<star>)\\<^sup>T * top * (top * e * w\\<^sup>T\\<^sup>\\<star>)\"\n    by (simp add: conv_isotone mult_isotone)\n  also have \"... = w\\<^sup>\\<star> * e\\<^sup>T * top * e * w\\<^sup>T\\<^sup>\\<star>\"\n    by (metis conv_star_commute conv_dist_comp conv_involutive conv_top mult_assoc top_mult_top)\n  also have \"... \\<le> w\\<^sup>\\<star> * w\\<^sup>T\\<^sup>\\<star>\"\n    using 1 by (metis mult_assoc mult_1_right mult_right_isotone mult_left_isotone)\n  also have \"... = w\\<^sup>\\<star> \\<squnion> w\\<^sup>T\\<^sup>\\<star>\"\n    by (metis assms(3) cancel_separate inf.eq_iff star.circ_sup_sub_sup_one_1 star.circ_plus_one star_involutive)\n  also have \"... = w\\<^sup>+ \\<squnion> w\\<^sup>T\\<^sup>+ \\<squnion> 1\"\n    by (metis star.circ_plus_one star_left_unfold_equal sup.assoc sup.commute)\n  finally have 7: \"(prim_E w v e)\\<^sup>T * top * prim_E w v e \\<le> w\\<^sup>+ \\<squnion> w\\<^sup>T\\<^sup>+ \\<squnion> 1\"\n    .\n  have \"prim_E w v e \\<le> --v * -v\\<^sup>T\"\n    by (simp add: le_infI1)\n  also have \"... \\<le> top * -v\\<^sup>T\"\n    by (simp add: mult_left_isotone)\n  also have \"... = -v\\<^sup>T\"\n    by (simp add: assms(1) vector_conv_compl)\n  finally have 8: \"prim_E w v e \\<le> -v\\<^sup>T\"\n    .\n  hence 9: \"(prim_E w v e)\\<^sup>T \\<le> -v\"\n    by (metis conv_complement conv_involutive conv_isotone)\n  have \"(prim_E w v e)\\<^sup>T * top * prim_E w v e = (w\\<^sup>+ \\<squnion> w\\<^sup>T\\<^sup>+ \\<squnion> 1) \\<sqinter> (prim_E w v e)\\<^sup>T * top * prim_E w v e\"\n    using 7 by (simp add: inf.absorb_iff2)\n  also have \"... = (1 \\<sqinter> (prim_E w v e)\\<^sup>T * top * prim_E w v e) \\<squnion> (w\\<^sup>+ \\<sqinter> (prim_E w v e)\\<^sup>T * top * prim_E w v e) \\<squnion> (w\\<^sup>T\\<^sup>+ \\<sqinter> (prim_E w v e)\\<^sup>T * top * prim_E w v e)\"\n    using comp_inf.mult_right_dist_sup sup_assoc sup_commute by auto\n  also have \"... \\<le> 1 \\<squnion> (w\\<^sup>+ \\<sqinter> (prim_E w v e)\\<^sup>T * top * prim_E w v e) \\<squnion> (w\\<^sup>T\\<^sup>+ \\<sqinter> (prim_E w v e)\\<^sup>T * top * prim_E w v e)\"\n    using inf_le1 sup_left_isotone by blast\n  also have \"... \\<le> 1 \\<squnion> (w\\<^sup>+ \\<sqinter> (prim_E w v e)\\<^sup>T * top * prim_E w v e) \\<squnion> (w\\<^sup>T\\<^sup>+ \\<sqinter> (prim_E w v e)\\<^sup>T * top * -v\\<^sup>T)\"\n    using 8 inf.sup_right_isotone mult_right_isotone sup_right_isotone by blast\n  also have \"... \\<le> 1 \\<squnion> (w\\<^sup>+ \\<sqinter> -v * top * prim_E w v e) \\<squnion> (w\\<^sup>T\\<^sup>+ \\<sqinter> (prim_E w v e)\\<^sup>T * top * -v\\<^sup>T)\"\n    using 9 by (metis inf.sup_right_isotone mult_left_isotone sup.commute sup_right_isotone)\n  also have \"... = 1 \\<squnion> (w\\<^sup>+ \\<sqinter> -v * top \\<sqinter> top * prim_E w v e) \\<squnion> (w\\<^sup>T\\<^sup>+ \\<sqinter> (prim_E w v e)\\<^sup>T * top \\<sqinter> top * -v\\<^sup>T)\"\n    by (metis (no_types) vector_export_comp inf_top_right inf_assoc)\n  also have \"... = 1 \\<squnion> (w\\<^sup>+ \\<sqinter> -v \\<sqinter> top * prim_E w v e) \\<squnion> (w\\<^sup>T\\<^sup>+ \\<sqinter> (prim_E w v e)\\<^sup>T * top \\<sqinter> -v\\<^sup>T)\"\n    using assms(1) vector_complement_closed vector_conv_compl by auto\n  also have \"... = 1\"\n    using 5 6 by (simp add: conv_star_commute conv_dist_comp inf.commute inf_assoc star.circ_plus_same)\n  finally show ?thesis\n    .\nqed\n\nlemma arc_edge_6:\n  assumes \"vector v\"\n      and \"w * v \\<le> v\"\n      and \"injective w\"\n      and \"arc e\"\n    shows \"prim_E w v e * top * (prim_E w v e)\\<^sup>T \\<le> 1\"\nproof -\n  have \"prim_E w v e * 1 * (prim_E w v e)\\<^sup>T \\<le> w * w\\<^sup>T\"\n    using comp_isotone conv_order inf.coboundedI1 mult_one_associative by auto\n  also have \"... \\<le> 1\"\n    by (simp add: assms(3))\n  finally have 1: \"prim_E w v e * 1 * (prim_E w v e)\\<^sup>T \\<le> 1\"\n    .\n  have \"(prim_E w v e)\\<^sup>T * top * prim_E w v e \\<le> 1\"\n    by (simp add: assms arc_edge_5)\n  also have \"... \\<le> --1\"\n    by (simp add: pp_increasing)\n  finally have 2: \"prim_E w v e * -1 * (prim_E w v e)\\<^sup>T \\<le> bot\"\n    by (metis conv_involutive regular_closed_bot regular_dense_top triple_schroeder_p)\n  have \"prim_E w v e * top * (prim_E w v e)\\<^sup>T = prim_E w v e * 1 * (prim_E w v e)\\<^sup>T \\<squnion> prim_E w v e * -1 * (prim_E w v e)\\<^sup>T\"\n    by (metis mult_left_dist_sup mult_right_dist_sup regular_complement_top regular_one_closed)\n  also have \"... \\<le> 1\"\n    using 1 2 by (simp add: bot_unique)\n  finally show ?thesis\n    .\nqed\n\nlemma arc_edge:\n  assumes \"e \\<le> v * -v\\<^sup>T \\<sqinter> g\"\n      and \"vector v\"\n      and \"v\\<^sup>T = r\\<^sup>T * t\\<^sup>\\<star>\"\n      and \"t \\<le> g\"\n      and \"r\\<^sup>T * g\\<^sup>\\<star> \\<le> r\\<^sup>T * w\\<^sup>\\<star>\"\n      and \"w * v \\<le> v\"\n      and \"injective w\"\n      and \"arc e\"\n    shows \"arc (prim_E w v e)\"\nproof (intro conjI)\n  have \"prim_E w v e * top * (prim_E w v e)\\<^sup>T \\<le> 1\"\n    using assms(2,6-8) arc_edge_6 by simp\n  thus \"injective (prim_E w v e * top)\"\n    by (metis conv_dist_comp conv_top mult_assoc top_mult_top)\nnext\n  show \"surjective (prim_E w v e * top)\"\n    using assms(1-5,8) arc_edge_4 mult_assoc by simp\nnext\n  have \"(prim_E w v e)\\<^sup>T * top * prim_E w v e \\<le> 1\"\n    using assms(2,6-8) arc_edge_5 by simp\n  thus \"injective ((prim_E w v e)\\<^sup>T * top)\"\n    by (metis conv_dist_comp conv_involutive conv_top mult_assoc top_mult_top)\nnext\n  have \"top * prim_E w v e * top = top\"\n    using assms(1-5,8) arc_edge_4 by simp\n  thus \"surjective ((prim_E w v e)\\<^sup>T * top)\"\n    by (metis mult_assoc conv_dist_comp conv_top)\nqed\n\nsubsubsection \\<open>Invariant implies Postcondition\\<close>\n\ntext \\<open>\nThe lemmas in this section are used to show that the invariant implies the postcondition at the end of the algorithm.\nThe following lemma shows that the nodes reachable in the graph are the same as those reachable in the constructed tree.\n\\<close>\n\nlemma span_post:\n  assumes \"regular v\"\n      and \"vector v\"\n      and \"v\\<^sup>T = r\\<^sup>T * t\\<^sup>\\<star>\"\n      and \"v * -v\\<^sup>T \\<sqinter> g = bot\"\n      and \"t \\<le> v * v\\<^sup>T \\<sqinter> g\"\n      and \"r\\<^sup>T * (v * v\\<^sup>T \\<sqinter> g)\\<^sup>\\<star> \\<le> r\\<^sup>T * t\\<^sup>\\<star>\"\n    shows \"v\\<^sup>T = r\\<^sup>T * g\\<^sup>\\<star>\"\nproof -\n  let ?vv = \"v * v\\<^sup>T \\<sqinter> g\"\n  have 1: \"r\\<^sup>T \\<le> v\\<^sup>T\"\n    using assms(3) mult_right_isotone mult_1_right star.circ_reflexive by fastforce\n  have \"v * top \\<sqinter> g = (v * v\\<^sup>T \\<squnion> v * -v\\<^sup>T) \\<sqinter> g\"\n    by (metis assms(1) conv_complement mult_left_dist_sup regular_complement_top)\n  also have \"... = ?vv \\<squnion> (v * -v\\<^sup>T \\<sqinter> g)\"\n    by (simp add: inf_sup_distrib2)\n  also have \"... = ?vv\"\n    by (simp add: assms(4))\n  finally have 2: \"v * top \\<sqinter> g = ?vv\"\n    by simp\n  have \"r\\<^sup>T * ?vv\\<^sup>\\<star> \\<le> v\\<^sup>T * ?vv\\<^sup>\\<star>\"\n    using 1 by (simp add: comp_left_isotone)\n  also have \"... \\<le> v\\<^sup>T * (v * v\\<^sup>T)\\<^sup>\\<star>\"\n    by (simp add: comp_right_isotone star.circ_isotone)\n  also have \"... \\<le> v\\<^sup>T\"\n    by (simp add: assms(2) vector_star_1)\n  finally have \"r\\<^sup>T * ?vv\\<^sup>\\<star> \\<le> v\\<^sup>T\"\n    by simp\n  hence \"r\\<^sup>T * ?vv\\<^sup>\\<star> * g = (r\\<^sup>T * ?vv\\<^sup>\\<star> \\<sqinter> v\\<^sup>T) * g\"\n    by (simp add: inf.absorb1)\n  also have \"... = r\\<^sup>T * ?vv\\<^sup>\\<star> * (v * top \\<sqinter> g)\"\n    by (simp add: assms(2) covector_inf_comp_3)\n  also have \"... = r\\<^sup>T * ?vv\\<^sup>\\<star> * ?vv\"\n    using 2 by simp\n  also have \"... \\<le> r\\<^sup>T * ?vv\\<^sup>\\<star>\"\n    by (simp add: comp_associative comp_right_isotone star.left_plus_below_circ star_plus)\n  finally have \"r\\<^sup>T \\<squnion> r\\<^sup>T * ?vv\\<^sup>\\<star> * g \\<le> r\\<^sup>T * ?vv\\<^sup>\\<star>\"\n    using star.circ_back_loop_prefixpoint by auto\n  hence \"r\\<^sup>T * g\\<^sup>\\<star> \\<le> r\\<^sup>T * ?vv\\<^sup>\\<star>\"\n    using star_right_induct by blast\n  hence \"r\\<^sup>T * g\\<^sup>\\<star> = r\\<^sup>T * ?vv\\<^sup>\\<star>\"\n    by (simp add: antisym mult_right_isotone star_isotone)\n  also have \"... = r\\<^sup>T * t\\<^sup>\\<star>\"\n    using assms(5,6) antisym mult_right_isotone star_isotone by auto\n  also have \"... = v\\<^sup>T\"\n    by (simp add: assms(3))\n  finally show ?thesis\n    by simp\nqed\n\ntext \\<open>\nThe following lemma shows that the minimum spanning tree extending a tree is the same as the tree at the end of the algorithm.\n\\<close>\n\nlemma mst_post:\n  assumes \"vector r\"\n      and \"injective r\"\n      and \"v\\<^sup>T = r\\<^sup>T * t\\<^sup>\\<star>\"\n      and \"forest w\"\n      and \"t \\<le> w\"\n      and \"w \\<le> v * v\\<^sup>T\"\n    shows \"w = t\"\nproof -\n  have 1: \"vector v\"\n    using assms(1,3) covector_mult_closed vector_conv_covector by auto\n  have \"w * v \\<le> v * v\\<^sup>T * v\"\n    by (simp add: assms(6) mult_left_isotone)\n  also have \"... \\<le> v\"\n    using 1 by (metis mult_assoc mult_right_isotone top_greatest)\n  finally have 2: \"w * v \\<le> v\"\n    .\n  have 3: \"r \\<le> v\"\n    by (metis assms(3) conv_order mult_right_isotone mult_1_right star.circ_reflexive)\n  have 4: \"v \\<sqinter> -r = t\\<^sup>T\\<^sup>\\<star> * r \\<sqinter> -r\"\n    by (metis assms(3) conv_dist_comp conv_involutive conv_star_commute)\n  also have \"... = (r \\<squnion> t\\<^sup>T\\<^sup>+ * r) \\<sqinter> -r\"\n    using mult_assoc star.circ_loop_fixpoint sup_commute by auto\n  also have \"... \\<le> t\\<^sup>T\\<^sup>+ * r\"\n    by (simp add: shunting)\n  also have \"... \\<le> t\\<^sup>T * top\"\n    by (simp add: comp_isotone mult_assoc)\n  finally have \"1 \\<sqinter> (v \\<sqinter> -r) * (v \\<sqinter> -r)\\<^sup>T \\<le> 1 \\<sqinter> t\\<^sup>T * top * (t\\<^sup>T * top)\\<^sup>T\"\n    using conv_order inf.sup_right_isotone mult_isotone by auto\n  also have \"... = 1 \\<sqinter> t\\<^sup>T * top * t\"\n    by (metis conv_dist_comp conv_involutive conv_top mult_assoc top_mult_top)\n  also have \"... \\<le> t\\<^sup>T * (top * t \\<sqinter> t * 1)\"\n    by (metis conv_involutive dedekind_1 inf.commute mult_assoc)\n  also have \"... \\<le> t\\<^sup>T * t\"\n    by (simp add: mult_right_isotone)\n  finally have 5: \"1 \\<sqinter> (v \\<sqinter> -r) * (v \\<sqinter> -r)\\<^sup>T \\<le> t\\<^sup>T * t\"\n    .\n  have \"w * w\\<^sup>+ \\<le> -1\"\n    by (metis assms(4) mult_right_isotone order_trans star.circ_increasing star.left_plus_circ)\n  hence 6: \"w\\<^sup>T\\<^sup>+ \\<le> -w\"\n    by (metis conv_star_commute mult_assoc mult_1_left triple_schroeder_p)\n  have \"w * r \\<sqinter> w\\<^sup>T\\<^sup>+ * r = (w \\<sqinter> w\\<^sup>T\\<^sup>+) * r\"\n    using assms(2) by (simp add: injective_comp_right_dist_inf)\n  also have \"... = bot\"\n    using 6 p_antitone pseudo_complement_pp semiring.mult_not_zero by blast\n  finally have 7: \"w * r \\<sqinter> w\\<^sup>T\\<^sup>+ * r = bot\"\n    .\n  have \"-1 * r \\<le> -r\"\n    using assms(2) dual_order.trans pp_increasing schroeder_4_p by blast\n  hence \"-1 * r * top \\<le> -r\"\n    by (simp add: assms(1) comp_associative)\n  hence 8: \"r\\<^sup>T * -1 * r \\<le> bot\"\n    by (simp add: mult_assoc schroeder_6_p)\n  have \"r\\<^sup>T * w * r \\<le> r\\<^sup>T * w\\<^sup>+ * r\"\n    by (simp add: mult_left_isotone mult_right_isotone star.circ_mult_increasing)\n  also have \"... \\<le> r\\<^sup>T * -1 * r\"\n    by (simp add: assms(4) comp_isotone)\n  finally have \"r\\<^sup>T * w * r \\<le> bot\"\n    using 8 by simp\n  hence \"w * r * top \\<le> -r\"\n    by (simp add: mult_assoc schroeder_6_p)\n  hence \"w * r \\<le> -r\"\n    by (simp add: assms(1) comp_associative)\n  hence \"w * r \\<le> -r \\<sqinter> w * v\"\n    using 3 by (simp add: mult_right_isotone)\n  also have \"... \\<le> -r \\<sqinter> v\"\n    using 2 by (simp add: le_infI2)\n  also have \"... = -r \\<sqinter> t\\<^sup>T\\<^sup>\\<star> * r\"\n    using 4 by (simp add: inf_commute)\n  also have \"... \\<le> -r \\<sqinter> w\\<^sup>T\\<^sup>\\<star> * r\"\n    using assms(5) comp_inf.mult_right_isotone conv_isotone mult_left_isotone star_isotone by auto\n  also have \"... = -r \\<sqinter> (r \\<squnion> w\\<^sup>T\\<^sup>+ * r)\"\n    using mult_assoc star.circ_loop_fixpoint sup_commute by auto\n  also have \"... \\<le> w\\<^sup>T\\<^sup>+ * r\"\n    using inf.commute maddux_3_13 by auto\n  finally have \"w * r = bot\"\n    using 7 by (simp add: le_iff_inf)\n  hence \"w = w \\<sqinter> top * -r\\<^sup>T\"\n    by (metis complement_conv_sub conv_dist_comp conv_involutive conv_bot inf.assoc inf.orderE regular_closed_bot regular_dense_top top_left_mult_increasing)\n  also have \"... = w \\<sqinter> v * v\\<^sup>T \\<sqinter> top * -r\\<^sup>T\"\n    by (simp add: assms(6) inf_absorb1)\n  also have \"... \\<le> w \\<sqinter> top * v\\<^sup>T \\<sqinter> top * -r\\<^sup>T\"\n    using comp_inf.mult_left_isotone comp_inf.mult_right_isotone mult_left_isotone by auto\n  also have \"... = w \\<sqinter> top * (v\\<^sup>T \\<sqinter> -r\\<^sup>T)\"\n    using 1 assms(1) covector_inf_closed inf_assoc vector_conv_compl vector_conv_covector by auto\n  also have \"... = w * (1 \\<sqinter> (v \\<sqinter> -r) * top)\"\n    by (simp add: comp_inf_vector conv_complement conv_dist_inf)\n  also have \"... = w * (1 \\<sqinter> (v \\<sqinter> -r) * (v \\<sqinter> -r)\\<^sup>T)\"\n    by (metis conv_top dedekind_eq inf_commute inf_top_left mult_1_left mult_1_right)\n  also have \"... \\<le> w * t\\<^sup>T * t\"\n    using 5 by (simp add: comp_isotone mult_assoc)\n  also have \"... \\<le> w * w\\<^sup>T * t\"\n    by (simp add: assms(5) comp_isotone conv_isotone)\n  also have \"... \\<le> t\"\n    using assms(4) mult_left_isotone mult_1_left by fastforce\n  finally show ?thesis\n    by (simp add: assms(5) antisym)\nqed\n\nsubsection \\<open>Kruskal's Algorithm\\<close>\n\ntext \\<open>\nThe following results are used for proving the correctness of Kruskal's minimum spanning tree algorithm.\n\\<close>\n\nsubsubsection \\<open>Preservation of Invariant\\<close>\n\ntext \\<open>\nWe first treat the preservation of the invariant.\nThe following lemmas show conditions necessary for preserving that \\<open>f\\<close> is a forest.\n\\<close>\n\nlemma kruskal_injective_inv_2:\n  assumes \"arc e\"\n      and \"acyclic f\"\n    shows \"top * e * f\\<^sup>T\\<^sup>\\<star> * f\\<^sup>T \\<le> -e\"\nproof -\n  have \"f \\<le> -f\\<^sup>T\\<^sup>\\<star>\"\n    using assms(2) acyclic_star_below_complement p_antitone_iff by simp\n  hence \"e * f \\<le> top * e * -f\\<^sup>T\\<^sup>\\<star>\"\n    by (simp add: comp_isotone top_left_mult_increasing)\n  also have \"... = -(top * e * f\\<^sup>T\\<^sup>\\<star>)\"\n    by (metis assms(1) comp_mapping_complement conv_dist_comp conv_involutive conv_top)\n  finally show ?thesis\n    using schroeder_4_p by simp\nqed\n\nlemma kruskal_injective_inv_3:\n  assumes \"arc e\"\n      and \"forest f\"\n    shows \"(top * e * f\\<^sup>T\\<^sup>\\<star>)\\<^sup>T * (top * e * f\\<^sup>T\\<^sup>\\<star>) \\<sqinter> f\\<^sup>T * f \\<le> 1\"\nproof -\n  have \"(top * e * f\\<^sup>T\\<^sup>\\<star>)\\<^sup>T * (top * e * f\\<^sup>T\\<^sup>\\<star>) = f\\<^sup>\\<star> * e\\<^sup>T * top * e * f\\<^sup>T\\<^sup>\\<star>\"\n    by (metis conv_dist_comp conv_involutive conv_star_commute conv_top vector_top_closed mult_assoc)\n  also have \"... \\<le> f\\<^sup>\\<star> * f\\<^sup>T\\<^sup>\\<star>\"\n    by (metis assms(1) arc_expanded mult_left_isotone mult_right_isotone mult_1_left mult_assoc)\n  finally have \"(top * e * f\\<^sup>T\\<^sup>\\<star>)\\<^sup>T * (top * e * f\\<^sup>T\\<^sup>\\<star>) \\<sqinter> f\\<^sup>T * f \\<le> f\\<^sup>\\<star> * f\\<^sup>T\\<^sup>\\<star> \\<sqinter> f\\<^sup>T * f\"\n    using inf.sup_left_isotone by simp\n  also have \"... \\<le> 1\"\n    using assms(2) forest_separate by simp\n  finally show ?thesis\n    by simp\nqed\n\nlemma kruskal_acyclic_inv:\n  assumes \"acyclic f\"\n      and \"covector q\"\n      and \"(f \\<sqinter> q)\\<^sup>T * f\\<^sup>\\<star> * e = bot\"\n      and \"e * f\\<^sup>\\<star> * e = bot\"\n      and \"f\\<^sup>T\\<^sup>\\<star> * f\\<^sup>\\<star> \\<le> -e\"\n    shows \"acyclic ((f \\<sqinter> -q) \\<squnion> (f \\<sqinter> q)\\<^sup>T \\<squnion> e)\"\nproof -\n  have \"(f \\<sqinter> -q) * (f \\<sqinter> q)\\<^sup>T = (f \\<sqinter> -q) * (f\\<^sup>T \\<sqinter> q\\<^sup>T)\"\n    by (simp add: conv_dist_inf)\n  hence 1: \"(f \\<sqinter> -q) * (f \\<sqinter> q)\\<^sup>T = bot\"\n    by (metis assms(2) comp_inf.semiring.mult_zero_right comp_inf_vector_1 conv_bot covector_bot_closed inf.sup_monoid.add_assoc p_inf)\n  hence 2: \"(f \\<sqinter> -q)\\<^sup>\\<star> * (f \\<sqinter> q)\\<^sup>T = (f \\<sqinter> q)\\<^sup>T\"\n    using mult_right_zero star_absorb star_simulation_right_equal by fastforce\n  hence 3: \"((f \\<sqinter> -q) \\<squnion> (f \\<sqinter> q)\\<^sup>T)\\<^sup>+ = (f \\<sqinter> q)\\<^sup>T\\<^sup>\\<star> * (f \\<sqinter> -q)\\<^sup>+ \\<squnion> (f \\<sqinter> q)\\<^sup>T\\<^sup>+\"\n    by (simp add: plus_sup)\n  have 4: \"((f \\<sqinter> -q) \\<squnion> (f \\<sqinter> q)\\<^sup>T)\\<^sup>\\<star> = (f \\<sqinter> q)\\<^sup>T\\<^sup>\\<star> * (f \\<sqinter> -q)\\<^sup>\\<star>\"\n    using 2 by (simp add: star.circ_sup_9)\n  have \"(f \\<sqinter> q)\\<^sup>T * (f \\<sqinter> -q)\\<^sup>\\<star> * e \\<le> (f \\<sqinter> q)\\<^sup>T * f\\<^sup>\\<star> * e\"\n    by (simp add: mult_left_isotone mult_right_isotone star_isotone)\n  hence \"(f \\<sqinter> q)\\<^sup>T * (f \\<sqinter> -q)\\<^sup>\\<star> * e = bot\"\n    using assms(3) le_bot by simp\n  hence 5: \"(f \\<sqinter> q)\\<^sup>T\\<^sup>\\<star> * (f \\<sqinter> -q)\\<^sup>\\<star> * e = (f \\<sqinter> -q)\\<^sup>\\<star> * e\"\n    by (metis comp_associative conv_bot conv_dist_comp conv_involutive conv_star_commute star_absorb)\n  have \"e * (f \\<sqinter> -q)\\<^sup>\\<star> * e \\<le> e * f\\<^sup>\\<star> * e\"\n    by (simp add: mult_left_isotone mult_right_isotone star_isotone)\n  hence \"e * (f \\<sqinter> -q)\\<^sup>\\<star> * e = bot\"\n    using assms(4) le_bot by simp\n  hence 6: \"((f \\<sqinter> -q)\\<^sup>\\<star> * e)\\<^sup>+ = (f \\<sqinter> -q)\\<^sup>\\<star> * e\"\n    by (simp add: comp_associative star_absorb)\n  have \"f\\<^sup>T\\<^sup>\\<star> * 1 * f\\<^sup>T\\<^sup>\\<star> * f\\<^sup>\\<star> \\<le> -e\"\n    by (simp add: assms(5) star.circ_transitive_equal)\n  hence 7: \"f\\<^sup>\\<star> * e * f\\<^sup>T\\<^sup>\\<star> * f\\<^sup>\\<star> \\<le> -1\"\n    by (metis comp_right_one conv_involutive conv_one conv_star_commute triple_schroeder_p)\n  have \"(f \\<sqinter> -q)\\<^sup>+ * (f \\<sqinter> q)\\<^sup>T\\<^sup>+ \\<le> -1\"\n    using 1 2 by (metis forest_bot mult_left_zero mult_assoc)\n  hence 8: \"(f \\<sqinter> q)\\<^sup>T\\<^sup>+ * (f \\<sqinter> -q)\\<^sup>+ \\<le> -1\"\n    using comp_commute_below_diversity by simp\n  have 9: \"f\\<^sup>T\\<^sup>+ \\<le> -1\"\n    using assms(1) acyclic_star_below_complement schroeder_5_p by force\n  have \"((f \\<sqinter> -q) \\<squnion> (f \\<sqinter> q)\\<^sup>T \\<squnion> e)\\<^sup>+ = (((f \\<sqinter> -q) \\<squnion> (f \\<sqinter> q)\\<^sup>T)\\<^sup>\\<star> * e)\\<^sup>\\<star> * ((f \\<sqinter> -q) \\<squnion> (f \\<sqinter> q)\\<^sup>T)\\<^sup>+ \\<squnion> (((f \\<sqinter> -q) \\<squnion> (f \\<sqinter> q)\\<^sup>T)\\<^sup>\\<star> * e)\\<^sup>+\"\n    by (simp add: plus_sup)\n  also have \"... = ((f \\<sqinter> q)\\<^sup>T\\<^sup>\\<star> * (f \\<sqinter> -q)\\<^sup>\\<star> * e)\\<^sup>\\<star> * ((f \\<sqinter> q)\\<^sup>T\\<^sup>\\<star> * (f \\<sqinter> -q)\\<^sup>+ \\<squnion> (f \\<sqinter> q)\\<^sup>T\\<^sup>+) \\<squnion> ((f \\<sqinter> q)\\<^sup>T\\<^sup>\\<star> * (f \\<sqinter> -q)\\<^sup>\\<star> * e)\\<^sup>+\"\n    using 3 4 by simp\n  also have \"... = ((f \\<sqinter> -q)\\<^sup>\\<star> * e)\\<^sup>\\<star> * ((f \\<sqinter> q)\\<^sup>T\\<^sup>\\<star> * (f \\<sqinter> -q)\\<^sup>+ \\<squnion> (f \\<sqinter> q)\\<^sup>T\\<^sup>+) \\<squnion> ((f \\<sqinter> -q)\\<^sup>\\<star> * e)\\<^sup>+\"\n    using 5 by simp\n  also have \"... = ((f \\<sqinter> -q)\\<^sup>\\<star> * e \\<squnion> 1) * ((f \\<sqinter> q)\\<^sup>T\\<^sup>\\<star> * (f \\<sqinter> -q)\\<^sup>+ \\<squnion> (f \\<sqinter> q)\\<^sup>T\\<^sup>+) \\<squnion> (f \\<sqinter> -q)\\<^sup>\\<star> * e\"\n    using 6 by (metis star_left_unfold_equal sup_monoid.add_commute)\n  also have \"... = (f \\<sqinter> -q)\\<^sup>\\<star> * e \\<squnion> (f \\<sqinter> -q)\\<^sup>\\<star> * e * (f \\<sqinter> q)\\<^sup>T\\<^sup>+ \\<squnion> (f \\<sqinter> -q)\\<^sup>\\<star> * e * (f \\<sqinter> q)\\<^sup>T\\<^sup>\\<star> * (f \\<sqinter> -q)\\<^sup>+ \\<squnion> (f \\<sqinter> q)\\<^sup>T\\<^sup>\\<star> * (f \\<sqinter> -q)\\<^sup>+ \\<squnion> (f \\<sqinter> q)\\<^sup>T\\<^sup>+\"\n    using comp_associative mult_left_dist_sup mult_right_dist_sup sup_assoc sup_commute by simp\n  also have \"... = (f \\<sqinter> -q)\\<^sup>\\<star> * e * (f \\<sqinter> q)\\<^sup>T\\<^sup>\\<star> * (f \\<sqinter> -q)\\<^sup>\\<star> \\<squnion> (f \\<sqinter> q)\\<^sup>T\\<^sup>\\<star> * (f \\<sqinter> -q)\\<^sup>+ \\<squnion> (f \\<sqinter> q)\\<^sup>T\\<^sup>+\"\n    by (metis star.circ_back_loop_fixpoint star_plus sup_monoid.add_commute mult_assoc)\n  also have \"... \\<le> f\\<^sup>\\<star> * e * f\\<^sup>T\\<^sup>\\<star> * (f \\<sqinter> -q)\\<^sup>\\<star> \\<squnion> (f \\<sqinter> q)\\<^sup>T\\<^sup>\\<star> * (f \\<sqinter> -q)\\<^sup>+ \\<squnion> (f \\<sqinter> q)\\<^sup>T\\<^sup>+\"\n    using mult_left_isotone mult_right_isotone star_isotone sup_left_isotone conv_isotone order_trans inf_le1 by meson\n  also have \"... \\<le> f\\<^sup>\\<star> * e * f\\<^sup>T\\<^sup>\\<star> * f\\<^sup>\\<star> \\<squnion> (f \\<sqinter> q)\\<^sup>T\\<^sup>\\<star> * (f \\<sqinter> -q)\\<^sup>+ \\<squnion> f\\<^sup>T\\<^sup>+\"\n    using mult_left_isotone mult_right_isotone star_isotone sup_left_isotone sup_right_isotone conv_isotone order_trans inf_le1 by meson\n  also have \"... = f\\<^sup>\\<star> * e * f\\<^sup>T\\<^sup>\\<star> * f\\<^sup>\\<star> \\<squnion> (f \\<sqinter> q)\\<^sup>T\\<^sup>+ * (f \\<sqinter> -q)\\<^sup>+ \\<squnion> (f \\<sqinter> -q)\\<^sup>+ \\<squnion> f\\<^sup>T\\<^sup>+\"\n    by (simp add: star.circ_loop_fixpoint sup_monoid.add_assoc mult_assoc)\n  also have \"... \\<le> f\\<^sup>\\<star> * e * f\\<^sup>T\\<^sup>\\<star> * f\\<^sup>\\<star> \\<squnion> (f \\<sqinter> q)\\<^sup>T\\<^sup>+ * (f \\<sqinter> -q)\\<^sup>+ \\<squnion> f\\<^sup>+ \\<squnion> f\\<^sup>T\\<^sup>+\"\n    using mult_left_isotone mult_right_isotone star_isotone sup_left_isotone sup_right_isotone order_trans inf_le1 by meson\n  also have \"... \\<le> -1\"\n    using 7 8 9 assms(1) by simp\n  finally show ?thesis\n    by simp\nqed\n\nlemma kruskal_exchange_acyclic_inv_1:\n  assumes \"acyclic f\"\n      and \"covector q\"\n    shows \"acyclic ((f \\<sqinter> -q) \\<squnion> (f \\<sqinter> q)\\<^sup>T)\"\n  using kruskal_acyclic_inv[where e=bot] by (simp add: assms)\n\nlemma kruskal_exchange_acyclic_inv_2:\n  assumes \"acyclic w\"\n      and \"injective w\"\n      and \"d \\<le> w\"\n      and \"bijective (d\\<^sup>T * top)\"\n      and \"bijective (e * top)\"\n      and \"d \\<le> top * e\\<^sup>T * w\\<^sup>T\\<^sup>\\<star>\"\n      and \"w * e\\<^sup>T * top = bot\"\n    shows \"acyclic ((w \\<sqinter> -d) \\<squnion> e)\"\nproof -\n  let ?v = \"w \\<sqinter> -d\"\n  let ?w = \"?v \\<squnion> e\"\n  have \"d\\<^sup>T * top \\<le> w\\<^sup>\\<star> * e * top\"\n    by (metis assms(6) comp_associative comp_inf.star.circ_decompose_9 comp_inf.star_star_absorb comp_isotone conv_dist_comp conv_involutive conv_order conv_star_commute conv_top inf.cobounded1 vector_top_closed)\n  hence 1: \"e * top \\<le> w\\<^sup>T\\<^sup>\\<star> * d\\<^sup>T * top\"\n    by (metis assms(4,5) bijective_reverse comp_associative conv_star_commute)\n  have 2: \"?v * d\\<^sup>T * top = bot\"\n    by (simp add: assms(2,3) kruskal_exchange_acyclic_inv_3)\n  have \"?v * w\\<^sup>T\\<^sup>+ * d\\<^sup>T * top \\<le> w * w\\<^sup>T\\<^sup>+ * d\\<^sup>T * top\"\n    by (simp add: mult_left_isotone)\n  also have \"... \\<le> w\\<^sup>T\\<^sup>\\<star> * d\\<^sup>T * top\"\n    by (metis assms(2) mult_left_isotone mult_1_left mult_assoc)\n  finally have \"?v * w\\<^sup>T\\<^sup>\\<star> * d\\<^sup>T * top \\<le> w\\<^sup>T\\<^sup>\\<star> * d\\<^sup>T * top\"\n    using 2 by (metis bot_least comp_associative mult_right_dist_sup star.circ_back_loop_fixpoint star.circ_plus_same sup_least)\n  hence 3: \"?v\\<^sup>\\<star> * e * top \\<le> w\\<^sup>T\\<^sup>\\<star> * d\\<^sup>T * top\"\n    using 1 by (simp add: comp_associative star_left_induct sup_least)\n  have \"d * e\\<^sup>T \\<le> bot\"\n    by (metis assms(3,7) conv_bot conv_dist_comp conv_involutive conv_top order.trans inf.absorb2 inf.cobounded2 inf_commute le_bot p_antitone_iff p_top schroeder_4_p top_left_mult_increasing)\n  hence 4: \"e\\<^sup>T * top \\<le> -(d\\<^sup>T * top)\"\n    by (metis (no_types) comp_associative inf.cobounded2 le_bot p_antitone_iff schroeder_3_p semiring.mult_zero_left)\n  have \"?v\\<^sup>T * -(d\\<^sup>T * top) \\<le> -(d\\<^sup>T * top)\"\n    using schroeder_3_p mult_assoc 2 by simp\n  hence \"?v\\<^sup>T\\<^sup>\\<star> * e\\<^sup>T * top \\<le> -(d\\<^sup>T * top)\"\n    using 4 by (simp add: comp_associative star_left_induct sup_least)\n  hence 5: \"d\\<^sup>T * top \\<le> -(?v\\<^sup>T\\<^sup>\\<star> * e\\<^sup>T * top)\"\n    by (simp add: p_antitone_iff)\n  have \"w * ?v\\<^sup>T\\<^sup>\\<star> * e\\<^sup>T * top = w * e\\<^sup>T * top \\<squnion> w * ?v\\<^sup>T\\<^sup>+ * e\\<^sup>T * top\"\n    by (metis star_left_unfold_equal mult_right_dist_sup mult_left_dist_sup mult_1_right mult_assoc)\n  also have \"... = w * ?v\\<^sup>T\\<^sup>+ * e\\<^sup>T * top\"\n    using assms(7) by simp\n  also have \"... \\<le> w * w\\<^sup>T * ?v\\<^sup>T\\<^sup>\\<star> * e\\<^sup>T * top\"\n    by (simp add: comp_associative conv_isotone mult_left_isotone mult_right_isotone)\n  also have \"... \\<le> ?v\\<^sup>T\\<^sup>\\<star> * e\\<^sup>T * top\"\n    by (metis assms(2) mult_1_left mult_left_isotone)\n  finally have \"w * ?v\\<^sup>T\\<^sup>\\<star> * e\\<^sup>T * top \\<le> --(?v\\<^sup>T\\<^sup>\\<star> * e\\<^sup>T * top)\"\n    by (simp add: p_antitone p_antitone_iff)\n  hence \"w\\<^sup>T * -(?v\\<^sup>T\\<^sup>\\<star> * e\\<^sup>T * top) \\<le> -(?v\\<^sup>T\\<^sup>\\<star> * e\\<^sup>T * top)\"\n    using comp_associative schroeder_3_p by simp\n  hence 6: \"w\\<^sup>T\\<^sup>\\<star> * d\\<^sup>T * top \\<le> -(?v\\<^sup>T\\<^sup>\\<star> * e\\<^sup>T * top)\"\n    using 5 by (simp add: comp_associative star_left_induct sup_least)\n  have \"e * ?v\\<^sup>\\<star> * e \\<le> e * ?v\\<^sup>\\<star> * e * top\"\n    by (simp add: top_right_mult_increasing)\n  also have \"... \\<le> e * w\\<^sup>T\\<^sup>\\<star> * d\\<^sup>T * top\"\n    using 3 by (simp add: comp_associative mult_right_isotone)\n  also have \"... \\<le> e * -(?v\\<^sup>T\\<^sup>\\<star> * e\\<^sup>T * top)\"\n    using 6 by (simp add: comp_associative mult_right_isotone)\n  also have \"... \\<le> bot\"\n    by (metis conv_complement_sub_leq conv_dist_comp conv_involutive conv_star_commute le_bot mult_right_sub_dist_sup_right p_bot regular_closed_bot star.circ_back_loop_fixpoint)\n  finally have 7: \"e * ?v\\<^sup>\\<star> * e = bot\"\n    by (simp add: antisym)\n  hence \"?v\\<^sup>\\<star> * e \\<le> -1\"\n    by (metis bot_least comp_associative comp_commute_below_diversity ex231d order_lesseq_imp semiring.mult_zero_left star.circ_left_top)\n  hence 8: \"?v\\<^sup>\\<star> * e * ?v\\<^sup>\\<star> \\<le> -1\"\n    by (metis comp_associative comp_commute_below_diversity star.circ_transitive_equal)\n  have \"1 \\<sqinter> ?w\\<^sup>+ = 1 \\<sqinter> ?w * ?v\\<^sup>\\<star> * (e * ?v\\<^sup>\\<star>)\\<^sup>\\<star>\"\n    by (simp add: star_sup_1 mult_assoc)\n  also have \"... = 1 \\<sqinter> ?w * ?v\\<^sup>\\<star> * (e * ?v\\<^sup>\\<star> \\<squnion> 1)\"\n    using 7 by (metis star.circ_mult_1 star_absorb sup_monoid.add_commute mult_assoc)\n  also have \"... = 1 \\<sqinter> (?v\\<^sup>+ * e * ?v\\<^sup>\\<star> \\<squnion> ?v\\<^sup>+ \\<squnion> e * ?v\\<^sup>\\<star> * e * ?v\\<^sup>\\<star> \\<squnion> e * ?v\\<^sup>\\<star>)\"\n    by (simp add: comp_associative mult_left_dist_sup mult_right_dist_sup sup_assoc sup_commute sup_left_commute)\n  also have \"... = 1 \\<sqinter> (?v\\<^sup>+ * e * ?v\\<^sup>\\<star> \\<squnion> ?v\\<^sup>+ \\<squnion> e * ?v\\<^sup>\\<star>)\"\n    using 7 by simp\n  also have \"... = 1 \\<sqinter> (?v\\<^sup>\\<star> * e * ?v\\<^sup>\\<star> \\<squnion> ?v\\<^sup>+)\"\n    by (metis (mono_tags, hide_lams) comp_associative star.circ_loop_fixpoint sup_assoc sup_commute)\n  also have \"... \\<le> 1 \\<sqinter> (?v\\<^sup>\\<star> * e * ?v\\<^sup>\\<star> \\<squnion> w\\<^sup>+)\"\n    using comp_inf.mult_right_isotone comp_isotone semiring.add_right_mono star_isotone sup_commute by simp\n  also have \"... = (1 \\<sqinter> ?v\\<^sup>\\<star> * e * ?v\\<^sup>\\<star>) \\<squnion> (1 \\<sqinter> w\\<^sup>+)\"\n    by (simp add: inf_sup_distrib1)\n  also have \"... = 1 \\<sqinter> ?v\\<^sup>\\<star> * e * ?v\\<^sup>\\<star>\"\n    by (metis assms(1) inf_commute pseudo_complement sup_bot_right)\n  also have \"... = bot\"\n    using 8 p_antitone_iff pseudo_complement by simp\n  finally show ?thesis\n    using le_bot p_antitone_iff pseudo_complement by auto\nqed\n\nsubsubsection \\<open>Exchange gives Spanning Trees\\<close>\n\ntext \\<open>\nThe lemmas in this section are used to show that the relation after exchange represents a spanning tree.\n\\<close>\n\nlemma inf_star_import:\n  assumes \"x \\<le> z\"\n      and \"univalent z\"\n      and \"reflexive y\"\n      and \"regular z\"\n    shows \"x\\<^sup>\\<star> * y \\<sqinter> z\\<^sup>\\<star> \\<le> x\\<^sup>\\<star> * (y \\<sqinter> z\\<^sup>\\<star>)\"\nproof -\n  have 1: \"y \\<le> x\\<^sup>\\<star> * (y \\<sqinter> z\\<^sup>\\<star>) \\<squnion> -z\\<^sup>\\<star>\"\n    by (metis assms(4) pp_dist_star shunting_var_p star.circ_loop_fixpoint sup.cobounded2)\n  have \"x * -z\\<^sup>\\<star> \\<sqinter> z\\<^sup>+ \\<le> x * (-z\\<^sup>\\<star> \\<sqinter> x\\<^sup>T * z\\<^sup>+)\"\n    by (simp add: dedekind_1)\n  also have \"... \\<le> x * (-z\\<^sup>\\<star> \\<sqinter> z\\<^sup>T * z\\<^sup>+)\"\n    using assms(1) comp_inf.mult_right_isotone conv_isotone mult_left_isotone mult_right_isotone by simp\n  also have \"... \\<le> x * (-z\\<^sup>\\<star> \\<sqinter> 1 * z\\<^sup>\\<star>)\"\n    by (metis assms(2) comp_associative comp_inf.mult_right_isotone mult_left_isotone mult_right_isotone)\n  finally have 2: \"x * -z\\<^sup>\\<star> \\<sqinter> z\\<^sup>+ = bot\"\n    by (simp add: antisym)\n  have \"x * -z\\<^sup>\\<star> \\<sqinter> z\\<^sup>\\<star> = (x * -z\\<^sup>\\<star> \\<sqinter> z\\<^sup>+) \\<squnion> (x * -z\\<^sup>\\<star> \\<sqinter> 1)\"\n    by (metis comp_inf.semiring.distrib_left star_left_unfold_equal sup_commute)\n  also have \"... \\<le> x\\<^sup>\\<star> * (y \\<sqinter> z\\<^sup>\\<star>)\"\n    using 2 by (simp add: assms(3) inf.coboundedI2 reflexive_mult_closed star.circ_reflexive)\n  finally have \"x * -z\\<^sup>\\<star> \\<le> x\\<^sup>\\<star> * (y \\<sqinter> z\\<^sup>\\<star>) \\<squnion> -z\\<^sup>\\<star>\"\n    by (metis assms(4) pp_dist_star shunting_var_p)\n  hence \"x * (x\\<^sup>\\<star> * (y \\<sqinter> z\\<^sup>\\<star>) \\<squnion> -z\\<^sup>\\<star>) \\<le> x\\<^sup>\\<star> * (y \\<sqinter> z\\<^sup>\\<star>) \\<squnion> -z\\<^sup>\\<star>\"\n    by (metis le_supE le_supI mult_left_dist_sup star.circ_loop_fixpoint sup.cobounded1)\n  hence \"x\\<^sup>\\<star> * y \\<le> x\\<^sup>\\<star> * (y \\<sqinter> z\\<^sup>\\<star>) \\<squnion> -z\\<^sup>\\<star>\"\n    using 1 by (simp add: star_left_induct)\n  hence \"x\\<^sup>\\<star> * y \\<sqinter> --z\\<^sup>\\<star> \\<le> x\\<^sup>\\<star> * (y \\<sqinter> z\\<^sup>\\<star>)\"\n    using shunting_var_p by simp\n  thus ?thesis\n    using order.trans inf.sup_right_isotone pp_increasing by blast\nqed\n\nlemma kruskal_exchange_forest_components_inv:\n  assumes \"injective ((w \\<sqinter> -d) \\<squnion> e)\"\n      and \"regular d\"\n      and \"e * top * e = e\"\n      and \"d \\<le> top * e\\<^sup>T * w\\<^sup>T\\<^sup>\\<star>\"\n      and \"w * e\\<^sup>T * top = bot\"\n      and \"injective w\"\n      and \"d \\<le> w\"\n      and \"d \\<le> (w \\<sqinter> -d)\\<^sup>T\\<^sup>\\<star> * e\\<^sup>T * top\"\n    shows \"forest_components w \\<le> forest_components ((w \\<sqinter> -d) \\<squnion> e)\"\nproof -\n  let ?v = \"w \\<sqinter> -d\"\n  let ?w = \"?v \\<squnion> e\"\n  let ?f = \"forest_components ?w\"\n  have 1: \"?v * d\\<^sup>T * top = bot\"\n    by (simp add: assms(6,7) kruskal_exchange_acyclic_inv_3)\n  have 2: \"d * e\\<^sup>T \\<le> bot\"\n    by (metis assms(5,7) conv_bot conv_dist_comp conv_involutive conv_top order.trans inf.absorb2 inf.cobounded2 inf_commute le_bot p_antitone_iff p_top schroeder_4_p top_left_mult_increasing)\n  have \"w\\<^sup>\\<star> * e\\<^sup>T * top = e\\<^sup>T * top\"\n    by (metis assms(5) conv_bot conv_dist_comp conv_involutive conv_star_commute star.circ_top star_absorb)\n  hence \"w\\<^sup>\\<star> * e\\<^sup>T * top \\<le> -(d\\<^sup>T * top)\"\n    using 2 by (metis (no_types) comp_associative inf.cobounded2 le_bot p_antitone_iff schroeder_3_p semiring.mult_zero_left)\n  hence 3: \"e\\<^sup>T * top \\<le> -(w\\<^sup>T\\<^sup>\\<star> * d\\<^sup>T * top)\"\n    by (metis conv_star_commute p_antitone_iff schroeder_3_p mult_assoc)\n  have \"?v * w\\<^sup>T\\<^sup>\\<star> * d\\<^sup>T * top = ?v * d\\<^sup>T * top \\<squnion> ?v * w\\<^sup>T\\<^sup>+ * d\\<^sup>T * top\"\n    by (metis comp_associative mult_left_dist_sup star.circ_loop_fixpoint sup_commute)\n  also have \"... \\<le> w * w\\<^sup>T\\<^sup>+ * d\\<^sup>T * top\"\n    using 1 by (simp add: mult_left_isotone)\n  also have \"... \\<le> w\\<^sup>T\\<^sup>\\<star> * d\\<^sup>T * top\"\n    by (metis assms(6) mult_assoc mult_1_left mult_left_isotone)\n  finally have \"?v * w\\<^sup>T\\<^sup>\\<star> * d\\<^sup>T * top \\<le> --(w\\<^sup>T\\<^sup>\\<star> * d\\<^sup>T * top)\"\n    using p_antitone p_antitone_iff by auto\n  hence 4: \"?v\\<^sup>T * -(w\\<^sup>T\\<^sup>\\<star> * d\\<^sup>T * top) \\<le> -(w\\<^sup>T\\<^sup>\\<star> * d\\<^sup>T * top)\"\n    using comp_associative schroeder_3_p by simp\n  have 5: \"injective ?v\"\n    using assms(1) conv_dist_sup mult_left_dist_sup mult_right_dist_sup by simp\n  have \"?v * ?v\\<^sup>T\\<^sup>\\<star> * e\\<^sup>T * top = ?v * e\\<^sup>T * top \\<squnion> ?v * ?v\\<^sup>T\\<^sup>+ * e\\<^sup>T * top\"\n    by (metis comp_associative mult_left_dist_sup star.circ_loop_fixpoint sup_commute)\n  also have \"... \\<le> w * e\\<^sup>T * top \\<squnion> ?v * ?v\\<^sup>T\\<^sup>+ * e\\<^sup>T * top\"\n    using mult_left_isotone sup_left_isotone by simp\n  also have \"... \\<le> w * e\\<^sup>T * top \\<squnion> ?v\\<^sup>T\\<^sup>\\<star> * e\\<^sup>T * top\"\n    using 5 by (metis mult_assoc mult_1_left mult_left_isotone sup_right_isotone)\n  finally have \"?v * ?v\\<^sup>T\\<^sup>\\<star> * e\\<^sup>T * top \\<le> ?v\\<^sup>T\\<^sup>\\<star> * e\\<^sup>T * top\"\n    by (simp add: assms(5))\n  hence \"?v\\<^sup>\\<star> * d * top \\<le> ?v\\<^sup>T\\<^sup>\\<star> * e\\<^sup>T * top\"\n    by (metis assms(8) star_left_induct sup_least comp_associative mult_right_sub_dist_sup_right sup.orderE vector_top_closed)\n  also have \"... \\<le> -(w\\<^sup>T\\<^sup>\\<star> * d\\<^sup>T * top)\"\n    using 3 4 by (simp add: comp_associative star_left_induct)\n  also have \"... \\<le> -(d\\<^sup>T * top)\"\n    by (metis p_antitone star.circ_left_top star_outer_increasing mult_assoc)\n  finally have 6: \"?v\\<^sup>\\<star> * d * top \\<le> -(d\\<^sup>T * top)\"\n    by simp\n  have \"d\\<^sup>T * top \\<le> w\\<^sup>\\<star> * e * top\"\n    by (metis assms(4) comp_associative comp_inf.star.circ_sup_2 comp_isotone conv_dist_comp conv_involutive conv_order conv_star_commute conv_top vector_top_closed)\n  also have \"... \\<le> (?v \\<squnion> d)\\<^sup>\\<star> * e * top\"\n    by (metis assms(2) comp_inf.semiring.distrib_left maddux_3_11_pp mult_left_isotone star_isotone sup.cobounded2 sup_commute sup_inf_distrib1)\n  also have \"... = ?v\\<^sup>\\<star> * (d * ?v\\<^sup>\\<star>)\\<^sup>\\<star> * e * top\"\n    by (simp add: star_sup_1)\n  also have \"... = ?v\\<^sup>\\<star> * e * top \\<squnion> ?v\\<^sup>\\<star> * d * ?v\\<^sup>\\<star> * (d * ?v\\<^sup>\\<star>)\\<^sup>\\<star> * e * top\"\n    by (metis semiring.distrib_right star.circ_unfold_sum star_decompose_1 star_decompose_3 mult_assoc)\n  also have \"... \\<le> ?v\\<^sup>\\<star> * e * top \\<squnion> ?v\\<^sup>\\<star> * d * top\"\n    by (metis comp_associative comp_isotone le_supI mult_left_dist_sup mult_right_dist_sup mult_right_isotone star.circ_decompose_5 star_decompose_3 sup.cobounded1 sup_commute top.extremum)\n  finally have \"d\\<^sup>T * top \\<le> ?v\\<^sup>\\<star> * e * top \\<squnion> (d\\<^sup>T * top \\<sqinter> ?v\\<^sup>\\<star> * d * top)\"\n    using sup_inf_distrib2 sup_monoid.add_commute by simp\n  hence \"d\\<^sup>T * top \\<le> ?v\\<^sup>\\<star> * e * top\"\n    using 6 by (metis inf_commute pseudo_complement sup_monoid.add_0_right)\n  hence 7: \"d \\<le> top * e\\<^sup>T * ?v\\<^sup>T\\<^sup>\\<star>\"\n    by (metis comp_associative conv_dist_comp conv_involutive conv_isotone conv_star_commute conv_top order.trans top_right_mult_increasing)\n  have 8: \"?v \\<le> ?f\"\n    using forest_components_increasing le_supE by blast\n  have \"d \\<le> ?v\\<^sup>T\\<^sup>\\<star> * e\\<^sup>T * top \\<sqinter> top * e\\<^sup>T * ?v\\<^sup>T\\<^sup>\\<star>\"\n    using 7 assms(8) by simp\n  also have \"... = ?v\\<^sup>T\\<^sup>\\<star> * e\\<^sup>T * top * e\\<^sup>T * ?v\\<^sup>T\\<^sup>\\<star>\"\n    by (metis inf_top_right vector_inf_comp vector_top_closed mult_assoc)\n  also have \"... = ?v\\<^sup>T\\<^sup>\\<star> * e\\<^sup>T * ?v\\<^sup>T\\<^sup>\\<star>\"\n    by (metis assms(3) comp_associative conv_dist_comp conv_top)\n  also have \"... \\<le> ?v\\<^sup>T\\<^sup>\\<star> * e\\<^sup>T * ?f\"\n    using 8 by (metis assms(1) forest_components_equivalence cancel_separate_1 conv_dist_comp conv_order mult_left_isotone star_involutive star_isotone)\n  also have \"... \\<le> ?v\\<^sup>T\\<^sup>\\<star> * ?f * ?f\"\n    by (metis assms(1) forest_components_equivalence forest_components_increasing conv_isotone le_supE mult_left_isotone mult_right_isotone)\n  also have \"... \\<le> ?f * ?f * ?f\"\n    by (metis comp_associative comp_isotone conv_dist_sup star.circ_loop_fixpoint star_isotone sup.cobounded1 sup.cobounded2)\n  also have \"... = ?f\"\n    by (simp add: assms(1) forest_components_equivalence preorder_idempotent)\n  finally have \"w \\<le> ?f\"\n    using 8 by (metis assms(2) shunting_var_p sup.orderE)\n  thus ?thesis\n    using assms(1) forest_components_idempotent forest_components_isotone by fastforce\nqed\n\nlemma kruskal_spanning_inv:\n  assumes \"injective ((f \\<sqinter> -q) \\<squnion> (f \\<sqinter> q)\\<^sup>T \\<squnion> e)\"\n      and \"regular q\"\n      and \"regular e\"\n      and \"(-h \\<sqinter> --g)\\<^sup>\\<star> \\<le> forest_components f\"\n    shows \"components (-(h \\<sqinter> -e \\<sqinter> -e\\<^sup>T) \\<sqinter> g) \\<le> forest_components ((f \\<sqinter> -q) \\<squnion> (f \\<sqinter> q)\\<^sup>T \\<squnion> e)\"\nproof -\n  let ?f = \"(f \\<sqinter> -q) \\<squnion> (f \\<sqinter> q)\\<^sup>T \\<squnion> e\"\n  let ?h = \"h \\<sqinter> -e \\<sqinter> -e\\<^sup>T\"\n  let ?F = \"forest_components f\"\n  let ?FF = \"forest_components ?f\"\n  have 1: \"equivalence ?FF\"\n    using assms(1) forest_components_equivalence by simp\n  hence 2: \"?f * ?FF \\<le> ?FF\"\n    using order.trans forest_components_increasing mult_left_isotone by blast\n  have 3: \"?f\\<^sup>T * ?FF \\<le> ?FF\"\n    using 1 by (metis forest_components_increasing mult_left_isotone conv_isotone preorder_idempotent)\n  have \"(f \\<sqinter> q) * ?FF \\<le> ?f\\<^sup>T * ?FF\"\n    using conv_dist_sup conv_involutive sup_assoc sup_left_commute mult_left_isotone by simp\n  hence 4: \"(f \\<sqinter> q) * ?FF \\<le> ?FF\"\n    using 3 order.trans by blast\n  have \"(f \\<sqinter> -q) * ?FF \\<le> ?f * ?FF\"\n    using le_supI1 mult_left_isotone by simp\n  hence \"(f \\<sqinter> -q) * ?FF \\<le> ?FF\"\n    using 2 order.trans by blast\n  hence \"((f \\<sqinter> q) \\<squnion> (f \\<sqinter> -q)) * ?FF \\<le> ?FF\"\n    using 4 mult_right_dist_sup by simp\n  hence \"f * ?FF \\<le> ?FF\"\n    by (metis assms(2) maddux_3_11_pp)\n  hence 5: \"f\\<^sup>\\<star> * ?FF \\<le> ?FF\"\n    using star_left_induct_mult_iff by simp\n  have \"(f \\<sqinter> -q)\\<^sup>T * ?FF \\<le> ?f\\<^sup>T * ?FF\"\n    by (meson conv_isotone order.trans mult_left_isotone sup.cobounded1)\n  hence 6: \"(f \\<sqinter> -q)\\<^sup>T * ?FF \\<le> ?FF\"\n    using 3 order.trans by blast\n  have \"(f \\<sqinter> q)\\<^sup>T * ?FF \\<le> ?f * ?FF\"\n    by (simp add: mult_left_isotone sup.left_commute sup_assoc)\n  hence \"(f \\<sqinter> q)\\<^sup>T * ?FF \\<le> ?FF\"\n    using 2 order.trans by blast\n  hence \"((f \\<sqinter> -q)\\<^sup>T \\<squnion> (f \\<sqinter> q)\\<^sup>T) * ?FF \\<le> ?FF\"\n    using 6 mult_right_dist_sup by simp\n  hence \"f\\<^sup>T * ?FF \\<le> ?FF\"\n    by (metis assms(2) conv_dist_sup maddux_3_11_pp)\n  hence 7: \"?F * ?FF \\<le> ?FF\"\n    using 5 star_left_induct mult_assoc by simp\n  have 8: \"e * ?FF \\<le> ?FF\"\n    using 2 by (simp add: mult_right_dist_sup mult_left_isotone)\n  have \"e\\<^sup>T * ?FF \\<le> ?f\\<^sup>T * ?FF\"\n    by (simp add: mult_left_isotone conv_isotone)\n  also have \"... \\<le> ?FF * ?FF\"\n    using 1 by (metis forest_components_increasing mult_left_isotone conv_isotone)\n  finally have \"e\\<^sup>T * ?FF \\<le> ?FF\"\n    using 1 preorder_idempotent by auto\n  hence 9: \"(?F \\<squnion> e \\<squnion> e\\<^sup>T) * ?FF \\<le> ?FF\"\n    using 7 8 mult_right_dist_sup by simp\n  have \"components (-?h \\<sqinter> g) \\<le> ((-h \\<sqinter> --g) \\<squnion> e \\<squnion> e\\<^sup>T)\\<^sup>\\<star>\"\n    by (metis assms(3) comp_inf.mult_left_sub_dist_sup_left conv_complement p_dist_inf pp_dist_inf regular_closed_p star_isotone sup_inf_distrib2 sup_monoid.add_assoc)\n  also have \"... \\<le> ((-h \\<sqinter> --g)\\<^sup>\\<star> \\<squnion> e \\<squnion> e\\<^sup>T)\\<^sup>\\<star>\"\n    using star.circ_increasing star_isotone sup_left_isotone by simp\n  also have \"... \\<le> (?F \\<squnion> e \\<squnion> e\\<^sup>T)\\<^sup>\\<star>\"\n    using assms(4) sup_left_isotone star_isotone by simp\n  also have \"... \\<le> ?FF\"\n    using 1 9 star_left_induct by force\n  finally show ?thesis\n    by simp\nqed\n\nlemma kruskal_exchange_spanning_inv_1:\n  assumes \"injective ((w \\<sqinter> -q) \\<squnion> (w \\<sqinter> q)\\<^sup>T)\"\n      and \"regular (w \\<sqinter> q)\"\n      and \"components g \\<le> forest_components w\"\n    shows \"components g \\<le> forest_components ((w \\<sqinter> -q) \\<squnion> (w \\<sqinter> q)\\<^sup>T)\"\nproof -\n  let ?p = \"w \\<sqinter> q\"\n  let ?w = \"(w \\<sqinter> -q) \\<squnion> ?p\\<^sup>T\"\n  have 1: \"w \\<sqinter> -?p \\<le> forest_components ?w\"\n    by (metis forest_components_increasing inf_import_p le_supE)\n  have \"w \\<sqinter> ?p \\<le> ?w\\<^sup>T\"\n    by (simp add: conv_dist_sup)\n  also have \"... \\<le> forest_components ?w\"\n    by (metis assms(1) conv_isotone forest_components_equivalence forest_components_increasing)\n  finally have \"w \\<sqinter> (?p \\<squnion> -?p) \\<le> forest_components ?w\"\n    using 1 inf_sup_distrib1 by simp\n  hence \"w \\<le> forest_components ?w\"\n    by (metis assms(2) inf_top_right stone)\n  hence 2: \"w\\<^sup>\\<star> \\<le> forest_components ?w\"\n    using assms(1) star_isotone forest_components_star by force\n  hence 3: \"w\\<^sup>T\\<^sup>\\<star> \\<le> forest_components ?w\"\n    using assms(1) conv_isotone conv_star_commute forest_components_equivalence by force\n  have \"components g \\<le> forest_components w\"\n    using assms(3) by simp\n  also have \"... \\<le> forest_components ?w * forest_components ?w\"\n    using 2 3 mult_isotone by simp\n  also have \"... = forest_components ?w\"\n    using assms(1) forest_components_equivalence preorder_idempotent by simp\n  finally show ?thesis\n    by simp\nqed\n\nlemma kruskal_exchange_spanning_inv_2:\n  assumes \"injective w\"\n      and \"w\\<^sup>\\<star> * e\\<^sup>T = e\\<^sup>T\"\n      and \"f \\<squnion> f\\<^sup>T \\<le> (w \\<sqinter> -d \\<sqinter> -d\\<^sup>T) \\<squnion> (w\\<^sup>T \\<sqinter> -d \\<sqinter> -d\\<^sup>T)\"\n      and \"d \\<le> forest_components f * e\\<^sup>T * top\"\n    shows \"d \\<le> (w \\<sqinter> -d)\\<^sup>T\\<^sup>\\<star> * e\\<^sup>T * top\"\nproof -\n  have 1: \"(w \\<sqinter> -d \\<sqinter> -d\\<^sup>T) * (w\\<^sup>T \\<sqinter> -d \\<sqinter> -d\\<^sup>T) \\<le> 1\"\n    using assms(1) comp_isotone order.trans inf.cobounded1 by blast\n  have \"d \\<le> forest_components f * e\\<^sup>T * top\"\n    using assms(4) by simp\n  also have \"... \\<le> (f \\<squnion> f\\<^sup>T)\\<^sup>\\<star> * (f \\<squnion> f\\<^sup>T)\\<^sup>\\<star> * e\\<^sup>T * top\"\n    by (simp add: comp_isotone star_isotone)\n  also have \"... = (f \\<squnion> f\\<^sup>T)\\<^sup>\\<star> * e\\<^sup>T * top\"\n    by (simp add: star.circ_transitive_equal)\n  also have \"... \\<le> ((w \\<sqinter> -d \\<sqinter> -d\\<^sup>T) \\<squnion> (w\\<^sup>T \\<sqinter> -d \\<sqinter> -d\\<^sup>T))\\<^sup>\\<star> * e\\<^sup>T * top\"\n    using assms(3) by (simp add: comp_isotone star_isotone)\n  also have \"... = (w\\<^sup>T \\<sqinter> -d \\<sqinter> -d\\<^sup>T)\\<^sup>\\<star> * (w \\<sqinter> -d \\<sqinter> -d\\<^sup>T)\\<^sup>\\<star> * e\\<^sup>T * top\"\n    using 1 cancel_separate_1 by simp\n  also have \"... \\<le> (w\\<^sup>T \\<sqinter> -d \\<sqinter> -d\\<^sup>T)\\<^sup>\\<star> * w\\<^sup>\\<star> * e\\<^sup>T * top\"\n    by (simp add: inf_assoc mult_left_isotone mult_right_isotone star_isotone)\n  also have \"... = (w\\<^sup>T \\<sqinter> -d \\<sqinter> -d\\<^sup>T)\\<^sup>\\<star> * e\\<^sup>T * top\"\n    using assms(2) mult_assoc by simp\n  also have \"... \\<le> (w\\<^sup>T \\<sqinter> -d\\<^sup>T)\\<^sup>\\<star> * e\\<^sup>T * top\"\n    using mult_left_isotone conv_isotone star_isotone comp_inf.mult_right_isotone inf.cobounded2 inf.left_commute inf.sup_monoid.add_commute by presburger\n  also have \"... = (w \\<sqinter> -d)\\<^sup>T\\<^sup>\\<star> * e\\<^sup>T * top\"\n    using conv_complement conv_dist_inf by presburger\n  finally show ?thesis\n    by simp\nqed\n\nlemma kruskal_spanning_inv_1:\n  assumes \"e \\<le> F\"\n      and \"regular e\"\n      and \"components (-h \\<sqinter> g) \\<le> F\"\n      and \"equivalence F\"\n    shows \"components (-(h \\<sqinter> -e \\<sqinter> -e\\<^sup>T) \\<sqinter> g) \\<le> F\"\nproof -\n  have 1: \"F * F \\<le> F\"\n    using assms(4) by simp\n  hence 2: \"e * F \\<le> F\"\n    using assms(1) mult_left_isotone order_lesseq_imp by blast\n  have \"e\\<^sup>T * F \\<le> F\"\n    by (metis assms(1,4) conv_isotone mult_left_isotone preorder_idempotent)\n  hence 3: \"(F \\<squnion> e \\<squnion> e\\<^sup>T) * F \\<le> F\"\n    using 1 2 mult_right_dist_sup by simp\n  have \"components (-(h \\<sqinter> -e \\<sqinter> -e\\<^sup>T) \\<sqinter> g) \\<le> ((-h \\<sqinter> --g) \\<squnion> e \\<squnion> e\\<^sup>T)\\<^sup>\\<star>\"\n    by (metis assms(2) comp_inf.mult_left_sub_dist_sup_left conv_complement p_dist_inf pp_dist_inf regular_closed_p star_isotone sup_inf_distrib2 sup_monoid.add_assoc)\n  also have \"... \\<le> ((-h \\<sqinter> --g)\\<^sup>\\<star> \\<squnion> e \\<squnion> e\\<^sup>T)\\<^sup>\\<star>\"\n    using sup_left_isotone star.circ_increasing star_isotone by simp\n  also have \"... \\<le> (F \\<squnion> e \\<squnion> e\\<^sup>T)\\<^sup>\\<star>\"\n    using assms(3) sup_left_isotone star_isotone by simp\n  also have \"... \\<le> F\"\n    using 3 assms(4) star_left_induct by force\n  finally show ?thesis\n    by simp\nqed\n\nlemma kruskal_reroot_edge:\n  assumes \"injective (e\\<^sup>T * top)\"\n      and \"acyclic w\"\n    shows \"((w \\<sqinter> -(top * e * w\\<^sup>T\\<^sup>\\<star>)) \\<squnion> (w \\<sqinter> top * e * w\\<^sup>T\\<^sup>\\<star>)\\<^sup>T) * e\\<^sup>T = bot\"\nproof -\n  let ?q = \"top * e * w\\<^sup>T\\<^sup>\\<star>\"\n  let ?p = \"w \\<sqinter> ?q\"\n  let ?w = \"(w \\<sqinter> -?q) \\<squnion> ?p\\<^sup>T\"\n  have \"(w \\<sqinter> -?q) * e\\<^sup>T * top = w * (e\\<^sup>T * top \\<sqinter> -?q\\<^sup>T)\"\n    by (metis comp_associative comp_inf_vector_1 conv_complement covector_complement_closed vector_top_closed)\n  also have \"... = w * (e\\<^sup>T * top \\<sqinter> -(w\\<^sup>\\<star> * e\\<^sup>T * top))\"\n    by (simp add: conv_dist_comp conv_star_commute mult_assoc)\n  also have \"... = bot\"\n    by (metis comp_associative comp_inf.semiring.mult_not_zero inf.sup_relative_same_increasing inf_p mult_right_zero star.circ_loop_fixpoint sup_commute sup_left_divisibility)\n  finally have 1: \"(w \\<sqinter> -?q) * e\\<^sup>T * top = bot\"\n    by simp\n  have \"?p\\<^sup>T * e\\<^sup>T * top = (w\\<^sup>T \\<sqinter> w\\<^sup>\\<star> * e\\<^sup>T * top) * e\\<^sup>T * top\"\n    by (simp add: conv_dist_comp conv_star_commute mult_assoc conv_dist_inf)\n  also have \"... = w\\<^sup>\\<star> * e\\<^sup>T * top \\<sqinter> w\\<^sup>T * e\\<^sup>T * top\"\n    by (simp add: inf_vector_comp vector_export_comp)\n  also have \"... = (w\\<^sup>\\<star> \\<sqinter> w\\<^sup>T) * e\\<^sup>T * top\"\n    using assms(1) injective_comp_right_dist_inf mult_assoc by simp\n  also have \"... = bot\"\n    using assms(2) acyclic_star_below_complement_1 semiring.mult_not_zero by blast\n  finally have \"?w * e\\<^sup>T * top = bot\"\n    using 1 mult_right_dist_sup by simp\n  thus ?thesis\n    by (metis star.circ_top star_absorb)\nqed\n\nsubsubsection \\<open>Exchange gives Minimum Spanning Trees\\<close>\n\ntext \\<open>\nThe lemmas in this section are used to show that the after exchange we obtain a minimum spanning tree.\nThe following lemmas show that the relation characterising the edge across the cut is an arc.\n\\<close>\n\nlemma kruskal_edge_arc:\n  assumes \"equivalence F\"\n      and \"forest w\"\n      and \"arc e\"\n      and \"regular F\"\n      and \"F \\<le> forest_components (F \\<sqinter> w)\"\n      and \"regular w\"\n      and \"w * e\\<^sup>T = bot\"\n      and \"e * F * e = bot\"\n      and \"e\\<^sup>T \\<le> w\\<^sup>\\<star>\"\n    shows \"arc (w \\<sqinter> top * e\\<^sup>T * w\\<^sup>T\\<^sup>\\<star> \\<sqinter> F * e\\<^sup>T * top \\<sqinter> top * e * -F)\"\nproof (unfold arc_expanded, intro conjI)\n  let ?E = \"top * e\\<^sup>T * w\\<^sup>T\\<^sup>\\<star>\"\n  let ?F = \"F * e\\<^sup>T * top\"\n  let ?G = \"top * e * -F\"\n  let ?FF = \"F * e\\<^sup>T * e * F\"\n  let ?GG = \"-F * e\\<^sup>T * e * -F\"\n  let ?w = \"forest_components (F \\<sqinter> w)\"\n  have \"F \\<sqinter> w\\<^sup>T\\<^sup>\\<star> \\<le> forest_components (F \\<sqinter> w) \\<sqinter> w\\<^sup>T\\<^sup>\\<star>\"\n    by (simp add: assms(5) inf.coboundedI1)\n  also have \"... \\<le> (F \\<sqinter> w)\\<^sup>T\\<^sup>\\<star> * ((F \\<sqinter> w)\\<^sup>\\<star> \\<sqinter> w\\<^sup>T\\<^sup>\\<star>)\"\n    apply (rule inf_star_import)\n    apply (simp add: conv_isotone)\n    apply (simp add: assms(2))\n    apply (simp add: star.circ_reflexive)\n    by (metis assms(6) conv_complement)\n  also have \"... \\<le> (F \\<sqinter> w)\\<^sup>T\\<^sup>\\<star> * (w\\<^sup>\\<star> \\<sqinter> w\\<^sup>T\\<^sup>\\<star>)\"\n    using comp_inf.mult_left_isotone mult_right_isotone star_isotone by simp\n  also have \"... = (F \\<sqinter> w)\\<^sup>T\\<^sup>\\<star>\"\n    by (simp add: assms(2) acyclic_star_inf_conv)\n  finally have \"w * (F \\<sqinter> w\\<^sup>T\\<^sup>\\<star>) * e\\<^sup>T * e \\<le> w * (F \\<sqinter> w)\\<^sup>T\\<^sup>\\<star> * e\\<^sup>T * e\"\n    by (simp add: mult_left_isotone mult_right_isotone)\n  also have \"... = w * e\\<^sup>T * e \\<squnion> w * (F \\<sqinter> w)\\<^sup>T\\<^sup>+ * e\\<^sup>T * e\"\n    by (metis comp_associative mult_left_dist_sup star.circ_loop_fixpoint sup_commute)\n  also have \"... = w * (F \\<sqinter> w)\\<^sup>T\\<^sup>+ * e\\<^sup>T * e\"\n    by (simp add: assms(7))\n  also have \"... \\<le> w * (F \\<sqinter> w)\\<^sup>T\\<^sup>+\"\n    by (metis assms(3) arc_univalent mult_assoc mult_1_right mult_right_isotone)\n  also have \"... \\<le> w * w\\<^sup>T * (F \\<sqinter> w)\\<^sup>T\\<^sup>\\<star>\"\n    by (simp add: comp_associative conv_isotone mult_left_isotone mult_right_isotone)\n  also have \"... \\<le> (F \\<sqinter> w)\\<^sup>T\\<^sup>\\<star>\"\n    using assms(2) coreflexive_comp_top_inf inf.sup_right_divisibility by auto\n  also have \"... \\<le> F\\<^sup>T\\<^sup>\\<star>\"\n    by (simp add: conv_dist_inf star_isotone)\n  finally have 1: \"w * (F \\<sqinter> w\\<^sup>T\\<^sup>\\<star>) * e\\<^sup>T * e \\<le> F\"\n    by (metis assms(1) antisym mult_1_left mult_left_isotone star.circ_plus_same star.circ_reflexive star.left_plus_below_circ star_left_induct_mult_iff)\n  have \"F * e\\<^sup>T * e \\<le> forest_components (F \\<sqinter> w) * e\\<^sup>T * e\"\n    by (simp add: assms(5) mult_left_isotone)\n  also have \"... \\<le> forest_components w * e\\<^sup>T * e\"\n    by (simp add: comp_isotone conv_dist_inf star_isotone)\n  also have \"... = w\\<^sup>T\\<^sup>\\<star> * e\\<^sup>T * e\"\n    by (metis (no_types) assms(7) comp_associative conv_bot conv_dist_comp conv_involutive conv_star_commute star_absorb)\n  also have \"... \\<le> w\\<^sup>T\\<^sup>\\<star>\"\n    by (metis assms(3) arc_univalent mult_assoc mult_1_right mult_right_isotone)\n  finally have 2: \"F * e\\<^sup>T * e \\<le> w\\<^sup>T\\<^sup>\\<star>\"\n    by simp\n  have \"w * F * e\\<^sup>T * e \\<le> w * F * e\\<^sup>T * e * e\\<^sup>T * e\"\n    using comp_associative ex231c mult_right_isotone by simp\n  also have \"... = w * (F * e\\<^sup>T * e \\<sqinter> w\\<^sup>T\\<^sup>\\<star>) * e\\<^sup>T * e\"\n    using 2 by (simp add: comp_associative inf.absorb1)\n  also have \"... \\<le> w * (F \\<sqinter> w\\<^sup>T\\<^sup>\\<star>) * e\\<^sup>T * e\"\n    by (metis assms(3) arc_univalent mult_assoc mult_1_right mult_right_isotone mult_left_isotone inf.sup_left_isotone)\n  also have \"... \\<le> F\"\n    using 1 by simp\n  finally have 3: \"w * F * e\\<^sup>T * e \\<le> F\"\n    by simp\n  hence \"e\\<^sup>T * e * F * w\\<^sup>T \\<le> F\"\n    by (metis assms(1) conv_dist_comp conv_dist_inf conv_involutive inf.absorb_iff1 mult_assoc)\n  hence \"e\\<^sup>T * e * F * w\\<^sup>T \\<le> e\\<^sup>T * top \\<sqinter> F\"\n    by (simp add: comp_associative mult_right_isotone)\n  also have \"... \\<le> e\\<^sup>T * e * F\"\n    by (metis conv_involutive dedekind_1 inf_top_left mult_assoc)\n  finally have 4: \"e\\<^sup>T * e * F * w\\<^sup>T \\<le> e\\<^sup>T * e * F\"\n    by simp\n  have \"(top * e)\\<^sup>T * (?F \\<sqinter> w\\<^sup>T\\<^sup>\\<star>) = e\\<^sup>T * top * e * F * w\\<^sup>T\\<^sup>\\<star>\"\n    by (metis assms(1) comp_inf.star.circ_decompose_9 comp_inf.star_star_absorb conv_dist_comp conv_involutive conv_top covector_inf_comp_3 vector_top_closed mult_assoc)\n  also have \"... = e\\<^sup>T * e * F * w\\<^sup>T\\<^sup>\\<star>\"\n    by (simp add: assms(3) arc_top_edge)\n  also have \"... \\<le> e\\<^sup>T * e * F\"\n    using 4 star_right_induct_mult by simp\n  also have \"... \\<le> F\"\n    by (metis assms(3) arc_injective conv_involutive mult_1_left mult_left_isotone)\n  finally have 5: \"(top * e)\\<^sup>T * (?F \\<sqinter> w\\<^sup>T\\<^sup>\\<star>) \\<le> F\"\n    by simp\n  have \"(?F \\<sqinter> w) * w\\<^sup>T\\<^sup>+ = ?F \\<sqinter> w * w\\<^sup>T\\<^sup>+\"\n    by (simp add: vector_export_comp)\n  also have \"... \\<le> ?F \\<sqinter> w\\<^sup>T\\<^sup>\\<star>\"\n    by (metis assms(2) comp_associative inf.sup_right_isotone mult_left_isotone star.circ_transitive_equal star_left_unfold_equal sup.absorb_iff2 sup_monoid.add_assoc)\n  also have 6: \"... \\<le> top * e * F\"\n    using 5 by (metis assms(3) shunt_mapping conv_dist_comp conv_involutive conv_top)\n  finally have 7: \"(?F \\<sqinter> w) * w\\<^sup>T\\<^sup>+ \\<le> top * e * F\"\n    by simp\n  have \"e\\<^sup>T * top * e \\<le> 1\"\n    by (simp add: assms(3) point_injective)\n  also have \"... \\<le> F\"\n    by (simp add: assms(1))\n  finally have 8: \"e * -F * e\\<^sup>T \\<le> bot\"\n    by (metis p_antitone p_antitone_iff p_bot regular_closed_bot schroeder_3_p schroeder_4_p mult_assoc)\n  have \"?FF \\<sqinter> w * (w\\<^sup>T\\<^sup>+ \\<sqinter> ?GG) * w\\<^sup>T \\<le> ?F \\<sqinter> w * (w\\<^sup>T\\<^sup>+ \\<sqinter> ?GG) * w\\<^sup>T\"\n    using comp_inf.mult_left_isotone mult_isotone mult_assoc by simp\n  also have \"... \\<le> ?F \\<sqinter> w * (w\\<^sup>T\\<^sup>+ \\<sqinter> ?G) * w\\<^sup>T\"\n    by (metis assms(3) arc_top_edge comp_inf.star.circ_decompose_9 comp_inf_covector inf.sup_right_isotone inf_le2 mult_left_isotone mult_right_isotone vector_top_closed mult_assoc)\n  also have \"... = (?F \\<sqinter> w) * (w\\<^sup>T\\<^sup>+ \\<sqinter> ?G) * w\\<^sup>T\"\n    by (simp add: vector_export_comp)\n  also have \"... = (?F \\<sqinter> w) * w\\<^sup>T\\<^sup>+ * (?G\\<^sup>T \\<sqinter> w\\<^sup>T)\"\n    by (simp add: covector_comp_inf covector_comp_inf_1 covector_mult_closed)\n  also have \"... \\<le> top * e * F * (?G\\<^sup>T \\<sqinter> w\\<^sup>T)\"\n    using 7 mult_left_isotone by simp\n  also have \"... \\<le> top * e * F * ?G\\<^sup>T\"\n    by (simp add: mult_right_isotone)\n  also have \"... = top * e * -F * e\\<^sup>T * top\"\n    by (metis assms(1) conv_complement conv_dist_comp conv_top equivalence_comp_left_complement mult_assoc)\n  finally have 9: \"?FF \\<sqinter> w * (w\\<^sup>T\\<^sup>+ \\<sqinter> ?GG) * w\\<^sup>T = bot\"\n    using 8 by (metis comp_associative covector_bot_closed le_bot vector_bot_closed)\n  hence 10: \"?FF \\<sqinter> w * (w\\<^sup>+ \\<sqinter> ?GG) * w\\<^sup>T = bot\"\n    using assms(1) comp_associative conv_bot conv_complement conv_dist_comp conv_dist_inf conv_star_commute star.circ_plus_same by fastforce\n  have \"(w \\<sqinter> ?E \\<sqinter> ?F \\<sqinter> ?G) * top * (w \\<sqinter> ?E \\<sqinter> ?F \\<sqinter> ?G)\\<^sup>T = (?F \\<sqinter> (w \\<sqinter> ?E \\<sqinter> ?G)) * top * ((w \\<sqinter> ?E \\<sqinter> ?G)\\<^sup>T \\<sqinter> ?F\\<^sup>T)\"\n    by (simp add: conv_dist_inf inf_commute inf_left_commute)\n  also have \"... = (?F \\<sqinter> (w \\<sqinter> ?E \\<sqinter> ?G)) * top * (w \\<sqinter> ?E \\<sqinter> ?G)\\<^sup>T \\<sqinter> ?F\\<^sup>T\"\n    using covector_comp_inf vector_conv_covector vector_mult_closed vector_top_closed by simp\n  also have \"... = ?F \\<sqinter> (w \\<sqinter> ?E \\<sqinter> ?G) * top * (w \\<sqinter> ?E \\<sqinter> ?G)\\<^sup>T \\<sqinter> ?F\\<^sup>T\"\n    by (simp add: vector_export_comp)\n  also have \"... = ?F \\<sqinter> top * e * F \\<sqinter> (w \\<sqinter> ?E \\<sqinter> ?G) * top * (w \\<sqinter> ?E \\<sqinter> ?G)\\<^sup>T\"\n    by (simp add: assms(1) conv_dist_comp inf_assoc inf_commute mult_assoc)\n  also have \"... = ?F * e * F \\<sqinter> (w \\<sqinter> ?E \\<sqinter> ?G) * top * (w \\<sqinter> ?E \\<sqinter> ?G)\\<^sup>T\"\n    by (metis comp_associative comp_inf_covector inf_top.left_neutral)\n  also have \"... = ?FF \\<sqinter> (w \\<sqinter> ?E \\<sqinter> ?G) * (top * (w \\<sqinter> ?E \\<sqinter> ?G)\\<^sup>T)\"\n    using assms(3) arc_top_edge comp_associative by simp\n  also have \"... = ?FF \\<sqinter> (w \\<sqinter> ?E \\<sqinter> ?G) * (top * (?G\\<^sup>T \\<sqinter> (?E\\<^sup>T \\<sqinter> w\\<^sup>T)))\"\n    by (simp add: conv_dist_inf inf_assoc inf_commute inf_left_commute)\n  also have \"... = ?FF \\<sqinter> (w \\<sqinter> ?E \\<sqinter> ?G) * (?G * (?E\\<^sup>T \\<sqinter> w\\<^sup>T))\"\n    by (metis covector_comp_inf_1 covector_top_closed covector_mult_closed inf_top_left)\n  also have \"... = ?FF \\<sqinter> (w \\<sqinter> ?E \\<sqinter> ?G) * (?G \\<sqinter> ?E) * w\\<^sup>T\"\n    by (metis covector_comp_inf_1 covector_top_closed mult_assoc)\n  also have \"... = ?FF \\<sqinter> (w \\<sqinter> ?E) * (?G\\<^sup>T \\<sqinter> ?G \\<sqinter> ?E) * w\\<^sup>T\"\n    by (metis covector_comp_inf_1 covector_mult_closed inf.sup_monoid.add_assoc vector_top_closed)\n  also have \"... = ?FF \\<sqinter> w * (?E\\<^sup>T \\<sqinter> ?G\\<^sup>T \\<sqinter> ?G \\<sqinter> ?E) * w\\<^sup>T\"\n    by (metis covector_comp_inf_1 covector_mult_closed inf.sup_monoid.add_assoc vector_top_closed)\n  also have \"... = ?FF \\<sqinter> w * (?E\\<^sup>T \\<sqinter> ?E \\<sqinter> (?G\\<^sup>T \\<sqinter> ?G)) * w\\<^sup>T\"\n    by (simp add: inf_commute inf_left_commute)\n  also have \"... = ?FF \\<sqinter> w * (?E\\<^sup>T \\<sqinter> ?E \\<sqinter> (-F * e\\<^sup>T * top \\<sqinter> ?G)) * w\\<^sup>T\"\n    by (simp add: assms(1) conv_complement conv_dist_comp mult_assoc)\n  also have \"... = ?FF \\<sqinter> w * (?E\\<^sup>T \\<sqinter> ?E \\<sqinter> (-F * e\\<^sup>T * ?G)) * w\\<^sup>T\"\n    by (metis comp_associative comp_inf_covector inf_top.left_neutral)\n  also have \"... = ?FF \\<sqinter> w * (?E\\<^sup>T \\<sqinter> ?E \\<sqinter> ?GG) * w\\<^sup>T\"\n    by (metis assms(3) arc_top_edge comp_associative)\n  also have \"... = ?FF \\<sqinter> w * (w\\<^sup>\\<star> * e * top \\<sqinter> ?E \\<sqinter> ?GG) * w\\<^sup>T\"\n    by (simp add: comp_associative conv_dist_comp conv_star_commute)\n  also have \"... = ?FF \\<sqinter> w * (w\\<^sup>\\<star> * e * ?E \\<sqinter> ?GG) * w\\<^sup>T\"\n    by (metis comp_associative comp_inf_covector inf_top.left_neutral)\n  also have \"... \\<le> ?FF \\<sqinter> w * (w\\<^sup>\\<star> * w\\<^sup>T\\<^sup>\\<star> \\<sqinter> ?GG) * w\\<^sup>T\"\n    by (metis assms(3) mult_assoc mult_1_right mult_left_isotone mult_right_isotone inf.sup_left_isotone inf.sup_right_isotone arc_expanded)\n  also have \"... = ?FF \\<sqinter> w * ((w\\<^sup>+ \\<squnion> 1 \\<squnion> w\\<^sup>T\\<^sup>\\<star>) \\<sqinter> ?GG) * w\\<^sup>T\"\n    by (simp add: assms(2) cancel_separate_eq star_left_unfold_equal sup_monoid.add_commute)\n  also have \"... = ?FF \\<sqinter> w * ((w\\<^sup>+ \\<squnion> 1 \\<squnion> w\\<^sup>T\\<^sup>+) \\<sqinter> ?GG) * w\\<^sup>T\"\n    using star.circ_plus_one star_left_unfold_equal sup_assoc by presburger\n  also have \"... = (?FF \\<sqinter> w * (w\\<^sup>+ \\<sqinter> ?GG) * w\\<^sup>T) \\<squnion> (?FF \\<sqinter> w * (1 \\<sqinter> ?GG) * w\\<^sup>T) \\<squnion> (?FF \\<sqinter> w * (w\\<^sup>T\\<^sup>+ \\<sqinter> ?GG) * w\\<^sup>T)\"\n    by (simp add: inf_sup_distrib1 inf_sup_distrib2 semiring.distrib_left semiring.distrib_right)\n  also have \"... \\<le> w * (1 \\<sqinter> ?GG) * w\\<^sup>T\"\n    using 9 10 by simp\n  also have \"... \\<le> w * w\\<^sup>T\"\n    by (metis inf.cobounded1 mult_1_right mult_left_isotone mult_right_isotone)\n  also have \"... \\<le> 1\"\n    by (simp add: assms(2))\n  finally show \"(w \\<sqinter> ?E \\<sqinter> ?F \\<sqinter> ?G) * top * (w \\<sqinter> ?E \\<sqinter> ?F \\<sqinter> ?G)\\<^sup>T \\<le> 1\"\n    by simp\n  have \"w\\<^sup>T\\<^sup>+ \\<sqinter> -F * e\\<^sup>T * e * -F \\<sqinter> w\\<^sup>T * F * e\\<^sup>T * e * F * w \\<le> w\\<^sup>T\\<^sup>+ \\<sqinter> ?G \\<sqinter> w\\<^sup>T * F * e\\<^sup>T * e * F * w\"\n    using top_greatest inf.sup_left_isotone inf.sup_right_isotone mult_left_isotone by simp\n  also have \"... \\<le> w\\<^sup>T\\<^sup>+ \\<sqinter> ?G \\<sqinter> w\\<^sup>T * ?F\"\n    using comp_associative inf.sup_right_isotone mult_right_isotone top.extremum by presburger\n  also have \"... = w\\<^sup>T * (w\\<^sup>T\\<^sup>\\<star> \\<sqinter> ?F) \\<sqinter> ?G\"\n    using assms(2) inf_assoc inf_commute inf_left_commute univalent_comp_left_dist_inf by simp\n  also have \"... \\<le> w\\<^sup>T * (top * e * F) \\<sqinter> ?G\"\n    using 6 by (metis inf.sup_monoid.add_commute inf.sup_right_isotone mult_right_isotone)\n  also have \"... \\<le> top * e * F \\<sqinter> ?G\"\n    by (metis comp_associative comp_inf_covector mult_left_isotone top.extremum)\n  also have \"... = bot\"\n    by (metis assms(3) conv_dist_comp conv_involutive conv_top inf_p mult_right_zero univalent_comp_left_dist_inf)\n  finally have 11: \"w\\<^sup>T\\<^sup>+ \\<sqinter> -F * e\\<^sup>T * e * -F \\<sqinter> w\\<^sup>T * F * e\\<^sup>T * e * F * w = bot\"\n    by (simp add: antisym)\n  hence 12: \"w\\<^sup>+ \\<sqinter> -F * e\\<^sup>T * e * -F \\<sqinter> w\\<^sup>T * F * e\\<^sup>T * e * F * w = bot\"\n    using assms(1) comp_associative conv_bot conv_complement conv_dist_comp conv_dist_inf conv_star_commute star.circ_plus_same by fastforce\n  have \"(w \\<sqinter> ?E \\<sqinter> ?F \\<sqinter> ?G)\\<^sup>T * top * (w \\<sqinter> ?E \\<sqinter> ?F \\<sqinter> ?G) = ((w \\<sqinter> ?E \\<sqinter> ?G)\\<^sup>T \\<sqinter> ?F\\<^sup>T) * top * (?F \\<sqinter> (w \\<sqinter> ?E \\<sqinter> ?G))\"\n    by (simp add: conv_dist_inf inf_commute inf_left_commute)\n  also have \"... = (w \\<sqinter> ?E \\<sqinter> ?G)\\<^sup>T * ?F * (?F \\<sqinter> (w \\<sqinter> ?E \\<sqinter> ?G))\"\n    by (simp add: covector_inf_comp_3 vector_mult_closed)\n  also have \"... = (w \\<sqinter> ?E \\<sqinter> ?G)\\<^sup>T * (?F \\<sqinter> ?F\\<^sup>T) * (w \\<sqinter> ?E \\<sqinter> ?G)\"\n    using covector_comp_inf covector_inf_comp_3 vector_conv_covector vector_mult_closed by simp\n  also have \"... = (w \\<sqinter> ?E \\<sqinter> ?G)\\<^sup>T * (?F \\<sqinter> ?F\\<^sup>T) * (w \\<sqinter> ?E) \\<sqinter> ?G\"\n    by (simp add: comp_associative comp_inf_covector)\n  also have \"... = (w \\<sqinter> ?E \\<sqinter> ?G)\\<^sup>T * (?F \\<sqinter> ?F\\<^sup>T) * w \\<sqinter> ?E \\<sqinter> ?G\"\n    by (simp add: comp_associative comp_inf_covector)\n  also have \"... = (?G\\<^sup>T \\<sqinter> (?E\\<^sup>T \\<sqinter> w\\<^sup>T)) * (?F \\<sqinter> ?F\\<^sup>T) * w \\<sqinter> ?E \\<sqinter> ?G\"\n    by (simp add: conv_dist_inf inf.left_commute inf.sup_monoid.add_commute)\n  also have \"... = ?G\\<^sup>T \\<sqinter> (?E\\<^sup>T \\<sqinter> w\\<^sup>T) * (?F \\<sqinter> ?F\\<^sup>T) * w \\<sqinter> ?E \\<sqinter> ?G\"\n    by (metis (no_types) comp_associative conv_dist_comp conv_top vector_export_comp)\n  also have \"... = ?G\\<^sup>T \\<sqinter> ?E\\<^sup>T \\<sqinter> w\\<^sup>T * (?F \\<sqinter> ?F\\<^sup>T) * w \\<sqinter> ?E \\<sqinter> ?G\"\n    by (metis (no_types) comp_associative inf_assoc conv_dist_comp conv_top vector_export_comp)\n  also have \"... = ?E\\<^sup>T \\<sqinter> ?E \\<sqinter> (?G\\<^sup>T \\<sqinter> ?G) \\<sqinter> w\\<^sup>T * (?F \\<sqinter> ?F\\<^sup>T) * w\"\n    by (simp add: inf_assoc inf.left_commute inf.sup_monoid.add_commute)\n  also have \"... = w\\<^sup>\\<star> * e * top \\<sqinter> ?E \\<sqinter> (?G\\<^sup>T \\<sqinter> ?G) \\<sqinter> w\\<^sup>T * (?F \\<sqinter> ?F\\<^sup>T) * w\"\n    by (simp add: comp_associative conv_dist_comp conv_star_commute)\n  also have \"... = w\\<^sup>\\<star> * e * ?E \\<sqinter> (?G\\<^sup>T \\<sqinter> ?G) \\<sqinter> w\\<^sup>T * (?F \\<sqinter> ?F\\<^sup>T) * w\"\n    by (metis comp_associative comp_inf_covector inf_top.left_neutral)\n  also have \"... \\<le> w\\<^sup>\\<star> * w\\<^sup>T\\<^sup>\\<star> \\<sqinter> (?G\\<^sup>T \\<sqinter> ?G) \\<sqinter> w\\<^sup>T * (?F \\<sqinter> ?F\\<^sup>T) * w\"\n    by (metis assms(3) mult_assoc mult_1_right mult_left_isotone mult_right_isotone inf.sup_left_isotone arc_expanded)\n  also have \"... = w\\<^sup>\\<star> * w\\<^sup>T\\<^sup>\\<star> \\<sqinter> (-F * e\\<^sup>T * top \\<sqinter> ?G) \\<sqinter> w\\<^sup>T * (?F \\<sqinter> ?F\\<^sup>T) * w\"\n    by (simp add: assms(1) conv_complement conv_dist_comp mult_assoc)\n  also have \"... = w\\<^sup>\\<star> * w\\<^sup>T\\<^sup>\\<star> \\<sqinter> -F * e\\<^sup>T * ?G \\<sqinter> w\\<^sup>T * (?F \\<sqinter> ?F\\<^sup>T) * w\"\n    by (metis comp_associative comp_inf_covector inf_top.left_neutral)\n  also have \"... = w\\<^sup>\\<star> * w\\<^sup>T\\<^sup>\\<star> \\<sqinter> -F * e\\<^sup>T * e * -F \\<sqinter> w\\<^sup>T * (?F \\<sqinter> ?F\\<^sup>T) * w\"\n    by (metis assms(3) arc_top_edge mult_assoc)\n  also have \"... = w\\<^sup>\\<star> * w\\<^sup>T\\<^sup>\\<star> \\<sqinter> -F * e\\<^sup>T * e * -F \\<sqinter> w\\<^sup>T * (?F \\<sqinter> top * e * F) * w\"\n    by (simp add: assms(1) conv_dist_comp mult_assoc)\n  also have \"... = w\\<^sup>\\<star> * w\\<^sup>T\\<^sup>\\<star> \\<sqinter> -F * e\\<^sup>T * e * -F \\<sqinter> w\\<^sup>T * (?F * e * F) * w\"\n    by (metis comp_associative comp_inf_covector inf_top.left_neutral)\n  also have \"... = w\\<^sup>\\<star> * w\\<^sup>T\\<^sup>\\<star> \\<sqinter> -F * e\\<^sup>T * e * -F \\<sqinter> w\\<^sup>T * F * e\\<^sup>T * e * F * w\"\n    by (metis assms(3) arc_top_edge mult_assoc)\n  also have \"... = (w\\<^sup>+ \\<squnion> 1 \\<squnion> w\\<^sup>T\\<^sup>\\<star>) \\<sqinter> -F * e\\<^sup>T * e * -F \\<sqinter> w\\<^sup>T * F * e\\<^sup>T * e * F * w\"\n    by (simp add: assms(2) cancel_separate_eq star_left_unfold_equal sup_monoid.add_commute)\n  also have \"... = (w\\<^sup>+ \\<squnion> 1 \\<squnion> w\\<^sup>T\\<^sup>+) \\<sqinter> -F * e\\<^sup>T * e * -F \\<sqinter> w\\<^sup>T * F * e\\<^sup>T * e * F * w\"\n    using star.circ_plus_one star_left_unfold_equal sup_assoc by presburger\n  also have \"... = (w\\<^sup>+ \\<sqinter> -F * e\\<^sup>T * e * -F \\<sqinter> w\\<^sup>T * F * e\\<^sup>T * e * F * w) \\<squnion> (1 \\<sqinter> -F * e\\<^sup>T * e * -F \\<sqinter> w\\<^sup>T * F * e\\<^sup>T * e * F * w) \\<squnion> (w\\<^sup>T\\<^sup>+ \\<sqinter> -F * e\\<^sup>T * e * -F \\<sqinter> w\\<^sup>T * F * e\\<^sup>T * e * F * w)\"\n    by (simp add: inf_sup_distrib2)\n  also have \"... \\<le> 1\"\n    using 11 12 by (simp add: inf.coboundedI1)\n  finally show \"(w \\<sqinter> ?E \\<sqinter> ?F \\<sqinter> ?G)\\<^sup>T * top * (w \\<sqinter> ?E \\<sqinter> ?F \\<sqinter> ?G) \\<le> 1\"\n    by simp\n  have \"(w \\<sqinter> -F) * (F \\<sqinter> w\\<^sup>T) \\<le> w * w\\<^sup>T \\<sqinter> -F * F\"\n    by (simp add: mult_isotone)\n  also have \"... \\<le> 1 \\<sqinter> -F\"\n    using assms(1,2) comp_inf.comp_isotone equivalence_comp_right_complement by auto\n  also have \"... = bot\"\n    using assms(1) bot_unique pp_isotone pseudo_complement_pp by blast\n  finally have 13: \"(w \\<sqinter> -F) * (F \\<sqinter> w\\<^sup>T) = bot\"\n    by (simp add: antisym)\n  have \"w \\<sqinter> ?G \\<le> F * (w \\<sqinter> ?G)\"\n    by (metis assms(1) mult_1_left mult_right_dist_sup sup.absorb_iff2)\n  also have \"... \\<le> F * (w \\<sqinter> ?G) * w\\<^sup>\\<star>\"\n    by (metis eq_refl le_supE star.circ_back_loop_fixpoint)\n  finally have 14: \"w \\<sqinter> ?G \\<le> F * (w \\<sqinter> ?G) * w\\<^sup>\\<star>\"\n    by simp\n  have \"w \\<sqinter> top * e * F \\<le> w * (e * F)\\<^sup>T * e * F\"\n    by (metis (no_types) comp_inf.star_slide dedekind_2 inf_left_commute inf_top_right mult_assoc)\n  also have \"... \\<le> F\"\n    using 3 assms(1) by (metis comp_associative conv_dist_comp mult_left_isotone preorder_idempotent)\n  finally have \"w \\<sqinter> -F \\<le> -(top * e * F)\"\n    using order.trans p_shunting_swap pp_increasing by blast\n  also have \"... = ?G\"\n    by (metis assms(3) comp_mapping_complement conv_dist_comp conv_involutive conv_top)\n  finally have \"(w \\<sqinter> -F) * F * (w \\<sqinter> ?G) = (w \\<sqinter> -F \\<sqinter> ?G) * F * (w \\<sqinter> ?G)\"\n    by (simp add: inf.absorb1)\n  also have \"... \\<le> (w \\<sqinter> -F \\<sqinter> ?G) * F * w\"\n    by (simp add: comp_isotone)\n  also have \"... \\<le> (w \\<sqinter> -F \\<sqinter> ?G) * forest_components (F \\<sqinter> w) * w\"\n    by (simp add: assms(5) mult_left_isotone mult_right_isotone)\n  also have \"... \\<le> (w \\<sqinter> -F \\<sqinter> ?G) * (F \\<sqinter> w)\\<^sup>T\\<^sup>\\<star> * w\\<^sup>\\<star> * w\"\n    by (simp add: mult_left_isotone mult_right_isotone star_isotone mult_assoc)\n  also have \"... \\<le> (w \\<sqinter> -F \\<sqinter> ?G) * (F \\<sqinter> w)\\<^sup>T\\<^sup>\\<star> * w\\<^sup>\\<star>\"\n    by (simp add: comp_associative mult_right_isotone star.circ_plus_same star.left_plus_below_circ)\n  also have \"... = (w \\<sqinter> -F \\<sqinter> ?G) * w\\<^sup>\\<star> \\<squnion> (w \\<sqinter> -F \\<sqinter> ?G) * (F \\<sqinter> w)\\<^sup>T\\<^sup>+ * w\\<^sup>\\<star>\"\n    by (metis comp_associative inf.sup_monoid.add_assoc mult_left_dist_sup star.circ_loop_fixpoint sup_commute)\n  also have \"... \\<le> (w \\<sqinter> -F \\<sqinter> ?G) * w\\<^sup>\\<star> \\<squnion> (w \\<sqinter> -F \\<sqinter> ?G) * (F \\<sqinter> w)\\<^sup>T * top\"\n    by (metis mult_assoc top_greatest mult_right_isotone sup_right_isotone)\n  also have \"... \\<le> (w \\<sqinter> -F \\<sqinter> ?G) * w\\<^sup>\\<star> \\<squnion> (w \\<sqinter> -F) * (F \\<sqinter> w)\\<^sup>T * top\"\n    using inf.cobounded1 mult_left_isotone sup_right_isotone by blast\n  also have \"... \\<le> (w \\<sqinter> ?G) * w\\<^sup>\\<star> \\<squnion> (w \\<sqinter> -F) * (F \\<sqinter> w)\\<^sup>T * top\"\n    using inf.sup_monoid.add_assoc inf.sup_right_isotone mult_left_isotone sup_commute sup_right_isotone by simp\n  also have \"... = (w \\<sqinter> ?G) * w\\<^sup>\\<star> \\<squnion> (w \\<sqinter> -F) * (F \\<sqinter> w\\<^sup>T) * top\"\n    by (simp add: assms(1) conv_dist_inf)\n  also have \"... \\<le> 1 * (w \\<sqinter> ?G) * w\\<^sup>\\<star>\"\n    using 13 by simp\n  also have \"... \\<le> F * (w \\<sqinter> ?G) * w\\<^sup>\\<star>\"\n    using assms(1) mult_left_isotone by blast\n  finally have 15: \"(w \\<sqinter> -F) * F * (w \\<sqinter> ?G) \\<le> F * (w \\<sqinter> ?G) * w\\<^sup>\\<star>\"\n    by simp\n  have \"(w \\<sqinter> F) * F * (w \\<sqinter> ?G) \\<le> F * F * (w \\<sqinter> ?G)\"\n    by (simp add: mult_left_isotone)\n  also have \"... = F * (w \\<sqinter> ?G)\"\n    by (simp add: assms(1) preorder_idempotent)\n  also have \"... \\<le> F * (w \\<sqinter> ?G) * w\\<^sup>\\<star>\"\n    by (metis eq_refl le_supE star.circ_back_loop_fixpoint)\n  finally have \"(w \\<sqinter> F) * F * (w \\<sqinter> ?G) \\<le> F * (w \\<sqinter> ?G) * w\\<^sup>\\<star>\"\n    by simp\n  hence \"((w \\<sqinter> F) \\<squnion> (w \\<sqinter> -F)) * F * (w \\<sqinter> ?G) \\<le> F * (w \\<sqinter> ?G) * w\\<^sup>\\<star>\"\n    using 15 by (simp add: semiring.distrib_right)\n  hence \"w * F * (w \\<sqinter> ?G) \\<le> F * (w \\<sqinter> ?G) * w\\<^sup>\\<star>\"\n    by (metis assms(4) maddux_3_11_pp)\n  hence \"w * F * (w \\<sqinter> ?G) * w\\<^sup>\\<star> \\<le> F * (w \\<sqinter> ?G) * w\\<^sup>\\<star>\"\n    by (metis (full_types) comp_associative mult_left_isotone star.circ_transitive_equal)\n  hence \"w\\<^sup>\\<star> * (w \\<sqinter> ?G) \\<le> F * (w \\<sqinter> ?G) * w\\<^sup>\\<star>\"\n    using 14 by (simp add: mult_assoc star_left_induct)\n  hence 16: \"w\\<^sup>+ \\<sqinter> ?G \\<le> F * (w \\<sqinter> ?G) * w\\<^sup>\\<star>\"\n    by (simp add: covector_comp_inf covector_mult_closed star.circ_plus_same)\n  have 17: \"e\\<^sup>T * top * e\\<^sup>T \\<le> -F\"\n    using assms(8) le_bot triple_schroeder_p by simp\n  hence \"(top * e)\\<^sup>T * e\\<^sup>T \\<le> -F\"\n    by (simp add: conv_dist_comp)\n  hence 18: \"e\\<^sup>T \\<le> ?G\"\n    by (metis assms(3) shunt_mapping conv_dist_comp conv_involutive conv_top)\n  have \"e\\<^sup>T \\<le> -F\"\n    using 17 by (simp add: assms(3) arc_top_arc)\n  also have \"... \\<le> -1\"\n    by (simp add: assms(1) p_antitone)\n  finally have \"e\\<^sup>T \\<le> w\\<^sup>\\<star> \\<sqinter> -1\"\n    using assms(9) by simp\n  also have \"... \\<le> w\\<^sup>+\"\n    using shunting_var_p star_left_unfold_equal sup_commute by simp\n  finally have \"e\\<^sup>T \\<le> w\\<^sup>+ \\<sqinter> ?G\"\n    using 18 by simp\n  hence \"e\\<^sup>T \\<le> F * (w \\<sqinter> ?G) * w\\<^sup>\\<star>\"\n    using 16 order_trans by blast\n  also have \"... = (F * w \\<sqinter> ?G) * w\\<^sup>\\<star>\"\n    by (simp add: comp_associative comp_inf_covector)\n  finally have \"e\\<^sup>T * top * e\\<^sup>T \\<le> (F * w \\<sqinter> ?G) * w\\<^sup>\\<star>\"\n    by (simp add: assms(3) arc_top_arc)\n  hence \"e\\<^sup>T * top * (e * top)\\<^sup>T \\<le> (F * w \\<sqinter> ?G) * w\\<^sup>\\<star>\"\n    by (metis conv_dist_comp conv_top vector_top_closed mult_assoc)\n  hence \"e\\<^sup>T * top \\<le> (F * w \\<sqinter> ?G) * w\\<^sup>\\<star> * e * top\"\n    by (metis assms(3) shunt_bijective mult_assoc)\n  hence \"(top * e)\\<^sup>T * top \\<le> (F * w \\<sqinter> ?G) * w\\<^sup>\\<star> * e * top\"\n    by (simp add: conv_dist_comp mult_assoc)\n  hence \"top \\<le> top * e * (F * w \\<sqinter> ?G) * w\\<^sup>\\<star> * e * top\"\n    by (metis assms(3) shunt_mapping conv_dist_comp conv_involutive conv_top mult_assoc)\n  also have \"... = top * e * F * w * (w\\<^sup>\\<star> * e * top \\<sqinter> ?G\\<^sup>T)\"\n    by (metis comp_associative comp_inf_vector_1)\n  also have \"... = top * (w \\<sqinter> (top * e * F)\\<^sup>T) * (w\\<^sup>\\<star> * e * top \\<sqinter> ?G\\<^sup>T)\"\n    by (metis comp_inf_vector_1 inf_top.left_neutral)\n  also have \"... = top * (w \\<sqinter> ?F) * (w\\<^sup>\\<star> * e * top \\<sqinter> ?G\\<^sup>T)\"\n    by (simp add: assms(1) conv_dist_comp mult_assoc)\n  also have \"... = top * (w \\<sqinter> ?F) * (?E\\<^sup>T \\<sqinter> ?G\\<^sup>T)\"\n    by (simp add: comp_associative conv_dist_comp conv_star_commute)\n  also have \"... = top * (w \\<sqinter> ?F \\<sqinter> ?G) * ?E\\<^sup>T\"\n    by (simp add: comp_associative comp_inf_vector_1)\n  also have \"... = top * (w \\<sqinter> ?F \\<sqinter> ?G \\<sqinter> ?E) * top\"\n    using comp_inf_vector_1 mult_assoc by simp\n  finally show \"top * (w \\<sqinter> ?E \\<sqinter> ?F \\<sqinter> ?G) * top = top\"\n    by (simp add: inf_commute inf_left_commute top_le)\nqed\n\nlemma kruskal_edge_arc_1:\n  assumes \"e \\<le> --h\"\n      and \"h \\<le> g\"\n      and \"symmetric g\"\n      and \"components g \\<le> forest_components w\"\n      and \"w * e\\<^sup>T = bot\"\n    shows \"e\\<^sup>T \\<le> w\\<^sup>\\<star>\"\nproof -\n  have \"w\\<^sup>T * top \\<le> -(e\\<^sup>T * top)\"\n    using assms(5) schroeder_3_p vector_bot_closed mult_assoc by fastforce\n  hence 1: \"w\\<^sup>T * top \\<sqinter> e\\<^sup>T * top = bot\"\n    using pseudo_complement by simp\n  have \"e\\<^sup>T \\<le> e\\<^sup>T * top \\<sqinter> --h\\<^sup>T\"\n    using assms(1) conv_complement conv_isotone top_right_mult_increasing by fastforce\n  also have \"... \\<le> e\\<^sup>T * top \\<sqinter> --g\"\n    by (metis assms(2,3) inf.sup_right_isotone pp_isotone conv_isotone)\n  also have \"... \\<le> e\\<^sup>T * top \\<sqinter> components g\"\n    using inf.sup_right_isotone star.circ_increasing by simp\n  also have \"... \\<le> e\\<^sup>T * top \\<sqinter> forest_components w\"\n    using assms(4) comp_inf.mult_right_isotone by simp\n  also have \"... = (e\\<^sup>T * top \\<sqinter> w\\<^sup>T\\<^sup>\\<star>) * w\\<^sup>\\<star>\"\n    by (simp add: inf_assoc vector_export_comp)\n  also have \"... = (e\\<^sup>T * top \\<sqinter> 1) * w\\<^sup>\\<star> \\<squnion> (e\\<^sup>T * top \\<sqinter> w\\<^sup>T\\<^sup>+) * w\\<^sup>\\<star>\"\n    by (metis inf_sup_distrib1 semiring.distrib_right star_left_unfold_equal)\n  also have \"... \\<le> w\\<^sup>\\<star> \\<squnion> (e\\<^sup>T * top \\<sqinter> w\\<^sup>T\\<^sup>+) * w\\<^sup>\\<star>\"\n    by (metis inf_le2 mult_1_left mult_left_isotone sup_left_isotone)\n  also have \"... \\<le> w\\<^sup>\\<star> \\<squnion> (e\\<^sup>T * top \\<sqinter> w\\<^sup>T) * top\"\n    using comp_associative comp_inf.mult_right_isotone sup_right_isotone mult_right_isotone top.extremum vector_export_comp by presburger\n  also have \"... = w\\<^sup>\\<star>\"\n    using 1 inf.sup_monoid.add_commute inf_vector_comp by simp\n  finally show ?thesis\n    by simp\nqed\n\nlemma kruskal_edge_between_components_1:\n  assumes \"equivalence F\"\n      and \"mapping (top * e)\"\n    shows \"F \\<le> -(w \\<sqinter> top * e\\<^sup>T * w\\<^sup>T\\<^sup>\\<star> \\<sqinter> F * e\\<^sup>T * top \\<sqinter> top * e * -F)\"\nproof -\n  let ?d = \"w \\<sqinter> top * e\\<^sup>T * w\\<^sup>T\\<^sup>\\<star> \\<sqinter> F * e\\<^sup>T * top \\<sqinter> top * e * -F\"\n  have \"?d \\<sqinter> F \\<le> F * e\\<^sup>T * top \\<sqinter> F\"\n    by (meson inf_le1 inf_le2 le_infI order_trans)\n  also have \"... \\<le> (F * e\\<^sup>T * top)\\<^sup>T * F\"\n    by (simp add: mult_assoc vector_restrict_comp_conv)\n  also have \"... = top * e * F * F\"\n    by (simp add: assms(1) comp_associative conv_dist_comp conv_star_commute)\n  also have \"... = top * e * F\"\n    using assms(1) preorder_idempotent mult_assoc by fastforce\n  finally have \"?d \\<sqinter> F \\<le> top * e * F \\<sqinter> top * e * -F\"\n    by (simp add: le_infI1)\n  also have \"... = top * e * F \\<sqinter> -(top * e * F)\"\n    using assms(2) conv_dist_comp total_conv_surjective comp_mapping_complement by simp\n  finally show ?thesis\n    by (metis inf_p le_bot p_antitone_iff pseudo_complement)\nqed\n\nlemma kruskal_edge_between_components_2:\n  assumes \"forest_components f \\<le> -d\"\n      and \"injective f\"\n      and \"f \\<squnion> f\\<^sup>T \\<le> w \\<squnion> w\\<^sup>T\"\n    shows \"f \\<squnion> f\\<^sup>T \\<le> (w \\<sqinter> -d \\<sqinter> -d\\<^sup>T) \\<squnion> (w\\<^sup>T \\<sqinter> -d \\<sqinter> -d\\<^sup>T)\"\nproof -\n  let ?F = \"forest_components f\"\n  have \"?F\\<^sup>T \\<le> -d\\<^sup>T\"\n    using assms(1) conv_complement conv_order by fastforce\n  hence 1: \"?F \\<le> -d\\<^sup>T\"\n    by (simp add: conv_dist_comp conv_star_commute)\n  have \"equivalence ?F\"\n    using assms(2) forest_components_equivalence by simp\n  hence \"f \\<squnion> f\\<^sup>T \\<le> ?F\"\n    by (metis conv_dist_inf forest_components_increasing inf.absorb_iff2 sup.boundedI)\n  also have \"... \\<le> -d \\<sqinter> -d\\<^sup>T\"\n    using 1 assms(1) by simp\n  finally have \"f \\<squnion> f\\<^sup>T \\<le> -d \\<sqinter> -d\\<^sup>T\"\n    by simp\n  thus ?thesis\n    by (metis assms(3) inf_sup_distrib2 le_inf_iff)\nqed\n\nend\n\nsubsection \\<open>Related Structures\\<close>\n\ntext \\<open>\nStone algebras can be expanded to Stone-Kleene relation algebras by reusing some operations.\n\\<close>\n\nsublocale stone_algebra < comp_inf: stone_kleene_relation_algebra where star = \"\\<lambda>x . top\" and one = top and times = inf and conv = id\n  apply unfold_locales\n  by simp\n\ntext \\<open>\nEvery bounded linear order can be expanded to a Stone algebra, which can be expanded to a Stone relation algebra, which can be expanded to a Stone-Kleene relation algebra.\n\\<close>\n\nclass linorder_stone_kleene_relation_algebra_expansion = linorder_stone_relation_algebra_expansion + star +\n  assumes star_def [simp]: \"x\\<^sup>\\<star> = top\"\nbegin\n\nsubclass kleene_algebra\n  apply unfold_locales\n  apply simp\n  apply (simp add: min.coboundedI1 min.commute)\n  by (simp add: min.coboundedI1)\n\nsubclass stone_kleene_relation_algebra\n  apply unfold_locales\n  by simp\n\nend\n\ntext \\<open>\nA Kleene relation algebra is based on a relation algebra.\n\\<close>\n\nclass kleene_relation_algebra = relation_algebra + stone_kleene_relation_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_Kleene_Relation_Algebras/Kleene_Relation_Algebras.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8615381987656672, "lm_q2_score": 0.8438951104066293, "lm_q1q2_score": 0.7270478733668813}}
{"text": "theory Function\n  imports HOL.Fun Main HOL.Real \"~~/src/HOL/ex/Sqrt\"\nbegin\n\nsubsection \\<open>function and relation\\<close>\n\ntype_synonym ('a, 'b) rel = \"('a \\<times> 'b) set\" \n\ndefinition func :: \"('a, 'b) rel \\<Rightarrow> 'a set \\<Rightarrow> 'b set \\<Rightarrow> bool\" (\"_ : _ \\<rightarrow> _\" [80,80,80] 81)\n  where \"func f X Y \\<equiv> f \\<subseteq> X \\<times> Y \\<and> X \\<noteq> {} \\<and> Y \\<noteq> {} \\<and> Domain f = X\n                        \\<and> (\\<forall>x y1 y2. (x, y1)\\<in>f \\<and> (x, y2)\\<in>f \\<longrightarrow> y1 = y2)\" \n\n\nsubsection \\<open>total and partial function\\<close>\n\ndefinition sqrt :: \"real \\<rightharpoonup> real\"\n  where \"sqrt r \\<equiv> (if r \\<ge> 0 then Some (root 2 r) else None)\"\n\ndefinition Pred :: \"nat \\<rightharpoonup> nat\"\n  where \"Pred n \\<equiv> (if n > 0 then Some (n - 1) else None)\"\n\nvalue \"Pred 9\"\nvalue \"Pred 0\"\n\ndefinition minus_nat :: \"nat \\<Rightarrow> nat \\<rightharpoonup> nat\"\n  where \"minus_nat a b \\<equiv> (if a \\<ge> b then Some (a - b) else None)\"\n\nvalue \"minus_nat 6 3\"\n\nvalue \"minus_nat 3 8\"\n\nsubsection \\<open>injective, surjective, bijective\\<close>\n\ndefinition add1 :: \"nat \\<Rightarrow> nat\"\n  where \"add1 n \\<equiv> n + 1\"\n\nlemma \"inj add1 = True\" \n  unfolding add1_def by auto\n\nlemma \"surj add1 = False\"\n  apply(simp add:add1_def surj_def)\n  apply(rule_tac x = 0 in exI)\n  by auto\n\ndefinition add2 :: \"real \\<Rightarrow> real\"\n  where \"add2 r \\<equiv> r + 1\"\n\nlemma add2_lm1: \"inj add2 = True\"\n  by (simp add:add2_def inj_def)\n\nlemma add2_lm2: \"surj add2 = True\"\n  apply (simp add:add2_def surj_def) \n  apply(rule allI)\n  by (metis add_diff_cancel_left' diff_minus_eq_add)\n  \nlemma \"bij add2 = True\"\n  using add2_lm1 add2_lm2 by (simp add:bij_def)\n\n\nlemma \"f = g \\<longleftrightarrow> (\\<forall>x. f x = g x)\"\n  by auto\n\nlemma \"f = g \\<longleftrightarrow> {(x,y). y = f x} = {(x,y). y = g x}\"\n  by auto\n\n\nsubsection \\<open>function operation\\<close>\n\ndefinition fun1 :: \"int \\<Rightarrow> int\"\n  where \"fun1 x \\<equiv> x + 1\"\n\nvalue \"fun_upd f a b\"\nvalue \"f(a := b)\"\n\nvalue \"fun1 2\"\n\nterm \"fun1(2 := 2)\"\n\nvalue \"(fun1(2 := 2)) 2\"\n\nvalue \"(fun1(1 := 1, 2 := 2, 3 := 3)) 2\"\nvalue \"(fun1(1 := 1, 2 := 2, 3 := 3)) 1\"\nvalue \"(fun1(1 := 1, 2 := 2, 3 := 3)) 3\"\n\nvalue \"(fun1(x := y)) x\"\n\nlemma \"(f(x := y)) x = y\"\n  by auto\n\nlemma \"z \\<noteq> x \\<Longrightarrow> (f(x := y)) z = f z\"\n  by auto\n\nlemma \"f(x := y, x := z) = f(x := z)\"\n  by auto\n\nvalue \"(fun1(x := y, x := z)) x\"\n\ndefinition \"fun2 x \\<equiv> fun1 x * 2\"\nvalue \"fun2 3\"\n\ndefinition \"fun3 \\<equiv> (\\<lambda>x. (fun1(x := fun1 x * 2)) x)\"\nvalue \"fun3 3\"\n\ndefinition fun4 :: \"int \\<Rightarrow> int\"\n  where \"fun4 x \\<equiv> x * 2\"\nvalue \"fun4 ` {1,2,3}\"\n\nvalue \"fun4 ` {1..10}\"\n\nlemma \"fun4 ` {x. x > 5 \\<and> x < 12} = {12,14,16,18,20,22}\"\n  using fun4_def by auto\n\nthm fun4_def\nthm swap_def\n\ndefinition \"fun5 \\<equiv> Fun.swap 2 3 fun4\"\n\nvalue \"fun4 2\"\nvalue \"fun4 3\"\nvalue \"fun5 2\"\nvalue \"fun5 3\"\n\nlemma \"(Fun.swap a b f) a = f b\"\n  by auto\n\nlemma \"(Fun.swap a b f) b = f a\"\n  by auto\n\nlemma \"c \\<noteq> a \\<and> c \\<noteq> b \\<Longrightarrow> Fun.swap a b f c = f c\"\n  by auto\n\ndefinition suc :: \"int \\<Rightarrow> int\"\n  where \"suc n \\<equiv> n + 1\"\n\nlemma bij_suc: \"bij suc\"\n  unfolding suc_def bij_def inj_def surj_def \n  apply(rule conjI)\n  apply auto apply(rule_tac x = \"y - 1\" in exI) by simp\n\ndefinition \"suc_inv \\<equiv> the_inv suc\"\n\ndefinition pred :: \"int \\<Rightarrow> int\"\n  where \"pred n \\<equiv> n - 1\"\n\nvalue \"pred 1\"\nvalue \"pred 0\"\n\nlemma \"suc_inv x = pred x\"\n  unfolding suc_inv_def pred_def the_inv_into_def suc_def using bij_suc by force\n\ndefinition suc2 :: \"nat \\<Rightarrow> nat\"\n  where \"suc2 n \\<equiv> n + 2\"\n\nlemma \"inj suc2\"\n  unfolding suc2_def inj_def by simp\n\ndefinition \"suc2_inv = the_inv suc2\"\n\nlemma \"suc2_inv 3 = 1\"\n  unfolding suc2_inv_def the_inv_into_def suc2_def by simp\n\nlemma \"suc2_inv 1 = 0\" (* its wrong *)\n   sorry\n\ndefinition pred2 :: \"nat \\<Rightarrow> nat\"\n  where \"pred2 n \\<equiv> n - 2\"\n\nvalue \"pred2 1\"\nvalue \"pred2 0\"\n\ndefinition f6 :: \"int \\<Rightarrow> int\"\n  where \"f6 x \\<equiv> (if x < 0 then x + 1 else 10)\"\n\nvalue \"f6 (-2)\"\nvalue \"f6 2\"\nvalue \"f6 3\"\n\nlemma \"\\<not>(\\<exists>x. f6 x = 5)\"\n  unfolding f6_def by simp\n\ndefinition \"f6_inv \\<equiv> the_inv f6\"\n\nlemma \"f6_inv (-1) = -2\"\n  unfolding f6_inv_def the_inv_into_def f6_def by auto\n\ndefinition f7 :: \"int \\<Rightarrow> int\"\n  where \"f7 n \\<equiv> n + 2\"\n\ndefinition g7 :: \"int \\<Rightarrow> int\"\n  where \"g7 n \\<equiv> n * 2\"\n\nvalue \"(f7 \\<circ> g7) 3\"\nvalue \"(g7 \\<circ> f7) 3\"\n\nlemma \"(f7 \\<circ> g7) x = x * 2 + 2\"\n  unfolding f7_def g7_def comp_def by simp\n\nlemma \"(g7 \\<circ> f7) x = (x + 2) * 2\"\n  unfolding f7_def g7_def comp_def by simp\n\nlemma \"(f \\<circ> g) x = f (g x)\"\n  by auto\n\nlemma \"(g \\<circ> f) x = g (f x)\"\n  by auto\n\nlemma \"(f \\<circ> g) \\<circ> h = f \\<circ> (g \\<circ> h)\"\n  by auto\n\nvalue \"id (2::int)\"\nvalue \"id ''hello''\"\nvalue \"id (0::nat)\"\nvalue \"id (2.0 :: real)\"\n\nlemma \"f \\<circ> id = f\"\n  by auto\n\nlemma \"id \\<circ> f = f\"\n  by auto\n\n\nsubsection \\<open>polymorphism\\<close>\n\ndefinition addi :: \"int \\<Rightarrow> int \\<Rightarrow> int\"\n  where \"addi x y \\<equiv> x + y\"\n\ndefinition first :: \"('a \\<times> 'b) \\<Rightarrow> 'a\"\n  where \"first p \\<equiv> case p of (a,b) \\<Rightarrow> a\"\n\ndefinition second :: \"('a \\<times> 'b) \\<Rightarrow> 'b\"\n  where \"second p \\<equiv> case p of (a,b) \\<Rightarrow> b\"\n\nvalue \"first (2::int, 3::nat)\"\nvalue \"second (2::int, 3::nat)\"\nvalue \"first (2.0::real, ''hello'')\"\nvalue \"second (2.0::real, ''hello'')\"\n\ntype_synonym 'a array = \"'a list\"\n\nprimrec array_assn :: \"'a array \\<Rightarrow> nat \\<Rightarrow> 'a \\<Rightarrow> 'a array\" (\"_[_] := _\")\n  where \"array_assn [] i v = []\" |\n        \"array_assn (x # xs) i v =\n            (case i of 0 \\<Rightarrow> v # xs | \n                  Suc j \\<Rightarrow> x # list_update xs j v)\"\n\ndefinition query :: \"'a array \\<Rightarrow> nat \\<Rightarrow> 'a\" (\"_[_]\")\n  where \"arr[i] \\<equiv> arr ! i\"\n\ndefinition arr1 :: \"int array\"\n  where \"arr1 \\<equiv> [1,2,3]\"\ndefinition \"arr2 \\<equiv> arr1[1] := 8\"\nvalue \"arr2[1]\"\n\ndefinition arr3 :: \"string array\"\n  where \"arr3 \\<equiv> [''aaaa'',''bbbb'',''cccc'']\"\ndefinition \"arr4 \\<equiv> arr3[1] := ''eeee''\"\nvalue \"arr4[1]\"\n\ntype_synonym ('k,'v) kvstore = \"'k \\<rightharpoonup> 'v\"\n\ndefinition getv :: \"('k,'v) kvstore \\<Rightarrow> 'k \\<Rightarrow> 'v option\"\n  where \"getv m k \\<equiv> m k\"\n\ndefinition update :: \"('k,'v) kvstore \\<Rightarrow> 'k \\<Rightarrow> 'v \\<Rightarrow> ('k,'v) kvstore\" (\"_ [_ :\\<rightarrow> _]\")\n  where \"update m k v \\<equiv> m(k:= Some v)\"\n\ndatatype 'v valT = I int | S string | L \"'v list\" | T \"'v set\"\n\nrecord info = name :: string\n              addr :: string\n              val  :: int\n\ntype_synonym imap = \"(int, info valT) kvstore\"\ntype_synonym smap = \"(string, info valT) kvstore\"\n\ndefinition kvs1 :: \"imap\"\n  where \"kvs1 \\<equiv> (\\<lambda>i. None)\"\n\nvalue \"kvs1 1\"\n\ndefinition \"kvs2 \\<equiv> kvs1[1 :\\<rightarrow> (S ''hello'')]\"\nvalue \"kvs2 1\"\ndefinition \"kvs3 \\<equiv> kvs2[2 :\\<rightarrow> (T {\\<lparr>name = ''david'',addr = ''beijing'', val = 1\\<rparr>})]\"\nvalue \"kvs3 1\"\nvalue \"kvs3 2\"\n\ndefinition kvs4 :: \"imap\"\n  where \"kvs4 \\<equiv> \\<lambda>x::int. if x > 5 \\<and> x < 10 then Some (I x) else kvs3 x\"\n\nvalue \"kvs4 1\"\nvalue \"kvs4 2\"\nvalue \"kvs4 4\"\nvalue \"kvs4 6\"\n\nvalue \"(2::int) + (3::int)\"\nvalue \"(2.5::real) + (3::int)\"\nvalue \"(2.5::real) + (3.4::real)\"\n\n\n\nend", "meta": {"author": "LVPGroup", "repo": "fpp", "sha": "7e18377ea2c553bf6e57412727a4f06832d93577", "save_path": "github-repos/isabelle/LVPGroup-fpp", "path": "github-repos/isabelle/LVPGroup-fpp/fpp-7e18377ea2c553bf6e57412727a4f06832d93577/2_functionalprog/Function.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382129861583, "lm_q2_score": 0.8438950947024555, "lm_q1q2_score": 0.7270478718377383}}
{"text": "theory Ex1_9\n  imports Main \nbegin \n  \n  \nprimrec zip1 :: \"'a list \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where \n  \"zip1 [] rest  = rest\"|\n  \"zip1 (x#xs) rest = (case rest of  [] \\<Rightarrow> (x#xs) | (y#ys) \\<Rightarrow> x # y # zip1 xs ys)\"\n  \nprimrec zip2 :: \"'a list \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where \n  \"zip2 rest [] = rest\"|\n  \"zip2 rest (x#xs) = (case rest of [] \\<Rightarrow> (x#xs) | (y#ys) \\<Rightarrow> y # x # zip2 ys xs)\"\n  \nfun zipr :: \"'a list \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where\n  \"zipr [] ys = ys\"|\n  \"zipr xs [] = xs\"|\n  \"zipr (x#xs) (y#ys) = x # y # zipr xs ys\"\n  \nlemma \"zip1 xs ys = zip2 xs ys\" \nproof (induct xs ys rule : list_induct2')\n  case 1\n  then show ?case by simp\nnext\n  case (2 x xs)\n  then show ?case by simp\nnext\n  case (3 y ys)\n  then show ?case by simp\nnext\n  case (4 x xs y ys)\n  then show ?case by simp\nqed  \n  \nlemma \"zip1 xs ys = zipr xs ys\" by (induct xs ys rule : list_induct2', simp_all)\n    \nlemma \"zip2 xs ys = zipr xs ys\" by (induct xs ys rule : list_induct2', simp_all)\n  \n  \nlemma \"\\<lbrakk> length p = length u ; length q = length v\\<rbrakk> \\<Longrightarrow> zipr (p@q) (u@v) = zipr p u @ zipr q v\" \nproof (induct p u rule : list_induct2)\n  case Nil\n  then show ?case  by simp\nnext\n  case (Cons x xs y ys)\n  assume hyp1:\"length xs = length ys\"\n  assume hyp2:\" length q = length v \\<Longrightarrow> zipr (xs @ q) (ys @ v) = zipr xs ys @ zipr q v\"\n  assume hyp3:\"length q = length v\"\n  show ?case using hyp3 hyp2 by simp\nqed\n\n  \n  \n\n  \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_9.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.89181104831338, "lm_q2_score": 0.8152324871074608, "lm_q1q2_score": 0.7270333389464286}}
{"text": "(*  Title:      HOL/Proofs/Extraction/Euclid.thy\n    Author:     Markus Wenzel, TU Muenchen\n    Author:     Freek Wiedijk, Radboud University Nijmegen\n    Author:     Stefan Berghofer, TU Muenchen\n*)\n\nsection \\<open>Euclid's theorem\\<close>\n\ntheory Euclid\nimports\n  \"~~/src/HOL/Number_Theory/Primes\"\n  Util\n  \"~~/src/HOL/Library/Code_Target_Numeral\"\nbegin\n\ntext \\<open>\n  A constructive version of the proof of Euclid's theorem by\n  Markus Wenzel and Freek Wiedijk @{cite \"Wenzel-Wiedijk-JAR2002\"}.\n\\<close>\n\nlemma factor_greater_one1: \"n = m * k \\<Longrightarrow> m < n \\<Longrightarrow> k < n \\<Longrightarrow> Suc 0 < m\"\n  by (induct m) auto\n\nlemma factor_greater_one2: \"n = m * k \\<Longrightarrow> m < n \\<Longrightarrow> k < n \\<Longrightarrow> Suc 0 < k\"\n  by (induct k) auto\n\nlemma prod_mn_less_k: \"0 < n \\<Longrightarrow> 0 < k \\<Longrightarrow> Suc 0 < m \\<Longrightarrow> m * n = k \\<Longrightarrow> n < k\"\n  by (induct m) auto\n\nlemma prime_eq: \"prime (p::nat) \\<longleftrightarrow> 1 < p \\<and> (\\<forall>m. m dvd p \\<longrightarrow> 1 < m \\<longrightarrow> m = p)\"\n  apply (simp add: prime_nat_iff)\n  apply (rule iffI)\n  apply blast\n  apply (erule conjE)\n  apply (rule conjI)\n  apply assumption\n  apply (rule allI impI)+\n  apply (erule allE)\n  apply (erule impE)\n  apply assumption\n  apply (case_tac \"m = 0\")\n  apply simp\n  apply (case_tac \"m = Suc 0\")\n  apply simp\n  apply simp\n  done\n\nlemma prime_eq': \"prime (p::nat) \\<longleftrightarrow> 1 < p \\<and> (\\<forall>m k. p = m * k \\<longrightarrow> 1 < m \\<longrightarrow> m = p)\"\n  by (simp add: prime_eq dvd_def HOL.all_simps [symmetric] del: HOL.all_simps)\n\nlemma not_prime_ex_mk:\n  assumes n: \"Suc 0 < n\"\n  shows \"(\\<exists>m k. Suc 0 < m \\<and> Suc 0 < k \\<and> m < n \\<and> k < n \\<and> n = m * k) \\<or> prime n\"\nproof -\n  from nat_eq_dec have \"(\\<exists>m<n. n = m * k) \\<or> \\<not> (\\<exists>m<n. n = m * k)\" for k\n    by (rule search)\n  then have \"(\\<exists>k<n. \\<exists>m<n. n = m * k) \\<or> \\<not> (\\<exists>k<n. \\<exists>m<n. n = m * k)\"\n    by (rule search)\n  then show ?thesis\n  proof\n    assume \"\\<exists>k<n. \\<exists>m<n. n = m * k\"\n    then obtain k m where k: \"k<n\" and m: \"m<n\" and nmk: \"n = m * k\"\n      by iprover\n    from nmk m k have \"Suc 0 < m\" by (rule factor_greater_one1)\n    moreover from nmk m k have \"Suc 0 < k\" by (rule factor_greater_one2)\n    ultimately show ?thesis using k m nmk by iprover\n  next\n    assume \"\\<not> (\\<exists>k<n. \\<exists>m<n. n = m * k)\"\n    then have A: \"\\<forall>k<n. \\<forall>m<n. n \\<noteq> m * k\" by iprover\n    have \"\\<forall>m k. n = m * k \\<longrightarrow> Suc 0 < m \\<longrightarrow> m = n\"\n    proof (intro allI impI)\n      fix m k\n      assume nmk: \"n = m * k\"\n      assume m: \"Suc 0 < m\"\n      from n m nmk have k: \"0 < k\"\n        by (cases k) auto\n      moreover from n have n: \"0 < n\" by simp\n      moreover note m\n      moreover from nmk have \"m * k = n\" by simp\n      ultimately have kn: \"k < n\" by (rule prod_mn_less_k)\n      show \"m = n\"\n      proof (cases \"k = Suc 0\")\n        case True\n        with nmk show ?thesis by (simp only: mult_Suc_right)\n      next\n        case False\n        from m have \"0 < m\" by simp\n        moreover note n\n        moreover from False n nmk k have \"Suc 0 < k\" by auto\n        moreover from nmk have \"k * m = n\" by (simp only: ac_simps)\n        ultimately have mn: \"m < n\" by (rule prod_mn_less_k)\n        with kn A nmk show ?thesis by iprover\n      qed\n    qed\n    with n have \"prime n\"\n      by (simp only: prime_eq' One_nat_def simp_thms)\n    then show ?thesis ..\n  qed\nqed\n\nlemma dvd_factorial: \"0 < m \\<Longrightarrow> m \\<le> n \\<Longrightarrow> m dvd fact n\"\nproof (induct n rule: nat_induct)\n  case 0\n  then show ?case by simp\nnext\n  case (Suc n)\n  from \\<open>m \\<le> Suc n\\<close> show ?case\n  proof (rule le_SucE)\n    assume \"m \\<le> n\"\n    with \\<open>0 < m\\<close> have \"m dvd fact n\" by (rule Suc)\n    then have \"m dvd (fact n * Suc n)\" by (rule dvd_mult2)\n    then show ?thesis by (simp add: mult.commute)\n  next\n    assume \"m = Suc n\"\n    then have \"m dvd (fact n * Suc n)\"\n      by (auto intro: dvdI simp: ac_simps)\n    then show ?thesis by (simp add: mult.commute)\n  qed\nqed\n\nlemma dvd_prod [iff]: \"n dvd (\\<Prod>m::nat \\<in># mset (n # ns). m)\"\n  by (simp add: prod_mset_Un)\n\ndefinition all_prime :: \"nat list \\<Rightarrow> bool\"\n  where \"all_prime ps \\<longleftrightarrow> (\\<forall>p\\<in>set ps. prime p)\"\n\nlemma all_prime_simps:\n  \"all_prime []\"\n  \"all_prime (p # ps) \\<longleftrightarrow> prime p \\<and> all_prime ps\"\n  by (simp_all add: all_prime_def)\n\nlemma all_prime_append: \"all_prime (ps @ qs) \\<longleftrightarrow> all_prime ps \\<and> all_prime qs\"\n  by (simp add: all_prime_def ball_Un)\n\nlemma split_all_prime:\n  assumes \"all_prime ms\" and \"all_prime ns\"\n  shows \"\\<exists>qs. all_prime qs \\<and>\n    (\\<Prod>m::nat \\<in># mset qs. m) = (\\<Prod>m::nat \\<in># mset ms. m) * (\\<Prod>m::nat \\<in># mset ns. m)\"\n  (is \"\\<exists>qs. ?P qs \\<and> ?Q qs\")\nproof -\n  from assms have \"all_prime (ms @ ns)\"\n    by (simp add: all_prime_append)\n  moreover\n  have \"(\\<Prod>m::nat \\<in># mset (ms @ ns). m) = (\\<Prod>m::nat \\<in># mset ms. m) * (\\<Prod>m::nat \\<in># mset ns. m)\"\n    using assms by (simp add: prod_mset_Un)\n  ultimately have \"?P (ms @ ns) \\<and> ?Q (ms @ ns)\" ..\n  then show ?thesis ..\nqed\n\nlemma all_prime_nempty_g_one:\n  assumes \"all_prime ps\" and \"ps \\<noteq> []\"\n  shows \"Suc 0 < (\\<Prod>m::nat \\<in># mset ps. m)\"\n  using \\<open>ps \\<noteq> []\\<close> \\<open>all_prime ps\\<close>\n  unfolding One_nat_def [symmetric]\n  by (induct ps rule: list_nonempty_induct)\n    (simp_all add: all_prime_simps prod_mset_Un prime_gt_1_nat less_1_mult del: One_nat_def)\n\nlemma factor_exists: \"Suc 0 < n \\<Longrightarrow> (\\<exists>ps. all_prime ps \\<and> (\\<Prod>m::nat \\<in># mset ps. m) = n)\"\nproof (induct n rule: nat_wf_ind)\n  case (1 n)\n  from \\<open>Suc 0 < n\\<close>\n  have \"(\\<exists>m k. Suc 0 < m \\<and> Suc 0 < k \\<and> m < n \\<and> k < n \\<and> n = m * k) \\<or> prime n\"\n    by (rule not_prime_ex_mk)\n  then show ?case\n  proof\n    assume \"\\<exists>m k. Suc 0 < m \\<and> Suc 0 < k \\<and> m < n \\<and> k < n \\<and> n = m * k\"\n    then obtain m k where m: \"Suc 0 < m\" and k: \"Suc 0 < k\" and mn: \"m < n\"\n      and kn: \"k < n\" and nmk: \"n = m * k\"\n      by iprover\n    from mn and m have \"\\<exists>ps. all_prime ps \\<and> (\\<Prod>m::nat \\<in># mset ps. m) = m\"\n      by (rule 1)\n    then obtain ps1 where \"all_prime ps1\" and prod_ps1_m: \"(\\<Prod>m::nat \\<in># mset ps1. m) = m\"\n      by iprover\n    from kn and k have \"\\<exists>ps. all_prime ps \\<and> (\\<Prod>m::nat \\<in># mset ps. m) = k\"\n      by (rule 1)\n    then obtain ps2 where \"all_prime ps2\" and prod_ps2_k: \"(\\<Prod>m::nat \\<in># mset ps2. m) = k\"\n      by iprover\n    from \\<open>all_prime ps1\\<close> \\<open>all_prime ps2\\<close>\n    have \"\\<exists>ps. all_prime ps \\<and> (\\<Prod>m::nat \\<in># mset ps. m) =\n      (\\<Prod>m::nat \\<in># mset ps1. m) * (\\<Prod>m::nat \\<in># mset ps2. m)\"\n      by (rule split_all_prime)\n    with prod_ps1_m prod_ps2_k nmk show ?thesis by simp\n  next\n    assume \"prime n\" then have \"all_prime [n]\" by (simp add: all_prime_simps)\n    moreover have \"(\\<Prod>m::nat \\<in># mset [n]. m) = n\" by (simp)\n    ultimately have \"all_prime [n] \\<and> (\\<Prod>m::nat \\<in># mset [n]. m) = n\" ..\n    then show ?thesis ..\n  qed\nqed\n\nlemma prime_factor_exists:\n  assumes N: \"(1::nat) < n\"\n  shows \"\\<exists>p. prime p \\<and> p dvd n\"\nproof -\n  from N obtain ps where \"all_prime ps\" and prod_ps: \"n = (\\<Prod>m::nat \\<in># mset ps. m)\"\n    using factor_exists by simp iprover\n  with N have \"ps \\<noteq> []\"\n    by (auto simp add: all_prime_nempty_g_one)\n  then obtain p qs where ps: \"ps = p # qs\"\n    by (cases ps) simp\n  with \\<open>all_prime ps\\<close> have \"prime p\"\n    by (simp add: all_prime_simps)\n  moreover from \\<open>all_prime ps\\<close> ps prod_ps have \"p dvd n\"\n    by (simp only: dvd_prod)\n  ultimately show ?thesis by iprover\nqed\n\ntext \\<open>Euclid's theorem: there are infinitely many primes.\\<close>\n\nlemma Euclid: \"\\<exists>p::nat. prime p \\<and> n < p\"\nproof -\n  let ?k = \"fact n + (1::nat)\"\n  have \"1 < ?k\" by simp\n  then obtain p where prime: \"prime p\" and dvd: \"p dvd ?k\"\n    using prime_factor_exists by iprover\n  have \"n < p\"\n  proof -\n    have \"\\<not> p \\<le> n\"\n    proof\n      assume pn: \"p \\<le> n\"\n      from \\<open>prime p\\<close> have \"0 < p\" by (rule prime_gt_0_nat)\n      then have \"p dvd fact n\" using pn by (rule dvd_factorial)\n      with dvd have \"p dvd ?k - fact n\" by (rule dvd_diff_nat)\n      then have \"p dvd 1\" by simp\n      with prime show False by auto\n    qed\n    then show ?thesis by simp\n  qed\n  with prime show ?thesis by iprover\nqed\n\nextract Euclid\n\ntext \\<open>\n  The program extracted from the proof of Euclid's theorem looks as follows.\n  @{thm [display] Euclid_def}\n  The program corresponding to the proof of the factorization theorem is\n  @{thm [display] factor_exists_def}\n\\<close>\n\ninstantiation nat :: default\nbegin\n\ndefinition \"default = (0::nat)\"\n\ninstance ..\n\nend\n\ninstantiation list :: (type) default\nbegin\n\ndefinition \"default = []\"\n\ninstance ..\n\nend\n\nprimrec iterate :: \"nat \\<Rightarrow> ('a \\<Rightarrow> 'a) \\<Rightarrow> 'a \\<Rightarrow> 'a list\"\nwhere\n  \"iterate 0 f x = []\"\n| \"iterate (Suc n) f x = (let y = f x in y # iterate n f y)\"\n\nlemma \"factor_exists 1007 = [53, 19]\" by eval\nlemma \"factor_exists 567 = [7, 3, 3, 3, 3]\" by eval\nlemma \"factor_exists 345 = [23, 5, 3]\" by eval\nlemma \"factor_exists 999 = [37, 3, 3, 3]\" by eval\nlemma \"factor_exists 876 = [73, 3, 2, 2]\" by eval\n\nlemma \"iterate 4 Euclid 0 = [2, 3, 7, 71]\" by eval\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/Proofs/Extraction/Euclid.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8723473813156294, "lm_q2_score": 0.8333245994514084, "lm_q1q2_score": 0.7269485321173319}}
{"text": "theory Strong_Convexity\n  imports Main \"HOL-Analysis.Analysis\" \"HOL-Analysis.Convex\" \nbegin\n\ndefinition strong_convex_on :: \"'a::euclidean_space set\\<Rightarrow> ('a \\<Rightarrow> real) \\<Rightarrow> real \\<Rightarrow> bool\"\n  where \"strong_convex_on s f k \\<longleftrightarrow>\n    (\\<forall>x\\<in>s. \\<forall>y\\<in>s. \\<forall>u\\<ge>0. \\<forall>v\\<ge>0. u + v = 1 \\<longrightarrow>\n     f (u *\\<^sub>R x + v *\\<^sub>R y) \\<le> u * f x + v * f y - (k/2) * u * v * norm(x-y) * norm(x-y) )\" \n\n\nlemma help2_3 : \"norm (x+y)^2 = norm x ^ 2 + 2 *\\<^sub>R (inner x y) + norm y ^ 2\" \n  for x y :: \"'a::euclidean_space\"\n  by (smt inner_commute inner_left_distrib power2_norm_eq_inner scaleR_2)\n\nlemma help2_31 : \"norm (x - y)^2 = norm x ^ 2 - 2 *\\<^sub>R (inner x y) + norm y ^ 2\" \n  for x y :: \"'a::euclidean_space\"\n  using help2_3\n  by (simp add: inner_commute inner_diff_right power2_norm_eq_inner)\n\n\nlemma help2_2 : \"(norm (u  *\\<^sub>R x +  v  *\\<^sub>R y))^2 = norm (u *\\<^sub>R x)^2 + (2 * u * v) *\\<^sub>R (inner x y) + norm (v *\\<^sub>R y)^2 \"\n  for x y :: \"'a::euclidean_space\"\n  by (simp add: help2_3)\n\nlemma help2_4: \"norm (u *\\<^sub>R x)^2  = u^2 * norm(x)^2\"\nproof -\n  have \"abs(u)^2 = u^2\" by simp\n  then show \"norm (u *\\<^sub>R x)^2  = u^2 * norm(x)^2\" \n    using norm_scaleR power2_eq_square\n    by (simp add: power_mult_distrib)\nqed\n\nlemma sq_norm_strong_convex: \"strong_convex_on s (\\<lambda> w. k * norm(w) * norm(w)) (2*k)\"\n  for s :: \"'a::euclidean_space set\"\nproof -\n  let ?f = \"(\\<lambda> w. k * norm(w) * norm(w))\"\n  have \"\\<forall> x\\<in>s. \\<forall>y\\<in>s. \\<forall>u\\<ge>0. \\<forall>v\\<ge>0.( u + v = 1 \\<longrightarrow>\n     ?f (u *\\<^sub>R x + v *\\<^sub>R y) \\<le> u * ?f x + v * ?f y - (2*k/2) * u * v * norm(x-y) * norm(x-y) )\"\n  proof (rule)+\n    fix x assume\"x\\<in>s\"\n    fix y assume\"y\\<in>s\"\n    fix u assume\"(u::real) \\<ge> 0\"\n    fix v assume\"(v::real) \\<ge> 0\"\n    assume \"u+v = 1\"\n    then show \"  k *norm (u *\\<^sub>R x + v *\\<^sub>R y) * norm (u *\\<^sub>R x + v *\\<^sub>R y) \\<le> \nu * (k * norm x * norm x) + v *(k * norm y * norm y) - 2 * k / 2 * u * v *norm (x - y) * norm (x - y)\" \n    proof -   \n      have  \"?f  (u *\\<^sub>R x + v *\\<^sub>R y) = k*(norm (u  *\\<^sub>R x +  v  *\\<^sub>R y))^2\" \n        by (simp add: power2_eq_square)\n      also  have \"k*(norm (u  *\\<^sub>R x +  v  *\\<^sub>R y))^2 =\n        k*(norm (u *\\<^sub>R x)^2 + (2 * u * v) * (inner x y) + norm (v *\\<^sub>R y)^2)\" by (simp add: help2_2)\n      also have \" k*(norm (u *\\<^sub>R x)^2 + (2 * u * v) * (inner x y) + norm (v *\\<^sub>R y)^2) =\n             k*(u^2 * norm (x)^2 + (2 * u * v) * (inner x y) + v^2 * norm (y)^2)\" using help2_4 by metis\n      also  have \"k*(u^2 * norm (x)^2 + (2 * u * v) * (inner x y) + v^2 * norm (y)^2)  =\n                            k*u*norm(x)^2 + (2 * k * u * v) * (inner x y) + k* v * norm (y)^2 \n                              - k * u * v * norm(x)^2 - k * u * v *norm(y)^2\" using `u+v = 1`  by algebra\n      also have \"k*u*norm(x)^2 + (2 * k * u * v) * (inner x y) + k* v * norm (y)^2 \n                              - k * u * v * norm(x)^2 - k * u * v *norm(y)^2 =                               \n                               k*u*norm(x)^2  + k* v * norm (y)^2 \n                              - (k * u * v) * ( norm(x)^2  -  2  * (inner x y) + norm(y)^2)\" using distrib_left  help2_31 by argo\n      also have \" k*u*norm(x)^2  + k* v * norm (y)^2 \n                              - (k * u * v) * ( norm(x)^2  -  2  * (inner x y) + norm(y)^2) =\n                           k*u*norm(x)^2  + k* v * norm (y)^2  - (k * u * v) * norm(x - y)^2\" \n        by (simp add: help2_31)\n\n      finally have \"?f  (u *\\<^sub>R x + v *\\<^sub>R y) =  u * ?f x + v * ?f y - (2*k/2) * u * v * norm(x-y) * norm(x-y)\"\n        by  (simp add: power2_eq_square help2_31)\n\n      then show ?thesis   by linarith\n    qed\n  qed\n  then show ?thesis unfolding strong_convex_on_def by blast\nqed\n\ninstantiation \"fun\" :: (type, plus) plus\nbegin\n\ndefinition fun_plus_def: \"A + B = (\\<lambda>x. A x + B x)\"\n\nlemma minus_apply [simp, code]: \"(A + B) x = A x + B x\"\n  by (simp add: fun_plus_def)\n\ninstance ..\n\n\nend\n\ninstantiation \"fun\" :: (ab_semigroup_add, ab_semigroup_add) ab_semigroup_add\nbegin\n\ninstance proof\n  fix x y z :: \"'a => 'b\"\n  show \"x + y + z = x + (y + z)\"\n    unfolding fun_plus_def \n    by (simp add: linordered_field_class.sign_simps(1)) \nnext\n  fix x y :: \"'a => 'b\"\n  show \"x + y = y + x\"\n    unfolding fun_plus_def\n    by (simp add: linordered_field_class.sign_simps(2))\nqed\nend\n\ninstantiation \"fun\" :: (comm_monoid_add, comm_monoid_add) comm_monoid_add\nbegin\n\ndefinition zero_fun_def:  \"0 == (\\<lambda>x. 0)\"\n\ninstance proof\n  fix a :: \"'a => 'b\"\n  show \"0 + a = a\" \n    unfolding zero_fun_def fun_plus_def by simp\nqed\n\nend\n\nlemma convex_fun_add:\n  assumes \"convex_on s f\" \"convex_on s g\"\n  shows \"convex_on s (f + g)\"\nproof - \n  have \"(f + g) = (\\<lambda> x. f x + g x)\" using fun_plus_def by auto\n  moreover have \"convex_on s (\\<lambda>x. f x + g x)\" using assms convex_on_add by auto\n  ultimately show \"convex_on s (f + g)\" by auto\nqed\n\nlemma strong_convex_sum: \"strong_convex_on s f k \\<and> convex_on s g  \\<longrightarrow> \n                            strong_convex_on s ( f + g) k\"\nproof \n  assume \"strong_convex_on s f k \\<and> convex_on s g\"\n  then show \"strong_convex_on s (f + g) k\"\n  proof\n    have \"strong_convex_on s f k\" using `strong_convex_on s f k \\<and> convex_on s g` by simp\n    have \"convex_on s g\" using `strong_convex_on s f k \\<and> convex_on s g` by simp\n    have  \"(\\<forall>x\\<in>s. \\<forall>y\\<in>s. \\<forall>u\\<ge>0. \\<forall>v\\<ge>0. u + v = 1 \\<longrightarrow>\n     (f+g) (u *\\<^sub>R x + v *\\<^sub>R y) \\<le> \n      u * (f+g) x + v * (f+g) y - (k/2) * u * v * norm(x-y) * norm(x-y) )\"\n    proof (rule)+\n      fix x assume\"x\\<in>s\"\n      fix y assume\"y\\<in>s\"\n      fix u assume\"(u::real) \\<ge> 0\"\n      fix v assume\"(v::real) \\<ge> 0\"\n      assume \"u+v = 1\"\n      then show \"(f+g) (u *\\<^sub>R x + v *\\<^sub>R y) \\<le> \n      u * (f+g) x + v * (f+g) y - (k/2) * u * v * norm(x-y) * norm(x-y)\"\n      proof -\n        have 1: \"f (u *\\<^sub>R x + v *\\<^sub>R y) \\<le> \n           u * f x + v * f y - (k/2) * u * v * norm(x-y) * norm(x-y)\"\n          using  \\<open>0 \\<le> u\\<close> \\<open>0 \\<le> v\\<close> \\<open>u + v = 1\\<close> \\<open>x \\<in> s\\<close> \\<open>y \\<in> s\\<close> \n            `strong_convex_on s f k` unfolding strong_convex_on_def by blast\n\n        have 2: \" g (u *\\<^sub>R x + v *\\<^sub>R y) \\<le> u * g x + v * g y\" \n          using \\<open>0 \\<le> u\\<close> \\<open>0 \\<le> v\\<close> \\<open>u + v = 1\\<close> \\<open>x \\<in> s\\<close> \\<open>y \\<in> s\\<close> `convex_on s g ` unfolding convex_on_def by blast\n\n        have 3:\"f (u *\\<^sub>R x + v *\\<^sub>R y)  +  g (u *\\<^sub>R x + v *\\<^sub>R y) \\<le> \n           u * f x + v * f y - (k/2) * u * v * norm(x-y) * norm(x-y)  + \n       u * g x + v * g y \"\n          using 1 2 by linarith\n        then show ?thesis  by (simp add: distrib_left)\n      qed\n    qed\n    then show ?thesis unfolding strong_convex_on_def by auto\n  qed\nqed\n\nlemma help7: \n  assumes \"(l::real)<0\" \n  assumes \"\\<forall>x. norm (f x - l)< -l\"\n  shows \"\\<forall>x. f x < 0\"\nproof (rule ccontr)\n  assume \"\\<not> (\\<forall>x. f x < 0)\"\n  then show False using assms(2)  real_norm_def by smt\nqed\n\nlemma LIM_fun_less_zero1: \"f \\<midarrow>a\\<rightarrow> l \\<Longrightarrow> l < 0 \\<Longrightarrow> \\<exists>r>0. \\<forall>x. x \\<noteq> a \\<and> norm(a - x) < r \\<longrightarrow> f x < 0\"\n  for a :: \"'b::euclidean_space\" and  l :: \"real\"\nproof -\n  assume \"f \\<midarrow>a\\<rightarrow> l\" \"l < 0\" \n  then have \"\\<exists>r. 0 < r \\<and> (\\<forall>x. x \\<noteq> a \\<and> norm(a - x) < r \\<longrightarrow> norm (f x - l)< -l)\" \n    using LIM_D[of f l a \"-l\"]\n    by (simp add: norm_minus_commute)\n  then obtain r where \"0 < r\" \"(\\<forall>x. x \\<noteq> a \\<and> norm(a - x) < r \\<longrightarrow> norm (f x - l)< -l)\" by auto\n  then have \"(\\<forall>x. x \\<noteq> a \\<and> norm(a - x) < r \\<longrightarrow>  f x < 0)\" \n    using `l<0` help7  by auto\n  then show ?thesis\n    using \\<open>0 < r\\<close> by blast\nqed\n\nlemma metric_LIM_le2:\n  fixes a :: \"real\"\n  assumes \"f \\<midarrow>a\\<rightarrow> (l::real)\"\n  assumes \"a\\<ge>0\"\n    and \"\\<forall>x>a. f x \\<ge> 0\"\n  shows \" l \\<ge> 0\" \nproof (rule ccontr)\n  assume \"\\<not> (l \\<ge> 0)\"\n  then have \" l < 0\"  by simp\n  then have \" \\<exists>r>0. \\<forall>x. x \\<noteq> a \\<and> norm(a - x) < r \\<longrightarrow> f x < 0\" using assms(1) LIM_fun_less_zero1 by blast\n  then have \"\\<exists>r>0. \\<forall>x>a. x \\<noteq> a \\<and> norm(a - x) < r \\<longrightarrow> f x < 0 \\<and> f x \\<ge> 0\"   using assms(3) by blast\n  then have \"\\<exists>r>0. \\<forall>x>a. norm(a - x) \\<ge> r\" by force\n  then obtain r where \"r>0\" and \" \\<forall>x>a. norm(a - x) \\<ge> r\" by auto\n  then have 1: \"\\<forall>x>a. norm(a - x) \\<ge> r\" by auto\n  have  \"\\<exists>k. k>0 \\<and>  k <r \" using `r>0`  by (simp add: dense)\n  then obtain k where \"k>0\" and \"k < r\" by auto\n  then have \"\\<exists> x. x>a \\<and> x-a = k\" by smt\n  then have \"\\<exists> x>a. norm(a-x) < r \\<and> norm(a - x) \\<ge> r\" using  `k<r`1 by auto\n  then show False  by linarith\nqed\n\nlemma metric_LIM_le_zero:\n  fixes a :: \"real\"\n  assumes \"f \\<midarrow>a\\<rightarrow> (l::real)\"\n  assumes \"a\\<ge>0\"\n    and \"\\<exists>r>0. \\<forall>x>a. norm(a-x) < r \\<longrightarrow> f x \\<ge> 0\"\n  shows \" l \\<ge> 0\" \nproof (rule ccontr)\n  assume \"\\<not> (l \\<ge> 0)\"\n  then have \" l < 0\"  by simp\n  then have \" \\<exists>r>0. \\<forall>x. x \\<noteq> a \\<and> norm(a - x) < r \\<longrightarrow> f x < 0\" using assms(1) LIM_fun_less_zero1\n    by blast\n  then obtain r where \"r>0\" and 1: \"\\<forall>x>a. norm(a - x) < r \\<longrightarrow> f x < 0\" by auto\n  obtain r1 where \"r1>0\" and 2: \"\\<forall>x>a. norm(a-x) < r1 \\<longrightarrow> f x \\<ge> 0\" using assms(3)\n    by auto\n  let ?min_r = \"min r1 r\"\n  have 3: \" r \\<ge> ?min_r \" by auto\n  have 4: \" r1 \\<ge> ?min_r \" by auto\n  have \"?min_r>0\" using `r>0` `r1>0` by auto\n  then have 5: \"\\<forall>x>a. norm(a - x) < ?min_r \\<longrightarrow> f x < 0\" using 1 3 by auto\n  then have \"\\<forall>x>a. norm(a - x) < ?min_r \\<longrightarrow> f x \\<ge> 0\" using 2 4 by auto\n  then have \"\\<forall>x>a. norm(a - x) < ?min_r \\<longrightarrow> f x < 0 \\<and> f x \\<ge> 0\" using 5 by blast\n  then have 6: \"\\<forall>x>a. norm(a - x) \\<ge> ?min_r\" by force\n\n  then have  \"\\<exists>k. k>0 \\<and>  k <?min_r \" using `?min_r>0` dense by blast \n  then obtain k where \"k>0\" and \"k < ?min_r\" by auto\n  then have \"\\<exists> x. x>a \\<and> x-a = k\" by smt\n  then have \"\\<exists> x>a. norm(a-x) < ?min_r \\<and> norm(a - x) \\<ge> ?min_r\" using  `k<?min_r` 6 by auto\n  then show False using LIM_fun_less_zero1 \n    by linarith\nqed\n\nlemma help_8: \"x > 0 \\<Longrightarrow> dist t 0 < r/x \\<longrightarrow>\n            norm(t) * x < r\" \nproof \n  assume \" x>0\"\n  assume \"dist t 0 <  r/x\" \n  then have \" norm(t) * x < (r/x) * x\" \n    using `dist t 0 <  r/x` `x>0` mult_less_le_imp_less[of \"norm t\"  \"r/x\" \"x\"  \"x\"] by auto\n  then show \"norm(t) * x  < r\" using `x>0`  nonzero_mult_div_cancel_right by auto\nqed\n\n\n\nlemma real_collapse [simp]: \"(1 - u) * a * b + (-1) * a * b = - u * a * b\"\n  for a :: \"real\"\n  by (simp add: algebra_simps)\n\nlemma real_left_commute: \"a * b * x = b * a * x\"\n  for a :: real\n  by (simp add: mult.commute)\n\nlemma strongly_convex_min:\n  assumes \"strong_convex_on s f k\"\n  assumes \"x \\<in> s\"\n  assumes \"\\<forall>y\\<in>s. (f x \\<le> f y)\"\n  assumes \"w \\<in> s\"\n  assumes \"convex s\"\n  shows \"f w - f x \\<ge> (k/2)*norm(w - x)^2\"\nproof (cases \"w = x\")\n  case True\n  then show ?thesis by auto\nnext\n  case False\n  then show ?thesis\n  proof(cases \"k = 0\")\n    case True\n    then show ?thesis using assms(3) assms(4) by auto\n  next\n    case False\n    then show ?thesis \n    proof -\n      have \"(\\<forall>x\\<in>s. \\<forall>y\\<in>s. \\<forall>u\\<ge>0. \\<forall>v\\<ge>0. u + v = 1 \\<longrightarrow>\n     f (u *\\<^sub>R x + v *\\<^sub>R y) \\<le> u * f x + v * f y - (k/2) * u * v * norm(x-y)^2)\"\n        using assms(1) unfolding  strong_convex_on_def \n        by (simp add: power2_eq_square mult.commute mult.left_commute)\n      then have 0:\" \\<forall>u\\<ge>0. \\<forall>v\\<ge>0. u + v = 1 \\<longrightarrow>\n     f (u *\\<^sub>R w + v *\\<^sub>R x) \\<le> u * f w + v * f x - (k/2) * u * v * norm(w-x)^2\"\n        using assms(2) assms(4) by blast\n\n      have  \"\\<forall>u>0. \\<forall>v\\<ge>0. u + v = 1 \\<longrightarrow>\n     (f (u *\\<^sub>R w + (1-u) *\\<^sub>R x) - f x )/u \\<le> f w  - f x - (k/2) * (1-u) * norm(w-x)^2\"\n      proof(rule)+\n        fix u assume \"(u::real)>0\"\n        fix v assume \"(v::real) \\<ge> 0\"\n        assume \"u + v = 1\"\n        then show \"(f (u *\\<^sub>R w + (1-u) *\\<^sub>R x) - f x )/u \\<le> f w  - f x - (k/2) * (1-u) * norm(w-x)^2\"\n        proof -\n          have \"f (u *\\<^sub>R w + (1-u) *\\<^sub>R x) \n            \\<le> u * f w + (1-u) * f x - (k/2) * u * (1-u) * norm(w-x)^2\" using `u + v = 1` 0\n            \\<open>0 < u\\<close> \\<open>0 \\<le> v\\<close> by auto\n          then have \" f (u *\\<^sub>R w + (1-u) *\\<^sub>R x)/u \\<le> \n        (u * f w + (1-u) * f x - (k/2) * u * (1-u) * norm(w-x)^2)/u\" using `u>0` \n            by (meson divide_right_mono less_eq_real_def)\n          then have \" f (u *\\<^sub>R w + (1-u) *\\<^sub>R x)/u \\<le> \n              (u * f w)/u + ((1-u) * f x)/u - ((k/2) * u * (1-u) * norm(w-x)^2)/u\" \n            by (simp add: add_divide_distrib diff_divide_distrib)\n          then have \" f (u *\\<^sub>R w + (1-u) *\\<^sub>R x)/u \\<le>\n               f w + ((1-u) / u)* f x - (k/2) * (1-u) * norm(w-x)^2\"\n            using \\<open>0 < u\\<close> add_divide_distrib diff_divide_distrib by auto\n          then have \" f (u *\\<^sub>R w + (1-u) *\\<^sub>R x)/u  \\<le> \n              f w + (1/u)* f x + (-u/u)*f x - (k/2) * (1-u) * norm(w-x)^2\"\n            by (simp add: diff_divide_distrib Groups.mult_ac(2) add_diff_eq right_diff_distrib')\n          then have \" f (u *\\<^sub>R w + (1-u) *\\<^sub>R x)/u - (1/u)* f x \\<le> \n              f w  - f x - (k/2) * (1-u) * norm(w-x)^2\"\n            using diff_divide_distrib Groups.mult_ac(2) add_diff_eq right_diff_distrib' `u>0` by force\n          then show ?thesis \n            by (simp add: diff_divide_distrib)\n        qed\n      qed\n      then have 1:\"\\<forall>u>0. u <= 1 \\<longrightarrow>\n     (\\<lambda> t. (f (t *\\<^sub>R w + (1-t) *\\<^sub>R x) - f x )/t) u \\<le> (\\<lambda> t. f w  - f x - (k/2) * (1-t) * norm(w-x)^2) u\" by smt\n\n      have \"\\<forall>u>0. u <= 1 \\<longrightarrow> u *\\<^sub>R w + (1 - u) *\\<^sub>R x \\<in> s \" \n         using assms(2) assms(4) assms(5) by (simp add: convex_def)\n      then have \"\\<forall>u>0. u <= 1 \\<longrightarrow>\n    (\\<lambda> t. (f (t *\\<^sub>R w + (1-t) *\\<^sub>R x) - f x )/t) u  \\<ge> 0\" using assms(3) \n          assms(2) assms(4) by auto\n      then have 11 : \"\\<forall>u>0. u <= 1 \\<longrightarrow>\n    0 \\<le> (\\<lambda> t. f w  - f x - (k/2) * (1-t) * norm(w-x)^2) u\" using 1 by fastforce\n\n      let ?f = \"(\\<lambda> t. f w  - f x - (k/2) * (1-t) * norm(w-x)^2)\"\n      let ?L = \"(f w  - f x - (k/2) * norm(w-x)^2)\"\n      have \"\\<forall>t. dist (?f t) ?L = norm(?f t - ?L)\"\n        using dist_norm by blast\n\n      then have 2: \"\\<forall>t. norm(?f t - ?L) = \n       norm( (k/2) * (1-t) * norm(w-x)^2 + (-1)* (k/2) * norm(w-x)^2)\" by auto\n\n      then have 3: \"\\<forall>t. norm(?f t - ?L) = norm(t*(k/2) * norm(w-x)^2)\" \n        using \"2\" real_left_commute  real_collapse real_left_commute \n        by (metis (no_types, hide_lams)  mult_minus_left norm_minus_cancel)\n\n      then have \"\\<forall>t. norm(t*(k/2) * norm(w-x)^2) = norm(t) * norm(k/2) * norm(w-x)^2\"\n        using norm_ge_zero norm_mult power2_eq_square real_norm_def \n        by smt\n      then have 5:\"\\<forall>t. norm(?f t - ?L) = norm(t) * norm(w-x)^2 * norm((k/2))\" using 3  by simp\n\n      have 55: \"norm(w-x)^2 * norm((k/2)) > 0\" using `w \\<noteq> x` `k \\<noteq> 0` by auto\n      then have \"\\<forall>r. \\<forall>t. t \\<noteq> 0 \\<and> dist t 0 < ( r/(norm(w-x)^2 * norm(k/2))) \\<longrightarrow>\n            norm(t) * norm(w-x)^2 * norm((k/2)) < r\"  by (simp add: help_8 mult.assoc)\n\n      then have 6: \"\\<forall>r. \\<forall>t. t \\<noteq> 0 \\<and> dist t 0 < ( r/(norm(w-x)^2 * norm(k/2))) \\<longrightarrow>\n            dist (?f t) ?L < r\" using 5 dist_norm by metis\n\n      then have \"\\<forall>r>0. (r/(norm(w-x)^2 * norm(k/2))) > 0\"\n        using divide_pos_pos 55 by blast \n      then have \"\\<forall>r > 0. \\<exists>s > 0. \\<forall>t. t \\<noteq> 0 \\<and> dist t 0 < s \\<longrightarrow> \n          dist (?f t) ?L < r\" using 6 by auto\n      then have 7:\" ?f \\<midarrow>0\\<rightarrow> ?L\" unfolding LIM_def by auto\n\n      then have \"\\<forall>u>0. u <= 1 \\<longrightarrow> 0 \\<le> ?f u\" using 11 by simp\n      then have \"\\<exists>r>0. \\<forall>u>0.  u \\<le> r \\<longrightarrow> 0 \\<le> ?f u\"  using zero_less_one by blast\n      then have \"\\<exists>r>0.\\<forall>u>0. norm (0 -u) < r \\<longrightarrow> 0 \\<le> ?f u\" by auto \n      then have \"?L \\<ge> 0\" using metric_LIM_le_zero using 7 by blast\n      then show ?thesis by auto\n    qed\n  qed\nqed\n\nlemma strong_conv_if_eq: \" f = g \\<Longrightarrow> strong_convex_on s f k \\<Longrightarrow> strong_convex_on s g k\"\n  using  HOL.subst by auto\n\nlemma strong_conv_then_conv:\n  assumes k_pos: \"k \\<ge> 0\" \n  shows \"strong_convex_on s f k \\<Longrightarrow> convex_on s f\"\nproof -\n  assume \"strong_convex_on s f k\"\n  then have 1:\" (\\<forall>x\\<in>s. \\<forall>y\\<in>s. \\<forall>u\\<ge>0. \\<forall>v\\<ge>0. u + v = 1 \\<longrightarrow>\n     f (u *\\<^sub>R x + v *\\<^sub>R y) \\<le> u * f x + v * f y - (k/2) * u * v * norm(x-y) * norm(x-y) )\"\n    unfolding strong_convex_on_def by auto\n  have \"\\<forall>x\\<in>s. \\<forall>y\\<in>s. \\<forall>u\\<ge>0. \\<forall>v\\<ge>0. u + v = 1 \\<longrightarrow> (k/2) * u * v * norm(x-y) * norm(x-y) \\<ge> 0\"\n    using k_pos  by simp\n  then have \"\\<forall>x\\<in>s. \\<forall>y\\<in>s. \\<forall>u\\<ge>0. \\<forall>v\\<ge>0. u + v = 1 \\<longrightarrow> \n  u * f x + v * f y - (k/2) * u * v * norm(x-y) * norm(x-y)  \\<le>\n  u * f x + v * f y \" by auto\n  then have \"(\\<forall>x\\<in>s. \\<forall>y\\<in>s. \\<forall>u\\<ge>0. \\<forall>v\\<ge>0. u + v = 1 \\<longrightarrow>\n     f (u *\\<^sub>R x + v *\\<^sub>R y) \\<le> u * f x + v * f y)\" using 1 by smt\n  then show \"convex_on s f\"  by (simp add: convex_on_def)\nqed\n\nend", "meta": {"author": "RaliDardjonova", "repo": "verify_ML", "sha": "de4316a2a86679a7ecc9a156da133e1b6eb7522e", "save_path": "github-repos/isabelle/RaliDardjonova-verify_ML", "path": "github-repos/isabelle/RaliDardjonova-verify_ML/verify_ML-de4316a2a86679a7ecc9a156da133e1b6eb7522e/Strong_Convexity.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473647220787, "lm_q2_score": 0.8333245891029456, "lm_q1q2_score": 0.7269485092620637}}
{"text": "theory Yen imports CoinClass begin\n\n\ndatatype Yen = Y1 | Y5 | Y10 | Y50 | Y100 | Y500\n\n\nlemma UNIV_Yen: \"(UNIV::Yen set) = {Y1, Y5, Y10, Y50, Y100, Y500}\"\n  apply(rule equalityI)\n  apply(rule subsetI)\n  apply(case_tac x; force)\n  apply(rule subset_UNIV)\n  done\n\n\ntheorem finite_UNIV_Yen: \"finite (UNIV::Yen set)\"\n  apply(subst UNIV_Yen)\n  apply(subst finite.intros)+\n  apply(rule TrueI)\n  done\n\n\ntheorem finite_Yen: \"finite C\" for C :: \"Yen set\"\n  apply(rule rev_finite_subset)\n  apply(rule finite_UNIV_Yen)\n  apply(rule subset_UNIV)\n  done\n\n\nlemma Yen_double_exhaust: \"\\<lbrakk>\n    P Y1 Y1; P Y1 Y5; P Y1 Y10; P Y1 Y50; P Y1 Y100; P Y1 Y500;\n    P Y5 Y1; P Y5 Y5; P Y5 Y10; P Y5 Y50; P Y5 Y100; P Y5 Y500;\n    P Y10 Y1; P Y10 Y5; P Y10 Y10; P Y10 Y50; P Y10 Y100; P Y10 Y500;\n    P Y50 Y1; P Y50 Y5; P Y50 Y10; P Y50 Y50; P Y50 Y100; P Y50 Y500;\n    P Y100 Y1; P Y100 Y5; P Y100 Y10; P Y100 Y50; P Y100 Y100; P Y100 Y500;\n    P Y500 Y1; P Y500 Y5; P Y500 Y10; P Y500 Y50; P Y500 Y100; P Y500 Y500\n\\<rbrakk> \\<Longrightarrow> P c1 c2\"\n  apply(rule_tac y=c1 in Yen.exhaust)\n  apply(rule_tac y=c2 in Yen.exhaust; erule ssubst; erule ssubst; assumption)\n  apply(rule_tac y=c2 in Yen.exhaust; erule ssubst; erule ssubst; assumption)\n  apply(rule_tac y=c2 in Yen.exhaust; erule ssubst; erule ssubst; assumption)\n  apply(rule_tac y=c2 in Yen.exhaust; erule ssubst; erule ssubst; assumption)\n  apply(rule_tac y=c2 in Yen.exhaust; erule ssubst; erule ssubst; assumption)\n  apply(rule_tac y=c2 in Yen.exhaust; erule ssubst; erule ssubst; assumption)\n  done\n\n\ninstantiation Yen :: linorder begin\nfun Yen_val_unit :: \"Yen \\<Rightarrow> val\" where\n  \"Yen_val_unit Y1 = 1\" |\n  \"Yen_val_unit Y5 = 5\" |\n  \"Yen_val_unit Y10 = 10\" |\n  \"Yen_val_unit Y50 = 50\" |                  \n  \"Yen_val_unit Y100 = 100\" |\n  \"Yen_val_unit Y500 = 500\"\n\nlemma inj_Yen_val_unit: \"inj Yen_val_unit\"\n  apply(unfold inj_def)\n  apply(intro allI)\n  apply(rule Yen_double_exhaust)\n  apply(auto)\n  done\n\nlemma dvd_Yen_val_unit[rule_format]: \"Yen_val_unit c1 < Yen_val_unit c2 \\<longrightarrow> Yen_val_unit c1 dvd Yen_val_unit c2\"\n  apply(rule Yen_double_exhaust)\n  apply(auto)\n  done\n\nlemma Yen_val_unit_gt_0: \"Yen_val_unit c > 0\"\n  apply(case_tac c; auto)\n  done\n\nlemma Yen_val_unit_range: \"range Yen_val_unit = {1, 5, 10, 50, 100, 500}\"\n  apply(auto)\n  apply(case_tac \"xa\"; auto)\n  apply(subst One_nat_def[symmetric])\n  apply(fold Yen_val_unit.simps)\n  apply(rule range_eqI; rule refl)\n  apply(rule range_eqI; rule refl)\n  apply(rule range_eqI; rule refl)\n  apply(rule range_eqI; rule refl)\n  apply(rule range_eqI; rule refl)\n  apply(rule range_eqI; rule refl)\n  done\n\ndefinition \"less_Yen (a::Yen) (b::Yen) \\<equiv> Yen_val_unit a < Yen_val_unit b\"\ndefinition \"less_eq_Yen (a::Yen) (b::Yen) \\<equiv> Yen_val_unit a \\<le> Yen_val_unit b\"  \n\ninstance\n  apply(standard)\n  apply(auto simp add: less_Yen_def less_eq_Yen_def inj_def)\n  apply(insert inj_Yen_val_unit)\n  apply(auto simp add: inj_def)\n  done\nend\n\n\nlemma strict_mono_Yen_val_unit: \"strict_mono Yen_val_unit\"\n  apply(simp add: strict_mono_def less_Yen_def)\n  done\n\n\ninstantiation Yen :: order_bot begin\ndefinition \"bot_Yen \\<equiv> Y1\"\ninstance\n  apply(standard)\n  apply(unfold bot_Yen_def less_eq_Yen_def)\n  apply(case_tac \"a\"; auto)\n  done\nend\n\n\ninstantiation Yen :: order_top begin\ndefinition \"top_Yen \\<equiv> Y500\"\ninstance\n  apply(standard)\n  apply(unfold top_Yen_def less_eq_Yen_def)\n  apply(case_tac \"a\"; auto)\n  done\nend\n\n\ninstantiation Yen :: Inf begin\ndefinition \"Inf_Yen C \\<equiv>\n  if Y1 \\<in> C then Y1\n    else if Y5 \\<in> C then Y5\n      else if Y10 \\<in> C then Y10\n        else if Y50 \\<in> C then Y50\n          else if Y100 \\<in> C then Y100\n            else Y500\"\n\n\nlemma Inf_empty_is_top_Yen: \"Inf {} = (top::Yen)\"\n  apply(unfold top_Yen_def Inf_Yen_def)\n  apply(auto)\n  done\n\n\nlemma Yen_val_unit_Inf_le: \"x \\<in> A \\<Longrightarrow> Yen_val_unit (Inf A) \\<le> Yen_val_unit x\"\n  apply(unfold Inf_Yen_def)\n  apply(case_tac x; auto)\n  done\n\n\nlemma Yen_val_unit_le_Inf: \"(\\<forall>x \\<in> A. Yen_val_unit z \\<le> Yen_val_unit x)\n    \\<Longrightarrow> Yen_val_unit z \\<le> Yen_val_unit (Inf A)\"\n  apply(unfold Inf_Yen_def)\n  apply(case_tac z; auto)\n  done\n\n\ninstance by standard\nend\n\n\ninstantiation Yen :: Sup begin\ndefinition \"Sup_Yen C \\<equiv>\n  if Y500 \\<in> C then Y500\n    else if Y100 \\<in> C then Y100\n      else if Y50 \\<in> C then Y50\n        else if Y10 \\<in> C then Y10\n          else if Y5 \\<in> C then Y5\n            else Y1\"\n\nlemma Sup_empty_is_bot_Yen: \"Sup {} = (bot::Yen)\"\n  apply(unfold bot_Yen_def Sup_Yen_def)\n  apply(auto)\n  done\n\nlemma Yen_val_unit_le_Sup: \"x \\<in> A \\<Longrightarrow> Yen_val_unit x \\<le> Yen_val_unit (Sup A)\"\n  apply(unfold Sup_Yen_def)\n  apply(case_tac x; auto)\n  done\n\nlemma Yen_val_unit_Sup_le: \"(\\<forall>x \\<in> A. Yen_val_unit x \\<le> Yen_val_unit z)\n    \\<Longrightarrow> Yen_val_unit (Sup A) \\<le> Yen_val_unit z\"\n  apply(unfold Sup_Yen_def)\n  apply(case_tac z; auto)\n  done\n\ninstance by standard\nend\n\n\ninstantiation Yen :: complete_lattice begin\ndefinition \"inf_Yen (a::Yen) (b::Yen) \\<equiv> if a \\<le> b then a else b\"\ndefinition \"sup_Yen (a::Yen) (b::Yen) \\<equiv> if a \\<le> b then b else a\"\ninstance\n  apply(standard)\n  apply(auto simp add: less_eq_Yen_def inf_Yen_def sup_Yen_def top_Yen_def bot_Yen_def)\n  apply(auto intro: Yen_val_unit_Inf_le Yen_val_unit_le_Inf Yen_val_unit_le_Sup Yen_val_unit_Sup_le)\n  apply(fold top_Yen_def bot_Yen_def)\n  apply(auto intro: Inf_empty_is_top_Yen Sup_empty_is_bot_Yen)\n  done\nend\n\n\ninstantiation Yen :: coins begin\ndefinition \"val_unit_Yen \\<equiv> Yen_val_unit\"\ninstance\n  apply(standard)\n  apply(auto simp add: val_unit_Yen_def bot_Yen_def intro: strict_mono_Yen_val_unit dvd_Yen_val_unit)\n  done\nend\nend", "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/Yen.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467548438124, "lm_q2_score": 0.8267117962054048, "lm_q1q2_score": 0.7268009928250808}}
{"text": "theory Ex013\nimports Main \nbegin \n\n\nlemma \"(A \\<longrightarrow> B) \\<longrightarrow> (\\<not>B \\<longrightarrow> \\<not>A)\"\nproof - \n{\n  assume \"A \\<longrightarrow> B\"\n  {\n    assume \"\\<not>B\"\n    {\n      assume A \n      with \\<open>A \\<longrightarrow> B\\<close> have B by (rule impE)\n      with \\<open>\\<not>B\\<close> have False by contradiction\n    }\n    hence \"\\<not>A\" by (rule notI)\n  }\n  hence \"\\<not>B \\<longrightarrow> \\<not>A\" by (rule impI)\n}\nthus ?thesis by (rule impI)\nqed\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/Ex013.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9284088045171238, "lm_q2_score": 0.7826624789529375, "lm_q1q2_score": 0.7266307364251053}}
{"text": "theory P3 imports Main\nbegin\n\nfun replace :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a list \\<Rightarrow> 'a list\"  where\n\"replace x y Nil = Nil\" | \n\"(replace x y (Cons z xs)) = (if x=z then (Cons y (replace x y xs)) else (Cons z (replace x y xs)))\"\n\n\n\nlemma [simp]: \"replace x y (zs @ [x]) = replace x y zs @ [y]\"\n  apply (induct zs)\n   apply auto\n  done\n\nlemma [simp]: \"x \\<noteq> a \\<Longrightarrow> replace x y zs @ [a] = replace x y (zs @ [a])\"\n  apply (induct zs)\n   apply auto\n  done\n\ntheorem \"rev(replace x y zs) = replace x y (rev zs)\"\n  apply (induct zs)\n   apply auto\n  done\n\nlemma \"replace x y (replace u v zs) = replace u v (replace x y zs)\"\n  nitpick\n  oops\n\nlemma \"replace y z (replace x y zs) = replace x z zs\"\n  nitpick\n  oops\n\nfun del1 :: \"'a \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where\n\"del1 x Nil = Nil\" |\n\"del1 x (y # xs) = (if x=y then xs else (y # xs))\"\n\nfun delall :: \"'a \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where\n\"delall x Nil = Nil\" |\n\"delall x (y # xs) = (if x=y then (delall x xs) else (y # (delall x xs)))\"\n\ntheorem \"del1 x (delall x xs) = delall x xs\"\n  apply (induct xs)\n   apply auto\n  done\n\ntheorem \"delall x (delall x xs) = delall x xs\"\n  apply (induct xs)\n   apply auto\n  done\n\ntheorem \"delall x (del1 x xs) = delall x xs\"\n  apply (induct xs)\n   apply auto\n  done\n\nlemma \"del1 x (del1 y zs) = del1 y (del1 x zs)\"\n  nitpick\n  oops\n\nlemma \"delall x (del1 y zs) = del1 y (delall x zs)\"\n  nitpick\n  oops\n\ntheorem \"delall x (delall y xs) = delall y (delall x xs)\"\n  apply (induct xs)\n   apply auto\n  done\n\nlemma \"del1 y (replace x y xs) = del1 x xs\"\n  nitpick\n  oops\n\nlemma \"delall y (replace x y xs) = delall x xs\"\n  nitpick\n  oops\n\ntheorem \"replace x y (delall x xs) = delall x xs\"\n  apply (induct xs)\n   apply auto\n  done\n\nlemma \"replace x y (delall z xs) = delall z (replace x y xs)\"\n  nitpick\n  oops\n\nlemma \"rev(del1 x xs) = del1 x (rev xs)\"\n  nitpick\n  oops\n\nlemma [simp]: \"delall x (xs @ [x]) = delall x xs\"\n  apply (induct xs)\n  apply auto\n  done\n\nlemma [simp]: \"x \\<noteq> a \\<Longrightarrow> delall x xs @ [a] = delall x (xs @ [a])\"\n  apply (induct xs)\n   apply auto\n  done\n\ntheorem \"rev(delall x xs) = delall x (rev xs)\"\n  apply (induct xs)\n   apply auto\n  done\n\nend\n\n", "meta": {"author": "albertqjiang", "repo": "Isa100days", "sha": "a8e1069390243033f993328421526d2ff077d1ca", "save_path": "github-repos/isabelle/albertqjiang-Isa100days", "path": "github-repos/isabelle/albertqjiang-Isa100days/Isa100days-a8e1069390243033f993328421526d2ff077d1ca/P3.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587993853654, "lm_q2_score": 0.8175744828610095, "lm_q1q2_score": 0.7266265157956618}}
{"text": "(*  \n    Title:      Inverse.thy\n    Author:     Jose Divas\u00f3n <jose.divasonm at unirioja.es>\n    Author:     Jes\u00fas Aransay <jesus-maria.aransay at unirioja.es>\n*)\n\nheader{*Inverse of a matrix using the Gauss Jordan algorithm*}\n\ntheory Inverse\nimports\n  Gauss_Jordan_PA\nbegin\n\nsubsection{*Several properties*}\n\ntext{*Properties about Gauss Jordan algorithm, reduced row echelon form, rank, identity matrix and invertibility*}\n\nlemma rref_id_implies_invertible:\nfixes A::\"'a::{field}^'n::{mod_type}^'n::{mod_type}\"\nassumes Gauss_mat_1: \"Gauss_Jordan A = mat 1\"\nshows \"invertible A\"\nproof -\nobtain P where P: \"invertible P\" and PA: \"Gauss_Jordan A = P ** A\" using invertible_Gauss_Jordan[of A] by blast\nhave \"A = mat 1 ** A\" unfolding matrix_mul_lid ..\nalso have \"... = (matrix_inv P ** P) ** A\" using P invertible_def matrix_inv_unique by metis\nalso have \"... = (matrix_inv P) ** (P ** A)\" by (metis PA assms calculation matrix_eq matrix_vector_mul_assoc matrix_vector_mul_lid)\nalso have \"... = (matrix_inv P) ** mat 1\" unfolding PA[symmetric] Gauss_mat_1 ..\nalso have \"... = (matrix_inv P)\" unfolding matrix_mul_rid ..\nfinally have \"A = (matrix_inv P)\" .\nthus ?thesis using P unfolding invertible_def using matrix_inv_unique by blast\nqed\n\ntext{*In the following case, nrows is equivalent to ncols due to we are working with a square matrix*}\nlemma full_rank_implies_invertible:\nfixes A::\"'a::{field}^'n::{mod_type}^'n::{mod_type}\"\nassumes rank_n: \"rank A = nrows A\"\nshows \"invertible A\"\nproof (unfold invertible_left_inverse[of A] matrix_left_invertible_ker, clarify)\nfix x\nassume Ax: \"A *v x = 0\"\nhave rank_eq_card_n: \"rank A = CARD('n)\" using rank_n unfolding nrows_def .\nhave \"vec.dim (null_space A)=0\" unfolding dim_null_space unfolding rank_eq_card_n dimension_vector by simp\nhence \"null_space A = {0}\" using vec.dim_zero_eq using Ax null_space_def by auto\nthus \"x = 0\" unfolding null_space_def using Ax by blast\nqed\n\n\nlemma invertible_implies_full_rank:\nfixes A::\"'a::{field}^'n::{mod_type}^'n::{mod_type}\"\nassumes inv_A: \"invertible A\"\nshows \"rank A = nrows A\"\nproof -\nhave \"(\\<forall>x. A *v x = 0 \\<longrightarrow> x = 0)\" using inv_A unfolding  invertible_left_inverse[unfolded matrix_left_invertible_ker] .\nhence null_space_eq_0: \"(null_space A) = {0}\" unfolding null_space_def using matrix_vector_zero by fast\nhave dim_null_space: \"vec.dim (null_space A) = 0\" unfolding vec.dim_def \n    by (rule someI2[of _\"0\"], rule exI[of _ \"{}\"], simp add: vec.independent_empty null_space_eq_0,\n      metis card_empty empty_subsetI null_space_eq_0 vec.span_empty vec.spanning_subset_independent)\nshow ?thesis using rank_nullity_theorem_matrices[of A] unfolding dim_null_space rank_eq_dim_col_space nrows_def\nunfolding col_space_eq unfolding ncols_def by simp\nqed\n\n\ndefinition id_upt_k :: \"'a::{zero, one}^'n::{mod_type}^'n::{mod_type} \\<Rightarrow> nat => bool\"\nwhere \"id_upt_k A k = (\\<forall>i j. to_nat i < k \\<and> to_nat j < k \\<longrightarrow> ((i = j \\<longrightarrow> A $ i $ j = 1) \\<and> (i \\<noteq> j \\<longrightarrow> A $ i $ j = 0)))\"\n\nlemma id_upt_nrows_mat_1:\nassumes \"id_upt_k A (nrows A)\"\nshows \"A = mat 1\"\nunfolding mat_def apply vector using assms unfolding id_upt_k_def nrows_def\nusing to_nat_less_card[where ?'a='b]\nby presburger\n\nsubsection{*Computing the inverse of a matrix using the Gauss Jordan algorithm*}\n\ntext{*This lemma is essential to demonstrate that the Gauss Jordan form of an invertible matrix is the identity. \n  The proof is made by induction and it is explained in \n  \\url{http://www.unirioja.es/cu/jodivaso/Isabelle/Gauss-Jordan-2013-2-Generalized/Demonstration_invertible.pdf}*}\n\nlemma id_upt_k_Gauss_Jordan:\nfixes A::\"'a::{field}^'n::{mod_type}^'n::{mod_type}\"\nassumes inv_A: \"invertible A\"\nshows \"id_upt_k (Gauss_Jordan A) k\"\nproof (induct k)\ncase 0\nshow ?case unfolding id_upt_k_def by fast\nnext\ncase (Suc k)\nnote id_k=Suc.hyps\nhave rref_k: \"reduced_row_echelon_form_upt_k (Gauss_Jordan A) k\"  using rref_implies_rref_upt[OF rref_Gauss_Jordan] .\nhave rref_suc_k: \"reduced_row_echelon_form_upt_k (Gauss_Jordan A) (Suc k)\"  using rref_implies_rref_upt[OF rref_Gauss_Jordan] .\nhave inv_gj: \"invertible (Gauss_Jordan A)\" by (metis inv_A invertible_Gauss_Jordan invertible_mult)\nshow \"id_upt_k (Gauss_Jordan A) (Suc k)\"\nproof (unfold id_upt_k_def, auto)\nfix j::'n\nassume j_less_suc: \"to_nat j < Suc k\"\n--\"First of all we prove a property which will be useful later\"\nhave greatest_prop: \"j \\<noteq> 0 \\<Longrightarrow> to_nat j = k \\<Longrightarrow> (GREATEST' m. \\<not> is_zero_row_upt_k m k (Gauss_Jordan A)) = j - 1\"\nproof (rule Greatest'_equality)\nassume j_not_zero: \"j \\<noteq> 0\" and j_eq_k: \"to_nat j = k\"\n have j_minus_1: \"to_nat (j - 1) < k\" by (metis (full_types) Suc_le' diff_add_cancel j_eq_k j_not_zero to_nat_mono)\n          show \"\\<not> is_zero_row_upt_k (j - 1) k (Gauss_Jordan A)\"\n            unfolding is_zero_row_upt_k_def\n            proof (auto, rule exI[of _ \"j - 1\"], rule conjI)\n               show \"to_nat (j - 1) < k\" using j_minus_1 .\n               show \"Gauss_Jordan A $ (j - 1) $ (j - 1) \\<noteq> 0\" using id_k unfolding id_upt_k_def using j_minus_1 by simp\n            qed\n            fix a::'n\n            assume not_zero_a: \"\\<not> is_zero_row_upt_k a k (Gauss_Jordan A)\"\n            show \"a \\<le> j - 1\"\n              proof (rule ccontr)\n                assume \" \\<not> a \\<le> j - 1\"\n                hence a_greater_i_minus_1: \"a > j - 1\" by simp\n                have \"is_zero_row_upt_k a k (Gauss_Jordan A)\"\n                  unfolding is_zero_row_upt_k_def\n                    proof (clarify)\n                    fix b::'n assume a: \"to_nat b < k\"\n                    have Least_eq: \"(LEAST n. Gauss_Jordan A $ b $ n \\<noteq> 0) = b\"\n                      proof (rule Least_equality)\n                        show \"Gauss_Jordan A $ b $ b \\<noteq> 0\" by (metis a id_k id_upt_k_def zero_neq_one)\n                        show \"\\<And>y. Gauss_Jordan A $ b $ y \\<noteq> 0 \\<Longrightarrow> b \\<le> y\"\n                          by (metis (hide_lams, no_types) a dual_linorder.not_less_iff_gr_or_eq id_k id_upt_k_def less_trans not_less to_nat_mono)\n                      qed\n                    moreover have \"\\<not> is_zero_row_upt_k b k (Gauss_Jordan A)\"\n                      unfolding is_zero_row_upt_k_def apply auto apply (rule exI[of _ b]) using a id_k unfolding id_upt_k_def by simp\n                    moreover have \"a \\<noteq> b\"\n                      proof -\n                       have \"b < from_nat k\" by (metis a from_nat_to_nat_id j_eq_k not_less_iff_gr_or_eq to_nat_le)\n                       also have \"... = j\" using j_eq_k to_nat_from_nat by auto\n                       also have \"... \\<le> a\" using a_greater_i_minus_1 by (metis diff_add_cancel le_Suc)\n                       finally show ?thesis by simp\n                      qed\n                    ultimately show \"Gauss_Jordan A $ a $ b = 0\" using rref_upt_condition4[OF rref_k] by auto\n                    qed\n                thus \"False\" using not_zero_a by contradiction\n              qed\n              qed\n\nshow Gauss_jj_1: \"Gauss_Jordan A $ j $ j = 1\"\nproof (cases \"j=0\")\n--\"In case that j be zero, the result is trivial\"\ncase True show ?thesis\n  proof (unfold True, rule rref_first_element)\n     show \"reduced_row_echelon_form (Gauss_Jordan A)\" by (rule rref_Gauss_Jordan)\n     show \"column 0 (Gauss_Jordan A) \\<noteq> 0\" by (metis det_zero_column inv_gj invertible_det_nz)\n  qed\nnext\ncase False note j_not_zero = False\nshow ?thesis\nproof (cases \"to_nat j < k\")\n  case True thus ?thesis using id_k unfolding id_upt_k_def by presburger  --\"Easy due to the inductive hypothesis\"\n  next\n  case False\n  hence j_eq_k: \"to_nat j = k\" using j_less_suc by auto\n  have j_minus_1: \"to_nat (j - 1) < k\" by (metis (full_types) Suc_le' diff_add_cancel j_eq_k j_not_zero to_nat_mono)\n  have \"(GREATEST' m. \\<not> is_zero_row_upt_k m k (Gauss_Jordan A)) = j - 1\" by (rule greatest_prop[OF j_not_zero j_eq_k])\n        hence zero_j_k: \"is_zero_row_upt_k j k (Gauss_Jordan A)\"\n                by (metis not_le greatest_ge_nonzero_row j_eq_k j_minus_1 to_nat_mono')\n              show ?thesis\n                proof (rule ccontr, cases \"Gauss_Jordan A $ j $ j = 0\")\n                case False\n                note gauss_jj_not_0 = False\n                assume gauss_jj_not_1: \"Gauss_Jordan A $ j $ j \\<noteq> 1\"\n                have \"(LEAST n. Gauss_Jordan A $ j $ n \\<noteq> 0) = j\"\n                  proof (rule Least_equality)\n                     show \"Gauss_Jordan A $ j $ j \\<noteq> 0\" using gauss_jj_not_0 .\n                     show \"\\<And>y. Gauss_Jordan A $ j $ y \\<noteq> 0 \\<Longrightarrow> j \\<le> y\" by (metis le_less_linear is_zero_row_upt_k_def j_eq_k to_nat_mono zero_j_k)\n                  qed\n                hence \"Gauss_Jordan A $ j $ (LEAST n. Gauss_Jordan A $ j $ n \\<noteq> 0) \\<noteq> 1\" using gauss_jj_not_1 by auto --\"Contradiction with the second condition of rref\"\n                thus False by (metis gauss_jj_not_0 is_zero_row_upt_k_def j_eq_k lessI rref_suc_k rref_upt_condition2)             \n                next\n                  case True\n                  note gauss_jj_0 = True\n                  have zero_j_suc_k: \"is_zero_row_upt_k j (Suc k) (Gauss_Jordan A)\" \n                    by (rule is_zero_row_upt_k_suc[OF zero_j_k], metis gauss_jj_0 j_eq_k to_nat_from_nat)                  \n                    have \"\\<not> (\\<exists>B. B ** (Gauss_Jordan A) = mat 1)\" --\"This will be a contradiction\"\n                    proof (unfold matrix_left_invertible_independent_columns, simp, \n                        rule exI[of _ \"\\<lambda>i. (if i < j then column j (Gauss_Jordan A) $ i else if i=j then -1 else 0)\"], rule conjI)\n                      show \"(\\<Sum>i\\<in>UNIV. (if i < j then column j (Gauss_Jordan A) $ i else if i=j then -1 else 0) *s column i (Gauss_Jordan A)) = 0\"                        \n                        proof (unfold vec_eq_iff setsum_component, auto)\n                          --\"We write the column j in a linear combination of the previous ones, which is a contradiction (the matrix wouldn't be invertible)\"\n                            let ?f=\"\\<lambda>i. (if i < j then column j (Gauss_Jordan A) $ i else if i=j then -1 else 0)\"\n                            fix i\n                            let ?g=\"(\\<lambda>x. ?f x * column x (Gauss_Jordan A) $ i)\"\n                            show \"setsum ?g UNIV = 0\"\n                              proof (cases \"i<j\")\n                              case True note i_less_j = True\n                              have setsum_rw: \"setsum ?g (UNIV - {i}) = ?g j + setsum ?g ((UNIV - {i}) - {j})\"\n                                proof (rule setsum.remove)\n                                   show \"finite (UNIV - {i})\" using finite_code by simp\n                                   show \"j \\<in> UNIV - {i}\" using True by blast\n                                qed                                \n                              have setsum_g0: \"setsum ?g (UNIV - {i} - {j}) = 0\"\n                                proof (rule setsum.neutral, auto)\n                                fix a\n                                assume a_not_j: \"a \\<noteq> j\" and a_not_i: \"a \\<noteq> i\" and a_less_j: \"a < j\" and column_a_not_zero: \"column a (Gauss_Jordan A) $ i \\<noteq> 0\"\n                                have \"Gauss_Jordan A $ i $ a = 0\" using id_k unfolding id_upt_k_def using a_less_j j_eq_k using i_less_j a_not_i to_nat_mono by blast\n                                thus \"column j (Gauss_Jordan A) $ a = 0\" using column_a_not_zero unfolding column_def by simp --\"Contradiction\"\n                                qed\n                              have \"setsum ?g UNIV = ?g i + setsum ?g (UNIV - {i})\" by (rule setsum.remove, simp_all)\n                              also have \"... = ?g i + ?g j + setsum ?g (UNIV - {i} - {j})\" unfolding setsum_rw by auto\n                              also have \"... = ?g i + ?g j\" unfolding setsum_g0 by simp\n                              also have \"... = 0\" using True unfolding column_def \n                                by (simp, metis id_k id_upt_k_def j_eq_k to_nat_mono)\n                              finally show ?thesis .\n                              next\n                              case False\n                              have zero_i_suc_k: \"is_zero_row_upt_k i (Suc k) (Gauss_Jordan A)\"\n                                    by (metis False zero_j_suc_k linorder_cases rref_suc_k rref_upt_condition1)\n                              show ?thesis\n                                proof (rule setsum.neutral, auto)              \n                                  show \"column j (Gauss_Jordan A) $ i = 0\"\n                                    using zero_i_suc_k unfolding column_def is_zero_row_upt_k_def\n                                    by (metis j_eq_k lessI vec_lambda_beta)\n                                  next\n                                  fix a\n                                  assume a_not_j: \"a \\<noteq> j\" and a_less_j: \"a < j\" and column_a_i: \"column a (Gauss_Jordan A) $ i \\<noteq> 0\"\n                                  have \"Gauss_Jordan A $ i $ a = 0\" using zero_i_suc_k unfolding is_zero_row_upt_k_def\n                                    by (metis (full_types) a_less_j j_eq_k less_SucI to_nat_mono)\n                                  thus \"column j (Gauss_Jordan A) $ a = 0\" using column_a_i unfolding column_def by simp                                  \n                        qed\n                    qed\n                    qed\n                    next\n                    show \"\\<exists>i. (if i < j then column j (Gauss_Jordan A) $ i else if i = j then -1 else 0) \\<noteq> 0\"\n                      by (metis False j_eq_k neg_equal_0_iff_equal to_nat_mono zero_neq_one)\n                    qed                    \n                    thus False using inv_gj unfolding invertible_def by simp\n                    qed\n                    qed \n                   qed\n                    fix i::'n\n                    assume i_less_suc: \"to_nat i < Suc k\" and i_not_j: \"i \\<noteq> j\"\n                    show \"Gauss_Jordan A $ i $ j = 0\" --\"This result is proved making use of the 4th condition of rref\"\n                      proof (cases \"to_nat i < k \\<and> to_nat j < k\")\n                        case True thus ?thesis using id_k i_not_j unfolding id_upt_k_def by blast --\"Easy due to the inductive hypothesis\"\n                        next\n                        case False note i_or_j_ge_k = False\n                        show ?thesis\n                        proof (cases \"to_nat i < k\")\n                          case True\n                          hence j_eq_k: \"to_nat j = k\" using i_or_j_ge_k j_less_suc by simp\n                          have j_noteq_0: \"j \\<noteq> 0\" by (metis True j_eq_k less_nat_zero_code to_nat_0)\n                          have j_minus_1: \"to_nat (j - 1) < k\" by (metis (full_types) Suc_le' diff_add_cancel j_eq_k j_noteq_0 to_nat_mono)\n                          have \"(GREATEST' m. \\<not> is_zero_row_upt_k m k (Gauss_Jordan A)) = j - 1\" by (rule greatest_prop[OF j_noteq_0 j_eq_k])\n                          hence zero_j_k: \"is_zero_row_upt_k j k (Gauss_Jordan A)\" \n                            by (metis (lifting, mono_tags) dual_linorder.less_linear dual_order.less_asym j_eq_k j_minus_1 not_greater_Greatest' to_nat_mono)\n                          have Least_eq_j: \"(LEAST n. Gauss_Jordan A $ j $ n \\<noteq> 0) = j\"\n                            proof (rule Least_equality)\n                               show \"Gauss_Jordan A $ j $ j \\<noteq> 0\" using Gauss_jj_1 by simp\n                               show \"\\<And>y. Gauss_Jordan A $ j $ y \\<noteq> 0 \\<Longrightarrow> j \\<le> y\" \n                               by (metis True dual_linorder.le_cases from_nat_to_nat_id i_or_j_ge_k is_zero_row_upt_k_def j_less_suc less_Suc_eq_le less_le to_nat_le zero_j_k)\n                            qed\n                          moreover have \"\\<not> is_zero_row_upt_k j (Suc k) (Gauss_Jordan A)\" unfolding is_zero_row_upt_k_def by (metis Gauss_jj_1 j_less_suc zero_neq_one)                          \n                          ultimately show ?thesis using rref_upt_condition4[OF rref_suc_k] i_not_j by fastforce\n                          next\n                          case False\n                          hence i_eq_k: \"to_nat i = k\" by (metis `to_nat i < Suc k` less_SucE)\n                          hence j_less_k: \"to_nat j < k\" by (metis i_not_j j_less_suc less_SucE to_nat_from_nat)\n                          have \"(LEAST n. Gauss_Jordan A $ j $ n \\<noteq> 0) = j\"\n                            proof (rule Least_equality)\n                               show \"Gauss_Jordan A $ j $ j \\<noteq> 0\" by (metis Gauss_jj_1 zero_neq_one)\n                               show \"\\<And>y. Gauss_Jordan A $ j $ y \\<noteq> 0 \\<Longrightarrow> j \\<le> y\"\n                                  by (metis dual_linorder.le_cases id_k id_upt_k_def j_less_k less_trans not_less to_nat_mono)\n                            qed\n                          moreover have \"\\<not> is_zero_row_upt_k j k (Gauss_Jordan A)\" by (metis (full_types) Gauss_jj_1 is_zero_row_upt_k_def j_less_k zero_neq_one)\n                          ultimately show ?thesis  using rref_upt_condition4[OF rref_k] i_not_j by fastforce\n                         qed\n                         qed\nqed\nqed\n\n\nlemma invertible_implies_rref_id:\n  fixes A::\"'a::{field}^'n::{mod_type}^'n::{mod_type}\"\n  assumes inv_A: \"invertible A\"\n  shows \"Gauss_Jordan A = mat 1\"\n  using id_upt_k_Gauss_Jordan[OF inv_A, of \"nrows (Gauss_Jordan A)\"]\n  using id_upt_nrows_mat_1\n  by fast\n\n\nlemma matrix_inv_Gauss:\nfixes A::\"'a::{field}^'n::{mod_type}^'n::{mod_type}\"\nassumes inv_A: \"invertible A\" and Gauss_eq: \"Gauss_Jordan A = P ** A\"\nshows \"matrix_inv A = P\"\nproof (unfold matrix_inv_def, rule some1_equality)\n show \"\\<exists>!A'. A ** A' = mat 1 \\<and> A' ** A = mat 1\" by (metis inv_A invertible_def matrix_inv_unique matrix_left_right_inverse)\n show \"A ** P = mat 1 \\<and> P ** A = mat 1\" by (metis Gauss_eq inv_A invertible_implies_rref_id matrix_left_right_inverse)\nqed\n\n\nlemma matrix_inv_Gauss_Jordan_PA:\nfixes A::\"'a::{field}^'n::{mod_type}^'n::{mod_type}\"\nassumes inv_A: \"invertible A\"\nshows \"matrix_inv A = fst (Gauss_Jordan_PA A)\"\nby (metis Gauss_Jordan_PA_eq fst_Gauss_Jordan_PA inv_A matrix_inv_Gauss)\n\n\nlemma invertible_eq_full_rank[code_unfold]:\nfixes A::\"'a::{field}^'n::{mod_type}^'n::{mod_type}\"\nshows \"invertible A = (rank A = nrows A)\"\nby (metis full_rank_implies_invertible invertible_implies_full_rank)\n\ndefinition \"inverse_matrix A = (if invertible A then Some (matrix_inv A) else None)\"\n\nlemma the_inverse_matrix:\nfixes A::\"'a::{field}^'n::{mod_type}^'n::{mod_type}\"\nassumes \"invertible A\"\nshows \"the (inverse_matrix A) = P_Gauss_Jordan A\"\n  by (metis P_Gauss_Jordan_def assms inverse_matrix_def matrix_inv_Gauss_Jordan_PA option.sel)\n\nlemma inverse_matrix:\nfixes A::\"'a::{field}^'n::{mod_type}^'n::{mod_type}\"\nshows \"inverse_matrix A = (if invertible A then Some (P_Gauss_Jordan A) else None)\"\n  by (metis inverse_matrix_def option.sel the_inverse_matrix)\n\nlemma inverse_matrix_code[code_unfold]:\nfixes A::\"'a::{field}^'n::{mod_type}^'n::{mod_type}\"\nshows \"inverse_matrix A = (let GJ = Gauss_Jordan_PA A;\n                                rank_A = (if A = 0 then 0 else to_nat (GREATEST' a. row a (snd GJ) \\<noteq> 0) + 1) in \n                                if nrows A = rank_A then Some (fst(GJ)) else None)\"\nunfolding inverse_matrix\nunfolding invertible_eq_full_rank\nunfolding rank_Gauss_Jordan_code\nunfolding P_Gauss_Jordan_def\nunfolding Let_def Gauss_Jordan_PA_eq by presburger\n\nend\n\n\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/Gauss_Jordan/Inverse.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8887588023318196, "lm_q2_score": 0.8175744739711883, "lm_q1q2_score": 0.7266265103037007}}
{"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 Lattice_Instance \n  \nimports \n  Order_Instances \n  Lattice_Class \n  Lattice_Morphism\n\nbegin\n\ntext {*\n\nIn this section we demonstrate the lattice properties of some important\ntype constructors.\n\n*}\n\nsection {* The booleans *}\n\ntext {*\n\nThe booleans form a complete, Boolean lattice with a linear order.\n\n*}\n\ninstantiation\n  bool :: clattice\n\nbegin\n\ndefinition\n  linf_bool_def: \"(op &&) \\<defs> (\\<olambda> (x::\\<bool>) y \\<bullet> x \\<and> y)\"\n\ndefinition\n  lsup_bool_def: \"(op ||) \\<defs> (\\<olambda> (x::\\<bool>) y \\<bullet> x \\<or> y)\"\n\ndefinition\n  Inf_bool_def: \"Inf \\<defs> (\\<olambda> (X::\\<bool> set) \\<bullet> (\\<forall> x | x \\<in> X \\<bullet> x))\"\n\ndefinition\n  Sup_bool_def: \"Sup \\<defs> (\\<olambda> (X::\\<bool> set) \\<bullet> (\\<exists> x | x \\<in> X \\<bullet> x))\"\n\ndefinition\n  bot_bool_def: \"bot \\<defs> \\<False>\"\n\ndefinition\n  top_bool_def: \"top \\<defs> \\<True>\"\n\ninstance\n  apply (intro_classes)\n  apply (unfold  le_bool_def linf_bool_def lsup_bool_def Inf_bool_def Sup_bool_def bot_bool_def top_bool_def)\n  apply (fast+)\n  done\n\nend\n\ninstantiation\n  bool :: boollattice\nbegin\n\ndefinition\n  lcomp_bool_def: \"ocomp \\<defs> Not\"\n\ninstance\n  apply (intro_classes)\n  apply (unfold  linf_bool_def lsup_bool_def bot_bool_def top_bool_def lcomp_bool_def)\n  apply (fast+)\n  done\n\nend\n\nlemmas lat_bool_defs = \n  linf_bool_def lsup_bool_def\n  Inf_bool_def Sup_bool_def\n  bot_bool_def top_bool_def lcomp_bool_def\n\n\n\nsection {* Product lattices *}\n\ntext {* The product constructor preserves all forms of lattices. *}\n\ninstantiation\n  prod :: (lat, lat) lat\nbegin\n\ndefinition\n  inf_prod_def: \"(op &&) \\<defs> (\\<olambda> (x, x') (y, y') \\<bullet> (x && y, x' && y'))\"\n\ndefinition\n  sup_prod_def: \"(op ||) \\<defs> (\\<olambda> (x, x') (y, y') \\<bullet> (x || y, x' || y'))\"\n\ninstance\n  by (intro_classes)\n\nend\n\ninstantiation\n  prod :: (blat, blat) blat\nbegin\n\ndefinition\n  bot_prod_def: \"bot \\<defs> (bot, bot)\"\n\ndefinition\n  top_prod_def: \"top \\<defs> (top, top)\"\n\ninstance\n  by (intro_classes)\n\nend\n\ninstantiation\n  prod :: (clat, clat) clat\nbegin\n\ndefinition\n  Inf_prod_def: \"Inf \\<defs> (\\<olambda> P \\<bullet> (Inf { x | x \\<in> P \\<bullet> \\<fst> x}, Inf { x | x \\<in> P \\<bullet> \\<snd> x}))\"\n\ndefinition\n  Sup_prod_def: \"Sup \\<defs> (\\<olambda> P \\<bullet> (Sup { x | x \\<in> P \\<bullet> \\<fst> x}, Sup { x | x \\<in> P \\<bullet> \\<snd> x}))\"\n\ninstance\n  by (intro_classes)\n\nend\n\ninstantiation\n  prod :: (bllat, bllat) bllat\nbegin\n\ndefinition\n  comp_prod_def: \"ocomp \\<defs> (\\<olambda> (x, y) \\<bullet> (ocomp x, ocomp y))\"\n\ninstance\n  by (intro_classes)\n\nend\n\ninstance\n  prod :: (lattice, lattice) lattice\n  apply (intro_classes)\n  apply (auto intro!: inf_lb1 inf_lb2 inf_glb sup_ub1 sup_ub2 sup_lub simp add: inf_prod_def sup_prod_def less_eq_prod_def product_order_def)\n  done\n\ninstance\n  prod :: (boundlattice, boundlattice) boundlattice\n  apply (intro_classes)\n  apply (auto simp add: bot_prod_def top_prod_def less_eq_prod_def product_order_def bot_lb top_ub)\n  done\n\ninstance\n  prod :: (clattice, clattice) clattice\n  apply (intro_classes)\n  apply (auto \n          intro!: Inf_lb Sup_ub Inf_glb Sup_lub inf_eq sup_eq bot_eq top_eq \n          simp add: less_eq_prod_def product_order_def Inf_prod_def Sup_prod_def eind_def)\n  done\n\ninstance\n  prod :: (dlattice, dlattice) dlattice\n  by (intro_classes, auto simp add: inf_prod_def sup_prod_def sup_dist eind_def)\n\ninstance\n  prod :: (boollattice, boollattice) boollattice\n  apply (intro_classes)\n  apply (auto simp add: \n            comp_prod_def inf_prod_def sup_prod_def bot_prod_def top_prod_def comp_inf comp_sup)\n  done\n\nsection {* Operator lattices *}\n\ntext {*\n\nThe function constructor preserves all forms of lattices structure in\nits range type.\n\n*}\n\ninstantiation\n  \"fun\" :: (type, lat) lat\nbegin\n\ndefinition\n  linf_fun_def: \"(op &&) \\<defs> (\\<olambda> f g x \\<bullet> (f x) && (g x))\"\n\ndefinition\n  lsup_fun_def: \"(op ||) \\<defs> (\\<olambda> f g x \\<bullet> (f x) || (g x))\"\n\ninstance\n  by (intro_classes)\n\nend\n\ninstantiation\n  \"fun\" :: (type, blat) blat\nbegin\n\ndefinition\n  bot_fun_def: \"bot \\<defs> (\\<olambda> x \\<bullet> bot)\"\n\ndefinition\n  top_fun_def: \"top \\<defs> (\\<olambda> x \\<bullet> top)\"\n\ninstance\n  by (intro_classes)\n\nend\n\ninstantiation\n  \"fun\" :: (type, clat) clat\nbegin\n\ndefinition\n  Inf_fun_def: \"Inf \\<defs> (\\<olambda> P x \\<bullet> Inf { f | f \\<in> P \\<bullet> f x })\"\n\ndefinition\n  Sup_fun_def: \"Sup \\<defs> (\\<olambda> P x \\<bullet> Sup { f | f \\<in> P \\<bullet> f x })\"\n\ninstance\n  by (intro_classes)\n\nend\n\ninstantiation\n  \"fun\" :: (type, bllat) bllat\nbegin\n\ndefinition\n  lcomp_fun_def: \"ocomp \\<defs> (\\<olambda> f x \\<bullet> ocomp (f x))\"\n\ninstance\n  by (intro_classes)\n\nend\n\ninstance\n  \"fun\" :: (type, lattice) lattice\n  apply (intro_classes)\n  apply (auto intro!: inf_lb1 inf_lb2 sup_ub1 sup_ub2 inf_glb sup_lub simp add: linf_fun_def lsup_fun_def le_fun_conv)\n  done\n\nlemma inf_mono_fun:\n  \"\\<lbrakk> mono (f::('a::order) \\<rightarrow> ('b::lattice)); mono g \\<rbrakk> \\<turnstile> mono (f \\<linf> g)\"\nproof (simp (no_asm) add: mono_def linf_fun_def, auto)\n  fix A::'a and B::'a\n  assume a1: \"mono f\" and\n    a2: \"mono g\" and\n    a3: \"A \\<le> B\"\n  show \"f A \\<linf> g A \\<le> f B \\<linf> g B\"\n    by (intro inf_mono a1 [THEN monoD] a2 [THEN monoD] a3)\nqed\n  \nlemma sup_mono_fun:\n  \"\\<lbrakk> mono (f::('a::order) \\<rightarrow> ('b::lattice)); mono g \\<rbrakk> \\<turnstile> mono (f \\<lsup> g)\"\nproof (simp (no_asm) add: mono_def lsup_fun_def, auto)\n  fix A::'a and B::'a\n  assume a1: \"mono f\" and\n    a2: \"mono g\" and\n    a3: \"A \\<le> B\"\n  show \"f A \\<lsup> g A \\<le> f B \\<lsup> g B\"\n    by (intro sup_mono a1 [THEN monoD] a2 [THEN monoD] a3)\nqed\n\ninstance\n  \"fun\" :: (type, boundlattice) boundlattice\n  apply (intro_classes)\n  apply (auto intro!: bot_lb top_ub simp add: le_fun_conv bot_fun_def top_fun_def)\n  done\n\ninstance\n  \"fun\" :: (type, clattice) clattice\n  apply (intro_classes)\n  apply (auto \n            intro!: Inf_lb Inf_glb Sup_ub Sup_lub inf_eq sup_eq bot_eq top_eq \n            simp add: le_fun_conv Inf_fun_def Sup_fun_def eind_def)\n  done\n\nlemma Inf_mono_fun:\n  assumes a1: \"(\\<And> x \\<bullet> P x \\<turnstile> mono ((f::'c \\<rightarrow> ('a::order) \\<rightarrow> ('b::clattice)) x))\"\n  shows \"mono (\\<lINF> x | P x \\<bullet> f x)\"\n  apply (simp only: mono_def Inf_fun_def)\n  apply (simp add: eind_def eind_comp)\n  apply (auto simp add: eind_norm [of \"(\\<olambda> x \\<bullet> lInf (Collect x))\"])\nproof -\n  fix A::'a and B::'a\n  assume b1: \"A \\<le> B\"\n  show \"(\\<lINF> x | P x \\<bullet> f x A) \\<le> (\\<lINF> x | P x \\<bullet> f x B)\"\n  proof (rule Inf_glb, auto)\n    fix x assume c1: \"P x\"\n    show \"(\\<lINF> x | P x \\<bullet> f x A) \\<le> f x B\"\n      by (rule order_trans [of _ \"f x A\"], rule Inf_lb)\n        (auto simp add: c1 intro!: b1 a1 [THEN monoD])\n  qed\nqed\n\nlemma Sup_mono_fun:\n  assumes a1: \"(\\<And> x \\<bullet> P x \\<turnstile> mono ((f::'c \\<rightarrow> ('a::order) \\<rightarrow> ('b::clattice)) x))\" \n  shows \"mono (\\<lSUP> x | P x \\<bullet> f x)\"\n  apply (simp only: mono_def Sup_fun_def)\n  apply (simp add: eind_def eind_comp)\n  apply (auto simp add: eind_norm [of \"(\\<olambda> x \\<bullet> lSup (Collect x))\"])\nproof -\n  fix A::'a and B::'a\n  assume b1: \"A \\<le> B\"\n  show \"(\\<lSUP> x | P x \\<bullet> f x A) \\<le> (\\<lSUP> x | P x \\<bullet> f x B)\"\n  proof (rule Sup_lub, auto)\n    fix x assume c1: \"P x\"\n    show \"f x A \\<le> (\\<lSUP> x | P x \\<bullet> f x B)\"\n      by (rule order_trans [of _ \"f x B\"])\n        (auto simp add: c1 eind_def intro!: Sup_ub b1 a1 [THEN monoD])\n  qed\nqed\n\ninstance\n  \"fun\" :: (type, dlattice) dlattice\n  by (intro_classes, rule ext, simp add: linf_fun_def lsup_fun_def sup_dist)\n\ninstance\n  \"fun\" :: (type, boollattice) boollattice\n  apply (intro_classes)\n  apply (auto simp add:  \n            lcomp_fun_def linf_fun_def lsup_fun_def bot_fun_def top_fun_def comp_inf comp_sup)\n  done\n\nlemmas lat_fun_defs = \n  linf_fun_def lsup_fun_def Inf_fun_def Sup_fun_def\n  bot_fun_def top_fun_def lcomp_fun_def\n\nlemma [simp]:\n    \"(f \\<linf> g) x = f x \\<linf> g x\"\n    \"(f \\<lsup> g) x = f x \\<lsup> g x\"\n  by (simp_all add: lat_fun_defs)\n\nlemma [simp]:\n  \"(\\<lINF> a | p a \\<bullet> f a) x = (\\<lINF> a | p a \\<bullet> f a x)\"\n  \"(\\<lSUP> a | p a \\<bullet> f a) x = (\\<lSUP> a | p a \\<bullet> f a x)\"\n  by (simp_all add: lat_fun_defs eind_def eind_comp)\n\nlemma [simp]:\n  \"\\<lbot> x = \\<lbot>\"\n  \"\\<ltop> x = \\<ltop>\"\n  by (simp_all add: lat_fun_defs)\n\nlemma [simp]:\n  \"(\\<lcomp> f) x = \\<lcomp> (f x)\"\n  by (simp_all add: lat_fun_defs)\n\ntext {*\n\nThe monotonic lattice functions form a complete sub-lattice.\n\n*}\n\nlemma bot_mh [msimp(wind)]:\n  \"\\<lbot> \\<in> \\<mh>\"\n  by (auto intro!: mhI simp add: bot_fun_def)\n\nlemma top_mh [msimp(wind)]:\n  \"\\<ltop> \\<in> \\<mh>\"\n  by (auto intro!: mhI simp add: top_fun_def)\n\nlemma inf_mh [msimp(wind)]:\n  \"\\<lbrakk> p \\<in> \\<mh>; q \\<in> \\<mh> \\<rbrakk> \\<turnstile> p \\<linf> q \\<in> \\<mh>\"\n  by (auto intro!: mhI dest!: mhD simp add: inf_mono linf_fun_def)\n\nlemma sup_mh [msimp(wind)]:\n  \"\\<lbrakk> p \\<in> \\<mh>; q \\<in> \\<mh> \\<rbrakk> \\<turnstile> (p \\<lsup> q) \\<in> \\<mh>\"\n  by (auto intro!: mhI dest!: mhD simp add: sup_mono lsup_fun_def)\n\nlemma Inf_mh [msimp(wind)]:\n  assumes\n    a1: \"(\\<And> p \\<bullet> p \\<in> CL_P \\<turnstile> p \\<in> \\<mh>)\"\n  shows\n    \"\\<lInf>CL_P \\<in> \\<mh>\"\n  apply (rule mhI)\n  apply (simp add: Inf_fun_def le_fun_def)\n  apply (rule QTInf_dom)\n  apply (auto simp add: mhD [OF a1])\n  done\n\nlemma Sup_mh [msimp(wind)]:\n  assumes\n    a1: \"(\\<And> p \\<bullet> p \\<in> CL_P \\<turnstile> p \\<in> \\<mh>)\"\n  shows\n    \"\\<lSup>CL_P \\<in> \\<mh>\"\n  apply (rule mhI)\n  apply (simp add: Sup_fun_def le_fun_def)\n  apply (rule QTSup_dom)\n  apply (auto simp add: mhD [OF a1])\n  done\n  \nlemma pth_clat: \n    \"\\<^clattice>{:\\<mh>-['A::Lattice_Class.clattice, 'B::Lattice_Class.clattice]:}{:\\<^subord>{:(op \\<le>):}{:\\<mh>:}:}\"\n  apply (rule sub_clattice.subclatticeI' [of \"\\<univ>\"])\n  apply (auto intro!: Inf_mh Sup_mh simp add: Inf_Meet Sup_Join)\n  apply (unfold_locales)\n  apply (auto intro!: exI bot_mh simp add: nempty_conv)\n  done\n\ntext {*\n\nThe bot/top-morphic operators also form complete lattices\n\n*}\n\nlemma bot_mhb:\n    \"\\<lbot> \\<in> \\<mhb>\"\n  apply (rule mhbI)\n  apply (rule bot_mh)\n  apply (simp)\n  done\n\ntext {*\n\nThe top of the bot-morphic lattice returns top everywhere except for bot, where \nit returns bot.\n\n*}\n\ndefinition\n  mk_mhb :: \"(('a::boundlattice) \\<rightarrow> ('b::boundlattice)) \\<rightarrow> (('a::boundlattice) \\<rightarrow> ('b::boundlattice))\"\nwhere\n  mk_mhb_def: \"mk_mhb \\<defs> (\\<olambda> p A \\<bullet> \\<if> A = \\<lbot> \\<then> \\<lbot> \\<else> p A \\<fi>)\"\n\nlemma mk_mhb_mhb:\n  assumes \n    a1: \"p \\<in> \\<mh>\"\n  shows\n    \"mk_mhb p \\<in> \\<mhb>\"\n  apply (unfold mk_mhb_def)\n  apply (rule mhbI)\n  apply (rule mhI) \n  apply (auto simp add: mhD [OF a1] bot_lb bot_min)\n  done\n\nlemma mk_mhb_lb:\n    \"mk_mhb p \\<lle> p\"\n  by (simp add: mk_mhb_def le_fun_def bot_lb)\n\nlemma mk_mhb_glb:\n  assumes \n    a1: \"q \\<in> \\<mhb>\" and\n    a2: \"q \\<lle> p\"\n  shows\n    \"q \\<lle> mk_mhb p\"\n  using a2\n  by (simp add: mk_mhb_def le_fun_def bot_min mhbD [OF a1])\n\ndefinition\n  top_b :: \"('a::boundlattice) \\<rightarrow> ('b::boundlattice)\"\nwhere\n  top_b_def: \"top_b \\<defs> mk_mhb \\<ltop>\"\n\nnotation (xsymbols output)\n  top_b (\"\\<top>\\<^sub>b\")\n\nnotation (zed)\n  top_b (\"\\<ltopb>\")\n\nlemma top_b_mh:\n    \"\\<ltopb> \\<in> \\<mh>\"\n  apply (unfold top_b_def)\n  apply (rule mk_mhb_mhb [THEN mhbDm])\n  apply (rule top_mh)\n  done\n\nlemma top_b_mhb:\n    \"\\<ltopb> \\<in> \\<mhb>\"\n  apply (unfold top_b_def)\n  apply (rule mk_mhb_mhb)\n  apply (rule top_mh)\n  done\n\nlemma top_b_ub:\n  assumes\n    a1: \"p \\<in> \\<mhb>\"\n  shows\n    \"p \\<lle> \\<ltopb>\"\n  apply (unfold top_b_def)\n  apply (rule mk_mhb_glb)\n  apply (auto simp add: a1 top_ub)\n  done\n\nlemma inf_mhb:\n  assumes\n    a1: \"p \\<in> \\<mhb>\" and\n    a2: \"q \\<in> \\<mhb>\"\n  shows\n    \"p \\<linf> q \\<in> \\<mhb>\"\n  apply (rule mhbI)\n  apply (simp add: inf_mh mhbDm a1 a2)\n  apply (simp add: mhbD [OF a1] mhbD [OF a2] lat_bounds)\n  done\n\nlemma Inf_mhb:\n  assumes\n    a1: \"CL_P \\<noteq> \\<emptyset>\" and\n    a2: \"\\<And> p \\<bullet> p \\<in> CL_P \\<turnstile> p \\<in> \\<mhb>\"\n  shows\n    \"\\<lInf> CL_P \\<in> \\<mhb>\"\n  apply (rule mhbI)\n  apply (simp add: Inf_mh [of CL_P] mhbDm [OF a2])\nproof -\n  have \n      \"(\\<lInf>CL_P) \\<lbot> \n      = (\\<lINF> p | p \\<in> CL_P \\<bullet> p \\<lbot>)\"\n    by (simp add: Inf_fun_def)\n  also have \"\\<dots>\n      = (\\<lINF> p | p \\<in> CL_P \\<bullet> \\<lbot>)\"\n    by (mauto(wind) mintro!: arg_cong [of _ _ \"\\<lInf>\"] msimp add: mhbD [OF a2])\n  also from a1 have \n      \"{ p | p \\<in> CL_P \\<bullet> \\<lbot> }\n      = {\\<lbot>}\"\n    by (auto)\n  also have \n      \"\\<lInf>{\\<lbot>}\n      = \\<lbot>\"\n    by (simp add: Inf_singleton)\n  finally show\n      \"(\\<lInf>CL_P) \\<lbot> = \\<lbot>\"\n    by (this)\nqed\n\nlemma sup_mhb:\n  assumes\n    a1: \"p \\<in> \\<mhb>\" and\n    a2: \"q \\<in> \\<mhb>\"\n  shows\n    \"p \\<lsup> q \\<in> \\<mhb>\"\n  apply (rule mhbI)\n  apply (simp add: sup_mh mhbDm a1 a2)\n  apply (simp add: mhbD [OF a1] mhbD [OF a2] lat_bounds)\n  done\n\nlemma Sup_mhb:\n  assumes\n    a1: \"\\<And> p \\<bullet> p \\<in> CL_P \\<turnstile> p \\<in> \\<mhb>\"\n  shows\n    \"\\<lSup> CL_P \\<in> \\<mhb>\"\n  apply (rule mhbI)\n  apply (simp add: Sup_mh mhbDm [OF a1])\nproof -\n  have \n      \"(\\<lSup>CL_P) \\<lbot> \n      = (\\<lSUP> p | p \\<in> CL_P \\<bullet> p \\<lbot>)\"\n    by (simp add: Sup_fun_def)\n  also have \"\\<dots>\n      = (\\<lSUP> p | p \\<in> CL_P \\<bullet> \\<lbot>)\"\n    by (mauto(wind) mintro!: arg_cong [of _ _ \"\\<lSup>\"] msimp add: mhbD [OF a1])\n  also have \"\\<dots>\n      = \\<lbot>\"\n    apply (simp add: Sup_bot_unique)\n    apply (auto)\n    done\n  finally show\n      \"(\\<lSup>CL_P) \\<lbot> = \\<lbot>\"\n    by (this)\nqed\n\ntext {*\n\nThe bottom of the top-morphic lattice returns bottom everywhere, except at top, where it returns top.\n\n*}\n\n\ndefinition\n  mk_mht :: \"(('a::boundlattice) \\<rightarrow> ('b::boundlattice)) \\<rightarrow> (('a::boundlattice) \\<rightarrow> ('b::boundlattice))\"\nwhere\n  mk_mht_def: \"mk_mht \\<defs> (\\<olambda> p A \\<bullet> \\<if> A = \\<ltop> \\<then> \\<ltop> \\<else> p A \\<fi>)\"\n\nlemma mk_mht_mht:\n  assumes \n    a1: \"p \\<in> \\<mh>\"\n  shows\n    \"mk_mht p \\<in> \\<mht>\"\n  apply (unfold mk_mht_def)\n  apply (rule mhtI)\n  apply (rule mhI) \n  apply (auto simp add: mhD [OF a1] top_ub top_max)\n  done\n\nlemma mk_mht_ub:\n    \"p \\<lle> mk_mht p\"\n  by (simp add: mk_mht_def le_fun_def top_ub)\n\nlemma mk_mht_lub:\n  assumes \n    a1: \"q \\<in> \\<mht>\" and\n    a2: \"p \\<lle> q\"\n  shows\n    \"mk_mht p \\<lle> q\"\n  using a2\n  by (simp add: mk_mht_def le_fun_def top_max mhtD [OF a1])\n\ndefinition\n  bot_t :: \"('a::boundlattice) \\<rightarrow> ('b::boundlattice)\"\nwhere\n  bot_t_def: \"bot_t \\<defs> mk_mht \\<lbot>\"\n\nnotation (xsymbols output)\n  bot_t (\"\\<bottom>\\<^sub>t\")\n\nnotation (zed)\n  bot_t (\"\\<lbott>\")\n\nlemma bot_t_mh:\n    \"\\<lbott> \\<in> \\<mh>\"\n  apply (unfold bot_t_def)\n  apply (rule mk_mht_mht [THEN mhtDm])\n  apply (rule bot_mh)\n  done\n\nlemma bot_t_mht:\n    \"\\<lbott> \\<in> \\<mht>\"\n  apply (unfold bot_t_def)\n  apply (rule mk_mht_mht)\n  apply (rule bot_mh)\n  done\n\nlemma bot_t_lb:\n  assumes\n    a1: \"p \\<in> \\<mht>\"\n  shows\n    \"\\<lbott> \\<lle> p\"\n  apply (unfold bot_t_def)\n  apply (rule mk_mht_lub)\n  apply (auto simp add: a1 bot_lb)\n  done\n\nlemma top_mht:\n    \"\\<ltop> \\<in> \\<mht>\"\n  apply (rule mhtI)\n  apply (rule top_mh)\n  apply (simp)\n  done\n\nlemma inf_mht:\n  assumes\n    a1: \"p \\<in> \\<mht>\" and\n    a2: \"q \\<in> \\<mht>\"\n  shows\n    \"p \\<linf> q \\<in> \\<mht>\"\n  apply (rule mhtI)\n  apply (simp add: inf_mh mhtDm a1 a2)\n  apply (simp add: mhtD [OF a1] mhtD [OF a2] lat_bounds)\n  done\n\nlemma sup_mht:\n  assumes\n    a1: \"p \\<in> \\<mht>\" and\n    a2: \"q \\<in> \\<mht>\"\n  shows\n    \"p \\<lsup> q \\<in> \\<mht>\"\n  apply (rule mhtI)\n  apply (simp add: sup_mh mhtDm a1 a2)\n  apply (simp add: mhtD [OF a1] mhtD [OF a2] lat_bounds)\n  done\n\nlemma Inf_mht:\n  assumes\n    a1: \"\\<And> p \\<bullet> p \\<in> CL_P \\<turnstile> p \\<in> \\<mht>\"\n  shows\n    \"\\<lInf> CL_P \\<in> \\<mht>\"\n  apply (rule mhtI)\n  apply (simp add: Inf_mh mhtDm [OF a1])\nproof -\n  have \n      \"(\\<lInf>CL_P) \\<ltop> \n      = (\\<lINF> p | p \\<in> CL_P \\<bullet> p \\<ltop>)\"\n    by (simp add: Inf_fun_def)\n  also have \"\\<dots>\n      = (\\<lINF> p | p \\<in> CL_P \\<bullet> \\<ltop>)\"\n    by (mauto(wind) mintro!: arg_cong [of _ _ \"\\<lInf>\"] msimp add: mhtD [OF a1])\n  also have \"\\<dots>\n      = \\<ltop>\"\n    apply (simp add: Inf_top_unique)\n    apply (auto)\n    done\n  finally show\n      \"(\\<lInf>CL_P) \\<ltop> = \\<ltop>\"\n    by (this)\nqed\n\nlemma Sup_mht:\n  assumes\n    a1: \"CL_P \\<noteq> \\<emptyset>\" and\n    a2: \"\\<And> p \\<bullet> p \\<in> CL_P \\<turnstile> p \\<in> \\<mht>\"\n  shows\n    \"\\<lSup> CL_P \\<in> \\<mht>\"\n  apply (rule mhtI)\n  apply (simp add: Sup_mh [of CL_P] mhtDm [OF a2])\nproof -\n  have \n      \"(\\<lSup>CL_P) \\<ltop> \n      = (\\<lSUP> p | p \\<in> CL_P \\<bullet> p \\<ltop>)\"\n    by (simp add: Sup_fun_def)\n  also have \"\\<dots>\n      = (\\<lSUP> p | p \\<in> CL_P \\<bullet> \\<ltop>)\"\n    by (mauto(wind) mintro!: arg_cong [of _ _ \"\\<lSup>\"] msimp add: mhtD [OF a2])\n  also from a1 have \n      \"{ p | p \\<in> CL_P \\<bullet> \\<ltop> }\n      = {\\<ltop>}\"\n    by (auto)\n  also have \n      \"\\<lSup>{\\<ltop>}\n      = \\<ltop>\"\n    by (simp add: Sup_singleton)\n  finally show\n      \"(\\<lSup>CL_P) \\<ltop> = \\<ltop>\"\n    by (this)\nqed\n\ntext {*\n\nThe bot-morphic top and top-morphic bottom are also top-morphic and bot-morphic respectively.\n\n*}\n\nlemma top_b_mht:\n  assumes\n    a1: \"\\<lbot>-['A] \\<noteq> \\<ltop>-['A]\"\n  shows\n    \"\\<ltopb> \\<in> \\<mht>-['A::boundlattice, 'B::boundlattice]\"\n  apply (unfold top_b_def mk_mhb_def)\n  apply (rule mhtI)\n  apply (rule mhI)\n  apply (auto simp add: bot_min top_ub a1 a1 [symmetric])\n  done\n\nlemma bot_t_mhb:\n  assumes\n    a1: \"\\<lbot>-['A] \\<noteq> \\<ltop>-['A]\"\n  shows\n    \"\\<lbott> \\<in> \\<mhb>-['A::boundlattice, 'B::boundlattice]\"\n  apply (unfold bot_t_def mk_mht_def)\n  apply (rule mhbI)\n  apply (rule mhI)\n  apply (auto simp add: top_max top_ub a1 a1 [symmetric])\n  done\n\ntext {* \n\nThe inf/sup-morphic operators form (complete) semi-lattices in the monotonic operators.\n\n*}\n\nlemma bot_mhs:\n    \"\\<lbot> \\<in> \\<mhs>\"\n  apply (rule mhsI)\n  apply (simp add: lat_bounds)\n  done\n\nlemma top_mhs:\n    \"\\<ltop> \\<in> \\<mhs>\"\n  apply (rule mhsI)\n  apply (simp add: lat_bounds)\n  done\n\nlemma sup_mhs:\n  assumes\n    a1: \"p \\<in> \\<mhs>\" and\n    a2: \"q \\<in> \\<mhs>\"\n  shows\n    \"p \\<lsup> q \\<in> \\<mhs>\"\n  apply (rule mhsI)\n  apply (simp add: mhsD [OF a1] mhsD [OF a2] lat_com_assoc)\n  done\n\nlemma Sup_mhs:\n  assumes\n    a1: \"\\<And> p \\<bullet> p \\<in> CL_A \\<turnstile> p \\<in> \\<mhs>\"\n  shows\n    \"\\<lSup> CL_A \\<in> \\<mhs>\"\nproof (rule mhsI)\n  fix A B\n  have \n      \"(\\<lSup>CL_A) (A \\<lsup> B)\n      = (\\<lSUP> p | p \\<in> CL_A \\<bullet> p (A \\<lsup> B))\"\n    by (simp add: Sup_fun_def)\n  also have \"\\<dots>\n      = (\\<lSUP> p | p \\<in> CL_A \\<bullet> p A \\<lsup> p B)\"\n    by (mauto(wind) mintro!: arg_cong [of _ _ \"\\<lSup>\"] msimp add: mhsD [OF a1])\n  also have \"\\<dots> \n       = (\\<lSup> ({ p | p \\<in> CL_A \\<bullet> p A } \\<union> { p | p \\<in> CL_A \\<bullet> p B }))\"\n    by (simp add: Sup_sup')\n  also have \"\\<dots> \n       = (\\<lSup>CL_A) A \\<lsup> (\\<lSup>CL_A) B\"\n    by (simp add: Sup_fun_def Sup_sup)\n  finally show \n      \"(\\<lSup>CL_A) (A \\<lsup> B) = (\\<lSup>CL_A) A \\<lsup> (\\<lSup>CL_A) B\"\n    by (this)\nqed\n\ntext {*\n\nThe inf of sup-morphic operators is the sup of the sup-morphic lower bounds.\n\n*}\n\ndefinition\n  gslb :: \"(('a::lattice) \\<rightarrow> ('b::clattice)) \\<rightarrow> ('a \\<rightarrow> 'b)\"\nwhere\n  gslb_def: \"gslb \\<defs> (\\<olambda> p \\<bullet> (\\<lSUP> t | t \\<in> \\<mhs> \\<and> t \\<lle> p))\"\n\nlemma gslb_mhs:\n    \"gslb p \\<in> \\<mhs>\"\n  apply (simp add: gslb_def)\n  apply (rule Sup_mhs)\n  apply (simp)\n  done\n\nlemma gslb_lb:\n    \"gslb p \\<lle> p\"\n  apply (unfold gslb_def)\n  apply (rule Sup_lub)\n  apply (simp)\n  done\n\nlemma gslb_gslb:\n  assumes\n    a1: \"q \\<in> \\<mhs>\" and\n    a2: \"q \\<lle> p\"\n  shows\n    \"q \\<lle> gslb p\"\n  apply (unfold gslb_def)\n  apply (rule Sup_ub)\n  apply (simp add: a1 a2)\n  done\n\ndefinition\n  inf_s :: \"[('a::lattice) \\<rightarrow> ('b::clattice), 'a \\<rightarrow> 'b] \\<rightarrow> ('a \\<rightarrow> 'b)\"\nwhere\n  inf_s_def: \"inf_s \\<defs> (\\<olambda> p q \\<bullet> gslb (p \\<linf> q))\"\n\nnotation (xsymbols output)\n  inf_s (infixl \"\\<sqinter>\\<^sub>s\" 70)\n\nnotation (zed)\n  inf_s (infixl \"\\<linfs>\" 70)\n\nlemma inf_s_mhs:\n  assumes\n    a1: \"p \\<in> \\<mhs>\" and\n    a2: \"q \\<in> \\<mhs>\"\n  shows\n    \"p \\<linfs> q \\<in> \\<mhs>\"\n  apply (simp add: inf_s_def)\n  apply (rule gslb_mhs)\n  done\n\nlemma inf_s_lb1:\n    \"p \\<linfs> q \\<lle> p\"\n  apply (unfold inf_s_def)\n  apply (rule order_trans [OF gslb_lb inf_lb1])\n  done\n\nlemma inf_s_lb2:\n    \"p \\<linfs> q \\<lle> q\"\n  apply (unfold inf_s_def)\n  apply (rule order_trans [OF gslb_lb inf_lb2])\n  done\n\nlemma inf_s_gslb:\n  assumes\n    a1: \"t \\<in> \\<mhs>\" and\n    a2: \"t \\<lle> p\" and\n    a3: \"t \\<lle> q\"\n  shows\n    \"t \\<lle> p \\<linfs> q\"\n  apply (unfold inf_s_def)\n  apply (rule gslb_gslb)\n  apply (rule a1)\n  apply (rule inf_glb [OF a2 a3])\n  done\n\ndefinition\n  Inf_s :: \"(('a::clattice) \\<rightarrow> ('b::clattice)) set \\<rightarrow> ('a \\<rightarrow> 'b)\"\nwhere\n  Inf_s_def: \"Inf_s \\<defs> (\\<olambda> CL_P \\<bullet> gslb (\\<lInf> CL_P))\"\n\nnotation (xsymbols output)\n  Inf_s (\"\\<Sqinter>\\<^sub>s\")\n\nnotation (zed)\n  Inf_s (\"\\<lInfs>\")\n\nlemma Inf_s_mhs:\n  assumes\n    a1: \"\\<And> p \\<bullet> p \\<in> CL_P \\<turnstile> p \\<in> \\<mhs>\"\n  shows\n    \"\\<lInfs> CL_P \\<in> \\<mhs>\"\n  apply (unfold Inf_s_def)\n  apply (rule gslb_mhs)\n  done\n\nlemma Inf_s_lb:\n  assumes\n    a1: \"p \\<in> CL_P\"\n  shows\n    \"\\<lInfs> CL_P \\<lle> p\"\n  apply (unfold Inf_s_def)\n  apply (rule order_trans [OF gslb_lb Inf_lb])\n  apply (rule a1)\n  done\n\nlemma Inf_s_gslb:\n  assumes\n    a1: \"t \\<in> \\<mhs>\" and\n    a2: \"\\<And> p \\<bullet> p \\<in> CL_P \\<turnstile> t \\<lle> p\"\n  shows\n    \"t \\<lle> \\<lInfs> CL_P\"\n  apply (unfold Inf_s_def)\n  apply (rule gslb_gslb)\n  apply (rule a1)\n  apply (rule Inf_glb)\n  apply (rule a2)\n  apply (assumption)\n  done\n\nlemma bot_mhi:\n    \"\\<lbot> \\<in> \\<mhi>\"\n  apply (rule mhiI)\n  apply (simp add: lat_bounds)\n  done\n\nlemma top_mhi:\n    \"\\<ltop> \\<in> \\<mhi>\"\n  apply (rule mhiI)\n  apply (simp add: lat_bounds)\n  done\n\nlemma inf_mhi:\n  assumes\n    a1: \"p \\<in> \\<mhi>\" and\n    a2: \"q \\<in> \\<mhi>\"\n  shows\n    \"p \\<linf> q \\<in> \\<mhi>\"\n  apply (rule mhiI)\n  apply (simp add: mhiD [OF a1] mhiD [OF a2] lat_com_assoc)\n  done\n\nlemma Inf_mhi:\n  assumes\n    a1: \"\\<And> p \\<bullet> p \\<in> CL_A \\<turnstile> p \\<in> \\<mhi>\"\n  shows\n    \"\\<lInf> CL_A \\<in> \\<mhi>\"\nproof (rule mhiI)\n  fix A B\n  have \n      \"(\\<lInf>CL_A) (A \\<linf> B)\n      = (\\<lINF> p | p \\<in> CL_A \\<bullet> p (A \\<linf> B))\"\n    by (simp add: Inf_fun_def)\n  also have \"\\<dots>\n      = (\\<lINF> p | p \\<in> CL_A \\<bullet> p A \\<linf> p B)\"\n    by (mauto(wind) mintro!: arg_cong [of _ _ \"\\<lInf>\"] msimp add: mhiD [OF a1])\n  also have \"\\<dots> \n       = (\\<lInf> ({ p | p \\<in> CL_A \\<bullet> p A } \\<union> { p | p \\<in> CL_A \\<bullet> p B }))\"\n    by (simp add: Inf_inf')\n  also have \"\\<dots> \n       = (\\<lInf>CL_A) A \\<linf> (\\<lInf>CL_A) B\"\n    by (simp add: Inf_fun_def Inf_inf)\n  finally show \n      \"(\\<lInf>CL_A) (A \\<linf> B) = (\\<lInf>CL_A) A \\<linf> (\\<lInf>CL_A) B\"\n    by (this)\nqed\n\ntext {*\n\nThe sup of inf-morphic operators is the inf of the inf-morphic upper bounds.\n\n*}\n\ndefinition\n  liub :: \"(('a::lattice) \\<rightarrow> ('b::clattice)) \\<rightarrow> ('a \\<rightarrow> 'b)\"\nwhere\n  liub_def: \"liub \\<defs> (\\<olambda> p \\<bullet> (\\<lINF> t | t \\<in> \\<mhi> \\<and> p \\<lle> t))\"\n\nlemma liub_mhi:\n    \"liub p \\<in> \\<mhi>\"\n  apply (simp add: liub_def)\n  apply (rule Inf_mhi)\n  apply (simp)\n  done\n\nlemma liub_ub:\n    \"p \\<lle> liub p\"\n  apply (unfold liub_def)\n  apply (rule Inf_glb)\n  apply (simp)\n  done\n\nlemma liub_liub:\n  assumes\n    a1: \"q \\<in> \\<mhi>\" and\n    a2: \"p \\<lle> q\"\n  shows\n    \"liub p \\<lle> q\"\n  apply (unfold liub_def)\n  apply (rule Inf_lb)\n  apply (simp add: a1 a2)\n  done\n\ndefinition\n  sup_i :: \"[('a::lattice) \\<rightarrow> ('b::clattice), 'a \\<rightarrow> 'b] \\<rightarrow> ('a \\<rightarrow> 'b)\"\nwhere\n  sup_i_def: \"sup_i \\<defs> (\\<olambda> p q \\<bullet> liub (p \\<lsup> q))\"\n\nnotation (xsymbols output)\n  sup_i (infixl \"\\<squnion>\\<^sub>i\" 65)\n\nnotation (zed)\n  sup_i (infixl \"\\<lsupi>\" 65)\n\nlemma sup_i_mhi:\n  assumes\n    a1: \"p \\<in> \\<mhi>\" and\n    a2: \"q \\<in> \\<mhi>\"\n  shows\n    \"p \\<lsupi> q \\<in> \\<mhi>\"\n  apply (simp add: sup_i_def)\n  apply (rule liub_mhi)\n  done\n\nlemma sup_i_ub1:\n    \"p \\<lle> p \\<lsupi> q\"\n  apply (unfold sup_i_def)\n  apply (rule order_trans [OF sup_ub1 liub_ub])\n  done\n\nlemma sup_i_ub2:\n    \"q \\<lle> p \\<lsupi> q\"\n  apply (unfold sup_i_def)\n  apply (rule order_trans [OF sup_ub2 liub_ub])\n  done\n\nlemma sup_i_liub:\n  assumes\n    a1: \"t \\<in> \\<mhi>\" and\n    a2: \"p \\<lle> t\" and\n    a3: \"q \\<lle> t\"\n  shows\n    \"p \\<lsupi> q \\<lle> t\"\n  apply (unfold sup_i_def)\n  apply (rule liub_liub)\n  apply (rule a1)\n  apply (rule sup_lub [OF a2 a3])\n  done\n\ndefinition\n  Sup_i :: \"(('a::clattice) \\<rightarrow> ('b::clattice)) set \\<rightarrow> ('a \\<rightarrow> 'b)\"\nwhere\n  Sup_i_def: \"Sup_i \\<defs> (\\<olambda> CL_P \\<bullet> liub (\\<lSup> CL_P))\"\n\nnotation (xsymbols output)\n  Sup_i (\"\\<Squnion>\\<^sub>i\")\n\nnotation (zed)\n  Sup_i (\"\\<lSupi>\")\n\nlemma Sup_i_mhs:\n  assumes\n    a1: \"\\<And> p \\<bullet> p \\<in> CL_P \\<turnstile> p \\<in> \\<mhi>\"\n  shows\n    \"\\<lSupi> CL_P \\<in> \\<mhi>\"\n  apply (unfold Sup_i_def)\n  apply (rule liub_mhi)\n  done\n\nlemma Sup_i_lb:\n  assumes\n    a1: \"p \\<in> CL_P\"\n  shows\n    \"p \\<lle> \\<lSupi> CL_P\"\n  apply (unfold Sup_i_def)\n  apply (rule order_trans [OF Sup_ub liub_ub])\n  apply (rule a1)\n  done\n\nlemma Sup_i_liub:\n  assumes\n    a1: \"t \\<in> \\<mhi>\" and\n    a2: \"\\<And> p \\<bullet> p \\<in> CL_P \\<turnstile> p \\<lle> t\"\n  shows\n    \"\\<lSupi> CL_P \\<lle> t\"\n  apply (unfold Sup_i_def)\n  apply (rule liub_liub)\n  apply (rule a1)\n  apply (rule Sup_lub)\n  apply (rule a2)\n  apply (assumption)\n  done\n\ntext {* \n\nThe Inf/Sup-morphic operators form (complete) semi-lattices in the monotonic operators.\n\n*}\n\nlemma bot_mhS:\n    \"\\<lbot> \\<in> \\<mhS>\"\n  apply (rule mhSI)\n  apply (simp add: lat_bounds nempty_conv Sup_singleton eind_def)\n  done\n\nlemma top_mhS:\n    \"\\<ltop> \\<in> \\<mhS>\"\n  apply (rule mhSI)\n  apply (simp add: lat_bounds nempty_conv Sup_singleton eind_def)\n  done\n\nlemma sup_mhS:\n  assumes\n    a1: \"p \\<in> \\<mhS>\" and\n    a2: \"q \\<in> \\<mhS>\"\n  shows\n    \"p \\<lsup> q \\<in> \\<mhS>\"\n  apply (rule mhSI)\n  apply (simp add: mhSD [OF a1] mhSD [OF a2] lat_com_assoc Sup_sup Sup_sup')\n  done\n\nlemma Sup_mhS:\n  assumes\n    a1: \"\\<And> p \\<bullet> p \\<in> CL_A \\<turnstile> p \\<in> \\<mhS>\"\n  shows\n    \"\\<lSup> CL_A \\<in> \\<mhS>\"\nproof (rule mhSI)\n  fix CL_X::\"'a set\"\n  assume\n    b1: \"CL_X \\<noteq> \\<emptyset>\"\n  have \n      \"(\\<lSup>CL_A) (\\<lSup>CL_X)\n      = (\\<lSUP> p | p \\<in> CL_A \\<bullet> p (\\<lSup>CL_X))\"\n    by (simp add: Sup_fun_def)\n  also have \"\\<dots>\n      = (\\<lSUP> p | p \\<in> CL_A \\<bullet> (\\<lSUP> x | x \\<in> CL_X \\<bullet> p x))\"\n    by (mauto(wind) mintro!: arg_cong [of _ _ \"\\<lSup>\"] msimp add: mhSD [OF a1] b1)\n  also have \"\\<dots> \n       = (\\<lSUP> x | x \\<in> CL_X \\<bullet> (\\<lSUP> p | p \\<in> CL_A \\<bullet> p x))\"\n    apply (simp add: Sup_Sup)\n    apply (mauto(wind) mintro!: arg_cong [of _ _ \"\\<lSup>\"])\n    apply (auto simp add: eind_def)\n    done\n  also have \"\\<dots> \n       = (\\<lSUP> x | x \\<in> CL_X \\<bullet> (\\<lSup>CL_A) x)\"\n    by (simp add: Sup_fun_def eind_def)\n  finally show \n      \"(\\<lSup>CL_A) (\\<lSup>CL_X) = (\\<lSUP> x | x \\<in> CL_X \\<bullet> (\\<lSup>CL_A) x)\"\n    by (this)\nqed\n\ntext {*\n\nThe inf of Sup-morphic operators is the sup of the Sup-morphic lower bounds.\n\n*}\n\ndefinition\n  gSlb :: \"(('a::clattice) \\<rightarrow> ('b::clattice)) \\<rightarrow> ('a \\<rightarrow> 'b)\"\nwhere\n  gSlb_def: \"gSlb \\<defs> (\\<olambda> p \\<bullet> (\\<lSUP> t | t \\<in> \\<mhS> \\<and> t \\<lle> p))\"\n\nlemma gSlb_mhS:\n    \"gSlb p \\<in> \\<mhS>\"\n  apply (simp add: gSlb_def)\n  apply (rule Sup_mhS)\n  apply (simp)\n  done\n\nlemma gSlb_lb:\n    \"gSlb p \\<lle> p\"\n  apply (unfold gSlb_def)\n  apply (rule Sup_lub)\n  apply (simp)\n  done\n\nlemma gSlb_gSlb:\n  assumes\n    a1: \"q \\<in> \\<mhS>\" and\n    a2: \"q \\<lle> p\"\n  shows\n    \"q \\<lle> gSlb p\"\n  apply (unfold gSlb_def)\n  apply (rule Sup_ub)\n  apply (simp add: a1 a2)\n  done\n\ndefinition\n  inf_S :: \"[('a::clattice) \\<rightarrow> ('b::clattice), 'a \\<rightarrow> 'b] \\<rightarrow> ('a \\<rightarrow> 'b)\"\nwhere\n  inf_S_def: \"inf_S \\<defs> (\\<olambda> p q \\<bullet> gSlb (p \\<linf> q))\"\n\nnotation (xsymbols output)\n  inf_S (infixl \"\\<sqinter>\\<^sub>S\" 70)\n\nnotation (zed)\n  inf_S (infixl \"\\<linfS>\" 70)\n\nlemma inf_S_mhS:\n  assumes\n    a1: \"p \\<in> \\<mhS>\" and\n    a2: \"q \\<in> \\<mhS>\"\n  shows\n    \"p \\<linfS> q \\<in> \\<mhS>\"\n  apply (simp add: inf_S_def)\n  apply (rule gSlb_mhS)\n  done\n\nlemma inf_S_lb1:\n    \"p \\<linfS> q \\<lle> p\"\n  apply (unfold inf_S_def)\n  apply (rule order_trans [OF gSlb_lb inf_lb1])\n  done\n\nlemma inf_S_lb2:\n    \"p \\<linfS> q \\<lle> q\"\n  apply (unfold inf_S_def)\n  apply (rule order_trans [OF gSlb_lb inf_lb2])\n  done\n\nlemma inf_S_gSlb:\n  assumes\n    a1: \"t \\<in> \\<mhS>\" and\n    a2: \"t \\<lle> p\" and\n    a3: \"t \\<lle> q\"\n  shows\n    \"t \\<lle> p \\<linfS> q\"\n  apply (unfold inf_S_def)\n  apply (rule gSlb_gSlb)\n  apply (rule a1)\n  apply (rule inf_glb [OF a2 a3])\n  done\n\ndefinition\n  Inf_S :: \"(('a::clattice) \\<rightarrow> ('b::clattice)) set \\<rightarrow> ('a \\<rightarrow> 'b)\"\nwhere\n  Inf_S_def: \"Inf_S \\<defs> (\\<olambda> CL_P \\<bullet> gSlb (\\<lInf> CL_P))\"\n\nnotation (xsymbols output)\n  Inf_S (\"\\<Sqinter>\\<^sub>S\")\n\nnotation (zed)\n  Inf_S (\"\\<lInfS>\")\n\nlemma Inf_S_mhS:\n  assumes\n    a1: \"\\<And> p \\<bullet> p \\<in> CL_P \\<turnstile> p \\<in> \\<mhS>\"\n  shows\n    \"\\<lInfS> CL_P \\<in> \\<mhS>\"\n  apply (unfold Inf_S_def)\n  apply (rule gSlb_mhS)\n  done\n\nlemma Inf_S_lb:\n  assumes\n    a1: \"p \\<in> CL_P\"\n  shows\n    \"\\<lInfS> CL_P \\<lle> p\"\n  apply (unfold Inf_S_def)\n  apply (rule order_trans [OF gSlb_lb Inf_lb])\n  apply (rule a1)\n  done\n\nlemma Inf_S_gSlb:\n  assumes\n    a1: \"t \\<in> \\<mhS>\" and\n    a2: \"\\<And> p \\<bullet> p \\<in> CL_P \\<turnstile> t \\<lle> p\"\n  shows\n    \"t \\<lle> \\<lInfS> CL_P\"\n  apply (unfold Inf_S_def)\n  apply (rule gSlb_gSlb)\n  apply (rule a1)\n  apply (rule Inf_glb)\n  apply (rule a2)\n  apply (assumption)\n  done\n\nlemma bot_mhI:\n    \"\\<lbot> \\<in> \\<mhI>\"\n  apply (rule mhII)\n  apply (simp add: lat_bounds nempty_conv Inf_singleton eind_def)\n  done\n\nlemma top_mhI:\n    \"\\<ltop> \\<in> \\<mhI>\"\n  apply (rule mhII)\n  apply (simp add: lat_bounds nempty_conv Inf_singleton eind_def)\n  done\n\nlemma inf_mhI:\n  assumes\n    a1: \"p \\<in> \\<mhI>\" and\n    a2: \"q \\<in> \\<mhI>\"\n  shows\n    \"p \\<linf> q \\<in> \\<mhI>\"\n  apply (rule mhII)\n  apply (simp add: mhID [OF a1] mhID [OF a2] lat_com_assoc Inf_inf Inf_inf')\n  done\n\nlemma Inf_mhI:\n  assumes\n    a1: \"\\<And> p \\<bullet> p \\<in> CL_A \\<turnstile> p \\<in> \\<mhI>\"\n  shows\n    \"\\<lInf> CL_A \\<in> \\<mhI>\"\nproof (rule mhII)\n  fix CL_X::\"'a set\"\n  assume\n    b1: \"CL_X \\<noteq> \\<emptyset>\"\n  have \n      \"(\\<lInf>CL_A) (\\<lInf>CL_X)\n      = (\\<lINF> p | p \\<in> CL_A \\<bullet> p (\\<lInf>CL_X))\"\n    by (simp add: Inf_fun_def)\n  also have \"\\<dots>\n      = (\\<lINF> p | p \\<in> CL_A \\<bullet> (\\<lINF> x | x \\<in> CL_X \\<bullet> p x))\"\n    by (mauto(wind) mintro!: arg_cong [of _ _ \"\\<lInf>\"] msimp add: mhID [OF a1] b1)\n  also have \"\\<dots> \n       = (\\<lINF> x | x \\<in> CL_X \\<bullet> (\\<lINF> p | p \\<in> CL_A \\<bullet> p x))\"\n    apply (simp add: Inf_Inf)\n    apply (mauto(wind) mintro!: arg_cong [of _ _ \"\\<lInf>\"])\n    apply (auto simp add: eind_def)\n    done\n  also have \"\\<dots> \n       = (\\<lINF> x | x \\<in> CL_X \\<bullet> (\\<lInf>CL_A) x)\"\n    by (simp add: Inf_fun_def)\n  finally show \n      \"(\\<lInf>CL_A) (\\<lInf>CL_X) = (\\<lINF> x | x \\<in> CL_X \\<bullet> (\\<lInf>CL_A) x)\"\n    by (this)\nqed\n\ntext {*\n\nThe sup of Inf-morphic operators is the inf of the Inf-morphic upper bounds.\n\n*}\n\ndefinition\n  lIub :: \"(('a::clattice) \\<rightarrow> ('b::clattice)) \\<rightarrow> ('a \\<rightarrow> 'b)\"\nwhere\n  lIub_def: \"lIub \\<defs> (\\<olambda> p \\<bullet> (\\<lINF> t | t \\<in> \\<mhI> \\<and> p \\<lle> t))\"\n\nlemma lIub_mhI:\n    \"lIub p \\<in> \\<mhI>\"\n  apply (simp add: lIub_def)\n  apply (rule Inf_mhI)\n  apply (simp)\n  done\n\nlemma lIub_ub:\n    \"p \\<lle> lIub p\"\n  apply (unfold lIub_def)\n  apply (rule Inf_glb)\n  apply (simp)\n  done\n\nlemma lIub_lIub:\n  assumes\n    a1: \"q \\<in> \\<mhI>\" and\n    a2: \"p \\<lle> q\"\n  shows\n    \"lIub p \\<lle> q\"\n  apply (unfold lIub_def)\n  apply (rule Inf_lb)\n  apply (simp add: a1 a2)\n  done\n\ndefinition\n  sup_I :: \"[('a::clattice) \\<rightarrow> ('b::clattice), 'a \\<rightarrow> 'b] \\<rightarrow> ('a \\<rightarrow> 'b)\"\nwhere\n  sup_I_def: \"sup_I \\<defs> (\\<olambda> p q \\<bullet> lIub (p \\<lsup> q))\"\n\nnotation (xsymbols output)\n  sup_I (infixl \"\\<squnion>\\<^sub>I\" 65)\n\nnotation (zed)\n  sup_I (infixl \"\\<lsupI>\" 65)\n\nlemma sup_I_mhI:\n  assumes\n    a1: \"p \\<in> \\<mhI>\" and\n    a2: \"q \\<in> \\<mhI>\"\n  shows\n    \"p \\<lsupI> q \\<in> \\<mhI>\"\n  apply (simp add: sup_I_def)\n  apply (rule lIub_mhI)\n  done\n\nlemma sup_I_ub1:\n    \"p \\<lle> p \\<lsupI> q\"\n  apply (unfold sup_I_def)\n  apply (rule order_trans [OF sup_ub1 lIub_ub])\n  done\n\nlemma sup_I_ub2:\n    \"q \\<lle> p \\<lsupI> q\"\n  apply (unfold sup_I_def)\n  apply (rule order_trans [OF sup_ub2 lIub_ub])\n  done\n\nlemma sup_I_lIub:\n  assumes\n    a1: \"t \\<in> \\<mhI>\" and\n    a2: \"p \\<lle> t\" and\n    a3: \"q \\<lle> t\"\n  shows\n    \"p \\<lsupI> q \\<lle> t\"\n  apply (unfold sup_I_def)\n  apply (rule lIub_lIub)\n  apply (rule a1)\n  apply (rule sup_lub [OF a2 a3])\n  done\n\ndefinition\n  Sup_I :: \"(('a::clattice) \\<rightarrow> ('b::clattice)) set \\<rightarrow> ('a \\<rightarrow> 'b)\"\nwhere\n  Sup_I_def: \"Sup_I \\<defs> (\\<olambda> CL_P \\<bullet> lIub (\\<lSup> CL_P))\"\n\nnotation (xsymbols output)\n  Sup_I (\"\\<Squnion>\\<^sub>I\")\n\nnotation (zed)\n  Sup_I (\"\\<lSupI>\")\n\nlemma Sup_I_mhI:\n  assumes\n    a1: \"\\<And> p \\<bullet> p \\<in> CL_P \\<turnstile> p \\<in> \\<mhI>\"\n  shows\n    \"\\<lSupI> CL_P \\<in> \\<mhI>\"\n  apply (unfold Sup_I_def)\n  apply (rule lIub_mhI)\n  done\n\nlemma Sup_I_lb:\n  assumes\n    a1: \"p \\<in> CL_P\"\n  shows\n    \"p \\<lle> \\<lSupI> CL_P\"\n  apply (unfold Sup_I_def)\n  apply (rule order_trans [OF Sup_ub lIub_ub])\n  apply (rule a1)\n  done\n\nlemma Sup_I_lIub:\n  assumes\n    a1: \"t \\<in> \\<mhI>\" and\n    a2: \"\\<And> p \\<bullet> p \\<in> CL_P \\<turnstile> p \\<lle> t\"\n  shows\n    \"\\<lSupI> CL_P \\<lle> t\"\n  apply (unfold Sup_I_def)\n  apply (rule lIub_lIub)\n  apply (rule a1)\n  apply (rule Sup_lub)\n  apply (rule a2)\n  apply (assumption)\n  done\n\ntext {* \n\nThe top-Inf/bot-Sup-morphic operators form (complete) semi-lattices in the monotonic operators.\n\n*}\n\nlemma bot_mhbS:\n    \"\\<lbot> \\<in> \\<mhbS>\"\n  apply (rule mhbSI)\n  apply (simp add: lat_bounds nempty_conv Sup_singleton)\n  apply (intro allI bot_eq Sup_lub)\n  apply (auto simp add: bot_lb)\n  done\n\nlemma sup_mhbS:\n  assumes\n    a1: \"p \\<in> \\<mhbS>\" and\n    a2: \"q \\<in> \\<mhbS>\"\n  shows\n    \"p \\<lsup> q \\<in> \\<mhbS>\"\n  apply (rule mhbSI)\n  apply (simp add: mhbSD [OF a1] mhbSD [OF a2] lat_com_assoc Sup_sup Sup_sup')\n  done\n\nlemma Sup_mhbS:\n  assumes\n    a1: \"\\<And> p \\<bullet> p \\<in> CL_A \\<turnstile> p \\<in> \\<mhbS>\"\n  shows\n    \"\\<lSup> CL_A \\<in> \\<mhbS>\"\nproof (rule mhbSI)\n  fix CL_X::\"'a set\"\n  have \n      \"(\\<lSup>CL_A) (\\<lSup>CL_X)\n      = (\\<lSUP> p | p \\<in> CL_A \\<bullet> p (\\<lSup>CL_X))\"\n    by (simp add: Sup_fun_def)\n  also have \"\\<dots>\n      = (\\<lSUP> p | p \\<in> CL_A \\<bullet> (\\<lSUP> x | x \\<in> CL_X \\<bullet> p x))\"\n    by (mauto(wind) mintro!: arg_cong [of _ _ \"\\<lSup>\"] msimp add: mhbSD [OF a1])\n  also have \"\\<dots> \n       = (\\<lSUP> x | x \\<in> CL_X \\<bullet> (\\<lSUP> p | p \\<in> CL_A \\<bullet> p x))\"\n    apply (simp add: Sup_Sup)\n    apply (mauto(wind) mintro!: arg_cong [of _ _ \"\\<lSup>\"])\n    apply (auto simp add: eind_def)\n    done\n  also have \"\\<dots> \n       = (\\<lSUP> x | x \\<in> CL_X \\<bullet> (\\<lSup>CL_A) x)\"\n    by (simp add: Sup_fun_def)\n  finally show \n      \"(\\<lSup>CL_A) (\\<lSup>CL_X) = (\\<lSUP> x | x \\<in> CL_X \\<bullet> (\\<lSup>CL_A) x)\"\n    by (this)\nqed\n\ntext {*\n\nThe top/inf/Inf of bot-Sup-morphic operators is the sup of the bot-Sup-morphic lower bounds.\n\n*}\n\ndefinition\n  gbSlb :: \"(('a::clattice) \\<rightarrow> ('b::clattice)) \\<rightarrow> ('a \\<rightarrow> 'b)\"\nwhere\n  gbSlb_def: \"gbSlb \\<defs> (\\<olambda> p \\<bullet> (\\<lSUP> t | t \\<in> \\<mhbS> \\<and> t \\<lle> p))\"\n\nlemma gbSlb_mhbS:\n    \"gbSlb p \\<in> \\<mhbS>\"\n  apply (unfold gbSlb_def)\n  apply (rule Sup_mhbS)\n  apply (simp)\n  done\n\nlemma gbSlb_lb:\n    \"gbSlb p \\<lle> p\"\n  apply (unfold gbSlb_def)\n  apply (rule Sup_lub)\n  apply (simp)\n  done\n\nlemma gbSlb_gbSlb:\n  assumes\n    a1: \"q \\<in> \\<mhbS>\" and\n    a2: \"q \\<lle> p\"\n  shows\n    \"q \\<lle> gbSlb p\"\n  apply (unfold gbSlb_def)\n  apply (rule Sup_ub)\n  using a1 a2\n  apply (simp)\n  done\n\ndefinition\n  top_bS :: \"('a::clattice) \\<rightarrow> ('b::clattice)\"\nwhere\n  top_bS_def: \"top_bS \\<defs> gbSlb \\<ltop>\"\n\nnotation (xsymbols output)\n  top_bS (\"\\<top>\\<^sub>b\\<^sub>S\")\n\nnotation (zed)\n  top_bS (\"\\<ltopbS>\")\n\nlemma top_bS_mhbS:\n    \"\\<ltopbS> \\<in> \\<mhbS>\"\n  apply (unfold top_bS_def)\n  apply (rule gbSlb_mhbS)\n  done\n\nlemma top_bS_ub:\n  assumes \n    a1: \"p \\<in> \\<mhbS>\"\n  shows\n    \"p \\<lle> \\<ltopbS>\"\n  apply (unfold top_bS_def)\n  apply (rule gbSlb_gbSlb [OF a1])\n  apply (rule top_ub)\n  done\n\nlemma top_bS_max:\n  assumes \n    a1: \"p \\<in> \\<mhbS>\"\n  shows\n    \"\\<ltopbS> \\<lle> p \\<Leftrightarrow> p = \\<ltopbS>\"\n  apply (auto)\n  apply (rule order_antisym)\n  apply (rule top_bS_ub [OF a1])\n  apply (assumption)\n  done\n\ndefinition\n  inf_bS :: \"[('a::clattice) \\<rightarrow> ('b::clattice), 'a \\<rightarrow> 'b] \\<rightarrow> ('a \\<rightarrow> 'b)\"\nwhere\n  inf_bS_def: \"inf_bS \\<defs> (\\<olambda> p q \\<bullet> gbSlb (p \\<linf> q))\"\n\nnotation (xsymbols output)\n  inf_bS (infixl \"\\<sqinter>\\<^sub>b\\<^sub>S\" 70)\n\nnotation (zed)\n  inf_bS (infixl \"\\<linfbS>\" 70)\n\nlemma inf_bS_mhbS:\n  assumes\n    a1: \"p \\<in> \\<mhbS>\" and\n    a2: \"q \\<in> \\<mhbS>\"\n  shows\n    \"p \\<linfbS> q \\<in> \\<mhbS>\"\n  apply (unfold inf_bS_def)\n  apply (rule gbSlb_mhbS)\n  done\n\nlemma inf_bS_lb1:\n    \"p \\<linfbS> q \\<lle> p\"\n  apply (unfold inf_bS_def)\n  apply (rule order_trans [OF gbSlb_lb inf_lb1])\n  done\n\nlemma inf_bS_lb2:\n    \"p \\<linfbS> q \\<lle> q\"\n  apply (unfold inf_bS_def)\n  apply (rule order_trans [OF gbSlb_lb inf_lb2])\n  done\n\nlemma inf_bS_gbSlb:\n  assumes\n    a1: \"t \\<in> \\<mhbS>\" and\n    a2: \"t \\<lle> p\" and\n    a3: \"t \\<lle> q\"\n  shows\n    \"t \\<lle> p \\<linfbS> q\"\n  apply (unfold inf_bS_def)\n  apply (rule gbSlb_gbSlb)\n  apply (rule a1)\n  apply (rule inf_glb [OF a2 a3])\n  done\n\ndefinition\n  Inf_bS :: \"(('a::clattice) \\<rightarrow> ('b::clattice)) set \\<rightarrow> ('a \\<rightarrow> 'b)\"\nwhere\n  Inf_bS_def: \"Inf_bS \\<defs> (\\<olambda> CL_P \\<bullet> gbSlb (\\<lInf> CL_P))\"\n\nnotation (xsymbols output)\n  Inf_bS (\"\\<Sqinter>\\<^sub>b\\<^sub>S\")\n\nnotation (zed)\n  Inf_bS (\"\\<lInfbS>\")\n\nlemma Inf_bS_mhbS:\n  assumes\n    a1: \"\\<And> p \\<bullet> p \\<in> CL_P \\<turnstile> p \\<in> \\<mhbS>\"\n  shows\n    \"\\<lInfbS> CL_P \\<in> \\<mhbS>\"\n  apply (unfold Inf_bS_def)\n  apply (rule gbSlb_mhbS)\n  done\n\nlemma Inf_bS_lb:\n  assumes\n    a1: \"p \\<in> CL_P\"\n  shows\n    \"\\<lInfbS> CL_P \\<lle> p\"\n  apply (unfold Inf_bS_def)\n  apply (rule order_trans [OF gbSlb_lb Inf_lb])\n  apply (rule a1)\n  done\n\nlemma Inf_bS_gSlb:\n  assumes\n    a1: \"t \\<in> \\<mhbS>\" and\n    a2: \"\\<And> p \\<bullet> p \\<in> CL_P \\<turnstile> t \\<lle> p\"\n  shows\n    \"t \\<lle> \\<lInfbS> CL_P\"\n  apply (unfold Inf_bS_def)\n  apply (rule gbSlb_gbSlb)\n  apply (rule a1)\n  apply (rule Inf_glb)\n  apply (rule a2)\n  apply (assumption)\n  done\n\nlemma top_mhtI:\n    \"\\<ltop> \\<in> \\<mhIt>\"\n  apply (rule mhItI)\n  apply (simp add: lat_bounds nempty_conv Inf_singleton)\n  apply (intro allI top_eq Inf_glb)\n  apply (auto simp add: top_ub)\n  done\n\nlemma inf_mhIt:\n  assumes\n    a1: \"p \\<in> \\<mhIt>\" and\n    a2: \"q \\<in> \\<mhIt>\"\n  shows\n    \"p \\<linf> q \\<in> \\<mhIt>\"\n  apply (rule mhItI)\n  apply (simp add: mhItD [OF a1] mhItD [OF a2] lat_com_assoc Inf_inf Inf_inf')\n  done\n\nlemma Inf_mhIt:\n  assumes\n    a1: \"\\<And> p \\<bullet> p \\<in> CL_A \\<turnstile> p \\<in> \\<mhIt>\"\n  shows\n    \"\\<lInf> CL_A \\<in> \\<mhIt>\"\nproof (rule mhItI)\n  fix CL_X::\"'a set\"\n  have \n      \"(\\<lInf>CL_A) (\\<lInf>CL_X)\n      = (\\<lINF> p | p \\<in> CL_A \\<bullet> p (\\<lInf>CL_X))\"\n    by (simp add: Inf_fun_def)\n  also have \"\\<dots>\n      = (\\<lINF> p | p \\<in> CL_A \\<bullet> (\\<lINF> x | x \\<in> CL_X \\<bullet> p x))\"\n    by (mauto(wind) mintro!: arg_cong [of _ _ \"\\<lInf>\"] msimp add: mhItD [OF a1])\n  also have \"\\<dots> \n       = (\\<lINF> x | x \\<in> CL_X \\<bullet> (\\<lINF> p | p \\<in> CL_A \\<bullet> p x))\"\n    apply (simp add: Inf_Inf)\n    apply (mauto(wind) mintro!: arg_cong [of _ _ \"\\<lInf>\"])\n    apply (auto simp add: eind_def)\n    done\n  also have \"\\<dots> \n       = (\\<lINF> x | x \\<in> CL_X \\<bullet> (\\<lInf>CL_A) x)\"\n    by (simp add: Inf_fun_def)\n  finally show \n      \"(\\<lInf>CL_A) (\\<lInf>CL_X) = (\\<lINF> x | x \\<in> CL_X \\<bullet> (\\<lInf>CL_A) x)\"\n    by (this)\nqed\n\ntext {*\n\nThe sup of Inf-morphic operators is the inf of the Inf-morphic upper bounds.\n\n*}\n\ndefinition\n  lItub :: \"(('a::clattice) \\<rightarrow> ('b::clattice)) \\<rightarrow> ('a \\<rightarrow> 'b)\"\nwhere\n  lItub_def: \"lItub \\<defs> (\\<olambda> p \\<bullet> (\\<lINF> t | t \\<in> \\<mhIt> \\<and> p \\<lle> t))\"\n\nlemma lItub_mhIt:\n    \"lItub p \\<in> \\<mhIt>\"\n  apply (unfold lItub_def)\n  apply (rule Inf_mhIt)\n  apply (simp)\n  done\n\nlemma lItub_ub:\n    \"p \\<lle> lItub p\"\n  apply (unfold lItub_def)\n  apply (rule Inf_glb)\n  apply (simp)\n  done\n\nlemma lItub_lItub:\n  assumes\n    a1: \"q \\<in> \\<mhIt>\" and\n    a2: \"p \\<lle> q\"\n  shows\n    \"lItub p \\<lle> q\"\n  apply (unfold lItub_def)\n  apply (rule Inf_lb)\n  using a1 a2\n  apply (simp)\n  done\n\ndefinition\n  bot_It :: \"('a::clattice) \\<rightarrow> ('b::clattice)\"\nwhere\n  bot_It_def: \"bot_It \\<defs> lItub \\<lbot>\"\n\nnotation (xsymbols output)\n  bot_It (\"\\<bottom>\\<^sub>I\\<^sub>t\")\n\nnotation (zed)\n  bot_It (\"\\<lbotIt>\")\n\nlemma bot_It_mhIt:\n    \"\\<lbotIt> \\<in> \\<mhIt>\"\n  apply (unfold bot_It_def)\n  apply (rule lItub_mhIt)\n  done\n\nlemma bot_It_lb:\n  assumes \n    a1: \"p \\<in> \\<mhIt>\"\n  shows\n    \"\\<lbotIt> \\<lle> p\"\n  apply (unfold bot_It_def)\n  apply (rule lItub_lItub [OF a1])\n  apply (rule bot_lb)\n  done\n\nlemma bot_It_min:\n  assumes \n    a1: \"p \\<in> \\<mhIt>\"\n  shows\n    \"p \\<lle> \\<lbotIt> \\<Leftrightarrow> p = \\<lbotIt>\"\n  apply (auto)\n  apply (rule order_antisym)\n  apply (assumption)\n  apply (rule bot_It_lb [OF a1])\n  done\n\ndefinition\n  sup_It :: \"[('a::clattice) \\<rightarrow> ('b::clattice), 'a \\<rightarrow> 'b] \\<rightarrow> ('a \\<rightarrow> 'b)\"\nwhere\n  sup_It_def: \"sup_It \\<defs> (\\<olambda> p q \\<bullet> lItub (p \\<lsup> q))\"\n\nnotation (xsymbols output)\n  sup_It (infixl \"\\<squnion>\\<^sub>I\\<^sub>t\" 65)\n\nnotation (zed)\n  sup_It (infixl \"\\<lsupIt>\" 65)\n\nlemma sup_It_mhIt:\n  assumes\n    a1: \"p \\<in> \\<mhIt>\" and\n    a2: \"q \\<in> \\<mhIt>\"\n  shows\n    \"p \\<lsupIt> q \\<in> \\<mhIt>\"\n  apply (unfold sup_It_def)\n  apply (rule lItub_mhIt)\n  done\n\nlemma sup_It_ub1:\n    \"p \\<lle> p \\<lsupIt> q\"\n  apply (unfold sup_It_def)\n  apply (rule order_trans [OF sup_ub1 lItub_ub])\n  done\n\nlemma sup_It_ub2:\n    \"q \\<lle> p \\<lsupIt> q\"\n  apply (unfold sup_It_def)\n  apply (rule order_trans [OF sup_ub2 lItub_ub])\n  done\n\nlemma sup_It_lItub:\n  assumes\n    a1: \"t \\<in> \\<mhIt>\" and\n    a2: \"p \\<lle> t\" and\n    a3: \"q \\<lle> t\"\n  shows\n    \"p \\<lsupIt> q \\<lle> t\"\n  apply (unfold sup_It_def)\n  apply (rule lItub_lItub)\n  apply (rule a1)\n  apply (rule sup_lub [OF a2 a3])\n  done\n\ndefinition\n  Sup_It :: \"(('a::clattice) \\<rightarrow> ('b::clattice)) set \\<rightarrow> ('a \\<rightarrow> 'b)\"\nwhere\n  Sup_It_def: \"Sup_It \\<defs> (\\<olambda> CL_P \\<bullet> lItub (\\<lSup> CL_P))\"\n\nnotation (xsymbols output)\n  Sup_It (\"\\<Squnion>\\<^sub>I\\<^sub>t\")\n\nnotation (zed)\n  Sup_It (\"\\<lSupIt>\")\n\nlemma Sup_It_mhIt:\n  assumes\n    a1: \"\\<And> p \\<bullet> p \\<in> CL_P \\<turnstile> p \\<in> \\<mhIt>\"\n  shows\n    \"\\<lSupIt> CL_P \\<in> \\<mhIt>\"\n  apply (unfold Sup_It_def)\n  apply (rule lItub_mhIt)\n  done\n\nlemma Sup_It_lb:\n  assumes\n    a1: \"p \\<in> CL_P\"\n  shows\n    \"p \\<lle> \\<lSupIt> CL_P\"\n  apply (unfold Sup_It_def)\n  apply (rule order_trans [OF Sup_ub lItub_ub])\n  apply (rule a1)\n  done\n\nlemma Sup_It_lItub:\n  assumes\n    a1: \"t \\<in> \\<mhIt>\" and\n    a2: \"\\<And> p \\<bullet> p \\<in> CL_P \\<turnstile> p \\<lle> t\"\n  shows\n    \"\\<lSupIt> CL_P \\<lle> t\"\n  apply (unfold Sup_It_def)\n  apply (rule lItub_lItub)\n  apply (rule a1)\n  apply (rule Sup_lub)\n  apply (rule a2)\n  apply (assumption)\n  done\n\nsection {* Sets *}\n\n(*\ninstance\n  set :: (type) clat\n  by (intro_classes)\n\ninstance\n  set :: (type) bllat\n  by (intro_classes)\n*)\n\ninstantiation\n  set :: (type) clattice\n\nbegin\n\ndefinition\n  inf_set_def: \"(op &&) \\<defs> (\\<olambda> (x::'a set) y \\<bullet> x \\<inter> y)\"\n\ndefinition\n  sup_set_def: \"(op ||) \\<defs> (\\<olambda> (x::'a set) y \\<bullet> x \\<union> y)\"\n\ndefinition\n  Inf_set_def: \"Inf \\<defs> (\\<olambda> (X::'a set set) \\<bullet> (\\<Inter> x | x \\<in> X \\<bullet> x))\"\n\ndefinition\n  Sup_set_def: \"Sup \\<defs> (\\<olambda> (X::'a set set) \\<bullet> (\\<Union> x | x \\<in> X \\<bullet> x))\"\n\ndefinition\n  bot_set_def: \"bot \\<defs> \\<emptyset>\"\n\ndefinition\n  top_set_def: \"top \\<defs> \\<univ>\"\n\n\ninstance \n  apply (intro_classes)\n  apply (auto intro!: Inf_lb Inf_glb Sup_ub Sup_lub \n              simp add: inf_set_def sup_set_def Inf_set_def Sup_set_def bot_set_def top_set_def \n                        eind_def)\n  done\n\nend\n\n\nlemma inf_set_conv [simp]:\n  \"(A \\<linf> B) = (A \\<inter> B)\"\n  by (simp add: inf_set_def)\n\nlemma sup_set_conv [simp]:\n  \"(A \\<lsup> B) = (A \\<union> B)\"\n  by (simp add: sup_set_def)\n\n(*\ninstance set :: (type) nonsqord\n  by (intro_classes)\n*)\n\nlemma Inf_set_conv [simp]: \"\\<lInf>CL_A = \\<Inter>CL_A\"\n  by (simp add: Inf_set_def eind_def)\n\nlemma Sup_set_conv [simp]: \"\\<lSup>CL_A = \\<Union>CL_A\"\n  by (simp add: Sup_set_def eind_def)\n\nlemma bot_set_conv [simp]: \"\\<lbot> = \\<emptyset>\"\n  by (simp add: bot_set_def)\n\nlemma top_set_conv [simp]: \"\\<ltop> = \\<univ>\"\n  by (simp add: top_set_def)\n\ninstantiation  set:: (type) boollattice\nbegin\n\ndefinition\n  comp_set_def: \"ocomp \\<defs> (\\<olambda> (x::'a set) \\<bullet> -x)\"\n(*\ndefinition\n  comp_set_def: \"ocomp \\<defs> (\\<olambda> (x::'a set) \\<bullet> \\<univ> \\<setminus> x)\"\n*)\n\ninstance\n  apply (intro_classes)\n  apply (auto simp add: comp_set_def)\n  done\n\nend\n\nlemma comp_set_conv [simp]: \"\\<lcomp> (A::'a set) = -A\"\n  by (simp add: comp_set_def)\n\n\n\n\n\n(*\nlemma inf_set_def: \n  \"(op &&) = (\\<olambda> (x::'a set) y \\<bullet> x \\<inter> y)\"\n  apply (intro ext)\n  apply (simp add: linf_fun_def Int_def linf_bool_def)\n  done\n  \nlemma sup_set_def: \n  \"(op ||) = (\\<olambda> (x::'a set) y \\<bullet> x \\<union> y)\"\n  by (simp add: lsup_fun_def Un_def lsup_bool_def Collect_def mem_def)\n\nlemma Inf_set_def: \n  \"Inf = (\\<olambda> (X::'a set set) \\<bullet> (\\<Inter> x | x \\<in> X \\<bullet> x))\"\n  apply (intro ext)\n  apply (auto simp add: Inf_fun_def Inter_eq Inf_bool_def Collect_def mem_def)\n  done\n\nlemma\n  Sup_set_def: \"Sup = (\\<olambda> (X::'a set set) \\<bullet> (\\<Union> x | x \\<in> X \\<bullet> x))\"\n  apply (intro ext)\n  apply (auto simp add: Sup_fun_def Union_eq Sup_bool_def Collect_def mem_def)\n  done\n\nlemma\n  bot_set_def: \"bot = \\<emptyset>\"\n  apply (intro set_eqI)\n  apply (simp add: bot_fun_def bot_bool_def)\n  apply (simp add: mem_def)\n  done\n\nlemma\n  top_set_def: \"top = \\<univ>\"\n  apply (intro set_eqI)\n  apply (simp add: top_fun_def top_bool_def)\n  apply (simp add: mem_def)\n  done\n\nlemma\n  comp_set_def: \"lcomp = (\\<olambda> (x::'a set) \\<bullet> -x)\"\n  apply (intro set_eqI ext)\n  apply (simp add: lcomp_fun_def lcomp_bool_def)\n  apply (simp add: mem_def) \n  done\n\nlemmas lat_set_defs = \n  inf_set_def sup_set_def Inf_set_def Sup_set_def\n  bot_set_def top_set_def comp_set_def\n\nlemma [simp]:\n    \"x \\<in> (X \\<linf> Y) \\<Leftrightarrow> x \\<in> X \\<and> x \\<in> Y\" \n    \"x \\<in> (X \\<lsup> Y) \\<Leftrightarrow> x \\<in> X \\<or> x \\<in> Y\"\n    \"x \\<in> (\\<lINF> a | p a \\<bullet> f a) \\<Leftrightarrow> (\\<forall> a | p a \\<bullet> x \\<in> (f a))\"\n    \"x \\<in> (\\<lSUP> a | p a \\<bullet> f a) \\<Leftrightarrow> (\\<exists> a | p a \\<bullet> x \\<in> (f a))\"\n    \"x \\<in> \\<lbot> \\<Leftrightarrow> \\<False>\"\n    \"x \\<in> \\<ltop> \\<Leftrightarrow> \\<True>\"\n    \"x \\<in> \\<lcomp>X \\<Leftrightarrow> x \\<notin> X\"\n  by (simp_all add: lat_set_defs)\n*)\n\n\nlemmas lat_set_defs = \n  inf_set_def sup_set_def Inf_set_def Sup_set_def\n  bot_set_def top_set_def comp_set_def\n\nlemma [simp]:\n    \"x \\<in> (X \\<linf> Y) \\<Leftrightarrow> x \\<in> X \\<and> x \\<in> Y\" \n    \"x \\<in> (X \\<lsup> Y) \\<Leftrightarrow> x \\<in> X \\<or> x \\<in> Y\"\n    \"x \\<in> (\\<lINF> a | p a \\<bullet> f a) \\<Leftrightarrow> (\\<forall> a | p a \\<bullet> x \\<in> (f a))\"\n    \"x \\<in> (\\<lSUP> a | p a \\<bullet> f a) \\<Leftrightarrow> (\\<exists> a | p a \\<bullet> x \\<in> (f a))\"\n    \"x \\<in> \\<lbot> \\<Leftrightarrow> \\<False>\"\n    \"x \\<in> \\<ltop> \\<Leftrightarrow> \\<True>\"\n    \"x \\<in> \\<lcomp>X \\<Leftrightarrow> x \\<notin> X\"\n  by (simp_all add: lat_set_defs)\n\nsection {* Predicate functions *}\n\ntext {*\n\nFunctions on predicates (predicate transformers)\noffer some interesting algebraic properties, in particular a \nGalois transformation with corresponding base type functions (relations).\n\n*}\n\ndefinition\n  relS :: \"('a \\<rightarrow> ('b::clattice)) \\<rightarrow> (('a \\<rightarrow> \\<bool>) \\<rightarrow> 'b)\"\nwhere\n  relS_def: \"relS \\<defs> (\\<olambda> r BS_phi \\<bullet> (\\<lSUP> a | BS_phi a \\<bullet> r a))\"\n\nlemma mono_relS:\n  assumes\n    a1: \"r \\<lle> s\"\n  shows\n    \"relS r \\<lle> relS s\"\n  using a1\n  by (auto intro: QTSup_dom simp add: relS_def le_fun_def)\n\ndefinition\n  effS :: \"(('a \\<rightarrow> \\<bool>) \\<rightarrow> 'b) \\<rightarrow> ('a \\<rightarrow> ('b::clattice))\"\nwhere\n  effS_def: \"effS \\<defs> (\\<olambda> p a \\<bullet> p (\\<olambda> x \\<bullet> x = a))\"\n\nlemma mono_effS:\n  assumes\n    a1: \"p \\<lle> q\"\n  shows\n    \"effS p \\<lle> effS q\"\n  using a1\n  by (simp add: effS_def le_fun_def)\n\nlemma relS_inv:\n    \"effS (relS r) = r\"\n  by (simp add: relS_def effS_def Sup_singleton eind_def)\n\nlemma relS_mhS:\n    \"relS r \\<in> \\<mhS>\"\n  apply (rule mhSI)\n  apply (simp add: relS_def Sup_fun_def)\n  apply (simp add: Sup_Sup)\n  apply (rule arg_cong [of _ _ \"\\<lSup>\"])\n  apply (auto)\n  apply (intro exI conjI)\n  apply (rule refl)\n  apply (rotate_tac 1)\n  apply (assumption+)\n  apply (intro exI conjI)\n  apply (rule refl)\n  apply (rotate_tac 1)\n  apply (assumption+)\n  done\n\nlemma relS_mhb:\n    \"relS r \\<in> \\<mhb>\"\n  apply (rule mhbI)\n  apply (rule mhSDm [OF relS_mhS])\n  apply (simp add: relS_def Sup_empty eind_def)\n  done\n\nlemma relS_rgal: \n  assumes\n    a1: \"p \\<in> \\<mh>\"\n  shows \n    \"relS (effS p) \\<lle> p\"\n  apply (simp add: relS_def effS_def le_fun_def)\n  apply (intro allI Sup_lub)\n  apply (auto)\n  apply (rule mhD [OF a1])\n  apply (auto)\n  done\n\nlemma effS_inv_mhbS:\n  assumes\n    a1: \"p \\<in> \\<mhbS>\"\n  shows \n    \"relS (effS p) = p\"\nproof (rule ext)\n  fix BS_phi\n  have \n      \"relS (effS p) BS_phi\n      = (\\<lSUP> a | BS_phi a \\<bullet> p (\\<olambda> b \\<bullet> b = a))\"\n    by (auto simp add: relS_def effS_def)\n  also have \"\\<dots>\n      = p (\\<lSUP> a | BS_phi a \\<bullet> (\\<olambda> b \\<bullet> b = a))\"\n    by (simp add: mhbSD [OF a1] eind_def eind_comp)\n  also have \n      \"(\\<lSUP> a | BS_phi a \\<bullet> (\\<olambda> b \\<bullet> b = a)) \n      = BS_phi\"\n    by (simp add: Sup_fun_def)\n  finally show \n      \"relS (effS p) BS_phi = p BS_phi\"\n    by (this)\nqed\n \nlemma mhbS_char:\n  \"\\<mhbS> = range relS\"\nproof (intro set_eqI iffI)\n  fix p\n  assume \"p \\<in> range relS\"\n  then show \"p \\<in> \\<mhbS>\"\n    by (auto simp add: image_def relS_mhS relS_mhb)\nnext\n  fix p::\"('a \\<rightarrow> \\<bool>) \\<rightarrow> 'b\"\n  assume b1: \"p \\<in> \\<mhbS>\" \n  then have \"p = relS (effS p)\"\n    by (simp add: effS_inv_mhbS)\n  then show \"p \\<in> range relS\"\n    by (auto simp add: image_def)\nqed\n \nlemma mhbSE:\n  assumes a1: \"p \\<in> \\<mhbS>\" and\n    a2: \"\\<And> r \\<bullet> p = relS r \\<turnstile> R\"\n  shows \"R\"\nproof -\n  from a1 obtain r where b1: \"p = relS r\"\n    by (auto simp add: mhbS_char)\n  then show \"R\"\n    by (rule a2)\nqed\n\nlemma gbSlb_decomp: \n  assumes \n    a1: \"p \\<in> \\<mh>\"\n  shows \n    \"gbSlb p = relS (effS p)\"\n  apply (unfold gbSlb_def)\n  apply (rule Sup_eq)\n  apply (simp_all only: mem_Collect_eq)\n  apply (msafe(inference))\nproof -\n  fix q\n  assume \n    b1: \"q \\<in> \\<mhbS>\" and \n    b2: \"q \\<lle> p\"\n  from b1 have \n      \"q = relS (effS q)\"\n    by (simp add: effS_inv_mhbS)\n  also from b2 have \n      \"\\<dots> \\<lle> relS (effS p)\"\n    by (simp add: mono_relS  mono_effS)\n  finally show \n      \"q \\<lle> relS (effS p)\"\n    by (this)\nnext\n  fix q\n  assume \n    b1: \"\\<forall> q' | q' \\<in> \\<mhbS> \\<and> q' \\<lle> p \\<bullet> q' \\<lle> q\"\n  show \"relS (effS p) \\<lle> q\"\n  proof (rule b1 [rule_format])\n    show \n        \"relS (effS p) \\<in> \\<mhbS>\"\n      by (auto simp add: mhbS_char image_def)\n    from a1 show \n        \"relS (effS p) \\<lle> p\"\n      by (rule relS_rgal)\n  qed\nqed\n\ndefinition\n  relI :: \"('a \\<rightarrow> ('b::{clattice,boollattice})) \\<rightarrow> (('a \\<rightarrow> \\<bool>) \\<rightarrow> 'b)\"\nwhere\n  relI_def: \"relI \\<defs> (\\<olambda> r BS_phi \\<bullet> (\\<lINF> a | \\<not>(BS_phi a) \\<bullet> \\<lcomp>(r a)))\"\n\nlemma amono_relI:\n  assumes\n    a1: \"r \\<lle> s\"\n  shows\n    \"relI s \\<lle> relI r\"\n  using a1\n  by (auto intro!: QTInf_dom simp add: relI_def le_fun_def comp_antimono)\n\ndefinition\n  effI :: \"(('a \\<rightarrow> \\<bool>) \\<rightarrow> 'b) \\<rightarrow> ('a \\<rightarrow> ('b::{clattice,boollattice}))\"\nwhere\n  effI_def: \"effI \\<defs> (\\<olambda> p a \\<bullet> \\<lcomp> (p (\\<olambda> x \\<bullet> x \\<noteq> a)))\"\n\nlemma amono_effI:\n  assumes\n    a1: \"p \\<lle> q\"\n  shows\n    \"effI q \\<lle> effI p\"\n  using a1\n  by (simp add: effI_def le_fun_def comp_antimono)\n\nlemma relI_inv:\n    \"effI (relI r) = r\"\n  by (simp add: fun_eq_def relI_def effI_def Sup_singleton Inf_demorgan comp_involution eind_def)\n\nlemma relI_mhI:\n    \"relI r \\<in> \\<mhI>\"\n  apply (rule mhII)\n  apply (simp add: relI_def Inf_fun_def)\n  apply (simp add: Inf_Inf)\n  apply (rule arg_cong [of _ _ \"\\<lInf>\"])\n  apply (auto simp add: eind_def)\n  done\n\nlemma relI_mht:\n    \"relI r \\<in> \\<mht>\"\n  apply (rule mhtI)\n  apply (rule mhIDm [OF relI_mhI])\n  apply (simp add: relI_def Inf_empty eind_def)\n  done\n\nlemma relI_lgal: \n  assumes\n    a1: \"p \\<in> \\<mh>\"\n  shows \n    \"p \\<lle> relI (effI p)\"\n  apply (simp add: relI_def effI_def le_fun_def comp_involution)\n  apply (intro allI Inf_glb)\n  apply (auto)\n  apply (rule mhD [OF a1])\n  apply (auto)\n  done\n\nlemma effI_inv_mhIt:\n  assumes\n    a1: \"p \\<in> \\<mhIt>\"\n  shows \n    \"relI (effI p) = p\"\nproof (rule ext)\n  fix BS_phi\n  have \n      \"relI (effI p) BS_phi\n      = (\\<lINF> a | \\<not>(BS_phi a) \\<bullet> p (\\<olambda> b \\<bullet> b \\<noteq> a))\"\n    by (auto simp add: relI_def effI_def comp_involution)\n  also have \"\\<dots>\n      = p (\\<lINF> a | \\<not>(BS_phi a) \\<bullet> (\\<olambda> b \\<bullet> b \\<noteq> a))\"\n    by (simp add: mhItD [OF a1] eind_def eind_comp)\n  also have \n      \"(\\<lINF> a | \\<not>(BS_phi a) \\<bullet> (\\<olambda> b \\<bullet> b \\<noteq> a)) \n      = BS_phi\"\n    apply (rule ext)\n    apply (auto simp add: Inf_fun_def)\n    done\n  finally show \n      \"relI (effI p) BS_phi = p BS_phi\"\n    by (this)\nqed\n \nlemma mhIt_char:\n  \"\\<mhIt> = range relI\"\nproof (intro set_eqI iffI)\n  fix p\n  assume \n      \"p \\<in> range relI\"\n  then show \n      \"p \\<in> \\<mhIt>\"\n    by (auto simp add: image_def relI_mhI relI_mht)\nnext\n  fix p::\"('a \\<rightarrow> \\<bool>) \\<rightarrow> 'b\"\n  assume \n    b1: \"p \\<in> \\<mhIt>\" \n  then have \n      \"p = relI (effI p)\"\n    by (simp add: effI_inv_mhIt)\n  then show \n      \"p \\<in> range relI\"\n    by (auto simp add: image_def)\nqed\n \nlemma mhItE:\n  assumes \n    a1: \"p \\<in> \\<mhIt>\" and\n    a2: \"\\<And> r \\<bullet> p = relI r \\<turnstile> R\"\n  shows \n    \"R\"\nproof -\n  from a1 obtain r where \n    b1: \"p = relI r\"\n    by (auto simp add: mhIt_char)\n  then show \n      \"R\"\n    by (rule a2)\nqed\n\nlemma gItlb_decomp: \n  assumes \n    a1: \"p \\<in> \\<mh>\"\n  shows \n    \"lItub p = relI (effI p)\"\n  apply (unfold lItub_def)\n  apply (rule Inf_eq)\n  apply (simp_all only: mem_Collect_eq)\n  apply (msafe(inference))\nproof -\n  fix q\n  assume \n    b1: \"q \\<in> \\<mhIt>\" and \n    b2: \"p \\<lle> q\"\n  from b2 have \n      \"relI (effI p) \n      \\<lle> relI (effI q)\"\n    by (simp add: amono_relI  amono_effI)\n  also from b1 have \"\\<dots>\n      = q\"\n    by (simp add: effI_inv_mhIt) \n  finally show \n      \"relI (effI p) \\<lle> q\"\n    by (this)\nnext\n  fix q\n  assume \n    b1: \"\\<forall> q' | q' \\<in> \\<mhIt> \\<and> p \\<lle> q' \\<bullet> q \\<lle> q'\"\n  show \n      \"q \\<lle> relI (effI p)\"\n  proof (rule b1 [rule_format])\n    show \n        \"relI (effI p) \\<in> \\<mhIt>\"\n      by (auto simp add: mhIt_char image_def)\n    from a1 show \n        \"p \\<lle> relI (effI p)\"\n      by (rule relI_lgal)\n  qed\nqed\n\nsection {* Total Graphs *}\n\ntext {*\n\nTotal graphs also inherit lattice properties from their ranges.\n\n*}\n\nlemma (in Lattice_Locale.lattice) tfun_latticeI:\n  \"\\<^lattice>{:(Y \\<ztfun> X):}{:(tfun_order Y X (op \\<sqsubseteq>)):}\"\nproof (rule partial_order.latticeI)\n  from partial_order show \n      \"\\<^poset>{:(Y \\<ztfun> X):}{:(tfun_order Y X (op \\<sqsubseteq>)):}\"\n    by (rule tfun_poI)\nnext\n  fix \n    f g \n  assume \n    b1: \"f \\<in> Y \\<ztfun> X\" \"g \\<in> Y \\<ztfun> X\"\n  show \n      \"(\\<exists> h \\<bullet> \\<^glbp>{:(Y \\<ztfun> X):}{:(tfun_order Y X (op \\<sqsubseteq>)):} {f, g} h)\"\n  proof (witness \"(\\<glambda> y | y \\<in> Y \\<bullet> f\\<cdot>y \\<sqinter> g\\<cdot>y)\")\n    from b1 [THEN tfun_range] have \n      c1: \"(\\<forall> y | y \\<in> Y \\<bullet> f\\<cdot>y \\<sqinter> g\\<cdot>y \\<in> X)\"\n      by (auto)\n    then have \n      c2: \"(\\<glambda> y | y \\<in> Y \\<bullet> f\\<cdot>y \\<sqinter> g\\<cdot>y) \\<in> Y \\<ztfun> X\"\n      apply (mauto(fspace) msimp add: glambda_dom glambda_ran)\n      apply (auto simp add: glambda_dom glambda_ran)\n      done\n    from b1 b1 [THEN tfun_range] c1 c2 show \n        \"\\<^glbp>{:(Y \\<ztfun> X):}{:(tfun_order Y X (op \\<sqsubseteq>)):} {f, g} (\\<glambda> y | y \\<in> Y \\<bullet> f\\<cdot>y \\<sqinter> g\\<cdot>y)\"\n      by (auto simp add: is_glb_def is_greatest_def is_lb_def tfun_order_def\n        glambda_beta meet_lbD1 meet_lbD2 meet_glbD)\n  qed\nnext\n  fix   \n    f g \n  assume \n    b1: \"f \\<in> Y \\<ztfun> X\" \"g \\<in> Y \\<ztfun> X\"\n  show \n      \"(\\<exists> h \\<bullet> \\<^lubp>{:(Y \\<ztfun> X):}{:(tfun_order Y X (op \\<sqsubseteq>)):} {f, g} h)\"\n  proof (witness \"(\\<glambda> y | y \\<in> Y \\<bullet> f\\<cdot>y \\<squnion> g\\<cdot>y)\")\n    from b1 [THEN tfun_range] have \n      c1: \"(\\<forall> y | y \\<in> Y \\<bullet> f\\<cdot>y \\<squnion> g\\<cdot>y \\<in> X)\"\n      by (auto)\n    then have c2: \"(\\<glambda> y | y \\<in> Y \\<bullet> f\\<cdot>y \\<squnion> g\\<cdot>y) \\<in> Y \\<ztfun> X\"\n      apply (msafe(fspace))\n      apply (auto simp add: glambda_dom glambda_ran)\n      done\n    from b1 b1 [THEN tfun_range] c1 c2 show \n        \"\\<^lubp>{:(Y \\<ztfun> X):}{:(tfun_order Y X (op \\<sqsubseteq>)):} {f, g} (\\<glambda> y | y \\<in> Y \\<bullet> f\\<cdot>y \\<squnion> g\\<cdot>y)\"\n      by (auto simp add: is_lub_def is_least_def is_ub_def tfun_order_def\n        glambda_beta join_ubD1 join_ubD2 join_lubD)\n  qed\nqed\n\nlemma (in Lattice_Locale.clattice) tfun_clatticeI:\n  \"\\<^clattice>{:(Y \\<ztfun> X):}{:(tfun_order Y X (op \\<sqsubseteq>)):}\"\nproof (rule partial_order.clatticeI)\n  from partial_order show \n    b1: \"\\<^poset>{:(Y \\<ztfun> X):}{:(tfun_order Y X (op \\<sqsubseteq>)):}\"\n    by (rule tfun_poI) \n  then interpret \n    fun_po: Order_Locale.partial_order \"(Y \\<ztfun> X)\" \"(tfun_order Y X (op \\<sqsubseteq>))\"\n    by (simp_all add: Order_Locale.partial_order_def)\n{\n  fix \n    F\n  assume \n    b2: \"F \\<subseteq> Y \\<ztfun> X\"\n  show \n      \"(\\<exists> f \\<bullet> \\<^glbp>{:(Y \\<ztfun> X):}{:(tfun_order Y X (op \\<sqsubseteq>)):} F f)\"\n  proof (witness \"(\\<glambda> y | y \\<in> Y \\<bullet> \\<Sqinter>{f | f \\<in> F \\<bullet> f\\<cdot>y})\")\n    from b2 have \n      c1: \"(\\<forall> y | y \\<in> Y \\<bullet> {f | f \\<in> F \\<bullet> f\\<cdot>y} \\<subseteq> X)\"\n      by (auto simp add: eind_def)\n    then have \n      c2: \"(\\<forall> y | y \\<in> Y \\<bullet> is_glb {f | f \\<in> F \\<bullet> f\\<cdot>y} (\\<Sqinter>{f | f \\<in> F \\<bullet> f\\<cdot>y}))\"\n      by (auto intro!: Meet_glb simp add: eind_def eind_comp)\n    from b2 c2 have \n      c3: \"(\\<glambda> y | y \\<in> Y \\<bullet> \\<Sqinter>{f | f \\<in> F \\<bullet> f\\<cdot>y}) \\<in> Y \\<ztfun> X\"\n      apply (msafe(fspace))\n      apply (auto simp add: glambda_dom glambda_ran is_glb_def \n        is_greatest_def is_lb_def)\n      done\n    from b2 c1 c2 c3 show \n        \"\\<^glbp>{:(Y \\<ztfun> X):}{:(tfun_order Y X (op \\<sqsubseteq>)):} F (\\<glambda> y | y \\<in> Y \\<bullet> \\<Sqinter>{f | f \\<in> F \\<bullet> f\\<cdot>y})\"\n      apply (intro fun_po.is_glbI [OF c3])\n      apply (auto intro!: Meet_lbD Meet_glbD\n        simp add: tfun_order_def glambda_beta eind_def eind_comp) \n      done\n  qed\n}\n{\n  fix \n    F\n  assume \n    b2: \"F \\<subseteq> Y \\<ztfun> X\"\n  show \n      \"(\\<exists> f \\<bullet> \\<^lubp>{:(Y \\<ztfun> X):}{:(tfun_order Y X (op \\<sqsubseteq>)):} F f)\"\n  proof (witness \"(\\<glambda> y | y \\<in> Y \\<bullet> \\<Squnion>{f | f \\<in> F \\<bullet> f\\<cdot>y})\")\n    from b2 have \n      c1: \"(\\<forall> y | y \\<in> Y \\<bullet> {f | f \\<in> F \\<bullet> f\\<cdot>y} \\<subseteq> X)\"\n      by (auto simp add: eind_def)\n    then have \n      c2: \"(\\<forall> y | y \\<in> Y \\<bullet> is_lub {f | f \\<in> F \\<bullet> f\\<cdot>y} (\\<Squnion>{f | f \\<in> F \\<bullet> f\\<cdot>y}))\"\n      by (auto intro!: Join_lub simp add: eind_def eind_comp)\n    from b2 c2 have \n      c3: \"(\\<glambda> y | y \\<in> Y \\<bullet> \\<Squnion>{f | f \\<in> F \\<bullet> f\\<cdot>y}) \\<in> Y \\<ztfun> X\"\n      apply (msafe(fspace))\n      apply (auto simp add: glambda_dom glambda_ran is_lub_def \n        is_least_def is_ub_def)\n      done\n    from b2 c1 c2 c3 show \n        \"\\<^lubp>{:(Y \\<ztfun> X):}{:(tfun_order Y X (op \\<sqsubseteq>)):} F (\\<glambda> y | y \\<in> Y \\<bullet> \\<Squnion>{f | f \\<in> F \\<bullet> f\\<cdot>y})\"\n      apply (intro fun_po.is_lubI [OF c3])\n      apply (auto intro!: Join_ubD Join_lubD\n        simp add: tfun_order_def glambda_beta eind_def eind_comp) \n      done\n  qed\n}\nqed\n\n\nsection {* Dual spaces *}\n\ntext {*\n\nDual spaces preserve all of the lattice structure of the original space.\n\n*}\n\ninstantiation\n  dual :: (lat) lat\nbegin\n\ndefinition\n  linf_dual_def: \"(op &&) \\<defs> (\\<olambda> x y \\<bullet> \\<^adual>{:(\\<^rdual>{:x:} || \\<^rdual>{:y:}):})\"\n\ndefinition\n  lsup_dual_def: \"(op ||) \\<defs> (\\<olambda> x y \\<bullet> \\<^adual>{:(\\<^rdual>{:x:} && \\<^rdual>{:y:}):})\"\n\ninstance\n  by (intro_classes)\n\nend\n\ninstantiation\n  dual :: (blat) blat\nbegin\n\ndefinition\n  bot_dual_def: \"bot \\<defs> \\<^adual>{:top:}\"\n\ndefinition\n  top_dual_def: \"top \\<defs> \\<^adual>{:bot:}\"\n\ninstance\n  by (intro_classes)\n\nend\n\ninstantiation\n  dual :: (clat) clat\nbegin\n\ndefinition\n  Inf_dual_def: \"Inf \\<defs> (\\<olambda> P \\<bullet> \\<^adual>{:(Sup { x | x \\<in> P \\<bullet> \\<^rdual>{:x:} }):})\"\n\ndefinition\n  Sup_dual_def: \"Sup \\<defs> (\\<olambda> P \\<bullet> \\<^adual>{:(Inf { x | x \\<in> P \\<bullet> \\<^rdual>{:x:} }):})\"\n\ninstance\n  by (intro_classes)\n\nend\n\ninstantiation\n  dual :: (bllat) bllat\nbegin\n\ndefinition\n  lcomp_dual_def: \"ocomp \\<defs> (\\<olambda> x \\<bullet> \\<^adual>{:(ocomp \\<^rdual>{:x:}):})\"\n\ninstance\n  by (intro_classes)\n\nend\n\ninstance\n  dual :: (lattice) lattice\n  apply (intro_classes)\n  apply (auto intro: inf_lb1 inf_lb2 sup_ub1 sup_ub2 inf_glb sup_lub simp add: linf_dual_def lsup_dual_def less_eq_dual_conv Abs_dual_inverse2)\n  done\n\ninstance\n  dual :: (boundlattice) boundlattice\n  apply (intro_classes)\n  apply (auto intro: bot_lb top_ub simp add: bot_dual_def top_dual_def less_eq_dual_conv Abs_dual_inverse2)\n  done\n\ninstance\n  dual :: (clattice) clattice\n  apply (intro_classes)\n  apply (auto intro!: Inf_lb Inf_glb Sup_ub Sup_lub arg_cong [of _ _ \"Inf\"] arg_cong [of _ _ \"Sup\"] simp add: Inf_dual_def Sup_dual_def linf_dual_def inf_Inf lsup_dual_def sup_Sup bot_dual_def bot_Inf top_dual_def top_Sup less_eq_dual_conv Abs_dual_inverse2 Abs_dual_inject2)\n  apply (auto intro!: exI Abs_dual_inverse2 [symmetric])\n  done\n\nlemma Inf_dual_conv:\n  \"\\<lInf> P = \\<^adual>{:(\\<lSUP> x | x \\<in> P \\<bullet> \\<^rdual>{:x:}):}\"\n  by (simp add: Inf_dual_def)\n\nlemma QInf_dual_conv:\n  \"(\\<lINF> x | P x) = \\<^adual>{:(\\<lSUP> x | P x \\<bullet> \\<^rdual>{:x:}):}\"\n  by (simp add: Inf_dual_def)\n\nlemma TQInf_dual_conv:\n  \"(\\<lINF> x | P x \\<bullet> f x) = \\<^adual>{:(\\<lSUP> x | P x \\<bullet> \\<^rdual>{:(f x):}):}\"\n  by (simp add: Inf_dual_def eind_def eind_comp)\n\nlemma Sup_dual_conv:\n  \"\\<lSup> P = \\<^adual>{:(\\<lINF> x | x \\<in> P \\<bullet> \\<^rdual>{:x:}):}\"\n  by (simp add: Sup_dual_def)\n\nlemma QSup_dual_conv:\n  \"(\\<lSUP> x | P x) = \\<^adual>{:(\\<lINF> x | P x \\<bullet> \\<^rdual>{:x:}):}\"\n  by (simp add: Sup_dual_def)\n\nlemma TQSup_dual_conv:\n  \"(\\<lSUP> x | P x \\<bullet> f x) = \\<^adual>{:(\\<lINF> x | P x \\<bullet> \\<^rdual>{:(f x):}):}\"\n  by (simp add: Sup_dual_def eind_def eind_comp)\n\ninstance\n  dual :: (dlattice) dlattice\n  apply (intro_classes)\n  apply (simp add: linf_dual_def lsup_dual_def Abs_dual_inverse2 Abs_dual_inject2 inf_dist)\n  done\n\ninstance\n  dual :: (boollattice) boollattice\n  apply (intro_classes)\n  apply (auto simp add: linf_dual_def lsup_dual_def bot_dual_def top_dual_def lcomp_dual_def comp_inf comp_sup Abs_dual_inverse2 Abs_dual_inject2)\n  done\n\nsection {* The unit lattice *}\n\ninstantiation\n  unit :: clat\nbegin\n\ndefinition\n  linf_unit_def: \"(op &&) \\<defs> (\\<olambda> (x::unit) y \\<bullet> ())\"\n\ndefinition\n  lsup_unit_def: \"(op ||) \\<defs> (\\<olambda> (x::unit) y \\<bullet> ())\"\n\ndefinition\n  Inf_unit_def: \"Inf \\<defs> (\\<olambda> (X::unit set) \\<bullet> ())\"\n\ndefinition\n  Sup_unit_def: \"Sup \\<defs> (\\<olambda> (X::unit set) \\<bullet> ())\"\n\ndefinition\n  bot_unit_def: \"bot \\<defs> ()\"\n\ndefinition\n  top_unit_def: \"top \\<defs> ()\"\n\ninstance\n  by (intro_classes)\n\nend\n \ninstantiation\n unit :: bllat\nbegin\n\ndefinition\n  lcomp_unit_def: \"ocomp \\<defs> (\\<olambda> (x::unit) \\<bullet> ())\"\n\ninstance\n  by (intro_classes)\n\nend\n\ninstance\n  unit :: clattice\n  apply (intro_classes)\n  apply (auto simp add: \n            linf_unit_def lsup_unit_def Inf_unit_def Sup_unit_def bot_unit_def top_unit_def)\n  done\n\ninstance\n  unit :: boollattice\n  apply (intro_classes)\n  apply (auto simp add: linf_unit_def lsup_unit_def bot_unit_def top_unit_def lcomp_unit_def)\n  done\n\nsection {* (Bounded) Reals *}\n\ntext {*\n\nThe reals as a whole form a linear order -- and so, of course, a lattice.\nSuch results are obvious from default\\_order and linorder_classD.\n\n*}\n\ninstantiation\n  real :: linlat\nbegin\n\ndefinition\n  inf_real_def: \"oinf \\<defs> (\\<olambda> (x::\\<real>) y \\<bullet> \\<if> x \\<le> y \\<then> x \\<else> y \\<fi>)\"\n\ndefinition\n  sup_real_def: \"osup \\<defs> (\\<olambda> (x::\\<real>) y \\<bullet> \\<if> x \\<le> y \\<then> y \\<else> x \\<fi>)\"\n\ninstance\n  apply (intro_classes)\n  apply (simp_all add: inf_real_def sup_real_def)\n  done\n\nend\n\ninterpretation \n  real_lattice: Lattice_Locale.lattice \"\\<univ>-[\\<real>]\" \"op \\<le>\"\n  by (unfold_locales)\n\ntext{*\nThe reals as a whole are not a complete lattice, but they are locally complete in the\nsense that any bounded subset is a complete lattice. We introduce a useful class of \ncomplete sub-orders of the reals in the form of real intervals bounded by a given natural \nnumber.\nThe naturals are convenient for this purpose as they are positive by construction.\n\n*}\n\ndefinition\n  ball :: \"\\<nat> \\<rightarrow> \\<real> set\"\nwhere\n  ball_def: \"ball N \\<defs> { x | \\<abs>x\\<abs> \\<le> of_nat N }\"\n\ntext {* \n\\subsection{Bounded reals}\n\nWe begin with some technical lemmas about these intervals.\n\n*}\n\nlemma ball_nempty:\n  \"ball N \\<noteq> \\<emptyset>\"\n  apply (auto simp add: ball_def)\n  apply (witness \"0::\\<real>\")\n  apply (auto)\n  done\n\nlemma ball_inv_sub:\n  assumes \n    a1: \"X \\<subseteq> ball N\"\n  shows \n    \"{ y | -y \\<in> X } \\<subseteq> ball N\"\n  using a1\n  by (auto simp add: ball_def)\n\nlemma ball_inv_sub':\n  assumes \n    a1: \"X \\<subseteq> ball N\"\n  shows \n    \"{ y | y \\<in> X \\<bullet> -y } \\<subseteq> ball N\"\n  using a1\n  by (auto simp add: ball_def eind_def)\n\ntext {*\n\nWe note that the reals are a linear order and hence that each natural interval is a \nlinear order.\n\n*}\n\n\ninterpretation bound_real_order: Order_Locale.order \"ball N\" \"default_order (ball N)\"\n  apply (insert default_order [OF ball_nempty])\n  apply (auto simp add: Order_Locale.order_def)\n  done\n\ntext {*\n\nWe introduce some technical lemmas about the real order.\n\n*}\n(*\nlemma default_order_elim:\n  \"default_order UNIV = (op \\<le>)\"\n  by (auto simp add: fun_eq_def)\n*)\n\nlemma neg_leI:\n  fixes x::\"\\<real>\" and y::\"\\<real>\"\n  assumes a1: \"-x \\<le> y\"\n  shows \"-y \\<le> x\"\n  apply (rule le_iff_diff_le_0 [THEN iffD2])\n  apply (insert a1 [THEN le_iff_diff_le_0 [THEN iffD1]])\n  apply (auto)\n  done\n\nlemma le_negI:\n  fixes x::\"\\<real>\" and y::\"\\<real>\"\n  assumes a1: \"x \\<le> -y\"\n  shows \"y \\<le> -x\"\n  apply (rule le_iff_diff_le_0 [THEN iffD2])\n  apply (insert a1 [THEN le_iff_diff_le_0 [THEN iffD1]])\n  apply (auto)\n  done\n\nlemma neg_le_negE:\n  fixes x::\"\\<real>\" and y::\"\\<real>\"\n  assumes a1: \"-x \\<le> -y\"\n  shows \"y \\<le> x\"\n  apply (rule le_iff_diff_le_0 [THEN iffD2])\n  apply (insert a1 [THEN le_iff_diff_le_0 [THEN iffD1]])\n  apply (auto)\n  done\n\nlemma neg_le_negI:\n  fixes x::\"\\<real>\" and y::\"\\<real>\"\n  assumes a1: \"x \\<le> y\"\n  shows \"-y \\<le> -x\"\n  apply (rule le_iff_diff_le_0 [THEN iffD2])\n  apply (insert a1 [THEN le_iff_diff_le_0 [THEN iffD1]])\n  apply (auto)\n  done\n\ntext {*\n\nThe Isabelle base library records that bounded sets do have least upper bounds. To make\nuse of this result we have to reinterpret it in terms of the order operators of \n@{text \"Order_Locale\"}.\n\n*}\n\nlemma isLub_is_lub: \"isLub UNIV X x \\<Leftrightarrow> is_lub UNIV (op \\<le>) X x\"\n  by (simp add: is_lub_def is_least_def is_ub_def isLub_def isUb_def leastP_def setle_def setge_def)\n\nlemma isUb_is_ub: \"isUb UNIV X x \\<Leftrightarrow> is_ub UNIV (op \\<le>) X x\"\n  by (simp add: is_ub_def isUb_def setle_def setge_def)\n\ntext {*\n\nThe existence of greatest lower bounds may be induced from the existence least upper bounds\nby applying the duality principle.\n\n*}\n\nlemma is_glb_negative:\n  \"is_glb UNIV (op \\<le>) X (x::\\<real>) \\<Leftrightarrow> is_lub UNIV (op \\<le>) { y | y \\<in> X \\<bullet> -y } (-x)\"\nproof (rule iffI)\n  assume b1: \"is_glb UNIV (op \\<le>) X (x::\\<real>)\"\n  show \"is_lub UNIV (op \\<le>) { y | y \\<in> X \\<bullet> -y } (-x)\"\n    apply (simp add: is_lub_def is_ub_def is_least_def)\n    apply (msafe(inference))\n  proof -\n    fix y\n    assume \"y \\<in> X\"\n    with b1 show \"x \\<le> y\"\n      by (simp add: is_glb_def is_lb_def is_greatest_def)\n  next\n    fix x' \n    assume c1 [rule_format]: \"(\\<forall> y \\<bullet> y \\<in> X \\<Rightarrow> -y \\<le> x')\"\n    from b1 show \"-x \\<le> x'\"\n      apply (simp add: is_glb_def is_lb_def is_greatest_def)\n      apply (msafe(inference))\n    proof -\n      assume d1 [rule_format]: \"(\\<forall> y \\<bullet> y \\<in> X \\<Rightarrow> x \\<le> y)\" and\n        d2 [rule_format]: \"(\\<forall> x' \\<bullet> (\\<forall> y \\<bullet> y \\<in> X \\<Rightarrow> x' \\<le> y) \\<Rightarrow> x' \\<le> x)\"\n      show \"-x \\<le> x'\"\n        apply (rule neg_leI)\n        apply (rule d2)\n        apply (rule neg_leI)\n        apply (rule c1)\n        apply (assumption)\n        done\n    qed\n  qed\nnext\n  assume b1: \"is_lub UNIV (op \\<le>) { y | y \\<in> X \\<bullet> -y } (-x)\"\n  show \"is_glb UNIV (op \\<le>) X (x::\\<real>)\"\n    apply (simp add: is_glb_def is_lb_def is_greatest_def)\n    apply (msafe(inference))\n  proof -\n    fix y\n    assume \"y \\<in> X\"\n    with b1 show \"x \\<le> y\"\n      by (simp add: is_lub_def is_ub_def is_least_def)\n  next\n    fix x' \n    assume c1 [rule_format]: \"(\\<forall> y \\<bullet> y \\<in> X \\<Rightarrow> x' \\<le> y)\"\n    from b1 show \"x' \\<le> x\"\n      apply (simp add: is_lub_def is_ub_def is_least_def)\n      apply (msafe(inference))\n    proof -\n      assume d1 [rule_format]: \"(\\<forall> y \\<bullet> y \\<in> X \\<Rightarrow> x \\<le> y)\" and\n        d2 [rule_format]: \"(\\<forall> x' \\<bullet> (\\<forall> y \\<bullet> y \\<in> X \\<Rightarrow> -y \\<le> x') \\<Rightarrow> -x \\<le> x')\"\n      show \"x' \\<le> x\"\n        apply (rule neg_le_negE)\n        apply (rule d2)\n        apply (rule neg_le_negI)\n        apply (rule c1)\n        apply (assumption)\n        done\n    qed\n  qed\nqed\n\ntext {*\n\nWe are now in a position to use the result from to infer the existence\nof least upper bounds and greatest loweer bounds for subsets of the natural intervals.\n\n*}\n\nlemma ball_Join_is_lub:\n  assumes \n    nempty: \"X \\<noteq> \\<emptyset>\" and\n    sub_ball: \"X \\<subseteq> ball N\"\n  shows \n    \"is_lub UNIV (op \\<le>) X (\\<^Join>{:UNIV:}{:(op \\<le>):} X)\"\n  apply (rule order_classD \n                [THEN partial_order.ex_Join_lub, \n                  OF _ reals_complete [simplified isLub_is_lub isUb_is_ub]])\n  using nempty sub_ball\n  apply (simp_all add: nempty_conv)\n  apply (witness \"(of_nat N)::\\<real>\")\n  apply (simp add: is_ub_def ball_def subset_def abs_le_interval_iff)\n  done\n\nlemma Meet_negative:\n  assumes \n    nempty: \"X \\<noteq> \\<emptyset>\" and\n    sub_ball: \"X \\<subseteq> ball N\"\n  shows \"(\\<^Meet>{:UNIV:}{:(op \\<le>):} X) =  - (\\<^Join>{:UNIV:}{:(op \\<le>):} { y | y \\<in> X \\<bullet> -y })\"\n  apply (simp add: Meet_def)\n  apply (rule the_equality)\n  apply (auto simp add: is_glb_negative)\n  apply (rule ball_Join_is_lub)\n  using nempty sub_ball\n  apply (simp add: eind_def)\n  apply (rule ball_inv_sub' [OF sub_ball])\nproof -\n  fix x\n  assume b1: \"is_lub UNIV (op \\<le>) { y | y \\<in> X \\<bullet> -y } (-x)\"\n  from \n      order_classD \n        [THEN partial_order.lub_unique , \n          OF ball_Join_is_lub [OF _ ball_inv_sub' [OF sub_ball]] b1] \n      b1 nempty sub_ball \n  show \n    \"x = - (\\<^Join>{:UNIV:}{:(op \\<le>):} { y | y \\<in> X \\<bullet> -y })\"\n    by (auto)\nqed\n\nlemma ball_Meet_is_glb:\n  assumes \n    nempty: \"X \\<noteq> \\<emptyset>\" and\n    sub_ball: \"X \\<subseteq> ball N\"\n  shows \n    \"is_glb UNIV (op \\<le>) X (\\<^Meet>{:UNIV:}{:(op \\<le>):} X)\"\n  apply (simp add: is_glb_negative Meet_negative[OF nempty sub_ball])\n  apply (rule ball_Join_is_lub [OF _ ball_inv_sub'])\n  using nempty sub_ball\n  apply (auto)\n  done\n\ntext {*\nFinally we show that the natural intervals form complete lattices.\n\n*}\n\ninterpretation \n  bound_real_clat: Lattice_Locale.clattice \"ball N\" \"default_order (ball N)\"\n  apply (intro_locales)\n  apply (auto simp add: \n            Lattice_Locale.clattice_axioms_def Lattice_Locale.lattice_axioms_def isLub_is_lub)\nproof -\n{ fix X \n  assume \n    sub_ball: \"X \\<subseteq> ball N\"\n  show \n      \"(\\<exists> x \\<bullet> \\<^glbp>{:(ball N):}{:(default_order (ball N)):} X x)\"\n  proof (cases \"X = \\<emptyset>\")\n    assume \n      nempty: \"X \\<noteq> \\<emptyset>\"\n    have \n      c1: \"\\<^Meet>{:UNIV:}{:(op \\<le>):} X \\<in> ball N\"\n    proof (auto simp add: ball_def abs_le_interval_iff)\n      show \n          \"-(of_nat N) \\<le> \\<^Meet>{:UNIV:}{:(op \\<le>):} X\"\n        apply (rule order_class.is_glbD2' [OF ball_Meet_is_glb [OF nempty sub_ball]])\n        using sub_ball\n        apply (auto simp add: ball_def abs_le_interval_iff)\n        done\n    next\n      from nempty obtain y where \n        d1: \"y \\<in> X\"\n        by (auto) \n      from d1 have \n          \"\\<^Meet>{:UNIV:}{:(op \\<le>):} X \n          \\<le> y\"\n        by (rule order_class.is_glbD1' [OF ball_Meet_is_glb [OF nempty sub_ball]])\n      also from d1 sub_ball have \n          \"y \n          \\<le> of_nat N\"\n        by (auto simp add: ball_def abs_le_interval_iff)        \n      finally show \n          \"\\<^Meet>{:UNIV:}{:(op \\<le>):} X \\<le> of_nat N\"\n        by (this)\n    qed   \n    from sub_ball have \n      c2 [rule_format]: \"(\\<forall> x | x \\<in> X \\<bullet> x \\<in> ball N)\"\n      by (auto)\n    show \n        \"(\\<exists> x \\<bullet> is_glb (ball N) (default_order (ball N)) X x)\"\n      apply (witness \"\\<^Meet>{:UNIV:}{:(op \\<le>):} X\")\n      apply (rule bound_real_order.is_glbI)\n      apply (auto simp add: c1 c2)\n    proof -\n      fix \n        x \n      assume \n        d1: \"x \\<in> X\"\n      show \n          \"\\<^Meet>{:UNIV:}{:(op \\<le>):} X \\<le> x\"\n        apply (rule order_class.is_glbD1' [OF _ d1])\n        apply (rule ball_Meet_is_glb [OF nempty sub_ball])\n        done\n    next\n      fix \n        a\n      assume \n        d1: \"a \\<in> ball N\" and\n        d2: \"(\\<forall> x \\<bullet> x \\<in> X \\<Rightarrow> a \\<le> x)\"\n      show \n          \"a \\<le> \\<^Meet>{:UNIV:}{:(op \\<le>):} X\"\n        apply (rule order_class.is_glbD2')\n        apply (rule ball_Meet_is_glb [OF nempty sub_ball])\n        using d2\n        apply (auto)\n        done\n    qed\n  next \n    assume \n      empty: \"X = \\<emptyset>\"\n    with sub_ball show \n        \"(\\<exists> x \\<bullet> \\<^glbp>{:(ball N):}{:(default_order (ball N)):} X x)\"\n      apply (witness \"(of_nat N)::\\<real>\")\n      apply (rule bound_real_order.is_glbI)\n      apply (auto simp add: ball_def abs_le_interval_iff)\n      done\n  qed }\nnext\n{ fix X \n  assume \n    sub_ball: \"X \\<subseteq> ball N\"\n  show \n    \"(\\<exists> x \\<bullet> \\<^lubp>{:(ball N):}{:(default_order (ball N)):} X x)\"\n  proof (cases \"X = \\<emptyset>\")\n    assume \n      nempty: \"X \\<noteq> \\<emptyset>\"\n    have \n      c1: \"\\<^Join>{:UNIV:}{:(op \\<le>):} X \\<in> ball N\"\n    proof (auto simp add: ball_def abs_le_interval_iff)\n      from nempty obtain y where \n        d1: \"y \\<in> X\"\n        by (auto) \n      from d1 sub_ball have \n          \"-(of_nat N) \n          \\<le> y\"\n        by (auto simp add: ball_def abs_le_interval_iff)\n      also from d1 have \n          \"y \n          \\<le> \\<^Join>{:UNIV:}{:(op \\<le>):} X\"\n        by (rule order_class.is_lubD1' [OF ball_Join_is_lub [OF nempty sub_ball]])\n      finally show \n          \"-(of_nat N) \\<le> \\<^Join>{:UNIV:}{:(op \\<le>):} X\"\n        by (this)\n    next\n      show \n          \"\\<^Join>{:UNIV:}{:(op \\<le>):} X \\<le> of_nat N\"\n        apply (rule order_class.is_lubD2' [OF ball_Join_is_lub [OF nempty sub_ball]])\n        using sub_ball\n        apply (auto simp add: ball_def abs_le_interval_iff)\n        done\n    qed\n    from sub_ball have \n      c2 [rule_format]: \"(\\<forall> x | x \\<in> X \\<bullet> x \\<in> ball N)\"\n      by (auto)\n    show \n        \"(\\<exists> x \\<bullet> \\<^lubp>{:(ball N):}{:(default_order (ball N)):} X x)\"\n      apply (witness \"\\<^Join>{:UNIV:}{:(op \\<le>):} X\")\n      apply (rule bound_real_order.is_lubI)\n      apply (auto simp add: c1 c2)\n    proof -\n     fix x \n      assume \n        d1: \"x \\<in> X\"\n      show \n          \"x \\<le> \\<^Join>{:UNIV:}{:(op \\<le>):} X\"\n        apply (rule order_class.is_lubD1' [OF _ d1])\n        apply (rule ball_Join_is_lub [OF nempty sub_ball])\n        done\n    next\n      fix \n        a\n      assume \n        d1: \"a \\<in> ball N\" and\n        d2: \"(\\<forall> x \\<bullet> x \\<in> X \\<Rightarrow> x \\<le> a)\"\n      show \n          \"\\<^Join>{:UNIV:}{:(op \\<le>):} X \\<le> a\"\n        apply (rule order_class.is_lubD2')\n        apply (rule ball_Join_is_lub [OF nempty sub_ball])\n        using d2\n        apply (auto)\n        done\n    qed\n  next \n    assume \n      empty: \"X = \\<emptyset>\"\n    with sub_ball show \n        \"(\\<exists> x \\<bullet> \\<^lubp>{:(ball N):}{:(default_order (ball N)):} X x)\"\n      apply (witness \"-(of_nat N)::\\<real>\")\n      apply (rule bound_real_order.is_lubI)\n      apply (auto simp add: ball_def abs_le_interval_iff)\n      done\n  qed } \nqed\n\ntext {*\n\n\\subsection{Bounded meet and join}\n\nFinally we introduce bounded meet and join operators for the reals. These may,\non occasion, be preferable to explicitly restricting your model to a natural interval.\n\n*}\n\ndefinition\n  brInf :: \"[\\<nat>, \\<real> set] \\<rightarrow> \\<real>\"\nwhere\n  brInf_def: \n    \"brInf N \n    \\<defs> (\\<olambda> X \\<bullet> \n        \\<if> (\\<exists> x | x \\<in> X \\<bullet> x < -(of_nat N)) \\<then> \n          -(of_nat N) \n        \\<else> \n          \\<^Meet>{:\\<univ>:}{:(op \\<le>):} X \n        \\<fi>)\"\n\ndefinition\n  brSup :: \"[\\<nat>, \\<real> set] \\<rightarrow> \\<real>\"\nwhere\n  brSup_def: \n    \"brSup N \n    \\<defs> (\\<olambda> X \\<bullet> \n        \\<if> (\\<exists> x | x \\<in> X \\<bullet> of_nat N < x) \n        \\<then> of_nat N \n        \\<else> \\<^Join>{:\\<univ>:}{:(op \\<le>):} X \n        \\<fi>)\"\n\nnotation (zed)\n  brInf (\"\\<^brInf>{:_:}\") and\n  brSup (\"\\<^brSup>{:_:}\")\n\nlemma brSup_is_lub:\n  assumes \n    a1: \"X \\<noteq> \\<emptyset>\" and\n    a2: \"(\\<forall> x | x \\<in> X \\<bullet> x \\<le> of_nat N)\"\n  shows \n    \"is_lub \\<univ> (op \\<le>) X (\\<^brSup>{:N:} X)\"\n  using a1 a2\n  apply (auto simp add: brSup_def)\n  apply (rule order_classD \n                [THEN partial_order.ex_Join_lub,\n                  OF _ reals_complete [simplified isLub_is_lub isUb_is_ub]])\n  apply (auto simp add: is_ub_def)\n  done\n\nlemma brInf_negative:\n  assumes \n    a1: \"X \\<noteq> \\<emptyset>\" and \n    a2: \"(\\<forall> x | x \\<in> X \\<bullet> -(of_nat N) \\<le> x)\"\n  shows \"(\\<^brInf>{:N:} X) =  - (\\<^brSup>{:N:} { y | y \\<in> X \\<bullet> -y })\"\n  using a1 a2\n  apply (auto simp add: brSup_def brInf_def)\n  apply (simp add: Meet_def)\n  apply (rule the_equality)\n  apply (auto simp add: is_glb_negative)\n  apply (rule order_classD \n                [THEN partial_order.ex_Join_lub, \n                  OF _ reals_complete [simplified isLub_is_lub isUb_is_ub]])\n  apply (auto intro: neg_leI simp add: is_ub_def)\nproof -\n  fix x\n  assume \n    b1: \"is_lub UNIV (op \\<le>) { y | y \\<in> X \\<bullet> -y } (-x)\"\n  from a2 have \n    b2: \"\\<not>(\\<exists> x | x \\<in> X \\<bullet> of_nat N < -x)\"\n    by (auto intro: neg_leI simp add: linorder_not_less)\n  have \"is_lub \\<univ> (op \\<le>) { y | y \\<in> X \\<bullet> -y } (\\<^brSup>{:N:} { y | y \\<in> X \\<bullet> -y })\"\n    apply (rule brSup_is_lub)\n    using a1 a2 b1 b2\n    apply (auto)\n    done\n  then have \n    b3: \"is_lub \\<univ> (op \\<le>) { y | y \\<in> X \\<bullet> -y } (\\<^Join>{:UNIV:}{:(op \\<le>):} { y | y \\<in> X \\<bullet> -y })\"\n    by (auto simp add: brSup_def b2)\n  from order_classD [THEN partial_order.lub_unique, OF b3 b1] \n  show \n    \"x = - (\\<^Join>{:UNIV:}{:(op \\<le>):} { y | y \\<in> X \\<bullet> -y })\"\n    by (auto)\nqed\n\nlemma brInf_is_glb:\n  assumes \n    a1: \"X \\<noteq> \\<emptyset>\" and \n    a2: \"(\\<forall> x | x \\<in> X \\<bullet> -(of_nat N) \\<le> x)\"\n  shows \"is_glb \\<univ> (op \\<le>) X (\\<^brInf>{:N:} X)\"\n  apply (simp add: is_glb_negative brInf_negative [OF a1 a2])\n  apply (rule brSup_is_lub)\n  using a1 a2\n  apply (auto)\n  done\n\n\ntext{*\n\\subsection{Real intervals}\n\nIt seems worthwhile showing that closed intervals form a complete lattice.\nThis is a small generalisation of the above.\n\n*}\n\n\nlemma interval_poset:\n\"(a::\\<real>) \\<le> b \\<turnstile> \\<^poset>{:\\<lclose>a\\<dots>b\\<rclose>:}{:default_order \\<lclose>a\\<dots>b\\<rclose>:}\"\n  apply (rule default_po)\n  apply (auto simp add: interval_defs)\ndone\n\nlemma interval_order:\n  assumes A1: \"(a::\\<real>) \\<le> b\"\n  shows\n  \"Order_Locale.order \\<lclose>a\\<dots>b\\<rclose> (default_order \\<lclose>a\\<dots>b\\<rclose>)\"\n  apply (insert A1 [THEN interval_poset], unfold_locales)\n  apply (simp_all add: partial_order_def')\n  apply (auto simp add: interval_defs)  \ndone\n\ntheorem interval_lattice:\n  assumes \n    a1: \"(a::\\<real>) \\<le> b\"\n  shows\n      \"\\<^lattice>{:\\<lclose>a\\<dots>b\\<rclose>:}{:default_order \\<lclose>a\\<dots>b\\<rclose>:}\"\n  apply (simp add: default_order_def)\n  apply (rule sub_lattice.sublatticeI' [of \"\\<univ>\"])\n  apply (msafe(inference))\nproof -\n  fix\n    x y\n  assume\n    b1: \"x \\<in> \\<lclose>a\\<dots>b\\<rclose>\" and\n    b2: \"y \\<in> \\<lclose>a\\<dots>b\\<rclose>\"\n  from b1 b2 show\n      \"x \\<^meet>{:\\<univ>:}{:(op \\<le>):} y \\<in> \\<lclose>a\\<dots>b\\<rclose>\"\n    by (simp add: \n          interval_defs inf_meet [THEN fun_cong, THEN fun_cong, of x y, symmetric] inf_real_def)\n  from b1 b2 show\n      \"x \\<^join>{:\\<univ>:}{:(op \\<le>):} y \\<in> \\<lclose>a\\<dots>b\\<rclose>\"\n    by (simp add: \n          interval_defs sup_join [THEN fun_cong, THEN fun_cong, of x y, symmetric] sup_real_def)\nnext\n  show \n      \"sub_lattice \\<univ> (op \\<le>) \\<lclose>a\\<dots>b\\<rclose>\"\n    apply (unfold_locales)\n    apply (auto simp add: nempty_conv a1 interval_defs)\n    done\nqed\n\nlemma domain_of_suborder_closed: \n    \"\\<zdom> \\<^oprel>{:\\<^subord>{:op \\<le>:}{:\\<lclose>(a::\\<real>)\\<dots>b\\<rclose>:}:} = \\<lclose>a\\<dots>b\\<rclose>\"\n  by (auto simp add: subset_order_def op2rel_def rel2op_def)\n\n\ntheorem real_ex_Sup: \n  assumes \n    a1: \"(P::real set) \\<noteq> \\<emptyset>\" and      \n    a2: \"\\<^ubp>{:\\<univ>-[\\<real>]:}{:(op \\<le>):} P u\"\n  shows\n      \"(\\<exists> Sup \\<bullet> \\<^lubp>{:\\<univ>-[\\<real>]:}{:(op \\<le>):} P Sup)\"\nproof -\n  from a1 a2 have \n      \"(\\<exists> t \\<bullet> isLub UNIV P t)\"\n    by (intro reals_complete, auto simp add:  isUb_is_ub)\n  then show \n      ?thesis\n    by (auto simp add: isLub_is_lub)\nqed\n\ntheorem real_ex_Inf: \n  assumes \n    A1: \"(P::real set) \\<noteq> \\<emptyset>\" and        \n    A2: \"\\<^lbp>{:\\<univ>-[\\<real>]:}{:(op \\<le>):} P l\"\n  shows\n      \"(\\<exists> Inf \\<bullet> \\<^glbp>{:\\<univ>-[\\<real>]:}{:(op \\<le>):} P Inf)\"\nproof -\n  let ?PM = \"{y | y \\<in> P \\<bullet> -y}\"\n  from A1 have \n    a_notempty: \"?PM \\<noteq> \\<emptyset>\" \n    by (auto)\n  from A2 have \n    a_ub: \"\\<^ubp>{:\\<univ>-[\\<real>]:}{:(op \\<le>):} ?PM (-l)\" \n    by (auto simp add: is_ub_def is_lb_def)\n  from a_ub [THEN a_notempty [THEN real_ex_Sup]] obtain Sup where \n    a4: \"\\<^lubp>{:\\<univ>-[\\<real>]:}{:(op \\<le>):} ?PM Sup\" \n    by auto\n  show \n      ?thesis\n    apply (witness \"-Sup\")\n    apply (simp add: is_glb_negative)\n    apply (rule a4)\n  done\nqed\n\n\ntheorem real_interval_clattice:\n  assumes \n    A1: \"(a::\\<real>) \\<le> b\"\n  shows\n      \"\\<^clattice>{:\\<lclose>a\\<dots>b\\<rclose>:}{:default_order \\<lclose>a\\<dots>b\\<rclose>:}\"\nproof-\n  interpret \n    po_interval: partial_order \"\\<lclose>a\\<dots>b\\<rclose>\" \"default_order \\<lclose>a\\<dots>b\\<rclose>\"\n    by (rule default_po, auto simp only: A1 interval_defs)\n  show \n      ?thesis\n  proof (rule po_interval.clatticeI)\n    fix \n      X :: \"\\<real> set\"\n    assume \n      A2: \"X \\<subseteq> \\<lclose>a\\<dots>b\\<rclose>\"\n    show\n        \"(\\<exists> z \\<bullet> \\<^glbp>{:\\<lclose>a\\<dots>b\\<rclose>:}{:(default_order \\<lclose>a\\<dots>b\\<rclose>):} X z)\"\n    proof (cases \"X = \\<emptyset>\")\n      assume \n        A11: \"X = \\<emptyset>\"\n      from A1 A2 A11 show \n          ?thesis\n        by (auto simp add: is_glb_def is_lb_def is_greatest_def interval_defs)\n    next\n      assume \n        A11: \"X \\<noteq> \\<emptyset>\"\n      from A11 obtain x where \n        R0': \"x \\<in> X\" \n        by auto \n      from A1 A2 A11 have \n        R0'': \"\\<^lbp>{:\\<univ>-[\\<real>]:}{:(op \\<le>):} X a\"\n        by (intro order_class.is_lbI, auto simp add: interval_defs)\n      from R0'' [THEN A11 [THEN real_ex_Inf]] obtain Inf where \n        R1': \"\\<^glbp>{:\\<univ>-[\\<real>]:}{:(op \\<le>):} X Inf\"\n        by auto\n      have  \n        R2': \"Inf \\<in> \\<lclose>a\\<dots>b\\<rclose>\"\n      proof -\n        have \n          Rb1: \"a \\<le> Inf\" \n          apply (rule R1' [THEN order_class.is_glbD2'], simp)\n          apply (rule R0'' [THEN order_class.is_lbD], simp)\n          done\n        from R0' have \n            \"Inf \\<le> x\" \n          by (rule R1' [THEN order_class.is_glbD1'])\n        with R0' Rb1 A1 A2 show \n          ?thesis \n          by (auto simp add: interval_defs)\n      qed\n    \n      with A1 A2 show\n          ?thesis\n        apply (witness \"Inf\")\n        apply (rule po_interval.is_glbI, simp_all add: default_order_conv)\n        apply (msafe(inference))\n        apply (simp add: subset_eq interval_defs)\n        apply (simp add: subset_eq interval_defs)\n        apply (rule R1' [THEN order_class.is_glbD1'], simp)\n        apply (rule R1' [THEN order_class.is_glbD2'], auto)\n        done\n    qed\n  next\n    fix \n      X :: \"\\<real> set\"\n    assume \n      A2: \"X \\<subseteq> \\<lclose>a\\<dots>b\\<rclose>\"\n    show\n        \"(\\<exists> z \\<bullet> \\<^lubp>{:\\<lclose>a\\<dots>b\\<rclose>:}{:(default_order \\<lclose>a\\<dots>b\\<rclose>):} X z)\"\n    proof (cases \"X = \\<emptyset>\")\n      assume \n        A11: \"X = \\<emptyset>\"\n      from A1 A2 A11 show \n          ?thesis\n        by (auto simp add: is_lub_def is_ub_def is_least_def interval_defs)\n    next\n      assume \n        A11: \"X \\<noteq> \\<emptyset>\"\n      from A11 obtain x where \n        R0': \"x \\<in> X\" \n        by auto\n      from A1 A2 A11 have \n        R0'': \"\\<^ubp>{:\\<univ>-[\\<real>]:}{:(op \\<le>):} X b\"\n        by (intro order_class.is_ubI, auto simp add: interval_defs)\n      from R0'' [THEN A11 [THEN real_ex_Sup]] obtain Sup where \n        R1': \"\\<^lubp>{:\\<univ>-[\\<real>]:}{:(op \\<le>):} X Sup\"\n        by auto\n      have \n        R2': \"Sup \\<in> \\<lclose>a\\<dots>b\\<rclose>\"\n      proof-\n        have \n          Rb1: \"Sup \\<le> b\" \n          apply (rule R1' [THEN order_class.is_lubD2'], simp)\n          apply (rule R0'' [THEN order_class.is_ubD], simp)\n          done\n        from R0' have \n          \"x \\<le> Sup\" \n          by (rule R1' [THEN order_class.is_lubD1'])\n        with R0' Rb1 A1 A2 show \n            ?thesis \n          by (auto simp add: interval_defs)\n      qed\n    \n      with A1 A2 show \n          ?thesis\n        apply (witness \"Sup\")\n        apply (rule po_interval.is_lubI, simp_all add: default_order_conv)\n        apply (msafe(inference))\n        apply (simp add: subset_eq)\n        apply (simp add: subset_eq)\n        apply (rule R1' [THEN order_class.is_lubD1'], simp)\n        apply (rule R1' [THEN order_class.is_lubD2'], auto)\n        done\n    qed\n  qed\nqed\n\n\nend\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/Lattice_Instance.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587846530938, "lm_q2_score": 0.8175744806385543, "lm_q1q2_score": 0.7266265017757059}}
{"text": "(* \n  Title: The Powerset Monad, State Transformers and Predicate Transformers\n  Author: Georg Struth \n  Maintainer: Georg Struth <g.struth@sheffield.ac.uk> \n*)\n\nsection \\<open>The Powerset Monad, State Transformers and Predicate Transformers\\<close>\n\ntheory Powerset_Monad\n\nimports \"Order_Lattice_Props.Order_Lattice_Props\" \n\nbegin          \n\nnotation relcomp (infixl \";\" 75) \n  and image (\"\\<P>\")\n\nsubsection \\<open>The Powerset Monad\\<close>\n\ntext \\<open>First I recall functoriality of the powerset functor.\\<close>\n\nlemma P_func1: \"\\<P> (f \\<circ> g) = \\<P> f \\<circ> \\<P> g\"\n  unfolding fun_eq_iff by force\n\nlemma P_func2: \"\\<P> id = id\"\n  by simp\n\ntext \\<open>Isabelle' type systems doesn't allow formalising arbitrary monads, but instances such as the powerset monad\ncan still be developed.\\<close>\n\nabbreviation eta :: \"'a \\<Rightarrow> 'a set\" (\"\\<eta>\") where\n  \"\\<eta> \\<equiv> (\\<lambda>x. {x})\"\n\nabbreviation mu :: \"'a set set \\<Rightarrow> 'a set\" (\"\\<mu>\") where\n  \"\\<mu> \\<equiv> Union\"\n\ntext \\<open>$\\eta$ and $\\mu$ are natural transformations.\\<close>\n\nlemma eta_nt: \"\\<P> f \\<circ> \\<eta> = \\<eta> \\<circ> id f\"\n  by fastforce\n  \nlemma mu_nt: \"\\<mu> \\<circ> (\\<P> \\<circ> \\<P>) f = (\\<P> f) \\<circ> \\<mu>\" \n  by fastforce\n\ntext \\<open>They satisfy the following coherence conditions. Explicit typing clarifies that $\\eta$ and $\\mu$ have different type in these expressions.\\<close>\n \nlemma pow_assoc: \"(\\<mu>::'a set set \\<Rightarrow> 'a set) \\<circ> \\<P> (\\<mu>::'a set set \\<Rightarrow> 'a set) = (\\<mu> ::'a set set \\<Rightarrow> 'a set) \\<circ> (\\<mu>::'a set set set \\<Rightarrow> 'a set set)\"\n  using fun_eq_iff by fastforce\n\nlemma pow_un1: \"(\\<mu>::'a set set \\<Rightarrow> 'a set) \\<circ> (\\<P> (\\<eta>:: 'a  \\<Rightarrow> 'a set)) = (id::'a set  \\<Rightarrow> 'a set)\"\n  using fun_eq_iff by fastforce\n  \nlemma pow_un2: \"(\\<mu>::'a set set \\<Rightarrow> 'a set) \\<circ> (\\<eta>::'a set \\<Rightarrow> 'a set set) = (id::'a set \\<Rightarrow> 'a set)\"\n  using fun_eq_iff by fastforce\n\ntext \\<open>Thus the powerset monad is indeed a monad.\\<close>\n\n\nsubsection \\<open>Kleisli Category of the Powerset Monad\\<close>\n\ntext \\<open>Next I define the Kleisli composition and Kleisli lifting (Kleisli extension) of Kleisli arrows. \nThe Kleisli lifting turns Kleisli arrows into forward predicate transformers.\\<close>\n\ndefinition kcomp :: \"('a \\<Rightarrow> 'b set) \\<Rightarrow> ('b \\<Rightarrow> 'c set) \\<Rightarrow> ('a  \\<Rightarrow> 'c set)\" (infixl \"\\<circ>\\<^sub>K\" 75) where\n  \"f \\<circ>\\<^sub>K g = \\<mu> \\<circ> \\<P> g \\<circ> f\"     \n\nlemma kcomp_prop: \"(f \\<circ>\\<^sub>K g) x = (\\<Squnion>y \\<in> f x. g y)\"\n  by (simp add: kcomp_def)\n\ndefinition klift :: \"('a \\<Rightarrow> 'b set) \\<Rightarrow> 'a set \\<Rightarrow> 'b set\" (\"_\\<^sup>\\<dagger>\" [101] 100) where\n  \"f\\<^sup>\\<dagger> = \\<mu> \\<circ> \\<P> f\"\n\nlemma klift_prop: \"(f\\<^sup>\\<dagger>) X = (\\<Squnion>x \\<in> X. f x)\" \n  by (simp add: klift_def)\n\nlemma kcomp_klift: \"f \\<circ>\\<^sub>K g = g\\<^sup>\\<dagger> \\<circ> f\"\n  unfolding kcomp_def klift_def by simp\n\nlemma klift_prop1: \"(f\\<^sup>\\<dagger> \\<circ> g)\\<^sup>\\<dagger> = f\\<^sup>\\<dagger> \\<circ> g\\<^sup>\\<dagger>\" \n  unfolding fun_eq_iff klift_def by simp\n\nlemma klift_eta_inv1 [simp]: \"f\\<^sup>\\<dagger> \\<circ> \\<eta> = f\"\n  unfolding fun_eq_iff klift_def by simp\n\nlemma klift_eta_pres [simp]: \"\\<eta>\\<^sup>\\<dagger> = (id::'a set \\<Rightarrow> 'a set)\"\n  unfolding fun_eq_iff klift_def by simp\n\nlemma klift_id_pres [simp]: \"id\\<^sup>\\<dagger> = \\<mu>\"\n  unfolding klift_def by simp\n\nlemma kcomp_assoc: \"(f \\<circ>\\<^sub>K g) \\<circ>\\<^sub>K h = f \\<circ>\\<^sub>K (g \\<circ>\\<^sub>K h)\"\n  unfolding kcomp_klift klift_prop1 by force\n\nlemma kcomp_idl [simp]: \"\\<eta> \\<circ>\\<^sub>K f = f\"\n  unfolding kcomp_klift by simp\n\nlemma kcomp_idr [simp]: \"f \\<circ>\\<^sub>K \\<eta> = f\"\n  unfolding kcomp_klift by simp\n\ntext \\<open>In the following interpretation statement, types are restricted.\nThis is needed for defining iteration.\\<close>\n\ninterpretation kmon: monoid_mult \"\\<eta>\" \"(\\<circ>\\<^sub>K)\"\n  by unfold_locales (simp_all add: kcomp_assoc)\n \ntext \\<open>Next I show that $\\eta$ is a (contravariant) functor from Set into the Kleisli category of the powerset monad.\nIt simply turns functions into Kleisli arrows.\\<close>\n\nlemma eta_func1: \"\\<eta> \\<circ> (f \\<circ> g) = (\\<eta> \\<circ> g) \\<circ>\\<^sub>K (\\<eta> \\<circ> f)\"\n  unfolding fun_eq_iff kcomp_def by simp\n\n\nsubsection \\<open>Eilenberg-Moore Algebra\\<close>\n\ntext \\<open>It is well known that the Eilenberg-Moore algebras of the powerset monad form complete join semilattices (hence Sup-lattices).\\<close>\n\ntext \\<open>First I verify that every complete lattice with structure map Sup satisfies the laws of Eilenberg-Moore algebras.\\<close>\n\nnotation Sup (\"\\<sigma>\")\n\nlemma em_assoc [simp]: \"\\<sigma> \\<circ> \\<P> (\\<sigma>::'a::complete_lattice set \\<Rightarrow> 'a) = \\<sigma> \\<circ> \\<mu>\"\n  apply (standard, rule antisym)\n   apply (simp add: SUP_least Sup_subset_mono Sup_upper)\n  by (metis (no_types, lifting) SUP_upper2 Sup_least Sup_upper UnionE comp_def)\n\nlemma em_id [simp]: \"\\<sigma> \\<circ> \\<eta> = (id::'a::complete_lattice \\<Rightarrow> 'a)\"\n  by (simp add: fun_eq_iff)\n\ntext\\<open>Hence every Sup-lattice is an Eilenberg-Moore algebra for the powerset monad. \nThe morphisms between Eilenberg-Moore algebras of the powerset monad are Sup-preserving maps. \nIn particular, powersets with structure map $\\mu$ form an Eilenberg-Moore algebra (in fact the free one):\\<close>\n\nlemma em_mu_assoc [simp]: \"\\<mu> \\<circ> \\<P> \\<mu> = \\<mu> \\<circ> \\<mu>\"\n  by simp\n \nlemma em_mu_id [simp]: \"\\<mu> \\<circ> \\<eta> = id\"\n  by simp\n\ntext \\<open>Next I show that every Eilenberg-Moore algebras for the \npowerset functor is a Sup-lattice.\\<close>\n\nclass eilenberg_moore_pow = \n  fixes smap :: \"'a set \\<Rightarrow> 'a\"\n  assumes smap_assoc: \"smap \\<circ> \\<P> smap = smap \\<circ> \\<mu>\"\n  and smap_id: \"smap \\<circ> \\<eta> = id\"\n\nbegin\n\ndefinition \"sleq = (\\<lambda>x y. smap {x,y} = y)\"\n\ndefinition \"sle = (\\<lambda>x y. sleq x y \\<and> y \\<noteq> x)\"\n\nlemma smap_un1: \"smap {x, smap Y} = smap ({x} \\<union> Y)\" \nproof-\n  have \"smap {x, smap Y} = smap {smap {x}, smap Y}\"\n    by (metis comp_apply id_apply smap_id)\n  also have \"... = (smap \\<circ> \\<P> smap) {{x}, Y}\"\n    by simp\n  finally show ?thesis\n    using local.smap_assoc by auto\nqed\n\nlemma smap_comm: \"smap {x, smap Y} = smap {smap Y, x}\"\n  by (simp add: insert_commute)\n\nlemma smap_un2: \"smap {smap X, y} = smap (X \\<union> {y})\"\n  using smap_comm smap_un1 by auto \n\nlemma sleq_refl: \"sleq x x\"\n  by (metis id_apply insert_absorb2 local.smap_id o_apply sleq_def)\n\n\n\nlemma sleq_antisym: \"sleq x y \\<Longrightarrow> sleq y x \\<Longrightarrow> x = y\"\n  by (simp add: insert_commute sleq_def)\n\nlemma smap_ub: \"x \\<in> A \\<Longrightarrow> sleq x (smap A)\"\n  using insert_absorb sleq_def smap_un1 by fastforce\n\nlemma smap_lub: \"(\\<And>x. x \\<in> A \\<Longrightarrow> sleq x z) \\<Longrightarrow> sleq (smap A) z\"\nproof-\n  assume h: \"\\<And>x. x \\<in> A \\<Longrightarrow> sleq x z\"\n  have \"smap {smap A, z} = smap (A \\<union> {z})\"\n    by (simp add: smap_un2)\n  also have \"... = smap ((\\<Union>x \\<in> A. {x,z})  \\<union> {z})\" \n    by (rule_tac f=smap in arg_cong, auto)\n  also have \"... = smap {(smap \\<circ> \\<mu>) {{x,z} |x. x \\<in> A}, z}\"\n    by (simp add: Setcompr_eq_image smap_un2)\n  also have \"... = smap {(smap \\<circ> \\<P> smap) {{x,z} |x. x \\<in> A}, z}\"\n    by (simp add: local.smap_assoc)\n  also have \"... = smap {smap {smap {x,z} |x. x \\<in> A}, z}\"\n    by (simp add: Setcompr_eq_image image_image)\n  also have \"... = smap {smap {z |x. x \\<in> A}, z}\"\n    by (metis h sleq_def)\n  also have \"... = smap ({z |x. x \\<in> A} \\<union> {z})\"\n    by (simp add: smap_un2)\n  also have \"... = smap {z}\"\n     by (rule_tac f=smap in arg_cong, auto)\n   finally show ?thesis\n     using sleq_def sleq_refl by auto\n qed\n\nsublocale smap_Sup_lat: Sup_lattice smap sleq sle\n  by unfold_locales (simp_all add: sleq_refl sleq_antisym sleq_trans smap_ub smap_lub)\n\ntext \\<open>Hence every complete lattice is an Eilenberg-Moore algebra of $\\mathcal{P}$.\\<close>\n\nno_notation Sup (\"\\<sigma>\")\n\nend\n\n\nsubsection \\<open>Isomorphism between Kleisli Category and Rel\\<close>\n\ntext \\<open>This is again well known---the isomorphism is essentially curry vs uncurry. Kleisli arrows are nondeterministic functions; \nthey are also known as state transformers.  Binary relations are very well developed in Isabelle; Kleisli composition of Kleisli \narrows isn't. Ideally one should therefore use the isomorphism to transport theorems from relations to Kleisli arrows automatically. \nI spell out the isomorphisms and prove that the full quantalic structure, that is, complete lattices plus compositions, \nis preserved by the isomorphisms.\\<close>\n\nabbreviation kzero :: \"'a \\<Rightarrow> 'b set\" (\"\\<zeta>\") where\n  \"\\<zeta> \\<equiv> (\\<lambda>x::'a. {})\"\n\ntext \\<open>First I define the morphisms. The second one is nothing but the graph of a function.\\<close>\n\ndefinition r2f :: \"('a \\<times> 'b) set \\<Rightarrow> 'a \\<Rightarrow> 'b set\" (\"\\<F>\") where\n  \"\\<F> R = Image R \\<circ> \\<eta>\" \n\ndefinition f2r :: \"('a \\<Rightarrow> 'b set) \\<Rightarrow> ('a \\<times> 'b) set\" (\"\\<R>\") where\n  \"\\<R> f = {(x,y). y \\<in> f x}\"\n\ntext \\<open>The functors form a bijective pair.\\<close>\n\nlemma r2f2r_inv1 [simp]: \"\\<R> \\<circ> \\<F> = id\"\n  unfolding f2r_def r2f_def by force\n\nlemma f2r2f_inv2 [simp]: \"\\<F> \\<circ> \\<R> = id\"\n  unfolding f2r_def r2f_def by force\n\nlemma r2f_f2r_galois: \"(\\<R> f = R) = (\\<F> R = f)\"\n  by (force simp: f2r_def r2f_def)\n\nlemma r2f_f2r_galois_var: \"(\\<R> \\<circ> f = R) = (\\<F> \\<circ> R = f)\"\n  by (force simp: f2r_def r2f_def)\n\nlemma r2f_f2r_galois_var2: \"(f \\<circ> \\<R> = R) = (R \\<circ> \\<F> = f)\"\n  by (metis (no_types, hide_lams) comp_id f2r2f_inv2 map_fun_def o_assoc r2f2r_inv1)\n\nlemma r2f_inj: \"inj \\<F>\"\n  by (meson inj_on_inverseI r2f_f2r_galois)\n\nlemma f2r_inj: \"inj \\<R>\"\n  unfolding inj_def using r2f_f2r_galois by metis\n\nlemma r2f_mono: \"\\<forall>f g. \\<F> \\<circ> f = \\<F> \\<circ> g \\<longrightarrow> f = g\"\n  by (force simp: fun_eq_iff r2f_def)\n\nlemma f2r_mono: \"\\<forall>f g. \\<R> \\<circ> f = \\<R> \\<circ> g \\<longrightarrow> f = g\" \n  by (force simp: fun_eq_iff f2r_def)\n\nlemma r2f_mono_iff: \"(\\<F> \\<circ> f = \\<F> \\<circ> g) = (f = g)\"\n  using r2f_mono by blast\n\nlemma f2r_mono_iff : \"(\\<R> \\<circ> f = \\<R> \\<circ> g) = (f = g)\"\n  using f2r_mono by blast\n\nlemma r2f_inj_iff: \"(\\<R> f = \\<R> g) = (f = g)\"\n  by (simp add: f2r_inj inj_eq)\n\nlemma f2r_inj_iff: \"(\\<F> R = \\<F> S) = (R = S)\"\n  by (simp add: r2f_inj inj_eq)\n\nlemma r2f_surj: \"surj \\<F>\"\n  by (metis r2f_f2r_galois surj_def)\n\nlemma f2r_surj: \"surj \\<R>\"\n  using r2f_f2r_galois by auto\n\nlemma r2f_epi: \"\\<forall>f g. f \\<circ> \\<F> = g \\<circ> \\<F> \\<longrightarrow> f = g\"\n  by (metis r2f_f2r_galois_var2)\n\nlemma f2r_epi: \"\\<forall>f g. f \\<circ> \\<R> = g \\<circ> \\<R> \\<longrightarrow> f = g\"\n  by (metis r2f_f2r_galois_var2)\n\nlemma r2f_epi_iff: \"(f \\<circ> \\<F> = g \\<circ> \\<F>) = (f = g)\"\n  using r2f_epi by blast\n\nlemma f2r_epi_iff: \"(f \\<circ> \\<R> = g \\<circ> \\<R>) = (f = g)\"\n  using f2r_epi by blast\n\nlemma r2f_bij: \"bij \\<F>\"\n  by (simp add: bijI r2f_inj r2f_surj)\n\nlemma f2r_bij: \"bij \\<R>\"\n  by (simp add: bij_def f2r_inj f2r_surj)\n\ntext \\<open>r2f is essentially curry and f2r is uncurry, yet in Isabelle the type of sets and predicates \n(boolean-valued functions) are different. Collect transforms predicates into sets and the following function\nsets into predicates:\\<close>\n\nabbreviation \"s2p X \\<equiv> (\\<lambda>x. x \\<in> X)\"\n\nlemma r2f_curry: \"r2f R = Collect \\<circ> (curry \\<circ> s2p) R\"\n  by (force simp: r2f_def fun_eq_iff curry_def)\n\nlemma f2r_uncurry: \"f2r f = (Collect \\<circ> case_prod) (s2p \\<circ> f)\"\n  by (force simp: fun_eq_iff f2r_def)\n\ntext \\<open>Uncurry is case-prod in Isabelle.\\<close>\n\ntext \\<open>f2r and r2f preserve the quantalic structures of relations and Kleisli arrows. In particular they are functors.\\<close>\n\nlemma r2f_comp_pres: \"\\<F> (R ; S) = \\<F> R \\<circ>\\<^sub>K \\<F> S\"\n  unfolding fun_eq_iff r2f_def kcomp_def by force\n\nlemma r2f_Id_pres [simp]: \"\\<F> Id = \\<eta>\"\n  unfolding fun_eq_iff r2f_def by simp\n\nlemma r2f_Sup_pres: \"Sup_pres \\<F>\"\n  unfolding fun_eq_iff r2f_def by force\n\nlemma r2f_Sup_pres_var: \"\\<F> (\\<Union>R) = (\\<Squnion>r \\<in> R. \\<F> r)\" \n  unfolding r2f_def by force\n\nlemma r2f_sup_pres: \"sup_pres \\<F>\"\n  unfolding r2f_def by force\n\nlemma r2f_Inf_pres: \"Inf_pres \\<F>\"\n  unfolding fun_eq_iff r2f_def by force\n\nlemma r2f_Inf_pres_var: \"\\<F> (\\<Sqinter>R) = (\\<Sqinter>r \\<in> R. \\<F> r)\" \n  unfolding r2f_def by force\n\nlemma r2f_inf_pres: \"inf_pres \\<F>\"\n  unfolding r2f_def by force\n\nlemma r2f_bot_pres: \"bot_pres \\<F>\"\n  by (metis SUP_empty Sup_empty r2f_Sup_pres_var)\n\nlemma r2f_top_pres: \"top_pres \\<F>\"\n  by (metis Sup_UNIV r2f_Sup_pres_var r2f_surj)\n\nlemma r2f_leq: \"(R \\<subseteq> S) = (\\<F> R \\<le> \\<F> S)\"\n  by (metis le_iff_sup r2f_f2r_galois r2f_sup_pres)\n\ntext \\<open>Dual statements for f2r hold. Can one automate this?\\<close>\n \nlemma f2r_kcomp_pres: \"\\<R> (f \\<circ>\\<^sub>K g) = \\<R> f ; \\<R> g\"\n  by (simp add: r2f_f2r_galois r2f_comp_pres pointfree_idE)\n\nlemma f2r_eta_pres [simp]: \"\\<R> \\<eta> = Id\"\n  by (simp add: r2f_f2r_galois) \n\nlemma f2r_Sup_pres:\"Sup_pres \\<R>\"\n  by (auto simp: r2f_f2r_galois_var comp_assoc[symmetric] r2f_Sup_pres image_comp)\n\nlemma f2r_Sup_pres_var: \"\\<R> (\\<Squnion>F) = (\\<Squnion>f \\<in> F. \\<R> f)\"\n  by (simp add: r2f_f2r_galois r2f_Sup_pres_var image_comp)\n\nlemma f2r_sup_pres: \"sup_pres \\<R>\"\n  by (simp add: r2f_f2r_galois r2f_sup_pres pointfree_idE)\n\nlemma f2r_Inf_pres: \"Inf_pres \\<R>\"\n  by (auto simp: r2f_f2r_galois_var comp_assoc[symmetric] r2f_Inf_pres image_comp)\n\nlemma f2r_Inf_pres_var: \"\\<R> (\\<Sqinter>F) = (\\<Inter>f \\<in> F. \\<R> f)\"\n  by (simp add: r2f_f2r_galois r2f_Inf_pres_var image_comp)\n\nlemma f2r_inf_pres: \"inf_pres \\<R>\"\n  by (simp add: r2f_f2r_galois r2f_inf_pres pointfree_idE)\n\nlemma f2r_bot_pres: \"bot_pres \\<R>\"\n  by (simp add: r2f_bot_pres r2f_f2r_galois)\n\nlemma f2r_top_pres: \"top_pres \\<R>\"\n  by (simp add: r2f_f2r_galois r2f_top_pres)\n\n\n\ntext \\<open>Relational subidentities are isomorphic to particular Kleisli arrows.\\<close>\n\nlemma r2f_Id_on1: \"\\<F> (Id_on X) = (\\<lambda>x. if x \\<in> X then {x} else {})\"\n  by (force simp add: fun_eq_iff r2f_def Id_on_def)\n\nlemma r2f_Id_on2: \"\\<F> (Id_on X) \\<circ>\\<^sub>K f = (\\<lambda>x. if x \\<in> X then f x else {})\"\n  unfolding fun_eq_iff Id_on_def r2f_def kcomp_def by auto\n\nlemma r2f_Id_on3: \"f \\<circ>\\<^sub>K \\<F> (Id_on X) = (\\<lambda>x. X \\<inter> f x)\"\n  unfolding kcomp_def r2f_def Id_on_def fun_eq_iff by auto\n\n\nsubsection \\<open>The opposite Kleisli Category\\<close>\n\ntext \\<open>Opposition is funtamental for categories; yet hard to realise in Isabelle in general. Due to the access to relations,\nthe Kleisli category of the powerset functor is an exception.\\<close>\n\nnotation converse (\"\\<smile>\")\n\ndefinition kop :: \"('a \\<Rightarrow> 'b set) \\<Rightarrow> 'b \\<Rightarrow> 'a set\" (\"op\\<^sub>K\") where\n  \"op\\<^sub>K = \\<F> \\<circ> (\\<smile>) \\<circ> \\<R>\"\n\ntext \\<open>Kop is a contravariant functor.\\<close>\n\nlemma kop_contrav: \"op\\<^sub>K (f \\<circ>\\<^sub>K g) = op\\<^sub>K g \\<circ>\\<^sub>K op\\<^sub>K f\"\n  unfolding kop_def r2f_def f2r_def converse_def kcomp_def fun_eq_iff comp_def by fastforce\n\nlemma kop_func2 [simp]: \"op\\<^sub>K \\<eta> = \\<eta>\"\n  unfolding kop_def r2f_def f2r_def converse_def comp_def fun_eq_iff by fastforce\n\n\n\nlemma converse_galois: \"((\\<smile>) \\<circ> f = g) = ((\\<smile>) \\<circ> g = f)\"\n  by auto\n\nlemma converse_galois2: \"(f \\<circ> (\\<smile>) = g) = (g \\<circ> (\\<smile>) = f)\"\n  apply (simp add: fun_eq_iff)\n  by (metis converse_converse)\n\nlemma converse_mono_iff: \"((\\<smile>) \\<circ> f = (\\<smile>) \\<circ> g) = (f = g)\"\n  using converse_galois by force\n\nlemma converse_epi_iff: \"(f \\<circ> (\\<smile>) = g \\<circ> (\\<smile>)) = (f = g)\"\n  using converse_galois2 by force\n\nlemma kop_idem [simp]: \"op\\<^sub>K \\<circ> op\\<^sub>K = id\" \n  unfolding kop_def comp_def fun_eq_iff by (metis converse_converse id_apply r2f_f2r_galois)\n\nlemma kop_galois: \"(op\\<^sub>K f = g) = (op\\<^sub>K g = f)\"\n  by (metis kop_idem pointfree_idE)\n\nlemma kop_galois_var: \"(op\\<^sub>K \\<circ> f = g) = (op\\<^sub>K \\<circ> g = f)\"\n  by (auto simp: kop_def f2r_def r2f_def converse_def fun_eq_iff)   \n\nlemma kop_galois_var2: \"(f \\<circ> op\\<^sub>K = g) = (g \\<circ> op\\<^sub>K = f)\"\n  by (metis (no_types, hide_lams) comp_assoc comp_id kop_idem)\n\nlemma kop_inj: \"inj op\\<^sub>K\"\n  unfolding inj_def by (simp add: f2r_inj_iff kop_def r2f_inj_iff)\n\nlemma kop_inj_iff: \"(op\\<^sub>K f = op\\<^sub>K g) = (f = g)\"\n  by (simp add: inj_eq kop_inj)\n\nlemma kop_surj: \"surj op\\<^sub>K\"\n  unfolding surj_def by (metis kop_galois)\n\nlemma kop_bij: \"bij op\\<^sub>K\"\n  by (simp add: bij_def kop_inj kop_surj)\n\nlemma kop_mono: \"(op\\<^sub>K \\<circ> f = op\\<^sub>K \\<circ> g) \\<Longrightarrow> (f = g)\"\n  by (simp add: fun.inj_map inj_eq kop_inj)\n\nlemma kop_mono_iff: \"(op\\<^sub>K \\<circ> f = op\\<^sub>K \\<circ> g) = (f = g)\"\n  using kop_mono by blast\n\nlemma kop_epi: \"(f \\<circ> op\\<^sub>K = g \\<circ> op\\<^sub>K) \\<Longrightarrow> (f = g)\"\n  by (metis kop_galois_var2)\n\nlemma kop_epi_iff: \"(f \\<circ> op\\<^sub>K = g \\<circ> op\\<^sub>K) = (f = g)\"\n  using kop_epi by blast\n\nlemma Sup_pres_kop: \"Sup_pres op\\<^sub>K\"\n  unfolding kop_def fun_eq_iff comp_def r2f_def f2r_def converse_def by auto\n\nlemma Inf_pres_kop: \"Inf_pres op\\<^sub>K\"\n  unfolding kop_def fun_eq_iff comp_def r2f_def f2r_def converse_def 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/Transformer_Semantics/Powerset_Monad.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8887587846530938, "lm_q2_score": 0.8175744761936437, "lm_q1q2_score": 0.7266264978252525}}
{"text": "theory Clauses imports\n  Main\n  \"../Containers\"\nbegin\n\ntype_synonym literal = \"nat \\<times> bool\"\ntype_synonym clause = \"literal set\"\ntype_synonym cnf = \"clause set\"\n\ndatatype bexp\n  = Var nat\n  | not bexp\n  | Or bexp bexp (infixl \"or\" 110)\n  | And bexp bexp (infixl \"and\" 120)\n\ndeclare [[coercion Var]] [[coercion_enabled]]\n\ndeclare strong_SUP_cong[fundef_cong del]\nfunction cnf :: \"bexp \\<Rightarrow> cnf\"\nwhere\n  \"cnf v = {{(v, True)}}\"\n| \"cnf (b and b') = cnf b \\<union> cnf b'\"\n| \"cnf (b or b') = (\\<Union>c \\<in> cnf b. (\\<lambda>c'. c \\<union> c') ` cnf b')\"\n| \"cnf (not v) = {{(v, False)}}\"\n| \"cnf (not (not b)) = cnf b\"\n| \"cnf (not (b and b')) = cnf (not b or not b')\"\n| \"cnf (not (b or b')) = cnf (not b and not b')\"\nby pat_completeness simp_all\ntermination by(relation \"measure (rec_bexp (\\<lambda>_. 1) (\\<lambda>_ n. 3 * n + 1) (\\<lambda>_ _ n m. n + m + 1) (\\<lambda>_ _ n m. n + m + 1))\") simp_all\ndeclare strong_SUP_cong[fundef_cong]\n\ndefinition test \nwhere \n  \"test = \n  (1 and 2) or (not 1 and not 2) or\n  (3 and 4) or (not 3 and not 4) or\n  (5 and 6) or (not 5 and not 6) or\n  (7 and 8) or (not 7 and not 8) or\n  (9 and 10) or (not 9 and not 10) or\n  (11 and 12) or (not 11 and not 12) or\n  (1 and 2) or (3 and 4) or\n  (1 and 3) or (2 and 4)\"\n\nvalue \"cnf test = {}\"\n\ntext {* Sanity check for correctness *}\n\ntype_synonym env = \"nat \\<Rightarrow> bool\"\n\nprimrec eval_bexp :: \"env \\<Rightarrow> bexp \\<Rightarrow> bool\" (\"_ \\<Turnstile> _\" [100, 100] 70)\nwhere\n  \"\\<Phi> \\<Turnstile> v \\<longleftrightarrow> \\<Phi> v\"\n| \"\\<Phi> \\<Turnstile> not b \\<longleftrightarrow> \\<not> \\<Phi> \\<Turnstile> b\"\n| \"\\<Phi> \\<Turnstile> b and b' \\<longleftrightarrow> \\<Phi> \\<Turnstile> b \\<and> \\<Phi> \\<Turnstile> b'\"\n| \"\\<Phi> \\<Turnstile> b or b' \\<longleftrightarrow> \\<Phi> \\<Turnstile> b \\<or> \\<Phi> \\<Turnstile> b'\"\n\ndefinition eval_cnf :: \"env \\<Rightarrow> cnf \\<Rightarrow> bool\" (\"_ \\<turnstile> _\" [100, 100] 70)\nwhere \"\\<Phi> \\<turnstile> F \\<longleftrightarrow> (\\<forall>C \\<in> F. \\<exists>(n, b) \\<in> C. \\<Phi> n = b)\"\n\nlemma cnf_correct: \"\\<Phi> \\<turnstile> cnf b \\<longleftrightarrow> \\<Phi> \\<Turnstile> b\"\nproof(rule sym, induction b rule: cnf.induct)\n  case 2 show ?case by(simp add: \"2.IH\")(auto simp add: eval_cnf_def)\nnext\n  case 3 then show ?case\n    by (auto simp add: \"3.IH\" eval_cnf_def split_beta) blast+\nqed(auto simp add: eval_cnf_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/Containers/ITP-2013/Clauses.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505351008904, "lm_q2_score": 0.8031737963569016, "lm_q1q2_score": 0.7265916046532847}}
{"text": "theory Ex2_1 \n  imports Main \nbegin \n  \n  \ndatatype 'a tree = Leaf 'a  | Branch 'a \"'a tree\"  \"'a tree\"\n  \nprimrec preOrder :: \"'a tree \\<Rightarrow> 'a list\" where \n  \"preOrder (Leaf val) = [val]\"|\n  \"preOrder (Branch val lft rgt) = val #  preOrder lft  @ preOrder rgt\"\n  \nprimrec postOrder :: \"'a tree \\<Rightarrow> 'a list\" where \n  \"postOrder (Leaf val) = [val]\"|\n  \"postOrder (Branch val lft rgt) = postOrder lft @ postOrder rgt @ [val]\"\n  \n  \nprimrec inOrder :: \"'a tree \\<Rightarrow> 'a list\" where \n  \"inOrder (Leaf val) = [val]\"|\n  \"inOrder (Branch val lft rgt) = inOrder lft @ val # inOrder rgt\"\n  \nprimrec mirror :: \"'a tree \\<Rightarrow> 'a tree\" where \n  \"mirror (Leaf val) = (Leaf val)\"|\n  \"mirror (Branch val lft rgt) = Branch val (mirror rgt) (mirror lft) \"\n  \n  (*\nlemma \"inOrder (mirror t) = rev (inOrder t)\" \nproof (induct t)\n  case (Leaf x)\n  then show ?case by simp\nnext\n  case (Branch x1a t1 t2)\n  assume \"inOrder (mirror t1) = rev (inOrder t1)\"\n  assume \"inOrder (mirror t2) = rev (inOrder t2)\"\n    \n   \nqed\n  *)\n  \nprimrec root :: \"'a tree \\<Rightarrow> 'a\" where \n  \"root (Leaf val) = val\"|\n  \"root (Branch val _ _) = val\"\n  \nprimrec leftmost :: \"'a tree \\<Rightarrow> 'a\" where \n  \"leftmost (Leaf val) = val\"|\n  \"leftmost (Branch _ lft _) = leftmost lft\"\n  \nprimrec rightmost :: \"'a tree \\<Rightarrow> 'a\" where \n  \"rightmost (Leaf val) = val\"|\n  \"rightmost (Branch _ _ rgt) = rightmost rgt\"  \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/Trees and other inductive data types/Ex2_1.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505402422645, "lm_q2_score": 0.8031737869342623, "lm_q1q2_score": 0.7265916002585059}}
{"text": "section \\<open>Lexicographic orderings\\<close>\n\ntheory Lexord\n  imports MainRLT\nbegin\n\nsubsection \\<open>The preorder case\\<close>\n\nlocale lex_preordering = preordering\nbegin\n\ninductive lex_less :: \\<open>'a list \\<Rightarrow> 'a list \\<Rightarrow> bool\\<close>  (infix \\<open>[\\<^bold><]\\<close> 50) \nwhere\n  Nil: \\<open>[] [\\<^bold><] y # ys\\<close>\n| Cons: \\<open>x \\<^bold>< y \\<Longrightarrow> x # xs [\\<^bold><] y # ys\\<close>\n| Cons_eq: \\<open>x \\<^bold>\\<le> y \\<Longrightarrow> y \\<^bold>\\<le> x \\<Longrightarrow> xs [\\<^bold><] ys \\<Longrightarrow> x # xs [\\<^bold><] y # ys\\<close>\n\ninductive lex_less_eq :: \\<open>'a list \\<Rightarrow> 'a list \\<Rightarrow> bool\\<close>  (infix \\<open>[\\<^bold>\\<le>]\\<close> 50)\nwhere\n  Nil: \\<open>[] [\\<^bold>\\<le>] ys\\<close>\n| Cons: \\<open>x \\<^bold>< y \\<Longrightarrow> x # xs [\\<^bold>\\<le>] y # ys\\<close>\n| Cons_eq: \\<open>x \\<^bold>\\<le> y \\<Longrightarrow> y \\<^bold>\\<le> x \\<Longrightarrow> xs [\\<^bold>\\<le>] ys \\<Longrightarrow> x # xs [\\<^bold>\\<le>] y # ys\\<close>\n\nlemma lex_less_simps [simp]:\n  \\<open>[] [\\<^bold><] y # ys\\<close>\n  \\<open>\\<not> xs [\\<^bold><] []\\<close>\n  \\<open>x # xs [\\<^bold><] y # ys \\<longleftrightarrow> x \\<^bold>< y \\<or> x \\<^bold>\\<le> y \\<and> y \\<^bold>\\<le> x \\<and> xs [\\<^bold><] ys\\<close>\n  by (auto intro: lex_less.intros elim: lex_less.cases)\n\nlemma lex_less_eq_simps [simp]:\n  \\<open>[] [\\<^bold>\\<le>] ys\\<close>\n  \\<open>\\<not> x # xs [\\<^bold>\\<le>] []\\<close>\n  \\<open>x # xs [\\<^bold>\\<le>] y # ys \\<longleftrightarrow> x \\<^bold>< y \\<or> x \\<^bold>\\<le> y \\<and> y \\<^bold>\\<le> x \\<and> xs [\\<^bold>\\<le>] ys\\<close>\n  by (auto intro: lex_less_eq.intros elim: lex_less_eq.cases)\n\nlemma lex_less_code [code]:\n  \\<open>[] [\\<^bold><] y # ys \\<longleftrightarrow> True\\<close>\n  \\<open>xs [\\<^bold><] [] \\<longleftrightarrow> False\\<close>\n  \\<open>x # xs [\\<^bold><] y # ys \\<longleftrightarrow> x \\<^bold>< y \\<or> x \\<^bold>\\<le> y \\<and> y \\<^bold>\\<le> x \\<and> xs [\\<^bold><] ys\\<close>\n  by simp_all\n\nlemma lex_less_eq_code [code]:\n  \\<open>[] [\\<^bold>\\<le>] ys \\<longleftrightarrow> True\\<close>\n  \\<open>x # xs [\\<^bold>\\<le>] [] \\<longleftrightarrow> False\\<close>\n  \\<open>x # xs [\\<^bold>\\<le>] y # ys \\<longleftrightarrow> x \\<^bold>< y \\<or> x \\<^bold>\\<le> y \\<and> y \\<^bold>\\<le> x \\<and> xs [\\<^bold>\\<le>] ys\\<close>\n  by simp_all\n\nlemma preordering:\n  \\<open>preordering ([\\<^bold>\\<le>]) ([\\<^bold><])\\<close>\nproof\n  fix xs ys zs\n  show \\<open>xs [\\<^bold>\\<le>] xs\\<close>\n    by (induction xs) (simp_all add: refl)\n  show \\<open>xs [\\<^bold>\\<le>] zs\\<close> if \\<open>xs [\\<^bold>\\<le>] ys\\<close> \\<open>ys [\\<^bold>\\<le>] zs\\<close>\n  using that proof (induction arbitrary: zs)\n    case (Nil ys)\n    then show ?case by simp\n  next\n    case (Cons x y xs ys)\n    then show ?case\n      by (cases zs) (auto dest: strict_trans strict_trans2)\n  next\n    case (Cons_eq x y xs ys)\n    then show ?case\n      by (cases zs) (auto dest: strict_trans1 intro: trans)\n  qed\n  show \\<open>xs [\\<^bold><] ys \\<longleftrightarrow> xs [\\<^bold>\\<le>] ys \\<and> \\<not> ys [\\<^bold>\\<le>] xs\\<close> (is \\<open>?P \\<longleftrightarrow> ?Q\\<close>)\n  proof\n    assume ?P\n    then have \\<open>xs [\\<^bold>\\<le>] ys\\<close>\n      by induction simp_all\n    moreover have \\<open>\\<not> ys [\\<^bold>\\<le>] xs\\<close>\n      using \\<open>?P\\<close>\n      by induction (simp_all, simp_all add: strict_iff_not asym)\n    ultimately show ?Q ..\n  next\n    assume ?Q\n    then have \\<open>xs [\\<^bold>\\<le>] ys\\<close> \\<open>\\<not> ys [\\<^bold>\\<le>] xs\\<close>\n      by auto\n    then show ?P\n    proof induction\n      case (Nil ys)\n      then show ?case\n        by (cases ys) simp_all\n    next\n      case (Cons x y xs ys)\n      then show ?case\n        by simp\n    next\n      case (Cons_eq x y xs ys)\n      then show ?case\n        by simp\n    qed\n  qed\nqed\n\ninterpretation lex: preordering \\<open>([\\<^bold>\\<le>])\\<close> \\<open>([\\<^bold><])\\<close>\n  by (fact preordering)\n\nend\n\n\nsubsection \\<open>The order case\\<close>\n\nlocale lex_ordering = lex_preordering + ordering\nbegin\n\ninterpretation lex: preordering \\<open>([\\<^bold>\\<le>])\\<close> \\<open>([\\<^bold><])\\<close>\n  by (fact preordering)\n\nlemma less_lex_Cons_iff [simp]:\n  \\<open>x # xs [\\<^bold><] y # ys \\<longleftrightarrow> x \\<^bold>< y \\<or> x = y \\<and> xs [\\<^bold><] ys\\<close>\n  by (auto intro: refl antisym)\n\nlemma less_eq_lex_Cons_iff [simp]:\n  \\<open>x # xs [\\<^bold>\\<le>] y # ys \\<longleftrightarrow> x \\<^bold>< y \\<or> x = y \\<and> xs [\\<^bold>\\<le>] ys\\<close>\n  by (auto intro: refl antisym)\n\nlemma ordering:\n  \\<open>ordering ([\\<^bold>\\<le>]) ([\\<^bold><])\\<close>\nproof\n  fix xs ys\n  show *: \\<open>xs = ys\\<close> if \\<open>xs [\\<^bold>\\<le>] ys\\<close> \\<open>ys [\\<^bold>\\<le>] xs\\<close>\n  using that proof induction\n  case (Nil ys)\n    then show ?case by (cases ys) simp\n  next\n    case (Cons x y xs ys)\n    then show ?case by (auto dest: asym intro: antisym)\n      (simp add: strict_iff_not)\n  next\n    case (Cons_eq x y xs ys)\n    then show ?case by (auto intro: antisym)\n      (simp add: strict_iff_not)\n  qed\n  show \\<open>xs [\\<^bold><] ys \\<longleftrightarrow> xs [\\<^bold>\\<le>] ys \\<and> xs \\<noteq> ys\\<close>\n    by (auto simp add: lex.strict_iff_not dest: *)\nqed\n\ninterpretation lex: ordering \\<open>([\\<^bold>\\<le>])\\<close> \\<open>([\\<^bold><])\\<close>\n  by (fact ordering)\n\nend\n\n\nsubsection \\<open>Canonical instance\\<close>\n\ninstantiation list :: (preorder) preorder\nbegin\n\nglobal_interpretation lex: lex_preordering \\<open>(\\<le>) :: 'a::preorder \\<Rightarrow> 'a \\<Rightarrow> bool\\<close> \\<open>(<) :: 'a \\<Rightarrow> 'a \\<Rightarrow> bool\\<close>\n  defines less_eq_list = lex.lex_less_eq\n    and less_list = lex.lex_less ..\n\ninstance\n  by (rule class.preorder.of_class.intro, rule preordering_preorderI, fact lex.preordering)\n\nend\n\nglobal_interpretation lex: lex_ordering \\<open>(\\<le>) :: 'a::order \\<Rightarrow> 'a \\<Rightarrow> bool\\<close> \\<open>(<) :: 'a \\<Rightarrow> 'a \\<Rightarrow> bool\\<close>\n  rewrites \\<open>lex_preordering.lex_less_eq (\\<le>) (<) = ((\\<le>) :: 'a list \\<Rightarrow> 'a list \\<Rightarrow> bool)\\<close>\n    and \\<open>lex_preordering.lex_less (\\<le>) (<) = ((<) :: 'a list \\<Rightarrow> 'a list \\<Rightarrow> bool)\\<close>\nproof -\n  interpret lex_ordering \\<open>(\\<le>) :: 'a \\<Rightarrow> 'a \\<Rightarrow> bool\\<close> \\<open>(<) :: 'a \\<Rightarrow> 'a \\<Rightarrow> bool\\<close> ..\n  show \\<open>lex_ordering ((\\<le>)  :: 'a \\<Rightarrow> 'a \\<Rightarrow> bool) (<)\\<close>\n    by (fact lex_ordering_axioms)\n  show \\<open>lex_preordering.lex_less_eq (\\<le>) (<) = (\\<le>)\\<close>\n    by (simp add: less_eq_list_def)\n  show \\<open>lex_preordering.lex_less (\\<le>) (<) = (<)\\<close>\n    by (simp add: less_list_def)\nqed\n\ninstance list :: (order) order\n  by (rule class.order.of_class.intro, rule ordering_orderI, fact lex.ordering)\n\nexport_code \\<open>(\\<le>) :: _ list \\<Rightarrow> _ list \\<Rightarrow> bool\\<close> \\<open>(<) :: _ list \\<Rightarrow> _ list \\<Rightarrow> bool\\<close> in Haskell\n\n\nsubsection \\<open>Non-canonical instance\\<close>\n\ncontext comm_monoid_mult\nbegin\n\ndefinition dvd_strict :: \\<open>'a \\<Rightarrow> 'a \\<Rightarrow> bool\\<close>\n  where \\<open>dvd_strict a b \\<longleftrightarrow> a dvd b \\<and> \\<not> b dvd a\\<close>\n\nend\n\nglobal_interpretation dvd: lex_preordering \\<open>(dvd) :: 'a::comm_monoid_mult \\<Rightarrow> 'a \\<Rightarrow> bool\\<close> dvd_strict\n  defines lex_dvd = dvd.lex_less_eq\n    and lex_dvd_strict = dvd.lex_less\n  apply (rule lex_preordering.intro)\n  apply standard\n    apply (auto simp add: dvd_strict_def)\n  done\n\nglobal_interpretation lex_dvd: preordering lex_dvd lex_dvd_strict\n  by (fact dvd.preordering)\n\ndefinition \\<open>example = lex_dvd [(4::int), - 7, 8] [- 8, 13, 5]\\<close>\n\nexport_code example in Haskell\n\nvalue example\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/Lexord.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339797047029, "lm_q2_score": 0.865224084314688, "lm_q1q2_score": 0.7265580636579303}}
{"text": "(* Section 3.4 Advanced Datatypes *)\n\ntheory FAdvancedDatatypes\nimports Main\nbegin\n\n(* Section 3.4.1 Mutual Recursion *)\n\n(* Mutually recursive data types *)\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\n(* Mutually recursive data types have mutually recursive primitive recursion functions. *)\n\n(* Evaluation *)\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 = (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\n(* Substitution *)\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) =  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\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)\napply simp_all\ndone\n\n(* Exercise 3.4.1 *)\n\n(*\nNormalize IF with Less and without And and Neg.\nNote the primitive recursion requirements for norma and normif.\n*)\nprimrec norma  :: \"'a aexp \\<Rightarrow> 'a aexp\" and\n        normif :: \"'a bexp \\<Rightarrow> 'a aexp \\<Rightarrow> 'a aexp \\<Rightarrow> 'a aexp\" where\n\"norma (IF b a1 a2) = normif b (norma a1) (norma a2)\" |\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\"normif (Less a1 a2) a1' a2' = IF (Less (norma a1) (norma a2)) a1' a2'\" |\n\"normif (And b1 b2)  a1' a2' = normif b1 (normif b2 a1' a2') a2'\" |\n\"normif (Neg b)      a1' a2' = normif b a2' a1'\"\n\n(*\nThe value of a normalized IF is the same as that of a non-normalized IF.\nNote that the quantification cannot be lifted.\n*)\ntheorem \"evala (norma a) env = evala a env \\<and>\n         (\\<forall>a1 a2. evala (normif b a1 a2) env = evala (IF b a1 a2) env)\"\napply (induct_tac a and b)\napply auto\ndone\n\nprimrec normala :: \"'a aexp \\<Rightarrow> bool\" and\n        normalb :: \"'a bexp \\<Rightarrow> bool\" where\n\"normala (IF b a1 a2) = (normalb b \\<and> normala a1 \\<and> normala a2)\" |\n\"normala (Sum a1 a2)  = (normala a1 \\<and> normala a2)\" |\n\"normala (Diff a1 a2) = (normala a1 \\<and> normala a2)\" |\n\"normala (Var _)      = True\" |\n\"normala (Num _)      = True\" |\n\n\"normalb (Less a1 a2) = (normala a1 \\<and> normala a2)\" |\n\"normalb (And _ _)    = False\" |\n\"normalb (Neg _)      = False\"\n\n(* normif normalizes the condition but not the branches. *)\ntheorem \"normala (norma (a :: 'a aexp)) \\<and>\n         (\\<forall>a1 a2. normala (normif (b :: 'a bexp) a1 a2) = (normala a1 \\<and> normala a2))\"\napply (induct_tac a and b)\napply auto\ndone\n", "meta": {"author": "spl", "repo": "isabelle-tutorial", "sha": "56ee8d748d6d639ea7238e5fbb9edce4330637f2", "save_path": "github-repos/isabelle/spl-isabelle-tutorial", "path": "github-repos/isabelle/spl-isabelle-tutorial/isabelle-tutorial-56ee8d748d6d639ea7238e5fbb9edce4330637f2/FAdvancedDatatypes.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772351648677, "lm_q2_score": 0.8311430520409023, "lm_q1q2_score": 0.7264832209544017}}
{"text": "section\\<open>Square integrable functions over the reals\\<close>\n\ntheory Square_Integrable\n  imports Lspace \nbegin\n\nsubsection\\<open>Basic definitions\\<close>\n\ndefinition square_integrable:: \"(real \\<Rightarrow> real) \\<Rightarrow> real set \\<Rightarrow> bool\" (infixr \"square'_integrable\" 46)\n  where \"f square_integrable S \\<equiv> S \\<in> sets lebesgue \\<and> f \\<in> borel_measurable (lebesgue_on S) \\<and> integrable (lebesgue_on S) (\\<lambda>x. f x ^ 2)\"\n\nlemma square_integrable_imp_measurable:\n   \"f square_integrable S \\<Longrightarrow> f \\<in> borel_measurable (lebesgue_on S)\"\n  by (simp add: square_integrable_def)\n\nlemma square_integrable_imp_lebesgue:\n   \"f square_integrable S \\<Longrightarrow> S \\<in> sets lebesgue\"\n  by (simp add: square_integrable_def)\n\nlemma square_integrable_imp_lspace:\n  assumes \"f square_integrable S\" shows \"f \\<in> lspace (lebesgue_on S) 2\"\nproof -\n  have \"(\\<lambda>x. (f x)\\<^sup>2) absolutely_integrable_on S\"\n    by (metis assms integrable_on_lebesgue_on nonnegative_absolutely_integrable_1 square_integrable_def zero_le_power2)\n  moreover have \"S \\<in> sets lebesgue\"\n    using assms square_integrable_def by blast\n  ultimately show ?thesis\n    by (simp add: assms Lp_space_numeral integrable_restrict_space set_integrable_def square_integrable_imp_measurable)\nqed\n\nlemma square_integrable_iff_lspace:\n  assumes \"S \\<in> sets lebesgue\"\n  shows \"f square_integrable S \\<longleftrightarrow> f \\<in> lspace (lebesgue_on S) 2\" (is \"?lhs = ?rhs\")\nproof\n  assume L: ?lhs\n  then show ?rhs\n    using square_integrable_imp_lspace by blast\nnext\n  assume ?rhs then show ?lhs\n  using assms by (auto simp: Lp_space_numeral square_integrable_def integrable_on_lebesgue_on)\nqed\n\nlemma square_integrable_0 [simp]:\n   \"S \\<in> sets lebesgue \\<Longrightarrow> (\\<lambda>x. 0) square_integrable S\"\n  by (simp add: square_integrable_def power2_eq_square integrable_0)\n\nlemma square_integrable_neg_eq [simp]:\n   \"(\\<lambda>x. -(f x)) square_integrable S \\<longleftrightarrow> f square_integrable S\"\n  by (auto simp: square_integrable_def)\n\nlemma square_integrable_lmult [simp]:\n  assumes \"f square_integrable S\"\n  shows \"(\\<lambda>x. c * f x) square_integrable S\"\nproof (simp add: square_integrable_def, intro conjI)\n  have f: \"f \\<in> borel_measurable (lebesgue_on S)\" \"integrable (lebesgue_on S) (\\<lambda>x. f x ^ 2)\"\n    using assms by (simp_all add: square_integrable_def)\n  then show \"(\\<lambda>x. c * f x) \\<in> borel_measurable (lebesgue_on S)\"\n    using borel_measurable_scaleR [of \"\\<lambda>x. c\" \"lebesgue_on S\" f]  by simp\n  have \"integrable (lebesgue_on S) (\\<lambda>x. c\\<^sup>2 * (f x)\\<^sup>2)\"\n  by (cases \"c=0\") (auto simp: f integrable_0)\n  then show \"integrable (lebesgue_on S) (\\<lambda>x. (c * f x)\\<^sup>2)\"\n    by (simp add: power2_eq_square mult_ac)\n  show \"S \\<in> sets lebesgue\"\n    using assms square_integrable_def by blast\nqed\n\nlemma square_integrable_rmult [simp]:\n   \"f square_integrable S \\<Longrightarrow> (\\<lambda>x. f x * c) square_integrable S\"\n  using square_integrable_lmult [of f S c] by (simp add: mult.commute)\n\nlemma square_integrable_imp_absolutely_integrable_product:\n  assumes f: \"f square_integrable S\" and g: \"g square_integrable S\"\n  shows \"(\\<lambda>x. f x * g x) absolutely_integrable_on S\"\nproof -\n  have fS: \"integrable (lebesgue_on S) (\\<lambda>r. (f r)\\<^sup>2)\" \"integrable (lebesgue_on S) (\\<lambda>r. (g r)\\<^sup>2)\"\n    using assms square_integrable_def by blast+\n  have \"integrable (lebesgue_on S) (\\<lambda>x. \\<bar>f x * g x\\<bar>)\"\n  proof (intro integrable_abs Holder_inequality [of 2 2])\n    show \"f \\<in> borel_measurable (lebesgue_on S)\" \"g \\<in> borel_measurable (lebesgue_on S)\"\n      using f g square_integrable_def by blast+\n    show \"integrable (lebesgue_on S) (\\<lambda>x. \\<bar>f x\\<bar> powr 2)\" \"integrable (lebesgue_on S) (\\<lambda>x. \\<bar>g x\\<bar> powr 2)\"\n      using nonnegative_absolutely_integrable_1 [of \"(\\<lambda>x. (f x)\\<^sup>2)\"] nonnegative_absolutely_integrable_1 [of \"(\\<lambda>x. (g x)\\<^sup>2)\"]\n      by (simp_all add: fS integrable_restrict_space set_integrable_def)\n  qed auto\n  then show ?thesis\n    using assms\n    by (simp add: absolutely_integrable_measurable_real borel_measurable_times square_integrable_def)\nqed\n\nlemma square_integrable_imp_integrable_product:\n  assumes \"f square_integrable S\" \"g square_integrable S\"\n  shows  \"integrable (lebesgue_on S) (\\<lambda>x. f x * g x)\"\n  using absolutely_integrable_measurable assms integrable_abs_iff\n  by (metis (full_types) absolutely_integrable_measurable_real square_integrable_def square_integrable_imp_absolutely_integrable_product)\n\nlemma square_integrable_add [simp]:\n  assumes f: \"f square_integrable S\" and g: \"g square_integrable S\"\n  shows \"(\\<lambda>x. f x + g x) square_integrable S\"\n  unfolding square_integrable_def\nproof (intro conjI)\n  show \"S \\<in> sets lebesgue\"\n    using assms square_integrable_def by blast\n  show \"(\\<lambda>x. f x + g x) \\<in> borel_measurable (lebesgue_on S)\"\n    by (simp add: f g borel_measurable_add square_integrable_imp_measurable)\n  show \"integrable (lebesgue_on S) (\\<lambda>x. (f x + g x)\\<^sup>2)\"\n    unfolding power2_eq_square distrib_right distrib_left\n  proof (intro Bochner_Integration.integrable_add)\n    show \"integrable (lebesgue_on S) (\\<lambda>x. f x * f x)\" \"integrable (lebesgue_on S) (\\<lambda>x. g x * g x)\"\n      using f g square_integrable_imp_integrable_product by blast+\n    show \"integrable (lebesgue_on S) (\\<lambda>x. f x * g x)\" \"integrable (lebesgue_on S) (\\<lambda>x. g x * f x)\"\n      using f g square_integrable_imp_integrable_product by blast+\n  qed\nqed\n\nlemma square_integrable_diff [simp]:\n   \"\\<lbrakk>f square_integrable S; g square_integrable S\\<rbrakk> \\<Longrightarrow> (\\<lambda>x. f x - g x) square_integrable S\"\n  using square_integrable_neg_eq square_integrable_add [of f S \"\\<lambda>x. - (g x)\"] by auto\n\nlemma square_integrable_abs [simp]:\n   \"f square_integrable S \\<Longrightarrow> (\\<lambda>x. \\<bar>f x\\<bar>) square_integrable S\"\n  by (simp add: square_integrable_def borel_measurable_abs)\n\nlemma square_integrable_sum [simp]:\n  assumes I: \"finite I\" \"\\<And>i. i \\<in> I \\<Longrightarrow> f i square_integrable S\" and S: \"S \\<in> sets lebesgue\"\n  shows \"(\\<lambda>x. \\<Sum>i\\<in>I. f i x) square_integrable S\"\n  using I by induction (simp_all add: S)\n\nlemma continuous_imp_square_integrable [simp]:\n   \"continuous_on {a..b} f \\<Longrightarrow> f square_integrable {a..b}\"\n  using continuous_imp_integrable [of a b \"(\\<lambda>x. (f x)\\<^sup>2)\"]\n  by (simp add: square_integrable_def continuous_on_power continuous_imp_measurable_on_sets_lebesgue)\n\nlemma square_integrable_imp_absolutely_integrable:\n  assumes f: \"f square_integrable S\" and S: \"S \\<in> lmeasurable\"\n  shows \"f absolutely_integrable_on S\"\nproof -\n  have \"f \\<in> lspace (lebesgue_on S) 2\"\n    using f S square_integrable_iff_lspace by blast\n  then have \"f \\<in> lspace (lebesgue_on S) 1\"\n    by (rule lspace_mono) (use S in auto)\n  then show ?thesis\n    using S by (simp flip: lspace_1)\nqed\n\nlemma square_integrable_imp_integrable:\n  assumes f: \"f square_integrable S\" and S: \"S \\<in> lmeasurable\"\n  shows \"integrable (lebesgue_on S) f\"\n  by (meson S absolutely_integrable_measurable_real f fmeasurableD integrable_abs_iff square_integrable_imp_absolutely_integrable)\n\nsubsection\\<open> The norm and inner product in L2\\<close>\n\ndefinition l2product :: \"'a::euclidean_space set \\<Rightarrow> ('a \\<Rightarrow> real) \\<Rightarrow> ('a \\<Rightarrow> real) \\<Rightarrow> real\"\n  where \"l2product S f g \\<equiv> (\\<integral>x. f x * g x \\<partial>(lebesgue_on S))\"\n\ndefinition l2norm :: \"['a::euclidean_space set, 'a \\<Rightarrow> real] \\<Rightarrow> real\"\n  where \"l2norm S f \\<equiv> sqrt (l2product S f f)\"\n\ndefinition lnorm :: \"['a measure, real, 'a \\<Rightarrow> real] \\<Rightarrow> real\"\n  where \"lnorm M p f \\<equiv> (\\<integral>x. \\<bar>f x\\<bar> powr p \\<partial>M) powr (1/p)\"\n\ncorollary Holder_inequality_lnorm:\n  assumes \"p > (0::real)\" \"q > 0\" \"1/p+1/q = 1\"\n      and \"f \\<in> borel_measurable M\" \"g \\<in> borel_measurable M\"\n          \"integrable M (\\<lambda>x. \\<bar>f x\\<bar> powr p)\"\n          \"integrable M (\\<lambda>x. \\<bar>g x\\<bar> powr q)\"\n  shows \"(\\<integral>x. \\<bar>f x * g x\\<bar> \\<partial>M) \\<le> lnorm M p f * lnorm M q g\"\n        \"\\<bar>\\<integral>x. f x * g x \\<partial>M \\<bar> \\<le> lnorm M p f * lnorm M q g\"\n  by (simp_all add: Holder_inequality assms lnorm_def)\n\nlemma l2norm_lnorm: \"l2norm S f = lnorm (lebesgue_on S) 2 f\"\nproof -\n  have \"(LINT x|lebesgue_on S. (f x)\\<^sup>2) \\<ge> 0\"\n    by simp\n  then show ?thesis\n    by (auto simp: lnorm_def l2norm_def l2product_def power2_eq_square powr_half_sqrt)\nqed\n\nlemma lnorm_nonneg: \"lnorm M p f \\<ge> 0\"\n  by (simp add: lnorm_def)\n\nlemma lnorm_minus_commute: \"lnorm M p (g - f) = lnorm M p (f - g)\"\n  by (simp add: lnorm_def abs_minus_commute)\n\n\ntext\\<open> Extending a continuous function in a periodic way\\<close>\n\nproposition continuous_on_compose_frac:\n  fixes f:: \"real \\<Rightarrow> real\"\n  assumes contf: \"continuous_on {0..1} f\" and f10: \"f 1 = f 0\"\n  shows \"continuous_on UNIV (f \\<circ> frac)\"\nproof -\n  have *: \"isCont (f \\<circ> frac) x\"\n    if caf: \"\\<And>x. \\<lbrakk>0 \\<le> x; x \\<le> 1\\<rbrakk> \\<Longrightarrow> continuous (at x within {0..1}) f\" for x\n  proof (cases \"x \\<in> \\<int>\")\n    case True\n    then have [simp]: \"frac x = 0\"\n      by simp\n    show ?thesis\n    proof (clarsimp simp add: continuous_at_eps_delta dist_real_def)\n      have f0: \"continuous (at 0 within {0..1}) f\" and f1: \"continuous (at 1 within {0..1}) f\"\n        by (auto intro: caf)\n      show \"\\<exists>d>0. \\<forall>x'. \\<bar>x'-x\\<bar> < d \\<longrightarrow> \\<bar>f(frac x') - f 0\\<bar> < e\"\n        if \"0 < e\" for e\n      proof -\n        obtain d0 where \"d0 > 0\" and d0: \"\\<And>x'. \\<lbrakk>x'\\<in>{0..1}; \\<bar>x'\\<bar> < d0\\<rbrakk> \\<Longrightarrow> \\<bar>f x' - f 0\\<bar> < e\"\n          using \\<open>e > 0\\<close> caf [of 0] dist_not_less_zero\n          by (auto simp: continuous_within_eps_delta dist_real_def)\n        obtain d1 where \"d1 > 0\" and d1: \"\\<And>x'. \\<lbrakk>x'\\<in>{0..1}; \\<bar>x' - 1\\<bar> < d1\\<rbrakk> \\<Longrightarrow> \\<bar>f x' - f 0\\<bar> < e\"\n          using \\<open>e > 0\\<close> caf [of 1] dist_not_less_zero f10\n          by (auto simp: continuous_within_eps_delta dist_real_def)\n        show ?thesis\n        proof (intro exI conjI allI impI)\n          show \"0 < min 1 (min d0 d1)\"\n            by (auto simp: \\<open>d0 > 0\\<close> \\<open>d1 > 0\\<close>)\n          show \"\\<bar>f(frac x') - f 0\\<bar> < e\"\n            if \"\\<bar>x'-x\\<bar> < min 1 (min d0 d1)\" for x'\n          proof (cases \"x \\<le> x'\")\n            case True\n            with \\<open>x \\<in> \\<int>\\<close> that have \"frac x' = x' - x\"\n              by (simp add: frac_unique_iff)\n            then show ?thesis\n              using True d0 that by auto\n          next\n            case False\n            then have [simp]: \"frac x' = 1 - (x - x')\"\n              using that \\<open>x \\<in> \\<int>\\<close> by (simp add: not_le frac_unique_iff)\n            show ?thesis\n              using False d1 that by auto\n          qed\n        qed\n      qed\n    qed\n  next\n    case False\n    show ?thesis\n    proof (rule continuous_at_compose)\n      show \"isCont frac x\"\n        by (simp add: False continuous_frac)\n      have \"frac x \\<in> {0<..<1}\"\n        by (simp add: False frac_lt_1)\n      then show \"isCont f(frac x)\"\n        by (metis at_within_Icc_at greaterThanLessThan_iff le_cases not_le that)\n    qed\n  qed\n  then show ?thesis\n    using contf by (simp add: o_def continuous_on_eq_continuous_within)\nqed\n\n\nproposition Tietze_periodic_interval:\n  fixes f:: \"real \\<Rightarrow> real\"\n  assumes contf: \"continuous_on {a..b} f\" and fab: \"f a = f b\"\n  obtains g where \"continuous_on UNIV g\" \"\\<And>x. x \\<in> {a..b} \\<Longrightarrow> g x = f x\"\n                  \"\\<And>x. g(x + (b-a)) = g x\"\nproof (cases \"a < b\")\n  case True\n  let ?g = \"f \\<circ> (\\<lambda>y. a + (b-a) * y) \\<circ> frac \\<circ>\n                (\\<lambda>x. (x - a) / (b-a))\"\n  show ?thesis\n  proof\n    have \"a + (b - a) * y \\<le> b\" if \"a < b\" \"0 \\<le> y\" \"y \\<le> 1\" for y\n      using that affine_ineq by (force simp: field_simps)\n    then have *: \"continuous_on (range (\\<lambda>x. (x - a) / (b - a))) (f \\<circ> (\\<lambda>y. a + (b - a) * y) \\<circ> frac)\"\n      apply (intro continuous_on_subset [OF continuous_on_compose_frac] continuous_on_subset [OF contf]\n          continuous_intros)\n      using \\<open>a < b\\<close>\n      by (auto simp: fab)\n    show \"continuous_on UNIV ?g\"\n      by (intro * continuous_on_compose continuous_intros) (use True in auto)\n    show \"?g x = f x\" if \"x \\<in> {a..b}\" for x :: real\n    proof (cases \"x=b\")\n      case True\n      then show ?thesis\n        by (auto simp: frac_def intro: fab)\n    next\n      case False\n      with \\<open>a < b\\<close> that have \"frac ((x - a) / (b - a)) = (x - a) / (b - a)\"\n        by (subst frac_eq) (auto simp: divide_simps)\n      with \\<open>a < b\\<close> show ?thesis\n        by auto\n    qed\n    have \"a + (b-a) * frac ((x + b - 2 * a) / (b-a)) = a + (b-a) * frac ((x - a) / (b-a))\" for x\n      using True frac_1_eq [of \"(x - a) / (b-a)\"] by (auto simp: divide_simps)\n    then show \"?g (x + (b-a)) = (?g x::real)\" for x\n      by force\n  qed\nnext\n  case False\n  show ?thesis\n  proof\n    show \"f a = f x\" if \"x \\<in> {a..b}\" for x\n      using that False order_trans by fastforce\n  qed auto\nqed\n\n\nsubsection\\<open>Lspace stuff\\<close>\n\nlemma eNorm_triangle_eps:\n  assumes \"eNorm N (x' - x) < a\" \"defect N = 1\"\n  obtains e where \"e > 0\" \"\\<And>y. eNorm N (y - x') < e \\<Longrightarrow> eNorm N (y - x) < a\"\nproof -\n  let ?d = \"a - Norm N (x' - x)\"\n  have nt: \"eNorm N (x' - x) < \\<top>\"\n    using assms top.not_eq_extremum by fastforce\n  with assms have d: \"?d > 0\"\n    by (simp add: Norm_def diff_gr0_ennreal)\n  have [simp]: \"ennreal (1 - Norm N (x' - x)) = 1 - eNorm N (x' - x)\"\n    using that nt  unfolding Norm_def  by (metis enn2real_nonneg ennreal_1 ennreal_enn2real ennreal_minus)\n  show ?thesis\n  proof\n    show \"(0::ennreal) < ?d\"\n      using d ennreal_less_zero_iff by blast\n    show \"eNorm N (y - x) < a\"\n      if \"eNorm N (y - x') < ?d\" for y\n      using that assms eNorm_triangular_ineq [of N \"y - x'\" \"x' - x\"] le_less_trans less_diff_eq_ennreal\n      by (simp add: Norm_def nt)\n  qed\nqed\n\nlemma topspace_topology\\<^sub>N [simp]:\n  assumes \"defect N = 1\" shows \"topspace (topology\\<^sub>N N) = UNIV\"\nproof -\n  have \"x \\<in> topspace (topology\\<^sub>N N)\" for x\n  proof -\n    have \"\\<exists>e>0. \\<forall>y. eNorm N (y - x') < e \\<longrightarrow> eNorm N (y - x) < 1\"\n      if \"eNorm N (x' - x) < 1\" for x'\n      using eNorm_triangle_eps\n      by (metis assms that)\n    then show ?thesis\n      unfolding topspace_def\n      by (rule_tac X=\"{y. eNorm N (y - x) < 1}\" in UnionI) (auto intro: openin_topology\\<^sub>N_I)\n  qed\n  then show ?thesis\n    by auto\nqed\n\nlemma tendsto_ine\\<^sub>N_iff_limitin:\n  assumes \"defect N = 1\"\n  shows \"tendsto_ine\\<^sub>N N u x = limitin (topology\\<^sub>N N) u x sequentially\"\nproof -\n  have \"\\<forall>\\<^sub>F x in sequentially. u x \\<in> U\"\n    if 0: \"(\\<lambda>n. eNorm N (u n - x)) \\<longlonglongrightarrow> 0\" and U: \"openin (topology\\<^sub>N N) U\" \"x \\<in> U\" for U\n  proof -\n    obtain e where \"e > 0\" and e: \"\\<And>y. eNorm N (y-x) < e \\<Longrightarrow> y \\<in> U\"\n      using openin_topology\\<^sub>N_D U by metis\n    then show ?thesis\n      using eventually_mono order_tendstoD(2)[OF 0] by force\n  qed\n  moreover have \"(\\<lambda>n. eNorm N (u n - x)) \\<longlonglongrightarrow> 0\"\n    if x: \"x \\<in> topspace (topology\\<^sub>N N)\"\n      and *: \"\\<And>U. \\<lbrakk>openin (topology\\<^sub>N N) U; x \\<in> U\\<rbrakk> \\<Longrightarrow> (\\<forall>\\<^sub>F x in sequentially. u x \\<in> U)\"\n  proof (rule order_tendstoI)\n    show \"\\<forall>\\<^sub>F n in sequentially. eNorm N (u n - x) < a\" if \"a > 0\" for a\n      apply (rule * [OF openin_topology\\<^sub>N_I, of \"{v. eNorm N (v - x) < a}\", simplified])\n      using assms eNorm_triangle_eps that apply blast+\n      done\n  qed simp\n  ultimately show ?thesis\n    by (auto simp: tendsto_ine\\<^sub>N_def limitin_def assms)\nqed\n\ncorollary tendsto_ine\\<^sub>N_iff_limitin_ge1:\n  fixes p :: ennreal\n  assumes \"p \\<ge> 1\"\n  shows \"tendsto_ine\\<^sub>N (\\<LL> p M) u x = limitin (topology\\<^sub>N (\\<LL> p M)) u x sequentially\"\nproof (rule tendsto_ine\\<^sub>N_iff_limitin)\n  show \"defect (\\<LL> p M) = 1\"\n    by (metis (full_types) L_infinity(2) L_zero(2) Lp(2) Lp_cases assms ennreal_ge_1)\nqed\n\ncorollary tendsto_in\\<^sub>N_iff_limitin:\n  assumes \"defect N = 1\" \"x \\<in> space\\<^sub>N N\" \"\\<And>n. u n \\<in> space\\<^sub>N N\"\n  shows \"tendsto_in\\<^sub>N N u x = limitin (topology\\<^sub>N N) u x sequentially\"\n  using assms tendsto_ine\\<^sub>N_iff_limitin tendsto_ine_in by blast\n\ncorollary tendsto_in\\<^sub>N_iff_limitin_ge1:\n  fixes p :: ennreal\n  assumes \"p \\<ge> 1\" \"x \\<in> lspace M p\" \"\\<And>n. u n \\<in> lspace M p\"\n  shows \"tendsto_in\\<^sub>N (\\<LL> p M) u x = limitin (topology\\<^sub>N (\\<LL> p M)) u x sequentially\"\nproof (rule tendsto_in\\<^sub>N_iff_limitin)\n  show \"defect (\\<LL> p M) = 1\"\n    by (metis (full_types) L_infinity(2) L_zero(2) Lp(2) Lp_cases \\<open>p \\<ge> 1\\<close> ennreal_ge_1)\nqed (auto simp: assms)\n\n\nlemma l2product_sym: \"l2product S f g = l2product S g f\"\n  by (simp add: l2product_def mult.commute)\n\nlemma l2product_pos_le:\n   \"f square_integrable S \\<Longrightarrow> 0 \\<le> l2product S f f\"\n  by (simp add: square_integrable_def l2product_def flip: power2_eq_square)\n\nlemma l2norm_pow_2:\n   \"f square_integrable S \\<Longrightarrow> (l2norm S f) ^ 2 = l2product S f f\"\n  by (simp add: l2norm_def l2product_pos_le)\n\nlemma l2norm_pos_le:\n   \"f square_integrable S \\<Longrightarrow> 0 \\<le> l2norm S f\"\n  by (simp add: l2norm_def l2product_pos_le)\n\nlemma l2norm_le: \"(l2norm S f \\<le> l2norm S g \\<longleftrightarrow> l2product S f f \\<le> l2product S g g)\"\n  by (simp add: l2norm_def)\n\nlemma l2norm_eq:\n   \"(l2norm S f = l2norm S g \\<longleftrightarrow> l2product S f f = l2product S g g)\"\n  by (simp add: l2norm_def)\n\nlemma Schwartz_inequality_strong:\n  assumes \"f square_integrable S\" \"g square_integrable S\"\n  shows \"l2product S (\\<lambda>x. \\<bar>f x\\<bar>) (\\<lambda>x. \\<bar>g x\\<bar>) \\<le> l2norm S f * l2norm S g\"\n  using Holder_inequality_lnorm [of 2 2 f \"lebesgue_on S\" g] assms\n  by (simp add: square_integrable_def l2product_def abs_mult flip: l2norm_lnorm)\n\nlemma Schwartz_inequality_abs:\n  assumes \"f square_integrable S\" \"g square_integrable S\"\n  shows \"\\<bar>l2product S f g\\<bar> \\<le> l2norm S f * l2norm S g\"\nproof -\n  have \"\\<bar>l2product S f g\\<bar> \\<le> l2product S (\\<lambda>x. \\<bar>f x\\<bar>) (\\<lambda>x. \\<bar>g x\\<bar>)\"\n    unfolding l2product_def\n  proof (rule integral_abs_bound_integral)\n    show \"integrable (lebesgue_on S) (\\<lambda>x. f x * g x)\" \"integrable (lebesgue_on S) (\\<lambda>x. \\<bar>f x\\<bar> * \\<bar>g x\\<bar>)\"\n      by (simp_all add: assms square_integrable_imp_integrable_product)\n  qed (simp add: abs_mult)\n  also have \"\\<dots> \\<le> l2norm S f * l2norm S g\"\n    by (simp add: Schwartz_inequality_strong assms)\n  finally show ?thesis .\nqed\n\nlemma Schwartz_inequality:\n  assumes \"f square_integrable S\" \"g square_integrable S\"\n  shows \"l2product S f g \\<le> l2norm S f * l2norm S g\"\n  using Schwartz_inequality_abs assms by fastforce\n\n\nlemma lnorm_triangle:\n  assumes f: \"f \\<in> lspace M p\" and g: \"g \\<in> lspace M p\" and \"p \\<ge> 1\"\n  shows \"lnorm M p (\\<lambda>x. f x + g x) \\<le> lnorm M p f + lnorm M p g\"\nproof -\n  have \"p > 0\"\n    using assms by linarith\n  then have \"integrable M (\\<lambda>x. \\<bar>f x\\<bar> powr p)\" \"integrable M (\\<lambda>x. \\<bar>g x\\<bar> powr p)\"\n    by (simp_all add: Lp_D(2) assms)\n  moreover have \"f \\<in> borel_measurable M\" \"g \\<in> borel_measurable M\"\n    using Lp_measurable f g by blast+\n  ultimately show ?thesis\n    unfolding lnorm_def using Minkowski_inequality(2) \\<open>p \\<ge> 1\\<close> by blast\nqed\n\nlemma lnorm_triangle_fun:\n  assumes f: \"f \\<in> lspace M p\" and g: \"g \\<in> lspace M p\" and \"p \\<ge> 1\"\n  shows \"lnorm M p (f + g) \\<le> lnorm M p f + lnorm M p g\"\n  using lnorm_triangle [OF assms] by (simp add: plus_fun_def)\n\nlemma l2norm_triangle:\n  assumes \"f square_integrable S\" \"g square_integrable S\"\n  shows \"l2norm S (\\<lambda>x. f x + g x) \\<le> l2norm S f + l2norm S g\"\nproof -\n  have \"f \\<in> lspace (lebesgue_on S) 2\" \"g \\<in> lspace (lebesgue_on S) 2\"\n    using assms by (simp_all add: square_integrable_imp_lspace)\n  then show ?thesis\n    using lnorm_triangle [of f 2 \"lebesgue_on S\"]\n    by (simp add: l2norm_lnorm)\nqed\n\n\nlemma l2product_ladd:\n   \"\\<lbrakk>f square_integrable S; g square_integrable S; h square_integrable S\\<rbrakk>\n    \\<Longrightarrow> l2product S (\\<lambda>x. f x + g x) h = l2product S f h + l2product S g h\"\n  by (simp add: l2product_def algebra_simps square_integrable_imp_integrable_product)\n\nlemma l2product_radd:\n   \"\\<lbrakk>f square_integrable S; g square_integrable S; h square_integrable S\\<rbrakk>\n    \\<Longrightarrow> l2product S f(\\<lambda>x. g x + h x) = l2product S f g + l2product S f h\"\n  by (simp add: l2product_def algebra_simps square_integrable_imp_integrable_product)\n\nlemma l2product_ldiff:\n   \"\\<lbrakk>f square_integrable S; g square_integrable S; h square_integrable S\\<rbrakk>\n    \\<Longrightarrow> l2product S (\\<lambda>x. f x - g x) h = l2product S f h - l2product S g h\"\n  by (simp add: l2product_def algebra_simps square_integrable_imp_integrable_product)\n\nlemma l2product_rdiff:\n   \"\\<lbrakk>f square_integrable S; g square_integrable S; h square_integrable S\\<rbrakk>\n    \\<Longrightarrow> l2product S f(\\<lambda>x. g x - h x) = l2product S f g - l2product S f h\"\n  by (simp add: l2product_def algebra_simps square_integrable_imp_integrable_product)\n\nlemma l2product_lmult:\n   \"\\<lbrakk>f square_integrable S; g square_integrable S\\<rbrakk>\n    \\<Longrightarrow> l2product S (\\<lambda>x. c * f x) g = c * l2product S f g\"\n  by (simp add: l2product_def algebra_simps)\n\nlemma l2product_rmult:\n   \"\\<lbrakk>f square_integrable S; g square_integrable S\\<rbrakk>\n    \\<Longrightarrow> l2product S f(\\<lambda>x. c * g x) = c * l2product S f g\"\n  by (simp add: l2product_def algebra_simps)\n\nlemma l2product_lzero [simp]: \"l2product S (\\<lambda>x. 0) f = 0\"\n  by (simp add: l2product_def)\n\nlemma l2product_rzero [simp]: \"l2product S f(\\<lambda>x. 0) = 0\"\n  by (simp add: l2product_def)\n\nlemma l2product_lsum:\n  assumes I: \"finite I\" \"\\<And>i. i \\<in> I \\<Longrightarrow> (f i) square_integrable S\" and S: \"g square_integrable S\"\n  shows \"l2product S (\\<lambda>x. \\<Sum>i\\<in>I. f i x) g = (\\<Sum>i\\<in>I. l2product S (f i) g)\"\n  using I\nproof induction\n  case (insert i I)\n  with S show ?case\n    by (simp add: l2product_ladd square_integrable_imp_lebesgue)\nqed auto\n\nlemma l2product_rsum:\n  assumes I: \"finite I\" \"\\<And>i. i \\<in> I \\<Longrightarrow> (f i) square_integrable S\" and S: \"g square_integrable S\"\n  shows \"l2product S g (\\<lambda>x. \\<Sum>i\\<in>I. f i x) = (\\<Sum>i\\<in>I. l2product S g (f i))\"\n  using l2product_lsum [OF assms] by (simp add: l2product_sym)\n\nlemma l2norm_lmult:\n   \"f square_integrable S \\<Longrightarrow> l2norm S (\\<lambda>x. c * f x) = \\<bar>c\\<bar> * l2norm S f\"\n  by (simp add: l2norm_def l2product_rmult l2product_sym real_sqrt_mult)\n\nlemma l2norm_rmult:\n   \"f square_integrable S \\<Longrightarrow> l2norm S (\\<lambda>x. f x * c) = l2norm S f * \\<bar>c\\<bar>\"\n  using l2norm_lmult by (simp add: mult.commute)\n\nlemma l2norm_neg:\n   \"f square_integrable S \\<Longrightarrow> l2norm S (\\<lambda>x. - f x) = l2norm S f\"\n  using l2norm_lmult [of f S \"-1\"] by simp\n\nlemma l2norm_diff:\n  assumes \"f square_integrable S\" \"g square_integrable S\"\n  shows \"l2norm S (\\<lambda>x. f x - g x) = l2norm S (\\<lambda>x. g x - f x)\"\nproof -\n  have \"(\\<lambda>x. f x - g x) square_integrable S\"\n    using assms square_integrable_diff by blast\n  then show ?thesis\n    using l2norm_neg [of \"\\<lambda>x. f x - g x\" S] by (simp add: algebra_simps)\nqed\n\n\nsubsection\\<open>Completeness (Riesz-Fischer)\\<close>\n\nlemma eNorm_eq_lnorm: \"\\<lbrakk>f \\<in> lspace M p; p > 0\\<rbrakk> \\<Longrightarrow> eNorm (\\<LL> (ennreal p) M) f = ennreal (lnorm M p f)\"\n  by (simp add: Lp_D(4) lnorm_def)\n\nlemma Norm_eq_lnorm: \"\\<lbrakk>f \\<in> lspace M p; p > 0\\<rbrakk> \\<Longrightarrow> Norm (\\<LL> (ennreal p) M) f = lnorm M p f\"\n  by (simp add: Lp_D(3) lnorm_def)\n\n\nlemma eNorm_ge1_triangular_ineq:\n  assumes \"p \\<ge> (1::real)\"\n  shows \"eNorm (\\<LL> p M) (x + y) \\<le> eNorm (\\<LL> p M) x + eNorm (\\<LL> p M) y\"\n  using eNorm_triangular_ineq [of \"(\\<LL> p M)\"] assms\n  by (simp add: Lp(2))\n\ntext\\<open>A mere repackaging of the theorem @{thm Lp_complete}, but nearly as much work again.\\<close>\nproposition l2_complete:\n  assumes f: \"\\<And>i::nat. f i square_integrable S\"\n    and cauchy: \"\\<And>e. 0 < e \\<Longrightarrow> \\<exists>N. \\<forall>m\\<ge>N. \\<forall>n\\<ge>N. l2norm S (\\<lambda>x. f m x - f n x) < e\"\n  obtains g where \"g square_integrable S\" \"((\\<lambda>n. l2norm S (\\<lambda>x. f n x - g x)) \\<longlonglongrightarrow> 0)\"\nproof -\n  have finite: \"eNorm (\\<LL> 2 (lebesgue_on S)) (f n - f m) < \\<top>\" for m n\n    by (metis f infinity_ennreal_def spaceN_diff spaceN_iff square_integrable_imp_lspace)\n  have *: \"cauchy_ine\\<^sub>N (\\<LL> 2 (lebesgue_on S)) f\"\n  proof (clarsimp simp: cauchy_ine\\<^sub>N_def)\n    show \"\\<exists>M. \\<forall>n\\<ge>M. \\<forall>m\\<ge>M. eNorm (\\<LL> 2 (lebesgue_on S)) (f n - f m) < e\"\n      if \"e > 0\" for e\n    proof (cases e)\n      case (real r)\n      then have \"r > 0\"\n        using that by auto\n      with cauchy obtain N::nat where N: \"\\<And>m n. \\<lbrakk>m \\<ge> N; n \\<ge> N\\<rbrakk> \\<Longrightarrow> l2norm S (\\<lambda>x. f n x - f m x) < r\"\n        by blast\n      show ?thesis\n      proof (intro exI allI impI)\n        show \"eNorm (\\<LL> 2 (lebesgue_on S)) (f n - f m) < e\"\n          if \"N \\<le> m\" \"N \\<le> n\" for m n\n        proof -\n          have fnm: \"(f n - f m) \\<in> borel_measurable (lebesgue_on S)\"\n            using f unfolding square_integrable_def by (blast intro: borel_measurable_diff')\n          have \"l2norm S (\\<lambda>x. f n x - f m x) = lnorm (lebesgue_on S) 2 (\\<lambda>x. f n x - f m x)\"\n            by (metis l2norm_lnorm)\n          also have \"\\<dots> = Norm (\\<LL> 2 (lebesgue_on S)) (f n - f m)\"\n            using Lp_Norm [OF _ fnm, of 2] by (simp add: lnorm_def)\n          finally show ?thesis\n            using N [OF that] real finite\n            by (simp add: Norm_def)\n        qed\n      qed\n    qed (simp add: finite)\n  qed\n  then obtain g where g: \"tendsto_ine\\<^sub>N (\\<LL> 2 (lebesgue_on S)) f g\"\n    using Lp_complete complete\\<^sub>N_def by blast\n  show ?thesis\n  proof\n    have fng_to_0: \"(\\<lambda>n. eNorm (\\<LL> 2 (lebesgue_on S)) (\\<lambda>x. f n x - g x)) \\<longlonglongrightarrow> 0\"\n      using g Lp_D(4) [of 2 _ \"lebesgue_on S\"]\n      by (simp add: tendsto_ine\\<^sub>N_def minus_fun_def)\n    then obtain M where \"\\<And>n . n \\<ge> M \\<Longrightarrow> eNorm (\\<LL> 2 (lebesgue_on S)) (\\<lambda>x. f n x - g x) < \\<top>\"\n      apply (simp add: lim_explicit)\n      by (metis (full_types) open_lessThan diff_self eNorm_zero lessThan_iff local.finite)\n    then have \"eNorm (\\<LL> 2 (lebesgue_on S)) (\\<lambda>x. g x - f M x) < \\<top>\"\n      using eNorm_uminus [of _ \"\\<lambda>x. g x - f _ x\"] by (simp add: uminus_fun_def)\n    moreover have \"eNorm (\\<LL> 2 (lebesgue_on S)) (\\<lambda>x. f M x) < \\<top>\"\n      using f square_integrable_imp_lspace by (simp add: spaceN_iff)\n    ultimately have \"eNorm (\\<LL> 2 (lebesgue_on S)) g < \\<top>\"\n      using eNorm_ge1_triangular_ineq [of 2 \"lebesgue_on S\" \"g - f M\" \"f M\", simplified] not_le top.not_eq_extremum\n      by (fastforce simp add: minus_fun_def)\n    then have g_space: \"g \\<in> space\\<^sub>N (\\<LL> 2 (lebesgue_on S))\"\n      by (simp add: spaceN_iff)\n    show \"g square_integrable S\"\n      unfolding square_integrable_def\n    proof (intro conjI)\n      show \"g \\<in> borel_measurable (lebesgue_on S)\"\n        using Lp_measurable g_space by blast\n      show \"S \\<in> sets lebesgue\"\n        using f square_integrable_def by blast\n      then show \"integrable (lebesgue_on S) (\\<lambda>x. (g x)\\<^sup>2)\"\n        using g_space square_integrable_def square_integrable_iff_lspace by blast\n    qed\n    then have \"f n - g \\<in> lspace (lebesgue_on S) 2\" for n\n      using f spaceN_diff square_integrable_imp_lspace by blast\n    with fng_to_0 have \"(\\<lambda>n. ennreal (lnorm (lebesgue_on S) 2 (\\<lambda>x. f n x - g x))) \\<longlonglongrightarrow> 0\"\n      by (simp add: minus_fun_def flip: eNorm_eq_lnorm)\n    then have \"(\\<lambda>n. lnorm (lebesgue_on S) 2 (\\<lambda>x. f n x - g x)) \\<longlonglongrightarrow> 0\"\n      by (simp add: ennreal_tendsto_0_iff lnorm_def)\n    then show \"(\\<lambda>n. l2norm S (\\<lambda>x. f n x - g x)) \\<longlonglongrightarrow> 0\"\n      using g by (simp add:  l2norm_lnorm lnorm_def)\n  qed\nqed\n\nsubsection\\<open>Approximation of functions in Lp by bounded and continuous ones\\<close>\n\nlemma lspace_bounded_measurable:\n  fixes p::real\n  assumes f: \"f \\<in> borel_measurable (lebesgue_on S)\" and g: \"g \\<in> lspace (lebesgue_on S) p\" and \"p > 0\"\n    and le: \" AE x in lebesgue_on S. norm (\\<bar>f x\\<bar> powr p) \\<le> norm (\\<bar>g x\\<bar> powr p)\"\n  shows \"f \\<in> lspace (lebesgue_on S) p\"\n  using assms by (auto simp: lspace_ennreal_iff intro: Bochner_Integration.integrable_bound)\n\nlemma lspace_approximate_bounded:\n  assumes f: \"f \\<in> lspace (lebesgue_on S) p\" and S: \"S \\<in> lmeasurable\" and \"p > 0\" \"e > 0\"\n  obtains g where \"g \\<in> lspace (lebesgue_on S) p\" \"bounded (g ` S)\"\n    \"lnorm (lebesgue_on S) p (f - g) < e\"\nproof -\n  have f_bm: \"f \\<in> borel_measurable (lebesgue_on S)\"\n    using Lp_measurable f by blast\n  let ?f = \"\\<lambda>n::nat. \\<lambda>x. max (- n) (min n (f x))\"\n  have \"tendsto_in\\<^sub>N (\\<LL> p (lebesgue_on S)) ?f f\"\n  proof (rule Lp_domination_limit)\n    show \"\\<And>n::nat. ?f n \\<in> borel_measurable (lebesgue_on S)\"\n      by (intro f_bm borel_measurable_max borel_measurable_min borel_measurable_const)\n    show \"abs \\<circ> f \\<in> lspace (lebesgue_on S) p\"\n      using Lp_Banach_lattice [OF f] by (simp add: o_def)\n    have *: \"\\<forall>\\<^sub>F n in sequentially. dist (?f n x) (f x) < e\"\n      if x: \"x \\<in> space (lebesgue_on S)\" and \"e > 0\" for x e\n    proof\n      show \"dist (?f n x) (f x) < e\"\n        if \"nat \\<lceil>\\<bar>f x\\<bar>\\<rceil> \\<le> n\" for n :: nat\n        using that \\<open>0 < e\\<close> by (simp add: dist_real_def max_def min_def abs_if split: if_split_asm)\n    qed\n    then show \"AE x in lebesgue_on S. (\\<lambda>n::nat. max (- n) (min n (f x))) \\<longlonglongrightarrow> f x\"\n      by (blast intro: tendstoI)\n  qed (auto simp: f_bm)\n  moreover\n  have lspace: \"?f n \\<in> lspace (lebesgue_on S) p\" for n::nat\n    by (intro f lspace_const lspace_min lspace_max \\<open>p > 0\\<close> S)\n  ultimately have \"(\\<lambda>n. lnorm (lebesgue_on S) p (?f n - f)) \\<longlonglongrightarrow> 0\"\n    by (simp add: tendsto_in\\<^sub>N_def Norm_eq_lnorm \\<open>p > 0\\<close> f)\n  with \\<open>e > 0\\<close> obtain N where N: \"\\<bar>lnorm (lebesgue_on S) p (?f N - f)\\<bar> < e\"\n    by (auto simp: LIMSEQ_iff)\n  show ?thesis\n  proof\n    have \"\\<forall>x\\<in>S. \\<bar>max (- real N) (min (real N) (f x))\\<bar> \\<le> N\"\n      by auto\n    then show \"bounded (?f N ` S::real set)\"\n      by (force simp: bounded_iff)\n    show \"lnorm (lebesgue_on S) p (f - ?f N) < e\"\n      using N by (simp add: lnorm_minus_commute)\n  qed (auto simp: lspace)\nqed\n\nlemma borel_measurable_imp_continuous_limit:\n  fixes h :: \"'a::euclidean_space \\<Rightarrow> 'b::euclidean_space\"\n  assumes h: \"h \\<in> borel_measurable (lebesgue_on S)\" and S: \"S \\<in> sets lebesgue\"\n  obtains g where \"\\<And>n. continuous_on UNIV (g n)\" \"AE x in lebesgue_on S. (\\<lambda>n::nat. g n x) \\<longlonglongrightarrow> h x\"\nproof -\n  have \"h measurable_on S\"\n    using S h measurable_on_iff_borel_measurable by blast\n  then obtain N g where N: \"N \\<in> null_sets lebesgue\" and g: \"\\<And>n. continuous_on UNIV (g n)\"\n    and tends: \"\\<And>x. x \\<notin> N \\<Longrightarrow> (\\<lambda>n. g n x) \\<longlonglongrightarrow> (if x \\<in> S then h x else 0)\"\n    by (auto simp: measurable_on_def negligible_iff_null_sets)\n  moreover have \"AE x in lebesgue_on S. (\\<lambda>n::nat. g n x) \\<longlonglongrightarrow> h x\"\n  proof (rule AE_I')\n    show \"N \\<inter> S \\<in> null_sets (lebesgue_on S)\"\n      by (simp add: S N null_set_Int2 null_sets_restrict_space)\n    show \"{x \\<in> space (lebesgue_on S). \\<not> (\\<lambda>n. g n x) \\<longlonglongrightarrow> h x} \\<subseteq> N \\<inter> S\"\n      using tends by force\n  qed\n  ultimately show thesis\n    using that by blast\nqed\n\n\nproposition lspace_approximate_continuous:\n  assumes f: \"f \\<in> lspace (lebesgue_on S) p\" and S: \"S \\<in> lmeasurable\" and \"1 \\<le> p\" \"e > 0\"\n  obtains g where \"continuous_on UNIV g\" \"g \\<in> lspace (lebesgue_on S) p\" \"lnorm (lebesgue_on S) p (f - g) < e\"\nproof -\n  have \"p > 0\"\n    using assms by simp\n  obtain h where h: \"h \\<in> lspace (lebesgue_on S) p\" and \"bounded (h ` S)\"\n    and lesse2: \"lnorm (lebesgue_on S) p (f - h) < e/2\"\n    by (rule lspace_approximate_bounded [of f p S \"e/2\"]) (use assms in auto)\n  then obtain B where \"B > 0\" and B: \"\\<And>x. x \\<in> S \\<Longrightarrow> \\<bar>h x\\<bar> \\<le> B\"\n    by (auto simp: bounded_pos)\n  have bmh: \"h \\<in> borel_measurable (lebesgue_on S)\"\n    using h lspace_ennreal_iff [of p] \\<open>p \\<ge> 1\\<close> by auto\n  obtain g where contg: \"\\<And>n. continuous_on UNIV (g n)\"\n    and gle: \"\\<And>n x. x \\<in> S \\<Longrightarrow> \\<bar>g n x\\<bar> \\<le> B\"\n    and tends: \"AE x in lebesgue_on S. (\\<lambda>n::nat. g n x) \\<longlonglongrightarrow> h x\"\n  proof -\n    obtain \\<gamma> where cont: \"\\<And>n. continuous_on UNIV (\\<gamma> n)\"\n      and tends: \"AE x in lebesgue_on S. (\\<lambda>n::nat. \\<gamma> n x) \\<longlonglongrightarrow> h x\"\n      using borel_measurable_imp_continuous_limit S bmh by blast\n    let ?g = \"\\<lambda>n::nat. \\<lambda>x. max (- B) (min B (\\<gamma> n x))\"\n    show thesis\n    proof\n      show \"continuous_on UNIV (?g n)\" for n\n        by (intro continuous_intros cont)\n      show \"\\<bar>?g n x\\<bar> \\<le> B\" if \"x \\<in> S\"  for n x\n        using that \\<open>B > 0\\<close> by (auto simp: max_def min_def)\n      have \"(\\<lambda>n. max (- B) (min B (\\<gamma> n x))) \\<longlonglongrightarrow> h x\"\n        if \"(\\<lambda>n. \\<gamma> n x) \\<longlonglongrightarrow> h x\" \"x \\<in> S\" for x\n        using that \\<open>B > 0\\<close> B [OF \\<open>x \\<in> S\\<close>]\n        unfolding LIMSEQ_def by (fastforce simp: min_def max_def dist_real_def)\n      then show \"AE x in lebesgue_on S. (\\<lambda>n. ?g n x) \\<longlonglongrightarrow> h x\"\n        using tends by auto\n    qed\n  qed\n  have lspace_B: \"(\\<lambda>x. B) \\<in> lspace (lebesgue_on S) p\"\n    by (simp add: S \\<open>0 < p\\<close> lspace_const)\n  have lspace_g: \"g n \\<in> lspace (lebesgue_on S) p\" for n\n  proof (rule lspace_bounded_measurable)\n    show \"g n \\<in> borel_measurable (lebesgue_on S)\"\n      by (simp add: borel_measurable_continuous_onI contg measurable_completion measurable_restrict_space1)\n    show \"AE x in lebesgue_on S. norm (\\<bar>g n x\\<bar> powr p) \\<le> norm (\\<bar>B\\<bar> powr p)\"\n      using \\<open>B > 0\\<close> gle S \\<open>0 < p\\<close> powr_mono2 by auto\n  qed (use \\<open>p > 0\\<close> lspace_B in auto)\n  have \"tendsto_in\\<^sub>N (\\<LL> p (lebesgue_on S)) g h\"\n  proof (rule Lp_domination_limit [OF bmh _ lspace_B tends])\n    show \"\\<And>n::nat. g n \\<in> borel_measurable (lebesgue_on S)\"\n      using Lp_measurable lspace_g by blast\n    show \"\\<And>n. AE x in lebesgue_on S. \\<bar>g n x\\<bar> \\<le> B\"\n      using S gle by auto\n  qed\n  then have 0: \"(\\<lambda>n. Norm (\\<LL> p (lebesgue_on S)) (g n - h)) \\<longlonglongrightarrow> 0\"\n    by (simp add: tendsto_in\\<^sub>N_def)\n  have \"\\<And>e. 0 < e \\<Longrightarrow> \\<exists>N. \\<forall>n\\<ge>N. lnorm (lebesgue_on S) p (g n - h) < e\"\n    using LIMSEQ_D [OF 0] \\<open>e > 0\\<close>\n    by (force simp: Norm_eq_lnorm \\<open>0 < p\\<close> h lspace_g)\n  then obtain N where N: \"lnorm (lebesgue_on S) p (g N - h) < e/2\"\n    unfolding minus_fun_def by (meson \\<open>e>0\\<close> half_gt_zero order_refl)\n  show ?thesis\n  proof\n    show \"continuous_on UNIV (g N)\"\n      by (simp add: contg)\n    show \"g N \\<in> lspace (lebesgue_on S) (ennreal p)\"\n      by (simp add: lspace_g)\n    have \"lnorm (lebesgue_on S) p (f - h + - (g N - h)) \\<le> lnorm (lebesgue_on S) p (f - h) + lnorm (lebesgue_on S) p (- (g N - h))\"\n      by (rule lnorm_triangle_fun) (auto simp: lspace_g h assms)\n    also have \"\\<dots>  < e/2 + e/2\"\n      using lesse2 N by (simp add: lnorm_minus_commute)\n    finally show \"lnorm (lebesgue_on S) p (f - g N) < e\"\n      by simp\n  qed\nqed\n\nproposition square_integrable_approximate_continuous:\n  assumes f: \"f square_integrable S\" and S: \"S \\<in> lmeasurable\" and \"e > 0\"\n  obtains g where \"continuous_on UNIV g\" \"g square_integrable S\" \"l2norm S (\\<lambda>x. f x - g x) < e\"\nproof -\n  have f2: \"f \\<in> lspace (lebesgue_on S) 2\"\n    by (simp add: f square_integrable_imp_lspace)\n  then obtain g where contg: \"continuous_on UNIV g\"\n             and g2: \"g \\<in> lspace (lebesgue_on S) 2\"\n             and less_e: \"lnorm (lebesgue_on S) 2 (\\<lambda>x. f x - g x) < e\"\n    using lspace_approximate_continuous [of f 2 S e] S \\<open>0 < e\\<close> by (auto simp: minus_fun_def)\n  show thesis\n  proof\n    show \"g square_integrable S\"\n      using g2 by (simp add: S fmeasurableD square_integrable_iff_lspace)\n    show \"l2norm S (\\<lambda>x. f x - g x) < e\"\n      using less_e by (simp add: l2norm_lnorm)\n  qed (simp add: contg)\nqed\n\nlemma absolutely_integrable_approximate_continuous:\n  fixes f :: \"real \\<Rightarrow> real\"\n  assumes f: \"f absolutely_integrable_on S\" and S: \"S \\<in> lmeasurable\" and \"0 < e\"\n  obtains g where \"continuous_on UNIV g\" \"g absolutely_integrable_on S\" \"integral\\<^sup>L (lebesgue_on S) (\\<lambda>x. \\<bar>f x - g x\\<bar>) < e\"\nproof -\n  obtain g where \"continuous_on UNIV g\" \"g \\<in> lspace (lebesgue_on S) 1\"\n              and lnorm: \"lnorm (lebesgue_on S) 1 (f - g) < e\"\n  proof (rule lspace_approximate_continuous)\n    show \"f \\<in> lspace (lebesgue_on S) (ennreal 1)\"\n      by (simp add: S f fmeasurableD lspace_1)\n  qed (auto simp: assms)\n  show thesis\n  proof\n    show \"continuous_on UNIV g\"\n      by fact\n    show \"g absolutely_integrable_on S\"\n      using S \\<open>g \\<in> lspace (lebesgue_on S) 1\\<close> lspace_1 by blast\n    have *: \"(\\<lambda>x. f x - g x) absolutely_integrable_on S\"\n      by (simp add: \\<open>g absolutely_integrable_on S\\<close> f)\n    moreover have \"integrable (lebesgue_on S) (\\<lambda>x. \\<bar>f x - g x\\<bar>)\"\n      by (simp add: L1_D(2) S * fmeasurableD lspace_1)\n    ultimately show \"integral\\<^sup>L (lebesgue_on S)  (\\<lambda>x. \\<bar>f x - g x\\<bar>) < e\"\n      using lnorm S unfolding lnorm_def absolutely_integrable_on_def\n      by 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/Fourier/Square_Integrable.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8740772384450968, "lm_q2_score": 0.8311430436757313, "lm_q1q2_score": 0.7264832163689356}}
{"text": "theory mult\n  imports Main soma\nbegin\nprimrec mult::\"nat \\<Rightarrow> nat \\<Rightarrow> nat\" where\nmulteq1:\"mult x 0 = 0\"|\nmulteq2:\"mult x (Suc y) = soma x (mult x y)\"\n\nthm nat.induct\nprint_statement nat.induct\n\nvalue \"mult 1 0\"\nvalue \"mult 1 1\"\nvalue \"mult 1 2\"\nvalue \"mult 2 2\"\nvalue \"mult 2 3\"\n\ntheorem mult1:\"\\<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:multeq1)\n    also have \"... = x0 * 0\" by simp\n    finally show \"mult x0 0 = x0 * 0\" by simp\n  qed\nnext\n  fix y0::nat\n  assume HI:\"\\<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) = soma x0 (mult x0 y0)\" by (simp only:multeq2)\n    also have \"... = soma x0 (x0 * y0)\" by (simp only:HI)\n    also have \"... = soma (x0 * y0) x0\" by (simp only:soma2)\n    also have \"... = (x0 * y0) + x0\" by (simp only:soma1)\n    also have \"... = x0 * (Suc y0) + 0\" by simp\n    also have \"... = soma (x0 * (Suc y0)) 0\" by (simp only:soma1)\n    also have \"... = x0 * (Suc y0)\" by (simp only:somaeq1)\n    finally show \"mult x0 (Suc y0) = x0 * (Suc y0)\" by simp\n  qed\nqed\n\ntheorem mult2:\"\\<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:multeq1)\n    also have \"... = 0*x0\" by simp\n    also have \"... = 0*x0 + 0\" by simp\n    also have \"... = (mult 0 x0) + 0\" by (simp only:mult1)\n    also have \"... = soma (mult 0 x0) 0\" by (simp only:soma1)\n    also have \"... = mult 0 x0\" by (simp only:somaeq1)\n    finally show \"mult x0 0 = mult 0 x0\" by simp\n  qed\nnext\n  fix y0::nat\n  assume HI: \"\\<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) = soma x0 (mult x0 y0)\" by (simp only:multeq2)\n    also have \"... = soma x0 (mult y0 x0)\" by (simp only:HI)\n    also have \"... = soma x0 (y0 * x0)\" by (simp only:mult1)\n    also have \"... = soma (y0 * x0) x0\" by (simp only:soma2)\n    also have \"... = (y0 * x0) + x0\" by (simp only:soma1)\n    also have \"... = (Suc y0) * x0 + 0\" by simp\n    also have \"... = soma ((Suc y0) * x0) 0\" by (simp only:soma1)\n    also have \"... = (Suc y0) * x0\" by (simp only:somaeq1)\n    also have \"... = mult (Suc y0) x0\" by (simp only:mult1)\n    finally show \"mult x0 (Suc y0) = mult (Suc y0) x0\" by simp\n  qed\nqed\n", "meta": {"author": "pedroeml", "repo": "metodos-formais", "sha": "400e4a747786792f2654590e617ab86ae39517da", "save_path": "github-repos/isabelle/pedroeml-metodos-formais", "path": "github-repos/isabelle/pedroeml-metodos-formais/metodos-formais-400e4a747786792f2654590e617ab86ae39517da/T1/mult.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772253241802, "lm_q2_score": 0.8311430520409023, "lm_q1q2_score": 0.7264832127753826}}
{"text": "\\<^marker>\\<open>creator \"Kevin Kappelmann\"\\<close>\nsubsection \\<open>Antisymmetric\\<close>\ntheory SBinary_Relations_Antisymmetric\n  imports\n    Pairs\nbegin\n\ndefinition \"antisymmetric D R \\<equiv> \\<forall>x y \\<in> D. \\<langle>x, y\\<rangle> \\<in> R \\<and> \\<langle>y, x\\<rangle> \\<in> R \\<longrightarrow> x = y\"\n\nlemma antisymmetricI [intro]:\n  assumes \"\\<And>x y. x \\<in> D \\<Longrightarrow> y \\<in> D \\<Longrightarrow> \\<langle>x, y\\<rangle> \\<in> R \\<Longrightarrow> \\<langle>y, x\\<rangle> \\<in> R \\<Longrightarrow> x = y\"\n  shows \"antisymmetric D R\"\n  using assms unfolding antisymmetric_def by blast\n\nlemma antisymmetricD:\n  assumes \"antisymmetric D R\"\n  and \"x \\<in> D\" \"y \\<in> D\"\n  and \"\\<langle>x, y\\<rangle> \\<in> R\" \"\\<langle>y, x\\<rangle> \\<in> R\"\n  shows \"x = y\"\n  using assms unfolding antisymmetric_def by blast\n\n\nend", "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/HOTG/Binary_Relations/Properties/SBinary_Relations_Antisymmetric.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772220439509, "lm_q2_score": 0.8311430415844385, "lm_q1q2_score": 0.726483200909286}}
{"text": "section \\<open>Some Uncountable Sets\\<close>\n\ntheory Uncountable_Sets\n  imports Path_Connected Continuum_Not_Denumerable  \nbegin\n\nlemma uncountable_closed_segment:\n  fixes a :: \"'a::real_normed_vector\"\n  assumes \"a \\<noteq> b\" shows \"uncountable (closed_segment a b)\"\nunfolding path_image_linepath [symmetric] path_image_def\n  using inj_on_linepath [OF assms] uncountable_closed_interval [of 0 1]\n        countable_image_inj_on by auto\n\nlemma uncountable_open_segment:\n  fixes a :: \"'a::real_normed_vector\"\n  assumes \"a \\<noteq> b\" shows \"uncountable (open_segment a b)\"\n  by (simp add: assms open_segment_def uncountable_closed_segment uncountable_minus_countable)\n\nlemma uncountable_convex:\n  fixes a :: \"'a::real_normed_vector\"\n  assumes \"convex S\" \"a \\<in> S\" \"b \\<in> S\" \"a \\<noteq> b\"\n    shows \"uncountable S\"\nproof -\n  have \"uncountable (closed_segment a b)\"\n    by (simp add: uncountable_closed_segment assms)\n  then show ?thesis\n    by (meson assms convex_contains_segment countable_subset)\nqed\n\nlemma uncountable_ball:\n  fixes a :: \"'a::euclidean_space\"\n  assumes \"r > 0\"\n    shows \"uncountable (ball a r)\"\nproof -\n  have \"uncountable (open_segment a (a + r *\\<^sub>R (SOME i. i \\<in> Basis)))\"\n    by (metis Basis_zero SOME_Basis add_cancel_right_right assms less_le scale_eq_0_iff uncountable_open_segment)\n  moreover have \"open_segment a (a + r *\\<^sub>R (SOME i. i \\<in> Basis)) \\<subseteq> ball a r\"\n    using assms by (auto simp: in_segment algebra_simps dist_norm SOME_Basis)\n  ultimately show ?thesis\n    by (metis countable_subset)\nqed\n\nlemma ball_minus_countable_nonempty:\n  assumes \"countable (A :: 'a :: euclidean_space set)\" \"r > 0\"\n  shows   \"ball z r - A \\<noteq> {}\"\nproof\n  assume *: \"ball z r - A = {}\"\n  have \"uncountable (ball z r - A)\"\n    by (intro uncountable_minus_countable assms uncountable_ball)\n  thus False by (subst (asm) *) auto\nqed\n\nlemma uncountable_cball:\n  fixes a :: \"'a::euclidean_space\"\n  assumes \"r > 0\"\n  shows \"uncountable (cball a r)\"\n  using assms countable_subset uncountable_ball by auto\n\nlemma pairwise_disjnt_countable:\n  fixes \\<N> :: \"nat set set\"\n  assumes \"pairwise disjnt \\<N>\"\n    shows \"countable \\<N>\"\n  by (simp add: assms countable_disjoint_open_subsets open_discrete)\n\nlemma pairwise_disjnt_countable_Union:\n    assumes \"countable (\\<Union>\\<N>)\" and pwd: \"pairwise disjnt \\<N>\"\n    shows \"countable \\<N>\"\nproof -\n  obtain f :: \"_ \\<Rightarrow> nat\" where f: \"inj_on f (\\<Union>\\<N>)\"\n    using assms by blast\n  then have \"pairwise disjnt (\\<Union> X \\<in> \\<N>. {f ` X})\"\n    using assms by (force simp: pairwise_def disjnt_inj_on_iff [OF f])\n  then have \"countable (\\<Union> X \\<in> \\<N>. {f ` X})\"\n    using pairwise_disjnt_countable by blast\n  then show ?thesis\n    by (meson pwd countable_image_inj_on disjoint_image f inj_on_image pairwise_disjnt_countable)\nqed\n\nlemma connected_uncountable:\n  fixes S :: \"'a::metric_space set\"\n  assumes \"connected S\" \"a \\<in> S\" \"b \\<in> S\" \"a \\<noteq> b\" shows \"uncountable S\"\nproof -\n  have \"continuous_on S (dist a)\"\n    by (intro continuous_intros)\n  then have \"connected (dist a ` S)\"\n    by (metis connected_continuous_image \\<open>connected S\\<close>)\n  then have \"closed_segment 0 (dist a b) \\<subseteq> (dist a ` S)\"\n    by (simp add: assms closed_segment_subset is_interval_connected_1 is_interval_convex)\n  then have \"uncountable (dist a ` S)\"\n    by (metis \\<open>a \\<noteq> b\\<close> countable_subset dist_eq_0_iff uncountable_closed_segment)\n  then show ?thesis\n    by blast\nqed\n\nlemma path_connected_uncountable:\n  fixes S :: \"'a::metric_space set\"\n  assumes \"path_connected S\" \"a \\<in> S\" \"b \\<in> S\" \"a \\<noteq> b\" shows \"uncountable S\"\n  using path_connected_imp_connected assms connected_uncountable by metis\n\nlemma simple_path_image_uncountable: \n  fixes g :: \"real \\<Rightarrow> 'a::metric_space\"\n  assumes \"simple_path g\"\n  shows \"uncountable (path_image g)\"\nproof -\n  have \"g 0 \\<in> path_image g\" \"g (1/2) \\<in> path_image g\"\n    by (simp_all add: path_defs)\n  moreover have \"g 0 \\<noteq> g (1/2)\"\n    using assms by (fastforce simp add: simple_path_def loop_free_def)\n  ultimately have \"\\<forall>a. \\<not> path_image g \\<subseteq> {a}\"\n    by blast\n  then show ?thesis\n    using assms connected_simple_path_image connected_uncountable by blast\nqed\n\nlemma arc_image_uncountable:\n  fixes g :: \"real \\<Rightarrow> 'a::metric_space\"\n  assumes \"arc g\"\n  shows \"uncountable (path_image g)\"\n  by (simp add: arc_imp_simple_path assms simple_path_image_uncountable)\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/Uncountable_Sets.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513620489619, "lm_q2_score": 0.8104789018037399, "lm_q1q2_score": 0.7263928196535488}}
{"text": "(* ---------------------------------------------------------------------------- *)\nsection \\<open>Circlines\\<close>\n(* ---------------------------------------------------------------------------- *)\ntheory Circlines\n  imports More_Set Moebius Hermitean_Matrices Elementary_Complex_Geometry\nbegin\n\n(* ----------------------------------------------------------------- *)\nsubsection \\<open>Definition of circlines\\<close>\n(* ----------------------------------------------------------------- *)\n\ntext \\<open>In our formalization we follow the approach described by Schwerdtfeger\n\\cite{schwerdtfeger} and represent circlines by Hermitean, non-zero\n$2\\times 2$ matrices. In the original formulation, a matrix\n$\\left(\\begin{array}{cc}A & B\\\\C & D\\end{array}\\right)$ corresponds to\nthe equation $A\\cdot z\\cdot \\overline{z} + B\\cdot \\overline{z} + C\\cdot z + D = 0$,\nwhere $C = \\overline{B}$ and $A$ and $D$ are real (as the matrix is\nHermitean).\\<close>\n\nabbreviation hermitean_nonzero where\n  \"hermitean_nonzero \\<equiv> {H. hermitean H \\<and> H \\<noteq> mat_zero}\"\n\ntypedef circline_mat = hermitean_nonzero\nby (rule_tac x=\"eye\" in exI) (auto simp add: hermitean_def mat_adj_def mat_cnj_def)\n\nsetup_lifting type_definition_circline_mat\n\n\ndefinition circline_eq_cmat :: \"complex_mat \\<Rightarrow> complex_mat \\<Rightarrow> bool\" where\n [simp]: \"circline_eq_cmat A B \\<longleftrightarrow> (\\<exists> k::real. k \\<noteq> 0 \\<and> B = cor k *\\<^sub>s\\<^sub>m A)\"\n\nlemma symp_circline_eq_cmat: \"symp circline_eq_cmat\"\n  unfolding symp_def\nproof ((rule allI)+, rule impI)\n  fix x y\n  assume \"circline_eq_cmat x y\"\n  then obtain k where \"k \\<noteq> 0 \\<and> y = cor k *\\<^sub>s\\<^sub>m x\"\n    by auto\n  hence  \"1 / k \\<noteq> 0 \\<and> x = cor (1 / k) *\\<^sub>s\\<^sub>m y\"\n    by auto\n  thus \"circline_eq_cmat y x\"\n    unfolding circline_eq_cmat_def\n    by blast\nqed\n\ntext\\<open>Hermitean non-zero matrices are equivalent only to such matrices\\<close>\nlemma circline_eq_cmat_hermitean_nonzero:\n  assumes \"hermitean H \\<and> H \\<noteq> mat_zero\" \"circline_eq_cmat H H'\"\n  shows \"hermitean H' \\<and> H' \\<noteq> mat_zero\"\n  using assms\n  by (metis circline_eq_cmat_def hermitean_mult_real nonzero_mult_real of_real_eq_0_iff)\n\n\nlift_definition circline_eq_clmat :: \"circline_mat \\<Rightarrow> circline_mat \\<Rightarrow> bool\" is circline_eq_cmat\n  done\n\nlemma circline_eq_clmat_refl [simp]: \"circline_eq_clmat H H\"\n  by transfer (simp, rule_tac x=\"1\" in exI, simp)\n\nquotient_type circline = circline_mat / circline_eq_clmat\nproof (rule equivpI)\n  show \"reflp circline_eq_clmat\"\n    unfolding reflp_def\n    by transfer (auto, rule_tac x=\"1\" in exI, simp)\nnext\n  show \"symp circline_eq_clmat\"\n    unfolding symp_def\n    by transfer (auto, (rule_tac x=\"1/k\" in exI, simp)+)\nnext\n  show \"transp circline_eq_clmat\"\n    unfolding transp_def\n    by transfer (simp, safe, (rule_tac x=\"ka*k\" in exI, simp)+)\nqed\n\ntext \\<open>Circline with specified matrix\\<close>\n\ntext \\<open>An auxiliary constructor @{term mk_circline} returns a circline (an\nequivalence class) for given four complex numbers $A$, $B$, $C$ and\n$D$ (provided that they form a Hermitean, non-zero matrix).\\<close>\n\ndefinition mk_circline_cmat :: \"complex \\<Rightarrow> complex \\<Rightarrow> complex \\<Rightarrow> complex \\<Rightarrow> complex_mat\" where\n[simp]: \"mk_circline_cmat A B C D =\n          (let M = (A, B, C, D)\n            in if M \\<in> hermitean_nonzero then\n                  M\n               else\n                  eye)\"\n\nlift_definition mk_circline_clmat :: \"complex \\<Rightarrow> complex \\<Rightarrow> complex \\<Rightarrow> complex \\<Rightarrow> circline_mat\" is mk_circline_cmat\n  by (auto simp add: Let_def hermitean_def mat_adj_def mat_cnj_def)\n\nlift_definition mk_circline :: \"complex \\<Rightarrow> complex \\<Rightarrow> complex \\<Rightarrow> complex \\<Rightarrow> circline\" is mk_circline_clmat\n  done\n\nlemma ex_mk_circline:\n  shows \"\\<exists> A B C D. H = mk_circline A B C D \\<and> hermitean (A, B, C, D) \\<and> (A, B, C, D) \\<noteq> mat_zero\"\nproof (transfer, transfer)\n  fix H\n  assume *: \"hermitean H \\<and> H \\<noteq> mat_zero\"\n  obtain A B C D where \"H = (A, B, C, D)\"\n    by (cases \" H\", auto)\n  hence \"circline_eq_cmat H (mk_circline_cmat A B C D) \\<and> hermitean (A, B, C, D) \\<and> (A, B, C, D) \\<noteq> mat_zero\"\n    using *\n    by auto\n  thus \"\\<exists> A B C D. circline_eq_cmat H (mk_circline_cmat A B C D) \\<and> hermitean (A, B, C, D) \\<and> (A, B, C, D) \\<noteq> mat_zero\"\n    by blast\nqed\n\n(* ----------------------------------------------------------------- *)\nsubsection \\<open>Circline type\\<close>\n(* ----------------------------------------------------------------- *)\n\ndefinition circline_type_cmat :: \"complex_mat \\<Rightarrow> real\" where\n  [simp]: \"circline_type_cmat H = sgn (Re (mat_det H))\"\n\nlift_definition circline_type_clmat :: \"circline_mat \\<Rightarrow> real\" is circline_type_cmat\n  done\n\nlift_definition circline_type :: \"circline \\<Rightarrow> real\" is circline_type_clmat\n  by transfer (simp, erule exE, simp add: sgn_mult)\n\nlemma circline_type: \"circline_type H = -1 \\<or> circline_type H = 0 \\<or> circline_type H = 1\"\n  by (transfer, transfer, simp add: sgn_if)\n\nlemma circline_type_mk_circline [simp]:\n  assumes \"(A, B, C, D) \\<in> hermitean_nonzero\"\n  shows  \"circline_type (mk_circline A B C D) = sgn (Re (A*D - B*C))\"\n  using assms\n  by (transfer, transfer, simp)\n\n(* ----------------------------------------------------------------- *)\nsubsection \\<open>Points on the circline\\<close>\n(* ----------------------------------------------------------------- *)\n\ntext \\<open>Each circline determines a corresponding set of points. Again, a description given in\nhomogeneous coordinates is a bit better than the original description defined only for ordinary\ncomplex numbers. The point with homogeneous coordinates $(z_1, z_2)$ will belong to the set of\ncircline points iff $A \\cdot z_1\\cdot \\overline{z_1} + B\\cdot \\overline{z_1} \\cdot z_2 + C\\cdot z_1 \\cdot\\overline{z_2} +\nD\\cdot z_2 \\cdot \\overline{z_2} = 0$. Note that this is a quadratic form determined by a vector of\nhomogeneous coordinates and the Hermitean matrix.\\<close>\n\ndefinition on_circline_cmat_cvec :: \"complex_mat \\<Rightarrow> complex_vec \\<Rightarrow> bool\" where\n  [simp]: \"on_circline_cmat_cvec H z \\<longleftrightarrow> quad_form z H = 0\"\n\nlift_definition on_circline_clmat_hcoords :: \"circline_mat \\<Rightarrow> complex_homo_coords \\<Rightarrow> bool\" is on_circline_cmat_cvec\n  done\n\nlift_definition on_circline :: \"circline \\<Rightarrow> complex_homo \\<Rightarrow> bool\" is on_circline_clmat_hcoords\n  by transfer (simp del: quad_form_def, (erule exE)+, simp del: quad_form_def add: quad_form_scale_m quad_form_scale_v)\n\ndefinition circline_set :: \"circline \\<Rightarrow> complex_homo set\" where\n  \"circline_set H = {z. on_circline H z}\"\n\nlemma circline_set_I [simp]:\n  assumes \"on_circline H z\"\n  shows \"z \\<in> circline_set H\"\n  using assms\n  unfolding circline_set_def\n  by auto\n\nabbreviation circline_equation where\n  \"circline_equation A B C D z1 z2 \\<equiv> A*z1*cnj z1 + B*z2*cnj z1 + C*cnj z2*z1 + D*z2*cnj z2 = 0\"\n\nlemma on_circline_cmat_cvec_circline_equation:\n  \"on_circline_cmat_cvec (A, B, C, D) (z1, z2) \\<longleftrightarrow> circline_equation A B C D z1 z2\"\n  by (simp add: vec_cnj_def field_simps)\n\nlemma circline_equation:\n  assumes \"H = mk_circline A B C D\" and \"(A, B, C, D) \\<in> hermitean_nonzero\"\n  shows \"of_complex z \\<in> circline_set H \\<longleftrightarrow> circline_equation A B C D z 1\"\n  using assms\n  unfolding circline_set_def\n  by simp (transfer, transfer, simp add: vec_cnj_def field_simps)\n\ntext \\<open>Circlines trough 0 and inf.\\<close>\ntext \\<open>The circline represents a line when $A=0$ or a circle, otherwise.\\<close>\n\ndefinition circline_A0_cmat :: \"complex_mat \\<Rightarrow> bool\" where\n  [simp]: \"circline_A0_cmat H \\<longleftrightarrow> (let (A, B, C, D) = H in A = 0)\"\nlift_definition circline_A0_clmat :: \"circline_mat \\<Rightarrow> bool\" is circline_A0_cmat\n  done\nlift_definition circline_A0 :: \"circline \\<Rightarrow> bool\" is circline_A0_clmat\n  by transfer auto\n\nabbreviation is_line where\n  \"is_line H \\<equiv> circline_A0 H\"\n\nabbreviation is_circle where\n  \"is_circle H \\<equiv> \\<not> circline_A0 H\"\n\ndefinition circline_D0_cmat :: \"complex_mat \\<Rightarrow> bool\" where\n  [simp]: \"circline_D0_cmat H \\<longleftrightarrow> (let (A, B, C, D) = H in D = 0)\"\nlift_definition circline_D0_clmat :: \"circline_mat \\<Rightarrow> bool\" is circline_D0_cmat\n  done\nlift_definition circline_D0 :: \"circline \\<Rightarrow> bool\" is circline_D0_clmat\n  by transfer auto\n\nlemma inf_on_circline: \"on_circline H \\<infinity>\\<^sub>h \\<longleftrightarrow> circline_A0 H\"\n  by (transfer, transfer, auto simp add: vec_cnj_def)\n\nlemma\n  inf_in_circline_set: \"\\<infinity>\\<^sub>h \\<in> circline_set H \\<longleftrightarrow> is_line H\"\n  using inf_on_circline\n  unfolding circline_set_def\n  by simp\n\nlemma zero_on_circline: \"on_circline H 0\\<^sub>h \\<longleftrightarrow> circline_D0 H\"\n  by (transfer, transfer, auto simp add: vec_cnj_def)\n\nlemma\n  zero_in_circline_set: \"0\\<^sub>h \\<in> circline_set H \\<longleftrightarrow> circline_D0 H\"\n  using zero_on_circline\n  unfolding circline_set_def\n  by simp\n\n(* ----------------------------------------------------------------- *)\nsubsection \\<open>Connection with circles and lines in the classic complex plane\\<close>\n(* ----------------------------------------------------------------- *)\n\ntext \\<open>Every Euclidean circle and Euclidean line can be represented by a\ncircline.\\<close>\n\nlemma classic_circline:\n  assumes \"H = mk_circline A B C D\" and \"hermitean (A, B, C, D) \\<and> (A, B, C, D) \\<noteq> mat_zero\"\n  shows \"circline_set H - {\\<infinity>\\<^sub>h} = of_complex ` circline (Re A) B (Re D)\"\nusing assms\nunfolding circline_set_def\nproof (safe)\n  fix z\n  assume \"hermitean (A, B, C, D)\" \"(A, B, C, D) \\<noteq> mat_zero\" \"z \\<in> circline (Re A) B (Re D)\"\n    thus \"on_circline (mk_circline A B C D) (of_complex z)\"\n      using hermitean_elems[of A B C D]\n      by (transfer, transfer) (auto simp add: circline_def vec_cnj_def field_simps)\nnext\n  fix z\n  assume \"of_complex z = \\<infinity>\\<^sub>h\"\n  thus False\n    by simp\nnext\n  fix z\n  assume \"hermitean (A, B, C, D)\" \"(A, B, C, D) \\<noteq> mat_zero\" \"on_circline (mk_circline A B C D) z\" \"z \\<notin> of_complex ` circline (Re A) B (Re D)\"\n  moreover\n  have \"z \\<noteq> \\<infinity>\\<^sub>h \\<longrightarrow> z \\<in> of_complex ` circline (Re A) B (Re D)\"\n  proof\n    assume \"z \\<noteq> \\<infinity>\\<^sub>h\"\n    show \"z \\<in> of_complex ` circline (Re A) B (Re D)\"\n    proof\n      show \"z = of_complex (to_complex z)\"\n        using \\<open>z \\<noteq> \\<infinity>\\<^sub>h\\<close>\n        by simp\n    next\n      show \"to_complex z \\<in> circline (Re A) B (Re D)\"\n        using \\<open>on_circline (mk_circline A B C D) z\\<close> \\<open>z \\<noteq> \\<infinity>\\<^sub>h\\<close>\n        using \\<open>hermitean (A, B, C, D)\\<close> \\<open>(A, B, C, D) \\<noteq> mat_zero\\<close>\n      proof (transfer, transfer)\n        fix A B C D and z :: complex_vec\n        obtain z1 z2 where zz: \"z = (z1, z2)\"\n          by (cases z, auto)\n        assume *: \"z \\<noteq> vec_zero\"  \"\\<not> z \\<approx>\\<^sub>v \\<infinity>\\<^sub>v\"\n                  \"on_circline_cmat_cvec (mk_circline_cmat A B C D) z\"\n                  \"hermitean (A, B, C, D)\" \"(A, B, C, D) \\<noteq> mat_zero\"\n        have \"z2 \\<noteq> 0\"\n          using \\<open>z \\<noteq> vec_zero\\<close> \\<open>\\<not> z \\<approx>\\<^sub>v \\<infinity>\\<^sub>v\\<close>\n          using inf_cvec_z2_zero_iff zz\n          by blast\n        thus \"to_complex_cvec z \\<in> circline (Re A) B (Re D)\"\n          using * zz\n          using hermitean_elems[of A B C D]\n          by (simp add: vec_cnj_def circline_def field_simps)\n      qed\n    qed\n  qed\n  ultimately\n  show \"z = \\<infinity>\\<^sub>h\"\n    by simp\nqed\n\ntext \\<open>The matrix of the circline representing circle determined with center and radius.\\<close>\ndefinition mk_circle_cmat :: \"complex \\<Rightarrow> real \\<Rightarrow> complex_mat\" where\n  [simp]: \"mk_circle_cmat a r = (1, -a, -cnj a, a*cnj a - cor r*cor r)\"\n\nlift_definition mk_circle_clmat :: \"complex \\<Rightarrow> real \\<Rightarrow> circline_mat\" is mk_circle_cmat\n  by (simp add: hermitean_def mat_adj_def mat_cnj_def)\n\nlift_definition mk_circle :: \"complex \\<Rightarrow> real \\<Rightarrow> circline\" is mk_circle_clmat\n  done\n\nlemma is_circle_mk_circle: \"is_circle (mk_circle a r)\"\n  by (transfer, transfer, simp)\n\nlemma circline_set_mk_circle [simp]:\n  assumes \"r \\<ge> 0\"\n  shows \"circline_set (mk_circle a r) = of_complex ` circle a r\"\nproof-\n  let ?A = \"1\" and ?B = \"-a\" and ?C = \"-cnj a\" and ?D = \"a*cnj a - cor r*cor r\"\n  have *: \"(?A, ?B, ?C, ?D) \\<in> {H. hermitean H \\<and> H \\<noteq> mat_zero}\"\n    by (simp add: hermitean_def mat_adj_def mat_cnj_def)\n  have \"mk_circle a r = mk_circline ?A ?B ?C ?D\"\n    using *\n    by (transfer, transfer, simp)\n  hence \"circline_set (mk_circle a r) - {\\<infinity>\\<^sub>h} = of_complex ` circline ?A ?B (Re ?D)\"\n    using classic_circline[of \"mk_circle a r\" ?A ?B ?C ?D] *\n    by simp\n  moreover\n  have \"circline ?A ?B (Re ?D) = circle a r\"\n    by (rule circline_circle[of ?A \"Re ?D\" \"?B\" \"circline ?A ?B (Re ?D)\" \"a\" \"r*r\" r], simp_all add: cmod_square \\<open>r \\<ge> 0\\<close>)\n  moreover\n  have \"\\<infinity>\\<^sub>h \\<notin> circline_set (mk_circle a r)\"\n    using inf_in_circline_set[of \"mk_circle a r\"] is_circle_mk_circle[of a r]\n    by auto\n  ultimately\n  show ?thesis\n    unfolding circle_def\n    by simp\nqed\n\ntext \\<open>The matrix of the circline representing line determined with two (not equal) complex points.\\<close>\ndefinition mk_line_cmat :: \"complex \\<Rightarrow> complex \\<Rightarrow> complex_mat\" where\n  [simp]: \"mk_line_cmat z1 z2 =\n    (if z1 \\<noteq> z2 then\n          let B = \\<i> * (z2 - z1) in (0, B, cnj B, -cnj_mix B z1)\n    else\n          eye)\"\n\nlift_definition mk_line_clmat :: \"complex \\<Rightarrow> complex \\<Rightarrow> circline_mat\" is mk_line_cmat\n  by (auto simp add: Let_def hermitean_def mat_adj_def mat_cnj_def  split: if_split_asm)\n\nlift_definition mk_line :: \"complex \\<Rightarrow> complex \\<Rightarrow> circline\" is mk_line_clmat\n  done\n\nlemma circline_set_mk_line [simp]:\n  assumes \"z1 \\<noteq> z2\"\n  shows \"circline_set (mk_line z1 z2) - {\\<infinity>\\<^sub>h} = of_complex ` line z1 z2\"\nproof-\n  let ?A = \"0\" and ?B = \"\\<i>*(z2 - z1)\"\n  let ?C = \"cnj ?B\" and ?D = \"-cnj_mix ?B z1\"\n  have *: \"(?A, ?B, ?C, ?D) \\<in> {H. hermitean H \\<and> H \\<noteq> mat_zero}\"\n    using assms\n    by (simp add: hermitean_def mat_adj_def mat_cnj_def)\n  have \"mk_line z1 z2 = mk_circline ?A ?B ?C ?D\"\n    using * assms\n    by (transfer, transfer, auto simp add: Let_def)\n  hence \"circline_set (mk_line z1 z2) - {\\<infinity>\\<^sub>h} = of_complex ` circline ?A ?B (Re ?D)\"\n    using classic_circline[of \"mk_line z1 z2\" ?A ?B ?C ?D] *\n    by simp\n  moreover\n  have \"circline ?A ?B (Re ?D) = line z1 z2\"\n    using \\<open>z1 \\<noteq> z2\\<close>\n    using circline_line'\n    by simp\n  ultimately\n  show ?thesis\n    by simp\nqed\n\ntext \\<open>The set of points determined by a circline is always \neither an Euclidean circle or an Euclidean line. \\<close>\n\ntext \\<open>Euclidean circle is determined by its center and radius.\\<close>\ntype_synonym euclidean_circle = \"complex \\<times> real\"\n\ndefinition euclidean_circle_cmat :: \"complex_mat \\<Rightarrow> euclidean_circle\" where\n  [simp]: \"euclidean_circle_cmat H = (let (A, B, C, D) = H in (-B/A, sqrt(Re ((B*C - A*D)/(A*A)))))\"\n\nlift_definition euclidean_circle_clmat :: \"circline_mat \\<Rightarrow> euclidean_circle\" is euclidean_circle_cmat\n  done\n\nlift_definition euclidean_circle :: \"circline \\<Rightarrow> euclidean_circle\" is euclidean_circle_clmat\nproof transfer\n  fix H1 H2\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  assume \"circline_eq_cmat H1 H2\"\n  then obtain k where \"k \\<noteq> 0\" and *: \"A2 = cor k * A1\" \"B2 = cor k * B1\" \"C2 = cor k * C1\" \"D2 = cor k * D1\"\n    using HH1 HH2\n    by auto\n  have \"(cor k * B1 * (cor k * C1) - cor k * A1 * (cor k * D1)) = (cor k)\\<^sup>2 * (B1*C1 - A1*D1)\"\n    \"(cor k * A1 * (cor k * A1)) = (cor k)\\<^sup>2 * (A1*A1)\"\n    by (auto simp add: field_simps power2_eq_square)\n  hence \"(cor k * B1 * (cor k * C1) - cor k * A1 * (cor k * D1)) /\n         (cor k * A1 * (cor k * A1)) = (B1*C1 - A1*D1) / (A1*A1)\"\n    using \\<open>k \\<noteq> 0\\<close>\n    by (simp add: power2_eq_square)\n  thus \"euclidean_circle_cmat H1 = euclidean_circle_cmat H2\"\n    using HH1 HH2 * hh\n    by auto\nqed\n\nlemma classic_circle:\n  assumes \"is_circle H\" and \"(a, r) = euclidean_circle H\" and \"circline_type H \\<le> 0\"\n  shows \"circline_set H = of_complex ` circle a r\"\nproof-\n  obtain A B C D where *: \"H = mk_circline A B C D\" \"hermitean (A, B, C, D)\" \"(A, B, C, D) \\<noteq> mat_zero\"\n    using ex_mk_circline[of H]\n    by auto\n  have \"is_real A\" \"is_real D\" \"C = cnj B\"\n    using * hermitean_elems\n    by auto\n  have \"Re (A*D - B*C) \\<le> 0\"\n    using \\<open>circline_type H \\<le> 0\\<close> *\n    by simp\n\n  hence **: \"Re A * Re D \\<le> (cmod B)\\<^sup>2\"\n    using \\<open>is_real A\\<close> \\<open>is_real D\\<close> \\<open>C = cnj B\\<close>\n    by (simp add: cmod_square)\n\n  have \"A \\<noteq> 0\"\n    using \\<open>is_circle H\\<close> * \\<open>is_real A\\<close>\n    by simp (transfer, transfer, simp)\n\n  hence \"Re A \\<noteq> 0\"\n    using \\<open>is_real A\\<close>\n    by (metis complex_surj zero_complex.code)\n\n  have ***: \"\\<infinity>\\<^sub>h \\<notin> circline_set H\"\n    using * inf_in_circline_set[of H] \\<open>is_circle H\\<close>\n    by simp\n\n  let ?a = \"-B/A\"\n  let ?r2 = \"((cmod B)\\<^sup>2 - Re A * Re D) / (Re A)\\<^sup>2\"\n  let ?r = \"sqrt ?r2\"\n\n  have \"?a = a \\<and> ?r = r\"\n    using \\<open>(a, r) = euclidean_circle H\\<close>\n    using * \\<open>is_real A\\<close> \\<open>is_real D\\<close> \\<open>C = cnj B\\<close> \\<open>A \\<noteq> 0\\<close>\n    apply simp\n    apply transfer\n    apply transfer\n    apply simp\n    apply (subst Re_divide_real)\n    apply (simp_all add: cmod_square, simp add: power2_eq_square)\n    done\n\n  show ?thesis\n    using * ** *** \\<open>Re A \\<noteq> 0\\<close> \\<open>is_real A\\<close> \\<open>C = cnj B\\<close> \\<open>?a = a \\<and> ?r = r\\<close>\n    using classic_circline[of H A B C D] assms circline_circle[of \"Re A\" \"Re D\" B \"circline (Re A) B (Re D)\" ?a ?r2 ?r]\n    by (simp add: circle_def)\nqed\n\ntext \\<open>Euclidean line is represented by two points.\\<close>\ntype_synonym euclidean_line = \"complex \\<times> complex\"\n\ndefinition euclidean_line_cmat :: \"complex_mat \\<Rightarrow> euclidean_line\" where\n [simp]: \"euclidean_line_cmat H =\n         (let (A, B, C, D) = H;\n              z1 = -(D*B)/(2*B*C);\n              z2 = z1 + \\<i> * sgn (if arg B > 0 then -B else B)\n           in (z1, z2))\"\n\nlift_definition euclidean_line_clmat :: \"circline_mat \\<Rightarrow> euclidean_line\" is euclidean_line_cmat\n  done\n\nlift_definition euclidean_line :: \"circline \\<Rightarrow> complex \\<times> complex\" is euclidean_line_clmat\nproof transfer\n  fix H1 H2\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  assume \"circline_eq_cmat H1 H2\"\n  then obtain k where \"k \\<noteq> 0\" and *: \"A2 = cor k * A1\" \"B2 = cor k * B1\" \"C2 = cor k * C1\" \"D2 = cor k * D1\"\n    using HH1 HH2\n    by auto\n  have 1: \"B1 \\<noteq> 0 \\<and> 0 < arg B1 \\<longrightarrow> \\<not> 0 < arg (- B1)\"\n    using canon_ang_plus_pi1[of \"arg B1\"] arg_bounded[of B1]\n    by (auto simp add: arg_uminus)\n  have 2: \"B1 \\<noteq> 0 \\<and> \\<not> 0 < arg B1 \\<longrightarrow> 0 < arg (- B1)\"\n    using canon_ang_plus_pi2[of \"arg B1\"] arg_bounded[of B1]\n    by (auto simp add: arg_uminus)\n\n  show \"euclidean_line_cmat H1 = euclidean_line_cmat H2\"\n    using HH1 HH2 * \\<open>k \\<noteq> 0\\<close>\n    by (cases \"k > 0\") (auto simp add: Let_def, simp_all add: sgn_eq 1 2)\nqed\n\nlemma classic_line:\n  assumes \"is_line H\" and \"circline_type H < 0\" and \"(z1, z2) = euclidean_line H\"\n  shows \"circline_set H - {\\<infinity>\\<^sub>h} = of_complex ` line z1 z2\"\nproof-\n  obtain A B C D where *: \"H = mk_circline A B C D\" \"hermitean (A, B, C, D)\" \"(A, B, C, D) \\<noteq> mat_zero\"\n    using ex_mk_circline[of H]\n    by auto\n  have \"is_real A\" \"is_real D\" \"C = cnj B\"\n    using * hermitean_elems\n    by auto\n  have \"Re A = 0\"\n    using \\<open>is_line H\\<close> * \\<open>is_real A\\<close> \\<open>is_real D\\<close> \\<open>C = cnj B\\<close>\n    by simp (transfer, transfer, simp)\n  have \"B \\<noteq> 0\"\n    using \\<open>Re A = 0\\<close>  \\<open>is_real A\\<close> \\<open>is_real D\\<close> \\<open>C = cnj B\\<close> * \\<open>circline_type H < 0\\<close>\n    using circline_type_mk_circline[of A B C D]\n    by auto\n\n  let ?z1 = \"- cor (Re D) * B / (2 * B * cnj B)\"\n  let ?z2 = \"?z1 + \\<i> * sgn (if 0 < arg B then - B else B)\"\n  have \"z1 = ?z1 \\<and> z2 = ?z2\"\n    using \\<open>(z1, z2) = euclidean_line H\\<close> * \\<open>is_real A\\<close> \\<open>is_real D\\<close> \\<open>C = cnj B\\<close>\n    by simp (transfer, transfer, simp add: Let_def)\n  thus ?thesis\n    using *\n    using classic_circline[of H A B C D] circline_line[of \"Re A\" B \"circline (Re A) B (Re D)\" \"Re D\" ?z1 ?z2] \\<open>Re A = 0\\<close> \\<open>B \\<noteq> 0\\<close>\n    by simp\nqed\n\n\n(* ----------------------------------------------------------------- *)\nsubsection \\<open>Some special circlines\\<close>\n(* ----------------------------------------------------------------- *)\n\n(* ---------------------------------------------------------------------------- *)\nsubsubsection \\<open>Unit circle\\<close>\n(* ---------------------------------------------------------------------------- *)\n\ndefinition unit_circle_cmat :: complex_mat where\n  [simp]: \"unit_circle_cmat =  (1, 0, 0, -1)\"\nlift_definition unit_circle_clmat :: circline_mat is unit_circle_cmat\n  by (simp add: hermitean_def mat_adj_def mat_cnj_def)\nlift_definition unit_circle :: circline is unit_circle_clmat\n  done\n\nlemma on_circline_cmat_cvec_unit:\n  shows \"on_circline_cmat_cvec unit_circle_cmat (z1, z2) \\<longleftrightarrow> \n         z1 * cnj z1 = z2 * cnj z2\"\n  by (simp add: vec_cnj_def field_simps)\n\nlemma\n  one_on_unit_circle [simp]: \"on_circline unit_circle 1\\<^sub>h\"  and\n  ii_on_unit_circle [simp]: \"on_circline unit_circle ii\\<^sub>h\" and\n  not_zero_on_unit_circle [simp]: \"\\<not> on_circline unit_circle 0\\<^sub>h\"\n  by (transfer, transfer, simp add: vec_cnj_def)+\n\nlemma  \n  one_in_unit_circle_set [simp]: \"1\\<^sub>h \\<in> circline_set unit_circle\" and\n  ii_in_unit_circle_set [simp]: \"ii\\<^sub>h \\<in> circline_set unit_circle\" and\n  zero_in_unit_circle_set [simp]: \"0\\<^sub>h \\<notin> circline_set unit_circle\"\n  unfolding circline_set_def\n  by simp_all\n\nlemma is_circle_unit_circle [simp]:\n  shows \"is_circle unit_circle\"\n  by (transfer, transfer, simp)\n\nlemma not_inf_on_unit_circle' [simp]:\n  shows \"\\<not> on_circline unit_circle \\<infinity>\\<^sub>h\"\n  using is_circle_unit_circle inf_on_circline\n  by blast\n\nlemma not_inf_on_unit_circle'' [simp]:\n  shows \"\\<infinity>\\<^sub>h \\<notin> circline_set unit_circle\"\n  by (simp add: inf_in_circline_set)\n\nlemma euclidean_circle_unit_circle [simp]:\n  shows \"euclidean_circle unit_circle = (0, 1)\"\n  by (transfer, transfer, simp)\n\nlemma circline_type_unit_circle [simp]:\n  shows \"circline_type unit_circle = -1\"\n  by (transfer, transfer, simp)\n\nlemma on_circline_unit_circle [simp]:\n  shows \"on_circline unit_circle (of_complex z) \\<longleftrightarrow> cmod z = 1\"\n  by (transfer, transfer, simp add: vec_cnj_def mult.commute)\n\nlemma circline_set_unit_circle [simp]:\n  shows \"circline_set unit_circle = of_complex ` {z. cmod z = 1}\"\nproof-\n  show ?thesis\n  proof safe\n    fix x\n    assume \"x \\<in> circline_set unit_circle\"\n    then obtain x' where \"x = of_complex x'\"\n      using inf_or_of_complex[of x]\n      by auto\n    thus \"x \\<in> of_complex ` {z. cmod z = 1}\"\n      using \\<open>x \\<in> circline_set unit_circle\\<close>\n      unfolding circline_set_def              \n      by auto\n  next\n    fix x\n    assume \"cmod x = 1\"\n    thus \"of_complex x \\<in> circline_set unit_circle\"\n      unfolding circline_set_def\n      by auto\n  qed\nqed\n\nlemma circline_set_unit_circle_I [simp]:\n  assumes \"cmod z = 1\"\n  shows \"of_complex z \\<in> circline_set unit_circle\"\n  using assms\n  unfolding circline_set_unit_circle\n  by simp\n\nlemma inversion_unit_circle [simp]:\n  assumes \"on_circline unit_circle x\"\n  shows \"inversion x = x\"\nproof-\n  obtain x' where \"x = of_complex x'\" \"x' \\<noteq> 0\"\n    using inf_or_of_complex[of x]\n    using assms\n    by force\n  moreover\n  hence \"x' * cnj x' = 1\"\n    using assms\n    using circline_set_unit_circle\n    unfolding circline_set_def\n    by auto\n  hence \"1 / cnj x' = x'\"\n    using \\<open>x' \\<noteq> 0\\<close>\n    by (simp add: field_simps)\n  ultimately\n  show ?thesis\n    using assms\n    unfolding inversion_def\n    by simp\nqed\n\nlemma inversion_id_iff_on_unit_circle: \n  shows \"inversion a = a \\<longleftrightarrow> on_circline unit_circle a\"\n  using inversion_id_iff[of a] inf_or_of_complex[of a]\n  by auto\n\nlemma on_unit_circle_conjugate [simp]:\n  shows \"on_circline unit_circle (conjugate z) \\<longleftrightarrow> on_circline unit_circle z\"\n  by (transfer, transfer, auto simp add: vec_cnj_def field_simps)\n\nlemma conjugate_unit_circle_set [simp]:\n  shows \"conjugate ` (circline_set unit_circle) = circline_set unit_circle\"\n  unfolding circline_set_def\n  by (auto simp add: image_iff, rule_tac x=\"conjugate x\" in exI, simp)\n\n(* ---------------------------------------------------------------------------- *)\nsubsubsection \\<open>x-axis\\<close>\n(* ---------------------------------------------------------------------------- *)\n\ndefinition x_axis_cmat :: complex_mat where\n  [simp]: \"x_axis_cmat =  (0, \\<i>, -\\<i>, 0)\"\nlift_definition x_axis_clmat :: circline_mat is x_axis_cmat\n  by (simp add: hermitean_def mat_adj_def mat_cnj_def)\nlift_definition x_axis :: circline is x_axis_clmat\n  done\n\nlemma special_points_on_x_axis' [simp]:\n  shows \"on_circline x_axis 0\\<^sub>h\" and \"on_circline x_axis 1\\<^sub>h\" and \"on_circline x_axis \\<infinity>\\<^sub>h\"\n  by (transfer, transfer, simp add: vec_cnj_def)+\n\nlemma special_points_on_x_axis'' [simp]:\n  shows \"0\\<^sub>h \\<in> circline_set x_axis\" and \"1\\<^sub>h \\<in> circline_set x_axis\" and \"\\<infinity>\\<^sub>h \\<in> circline_set x_axis\"\n  unfolding circline_set_def\n  by auto\n\nlemma is_line_x_axis [simp]:\n  shows \"is_line x_axis\"\n  by (transfer, transfer, simp)\n\nlemma circline_type_x_axis [simp]:\n  shows \"circline_type x_axis = -1\"\n  by (transfer, transfer, simp)\n\nlemma on_circline_x_axis:\n  shows \"on_circline x_axis z \\<longleftrightarrow> (\\<exists> c. is_real c \\<and> z = of_complex c) \\<or> z = \\<infinity>\\<^sub>h\"\nproof safe\n  fix z c\n  assume \"is_real c\"\n  thus \"on_circline x_axis (of_complex c)\"\n  proof (transfer, transfer)\n    fix c\n    assume \"is_real c\"\n    thus \"on_circline_cmat_cvec x_axis_cmat (of_complex_cvec c)\"\n      using eq_cnj_iff_real[of c]\n      by (simp add: vec_cnj_def)\n  qed\nnext\n  fix z\n  assume \"on_circline x_axis z\" \"z \\<noteq> \\<infinity>\\<^sub>h\"\n  thus \"\\<exists>c. is_real c \\<and> z = of_complex c\"\n  proof (transfer, transfer, safe)\n    fix a b\n    assume \"(a, b) \\<noteq> vec_zero\"\n      \"on_circline_cmat_cvec x_axis_cmat (a, b)\"\n      \"\\<not> (a, b) \\<approx>\\<^sub>v \\<infinity>\\<^sub>v\"\n    hence \"b \\<noteq> 0\" \"cnj a * b = cnj b * a\" using inf_cvec_z2_zero_iff\n      by (auto simp add: vec_cnj_def)\n    thus \"\\<exists>c. is_real c \\<and> (a, b) \\<approx>\\<^sub>v of_complex_cvec c\"\n      apply (rule_tac x=\"a/b\" in exI)\n      apply (auto simp add: is_real_div field_simps)\n      apply (rule_tac x=\"1/b\" in exI, simp)\n      done\n  qed\nnext\n  show \"on_circline x_axis \\<infinity>\\<^sub>h\"\n    by auto\nqed\n\nlemma on_circline_x_axis_I [simp]:\n  assumes \"is_real z\"\n  shows \"on_circline x_axis (of_complex z)\"\n  using assms\n  unfolding on_circline_x_axis\n  by auto\n\nlemma circline_set_x_axis:\n  shows \"circline_set x_axis = of_complex ` {x. is_real x} \\<union> {\\<infinity>\\<^sub>h}\"\n  using on_circline_x_axis\n  unfolding circline_set_def\n  by auto\n\nlemma circline_set_x_axis_I:\n  assumes \"is_real z\"\n  shows \"of_complex z \\<in> circline_set x_axis\"\n  using assms\n  unfolding circline_set_x_axis\n  by auto\n\nlemma circline_equation_x_axis:\n  shows \"of_complex z \\<in> circline_set x_axis \\<longleftrightarrow> z = cnj z\"\n  unfolding circline_set_x_axis\nproof auto\n  fix x\n  assume \"of_complex z = of_complex x\" \"is_real x\"\n  hence \"z = x\"\n    using of_complex_inj[of z x]\n    by simp\n  thus \"z = cnj z\"\n    using eq_cnj_iff_real[of z] \\<open>is_real x\\<close>\n    by auto\nnext\n  assume \"z = cnj z\"\n  thus \"of_complex z \\<in> of_complex ` {x. is_real x} \"\n    using eq_cnj_iff_real[of z]\n    by auto\nqed\n\ntext \\<open>Positive and negative part of x-axis\\<close>\n\ndefinition positive_x_axis where\n  \"positive_x_axis = {z. z \\<in> circline_set x_axis \\<and> z \\<noteq> \\<infinity>\\<^sub>h \\<and> Re (to_complex z) > 0}\"\n\ndefinition negative_x_axis where\n  \"negative_x_axis = {z. z \\<in> circline_set x_axis \\<and> z \\<noteq> \\<infinity>\\<^sub>h \\<and> Re (to_complex z) < 0}\"\n\nlemma circline_set_positive_x_axis_I [simp]:\n  assumes \"is_real z\" and \"Re z > 0\"\n  shows \"of_complex z \\<in> positive_x_axis\"\n  using assms\n  unfolding positive_x_axis_def\n  by simp\n\nlemma circline_set_negative_x_axis_I [simp]:\n  assumes \"is_real z\" and \"Re z < 0\"\n  shows \"of_complex z \\<in> negative_x_axis\"\n  using assms\n  unfolding negative_x_axis_def\n  by simp\n\n(* ---------------------------------------------------------------------------- *)\nsubsubsection \\<open>y-axis\\<close>\n(* ---------------------------------------------------------------------------- *)\n\ndefinition y_axis_cmat :: complex_mat where\n  [simp]: \"y_axis_cmat = (0, 1, 1, 0)\"\nlift_definition y_axis_clmat :: circline_mat is y_axis_cmat\n  by (simp add: hermitean_def mat_adj_def mat_cnj_def)\nlift_definition y_axis :: circline is y_axis_clmat\n  done\n\nlemma special_points_on_y_axis' [simp]:\n  shows \"on_circline y_axis 0\\<^sub>h\" and \"on_circline y_axis ii\\<^sub>h\" and \"on_circline y_axis \\<infinity>\\<^sub>h\"\n  by (transfer, transfer, simp add: vec_cnj_def)+\n\nlemma special_points_on_y_axis'' [simp]:\n  shows \"0\\<^sub>h \\<in> circline_set y_axis\" and \"ii\\<^sub>h \\<in> circline_set y_axis\" and \"\\<infinity>\\<^sub>h \\<in> circline_set y_axis\"\n  unfolding circline_set_def\n  by auto\n\nlemma on_circline_y_axis: \n  shows \"on_circline y_axis z \\<longleftrightarrow> (\\<exists> c. is_imag c \\<and> z = of_complex c) \\<or> z = \\<infinity>\\<^sub>h\"\nproof safe\n  fix z c\n  assume \"is_imag c\"\n  thus \"on_circline y_axis (of_complex c)\"                                 \n  proof (transfer, transfer)\n    fix c                                                       \n    assume \"is_imag c\"\n    thus \"on_circline_cmat_cvec y_axis_cmat (of_complex_cvec c)\"\n      using eq_minus_cnj_iff_imag[of c]\n      by (simp add: vec_cnj_def)\n  qed\nnext\n  fix z\n  assume \"on_circline y_axis z\" \"z \\<noteq> \\<infinity>\\<^sub>h\"\n  thus \"\\<exists>c. is_imag c \\<and> z = of_complex c\"\n  proof (transfer, transfer, safe)\n    fix a b\n    assume \"(a, b) \\<noteq> vec_zero\"\n      \"on_circline_cmat_cvec y_axis_cmat (a, b)\"\n      \"\\<not> (a, b) \\<approx>\\<^sub>v \\<infinity>\\<^sub>v\"\n    hence \"b \\<noteq> 0\" \"cnj a * b + cnj b * a = 0\"\n      using inf_cvec_z2_zero_iff\n      by (blast, smt add.left_neutral add_cancel_right_right mult.commute mult.left_neutral mult_not_zero on_circline_cmat_cvec_circline_equation y_axis_cmat_def)\n    thus \"\\<exists>c. is_imag c \\<and> (a, b) \\<approx>\\<^sub>v of_complex_cvec c\"\n      using eq_minus_cnj_iff_imag[of \"a / b\"]\n      apply (rule_tac x=\"a/b\" in exI)\n      apply (auto simp add: field_simps)\n      apply (rule_tac x=\"1/b\" in exI, simp)\n      using add_eq_0_iff apply blast\n      apply (rule_tac x=\"1/b\" in exI, simp)\n      done\n  qed\nnext\n  show \"on_circline y_axis \\<infinity>\\<^sub>h\"\n    by simp\nqed\n\nlemma on_circline_y_axis_I [simp]:\n  assumes \"is_imag z\"\n  shows \"on_circline y_axis (of_complex z)\"\n  using assms\n  unfolding on_circline_y_axis\n  by auto\n\nlemma circline_set_y_axis:\n  shows \"circline_set y_axis = of_complex ` {x. is_imag x} \\<union> {\\<infinity>\\<^sub>h}\"\n  using on_circline_y_axis\n  unfolding circline_set_def\n  by auto\n\nlemma circline_set_y_axis_I:\n  assumes \"is_imag z\"\n  shows \"of_complex z \\<in> circline_set y_axis\"\n  using assms\n  unfolding circline_set_y_axis\n  by auto\n\ntext \\<open>Positive and negative part of y-axis\\<close>\n\ndefinition positive_y_axis where\n  \"positive_y_axis = {z. z \\<in> circline_set y_axis \\<and> z \\<noteq> \\<infinity>\\<^sub>h \\<and> Im (to_complex z) > 0}\"\n\ndefinition negative_y_axis where\n  \"negative_y_axis = {z. z \\<in> circline_set y_axis \\<and> z \\<noteq> \\<infinity>\\<^sub>h \\<and> Im (to_complex z) < 0}\"\n\nlemma circline_set_positive_y_axis_I [simp]:\n  assumes \"is_imag z\" and \"Im z > 0\"\n  shows \"of_complex z \\<in> positive_y_axis\"\n  using assms\n  unfolding positive_y_axis_def\n  by simp\n\nlemma circline_set_negative_y_axis_I [simp]:\n  assumes \"is_imag z\" and \"Im z < 0\"\n  shows \"of_complex z \\<in> negative_y_axis\"\n  using assms\n  unfolding negative_y_axis_def\n  by simp\n\n(* ---------------------------------------------------------------------------- *)\nsubsubsection \\<open>Point zero as a circline\\<close>\n(* ---------------------------------------------------------------------------- *)\n\ndefinition circline_point_0_cmat :: complex_mat where\n  [simp]: \"circline_point_0_cmat =  (1, 0, 0, 0)\"\nlift_definition circline_point_0_clmat :: circline_mat is circline_point_0_cmat\n  by (simp add: hermitean_def mat_adj_def mat_cnj_def)\nlift_definition circline_point_0 :: circline is circline_point_0_clmat\n  done\n\nlemma circline_type_circline_point_0 [simp]:\n  shows \"circline_type circline_point_0 = 0\"\n  by (transfer, transfer, simp)\n\nlemma zero_in_circline_point_0 [simp]:\n  shows \"0\\<^sub>h \\<in> circline_set circline_point_0\"\n  unfolding circline_set_def\n  by auto (transfer, transfer, simp add: vec_cnj_def)+\n\n(* ---------------------------------------------------------------------------- *)\nsubsubsection \\<open>Imaginary unit circle\\<close>\n(* ---------------------------------------------------------------------------- *)\n\ndefinition imag_unit_circle_cmat :: complex_mat where\n  [simp]: \"imag_unit_circle_cmat =  (1, 0, 0, 1)\"\nlift_definition imag_unit_circle_clmat :: circline_mat is imag_unit_circle_cmat\n  by (simp add: hermitean_def mat_adj_def mat_cnj_def)\nlift_definition imag_unit_circle :: circline is imag_unit_circle_clmat\n  done\n\nlemma circline_type_imag_unit_circle [simp]:\n  shows \"circline_type imag_unit_circle = 1\"\n  by (transfer, transfer, simp)\n\n(* ----------------------------------------------------------------- *)\nsubsection \\<open>Intersection of circlines\\<close>\n(* ----------------------------------------------------------------- *)\n\ndefinition circline_intersection :: \"circline \\<Rightarrow> circline \\<Rightarrow> complex_homo set\" where\n  \"circline_intersection H1 H2 = {z. on_circline H1 z \\<and> on_circline H2 z}\"\n\nlemma circline_equation_cancel_z2:\n  assumes \"circline_equation A B C D z1 z2 \" and \"z2 \\<noteq> 0\"\n  shows \"circline_equation A B C D (z1/z2) 1\"\n  using assms\n  by (simp add: field_simps)\n\nlemma circline_equation_quadratic_equation:\n  assumes \"circline_equation A B (cnj B) D z 1\" and \n          \"Re z = x\" and \"Im z = y\" and \"Re B = bx\" and \"Im B = by\"\n  shows \"A*x\\<^sup>2 + A*y\\<^sup>2 + 2*bx*x + 2*by*y + D = 0\"\n  using assms\nproof-\n  have \"z = x + \\<i>*y\" \"B = bx + \\<i>*by\"\n    using assms complex_eq\n    by auto\n  thus ?thesis\n    using assms\n    by (simp add: field_simps power2_eq_square)\nqed\n\nlemma circline_intersection_symetry:\n  shows \"circline_intersection H1 H2 = circline_intersection H2 H1\"\n  unfolding circline_intersection_def\n  by auto\n\n(* ----------------------------------------------------------------- *)\nsubsection \\<open>M\u00f6bius action on circlines\\<close>\n(* ----------------------------------------------------------------- *)\n\ndefinition moebius_circline_cmat_cmat :: \"complex_mat \\<Rightarrow> complex_mat \\<Rightarrow> complex_mat\" where\n  [simp]: \"moebius_circline_cmat_cmat M H = congruence (mat_inv M) H\"\n\nlift_definition moebius_circline_mmat_clmat :: \"moebius_mat \\<Rightarrow> circline_mat \\<Rightarrow> circline_mat\" is moebius_circline_cmat_cmat\n  using mat_det_inv congruence_nonzero hermitean_congruence\n  by simp\n\nlift_definition moebius_circline :: \"moebius \\<Rightarrow> circline \\<Rightarrow> circline\" is moebius_circline_mmat_clmat\nproof transfer\n  fix M M' H H'\n  assume \"moebius_cmat_eq M M'\" \"circline_eq_cmat H H'\"\n  thus \"circline_eq_cmat (moebius_circline_cmat_cmat M H) (moebius_circline_cmat_cmat M' H')\"\n    by (auto simp add: mat_inv_mult_sm) (rule_tac x=\"ka / Re (k * cnj k)\" in exI, auto simp add: complex_mult_cnj_cmod power2_eq_square)\nqed\n\nlemma moebius_preserve_circline_type [simp]:                                \n  shows \"circline_type (moebius_circline M H) = circline_type H\"\nproof (transfer, transfer)\n  fix M H :: complex_mat\n  assume \"mat_det M \\<noteq> 0\" \"hermitean H \\<and> H \\<noteq> mat_zero\"\n  thus \"circline_type_cmat (moebius_circline_cmat_cmat M H) = circline_type_cmat H\"\n    using Re_det_sgn_congruence[of \"mat_inv M\" \"H\"] mat_det_inv[of \"M\"]\n    by (simp del: congruence_def)\nqed\n\ntext \\<open>The central lemma in this section connects the action of M\u00f6bius transformations on points and\non circlines.\\<close>\n\nlemma moebius_circline:\n  shows \"{z. on_circline (moebius_circline M H) z} =\n         moebius_pt M ` {z. on_circline H z}\"\nproof safe\n  fix z\n  assume \"on_circline H z\"\n  thus \"on_circline (moebius_circline M H) (moebius_pt M z)\"\n  proof (transfer, transfer)\n    fix z :: complex_vec and M H :: complex_mat\n    assume hh: \"hermitean H \\<and> H \\<noteq> mat_zero\" \"z \\<noteq> vec_zero\" \"mat_det M \\<noteq> 0\"\n    let ?z = \"M *\\<^sub>m\\<^sub>v z\"\n    let ?H = \"mat_adj (mat_inv M) *\\<^sub>m\\<^sub>m H *\\<^sub>m\\<^sub>m (mat_inv M)\"\n    assume *: \"on_circline_cmat_cvec H z\"\n    hence \"quad_form z H = 0\"\n      by simp\n    hence \"quad_form ?z ?H = 0\"\n      using quad_form_congruence[of M z H] hh\n      by simp\n    thus \"on_circline_cmat_cvec (moebius_circline_cmat_cmat M H) (moebius_pt_cmat_cvec M z)\"\n      by simp\n  qed\nnext\n  fix z\n  assume \"on_circline (moebius_circline M H) z\"\n  hence \"\\<exists> z'. z = moebius_pt M z' \\<and> on_circline H z'\"\n  proof (transfer, transfer)\n    fix z :: complex_vec and M H :: complex_mat\n    assume hh: \"hermitean H \\<and> H \\<noteq> mat_zero\" \"z \\<noteq> vec_zero\" \"mat_det M \\<noteq> 0\"\n    let ?iM = \"mat_inv M\"\n    let ?z' = \"?iM *\\<^sub>m\\<^sub>v z\"\n    assume *: \"on_circline_cmat_cvec (moebius_circline_cmat_cmat M H) z\"\n    have \"?z' \\<noteq> vec_zero\"\n      using hh\n      using mat_det_inv mult_mv_nonzero\n      by auto\n    moreover\n    have \"z \\<approx>\\<^sub>v moebius_pt_cmat_cvec M ?z'\"\n      using hh eye_mv_l mat_inv_r\n      by simp\n    moreover\n    have \"M *\\<^sub>m\\<^sub>v (?iM *\\<^sub>m\\<^sub>v z) = z\"\n      using hh eye_mv_l mat_inv_r\n      by auto\n    hence \"on_circline_cmat_cvec H ?z'\"\n      using hh *\n      using quad_form_congruence[of M \"?iM *\\<^sub>m\\<^sub>v z\" H, symmetric]\n      unfolding moebius_circline_cmat_cmat_def\n      unfolding on_circline_cmat_cvec_def\n      by simp\n    ultimately\n    show \"\\<exists>z'\\<in>{v. v \\<noteq> vec_zero}. z \\<approx>\\<^sub>v moebius_pt_cmat_cvec M z' \\<and> on_circline_cmat_cvec H z'\"\n      by blast\n  qed\n  thus \"z \\<in> moebius_pt M ` {z. on_circline H z}\"\n    by auto\nqed\n\nlemma on_circline_moebius_circline_I [simp]:\n  assumes \"on_circline H z\"\n  shows \"on_circline (moebius_circline M H) (moebius_pt M z)\"\n  using assms moebius_circline\n  by fastforce\n\nlemma circline_set_moebius_circline [simp]:\n  shows \"circline_set (moebius_circline M H) = moebius_pt M ` circline_set H\"\n  using moebius_circline[of M H]\n  unfolding circline_set_def\n  by auto\n\nlemma circline_set_moebius_circline_I [simp]:\n  assumes \"z \\<in> circline_set H\"\n  shows \"moebius_pt M z \\<in> circline_set (moebius_circline M H)\"\n  using assms\n  by simp\n\nlemma circline_set_moebius_circline_E:\n  assumes \"moebius_pt M z \\<in> circline_set (moebius_circline M H)\"\n  shows \"z \\<in> circline_set H\"\n  using assms\n  using moebius_pt_eq_I[of M z]\n  by auto\n\nlemma circline_set_moebius_circline_iff [simp]:\n  shows \"moebius_pt M z \\<in> circline_set (moebius_circline M H) \\<longleftrightarrow> \n         z \\<in> circline_set H\"\n  using moebius_pt_eq_I[of M z]\n  by auto\n\nlemma inj_moebius_circline:\n  shows \"inj (moebius_circline M)\"\nunfolding inj_on_def\nproof (safe)\n  fix H H'\n  assume \"moebius_circline M H = moebius_circline M H'\"\n  thus \"H = H'\"\n  proof (transfer, transfer)\n    fix M H H' :: complex_mat\n    assume hh: \"mat_det M \\<noteq> 0\"\n    let ?iM = \"mat_inv M\"\n    assume \"circline_eq_cmat (moebius_circline_cmat_cmat M H) (moebius_circline_cmat_cmat M H')\"\n    then obtain k where \"congruence ?iM H' = congruence ?iM (cor k *\\<^sub>s\\<^sub>m H)\" \"k \\<noteq> 0\"\n      by auto\n    thus \"circline_eq_cmat H H'\"\n      using hh inj_congruence[of ?iM H' \"cor k *\\<^sub>s\\<^sub>m H\"] mat_det_inv[of M]\n      by auto\n  qed\nqed\n\nlemma moebius_circline_eq_I:\n  assumes \"moebius_circline M H1 = moebius_circline M H2\"\n  shows \"H1 = H2\"\n  using assms inj_moebius_circline[of M]\n  unfolding inj_on_def\n  by blast\n\nlemma moebius_circline_neq_I [simp]:\n  assumes \"H1 \\<noteq> H2\"\n  shows \"moebius_circline M H1 \\<noteq> moebius_circline M H2\"\n  using assms inj_moebius_circline[of M]\n  unfolding inj_on_def\n  by blast\n\n(* ---------------------------------------------------------------------------- *)\nsubsubsection \\<open>Group properties of M\u00f6bius action on ciclines\\<close>\n(* ---------------------------------------------------------------------------- *)\n\ntext \\<open>M\u00f6bius actions on circlines have similar properties as M\u00f6bius actions on points.\\<close>\n\nlemma moebius_circline_id [simp]:\n  shows \"moebius_circline id_moebius H = H\"\n  by (transfer, transfer) (simp add: mat_adj_def mat_cnj_def, rule_tac x=1 in exI, auto)\n\nlemma moebius_circline_comp [simp]:\n  shows \"moebius_circline (moebius_comp M1 M2) H = moebius_circline M1 (moebius_circline M2 H)\"\n  by (transfer, transfer) (simp add: mat_inv_mult_mm, rule_tac x=1 in exI, simp add: mult_mm_assoc)\n\nlemma moebius_circline_comp_inv_left [simp]:\n  shows \"moebius_circline (moebius_inv M) (moebius_circline M H) = H\"\n  by (subst moebius_circline_comp[symmetric], simp)\n\nlemma moebius_circline_comp_inv_right [simp]:\n  shows \"moebius_circline M (moebius_circline (moebius_inv M) H) = H\"\n  by (subst moebius_circline_comp[symmetric], simp)\n\n(* ----------------------------------------------------------------- *)\nsubsection \\<open>Action of Euclidean similarities on circlines\\<close>\n(* ----------------------------------------------------------------- *)\n\nlemma moebius_similarity_lines_to_lines [simp]:\n  assumes \"a \\<noteq> 0\"\n  shows \"\\<infinity>\\<^sub>h \\<in> circline_set (moebius_circline (moebius_similarity a b) H) \\<longleftrightarrow> \n         \\<infinity>\\<^sub>h \\<in> circline_set H\"\n  using assms       \n  by (metis circline_set_moebius_circline_iff moebius_similarity_inf)\n\nlemma moebius_similarity_lines_to_lines':\n  assumes \"a \\<noteq> 0\"\n  shows \"on_circline (moebius_circline (moebius_similarity a b) H) \\<infinity>\\<^sub>h \\<longleftrightarrow>\n         \\<infinity>\\<^sub>h \\<in> circline_set H\"\n  using moebius_similarity_lines_to_lines assms\n  unfolding circline_set_def\n  by simp\n\n(* ----------------------------------------------------------------- *)\nsubsection \\<open>Conjugation, recpiprocation and inversion of circlines\\<close>\n(* ----------------------------------------------------------------- *)\n\ntext \\<open>Conjugation of circlines\\<close>\ndefinition conjugate_circline_cmat :: \"complex_mat \\<Rightarrow> complex_mat\" where\n [simp]: \"conjugate_circline_cmat = mat_cnj\"\nlift_definition conjugate_circline_clmat :: \"circline_mat \\<Rightarrow> circline_mat\" is conjugate_circline_cmat\n  by (auto simp add: hermitean_def mat_adj_def mat_cnj_def)\nlift_definition conjugate_circline :: \"circline \\<Rightarrow> circline\" is conjugate_circline_clmat\n  by transfer (metis circline_eq_cmat_def conjugate_circline_cmat_def hermitean_transpose mat_t_mult_sm)\n\nlemma conjugate_circline_set':\n  shows \"conjugate ` circline_set H \\<subseteq> circline_set (conjugate_circline H)\"\nproof (safe)\n  fix z\n  assume \"z \\<in> circline_set H\"\n  thus \"conjugate z \\<in> circline_set (conjugate_circline H)\"\n    unfolding circline_set_def\n    apply simp\n    apply (transfer, transfer)\n    unfolding on_circline_cmat_cvec_def conjugate_cvec_def conjugate_circline_cmat_def\n    apply (subst quad_form_vec_cnj_mat_cnj, simp_all)\n    done\nqed\n\nlemma conjugate_conjugate_circline [simp]:\n  shows \"conjugate_circline (conjugate_circline H) = H\"\n  by (transfer, transfer, force)\n\nlemma circline_set_conjugate_circline [simp]:\n  shows \"circline_set (conjugate_circline H) = conjugate ` circline_set H\" (is \"?lhs = ?rhs\")\nproof (safe)\n  fix z\n  assume \"z \\<in> ?lhs\"\n  show \"z \\<in> ?rhs\"\n  proof\n    show \"z = conjugate (conjugate z)\"\n      by simp\n  next\n    show \"conjugate z \\<in> circline_set H\"\n      using \\<open>z \\<in> circline_set (conjugate_circline H)\\<close>\n      using conjugate_circline_set'[of \"conjugate_circline H\"]\n      by auto\n  qed\nnext\n  fix z\n  assume \"z \\<in> circline_set H\"\n  thus \"conjugate z \\<in> circline_set (conjugate_circline H)\"\n    using conjugate_circline_set'[of H]\n    by auto\nqed\n\nlemma on_circline_conjugate_circline [simp]: \n  shows \"on_circline (conjugate_circline H) z \\<longleftrightarrow> on_circline H (conjugate z)\"\n  using circline_set_conjugate_circline[of H]\n  unfolding circline_set_def\n  by force\n\ntext \\<open>Inversion of circlines\\<close>\n\ndefinition circline_inversion_cmat :: \"complex_mat \\<Rightarrow> complex_mat\" where\n  [simp]:  \"circline_inversion_cmat H = (let (A, B, C, D) = H in (D, B, C, A))\"\nlift_definition circline_inversion_clmat :: \"circline_mat \\<Rightarrow> circline_mat\" is circline_inversion_cmat\n  by (auto simp add: hermitean_def mat_adj_def mat_cnj_def)\nlift_definition circline_inversion :: \"circline \\<Rightarrow> circline\" is circline_inversion_clmat\n  by transfer auto\n\nlemma on_circline_circline_inversion [simp]:\n  shows \"on_circline (circline_inversion H) z \\<longleftrightarrow> on_circline H (reciprocal (conjugate z))\"\n  by (transfer, transfer, auto simp add: vec_cnj_def field_simps)\n\nlemma circline_set_circline_inversion [simp]:\n  shows \"circline_set (circline_inversion H) = inversion ` circline_set H\"\n  unfolding circline_set_def inversion_def\n  by (force simp add: comp_def image_iff)\n\ntext \\<open>Reciprocal of circlines\\<close>\n\ndefinition circline_reciprocal :: \"circline \\<Rightarrow> circline\" where\n  \"circline_reciprocal = conjugate_circline \\<circ> circline_inversion\"\n\nlemma circline_set_circline_reciprocal:\n  shows \"circline_set (circline_reciprocal H) = reciprocal ` circline_set H\"\n  unfolding circline_reciprocal_def comp_def\n  by (auto simp add: inversion_def image_iff)\n\ntext \\<open>Rotation of circlines\\<close>\n\nlemma rotation_pi_2_y_axis [simp]:\n  shows \"moebius_circline (moebius_rotation (pi/2)) y_axis = x_axis\"\n  unfolding moebius_rotation_def moebius_similarity_def\n  by (transfer, transfer, simp add: mat_adj_def mat_cnj_def)\n\nlemma rotation_minus_pi_2_y_axis [simp]:\n  shows \"moebius_circline (moebius_rotation (-pi/2)) y_axis = x_axis\"\n  unfolding moebius_rotation_def moebius_similarity_def\n  by (transfer, transfer, simp add: mat_adj_def mat_cnj_def, rule_tac x=\"-1\" in exI, simp)\n\nlemma rotation_minus_pi_2_x_axis [simp]:\n  shows \"moebius_circline (moebius_rotation (-pi/2)) x_axis = y_axis\"\n  unfolding moebius_rotation_def moebius_similarity_def\n  by (transfer, transfer, simp add: mat_adj_def mat_cnj_def)\n\nlemma rotation_pi_2_x_axis [simp]:\n  shows \"moebius_circline (moebius_rotation (pi/2)) x_axis = y_axis\"\n  unfolding moebius_rotation_def moebius_similarity_def\n  by (transfer, transfer, simp add: mat_adj_def mat_cnj_def, rule_tac x=\"-1\" in exI, simp)\n\nlemma rotation_minus_pi_2_positive_y_axis [simp]:\n  shows \"(moebius_pt (moebius_rotation (-pi/2))) ` positive_y_axis = positive_x_axis\"\nproof safe\n  fix y\n  assume y: \"y \\<in> positive_y_axis\"\n  have *: \"Re (a * \\<i> / b) < 0 \\<longleftrightarrow> Im (a / b) > 0\" for a b\n    by (subst times_divide_eq_left [symmetric], subst mult.commute, subst Re_i_times) auto\n  from y * show \"moebius_pt (moebius_rotation (-pi/2)) y \\<in> positive_x_axis\"\n    unfolding positive_y_axis_def positive_x_axis_def circline_set_def\n    unfolding moebius_rotation_def moebius_similarity_def\n    apply simp\n    apply transfer\n    apply transfer\n    apply (auto simp add: vec_cnj_def field_simps add_eq_0_iff)\n    done\nnext\n  fix x\n  assume x: \"x \\<in> positive_x_axis\"\n  let ?y = \"moebius_pt (moebius_rotation (pi/2)) x\"\n  have *: \"Im (a * \\<i> / b) > 0 \\<longleftrightarrow> Re (a / b) > 0\" for a b\n    by (subst times_divide_eq_left [symmetric], subst mult.commute, subst Im_i_times) auto\n  hence \"?y \\<in> positive_y_axis\"\n    using \\<open>x \\<in> positive_x_axis\\<close>\n    unfolding positive_x_axis_def positive_y_axis_def\n    unfolding moebius_rotation_def moebius_similarity_def\n    unfolding circline_set_def\n    apply simp\n    apply transfer\n    apply transfer\n    apply (auto simp add: vec_cnj_def field_simps add_eq_0_iff)\n    done\n  thus \"x \\<in> moebius_pt (moebius_rotation (-pi/2)) ` positive_y_axis\"\n    by (auto simp add: image_iff) (rule_tac x=\"?y\" in bexI, simp_all)\nqed\n\n(* ----------------------------------------------------------------- *)\nsubsection \\<open>Circline uniqueness\\<close>\n(* ----------------------------------------------------------------- *)\n\n(* ----------------------------------------------------------------- *)\nsubsubsection \\<open>Zero type circline uniqueness\\<close>\n(* ----------------------------------------------------------------- *)\n\nlemma unique_circline_type_zero_0':\n  shows \"(circline_type circline_point_0 = 0 \\<and> 0\\<^sub>h \\<in> circline_set circline_point_0) \\<and>\n         (\\<forall> H. circline_type H = 0 \\<and> 0\\<^sub>h \\<in> circline_set H \\<longrightarrow> H = circline_point_0)\"\nunfolding circline_set_def\nproof (safe)\n  show \"circline_type circline_point_0 = 0\"\n    by (transfer, transfer, simp)\nnext\n  show \"on_circline circline_point_0 0\\<^sub>h\"\n    using circline_set_def zero_in_circline_point_0\n    by auto\nnext\n  fix H\n  assume \"circline_type H = 0\" \"on_circline H 0\\<^sub>h\"\n  thus \"H = circline_point_0\"\n  proof (transfer, transfer)\n    fix H :: complex_mat\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 *: \"C = cnj B\" \"is_real A\"\n      using hh hermitean_elems[of A B C D]\n      by auto\n    assume \"circline_type_cmat H = 0\" \"on_circline_cmat_cvec H 0\\<^sub>v\"\n    thus \"circline_eq_cmat H circline_point_0_cmat\"\n      using HH hh *\n      by (simp add: Let_def vec_cnj_def sgn_minus sgn_mult sgn_zero_iff)\n         (rule_tac x=\"1/Re A\" in exI, cases A, cases B, simp add: Complex_eq sgn_zero_iff)\n  qed\nqed\n\nlemma unique_circline_type_zero_0:\n  shows \"\\<exists>! H. circline_type H = 0 \\<and> 0\\<^sub>h \\<in> circline_set H\"\n  using unique_circline_type_zero_0'\n  by blast\n\nlemma unique_circline_type_zero:\n  shows \"\\<exists>! H. circline_type H = 0 \\<and> z \\<in> circline_set H\"\nproof-\n  obtain M where ++: \"moebius_pt M z = 0\\<^sub>h\"\n    using ex_moebius_1[of z]\n    by auto\n  have +++: \"z = moebius_pt (moebius_inv M) 0\\<^sub>h\"\n    by (subst ++[symmetric]) simp\n  then obtain H0 where *: \"circline_type H0 = 0 \\<and> 0\\<^sub>h \\<in> circline_set H0\" and\n    **: \"\\<forall> H'. circline_type H' = 0 \\<and> 0\\<^sub>h \\<in> circline_set H' \\<longrightarrow> H' = H0\"\n    using unique_circline_type_zero_0\n    by auto\n  let ?H' = \"moebius_circline (moebius_inv M) H0\"\n  show ?thesis\n    unfolding Ex1_def\n    using * +++\n  proof (rule_tac x=\"?H'\" in exI, simp, safe)\n    fix H'\n    assume \"circline_type H' = 0\" \"moebius_pt (moebius_inv M) 0\\<^sub>h \\<in> circline_set H'\"\n    hence \"0\\<^sub>h \\<in> circline_set (moebius_circline M H')\"\n      using ++ +++\n      by force\n    hence \"moebius_circline M H' = H0\"\n      using **[rule_format, of \"moebius_circline M H'\"]\n      using \\<open>circline_type H' = 0\\<close>\n      by simp\n    thus \"H' = moebius_circline (moebius_inv M) H0\"\n      by auto\n  qed\nqed\n\n(* ----------------------------------------------------------------- *)\nsubsubsection \\<open>Negative type circline uniqueness\\<close>\n(* ----------------------------------------------------------------- *)\n\nlemma unique_circline_01inf':\n  shows \"0\\<^sub>h \\<in> circline_set x_axis \\<and> 1\\<^sub>h \\<in> circline_set x_axis \\<and> \\<infinity>\\<^sub>h \\<in> circline_set x_axis \\<and>\n        (\\<forall> H. 0\\<^sub>h \\<in> circline_set H \\<and> 1\\<^sub>h \\<in> circline_set H \\<and> \\<infinity>\\<^sub>h \\<in> circline_set H  \\<longrightarrow> H = x_axis)\"\nproof safe\n  fix H\n  assume \"0\\<^sub>h \\<in> circline_set H\"  \"1\\<^sub>h \\<in> circline_set H\" \"\\<infinity>\\<^sub>h \\<in> circline_set H\"\n  thus \"H = x_axis\"\n    unfolding circline_set_def\n    apply simp\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 *: \"C = cnj B\" \"A = 0 \\<and> D = 0 \\<longrightarrow> B \\<noteq> 0\"\n      using hermitean_elems[of A B C D] hh HH\n      by auto\n    obtain Bx By where \"B = Complex Bx By\"\n      by (cases B) auto\n    assume \"on_circline_cmat_cvec H 0\\<^sub>v\" \"on_circline_cmat_cvec H 1\\<^sub>v\" \"on_circline_cmat_cvec H \\<infinity>\\<^sub>v\"\n    thus \"circline_eq_cmat H x_axis_cmat\"\n      using * HH \\<open>C = cnj B\\<close> \\<open>B = Complex Bx By\\<close>\n      by (simp add: Let_def vec_cnj_def Complex_eq) (rule_tac x=\"1/By\" in exI, auto)\n  qed\nqed simp_all\n\nlemma unique_circline_set:\n  assumes \"A \\<noteq> B\" and \"A \\<noteq> C\" and \"B \\<noteq> C\"\n  shows \"\\<exists>! H. A \\<in> circline_set H \\<and> B \\<in> circline_set H \\<and> C \\<in> circline_set H\"\nproof-\n  let ?P = \"\\<lambda> A B C. A \\<noteq> B \\<and> A \\<noteq> C \\<and> B \\<noteq> C \\<longrightarrow> (\\<exists>! H. A \\<in> circline_set H \\<and> B \\<in> circline_set H \\<and> C \\<in> circline_set H)\"\n  have \"?P A B C\"\n  proof (rule wlog_moebius_01inf[of ?P])\n    fix M a b c\n    let ?M = \"moebius_pt M\"\n    assume \"?P a b c\"\n    show \"?P (?M a) (?M b) (?M c)\"\n    proof\n      assume \"?M a \\<noteq> ?M b \\<and> ?M a \\<noteq> ?M c \\<and> ?M b \\<noteq> ?M c\"\n      hence \"a \\<noteq> b\" \"b \\<noteq> c\" \"a \\<noteq> c\"\n        by auto\n      hence \"\\<exists>!H. a \\<in> circline_set H \\<and> b \\<in> circline_set H \\<and> c \\<in> circline_set H\"\n        using \\<open>?P a b c\\<close>\n        by simp\n      then obtain H where\n        *: \"a \\<in> circline_set H \\<and> b \\<in> circline_set H \\<and> c \\<in> circline_set H\" and\n        **: \"\\<forall>H'. a \\<in> circline_set H' \\<and> b \\<in> circline_set H' \\<and> c \\<in> circline_set H' \\<longrightarrow> H' = H\"\n        unfolding Ex1_def\n        by auto\n      let ?H' = \"moebius_circline M H\"\n      show \"\\<exists>! H. ?M a \\<in> circline_set H \\<and> moebius_pt M b \\<in> circline_set H \\<and> moebius_pt M c \\<in> circline_set H\"\n        unfolding Ex1_def\n      proof (rule_tac x=\"?H'\" in exI, rule)\n        show \"?M a \\<in> circline_set ?H' \\<and> ?M b \\<in> circline_set ?H' \\<and> ?M c \\<in> circline_set ?H'\"\n          using * \n          by auto\n      next\n        show \"\\<forall>H'. ?M a \\<in> circline_set H' \\<and> ?M b \\<in> circline_set H' \\<and> ?M c \\<in> circline_set H' \\<longrightarrow> H' = ?H'\"\n        proof (safe)\n          fix H'\n          let ?iH' = \"moebius_circline (moebius_inv M) H'\"\n          assume \"?M a \\<in> circline_set H'\" \"?M b \\<in> circline_set H'\" \"?M c \\<in> circline_set H'\"\n          hence \"a \\<in> circline_set ?iH' \\<and> b \\<in> circline_set ?iH' \\<and> c \\<in> circline_set ?iH'\"\n            by simp\n          hence \"H = ?iH'\"\n            using **\n            by blast\n          thus \"H' = moebius_circline M H\"\n            by simp\n        qed\n      qed\n    qed\n  next\n    show \"?P 0\\<^sub>h 1\\<^sub>h \\<infinity>\\<^sub>h\"\n      using unique_circline_01inf'\n      unfolding Ex1_def\n      by (safe, rule_tac x=\"x_axis\" in exI) auto\n  qed fact+\n  thus ?thesis\n    using assms\n    by simp\nqed\n\nlemma zero_one_inf_x_axis [simp]:\n  assumes \"0\\<^sub>h \\<in> circline_set H\" and \"1\\<^sub>h \\<in> circline_set H\" and \"\\<infinity>\\<^sub>h \\<in> circline_set H\"\n  shows \"H = x_axis\"\n  using assms unique_circline_set[of \"0\\<^sub>h\" \"1\\<^sub>h\" \"\\<infinity>\\<^sub>h\"]\n  by auto\n\n(* ----------------------------------------------------------------- *)\nsubsection \\<open>Circline set cardinality\\<close>\n(* ----------------------------------------------------------------- *)\n\n(* ----------------------------------------------------------------- *)\nsubsubsection \\<open>Diagonal circlines\\<close>\n(* ----------------------------------------------------------------- *)\n\ndefinition is_diag_circline_cmat :: \"complex_mat \\<Rightarrow> bool\" where\n [simp]: \"is_diag_circline_cmat H = (let (A, B, C, D) = H in B = 0 \\<and> C = 0)\"\nlift_definition is_diag_circline_clmat :: \"circline_mat \\<Rightarrow> bool\" is is_diag_circline_cmat\n  done\nlift_definition circline_diag :: \"circline \\<Rightarrow> bool\" is is_diag_circline_clmat\n  by transfer auto\n\nlemma circline_diagonalize:\n  shows \"\\<exists> M H'. moebius_circline M H = H' \\<and> circline_diag H'\"\nproof (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  hence HH_elems: \"is_real A\" \"is_real D\" \"C = cnj B\"\n    using hermitean_elems[of A B C D] hh\n    by auto\n  obtain M k1 k2 where *: \"mat_det M \\<noteq> 0\" \"unitary M\" \"congruence M H = (k1, 0, 0, k2)\" \"is_real k1\" \"is_real k2\"\n    using hermitean_diagonizable[of H] hh\n    by auto\n  have \"k1 \\<noteq> 0 \\<or> k2 \\<noteq> 0\"\n    using \\<open>congruence M H = (k1, 0, 0, k2)\\<close> hh congruence_nonzero[of H M] \\<open>mat_det M \\<noteq> 0\\<close>\n    by auto\n  let ?M' = \"mat_inv M\"\n  let ?H' = \"(k1, 0, 0, k2)\"\n  have \"circline_eq_cmat (moebius_circline_cmat_cmat ?M' H) ?H' \\<and> is_diag_circline_cmat ?H'\"\n    using *\n    by force\n  moreover\n  have \"?H' \\<in> hermitean_nonzero\"\n    using * \\<open>k1 \\<noteq> 0 \\<or> k2 \\<noteq> 0\\<close> eq_cnj_iff_real[of k1] eq_cnj_iff_real[of k2]\n    by (auto simp add: hermitean_def mat_adj_def mat_cnj_def)\n  moreover\n  have \"mat_det ?M' \\<noteq> 0\"\n    using * mat_det_inv[of M]\n    by auto\n  ultimately\n  show \"\\<exists>M\\<in>{M. mat_det M \\<noteq> 0}.\n            \\<exists>H'\\<in>hermitean_nonzero.\n               circline_eq_cmat (moebius_circline_cmat_cmat M H) H' \\<and> is_diag_circline_cmat H'\"\n    by blast\nqed\n\nlemma wlog_circline_diag:\n  assumes \"\\<And> H. circline_diag H \\<Longrightarrow> P H\"\n          \"\\<And> M H. P H \\<Longrightarrow> P (moebius_circline M H)\"\n  shows \"P H\"\nproof-\n  obtain M H' where \"moebius_circline M H = H'\" \"circline_diag H'\"\n    using circline_diagonalize[of H]\n    by auto\n  hence \"P (moebius_circline M H)\"\n    using assms(1)\n    by simp\n  thus ?thesis\n    using assms(2)[of \"moebius_circline M H\" \"moebius_inv M\"]\n    by simp\nqed\n\n(* ----------------------------------------------------------------- *)\nsubsubsection \\<open>Zero type circline set cardinality\\<close>\n(* ----------------------------------------------------------------- *)\n\nlemma circline_type_zero_card_eq1_0:\n  assumes \"circline_type H = 0\" and \"0\\<^sub>h \\<in> circline_set H\"\n  shows \"circline_set H = {0\\<^sub>h}\"\nusing assms\nunfolding circline_set_def\nproof(safe)\n  fix z\n  assume \"on_circline H z\" \"circline_type H = 0\" \"on_circline H 0\\<^sub>h\"\n  hence \"H = circline_point_0\"\n    using unique_circline_type_zero_0'\n    unfolding circline_set_def\n    by simp\n  thus \"z = 0\\<^sub>h\"\n    using \\<open>on_circline H z\\<close>\n    by (transfer, transfer) (case_tac z, case_tac H, force simp add: vec_cnj_def)\nqed\n\n\nlemma circline_type_zero_card_eq1:\n  assumes \"circline_type H = 0\"\n  shows \"\\<exists> z. circline_set H = {z}\"\nproof-\n  have \"\\<exists> z. on_circline H z\"\n    using assms\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    hence \"C = cnj B\" \"is_real A\" \"is_real D\"\n      using hh hermitean_elems[of A B C D]\n      by auto\n    assume \"circline_type_cmat H = 0\"\n    hence \"mat_det H = 0\"\n      by (simp add: complex_eq_if_Re_eq hh mat_det_hermitean_real sgn_eq_0_iff)\n    hence \"A*D = B*C\"\n      using HH\n      by simp\n    show \"Bex {v. v \\<noteq> vec_zero} (on_circline_cmat_cvec H)\"\n    proof (cases \"A \\<noteq> 0 \\<or> B \\<noteq> 0\")\n      case True\n      thus ?thesis\n        using HH \\<open>A*D = B*C\\<close>\n        by (rule_tac x=\"(-B, A)\" in bexI) (auto simp add: Let_def vec_cnj_def field_simps)\n    next\n      case False\n      thus ?thesis\n        using HH \\<open>C = cnj B\\<close>\n        by (rule_tac x=\"(1, 0)\" in bexI) (simp_all add: Let_def vec_cnj_def)\n    qed\n  qed\n  then obtain z where \"on_circline H z\"\n    by auto\n  obtain M where \"moebius_pt M z = 0\\<^sub>h\"\n    using ex_moebius_1[of z]\n    by auto\n  hence \"0\\<^sub>h \\<in> circline_set (moebius_circline M H)\"\n    using on_circline_moebius_circline_I[OF \\<open>on_circline H z\\<close>, of M]\n    unfolding circline_set_def\n    by simp\n  hence \"circline_set (moebius_circline M H) = {0\\<^sub>h}\"\n    using circline_type_zero_card_eq1_0[of \"moebius_circline M H\"] \\<open>circline_type H = 0\\<close>\n    by auto\n  hence \"circline_set H = {z}\"\n    using \\<open>moebius_pt M z = 0\\<^sub>h\\<close>\n    using bij_moebius_pt[of M] bij_image_singleton[of \"moebius_pt M\" \"circline_set H\" _ z]\n    by simp\n  thus ?thesis\n    by auto\nqed\n\n(* ----------------------------------------------------------------- *)\nsubsubsection \\<open>Negative type circline set cardinality\\<close>\n(* ----------------------------------------------------------------- *)\n\nlemma quad_form_diagonal_iff:\n  assumes \"k1 \\<noteq> 0\" and \"is_real k1\" and \"is_real k2\" and \"Re k1 * Re k2 < 0\"\n  shows \"quad_form (z1, 1) (k1, 0, 0, k2) = 0 \\<longleftrightarrow> (\\<exists> \\<phi>. z1 = rcis (sqrt (Re (-k2 /k1))) \\<phi>)\"\nproof-\n  have \"Re (-k2/k1) \\<ge> 0\"\n    using \\<open>Re k1 * Re k2 < 0\\<close> \\<open>is_real k1\\<close> \\<open>is_real k2\\<close> \\<open>k1 \\<noteq> 0\\<close>\n    using Re_divide_real[of k1 \"-k2\"]\n    by (smt divide_less_0_iff mult_nonneg_nonneg mult_nonpos_nonpos uminus_complex.simps(1))\n\n  have \"quad_form (z1, 1) (k1, 0, 0, k2) = 0 \\<longleftrightarrow> (cor (cmod z1))\\<^sup>2 = -k2 / k1\"\n    using assms add_eq_0_iff[of k2 \"k1*(cor (cmod z1))\\<^sup>2\"]\n    using eq_divide_imp[of k1 \"(cor (cmod z1))\\<^sup>2\" \"-k2\"]\n    by (auto simp add: vec_cnj_def field_simps complex_mult_cnj_cmod)\n  also have \"... \\<longleftrightarrow> (cmod z1)\\<^sup>2 = Re (-k2 /k1)\"\n    using assms\n    apply (subst complex_eq_if_Re_eq)\n    using Re_complex_of_real[of \"(cmod z1)\\<^sup>2\"] div_reals\n    by auto\n  also have \"... \\<longleftrightarrow> cmod z1 = sqrt (Re (-k2 /k1))\"\n    by (metis norm_ge_zero real_sqrt_ge_0_iff real_sqrt_pow2 real_sqrt_power)\n  also have \"... \\<longleftrightarrow> (\\<exists> \\<phi>. z1 = rcis (sqrt (Re (-k2 /k1))) \\<phi>)\"\n    using rcis_cmod_arg[of z1, symmetric] assms abs_of_nonneg[of \"sqrt (Re (-k2/k1))\"]\n    using \\<open>Re (-k2/k1) \\<ge> 0\\<close>\n    by auto\n  finally show ?thesis\n    .\nqed\n\nlemma circline_type_neg_card_gt3_diag:\n  assumes \"circline_type H < 0\" and \"circline_diag H\"\n  shows \"\\<exists> A B C. A \\<noteq> B \\<and> A \\<noteq> C \\<and> B \\<noteq> C \\<and> {A, B, C} \\<subseteq> circline_set H\"\n  using assms\n  unfolding circline_set_def\n  apply (simp del: HOL.ex_simps)\nproof (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  hence HH_elems: \"is_real A\" \"is_real D\" \"C = cnj B\"\n    using hermitean_elems[of A B C D] hh\n    by auto\n  assume \"circline_type_cmat H < 0\" \"is_diag_circline_cmat H\"\n  hence \"B = 0\" \"C = 0\" \"Re A * Re D < 0\" \"A \\<noteq> 0\"\n    using HH \\<open>is_real A\\<close> \\<open>is_real D\\<close>\n    by auto\n\n  let ?x = \"sqrt (Re (- D / A))\"\n  let ?A = \"(rcis ?x 0, 1)\"\n  let ?B = \"(rcis ?x (pi/2), 1)\"\n  let ?C = \"(rcis ?x pi, 1)\"\n  from quad_form_diagonal_iff[OF \\<open>A \\<noteq> 0\\<close> \\<open>is_real A\\<close> \\<open>is_real D\\<close> \\<open>Re A * Re D < 0\\<close>]\n  have \"quad_form ?A (A, 0, 0, D) = 0\"  \"quad_form ?B (A, 0, 0, D) = 0\"  \"quad_form ?C (A, 0, 0, D) = 0\"\n    by (auto simp del: rcis_zero_arg)\n  hence \"on_circline_cmat_cvec H ?A \\<and> on_circline_cmat_cvec H ?B \\<and> on_circline_cmat_cvec H ?C\"\n    using HH \\<open>B = 0\\<close> \\<open>C = 0\\<close>\n    by simp\n  moreover                                    \n  have \"Re (D / A) < 0\"\n    using \\<open>Re A * Re D < 0\\<close> \\<open>A \\<noteq> 0\\<close> \\<open>is_real A\\<close> \\<open>is_real D\\<close>\n    using Re_divide_real[of A D]\n    by (metis Re_complex_div_lt_0 Re_mult_real div_reals eq_cnj_iff_real is_real_div)\n  hence \"\\<not> ?A \\<approx>\\<^sub>v ?B \\<and> \\<not> ?A \\<approx>\\<^sub>v ?C \\<and> \\<not> ?B \\<approx>\\<^sub>v ?C\"\n    unfolding rcis_def\n    by (auto simp add: cis_def complex.corec)\n  moreover\n  have \"?A \\<noteq> vec_zero\" \"?B \\<noteq> vec_zero\" \"?C \\<noteq> vec_zero\"\n    by auto\n  ultimately\n  show \"\\<exists>A\\<in>{v. v \\<noteq> vec_zero}. \\<exists>B\\<in>{v. v \\<noteq> vec_zero}. \\<exists>C\\<in>{v. v \\<noteq> vec_zero}.\n            \\<not> A \\<approx>\\<^sub>v B \\<and> \\<not> A \\<approx>\\<^sub>v C \\<and> \\<not> B \\<approx>\\<^sub>v C \\<and>\n            on_circline_cmat_cvec H A \\<and> on_circline_cmat_cvec H B \\<and> on_circline_cmat_cvec H C\"\n    by blast\nqed\n\nlemma circline_type_neg_card_gt3:\n  assumes \"circline_type H < 0\"\n  shows \"\\<exists> A B C. A \\<noteq> B \\<and> A \\<noteq> C \\<and> B \\<noteq> C \\<and> {A, B, C} \\<subseteq> circline_set H\"\nproof-\n  obtain M H' where \"moebius_circline M H = H'\" \"circline_diag H'\"\n    using circline_diagonalize[of H] assms\n    by auto\n  moreover\n  hence \"circline_type H' < 0\"\n    using assms moebius_preserve_circline_type\n    by auto\n  ultimately\n  obtain A B C where \"A \\<noteq> B\" \"A \\<noteq> C\" \"B \\<noteq> C\" \"{A, B, C} \\<subseteq> circline_set H'\"\n    using circline_type_neg_card_gt3_diag[of H']\n    by auto\n  let ?iM = \"moebius_inv M\"\n  have \"moebius_circline ?iM H' = H\"\n    using \\<open>moebius_circline M H = H'\\<close>[symmetric]\n    by simp\n  let ?A = \"moebius_pt ?iM A\" and ?B= \"moebius_pt ?iM B\" and ?C = \"moebius_pt ?iM C\"\n  have \"?A \\<in> circline_set H\"  \"?B \\<in> circline_set H\"  \"?C \\<in> circline_set H\"\n    using \\<open>moebius_circline ?iM H' = H\\<close>[symmetric] \\<open>{A, B, C} \\<subseteq> circline_set H'\\<close>\n    by simp_all\n  moreover\n  have \"?A \\<noteq> ?B\" \"?A \\<noteq> ?C\" \"?B \\<noteq> ?C\"\n    using \\<open>A \\<noteq> B\\<close> \\<open>A \\<noteq> C\\<close> \\<open>B \\<noteq> C\\<close>\n    by auto\n  ultimately\n  show ?thesis\n    by auto\nqed\n\n(* ----------------------------------------------------------------- *)\nsubsubsection \\<open>Positive type circline set cardinality\\<close>\n(* ----------------------------------------------------------------- *)\n\n\n\nlemma circline_type_pos_card_eq0:\n  assumes \"circline_type H > 0\"\n  shows \"circline_set H = {}\"\nproof-\n  obtain M H' where \"moebius_circline M H = H'\" \"circline_diag H'\"\n    using circline_diagonalize[of H] assms\n    by auto\n  moreover\n  hence \"circline_type H' > 0\"\n    using assms moebius_preserve_circline_type\n    by auto\n  ultimately\n  have \"circline_set H' = {}\"\n    using circline_type_pos_card_eq0_diag[of H']\n    by auto\n  let ?iM = \"moebius_inv M\"\n  have \"moebius_circline ?iM H' = H\"\n    using \\<open>moebius_circline M H = H'\\<close>[symmetric]\n    by simp\n  thus ?thesis\n    using \\<open>circline_set H' = {}\\<close>\n    by auto\nqed\n\n(* ----------------------------------------------------------------- *)\nsubsubsection \\<open>Cardinality determines type\\<close>\n(* ----------------------------------------------------------------- *)\n\nlemma card_eq1_circline_type_zero:\n  assumes \"\\<exists> z. circline_set H = {z}\"\n  shows \"circline_type H = 0\"\nproof (cases \"circline_type H < 0\")\n  case True\n  thus ?thesis\n    using circline_type_neg_card_gt3[of H] assms\n    by auto\nnext\n  case False\n  show ?thesis\n  proof (cases \"circline_type H > 0\")\n    case True\n    thus ?thesis\n      using circline_type_pos_card_eq0[of H] assms\n      by auto\n  next\n    case False\n    thus ?thesis\n      using \\<open>\\<not> (circline_type H) < 0\\<close>\n      by simp\n  qed\nqed\n\n(* ----------------------------------------------------------------- *)\nsubsubsection \\<open>Circline set is injective\\<close>\n(* ----------------------------------------------------------------- *)\n\nlemma inj_circline_set:\n  assumes \"circline_set H = circline_set H'\" and \"circline_set H \\<noteq> {}\"\n  shows \"H = H'\"\nproof (cases \"circline_type H < 0\")\n  case True\n  then obtain A B C where \"A \\<noteq> B\" \"A \\<noteq> C\" \"B \\<noteq> C\" \"{A, B, C} \\<subseteq> circline_set H\"\n    using circline_type_neg_card_gt3[of H]\n    by auto\n  hence \"\\<exists>!H. A \\<in> circline_set H \\<and> B \\<in> circline_set H \\<and> C \\<in> circline_set H\"\n    using unique_circline_set[of A B C]\n    by simp\n  thus ?thesis\n    using \\<open>circline_set H = circline_set H'\\<close> \\<open>{A, B, C} \\<subseteq> circline_set H\\<close>\n    by auto\nnext\n  case False\n  show ?thesis\n  proof (cases \"circline_type H = 0\")\n    case True\n    moreover\n    then obtain A where \"{A} = circline_set H\"\n      using circline_type_zero_card_eq1[of H]\n      by auto\n    moreover\n    hence \"circline_type H' = 0\"\n      using \\<open>circline_set H = circline_set H'\\<close> card_eq1_circline_type_zero[of H']\n      by auto\n    ultimately\n    show ?thesis\n      using unique_circline_type_zero[of A] \\<open>circline_set H = circline_set H'\\<close>\n      by auto\n  next\n    case False\n    hence \"circline_type H > 0\"\n      using \\<open>\\<not> (circline_type H < 0)\\<close>\n      by auto\n    thus ?thesis\n      using \\<open>circline_set H \\<noteq> {}\\<close>  circline_type_pos_card_eq0[of H]\n      by auto\n  qed\nqed\n\n(* ----------------------------------------------------------------- *)\nsubsection \\<open>Circline points - cross ratio real\\<close>\n(* ----------------------------------------------------------------- *)\n\nlemma four_points_on_circline_iff_cross_ratio_real:\n  assumes \"distinct [z, u, v, w]\"\n  shows \"is_real (to_complex (cross_ratio z u v w)) \\<longleftrightarrow> \n         (\\<exists> H. {z, u, v, w} \\<subseteq> circline_set H)\"\nproof-\n  have \"\\<forall> z. distinct [z, u, v, w] \\<longrightarrow> is_real (to_complex (cross_ratio z u v w)) \\<longleftrightarrow> (\\<exists> H. {z, u, v, w} \\<subseteq> circline_set H)\"\n       (is \"?P u v w\")\n  proof (rule wlog_moebius_01inf[of ?P u v w])\n    fix M a b c\n    assume aa: \"?P a b c\"\n    let ?Ma = \"moebius_pt M a\" and ?Mb = \"moebius_pt M b\" and ?Mc = \"moebius_pt M c\"\n    show \"?P ?Ma ?Mb ?Mc\"\n    proof (rule allI, rule impI)\n      fix z\n      obtain d where *: \"z = moebius_pt M d\"\n        using bij_moebius_pt[of M]\n        unfolding bij_def\n        by auto\n      let ?Md = \"moebius_pt M d\"\n      assume \"distinct [z, moebius_pt M a, moebius_pt M b, moebius_pt M c]\"\n      hence \"distinct [a, b, c, d]\"\n        using *\n        by auto\n      moreover\n      have \"(\\<exists> H. {d, a, b, c} \\<subseteq> circline_set H) \\<longleftrightarrow> (\\<exists> H. {z, ?Ma, ?Mb, ?Mc} \\<subseteq> circline_set H)\"\n        using *\n        apply auto\n        apply (rule_tac x=\"moebius_circline M H\" in exI, simp)\n        apply (rule_tac x=\"moebius_circline (moebius_inv M) H\" in exI, simp)\n        done\n      ultimately\n      show \"is_real (to_complex (cross_ratio z ?Ma ?Mb ?Mc)) = (\\<exists>H. {z, ?Ma, ?Mb, ?Mc} \\<subseteq> circline_set H)\"\n        using aa[rule_format, of d] *\n        by auto\n    qed\n  next\n    show \"?P 0\\<^sub>h 1\\<^sub>h \\<infinity>\\<^sub>h\"\n    proof safe\n      fix z\n      assume \"distinct [z, 0\\<^sub>h, 1\\<^sub>h, \\<infinity>\\<^sub>h]\"\n      hence \"z \\<noteq> \\<infinity>\\<^sub>h\"\n        by auto\n      assume \"is_real (to_complex (cross_ratio z 0\\<^sub>h 1\\<^sub>h \\<infinity>\\<^sub>h))\"\n      hence \"is_real (to_complex z)\"\n        by simp\n      hence \"z \\<in> circline_set x_axis\"\n        using of_complex_to_complex[symmetric, OF \\<open>z \\<noteq> \\<infinity>\\<^sub>h\\<close>]\n        using circline_set_x_axis\n        by auto\n      thus \"\\<exists>H. {z, 0\\<^sub>h, 1\\<^sub>h, \\<infinity>\\<^sub>h} \\<subseteq> circline_set H\"\n        by (rule_tac x=x_axis in exI, auto)\n    next\n      fix z H\n      assume *: \"distinct [z, 0\\<^sub>h, 1\\<^sub>h, \\<infinity>\\<^sub>h]\" \"{z, 0\\<^sub>h, 1\\<^sub>h, \\<infinity>\\<^sub>h} \\<subseteq> circline_set H\"\n      hence \"H = x_axis\"\n        by auto\n      hence \"z \\<in> circline_set x_axis\"\n        using *\n        by auto\n      hence \"is_real (to_complex z)\"\n        using * circline_set_x_axis\n        by auto\n      thus \"is_real (to_complex (cross_ratio z 0\\<^sub>h 1\\<^sub>h \\<infinity>\\<^sub>h))\"\n        by simp\n    qed\n  next\n    show \"u \\<noteq> v\" \"v \\<noteq> w\" \"u \\<noteq> w\"\n      using assms\n      by auto\n  qed\n  thus ?thesis\n    using assms\n    by auto\nqed\n\n(* ----------------------------------------------------------------- *)\nsubsection \\<open>Symmetric points wrt. circline\\<close>\n(* ----------------------------------------------------------------- *)\n\ntext \\<open>In the extended complex plane there are no substantial differences between circles and lines,\nso we will consider only one kind of relation and call two points \\emph{circline symmetric} if they\nare mapped to one another using either reflection or inversion over arbitrary line or circle. Points\nare symmetric iff the bilinear form of their representation vectors and matrix is zero.\\<close>\n\ndefinition circline_symmetric_cvec_cmat :: \"complex_vec \\<Rightarrow> complex_vec \\<Rightarrow> complex_mat \\<Rightarrow> bool\" where\n  [simp]: \"circline_symmetric_cvec_cmat z1 z2 H \\<longleftrightarrow> bilinear_form z1 z2 H = 0\"\nlift_definition circline_symmetric_hcoords_clmat :: \"complex_homo_coords \\<Rightarrow> complex_homo_coords \\<Rightarrow> circline_mat \\<Rightarrow> bool\" is circline_symmetric_cvec_cmat\n  done\nlift_definition circline_symmetric :: \"complex_homo \\<Rightarrow> complex_homo \\<Rightarrow> circline \\<Rightarrow> bool\" is circline_symmetric_hcoords_clmat\n  apply transfer\n  apply (simp del: bilinear_form_def)\n  apply (erule exE)+\n  apply (simp add: bilinear_form_scale_m bilinear_form_scale_v1 bilinear_form_scale_v2 del: vec_cnj_sv quad_form_def bilinear_form_def)\n  done\n\nlemma symmetry_principle [simp]:\n  assumes \"circline_symmetric z1 z2 H\"\n  shows \"circline_symmetric (moebius_pt M z1) (moebius_pt M z2) (moebius_circline M H)\"\n  using assms\n  by (transfer, transfer, simp del: bilinear_form_def congruence_def)\n\ntext \\<open>Symmetry wrt. @{term \"unit_circle\"}\\<close>\nlemma circline_symmetric_0inf_disc [simp]:\n  shows \"circline_symmetric 0\\<^sub>h \\<infinity>\\<^sub>h unit_circle\"\n  by (transfer, transfer, simp add: vec_cnj_def)\n\nlemma circline_symmetric_inv_homo_disc [simp]:\n  shows \"circline_symmetric a (inversion a) unit_circle\"\n  unfolding inversion_def\n  by (transfer, transfer) (case_tac a, auto simp add: vec_cnj_def)\n\nlemma circline_symmetric_inv_homo_disc':\n  assumes \"circline_symmetric a a' unit_circle\"\n  shows \"a' = inversion a\"\n  unfolding inversion_def\n  using assms\nproof (transfer, transfer)\n  fix a a'\n  assume vz: \"a \\<noteq> vec_zero\" \"a' \\<noteq> vec_zero\"\n  obtain a1 a2 where aa: \"a = (a1, a2)\"\n    by (cases a, auto)\n  obtain a1' a2' where aa': \"a' = (a1', a2')\"\n    by (cases a', auto)\n  assume *: \"circline_symmetric_cvec_cmat a a' unit_circle_cmat\"\n  show \"a' \\<approx>\\<^sub>v (conjugate_cvec \\<circ> reciprocal_cvec) a\"\n  proof (cases \"a1' = 0\")\n    case True\n    thus ?thesis\n      using aa aa' vz *\n      by (auto simp add: vec_cnj_def field_simps)\n  next\n    case False\n    show ?thesis\n    proof (cases \"a2 = 0\")\n      case True\n      thus ?thesis\n        using \\<open>a1' \\<noteq> 0\\<close>\n        using aa aa' * vz\n        by (simp add:  vec_cnj_def field_simps)\n    next\n      case False\n      thus ?thesis\n        using \\<open>a1' \\<noteq> 0\\<close> aa aa' *\n        by (simp add: vec_cnj_def field_simps) (rule_tac x=\"cnj a2 / a1'\" in exI, simp add: field_simps)\n    qed\n  qed\nqed\n\nlemma ex_moebius_circline_x_axis:\n  assumes \"circline_type H < 0\"\n  shows \"\\<exists> M. moebius_circline M H = x_axis\"\nproof-\n  obtain A B C where *: \"A \\<noteq> B\" \"A \\<noteq> C\" \"B \\<noteq> C\" \"on_circline H A\" \"on_circline H B\" \"on_circline H C\"\n    using circline_type_neg_card_gt3[OF assms]\n    unfolding circline_set_def\n    by auto\n  then obtain M where \"moebius_pt M A = 0\\<^sub>h\" \"moebius_pt M B = 1\\<^sub>h\" \"moebius_pt M C = \\<infinity>\\<^sub>h\"\n    using ex_moebius_01inf by blast\n  hence \"moebius_circline M H = x_axis\"\n    using *\n    by (metis circline_set_I circline_set_moebius_circline rev_image_eqI unique_circline_01inf')\n  thus ?thesis\n    by blast\nqed\n\nlemma wlog_circline_x_axis:\n  assumes \"circline_type H < 0\"\n  assumes \"\\<And> M H. P H \\<Longrightarrow> P (moebius_circline M H)\"\n  assumes \"P x_axis\"\n  shows \"P H\"\nproof-\n  obtain M where \"moebius_circline M H = x_axis\"\n    using ex_moebius_circline_x_axis[OF assms(1)]\n    by blast\n  then obtain M' where \"moebius_circline M' x_axis = H\"\n    by (metis moebius_circline_comp_inv_left)\n  thus ?thesis\n    using assms(2)[of x_axis M'] assms(3)\n    by simp\nqed\n\nlemma circline_intersection_at_most_2_points:\n  assumes \"H1 \\<noteq> H2\"\n  shows \"finite (circline_intersection H1 H2) \\<and> card (circline_intersection H1 H2) \\<le> 2\"\nproof (rule ccontr)\n  assume \"\\<not> ?thesis\"\n  hence \"infinite (circline_intersection H1 H2) \\<or> card (circline_intersection H1 H2) > 2\"\n    by auto\n  hence \"\\<exists> A B C. A \\<noteq> B \\<and> B \\<noteq> C \\<and> A \\<noteq> C \\<and> {A, B, C} \\<subseteq> circline_intersection H1 H2\"\n  proof\n    assume \"card (circline_intersection H1 H2) > 2\"\n    thus ?thesis\n      using card_geq_3_iff_contains_3_elems[of \"circline_intersection H1 H2\"]\n      by auto\n  next\n    assume \"infinite (circline_intersection H1 H2)\"\n    thus ?thesis\n      using infinite_contains_3_elems\n      by blast\n  qed\n  then obtain A B C where \"A \\<noteq> B\" \"B \\<noteq> C\" \"A \\<noteq> C\" \"{A, B, C} \\<subseteq> circline_intersection H1 H2\"\n    by blast\n  hence \"H2 = H1\"\n    using circline_intersection_def mem_Collect_eq unique_circline_set by fastforce\n  thus False\n    using assms\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/Complex_Geometry/Circlines.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9099070060380481, "lm_q2_score": 0.7981867801399695, "lm_q1q2_score": 0.7262757433763094}}
{"text": "(*  \n    Author:      Ren\u00e9 Thiemann \n                 Akihisa Yamada\n    License:     BSD\n*)\ntheory Conjugate\n  imports HOL.Complex \"HOL-Library.Complex_Order\"\nbegin\n\nclass conjugate =\n  fixes conjugate :: \"'a \\<Rightarrow> 'a\"\n  assumes conjugate_id[simp]: \"conjugate (conjugate a) = a\"\n      and conjugate_cancel_iff[simp]: \"conjugate a = conjugate b \\<longleftrightarrow> a = b\"\n\nclass conjugatable_ring = ring + conjugate +\n  assumes conjugate_dist_mul: \"conjugate (a * b) = conjugate a * conjugate b\"\n      and conjugate_dist_add: \"conjugate (a + b) = conjugate a + conjugate b\"\n      and conjugate_neg: \"conjugate (-a) = - conjugate a\"\n      and conjugate_zero[simp]: \"conjugate 0 = 0\"\nbegin\n  lemma conjugate_zero_iff[simp]: \"conjugate a = 0 \\<longleftrightarrow> a = 0\"\n    using conjugate_cancel_iff[of _ 0, unfolded conjugate_zero].\nend\n\nclass conjugatable_field = conjugatable_ring + field\n\nlemma sum_conjugate:\n  fixes f :: \"'b \\<Rightarrow> 'a :: conjugatable_ring\"\n  assumes finX: \"finite X\"\n  shows \"conjugate (sum f X) = sum (\\<lambda>x. conjugate (f x)) X\"\n  using finX by (induct set:finite, auto simp: conjugate_dist_add)\n\nclass conjugatable_ordered_ring = conjugatable_ring + ordered_comm_monoid_add +\n  assumes conjugate_square_positive: \"a * conjugate a \\<ge> 0\"\n\nclass conjugatable_ordered_field = conjugatable_ordered_ring + field\nbegin\n  subclass conjugatable_field..\nend\n\nlemma conjugate_square_0:\n  fixes a :: \"'a :: {conjugatable_ordered_ring, semiring_no_zero_divisors}\"\n  shows \"a * conjugate a = 0 \\<Longrightarrow> a = 0\" by auto\n\n\nsubsection \\<open>Instantiations\\<close>\n\ninstantiation complex :: conjugatable_ordered_field\nbegin\n  definition [simp]: \"conjugate \\<equiv> cnj\"\n  \ninstance\n  by intro_classes (auto simp: less_eq_complex_def)\n\nend\n\ninstantiation real :: conjugatable_ordered_field\nbegin\n  definition [simp]: \"conjugate (x::real) \\<equiv> x\"\n  instance by (intro_classes, auto)\nend\n\ninstantiation rat :: conjugatable_ordered_field\nbegin\n  definition [simp]: \"conjugate (x::rat) \\<equiv> x\"\n  instance by (intro_classes, auto)\nend\n\ninstantiation int :: conjugatable_ordered_ring\nbegin\n  definition [simp]: \"conjugate (x::int) \\<equiv> x\"\n  instance by (intro_classes, auto)\nend\n\nlemma conjugate_square_eq_0 [simp]:\n  fixes x :: \"'a :: {conjugatable_ring,semiring_no_zero_divisors}\"\n  shows \"x * conjugate x = 0 \\<longleftrightarrow> x = 0\" \"conjugate x * x = 0 \\<longleftrightarrow> x = 0\"\n  by auto\n\nlemma conjugate_square_greater_0 [simp]:\n  fixes x :: \"'a :: {conjugatable_ordered_ring,ring_no_zero_divisors}\"\n  shows \"x * conjugate x > 0 \\<longleftrightarrow> x \\<noteq> 0\" \n  using conjugate_square_positive[of x]\n  by (auto simp: le_less)\n\nlemma conjugate_square_smaller_0 [simp]:\n  fixes x :: \"'a :: {conjugatable_ordered_ring,ring_no_zero_divisors}\"\n  shows \"\\<not> x * conjugate x < 0\"\n  using conjugate_square_positive[of x] by 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/Jordan_Normal_Form/Conjugate.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8670357701094303, "lm_q2_score": 0.8376199673867852, "lm_q1q2_score": 0.7262464734822373}}
{"text": "theory Summation\nimports\n  Complex_Main\n  \"~~/src/HOL/Library/Extended_Real\" \n  \"~~/src/HOL/Library/Liminf_Limsup\"\n  Liminf_Limsup_Lemma_Bucket\n  Extended_Real_Lemma_Bucket\n  Natlog2\nbegin\n\nsubsection \\<open>Convergence tests for infinite sums\\<close>\n\nsubsubsection \\<open>Root test\\<close>\n\nlemma limsup_root_powser:\n  fixes f :: \"nat \\<Rightarrow> 'a :: {banach, real_normed_div_algebra}\"\n  shows \"limsup (\\<lambda>n. ereal (root n (norm (f n * z ^ n)))) = \n             limsup (\\<lambda>n. ereal (root n (norm (f n)))) * ereal (norm z)\"\nproof -\n  have A: \"(\\<lambda>n. ereal (root n (norm (f n * z ^ n)))) = \n              (\\<lambda>n. ereal (root n (norm (f n))) * ereal (norm z))\" (is \"?g = ?h\")\n  proof\n    fix n show \"?g n = ?h n\"\n    by (cases \"n = 0\") (simp_all add: norm_mult real_root_mult real_root_pos2 norm_power)\n  qed\n  show ?thesis by (subst A, subst limsup_ereal_mult_right) simp_all\nqed\n\nlemma limsup_root_limit:\n  assumes \"(\\<lambda>n. ereal (root n (norm (f n)))) ----> l\" (is \"?g ----> _\")\n  shows   \"limsup (\\<lambda>n. ereal (root n (norm (f n)))) = l\"\nproof -\n  from assms have \"convergent ?g\" \"lim ?g = l\"\n    unfolding convergent_def by (blast intro: limI)+\n  with convergent_limsup_cl show ?thesis by force\nqed\n\nlemma limsup_root_limit':\n  assumes \"(\\<lambda>n. root n (norm (f n))) ----> l\"\n  shows   \"limsup (\\<lambda>n. ereal (root n (norm (f n)))) = ereal l\"\n  by (intro limsup_root_limit tendsto_ereal assms)\n\nlemma root_test_convergence':\n  fixes f :: \"nat \\<Rightarrow> 'a :: banach\"\n  defines \"l \\<equiv> limsup (\\<lambda>n. ereal (root n (norm (f n))))\"\n  assumes l: \"l < 1\"\n  shows   \"summable f\"\nproof -\n  have \"0 = limsup (\\<lambda>n. 0)\" by (simp add: Limsup_const)\n  also have \"... \\<le> l\" unfolding l_def by (intro Limsup_mono) (simp_all add: real_root_ge_zero)\n  finally have \"l \\<ge> 0\" by simp\n  with l obtain l' where l': \"l = ereal l'\" by (cases l) simp_all\n\n  def c \\<equiv> \"(1 - l') / 2\"\n  from l and `l \\<ge> 0` have c: \"l + c > l\" \"l' + c \\<ge> 0\" \"l' + c < 1\" unfolding c_def \n    by (simp_all add: field_simps l')\n  have \"\\<forall>C>l. eventually (\\<lambda>n. ereal (root n (norm (f n))) < C) sequentially\"\n    by (subst ge_Limsup_iff[symmetric]) (simp add: l_def)\n  with c have \"eventually (\\<lambda>n. ereal (root n (norm (f n))) < l + ereal c) sequentially\" by simp\n  with eventually_gt_at_top[of \"0::nat\"]\n    have \"eventually (\\<lambda>n. norm (f n) \\<le> (l' + c) ^ n) sequentially\"\n  proof eventually_elim\n    fix n :: nat assume n: \"n > 0\" \n    assume \"ereal (root n (norm (f n))) < l + ereal c\"\n    hence \"root n (norm (f n)) \\<le> l' + c\" by (simp add: l')\n    with c n have \"root n (norm (f n)) ^ n \\<le> (l' + c) ^ n\"\n      by (intro power_mono) (simp_all add: real_root_ge_zero)\n    also from n have \"root n (norm (f n)) ^ n = norm (f n)\" by simp\n    finally show \"norm (f n) \\<le> (l' + c) ^ n\" by simp\n  qed\n  thus ?thesis\n    by (rule summable_comparison_test_ev[OF _ summable_geometric]) (simp add: c)\nqed\n\nlemma root_test_divergence:\n  fixes f :: \"nat \\<Rightarrow> 'a :: banach\"\n  defines \"l \\<equiv> limsup (\\<lambda>n. ereal (root n (norm (f n))))\"\n  assumes l: \"l > 1\"\n  shows   \"\\<not>summable f\"\nproof\n  assume \"summable f\"\n  hence bounded: \"Bseq f\" by (simp add: summable_imp_Bseq)\n\n  have \"0 = limsup (\\<lambda>n. 0)\" by (simp add: Limsup_const)\n  also have \"... \\<le> l\" unfolding l_def by (intro Limsup_mono) (simp_all add: real_root_ge_zero)\n  finally have l_nonneg: \"l \\<ge> 0\" by simp\n\n  def c \\<equiv> \"if l = \\<infinity> then 2 else 1 + (real_of_ereal l - 1) / 2\"\n  from l l_nonneg consider \"l = \\<infinity>\" | \"\\<exists>l'. l = ereal l'\" by (cases l) simp_all\n  hence c: \"c > 1 \\<and> ereal c < l\" by cases (insert l, auto simp: c_def field_simps)\n\n  have unbounded: \"\\<not>bdd_above {n. root n (norm (f n)) > c}\"\n  proof\n    assume \"bdd_above {n. root n (norm (f n)) > c}\"\n    then obtain N where \"\\<forall>n. root n (norm (f n)) > c \\<longrightarrow> n \\<le> N\" unfolding bdd_above_def by blast\n    hence \"\\<exists>N. \\<forall>n\\<ge>N. root n (norm (f n)) \\<le> c\"\n      by (intro exI[of _ \"N + 1\"]) (force simp: not_less_eq_eq[symmetric])\n    hence \"eventually (\\<lambda>n. root n (norm (f n)) \\<le> c) sequentially\"\n      by (auto simp: eventually_at_top_linorder)\n    hence \"l \\<le> c\" unfolding l_def by (intro Limsup_bounded) simp_all\n    with c show False by auto\n  qed\n  \n  from bounded obtain K where K: \"K > 0\" \"\\<And>n. norm (f n) \\<le> K\" using BseqE by blast\n  def n \\<equiv> \"nat \\<lceil>log c K\\<rceil>\"\n  from unbounded have \"\\<exists>m>n. c < root m (norm (f m))\" unfolding bdd_above_def\n    by (auto simp: not_le)\n  then guess m by (elim exE conjE) note m = this\n  from c K have \"K = c powr log c K\" by (simp add: powr_def log_def)\n  also from c have \"c powr log c K \\<le> c powr real n\" unfolding n_def\n    by (intro powr_mono, linarith, simp)\n  finally have \"K \\<le> c ^ n\" using c by (simp add: powr_realpow)\n  also from c m have \"c ^ n < c ^ m\" by simp\n  also from c m have \"c ^ m < root m (norm (f m)) ^ m\" by (intro power_strict_mono) simp_all\n  also from m have \"... = norm (f m)\" by simp\n  finally show False using K(2)[of m]  by simp\nqed\n\n\nsubsection \\<open>Cauchy's condensation test\\<close>\n\ncontext\nfixes f :: \"nat \\<Rightarrow> real\"\nbegin\n\nprivate lemma condensation_inequality:\n  assumes mono: \"\\<And>m n. 0 < m \\<Longrightarrow> m \\<le> n \\<Longrightarrow> f n \\<le> f m\"\n  shows   \"(\\<Sum>k=1..<n. f k) \\<ge> (\\<Sum>k=1..<n. f (2 * 2 ^ natlog2 k))\" (is \"?thesis1\")\n          \"(\\<Sum>k=1..<n. f k) \\<le> (\\<Sum>k=1..<n. f (2 ^ natlog2 k))\" (is \"?thesis2\")\n  by (intro setsum_mono mono pow_natlog2_ge pow_natlog2_le, simp, simp)+\n\nprivate lemma condensation_condense1: \"(\\<Sum>k=1..<2^n. f (2 ^ natlog2 k)) = (\\<Sum>k<n. 2^k * f (2 ^ k))\"\nproof (induction n)\n  case (Suc n)\n  have \"{1..<2^Suc n} = {1..<2^n} \\<union> {2^n..<(2^Suc n :: nat)}\" by auto  \n  also have \"(\\<Sum>k\\<in>\\<dots>. f (2 ^ natlog2 k)) = \n                 (\\<Sum>k<n. 2^k * f (2^k)) + (\\<Sum>k = 2^n..<2^Suc n. f (2^natlog2 k))\" \n    by (subst setsum.union_disjoint) (insert Suc, auto)\n  also have \"natlog2 k = n\" if \"k \\<in> {2^n..<2^Suc n}\" for k using that by (intro natlog2_eqI) simp_all\n  hence \"(\\<Sum>k = 2^n..<2^Suc n. f (2^natlog2 k)) = (\\<Sum>(_::nat) = 2^n..<2^Suc n. f (2^n))\"\n    by (intro setsum.cong) simp_all\n  also have \"\\<dots> = 2^n * f (2^n)\" by (simp add: of_nat_power)\n  finally show ?case by simp\nqed simp\n\nprivate lemma condensation_condense2: \"(\\<Sum>k=1..<2^n. f (2 * 2 ^ natlog2 k)) = (\\<Sum>k<n. 2^k * f (2 ^ Suc k))\"\nproof (induction n)\n  case (Suc n)\n  have \"{1..<2^Suc n} = {1..<2^n} \\<union> {2^n..<(2^Suc n :: nat)}\" by auto  \n  also have \"(\\<Sum>k\\<in>\\<dots>. f (2 * 2 ^ natlog2 k)) = \n                 (\\<Sum>k<n. 2^k * f (2^Suc k)) + (\\<Sum>k = 2^n..<2^Suc n. f (2 * 2^natlog2 k))\" \n    by (subst setsum.union_disjoint) (insert Suc, auto)\n  also have \"natlog2 k = n\" if \"k \\<in> {2^n..<2^Suc n}\" for k using that by (intro natlog2_eqI) simp_all\n  hence \"(\\<Sum>k = 2^n..<2^Suc n. f (2*2^natlog2 k)) = (\\<Sum>(_::nat) = 2^n..<2^Suc n. f (2^Suc n))\"\n    by (intro setsum.cong) simp_all\n  also have \"\\<dots> = 2^n * f (2^Suc n)\" by (simp add: of_nat_power)\n  finally show ?case by simp\nqed simp\n\nlemma condensation_test:\n  assumes mono: \"\\<And>m. 0 < m \\<Longrightarrow> f (Suc m) \\<le> f m\"\n  assumes nonneg: \"\\<And>n. f n \\<ge> 0\"\n  shows \"summable f \\<longleftrightarrow> summable (\\<lambda>n. 2^n * f (2^n))\"\nproof -\n  def f' \\<equiv> \"\\<lambda>n. if n = 0 then 0 else f n\"\n  from mono have mono': \"decseq (\\<lambda>n. f (Suc n))\" by (intro decseq_SucI) simp\n  hence mono': \"f n \\<le> f m\" if \"m \\<le> n\" \"m > 0\" for m n \n    using that decseqD[OF mono', of \"m - 1\" \"n - 1\"] by simp\n  \n  have \"(\\<lambda>n. f (Suc n)) = (\\<lambda>n. f' (Suc n))\" by (intro ext) (simp add: f'_def)\n  hence \"summable f \\<longleftrightarrow> summable f'\"\n    by (subst (1 2) summable_Suc_iff [symmetric]) (simp only:)\n  also have \"\\<dots> \\<longleftrightarrow> convergent (\\<lambda>n. \\<Sum>k<n. f' k)\" unfolding summable_iff_convergent ..\n  also have \"monoseq (\\<lambda>n. \\<Sum>k<n. f' k)\" unfolding f'_def\n    by (intro mono_SucI1) (auto intro!: mult_nonneg_nonneg nonneg)\n  hence \"convergent (\\<lambda>n. \\<Sum>k<n. f' k) \\<longleftrightarrow> Bseq (\\<lambda>n. \\<Sum>k<n. f' k)\"\n    by (rule monoseq_imp_convergent_iff_Bseq)\n  also have \"\\<dots> \\<longleftrightarrow> Bseq (\\<lambda>n. \\<Sum>k=1..<n. f' k)\" unfolding One_nat_def\n    by (subst setsum_shift_lb_Suc0_0_upt) (simp_all add: f'_def atLeast0LessThan)\n  also have \"\\<dots> \\<longleftrightarrow> Bseq (\\<lambda>n. \\<Sum>k=1..<n. f k)\" unfolding f'_def by simp\n  also have \"\\<dots> \\<longleftrightarrow> Bseq (\\<lambda>n. \\<Sum>k=1..<2^n. f k)\"\n    by (rule nonneg_incseq_Bseq_subseq_iff[symmetric])\n       (auto intro!: setsum_nonneg incseq_SucI nonneg simp: subseq_def)\n  also have \"\\<dots> \\<longleftrightarrow> Bseq (\\<lambda>n. \\<Sum>k<n. 2^k * f (2^k))\"\n  proof (intro iffI)\n    assume A: \"Bseq (\\<lambda>n. \\<Sum>k=1..<2^n. f k)\"\n    have \"eventually (\\<lambda>n. norm (\\<Sum>k<n. 2^k * f (2^Suc k)) \\<le> norm (\\<Sum>k=1..<2^n. f k)) sequentially\"\n    proof (intro always_eventually allI)\n      fix n :: nat\n      have \"norm (\\<Sum>k<n. 2^k * f (2^Suc k)) = (\\<Sum>k<n. 2^k * f (2^Suc k))\" unfolding real_norm_def\n        by (intro abs_of_nonneg setsum_nonneg ballI mult_nonneg_nonneg nonneg) simp_all\n      also have \"\\<dots> \\<le> (\\<Sum>k=1..<2^n. f k)\"\n        by (subst condensation_condense2 [symmetric]) (intro condensation_inequality mono')\n      also have \"\\<dots> = norm \\<dots>\" unfolding real_norm_def\n        by (intro abs_of_nonneg[symmetric] setsum_nonneg ballI mult_nonneg_nonneg nonneg)\n      finally show \"norm (\\<Sum>k<n. 2 ^ k * f (2 ^ Suc k)) \\<le> norm (\\<Sum>k=1..<2^n. f k)\" .\n    qed\n    from this and A have \"Bseq (\\<lambda>n. \\<Sum>k<n. 2^k * f (2^Suc k))\" by (rule Bseq_eventually_mono)\n    from Bseq_mult[OF Bfun_const[of 2] this] have \"Bseq (\\<lambda>n. \\<Sum>k<n. 2^Suc k * f (2^Suc k))\"\n      by (simp add: setsum_right_distrib setsum_left_distrib mult_ac)\n    hence \"Bseq (\\<lambda>n. (\\<Sum>k=Suc 0..<Suc n. 2^k * f (2^k)) + f 1)\"\n      by (intro Bseq_add, subst setsum_shift_bounds_Suc_ivl) (simp add: atLeast0LessThan)\n    hence \"Bseq (\\<lambda>n. (\\<Sum>k=0..<Suc n. 2^k * f (2^k)))\"\n      by (subst setsum_head_upt_Suc) (simp_all add: add_ac)\n    thus \"Bseq (\\<lambda>n. (\\<Sum>k<n. 2^k * f (2^k)))\" \n      by (subst (asm) Bseq_Suc_iff) (simp add: atLeast0LessThan)\n  next\n    assume A: \"Bseq (\\<lambda>n. (\\<Sum>k<n. 2^k * f (2^k)))\"\n    have \"eventually (\\<lambda>n. norm (\\<Sum>k=1..<2^n. f k) \\<le> norm (\\<Sum>k<n. 2^k * f (2^k))) sequentially\"\n    proof (intro always_eventually allI)\n      fix n :: nat\n      have \"norm (\\<Sum>k=1..<2^n. f k) = (\\<Sum>k=1..<2^n. f k)\" unfolding real_norm_def\n        by (intro abs_of_nonneg setsum_nonneg ballI mult_nonneg_nonneg nonneg)\n      also have \"\\<dots> \\<le> (\\<Sum>k<n. 2^k * f (2^k))\"\n        by (subst condensation_condense1 [symmetric]) (intro condensation_inequality mono')\n      also have \"\\<dots> = norm \\<dots>\" unfolding real_norm_def\n        by (intro abs_of_nonneg [symmetric] setsum_nonneg ballI mult_nonneg_nonneg nonneg) simp_all\n      finally show \"norm (\\<Sum>k=1..<2^n. f k) \\<le> norm (\\<Sum>k<n. 2^k * f (2^k))\" .\n    qed\n    from this and A show \"Bseq (\\<lambda>n. \\<Sum>k=1..<2^n. f k)\" by (rule Bseq_eventually_mono)\n  qed\n  also have \"monoseq (\\<lambda>n. (\\<Sum>k<n. 2^k * f (2^k)))\"\n    by (intro mono_SucI1) (auto intro!: mult_nonneg_nonneg nonneg)\n  hence \"Bseq (\\<lambda>n. (\\<Sum>k<n. 2^k * f (2^k))) \\<longleftrightarrow> convergent (\\<lambda>n. (\\<Sum>k<n. 2^k * f (2^k)))\"\n    by (rule monoseq_imp_convergent_iff_Bseq [symmetric])\n  also have \"\\<dots> \\<longleftrightarrow> summable (\\<lambda>k. 2^k * f (2^k))\" by (simp only: summable_iff_convergent)\n  finally show ?thesis .\nqed\n\nend\n\n\nsubsection \\<open>Summability of powers\\<close>\n\nlemma abs_summable_complex_powr_iff: \n    \"summable (\\<lambda>n. norm (exp (of_real (ln (of_nat n)) * s))) \\<longleftrightarrow> Re s < -1\"\nproof (cases \"Re s \\<le> 0\")\n  let ?l = \"\\<lambda>n. complex_of_real (ln (of_nat n))\"\n  case False\n  with eventually_gt_at_top[of \"0::nat\"]\n    have \"eventually (\\<lambda>n. norm (1 :: real) \\<le> norm (exp (?l n * s))) sequentially\" \n    by (auto intro!: ge_one_powr_ge_zero elim!: eventually_mono)\n  from summable_comparison_test_ev[OF this] False show ?thesis by (auto simp: summable_const_iff)\nnext\n  let ?l = \"\\<lambda>n. complex_of_real (ln (of_nat n))\"\n  case True\n  hence \"summable (\\<lambda>n. norm (exp (?l n * s))) \\<longleftrightarrow> summable (\\<lambda>n. 2^n * norm (exp (?l (2^n) * s)))\"\n    by (intro condensation_test) (auto intro!: mult_right_mono_neg)\n  also have \"(\\<lambda>n. 2^n * norm (exp (?l (2^n) * s))) = (\\<lambda>n. (2 powr (Re s + 1)) ^ n)\"\n  proof\n    fix n :: nat\n    have \"2^n * norm (exp (?l (2^n) * s)) = exp (real n * ln 2) * exp (real n * ln 2 * Re s)\"\n      using True by (subst exp_of_nat_mult) (simp add: ln_realpow algebra_simps) \n    also have \"\\<dots> = exp (real n * (ln 2 * (Re s + 1)))\"\n      by (simp add: algebra_simps exp_add)\n    also have \"\\<dots> = exp (ln 2 * (Re s + 1)) ^ n\" by (subst exp_of_nat_mult) simp\n    also have \"exp (ln 2 * (Re s + 1)) = 2 powr (Re s + 1)\" by (simp add: powr_def)\n    finally show \"2^n * norm (exp (?l (2^n) * s)) = (2 powr (Re s + 1)) ^ n\" .\n  qed\n  also have \"summable \\<dots> \\<longleftrightarrow> 2 powr (Re s + 1) < 2 powr 0\"\n    by (subst summable_geometric_iff) simp\n  also have \"\\<dots> \\<longleftrightarrow> Re s < -1\" by (subst powr_less_cancel_iff) (simp, linarith)\n  finally show ?thesis .\nqed\n\nlemma abs_summable_zetalike: \n  assumes \"Re s < -1\" \"Bseq a\"\n  shows   \"summable (\\<lambda>n. norm (a n * exp (complex_of_real (ln (of_nat n)) * s)))\"\nproof -\n  from \\<open>Bseq a\\<close> obtain C where C: \"C > 0\" \"\\<And>n. norm (a n) \\<le> C\" unfolding Bseq_def by blast\n  with assms have A: \"summable (\\<lambda>n. C * norm (exp (of_real (ln (of_nat n)) * s)))\"\n    by (intro summable_mult, subst abs_summable_complex_powr_iff)\n  from C have B: \"norm (norm (a n * exp (of_real (ln (of_nat n)) * s))) \\<le>\n                            C * norm (exp (of_real (ln (of_nat n)) * s))\" for n\n    by (auto simp: norm_mult)\n  from summable_comparison_test'[OF A B] show ?thesis .\nqed\n\nlemma summable_zetalike: \n  assumes \"Re s < -1\" \"Bseq a\"\n  shows   \"summable (\\<lambda>n. a n * exp (complex_of_real (ln (of_nat n)) * s))\"\n  by (rule summable_norm_cancel, rule abs_summable_zetalike) fact+\n\nlemma summable_complex_powr_iff: \n  assumes \"Re s < -1\"\n  shows   \"summable (\\<lambda>n. exp (of_real (ln (of_nat n)) * s))\"\n  by (rule summable_norm_cancel, subst abs_summable_complex_powr_iff) fact\n\nlemma summable_real_powr_iff: \"summable (\\<lambda>n. of_nat n powr s :: real) \\<longleftrightarrow> s < -1\"\nproof -\n  from eventually_gt_at_top[of \"0::nat\"]\n    have \"summable (\\<lambda>n. of_nat n powr s) \\<longleftrightarrow> summable (\\<lambda>n. exp (ln (of_nat n) * s))\"\n    by (intro summable_cong) (auto elim!: eventually_mono simp: powr_def)\n  also have \"\\<dots> \\<longleftrightarrow> s < -1\" using abs_summable_complex_powr_iff[of \"of_real s\"] by simp\n  finally show ?thesis .\nqed\n\nlemma inverse_power_summable:\n  assumes s: \"s \\<ge> 2\"\n  shows \"summable (\\<lambda>n. inverse (of_nat n ^ s :: 'a :: {real_normed_div_algebra,banach}))\"\nproof (rule summable_norm_cancel, subst summable_cong)\n  from eventually_gt_at_top[of \"0::nat\"]\n    show \"eventually (\\<lambda>n. norm (inverse (of_nat n ^ s:: 'a)) = real_of_nat n powr (-real s)) at_top\"\n    by eventually_elim (simp add: norm_inverse norm_power powr_minus powr_realpow)\nqed (insert s summable_real_powr_iff[of \"-s\"], simp_all)\n\nlemma not_summable_harmonic: \"\\<not>summable (\\<lambda>n. inverse (of_nat n) :: 'a :: real_normed_field)\"\nproof\n  assume \"summable (\\<lambda>n. inverse (of_nat n) :: 'a)\"\n  hence \"convergent (\\<lambda>n. norm (of_real (\\<Sum>k<n. inverse (of_nat k)) :: 'a))\" \n    by (simp add: summable_iff_convergent convergent_norm)\n  hence \"convergent (\\<lambda>n. abs (\\<Sum>k<n. inverse (of_nat k)) :: real)\" by (simp only: norm_of_real)\n  also have \"(\\<lambda>n. abs (\\<Sum>k<n. inverse (of_nat k)) :: real) = (\\<lambda>n. \\<Sum>k<n. inverse (of_nat k))\"\n    by (intro ext abs_of_nonneg setsum_nonneg) auto\n  also have \"convergent \\<dots> \\<longleftrightarrow> summable (\\<lambda>k. inverse (of_nat k) :: real)\"\n    by (simp add: summable_iff_convergent)\n  finally show False using summable_real_powr_iff[of \"-1\"] by (simp add: powr_minus)\nqed\n\n\nsubsection \\<open>Kummer's test\\<close>\n\nlemma kummers_test_convergence:\n  fixes f p :: \"nat \\<Rightarrow> real\"\n  assumes pos_f: \"eventually (\\<lambda>n. f n > 0) sequentially\" \n  assumes nonneg_p: \"eventually (\\<lambda>n. p n \\<ge> 0) sequentially\"\n  defines \"l \\<equiv> liminf (\\<lambda>n. ereal (p n * f n / f (Suc n) - p (Suc n)))\"\n  assumes l: \"l > 0\"\n  shows   \"summable f\"\n  unfolding summable_iff_convergent'\nproof -\n  def r \\<equiv> \"(if l = \\<infinity> then 1 else real_of_ereal l / 2)\"\n  from l have \"r > 0 \\<and> of_real r < l\" by (cases l) (simp_all add: r_def)\n  hence r: \"r > 0\" \"of_real r < l\" by simp_all\n  hence \"eventually (\\<lambda>n. p n * f n / f (Suc n) - p (Suc n) > r) sequentially\"\n    unfolding l_def by (force dest: less_LiminfD)\n  moreover from pos_f have \"eventually (\\<lambda>n. f (Suc n) > 0) sequentially\" \n    by (subst eventually_sequentially_Suc)\n  ultimately have \"eventually (\\<lambda>n. p n * f n - p (Suc n) * f (Suc n) > r * f (Suc n)) sequentially\"\n    by eventually_elim (simp add: field_simps)\n  from eventually_conj[OF pos_f eventually_conj[OF nonneg_p this]]\n    obtain m where m: \"\\<And>n. n \\<ge> m \\<Longrightarrow> f n > 0\" \"\\<And>n. n \\<ge> m \\<Longrightarrow> p n \\<ge> 0\"\n        \"\\<And>n. n \\<ge> m \\<Longrightarrow> p n * f n - p (Suc n) * f (Suc n) > r * f (Suc n)\"\n    unfolding eventually_at_top_linorder by blast\n\n  let ?c = \"(norm (\\<Sum>k\\<le>m. r * f k) + p m * f m) / r\"\n  have \"Bseq (\\<lambda>n. (\\<Sum>k\\<le>n + Suc m. f k))\"\n  proof (rule BseqI')\n    fix k :: nat\n    def n \\<equiv> \"k + Suc m\"\n    have n: \"n > m\" by (simp add: n_def)\n\n    from r have \"r * norm (\\<Sum>k\\<le>n. f k) = norm (\\<Sum>k\\<le>n. r * f k)\"\n      by (simp add: setsum_right_distrib[symmetric] abs_mult)\n    also from n have \"{..n} = {..m} \\<union> {Suc m..n}\" by auto\n    hence \"(\\<Sum>k\\<le>n. r * f k) = (\\<Sum>k\\<in>{..m} \\<union> {Suc m..n}. r * f k)\" by (simp only:)\n    also have \"\\<dots> = (\\<Sum>k\\<le>m. r * f k) + (\\<Sum>k=Suc m..n. r * f k)\"\n      by (subst setsum.union_disjoint) auto\n    also have \"norm \\<dots> \\<le> norm (\\<Sum>k\\<le>m. r * f k) + norm (\\<Sum>k=Suc m..n. r * f k)\"\n      by (rule norm_triangle_ineq)\n    also from r less_imp_le[OF m(1)] have \"(\\<Sum>k=Suc m..n. r * f k) \\<ge> 0\" \n      by (intro setsum_nonneg) auto\n    hence \"norm (\\<Sum>k=Suc m..n. r * f k) = (\\<Sum>k=Suc m..n. r * f k)\" by simp\n    also have \"(\\<Sum>k=Suc m..n. r * f k) = (\\<Sum>k=m..<n. r * f (Suc k))\"\n     by (subst setsum_shift_bounds_Suc_ivl [symmetric])\n          (simp only: atLeastLessThanSuc_atLeastAtMost)\n    also from m have \"\\<dots> \\<le> (\\<Sum>k=m..<n. p k * f k - p (Suc k) * f (Suc k))\"\n      by (intro setsum_mono[OF less_imp_le]) simp_all\n    also have \"\\<dots> = -(\\<Sum>k=m..<n. p (Suc k) * f (Suc k) - p k * f k)\"\n      by (simp add: setsum_negf [symmetric] algebra_simps)\n    also from n have \"\\<dots> = p m * f m - p n * f n\"\n      by (cases n, simp, simp only: atLeastLessThanSuc_atLeastAtMost, subst setsum_Suc_diff) simp_all\n    also from less_imp_le[OF m(1)] m(2) n have \"\\<dots> \\<le> p m * f m\" by simp\n    finally show \"norm (\\<Sum>k\\<le>n. f k) \\<le> (norm (\\<Sum>k\\<le>m. r * f k) + p m * f m) / r\" using r\n      by (subst pos_le_divide_eq[OF r(1)]) (simp only: mult_ac)\n  qed\n  moreover have \"(\\<Sum>k\\<le>n. f k) \\<le> (\\<Sum>k\\<le>n'. f k)\" if \"Suc m \\<le> n\" \"n \\<le> n'\" for n n'\n    using less_imp_le[OF m(1)] that by (intro setsum_mono2) auto\n  ultimately show \"convergent (\\<lambda>n. \\<Sum>k\\<le>n. f k)\" by (rule Bseq_monoseq_convergent'_inc)\nqed\n\n\nlemma kummers_test_divergence:\n  fixes f p :: \"nat \\<Rightarrow> real\"\n  assumes pos_f: \"eventually (\\<lambda>n. f n > 0) sequentially\" \n  assumes pos_p: \"eventually (\\<lambda>n. p n > 0) sequentially\"\n  assumes divergent_p: \"\\<not>summable (\\<lambda>n. inverse (p n))\"\n  defines \"l \\<equiv> limsup (\\<lambda>n. ereal (p n * f n / f (Suc n) - p (Suc n)))\"\n  assumes l: \"l < 0\"\n  shows   \"\\<not>summable f\"\nproof\n  assume \"summable f\"\n  from eventually_conj[OF pos_f eventually_conj[OF pos_p gt_LimsupD[OF l[unfolded l_def]]]]\n    obtain N where N: \"\\<And>n. n \\<ge> N \\<Longrightarrow> p n > 0\" \"\\<And>n. n \\<ge> N \\<Longrightarrow> f n > 0\"\n                      \"\\<And>n. n \\<ge> N \\<Longrightarrow> p n * f n / f (Suc n) - p (Suc n) < 0\"\n    by (auto simp: eventually_at_top_linorder)\n  hence A: \"p n * f n < p (Suc n) * f (Suc n)\" if \"n \\<ge> N\" for n using that N[of n] N[of \"Suc n\"] \n    by (simp add: field_simps)\n  have \"p n * f n \\<ge> p N * f N\" if \"n \\<ge> N\" for n using that and A\n      by (induction n rule: dec_induct) (auto intro!: less_imp_le elim!: order.trans)\n  from eventually_ge_at_top[of N] N this\n    have \"eventually (\\<lambda>n. norm (p N * f N * inverse (p n)) \\<le> f n) sequentially\"\n    by (auto elim!: eventually_mono simp: field_simps abs_of_pos)\n  from this and \\<open>summable f\\<close> have \"summable (\\<lambda>n. p N * f N * inverse (p n))\"\n    by (rule summable_comparison_test_ev)\n  from summable_mult[OF this, of \"inverse (p N * f N)\"] N[OF le_refl] \n    have \"summable (\\<lambda>n. inverse (p n))\" by (simp add: divide_simps)\n  with divergent_p show False by contradiction\nqed\n\n\nsubsection \\<open>Ratio test\\<close>\n\nlemma ratio_test_convergence:\n  fixes f :: \"nat \\<Rightarrow> real\"\n  assumes pos_f: \"eventually (\\<lambda>n. f n > 0) sequentially\" \n  defines \"l \\<equiv> liminf (\\<lambda>n. ereal (f n / f (Suc n)))\"\n  assumes l: \"l > 1\"\n  shows   \"summable f\"\nproof (rule kummers_test_convergence[OF pos_f])\n  note l\n  also have \"l = liminf (\\<lambda>n. ereal (f n / f (Suc n) - 1)) + 1\" \n    by (subst Liminf_add_ereal_right[symmetric]) (simp_all add: minus_ereal_def l_def one_ereal_def)\n  finally show \"liminf (\\<lambda>n. ereal (1 * f n / f (Suc n) - 1)) > 0\"\n    by (cases \"liminf (\\<lambda>n. ereal (1 * f n / f (Suc n) - 1))\") simp_all\nqed simp\n\nlemma ratio_test_divergence:\n  fixes f :: \"nat \\<Rightarrow> real\"\n  assumes pos_f: \"eventually (\\<lambda>n. f n > 0) sequentially\" \n  defines \"l \\<equiv> limsup (\\<lambda>n. ereal (f n / f (Suc n)))\"\n  assumes l: \"l < 1\"\n  shows   \"\\<not>summable f\"\nproof (rule kummers_test_divergence[OF pos_f])\n  have \"limsup (\\<lambda>n. ereal (f n / f (Suc n) - 1)) + 1 = l\" \n    by (subst Limsup_add_ereal_right[symmetric]) (simp_all add: minus_ereal_def l_def one_ereal_def)\n  also note l\n  finally show \"limsup (\\<lambda>n. ereal (1 * f n / f (Suc n) - 1)) < 0\"\n    by (cases \"limsup (\\<lambda>n. ereal (1 * f n / f (Suc n) - 1))\") simp_all\nqed (simp_all add: summable_const_iff)\n\n\nsubsection \\<open>Raabe's test\\<close>\n\nlemma raabes_test_convergence:\nfixes f :: \"nat \\<Rightarrow> real\"\n  assumes pos: \"eventually (\\<lambda>n. f n > 0) sequentially\"\n  defines \"l \\<equiv> liminf (\\<lambda>n. ereal (of_nat n * (f n / f (Suc n) - 1)))\"\n  assumes l: \"l > 1\"\n  shows   \"summable f\"\nproof (rule kummers_test_convergence)\n  let ?l' = \"liminf (\\<lambda>n. ereal (of_nat n * f n / f (Suc n) - of_nat (Suc n)))\"\n  have \"1 < l\" by fact\n  also have \"l = liminf (\\<lambda>n. ereal (of_nat n * f n / f (Suc n) - of_nat (Suc n)) + 1)\"\n    by (simp add: l_def algebra_simps)\n  also have \"\\<dots> = ?l' + 1\" by (subst Liminf_add_ereal_right) simp_all\n  finally show \"?l' > 0\" by (cases ?l') (simp_all add: algebra_simps)\nqed (simp_all add: pos)\n\nlemma raabes_test_divergence:\nfixes f :: \"nat \\<Rightarrow> real\"\n  assumes pos: \"eventually (\\<lambda>n. f n > 0) sequentially\"\n  defines \"l \\<equiv> limsup (\\<lambda>n. ereal (of_nat n * (f n / f (Suc n) - 1)))\"\n  assumes l: \"l < 1\"\n  shows   \"\\<not>summable f\"\nproof (rule kummers_test_divergence)\n  let ?l' = \"limsup (\\<lambda>n. ereal (of_nat n * f n / f (Suc n) - of_nat (Suc n)))\"\n  note l\n  also have \"l = limsup (\\<lambda>n. ereal (of_nat n * f n / f (Suc n) - of_nat (Suc n)) + 1)\"\n    by (simp add: l_def algebra_simps)\n  also have \"\\<dots> = ?l' + 1\" by (subst Limsup_add_ereal_right) simp_all\n  finally show \"?l' < 0\" by (cases ?l') (simp_all add: algebra_simps)\nqed (insert pos eventually_gt_at_top[of \"0::nat\"] not_summable_harmonic, simp_all)\n\n\n\nsubsection \\<open>Radius of convergence\\<close>\n\ntext \\<open>\n  The radius of convergence of a power series. This value always exists, ranges from\n  @{term \"0::ereal\"} to @{term \"\\<infinity>::ereal\"}, and the power series is guaranteed to converge for \n  all inputs with a norm that is smaller than that radius and to diverge for all inputs with a\n  norm that is greater. \n\\<close>\ndefinition conv_radius :: \"(nat \\<Rightarrow> 'a :: banach) \\<Rightarrow> ereal\" where\n  \"conv_radius f = inverse (limsup (\\<lambda>n. ereal (root n (norm (f n)))))\"\n\nlemma conv_radius_nonneg: \"conv_radius f \\<ge> 0\"\nproof -\n  have \"0 = limsup (\\<lambda>n. 0)\" by (subst Limsup_const) simp_all\n  also have \"\\<dots> \\<le> limsup (\\<lambda>n. ereal (root n (norm (f n))))\"\n    by (intro Limsup_mono) (simp_all add: real_root_ge_zero)\n  finally show ?thesis\n    unfolding conv_radius_def by (auto simp: ereal_inverse_nonneg_iff)\nqed\n\nlemma conv_radius_zero [simp]: \"conv_radius (\\<lambda>_. 0) = \\<infinity>\"\n  by (auto simp: conv_radius_def zero_ereal_def [symmetric] Limsup_const)\n\nlemma conv_radius_cong:\n  assumes \"eventually (\\<lambda>x. f x = g x) sequentially\"\n  shows   \"conv_radius f = conv_radius g\"\nproof -\n  have \"eventually (\\<lambda>n. ereal (root n (norm (f n))) = ereal (root n (norm (g n)))) sequentially\"\n    using assms by eventually_elim simp\n  from Limsup_eq[OF this] show ?thesis unfolding conv_radius_def by simp\nqed\n\nlemma conv_radius_altdef:\n  \"conv_radius f = liminf (\\<lambda>n. inverse (ereal (root n (norm (f n)))))\"\n  by (subst Liminf_inverse_ereal) (simp_all add: real_root_ge_zero conv_radius_def)\n\n\nlemma abs_summable_in_conv_radius:\n  fixes f :: \"nat \\<Rightarrow> 'a :: {banach, real_normed_div_algebra}\"\n  assumes \"ereal (norm z) < conv_radius f\"\n  shows   \"summable (\\<lambda>n. norm (f n * z ^ n))\"\nproof (rule root_test_convergence')\n  def l \\<equiv> \"limsup (\\<lambda>n. ereal (root n (norm (f n))))\"\n  have \"0 = limsup (\\<lambda>n. 0)\" by (simp add: Limsup_const)\n  also have \"... \\<le> l\" unfolding l_def by (intro Limsup_mono) (simp_all add: real_root_ge_zero)\n  finally have l_nonneg: \"l \\<ge> 0\" .\n\n  have \"limsup (\\<lambda>n. root n (norm (f n * z^n))) = l * ereal (norm z)\" unfolding l_def\n    by (rule limsup_root_powser)\n  also from l_nonneg consider \"l = 0\" | \"l = \\<infinity>\" | \"\\<exists>l'. l = ereal l' \\<and> l' > 0\"\n    by (cases \"l\") (auto simp: less_le)\n  hence \"l * ereal (norm z) < 1\"\n  proof cases\n    assume \"l = \\<infinity>\"\n    hence \"conv_radius f = 0\" unfolding conv_radius_def l_def by simp\n    with assms show ?thesis by simp\n  next\n    assume \"\\<exists>l'. l = ereal l' \\<and> l' > 0\"\n    then guess l' by (elim exE conjE) note l' = this\n    hence \"l \\<noteq> \\<infinity>\" by auto\n    have \"l * ereal (norm z) < l * conv_radius f\"\n      by (intro ereal_mult_strict_left_mono) (simp_all add: l' assms)\n    also have \"conv_radius f = inverse l\" by (simp add: conv_radius_def l_def)\n    also from l' have \"l * inverse l = 1\" by simp\n    finally show ?thesis .\n  qed simp_all\n  finally show \"limsup (\\<lambda>n. ereal (root n (norm (norm (f n * z ^ n))))) < 1\" by simp\nqed\n\nlemma summable_in_conv_radius:\n  fixes f :: \"nat \\<Rightarrow> 'a :: {banach, real_normed_div_algebra}\"\n  assumes \"ereal (norm z) < conv_radius f\"\n  shows   \"summable (\\<lambda>n. f n * z ^ n)\"\n  by (rule summable_norm_cancel, rule abs_summable_in_conv_radius) fact+\n\nlemma not_summable_outside_conv_radius:\n  fixes f :: \"nat \\<Rightarrow> 'a :: {banach, real_normed_div_algebra}\"\n  assumes \"ereal (norm z) > conv_radius f\"\n  shows   \"\\<not>summable (\\<lambda>n. f n * z ^ n)\"\nproof (rule root_test_divergence)\n  def l \\<equiv> \"limsup (\\<lambda>n. ereal (root n (norm (f n))))\"\n  have \"0 = limsup (\\<lambda>n. 0)\" by (simp add: Limsup_const)\n  also have \"... \\<le> l\" unfolding l_def by (intro Limsup_mono) (simp_all add: real_root_ge_zero)\n  finally have l_nonneg: \"l \\<ge> 0\" .\n  from assms have l_nz: \"l \\<noteq> 0\" unfolding conv_radius_def l_def by auto\n\n  have \"limsup (\\<lambda>n. ereal (root n (norm (f n * z^n)))) = l * ereal (norm z)\"\n    unfolding l_def by (rule limsup_root_powser)\n  also have \"... > 1\"\n  proof (cases l)\n    assume \"l = \\<infinity>\"\n    with assms conv_radius_nonneg[of f] show ?thesis\n      by (auto simp: zero_ereal_def[symmetric])\n  next\n    fix l' assume l': \"l = ereal l'\"\n    from l_nonneg l_nz have \"1 = l * inverse l\" by (auto simp: l' field_simps)\n    also from l_nz have \"inverse l = conv_radius f\" \n      unfolding l_def conv_radius_def by auto\n    also from l' l_nz l_nonneg assms have \"l * \\<dots> < l * ereal (norm z)\"\n      by (intro ereal_mult_strict_left_mono) (auto simp: l')\n    finally show ?thesis .\n  qed (insert l_nonneg, simp_all)\n  finally show \"limsup (\\<lambda>n. ereal (root n (norm (f n * z^n)))) > 1\" .\nqed\n\n\nlemma conv_radius_geI:\n  assumes \"summable (\\<lambda>n. f n * z ^ n :: 'a :: {banach, real_normed_div_algebra})\"\n  shows   \"conv_radius f \\<ge> norm z\"\n  using not_summable_outside_conv_radius[of f z] assms by (force simp: not_le[symmetric])\n\nlemma conv_radius_leI:\n  assumes \"\\<not>summable (\\<lambda>n. norm (f n * z ^ n :: 'a :: {banach, real_normed_div_algebra}))\"\n  shows   \"conv_radius f \\<le> norm z\"\n  using abs_summable_in_conv_radius[of z f] assms by (force simp: not_le[symmetric])\n\nlemma conv_radius_leI':\n  assumes \"\\<not>summable (\\<lambda>n. f n * z ^ n :: 'a :: {banach, real_normed_div_algebra})\"\n  shows   \"conv_radius f \\<le> norm z\"\n  using summable_in_conv_radius[of z f] assms by (force simp: not_le[symmetric])\n\nlemma conv_radius_geI_ex:\n  fixes f :: \"nat \\<Rightarrow> 'a :: {banach, real_normed_div_algebra}\"\n  assumes \"\\<And>r. 0 < r \\<Longrightarrow> ereal r < R \\<Longrightarrow> \\<exists>z. norm z = r \\<and> summable (\\<lambda>n. f n * z^n)\"\n  shows   \"conv_radius f \\<ge> R\"\nproof (rule linorder_cases[of \"conv_radius f\" R])\n  assume R: \"conv_radius f < R\"\n  with conv_radius_nonneg[of f] obtain conv_radius' \n    where [simp]: \"conv_radius f = ereal conv_radius'\"\n    by (cases \"conv_radius f\") simp_all\n  def r \\<equiv> \"if R = \\<infinity> then conv_radius' + 1 else (real_of_ereal R + conv_radius') / 2\"\n  from R conv_radius_nonneg[of f] have \"0 < r \\<and> ereal r < R \\<and> ereal r > conv_radius f\" \n    unfolding r_def by (cases R) (auto simp: r_def field_simps)\n  with assms(1)[of r] obtain z where \"norm z > conv_radius f\" \"summable (\\<lambda>n. f n * z^n)\" by auto\n  with not_summable_outside_conv_radius[of f z] show ?thesis by simp\nqed simp_all\n\nlemma conv_radius_geI_ex':\n  fixes f :: \"nat \\<Rightarrow> 'a :: {banach, real_normed_div_algebra}\"\n  assumes \"\\<And>r. 0 < r \\<Longrightarrow> ereal r < R \\<Longrightarrow> summable (\\<lambda>n. f n * of_real r^n)\"\n  shows   \"conv_radius f \\<ge> R\"\nproof (rule conv_radius_geI_ex)\n  fix r assume \"0 < r\" \"ereal r < R\"\n  with assms[of r] show \"\\<exists>z. norm z = r \\<and> summable (\\<lambda>n. f n * z ^ n)\"\n    by (intro exI[of _ \"of_real r :: 'a\"]) auto\nqed\n\nlemma conv_radius_leI_ex:\n  fixes f :: \"nat \\<Rightarrow> 'a :: {banach, real_normed_div_algebra}\"\n  assumes \"R \\<ge> 0\"\n  assumes \"\\<And>r. 0 < r \\<Longrightarrow> ereal r > R \\<Longrightarrow> \\<exists>z. norm z = r \\<and> \\<not>summable (\\<lambda>n. norm (f n * z^n))\"\n  shows   \"conv_radius f \\<le> R\"\nproof (rule linorder_cases[of \"conv_radius f\" R])\n  assume R: \"conv_radius f > R\"\n  from R assms(1) obtain R' where R': \"R = ereal R'\" by (cases R) simp_all\n  def r \\<equiv> \"if conv_radius f = \\<infinity> then R' + 1 else (R' + real_of_ereal (conv_radius f)) / 2\"\n  from R conv_radius_nonneg[of f] have \"r > R \\<and> r < conv_radius f\" unfolding r_def\n    by (cases \"conv_radius f\") (auto simp: r_def field_simps R')\n  with assms(1) assms(2)[of r] R' \n    obtain z where \"norm z < conv_radius f\" \"\\<not>summable (\\<lambda>n. norm (f n * z^n))\" by auto\n  with abs_summable_in_conv_radius[of z f] show ?thesis by auto\nqed simp_all\n\nlemma conv_radius_leI_ex':\n  fixes f :: \"nat \\<Rightarrow> 'a :: {banach, real_normed_div_algebra}\"\n  assumes \"R \\<ge> 0\"\n  assumes \"\\<And>r. 0 < r \\<Longrightarrow> ereal r > R \\<Longrightarrow> \\<not>summable (\\<lambda>n. f n * of_real r^n)\"\n  shows   \"conv_radius f \\<le> R\"\nproof (rule conv_radius_leI_ex)\n  fix r assume \"0 < r\" \"ereal r > R\"\n  with assms(2)[of r] show \"\\<exists>z. norm z = r \\<and> \\<not>summable (\\<lambda>n. norm (f n * z ^ n))\"\n    by (intro exI[of _ \"of_real r :: 'a\"]) (auto dest: summable_norm_cancel)\nqed fact+\n\nlemma conv_radius_eqI:\n  fixes f :: \"nat \\<Rightarrow> 'a :: {banach, real_normed_div_algebra}\"\n  assumes \"R \\<ge> 0\"\n  assumes \"\\<And>r. 0 < r \\<Longrightarrow> ereal r < R \\<Longrightarrow> \\<exists>z. norm z = r \\<and> summable (\\<lambda>n. f n * z^n)\"\n  assumes \"\\<And>r. 0 < r \\<Longrightarrow> ereal r > R \\<Longrightarrow> \\<exists>z. norm z = r \\<and> \\<not>summable (\\<lambda>n. norm (f n * z^n))\"\n  shows   \"conv_radius f = R\"\n  by (intro antisym conv_radius_geI_ex conv_radius_leI_ex assms)\n\nlemma conv_radius_eqI':\n  fixes f :: \"nat \\<Rightarrow> 'a :: {banach, real_normed_div_algebra}\"\n  assumes \"R \\<ge> 0\"\n  assumes \"\\<And>r. 0 < r \\<Longrightarrow> ereal r < R \\<Longrightarrow> summable (\\<lambda>n. f n * (of_real r)^n)\"\n  assumes \"\\<And>r. 0 < r \\<Longrightarrow> ereal r > R \\<Longrightarrow> \\<not>summable (\\<lambda>n. norm (f n * (of_real r)^n))\"\n  shows   \"conv_radius f = R\"\nproof (intro conv_radius_eqI[OF assms(1)])\n  fix r assume \"0 < r\" \"ereal r < R\" with assms(2)[OF this] \n    show \"\\<exists>z. norm z = r \\<and> summable (\\<lambda>n. f n * z ^ n)\" by force\nnext\n  fix r assume \"0 < r\" \"ereal r > R\" with assms(3)[OF this] \n    show \"\\<exists>z. norm z = r \\<and> \\<not>summable (\\<lambda>n. norm (f n * z ^ n))\" by force  \nqed\n\nlemma conv_radius_zeroI:\n  fixes f :: \"nat \\<Rightarrow> 'a :: {banach,real_normed_div_algebra}\"\n  assumes \"\\<And>z. z \\<noteq> 0 \\<Longrightarrow> \\<not>summable (\\<lambda>n. f n * z^n)\"\n  shows   \"conv_radius f = 0\"\nproof (rule ccontr)\n  assume \"conv_radius f \\<noteq> 0\"\n  with conv_radius_nonneg[of f] have pos: \"conv_radius f > 0\" by simp\n  def r \\<equiv> \"if conv_radius f = \\<infinity> then 1 else real_of_ereal (conv_radius f) / 2\"\n  from pos have r: \"ereal r > 0 \\<and> ereal r < conv_radius f\" \n    by (cases \"conv_radius f\") (simp_all add: r_def)\n  hence \"summable (\\<lambda>n. f n * of_real r ^ n)\" by (intro summable_in_conv_radius) simp\n  moreover from r and assms[of \"of_real r\"] have \"\\<not>summable (\\<lambda>n. f n * of_real r ^ n)\" by simp\n  ultimately show False by contradiction\nqed\n\nlemma conv_radius_inftyI':\n  fixes f :: \"nat \\<Rightarrow> 'a :: {banach,real_normed_div_algebra}\"\n  assumes \"\\<And>r. r > c \\<Longrightarrow> \\<exists>z. norm z = r \\<and> summable (\\<lambda>n. f n * z^n)\"\n  shows   \"conv_radius f = \\<infinity>\"\nproof -\n  {\n    fix r :: real\n    have \"max r (c + 1) > c\" by (auto simp: max_def)\n    from assms[OF this] obtain z where \"norm z = max r (c + 1)\" \"summable (\\<lambda>n. f n * z^n)\" by blast\n    from conv_radius_geI[OF this(2)] this(1) have \"conv_radius f \\<ge> r\" by simp\n  }\n  from this[of \"real_of_ereal (conv_radius f + 1)\"] show \"conv_radius f = \\<infinity>\"\n    by (cases \"conv_radius f\") simp_all\nqed\n\nlemma conv_radius_inftyI:\n  fixes f :: \"nat \\<Rightarrow> 'a :: {banach,real_normed_div_algebra}\"\n  assumes \"\\<And>r. \\<exists>z. norm z = r \\<and> summable (\\<lambda>n. f n * z^n)\"\n  shows   \"conv_radius f = \\<infinity>\"\n  using assms by (rule conv_radius_inftyI')\n\nlemma conv_radius_inftyI'':\n  fixes f :: \"nat \\<Rightarrow> 'a :: {banach,real_normed_div_algebra}\"\n  assumes \"\\<And>z. summable (\\<lambda>n. f n * z^n)\"\n  shows   \"conv_radius f = \\<infinity>\"\nproof (rule conv_radius_inftyI')\n  fix r :: real assume \"r > 0\"\n  with assms show \"\\<exists>z. norm z = r \\<and> summable (\\<lambda>n. f n * z^n)\"\n    by (intro exI[of _ \"of_real r\"]) simp\nqed\n\nlemma conv_radius_ratio_limit_ereal:\n  fixes f :: \"nat \\<Rightarrow> 'a :: {banach,real_normed_div_algebra}\"\n  assumes nz:  \"eventually (\\<lambda>n. f n \\<noteq> 0) sequentially\"\n  assumes lim: \"(\\<lambda>n. ereal (norm (f n) / norm (f (Suc n)))) ----> c\"\n  shows   \"conv_radius f = c\"\nproof (rule conv_radius_eqI')\n  show \"c \\<ge> 0\" by (intro Lim_bounded2_ereal[OF lim]) simp_all\nnext\n  fix r assume r: \"0 < r\" \"ereal r < c\"\n  let ?l = \"liminf (\\<lambda>n. ereal (norm (f n * of_real r ^ n) / norm (f (Suc n) * of_real r ^ Suc n)))\"\n  have \"?l = liminf (\\<lambda>n. ereal (norm (f n) / (norm (f (Suc n)))) * ereal (inverse r))\"\n    using r by (simp add: norm_mult norm_power divide_simps)\n  also from r have \"\\<dots> = liminf (\\<lambda>n. ereal (norm (f n) / (norm (f (Suc n))))) * ereal (inverse r)\"\n    by (intro Liminf_ereal_mult_right) simp_all\n  also have \"liminf (\\<lambda>n. ereal (norm (f n) / (norm (f (Suc n))))) = c\"\n    by (intro lim_imp_Liminf lim) simp\n  finally have l: \"?l = c * ereal (inverse r)\" by simp\n  from r have  l': \"c * ereal (inverse r) > 1\" by (cases c) (simp_all add: field_simps)\n  show \"summable (\\<lambda>n. f n * of_real r^n)\"\n    by (rule summable_norm_cancel, rule ratio_test_convergence)\n       (insert r nz l l', auto elim!: eventually_mono)\nnext\n  fix r assume r: \"0 < r\" \"ereal r > c\"\n  let ?l = \"limsup (\\<lambda>n. ereal (norm (f n * of_real r ^ n) / norm (f (Suc n) * of_real r ^ Suc n)))\"\n  have \"?l = limsup (\\<lambda>n. ereal (norm (f n) / (norm (f (Suc n)))) * ereal (inverse r))\"\n    using r by (simp add: norm_mult norm_power divide_simps)\n  also from r have \"\\<dots> = limsup (\\<lambda>n. ereal (norm (f n) / (norm (f (Suc n))))) * ereal (inverse r)\"\n    by (intro Limsup_ereal_mult_right) simp_all\n  also have \"limsup (\\<lambda>n. ereal (norm (f n) / (norm (f (Suc n))))) = c\"\n    by (intro lim_imp_Limsup lim) simp\n  finally have l: \"?l = c * ereal (inverse r)\" by simp\n  from r have  l': \"c * ereal (inverse r) < 1\" by (cases c) (simp_all add: field_simps)\n  show \"\\<not>summable (\\<lambda>n. norm (f n * of_real r^n))\"\n    by (rule ratio_test_divergence) (insert r nz l l', auto elim!: eventually_mono)\nqed\n\nlemma conv_radius_ratio_limit_ereal_nonzero:\n  fixes f :: \"nat \\<Rightarrow> 'a :: {banach,real_normed_div_algebra}\"\n  assumes nz:  \"c \\<noteq> 0\"\n  assumes lim: \"(\\<lambda>n. ereal (norm (f n) / norm (f (Suc n)))) ----> c\"\n  shows   \"conv_radius f = c\"\nproof (rule conv_radius_ratio_limit_ereal[OF _ lim], rule ccontr)\n  assume \"\\<not>eventually (\\<lambda>n. f n \\<noteq> 0) sequentially\"\n  hence \"frequently (\\<lambda>n. f n = 0) sequentially\" by (simp add: frequently_def)\n  hence \"frequently (\\<lambda>n. ereal (norm (f n) / norm (f (Suc n))) = 0) sequentially\"\n    by (force elim!: frequently_elim1)\n  hence \"c = 0\" by (intro limit_frequently_eq[OF _ _ lim]) auto\n  with nz show False by contradiction\nqed \n\nlemma conv_radius_ratio_limit:\n  fixes f :: \"nat \\<Rightarrow> 'a :: {banach,real_normed_div_algebra}\"\n  assumes \"c' = ereal c\"\n  assumes nz:  \"eventually (\\<lambda>n. f n \\<noteq> 0) sequentially\"\n  assumes lim: \"(\\<lambda>n. norm (f n) / norm (f (Suc n))) ----> c\"\n  shows   \"conv_radius f = c'\"\n  using assms by (intro conv_radius_ratio_limit_ereal) simp_all\n  \nlemma conv_radius_ratio_limit_nonzero:\n  fixes f :: \"nat \\<Rightarrow> 'a :: {banach,real_normed_div_algebra}\"\n  assumes \"c' = ereal c\"\n  assumes nz:  \"c \\<noteq> 0\"\n  assumes lim: \"(\\<lambda>n. norm (f n) / norm (f (Suc n))) ----> c\"\n  shows   \"conv_radius f = c'\"\n  using assms by (intro conv_radius_ratio_limit_ereal_nonzero) simp_all\n\nlemma conv_radius_mult_power: \n  assumes \"c \\<noteq> (0 :: 'a :: {real_normed_div_algebra,banach})\"\n  shows   \"conv_radius (\\<lambda>n. c ^ n * f n) = conv_radius f / ereal (norm c)\"\nproof - \n  have \"limsup (\\<lambda>n. ereal (root n (norm (c ^ n * f n)))) =\n          limsup (\\<lambda>n. ereal (norm c) * ereal (root n (norm (f n))))\" \n    using eventually_gt_at_top[of \"0::nat\"]\n    by (intro Limsup_eq) \n       (auto elim!: eventually_mono simp: norm_mult norm_power real_root_mult real_root_power)\n  also have \"\\<dots> = ereal (norm c) * limsup (\\<lambda>n. ereal (root n (norm (f n))))\"\n    using assms by (subst Limsup_ereal_mult_left[symmetric]) simp_all\n  finally have A: \"limsup (\\<lambda>n. ereal (root n (norm (c ^ n * f n)))) = \n                       ereal (norm c) * limsup (\\<lambda>n. ereal (root n (norm (f n))))\" .\n  show ?thesis using assms\n    apply (cases \"limsup (\\<lambda>n. ereal (root n (norm (f n)))) = 0\")\n    apply (simp add: A conv_radius_def)\n    apply (unfold conv_radius_def A divide_ereal_def, simp add: mult.commute ereal_inverse_mult)\n    done\nqed\n\nlemma conv_radius_mult_power_right: \n  assumes \"c \\<noteq> (0 :: 'a :: {real_normed_div_algebra,banach})\"\n  shows   \"conv_radius (\\<lambda>n. f n * c ^ n) = conv_radius f / ereal (norm c)\"\n  using conv_radius_mult_power[OF assms, of f]\n  unfolding conv_radius_def by (simp add: mult.commute norm_mult)\n\nlemma conv_radius_divide_power: \n  assumes \"c \\<noteq> (0 :: 'a :: {real_normed_div_algebra,banach})\"\n  shows   \"conv_radius (\\<lambda>n. f n / c^n) = conv_radius f * ereal (norm c)\"\nproof - \n  from assms have \"inverse c \\<noteq> 0\" by simp\n  from conv_radius_mult_power_right[OF this, of f] show ?thesis\n    by (simp add: divide_inverse divide_ereal_def assms norm_inverse power_inverse)\nqed\n\n\nlemma conv_radius_add_ge: \n  \"min (conv_radius f) (conv_radius g) \\<le> \n       conv_radius (\\<lambda>x. f x + g x :: 'a :: {banach,real_normed_div_algebra})\"\n  by (rule conv_radius_geI_ex')\n     (auto simp: algebra_simps intro!: summable_add summable_in_conv_radius)\n\nlemma summable_Cauchy_product:\n  assumes \"summable (\\<lambda>k. norm (a k :: 'a :: {real_normed_algebra,banach}))\" \n          \"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(* TODO: Move *)\nlemma scaleR_power: \n  fixes y :: \"'a :: real_normed_algebra_1\"\n  shows \"(scaleR x y) ^ n = scaleR (x^n) (y^n)\"\n  by (induction n) simp_all\n\nlemma conv_radius_mult_ge:\n  fixes f g :: \"nat \\<Rightarrow> ('a :: {banach,real_normed_div_algebra})\"\n  shows \"conv_radius (\\<lambda>x. \\<Sum>i\\<le>x. f i * g (x - i)) \\<ge> min (conv_radius f) (conv_radius g)\"\nproof (rule conv_radius_geI_ex')\n  fix r assume r: \"r > 0\" \"ereal r < min (conv_radius f) (conv_radius g)\"\n  from r have \"summable (\\<lambda>n. (\\<Sum>i\\<le>n. (f i * of_real r^i) * (g (n - i) * of_real r^(n - i))))\"\n    by (intro summable_Cauchy_product abs_summable_in_conv_radius) simp_all\n  thus \"summable (\\<lambda>n. (\\<Sum>i\\<le>n. f i * g (n - i)) * of_real r ^ n)\"\n    by (simp add: algebra_simps of_real_def scaleR_power power_add [symmetric] scaleR_setsum_right)\nqed\n\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/Summation.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8670357529306639, "lm_q2_score": 0.8376199714402813, "lm_q1q2_score": 0.7262464626074855}}
{"text": "(*  Title:      HOL/Library/Liminf_Limsup.thy\n    Author:     Johannes H\u00f6lzl, TU M\u00fcnchen\n*)\n\nsection {* Liminf and Limsup on complete lattices *}\n\ntheory Liminf_Limsup\nimports Complex_Main\nbegin\n\nlemma le_Sup_iff_less:\n  fixes x :: \"'a :: {complete_linorder, dense_linorder}\"\n  shows \"x \\<le> (SUP i:A. f i) \\<longleftrightarrow> (\\<forall>y<x. \\<exists>i\\<in>A. y \\<le> f i)\" (is \"?lhs = ?rhs\")\n  unfolding le_SUP_iff\n  by (blast intro: less_imp_le less_trans less_le_trans dest: dense)\n\nlemma Inf_le_iff_less:\n  fixes x :: \"'a :: {complete_linorder, dense_linorder}\"\n  shows \"(INF i:A. f i) \\<le> x \\<longleftrightarrow> (\\<forall>y>x. \\<exists>i\\<in>A. f i \\<le> y)\"\n  unfolding INF_le_iff\n  by (blast intro: less_imp_le less_trans le_less_trans dest: dense)\n\nlemma SUP_pair:\n  fixes f :: \"_ \\<Rightarrow> _ \\<Rightarrow> _ :: complete_lattice\"\n  shows \"(SUP i : A. SUP j : B. f i j) = (SUP p : A \\<times> B. f (fst p) (snd p))\"\n  by (rule antisym) (auto intro!: SUP_least SUP_upper2)\n\nlemma INF_pair:\n  fixes f :: \"_ \\<Rightarrow> _ \\<Rightarrow> _ :: complete_lattice\"\n  shows \"(INF i : A. INF j : B. f i j) = (INF p : A \\<times> B. f (fst p) (snd p))\"\n  by (rule antisym) (auto intro!: INF_greatest INF_lower2)\n\nsubsubsection {* @{text Liminf} and @{text Limsup} *}\n\ndefinition Liminf :: \"'a filter \\<Rightarrow> ('a \\<Rightarrow> 'b) \\<Rightarrow> 'b :: complete_lattice\" where\n  \"Liminf F f = (SUP P:{P. eventually P F}. INF x:{x. P x}. f x)\"\n\ndefinition Limsup :: \"'a filter \\<Rightarrow> ('a \\<Rightarrow> 'b) \\<Rightarrow> 'b :: complete_lattice\" where\n  \"Limsup F f = (INF P:{P. eventually P F}. SUP x:{x. P x}. f x)\"\n\nabbreviation \"liminf \\<equiv> Liminf sequentially\"\n\nabbreviation \"limsup \\<equiv> Limsup sequentially\"\n\nlemma Liminf_eqI:\n  \"(\\<And>P. eventually P F \\<Longrightarrow> INFIMUM (Collect P) f \\<le> x) \\<Longrightarrow>  \n    (\\<And>y. (\\<And>P. eventually P F \\<Longrightarrow> INFIMUM (Collect P) f \\<le> y) \\<Longrightarrow> x \\<le> y) \\<Longrightarrow> Liminf F f = x\"\n  unfolding Liminf_def by (auto intro!: SUP_eqI)\n\nlemma Limsup_eqI:\n  \"(\\<And>P. eventually P F \\<Longrightarrow> x \\<le> SUPREMUM (Collect P) f) \\<Longrightarrow>  \n    (\\<And>y. (\\<And>P. eventually P F \\<Longrightarrow> y \\<le> SUPREMUM (Collect P) f) \\<Longrightarrow> y \\<le> x) \\<Longrightarrow> Limsup F f = x\"\n  unfolding Limsup_def by (auto intro!: INF_eqI)\n\nlemma liminf_SUP_INF: \"liminf f = (SUP n. INF m:{n..}. f m)\"\n  unfolding Liminf_def eventually_sequentially\n  by (rule SUP_eq) (auto simp: atLeast_def intro!: INF_mono)\n\nlemma limsup_INF_SUP: \"limsup f = (INF n. SUP m:{n..}. f m)\"\n  unfolding Limsup_def eventually_sequentially\n  by (rule INF_eq) (auto simp: atLeast_def intro!: SUP_mono)\n\nlemma Limsup_const: \n  assumes ntriv: \"\\<not> trivial_limit F\"\n  shows \"Limsup F (\\<lambda>x. c) = c\"\nproof -\n  have *: \"\\<And>P. Ex P \\<longleftrightarrow> P \\<noteq> (\\<lambda>x. False)\" by auto\n  have \"\\<And>P. eventually P F \\<Longrightarrow> (SUP x : {x. P x}. c) = c\"\n    using ntriv by (intro SUP_const) (auto simp: eventually_False *)\n  then show ?thesis\n    unfolding Limsup_def using eventually_True\n    by (subst INF_cong[where D=\"\\<lambda>x. c\"])\n       (auto intro!: INF_const simp del: eventually_True)\nqed\n\nlemma Liminf_const:\n  assumes ntriv: \"\\<not> trivial_limit F\"\n  shows \"Liminf F (\\<lambda>x. c) = c\"\nproof -\n  have *: \"\\<And>P. Ex P \\<longleftrightarrow> P \\<noteq> (\\<lambda>x. False)\" by auto\n  have \"\\<And>P. eventually P F \\<Longrightarrow> (INF x : {x. P x}. c) = c\"\n    using ntriv by (intro INF_const) (auto simp: eventually_False *)\n  then show ?thesis\n    unfolding Liminf_def using eventually_True\n    by (subst SUP_cong[where D=\"\\<lambda>x. c\"])\n       (auto intro!: SUP_const simp del: eventually_True)\nqed\n\nlemma Liminf_mono:\n  assumes ev: \"eventually (\\<lambda>x. f x \\<le> g x) F\"\n  shows \"Liminf F f \\<le> Liminf F g\"\n  unfolding Liminf_def\nproof (safe intro!: SUP_mono)\n  fix P assume \"eventually P F\"\n  with ev have \"eventually (\\<lambda>x. f x \\<le> g x \\<and> P x) F\" (is \"eventually ?Q F\") by (rule eventually_conj)\n  then show \"\\<exists>Q\\<in>{P. eventually P F}. INFIMUM (Collect P) f \\<le> INFIMUM (Collect Q) g\"\n    by (intro bexI[of _ ?Q]) (auto intro!: INF_mono)\nqed\n\nlemma Liminf_eq:\n  assumes \"eventually (\\<lambda>x. f x = g x) F\"\n  shows \"Liminf F f = Liminf F g\"\n  by (intro antisym Liminf_mono eventually_mono[OF _ assms]) auto\n\nlemma Limsup_mono:\n  assumes ev: \"eventually (\\<lambda>x. f x \\<le> g x) F\"\n  shows \"Limsup F f \\<le> Limsup F g\"\n  unfolding Limsup_def\nproof (safe intro!: INF_mono)\n  fix P assume \"eventually P F\"\n  with ev have \"eventually (\\<lambda>x. f x \\<le> g x \\<and> P x) F\" (is \"eventually ?Q F\") by (rule eventually_conj)\n  then show \"\\<exists>Q\\<in>{P. eventually P F}. SUPREMUM (Collect Q) f \\<le> SUPREMUM (Collect P) g\"\n    by (intro bexI[of _ ?Q]) (auto intro!: SUP_mono)\nqed\n\nlemma Limsup_eq:\n  assumes \"eventually (\\<lambda>x. f x = g x) net\"\n  shows \"Limsup net f = Limsup net g\"\n  by (intro antisym Limsup_mono eventually_mono[OF _ assms]) auto\n\nlemma Liminf_le_Limsup:\n  assumes ntriv: \"\\<not> trivial_limit F\"\n  shows \"Liminf F f \\<le> Limsup F f\"\n  unfolding Limsup_def Liminf_def\n  apply (rule SUP_least)\n  apply (rule INF_greatest)\nproof safe\n  fix P Q assume \"eventually P F\" \"eventually Q F\"\n  then have \"eventually (\\<lambda>x. P x \\<and> Q x) F\" (is \"eventually ?C F\") by (rule eventually_conj)\n  then have not_False: \"(\\<lambda>x. P x \\<and> Q x) \\<noteq> (\\<lambda>x. False)\"\n    using ntriv by (auto simp add: eventually_False)\n  have \"INFIMUM (Collect P) f \\<le> INFIMUM (Collect ?C) f\"\n    by (rule INF_mono) auto\n  also have \"\\<dots> \\<le> SUPREMUM (Collect ?C) f\"\n    using not_False by (intro INF_le_SUP) auto\n  also have \"\\<dots> \\<le> SUPREMUM (Collect Q) f\"\n    by (rule SUP_mono) auto\n  finally show \"INFIMUM (Collect P) f \\<le> SUPREMUM (Collect Q) f\" .\nqed\n\nlemma Liminf_bounded:\n  assumes ntriv: \"\\<not> trivial_limit F\"\n  assumes le: \"eventually (\\<lambda>n. C \\<le> X n) F\"\n  shows \"C \\<le> Liminf F X\"\n  using Liminf_mono[OF le] Liminf_const[OF ntriv, of C] by simp\n\nlemma Limsup_bounded:\n  assumes ntriv: \"\\<not> trivial_limit F\"\n  assumes le: \"eventually (\\<lambda>n. X n \\<le> C) F\"\n  shows \"Limsup F X \\<le> C\"\n  using Limsup_mono[OF le] Limsup_const[OF ntriv, of C] by simp\n\nlemma le_Liminf_iff:\n  fixes X :: \"_ \\<Rightarrow> _ :: complete_linorder\"\n  shows \"C \\<le> Liminf F X \\<longleftrightarrow> (\\<forall>y<C. eventually (\\<lambda>x. y < X x) F)\"\nproof -\n  { fix y P assume \"eventually P F\" \"y < INFIMUM (Collect P) X\"\n    then have \"eventually (\\<lambda>x. y < X x) F\"\n      by (auto elim!: eventually_elim1 dest: less_INF_D) }\n  moreover\n  { fix y P assume \"y < C\" and y: \"\\<forall>y<C. eventually (\\<lambda>x. y < X x) F\"\n    have \"\\<exists>P. eventually P F \\<and> y < INFIMUM (Collect P) X\"\n    proof (cases \"\\<exists>z. y < z \\<and> z < C\")\n      case True\n      then obtain z where z: \"y < z \\<and> z < C\" ..\n      moreover from z have \"z \\<le> INFIMUM {x. z < X x} X\"\n        by (auto intro!: INF_greatest)\n      ultimately show ?thesis\n        using y by (intro exI[of _ \"\\<lambda>x. z < X x\"]) auto\n    next\n      case False\n      then have \"C \\<le> INFIMUM {x. y < X x} X\"\n        by (intro INF_greatest) auto\n      with `y < C` show ?thesis\n        using y by (intro exI[of _ \"\\<lambda>x. y < X x\"]) auto\n    qed }\n  ultimately show ?thesis\n    unfolding Liminf_def le_SUP_iff by auto\nqed\n\nlemma lim_imp_Liminf:\n  fixes f :: \"'a \\<Rightarrow> _ :: {complete_linorder, linorder_topology}\"\n  assumes ntriv: \"\\<not> trivial_limit F\"\n  assumes lim: \"(f ---> f0) F\"\n  shows \"Liminf F f = f0\"\nproof (intro Liminf_eqI)\n  fix P assume P: \"eventually P F\"\n  then have \"eventually (\\<lambda>x. INFIMUM (Collect P) f \\<le> f x) F\"\n    by eventually_elim (auto intro!: INF_lower)\n  then show \"INFIMUM (Collect P) f \\<le> f0\"\n    by (rule tendsto_le[OF ntriv lim tendsto_const])\nnext\n  fix y assume upper: \"\\<And>P. eventually P F \\<Longrightarrow> INFIMUM (Collect P) f \\<le> y\"\n  show \"f0 \\<le> y\"\n  proof cases\n    assume \"\\<exists>z. y < z \\<and> z < f0\"\n    then obtain z where \"y < z \\<and> z < f0\" ..\n    moreover have \"z \\<le> INFIMUM {x. z < f x} f\"\n      by (rule INF_greatest) simp\n    ultimately show ?thesis\n      using lim[THEN topological_tendstoD, THEN upper, of \"{z <..}\"] by auto\n  next\n    assume discrete: \"\\<not> (\\<exists>z. y < z \\<and> z < f0)\"\n    show ?thesis\n    proof (rule classical)\n      assume \"\\<not> f0 \\<le> y\"\n      then have \"eventually (\\<lambda>x. y < f x) F\"\n        using lim[THEN topological_tendstoD, of \"{y <..}\"] by auto\n      then have \"eventually (\\<lambda>x. f0 \\<le> f x) F\"\n        using discrete by (auto elim!: eventually_elim1)\n      then have \"INFIMUM {x. f0 \\<le> f x} f \\<le> y\"\n        by (rule upper)\n      moreover have \"f0 \\<le> INFIMUM {x. f0 \\<le> f x} f\"\n        by (intro INF_greatest) simp\n      ultimately show \"f0 \\<le> y\" by simp\n    qed\n  qed\nqed\n\nlemma lim_imp_Limsup:\n  fixes f :: \"'a \\<Rightarrow> _ :: {complete_linorder, linorder_topology}\"\n  assumes ntriv: \"\\<not> trivial_limit F\"\n  assumes lim: \"(f ---> f0) F\"\n  shows \"Limsup F f = f0\"\nproof (intro Limsup_eqI)\n  fix P assume P: \"eventually P F\"\n  then have \"eventually (\\<lambda>x. f x \\<le> SUPREMUM (Collect P) f) F\"\n    by eventually_elim (auto intro!: SUP_upper)\n  then show \"f0 \\<le> SUPREMUM (Collect P) f\"\n    by (rule tendsto_le[OF ntriv tendsto_const lim])\nnext\n  fix y assume lower: \"\\<And>P. eventually P F \\<Longrightarrow> y \\<le> SUPREMUM (Collect P) f\"\n  show \"y \\<le> f0\"\n  proof (cases \"\\<exists>z. f0 < z \\<and> z < y\")\n    case True\n    then obtain z where \"f0 < z \\<and> z < y\" ..\n    moreover have \"SUPREMUM {x. f x < z} f \\<le> z\"\n      by (rule SUP_least) simp\n    ultimately show ?thesis\n      using lim[THEN topological_tendstoD, THEN lower, of \"{..< z}\"] by auto\n  next\n    case False\n    show ?thesis\n    proof (rule classical)\n      assume \"\\<not> y \\<le> f0\"\n      then have \"eventually (\\<lambda>x. f x < y) F\"\n        using lim[THEN topological_tendstoD, of \"{..< y}\"] by auto\n      then have \"eventually (\\<lambda>x. f x \\<le> f0) F\"\n        using False by (auto elim!: eventually_elim1 simp: not_less)\n      then have \"y \\<le> SUPREMUM {x. f x \\<le> f0} f\"\n        by (rule lower)\n      moreover have \"SUPREMUM {x. f x \\<le> f0} f \\<le> f0\"\n        by (intro SUP_least) simp\n      ultimately show \"y \\<le> f0\" by simp\n    qed\n  qed\nqed\n\nlemma Liminf_eq_Limsup:\n  fixes f0 :: \"'a :: {complete_linorder, linorder_topology}\"\n  assumes ntriv: \"\\<not> trivial_limit F\"\n    and lim: \"Liminf F f = f0\" \"Limsup F f = f0\"\n  shows \"(f ---> f0) F\"\nproof (rule order_tendstoI)\n  fix a assume \"f0 < a\"\n  with assms have \"Limsup F f < a\" by simp\n  then obtain P where \"eventually P F\" \"SUPREMUM (Collect P) f < a\"\n    unfolding Limsup_def INF_less_iff by auto\n  then show \"eventually (\\<lambda>x. f x < a) F\"\n    by (auto elim!: eventually_elim1 dest: SUP_lessD)\nnext\n  fix a assume \"a < f0\"\n  with assms have \"a < Liminf F f\" by simp\n  then obtain P where \"eventually P F\" \"a < INFIMUM (Collect P) f\"\n    unfolding Liminf_def less_SUP_iff by auto\n  then show \"eventually (\\<lambda>x. a < f x) F\"\n    by (auto elim!: eventually_elim1 dest: less_INF_D)\nqed\n\nlemma tendsto_iff_Liminf_eq_Limsup:\n  fixes f0 :: \"'a :: {complete_linorder, linorder_topology}\"\n  shows \"\\<not> trivial_limit F \\<Longrightarrow> (f ---> f0) F \\<longleftrightarrow> (Liminf F f = f0 \\<and> Limsup F f = f0)\"\n  by (metis Liminf_eq_Limsup lim_imp_Limsup lim_imp_Liminf)\n\nlemma liminf_subseq_mono:\n  fixes X :: \"nat \\<Rightarrow> 'a :: complete_linorder\"\n  assumes \"subseq r\"\n  shows \"liminf X \\<le> liminf (X \\<circ> r) \"\nproof-\n  have \"\\<And>n. (INF m:{n..}. X m) \\<le> (INF m:{n..}. (X \\<circ> r) m)\"\n  proof (safe intro!: INF_mono)\n    fix n m :: nat assume \"n \\<le> m\" then show \"\\<exists>ma\\<in>{n..}. X ma \\<le> (X \\<circ> r) m\"\n      using seq_suble[OF `subseq r`, of m] by (intro bexI[of _ \"r m\"]) auto\n  qed\n  then show ?thesis by (auto intro!: SUP_mono simp: liminf_SUP_INF comp_def)\nqed\n\nlemma limsup_subseq_mono:\n  fixes X :: \"nat \\<Rightarrow> 'a :: complete_linorder\"\n  assumes \"subseq r\"\n  shows \"limsup (X \\<circ> r) \\<le> limsup X\"\nproof-\n  have \"\\<And>n. (SUP m:{n..}. (X \\<circ> r) m) \\<le> (SUP m:{n..}. X m)\"\n  proof (safe intro!: SUP_mono)\n    fix n m :: nat assume \"n \\<le> m\" then show \"\\<exists>ma\\<in>{n..}. (X \\<circ> r) m \\<le> X ma\"\n      using seq_suble[OF `subseq r`, of m] by (intro bexI[of _ \"r m\"]) auto\n  qed\n  then show ?thesis by (auto intro!: INF_mono simp: limsup_INF_SUP comp_def)\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/Liminf_Limsup.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8670357460591569, "lm_q2_score": 0.8376199694135332, "lm_q1q2_score": 0.7262464550945109}}
{"text": "           (*-------------------------------------------*\n            |        CSP-Prover on Isabelle2004         |\n            |               November 2004               |\n            |                                           |\n            |        CSP-Prover on Isabelle2005         |\n            |                October 2005  (modified)   |\n            |                  March 2006  (modified)   |\n\n            |        CSP-Prover on Isabelle2016         |\n            |                    May 2016  (modified)   |\n            |                                           |\n            |        Yoshinao Isobe (AIST JAPAN)        |\n            *-------------------------------------------*)\n\ntheory Norm_seq\nimports CMS\nbegin\n\n(*****************************************************************\n\n         1. Definition of Normarized sequences\n         2. Properties of Normarized sequences\n         3. How to transform each Cauchy sequence to NF\n         4. The same limit between xs and NF(xs)\n\n *****************************************************************)\n\ndefinition\n  normal :: \"'a::ms infinite_seq => bool\"\n  where\n  normal_def : \n    \"normal xs == ALL (n::nat) (m::nat). \n        distance(xs n, xs m) <= (1/2)^(min n m)\"\n  \ndefinition  \n  Nset   :: \"'a::ms infinite_seq => real => nat set\"\n  where\n  Nset_def :\n    \"Nset xs delta == \n     {N. ALL n m. (N <= m & N <= n) --> distance(xs n, xs m) <= delta}\"\n  \ndefinition  \n  Nmin   :: \"'a::ms infinite_seq => real => nat\"\n  where\n  Nmin_def :\n    \"Nmin xs delta == MIN (Nset xs delta)\"\n  \ndefinition  \n  NF     :: \"'a::ms infinite_seq => 'a::ms infinite_seq\"\n  where\n  NF_def :\n    \"NF xs == (%n. xs (Nmin xs ((1/2)^n)))\"\n\n(********************************************************************\n                          Normalization\n ********************************************************************)\n\n(*** normalized sequence --> Cauchy sequence ***)\n\nlemma normal_cauchy: \"normal xs ==> cauchy xs\"\napply (simp add: cauchy_def)\napply (intro allI impI)\n\napply (subgoal_tac \"EX n. (1/2) ^ n < delta\")\napply (erule exE)\napply (rule_tac x=\"n\" in exI)\napply (intro allI impI)\napply (simp add: normal_def)\napply (drule_tac x=\"i\" in spec)\napply (drule_tac x=\"j\" in spec)\n\napply (subgoal_tac \"((1::real) / 2) ^ min i j <= (1 / 2) ^ n\")\napply (simp)\n\napply (case_tac \"i <= j\")\napply (simp add: min_def power_decreasing)\napply (simp add: min_def power_decreasing)\n\napply (simp add: pow_convergence)\ndone\n\n(*\ndeclare realpow_Suc          [simp del]\nin isabelle2008\n*)\n\ndeclare power_Suc          [simp del]\n\nlemma normal_Limit: \n  \"[| normal xs ; xs convergeTo y |]\n        ==> distance(xs (Suc n), y) < (1/2)^n\"\napply (simp add: convergeTo_def)\napply (drule_tac x=\"(1/2)^(Suc n)\" in spec)\napply (simp)\napply (erule exE)\n\napply (rename_tac N)\napply (case_tac \"N <= Suc n\")\n apply (drule_tac x=\"Suc n\" in spec)\n apply (simp add: symmetry_ms)\n\n apply (subgoal_tac \"((1::real) / 2) ^ Suc n <= (1 / 2) ^ n\")\n apply (simp)\n apply (simp add: power_decreasing)\n\n(* else (i.e. Suc n < N *)\n apply (drule_tac x=\"N\" in spec)\n apply (simp)\n apply (insert triangle_inequality_ms)\n apply (drule_tac x=\"xs (Suc n)\" in spec)\n apply (drule_tac x=\"xs N\" in spec)\n apply (drule_tac x=\"y\" in spec)\n\n apply (simp add: normal_def)\n apply (drule_tac x=\"Suc n\" in spec)\n apply (drule_tac x=\"N\" in spec)\n apply (simp add: symmetry_ms)\n apply (simp add: min_def)\n apply (simp add: power_Suc)\ndone\n\n(*\ndeclare realpow_Suc          [simp]\n*)\ndeclare power_Suc          [simp]\n\n(********************************************************************\n                                Nmin\n ********************************************************************)\n\n(*** Nmin exists ***)\n\nlemma Nmin_exists: \n  \"[| 0 < delta ; cauchy xs |] ==> EX N. N isMIN (Nset xs delta)\"\napply (simp add: cauchy_def)\napply (drule_tac x=\"delta\" in spec)\napply (simp)\napply (erule exE)\n\napply (rule EX_MIN_nat)\napply (simp add: Nset_def)\napply (rule_tac x=\"n\" in exI)\napply (intro allI impI)\napply (drule_tac x=\"na\" in spec)\napply (drule_tac x=\"m\" in spec)\nby (simp)\n\nlemma Nset_hasMIN: \n  \"[| 0 < delta ; cauchy xs |] ==> (Nset xs delta) hasMIN\"\napply (simp add: hasMIN_def)\napply (rule Nmin_exists)\nby (simp)\n\n(*** Nmin unique ***)\n\nlemma Nmin_unique: \n  \"[| N isMIN (Nset xs delta) ; M isMIN (Nset xs delta) |] ==> N = M\"\nby (simp add: MIN_unique)\n\n(*-----------------------*\n |       the Nmin        |\n *-----------------------*)\n\nlemma Nset_to_Nmin : \n  \"[| 0 < delta ; cauchy xs |]\n   ==> (N isMIN (Nset xs delta)) = (Nmin xs delta = N)\"\napply (simp add: Nmin_def)\napply (rule iffI)\n\napply (simp add: MIN_def Nset_hasMIN)\napply (rule the_equality)\napply (simp)\napply (simp add: Nmin_unique)\n\nby (simp add: MIN_iff Nset_hasMIN)\n\nlemmas Nmin_to_Nset = Nset_to_Nmin[THEN sym]\n\nlemma Nmin_to_Nset_sym :\n    \"[| 0 < delta ; cauchy xs |] \n     ==> (N = Nmin xs delta) = (N isMIN (Nset xs delta))\"\nby (auto simp add: Nset_to_Nmin)\n\nlemmas Nmin_iff = Nmin_to_Nset Nmin_to_Nset_sym\n\n(*-----------------------*\n |      property         |\n *-----------------------*)\n\nlemma Nmin_cauchy_lm:\n  \"[| 0 < delta ; cauchy xs ; Nmin xs delta = N |]\n   ==> (ALL n m. (N <= m & N <= n) --> distance(xs n, xs m) <= delta)\"\nby (simp add: Nmin_iff Nset_def isMIN_def)\n\nlemma Nmin_cauchy:\n  \"[| 0 < delta ; cauchy xs ; Nmin xs delta <= m ; Nmin xs delta <= n |]\n   ==> distance(xs n, xs m) <= delta\"\nby (simp add: Nmin_cauchy_lm)\n\n(*-----------------------*\n |   min_number_cauchy   |\n *-----------------------*)\n\n(*** Nmin order (check) ***)\n\nlemma min_number_cauchy_lm:\n  \"[| 0 < delta1 ; delta1 <= delta2 ; cauchy xs |]\n   ==> Nset xs delta1 <= Nset xs delta2\"\napply (simp add: Nset_def)\napply (rule subsetI)\napply (simp)\napply (intro allI impI)\napply (drule_tac x=\"n\" in spec)\napply (drule_tac x=\"m\" in spec)\nby (simp)\n\n(*** Nmin order ***)\n\nlemma min_number_cauchy:\n  \"[| 0 < delta1 ; delta1 <= delta2 ; cauchy xs ;\n      Nmin xs delta1 = N1 ; Nmin xs delta2 = N2 |]\n   ==> N2 <= N1\"\napply (simp add: Nmin_iff)\nby (simp add: isMIN_subset min_number_cauchy_lm)\n\n(*** Nmin order half ***)\n\nlemma min_number_cauchy_half:\n  \"[| n <= m ; cauchy xs ; Nmin xs ((1/2)^n) = N1 ; Nmin xs ((1/2)^m) = N2 |]\n   ==> N1 <= N2\"\napply (rule min_number_cauchy)\nby (simp_all add: power_decreasing)\n\n(*------------------------*\n | normal_form_seq_normal |\n *------------------------*)\n\nlemma normal_form_seq_normal: \"cauchy xs ==> normal (NF(xs))\"\napply (simp add: normal_def NF_def)\napply (intro allI)\n\napply (case_tac \"n <= m\")\n apply (simp add: min_def)\n apply (rule Nmin_cauchy, simp_all)\n apply (rule min_number_cauchy_half, simp_all)\n\n(* else *)\n apply (simp add: min_def)\n apply (rule Nmin_cauchy, simp_all)\n apply (rule min_number_cauchy_half, simp_all)\ndone\n\n(*----------------------------*\n | normal_form_seq_same_Limit |\n *----------------------------*)\n\n(*** only if part ***)\n\nlemma normal_form_seq_same_Limit_only_if:\n  \"[| cauchy xs ; xs convergeTo y |] ==> NF(xs) convergeTo y\"\napply (simp add: convergeTo_def)\napply (intro allI impI)\napply (drule_tac x=\"eps/2\" in spec)\napply (simp)\napply (erule exE)\n\napply (subgoal_tac \"EX n. (1 / 2) ^ n < eps/2\")\napply (erule exE)\napply (rename_tac eps N M)\n\napply (rule_tac x=\"M\" in exI)\napply (intro allI impI)\n\napply (case_tac \"N <= Nmin xs ((1/2)^m)\")\n\n apply (drule_tac x=\"Nmin xs ((1/2)^m)\" in spec)\n apply (simp add: NF_def)\n\n(* else *)\n apply (insert triangle_inequality_ms)\n apply (drule_tac x=\"y\" in spec)\n apply (drule_tac x=\"xs N\" in spec)\n apply (drule_tac x=\"(NF xs) m\" in spec)\n\n apply (drule_tac x=\"N\" in spec)\n apply (simp add: NF_def)\n\n apply (subgoal_tac \"distance (xs N, xs (Nmin xs ((1 / 2) ^ m))) <= (1 / 2) ^ m\")\n apply (subgoal_tac \"((1::real) / 2) ^ m <= (1 / 2) ^ M\")\n apply (simp)\n\n apply (simp add: power_decreasing)\n apply (rule Nmin_cauchy)\n apply (simp, simp, simp, simp)\n apply (rule pow_convergence)\n apply (simp_all)\ndone\n\n(*** if part ***)\n\nlemma normal_form_seq_same_Limit_if:\n  \"[| cauchy xs ; NF (xs) convergeTo y |] ==> xs convergeTo y\"\napply (simp add: convergeTo_def)\napply (intro allI impI)\napply (drule_tac x=\"eps/2\" in spec)\napply (simp)\napply (erule exE)\n\napply (subgoal_tac \"EX n. (1 / 2) ^ n < eps/2\")\napply (erule exE)\napply (rename_tac eps N M)\n\napply (rule_tac x=\"Nmin xs ((1/2)^(max N M))\" in exI)\napply (intro allI impI)\n\napply (insert triangle_inequality_ms)\napply (drule_tac x=\"y\" in spec)\napply (drule_tac x=\"xs (Nmin xs ((1/2)^(max N M)))\" in spec)\napply (drule_tac x=\"xs m\" in spec)\n\napply (drule_tac x=\"max N M\" in spec)\n(* apply (simp add: le_maxI1) *)\napply (simp add: NF_def)\n\n(* *)\n apply (subgoal_tac \n   \"distance(xs (Nmin xs ((1 / 2) ^ max N M)), xs m) <= (1 / 2) ^ max N M\")\n apply (subgoal_tac \"((1::real) / 2) ^ max N M <= (1 / 2) ^ M\")\n apply (simp)\n apply (simp add: max_def power_decreasing)\n\n apply (rule Nmin_cauchy)\n apply (simp, simp, simp, simp)\n apply (rule pow_convergence)\n apply (simp_all)\ndone\n\n(*** iff ***)\n\nlemma normal_form_seq_same_Limit:\n  \"cauchy xs ==> xs convergeTo y = NF(xs) convergeTo y\"\napply (rule iffI)\napply (simp add: normal_form_seq_same_Limit_only_if)\napply (simp add: normal_form_seq_same_Limit_if)\ndone\n\nend\n", "meta": {"author": "pefribeiro", "repo": "CSP-Prover", "sha": "8967cc482e5695fca4abb52d9dc2cf36b7b7a44e", "save_path": "github-repos/isabelle/pefribeiro-CSP-Prover", "path": "github-repos/isabelle/pefribeiro-CSP-Prover/CSP-Prover-8967cc482e5695fca4abb52d9dc2cf36b7b7a44e/CSP/Norm_seq.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970873650401, "lm_q2_score": 0.8244619263765707, "lm_q1q2_score": 0.7261836633958536}}
{"text": "(*\n  File:     Quick_Sort_Average_Case.thy\n  Author:   Manuel Eberl <eberlm@in.tum.de>\n\n  Definition and average-case analysis of the standard deterministic QuickSort algorithm\n*)\nsection \\<open>Average case analysis of deterministic QuickSort\\<close>\ntheory Quick_Sort_Average_Case\n  imports Randomised_Quick_Sort\nbegin\n  \nsubsection \\<open>Definition of deterministic QuickSort\\<close>\n  \ntext \\<open>\n  This is the functional description of the standard variant of deterministic QuickSort that \n  always chooses the first list element as the pivot as given by Hoare in 1962~\\cite{hoare}. \n  For a list that is already sorted, this leads to $n(n-1)$ \n  comparisons, but as is well known, the average case is not that bad.\n\\<close>\nfun quicksort :: \"('a \\<times> 'a) set \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where\n  \"quicksort _ [] = []\"\n| \"quicksort R (x # xs) = \n     quicksort R (filter (\\<lambda>y. (y,x) \\<in> R) xs) @ [x] @ quicksort R (filter (\\<lambda>y. (y,x) \\<notin> R) xs)\"\n\ntext \\<open>\n  We can easily show that this QuickSort is correct:\n\\<close>\ntheorem mset_quicksort [simp]: \"mset (quicksort R xs) = mset xs\"\n  by (induction R xs rule: quicksort.induct) (simp_all)\n\ncorollary set_quicksort [simp]: \"set (quicksort R xs) = set xs\"\n  by (induction R xs rule: quicksort.induct) auto\n\ntheorem sorted_wrt_quicksort: \n  assumes \"trans R\" and \"total_on (set xs) R\" and \"\\<And>x. x \\<in> set xs \\<Longrightarrow> (x, x) \\<in> R\"\n  shows   \"sorted_wrt R (quicksort R xs)\"\nusing assms\nproof (induction R xs rule: quicksort.induct)\n  case (2 R x xs)\n  have total: \"(a, b) \\<in> R\" if \"(b, a) \\<notin> R\" \"a \\<in> set (x#xs)\" \"b \\<in> set (x#xs)\" for a b\n    using \"2.prems\" that unfolding total_on_def by (cases \"a = b\") auto\n    \n  have *: \"sorted_wrt R (quicksort R (filter (\\<lambda>y. (y,x) \\<in> R) xs))\"\n          \"sorted_wrt R (quicksort R (filter (\\<lambda>y. (y,x) \\<notin> R) xs))\"\n    by ((rule 2 total_on_subset[OF \\<open>total_on (set (x#xs)) R\\<close>]) | force)+\n  show ?case\n    by (auto intro!: sorted_wrt_append sorted_wrt.intros \\<open>trans R\\<close> * \n             intro: transD[OF \\<open>trans R\\<close>] dest!: total simp: total_on_def)\nqed auto\n\ncorollary sorted_wrt_quicksort':\n  assumes \"linorder_on A R\" and \"set xs \\<subseteq> A\"\n  shows   \"sorted_wrt R (quicksort R xs)\"\n  by (rule sorted_wrt_quicksort)\n     (insert assms, auto simp: linorder_on_def refl_on_def dest: total_on_subset)\n\ntext \\<open>\n  We now define another version of QuickSort that is identical to the previous one but also \n  counts the number of comparisons that were made.\n\\<close>\nfun quicksort' :: \"('a \\<times> 'a) set \\<Rightarrow> 'a list \\<Rightarrow> 'a list \\<times> nat\" where\n  \"quicksort' _ [] = ([], 0)\"\n| \"quicksort' R (x # xs) = (\n     let (ls, rs)  = partition (\\<lambda>y. (y,x) \\<in> R) xs;\n         (ls', n1) = quicksort' R ls;\n         (rs', n2) = quicksort' R rs\n     in\n         (ls' @ [x] @ rs', length xs + n1 + n2))\"\n\ntext \\<open>\n  For convenience, we also define a function that computes only the number of comparisons that \n  were made and not the result list.\n\\<close>\nfun qs_cost :: \"('a \\<times> 'a) set \\<Rightarrow> 'a list \\<Rightarrow> nat\" where\n  \"qs_cost _ [] = 0\"\n| \"qs_cost R (x # xs) = \n     length xs + qs_cost R (filter (\\<lambda>y. (y,x)\\<in>R) xs) + qs_cost R (filter (\\<lambda>y. (y,x)\\<notin>R) xs)\"\n\n\ntext \\<open>\n  It is obvious that the original QuickSort and the cost function are the projections \n  of the cost-counting QuickSort.\n\\<close>  \nlemma fst_quicksort' [simp]: \"fst (quicksort' R xs) = quicksort R xs\"\n  by (induction R xs rule: quicksort.induct) (simp_all add: case_prod_unfold Let_def o_def)\n\nlemma snd_quicksort' [simp]: \"snd (quicksort' R xs) = qs_cost R xs\"\n  by (induction R xs rule: quicksort.induct) (simp_all add: case_prod_unfold Let_def o_def)\n\n    \nsubsection \\<open>Analysis\\<close>\n\ntext \\<open>\n  We will reduce the average-case analysis to showing that it is essentially equivalent to \n  the randomised QuickSort we analysed earlier. Similar, but more direct analyses are given \n  by Hoare~\\cite{hoare} and Sedgewick~\\cite{sedgewick}. \n\n  The proof is relatively straightforward -- but still a bit messy. We show that the cost \n  distribution of QuickSort run on a random permutation of a set of size $n$ is exactly the same \n  as that of randomised QuickSort being run on any fixed list of size $n$ (which we analysed \n  before):  \n\\<close>\ntheorem qs_cost_average_conv_rqs_cost:\n  assumes \"finite A\" and \"linorder_on B R\" and \"A \\<subseteq> B\"\n  shows   \"map_pmf (qs_cost R) (pmf_of_set (permutations_of_set A)) = rqs_cost (card A)\"\nusing assms(1,3)\nproof (induction A rule: finite_psubset_induct)\n  case (psubset A)\n  show ?case\n  proof (cases \"A = {}\")\n    case True\n    thus ?thesis by (simp add: pmf_of_set_singleton)\n  next\n    case False\n    note A = \\<open>finite A\\<close> \\<open>A \\<noteq> {}\\<close>\n    define n where \"n = card A - 1\"\n    from A have \"pmf_of_set (permutations_of_set A) = \n      do {x \\<leftarrow> pmf_of_set A; xs \\<leftarrow> pmf_of_set (permutations_of_set (A - {x})); return_pmf (x#xs)}\"\n      by (rule random_permutation_of_set)\n    also have \"map_pmf (qs_cost R) \\<dots> =\n                 do {\n                   x \\<leftarrow> pmf_of_set A;\n                   xs \\<leftarrow> pmf_of_set (permutations_of_set (A - {x}));\n                   return_pmf (length xs + qs_cost R [y\\<leftarrow>xs. (y,x)\\<in>R] + qs_cost R [y\\<leftarrow>xs. (y,x)\\<notin>R])\n                 }\" by (simp add: map_bind_pmf)\n    also have \"\\<dots> = map_pmf (\\<lambda>m. n + m) (\n          do {\n            x \\<leftarrow> pmf_of_set A;\n            xs \\<leftarrow> pmf_of_set (permutations_of_set (A - {x}));\n            return_pmf (qs_cost R [y\\<leftarrow>xs. (y,x)\\<in>R] + qs_cost R [y\\<leftarrow>xs. (y,x)\\<notin>R])\n          })\" (is \"_ = map_pmf _ ?X\") using A unfolding n_def map_bind_pmf\n      by (intro bind_pmf_cong map_pmf_cong refl) (auto simp: length_finite_permutations_of_set)\n    also have \"?X = do {\n                      x \\<leftarrow> pmf_of_set A;\n                      (ls,rs) \\<leftarrow> map_pmf (partition (\\<lambda>y. (y,x)\\<in>R)) \n                                   (pmf_of_set (permutations_of_set (A - {x})));\n                      return_pmf (qs_cost R ls + qs_cost R rs)\n                    }\" by (simp add: bind_map_pmf o_def)\n    also have \"\\<dots> = do {\n                      x \\<leftarrow> pmf_of_set A;\n                      (n1, n2) \\<leftarrow> pair_pmf \n                        (rqs_cost (linorder_rank R A x)) (rqs_cost (n - linorder_rank R A x));\n                      return_pmf (n1 + n2)}\"\n    proof (intro bind_pmf_cong refl, goal_cases)\n      case (1 x)\n      have \"map_pmf (partition (\\<lambda>y. (y,x)\\<in>R)) (pmf_of_set (permutations_of_set (A - {x})))\n              \\<bind> (\\<lambda>(ls, rs). return_pmf (qs_cost R ls + qs_cost R rs)) = \n            map_pmf (\\<lambda>(n1, n2). n1 + n2) (pair_pmf\n              (map_pmf (qs_cost R) (pmf_of_set (permutations_of_set {xa \\<in> A - {x}. (xa, x) \\<in> R})))\n              (map_pmf (qs_cost R) (pmf_of_set (permutations_of_set {xa \\<in> A - {x}. (xa, x) \\<notin> R}))))\"\n        (is \"_ = map_pmf _ (pair_pmf ?X ?Y)\")\n        by (subst partition_random_permutations)\n           (simp_all add: map_pmf_def case_prod_unfold bind_return_pmf bind_assoc_pmf pair_pmf_def A)\n      also {\n        have \"{xa \\<in> A - {x}. (xa, x) \\<in> R} \\<subseteq> A - {x}\" by blast\n        also have \"\\<dots> \\<subset> A\" using 1 A by auto\n        finally have subset: \"{xa \\<in> A - {x}. (xa, x) \\<in> R} \\<subset> A\" .\n        also have \"\\<dots> \\<subseteq> B\" by fact\n        finally have \"?X = rqs_cost (card {xa \\<in> A - {x}. (xa, x) \\<in> R})\" using subset\n          by (intro psubset.IH) auto\n        also have \"card {xa \\<in> A - {x}. (xa, x) \\<in> R} = linorder_rank R A x\"\n          by (simp add: linorder_rank_def)\n        finally have \"?X = rqs_cost \\<dots>\" .\n      }\n      also {\n        have \"{xa \\<in> A - {x}. (xa, x) \\<notin> R} \\<subseteq> A - {x}\" by blast\n        also have \"\\<dots> \\<subset> A\" using 1 A by auto\n        finally have subset: \"{xa \\<in> A - {x}. (xa, x) \\<notin> R} \\<subset> A\" .\n        also have \"\\<dots> \\<subseteq> B\" by fact\n        finally have \"?Y = rqs_cost (card {xa \\<in> A - {x}. (xa, x) \\<notin> R})\" using subset\n          by (intro psubset.IH) auto\n        also {\n          have \"card ({y\\<in>A-{x}. (y,x)\\<in>R} \\<union> {y\\<in>A-{x}. (y,x)\\<notin>R}) = \n                  linorder_rank R A x + card {xa \\<in> A - {x}. (xa, x) \\<notin> R}\"\n            unfolding linorder_rank_def using A by (intro card_Un_disjoint) auto\n          also have \"{y\\<in>A-{x}. (y,x)\\<in>R} \\<union> {y\\<in>A-{x}. (y,x)\\<notin>R} = A - {x}\" by blast\n          also have \"card \\<dots> = n\" using A 1 by (simp add: n_def)\n          finally have \"card {xa \\<in> A - {x}. (xa, x) \\<notin> R} = n - linorder_rank R A x\" by simp\n        }\n        finally have \"?Y = rqs_cost (n - linorder_rank R A x)\" .\n      }\n      finally show ?case by (simp add: case_prod_unfold map_pmf_def)\n    qed\n    also have \"\\<dots> = do {\n                      i \\<leftarrow> map_pmf (linorder_rank R A) (pmf_of_set A);\n                      (n1, n2) \\<leftarrow> pair_pmf (rqs_cost i) (rqs_cost (n - i));\n                      return_pmf (n1 + n2)\n                    }\" by (simp add: bind_map_pmf)\n    also have \"map_pmf (linorder_rank R A) (pmf_of_set A) = pmf_of_set {..<card A}\"\n      by (intro map_pmf_of_set_bij_betw bij_betw_linorder_rank[OF assms(2)] A psubset.prems)\n    also from A have \"card A > 0\" by (intro Nat.gr0I) auto\n    hence \"{..<card A} = {..n}\" by (auto simp: n_def)\n    also have \"map_pmf (\\<lambda>m. n + m) (\n                 do {\n                      i \\<leftarrow> pmf_of_set {..n};\n                      (n1, n2) \\<leftarrow> pair_pmf (rqs_cost i) (rqs_cost (n - i));\n                      return_pmf (n1 + n2)\n                    }) = rqs_cost (Suc n)\"\n      by (simp add: pair_pmf_def map_bind_pmf case_prod_unfold\n                    bind_assoc_pmf bind_return_pmf add_ac)\n    also from A have \"card A > 0\" by (intro Nat.gr0I) auto\n    hence \"Suc n = card A\" by (simp add: n_def)\n    finally show ?thesis .\n  qed\nqed\n\ntext \\<open>\n  We therefore have the same expectation as well. (Note that we showed \n  @{thm rqs_cost_exp_eq [no_vars]} and @{thm rqs_cost_exp_asymp_equiv [no_vars]} before.\n\\<close>\ncorollary expectation_qs_cost: \n  assumes \"finite A\" and \"linorder_on B R\" and \"A \\<subseteq> B\"\n  defines \"random_list \\<equiv> pmf_of_set (permutations_of_set A)\"\n  shows   \"measure_pmf.expectation (map_pmf (qs_cost R) random_list) real = \n             rqs_cost_exp (card A)\"\n  unfolding random_list_def\n  by (subst qs_cost_average_conv_rqs_cost[OF assms(1-3)]) (simp add: expectation_rqs_cost)\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/Quick_Sort_Cost/Quick_Sort_Average_Case.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8244619177503205, "lm_q2_score": 0.8807970889295663, "lm_q1q2_score": 0.7261836570877699}}
{"text": "section \\<open>Generalization of the statement about the uniqueness of the Hermite normal form\\<close>\n\ntheory Uniqueness_Hermite\nimports Hermite.Hermite\nbegin\n\n(*This file presents a generalized version of the theorem Hermite_unique when applied to integer\nmatrices. More concretely, instead of assuming invertibility over Z of the input matrix A, we now \nassume invertibility over Q. Only some changes to adapt the original proof are required.*)\n\ninstance int :: bezout_ring_div\nproof qed\n\nlemma map_matrix_rat_of_int_mult:\n  shows \"map_matrix rat_of_int (A**B) = (map_matrix rat_of_int A)**(map_matrix rat_of_int B)\" \n  unfolding map_matrix_def matrix_matrix_mult_def by auto\n\nlemma det_map_matrix:\n  fixes A :: \"int^'n::mod_type^'n::mod_type\"\n  shows \"det (map_matrix rat_of_int A) = rat_of_int (det A)\" \n  unfolding map_matrix_def unfolding Determinants.det_def by auto\n\nlemma inv_Z_imp_inv_Q:\n  fixes A :: \"int^'n::mod_type^'n::mod_type\"\n  assumes inv_A: \"invertible A\"\n  shows \"invertible (map_matrix rat_of_int A)\"\nproof -\n  have \"is_unit (det A)\" using inv_A invertible_iff_is_unit by blast\n  hence \"is_unit (det (map_matrix rat_of_int A))\"\n    by (simp add: det_map_matrix dvd_if_abs_eq)\n  thus ?thesis using invertible_iff_is_unit by blast\nqed\n\nlemma upper_triangular_Z_eq_Q:\n  \"upper_triangular (map_matrix rat_of_int A) = upper_triangular A\" \n  unfolding upper_triangular_def by auto\n\nlemma invertible_and_upper_diagonal_not0:\n  fixes H :: \"int^'n::mod_type^'n::mod_type\"\n  assumes inv_H: \"invertible (map_matrix rat_of_int H)\" and up_H: \"upper_triangular H\"\n  shows \"H $ i $ i \\<noteq> 0\"\nproof -\n  let ?RAT_H = \"(map_matrix rat_of_int H)\"\n  have up_RAT_H: \"upper_triangular ?RAT_H\"\n    using up_H unfolding upper_triangular_def by auto\n  have \"is_unit (det ?RAT_H)\" using inv_H using invertible_iff_is_unit by blast\n  hence \"?RAT_H $ i $ i \\<noteq> 0\" using inv_H up_RAT_H is_unit_diagonal\n    by (metis not_is_unit_0)\n  thus ?thesis by auto\nqed\n\nlemma diagonal_least_nonzero:\n  fixes H :: \"int^'n::mod_type^'n::mod_type\"\n  assumes H: \"Hermite associates residues H\"\n  and inv_H: \"invertible (map_matrix rat_of_int H)\" and up_H: \"upper_triangular H\"\n  shows \"(LEAST n. H $ i $ n \\<noteq> 0) = i\"\nproof (rule Least_equality)\n  show \"H $ i $ i \\<noteq> 0\" by (rule invertible_and_upper_diagonal_not0[OF inv_H up_H])\n  fix y\n  assume Hiy: \"H $ i $ y \\<noteq> 0\"\n  show \"i \\<le> y\" \n    using up_H unfolding upper_triangular_def\n    by (metis (poly_guards_query) Hiy not_less)\nqed\n\nlemma diagonal_in_associates:\n  fixes H :: \"int^'n::mod_type^'n::mod_type\"\n  assumes H: \"Hermite associates residues H\"\n  and inv_H: \"invertible (map_matrix rat_of_int H)\" and up_H: \"upper_triangular H\"\n  shows \"H $ i $ i \\<in> associates\"\nproof -\n  have \"H $ i $ i \\<noteq> 0\" by (rule invertible_and_upper_diagonal_not0[OF inv_H up_H])\n  hence \"\\<not> is_zero_row i H\" unfolding is_zero_row_def is_zero_row_upt_k_def ncols_def by auto\n  thus ?thesis using H unfolding Hermite_def unfolding diagonal_least_nonzero[OF H inv_H up_H] \n    by auto\nqed\n\nlemma above_diagonal_in_residues:\n  fixes H :: \"int^'n::mod_type^'n::mod_type\"\n  assumes H: \"Hermite associates residues H\"\n  and inv_H: \"invertible (map_matrix rat_of_int H)\" and up_H: \"upper_triangular H\"\n  and j_i: \"j<i\"\n  shows \"H $ j $ (LEAST n. H $ i $ n \\<noteq> 0) \\<in> residues (H $ i $ (LEAST n. H $ i $ n \\<noteq> 0))\" \nproof -\n  have \"H $ i $ i \\<noteq> 0\" by (rule invertible_and_upper_diagonal_not0[OF inv_H up_H])\n  hence \"\\<not> is_zero_row i H\" unfolding is_zero_row_def is_zero_row_upt_k_def ncols_def by auto\n  thus ?thesis using H j_i unfolding Hermite_def unfolding diagonal_least_nonzero[OF H inv_H up_H] \n    by auto\nqed\n\n\nlemma Hermite_unique_generalized:\n  fixes K::\"int^'n::mod_type^'n::mod_type\"\n  assumes A_PH: \"A = P ** H\" \n  and A_QK: \"A = Q ** K\"\n  and inv_A: \"invertible (map_matrix rat_of_int A)\" (*The original statement assumes \"invertible A\", \n                                                      that is, invertibility over integers, which is\n                                                      more restrictive.*)\n  and inv_P: \"invertible P\"\n  and inv_Q: \"invertible Q\"\n  and H: \"Hermite associates residues H\"\n  and K: \"Hermite associates residues K\"\n  shows \"H = K\"\nproof -\n  let ?RAT = \"map_matrix rat_of_int\"\n  have cs_residues: \"Complete_set_residues residues\" using H unfolding Hermite_def by simp\n  have inv_H: \"invertible (?RAT H)\"\n  proof -\n    have \"?RAT A = ?RAT P ** ?RAT H\" using A_PH map_matrix_rat_of_int_mult by blast\n    thus ?thesis\n      by (metis inv_A invertible_left_inverse matrix_inv(1) matrix_mul_assoc)\n  qed\n  have inv_K: \"invertible (?RAT K)\"\n  proof -\n   have \"?RAT A = ?RAT Q ** ?RAT K\" using A_QK map_matrix_rat_of_int_mult by blast\n    thus ?thesis\n      by (metis inv_A invertible_left_inverse matrix_inv(1) matrix_mul_assoc)\n  qed\n  define U where \"U = (matrix_inv P)**Q\"\n  have inv_U: \"invertible U\" \n    by (metis U_def inv_P inv_Q invertible_def invertible_mult matrix_inv_left matrix_inv_right)\n  have H_UK: \"H = U ** K\" using A_PH A_QK inv_P \n    by (metis U_def matrix_inv_left matrix_mul_assoc matrix_mul_lid)\n  have \"Determinants.det K *k U = H ** adjugate K\"\n    unfolding H_UK matrix_mul_assoc[symmetric] mult_adjugate_det matrix_mul_mat ..\n  have upper_triangular_H: \"upper_triangular H\"\n    by (metis H Hermite_def echelon_form_imp_upper_triagular)\n  have upper_triangular_K: \"upper_triangular K\" \n    by (metis K Hermite_def echelon_form_imp_upper_triagular)\n  have upper_triangular_U: \"upper_triangular U\" \n  proof -\n    have U_H_K: \"?RAT U = (?RAT H) ** (matrix_inv (?RAT K))\"\n      by (metis H_UK inv_K map_matrix_rat_of_int_mult matrix_inv(2) matrix_mul_assoc matrix_mul_rid)\n    have up_inv_RAT_K: \"upper_triangular (matrix_inv (?RAT K))\" using upper_triangular_inverse\n      by (simp add: upper_triangular_inverse inv_K upper_triangular_K upper_triangular_Z_eq_Q)\n    have \"upper_triangular (?RAT U)\" unfolding U_H_K \n      by (rule upper_triangular_mult[OF _ up_inv_RAT_K], \n          auto simp add: upper_triangular_H upper_triangular_Z_eq_Q)\n    thus ?thesis using upper_triangular_Z_eq_Q by auto\n  qed\n  have unit_det_U: \"is_unit (det U)\" by (metis inv_U invertible_iff_is_unit)\n  have is_unit_diagonal_U: \"(\\<forall>i. is_unit (U $ i $ i))\"\n    by (rule is_unit_diagonal[OF upper_triangular_U unit_det_U])\n  have Uii_1: \"(\\<forall>i. (U $ i $ i) = 1)\" and Hii_Kii: \"(\\<forall>i. (H $ i $ i) = (K $ i $ i))\"\n  proof (auto)\n    fix i\n    have Hii: \"H $ i $ i \\<in> associates\" \n      by (rule diagonal_in_associates[OF H inv_H upper_triangular_H])\n    have Kii: \"K $ i $ i \\<in> associates\"\n      by (rule diagonal_in_associates[OF K inv_K upper_triangular_K])\n    have ass_Hii_Kii: \"normalize (H $ i $ i) = normalize (K $ i $ i)\"\n      by (metis H_UK is_unit_diagonal_U normalize_mult_unit_left upper_triangular_K upper_triangular_U upper_triangular_mult_diagonal)\n    show Hii_eq_Kii: \"H $ i $ i = K $ i $ i\"\n      by (metis Hermite_def Hii K Kii ass_Hii_Kii in_Ass_not_associated)\n    have \"H $ i $ i = U $ i $ i * K $ i $ i\" \n      by (metis H_UK upper_triangular_K upper_triangular_U upper_triangular_mult_diagonal)\n    thus \"U $ i $ i = 1\" unfolding Hii_eq_Kii mult_cancel_right1\n      using inv_K invertible_and_upper_diagonal_not0 upper_triangular_K by blast \n  qed\n  have zero_above: \"\\<forall>j s. j\\<ge>1 \\<and> j < ncols A - to_nat s \\<longrightarrow> U $ s $ (s + from_nat j) = 0\"\n  proof (clarify)\n    fix j s assume  \"1 \\<le> j\" and \"j < ncols A - (to_nat (s::'n))\"\n    thus \"U $ s $ (s + from_nat j) = 0\"\n    proof (induct j rule: less_induct)\n      fix p \n      assume induct_step: \"(\\<And>y. y < p \\<Longrightarrow> 1 \\<le> y \\<Longrightarrow> y < ncols A - to_nat s \\<Longrightarrow> U $ s $ (s + from_nat y) = 0)\"\n        and p1: \"1 \\<le> p\" and p2: \"p < ncols A - to_nat s\"\n      have s_less: \"s < s + from_nat p\" using p1 p2 unfolding ncols_def\n        by (metis One_nat_def add.commute add_diff_cancel_right' add_lessD1 add_to_nat_def \n          from_nat_to_nat_id less_diff_conv neq_iff not_le\n          to_nat_from_nat_id to_nat_le zero_less_Suc)\n      show \"U $ s $ (s + from_nat p) = 0\"\n      proof -\n        have UNIV_rw: \"UNIV = insert s (UNIV-{s})\" by auto\n        have UNIV_s_rw: \"UNIV-{s} = insert (s + from_nat p) ((UNIV-{s}) - {s + from_nat p})\" \n          using p1 p2 s_less unfolding ncols_def by (auto simp: algebra_simps)\n        have sum_rw: \"(\\<Sum>k\\<in>UNIV-{s}. U $ s $ k * K $ k $ (s + from_nat p)) \n          = U $ s $ (s + from_nat p) * K $ (s + from_nat p) $ (s + from_nat p) \n          + (\\<Sum>k\\<in>(UNIV-{s})-{s + from_nat p}. U $ s $ k * K $ k $ (s + from_nat p))\"\n          using UNIV_s_rw sum.insert by (metis (erased, lifting) Diff_iff finite singletonI)\n        have sum_0: \"(\\<Sum>k\\<in>(UNIV-{s})-{s + from_nat p}. U $ s $ k * K $ k $ (s + from_nat p)) = 0\"\n        proof (rule sum.neutral, rule)\n          fix x assume x: \"x \\<in> UNIV - {s} - {s + from_nat p}\"\n          show \"U $ s $ x * K $ x $ (s + from_nat p) = 0\" \n          proof (cases \"x<s\")\n            case True\n            thus ?thesis using upper_triangular_U unfolding upper_triangular_def\n              by auto\n          next\n            case False\n            hence x_g_s: \"x>s\" using x by (metis Diff_iff neq_iff singletonI)\n            show ?thesis \n            proof (cases \"x<s+from_nat p\")\n              case True\n              define a where \"a = to_nat x - to_nat s\"\n              from x_g_s have \"to_nat s < to_nat x\" by (rule to_nat_mono)\n              hence xa: \"x=s+(from_nat a)\" unfolding a_def add_to_nat_def\n                by (simp add: less_imp_diff_less to_nat_less_card algebra_simps to_nat_from_nat_id)\n              have \"U $ s $ x =0\" \n              proof (unfold xa, rule induct_step)\n                show a_p: \"a<p\" unfolding a_def using p2 unfolding ncols_def \n                proof -\n                  have \"x < from_nat (to_nat s + to_nat (from_nat p::'n))\"\n                    by (metis (no_types) True add_to_nat_def)\n                  hence \"to_nat x - to_nat s < to_nat (from_nat p::'n)\"\n                    by (simp add: add.commute less_diff_conv2 less_imp_le to_nat_le x_g_s)\n                  thus \"to_nat x - to_nat s < p\"\n                    by (metis (no_types) from_nat_eq_imp_eq from_nat_to_nat_id le_less_trans \n                        less_imp_le not_le to_nat_less_card)\n                qed                    \n                show \"1 \\<le> a\" \n                  by (auto simp add: a_def p1 p2) (metis Suc_leI to_nat_mono x_g_s zero_less_diff)\n                show \"a < ncols A - to_nat s\" using a_p p2 by auto\n              qed\n              thus ?thesis by simp\n            next\n              case False\n              hence \"x>s+from_nat p\" using x_g_s x by auto\n              thus ?thesis using upper_triangular_K unfolding upper_triangular_def\n                by auto\n            qed\n          qed \n        qed\n        have \"H $ s $ (s + from_nat p) = (\\<Sum>k\\<in>UNIV. U $ s $ k * K $ k $ (s + from_nat p))\"\n          unfolding H_UK matrix_matrix_mult_def by auto\n        also have \"... = (\\<Sum>k\\<in>insert s (UNIV-{s}). U $ s $ k * K $ k $ (s + from_nat p))\"\n          using UNIV_rw by simp\n        also have \"... = U $ s $ s * K $ s $ (s + from_nat p) \n          + (\\<Sum>k\\<in>UNIV-{s}. U $ s $ k * K $ k $ (s + from_nat p))\"\n          by (rule sum.insert, simp_all)\n        also have \"... = U $ s $ s * K $ s $ (s + from_nat p) \n          + U $ s $ (s + from_nat p) * K $ (s + from_nat p) $ (s + from_nat p)\"\n          unfolding sum_rw sum_0 by simp\n        finally have H_s_sp: \"H $ s $ (s + from_nat p) \n          = U $ s $ (s + from_nat p) * K $ (s + from_nat p) $ (s + from_nat p) + K $ s $ (s + from_nat p)\"\n          using Uii_1 by auto\n        hence cong_HK: \"cong (H $ s $ (s + from_nat p)) (K $ s $ (s + from_nat p)) (K $ (s+from_nat p) $ (s + from_nat p))\"\n          unfolding cong_def by auto\n        have H_s_sp_residues: \"(H $ s $ (s + from_nat p)) \\<in> residues (K $ (s+from_nat p) $ (s + from_nat p))\" \n          using above_diagonal_in_residues[OF H inv_H upper_triangular_H s_less]\n          unfolding diagonal_least_nonzero[OF H inv_H upper_triangular_H]\n          by (metis Hii_Kii)\n        have K_s_sp_residues: \"(K $ s $ (s + from_nat p)) \\<in> residues (K $ (s+from_nat p) $ (s + from_nat p))\"\n          using above_diagonal_in_residues[OF K inv_K upper_triangular_K s_less]\n          unfolding diagonal_least_nonzero[OF K inv_K upper_triangular_K] .\n        have Hs_sp_Ks_sp: \"(H $ s $ (s + from_nat p)) = (K $ s $ (s + from_nat p))\"             \n          using cong_HK in_Res_not_congruent[OF cs_residues H_s_sp_residues K_s_sp_residues]\n          by fast\n        have \"K $ (s + from_nat p) $ (s + from_nat p) \\<noteq> 0\"\n          using inv_K invertible_and_upper_diagonal_not0 upper_triangular_K by blast\n        thus ?thesis unfolding from_nat_1 using H_s_sp unfolding Hs_sp_Ks_sp by auto\n      qed \n    qed \n  qed\n  have \"U = mat 1\" \n  proof (unfold mat_def vec_eq_iff, auto)\n    fix ia show \"U $ ia $ ia = 1\" using Uii_1 by simp\n    fix i assume i_ia: \"i \\<noteq> ia\"\n    show \"U $ i $ ia = 0\"\n    proof (cases \"ia<i\")\n      case True\n      thus ?thesis using upper_triangular_U unfolding upper_triangular_def by auto\n    next\n      case False\n      hence i_less_ia: \"i<ia\" using i_ia by auto\n      define a where \"a = to_nat ia - to_nat i\"\n      have ia_eq: \"ia = i + from_nat a\" unfolding a_def\n        by (metis i_less_ia a_def add_to_nat_def dual_order.strict_iff_order from_nat_to_nat_id \n            le_add_diff_inverse less_imp_diff_less to_nat_from_nat_id to_nat_less_card to_nat_mono)\n      have \"1 \\<le> a\" unfolding a_def\n        by (metis diff_is_0_eq i_less_ia less_one not_less to_nat_mono)\n      moreover have \"a < ncols A - to_nat i\"\n        unfolding a_def ncols_def\n        by (metis False diff_less_mono not_less to_nat_less_card to_nat_mono')\n      ultimately show ?thesis using zero_above unfolding ia_eq by blast\n    qed\n  qed\n  thus ?thesis using H_UK matrix_mul_lid by fast\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/Modular_arithmetic_LLL_and_HNF_algorithms/Uniqueness_Hermite.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970748488296, "lm_q2_score": 0.8244619285331332, "lm_q1q2_score": 0.7261836549762085}}
{"text": "theory Permute\n  imports Main Seq2less\nbegin\n\n(* Here we play with permutability of triplet components of 2-less sequences. *)\n\n(* Permutations (redundant) of a triplet *)\n\nfun swap_12 :: \"Tri \\<Rightarrow> Tri\" where\n  \"swap_12 (x1, x2, x3) = (x2, x1, x3)\"\n\nfun swap_13 :: \"Tri \\<Rightarrow> Tri\" where\n  \"swap_13 (x1, x2, x3) = (x3, x2, x1)\"\n\nfun swap_23 :: \"Tri \\<Rightarrow> Tri\" where\n  \"swap_23 (x1, x2, x3) =  (x1, x3, x2)\"\n\nfun rot_r :: \"Tri \\<Rightarrow> Tri\" where\n  \"rot_r (x1, x2, x3) =  (x3, x1, x2)\"\n\nfun rot_l :: \"Tri \\<Rightarrow> Tri\" where\n  \"rot_l (x1, x2, x3) =  (x2, x3, x1)\"\n\n(* Function perm gathers all of the above transformations. *)\n\ndatatype Perm = Swap12 | Swap13 | Swap23 | RotR | RotL\n\nfun perm :: \"Perm \\<Rightarrow> Tri \\<Rightarrow> Tri\" where\n  \"perm k t = (case k of\n    Swap12 \\<Rightarrow> swap_12 t |\n    Swap13 \\<Rightarrow> swap_13 t |\n    Swap23 \\<Rightarrow> swap_23 t |\n    RotR \\<Rightarrow> rot_r t |\n    RotL \\<Rightarrow> rot_l t)\"\n\n(* Given a pf transform a sequence by applying pf on each element. *)\n\nprimrec permute :: \"(Tri \\<Rightarrow> Tri) \\<Rightarrow> Tri list \\<Rightarrow> Tri list\" where\n  \"permute pf [] = []\" |\n  \"permute pf (h#t) = ((pf h)#(permute pf t))\"\n\n\n(* Lemmata *)\n\n(* Transformation of triplets preserves 2-lessness (for \\<prec>, lt_all, is_2less) *)\n\nlemma permutability_lt:\n  \"(x \\<prec> y) \\<longrightarrow> (perm k x \\<prec> perm k y)\"\n  apply (simp add: split_def)\n  by (smt Perm.exhaust Perm.simps(21) Perm.simps(22) Perm.simps(23) Perm.simps(24) Perm.simps(25) lt.elims(2) lt.simps rot_l.simps rot_r.simps swap_12.simps swap_13.simps swap_23.simps)\n\nlemma permutability_lt_all:\n  \"lt_all x t \\<longrightarrow> lt_all (perm k x) (permute (perm k) t)\"\n  apply (induction t arbitrary: k)\n  using permutability_lt\n  by auto\n\ntheorem permutability_is_2less:\n  \"is_2less t \\<longrightarrow> is_2less (permute (perm k) t)\"\n  apply (induction t arbitrary: k)\n  using permutability_lt permutability_lt_all\n  by auto\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/Permute.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970779778825, "lm_q2_score": 0.8244619242200082, "lm_q1q2_score": 0.7261836537570057}}
{"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.*)\n  theory TIP_prop_30\n  imports \"../../Test_Base\"\nbegin\n\ndatatype 'a list = nil2 | cons2 \"'a\" \"'a list\"\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\nlemma app_nil: \"x y nil2 = y\" by (induct y, auto)\nlemma app_assoc: \"x (x y z) w = x y (x z w)\" by (induction y, auto)\nlemma rev_app: \"rev (x y z) = x (rev z) (rev y)\" \n  apply(induction y, auto)\n   apply(simp add: app_nil) \n  using app_assoc apply(auto)\n  done\n\nlemma revrev: \"rev (rev y) = y\"\n  apply(induction y, auto)\n  apply(simp add: rev_app)\n  done\n\ntheorem property0 :\n  \"((rev (x (rev y) (nil2))) = y)\"\n  apply(simp add: app_nil revrev) \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_30.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.880797081106935, "lm_q2_score": 0.8244619177503205, "lm_q1q2_score": 0.7261836506383083}}
{"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 ==\n     \\<forall>X. ~Finite(X) \\<longrightarrow> (\\<exists>R. well_ord(X,R) & ~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\"\napply (unfold 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 ==> WO1\"\napply (unfold 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    \"[| Ord(a); ~Finite(a) |] ==> ~wf[a](converse(Memrel(a)))\"\napply (unfold 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    \"[| Ord(a); ~Finite(a) |] ==> ~well_ord(a,converse(Memrel(a)))\"\napply (unfold 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     \"[| well_ord(A,r); well_ord(A,converse(r)) |]   \n      ==> 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 ==> 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 ==> WO8\"\nby (unfold WO1_def WO8_def, fast)\n\n\n(* The implication \"WO8 ==> WO1\": a faithful image of Rubin & Rubin's proof*)\nlemma WO8_WO1: \"WO8 ==> WO1\"\napply (unfold 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": "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/AC/WO1_WO7.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933093975331751, "lm_q2_score": 0.8128673246376009, "lm_q1q2_score": 0.7261420200464191}}
{"text": "(* Title:      Antidomain Semirings\n   Author:     Victor B. F. Gomes, Walter Guttmann, Peter H\u00f6fner, 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>Antidomain Semirings\\<close>\n\ntheory Antidomain_Semiring\nimports Domain_Semiring\nbegin\n\nsubsection \\<open>Antidomain Monoids\\<close>\n\ntext \\<open>We axiomatise antidomain monoids, using the axioms of~\\<^cite>\\<open>\"DesharnaisJipsenStruth\"\\<close>.\\<close>\n\nclass antidomain_op =\n  fixes antidomain_op :: \"'a \\<Rightarrow> 'a\" (\"ad\")\n\nclass antidomain_left_monoid = monoid_mult + antidomain_op +\n  assumes am1 [simp]: \"ad x \\<cdot> x = ad 1\"\n  and am2: \"ad x \\<cdot> ad y = ad y \\<cdot> ad x\"\n  and am3 [simp]: \"ad (ad x) \\<cdot> x = x\"\n  and am4 [simp]: \"ad (x \\<cdot> y) \\<cdot> ad (x \\<cdot> ad y) = ad x\"\n  and am5 [simp]: \"ad (x \\<cdot> y) \\<cdot> x \\<cdot> ad y = ad (x \\<cdot> y) \\<cdot> x\"\n\nbegin\n\nno_notation domain_op (\"d\")\nno_notation zero_class.zero (\"0\")\n\ntext \\<open>We define a zero element and operations of domain and addition.\\<close>\n\ndefinition a_zero :: \"'a\" (\"0\") where\n  \"0 = ad 1\"\n\ndefinition am_d :: \"'a \\<Rightarrow> 'a\" (\"d\") where\n   \"d x = ad (ad x)\"\n\ndefinition am_add_op :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a\" (infixl \"\\<oplus>\" 65) where\n  \"x \\<oplus> y \\<equiv> ad (ad x \\<cdot> ad y)\"\n\nlemma a_d_zero [simp]: \"ad x \\<cdot> d x = 0\"\n  by (metis am1 am2 a_zero_def am_d_def)\n\nlemma a_d_one [simp]: \"d x \\<oplus> ad x = 1\"\n  by (metis am1 am3 mult_1_right am_d_def am_add_op_def)\n\nlemma n_annil [simp]: \"0 \\<cdot> x = 0\"\nproof -\n  have \"0 \\<cdot> x = d x \\<cdot> ad x \\<cdot> x\"\n    by (simp add: a_zero_def am_d_def)\n  also have \"... = d x \\<cdot> 0\"\n    by (metis am1 mult_assoc a_zero_def)\n  thus ?thesis\n    by (metis am1 am2 am3 mult_assoc a_zero_def)\nqed\n\nlemma a_mult_idem [simp]: \"ad x \\<cdot> ad x = ad x\"\nproof -\n  have \"ad x \\<cdot> ad x = ad (1 \\<cdot> x) \\<cdot> 1 \\<cdot> ad x\"\n    by simp\n  also have \"... = ad (1 \\<cdot> x) \\<cdot> 1\"\n    using am5 by blast\n  finally show ?thesis\n    by simp\nqed\n\nlemma a_add_idem [simp]: \"ad x \\<oplus> ad x = ad x\"\n  by (metis am1 am3 am4 mult_1_right am_add_op_def)\n\ntext \\<open>The next three axioms suffice to show that the domain elements form a Boolean algebra.\\<close>\n\nlemma a_add_comm: \"x \\<oplus> y = y \\<oplus> x\"\n  using am2 am_add_op_def by auto\n\nlemma a_add_assoc: \"x \\<oplus> (y \\<oplus> z) = (x \\<oplus> y) \\<oplus> z\"\nproof -\n  have \"\\<And>x y. ad x \\<cdot> ad (x \\<cdot> y) = ad x\"\n    by (metis a_mult_idem am2 am4 mult_assoc)\n  thus ?thesis\n    by (metis a_add_comm am_add_op_def local.am3 local.am4 mult_assoc)\nqed\n\nlemma huntington [simp]: \"ad (x \\<oplus> y) \\<oplus> ad (x \\<oplus> ad y) = ad x\"\n  using a_add_idem am_add_op_def by auto\n\nlemma a_absorb1 [simp]: \"(ad x \\<oplus> ad y) \\<cdot> ad x = ad x\"\n  by (metis a_add_idem a_mult_idem am4 mult_assoc am_add_op_def)\n\nlemma a_absorb2 [simp]: \"ad x \\<oplus> ad x \\<cdot> ad y = ad x\"\nproof -\n  have \"ad (ad x) \\<cdot> ad (ad x \\<cdot> ad y) = ad (ad x)\"\n    by (metis (no_types) a_mult_idem local.am4 local.mult.semigroup_axioms semigroup.assoc)\n  then show ?thesis\n    using a_add_idem am_add_op_def by auto\nqed\n\ntext \\<open>The distributivity laws remain to be proved; our proofs follow those of Maddux~\\<^cite>\\<open>\"maddux\"\\<close>.\\<close>\n\nlemma prod_split [simp]: \"ad x \\<cdot> ad y \\<oplus> ad x \\<cdot> d y = ad x\"\n  using a_add_idem am_d_def am_add_op_def by auto\n\nlemma sum_split [simp]: \"(ad x \\<oplus> ad y) \\<cdot> (ad x \\<oplus> d y) = ad x\"\n  using a_add_idem am_d_def am_add_op_def by fastforce\n\nlemma a_comp_simp [simp]: \"(ad x \\<oplus> ad y) \\<cdot> d x = ad y \\<cdot> d x\"\nproof -\n  have f1: \"(ad x \\<oplus> ad y) \\<cdot> d x = ad (ad (ad x) \\<cdot> ad (ad y)) \\<cdot> ad (ad x) \\<cdot> ad (ad (ad y))\"\n    by (simp add: am_add_op_def am_d_def)\n  have f2: \"ad y = ad (ad (ad y))\"\n    using a_add_idem am_add_op_def by auto\n  have \"ad y = ad (ad (ad x) \\<cdot> ad (ad y)) \\<cdot> ad y\"\n    by (metis (no_types) a_absorb1 a_add_comm am_add_op_def)\n  then show ?thesis\n    using f2 f1 by (simp add: am_d_def local.am2 local.mult.semigroup_axioms semigroup.assoc)\nqed\n\nlemma a_distrib1: \"ad x \\<cdot> (ad y \\<oplus> ad z) = ad x \\<cdot> ad y \\<oplus> ad x \\<cdot> ad z\"\nproof -\n  have f1: \"\\<And>a. ad (ad (ad (a::'a)) \\<cdot> ad (ad a)) = ad a\"\n    using a_add_idem am_add_op_def by auto\n  have f2: \"\\<And>a aa. ad ((a::'a) \\<cdot> aa) \\<cdot> (a \\<cdot> ad aa) = ad (a \\<cdot> aa) \\<cdot> a\"\n    using local.am5 mult_assoc by auto\n  have f3: \"\\<And>a. ad (ad (ad (a::'a))) = ad a\"\n    using f1 by simp\n  have \"\\<And>a. ad (a::'a) \\<cdot> ad a = ad a\"\n    by simp\n  then have \"\\<And>a aa. ad (ad (ad (a::'a) \\<cdot> ad aa)) = ad aa \\<cdot> ad a\"\n    using f3 f2 by (metis (no_types) local.am2 local.am4 mult_assoc)\n  then have  \"ad x \\<cdot> (ad y \\<oplus> ad z) = ad x \\<cdot> (ad y \\<oplus> ad z) \\<cdot> ad y \\<oplus> ad x \\<cdot> (ad y \\<oplus> ad z) \\<cdot> d y\"\n    using am_add_op_def am_d_def local.am2 local.am4 by presburger\n  also have \"... = ad x \\<cdot> ad y \\<oplus> ad x \\<cdot> (ad y \\<oplus> ad z) \\<cdot> d y\"\n    by (simp add: mult_assoc)\n  also have \"... = ad x \\<cdot> ad y \\<oplus> ad x \\<cdot> ad z \\<cdot> d y\"\n    by (simp add: mult_assoc)\n  also have \"... = ad x \\<cdot> ad y \\<oplus> ad x \\<cdot> ad y \\<cdot> ad z \\<oplus> ad x \\<cdot> ad z \\<cdot> d y\"\n    by (metis a_add_idem a_mult_idem local.am4 mult_assoc am_add_op_def)\n  also have \"... = ad x \\<cdot> ad y \\<oplus> (ad x \\<cdot> ad z \\<cdot> ad y \\<oplus> ad x \\<cdot> ad z \\<cdot> d y)\"\n    by (metis am2 mult_assoc a_add_assoc)\n  finally show ?thesis\n    by (metis a_add_idem a_mult_idem am4 am_d_def am_add_op_def)\nqed\n\nlemma a_distrib2: \"ad x \\<oplus> ad y \\<cdot> ad z = (ad x \\<oplus> ad y) \\<cdot> (ad x \\<oplus> ad z)\"\nproof -\n  have f1: \"\\<And>a aa ab. ad (ad (ad (a::'a) \\<cdot> ad aa) \\<cdot> ad (ad a \\<cdot> ad ab)) = ad a \\<cdot> ad (ad (ad aa) \\<cdot> ad (ad ab))\"\n    using a_distrib1 am_add_op_def by auto\n  have \"\\<And>a. ad (ad (ad (a::'a))) = ad a\"\n    by (metis a_absorb2 a_mult_idem am_add_op_def)\n  then have \"ad (ad (ad x) \\<cdot> ad (ad y)) \\<cdot> ad (ad (ad x) \\<cdot> ad (ad z)) = ad (ad (ad x) \\<cdot> ad (ad y \\<cdot> ad z))\"\n    using f1 by (metis (full_types))\n  then show ?thesis\n    by (simp add: am_add_op_def)\nqed\n\nlemma aa_loc [simp]: \"d (x \\<cdot> d y) = d (x \\<cdot> y)\"\nproof -\n  have f1: \"x \\<cdot> d y \\<cdot> y = x \\<cdot> y\"\n    by (metis am3 mult_assoc am_d_def)\n  have f2: \"\\<And>w z. ad (w \\<cdot> z) \\<cdot> (w \\<cdot> ad z) = ad (w \\<cdot> z) \\<cdot> w\"\n    by (metis am5 mult_assoc)\n  hence f3: \"\\<And>z. ad (x \\<cdot> y) \\<cdot> (x \\<cdot> z) = ad (x \\<cdot> y) \\<cdot> (x \\<cdot> (ad (ad (ad y) \\<cdot> y) \\<cdot> z))\"\n    using f1 by (metis (no_types) mult_assoc am_d_def)\n  have \"ad (x \\<cdot> ad (ad y)) \\<cdot> (x \\<cdot> y) = 0\" using f1\n    by (metis am1 mult_assoc n_annil a_zero_def am_d_def)\n  thus ?thesis\n    by (metis a_d_zero am_d_def f3 local.am1 local.am2 local.am3 local.am4)\nqed\n\nlemma a_loc [simp]: \"ad (x \\<cdot> d y) = ad (x \\<cdot> y)\"\nproof -\n  have \"\\<And>a. ad (ad (ad (a::'a))) = ad a\"\n    using am_add_op_def am_d_def prod_split by auto\n  then show ?thesis\n    by (metis (full_types) aa_loc am_d_def)\nqed\n\nlemma d_a_export [simp]: \"d (ad x \\<cdot> y) = ad x \\<cdot> d y\"\nproof -\n  have f1: \"\\<And>a aa. ad ((a::'a) \\<cdot> ad (ad aa)) = ad (a \\<cdot> aa)\"\n    using a_loc am_d_def by auto\n  have \"\\<And>a. ad (ad (a::'a) \\<cdot> a) = 1\"\n    using a_d_one am_add_op_def am_d_def by auto\n  then have \"\\<And>a aa. ad (ad (ad (a::'a) \\<cdot> ad aa)) = ad a \\<cdot> ad aa\"\n    using f1 by (metis a_distrib2 am_add_op_def local.mult_1_left)\n  then show ?thesis\n    using f1 by (metis (no_types) am_d_def)\nqed\n\ntext \\<open>Every antidomain monoid is a domain monoid.\\<close>\n\nsublocale dm: domain_monoid am_d \"(\\<cdot>)\" 1\n  apply (unfold_locales)\n  apply (simp add: am_d_def)\n  apply simp\n  using am_d_def d_a_export apply auto[1]\n  by (simp add: am_d_def local.am2)\n\nlemma ds_ord_iso1: \"x \\<sqsubseteq> y \\<Longrightarrow> z \\<cdot> x \\<sqsubseteq> z \\<cdot> y\"\n(*nitpick [expect=genuine]*)\noops\n\nlemma a_very_costrict: \"ad x = 1 \\<longleftrightarrow> x = 0\"\nproof\n  assume a: \"ad x = 1\"\n  hence \"0 = ad x \\<cdot> x\"\n    using a_zero_def by force\n  thus \"x = 0\"\n    by (simp add: a)\nnext\n  assume \"x = 0\"\n  thus \"ad x = 1\"\n    using a_zero_def am_d_def dm.dom_one by auto\nqed\n\nlemma a_weak_loc: \"x \\<cdot> y = 0 \\<longleftrightarrow> x \\<cdot> d y = 0\"\nproof -\n  have \"x \\<cdot> y = 0 \\<longleftrightarrow> ad (x \\<cdot> y) = 1\"\n    by (simp add: a_very_costrict)\n  also have \"... \\<longleftrightarrow> ad (x \\<cdot> d y) = 1\"\n    by simp\n  finally show ?thesis\n    using a_very_costrict by blast\nqed\n\nlemma a_closure [simp]: \"d (ad x) = ad x\"\n  using a_add_idem am_add_op_def am_d_def by auto\n\nlemma a_d_mult_closure [simp]: \"d (ad x \\<cdot> ad y) = ad x \\<cdot> ad y\"\n  by simp\n\nlemma kat_3': \"d x \\<cdot> y \\<cdot> ad z = 0 \\<Longrightarrow> d x \\<cdot> y = d x \\<cdot> y \\<cdot> d z\"\n  by (metis dm.dom_one local.am5 local.mult_1_left a_zero_def am_d_def)\n\nlemma s4 [simp]: \"ad x \\<cdot> ad (ad x \\<cdot> y) = ad x \\<cdot> ad y\"\nproof -\n  have \"\\<And>a aa. ad (a::'a) \\<cdot> ad (ad aa) = ad (ad (ad a \\<cdot> aa))\"\n    using am_d_def d_a_export by presburger\n  then have \"\\<And>a aa. ad (ad (a::'a)) \\<cdot> ad aa = ad (ad (ad aa \\<cdot> a))\"\n    using local.am2 by presburger\n  then show ?thesis\n    by (metis a_comp_simp a_d_mult_closure am_add_op_def am_d_def local.am2)\nqed\n\nend\n\nclass antidomain_monoid = antidomain_left_monoid +\n  assumes am6 [simp]: \"x \\<cdot> ad 1 = ad 1\"\n\nbegin\n\nlemma kat_3_equiv: \"d x \\<cdot> y \\<cdot> ad z = 0 \\<longleftrightarrow> d x \\<cdot> y = d x \\<cdot> y \\<cdot> d z\"\n  apply standard\n  apply (metis kat_3')\n  by (simp add: mult_assoc a_zero_def am_d_def)\n\nno_notation a_zero (\"0\")\nno_notation am_d (\"d\")\n\nend\n\nsubsection \\<open>Antidomain Near-Semirings\\<close>\n\ntext \\<open>We define antidomain near-semirings. We do not consider units separately. The axioms are taken from~\\<^cite>\\<open>\"DesharnaisStruthAMAST\"\\<close>.\\<close>\n\nnotation zero_class.zero (\"0\")\n\nclass antidomain_near_semiring = ab_near_semiring_one_zerol + antidomain_op + plus_ord +\n  assumes ans1 [simp]: \"ad x \\<cdot> x = 0\"\n  and ans2 [simp]: \"ad (x \\<cdot> y) + ad (x \\<cdot> ad (ad y)) = ad (x \\<cdot> ad (ad y))\"\n  and ans3 [simp]: \"ad (ad x) + ad x = 1\"\n  and ans4 [simp]: \"ad (x + y) = ad x \\<cdot> ad y\"\n\nbegin\n\ndefinition ans_d :: \"'a \\<Rightarrow> 'a\" (\"d\") where\n   \"d x = ad (ad x)\"\n\nlemma a_a_one [simp]: \"d 1 = 1\"\nproof -\n  have \"d 1 = d 1 + 0\"\n    by simp\n  also have \"... = d 1 + ad 1\"\n    by (metis ans1 mult_1_right)\n  finally show ?thesis\n    by (simp add: ans_d_def)\nqed\n\nlemma a_very_costrict': \"ad x = 1 \\<longleftrightarrow> x = 0\"\nproof\n  assume \"ad x = 1\"\n  hence \"x = ad x \\<cdot> x\"\n    by simp\n  thus \"x = 0\"\n    by auto\nnext\n  assume \"x = 0\"\n  hence \"ad x = ad 0\"\n    by blast\n  thus \"ad x = 1\"\n    by (metis a_a_one ans_d_def local.ans1 local.mult_1_right)\nqed\n\nlemma one_idem [simp]: \"1 + 1 = 1\"\nproof -\n  have \"1 + 1 = d 1 + d 1\"\n    by simp\n  also have \"... = ad (ad 1 \\<cdot> 1) + ad (ad 1 \\<cdot> d 1)\"\n    using a_a_one ans_d_def by auto\n  also have \"... = ad (ad 1 \\<cdot> d 1)\"\n    using ans_d_def local.ans2 by presburger\n  also have \"... = ad (ad 1 \\<cdot> 1)\"\n    by simp\n  also have \"... = d 1\"\n    by (simp add: ans_d_def)\n  finally show ?thesis\n    by simp\nqed\n\ntext \\<open>Every antidomain near-semiring is automatically a dioid, and therefore ordered.\\<close>\n\nsubclass near_dioid_one_zerol\nproof\n  show \"\\<And>x. x + x = x\"\n  proof -\n    fix x\n    have \"x + x = 1 \\<cdot> x + 1 \\<cdot> x\"\n      by simp\n    also have \"... = (1 + 1) \\<cdot> x\"\n      using distrib_right' by presburger\n    finally show \"x + x = x\"\n      by simp\n  qed\nqed\n\nlemma d1_a [simp]: \"d x \\<cdot> x = x\"\nproof -\n  have \"x = (d x + ad x) \\<cdot> x\"\n    by (simp add: ans_d_def)\n  also have \"... = d x \\<cdot> x + ad x \\<cdot> x\"\n    using distrib_right' by blast\n  also have \"... = d x \\<cdot> x + 0\"\n    by simp\n  finally show ?thesis\n    by auto\nqed\n\nlemma a_comm: \"ad x \\<cdot> ad y = ad y \\<cdot> ad x\"\n  using add_commute ans4 by fastforce\n\nlemma a_subid: \"ad x \\<le> 1\"\n  using local.ans3 local.join.sup_ge2 by fastforce\n\nlemma a_subid_aux1: \"ad x \\<cdot> y \\<le> y\"\n  using a_subid mult_isor by fastforce\n\nlemma a_subdist: \"ad (x + y) \\<le> ad x\"\n  by (metis a_subid_aux1 ans4 add_comm)\n\nlemma a_antitone: \"x \\<le> y \\<Longrightarrow> ad y \\<le> ad x\"\n  using a_subdist local.order_prop by auto\n\n\n\nlemma a_gla1: \"ad x \\<cdot> y = 0 \\<Longrightarrow> ad x \\<le> ad y\"\nproof -\n  assume \"ad x \\<cdot> y = 0\"\n  hence a: \"ad x \\<cdot> d y = 0\"\n    by (metis a_subid a_very_costrict' ans_d_def local.ans2 local.join.sup.order_iff)\n  have \"ad x = (d y + ad y ) \\<cdot> ad x\"\n    by (simp add: ans_d_def)\n  also have \"... = d y \\<cdot> ad x + ad y \\<cdot> ad x\"\n    using distrib_right' by blast\n  also have \"... = ad x \\<cdot> d y + ad x \\<cdot> ad y\"\n    using a_comm ans_d_def by auto\n  also have \"... = ad x \\<cdot> ad y\"\n    by (simp add: a)\n  finally show \"ad x \\<le> ad y\"\n    by (metis a_subid_aux1)\nqed\n\nlemma a_gla2: \"ad x \\<le> ad y \\<Longrightarrow> ad x \\<cdot> y = 0\"\nproof -\n  assume \"ad x \\<le> ad y\"\n  hence \"ad x \\<cdot> y \\<le> ad y \\<cdot> y\"\n    using mult_isor by blast\n  thus ?thesis\n    by (simp add: join.le_bot)\nqed\n\nlemma a2_eq [simp]: \"ad (x \\<cdot> d y) = ad (x \\<cdot> y)\"\nproof (rule order.antisym)\n  show \"ad (x \\<cdot> y) \\<le> ad (x \\<cdot> d y)\"\n    by (simp add: ans_d_def local.less_eq_def)\nnext\n  show \"ad (x \\<cdot> d y) \\<le> ad (x \\<cdot> y)\"\n    by (metis a_gla1 a_mul_d ans1 d1_a mult_assoc)\nqed\n\nlemma a_export' [simp]: \"ad (ad x \\<cdot> y) = d x + ad y\"\nproof (rule order.antisym)\n  have \"ad (ad x \\<cdot> y) \\<cdot> ad x \\<cdot> d y = 0\"\n    by (simp add: a_gla2 local.mult.semigroup_axioms semigroup.assoc)\n  hence a: \"ad (ad x \\<cdot> y) \\<cdot> d y \\<le> ad (ad x)\"\n    by (metis a_comm a_gla1 ans4 mult_assoc ans_d_def)\n  have \"ad (ad x \\<cdot> y) = ad (ad x \\<cdot> y) \\<cdot> d y + ad (ad x \\<cdot> y) \\<cdot> ad y\"\n    by (metis (no_types) add_commute ans3 ans4 distrib_right' mult_onel ans_d_def)\n  thus \"ad (ad x \\<cdot> y) \\<le> d x + ad y\"\n    by (metis a_subid_aux1 a join.sup_mono ans_d_def)\nnext\n  show \"d x + ad y \\<le> ad (ad x \\<cdot> y)\"\n    by (metis a2_eq a_antitone a_comm a_subid_aux1 join.sup_least ans_d_def)\nqed\n\ntext \\<open>Every antidomain near-semiring is a domain near-semiring.\\<close>\n\nsublocale dnsz: domain_near_semiring_one_zerol \"(+)\" \"(\\<cdot>)\" 1 0 \"ans_d\" \"(\\<le>)\" \"(<)\"\n  apply (unfold_locales)\n  apply simp\n  using a2_eq ans_d_def apply auto[1]\n  apply (simp add: a_subid ans_d_def local.join.sup_absorb2)\n  apply (simp add: ans_d_def)\n  apply (simp add: a_comm ans_d_def)\n  using a_a_one a_very_costrict' ans_d_def by force\n\nlemma a_idem [simp]: \"ad x \\<cdot> ad x = ad x\"\nproof -\n  have \"ad x = (d x + ad x ) \\<cdot> ad x\"\n    by (simp add: ans_d_def)\n  also have \"... = d x \\<cdot> ad x + ad x \\<cdot> ad x\"\n    using distrib_right' by blast\n  finally show ?thesis\n    by (simp add: ans_d_def)\nqed\n\nlemma a_3_var [simp]: \"ad x \\<cdot> ad y \\<cdot> (x + y) = 0\"\n  by (metis ans1 ans4)\n\nlemma a_3 [simp]: \"ad x \\<cdot> ad y \\<cdot> d (x + y) = 0\"\n  by (metis a_mul_d ans4)\n\nlemma a_closure' [simp]: \"d (ad x) = ad x\"\nproof -\n  have \"d (ad x) = ad (1 \\<cdot> d x)\"\n    by (simp add: ans_d_def)\n  also have \"... = ad (1 \\<cdot> x)\"\n    using a2_eq by blast\n  finally show ?thesis\n    by simp\nqed\n\ntext \\<open>The following counterexamples show that some of the antidomain monoid axioms do not need to hold.\\<close>\n\nlemma \"x \\<cdot> ad 1 = ad 1\"\n(*nitpick [expect=genuine]*)\noops\n\nlemma \"ad (x \\<cdot> y) \\<cdot> ad (x \\<cdot> ad y) = ad x\"\n(*nitpick [expect=genuine]*)\noops\n\nlemma \"ad (x \\<cdot> y) \\<cdot> ad (x \\<cdot> ad y) = ad x\"\n(*nitpick [expect=genuine]*)\noops\n\nlemma phl_seq_inv: \"d v \\<cdot> x \\<cdot> y \\<cdot> ad w = 0 \\<Longrightarrow> \\<exists>z. d v \\<cdot> x \\<cdot> d z = 0 \\<and> ad z \\<cdot> y \\<cdot> ad w = 0\"\nproof -\n  assume \"d v \\<cdot> x \\<cdot> y \\<cdot> ad w = 0\"\n  hence \"d v \\<cdot> x \\<cdot> d (y \\<cdot> ad w) = 0 \\<and> ad (y \\<cdot> ad w) \\<cdot> y \\<cdot> ad w = 0\"\n    by (metis dnsz.dom_weakly_local local.ans1 mult_assoc)\n  thus \"\\<exists>z. d v \\<cdot> x \\<cdot> d z = 0 \\<and> ad z \\<cdot> y \\<cdot> ad w = 0\"\n    by blast\nqed\n\nlemma a_fixpoint: \"ad x = x \\<Longrightarrow> (\\<forall>y. y = 0)\"\nproof -\n  assume a1: \"ad x = x\"\n  { fix aa :: 'a\n    have \"aa = 0\"\n      using a1 by (metis (no_types) a_mul_d ans_d_def local.annil local.ans3 local.join.sup.idem local.mult_1_left)\n  }\n  then show ?thesis\n    by blast\nqed\n\nno_notation ans_d (\"d\")\n\nend\n\nsubsection \\<open>Antidomain Pre-Dioids\\<close>\n\ntext \\<open>Antidomain pre-diods are based on a different set of axioms, which are again taken from~\\<^cite>\\<open>\"DesharnaisStruthAMAST\"\\<close>.\\<close>\n\nclass antidomain_pre_dioid = pre_dioid_one_zerol + antidomain_op +\n  assumes apd1 [simp]: \"ad x \\<cdot> x = 0\"\n  and apd2 [simp]: \"ad (x \\<cdot> y) \\<le> ad (x \\<cdot> ad (ad y))\"\n  and apd3 [simp]: \"ad (ad x) + ad x = 1\"\n\nbegin\n\ndefinition apd_d :: \"'a \\<Rightarrow> 'a\" (\"d\") where\n   \"d x = ad (ad x)\"\n\nlemma a_very_costrict'': \"ad x = 1 \\<longleftrightarrow> x = 0\"\n  by (metis add_commute local.add_zerol order.antisym local.apd1 local.apd3 local.join.bot_least local.mult_1_right local.phl_skip)\n\nlemma a_subid': \"ad x \\<le> 1\"\n  using local.apd3 local.join.sup_ge2 by fastforce\n\nlemma d1_a' [simp]: \"d x \\<cdot> x = x\"\nproof -\n  have \"x = (d x + ad x) \\<cdot> x\"\n    by (simp add: apd_d_def)\n  also have \"... = d x \\<cdot> x + ad x \\<cdot> x\"\n    using distrib_right' by blast\n  also have \"... = d x \\<cdot> x + 0\"\n    by simp\n  finally show ?thesis\n    by auto\nqed\n\nlemma a_subid_aux1': \"ad x \\<cdot> y \\<le> y\"\n  using a_subid' mult_isor by fastforce\n\nlemma a_mul_d' [simp]: \"ad x \\<cdot> d x = 0\"\nproof -\n  have \"1 = ad (ad x \\<cdot> x)\"\n    using a_very_costrict'' by force\n  thus ?thesis\n    by (metis a_subid' a_very_costrict'' apd_d_def order.antisym local.apd2)\nqed\n\n\n\nlemma meet_ord_def: \"ad x \\<le> ad y \\<longleftrightarrow> ad x \\<cdot> ad y = ad x\"\n  by (metis a_d_closed a_subid_aux1' d1_a' order.eq_iff mult_1_right mult_isol)\n\nlemma d_weak_loc: \"x \\<cdot> y = 0 \\<longleftrightarrow> x \\<cdot> d y = 0\"\nproof -\n  have \"x \\<cdot> y = 0 \\<longleftrightarrow> ad (x \\<cdot> y) = 1\"\n    by (simp add: a_very_costrict'')\n  also have \"... \\<longleftrightarrow> ad (x \\<cdot> d y) = 1\"\n    by (metis apd1 apd2 a_subid' apd_d_def d1_a' order.eq_iff mult_1_left mult_assoc)\n  finally show ?thesis\n    by (simp add: a_very_costrict'')\nqed\n\nlemma gla_1: \"ad x \\<cdot> y = 0 \\<Longrightarrow> ad x \\<le> ad y\"\nproof -\n  assume \"ad x \\<cdot> y = 0\"\n  hence a: \"ad x \\<cdot> d y = 0\"\n    using d_weak_loc by force\n  hence \"d y = ad x \\<cdot> d y + d y\"\n    by simp\n  also have \"... = (1 + ad x) \\<cdot> d y\"\n    using join.sup_commute by auto\n  also have \"... = (d x + ad x) \\<cdot> d y\"\n    using apd_d_def calculation by auto\n  also have \"... = d x \\<cdot> d y\"\n    by (simp add: a join.sup_commute)\n  finally have \"d y \\<le> d x\"\n    by (metis apd_d_def a_subid' mult_1_right mult_isol)\n  hence \"d y \\<cdot> ad x = 0\"\n    by (metis apd_d_def a_d_closed a_mul_d' distrib_right' less_eq_def no_trivial_inverse)\n  hence \"ad x = ad y \\<cdot> ad x\"\n    by (metis apd_d_def apd3 add_0_left distrib_right' mult_1_left)\n  thus \"ad x \\<le> ad y\"\n    by (metis add_commute apd3 mult_oner subdistl)\nqed\n\nlemma a2_eq' [simp]: \"ad (x \\<cdot> d y) = ad (x \\<cdot> y)\"\nproof (rule order.antisym)\n  show \"ad (x \\<cdot> y) \\<le> ad (x \\<cdot> d y)\"\n    by (simp add: apd_d_def)\nnext\n  show \"ad (x \\<cdot> d y) \\<le> ad (x \\<cdot> y)\"\n    by (metis gla_1 apd1 a_mul_d' d1_a' mult_assoc)\nqed\n\nlemma a_supdist_var: \"ad (x + y) \\<le> ad x\"\n  by (metis gla_1 apd1 join.le_bot subdistl)\n\nlemma a_antitone': \"x \\<le> y \\<Longrightarrow> ad y \\<le> ad x\"\n  using a_supdist_var local.order_prop by auto\n\nlemma a_comm_var: \"ad x \\<cdot> ad y \\<le> ad y \\<cdot> ad x\"\nproof -\n  have \"ad x \\<cdot> ad y = d (ad x \\<cdot> ad y) \\<cdot> ad x \\<cdot> ad y\"\n    by (simp add: mult_assoc)\n  also have \"... \\<le> d (ad x \\<cdot> ad y) \\<cdot> ad x\"\n    using a_subid' mult_isol by fastforce\n  also have \"... \\<le> d (ad y) \\<cdot> ad x\"\n    by (simp add: a_antitone' a_subid_aux1' apd_d_def local.mult_isor)\n  finally show ?thesis\n    by simp\nqed\n\nlemma a_comm': \"ad x \\<cdot> ad y = ad y \\<cdot> ad x\"\n  by (simp add: a_comm_var order.eq_iff)\n\nlemma a_closed [simp]: \"d (ad x \\<cdot> ad y) = ad x \\<cdot> ad y\"\nproof -\n  have f1: \"\\<And>x y. ad x \\<le> ad (ad y \\<cdot> x)\"\n    by (simp add: a_antitone' a_subid_aux1')\n  have \"\\<And>x y. d (ad x \\<cdot> y) \\<le> ad x\"\n    by (metis a2_eq' a_antitone' a_comm' a_d_closed apd_d_def f1)\n  hence \"\\<And>x y. d (ad x \\<cdot> y) \\<cdot> y = ad x \\<cdot> y\"\n    by (metis d1_a' meet_ord_def mult_assoc apd_d_def)\n  thus ?thesis\n    by (metis f1 a_comm' apd_d_def meet_ord_def)\nqed\n\nlemma a_export'' [simp]: \"ad (ad x \\<cdot> y) = d x + ad y\"\nproof (rule order.antisym)\n  have \"ad (ad x \\<cdot> y) \\<cdot> ad x \\<cdot> d y = 0\"\n    using d_weak_loc mult_assoc by fastforce\n  hence a: \"ad (ad x \\<cdot> y) \\<cdot> d y \\<le> d x\"\n    by (metis a_closed a_comm' apd_d_def gla_1 mult_assoc)\n  have \"ad (ad x \\<cdot> y) = ad (ad x \\<cdot> y) \\<cdot> d y + ad (ad x \\<cdot> y) \\<cdot> ad y\"\n    by (metis apd3 a_comm' d1_a' distrib_right' mult_1_right apd_d_def)\n  thus \"ad (ad x \\<cdot> y) \\<le> d x + ad y\"\n    by (metis a_subid_aux1' a join.sup_mono)\nnext\n  have \"ad y \\<le> ad (ad x \\<cdot> y)\"\n    by (simp add: a_antitone' a_subid_aux1')\n  thus \"d x + ad y \\<le> ad (ad x \\<cdot> y)\"\n    by (metis apd_d_def a_mul_d' d1_a' gla_1 apd1 join.sup_least mult_assoc)\nqed\n\nlemma d1_sum_var: \"x + y \\<le> (d x + d y) \\<cdot> (x + y)\"\nproof -\n  have \"x + y = d x \\<cdot> x + d y \\<cdot> y\"\n    by simp\n  also have \"... \\<le> (d x + d y) \\<cdot> x + (d x + d y) \\<cdot> y\"\n    using local.distrib_right' local.join.sup_ge1 local.join.sup_ge2 local.join.sup_mono by presburger\n  finally show ?thesis\n    using order_trans subdistl_var by blast\nqed\n\nlemma a4': \"ad (x + y) = ad x \\<cdot> ad y\"\nproof (rule order.antisym)\n  show \"ad (x + y) \\<le> ad x \\<cdot> ad y\"\n    by (metis a_d_closed a_supdist_var add_commute d1_a' local.mult_isol_var)\n  hence \"ad x \\<cdot> ad y = ad x \\<cdot> ad y + ad (x + y)\"\n    using less_eq_def add_commute by simp\n  also have \"... = ad (ad (ad x \\<cdot> ad y) \\<cdot> (x + y))\"\n    by (metis a_closed a_export'')\n  finally show \"ad x \\<cdot> ad y \\<le> ad (x + y)\"\n    using a_antitone' apd_d_def d1_sum_var by auto\nqed\n\ntext \\<open>Antidomain pre-dioids are domain pre-dioids and antidomain near-semirings, but still not antidomain monoids.\\<close>\n\nsublocale dpdz: domain_pre_dioid_one_zerol \"(+)\" \"(\\<cdot>)\" 1 0 \"(\\<le>)\" \"(<)\" \"\\<lambda>x. ad (ad x)\"\n  apply (unfold_locales)\n  using apd_d_def d1_a' apply auto[1]\n  using a2_eq' apd_d_def apply auto[1]\n  apply (simp add: a_subid')\n  apply (simp add: a4' apd_d_def)\n  by (metis a_mul_d' a_very_costrict'' apd_d_def local.mult_onel)\n\nsubclass antidomain_near_semiring\n  apply (unfold_locales)\n  apply simp\n  using local.apd2 local.less_eq_def apply blast\n  apply simp\n  by (simp add: a4')\n\nlemma a_supdist: \"ad (x + y) \\<le> ad x + ad y\"\n  using a_supdist_var local.join.le_supI1 by auto\n\nlemma a_gla: \"ad x \\<cdot> y = 0 \\<longleftrightarrow> ad x \\<le> ad y\"\n  using gla_1 a_gla2 by blast\n\nlemma a_subid_aux2: \"x \\<cdot> ad y \\<le> x\"\n  using a_subid' mult_isol by fastforce\n\nlemma a42_var: \"d x \\<cdot> d y \\<le> ad (ad x + ad y)\"\n  by (simp add: apd_d_def)\n\nlemma d1_weak [simp]: \"(d x + d y) \\<cdot> x = x\"\nproof -\n  have \"(d x + d y) \\<cdot> x = (1 + d y) \\<cdot> x\"\n    by simp\n  thus ?thesis\n   by (metis add_commute apd_d_def dpdz.dnso3 local.mult_1_left)\nqed\n\nlemma \"x \\<cdot> ad 1 = ad 1\"\n(*nitpick [expect=genuine]*)\noops\n\nlemma \"ad x \\<cdot> (y + z) = ad x \\<cdot> y + ad x \\<cdot> z\"\n(*nitpick [expect=genuine]*)\noops\n\nlemma \"ad (x \\<cdot> y) \\<cdot> ad (x \\<cdot> ad y) = ad x\"\n(*nitpick [expect=genuine]*)\noops\n\nlemma \"ad (x \\<cdot> y) \\<cdot> ad (x \\<cdot> ad y) = ad x\"\n(*nitpick [expect=genuine]*)\noops\n\nno_notation apd_d (\"d\")\n\nend\n\nsubsection \\<open>Antidomain Semirings\\<close>\n\ntext \\<open>Antidomain semirings are direct expansions of antidomain pre-dioids, but do not require idempotency of addition. Hence we give a slightly different axiomatisation, following~\\<^cite>\\<open>\"DesharnaisStruthSCP\"\\<close>.\\<close>\n\nclass antidomain_semiringl = semiring_one_zerol + plus_ord + antidomain_op +\n  assumes as1 [simp]: \"ad x \\<cdot> x = 0\"\n  and as2 [simp]: \"ad (x \\<cdot> y) + ad (x \\<cdot> ad (ad y)) = ad (x \\<cdot> ad (ad y))\"\n  and as3 [simp]: \"ad (ad x) + ad x = 1\"\n\nbegin\n\ndefinition ads_d :: \"'a \\<Rightarrow> 'a\" (\"d\") where\n  \"d x = ad (ad x)\"\n\nlemma one_idem': \"1 + 1 = 1\"\n  by (metis as1 as2 as3 add_zeror mult.right_neutral)\n\ntext \\<open>Every antidomain semiring is a dioid and an antidomain pre-dioid.\\<close>\n\nsubclass dioid\n  by (standard, metis distrib_left mult.right_neutral one_idem')\n\nsubclass antidomain_pre_dioid\n  by (unfold_locales, auto simp: local.less_eq_def)\n\nlemma am5_lem [simp]: \"ad (x \\<cdot> y) \\<cdot> ad (x \\<cdot> ad y) = ad x\"\nproof -\n  have \"ad (x \\<cdot> y ) \\<cdot> ad (x \\<cdot> ad y) = ad (x \\<cdot> d y) \\<cdot> ad (x \\<cdot> ad y)\"\n    using ads_d_def local.a2_eq' local.apd_d_def by auto\n  also have \"... = ad (x \\<cdot> d y + x \\<cdot> ad y)\"\n    using ans4 by presburger\n  also have \"... = ad (x \\<cdot> (d y + ad y))\"\n    using distrib_left by presburger\n  finally show ?thesis\n    by (simp add: ads_d_def)\nqed\n\nlemma am6_lem [simp]: \"ad (x \\<cdot> y) \\<cdot> x \\<cdot> ad y = ad (x \\<cdot> y) \\<cdot> x\"\nproof -\n  fix x y\n  have \"ad (x \\<cdot> y) \\<cdot> x \\<cdot> ad y = ad (x \\<cdot> y) \\<cdot> x \\<cdot> ad y + 0\"\n    by simp\n  also have \"... = ad (x \\<cdot> y) \\<cdot> x \\<cdot> ad y + ad (x \\<cdot> d y) \\<cdot> x \\<cdot> d y\"\n    using ans1 mult_assoc by presburger\n  also have \"... = ad (x \\<cdot> y) \\<cdot> x \\<cdot> (ad y + d y)\"\n    using ads_d_def local.a2_eq' local.apd_d_def local.distrib_left by auto\n  finally show \"ad (x \\<cdot> y) \\<cdot> x \\<cdot> ad y = ad (x \\<cdot> y) \\<cdot> x\"\n    using add_commute ads_d_def local.as3 by auto\nqed\n\nlemma a_zero [simp]: \"ad 0 = 1\"\n  by (simp add: local.a_very_costrict'')\n\nlemma a_one [simp]: \"ad 1 = 0\"\n  using a_zero local.dpdz.dpd5 by blast\n\nsubclass antidomain_left_monoid\n  by (unfold_locales, auto simp:  local.a_comm')\n\ntext \\<open>Every antidomain left semiring is a domain left semiring.\\<close>\n\nno_notation domain_semiringl_class.fd (\"( |_\\<rangle> _)\" [61,81] 82)\n\ndefinition fdia :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a\" (\"( |_\\<rangle> _)\" [61,81] 82) where\n  \"|x\\<rangle> y = ad (ad (x \\<cdot> y))\"\n\nsublocale ds: domain_semiringl \"(+)\" \"(\\<cdot>)\" 1 0 \"\\<lambda>x. ad (ad x)\" \"(\\<le>)\" \"(<)\"\n  rewrites \"ds.fd x y \\<equiv> fdia x y\"\nproof -\n  show \"class.domain_semiringl (+) (\\<cdot>) 1 0 (\\<lambda>x. ad (ad x)) (\\<le>) (<) \"\n    by (unfold_locales, auto simp: local.dpdz.dpd4 ans_d_def)\n  then interpret ds: domain_semiringl \"(+)\" \"(\\<cdot>)\" 1 0 \"\\<lambda>x. ad (ad x)\" \"(\\<le>)\" \"(<)\" .\n  show \"ds.fd x y \\<equiv> fdia x y\"\n    by (auto simp: fdia_def ds.fd_def)\nqed\n\nlemma fd_eq_fdia [simp]: \"domain_semiringl.fd (\\<cdot>) d x y \\<equiv> fdia x y\"\nproof -\n  have \"class.domain_semiringl (+) (\\<cdot>) 1 0 d (\\<le>) (<)\"\n    by (unfold_locales, auto simp: ads_d_def local.ans_d_def)\n  hence \"domain_semiringl.fd (\\<cdot>) d x y = d ((\\<cdot>) x y)\"\n    by (rule domain_semiringl.fd_def)\n  also have \"... = ds.fd x y\"\n    by (simp add: ds.fd_def ads_d_def)\n  finally show \"domain_semiringl.fd (\\<cdot>) d x y \\<equiv> |x\\<rangle> y\"\n    by auto\nqed\n\nend\n\nclass antidomain_semiring = antidomain_semiringl + semiring_one_zero\n\nbegin\n\ntext \\<open>Every antidomain semiring is an antidomain monoid.\\<close>\n\nsubclass antidomain_monoid\n  by (standard, metis ans1 mult_1_right annir)\n\nlemma \"a_zero = 0\"\n  by (simp add: local.a_zero_def)\n\nsublocale ds: domain_semiring \"(+)\" \"(\\<cdot>)\" 1 0 \"\\<lambda>x. ad (ad x)\" \"(\\<le>)\" \"(<)\"\n  rewrites \"ds.fd x y \\<equiv> fdia x y\"\n  by unfold_locales\n\nend\n\nsubsection \\<open>The Boolean Algebra of Domain Elements\\<close>\n\ntypedef (overloaded) 'a a2_element = \"{x :: 'a :: antidomain_semiring. x = d x}\"\n  by (rule_tac x=1 in exI, auto simp: ads_d_def)\n\nsetup_lifting type_definition_a2_element\n\ninstantiation a2_element :: (antidomain_semiring) boolean_algebra\n\nbegin\n\nlift_definition less_eq_a2_element :: \"'a a2_element \\<Rightarrow> 'a a2_element \\<Rightarrow> bool\" is \"(\\<le>)\" .\n\nlift_definition less_a2_element :: \"'a a2_element \\<Rightarrow> 'a a2_element \\<Rightarrow> bool\" is \"(<)\" .\n\nlift_definition bot_a2_element :: \"'a a2_element\" is 0\n  by (simp add: ads_d_def)\n\nlift_definition top_a2_element :: \"'a a2_element\" is 1\n  by (simp add: ads_d_def)\n\nlift_definition inf_a2_element :: \"'a a2_element \\<Rightarrow> 'a a2_element \\<Rightarrow> 'a a2_element\" is \"(\\<cdot>)\"\n  by (metis (no_types, lifting) ads_d_def dpdz.dom_mult_closed)\n\nlift_definition sup_a2_element :: \"'a a2_element \\<Rightarrow> 'a a2_element \\<Rightarrow> 'a a2_element\" is \"(+)\"\n  by (metis ads_d_def ds.dsr5)\n\nlift_definition minus_a2_element :: \"'a a2_element \\<Rightarrow> 'a a2_element \\<Rightarrow> 'a a2_element\" is \"\\<lambda>x y. x \\<cdot> ad y\"\n  by (metis (no_types, lifting) ads_d_def dpdz.domain_export'')\n\nlift_definition uminus_a2_element :: \"'a a2_element \\<Rightarrow> 'a a2_element\" is antidomain_op\n  by (simp add: ads_d_def)\n\ninstance\n  apply (standard; transfer)\n  apply (simp add: less_le_not_le)\n  apply simp\n  apply auto[1]\n  apply simp\n  apply (metis a_subid_aux2 ads_d_def)\n  apply (metis a_subid_aux1' ads_d_def)\n  apply (metis (no_types, lifting) ads_d_def dpdz.dom_glb)\n  apply simp\n  apply simp\n  apply simp\n  apply simp\n  apply (metis a_subid' ads_d_def)\n  apply (metis (no_types, lifting) ads_d_def dpdz.dom_distrib)\n  apply (metis ads_d_def ans1)\n  apply (metis ads_d_def ans3)\n  by simp\n\nend\n\nsubsection \\<open>Further Properties\\<close>\n\ncontext antidomain_semiringl\n\nbegin\n\nlemma a_2_var: \"ad x \\<cdot> d y = 0 \\<longleftrightarrow> ad x \\<le> ad y\"\n  using local.a_gla local.ads_d_def local.dpdz.dom_weakly_local by auto\n\ntext \\<open>The following two lemmas give the Galois connection of Heyting algebras.\\<close>\n\nlemma da_shunt1: \"x \\<le> d y + z \\<Longrightarrow> x \\<cdot> ad y \\<le> z\"\nproof -\n  assume \"x \\<le> d y + z\"\n  hence \"x \\<cdot> ad y \\<le> (d y + z) \\<cdot> ad y\"\n    using mult_isor by blast\n  also have \"... = d y \\<cdot> ad y + z \\<cdot> ad y\"\n    by simp\n  also have \"... \\<le> z\"\n    by (simp add: a_subid_aux2 ads_d_def)\n  finally show \"x \\<cdot> ad y \\<le> z\"\n    by simp\nqed\n\nlemma da_shunt2: \"x \\<le> ad y + z \\<Longrightarrow> x \\<cdot> d y \\<le> z\"\n  using da_shunt1 local.a_add_idem local.ads_d_def am_add_op_def by auto\n\nlemma d_a_galois1: \"d x \\<cdot> ad y \\<le> d z \\<longleftrightarrow> d x \\<le> d z + d y\"\n  by (metis add_assoc local.a_gla local.ads_d_def local.am2 local.ans4 local.ans_d_def local.dnsz.dnso4)\n\nlemma d_a_galois2: \"d x \\<cdot> d y \\<le> d z \\<longleftrightarrow> d x \\<le> d z + ad y\"\nproof -\n  have \"\\<And>a aa. ad ((a::'a) \\<cdot> ad (ad aa)) = ad (a \\<cdot> aa)\"\n    using local.a2_eq' local.apd_d_def by force\n  then show ?thesis\n    by (metis d_a_galois1 local.a_export' local.ads_d_def local.ans_d_def)\nqed\n\nlemma d_cancellation_1: \"d x \\<le> d y + d x \\<cdot> ad y\"\nproof -\n  have a: \"d (d x \\<cdot> ad y) = ad y \\<cdot> d x\"\n    using local.a_closure' local.ads_d_def local.am2 local.ans_d_def by auto\n  hence \"d x \\<le> d (d x \\<cdot> ad y) + d y\"\n    using d_a_galois1 local.a_comm_var local.ads_d_def by fastforce\n  thus ?thesis\n    using a add_commute local.ads_d_def local.am2 by auto\nqed\n\nlemma d_cancellation_2: \"(d z + d y) \\<cdot> ad y \\<le> d z\"\n  by (simp add: da_shunt1)\n\nlemma a_de_morgan: \"ad (ad x \\<cdot> ad y) = d (x + y)\"\n  by (simp add: local.ads_d_def)\n\nlemma a_de_morgan_var_3: \"ad (d x + d y) = ad x \\<cdot> ad y\"\n  using local.a_add_idem local.ads_d_def am_add_op_def by auto\n\nlemma a_de_morgan_var_4: \"ad (d x \\<cdot> d y) = ad x + ad y\"\n  using local.a_add_idem local.ads_d_def am_add_op_def by auto\n\nlemma a_4: \"ad x \\<le> ad (x \\<cdot> y)\"\n  using local.a_add_idem local.a_antitone' local.dpdz.domain_1'' am_add_op_def by fastforce\n\nlemma a_6: \"ad (d x \\<cdot> y) = ad x + ad y\"\n  using a_de_morgan_var_4 local.ads_d_def by auto\n\nlemma a_7: \"d x \\<cdot> ad (d y + d z) = d x \\<cdot> ad y \\<cdot> ad z\"\n  using a_de_morgan_var_3 local.mult.semigroup_axioms semigroup.assoc by fastforce\n\nlemma a_d_add_closure [simp]: \"d (ad x + ad y) = ad x + ad y\"\n  using local.a_add_idem local.ads_d_def am_add_op_def by auto\n\nlemma d_6 [simp]: \"d x + ad x \\<cdot> d y = d x + d y\"\nproof -\n  have \"ad (ad x \\<cdot> (x + ad y)) = d (x + y)\"\n    by (simp add: distrib_left ads_d_def)\n  thus ?thesis\n    by (simp add: local.ads_d_def local.ans_d_def)\nqed\n\nlemma d_7 [simp]: \"ad x + d x \\<cdot> ad y = ad x + ad y\"\n  by (metis a_d_add_closure local.ads_d_def local.ans4 local.s4)\n\nlemma a_mult_add: \"ad x \\<cdot> (y + x) = ad x \\<cdot> y\"\n  by (simp add: distrib_left)\n\nlemma kat_2: \"y \\<cdot> ad z \\<le> ad x \\<cdot> y \\<Longrightarrow> d x \\<cdot> y \\<cdot> ad z = 0\"\nproof -\n  assume a: \"y \\<cdot> ad z \\<le> ad x \\<cdot> y\"\n  hence \"d x \\<cdot> y \\<cdot> ad z \\<le> d x \\<cdot> ad x \\<cdot> y\"\n    using local.mult_isol mult_assoc by presburger\n  thus ?thesis\n    using local.join.le_bot ads_d_def by auto\nqed\n\nlemma kat_3: \"d x \\<cdot> y \\<cdot> ad z = 0 \\<Longrightarrow> d x \\<cdot> y = d x \\<cdot> y \\<cdot> d z\"\n  using local.a_zero_def local.ads_d_def local.am_d_def local.kat_3' by auto\n\nlemma kat_4: \"d x \\<cdot> y = d x \\<cdot> y \\<cdot> d z \\<Longrightarrow> d x \\<cdot> y \\<le> y \\<cdot> d z\"\n  using a_subid_aux1 mult_assoc ads_d_def by auto\n\nlemma kat_2_equiv: \"y \\<cdot> ad z \\<le> ad x \\<cdot> y \\<longleftrightarrow> d x \\<cdot> y \\<cdot> ad z = 0\"\nproof\n  assume \"y \\<cdot> ad z \\<le> ad x \\<cdot> y\"\n  thus \"d x \\<cdot> y \\<cdot> ad z = 0\"\n    by (simp add: kat_2)\nnext\n  assume 1: \"d x \\<cdot> y \\<cdot> ad z = 0\"\n  have \"y \\<cdot> ad z = (d x + ad x) \\<cdot> y \\<cdot> ad z\"\n    by (simp add: local.ads_d_def)\n  also have \"... = d x \\<cdot> y \\<cdot> ad z + ad x \\<cdot> y \\<cdot> ad z\"\n    using local.distrib_right by presburger\n  also have \"... = ad x \\<cdot> y \\<cdot> ad z\"\n    using \"1\" by auto\n  also have \"... \\<le> ad x \\<cdot> y\"\n    by (simp add: local.a_subid_aux2)\n  finally show \"y \\<cdot> ad z \\<le> ad x \\<cdot> y\" .\nqed\n\nlemma kat_4_equiv: \"d x \\<cdot> y = d x \\<cdot> y \\<cdot> d z \\<longleftrightarrow> d x \\<cdot> y \\<le> y \\<cdot> d z\"\n  using local.ads_d_def local.dpdz.d_preserves_equation by auto\n\nlemma kat_3_equiv_opp: \"ad z \\<cdot> y \\<cdot> d x = 0 \\<longleftrightarrow> y \\<cdot> d x = d z \\<cdot> y \\<cdot> d x\"\nproof -\n  have \"ad z \\<cdot> (y \\<cdot> d x) = 0 \\<longrightarrow> (ad z \\<cdot> y \\<cdot> d x = 0) = (y \\<cdot> d x = d z \\<cdot> y \\<cdot> d x)\"\n    by (metis (no_types, opaque_lifting) add_commute local.add_zerol local.ads_d_def local.as3 local.distrib_right' local.mult_1_left mult_assoc)\n  thus ?thesis\n    by (metis a_4 local.a_add_idem local.a_gla2 local.ads_d_def mult_assoc am_add_op_def)\nqed\n\nlemma kat_4_equiv_opp: \"y \\<cdot> d x = d z \\<cdot> y \\<cdot> d x \\<longleftrightarrow> y \\<cdot> d x \\<le> d z \\<cdot> y\"\n  using kat_2_equiv kat_3_equiv_opp local.ads_d_def by auto\n\nsubsection \\<open>Forward Box and Diamond Operators\\<close>\n\nlemma fdemodalisation22: \"|x\\<rangle> y \\<le> d z \\<longleftrightarrow> ad z \\<cdot> x \\<cdot> d y = 0\"\nproof -\n  have \"|x\\<rangle> y \\<le> d z \\<longleftrightarrow> d (x \\<cdot> y) \\<le> d z\"\n    by (simp add: fdia_def ads_d_def)\n  also have \"... \\<longleftrightarrow> ad z \\<cdot> d (x \\<cdot> y) = 0\"\n    by (metis add_commute local.a_gla local.ads_d_def local.ans4)\n  also have \"... \\<longleftrightarrow> ad z \\<cdot> x \\<cdot> y = 0\"\n    using dpdz.dom_weakly_local mult_assoc ads_d_def by auto\n  finally show ?thesis\n    using dpdz.dom_weakly_local ads_d_def by auto\nqed\n\nlemma dia_diff_var: \"|x\\<rangle> y \\<le> |x\\<rangle> (d y \\<cdot> ad z) + |x\\<rangle> z\"\nproof -\n  have 1: \"|x\\<rangle> (d y \\<cdot> d z) \\<le> |x\\<rangle> (1 \\<cdot> d z)\"\n    using dpdz.dom_glb_eq ds.fd_subdist fdia_def ads_d_def by force\n  have \"|x\\<rangle> y = |x\\<rangle> (d y \\<cdot> (ad z + d z))\"\n    by (metis as3 add_comm ds.fdia_d_simp mult_1_right ads_d_def)\n  also have \"... = |x\\<rangle> (d y \\<cdot> ad z) + |x\\<rangle> (d y \\<cdot> d z)\"\n    by (simp add: local.distrib_left local.ds.fdia_add1)\n  also have \"... \\<le> |x\\<rangle> (d y \\<cdot> ad z) + |x\\<rangle> (1 \\<cdot> d z)\"\n    using \"1\" local.join.sup.mono by blast\n  finally show ?thesis\n    by (simp add: fdia_def ads_d_def)\nqed\n\nlemma dia_diff: \"|x\\<rangle> y \\<cdot> ad ( |x\\<rangle> z ) \\<le> |x\\<rangle> (d y \\<cdot> ad z)\"\n  using fdia_def dia_diff_var d_a_galois2 ads_d_def by metis\n\nlemma fdia_export_2: \"ad y \\<cdot> |x\\<rangle> z = |ad y \\<cdot> x\\<rangle> z\"\n  using local.am_d_def local.d_a_export local.fdia_def mult_assoc by auto\n\nlemma fdia_split: \"|x\\<rangle> y = d z \\<cdot> |x\\<rangle> y + ad z \\<cdot> |x\\<rangle> y\"\n  by (metis mult_onel ans3 distrib_right ads_d_def)\n\ndefinition fbox :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a\" (\"( |_] _)\" [61,81] 82) where\n  \"|x] y = ad (x \\<cdot> ad y)\"\n\ntext \\<open>The next lemmas establish the De Morgan duality between boxes and diamonds.\\<close>\n\nlemma fdia_fbox_de_morgan_2: \"ad ( |x\\<rangle> y) = |x] ad y\"\n  using fbox_def local.a_closure local.a_loc local.am_d_def local.fdia_def by auto\n\nlemma fbox_simp: \"|x] y = |x] d y\"\n  using fbox_def local.a_add_idem local.ads_d_def am_add_op_def by auto\n\nlemma fbox_dom [simp]: \"|x] 0 = ad x\"\n  by (simp add: fbox_def)\n\nlemma fbox_add1: \"|x] (d y \\<cdot> d z) = |x] y \\<cdot> |x] z\"\n  using a_de_morgan_var_4 fbox_def local.distrib_left by auto\n\nlemma fbox_add2: \"|x + y] z = |x] z \\<cdot> |y] z\"\n  by (simp add: fbox_def)\n\nlemma fbox_mult: \"|x \\<cdot> y] z = |x] |y] z\"\n  using fbox_def local.a2_eq' local.apd_d_def mult_assoc by auto\n\nlemma fbox_zero [simp]: \"|0] x = 1\"\n  by (simp add: fbox_def)\n\nlemma fbox_one [simp]: \"|1] x = d x\"\n  by (simp add: fbox_def ads_d_def)\n\nlemma fbox_iso: \"d x \\<le> d y \\<Longrightarrow> |z] x \\<le> |z] y\"\nproof -\n  assume \"d x \\<le> d y\"\n  hence \"ad y \\<le> ad x\"\n    using local.a_add_idem local.a_antitone' local.ads_d_def am_add_op_def by fastforce\n  hence \"z \\<cdot> ad y \\<le> z \\<cdot> ad x\"\n    by (simp add: mult_isol)\n  thus \"|z] x \\<le> |z] y\"\n    by (simp add: fbox_def a_antitone')\nqed\n\nlemma fbox_antitone_var: \"x \\<le> y \\<Longrightarrow> |y] z \\<le> |x] z\"\n  by (simp add: fbox_def a_antitone mult_isor)\n\nlemma fbox_subdist_1: \"|x] (d y \\<cdot> d z) \\<le> |x] y\"\n  using a_de_morgan_var_4 fbox_def local.a_supdist_var local.distrib_left by force\n\nlemma fbox_subdist_2: \"|x] y \\<le>|x] (d y + d z)\"\n  by (simp add: fbox_iso ads_d_def)\n\n\n\nlemma fbox_diff_var: \"|x] (d y + ad z) \\<cdot> |x] z \\<le> |x] y\"\nproof -\n  have \"ad (ad y) \\<cdot> ad (ad z) = ad (ad z + ad y)\"\n    using local.dpdz.dsg4 by auto\n  then have \"d (d (d y + ad z) \\<cdot> d z) \\<le> d y\"\n    by (simp add: local.a_subid_aux1' local.ads_d_def)\n  then show ?thesis\n    by (metis fbox_add1 fbox_iso)\nqed\n\nlemma fbox_diff: \"|x] (d y + ad z) \\<le> |x] y + ad ( |x] z )\"\nproof -\n  have f1: \"\\<And>a. ad (ad (ad (a::'a))) = ad a\"\n    using local.a_closure' local.ans_d_def by force\n  have f2: \"\\<And>a aa. ad (ad (a::'a)) + ad aa = ad (ad a \\<cdot> aa)\"\n    using local.ans_d_def by auto\n  have f3: \"\\<And>a aa. ad ((a::'a) + aa) = ad (aa + a)\"\n    by (simp add: local.am2)\n  then have f4: \"\\<And>a aa. ad (ad (ad (a::'a) \\<cdot> aa)) = ad (ad aa + a)\"\n    using f2 f1 by (metis (no_types) local.ans4)\n  have f5: \"\\<And>a aa ab. ad ((a::'a) \\<cdot> (aa + ab)) = ad (a \\<cdot> (ab + aa))\"\n    using f3 local.distrib_left by presburger\n  have f6: \"\\<And>a aa. ad (ad (ad (a::'a) + aa)) = ad (ad aa \\<cdot> a)\"\n    using f3 f1 by fastforce\n  have \"ad (x \\<cdot> ad (y + ad z)) \\<le> ad (ad (x \\<cdot> ad z) \\<cdot> (x \\<cdot> ad y))\"\n    using f5 f2 f1 by (metis (no_types) a_mult_add fbox_def fbox_subdist_1 local.a_gla2 local.ads_d_def local.ans4 local.distrib_left local.gla_1 mult_assoc)\n  then show ?thesis\n    using f6 f4 f3 f1 by (simp add: fbox_def local.ads_d_def)\nqed\n\nend\n\ncontext antidomain_semiring\n\nbegin\n\nlemma kat_1: \"d x \\<cdot> y \\<le> y \\<cdot> d z \\<Longrightarrow> y \\<cdot> ad z \\<le> ad x \\<cdot> y\"\nproof -\n  assume a: \"d x \\<cdot> y \\<le> y \\<cdot> d z\"\n  have \"y \\<cdot> ad z = d x \\<cdot> y \\<cdot> ad z + ad x \\<cdot> y \\<cdot> ad z\"\n    by (metis local.ads_d_def local.as3 local.distrib_right local.mult_1_left)\n  also have \"... \\<le> y \\<cdot> (d z \\<cdot> ad z) + ad x \\<cdot> y \\<cdot> ad z\"\n    by (metis a add_iso mult_isor mult_assoc)\n  also have \"... = ad x \\<cdot> y \\<cdot> ad z\"\n    by (simp add: ads_d_def)\n  finally show \"y \\<cdot> ad z \\<le> ad x \\<cdot> y\"\n    using local.a_subid_aux2 local.dual_order.trans by blast\nqed\n\nlemma kat_1_equiv: \"d x \\<cdot> y \\<le> y \\<cdot> d z \\<longleftrightarrow> y \\<cdot> ad z \\<le> ad x \\<cdot> y\"\n  using kat_1 kat_2 kat_3 kat_4 by blast\n\nlemma kat_3_equiv': \"d x \\<cdot> y \\<cdot> ad z = 0 \\<longleftrightarrow> d x \\<cdot> y = d x \\<cdot> y \\<cdot> d z\"\n  by (simp add: kat_1_equiv local.kat_2_equiv local.kat_4_equiv)\n\nlemma kat_1_equiv_opp: \"y \\<cdot> d x \\<le> d z \\<cdot> y \\<longleftrightarrow> ad z \\<cdot> y \\<le> y \\<cdot> ad x\"\n  by (metis kat_1_equiv local.a_closure' local.ads_d_def local.ans_d_def)\n\nlemma kat_2_equiv_opp: \"ad z \\<cdot> y \\<le> y \\<cdot> ad x \\<longleftrightarrow> ad z \\<cdot> y \\<cdot> d x = 0\"\n  by (simp add: kat_1_equiv_opp local.kat_3_equiv_opp local.kat_4_equiv_opp)\n\nlemma fbox_one_1 [simp]: \"|x] 1 = 1\"\n  by (simp add: fbox_def)\n\nlemma fbox_demodalisation3: \"d y \\<le> |x] d z \\<longleftrightarrow> d y \\<cdot> x \\<le> x \\<cdot> d z\"\n  by (simp add: fbox_def a_gla kat_2_equiv_opp mult_assoc ads_d_def)\n\nend\n\nsubsection \\<open>Antidomain Kleene Algebras\\<close>\n\nclass antidomain_left_kleene_algebra = antidomain_semiringl + left_kleene_algebra_zerol\n\nbegin\n\nsublocale dka: domain_left_kleene_algebra \"(+)\" \"(\\<cdot>)\" 1 0 d \"(\\<le>)\" \"(<)\" star\n  rewrites \"domain_semiringl.fd (\\<cdot>) d x y \\<equiv> |x\\<rangle> y\"\n  by (unfold_locales, auto simp add: local.ads_d_def ans_d_def)\n\n\n\nlemma fbox_star_unfold [simp]: \"|1] z \\<cdot> |x] |x\\<^sup>\\<star>] z = |x\\<^sup>\\<star>] z\"\nproof -\n  have \"ad (ad z + x \\<cdot> (x\\<^sup>\\<star> \\<cdot> ad z)) = ad (x\\<^sup>\\<star> \\<cdot> ad z)\"\n    using local.conway.dagger_unfoldl_distr mult_assoc by auto\n  then show ?thesis\n    using local.a_closure' local.ans_d_def local.fbox_def local.fdia_def local.fdia_fbox_de_morgan_2 by fastforce\nqed\n\nlemma fbox_star_unfold_var [simp]: \"d z \\<cdot> |x] |x\\<^sup>\\<star>] z = |x\\<^sup>\\<star>] z\"\n  using fbox_star_unfold by auto\n\nlemma fbox_star_unfoldr [simp]: \"|1] z \\<cdot> |x\\<^sup>\\<star>] |x] z = |x\\<^sup>\\<star>] z\"\n  by (metis fbox_star_unfold fbox_mult star_slide_var)\n\nlemma fbox_star_unfoldr_var [simp]: \"d z \\<cdot> |x\\<^sup>\\<star>] |x] z = |x\\<^sup>\\<star>] z\"\n  using fbox_star_unfoldr by auto\n\nlemma fbox_star_induct_var: \"d y \\<le> |x] y \\<Longrightarrow> d y \\<le> |x\\<^sup>\\<star>] y\"\nproof -\n  assume a1: \"d y \\<le> |x] y\"\n  have \"\\<And>a. ad (ad (ad (a::'a))) = ad a\"\n    using local.a_closure' local.ans_d_def by auto\n  then have \"ad (ad (x\\<^sup>\\<star> \\<cdot> ad y)) \\<le> ad y\"\n    using a1 by (metis dka.fdia_star_induct local.a_export' local.ads_d_def local.ans4 local.ans_d_def local.eq_refl local.fbox_def local.fdia_def local.meet_ord_def)\n  then have \"ad (ad y + ad (x\\<^sup>\\<star> \\<cdot> ad y)) = zero_class.zero\"\n    by (metis (no_types) add_commute local.a_2_var local.ads_d_def local.ans4)\n  then show ?thesis\n    using local.a_2_var local.ads_d_def local.fbox_def by auto\nqed\n\nlemma fbox_star_induct: \"d y \\<le> d z \\<cdot> |x] y \\<Longrightarrow> d y \\<le> |x\\<^sup>\\<star>] z\"\nproof -\n  assume a1: \"d y \\<le> d z \\<cdot> |x] y\"\n  hence a: \"d y \\<le> d z\" and \"d y \\<le> |x] y\"\n    apply (metis local.a_subid_aux2 local.dual_order.trans local.fbox_def)\n    using a1 dka.dom_subid_aux2 local.dual_order.trans by blast\n  hence \"d y \\<le> |x\\<^sup>\\<star>] y\"\n    using fbox_star_induct_var by blast\n  thus ?thesis\n    using a local.fbox_iso local.order.trans by blast\nqed\n\nlemma fbox_star_induct_eq: \"d z \\<cdot> |x] y = d y \\<Longrightarrow> d y \\<le> |x\\<^sup>\\<star>] z\"\n  by (simp add: fbox_star_induct)\n\nlemma fbox_export_1: \"ad y + |x] y = |d y \\<cdot> x] y\"\n  by (simp add: local.a_6 local.fbox_def mult_assoc)\n\nlemma fbox_export_2: \"d y + |x] y = |ad y \\<cdot> x] y\"\n  by (simp add: local.ads_d_def local.ans_d_def local.fbox_def mult_assoc)\n\nend\n\nclass antidomain_kleene_algebra = antidomain_semiring + kleene_algebra\n\nbegin\n\nsubclass antidomain_left_kleene_algebra ..\n\nlemma \"d p \\<le> |(d t \\<cdot> x)\\<^sup>\\<star> \\<cdot> ad t] (d q \\<cdot> ad t) \\<Longrightarrow> d p \\<le> |d t \\<cdot> x] d q\"\n(*nitpick [expect=genuine]*)\noops\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/Antidomain_Semiring.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8856314858927011, "lm_q2_score": 0.8198933425148213, "lm_q1q2_score": 0.7261233592049345}}
{"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_HSortIsSort\n  imports \"../../Test_Base\"\nbegin\n\ndatatype 'a list = nil2 | cons2 \"'a\" \"'a list\"\n\ndatatype Heap = Node \"Heap\" \"int\" \"Heap\" | Nil\n\nfun toHeap :: \"int list => Heap list\" where\n  \"toHeap (nil2) = nil2\"\n| \"toHeap (cons2 y z) = cons2 (Node Nil y Nil) (toHeap z)\"\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\nfun hmerge :: \"Heap => Heap => Heap\" where\n  \"hmerge (Node z x2 x3) (Node x4 x5 x6) =\n   (if 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 p (nil2)) = cons2 p (nil2)\"\n| \"hpairwise (cons2 p (cons2 q qs)) =\n     cons2 (hmerge p q) (hpairwise qs)\"\n\n(*fun did not finish the proof*)\nfunction hmerging :: \"Heap list => Heap\" where\n  \"hmerging (nil2) = Nil\"\n| \"hmerging (cons2 p (nil2)) = p\"\n| \"hmerging (cons2 p (cons2 z x2)) =\n     hmerging (hpairwise (cons2 p (cons2 z x2)))\"\n  by pat_completeness auto\n\nfun toHeap2 :: \"int list => Heap\" where\n  \"toHeap2 x = hmerging (toHeap x)\"\n\n(*fun did not finish the proof*)\nfunction toList :: \"Heap => int list\" where\n  \"toList (Node p y q) = cons2 y (toList (hmerge p q))\"\n| \"toList (Nil) = nil2\"\n  by pat_completeness auto\n\nfun hsort :: \"int list => int 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_with_Proof/TIP15/TIP15/TIP_sort_HSortIsSort.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869981319863, "lm_q2_score": 0.8289388167733099, "lm_q1q2_score": 0.7259738379769778}}
{"text": "(* Author: Florian Haftmann, TU Muenchen *)\n\nsection \\<open>Preorders with explicit equivalence relation\\<close>\n\ntheory Preorder\nimports MainRLT\nbegin\n\nclass preorder_equiv = preorder\nbegin\n\ndefinition equiv :: \"'a \\<Rightarrow> 'a \\<Rightarrow> bool\"\n  where \"equiv x y \\<longleftrightarrow> x \\<le> y \\<and> y \\<le> x\"\n\nnotation\n  equiv (\"'(\\<approx>')\") and\n  equiv (\"(_/ \\<approx> _)\"  [51, 51] 50)\n\nlemma equivD1: \"x \\<le> y\" if \"x \\<approx> y\"\n  using that by (simp add: equiv_def)\n\nlemma equivD2: \"y \\<le> x\" if \"x \\<approx> y\"\n  using that by (simp add: equiv_def)\n\nlemma equiv_refl [iff]: \"x \\<approx> x\"\n  by (simp add: equiv_def)\n\nlemma equiv_sym: \"x \\<approx> y \\<longleftrightarrow> y \\<approx> x\"\n  by (auto simp add: equiv_def)\n\nlemma equiv_trans: \"x \\<approx> y \\<Longrightarrow> y \\<approx> z \\<Longrightarrow> x \\<approx> z\"\n  by (auto simp: equiv_def intro: order_trans)\n\nlemma equiv_antisym: \"x \\<le> y \\<Longrightarrow> y \\<le> x \\<Longrightarrow> x \\<approx> y\"\n  by (simp only: equiv_def)\n\nlemma less_le: \"x < y \\<longleftrightarrow> x \\<le> y \\<and> \\<not> x \\<approx> y\"\n  by (auto simp add: equiv_def less_le_not_le)\n\nlemma le_less: \"x \\<le> y \\<longleftrightarrow> x < y \\<or> x \\<approx> y\"\n  by (auto simp add: equiv_def less_le)\n\nlemma le_imp_less_or_equiv: \"x \\<le> y \\<Longrightarrow> x < y \\<or> x \\<approx> y\"\n  by (simp add: less_le)\n\nlemma less_imp_not_equiv: \"x < y \\<Longrightarrow> \\<not> x \\<approx> y\"\n  by (simp add: less_le)\n\nlemma not_equiv_le_trans: \"\\<not> a \\<approx> b \\<Longrightarrow> a \\<le> b \\<Longrightarrow> a < b\"\n  by (simp add: less_le)\n\nlemma le_not_equiv_trans: \"a \\<le> b \\<Longrightarrow> \\<not> a \\<approx> b \\<Longrightarrow> a < b\"\n  by (rule not_equiv_le_trans)\n\nlemma antisym_conv: \"y \\<le> x \\<Longrightarrow> x \\<le> y \\<longleftrightarrow> x \\<approx> y\"\n  by (simp add: equiv_def)\n\nend\n\nML_file \\<open>~~/src/Provers/preorder.ML\\<close>\n\nML \\<open>\nstructure Quasi = Quasi_Tac(\nstruct\n\nval le_trans = @{thm order_trans};\nval le_refl = @{thm order_refl};\nval eqD1 = @{thm equivD1};\nval eqD2 = @{thm equivD2};\nval less_reflE = @{thm less_irrefl};\nval less_imp_le = @{thm less_imp_le};\nval le_neq_trans = @{thm le_not_equiv_trans};\nval neq_le_trans = @{thm not_equiv_le_trans};\nval less_imp_neq = @{thm less_imp_not_equiv};\n\nfun decomp_quasi thy (Const (@{const_name less_eq}, _) $ t1 $ t2) = SOME (t1, \"<=\", t2)\n  | decomp_quasi thy (Const (@{const_name less}, _) $ t1 $ t2) = SOME (t1, \"<\", t2)\n  | decomp_quasi thy (Const (@{const_name equiv}, _) $ t1 $ t2) = SOME (t1, \"=\", t2)\n  | decomp_quasi thy (Const (@{const_name Not}, _) $ (Const (@{const_name equiv}, _) $ t1 $ t2)) = SOME (t1, \"~=\", t2)\n  | decomp_quasi thy _ = NONE;\n\nfun decomp_trans thy t = case decomp_quasi thy t of\n    x as SOME (t1, \"<=\", t2) => x\n  | _ => NONE;\n\nend\n);\n\\<close>\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/Preorder.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869851639066, "lm_q2_score": 0.8289388019824947, "lm_q1q2_score": 0.7259738142736296}}
{"text": "(*\nTitle: FriendshipTheory.thy\nAuthor:Wenda Li\n*)\n\ntheory FriendshipTheory \n  imports MoreGraph  \"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\\<open>Common steps\\<close>\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 \\<open>adjacent v1 v2\\<close> \\<open>adjacent v2 v3\\<close> \\<open>adjacent v3 v4\\<close> \\<open>adjacent v4 v1\\<close> \\<open>v2 \\<noteq> v4\\<close> \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 \\<open>finite A\\<close> by auto\n      moreover have \"card B<card A\" using B \\<open>finite A\\<close> \n        by (metis Diff_insert \\<open>f x \\<in> A\\<close> \\<open>x \\<in> A\\<close> 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 \\<open>y \\<in> A\\<close> less.prems(2))\n              hence \"f y\\<in>{x, f x}\" by (metis B DiffI \\<open>f y \\<notin> B\\<close>)\n              moreover have \"f y=x \\<Longrightarrow> False\" \n                by (metis B Diff_iff Diff_insert2 \\<open>f (f y) = y\\<close> \\<open>y \\<in> B\\<close> singleton_iff)\n              moreover have \"f y= f x\\<Longrightarrow> False\" \n                by (metis B Diff_iff \\<open>x \\<in> A\\<close> \\<open>y \\<in> B\\<close> 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 \\<open>f x\\<in>A\\<close> \\<open>x\\<in>A\\<close> by auto\n      moreover have \"card {x, f x} = 2\" using \\<open>f x\\<noteq>x\\<close> by auto\n      ultimately show ?case using B \\<open>finite A\\<close> 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] \\<open>v\\<in>V\\<close>  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 \\<open>adjacent v x\\<close> 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 \\<open>adjacent v x\\<close> 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 \\<open>adjacent v x\\<close> adjacent_V(2) adjacent_no_loop f)\n          moreover have \"v\\<noteq>f x\" \n            by (metis \\<open>f x \\<in> {n. adjacent v n}\\<close> adjacent_no_loop mem_Collect_eq)\n          ultimately show False \n            using no_quad[OF friend_assm] using \\<open>adjacent v x\\<close> \\<open>f (f x)\\<noteq>x\\<close> \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 \\<open>finite E\\<close>,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 \\<open>card {n. adjacent v n}=2\\<close> 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 \\<open>{n. adjacent v n} = insert v1 S\\<close> \\<open>v1 \\<notin> S\\<close> 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 \\<open>adjacent v1 n\\<close> adjacent_no_loop)\n      ultimately have \"n=v2\" using v1v2 by auto\n      thus ?thesis by (metis \\<open>adjacent v1 n\\<close>)\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 \\<open>x \\<in> V\\<close> 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 \\<open>adjacent x y\\<close> \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 \\<open>n \\<noteq> v2\\<close> empty_iff insert_iff v1_adj)\n          thus ?thesis by (metis Un_iff \\<open>n \\<in> V\\<close> 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 \\<open>n \\<noteq> v1\\<close> empty_iff insert_iff v2_adj)\n          thus ?thesis by (metis Un_iff \\<open>n \\<in> V\\<close> 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 \\<open>a=b\\<close> adjacent_sym by auto\n          moreover have \"a\\<noteq>v\" by (metis DiffD2 \\<open>a = b\\<close> 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 \\<open>v1\\<noteq>v2\\<close> 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 \\<open>adjacent b c\\<close> 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 \\<open>adjacent v1 v2\\<close> 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 \\<open>adjacent a c\\<close> 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 \\<open>v1 \\<noteq> v2\\<close> 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 \\<open>adjacent a c\\<close> .\n              moreover have \"adjacent v1 a\" by (metis (full_types) Diff_iff a mem_Collect_eq) \n              moreover have \"adjacent v2 v1\" by (metis \\<open>adjacent v1 v2\\<close> 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 \\<open>adjacent b c\\<close> 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 \\<open>v1 \\<noteq> v2\\<close> 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 \\<open>2\\<le>card V\\<close> 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 \\<open>2\\<le>card V\\<close> \n        by (metis add_leE card_infinite not_one_le_zero numeral_Bit0 numeral_One)\n      ultimately have \"1\\<le>card S\" \n        using \\<open>2\\<le>card V\\<close>  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 \\<open>v\\<notin>S\\<close> by auto\n      thus thesis using that[of v1] \\<open>v1\\<in>S\\<close> \\<open>V=insert v S\\<close> 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 \\<open>v1 \\<in> V\\<close> \\<open>v1 \\<noteq> v\\<close>)\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 \\<open> adjacent v1 v2 \\<close> \\<open> v1 \\<in> V \\<close> \\<open> v1 \\<noteq> v \\<close> adjacent_sym bot_least insert_subset \n          mem_Collect_eq v)\n      moreover have \"v\\<noteq>v2\" using \\<open>adjacent v v2\\<close> 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 \\<open>finite E\\<close>, of v1] by (metis card_mono)\n      hence \"card {n. adjacent v1 n} \\<ge>3\" using \\<open>card {n. adjacent v1 n}\\<noteq>2\\<close> by auto\n      then obtain v3 where \"v3\\<in>{n. adjacent v1 n}\" and \"v3\\<notin>{v,v2}\"\n        using \\<open>{v,v2} \\<subseteq> {n. adjacent v1 n}\\<close> \\<open>card {v, v2} = 2\\<close>  \n        by (metis \\<open>card {n. adjacent v1 n} \\<noteq> 2\\<close> subsetI subset_antisym)\n      hence \"adjacent v1 v3\" by auto\n      moreover have \"adjacent v3 v\" using v \n        by (metis \\<open>v3 \\<notin> {v, v2}\\<close> adjacent_V(2) adjacent_sym calculation insertCI)\n      moreover have \"adjacent v v2\" using \\<open>adjacent v v2\\<close> .\n      moreover have \"adjacent v2 v1\" using \\<open>adjacent v1 v2\\<close> adjacent_sym by auto\n      moreover have \"v1\\<noteq>v\" using \\<open>v1 \\<noteq> v\\<close> .\n      moreover have \"v3\\<noteq>v2\" by (metis \\<open>v3 \\<notin> {v, v2}\\<close> 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 \\<open>v1\\<in>V\\<close> 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] \\<open>non_adj v u\\<close> 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 \\<open>finite E\\<close>] by auto\n    have \"finite v_adj\" using v_adj adjacent_finite[OF \\<open>finite E\\<close>] by auto\n    hence \"finite v_adj_u\" using v_adj_u adjacent_finite[OF \\<open>finite E\\<close>] 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 \\<open>x \\<in> v_adj\\<close> adjacent_V(2) mem_Collect_eq v_adj)\n        moreover have \"x\\<noteq>u\" by (metis \\<open>non_adj v u\\<close> \\<open>x \\<in> v_adj\\<close> 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 \\<open>non_adj v u\\<close> non_adj_def)\n        have \"y\\<in>V\" by (metis \\<open>y \\<in> v_adj\\<close> adjacent_V(2) mem_Collect_eq v_adj) \n        moreover have \"y\\<noteq>u\" by (metis \\<open>non_adj v u\\<close> \\<open>y \\<in> v_adj\\<close> 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 \\<open>x\\<in>v_adj\\<close> \\<open>y\\<in>v_adj\\<close> \\<open>f x=f y\\<close> \\<open>x\\<noteq>y\\<close> \\<open>adjacent x (f x)\\<close> v_adj adjacent_sym \\<open>f x \\<noteq> v\\<close> \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 \\<open>y \\<in> v_adj\\<close> adjacent_V(2) mem_Collect_eq v_adj) \n        moreover have \"y\\<noteq>u\" by (metis \\<open>non_adj v u\\<close> \\<open>y \\<in> v_adj\\<close> 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 \\<open>finite E\\<close>, of v] v_adj by auto\n    moreover have \"card u_adj=degree u G\" using degree_adjacent[OF \\<open>finite E\\<close>, of u] u_adj by auto\n    ultimately have \"degree v G \\<le> degree u G\" using \\<open>finite u_adj\\<close> \n      by (metis \\<open>inj_on f v_adj\\<close> 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] \\<open>card V=3\\<close> 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 \\<open>v1\\<notin>S1\\<close> \\<open>v2\\<notin>S2\\<close> \\<open>S2={v3}\\<close> 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 \\<open>V = {v1, v2, v3}\\<close> \\<open>v1 \\<noteq> v2\\<close> insertI1 insertI2)\n      moreover hence \"n=v3\" \n        using \\<open>V = {v1, v2, v3}\\<close> 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 \\<open>V = {v1, v2, v3}\\<close> \\<open>v2 \\<noteq> v3\\<close> insertI1 insertI2)\n      moreover hence \"n'=v1\" \n        using \\<open>V = {v1, v2, v3}\\<close> 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 \\<open>adjacent v1 v2\\<close> \\<open>adjacent v3 v1\\<close> adjacent_sym \n            by (auto,metis adjacent_no_loop)\n          hence \"{n. adjacent v1 n}={v2,v3}\" using \\<open>V={v1,v2,v3}\\<close> by auto \n            thus ?thesis using degree_adjacent[OF \\<open>finite E\\<close>,of v1] \\<open>v2\\<noteq>v3\\<close> 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 \\<open>adjacent v1 v2\\<close> \\<open>adjacent v2 v3\\<close> adjacent_sym \n            by (auto,metis adjacent_no_loop)\n          hence \"{n. adjacent v2 n}={v1,v3}\" using \\<open>V={v1,v2,v3}\\<close> by force \n            thus ?thesis using degree_adjacent[OF \\<open>finite E\\<close>,of v2] \\<open>v1\\<noteq>v3\\<close> 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 \\<open>adjacent v3 v1\\<close> \\<open>adjacent v2 v3\\<close> adjacent_sym \n            by (auto,metis adjacent_no_loop)\n          hence \"{n. adjacent v3 n}={v1,v2}\" using \\<open>V={v1,v2,v3}\\<close> by force \n          thus ?thesis using degree_adjacent[OF \\<open>finite E\\<close>,of v3] \\<open>v1\\<noteq>v2\\<close> by auto\n        qed\n      ultimately show \"\\<forall>v\\<in>V. degree v G = 2\" using \\<open>V={v1,v2,v3}\\<close> 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] \\<open>card V=2\\<close> 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 \\<open>v1\\<notin>S1\\<close> \\<open>S1={v2}\\<close> 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 \\<open>V={v1,v2}\\<close> by auto\n      thus False using \\<open>adjacent v1 v3\\<close> 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 \\<open>V={v1}\\<close> 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 \\<open>V={v1}\\<close>by auto\n    qed\n  moreover have \"card V=0 \\<Longrightarrow> ?thesis\"\n    proof -\n      assume \"card V=0\"\n      hence \"V={}\" using \\<open>finite V\\<close> 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\"\n            using \\<open>card V\\<ge>4\\<close> card_le_Suc_iff[of 3 V] by auto\n          then obtain v2 B2 where \"B1 = insert v2 B2\"  \"v2 \\<notin> B2\"  \"card B2 \\<ge>2\"\n            using card_le_Suc_iff[of 2 B1] by auto\n          then obtain v3 B3 where \"B2= insert v3 B3\" \"v3\\<notin>B3\" \"card B3\\<ge>1\"\n            using card_le_Suc_iff[of 1 B2] by auto\n          then obtain v4 B4 where \"B3=insert v4 B4\" \"v4\\<notin>B4\" \n            using card_le_Suc_iff[of 0 B3] by auto\n          have \"v1\\<in>V\" by (metis \\<open>V = insert v1 B1\\<close> insert_subset order_refl)\n          moreover have \"v2\\<in>V\" \n            by (metis \\<open>B1 = insert v2 B2\\<close> \\<open>V = insert v1 B1\\<close> insert_subset subset_insertI)\n          moreover have \"v3\\<in>V\" \n            by (metis \\<open>B1 = insert v2 B2\\<close> \\<open>B2 = insert v3 B3\\<close> \\<open>V = insert v1 B1\\<close> insert_iff)\n          moreover have \"v4\\<in>V\" \n            by (metis \\<open>B1 = insert v2 B2\\<close> \\<open>B2 = insert v3 B3\\<close> \\<open>B3 = insert v4 B4\\<close> \n              \\<open>V = insert v1 B1\\<close> insert_iff)\n          moreover have \"v1\\<noteq>v2\" \n            by (metis (full_types) \\<open>B1 = insert v2 B2\\<close> \\<open>v1 \\<notin> B1\\<close> insertI1)\n          moreover have \"v1\\<noteq>v3\" \n            by (metis \\<open>B1 = insert v2 B2\\<close> \\<open>B2 = insert v3 B3\\<close> \\<open>v1 \\<notin> B1\\<close> insert_iff)\n          moreover have \"v1\\<noteq>v4\" \n            by (metis \\<open>B1 = insert v2 B2\\<close> \\<open>B2 = insert v3 B3\\<close> \\<open>B3 = insert v4 B4\\<close> \\<open>v1 \\<notin> B1\\<close> \n              insert_iff)\n          moreover have \"v2\\<noteq>v3\" \n            by (metis (full_types) \\<open>B2 = insert v3 B3\\<close> \\<open>v2 \\<notin> B2\\<close> insertI1)\n          moreover have \"v2\\<noteq>v4\" \n            by (metis \\<open>B2 = insert v3 B3\\<close> \\<open>B3 = insert v4 B4\\<close> \\<open>v2 \\<notin> B2\\<close> insert_iff)\n          moreover have \"v3\\<noteq>v4\" \n            by (metis (full_types) \\<open>B3 = insert v4 B4\\<close> \\<open>v3 \\<notin> B3\\<close> 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 \\<open>v2 \\<in> V\\<close> \\<open>v2 \\<noteq> v3\\<close> \\<open>v3 \\<in> V\\<close>)\n      moreover have \"adjacent v3 v4\" using non_non_adj by (metis \\<open>v3 \\<in> V\\<close> \\<open>v3 \\<noteq> v4\\<close> \\<open>v4 \\<in> V\\<close>)\n      moreover have \"adjacent v4 v1\" using non_non_adj by (metis \\<open>v1 \\<in> V\\<close> \\<open>v1 \\<noteq> v4\\<close> \\<open>v4 \\<in> V\\<close>)\n      ultimately show False using no_quad[OF friend_assm] \n        by (metis \\<open>v1 \\<noteq> v3\\<close> \\<open>v2 \\<noteq> v4\\<close>)\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 \\<open>non_adj v u\\<close> 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 \\<open>non_adj v u\\<close> 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 \\<open>n \\<in> V\\<close> \\<open>n \\<noteq> w\\<close> \\<open>non_adj v u\\<close> 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 \\<open>card V\\<ge>4\\<close> 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 \\<open>n\\<in>V\\<close> non_adj_def)\n              have \"w1=v \\<Longrightarrow> degree n G = degree v G\" \n                by (metis \\<open>n = w\\<close> \\<open>non_adj w w1\\<close> non_adj_degree)\n              moreover have \"w1=u \\<Longrightarrow> degree n G = degree v G\" \n                by (metis \\<open>adjacent u w\\<close> \\<open>non_adj w w1\\<close> 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 \\<open>n = w\\<close> \\<open>non_adj v u\\<close> \\<open>non_adj w w1\\<close> 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\\<open>Exclusive steps for combinatorial proofs\\<close>\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) \\<open>C \\<in> (\\<lambda>x. {n. R x n}) ` A\\<close> 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 \\<open>C1 \\<in> (\\<lambda>x. {n. R x n}) ` A\\<close> imageE)\n      obtain v2 where \"v2\\<in>A\" \"C2={n. R v2 n}\" by (metis \\<open>C2 \\<in> (\\<lambda>x. {n. R x n}) ` A\\<close> imageE)\n      have \"v1\\<noteq>v2\" by (metis \\<open>C1 = {n. R v1 n}\\<close> \\<open>C1 \\<noteq> C2\\<close> \\<open>C2 = {n. R v2 n}\\<close>)\n      thus \"C1 \\<inter> C2 ={}\" by (metis \\<open>C1 = {n. R v1 n}\\<close> \\<open>C2 = {n. R v2 n}\\<close> 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) 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 \\<open>\\<forall>v1 v2. v1\\<noteq>v2 \\<longrightarrow> {n. R v1 n} \\<inter> {n. R v2 n}={}\\<close> \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 \\<open>v\\<in>V\\<close> 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 \\<open>v\\<in>V\\<close>] by auto\n        next\n          case False\n          have \"last ps \\<in> V\" using adj_path_V by (metis False \\<open>adj_path v ps\\<close> last_in_set subsetD)\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  \\<open>xs=ps@[q]\\<close> by auto              \n              ultimately show \"ext ps xs\" using ext \\<open>xs=ps@[q]\\<close> 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  \\<open>adj_path v ps\\<close> False adj_path_app by auto  \n              hence \"adj_path v xs\" by (metis \\<open>app q = xs\\<close> app)\n              moreover have \"butlast xs=ps\" by (metis \\<open>app q = xs\\<close> 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 \\<open>qs = {n. adjacent v n}\\<close>\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 \\<open>adj_path v xs\\<close> False adj_path_app' by auto\n              thus \"xs \\<in> app ` qs\" using qs \n                by (metis (lifting, full_types) False \\<open>xs = ps @ [q]\\<close> 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 \\<open>card qs = k\\<close> 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    using Suc.hyps assms by (auto intro: card_ge_0_finite)\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] \\<open>k>0\\<close> 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 \\<open>adj_path v xs\\<close> \\<open>length xs = n + 1\\<close> 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) \\<open>ext ys xs\\<close> 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 \\<open>rotate (Suc m') xs = rotate n xs\\<close> 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 \\<open>\\<not> (\\<exists>v\\<in>V. degree v G = 2)\\<close> 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 \\<open>card V\\<ge>2\\<close> by (metis \\<open>\\<not>(\\<exists>v\\<in>V. degree v G = 2)\\<close> 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 \\<open>v1\\<in>V\\<close> \\<open>v2\\<in>V\\<close> \\<open>v1\\<noteq>v2\\<close>] by auto\n          hence \"card {n. adjacent v1 n} \\<noteq> 0\" using adjacent_finite[OF \\<open>finite E\\<close>] by auto\n          moreover have \"card {n. adjacent v1 n} = 0\" using k_adj[OF \\<open>v1\\<in>V\\<close>] \n            by (metis \\<open>k = 0\\<close>)\n          ultimately show False by simp\n        qed\n      moreover have \"even k\" using even_degree[OF friend_assm] \n        by (metis \\<open>v1 \\<in> V\\<close> assms(2) degree_adjacent k_adj)\n      hence \"k\\<noteq>1\" and \"k\\<noteq>3\" by auto\n      moreover have \"k\\<noteq>2\" using \\<open>\\<And>v. v\\<in>V \\<Longrightarrow> degree v G\\<noteq>2\\<close> degree_adjacent k_adj \n        by (metis \\<open>v1 \\<in> V\\<close> 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 \\<open>ps' = v # ps\\<close> 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 \\<open>tl x= tl y\\<close> 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]  \\<open>4 \\<le> k\\<close> \\<open>v \\<in> V\\<close> 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\"] \\<open> 4 \\<le> k \\<close> 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 \\<open>finite E\\<close> \\<open>finite V\\<close> \n          \\<open>card V\\<ge>2\\<close> \\<open>4 \\<le> k\\<close> 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 \\<open>k\\<ge>4\\<close> 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 \\<open>adj_path (hd ps) (tl ps)\\<close> 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 \\<open>butlast x=ps\\<close> 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 \\<open>x=x1#t1\\<close> \\<open>t1=[x2]\\<close> by auto\n                          thus \"adjacent (last ps) (last x)\"\n                             using \\<open>adj_path (hd x) (tl x)\\<close> \\<open>butlast x=ps\\<close> by auto\n                        next\n                          case False\n                          hence \"tl ps\\<noteq>[]\" \n                            by (metis \\<open>length ps = l + 1\\<close> 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 \\<open>adj_path (hd x) (tl x)\\<close> \\<open>butlast x=ps\\<close> \\<open>x \\<noteq> []\\<close>\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 \\<open>tl ps \\<noteq> []\\<close> last_tl)\n                        qed\n                      thus \"x \\<in> app ` qs\" using app qs \n                        by (metis \\<open>butlast x = ps\\<close> \\<open>x \\<noteq> []\\<close> 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 \\<open>length ps = l + 1\\<close>  \\<open>adj_path (hd ps) (tl ps)\\<close> adj_path_V \n                by (metis \\<open>last ps = hd ps\\<close> 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 \\<open>k\\<ge>4\\<close> 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 \\<open> butlast x = ps \\<close> \\<open> length ps = l + 1 \\<close> length_butlast by auto\n                  moreover have \"adj_path (hd x) (tl x)\" by (metis \\<open>adj_path (hd x) (tl x)\\<close>)\n                  moreover have \"adjacent (last x) (hd x)\" \n                    proof -\n                      have \"length x\\<ge>2\" using \\<open>length x=l+2\\<close> by auto\n                      hence \"adjacent (last (butlast x)) (last x)\" using \\<open>adj_path (hd x) (tl x)\\<close>\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 \\<open>butlast x=ps\\<close> by auto\n                      hence \"adjacent (hd ps) (last x)\" using \\<open>last ps=hd ps\\<close> by auto\n                      hence \"adjacent (hd x) (last x)\" \n                        using \\<open>butlast x=ps\\<close> \\<open>length ps=l+1\\<close>\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 \\<open>butlast x = ps\\<close> \\<open>last ps = hd ps\\<close> \\<open>x \\<noteq> []\\<close> 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 \\<open>length x=l+2\\<close> by auto\n                      moreover have \"hd ps=hd x\" \n                        using ps \\<open>length x=l+2\\<close> \n                        by (metis (full_types) \\<open> adjacent (last x) (hd x) \\<close> 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 \\<open>adj_path (hd x) (tl x)\\<close> butlast_tl ps)\n                      moreover have \"last ps = hd ps\" \n                        by (metis \\<open>hd ps = hd x\\<close> \\<open>last (butlast x) = hd x\\<close> ps)\n                      ultimately show ?thesis using C_star by auto\n                    qed\n                  moreover have \"ext ps x\" using ext \n                    by (metis \\<open>adj_path (hd x) (tl x)\\<close> \\<open>adjacent (last x) (hd x)\\<close> \n                      \\<open>last (butlast x) = hd x\\<close> 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] \\<open>k\\<ge>4\\<close> 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 \\<open>adj_path (hd ps) (tl ps)\\<close>]\n                by (cases ps) auto\n              hence \"\\<exists>n. adjacent (last ps) n \\<and> adjacent (hd ps) n\"\n                using adj_path_V'[OF \\<open>adj_path (hd ps) (tl ps)\\<close>] \\<open>last ps\\<noteq>hd ps\\<close>  \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 \\<open>x=app ps\\<close> 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 \\<open>x=app ps\\<close> \\<open>length ps=l+1\\<close> app\n                by (cases ps) auto\n              have \"length x = l + 2\" using \\<open>x=app ps\\<close> \\<open>length ps=l+1\\<close> app by auto\n              moreover have \"adj_path (hd x) (tl x)\" \n                proof -\n                  have \"last (tl ps)=last ps\" using \\<open>length ps=l+1\\<close> \n                    by (metis \\<open>last ps \\<noteq> hd ps\\<close> list.sel(1,3) last_ConsL last_tl neq_Nil_conv)\n                  moreover have \"length ps\\<noteq>1\" using \\<open>last ps \\<noteq> hd ps\\<close> \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 \\<open>length ps=l+1\\<close> \n                    by(auto simp: length_Suc_conv)\n                  ultimately have \"adj_path (hd ps) (tl ps @ [last x])\"\n                    using  adj_path_app[OF \\<open>adj_path (hd ps) (tl ps)\\<close>,of \"last x\"]  \n                      \\<open>adjacent (last ps) (last x)\\<close>  \n                    by auto\n                  moreover have \"tl ps @ [last x]=tl x\" \n                    using \\<open>x=app ps\\<close> app\n                    by (metis \\<open> last x = (SOME n. adjacent (last ps) n \\<and> adjacent (hd ps) n) \\<close> \n                      \\<open> tl ps \\<noteq> [] \\<close> list.sel(2) tl_append2)\n                  ultimately show ?thesis using \\<open>hd x=hd ps\\<close> by auto\n                qed\n              moreover have \"adjacent (last x) (hd x)\" \n                using \\<open>hd x=hd ps\\<close> \\<open>adjacent (hd ps) (last x)\\<close> adjacent_sym by auto\n              moreover have \"last (butlast x) \\<noteq> hd x\" \n                using \\<open>last ps \\<noteq> hd ps\\<close> \\<open>hd x=hd ps\\<close>\n                by (metis \\<open>x = app ps\\<close> 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 \\<open>length x = l + 2\\<close> length_butlast by auto\n                  moreover have \"hd (butlast x)=hd x\" \n                    using \\<open>length x=l+2\\<close> \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 \\<open>adj_path (hd x) (tl x)\\<close> by (metis adj_path_butlast butlast_tl)\n                  moreover have \"last (butlast x) \\<noteq> hd (butlast x)\" \n                    using \\<open>last (butlast x)\\<noteq>hd x\\<close> \\<open>hd (butlast x)=hd x\\<close> 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 \\<open>3 \\<le> length (x1 # t1)\\<close> 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 \\<open>t1=x2#t2\\<close> \\<open>t2=[x3]\\<close> 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 \\<open>adj_path (hd x) (tl x)\\<close>] by auto\n                    next\n                      case False\n                      hence \"length x=2\" using \\<open>length x=l+2\\<close>  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] \\<open>length x=2\\<close> 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 \\<open>x=x1#t1\\<close> \\<open>t1=[x2]\\<close> 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 \\<open>adj_path (hd x) (tl x)\\<close>] by auto\n                    qed\n                  moreover have \"hd (butlast x)=hd x\" using \\<open>length x=l+2\\<close>\n                    by (metis \\<open>adjacent (last x) (hd x)\\<close> 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 \\<open>adj_path (hd x) (tl x)\\<close>] by auto\n                  moreover have \"last (butlast x)\\<noteq>hd (butlast x)\" \n                    using \\<open>last (butlast x)\\<noteq>hd x\\<close> \\<open>hd (butlast x)=hd x\\<close> 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 \\<open>length x=l+2\\<close> by auto\n                  hence \"adjacent (last (butlast x)) (last x)\" \n                    using \\<open>adj_path (hd x) (tl x)\\<close> \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 \\<open>adjacent (last x) (hd x)\\<close> \\<open>hd (butlast x)=hd x\\<close> 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 \\<open>adjacent (last (butlast x)) (last x)\\<close> 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 \\<open>k\\<ge>4\\<close> by auto\n      hence \"finite (T l)\" using \\<open>k\\<ge>4\\<close> 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 \\<open>\\<And>l::nat. card (C (l+1)) = k* card (C_star l) + card (T l - C_star l)\\<close>\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 \\<open>C_star l \\<subseteq> T l\\<close> \\<open>finite (T l)\\<close> 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 \\<open>C_star l \\<subseteq> T l\\<close> \\<open>finite (T l)\\<close> by (metis card_mono)\n          moreover have \"k*card (C_star l) \\<ge> card (C_star l)\" using \\<open>k\\<ge>4\\<close> by auto\n          ultimately show ?thesis by auto\n        qed\n      also have \"...=(k-(1::nat))*card(C_star l)+card(T l)\" using \\<open>k\\<ge>4\\<close> \n        by (metis 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 \\<open>k>=4\\<close> \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 \\<open>k\\<ge>4\\<close> 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 \\<open>k\\<ge>4\\<close> 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 \\<open>k\\<ge>4\\<close> 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 \\<open>k\\<ge>4\\<close> \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_iff)\n  hence *: \"\\<And>l::nat. card (C (l+1)) mod p=1\"\n    using \\<open>\\<And>l::nat. card (C (l+1)) mod (k-(1::nat))=1\\<close> mod_mod_cancel[OF \\<open>p dvd (k-(1::nat))\\<close>]\n      \\<open>prime p\\<close>\n    by (metis mod_if prime_gt_1_nat)\n  have \"card (C (p - 1)) mod p = 1\"\n  proof (cases \"2 \\<le> p\")\n    case True with * [of \"p - 2\"] show ?thesis\n      by (metis Nat.add_diff_assoc2 add_le_cancel_right diff_diff_left one_add_one p_minus_1)\n  next\n    case False with * [of \"p - 2\"] \\<open>prime p\\<close> prime_ge_2_nat show ?thesis\n      by blast\n  qed\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 \\<open>length x=p\\<close> \\<open>prime p\\<close> by auto\n              hence \"adjacent (last (rotate1 x)) (hd (rotate1 x))=adjacent (hd x) (hd (tl x))\"\n                by (metis \\<open> adjacent (last x) (hd x) \\<close> adjacent_no_loop append_Nil list.sel(1,3)\n                  hd_append2 last_snoc list.exhaust rotate1_hd_tl)\n              also have \"...=True\" using \\<open>adj_path (hd x) (tl x)\\<close> \n                using \\<open>adjacent (last x) (hd x)\\<close> \\<open>x \\<noteq> []\\<close>\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 \\<open>length x=p\\<close> \\<open>prime p\\<close> 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 \\<open>adj_path (hd x) (tl x)\\<close>, metis \\<open>adjacent (last x) (hd x)\\<close> \\<open>y = hd x\\<close> \n                  \\<open>ys = tl x\\<close> adjacent_no_loop list.sel(1,3) last.simps last_tl list.exhaust\n                  , metis \\<open>adjacent (last x) (hd x)\\<close> \\<open>x \\<noteq> []\\<close> \\<open>ys = tl x\\<close> 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 \\<open>x\\<noteq>[]\\<close> \\<open>y=hd x\\<close> \\<open>ys=tl x\\<close> by (metis rotate1_hd_tl)\n              also have \"...=adj_path (hd ys) ((tl ys)@[y])\" \n                by (metis \\<open>ys \\<noteq> []\\<close> hd_append tl_append2)\n              also have \"...=True\" \n                using adj_path_app[OF \\<open>adj_path y ys\\<close> \\<open>ys\\<noteq>[]\\<close> \\<open>adjacent (last ys) y\\<close>] \\<open>ys\\<noteq>[]\\<close>\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 \\<open>length x=p\\<close> 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 \\<open>n1 \\<in> {0..<p}\\<close> \\<open>n2 \\<in> {0..<p}\\<close> \\<open>n1>n2\\<close> by auto\n                    with \\<open>prime p\\<close> have \"coprime (n1 - n2) p\"\n                      by (simp add: prime_nat_iff'' coprime_commute [of p])\n                    then have \"\\<exists>x. [(n1 - n2) * x = 1] (mod p)\"\n                      by (simp add: cong_solve_coprime_nat)\n                    then obtain s where \"s * (n1 - n2) mod p = 1\" \n                      using \\<open>prime p\\<close> prime_gt_1_nat [of p]\n                      by (auto simp add: cong_def ac_simps)\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 \\<open>rotate n1 x=rotate n2 x\\<close>\n                  apply (induct s)\n                  apply (auto simp add: algebra_simps)\n                  by (metis add.commute 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 \\<open>s*(n1-n2) mod p=1\\<close> \\<open>length x=p\\<close> \n                  by (metis rotate_conv_mod) \n                hence \"rotate1 x=x\" by auto\n                have \"hd x=hd (tl x)\" using \\<open>prime p\\<close> \\<open>length x=p\\<close> \n                  proof -\n                    have \"length x\\<ge>2\" using \\<open>prime p\\<close> \\<open>length x=p\\<close> using prime_ge_2_nat by blast \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 \\<open>rotate1 x = x\\<close> 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 \\<open>x \\<in> C (p-(1::nat))\\<close> C by auto\n                    moreover have \"length x\\<ge>2\" using \\<open>prime p\\<close> \\<open>length x=p\\<close> using prime_ge_2_nat by blast\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 \\<open>n1 \\<in> {0..<p}\\<close> \\<open>n1 \\<noteq> n2\\<close> \\<open>n2 \\<in> {0..<p}\\<close> \\<open>rotate n1 x = rotate n2 x\\<close> \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 \\<open>x\\<in>r\\<close> r by auto\n              ultimately show  \"x \\<in> C (p - 1) \\<times> C (p - 1)\" using \\<open>fst x\\<in> C (p - 1)\\<close> \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 \\<open>prime p\\<close> by (auto intro: prime_gt_0_nat)\n              ultimately have \"(x,rotate 0 x)\\<in> r\" using \\<open>x\\<in>C (p - 1 )\\<close> 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 \\<open>(x,y)\\<in>r\\<close> r by auto\n          hence \"y\\<in> C (p - 1)\" using closure[OF \\<open>x\\<in> C (p - 1)\\<close>] by auto\n          have \"n=0\\<Longrightarrow>(y, x) \\<in> r\" \n            proof -\n              assume \"n=0\"\n              hence \"x=y\" using \\<open>rotate n x=y\\<close> by auto\n              thus \"(y,x)\\<in>r\" using \\<open>refl_on (C (p - 1)) r\\<close> \\<open>y \\<in> C (p - 1)\\<close> 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 \\<open>rotate n x=y\\<close> 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 \\<open>n<p\\<close> by auto\n                  also have \"...=rotate 0 x\" using \\<open>length x=p\\<close> by auto\n                  also have \"...=x\" by auto\n                  finally show ?thesis .\n                qed\n              moreover have \"p-n<p\" using \\<open>n<p\\<close> \\<open>n\\<noteq>0\\<close> by auto\n              ultimately show \"(y,x)\\<in>r\" using r \\<open>y\\<in> C (p - 1)\\<close> 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 \\<open>(x,y)\\<in>r\\<close> \\<open>(y,z)\\<in>r\\<close> by auto\n          hence \"z=rotate (n2+n1) x\" by (metis rotate_rotate)\n          hence \"z=rotate ((n2+n1) mod p) x\" using \\<open>length x=p\\<close> by (metis rotate_conv_mod)\n          moreover have \"(n2+n1) mod p < p\" by (metis \\<open>prime p\\<close> mod_less_divisor prime_gt_0_nat)\n          ultimately show \"(x,z)\\<in>r\" using \\<open>x\\<in> C (p - 1)\\<close> r by auto \n        qed\n      moreover have \"finite (C (p - 1))\" \n        by (metis \\<open>card (C (p - 1)) mod p = 1\\<close> 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 \\<open>finite V\\<close>\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] \\<open>finite V\\<close> by auto\n      thus ?thesis \n        using degree_two_windmill[OF friend_assm] \\<open>card V\\<ge>2\\<close> \\<open>finite V\\<close> by auto\n    qed\n  ultimately show ?thesis by force\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/Koenigsberg_Friendship/FriendshipTheory.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8757869851639066, "lm_q2_score": 0.8289388019824947, "lm_q1q2_score": 0.7259738142736296}}
{"text": "(*  Title:   HOL/Groups.thy\n    Author:  Gertrud Bauer, Steven Obua, Lawrence C Paulson, Markus Wenzel, Jeremy Avigad\n*)\n\nsection {* Groups, also combined with orderings *}\n\ntheory Groups\nimports Orderings\nbegin\n\nsubsection {* Dynamic facts *}\n\nnamed_theorems ac_simps \"associativity and commutativity simplification rules\"\n\n\ntext{* The rewrites accumulated in @{text algebra_simps} deal with the\nclassical algebraic structures of groups, rings and family. They simplify\nterms by multiplying everything out (in case of a ring) and bringing sums and\nproducts into a canonical form (by ordered rewriting). As a result it decides\ngroup and ring equalities but also helps with inequalities.\n\nOf course it also works for fields, but it knows nothing about multiplicative\ninverses or division. This is catered for by @{text field_simps}. *}\n\nnamed_theorems algebra_simps \"algebra simplification rules\"\n\n\ntext{* Lemmas @{text field_simps} multiply with denominators in (in)equations\nif they can be proved to be non-zero (for equations) or positive/negative\n(for inequations). Can be too aggressive and is therefore separate from the\nmore benign @{text algebra_simps}. *}\n\nnamed_theorems field_simps \"algebra simplification rules for fields\"\n\n\nsubsection {* Abstract structures *}\n\ntext {*\n  These locales provide basic structures for interpretation into\n  bigger structures;  extensions require careful thinking, otherwise\n  undesired effects may occur due to interpretation.\n*}\n\nlocale semigroup =\n  fixes f :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a\" (infixl \"*\" 70)\n  assumes assoc [ac_simps]: \"a * b * c = a * (b * c)\"\n\nlocale abel_semigroup = semigroup +\n  assumes commute [ac_simps]: \"a * b = b * a\"\nbegin\n\nlemma left_commute [ac_simps]:\n  \"b * (a * c) = a * (b * c)\"\nproof -\n  have \"(b * a) * c = (a * b) * c\"\n    by (simp only: commute)\n  then show ?thesis\n    by (simp only: assoc)\nqed\n\nend\n\nlocale monoid = semigroup +\n  fixes z :: 'a (\"1\")\n  assumes left_neutral [simp]: \"1 * a = a\"\n  assumes right_neutral [simp]: \"a * 1 = a\"\n\nlocale comm_monoid = abel_semigroup +\n  fixes z :: 'a (\"1\")\n  assumes comm_neutral: \"a * 1 = a\"\nbegin\n\nsublocale monoid\n  by default (simp_all add: commute comm_neutral)\n\nend\n\n\nsubsection {* Generic operations *}\n\nclass zero = \n  fixes zero :: 'a  (\"0\")\n\nclass one =\n  fixes one  :: 'a  (\"1\")\n\nhide_const (open) zero one\n\nlemma Let_0 [simp]: \"Let 0 f = f 0\"\n  unfolding Let_def ..\n\nlemma Let_1 [simp]: \"Let 1 f = f 1\"\n  unfolding Let_def ..\n\nsetup {*\n  Reorient_Proc.add\n    (fn Const(@{const_name Groups.zero}, _) => true\n      | Const(@{const_name Groups.one}, _) => true\n      | _ => false)\n*}\n\nsimproc_setup reorient_zero (\"0 = x\") = Reorient_Proc.proc\nsimproc_setup reorient_one (\"1 = x\") = Reorient_Proc.proc\n\ntyped_print_translation {*\n  let\n    fun tr' c = (c, fn ctxt => fn T => fn ts =>\n      if null ts andalso Printer.type_emphasis ctxt T then\n        Syntax.const @{syntax_const \"_constrain\"} $ Syntax.const c $\n          Syntax_Phases.term_of_typ ctxt T\n      else raise Match);\n  in map tr' [@{const_syntax Groups.one}, @{const_syntax Groups.zero}] end;\n*} -- {* show types that are presumably too general *}\n\nclass plus =\n  fixes plus :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a\"  (infixl \"+\" 65)\n\nclass minus =\n  fixes minus :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a\"  (infixl \"-\" 65)\n\nclass uminus =\n  fixes uminus :: \"'a \\<Rightarrow> 'a\"  (\"- _\" [81] 80)\n\nclass times =\n  fixes times :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a\"  (infixl \"*\" 70)\n\n\nsubsection {* Semigroups and Monoids *}\n\nclass semigroup_add = plus +\n  assumes add_assoc [algebra_simps, field_simps]: \"(a + b) + c = a + (b + c)\"\nbegin\n\nsublocale add!: semigroup plus\n  by default (fact add_assoc)\n\nend\n\nhide_fact add_assoc\n\nclass ab_semigroup_add = semigroup_add +\n  assumes add_commute [algebra_simps, field_simps]: \"a + b = b + a\"\nbegin\n\nsublocale add!: abel_semigroup plus\n  by default (fact add_commute)\n\ndeclare add.left_commute [algebra_simps, field_simps]\n\ntheorems add_ac = add.assoc add.commute add.left_commute\n\nend\n\nhide_fact add_commute\n\ntheorems add_ac = add.assoc add.commute add.left_commute\n\nclass semigroup_mult = times +\n  assumes mult_assoc [algebra_simps, field_simps]: \"(a * b) * c = a * (b * c)\"\nbegin\n\nsublocale mult!: semigroup times\n  by default (fact mult_assoc)\n\nend\n\nhide_fact mult_assoc\n\nclass ab_semigroup_mult = semigroup_mult +\n  assumes mult_commute [algebra_simps, field_simps]: \"a * b = b * a\"\nbegin\n\nsublocale mult!: abel_semigroup times\n  by default (fact mult_commute)\n\ndeclare mult.left_commute [algebra_simps, field_simps]\n\ntheorems mult_ac = mult.assoc mult.commute mult.left_commute\n\nend\n\nhide_fact mult_commute\n\ntheorems mult_ac = mult.assoc mult.commute mult.left_commute\n\nclass monoid_add = zero + semigroup_add +\n  assumes add_0_left: \"0 + a = a\"\n    and add_0_right: \"a + 0 = a\"\nbegin\n\nsublocale add!: monoid plus 0\n  by default (fact add_0_left add_0_right)+\n\nend\n\nlemma zero_reorient: \"0 = x \\<longleftrightarrow> x = 0\"\n  by (fact eq_commute)\n\nclass comm_monoid_add = zero + ab_semigroup_add +\n  assumes add_0: \"0 + a = a\"\nbegin\n\nsublocale add!: comm_monoid plus 0\n  by default (insert add_0, simp add: ac_simps)\n\nsubclass monoid_add\n  by default (fact add.left_neutral add.right_neutral)+\n\nend\n\nclass comm_monoid_diff = comm_monoid_add + minus +\n  assumes diff_zero [simp]: \"a - 0 = a\"\n    and zero_diff [simp]: \"0 - a = 0\"\n    and add_diff_cancel_left [simp]: \"(c + a) - (c + b) = a - b\"\n    and diff_diff_add: \"a - b - c = a - (b + c)\"\nbegin\n\nlemma add_diff_cancel_right [simp]:\n  \"(a + c) - (b + c) = a - b\"\n  using add_diff_cancel_left [symmetric] by (simp add: add.commute)\n\nlemma add_diff_cancel_left' [simp]:\n  \"(b + a) - b = a\"\nproof -\n  have \"(b + a) - (b + 0) = a\" by (simp only: add_diff_cancel_left diff_zero)\n  then show ?thesis by simp\nqed\n\nlemma add_diff_cancel_right' [simp]:\n  \"(a + b) - b = a\"\n  using add_diff_cancel_left' [symmetric] by (simp add: add.commute)\n\nlemma diff_add_zero [simp]:\n  \"a - (a + b) = 0\"\nproof -\n  have \"a - (a + b) = (a + 0) - (a + b)\" by simp\n  also have \"\\<dots> = 0\" by (simp only: add_diff_cancel_left zero_diff)\n  finally show ?thesis .\nqed\n\nlemma diff_cancel [simp]:\n  \"a - a = 0\"\nproof -\n  have \"(a + 0) - (a + 0) = 0\" by (simp only: add_diff_cancel_left diff_zero)\n  then show ?thesis by simp\nqed\n\nlemma diff_right_commute:\n  \"a - c - b = a - b - c\"\n  by (simp add: diff_diff_add add.commute)\n\nlemma add_implies_diff:\n  assumes \"c + b = a\"\n  shows \"c = a - b\"\nproof -\n  from assms have \"(b + c) - (b + 0) = a - b\" by (simp add: add.commute)\n  then show \"c = a - b\" by simp\nqed\n\nend\n\nclass monoid_mult = one + semigroup_mult +\n  assumes mult_1_left: \"1 * a  = a\"\n    and mult_1_right: \"a * 1 = a\"\nbegin\n\nsublocale mult!: monoid times 1\n  by default (fact mult_1_left mult_1_right)+\n\nend\n\nlemma one_reorient: \"1 = x \\<longleftrightarrow> x = 1\"\n  by (fact eq_commute)\n\nclass comm_monoid_mult = one + ab_semigroup_mult +\n  assumes mult_1: \"1 * a = a\"\nbegin\n\nsublocale mult!: comm_monoid times 1\n  by default (insert mult_1, simp add: ac_simps)\n\nsubclass monoid_mult\n  by default (fact mult.left_neutral mult.right_neutral)+\n\nend\n\nclass cancel_semigroup_add = semigroup_add +\n  assumes add_left_imp_eq: \"a + b = a + c \\<Longrightarrow> b = c\"\n  assumes add_right_imp_eq: \"b + a = c + a \\<Longrightarrow> b = c\"\nbegin\n\nlemma add_left_cancel [simp]:\n  \"a + b = a + c \\<longleftrightarrow> b = c\"\nby (blast dest: add_left_imp_eq)\n\nlemma add_right_cancel [simp]:\n  \"b + a = c + a \\<longleftrightarrow> b = c\"\nby (blast dest: add_right_imp_eq)\n\nend\n\nclass cancel_ab_semigroup_add = ab_semigroup_add +\n  assumes add_imp_eq: \"a + b = a + c \\<Longrightarrow> b = c\"\nbegin\n\nsubclass cancel_semigroup_add\nproof\n  fix a b c :: 'a\n  assume \"a + b = a + c\" \n  then show \"b = c\" by (rule add_imp_eq)\nnext\n  fix a b c :: 'a\n  assume \"b + a = c + a\"\n  then have \"a + b = a + c\" by (simp only: add.commute)\n  then show \"b = c\" by (rule add_imp_eq)\nqed\n\nend\n\nclass cancel_comm_monoid_add = cancel_ab_semigroup_add + comm_monoid_add\n\n\nsubsection {* Groups *}\n\nclass group_add = minus + uminus + monoid_add +\n  assumes left_minus [simp]: \"- a + a = 0\"\n  assumes add_uminus_conv_diff [simp]: \"a + (- b) = a - b\"\nbegin\n\nlemma diff_conv_add_uminus:\n  \"a - b = a + (- b)\"\n  by simp\n\nlemma minus_unique:\n  assumes \"a + b = 0\" shows \"- a = b\"\nproof -\n  have \"- a = - a + (a + b)\" using assms by simp\n  also have \"\\<dots> = b\" by (simp add: add.assoc [symmetric])\n  finally show ?thesis .\nqed\n\nlemma minus_zero [simp]: \"- 0 = 0\"\nproof -\n  have \"0 + 0 = 0\" by (rule add_0_right)\n  thus \"- 0 = 0\" by (rule minus_unique)\nqed\n\nlemma minus_minus [simp]: \"- (- a) = a\"\nproof -\n  have \"- a + a = 0\" by (rule left_minus)\n  thus \"- (- a) = a\" by (rule minus_unique)\nqed\n\nlemma right_minus: \"a + - a = 0\"\nproof -\n  have \"a + - a = - (- a) + - a\" by simp\n  also have \"\\<dots> = 0\" by (rule left_minus)\n  finally show ?thesis .\nqed\n\nlemma diff_self [simp]:\n  \"a - a = 0\"\n  using right_minus [of a] by simp\n\nsubclass cancel_semigroup_add\nproof\n  fix a b c :: 'a\n  assume \"a + b = a + c\"\n  then have \"- a + a + b = - a + a + c\"\n    unfolding add.assoc by simp\n  then show \"b = c\" by simp\nnext\n  fix a b c :: 'a\n  assume \"b + a = c + a\"\n  then have \"b + a + - a = c + a  + - a\" by simp\n  then show \"b = c\" unfolding add.assoc by simp\nqed\n\nlemma minus_add_cancel [simp]:\n  \"- a + (a + b) = b\"\n  by (simp add: add.assoc [symmetric])\n\nlemma add_minus_cancel [simp]:\n  \"a + (- a + b) = b\"\n  by (simp add: add.assoc [symmetric])\n\nlemma diff_add_cancel [simp]:\n  \"a - b + b = a\"\n  by (simp only: diff_conv_add_uminus add.assoc) simp\n\nlemma add_diff_cancel [simp]:\n  \"a + b - b = a\"\n  by (simp only: diff_conv_add_uminus add.assoc) simp\n\nlemma minus_add:\n  \"- (a + b) = - b + - a\"\nproof -\n  have \"(a + b) + (- b + - a) = 0\"\n    by (simp only: add.assoc add_minus_cancel) simp\n  then show \"- (a + b) = - b + - a\"\n    by (rule minus_unique)\nqed\n\nlemma right_minus_eq [simp]:\n  \"a - b = 0 \\<longleftrightarrow> a = b\"\nproof\n  assume \"a - b = 0\"\n  have \"a = (a - b) + b\" by (simp add: add.assoc)\n  also have \"\\<dots> = b\" using `a - b = 0` by simp\n  finally show \"a = b\" .\nnext\n  assume \"a = b\" thus \"a - b = 0\" by simp\nqed\n\nlemma eq_iff_diff_eq_0:\n  \"a = b \\<longleftrightarrow> a - b = 0\"\n  by (fact right_minus_eq [symmetric])\n\nlemma diff_0 [simp]:\n  \"0 - a = - a\"\n  by (simp only: diff_conv_add_uminus add_0_left)\n\nlemma diff_0_right [simp]:\n  \"a - 0 = a\" \n  by (simp only: diff_conv_add_uminus minus_zero add_0_right)\n\nlemma diff_minus_eq_add [simp]:\n  \"a - - b = a + b\"\n  by (simp only: diff_conv_add_uminus minus_minus)\n\nlemma neg_equal_iff_equal [simp]:\n  \"- a = - b \\<longleftrightarrow> a = b\" \nproof \n  assume \"- a = - b\"\n  hence \"- (- a) = - (- b)\" by simp\n  thus \"a = b\" by simp\nnext\n  assume \"a = b\"\n  thus \"- a = - b\" by simp\nqed\n\nlemma neg_equal_0_iff_equal [simp]:\n  \"- a = 0 \\<longleftrightarrow> a = 0\"\n  by (subst neg_equal_iff_equal [symmetric]) simp\n\nlemma neg_0_equal_iff_equal [simp]:\n  \"0 = - a \\<longleftrightarrow> 0 = a\"\n  by (subst neg_equal_iff_equal [symmetric]) simp\n\ntext{*The next two equations can make the simplifier loop!*}\n\nlemma equation_minus_iff:\n  \"a = - b \\<longleftrightarrow> b = - a\"\nproof -\n  have \"- (- a) = - b \\<longleftrightarrow> - a = b\" by (rule neg_equal_iff_equal)\n  thus ?thesis by (simp add: eq_commute)\nqed\n\nlemma minus_equation_iff:\n  \"- a = b \\<longleftrightarrow> - b = a\"\nproof -\n  have \"- a = - (- b) \\<longleftrightarrow> a = -b\" by (rule neg_equal_iff_equal)\n  thus ?thesis by (simp add: eq_commute)\nqed\n\nlemma eq_neg_iff_add_eq_0:\n  \"a = - b \\<longleftrightarrow> a + b = 0\"\nproof\n  assume \"a = - b\" then show \"a + b = 0\" by simp\nnext\n  assume \"a + b = 0\"\n  moreover have \"a + (b + - b) = (a + b) + - b\"\n    by (simp only: add.assoc)\n  ultimately show \"a = - b\" by simp\nqed\n\nlemma add_eq_0_iff2:\n  \"a + b = 0 \\<longleftrightarrow> a = - b\"\n  by (fact eq_neg_iff_add_eq_0 [symmetric])\n\nlemma neg_eq_iff_add_eq_0:\n  \"- a = b \\<longleftrightarrow> a + b = 0\"\n  by (auto simp add: add_eq_0_iff2)\n\nlemma add_eq_0_iff:\n  \"a + b = 0 \\<longleftrightarrow> b = - a\"\n  by (auto simp add: neg_eq_iff_add_eq_0 [symmetric])\n\nlemma minus_diff_eq [simp]:\n  \"- (a - b) = b - a\"\n  by (simp only: neg_eq_iff_add_eq_0 diff_conv_add_uminus add.assoc minus_add_cancel) simp\n\nlemma add_diff_eq [algebra_simps, field_simps]:\n  \"a + (b - c) = (a + b) - c\"\n  by (simp only: diff_conv_add_uminus add.assoc)\n\nlemma diff_add_eq_diff_diff_swap:\n  \"a - (b + c) = a - c - b\"\n  by (simp only: diff_conv_add_uminus add.assoc minus_add)\n\nlemma diff_eq_eq [algebra_simps, field_simps]:\n  \"a - b = c \\<longleftrightarrow> a = c + b\"\n  by auto\n\nlemma eq_diff_eq [algebra_simps, field_simps]:\n  \"a = c - b \\<longleftrightarrow> a + b = c\"\n  by auto\n\nlemma diff_diff_eq2 [algebra_simps, field_simps]:\n  \"a - (b - c) = (a + c) - b\"\n  by (simp only: diff_conv_add_uminus add.assoc) simp\n\nlemma diff_eq_diff_eq:\n  \"a - b = c - d \\<Longrightarrow> a = b \\<longleftrightarrow> c = d\"\n  by (simp only: eq_iff_diff_eq_0 [of a b] eq_iff_diff_eq_0 [of c d])\n\nend\n\nclass ab_group_add = minus + uminus + comm_monoid_add +\n  assumes ab_left_minus: \"- a + a = 0\"\n  assumes ab_add_uminus_conv_diff: \"a - b = a + (- b)\"\nbegin\n\nsubclass group_add\n  proof qed (simp_all add: ab_left_minus ab_add_uminus_conv_diff)\n\nsubclass cancel_comm_monoid_add\nproof\n  fix a b c :: 'a\n  assume \"a + b = a + c\"\n  then have \"- a + a + b = - a + a + c\"\n    by (simp only: add.assoc)\n  then show \"b = c\" by simp\nqed\n\nlemma uminus_add_conv_diff [simp]:\n  \"- a + b = b - a\"\n  by (simp add: add.commute)\n\nlemma minus_add_distrib [simp]:\n  \"- (a + b) = - a + - b\"\n  by (simp add: algebra_simps)\n\nlemma diff_add_eq [algebra_simps, field_simps]:\n  \"(a - b) + c = (a + c) - b\"\n  by (simp add: algebra_simps)\n\nlemma diff_diff_eq [algebra_simps, field_simps]:\n  \"(a - b) - c = a - (b + c)\"\n  by (simp add: algebra_simps)\n\nlemma diff_add_eq_diff_diff:\n  \"a - (b + c) = a - b - c\"\n  using diff_add_eq_diff_diff_swap [of a c b] by (simp add: add.commute)\n\nlemma add_diff_cancel_left [simp]:\n  \"(c + a) - (c + b) = a - b\"\n  by (simp add: algebra_simps)\n\nend\n\n\nsubsection {* (Partially) Ordered Groups *} \n\ntext {*\n  The theory of partially ordered groups is taken from the books:\n  \\begin{itemize}\n  \\item \\emph{Lattice Theory} by Garret Birkhoff, American Mathematical Society 1979 \n  \\item \\emph{Partially Ordered Algebraic Systems}, Pergamon Press 1963\n  \\end{itemize}\n  Most of the used notions can also be looked up in \n  \\begin{itemize}\n  \\item @{url \"http://www.mathworld.com\"} by Eric Weisstein et. al.\n  \\item \\emph{Algebra I} by van der Waerden, Springer.\n  \\end{itemize}\n*}\n\nclass ordered_ab_semigroup_add = order + ab_semigroup_add +\n  assumes add_left_mono: \"a \\<le> b \\<Longrightarrow> c + a \\<le> c + b\"\nbegin\n\nlemma add_right_mono:\n  \"a \\<le> b \\<Longrightarrow> a + c \\<le> b + c\"\nby (simp add: add.commute [of _ c] add_left_mono)\n\ntext {* non-strict, in both arguments *}\nlemma add_mono:\n  \"a \\<le> b \\<Longrightarrow> c \\<le> d \\<Longrightarrow> a + c \\<le> b + d\"\n  apply (erule add_right_mono [THEN order_trans])\n  apply (simp add: add.commute add_left_mono)\n  done\n\nend\n\nclass ordered_cancel_ab_semigroup_add =\n  ordered_ab_semigroup_add + cancel_ab_semigroup_add\nbegin\n\nlemma add_strict_left_mono:\n  \"a < b \\<Longrightarrow> c + a < c + b\"\nby (auto simp add: less_le add_left_mono)\n\nlemma add_strict_right_mono:\n  \"a < b \\<Longrightarrow> a + c < b + c\"\nby (simp add: add.commute [of _ c] add_strict_left_mono)\n\ntext{*Strict monotonicity in both arguments*}\nlemma add_strict_mono:\n  \"a < b \\<Longrightarrow> c < d \\<Longrightarrow> a + c < b + d\"\napply (erule add_strict_right_mono [THEN less_trans])\napply (erule add_strict_left_mono)\ndone\n\nlemma add_less_le_mono:\n  \"a < b \\<Longrightarrow> c \\<le> d \\<Longrightarrow> a + c < b + d\"\napply (erule add_strict_right_mono [THEN less_le_trans])\napply (erule add_left_mono)\ndone\n\nlemma add_le_less_mono:\n  \"a \\<le> b \\<Longrightarrow> c < d \\<Longrightarrow> a + c < b + d\"\napply (erule add_right_mono [THEN le_less_trans])\napply (erule add_strict_left_mono) \ndone\n\nend\n\nclass ordered_ab_semigroup_add_imp_le =\n  ordered_cancel_ab_semigroup_add +\n  assumes add_le_imp_le_left: \"c + a \\<le> c + b \\<Longrightarrow> a \\<le> b\"\nbegin\n\nlemma add_less_imp_less_left:\n  assumes less: \"c + a < c + b\" shows \"a < b\"\nproof -\n  from less have le: \"c + a <= c + b\" by (simp add: order_le_less)\n  have \"a <= b\" \n    apply (insert le)\n    apply (drule add_le_imp_le_left)\n    by (insert le, drule add_le_imp_le_left, assumption)\n  moreover have \"a \\<noteq> b\"\n  proof (rule ccontr)\n    assume \"~(a \\<noteq> b)\"\n    then have \"a = b\" by simp\n    then have \"c + a = c + b\" by simp\n    with less show \"False\"by simp\n  qed\n  ultimately show \"a < b\" by (simp add: order_le_less)\nqed\n\nlemma add_less_imp_less_right:\n  \"a + c < b + c \\<Longrightarrow> a < b\"\napply (rule add_less_imp_less_left [of c])\napply (simp add: add.commute)  \ndone\n\nlemma add_less_cancel_left [simp]:\n  \"c + a < c + b \\<longleftrightarrow> a < b\"\n  by (blast intro: add_less_imp_less_left add_strict_left_mono) \n\nlemma add_less_cancel_right [simp]:\n  \"a + c < b + c \\<longleftrightarrow> a < b\"\n  by (blast intro: add_less_imp_less_right add_strict_right_mono)\n\nlemma add_le_cancel_left [simp]:\n  \"c + a \\<le> c + b \\<longleftrightarrow> a \\<le> b\"\n  by (auto, drule add_le_imp_le_left, simp_all add: add_left_mono) \n\nlemma add_le_cancel_right [simp]:\n  \"a + c \\<le> b + c \\<longleftrightarrow> a \\<le> b\"\n  by (simp add: add.commute [of a c] add.commute [of b c])\n\nlemma add_le_imp_le_right:\n  \"a + c \\<le> b + c \\<Longrightarrow> a \\<le> b\"\nby simp\n\nlemma max_add_distrib_left:\n  \"max x y + z = max (x + z) (y + z)\"\n  unfolding max_def by auto\n\nlemma min_add_distrib_left:\n  \"min x y + z = min (x + z) (y + z)\"\n  unfolding min_def by auto\n\nlemma max_add_distrib_right:\n  \"x + max y z = max (x + y) (x + z)\"\n  unfolding max_def by auto\n\nlemma min_add_distrib_right:\n  \"x + min y z = min (x + y) (x + z)\"\n  unfolding min_def by auto\n\nend\n\nclass ordered_cancel_comm_monoid_diff = comm_monoid_diff + ordered_ab_semigroup_add_imp_le +\n  assumes le_iff_add: \"a \\<le> b \\<longleftrightarrow> (\\<exists>c. b = a + c)\"\nbegin\n\ncontext\n  fixes a b\n  assumes \"a \\<le> b\"\nbegin\n\nlemma add_diff_inverse:\n  \"a + (b - a) = b\"\n  using `a \\<le> b` by (auto simp add: le_iff_add)\n\nlemma add_diff_assoc:\n  \"c + (b - a) = c + b - a\"\n  using `a \\<le> b` by (auto simp add: le_iff_add add.left_commute [of c])\n\nlemma add_diff_assoc2:\n  \"b - a + c = b + c - a\"\n  using `a \\<le> b` by (auto simp add: le_iff_add add.assoc)\n\nlemma diff_add_assoc:\n  \"c + b - a = c + (b - a)\"\n  using `a \\<le> b` by (simp add: add.commute add_diff_assoc)\n\nlemma diff_add_assoc2:\n  \"b + c - a = b - a + c\"\n  using `a \\<le> b`by (simp add: add.commute add_diff_assoc)\n\nlemma diff_diff_right:\n  \"c - (b - a) = c + a - b\"\n  by (simp add: add_diff_inverse add_diff_cancel_left [of a c \"b - a\", symmetric] add.commute)\n\nlemma diff_add:\n  \"b - a + a = b\"\n  by (simp add: add.commute add_diff_inverse)\n\nlemma le_add_diff:\n  \"c \\<le> b + c - a\"\n  by (auto simp add: add.commute diff_add_assoc2 le_iff_add)\n\nlemma le_imp_diff_is_add:\n  \"a \\<le> b \\<Longrightarrow> b - a = c \\<longleftrightarrow> b = c + a\"\n  by (auto simp add: add.commute add_diff_inverse)\n\nlemma le_diff_conv2:\n  \"c \\<le> b - a \\<longleftrightarrow> c + a \\<le> b\" (is \"?P \\<longleftrightarrow> ?Q\")\nproof\n  assume ?P\n  then have \"c + a \\<le> b - a + a\" by (rule add_right_mono)\n  then show ?Q by (simp add: add_diff_inverse add.commute)\nnext\n  assume ?Q\n  then have \"a + c \\<le> a + (b - a)\" by (simp add: add_diff_inverse add.commute)\n  then show ?P by simp\nqed\n\nend\n\nend\n\n\nsubsection {* Support for reasoning about signs *}\n\nclass ordered_comm_monoid_add =\n  ordered_cancel_ab_semigroup_add + comm_monoid_add\nbegin\n\nlemma add_pos_nonneg:\n  assumes \"0 < a\" and \"0 \\<le> b\" shows \"0 < a + b\"\nproof -\n  have \"0 + 0 < a + b\" \n    using assms by (rule add_less_le_mono)\n  then show ?thesis by simp\nqed\n\nlemma add_pos_pos:\n  assumes \"0 < a\" and \"0 < b\" shows \"0 < a + b\"\nby (rule add_pos_nonneg) (insert assms, auto)\n\nlemma add_nonneg_pos:\n  assumes \"0 \\<le> a\" and \"0 < b\" shows \"0 < a + b\"\nproof -\n  have \"0 + 0 < a + b\" \n    using assms by (rule add_le_less_mono)\n  then show ?thesis by simp\nqed\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_neg_nonpos:\n  assumes \"a < 0\" and \"b \\<le> 0\" shows \"a + b < 0\"\nproof -\n  have \"a + b < 0 + 0\"\n    using assms by (rule add_less_le_mono)\n  then show ?thesis by simp\nqed\n\nlemma add_neg_neg: \n  assumes \"a < 0\" and \"b < 0\" shows \"a + b < 0\"\nby (rule add_neg_nonpos) (insert assms, auto)\n\nlemma add_nonpos_neg:\n  assumes \"a \\<le> 0\" and \"b < 0\" shows \"a + b < 0\"\nproof -\n  have \"a + b < 0 + 0\"\n    using assms by (rule add_le_less_mono)\n  then show ?thesis by simp\nqed\n\nlemma add_nonpos_nonpos:\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\nlemmas add_sign_intros =\n  add_pos_nonneg add_pos_pos add_nonneg_pos add_nonneg_nonneg\n  add_neg_nonpos add_neg_neg add_nonpos_neg add_nonpos_nonpos\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\"\nproof (intro iffI conjI)\n  have \"x = x + 0\" by simp\n  also have \"x + 0 \\<le> x + y\" using y by (rule add_left_mono)\n  also assume \"x + y = 0\"\n  also have \"0 \\<le> x\" using x .\n  finally show \"x = 0\" .\nnext\n  have \"y = 0 + y\" by simp\n  also have \"0 + y \\<le> x + y\" using x by (rule add_right_mono)\n  also assume \"x + y = 0\"\n  also have \"0 \\<le> y\" using y .\n  finally show \"y = 0\" .\nnext\n  assume \"x = 0 \\<and> y = 0\"\n  then show \"x + y = 0\" by simp\nqed\n\nlemma add_increasing:\n  \"0 \\<le> a \\<Longrightarrow> b \\<le> c \\<Longrightarrow> b \\<le> a + c\"\n  by (insert add_mono [of 0 a b c], simp)\n\nlemma add_increasing2:\n  \"0 \\<le> c \\<Longrightarrow> b \\<le> a \\<Longrightarrow> b \\<le> a + c\"\n  by (simp add: add_increasing add.commute [of a])\n\nlemma add_strict_increasing:\n  \"0 < a \\<Longrightarrow> b \\<le> c \\<Longrightarrow> b < a + c\"\n  by (insert add_less_le_mono [of 0 a b c], simp)\n\nlemma add_strict_increasing2:\n  \"0 \\<le> a \\<Longrightarrow> b < c \\<Longrightarrow> b < a + c\"\n  by (insert add_le_less_mono [of 0 a b c], simp)\n\nend\n\nclass ordered_ab_group_add =\n  ab_group_add + ordered_ab_semigroup_add\nbegin\n\nsubclass ordered_cancel_ab_semigroup_add ..\n\nsubclass ordered_ab_semigroup_add_imp_le\nproof\n  fix a b c :: 'a\n  assume \"c + a \\<le> c + b\"\n  hence \"(-c) + (c + a) \\<le> (-c) + (c + b)\" by (rule add_left_mono)\n  hence \"((-c) + c) + a \\<le> ((-c) + c) + b\" by (simp only: add.assoc)\n  thus \"a \\<le> b\" by simp\nqed\n\nsubclass ordered_comm_monoid_add ..\n\nlemma add_less_same_cancel1 [simp]:\n  \"b + a < b \\<longleftrightarrow> a < 0\"\n  using add_less_cancel_left [of _ _ 0] by simp\n\nlemma add_less_same_cancel2 [simp]:\n  \"a + b < b \\<longleftrightarrow> a < 0\"\n  using add_less_cancel_right [of _ _ 0] by simp\n\nlemma less_add_same_cancel1 [simp]:\n  \"a < a + b \\<longleftrightarrow> 0 < b\"\n  using add_less_cancel_left [of _ 0] by simp\n\nlemma less_add_same_cancel2 [simp]:\n  \"a < b + a \\<longleftrightarrow> 0 < b\"\n  using add_less_cancel_right [of 0] by simp\n\nlemma add_le_same_cancel1 [simp]:\n  \"b + a \\<le> b \\<longleftrightarrow> a \\<le> 0\"\n  using add_le_cancel_left [of _ _ 0] by simp\n\nlemma add_le_same_cancel2 [simp]:\n  \"a + b \\<le> b \\<longleftrightarrow> a \\<le> 0\"\n  using add_le_cancel_right [of _ _ 0] by simp\n\nlemma le_add_same_cancel1 [simp]:\n  \"a \\<le> a + b \\<longleftrightarrow> 0 \\<le> b\"\n  using add_le_cancel_left [of _ 0] by simp\n\nlemma le_add_same_cancel2 [simp]:\n  \"a \\<le> b + a \\<longleftrightarrow> 0 \\<le> b\"\n  using add_le_cancel_right [of 0] by simp\n\nlemma max_diff_distrib_left:\n  shows \"max x y - z = max (x - z) (y - z)\"\n  using max_add_distrib_left [of x y \"- z\"] by simp\n\nlemma min_diff_distrib_left:\n  shows \"min x y - z = min (x - z) (y - z)\"\n  using min_add_distrib_left [of x y \"- z\"] by simp\n\nlemma le_imp_neg_le:\n  assumes \"a \\<le> b\" shows \"-b \\<le> -a\"\nproof -\n  have \"-a+a \\<le> -a+b\" using `a \\<le> b` by (rule add_left_mono) \n  then have \"0 \\<le> -a+b\" by simp\n  then have \"0 + (-b) \\<le> (-a + b) + (-b)\" by (rule add_right_mono) \n  then show ?thesis by (simp add: algebra_simps)\nqed\n\nlemma neg_le_iff_le [simp]: \"- b \\<le> - a \\<longleftrightarrow> a \\<le> b\"\nproof \n  assume \"- b \\<le> - a\"\n  hence \"- (- a) \\<le> - (- b)\" by (rule le_imp_neg_le)\n  thus \"a\\<le>b\" by simp\nnext\n  assume \"a\\<le>b\"\n  thus \"-b \\<le> -a\" by (rule le_imp_neg_le)\nqed\n\nlemma neg_le_0_iff_le [simp]: \"- a \\<le> 0 \\<longleftrightarrow> 0 \\<le> a\"\nby (subst neg_le_iff_le [symmetric], simp)\n\nlemma neg_0_le_iff_le [simp]: \"0 \\<le> - a \\<longleftrightarrow> a \\<le> 0\"\nby (subst neg_le_iff_le [symmetric], simp)\n\nlemma neg_less_iff_less [simp]: \"- b < - a \\<longleftrightarrow> a < b\"\nby (force simp add: less_le) \n\nlemma neg_less_0_iff_less [simp]: \"- a < 0 \\<longleftrightarrow> 0 < a\"\nby (subst neg_less_iff_less [symmetric], simp)\n\nlemma neg_0_less_iff_less [simp]: \"0 < - a \\<longleftrightarrow> a < 0\"\nby (subst neg_less_iff_less [symmetric], simp)\n\ntext{*The next several equations can make the simplifier loop!*}\n\nlemma less_minus_iff: \"a < - b \\<longleftrightarrow> b < - a\"\nproof -\n  have \"(- (-a) < - b) = (b < - a)\" by (rule neg_less_iff_less)\n  thus ?thesis by simp\nqed\n\nlemma minus_less_iff: \"- a < b \\<longleftrightarrow> - b < a\"\nproof -\n  have \"(- a < - (-b)) = (- b < a)\" by (rule neg_less_iff_less)\n  thus ?thesis by simp\nqed\n\nlemma le_minus_iff: \"a \\<le> - b \\<longleftrightarrow> b \\<le> - a\"\nproof -\n  have mm: \"!! a (b::'a). (-(-a)) < -b \\<Longrightarrow> -(-b) < -a\" by (simp only: minus_less_iff)\n  have \"(- (- a) <= -b) = (b <= - a)\" \n    apply (auto simp only: le_less)\n    apply (drule mm)\n    apply (simp_all)\n    apply (drule mm[simplified], assumption)\n    done\n  then show ?thesis by simp\nqed\n\nlemma minus_le_iff: \"- a \\<le> b \\<longleftrightarrow> - b \\<le> a\"\nby (auto simp add: le_less minus_less_iff)\n\nlemma diff_less_0_iff_less [simp]:\n  \"a - b < 0 \\<longleftrightarrow> a < b\"\nproof -\n  have \"a - b < 0 \\<longleftrightarrow> a + (- b) < b + (- b)\" by simp\n  also have \"... \\<longleftrightarrow> a < b\" by (simp only: add_less_cancel_right)\n  finally show ?thesis .\nqed\n\nlemmas less_iff_diff_less_0 = diff_less_0_iff_less [symmetric]\n\nlemma diff_less_eq [algebra_simps, field_simps]:\n  \"a - b < c \\<longleftrightarrow> a < c + b\"\napply (subst less_iff_diff_less_0 [of a])\napply (rule less_iff_diff_less_0 [of _ c, THEN ssubst])\napply (simp add: algebra_simps)\ndone\n\nlemma less_diff_eq[algebra_simps, field_simps]:\n  \"a < c - b \\<longleftrightarrow> a + b < c\"\napply (subst less_iff_diff_less_0 [of \"a + b\"])\napply (subst less_iff_diff_less_0 [of a])\napply (simp add: algebra_simps)\ndone\n\nlemma diff_le_eq[algebra_simps, field_simps]: \"a - b \\<le> c \\<longleftrightarrow> a \\<le> c + b\"\nby (auto simp add: le_less diff_less_eq )\n\nlemma le_diff_eq[algebra_simps, field_simps]: \"a \\<le> c - b \\<longleftrightarrow> a + b \\<le> c\"\nby (auto simp add: le_less less_diff_eq)\n\nlemma diff_le_0_iff_le [simp]:\n  \"a - b \\<le> 0 \\<longleftrightarrow> a \\<le> b\"\n  by (simp add: algebra_simps)\n\nlemmas le_iff_diff_le_0 = diff_le_0_iff_le [symmetric]\n\nlemma diff_eq_diff_less:\n  \"a - b = c - d \\<Longrightarrow> a < b \\<longleftrightarrow> c < d\"\n  by (auto simp only: less_iff_diff_less_0 [of a b] less_iff_diff_less_0 [of c d])\n\nlemma diff_eq_diff_less_eq:\n  \"a - b = c - d \\<Longrightarrow> a \\<le> b \\<longleftrightarrow> c \\<le> d\"\n  by (auto simp only: le_iff_diff_le_0 [of a b] le_iff_diff_le_0 [of c d])\n\nlemma diff_mono: \"a \\<le> b \\<Longrightarrow> d \\<le> c \\<Longrightarrow> a - c \\<le> b - d\"\n  by (simp add: field_simps add_mono)\n\nlemma diff_left_mono: \"b \\<le> a \\<Longrightarrow> c - a \\<le> c - b\"\n  by (simp add: field_simps)\n\nlemma diff_right_mono: \"a \\<le> b \\<Longrightarrow> a - c \\<le> b - c\"\n  by (simp add: field_simps)\n\nlemma diff_strict_mono: \"a < b \\<Longrightarrow> d < c \\<Longrightarrow> a - c < b - d\"\n  by (simp add: field_simps add_strict_mono)\n\nlemma diff_strict_left_mono: \"b < a \\<Longrightarrow> c - a < c - b\"\n  by (simp add: field_simps)\n\nlemma diff_strict_right_mono: \"a < b \\<Longrightarrow> a - c < b - c\"\n  by (simp add: field_simps)\n\nend\n\nML_file \"Tools/group_cancel.ML\"\n\nsimproc_setup group_cancel_add (\"a + b::'a::ab_group_add\") =\n  {* fn phi => fn ss => try Group_Cancel.cancel_add_conv *}\n\nsimproc_setup group_cancel_diff (\"a - b::'a::ab_group_add\") =\n  {* fn phi => fn ss => try Group_Cancel.cancel_diff_conv *}\n\nsimproc_setup group_cancel_eq (\"a = (b::'a::ab_group_add)\") =\n  {* fn phi => fn ss => try Group_Cancel.cancel_eq_conv *}\n\nsimproc_setup group_cancel_le (\"a \\<le> (b::'a::ordered_ab_group_add)\") =\n  {* fn phi => fn ss => try Group_Cancel.cancel_le_conv *}\n\nsimproc_setup group_cancel_less (\"a < (b::'a::ordered_ab_group_add)\") =\n  {* fn phi => fn ss => try Group_Cancel.cancel_less_conv *}\n\nclass linordered_ab_semigroup_add =\n  linorder + ordered_ab_semigroup_add\n\nclass linordered_cancel_ab_semigroup_add =\n  linorder + ordered_cancel_ab_semigroup_add\nbegin\n\nsubclass linordered_ab_semigroup_add ..\n\nsubclass ordered_ab_semigroup_add_imp_le\nproof\n  fix a b c :: 'a\n  assume le: \"c + a <= c + b\"  \n  show \"a <= b\"\n  proof (rule ccontr)\n    assume w: \"~ a \\<le> b\"\n    hence \"b <= a\" by (simp add: linorder_not_le)\n    hence le2: \"c + b <= c + a\" by (rule add_left_mono)\n    have \"a = b\" \n      apply (insert le)\n      apply (insert le2)\n      apply (drule antisym, simp_all)\n      done\n    with w show False \n      by (simp add: linorder_not_le [symmetric])\n  qed\nqed\n\nend\n\nclass linordered_ab_group_add = linorder + ordered_ab_group_add\nbegin\n\nsubclass linordered_cancel_ab_semigroup_add ..\n\nlemma equal_neg_zero [simp]:\n  \"a = - a \\<longleftrightarrow> a = 0\"\nproof\n  assume \"a = 0\" then show \"a = - a\" by simp\nnext\n  assume A: \"a = - a\" show \"a = 0\"\n  proof (cases \"0 \\<le> a\")\n    case True with A have \"0 \\<le> - a\" by auto\n    with le_minus_iff have \"a \\<le> 0\" by simp\n    with True show ?thesis by (auto intro: order_trans)\n  next\n    case False then have B: \"a \\<le> 0\" by auto\n    with A have \"- a \\<le> 0\" by auto\n    with B show ?thesis by (auto intro: order_trans)\n  qed\nqed\n\nlemma neg_equal_zero [simp]:\n  \"- a = a \\<longleftrightarrow> a = 0\"\n  by (auto dest: sym)\n\nlemma neg_less_eq_nonneg [simp]:\n  \"- a \\<le> a \\<longleftrightarrow> 0 \\<le> a\"\nproof\n  assume A: \"- a \\<le> a\" show \"0 \\<le> a\"\n  proof (rule classical)\n    assume \"\\<not> 0 \\<le> a\"\n    then have \"a < 0\" by auto\n    with A have \"- a < 0\" by (rule le_less_trans)\n    then show ?thesis by auto\n  qed\nnext\n  assume A: \"0 \\<le> a\" show \"- a \\<le> a\"\n  proof (rule order_trans)\n    show \"- a \\<le> 0\" using A by (simp add: minus_le_iff)\n  next\n    show \"0 \\<le> a\" using A .\n  qed\nqed\n\nlemma neg_less_pos [simp]:\n  \"- a < a \\<longleftrightarrow> 0 < a\"\n  by (auto simp add: less_le)\n\nlemma less_eq_neg_nonpos [simp]:\n  \"a \\<le> - a \\<longleftrightarrow> a \\<le> 0\"\n  using neg_less_eq_nonneg [of \"- a\"] by simp\n\nlemma less_neg_neg [simp]:\n  \"a < - a \\<longleftrightarrow> a < 0\"\n  using neg_less_pos [of \"- a\"] by simp\n\nlemma double_zero [simp]:\n  \"a + a = 0 \\<longleftrightarrow> a = 0\"\nproof\n  assume assm: \"a + a = 0\"\n  then have a: \"- a = a\" by (rule minus_unique)\n  then show \"a = 0\" by (simp only: neg_equal_zero)\nqed simp\n\nlemma double_zero_sym [simp]:\n  \"0 = a + a \\<longleftrightarrow> a = 0\"\n  by (rule, drule sym) simp_all\n\nlemma zero_less_double_add_iff_zero_less_single_add [simp]:\n  \"0 < a + a \\<longleftrightarrow> 0 < a\"\nproof\n  assume \"0 < a + a\"\n  then have \"0 - a < a\" by (simp only: diff_less_eq)\n  then have \"- a < a\" by simp\n  then show \"0 < a\" by simp\nnext\n  assume \"0 < a\"\n  with this have \"0 + 0 < a + a\"\n    by (rule add_strict_mono)\n  then show \"0 < a + a\" by simp\nqed\n\nlemma zero_le_double_add_iff_zero_le_single_add [simp]:\n  \"0 \\<le> a + a \\<longleftrightarrow> 0 \\<le> a\"\n  by (auto simp add: le_less)\n\nlemma double_add_less_zero_iff_single_add_less_zero [simp]:\n  \"a + a < 0 \\<longleftrightarrow> a < 0\"\nproof -\n  have \"\\<not> a + a < 0 \\<longleftrightarrow> \\<not> a < 0\"\n    by (simp add: not_less)\n  then show ?thesis by simp\nqed\n\nlemma double_add_le_zero_iff_single_add_le_zero [simp]:\n  \"a + a \\<le> 0 \\<longleftrightarrow> a \\<le> 0\" \nproof -\n  have \"\\<not> a + a \\<le> 0 \\<longleftrightarrow> \\<not> a \\<le> 0\"\n    by (simp add: not_le)\n  then show ?thesis by simp\nqed\n\nlemma minus_max_eq_min:\n  \"- max x y = min (-x) (-y)\"\n  by (auto simp add: max_def min_def)\n\nlemma minus_min_eq_max:\n  \"- min x y = max (-x) (-y)\"\n  by (auto simp add: max_def min_def)\n\nend\n\nclass abs =\n  fixes abs :: \"'a \\<Rightarrow> 'a\"\nbegin\n\nnotation (xsymbols)\n  abs  (\"\\<bar>_\\<bar>\")\n\nnotation (HTML output)\n  abs  (\"\\<bar>_\\<bar>\")\n\nend\n\nclass sgn =\n  fixes sgn :: \"'a \\<Rightarrow> 'a\"\n\nclass abs_if = minus + uminus + ord + zero + abs +\n  assumes abs_if: \"\\<bar>a\\<bar> = (if a < 0 then - a else a)\"\n\nclass sgn_if = minus + uminus + zero + one + ord + sgn +\n  assumes sgn_if: \"sgn x = (if x = 0 then 0 else if 0 < x then 1 else - 1)\"\nbegin\n\nlemma sgn0 [simp]: \"sgn 0 = 0\"\n  by (simp add:sgn_if)\n\nend\n\nclass ordered_ab_group_add_abs = ordered_ab_group_add + abs +\n  assumes abs_ge_zero [simp]: \"\\<bar>a\\<bar> \\<ge> 0\"\n    and abs_ge_self: \"a \\<le> \\<bar>a\\<bar>\"\n    and abs_leI: \"a \\<le> b \\<Longrightarrow> - a \\<le> b \\<Longrightarrow> \\<bar>a\\<bar> \\<le> b\"\n    and abs_minus_cancel [simp]: \"\\<bar>-a\\<bar> = \\<bar>a\\<bar>\"\n    and abs_triangle_ineq: \"\\<bar>a + b\\<bar> \\<le> \\<bar>a\\<bar> + \\<bar>b\\<bar>\"\nbegin\n\nlemma abs_minus_le_zero: \"- \\<bar>a\\<bar> \\<le> 0\"\n  unfolding neg_le_0_iff_le by simp\n\nlemma abs_of_nonneg [simp]:\n  assumes nonneg: \"0 \\<le> a\" shows \"\\<bar>a\\<bar> = a\"\nproof (rule antisym)\n  from nonneg le_imp_neg_le have \"- a \\<le> 0\" by simp\n  from this nonneg have \"- a \\<le> a\" by (rule order_trans)\n  then show \"\\<bar>a\\<bar> \\<le> a\" by (auto intro: abs_leI)\nqed (rule abs_ge_self)\n\nlemma abs_idempotent [simp]: \"\\<bar>\\<bar>a\\<bar>\\<bar> = \\<bar>a\\<bar>\"\nby (rule antisym)\n   (auto intro!: abs_ge_self abs_leI order_trans [of \"- \\<bar>a\\<bar>\" 0 \"\\<bar>a\\<bar>\"])\n\nlemma abs_eq_0 [simp]: \"\\<bar>a\\<bar> = 0 \\<longleftrightarrow> a = 0\"\nproof -\n  have \"\\<bar>a\\<bar> = 0 \\<Longrightarrow> a = 0\"\n  proof (rule antisym)\n    assume zero: \"\\<bar>a\\<bar> = 0\"\n    with abs_ge_self show \"a \\<le> 0\" by auto\n    from zero have \"\\<bar>-a\\<bar> = 0\" by simp\n    with abs_ge_self [of \"- a\"] have \"- a \\<le> 0\" by auto\n    with neg_le_0_iff_le show \"0 \\<le> a\" by auto\n  qed\n  then show ?thesis by auto\nqed\n\nlemma abs_zero [simp]: \"\\<bar>0\\<bar> = 0\"\nby simp\n\nlemma abs_0_eq [simp]: \"0 = \\<bar>a\\<bar> \\<longleftrightarrow> a = 0\"\nproof -\n  have \"0 = \\<bar>a\\<bar> \\<longleftrightarrow> \\<bar>a\\<bar> = 0\" by (simp only: eq_ac)\n  thus ?thesis by simp\nqed\n\nlemma abs_le_zero_iff [simp]: \"\\<bar>a\\<bar> \\<le> 0 \\<longleftrightarrow> a = 0\" \nproof\n  assume \"\\<bar>a\\<bar> \\<le> 0\"\n  then have \"\\<bar>a\\<bar> = 0\" by (rule antisym) simp\n  thus \"a = 0\" by simp\nnext\n  assume \"a = 0\"\n  thus \"\\<bar>a\\<bar> \\<le> 0\" by simp\nqed\n\nlemma zero_less_abs_iff [simp]: \"0 < \\<bar>a\\<bar> \\<longleftrightarrow> a \\<noteq> 0\"\nby (simp add: less_le)\n\nlemma abs_not_less_zero [simp]: \"\\<not> \\<bar>a\\<bar> < 0\"\nproof -\n  have a: \"\\<And>x y. x \\<le> y \\<Longrightarrow> \\<not> y < x\" by auto\n  show ?thesis by (simp add: a)\nqed\n\nlemma abs_ge_minus_self: \"- a \\<le> \\<bar>a\\<bar>\"\nproof -\n  have \"- a \\<le> \\<bar>-a\\<bar>\" by (rule abs_ge_self)\n  then show ?thesis by simp\nqed\n\nlemma abs_minus_commute: \n  \"\\<bar>a - b\\<bar> = \\<bar>b - a\\<bar>\"\nproof -\n  have \"\\<bar>a - b\\<bar> = \\<bar>- (a - b)\\<bar>\" by (simp only: abs_minus_cancel)\n  also have \"... = \\<bar>b - a\\<bar>\" by simp\n  finally show ?thesis .\nqed\n\nlemma abs_of_pos: \"0 < a \\<Longrightarrow> \\<bar>a\\<bar> = a\"\nby (rule abs_of_nonneg, rule less_imp_le)\n\nlemma abs_of_nonpos [simp]:\n  assumes \"a \\<le> 0\" shows \"\\<bar>a\\<bar> = - a\"\nproof -\n  let ?b = \"- a\"\n  have \"- ?b \\<le> 0 \\<Longrightarrow> \\<bar>- ?b\\<bar> = - (- ?b)\"\n  unfolding abs_minus_cancel [of \"?b\"]\n  unfolding neg_le_0_iff_le [of \"?b\"]\n  unfolding minus_minus by (erule abs_of_nonneg)\n  then show ?thesis using assms by auto\nqed\n  \nlemma abs_of_neg: \"a < 0 \\<Longrightarrow> \\<bar>a\\<bar> = - a\"\nby (rule abs_of_nonpos, rule less_imp_le)\n\nlemma abs_le_D1: \"\\<bar>a\\<bar> \\<le> b \\<Longrightarrow> a \\<le> b\"\nby (insert abs_ge_self, blast intro: order_trans)\n\nlemma abs_le_D2: \"\\<bar>a\\<bar> \\<le> b \\<Longrightarrow> - a \\<le> b\"\nby (insert abs_le_D1 [of \"- a\"], simp)\n\nlemma abs_le_iff: \"\\<bar>a\\<bar> \\<le> b \\<longleftrightarrow> a \\<le> b \\<and> - a \\<le> b\"\nby (blast intro: abs_leI dest: abs_le_D1 abs_le_D2)\n\nlemma abs_triangle_ineq2: \"\\<bar>a\\<bar> - \\<bar>b\\<bar> \\<le> \\<bar>a - b\\<bar>\"\nproof -\n  have \"\\<bar>a\\<bar> = \\<bar>b + (a - b)\\<bar>\"\n    by (simp add: algebra_simps)\n  then have \"\\<bar>a\\<bar> \\<le> \\<bar>b\\<bar> + \\<bar>a - b\\<bar>\"\n    by (simp add: abs_triangle_ineq)\n  then show ?thesis\n    by (simp add: algebra_simps)\nqed\n\nlemma abs_triangle_ineq2_sym: \"\\<bar>a\\<bar> - \\<bar>b\\<bar> \\<le> \\<bar>b - a\\<bar>\"\n  by (simp only: abs_minus_commute [of b] abs_triangle_ineq2)\n\nlemma abs_triangle_ineq3: \"\\<bar>\\<bar>a\\<bar> - \\<bar>b\\<bar>\\<bar> \\<le> \\<bar>a - b\\<bar>\"\n  by (simp add: abs_le_iff abs_triangle_ineq2 abs_triangle_ineq2_sym)\n\nlemma abs_triangle_ineq4: \"\\<bar>a - b\\<bar> \\<le> \\<bar>a\\<bar> + \\<bar>b\\<bar>\"\nproof -\n  have \"\\<bar>a - b\\<bar> = \\<bar>a + - b\\<bar>\" by (simp add: algebra_simps)\n  also have \"... \\<le> \\<bar>a\\<bar> + \\<bar>- b\\<bar>\" by (rule abs_triangle_ineq)\n  finally show ?thesis by simp\nqed\n\nlemma abs_diff_triangle_ineq: \"\\<bar>a + b - (c + d)\\<bar> \\<le> \\<bar>a - c\\<bar> + \\<bar>b - d\\<bar>\"\nproof -\n  have \"\\<bar>a + b - (c+d)\\<bar> = \\<bar>(a-c) + (b-d)\\<bar>\" by (simp add: algebra_simps)\n  also have \"... \\<le> \\<bar>a-c\\<bar> + \\<bar>b-d\\<bar>\" by (rule abs_triangle_ineq)\n  finally show ?thesis .\nqed\n\nlemma abs_add_abs [simp]:\n  \"\\<bar>\\<bar>a\\<bar> + \\<bar>b\\<bar>\\<bar> = \\<bar>a\\<bar> + \\<bar>b\\<bar>\" (is \"?L = ?R\")\nproof (rule antisym)\n  show \"?L \\<ge> ?R\" by(rule abs_ge_self)\nnext\n  have \"?L \\<le> \\<bar>\\<bar>a\\<bar>\\<bar> + \\<bar>\\<bar>b\\<bar>\\<bar>\" by(rule abs_triangle_ineq)\n  also have \"\\<dots> = ?R\" by simp\n  finally show \"?L \\<le> ?R\" .\nqed\n\nend\n\n\nsubsection {* Tools setup *}\n\nlemma add_mono_thms_linordered_semiring:\n  fixes i j k :: \"'a\\<Colon>ordered_ab_semigroup_add\"\n  shows \"i \\<le> j \\<and> k \\<le> l \\<Longrightarrow> i + k \\<le> j + l\"\n    and \"i = j \\<and> k \\<le> l \\<Longrightarrow> i + k \\<le> j + l\"\n    and \"i \\<le> j \\<and> k = l \\<Longrightarrow> i + k \\<le> j + l\"\n    and \"i = j \\<and> k = l \\<Longrightarrow> i + k = j + l\"\nby (rule add_mono, clarify+)+\n\nlemma add_mono_thms_linordered_field:\n  fixes i j k :: \"'a\\<Colon>ordered_cancel_ab_semigroup_add\"\n  shows \"i < j \\<and> k = l \\<Longrightarrow> i + k < j + l\"\n    and \"i = j \\<and> k < l \\<Longrightarrow> i + k < j + l\"\n    and \"i < j \\<and> k \\<le> l \\<Longrightarrow> i + k < j + l\"\n    and \"i \\<le> j \\<and> k < l \\<Longrightarrow> i + k < j + l\"\n    and \"i < j \\<and> k < l \\<Longrightarrow> i + k < j + l\"\nby (auto intro: add_strict_right_mono add_strict_left_mono\n  add_less_le_mono add_le_less_mono add_strict_mono)\n\ncode_identifier\n  code_module Groups \\<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/Groups.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835493924953, "lm_q2_score": 0.8688267745399466, "lm_q1q2_score": 0.7258904773998678}}
{"text": "theory HSV_tasks_2020 imports Complex_Main begin\n\nsection \\<open>Task 1: proving that \"3 / sqrt 2\" is irrational.\\<close>\n\n(* In case it is helpful, the following theorem is copied from Chapter 3 of the worksheet. *)\ntheorem sqrt2_irrational: \"sqrt 2 \\<notin> \\<rat>\"\nproof auto\n  assume \"sqrt 2 \\<in> \\<rat>\"\n  then obtain m n where \n    \"n \\<noteq> 0\" and \"\\<bar>sqrt 2\\<bar> = real m / real n\" and \"coprime m n\" \n    by (rule Rats_abs_nat_div_natE)\n  hence \"\\<bar>sqrt 2\\<bar>^2 = (real m / real n)^2\" by auto \n  hence \"2 = (real m / real n)^2\" by simp\n  hence \"2 = (real m)^2 / (real n)^2\" unfolding power_divide by auto\n  hence \"2 * (real n)^2 = (real m)^2\"\n    by (simp add: nonzero_eq_divide_eq `n \\<noteq> 0`)\n  hence \"real (2 * n^2) = (real m)^2\" by auto\n  hence *: \"2 * n^2 = m^2\"\n    using of_nat_power_eq_of_nat_cancel_iff by blast\n  hence \"even (m^2)\" by presburger\n  hence \"even m\" by simp\n  then obtain m' where \"m = 2 * m'\" by auto\n  with * have \"2 * n^2 = (2 * m')^2\" by auto\n  hence \"2 * n^2 = 4 * m'^2\" by simp\n  hence \"n^2 = 2 * m'^2\" by simp\n  hence \"even (n^2)\" by presburger\n  hence \"even n\" by simp\n  with `even m` and `coprime m n` show False by auto\nqed\n\ntheorem \"3 / sqrt 2 \\<notin> \\<rat>\" \n  sorry (* TODO: Complete this proof. *)\n\nsection \\<open>Task 2: Centred pentagonal numbers.\\<close>\n\nfun pent :: \"nat \\<Rightarrow> nat\" where\n  \"pent n = (if n = 0 then 1 else 5 * n + pent (n - 1))\"\n\nvalue \"pent 0\" (* should be 1 *)\nvalue \"pent 1\" (* should be 6 *)\nvalue \"pent 2\" (* should be 16 *)\nvalue \"pent 3\" (* should be 31 *)\n\ntheorem \"pent n = (5 * n^2 + 5 * n + 2) div 2\"\n  sorry (* TODO: Complete this proof. *)\n\n\nsection \\<open>Task 3: Lucas numbers.\\<close>\n\nfun fib :: \"nat \\<Rightarrow> nat\" where\n  \"fib n = (if n = 0 then 0 else if n = 1 then 1 else fib (n - 1) + fib (n - 2))\"\n\nvalue \"fib 0\" (* should be 0 *)\nvalue \"fib 1\" (* should be 1 *)\nvalue \"fib 2\" (* should be 1 *)\nvalue \"fib 3\" (* should be 2 *)\n\nthm fib.induct (* rule induction theorem for fib *)\n\n(* TODO: Complete this task. *)\n\n\nsection \\<open>Task 4: Balancing circuits.\\<close>\n\n(* Here is a datatype for representing circuits, copied from the worksheet *)\n\ndatatype \"circuit\" = \n  NOT \"circuit\"\n| AND \"circuit\" \"circuit\"\n| OR \"circuit\" \"circuit\"\n| TRUE\n| FALSE\n| INPUT \"int\"\n\ntext \\<open>Delay (assuming all gates have a delay of 1)\\<close>\n\n(* The following \"delay\" function also appeared in the 2019 coursework exercises. *)\n\nfun delay :: \"circuit \\<Rightarrow> nat\" where\n  \"delay (NOT c) = 1 + delay c\"\n| \"delay (AND c1 c2) = 1 + max (delay c1) (delay c2)\"\n| \"delay (OR c1 c2) = 1 + max (delay c1) (delay c2)\" \n| \"delay _ = 0\"\n\n(* TODO: Complete this task. *)\n\n\nsection \\<open>Task 5: Extending with NAND gates.\\<close>\n\n(* TODO: Complete this task. *)\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/2020/HSV_tasks_2020.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267762381843, "lm_q2_score": 0.8354835432479661, "lm_q1q2_score": 0.725890473480186}}
{"text": "(*<*)\ntheory Typed_Arithmetic_Expressions\nimports Main\n  Untyped_Arithmetic_Expressions\nbegin\n(*>*)\n\nsection {* Typed Arithmetic Expressions *}\ntext {* \\label{sec:typed-arith-expr} *}\n\ntext {* In this section, we revisit the previously formalized arithmetic expression language\n(Section~\\ref{sec:untyped-arith-expr}) and augment it with static types. Since types are a\ncharacterization external to the definition of terms, we import the theory to reuse its definitions\nand theorems. We complete the definitions with the typing relation and prove type safety through the\nprogress and preservation theorems.\n*}\n\nsubsection {* Definitions *}\n\ntext {*\nThe language of arithmetic expressions contains two types for Booleans and natural numbers, which we\nmodel using a datatype:\n*}\n\ndatatype nbtype = Bool | Nat\n\n(* Definition 8.2.1 *)\n\ntext {*\nThe typing relation serves to assign a type to an expression. It is characterized by the following\ninference rules:\n\\setcounter{equation}{0}\n\\begin{gather}\n  \\inferrule {}{\\text{true} : \\text{Bool}} \\\\[0.8em]\n  \\inferrule {}{\\text{false} : \\text{Bool}} \\\\[0.8em]\n  \\inferrule {t_1 : \\text{Bool} \\\\ t_2 : \\text{T} \\\\ t_3 : \\text{T}}\n    {\\text{if } t_1 \\text{ then } t_2 \\text{ else } t_3 : \\text{T}} \\\\[0.8em]\n    \\inferrule {}{0 : \\text{Nat}} \\displaybreak\\\\[0.8em]\n  \\inferrule {t_1 : \\text{Nat}}{\\text{succ } t_1 : \\text{Nat}} \\\\[0.8em]\n  \\inferrule {t_1 : \\text{Nat}}{\\text{pred } t_1 : \\text{Nat}} \\\\[0.8em]\n  \\inferrule {t_1 : \\text{Nat}}{\\text{iszero } t_1 : \\text{Bool}}\n\\end{gather}\n\nThe first, second and fourth rules give the type of constants. The third rule requires that both\nbranches of a conditional have the same type and that the condition is a Boolean. The fifth and\nsixth rules state that the successor and predecessor of natural numbers are natural numbers\nthemselves. Finally, the seventh rule state that the test of equality with zero requires a natural\nnumber and leads a Boolean. We translate these rules in an inductive definition, for which we also\nprovide the @{text \"|:|\"} operator as a more conventional notation:\n*}\n\ninductive has_type :: \"nbterm \\<Rightarrow> nbtype \\<Rightarrow> bool\" (infix \"|:|\" 150) where\n  \\<comment> \\<open>Rules relating to the type of Booleans\\<close>\n  has_type_NBTrue:\n    \"NBTrue |:| Bool\" |\n  has_type_NBFalse:\n    \"NBFalse |:| Bool\" |\n  has_type_NBIf:\n    \"t1 |:| Bool \\<Longrightarrow> t2 |:| T \\<Longrightarrow> t3 |:| T \\<Longrightarrow> NBIf t1 t2 t3 |:| T\" |\n\n  \\<comment> \\<open>Rules relating to the type of natural numbers\\<close>\n  has_type_NBZero:\n    \"NBZero |:| Nat\" |\n  has_type_NBSucc:\n    \"t |:| Nat \\<Longrightarrow> NBSucc t |:| Nat\" |\n  has_type_NBPred:\n    \"t |:| Nat \\<Longrightarrow> NBPred t |:| Nat\" |\n  has_type_NBIs_zero:\n    \"t |:| Nat \\<Longrightarrow> NBIs_zero t |:| Bool\"\n\n(* Lemma 8.2.2 *)\n\ntext {*\nThe inversion of the typing relation gives us information on types for specific terms:\n*}\n\nlemma inversion_of_typing_relation:\n  \"NBTrue |:| R \\<Longrightarrow> R = Bool\"\n  \"NBFalse |:| R \\<Longrightarrow> R = Bool\"\n  \"NBIf t1 t2 t3 |:| R \\<Longrightarrow> t1 |:| Bool \\<and> t2 |:| R \\<and> t3 |:| R\"\n  \"NBZero |:| R \\<Longrightarrow> R = Nat\"\n  \"NBSucc t |:| R \\<Longrightarrow> R = Nat \\<and> t |:| Nat\"\n  \"NBPred t |:| R \\<Longrightarrow> R = Nat \\<and> t |:| Nat\"\n  \"NBIs_zero t |:| R \\<Longrightarrow> R = Bool \\<and> t |:| Nat\"\nby (auto elim: has_type.cases)\n\n(* Theorem 8.2.4 *)\n\ntext {*\nIn the typed arithmetic language, every term @{term t} has at most one type. That is, if @{term t}\nis typable, then its type is unique:\n*}\n\ntheorem uniqueness_of_types:\n  \"t |:| T \\<Longrightarrow> t |:| T' \\<Longrightarrow> T = T'\"\nby (induction t T rule: has_type.induct) (auto dest: inversion_of_typing_relation)\n\nsubsection {* Safety = Progress + Preservation *}\n\ntext {*\nThe most basic property a type system must provide is \\emph{safety}, also called \\emph{soundness}:\nthe evaluation of a well-typed term will not reach a state whose semantics is undefined. Since our\n\\emph{operational semantics} is based the of the evaluation relation and the value predicate, every\nterm that does not fit in one or the other has no defined semantics.\n\nAn example of an undefined state is @{term \"NBSucc NBTrue\"}: there is no further evaluation\nstep possible but it is not a value neither. In our current language, there is nothing we can do\nwith this term.\n*}\n\n(* Lemma 8.3.1 *)\n\ntext {*\nAnother usefull lemma is the canonical form of values which, for well typed terms, give us\ninformation on the nature of the terms:\n*}\n\nlemma canonical_form:\n  \"is_value_NB v \\<Longrightarrow> v |:| Bool \\<Longrightarrow> v = NBTrue \\<or> v = NBFalse\"\n  \"is_value_NB v \\<Longrightarrow> v |:| Nat \\<Longrightarrow> is_numeric_value_NB v\"\nby (auto elim: has_type.cases is_value_NB.cases is_numeric_value_NB.cases)\n\n(* Theorem 8.3.2 *)\n\ntext {*\nThe safety of a type system can be shown in two step: progress and preservation. Progress means that\na well-typed term is not stuck, i.e. either it is a value or it can take a step according to the\nevaluation rules.\n*}\n\ntheorem progress:\n  \"t |:| T \\<Longrightarrow> is_value_NB t \\<or> (\\<exists>t'. eval1_NB t t')\"\nproof (induction t T rule: has_type.induct)\n  case (has_type_NBPred t)\n  thus ?case\n    by (auto intro: eval1_NB.intros is_numeric_value_NB.cases dest: canonical_form)\nnext\n  case (has_type_NBIs_zero t)\n  thus ?case\n    by (auto intro: eval1_NB.intros is_numeric_value_NB.cases dest: canonical_form)\nqed (auto\n  intro: eval1_NB.intros is_value_NB.intros is_numeric_value_NB.intros\n  dest: canonical_form)\n\n(* Theorem 8.3.3 *)\n\ntext {*\nPreservation means that if a well-typed term takes a step of evaluation, then the resulting term is\nalso well-typed.\n*}\n\ntheorem preservation: \"t |:| T \\<Longrightarrow> eval1_NB t t' \\<Longrightarrow> t' |:| T\"\nproof (induction t T arbitrary: t' rule: has_type.induct)\n  case (has_type_NBIf t1 t2 T t3)\n  from has_type_NBIf.prems has_type_NBIf.IH has_type_NBIf.hyps show ?case\n    by (auto intro: has_type.intros elim: eval1_NB.cases)\nqed (auto\n  intro: has_type.intros\n  dest: inversion_of_typing_relation\n  elim: eval1_NB.cases)\n\n(*<*)\nend\n(*>*)\n", "meta": {"author": "mdesharnais", "repo": "log792-type-systems-formalization", "sha": "6b82d50845ee2603da295dfa972f45a258602a1c", "save_path": "github-repos/isabelle/mdesharnais-log792-type-systems-formalization", "path": "github-repos/isabelle/mdesharnais-log792-type-systems-formalization/log792-type-systems-formalization-6b82d50845ee2603da295dfa972f45a258602a1c/Typed_Arithmetic_Expressions.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8354835248143776, "lm_q2_score": 0.868826784729373, "lm_q1q2_score": 0.725890464558839}}
{"text": "theory nanocop_propositional imports Main\nbegin\n\n(*--List Set Operations----*)\nprimrec member (infix\\<open>|\\<in>|\\<close> 200) where\n  \\<open>(_ |\\<in>| []) = False\\<close> |\n  \\<open>(x |\\<in>| (x' # xs)) = ((x = x') \\<or> (x |\\<in>| xs))\\<close>\n\nlemma member_simp[simp]: \\<open>x |\\<in>| xs \\<longleftrightarrow> x \\<in> (set xs)\\<close> \n  by (induct xs) simp_all\n\nabbreviation notmember (infix \\<open>|\\<notin>|\\<close> 200) where \\<open>x |\\<notin>| xs \\<equiv> \\<not> x |\\<in>| xs\\<close>\n\ndefinition \\<open>linsert x xs \\<equiv> (if (x |\\<in>| xs) then xs else x # xs)\\<close>\n\nlemma linsert_is_insert: \\<open>set (linsert x xs) = insert x (set xs)\\<close>\n  by (induct xs) (simp_all add: linsert_def insert_absorb)\n\nprimrec subseteq (infix \\<open>|\\<subseteq>|\\<close> 120) where\n  \\<open>([] |\\<subseteq>| _) = True\\<close> |\n  \\<open>((x # xs) |\\<subseteq>| ys) = ((x |\\<in>| ys) \\<and> (xs |\\<subseteq>| ys))\\<close>\n\nlemma subseteq_simp[simp]: \\<open>xs |\\<subseteq>| ys \\<longleftrightarrow> (set xs) \\<subseteq> (set ys)\\<close> \n  by (induct xs) simp_all\n\nprimrec lremove where\n  \\<open>lremove _ [] = []\\<close> |\n  \\<open>lremove x (y # ys) = (if y = x then lremove x ys else y # (lremove x ys))\\<close>\n\nlemma lremove_simp[simp]: \\<open>set (lremove x xs) = (set xs) - {x}\\<close>\n  by (induct xs) (simp_all add: insert_Diff_if)\n  \nprimrec lminus (infix \\<open>|-|\\<close> 210) where\n  \\<open>xs |-| [] = xs\\<close> |\n  \\<open>xs |-| (y # ys) = (lremove y xs) |-| ys\\<close>\n\nlemma hoist_lremove:\\<open>set ((lremove x xs) |-| ys) = set (lremove x (xs |-| ys))\\<close> \n  apply (induct ys arbitrary: x xs)\n   apply simp\n  by (metis Diff_insert Diff_insert2 lminus.simps(2) lremove_simp)\n\nlemma lminus_simp[simp]: \\<open>set (xs |-| ys) = (set xs) - (set ys)\\<close>\nproof (induct ys)\n  case Nil\n  then show ?case by simp\nnext\n  case (Cons y ys)\n  have \\<open>set (xs |-| (y # ys)) = set (xs |-| ys) - {y}\\<close>\n    by (simp add: hoist_lremove)\n  then show ?case\n    using Cons.hyps by force\nqed\n\ndefinition lequal (infix \\<open>|=|\\<close> 120) where \\<open>xs |=| ys \\<equiv> xs |\\<subseteq>| ys \\<and> ys |\\<subseteq>| xs\\<close>\n\nlemma lequal_simp[simp]: \\<open>xs |=| ys \\<longleftrightarrow> (set xs) = (set ys)\\<close>\n  by (simp add: lequal_def set_eq_subset)\n\nprimrec lunion (infix \\<open>|\\<union>|\\<close> 110) where\n  \\<open>lunion xs [] = xs\\<close> |\n  \\<open>lunion xs (y # ys) = (if y |\\<in>| xs then lunion xs ys else y # (lunion xs ys))\\<close>\n\nlemma lunion_simp[simp]: \\<open>set (xs |\\<union>| ys) = set xs \\<union> set ys\\<close> \n  by (induct ys) auto\n\nprimrec isset where\n  \\<open>isset [] = True\\<close> |\n  \\<open>isset (x # xs) = (x |\\<notin>| xs \\<and> isset xs)\\<close>\n\nlemma isset_length: \\<open>isset xs \\<Longrightarrow> size xs = size (sorted_list_of_set (set xs))\\<close>\n  by (induct xs) simp_all\n\nprimrec union_many where\n  \\<open>union_many [] = {}\\<close> |\n  \\<open>union_many (xs # ys) = xs \\<union> (union_many ys)\\<close>\n\n\nfun count where\n  \\<open>count x [] = 0\\<close> |\n  \\<open>count x (y # ys) = (if x = y then Suc (count x ys) else count x ys)\\<close>\n\nlemma count_0: \\<open>count x xs = 0 \\<longleftrightarrow> x \\<notin> set xs\\<close>\n  by (induct xs) auto\n\nlemma count_1: \\<open>count x ys \\<ge> 1 \\<longleftrightarrow> x \\<in> set ys\\<close>\n  by (induct ys) (simp_all | force)\n\nfun remove where\n  \\<open>remove x [] = []\\<close> |\n  \\<open>remove x (y # ys) = (\n    if x = y \n    then ys\n    else y # remove x ys)\\<close>\n\nlemma remove_length: \\<open>member x ys \\<Longrightarrow> length ys = length (remove x ys) + 1\\<close> \n  by (induct ys) auto\n\nlemma remove_set: \\<open>member x ys \\<Longrightarrow> set ([x] |\\<union>| (remove x ys)) = set ys\\<close> \n  by (induct ys) (auto|force)\n\nlemma remove_count: \\<open>member x ys \\<Longrightarrow> count x ys = count x (remove x ys) + 1\\<close>\n  by (induct ys) auto\n\nlemma remove_count2: \\<open>x \\<noteq> y \\<Longrightarrow> count x ys = count x (remove y ys)\\<close> \nproof (induct ys)\n  case Nil\n  then show ?case by simp\nnext\n  case (Cons z ys)\n  consider (1)\\<open>z = y\\<close> | (2)\\<open>z \\<noteq> y\\<close> by fast\n  then show ?case\n  proof cases\n    case 1\n    then have \\<open>count x (remove y (z # ys)) = count x ys\\<close> \n      by simp\n    moreover have \\<open>x \\<noteq> z \\<Longrightarrow> count x ys = count x (z # ys)\\<close> \n      by simp\n    ultimately show ?thesis \n      by (metis \"1\" Cons.prems)\n  next\n    case 2\n    show ?thesis \n        using Cons.hyps Cons.prems by auto\n  qed\nqed\n\nfun permutation where\n  \\<open>permutation [] [] = True\\<close> |\n  \\<open>permutation _ [] = False\\<close> |\n  \\<open>permutation [] _ = False\\<close> |\n  \\<open>permutation (x # xs) ys = (\n    member x ys \\<and>\n    permutation xs (remove x ys))\\<close>\n\nlemma permutation_count: \\<open>permutation xs ys \\<longleftrightarrow> (\\<forall> x. count x xs = count x ys)\\<close>\nproof (induct xs arbitrary: ys)\n  case Nil\n  then show ?case by \n      (metis count.simps(1) count_0 list.set_intros(1) neq_Nil_conv permutation.simps(1) \n        permutation.simps(3))\nnext\n  case (Cons x xs)\n  have rimp: \\<open>permutation (x # xs) ys \\<Longrightarrow> (\\<forall> y. count y (x # xs) = count y ys)\\<close> \n  proof\n    fix y\n    assume asm:\\<open>permutation (x # xs) ys\\<close>\n    consider (1) \\<open>x = y\\<close> | (2) \\<open>x \\<noteq> y\\<close> by fast\n    then show \\<open>count y (x # xs) = count y ys\\<close> \n    proof cases\n      case 1\n      have \\<open>member x ys\\<close> \n        using asm permutation.elims(2) by blast\n      then have \\<open>count x ys = count x (remove x ys) + 1\\<close> \n        by (simp add: remove_count)\n      then show ?thesis \n        using 1 asm local.Cons permutation.elims(2) permutation.simps(4) remove.simps(2) \n        by fastforce\n    next\n      case 2\n      then have \\<open>count y ys = count y (remove x ys)\\<close> sorry\n      moreover have \\<open>count y xs = count y (x # xs)\\<close> using 2 by auto\n      ultimately show ?thesis using asm\n        by (smt (verit, ccfv_threshold) list.inject local.Cons permutation.elims(2))\n    qed\n  qed\n  have limp: \\<open>(\\<forall> y. count y (x # xs) = count y ys) \\<Longrightarrow> permutation (x # xs) ys\\<close>\n  proof-\n    assume \\<open>(\\<forall> y. count y (x # xs) = count y ys)\\<close>\n    show \\<open>permutation (x # xs) ys\\<close> sorry\n  qed\n  then show ?case using limp rimp by fast\nqed \n  \nlemma permutation_alt: \\<open>permutation xs ys \\<Longrightarrow> length xs = length ys \\<and> set xs = set ys\\<close>\nproof (induct xs arbitrary: ys)\n  case Nil\n  then show ?case using permutation.elims(2) by auto\nnext\n  case (Cons x xs)\n  have \\<open>member x ys\\<close> \n    using Cons.prems permutation.elims(2) by blast\n  then have \\<open>length (x # xs) = length ys\\<close>\n    using remove_length \n    by (smt (verit, ccfv_threshold) Cons.hyps Cons.prems list.inject \n        member.simps(2) permutation.elims(2) remove.simps(2))\n  moreover have \\<open>member x xs \\<Longrightarrow> set (x # xs) = set ys\\<close>\n    by (smt (verit) Cons.hyps Cons.prems insert_absorb list.inject list.simps(15) lunion_simp \n        member_simp permutation.elims(2) remove_set sup.left_idem)\n  ultimately show ?case sorry\nqed\n  \n(*-------------------------*)\n\n\n(*--------NaNoCop----------*)\ndatatype mat \n  = Lit bool nat\n  | Mat \\<open>(nat \\<times> (nat \\<times> mat) list) list\\<close>\n\n\nfun exi_clause where\n  \\<open>exi_clause P (_,Lit _ _) = False\\<close> |\n  \\<open>exi_clause P (_,Mat []) = False\\<close> |\n  \\<open>exi_clause P (mid,Mat ((cid,ms) # cs)) = \n  (P (cid,ms) \\<or> (\\<exists> m \\<in> set ms. exi_clause P m) \\<or> exi_clause P (mid,Mat cs))\\<close>\n\ndefinition \\<open>exi_mat P m \\<equiv> P m \\<or> exi_clause (\\<lambda> (_,ms). \\<exists> m' \\<in> set ms. P m') m\\<close>\n\nfun all_clause where\n  \\<open>all_clause P (_,Lit _ _) = True\\<close> |\n  \\<open>all_clause P (_,Mat []) = True\\<close> |\n  \\<open>all_clause P (mid,Mat ((cid,ms) # cs)) = \n  (P (cid,ms) \\<and> (\\<forall> m \\<in> set ms. all_clause P m) \\<and> all_clause P (mid,Mat cs))\\<close>\n\ndefinition \\<open>all_mat P m \\<equiv> P m \\<and> all_clause (\\<lambda> (_,ms). \\<forall> m' \\<in> set ms. P m') m\\<close>\n\ndefinition \\<open>contains_cls c m \\<equiv> exi_clause (\\<lambda> c'. c = c') m\\<close>\n\ndefinition \\<open>contains_mat m1 m2 \\<equiv> exi_mat (\\<lambda> m'. m' = m1) m2\\<close>\n\ndefinition \\<open>id_exists idty m \\<equiv> exi_clause (\\<lambda> (n,_). n = idty) m \\<or> exi_mat (\\<lambda> (n,_). n = idty) m\\<close>\n\nfun siblings where\n  \\<open>siblings c1 c2 (_,Lit _ _) = False\\<close> |\n  \\<open>siblings c1 c2 (_,Mat cs) = (member c1 cs \\<and> member c2 cs)\\<close>\n\nabbreviation \\<open>\n  alpha_top_level c l m \\<equiv> (\\<exists> cid' c'. \n    c \\<noteq> (cid',c') \\<and> \n    siblings c (cid',c') m \\<and> \n    (\\<exists> m' \\<in> set c'. contains_mat l m'))\\<close>\n\ndefinition \\<open>extension_clause M P C \\<equiv> True\\<close>\n\n(*fun beta_clause where\n  \\<open>beta_clause l [] = []\\<close> |\n  \\<open>beta_clause l ((Lit pol prop) # ms) = (\n    if l = (pol,prop)\n    then ms\n    else (Lit pol prop) # (beta_clause l ms))\\<close> |\n  \\<open>beta_clause l ((Mat []) # ms) = \\<close>*)\n\ninductive CC (\\<open>\\<turnstile> _ _ _\\<close> 0) where \nAxiom: \\<open>\\<turnstile> [] _ _\\<close> |\nReduction: \\<open>\n  (\\<turnstile> C M ((lid,pol,prp) # P)) \\<Longrightarrow>\n  pol \\<longleftrightarrow> \\<not>pol' \\<Longrightarrow>\n  (\\<turnstile> ((_,Lit pol' prp) # C) M ((lid,pol,prp) # P))\\<close> |\nPermutation: \\<open>\n  (\\<turnstile> C M P) \\<Longrightarrow>\n  permutation C C' \\<Longrightarrow> permutation P P' \\<Longrightarrow>\n  (\\<turnstile> C' M P')\\<close> |\nExtention: \\<open>\n  (\\<turnstile> C' M ((lid,pol,prp) # P)) \\<Longrightarrow>\n  contains_cls (cid,C') (0,Mat M) \\<Longrightarrow>\n  extension_clause M P (cid,C')  \\<Longrightarrow>\n  (\\<turnstile> C M P) \\<Longrightarrow>\n  (\\<turnstile> ((lid,Lit pol prp) # C) M P)\\<close> |\nDecomposition: \\<open>\n  (\\<turnstile> (C' @ C) M P) \\<Longrightarrow>\n  member (_,C') cs \\<Longrightarrow>\n  (\\<turnstile> ((mid,Mat cs) # C) M P)\\<close>\n\nfun CC_mat where \n  \\<open>CC_mat (Lit _ _) = False\\<close> |\n  \\<open>CC_mat (Mat []) = False\\<close> |\n  \\<open>CC_mat (Mat ((cid,c) # m)) = (\\<turnstile> c ((cid,c) # m) [])\\<close>\n(*-------------------------*)\n\n(*---Generic Prop Forms----*)\ndatatype 'a gen_forms\n  = Atm 'a\n  | Neg \\<open>'a gen_forms\\<close>\n  | Con \\<open>'a gen_forms\\<close> \\<open>'a gen_forms\\<close>\n  | Dis \\<open>'a gen_forms\\<close> \\<open>'a gen_forms\\<close>\n  | Imp \\<open>'a gen_forms\\<close> \\<open>'a gen_forms\\<close>\n\nfun form_to_clauses where\n  \\<open>form_to_clauses mx pol (Atm n) = (mx + 1,(mx,Lit pol n))\\<close> |\n  \\<open>form_to_clauses mx pol (Neg p) = form_to_clauses mx (\\<not>pol) p\\<close> |\n  \\<open>form_to_clauses mx True (Con p1 p2) = (\n    let (nmx,mat1) = form_to_clauses (mx + 3) True p1 in\n    let (nnmx,mat2) = form_to_clauses nmx True p2 in\n    (nnmx,(mx,Mat [(mx + 1,[mat1]),(mx + 2,[mat2])])))\\<close> |\n  \\<open>form_to_clauses mx False (Dis p1 p2) = (\n    let (nmx,mat1) = form_to_clauses (mx + 3) False p1 in\n    let (nnmx,mat2) = form_to_clauses nmx False p2 in\n    (nnmx,(mx,Mat [(mx + 1,[mat1]),(mx + 2,[mat2])])))\\<close> |\n  \\<open>form_to_clauses mx False (Imp p1 p2) = (\n    let (nmx,mat1) = form_to_clauses (mx + 3) True p1 in\n    let (nnmx,mat2) = form_to_clauses nmx False p2 in\n    (nnmx,(mx,Mat [(mx + 1,[mat1]),(mx + 2,[mat2])])))\\<close> |\n  \\<open>form_to_clauses mx False (Con p1 p2) = (\n    let (nmx,mat1) = form_to_clauses (mx + 2) False p1 in\n    let (nnmx,mat2) = form_to_clauses nmx False p2 in\n    (nnmx,(mx,Mat [(mx + 1,[mat1, mat2])])))\\<close> |\n  \\<open>form_to_clauses mx True (Dis p1 p2) = (\n    let (nmx,mat1) = form_to_clauses (mx + 2) True p1 in\n    let (nnmx,mat2) = form_to_clauses nmx True p2 in\n    (nnmx,(mx,Mat [(mx + 1,[mat1, mat2])])))\\<close> |\n  \\<open>form_to_clauses mx True (Imp p1 p2) = (\n    let (nmx,mat1) = form_to_clauses (mx + 2) False p1 in\n    let (nnmx,mat2) = form_to_clauses nmx True p2 in\n    (nnmx,(mx,Mat [(mx + 1,[mat1, mat2])])))\\<close>\n\nfun collaps_mat and collaps_clause where\n  \\<open>collaps_mat (mid,Lit pol prp) = (mid,Lit pol prp)\\<close> |\n  \\<open>collaps_mat (mid,Mat [(_,[(mid2,Mat cs)])]) = collaps_mat (mid,Mat cs)\\<close> |\n  \\<open>collaps_mat (mid,Mat cs) = (mid,Mat (map collaps_clause cs))\\<close> | \n  \\<open>collaps_clause (cid,[(mid,Mat [c])]) = collaps_clause c\\<close> |\n  \\<open>collaps_clause (cid,ms) = (cid, (map collaps_mat ms))\\<close>\n\n(*prove idunique here*)\n\nvalue \\<open>form_to_clauses 0 False (Imp (Con (Imp (Atm 0) (Atm 1)) (Atm 0)) (Atm 1))\\<close>\nvalue \\<open>collaps_mat \n(0,\n  Mat [(1, [(3, Mat [(4, [(6, Mat [(7, [(8, Lit False 0), (9, Lit True 1)])])]),\n                     (5, [(10, Lit True 0)])])]),\n       (2, [(11, Lit False 1)])])\\<close>\n\nlemma \\<open>CC_mat (\n  Mat [\n    (0, [(5,Mat [\n      (1, [(6,Mat [(2, [(7,Lit False 0), (8,Lit True 1)])])]), \n      (3, [(9,Lit True 0)])])]), \n    (4, [(10,Lit False 1)])])\\<close> (is \\<open>CC_mat (Mat ?M)\\<close>)\nproof -\n  have ?thesis if \\<open>(\\<turnstile> \n    [(5,Mat [\n      (1, [(6,Mat [(2, [(7,Lit False 0), (8,Lit True 1)])])]), \n      (3, [(9,Lit True 0)])])] ?M [])\\<close> \n    using that by simp\n  then have ?thesis if \\<open>(\\<turnstile> \n    [(9,Lit True 0)] ?M [])\\<close> \n    using that Decomposition by simp\n  moreover have \\<open>alpha_related ?M (4,[(10,Lit False 1)]) (9,Lit True 0)\\<close>sorry\n  ultimately have ?thesis if \\<open>(\\<turnstile> \n    [(10,Lit False 1)] ?M [(9,True, 0)])\\<close> \n    using that Extention Axiom sorry\n  then have ?thesis if \\<open>(\\<turnstile> \n    [Lit False 0, Lit True 1] ?M [(False,1),(True, 0)])\\<close> \n    using that Extention Axiom by simp\n  then have ?thesis if \\<open>(\\<turnstile> \n    [Lit False 0, Lit True 1] ?M [(True, 0),(False,1)])\\<close> \n    using that Permutation by simp\n  then have ?thesis if \\<open>(\\<turnstile> \n    [Lit True 1] ?M [(True, 0),(False,1)])\\<close> \n    using that Reduction by fast\n  then have ?thesis if \\<open>(\\<turnstile> \n    [Lit True 1] ?M [(False,1),(True, 0)])\\<close> \n    using that Permutation by simp\n  then show ?thesis using Reduction Axiom by simp\nqed\n(*-------------------------*)\n\n(*---Paths-----------------*)\nfun is_path where\n  \\<open>is_path p (Lit pol prop) = member (pol, prop) p\\<close> |\n  \\<open>is_path p (Mat cs) = (\\<forall> (_,ms) \\<in> set cs. \\<exists> m \\<in> set ms. is_path p m)\\<close>\n\ndefinition \\<open>\n  cc_valid c m p \\<equiv> \n    \\<forall> p'. is_path p' m \\<longrightarrow> (\\<exists> m' \\<in> set c. is_path p m') \\<longrightarrow> set p \\<subseteq> set p' \\<longrightarrow> \n      (\\<exists> prop. member (True,prop) p \\<and> member (False,prop) p)\\<close>\n\ntheorem cc_soundness: \\<open>(\\<turnstile> c m p) \\<Longrightarrow> cc_valid c m p\\<close>\nproof (induct rule: CC.induct)\n  case (Axiom uu uv)\n  then show ?case \n    using cc_valid_def by simp\nnext\n  case (Reduction C M pol prp P pol')\n  then show ?case sorry\nnext\n  case (Permutation C M P C' P')\n  then show ?case sorry\nnext\n  case (Extention C' M pol prp P C)\n  then show ?case sorry\nnext\n  case (Decomposition C' C M P uw cs)\n  then show ?case sorry\nqed\n\n\ndefinition \\<open>\n  mat_valid m \\<equiv> \\<forall> p. is_path p m \\<longrightarrow> (\\<exists> prop. member (True,prop) p \\<and> member (False,prop) p)\\<close>\n\ntheorem mat_soundness: \\<open>cc_valid c (Mat ((cid,c) # m)) [] \\<Longrightarrow> mat_valid (Mat ((cid,c) # m))\\<close> sorry\n(*-------------------------*)\n\n(*---Semantics-------------*)\nprimrec form_semantics where\n  \\<open>form_semantics i (Atm a) = i a\\<close> |\n  \\<open>form_semantics i (Neg p) = (\\<not>form_semantics i p)\\<close> |\n  \\<open>form_semantics i (Con p1 p2) = (form_semantics i p1 \\<and> form_semantics i p2)\\<close> |\n  \\<open>form_semantics i (Dis p1 p2) = (form_semantics i p1 \\<or> form_semantics i p2)\\<close> |\n  \\<open>form_semantics i (Imp p1 p2) = (form_semantics i p1 \\<longrightarrow> form_semantics i p2)\\<close>\n\nfun mat_semantics where \n  \\<open>mat_semantics i (Lit pol prp) = (i prp \\<longleftrightarrow> \\<not>pol)\\<close> |\n  \\<open>mat_semantics i (Mat cs) = (\\<exists> (c,ms) \\<in> set cs. \\<forall> m \\<in> set ms. mat_semantics i m)\\<close>\n\nlemma path_to_semantics_soundness: \\<open>\n  mat_valid m \\<Longrightarrow> \\<forall> i. mat_semantics i m\\<close> sorry\n\nlemma mat_to_form: \\<open>\n  form_to_clauses mx pol p = (n,m) \\<Longrightarrow> \n  mat_semantics i m \\<Longrightarrow> \n  (\\<not>pol \\<longleftrightarrow> form_semantics i p)\\<close> \nproof (induct p arbitrary: mx pol n m)\n  case (Atm a)\n  then show ?case by auto\nnext\n  case (Neg p)\n  then show ?case \n    by auto\nnext\n  case (Con p1 p2)\n  then show ?case sorry\nnext\n  case (Dis p1 p2)\n  then show ?case sorry\nnext\n  case (Imp p1 p2)\n  then show ?case sorry\nqed\n\ntheorem form_soundness: \\<open>\n  form_to_clauses 0 False p = (n,Mat ((cid,c) # cs)) \\<Longrightarrow>\n  (\\<turnstile> c (Mat ((cid,c) # cs)) []) \\<Longrightarrow>\n  \\<forall> i. form_semantics i p\\<close> (is \\<open>?translation \\<Longrightarrow> ?proof \\<Longrightarrow> ?valid\\<close>)\nproof-\n  let ?m = \\<open>Mat ((cid,c) # cs)\\<close>\n  assume t:?translation\n  assume ?proof\n  then have \\<open>mat_valid ?m\\<close>\n    by (simp add: cc_soundness mat_soundness)\n  then have \\<open>\\<forall> i. mat_semantics i ?m\\<close>\n    using path_to_semantics_soundness by blast\n  then show ?valid \n    using mat_to_form t by blast\nqed\n\nend", "meta": {"author": "Barrikad", "repo": "nanoCoP-in-Isabelle", "sha": "5669ba700517a85b8fb2268ead80c921c3ad4132", "save_path": "github-repos/isabelle/Barrikad-nanoCoP-in-Isabelle", "path": "github-repos/isabelle/Barrikad-nanoCoP-in-Isabelle/nanoCoP-in-Isabelle-5669ba700517a85b8fb2268ead80c921c3ad4132/nanocop_propositional.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527944504227, "lm_q2_score": 0.8519528038477825, "lm_q1q2_score": 0.7258235719779912}}
{"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 \"MainRLT\"\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 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 r {..<card S} \\<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 h {..<card M}\"\nproof\n  show \"bij_betw (enumerate M) {..<card M} M\"\n    by (simp add: assms finite_bij_enumerate)\n  show \"strict_mono_on (enumerate M) {..<card M}\"\n    by (simp add: assms finite_enumerate_mono strict_mono_on_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/Infinite_Set.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127678225575, "lm_q2_score": 0.8499711718571774, "lm_q1q2_score": 0.725801235929945}}
{"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_08\n  imports \"../../Test_Base\"\nbegin\n\ndatatype Nat = Z | S \"Nat\"\n\nfun t22 :: \"Nat => Nat => Nat\" where\n  \"t22 (Z) y = y\"\n| \"t22 (S z) y = S (t22 z y)\"\n\nfun t2 :: \"Nat => Nat => Nat\" where\n  \"t2 (Z) y = Z\"\n| \"t2 (S z) (Z) = S z\"\n| \"t2 (S z) (S x2) = t2 z x2\"\n\ntheorem property0 :\n  \"((t2 (t22 k m) (t22 k n)) = (t2 m n))\"\n  find_proof DInd\n  apply (induct arbitrary: n rule: TIP_prop_08.t22.induct)\n   apply auto\n  done\n\ntheorem property0' :\n  \"((t2 (t22 k m) (t22 k n)) = (t2 m n))\"\n  apply(induct k arbitrary:n m)(*equivalent to apply (induct arbitrary: n rule: TIP_prop_08.t22.induct)*)\n   apply auto\n  done\n\ntheorem property0'' :\n  \"((t2 (t22 k m) (t22 k n)) = (t2 m n))\"\n  (*applying induction on \"k\" is the natural choice:\n    \"t22\" is the unique innermost recursive constant, which pattern-matches on the first parameter.\n    Furthermore, the other recursive function, \"t2\" takes \"t22\" in its arguments, and\n    the two \"t22\"s have different arguments (\"m\" and \"n\"). Therefore, without applying induction on\n    \"t22\"'s argument we cannot finish this proof.*)\n  apply(induct k)\n   apply auto\n  done\n\ntheorem property0''' :(*sub-optimal proof*)\n  \"((t2 (t22 k m) (t22 k n)) = (t2 m n))\"\n  apply(induct m)\n   apply clarsimp\n   apply(induct k)(*extra induction*)\n    apply fastforce+\n  apply(induct k)(*extra induction*)\n   apply auto\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_08.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.849971175657575, "lm_q2_score": 0.8539127510928476, "lm_q1q2_score": 0.7258012249553818}}
{"text": "\ntheory ListLexorder\nimports Main\nbegin\n\nsection\\<open>Detour: Lexicographic ordering for lists\\<close>\ntext\\<open>Simplicial complexes are defined as sets of sets.\nTo conveniently run computations on them, we convert those sets to lists via @{const sorted_list_of_set}.\nThis requires providing an arbitrary linear order for lists.\nWe pick a lexicographic order.\\<close>\n\n(* There's probably an easier way to get a sorted list of lists from a set of lists. Some lexicographic ordering does have to exist. No idea... *)\n\ndatatype 'a :: linorder linorder_list = LinorderList \"'a list\"\n\ndefinition \"linorder_list_unwrap L \\<equiv> case L of LinorderList L \\<Rightarrow> L\" (* Meh, there is a way to get datatype to generate this. I forgot *)\n\nfun less_eq_linorder_list_pre where\n  \"less_eq_linorder_list_pre (LinorderList []) (LinorderList []) = True\" |\n  \"less_eq_linorder_list_pre (LinorderList []) _ = True\" |\n  \"less_eq_linorder_list_pre _ (LinorderList []) = False\" |\n  \"less_eq_linorder_list_pre (LinorderList (a # as)) (LinorderList (b # bs))\n    = (if a = b then less_eq_linorder_list_pre (LinorderList as) (LinorderList bs) else a < b)\"\n\ninstantiation linorder_list :: (linorder) linorder\nbegin\ndefinition \"less_linorder_list x y \\<equiv>\n              (less_eq_linorder_list_pre x y \\<and> \\<not> less_eq_linorder_list_pre y x)\"\ndefinition \"less_eq_linorder_list x y \\<equiv> less_eq_linorder_list_pre x y\"\ninstance\nproof (standard; unfold less_eq_linorder_list_def less_linorder_list_def)\n  fix x y z\n  show \"less_eq_linorder_list_pre x x\"\n  proof(induction x)\n    case (LinorderList xa)\n    then show ?case by(induction xa; simp)\n  qed\n  show \"less_eq_linorder_list_pre x y \\<Longrightarrow> less_eq_linorder_list_pre y x \\<Longrightarrow> x = y\"\n    by(induction x y rule: less_eq_linorder_list_pre.induct; simp split: if_splits)\n  show \"less_eq_linorder_list_pre x y \\<or> less_eq_linorder_list_pre y x\"\n    by(induction x y rule: less_eq_linorder_list_pre.induct; auto)\n  show \"less_eq_linorder_list_pre x y \\<Longrightarrow> less_eq_linorder_list_pre y z \\<Longrightarrow> less_eq_linorder_list_pre x z\"\n  proof(induction x z arbitrary: y rule: less_eq_linorder_list_pre.induct)\n    case (3 va vb)\n    then show ?case\n      using less_eq_linorder_list_pre.elims(2) by blast\n  next\n    case (4 a1 as b1 bs)\n    obtain y1 ys where y: \"y = LinorderList (y1 # ys)\"\n      using \"4.prems\"(1) less_eq_linorder_list_pre.elims(2) by blast\n    then show ?case proof(cases \"a1 = b1\")\n      case True\n      have prems: \"less_eq_linorder_list_pre (LinorderList as) (LinorderList ys)\" \"less_eq_linorder_list_pre (LinorderList ys) (LinorderList bs)\"\n        by (metis \"4.prems\" True y less_eq_linorder_list_pre.simps(4) not_less_iff_gr_or_eq)+\n      note IH = \"4.IH\"[OF _ this]\n      then show ?thesis\n        using True by simp\n\n    next\n      case False\n        then show ?thesis using \"4.prems\" less_trans y by (simp  split: if_splits)\n      qed\n  qed simp_all\nqed simp\n\nend\n\ntext\\<open>The main product of this theory file:\\<close>\ndefinition \"sorted_list_of_list_set L \\<equiv>\n  map linorder_list_unwrap (sorted_list_of_set (LinorderList ` L))\"\n\nlemma set_sorted_list_of_list_set[simp]:\n  \"finite L \\<Longrightarrow> set (sorted_list_of_list_set L) = L\"\n  by(force simp add: sorted_list_of_list_set_def linorder_list_unwrap_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/Simplicial_complexes_and_boolean_functions/ListLexorder.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127380808499, "lm_q2_score": 0.84997116805678, "lm_q1q2_score": 0.7258012074051432}}
{"text": "(*\n  File:   Akra_Bazzi_Real.thy\n  Author: Manuel Eberl <eberlm@in.tum.de>\n\n  The continuous version of the Akra-Bazzi theorem for functions on the reals.\n*)\n\nsection \\<open>The continuous Akra-Bazzi theorem\\<close>\ntheory Akra_Bazzi_Real\nimports\n  Complex_Main\n  Akra_Bazzi_Asymptotics\nbegin\n\ntext \\<open>\n  We want to be generic over the integral definition used; we fix some arbitrary\n  notions of integrability and integral and assume just the properties we need.\n  The user can then instantiate the theorems with any desired integral definition.\n\\<close>\nlocale akra_bazzi_integral =\n  fixes integrable :: \"(real \\<Rightarrow> real) \\<Rightarrow> real \\<Rightarrow> real \\<Rightarrow> bool\"\n    and integral   :: \"(real \\<Rightarrow> real) \\<Rightarrow> real \\<Rightarrow> real \\<Rightarrow> real\"\n  assumes integrable_const: \"c \\<ge> 0 \\<Longrightarrow> integrable (\\<lambda>_. c) a b\"\n      and integral_const:   \"c \\<ge> 0 \\<Longrightarrow> a \\<le> b \\<Longrightarrow> integral (\\<lambda>_. c) a b = (b - a) * c\"\n      and integrable_subinterval:\n            \"integrable f a b \\<Longrightarrow> a \\<le> a' \\<Longrightarrow> b' \\<le> b \\<Longrightarrow> integrable f a' b'\"\n      and integral_le:\n            \"integrable f a b \\<Longrightarrow> integrable g a b \\<Longrightarrow> (\\<And>x. x \\<in> {a..b} \\<Longrightarrow> f x \\<le> g x) \\<Longrightarrow>\n                 integral f a b \\<le> integral g a b\"\n      and integral_combine:\n            \"a \\<le> c \\<Longrightarrow> c \\<le> b \\<Longrightarrow> integrable f a b \\<Longrightarrow>\n                 integral f a c + integral f c b = integral f a b\"\nbegin\nlemma integral_nonneg:\n  \"a \\<le> b \\<Longrightarrow> integrable f a b \\<Longrightarrow> (\\<And>x. x \\<in> {a..b} \\<Longrightarrow> f x \\<ge> 0) \\<Longrightarrow> integral f a b \\<ge> 0\"\n  using integral_le[OF integrable_const[of 0], of f a b]  by (simp add: integral_const)\nend\n\n\ndeclare sum.cong[fundef_cong]\n\nlemma strict_mono_imp_ex1_real:\n  fixes f :: \"real \\<Rightarrow> real\"\n  assumes lim_neg_inf: \"LIM x at_bot. f x :> at_top\"\n  assumes lim_inf: \"(f \\<longlongrightarrow> z) at_top\"\n  assumes mono: \"\\<And>a b. a < b \\<Longrightarrow> f b < f a\"\n  assumes cont: \"\\<And>x. isCont f x\"\n  assumes y_greater_z: \"z < y\"\n  shows   \"\\<exists>!x. f x = y\"\nproof (rule ex_ex1I)\n  fix a b assume \"f a = y\" \"f b = y\"\n  thus \"a = b\" by (cases rule: linorder_cases[of a b]) (auto dest: mono)\nnext\n  from lim_neg_inf have \"eventually (\\<lambda>x. y \\<le> f x) at_bot\" by (subst (asm) filterlim_at_top) simp\n  then obtain l where l: \"\\<And>x. x \\<le> l \\<Longrightarrow> y \\<le> f x\" by (subst (asm) eventually_at_bot_linorder) auto\n\n  from order_tendstoD(2)[OF lim_inf y_greater_z]\n    obtain u where u: \"\\<And>x. x \\<ge> u \\<Longrightarrow> f x < y\" by (subst (asm) eventually_at_top_linorder) auto\n  define a where \"a = min l u\"\n  define b where \"b = max l u\"\n  have a: \"f a \\<ge> y\" unfolding a_def by (intro l) simp\n  moreover have b: \"f b < y\" unfolding b_def by (intro u) simp\n  moreover have a_le_b: \"a \\<le> b\" by (simp add: a_def b_def)\n  ultimately have \"\\<exists>x\\<ge>a. x \\<le> b \\<and> f x = y\" using cont by (intro IVT2) auto\n  thus \"\\<exists>x. f x = y\" by blast\nqed\n\ntext \\<open>The parameter @{term \"p\"} in the Akra-Bazzi theorem always exists and is unique.\\<close>\n\ndefinition akra_bazzi_exponent :: \"real list \\<Rightarrow> real list \\<Rightarrow> real\" where\n  \"akra_bazzi_exponent as bs \\<equiv> (THE p. (\\<Sum>i<length as. as!i * bs!i powr p) = 1)\"\n\nlocale akra_bazzi_params =\n  fixes k :: nat and as bs :: \"real list\"\n  assumes length_as: \"length as = k\"\n  and     length_bs: \"length bs = k\"\n  and     k_not_0:   \"k \\<noteq> 0\"\n  and     a_ge_0:    \"a \\<in> set as \\<Longrightarrow> a \\<ge> 0\"\n  and     b_bounds:  \"b \\<in> set bs \\<Longrightarrow> b \\<in> {0<..<1}\"\nbegin\n\nabbreviation p :: real where \"p \\<equiv> akra_bazzi_exponent as bs\"\n\nlemma p_def: \"p = (THE p. (\\<Sum>i<k. as!i * bs!i powr p) = 1)\"\n  by (simp add: akra_bazzi_exponent_def length_as)\n\nlemma b_pos: \"b \\<in> set bs \\<Longrightarrow> b > 0\" and b_less_1: \"b \\<in> set bs \\<Longrightarrow> b < 1\"\n  using b_bounds by simp_all\n\nlemma as_nonempty [simp]: \"as \\<noteq> []\" and bs_nonempty [simp]: \"bs \\<noteq> []\"\n  using length_as length_bs k_not_0 by auto\n\nlemma a_in_as[intro, simp]: \"i < k \\<Longrightarrow> as ! i \\<in> set as\"\n  by (rule nth_mem) (simp add: length_as)\n\nlemma b_in_bs[intro, simp]: \"i < k \\<Longrightarrow> bs ! i \\<in> set bs\"\n  by (rule nth_mem) (simp add: length_bs)\n\nend\n\n\nlocale akra_bazzi_params_nonzero =\n  fixes k :: nat and as bs :: \"real list\"\n  assumes length_as: \"length as = k\"\n  and     length_bs: \"length bs = k\"\n  and     a_ge_0:    \"a \\<in> set as \\<Longrightarrow> a \\<ge> 0\"\n  and     ex_a_pos:  \"\\<exists>a\\<in>set as. a > 0\"\n  and     b_bounds:  \"b \\<in> set bs \\<Longrightarrow> b \\<in> {0<..<1}\"\nbegin\n\nsublocale akra_bazzi_params k as bs\n by unfold_locales (insert length_as length_bs a_ge_0 ex_a_pos b_bounds, auto)\n\nlemma akra_bazzi_p_strict_mono:\n  assumes \"x < y\"\n  shows \"(\\<Sum>i<k. as!i * bs!i powr y) < (\\<Sum>i<k. as!i * bs!i powr x)\"\nproof (intro sum_strict_mono_ex1 ballI)\n  from ex_a_pos obtain a where \"a \\<in> set as\" \"a > 0\" by blast\n  then obtain i where \"i < k\" \"as!i > 0\" by (force simp: in_set_conv_nth length_as)\n  with b_bounds \\<open>x < y\\<close> have \"as!i * bs!i powr y < as!i * bs!i powr x\"\n    by (intro mult_strict_left_mono powr_less_mono') auto\n  with \\<open>i < k\\<close> show \"\\<exists>i\\<in>{..<k}. as!i * bs!i powr y < as!i * bs!i powr x\" by blast\nnext\n  fix i assume \"i \\<in> {..<k}\"\n  with a_ge_0 b_bounds[of \"bs!i\"] \\<open>x < y\\<close> show \"as!i * bs!i powr y \\<le> as!i * bs!i powr x\"\n    by (intro mult_left_mono powr_mono') simp_all\nqed simp_all\n\nlemma akra_bazzi_p_mono:\n  assumes \"x \\<le> y\"\n  shows \"(\\<Sum>i<k. as!i * bs!i powr y) \\<le> (\\<Sum>i<k. as!i * bs!i powr x)\"\napply (cases \"x < y\")\nusing akra_bazzi_p_strict_mono[of x y] assms apply simp_all\ndone\n\n\nlemma akra_bazzi_p_unique:\n  \"\\<exists>!p. (\\<Sum>i<k. as!i * bs!i powr p) = 1\"\nproof (rule strict_mono_imp_ex1_real)\n  from as_nonempty have [simp]: \"k > 0\" by (auto simp: length_as[symmetric])\n  have [simp]: \"\\<And>i. i < k \\<Longrightarrow> as!i \\<ge> 0\" by (rule a_ge_0) simp\n  from ex_a_pos obtain a where \"a \\<in> set as\" \"a > 0\" by blast\n  then obtain i where i: \"i < k\" \"as!i > 0\" by (force simp: in_set_conv_nth length_as)\n\n  hence \"LIM p at_bot. as!i * bs!i powr p :> at_top\" using b_bounds i\n    by (intro filterlim_tendsto_pos_mult_at_top[OF tendsto_const] real_powr_at_bot_neg) simp_all\n  moreover have \"\\<forall>p. as!i*bs!i powr p \\<le> (\\<Sum>i\\<in>{..<k}. as ! i * bs ! i powr p)\"\n  proof\n    fix p :: real\n    from a_ge_0 b_bounds have \"(\\<Sum>i\\<in>{..<k}-{i}. as ! i * bs ! i powr p) \\<ge> 0\"\n      by (intro sum_nonneg mult_nonneg_nonneg) simp_all\n    also have \"as!i * bs!i powr p + ... = (\\<Sum>i\\<in>insert i {..<k}. as ! i * bs ! i powr p)\"\n      by (simp add: sum.insert_remove)\n    also from i have \"insert i {..<k} = {..<k}\" by blast\n    finally show \"as!i*bs!i powr p \\<le> (\\<Sum>i\\<in>{..<k}. as ! i * bs ! i powr p)\" by simp\n  qed\n  ultimately show \"LIM p at_bot. \\<Sum>i<k. as ! i * bs ! i powr p :> at_top\"\n    by (rule filterlim_at_top_mono[OF _ always_eventually])\nnext\n  from b_bounds show \"((\\<lambda>x. \\<Sum>i<k. as ! i * bs ! i powr x) \\<longlongrightarrow> (\\<Sum>i<k. 0)) at_top\"\n    by (intro tendsto_sum tendsto_mult_right_zero real_powr_at_top_neg) simp_all\nnext\n  fix x\n  from b_bounds have A: \"\\<And>i. i < k \\<Longrightarrow> bs ! i > 0\" by simp\n  show \"isCont (\\<lambda>x. \\<Sum>i<k. as ! i * bs ! i powr x) x\"\n    using b_bounds[OF nth_mem] by (intro continuous_intros) (auto dest: A)\nqed (simp_all add: akra_bazzi_p_strict_mono)\n\nlemma p_props:  \"(\\<Sum>i<k. as!i * bs!i powr p) = 1\"\n  and p_unique: \"(\\<Sum>i<k. as!i * bs!i powr p') = 1 \\<Longrightarrow> p = p'\"\nproof-\n  from theI'[OF akra_bazzi_p_unique] the1_equality[OF akra_bazzi_p_unique]\n    show \"(\\<Sum>i<k. as!i * bs!i powr p) = 1\" \"(\\<Sum>i<k. as!i * bs!i powr p') = 1 \\<Longrightarrow> p = p'\"\n    unfolding p_def by - blast+\nqed\n\nlemma p_greaterI: \"1 < (\\<Sum>i<k. as!i * bs!i powr p') \\<Longrightarrow> p' < p\"\n  by (rule disjE[OF le_less_linear, of p p'], drule akra_bazzi_p_mono, subst (asm) p_props, simp_all)\n\nlemma p_lessI: \"1 > (\\<Sum>i<k. as!i * bs!i powr p') \\<Longrightarrow> p' > p\"\n  by (rule disjE[OF le_less_linear, of p' p], drule akra_bazzi_p_mono, subst (asm) p_props, simp_all)\n\nlemma p_geI: \"1 \\<le> (\\<Sum>i<k. as!i * bs!i powr p') \\<Longrightarrow> p' \\<le> p\"\n  by (rule disjE[OF le_less_linear, of p' p], simp, drule akra_bazzi_p_strict_mono,\n      subst (asm) p_props, simp_all)\n\nlemma p_leI: \"1 \\<ge> (\\<Sum>i<k. as!i * bs!i powr p') \\<Longrightarrow> p' \\<ge> p\"\n  by (rule disjE[OF le_less_linear, of p p'], simp, drule akra_bazzi_p_strict_mono,\n      subst (asm) p_props, simp_all)\n\nlemma p_boundsI: \"(\\<Sum>i<k. as!i * bs!i powr x) \\<le> 1 \\<and> (\\<Sum>i<k. as!i * bs!i powr y) \\<ge> 1 \\<Longrightarrow> p \\<in> {y..x}\"\n  by (elim conjE, drule p_leI, drule p_geI, simp)\n\nlemma p_boundsI': \"(\\<Sum>i<k. as!i * bs!i powr x) < 1 \\<and> (\\<Sum>i<k. as!i * bs!i powr y) > 1 \\<Longrightarrow> p \\<in> {y<..<x}\"\n  by (elim conjE, drule p_lessI, drule p_greaterI, simp)\n\nlemma p_nonneg: \"sum_list as \\<ge> 1 \\<Longrightarrow> p \\<ge> 0\"\nproof (rule p_geI)\n  assume \"sum_list as \\<ge> 1\"\n  also have \"... = (\\<Sum>i<k. as!i)\" by (simp add: sum_list_sum_nth length_as atLeast0LessThan)\n  also {\n    fix i assume \"i < k\"\n    with b_bounds have \"bs!i > 0\" by simp\n    hence \"as!i * bs!i powr 0 = as!i\" by simp\n  }\n  hence \"(\\<Sum>i<k. as!i) = (\\<Sum>i<k. as!i * bs!i powr 0)\" by (intro sum.cong) simp_all\n  finally show \"1 \\<le> (\\<Sum>i<k. as ! i * bs ! i powr 0)\" .\nqed\n\nend\n\n\nlocale akra_bazzi_real_recursion =\n  fixes as bs :: \"real list\" and hs :: \"(real \\<Rightarrow> real) list\" and k :: nat and x\\<^sub>0 x\\<^sub>1 hb e p :: real\n  assumes length_as: \"length as = k\"\n  and     length_bs: \"length bs = k\"\n  and     length_hs: \"length hs = k\"\n  and     k_not_0:   \"k \\<noteq> 0\"\n  and     a_ge_0:    \"a \\<in> set as \\<Longrightarrow> a \\<ge> 0\"\n  and     b_bounds:  \"b \\<in> set bs \\<Longrightarrow> b \\<in> {0<..<1}\"\n\n  (* The recursively-defined function *)\n  and     x0_ge_1:      \"x\\<^sub>0 \\<ge> 1\"\n  and     x0_le_x1:     \"x\\<^sub>0 \\<le> x\\<^sub>1\"\n  and     x1_ge:        \"b \\<in> set bs \\<Longrightarrow> x\\<^sub>1 \\<ge> 2 * x\\<^sub>0 * inverse b\"\n  (* Bounds on the variation functions *)\n  and     e_pos:        \"e > 0\"\n  and     h_bounds:     \"x \\<ge> x\\<^sub>1 \\<Longrightarrow> h \\<in> set hs \\<Longrightarrow> \\<bar>h x\\<bar> \\<le> hb * x / ln x powr (1 + e)\"\n  (* Asymptotic inequalities *)\n  and     asymptotics:  \"x \\<ge> x\\<^sub>0 \\<Longrightarrow> b \\<in> set bs \\<Longrightarrow> akra_bazzi_asymptotics b hb e p x\"\nbegin\n\nsublocale akra_bazzi_params k as bs\n  using length_as length_bs k_not_0 a_ge_0 b_bounds by unfold_locales\n\nlemma h_in_hs[intro, simp]: \"i < k \\<Longrightarrow> hs ! i \\<in> set hs\"\n  by (rule nth_mem) (simp add: length_hs)\n\nlemma x1_gt_1: \"x\\<^sub>1 > 1\"\nproof-\n  from bs_nonempty obtain b where \"b \\<in> set bs\" by (cases bs) auto\n  from b_pos[OF this] b_less_1[OF this] x0_ge_1 have \"1 < 2 * x\\<^sub>0 * inverse b\"\n    by (simp add: field_simps)\n  also from x1_ge and \\<open>b \\<in> set bs\\<close> have \"... \\<le> x\\<^sub>1\" by simp\n  finally show ?thesis .\nqed\n\nlemma x1_ge_1: \"x\\<^sub>1 \\<ge> 1\" using x1_gt_1 by simp\n\nlemma x1_pos: \"x\\<^sub>1 > 0\" using x1_ge_1 by simp\n\nlemma bx_le_x: \"x \\<ge> 0 \\<Longrightarrow> b \\<in> set bs \\<Longrightarrow>  b * x \\<le> x\"\n  using b_pos[of b] b_less_1[of b] by (intro mult_left_le_one_le) (simp_all)\n\nlemma x0_pos: \"x\\<^sub>0 > 0\" using x0_ge_1 by simp\n\nlemma\n  assumes \"x \\<ge> x\\<^sub>0\" \"b \\<in> set bs\"\n  shows x0_hb_bound0: \"hb / ln x powr (1 + e) < b/2\"\n  and   x0_hb_bound1: \"hb / ln x powr (1 + e) < (1 - b) / 2\"\n  and   x0_hb_bound2: \"x*(1 - b - hb / ln x powr (1 + e)) > 1\"\nusing asymptotics[OF assms] unfolding akra_bazzi_asymptotic_defs by blast+\n\nlemma step_diff:\n  assumes \"i < k\" \"x \\<ge> x\\<^sub>1\"\n  shows   \"bs ! i * x + (hs ! i) x + 1 < x\"\nproof-\n  have \"bs ! i * x + (hs ! i) x + 1 \\<le> bs ! i * x + \\<bar>(hs ! i) x\\<bar> + 1\" by simp\n  also from assms have \"\\<bar>(hs ! i) x\\<bar> \\<le> hb * x / ln x powr (1 + e)\" by (simp add: h_bounds)\n  also from assms x0_le_x1 have \"x*(1 - bs ! i - hb / ln x powr (1 + e)) > 1\"\n    by (simp add: x0_hb_bound2)\n  hence \"bs ! i * x + hb * x / ln x powr (1 + e) + 1 < x\" by (simp add: algebra_simps)\n  finally show ?thesis by simp\nqed\n\nlemma step_le_x: \"i < k \\<Longrightarrow> x \\<ge> x\\<^sub>1 \\<Longrightarrow> bs ! i * x + (hs ! i) x \\<le> x\"\n  by (drule (1) step_diff) simp\n\nlemma x0_hb_bound0': \"\\<And>x b. x \\<ge> x\\<^sub>0 \\<Longrightarrow> b \\<in> set bs \\<Longrightarrow> hb / ln x powr (1 + e) < b\"\n  by (drule (1) x0_hb_bound0, erule less_le_trans) (simp add: b_pos)\n\nlemma step_pos:\n  assumes \"i < k\" \"x \\<ge> x\\<^sub>1\"\n  shows   \"bs ! i * x + (hs ! i) x > 0\"\nproof-\n  from assms x0_le_x1 have \"hb / ln x powr (1 + e) < bs ! i\" by (simp add: x0_hb_bound0')\n  with assms x0_pos x0_le_x1 have \"x * 0 < x * (bs ! i - hb / ln x powr (1 + e))\" by simp\n  also have \"... = bs ! i * x - hb * x / ln x powr (1 + e)\"\n    by (simp add: algebra_simps)\n  also from assms have \"-hb * x / ln x powr (1 + e) \\<le> -\\<bar>(hs ! i) x\\<bar>\" by (simp add: h_bounds)\n  hence \"bs ! i * x - hb * x / ln x powr (1 + e) \\<le> bs ! i * x + -\\<bar>(hs ! i) x\\<bar>\" by simp\n  also have \"-\\<bar>(hs ! i) x\\<bar> \\<le> (hs ! i) x\" by simp\n  finally show \"bs ! i * x + (hs ! i) x > 0\" by simp\nqed\n\nlemma step_nonneg: \"i < k \\<Longrightarrow> x \\<ge> x\\<^sub>1 \\<Longrightarrow> bs ! i * x + (hs ! i) x \\<ge> 0\"\n  by (drule (1) step_pos) simp\n\nlemma step_nonneg': \"i < k \\<Longrightarrow> x \\<ge> x\\<^sub>1 \\<Longrightarrow> bs ! i + (hs ! i) x / x \\<ge> 0\"\n  by (frule (1) step_nonneg, insert x0_pos x0_le_x1) (simp_all add: field_simps)\n\nlemma hb_nonneg: \"hb \\<ge> 0\"\nproof-\n  from k_not_0 and length_hs have \"hs \\<noteq> []\" by auto\n  then obtain h where h: \"h \\<in> set hs\" by (cases hs) auto\n  have \"0 \\<le> \\<bar>h x\\<^sub>1\\<bar>\" by simp\n  also from h have \"\\<bar>h x\\<^sub>1\\<bar> \\<le> hb * x\\<^sub>1 / ln x\\<^sub>1 powr (1+e)\" by (intro h_bounds) simp_all\n  finally have \"0 \\<le> hb * x\\<^sub>1 / ln x\\<^sub>1 powr (1 + e)\" .\n  hence \"0 \\<le> ... * (ln x\\<^sub>1 powr (1 + e) / x\\<^sub>1)\"\n    by (rule mult_nonneg_nonneg) (intro divide_nonneg_nonneg, insert x1_pos, simp_all)\n  also have \"... = hb\" using x1_gt_1 by (simp add: field_simps)\n  finally show ?thesis .\nqed\n\nlemma x0_hb_bound3:\n  assumes \"x \\<ge> x\\<^sub>1\" \"i < k\"\n  shows   \"x - (bs ! i * x + (hs ! i) x) \\<le> x\"\nproof-\n  have \"-(hs ! i) x \\<le> \\<bar>(hs ! i) x\\<bar>\" by simp\n  also from assms have \"... \\<le> hb * x / ln x powr (1 + e)\" by (simp add: h_bounds)\n  also have \"... = x * (hb / ln x powr (1 + e))\" by simp\n  also from assms x0_pos x0_le_x1 have \"... < x * bs ! i\"\n    by (intro mult_strict_left_mono x0_hb_bound0') simp_all\n  finally show ?thesis by (simp add: algebra_simps)\nqed\n\nlemma x0_hb_bound4:\n  assumes \"x \\<ge> x\\<^sub>1\" \"i < k\"\n  shows   \"(bs ! i + (hs ! i) x / x) > bs ! i / 2\"\nproof-\n  from assms x0_le_x1 have \"hb / ln x powr (1 + e) < bs ! i / 2\" by (intro x0_hb_bound0) simp_all\n  with assms x0_pos x0_le_x1 have \"(-bs ! i / 2) * x < (-hb / ln x powr (1 + e)) * x\"\n    by (intro mult_strict_right_mono) simp_all\n  also from assms x0_pos have \"... \\<le> -\\<bar>(hs ! i) x\\<bar>\" using h_bounds by simp\n  also have \"... \\<le> (hs ! i) x\" by simp\n  finally show ?thesis using assms x1_pos by (simp add: field_simps)\nqed\n\nlemma x0_hb_bound4': \"x \\<ge> x\\<^sub>1 \\<Longrightarrow> i < k \\<Longrightarrow> (bs ! i + (hs ! i) x / x) \\<ge> bs ! i / 2\"\n  by (drule (1) x0_hb_bound4) simp\n\nlemma x0_hb_bound5:\n  assumes \"x \\<ge> x\\<^sub>1\" \"i < k\"\n  shows   \"(bs ! i + (hs ! i) x / x) \\<le> bs ! i * 3/2\"\nproof-\n  have \"(hs ! i) x \\<le> \\<bar>(hs ! i) x\\<bar>\" by simp\n  also from assms have \"... \\<le> hb * x / ln x powr (1 + e)\" by (simp add: h_bounds)\n  also have \"... = x * (hb / ln x powr (1 + e))\" by simp\n  also from assms x0_pos x0_le_x1 have \"... < x * (bs ! i / 2)\"\n    by (intro mult_strict_left_mono x0_hb_bound0) simp_all\n  finally show ?thesis using assms x1_pos by (simp add: field_simps)\nqed\n\nlemma x0_hb_bound6:\n  assumes \"x \\<ge> x\\<^sub>1\" \"i < k\"\n  shows   \"x * ((1 - bs ! i) / 2) \\<le> x - (bs ! i * x + (hs ! i) x)\"\nproof-\n  from assms x0_le_x1 have \"hb / ln x powr (1 + e) < (1 - bs ! i) / 2\" using x0_hb_bound1 by simp\n  with assms x1_pos have \"x * ((1 - bs ! i) / 2) \\<le> x * (1 - (bs ! i + hb / ln x powr (1 + e)))\"\n    by (intro mult_left_mono) (simp_all add: field_simps)\n  also have \"... = x - bs ! i * x + -hb * x / ln x powr (1 + e)\" by (simp add: algebra_simps)\n  also from h_bounds assms have \"-hb * x / ln x powr (1 + e) \\<le> -\\<bar>(hs ! i) x\\<bar>\"\n    by (simp add: length_hs)\n  also have \"... \\<le> -(hs ! i) x\" by simp\n  finally show ?thesis by (simp add: algebra_simps)\nqed\n\nlemma x0_hb_bound7:\n  assumes \"x \\<ge> x\\<^sub>1\" \"i < k\"\n  shows   \"bs!i*x + (hs!i) x > x\\<^sub>0\"\nproof-\n  from assms x0_le_x1 have x': \"x \\<ge> x\\<^sub>0\" by simp\n  from x1_ge assms have \"2 * x\\<^sub>0 * inverse (bs!i) \\<le> x\\<^sub>1\" by simp\n  with assms b_pos have \"x\\<^sub>0 \\<le> x\\<^sub>1 * (bs!i / 2)\" by (simp add: field_simps)\n  also from assms x' have \"bs!i/2 < bs!i + (hs!i) x / x\" by (intro x0_hb_bound4)\n  also from assms step_nonneg' x' have \"x\\<^sub>1 * ... \\<le> x * ...\" by (intro mult_right_mono) (simp_all)\n  also from assms x1_pos have \"x * (bs!i + (hs!i) x / x) = bs!i*x + (hs!i) x\"\n    by (simp add: field_simps)\n  finally show ?thesis using x1_pos by simp\nqed\n\nlemma x0_hb_bound7': \"x \\<ge> x\\<^sub>1 \\<Longrightarrow> i < k \\<Longrightarrow> bs!i*x + (hs!i) x > 1\"\n  by (rule le_less_trans[OF _ x0_hb_bound7]) (insert x0_le_x1 x0_ge_1, simp_all)\n\nlemma x0_hb_bound8:\n  assumes \"x \\<ge> x\\<^sub>1\" \"i < k\"\n  shows   \"bs!i*x - hb * x / ln x powr (1+e) > x\\<^sub>0\"\nproof-\n  from assms have \"2 * x\\<^sub>0 * inverse (bs!i) \\<le> x\\<^sub>1\" by (intro x1_ge) simp_all\n  with b_pos assms have \"x\\<^sub>0 \\<le> x\\<^sub>1 * (bs!i/2)\" by (simp add: field_simps)\n  also from assms b_pos have \"... \\<le> x * (bs!i/2)\" by simp\n  also from assms x0_le_x1 have \"hb / ln x powr (1+e) < bs!i/2\" by (intro x0_hb_bound0) simp_all\n  with assms have \"bs!i/2 < bs!i - hb / ln x powr (1+e)\" by (simp add: field_simps)\n  also have \"x * ... = bs!i*x - hb * x / ln x powr (1+e)\" by (simp add: algebra_simps)\n  finally show ?thesis using assms x1_pos by (simp add: field_simps)\nqed\n\nlemma x0_hb_bound8':\n  assumes \"x \\<ge> x\\<^sub>1\" \"i < k\"\n  shows   \"bs!i*x + hb * x / ln x powr (1+e) > x\\<^sub>0\"\nproof-\n  from assms have \"x\\<^sub>0 < bs!i*x - hb * x / ln x powr (1+e)\" by (rule x0_hb_bound8)\n  also from assms hb_nonneg x1_pos have \"hb * x / ln x powr (1+e) \\<ge> 0\"\n    by (intro mult_nonneg_nonneg divide_nonneg_nonneg) simp_all\n  hence \"bs!i*x - hb * x / ln x powr (1+e) \\<le> bs!i*x + hb * x / ln x powr (1+e)\" by simp\n  finally show ?thesis .\nqed\n\nlemma\n  assumes \"x \\<ge> x\\<^sub>0\"\n  shows   asymptotics1: \"i < k \\<Longrightarrow> 1 + ln x powr (- e / 2) \\<le>\n             (1 - hb * inverse (bs!i) * ln x powr -(1+e)) powr p *\n             (1 + ln (bs!i*x + hb*x/ln x powr (1+e)) powr (-e/2))\"\n  and     asymptotics2: \"i < k \\<Longrightarrow> 1 - ln x powr (- e / 2) \\<ge>\n             (1 + hb * inverse (bs!i) * ln x powr -(1+e)) powr p *\n             (1 - ln (bs!i*x + hb*x/ln x powr (1+e)) powr (-e/2))\"\n  and     asymptotics1': \"i < k \\<Longrightarrow> 1 + ln x powr (- e / 2) \\<le>\n             (1 + hb * inverse (bs!i) * ln x powr -(1+e)) powr p *\n             (1 + ln (bs!i*x + hb*x/ln x powr (1+e)) powr (-e/2))\"\n  and     asymptotics2': \"i < k \\<Longrightarrow> 1 - ln x powr (- e / 2) \\<ge>\n             (1 - hb * inverse (bs!i) * ln x powr -(1+e)) powr p *\n             (1 - ln (bs!i*x + hb*x/ln x powr (1+e)) powr (-e/2))\"\n  and     asymptotics3: \"(1 + ln x powr (- e / 2)) / 2 \\<le> 1\"\n  and     asymptotics4: \"(1 - ln x powr (- e / 2)) * 2 \\<ge> 1\"\n  and     asymptotics5: \"i < k \\<Longrightarrow> ln (bs!i*x - hb*x*ln x powr -(1+e)) powr (-e/2) < 1\"\napply -\nusing assms asymptotics[of x \"bs!i\"] unfolding akra_bazzi_asymptotic_defs\napply simp_all[4]\nusing assms asymptotics[of x \"bs!0\"] unfolding akra_bazzi_asymptotic_defs\napply simp_all[2]\nusing assms asymptotics[of x \"bs!i\"] unfolding akra_bazzi_asymptotic_defs\napply simp_all\ndone\n\n\nlemma x0_hb_bound9:\n  assumes \"x \\<ge> x\\<^sub>1\" \"i < k\"\n  shows   \"ln (bs!i*x + (hs!i) x) powr -(e/2) < 1\"\nproof-\n  from b_pos assms have \"0 < bs!i/2\" by simp\n  also from assms x0_le_x1 have \"... < bs!i + (hs!i) x / x\" by (intro x0_hb_bound4) simp_all\n  also from assms x1_pos have \"x * ... = bs!i*x + (hs!i) x\" by (simp add: field_simps)\n  finally have pos: \"bs!i*x + (hs!i) x > 0\" using assms x1_pos by simp\n  from x0_hb_bound8[OF assms] x0_ge_1 have pos': \"bs!i*x - hb * x / ln x powr (1+e) > 1\" by simp\n\n  from assms have \"-(hb * x / ln x powr (1+e)) \\<le> -\\<bar>(hs!i) x\\<bar>\"\n    by (intro le_imp_neg_le h_bounds) simp_all\n  also have \"... \\<le> (hs!i) x\" by simp\n  finally have \"ln (bs!i*x - hb * x / ln x powr (1+e)) \\<le> ln (bs!i*x + (hs!i) x)\"\n    using assms b_pos x0_pos pos' by (intro ln_mono mult_pos_pos pos) simp_all\n  hence \"ln (bs!i*x + (hs!i) x) powr -(e/2) \\<le> ln (bs!i*x - hb * x / ln x powr (1+e)) powr -(e/2)\"\n    using assms e_pos asymptotics5[of x] pos' by (intro powr_mono2' ln_gt_zero) simp_all\n  also have \"... < 1\" using asymptotics5[of x i] assms x0_le_x1\n    by (subst (asm) powr_minus) (simp_all add: field_simps)\n  finally show ?thesis .\nqed\n\n\ndefinition akra_bazzi_measure :: \"real \\<Rightarrow> nat\" where\n  \"akra_bazzi_measure x = nat \\<lceil>x\\<rceil>\"\n\nlemma akra_bazzi_measure_decreases:\n  assumes \"x \\<ge> x\\<^sub>1\" \"i < k\"\n  shows   \"akra_bazzi_measure (bs!i*x + (hs!i) x) < akra_bazzi_measure x\"\nproof-\n  from step_diff assms have \"(bs!i * x + (hs!i) x) + 1 < x\" by (simp add: algebra_simps)\n  hence \"\\<lceil>(bs!i * x + (hs!i) x) + 1\\<rceil> \\<le> \\<lceil>x\\<rceil>\" by (intro ceiling_mono) simp\n  hence \"\\<lceil>(bs!i * x + (hs!i) x)\\<rceil> < \\<lceil>x\\<rceil>\" by simp\n  with assms x1_pos have \"nat \\<lceil>(bs!i * x + (hs!i) x)\\<rceil> < nat \\<lceil>x\\<rceil>\" by (subst nat_mono_iff) simp_all\n  thus ?thesis unfolding akra_bazzi_measure_def .\nqed\n\n\nlemma akra_bazzi_induct[consumes 1, case_names base rec]:\n  assumes \"x \\<ge> x\\<^sub>0\"\n  assumes base: \"\\<And>x. x \\<ge> x\\<^sub>0 \\<Longrightarrow> x \\<le> x\\<^sub>1 \\<Longrightarrow> P x\"\n  assumes rec:  \"\\<And>x. x > x\\<^sub>1 \\<Longrightarrow> (\\<And>i. i < k \\<Longrightarrow> P (bs!i*x + (hs!i) x)) \\<Longrightarrow> P x\"\n  shows   \"P x\"\nproof (insert \\<open>x \\<ge> x\\<^sub>0\\<close>, induction \"akra_bazzi_measure x\" arbitrary: x rule: less_induct)\n  case less\n  show ?case\n  proof (cases \"x \\<le> x\\<^sub>1\")\n    case True\n    with base and \\<open>x \\<ge> x\\<^sub>0\\<close> show ?thesis .\n  next\n    case False\n    hence x: \"x > x\\<^sub>1\" by simp\n    thus ?thesis\n    proof (rule rec)\n      fix i assume i: \"i < k\"\n      from x0_hb_bound7[OF _ i, of x] x have \"bs!i*x + (hs!i) x \\<ge> x\\<^sub>0\" by simp\n      with i x show \"P (bs ! i * x + (hs ! i) x)\"\n        by (intro less akra_bazzi_measure_decreases) simp_all\n    qed\n  qed\nqed\n\nend\n\n\nlocale akra_bazzi_real = akra_bazzi_real_recursion +\n  fixes integrable integral\n  assumes integral: \"akra_bazzi_integral integrable integral\"\n  fixes f :: \"real \\<Rightarrow> real\"\n  and   g :: \"real \\<Rightarrow> real\"\n  and   C :: real\n  assumes p_props:      \"(\\<Sum>i<k. as!i * bs!i powr p) = 1\"\n  and     f_base:       \"x \\<ge> x\\<^sub>0 \\<Longrightarrow> x \\<le> x\\<^sub>1 \\<Longrightarrow> f x \\<ge> 0\"\n  and     f_rec:        \"x > x\\<^sub>1 \\<Longrightarrow> f x = g x + (\\<Sum>i<k. as!i * f (bs!i * x + (hs!i) x))\"\n  and     g_nonneg:     \"x \\<ge> x\\<^sub>0 \\<Longrightarrow> g x \\<ge> 0\"\n  and     C_bound:      \"b \\<in> set bs \\<Longrightarrow> x \\<ge> x\\<^sub>1 \\<Longrightarrow> C*x \\<le> b*x - hb*x/ln x powr (1+e)\"\n  and     g_integrable: \"x \\<ge> x\\<^sub>0 \\<Longrightarrow> integrable (\\<lambda>u. g u / u powr (p + 1)) x\\<^sub>0 x\"\nbegin\n\ninterpretation akra_bazzi_integral integrable integral by (rule integral)\n\nlemma akra_bazzi_integrable:\n  \"a \\<ge> x\\<^sub>0 \\<Longrightarrow> a \\<le> b \\<Longrightarrow> integrable (\\<lambda>x. g x / x powr (p + 1)) a b\"\n  by (rule integrable_subinterval[OF g_integrable, of b]) simp_all\n\ndefinition g_approx :: \"nat \\<Rightarrow> real \\<Rightarrow> real\" where\n  \"g_approx i x = x powr p * integral (\\<lambda>u. g u / u powr (p + 1)) (bs!i * x + (hs!i) x) x\"\n\nlemma f_nonneg: \"x \\<ge> x\\<^sub>0 \\<Longrightarrow> f x \\<ge> 0\"\nproof (induction x rule: akra_bazzi_induct)\n  case (base x)\n  with f_base[of x] show ?case by simp\nnext\n  case (rec x)\n  with x0_le_x1 have \"g x \\<ge> 0\" by (intro g_nonneg) simp_all\n  moreover {\n    fix i assume i: \"i < k\"\n    with rec.IH have \"f (bs!i*x + (hs!i) x) \\<ge> 0\" by simp\n    with i have \"as!i * f (bs!i*x + (hs!i) x) \\<ge> 0\"\n        by (intro mult_nonneg_nonneg[OF a_ge_0]) simp_all\n  }\n  hence \"(\\<Sum>i<k. as!i * f (bs!i*x + (hs!i) x)) \\<ge> 0\" by (intro sum_nonneg) blast\n  ultimately show \"f x \\<ge> 0\" using rec.hyps by (subst f_rec) simp_all\nqed\n\n\ndefinition f_approx :: \"real \\<Rightarrow> real\" where\n  \"f_approx x = x powr p * (1 + integral (\\<lambda>u. g u / u powr (p + 1)) x\\<^sub>0 x)\"\n\nlemma f_approx_aux:\n  assumes \"x \\<ge> x\\<^sub>0\"\n  shows   \"1 + integral (\\<lambda>u. g u / u powr (p + 1)) x\\<^sub>0 x \\<ge> 1\"\nproof-\n  from assms have \"integral (\\<lambda>u. g u / u powr (p + 1)) x\\<^sub>0 x \\<ge> 0\"\n    by (intro integral_nonneg ballI g_nonneg divide_nonneg_nonneg g_integrable) simp_all\n  thus ?thesis by simp\nqed\n\nlemma f_approx_pos: \"x \\<ge> x\\<^sub>0 \\<Longrightarrow> f_approx x > 0\"\n  unfolding f_approx_def by (intro mult_pos_pos, insert x0_pos, simp, drule f_approx_aux, simp)\n\nlemma f_approx_nonneg: \"x \\<ge> x\\<^sub>0 \\<Longrightarrow> f_approx x \\<ge> 0\"\n  using f_approx_pos[of x] by simp\n\n\nlemma f_approx_bounded_below:\n  obtains c where \"\\<And>x. x \\<ge> x\\<^sub>0 \\<Longrightarrow> x \\<le> x\\<^sub>1 \\<Longrightarrow> f_approx x \\<ge> c\" \"c > 0\"\nproof-\n  {\n    fix x assume x: \"x \\<ge> x\\<^sub>0\" \"x \\<le> x\\<^sub>1\"\n    with x0_pos have \"x powr p \\<ge> min (x\\<^sub>0 powr p) (x\\<^sub>1 powr p)\"\n      by (intro powr_lower_bound) simp_all\n    with x have \"f_approx x \\<ge> min (x\\<^sub>0 powr p) (x\\<^sub>1 powr p) * 1\"\n      unfolding f_approx_def by (intro mult_mono f_approx_aux) simp_all\n  }\n  from this x0_pos x1_pos show ?thesis by (intro that[of \"min (x\\<^sub>0 powr p) (x\\<^sub>1 powr p)\"]) auto\nqed\n\n\nlemma asymptotics_aux:\n  assumes \"x \\<ge> x\\<^sub>1\" \"i < k\"\n  assumes \"s \\<equiv> (if p \\<ge> 0 then 1 else -1)\"\n  shows \"(bs!i*x - s*hb*x*ln x powr -(1+e)) powr p \\<le> (bs!i*x + (hs!i) x) powr p\" (is \"?thesis1\")\n  and   \"(bs!i*x + (hs!i) x) powr p \\<le> (bs!i*x + s*hb*x*ln x powr -(1+e)) powr p\" (is \"?thesis2\")\nproof-\n  from assms x1_gt_1 have ln_x_pos: \"ln x > 0\" by simp\n  from assms x1_pos have x_pos: \"x > 0\" by simp\n  from assms x0_le_x1 have *: \"hb / ln x powr (1+e) < bs!i/2\" by (intro x0_hb_bound0) simp_all\n  with hb_nonneg ln_x_pos have \"(bs!i - hb * ln x powr -(1+e)) > 0\"\n    by (subst powr_minus) (simp_all add: field_simps)\n  with * have \"0 < x * (bs!i - hb * ln x powr -(1+e))\" using x_pos\n    by (subst (asm) powr_minus, intro mult_pos_pos)\n  hence A: \"0 < bs!i*x - hb * x * ln x powr -(1+e)\" by (simp add: algebra_simps)\n\n  from assms have \"-(hb*x*ln x powr -(1+e)) \\<le> -\\<bar>(hs!i) x\\<bar>\"\n    using h_bounds[of x \"hs!i\"] by (subst neg_le_iff_le, subst powr_minus) (simp add: field_simps)\n  also have \"... \\<le> (hs!i) x\" by simp\n  finally have B: \"bs!i*x - hb*x*ln x powr -(1+e) \\<le> bs!i*x + (hs!i) x\" by simp\n\n  have \"(hs!i) x \\<le> \\<bar>(hs!i) x\\<bar>\" by simp\n  also from assms have \"... \\<le> (hb*x*ln x powr -(1+e))\"\n     using h_bounds[of x \"hs!i\"] by (subst powr_minus) (simp_all add: field_simps)\n  finally have C: \"bs!i*x + hb*x*ln x powr -(1+e) \\<ge> bs!i*x + (hs!i) x\" by simp\n\n  from A B C show ?thesis1\n    by (cases \"p \\<ge> 0\") (auto intro: powr_mono2 powr_mono2' simp: assms(3))\n  from A B C show ?thesis2\n    by (cases \"p \\<ge> 0\") (auto intro: powr_mono2 powr_mono2' simp: assms(3))\nqed\n\nlemma asymptotics1':\n  assumes \"x \\<ge> x\\<^sub>1\" \"i < k\"\n  shows   \"(bs!i*x) powr p * (1 + ln x powr (-e/2)) \\<le>\n           (bs!i*x + (hs!i) x) powr p * (1 + ln (bs!i*x + (hs!i) x) powr (-e/2))\"\nproof-\n  from assms x0_le_x1 have x: \"x \\<ge> x\\<^sub>0\" by simp\n  from b_pos[of \"bs!i\"] assms have b_pos: \"bs!i > 0\" \"bs!i \\<noteq> 0\" by simp_all\n  from b_less_1[of \"bs!i\"] assms have b_less_1: \"bs!i < 1\" by simp\n  from x1_gt_1 assms have ln_x_pos: \"ln x > 0\" by simp\n  have mono: \"\\<And>a b. a \\<le> b \\<Longrightarrow> (bs!i*x) powr p * a \\<le> (bs!i*x) powr p * b\"\n    by (rule mult_left_mono) simp_all\n\n  define s :: real where [abs_def]: \"s = (if p \\<ge> 0 then 1 else -1)\"\n  have \"1 + ln x powr (-e/2) \\<le>\n          (1 - s*hb*inverse(bs!i)*ln x powr -(1+e)) powr p *\n          (1 + ln (bs!i*x + hb * x / ln x powr (1+e)) powr (-e/2))\" (is \"_ \\<le> ?A * ?B\")\n    using assms x unfolding s_def using asymptotics1[OF x assms(2)] asymptotics1'[OF x assms(2)]\n    by simp\n  also have \"(bs!i*x) powr p * ... = (bs!i*x) powr p * ?A * ?B\" by simp\n  also from x0_hb_bound0'[OF x, of \"bs!i\"] hb_nonneg x ln_x_pos assms\n    have \"s*hb * ln x powr -(1 + e) < bs ! i\"\n    by (subst powr_minus) (simp_all add: field_simps s_def)\n  hence \"(bs!i*x) powr p * ?A = (bs!i*x*(1 - s*hb*inverse (bs!i)*ln x powr -(1+e))) powr p\"\n    using b_pos assms x x0_pos b_less_1 ln_x_pos\n    by (subst powr_mult[symmetric]) (simp_all add: s_def field_simps)\n  also have \"bs!i*x*(1 - s*hb*inverse (bs!i)*ln x powr -(1+e)) = bs!i*x - s*hb*x*ln x powr -(1+e)\"\n    using b_pos assms by (simp add: algebra_simps)\n  also have \"?B = 1 + ln (bs!i*x + hb*x*ln x powr -(1+e)) powr (-e/2)\"\n    by (subst powr_minus) (simp add: field_simps)\n\n  also {\n    from x assms have \"(bs!i*x - s*hb*x*ln x powr -(1+e)) powr p \\<le> (bs!i*x + (hs!i) x) powr p\"\n      using asymptotics_aux(1)[OF assms(1,2) s_def] by blast\n    moreover {\n      have \"(hs!i) x \\<le> \\<bar>(hs!i) x\\<bar>\" by simp\n      also from assms have \"\\<bar>(hs!i) x\\<bar> \\<le> hb * x / ln x powr (1+e)\" by (intro h_bounds) simp_all\n      finally have \"(hs ! i) x \\<le> hb * x * ln x powr -(1 + e)\"\n        by (subst powr_minus) (simp_all add: field_simps)\n      moreover from x hb_nonneg x0_pos have \"hb * x * ln x powr -(1+e) \\<ge> 0\"\n        by (intro mult_nonneg_nonneg) simp_all\n      ultimately have \"1 + ln (bs!i*x + hb * x * ln x powr -(1+e)) powr (-e/2) \\<le>\n                       1 + ln (bs!i*x + (hs!i) x) powr (-e/2)\" using assms x e_pos b_pos x0_pos\n      by (intro add_left_mono powr_mono2' ln_mono ln_gt_zero step_pos x0_hb_bound7'\n                add_pos_nonneg mult_pos_pos) simp_all\n    }\n    ultimately have \"(bs!i*x - s*hb*x*ln x powr -(1+e)) powr p *\n                         (1 + ln (bs!i*x + hb * x * ln x powr -(1+e)) powr (-e/2))\n                     \\<le> (bs!i*x + (hs!i) x) powr p * (1 + ln (bs!i*x + (hs!i) x) powr (-e/2))\"\n      by (rule mult_mono) simp_all\n  }\n  finally show ?thesis by (simp_all add: mono)\nqed\n\nlemma asymptotics2':\n  assumes \"x \\<ge> x\\<^sub>1\" \"i < k\"\n  shows   \"(bs!i*x + (hs!i) x) powr p * (1 - ln (bs!i*x + (hs!i) x) powr (-e/2)) \\<le>\n           (bs!i*x) powr p * (1 - ln x powr (-e/2))\"\nproof-\n  define s :: real where \"s = (if p \\<ge> 0 then 1 else -1)\"\n  from assms x0_le_x1 have x: \"x \\<ge> x\\<^sub>0\" by simp\n  from assms x1_gt_1 have ln_x_pos: \"ln x > 0\" by simp\n  from b_pos[of \"bs!i\"] assms have b_pos: \"bs!i > 0\" \"bs!i \\<noteq> 0\" by simp_all\n  from b_pos hb_nonneg have pos: \"1 + s * hb * (inverse (bs!i) * ln x powr -(1+e)) > 0\"\n    using x0_hb_bound0'[OF x, of \"bs!i\"] b_pos assms ln_x_pos\n    by (subst powr_minus) (simp add: field_simps s_def)\n  have mono: \"\\<And>a b. a \\<le> b \\<Longrightarrow> (bs!i*x) powr p * a \\<le> (bs!i*x) powr p * b\"\n    by (rule mult_left_mono) simp_all\n\n  let ?A = \"(1 + s*hb*inverse(bs!i)*ln x powr -(1+e)) powr p\"\n  let ?B = \"1 - ln (bs!i*x + (hs!i) x) powr (-e/2)\"\n  let ?B' = \"1 - ln (bs!i*x + hb * x / ln x powr (1+e)) powr (-e/2)\"\n\n  from assms x have \"(bs!i*x + (hs!i) x) powr p \\<le> (bs!i*x + s*hb*x*ln x powr -(1+e)) powr p\"\n    by (intro asymptotics_aux(2)) (simp_all add: s_def)\n  moreover from x0_hb_bound9[OF assms(1,2)] have \"?B \\<ge> 0\" by (simp add: field_simps)\n  ultimately have \"(bs!i*x + (hs!i) x) powr p * ?B \\<le>\n                   (bs!i*x + s*hb*x*ln x powr -(1+e)) powr p * ?B\" by (rule mult_right_mono)\n  also from assms e_pos pos have \"?B \\<le> ?B'\"\n  proof -\n    from x0_hb_bound8'[OF assms(1,2)] x0_hb_bound8[OF assms(1,2)] x0_ge_1\n    have *: \"bs ! i * x + s*hb * x / ln x powr (1 + e) > 1\" by (simp add: s_def)\n    moreover from * have \"... > 0\" by simp\n    moreover from x0_hb_bound7[OF assms(1,2)] x0_ge_1 have \"bs ! i * x + (hs ! i) x > 1\" by simp\n    moreover {\n      have \"(hs!i) x \\<le> \\<bar>(hs!i) x\\<bar>\" by simp\n      also from assms x0_le_x1 have \"... \\<le> hb*x/ln x powr (1+e)\" by (intro h_bounds) simp_all\n      finally have \"bs!i*x + (hs!i) x \\<le> bs!i*x + hb*x/ln x powr (1+e)\" by simp\n    }\n    ultimately show \"?B \\<le> ?B'\" using assms e_pos x step_pos\n      by (intro diff_left_mono powr_mono2' ln_mono ln_gt_zero) simp_all\n  qed\n  hence \"(bs!i*x + s*hb*x*ln x powr -(1+e)) powr p * ?B \\<le>\n             (bs!i*x + s*hb*x*ln x powr -(1+e)) powr p * ?B'\" by (intro mult_left_mono) simp_all\n  also have \"bs!i*x + s*hb*x*ln x powr -(1+e) = bs!i*x*(1 + s*hb*inverse (bs!i)*ln x powr -(1+e))\"\n    using b_pos by (simp_all add: field_simps)\n  also have \"... powr p = (bs!i*x) powr p * ?A\"\n    using b_pos x x0_pos pos by (intro powr_mult) simp_all\n  also have \"(bs!i*x) powr p * ?A * ?B' = (bs!i*x) powr p * (?A * ?B')\" by simp\n  also have \"?A * ?B' \\<le> 1 - ln x powr (-e/2)\" using assms x\n    using asymptotics2[OF x assms(2)] asymptotics2'[OF x assms(2)] by (simp add: s_def)\n  finally show ?thesis by (simp_all add: mono)\nqed\n\nlemma Cx_le_step:\n  assumes \"i < k\" \"x \\<ge> x\\<^sub>1\"\n  shows   \"C*x \\<le> bs!i*x + (hs!i) x\"\nproof-\n  from assms have \"C*x \\<le> bs!i*x - hb*x/ln x powr (1+e)\" by (intro C_bound) simp_all\n  also from assms have \"-(hb*x/ln x powr (1+e)) \\<le> -\\<bar>(hs!i) x\\<bar>\"\n    by (subst neg_le_iff_le, intro h_bounds) simp_all\n  hence \"bs!i*x - hb*x/ln x powr (1+e) \\<le> bs!i*x + -\\<bar>(hs!i) x\\<bar>\" by simp\n  also have \"-\\<bar>(hs!i) x\\<bar> \\<le> (hs!i) x\" by simp\n  finally show ?thesis by simp\nqed\n\nend\n\n\nlocale akra_bazzi_nat_to_real = akra_bazzi_real_recursion +\n  fixes f :: \"nat \\<Rightarrow> real\"\n  and   g :: \"real \\<Rightarrow> real\"\n  assumes f_base: \"real x \\<ge> x\\<^sub>0 \\<Longrightarrow> real x \\<le> x\\<^sub>1 \\<Longrightarrow> f x \\<ge> 0\"\n  and     f_rec:  \"real x > x\\<^sub>1 \\<Longrightarrow>\n                          f x = g (real x) + (\\<Sum>i<k. as!i * f (nat \\<lfloor>bs!i * x + (hs!i) (real x)\\<rfloor>))\"\n  and     x0_int: \"real (nat \\<lfloor>x\\<^sub>0\\<rfloor>) = x\\<^sub>0\"\nbegin\n\nfunction f' :: \"real \\<Rightarrow> real\" where\n  \"x \\<le> x\\<^sub>1 \\<Longrightarrow> f' x = f (nat \\<lfloor>x\\<rfloor>)\"\n| \"x > x\\<^sub>1 \\<Longrightarrow> f' x = g x + (\\<Sum>i<k. as!i * f' (bs!i * x + (hs!i) x))\"\nby (force, simp_all)\ntermination by (relation \"Wellfounded.measure akra_bazzi_measure\")\n               (simp_all add: akra_bazzi_measure_decreases)\n\nlemma f'_base: \"x \\<ge> x\\<^sub>0 \\<Longrightarrow> x \\<le> x\\<^sub>1 \\<Longrightarrow> f' x \\<ge> 0\"\n  apply (subst f'.simps(1), assumption)\n  apply (rule f_base)\n  apply (rule order.trans[of _ \"real (nat \\<lfloor>x\\<^sub>0\\<rfloor>)\"], simp add: x0_int)\n  apply (subst of_nat_le_iff, intro nat_mono floor_mono, assumption)\n  using x0_pos apply linarith\n  done\n\nlemmas f'_rec = f'.simps(2)\n\nend\n\n\nlocale akra_bazzi_real_lower = akra_bazzi_real +\n  fixes fb2 gb2 c2 :: real\n  assumes f_base2:   \"x \\<ge> x\\<^sub>0 \\<Longrightarrow> x \\<le> x\\<^sub>1 \\<Longrightarrow> f x \\<ge> fb2\"\n  and     fb2_pos:   \"fb2 > 0\"\n  and     g_growth2: \"\\<forall>x\\<ge>x\\<^sub>1. \\<forall>u\\<in>{C*x..x}. c2 * g x \\<ge> g u\"\n  and     c2_pos:    \"c2 > 0\"\n  and     g_bounded: \"x \\<ge> x\\<^sub>0 \\<Longrightarrow> x \\<le> x\\<^sub>1 \\<Longrightarrow> g x \\<le> gb2\"\nbegin\n\ninterpretation akra_bazzi_integral integrable integral by (rule integral)\n\nlemma gb2_nonneg: \"gb2 \\<ge> 0\" using g_bounded[of x\\<^sub>0] x0_le_x1 x0_pos g_nonneg[of x\\<^sub>0] by simp\n\nlemma g_growth2':\n  assumes \"x \\<ge> x\\<^sub>1\" \"i < k\" \"u \\<in> {bs!i*x+(hs!i) x..x}\"\n  shows   \"c2 * g x \\<ge> g u\"\nproof-\n  from assms have \"C*x \\<le> bs!i*x+(hs!i) x\" by (intro Cx_le_step)\n  with assms have \"u \\<in> {C*x..x}\" by auto\n  with assms g_growth2 show ?thesis by simp\nqed\n\nlemma g_bounds2:\n  obtains c4 where \"\\<And>x i. x \\<ge> x\\<^sub>1 \\<Longrightarrow> i < k \\<Longrightarrow> g_approx i x \\<le> c4 * g x\" \"c4 > 0\"\nproof-\n  define c4\n    where \"c4 = Max {c2 / min 1 (min ((b/2) powr (p+1)) ((b*3/2) powr (p+1))) |b. b \\<in> set bs}\"\n\n  {\n    from bs_nonempty obtain b where b: \"b \\<in> set bs\" by (cases bs) auto\n    let ?m = \"min 1 (min ((b/2) powr (p+1)) ((b*3/2) powr (p+1)))\"\n    from b b_pos have \"?m > 0\" unfolding min_def by (auto simp: not_le)\n    with b b_pos c2_pos have \"c2 / ?m > 0\" by (simp_all add: field_simps)\n    with b have \"c4 > 0\" unfolding c4_def by (subst Max_gr_iff) (simp, simp, blast)\n  }\n\n  {\n    fix x i assume i: \"i < k\" and x: \"x \\<ge> x\\<^sub>1\"\n    have powr_negD: \"a powr b \\<le> 0 \\<Longrightarrow> a = 0\"\n      for a b :: real unfolding powr_def by (simp split: if_split_asm)\n    let ?m = \"min 1 (min ((bs!i/2) powr (p+1)) ((bs!i*3/2) powr (p+1)))\"\n    have \"min 1 ((bs!i + (hs ! i) x / x) powr (p+1)) \\<ge> min 1 (min ((bs!i/2) powr (p+1)) ((bs!i*3/2) powr (p+1)))\"\n      apply (insert x i x0_le_x1 x1_pos step_pos b_pos[OF b_in_bs[OF i]],\n             rule min.mono, simp, cases \"p + 1 \\<ge> 0\")\n      apply (rule order.trans[OF min.cobounded1 powr_mono2[OF _ _ x0_hb_bound4']], simp_all add: field_simps) []\n      apply (rule order.trans[OF min.cobounded2 powr_mono2'[OF _ _ x0_hb_bound5]], simp_all add: field_simps) []\n      done\n    with i b_pos[of \"bs!i\"] have \"c2 / min 1 ((bs!i + (hs ! i) x / x) powr (p+1)) \\<le> c2 / ?m\" using c2_pos\n      unfolding min_def by (intro divide_left_mono) (auto intro!: mult_pos_pos dest!: powr_negD)\n\n    also from i x have \"... \\<le> c4\" unfolding c4_def by (intro Max.coboundedI) auto\n    finally have \"c2 / min 1 ((bs!i + (hs ! i) x / x) powr (p+1)) \\<le> c4\" .\n  } note c4 = this\n\n  {\n    fix x :: real and i :: nat\n    assume x: \"x \\<ge> x\\<^sub>1\" and i: \"i < k\"\n    from x x1_pos have x_pos: \"x > 0\" by simp\n    let ?x' = \"bs ! i * x + (hs ! i) x\"\n    let ?x'' = \"bs ! i + (hs ! i) x / x\"\n    from x x1_ge_1 i g_growth2' x0_le_x1 c2_pos\n      have c2: \"c2 > 0\" \"\\<forall>u\\<in>{?x'..x}. g u \\<le> c2 * g x\" by auto\n\n    from x0_le_x1 x i have x'_le_x: \"?x' \\<le> x\" by (intro step_le_x) simp_all\n    let ?m = \"min (?x' powr (p + 1)) (x powr (p + 1))\"\n    define m' where \"m' = min 1 (?x'' powr (p + 1))\"\n    have [simp]: \"bs ! i > 0\" by (intro b_pos nth_mem) (simp add: i length_bs)\n    from x0_le_x1 x i have [simp]: \"?x' > 0\" by (intro step_pos) simp_all\n\n\n    {\n      fix u assume u: \"u \\<ge> ?x'\" \"u \\<le> x\"\n      have \"?m \\<le> u powr (p + 1)\" using x u by (intro powr_lower_bound mult_pos_pos) simp_all\n      moreover from c2 and u have \"g u \\<le> c2 * g x\" by simp\n      ultimately have \"g u * ?m \\<le> c2 * g x * u powr (p + 1)\" using c2 x x1_pos x0_le_x1\n        by (intro mult_mono mult_nonneg_nonneg g_nonneg) auto\n    }\n    hence \"integral (\\<lambda>u. g u / u powr (p+1)) ?x' x \\<le> integral (\\<lambda>u. c2 * g x / ?m) ?x' x\"\n      using x_pos step_pos[OF i x] x0_hb_bound7[OF x i] c2 x x0_le_x1\n      by (intro integral_le x'_le_x akra_bazzi_integrable ballI integrable_const)\n         (auto simp: field_simps intro!: mult_nonneg_nonneg g_nonneg)\n\n    also from x0_pos x x0_le_x1 x'_le_x c2 have \"... = (x - ?x') * (c2 * g x / ?m)\"\n      by (subst integral_const) (simp_all add: g_nonneg)\n    also from c2 x_pos x x0_le_x1 have \"c2 * g x \\<ge> 0\"\n      by (intro mult_nonneg_nonneg g_nonneg) simp_all\n    with x i x0_le_x1 have \"(x - ?x') * (c2 * g x / ?m) \\<le> x * (c2 * g x / ?m)\"\n      by (intro x0_hb_bound3 mult_right_mono) (simp_all add: field_simps)\n\n    also have \"x powr (p + 1) = x powr (p + 1) * 1\" by simp\n    also have \"(bs ! i * x + (hs ! i) x) powr (p + 1) =\n               (bs ! i + (hs ! i) x / x) powr (p + 1) * x powr (p + 1)\"\n      using x x1_pos step_pos[OF i x] x_pos i x0_le_x1\n      by (subst powr_mult[symmetric]) (simp add: field_simps, simp, simp add: algebra_simps)\n    also have \"... = x powr (p + 1) * (bs ! i + (hs ! i) x / x) powr (p + 1)\" by simp\n    also have \"min ... (x powr (p + 1) * 1) = x powr (p + 1) * m'\" unfolding m'_def using x_pos\n      by (subst min.commute, intro min_mult_left[symmetric]) simp\n\n    also from x_pos have \"x * (c2 * g x / (x powr (p + 1) * m')) = (c2/m') * (g x / x powr p)\"\n      by (simp add: field_simps powr_add)\n    also from x i g_nonneg x0_le_x1 x1_pos have \"... \\<le> c4 * (g x / x powr p)\" unfolding m'_def\n      by (intro mult_right_mono c4) (simp_all add: field_simps)\n    finally have \"g_approx i x \\<le> c4 * g x\"\n      unfolding g_approx_def using x_pos by (simp add: field_simps)\n  }\n  thus ?thesis using that \\<open>c4 > 0\\<close> by blast\nqed\n\nlemma f_approx_bounded_above:\n  obtains c where \"\\<And>x. x \\<ge> x\\<^sub>0 \\<Longrightarrow> x \\<le> x\\<^sub>1 \\<Longrightarrow> f_approx x \\<le> c\" \"c > 0\"\nproof-\n  let ?m1 = \"max (x\\<^sub>0 powr p) (x\\<^sub>1 powr p)\"\n  let ?m2 = \"max (x\\<^sub>0 powr (-(p+1))) (x\\<^sub>1 powr (-(p+1)))\"\n  let ?m3 = \"gb2 * ?m2\"\n  let ?m4 = \"1 + (x\\<^sub>1 - x\\<^sub>0) * ?m3\"\n  let ?int = \"\\<lambda>x. integral (\\<lambda>u. g u / u powr (p + 1)) x\\<^sub>0 x\"\n  {\n    fix x assume x: \"x \\<ge> x\\<^sub>0\" \"x \\<le> x\\<^sub>1\"\n    with x0_pos have \"x powr p \\<le> ?m1\" \"?m1 \\<ge> 0\" by (intro powr_upper_bound) (simp_all add: max_def)\n    moreover {\n      fix u assume u: \"u \\<in> {x\\<^sub>0..x}\"\n      have \"g u / u powr (p + 1) = g u * u powr (-(p+1))\"\n        by (subst powr_minus) (simp add: field_simps)\n      also from u x x0_pos have \"u powr (-(p+1)) \\<le> ?m2\"\n        by (intro powr_upper_bound) simp_all\n      hence \"g u * u powr (-(p+1)) \\<le> g u * ?m2\"\n        using u g_nonneg x0_pos by (intro mult_left_mono) simp_all\n      also from x u x0_pos have \"g u \\<le> gb2\" by (intro g_bounded) simp_all\n      hence \"g u * ?m2 \\<le> gb2 * ?m2\" by (intro mult_right_mono) (simp_all add: max_def)\n      finally have \"g u / u powr (p + 1) \\<le> ?m3\" .\n    } note A = this\n    {\n      from A x gb2_nonneg have \"?int x \\<le> integral (\\<lambda>_. ?m3) x\\<^sub>0 x\"\n        by (intro integral_le akra_bazzi_integrable integrable_const mult_nonneg_nonneg)\n           (simp_all add: le_max_iff_disj)\n      also from x gb2_nonneg have \"... \\<le> (x - x\\<^sub>0) * ?m3\"\n        by (subst integral_const) (simp_all add: le_max_iff_disj)\n      also from x gb2_nonneg have \"... \\<le> (x\\<^sub>1 - x\\<^sub>0) * ?m3\"\n        by (intro mult_right_mono mult_nonneg_nonneg) (simp_all add: max_def)\n      finally have \"1 + ?int x \\<le> ?m4\" by simp\n    }\n    moreover from x g_nonneg x0_pos have \"?int x \\<ge> 0\"\n      by (intro integral_nonneg akra_bazzi_integrable) (simp_all add: powr_def field_simps)\n    hence \"1 + ?int x \\<ge> 0\" by simp\n    ultimately have \"f_approx x \\<le> ?m1 * ?m4\"\n      unfolding f_approx_def by (intro mult_mono)\n    hence \"f_approx x \\<le> max 1 (?m1 * ?m4)\" by simp\n  }\n  from that[OF this] show ?thesis by auto\nqed\n\nlemma f_bounded_below:\n  assumes c': \"c' > 0\"\n  obtains c where \"\\<And>x. x \\<ge> x\\<^sub>0 \\<Longrightarrow> x \\<le> x\\<^sub>1 \\<Longrightarrow> 2 * (c * f_approx x) \\<le> f x\" \"c \\<le> c'\" \"c > 0\"\nproof-\n  obtain c where c: \"\\<And>x. x\\<^sub>0 \\<le> x \\<Longrightarrow> x \\<le> x\\<^sub>1 \\<Longrightarrow> f_approx x \\<le> c\" \"c > 0\"\n    by (rule f_approx_bounded_above) blast\n  {\n    fix x assume x: \"x\\<^sub>0 \\<le> x\" \"x \\<le> x\\<^sub>1\"\n    with c have \"inverse c * f_approx x \\<le> 1\" by (simp add: field_simps)\n    moreover from x f_base2 x0_pos have \"f x \\<ge> fb2\" by auto\n    ultimately have \"inverse c * f_approx x * fb2 \\<le> 1 * f x\" using fb2_pos\n      by (intro mult_mono) simp_all\n    hence \"inverse c * fb2 * f_approx x \\<le> f x\" by (simp add: field_simps)\n    moreover have \"min c' (inverse c * fb2) * f_approx x \\<le> inverse c * fb2 * f_approx x\"\n      using f_approx_nonneg x c\n      by (intro mult_right_mono f_approx_nonneg) (simp_all add: field_simps)\n    ultimately have \"2 * (min c' (inverse c * fb2) / 2 * f_approx x) \\<le> f x\" by simp\n  }\n  moreover from c' have \"min c' (inverse c * fb2) / 2 \\<le> c'\" by simp\n  moreover have \"min c' (inverse c * fb2) / 2 > 0\"\n    using c fb2_pos c' by simp\n  ultimately show ?thesis by (rule that)\nqed\n\nlemma akra_bazzi_lower:\n  obtains c5 where \"\\<And>x. x \\<ge> x\\<^sub>0 \\<Longrightarrow> f x \\<ge> c5 * f_approx x\" \"c5 > 0\"\nproof-\n  obtain c4 where c4: \"\\<And>x i. x \\<ge> x\\<^sub>1 \\<Longrightarrow> i < k \\<Longrightarrow> g_approx i x \\<le> c4 * g x\" \"c4 > 0\"\n    by (rule g_bounds2) blast\n  hence \"inverse c4 / 2 > 0\" by simp\n  then obtain c5 where c5: \"\\<And>x. x \\<ge> x\\<^sub>0 \\<Longrightarrow> x \\<le> x\\<^sub>1 \\<Longrightarrow> 2 * (c5 * f_approx x) \\<le> f x\"\n                           \"c5 \\<le> inverse c4 / 2\" \"c5 > 0\"\n    by (rule f_bounded_below) blast\n\n  {\n  fix x :: real assume x: \"x \\<ge> x\\<^sub>0\"\n  from c5 x have  \" c5 * 1 * f_approx x \\<le> c5 * (1 + ln x powr (- e / 2)) * f_approx x\"\n    by (intro mult_right_mono mult_left_mono f_approx_nonneg) simp_all\n  also from x have \"c5 * (1 + ln x powr (-e/2)) * f_approx x \\<le> f x\"\n  proof (induction x rule: akra_bazzi_induct)\n    case (base x)\n    have \"1 + ln x powr (-e/2) \\<le> 2\" using asymptotics3 base by simp\n    hence \"(1 + ln x powr (-e/2)) * (c5 * f_approx x) \\<le> 2 * (c5 * f_approx x)\"\n      using c5 f_approx_nonneg base x0_ge_1 by (intro mult_right_mono mult_nonneg_nonneg) simp_all\n    also from base have \"2 * (c5 * f_approx x) \\<le> f x\"  by (intro c5) simp_all\n    finally show ?case by (simp add: algebra_simps)\n  next\n    case (rec x)\n    let ?a = \"\\<lambda>i. as!i\" and ?b = \"\\<lambda>i. bs!i\" and ?h = \"\\<lambda>i. hs!i\"\n    let ?int = \"integral (\\<lambda>u. g u / u powr (p+1)) x\\<^sub>0 x\"\n    let ?int1 = \"\\<lambda>i. integral (\\<lambda>u. g u / u powr (p+1)) x\\<^sub>0 (?b i*x+?h i x)\"\n    let ?int2 = \"\\<lambda>i. integral (\\<lambda>u. g u / u powr (p+1)) (?b i*x+?h i x) x\"\n    let ?l = \"ln x powr (-e/2)\" and ?l' = \"\\<lambda>i. ln (?b i*x + ?h i x) powr (-e/2)\"\n\n    from rec and x0_le_x1 x0_ge_1 have x: \"x \\<ge> x\\<^sub>0\" and x_gt_1: \"x > 1\" by simp_all\n    with x0_pos have x_pos: \"x > 0\" and x_nonneg: \"x \\<ge> 0\" by simp_all\n    from c5 c4 have \"c5 * c4 \\<le> 1/2\" by (simp add: field_simps)\n    moreover from asymptotics3 x have \"(1 + ?l) \\<le> 2\" by (simp add: field_simps)\n    ultimately have \"(c5*c4)*(1 + ?l) \\<le> (1/2) * 2\" by (rule mult_mono) simp_all\n    hence \"0 \\<le> 1 - c5*c4*(1 + ?l)\" by simp\n    with g_nonneg[OF x] have \"0 \\<le> g x * ...\" by (intro mult_nonneg_nonneg) simp_all\n    hence \"c5 * (1 + ?l) * f_approx x \\<le> c5 * (1 + ?l) * f_approx x + g x - c5*c4*(1 + ?l) * g x\"\n      by (simp add: algebra_simps)\n    also from x_gt_1 have \"... = c5 * x powr p * (1 + ?l) * (1 + ?int - c4*g x/x powr p) + g x\"\n      by (simp add: field_simps f_approx_def powr_minus)\n    also have \"c5 * x powr p * (1 + ?l) * (1 + ?int - c4*g x/x powr p) =\n                 (\\<Sum>i<k. (?a i * ?b i powr p) * (c5 * x powr p * (1 + ?l) * (1 + ?int - c4*g x/x powr p)))\"\n      by (subst sum_distrib_right[symmetric]) (simp add: p_props)\n    also have \"... \\<le> (\\<Sum>i<k. ?a i * f (?b i*x + ?h i x))\"\n    proof (intro sum_mono, clarify)\n      fix i assume i: \"i < k\"\n      let ?f = \"c5 * ?a i * (?b i * x) powr p\"\n      from rec.hyps i have \"x\\<^sub>0 < bs ! i * x + (hs ! i) x\" by (intro x0_hb_bound7) simp_all\n      hence \"1 + ?int1 i \\<ge> 1\" by (intro f_approx_aux x0_hb_bound7) simp_all\n      hence int_nonneg: \"1 + ?int1 i \\<ge> 0\" by simp\n\n      have \"(?a i * ?b i powr p) * (c5 * x powr p * (1 + ?l) * (1 + ?int - c4*g x/x powr p)) =\n            ?f * (1 + ?l) * (1 + ?int - c4*g x/x powr p)\" (is \"?expr = ?A * ?B\")\n            using x_pos b_pos[of \"bs!i\"] i by (subst powr_mult) simp_all\n      also from rec.hyps i have \"g_approx i x \\<le> c4 * g x\" by (intro c4) simp_all\n      hence \"c4*g x/x powr p \\<ge> ?int2 i\" unfolding g_approx_def using x_pos\n        by (simp add: field_simps)\n      hence \"?A * ?B \\<le> ?A * (1 + (?int - ?int2 i))\" using i c5 a_ge_0\n        by (intro mult_left_mono mult_nonneg_nonneg) simp_all\n      also from rec.hyps i have \"x\\<^sub>0 < bs ! i * x + (hs ! i) x\" by (intro x0_hb_bound7) simp_all\n      hence \"?int - ?int2 i = ?int1 i\"\n        apply (subst diff_eq_eq, subst eq_commute)\n        apply (intro integral_combine akra_bazzi_integrable)\n        apply (insert rec.hyps step_le_x[OF i, of x], simp_all)\n        done\n      also have \"?A * (1 + ?int1 i) = (c5*?a i*(1 + ?int1 i)) * ((?b i*x) powr p * (1 + ?l))\"\n        by (simp add: algebra_simps)\n      also have \"... \\<le> (c5*?a i*(1 + ?int1 i)) * ((?b i*x + ?h i x) powr p * (1 + ?l' i))\"\n        using rec.hyps i c5 a_ge_0 int_nonneg\n        by (intro mult_left_mono asymptotics1' mult_nonneg_nonneg) simp_all\n      also have \"... = ?a i*(c5*(1 + ?l' i)*f_approx (?b i*x + ?h i x))\"\n        by (simp add: algebra_simps f_approx_def)\n      also from i have \"... \\<le> ?a i * f (?b i*x + ?h i x)\"\n        by (intro mult_left_mono a_ge_0 rec.IH) simp_all\n      finally show \"?expr \\<le> ?a i * f (?b i*x + ?h i x)\" .\n    qed\n    also have \"... + g x = f x\" using f_rec[of x] rec.hyps x0_le_x1 by simp\n    finally show ?case by simp\n  qed\n  finally have \"c5 * f_approx x \\<le> f x\" by simp\n  }\n  from this and c5(3) show ?thesis by (rule that)\nqed\n\nlemma akra_bazzi_bigomega:\n  \"f \\<in> \\<Omega>(\\<lambda>x. x powr p * (1 + integral (\\<lambda>u. g u / u powr (p + 1)) x\\<^sub>0 x))\"\napply (fold f_approx_def, rule akra_bazzi_lower, erule landau_omega.bigI)\napply (subst eventually_at_top_linorder, rule exI[of _ x\\<^sub>0])\napply (simp add: f_nonneg f_approx_nonneg)\ndone\n\nend\n\n\nlocale akra_bazzi_real_upper = akra_bazzi_real +\n  fixes fb1 c1 :: real\n  assumes f_base1:   \"x \\<ge> x\\<^sub>0 \\<Longrightarrow> x \\<le> x\\<^sub>1 \\<Longrightarrow> f x \\<le> fb1\"\n  and     g_growth1: \"\\<forall>x\\<ge>x\\<^sub>1. \\<forall>u\\<in>{C*x..x}. c1 * g x \\<le> g u\"\n  and     c1_pos:    \"c1 > 0\"\nbegin\n\ninterpretation akra_bazzi_integral integrable integral by (rule integral)\n\nlemma g_growth1':\n  assumes \"x \\<ge> x\\<^sub>1\" \"i < k\" \"u \\<in> {bs!i*x+(hs!i) x..x}\"\n  shows   \"c1 * g x \\<le> g u\"\nproof-\n  from assms have \"C*x \\<le> bs!i*x+(hs!i) x\" by (intro Cx_le_step)\n  with assms have \"u \\<in> {C*x..x}\" by auto\n  with assms g_growth1 show ?thesis by simp\nqed\n\nlemma g_bounds1:\n  obtains c3 where\n    \"\\<And>x i. x \\<ge> x\\<^sub>1 \\<Longrightarrow> i < k \\<Longrightarrow> c3 * g x \\<le> g_approx i x\" \"c3 > 0\"\nproof-\n  define c3 where \"c3 =\n    Min {c1*((1-b)/2) / max 1 (max ((b/2) powr (p+1)) ((b*3/2) powr (p+1))) |b. b \\<in> set bs}\"\n\n  {\n    fix b assume b: \"b \\<in> set bs\"\n    let ?x = \"max 1 (max ((b/2) powr (p+1)) ((b*3/2) powr (p+1)))\"\n    have \"?x \\<ge> 1\" by simp\n    hence \"?x > 0\" by (rule less_le_trans[OF zero_less_one])\n    with b b_less_1 c1_pos have \"c1*((1-b)/2) / ?x > 0\"\n      by (intro divide_pos_pos mult_pos_pos) (simp_all add: algebra_simps)\n  }\n  hence \"c3 > 0\" unfolding c3_def by (subst Min_gr_iff) auto\n\n  {\n    fix x i assume i: \"i < k\" and x: \"x \\<ge> x\\<^sub>1\"\n    with b_less_1 have b_less_1': \"bs ! i < 1\" by simp\n    let ?m = \"max 1 (max ((bs!i/2) powr (p+1)) ((bs!i*3/2) powr (p+1)))\"\n    from i x have \"c3 \\<le> c1*((1-bs!i)/2) / ?m\" unfolding c3_def by (intro Min.coboundedI) auto\n    also have \"max 1 ((bs!i + (hs ! i) x / x) powr (p+1)) \\<le> max 1 (max ((bs!i/2) powr (p+1)) ((bs!i*3/2) powr (p+1)))\"\n      apply (insert x i x0_le_x1 x1_pos step_pos[OF i x] b_pos[OF b_in_bs[OF i]],\n             rule max.mono, simp, cases \"p + 1 \\<ge> 0\")\n      apply (rule order.trans[OF powr_mono2[OF _ _ x0_hb_bound5] max.cobounded2], simp_all add: field_simps) []\n      apply (rule order.trans[OF powr_mono2'[OF _ _ x0_hb_bound4'] max.cobounded1], simp_all add: field_simps) []\n      done\n    with b_less_1' c1_pos have \"c1*((1-bs!i)/2) / ?m \\<le>\n          c1*((1-bs!i)/2) / max 1 ((bs!i + (hs ! i) x / x) powr (p+1))\"\n      by (intro divide_left_mono mult_nonneg_nonneg) (simp_all add: algebra_simps)\n    finally have \"c3 \\<le> c1*((1-bs!i)/2) / max 1 ((bs!i + (hs ! i) x / x) powr (p+1))\" .\n  } note c3 = this\n\n  {\n    fix x :: real and i :: nat\n    assume x: \"x \\<ge> x\\<^sub>1\" and i: \"i < k\"\n    from x x1_pos have x_pos: \"x > 0\" by simp\n    let ?x' = \"bs ! i * x + (hs ! i) x\"\n    let ?x'' = \"bs ! i + (hs ! i) x / x\"\n    from x x1_ge_1 x0_le_x1 i c1_pos g_growth1'\n      have c1: \"c1 > 0\" \"\\<forall>u\\<in>{?x'..x}. g u \\<ge> c1 * g x\" by auto\n    define b' where \"b' = (1 - bs!i)/2\"\n\n    from x x0_le_x1 i have x'_le_x: \"?x' \\<le> x\" by (intro step_le_x) simp_all\n    let ?m = \"max (?x' powr (p + 1)) (x powr (p + 1))\"\n    define m' where \"m' = max 1 (?x'' powr (p + 1))\"\n    have [simp]: \"bs ! i > 0\" by (intro b_pos nth_mem) (simp add: i length_bs)\n    from x x0_le_x1 i have x'_pos: \"?x' > 0\" by (intro step_pos) simp_all\n    have m_pos: \"?m > 0\" unfolding max_def using x_pos step_pos[OF i x] by auto\n    with x x0_le_x1 c1 have c1_g_m_nonneg: \"c1 * g x / ?m \\<ge> 0\"\n      by (intro mult_nonneg_nonneg divide_nonneg_pos g_nonneg) simp_all\n\n    from x i g_nonneg x0_le_x1 have \"c3 * (g x / x powr p) \\<le> (c1*b'/m') * (g x / x powr p)\"\n      unfolding m'_def b'_def by (intro mult_right_mono c3) (simp_all add: field_simps)\n    also from x_pos have \"... = (x * b') * (c1 * g x / (x powr (p + 1) * m'))\"\n      by (simp add: field_simps powr_add)\n    also from x i c1_pos x1_pos x0_le_x1\n      have \"... \\<le> (x - ?x') * (c1 * g x / (x powr (p + 1) * m'))\"\n      unfolding b'_def m'_def by (intro x0_hb_bound6 mult_right_mono mult_nonneg_nonneg\n                                        divide_nonneg_nonneg g_nonneg) simp_all\n    also have \"x powr (p + 1) * m' =\n                 max (x powr (p + 1) * (bs ! i + (hs ! i) x / x) powr (p + 1)) (x powr (p + 1) * 1)\"\n      unfolding m'_def using x_pos by (subst max.commute, intro max_mult_left) simp\n    also have \"(x powr (p + 1) * (bs ! i + (hs ! i) x / x) powr (p + 1)) =\n                 (bs ! i + (hs ! i) x / x) powr (p + 1) * x powr (p + 1)\" by simp\n    also have \"... = (bs ! i * x + (hs ! i) x) powr (p + 1)\"\n      using x x1_pos step_pos[OF i x] x_pos i x0_le_x1 x_pos\n      by (subst powr_mult[symmetric]) (simp add: field_simps, simp, simp add: algebra_simps)\n    also have \"x powr (p + 1) * 1 = x powr (p + 1)\" by simp\n    also have \"(x - ?x') * (c1 * g x / ?m) = integral (\\<lambda>_. c1 * g x / ?m) ?x' x\"\n      using x'_le_x by (subst integral_const[OF c1_g_m_nonneg]) auto\n    also {\n      fix u assume u: \"u \\<ge> ?x'\" \"u \\<le> x\"\n      have \"u powr (p + 1) \\<le> ?m\" using x u x'_pos by (intro powr_upper_bound mult_pos_pos) simp_all\n      moreover from x'_pos u have \"u \\<ge> 0\" by simp\n      moreover from c1 and u have \"c1 * g x \\<le> g u\" by simp\n      ultimately have \"c1 * g x * u powr (p + 1) \\<le> g u * ?m\" using c1 x u x0_hb_bound7[OF x i]\n        by (intro mult_mono g_nonneg) auto\n      with m_pos u step_pos[OF i x]\n        have \"c1 * g x / ?m \\<le> g u / u powr (p + 1)\" by (simp add: field_simps)\n    }\n    hence \"integral (\\<lambda>_. c1 * g x / ?m) ?x' x \\<le> integral (\\<lambda>u. g u / u powr (p + 1)) ?x' x\"\n      using x0_hb_bound7[OF x i] x'_le_x\n      by (intro integral_le ballI akra_bazzi_integrable integrable_const c1_g_m_nonneg) simp_all\n    finally have \"c3 * g x \\<le> g_approx i x\" using x_pos\n      unfolding g_approx_def by (simp add: field_simps)\n  }\n  thus ?thesis using that \\<open>c3 > 0\\<close> by blast\nqed\n\n\nlemma f_bounded_above:\n  assumes c': \"c' > 0\"\n  obtains c where \"\\<And>x. x \\<ge> x\\<^sub>0 \\<Longrightarrow> x \\<le> x\\<^sub>1 \\<Longrightarrow> f x \\<le> (1/2) * (c * f_approx x)\" \"c \\<ge> c'\" \"c > 0\"\nproof-\n  obtain c where c: \"\\<And>x. x\\<^sub>0 \\<le> x \\<Longrightarrow> x \\<le> x\\<^sub>1 \\<Longrightarrow> f_approx x \\<ge> c\" \"c > 0\"\n    by (rule f_approx_bounded_below) blast\n  have fb1_nonneg: \"fb1 \\<ge> 0\" using f_base1[of \"x\\<^sub>0\"] f_nonneg[of x\\<^sub>0] x0_le_x1 by simp\n  {\n    fix x assume x: \"x \\<ge> x\\<^sub>0\" \"x \\<le> x\\<^sub>1\"\n    with f_base1 x0_pos have \"f x \\<le> fb1\" by simp\n    moreover from c and x have \"f_approx x \\<ge> c\" by blast\n    ultimately have \"f x * c \\<le> fb1 * f_approx x\" using c fb1_nonneg by (intro mult_mono) simp_all\n    also from f_approx_nonneg x have \"... \\<le> (fb1 + 1) * f_approx x\" by (simp add: algebra_simps)\n    finally have \"f x \\<le> ((fb1+1) / c) * f_approx x\" by (simp add: field_simps c)\n    also have \"... \\<le> max ((fb1+1) / c) c' * f_approx x\"\n      by (intro mult_right_mono) (simp_all add: f_approx_nonneg x)\n    finally have \"f x \\<le> 1/2 * (max ((fb1+1) / c) c' * 2 * f_approx x)\" by simp\n  }\n  moreover have \"max ((fb1+1) / c) c' * 2 \\<ge> max ((fb1+1) / c) c'\"\n    by (subst mult_le_cancel_left1) (insert c', simp)\n  hence \"max ((fb1+1) / c) c' * 2 \\<ge> c'\" by (rule order.trans[OF max.cobounded2])\n  moreover from fb1_nonneg and c have \"(fb1+1) / c > 0\" by simp\n  hence \"max ((fb1+1) / c) c' * 2 > 0\" by simp\n  ultimately show ?thesis by (rule that)\nqed\n\n\nlemma akra_bazzi_upper:\n  obtains c6 where \"\\<And>x. x \\<ge> x\\<^sub>0 \\<Longrightarrow> f x \\<le> c6 * f_approx x\" \"c6 > 0\"\nproof-\n  obtain c3 where c3: \"\\<And>x i. x \\<ge> x\\<^sub>1 \\<Longrightarrow> i < k \\<Longrightarrow> c3 * g x \\<le> g_approx i x\" \"c3 > 0\"\n    by (rule g_bounds1) blast\n  hence \"2 / c3 > 0\" by simp\n  then obtain c6 where c6: \"\\<And>x. x \\<ge> x\\<^sub>0 \\<Longrightarrow> x \\<le> x\\<^sub>1 \\<Longrightarrow> f x \\<le> 1/2 * (c6 * f_approx x)\"\n                           \"c6 \\<ge> 2 / c3\" \"c6 > 0\"\n    by (rule f_bounded_above) blast\n\n  {\n  fix x :: real assume x: \"x \\<ge> x\\<^sub>0\"\n  hence \"f x \\<le> c6 * (1 - ln x powr (-e/2)) * f_approx x\"\n  proof (induction x rule: akra_bazzi_induct)\n    case (base x)\n    from base have \"f x \\<le> 1/2 * (c6 * f_approx x)\"  by (intro c6) simp_all\n    also have \"1 - ln x powr (-e/2) \\<ge> 1/2\" using asymptotics4 base by simp\n    hence \"(1 - ln x powr (-e/2)) * (c6 * f_approx x) \\<ge> 1/2 * (c6 * f_approx x)\"\n      using c6 f_approx_nonneg base x0_ge_1 by (intro mult_right_mono mult_nonneg_nonneg) simp_all\n    finally show ?case by (simp add: algebra_simps)\n  next\n    case (rec x)\n    let ?a = \"\\<lambda>i. as!i\" and ?b = \"\\<lambda>i. bs!i\" and ?h = \"\\<lambda>i. hs!i\"\n    let ?int = \"integral (\\<lambda>u. g u / u powr (p+1)) x\\<^sub>0 x\"\n    let ?int1 = \"\\<lambda>i. integral (\\<lambda>u. g u / u powr (p+1)) x\\<^sub>0 (?b i*x+?h i x)\"\n    let ?int2 = \"\\<lambda>i. integral (\\<lambda>u. g u / u powr (p+1)) (?b i*x+?h i x) x\"\n    let ?l = \"ln x powr (-e/2)\" and ?l' = \"\\<lambda>i. ln (?b i*x + ?h i x) powr (-e/2)\"\n\n    from rec and x0_le_x1 have x: \"x \\<ge> x\\<^sub>0\" by simp\n    with x0_pos have x_pos: \"x > 0\" and x_nonneg: \"x \\<ge> 0\" by simp_all\n    from c6 c3 have \"c6 * c3 \\<ge> 2\" by (simp add: field_simps)\n    have \"f x = (\\<Sum>i<k. ?a i * f (?b i*x + ?h i x)) + g x\" (is \"_ = ?sum + _\")\n      using f_rec[of x] rec.hyps x0_le_x1 by simp\n    also have \"?sum \\<le> (\\<Sum>i<k. (?a i*?b i powr p) * (c6*x powr p*(1 - ?l)*(1 + ?int - c3*g x/x powr p)))\" (is \"_ \\<le> ?sum'\")\n    proof (rule sum_mono, clarify)\n      fix i assume i: \"i < k\"\n      from rec.hyps i have \"x\\<^sub>0 < bs ! i * x + (hs ! i) x\" by (intro x0_hb_bound7) simp_all\n      hence \"1 + ?int1 i \\<ge> 1\" by (intro f_approx_aux x0_hb_bound7) simp_all\n      hence int_nonneg: \"1 + ?int1 i \\<ge> 0\" by simp\n      have l_le_1: \"ln x powr -(e/2) \\<le> 1\" using asymptotics3[OF x] by (simp add: field_simps)\n\n      from i have \"f (?b i*x + ?h i x) \\<le> c6 * (1 - ?l' i) * f_approx (?b i*x + ?h i x)\"\n        by (rule rec.IH)\n      hence \"?a i * f (?b i*x + ?h i x) \\<le> ?a i * ...\" using a_ge_0 i\n        by (intro mult_left_mono) simp_all\n      also have \"... = (c6*?a i*(1 + ?int1 i)) * ((?b i*x + ?h i x) powr p * (1 - ?l' i))\"\n        unfolding f_approx_def by (simp add: algebra_simps)\n      also from i rec.hyps c6 a_ge_0\n        have \"... \\<le> (c6*?a i*(1 + ?int1 i)) * ((?b i*x) powr p * (1 - ?l))\"\n        by (intro mult_left_mono asymptotics2' mult_nonneg_nonneg int_nonneg) simp_all\n      also have \"... = (1 + ?int1 i) * (c6*?a i*(?b i*x) powr p * (1 - ?l))\"\n        by (simp add: algebra_simps)\n      also from rec.hyps i have \"x\\<^sub>0 < bs ! i * x + (hs ! i) x\" by (intro x0_hb_bound7) simp_all\n      hence \"?int1 i = ?int - ?int2 i\"\n        apply (subst eq_diff_eq)\n        apply (intro integral_combine akra_bazzi_integrable)\n        apply (insert rec.hyps step_le_x[OF i, of x], simp_all)\n        done\n      also from rec.hyps i have \"c3 * g x \\<le> g_approx i x\" by (intro c3) simp_all\n      hence \"?int2 i \\<ge> c3*g x/x powr p\" unfolding g_approx_def using x_pos\n        by (simp add: field_simps)\n      hence \"(1 + (?int - ?int2 i)) * (c6*?a i*(?b i*x) powr p * (1 - ?l)) \\<le>\n             (1 + ?int - c3*g x/x powr p) * (c6*?a i*(?b i*x) powr p * (1 - ?l))\"\n             using i c6 a_ge_0 l_le_1\n             by (intro mult_right_mono mult_nonneg_nonneg) (simp_all add: field_simps)\n      also have \"... = (?a i*?b i powr p) * (c6*x powr p*(1 - ?l) * (1 + ?int - c3*g x/x powr p))\"\n        using b_pos[of \"bs!i\"] x x0_pos i by (subst powr_mult) (simp_all add: algebra_simps)\n      finally show \"?a i * f (?b i*x + ?h i x) \\<le> ...\" .\n    qed\n\n    hence \"?sum + g x \\<le> ?sum' + g x\" by simp\n    also have \"... = c6 * x powr p * (1 - ?l) * (1 + ?int - c3*g x/x powr p) + g x\"\n      by (simp add: sum_distrib_right[symmetric] p_props)\n    also have \"... = c6 * (1 - ?l) * f_approx x - (c6*c3*(1 - ?l) - 1) * g x\"\n      unfolding f_approx_def using x_pos by (simp add: field_simps)\n    also {\n       from c6 c3 have \"c6*c3 \\<ge> 2\" by (simp add: field_simps)\n       moreover have \"(1 - ?l) \\<ge> 1/2\" using asymptotics4[OF x] by simp\n       ultimately have \"c6*c3*(1 - ?l) \\<ge> 2 * (1/2)\" by (intro mult_mono) simp_all\n       with x x_pos have \"(c6*c3*(1 - ?l) - 1) * g x \\<ge> 0\"\n         by (intro mult_nonneg_nonneg g_nonneg) simp_all\n       hence \"c6 * (1 - ?l) * f_approx x - (c6*c3*(1 - ?l) - 1) * g x \\<le>\n                  c6 * (1 - ?l) * f_approx x\" by (simp add: algebra_simps)\n    }\n    finally show ?case .\n  qed\n  also from x c6 have \"... \\<le> c6 * 1 * f_approx x\"\n    by (intro mult_left_mono mult_right_mono f_approx_nonneg) simp_all\n  finally have \"f x \\<le> c6 * f_approx x\" by simp\n  }\n  from this and c6(3) show ?thesis by (rule that)\nqed\n\nlemma akra_bazzi_bigo:\n  \"f \\<in> O(\\<lambda>x. x powr p *(1 + integral (\\<lambda>u. g u / u powr (p + 1)) x\\<^sub>0 x))\"\napply (fold f_approx_def, rule akra_bazzi_upper, erule landau_o.bigI)\napply (subst eventually_at_top_linorder, rule exI[of _ x\\<^sub>0])\napply (simp add: f_nonneg f_approx_nonneg)\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/Akra_Bazzi/Akra_Bazzi_Real.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8558511469672594, "lm_q2_score": 0.847967764140929, "lm_q1q2_score": 0.7257341835312766}}
{"text": "(*  Title:      HOL/Probability/Independent_Family.thy\n    Author:     Johannes H\u00f6lzl, TU M\u00fcnchen\n    Author:     Sudeep Kanav, TU M\u00fcnchen\n*)\n\nsection {* Independent families of events, event sets, and random variables *}\n\ntheory Independent_Family\n  imports Probability_Measure 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 `J \\<noteq> {}` 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 def G \\<equiv> \"?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 `j \\<in> J` `A j = X` by (auto intro!: arg_cong[where f=prob] split: split_if_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 `J \\<noteq> {j}` `j \\<in> J` 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 `A j = X` by simp\n              also have \"\\<dots> = (\\<Prod>i\\<in>J. prob (A i))\"\n                unfolding setprod.insert_remove[OF `finite J`, symmetric, of \"\\<lambda>i. prob  (A i)\"]\n                using `j \\<in> J` 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: split_if_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 `J \\<noteq> {}`\n            by (auto intro!: arg_cong[where f=prob] split: split_if_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 `J \\<noteq> {}` `j \\<notin> J` A_sets X sets.sets_into_space\n            by (auto intro!: finite_measure_Diff sets.finite_INT split: split_if_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 `finite J` 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 `j \\<in> K` 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 `finite J` `j \\<notin> J` by (auto intro!: setprod.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 `J \\<noteq> {}` `j \\<notin> J` `j \\<in> K` by (auto intro!: arg_cong[where f=prob] split: split_if_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 `finite J` `J \\<noteq> {}` `j \\<notin> J` by (auto intro!: sets.Int)\n          qed\n          moreover { fix k\n            from J A `j \\<in> K` 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!: setprod.cong split: split_if_asm)\n            also have \"\\<dots> = prob (F k) * prob (\\<Inter>i\\<in>J. A i)\"\n              using J A `j \\<in> K` 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 `j \\<in> K` 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 `j \\<in> K` by auto\n        from `indep_sets G K`\n        show \"indep_sets (G(j := {X})) K\"\n          by (rule indep_sets_mono_sets) (insert `X \\<in> G j`, 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: split_if_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 `j \\<in> K` `j \\<notin> J`, auto simp: G_def)\n    qed (insert `indep_sets F K`, simp) }\n  from this[OF `indep_sets F J` `finite J` 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=\"op \\<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 `indep_set A B`[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 `i \\<in> I`] 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 guess 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] guess E' ..\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\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 `K \\<subseteq> J` `k \\<in> K` `j \\<in> K` have \"I k \\<inter> I j = {}\"\n            unfolding disjoint_family_on_def by auto\n          with L(2,3)[OF `j \\<in> K`] L(2,3)[OF `k \\<in> K`]\n          show False using `l \\<in> L k` `l \\<in> L j` by auto\n        qed }\n      note L_inj = this\n\n      def k \\<equiv> \"\\<lambda>l. (SOME k. k \\<in> K \\<and> l \\<in> L k)\"\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 setprod.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!: setprod.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 ?A = \"\\<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 \"a \\<inter> b = INTER (Ka \\<union> Kb) ?A\"\n        by (simp add: a b set_eq_iff) auto\n      with a b `j \\<in> J` Int_stableD[OF Int_stable] show \"a \\<inter> b \\<in> ?E j\"\n        by (intro CollectI exI[of _ \"Ka \\<union> Kb\"] exI[of _ ?A]) 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 J A \\<in> ?UN j\"\n            using `finite J` `J \\<noteq> {}` by (rule finite_INT) blast }\n        note INT = this\n\n        from `J \\<noteq> {}` 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 `J \\<subseteq> K j` 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 {n..} A))\"\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 {n..} A))\"\n  from X have \"\\<And>n::nat. X \\<in> sigma_sets (space M) (UNION {n..} A)\" by (auto simp: tail_events_def)\n  from this[of 0] have \"X \\<in> sigma_sets (space M) (UNION UNIV A)\" 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 {n..} A))\"\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 {n..} A)\" by auto\n    from this[of 0] have \"X \\<in> sigma_sets (space M) (UNION UNIV A)\" by simp\n    then have \"X \\<subseteq> space M\"\n      by induct (insert A.sets_into_space, auto)\n    with `x \\<in> X` 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 UNIV F) \\<in> sigma_sets (space M) (UNION {n..} A)\"\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 `X \\<subseteq> space M` 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 `X \\<subseteq> space M` 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 `X \\<subseteq> space M` 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 `X \\<in> tail_events A`\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 assume \"a \\<in> ?A\" then guess n .. note a = this\n      fix b assume \"b \\<in> ?A\" then guess m .. note b = this\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 `?A \\<subseteq> ?D` 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 \"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) fact\n  also have \"prob (\\<Inter>n. \\<Union>m\\<in>{n..}. ?P m) = 0 \\<longleftrightarrow> (AE x in M. finite {m. P m x})\"\n    by (subst prob_eq_0) (auto simp add: finite_nat_iff_bounded Ball_def not_less[symmetric])\n  also have \"prob (\\<Inter>n. \\<Union>m\\<in>{n..}. ?P m) = 1 \\<longleftrightarrow> (AE x in M. infinite {m. P m x})\"\n    by (subst prob_eq_1) (simp_all add: Bex_def infinite_nat_iff_unbounded_le)\n  finally show ?thesis\n    by metis\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: split_if_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: split_if_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 setprod.If_cases[OF `finite I`]\n      using prob_space `J \\<subseteq> I` by (simp add: Int_absorb1 setprod.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 `i \\<in> I`]\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 `i \\<in> I`, symmetric] M'[OF `i \\<in> I`]\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 `i \\<in> I`]\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 `i \\<in> I`] have \"A \\<in> sets (M' i)\" by auto\n      moreover\n      from rv[OF `i\\<in>I`] 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 `i\\<in>I`] space[OF `i\\<in>I`]\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 I A) = (\\<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 `?L`[THEN bspec, of \"\\<lambda>i. X i -` A i \\<inter> space M\"] A `I \\<noteq> {}`\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 `?R`[THEN bspec, OF B(2)] B(1) `I \\<noteq> {}`\n    show \"prob (INTER I A) = (\\<Prod>j\\<in>I. prob (A j))\"\n      by simp\n  qed\n  then show ?thesis using `I \\<noteq> {}`\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 `indep_vars M' X I`\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 `indep_vars M' X I` 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 `indep_vars M' X I` 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 `i \\<in> I` 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_setsum:\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_setprod:\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] guess J Y . note J = this\n\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 `I \\<noteq> {}` measurable_space[OF rv] by (auto simp: prod_emb_def PiE_iff split: split_if_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 `indep_vars M' X I` J `I \\<noteq> {}` using indep_varsD[of M' X I J]\n        by (auto simp: emeasure_eq_measure setprod_ereal)\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 `I \\<noteq> {}` measurable_space[OF rv] by (auto simp: prod_emb_def PiE_iff split: split_if_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 `?D = ?P'` 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 setprod_ereal)\n    qed\n  qed\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= \"op *\"] 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 `indep_var S X T Y`, of A B] A B by (simp add: emeasure_eq_measure)\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 `X \\<in> measurable M S` 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 `Y \\<in> measurable M T` by (auto intro: measurable_sets) }\n    next\n      fix A B assume ab: \"A \\<in> sets S\" \"B \\<in> sets T\"\n      then have \"ereal (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 intro!: arg_cong[where f=\"prob\"])\n      also have \"\\<dots> = emeasure (?S \\<Otimes>\\<^sub>M ?T) (A \\<times> B)\"\n        unfolding `?S \\<Otimes>\\<^sub>M ?T = ?J` ..\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)\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  def Y \\<equiv> \"\\<lambda>i \\<omega>. if i \\<in> I then X i \\<omega> else 0\"\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: Y_def indep_vars_def)\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. max 0 (Y i \\<omega>)) \\<partial>M)\"\n    using I(3) by (auto intro!: nn_integral_cong setprod.cong simp add: Y_def max_def)\n  also have \"\\<dots> = (\\<integral>\\<^sup>+\\<omega>. (\\<Prod>i\\<in>I. max 0 (\\<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. max 0 (\\<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 `I \\<noteq> {}` rv_Y indep_Y] ..\n  also have \"\\<dots> = (\\<Prod>i\\<in>I. (\\<integral>\\<^sup>+\\<omega>. max 0 \\<omega> \\<partial>distr M borel (Y i)))\"\n    by (rule product_nn_integral_setprod) (auto intro: `finite I`)\n  also have \"\\<dots> = (\\<Prod>i\\<in>I. \\<integral>\\<^sup>+\\<omega>. X i \\<omega> \\<partial>M)\"\n    by (intro setprod.cong nn_integral_cong)\n       (auto simp: nn_integral_distr nn_integral_max_0 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  def Y \\<equiv> \"\\<lambda>i \\<omega>. if i \\<in> I then X i \\<omega> else 0\"\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: Y_def indep_vars_def)\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 `I \\<noteq> {}` 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_setprod) (auto intro: `finite I` simp: integrable_distr_eq int_Y)\n  also have \"\\<dots> = (\\<Prod>i\\<in>I. \\<integral>\\<omega>. X i \\<omega> \\<partial>M)\"\n    by (intro setprod.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 `I \\<noteq> {}` rv_Y indep_Y]\n    by (intro product_integrable_setprod[OF `finite I`])\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": "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/Probability/Independent_Family.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681049901037, "lm_q2_score": 0.8459424353665381, "lm_q1q2_score": 0.7256224397150687}}
{"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_s\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 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 (s n)) = (plus (S Z) (toNat n)))\"\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_s.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009549929797, "lm_q2_score": 0.7931059536292271, "lm_q1q2_score": 0.7256133943859978}}
{"text": "section \\<open>Validating the Specification\\<close>\n\ntheory Elliptic_Test\nimports\n  Elliptic_Locale\n  \"HOL-Number_Theory.Residues\"\nbegin\n\nsubsection \\<open>Specialized Definitions for Prime Fields\\<close>\n\ndefinition mmult :: \"int \\<Rightarrow> int \\<Rightarrow> int \\<Rightarrow> int\" (infixl \"**\\<index>\" 70)\nwhere \"x **\\<^bsub>m\\<^esub> y = x * y mod m\"\n\ndefinition madd :: \"int \\<Rightarrow> int \\<Rightarrow> int \\<Rightarrow> int\" (infixl \"++\\<index>\" 65)\nwhere \"x ++\\<^bsub>m\\<^esub> y = (x + y) mod m\"\n\ndefinition msub :: \"int \\<Rightarrow> int \\<Rightarrow> int \\<Rightarrow> int\" (infixl \"--\\<index>\" 65)\nwhere \"x --\\<^bsub>m\\<^esub> y = (x - y) mod m\"\n\ndefinition mpow :: \"int \\<Rightarrow> int \\<Rightarrow> nat \\<Rightarrow> int\" (infixr \"^^^\\<index>\" 80)\nwhere \"x ^^^\\<^bsub>m\\<^esub> n = x ^ n mod m\"\n\nlemma (in residues) res_of_natural_eq: \"\\<guillemotleft>n\\<guillemotright>\\<^sub>\\<nat> = int n mod m\"\n  by (induct n)\n    (simp_all add: of_natural_def res_zero_eq res_one_eq res_add_eq mod_add_right_eq)\n\nlemma (in residues) res_of_integer_eq: \"\\<guillemotleft>i\\<guillemotright> = i mod m\"\n  by (simp add: of_integer_def res_of_natural_eq res_neg_eq mod_minus_eq)\n\nlemma (in residues) res_pow_eq: \"x [^] (n::nat) = x ^ n mod m\"\n  using m_gt_one\n  by (induct n)\n    (simp_all add: res_one_eq res_mult_eq mult_ac mod_mult_right_eq)\n\nlemma (in residues) res_sub_eq: \"(x mod m) \\<ominus> (y mod m) = (x mod m - y mod m) mod m\"\n  by (simp add: minus_eq res_neg_eq res_add_eq mod_minus_eq mod_add_eq mod_diff_eq)\n\ndefinition mpdouble :: \"int \\<Rightarrow> int \\<Rightarrow> int ppoint \\<Rightarrow> int ppoint\" where\n  \"mpdouble m a p =\n     (let (x, y, z) = p\n      in\n        if z = 0 then p\n        else\n          let\n            l = 2 mod m **\\<^bsub>m\\<^esub> y **\\<^bsub>m\\<^esub> z;\n            n = 3 mod m **\\<^bsub>m\\<^esub> x ^^^\\<^bsub>m\\<^esub> 2 ++\\<^bsub>m\\<^esub> a **\\<^bsub>m\\<^esub> z ^^^\\<^bsub>m\\<^esub> 2\n          in\n            (l **\\<^bsub>m\\<^esub> (n ^^^\\<^bsub>m\\<^esub> 2 --\\<^bsub>m\\<^esub> 4 mod m **\\<^bsub>m\\<^esub> x **\\<^bsub>m\\<^esub> y **\\<^bsub>m\\<^esub> l),\n             n **\\<^bsub>m\\<^esub> (6 mod m **\\<^bsub>m\\<^esub> x **\\<^bsub>m\\<^esub> y **\\<^bsub>m\\<^esub> l --\\<^bsub>m\\<^esub> n ^^^\\<^bsub>m\\<^esub> 2) --\\<^bsub>m\\<^esub>\n             2 mod m **\\<^bsub>m\\<^esub> y ^^^\\<^bsub>m\\<^esub> 2 **\\<^bsub>m\\<^esub> l ^^^\\<^bsub>m\\<^esub> 2,\n             l ^^^\\<^bsub>m\\<^esub> 3))\"\n\ndefinition mpadd :: \"int \\<Rightarrow> int \\<Rightarrow> int ppoint \\<Rightarrow> int ppoint \\<Rightarrow> int ppoint\" where\n  \"mpadd m 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 **\\<^bsub>m\\<^esub> z\\<^sub>1;\n            d\\<^sub>2 = x\\<^sub>1 **\\<^bsub>m\\<^esub> z\\<^sub>2;\n            l = d\\<^sub>1 --\\<^bsub>m\\<^esub> d\\<^sub>2;\n            n = y\\<^sub>2 **\\<^bsub>m\\<^esub> z\\<^sub>1 --\\<^bsub>m\\<^esub> y\\<^sub>1 **\\<^bsub>m\\<^esub> z\\<^sub>2\n          in\n            if l = 0 then\n              if n = 0 then mpdouble m a p\\<^sub>1\n              else (0, 0, 0)\n            else\n              let h = n ^^^\\<^bsub>m\\<^esub> 2 **\\<^bsub>m\\<^esub> z\\<^sub>1 **\\<^bsub>m\\<^esub> z\\<^sub>2 --\\<^bsub>m\\<^esub> (d\\<^sub>1 ++\\<^bsub>m\\<^esub> d\\<^sub>2) **\\<^bsub>m\\<^esub> l ^^^\\<^bsub>m\\<^esub> 2\n              in\n                (l **\\<^bsub>m\\<^esub> h,\n                 (d\\<^sub>2 **\\<^bsub>m\\<^esub> l ^^^\\<^bsub>m\\<^esub> 2 --\\<^bsub>m\\<^esub> h) **\\<^bsub>m\\<^esub> n --\\<^bsub>m\\<^esub> l ^^^\\<^bsub>m\\<^esub> 3 **\\<^bsub>m\\<^esub> y\\<^sub>1 **\\<^bsub>m\\<^esub> z\\<^sub>2,\n                 l ^^^\\<^bsub>m\\<^esub> 3 **\\<^bsub>m\\<^esub> z\\<^sub>1 **\\<^bsub>m\\<^esub> z\\<^sub>2))\"\n\nlemma (in residues) pdouble_residue_eq: \"pdouble a p = mpdouble m a p\"\n  by (simp only: pdouble_def mpdouble_def\n    madd_def mmult_def msub_def mpow_def res_zero_eq res_add_eq res_mult_eq res_of_integer_eq\n    res_pow_eq res_sub_eq)\n\nlemma (in residues) padd_residue_eq: \"padd a p\\<^sub>1 p\\<^sub>2 = mpadd m a p\\<^sub>1 p\\<^sub>2\"\n  by (simp only: padd_def mpadd_def pdouble_residue_eq\n    madd_def mmult_def msub_def mpow_def res_zero_eq res_add_eq res_mult_eq res_of_integer_eq\n    res_pow_eq res_sub_eq Let_def)\n\nfun fast_ppoint_mult :: \"int \\<Rightarrow> int \\<Rightarrow> nat \\<Rightarrow> int ppoint \\<Rightarrow> int ppoint\"\nwhere\n  \"fast_ppoint_mult m a n p =\n     (if n = 0 then (0, 0, 0)\n      else if n mod 2 = 0 then mpdouble m a (fast_ppoint_mult m a (n div 2) p)\n      else mpadd m a p (mpdouble m a (fast_ppoint_mult m a (n div 2) p)))\"\n\nlemma fast_ppoint_mult_0 [simp]: \"fast_ppoint_mult m a 0 p = (0, 0, 0)\"\n  by simp\n\nlemma fast_ppoint_mult_even [simp]:\n  \"n \\<noteq> 0 \\<Longrightarrow> n mod 2 = 0 \\<Longrightarrow>\n   fast_ppoint_mult m a n p = mpdouble m a (fast_ppoint_mult m a (n div 2) p)\"\n  by simp\n\nlemma fast_ppoint_mult_odd [simp]:\n  \"n \\<noteq> 0 \\<Longrightarrow> n mod 2 \\<noteq> 0 \\<Longrightarrow>\n   fast_ppoint_mult m a n p = mpadd m a p (mpdouble m a (fast_ppoint_mult m a (n div 2) p))\"\n  by simp\n\ndeclare fast_ppoint_mult.simps [simp del]\n\nlocale residues_prime_gt2 = residues_prime +\n  assumes gt2: \"2 < p\"\n\nsublocale residues_prime_gt2 < ell_field\n  using gt2\n  by unfold_locales (simp add: res_of_integer_eq res_zero_eq)\n\nlemma (in residues_prime_gt2) fast_ppoint_mult_closed:\n  assumes \"a \\<in> carrier R\" \"b \\<in> carrier R\" \"on_curvep a b q\"\n  shows \"on_curvep a b (fast_ppoint_mult (int p) a n q)\"\n  using assms\nproof (induct \"int p\" a n q rule: fast_ppoint_mult.induct)\n  case (1 a n q)\n  show ?case\n  proof (cases \"n = 0\")\n    case True\n    then show ?thesis using m_gt_one\n      by (simp add: on_curvep_infinity [simplified res_zero_eq] res_carrier_eq)\n  next\n    case False\n    with 1 show ?thesis\n      by (cases \"n mod 2 = 0\")\n        (simp_all add: padd_residue_eq [symmetric] pdouble_residue_eq [symmetric]\n          padd_closed pdouble_closed)\n  qed\nqed\n  \nlemma (in residues_prime_gt2) point_mult_residue_eq:\n  assumes \"a \\<in> carrier R\" \"b \\<in> carrier R\" \"on_curvep a b q\" \"nonsingular a b\"\n  shows \"proj_eq (ppoint_mult a n q) (fast_ppoint_mult (int p) a n q)\"\nproof -\n  from assms\n  have \"point_mult a n (make_affine q) = make_affine (fast_ppoint_mult (int p) a n q)\"\n  proof (induct \"int p\" a n q rule: fast_ppoint_mult.induct)\n    case (1 a n q)\n    show ?case\n    proof (cases \"n = 0\")\n      case True\n      then show ?thesis by (simp add: make_affine_infinity [simplified res_zero_eq])\n    next\n      case False\n      have \"point_mult a n (make_affine q) =\n        point_mult a (n div 2 * 2 + n mod 2) (make_affine q)\"\n        by simp\n      also from 1\n      have \"\\<dots> = add a (point_mult a 2 (point_mult a (n div 2) (make_affine q)))\n        (point_mult a (n mod 2) (make_affine q))\"\n        by (simp only: point_mult_mult point_mult_add\n          on_curvep_iff_on_curve [symmetric] on_curvep_imp_in_carrierp)\n      also have \"\\<dots> = make_affine (fast_ppoint_mult (int p) a n q)\"\n        using 1 False\n        by (cases \"n mod 2 = 0\")\n          (simp_all add: padd_residue_eq [symmetric] pdouble_residue_eq [symmetric] add_0_r\n             padd_correct pdouble_correct\n             fast_ppoint_mult_closed on_curvep_imp_in_carrierp [of a b]\n             point_mult2_eq_double pdouble_closed\n             add_assoc [symmetric] add_comm add_comm' on_curvep_iff_on_curve [symmetric])\n      finally show ?thesis .\n    qed\n  qed\n  with assms show ?thesis\n    by (simp add: make_affine_proj_eq_iff fast_ppoint_mult_closed\n      ppoint_mult_correct on_curvep_imp_in_carrierp [of a b])\nqed\n\ndefinition mmake_affine :: \"int \\<Rightarrow> int ppoint \\<Rightarrow> int point\" where\n  \"mmake_affine q p =\n     (let (x, y, z) = p\n      in if z = 0 then Infinity else\n        let (a, b) = bezout_coefficients z q\n        in Point (a **\\<^bsub>q\\<^esub> x) (a **\\<^bsub>q\\<^esub>y))\"\n\nlemma (in residues_prime) make_affine_residue_eq:\n  assumes \"in_carrierp q\"\n  shows \"make_affine q = mmake_affine (int p) q\"\nproof (cases q)\n  case (fields x y z)\n  show ?thesis\n  proof (cases \"z = 0\")\n    case True\n    with fields show ?thesis by (simp add: make_affine_def mmake_affine_def res_zero_eq)\n  next\n    case False\n    show ?thesis\n    proof (cases \"bezout_coefficients z (int p)\")\n      case (Pair a b)\n      with fields False assms have \"\\<not> int p dvd z\"\n        by (auto simp add: in_carrierp_def res_carrier_eq prime_imp_coprime zdvd_not_zless)\n      with p_prime have \"coprime (int p) z\"\n        by (auto intro: prime_imp_coprime)\n      then have \"coprime z (int p)\"\n        by (simp add: ac_simps)\n      then have \"fst (bezout_coefficients z (int p)) * z +\n        snd (bezout_coefficients z (int p)) * int p = 1\"\n        by (simp add: bezout_coefficients_fst_snd)\n      with m_gt_one have \"fst (bezout_coefficients z (int p)) * z mod int p = 1\"\n        by (auto dest: arg_cong [of _ _ \"\\<lambda>x. x mod int p\"])\n      then have \"z \\<otimes> (fst (bezout_coefficients z (int p)) mod int p) = \\<one>\"\n        by (simp add: res_mult_eq res_one_eq mult.commute mod_mult_right_eq)\n      with fields assms have \"inv z = fst (bezout_coefficients z (int p)) mod int p\"\n        by (simp add: inverse_unique in_carrierp_def res_carrier_eq)\n      with fields Pair False show ?thesis\n        by (simp add: make_affine_def mmake_affine_def res_zero_eq m_div_def\n          res_mult_eq mmult_def mod_mult_right_eq mult.commute)\n    qed\n  qed\nqed\n\ndefinition mon_curve :: \"int \\<Rightarrow> int \\<Rightarrow> int \\<Rightarrow> int point \\<Rightarrow> bool\" where\n  \"mon_curve m a b p = (case p of\n       Infinity \\<Rightarrow> True\n     | Point x y \\<Rightarrow> 0 \\<le> x \\<and> x < m \\<and> 0 \\<le> y \\<and> y < m \\<and>\n         y ^^^\\<^bsub>m\\<^esub> 2 = x ^^^\\<^bsub>m\\<^esub> 3 ++\\<^bsub>m\\<^esub> a **\\<^bsub>m\\<^esub> x ++\\<^bsub>m\\<^esub> b)\"\n\nlemma (in residues_prime_gt2) on_curve_residues_eq:\n  \"on_curve a b q = mon_curve (int p) a b q\"\n  by (simp add: on_curve_def mon_curve_def res_carrier_eq res_add_eq res_mult_eq res_pow_eq\n    madd_def mmult_def mpow_def split: point.split)\n\nsubsection \\<open>The NIST Curve P-521\\<close>\n\ntext \\<open>\nThe following test data is taken from RFC 5903 \\cite{RFC5903}, \\S 3.3 and \\S 8.3.\nThe curve parameters can also be found in \\S D.1.2.5 of FIPS PUB 186-4 \\cite{FIPS186-4}.\n\\<close>\n\ndefinition m :: int where\n  \"m = 0x01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF\"\n\ndefinition a :: int where\n  \"a = m - 3\"\n\ndefinition b :: int where\n  \"b = 0x0051953EB9618E1C9A1F929A21A0B68540EEA2DA725B99B315F3B8B489918EF109E156193951EC7E937B1652C0BD3BB1BF073573DF883D2C34F1EF451FD46B503F00\"\n\ndefinition gx :: int where\n  \"gx = 0x00C6858E06B70404E9CD9E3ECB662395B4429C648139053FB521F828AF606B4D3DBAA14B5E77EFE75928FE1DC127A2FFA8DE3348B3C1856A429BF97E7E31C2E5BD66\"\n\ndefinition gy :: int where\n  \"gy = 0x011839296A789A3BC0045C8A5FB42C7D1BD998F54449579B446817AFBD17273E662C97EE72995EF42640C550B9013FAD0761353C7086A272C24088BE94769FD16650\"\n\ndefinition priv :: nat where\n  \"priv = 0x0037ADE9319A89F4DABDB3EF411AACCCA5123C61ACAB57B5393DCE47608172A095AA85A30FE1C2952C6771D937BA9777F5957B2639BAB072462F68C27A57382D4A52\"\n\ndefinition pubx :: int where\n  \"pubx = 0x0015417E84DBF28C0AD3C278713349DC7DF153C897A1891BD98BAB4357C9ECBEE1E3BF42E00B8E380AEAE57C2D107564941885942AF5A7F4601723C4195D176CED3E\"\n\ndefinition puby :: int where\n  \"puby = 0x017CAE20B6641D2EEB695786D8C946146239D099E18E1D5A514C739D7CB4A10AD8A788015AC405D7799DC75E7B7D5B6CF2261A6A7F1507438BF01BEB6CA3926F9582\"\n\ndefinition order :: nat where\n  \"order = 0x01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFA51868783BF2F966B7FCC0148F709A5D03BB5C9B8899C47AEBB6FB71E91386409\"\n\nlemma \"mon_curve m a b (Point gx gy)\"\n  by eval\n\nlemma \"mmake_affine m (fast_ppoint_mult m a priv (gx, gy, 1)) = Point pubx puby\"\n  by eval\n\nlemma \"mmake_affine m (fast_ppoint_mult m a order (gx, gy, 1)) = Infinity\"\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/Example/afp-2020-05-16/thys/Elliptic_Curves_Group_Law/Elliptic_Test.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009619539554, "lm_q2_score": 0.7931059414036511, "lm_q1q2_score": 0.7256133887215978}}
{"text": "(*\n  IMPORTANT: This file MUST be viewed with the Isabelle IDE.\n    In a normal text editor, it is most likely unreadable!\n    \n    Download Isabelle at https://isabelle.in.tum.de/\n   \n*)\ntheory Demo\nimports Main\nbegin\n\n  section \\<open>Functions\\<close>\n  subsection \\<open>Append\\<close>\n\n  thm append.simps (* See result in output panel! *)\n  \n  value \"[1::nat,2,3]@[4,5,6]\" (* Use ::nat to indicate what number type you want! *)\n\n  subsection \\<open>Filter\\<close>\n\n  (* Erase elements not \\<le>4 from list *)\n  fun leq4 :: \"nat list \\<Rightarrow> nat list\" where\n    \"leq4 [] = []\"\n  | \"leq4 (x#l) = (if x\\<le>4 then x # leq4 l else leq4 l)\"  \n\n  (*\n  fun f :: \"nat \\<Rightarrow> nat\" where \"f x = (if x<65 then f (x+1) else 8)\"\n  *)\n  \n  (*\n    Function type:  nat list \\<Rightarrow> nat list\n      Function that takes a list argument, and returns a list\n  \n  *)\n  \n  \n  \n  value \"leq4 [1,42,7,5,2,6,3]\"\n\n  (*\n    Syntax for function application:\n  \n    f x\\<^sub>1 x\\<^sub>2 x\\<^sub>3   function f applied to arguments x\\<^sub>1 x\\<^sub>2 x\\<^sub>3\n  *)\n  \n  \n  \n  (* More general: Erase elements not satisfying a condition *)\n  term filter\n  \n  (* 'a list -- polymorphic type: Works for lists with any element type *)\n  \n  thm filter.simps\n  value \"filter (\\<lambda>x. x\\<le>4) [1::nat,42,7,5,2,6,3]\"\n  \n  value \"filter (\\<lambda>s::string. size s < 3) [''a'',''abcd'',''ab'']\"\n  \n  value \"CHR ''a''\"\n  \n  \n  \n  (*\n    \\<lambda>x.    define anonymous function, with parameter x\n  *)\n  \n  \n  (** BACK TO SLIDES **)\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  subsection \\<open>Count\\<close>\n\n  (* How often does specific element occur in list? *)\n  fun count :: \"nat list \\<Rightarrow> nat \\<Rightarrow> nat\" where\n    \"count [] y = 0\"\n  | \"count (x#xs) y = (if x=y then 1 + count xs y else count xs y)\"\n\n  lemmas count_simps'[simp] = count.simps[abs_def] (* Technical detail, ignore for first! *)\n  \n  value \"count [1,2,3,4,1,2,3,4,2,6] 2\"\n\n  \n  subsection \\<open>Sortedness Check\\<close>\n  (* Many possible definitions, a straightforward one is: *)\n  term sorted\n  thm sorted.simps\n  thm sorted.simps(1) sorted1 sorted2\n\n  value \"sorted [1,2,2,3,4::nat]\"  \n  value \"sorted [1,2,1,3,4::nat]\"\n  \n  (** BACK TO SLIDES **)\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  \n  \n  \n  \n  \n  \n  \n  subsection \\<open>Quicksort\\<close>\n    \n  fun qs :: \"nat list \\<Rightarrow> nat list\" where\n    \"qs [] = []\"\n  | \"qs (p#l) = qs (filter (\\<lambda>x. x\\<le>p) l) @ [p] @ qs (filter (\\<lambda>x. x>p) l)\"  \n  \n  \n  value \"qs [3,2,5,4,7]\"\n\n  \n  (** BACK TO SLIDES **)  \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\n  section \\<open>Correctness of Sorting Algorithm\\<close>\n  \n  (* A sorting algorithm is correct, iff it returns a sorted list, with the same elements *)\n  definition \"correct_sorting f = (\\<forall>xs. sorted (f xs) \\<and> count (f xs) = count xs)\"\n  \n  (*\n    \\<forall>xs.   for all xs\n    \\<and>      and\n  *)\n  \n  (* Note: Two functions are equal, if they are equal for all arguments (extensionality).\n  \n    That is, count (f xs) = count xs means, that count is the same for all elements\n  *)\n  lemma \"(count (f xs) = count xs) = (\\<forall>x. count (f xs) x = count xs x)\" \n    by auto\n  \n  (* Ultimately, we want to show *)\n  lemma \"correct_sorting qs\"\n    oops (* But this needs some preparation first! *)\n  \n  (** BACK TO SLIDES **)  \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n  section \\<open>Proofs\\<close>\n  \n  subsection \\<open>Useful Properties\\<close>\n  \n  lemma count_append: \"count (l\\<^sub>1@l\\<^sub>2) x = count l\\<^sub>1 x + count l\\<^sub>2 x\"\n    by (induction l\\<^sub>1) auto  (* Ignore the proofs for now *)\n  \n  lemma count_filter: \"count (filter P l) x = (if P x then count l x else 0)\"\n    by (induction l) auto\n  \n  lemma count_filter_complete:\n    \"count (filter (\\<lambda>x. x \\<le> p) l) x + count (filter (\\<lambda>x. x > p) l) x\n     = count l x\"\n    by (cases \"x\\<le>p\") (simp_all add: count_filter)\n  \n  (** BACK TO SLIDES **)  \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  subsection \\<open>Quicksort preserves Elements\\<close>\n  (* Let's prove preservation of elements first *)\n  lemma qs_preserves_elements: \"count (qs xs) x = count xs x\"\n  proof (induction xs rule: qs.induct)\n    (* Proof principle: Show correctness, assuming recursive calls are correct *)\n  \n    case 1 (* Empty list *)\n    show \"count (qs []) x = count [] x\"\n      apply (subst qs.simps) (* Definition of qs*)\n      .. (* reflexivity *)\n      \n  next\n    case (2 p l) (* Non-empty list *)\n    \n    let ?l\\<^sub>1 = \"filter (\\<lambda>x. x \\<le> p) l\"\n    let ?l\\<^sub>2 = \"filter (\\<lambda>x. x > p) l\"\n    \n    (* Assume the recursive calls preserve the elements *)\n    assume IH1: \"count (qs ?l\\<^sub>1) x = count ?l\\<^sub>1 x\"\n       and IH2: \"count (qs ?l\\<^sub>2) x = count ?l\\<^sub>2 x\"\n    \n    (* Show that this call preserves the elements *)   \n    show \"count (qs (p # l)) x = count (p # l) x\" proof -\n      have \"count (qs (p # l)) x = count (qs ?l\\<^sub>1 @ [p] @ qs ?l\\<^sub>2) x\" \n        by simp (* Def. of qs *)\n      also have \"\\<dots> = count [p] x + count (qs ?l\\<^sub>1) x + count (qs ?l\\<^sub>2) x\"\n        by (simp add: count_append) (* count_append, commutativity of + *)\n      also have \"\\<dots> = count [p] x + (count (?l\\<^sub>1) x + count (?l\\<^sub>2) x)\"\n        by (simp add: IH1 IH2) (* Induction hypothesis *)\n      also have \"\\<dots> = count [p] x + count l x\"\n        by (simp add: count_filter_complete) (* count_filter_complete *)\n      also have \"\\<dots> = count (p#l) x\" \n        by simp (* Def of count *)\n      finally show \"count (qs (p # l)) x = count (p # l) x\" .  \n    qed\n  qed          \n  \n\n  (* The above proof was quite explicit. \n    Many of the steps can be summarized \n    BUT: The proof is still the same!\n      * It's more concise to write, but harder to understand!\n      * Automation does not always work completely. \n        It requires training to get an intuition what will work and what won't,\n        know some \"tricks\" to make things work,\n        and to write proofs at a good balance of conciseness and readability!\n      \n  *)\n  lemma \"count (qs xs) x = count xs x\"\n    by (induction xs rule: qs.induct) \n       (auto simp: count_append count_filter_complete)\n  \n  (** BACK TO SLIDES **)  \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  subsection \\<open>More useful Properties\\<close>\n  \n  (* Concept: Set of elements in list *)\n  lemma in_set_conv_count: \"x\\<in>set l = (count l x > 0)\"\n    by (induction l) auto\n  \n  lemma qs_preserves_set: \"set (qs l) = set l\"\n    by (auto simp: in_set_conv_count qs_preserves_elements)\n    \n  (* When is l\\<^sub>1@l\\<^sub>2 sorted ? \n    \n    Both lists are sorted, and elements in l\\<^sub>1 are less than elements in l\\<^sub>2\n  *)  \n  thm sorted_append\n  \n  (* How about l\\<^sub>1@[p]@l\\<^sub>2 ? *)\n  lemma sorted_lel: \"sorted (l\\<^sub>1@[p]@l\\<^sub>2) = (\n    sorted l\\<^sub>1 \\<and> sorted l\\<^sub>2 \\<and> (\\<forall>x\\<in>set l\\<^sub>1. x\\<le>p) \\<and> (\\<forall>x\\<in>set l\\<^sub>2. p\\<le>x))\"\n    by (fastforce simp: sorted_append)\n\n    \n  lemma in_set_filter: \"x\\<in>set (filter P xs) \\<Longrightarrow> P x\" by simp \n    (* A \\<Longrightarrow> B   if A holds then B holds *)\n    \n  lemma \"x\\<in>set (filter P xs) = (P x \\<and> x\\<in>set xs)\"\n    by auto\n    \n    \n  subsection \\<open>Quicksort Sorts\\<close>  \n      \n  lemma qs_sorts: \"sorted (qs xs)\"\n  proof (induction xs rule: qs.induct)\n    case 1 thus ?case by simp\n  next\n    case (2 p l)\n    \n    (* Introduce shortcut notation. Isabelle still sees expanded term, \n      it's just syntax sugar to make terms more concise to write! *)\n    let ?l\\<^sub>1 = \"filter (\\<lambda>x. x \\<le> p) l\"\n    let ?l\\<^sub>2 = \"filter (\\<lambda>x. x > p) l\"\n    \n    (* Assume that recursive calls sort *)\n    assume IH1: \"sorted (qs ?l\\<^sub>1)\" and IH2: \"sorted (qs ?l\\<^sub>2)\"\n    \n    (* Show that this call sorts *)\n    show \"sorted (qs (p#l))\" proof -\n      have \"sorted (qs (p#l)) = sorted (qs ?l\\<^sub>1 @ [p] @ qs ?l\\<^sub>2)\"\n       (* Def. of qs *)\n        by simp\n      also have \"\\<dots> \n        = (sorted (qs ?l\\<^sub>1) \\<and> sorted (qs ?l\\<^sub>2) \n          \\<and> (\\<forall>x\\<in>set (qs ?l\\<^sub>1). x\\<le>p) \\<and> (\\<forall>x\\<in>set (qs ?l\\<^sub>2). p\\<le>x))\"\n        (* sorted_lel *)\n        by (simp add: sorted_lel[simplified])\n      also have \"\\<dots>\" proof (intro conjI)\n        show \"sorted (qs ?l\\<^sub>1)\" using IH1 .\n        show \"sorted (qs ?l\\<^sub>2)\" using IH2 .\n        \n        show \"\\<forall>x\\<in>set (qs ?l\\<^sub>1). x\\<le>p\" proof\n          fix x \n          assume \"x\\<in>set (qs ?l\\<^sub>1)\" \n          hence \"x\\<in>set ?l\\<^sub>1\" by (simp add: qs_preserves_set)\n          thus \"x\\<le>p\" by (rule in_set_filter)\n        qed  \n       \n        show \"\\<forall>x\\<in>set (qs ?l\\<^sub>2). x\\<ge>p\" \n          by (auto simp: qs_preserves_set) (* Analogously, thus written more concise here *)\n          \n      qed  \n      finally show \"sorted (qs (p # l))\" by auto\n    qed\n  qed    \n    \n    \n  (* Again, proof can be written down very concise \n    (but hard to understand what is going on for the beginner!)*)\n  lemma \"sorted (qs xs)\"\n    by (induction xs rule: qs.induct)\n       (auto simp: sorted_append qs_preserves_set)\n  \n  subsection \\<open>Quicksort is correct Sorting Algorithm\\<close>\n  (* Finally! *)    \n  theorem qs_correct: \"correct_sorting qs\"\n    unfolding correct_sorting_def\n    using qs_preserves_elements qs_sorts \n    by auto\n\nend\n", "meta": {"author": "lammich", "repo": "MCR_SS_2019_FunProgProve", "sha": "01d7d06915d1b231afbfd38505a94ee7805d077a", "save_path": "github-repos/isabelle/lammich-MCR_SS_2019_FunProgProve", "path": "github-repos/isabelle/lammich-MCR_SS_2019_FunProgProve/MCR_SS_2019_FunProgProve-01d7d06915d1b231afbfd38505a94ee7805d077a/Demo.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8221891305219504, "lm_q2_score": 0.8824278772763471, "lm_q1q2_score": 0.7255226091661702}}
{"text": "(*  Title:      ZF/Order.thy\n    Author:     Lawrence C Paulson, Cambridge University Computer Laboratory\n    Copyright   1994  University of Cambridge\n\nResults from the book \"Set Theory: an Introduction to Independence Proofs\"\n        by Kenneth Kunen.  Chapter 1, section 6.\nAdditional definitions and lemmas for reflexive orders.\n*)\n\nsection\\<open>Partial and Total Orderings: Basic Definitions and Properties\\<close>\n\ntheory Order imports WF Perm begin\n\ntext \\<open>We adopt the following convention: \\<open>ord\\<close> is used for\n  strict orders and \\<open>order\\<close> is used for their reflexive\n  counterparts.\\<close>\n\ndefinition\n  part_ord :: \"[i,i]\\<Rightarrow>o\"                (*Strict partial ordering*)  where\n   \"part_ord(A,r) \\<equiv> irrefl(A,r) \\<and> trans[A](r)\"\n\ndefinition\n  linear   :: \"[i,i]\\<Rightarrow>o\"                (*Strict total ordering*)  where\n   \"linear(A,r) \\<equiv> (\\<forall>x\\<in>A. \\<forall>y\\<in>A. \\<langle>x,y\\<rangle>:r | x=y | \\<langle>y,x\\<rangle>:r)\"\n\ndefinition\n  tot_ord  :: \"[i,i]\\<Rightarrow>o\"                (*Strict total ordering*)  where\n   \"tot_ord(A,r) \\<equiv> part_ord(A,r) \\<and> linear(A,r)\"\n\ndefinition\n  \"preorder_on(A, r) \\<equiv> refl(A, r) \\<and> trans[A](r)\"\n\ndefinition                              (*Partial ordering*)\n  \"partial_order_on(A, r) \\<equiv> preorder_on(A, r) \\<and> antisym(r)\"\n\nabbreviation\n  \"Preorder(r) \\<equiv> preorder_on(field(r), r)\"\n\nabbreviation\n  \"Partial_order(r) \\<equiv> partial_order_on(field(r), r)\"\n\ndefinition\n  well_ord :: \"[i,i]\\<Rightarrow>o\"                (*Well-ordering*)  where\n   \"well_ord(A,r) \\<equiv> tot_ord(A,r) \\<and> wf[A](r)\"\n\ndefinition\n  mono_map :: \"[i,i,i,i]\\<Rightarrow>i\"            (*Order-preserving maps*)  where\n   \"mono_map(A,r,B,s) \\<equiv>\n              {f \\<in> A->B. \\<forall>x\\<in>A. \\<forall>y\\<in>A. \\<langle>x,y\\<rangle>:r \\<longrightarrow> <f`x,f`y>:s}\"\n\ndefinition\n  ord_iso  :: \"[i,i,i,i]\\<Rightarrow>i\"  (\\<open>(\\<langle>_, _\\<rangle> \\<cong>/ \\<langle>_, _\\<rangle>)\\<close> 51)  (*Order isomorphisms*)  where\n   \"\\<langle>A,r\\<rangle> \\<cong> \\<langle>B,s\\<rangle> \\<equiv>\n              {f \\<in> bij(A,B). \\<forall>x\\<in>A. \\<forall>y\\<in>A. \\<langle>x,y\\<rangle>:r \\<longleftrightarrow> <f`x,f`y>:s}\"\n\ndefinition\n  pred     :: \"[i,i,i]\\<Rightarrow>i\"              (*Set of predecessors*)  where\n   \"pred(A,x,r) \\<equiv> {y \\<in> A. \\<langle>y,x\\<rangle>:r}\"\n\ndefinition\n  ord_iso_map :: \"[i,i,i,i]\\<Rightarrow>i\"         (*Construction for linearity theorem*)  where\n   \"ord_iso_map(A,r,B,s) \\<equiv>\n     \\<Union>x\\<in>A. \\<Union>y\\<in>B. \\<Union>f \\<in> ord_iso(pred(A,x,r), r, pred(B,y,s), s). {\\<langle>x,y\\<rangle>}\"\n\ndefinition\n  first :: \"[i, i, i] \\<Rightarrow> o\"  where\n    \"first(u, X, R) \\<equiv> u \\<in> X \\<and> (\\<forall>v\\<in>X. v\\<noteq>u \\<longrightarrow> \\<langle>u,v\\<rangle> \\<in> R)\"\n\nsubsection\\<open>Immediate Consequences of the Definitions\\<close>\n\nlemma part_ord_Imp_asym:\n    \"part_ord(A,r) \\<Longrightarrow> asym(r \\<inter> A*A)\"\nby (unfold part_ord_def irrefl_def trans_on_def asym_def, blast)\n\nlemma linearE:\n    \"\\<lbrakk>linear(A,r);  x \\<in> A;  y \\<in> A;\n        \\<langle>x,y\\<rangle>:r \\<Longrightarrow> P;  x=y \\<Longrightarrow> P;  \\<langle>y,x\\<rangle>:r \\<Longrightarrow> P\\<rbrakk>\n     \\<Longrightarrow> P\"\nby (simp add: linear_def, blast)\n\n\n(** General properties of well_ord **)\n\nlemma well_ordI:\n    \"\\<lbrakk>wf[A](r); linear(A,r)\\<rbrakk> \\<Longrightarrow> well_ord(A,r)\"\napply (simp add: irrefl_def part_ord_def tot_ord_def\n                 trans_on_def well_ord_def wf_on_not_refl)\napply (fast elim: linearE wf_on_asym wf_on_chain3)\ndone\n\nlemma well_ord_is_wf:\n    \"well_ord(A,r) \\<Longrightarrow> wf[A](r)\"\nby (unfold well_ord_def, safe)\n\nlemma well_ord_is_trans_on:\n    \"well_ord(A,r) \\<Longrightarrow> trans[A](r)\"\nby (unfold well_ord_def tot_ord_def part_ord_def, safe)\n\nlemma well_ord_is_linear: \"well_ord(A,r) \\<Longrightarrow> linear(A,r)\"\nby (unfold well_ord_def tot_ord_def, blast)\n\n\n(** Derived rules for pred(A,x,r) **)\n\nlemma pred_iff: \"y \\<in> pred(A,x,r) \\<longleftrightarrow> \\<langle>y,x\\<rangle>:r \\<and> y \\<in> A\"\nby (unfold pred_def, blast)\n\nlemmas predI = conjI [THEN pred_iff [THEN iffD2]]\n\nlemma predE: \"\\<lbrakk>y \\<in> pred(A,x,r);  \\<lbrakk>y \\<in> A; \\<langle>y,x\\<rangle>:r\\<rbrakk> \\<Longrightarrow> P\\<rbrakk> \\<Longrightarrow> P\"\nby (simp add: pred_def)\n\nlemma pred_subset_under: \"pred(A,x,r) \\<subseteq> r -`` {x}\"\nby (simp add: pred_def, blast)\n\nlemma pred_subset: \"pred(A,x,r) \\<subseteq> A\"\nby (simp add: pred_def, blast)\n\nlemma pred_pred_eq:\n    \"pred(pred(A,x,r), y, r) = pred(A,x,r) \\<inter> pred(A,y,r)\"\nby (simp add: pred_def, blast)\n\nlemma trans_pred_pred_eq:\n    \"\\<lbrakk>trans[A](r);  \\<langle>y,x\\<rangle>:r;  x \\<in> A;  y \\<in> A\\<rbrakk>\n     \\<Longrightarrow> pred(pred(A,x,r), y, r) = pred(A,y,r)\"\nby (unfold trans_on_def pred_def, blast)\n\n\nsubsection\\<open>Restricting an Ordering's Domain\\<close>\n\n(** The ordering's properties hold over all subsets of its domain\n    [including initial segments of the form pred(A,x,r) **)\n\n(*Note: a relation s such that s<=r need not be a partial ordering*)\nlemma part_ord_subset:\n    \"\\<lbrakk>part_ord(A,r);  B<=A\\<rbrakk> \\<Longrightarrow> part_ord(B,r)\"\nby (unfold part_ord_def irrefl_def trans_on_def, blast)\n\nlemma linear_subset:\n    \"\\<lbrakk>linear(A,r);  B<=A\\<rbrakk> \\<Longrightarrow> linear(B,r)\"\nby (unfold linear_def, blast)\n\nlemma tot_ord_subset:\n    \"\\<lbrakk>tot_ord(A,r);  B<=A\\<rbrakk> \\<Longrightarrow> tot_ord(B,r)\"\n  unfolding tot_ord_def\napply (fast elim!: part_ord_subset linear_subset)\ndone\n\nlemma well_ord_subset:\n    \"\\<lbrakk>well_ord(A,r);  B<=A\\<rbrakk> \\<Longrightarrow> well_ord(B,r)\"\n  unfolding well_ord_def\napply (fast elim!: tot_ord_subset wf_on_subset_A)\ndone\n\n\n(** Relations restricted to a smaller domain, by Krzysztof Grabczewski **)\n\nlemma irrefl_Int_iff: \"irrefl(A,r \\<inter> A*A) \\<longleftrightarrow> irrefl(A,r)\"\nby (unfold irrefl_def, blast)\n\nlemma trans_on_Int_iff: \"trans[A](r \\<inter> A*A) \\<longleftrightarrow> trans[A](r)\"\nby (unfold trans_on_def, blast)\n\nlemma part_ord_Int_iff: \"part_ord(A,r \\<inter> A*A) \\<longleftrightarrow> part_ord(A,r)\"\n  unfolding part_ord_def\napply (simp add: irrefl_Int_iff trans_on_Int_iff)\ndone\n\nlemma linear_Int_iff: \"linear(A,r \\<inter> A*A) \\<longleftrightarrow> linear(A,r)\"\nby (unfold linear_def, blast)\n\nlemma tot_ord_Int_iff: \"tot_ord(A,r \\<inter> A*A) \\<longleftrightarrow> tot_ord(A,r)\"\n  unfolding tot_ord_def\napply (simp add: part_ord_Int_iff linear_Int_iff)\ndone\n\nlemma wf_on_Int_iff: \"wf[A](r \\<inter> A*A) \\<longleftrightarrow> wf[A](r)\"\napply (unfold wf_on_def wf_def, fast) (*10 times faster than blast!*)\ndone\n\nlemma well_ord_Int_iff: \"well_ord(A,r \\<inter> A*A) \\<longleftrightarrow> well_ord(A,r)\"\n  unfolding well_ord_def\napply (simp add: tot_ord_Int_iff wf_on_Int_iff)\ndone\n\n\nsubsection\\<open>Empty and Unit Domains\\<close>\n\n(*The empty relation is well-founded*)\nlemma wf_on_any_0: \"wf[A](0)\"\nby (simp add: wf_on_def wf_def, fast)\n\nsubsubsection\\<open>Relations over the Empty Set\\<close>\n\nlemma irrefl_0: \"irrefl(0,r)\"\nby (unfold irrefl_def, blast)\n\nlemma trans_on_0: \"trans[0](r)\"\nby (unfold trans_on_def, blast)\n\nlemma part_ord_0: \"part_ord(0,r)\"\n  unfolding part_ord_def\napply (simp add: irrefl_0 trans_on_0)\ndone\n\nlemma linear_0: \"linear(0,r)\"\nby (unfold linear_def, blast)\n\nlemma tot_ord_0: \"tot_ord(0,r)\"\n  unfolding tot_ord_def\napply (simp add: part_ord_0 linear_0)\ndone\n\nlemma wf_on_0: \"wf[0](r)\"\nby (unfold wf_on_def wf_def, blast)\n\nlemma well_ord_0: \"well_ord(0,r)\"\n  unfolding well_ord_def\napply (simp add: tot_ord_0 wf_on_0)\ndone\n\n\nsubsubsection\\<open>The Empty Relation Well-Orders the Unit Set\\<close>\n\ntext\\<open>by Grabczewski\\<close>\n\nlemma tot_ord_unit: \"tot_ord({a},0)\"\nby (simp add: irrefl_def trans_on_def part_ord_def linear_def tot_ord_def)\n\nlemma well_ord_unit: \"well_ord({a},0)\"\n  unfolding well_ord_def\napply (simp add: tot_ord_unit wf_on_any_0)\ndone\n\n\nsubsection\\<open>Order-Isomorphisms\\<close>\n\ntext\\<open>Suppes calls them \"similarities\"\\<close>\n\n(** Order-preserving (monotone) maps **)\n\nlemma mono_map_is_fun: \"f \\<in> mono_map(A,r,B,s) \\<Longrightarrow> f \\<in> A->B\"\nby (simp add: mono_map_def)\n\nlemma mono_map_is_inj:\n    \"\\<lbrakk>linear(A,r);  wf[B](s);  f \\<in> mono_map(A,r,B,s)\\<rbrakk> \\<Longrightarrow> f \\<in> inj(A,B)\"\napply (unfold mono_map_def inj_def, clarify)\napply (erule_tac x=w and y=x in linearE, assumption+)\napply (force intro: apply_type dest: wf_on_not_refl)+\ndone\n\nlemma ord_isoI:\n    \"\\<lbrakk>f \\<in> bij(A, B);\n        \\<And>x y. \\<lbrakk>x \\<in> A; y \\<in> A\\<rbrakk> \\<Longrightarrow> \\<langle>x, y\\<rangle> \\<in> r \\<longleftrightarrow> <f`x, f`y> \\<in> s\\<rbrakk>\n     \\<Longrightarrow> f \\<in> ord_iso(A,r,B,s)\"\nby (simp add: ord_iso_def)\n\nlemma ord_iso_is_mono_map:\n    \"f \\<in> ord_iso(A,r,B,s) \\<Longrightarrow> f \\<in> mono_map(A,r,B,s)\"\napply (simp add: ord_iso_def mono_map_def)\napply (blast dest!: bij_is_fun)\ndone\n\nlemma ord_iso_is_bij:\n    \"f \\<in> ord_iso(A,r,B,s) \\<Longrightarrow> f \\<in> bij(A,B)\"\nby (simp add: ord_iso_def)\n\n(*Needed?  But ord_iso_converse is!*)\nlemma ord_iso_apply:\n    \"\\<lbrakk>f \\<in> ord_iso(A,r,B,s);  \\<langle>x,y\\<rangle>: r;  x \\<in> A;  y \\<in> A\\<rbrakk> \\<Longrightarrow> <f`x, f`y> \\<in> s\"\nby (simp add: ord_iso_def)\n\nlemma ord_iso_converse:\n    \"\\<lbrakk>f \\<in> ord_iso(A,r,B,s);  \\<langle>x,y\\<rangle>: s;  x \\<in> B;  y \\<in> B\\<rbrakk>\n     \\<Longrightarrow> <converse(f) ` x, converse(f) ` y> \\<in> r\"\napply (simp add: ord_iso_def, clarify)\napply (erule bspec [THEN bspec, THEN iffD2])\napply (erule asm_rl bij_converse_bij [THEN bij_is_fun, THEN apply_type])+\napply (auto simp add: right_inverse_bij)\ndone\n\n\n(** Symmetry and Transitivity Rules **)\n\n(*Reflexivity of similarity*)\nlemma ord_iso_refl: \"id(A): ord_iso(A,r,A,r)\"\nby (rule id_bij [THEN ord_isoI], simp)\n\n(*Symmetry of similarity*)\nlemma ord_iso_sym: \"f \\<in> ord_iso(A,r,B,s) \\<Longrightarrow> converse(f): ord_iso(B,s,A,r)\"\napply (simp add: ord_iso_def)\napply (auto simp add: right_inverse_bij bij_converse_bij\n                      bij_is_fun [THEN apply_funtype])\ndone\n\n(*Transitivity of similarity*)\nlemma mono_map_trans:\n    \"\\<lbrakk>g \\<in> mono_map(A,r,B,s);  f \\<in> mono_map(B,s,C,t)\\<rbrakk>\n     \\<Longrightarrow> (f O g): mono_map(A,r,C,t)\"\n  unfolding mono_map_def\napply (auto simp add: comp_fun)\ndone\n\n(*Transitivity of similarity: the order-isomorphism relation*)\nlemma ord_iso_trans:\n    \"\\<lbrakk>g \\<in> ord_iso(A,r,B,s);  f \\<in> ord_iso(B,s,C,t)\\<rbrakk>\n     \\<Longrightarrow> (f O g): ord_iso(A,r,C,t)\"\napply (unfold ord_iso_def, clarify)\napply (frule bij_is_fun [of f])\napply (frule bij_is_fun [of g])\napply (auto simp add: comp_bij)\ndone\n\n(** Two monotone maps can make an order-isomorphism **)\n\nlemma mono_ord_isoI:\n    \"\\<lbrakk>f \\<in> mono_map(A,r,B,s);  g \\<in> mono_map(B,s,A,r);\n        f O g = id(B);  g O f = id(A)\\<rbrakk> \\<Longrightarrow> f \\<in> ord_iso(A,r,B,s)\"\napply (simp add: ord_iso_def mono_map_def, safe)\napply (intro fg_imp_bijective, auto)\napply (subgoal_tac \"<g` (f`x), g` (f`y) > \\<in> r\")\napply (simp add: comp_eq_id_iff [THEN iffD1])\napply (blast intro: apply_funtype)\ndone\n\nlemma well_ord_mono_ord_isoI:\n     \"\\<lbrakk>well_ord(A,r);  well_ord(B,s);\n         f \\<in> mono_map(A,r,B,s);  converse(f): mono_map(B,s,A,r)\\<rbrakk>\n      \\<Longrightarrow> f \\<in> ord_iso(A,r,B,s)\"\napply (intro mono_ord_isoI, auto)\napply (frule mono_map_is_fun [THEN fun_is_rel])\napply (erule converse_converse [THEN subst], rule left_comp_inverse)\napply (blast intro: left_comp_inverse mono_map_is_inj well_ord_is_linear\n                    well_ord_is_wf)+\ndone\n\n\n(** Order-isomorphisms preserve the ordering's properties **)\n\nlemma part_ord_ord_iso:\n    \"\\<lbrakk>part_ord(B,s);  f \\<in> ord_iso(A,r,B,s)\\<rbrakk> \\<Longrightarrow> part_ord(A,r)\"\napply (simp add: part_ord_def irrefl_def trans_on_def ord_iso_def)\napply (fast intro: bij_is_fun [THEN apply_type])\ndone\n\nlemma linear_ord_iso:\n    \"\\<lbrakk>linear(B,s);  f \\<in> ord_iso(A,r,B,s)\\<rbrakk> \\<Longrightarrow> linear(A,r)\"\napply (simp add: linear_def ord_iso_def, safe)\napply (drule_tac x1 = \"f`x\" and x = \"f`y\" in bspec [THEN bspec])\napply (safe elim!: bij_is_fun [THEN apply_type])\napply (drule_tac t = \"(`) (converse (f))\" in subst_context)\napply (simp add: left_inverse_bij)\ndone\n\nlemma wf_on_ord_iso:\n    \"\\<lbrakk>wf[B](s);  f \\<in> ord_iso(A,r,B,s)\\<rbrakk> \\<Longrightarrow> wf[A](r)\"\napply (simp add: wf_on_def wf_def ord_iso_def, safe)\napply (drule_tac x = \"{f`z. z \\<in> Z \\<inter> A}\" in spec)\napply (safe intro!: equalityI)\napply (blast dest!: equalityD1 intro: bij_is_fun [THEN apply_type])+\ndone\n\nlemma well_ord_ord_iso:\n    \"\\<lbrakk>well_ord(B,s);  f \\<in> ord_iso(A,r,B,s)\\<rbrakk> \\<Longrightarrow> well_ord(A,r)\"\n  unfolding well_ord_def tot_ord_def\napply (fast elim!: part_ord_ord_iso linear_ord_iso wf_on_ord_iso)\ndone\n\n\nsubsection\\<open>Main results of Kunen, Chapter 1 section 6\\<close>\n\n(*Inductive argument for Kunen's Lemma 6.1, etc.\n  Simple proof from Halmos, page 72*)\nlemma well_ord_iso_subset_lemma:\n     \"\\<lbrakk>well_ord(A,r);  f \\<in> ord_iso(A,r, A',r);  A'<= A;  y \\<in> A\\<rbrakk>\n      \\<Longrightarrow> \\<not> <f`y, y>: r\"\napply (simp add: well_ord_def ord_iso_def)\napply (elim conjE CollectE)\napply (rule_tac a=y in wf_on_induct, assumption+)\napply (blast dest: bij_is_fun [THEN apply_type])\ndone\n\n(*Kunen's Lemma 6.1 \\<in> there's no order-isomorphism to an initial segment\n                     of a well-ordering*)\nlemma well_ord_iso_predE:\n     \"\\<lbrakk>well_ord(A,r);  f \\<in> ord_iso(A, r, pred(A,x,r), r);  x \\<in> A\\<rbrakk> \\<Longrightarrow> P\"\napply (insert well_ord_iso_subset_lemma [of A r f \"pred(A,x,r)\" x])\napply (simp add: pred_subset)\n(*Now we know  f`x < x *)\napply (drule ord_iso_is_bij [THEN bij_is_fun, THEN apply_type], assumption)\n(*Now we also know @{term\"f`x \\<in> pred(A,x,r)\"}: contradiction! *)\napply (simp add: well_ord_def pred_def)\ndone\n\n(*Simple consequence of Lemma 6.1*)\nlemma well_ord_iso_pred_eq:\n     \"\\<lbrakk>well_ord(A,r);  f \\<in> ord_iso(pred(A,a,r), r, pred(A,c,r), r);\n         a \\<in> A;  c \\<in> A\\<rbrakk> \\<Longrightarrow> a=c\"\napply (frule well_ord_is_trans_on)\napply (frule well_ord_is_linear)\napply (erule_tac x=a and y=c in linearE, assumption+)\napply (drule ord_iso_sym)\n(*two symmetric cases*)\napply (auto elim!: well_ord_subset [OF _ pred_subset, THEN well_ord_iso_predE]\n            intro!: predI\n            simp add: trans_pred_pred_eq)\ndone\n\n(*Does not assume r is a wellordering!*)\nlemma ord_iso_image_pred:\n     \"\\<lbrakk>f \\<in> ord_iso(A,r,B,s);  a \\<in> A\\<rbrakk> \\<Longrightarrow> f `` pred(A,a,r) = pred(B, f`a, s)\"\n  unfolding ord_iso_def pred_def\napply (erule CollectE)\napply (simp (no_asm_simp) add: image_fun [OF bij_is_fun Collect_subset])\napply (rule equalityI)\napply (safe elim!: bij_is_fun [THEN apply_type])\napply (rule RepFun_eqI)\napply (blast intro!: right_inverse_bij [symmetric])\napply (auto simp add: right_inverse_bij  bij_is_fun [THEN apply_funtype])\ndone\n\nlemma ord_iso_restrict_image:\n     \"\\<lbrakk>f \\<in> ord_iso(A,r,B,s);  C<=A\\<rbrakk>\n      \\<Longrightarrow> restrict(f,C) \\<in> ord_iso(C, r, f``C, s)\"\napply (simp add: ord_iso_def)\napply (blast intro: bij_is_inj restrict_bij)\ndone\n\n(*But in use, A and B may themselves be initial segments.  Then use\n  trans_pred_pred_eq to simplify the pred(pred...) terms.  See just below.*)\nlemma ord_iso_restrict_pred:\n   \"\\<lbrakk>f \\<in> ord_iso(A,r,B,s);   a \\<in> A\\<rbrakk>\n    \\<Longrightarrow> restrict(f, pred(A,a,r)) \\<in> ord_iso(pred(A,a,r), r, pred(B, f`a, s), s)\"\napply (simp add: ord_iso_image_pred [symmetric])\napply (blast intro: ord_iso_restrict_image elim: predE)\ndone\n\n(*Tricky; a lot of forward proof!*)\nlemma well_ord_iso_preserving:\n     \"\\<lbrakk>well_ord(A,r);  well_ord(B,s);  \\<langle>a,c\\<rangle>: r;\n         f \\<in> ord_iso(pred(A,a,r), r, pred(B,b,s), s);\n         g \\<in> ord_iso(pred(A,c,r), r, pred(B,d,s), s);\n         a \\<in> A;  c \\<in> A;  b \\<in> B;  d \\<in> B\\<rbrakk> \\<Longrightarrow> \\<langle>b,d\\<rangle>: s\"\napply (frule ord_iso_is_bij [THEN bij_is_fun, THEN apply_type], (erule asm_rl predI predE)+)\napply (subgoal_tac \"b = g`a\")\napply (simp (no_asm_simp))\napply (rule well_ord_iso_pred_eq, auto)\napply (frule ord_iso_restrict_pred, (erule asm_rl predI)+)\napply (simp add: well_ord_is_trans_on trans_pred_pred_eq)\napply (erule ord_iso_sym [THEN ord_iso_trans], assumption)\ndone\n\n(*See Halmos, page 72*)\nlemma well_ord_iso_unique_lemma:\n     \"\\<lbrakk>well_ord(A,r);\n         f \\<in> ord_iso(A,r, B,s);  g \\<in> ord_iso(A,r, B,s);  y \\<in> A\\<rbrakk>\n      \\<Longrightarrow> \\<not> <g`y, f`y> \\<in> s\"\napply (frule well_ord_iso_subset_lemma)\napply (rule_tac f = \"converse (f) \" and g = g in ord_iso_trans)\napply auto\napply (blast intro: ord_iso_sym)\napply (frule ord_iso_is_bij [of f])\napply (frule ord_iso_is_bij [of g])\napply (frule ord_iso_converse)\napply (blast intro!: bij_converse_bij\n             intro: bij_is_fun apply_funtype)+\napply (erule notE)\napply (simp add: left_inverse_bij bij_is_fun comp_fun_apply [of _ A B])\ndone\n\n\n(*Kunen's Lemma 6.2: Order-isomorphisms between well-orderings are unique*)\nlemma well_ord_iso_unique: \"\\<lbrakk>well_ord(A,r);\n         f \\<in> ord_iso(A,r, B,s);  g \\<in> ord_iso(A,r, B,s)\\<rbrakk> \\<Longrightarrow> f = g\"\napply (rule fun_extension)\napply (erule ord_iso_is_bij [THEN bij_is_fun])+\napply (subgoal_tac \"f`x \\<in> B \\<and> g`x \\<in> B \\<and> linear(B,s)\")\n apply (simp add: linear_def)\n apply (blast dest: well_ord_iso_unique_lemma)\napply (blast intro: ord_iso_is_bij bij_is_fun apply_funtype\n                    well_ord_is_linear well_ord_ord_iso ord_iso_sym)\ndone\n\nsubsection\\<open>Towards Kunen's Theorem 6.3: Linearity of the Similarity Relation\\<close>\n\nlemma ord_iso_map_subset: \"ord_iso_map(A,r,B,s) \\<subseteq> A*B\"\nby (unfold ord_iso_map_def, blast)\n\nlemma domain_ord_iso_map: \"domain(ord_iso_map(A,r,B,s)) \\<subseteq> A\"\nby (unfold ord_iso_map_def, blast)\n\nlemma range_ord_iso_map: \"range(ord_iso_map(A,r,B,s)) \\<subseteq> B\"\nby (unfold ord_iso_map_def, blast)\n\nlemma converse_ord_iso_map:\n    \"converse(ord_iso_map(A,r,B,s)) = ord_iso_map(B,s,A,r)\"\n  unfolding ord_iso_map_def\napply (blast intro: ord_iso_sym)\ndone\n\nlemma function_ord_iso_map:\n    \"well_ord(B,s) \\<Longrightarrow> function(ord_iso_map(A,r,B,s))\"\n  unfolding ord_iso_map_def function_def\napply (blast intro: well_ord_iso_pred_eq ord_iso_sym ord_iso_trans)\ndone\n\nlemma ord_iso_map_fun: \"well_ord(B,s) \\<Longrightarrow> ord_iso_map(A,r,B,s)\n           \\<in> domain(ord_iso_map(A,r,B,s)) -> range(ord_iso_map(A,r,B,s))\"\nby (simp add: Pi_iff function_ord_iso_map\n                 ord_iso_map_subset [THEN domain_times_range])\n\nlemma ord_iso_map_mono_map:\n    \"\\<lbrakk>well_ord(A,r);  well_ord(B,s)\\<rbrakk>\n     \\<Longrightarrow> ord_iso_map(A,r,B,s)\n           \\<in> mono_map(domain(ord_iso_map(A,r,B,s)), r,\n                      range(ord_iso_map(A,r,B,s)), s)\"\n  unfolding mono_map_def\napply (simp (no_asm_simp) add: ord_iso_map_fun)\napply safe\napply (subgoal_tac \"x \\<in> A \\<and> ya:A \\<and> y \\<in> B \\<and> yb:B\")\n apply (simp add: apply_equality [OF _  ord_iso_map_fun])\n   unfolding ord_iso_map_def\n apply (blast intro: well_ord_iso_preserving, blast)\ndone\n\nlemma ord_iso_map_ord_iso:\n    \"\\<lbrakk>well_ord(A,r);  well_ord(B,s)\\<rbrakk> \\<Longrightarrow> ord_iso_map(A,r,B,s)\n           \\<in> ord_iso(domain(ord_iso_map(A,r,B,s)), r,\n                      range(ord_iso_map(A,r,B,s)), s)\"\napply (rule well_ord_mono_ord_isoI)\n   prefer 4\n   apply (rule converse_ord_iso_map [THEN subst])\n   apply (simp add: ord_iso_map_mono_map\n                    ord_iso_map_subset [THEN converse_converse])\napply (blast intro!: domain_ord_iso_map range_ord_iso_map\n             intro: well_ord_subset ord_iso_map_mono_map)+\ndone\n\n\n(*One way of saying that domain(ord_iso_map(A,r,B,s)) is downwards-closed*)\nlemma domain_ord_iso_map_subset:\n     \"\\<lbrakk>well_ord(A,r);  well_ord(B,s);\n         a \\<in> A;  a \\<notin> domain(ord_iso_map(A,r,B,s))\\<rbrakk>\n      \\<Longrightarrow>  domain(ord_iso_map(A,r,B,s)) \\<subseteq> pred(A, a, r)\"\n  unfolding ord_iso_map_def\napply (safe intro!: predI)\n(*Case analysis on  xa vs a in r *)\napply (simp (no_asm_simp))\napply (frule_tac A = A in well_ord_is_linear)\napply (rename_tac b y f)\napply (erule_tac x=b and y=a in linearE, assumption+)\n(*Trivial case: b=a*)\napply clarify\napply blast\n(*Harder case: \\<langle>a, xa\\<rangle>: r*)\napply (frule ord_iso_is_bij [THEN bij_is_fun, THEN apply_type],\n       (erule asm_rl predI predE)+)\napply (frule ord_iso_restrict_pred)\n apply (simp add: pred_iff)\napply (simp split: split_if_asm\n          add: well_ord_is_trans_on trans_pred_pred_eq domain_UN domain_Union, blast)\ndone\n\n(*For the 4-way case analysis in the main result*)\nlemma domain_ord_iso_map_cases:\n     \"\\<lbrakk>well_ord(A,r);  well_ord(B,s)\\<rbrakk>\n      \\<Longrightarrow> domain(ord_iso_map(A,r,B,s)) = A |\n          (\\<exists>x\\<in>A. domain(ord_iso_map(A,r,B,s)) = pred(A,x,r))\"\napply (frule well_ord_is_wf)\n  unfolding wf_on_def wf_def\napply (drule_tac x = \"A-domain (ord_iso_map (A,r,B,s))\" in spec)\napply safe\n(*The first case: the domain equals A*)\napply (rule domain_ord_iso_map [THEN equalityI])\napply (erule Diff_eq_0_iff [THEN iffD1])\n(*The other case: the domain equals an initial segment*)\napply (blast del: domainI subsetI\n             elim!: predE\n             intro!: domain_ord_iso_map_subset\n             intro: subsetI)+\ndone\n\n(*As above, by duality*)\nlemma range_ord_iso_map_cases:\n    \"\\<lbrakk>well_ord(A,r);  well_ord(B,s)\\<rbrakk>\n     \\<Longrightarrow> range(ord_iso_map(A,r,B,s)) = B |\n         (\\<exists>y\\<in>B. range(ord_iso_map(A,r,B,s)) = pred(B,y,s))\"\napply (rule converse_ord_iso_map [THEN subst])\napply (simp add: domain_ord_iso_map_cases)\ndone\n\ntext\\<open>Kunen's Theorem 6.3: Fundamental Theorem for Well-Ordered Sets\\<close>\ntheorem well_ord_trichotomy:\n   \"\\<lbrakk>well_ord(A,r);  well_ord(B,s)\\<rbrakk>\n    \\<Longrightarrow> ord_iso_map(A,r,B,s) \\<in> ord_iso(A, r, B, s) |\n        (\\<exists>x\\<in>A. ord_iso_map(A,r,B,s) \\<in> ord_iso(pred(A,x,r), r, B, s)) |\n        (\\<exists>y\\<in>B. ord_iso_map(A,r,B,s) \\<in> ord_iso(A, r, pred(B,y,s), s))\"\napply (frule_tac B = B in domain_ord_iso_map_cases, assumption)\napply (frule_tac B = B in range_ord_iso_map_cases, assumption)\napply (drule ord_iso_map_ord_iso, assumption)\napply (elim disjE bexE)\n   apply (simp_all add: bexI)\napply (rule wf_on_not_refl [THEN notE])\n  apply (erule well_ord_is_wf)\n apply assumption\napply (subgoal_tac \"\\<langle>x,y\\<rangle>: ord_iso_map (A,r,B,s) \")\n apply (drule rangeI)\n apply (simp add: pred_def)\napply (unfold ord_iso_map_def, blast)\ndone\n\n\nsubsection\\<open>Miscellaneous Results by Krzysztof Grabczewski\\<close>\n\n(** Properties of converse(r) **)\n\nlemma irrefl_converse: \"irrefl(A,r) \\<Longrightarrow> irrefl(A,converse(r))\"\nby (unfold irrefl_def, blast)\n\nlemma trans_on_converse: \"trans[A](r) \\<Longrightarrow> trans[A](converse(r))\"\nby (unfold trans_on_def, blast)\n\nlemma part_ord_converse: \"part_ord(A,r) \\<Longrightarrow> part_ord(A,converse(r))\"\n  unfolding part_ord_def\napply (blast intro!: irrefl_converse trans_on_converse)\ndone\n\nlemma linear_converse: \"linear(A,r) \\<Longrightarrow> linear(A,converse(r))\"\nby (unfold linear_def, blast)\n\nlemma tot_ord_converse: \"tot_ord(A,r) \\<Longrightarrow> tot_ord(A,converse(r))\"\n  unfolding tot_ord_def\napply (blast intro!: part_ord_converse linear_converse)\ndone\n\n\n(** By Krzysztof Grabczewski.\n    Lemmas involving the first element of a well ordered set **)\n\nlemma first_is_elem: \"first(b,B,r) \\<Longrightarrow> b \\<in> B\"\nby (unfold first_def, blast)\n\nlemma well_ord_imp_ex1_first:\n        \"\\<lbrakk>well_ord(A,r); B<=A; B\\<noteq>0\\<rbrakk> \\<Longrightarrow> (\\<exists>!b. first(b,B,r))\"\n  unfolding well_ord_def wf_on_def wf_def first_def\napply (elim conjE allE disjE, blast)\napply (erule bexE)\napply (rule_tac a = x in ex1I, auto)\napply (unfold tot_ord_def linear_def, blast)\ndone\n\nlemma the_first_in:\n     \"\\<lbrakk>well_ord(A,r); B<=A; B\\<noteq>0\\<rbrakk> \\<Longrightarrow> (THE b. first(b,B,r)) \\<in> B\"\napply (drule well_ord_imp_ex1_first, assumption+)\napply (rule first_is_elem)\napply (erule theI)\ndone\n\n\nsubsection \\<open>Lemmas for the Reflexive Orders\\<close>\n\nlemma subset_vimage_vimage_iff:\n  \"\\<lbrakk>Preorder(r); A \\<subseteq> field(r); B \\<subseteq> field(r)\\<rbrakk> \\<Longrightarrow>\n  r -`` A \\<subseteq> r -`` B \\<longleftrightarrow> (\\<forall>a\\<in>A. \\<exists>b\\<in>B. \\<langle>a, b\\<rangle> \\<in> r)\"\n  apply (auto simp: subset_def preorder_on_def refl_def vimage_def image_def)\n   apply blast\n  unfolding trans_on_def\n  apply (erule_tac P = \"(\\<lambda>x. \\<forall>y\\<in>field(r).\n          \\<forall>z\\<in>field(r). \\<langle>x, y\\<rangle> \\<in> r \\<longrightarrow> \\<langle>y, z\\<rangle> \\<in> r \\<longrightarrow> \\<langle>x, z\\<rangle> \\<in> r)\" for r in rev_ballE)\n    (* instance obtained from proof term generated by best *)\n   apply best\n  apply blast\n  done\n\nlemma subset_vimage1_vimage1_iff:\n  \"\\<lbrakk>Preorder(r); a \\<in> field(r); b \\<in> field(r)\\<rbrakk> \\<Longrightarrow>\n  r -`` {a} \\<subseteq> r -`` {b} \\<longleftrightarrow> \\<langle>a, b\\<rangle> \\<in> r\"\n  by (simp add: subset_vimage_vimage_iff)\n\nlemma Refl_antisym_eq_Image1_Image1_iff:\n  \"\\<lbrakk>refl(field(r), r); antisym(r); a \\<in> field(r); b \\<in> field(r)\\<rbrakk> \\<Longrightarrow>\n  r `` {a} = r `` {b} \\<longleftrightarrow> a = b\"\n  apply rule\n   apply (frule equality_iffD)\n   apply (drule equality_iffD)\n   apply (simp add: antisym_def refl_def)\n   apply best\n  apply (simp add: antisym_def refl_def)\n  done\n\nlemma Partial_order_eq_Image1_Image1_iff:\n  \"\\<lbrakk>Partial_order(r); a \\<in> field(r); b \\<in> field(r)\\<rbrakk> \\<Longrightarrow>\n  r `` {a} = r `` {b} \\<longleftrightarrow> a = b\"\n  by (simp add: partial_order_on_def preorder_on_def\n    Refl_antisym_eq_Image1_Image1_iff)\n\nlemma Refl_antisym_eq_vimage1_vimage1_iff:\n  \"\\<lbrakk>refl(field(r), r); antisym(r); a \\<in> field(r); b \\<in> field(r)\\<rbrakk> \\<Longrightarrow>\n  r -`` {a} = r -`` {b} \\<longleftrightarrow> a = b\"\n  apply rule\n   apply (frule equality_iffD)\n   apply (drule equality_iffD)\n   apply (simp add: antisym_def refl_def)\n   apply best\n  apply (simp add: antisym_def refl_def)\n  done\n\nlemma Partial_order_eq_vimage1_vimage1_iff:\n  \"\\<lbrakk>Partial_order(r); a \\<in> field(r); b \\<in> field(r)\\<rbrakk> \\<Longrightarrow>\n  r -`` {a} = r -`` {b} \\<longleftrightarrow> a = b\"\n  by (simp add: partial_order_on_def preorder_on_def\n    Refl_antisym_eq_vimage1_vimage1_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/ZF/Order.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8824278695464501, "lm_q2_score": 0.822189134878876, "lm_q1q2_score": 0.7255226066554055}}
{"text": "section\\<open>Arities of internalized formulas\\<close>\ntheory Arities\n  imports FrecR\nbegin\n\nlemma arity_upair_fm : \"\\<lbrakk>  t1\\<in>nat ; t2\\<in>nat ; up\\<in>nat  \\<rbrakk> \\<Longrightarrow> \n  arity(upair_fm(t1,t2,up)) = \\<Union> {succ(t1),succ(t2),succ(up)}\"\n  unfolding  upair_fm_def\n  using nat_union_abs1 nat_union_abs2 pred_Un   \n  by auto\n\n\nlemma arity_pair_fm : \"\\<lbrakk>  t1\\<in>nat ; t2\\<in>nat ; p\\<in>nat  \\<rbrakk> \\<Longrightarrow> \n  arity(pair_fm(t1,t2,p)) = \\<Union> {succ(t1),succ(t2),succ(p)}\"\n  unfolding pair_fm_def \n  using arity_upair_fm nat_union_abs1 nat_union_abs2 pred_Un\n  by auto\n\nlemma arity_composition_fm :\n  \"\\<lbrakk> r\\<in>nat ; s\\<in>nat ; t\\<in>nat \\<rbrakk> \\<Longrightarrow> arity(composition_fm(r,s,t)) = \\<Union> {succ(r), succ(s), succ(t)}\"\n  unfolding composition_fm_def    \n  using arity_pair_fm nat_union_abs1 nat_union_abs2 pred_Un_distrib\n  by auto\n\nlemma arity_domain_fm : \n    \"\\<lbrakk> r\\<in>nat ; z\\<in>nat \\<rbrakk> \\<Longrightarrow> arity(domain_fm(r,z)) = succ(r) \\<union> succ(z)\"\n  unfolding domain_fm_def \n  using arity_pair_fm nat_union_abs1 nat_union_abs2 pred_Un_distrib\n  by auto\n\nlemma arity_range_fm : \n    \"\\<lbrakk> r\\<in>nat ; z\\<in>nat \\<rbrakk> \\<Longrightarrow> arity(range_fm(r,z)) = succ(r) \\<union> succ(z)\"\n  unfolding range_fm_def \n  using arity_pair_fm nat_union_abs1 nat_union_abs2 pred_Un_distrib\n  by auto\n\nlemma arity_union_fm : \n  \"\\<lbrakk> x\\<in>nat ; y\\<in>nat ; z\\<in>nat \\<rbrakk> \\<Longrightarrow> arity(union_fm(x,y,z)) = \\<Union> {succ(x), succ(y), succ(z)}\"\n  unfolding union_fm_def\n  using  nat_union_abs1 nat_union_abs2 pred_Un_distrib\n  by auto\n\nlemma arity_image_fm : \n  \"\\<lbrakk> x\\<in>nat ; y\\<in>nat ; z\\<in>nat \\<rbrakk> \\<Longrightarrow> arity(image_fm(x,y,z)) = \\<Union> {succ(x), succ(y), succ(z)}\"\n  unfolding image_fm_def\n  using arity_pair_fm  nat_union_abs1 nat_union_abs2 pred_Un_distrib\n  by auto\n\nlemma arity_pre_image_fm : \n  \"\\<lbrakk> x\\<in>nat ; y\\<in>nat ; z\\<in>nat \\<rbrakk> \\<Longrightarrow> arity(pre_image_fm(x,y,z)) = \\<Union> {succ(x), succ(y), succ(z)}\"\n  unfolding pre_image_fm_def\n  using arity_pair_fm  nat_union_abs1 nat_union_abs2 pred_Un_distrib\n  by auto\n\n\nlemma arity_big_union_fm : \n  \"\\<lbrakk> x\\<in>nat ; y\\<in>nat \\<rbrakk> \\<Longrightarrow> arity(big_union_fm(x,y)) = succ(x) \\<union> succ(y)\"\n  unfolding big_union_fm_def\n  using nat_union_abs1 nat_union_abs2 pred_Un_distrib\n  by auto\n\nlemma arity_fun_apply_fm : \n  \"\\<lbrakk> x\\<in>nat ; y\\<in>nat ; f\\<in>nat \\<rbrakk> \\<Longrightarrow> \n    arity(fun_apply_fm(f,x,y)) =  succ(f) \\<union> succ(x) \\<union> succ(y)\"\n  unfolding fun_apply_fm_def\n  using arity_upair_fm arity_image_fm arity_big_union_fm nat_union_abs2 pred_Un_distrib\n  by auto\n\nlemma arity_field_fm : \n    \"\\<lbrakk> r\\<in>nat ; z\\<in>nat \\<rbrakk> \\<Longrightarrow> arity(field_fm(r,z)) = succ(r) \\<union> succ(z)\"\n  unfolding field_fm_def \n  using arity_pair_fm arity_domain_fm arity_range_fm arity_union_fm \n    nat_union_abs1 nat_union_abs2 pred_Un_distrib\n  by auto\n\nlemma arity_empty_fm : \n    \"\\<lbrakk> r\\<in>nat \\<rbrakk> \\<Longrightarrow> arity(empty_fm(r)) = succ(r)\"\n  unfolding empty_fm_def \n  using nat_union_abs1 nat_union_abs2 pred_Un_distrib\n  by simp\n\nlemma arity_succ_fm :\n  \"\\<lbrakk>x\\<in>nat;y\\<in>nat\\<rbrakk> \\<Longrightarrow> arity(succ_fm(x,y)) = succ(x) \\<union> succ(y)\"\n  unfolding succ_fm_def cons_fm_def \n  using arity_upair_fm arity_union_fm nat_union_abs2 pred_Un_distrib\n  by auto\n\n\nlemma number1arity__fm : \n    \"\\<lbrakk> r\\<in>nat \\<rbrakk> \\<Longrightarrow> arity(number1_fm(r)) = succ(r)\"\n  unfolding number1_fm_def \n  using arity_empty_fm arity_succ_fm nat_union_abs1 nat_union_abs2 pred_Un_distrib\n  by simp\n\n\nlemma arity_function_fm : \n    \"\\<lbrakk> r\\<in>nat \\<rbrakk> \\<Longrightarrow> arity(function_fm(r)) = succ(r)\"\n  unfolding function_fm_def \n  using arity_pair_fm nat_union_abs1 nat_union_abs2 pred_Un_distrib\n  by simp\n\nlemma arity_relation_fm : \n    \"\\<lbrakk> r\\<in>nat \\<rbrakk> \\<Longrightarrow> arity(relation_fm(r)) = succ(r)\"\n  unfolding relation_fm_def \n  using arity_pair_fm nat_union_abs1 nat_union_abs2 pred_Un_distrib\n  by simp\n\nlemma arity_restriction_fm : \n    \"\\<lbrakk> r\\<in>nat ; z\\<in>nat ; A\\<in>nat \\<rbrakk> \\<Longrightarrow> arity(restriction_fm(A,z,r)) = succ(A) \\<union> succ(r) \\<union> succ(z)\"\n  unfolding restriction_fm_def \n  using arity_pair_fm nat_union_abs2 pred_Un_distrib\n  by auto\n\nlemma arity_typed_function_fm : \n  \"\\<lbrakk> x\\<in>nat ; y\\<in>nat ; f\\<in>nat \\<rbrakk> \\<Longrightarrow> \n    arity(typed_function_fm(f,x,y)) = \\<Union> {succ(f), succ(x), succ(y)}\"\n  unfolding typed_function_fm_def\n  using arity_pair_fm arity_relation_fm arity_function_fm arity_domain_fm \n    nat_union_abs2 pred_Un_distrib\n  by auto\n\n\nlemma arity_subset_fm : \n  \"\\<lbrakk>x\\<in>nat ; y\\<in>nat\\<rbrakk> \\<Longrightarrow> arity(subset_fm(x,y)) = succ(x) \\<union> succ(y)\"\n  unfolding subset_fm_def \n  using nat_union_abs2 pred_Un_distrib\n  by auto\n\nlemma arity_transset_fm :\n  \"\\<lbrakk>x\\<in>nat\\<rbrakk> \\<Longrightarrow> arity(transset_fm(x)) = succ(x)\"\n  unfolding transset_fm_def \n  using arity_subset_fm nat_union_abs2 pred_Un_distrib\n  by auto\n\nlemma arity_ordinal_fm :\n  \"\\<lbrakk>x\\<in>nat\\<rbrakk> \\<Longrightarrow> arity(ordinal_fm(x)) = succ(x)\"\n  unfolding ordinal_fm_def \n  using arity_transset_fm nat_union_abs2 pred_Un_distrib\n  by auto\n\nlemma arity_limit_ordinal_fm :\n  \"\\<lbrakk>x\\<in>nat\\<rbrakk> \\<Longrightarrow> arity(limit_ordinal_fm(x)) = succ(x)\"\n  unfolding limit_ordinal_fm_def \n  using arity_ordinal_fm arity_succ_fm arity_empty_fm nat_union_abs2 pred_Un_distrib\n  by auto\n\nlemma arity_finite_ordinal_fm :\n  \"\\<lbrakk>x\\<in>nat\\<rbrakk> \\<Longrightarrow> arity(finite_ordinal_fm(x)) = succ(x)\"\n  unfolding finite_ordinal_fm_def \n  using arity_ordinal_fm arity_limit_ordinal_fm arity_succ_fm arity_empty_fm \n    nat_union_abs2 pred_Un_distrib\n  by auto\n\nlemma arity_omega_fm :\n  \"\\<lbrakk>x\\<in>nat\\<rbrakk> \\<Longrightarrow> arity(omega_fm(x)) = succ(x)\"\n  unfolding omega_fm_def \n  using arity_limit_ordinal_fm nat_union_abs2 pred_Un_distrib\n  by auto\n\nlemma arity_cartprod_fm : \n  \"\\<lbrakk> A\\<in>nat ; B\\<in>nat ; z\\<in>nat \\<rbrakk> \\<Longrightarrow> arity(cartprod_fm(A,B,z)) = succ(A) \\<union> succ(B) \\<union> succ(z)\"\n  unfolding cartprod_fm_def\n  using arity_pair_fm nat_union_abs2 pred_Un_distrib\n  by auto\n\nlemma arity_fst_fm :\n  \"\\<lbrakk>x\\<in>nat ; t\\<in>nat\\<rbrakk> \\<Longrightarrow> arity(fst_fm(x,t)) = succ(x) \\<union> succ(t)\"\n  unfolding fst_fm_def\n  using arity_pair_fm arity_empty_fm nat_union_abs2 pred_Un_distrib\n  by auto\n\nlemma arity_snd_fm :\n  \"\\<lbrakk>x\\<in>nat ; t\\<in>nat\\<rbrakk> \\<Longrightarrow> arity(snd_fm(x,t)) = succ(x) \\<union> succ(t)\"\n  unfolding snd_fm_def\n  using arity_pair_fm arity_empty_fm nat_union_abs2 pred_Un_distrib\n  by auto\n\nlemma arity_snd_snd_fm :\n  \"\\<lbrakk>x\\<in>nat ; t\\<in>nat\\<rbrakk> \\<Longrightarrow> arity(snd_snd_fm(x,t)) = succ(x) \\<union> succ(t)\"\n  unfolding snd_snd_fm_def hcomp_fm_def\n  using arity_snd_fm arity_empty_fm nat_union_abs2 pred_Un_distrib\n  by auto\n\nlemma arity_ftype_fm :\n  \"\\<lbrakk>x\\<in>nat ; t\\<in>nat\\<rbrakk> \\<Longrightarrow> arity(ftype_fm(x,t)) = succ(x) \\<union> succ(t)\"\n  unfolding ftype_fm_def\n  using arity_fst_fm \n  by auto\n\nlemma name1arity__fm :\n  \"\\<lbrakk>x\\<in>nat ; t\\<in>nat\\<rbrakk> \\<Longrightarrow> arity(name1_fm(x,t)) = succ(x) \\<union> succ(t)\"\n  unfolding name1_fm_def hcomp_fm_def\n  using arity_fst_fm arity_snd_fm nat_union_abs2 pred_Un_distrib\n  by auto\n\nlemma name2arity__fm :\n  \"\\<lbrakk>x\\<in>nat ; t\\<in>nat\\<rbrakk> \\<Longrightarrow> arity(name2_fm(x,t)) = succ(x) \\<union> succ(t)\"\n  unfolding name2_fm_def hcomp_fm_def\n  using arity_fst_fm arity_snd_snd_fm nat_union_abs2 pred_Un_distrib\n  by auto\n\nlemma arity_cond_of_fm :\n  \"\\<lbrakk>x\\<in>nat ; t\\<in>nat\\<rbrakk> \\<Longrightarrow> arity(cond_of_fm(x,t)) = succ(x) \\<union> succ(t)\"\n  unfolding cond_of_fm_def hcomp_fm_def\n  using arity_snd_fm arity_snd_snd_fm nat_union_abs2 pred_Un_distrib\n  by auto\n\nlemma arity_singleton_fm :\n  \"\\<lbrakk>x\\<in>nat ; t\\<in>nat\\<rbrakk> \\<Longrightarrow> arity(singleton_fm(x,t)) = succ(x) \\<union> succ(t)\"\n  unfolding singleton_fm_def cons_fm_def\n  using arity_union_fm arity_upair_fm arity_empty_fm nat_union_abs2 pred_Un_distrib\n  by auto\n\nlemma arity_Memrel_fm :\n  \"\\<lbrakk>x\\<in>nat ; t\\<in>nat\\<rbrakk> \\<Longrightarrow> arity(Memrel_fm(x,t)) = succ(x) \\<union> succ(t)\"\n  unfolding Memrel_fm_def \n  using  arity_pair_fm nat_union_abs2 pred_Un_distrib\n  by auto\n\nlemma arity_quasinat_fm :\n  \"\\<lbrakk>x\\<in>nat\\<rbrakk> \\<Longrightarrow> arity(quasinat_fm(x)) = succ(x)\"\n  unfolding quasinat_fm_def cons_fm_def \n  using arity_succ_fm arity_empty_fm\n    nat_union_abs2 pred_Un_distrib\n  by auto\n\nlemma arity_is_recfun_fm :\n  \"\\<lbrakk>p\\<in>formula ; v\\<in>nat ; n\\<in>nat; Z\\<in>nat;i\\<in>nat\\<rbrakk> \\<Longrightarrow>  arity(p) = i \\<Longrightarrow> \n  arity(is_recfun_fm(p,v,n,Z)) = succ(v) \\<union> succ(n) \\<union> succ(Z) \\<union> pred(pred(pred(pred(i))))\"\n  unfolding is_recfun_fm_def\n  using arity_upair_fm arity_pair_fm arity_pre_image_fm arity_restriction_fm\n    nat_union_abs2 pred_Un_distrib\n  by auto\n\nlemma arity_is_wfrec_fm :\n  \"\\<lbrakk>p\\<in>formula ; v\\<in>nat ; n\\<in>nat; Z\\<in>nat ; i\\<in>nat\\<rbrakk> \\<Longrightarrow> arity(p) = i \\<Longrightarrow> \n    arity(is_wfrec_fm(p,v,n,Z)) = succ(v) \\<union> succ(n) \\<union> succ(Z) \\<union> pred(pred(pred(pred(pred(i)))))\"\n  unfolding is_wfrec_fm_def\n  using arity_succ_fm  arity_is_recfun_fm \n     nat_union_abs2 pred_Un_distrib\n  by auto\n\nlemma arity_is_nat_case_fm :\n  \"\\<lbrakk>p\\<in>formula ; v\\<in>nat ; n\\<in>nat; Z\\<in>nat; i\\<in>nat\\<rbrakk> \\<Longrightarrow> arity(p) = i \\<Longrightarrow> \n    arity(is_nat_case_fm(v,p,n,Z)) = succ(v) \\<union> succ(n) \\<union> succ(Z) \\<union> pred(pred(i))\"\n  unfolding is_nat_case_fm_def\n  using arity_succ_fm arity_empty_fm arity_quasinat_fm \n    nat_union_abs2 pred_Un_distrib\n  by auto\n\nlemma arity_iterates_MH_fm :\n  assumes \"isF\\<in>formula\" \"v\\<in>nat\" \"n\\<in>nat\" \"g\\<in>nat\" \"z\\<in>nat\" \"i\\<in>nat\" \n      \"arity(isF) = i\"\n    shows \"arity(iterates_MH_fm(isF,v,n,g,z)) = \n           succ(v) \\<union> succ(n) \\<union> succ(g) \\<union> succ(z) \\<union> pred(pred(pred(pred(i))))\"\nproof -\n  let ?\\<phi> = \"Exists(And(fun_apply_fm(succ(succ(succ(g))), 2, 0), Forall(Implies(Equal(0, 2), isF))))\"\n  let ?ar = \"succ(succ(succ(g))) \\<union> pred(pred(i))\"\n  from assms\n  have \"arity(?\\<phi>) =?ar\" \"?\\<phi>\\<in>formula\" \n    using arity_fun_apply_fm\n    nat_union_abs1 nat_union_abs2 pred_Un_distrib succ_Un_distrib Un_assoc[symmetric]\n    by simp_all\n  then\n  show ?thesis\n    unfolding iterates_MH_fm_def\n    using arity_is_nat_case_fm[OF \\<open>?\\<phi>\\<in>_\\<close> _ _ _ _ \\<open>arity(?\\<phi>) = _\\<close>] assms pred_succ_eq pred_Un_distrib\n    by auto\nqed\n\nlemma arity_is_iterates_fm :\n  assumes \"p\\<in>formula\" \"v\\<in>nat\" \"n\\<in>nat\" \"Z\\<in>nat\" \"i\\<in>nat\" \n    \"arity(p) = i\"\n  shows \"arity(is_iterates_fm(p,v,n,Z)) = succ(v) \\<union> succ(n) \\<union> succ(Z) \\<union> \n          pred(pred(pred(pred(pred(pred(pred(pred(pred(pred(pred(i)))))))))))\"\nproof -\n  let ?\\<phi> = \"iterates_MH_fm(p, 7#+v, 2, 1, 0)\"\n  let ?\\<psi> = \"is_wfrec_fm(?\\<phi>, 0, succ(succ(n)),succ(succ(Z)))\"\n  from \\<open>v\\<in>_\\<close>\n  have \"arity(?\\<phi>) = (8#+v) \\<union> pred(pred(pred(pred(i))))\" \"?\\<phi>\\<in>formula\"\n    using assms arity_iterates_MH_fm nat_union_abs2\n    by simp_all\n  then\n  have \"arity(?\\<psi>) = succ(succ(succ(n))) \\<union> succ(succ(succ(Z))) \\<union> (3#+v) \\<union> \n      pred(pred(pred(pred(pred(pred(pred(pred(pred(i)))))))))\"\n    using assms arity_is_wfrec_fm[OF \\<open>?\\<phi>\\<in>_\\<close> _ _ _ _ \\<open>arity(?\\<phi>) = _\\<close>] nat_union_abs1 pred_Un_distrib\n    by auto\n  then\n  show ?thesis\n    unfolding is_iterates_fm_def \n    using arity_Memrel_fm arity_succ_fm assms nat_union_abs1 pred_Un_distrib\n    by auto\nqed\n\nlemma arity_eclose_n_fm :\n  assumes \"A\\<in>nat\" \"x\\<in>nat\" \"t\\<in>nat\" \n  shows \"arity(eclose_n_fm(A,x,t)) = succ(A) \\<union> succ(x) \\<union> succ(t)\"\nproof -\n  let ?\\<phi> = \"big_union_fm(1,0)\"\n  have \"arity(?\\<phi>) = 2\" \"?\\<phi>\\<in>formula\" \n    using arity_big_union_fm nat_union_abs2\n    by simp_all\n  with assms\n  show ?thesis\n    unfolding eclose_n_fm_def\n    using arity_is_iterates_fm[OF \\<open>?\\<phi>\\<in>_\\<close> _ _ _,of _ _ _ 2] \n    by auto\nqed\n\nlemma arity_mem_eclose_fm :\n  assumes \"x\\<in>nat\" \"t\\<in>nat\"\n  shows \"arity(mem_eclose_fm(x,t)) = succ(x) \\<union> succ(t)\"\nproof -  \n  let ?\\<phi>=\"eclose_n_fm(x #+ 2, 1, 0)\"\n  from \\<open>x\\<in>nat\\<close>\n  have \"arity(?\\<phi>) = x#+3\" \n    using arity_eclose_n_fm nat_union_abs2 \n    by simp\n  with assms\n  show ?thesis\n    unfolding mem_eclose_fm_def \n    using arity_finite_ordinal_fm nat_union_abs2 pred_Un_distrib\n    by simp\nqed\n\nlemma arity_is_eclose_fm :\n  \"\\<lbrakk>x\\<in>nat ; t\\<in>nat\\<rbrakk> \\<Longrightarrow> arity(is_eclose_fm(x,t)) = succ(x) \\<union> succ(t)\"\n  unfolding is_eclose_fm_def \n  using arity_mem_eclose_fm nat_union_abs2 pred_Un_distrib\n  by auto\n\nlemma eclose_n1arity__fm :\n  \"\\<lbrakk>x\\<in>nat ; t\\<in>nat\\<rbrakk> \\<Longrightarrow> arity(eclose_n1_fm(x,t)) = succ(x) \\<union> succ(t)\"\n  unfolding eclose_n1_fm_def \n  using arity_is_eclose_fm arity_singleton_fm name1arity__fm nat_union_abs2 pred_Un_distrib\n  by auto\n\nlemma eclose_n2arity__fm :\n  \"\\<lbrakk>x\\<in>nat ; t\\<in>nat\\<rbrakk> \\<Longrightarrow> arity(eclose_n2_fm(x,t)) = succ(x) \\<union> succ(t)\"\n  unfolding eclose_n2_fm_def \n  using arity_is_eclose_fm arity_singleton_fm name2arity__fm nat_union_abs2 pred_Un_distrib\n  by auto\n\nlemma arity_ecloseN_fm :\n  \"\\<lbrakk>x\\<in>nat ; t\\<in>nat\\<rbrakk> \\<Longrightarrow> arity(ecloseN_fm(x,t)) = succ(x) \\<union> succ(t)\"\n  unfolding ecloseN_fm_def \n  using eclose_n1arity__fm eclose_n2arity__fm arity_union_fm nat_union_abs2 pred_Un_distrib\n  by auto\n\nlemma arity_frecR_fm :\n  \"\\<lbrakk>a\\<in>nat;b\\<in>nat\\<rbrakk> \\<Longrightarrow> arity(frecR_fm(a,b)) = succ(a) \\<union> succ(b)\"\n  unfolding frecR_fm_def\n  using arity_ftype_fm name1arity__fm name2arity__fm arity_domain_fm \n      number1arity__fm arity_empty_fm nat_union_abs2 pred_Un_distrib\n  by auto\n\nlemma arity_Collect_fm :\n  assumes \"x \\<in> nat\" \"y \\<in> nat\" \"p\\<in>formula\" \n  shows \"arity(Collect_fm(x,p,y)) = succ(x) \\<union> succ(y) \\<union> pred(arity(p))\"\n  unfolding Collect_fm_def\n  using assms pred_Un_distrib\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/Forcing/Arities.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942119105696, "lm_q2_score": 0.8031737963569016, "lm_q1q2_score": 0.7255022414074277}}
{"text": "(* author: wzh*)\n\ntheory MyList\n  imports Main\n\nbegin\n\ndatatype 'a list = Nil | Cons 'a \"'a list\"\n\n(*app means add two lists*)\nfun app :: \"'a list \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where\n\"app Nil xs = xs\" |\n\"app (Cons x xs) ys = Cons x (app xs ys)\"\n\n\n(*rev means reverse a list*)\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 \"rev(Cons a (Cons b 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\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/MyList.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942014971872, "lm_q2_score": 0.8031738034238807, "lm_q1q2_score": 0.7255022394272331}}
{"text": "section \\<open>Permutations as Products of Disjoint Cycles\\<close>\n\ntheory Executable_Permutations\nimports\n  Graph_Theory.Funpow\n  List_Aux\n  \"HOL-Library.Permutations\"\n  \"HOL-Library.Rewrite\"\nbegin\n\nsubsection \\<open>Cyclic Permutations\\<close>\n\ndefinition list_succ :: \"'a list \\<Rightarrow> 'a \\<Rightarrow> 'a\" where\n  \"list_succ xs x = (if x \\<in> set xs then xs ! ((index xs x + 1) mod length xs) else x)\"\n\ntext \\<open>\n  We demonstrate the functions on the following simple lemmas\n\n  @{lemma \"list_succ [1 :: int, 2, 3] 1 = 2\" by code_simp}\n  @{lemma \"list_succ [1 :: int, 2, 3] 2 = 3\" by code_simp}\n  @{lemma \"list_succ [1 :: int, 2, 3] 3 = 1\" by code_simp}\n\\<close>\n\nlemma list_succ_altdef:\n  \"list_succ xs x = (let n = index xs x in if n + 1 = length xs then xs ! 0 else if n + 1 < length xs then xs ! (n + 1) else x)\"\n  using index_le_size[of xs x] unfolding list_succ_def index_less_size_conv[symmetric] by (auto simp: Let_def)\n\nlemma list_succ_Nil:\n  \"list_succ [] = id\"\n  by (simp add: list_succ_def fun_eq_iff)\n\nlemma list_succ_singleton:\n  \"list_succ [x] = list_succ []\"\n  by (simp add: fun_eq_iff list_succ_def)\n\nlemma list_succ_short:\n  assumes \"length xs < 2\" shows \"list_succ xs = id\"\n  using assms\n  by (cases xs) (rename_tac [2] y ys, case_tac [2] ys, auto simp: list_succ_Nil list_succ_singleton)\n\nlemma list_succ_simps:\n  \"index xs x + 1 = length xs \\<Longrightarrow> list_succ xs x = xs ! 0\"\n  \"index xs x + 1 < length xs \\<Longrightarrow> list_succ xs x = xs ! (index xs x + 1)\"\n  \"length xs \\<le> index xs x \\<Longrightarrow> list_succ xs x = x\"\n  by (auto simp: list_succ_altdef)\n\nlemma list_succ_not_in:\n  assumes \"x \\<notin> set xs\" shows \"list_succ xs x = x\"\n  using assms by (auto simp: list_succ_def)\n\nlemma list_succ_list_succ_rev:\n  assumes \"distinct xs\" shows \"list_succ (rev xs) (list_succ xs x) = x\"\nproof -\n  { assume \"index xs x + 1 < length xs\"\n    moreover then have \"length xs - Suc (Suc (length xs - Suc (Suc (index xs x)))) = index xs x\"\n      by linarith\n    ultimately have ?thesis using assms\n      by (simp add: list_succ_def index_rev index_nth_id rev_nth)\n  }\n  moreover\n  { assume A: \"index xs x + 1 = length xs\"\n    moreover\n    from A have \"xs \\<noteq> []\" by auto\n    moreover\n    with A have \"last xs = xs ! index xs x\" by (cases \"length xs\") (auto simp: last_conv_nth)\n    ultimately\n    have ?thesis\n      using assms\n      by (auto simp add: list_succ_def rev_nth index_rev index_nth_id last_conv_nth)\n  }\n  moreover\n  { assume A: \"index xs x \\<ge> length xs\"\n    then have \"x \\<notin> set xs\" by (metis index_less less_irrefl)\n    then have ?thesis by (auto simp: list_succ_def) }\n  ultimately show ?thesis by (metis discrete le_less not_less) \nqed\n\nlemma inj_list_succ: \"distinct xs \\<Longrightarrow> inj (list_succ xs)\"\n  by (metis injI list_succ_list_succ_rev)\n\nlemma inv_list_succ_eq: \"distinct xs \\<Longrightarrow> inv (list_succ xs) = list_succ (rev xs)\"\n  by (metis distinct_rev inj_imp_inv_eq inj_list_succ list_succ_list_succ_rev)\n\nlemma bij_list_succ: \"distinct xs \\<Longrightarrow> bij (list_succ xs)\"\n  by (metis bij_def inj_list_succ distinct_rev list_succ_list_succ_rev surj_def)\n\nlemma list_succ_permutes:\n  assumes \"distinct xs\" shows \"list_succ xs permutes set xs\"\n  using assms by (auto simp: permutes_conv_has_dom bij_list_succ has_dom_def list_succ_def)\n\nlemma permutation_list_succ:\n  assumes \"distinct xs\" shows \"permutation (list_succ xs)\"\n  using list_succ_permutes[OF assms] by (auto simp: permutation_permutes)\n\nlemma list_succ_nth:\n  assumes \"distinct xs\" \"n < length xs\" shows \"list_succ xs (xs ! n) = xs ! (Suc n mod length xs)\"\n  using assms by (auto simp: list_succ_def index_nth_id)\n\nlemma list_succ_last[simp]:\n  assumes \"distinct xs\" \"xs \\<noteq> []\" shows \"list_succ xs (last xs) = hd xs\"\n  using assms by (auto simp: list_succ_def hd_conv_nth)\n\nlemma list_succ_rotate1[simp]:\n  assumes \"distinct xs\" shows \"list_succ (rotate1 xs) = list_succ xs\"\nproof (rule ext)\n  fix y show \"list_succ (rotate1 xs) y = list_succ xs y\"\n    using assms\n  proof (induct xs)\n    case Nil then show ?case by simp\n  next\n    case (Cons x xs)\n    show ?case\n    proof (cases \"x = y\")\n      case True\n      then have \"index (xs @ [y]) y = length xs\"\n        using \\<open>distinct (x # xs)\\<close> by (simp add: index_append)\n      with True show ?thesis by (cases \"xs=[]\") (auto simp: list_succ_def nth_append)\n    next\n      case False\n      then show ?thesis\n        apply (cases \"index xs y + 1 < length xs\")\n        apply (auto simp:list_succ_def index_append nth_append)\n        by (metis Suc_lessI index_less_size_conv mod_self nth_Cons_0 nth_append nth_append_length)\n    qed\n  qed\nqed\n  \nlemma list_succ_rotate[simp]:\n  assumes \"distinct xs\" shows \"list_succ (rotate n xs) = list_succ xs\"\n  using assms by (induct n) auto\n\nlemma list_succ_in_conv:\n  \"list_succ xs x \\<in> set xs \\<longleftrightarrow> x \\<in> set xs\"\n  by (auto simp: list_succ_def not_nil_if_in_set )\n\nlemma list_succ_in_conv1:\n  assumes \"A \\<inter> set xs = {}\"\n  shows \"list_succ xs x \\<in> A \\<longleftrightarrow> x \\<in> A\"\n  by (metis assms disjoint_iff_not_equal list_succ_in_conv list_succ_not_in)\n\nlemma list_succ_commute:\n  assumes \"set xs \\<inter> set ys = {}\"\n  shows \"list_succ xs (list_succ ys x) = list_succ ys (list_succ xs x)\"\nproof -\n  have \"\\<And>x. x \\<in> set xs \\<Longrightarrow> list_succ ys x = x\"\n     \"\\<And>x. x \\<in> set ys \\<Longrightarrow> list_succ xs x = x\"\n    using assms by (blast intro: list_succ_not_in)+\n  then show ?thesis\n    by (cases \"x \\<in> set xs \\<union> set ys\") (auto simp: list_succ_in_conv list_succ_not_in)\nqed\n\n\nsubsection \\<open>Arbitrary Permutations\\<close>\n\nfun lists_succ :: \"'a list list \\<Rightarrow> 'a \\<Rightarrow> 'a\" where\n  \"lists_succ [] x = x\"\n| \"lists_succ (xs # xss) x = list_succ xs (lists_succ xss x)\"\n\ndefinition distincts ::  \"'a list list \\<Rightarrow> bool\" where\n  \"distincts xss \\<equiv> distinct xss \\<and> (\\<forall>xs \\<in> set xss. distinct xs \\<and> xs \\<noteq> []) \\<and> (\\<forall>xs \\<in> set xss. \\<forall>ys \\<in> set xss. xs \\<noteq> ys \\<longrightarrow> set xs \\<inter> set ys = {})\"\n\nlemma distincts_distinct: \"distincts xss \\<Longrightarrow> distinct xss\"\n  by (auto simp: distincts_def)\n\nlemma distincts_Nil[simp]: \"distincts []\"\n  by (simp add: distincts_def)\n\nlemma distincts_single: \"distincts [xs] \\<longleftrightarrow> distinct xs \\<and> xs \\<noteq> []\"\n  by (auto simp add: distincts_def)\n\nlemma distincts_Cons: \"distincts (xs # xss)\n   \\<longleftrightarrow> xs \\<noteq> [] \\<and> distinct xs \\<and> distincts xss \\<and> (set xs \\<inter> (\\<Union>ys \\<in> set xss. set ys)) = {}\" (is \"?L \\<longleftrightarrow> ?R\")\nproof \n  assume ?L then show ?R by (auto simp: distincts_def)\nnext\n  assume ?R\n  then have \"distinct (xs # xss)\"\n    apply (auto simp: disjoint_iff_not_equal distincts_distinct)\n    apply (metis length_greater_0_conv nth_mem)\n    done\n  moreover\n  from \\<open>?R\\<close> have \"\\<forall>xs \\<in> set (xs # xss). distinct xs \\<and> xs \\<noteq> []\"\n    by (auto simp: distincts_def)\n  moreover\n  from \\<open>?R\\<close> have \"\\<forall>xs' \\<in> set (xs # xss). \\<forall>ys \\<in> set (xs # xss). xs' \\<noteq> ys \\<longrightarrow> set xs' \\<inter> set ys = {}\"\n    by (simp add: distincts_def) blast\n  ultimately show ?L unfolding distincts_def by (intro conjI)\nqed\n\nlemma distincts_Cons': \"distincts (xs # xss)\n   \\<longleftrightarrow> xs \\<noteq> [] \\<and> distinct xs \\<and> distincts xss \\<and> (\\<forall>ys \\<in> set xss. set xs \\<inter> set ys = {})\" (is \"?L \\<longleftrightarrow> ?R\")\n unfolding distincts_Cons by blast\n\nlemma distincts_rev:\n  \"distincts (map rev xss) \\<longleftrightarrow> distincts xss\"\n  by (simp add: distincts_def distinct_map)\n\nlemma length_distincts:\n  assumes \"distincts xss\"\n  shows \"length xss = card (set ` set xss)\"\n  using assms\nproof (induct xss)\n  case Nil then show ?case by simp\nnext\n  case (Cons xs xss)\n  then have \"set xs \\<notin> set ` set xss\"\n    using equals0I[of \"set xs\"] by (auto simp: distincts_Cons disjoint_iff_not_equal )\n  with Cons show ?case by (auto simp add: distincts_Cons)\nqed\n\nlemma distincts_remove1: \"distincts xss \\<Longrightarrow> distincts (remove1 xs xss)\"\n  by (auto simp: distincts_def)\n\nlemma distinct_Cons_remove1:\n  \"x \\<in> set xs \\<Longrightarrow> distinct (x # remove1 x xs) = distinct xs\"\n  by (induct xs) auto\n\nlemma set_Cons_remove1:\n  \"x \\<in> set xs \\<Longrightarrow> set (x # remove1 x xs) = set xs\"\n  by (induct xs) auto\n\nlemma distincts_Cons_remove1:\n  \"xs \\<in> set xss \\<Longrightarrow> distincts (xs # remove1 xs xss) = distincts xss\"\n  by (simp only: distinct_Cons_remove1 set_Cons_remove1 distincts_def)\n\nlemma distincts_inj_on_set:\n  assumes \"distincts xss\" shows \"inj_on set (set xss)\"\n  by (rule inj_onI) (metis assms distincts_def inf.idem set_empty)\n\nlemma distincts_distinct_set:\n  assumes \"distincts xss\" shows \"distinct (map set xss)\"\n  using assms by (auto simp: distinct_map distincts_distinct distincts_inj_on_set)\n\nlemma distincts_distinct_nth:\n  assumes \"distincts xss\" \"n < length xss\" shows \"distinct (xss ! n)\"\n  using assms by (auto simp: distincts_def)\n\nlemma lists_succ_not_in:\n  assumes \"x \\<notin> (\\<Union>xs\\<in>set xss. set xs)\" shows \"lists_succ xss x = x\"\n  using assms by (induct xss) (auto simp: list_succ_not_in)\n\nlemma lists_succ_in_conv:\n  \"lists_succ xss x \\<in> (\\<Union>xs\\<in>set xss. set xs) \\<longleftrightarrow> x \\<in> (\\<Union>xs\\<in>set xss. set xs)\"\n  by (induct xss) (auto simp: list_succ_in_conv lists_succ_not_in list_succ_not_in)\n\nlemma lists_succ_in_conv1:\n  assumes \"A \\<inter> (\\<Union>xs\\<in>set xss. set xs) = {}\"\n  shows \"lists_succ xss x \\<in> A \\<longleftrightarrow> x \\<in> A\"\n  by (metis Int_iff assms emptyE lists_succ_in_conv lists_succ_not_in)\n\nlemma lists_succ_Cons_pf: \"lists_succ (xs # xss) = list_succ xs o lists_succ xss\"\n  by auto\n\nlemma lists_succ_Nil_pf: \"lists_succ [] = id\"\n  by (simp add: fun_eq_iff)\n\nlemmas lists_succ_simps_pf = lists_succ_Cons_pf lists_succ_Nil_pf\n\nlemma lists_succ_permutes:\n  assumes \"distincts xss\"\n  shows \"lists_succ xss permutes (\\<Union>xs \\<in> set xss. set xs)\"\n  using assms\nproof (induction xss)\n  case Nil then show ?case by auto\nnext\n  case (Cons xs xss)\n  have \"list_succ xs permutes (set xs)\"\n    using Cons by (intro list_succ_permutes) (simp add: distincts_def in_set_member)\n  moreover\n  have \"lists_succ xss permutes (\\<Union>ys \\<in> set xss. set ys)\"\n    using Cons by (auto simp: Cons distincts_def)\n  ultimately show \"lists_succ (xs # xss) permutes (\\<Union>ys \\<in> set (xs # xss). set ys)\"\n    using Cons by (auto simp: lists_succ_Cons_pf intro: permutes_compose permutes_subset)\nqed\n\nlemma bij_lists_succ: \"distincts xss \\<Longrightarrow> bij (lists_succ xss)\"\n  by (induct xss) (auto simp: lists_succ_simps_pf bij_comp bij_list_succ distincts_Cons)\n\nlemma lists_succ_snoc: \"lists_succ (xss @ [xs]) = lists_succ xss o list_succ xs\"\n  by (induct xss) auto\n\nlemma inv_lists_succ_eq:\n  assumes \"distincts xss\"\n  shows \"inv (lists_succ xss) = lists_succ (rev (map rev xss))\"\nproof -\n  have *: \"\\<And>f g. inv (\\<lambda>b. f (g b)) = inv (f o g)\" by (simp add: o_def)\n  have **: \"lists_succ [] = id\" by auto\n  show ?thesis\n    using assms by (induct xss) (auto simp: * ** lists_succ_snoc lists_succ_Cons_pf o_inv_distrib\n      inv_list_succ_eq distincts_Cons bij_list_succ bij_lists_succ)\nqed\n\nlemma lists_succ_remove1:\n  assumes \"distincts xss\" \"xs \\<in> set xss\"\n  shows \"lists_succ (xs # remove1 xs xss) = lists_succ xss\"\n  using assms\nproof (induct xss)\n  case Nil then show ?case by simp\nnext\n  case (Cons ys xss)\n  show ?case\n  proof cases\n    assume \"xs = ys\" then show ?case by simp\n  next\n    assume \"xs \\<noteq> ys\"\n    with Cons.prems have inter: \"set xs \\<inter> set ys = {}\" and \"xs \\<in> set xss\"\n      by (auto simp: distincts_Cons)\n    have dists:\n        \"distincts (xs # remove1 xs xss)\"\n        \"distincts (xs # ys # remove1 xs xss)\"\n      using \\<open>distincts (ys # xss)\\<close> \\<open>xs \\<in> set xss\\<close> by (auto simp: distincts_def)\n\n    have \"list_succ xs \\<circ> (list_succ ys \\<circ> lists_succ (remove1 xs xss))\n        = list_succ ys \\<circ> (list_succ xs \\<circ> lists_succ (remove1 xs xss))\"\n      using inter unfolding fun_eq_iff comp_def\n      by (subst list_succ_commute) auto\n    also have \"\\<dots> = list_succ ys o (lists_succ (xs # remove1 xs xss))\"\n      using dists by (simp add: lists_succ_Cons_pf distincts_Cons)\n    also have \"\\<dots> = list_succ ys o lists_succ xss\"\n      using \\<open>xs \\<in> set xss\\<close> \\<open>distincts (ys # xss)\\<close>\n      by (simp add: distincts_Cons Cons.hyps)\n    finally\n    show \"lists_succ (xs # remove1 xs (ys # xss)) = lists_succ (ys # xss)\"\n      using Cons dists by (auto simp: lists_succ_Cons_pf distincts_Cons)\n  qed\nqed\n\nlemma lists_succ_no_order:\n  assumes \"distincts xss\" \"distincts yss\" \"set xss = set yss\"\n  shows \"lists_succ xss = lists_succ yss\"\n  using assms\nproof (induct xss arbitrary: yss)\n  case Nil then show ?case by simp\nnext\n  case (Cons xs xss)\n  have \"xs \\<notin> set xss\" \"xs \\<in> set yss\" using Cons.prems\n    by (auto dest: distincts_distinct)\n  have \"lists_succ xss = lists_succ (remove1 xs yss)\"\n    using Cons.prems \\<open>xs \\<notin> _\\<close>\n    by (intro Cons.hyps) (auto simp add: distincts_Cons distincts_remove1 distincts_distinct)\n  then have \"lists_succ (xs # xss) = lists_succ (xs # remove1 xs yss)\"\n    using Cons.prems \\<open>xs \\<in> _\\<close>\n    by (simp add: lists_succ_Cons_pf distincts_Cons_remove1)\n  then show ?case\n    using Cons.prems \\<open>xs \\<in> _\\<close> by (simp add: lists_succ_remove1)\nqed\n\n\n\nsection \\<open>List Orbits\\<close>\n\ntext \\<open>Computes the orbit of @{term x} under @{term f}\\<close>\ndefinition orbit_list :: \"('a \\<Rightarrow> 'a) \\<Rightarrow> 'a \\<Rightarrow> 'a list\" where\n  \"orbit_list f x \\<equiv> iterate 0 (funpow_dist1 f x x) f x\"\n\npartial_function (tailrec)\n  orbit_list_impl :: \"('a \\<Rightarrow> 'a) \\<Rightarrow> 'a \\<Rightarrow> 'a list \\<Rightarrow> 'a \\<Rightarrow> 'a list\"\nwhere\n  \"orbit_list_impl f s acc x = (let x' = f x in if x' = s then rev (x # acc) else orbit_list_impl f s (x # acc) x')\"\n\ncontext notes [simp] = length_fold_remove1_le begin\ntext \\<open>Computes the list of orbits\\<close>\nfun orbits_list :: \"('a \\<Rightarrow> 'a) \\<Rightarrow> 'a list \\<Rightarrow> 'a list list\" where\n  \"orbits_list f [] = []\"\n| \"orbits_list f (x # xs) =\n     orbit_list f x # orbits_list f (fold remove1 (orbit_list f x) xs)\"\n\nfun orbits_list_impl :: \"('a \\<Rightarrow> 'a) \\<Rightarrow> 'a list \\<Rightarrow> 'a list list\" where\n  \"orbits_list_impl f [] = []\"\n| \"orbits_list_impl f (x # xs) =\n     (let fc = orbit_list_impl f x [] x in fc # orbits_list_impl f (fold remove1 fc xs))\"\n\ndeclare orbit_list_impl.simps[code]\nend\n\nabbreviation sset :: \"'a list list \\<Rightarrow> 'a set set\" where\n  \"sset xss \\<equiv> set ` set xss\"\n\nlemma iterate_funpow_step:\n  assumes \"f x \\<noteq> y\" \"y \\<in> orbit f x\"\n  shows \"iterate 0 (funpow_dist1 f x y) f x = x # iterate 0 (funpow_dist1 f (f x) y) f (f x)\"\nproof -\n  from assms have A: \"y \\<in> orbit f (f x)\" by (simp add: orbit_step)\n  have \"iterate 0 (funpow_dist1 f x y) f x = x # iterate 1 (funpow_dist1 f x y) f x\" (is \"_ = _ # ?it\")\n    unfolding iterate_def by (rewrite in \"\\<hole> = _\" upt_conv_Cons) auto\n  also have \"?it = map (\\<lambda>n. (f ^^ n) x) (map Suc [0..<funpow_dist f (f x) y])\"\n    unfolding iterate_def map_Suc_upt by simp\n  also have \"\\<dots> = map (\\<lambda>n. (f ^^ n) (f x)) [0..<funpow_dist f (f x) y]\"\n    by (simp add: funpow_swap1)\n  also have \"\\<dots> = iterate 0 (funpow_dist1 f (f x) y) f (f x)\"\n    unfolding iterate_def\n    unfolding iterate_def by (simp add: funpow_dist_step[OF assms(1) A])\n  finally show ?thesis .\nqed\n\nlemma orbit_list_impl_conv:\n  assumes \"y \\<in> orbit f x\"\n  shows \"orbit_list_impl f y acc x = rev acc @ iterate 0 (funpow_dist1 f x y) f x\"\n  using assms\nproof (induct n\\<equiv>\"funpow_dist1 f x y\" arbitrary: x acc)\n  case (Suc x)\n\n  show ?case\n  proof cases\n    assume \"f x = y\"\n    then show ?thesis by (subst orbit_list_impl.simps) (simp add: Let_def iterate_def funpow_dist_0)\n  next\n    assume not_y :\"f x \\<noteq> y\"\n\n    have y_in_succ: \"y \\<in> orbit f (f x)\"\n      by (intro orbit_step Suc.prems not_y)\n\n    have \"orbit_list_impl f y acc x = orbit_list_impl f y (x # acc) (f x)\"\n      using not_y by (subst orbit_list_impl.simps) simp\n    also have \"\\<dots> = rev (x # acc) @ iterate 0 (funpow_dist1 f (f x) y) f (f x)\" (is \"_ = ?rev @ ?it\")\n      by (intro Suc funpow_dist_step not_y y_in_succ)\n    also have \"\\<dots> = rev acc @ iterate 0 (funpow_dist1 f x y) f x\"\n      using not_y Suc.prems by (simp add: iterate_funpow_step)\n    finally show ?thesis .\n  qed\nqed\n\nlemma orbit_list_conv_impl:\n  assumes \"x \\<in> orbit f x\"\n  shows \"orbit_list f x = orbit_list_impl f x [] x\"\n  unfolding orbit_list_impl_conv[OF assms] orbit_list_def by simp\n\n\nlemma set_orbit_list:\n  assumes \"x \\<in> orbit f x\"\n  shows \"set (orbit_list f x) = orbit f x\"\n  by (simp add: orbit_list_def orbit_conv_funpow_dist1[OF assms] set_iterate)\n\nlemma set_orbit_list':\n  assumes \"permutation f\" shows \"set (orbit_list f x) = orbit f x\"\n  using assms by (simp add: permutation_self_in_orbit set_orbit_list)\n\nlemma distinct_orbit_list:\n  assumes \"x \\<in> orbit f x\"\n  shows \"distinct (orbit_list f x)\"\n  by (simp del: upt_Suc add: orbit_list_def iterate_def distinct_map inj_on_funpow_dist1[OF assms])\n\nlemma distinct_orbit_list':\n  assumes \"permutation f\" shows \"distinct (orbit_list f x)\"\n  using assms by (simp add: permutation_self_in_orbit distinct_orbit_list)\n\nlemma orbits_list_conv_impl:\n  assumes \"permutation f\"\n  shows \"orbits_list f xs = orbits_list_impl f xs\"\nproof (induct \"length xs\" arbitrary: xs rule: less_induct)\n  case less show ?case\n    using assms by (cases xs) (auto simp: assms less less_Suc_eq_le length_fold_remove1_le\n      orbit_list_conv_impl permutation_self_in_orbit Let_def)\nqed\n\nlemma orbit_list_not_nil[simp]: \"orbit_list f x \\<noteq> []\"\n  by (simp add: orbit_list_def)\n\nlemma sset_orbits_list:\n  assumes \"permutation f\" shows \"sset (orbits_list f xs) = (orbit f) ` set xs\"\nproof (induct \"length xs\" arbitrary: xs rule: less_induct)\n  case less\n  show ?case\n  proof (cases xs)\n    case Nil then show ?thesis by simp\n  next\n    case (Cons x' xs')\n    let ?xs'' = \"fold remove1 (orbit_list f x') xs'\"\n    have A: \"sset (orbits_list f ?xs'') = orbit f ` set ?xs''\"\n      using Cons by (simp add: less_Suc_eq_le length_fold_remove1_le less.hyps)\n    have B: \"set (orbit_list f x') = orbit f x'\"\n      by (rule set_orbit_list) (simp add: permutation_self_in_orbit assms)\n\n    have \"orbit f ` set (fold remove1 (orbit_list f x') xs') \\<subseteq> orbit f ` set xs'\"\n      using set_fold_remove1[of _ xs'] by auto\n    moreover\n    have \"orbit f ` set xs' - {orbit f x'} \\<subseteq> (orbit f ` set (fold remove1 (orbit_list f x') xs'))\" (is \"?L \\<subseteq> ?R\")\n    proof\n      fix A assume \"A \\<in> ?L\"\n      then obtain y where \"A = orbit f y\" \"y \\<in> set xs'\" by auto\n      have \"A \\<noteq> orbit f x'\" using \\<open>A \\<in> ?L\\<close> by auto\n      from \\<open>A = _\\<close> \\<open>A \\<noteq> _\\<close> have \"y \\<notin> orbit f x'\"\n        by (meson assms cyclic_on_orbit orbit_cyclic_eq3 permutation_permutes)\n      with \\<open>y \\<in> _\\<close> have \"y \\<in> set (fold remove1 (orbit_list f x') xs')\"\n        by (auto simp: set_fold_remove1' set_orbit_list permutation_self_in_orbit assms)\n      then show \"A \\<in> ?R\" using \\<open>A = _\\<close> by auto\n    qed\n    ultimately\n    show ?thesis by (auto simp: A B Cons)\n  qed\nqed\n\n\n\nsubsection \\<open>Relation to @{term cyclic_on}\\<close>\n\nlemma list_succ_orbit_list:\n  assumes \"s \\<in> orbit f s\" \"\\<And>x. x \\<notin> orbit f s \\<Longrightarrow> f x = x\"\n  shows \"list_succ (orbit_list f s) = f\"\nproof -\n  have \"distinct (orbit_list f s)\" \"\\<And>x. x \\<notin> set (orbit_list f s) \\<Longrightarrow> x = f x\"\n    using assms by (simp_all add: distinct_orbit_list set_orbit_list)\n  moreover\n  have \"\\<And>i. i < length (orbit_list f s) \\<Longrightarrow> orbit_list f s ! (Suc i mod length (orbit_list f s)) = f (orbit_list f s ! i)\"\n    using funpow_dist1_prop[OF \\<open>s \\<in> orbit f s\\<close>] by (auto simp: orbit_list_def funpow_mod_eq)\n  ultimately show ?thesis\n    by (auto simp: list_succ_def fun_eq_iff)\nqed\n\nlemma list_succ_funpow_conv:\n  assumes A: \"distinct xs\" \"x \\<in> set xs\"\n  shows \"(list_succ xs ^^ n) x = xs ! ((index xs x + n) mod length xs)\"\nproof -\n  have \"xs \\<noteq> []\" using assms by auto\n  then show ?thesis\n    by (induct n) (auto simp: hd_conv_nth A index_nth_id list_succ_def mod_simps)\nqed\n\nlemma orbit_list_succ:\n  assumes \"distinct xs\" \"x \\<in> set xs\"\n  shows \"orbit (list_succ xs) x = set xs\"\nproof (intro set_eqI iffI)\n  fix y assume \"y \\<in> orbit (list_succ xs) x\"\n  then show \"y \\<in> set xs\"\n    by induct (auto simp: list_succ_in_conv \\<open>x \\<in> set xs\\<close>)\nnext\n  fix y assume \"y \\<in> set xs\"\n  moreover\n  { fix i j have \"i < length xs \\<Longrightarrow> j < length xs \\<Longrightarrow> \\<exists>n. xs ! j = xs ! ((i + n) mod length xs)\"\n      using assms by (auto simp: exI[where x=\"j + (length xs - i)\"])\n  }\n  ultimately\n  show \"y \\<in> orbit (list_succ xs) x\"\n    using assms by (auto simp: orbit_altdef_permutation permutation_list_succ list_succ_funpow_conv index_nth_id in_set_conv_nth)\nqed\n\nlemma cyclic_on_list_succ:\n  assumes \"distinct xs\" \"xs \\<noteq> []\" shows \"cyclic_on (list_succ xs) (set xs)\"\n  using assms last_in_set by (auto simp: cyclic_on_def orbit_list_succ)\n\nlemma obtain_orbit_list_func:\n  assumes \"s \\<in> orbit f s\" \"\\<And>x. x \\<notin> orbit f s \\<Longrightarrow> f x = x\"\n  obtains xs where \"f = list_succ xs\" \"set xs = orbit f s\" \"distinct xs\" \"hd xs = s\"\nproof -\n  { from assms have \"f = list_succ (orbit_list f s)\" by (simp add: list_succ_orbit_list)\n    moreover\n    have \"set (orbit_list f s) = orbit f s\" \"distinct (orbit_list f s)\"\n      by (auto simp: set_orbit_list distinct_orbit_list assms)\n    moreover have \"hd (orbit_list f s) = s\"\n      by (simp add: orbit_list_def iterate_def hd_map del: upt_Suc)\n    ultimately have \"\\<exists>xs. f = list_succ xs \\<and> set xs = orbit f s \\<and> distinct xs \\<and> hd xs = s\" by blast\n  } then show ?thesis by (metis that)\nqed\n\nlemma cyclic_on_obtain_list_succ:\n  assumes \"cyclic_on f S\" \"\\<And>x. x \\<notin> S \\<Longrightarrow> f x = x\"\n  obtains xs where \"f = list_succ xs\" \"set xs = S\" \"distinct xs\"\nproof -\n  from assms obtain s where s: \"s \\<in> orbit f s\" \"\\<And>x. x \\<notin> orbit f s \\<Longrightarrow> f x = x\"  \"S = orbit f s\"\n    by (auto simp: cyclic_on_def)\n  then show ?thesis by (metis that obtain_orbit_list_func)\nqed\n\nlemma cyclic_on_obtain_list_succ':\n  assumes \"cyclic_on f S\" \"f permutes S\"\n  obtains xs where \"f = list_succ xs\" \"set xs = S\" \"distinct xs\"\n  using assms unfolding permutes_def by (metis cyclic_on_obtain_list_succ)\n\nlemma list_succ_unique:\n  assumes \"s \\<in> orbit f s\" \"\\<And>x. x \\<notin> orbit f s \\<Longrightarrow> f x = x\"\n  shows \"\\<exists>!xs. f = list_succ xs \\<and> distinct xs \\<and> hd xs = s \\<and> set xs = orbit f s\"\nproof -\n  from assms obtain xs where xs: \"f = list_succ xs\" \"distinct xs\" \"hd xs = s\" \"set xs = orbit f s\" \n    by (rule obtain_orbit_list_func)\n  moreover\n  { fix zs\n    assume A: \"f = list_succ zs\" \"distinct zs\" \"hd zs = s\" \"set zs = orbit f s\"\n    then have \"zs \\<noteq> []\" using \\<open>s \\<in> orbit f s\\<close> by auto\n    from \\<open>distinct xs\\<close> \\<open>distinct zs\\<close> \\<open>set xs = orbit f s\\<close> \\<open>set zs = orbit f s\\<close>\n    have len: \"length xs = length zs\" by (metis distinct_card)\n\n    { fix n assume \"n < length xs\"\n      then have \"zs ! n = xs ! n\"\n      proof (induct n)\n        case 0 with A xs \\<open>zs \\<noteq> []\\<close> show ?case by (simp add: hd_conv_nth nth_rotate_conv_nth)\n      next\n        case (Suc n)\n        then have \"list_succ zs (zs ! n) = list_succ xs (xs! n)\"\n          using \\<open>f = list_succ xs\\<close> \\<open>f = list_succ zs\\<close> by simp\n        with \\<open>Suc n < _\\<close> show ?case\n          by (simp add:list_succ_nth len \\<open>distinct xs\\<close> \\<open>distinct zs\\<close>)\n      qed }\n    then have \"zs = xs\" by (metis len nth_equalityI) }\n  ultimately show ?thesis by metis\nqed\n\nlemma distincts_orbits_list:\n  assumes \"distinct as\" \"permutation f\"\n  shows \"distincts (orbits_list f as)\"\n  using assms(1)\nproof (induct \"length as\" arbitrary: as rule: less_induct)\n  case less\n  show ?case\n  proof (cases as)\n    case Nil then show ?thesis by simp\n  next\n    case (Cons a as')\n    let ?as' = \"fold remove1 (orbit_list f a) as'\"\n    from Cons less.prems have A: \"distincts (orbits_list f (fold remove1 (orbit_list f a) as'))\"\n      by (intro less) (auto simp: distinct_fold_remove1 length_fold_remove1_le less_Suc_eq_le)\n\n    have B: \"set (orbit_list f a) \\<inter> \\<Union>(sset (orbits_list f (fold remove1 (orbit_list f a) as'))) = {}\"\n    proof -\n      have \"orbit f a \\<inter> set (fold remove1 (orbit_list f a) as') = {}\"\n        using assms less.prems Cons by (simp add: set_fold_remove1_distinct set_orbit_list')\n      then have \"orbit f a \\<inter> \\<Union> (orbit f ` set (fold remove1 (orbit_list f a) as')) = {}\"\n        by auto (metis assms(2) cyclic_on_orbit disjoint_iff_not_equal permutation_self_in_orbit[OF assms(2)] orbit_cyclic_eq3 permutation_permutes)\n      then show ?thesis using assms\n      by (auto simp: set_orbit_list' sset_orbits_list disjoint_iff_not_equal)\n    qed\n    show ?thesis\n      using A B assms by (auto simp: distincts_Cons Cons distinct_orbit_list')\n  qed\nqed\n\nlemma cyclic_on_lists_succ':\n  assumes \"distincts xss\"\n  shows \"A \\<in> sset xss \\<Longrightarrow> cyclic_on (lists_succ xss) A\"\n  using assms\nproof (induction xss arbitrary: A)\n  case Nil then show ?case by auto\nnext\n  case (Cons xs xss A)\n  then have inter: \"set xs \\<inter> (\\<Union>ys\\<in>set xss. set ys) = {}\" by (auto simp: distincts_Cons)\n\n  note pcp[OF _ _ inter] = permutes_comp_preserves_cyclic1 permutes_comp_preserves_cyclic2\n  from Cons show \"cyclic_on (lists_succ (xs # xss)) A\"\n    by (cases \"A = set xs\")\n      (auto intro: pcp simp: cyclic_on_list_succ list_succ_permutes\n        lists_succ_permutes lists_succ_Cons_pf distincts_Cons)\nqed\n\nlemma cyclic_on_lists_succ:\n  assumes \"distincts xss\"\n  shows \"\\<And>xs. xs \\<in> set xss \\<Longrightarrow> cyclic_on (lists_succ xss) (set xs)\"\n  using assms by (auto intro: cyclic_on_lists_succ')\n\nlemma permutes_as_lists_succ:\n  assumes \"distincts xss\"\n  assumes ls_eq: \"\\<And>xs. xs \\<in> set xss \\<Longrightarrow> list_succ xs = perm_restrict f (set xs)\"\n  assumes \"f permutes (\\<Union>(sset xss))\"\n  shows \"f = lists_succ xss\"\n  using assms\nproof (induct xss arbitrary: f)\n  case Nil then show ?case by simp\nnext\n  case (Cons xs xss)\n  let ?sets = \"\\<lambda>xss. \\<Union>ys \\<in> set xss. set ys\"\n\n  have xs: \"distinct xs\" \"xs \\<noteq> []\" using Cons by (auto simp: distincts_Cons)\n\n  have f_xs: \"perm_restrict f (set xs) = list_succ xs\"\n    using Cons by simp\n\n  have co_xs: \"cyclic_on (perm_restrict f (set xs)) (set xs)\"\n    unfolding f_xs using xs by (rule cyclic_on_list_succ)\n\n  have perm_xs: \"perm_restrict f (set xs) permutes set xs\"\n    unfolding f_xs using \\<open>distinct xs\\<close> by (rule list_succ_permutes)\n\n  have perm_xss: \"perm_restrict f (?sets xss) permutes (?sets xss)\"\n  proof -\n    have \"perm_restrict f (?sets (xs # xss) - set xs) permutes (?sets (xs # xss) - set xs)\"\n      using Cons co_xs by (intro perm_restrict_diff_cyclic) (auto simp: cyclic_on_perm_restrict)\n    also have \"?sets (xs # xss) - set xs = ?sets xss\"\n      using Cons by (auto simp: distincts_Cons)\n    finally show ?thesis .\n  qed\n\n  have f_xss: \"perm_restrict f (?sets xss) = lists_succ xss\"\n  proof -\n    have *: \"\\<And>xs. xs \\<in> set xss \\<Longrightarrow> ((\\<Union>x\\<in>set xss. set x) \\<inter> set xs) = set xs\"\n      by blast\n    with perm_xss Cons.prems show ?thesis\n      by (intro Cons.hyps) (auto simp: distincts_Cons perm_restrict_perm_restrict *)\n  qed\n\n  from Cons.prems show \"f = lists_succ (xs # xss)\"\n    by (simp add: lists_succ_Cons_pf distincts_Cons f_xss[symmetric]\n      perm_restrict_union perm_xs perm_xss)\nqed\n\nlemma cyclic_on_obtain_lists_succ:\n  assumes\n    permutes: \"f permutes S\" and\n    S: \"S = \\<Union>(sset css)\" and\n    dists: \"distincts css\" and\n    cyclic: \"\\<And>cs. cs \\<in> set css \\<Longrightarrow> cyclic_on f (set cs)\"\n  obtains xss where \"f = lists_succ xss\" \"distincts xss\" \"map set xss = map set css\" \"map hd xss = map hd css\"\nproof -\n  let ?fc = \"\\<lambda>cs. perm_restrict f (set cs)\"\n  define some_list where \"some_list cs = (SOME xs. ?fc cs = list_succ xs \\<and> set xs = set cs \\<and> distinct xs \\<and> hd xs = hd cs)\" for cs\n  { fix cs assume \"cs \\<in> set css\"\n    then have \"cyclic_on (?fc cs) (set cs)\" \"\\<And>x. x \\<notin> set cs \\<Longrightarrow> ?fc cs x = x\" \"hd cs \\<in> set cs\"\n      using cyclic dists by (auto simp add: cyclic_on_perm_restrict perm_restrict_def distincts_def)\n    then have \"hd cs \\<in> orbit (?fc cs) (hd cs)\"  \"\\<And>x. x \\<notin> orbit (?fc cs) (hd cs) \\<Longrightarrow> ?fc cs x = x\" \"hd cs \\<in> set cs\" \"set cs = orbit (?fc cs) (hd cs)\"\n      by (auto simp: cyclic_on_alldef)\n    then have \"\\<exists>xs. ?fc cs = list_succ xs \\<and> set xs = set cs \\<and> distinct xs \\<and> hd xs = hd cs\"\n      by (metis obtain_orbit_list_func)\n    then have \"?fc cs = list_succ (some_list cs) \\<and> set (some_list cs) = set cs \\<and> distinct (some_list cs) \\<and> hd (some_list cs) = hd cs\"\n      unfolding some_list_def by (rule someI_ex)\n    then have \"?fc cs = list_succ (some_list cs)\" \"set (some_list cs) = set cs\" \"distinct (some_list cs)\" \"hd (some_list cs) = hd cs\"\n      by auto\n  } note sl_cs  = this\n\n  have \"\\<And>cs. cs \\<in> set css \\<Longrightarrow> cs \\<noteq> []\" using dists by (auto simp: distincts_def)\n  then have some_list_ne: \"\\<And>cs. cs \\<in> set css \\<Longrightarrow> some_list cs \\<noteq> []\"\n    by (metis set_empty sl_cs(2))\n\n  have set: \"map set (map some_list css) = map set css\" \"map hd (map some_list css) = map hd css\"\n    using sl_cs(2,4) by (auto simp add: map_idI)\n\n  have distincts: \"distincts (map some_list css)\"\n  proof -\n    have c_dist: \"\\<And>xs ys. \\<lbrakk>xs\\<in>set css; ys\\<in>set css; xs \\<noteq> ys\\<rbrakk> \\<Longrightarrow> set xs \\<inter> set ys = {}\"\n      using dists by (auto simp: distincts_def)\n\n    have \"distinct (map some_list css)\"\n    proof -\n      have \"inj_on some_list (set css)\"\n        using sl_cs(2) c_dist by (intro inj_onI) (metis inf.idem set_empty) \n      with \\<open>distincts css\\<close> show ?thesis\n        by (auto simp: distincts_distinct distinct_map)\n    qed\n    moreover\n    have \"\\<forall>xs\\<in>set (map some_list css). distinct xs \\<and> xs \\<noteq> []\"\n      using sl_cs(3) some_list_ne by auto\n    moreover\n    from c_dist have \"(\\<forall>xs\\<in>set (map some_list css). \\<forall>ys\\<in>set (map some_list css). xs \\<noteq> ys \\<longrightarrow> set xs \\<inter> set ys = {})\"\n      using sl_cs(2) by auto\n    ultimately\n    show ?thesis by (simp add: distincts_def)\n  qed\n\n  have f: \"f = lists_succ (map some_list css)\"\n    using distincts\n  proof (rule permutes_as_lists_succ)\n    fix xs assume \"xs \\<in> set (map some_list css)\"\n    then show \"list_succ xs = perm_restrict f (set xs)\"\n      using sl_cs(1) sl_cs(2) by auto\n  next\n    have \"S = (\\<Union>xs\\<in>set (map some_list css). set xs)\"\n      using S sl_cs(2) by auto\n    with permutes show \"f permutes \\<Union>(sset (map some_list css))\"\n      by simp\n  qed\n\n  from f distincts set  show ?thesis ..\nqed\n\n\nsubsection \\<open>Permutations of a List\\<close>\n\nlemma length_remove1_less:\n  assumes \"x \\<in> set xs\" shows \"length (remove1 x xs) < length xs\"\nproof -\n  from assms have \"0 < length xs\" by auto\n  with assms show ?thesis by (auto simp: length_remove1)\nqed\ncontext notes [simp] = length_remove1_less begin\nfun permutations :: \"'a list \\<Rightarrow> 'a list list\" where\n  permutations_Nil: \"permutations [] = [[]]\"\n| permutations_Cons:\n    \"permutations xs = [y # ys. y <- xs, ys <- permutations (remove1 y xs)]\"\nend\n\ndeclare permutations_Cons[simp del]\n\ntext \\<open>\n  The function above returns all permutations of a list. The function below computes\n  only those which yield distinct cyclic permutation functions (cf. @{term list_succ}).\n\\<close>\n\nfun cyc_permutations :: \"'a list \\<Rightarrow> 'a list list\" where\n  \"cyc_permutations [] = [[]]\"\n| \"cyc_permutations (x # xs) = map (Cons x) (permutations xs)\"\n\n\n\nlemma nil_in_permutations[simp]: \"[] \\<in> set (permutations xs) \\<longleftrightarrow> xs = []\"\n  by (induct xs) (auto simp: permutations_Cons)\n\nlemma permutations_not_nil:\n  assumes \"xs \\<noteq> []\"\n  shows \"permutations xs = concat (map (\\<lambda>x. map ((#) x) (permutations (remove1 x xs))) xs)\"\n  using assms by (cases xs) (auto simp: permutations_Cons)\n\nlemma set_permutations_step:\n  assumes \"xs \\<noteq> []\"\n  shows \"set (permutations xs) = (\\<Union>x \\<in> set xs. Cons x ` set (permutations (remove1 x xs)))\"\n  using assms by (cases xs) (auto simp: permutations_Cons)\n\nlemma in_set_permutations:\n  assumes \"distinct xs\"\n  shows \"ys \\<in> set (permutations xs) \\<longleftrightarrow> distinct ys \\<and> set xs = set ys\" (is \"?L xs ys \\<longleftrightarrow> ?R xs ys\")\n  using assms\nproof (induct \"length xs\" arbitrary: xs ys)\n  case 0 then show ?case by auto\nnext\n  case (Suc n)\n  then have \"xs \\<noteq> []\" by auto\n\n  show ?case\n  proof\n    assume \"?L xs ys\"\n    then obtain y ys' where \"ys = y # ys'\" \"y \\<in> set xs\" \"ys' \\<in> set (permutations (remove1 (hd ys) xs))\"\n      using \\<open>xs \\<noteq> []\\<close> by (auto simp: permutations_not_nil)\n    moreover\n    then have \"?R (remove1 y xs) ys'\"\n      using Suc.prems Suc.hyps(2) by (intro Suc.hyps(1)[THEN iffD1]) (auto simp: length_remove1)\n    ultimately show \"?R xs ys\"\n      using Suc by auto\n  next\n    assume \"?R xs ys\"\n    with \\<open>xs \\<noteq> []\\<close> obtain y ys' where \"ys = y # ys'\" \"y \\<in> set xs\" by (cases ys) auto\n    moreover\n    then have \"ys' \\<in> set (permutations (remove1 y xs))\"\n      using Suc \\<open>?R xs ys\\<close> by (intro Suc.hyps(1)[THEN iffD2]) (auto simp: length_remove1)\n    ultimately\n    show \"?L xs ys\"\n      using \\<open>xs \\<noteq> []\\<close> by (auto simp: permutations_not_nil)\n  qed\nqed\n\nlemma in_set_cyc_permutations:\n  assumes \"distinct xs\"\n  shows \"ys \\<in> set (cyc_permutations xs) \\<longleftrightarrow> distinct ys \\<and> set xs = set ys \\<and> hd ys = hd xs\" (is \"?L xs ys \\<longleftrightarrow> ?R xs ys\")\nproof (cases xs)\n  case (Cons x xs) with assms show ?thesis\n    by (cases ys) (auto simp: in_set_permutations intro!: imageI)\nqed auto\n\nlemma in_set_cyc_permutations_obtain:\n  assumes \"distinct xs\" \"distinct ys\" \"set xs = set ys\"\n  obtains n where \"rotate n ys \\<in> set (cyc_permutations xs)\"\nproof (cases xs)\n  case Nil with assms have \"rotate 0 ys \\<in> set (cyc_permutations xs)\" by auto\n  then show ?thesis ..\nnext\n  case (Cons x xs')\n  let ?ys' = \"rotate (index ys x) ys\"\n  have \"ys \\<noteq> []\" \"x \\<in> set ys\"\n    using Cons assms by auto\n  then have \"distinct ?ys' \\<and> set xs = set ?ys' \\<and> hd ?ys' = hd xs\"\n    using assms Cons by (auto simp add: hd_rotate_conv_nth)\n  with \\<open>distinct xs\\<close> have \"?ys' \\<in> set (cyc_permutations xs)\"\n    by (rule in_set_cyc_permutations[THEN iffD2])\n  then show ?thesis ..\nqed\n\nlemma list_succ_set_cyc_permutations:\n  assumes \"distinct xs\" \"xs \\<noteq> []\"\n  shows \"list_succ ` set (cyc_permutations xs) = {f. f permutes set xs \\<and> cyclic_on f (set xs)}\" (is \"?L = ?R\")\nproof (intro set_eqI iffI)\n  fix f assume \"f \\<in> ?L\"\n  moreover have \"\\<And>ys. set xs = set ys \\<Longrightarrow> xs \\<noteq> [] \\<Longrightarrow> ys \\<noteq> []\" by auto\n  ultimately show \"f \\<in> ?R\"\n    using assms by (auto simp: in_set_cyc_permutations list_succ_permutes cyclic_on_list_succ)\nnext\n  fix f assume \"f \\<in> ?R\"\n  then obtain ys where ys: \"list_succ ys = f\" \"distinct ys\" \"set ys = set xs\"\n    by (auto elim: cyclic_on_obtain_list_succ')\n  moreover\n  with \\<open>distinct xs\\<close> obtain n where \"rotate n ys \\<in> set (cyc_permutations xs)\"\n    by (auto elim: in_set_cyc_permutations_obtain)\n  then have \"list_succ (rotate n ys) \\<in> ?L\" by simp\n  ultimately\n  show \"f \\<in> ?L\" by simp\nqed\n\n\nsubsection \\<open>Enumerating Permutations from List Orbits\\<close>\n\ndefinition cyc_permutationss :: \"'a list list \\<Rightarrow> 'a list list list\" where\n  \"cyc_permutationss = product_lists o map cyc_permutations\"\n\nlemma cyc_permutationss_Nil[simp]: \"cyc_permutationss [] = [[]]\"\n  by (auto simp: cyc_permutationss_def)\n\nlemma in_set_cyc_permutationss:\n  assumes \"distincts xss\"\n  shows \"yss \\<in> set (cyc_permutationss xss) \\<longleftrightarrow> distincts yss \\<and> map set xss = map set yss \\<and> map hd xss = map hd yss\"\nproof -\n  { assume A: \"list_all2 (\\<lambda>x ys. x \\<in> set ys) yss (map cyc_permutations xss)\"\n    then have \"length yss = length xss\" by (auto simp: list_all2_lengthD)\n    then have \"\\<Union>(sset xss) = \\<Union>(sset yss)\" \"distincts yss\" \"map set xss = map set yss\" \"map hd xss = map hd yss\"\n      using A assms\n      by (induct yss xss rule: list_induct2) (auto simp: distincts_Cons in_set_cyc_permutations)\n  } note X = this\n  { assume A: \"distincts yss\" \"map set xss = map set yss\" \"map hd xss = map hd yss\"\n    then have \"length yss = length xss\" by (auto dest: map_eq_imp_length_eq)\n    then have \"list_all2 (\\<lambda>x ys. x \\<in> set ys) yss (map cyc_permutations xss)\"\n      using A assms\n      by (induct yss xss rule: list_induct2) (auto simp: distincts_Cons in_set_cyc_permutations)\n  } note Y = this\n  show \"?thesis\"\n    unfolding cyc_permutationss_def\n    by (auto simp: product_lists_set intro: X Y)\nqed\n\nlemma lists_succ_set_cyc_permutationss:\n  assumes \"distincts xss\"\n  shows \"lists_succ ` set (cyc_permutationss xss) = {f. f permutes \\<Union>(sset xss) \\<and> (\\<forall>c \\<in> sset xss. cyclic_on f c)}\" (is \"?L = ?R\")\n  using assms\nproof (intro set_eqI iffI)\n  fix f assume \"f \\<in> ?L\"\n  then obtain yss where \"yss \\<in> set (cyc_permutationss xss)\" \"f = lists_succ yss\" by (rule imageE)\n  moreover\n  from \\<open>yss \\<in> _\\<close> assms have \"set (map set xss) = set (map set yss)\"\n    by (auto simp: in_set_cyc_permutationss)\n  then have \"sset xss = sset yss\" by simp\n  ultimately\n  show \"f \\<in> ?R\"\n    using assms\n  by (auto simp: in_set_cyc_permutationss cyclic_on_lists_succ') (metis lists_succ_permutes)\nnext\n  fix f assume \"f \\<in> ?R\"\n  then have \"f permutes \\<Union>(sset xss)\" \"\\<And>cs. cs \\<in> set xss \\<Longrightarrow> cyclic_on f (set cs)\"\n    by auto\n  from this(1) refl assms this(2)\n  obtain yss where \"f = lists_succ yss\" \"distincts yss\" \"map set yss = map set xss\" \"map hd yss = map hd xss\"\n    by (rule cyclic_on_obtain_lists_succ)\n  with assms show \"f \\<in> ?L\" by (auto intro!: imageI simp: in_set_cyc_permutationss)\nqed\n\n\nsubsection \\<open>Lists of Permutations\\<close>\n\ndefinition permutationss :: \"'a list list \\<Rightarrow> 'a list list list\" where\n  \"permutationss = product_lists o map permutations\"\n\nlemma permutationss_Nil[simp]: \"permutationss [] = [[]]\"\n  by (auto simp: permutationss_def)\n\nlemma permutationss_Cons:\n  \"permutationss (xs # xss) = concat (map (\\<lambda>ys. map (Cons ys) (permutationss xss)) (permutations xs))\"\n  by (auto simp: permutationss_def)\n\nlemma in_set_permutationss:\n  assumes \"distincts xss\"\n  shows \"yss \\<in> set (permutationss xss) \\<longleftrightarrow> distincts yss \\<and> map set xss = map set yss\"\nproof -\n  { assume A: \"list_all2 (\\<lambda>x ys. x \\<in> set ys) yss (map permutations xss)\"\n    then have \"length yss = length xss\" by (auto simp: list_all2_lengthD)\n    then have \"\\<Union>(sset xss) = \\<Union>(sset yss)\" \"distincts yss\" \"map set xss = map set yss\"\n      using A assms\n      by (induct yss xss rule: list_induct2) (auto simp: distincts_Cons in_set_permutations)\n  } note X = this\n  { assume A: \"distincts yss\" \"map set xss = map set yss\"\n    then have \"length yss = length xss\" by (auto dest: map_eq_imp_length_eq)\n    then have \"list_all2 (\\<lambda>x ys. x \\<in> set ys) yss (map permutations xss)\"\n      using A assms\n      by (induct yss xss rule: list_induct2) (auto simp: in_set_permutations distincts_Cons)\n  } note Y = this\n  show \"?thesis\"\n    unfolding permutationss_def\n    by (auto simp: product_lists_set intro: X Y)\nqed\n\nlemma set_permutationss:\n  assumes \"distincts xss\"\n  shows \"set (permutationss xss) = {yss. distincts yss \\<and> map set xss = map set yss}\"\n  using in_set_permutationss[OF assms] by blast\n\n\n\nlemma permutations_complete: (* could generalize with multi-sets *)\n  assumes \"distinct xs\" \"distinct ys\" \"set xs = set ys\"\n  shows \"ys \\<in> set (permutations xs)\"\n  using assms\nproof (induct \"length xs\" arbitrary: xs ys)\n  case 0 then show ?case by simp\nnext\n  case (Suc n)\n  from Suc.hyps have \"xs \\<noteq> []\" by auto\n  then obtain y ys' where [simp]: \"ys = y # ys'\" \"y \\<in> set xs\" using Suc.prems by (cases ys) auto\n  have \"ys' \\<in> set (permutations (remove1 y xs))\"\n    using Suc.prems \\<open>Suc n = _\\<close> by (intro Suc.hyps) (simp_all add: length_remove1 )\n  then show ?case using \\<open>xs \\<noteq> []\\<close> by (auto simp: set_permutations_step)\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/Planarity_Certificates/Planarity/Executable_Permutations.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.833324607730178, "lm_q2_score": 0.8705972768020108, "lm_q1q2_score": 0.7254901341819969}}
{"text": "(*\n  File:    Hoeffding.thy\n  Author:  Manuel Eberl, TU M\u00fcnchen\n*)\nsection \\<open>Hoeffding's Lemma and Hoeffding's Inequality\\<close>\ntheory Hoeffding\n  imports Product_PMF Independent_Family\nbegin\n\ntext \\<open>\n  Hoeffding's inequality shows that a sum of bounded independent random variables is concentrated\n  around its mean, with an exponential decay of the tail probabilities.\n\\<close>\n\nsubsection \\<open>Hoeffding's Lemma\\<close>\n\nlemma convex_on_exp: \n  fixes l :: real\n  assumes \"l \\<ge> 0\"\n  shows   \"convex_on UNIV (\\<lambda>x. exp(l*x))\"\n  using assms\n  by (intro convex_on_realI[where f' = \"\\<lambda>x. l * exp (l * x)\"])\n     (auto intro!: derivative_eq_intros mult_left_mono)\n\nlemma mult_const_minus_self_real_le:\n  fixes x :: real\n  shows \"x * (c - x) \\<le> c\\<^sup>2 / 4\"\nproof -\n  have \"x * (c - x) = -(x - c / 2)\\<^sup>2 + c\\<^sup>2 / 4\"\n    by (simp add: field_simps power2_eq_square)\n  also have \"\\<dots> \\<le> 0 + c\\<^sup>2 / 4\"\n    by (intro add_mono) auto\n  finally show ?thesis by simp\nqed\n\nlemma Hoeffdings_lemma_aux:\n  fixes h p :: real\n  assumes \"h \\<ge> 0\" and \"p \\<ge> 0\"\n  defines \"L \\<equiv> (\\<lambda>h. -h * p + ln (1 + p * (exp h - 1)))\"\n  shows   \"L h \\<le> h\\<^sup>2 / 8\"\nproof (cases \"h = 0\")\n  case False\n  hence h: \"h > 0\"\n    using \\<open>h \\<ge> 0\\<close> by simp\n  define L' where \"L' = (\\<lambda>h. -p + p * exp h / (1 + p * (exp h - 1)))\"\n  define L'' where \"L'' = (\\<lambda>h. -(p\\<^sup>2) * exp h * exp h / (1 + p * (exp h - 1))\\<^sup>2 +\n                              p * exp h / (1 + p * (exp h - 1)))\"\n  define Ls where \"Ls = (\\<lambda>n. [L, L', L''] ! n)\"\n\n  have [simp]: \"L 0 = 0\" \"L' 0 = 0\"\n    by (auto simp: L_def L'_def)\n\n  have L': \"(L has_real_derivative L' x) (at x)\" if \"x \\<in> {0..h}\" for x\n  proof -\n    have \"1 + p * (exp x - 1) > 0\"\n      using \\<open>p \\<ge> 0\\<close> that by (intro add_pos_nonneg mult_nonneg_nonneg) auto\n    thus ?thesis\n      unfolding L_def L'_def by (auto intro!: derivative_eq_intros)\n  qed\n\n  have L'': \"(L' has_real_derivative L'' x) (at x)\" if \"x \\<in> {0..h}\" for x\n  proof -\n    have *: \"1 + p * (exp x - 1) > 0\"\n      using \\<open>p \\<ge> 0\\<close> that by (intro add_pos_nonneg mult_nonneg_nonneg) auto\n    show ?thesis\n      unfolding L'_def L''_def\n      by (insert *, (rule derivative_eq_intros refl | simp)+) (auto simp: divide_simps; algebra)\n  qed\n\n  have diff: \"\\<forall>m t. m < 2 \\<and> 0 \\<le> t \\<and> t \\<le> h \\<longrightarrow> (Ls m has_real_derivative Ls (Suc m) t) (at t)\"\n    using L' L'' by (auto simp: Ls_def nth_Cons split: nat.splits)\n  from Taylor[of 2 Ls L 0 h 0 h, OF _ _ diff]\n    obtain t where t: \"t \\<in> {0<..<h}\" \"L h = L'' t * h\\<^sup>2 / 2\"\n      using \\<open>h > 0\\<close> by (auto simp: Ls_def lessThan_nat_numeral)\n  define u where \"u = p * exp t / (1 + p * (exp t - 1))\"\n\n  have \"L'' t = u * (1 - u)\"\n    by (simp add: L''_def u_def divide_simps; algebra)\n  also have \"\\<dots> \\<le> 1 / 4\"\n    using mult_const_minus_self_real_le[of u 1] by simp\n  finally have \"L'' t \\<le> 1 / 4\" .\n\n  note t(2)\n  also have \"L'' t * h\\<^sup>2 / 2 \\<le> (1 / 4) * h\\<^sup>2 / 2\"\n    using \\<open>L'' t \\<le> 1 / 4\\<close> by (intro mult_right_mono divide_right_mono) auto\n  finally show \"L h \\<le> h\\<^sup>2 / 8\" by simp\nqed (auto simp: L_def)\n\n\nlocale interval_bounded_random_variable = prob_space +\n  fixes f :: \"'a \\<Rightarrow> real\" and a b :: real\n  assumes random_variable [measurable]: \"random_variable borel f\"\n  assumes AE_in_interval: \"AE x in M. f x \\<in> {a..b}\"\nbegin\n\nlemma integrable [intro]: \"integrable M f\"\nproof (rule integrable_const_bound)\n  show \"AE x in M. norm (f x) \\<le> max \\<bar>a\\<bar> \\<bar>b\\<bar>\"\n    by (intro eventually_mono[OF AE_in_interval]) auto\nqed (fact random_variable)\n\ntext \\<open>\n  We first show Hoeffding's lemma for distributions whose expectation is 0. The general\n  case will easily follow from this later.\n\\<close>\nlemma Hoeffdings_lemma_nn_integral_0:\n  assumes \"l > 0\" and E0: \"expectation f = 0\"\n  shows   \"nn_integral M (\\<lambda>x. exp (l * f x)) \\<le> ennreal (exp (l\\<^sup>2 * (b - a)\\<^sup>2 / 8))\"\nproof (cases \"AE x in M. f x = 0\")\n  case True\n  hence \"nn_integral M (\\<lambda>x. exp (l * f x)) = nn_integral M (\\<lambda>x. ennreal 1)\"\n    by (intro nn_integral_cong_AE) auto\n  also have \"\\<dots> = ennreal (expectation (\\<lambda>_. 1))\"\n    by (intro nn_integral_eq_integral) auto\n  finally show ?thesis by (simp add: prob_space)\nnext\n  case False\n  have \"a < 0\"\n  proof (rule ccontr)\n    assume a: \"\\<not>(a < 0)\"\n    have \"AE x in M. f x = 0\"\n    proof (subst integral_nonneg_eq_0_iff_AE [symmetric])\n      show \"AE x in M. f x \\<ge> 0\"\n        using AE_in_interval by eventually_elim (use a in auto)\n    qed (use E0 in \\<open>auto simp: id_def integrable\\<close>)\n    with False show False by contradiction\n  qed\n\n  have \"b > 0\"\n  proof (rule ccontr)\n    assume b: \"\\<not>(b > 0)\"\n    have \"AE x in M. -f x = 0\"\n    proof (subst integral_nonneg_eq_0_iff_AE [symmetric])\n      show \"AE x in M. -f x \\<ge> 0\"\n        using AE_in_interval by eventually_elim (use b in auto)\n    qed (use E0 in \\<open>auto simp: id_def integrable\\<close>)\n    with False show False by simp\n  qed\n    \n  have \"a < b\"\n    using \\<open>a < 0\\<close> \\<open>b > 0\\<close> by linarith\n\n  define p where \"p = -a / (b - a)\"\n  define L where \"L = (\\<lambda>t. -t* p + ln (1 - p + p * exp t))\"\n  define z where \"z = l * (b - a)\"\n  have \"z > 0\"\n    unfolding z_def using \\<open>a < b\\<close> \\<open>l > 0\\<close> by auto\n  have \"p > 0\"\n    using \\<open>a < 0\\<close> \\<open>a < b\\<close> unfolding p_def by (intro divide_pos_pos) auto\n\n  have \"(\\<integral>\\<^sup>+x. exp (l * f x) \\<partial>M) \\<le>\n        (\\<integral>\\<^sup>+x. (b - f x) / (b - a) * exp (l * a) + (f x - a) / (b - a) * exp (l * b) \\<partial>M)\"\n  proof (intro nn_integral_mono_AE eventually_mono[OF AE_in_interval] ennreal_leI)\n    fix x assume x: \"f x \\<in> {a..b}\"\n    define y where \"y = (b - f x) / (b-a)\"\n    have y: \"y \\<in> {0..1}\"\n      using x \\<open>a < b\\<close> by (auto simp: y_def)\n    have conv: \"convex_on UNIV (\\<lambda>x. exp(l*x))\"\n      using \\<open>l > 0\\<close> by (intro convex_on_exp) auto\n    have \"exp (l * ((1 - y) *\\<^sub>R b + y *\\<^sub>R a)) \\<le> (1 - y) * exp (l * b) + y * exp (l * a)\"\n      using y \\<open>l > 0\\<close> by (intro convex_onD[OF convex_on_exp]) auto\n    also have \"(1 - y) *\\<^sub>R b + y *\\<^sub>R a = f x\"\n      using \\<open>a < b\\<close> by (simp add: y_def divide_simps) (simp add: algebra_simps)?\n    also have \"1 - y = (f x - a) / (b - a)\"\n      using \\<open>a < b\\<close> by (simp add: field_simps y_def)\n    finally show \"exp (l * f x) \\<le> (b - f x) / (b - a) * exp (l*a) + (f x - a)/(b-a) * exp (l*b)\"\n      by (simp add: y_def)\n  qed\n  also have \"\\<dots> = (\\<integral>\\<^sup>+x. ennreal (b - f x) * exp (l * a) / (b - a) +\n                        ennreal (f x - a) * exp (l * b) / (b - a) \\<partial>M)\"\n    using \\<open>a < 0\\<close> \\<open>b > 0\\<close>\n    by (intro nn_integral_cong_AE eventually_mono[OF AE_in_interval])\n       (simp add: ennreal_plus ennreal_mult flip: divide_ennreal)\n  also have \"\\<dots> = ((\\<integral>\\<^sup>+ x. ennreal (b - f x) \\<partial>M) * ennreal (exp (l * a)) +\n                   (\\<integral>\\<^sup>+ x. ennreal (f x - a) \\<partial>M) * ennreal (exp (l * b))) / ennreal (b - a)\"\n    by (simp add: nn_integral_add nn_integral_divide nn_integral_multc add_divide_distrib_ennreal)\n  also have \"(\\<integral>\\<^sup>+ x. ennreal (b - f x) \\<partial>M) = ennreal (expectation (\\<lambda>x. b - f x))\"\n    by (intro nn_integral_eq_integral Bochner_Integration.integrable_diff\n              eventually_mono[OF AE_in_interval] integrable_const integrable) auto\n  also have \"expectation (\\<lambda>x. b - f x) = b\"\n    using assms by (subst Bochner_Integration.integral_diff) (auto simp: prob_space)\n  also have \"(\\<integral>\\<^sup>+ x. ennreal (f x - a) \\<partial>M) = ennreal (expectation (\\<lambda>x. f x - a))\"\n    by (intro nn_integral_eq_integral Bochner_Integration.integrable_diff\n              eventually_mono[OF AE_in_interval] integrable_const integrable) auto\n  also have \"expectation (\\<lambda>x. f x - a) = (-a)\"\n    using assms by (subst Bochner_Integration.integral_diff) (auto simp: prob_space)\n  also have \"(ennreal b * (exp (l * a)) + ennreal (-a) * (exp (l * b))) / (b - a) =\n             ennreal (b * exp (l * a) - a * exp (l * b)) / ennreal (b - a)\"\n    using \\<open>a < 0\\<close> \\<open>b > 0\\<close>\n    by (simp flip: ennreal_mult ennreal_plus add: mult_nonpos_nonneg divide_ennreal mult_mono)\n  also have \"b * exp (l * a) - a * exp (l * b) = exp (L z) * (b - a)\"\n  proof -\n    have pos: \"1 - p + p * exp z > 0\"\n    proof -\n      have \"exp z > 1\" using \\<open>l > 0\\<close> and \\<open>a < b\\<close>\n        by (subst one_less_exp_iff) (auto simp: z_def intro!: mult_pos_pos)\n      hence \"(exp z - 1) * p \\<ge> 0\"\n        unfolding p_def using \\<open>a < 0\\<close> and \\<open>a < b\\<close>\n        by (intro mult_nonneg_nonneg divide_nonneg_pos) auto\n      thus ?thesis\n        by (simp add: algebra_simps)\n    qed\n\n    have \"exp (L z) * (b - a) = exp (-z * p) * (1 - p + p * exp z) * (b - a)\"\n      using pos by (simp add: exp_add L_def exp_diff exp_minus divide_simps)\n    also have \"\\<dots> = b * exp (l * a) - a * exp (l * b)\" using \\<open>a < b\\<close>\n      by (simp add: p_def z_def divide_simps) (simp add:  exp_diff algebra_simps)?\n    finally show ?thesis by simp\n  qed\n  also have \"ennreal (exp (L z) * (b - a)) / ennreal (b - a) = ennreal (exp (L z))\"\n    using \\<open>a < b\\<close> by (simp add: divide_ennreal)\n  also have \"L z = -z * p + ln (1 + p * (exp z - 1))\"\n    by (simp add: L_def algebra_simps)\n  also have \"\\<dots> \\<le> z\\<^sup>2 / 8\"\n    unfolding L_def by (rule Hoeffdings_lemma_aux[where p = p]) (use \\<open>z > 0\\<close> \\<open>p > 0\\<close> in simp_all)\n  hence \"ennreal (exp (-z * p + ln (1 + p * (exp z - 1)))) \\<le> ennreal (exp (z\\<^sup>2 / 8))\"\n    by (intro ennreal_leI) auto\n  finally show ?thesis\n    by (simp add: z_def power_mult_distrib)\nqed\n\ncontext\nbegin\n\ninterpretation shift: interval_bounded_random_variable M \"\\<lambda>x. f x - \\<mu>\" \"a - \\<mu>\" \"b - \\<mu>\"\n  rewrites \"b - \\<mu> - (a - \\<mu>) \\<equiv> b - a\"\n  by unfold_locales (auto intro!: eventually_mono[OF AE_in_interval])\n\nlemma expectation_shift: \"expectation (\\<lambda>x. f x - expectation f) = 0\"\n  by (subst Bochner_Integration.integral_diff) (auto simp: integrable prob_space)\n\nlemmas Hoeffdings_lemma_nn_integral = shift.Hoeffdings_lemma_nn_integral_0[OF _ expectation_shift]\n\nend\n\nend\n\n\n\nsubsection \\<open>Hoeffding's Inequality\\<close>\n\ntext \\<open>\n  Consider \\<open>n\\<close> independent real random variables $X_1, \\ldots, X_n$ that each almost surely lie\n  in a compact interval $[a_i, b_i]$. Hoeffding's inequality states that the distribution of the\n  sum of the $X_i$ is tightly concentrated around the sum of the expected values: the probability\n  of it being above or below the sum of the expected values by more than some \\<open>\\<epsilon>\\<close> decreases\n  exponentially with \\<open>\\<epsilon>\\<close>.\n\\<close>\n\nlocale indep_interval_bounded_random_variables = prob_space +\n  fixes I :: \"'b set\" and X :: \"'b \\<Rightarrow> 'a \\<Rightarrow> real\"\n  fixes a b :: \"'b \\<Rightarrow> real\"\n  assumes fin: \"finite I\"\n  assumes indep: \"indep_vars (\\<lambda>_. borel) X I\"\n  assumes AE_in_interval: \"\\<And>i. i \\<in> I \\<Longrightarrow> AE x in M. X i x \\<in> {a i..b i}\"\nbegin\n\nlemma random_variable [measurable]:\n  assumes i: \"i \\<in> I\"\n  shows \"random_variable borel (X i)\"\n  using i indep unfolding indep_vars_def by blast\n\nlemma bounded_random_variable [intro]:\n  assumes i: \"i \\<in> I\"\n  shows   \"interval_bounded_random_variable M (X i) (a i) (b i)\"\n  by unfold_locales (use AE_in_interval[OF i] i in auto)\n\nend\n\n\nlocale Hoeffding_ineq = indep_interval_bounded_random_variables +\n  fixes \\<mu> :: real\n  defines \"\\<mu> \\<equiv> (\\<Sum>i\\<in>I. expectation (X i))\"\nbegin\n\ntheorem%important Hoeffding_ineq_ge:\n  assumes \"\\<epsilon> \\<ge> 0\"\n  assumes \"(\\<Sum>i\\<in>I. (b i - a i)\\<^sup>2) > 0\"\n  shows   \"prob {x\\<in>space M. (\\<Sum>i\\<in>I. X i x) \\<ge> \\<mu> + \\<epsilon>} \\<le> exp (-2 * \\<epsilon>\\<^sup>2 / (\\<Sum>i\\<in>I. (b i - a i)\\<^sup>2))\"\nproof (cases \"\\<epsilon> = 0\")\n  case [simp]: True\n  have \"prob {x\\<in>space M. (\\<Sum>i\\<in>I. X i x) \\<ge> \\<mu> + \\<epsilon>} \\<le> 1\"\n    by simp\n  thus ?thesis by simp\nnext\n  case False\n  with \\<open>\\<epsilon> \\<ge> 0\\<close> have \\<epsilon>: \"\\<epsilon> > 0\"\n    by auto\n\n  define d where \"d = (\\<Sum>i\\<in>I. (b i - a i)\\<^sup>2)\"\n  define l :: real where \"l = 4 * \\<epsilon> / d\"\n  have d: \"d > 0\"\n    using assms by (simp add: d_def)\n  have l: \"l > 0\"\n    using \\<epsilon> d by (simp add: l_def)\n  define \\<mu>' where \"\\<mu>' = (\\<lambda>i. expectation (X i))\"\n\n  have \"{x\\<in>space M. (\\<Sum>i\\<in>I. X i x) \\<ge> \\<mu> + \\<epsilon>} = {x\\<in>space M. (\\<Sum>i\\<in>I. X i x) - \\<mu> \\<ge> \\<epsilon>}\"\n    by (simp add: algebra_simps)\n  hence \"ennreal (prob {x\\<in>space M. (\\<Sum>i\\<in>I. X i x) \\<ge> \\<mu> + \\<epsilon>}) = emeasure M \\<dots>\"\n    by (simp add: emeasure_eq_measure)\n  also have \"\\<dots> \\<le> ennreal (exp (-l*\\<epsilon>)) * (\\<integral>\\<^sup>+x\\<in>space M. exp (l * ((\\<Sum>i\\<in>I. X i x) - \\<mu>)) \\<partial>M)\"\n    by (intro Chernoff_ineq_nn_integral_ge l) auto\n  also have \"(\\<lambda>x. (\\<Sum>i\\<in>I. X i x) - \\<mu>) = (\\<lambda>x. (\\<Sum>i\\<in>I. X i x - \\<mu>' i))\"\n    by (simp add: \\<mu>_def sum_subtractf \\<mu>'_def)\n  also have \"(\\<integral>\\<^sup>+x\\<in>space M. exp (l * ((\\<Sum>i\\<in>I. X i x - \\<mu>' i))) \\<partial>M) =\n             (\\<integral>\\<^sup>+x. (\\<Prod>i\\<in>I. ennreal (exp (l * (X i x - \\<mu>' i)))) \\<partial>M)\"\n    by (intro nn_integral_cong)\n       (simp_all add: sum_distrib_left ring_distribs exp_diff exp_sum fin prod_ennreal)\n  also have \"\\<dots> = (\\<Prod>i\\<in>I. \\<integral>\\<^sup>+x. ennreal (exp (l * (X i x - \\<mu>' i))) \\<partial>M)\"\n    by (intro indep_vars_nn_integral fin indep_vars_compose2[OF indep]) auto\n  also have \"ennreal (exp (-l * \\<epsilon>)) * \\<dots> \\<le>\n               ennreal (exp (-l * \\<epsilon>)) * (\\<Prod>i\\<in>I. ennreal (exp (l\\<^sup>2 * (b i - a i)\\<^sup>2 / 8)))\"\n  proof (intro mult_left_mono prod_mono_ennreal)\n    fix i assume i: \"i \\<in> I\"\n    from i interpret interval_bounded_random_variable M \"X i\" \"a i\" \"b i\" ..\n    show \"(\\<integral>\\<^sup>+x. ennreal (exp (l * (X i x - \\<mu>' i))) \\<partial>M) \\<le> ennreal (exp (l\\<^sup>2 * (b i - a i)\\<^sup>2 / 8))\"\n      unfolding \\<mu>'_def by (rule Hoeffdings_lemma_nn_integral) fact+\n  qed auto\n  also have \"\\<dots> = ennreal (exp (-l*\\<epsilon>) * (\\<Prod>i\\<in>I. exp (l\\<^sup>2 * (b i - a i)\\<^sup>2 / 8)))\"\n    by (simp add: prod_ennreal prod_nonneg flip: ennreal_mult)\n  also have \"exp (-l*\\<epsilon>) * (\\<Prod>i\\<in>I. exp (l\\<^sup>2 * (b i - a i)\\<^sup>2 / 8)) = exp (d * l\\<^sup>2 / 8 - l * \\<epsilon>)\"\n    by (simp add: exp_diff exp_minus sum_divide_distrib sum_distrib_left\n                  sum_distrib_right exp_sum fin divide_simps mult_ac d_def)\n  also have \"d * l\\<^sup>2 / 8 - l * \\<epsilon> = -2 * \\<epsilon>\\<^sup>2 / d\"\n    using d by (simp add: l_def field_simps power2_eq_square)\n  finally show ?thesis\n    by (subst (asm) ennreal_le_iff) (simp_all add: d_def)\nqed\n\ncorollary Hoeffding_ineq_le:\n  assumes \\<epsilon>: \"\\<epsilon> \\<ge> 0\"\n  assumes \"(\\<Sum>i\\<in>I. (b i - a i)\\<^sup>2) > 0\"\n  shows   \"prob {x\\<in>space M. (\\<Sum>i\\<in>I. X i x) \\<le> \\<mu> - \\<epsilon>} \\<le> exp (-2 * \\<epsilon>\\<^sup>2 / (\\<Sum>i\\<in>I. (b i - a i)\\<^sup>2))\"\nproof -\n  interpret flip: Hoeffding_ineq M I \"\\<lambda>i x. -X i x\" \"\\<lambda>i. -b i\" \"\\<lambda>i. -a i\" \"-\\<mu>\"\n  proof unfold_locales\n    fix i assume \"i \\<in> I\"\n    then interpret interval_bounded_random_variable M \"X i\" \"a i\" \"b i\" ..\n    show \"AE x in M. - X i x \\<in> {- b i..- a i}\"\n      by (intro eventually_mono[OF AE_in_interval]) auto\n  qed (auto simp: fin \\<mu>_def sum_negf intro: indep_vars_compose2[OF indep])\n\n  have \"prob {x\\<in>space M. (\\<Sum>i\\<in>I. X i x) \\<le> \\<mu> - \\<epsilon>} = prob {x\\<in>space M. (\\<Sum>i\\<in>I. -X i x) \\<ge> -\\<mu> + \\<epsilon>}\"\n    by (simp add: sum_negf algebra_simps)\n  also have \"\\<dots> \\<le> exp (- 2 * \\<epsilon>\\<^sup>2 / (\\<Sum>i\\<in>I. (b i - a i)\\<^sup>2))\"\n    using flip.Hoeffding_ineq_ge[OF \\<epsilon>] assms(2) by simp\n  finally show ?thesis .\nqed\n\ncorollary Hoeffding_ineq_abs_ge:\n  assumes \\<epsilon>: \"\\<epsilon> \\<ge> 0\"\n  assumes \"(\\<Sum>i\\<in>I. (b i - a i)\\<^sup>2) > 0\"\n  shows   \"prob {x\\<in>space M. \\<bar>(\\<Sum>i\\<in>I. X i x) - \\<mu>\\<bar> \\<ge> \\<epsilon>} \\<le> 2 * exp (-2 * \\<epsilon>\\<^sup>2 / (\\<Sum>i\\<in>I. (b i - a i)\\<^sup>2))\"\nproof -\n  have \"{x\\<in>space M. \\<bar>(\\<Sum>i\\<in>I. X i x) - \\<mu>\\<bar> \\<ge> \\<epsilon>} =\n        {x\\<in>space M. (\\<Sum>i\\<in>I. X i x) \\<ge> \\<mu> + \\<epsilon>} \\<union> {x\\<in>space M. (\\<Sum>i\\<in>I. X i x) \\<le> \\<mu> - \\<epsilon>}\"\n    by auto\n  also have \"prob \\<dots> \\<le> prob {x\\<in>space M. (\\<Sum>i\\<in>I. X i x) \\<ge> \\<mu> + \\<epsilon>} +\n                       prob {x\\<in>space M. (\\<Sum>i\\<in>I. X i x) \\<le> \\<mu> - \\<epsilon>}\"\n    by (intro measure_Un_le) auto\n  also have \"\\<dots> \\<le> exp (-2 * \\<epsilon>\\<^sup>2 / (\\<Sum>i\\<in>I. (b i - a i)\\<^sup>2)) + exp (-2 * \\<epsilon>\\<^sup>2 / (\\<Sum>i\\<in>I. (b i - a i)\\<^sup>2))\"\n    by (intro add_mono Hoeffding_ineq_ge Hoeffding_ineq_le assms)\n  finally show ?thesis by simp\nqed\n\nend\n\n\nsubsection \\<open>Hoeffding's inequality for i.i.d. bounded random variables\\<close>\n\ntext \\<open>\n  If we have \\<open>n\\<close> even identically-distributed random variables, the statement of Hoeffding's\n  lemma simplifies a bit more: it shows that the probability that the average of the $X_i$\n  is more than \\<open>\\<epsilon>\\<close> above the expected value is no greater than $e^{\\frac{-2ny^2}{(b-a)^2}}$.\n\n  This essentially gives us a more concrete version of the weak law of large numbers: the law\n  states that the probability vanishes for \\<open>n \\<rightarrow> \\<infinity>\\<close> for any \\<open>\\<epsilon> > 0\\<close>. Unlike Hoeffding's inequality,\n  it does not assume the variables to have bounded support, but it does not provide concrete bounds.\n\\<close>\n\nlocale iid_interval_bounded_random_variables = prob_space +\n  fixes I :: \"'b set\" and X :: \"'b \\<Rightarrow> 'a \\<Rightarrow> real\" and Y :: \"'a \\<Rightarrow> real\"\n  fixes a b :: real\n  assumes fin: \"finite I\"\n  assumes indep: \"indep_vars (\\<lambda>_. borel) X I\"\n  assumes distr_X: \"i \\<in> I \\<Longrightarrow> distr M borel (X i) = distr M borel Y\"\n  assumes rv_Y [measurable]: \"random_variable borel Y\"\n  assumes AE_in_interval: \"AE x in M. Y x \\<in> {a..b}\"\nbegin\n\nlemma random_variable [measurable]:\n  assumes i: \"i \\<in> I\"\n  shows \"random_variable borel (X i)\"\n  using i indep unfolding indep_vars_def by blast\n\nsublocale X: indep_interval_bounded_random_variables M I X \"\\<lambda>_. a\" \"\\<lambda>_. b\"\nproof\n  fix i assume i: \"i \\<in> I\"\n  have \"AE x in M. Y x \\<in> {a..b}\"\n    by (fact AE_in_interval)\n  also have \"?this \\<longleftrightarrow> (AE x in distr M borel Y. x \\<in> {a..b})\"\n    by (subst AE_distr_iff) auto\n  also have \"distr M borel Y = distr M borel (X i)\"\n    using i by (simp add: distr_X)\n  also have \"(AE x in \\<dots>. x \\<in> {a..b}) \\<longleftrightarrow> (AE x in M. X i x \\<in> {a..b})\"\n    using i by (subst AE_distr_iff) auto\n  finally show \"AE x in M. X i x \\<in> {a..b}\" .\nqed (simp_all add: fin indep)\n\nlemma expectation_X [simp]:\n  assumes i: \"i \\<in> I\"\n  shows \"expectation (X i) = expectation Y\"\nproof -\n  have \"expectation (X i) = lebesgue_integral (distr M borel (X i)) (\\<lambda>x. x)\"\n    using i by (intro integral_distr [symmetric]) auto\n  also have \"distr M borel (X i) = distr M borel Y\"\n    using i by (rule distr_X)\n  also have \"lebesgue_integral \\<dots> (\\<lambda>x. x) = expectation Y\"\n    by (rule integral_distr) auto\n  finally show \"expectation (X i) = expectation Y\" .\nqed\n\nend\n\n\nlocale Hoeffding_ineq_iid = iid_interval_bounded_random_variables +\n  fixes \\<mu> :: real\n  defines \"\\<mu> \\<equiv> expectation Y\"\nbegin\n\nsublocale X: Hoeffding_ineq M I X \"\\<lambda>_. a\" \"\\<lambda>_. b\" \"real (card I) * \\<mu>\"\n  by unfold_locales (simp_all add: \\<mu>_def)\n\ncorollary\n  assumes \\<epsilon>: \"\\<epsilon> \\<ge> 0\"\n  assumes \"a < b\" \"I \\<noteq> {}\"\n  defines \"n \\<equiv> card I\"\n  shows   Hoeffding_ineq_ge:\n            \"prob {x\\<in>space M. (\\<Sum>i\\<in>I. X i x) \\<ge> n * \\<mu> + \\<epsilon>} \\<le>\n               exp (-2 * \\<epsilon>\\<^sup>2 / (n * (b - a)\\<^sup>2))\" (is ?le)\n    and   Hoeffding_ineq_le:\n            \"prob {x\\<in>space M. (\\<Sum>i\\<in>I. X i x) \\<le> n * \\<mu> - \\<epsilon>} \\<le>\n               exp (-2 * \\<epsilon>\\<^sup>2 / (n * (b - a)\\<^sup>2))\" (is ?ge)\n    and   Hoeffding_ineq_abs_ge:\n            \"prob {x\\<in>space M. \\<bar>(\\<Sum>i\\<in>I. X i x) - n * \\<mu>\\<bar> \\<ge> \\<epsilon>} \\<le>\n               2 * exp (-2 * \\<epsilon>\\<^sup>2 / (n * (b - a)\\<^sup>2))\" (is ?abs_ge)\nproof -\n  have pos: \"(\\<Sum>i\\<in>I. (b - a)\\<^sup>2) > 0\"\n    using \\<open>a < b\\<close> \\<open>I \\<noteq> {}\\<close> fin by (intro sum_pos) auto\n  show ?le\n    using X.Hoeffding_ineq_ge[OF \\<epsilon> pos] by (simp add: n_def)\n  show ?ge\n    using X.Hoeffding_ineq_le[OF \\<epsilon> pos] by (simp add: n_def)\n  show ?abs_ge\n    using X.Hoeffding_ineq_abs_ge[OF \\<epsilon> pos] by (simp add: n_def)\nqed\n\nlemma \n  assumes \\<epsilon>: \"\\<epsilon> \\<ge> 0\"\n  assumes \"a < b\" \"I \\<noteq> {}\"\n  defines \"n \\<equiv> card I\"\n  shows   Hoeffding_ineq_ge':\n            \"prob {x\\<in>space M. (\\<Sum>i\\<in>I. X i x) / n \\<ge> \\<mu> + \\<epsilon>} \\<le>\n               exp (-2 * n * \\<epsilon>\\<^sup>2 / (b - a)\\<^sup>2)\" (is ?ge)\n    and   Hoeffding_ineq_le':\n            \"prob {x\\<in>space M. (\\<Sum>i\\<in>I. X i x) / n \\<le> \\<mu> - \\<epsilon>} \\<le>\n               exp (-2 * n * \\<epsilon>\\<^sup>2 / (b - a)\\<^sup>2)\" (is ?le)\n    and   Hoeffding_ineq_abs_ge':\n            \"prob {x\\<in>space M. \\<bar>(\\<Sum>i\\<in>I. X i x) / n - \\<mu>\\<bar> \\<ge> \\<epsilon>} \\<le>\n               2 * exp (-2 * n * \\<epsilon>\\<^sup>2 / (b - a)\\<^sup>2)\" (is ?abs_ge)\nproof -\n  have \"n > 0\"\n    using assms fin by (auto simp: field_simps)\n  have \\<epsilon>': \"\\<epsilon> * n \\<ge> 0\"\n    using \\<open>n > 0\\<close> \\<open>\\<epsilon> \\<ge> 0\\<close> by auto\n  have eq: \"- (2 * (\\<epsilon> * real n)\\<^sup>2 / (real (card I) * (b - a)\\<^sup>2)) =\n            - (2 * real n * \\<epsilon>\\<^sup>2 / (b - a)\\<^sup>2)\"\n    using \\<open>n > 0\\<close> by (simp add: power2_eq_square divide_simps n_def)\n\n  have \"{x\\<in>space M. (\\<Sum>i\\<in>I. X i x) / n \\<ge> \\<mu> + \\<epsilon>} =\n        {x\\<in>space M. (\\<Sum>i\\<in>I. X i x) \\<ge> \\<mu> * n + \\<epsilon> * n}\"\n    using \\<open>n > 0\\<close> by (intro Collect_cong conj_cong refl) (auto simp: field_simps)\n  with Hoeffding_ineq_ge[OF \\<epsilon>' \\<open>a < b\\<close> \\<open>I \\<noteq> {}\\<close>] \\<open>n > 0\\<close> eq show ?ge\n    by (simp add: n_def mult_ac)\n\n  have \"{x\\<in>space M. (\\<Sum>i\\<in>I. X i x) / n \\<le> \\<mu> - \\<epsilon>} =\n        {x\\<in>space M. (\\<Sum>i\\<in>I. X i x) \\<le> \\<mu> * n - \\<epsilon> * n}\"\n    using \\<open>n > 0\\<close> by (intro Collect_cong conj_cong refl) (auto simp: field_simps)\n  with Hoeffding_ineq_le[OF \\<epsilon>' \\<open>a < b\\<close> \\<open>I \\<noteq> {}\\<close>] \\<open>n > 0\\<close> eq show ?le\n    by (simp add: n_def mult_ac)\n\n  have \"{x\\<in>space M. \\<bar>(\\<Sum>i\\<in>I. X i x) / n - \\<mu>\\<bar> \\<ge> \\<epsilon>} =\n        {x\\<in>space M. \\<bar>(\\<Sum>i\\<in>I. X i x) - \\<mu> * n\\<bar> \\<ge> \\<epsilon> * n}\"\n    using \\<open>n > 0\\<close> by (intro Collect_cong conj_cong refl) (auto simp: field_simps)\n  with Hoeffding_ineq_abs_ge[OF \\<epsilon>' \\<open>a < b\\<close> \\<open>I \\<noteq> {}\\<close>] \\<open>n > 0\\<close> eq show ?abs_ge\n    by (simp add: n_def mult_ac)\nqed\n\nend\n\n\nsubsection \\<open>Hoeffding's Inequality for the Binomial distribution\\<close>\n\ntext \\<open>\n  We can now apply Hoeffding's inequality to the Binomial distribution, which can be seen\n  as the sum of \\<open>n\\<close> i.i.d. coin flips (the support of each of which is contained in $[0,1]$).\n\\<close>\n\nlocale binomial_distribution =\n  fixes n :: nat and p :: real\n  assumes p: \"p \\<in> {0..1}\"\nbegin\n\ncontext\n  fixes coins :: \"(nat \\<Rightarrow> bool) pmf\" and \\<mu>\n  assumes n: \"n > 0\"\n  defines \"coins \\<equiv> Pi_pmf {..<n} False (\\<lambda>_. bernoulli_pmf p)\"\nbegin\n\nlemma coins_component:\n  assumes i: \"i < n\"\n  shows   \"distr (measure_pmf coins) borel (\\<lambda>f. if f i then 1 else 0) =\n             distr (measure_pmf (bernoulli_pmf p)) borel (\\<lambda>b. if b then 1 else 0)\"\nproof -\n  have \"distr (measure_pmf coins) borel (\\<lambda>f. if f i then 1 else 0) =\n        distr (measure_pmf (map_pmf (\\<lambda>f. f i) coins)) borel (\\<lambda>b. if b then 1 else 0)\"\n    unfolding map_pmf_rep_eq by (subst distr_distr) (auto simp: o_def)\n  also have \"map_pmf (\\<lambda>f. f i) coins = bernoulli_pmf p\"\n    unfolding coins_def using i by (subst Pi_pmf_component) auto\n  finally show ?thesis\n    unfolding map_pmf_rep_eq .\nqed\n\nlemma prob_binomial_pmf_conv_coins:\n  \"measure_pmf.prob (binomial_pmf n p) {x. P (real x)} = \n   measure_pmf.prob coins {x. P (\\<Sum>i<n. if x i then 1 else 0)}\"\nproof -\n  have eq1: \"(\\<Sum>i<n. if x i then 1 else 0) = real (card {i\\<in>{..<n}. x i})\" for x\n  proof -\n    have \"(\\<Sum>i<n. if x i then 1 else (0::real)) = (\\<Sum>i\\<in>{i\\<in>{..<n}. x i}. 1)\"\n      by (intro sum.mono_neutral_cong_right) auto\n    thus ?thesis by simp\n  qed\n  have eq2: \"binomial_pmf n p = map_pmf (\\<lambda>v. card {i\\<in>{..<n}. v i}) coins\"\n    unfolding coins_def by (rule binomial_pmf_altdef') (use p in auto)\n  show ?thesis\n    by (subst eq2) (simp_all add: eq1)\nqed\n\ninterpretation Hoeffding_ineq_iid\n  coins \"{..<n}\" \"\\<lambda>i f. if f i then 1 else 0\" \"\\<lambda>f. if f 0 then 1 else 0\" 0 1 p\nproof unfold_locales\n  show \"prob_space.indep_vars (measure_pmf coins) (\\<lambda>_. borel) (\\<lambda>i f. if f i then 1 else 0) {..<n}\"\n    unfolding coins_def\n    by (intro prob_space.indep_vars_compose2[OF _ indep_vars_Pi_pmf])\n       (auto simp: measure_pmf.prob_space_axioms)\nnext\n  have \"measure_pmf.expectation coins (\\<lambda>f. if f 0 then 1 else 0 :: real) =\n        measure_pmf.expectation (map_pmf (\\<lambda>f. f 0) coins) (\\<lambda>b. if b then 1 else 0 :: real)\"\n    by (simp add: coins_def)\n  also have \"map_pmf (\\<lambda>f. f 0) coins = bernoulli_pmf p\"\n    using n by (simp add: coins_def Pi_pmf_component)\n  also have \"measure_pmf.expectation \\<dots> (\\<lambda>b. if b then 1 else 0) = p\"\n    using p by simp\n  finally show \"p \\<equiv> measure_pmf.expectation coins (\\<lambda>f. if f 0 then 1 else 0)\" by simp\nqed (auto simp: coins_component)\n\ncorollary\n  fixes \\<epsilon> :: real\n  assumes \\<epsilon>: \"\\<epsilon> \\<ge> 0\"\n  shows prob_ge: \"measure_pmf.prob (binomial_pmf n p) {x. x \\<ge> n * p + \\<epsilon>} \\<le> exp (-2 * \\<epsilon>\\<^sup>2 / n)\"\n    and prob_le: \"measure_pmf.prob (binomial_pmf n p) {x. x \\<le> n * p - \\<epsilon>} \\<le> exp (-2 * \\<epsilon>\\<^sup>2 / n)\"\n    and prob_abs_ge:\n          \"measure_pmf.prob (binomial_pmf n p) {x. \\<bar>x - n * p\\<bar> \\<ge> \\<epsilon>} \\<le> 2 * exp (-2 * \\<epsilon>\\<^sup>2 / n)\"\nproof -\n  have [simp]: \"{..<n} \\<noteq> {}\"\n    using n by auto\n  show \"measure_pmf.prob (binomial_pmf n p) {x. x \\<ge> n * p + \\<epsilon>} \\<le> exp (-2 * \\<epsilon>\\<^sup>2 / n)\"\n    using Hoeffding_ineq_ge[of \\<epsilon>] by (subst prob_binomial_pmf_conv_coins) (use assms in simp_all)\n  show \"measure_pmf.prob (binomial_pmf n p) {x. x \\<le> n * p - \\<epsilon>} \\<le> exp (-2 * \\<epsilon>\\<^sup>2 / n)\"\n    using Hoeffding_ineq_le[of \\<epsilon>] by (subst prob_binomial_pmf_conv_coins) (use assms in simp_all)\n  show \"measure_pmf.prob (binomial_pmf n p) {x. \\<bar>x - n * p\\<bar> \\<ge> \\<epsilon>} \\<le> 2 *  exp (-2 * \\<epsilon>\\<^sup>2 / n)\"\n    using Hoeffding_ineq_abs_ge[of \\<epsilon>]\n    by (subst prob_binomial_pmf_conv_coins) (use assms in simp_all)\nqed\n\ncorollary\n  fixes \\<epsilon> :: real\n  assumes \\<epsilon>: \"\\<epsilon> \\<ge> 0\"\n  shows prob_ge': \"measure_pmf.prob (binomial_pmf n p) {x. x / n \\<ge> p + \\<epsilon>} \\<le> exp (-2 * n * \\<epsilon>\\<^sup>2)\"\n    and prob_le': \"measure_pmf.prob (binomial_pmf n p) {x. x / n \\<le> p - \\<epsilon>} \\<le> exp (-2 * n * \\<epsilon>\\<^sup>2)\"\n    and prob_abs_ge':\n          \"measure_pmf.prob (binomial_pmf n p) {x. \\<bar>x / n - p\\<bar> \\<ge> \\<epsilon>} \\<le> 2 * exp (-2 * n * \\<epsilon>\\<^sup>2)\"\nproof -\n  have [simp]: \"{..<n} \\<noteq> {}\"\n    using n by auto\n  show \"measure_pmf.prob (binomial_pmf n p) {x. x / n \\<ge> p + \\<epsilon>} \\<le> exp (-2 * n * \\<epsilon>\\<^sup>2)\"\n    using Hoeffding_ineq_ge'[of \\<epsilon>] by (subst prob_binomial_pmf_conv_coins) (use assms in simp_all)\n  show \"measure_pmf.prob (binomial_pmf n p) {x. x / n \\<le> p - \\<epsilon>} \\<le> exp (-2 * n * \\<epsilon>\\<^sup>2)\"\n    using Hoeffding_ineq_le'[of \\<epsilon>] by (subst prob_binomial_pmf_conv_coins) (use assms in simp_all)\n  show \"measure_pmf.prob (binomial_pmf n p) {x. \\<bar>x / n - p\\<bar> \\<ge> \\<epsilon>} \\<le> 2 * exp (-2 * n * \\<epsilon>\\<^sup>2)\"\n    using Hoeffding_ineq_abs_ge'[of \\<epsilon>]\n    by (subst prob_binomial_pmf_conv_coins) (use assms in simp_all)\nqed\n\nend\n\nend\n\n\nsubsection \\<open>Tail bounds for the negative binomial distribution\\<close>\n\ntext \\<open>\n  Since the tail probabilities of a negative Binomial distribution are equal to the\n  tail probabilities of some Binomial distribution, we can obtain tail bounds for the\n  negative Binomial distribution through the Hoeffding tail bounds for the Binomial\n  distribution.\n\\<close>\n\ncontext\n  fixes p q :: real\n  assumes p: \"p \\<in> {0<..<1}\"\n  defines \"q \\<equiv> 1 - p\"\nbegin\n\nlemma prob_neg_binomial_pmf_ge_bound:\n  fixes n :: nat and k :: real\n  defines \"\\<mu> \\<equiv> real n * q / p\"\n  assumes k: \"k \\<ge> 0\"\n  shows \"measure_pmf.prob (neg_binomial_pmf n p) {x. real x \\<ge> \\<mu> + k}\n         \\<le> exp (- 2 * p ^ 3 * k\\<^sup>2 / (n + p * k))\"\nproof -\n  consider \"n = 0\" | \"p = 1\" | \"n > 0\" \"p \\<noteq> 1\"\n    by blast\n  thus ?thesis\n  proof cases\n    assume [simp]: \"n = 0\"\n    show ?thesis using k\n      by (simp add: indicator_def \\<mu>_def)\n  next\n    assume [simp]: \"p = 1\"\n    show ?thesis using k\n      by (auto simp add: indicator_def \\<mu>_def q_def)\n  next\n    assume n: \"n > 0\" and \"p \\<noteq> 1\"\n    from \\<open>p \\<noteq> 1\\<close> and p have p: \"p \\<in> {0<..<1}\"\n      by auto\n    from p have q: \"q \\<in> {0<..<1}\"\n      by (auto simp: q_def)\n\n    define k1 where \"k1 = \\<mu> + k\"\n    have k1: \"k1 \\<ge> \\<mu>\"\n      using k by (simp add: k1_def)\n    have \"k1 > 0\"\n      by (rule less_le_trans[OF _ k1]) (use p n in \\<open>auto simp: q_def \\<mu>_def\\<close>)\n  \n    define k1' where \"k1' = nat (ceiling k1)\"\n    have \"\\<mu> \\<ge> 0\" using p\n      by (auto simp: \\<mu>_def q_def)\n    have \"\\<not>(x < k1') \\<longleftrightarrow> real x \\<ge> k1\" for x\n      unfolding k1'_def by linarith\n    hence eq: \"UNIV - {..<k1'} = {x. x \\<ge> k1}\"\n      by auto\n    hence \"measure_pmf.prob (neg_binomial_pmf n p) {n. n \\<ge> k1} =\n          1 - measure_pmf.prob (neg_binomial_pmf n p) {..<k1'}\"\n      using measure_pmf.prob_compl[of \"{..<k1'}\" \"neg_binomial_pmf n p\"] by simp\n    also have \"measure_pmf.prob (neg_binomial_pmf n p) {..<k1'} =\n               measure_pmf.prob (binomial_pmf (n + k1' - 1) q) {..<k1'}\"\n      unfolding q_def using p by (intro prob_neg_binomial_pmf_lessThan) auto\n    also have \"1 - \\<dots> = measure_pmf.prob (binomial_pmf (n + k1' - 1) q) {n. n \\<ge> k1}\"\n      using measure_pmf.prob_compl[of \"{..<k1'}\" \"binomial_pmf (n + k1' - 1) q\"] eq by simp\n    also have \"{x. real x \\<ge> k1} = {x. x \\<ge> real (n + k1' - 1) * q + (k1 - real (n + k1' - 1) * q)}\"\n      by simp\n    also have \"measure_pmf.prob (binomial_pmf (n + k1' - 1) q) \\<dots> \\<le>\n                 exp (-2 * (k1 - real (n + k1' - 1) * q)\\<^sup>2 / real (n + k1' - 1))\"\n    proof (rule binomial_distribution.prob_ge)\n      show \"binomial_distribution q\"\n        by unfold_locales (use q in auto)\n    next\n      show \"n + k1' - 1 > 0\"\n        using \\<open>k1 > 0\\<close> n unfolding k1'_def by linarith\n    next\n      have \"real (n + nat \\<lceil>k1\\<rceil> - 1) \\<le> real n + k1\"\n        using \\<open>k1 > 0\\<close> by linarith\n      hence \"real (n + k1' - 1) * q  \\<le> (real n + k1) * q\"\n        unfolding k1'_def by (intro mult_right_mono) (use p in \\<open>simp_all add: q_def\\<close>)\n      also have \"\\<dots> \\<le> k1\"\n        using k1 p by (simp add: q_def field_simps \\<mu>_def)\n      finally show \"0 \\<le> k1 - real (n + k1' - 1) * q\"\n        by simp\n    qed\n    also have \"{x. real (n + k1' - 1) * q + (k1 - real (n + k1' - 1) * q) \\<le> real x} = {x. real x \\<ge> k1}\"\n      by simp\n    also have \"exp (-2 * (k1 - real (n + k1' - 1) * q)\\<^sup>2 / real (n + k1' - 1)) \\<le>\n               exp (-2 * (k1 - (n + k1) * q)\\<^sup>2 / (n + k1))\"\n    proof -\n      have \"real (n + k1' - Suc 0) \\<le> real n + k1\"\n        unfolding k1'_def using \\<open>k1 > 0\\<close> by linarith\n      moreover have \"(real n + k1) * q \\<le> k1\"\n        using k1 p by (auto simp: q_def field_simps \\<mu>_def)\n      moreover have \"1 < n + k1'\"\n        using n \\<open>k1 > 0\\<close> unfolding k1'_def by linarith\n      ultimately have \"2 * (k1 - real (n + k1' - 1) * q)\\<^sup>2 / real (n + k1' - 1) \\<ge>\n                       2 * (k1 - (n + k1) * q)\\<^sup>2 / (n + k1)\"\n        by (intro frac_le mult_left_mono power_mono mult_nonneg_nonneg mult_right_mono diff_mono)\n           (use q in simp_all)\n      thus ?thesis\n        by simp\n    qed\n    also have \"\\<dots> = exp (-2 * (p * k1 - q * n)\\<^sup>2 / (k1 + n))\"\n      by (simp add: q_def algebra_simps)\n    also have \"-2 * (p * k1 - q * n)\\<^sup>2 = -2 * p\\<^sup>2 * (k1 - \\<mu>)\\<^sup>2\"\n      using p by (auto simp: field_simps \\<mu>_def)\n    also have \"k1 - \\<mu> = k\"\n      by (simp add: k1_def \\<mu>_def)\n    also note k1_def\n    also have \"\\<mu> + k + real n = real n / p + k\"\n      using p by (simp add: \\<mu>_def q_def field_simps)\n    also have \"- 2 * p\\<^sup>2 * k\\<^sup>2 / (real n / p + k) = - 2 * p ^ 3 * k\\<^sup>2 / (p * k + n)\"\n      using p by (simp add: field_simps power3_eq_cube power2_eq_square)\n    finally show ?thesis by (simp add: add_ac)\n  qed\nqed\n\nlemma prob_neg_binomial_pmf_le_bound:\n  fixes n :: nat and k :: real\n  defines \"\\<mu> \\<equiv> real n * q / p\"\n  assumes k: \"k \\<ge> 0\"\n  shows \"measure_pmf.prob (neg_binomial_pmf n p) {x. real x \\<le> \\<mu> - k}\n         \\<le> exp (-2 * p ^ 3 * k\\<^sup>2 / (n - p * k))\"\nproof -\n  consider \"n = 0\" | \"p = 1\" | \"k > \\<mu>\" | \"n > 0\" \"p \\<noteq> 1\" \"k \\<le> \\<mu>\"\n    by force\n  thus ?thesis\n  proof cases\n    assume [simp]: \"n = 0\"\n    show ?thesis using k\n      by (simp add: indicator_def \\<mu>_def)\n  next\n    assume [simp]: \"p = 1\"\n    show ?thesis using k\n      by (auto simp add: indicator_def \\<mu>_def q_def)\n  next\n    assume \"k > \\<mu>\"\n    hence \"{x. real x \\<le> \\<mu> - k} = {}\"\n      by auto\n    thus ?thesis by simp\n  next\n    assume n: \"n > 0\" and \"p \\<noteq> 1\" and \"k \\<le> \\<mu>\"\n    from \\<open>p \\<noteq> 1\\<close> and p have p: \"p \\<in> {0<..<1}\"\n      by auto\n    from p have q: \"q \\<in> {0<..<1}\"\n      by (auto simp: q_def)\n\n    define f :: \"real \\<Rightarrow> real\" where \"f = (\\<lambda>x. (p * x - q * n)\\<^sup>2 / (x + n))\"\n    have f_mono: \"f x \\<ge> f y\" if \"x \\<ge> 0\" \"y \\<le> n * q / p\" \"x \\<le> y\" for x y :: real\n      using that(3)\n    proof (rule DERIV_nonpos_imp_nonincreasing)\n      fix t assume t: \"t \\<ge> x\" \"t \\<le> y\"\n      have \"x > -n\"\n        using n \\<open>x \\<ge> 0\\<close> by linarith\n      hence \"(f has_field_derivative ((p * t - q * n) * (n * (1 + p) + p * t) / (n + t) ^ 2)) (at t)\"\n        unfolding f_def using t\n        by (auto intro!: derivative_eq_intros simp: algebra_simps q_def power2_eq_square)\n      moreover {\n        have \"p * t \\<le> p * y\"\n          using p by (intro mult_left_mono t) auto\n        also have \"p * y \\<le> q * n\"\n          using \\<open>y \\<le> n * q / p\\<close> p by (simp add: field_simps)\n        finally have \"p * t \\<le> q * n\" .\n      }\n      hence \"(p * t - q * n) * (n * (1 + p) + p * t) / (n + t) ^ 2 \\<le> 0\"\n        using p \\<open>x \\<ge> 0\\<close> t\n        by (intro mult_nonpos_nonneg divide_nonpos_nonneg add_nonneg_nonneg mult_nonneg_nonneg) auto\n      ultimately show \"\\<exists>y. (f has_real_derivative y) (at t) \\<and> y \\<le> 0\"\n        by blast\n    qed\n\n    define k1 where \"k1 = \\<mu> - k\"\n    have k1: \"k1 \\<le> real n * q / p\"\n      using assms by (simp add: \\<mu>_def k1_def)\n    have \"k1 \\<ge> 0\"\n      using k \\<open>k \\<le> \\<mu>\\<close> by (simp add: \\<mu>_def k1_def)\n  \n    define k1' where \"k1' = nat (floor k1)\"\n    have \"\\<mu> \\<ge> 0\" using p\n      by (auto simp: \\<mu>_def q_def)\n    have \"(x \\<le> k1') \\<longleftrightarrow> real x \\<le> k1\" for x\n      unfolding k1'_def not_less using \\<open>k1 \\<ge> 0\\<close> by linarith\n    hence eq: \"{n. n \\<le> k1}  = {..k1'}\"\n      by auto\n    hence \"measure_pmf.prob (neg_binomial_pmf n p) {n. n \\<le> k1} =\n           measure_pmf.prob (neg_binomial_pmf n p) {..k1'}\"\n      by simp\n    also have \"measure_pmf.prob (neg_binomial_pmf n p) {..k1'} =\n               measure_pmf.prob (binomial_pmf (n + k1') q) {..k1'}\"\n      unfolding q_def using p by (intro prob_neg_binomial_pmf_atMost) auto\n    also note eq [symmetric]\n    also have \"{x. real x \\<le> k1} = {x. x \\<le> real (n + k1') * q - (real (n + k1') * q - real k1')}\"\n      using eq by auto\n    also have \"measure_pmf.prob (binomial_pmf (n + k1') q) \\<dots> \\<le>\n                 exp (-2 * (real (n + k1') * q - real k1')\\<^sup>2 / real (n + k1'))\"\n    proof (rule binomial_distribution.prob_le)\n      show \"binomial_distribution q\"\n        by unfold_locales (use q in auto)\n    next\n      show \"n + k1' > 0\"\n        using \\<open>k1 \\<ge> 0\\<close> n unfolding k1'_def by linarith\n    next\n      have \"p * k1' \\<le> p * k1\"\n        using p \\<open>k1 \\<ge> 0\\<close> by (intro mult_left_mono) (auto simp: k1'_def)\n      also have \"\\<dots> \\<le> q * n\"\n        using k1 p by (simp add: field_simps)\n      finally show \"0 \\<le> real (n + k1') * q - real k1'\"\n        by (simp add: algebra_simps q_def)\n    qed\n    also have \"{x. real x \\<le> real (n + k1') * q - (real (n + k1') * q - k1')} = {..k1'}\"\n      by auto\n    also have \"real (n + k1') * q - k1' = -(p * k1' - q * n)\"\n      by (simp add: q_def algebra_simps)\n    also have \"\\<dots> ^ 2 = (p * k1' - q * n) ^ 2\"\n      by algebra\n    also have \"- 2 * (p * real k1' - q * real n)\\<^sup>2 / real (n + k1') = -2 * f (real k1')\"\n      by (simp add: f_def)\n    also have \"f (real k1') \\<ge> f k1\"\n      by (rule f_mono) (use \\<open>k1 \\<ge> 0\\<close> k1 in \\<open>auto simp: k1'_def\\<close>)\n    hence \"exp (-2 * f (real k1')) \\<le> exp (-2 * f k1)\"\n      by simp\n    also have \"\\<dots> = exp (-2 * (p * k1 - q * n)\\<^sup>2 / (k1 + n))\"\n      by (simp add: f_def)\n\n    also have \"-2 * (p * k1 - q * n)\\<^sup>2 = -2 * p\\<^sup>2 * (k1 - \\<mu>)\\<^sup>2\"\n      using p by (auto simp: field_simps \\<mu>_def)\n    also have \"(k1 - \\<mu>) ^ 2 = k ^ 2\"\n      by (simp add: k1_def \\<mu>_def)\n    also note k1_def\n    also have \"\\<mu> - k + real n = real n / p - k\"\n      using p by (simp add: \\<mu>_def q_def field_simps)\n    also have \"- 2 * p\\<^sup>2 * k\\<^sup>2 / (real n / p - k) = - 2 * p ^ 3 * k\\<^sup>2 / (n - p * k)\"\n      using p by (simp add: field_simps power3_eq_cube power2_eq_square)\n    also have \"{..k1'} = {x. real x \\<le> \\<mu> - k}\"\n      using eq by (simp add: k1_def)\n    finally show ?thesis .\n  qed\nqed\n\ntext \\<open>\n  Due to the function $exp(-l/x)$ being concave for $x \\geq \\frac{l}{2}$, the above two\n  bounds can be combined into the following one for moderate values of \\<open>k\\<close>.\n  (cf. \\<^url>\\<open>https://math.stackexchange.com/questions/1565559\\<close>)\n\\<close>\nlemma prob_neg_binomial_pmf_abs_ge_bound:\n  fixes n :: nat and k :: real\n  defines \"\\<mu> \\<equiv> real n * q / p\"\n  assumes \"k \\<ge> 0\" and n_ge: \"n \\<ge> p * k * (p\\<^sup>2 * k + 1)\"\n  shows \"measure_pmf.prob (neg_binomial_pmf n p) {x. \\<bar>real x - \\<mu>\\<bar> \\<ge> k} \\<le>\n           2 * exp (-2 * p ^ 3 * k ^ 2 / n)\"\nproof (cases \"k = 0\")\n  case False\n  with \\<open>k \\<ge> 0\\<close> have k: \"k > 0\"\n    by auto\n  define l :: real where \"l = 2 * p ^ 3 * k ^ 2\"\n  have l: \"l > 0\"\n    using p k by (auto simp: l_def)\n  define f :: \"real \\<Rightarrow> real\" where \"f = (\\<lambda>x. exp (-l / x))\"\n  define f' where \"f' = (\\<lambda>x. -l * exp (-l / x) / x ^ 2)\"\n\n  have f'_mono: \"f' x \\<le> f' y\" if \"x \\<ge> l / 2\" \"x \\<le> y\" for x y :: real\n    using that(2)\n  proof (rule DERIV_nonneg_imp_nondecreasing)\n    fix t assume t: \"x \\<le> t\" \"t \\<le> y\"\n    have \"t > 0\"\n      using that l t by auto\n    have \"(f' has_field_derivative (l * (2 * t - l) / (exp (l / t) * t ^ 4))) (at t)\"\n      unfolding f'_def using t that \\<open>t > 0\\<close>\n      by (auto intro!: derivative_eq_intros simp: field_simps exp_minus simp flip: power_Suc)\n    moreover have \"l * (2 * t - l) / (exp (l / t) * t ^ 4) \\<ge> 0\"\n      using that t l by (intro divide_nonneg_pos mult_nonneg_nonneg) auto\n    ultimately show \"\\<exists>y. (f' has_real_derivative y) (at t) \\<and> 0 \\<le> y\" by blast\n  qed\n\n  have convex: \"convex_on {l/2..} (\\<lambda>x. -f x)\" unfolding f_def\n  proof (intro convex_on_realI[where f' = f'])\n    show \"((\\<lambda>x. - exp (- l / x)) has_real_derivative f' x) (at x)\" if \"x \\<in> {l/2..}\" for x\n      using that l\n      by (auto intro!: derivative_eq_intros simp: f'_def power2_eq_square algebra_simps)\n  qed (use l in \\<open>auto intro!: f'_mono\\<close>)\n\n  have eq: \"{x. \\<bar>real x - \\<mu>\\<bar> \\<ge> k} = {x. real x \\<le> \\<mu> - k} \\<union> {x. real x \\<ge> \\<mu> + k}\"\n    by auto\n  have \"measure_pmf.prob (neg_binomial_pmf n p) {x. \\<bar>real x - \\<mu>\\<bar> \\<ge> k} \\<le>\n        measure_pmf.prob (neg_binomial_pmf n p) {x. real x \\<le> \\<mu> - k} +\n        measure_pmf.prob (neg_binomial_pmf n p) {x. real x \\<ge> \\<mu> + k}\"\n    by (subst eq, rule measure_Un_le) auto\n  also have \"\\<dots> \\<le> exp (-2 * p ^ 3 * k\\<^sup>2 / (n - p * k)) + exp (-2 * p ^ 3 * k\\<^sup>2 / (n + p * k))\"\n    unfolding \\<mu>_def\n    by (intro prob_neg_binomial_pmf_le_bound prob_neg_binomial_pmf_ge_bound add_mono \\<open>k \\<ge> 0\\<close>)\n  also have \"\\<dots> = 2 * (1/2 * f (n - p * k) + 1/2 * f (n + p * k))\"\n    by (simp add: f_def l_def)\n  also have \"1/2 * f (n - p * k) + 1/2 * f (n + p * k) \\<le> f (1/2 * (n - p * k) + 1/2 * (n + p * k))\"\n  proof -\n    let ?x = \"n - p * k\" and ?y = \"n + p * k\"\n    have le1: \"l / 2 \\<le> ?x\" using n_ge\n      by (simp add: l_def power2_eq_square power3_eq_cube algebra_simps)\n    also have \"\\<dots> \\<le> ?y\"\n      using p k by simp\n    finally have le2: \"l / 2 \\<le> ?y\" .\n    have \"-f ((1 - 1 / 2) *\\<^sub>R ?x + (1 / 2) *\\<^sub>R ?y) \\<le> (1 - 1 / 2) * - f ?x + 1 / 2 * - f ?y\"\n      using le1 le2 by (intro convex_onD[OF convex]) auto\n    thus ?thesis by simp\n  qed\n  also have \"1/2 * (n - p * k) + 1/2 * (n + p * k) = n\"\n    by (simp add: algebra_simps)\n  also have \"2 * f n = 2 * exp (-l / n)\"\n    by (simp add: f_def)\n  finally show ?thesis\n    by (simp add: l_def)\nqed auto\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/Probability/Hoeffding.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246035907933, "lm_q2_score": 0.8705972717658209, "lm_q1q2_score": 0.7254901263814788}}
{"text": "theory Ex4_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 4.5:\n\nby: Vadim Zaliva with help from Jeremy Johnson\n*)\n\n(* terminals *)\ndatatype alpha = a | b \n\n(* empty word defintion.\nNB: This is syntactic sugar. We might as well used [] in the contexts where the type of [] could be derived automaticlaly *)\ndefinition \\<epsilon> :: \"alpha list\" where \"\\<epsilon>=[]\"\n\ninductive S :: \"(alpha list) \\<Rightarrow> bool\" where\n  empty: \"S \\<epsilon>\"\n  | paren: \"S w \\<Longrightarrow> S (a # w @ [b])\"\n  | repeat: \"\\<lbrakk>S x; S y \\<rbrakk> \\<Longrightarrow> S (x@y)\"\n\ninductive T :: \"(alpha list) \\<Rightarrow> bool\" where\n  empty: \"T \\<epsilon>\"\n  | interleave: \"\\<lbrakk>T x; T y \\<rbrakk> \\<Longrightarrow> T (x@[a]@y@[b])\"\n\nlemma TS : \"T w \\<Longrightarrow> S w \"\n  apply(induction rule: T.induct)\n  apply(rule S.empty)\n  apply(rule S.repeat)\n  apply(simp)\n  apply(simp)\n  apply(rule S.paren)\n  apply(simp)\ndone\n\nlemma T01: \"T (a#w@[b]) = T (\\<epsilon> @ [a] @ w @ [b])\"\n  apply(simp add: \\<epsilon>_def)\ndone\n\nlemma simpTI : \"T (x @ a # y @ [b]) = T (x @ [a] @ y @ [b])\"\n  apply(auto)\ndone\n \n\nlemma Tgroup : \"T(x1 @ x2 @ [a] @ y @ [b]) = T((x1 @ x2) @ [a] @ y @ [b])\"\napply (auto)\ndone\n\nlemma Tconcat : \"\\<lbrakk>T w2; T w1 \\<rbrakk> \\<Longrightarrow> T (w1 @ w2)\"\napply (induction rule: T.induct)\napply(simp add: \\<epsilon>_def)\napply (simp only: Tgroup)\napply (rule T.interleave)\napply (auto)\ndone\n\nlemma ST : \"S w \\<Longrightarrow> T w\"\napply (induction rule: S.induct)\napply (rule T.empty)\napply (simp only: T01)\napply (rule T.interleave)\napply (rule T.empty)\napply(simp add: \\<epsilon>_def)\napply (simp only: Tconcat) \ndone\n\ntheorem eqST : \"S w = T w \"\n  apply(auto)\n  apply(rule ST)\n  apply(simp)\n  apply(rule TS)\n  apply(simp)\ndone\n\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/Ex4_5.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972684083609, "lm_q2_score": 0.8333245994514084, "lm_q1q2_score": 0.7254901199798877}}
{"text": "section {* \\isaheader{Example for Foreach-Loops} *}\ntheory Foreach_Refine\nimports \n  \"../../Refine_Dflt_Only_ICF\" \nbegin\n\ntext {*\n  This example presents the usage of the foreach loop.\n  We define a simple foreach loop that looks for the largest element with\n  a given property. Ordered loops are used to be sure to find the largest one.\n*}\n\nsubsection {* Definition *}\n\ndefinition find_max_invar where\n  \"find_max_invar P S it \\<sigma> = \n     (case \\<sigma> of None \\<Rightarrow> (\\<forall>x \\<in> S - it. \\<not>(P x))\n             | Some y \\<Rightarrow> (P y \\<and> y \\<in> S-it \\<and> (\\<forall>x \\<in> S - it - {y}. \\<not>(P x))))\"\n\ndefinition find_max :: \"('a::{linorder} \\<Rightarrow> bool) \\<Rightarrow> 'a set \\<Rightarrow> ('a option) nres\" where\n  \"find_max P S \\<equiv> \n   FOREACHoci (op\\<ge>) (find_max_invar P S) S\n     (\\<lambda>\\<sigma>. \\<sigma> = None) (\\<lambda>x _. RETURN (if P x then Some x else None)) None\"\n\nsubsection {* Correctness *}\ntext {* As simple correctness property, we show:\n  If the algorithm returns the maximal element satisfying @{text \"P\"}.\n*}\nlemma find_max_correct:\n  fixes S:: \"'a::{linorder} set\"\n  assumes \"finite S\"\n  shows \"find_max P S \\<le> SPEC (\\<lambda>\\<sigma>. case \\<sigma> of None \\<Rightarrow> \\<forall>x\\<in>S. \\<not>(P x)\n                                          | Some y \\<Rightarrow> (P y \\<and> y \\<in> S \\<and> (\\<forall>x\\<in>S. P x \\<longrightarrow> y \\<ge> x)))\"\n  unfolding find_max_def\nproof (rule FOREACHoci_rule)\n  show \"finite S\" by fact\nnext\n  show \"find_max_invar P S S None\" \n  unfolding find_max_invar_def by simp\nnext\n  fix x it \\<sigma>\n  assume \"\\<sigma> = None\"\n         \"x \\<in> it\"\n         \"it \\<subseteq> S\"\n         \"find_max_invar P S it \\<sigma>\"\n         \"\\<forall>y\\<in>it - {x}. y \\<le> x\"\n         \"\\<forall>y\\<in>S - it. x \\<le> y\"\n\n  from `find_max_invar P S it \\<sigma>` `\\<sigma> = None` \n  have not_P_others: \"\\<forall>x\\<in>S - it. \\<not> P x\"\n    by (simp add: find_max_invar_def)\n\n  from `x \\<in> it` `it \\<subseteq> S` have \"x \\<in> S\" by blast\n\n  show \"RETURN (if P x then Some x else None) \\<le> SPEC (find_max_invar P S (it - {x}))\"\n    using not_P_others `x \\<in> S`\n    by (auto simp add: find_max_invar_def)\nnext\n  fix \\<sigma>\n  assume \"find_max_invar P S {} \\<sigma>\"\n  thus \"case \\<sigma> of None \\<Rightarrow> \\<forall>x\\<in>S. \\<not> P x\n        | Some y \\<Rightarrow> P y \\<and> y \\<in> S \\<and> (\\<forall>x\\<in>S. P x \\<longrightarrow> x \\<le> y)\"\n    by (cases \\<sigma>, auto simp add: find_max_invar_def)\nnext\n  fix it \\<sigma>\n  assume \"it \\<noteq> {}\"\n         \"it \\<subseteq> S\"\n         \"find_max_invar P S it \\<sigma>\"\n         \"\\<sigma> \\<noteq> None\"\n         \"\\<forall>x\\<in>it. \\<forall>y\\<in>S - it. x \\<le> y\"\n\n  from `\\<sigma> \\<noteq> None` obtain y where \\<sigma>_eq[simp]: \"\\<sigma> = Some y\" by auto\n  from `find_max_invar P S it \\<sigma>` \n    have y_props[simp]: \"P y\" \"y \\<in> S\" \"y \\<notin> it\" and not_P: \"\\<forall>x\\<in>S - it - {y}. \\<not> P x\"\n    by (simp_all add: find_max_invar_def)\n \n  { fix x\n    assume \"x \\<in> S\" \"P x\"\n    with not_P have \"x \\<in> it \\<or> x = y\" by auto\n    with `\\<forall>x\\<in>it. \\<forall>y\\<in>S - it. x \\<le> y` y_props have \"x \\<le> y\" by auto\n  } note less_eq_y = this\n\n  show \"case \\<sigma> of None \\<Rightarrow> \\<forall>x\\<in>S. \\<not> P x\n        | Some y \\<Rightarrow> P y \\<and> y \\<in> S \\<and> (\\<forall>x\\<in>S. P x \\<longrightarrow> x \\<le> y)\" \n   by (simp add: find_max_invar_def Ball_def less_eq_y)\nqed\n\nsubsection {* Data Refinement and Determinization *}\ntext {*\n  Next, we use automatic data refinement and transfer to generate an\n  executable algorithm using a red-black-tree. \n*}\nschematic_goal find_max_impl_refine_aux:\n  assumes invar_S: \"rs.invar S\"\n  shows \"RETURN (?f) \\<le> (find_max P (rs.\\<alpha> S))\"\n  unfolding find_max_def\n  by (refine_transfer \n    RBTSetImpl.rs.rev_iterateoi_correct[unfolded set_iterator_rev_linord_def,\n    OF invar_S])\n\nconcrete_definition find_max_impl for P S uses find_max_impl_refine_aux\n\nlemma find_max_impl_refine:\n  assumes invar_S: \"rs.invar S\"\n  shows \"RETURN (find_max_impl P S) \\<le> (find_max P (rs.\\<alpha> S))\"\n  using assms by (rule find_max_impl.refine)\n\nsubsubsection {* Executable Code *}\n\nlemma find_max_impl_correct :\nassumes invar_S: \"rs.invar S\"\nshows \"case find_max_impl P S of None \\<Rightarrow> \\<forall>x\\<in>rs.\\<alpha> S. \\<not>(P x)\n                               | Some y \\<Rightarrow> (P y \\<and> y \\<in> (rs.\\<alpha> S) \n                                 \\<and> (\\<forall>x\\<in>rs.\\<alpha> S. P x \\<longrightarrow> y \\<ge> x))\"\nproof -\n  note find_max_impl_refine [of S P, OF invar_S]\n  also note find_max_correct [OF RBTSetImpl.rs.finite[of S, OF invar_S], of P]\n  finally show ?thesis by simp\nqed\n\ntext {* Finally, we can generate code *}\nexport_code find_max_impl in SML\nexport_code find_max_impl in OCaml\nexport_code find_max_impl in Haskell\nexport_code find_max_impl in Scala\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/Examples/Refine_Monadic/Foreach_Refine.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8596637577007393, "lm_q2_score": 0.8438950966654774, "lm_q1q2_score": 0.7254660299046729}}
{"text": "chapter \\<open>Set and bool as a pointed cpo.\\<close>\n\ntheory SetPcpo\nimports HOLCF LNat\nbegin\n\ntext \\<open>PCPO on sets and bools. The \\<open>\\<sqsubseteq>\\<close> operator of the order is defined as the \\<open>\\<subseteq>\\<close> operator on sets\n  and as \\<open>\\<longrightarrow>\\<close> on booleans.\n\\<close>\n\n(* ----------------------------------------------------------------------- *)\nsection \\<open>Order on sets.\\<close>\n(* ----------------------------------------------------------------------- *)\n\ntext \\<open>{text \"\\<sqsubseteq>\"} operator as the \\<open>\\<subseteq>\\<close> operator on sets -> partial order.\\<close>\ninstantiation set :: (type) po\nbegin\n  definition less_set_def: \"(\\<sqsubseteq>) = (\\<subseteq>)\"\ninstance\napply intro_classes\napply (simp add: less_set_def)\napply (simp add: less_set_def)\napply (simp add: less_set_def)\ndone\nend\n\ntext \\<open>The least upper bound on sets corresponds to the \\<open>Union\\<close> operator.\\<close>\nlemma Union_is_lub: \"A <<| \\<Union>A\"\napply (simp add: is_lub_def)\napply (simp add: is_ub_def)\napply (simp add: less_set_def Union_upper)\napply (simp add: Sup_least)\ndone\n\ntext \\<open>Another needed variant of the fact that lub on sets corresponds to union.\\<close>\nlemma lub_eq_Union: \"lub = Union\"\napply (rule ext)\napply (rule lub_eqI [OF Union_is_lub])\ndone\n\ntext \\<open>The partial order on sets is complete.\\<close>\ninstance set :: (type) cpo\napply intro_classes\nusing Union_is_lub \napply auto\ndone\n\ntext \\<open>Sets are also pcpo`s, pointed with \\<open>{}\\<close> as minimal element.\\<close>\ninstance set :: (type) pcpo\napply intro_classes\napply (rule_tac x= \"{}\" in exI)\napply (simp add: less_set_def)\ndone\n\ntext \\<open>For sets, the minimal element is the empty set.\\<close>\nlemma UU_eq_empty: \"\\<bottom> = {}\"\napply (simp add: less_set_def bottomI)\ndone\n\ntext \\<open>We group the following lemmas in order to simplify future proofs.\\<close>\nlemmas set_cpo_simps = less_set_def lub_eq_Union UU_eq_empty\n\n(* ----------------------------------------------------------------------- *)\nsection \\<open>Order on booleans.\\<close>\n(* ----------------------------------------------------------------------- *)\n\ntext \\<open>If one defines the \\<open>\\<sqsubseteq>\\<close> operator as the \\<open>\\<longrightarrow>\\<close> operator on booleans,\n  one obtains a partial order.\\<close>\ninstantiation bool :: po\nbegin\n  definition less_bool_def: \"(\\<sqsubseteq>) = (\\<longrightarrow>)\"\ninstance\napply intro_classes\napply (simp add: less_bool_def)\napply (simp add: less_bool_def)\napply (simp add: less_bool_def)\napply (simp add: less_bool_def)\napply auto\ndone\nend\n\ntext \\<open>Chains of bools are always finite. This is needed to prove that bool is a cpo.\\<close>\ninstance bool :: chfin\nproof\n  fix S:: \"nat \\<Rightarrow> bool\"\n  assume S: \"chain S\"\n  then have \"finite (range S)\" \n  apply simp\n  done\n  from S and this \n  have \"finite_chain S\" \n  apply (rule finite_range_imp_finch)\n  done\n  thus \"\\<exists> n. max_in_chain n S\" \n  apply (unfold finite_chain_def, simp)\n  done\nqed\n\ntext \\<open>The partial order on bools is complete.\\<close>\ninstance bool :: cpo ..\n\ntext \\<open>Bools are also pointed with \\<open>False\\<close> as minimal element.\\<close>\ninstance bool :: pcpo\nproof\n  have \"\\<forall>y::bool. False \\<sqsubseteq> y\" \n  unfolding less_bool_def \n  apply simp\n  done\n  thus \"\\<exists>x::bool. \\<forall>y. x \\<sqsubseteq> y\" ..\nqed\n\n(* ----------------------------------------------------------------------- *)\nsection \\<open>Properties\\<close>\n(* ----------------------------------------------------------------------- *)\n\n(* ----------------------------------------------------------------------- *)\nsubsection \\<open>Admissibility of set predicates\\<close>\n(* ----------------------------------------------------------------------- *)\n\ntext \\<open>The predicate \"\\<lambda>A. \\<exists>x. x \\<in> A\" is admissible.\\<close>\nlemma adm_nonempty: \"adm (\\<lambda>A. \\<exists>x. x \\<in> A)\"\napply (rule admI)\napply (simp add: lub_eq_Union)\napply force\ndone\n\ntext \\<open>The predicate \"\\<lambda>A. x \\<in> A\" is admissible.\\<close>\nlemma adm_in: \"adm (\\<lambda>A. x \\<in> A)\"\napply (rule admI)\napply (simp add: lub_eq_Union)\ndone\n\ntext \\<open>The predicate \"\\<lambda>A. x \\<notin> A\" is admissible.\\<close>\nlemma adm_not_in: \"adm (\\<lambda>A. x \\<notin> A)\"\napply (rule admI)\napply (simp add: lub_eq_Union)\ndone\n\ntext \\<open>If for all x the predicate \"\\<lambda>A. P A x\" is admissible, then so is \"\\<lambda>A. \\<forall>x\\<in>A. P A x\".\\<close>\nlemma adm_Ball: \"(\\<And>x. adm (\\<lambda>A. P A x)) \\<Longrightarrow> adm (\\<lambda>A. \\<forall>x\\<in>A. P A x)\"\napply (simp add: Ball_def)\napply (simp add: adm_not_in)\ndone\n\ntext \\<open>The predicate \"\\<lambda>A. Bex A P\", which means \"\\<lambda>A. \\<exists>x. x \\<in> A \\<and> P x\" is admissible.\\<close>\nlemma adm_Bex: \"adm (\\<lambda>A. Bex A P)\"\napply (rule admI)\napply (simp add: lub_eq_Union)\ndone\n\ntext \\<open>The predicate \"\\<lambda>A. A \\<subseteq> B\" is admissible.\\<close>\nlemma adm_subset: \"adm (\\<lambda>A. A \\<subseteq> B)\"\napply (rule admI)\napply (simp add: lub_eq_Union)\napply auto\ndone\n\ntext \\<open>The predicate \"\\<lambda>A. B \\<subseteq> A\" is admissible.\\<close>\nlemma adm_superset: \"adm (\\<lambda>A. B \\<subseteq> A)\"\napply (rule admI)\napply (simp add: lub_eq_Union)\napply auto\ndone\n\ntext \\<open>We group the following lemmas in order to simplify future proofs.\\<close>\nlemmas adm_set_lemmas = adm_nonempty adm_in adm_not_in adm_Bex adm_Ball adm_subset adm_superset\n\n(* ----------------------------------------------------------------------- *)\nsubsection \\<open>Compactness\\<close>\n(* ----------------------------------------------------------------------- *)\n\ntext \\<open>The bottom element of the set cpo ist compact.\\<close>\nlemma compact_empty: \"compact {}\"\napply (fold UU_eq_empty)\napply simp\ndone\n\ntext \\<open>Induction step for compact sets: \nIf a set is compact and we insert an element into it, then the compactness is preserved.\\<close>\nlemma compact_insert: \"compact A \\<Longrightarrow> compact (insert x A)\"\napply (simp add: compact_def)\napply (simp add: set_cpo_simps)\napply (simp add: adm_set_lemmas)\ndone\n\ntext \\<open>The compactness of finite sets is proven by induction from the lemma above.\\<close>\nlemma finite_imp_compact: \"finite A \\<Longrightarrow> compact A\"\napply (induct A set: finite)\napply (rule compact_empty)\napply (erule compact_insert)\ndone\n\nlemma union_cont:\"cont (\\<lambda>S2. union S1 S2)\"\n  apply(rule contI)\n  unfolding  SetPcpo.less_set_def\n  unfolding lub_eq_Union \n  by (metis (no_types, lifting) UN_simps(3) Union_is_lub empty_not_UNIV lub_eq lub_eqI)\n\n\n\n\n\nsection \\<open>setify\\<close>\ndefinition setify_on::\"'m set \\<Rightarrow> ('m::type \\<Rightarrow> ('n::type set)) \\<Rightarrow> ('m \\<Rightarrow> 'n) set\" where\n\"setify_on Dom \\<equiv> \\<lambda> f. {g. \\<forall>m\\<in>Dom. g m \\<in> (f m)}\"\n\ndefinition setify::\"('m::type \\<Rightarrow> ('n::type set)) \\<Rightarrow> ('m \\<Rightarrow> 'n) set\" where\n\"setify \\<equiv> \\<lambda> f. {g. \\<forall>m. g m \\<in> (f m)}\"\n\n\n\nsubsection \\<open>setify_on\\<close>\nthm setify_def\nlemma setify_on_mono[simp]: \"\\<And> Dom. monofun (\\<lambda> f. {g. \\<forall>m\\<in>Dom. g m \\<in> (f m)})\"\nproof (rule monofunI, simp add: less_set_def, rule)\n  fix x y::\"'m::type \\<Rightarrow> ('n::type set)\"  \n  fix Dom::\"'m set\"\n  fix xa:: \"'m \\<Rightarrow> 'n\"\n  assume a1:\"x \\<sqsubseteq> y\"\n  assume a2: \"xa \\<in> {g. \\<forall>m\\<in>Dom. g m \\<in> x m}\"\n  have f0: \"\\<And>m. x m \\<sqsubseteq> y m\"\n    by (simp add: a1 fun_belowD)\n  have f1: \"\\<And>m. m \\<in> Dom \\<Longrightarrow> xa m \\<in> x m\"\n    using a2 by blast\n  have f2: \"\\<And>m. m \\<in> Dom \\<Longrightarrow> xa m \\<in> y m\"\n    by (metis SetPcpo.less_set_def f0 f1 subsetCE)\n  show \"xa \\<in> {g. \\<forall>m\\<in>Dom. g m \\<in> y m}\"\n    using f2 by blast\nqed\n\nlemma setify_on_empty:\"\\<And> Dom. sbe \\<in> Dom \\<Longrightarrow> f sbe = {} \\<Longrightarrow> setify_on Dom f = {}\"\n  apply(simp add: setify_on_def)\n  by (metis empty_iff)\n\nlemma setify_on_notempty_ex:\"setify_on Dom f \\<noteq> {} \\<Longrightarrow> \\<exists>g.(\\<forall>m \\<in> Dom. g m \\<in> (f m))\"\n  by (metis (no_types, lifting) Collect_empty_eq setify_on_def)\n\nlemma setify_on_notempty:assumes \"\\<forall>m \\<in> Dom. f m \\<noteq> {}\" shows\" setify_on Dom f \\<noteq> {}\"\nproof(simp add: setify_on_def)\n  have \"\\<forall>m \\<in> Dom. (\\<exists>x. x\\<in>((f m)))\"\n    by (metis all_not_in_conv assms)\n  have \"\\<forall>m \\<in> Dom. (\\<lambda>e. SOME x. x\\<in> (f e)) m \\<in> (f m)\"\n    by (metis assms some_in_eq)\n  then show \"\\<exists>x::'a \\<Rightarrow> 'b. \\<forall>m::'a \\<in> Dom. x m \\<in> (f m)\"\n    by(rule_tac x=\"(\\<lambda>e. SOME x. x\\<in> (f e))\" in exI, auto)\nqed\n\nlemma setify_on_final:assumes \"\\<forall>m \\<in> Dom. f m \\<noteq> {}\" and \"x \\<in> (f m)\" \n  shows\"\\<exists>g\\<in>((setify_on Dom f)). g m = x\"\nproof(simp add: setify_on_def)         \n  have \"\\<exists>g.(\\<forall>m \\<in> Dom. g m \\<in> (f m))\"\n    by(simp add: setify_on_notempty setify_on_notempty_ex assms(1))\n  then obtain g where g_def:\"(\\<forall>m \\<in> Dom. g m \\<in> (f m))\"\n    by auto\n  have g2_def:\"\\<forall>n \\<in> Dom. (\\<lambda>e. if e = m then x else g e) n \\<in> (f n)\"\n    by (simp add: assms(2) g_def)\n  then show \"\\<exists>g::'a \\<Rightarrow> 'b. (\\<forall>m::'a \\<in> Dom. g m \\<in> (f m)) \\<and> g m = x\"     \n    by(rule_tac x=\"(\\<lambda>e. if e = m then x else g e)\" in exI, auto) \nqed\n\n\n\nsubsection \\<open>setify\\<close>\nlemma setify_mono[simp]:\"monofun (\\<lambda>f. {g. \\<forall>m. g m \\<in> (f m)})\"\n  apply(rule monofunI)\n  by (smt Collect_mono SetPcpo.less_set_def below_fun_def subsetCE)\n\nlemma setify_cont[simp]:\"cont (\\<lambda>f. {g. \\<forall>m. g m \\<in> ((f m))})\"\nproof(rule Cont.contI2, simp)\n  fix Y::\"nat \\<Rightarrow> 'a \\<Rightarrow> 'b set\"\n  assume a1:\"chain Y\"\n  assume a2:\"chain (\\<lambda>i::nat. {g::'a \\<Rightarrow> 'b. \\<forall>m::'a. g m \\<in> (Y i m)})\"\n  have a3:\"\\<forall>m. chain (\\<lambda>i. Y i m)\"\n    by (simp add: a1 ch2ch_fun)\n  then have \"\\<forall>m.((\\<Squnion>i::nat. Y i) m) = (\\<Squnion>i::nat. Y i m)\"\n    by (simp add: a1 lub_fun)\n  show \"{g::'a \\<Rightarrow> 'b. \\<forall>m::'a. g m \\<in> ((\\<Squnion>i::nat. Y i) m)} \\<sqsubseteq> (\\<Squnion>i::nat. {g::'a \\<Rightarrow> 'b. \\<forall>m::'a. g m \\<in>  (Y i m)})\"\n    apply(simp add: lub_eq_Union less_set_def)\n    apply auto\n    oops\n\n(*\nlemma setify_insert:\"setify\\<cdot>f = Rev {g. \\<forall>m. g m \\<in> (inv Rev(f m))}\"\n  by(simp add: setify_def)\n  *)\nlemma setify_empty:\"f m = {} \\<Longrightarrow> setify f = {}\"\n  apply(simp add: setify_def)\n  by (metis empty_iff)\n    \nlemma setify_notempty:assumes \"\\<forall>m. f m \\<noteq> {}\" shows\" setify f \\<noteq> {}\"\nproof(simp add: setify_def)\n  have \"\\<forall>m. \\<exists>x. x\\<in>((f m))\"\n    by (metis all_not_in_conv assms)\n  have \"\\<forall>m. (\\<lambda>e. SOME x. x\\<in> (f e)) m \\<in> (f m)\"\n    by (metis assms some_in_eq)\n  then show \"\\<exists>x::'a \\<Rightarrow> 'b. \\<forall>m::'a. x m \\<in> (f m)\"\n    by(rule_tac x=\"(\\<lambda>e. SOME x. x\\<in> (f e))\" in exI, auto)\nqed\n  \nlemma setify_notempty_ex:\"setify f \\<noteq> {} \\<Longrightarrow> \\<exists>g.(\\<forall>m. g m \\<in> (f m))\"\n  by(simp add: setify_def)\n  \nlemma setify_final:assumes \"\\<forall>m. f m \\<noteq> {}\" and \"x \\<in> (f m)\" shows\"\\<exists>g\\<in>((setify f)). g m = x\"\nproof(simp add: setify_def)\n  have \"\\<exists>g.(\\<forall>m. g m \\<in> (f m))\"\n    by(simp add: setify_notempty setify_notempty_ex assms(1))\n  then obtain g where g_def:\"(\\<forall>m. g m \\<in> (f m))\"\n    by auto\n  have g2_def:\"\\<forall>n. (\\<lambda>e. if e = m then x else g e) n \\<in> (f n)\"\n    by (simp add: assms(2) g_def)\n  then show \"\\<exists>g::'a \\<Rightarrow> 'b. (\\<forall>m::'a. g m \\<in> (f m)) \\<and> g m = x\"     \n    by(rule_tac x=\"(\\<lambda>e. if e = m then x else g e)\" in exI, auto) \nqed\n\n\n\ninductive setSize_helper :: \"'a set \\<Rightarrow> nat \\<Rightarrow> bool\"\n  where\n    \"setSize_helper {} 0\"\n  |  \"setSize_helper A X \\<and> a \\<notin> A \\<Longrightarrow> setSize_helper (insert a A) (Suc X)\"\n\ndefinition setSize :: \"'a set \\<Rightarrow> lnat\"\n  where\n  \"setSize X \\<equiv> if (finite X) then Fin (THE Y. setSize_helper X Y) else \\<infinity>\"\n\n\nlemma setSizeEx: assumes \"finite X\" shows \"\\<exists> Y. setSize_helper X Y\"\n  apply (rule finite_induct)\n  apply (simp add: assms)\n  using setSize_helper.intros(1) apply auto[1]\n  by (metis setSize_helper.simps)\n\nlemma setSize_remove: \"y \\<in> F \\<and> setSize_helper (F - {y}) A \\<longrightarrow> setSize_helper F (Suc A)\"\n  by (metis Diff_insert_absorb Set.set_insert setSize_helper.intros(2))\n\n\nlemma setSizeBack_helper:  \n  assumes \"\\<forall>(F::'a set) x::'a. (finite F \\<and> setSize_helper (insert x F) (Suc A) \\<and> x \\<notin> F) \\<longrightarrow> setSize_helper F A\"\n  shows \"\\<forall>(F::'a set) x::'a. (finite F \\<and> setSize_helper (insert x F) (Suc (Suc A)) \\<and> x \\<notin> F) \\<longrightarrow> setSize_helper F (Suc A)\"\nproof -\nhave b0: \"\\<And>A::nat. \\<forall>(F::'a set) x::'a. ((setSize_helper (insert x F) (Suc (Suc A)) \\<and> x \\<notin> F) \n  \\<longrightarrow> (\\<exists> y. y \\<in> (insert x F) \\<and> setSize_helper ((insert x F) - {y}) (Suc A)))\"\n    by (metis Diff_insert_absorb add_diff_cancel_left' insertI1 insert_not_empty plus_1_eq_Suc setSize_helper.simps)\nhave b1: \"\\<forall>(F::'a set) (x::'a) y::'a. ((finite F \\<and> setSize_helper (insert x (F - {y})) (Suc A) \\<and> x \\<notin> F)\n  \\<longrightarrow> setSize_helper (F - {y}) A)\"\n  using assms by auto\nhave b2: \"\\<forall>(F::'a set) x::'a. (setSize_helper (insert x F) (Suc (Suc A)) \\<and> x \\<notin> F) \n  \\<longrightarrow> ((\\<exists> y. (y\\<noteq>x \\<and> y \\<in> F \\<and> setSize_helper (insert x (F - {y})) (Suc A))) \\<or> setSize_helper F (Suc A))\"\n  by (metis Diff_insert_absorb b0 empty_iff insert_Diff_if insert_iff)\nhave b3: \"\\<forall>(F::'a set) x::'a. (setSize_helper (insert x F) (Suc (Suc A)) \\<and> x \\<notin> F \\<and> finite F) \n  \\<longrightarrow> ((\\<exists> y. (y\\<noteq>x \\<and> y \\<in> F \\<and> setSize_helper (F - {y}) A)) \\<or> setSize_helper F (Suc A))\"\n  by (meson b1 b2)\nshow \"\\<forall>(F::'a set) x::'a. (finite F \\<and> setSize_helper (insert x F) (Suc (Suc A)) \\<and> x \\<notin> F) \\<longrightarrow> setSize_helper F (Suc A)\"\n  by (meson b3 setSize_remove)\nqed\n\n\nlemma setSizeBack: \"\\<And> F x. (finite F \\<and> setSize_helper (insert x F) (Suc A) \\<and> x \\<notin> F) \\<Longrightarrow> setSize_helper F A\"\n  apply (induction A)\n  apply (metis Suc_inject empty_iff insertI1 insert_eq_iff nat.distinct(1) setSize_helper.simps)\n  using setSizeBack_helper by blast\n\n\nlemma setSizeonlyOne: assumes \"finite X\" shows \"\\<exists>! Y. setSize_helper X Y\"\n  apply (rule finite_induct)\n  apply (simp add: assms)\n  apply (metis empty_not_insert setSize_helper.simps)\n  by (metis insert_not_empty setSizeBack setSize_helper.intros(2) setSize_helper.simps)\n\nlemma setSizeSuc: assumes \"finite X\" and \"z \\<notin> X\" shows \"setSize (insert z X) = lnsuc\\<cdot>(setSize X)\"\n  apply (simp add: setSize_def)\n  using assms setSizeonlyOne\n  by (metis (mono_tags, lifting) Diff_insert_absorb finite.insertI insertI1 setSize_remove theI_unique)\n\nlemma setSizeEmpty: \"setSize {} = Fin 0\"\n  by (metis finite.emptyI setSize_def setSize_helper.intros(1) setSizeonlyOne theI_unique)\n\nlemma setSizeSingleton: \"setSize {x} = lnsuc\\<cdot>(Fin 0)\"\n  by (simp add: setSizeEmpty setSizeSuc)\n\nlemma setsize_union_helper1: \n  assumes \"finite F\"\n      and \"x \\<notin> F\"\n      and \"x \\<notin> X\"\n    shows \"setSize (X \\<union> F) + setSize (X \\<inter> F) = setSize X + setSize F \\<Longrightarrow>\n       setSize (X \\<union> insert x F) + setSize (X \\<inter> insert x F) = setSize X + setSize (insert x F)\"\nproof - \n  assume a0: \"setSize (X \\<union> F) + setSize (X \\<inter> F) = setSize X + setSize F\"\n  have b0: \"X \\<union> insert x F = insert x (X \\<union> F)\"\n    by simp\n  have b1: \"setSize (X \\<union> insert x F) = lnsuc\\<cdot>(setSize (X \\<union> F))\"\n    by (metis Un_iff Un_infinite assms(1) assms(2) assms(3) b0 finite_UnI fold_inf setSizeSuc setSize_def sup_commute)\n  have b2: \"setSize (X \\<inter> insert x F) = setSize (X \\<inter> F)\"\n    by (simp add: assms(3)) \n  show \"setSize (X \\<union> insert x F) + setSize (X \\<inter> insert x F) = setSize X + setSize (insert x F)\"\n    by (metis (no_types, lifting) a0 ab_semigroup_add_class.add_ac(1) add.commute assms(1) assms(2) \n      b1 b2 lnat_plus_suc setSizeSuc)\nqed\n\nlemma setsize_union_helper2: \n  assumes \"finite F\"\n      and \"x \\<notin> F\"\n      and \"x \\<in> X\"\n    shows \"setSize (X \\<union> F) + setSize (X \\<inter> F) = setSize X + setSize F \\<Longrightarrow>\n       setSize (X \\<union> insert x F) + setSize (X \\<inter> insert x F) = setSize X + setSize (insert x F)\"\nproof -\n  assume a0: \"setSize (X \\<union> F) + setSize (X \\<inter> F) = setSize X + setSize F\"\n  have b0: \"setSize (X \\<union> insert x F) = setSize (X \\<union> F)\"\n    by (metis Un_Diff_cancel assms(3) insert_Diff1)\n  have b1: \"setSize (X \\<inter> insert x F) =  lnsuc\\<cdot>(setSize (X \\<inter> F))\"\n    by (simp add: assms(1) assms(2) assms(3) setSizeSuc)\n  show \"setSize (X \\<union> insert x F) + setSize (X \\<inter> insert x F) = setSize X + setSize (insert x F)\"\n    by (metis a0 ab_semigroup_add_class.add_ac(1) assms(1) assms(2) b0 b1 lnat_plus_suc setSizeSuc)\nqed\n\nlemma setsize_union_helper3: assumes \"finite X\" and \"finite Y\"\n  shows \"setSize (X \\<union> Y) + setSize (X \\<inter> Y) = setSize X + setSize Y\"\n  apply (rule finite_induct)\n  apply (simp add: assms)\n  apply simp\n  by (meson setsize_union_helper1 setsize_union_helper2)\n\nlemma setsize_union_helper4: assumes \"infinite X \\<or> infinite Y\"\n  shows \"setSize (X \\<union> Y) + setSize (X \\<inter> Y) = setSize X + setSize Y\"\nproof -\n  have b0: \"setSize (X \\<union> Y) = \\<infinity>\"\n    by (metis (full_types) assms infinite_Un setSize_def)\n  have b1: \"setSize X = \\<infinity> \\<or> setSize Y = \\<infinity>\"\n    by (meson assms setSize_def)\n  show ?thesis\n    using b0 b1 plus_lnatInf_r by auto\nqed\n\nlemma setsize_union: \"setSize (X \\<union> Y) + setSize (X \\<inter> Y) = setSize X + setSize Y\"\n  by (meson setsize_union_helper3 setsize_union_helper4)\n\nlemma setsize_union_disjoint: assumes \"X \\<inter> Y = {}\"\n  shows \"setSize (X \\<union> Y) = setSize X + setSize Y\"\n  by (metis Fin_02bot add.left_neutral assms bot_is_0 lnat_plus_commu setSizeEmpty setsize_union)\n\nlemma setsize_subset_union: assumes \"X \\<subseteq> Y\"\n  shows \"setSize (X \\<union> Y) = setSize Y\"\n  by (simp add: assms sup.absorb2)\n\nlemma set_union_ins: \"\\<And> F G x. setSize (F \\<union> G) \\<le> setSize (F \\<union> (insert x G))\"\n  by (metis Fin_Suc Fin_leq_Suc_leq  Un_insert_right finite_insert insert_absorb lnat_po_eq_conv \n  setSizeSuc setSize_def)\n\nlemma setsize_mono_union_helper1: \n  assumes \"finite F\" and \"finite G\"\n  shows \"setSize F \\<le> setSize (F \\<union> G)\"\nproof -\n  have b0:  \"\\<And>P. P = (\\<lambda>G. setSize F \\<le> setSize (F \\<union> G)) \\<Longrightarrow> P G\"\n    by (metis assms(2) finite_induct order_refl set_union_ins sup_bot.right_neutral trans_lnle)\n  have b1: \"(\\<lambda>G. setSize F \\<le> setSize (F \\<union> G)) G\"\n    using b0 by auto\n  show \"setSize F \\<le> setSize (F \\<union> G)\"\n    by (simp add: b1)\nqed\n\nlemma setsize_mono_union_helper2: \n  assumes \"infinite F \\<or> infinite G\"\n  shows \"setSize F \\<le> setSize (F \\<union> G)\"\nproof -\n  have b0: \"setSize (F \\<union> G) = \\<infinity>\"\n    by (meson assms infinite_Un setSize_def)\n  show ?thesis\n    by (simp add: b0)\nqed\n\nlemma setsize_mono_union: \"setSize F \\<le> setSize (F \\<union> G)\"\n  by (meson setsize_mono_union_helper1 setsize_mono_union_helper2)\n\n\nlemma setsize_mono: \n  assumes \"F \\<subseteq> G\"\n  shows \"setSize F \\<le> setSize G\"\n  by (metis Un_absorb1 assms setsize_mono_union)\n\n\n\n\n\nsubsection \\<open>setflat\\<close>\n\ndefinition setflat :: \"'a set set \\<rightarrow> 'a set\" where\n\"setflat = (\\<Lambda> S. {K  | Z K. K\\<in>Z \\<and> Z \\<in>S} )\"\n\nlemma setflat_mono: \"monofun (\\<lambda> S. {K  | Z K. K\\<in>Z \\<and> Z \\<in>S} )\"\n  apply(rule monofunI)\n  apply auto\n  apply (simp add: less_set_def)\n  apply (rule subsetI)\n  by auto\n\n\nlemma setflat_cont: \"cont (\\<lambda> S. {K  | Z K. K\\<in>Z \\<and> Z \\<in>S} )\"\n  apply(rule contI2)\n  using setflat_mono apply simp\n  apply auto\n  unfolding  SetPcpo.less_set_def\n  unfolding lub_eq_Union\n  by blast\n\nlemma setflat_insert: \"setflat\\<cdot>S = {K  | Z K. K\\<in>Z \\<and> Z \\<in>S}\"\n  unfolding setflat_def\n  by (metis (mono_tags, lifting) Abs_cfun_inverse2 setflat_cont)  \n    \nlemma setflat_empty:\"(setflat\\<cdot>S = {}) \\<longleftrightarrow> (\\<forall>x\\<in>S. x = {})\"\n  by(simp add: setflat_insert, auto)\n\nlemma setflat_not_empty:\"(setflat\\<cdot>S \\<noteq> {}) \\<longleftrightarrow> (\\<exists>x\\<in>S. x \\<noteq> {})\"\n  by (simp add: setflat_empty)\n\nlemma setflat_obtain: assumes \"f \\<in> setflat\\<cdot>S\"\n  shows \"\\<exists> Z \\<in> S. f \\<in> Z\"\nproof -\n  have \"f \\<in> {a. \\<exists>A aa. a = aa \\<and> aa \\<in> A \\<and> A \\<in> S}\"\n    by (metis assms setflat_insert)\n  then show ?thesis\n    by blast\nqed\n\nlemma setflat_union: \"setflat\\<cdot>S = \\<Union>S\"\n  apply (simp add: setflat_insert)\n  apply (subst Union_eq)\n  by auto\n\nlemma setflatten_mono2: assumes \"\\<And>b. b\\<in>S1 \\<Longrightarrow>( \\<exists>c. c\\<in>S2 \\<and> b \\<subseteq> c)\"\n  shows \"setflat\\<cdot>S1 \\<subseteq> setflat\\<cdot> S2\"\n  by (smt Abs_cfun_inverse2 setflat_def setflat_cont assms mem_Collect_eq subsetCE subsetI)\n\nlemma setfilter_easy: \"Set.filter (\\<lambda>f. True) X = X\"\n  using member_filter by auto\n\nlemma setfilter_cont: \"cont (Set.filter P)\"\n  by (simp add: Prelude.contI2 SetPcpo.less_set_def lub_eq_Union monofun_def subset_eq)\n\nend", "meta": {"author": "yyisgladiator", "repo": "demo", "sha": "2a57300dfa7268721c78c233ee6b0a5454acce1f", "save_path": "github-repos/isabelle/yyisgladiator-demo", "path": "github-repos/isabelle/yyisgladiator-demo/demo-2a57300dfa7268721c78c233ee6b0a5454acce1f/src/inc/SetPcpo.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8596637505099167, "lm_q2_score": 0.8438951005915208, "lm_q1q2_score": 0.7254660272114503}}
{"text": "section \\<open>Examples\\<close>\ntheory LLVM_Examples\nimports \n  \"../ds/LLVM_DS_Dflt\"\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>Regression Tests\\<close>\ntypedef my_pair = \"UNIV :: (64 word \\<times> 32 word) set\" by simp\n\nlemmas my_pair_bij[simp] = Abs_my_pair_inverse[simplified] Rep_my_pair_inverse\n\ninstantiation my_pair :: 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 (_:: my_pair itself) \\<equiv> struct_of TYPE(64 word \\<times> 32 word)\"\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)\n    done\n\nend\n\ndefinition my_fst :: \"my_pair \\<Rightarrow> 64 word llM\" where [llvm_inline]: \"my_fst \\<equiv> ll_extract_fst\"\ndefinition my_snd :: \"my_pair \\<Rightarrow> 32 word llM\" where [llvm_inline]: \"my_snd \\<equiv> ll_extract_snd\"\ndefinition my_ins_fst :: \"my_pair \\<Rightarrow> 64 word \\<Rightarrow> my_pair llM\" where [llvm_inline]: \"my_ins_fst \\<equiv> ll_insert_fst\"\ndefinition my_ins_snd :: \"my_pair \\<Rightarrow> 32 word \\<Rightarrow> my_pair llM\" where [llvm_inline]: \"my_ins_snd \\<equiv> ll_insert_snd\"\ndefinition my_gep_fst :: \"my_pair ptr \\<Rightarrow> 64 word ptr llM\" where [llvm_inline]: \"my_gep_fst \\<equiv> ll_gep_fst\"\ndefinition my_gep_snd :: \"my_pair ptr \\<Rightarrow> 32 word ptr llM\" where [llvm_inline]: \"my_gep_snd \\<equiv> ll_gep_snd\"\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::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(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\n\n\nlemma [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\nexport_llvm (debug) test_named file \"code/test_named.ll\"\n\n\n\n\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-2020/examples/LLVM_Examples.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637433190938, "lm_q2_score": 0.8438950986284991, "lm_q1q2_score": 0.7254660194556114}}
{"text": "theory NaDeA imports Main begin\n\ntype_synonym id = \"char list\"\n\ndatatype tm = Var nat | Fun id \"tm list\"\n\ndatatype fm = Falsity | Pre id \"tm list\" | Imp fm fm | Dis fm fm | Con fm fm | Exi fm | Uni fm\n\nprimrec\n  semantics_term :: \"(nat \\<Rightarrow> 'a) \\<Rightarrow> (id \\<Rightarrow> 'a list \\<Rightarrow> 'a) \\<Rightarrow> tm \\<Rightarrow> 'a\"\nand\n  semantics_list :: \"(nat \\<Rightarrow> 'a) \\<Rightarrow> (id \\<Rightarrow> 'a list \\<Rightarrow> 'a) \\<Rightarrow> tm list \\<Rightarrow> 'a list\"\nwhere\n  \"semantics_term e f (Var n) = e n\" |\n  \"semantics_term e f (Fun i l) = f i (semantics_list e f l)\" |\n  \"semantics_list e f [] = []\" |\n  \"semantics_list e f (t # l) = semantics_term e f t # semantics_list e f l\"\n\nprimrec\n  semantics :: \"(nat \\<Rightarrow> 'a) \\<Rightarrow> (id \\<Rightarrow> 'a list \\<Rightarrow> 'a) \\<Rightarrow> (id \\<Rightarrow> 'a list \\<Rightarrow> bool) \\<Rightarrow> fm \\<Rightarrow> bool\"\nwhere\n  \"semantics e f g Falsity = False\" |\n  \"semantics e f g (Pre i l) = g i (semantics_list e f l)\" |\n  \"semantics e f g (Imp p q) = (if semantics e f g p then semantics e f g q else True)\" |\n  \"semantics e f g (Dis p q) = (if semantics e f g p then True else semantics e f g q)\" |\n  \"semantics e f g (Con p q) = (if semantics e f g p then semantics e f g q else False)\" |\n  \"semantics e f g (Exi p) = (\\<exists>x. semantics (\\<lambda>n. if n = 0 then x else e (n - 1)) f g p)\" |\n  \"semantics e f g (Uni p) = (\\<forall>x. semantics (\\<lambda>n. if n = 0 then x else e (n - 1)) f g p)\"\n\nprimrec\n  member :: \"fm \\<Rightarrow> fm list \\<Rightarrow> bool\"\nwhere\n  \"member p [] = False\" |\n  \"member p (q # z) = (if p = q then True else member p z)\"\n\nprimrec\n  new_term :: \"id \\<Rightarrow> tm \\<Rightarrow> bool\"\nand\n  new_list :: \"id \\<Rightarrow> tm list \\<Rightarrow> bool\"\nwhere\n  \"new_term c (Var n) = True\" |\n  \"new_term c (Fun i l) = (if i = c then False else new_list c l)\" |\n  \"new_list c [] = True\" |\n  \"new_list c (t # l) = (if new_term c t then new_list c l else False)\"\n\nprimrec\n  new :: \"id \\<Rightarrow> fm \\<Rightarrow> bool\"\nwhere\n  \"new c Falsity = True\" |\n  \"new c (Pre i l) = new_list c l\" |\n  \"new c (Imp p q) = (if new c p then new c q else False)\" |\n  \"new c (Dis p q) = (if new c p then new c q else False)\" |\n  \"new c (Con p q) = (if new c p then new c q else False)\" |\n  \"new c (Exi p) = new c p\" |\n  \"new c (Uni p) = new c p\"\n\nprimrec\n  news :: \"id \\<Rightarrow> fm list \\<Rightarrow> bool\"\nwhere\n  \"news c [] = True\" |\n  \"news c (p # z) = (if new c p then news c z else False)\"\n\nprimrec\n  inc_term :: \"tm \\<Rightarrow> tm\"\nand\n  inc_list :: \"tm list \\<Rightarrow> tm list\"\nwhere\n  \"inc_term (Var n) = Var (n + 1)\" |\n  \"inc_term (Fun i l) = Fun i (inc_list l)\" |\n  \"inc_list [] = []\" |\n  \"inc_list (t # l) = inc_term t # inc_list l\"\n\nprimrec\n  sub_term :: \"nat \\<Rightarrow> tm \\<Rightarrow> tm \\<Rightarrow> tm\"\nand\n  sub_list :: \"nat \\<Rightarrow> tm \\<Rightarrow> tm list \\<Rightarrow> tm list\"\nwhere\n  \"sub_term v s (Var n) = (if n < v then Var n else if n = v then s else Var (n - 1))\" |\n  \"sub_term v s (Fun i l) = Fun i (sub_list v s l)\" |\n  \"sub_list v s [] = []\" |\n  \"sub_list v s (t # l) = sub_term v s t # sub_list v s l\"\n\nprimrec\n  sub :: \"nat \\<Rightarrow> tm \\<Rightarrow> fm \\<Rightarrow> fm\"\nwhere\n  \"sub v s Falsity = Falsity\" |\n  \"sub v s (Pre i l) = Pre i (sub_list v s l)\" |\n  \"sub v s (Imp p q) = Imp (sub v s p) (sub v s q)\" |\n  \"sub v s (Dis p q) = Dis (sub v s p) (sub v s q)\" |\n  \"sub v s (Con p q) = Con (sub v s p) (sub v s q)\" |\n  \"sub v s (Exi p) = Exi (sub (v + 1) (inc_term s) p)\" |\n  \"sub v s (Uni p) = Uni (sub (v + 1) (inc_term s) p)\"\n\ninductive\n  OK :: \"fm \\<Rightarrow> fm list \\<Rightarrow> bool\"\nwhere\nAssume:\n        \"member p z \\<Longrightarrow> OK p z\" |\nBoole:\n        \"OK Falsity ((Imp p Falsity) # z) \\<Longrightarrow> OK p z\" |\nImp_E:\n        \"OK (Imp p q) z \\<Longrightarrow> OK p z \\<Longrightarrow> OK q z\" |\nImp_I:\n        \"OK q (p # z) \\<Longrightarrow> OK (Imp p q) z\" |\nDis_E:\n        \"OK (Dis p q) z \\<Longrightarrow> OK r (p # z) \\<Longrightarrow> OK r (q # z) \\<Longrightarrow> OK r z\" |\nDis_I1:\n        \"OK p z \\<Longrightarrow> OK (Dis p q) z\" |\nDis_I2:\n        \"OK q z \\<Longrightarrow> OK (Dis p q) z\" |\nCon_E1:\n        \"OK (Con p q) z \\<Longrightarrow> OK p z\" |\nCon_E2:\n        \"OK (Con p q) z \\<Longrightarrow> OK q z\" |\nCon_I:\n        \"OK p z \\<Longrightarrow> OK q z \\<Longrightarrow> OK (Con p q) z\" |\nExi_E:\n        \"OK (Exi p) z \\<Longrightarrow> OK q ((sub 0 (Fun c []) p) # z) \\<Longrightarrow> news c (p # q # z) \\<Longrightarrow> OK q z\" |\nExi_I:\n        \"OK (sub 0 t p) z \\<Longrightarrow> OK (Exi p) z\" |\nUni_E:\n        \"OK (Uni p) z \\<Longrightarrow> OK (sub 0 t p) z\" |\nUni_I:\n        \"OK (sub 0 (Fun c []) p) z \\<Longrightarrow> news c (p # z) \\<Longrightarrow> OK (Uni p) z\"\n\nlemma \"OK (Imp (Pre ''A'' []) (Pre ''A'' [])) []\" proof (rule Imp_I, rule Assume, simp) qed\n\nlemma \"OK (Imp (Pre ''A'' []) (Pre ''A'' [])) []\"\nproof -\n  have \"OK (Pre ''A'' []) [(Pre ''A'' [])]\" proof (rule Assume) qed simp\n  then show \"OK (Imp (Pre ''A'' []) (Pre ''A'' [])) []\" proof (rule Imp_I) qed\nqed\n\nfun\n  put :: \"(nat \\<Rightarrow> 'a) \\<Rightarrow> nat \\<Rightarrow> 'a \\<Rightarrow> nat \\<Rightarrow> 'a\"\nwhere\n  \"put e v x = (\\<lambda>n. if n < v then e n else if n = v then x else e (n - 1))\"\n\nlemma \"put e 0 x = (\\<lambda>n. if n = 0 then x else e (n - 1))\" proof simp qed\n\nlemma increment:\n  \"semantics_term (put e 0 x) f (inc_term t) = semantics_term e f t\"\n  \"semantics_list (put e 0 x) f (inc_list l) = semantics_list e f l\"\nproof (induct t and l rule: semantics_term.induct semantics_list.induct) qed simp_all\n\nlemma commute: \"put (put e v x) 0 y = put (put e 0 y) (v + 1) x\" proof force qed\n\nfun\n  all :: \"(fm \\<Rightarrow> bool) \\<Rightarrow> fm list \\<Rightarrow> bool\"\nwhere\n  \"all b z = (\\<forall>p. if member p z then b p else True)\"\n\nlemma allhead: \"all b (p # z) \\<Longrightarrow> b p\" proof simp qed\n\nlemma alltail: \"all b (p # z) \\<Longrightarrow> all b z\" proof simp qed\n\nlemma allnew: \"all (new c) z = news c z\" proof (induct z) qed (simp, simp, metis)\n\nlemma map':\n  \"new_term c t \\<Longrightarrow> semantics_term e (f(c := m)) t = semantics_term e f t\"\n  \"new_list c l \\<Longrightarrow> semantics_list e (f(c := m)) l = semantics_list e f l\"\nproof (induct t and l rule: semantics_term.induct semantics_list.induct)\nqed (simp, simp, metis, simp, simp, metis)\n\nlemma map: \"new c p \\<Longrightarrow> semantics e (f(c := m)) g p = semantics e f g p\"\nproof (induct p arbitrary: e)\nqed (simp, simp, metis map'(2), simp, metis, simp, metis, simp, metis, simp_all)\n\nlemma allmap: \"news c z \\<Longrightarrow> all (semantics e (f(c := m)) g) z = all (semantics e f g) z\"\nproof (induct z) qed (simp, simp, metis map)\n\nlemma substitute':\n  \"semantics_term e f (sub_term v s t) = semantics_term (put e v (semantics_term e f s)) f t\"\n  \"semantics_list e f (sub_list v s l) = semantics_list (put e v (semantics_term e f s)) f l\"\nproof (induct t and l rule: semantics_term.induct semantics_list.induct) qed simp_all\n\nlemma substitute: \"semantics e f g (sub v t p) = semantics (put e v (semantics_term e f t)) f g p\"\nproof (induct p arbitrary: e v t)\n  fix i l e v t\n  show \"semantics e f g (sub v t (Pre i l)) =\n      semantics (put e v (semantics_term e f t)) f g (Pre i l)\"\n  proof (simp add: substitute'(2)) qed\nnext\n  fix p e v t assume *: \"semantics e' f g (sub v' t' p) =\n      semantics (put e' v' (semantics_term e' f t')) f g p\" for e' v' t'\n  have \"semantics e f g (sub v t (Exi p)) =\n      (\\<exists>x. semantics (put (put e 0 x) (v + 1) (semantics_term (put e 0 x) f (inc_term t))) f g p)\"\n    using * proof simp qed\n  also have \"... = (\\<exists>x. semantics (put (put e v (semantics_term e f t)) 0 x) f g p)\"\n    using commute increment(1) proof metis qed\n  finally show \"semantics e f g (sub v t (Exi p)) =\n      semantics (put e v (semantics_term e f t)) f g (Exi p)\" proof simp qed\n  have \"semantics e f g (sub v t (Uni p)) =\n      (\\<forall>x. semantics (put (put e 0 x) (v + 1) (semantics_term (put e 0 x) f (inc_term t))) f g p)\"\n    using * proof simp qed\n  also have \"... = (\\<forall>x. semantics (put (put e v (semantics_term e f t)) 0 x) f g p)\"\n    using commute increment(1) proof metis qed\n  finally show \"semantics e f g (sub v t (Uni p)) =\n      semantics (put e v (semantics_term e f t)) f g (Uni p)\" proof simp qed\nqed simp_all\n\nlemma soundness': \"OK p z \\<Longrightarrow> all (semantics e f g) z \\<Longrightarrow> semantics e f g p\"\nproof (induct arbitrary: f rule: OK.induct)\n  fix f p z assume \"all (semantics e f g) z\"\n      \"all (semantics e f' g) (Imp p Falsity # z) \\<Longrightarrow> semantics e f' g Falsity\" for f'\n  then show \"semantics e f g p\" proof force qed\nnext\n  fix f p q z r assume \"all (semantics e f g) z\"\n      \"all (semantics e f' g) z \\<Longrightarrow> semantics e f' g (Dis p q)\"\n      \"all (semantics e f' g) (p # z) \\<Longrightarrow> semantics e f' g r\"\n      \"all (semantics e f' g) (q # z) \\<Longrightarrow> semantics e f' g r\" for f'\n  then show \"semantics e f g r\" proof (simp, metis) qed\nnext\n  fix f p q z assume \"all (semantics e f g) z\"\n      \"all (semantics e f' g) z \\<Longrightarrow> semantics e f' g (Con p q)\" for f'\n  then show \"semantics e f g p\" \"semantics e f g q\" proof (simp, metis, simp, metis) qed\nnext\n  fix f p z q c assume *: \"all (semantics e f g) z\"\n      \"all (semantics e f' g) z \\<Longrightarrow> semantics e f' g (Exi p)\"\n      \"all (semantics e f' g) (sub 0 (Fun c []) p # z) \\<Longrightarrow> semantics e f' g q\"\n      \"news c (p # q # z)\" for f'\n  obtain x where \"semantics (\\<lambda>n. if n = 0 then x else e (n - 1)) f g p\"\n    using *(1) *(2) proof force qed\n  then have \"semantics (put e 0 x) f g p\" proof simp qed\n  then have \"semantics (put e 0 x) (f(c := \\<lambda>w. x)) g p\"\n    using *(4) allhead allnew map proof blast qed\n  then have \"semantics e (f(c := \\<lambda>w. x)) g (sub 0 (Fun c []) p)\"\n    proof (simp add: substitute) qed\n  moreover have \"all (semantics e (f(c := \\<lambda>w. x)) g) z\"\n    using *(1) *(4) alltail allnew allmap proof blast qed\n  ultimately have \"semantics e (f(c := \\<lambda>w. x)) g q\" using *(3) proof simp qed\n  then show \"semantics e f g q\" using *(4) allhead alltail allnew map proof blast qed\nnext\n  fix f z t p assume \"all (semantics e f g) z\"\n      \"all (semantics e f' g) z \\<Longrightarrow> semantics e f' g (sub 0 t p)\" for f'\n  then have \"semantics (put e 0 (semantics_term e f t)) f g p\" proof (simp add: substitute) qed\n  then show \"semantics e f g (Exi p)\" proof (simp, metis) qed\nnext\n  fix f z t p assume \"all (semantics e f g) z\"\n      \"all (semantics e f' g) z \\<Longrightarrow> semantics e f' g (Uni p)\" for f'\n  then show \"semantics e f g (sub 0 t p)\" proof (simp add: substitute) qed\nnext\n  fix f c p z assume *: \"all (semantics e f g) z\"\n      \"all (semantics e f' g) z \\<Longrightarrow> semantics e f' g (sub 0 (Fun c []) p)\"\n      \"news c (p # z)\" for f'\n  have \"semantics (\\<lambda>n. if n = 0 then x else e (n - 1)) f g p\" for x\n  proof -\n    have \"all (semantics e (f(c := \\<lambda>w. x)) g) z\"\n      using *(1) *(3) alltail allnew allmap proof blast qed\n    then have \"semantics e (f(c := \\<lambda>w. x)) g (sub 0 (Fun c []) p)\"\n      using *(2) proof simp qed\n    then have \"semantics (\\<lambda>n. if n = 0 then x else e (n - 1)) (f(c := \\<lambda>w. x)) g p\"\n      proof (simp add: substitute) qed\n    then show \"semantics (\\<lambda>n. if n = 0 then x else e (n - 1)) f g p\"\n      using *(3) allhead alltail allnew map proof blast qed\n  qed\n  then show \"semantics e f g (Uni p)\" proof simp qed\nqed simp_all\n\ntheorem soundness: \"OK p [] \\<Longrightarrow> semantics e f g p\" proof (simp add: soundness') qed\n\ncorollary \"\\<exists>p. OK p []\" \"\\<exists>p. \\<not> OK p []\"\nproof -\n  have \"OK (Imp p p) []\" for p proof (rule Imp_I, rule Assume, simp) qed\n  then show \"\\<exists>p. OK p []\" proof iprover qed\nnext\n  have \"\\<not> semantics (e :: nat \\<Rightarrow> unit) f g Falsity\" for e f g proof simp qed\n  then show \"\\<exists>p. \\<not> OK p []\" using soundness proof iprover qed\nqed\n\nend\n", "meta": {"author": "logic-tools", "repo": "nadea", "sha": "26824f65892b9e3494480eeaf8d4b399af44ee37", "save_path": "github-repos/isabelle/logic-tools-nadea", "path": "github-repos/isabelle/logic-tools-nadea/nadea-26824f65892b9e3494480eeaf8d4b399af44ee37/Isabelle/NaDeA.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976953003183443, "lm_q2_score": 0.8080672181749422, "lm_q1q2_score": 0.7253981440969638}}
{"text": "section \"Solution to Day 3 of AoC 2020\"\n\ntheory day3\n  imports Main \"HOL.Code_Numeral\" string_utils list_natural_utils natural_utils\nbegin\n\ntext \"This is a solution to the puzzle for day 3\"\n\nsubsection \"Input parsing\"\n\ndefinition is_tree :: \"char \\<Rightarrow> bool\"\n  where \"is_tree c = (c = CHR ''#'')\"\n\ndefinition parse_input :: \"string \\<Rightarrow> bool list list\"\n  where \"parse_input a = map (map is_tree) (split CHR ''\\<newline>'' (trim a))\"\n\nsubsection \"Solution Algorithm\"\n\nfun trees_hit :: \"bool list list \\<Rightarrow> natural \\<Rightarrow> natural \\<Rightarrow> natural\"\n  where\"trees_hit [] _ _ = 0\"\n  |\"trees_hit (Cons h t) \\<Delta>x x = ((count_bool ((nth_mod_len x h))) + (trees_hit t \\<Delta>x (x+\\<Delta>x)))\"\n\ndefinition scan_trajectory ::\"bool list list \\<Rightarrow> natural \\<Rightarrow> natural \\<Rightarrow> natural\"\n  where \"scan_trajectory grid x y = (trees_hit (skip_each (y-1) grid) x 0)\"\n\ntext \"The solution to part1 counts the number of trees we will hit on a 3:1 slope\"\n\nfun part1 :: \"string \\<Rightarrow> natural\"\n  where \"part1 a = (scan_trajectory (parse_input a) 3 1)\"\n\ntext \"In part 2 we need the product of a few different trajectory totals\"\n\nfun part2 :: \"string \\<Rightarrow> natural\"\n  where \"part2 a = (let scan_grid = scan_trajectory (parse_input a) in prod_list (map2 scan_grid\n    [1, 3, 5, 7, 1]\n    [1, 1, 1, 1, 2]\n  ))\"\n\nsubsection \"Testing\"\n\ntext \"We expect our test case to return 7\"\n\ndefinition example_input::string where \"example_input = ''\n..##.......\n#...#...#..\n.#....#..#.\n..#.#...#.#\n.#...##..#.\n..#.##.....\n.#.#.#....#\n.#........#\n#.##...#...\n#...##....#\n.#..#...#.#\n''\"\n\nlemma \"part1 example_input = 7\"\n  by eval\n\ntext \"For part 2 the example should return 336\"\n\nlemma \"part2 example_input = 336\"\n  by eval\n\nexport_code \"part1\" \"part2\" in Haskell module_name Solution\n\nend\n", "meta": {"author": "lexbailey", "repo": "AOC2020_isabelle", "sha": "c08c347793814e9cc3e9d9638dd889d2ada2eb1d", "save_path": "github-repos/isabelle/lexbailey-AOC2020_isabelle", "path": "github-repos/isabelle/lexbailey-AOC2020_isabelle/AOC2020_isabelle-c08c347793814e9cc3e9d9638dd889d2ada2eb1d/day3.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952893703478, "lm_q2_score": 0.808067204308405, "lm_q1q2_score": 0.7253981228023215}}
{"text": "section \"Bitvector based Sets of Naturals\"\ntheory Impl_Bit_Set\nimports \n  \"../../Iterator/Iterator\" \n  \"../Intf/Intf_Set\" \n  \"../../../Native_Word/Bits_Integer\"\nbegin\n  text {*\n    Based on the Native-Word library, using bit-operations on arbitrary\n    precision integers. Fast for sets of small numbers, \n    direct and fast implementations of equal, union, inter, diff.\n\n    Note: On Poly/ML 5.5.1, bit-operations on arbitrary precision integers are \n      rather inefficient. Use MLton instead, here they are efficiently implemented.\n    *}\n\n  type_synonym bitset = integer\n\n  definition bs_\\<alpha> :: \"bitset \\<Rightarrow> nat set\" where \"bs_\\<alpha> s \\<equiv> { n . test_bit s n}\"\n\n\ncontext includes integer.lifting begin\n\n  definition bs_empty :: \"unit \\<Rightarrow> bitset\" where \"bs_empty \\<equiv> \\<lambda>_. 0\"\n\n\n  lemma bs_empty_correct: \"bs_\\<alpha> (bs_empty ()) = {}\"\n    unfolding bs_\\<alpha>_def bs_empty_def \n    apply transfer\n    by auto\n\n  definition bs_isEmpty :: \"bitset \\<Rightarrow> bool\" where \"bs_isEmpty s \\<equiv> s=0\"\n\n  lemma bs_isEmpty_correct: \"bs_isEmpty s \\<longleftrightarrow> bs_\\<alpha> s = {}\"\n    unfolding bs_isEmpty_def bs_\\<alpha>_def \n    by transfer (auto simp: bin_eq_iff) \n    \n  term set_bit\n  definition bs_insert :: \"nat \\<Rightarrow> bitset \\<Rightarrow> bitset\" where\n    \"bs_insert i s \\<equiv> set_bit s i True\"\n\n  lemma bs_insert_correct: \"bs_\\<alpha> (bs_insert i s) = insert i (bs_\\<alpha> s)\"\n    unfolding bs_\\<alpha>_def bs_insert_def\n    apply transfer\n    apply auto\n    apply (metis bin_nth_sc_gen bin_set_conv_OR int_set_bit_True_conv_OR)\n    apply (metis bin_nth_sc_gen bin_set_conv_OR int_set_bit_True_conv_OR)\n    by (metis bin_nth_sc_gen bin_set_conv_OR int_set_bit_True_conv_OR)\n\n  definition bs_delete :: \"nat \\<Rightarrow> bitset \\<Rightarrow> bitset\" where\n    \"bs_delete i s \\<equiv> set_bit s i False\"\n\n  lemma bs_delete_correct: \"bs_\\<alpha> (bs_delete i s) = (bs_\\<alpha> s) - {i}\"\n    unfolding bs_\\<alpha>_def bs_delete_def\n    apply transfer\n    apply auto\n    apply (metis bin_nth_ops(1) int_set_bit_False_conv_NAND)\n    apply (metis (full_types) bin_nth_sc set_bit_int_def)\n    by (metis (full_types) bin_nth_sc_gen set_bit_int_def)\n  \n  definition bs_mem :: \"nat \\<Rightarrow> bitset \\<Rightarrow> bool\" where\n    \"bs_mem i s \\<equiv> test_bit s i\"\n\n  lemma bs_mem_correct: \"bs_mem i s \\<longleftrightarrow> i\\<in>bs_\\<alpha> s\"\n    unfolding bs_mem_def bs_\\<alpha>_def by transfer auto\n\n\n  definition bs_eq :: \"bitset \\<Rightarrow> bitset \\<Rightarrow> bool\" where \n    \"bs_eq s1 s2 \\<equiv> (s1=s2)\"\n\n  lemma bs_eq_correct: \"bs_eq s1 s2 \\<longleftrightarrow> bs_\\<alpha> s1 = bs_\\<alpha> s2\"\n    unfolding bs_eq_def bs_\\<alpha>_def\n    including integer.lifting\n    apply transfer\n    apply auto\n    by (metis bin_eqI mem_Collect_eq test_bit_int_def)\n\n  definition bs_subset_eq :: \"bitset \\<Rightarrow> bitset \\<Rightarrow> bool\" where\n    \"bs_subset_eq s1 s2 \\<equiv> s1 AND NOT s2 = 0\"\n  \n  lemma bs_subset_eq_correct: \"bs_subset_eq s1 s2 \\<longleftrightarrow> bs_\\<alpha> s1 \\<subseteq> bs_\\<alpha> s2\"\n    unfolding bs_\\<alpha>_def bs_subset_eq_def\n    apply transfer\n    apply rule\n    apply auto []\n    apply (metis bin_nth_code(1) bin_nth_ops(1) bin_nth_ops(4))\n    apply (auto intro!: bin_eqI simp: bin_nth_ops)\n    done\n\n  definition bs_disjoint :: \"bitset \\<Rightarrow> bitset \\<Rightarrow> bool\" where\n    \"bs_disjoint s1 s2 \\<equiv> s1 AND s2 = 0\"\n  \n  lemma bs_disjoint_correct: \"bs_disjoint s1 s2 \\<longleftrightarrow> bs_\\<alpha> s1 \\<inter> bs_\\<alpha> s2 = {}\"\n    unfolding bs_\\<alpha>_def bs_disjoint_def\n    apply transfer\n    apply rule\n    apply auto []\n    apply (metis bin_nth_code(1) bin_nth_ops(1))\n    apply (auto intro!: bin_eqI simp: bin_nth_ops)\n    done\n\n  definition bs_union :: \"bitset \\<Rightarrow> bitset \\<Rightarrow> bitset\" where\n    \"bs_union s1 s2 = s1 OR s2\"\n\n  lemma bs_union_correct: \"bs_\\<alpha> (bs_union s1 s2) = bs_\\<alpha> s1 \\<union> bs_\\<alpha> s2\"\n    unfolding bs_\\<alpha>_def bs_union_def\n    by transfer (auto simp: bin_nth_ops)\n\n  definition bs_inter :: \"bitset \\<Rightarrow> bitset \\<Rightarrow> bitset\" where\n    \"bs_inter s1 s2 = s1 AND s2\"\n\n  lemma bs_inter_correct: \"bs_\\<alpha> (bs_inter s1 s2) = bs_\\<alpha> s1 \\<inter> bs_\\<alpha> s2\"\n    unfolding bs_\\<alpha>_def bs_inter_def\n    by transfer (auto simp: bin_nth_ops)\n\n  definition bs_diff :: \"bitset \\<Rightarrow> bitset \\<Rightarrow> bitset\" where\n    \"bs_diff s1 s2 = s1 AND NOT s2\"\n\n  lemma bs_diff_correct: \"bs_\\<alpha> (bs_diff s1 s2) = bs_\\<alpha> s1 - bs_\\<alpha> s2\"\n    unfolding bs_\\<alpha>_def bs_diff_def\n    by transfer (auto simp: bin_nth_ops)\n\n  definition bs_UNIV :: \"unit \\<Rightarrow> bitset\" where \"bs_UNIV \\<equiv> \\<lambda>_. -1\"\n\n  lemma bs_UNIV_correct: \"bs_\\<alpha> (bs_UNIV ()) = UNIV\"\n    unfolding bs_\\<alpha>_def bs_UNIV_def\n    by transfer (auto)\n\n  definition bs_complement :: \"bitset \\<Rightarrow> bitset\" where\n    \"bs_complement s = NOT s\"\n\n  lemma bs_complement_correct: \"bs_\\<alpha> (bs_complement s) = - bs_\\<alpha> s\"\n    unfolding bs_\\<alpha>_def bs_complement_def\n    by transfer (auto simp: bin_nth_ops)\n\nend\n\n  lemmas bs_correct[simp] = \n    bs_empty_correct\n    bs_isEmpty_correct\n    bs_insert_correct\n    bs_delete_correct\n    bs_mem_correct\n    bs_eq_correct\n    bs_subset_eq_correct\n    bs_disjoint_correct\n    bs_union_correct\n    bs_inter_correct\n    bs_diff_correct\n    bs_UNIV_correct\n    bs_complement_correct\n\n\nsubsection {* Autoref Setup *}\n\ndefinition bs_set_rel_def_internal: \n  \"bs_set_rel Rk \\<equiv> \n    if Rk=nat_rel then br bs_\\<alpha> (\\<lambda>_. True) else {}\"\nlemma bs_set_rel_def: \n  \"\\<langle>nat_rel\\<rangle>bs_set_rel \\<equiv> br bs_\\<alpha> (\\<lambda>_. True)\" \n  unfolding bs_set_rel_def_internal relAPP_def by simp\n\nlemmas [autoref_rel_intf] = REL_INTFI[of \"bs_set_rel\" i_set]\n\nlemma bs_set_rel_sv[relator_props]: \"single_valued (\\<langle>nat_rel\\<rangle>bs_set_rel)\"\n  unfolding bs_set_rel_def by auto\n\n\nterm bs_empty\n\nlemma [autoref_rules]: \"(bs_empty (),{})\\<in>\\<langle>nat_rel\\<rangle>bs_set_rel\"\n  by (auto simp: bs_set_rel_def br_def)\n\nlemma [autoref_rules]: \"(bs_UNIV (),UNIV)\\<in>\\<langle>nat_rel\\<rangle>bs_set_rel\"\n  by (auto simp: bs_set_rel_def br_def)\n\nlemma [autoref_rules]: \"(bs_isEmpty,op_set_isEmpty)\\<in>\\<langle>nat_rel\\<rangle>bs_set_rel \\<rightarrow> bool_rel\"\n  by (auto simp: bs_set_rel_def br_def)\n\nterm insert\nlemma [autoref_rules]: \"(bs_insert,insert)\\<in>nat_rel \\<rightarrow> \\<langle>nat_rel\\<rangle>bs_set_rel \\<rightarrow> \\<langle>nat_rel\\<rangle>bs_set_rel\"\n  by (auto simp: bs_set_rel_def br_def)\n\nterm op_set_delete\nlemma [autoref_rules]: \"(bs_delete,op_set_delete)\\<in>nat_rel \\<rightarrow> \\<langle>nat_rel\\<rangle>bs_set_rel \\<rightarrow> \\<langle>nat_rel\\<rangle>bs_set_rel\"\n  by (auto simp: bs_set_rel_def br_def)\n\nlemma [autoref_rules]: \"(bs_mem,op \\<in>)\\<in>nat_rel \\<rightarrow> \\<langle>nat_rel\\<rangle>bs_set_rel \\<rightarrow> bool_rel\"\n  by (auto simp: bs_set_rel_def br_def)\n\nlemma [autoref_rules]: \"(bs_eq,op =)\\<in>\\<langle>nat_rel\\<rangle>bs_set_rel \\<rightarrow> \\<langle>nat_rel\\<rangle>bs_set_rel \\<rightarrow> bool_rel\"\n  by (auto simp: bs_set_rel_def br_def)\n\nlemma [autoref_rules]: \"(bs_subset_eq,op \\<subseteq>)\\<in>\\<langle>nat_rel\\<rangle>bs_set_rel \\<rightarrow> \\<langle>nat_rel\\<rangle>bs_set_rel \\<rightarrow> bool_rel\"\n  by (auto simp: bs_set_rel_def br_def)\n\nlemma [autoref_rules]: \"(bs_union,op \\<union>)\\<in>\\<langle>nat_rel\\<rangle>bs_set_rel \\<rightarrow> \\<langle>nat_rel\\<rangle>bs_set_rel \\<rightarrow> \\<langle>nat_rel\\<rangle>bs_set_rel\"\n  by (auto simp: bs_set_rel_def br_def)\n\nlemma [autoref_rules]: \"(bs_inter,op \\<inter>)\\<in>\\<langle>nat_rel\\<rangle>bs_set_rel \\<rightarrow> \\<langle>nat_rel\\<rangle>bs_set_rel \\<rightarrow> \\<langle>nat_rel\\<rangle>bs_set_rel\"\n  by (auto simp: bs_set_rel_def br_def)\n\nlemma [autoref_rules]: \"(bs_diff,op -)\\<in>\\<langle>nat_rel\\<rangle>bs_set_rel \\<rightarrow> \\<langle>nat_rel\\<rangle>bs_set_rel \\<rightarrow> \\<langle>nat_rel\\<rangle>bs_set_rel\"\n  by (auto simp: bs_set_rel_def br_def)\n\nlemma [autoref_rules]: \"(bs_complement,uminus)\\<in>\\<langle>nat_rel\\<rangle>bs_set_rel \\<rightarrow> \\<langle>nat_rel\\<rangle>bs_set_rel\"\n  by (auto simp: bs_set_rel_def br_def)\n\nlemma [autoref_rules]: \"(bs_disjoint,op_set_disjoint)\\<in>\\<langle>nat_rel\\<rangle>bs_set_rel \\<rightarrow> \\<langle>nat_rel\\<rangle>bs_set_rel \\<rightarrow> bool_rel\"\n  by (auto simp: bs_set_rel_def br_def)\n\n\nexport_code \n    bs_empty\n    bs_isEmpty\n    bs_insert\n    bs_delete\n    bs_mem\n    bs_eq\n    bs_subset_eq\n    bs_disjoint\n    bs_union\n    bs_inter\n    bs_diff\n    bs_UNIV\n    bs_complement\n in SML\n\n(*\n\n    TODO: Iterator\n\n  definition \"maxbi s \\<equiv> GREATEST i. s!!i\"\n\n  lemma cmp_BIT_append_conv[simp]: \"i < i BIT b \\<longleftrightarrow> ((i\\<ge>0 \\<and> b=1) \\<or> i>0)\"\n    by (cases b) (auto simp: Bit_B0 Bit_B1)\n\n  lemma BIT_append_cmp_conv[simp]: \"i BIT b < i \\<longleftrightarrow> ((i<0 \\<and> (i=-1 \\<longrightarrow> b=0)))\"\n    by (cases b) (auto simp: Bit_B0 Bit_B1)\n\n  lemma BIT_append_eq[simp]: fixes i :: int shows \"i BIT b = i \\<longleftrightarrow> (i=0 \\<and> b=0) \\<or> (i=-1 \\<and> b=1)\"\n    by (cases b) (auto simp: Bit_B0 Bit_B1)\n\n  lemma int_no_bits_eq_zero[simp]:\n    fixes s::int shows \"(\\<forall>i. \\<not>s!!i) \\<longleftrightarrow> s=0\"\n    apply clarsimp\n    by (metis bin_eqI bin_nth_code(1))\n\n  lemma int_obtain_bit:\n    fixes s::int\n    assumes \"s\\<noteq>0\"\n    obtains i where \"s!!i\"\n    by (metis assms int_no_bits_eq_zero)\n    \n  lemma int_bit_bound:\n    fixes s::int\n    assumes \"s\\<ge>0\" and \"s!!i\"\n    shows \"i \\<le> Bits_Integer.log2 s\"\n  proof (rule ccontr)\n    assume \"\\<not>i\\<le>Bits_Integer.log2 s\"\n    hence \"i>Bits_Integer.log2 s\" by simp\n    hence \"i - 1 \\<ge> Bits_Integer.log2 s\" by simp\n    hence \"s AND bin_mask (i - 1) = s\" by (simp add: int_and_mask `s\\<ge>0`)\n    hence \"\\<not> (s!!i)\"  \n      by clarsimp (metis Nat.diff_le_self bin_nth_mask bin_nth_ops(1) leD)\n    thus False using `s!!i` ..\n  qed\n\n  lemma int_bit_bound':\n    fixes s::int\n    assumes \"s\\<ge>0\" and \"s!!i\"\n    shows \"i < Bits_Integer.log2 s + 1\"\n    using assms int_bit_bound by smt\n\n  lemma int_obtain_bit_pos:\n    fixes s::int\n    assumes \"s>0\"\n    obtains i where \"s!!i\" \"i < Bits_Integer.log2 s + 1\"\n    by (metis assms int_bit_bound' int_no_bits_eq_zero less_imp_le less_irrefl)\n\n  lemma maxbi_set: fixes s::int shows \"s>0 \\<Longrightarrow> s!!maxbi s\"\n    unfolding maxbi_def\n    apply (rule int_obtain_bit_pos, assumption)\n    apply (rule GreatestI, assumption)\n    apply (intro allI impI)\n    apply (rule int_bit_bound'[rotated], assumption)\n    by auto\n\n  lemma maxbi_max: fixes s::int shows \"i>maxbi s \\<Longrightarrow> \\<not> s!!i\"\n    oops\n\n  function get_maxbi :: \"nat \\<Rightarrow> int \\<Rightarrow> nat\" where\n    \"get_maxbi n s = (let\n        b = 1<<n\n      in\n        if b\\<le>s then get_maxbi (n+1) s\n        else n\n    )\"\n    by pat_completeness auto\n\n  termination\n    apply (rule \"termination\"[of \"measure (\\<lambda>(n,s). nat (s + 1 - (1<<n)))\"])\n    apply simp\n    apply auto\n    by (smt bin_mask_ge0 bin_mask_p1_conv_shift)\n\n\n  partial_function (tailrec) \n    bs_iterate_aux :: \"nat \\<Rightarrow> bitset \\<Rightarrow> ('\\<sigma> \\<Rightarrow> bool) \\<Rightarrow> (nat \\<Rightarrow> '\\<sigma> \\<Rightarrow> '\\<sigma>) \\<Rightarrow> '\\<sigma> \\<Rightarrow> '\\<sigma>\"\n    where \"bs_iterate_aux i s c f \\<sigma> = (\n    if s < 1 << i then \\<sigma>\n    else if \\<not>c \\<sigma> then \\<sigma>\n    else if test_bit s i then bs_iterate_aux (i+1) s c f (f i \\<sigma>)\n    else bs_iterate_aux (i+1) s c f \\<sigma>\n  )\"\n\n  definition bs_iteratei :: \"bitset \\<Rightarrow> (nat,'\\<sigma>) set_iterator\" where \n    \"bs_iteratei s = bs_iterate_aux 0 s\"\n\n\n  definition bs_set_rel_def_internal: \n    \"bs_set_rel Rk \\<equiv> \n      if Rk=nat_rel then br bs_\\<alpha> (\\<lambda>_. True) else {}\"\n  lemma bs_set_rel_def: \n    \"\\<langle>nat_rel\\<rangle>bs_set_rel \\<equiv> br bs_\\<alpha> (\\<lambda>_. True)\" \n    unfolding bs_set_rel_def_internal relAPP_def by simp\n\n\n  definition \"bs_to_list \\<equiv> it_to_list bs_iteratei\"\n\n  lemma \"(1::int)<<i = 2^i\"\n    by (simp add: shiftl_int_def)\n\n  lemma \n    fixes s :: int\n    assumes \"s\\<ge>0\"  \n    shows \"s < 1<<i \\<longleftrightarrow> Bits_Integer.log2 s \\<le> i\"\n    using assms\n  proof (induct i arbitrary: s)\n    case 0 thus ?case by auto\n  next\n    case (Suc i)\n    note GE=`0\\<le>s`\n    show ?case proof\n      assume \"s < 1 << Suc i\"\n\n      have \"s \\<le> (s >> 1) BIT 1\"\n\n      hence \"(s >> 1) < (1<<i)\" using GE apply auto\n      with Suc.hyps[of \"s div 2\"]\n\n\n    apply auto\n    \n\n\n  lemma \"distinct (bs_to_list s)\"\n    unfolding bs_to_list_def it_to_list_def bs_iteratei_def[abs_def]\n  proof -\n    {\n      fix l i\n      assume \"distinct l\"\n      show \"distinct (bs_iterate_aux 0 s (\\<lambda>_. True) (\\<lambda>x l. l @ [x]) [])\"\n\n    }\n\n\n    apply auto\n    \n\n\n\n    lemma \"set (bs_to_list s) = bs_\\<alpha> s\"\n\n\n  lemma autoref_iam_is_iterator[autoref_ga_rules]: \n    shows \"is_set_to_list nat_rel bs_set_rel bs_to_list\"\n    unfolding is_set_to_list_def is_set_to_sorted_list_def\n    apply clarsimp\n    unfolding it_to_sorted_list_def\n    apply (refine_rcg refine_vcg)\n    apply (simp_all add: bs_set_rel_def br_def)\n\n  proof (clarsimp)\n\n\n\n  definition \n\n\"iterate s c f \\<sigma> \\<equiv> let\n    i=0;\n    b=0;\n    (_,_,s) = while \n  in\n\n  end\"\n\n\n*)\n\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/GenCF/Impl/Impl_Bit_Set.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8872045937171068, "lm_q2_score": 0.8175744828610095, "lm_q1q2_score": 0.7253558369001757}}
{"text": "(*  Author:     Tobias Nipkow\n    Copyright   1998 TUM\n*)\n\nheader \"From regular expressions to nondeterministic automata with epsilon\"\n\ntheory RegExp2NAe\nimports \"../Regular-Sets/Regular_Exp\" NAe\nbegin\n\ntype_synonym 'a bitsNAe = \"('a,bool list)nae\"\n\ndefinition\n epsilon :: \"'a bitsNAe\" where\n\"epsilon = ([],%a s. {}, %s. s=[])\"\n\ndefinition\n\"atom\"  :: \"'a => 'a bitsNAe\" where\n\"atom a = ([True],\n            %b s. if s=[True] & b=Some a then {[False]} else {},\n            %s. s=[False])\"\n\ndefinition\n or :: \"'a bitsNAe => 'a bitsNAe => 'a bitsNAe\" where\n\"or = (%(ql,dl,fl)(qr,dr,fr).\n   ([],\n    %a s. case s of\n            [] => if a=None then {True#ql,False#qr} else {}\n          | left#s => if left then True ## dl a s\n                              else False ## dr a s,\n    %s. case s of [] => False | left#s => if left then fl s else fr s))\"\n\ndefinition\n conc :: \"'a bitsNAe => 'a bitsNAe => 'a bitsNAe\" where\n\"conc = (%(ql,dl,fl)(qr,dr,fr).\n   (True#ql,\n    %a s. case s of\n            [] => {}\n          | left#s => if left then (True ## dl a s) Un\n                                   (if fl s & a=None then {False#qr} else {})\n                              else False ## dr a s,\n    %s. case s of [] => False | left#s => ~left & fr s))\"\n\ndefinition\n star :: \"'a bitsNAe => 'a bitsNAe\" where\n\"star = (%(q,d,f).\n   ([],\n    %a s. case s of\n            [] => if a=None then {True#q} else {}\n          | left#s => if left then (True ## d a s) Un\n                                   (if f s & a=None then {True#q} else {})\n                              else {},\n    %s. case s of [] => True | left#s => left & f s))\"\n\nprimrec rexp2nae :: \"'a rexp => 'a bitsNAe\" where\n\"rexp2nae Zero       = ([], %a s. {}, %s. False)\" |\n\"rexp2nae One        = epsilon\" |\n\"rexp2nae(Atom a)    = atom a\" |\n\"rexp2nae(Plus r s)  = or   (rexp2nae r) (rexp2nae s)\" |\n\"rexp2nae(Times r s) = conc (rexp2nae r) (rexp2nae s)\" |\n\"rexp2nae(Star r)    = star (rexp2nae r)\"\n\ndeclare split_paired_all[simp]\n\n(******************************************************)\n(*                     epsilon                        *)\n(******************************************************)\n\nlemma step_epsilon[simp]: \"step epsilon a = {}\"\nby(simp add:epsilon_def step_def)\n\nlemma steps_epsilon: \"((p,q) : steps epsilon w) = (w=[] & p=q)\"\nby (induct \"w\") auto\n\nlemma accepts_epsilon[simp]: \"accepts epsilon w = (w = [])\"\napply (simp add: steps_epsilon accepts_def)\napply (simp add: epsilon_def)\ndone\n\n(******************************************************)\n(*                       atom                         *)\n(******************************************************)\n\nlemma fin_atom: \"(fin (atom a) q) = (q = [False])\"\nby(simp add:atom_def)\n\nlemma start_atom: \"start (atom a) = [True]\"\nby(simp add:atom_def)\n\n(* Use {x. False} = {}? *)\n\nlemma eps_atom[simp]:\n \"eps(atom a) = {}\"\nby (simp add:atom_def step_def)\n\nlemma in_step_atom_Some[simp]:\n \"(p,q) : step (atom a) (Some b) = (p=[True] & q=[False] & b=a)\"\nby (simp add:atom_def step_def)\n\nlemma False_False_in_steps_atom:\n  \"([False],[False]) : steps (atom a) w = (w = [])\"\napply (induct \"w\")\n apply (simp)\napply (simp add: relcomp_unfold)\ndone\n\nlemma start_fin_in_steps_atom:\n  \"(start (atom a), [False]) : steps (atom a) w = (w = [a])\"\napply (induct \"w\")\n apply (simp add: start_atom rtrancl_empty)\napply (simp add: False_False_in_steps_atom relcomp_unfold start_atom)\ndone\n\nlemma accepts_atom: \"accepts (atom a) w = (w = [a])\"\nby (simp add: accepts_def start_fin_in_steps_atom fin_atom)\n\n\n(******************************************************)\n(*                      or                            *)\n(******************************************************)\n\n(***** lift True/False over fin *****)\n\nlemma fin_or_True[iff]:\n \"!!L R. fin (or L R) (True#p) = fin L p\"\nby(simp add:or_def)\n\nlemma fin_or_False[iff]:\n \"!!L R. fin (or L R) (False#p) = fin R p\"\nby(simp add:or_def)\n\n(***** lift True/False over step *****)\n\n\n\n\n\n\n(***** lift True/False over epsclosure *****)\n\nlemma lemma1a:\n \"(tp,tq) : (eps(or L R))^* ==> \n (!!p. tp = True#p ==> ? q. (p,q) : (eps L)^* & tq = True#q)\"\napply (induct rule:rtrancl_induct)\n apply (blast)\napply (clarify)\napply (simp)\napply (blast intro: rtrancl_into_rtrancl)\ndone\n\nlemma lemma1b:\n \"(tp,tq) : (eps(or L R))^* ==> \n (!!p. tp = False#p ==> ? q. (p,q) : (eps R)^* & tq = False#q)\"\napply (induct rule:rtrancl_induct)\n apply (blast)\napply (clarify)\napply (simp)\napply (blast intro: rtrancl_into_rtrancl)\ndone\n\nlemma lemma2a:\n \"(p,q) : (eps L)^*  ==> (True#p, True#q) : (eps(or L R))^*\"\napply (induct rule: rtrancl_induct)\n apply (blast)\napply (blast intro: rtrancl_into_rtrancl)\ndone\n\nlemma lemma2b:\n \"(p,q) : (eps R)^*  ==> (False#p, False#q) : (eps(or L R))^*\"\napply (induct rule: rtrancl_induct)\n apply (blast)\napply (blast intro: rtrancl_into_rtrancl)\ndone\n\nlemma True_epsclosure_or[iff]:\n \"(True#p,q) : (eps(or L R))^* = (? r. q = True#r & (p,r) : (eps L)^*)\"\nby (blast dest: lemma1a lemma2a)\n\nlemma False_epsclosure_or[iff]:\n \"(False#p,q) : (eps(or L R))^* = (? r. q = False#r & (p,r) : (eps R)^*)\"\nby (blast dest: lemma1b lemma2b)\n\n(***** lift True/False over steps *****)\n\nlemma lift_True_over_steps_or[iff]:\n \"!!p. (True#p,q):steps (or L R) w = (? r. q = True # r & (p,r):steps L w)\"\napply (induct \"w\")\n apply auto\napply force\ndone\n\nlemma lift_False_over_steps_or[iff]:\n \"!!p. (False#p,q):steps (or L R) w = (? r. q = False#r & (p,r):steps R w)\"\napply (induct \"w\")\n apply auto\napply (force)\ndone\n\n(***** Epsilon closure of start state *****)\n\nlemma unfold_rtrancl2:\n \"R^* = Id Un (R O R^*)\"\napply (rule set_eqI)\napply (simp)\napply (rule iffI)\n apply (erule rtrancl_induct)\n  apply (blast)\n apply (blast intro: rtrancl_into_rtrancl)\napply (blast intro: converse_rtrancl_into_rtrancl)\ndone\n\nlemma in_unfold_rtrancl2:\n \"(p,q) : R^* = (q = p | (? r. (p,r) : R & (r,q) : R^*))\"\napply (rule unfold_rtrancl2[THEN equalityE])\napply (blast)\ndone\n\nlemmas [iff] = in_unfold_rtrancl2[where ?p = \"start(or L R)\"] for L R\n\nlemma start_eps_or[iff]:\n \"!!L R. (start(or L R),q) : eps(or L R) = \n       (q = True#start L | q = False#start R)\"\nby (simp add:or_def step_def)\n\nlemma not_start_step_or_Some[iff]:\n \"!!L R. (start(or L R),q) ~: step (or L R) (Some a)\"\nby (simp add:or_def step_def)\n\nlemma steps_or:\n \"(start(or L R), q) : steps (or L R) w = \n ( (w = [] & q = start(or L R)) | \n   (? p.  q = True  # p & (start L,p) : steps L w | \n          q = False # p & (start R,p) : steps R w) )\"\napply (case_tac \"w\")\n apply (simp)\n apply (blast)\napply (simp)\napply (blast)\ndone\n\nlemma start_or_not_final[iff]:\n \"!!L R. ~ fin (or L R) (start(or L R))\"\nby (simp add:or_def)\n\nlemma accepts_or:\n \"accepts (or L R) w = (accepts L w | accepts R w)\"\napply (simp add:accepts_def steps_or)\n apply auto\ndone\n\n\n(******************************************************)\n(*                      conc                          *)\n(******************************************************)\n\n(** True/False in fin **)\n\nlemma in_conc_True[iff]:\n \"!!L R. fin (conc L R) (True#p) = False\"\nby (simp add:conc_def)\n\nlemma fin_conc_False[iff]:\n \"!!L R. fin (conc L R) (False#p) = fin R p\"\nby (simp add:conc_def)\n\n(** True/False in step **)\n\nlemma True_step_conc[iff]:\n \"!!L R. (True#p,q) : step (conc L R) a = \n       ((? r. q=True#r & (p,r): step L a) | \n        (fin L p & a=None & q=False#start R))\"\nby (simp add:conc_def step_def) (blast)\n\nlemma False_step_conc[iff]:\n \"!!L R. (False#p,q) : step (conc L R) a = \n       (? r. q = False#r & (p,r) : step R a)\"\nby (simp add:conc_def step_def) (blast)\n\n(** False in epsclosure **)\n\nlemma lemma1b':\n \"(tp,tq) : (eps(conc L R))^* ==> \n  (!!p. tp = False#p ==> ? q. (p,q) : (eps R)^* & tq = False#q)\"\napply (induct rule: rtrancl_induct)\n apply (blast)\napply (blast intro: rtrancl_into_rtrancl)\ndone\n\nlemma lemma2b':\n \"(p,q) : (eps R)^* ==> (False#p, False#q) : (eps(conc L R))^*\"\napply (induct rule: rtrancl_induct)\n apply (blast)\napply (blast intro: rtrancl_into_rtrancl)\ndone\n\nlemma False_epsclosure_conc[iff]:\n \"((False # p, q) : (eps (conc L R))^*) = \n (? r. q = False # r & (p, r) : (eps R)^*)\"\napply (rule iffI)\n apply (blast dest: lemma1b')\napply (blast dest: lemma2b')\ndone\n\n(** False in steps **)\n\nlemma False_steps_conc[iff]:\n \"!!p. (False#p,q): steps (conc L R) w = (? r. q=False#r & (p,r): steps R w)\"\napply (induct \"w\")\n apply (simp)\napply (simp)\napply (fast)  (*MUCH faster than blast*)\ndone\n\n(** True in epsclosure **)\n\nlemma True_True_eps_concI:\n \"(p,q): (eps L)^* ==> (True#p,True#q) : (eps(conc L R))^*\"\napply (induct rule: rtrancl_induct)\n apply (blast)\napply (blast intro: rtrancl_into_rtrancl)\ndone\n\nlemma True_True_steps_concI:\n \"!!p. (p,q) : steps L w ==> (True#p,True#q) : steps (conc L R) w\"\napply (induct \"w\")\n apply (simp add: True_True_eps_concI)\napply (simp)\napply (blast intro: True_True_eps_concI)\ndone\n\nlemma lemma1a':\n \"(tp,tq) : (eps(conc L R))^* ==> \n (!!p. tp = True#p ==> \n  (? q. tq = True#q & (p,q) : (eps L)^*) | \n  (? q r. tq = False#q & (p,r):(eps L)^* & fin L r & (start R,q) : (eps R)^*))\"\napply (induct rule: rtrancl_induct)\n apply (blast)\napply (blast intro: rtrancl_into_rtrancl)\ndone\n\nlemma lemma2a':\n \"(p, q) : (eps L)^* ==> (True#p, True#q) : (eps(conc L R))^*\"\napply (induct rule: rtrancl_induct)\n apply (blast)\napply (blast intro: rtrancl_into_rtrancl)\ndone\n\nlemma lem:\n \"!!L R. (p,q) : step R None ==> (False#p, False#q) : step (conc L R) None\"\nby(simp add: conc_def step_def)\n\nlemma lemma2b'':\n \"(p,q) : (eps R)^* ==> (False#p, False#q) : (eps(conc L R))^*\"\napply (induct rule: rtrancl_induct)\n apply (blast)\napply (drule lem)\napply (blast intro: rtrancl_into_rtrancl)\ndone\n\nlemma True_False_eps_concI:\n \"!!L R. fin L p ==> (True#p, False#start R) : eps(conc L R)\"\nby(simp add: conc_def step_def)\n\nlemma True_epsclosure_conc[iff]:\n \"((True#p,q) : (eps(conc L R))^*) = \n ((? r. (p,r) : (eps L)^* & q = True#r) | \n  (? r. (p,r) : (eps L)^* & fin L r & \n        (? s. (start R, s) : (eps R)^* & q = False#s)))\"\napply (rule iffI)\n apply (blast dest: lemma1a')\napply (erule disjE)\n apply (blast intro: lemma2a')\napply (clarify)\napply (rule rtrancl_trans)\napply (erule lemma2a')\napply (rule converse_rtrancl_into_rtrancl)\napply (erule True_False_eps_concI)\napply (erule lemma2b'')\ndone\n\n(** True in steps **)\n\nlemma True_steps_concD[rule_format]:\n \"!p. (True#p,q) : steps (conc L R) w --> \n     ((? r. (p,r) : steps L w & q = True#r)  | \n      (? u v. w = u@v & (? r. (p,r) : steps L u & fin L r & \n              (? s. (start R,s) : steps R v & q = False#s))))\"\napply (induct \"w\")\n apply (simp)\napply (simp)\napply (clarify del: disjCI)\n apply (erule disjE)\n apply (clarify del: disjCI)\n apply (erule disjE)\n  apply (clarify del: disjCI)\n  apply (erule allE, erule impE, assumption)\n  apply (erule disjE)\n   apply (blast)\n  apply (rule disjI2)\n  apply (clarify)\n  apply (simp)\n  apply (rule_tac x = \"a#u\" in exI)\n  apply (simp)\n  apply (blast)\n apply (blast)\napply (rule disjI2)\napply (clarify)\napply (simp)\napply (rule_tac x = \"[]\" in exI)\napply (simp)\napply (blast)\ndone\n\nlemma True_steps_conc:\n \"(True#p,q) : steps (conc L R) w = \n ((? r. (p,r) : steps L w & q = True#r)  | \n  (? u v. w = u@v & (? r. (p,r) : steps L u & fin L r & \n          (? s. (start R,s) : steps R v & q = False#s))))\"\nby (blast dest: True_steps_concD\n    intro: True_True_steps_concI in_steps_epsclosure)\n\n(** starting from the start **)\n\nlemma start_conc:\n  \"!!L R. start(conc L R) = True#start L\"\nby (simp add: conc_def)\n\nlemma final_conc:\n \"!!L R. fin(conc L R) p = (? s. p = False#s & fin R s)\"\nby (simp add:conc_def split: list.split)\n\nlemma accepts_conc:\n \"accepts (conc L R) w = (? u v. w = u@v & accepts L u & accepts R v)\"\napply (simp add: accepts_def True_steps_conc final_conc start_conc)\napply (blast)\ndone\n\n(******************************************************)\n(*                       star                         *)\n(******************************************************)\n\nlemma True_in_eps_star[iff]:\n \"!!A. (True#p,q) : eps(star A) = \n     ( (? r. q = True#r & (p,r) : eps A) | (fin A p & q = True#start A) )\"\nby (simp add:star_def step_def) (blast)\n\nlemma True_True_step_starI:\n  \"!!A. (p,q) : step A a ==> (True#p, True#q) : step (star A) a\"\nby (simp add:star_def step_def)\n\nlemma True_True_eps_starI:\n  \"(p,r) : (eps A)^* ==> (True#p, True#r) : (eps(star A))^*\"\napply (induct rule: rtrancl_induct)\n apply (blast)\napply (blast intro: True_True_step_starI rtrancl_into_rtrancl)\ndone\n\nlemma True_start_eps_starI:\n \"!!A. fin A p ==> (True#p,True#start A) : eps(star A)\"\nby (simp add:star_def step_def)\n\nlemma lem':\n \"(tp,s) : (eps(star A))^* ==> (! p. tp = True#p --> \n (? r. ((p,r) : (eps A)^* | \n        (? q. (p,q) : (eps A)^* & fin A q & (start A,r) : (eps A)^*)) & \n       s = True#r))\"\napply (induct rule: rtrancl_induct)\n apply (simp)\napply (clarify)\napply (simp)\napply (blast intro: rtrancl_into_rtrancl)\ndone\n\nlemma True_eps_star[iff]:\n \"((True#p,s) : (eps(star A))^*) = \n (? r. ((p,r) : (eps A)^* | \n        (? q. (p,q) : (eps A)^* & fin A q & (start A,r) : (eps A)^*)) & \n       s = True#r)\"\napply (rule iffI)\n apply (drule lem')\n apply (blast)\n(* Why can't blast do the rest? *)\napply (clarify)\napply (erule disjE)\napply (erule True_True_eps_starI)\napply (clarify)\napply (rule rtrancl_trans)\napply (erule True_True_eps_starI)\napply (rule rtrancl_trans)\napply (rule r_into_rtrancl)\napply (erule True_start_eps_starI)\napply (erule True_True_eps_starI)\ndone\n\n(** True in step Some **)\n\nlemma True_step_star[iff]:\n \"!!A. (True#p,r): step (star A) (Some a) = \n     (? q. (p,q): step A (Some a) & r=True#q)\"\nby (simp add:star_def step_def) (blast)\n\n\n(** True in steps **)\n\n(* reverse list induction! Complicates matters for conc? *)\nlemma True_start_steps_starD[rule_format]:\n \"!rr. (True#start A,rr) : steps (star A) w --> \n (? us v. w = concat us @ v & \n             (!u:set us. accepts A u) & \n             (? r. (start A,r) : steps A v & rr = True#r))\"\napply (induct w rule: rev_induct)\n apply (simp)\n apply (clarify)\n apply (rule_tac x = \"[]\" in exI)\n apply (erule disjE)\n  apply (simp)\n apply (clarify)\n apply (simp)\napply (simp add: O_assoc[symmetric] epsclosure_steps)\napply (clarify)\napply (erule allE, erule impE, assumption)\napply (clarify)\napply (erule disjE)\n apply (rule_tac x = \"us\" in exI)\n apply (rule_tac x = \"v@[x]\" in exI)\n apply (simp add: O_assoc[symmetric] epsclosure_steps)\n apply (blast)\napply (clarify)\napply (rule_tac x = \"us@[v@[x]]\" in exI)\napply (rule_tac x = \"[]\" in exI)\napply (simp add: accepts_def)\napply (blast)\ndone\n\nlemma True_True_steps_starI:\n  \"!!p. (p,q) : steps A w ==> (True#p,True#q) : steps (star A) w\"\napply (induct \"w\")\n apply (simp)\napply (simp)\napply (blast intro: True_True_eps_starI True_True_step_starI)\ndone\n\nlemma steps_star_cycle:\n \"(!u : set us. accepts A u) ==> \n (True#start A,True#start A) : steps (star A) (concat us)\"\napply (induct \"us\")\n apply (simp add:accepts_def)\napply (simp add:accepts_def)\nby(blast intro: True_True_steps_starI True_start_eps_starI in_epsclosure_steps)\n\n(* Better stated directly with start(star A)? Loop in star A back to start(star A)?*)\nlemma True_start_steps_star:\n \"(True#start A,rr) : steps (star A) w = \n (? us v. w = concat us @ v & \n             (!u:set us. accepts A u) & \n             (? r. (start A,r) : steps A v & rr = True#r))\"\napply (rule iffI)\n apply (erule True_start_steps_starD)\napply (clarify)\napply (blast intro: steps_star_cycle True_True_steps_starI)\ndone\n\n(** the start state **)\n\nlemma start_step_star[iff]:\n  \"!!A. (start(star A),r) : step (star A) a = (a=None & r = True#start A)\"\nby (simp add:star_def step_def)\n\nlemmas epsclosure_start_step_star =\n  in_unfold_rtrancl2[where ?p = \"start (star A)\"] for A\n\nlemma start_steps_star:\n \"(start(star A),r) : steps (star A) w = \n ((w=[] & r= start(star A)) | (True#start A,r) : steps (star A) w)\"\napply (rule iffI)\n apply (case_tac \"w\")\n  apply (simp add: epsclosure_start_step_star)\n apply (simp)\n apply (clarify)\n apply (simp add: epsclosure_start_step_star)\n apply (blast)\napply (erule disjE)\n apply (simp)\napply (blast intro: in_steps_epsclosure)\ndone\n\nlemma fin_star_True[iff]: \"!!A. fin (star A) (True#p) = fin A p\"\nby (simp add:star_def)\n\nlemma fin_star_start[iff]: \"!!A. fin (star A) (start(star A))\"\nby (simp add:star_def)\n\n(* too complex! Simpler if loop back to start(star A)? *)\nlemma accepts_star:\n \"accepts (star A) w = \n (? us. (!u : set(us). accepts A u) & (w = concat us) )\"\napply(unfold accepts_def)\napply (simp add: start_steps_star True_start_steps_star)\napply (rule iffI)\n apply (clarify)\n apply (erule disjE)\n  apply (clarify)\n  apply (simp)\n  apply (rule_tac x = \"[]\" in exI)\n  apply (simp)\n apply (clarify)\n apply (rule_tac x = \"us@[v]\" in exI)\n apply (simp add: accepts_def)\n apply (blast)\napply (clarify)\napply (rule_tac xs = \"us\" in rev_exhaust)\n apply (simp)\n apply (blast)\napply (clarify)\napply (simp add: accepts_def)\napply (blast)\ndone\n\n\n(***** Correctness of r2n *****)\n\nlemma accepts_rexp2nae:\n \"!!w. accepts (rexp2nae r) w = (w : lang r)\"\napply (induct \"r\")\n     apply (simp add: accepts_def)\n    apply simp\n   apply (simp add: accepts_atom)\n  apply (simp add: accepts_or)\n apply (simp add: accepts_conc Regular_Set.conc_def)\napply (simp add: accepts_star in_star_iff_concat subset_iff Ball_def)\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/Functional-Automata/RegExp2NAe.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045996818987, "lm_q2_score": 0.8175744673038222, "lm_q1q2_score": 0.7253558279744291}}
{"text": "(*  \n    Author:      Ren\u00e9 Thiemann \n                 Akihisa Yamada\n    License:     BSD\n*)\nsection \\<open>Improved Code Equations\\<close>\n\ntext \\<open>This theory contains improved code equations for certain algorithms.\\<close>\n\ntheory Improved_Code_Equations\nimports \n  \"HOL-Computational_Algebra.Polynomial\"\n  \"HOL-Library.Code_Target_Nat\"\nbegin\n\nsubsection \\<open>@{const divmod_integer}.\\<close>\n\ntext \\<open>We improve @{thm divmod_integer_code} by deleting @{const sgn}-expressions.\\<close>\n\ntext \\<open>We guard the application of divmod-abs' with the condition @{term \"x \\<ge> 0 \\<and> y \\<ge> 0\"}, \n  so that application can be ensured on non-negative values. Hence, one can drop \"abs\" in \n   target language setup.\\<close>\n\ndefinition divmod_abs' where \n  \"x \\<ge> 0 \\<Longrightarrow> y \\<ge> 0 \\<Longrightarrow> divmod_abs' x y = Code_Numeral.divmod_abs x y\" \n\n(* led to an another 10 % improvement on factorization example *)\n\nlemma divmod_integer_code''[code]: \"divmod_integer k l =\n  (if k = 0 then (0, 0)\n    else if l > 0 then\n            (if k > 0 then divmod_abs' k l\n             else case divmod_abs' (- k) l of (r, s) \\<Rightarrow>\n                  if s = 0 then (- r, 0) else (- r - 1, l - s))\n    else if l = 0 then (0, k)\n    else apsnd uminus\n            (if k < 0 then divmod_abs' (-k) (-l)\n             else case divmod_abs' k (-l) of (r, s) \\<Rightarrow>\n                  if s = 0 then (- r, 0) else (- r - 1, - l - s)))\"\n   unfolding divmod_integer_code\n   by (cases \"l = 0\"; cases \"l < 0\"; cases \"l > 0\"; auto split: prod.splits simp: divmod_abs'_def divmod_abs_def)\n\ncode_printing \\<comment> \\<open>FIXME illusion of partiality\\<close>\n  constant divmod_abs' \\<rightharpoonup>\n    (SML) \"IntInf.divMod/ ( _,/ _ )\"\n    and (Eval) \"Integer.div'_mod/ ( _ )/ ( _ )\"\n    and (OCaml) \"Z.div'_rem\"\n    and (Haskell) \"divMod/ ( _ )/ ( _ )\"\n    and (Scala) \"!((k: BigInt) => (l: BigInt) =>/ if (l == 0)/ (BigInt(0), k) else/ (k '/% l))\"\n\nsubsection \\<open>@{const Euclidean_Rings.divmod_nat}.\\<close>\ntext \\<open>We implement @{const Euclidean_Rings.divmod_nat} via @{const divmod_integer}\n  instead of invoking both division and modulo separately, \n  and we further simplify the case-analysis which is\n  performed in @{thm divmod_integer_code''}.\\<close>\n\nlemma divmod_nat_code'[code]: \"Euclidean_Rings.divmod_nat m n = (\n  let k = integer_of_nat m; l = integer_of_nat n\n  in map_prod nat_of_integer nat_of_integer\n  (if k = 0 then (0, 0)\n    else if l = 0 then (0,k) else\n            divmod_abs' k l))\"\n  using divmod_nat_code [of m n]\n  by (simp add: divmod_abs'_def integer_of_nat_eq_of_nat Let_def)\n\n\nsubsection \\<open>@{const binomial}\\<close>\n\nlemma binomial_code[code]:\n  \"n choose k = (if k \\<le> n then fact n div (fact k * fact (n - k)) else 0)\"\n  using binomial_eq_0[of n k] binomial_altdef_nat[of k 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/Polynomial_Interpolation/Improved_Code_Equations.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8872045817875224, "lm_q2_score": 0.8175744828610095, "lm_q1q2_score": 0.7253558271468519}}
{"text": "(*  Author:  Florian Haftmann, TU Muenchen\n*)\n\nsubsection \\<open>Rounded division: modulus centered towars zero.\\<close>\n\ntheory Rounded_Division\n  imports Main\nbegin\n\ndefinition rounded_divide :: \\<open>int \\<Rightarrow> int \\<Rightarrow> int\\<close>  (infixl \\<open>rdiv\\<close> 70)\n  where \\<open>k rdiv l = (k + l div 2 + of_bool (l < 0)) div l\\<close>\n\ndefinition rounded_modulo :: \\<open>int \\<Rightarrow> int \\<Rightarrow> int\\<close>  (infixl \\<open>rmod\\<close> 70)\n  where \\<open>k rmod l = k - k rdiv l * l\\<close>\n\nlemma rdiv_mult_rmod_eq:\n  \\<open>k rdiv l * l + k rmod l = k\\<close>\n  by (simp add: rounded_divide_def rounded_modulo_def)\n\nlemma mult_rdiv_rmod_eq:\n  \\<open>l * (k rdiv l) + k rmod l = k\\<close>\n  using rdiv_mult_rmod_eq [of k l] by (simp add: ac_simps)\n\nlemma rmod_rdiv_mult_eq:\n  \\<open>k rmod l + k rdiv l * l = k\\<close>\n  using rdiv_mult_rmod_eq [of k l] by (simp add: ac_simps)\n\nlemma rmod_mult_rdiv_eq:\n  \\<open>k rmod l + l * (k rdiv l) = k\\<close>\n  using rdiv_mult_rmod_eq [of k l] by (simp add: ac_simps)\n\nlemma minus_rdiv_mult_eq_rmod:\n  \\<open>k - k rdiv l * l = k rmod l\\<close>\n  by (rule add_implies_diff [symmetric]) (fact rmod_rdiv_mult_eq)\n\nlemma minus_mult_rdiv_eq_rmod:\n  \\<open>k - l * (k rdiv l) = k rmod l\\<close>\n  by (rule add_implies_diff [symmetric]) (fact rmod_mult_rdiv_eq)\n\nlemma minus_rmod_eq_rdiv_mult:\n  \\<open>k - k rmod l = k rdiv l * l\\<close>\n  by (rule add_implies_diff [symmetric]) (fact rdiv_mult_rmod_eq)\n\nlemma minus_rmod_eq_mult_rdiv:\n  \\<open>k - k rmod l = l * (k rdiv l)\\<close>\n  by (rule add_implies_diff [symmetric]) (fact mult_rdiv_rmod_eq)\n\nlemma rdiv_0_eq [simp]:\n  \\<open>k rdiv 0 = 0\\<close>\n  by (simp add: rounded_divide_def)\n\nlemma rmod_0_eq [simp]:\n  \\<open>k rmod 0 = k\\<close>\n  by (simp add: rounded_modulo_def)\n\nlemma rdiv_1_eq [simp]:\n  \\<open>k rdiv 1 = k\\<close>\n  by (simp add: rounded_divide_def)\n\nlemma rmod_1_eq [simp]:\n  \\<open>k rmod 1 = 0\\<close>\n  by (simp add: rounded_modulo_def)\n\nlemma zero_rdiv_eq [simp]:\n  \\<open>0 rdiv k = 0\\<close>\n  by (auto simp add: rounded_divide_def not_less zdiv_eq_0_iff)\n\nlemma zero_rmod_eq [simp]:\n  \\<open>0 rmod k = 0\\<close>\n  by (simp add: rounded_modulo_def)\n\nlemma nonzero_mult_rdiv_cancel_right:\n  \\<open>k * l rdiv l = k\\<close> if \\<open>l \\<noteq> 0\\<close>\n  using that by (auto simp add: rounded_divide_def ac_simps)\n\nlemma rdiv_self_eq [simp]:\n  \\<open>k rdiv k = 1\\<close> if \\<open>k \\<noteq> 0\\<close>\n  using that nonzero_mult_rdiv_cancel_right [of k 1] by simp\n\nlemma rmod_self_eq [simp]:\n  \\<open>k rmod k = 0\\<close>\n  by (cases \\<open>k = 0\\<close>) (simp_all add: rounded_modulo_def)\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/Library/Rounded_Division.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045817875224, "lm_q2_score": 0.8175744806385543, "lm_q1q2_score": 0.7253558251750793}}
{"text": "(*   Author:      Florian Haftmann, TU Muenchen; based on existing material on complex numbers\\<close>\n*)\n\nsection \\<open>Gauss Numbers: integral gauss numbers\\<close>\n\ntheory Gauss_Numbers\n  imports \"HOL-Library.Rounded_Division\"\nbegin\n\ncodatatype gauss = Gauss (Re: int) (Im: int)\n\nlemma gauss_eqI [intro?]:\n  \\<open>x = y\\<close> if \\<open>Re x = Re y\\<close> \\<open>Im x = Im y\\<close>\n  by (rule gauss.expand) (use that in simp)\n\nlemma gauss_eq_iff:\n  \\<open>x = y \\<longleftrightarrow> Re x = Re y \\<and> Im x = Im y\\<close>\n  by (auto intro: gauss_eqI)\n\n\nsubsection \\<open>Basic arithmetic\\<close>\n\ninstantiation gauss :: comm_ring_1\nbegin\n\nprimcorec zero_gauss :: \\<open>gauss\\<close>\n  where\n    \\<open>Re 0 = 0\\<close>\n  | \\<open>Im 0 = 0\\<close>\n\nprimcorec one_gauss :: \\<open>gauss\\<close>\n  where\n    \\<open>Re 1 = 1\\<close>\n  | \\<open>Im 1 = 0\\<close>\n\nprimcorec plus_gauss :: \\<open>gauss \\<Rightarrow> gauss \\<Rightarrow> gauss\\<close>\n  where\n    \\<open>Re (x + y) = Re x + Re y\\<close>\n  | \\<open>Im (x + y) = Im x + Im y\\<close>\n\nprimcorec uminus_gauss :: \\<open>gauss \\<Rightarrow> gauss\\<close>\n  where\n    \\<open>Re (- x) = - Re x\\<close>\n  | \\<open>Im (- x) = - Im x\\<close>\n\nprimcorec minus_gauss :: \\<open>gauss \\<Rightarrow> gauss \\<Rightarrow> gauss\\<close>\n  where\n    \\<open>Re (x - y) = Re x - Re y\\<close>\n  | \\<open>Im (x - y) = Im x - Im y\\<close>\n\nprimcorec times_gauss :: \\<open>gauss \\<Rightarrow> gauss \\<Rightarrow> gauss\\<close>\n  where\n    \\<open>Re (x * y) = Re x * Re y - Im x * Im y\\<close>\n  | \\<open>Im (x * y) = Re x * Im y + Im x * Re y\\<close>\n\ninstance\n  by standard (simp_all add: gauss_eq_iff algebra_simps)\n\nend\n\nlemma of_nat_gauss:\n  \\<open>of_nat n = Gauss (int n) 0\\<close>\n  by (induction n) (simp_all add: gauss_eq_iff)\n\nlemma numeral_gauss:\n  \\<open>numeral n = Gauss (numeral n) 0\\<close>\nproof -\n  have \\<open>numeral n = (of_nat (numeral n) :: gauss)\\<close>\n    by simp\n  also have \\<open>\\<dots> = Gauss (of_nat (numeral n)) 0\\<close>\n    by (simp add: of_nat_gauss)\n  finally show ?thesis\n    by simp\nqed\n\nlemma of_int_gauss:\n  \\<open>of_int k = Gauss k 0\\<close>\n  by (simp add: gauss_eq_iff of_int_of_nat of_nat_gauss)\n\nlemma conversion_simps [simp]:\n  \\<open>Re (numeral m) = numeral m\\<close>\n  \\<open>Im (numeral m) = 0\\<close>\n  \\<open>Re (of_nat n) = int n\\<close>\n  \\<open>Im (of_nat n) = 0\\<close>\n  \\<open>Re (of_int k) = k\\<close>\n  \\<open>Im (of_int k) = 0\\<close>\n  by (simp_all add: numeral_gauss of_nat_gauss of_int_gauss)\n\nlemma gauss_eq_0:\n  \\<open>z = 0 \\<longleftrightarrow> (Re z)\\<^sup>2 + (Im z)\\<^sup>2 = 0\\<close>\n  by (simp add: gauss_eq_iff sum_power2_eq_zero_iff)\n\nlemma gauss_neq_0:\n  \\<open>z \\<noteq> 0 \\<longleftrightarrow> (Re z)\\<^sup>2 + (Im z)\\<^sup>2 > 0\\<close>\n  by (simp add: gauss_eq_0 sum_power2_ge_zero less_le)\n\nlemma Re_sum [simp]:\n  \\<open>Re (sum f s) = (\\<Sum>x\\<in>s. Re (f x))\\<close>\n  by (induct s rule: infinite_finite_induct) auto\n\nlemma Im_sum [simp]:\n  \\<open>Im (sum f s) = (\\<Sum>x\\<in>s. Im (f x))\\<close>\n  by (induct s rule: infinite_finite_induct) auto\n\ninstance gauss :: idom\nproof\n  fix x y :: gauss\n  assume \\<open>x \\<noteq> 0\\<close> \\<open>y \\<noteq> 0\\<close>\n  then show \\<open>x * y \\<noteq> 0\\<close>\n    by (simp_all add: gauss_eq_iff)\n      (smt (verit, best) mult_eq_0_iff mult_neg_neg mult_neg_pos mult_pos_neg mult_pos_pos)\nqed\n\n\n\nsubsection \\<open>The Gauss Number $i$\\<close>\n\nprimcorec imaginary_unit :: gauss  (\\<open>\\<i>\\<close>)\n  where\n    \\<open>Re \\<i> = 0\\<close>\n  | \\<open>Im \\<i> = 1\\<close>\n\nlemma Gauss_eq:\n  \\<open>Gauss a b = of_int a + \\<i> * of_int b\\<close>\n  by (simp add: gauss_eq_iff)\n\nlemma gauss_eq:\n  \\<open>a = of_int (Re a) + \\<i> * of_int (Im a)\\<close>\n  by (simp add: gauss_eq_iff)\n\nlemma gauss_i_not_zero [simp]:\n  \\<open>\\<i> \\<noteq> 0\\<close>\n  by (simp add: gauss_eq_iff)\n\nlemma gauss_i_not_one [simp]:\n  \\<open>\\<i> \\<noteq> 1\\<close>\n  by (simp add: gauss_eq_iff)\n\nlemma gauss_i_not_numeral [simp]:\n  \\<open>\\<i> \\<noteq> numeral n\\<close>\n  by (simp add: gauss_eq_iff)\n\nlemma gauss_i_not_neg_numeral [simp]:\n  \\<open>\\<i> \\<noteq> - numeral n\\<close>\n  by (simp add: gauss_eq_iff)\n\nlemma i_mult_i_eq [simp]:\n  \\<open>\\<i> * \\<i> = - 1\\<close>\n  by (simp add: gauss_eq_iff)\n\nlemma gauss_i_mult_minus [simp]:\n  \\<open>\\<i> * (\\<i> * x) = - x\\<close>\n  by (simp flip: mult.assoc)\n\nlemma i_squared [simp]:\n  \\<open>\\<i>\\<^sup>2 = - 1\\<close>\n  by (simp add: power2_eq_square)\n\nlemma i_even_power [simp]:\n  \\<open>\\<i> ^ (n * 2) = (- 1) ^ n\\<close>\n  unfolding mult.commute [of n] power_mult by simp\n\nlemma Re_i_times [simp]:\n  \\<open>Re (\\<i> * z) = - Im z\\<close>\n  by simp\n\nlemma Im_i_times [simp]:\n  \\<open>Im (\\<i> * z) = Re z\\<close>\n  by simp\n\nlemma i_times_eq_iff:\n  \\<open>\\<i> * w = z \\<longleftrightarrow> w = - (\\<i> * z)\\<close>\n  by auto\n\nlemma is_unit_i [simp]:\n  \\<open>\\<i> dvd 1\\<close>\n  by (rule dvdI [of _ _ \\<open>- \\<i>\\<close>]) simp\n\nlemma gauss_numeral [code_post]:\n  \\<open>Gauss 0 0 = 0\\<close>\n  \\<open>Gauss 1 0 = 1\\<close>\n  \\<open>Gauss (- 1) 0 = - 1\\<close>\n  \\<open>Gauss (numeral n) 0 = numeral n\\<close>\n  \\<open>Gauss (- numeral n) 0 = - numeral n\\<close>\n  \\<open>Gauss 0 1 = \\<i>\\<close>\n  \\<open>Gauss 0 (- 1) = - \\<i>\\<close>\n  \\<open>Gauss 0 (numeral n) = numeral n * \\<i>\\<close>\n  \\<open>Gauss 0 (- numeral n) = - numeral n * \\<i>\\<close>\n  \\<open>Gauss 1 1 = 1 + \\<i>\\<close>\n  \\<open>Gauss (- 1) 1 = - 1 + \\<i>\\<close>\n  \\<open>Gauss (numeral n) 1 = numeral n + \\<i>\\<close>\n  \\<open>Gauss (- numeral n) 1 = - numeral n + \\<i>\\<close>\n  \\<open>Gauss 1 (- 1) = 1 - \\<i>\\<close>\n  \\<open>Gauss 1 (numeral n) = 1 + numeral n * \\<i>\\<close>\n  \\<open>Gauss 1 (- numeral n) = 1 - numeral n * \\<i>\\<close>\n  \\<open>Gauss (- 1) (- 1) = - 1 - \\<i>\\<close>\n  \\<open>Gauss (numeral n) (- 1) = numeral n - \\<i>\\<close>\n  \\<open>Gauss (- numeral n) (- 1) = - numeral n - \\<i>\\<close>\n  \\<open>Gauss (- 1) (numeral n) = - 1 + numeral n * \\<i>\\<close>\n  \\<open>Gauss (- 1) (- numeral n) = - 1 - numeral n * \\<i>\\<close>\n  \\<open>Gauss (numeral m) (numeral n) = numeral m + numeral n * \\<i>\\<close>\n  \\<open>Gauss (- numeral m) (numeral n) = - numeral m + numeral n * \\<i>\\<close>\n  \\<open>Gauss (numeral m) (- numeral n) = numeral m - numeral n * \\<i>\\<close>\n  \\<open>Gauss (- numeral m) (- numeral n) = - numeral m - numeral n * \\<i>\\<close>\n  by (simp_all add: gauss_eq_iff)\n\n\nsubsection \\<open>Gauss Conjugation\\<close>\n\nprimcorec cnj :: \\<open>gauss \\<Rightarrow> gauss\\<close>\n  where\n    \\<open>Re (cnj z) = Re z\\<close>\n  | \\<open>Im (cnj z) = - Im z\\<close>\n\nlemma gauss_cnj_cancel_iff [simp]:\n  \\<open>cnj x = cnj y \\<longleftrightarrow> x = y\\<close>\n  by (simp add: gauss_eq_iff)\n\nlemma gauss_cnj_cnj [simp]:\n  \\<open>cnj (cnj z) = z\\<close>\n  by (simp add: gauss_eq_iff)\n\nlemma gauss_cnj_zero [simp]:\n  \\<open>cnj 0 = 0\\<close>\n  by (simp add: gauss_eq_iff)\n\nlemma gauss_cnj_zero_iff [iff]:\n  \\<open>cnj z = 0 \\<longleftrightarrow> z = 0\\<close>\n  by (simp add: gauss_eq_iff)\n\nlemma gauss_cnj_one_iff [simp]:\n  \\<open>cnj z = 1 \\<longleftrightarrow> z = 1\\<close>\n  by (simp add: gauss_eq_iff)\n\nlemma gauss_cnj_add [simp]:\n  \\<open>cnj (x + y) = cnj x + cnj y\\<close>\n  by (simp add: gauss_eq_iff)\n\nlemma cnj_sum [simp]:\n  \\<open>cnj (sum f s) = (\\<Sum>x\\<in>s. cnj (f x))\\<close>\n  by (induct s rule: infinite_finite_induct) auto\n\nlemma gauss_cnj_diff [simp]:\n  \\<open>cnj (x - y) = cnj x - cnj y\\<close>\n  by (simp add: gauss_eq_iff)\n\nlemma gauss_cnj_minus [simp]:\n  \\<open>cnj (- x) = - cnj x\\<close>\n  by (simp add: gauss_eq_iff)\n\nlemma gauss_cnj_one [simp]:\n  \\<open>cnj 1 = 1\\<close>\n  by (simp add: gauss_eq_iff)\n\nlemma gauss_cnj_mult [simp]:\n  \\<open>cnj (x * y) = cnj x * cnj y\\<close>\n  by (simp add: gauss_eq_iff)\n\nlemma cnj_prod [simp]:\n  \\<open>cnj (prod f s) = (\\<Prod>x\\<in>s. cnj (f x))\\<close>\n  by (induct s rule: infinite_finite_induct) auto\n\nlemma gauss_cnj_power [simp]:\n  \\<open>cnj (x ^ n) = cnj x ^ n\\<close>\n  by (induct n) simp_all\n\nlemma gauss_cnj_numeral [simp]:\n  \\<open>cnj (numeral w) = numeral w\\<close>\n  by (simp add: gauss_eq_iff)\n\nlemma gauss_cnj_of_nat [simp]:\n  \\<open>cnj (of_nat n) = of_nat n\\<close>\n  by (simp add: gauss_eq_iff)\n\nlemma gauss_cnj_of_int [simp]:\n  \\<open>cnj (of_int z) = of_int z\\<close>\n  by (simp add: gauss_eq_iff)\n\nlemma gauss_cnj_i [simp]:\n  \\<open>cnj \\<i> = - \\<i>\\<close>\n  by (simp add: gauss_eq_iff)\n\nlemma gauss_add_cnj:\n  \\<open>z + cnj z = of_int (2 * Re z)\\<close>\n  by (simp add: gauss_eq_iff)\n\nlemma gauss_diff_cnj:\n  \\<open>z - cnj z = of_int (2 * Im z) * \\<i>\\<close>\n  by (simp add: gauss_eq_iff)\n\nlemma gauss_mult_cnj:\n  \\<open>z * cnj z = of_int ((Re z)\\<^sup>2 + (Im z)\\<^sup>2)\\<close>\n  by (simp add: gauss_eq_iff power2_eq_square)\n\nlemma cnj_add_mult_eq_Re:\n  \\<open>z * cnj w + cnj z * w = of_int (2 * Re (z * cnj w))\\<close>\n  by (simp add: gauss_eq_iff)\n\nlemma gauss_In_mult_cnj_zero [simp]:\n  \\<open>Im (z * cnj z) = 0\\<close>\n  by simp\n\n\nsubsection \\<open>Algebraic division\\<close>\n\ninstantiation gauss :: idom_modulo\nbegin\n\nprimcorec divide_gauss :: \\<open>gauss \\<Rightarrow> gauss \\<Rightarrow> gauss\\<close>\n  where\n    \\<open>Re (x div y) = (Re x * Re y + Im x * Im y) rdiv ((Re y)\\<^sup>2 + (Im y)\\<^sup>2)\\<close>\n  | \\<open>Im (x div y) = (Im x * Re y - Re x * Im y) rdiv ((Re y)\\<^sup>2 + (Im y)\\<^sup>2)\\<close>\n\nprimcorec modulo_gauss :: \\<open>gauss \\<Rightarrow> gauss \\<Rightarrow> gauss\\<close>\n  where\n    \\<open>Re (x mod y) = Re x -\n      ((Re x * Re y + Im x * Im y) rdiv ((Re y)\\<^sup>2 + (Im y)\\<^sup>2) * Re y -\n       (Im x * Re y - Re x * Im y) rdiv ((Re y)\\<^sup>2 + (Im y)\\<^sup>2) * Im y)\\<close>\n  | \\<open>Im (x mod y) = Im x -\n      ((Re x * Re y + Im x * Im y) rdiv ((Re y)\\<^sup>2 + (Im y)\\<^sup>2) * Im y +\n       (Im x * Re y - Re x * Im y) rdiv ((Re y)\\<^sup>2 + (Im y)\\<^sup>2) * Re y)\\<close>\n\ninstance proof\n  fix x y :: gauss\n  show \\<open>x div 0 = 0\\<close>\n    by (simp add: gauss_eq_iff)\n  show \\<open>x * y div y = x\\<close> if \\<open>y \\<noteq> 0\\<close>\n  proof -\n    define Y where \\<open>Y = (Re y)\\<^sup>2 + (Im y)\\<^sup>2\\<close>\n    moreover have \\<open>Y > 0\\<close>\n      using that by (simp add: gauss_eq_0 less_le Y_def)\n    have *: \\<open>Im y * (Im y * Re x) + Re x * (Re y * Re y) = Re x * Y\\<close>\n      \\<open>Im x * (Im y * Im y) + Im x * (Re y * Re y) = Im x * Y\\<close>\n      \\<open>(Im y)\\<^sup>2 + (Re y)\\<^sup>2 = Y\\<close>\n      by (simp_all add: power2_eq_square algebra_simps Y_def)\n    from \\<open>Y > 0\\<close> show ?thesis\n      by (simp add: gauss_eq_iff algebra_simps) (simp add: * nonzero_mult_rdiv_cancel_right)\n  qed\n  show \\<open>x div y * y + x mod y = x\\<close>\n    by (simp add: gauss_eq_iff)\nqed\n\nend\n\ninstantiation gauss :: euclidean_ring\nbegin\n\ndefinition euclidean_size_gauss :: \\<open>gauss \\<Rightarrow> nat\\<close>\n  where \\<open>euclidean_size x = nat ((Re x)\\<^sup>2 + (Im x)\\<^sup>2)\\<close>\n\ninstance proof\n  show \\<open>euclidean_size (0::gauss) = 0\\<close>\n    by (simp add: euclidean_size_gauss_def)\n  show \\<open>euclidean_size (x mod y) < euclidean_size y\\<close> if \\<open>y \\<noteq> 0\\<close> for x y :: gauss\n  proof-\n    define X and Y and R and I\n      where \\<open>X = (Re x)\\<^sup>2 + (Im x)\\<^sup>2\\<close> and \\<open>Y = (Re y)\\<^sup>2 + (Im y)\\<^sup>2\\<close>\n        and \\<open>R = Re x * Re y + Im x * Im y\\<close> and \\<open>I = Im x * Re y - Re x * Im y\\<close>\n    with that have \\<open>0 < Y\\<close> and rhs: \\<open>int (euclidean_size y) = Y\\<close>\n      by (simp_all add: gauss_neq_0 euclidean_size_gauss_def)\n    have \\<open>X * Y = R\\<^sup>2 + I\\<^sup>2\\<close>\n      by (simp add: R_def I_def X_def Y_def power2_eq_square algebra_simps)\n    let ?lhs = \\<open>X - I * (I rdiv Y) - R * (R rdiv Y)\n        - I rdiv Y * (I rmod Y) - R rdiv Y * (R rmod Y)\\<close>\n    have \\<open>?lhs = X + Y * (R rdiv Y) * (R rdiv Y) + Y * (I rdiv Y) * (I rdiv Y)\n        - 2 * (R rdiv Y * R + I rdiv Y * I)\\<close>\n      by (simp flip: minus_rmod_eq_mult_rdiv add: algebra_simps)\n    also have \\<open>\\<dots> = (Re (x mod y))\\<^sup>2 + (Im (x mod y))\\<^sup>2\\<close>\n      by (simp add: X_def Y_def R_def I_def algebra_simps power2_eq_square)\n    finally have lhs: \\<open>int (euclidean_size (x mod y)) = ?lhs\\<close>\n      by (simp add: euclidean_size_gauss_def)\n    have \\<open>?lhs * Y = (I rmod Y)\\<^sup>2 + (R rmod Y)\\<^sup>2\\<close>\n      apply (simp add: algebra_simps power2_eq_square \\<open>X * Y = R\\<^sup>2 + I\\<^sup>2\\<close>)\n      apply (simp flip: mult.assoc add.assoc minus_rmod_eq_mult_rdiv)\n      apply (simp add: algebra_simps)\n      done\n    also have \\<open>\\<dots> \\<le> (Y div 2)\\<^sup>2 + (Y div 2)\\<^sup>2\\<close>\n      by (rule add_mono) (use \\<open>Y > 0\\<close> abs_rmod_less_equal [of Y] in \\<open>simp_all add: power2_le_iff_abs_le\\<close>)\n    also have \\<open>\\<dots> < Y\\<^sup>2\\<close>\n      using \\<open>Y > 0\\<close> by (cases \\<open>Y = 1\\<close>) (simp_all add: power2_eq_square mult_le_less_imp_less flip: mult.assoc)\n    finally have \\<open>?lhs * Y < Y\\<^sup>2\\<close> .\n    with \\<open>Y > 0\\<close> have \\<open>?lhs < Y\\<close>\n      by (simp add: power2_eq_square)\n    then have \\<open>int (euclidean_size (x mod y)) < int (euclidean_size y)\\<close>\n      by (simp only: lhs rhs)\n    then show ?thesis\n      by simp\n  qed\n  show \\<open>euclidean_size x \\<le> euclidean_size (x * y)\\<close> if \\<open>y \\<noteq> 0\\<close> for x y :: gauss\n  proof -\n    from that have \\<open>euclidean_size y > 0\\<close>\n      by (simp add: euclidean_size_gauss_def gauss_neq_0)\n    then have \\<open>euclidean_size x \\<le> euclidean_size x * euclidean_size y\\<close>\n      by simp\n    also have \\<open>\\<dots> = nat (((Re x)\\<^sup>2 + (Im x)\\<^sup>2) * ((Re y)\\<^sup>2 + (Im y)\\<^sup>2))\\<close>\n      by (simp add: euclidean_size_gauss_def nat_mult_distrib)\n    also have \\<open>\\<dots> = euclidean_size (x * y)\\<close>\n      by (simp add: euclidean_size_gauss_def eq_nat_nat_iff) (simp add: algebra_simps power2_eq_square)\n    finally show ?thesis .\n  qed\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/Examples/Gauss_Numbers.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382200964035, "lm_q2_score": 0.8418256393148982, "lm_q1q2_score": 0.7252649629268743}}
{"text": "section \"Priority Queues Based on Braun Trees 2\"\n\ntheory Priority_Queue_Braun2\nimports Priority_Queue_Braun\nbegin\n\ntext \\<open>This is the version verified by Jean-Christophe Filli\u00e2tre with the help of the Why3 system\n\\<^url>\\<open>http://toccata.lri.fr/gallery/braun_trees.en.html\\<close>.\nOnly the deletion function (\\<open>del_min2\\<close> below) differs from Paulson's version.\nBut the difference turns out to be minor --- see below.\\<close>\n\n\nsubsection \"Function \\<open>del_min2\\<close>\"\n\nfun le_root :: \"'a::linorder \\<Rightarrow> 'a tree \\<Rightarrow> bool\" where\n\"le_root a t = (t = Leaf \\<or> a \\<le> value t)\"\n\nfun replace_min :: \"'a::linorder \\<Rightarrow> 'a tree \\<Rightarrow> 'a tree\" where\n\"replace_min x (Node l _ r) =\n  (if le_root x l & le_root x r then Node l x r\n   else\n     let a = value l in\n     if le_root a r then Node (replace_min x l) a r\n     else Node l (value r) (replace_min x r))\"\n\nfun merge :: \"'a::linorder tree \\<Rightarrow> 'a tree \\<Rightarrow> 'a tree\" where\n\"merge l Leaf = l\" |\n\"merge (Node l1 a1 r1) (Node l2 a2 r2) =\n   (if a1 \\<le> a2 then Node (Node l2 a2 r2) a1 (merge l1 r1)\n    else let (x, l') = del_left (Node l1 a1 r1)\n         in Node (replace_min x (Node l2 a2 r2)) a2 l')\"\n\nfun del_min2 where\n\"del_min2 Leaf = Leaf\" |\n\"del_min2 (Node l x r) = merge l r\"\n\n\nsubsection \"Correctness Proof\"\n\ntext \\<open>It turns out that @{const replace_min} is just @{const sift_down} in disguise:\\<close>\n\nlemma replace_min_sift_down: \"braun (Node l a r) \\<Longrightarrow> replace_min x (Node l a r) = sift_down l x r\"\nby(induction l x r rule: sift_down.induct)(auto)\n\ntext \\<open>This means that @{const del_min2} is merely a slight optimization of @{const del_min}:\ninstead of calling @{const del_left} right away, @{const merge} can take advantage of the case\nwhere the smaller element is at the root of the left heap and can be moved up without complications.\nHowever, on average this is just the case on the first level.\\<close>\n\ntext \\<open>Function @{const merge}:\\<close>\n\nlemma mset_tree_merge:\n  \"braun (Node l x r) \\<Longrightarrow> mset_tree(merge l r) = mset_tree l + mset_tree r\"\nby(induction l r rule: merge.induct)\n  (auto simp: Let_def tree.set_sel(2) mset_sift_down replace_min_sift_down\n        simp del: replace_min.simps dest!: del_left_mset split!: prod.split)\n\nlemma heap_merge:\n  \"\\<lbrakk> braun (Node l x r); heap l; heap r \\<rbrakk> \\<Longrightarrow> heap(merge l r)\"\nproof(induction l r rule: merge.induct)\n  case 1 thus ?case by simp\nnext\n  case (2 l1 a1 r1 l2 a2 r2)\n  show ?case\n  proof cases\n    assume \"a1 \\<le> a2\"\n    thus ?thesis using 2 by(auto simp: ball_Un mset_tree_merge simp flip: set_mset_tree)\n  next\n    assume \"\\<not> a1 \\<le> a2\"\n    let ?l = \"Node l1 a1 r1\" let ?r = \"Node l2 a2 r2\"\n    have \"braun ?r\" using \"2.prems\"(1) by auto\n    obtain x l' where dl: \"del_left ?l = (x, l')\" by (metis surj_pair)\n    from del_left_heap[OF this _ \"2.prems\"(2)] have \"heap l'\" by auto\n    have hr: \"heap(replace_min x ?r)\" using \\<open>braun ?r\\<close> \"2.prems\"(3)\n      by(simp add: heap_sift_down neq_Leaf_iff replace_min_sift_down del: replace_min.simps)\n    have 0: \"\\<forall>x \\<in> set_tree ?l. a2 \\<le> x\" using \"2.prems\"(2) \\<open>\\<not> a1 \\<le> a2\\<close> by (auto simp: ball_Un)\n    moreover have \"set_tree l' \\<subseteq> set_tree ?l\" \"x \\<in> set_tree ?l\"\n      using del_left_mset[OF dl] by (auto simp flip: set_mset_tree dest:in_diffD simp: union_iff)\n    ultimately have 1: \"\\<forall>x \\<in> set_tree l'. a2 \\<le> x\" by blast\n    have \"\\<forall>x \\<in> set_tree ?r. a2 \\<le> x\" using \\<open>heap ?r\\<close> by auto\n    thus ?thesis\n      using \\<open>\\<not> a1 \\<le> a2\\<close> dl \\<open>heap(replace_min x ?r)\\<close> \\<open>heap l'\\<close> \\<open>x \\<in> set_tree ?l\\<close> 0 1 \\<open>braun ?r\\<close>\n      by(auto simp: mset_sift_down replace_min_sift_down simp flip: set_mset_tree\n              simp del: replace_min.simps)\n  qed\nnext\n  case 3 thus ?case by simp\nqed\n\nlemma del_left_braun_size:\n  \"del_left t = (x,t') \\<Longrightarrow> braun t \\<Longrightarrow> t \\<noteq> Leaf \\<Longrightarrow> braun t' \\<and> size t = size t' + 1\"\nby (simp add: del_left_braun del_left_size)\n\nlemma braun_size_merge:\n  \"braun (Node l x r) \\<Longrightarrow> braun(merge l r) \\<and> size(merge l r) = size l + size r\"\napply(induction l r rule: merge.induct)\napply(auto simp: size_sift_down braun_sift_down replace_min_sift_down\n           simp del: replace_min.simps\n           dest!: del_left_braun_size split!: prod.split)\ndone\n\n\ntext \\<open>Last step: prove all axioms of the priority queue specification:\\<close>\n\ninterpretation braun: Priority_Queue\nwhere empty = Leaf and is_empty = \"\\<lambda>h. h = Leaf\"\nand insert = insert and del_min = del_min2\nand get_min = \"value\" and invar = \"\\<lambda>h. braun h \\<and> heap h\"\nand mset = mset_tree\nproof(standard, goal_cases)\n  case 1 show ?case by simp\nnext\n  case 2 show ?case by simp\nnext\n  case 3 show ?case by(simp add: mset_insert)\nnext\n  case 4 thus ?case by(auto simp: mset_tree_merge neq_Leaf_iff)\nnext\n  case 5 thus ?case using get_min mset_tree.simps(1) by blast\nnext\n  case 6 thus ?case by(simp)\nnext\n  case 7 thus ?case by(simp add: heap_insert braun_insert)\nnext\n  case 8 thus ?case by(auto simp: heap_merge braun_size_merge neq_Leaf_iff)\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/Priority_Queue_Braun/Priority_Queue_Braun2.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8418256393148982, "lm_q2_score": 0.8615382076534742, "lm_q1q2_score": 0.7252649524520974}}
{"text": "(*\n    Author:     Lawrence C Paulson, Cambridge University Computer Laboratory\n                Tobias Nipkow, TUM\n*)\n\ntheory Tilings imports Main begin\n\nsection{* Inductive Tiling *}\n\n\ninductive_set\n  tiling :: \"'a set set \\<Rightarrow> 'a set set\"\n  for A :: \"'a set set\" where\nempty [simp, intro]: \"{} \\<in> tiling A\" |\nUn [simp, intro]:    \"\\<lbrakk> a \\<in> A; t \\<in> tiling A; a \\<inter> t = {} \\<rbrakk>\n                         \\<Longrightarrow> a \\<union> t \\<in> tiling A\"\n\n\nlemma tiling_UnI [intro]:\n  \"\\<lbrakk> t \\<in> tiling A; u \\<in> tiling A; t \\<inter> u = {} \\<rbrakk> \\<Longrightarrow>  t \\<union> u \\<in> tiling A\"\napply (induct set: tiling)\napply (auto simp add: Un_assoc)\ndone\n\nlemma tiling_Diff1E:\nassumes \"t-a \\<in> tiling A\" and \"a \\<in> A\" and \"a \\<subseteq> t\"\nshows \"t \\<in> tiling A\"\nproof -\n  from assms(2-3) have  \"EX r. t = r Un a & r Int a = {}\"\n    by (metis Diff_disjoint Int_commute Un_Diff_cancel Un_absorb1 Un_commute)\n  thus ?thesis using assms(1,2)\n    by (auto simp:Un_Diff)\n       (metis Compl_Diff_eq Diff_Compl Diff_empty Int_commute Un_Diff_cancel\n              Un_commute double_complement tiling.Un)\nqed\n\nlemma tiling_finite:\n  assumes \"\\<And>a. a \\<in> A \\<Longrightarrow> finite a\"\n  shows \"t \\<in> tiling A \\<Longrightarrow> finite t\"\napply (induct set: tiling)\nusing assms apply auto\ndone\n\n\nsection{* The Mutilated Chess Board Cannot be Tiled by Dominoes *}\n\ntext {* The originator of this problem is Max Black, according to J A\nRobinson. It was popularized as the \\emph{Mutilated Checkerboard Problem} by\nJ McCarthy.  *}\n\ninductive_set domino :: \"(nat \\<times> nat) set set\" where\nhoriz [simp]: \"{(i, j), (i, Suc j)} \\<in> domino\" |\nvertl [simp]: \"{(i, j), (Suc i, j)} \\<in> domino\"\n\nlemma domino_finite: \"d \\<in> domino \\<Longrightarrow> finite d\"\nby (erule domino.cases, auto)\n\ndeclare tiling_finite[OF domino_finite, simp]\n\ntext {* \\medskip Sets of squares of the given colour *}\n\ndefinition\n  coloured :: \"nat \\<Rightarrow> (nat \\<times> nat) set\" where\n  \"coloured b = {(i, j). (i + j) mod 2 = b}\"\n\nabbreviation\n  whites  :: \"(nat \\<times> nat) set\" where\n  \"whites \\<equiv> coloured 0\"\n\nabbreviation\n  blacks  :: \"(nat \\<times> nat) set\" where\n  \"blacks \\<equiv> coloured (Suc 0)\"\n\n\ntext {* \\medskip Chess boards *}\n\nlemma Sigma_Suc1 [simp]:\n  \"{0..< Suc n} \\<times> B = ({n} \\<times> B) \\<union> ({0..<n} \\<times> B)\"\nby auto\n\nlemma Sigma_Suc2 [simp]:\n  \"A \\<times> {0..< Suc n} = (A \\<times> {n}) \\<union> (A \\<times> {0..<n})\"\nby auto\n\nlemma dominoes_tile_row [intro!]: \"{i} \\<times> {0..< 2*n} \\<in> tiling domino\"\napply (induct n)\napply (simp_all del:Un_insert_left add: Un_assoc [symmetric])\ndone\n\nlemma dominoes_tile_matrix: \"{0..<m} \\<times> {0..< 2*n} \\<in> tiling domino\"\nby (induct m) auto\n\n\ntext {* \\medskip @{term coloured} and Dominoes *}\n\nlemma coloured_insert [simp]:\n  \"coloured b \\<inter> (insert (i, j) t) =\n   (if (i + j) mod 2 = b then insert (i, j) (coloured b \\<inter> t)\n    else coloured b \\<inter> t)\"\nby (auto simp add: coloured_def)\n\nlemma domino_singletons:\n  \"d \\<in> domino \\<Longrightarrow>\n   (\\<exists>i j. whites \\<inter> d = {(i, j)}) \\<and>\n   (\\<exists>m n. blacks \\<inter> d = {(m, n)})\"\napply (erule domino.cases)\n apply (auto simp add: mod_Suc)\ndone\n\n\ntext {* \\medskip Tilings of dominoes *}\n\ndeclare\n  Int_Un_distrib [simp]\n  Diff_Int_distrib [simp]\n\nlemma tiling_domino_0_1:\n  \"t \\<in> tiling domino ==> card(whites \\<inter> t) = card(blacks \\<inter> t)\"\napply (induct set: tiling)\n apply (drule_tac [2] domino_singletons)\n apply (auto)\napply (subgoal_tac \"\\<forall>p C. C \\<inter> a = {p} --> p \\<notin> t\")\n  -- {* this lemma tells us that both ``inserts'' are non-trivial *}\n apply (simp (no_asm_simp))\napply blast\ndone\n\n\ntext {* \\medskip Final argument is surprisingly complex *}\n\ntheorem gen_mutil_not_tiling:\n  \"t \\<in> tiling domino ==>\n  (i + j) mod 2 = 0 ==> (m + n) mod 2 = 0 ==>\n  {(i, j), (m, n)} \\<subseteq> t\n  ==> (t - {(i,j)} - {(m,n)}) \\<notin> tiling domino\"\napply (rule notI)\napply (subgoal_tac\n  \"card (whites \\<inter> (t - {(i,j)} - {(m,n)})) <\n   card (blacks \\<inter> (t - {(i,j)} - {(m,n)}))\")\n apply (force simp only: tiling_domino_0_1)\napply (simp add: tiling_domino_0_1 [symmetric])\napply (simp add: coloured_def card_Diff2_less)\ndone\n\ntext {* Apply the general theorem to the well-known case *}\n\ntheorem mutil_not_tiling:\n  \"t = {0..< 2 * Suc m} \\<times> {0..< 2 * Suc n}\n   ==> t - {(0,0)} - {(Suc(2 * m), Suc(2 * n))} \\<notin> tiling domino\"\napply (rule gen_mutil_not_tiling)\n apply (blast intro!: dominoes_tile_matrix)\napply auto\ndone\n\n\nsection{* The Mutilated Chess Board Can be Tiled by Ls *}\n\ntext{* Remove a arbitrary square from a chess board of size $2^n \\times 2^n$.\nThe result can be tiled by L-shaped tiles:\n\\begin{picture}(8,8)\n\\put(0,0){\\framebox(4,4){}}\n\\put(4,0){\\framebox(4,4){}}\n\\put(0,4){\\framebox(4,4){}}\n\\end{picture}.\nThe four possible L-shaped tiles are obtained by dropping\none of the four squares from $\\{(x,y),(x+1,y),(x,y+1),(x+1,y+1)\\}$: *}\n\ndefinition \"L2 (x::nat) (y::nat) = {(x,y), (x+1,y), (x, y+1)}\"\ndefinition \"L3 (x::nat) (y::nat) = {(x,y), (x+1,y), (x+1, y+1)}\"\ndefinition \"L0 (x::nat) (y::nat) = {(x+1,y), (x,y+1), (x+1, y+1)}\"\ndefinition \"L1 (x::nat) (y::nat) = {(x,y), (x,y+1), (x+1, y+1)}\"\n\ntext{* All tiles: *}\n\ndefinition Ls :: \"(nat * nat) set set\" where\n\"Ls \\<equiv> { L0 x y | x y. True} \\<union> { L1 x y | x y. True} \\<union>\n      { L2 x y | x y. True} \\<union> { L3 x y | x y. True}\"\n\nlemma LinLs: \"L0 i j : Ls & L1 i j : Ls & L2 i j : Ls & L3 i j : Ls\"\nby(fastforce simp:Ls_def)\n\n\ntext{* Square $2^n \\times 2^n$ grid, shifted by $i$ and $j$: *}\n\ndefinition \"square2 (n::nat) (i::nat) (j::nat) = {i..< 2^n+i} \\<times> {j..< 2^n+j}\"\n\nlemma in_square2[simp]:\n  \"(a,b) : square2 n i j \\<longleftrightarrow> i\\<le>a \\<and> a<2^n+i \\<and> j\\<le>b \\<and> b<2^n+j\"\nby(simp add:square2_def)\n\nlemma square2_Suc: \"square2 (Suc n) i j =\n  square2 n i j \\<union> square2 n (2^n + i) j \\<union> square2 n i (2^n + j) \\<union>\n  square2 n (2^n + i) (2^n + j)\"\nby(auto simp:square2_def)\n\nlemma square2_disj: \"square2 n i j \\<inter> square2 n x y = {} \\<longleftrightarrow>\n  (2^n+i \\<le> x \\<or> 2^n+x \\<le> i) \\<or> (2^n+j \\<le> y \\<or> 2^n+y \\<le> j)\" (is \"?A = ?B\")\nproof-\n  { assume ?B hence ?A by(auto simp:square2_def) }\n  moreover\n  { assume \"\\<not> ?B\"\n    hence \"(max i x, max j y) : square2 n i j \\<inter> square2 n x y\" by simp\n    hence \"\\<not> ?A\" by blast }\n  ultimately show ?thesis by blast\nqed\n\ntext{* Some specific lemmas: *}\n\nlemma pos_pow2: \"(0::nat) < 2^(n::nat)\"\nby simp\n\ndeclare nat_zero_less_power_iff[simp del] zero_less_power[simp del]\n\nlemma Diff_insert_if: shows\n  \"B \\<noteq> {} \\<Longrightarrow> a:A \\<Longrightarrow> A - insert a B = (A-B - {a})\" and\n  \"B \\<noteq> {} \\<Longrightarrow> a ~: A \\<Longrightarrow> A - insert a B = A-B\"\nby auto\n\nlemma DisjI1: \"A Int B = {} \\<Longrightarrow> (A-X) Int B = {}\"\nby blast\nlemma DisjI2: \"A Int B = {} \\<Longrightarrow> A Int (B-X) = {}\"\nby blast\n\ntext{* The main theorem: *}\n\ntheorem Ls_can_tile: \"i \\<le> a \\<Longrightarrow> a < 2^n + i \\<Longrightarrow> j \\<le> b \\<Longrightarrow> b < 2^n + j\n  \\<Longrightarrow> square2 n i j - {(a,b)} : tiling Ls\"\nproof(induct n arbitrary: a b i j)\n  case 0 thus ?case by (simp add:square2_def)\nnext\n  case (Suc n) note IH = Suc(1) and a = Suc(2-3) and b = Suc(4-5)\n  hence \"a<2^n+i \\<and> b<2^n+j \\<or>\n         2^n+i\\<le>a \\<and> a<2^(n+1)+i \\<and> b<2^n+j \\<or>\n         a<2^n+i \\<and> 2^n+j\\<le>b \\<and> b<2^(n+1)+j \\<or>\n         2^n+i\\<le>a \\<and> a<2^(n+1)+i \\<and> 2^n+j\\<le>b \\<and> b<2^(n+1)+j\" (is \"?A|?B|?C|?D\")\n    by simp arith\n  moreover\n  { assume \"?A\"\n    hence \"square2 n i j - {(a,b)} : tiling Ls\" using IH a b by auto\n    moreover have \"square2 n (2^n+i) j - {(2^n+i,2^n+j - 1)} : tiling Ls\"\n      by(rule IH)(insert pos_pow2[of n], auto)\n    moreover have \"square2 n i (2^n+j) - {(2^n+i - 1, 2^n+j)} : tiling Ls\"\n      by(rule IH)(insert pos_pow2[of n], auto)\n    moreover have \"square2 n (2^n+i) (2^n+j) - {(2^n+i, 2^n+j)} : tiling Ls\"\n      by(rule IH)(insert pos_pow2[of n], auto)\n    ultimately\n    have \"square2 (n+1) i j - {(a,b)} - L0 (2^n+i - 1) (2^n+j - 1) \\<in> tiling Ls\"\n      using  a b `?A`\n      by (clarsimp simp: square2_Suc L0_def Un_Diff Diff_insert_if)\n         (fastforce intro!: tiling_UnI DisjI1 DisjI2 square2_disj[THEN iffD2]\n                   simp:Int_Un_distrib2)\n  } moreover\n  { assume \"?B\"\n    hence \"square2 n (2^n+i) j - {(a,b)} : tiling Ls\" using IH a b by auto\n    moreover have \"square2 n i j - {(2^n+i - 1,2^n+j - 1)} : tiling Ls\"\n      by(rule IH)(insert pos_pow2[of n], auto)\n    moreover have \"square2 n i (2^n+j) - {(2^n+i - 1, 2^n+j)} : tiling Ls\"\n      by(rule IH)(insert pos_pow2[of n], auto)\n    moreover have \"square2 n (2^n+i) (2^n+j) - {(2^n+i, 2^n+j)} : tiling Ls\"\n      by(rule IH)(insert pos_pow2[of n], auto)\n    ultimately\n    have \"square2 (n+1) i j - {(a,b)} - L1 (2^n+i - 1) (2^n+j - 1) \\<in> tiling Ls\"\n      using  a b `?B`\n      by (simp add: square2_Suc L1_def Un_Diff Diff_insert_if le_diff_conv2)\n         (fastforce intro!: tiling_UnI DisjI1 DisjI2 square2_disj[THEN iffD2]\n                   simp:Int_Un_distrib2)\n  } moreover\n  { assume \"?C\"\n    hence \"square2 n i (2^n+j) - {(a,b)} : tiling Ls\" using IH a b by auto\n    moreover have \"square2 n i j - {(2^n+i - 1,2^n+j - 1)} : tiling Ls\"\n      by(rule IH)(insert pos_pow2[of n], auto)\n    moreover have \"square2 n (2^n+i) j - {(2^n+i, 2^n+j - 1)} : tiling Ls\"\n      by(rule IH)(insert pos_pow2[of n], auto)\n    moreover have \"square2 n (2^n+i) (2^n+j) - {(2^n+i, 2^n+j)} : tiling Ls\"\n      by(rule IH)(insert pos_pow2[of n], auto)\n    ultimately\n    have \"square2 (n+1) i j - {(a,b)} - L3 (2^n+i - 1) (2^n+j - 1) \\<in> tiling Ls\"\n      using  a b `?C`\n      by (simp add: square2_Suc L3_def Un_Diff Diff_insert_if le_diff_conv2)\n         (fastforce intro!: tiling_UnI DisjI1 DisjI2 square2_disj[THEN iffD2]\n                   simp:Int_Un_distrib2)\n  } moreover\n  { assume \"?D\"\n    hence \"square2 n (2^n+i) (2^n+j) -{(a,b)} : tiling Ls\" using IH a b by auto\n    moreover have \"square2 n i j - {(2^n+i - 1,2^n+j - 1)} : tiling Ls\"\n      by(rule IH)(insert pos_pow2[of n], auto)\n    moreover have \"square2 n (2^n+i) j - {(2^n+i, 2^n+j - 1)} : tiling Ls\"\n      by(rule IH)(insert pos_pow2[of n], auto)\n    moreover have \"square2 n i (2^n+j) - {(2^n+i - 1, 2^n+j)} : tiling Ls\"\n      by(rule IH)(insert pos_pow2[of n], auto)\n    ultimately\n    have \"square2 (n+1) i j - {(a,b)} - L2 (2^n+i - 1) (2^n+j - 1) \\<in> tiling Ls\"\n      using  a b `?D`\n      by (simp add: square2_Suc L2_def Un_Diff Diff_insert_if le_diff_conv2)\n         (fastforce intro!: tiling_UnI DisjI1 DisjI2 square2_disj[THEN iffD2]\n                   simp:Int_Un_distrib2)\n  } moreover\n  have \"?A \\<Longrightarrow> L0 (2^n + i - 1) (2^n + j - 1) \\<subseteq> square2 (n+1) i j - {(a, b)}\"\n    using a b by(simp add:L0_def) arith moreover\n  have \"?B \\<Longrightarrow> L1 (2^n + i - 1) (2^n + j - 1) \\<subseteq> square2 (n+1) i j - {(a, b)}\"\n    using a b by(simp add:L1_def) arith moreover\n  have \"?C \\<Longrightarrow> L3 (2^n + i - 1) (2^n + j - 1) \\<subseteq> square2 (n+1) i j - {(a, b)}\"\n    using a b by(simp add:L3_def) arith moreover\n  have \"?D \\<Longrightarrow> L2 (2^n + i - 1) (2^n + j - 1) \\<subseteq> square2 (n+1) i j - {(a, b)}\"\n    using a b by(simp add:L2_def) arith\n  ultimately show ?case by simp (metis LinLs tiling_Diff1E)\nqed\n\ncorollary Ls_can_tile00:\n  \"a < 2^n \\<Longrightarrow> b < 2^n \\<Longrightarrow> square2 n 0 0 - {(a, b)} \\<in> tiling Ls\"\nby(rule Ls_can_tile) 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/FunWithTilings/Tilings.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8947894661025424, "lm_q2_score": 0.8104789155369047, "lm_q1q2_score": 0.7252079961206345}}
{"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_NMSortTDCount\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 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\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 (nmsorttd 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_NMSortTDCount.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026528034426, "lm_q2_score": 0.7905303236047049, "lm_q1q2_score": 0.7251555629641597}}
{"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_34\n  imports \"../../Test_Base\"\nbegin\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 min :: \"Nat => Nat => Nat\" where\n  \"min (Z) z = Z\"\n| \"min (S z2) (Z) = Z\"\n| \"min (S z2) (S y1) = S (min z2 y1)\"\n\nfun t2 :: \"Nat => Nat => bool\" where\n  \"t2 (Z) z = True\"\n| \"t2 (S z2) (Z) = False\"\n| \"t2 (S z2) (S x2) = t2 z2 x2\"\n\ntheorem property0 :(*This problem is similar to TIP_prop_33.thy*)\n  \"((x (min a b) b) = (t2 b a))\"\n  find_proof DInd\n  apply (induct rule: TIP_prop_34.x.induct)\n     apply auto\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_34.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026573249612, "lm_q2_score": 0.7905303087996142, "lm_q1q2_score": 0.7251555529578082}}
{"text": "\\<^marker>\\<open>creator \"Kevin Kappelmann\"\\<close>\nsubsection \\<open>Partial Equivalence Relations\\<close>\ntheory Partial_Equivalence_Relations\n  imports\n    Binary_Relations_Symmetric\n    Preorders\nbegin\n\ndefinition \"partial_equivalence_rel_on P R \\<equiv> transitive_on P R \\<and> symmetric_on P R\"\n\nlemma partial_equivalence_rel_onI [intro]:\n  assumes \"transitive_on P R\"\n  and \"symmetric_on P R\"\n  shows \"partial_equivalence_rel_on P R\"\n  unfolding partial_equivalence_rel_on_def using assms by blast\n\nlemma partial_equivalence_rel_onE [elim]:\n  assumes \"partial_equivalence_rel_on P R\"\n  obtains \"transitive_on P R\" \"symmetric_on P R\"\n  using assms unfolding partial_equivalence_rel_on_def by blast\n\nlemma partial_equivalence_rel_on_rel_self_if_rel_dom:\n  assumes \"partial_equivalence_rel_on (P :: 'a \\<Rightarrow> bool) (R :: 'a \\<Rightarrow> 'a \\<Rightarrow> bool)\"\n  and \"P x\" \"P y\"\n  and \"R x y\"\n  shows \"R x x\"\n  using assms by (blast dest: symmetric_onD transitive_onD)\n\nlemma partial_equivalence_rel_on_rel_self_if_rel_codom:\n  assumes \"partial_equivalence_rel_on (P :: 'a \\<Rightarrow> bool) (R :: 'a \\<Rightarrow> 'a \\<Rightarrow> bool)\"\n  and \"P x\" \"P y\"\n  and \"R x y\"\n  shows \"R y y\"\n  using assms by (blast dest: symmetric_onD transitive_onD)\n\nlemma partial_equivalence_rel_on_rel_inv_iff_partial_equivalence_rel_on [iff]:\n  \"partial_equivalence_rel_on P R\\<inverse> \\<longleftrightarrow> partial_equivalence_rel_on (P :: 'a \\<Rightarrow> bool) (R :: 'a \\<Rightarrow> _)\"\n  by blast\n\ndefinition \"partial_equivalence_rel (R :: 'a \\<Rightarrow> _) \\<equiv> partial_equivalence_rel_on (\\<top> :: 'a \\<Rightarrow> bool) R\"\n\nlemma partial_equivalence_rel_eq_partial_equivalence_rel_on:\n  \"partial_equivalence_rel (R :: 'a \\<Rightarrow> _) = partial_equivalence_rel_on (\\<top> :: 'a \\<Rightarrow> bool) R\"\n  unfolding partial_equivalence_rel_def ..\n\nlemma partial_equivalence_relI [intro]:\n  assumes \"transitive R\"\n  and \"symmetric R\"\n  shows \"partial_equivalence_rel R\"\n  unfolding partial_equivalence_rel_eq_partial_equivalence_rel_on using assms\n  by (intro partial_equivalence_rel_onI transitive_on_if_transitive symmetric_on_if_symmetric)\n\nlemma reflexive_on_in_field_if_partial_equivalence_rel:\n  assumes \"partial_equivalence_rel R\"\n  shows \"reflexive_on (in_field R) R\"\n  using assms unfolding partial_equivalence_rel_eq_partial_equivalence_rel_on\n  by (intro reflexive_onI) (blast\n    intro: top1I partial_equivalence_rel_on_rel_self_if_rel_dom\n    partial_equivalence_rel_on_rel_self_if_rel_codom)\n\nlemma partial_equivalence_relE [elim]:\n  assumes \"partial_equivalence_rel R\"\n  obtains \"preorder_on (in_field R) R\" \"symmetric R\"\n  using assms unfolding partial_equivalence_rel_eq_partial_equivalence_rel_on\n  by (elim partial_equivalence_rel_onE)\n  (auto intro: reflexive_on_in_field_if_partial_equivalence_rel\n    simp flip: transitive_eq_transitive_on symmetric_eq_symmetric_on)\n\nlemma partial_equivalence_rel_on_if_partial_equivalence_rel:\n  fixes P :: \"'a \\<Rightarrow> bool\" and R :: \"'a \\<Rightarrow> _\"\n  assumes \"partial_equivalence_rel R\"\n  shows \"partial_equivalence_rel_on P R\"\n  using assms by (elim partial_equivalence_relE preorder_on_in_fieldE)\n  (intro partial_equivalence_rel_onI transitive_on_if_transitive\n    symmetric_on_if_symmetric)\n\nlemma partial_equivalence_rel_rel_inv_iff_partial_equivalence_rel [iff]:\n  \"partial_equivalence_rel R\\<inverse> \\<longleftrightarrow> partial_equivalence_rel R\"\n  unfolding partial_equivalence_rel_eq_partial_equivalence_rel_on by blast\n\ncorollary in_codom_eq_in_dom_if_partial_equivalence_rel:\n  assumes \"partial_equivalence_rel R\"\n  shows \"in_codom R = in_dom R\"\n  using assms reflexive_on_in_field_if_partial_equivalence_rel\n    in_codom_eq_in_dom_if_reflexive_on_in_field\n  by auto\n\nlemma partial_equivalence_rel_rel_comp_self_eq_self:\n  assumes \"partial_equivalence_rel R\"\n  shows \"(R \\<circ>\\<circ> R) = R\"\n  using assms by (intro ext) (blast dest: symmetricD)\n\nlemma partial_equivalence_rel_if_partial_equivalence_rel_on_in_field:\n  assumes \"partial_equivalence_rel_on (in_field R) R\"\n  shows \"partial_equivalence_rel R\"\n  using assms by (intro partial_equivalence_relI)\n  (auto intro: transitive_if_transitive_on_in_field symmetric_if_symmetric_on_in_field)\n\ncorollary partial_equivalence_rel_on_in_field_iff_partial_equivalence_rel [iff]:\n  \"partial_equivalence_rel_on (in_field R) R \\<longleftrightarrow> partial_equivalence_rel R\"\n  using partial_equivalence_rel_if_partial_equivalence_rel_on_in_field\n    partial_equivalence_rel_on_if_partial_equivalence_rel\n  by blast\n\n\nsubsubsection \\<open>Instantiations\\<close>\n\nlemma partial_equivalence_rel_eq: \"partial_equivalence_rel (=)\"\n  using transitive_eq symmetric_eq by (rule partial_equivalence_relI)\n\nlemma partial_equivalence_rel_top: \"partial_equivalence_rel \\<top>\"\n  using transitive_top symmetric_top by (rule partial_equivalence_relI)\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/Orders/Partial_Equivalence_Relations.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473746782093, "lm_q2_score": 0.8311430520409023, "lm_q1q2_score": 0.7250454594299155}}
{"text": "section \\<open>The Reals as Dedekind Sections of Positive Rationals\\<close>\n\ntext \\<open>Fundamentals of Abstract Analysis [Gleason, p. 121] provides some of the definitions.\\<close>\n\ntheory Dedekind_Real\nimports Complex_Main \nbegin\n\nlemma add_eq_exists: \"\\<exists>x. a+x = (b::'a::ab_group_add)\"\n  by (rule_tac x=\"b-a\" in exI, simp)\n\nsubsection \\<open>Dedekind cuts or sections\\<close>\n\ndefinition\n  cut :: \"rat set \\<Rightarrow> bool\" where\n  \"cut A \\<equiv> {} \\<subset> A \\<and> A \\<subset> {0<..} \\<and>\n            (\\<forall>y \\<in> A. ((\\<forall>z. 0<z \\<and> z < y \\<longrightarrow> z \\<in> A) \\<and> (\\<exists>u \\<in> A. y < u)))\"\n\nlemma cut_of_rat: \n  assumes q: \"0 < q\" shows \"cut {r::rat. 0 < r \\<and> r < q}\" (is \"cut ?A\")\nproof -\n  from q have pos: \"?A \\<subset> {0<..}\" by force\n  have nonempty: \"{} \\<subset> ?A\"\n  proof\n    show \"{} \\<subseteq> ?A\" by simp\n    show \"{} \\<noteq> ?A\"\n      using field_lbound_gt_zero q by auto\n  qed\n  show ?thesis\n    by (simp add: cut_def pos nonempty,\n        blast dest: dense intro: order_less_trans)\nqed\n\n\ntypedef preal = \"Collect cut\"\n  by (blast intro: cut_of_rat [OF zero_less_one])\n\nlemma Abs_preal_induct [induct type: preal]:\n  \"(\\<And>x. cut x \\<Longrightarrow> P (Abs_preal x)) \\<Longrightarrow> P x\"\n  using Abs_preal_induct [of P x] by simp\n\nlemma cut_Rep_preal [simp]: \"cut (Rep_preal x)\"\n  using Rep_preal [of x] by simp\n\ndefinition\n  psup :: \"preal set \\<Rightarrow> preal\" where\n  \"psup P = Abs_preal (\\<Union>X \\<in> P. Rep_preal X)\"\n\ndefinition\n  add_set :: \"[rat set,rat set] \\<Rightarrow> rat set\" where\n  \"add_set A B = {w. \\<exists>x \\<in> A. \\<exists>y \\<in> B. w = x + y}\"\n\ndefinition\n  diff_set :: \"[rat set,rat set] \\<Rightarrow> rat set\" where\n  \"diff_set A B = {w. \\<exists>x. 0 < w \\<and> 0 < x \\<and> x \\<notin> B \\<and> x + w \\<in> A}\"\n\ndefinition\n  mult_set :: \"[rat set,rat set] \\<Rightarrow> rat set\" where\n  \"mult_set A B = {w. \\<exists>x \\<in> A. \\<exists>y \\<in> B. w = x * y}\"\n\ndefinition\n  inverse_set :: \"rat set \\<Rightarrow> rat set\" where\n  \"inverse_set A \\<equiv> {x. \\<exists>y. 0 < x \\<and> x < y \\<and> inverse y \\<notin> A}\"\n\ninstantiation preal :: \"{ord, plus, minus, times, inverse, one}\"\nbegin\n\ndefinition\n  preal_less_def:\n    \"r < s \\<equiv> Rep_preal r < Rep_preal s\"\n\ndefinition\n  preal_le_def:\n    \"r \\<le> s \\<equiv> Rep_preal r \\<subseteq> Rep_preal s\"\n\ndefinition\n  preal_add_def:\n    \"r + s \\<equiv> Abs_preal (add_set (Rep_preal r) (Rep_preal s))\"\n\ndefinition\n  preal_diff_def:\n    \"r - s \\<equiv> Abs_preal (diff_set (Rep_preal r) (Rep_preal s))\"\n\ndefinition\n  preal_mult_def:\n    \"r * s \\<equiv> Abs_preal (mult_set (Rep_preal r) (Rep_preal s))\"\n\ndefinition\n  preal_inverse_def:\n    \"inverse r \\<equiv> Abs_preal (inverse_set (Rep_preal r))\"\n\ndefinition \"r div s = r * inverse (s::preal)\"\n\ndefinition\n  preal_one_def:\n    \"1 \\<equiv> Abs_preal {x. 0 < x \\<and> x < 1}\"\n\ninstance ..\n\nend\n\n\ntext\\<open>Reduces equality on abstractions to equality on representatives\\<close>\ndeclare Abs_preal_inject [simp]\ndeclare Abs_preal_inverse [simp]\n\nlemma rat_mem_preal: \"0 < q \\<Longrightarrow> cut {r::rat. 0 < r \\<and> r < q}\"\nby (simp add: cut_of_rat)\n\nlemma preal_nonempty: \"cut A \\<Longrightarrow> \\<exists>x\\<in>A. 0 < x\"\n  unfolding cut_def [abs_def] by blast\n\nlemma preal_Ex_mem: \"cut A \\<Longrightarrow> \\<exists>x. x \\<in> A\"\n  using preal_nonempty by blast\n\nlemma preal_exists_bound: \"cut A \\<Longrightarrow> \\<exists>x. 0 < x \\<and> x \\<notin> A\"\n  using Dedekind_Real.cut_def by fastforce\n\nlemma preal_exists_greater: \"\\<lbrakk>cut A; y \\<in> A\\<rbrakk> \\<Longrightarrow> \\<exists>u \\<in> A. y < u\"\n  unfolding cut_def [abs_def] by blast\n\nlemma preal_downwards_closed: \"\\<lbrakk>cut A; y \\<in> A; 0 < z; z < y\\<rbrakk> \\<Longrightarrow> z \\<in> A\"\n  unfolding cut_def [abs_def] by blast\n\ntext\\<open>Relaxing the final premise\\<close>\nlemma preal_downwards_closed': \"\\<lbrakk>cut A; y \\<in> A; 0 < z; z \\<le> y\\<rbrakk> \\<Longrightarrow> z \\<in> A\"\n  using less_eq_rat_def preal_downwards_closed by blast\n\ntext\\<open>A positive fraction not in a positive real is an upper bound.\n Gleason p. 122 - Remark (1)\\<close>\n\nlemma not_in_preal_ub:\n  assumes A: \"cut A\"\n    and notx: \"x \\<notin> A\"\n    and y: \"y \\<in> A\"\n    and pos: \"0 < x\"\n  shows \"y < x\"\nproof (cases rule: linorder_cases)\n  assume \"x<y\"\n  with notx show ?thesis\n    by (simp add:  preal_downwards_closed [OF A y] pos)\nnext\n  assume \"x=y\"\n  with notx and y show ?thesis by simp\nnext\n  assume \"y<x\"\n  thus ?thesis .\nqed\n\ntext \\<open>preal lemmas instantiated to \\<^term>\\<open>Rep_preal X\\<close>\\<close>\n\nlemma mem_Rep_preal_Ex: \"\\<exists>x. x \\<in> Rep_preal X\"\nthm preal_Ex_mem\nby (rule preal_Ex_mem [OF cut_Rep_preal])\n\nlemma Rep_preal_exists_bound: \"\\<exists>x>0. x \\<notin> Rep_preal X\"\nby (rule preal_exists_bound [OF cut_Rep_preal])\n\nlemmas not_in_Rep_preal_ub = not_in_preal_ub [OF cut_Rep_preal]\n\n\nsubsection\\<open>Properties of Ordering\\<close>\n\ninstance preal :: order\nproof\n  fix w :: preal\n  show \"w \\<le> w\" by (simp add: preal_le_def)\nnext\n  fix i j k :: preal\n  assume \"i \\<le> j\" and \"j \\<le> k\"\n  then show \"i \\<le> k\" by (simp add: preal_le_def)\nnext\n  fix z w :: preal\n  assume \"z \\<le> w\" and \"w \\<le> z\"\n  then show \"z = w\" by (simp add: preal_le_def Rep_preal_inject)\nnext\n  fix z w :: preal\n  show \"z < w \\<longleftrightarrow> z \\<le> w \\<and> \\<not> w \\<le> z\"\n  by (auto simp: preal_le_def preal_less_def Rep_preal_inject)\nqed  \n\nlemma preal_imp_pos: \"\\<lbrakk>cut A; r \\<in> A\\<rbrakk> \\<Longrightarrow> 0 < r\"\n  by (auto simp: cut_def)\n\ninstance preal :: linorder\nproof\n  fix x y :: preal\n  show \"x \\<le> y \\<or> y \\<le> x\"\n    unfolding preal_le_def\n    by (meson cut_Rep_preal not_in_preal_ub preal_downwards_closed preal_imp_pos subsetI)\nqed\n\ninstantiation preal :: distrib_lattice\nbegin\n\ndefinition\n  \"(inf :: preal \\<Rightarrow> preal \\<Rightarrow> preal) = min\"\n\ndefinition\n  \"(sup :: preal \\<Rightarrow> preal \\<Rightarrow> preal) = max\"\n\ninstance\n  by intro_classes\n    (auto simp: inf_preal_def sup_preal_def max_min_distrib2)\n\nend\n\nsubsection\\<open>Properties of Addition\\<close>\n\nlemma preal_add_commute: \"(x::preal) + y = y + x\"\n  unfolding preal_add_def add_set_def\n  by (metis (no_types, opaque_lifting) add.commute)\n\ntext\\<open>Lemmas for proving that addition of two positive reals gives\n a positive real\\<close>\n\nlemma mem_add_set:\n  assumes \"cut A\" \"cut B\"\n  shows \"cut (add_set A B)\"\nproof -\n  have \"{} \\<subset> add_set A B\"\n    using assms by (force simp: add_set_def dest: preal_nonempty)\n  moreover\n  obtain q where \"q > 0\" \"q \\<notin> add_set A B\"\n  proof -\n    obtain a b where \"a > 0\" \"a \\<notin> A\" \"b > 0\" \"b \\<notin> B\" \"\\<And>x. x \\<in> A \\<Longrightarrow> x < a\" \"\\<And>y. y \\<in> B \\<Longrightarrow> y < b\"\n      by (meson assms preal_exists_bound not_in_preal_ub)\n    with assms have \"a+b \\<notin> add_set A B\"\n      by (fastforce simp add: add_set_def)\n    then show thesis\n      using \\<open>0 < a\\<close> \\<open>0 < b\\<close> add_pos_pos that by blast\n  qed\n  then have \"add_set A B \\<subset> {0<..}\"\n    unfolding add_set_def\n    using preal_imp_pos [OF \\<open>cut A\\<close>] preal_imp_pos [OF \\<open>cut B\\<close>]  by fastforce\n  moreover have \"z \\<in> add_set A B\" \n    if u: \"u \\<in> add_set A B\" and \"0 < z\" \"z < u\" for u z\n    using u unfolding add_set_def\n  proof (clarify)\n    fix x::rat and y::rat\n    assume ueq: \"u = x + y\" and x: \"x \\<in> A\" and y:\"y \\<in> B\"\n    have xpos [simp]: \"x > 0\" and ypos [simp]: \"y > 0\"\n      using assms preal_imp_pos x y by blast+\n    have xypos [simp]: \"x+y > 0\" by (simp add: pos_add_strict)\n    let ?f = \"z/(x+y)\"\n    have fless: \"?f < 1\"\n      using divide_less_eq_1_pos \\<open>z < u\\<close> ueq xypos by blast\n    show \"\\<exists>x' \\<in> A. \\<exists>y'\\<in>B. z = x' + y'\"\n    proof (intro bexI)\n      show \"z = x*?f + y*?f\"\n        by (simp add: distrib_right [symmetric] divide_inverse ac_simps order_less_imp_not_eq2)\n    next\n      show \"y * ?f \\<in> B\"\n      proof (rule preal_downwards_closed [OF \\<open>cut B\\<close> y])\n        show \"0 < y * ?f\"\n          by (simp add: \\<open>0 < z\\<close>)\n      next\n        show \"y * ?f < y\"\n          by (insert mult_strict_left_mono [OF fless ypos], simp)\n      qed\n    next\n      show \"x * ?f \\<in> A\"\n      proof (rule preal_downwards_closed [OF \\<open>cut A\\<close> x])\n        show \"0 < x * ?f\"\n          by (simp add: \\<open>0 < z\\<close>)\n      next\n        show \"x * ?f < x\"\n          by (insert mult_strict_left_mono [OF fless xpos], simp)\n      qed\n    qed\n  qed\n  moreover\n  have \"\\<And>y. y \\<in> add_set A B \\<Longrightarrow> \\<exists>u \\<in> add_set A B. y < u\"\n    unfolding add_set_def using preal_exists_greater assms by fastforce\n  ultimately show ?thesis\n    by (simp add: Dedekind_Real.cut_def)\nqed\n\nlemma preal_add_assoc: \"((x::preal) + y) + z = x + (y + z)\"\n  apply (simp add: preal_add_def mem_add_set)\n  apply (force simp: add_set_def ac_simps)\n  done\n\ninstance preal :: ab_semigroup_add\nproof\n  fix a b c :: preal\n  show \"(a + b) + c = a + (b + c)\" by (rule preal_add_assoc)\n  show \"a + b = b + a\" by (rule preal_add_commute)\nqed\n\n\nsubsection\\<open>Properties of Multiplication\\<close>\n\ntext\\<open>Proofs essentially same as for addition\\<close>\n\nlemma preal_mult_commute: \"(x::preal) * y = y * x\"\n  unfolding preal_mult_def mult_set_def\n  by (metis (no_types, opaque_lifting) mult.commute)\n\ntext\\<open>Multiplication of two positive reals gives a positive real.\\<close>\n\nlemma mem_mult_set:\n  assumes \"cut A\" \"cut B\"\n  shows \"cut (mult_set A B)\"\nproof -\n  have \"{} \\<subset> mult_set A B\"\n    using assms\n      by (force simp: mult_set_def dest: preal_nonempty)\n    moreover\n    obtain q where \"q > 0\" \"q \\<notin> mult_set A B\"\n    proof -\n      obtain x y where x [simp]: \"0 < x\" \"x \\<notin> A\" and y [simp]: \"0 < y\" \"y \\<notin> B\"\n        using preal_exists_bound assms by blast\n      show thesis\n      proof \n        show \"0 < x*y\" by simp\n        show \"x * y \\<notin> mult_set A B\"\n        proof -\n          {\n            fix u::rat and v::rat\n            assume u: \"u \\<in> A\" and v: \"v \\<in> B\" and xy: \"x*y = u*v\"\n            moreover have \"u<x\" and \"v<y\" using assms x y u v by (blast dest: not_in_preal_ub)+\n            moreover have \"0\\<le>v\"\n              using less_imp_le preal_imp_pos assms x y u v by blast\n            moreover have \"u*v < x*y\"\n                using assms x \\<open>u < x\\<close> \\<open>v < y\\<close> \\<open>0 \\<le> v\\<close> by (blast intro: mult_strict_mono)\n            ultimately have False by force\n          }\n          thus ?thesis by (auto simp: mult_set_def)\n        qed\n      qed\n    qed\n  then have \"mult_set A B \\<subset> {0<..}\"\n    unfolding mult_set_def\n    using preal_imp_pos [OF \\<open>cut A\\<close>] preal_imp_pos [OF \\<open>cut B\\<close>]  by fastforce\n  moreover have \"z \\<in> mult_set A B\"\n    if u: \"u \\<in> mult_set A B\" and \"0 < z\" \"z < u\" for u z\n    using u unfolding mult_set_def\n  proof (clarify)\n    fix x::rat and y::rat\n    assume ueq: \"u = x * y\" and x: \"x \\<in> A\" and y: \"y \\<in> B\"  \n    have [simp]: \"y > 0\"\n      using \\<open>cut B\\<close> preal_imp_pos y by blast\n    show \"\\<exists>x' \\<in> A. \\<exists>y' \\<in> B. z = x' * y'\"\n    proof\n      have \"z = (z/y)*y\"\n          by (simp add: divide_inverse mult.commute [of y] mult.assoc order_less_imp_not_eq2)\n      then show \"\\<exists>y'\\<in>B. z = (z/y) * y'\"\n        using y by blast\n    next\n      show \"z/y \\<in> A\"\n      proof (rule preal_downwards_closed [OF \\<open>cut A\\<close> x])\n        show \"0 < z/y\"\n          by (simp add: \\<open>0 < z\\<close>)\n        show \"z/y < x\"\n          using \\<open>0 < y\\<close> pos_divide_less_eq \\<open>z < u\\<close> ueq by blast  \n      qed\n    qed\n  qed\n  moreover have \"\\<And>y. y \\<in> mult_set A B \\<Longrightarrow> \\<exists>u \\<in> mult_set A B. y < u\"\n    apply (simp add: mult_set_def)\n    by (metis preal_exists_greater mult_strict_right_mono preal_imp_pos assms)\n  ultimately show ?thesis\n    by (simp add: Dedekind_Real.cut_def)\nqed\n\nlemma preal_mult_assoc: \"((x::preal) * y) * z = x * (y * z)\"\n  apply (simp add: preal_mult_def mem_mult_set Rep_preal)\n  apply (simp add: mult_set_def)\n  apply (metis (no_types, opaque_lifting) ab_semigroup_mult_class.mult_ac(1))\n  done\n\ninstance preal :: ab_semigroup_mult\nproof\n  fix a b c :: preal\n  show \"(a * b) * c = a * (b * c)\" by (rule preal_mult_assoc)\n  show \"a * b = b * a\" by (rule preal_mult_commute)\nqed\n\n\ntext\\<open>Positive real 1 is the multiplicative identity element\\<close>\n\nlemma preal_mult_1: \"(1::preal) * z = z\"\nproof (induct z)\n  fix A :: \"rat set\"\n  assume A: \"cut A\"\n  have \"{w. \\<exists>u. 0 < u \\<and> u < 1 \\<and> (\\<exists>v \\<in> A. w = u * v)} = A\" (is \"?lhs = A\")\n  proof\n    show \"?lhs \\<subseteq> A\"\n    proof clarify\n      fix x::rat and u::rat and v::rat\n      assume upos: \"0<u\" and \"u<1\" and v: \"v \\<in> A\"\n      have vpos: \"0<v\" by (rule preal_imp_pos [OF A v])\n      hence \"u*v < 1*v\" by (simp only: mult_strict_right_mono upos \\<open>u < 1\\<close> v)\n      thus \"u * v \\<in> A\"\n        by (force intro: preal_downwards_closed [OF A v] mult_pos_pos  upos vpos)\n    qed\n  next\n    show \"A \\<subseteq> ?lhs\"\n    proof clarify\n      fix x::rat\n      assume x: \"x \\<in> A\"\n      have xpos: \"0<x\" by (rule preal_imp_pos [OF A x])\n      from preal_exists_greater [OF A x]\n      obtain v where v: \"v \\<in> A\" and xlessv: \"x < v\" ..\n      have vpos: \"0<v\" by (rule preal_imp_pos [OF A v])\n      show \"\\<exists>u. 0 < u \\<and> u < 1 \\<and> (\\<exists>v\\<in>A. x = u * v)\"\n      proof (intro exI conjI)\n        show \"0 < x/v\"\n          by (simp add: zero_less_divide_iff xpos vpos)\n        show \"x / v < 1\"\n          by (simp add: pos_divide_less_eq vpos xlessv)\n        have \"x = (x/v)*v\"\n            by (simp add: divide_inverse mult.assoc vpos order_less_imp_not_eq2)\n        then show \"\\<exists>v'\\<in>A. x = (x / v) * v'\"\n          using v by blast\n      qed\n    qed\n  qed\n  thus \"1 * Abs_preal A = Abs_preal A\"\n    by (simp add: preal_one_def preal_mult_def mult_set_def rat_mem_preal A)\nqed\n\ninstance preal :: comm_monoid_mult\n  by intro_classes (rule preal_mult_1)\n\n\nsubsection\\<open>Distribution of Multiplication across Addition\\<close>\n\nlemma mem_Rep_preal_add_iff:\n  \"(z \\<in> Rep_preal(r+s)) = (\\<exists>x \\<in> Rep_preal r. \\<exists>y \\<in> Rep_preal s. z = x + y)\"\n  apply (simp add: preal_add_def mem_add_set Rep_preal)\n  apply (simp add: add_set_def) \n  done\n\nlemma mem_Rep_preal_mult_iff:\n  \"(z \\<in> Rep_preal(r*s)) = (\\<exists>x \\<in> Rep_preal r. \\<exists>y \\<in> Rep_preal s. z = x * y)\"\n  apply (simp add: preal_mult_def mem_mult_set Rep_preal)\n  apply (simp add: mult_set_def) \n  done\n\nlemma distrib_subset1:\n  \"Rep_preal (w * (x + y)) \\<subseteq> Rep_preal (w * x + w * y)\"\n  by (force simp: Bex_def mem_Rep_preal_add_iff mem_Rep_preal_mult_iff distrib_left)\n\nlemma preal_add_mult_distrib_mean:\n  assumes a: \"a \\<in> Rep_preal w\"\n    and b: \"b \\<in> Rep_preal w\"\n    and d: \"d \\<in> Rep_preal x\"\n    and e: \"e \\<in> Rep_preal y\"\n  shows \"\\<exists>c \\<in> Rep_preal w. a * d + b * e = c * (d + e)\"\nproof\n  let ?c = \"(a*d + b*e)/(d+e)\"\n  have [simp]: \"0<a\" \"0<b\" \"0<d\" \"0<e\" \"0<d+e\"\n    by (blast intro: preal_imp_pos [OF cut_Rep_preal] a b d e pos_add_strict)+\n  have cpos: \"0 < ?c\"\n    by (simp add: zero_less_divide_iff zero_less_mult_iff pos_add_strict)\n  show \"a * d + b * e = ?c * (d + e)\"\n    by (simp add: divide_inverse mult.assoc order_less_imp_not_eq2)\n  show \"?c \\<in> Rep_preal w\"\n  proof (cases rule: linorder_le_cases)\n    assume \"a \\<le> b\"\n    hence \"?c \\<le> b\"\n      by (simp add: pos_divide_le_eq distrib_left mult_right_mono\n                    order_less_imp_le)\n    thus ?thesis by (rule preal_downwards_closed' [OF cut_Rep_preal b cpos])\n  next\n    assume \"b \\<le> a\"\n    hence \"?c \\<le> a\"\n      by (simp add: pos_divide_le_eq distrib_left mult_right_mono\n                    order_less_imp_le)\n    thus ?thesis by (rule preal_downwards_closed' [OF cut_Rep_preal a cpos])\n  qed\nqed\n\nlemma distrib_subset2:\n  \"Rep_preal (w * x + w * y) \\<subseteq> Rep_preal (w * (x + y))\"\n  apply (clarsimp simp: mem_Rep_preal_add_iff mem_Rep_preal_mult_iff)\n  using mem_Rep_preal_add_iff preal_add_mult_distrib_mean by blast\n\nlemma preal_add_mult_distrib2: \"(w * ((x::preal) + y)) = (w * x) + (w * y)\"\n  by (metis Rep_preal_inverse distrib_subset1 distrib_subset2 subset_antisym)\n\nlemma preal_add_mult_distrib: \"(((x::preal) + y) * w) = (x * w) + (y * w)\"\n  by (simp add: preal_mult_commute preal_add_mult_distrib2)\n\ninstance preal :: comm_semiring\n  by intro_classes (rule preal_add_mult_distrib)\n\n\nsubsection\\<open>Existence of Inverse, a Positive Real\\<close>\n\nlemma mem_inverse_set:\n  assumes \"cut A\" shows \"cut (inverse_set A)\"\nproof -\n  have \"\\<exists>x y. 0 < x \\<and> x < y \\<and> inverse y \\<notin> A\"\n  proof -\n    from preal_exists_bound [OF \\<open>cut A\\<close>]\n    obtain x where [simp]: \"0<x\" \"x \\<notin> A\" by blast\n    show ?thesis\n    proof (intro exI conjI)\n      show \"0 < inverse (x+1)\"\n        by (simp add: order_less_trans [OF _ less_add_one]) \n      show \"inverse(x+1) < inverse x\"\n        by (simp add: less_imp_inverse_less less_add_one)\n      show \"inverse (inverse x) \\<notin> A\"\n        by (simp add: order_less_imp_not_eq2)\n    qed\n  qed\n  then have \"{} \\<subset> inverse_set A\"\n    using inverse_set_def by fastforce\n  moreover obtain q where \"q > 0\" \"q \\<notin> inverse_set A\"\n  proof -\n    from preal_nonempty [OF \\<open>cut A\\<close>]\n    obtain x where x: \"x \\<in> A\" and  xpos [simp]: \"0<x\" ..\n    show ?thesis\n    proof \n      show \"0 < inverse x\" by simp\n      show \"inverse x \\<notin> inverse_set A\"\n      proof -\n        { fix y::rat \n          assume ygt: \"inverse x < y\"\n          have [simp]: \"0 < y\" by (simp add: order_less_trans [OF _ ygt])\n          have iyless: \"inverse y < x\" \n            by (simp add: inverse_less_imp_less [of x] ygt)\n          have \"inverse y \\<in> A\"\n            by (simp add: preal_downwards_closed [OF \\<open>cut A\\<close> x] iyless)}\n        thus ?thesis by (auto simp: inverse_set_def)\n      qed\n    qed\n  qed\n  moreover have \"inverse_set A \\<subset> {0<..}\"\n    using calculation inverse_set_def by blast\n  moreover have \"z \\<in> inverse_set A\"\n    if u: \"u \\<in> inverse_set A\" and \"0 < z\" \"z < u\" for u z\n    using u that less_trans unfolding inverse_set_def by auto\n  moreover have \"\\<And>y. y \\<in> inverse_set A \\<Longrightarrow> \\<exists>u \\<in> inverse_set A. y < u\"\n    by (simp add: inverse_set_def) (meson dense less_trans)\n  ultimately show ?thesis\n    by (simp add: Dedekind_Real.cut_def)\nqed\n\n\nsubsection\\<open>Gleason's Lemma 9-3.4, page 122\\<close>\n\nlemma Gleason9_34_exists:\n  assumes A: \"cut A\"\n    and \"\\<forall>x\\<in>A. x + u \\<in> A\"\n    and \"0 \\<le> z\"\n  shows \"\\<exists>b\\<in>A. b + (of_int z) * u \\<in> A\"\nproof (cases z rule: int_cases)\n  case (nonneg n)\n  show ?thesis\n  proof (simp add: nonneg, induct n)\n    case 0\n    from preal_nonempty [OF A]\n    show ?case  by force \n  next\n    case (Suc k)\n    then obtain b where b: \"b \\<in> A\" \"b + of_nat k * u \\<in> A\" ..\n    hence \"b + of_int (int k)*u + u \\<in> A\" by (simp add: assms)\n    thus ?case by (force simp: algebra_simps b)\n  qed\nnext\n  case (neg n)\n  with assms show ?thesis by simp\nqed\n\nlemma Gleason9_34_contra:\n  assumes A: \"cut A\"\n    shows \"\\<lbrakk>\\<forall>x\\<in>A. x + u \\<in> A; 0 < u; 0 < y; y \\<notin> A\\<rbrakk> \\<Longrightarrow> False\"\nproof (induct u, induct y)\n  fix a::int and b::int\n  fix c::int and d::int\n  assume bpos [simp]: \"0 < b\"\n    and dpos [simp]: \"0 < d\"\n    and closed: \"\\<forall>x\\<in>A. x + (Fract c d) \\<in> A\"\n    and upos: \"0 < Fract c d\"\n    and ypos: \"0 < Fract a b\"\n    and notin: \"Fract a b \\<notin> A\"\n  have cpos [simp]: \"0 < c\" \n    by (simp add: zero_less_Fract_iff [OF dpos, symmetric] upos) \n  have apos [simp]: \"0 < a\" \n    by (simp add: zero_less_Fract_iff [OF bpos, symmetric] ypos) \n  let ?k = \"a*d\"\n  have frle: \"Fract a b \\<le> Fract ?k 1 * (Fract c d)\" \n  proof -\n    have \"?thesis = ((a * d * b * d) \\<le> c * b * (a * d * b * d))\"\n      by (simp add: order_less_imp_not_eq2 ac_simps) \n    moreover\n    have \"(1 * (a * d * b * d)) \\<le> c * b * (a * d * b * d)\"\n      by (rule mult_mono, \n          simp_all add: int_one_le_iff_zero_less zero_less_mult_iff \n                        order_less_imp_le)\n    ultimately\n    show ?thesis by simp\n  qed\n  have k: \"0 \\<le> ?k\" by (simp add: order_less_imp_le zero_less_mult_iff)  \n  from Gleason9_34_exists [OF A closed k]\n  obtain z where z: \"z \\<in> A\" \n             and mem: \"z + of_int ?k * Fract c d \\<in> A\" ..\n  have less: \"z + of_int ?k * Fract c d < Fract a b\"\n    by (rule not_in_preal_ub [OF A notin mem ypos])\n  have \"0<z\" by (rule preal_imp_pos [OF A z])\n  with frle and less show False by (simp add: Fract_of_int_eq) \nqed\n\n\nlemma Gleason9_34:\n  assumes \"cut A\" \"0 < u\"\n  shows \"\\<exists>r \\<in> A. r + u \\<notin> A\"\n  using assms Gleason9_34_contra preal_exists_bound by blast\n\n\n\nsubsection\\<open>Gleason's Lemma 9-3.6\\<close>\n\nlemma lemma_gleason9_36:\n  assumes A: \"cut A\"\n    and x: \"1 < x\"\n  shows \"\\<exists>r \\<in> A. r*x \\<notin> A\"\nproof -\n  from preal_nonempty [OF A]\n  obtain y where y: \"y \\<in> A\" and  ypos: \"0<y\" ..\n  show ?thesis \n  proof (rule classical)\n    assume \"~(\\<exists>r\\<in>A. r * x \\<notin> A)\"\n    with y have ymem: \"y * x \\<in> A\" by blast \n    from ypos mult_strict_left_mono [OF x]\n    have yless: \"y < y*x\" by simp \n    let ?d = \"y*x - y\"\n    from yless have dpos: \"0 < ?d\" and eq: \"y + ?d = y*x\" by auto\n    from Gleason9_34 [OF A dpos]\n    obtain r where r: \"r\\<in>A\" and notin: \"r + ?d \\<notin> A\" ..\n    have rpos: \"0<r\" by (rule preal_imp_pos [OF A r])\n    with dpos have rdpos: \"0 < r + ?d\" by arith\n    have \"~ (r + ?d \\<le> y + ?d)\"\n    proof\n      assume le: \"r + ?d \\<le> y + ?d\" \n      from ymem have yd: \"y + ?d \\<in> A\" by (simp add: eq)\n      have \"r + ?d \\<in> A\" by (rule preal_downwards_closed' [OF A yd rdpos le])\n      with notin show False by simp\n    qed\n    hence \"y < r\" by simp\n    with ypos have  dless: \"?d < (r * ?d)/y\"\n      using dpos less_divide_eq_1 by fastforce\n    have \"r + ?d < r*x\"\n    proof -\n      have \"r + ?d < r + (r * ?d)/y\" by (simp add: dless)\n      also from ypos have \"\\<dots> = (r/y) * (y + ?d)\"\n        by (simp only: algebra_simps divide_inverse, simp)\n      also have \"\\<dots> = r*x\" using ypos\n        by simp\n      finally show \"r + ?d < r*x\" .\n    qed\n    with r notin rdpos\n    show \"\\<exists>r\\<in>A. r * x \\<notin> A\" by (blast dest:  preal_downwards_closed [OF A])\n  qed  \nqed\n\nsubsection\\<open>Existence of Inverse: Part 2\\<close>\n\nlemma mem_Rep_preal_inverse_iff:\n  \"(z \\<in> Rep_preal(inverse r)) \\<longleftrightarrow> (0 < z \\<and> (\\<exists>y. z < y \\<and> inverse y \\<notin> Rep_preal r))\"\n  apply (simp add: preal_inverse_def mem_inverse_set Rep_preal)\n  apply (simp add: inverse_set_def) \n  done\n\nlemma Rep_preal_one:\n     \"Rep_preal 1 = {x. 0 < x \\<and> x < 1}\"\nby (simp add: preal_one_def rat_mem_preal)\n\nlemma subset_inverse_mult_lemma:\n  assumes xpos: \"0 < x\" and xless: \"x < 1\"\n  shows \"\\<exists>v u y. 0 < v \\<and> v < y \\<and> inverse y \\<notin> Rep_preal R \\<and> \n    u \\<in> Rep_preal R \\<and> x = v * u\"\nproof -\n  from xpos and xless have \"1 < inverse x\" by (simp add: one_less_inverse_iff)\n  from lemma_gleason9_36 [OF cut_Rep_preal this]\n  obtain t where t: \"t \\<in> Rep_preal R\" \n             and notin: \"t * (inverse x) \\<notin> Rep_preal R\" ..\n  have rpos: \"0<t\" by (rule preal_imp_pos [OF cut_Rep_preal t])\n  from preal_exists_greater [OF cut_Rep_preal t]\n  obtain u where u: \"u \\<in> Rep_preal R\" and rless: \"t < u\" ..\n  have upos: \"0<u\" by (rule preal_imp_pos [OF cut_Rep_preal u])\n  show ?thesis\n  proof (intro exI conjI)\n    show \"0 < x/u\" using xpos upos\n      by (simp add: zero_less_divide_iff)  \n    show \"x/u < x/t\" using xpos upos rpos\n      by (simp add: divide_inverse mult_less_cancel_left rless) \n    show \"inverse (x / t) \\<notin> Rep_preal R\" using notin\n      by (simp add: divide_inverse mult.commute) \n    show \"u \\<in> Rep_preal R\" by (rule u) \n    show \"x = x / u * u\" using upos \n      by (simp add: divide_inverse mult.commute) \n  qed\nqed\n\nlemma subset_inverse_mult: \n     \"Rep_preal 1 \\<subseteq> Rep_preal(inverse r * r)\"\n  by (force simp: Rep_preal_one mem_Rep_preal_inverse_iff mem_Rep_preal_mult_iff dest: subset_inverse_mult_lemma)\n\nlemma inverse_mult_subset: \"Rep_preal(inverse r * r) \\<subseteq> Rep_preal 1\"\n  proof -\n  have \"0 < u * v\" if \"v \\<in> Rep_preal r\" \"0 < u\" \"u < t\" for u v t :: rat\n    using that by (simp add: zero_less_mult_iff preal_imp_pos [OF cut_Rep_preal]) \n  moreover have \"t * q < 1\"\n    if \"q \\<in> Rep_preal r\" \"0 < t\" \"t < y\" \"inverse y \\<notin> Rep_preal r\"\n    for t q y :: rat\n  proof -\n    have \"q < inverse y\"\n      using not_in_Rep_preal_ub that by auto \n    hence \"t * q < t/y\" \n      using that by (simp add: divide_inverse mult_less_cancel_left)\n    also have \"\\<dots> \\<le> 1\" \n      using that by (simp add: pos_divide_le_eq)\n    finally show ?thesis .\n  qed\n  ultimately show ?thesis\n    by (auto simp: Rep_preal_one mem_Rep_preal_inverse_iff mem_Rep_preal_mult_iff)\nqed \n\nlemma preal_mult_inverse: \"inverse r * r = (1::preal)\"\n  by (meson Rep_preal_inject inverse_mult_subset subset_antisym subset_inverse_mult)\n\nlemma preal_mult_inverse_right: \"r * inverse r = (1::preal)\"\n  using preal_mult_commute preal_mult_inverse by auto\n\n\ntext\\<open>Theorems needing \\<open>Gleason9_34\\<close>\\<close>\n\nlemma Rep_preal_self_subset: \"Rep_preal (r) \\<subseteq> Rep_preal(r + s)\"\nproof \n  fix x\n  assume x: \"x \\<in> Rep_preal r\"\n  obtain y where y: \"y \\<in> Rep_preal s\" and \"y > 0\"\n    using Rep_preal preal_nonempty by blast\n  have ry: \"x+y \\<in> Rep_preal(r + s)\" using x y\n    by (auto simp: mem_Rep_preal_add_iff)\n  then show \"x \\<in> Rep_preal(r + s)\"\n    by (meson \\<open>0 < y\\<close> add_less_same_cancel1 not_in_Rep_preal_ub order.asym preal_imp_pos [OF cut_Rep_preal x])\nqed\n\nlemma Rep_preal_sum_not_subset: \"~ Rep_preal (r + s) \\<subseteq> Rep_preal(r)\"\nproof -\n  obtain y where y: \"y \\<in> Rep_preal s\" and \"y > 0\"\n    using Rep_preal preal_nonempty by blast\n  obtain x where \"x \\<in> Rep_preal r\" and notin: \"x + y \\<notin> Rep_preal r\"\n    using Dedekind_Real.Rep_preal Gleason9_34 \\<open>0 < y\\<close> by blast \n  then have \"x + y \\<in> Rep_preal (r + s)\" using y\n    by (auto simp: mem_Rep_preal_add_iff)\n  thus ?thesis using notin by blast\nqed\n\ntext\\<open>at last, Gleason prop. 9-3.5(iii) page 123\\<close>\nproposition preal_self_less_add_left: \"(r::preal) < r + s\"\n  by (meson Rep_preal_sum_not_subset not_less preal_le_def)\n\n\nsubsection\\<open>Subtraction for Positive Reals\\<close>\n\ntext\\<open>gleason prop. 9-3.5(iv), page 123: proving \\<^prop>\\<open>a < b \\<Longrightarrow> \\<exists>d. a + d = b\\<close>. \nWe define the claimed \\<^term>\\<open>D\\<close> and show that it is a positive real\\<close>\n\nlemma mem_diff_set:\n  assumes \"r < s\"\n  shows \"cut (diff_set (Rep_preal s) (Rep_preal r))\"\nproof -\n  obtain p where \"Rep_preal r \\<subseteq> Rep_preal s\" \"p \\<in> Rep_preal s\" \"p \\<notin> Rep_preal r\"\n    using assms unfolding preal_less_def by auto\n  then have \"{} \\<subset> diff_set (Rep_preal s) (Rep_preal r)\"\n    apply (simp add: diff_set_def psubset_eq)\n    by (metis cut_Rep_preal add_eq_exists less_add_same_cancel1 preal_exists_greater preal_imp_pos)\n  moreover\n  obtain q where \"q > 0\" \"q \\<notin> Rep_preal s\"\n    using Rep_preal_exists_bound by blast\n  then have qnot: \"q \\<notin> diff_set (Rep_preal s) (Rep_preal r)\"\n    by (auto simp: diff_set_def dest: cut_Rep_preal [THEN preal_downwards_closed])\n  moreover have \"diff_set (Rep_preal s) (Rep_preal r) \\<subset> {0<..}\" (is \"?lhs < ?rhs\")\n    using \\<open>0 < q\\<close> diff_set_def qnot by blast\n  moreover have \"z \\<in> diff_set (Rep_preal s) (Rep_preal r)\"\n    if u: \"u \\<in> diff_set (Rep_preal s) (Rep_preal r)\" and \"0 < z\" \"z < u\" for u z\n    using u that less_trans Rep_preal unfolding diff_set_def Dedekind_Real.cut_def by auto\n  moreover have \"\\<exists>u \\<in> diff_set (Rep_preal s) (Rep_preal r). y < u\"\n    if y: \"y \\<in> diff_set (Rep_preal s) (Rep_preal r)\" for y\n  proof -\n    obtain a b where \"0 < a\" \"0 < b\" \"a \\<notin> Rep_preal r\" \"a + y + b \\<in> Rep_preal s\"\n      using y\n      by (simp add: diff_set_def) (metis cut_Rep_preal add_eq_exists less_add_same_cancel1 preal_exists_greater) \n    then have \"a + (y + b) \\<in> Rep_preal s\"\n      by (simp add: add.assoc)\n    then have \"y + b \\<in> diff_set (Rep_preal s) (Rep_preal r)\"\n      using \\<open>0 < a\\<close> \\<open>0 < b\\<close> \\<open>a \\<notin> Rep_preal r\\<close> y\n      by (auto simp: diff_set_def)\n    then show ?thesis\n      using \\<open>0 < b\\<close> less_add_same_cancel1 by blast\n  qed\n  ultimately show ?thesis\n    by (simp add: Dedekind_Real.cut_def)\nqed\n\nlemma mem_Rep_preal_diff_iff:\n  \"r < s \\<Longrightarrow>\n       (z \\<in> Rep_preal (s - r)) \\<longleftrightarrow> \n       (\\<exists>x. 0 < x \\<and> 0 < z \\<and> x \\<notin> Rep_preal r \\<and> x + z \\<in> Rep_preal s)\"\n  apply (simp add: preal_diff_def mem_diff_set Rep_preal)\n  apply (force simp: diff_set_def) \n  done\n\nproposition less_add_left:\n  fixes r::preal \n  assumes \"r < s\"\n  shows \"r + (s-r) = s\"\nproof -\n  have \"a + b \\<in> Rep_preal s\"\n    if \"a \\<in> Rep_preal r\" \"c + b \\<in> Rep_preal s\" \"c \\<notin> Rep_preal r\"\n    and \"0 < b\" \"0 < c\" for a b c\n    by (meson cut_Rep_preal add_less_imp_less_right add_pos_pos not_in_Rep_preal_ub preal_downwards_closed preal_imp_pos that)\n  then have \"r + (s-r) \\<le> s\"\n    using assms mem_Rep_preal_add_iff mem_Rep_preal_diff_iff preal_le_def by auto\n  have \"x \\<in> Rep_preal (r + (s - r))\" if \"x \\<in> Rep_preal s\" for x\n  proof (cases \"x \\<in> Rep_preal r\")\n    case True\n    then show ?thesis\n      using Rep_preal_self_subset by blast\n  next\n    case False\n    have \"\\<exists>u v z. 0 < v \\<and> 0 < z \\<and> u \\<in> Rep_preal r \\<and> z \\<notin> Rep_preal r \\<and> z + v \\<in> Rep_preal s \\<and> x = u + v\"\n      if x: \"x \\<in> Rep_preal s\"\n    proof -\n      have xpos: \"x > 0\"\n        using Rep_preal preal_imp_pos that by blast \n      obtain e where epos: \"0 < e\" and xe: \"x + e \\<in> Rep_preal s\"\n        by (metis cut_Rep_preal x add_eq_exists less_add_same_cancel1 preal_exists_greater)\n      from  Gleason9_34 [OF cut_Rep_preal epos]\n      obtain u where r: \"u \\<in> Rep_preal r\" and notin: \"u + e \\<notin> Rep_preal r\" ..\n      with x False xpos have rless: \"u < x\" by (blast intro: not_in_Rep_preal_ub)\n      from add_eq_exists [of u x]\n      obtain y where eq: \"x = u+y\" by auto\n      show ?thesis \n      proof (intro exI conjI)\n        show \"u + e \\<notin> Rep_preal r\" by (rule notin)\n        show \"u + e + y \\<in> Rep_preal s\" using xe eq by (simp add: ac_simps)\n        show \"0 < u + e\" \n          using epos preal_imp_pos [OF cut_Rep_preal r] by simp\n      qed (use r rless eq in auto)\n    qed\n    then show ?thesis\n      using assms mem_Rep_preal_add_iff mem_Rep_preal_diff_iff that by blast\n  qed\n  then have \"s \\<le> r + (s-r)\"\n    by (auto simp: preal_le_def)\n  then show ?thesis\n    by (simp add: \\<open>r + (s - r) \\<le> s\\<close> antisym)\nqed\n\nlemma preal_add_less2_mono1: \"r < (s::preal) \\<Longrightarrow> r + t < s + t\"\n  by (metis add.assoc add.commute less_add_left preal_self_less_add_left)\n\nlemma preal_add_less2_mono2: \"r < (s::preal) \\<Longrightarrow> t + r < t + s\"\n  by (auto intro: preal_add_less2_mono1 simp add: preal_add_commute [of t])\n\nlemma preal_add_right_less_cancel: \"r + t < s + t \\<Longrightarrow> r < (s::preal)\"\n  by (metis linorder_cases order.asym preal_add_less2_mono1)\n\nlemma preal_add_left_less_cancel: \"t + r < t + s \\<Longrightarrow> r < (s::preal)\"\n  by (auto elim: preal_add_right_less_cancel simp add: preal_add_commute [of t])\n\nlemma preal_add_less_cancel_left [simp]: \"(t + (r::preal) < t + s) \\<longleftrightarrow> (r < s)\"\n  by (blast intro: preal_add_less2_mono2 preal_add_left_less_cancel)\n\nlemma preal_add_less_cancel_right [simp]: \"((r::preal) + t < s + t) = (r < s)\"\n  using preal_add_less_cancel_left [symmetric, of r s t] by (simp add: ac_simps)\n\nlemma preal_add_le_cancel_left [simp]: \"(t + (r::preal) \\<le> t + s) = (r \\<le> s)\"\n  by (simp add: linorder_not_less [symmetric]) \n\nlemma preal_add_le_cancel_right [simp]: \"((r::preal) + t \\<le> s + t) = (r \\<le> s)\"\n  using preal_add_le_cancel_left [symmetric, of r s t] by (simp add: ac_simps)\n\nlemma preal_add_right_cancel: \"(r::preal) + t = s + t \\<Longrightarrow> r = s\"\n  by (metis less_irrefl linorder_cases preal_add_less_cancel_right)\n\nlemma preal_add_left_cancel: \"c + a = c + b \\<Longrightarrow> a = (b::preal)\"\n  by (auto intro: preal_add_right_cancel simp add: preal_add_commute)\n\ninstance preal :: linordered_ab_semigroup_add\nproof\n  fix a b c :: preal\n  show \"a \\<le> b \\<Longrightarrow> c + a \\<le> c + b\" by (simp only: preal_add_le_cancel_left)\nqed\n\n\nsubsection\\<open>Completeness of type \\<^typ>\\<open>preal\\<close>\\<close>\n\ntext\\<open>Prove that supremum is a cut\\<close>\n\ntext\\<open>Part 1 of Dedekind sections definition\\<close>\n\nlemma preal_sup:\n  assumes le: \"\\<And>X. X \\<in> P \\<Longrightarrow> X \\<le> Y\" and \"P \\<noteq> {}\" \n  shows \"cut (\\<Union>X \\<in> P. Rep_preal(X))\"\nproof -\n  have \"{} \\<subset> (\\<Union>X \\<in> P. Rep_preal(X))\"\n    using \\<open>P \\<noteq> {}\\<close> mem_Rep_preal_Ex by fastforce\n  moreover\n  obtain q where \"q > 0\" and \"q \\<notin> (\\<Union>X \\<in> P. Rep_preal(X))\"\n    using Rep_preal_exists_bound [of Y] le by (auto simp: preal_le_def)\n  then have \"(\\<Union>X \\<in> P. Rep_preal(X)) \\<subset> {0<..}\"\n    using cut_Rep_preal preal_imp_pos by force\n  moreover\n  have \"\\<And>u z. \\<lbrakk>u \\<in> (\\<Union>X \\<in> P. Rep_preal(X)); 0 < z; z < u\\<rbrakk> \\<Longrightarrow> z \\<in> (\\<Union>X \\<in> P. Rep_preal(X))\"\n    by (auto elim: cut_Rep_preal [THEN preal_downwards_closed])\n  moreover\n  have \"\\<And>y. y \\<in> (\\<Union>X \\<in> P. Rep_preal(X)) \\<Longrightarrow> \\<exists>u \\<in> (\\<Union>X \\<in> P. Rep_preal(X)). y < u\"\n    by (blast dest: cut_Rep_preal [THEN preal_exists_greater])\n  ultimately show ?thesis\n    by (simp add: Dedekind_Real.cut_def)\nqed\n\nlemma preal_psup_le:\n     \"\\<lbrakk>\\<And>X. X \\<in> P \\<Longrightarrow> X \\<le> Y;  x \\<in> P\\<rbrakk> \\<Longrightarrow> x \\<le> psup P\"\n  using preal_sup [of P Y] unfolding preal_le_def psup_def by fastforce \n\nlemma psup_le_ub: \"\\<lbrakk>\\<And>X. X \\<in> P \\<Longrightarrow> X \\<le> Y; P \\<noteq> {}\\<rbrakk> \\<Longrightarrow> psup P \\<le> Y\"\n  using preal_sup [of P Y] by (simp add: SUP_least preal_le_def psup_def) \n\ntext\\<open>Supremum property\\<close>\nproposition preal_complete:\n  assumes le: \"\\<And>X. X \\<in> P \\<Longrightarrow> X \\<le> Y\" and \"P \\<noteq> {}\" \n  shows \"(\\<exists>X \\<in> P. Z < X) \\<longleftrightarrow> (Z < psup P)\" (is \"?lhs = ?rhs\")\nproof\n  assume ?lhs\n  then show ?rhs\n    using preal_sup [OF assms] preal_less_def psup_def by auto\nnext\n  assume ?rhs\n  then show ?lhs\n    by (meson \\<open>P \\<noteq> {}\\<close> not_less psup_le_ub) \nqed\n\nsubsection \\<open>Defining the Reals from the Positive Reals\\<close>\n\ntext \\<open>Here we do quotients the old-fashioned way\\<close>\n\ndefinition\n  realrel   ::  \"((preal * preal) * (preal * preal)) set\" where\n  \"realrel = {p. \\<exists>x1 y1 x2 y2. p = ((x1,y1),(x2,y2)) \\<and> x1+y2 = x2+y1}\"\n\ndefinition \"Real = UNIV//realrel\"\n\ntypedef real = Real\n  morphisms Rep_Real Abs_Real\n  unfolding Real_def by (auto simp: quotient_def)\n\ntext \\<open>This doesn't involve the overloaded \"real\" function: users don't see it\\<close>\ndefinition\n  real_of_preal :: \"preal \\<Rightarrow> real\" where\n  \"real_of_preal m = Abs_Real (realrel `` {(m + 1, 1)})\"\n\ninstantiation real :: \"{zero, one, plus, minus, uminus, times, inverse, ord, abs, sgn}\"\nbegin\n\ndefinition\n  real_zero_def: \"0 = Abs_Real(realrel``{(1, 1)})\"\n\ndefinition\n  real_one_def: \"1 = Abs_Real(realrel``{(1 + 1, 1)})\"\n\ndefinition\n  real_add_def: \"z + w =\n       the_elem (\\<Union>(x,y) \\<in> Rep_Real z. \\<Union>(u,v) \\<in> Rep_Real w.\n                 { Abs_Real(realrel``{(x+u, y+v)}) })\"\n\ndefinition\n  real_minus_def: \"- r =  the_elem (\\<Union>(x,y) \\<in> Rep_Real r. { Abs_Real(realrel``{(y,x)}) })\"\n\ndefinition\n  real_diff_def: \"r - (s::real) = r + - s\"\n\ndefinition\n  real_mult_def:\n    \"z * w =\n       the_elem (\\<Union>(x,y) \\<in> Rep_Real z. \\<Union>(u,v) \\<in> Rep_Real w.\n                 { Abs_Real(realrel``{(x*u + y*v, x*v + y*u)}) })\"\n\ndefinition\n  real_inverse_def: \"inverse (r::real) \\<equiv> (THE s. (r = 0 \\<and> s = 0) \\<or> s * r = 1)\"\n\ndefinition\n  real_divide_def: \"r div (s::real) \\<equiv> r * inverse s\"\n\ndefinition\n  real_le_def: \"z \\<le> (w::real) \\<equiv>\n    (\\<exists>x y u v. x+v \\<le> u+y \\<and> (x,y) \\<in> Rep_Real z \\<and> (u,v) \\<in> Rep_Real w)\"\n\ndefinition\n  real_less_def: \"x < (y::real) \\<equiv> x \\<le> y \\<and> x \\<noteq> y\"\n\ndefinition\n  real_abs_def: \"\\<bar>r::real\\<bar> = (if r < 0 then - r else r)\"\n\ndefinition\n  real_sgn_def: \"sgn (x::real) = (if x=0 then 0 else if 0<x then 1 else - 1)\"\n\ninstance ..\n\nend\n\nsubsection \\<open>Equivalence relation over positive reals\\<close>\n\nlemma realrel_iff [simp]: \"(((x1,y1),(x2,y2)) \\<in> realrel) = (x1 + y2 = x2 + y1)\"\n  by (simp add: realrel_def)\n\nlemma preal_trans_lemma:\n  assumes \"x + y1 = x1 + y\" and \"x + y2 = x2 + y\"\n  shows \"x1 + y2 = x2 + (y1::preal)\"\n  by (metis add.left_commute assms preal_add_left_cancel)\n\nlemma equiv_realrel: \"equiv UNIV realrel\"\n  by (auto simp: equiv_def refl_on_def sym_def trans_def realrel_def intro: dest: preal_trans_lemma)\n\ntext\\<open>Reduces equality of equivalence classes to the \\<^term>\\<open>realrel\\<close> relation:\n  \\<^term>\\<open>(realrel `` {x} = realrel `` {y}) = ((x,y) \\<in> realrel)\\<close>\\<close>\nlemmas equiv_realrel_iff [simp] = \n       eq_equiv_class_iff [OF equiv_realrel UNIV_I UNIV_I]\n\nlemma realrel_in_real [simp]: \"realrel``{(x,y)} \\<in> Real\"\n  by (simp add: Real_def realrel_def quotient_def, blast)\n\ndeclare Abs_Real_inject [simp] Abs_Real_inverse [simp]\n\n\ntext\\<open>Case analysis on the representation of a real number as an equivalence\n      class of pairs of positive reals.\\<close>\nlemma eq_Abs_Real [case_names Abs_Real, cases type: real]: \n     \"(\\<And>x y. z = Abs_Real(realrel``{(x,y)}) \\<Longrightarrow> P) \\<Longrightarrow> P\"\n  by (metis Rep_Real_inverse prod.exhaust  Rep_Real [of z, unfolded Real_def, THEN quotientE])\n\nsubsection \\<open>Addition and Subtraction\\<close>\n\nlemma real_add:\n     \"Abs_Real (realrel``{(x,y)}) + Abs_Real (realrel``{(u,v)}) =\n      Abs_Real (realrel``{(x+u, y+v)})\"\nproof -\n  have \"(\\<lambda>z w. (\\<lambda>(x,y). (\\<lambda>(u,v). {Abs_Real (realrel `` {(x+u, y+v)})}) w) z)\n        respects2 realrel\"\n  by (clarsimp simp: congruent2_def) (metis add.left_commute preal_add_assoc)\n  thus ?thesis\n    by (simp add: real_add_def UN_UN_split_split_eq UN_equiv_class2 [OF equiv_realrel equiv_realrel])\nqed\n\nlemma real_minus: \"- Abs_Real(realrel``{(x,y)}) = Abs_Real(realrel `` {(y,x)})\"\nproof -\n  have \"(\\<lambda>(x,y). {Abs_Real (realrel``{(y,x)})}) respects realrel\"\n    by (auto simp: congruent_def add.commute) \n  thus ?thesis\n    by (simp add: real_minus_def UN_equiv_class [OF equiv_realrel])\nqed\n\ninstance real :: ab_group_add\nproof\n  fix x y z :: real\n  show \"(x + y) + z = x + (y + z)\"\n    by (cases x, cases y, cases z, simp add: real_add add.assoc)\n  show \"x + y = y + x\"\n    by (cases x, cases y, simp add: real_add add.commute)\n  show \"0 + x = x\"\n    by (cases x, simp add: real_add real_zero_def ac_simps)\n  show \"- x + x = 0\"\n    by (cases x, simp add: real_minus real_add real_zero_def add.commute)\n  show \"x - y = x + - y\"\n    by (simp add: real_diff_def)\nqed\n\n\nsubsection \\<open>Multiplication\\<close>\n\nlemma real_mult_congruent2_lemma:\n     \"!!(x1::preal). \\<lbrakk>x1 + y2 = x2 + y1\\<rbrakk> \\<Longrightarrow>\n          x * x1 + y * y1 + (x * y2 + y * x2) =\n          x * x2 + y * y2 + (x * y1 + y * x1)\"\n  by (metis (no_types, opaque_lifting) add.left_commute preal_add_commute preal_add_mult_distrib2)\n\nlemma real_mult_congruent2:\n  \"(\\<lambda>p1 p2.\n        (\\<lambda>(x1,y1). (\\<lambda>(x2,y2). \n          { Abs_Real (realrel``{(x1*x2 + y1*y2, x1*y2+y1*x2)}) }) p2) p1)\n     respects2 realrel\"\n  apply (rule congruent2_commuteI [OF equiv_realrel])\n  by (auto simp: mult.commute add.commute combine_common_factor preal_add_assoc preal_add_commute)\n\nlemma real_mult:\n  \"Abs_Real((realrel``{(x1,y1)})) * Abs_Real((realrel``{(x2,y2)})) =\n   Abs_Real(realrel `` {(x1*x2+y1*y2,x1*y2+y1*x2)})\"\n  by (simp add: real_mult_def UN_UN_split_split_eq\n      UN_equiv_class2 [OF equiv_realrel equiv_realrel real_mult_congruent2])\n\nlemma real_mult_commute: \"(z::real) * w = w * z\"\nby (cases z, cases w, simp add: real_mult ac_simps)\n\nlemma real_mult_assoc: \"((z1::real) * z2) * z3 = z1 * (z2 * z3)\"\n  by (cases z1, cases z2, cases z3) (simp add: real_mult algebra_simps)\n\nlemma real_mult_1: \"(1::real) * z = z\"\n  by (cases z) (simp add: real_mult real_one_def algebra_simps)\n\nlemma real_add_mult_distrib: \"((z1::real) + z2) * w = (z1 * w) + (z2 * w)\"\n  by (cases z1, cases z2, cases w) (simp add: real_add real_mult algebra_simps)\n\ntext\\<open>one and zero are distinct\\<close>\nlemma real_zero_not_eq_one: \"0 \\<noteq> (1::real)\"\nproof -\n  have \"(1::preal) < 1 + 1\"\n    by (simp add: preal_self_less_add_left)\n  then show ?thesis\n    by (simp add: real_zero_def real_one_def neq_iff)\nqed\n\ninstance real :: comm_ring_1\nproof\n  fix x y z :: real\n  show \"(x * y) * z = x * (y * z)\" by (rule real_mult_assoc)\n  show \"x * y = y * x\" by (rule real_mult_commute)\n  show \"1 * x = x\" by (rule real_mult_1)\n  show \"(x + y) * z = x * z + y * z\" by (rule real_add_mult_distrib)\n  show \"0 \\<noteq> (1::real)\" by (rule real_zero_not_eq_one)\nqed\n\nsubsection \\<open>Inverse and Division\\<close>\n\nlemma real_zero_iff: \"Abs_Real (realrel `` {(x, x)}) = 0\"\n  by (simp add: real_zero_def add.commute)\n\nlemma real_mult_inverse_left_ex:\n  assumes \"x \\<noteq> 0\" obtains y::real where \"y*x = 1\"\nproof (cases x)\n  case (Abs_Real u v)\n  show ?thesis\n  proof (cases u v rule: linorder_cases)\n    case less\n    then have \"v * inverse (v - u) = 1 + u * inverse (v - u)\"\n      using less_add_left [of u v]\n      by (metis preal_add_commute preal_add_mult_distrib preal_mult_inverse_right)\n    then have \"Abs_Real (realrel``{(1, inverse (v-u) + 1)}) * x - 1 = 0\"\n      by (simp add: Abs_Real real_mult preal_mult_inverse_right real_one_def) (simp add: algebra_simps)\n    with that show thesis by auto\n  next\n    case equal\n    then show ?thesis\n      using Abs_Real assms real_zero_iff by blast\n  next\n    case greater\n    then have \"u * inverse (u - v) = 1 + v * inverse (u - v)\"\n      using less_add_left [of v u] by (metis add.commute distrib_right preal_mult_inverse_right)\n    then have \"Abs_Real (realrel``{(inverse (u-v) + 1, 1)}) * x - 1 = 0\"\n      by (simp add: Abs_Real real_mult preal_mult_inverse_right real_one_def) (simp add: algebra_simps)\n    with that show thesis by auto\n  qed\nqed\n\n\nlemma real_mult_inverse_left:\n  fixes x :: real\n  assumes \"x \\<noteq> 0\" shows \"inverse x * x = 1\"\nproof -\n  obtain y where \"y*x = 1\"\n    using assms real_mult_inverse_left_ex by blast\n  then have \"(THE s. s * x = 1) * x = 1\"\n  proof (rule theI)\n    show \"y' = y\" if \"y' * x = 1\" for y'\n      by (metis \\<open>y * x = 1\\<close> mult.left_commute mult.right_neutral that) \n  qed\n  then show ?thesis\n    using assms real_inverse_def by auto\nqed\n\n\nsubsection\\<open>The Real Numbers form a Field\\<close>\n\ninstance real :: field\nproof\n  fix x y z :: real\n  show \"x \\<noteq> 0 \\<Longrightarrow> inverse x * x = 1\" by (rule real_mult_inverse_left)\n  show \"x / y = x * inverse y\" by (simp add: real_divide_def)\n  show \"inverse 0 = (0::real)\" by (simp add: real_inverse_def)\nqed\n\n\nsubsection\\<open>The \\<open>\\<le>\\<close> Ordering\\<close>\n\nlemma real_le_refl: \"w \\<le> (w::real)\"\n  by (cases w, force simp: real_le_def)\n\ntext\\<open>The arithmetic decision procedure is not set up for type preal.\n  This lemma is currently unused, but it could simplify the proofs of the\n  following two lemmas.\\<close>\nlemma preal_eq_le_imp_le:\n  assumes eq: \"a+b = c+d\" and le: \"c \\<le> a\"\n  shows \"b \\<le> (d::preal)\"\nproof -\n  from le have \"c+d \\<le> a+d\" by simp\n  hence \"a+b \\<le> a+d\" by (simp add: eq)\n  thus \"b \\<le> d\" by simp\nqed\n\nlemma real_le_lemma:\n  assumes l: \"u1 + v2 \\<le> u2 + v1\"\n    and \"x1 + v1 = u1 + y1\"\n    and \"x2 + v2 = u2 + y2\"\n  shows \"x1 + y2 \\<le> x2 + (y1::preal)\"\nproof -\n  have \"(x1+v1) + (u2+y2) = (u1+y1) + (x2+v2)\" by (simp add: assms)\n  hence \"(x1+y2) + (u2+v1) = (x2+y1) + (u1+v2)\" by (simp add: ac_simps)\n  also have \"\\<dots> \\<le> (x2+y1) + (u2+v1)\" by (simp add: assms)\n  finally show ?thesis by simp\nqed\n\nlemma real_le: \n  \"Abs_Real(realrel``{(x1,y1)}) \\<le> Abs_Real(realrel``{(x2,y2)})  \\<longleftrightarrow>  x1 + y2 \\<le> x2 + y1\"\n  unfolding real_le_def by (auto intro: real_le_lemma)\n\nlemma real_le_antisym: \"\\<lbrakk>z \\<le> w; w \\<le> z\\<rbrakk> \\<Longrightarrow> z = (w::real)\"\n  by (cases z, cases w, simp add: real_le)\n\nlemma real_trans_lemma:\n  assumes \"x + v \\<le> u + y\"\n    and \"u + v' \\<le> u' + v\"\n    and \"x2 + v2 = u2 + y2\"\n  shows \"x + v' \\<le> u' + (y::preal)\"\nproof -\n  have \"(x+v') + (u+v) = (x+v) + (u+v')\" by (simp add: ac_simps)\n  also have \"\\<dots> \\<le> (u+y) + (u+v')\" by (simp add: assms)\n  also have \"\\<dots> \\<le> (u+y) + (u'+v)\" by (simp add: assms)\n  also have \"\\<dots> = (u'+y) + (u+v)\"  by (simp add: ac_simps)\n  finally show ?thesis by simp\nqed\n\nlemma real_le_trans: \"\\<lbrakk>i \\<le> j; j \\<le> k\\<rbrakk> \\<Longrightarrow> i \\<le> (k::real)\"\n  by (cases i, cases j, cases k) (auto simp: real_le intro: real_trans_lemma)\n\ninstance real :: order\nproof\n  show \"u < v \\<longleftrightarrow> u \\<le> v \\<and> \\<not> v \\<le> u\" for u v::real\n    by (auto simp: real_less_def intro: real_le_antisym)\nqed (auto intro: real_le_refl real_le_trans real_le_antisym)\n\ninstance real :: linorder\nproof\n  show \"x \\<le> y \\<or> y \\<le> x\" for x y :: real\n    by (meson eq_refl le_cases real_le_def)\nqed\n\ninstantiation real :: distrib_lattice\nbegin\n\ndefinition\n  \"(inf :: real \\<Rightarrow> real \\<Rightarrow> real) = min\"\n\ndefinition\n  \"(sup :: real \\<Rightarrow> real \\<Rightarrow> real) = max\"\n\ninstance\n  by standard (auto simp: inf_real_def sup_real_def max_min_distrib2)\n\nend\n\nsubsection\\<open>The Reals Form an Ordered Field\\<close>\n\nlemma real_le_eq_diff: \"(x \\<le> y) \\<longleftrightarrow> (x-y \\<le> (0::real))\"\n  by (cases x, cases y) (simp add: real_le real_zero_def real_diff_def real_add real_minus preal_add_commute)\n\nlemma real_add_left_mono: \n  assumes le: \"x \\<le> y\" shows \"z + x \\<le> z + (y::real)\"\nproof -\n  have \"z + x - (z + y) = (z + -z) + (x - y)\" \n    by (simp add: algebra_simps) \n  with le show ?thesis \n    by (simp add: real_le_eq_diff[of x] real_le_eq_diff[of \"z+x\"])\nqed\n\nlemma real_sum_gt_zero_less: \"(0 < s + (-w::real)) \\<Longrightarrow> (w < s)\"\n  by (simp add: linorder_not_le [symmetric] real_le_eq_diff [of s])\n\nlemma real_less_sum_gt_zero: \"(w < s) \\<Longrightarrow> (0 < s + (-w::real))\"\n  by (simp add: linorder_not_le [symmetric] real_le_eq_diff [of s])\n\nlemma real_mult_order: \n  fixes x y::real\n  assumes \"0 < x\" \"0 < y\"\n  shows \"0 < x * y\"\n  proof (cases x, cases y)\n  show \"0 < x * y\"\n    if x: \"x = Abs_Real (Dedekind_Real.realrel `` {(x1, x2)})\"\n      and y: \"y = Abs_Real (Dedekind_Real.realrel `` {(y1, y2)})\"\n    for x1 x2 y1 y2\n  proof -\n    have \"x2 < x1\" \"y2 < y1\"\n      using assms not_le real_zero_def real_le x y\n      by (metis preal_add_le_cancel_left real_zero_iff)+\n    then obtain xd yd where \"x1 = x2 + xd\" \"y1 = y2 + yd\"\n      using less_add_left by metis\n    then have \"\\<not> (x * y \\<le> 0)\"\n      apply (simp add: x y real_mult real_zero_def real_le)\n      apply (simp add: not_le algebra_simps preal_self_less_add_left)\n      done\n    then show ?thesis\n      by auto\n  qed\nqed\n\nlemma real_mult_less_mono2: \"\\<lbrakk>(0::real) < z; x < y\\<rbrakk> \\<Longrightarrow> z * x < z * y\"\n  by (metis add_uminus_conv_diff real_less_sum_gt_zero real_mult_order real_sum_gt_zero_less right_diff_distrib')\n\n\ninstance real :: linordered_field\nproof\n  fix x y z :: real\n  show \"x \\<le> y \\<Longrightarrow> z + x \\<le> z + y\" by (rule real_add_left_mono)\n  show \"\\<bar>x\\<bar> = (if x < 0 then -x else x)\" by (simp only: real_abs_def)\n  show \"sgn x = (if x=0 then 0 else if 0<x then 1 else - 1)\"\n    by (simp only: real_sgn_def)\n  show \"z * x < z * y\" if \"x < y\" \"0 < z\"\n    by (simp add: real_mult_less_mono2 that)\nqed\n\n\nsubsection \\<open>Completeness of the reals\\<close>\n\ntext\\<open>The function \\<^term>\\<open>real_of_preal\\<close> requires many proofs, but it seems\nto be essential for proving completeness of the reals from that of the\npositive reals.\\<close>\n\nlemma real_of_preal_add:\n  \"real_of_preal ((x::preal) + y) = real_of_preal x + real_of_preal y\"\n  by (simp add: real_of_preal_def real_add algebra_simps)\n\nlemma real_of_preal_mult:\n  \"real_of_preal ((x::preal) * y) = real_of_preal x * real_of_preal y\"\n  by (simp add: real_of_preal_def real_mult algebra_simps)\n\ntext\\<open>Gleason prop 9-4.4 p 127\\<close>\nlemma real_of_preal_trichotomy:\n  \"\\<exists>m. (x::real) = real_of_preal m \\<or> x = 0 \\<or> x = -(real_of_preal m)\"\nproof (cases x)\n  case (Abs_Real u v)\n  show ?thesis\n  proof (cases u v rule: linorder_cases)\n    case less\n    then show ?thesis\n      using less_add_left\n      apply (simp add: Abs_Real real_of_preal_def real_minus real_zero_def)\n      by (metis preal_add_assoc preal_add_commute)      \n  next\n    case equal\n    then show ?thesis\n      using Abs_Real real_zero_iff by blast\n  next\n    case greater\n    then show ?thesis\n      using less_add_left\n      apply (simp add: Abs_Real real_of_preal_def real_minus real_zero_def)\n      by (metis preal_add_assoc preal_add_commute)      \n  qed\nqed\n\nlemma real_of_preal_less_iff [simp]:\n  \"(real_of_preal m1 < real_of_preal m2) = (m1 < m2)\"\n  by (metis not_less preal_add_less_cancel_right real_le real_of_preal_def)\n\nlemma real_of_preal_le_iff [simp]:\n  \"(real_of_preal m1 \\<le> real_of_preal m2) = (m1 \\<le> m2)\"\n  by (simp add: linorder_not_less [symmetric])\n\nlemma real_of_preal_zero_less [simp]: \"0 < real_of_preal m\"\n  by (metis less_add_same_cancel2 preal_self_less_add_left real_of_preal_add real_of_preal_less_iff)\n\n\nsubsection\\<open>Theorems About the Ordering\\<close>\n\nlemma real_gt_zero_preal_Ex: \"(0 < x) \\<longleftrightarrow> (\\<exists>y. x = real_of_preal y)\"\n  using order.asym real_of_preal_trichotomy by fastforce\n\nsubsection \\<open>Completeness of Positive Reals\\<close>\n\ntext \\<open>\n  Supremum property for the set of positive reals\n\n  Let \\<open>P\\<close> be a non-empty set of positive reals, with an upper\n  bound \\<open>y\\<close>.  Then \\<open>P\\<close> has a least upper bound\n  (written \\<open>S\\<close>).\n\n  FIXME: Can the premise be weakened to \\<open>\\<forall>x \\<in> P. x\\<le> y\\<close>?\n\\<close>\n\nlemma posreal_complete:\n  assumes positive_P: \"\\<forall>x \\<in> P. (0::real) < x\"\n    and not_empty_P: \"\\<exists>x. x \\<in> P\"\n    and upper_bound_Ex: \"\\<exists>y. \\<forall>x \\<in> P. x<y\"\n  shows \"\\<exists>s. \\<forall>y. (\\<exists>x \\<in> P. y < x) = (y < s)\"\nproof (rule exI, rule allI)\n  fix y\n  let ?pP = \"{w. real_of_preal w \\<in> P}\"\n\n  show \"(\\<exists>x\\<in>P. y < x) = (y < real_of_preal (psup ?pP))\"\n  proof (cases \"0 < y\")\n    assume neg_y: \"\\<not> 0 < y\"\n    show ?thesis\n    proof\n      assume \"\\<exists>x\\<in>P. y < x\"\n      thus \"y < real_of_preal (psup ?pP)\"\n        by (metis dual_order.strict_trans neg_y not_less_iff_gr_or_eq real_of_preal_zero_less) \n    next\n      assume \"y < real_of_preal (psup ?pP)\"\n      obtain \"x\" where x_in_P: \"x \\<in> P\" using not_empty_P ..\n      thus \"\\<exists>x \\<in> P. y < x\" using x_in_P\n        using neg_y not_less_iff_gr_or_eq positive_P by fastforce \n    qed\n  next\n    assume pos_y: \"0 < y\"\n    then obtain py where y_is_py: \"y = real_of_preal py\"\n      by (auto simp: real_gt_zero_preal_Ex)\n\n    obtain a where \"a \\<in> P\" using not_empty_P ..\n    with positive_P have a_pos: \"0 < a\" ..\n    then obtain pa where \"a = real_of_preal pa\"\n      by (auto simp: real_gt_zero_preal_Ex)\n    hence \"pa \\<in> ?pP\" using \\<open>a \\<in> P\\<close> by auto\n    hence pP_not_empty: \"?pP \\<noteq> {}\" by auto\n\n    obtain sup where sup: \"\\<forall>x \\<in> P. x < sup\"\n      using upper_bound_Ex ..\n    from this and \\<open>a \\<in> P\\<close> have \"a < sup\" ..\n    hence \"0 < sup\" using a_pos by arith\n    then obtain possup where \"sup = real_of_preal possup\"\n      by (auto simp: real_gt_zero_preal_Ex)\n    hence \"\\<forall>X \\<in> ?pP. X \\<le> possup\"\n      using sup by auto\n    with pP_not_empty have psup: \"\\<And>Z. (\\<exists>X \\<in> ?pP. Z < X) = (Z < psup ?pP)\"\n      by (meson preal_complete)\n    show ?thesis\n    proof\n      assume \"\\<exists>x \\<in> P. y < x\"\n      then obtain x where x_in_P: \"x \\<in> P\" and y_less_x: \"y < x\" ..\n      hence \"0 < x\" using pos_y by arith\n      then obtain px where x_is_px: \"x = real_of_preal px\"\n        by (auto simp: real_gt_zero_preal_Ex)\n\n      have py_less_X: \"\\<exists>X \\<in> ?pP. py < X\"\n      proof\n        show \"py < px\" using y_is_py and x_is_px and y_less_x\n          by simp\n        show \"px \\<in> ?pP\" using x_in_P and x_is_px by simp\n      qed\n\n      have \"(\\<exists>X \\<in> ?pP. py < X) \\<Longrightarrow> (py < psup ?pP)\"\n        using psup by simp\n      hence \"py < psup ?pP\" using py_less_X by simp\n      thus \"y < real_of_preal (psup {w. real_of_preal w \\<in> P})\"\n        using y_is_py and pos_y by simp\n    next\n      assume y_less_psup: \"y < real_of_preal (psup ?pP)\"\n\n      hence \"py < psup ?pP\" using y_is_py\n        by simp\n      then obtain \"X\" where py_less_X: \"py < X\" and X_in_pP: \"X \\<in> ?pP\"\n        using psup by auto\n      then obtain x where x_is_X: \"x = real_of_preal X\"\n        by (simp add: real_gt_zero_preal_Ex)\n      hence \"y < x\" using py_less_X and y_is_py\n        by simp\n      moreover have \"x \\<in> P\" \n        using x_is_X and X_in_pP by simp\n      ultimately show \"\\<exists> x \\<in> P. y < x\" ..\n    qed\n  qed\nqed\n\n\nsubsection \\<open>Completeness\\<close>\n\nlemma reals_complete:\n  fixes S :: \"real set\"\n  assumes notempty_S: \"\\<exists>X. X \\<in> S\"\n    and exists_Ub: \"bdd_above S\"\n  shows \"\\<exists>x. (\\<forall>s\\<in>S. s \\<le> x) \\<and> (\\<forall>y. (\\<forall>s\\<in>S. s \\<le> y) \\<longrightarrow> x \\<le> y)\"\nproof -\n  obtain X where X_in_S: \"X \\<in> S\" using notempty_S ..\n  obtain Y where Y_isUb: \"\\<forall>s\\<in>S. s \\<le> Y\"\n    using exists_Ub by (auto simp: bdd_above_def)\n  let ?SHIFT = \"{z. \\<exists>x \\<in>S. z = x + (-X) + 1} \\<inter> {x. 0 < x}\"\n\n  {\n    fix x\n    assume S_le_x: \"\\<forall>s\\<in>S. s \\<le> x\"\n    {\n      fix s\n      assume \"s \\<in> {z. \\<exists>x\\<in>S. z = x + - X + 1}\"\n      hence \"\\<exists> x \\<in> S. s = x + -X + 1\" ..\n      then obtain x1 where x1: \"x1 \\<in> S\" \"s = x1 + (-X) + 1\" ..\n      then have \"x1 \\<le> x\" using S_le_x by simp\n      with x1 have \"s \\<le> x + - X + 1\" by arith\n    }\n    then have \"\\<forall>s\\<in>?SHIFT. s \\<le> x + (-X) + 1\"\n      by auto\n  } note S_Ub_is_SHIFT_Ub = this\n\n  have *: \"\\<forall>s\\<in>?SHIFT. s \\<le> Y + (-X) + 1\" using Y_isUb by (rule S_Ub_is_SHIFT_Ub)\n  have \"\\<forall>s\\<in>?SHIFT. s < Y + (-X) + 2\"\n  proof\n    fix s assume \"s\\<in>?SHIFT\"\n    with * have \"s \\<le> Y + (-X) + 1\" by simp\n    also have \"\\<dots> < Y + (-X) + 2\" by simp\n    finally show \"s < Y + (-X) + 2\" .\n  qed\n  moreover have \"\\<forall>y \\<in> ?SHIFT. 0 < y\" by auto\n  moreover have shifted_not_empty: \"\\<exists>u. u \\<in> ?SHIFT\"\n    using X_in_S and Y_isUb by auto\n  ultimately obtain t where t_is_Lub: \"\\<forall>y. (\\<exists>x\\<in>?SHIFT. y < x) = (y < t)\"\n    using posreal_complete [of ?SHIFT] unfolding bdd_above_def by blast\n\n  show ?thesis\n  proof\n    show \"(\\<forall>s\\<in>S. s \\<le> (t + X + (-1))) \\<and> (\\<forall>y. (\\<forall>s\\<in>S. s \\<le> y) \\<longrightarrow> (t + X + (-1)) \\<le> y)\"\n    proof safe\n      fix x\n      assume \"\\<forall>s\\<in>S. s \\<le> x\"\n      hence \"\\<forall>s\\<in>?SHIFT. s \\<le> x + (-X) + 1\"\n        using S_Ub_is_SHIFT_Ub by simp\n      then have \"\\<not> x + (-X) + 1 < t\"\n        by (subst t_is_Lub[rule_format, symmetric]) (simp add: not_less)\n      thus \"t + X + -1 \\<le> x\" by arith\n    next\n      fix y\n      assume y_in_S: \"y \\<in> S\"\n      obtain \"u\" where u_in_shift: \"u \\<in> ?SHIFT\" using shifted_not_empty ..\n      hence \"\\<exists> x \\<in> S. u = x + - X + 1\" by simp\n      then obtain \"x\" where x_and_u: \"u = x + - X + 1\" ..\n      have u_le_t: \"u \\<le> t\"\n      proof (rule dense_le)\n        fix x assume \"x < u\" then have \"x < t\"\n          using u_in_shift t_is_Lub by auto\n        then show \"x \\<le> t\"  by simp\n      qed\n\n      show \"y \\<le> t + X + -1\"\n      proof cases\n        assume \"y \\<le> x\"\n        moreover have \"x = u + X + - 1\" using x_and_u by arith\n        moreover have \"u + X + - 1  \\<le> t + X + -1\" using u_le_t by arith\n        ultimately show \"y  \\<le> t + X + -1\" by arith\n      next\n        assume \"~(y \\<le> x)\"\n        hence x_less_y: \"x < y\" by arith\n\n        have \"x + (-X) + 1 \\<in> ?SHIFT\" using x_and_u and u_in_shift by simp\n        hence \"0 < x + (-X) + 1\" by simp\n        hence \"0 < y + (-X) + 1\" using x_less_y by arith\n        hence *: \"y + (-X) + 1 \\<in> ?SHIFT\" using y_in_S by simp\n        have \"y + (-X) + 1 \\<le> t\"\n        proof (rule dense_le)\n          fix x assume \"x < y + (-X) + 1\" then have \"x < t\"\n            using * t_is_Lub by auto\n          then show \"x \\<le> t\"  by simp\n        qed\n        thus ?thesis by simp\n      qed\n    qed\n  qed\nqed\n\nsubsection \\<open>The Archimedean Property of the Reals\\<close>\n\ntheorem reals_Archimedean:\n  fixes x :: real\n  assumes x_pos: \"0 < x\"\n  shows \"\\<exists>n. inverse (of_nat (Suc n)) < x\"\nproof (rule ccontr)\n  assume contr: \"\\<not> ?thesis\"\n  have \"\\<forall>n. x * of_nat (Suc n) \\<le> 1\"\n  proof\n    fix n\n    from contr have \"x \\<le> inverse (of_nat (Suc n))\"\n      by (simp add: linorder_not_less)\n    hence \"x \\<le> (1 / (of_nat (Suc n)))\"\n      by (simp add: inverse_eq_divide)\n    moreover have \"(0::real) \\<le> of_nat (Suc n)\"\n      by (rule of_nat_0_le_iff)\n    ultimately have \"x * of_nat (Suc n) \\<le> (1 / of_nat (Suc n)) * of_nat (Suc n)\"\n      by (rule mult_right_mono)\n    thus \"x * of_nat (Suc n) \\<le> 1\" by (simp del: of_nat_Suc)\n  qed\n  hence 2: \"bdd_above {z. \\<exists>n. z = x * (of_nat (Suc n))}\"\n    by (auto intro!: bdd_aboveI[of _ 1])\n  have 1: \"\\<exists>X. X \\<in> {z. \\<exists>n. z = x* (of_nat (Suc n))}\" by auto\n  obtain t where\n    upper: \"\\<And>z. z \\<in> {z. \\<exists>n. z = x * of_nat (Suc n)} \\<Longrightarrow> z \\<le> t\" and\n    least: \"\\<And>y. (\\<And>a. a \\<in> {z. \\<exists>n. z = x * of_nat (Suc n)} \\<Longrightarrow> a \\<le> y) \\<Longrightarrow> t \\<le> y\"\n    using reals_complete[OF 1 2] by auto\n\n  have \"t \\<le> t + - x\"\n  proof (rule least)\n    fix a assume a: \"a \\<in> {z. \\<exists>n. z = x * (of_nat (Suc n))}\"\n    have \"\\<forall>n::nat. x * of_nat n \\<le> t + - x\"\n    proof\n      fix n\n      have \"x * of_nat (Suc n) \\<le> t\"\n        by (simp add: upper)\n      hence  \"x * (of_nat n) + x \\<le> t\"\n        by (simp add: distrib_left)\n      thus  \"x * (of_nat n) \\<le> t + - x\" by arith\n    qed    hence \"\\<forall>m. x * of_nat (Suc m) \\<le> t + - x\" by (simp del: of_nat_Suc)\n    with a show \"a \\<le> t + - x\"\n      by auto\n  qed\n  thus False using x_pos by arith\nqed\n\ntext \\<open>\n  There must be other proofs, e.g. \\<open>Suc\\<close> of the largest\n  integer in the cut representing \\<open>x\\<close>.\n\\<close>\n\nlemma reals_Archimedean2: \"\\<exists>n. (x::real) < of_nat (n::nat)\"\nproof cases\n  assume \"x \\<le> 0\"\n  hence \"x < of_nat (1::nat)\" by simp\n  thus ?thesis ..\nnext\n  assume \"\\<not> x \\<le> 0\"\n  hence x_greater_zero: \"0 < x\" by simp\n  hence \"0 < inverse x\" by simp\n  then obtain n where \"inverse (of_nat (Suc n)) < inverse x\"\n    using reals_Archimedean by blast\n  hence \"inverse (of_nat (Suc n)) * x < inverse x * x\"\n    using x_greater_zero by (rule mult_strict_right_mono)\n  hence \"inverse (of_nat (Suc n)) * x < 1\"\n    using x_greater_zero by simp\n  hence \"of_nat (Suc n) * (inverse (of_nat (Suc n)) * x) < of_nat (Suc n) * 1\"\n    by (rule mult_strict_left_mono) (simp del: of_nat_Suc)\n  hence \"x < of_nat (Suc n)\"\n    by (simp add: algebra_simps del: of_nat_Suc)\n  thus \"\\<exists>(n::nat). x < of_nat n\" ..\nqed\n\ninstance real :: archimedean_field\nproof\n  fix r :: real\n  obtain n :: nat where \"r < of_nat n\"\n    using reals_Archimedean2 ..\n  then have \"r \\<le> of_int (int n)\"\n    by simp\n  then show \"\\<exists>z. r \\<le> of_int z\" ..\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/Dedekind_Real/Dedekind_Real.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.863391617003942, "lm_q2_score": 0.8397339696776499, "lm_q1q2_score": 0.7250192699331253}}
{"text": "theory Chapter2\n  imports Complex_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.3 *)\nfun count :: \"'a \\<Rightarrow> 'a list \\<Rightarrow> nat\" where\n  \"count x Nil = 0\"\n| \"count x (Cons y ys) = (if x = y then 1 + count x ys else count x ys)\" \n\ntheorem count_le_len [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 Nil x = (Cons x Nil)\"\n| \"snoc (Cons y ys) x = (Cons y (snoc ys x))\"\n\nfun reverse :: \"'a list \\<Rightarrow> 'a list\" where\n  \"reverse Nil = Nil\"\n| \"reverse (Cons x xs) = (snoc (reverse xs) x)\"\n\nlemma reverse_cons [simp]: \"reverse (snoc xs a) = Cons a (reverse xs)\"\n  apply (induction xs)\n   apply (auto)\n  done\n\ntheorem reverse_reverse [simp]: \"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 n = (if n = 0 then 0 else n + (sum_upto (n - 1)))\"\n\ntheorem sum_upto_n [simp]: \"sum_upto n = n * (n + 1) div 2\"\n  apply (induction n)\n   apply (auto)\n  done\n\n(*********************************)\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\n(* Exercise 2.6 *)\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\nfun sum_list :: \"nat list \\<Rightarrow> nat\" where\n  \"sum_list [] = 0\"\n| \"sum_list (x # xs) = x + sum_list xs\"\n\nlemma sum_list_app [simp]: \"sum_list (xs @ ys) = sum_list xs + sum_list ys\"\n  apply (induction xs)\n   apply (auto)\n  done\n\ntheorem sum_tree_correct : \"sum_tree t = sum_list (contents t)\"\n  apply (induction t)\n   apply (auto)\n  done\n\n(* Exercise 2.7 *)\ndatatype 'a tree2 = Tip 'a | Node \"'a tree2\" 'a \"'a tree2\"\n\nfun mirror2 :: \"'a tree2 \\<Rightarrow> 'a tree2\" where\n  \"mirror2 (Tip x) = (Tip x)\"\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 (Tip x) = [x]\"\n| \"pre_order (Node l x r) = x # (pre_order l) @ (pre_order r)\"\n\nfun post_order :: \"'a tree2 \\<Rightarrow> 'a list\" where\n  \"post_order (Tip x) = [x]\"\n| \"post_order (Node l x r) = (post_order l) @ (post_order r) @ [x]\"\n\ntheorem tree_traversal : \"pre_order (mirror2 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 a [] = []\"\n| \"intersperse a (x # xs) = (x # a # intersperse a xs)\"\n\ntheorem intersperse_map : \"map f (intersperse a xs) = intersperse (f a) (map f xs)\"\n  apply (induction xs)\n   apply (auto)\n  done\n\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\nlemma \"itrev xs ys = rev xs @ ys\"\n  apply (induction xs arbitrary:ys)\n   apply (auto)\n  done\n\n(* Exercise 2.10 *)\ndatatype tree0 = Leaf | Node tree0 tree0\n\nfun nodes :: \"tree0 \\<Rightarrow> nat\" where\n  \"nodes Leaf = 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\ntheorem explode_node : \"nodes (explode n t) = 2^n * (nodes t + 1) - 1\"\n  apply (induction n arbitrary:t)\n   apply (auto)\n  apply (simp add:algebra_simps)\n  done\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 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> int\" where\n  \"evalp [] x = 0\"\n| \"evalp (c#cs) x = c + x * (evalp cs x)\"\n\nfun list_add :: \"int list \\<Rightarrow> int list \\<Rightarrow> int list\" where\n  \"list_add [] ys = ys\"\n| \"list_add xs [] = xs\"\n| \"list_add (x#xs) (y#ys) = (x + y) # (list_add xs ys)\"\n\nfun list_mult :: \"int list \\<Rightarrow> int list \\<Rightarrow> int list\" where\n  \"list_mult [] _ = []\"\n| \"list_mult _ [] = []\"\n| \"list_mult (x#xs) ys = list_add (map (\\<lambda>n. n * x) ys) (list_mult xs (0 # ys))\"\n\nfun coeffs :: \"exp \\<Rightarrow> int list\" where\n  \"coeffs Var = [0, 1]\"\n| \"coeffs (Const n) = [n]\"\n| \"coeffs (Add e1 e2) = list_add (coeffs e1) (coeffs e2)\"\n| \"coeffs (Mult e1 e2) = list_mult (coeffs e1) (coeffs e2)\"\n\n(* Why doesn't the following work with\n   apply (induction l1)\n   apply (auto)\n   apply (induction l2)\n   ...  *)\nlemma evalp_add_distr [simp]: \"evalp (list_add l1 l2) x = evalp l1 x + evalp l2 x\"\n  apply (induction rule:list_add.induct)\n   apply (auto simp add:algebra_simps)\n  done\n\nlemma evalp_map : \"evalp (map (\\<lambda>n. n * a) l) x = a * evalp l x\"\n  apply (induction l)\n   apply (auto simp add:algebra_simps)\n  done\n\nlemma evalp_mult_distr : \"evalp (list_mult l1 l2) x = evalp l1 x * evalp l2 x\"\n  apply (induction rule:list_mult.induct)\n  apply (auto)\n  apply (simp add:evalp_map)\n  apply (simp add:algebra_simps)\n  done\n\ntheorem coeffs_preserve : \"evalp (coeffs e) x = eval e x\"\n  apply (induction e)\n   apply (auto)\n   apply (simp add:evalp_add_distr)\n   apply (simp add:evalp_mult_distr)\n  done\n\nend\n", "meta": {"author": "momohatt", "repo": "sandbox", "sha": "6be8d7facf9b4c36965fea71580e609550631722", "save_path": "github-repos/isabelle/momohatt-sandbox", "path": "github-repos/isabelle/momohatt-sandbox/sandbox-6be8d7facf9b4c36965fea71580e609550631722/isabelle-tutorial/Chapter2.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916205190226, "lm_q2_score": 0.8397339656668287, "lm_q1q2_score": 0.7250192694219485}}
{"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_22\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 (max a b) c) = (max a (max b c)))\"\n(*This nested induction (a \\<rightarrow> b \\<rightarrow> c) is easy to choose:\n  \"induct a\" because the patter matching of \"max\" is exclusive on the first argument,\n             and \"a\" is always the first argument of \"max\" in this case\n             and for other first arguments of \"max\" are non-variable terms.\n  We have two innermost \"max\"es. For one \"max\" the first argument is \"b\".\n  Starting with induction on \"b\" also works, but the following proof becomes longer\n  because it necessitates induction on the first argument of other \"max\", which is \"a\" even for\n  the base case.\n *)\n  apply(induct a arbitrary: b c)\n   apply fastforce\n  (* We still have two \"max\"es: \"max (S a) b\" and \"max b c\".\n     But the first argument of \"max (S a) b\" starts with a constructor, on which we cannot induct.\n   *)\n  apply(induct_tac b)\n   apply fastforce\n  apply(induct_tac c)(*This can be case_tac*)\n  (*Despite the warning \"Induction variable occurs also among premises: \"c\"\", it works.*)\n  apply fastforce+\n  done\n\ntheorem property':(*sub-optimal proof with one extra induction step.*)\n  \"((max (max a b) c) = (max a (max b c)))\"\n  apply(induct b arbitrary: a c)\n  apply(induct_tac a) (*extra induction step.*)\n   apply fastforce+\n  apply(induct_tac a)\n   apply fastforce\n  apply(induct_tac c)(*Despite the warning \"Induction variable occurs also among premises: \"c\"\", it works.*)\n  apply fastforce+\n  done\n\ntheorem property'':(*bad.*)\n  \"((max (max a b) c) = (max a (max b c)))\"\n  apply(induct rule:max.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_22.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916134888613, "lm_q2_score": 0.8397339676722393, "lm_q1q2_score": 0.725019265249938}}
{"text": "(*  Title:      HOL/ex/HarmonicSeries.thy\n    Author:     Benjamin Porter, 2006\n*)\n\nsection {* Divergence of the Harmonic Series *}\n\ntheory HarmonicSeries\nimports Complex_Main\nbegin\n\nsubsection {* Abstract *}\n\ntext {* 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*}\n\nsubsection {* Formal Proof *}\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 {* 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}$. *}\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\n        \"inverse (real x) \\<ge> inverse (real ((2::nat)^m))\"\n        by (simp del: real_of_nat_power)\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 setsum_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 real_of_nat_def)\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 {* 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})$. *}\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 -- \"show that LHS = c and RHS = c, and thus LHS = RHS\"\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 setsum_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: setsum.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 {* 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. *}\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 setsum_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 {* 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] setsum_less_suminf} ( @{thm\nsetsum_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. *}\n\ntheorem DivergenceOfHarmonicSeries:\n  shows \"\\<not>summable (\\<lambda>n. 1/real (Suc n))\"\n  (is \"\\<not>summable ?f\")\nproof -- \"by contradiction\"\n  let ?s = \"suminf ?f\" -- \"let ?s equal the sum of the harmonic series\"\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\"\n  proof -\n    have \"\\<forall>n. 0 \\<le> ?f n\" by simp\n    with sf have \"?s \\<ge> 0\"\n      by (rule suminf_nonneg)\n    then have cgt0: \"\\<lceil>2*?s\\<rceil> \\<ge> 0\" by simp\n\n    from ndef have \"n = nat \\<lceil>(2*?s)\\<rceil>\" .\n    then have \"real n = real (nat \\<lceil>2*?s\\<rceil>)\" by simp\n    with cgt0 have \"real n = real \\<lceil>2*?s\\<rceil>\"\n      by (auto dest: real_nat_eq_real)\n    then have \"real n \\<ge> 2*(?s)\" by simp\n    then have \"real n/2 \\<ge> (?s)\" by simp\n    then show \"1 + real n/2 > (?s)\" by simp\n  qed\n\n  obtain j where jdef: \"j = (2::nat)^n\" by simp\n  have \"\\<forall>m\\<ge>j. 0 < ?f m\" by simp\n  with sf have \"(\\<Sum>i<j. ?f i) < ?s\" by (rule setsum_less_suminf)\n  then have \"(\\<Sum>i\\<in>{Suc 0..<Suc j}. 1/(real i)) < ?s\"\n    unfolding setsum_shift_bounds_Suc_ivl by (simp add: atLeast0LessThan)\n  with jdef 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": "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/HarmonicSeries.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.839733963661418, "lm_q2_score": 0.8633916117313211, "lm_q1q2_score": 0.7250192603111623}}
{"text": "theory  Search_Tree2\nimports Search_Tree\nbegin          \n\nlemmas search_tree2_induct = search_tree.induct[where 'a = \"'a * 'b\", split_format(complete)]\n\nlemmas search_tree2_cases = search_tree.exhaust[where 'a = \"'a * 'b\", split_format(complete)]\n\nfun inorder :: \"('a*'b)search_tree \\<Rightarrow> 'a list\" where\n\"inorder Leaf = []\" |\n\"inorder (Node l (a,_) r) = inorder l @ a # inorder r\"\n\nfun set_search_tree :: \"('a*'b) search_tree \\<Rightarrow> 'a set\" where\n\"set_search_tree Leaf = {}\" |\n\"set_search_tree (Node l (a,_) r) = {a} \\<union> set_search_tree l \\<union> set_search_tree r\"\n\nfun bst :: \"('a::linorder*'b) search_tree \\<Rightarrow> bool\" where\n\"bst Leaf = True\" |\n\"bst (Node l (a, _) r) = ((\\<forall>x \\<in> set_search_tree l. x < a) \\<and> (\\<forall>x \\<in> set_search_tree r. a < x) \\<and> bst l \\<and> bst r)\"\n\nlemma finite_set_search_tree[simp]: \"finite(set_search_tree t)\"\nby(induction t) auto\n\nlemma eq_set_search_tree_empty[simp]: \"set_search_tree t = {} \\<longleftrightarrow> t = Leaf\"\nby (cases t) auto\n\nlemma set_inorder[simp]: \"set (inorder t) = set_search_tree t\"\nby (induction t) auto\n\nlemma length_inorder[simp]: \"length (inorder t) = size t\"\nby (induction t) auto\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/Search_Tree2.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037384317887, "lm_q2_score": 0.7826624738835052, "lm_q1q2_score": 0.7249831754885631}}
{"text": "theory approach_Feb\n  imports Main\nbegin\n\ndefinition la :: \"nat list\" where \"la = [1::nat, 2]\"\ndefinition lb :: \"nat list\" where \"lb = [3::nat, 4]\"\ndefinition lc :: \"nat list\" where \"lc = [5::nat, 6, 7]\"\ndefinition ld :: \"nat list\" where \"ld = [8::nat, 9]\"\n\n(*BIP Simon*)\nvalue \"\\<exists>i \\<in> set la.\\<exists>j \\<in> set lb. \\<exists>k \\<in> set lc. ((P i \\<longrightarrow> ((Q j \\<and> R k))) \n\\<and> (\\<forall>i1 \\<in> set la - {i}.\\<not>P i1)\n\\<and> (\\<forall>j1 \\<in> set lb - {j}.\\<not>Q j1)\n\\<and> (\\<forall>k1 \\<in> set lc - {k}.\\<not>R k1)\n)\"\n\n(*BIP Trinh*)\nvalue \"(\\<forall>i \\<in> set la. ((P i \\<longrightarrow> (\\<exists>j \\<in> set lb. \\<exists>k \\<in> set lc.(Q j \\<and> R k))) \n\\<and> (\\<forall>i \\<in> set la.(P i \\<longrightarrow> (\\<forall>i1 \\<in> set la - {i}.\\<not>P i1)))\n\\<and> (\\<forall>j \\<in> set lb.(Q j \\<longrightarrow> (\\<forall>j1 \\<in> set lb - {j}.\\<not>Q j1)))\n\\<and> (\\<forall>k \\<in> set lc.(R k \\<longrightarrow> (\\<forall>k1 \\<in> set lc - {k}.\\<not>R k1)))\n))\"\n\n(*JavaBIP Simon*)\nvalue \"(\\<forall>i \\<in> set la. ((P i \\<longrightarrow> (\\<exists>j \\<in> set lb. \\<exists>k \\<in> set lc.(Q j \\<and> R k) \\<and> (\\<forall>j1 \\<in> set lb - {j}.\\<not>Q j1)\n\\<and> (\\<forall>k1 \\<in> set lc - {k}.\\<not>R k1))) \n\\<and> (\\<forall>i \\<in> set la.(P i \\<longrightarrow> (\\<forall>i1 \\<in> set la - {i}.\\<not>P i1)))\n\\<and> (\\<forall>j \\<in> set lb.(Q j \\<longrightarrow> (\\<forall>j1 \\<in> set lb - {j}.\\<not>Q j1)))\n\\<and> (\\<forall>k \\<in> set lc.(R k \\<longrightarrow> (\\<forall>k1 \\<in> set lc - {k}.\\<not>R k1)))\n))\"\n\nlemma btrinh_jvbsimon:\"(\\<exists>i \\<in> set la.\\<exists>j \\<in> set lb. \\<exists>k \\<in> set lc. ((P i \\<longrightarrow> ((Q j \\<and> R k))) \n\\<and> (\\<forall>i1 \\<in> set la - {i}.\\<not>P i1)\n\\<and> (\\<forall>j1 \\<in> set lb - {j}.\\<not>Q j1)\n\\<and> (\\<forall>k1 \\<in> set lc - {k}.\\<not>R k1)\n)) \\<longleftrightarrow>\n(\\<forall>i \\<in> set la. ((P i \\<longrightarrow> (\\<exists>j \\<in> set lb. \\<exists>k \\<in> set lc.(Q j \\<and> R k))) \n\\<and> (\\<forall>i \\<in> set la.(P i \\<longrightarrow> (\\<forall>i1 \\<in> set la - {i}.\\<not>P i1)))\n\\<and> (\\<forall>j \\<in> set lb.(Q j \\<longrightarrow> (\\<forall>j1 \\<in> set lb - {j}.\\<not>Q j1)))\n\\<and> (\\<forall>k \\<in> set lc.(R k \\<longrightarrow> (\\<forall>k1 \\<in> set lc - {k}.\\<not>R k1)))\n))\"\n  unfolding la_def lb_def lc_def ld_def\n  sledgehammer\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/2022/approach_Feb.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9294404077216355, "lm_q2_score": 0.7799929104825007, "lm_q1q2_score": 0.7249569287388407}}
{"text": "(*  Title:      HOL/Induct/Tree.thy\n    Author:     Stefan Berghofer,  TU Muenchen\n    Author:     Lawrence C Paulson, Cambridge University Computer Laboratory\n*)\n\nsection {* Infinitely branching trees *}\n\ntheory Tree\nimports Main\nbegin\n\ndatatype 'a tree =\n    Atom 'a\n  | Branch \"nat => 'a tree\"\n\nprimrec map_tree :: \"('a => 'b) => 'a tree => 'b tree\"\nwhere\n  \"map_tree f (Atom a) = Atom (f a)\"\n| \"map_tree f (Branch ts) = Branch (\\<lambda>x. map_tree f (ts x))\"\n\nlemma tree_map_compose: \"map_tree g (map_tree f t) = map_tree (g \\<circ> f) t\"\n  by (induct t) simp_all\n\nprimrec exists_tree :: \"('a => bool) => 'a tree => bool\"\nwhere\n  \"exists_tree P (Atom a) = P a\"\n| \"exists_tree P (Branch ts) = (\\<exists>x. exists_tree P (ts x))\"\n\nlemma exists_map:\n  \"(!!x. P x ==> Q (f x)) ==>\n    exists_tree P ts ==> exists_tree Q (map_tree f ts)\"\n  by (induct ts) auto\n\n\nsubsection{*The Brouwer ordinals, as in ZF/Induct/Brouwer.thy.*}\n\ndatatype brouwer = Zero | Succ \"brouwer\" | Lim \"nat => brouwer\"\n\ntext{*Addition of ordinals*}\nprimrec add :: \"[brouwer,brouwer] => brouwer\"\nwhere\n  \"add i Zero = i\"\n| \"add i (Succ j) = Succ (add i j)\"\n| \"add i (Lim f) = Lim (%n. add i (f n))\"\n\n\n\ntext{*Multiplication of ordinals*}\nprimrec mult :: \"[brouwer,brouwer] => brouwer\"\nwhere\n  \"mult i Zero = Zero\"\n| \"mult i (Succ j) = add (mult i j) i\"\n| \"mult i (Lim f) = Lim (%n. mult i (f n))\"\n\nlemma add_mult_distrib: \"mult i (add j k) = add (mult i j) (mult i k)\"\n  by (induct k) (auto simp add: add_assoc)\n\nlemma mult_assoc: \"mult (mult i j) k = mult i (mult j k)\"\n  by (induct k) (auto simp add: add_mult_distrib)\n\ntext{*We could probably instantiate some axiomatic type classes and use\nthe standard infix operators.*}\n\nsubsection{*A WF Ordering for The Brouwer ordinals (Michael Compton)*}\n\ntext{*To use the function package we need an ordering on the Brouwer\n  ordinals.  Start with a predecessor relation and form its transitive \n  closure. *} \n\ndefinition brouwer_pred :: \"(brouwer * brouwer) set\"\n  where \"brouwer_pred = (\\<Union>i. {(m,n). n = Succ m \\<or> (EX f. n = Lim f & m = f i)})\"\n\ndefinition brouwer_order :: \"(brouwer * brouwer) set\"\n  where \"brouwer_order = brouwer_pred^+\"\n\nlemma wf_brouwer_pred: \"wf brouwer_pred\"\n  by(unfold wf_def brouwer_pred_def, clarify, induct_tac x, blast+)\n\nlemma wf_brouwer_order[simp]: \"wf brouwer_order\"\n  by(unfold brouwer_order_def, rule wf_trancl[OF wf_brouwer_pred])\n\n\n\nlemma [simp]: \"(f n, Lim f) : brouwer_order\"\n  by(auto simp add: brouwer_order_def brouwer_pred_def)\n\ntext{*Example of a general function*}\n\nfunction add2 :: \"brouwer \\<Rightarrow> brouwer \\<Rightarrow> brouwer\"\nwhere\n  \"add2 i Zero = i\"\n| \"add2 i (Succ j) = Succ (add2 i j)\"\n| \"add2 i (Lim f) = Lim (\\<lambda>n. add2 i (f n))\"\nby pat_completeness auto\ntermination by (relation \"inv_image brouwer_order snd\") auto\n\nlemma add2_assoc: \"add2 (add2 i j) k = add2 i (add2 j k)\"\n  by (induct k) 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/Tree.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467580102418, "lm_q2_score": 0.8244619199068831, "lm_q1q2_score": 0.7248230239890359}}
{"text": "(*  Title:      HOL/Analysis/Continuum_Not_Denumerable.thy\n    Author:     Benjamin Porter, Monash University, NICTA, 2005\n    Author:     Johannes H\u00f6lzl, TU M\u00fcnchen\n*)\n\nsection \\<open>Non-Denumerability of the Continuum\\<close>\n\ntheory Continuum_Not_Denumerable\nimports\n  Complex_Main \n  \"HOL-Library.Countable_Set\"\nbegin\n\nsubsection\\<^marker>\\<open>tag unimportant\\<close> \\<open>Abstract\\<close>\n\ntext \\<open>\n  The following document presents a proof that the Continuum is uncountable.\n  It is formalised in the Isabelle/Isar theorem proving system.\n\n  \\<^bold>\\<open>Theorem:\\<close> The Continuum \\<open>\\<real>\\<close> is not denumerable. In other words, there does\n  not exist a function \\<open>f: \\<nat> \\<Rightarrow> \\<real>\\<close> such that \\<open>f\\<close> is surjective.\n\n  \\<^bold>\\<open>Outline:\\<close> An elegant informal proof of this result uses Cantor's\n  Diagonalisation argument. The proof presented here is not this one.\n\n  First we formalise some properties of closed intervals, then we prove the\n  Nested Interval Property. This property relies on the completeness of the\n  Real numbers and is the foundation for our argument. Informally it states\n  that an intersection of countable closed intervals (where each successive\n  interval is a subset of the last) is non-empty. We then assume a surjective\n  function \\<open>f: \\<nat> \\<Rightarrow> \\<real>\\<close> exists and find a real \\<open>x\\<close> such that \\<open>x\\<close> is not in the\n  range of \\<open>f\\<close> by generating a sequence of closed intervals then using the\n  Nested Interval Property.\n\\<close>\ntext\\<^marker>\\<open>tag important\\<close> \\<open>%whitespace\\<close>\ntheorem real_non_denum: \"\\<nexists>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 \\<open>First we construct a sequence of nested intervals, ignoring \\<^term>\\<open>range f\\<close>.\\<close>\n\n  have \"a < b \\<Longrightarrow> \\<exists>ka kb. ka < kb \\<and> {ka..kb} \\<subseteq> {a..b} \\<and> c \\<notin> {ka..kb}\" for a b c :: real\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    \"a < b \\<Longrightarrow> i a b c < j a b c\"\n      \"a < b \\<Longrightarrow> {i a b c .. j a b c} \\<subseteq> {a .. b}\"\n      \"a < b \\<Longrightarrow> c \\<notin> {i a b c .. j a b c}\"\n    for a b c :: real\n    by metis\n\n  define ivl where \"ivl =\n    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  define I where \"I n = {fst (ivl n) .. snd (ivl n)}\" for 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 \\<open>This is a decreasing sequence of non-empty intervals.\\<close>\n\n  have less: \"fst (ivl n) < snd (ivl n)\" for n\n    by (induct n) (auto intro!: ij)\n\n  have \"decseq I\"\n    unfolding I_def decseq_Suc_iff ivl fst_conv snd_conv\n    by (intro ij allI less)\n\n  txt \\<open>Now we apply the finite intersection property of compact sets.\\<close>\n\n  have \"I 0 \\<inter> (\\<Inter>i. I i) \\<noteq> {}\"\n  proof (rule compact_imp_fip_image)\n    fix S :: \"nat set\"\n    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 \\<open>decseq I\\<close>, of _ \"Max (insert 0 S)\"]\n      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 \"x \\<in> I n\" for n\n    by blast\n  moreover from \\<open>surj f\\<close> 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\ncorollary complex_non_denum: \"\\<nexists>f :: nat \\<Rightarrow> complex. surj f\"\n  by (metis (full_types) Re_complex_of_real comp_surj real_non_denum surj_def)\n\nlemma uncountable_UNIV_complex: \"uncountable (UNIV :: complex set)\"\n  using complex_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  define f where \"f a b c d x = (d - c)/(b - a) * (x - a) + c\" for a b c d x :: real\n  {\n    fix a b c d x :: real\n    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  }\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  then show ?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 arctan_tan)\n\nlemma uncountable_open_interval: \"uncountable {a<..<b} \\<longleftrightarrow> a < b\" for a b :: real\nproof\n  show \"a < b\" if \"uncountable {a<..<b}\"\n    using uncountable_def that by force\n  show \"uncountable {a<..<b}\" if \"a < b\"\n  proof -\n    obtain f where \"bij_betw f {a <..< b} {-pi/2<..<pi/2}\"\n      using bij_betw_open_intervals[OF \\<open>a < b\\<close>, of \"-pi/2\" \"pi/2\"] by auto\n    then show ?thesis\n      by (metis bij_betw_tan uncountable_bij_betw uncountable_UNIV_real)\n  qed\nqed\n\nlemma uncountable_half_open_interval_1: \"uncountable {a..<b} \\<longleftrightarrow> a < b\" for a b :: real\n  apply auto\n  using atLeastLessThan_empty_iff\n  apply fastforce\n  using uncountable_open_interval [of a b]\n  apply (metis countable_Un_iff ivl_disj_un_singleton(3))\n  done\n\nlemma uncountable_half_open_interval_2: \"uncountable {a<..b} \\<longleftrightarrow> a < b\" for a b :: real\n  apply auto\n  using atLeastLessThan_empty_iff\n  apply fastforce\n  using uncountable_open_interval [of a b]\n  apply (metis countable_Un_iff ivl_disj_un_singleton(4))\n  done\n\nlemma real_interval_avoid_countable_set:\n  fixes a b :: real and A :: \"real set\"\n  assumes \"a < b\" and \"countable A\"\n  shows \"\\<exists>x\\<in>{a<..<b}. x \\<notin> A\"\nproof -\n  from \\<open>countable A\\<close> have *: \"countable (A \\<inter> {a<..<b})\"\n    by auto\n  with \\<open>a < b\\<close> have \"\\<not> countable {a<..<b}\"\n    by (simp add: uncountable_open_interval)\n  with * have \"A \\<inter> {a<..<b} \\<noteq> {a<..<b}\"\n    by auto\n  then have \"A \\<inter> {a<..<b} \\<subset> {a<..<b}\"\n    by (intro psubsetI) auto\n  then have \"\\<exists>x. x \\<in> {a<..<b} - A \\<inter> {a<..<b}\"\n    by (rule psubset_imp_ex_mem)\n  then show ?thesis\n    by auto\nqed\n\nlemma uncountable_closed_interval: \"uncountable {a..b} \\<longleftrightarrow> a < b\" for a b :: real\n  using infinite_Icc_iff by (fastforce dest: countable_finite real_interval_avoid_countable_set)\n\nlemma open_minus_countable:\n  fixes S A :: \"real set\"\n  assumes \"countable A\" \"S \\<noteq> {}\" \"open S\"\n  shows \"\\<exists>x\\<in>S. x \\<notin> A\"\nproof -\n  obtain x where \"x \\<in> S\"\n    using \\<open>S \\<noteq> {}\\<close> by auto\n  then obtain e where \"0 < e\" \"{y. dist y x < e} \\<subseteq> S\"\n    using \\<open>open S\\<close> by (auto simp: open_dist subset_eq)\n  moreover have \"{y. dist y x < e} = {x - e <..< x + e}\"\n    by (auto simp: dist_real_def)\n  ultimately have \"uncountable (S - A)\"\n    using uncountable_open_interval[of \"x - e\" \"x + e\"] \\<open>countable A\\<close>\n    by (intro uncountable_minus_countable) (auto dest: countable_subset)\n  then show ?thesis\n    unfolding uncountable_def by auto\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/Analysis/Continuum_Not_Denumerable.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8244619091240701, "lm_q2_score": 0.8791467564270272, "lm_q1q2_score": 0.7248230132040607}}
{"text": "theory implication_subst\n  imports Main\n    \"HOL-Eisbach.Eisbach\"\n    \"fuzzyrule.fuzzyrule\"\nbegin\n\nsection \"Implication Subst\"\n\ntext \"Here we define a method to do subsitution with implications instead of equalities.\"\n\n\ntext \"The theorem collection pos_cong includes theorems for rewriting.\nEach of these theoremy has 2 assumptions.\nThe first one is the implication to use.\nThe left hand side of the implication should not contain any negations.\nThe second one represents the conclusion after rewriting.\"\nnamed_theorems pos_cong\n\n\nsubsection \"Quantifiers\"\n\nlemma implication_subst_exists[pos_cong]: \n  assumes \"\\<And>x. P x \\<Longrightarrow> Q x\"\n    and \"\\<exists>x. P x\"\n  shows \"\\<exists>x. Q x\"\n  using assms  by blast\n\nlemma implication_subst_not_exists[pos_cong]: \n  assumes \"\\<And>x. P x \\<Longrightarrow> \\<not>Q x\"\n    and \"\\<not>(\\<exists>x. \\<not>P x)\"\n  shows \"\\<not>(\\<exists>x. Q x)\"\n  using assms  by blast\n\nlemma implication_subst_forall[pos_cong]: \n  assumes \"\\<And>x. P x \\<Longrightarrow> Q x\"\n    and \"\\<forall>x. P x\"\n  shows \"\\<forall>x. Q x\"\n  using assms  by blast\n\nlemma implication_subst_not_forall[pos_cong]: \n  assumes \"\\<And>x. P x \\<Longrightarrow> \\<not>Q x\"\n    and \"\\<not>(\\<forall>x. \\<not>P x)\"\n  shows \"\\<not>(\\<forall>x. Q x)\"\n  using assms  by blast\n\n\n\nlemma implication_subst_bexists[pos_cong]: \n  assumes \"\\<And>x. P x \\<Longrightarrow> Q x\"\n    and \"\\<exists>x\\<in>S. P x\"\n  shows \"\\<exists>x\\<in>S. Q x\"\n  using assms by blast\n\nlemma implication_subst_not_bexists[pos_cong]: \n  assumes \"\\<And>x. P x \\<Longrightarrow> \\<not>Q x\"\n    and \"\\<not>(\\<exists>x\\<in>S. \\<not>P x)\"\n  shows \"\\<not>(\\<exists>x\\<in>S. Q x)\"\n  using assms  by blast\n\nlemma implication_subst_bforall[pos_cong]: \n  assumes \"\\<And>x. P x \\<Longrightarrow> Q x\"\n    and \"\\<forall>x\\<in>S. P x\"\n  shows \"\\<forall>x\\<in>S. Q x\"\n  using assms  by blast\n\nlemma implication_subst_not_bforall[pos_cong]: \n  assumes \"\\<And>x. P x \\<Longrightarrow> \\<not>Q x\"\n    and \"\\<not>(\\<forall>x\\<in>S. \\<not>P x)\"\n  shows \"\\<not>(\\<forall>x\\<in>S. Q x)\"\n  using assms  by blast\n\n\n\n\nsubsection \"Conjunction\"\n\nlemma implication_subst_conjl[pos_cong]:\n  assumes \"P \\<Longrightarrow> Q\"\n and \"P \\<and> A\"\nshows \"Q \\<and> A\"\n  using assms  by blast\n\nlemma implication_subst_conjr[pos_cong]:\n  assumes \"P \\<Longrightarrow> Q\"\n and \"A \\<and> P\"\nshows \"A \\<and> Q\"\n  using assms  by blast\n\nlemma implication_subst_not_conjl[pos_cong]:\n  assumes \"P \\<Longrightarrow> \\<not>Q\"\n and \"\\<not>(\\<not>P \\<and> A)\"\nshows \"\\<not>(Q \\<and> A)\"\n  using assms  by blast\n\nlemma implication_subst_not_conjr[pos_cong]:\n  assumes \"P \\<Longrightarrow> \\<not>Q\"\n and \"\\<not>(A \\<and> \\<not>P)\"\nshows \"\\<not>(A \\<and> Q)\"\n  using assms  by blast\n\nsubsection \"Double negation\"\n\nlemma implication_subst_neg[pos_cong]:\n  assumes \"P \\<Longrightarrow> Q\"\n    and \"P\"\n  shows \"\\<not>\\<not>Q\"\n  using assms by auto\n\nsubsection \"Implication\"\n\nlemma implication_subst_impl[pos_cong]:\n  assumes \"P \\<Longrightarrow> \\<not>Q\"\n    and \"\\<not>P \\<longrightarrow> A\"\n  shows \"Q \\<longrightarrow> A\"\n  using assms by auto\n\nlemma implication_subst_impr[pos_cong]:\n  assumes \"P \\<Longrightarrow> Q\"\n    and \"A \\<longrightarrow> P\"\n  shows \"A \\<longrightarrow> Q\"\n  using assms by auto\n\nlemma implication_subst_not_impl[pos_cong]:\n  assumes \"P \\<Longrightarrow> Q\"\n    and \"\\<not>(P \\<longrightarrow> A)\"\n  shows \"\\<not>(Q \\<longrightarrow> A)\"\n  using assms by auto\n\nlemma implication_subst_not_impr[pos_cong]:\n  assumes \"P \\<Longrightarrow> \\<not>Q\"\n    and \"\\<not>(A \\<longrightarrow> \\<not>P)\"\n  shows \"\\<not>(A \\<longrightarrow> Q)\"\n  using assms by auto\n\nsubsection \"Disjunction\"\n\n\nlemma implication_subst_disj_l[pos_cong]:\n  assumes \"P \\<Longrightarrow> Q\"\n    and \"P \\<or> A\"\n  shows \"Q \\<or> A\"\n  using assms by auto\n\nlemma implication_subst_r[pos_cong]:\n  assumes \"P \\<Longrightarrow> Q\"\n    and \"A \\<or> P\"\n  shows \"A \\<or> Q\"\n  using assms by auto\n\nlemma implication_subst_not_disj_l[pos_cong]:\n  assumes \"P \\<Longrightarrow> \\<not>Q\"\n    and \"\\<not>(\\<not>P \\<or> A)\"\n  shows \"\\<not>(Q \\<or> A)\"\n  using assms by auto\n\nlemma implication_subst_not_disj_r[pos_cong]:\n  assumes \"P \\<Longrightarrow> \\<not>Q\"\n    and \"\\<not>(A \\<or> \\<not>P)\"\n  shows \"\\<not>(A \\<or> Q)\"\n  using assms by auto\n\n\n\nmethod implication_subst_h uses r declares pos_cong = (\n      rule r \n      | (rule pos_cong, implication_subst_h r: r, assumption))\n\nmethod implication_subst uses r declares pos_cong =\n  (implication_subst_h r: r pos_cong: pos_cong, (unfold not_not)?)\n\n\nmethod implication_subst_fuzzy_h uses r declares pos_cong = (\n      fuzzy_rule r \n      | (rule pos_cong, implication_subst_h r: r, assumption))\n\nmethod implication_subst_fuzzy uses r declares pos_cong =\n  (implication_subst_fuzzy_h r: r pos_cong: pos_cong, (unfold not_not)?)\n\n\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/implication_subst.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392909114836, "lm_q2_score": 0.819893335913536, "lm_q1q2_score": 0.7248179233040531}}
{"text": "section \\<open>Binary Search_Tree\\<close>\n\ntheory Search_Tree\nimports Main\nbegin\n\ndatatype 'a search_tree =\n  Leaf (\"\\<langle>\\<rangle>\") |\n  Node \"'a search_tree\" (\"value\": 'a) \"'a search_tree\" (\"(1\\<langle>_,/ _,/ _\\<rangle>)\")\n\ndatatype_compat search_tree\n\nprimrec left :: \"'a search_tree \\<Rightarrow> 'a search_tree\" where\n\"left (Node l v r) = l\" |\n\"left Leaf = Leaf\"\n\nprimrec right :: \"'a search_tree \\<Rightarrow> 'a search_tree\" where\n\"right (Node l v r) = r\" |\n\"right Leaf = Leaf\"\n\ntext\\<open>Counting the number of leaves rather than nodes:\\<close>\n\nfun size1 :: \"'a search_tree \\<Rightarrow> nat\" where\n\"size1 \\<langle>\\<rangle> = 1\" |\n\"size1 \\<langle>l, x, r\\<rangle> = size1 l + size1 r\"\n\nfun subsearch_trees :: \"'a search_tree \\<Rightarrow> 'a search_tree set\" where\n\"subsearch_trees \\<langle>\\<rangle> = {\\<langle>\\<rangle>}\" |\n\"subsearch_trees (\\<langle>l, a, r\\<rangle>) = {\\<langle>l, a, r\\<rangle>} \\<union> subsearch_trees l \\<union> subsearch_trees r\"\n\nfun mirror :: \"'a search_tree \\<Rightarrow> 'a search_tree\" where\n\"mirror \\<langle>\\<rangle> = Leaf\" |\n\"mirror \\<langle>l,x,r\\<rangle> = \\<langle>mirror r, x, mirror l\\<rangle>\"\n\nclass height = fixes height :: \"'a \\<Rightarrow> nat\"\n\ninstantiation search_tree :: (type)height\nbegin\n\nfun height_search_tree :: \"'a search_tree => nat\" where\n\"height Leaf = 0\" |\n\"height (Node l a r) = max (height l) (height r) + 1\"\n\ninstance ..\n\nend\n\nfun min_height :: \"'a search_tree \\<Rightarrow> nat\" where\n\"min_height Leaf = 0\" |\n\"min_height (Node l _ r) = min (min_height l) (min_height r) + 1\"\n\nfun complete :: \"'a search_tree \\<Rightarrow> bool\" where\n\"complete Leaf = True\" |\n\"complete (Node l x r) = (height l = height r \\<and> complete l \\<and> complete r)\"\n\ntext \\<open>Almost complete:\\<close>\ndefinition acomplete :: \"'a search_tree \\<Rightarrow> bool\" where\n\"acomplete t = (height t - min_height t \\<le> 1)\"\n\ntext \\<open>Weight balanced:\\<close>\nfun wbalanced :: \"'a search_tree \\<Rightarrow> bool\" where\n\"wbalanced Leaf = True\" |\n\"wbalanced (Node l x r) = (abs(int(size l) - int(size r)) \\<le> 1 \\<and> wbalanced l \\<and> wbalanced r)\"\n\ntext \\<open>Internal path length:\\<close>\nfun ipl :: \"'a search_tree \\<Rightarrow> nat\" where\n\"ipl Leaf = 0 \" |\n\"ipl (Node l _ r) = ipl l + size l + ipl r + size r\"\n\nfun preorder :: \"'a search_tree \\<Rightarrow> 'a list\" where\n\"preorder \\<langle>\\<rangle> = []\" |\n\"preorder \\<langle>l, x, r\\<rangle> = x # preorder l @ preorder r\"\n\nfun inorder :: \"'a search_tree \\<Rightarrow> 'a list\" where\n\"inorder \\<langle>\\<rangle> = []\" |\n\"inorder \\<langle>l, x, r\\<rangle> = inorder l @ [x] @ inorder r\"\n\ntext\\<open>A linear version avoiding append:\\<close>\nfun inorder2 :: \"'a search_tree \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where\n\"inorder2 \\<langle>\\<rangle> xs = xs\" |\n\"inorder2 \\<langle>l, x, r\\<rangle> xs = inorder2 l (x # inorder2 r xs)\"\n\nfun postorder :: \"'a search_tree \\<Rightarrow> 'a list\" where\n\"postorder \\<langle>\\<rangle> = []\" |\n\"postorder \\<langle>l, x, r\\<rangle> = postorder l @ postorder r @ [x]\"\n\ntext\\<open>Binary Search Tree:\\<close>\nfun bst_wrt :: \"('a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> 'a search_tree \\<Rightarrow> bool\" where\n\"bst_wrt P \\<langle>\\<rangle> \\<longleftrightarrow> True\" |\n\"bst_wrt P \\<langle>l, a, r\\<rangle> \\<longleftrightarrow>\n (\\<forall>x\\<in>set_search_tree l. P x a) \\<and> (\\<forall>x\\<in>set_search_tree r. P a x) \\<and> bst_wrt P l \\<and> bst_wrt P r\"\n\nabbreviation bst :: \"('a::linorder) search_tree \\<Rightarrow> bool\" where\n\"bst \\<equiv> bst_wrt (<)\"\n\nfun (in linorder) heap :: \"'a search_tree \\<Rightarrow> bool\" where\n\"heap Leaf = True\" |\n\"heap (Node l m r) =\n  ((\\<forall>x \\<in> set_search_tree l \\<union> set_search_tree r. m \\<le> x) \\<and> heap l \\<and> heap r)\"\n\n\nsubsection \\<open>\\<^const>\\<open>map_search_tree\\<close>\\<close>\n\nlemma eq_map_search_tree_Leaf[simp]: \"map_search_tree f t = Leaf \\<longleftrightarrow> t = Leaf\"\nby (rule search_tree.map_disc_iff)\n\nlemma eq_Leaf_map_search_tree[simp]: \"Leaf = map_search_tree f t \\<longleftrightarrow> t = Leaf\"\nby (cases t) auto\n\n\nsubsection \\<open>\\<^const>\\<open>size\\<close>\\<close>\n\nlemma size1_size: \"size1 t = size t + 1\"\nby (induction t) simp_all\n\nlemma size1_ge0[simp]: \"0 < size1 t\"\nby (simp add: size1_size)\n\nlemma eq_size_0[simp]: \"size t = 0 \\<longleftrightarrow> t = Leaf\"\nby(cases t) auto\n\nlemma eq_0_size[simp]: \"0 = size t \\<longleftrightarrow> t = Leaf\"\nby(cases t) auto\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 size_map_search_tree[simp]: \"size (map_search_tree f t) = size t\"\nby (induction t) auto\n\nlemma size1_map_search_tree[simp]: \"size1 (map_search_tree f t) = size1 t\"\nby (simp add: size1_size)\n\n\nsubsection \\<open>\\<^const>\\<open>set_search_tree\\<close>\\<close>\n\nlemma eq_set_search_tree_empty[simp]: \"set_search_tree t = {} \\<longleftrightarrow> t = Leaf\"\nby (cases t) auto\n\nlemma eq_empty_set_search_tree[simp]: \"{} = set_search_tree t \\<longleftrightarrow> t = Leaf\"\nby (cases t) auto\n\nlemma finite_set_search_tree[simp]: \"finite(set_search_tree t)\"\nby(induction t) auto\n\n\nsubsection \\<open>\\<^const>\\<open>subsearch_trees\\<close>\\<close>\n\nlemma neq_subsearch_trees_empty[simp]: \"subsearch_trees t \\<noteq> {}\"\nby (cases t)(auto)\n\nlemma neq_empty_subsearch_trees[simp]: \"{} \\<noteq> subsearch_trees t\"\nby (cases t)(auto)\n\nlemma size_subsearch_trees: \"s \\<in> subsearch_trees t \\<Longrightarrow> size s \\<le> size t\"\nby(induction t)(auto)\n\nlemma set_search_treeE: \"a \\<in> set_search_tree t \\<Longrightarrow> \\<exists>l r. \\<langle>l, a, r\\<rangle> \\<in> subsearch_trees t\"\nby (induction t)(auto)\n\nlemma Node_notin_subsearch_trees_if[simp]: \"a \\<notin> set_search_tree t \\<Longrightarrow> Node l a r \\<notin> subsearch_trees t\"\nby (induction t) auto\n\nlemma in_set_search_tree_if: \"\\<langle>l, a, r\\<rangle> \\<in> subsearch_trees t \\<Longrightarrow> a \\<in> set_search_tree t\"\nby (metis Node_notin_subsearch_trees_if)\n\n\nsubsection \\<open>\\<^const>\\<open>height\\<close> and \\<^const>\\<open>min_height\\<close>\\<close>\n\nlemma eq_height_0[simp]: \"height t = 0 \\<longleftrightarrow> t = Leaf\"\nby(cases t) auto\n\nlemma eq_0_height[simp]: \"0 = height t \\<longleftrightarrow> t = Leaf\"\nby(cases t) auto\n\nlemma height_map_search_tree[simp]: \"height (map_search_tree f t) = height t\"\nby (induction t) auto\n\nlemma height_le_size_search_tree: \"height t \\<le> size (t::'a search_tree)\"\nby (induction t) auto\n\nlemma size1_height: \"size1 t \\<le> 2 ^ height (t::'a search_tree)\"\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 \"size1(Node l a r) = size1 l + size1 r\" by simp\n    also have \"\\<dots> \\<le> 2 ^ height l + 2 ^ height r\" using Node.IH by arith\n    also have \"\\<dots> \\<le> 2 ^ height r + 2 ^ height r\" using True by simp\n    also have \"\\<dots> = 2 ^ height (Node l a r)\"\n      using True by (auto simp: max_def mult_2)\n    finally show ?thesis .\n  next\n    case False\n    have \"size1(Node l a r) = size1 l + size1 r\" by simp\n    also have \"\\<dots> \\<le> 2 ^ height l + 2 ^ height r\" using Node.IH by arith\n    also have \"\\<dots> \\<le> 2 ^ height l + 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\ncorollary size_height: \"size t \\<le> 2 ^ height (t::'a search_tree) - 1\"\nusing size1_height[of t, unfolded size1_size] by(arith)\n\nlemma height_subsearch_trees: \"s \\<in> subsearch_trees t \\<Longrightarrow> height s \\<le> height t\"\nby (induction t) auto\n\n\nlemma min_height_le_height: \"min_height t \\<le> height t\"\nby(induction t) auto\n\nlemma min_height_map_search_tree[simp]: \"min_height (map_search_tree f t) = min_height t\"\nby (induction t) auto\n\nlemma min_height_size1: \"2 ^ min_height t \\<le> size1 t\"\nproof(induction t)\n  case (Node l a r)\n  have \"(2::nat) ^ min_height (Node l a r) \\<le> 2 ^ min_height l + 2 ^ min_height r\"\n    by (simp add: min_def)\n  also have \"\\<dots> \\<le> size1(Node l a r)\" using Node.IH by simp\n  finally show ?case .\nqed simp\n\n\nsubsection \\<open>\\<^const>\\<open>complete\\<close>\\<close>\n\nlemma complete_iff_height: \"complete t \\<longleftrightarrow> (min_height t = height t)\"\napply(induction t)\n apply simp\napply (simp add: min_def max_def)\nby (metis le_antisym le_trans min_height_le_height)\n\nlemma size1_if_complete: \"complete t \\<Longrightarrow> size1 t = 2 ^ height t\"\nby (induction t) auto\n\nlemma size_if_complete: \"complete t \\<Longrightarrow> size t = 2 ^ height t - 1\"\nusing size1_if_complete[simplified size1_size] by fastforce\n\nlemma size1_height_if_incomplete:\n  \"\\<not> complete t \\<Longrightarrow> size1 t < 2 ^ height t\"\nproof(induction t)\n  case Leaf thus ?case by simp\nnext\n  case (Node l x r)\n  have 1: ?case if h: \"height l < height r\"\n    using h size1_height[of l] size1_height[of r] power_strict_increasing[OF h, of \"2::nat\"]\n    by(auto simp: max_def simp del: power_strict_increasing_iff)\n  have 2: ?case if h: \"height l > height r\"\n    using h size1_height[of l] size1_height[of r] power_strict_increasing[OF h, of \"2::nat\"]\n    by(auto simp: max_def simp del: power_strict_increasing_iff)\n  have 3: ?case if h: \"height l = height r\" and c: \"\\<not> complete l\"\n    using h size1_height[of r] Node.IH(1)[OF c] by(simp)\n  have 4: ?case if h: \"height l = height r\" and c: \"\\<not> complete r\"\n    using h size1_height[of l] Node.IH(2)[OF c] by(simp)\n  from 1 2 3 4 Node.prems show ?case apply (simp add: max_def) by linarith\nqed\n\nlemma complete_iff_min_height: \"complete t \\<longleftrightarrow> (height t = min_height t)\"\nby(auto simp add: complete_iff_height)\n\nlemma min_height_size1_if_incomplete:\n  \"\\<not> complete t \\<Longrightarrow> 2 ^ min_height t < size1 t\"\nproof(induction t)\n  case Leaf thus ?case by simp\nnext\n  case (Node l x r)\n  have 1: ?case if h: \"min_height l < min_height r\"\n    using h min_height_size1[of l] min_height_size1[of r] power_strict_increasing[OF h, of \"2::nat\"]\n    by(auto simp: max_def simp del: power_strict_increasing_iff)\n  have 2: ?case if h: \"min_height l > min_height r\"\n    using h min_height_size1[of l] min_height_size1[of r] power_strict_increasing[OF h, of \"2::nat\"]\n    by(auto simp: max_def simp del: power_strict_increasing_iff)\n  have 3: ?case if h: \"min_height l = min_height r\" and c: \"\\<not> complete l\"\n    using h min_height_size1[of r] Node.IH(1)[OF c] by(simp add: complete_iff_min_height)\n  have 4: ?case if h: \"min_height l = min_height r\" and c: \"\\<not> complete r\"\n    using h min_height_size1[of l] Node.IH(2)[OF c] by(simp add: complete_iff_min_height)\n  from 1 2 3 4 Node.prems show ?case\n    by (fastforce simp: complete_iff_min_height[THEN iffD1])\nqed\n\nlemma complete_if_size1_height: \"size1 t = 2 ^ height t \\<Longrightarrow> complete t\"\nusing  size1_height_if_incomplete by fastforce\n\nlemma complete_if_size1_min_height: \"size1 t = 2 ^ min_height t \\<Longrightarrow> complete t\"\nusing min_height_size1_if_incomplete by fastforce\n\nlemma complete_iff_size1: \"complete t \\<longleftrightarrow> size1 t = 2 ^ height t\"\nusing complete_if_size1_height size1_if_complete by blast\n\n\nsubsection \\<open>\\<^const>\\<open>acomplete\\<close>\\<close>\n\nlemma acomplete_subsearch_treeL: \"acomplete (Node l x r) \\<Longrightarrow> acomplete l\"\nby(simp add: acomplete_def)\n\nlemma acomplete_subsearch_treeR: \"acomplete (Node l x r) \\<Longrightarrow> acomplete r\"\nby(simp add: acomplete_def)\n\nlemma acomplete_subsearch_trees: \"\\<lbrakk> acomplete t; s \\<in> subsearch_trees t \\<rbrakk> \\<Longrightarrow> acomplete s\"\nusing [[simp_depth_limit=1]]\nby(induction t arbitrary: s)\n  (auto simp add: acomplete_subsearch_treeL acomplete_subsearch_treeR)\n\ntext\\<open>Balanced search_trees have optimal height:\\<close>\n\nlemma acomplete_optimal:\nfixes t :: \"'a search_tree\" and t' :: \"'b search_tree\"\nassumes \"acomplete t\" \"size t \\<le> size t'\" shows \"height t \\<le> height t'\"\nproof (cases \"complete t\")\n  case True\n  have \"(2::nat) ^ height t \\<le> 2 ^ height t'\"\n  proof -\n    have \"2 ^ height t = size1 t\"\n      using True by (simp add: size1_if_complete)\n    also have \"\\<dots> \\<le> size1 t'\" using assms(2) by(simp add: size1_size)\n    also have \"\\<dots> \\<le> 2 ^ height t'\" by (rule size1_height)\n    finally show ?thesis .\n  qed\n  thus ?thesis by (simp)\nnext\n  case False\n  have \"(2::nat) ^ min_height t < 2 ^ height t'\"\n  proof -\n    have \"(2::nat) ^ min_height t < size1 t\"\n      by(rule min_height_size1_if_incomplete[OF False])\n    also have \"\\<dots> \\<le> size1 t'\" using assms(2) by (simp add: size1_size)\n    also have \"\\<dots> \\<le> 2 ^ height t'\"  by(rule size1_height)\n    finally have \"(2::nat) ^ min_height t < (2::nat) ^ height t'\" .\n    thus ?thesis .\n  qed\n  hence *: \"min_height t < height t'\" by simp\n  have \"min_height t + 1 = height t\"\n    using min_height_le_height[of t] assms(1) False\n    by (simp add: complete_iff_height acomplete_def)\n  with * show ?thesis by arith\nqed\n\n\nsubsection \\<open>\\<^const>\\<open>wbalanced\\<close>\\<close>\n\nlemma wbalanced_subsearch_trees: \"\\<lbrakk> wbalanced t; s \\<in> subsearch_trees t \\<rbrakk> \\<Longrightarrow> wbalanced s\"\nusing [[simp_depth_limit=1]] by(induction t arbitrary: s) auto\n\n\nsubsection \\<open>\\<^const>\\<open>ipl\\<close>\\<close>\n\ntext \\<open>The internal path length of a search_tree:\\<close>\n\nlemma ipl_if_complete_int:\n  \"complete t \\<Longrightarrow> int(ipl t) = (int(height t) - 2) * 2^(height t) + 2\"\napply(induction t)\n apply simp\napply simp\napply (simp add: algebra_simps size_if_complete of_nat_diff)\ndone\n\n\nsubsection \"List of entries\"\n\nlemma eq_inorder_Nil[simp]: \"inorder t = [] \\<longleftrightarrow> t = Leaf\"\nby (cases t) auto\n\nlemma eq_Nil_inorder[simp]: \"[] = inorder t \\<longleftrightarrow> t = Leaf\"\nby (cases t) auto\n\nlemma set_inorder[simp]: \"set (inorder t) = set_search_tree t\"\nby (induction t) auto\n\nlemma set_preorder[simp]: \"set (preorder t) = set_search_tree t\"\nby (induction t) auto\n\nlemma set_postorder[simp]: \"set (postorder t) = set_search_tree t\"\nby (induction t) auto\n\nlemma length_preorder[simp]: \"length (preorder t) = size t\"\nby (induction t) auto\n\nlemma length_inorder[simp]: \"length (inorder t) = size t\"\nby (induction t) auto\n\nlemma length_postorder[simp]: \"length (postorder t) = size t\"\nby (induction t) auto\n\nlemma preorder_map: \"preorder (map_search_tree f t) = map f (preorder t)\"\nby (induction t) auto\n\nlemma inorder_map: \"inorder (map_search_tree f t) = map f (inorder t)\"\nby (induction t) auto\n\nlemma postorder_map: \"postorder (map_search_tree f t) = map f (postorder t)\"\nby (induction t) auto\n\nlemma inorder2_inorder: \"inorder2 t xs = inorder t @ xs\"\nby (induction t arbitrary: xs) auto\n\n\nsubsection \\<open>Binary Search Tree\\<close>\n\nlemma bst_wrt_mono: \"(\\<And>x y. P x y \\<Longrightarrow> Q x y) \\<Longrightarrow> bst_wrt P t \\<Longrightarrow> bst_wrt Q t\"\nby (induction t) (auto)\n\nlemma bst_wrt_le_if_bst: \"bst t \\<Longrightarrow> bst_wrt (\\<le>) t\"\nusing bst_wrt_mono less_imp_le by blast\n\nlemma bst_wrt_le_iff_sorted: \"bst_wrt (\\<le>) t \\<longleftrightarrow> sorted (inorder t)\"\napply (induction t)\n apply(simp)\nby (fastforce simp: sorted_append intro: less_imp_le less_trans)\n\nlemma bst_iff_sorted_wrt_less: \"bst t \\<longleftrightarrow> sorted_wrt (<) (inorder t)\"\napply (induction t)\n apply simp\napply (fastforce simp: sorted_wrt_append)\ndone\n\n\nsubsection \\<open>\\<^const>\\<open>heap\\<close>\\<close>\n\n\nsubsection \\<open>\\<^const>\\<open>mirror\\<close>\\<close>\n\nlemma mirror_Leaf[simp]: \"mirror t = \\<langle>\\<rangle> \\<longleftrightarrow> t = \\<langle>\\<rangle>\"\nby (induction t) simp_all\n\nlemma Leaf_mirror[simp]: \"\\<langle>\\<rangle> = mirror t \\<longleftrightarrow> t = \\<langle>\\<rangle>\"\nusing mirror_Leaf by fastforce\n\nlemma size_mirror[simp]: \"size(mirror t) = size t\"\nby (induction t) simp_all\n\nlemma size1_mirror[simp]: \"size1(mirror t) = size1 t\"\nby (simp add: size1_size)\n\nlemma height_mirror[simp]: \"height(mirror t) = height t\"\nby (induction t) simp_all\n\nlemma min_height_mirror [simp]: \"min_height (mirror t) = min_height t\"\nby (induction t) simp_all  \n\nlemma ipl_mirror [simp]: \"ipl (mirror t) = ipl t\"\nby (induction t) simp_all\n\nlemma inorder_mirror: \"inorder(mirror t) = rev(inorder t)\"\nby (induction t) simp_all\n\nlemma map_mirror: \"map_search_tree f (mirror t) = mirror (map_search_tree f t)\"\nby (induction t) simp_all\n\nlemma mirror_mirror[simp]: \"mirror(mirror t) = t\"\nby (induction t) simp_all\n\nend\n", "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/Search_Tree.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8376199714402812, "lm_q2_score": 0.8652240825770432, "lm_q1q2_score": 0.7247289713376265}}
{"text": "section \\<open>\\isaheader{Examples from ITP-2010 slides (adopted to ICF v2)}\\<close>\ntheory itp_2010\nimports \n  Collections.Collections \n  Collections.Code_Target_ICF\nbegin\n\ntext \\<open>\n  Illustrates the various possibilities how to use the ICF in your own \n  algorithms by simple examples. The examples all use the data refinement\n  scheme, and either define a generic algorithm or fix the operations.\n\\<close>\n\n\nsubsection \"List to Set\"\ntext \\<open>\n  In this simple example we do conversion from a list to a set.\n  We define an abstract algorithm.\n  This is then refined by a generic algorithm using a locale and by a generic \n  algorithm fixing its operations as parameters.\n\\<close>\n  subsubsection \"Straightforward version\"\n  \\<comment> \\<open>Abstract algorithm\\<close>\n  fun set_a where\n    \"set_a [] s = s\" |\n    \"set_a (a#l) s = set_a l (insert a s)\"\n\n  \\<comment> \\<open>Correctness of aa\\<close>\n  lemma set_a_correct: \"set_a l s = set l \\<union> s\"\n    by (induct l arbitrary: s) auto\n\n  \\<comment> \\<open>Generic algorithm\\<close>\n\n  setup Locale_Code.open_block \\<comment> \\<open>Required to make definitions inside locales\n    executable\\<close>\n  fun (in StdSetDefs) set_i where\n    \"set_i [] s = s\" |\n    \"set_i (a#l) s = set_i l (ins a s)\"\n  setup Locale_Code.close_block\n\n  \\<comment> \\<open>Correct implementation of ca\\<close>\n  lemma (in StdSet) set_i_impl: \"invar s \\<Longrightarrow> invar (set_i l s) \\<and> \\<alpha> (set_i l s) = set_a l (\\<alpha> s)\"\n    by (induct l arbitrary: s) (auto simp add: correct)\n\n  \\<comment> \\<open>Instantiation\\<close>\n  (* We need to declare a constant to make the code generator work *)\n\n  definition \"hs_seti == hs.set_i\"\n  (*declare hs.set_i.simps[folded hs_seti_def, code]*)\n\n  lemmas hs_set_i_impl = hs.set_i_impl[folded hs_seti_def]\n\nexport_code hs_seti checking SML\n\n  \\<comment> \\<open>Code generation\\<close>\n  ML \\<open>@{code hs_seti}\\<close> \n  (*value \"hs_seti [1,2,3::nat] hs_empty\"*)\n\n  subsubsection \"Tail-Recursive version\"\n  \\<comment> \\<open>Abstract algorithm\\<close>\n  fun set_a2 where\n    \"set_a2 [] = {}\" |\n    \"set_a2 (a#l) = (insert a (set_a2 l))\"\n\n  \\<comment> \\<open>Correctness of aa\\<close>\n  lemma set_a2_correct: \"set_a2 l = set l\"\n    by (induct l) auto\n\n  \\<comment> \\<open>Generic algorithm\\<close>\n  setup Locale_Code.open_block\n  fun (in StdSetDefs) set_i2 where\n    \"set_i2 [] = empty ()\" |\n    \"set_i2 (a#l) = (ins a (set_i2 l))\"\n  setup Locale_Code.close_block\n\n  \\<comment> \\<open>Correct implementation of ca\\<close>\n  lemma (in StdSet) set_i2_impl: \"invar s \\<Longrightarrow> invar (set_i2 l) \\<and> \\<alpha> (set_i2 l) = set_a2 l\"\n    by (induct l) (auto simp add: correct)\n\n  \\<comment> \\<open>Instantiation\\<close>\n  definition \"hs_seti2 == hs.set_i2\"\n  (*declare hsr.set_i2.simps[folded hs_seti2_def, code]*)\n\n  lemmas hs_set_i2_impl = hs.set_i2_impl[folded hs_seti2_def]\n\n  \\<comment> \\<open>Code generation\\<close>\n  ML \\<open>@{code hs_seti2}\\<close> \n  (*value \"hs_seti [1,2,3::nat] hs_empty\"*)\n\nsubsubsection \"With explicit operation parameters\"\n\n  \\<comment> \\<open>Alternative for few operation parameters\\<close>\n  fun set_i' where\n    \"!!ins. set_i' ins [] s = s\" |\n    \"!!ins. set_i' ins (a#l) s = set_i' ins l (ins a s)\"\n\n  lemma (in StdSet) set_i'_impl:\n    \"invar s \\<Longrightarrow> invar (set_i' ins l s) \\<and> \\<alpha> (set_i' ins l s) = set_a l (\\<alpha> s)\"\n    by (induct l arbitrary: s) (auto simp add: correct)\n\n  \\<comment> \\<open>Instantiation\\<close>\n  definition \"hs_seti' == set_i' hs.ins\"\n  lemmas hs_set_i'_impl = hs.set_i'_impl[folded hs_seti'_def]\n\n  \\<comment> \\<open>Code generation\\<close>\n  ML \\<open>@{code hs_seti'}\\<close> \n  (*value \"hs_seti' [1,2,3::nat] hs_empty\"*)\n\n\nsubsection \"Filter Average\"\ntext \\<open>\n  In this more complex example, we develop a function that filters from a set all\n  numbers that are above the average of the set.\n \n  First, we formulate this as a generic algorithm using a locale.\n  This solution shows how the ICF v2 overcomes some technical problems that\n  ICF v1 had: \n  \\begin{itemize}\n    \\item Iterators are now polymorphic in the type, even inside locales.\n      Hence, there is no special handling of iterators, as it was required\n      in ICF v1.\n    \\item The Locale-Code package handles code generation for the instantiated\n      locale. There is no need for lengthy boilerplate code as it was required\n      in ICF v1.\n  \\end{itemize}\n\n\n  Another possibility is to fix the used \n  implementations beforehand. Changing the implementation is still easy by\n  changing the used operations. In this example, all used operations are \n  introduced by abbbreviations, localizing the required changes to a small part\n  of the theory. This approach is more powerful, as operations are now \n  polymorphic also in the element type. However, it only allows as single \n  instantiation at a time, which is no option for generic algorithms.\n\\<close>\n\n  abbreviation \"average S == \\<Sum>S div card S\"\n\nsubsubsection \"Generic Algorithm\"\n  locale MyContext =\n    StdSet ops for ops :: \"(nat,'s,'more) set_ops_scheme\"\n  begin\n    definition avg_aux :: \"'s \\<Rightarrow> nat\\<times>nat\" \n      where\n      \"avg_aux s == iterate s (\\<lambda>x (c,s). (c+1, s+x)) (0,0)\"\n\n    definition \"avg s == case avg_aux s of (c,s) \\<Rightarrow> s div c\"\n\n    definition \"filter_le_avg s == let a=avg s in\n      iterate s (\\<lambda>x s. if x\\<le>a then ins x s else s) (empty ())\"\n\n    lemma avg_aux_correct: \"invar s \\<Longrightarrow> avg_aux s = (card (\\<alpha> s), \\<Sum>(\\<alpha> s) )\"\n      apply (unfold avg_aux_def)\n      apply (rule_tac \n        I=\"\\<lambda>it (c,sum). c=card (\\<alpha> s - it) \\<and> sum=\\<Sum>(\\<alpha> s - it)\" \n        in iterate_rule_P)\n      apply auto\n      apply (subgoal_tac \"\\<alpha> s - (it - {x}) = insert x (\\<alpha> s - it)\")\n      apply auto\n      apply (subgoal_tac \"\\<alpha> s - (it - {x}) = insert x (\\<alpha> s - it)\")\n      apply auto\n      done\n\n    lemma avg_correct: \"invar s \\<Longrightarrow> avg s = average (\\<alpha> s)\"\n      unfolding avg_def\n      using avg_aux_correct\n      by auto\n\n    lemma filter_le_avg_correct: \n      \"invar s \\<Longrightarrow> \n        invar (filter_le_avg s) \\<and> \n        \\<alpha> (filter_le_avg s) = {x\\<in>\\<alpha> s. x\\<le>average (\\<alpha> s)}\"\n      unfolding filter_le_avg_def Let_def\n      apply (rule_tac\n        I=\"\\<lambda>it r. invar r \\<and> \\<alpha> r = {x\\<in>\\<alpha> s - it. x\\<le>average (\\<alpha> s)}\"\n        in iterate_rule_P)\n      apply (auto simp add: correct avg_correct)\n      done\n  end\n\n  setup Locale_Code.open_block\n  interpretation hs_ctx: MyContext hs_ops by unfold_locales\n  interpretation rs_ctx: MyContext rs_ops by unfold_locales\n  setup Locale_Code.close_block\n\n  definition \"hs_flt_avg_test \\<equiv> hs.to_list \n    o hs_ctx.filter_le_avg \n    o hs.from_list\"\n  definition \"rs_flt_avg_test \\<equiv> rs.to_list \n    o rs_ctx.filter_le_avg \n    o rs.from_list\"\n\n  \n  text \"Code generation\"\n  ML_val \\<open>\n    if @{code hs_flt_avg_test} (map @{code nat_of_integer} [1,2,3,4,6,7])\n    <> @{code rs_flt_avg_test} (map @{code nat_of_integer} [1,2,3,4,6,7])\n    then error \"Oops\"\n    else ()\n\\<close> \n  \n\nsubsubsection \"Using abbreviations\"\n\n  type_synonym 'a my_set = \"'a hs\"\n  abbreviation \"my_\\<alpha> == hs.\\<alpha>\"\n  abbreviation \"my_invar == hs.invar\"\n  abbreviation \"my_empty == hs.empty\"\n  abbreviation \"my_ins == hs.ins\"\n  abbreviation \"my_iterate == hs.iteratei\"\n  lemmas my_correct = hs.correct\n  lemmas my_iterate_rule_P = hs.iterate_rule_P\n\n  definition avg_aux :: \"nat my_set \\<Rightarrow> nat\\<times>nat\" \n    where\n    \"avg_aux s == my_iterate s (\\<lambda>_. True) (\\<lambda>x (c,s). (c+1, s+x)) (0,0)\"\n\n  definition \"avg s == case avg_aux s of (c,s) \\<Rightarrow> s div c\"\n\n  definition \"filter_le_avg s == let a=avg s in\n    my_iterate s (\\<lambda>_. True) (\\<lambda>x s. if x\\<le>a then my_ins x s else s) (my_empty ())\"\n\n  lemma avg_aux_correct: \"my_invar s \\<Longrightarrow> avg_aux s = (card (my_\\<alpha> s), \\<Sum>(my_\\<alpha> s) )\"\n    apply (unfold avg_aux_def)\n    apply (rule_tac \n      I=\"\\<lambda>it (c,sum). c=card (my_\\<alpha> s - it) \\<and> sum=\\<Sum>(my_\\<alpha> s - it)\" \n      in my_iterate_rule_P)\n    apply auto\n    apply (subgoal_tac \"my_\\<alpha> s - (it - {x}) = insert x (my_\\<alpha> s - it)\")\n    apply auto\n    apply (subgoal_tac \"my_\\<alpha> s - (it - {x}) = insert x (my_\\<alpha> s - it)\")\n    apply auto\n    done\n\n  lemma avg_correct: \"my_invar s \\<Longrightarrow> avg s = average (my_\\<alpha> s)\"\n    unfolding avg_def\n    using avg_aux_correct\n    by auto\n\n  lemma filter_le_avg_correct: \n    \"my_invar s \\<Longrightarrow> \n    my_invar (filter_le_avg s) \\<and> \n    my_\\<alpha> (filter_le_avg s) = {x\\<in>my_\\<alpha> s. x\\<le>average (my_\\<alpha> s)}\"\n    unfolding filter_le_avg_def Let_def\n    apply (rule_tac\n      I=\"\\<lambda>it r. my_invar r \\<and> my_\\<alpha> r = {x\\<in>my_\\<alpha> s - it. x\\<le>average (my_\\<alpha> s)}\"\n      in my_iterate_rule_P)\n    apply (auto simp add: my_correct avg_correct)\n    done\n\n\n  definition \"test_set == my_ins (1::nat) (my_ins 2 (my_ins 3 (my_empty ())))\"\n\n  export_code avg_aux avg filter_le_avg test_set in SML module_name Test\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/Examples/ICF/itp_2010.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8376199673867852, "lm_q2_score": 0.8652240860523328, "lm_q1q2_score": 0.7247289707414161}}
{"text": "theory natDed imports Main\nbegin\ntext{* Regras de Dedu\u00e7\u00e3o Natural no Isabelle. A seta dupla separa\n       premissas da conclus\u00e3o. *}\n\ntext{* Premissas \\<turnstile> Conclus\u00e3o (Premissas \\<Longrightarrow> Conclus\u00e3o) *}\n\nthm conjI (* introdu\u00e7\u00e3o da conjun\u00e7\u00e3o *)\nthm conjunct1 (* elimina\u00e7\u00e3o da conjun\u00e7\u00e3o *)\nthm conjunct2 (* elimina\u00e7\u00e3o da conjun\u00e7\u00e3o *)\nthm disjI1 (* introdu\u00e7\u00e3o da disjun\u00e7\u00e3o *)\nthm disjI2 (* introdu\u00e7\u00e3o da disjun\u00e7\u00e3o *)\nthm disjE (* elimina\u00e7\u00e3o da disjun\u00e7\u00e3o *)\nthm impI (* introdu\u00e7\u00e3o da implica\u00e7\u00e3o *)\nthm mp (* elimina\u00e7\u00e3o da implica\u00e7\u00e3o - modus ponens *)\nthm notI (* introdu\u00e7\u00e3o da nega\u00e7\u00e3o *)\nthm notE (* elimina\u00e7\u00e3o da nega\u00e7\u00e3o *)\nthm FalseE (* elimna\u00e7\u00e3o do Falso - bottom *)\nthm ccontr (* contra-cl\u00e1ssica - redu\u00e7\u00e3o ao absurdo *)\nthm allI (* introdu\u00e7\u00e3o do quantificador universal *)\nthm spec (* elimina\u00e7\u00e3o do quantificador universal *)\nthm allE (* elimina\u00e7\u00e3o do quantificador universal *)\nthm exI (* introdu\u00e7\u00e3o do quantificador existencial *)\nthm exE (* elimina\u00e7\u00e3o do quantificador existencial *)\nthm refl (* introdu\u00e7\u00e3o da igualdade - reflexividade *)\nthm subst (* elimina\u00e7\u00e3o da igualdade *)\nthm ssubst (* elimina\u00e7\u00e3o da igualdade *)\nthm sym (* simetria da igualdade *)\nthm trans (* transitividade da igualdade *)\n\ntext{* Hello World *}\n\ntheorem helloisar01:\nassumes prem: \"A \\<and> B\"\nshows \"B \\<and> A\"\n  proof -\n    from prem have d: \"A\" by (rule conjunct1)\n    from prem have    \"B\" by (rule conjunct2)\n    from this and d show \"B \\<and> A\" by (rule conjI)\n  qed\n\ntheorem helloisar02:\nassumes prem: \"A \\<and> B\"\nshows \"B \\<and> A\"\n  proof (rule conjI)\n    from prem show \"B\" by (rule conjunct2)\n    from prem show \"A\" by (rule conjunct1) \n  qed\n\ntext{* Exerc\u00edcio 1 *}\n\ntheorem ex1:\nassumes prem: \"(\\<forall>x. F x) \\<or> (\\<forall>x. G x)\"\nshows \"\\<forall>x. F x \\<or> G x\"\n  proof (rule allI) (* \\<forall>I *)\n    fix x0 (* hyp *)\n    show \"F x0 \\<or> G x0\"\n      proof (rule disjE[OF prem]) (* \\<or>E *)\n        assume h1: \"\\<forall>x. F x\"\n          from h1 have \"F x0\" by (rule spec) (* \\<forall>E *)\n          from this show \"F x0 \\<or> G x0\" by (rule disjI1) (* \\<or>I1 *)\n        next\n        assume h1: \"\\<forall>x. G x\"\n          from h1 have \"G x0\" by (rule spec) (* \\<forall>E *)\n          from this show \"F x0 \\<or> G x0\" by (rule disjI2) (* \\<or>I2 *)\n      qed\n  qed\n\ntext{* Exerc\u00edcio 2 *}\ntext{* Exerc\u00edcio 3 *}\ntext{* Exerc\u00edcio 4 *}\ntext{* Exerc\u00edcio 5 *}\n\nend\n", "meta": {"author": "taschetto", "repo": "formalMethods", "sha": "58a1eef1326ad463d8893d8604d7f246d64bf5ae", "save_path": "github-repos/isabelle/taschetto-formalMethods", "path": "github-repos/isabelle/taschetto-formalMethods/formalMethods-58a1eef1326ad463d8893d8604d7f246d64bf5ae/natDed.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.865224072151174, "lm_q2_score": 0.8376199572530448, "lm_q1q2_score": 0.7247289503295717}}
{"text": "section\\<open>Antichains\\<close>\n\n(*<*)\ntheory Antichain\n  imports\n    Auxiliary\nbegin\n(*>*)\n\ndefinition incomparable where\n  \"incomparable A = (\\<forall>x \\<in> A. \\<forall>y \\<in> A. x \\<noteq> y \\<longrightarrow> \\<not> x < y \\<and> \\<not> y < x)\"\n\nlemma incomparable_empty[simp, intro]: \"incomparable {}\"\n  unfolding incomparable_def by auto\n\ntypedef (overloaded) 'a :: order antichain =\n  \"{A :: 'a set. finite A \\<and> incomparable A}\"\n  morphisms set_antichain antichain\n  by auto\n\nsetup_lifting type_definition_antichain\n\nlift_definition member_antichain :: \"'a :: order \\<Rightarrow> 'a antichain \\<Rightarrow> bool\" (\"(_/ \\<in>\\<^sub>A _)\" [51, 51] 50) is \"Set.member\" .\n\nabbreviation not_member_antichain :: \"'a :: order \\<Rightarrow> 'a antichain \\<Rightarrow> bool\" (\"(_/ \\<notin>\\<^sub>A _)\" [51, 51] 50) where\n  \"x \\<notin>\\<^sub>A A \\<equiv> \\<not> x \\<in>\\<^sub>A A\"\n\nlift_definition empty_antichain :: \"'a :: order antichain\" (\"{}\\<^sub>A\") is \"{}\" by simp\n\nlemma mem_antichain_nonempty[simp]: \"s \\<in>\\<^sub>A A \\<Longrightarrow> A \\<noteq> {}\\<^sub>A\"\n  by transfer auto\n\ndefinition \"minimal_antichain A = {x \\<in> A. \\<not>(\\<exists>y \\<in> A. y < x)}\"\n\nlemma in_minimal_antichain: \"x \\<in> minimal_antichain A \\<longleftrightarrow> x \\<in> A \\<and> \\<not>(\\<exists>y \\<in> A. y < x)\"\n  unfolding minimal_antichain_def by auto\n\nlemma in_antichain_minimal_antichain[simp]: \"finite M \\<Longrightarrow> x \\<in>\\<^sub>A antichain (minimal_antichain M) \\<longleftrightarrow> x \\<in> minimal_antichain M\"\n  apply (clarsimp simp: minimal_antichain_def member_antichain.rep_eq)\n  apply (intro conjI iffI)\n    apply (subst (asm) antichain_inverse)\n     apply (simp add: incomparable_def)\n    apply simp\n   apply (subst (asm) antichain_inverse)\n    apply (simp add: incomparable_def)\n   apply simp\n  apply (subst antichain_inverse)\n   apply (simp add: incomparable_def)\n  apply simp\n  done\n\nlemma incomparable_minimal_antichain[simp]: \"incomparable (minimal_antichain A)\"\n  unfolding incomparable_def minimal_antichain_def\n  by auto\n\nlemma finite_minimal_antichain[simp]: \"finite A \\<Longrightarrow> finite (minimal_antichain A)\"\n  unfolding minimal_antichain_def by auto\n\nlemma finite_set_antichain[simp, intro]: \"finite (set_antichain A)\"\n  by transfer auto\n\nlemma minimal_antichain_subset: \"minimal_antichain A \\<subseteq> A\"\n  unfolding minimal_antichain_def by auto\n\nlift_definition frontier :: \"'t :: order zmultiset \\<Rightarrow> 't antichain\" is\n  \"\\<lambda>M. minimal_antichain {t. zcount M t > 0}\"\n  by (auto simp: finite_subset[OF minimal_antichain_subset finite_zcount_pos])\n\nlemma member_frontier_pos_zmset: \"t \\<in>\\<^sub>A frontier M \\<Longrightarrow> 0 < zcount M t\"\n  by (simp add: frontier_def in_minimal_antichain)\n\nlemma frontier_comparable_False[simp]: \"x \\<in>\\<^sub>A frontier M \\<Longrightarrow> y \\<in>\\<^sub>A frontier M \\<Longrightarrow> x < y \\<Longrightarrow> False\"\n  by transfer (auto simp: minimal_antichain_def)\n\nlemma minimal_antichain_idempotent[simp]: \"minimal_antichain (minimal_antichain A) = minimal_antichain A\"\n  by (auto simp: minimal_antichain_def)\n\ninstantiation antichain :: (order) minus begin\nlift_definition minus_antichain :: \"'a antichain \\<Rightarrow> 'a antichain \\<Rightarrow> 'a antichain\" is \"(-)\"\n  by (auto simp: incomparable_def)\ninstance ..\nend\n\ninstantiation antichain :: (order) plus begin\nlift_definition plus_antichain :: \"'a antichain \\<Rightarrow> 'a antichain \\<Rightarrow> 'a antichain\" is \"\\<lambda>M N. minimal_antichain (M \\<union> N)\"\n  by (auto simp: incomparable_def minimal_antichain_def)\ninstance ..\nend\n\nlemma antichain_add_commute: \"(M :: 'a :: order antichain) + N = N + M\"\n  by transfer (auto simp: incomparable_def sup_commute)\n\n\nlift_definition filter_antichain :: \"('a :: order \\<Rightarrow> bool) \\<Rightarrow> 'a antichain \\<Rightarrow> 'a antichain\" is \"Set.filter\"\n  by (auto simp: incomparable_def)\n\nsyntax (ASCII)\n  \"_ACCollect\" :: \"pttrn \\<Rightarrow> 'a :: order antichain \\<Rightarrow> bool \\<Rightarrow> 'a antichain\" (\"(1{_ :\\<^sub>A _./ _})\")\nsyntax\n  \"_ACCollect\" :: \"pttrn \\<Rightarrow> 'a :: order antichain \\<Rightarrow> bool \\<Rightarrow> 'a antichain\" (\"(1{_ \\<in>\\<^sub>A _./ _})\")\ntranslations\n  \"{x \\<in>\\<^sub>A M. P}\" == \"CONST filter_antichain (\\<lambda>x. P) M\"\n\n\ndeclare empty_antichain.rep_eq[simp]\n\nlemma minimal_antichain_empty[simp]: \"minimal_antichain {} = {}\"\n  by (simp add: minimal_antichain_def)\n\nlemma minimal_antichain_singleton[simp]: \"minimal_antichain {x::_ ::order} = {x}\"\n  by (auto simp: minimal_antichain_def)\n\nlemma minimal_antichain_nonempty:\n  \"finite A \\<Longrightarrow> (t::_::order) \\<in> A \\<Longrightarrow> minimal_antichain A \\<noteq> {}\"\n  by (auto simp: minimal_antichain_def dest: order_finite_set_exists_foundation[of _ t])\n\nlemma minimal_antichain_member:\n  \"finite A \\<Longrightarrow> (t::_::order) \\<in> A \\<Longrightarrow> \\<exists>t'. t' \\<in> minimal_antichain A \\<and> t' \\<le> t\"\n  by (auto simp: minimal_antichain_def dest: order_finite_set_exists_foundation[of _ t])\n\nlemma minimal_antichain_union: \"minimal_antichain ((A::(_ :: order) set) \\<union> B) \\<subseteq> minimal_antichain (minimal_antichain A \\<union> minimal_antichain B)\"\n  by (auto simp: minimal_antichain_def)\n\nlemma ac_Diff_iff: \"c \\<in>\\<^sub>A A - B \\<longleftrightarrow> c \\<in>\\<^sub>A A \\<and> c \\<notin>\\<^sub>A B\"\n  by transfer simp\n\nlemma ac_DiffD2: \"c \\<in>\\<^sub>A A - B \\<Longrightarrow> c \\<in>\\<^sub>A B \\<Longrightarrow> P\"\n  by transfer simp\n\nlemma ac_notin_Diff: \"\\<not> x \\<in>\\<^sub>A A - B \\<Longrightarrow> \\<not> x \\<in>\\<^sub>A A \\<or> x \\<in>\\<^sub>A B\"\n  by transfer simp\n\nlemma ac_eq_iff: \"A = B \\<longleftrightarrow> (\\<forall>x. x \\<in>\\<^sub>A A \\<longleftrightarrow> x \\<in>\\<^sub>A B)\"\n  by transfer auto\n\nlemma antichain_obtain_foundation:\n  assumes   \"t \\<in>\\<^sub>A M\"\n  obtains s where \"s \\<in>\\<^sub>A M \\<and> s \\<le> t \\<and> (\\<forall>u. u\\<in>\\<^sub>AM \\<longrightarrow> \\<not> u < s)\"\n  using assms unfolding member_antichain.rep_eq\n  by - (rule order_finite_set_obtain_foundation[of \"set_antichain M\" t]; auto)\n\nlemma set_antichain1[simp]: \"x \\<in> set_antichain X \\<Longrightarrow> x \\<in>\\<^sub>A X\"\n  by transfer simp\n\nlemma set_antichain2[simp]: \"x \\<in>\\<^sub>A X \\<Longrightarrow> x \\<in> set_antichain X\"\n  by transfer simp\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/Progress_Tracking/Antichain.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8740772384450968, "lm_q2_score": 0.8289388125473628, "lm_q1q2_score": 0.7245565481113566}}
{"text": "theory Pascal_Property\n  imports Main Projective_Plane_Axioms Pappus_Property\nbegin\n\n(* Author: Anthony Bordg, University of Cambridge, apdb3@cam.ac.uk .*)\n\ntext \\<open>\nContents:\n\\<^item> A hexagon is pascal if its three opposite sides meet in collinear points [is_pascal].\n\\<^item> A plane is pascal, or has Pascal's property, if for every hexagon of that plane\nPascal property is stable under any permutation of that hexagon. \n\\<close>\n\nsection \\<open>Pascal's Property\\<close>\n\ndefinition inters :: \"Lines \\<Rightarrow> Lines \\<Rightarrow> Points set\" where\n\"inters l m \\<equiv> {P. incid P l \\<and> incid P m}\"\n\nlemma inters_is_singleton:\n  assumes \"l \\<noteq> m\" and \"P \\<in> inters l m\" and \"Q \\<in> inters l m\"\n  shows \"P = Q\"\n  using assms ax_uniqueness inters_def \n  by blast\n\ndefinition inter :: \"Lines \\<Rightarrow> Lines \\<Rightarrow> Points\" where\n\"inter l m \\<equiv> @P. P \\<in> inters l m\"\n\nlemma uniq_inter:\n  assumes \"l \\<noteq> m\" and \"incid P l\" and \"incid P m\"\n  shows \"inter l m = P\"\nproof -\n  have \"P \\<in> inters l m\"\n    by (simp add: assms(2) assms(3) inters_def)\n  have \"\\<forall>Q. Q \\<in> inters l m \\<longrightarrow> Q = P\"\n    using \\<open>P \\<in> inters l m\\<close> assms(1) inters_is_singleton \n    by blast\n  show \"inter l m = P\"\n    using \\<open>P \\<in> inters l m\\<close> assms(1) inter_def inters_is_singleton \n    by auto\nqed\n\n(* The configuration of a hexagon where the three pairs of opposite sides meet in \ncollinear points *)\ndefinition is_pascal :: \"[Points, Points, Points, Points, Points, Points] \\<Rightarrow> bool\" where\n\"is_pascal A B C D E F \\<equiv> distinct6 A B C D E F \\<longrightarrow> line B C \\<noteq> line E F \\<longrightarrow> line C D \\<noteq> line A F\n\\<longrightarrow> line A B \\<noteq> line D E \\<longrightarrow> \n(let P = inter (line B C) (line E F) in\nlet Q = inter (line C D) (line A F) in\nlet R = inter (line A B) (line D E) in \ncol P Q R)\"\n\nlemma col_rot_CW:\n  assumes \"col P Q R\"\n  shows \"col R P Q\"\n  using assms col_def \n  by auto\n\nlemma col_2cycle: \n  assumes \"col P Q R\"\n  shows \"col P R Q\"\n  using assms col_def \n  by auto\n\nlemma distinct6_rot_CW:\n  assumes \"distinct6 A B C D E F\"\n  shows \"distinct6 F A B C D E\"\n  using assms distinct6_def \n  by auto\n\nlemma lines_comm: \"lines P Q = lines Q P\"\n  using lines_def \n  by auto\n\nlemma line_comm:\n  assumes \"P \\<noteq> Q\"\n  shows \"line P Q = line Q P\"\n  by (metis ax_uniqueness incidA_lAB incidB_lAB)\n  \nlemma inters_comm: \"inters l m = inters m l\"\n  using inters_def \n  by auto\n\nlemma inter_comm: \"inter l m = inter m l\"\n  by (simp add: inter_def inters_comm)\n\nlemma inter_line_line_comm:\n  assumes \"C \\<noteq> D\"\n  shows \"inter (line A B) (line C D) = inter (line A B) (line D C)\"\n  using assms line_comm \n  by auto\n\nlemma inter_line_comm_line:\n  assumes \"A \\<noteq> B\"\n  shows \"inter (line A B) (line C D) = inter (line B A) (line C D)\"\n  using assms line_comm \n  by auto\n\nlemma inter_comm_line_line_comm:\n  assumes \"C \\<noteq> D\" and \"line A B \\<noteq> line C D\"\n  shows \"inter (line A B) (line C D) = inter (line D C) (line A B)\"\n  by (metis inter_comm line_comm)\n\n(* Pascal's property is stable under the 6-cycle [A B C D E F] *)\nlemma is_pascal_rot_CW:\n  assumes \"is_pascal A B C D E F\"\n  shows \"is_pascal F A B C D E\"\nproof -\n  define P Q R where \"P = inter (line A B) (line D E)\" and \"Q = inter (line B C) (line E F)\" and\n    \"R = inter (line F A) (line C D)\"\n  have \"col P Q R\" if \"distinct6 F A B C D E\" and \"line A B \\<noteq> line D E\" and \"line B C \\<noteq> line E F\" \n    and \"line F A \\<noteq> line C D\"\n    using P_def Q_def R_def assms col_rot_CW distinct6_def inter_comm is_pascal_def line_comm \n      that(1) that(2) that(3) that(4) \n    by auto\n  then show \"is_pascal F A B C D E\"\n    by (metis P_def Q_def R_def is_pascal_def line_comm)\nqed\n\n(* We recall that the group of permutations S_6 is generated by the 2-cycle [1 2]\nand the 6-cycle [1 2 3 4 5 6] *)\n\n(* Assuming Pappus's property, Pascal's property is stable under the 2-cycle [A B] *)\n\nlemma incid_C_AB: \n  assumes \"A \\<noteq> B\" and \"incid A l\" and \"incid B l\" and \"incid C l\"\n  shows \"incid C (line A B)\"\n  using assms ax_uniqueness incidA_lAB incidB_lAB \n  by blast\n\nlemma incid_inters_left: \n  assumes \"P \\<in> inters l m\"\n  shows \"incid P l\"\n  using assms inters_def \n  by auto\n\nlemma incid_inters_right:\n  assumes \"P \\<in> inters l m\"\n  shows \"incid P m\"\n  using assms incid_inters_left inters_comm \n  by blast\n\nlemma inter_in_inters: \"inter l m \\<in> inters l m\"\nproof -\n  have \"\\<exists>P. P \\<in> inters l m\"\n    using inters_def ax2 \n    by auto\n  show \"inter l m \\<in> inters l m\"\n    by (metis \\<open>\\<exists>P. P \\<in> inters l m\\<close> inter_def some_eq_ex)\nqed\n\nlemma incid_inter_left: \"incid (inter l m) l\"\n  using incid_inters_left inter_in_inters \n  by blast\n\nlemma incid_inter_right: \"incid (inter l m) m\"\n  using incid_inter_left inter_comm \n  by fastforce\n\nlemma col_A_B_ABl: \"col A B (inter (line A B) l)\"\n  using col_def incidA_lAB incidB_lAB incid_inter_left \n  by blast\n\nlemma col_A_B_lAB: \"col A B (inter l (line A B))\"\n  using col_A_B_ABl inter_comm \n  by auto\n\nlemma inter_is_a_intersec: \"is_a_intersec (inter (line A B) (line C D)) A B C D\"\n  by (simp add: col_A_B_ABl col_A_B_lAB col_rot_CW is_a_intersec_def)\n\ndefinition line_ext :: \"Lines \\<Rightarrow> Points set\" where\n\"line_ext l \\<equiv> {P. incid P l}\"\n\nlemma line_left_inter_1: \n  assumes \"P \\<in> line_ext l\" and \"P \\<notin> line_ext m\"\n  shows \"line (inter l m) P = l\"\n  by (metis CollectD CollectI assms(1) assms(2) incidA_lAB incidB_lAB incid_inter_left \n      incid_inter_right line_ext_def uniq_inter)\n\nlemma line_left_inter_2:\n  assumes \"P \\<in> line_ext m\" and \"P \\<notin> line_ext l\"\n  shows \"line (inter l m) P = m\"\n  using assms inter_comm line_left_inter_1 \n  by fastforce\n\nlemma line_right_inter_1:\n  assumes \"P \\<in> line_ext l\" and \"P \\<notin> line_ext m\"\n  shows \"line P (inter l m) = l\"\n  by (metis assms line_comm line_left_inter_1)\n\nlemma line_right_inter_2:\n  assumes \"P \\<in> line_ext m\" and \"P \\<notin> line_ext l\"\n  shows \"line P (inter l m) = m\"\n  by (metis assms inter_comm line_comm line_left_inter_1)\n\nlemma inter_ABC_1: \n  assumes \"line A B \\<noteq> line C A\"\n  shows \"inter (line A B) (line C A) = A\"\n  using assms ax_uniqueness incidA_lAB incidB_lAB incid_inter_left incid_inter_right \n  by blast\n\nlemma line_inter_2:\n  assumes \"inter l m \\<noteq> inter l' m\" \n  shows \"line (inter l m) (inter l' m) = m\"\n  using assms ax_uniqueness incidA_lAB incidB_lAB incid_inter_right \n  by blast\n\nlemma col_line_ext_1:\n  assumes \"col A B C\" and \"A \\<noteq> C\"\n  shows \"B \\<in> line_ext (line A C)\"\n  by (metis CollectI assms ax_uniqueness col_def incidA_lAB incidB_lAB line_ext_def)\n\nlemma inter_line_ext_1:\n  assumes \"inter l m \\<in> line_ext n\" and \"l \\<noteq> m\" and \"l \\<noteq> n\"\n  shows \"inter l m = inter l n\"\n  using assms(1) assms(3) ax_uniqueness incid_inter_left incid_inter_right line_ext_def \n  by blast\n\nlemma inter_line_ext_2:\n  assumes \"inter l m \\<in> line_ext n\" and \"l \\<noteq> m\" and \"m \\<noteq> n\"\n  shows \"inter l m = inter m n\"\n  by (metis assms inter_comm inter_line_ext_1)\n\ndefinition pascal_prop :: \"bool\" where\n\"pascal_prop \\<equiv> \\<forall>A B C D E F. is_pascal A B C D E F \\<longrightarrow> is_pascal B A C D E F\"\n\nlemma pappus_pascal:\n  assumes \"is_pappus\"\n  shows \"pascal_prop\"\nproof-\n  have \"is_pascal B A C D E F\" if \"is_pascal A B C D E F\" for A B C D E F\n  proof-\n    define X Y Z where \"X = inter (line A C) (line E F)\" and \"Y = inter (line C D) (line B F)\"\n      and \"Z = inter (line B A) (line D E)\" \n    have \"col X Y Z\" if \"distinct6 B A C D E F\" and \"line A C \\<noteq> line E F\" and \"line C D \\<noteq> line B F\" \n      and \"line B A \\<noteq> line D E\" and \"line B C = line E F\"\n      by (smt X_def Y_def ax_uniqueness col_ABA col_rot_CW distinct6_def incidB_lAB incid_inter_left \n          incid_inter_right line_comm that(1) that(2) that(3) that(5))\n    have \"col X Y Z\" if \"distinct6 B A C D E F\" and \"line A C \\<noteq> line E F\" and \"line C D \\<noteq> line B F\" \n      and \"line B A \\<noteq> line D E\" and \"line C D = line A F\"\n      by (metis X_def Y_def col_ABA col_rot_CW distinct6_def inter_ABC_1 line_comm that(1) that(2) \n          that(3) that(5))\n    have \"col X Y Z\" if \"distinct6 B A C D E F\" and \"line A C \\<noteq> line E F\" and \"line C D \\<noteq> line B F\" \n      and \"line B A \\<noteq> line D E\" and \"line B C \\<noteq> line E F\" and \"line C D \\<noteq> line A F\"\n    proof-\n      define W where \"W = inter (line A C) (line E F)\"\n      have \"col A C W\"\n        by (simp add: col_A_B_ABl W_def)\n      define P Q R where \"P = inter (line B C) (line E F)\"\n        and \"Q = inter (line A B) (line D E)\"\n        and \"R = inter (line C D) (line A F)\"\n      have \"col P Q R\"\n        using P_def Q_def R_def \\<open>is_pascal A B C D E F\\<close> col_2cycle distinct6_def is_pascal_def \n          line_comm that(1) that(4) that(5) that(6) \n        by auto\n          (* Below we take care of a few degenerate cases *)\n      have \"col X Y Z\" if \"P = Q\"\n        by (smt P_def Q_def X_def Y_def Z_def \\<open>distinct6 B A C D E F\\<close> ax_uniqueness col_ABA col_def \n            distinct6_def incidA_lAB incidB_lAB incid_inter_left inter_comm that)\n      have \"col X Y Z\" if \"P = R\"\n        by (smt P_def R_def X_def Y_def Z_def \\<open>distinct6 B A C D E F\\<close> \\<open>line A C \\<noteq> line E F\\<close> \n            \\<open>line C D \\<noteq> line B F\\<close> col_2cycle col_A_B_ABl col_rot_CW distinct6_def incidA_lAB \n            incidB_lAB incid_inter_left incid_inter_right that uniq_inter)\n      have \"col X Y Z\" if \"P = A\"\n        by (smt P_def Q_def R_def X_def Y_def Z_def \\<open>P = Q \\<Longrightarrow> col X Y Z\\<close> \\<open>P = R \\<Longrightarrow> col X Y Z\\<close> \n            \\<open>col P Q R\\<close> \\<open>line B C \\<noteq> line E F\\<close> ax_uniqueness col_def incidA_lAB incid_inter_left \n            incid_inter_right line_comm that)\n      have \"col X Y Z\" if \"P = C\"\n        by (smt P_def Q_def R_def X_def Y_def Z_def \\<open>P = R \\<Longrightarrow> col X Y Z\\<close> \\<open>col P Q R\\<close> \n            \\<open>line A C \\<noteq> line E F\\<close> ax_uniqueness col_def incidA_lAB incid_inter_left \n            incid_inter_right line_comm that)\n      have \"col X Y Z\" if \"P = W\"\n        by (smt P_def Q_def R_def W_def X_def Y_def Z_def \\<open>P = C \\<Longrightarrow> col X Y Z\\<close> \\<open>P = Q \\<Longrightarrow> col X Y Z\\<close> \n            \\<open>col P Q R\\<close> \\<open>distinct6 B A C D E F\\<close> ax_uniqueness col_def distinct6_def incidB_lAB \n            incid_inter_left incid_inter_right line_comm that) \n      have \"col X Y Z\" if \"Q = R\"\n        by (smt Q_def R_def X_def Y_def Z_def \\<open>distinct6 B A C D E F\\<close> ax_uniqueness col_A_B_lAB \n            col_rot_CW distinct6_def incidB_lAB incid_inter_right inter_comm line_comm that)\n      have \"col X Y Z\" if \"Q = A\"\n        by (smt P_def Q_def R_def X_def Y_def Z_def \\<open>col P Q R\\<close> \\<open>distinct6 B A C D E F\\<close> \n            \\<open>line C D \\<noteq> line B F\\<close> ax_uniqueness col_ABA col_def distinct6_def incidA_lAB incidB_lAB \n            incid_inter_left incid_inter_right that)\n      have \"col X Y Z\" if \"Q = C\"\n        by (metis P_def Q_def W_def \\<open>P = W \\<Longrightarrow> col X Y Z\\<close> \\<open>distinct6 B A C D E F\\<close> ax_uniqueness \n            distinct6_def incidA_lAB incid_inter_left line_comm that)\n      have \"col X Y Z\" if \"Q = W\"\n        by (metis Q_def W_def X_def Z_def col_ABA line_comm that)\n      have \"col X Y Z\" if \"R = A\"\n        by (smt P_def Q_def R_def W_def X_def Y_def \\<open>P = W \\<Longrightarrow> col X Y Z\\<close> \\<open>Q = A \\<Longrightarrow> col X Y Z\\<close> \n            \\<open>col P Q R\\<close> \\<open>distinct6 B A C D E F\\<close> ax_uniqueness col_ABA col_def col_rot_CW distinct6_def \n            incidA_lAB incidB_lAB incid_inter_right inter_comm that)\n      have \"col X Y Z\" if \"R = C\"\n        by (smt P_def Q_def R_def X_def Y_def Z_def \\<open>col P Q R\\<close> \\<open>distinct6 B A C D E F\\<close> \n            \\<open>line A C \\<noteq> line E F\\<close> ax_uniqueness col_def distinct6_def incidA_lAB incidB_lAB \n            incid_inter_left inter_comm that)\n      have \"col X Y Z\" if \"R = W\"\n        by (metis R_def W_def \\<open>R = A \\<Longrightarrow> col X Y Z\\<close> \\<open>R = C \\<Longrightarrow> col X Y Z\\<close> \\<open>line C D \\<noteq> line A F\\<close> \n            ax_uniqueness incidA_lAB incidB_lAB incid_inter_left incid_inter_right that)\n      have \"col X Y Z\" if \"A = W\"\n        by (smt P_def Q_def R_def W_def X_def Y_def Z_def \\<open>P = R \\<Longrightarrow> col X Y Z\\<close> \\<open>Q = A \\<Longrightarrow> col X Y Z\\<close> \n            \\<open>col P Q R\\<close> \\<open>distinct6 B A C D E F\\<close> ax_uniqueness col_def distinct6_def incidA_lAB \n            incidB_lAB incid_inter_left incid_inter_right that)\n      have \"col X Y Z\" if \"C = W\"\n        by (metis P_def W_def \\<open>P = C \\<Longrightarrow> col X Y Z\\<close> \\<open>line B C \\<noteq> line E F\\<close> ax_uniqueness incidB_lAB \n            incid_inter_left incid_inter_right that)\n      have f1:\"col (inter (line P C) (line A Q)) (inter (line Q W) (line C R)) \n      (inter (line P W) (line A R))\" if \"distinct6 P Q R A C W\"\n        using assms(1) is_pappus_def is_pappus2_def \\<open>distinct6 P Q R A C W\\<close> \\<open>col P Q R\\<close>\n          \\<open>col A C W\\<close> inter_is_a_intersec inter_line_line_comm \n        by metis\n      have \"col X Y Z\" if \"C \\<in> line_ext (line E F)\"\n        using P_def \\<open>P = C \\<Longrightarrow> col X Y Z\\<close> \\<open>line B C \\<noteq> line E F\\<close> incidB_lAB line_ext_def that uniq_inter \n        by auto \n      have \"col X Y Z\" if \"A \\<in> line_ext (line D E)\"\n        by (metis Q_def \\<open>Q = A \\<Longrightarrow> col X Y Z\\<close> \\<open>line B A \\<noteq> line D E\\<close> ax_uniqueness incidA_lAB \n            incid_inter_left incid_inter_right line_comm line_ext_def mem_Collect_eq that)\n      have \"col X Y Z\" if \"line B C = line A B\"\n        by (metis P_def W_def \\<open>P = W \\<Longrightarrow> col X Y Z\\<close> \\<open>distinct6 B A C D E F\\<close> ax_uniqueness \n            distinct6_def incidA_lAB incidB_lAB that)\n          (* We can resume our proof with the non-degenerate case *)\n      have f2:\"inter (line P C) (line A Q) = B\" if\n        \"C \\<notin> line_ext (line E F)\" and \"A \\<notin> line_ext (line D E)\" and \"line B C \\<noteq> line A B\"\n        by (smt CollectI P_def Q_def ax_uniqueness incidA_lAB incidB_lAB incid_inter_left \n            incid_inter_right line_ext_def that(1) that(2) that(3))\n          (* Again, we need to take care of a few particular cases *)\n      have \"col X Y Z\" if \"line E F = line A F\"\n        by (metis W_def \\<open>A = W \\<Longrightarrow> col X Y Z\\<close> \\<open>line A C \\<noteq> line E F\\<close> inter_ABC_1 inter_comm that)\n      have \"col X Y Z\" if \"A \\<in> line_ext (line C D)\"\n        using R_def \\<open>R = A \\<Longrightarrow> col X Y Z\\<close> \\<open>line C D \\<noteq> line A F\\<close> ax_uniqueness incidA_lAB \n          incid_inter_left incid_inter_right line_ext_def that \n        by blast \n      have \"col X Y Z\" if \"inter (line B C) (line E F) = inter (line A C) (line E F)\"\n        by (simp add: P_def W_def \\<open>P = W \\<Longrightarrow> col X Y Z\\<close> that)\n          (* We resume the general case *)\n      have f3:\"inter (line P W) (line A R) = F\" if \"line E F \\<noteq> line A F\" and \"A \\<notin> line_ext (line C D)\"\n        and \"inter (line B C) (line E F) \\<noteq> inter (line A C) (line E F)\"\n        by (smt CollectI P_def R_def W_def ax_uniqueness incidA_lAB incidB_lAB incid_inter_left \n            incid_inter_right line_ext_def that(1) that(2) that(3))\n          (* Once again, first we need to handle a particular case, namely C \\<in> AF, then \n            we resume the general case *)\n      have \"col X Y Z\" if \"C \\<in> line_ext (line A F)\"\n        using R_def \\<open>R = C \\<Longrightarrow> col X Y Z\\<close> \\<open>line C D \\<noteq> line A F\\<close> ax_uniqueness incidA_lAB \n          incid_inter_left incid_inter_right line_ext_def that \n        by blast\n      have f4:\"inter (line Q W) (line C R) = inter (line Q W) (line C D)\" if \"C \\<notin> line_ext (line A F)\"\n        using R_def incidA_lAB line_ext_def line_right_inter_1 that \n        by auto\n      then have \"inter (line Q W) (line C D) \\<in> line_ext (line B F)\" if \"distinct6 P Q R A C W\"\n        and  \"C \\<notin> line_ext (line E F)\" and \"A \\<notin> line_ext (line D E)\" and \"line B C \\<noteq> line A B\"\n        and \"line E F \\<noteq> line A F\" and \"A \\<notin> line_ext (line C D)\"\n        and \"inter (line B C) (line E F) \\<noteq> inter (line A C) (line E F)\"\n        by (smt R_def \\<open>distinct6 B A C D E F\\<close> ax_uniqueness col_line_ext_1 distinct6_def f1 f2 f3 \n            incidA_lAB incidB_lAB incid_inter_left that(1) that(2) that(3) that(5) that(6) that(7))\n      then have \"inter (line Q W) (line C D) = inter (line C D) (line B F)\" if \"distinct6 P Q R A C W\"\n        and  \"C \\<notin> line_ext (line E F)\" and \"A \\<notin> line_ext (line D E)\" and \"line B C \\<noteq> line A B\"\n        and \"line E F \\<noteq> line A F\" and \"A \\<notin> line_ext (line C D)\"\n        and \"inter (line B C) (line E F) \\<noteq> inter (line A C) (line E F)\"\n        by (smt W_def \\<open>distinct6 B A C D E F\\<close> \\<open>line C D \\<noteq> line B F\\<close> ax_uniqueness distinct6_def f2 \n            incidA_lAB incidB_lAB incid_inter_left incid_inter_right inter_line_ext_2 that(1) that(2) \n            that(3) that(5) that(6) that(7))\n      moreover have \"inter (line C D) (line B F) \\<in> line_ext (line Q W)\" if \"distinct6 P Q R A C W\"\n        and  \"C \\<notin> line_ext (line E F)\" and \"A \\<notin> line_ext (line D E)\" and \"line B C \\<noteq> line A B\"\n        and \"line E F \\<noteq> line A F\" and \"A \\<notin> line_ext (line C D)\"\n        and \"inter (line B C) (line E F) \\<noteq> inter (line A C) (line E F)\"\n        by (metis calculation col_2cycle col_A_B_ABl col_line_ext_1 distinct6_def that(1) that(2) \n            that(3) that(4) that(5) that(6) that(7))\n      ultimately have \"col (inter (line A C) (line E F)) (inter (line C D) (line B F))\n      (inter (line A B) (line D E))\" if \"distinct6 P Q R A C W\"\n        and  \"C \\<notin> line_ext (line E F)\" and \"A \\<notin> line_ext (line D E)\" and \"line B C \\<noteq> line A B\"\n        and \"line E F \\<noteq> line A F\" and \"A \\<notin> line_ext (line C D)\"\n        and \"inter (line B C) (line E F) \\<noteq> inter (line A C) (line E F)\"\n        by (metis Q_def W_def col_A_B_ABl col_rot_CW that(1) that(2) that(3) that(4) that(5) that(6) \n            that(7))\n      show \"col X Y Z\"\n        by (metis P_def W_def X_def Y_def Z_def \\<open>A = W \\<Longrightarrow> col X Y Z\\<close> \\<open>A \\<in> line_ext (line C D) \\<Longrightarrow> col X Y Z\\<close> \n            \\<open>A \\<in> line_ext (line D E) \\<Longrightarrow> col X Y Z\\<close> \\<open>C = W \\<Longrightarrow> col X Y Z\\<close> \\<open>C \\<in> line_ext (line E F) \\<Longrightarrow> col X Y Z\\<close> \n            \\<open>P = A \\<Longrightarrow> col X Y Z\\<close> \\<open>P = C \\<Longrightarrow> col X Y Z\\<close> \\<open>P = Q \\<Longrightarrow> col X Y Z\\<close> \\<open>P = R \\<Longrightarrow> col X Y Z\\<close> \n            \\<open>Pascal_Property.inter (line B C) (line E F) = Pascal_Property.inter (line A C) (line E F) \\<Longrightarrow> col X Y Z\\<close> \n            \\<open>Q = A \\<Longrightarrow> col X Y Z\\<close> \\<open>Q = C \\<Longrightarrow> col X Y Z\\<close> \\<open>Q = R \\<Longrightarrow> col X Y Z\\<close> \\<open>Q = W \\<Longrightarrow> col X Y Z\\<close> \\<open>R = A \\<Longrightarrow> col X Y Z\\<close> \n            \\<open>R = C \\<Longrightarrow> col X Y Z\\<close> \\<open>R = W \\<Longrightarrow> col X Y Z\\<close> \\<open>\\<lbrakk>distinct6 P Q R A C W; C \\<notin> line_ext (line E F); A \\<notin> line_ext (line D E); line B C \\<noteq> line A B; line E F \\<noteq> line A F; A \\<notin> line_ext (line C D); Pascal_Property.inter (line B C) (line E F) \\<noteq> Pascal_Property.inter (line A C) (line E F)\\<rbrakk> \\<Longrightarrow> col (Pascal_Property.inter (line A C) (line E F)) (Pascal_Property.inter (line C D) (line B F)) (Pascal_Property.inter (line A B) (line D E))\\<close> \n            \\<open>line B C = line A B \\<Longrightarrow> col X Y Z\\<close> \\<open>line E F = line A F \\<Longrightarrow> col X Y Z\\<close> distinct6_def line_comm)\n     qed\n     show \"is_pascal B A C D E F\"\n       using X_def Y_def Z_def \\<open>\\<lbrakk>distinct6 B A C D E F; line A C \\<noteq> line E F; line C D \\<noteq> line B F; line B A \\<noteq> line D E; line B C = line E F\\<rbrakk> \\<Longrightarrow> col X Y Z\\<close> \n         \\<open>\\<lbrakk>distinct6 B A C D E F; line A C \\<noteq> line E F; line C D \\<noteq> line B F; line B A \\<noteq> line D E; line B C \\<noteq> line E F; line C D \\<noteq> line A F\\<rbrakk> \\<Longrightarrow> col X Y Z\\<close> \n         \\<open>\\<lbrakk>distinct6 B A C D E F; line A C \\<noteq> line E F; line C D \\<noteq> line B F; line B A \\<noteq> line D E; line C D = line A F\\<rbrakk> \\<Longrightarrow> col X Y Z\\<close> \n         is_pascal_def \n       by force\n  qed\n  thus \"pascal_prop\" using pascal_prop_def \n    by auto\nqed\n\nlemma is_pascal_under_alternate_vertices:\n  assumes \"pascal_prop\" and \"is_pascal A B C A' B' C'\"\n  shows \"is_pascal A B' C A' B C'\"\n  using assms pascal_prop_def is_pascal_rot_CW \n  by presburger\n\nlemma col_inter:\n  assumes \"distinct6 A B C D E F\" and \"col A B C\" and \"col D E F\"\n  shows \"inter (line B C) (line E F) = inter (line A B) (line D E)\"\n  by (smt assms ax_uniqueness col_def distinct6_def incidA_lAB incidB_lAB)\n\nlemma pascal_pappus1:\n  assumes \"pascal_prop\"\n  shows \"is_pappus1 A B C A' B' C' P Q R\"\nproof-\n  define a1 a2 a3 a4 a5 a6 where \"a1 = distinct6 A B C A' B' C'\"  and \"a2 = col A B C\" and \n\"a3 = col A' B' C'\" and \"a4 = is_a_proper_intersec P A B' A' B\" and \"a5 = is_a_proper_intersec Q B C' B' C\" \nand \"a6 = is_a_proper_intersec R A C' A' C\" \n  (* i.e. we have assumed a Pappus configuration *)\n  have \"inter (line B C) (line B' C') = inter (line A B) (line A' B')\" if a1 a2 a3 a4 a5 a6\n    using a1_def a2_def a3_def col_inter that(1) that(2) that(3) \n    by blast\n  then have \"is_pascal A B C A' B' C'\" if a1 a2 a3 a4 a5 a6\n    using a1_def col_ABA is_pascal_def that(1) that(2) that(3) that(4) that(5) that(6) \n    by auto\n  then have \"is_pascal A B' C A' B C'\" if a1 a2 a3 a4 a5 a6\n    using assms is_pascal_under_alternate_vertices that(1) that(2) that(3) that(4) that(5) that(6) \n    by blast\n  then have \"col P Q R\" if a1 a2 a3 a4 a5 a6\n    by (smt a1_def a4_def a5_def a6_def ax_uniqueness col_def distinct6_def incidB_lAB incid_inter_left \n        incid_inter_right is_a_proper_intersec_def is_pascal_def line_comm that(1) that(2) that(3) \n        that(4) that(5) that(6))\n  show \"is_pappus1 A B C A' B' C' P Q R\"\n    by (simp add: \\<open>\\<lbrakk>a1; a2; a3; a4; a5; a6\\<rbrakk> \\<Longrightarrow> col P Q R\\<close> a1_def a2_def a3_def a4_def a5_def a6_def \n        is_pappus1_def)\nqed\n\nlemma pascal_pappus:\n  assumes \"pascal_prop\"\n  shows \"is_pappus\"\n  by (simp add: assms is_pappus_def pappus12 pascal_pappus1)\n\ntheorem pappus_iff_pascal: \"is_pappus = pascal_prop\"\n  using pappus_pascal pascal_pappus \n  by blast\n\nend\n\n\n\n\n\n", "meta": {"author": "AnthonyBordg", "repo": "Isabelle_marries_Desargues", "sha": "e5061842d78328635169eba6e1c7c970fd33313f", "save_path": "github-repos/isabelle/AnthonyBordg-Isabelle_marries_Desargues", "path": "github-repos/isabelle/AnthonyBordg-Isabelle_marries_Desargues/Isabelle_marries_Desargues-e5061842d78328635169eba6e1c7c970fd33313f/Plane/Pascal_Property.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8740772450055545, "lm_q2_score": 0.8289388040954683, "lm_q1q2_score": 0.724556546161966}}
{"text": "section \\<open>Algebra\\<close>\n\ntext \\<open>\n  In this section, we develop the necessary algebra for developing the theory of Coxeter systems,\n  including groups, quotient groups, free groups, group presentations, and words in a group over a\n  set of generators.\n\\<close>\n\ntheory Algebra\nimports Prelim\n\nbegin\n\nsubsection \\<open>Miscellaneous algebra facts\\<close>\n\nlemma times2_conv_add: \"(j::nat) + j = 2*j\"\n  by (induct j) auto\n\nlemma (in comm_semiring_1) odd_n0: \"odd m \\<Longrightarrow> m\\<noteq>0\"\n  using dvd_0_right by fast\n\nlemma (in semigroup_add) add_assoc4: \"a + b + c + d = a + (b + c + d)\"\n  using add.assoc by simp\n\nlemmas (in monoid_add) sum_list_map_cong =\n  arg_cong[OF map_cong, OF refl, of _ _ _ sum_list]\n\ncontext group_add\nbegin\n\nlemma map_uminus_order2:\n  \"\\<forall>s\\<in>set ss. s+s=0 \\<Longrightarrow> map (uminus) ss = ss\"\n  by (induct ss) (auto simp add: minus_unique)\n\nlemma uminus_sum_list: \"- sum_list as = sum_list (map uminus (rev as))\"\n  by (induct as) (auto simp add: minus_add)\n\nlemma uminus_sum_list_order2:\n  \"\\<forall>s\\<in>set ss. s+s=0 \\<Longrightarrow> - sum_list ss = sum_list (rev ss)\"\n  using uminus_sum_list map_uminus_order2 by simp\n\nend (* context group_add *)\n\nsubsection \\<open>The type of permutations of a type\\<close>\n\ntext \\<open>\n  Here we construct a type consisting of all bijective functions on a type. This is the\n  prototypical example of a group, where the group operation is composition, and every group can\n  be embedded into such a type. It is for this purpose that we construct this type, so that we may\n  confer upon suitable subsets of types that are not of class @{class group_add} the properties of\n  that class, via a suitable injective correspondence to this permutation type.\n\\<close>\n\ntypedef 'a permutation = \"{f::'a\\<Rightarrow>'a. bij f}\"\n  morphisms permutation Abs_permutation\n  by fast\n\nsetup_lifting type_definition_permutation\n\nabbreviation permutation_apply :: \"'a permutation \\<Rightarrow> 'a \\<Rightarrow> 'a \" (infixr \"\\<rightarrow>\" 90)\n  where \"p \\<rightarrow> a \\<equiv> permutation p a\"\nabbreviation permutation_image :: \"'a permutation \\<Rightarrow> 'a set \\<Rightarrow> 'a set\"\n  (infixr \"`\\<rightarrow>\" 90)\n  where \"p `\\<rightarrow> A \\<equiv> permutation p ` A\"\n\nlemma permutation_eq_image: \"a `\\<rightarrow> A = a `\\<rightarrow> B \\<Longrightarrow> A=B\"\n  using permutation[of a] inj_eq_image[OF bij_is_inj] by auto\n\ninstantiation permutation :: (type) zero\nbegin\nlift_definition zero_permutation :: \"'a permutation\" is \"id::'a\\<Rightarrow>'a\" by simp\ninstance ..\nend\n\ninstantiation permutation :: (type) plus\nbegin\nlift_definition plus_permutation :: \"'a permutation \\<Rightarrow> 'a permutation \\<Rightarrow> 'a permutation\"\n  is    \"comp\"\n  using bij_comp\n  by    fast\ninstance ..\nend\n\nlemma plus_permutation_abs_eq:\n  \"bij f \\<Longrightarrow> bij g \\<Longrightarrow>\n    Abs_permutation f + Abs_permutation g = Abs_permutation (f\\<circ>g)\"\n  by (simp add: plus_permutation.abs_eq eq_onp_same_args)\n\ninstance permutation :: (type) semigroup_add\nproof\n  fix a b c :: \"'a permutation\" show \"a + b + c = a + (b + c)\"\n    using comp_assoc[of \"permutation a\" \"permutation b\" \"permutation c\"]\n    by    transfer simp\nqed\n\ninstance permutation :: (type) monoid_add\nproof\n  fix a :: \"'a permutation\"\n  show \"0 + a = a\" by transfer simp\n  show \"a + 0 = a\" by transfer simp\nqed\n\ninstantiation permutation :: (type) uminus\nbegin\nlift_definition uminus_permutation :: \"'a permutation \\<Rightarrow> 'a permutation\"\n  is    \"\\<lambda>f. the_inv f\"\n  using bij_betw_the_inv_into\n  by    fast\ninstance ..\nend\n\ninstantiation permutation :: (type) minus\nbegin\nlift_definition minus_permutation :: \"'a permutation \\<Rightarrow> 'a permutation \\<Rightarrow> 'a permutation\"\n  is    \"\\<lambda>f g. f \\<circ> (the_inv g)\"\n  using bij_betw_the_inv_into bij_comp\n  by    fast\ninstance ..\nend\n\nlemma minus_permutation_abs_eq:\n  \"bij f \\<Longrightarrow> bij g \\<Longrightarrow>\n    Abs_permutation f - Abs_permutation g = Abs_permutation (f \\<circ> the_inv g)\"\n  by (simp add: minus_permutation.abs_eq eq_onp_same_args)\n\ninstance permutation :: (type) group_add\nproof\n  fix a b :: \"'a permutation\"\n  show \"- a + a = 0\" using the_inv_leftinv[of \"permutation a\"] by transfer simp\n  show \"a + - b = a - b\" by transfer simp\nqed\n\n\nsubsection \\<open>Natural action of @{typ nat} on types of class @{class monoid_add}\\<close>\n\nsubsubsection \\<open>Translation from class @{class power}.\\<close>\n\ntext \\<open>\n  Here we translate the @{class power} class to apply to types of class @{class monoid_add}.\n\\<close>\n\ncontext monoid_add\nbegin\n\nsublocale nataction: power 0 plus .\nsublocale add_mult_translate: monoid_mult 0 plus\n  by unfold_locales (auto simp add: add.assoc)\n\nabbreviation nataction :: \"'a \\<Rightarrow> nat \\<Rightarrow> 'a\" (infix \"+^\" 80)\n  where \"a+^n  \\<equiv> nataction.power a n\"\n\nlemmas nataction_2    = add_mult_translate.power2_eq_square\nlemmas nataction_Suc2 = add_mult_translate.power_Suc2\n\nlemma alternating_sum_list_conv_nataction:\n  \"sum_list (alternating_list (2*n) s t) = (s+t)+^n\"\n  by (induct n) (auto simp add: nataction_Suc2[THEN sym])\n\nlemma nataction_add_flip: \"(a+b)+^(Suc n) = a + (b+a)+^n + b\"\n  using nataction_Suc2 add.assoc by (induct n arbitrary: a b) auto\n\nend (* context monoid_add *)\n\nlemma (in group_add) nataction_add_eq0_flip:\n  assumes \"(a+b)+^n = 0\"\n  shows   \"(b+a)+^n = 0\"\nproof (cases n)\n  case (Suc k) with assms show ?thesis\n    using nataction_add_flip add.assoc[of \"-a\" \"a+b\" \"(a+b)+^k\"] by simp\nqed simp\n\nsubsubsection \\<open>Additive order of an element\\<close>\n\ncontext monoid_add\nbegin\n\ndefinition add_order :: \"'a \\<Rightarrow> nat\"\n  where \"add_order a \\<equiv> if (\\<exists>n>0. a+^n = 0) then\n          (LEAST n. n>0 \\<and> a+^n = 0) else 0\"\n\nlemma add_order: \"a+^(add_order a) = 0\"\n  using LeastI_ex[of \"\\<lambda>n. n>0 \\<and> a+^n = 0\"] add_order_def by simp\n\nlemma add_order_least: \"n>0 \\<Longrightarrow> a+^n = 0 \\<Longrightarrow> add_order a \\<le> n\"\n  using Least_le[of \"\\<lambda>n. n>0 \\<and> a+^n = 0\"] add_order_def by simp\n\nlemma add_order_equality:\n  \"\\<lbrakk> n>0; a+^n = 0; (\\<And>m. m>0 \\<Longrightarrow> a+^m = 0 \\<Longrightarrow> n\\<le>m) \\<rbrakk> \\<Longrightarrow>\n    add_order a = n\"\n  using Least_equality[of \"\\<lambda>n. n>0 \\<and> a+^n = 0\"] add_order_def by auto\n\nlemma add_order0: \"add_order 0 = 1\"\n  using add_order_equality by simp\n\nlemma add_order_gt0: \"(add_order a > 0) = (\\<exists>n>0. a+^n = 0)\"\n  using LeastI_ex[of \"\\<lambda>n. n>0 \\<and> a+^n = 0\"] add_order_def by simp\n\nlemma add_order_eq0: \"add_order a = 0 \\<Longrightarrow> n>0 \\<Longrightarrow> a+^n \\<noteq> 0\"\n  using add_order_gt0 by force\n\nlemma less_add_order_eq_0:\n  assumes \"a+^k = 0\" \"k < add_order a\"\n  shows   \"k = 0\"\nproof (cases \"k=0\")\n  case False\n  moreover with assms(1) have \"\\<exists>n>0. a+^n = 0\" by fast\n  ultimately show ?thesis\n    using assms add_order_def not_less_Least[of k \"\\<lambda>n. n>0 \\<and> a+^n = 0\"]\n    by    auto\nqed simp\n\nlemma less_add_order_eq_0_contra: \"k>0 \\<Longrightarrow> k < add_order a \\<Longrightarrow> a+^k \\<noteq> 0\"\n  using less_add_order_eq_0 by fast\n\nlemma add_order_relator: \"add_order (a+^(add_order a)) = 1\"\n  using add_order by (auto intro: add_order_equality)\n\nabbreviation pair_relator_list :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a list\"\n  where \"pair_relator_list s t \\<equiv> alternating_list (2*add_order (s+t)) s t\"\nabbreviation pair_relator_halflist :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a list\"\n  where \"pair_relator_halflist s t \\<equiv> alternating_list (add_order (s+t)) s t\"\nabbreviation pair_relator_halflist2 :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a list\"\n  where \"pair_relator_halflist2 s t \\<equiv>\n    (if even (add_order (s+t)) then pair_relator_halflist s t else\n      pair_relator_halflist t s)\"\n\nlemma sum_list_pair_relator_list: \"sum_list (pair_relator_list s t) = 0\"\n  by (auto simp add: add_order alternating_sum_list_conv_nataction)\n\nend (* context monoid_add *)\n\ncontext group_add\nbegin\n\nlemma add_order_add_eq1: \"add_order (s+t) = 1 \\<Longrightarrow> t = -s\"\n  using add_order[of \"s+t\"] by (simp add: minus_unique)\n\nlemma add_order_add_sym: \"add_order (t+s) = add_order (s+t)\"\nproof (cases \"add_order (t+s) = 0\" \"add_order (s+t) = 0\" rule: two_cases)\n  case one thus ?thesis\n    using add_order nataction_add_eq0_flip[of s t] add_order_eq0 by auto\nnext\n  case other thus ?thesis\n    using add_order nataction_add_eq0_flip[of t s] add_order_eq0 by auto\nnext\n  case neither thus ?thesis\n    using add_order[of \"s+t\"] add_order[of \"t+s\"]\n          nataction_add_eq0_flip[of s t] nataction_add_eq0_flip[of t s]\n          add_order_least[of \"add_order (s+t)\"] add_order_least[of \"add_order (t+s)\"]\n    by fastforce\nqed simp\n\nlemma pair_relator_halflist_append:\n  \"pair_relator_halflist s t @ pair_relator_halflist2 s t = pair_relator_list s t\"\n  using alternating_list_split[of \"add_order (s+t)\" \"add_order (s+t)\" s t]\n  by    (auto simp add: times2_conv_add add_order_add_sym)\n\nlemma rev_pair_relator_list: \"rev (pair_relator_list s t) = pair_relator_list t s\"\n  by (simp add:rev_alternating_list add_order_add_sym)\n\n\n\nsubsection \\<open>Partial sums of a list\\<close>\n\ntext \\<open>\n  Here we construct a list that collects the results of adding the elements of a given list\n  together one-by-one.\n\\<close>\n\ncontext monoid_add\nbegin\n\nprimrec sums :: \"'a list \\<Rightarrow> 'a list\"\n  where\n    \"sums [] = [0]\"\n  | \"sums (x#xs) = 0 # map ((+) x) (sums xs)\"\n\nlemma length_sums: \"length (sums xs) = Suc (length xs)\"\n  by (induct xs) auto\n\nlemma sums_snoc: \"sums (xs@[x]) = sums xs @ [sum_list (xs@[x])]\"\n  by (induct xs) (auto simp add: add.assoc)\n\nlemma sums_append2:\n  \"sums (xs@ys) = butlast (sums xs) @ map ((+) (sum_list xs)) (sums ys)\"\nproof (induct ys rule: rev_induct)\n  case Nil show ?case by (cases xs rule: rev_cases) (auto simp add: sums_snoc)\nnext\n  case (snoc y ys) thus ?case using sums_snoc[of \"xs@ys\"] by (simp add: sums_snoc)\nqed\n\nlemma sums_Cons_conv_append_tl:\n  \"sums (x#xs) = 0 # x # map ((+) x) (tl (sums xs))\"\n  by (cases xs) auto\n\nlemma pullback_sums_map_middle2:\n  \"map F (sums xs) = ds@[d,e]@es \\<Longrightarrow>\n    \\<exists>as a bs. xs = as@[a]@bs \\<and> map F (sums as) = ds@[d] \\<and>\n      d = F (sum_list as) \\<and> e = F (sum_list (as@[a]))\"\nproof (induct xs es rule: list_induct2_snoc)\n  case (Nil2 xs)\n  show ?case\n  proof (cases xs rule: rev_cases)\n    case Nil with Nil2 show ?thesis by simp\n  next\n    case (snoc ys y) have ys: \"xs = ys@[y]\" by fact\n    with Nil2(1) have y: \"map F (sums ys) = ds@[d]\" \"e = F (sum_list (ys@[y]))\"\n      by (auto simp add: sums_snoc)\n    show ?thesis\n    proof (cases ys rule: rev_cases)\n      case Nil\n      with ys y have\n        \"xs = []@[y]@[]\" \"map F (sums []) = ds@[d]\"\n        \"d = F (sum_list [])\" \"e = F (sum_list ([]@[y]))\"\n        by auto\n      thus ?thesis by fast\n    next\n      case (snoc zs z)\n      with y(1) have z: \"map F (sums zs) = ds\" \"d = F (sum_list (zs@[z]))\"\n        by (auto simp add: sums_snoc)\n      from z(1) ys y snoc have\n        \"xs = (zs@[z])@[y]@[]\" \"map F (sums (zs@[z])) = ds@[d]\"\n        \"e = F (sum_list ((zs@[z])@[y]))\"\n        by auto\n      with z(2) show ?thesis by fast\n    qed\n  qed\nnext\n  case snoc thus ?case by (fastforce simp add: sums_snoc)\nqed simp\n\nlemma pullback_sums_map_middle3:\n  \"map F (sums xs) = ds@[d,e,f]@fs \\<Longrightarrow>\n    \\<exists>as a b bs. xs = as@[a,b]@bs \\<and> d = F (sum_list as) \\<and>\n      e = F (sum_list (as@[a])) \\<and> f = F (sum_list (as@[a,b]))\"\nproof (induct xs fs rule: list_induct2_snoc)\n  case (Nil2 xs)\n  show ?case\n  proof (cases xs rule: rev_cases)\n    case Nil with Nil2 show ?thesis by simp\n  next\n    case (snoc ys y)\n    with Nil2 have y: \"map F (sums ys) = ds@[d,e]\" \"f = F (sum_list (ys@[y]))\"\n      by (auto simp add: sums_snoc)\n    from y(1) obtain as a bs where asabs:\n      \"ys = as@[a]@bs\" \"map F (sums as) = ds@[d]\"\n      \"d = F (sum_list as)\" \"e = F (sum_list (as@[a]))\"\n      using pullback_sums_map_middle2[of F ys ds]\n      by    fastforce\n    have \"bs = []\"\n    proof-\n      from y(1) asabs(1,2) have \"Suc (length bs) = Suc 0\"\n        by (auto simp add: sums_append2 map_butlast length_sums[THEN sym])\n      thus ?thesis by fast\n    qed\n    with snoc asabs(1) y(2) have \"xs = as@[a,y]@[]\" \"f = F (sum_list (as@[a,y]))\"\n      by auto\n    with asabs(3,4) show ?thesis by fast\n  qed\nnext\n  case snoc thus ?case by (fastforce simp add: sums_snoc)\nqed simp\n\nlemma pullback_sums_map_double_middle2:\n  assumes \"map F (sums xs) = ds@[d,e]@es@[f,g]@gs\"\n  shows   \"\\<exists>as a bs b cs. xs = as@[a]@bs@[b]@cs \\<and> d = F (sum_list as) \\<and>\n            e = F (sum_list (as@[a])) \\<and> f = F (sum_list (as@[a]@bs)) \\<and>\n            g = F (sum_list (as@[a]@bs@[b]))\"\nproof-\n  from assms obtain As b cs where Asbcs:\n    \"xs = As@[b]@cs\" \"map F (sums As) = ds@[d,e]@es@[f]\"\n    \"f = F (sum_list As)\" \"g = F (sum_list (As@[b]))\"\n    using pullback_sums_map_middle2[of F xs \"ds@[d,e]@es\"]\n    by    fastforce\n  from Asbcs show ?thesis\n    using pullback_sums_map_middle2[of F As ds d e \"es@[f]\"] by fastforce\nqed\n\nend (* context monoid_add *)\n\nsubsection \\<open>Sums of alternating lists\\<close>\n\nlemma (in group_add) uminus_sum_list_alternating_order2:\n  \"s+s=0 \\<Longrightarrow> t+t=0 \\<Longrightarrow> - sum_list (alternating_list n s t) =\n    sum_list (if even n then alternating_list n t s else alternating_list n s t)\"\n  using uminus_sum_list_order2 set_alternating_list[of n] rev_alternating_list[of n s]\n  by    fastforce\n\ncontext monoid_add\nbegin\n\nlemma alternating_order2_cancel_1left:\n  \"s+s=0 \\<Longrightarrow>\n    sum_list (s # (alternating_list (Suc n) s t)) = sum_list (alternating_list n t s)\"\n  using add.assoc[of s s] alternating_list_Suc_Cons[of n s] by simp\n\nlemma alternating_order2_cancel_2left:\n  \"s+s=0 \\<Longrightarrow> t+t=0 \\<Longrightarrow>\n    sum_list (t # s # (alternating_list (Suc (Suc n)) s t)) =\n      sum_list (alternating_list n s t)\"\n    using alternating_order2_cancel_1left[of s \"Suc n\"]\n          alternating_order2_cancel_1left[of t n]\n    by    simp\n\nlemma alternating_order2_even_cancel_right:\n  assumes st    : \"s+s=0\" \"t+t=0\"\n  and     even_n: \"even n\"\n  shows   \"m \\<le> n \\<Longrightarrow> sum_list (alternating_list n s t @ alternating_list m t s) =\n            sum_list (alternating_list (n-m) s t)\"\nproof (induct n arbitrary: m rule: nat_even_induct, rule even_n)\n  case (SucSuc k) with st show ?case\n    using alternating_order2_cancel_2left[of t s]\n    by    (cases m rule: nat_cases_2Suc) auto\nqed simp\n\nend (* context monoid_add *)\n\nsubsection \\<open>Conjugation in @{class group_add}\\<close>\n\nsubsubsection \\<open>Abbreviations and basic facts\\<close>\n\ncontext group_add\nbegin\n\nabbreviation lconjby :: \"'a\\<Rightarrow>'a\\<Rightarrow>'a\"\n  where \"lconjby x y \\<equiv> x+y-x\"\n\nabbreviation rconjby :: \"'a\\<Rightarrow>'a\\<Rightarrow>'a\"\n  where \"rconjby x y \\<equiv> -x+y+x\"\n\nlemma lconjby_add: \"lconjby (x+y) z = lconjby x (lconjby y z)\"\n  by (auto simp add: algebra_simps)\n\nlemma rconjby_add: \"rconjby (x+y) z = rconjby y (rconjby x z)\"\n  by (simp add: minus_add add.assoc[THEN sym])\n\nlemma add_rconjby: \"rconjby x y + rconjby x z = rconjby x (y+z)\"\n  by (simp add: add.assoc)\n\nlemma lconjby_uminus: \"lconjby x (-y) = - lconjby x y\"\n  using minus_unique[of \"lconjby x y\", THEN sym] by (simp add: algebra_simps)\n\nlemma rconjby_uminus: \"rconjby x (-y) = - rconjby x y\"\n  using minus_unique[of \"rconjby x y\"] add_assoc4[of \"rconjby x y\" \"-x\" \"-y\" x] by simp\n\nlemma lconjby_rconjby: \"lconjby x (rconjby x y) = y\"\n  by (simp add: algebra_simps)\n\nlemma rconjby_lconjby: \"rconjby x (lconjby x y) = y\"\n  by (simp add: algebra_simps)\n\nlemma lconjby_inj: \"inj (lconjby x)\"\n  using rconjby_lconjby by (fast intro: inj_on_inverseI)\n\nlemma rconjby_inj: \"inj (rconjby x)\"\n  using lconjby_rconjby by (fast intro: inj_on_inverseI)\n\nlemma lconjby_surj: \"surj (lconjby x)\"\n  using lconjby_rconjby surjI[of \"lconjby x\"] by fast\n\nlemma lconjby_bij: \"bij (lconjby x)\"\n  unfolding bij_def using lconjby_inj lconjby_surj by fast\n\nlemma the_inv_lconjby: \"the_inv (lconjby x) = (rconjby x)\"\n  using bij_betw_f_the_inv_into_f[OF lconjby_bij, of _ x] lconjby_rconjby\n  by    (force intro: inj_onD[OF lconjby_inj, of x])\n\nlemma lconjby_eq_conv_rconjby_eq: \"w = lconjby x y \\<Longrightarrow> y = rconjby x w\"\n  using the_inv_lconjby the_inv_into_f_f[OF lconjby_inj] by force\n\nlemma rconjby_order2: \"s+s = 0 \\<Longrightarrow> rconjby x s + rconjby x s = 0\"\n  by (simp add: add_rconjby)\n\nlemma rconjby_order2_eq_lconjby:\n  assumes \"s+s=0\"\n  shows   \"rconjby s = lconjby s\"\nproof-\n  have \"rconjby s = lconjby (-s)\" by simp\n  with assms show ?thesis using minus_unique by simp\nqed\n\nlemma lconjby_alternating_list_order2:\n  assumes \"s+s=0\" \"t+t=0\"\n  shows   \"lconjby (sum_list (alternating_list k s t)) (if even k then s else t) =\n            sum_list (alternating_list (Suc (2*k)) s t)\"\nproof (induct k rule: nat_induct_step2)\n  case (SucSuc m)\n  have \"lconjby (sum_list (alternating_list (Suc (Suc m)) s t))\n          (if even (Suc (Suc m)) then s else t) = s + t +\n          lconjby (sum_list (alternating_list m s t)) (if even m then s else t) - t - s\"\n    using alternating_list_SucSuc_ConsCons[of m s t]\n    by    (simp add: algebra_simps)\n  also from assms SucSuc\n    have  \"\\<dots> = sum_list (alternating_list (Suc (2*Suc (Suc m))) s t)\"\n    using alternating_list_SucSuc_ConsCons[of \"Suc (2*m)\" s t]\n          sum_list.append[of \"alternating_list (Suc (2*Suc m)) s t\" \"[t]\"]\n    by    (simp add: algebra_simps)\n  finally show ?case by fast\nqed (auto simp add: assms(1) algebra_simps)\n\nend (* context group_add *)\n\nsubsubsection \\<open>The conjugation sequence\\<close>\n\ntext \\<open>\n  Given a list in @{class group_add}, we create a new list by conjugating each term by all the\n  previous terms. This sequence arises in Coxeter systems.\n\\<close>\n\ncontext group_add\nbegin\n\nprimrec lconjseq :: \"'a list \\<Rightarrow> 'a list\"\n  where\n    \"lconjseq []     = []\"\n  | \"lconjseq (x#xs) = x # (map (lconjby x) (lconjseq xs))\"\n\nlemma length_lconjseq: \"length (lconjseq xs) = length xs\"\n  by (induct xs) auto\n\nlemma lconjseq_snoc: \"lconjseq (xs@[x]) = lconjseq xs @ [lconjby (sum_list xs) x]\"\n  by (induct xs) (auto simp add: lconjby_add)\n\nlemma lconjseq_append:\n  \"lconjseq (xs@ys) = lconjseq xs @ (map (lconjby (sum_list xs)) (lconjseq ys))\"\nproof (induct ys rule: rev_induct)\n  case (snoc y ys) thus ?case\n    using lconjseq_snoc[of \"xs@ys\"] lconjseq_snoc[of ys] by (simp add: lconjby_add)\nqed simp\n\nlemma lconjseq_alternating_order2_repeats':\n  fixes   s t :: 'a\n  defines altst: \"altst \\<equiv> \\<lambda>n. alternating_list n s t\"\n  and     altts: \"altts \\<equiv> \\<lambda>n. alternating_list n t s\"\n  assumes st   : \"s+s=0\" \"t+t=0\" \"(s+t)+^k = 0\"\n  shows   \"map (lconjby (sum_list (altst k)))\n            (lconjseq (if even k then altst m else altts m)) = lconjseq (altst m)\"\nproof (induct m)\n  case (Suc j)\n  with altst altts\n    have  \"map (lconjby (sum_list (altst k)))\n            (lconjseq (if even k then altst (Suc j) else altts (Suc j))) =\n            lconjseq (altst j) @\n            [lconjby (sum_list (altst k @ (if even k then altst j else altts j)))\n            (if even k then (if even j then s else t) else (if even j then t else s))]\"\n    by    (auto simp add: lconjseq_snoc lconjby_add)\n  also from altst altts st(1,2)\n    have  \"\\<dots> = lconjseq (altst j) @ [sum_list (altst (Suc (2*(k+j))))]\"\n    using lconjby_alternating_list_order2[of s t \"k+j\"] \n    by    (cases \"even k\")\n          (auto simp add: alternating_list_append[of k])\n  finally show ?case using altst st\n    by    (auto simp add:\n            alternating_list_append(1)[THEN sym]\n            alternating_sum_list_conv_nataction\n            lconjby_alternating_list_order2 lconjseq_snoc\n          )\nqed (simp add: altst altts)\n\nlemma lconjseq_alternating_order2_repeats:\n  fixes   s t :: 'a and k :: nat\n  defines altst: \"altst \\<equiv> \\<lambda>n. alternating_list n s t\"\n  and     altts: \"altts \\<equiv> \\<lambda>n. alternating_list n t s\"\n  assumes st: \"s+s=0\" \"t+t=0\" \"(s+t)+^k = 0\"\n  shows   \"lconjseq (altst (2*k)) = lconjseq (altst k) @ lconjseq (altst k)\"\nproof-\n  from altst altts\n    have \"lconjseq (altst (2*k)) = lconjseq (altst k) @\n            map (lconjby (sum_list (altst k)))\n              (lconjseq (if even k then altst k else altts k))\"\n    using alternating_list_append[THEN sym, of k k s t]\n    by    (auto simp add: times2_conv_add lconjseq_append)\n  with altst altts st show ?thesis\n    using lconjseq_alternating_order2_repeats'[of s t k k] by auto\nqed\n\nlemma even_count_lconjseq_alternating_order2:\n  fixes   s t :: 'a\n  assumes \"s+s=0\" \"t+t=0\" \"(s+t)+^k = 0\"\n  shows   \"even (count_list (lconjseq (alternating_list (2*k) s t)) x)\"\nproof-\n  define xs where xs: \"xs \\<equiv> lconjseq (alternating_list (2*k) s t)\"\n  with assms obtain as where \"xs = as@as\"\n    using lconjseq_alternating_order2_repeats by fast\n  hence \"count_list xs x = 2 * (count_list as x)\"\n    by (simp add: count_list_append times2_conv_add)\n  with xs show ?thesis by simp\nqed\n\nlemma order2_hd_in_lconjseq_deletion:\n  shows \"s+s=0 \\<Longrightarrow> s \\<in> set (lconjseq ss)\n            \\<Longrightarrow> \\<exists>as b bs. ss = as@[b]@bs \\<and> sum_list (s#ss) = sum_list (as@bs)\"\nproof (induct ss arbitrary: s rule: rev_induct)\n  case (snoc t ts) show ?case\n  proof (cases \"s \\<in> set (lconjseq ts)\")\n    case True\n    with snoc(1,2) obtain as b bs\n      where   asbbs: \"ts = as @[b]@bs\" \"sum_list (s#ts) = sum_list (as@bs)\"\n      by      fastforce\n    from asbbs(2) have \"sum_list (s#ts@[t]) = sum_list (as@(bs@[t]))\"\n      using sum_list.append[of \"s#ts\" \"[t]\"] sum_list.append[of \"as@bs\" \"[t]\"] by simp\n    with asbbs(1) show ?thesis by fastforce\n  next\n    case False\n    with snoc(3) have s: \"s = lconjby (sum_list ts) t\" by (simp add: lconjseq_snoc)\n    with snoc(2) have \"t+t=0\"\n      using lconjby_eq_conv_rconjby_eq[of s \"sum_list ts\" t]\n            rconjby_order2[of s \"sum_list ts\"]\n      by    simp\n    moreover from s have \"sum_list (s#ts@[t]) = sum_list ts + t + t\"\n      using add.assoc[of \"sum_list ts + t - sum_list ts\" \"sum_list ts\"]\n      by    (simp add: algebra_simps)\n    ultimately have \"sum_list (s#ts@[t]) = sum_list (ts@[])\"\n      by (simp add: algebra_simps)\n    thus ?thesis by fast\n  qed\nqed simp\n\nend (* context group_add *)\n\nsubsubsection \\<open>The action on signed @{class group_add} elements\\<close>\n\ntext \\<open>\n  Here we construct an action of a group on itself by conjugation, where group elements are\n  endowed with an auxiliary sign by pairing with a boolean element. In multiple applications of\n  this action, the auxiliary sign helps keep track of how many times the elements conjugating and\n  being conjugated are the same. This action arises in exploring reduced expressions of group\n  elements as words in a set of generators of order two (in particular, in a Coxeter group).\n\\<close>\n\ntype_synonym 'a signed = \"'a\\<times>bool\"\n\ndefinition signed_funaction :: \"('a\\<Rightarrow>'a\\<Rightarrow>'a) \\<Rightarrow> 'a \\<Rightarrow> 'a signed \\<Rightarrow> 'a signed\"\n  where \"signed_funaction f s x \\<equiv> map_prod (f s) (\\<lambda>b. b \\<noteq> (fst x = s)) x\"\n  \\<comment> \\<open>so the sign of @{term x} is flipped precisely when its first component is equal to\n@{term s}\\<close>\n\ncontext group_add\nbegin\n\nabbreviation \"signed_lconjaction \\<equiv> signed_funaction lconjby\"\nabbreviation \"signed_rconjaction \\<equiv> signed_funaction rconjby\"\n\nlemmas signed_lconjactionD = signed_funaction_def[of lconjby]\nlemmas signed_rconjactionD = signed_funaction_def[of rconjby]\n\nabbreviation signed_lconjpermutation :: \"'a \\<Rightarrow> 'a signed permutation\"\n  where \"signed_lconjpermutation s \\<equiv> Abs_permutation (signed_lconjaction s)\"\n\nabbreviation signed_list_lconjaction :: \"'a list \\<Rightarrow> 'a signed \\<Rightarrow> 'a signed\"\n  where \"signed_list_lconjaction ss \\<equiv> foldr signed_lconjaction ss\"\n\nlemma signed_lconjaction_fst: \"fst (signed_lconjaction s x) = lconjby s (fst x)\"\n  using signed_lconjactionD by simp\n\nlemma signed_lconjaction_rconjaction:\n  \"signed_lconjaction s (signed_rconjaction s x) = x\"\nproof-\n  obtain a::'a and b::bool where \"x = (a,b)\" by fastforce\n  thus ?thesis\n    using signed_lconjactionD signed_rconjactionD injD[OF rconjby_inj, of s a]\n          lconjby_rconjby[of s a]\n    by    auto\nqed\n\nlemma signed_rconjaction_by_order2_eq_lconjaction:\n  \"s+s=0 \\<Longrightarrow> signed_rconjaction s = signed_lconjaction s\"\n  using signed_funaction_def[of lconjby s] signed_funaction_def[of rconjby s]\n        rconjby_order2_eq_lconjby[of s]\n  by    auto\n\nlemma inj_signed_lconjaction: \"inj (signed_lconjaction s)\"\nproof (rule injI)\n  fix x y assume 1: \"signed_lconjaction s x = signed_lconjaction s y\"\n  moreover obtain a1 a2 :: 'a and b1 b2 :: bool\n    where xy: \"x = (a1,b1)\" \"y = (a2,b2)\"\n    by    fastforce\n  ultimately show \"x=y\"\n    using injD[OF lconjby_inj, of s a1 a2] signed_lconjactionD \n    by    (cases \"a1=s\" \"a2=s\" rule: two_cases) auto\nqed\n\nlemma surj_signed_lconjaction: \"surj (signed_lconjaction s)\"\n  using signed_lconjaction_rconjaction[THEN sym] by fast\n\nlemma bij_signed_lconjaction: \"bij (signed_lconjaction s)\"\n  using inj_signed_lconjaction surj_signed_lconjaction by (fast intro: bijI)\n\nlemma the_inv_signed_lconjaction:\n  \"the_inv (signed_lconjaction s) = signed_rconjaction s\"\nproof\n  fix x\n  show \"the_inv (signed_lconjaction s) x = signed_rconjaction s x\"\n  proof (rule the_inv_into_f_eq, rule inj_signed_lconjaction)\n    show \"signed_lconjaction s (signed_rconjaction s x) = x\"\n      using signed_lconjaction_rconjaction by fast\n  qed (simp add: surj_signed_lconjaction)\nqed\n\nlemma the_inv_signed_lconjaction_by_order2:\n  \"s+s=0 \\<Longrightarrow> the_inv (signed_lconjaction s) = signed_lconjaction s\"\n  using the_inv_signed_lconjaction signed_rconjaction_by_order2_eq_lconjaction\n  by    simp\n\nlemma signed_list_lconjaction_fst:\n  \"fst (signed_list_lconjaction ss x) = lconjby (sum_list ss) (fst x)\"\n  using signed_lconjaction_fst lconjby_add by (induct ss) auto\n\nlemma signed_list_lconjaction_snd:\n  shows \"\\<forall>s\\<in>set ss. s+s=0 \\<Longrightarrow> snd (signed_list_lconjaction ss x)\n          = (if even (count_list (lconjseq (rev ss)) (fst x)) then snd x else \\<not>snd x)\"\nproof (induct ss)\n  case (Cons s ss) hence prevcase:\n    \"snd (signed_list_lconjaction ss x) =\n      (if even (count_list (lconjseq (rev ss)) (fst x)) then snd x else \\<not> snd x)\"\n    by simp\n  have 1: \"snd (signed_list_lconjaction (s # ss) x) =\n            snd (signed_lconjaction s (signed_list_lconjaction ss x))\"\n    by simp\n  show ?case\n  proof (cases \"fst (signed_list_lconjaction ss x) = s\")\n    case True\n    with 1 prevcase\n      have  \"snd (signed_list_lconjaction (s # ss) x) =\n              (if even (count_list (lconjseq (rev ss)) (fst x)) then \\<not> snd x else snd x)\"\n      by    (simp add: signed_lconjactionD)\n    with True Cons(2) show ?thesis\n      by    (simp add:\n              signed_list_lconjaction_fst lconjby_eq_conv_rconjby_eq\n              uminus_sum_list_order2[THEN sym] lconjseq_snoc count_list_snoc\n            )\n  next\n    case False\n    hence \"rconjby (sum_list ss) (lconjby (sum_list ss) (fst x)) \\<noteq>\n            rconjby (sum_list ss) s\"\n      by (simp add: signed_list_lconjaction_fst)\n    with Cons(2)\n      have  \"count_list (lconjseq (rev (s#ss))) (fst x) =\n              count_list (lconjseq (rev ss)) (fst x)\"\n      by    (simp add:\n              rconjby_lconjby uminus_sum_list_order2[THEN sym]\n              lconjseq_snoc count_list_snoc\n            )\n    moreover from False 1 prevcase\n      have \"snd (signed_list_lconjaction (s # ss) x) =\n              (if even (count_list (lconjseq (rev ss)) (fst x)) then snd x else \\<not> snd x)\"\n      by (simp add: signed_lconjactionD)\n    ultimately show ?thesis by simp\n  qed\nqed simp\n\nend (* context group_add *)\n\nsubsection \\<open>Cosets\\<close>\n\nsubsubsection \\<open>Basic facts\\<close>\n\nlemma set_zero_plus' [simp]: \"(0::'a::monoid_add) +o C = C\"\n\\<comment> \\<open>lemma @{text \"Set_Algebras.set_zero_plus\"} is restricted to types of class\n@{class comm_monoid_add}; here is a version in @{class monoid_add}.\\<close>\n  by (auto simp add: elt_set_plus_def)\n\nlemma lcoset_0: \"(w::'a::monoid_add) +o 0 = {w}\"\n  using elt_set_plus_def[of w] by simp\n\nlemma lcoset_refl: \"(0::'a::monoid_add) \\<in> A \\<Longrightarrow> a \\<in> a +o A\"\n  using elt_set_plus_def by force\n\nlemma lcoset_eq_reps_subset: \n  \"(a::'a::group_add) +o A \\<subseteq> a +o B \\<Longrightarrow> A \\<subseteq> B\"\n  using elt_set_plus_def[of a] by auto\n\nlemma lcoset_eq_reps: \"(a::'a::group_add) +o A = a +o B \\<Longrightarrow> A = B\"\n  using lcoset_eq_reps_subset[of a A B] lcoset_eq_reps_subset[of a B A] by auto\n\nlemma lcoset_inj_on: \"inj ((+o) (a::'a::group_add))\"\n  using lcoset_eq_reps inj_onI[of UNIV \"(+o) a\"] by auto\n\nlemma lcoset_conv_set: \"(a::'g::group_add) \\<in> b +o A \\<Longrightarrow> -b + a \\<in> A\"\n  by (auto simp add: elt_set_plus_def)\n\nsubsubsection \\<open>The supset order on cosets\\<close>\n\nlemma supset_lbound_lcoset_shift:\n  \"supset_lbound_of X Y B \\<Longrightarrow>\n    ordering.lbound_of (\\<supseteq>) (a +o X) (a +o Y) (a +o B)\"\n  using ordering.lbound_of_def[OF supset_poset, of X Y B] \n  by    (fast intro: ordering.lbound_ofI supset_poset)\n\nlemma supset_glbound_in_of_lcoset_shift:\n  fixes   P :: \"'a::group_add set set\"\n  assumes \"supset_glbound_in_of P X Y B\"\n  shows   \"supset_glbound_in_of ((+o) a ` P) (a +o X) (a +o Y) (a +o B)\"\n  using   ordering.glbound_in_ofD_in[OF supset_poset, OF assms]\n          ordering.glbound_in_ofD_lbound[OF supset_poset, OF assms]\n          supset_lbound_lcoset_shift[of X Y B a]\n          supset_lbound_lcoset_shift[of \"a +o X\" \"a +o Y\" _ \"-a\"]\n          ordering.glbound_in_ofD_glbound[OF supset_poset, OF assms]\n          ordering.glbound_in_ofI[\n            OF supset_poset, of \"a +o B\" \"(+o) a ` P\" \"a +o X\" \"a +o Y\"\n          ]\n  by      (fastforce simp add: set_plus_rearrange2)\n\nsubsubsection \\<open>The afforded partition\\<close>\n\ndefinition lcoset_rel :: \"'a::{uminus,plus} set \\<Rightarrow> ('a\\<times>'a) set\"\n  where \"lcoset_rel A \\<equiv> {(x,y). -x + y \\<in> A}\"\n\nlemma lcoset_relI: \"-x+y \\<in> A \\<Longrightarrow> (x,y) \\<in> lcoset_rel A\"\n  using lcoset_rel_def by fast\n\n\nsubsection \\<open>Groups\\<close>\n\ntext \\<open>We consider groups as closed sets in a type of class @{class group_add}.\\<close>\n\nsubsubsection \\<open>Locale definition and basic facts\\<close>\n\nlocale    Group =\n  fixes   G :: \"'g::group_add set\"\n  assumes nonempty   : \"G \\<noteq> {}\"\n  and     diff_closed: \"\\<And>g h. g \\<in> G \\<Longrightarrow> h \\<in> G \\<Longrightarrow> g - h \\<in> G\"\nbegin\n\nabbreviation Subgroup :: \"'g set \\<Rightarrow> bool\"\n  where \"Subgroup H \\<equiv> Group H \\<and> H \\<subseteq> G\"\n\nlemma SubgroupD1: \"Subgroup H \\<Longrightarrow> Group H\" by fast\n\nlemma zero_closed : \"0 \\<in> G\"\nproof-\n  from nonempty obtain g where \"g \\<in> G\" by fast\n  hence \"g - g \\<in> G\" using diff_closed by fast\n  thus ?thesis by simp\nqed\n\nlemma uminus_closed: \"g\\<in>G \\<Longrightarrow> -g\\<in>G\"\n  using zero_closed diff_closed[of 0 g] by simp\n\n\n\nlemma uminus_add_closed: \"g \\<in> G \\<Longrightarrow> h \\<in> G \\<Longrightarrow> -g + h \\<in> G\"\n  using uminus_closed add_closed by fast\n\nlemma lconjby_closed: \"g\\<in>G \\<Longrightarrow> x\\<in>G \\<Longrightarrow> lconjby g x \\<in> G\"\n  using add_closed diff_closed by fast\n\nlemma lconjby_set_closed: \"g\\<in>G \\<Longrightarrow> A\\<subseteq>G \\<Longrightarrow> lconjby g ` A \\<subseteq> G\"\n  using lconjby_closed by fast\n\nlemma set_lconjby_subset_closed:\n  \"H\\<subseteq>G \\<Longrightarrow> A\\<subseteq>G \\<Longrightarrow> (\\<Union>h\\<in>H. lconjby h ` A) \\<subseteq> G\"\n  using lconjby_set_closed[of _ A] by fast\n\nlemma sum_list_map_closed: \"set (map f as) \\<subseteq> G \\<Longrightarrow> (\\<Sum>a\\<leftarrow>as. f a) \\<in> G\"\n  using zero_closed add_closed by (induct as) auto\n\nlemma sum_list_closed: \"set as \\<subseteq> G \\<Longrightarrow> sum_list as \\<in> G\"\n    using sum_list_map_closed by force\n\nend (* context Group *)\n\nsubsubsection \\<open>Sets with a suitable binary operation\\<close>\n\ntext \\<open>\n  We have chosen to only consider groups in types of class @{class group_add} so that we can take\n  advantage of all the algebra lemmas already proven in @{theory HOL.Groups}, as well as\n  constructs like @{const sum_list}. The following locale builds a bridge between this restricted\n  view of groups and the usual notion of a binary operation on a set satisfying the group axioms,\n  by constructing an injective map into type @{type permutation} (which is of class\n  @{class group_add} with respect to the composition operation) that respects the group operation.\n  This bridge will be necessary to define quotient groups, in particular.\n\\<close>\n\nlocale BinOpSetGroup =\n  fixes G     :: \"'a set\"\n  and   binop :: \"'a\\<Rightarrow>'a\\<Rightarrow>'a\"\n  and   e     :: \"'a\"\n  assumes closed  : \"g\\<in>G \\<Longrightarrow> h\\<in>G \\<Longrightarrow> binop g h \\<in> G\"\n  and     assoc   :\n    \"\\<lbrakk> g\\<in>G; h\\<in>G; k\\<in>G \\<rbrakk> \\<Longrightarrow> binop (binop g h) k = binop g (binop h k)\"\n  and     identity: \"e\\<in>G\" \"g\\<in>G \\<Longrightarrow> binop g e = g\" \"g\\<in>G \\<Longrightarrow> binop e g = g\"\n  and     inverses: \"g\\<in>G \\<Longrightarrow> \\<exists>h\\<in>G. binop g h = e \\<and> binop h g = e\"\nbegin\n\nlemma unique_identity1: \"g\\<in>G \\<Longrightarrow> \\<forall>x\\<in>G. binop g x = x \\<Longrightarrow> g = e\"\n  using identity(1,2) by auto\n\nlemma unique_inverse:\n  assumes \"g\\<in>G\"\n  shows   \"\\<exists>!h. h\\<in>G \\<and> binop g h = e \\<and> binop h g = e\"\nproof (rule ex_ex1I)\n  from assms show \"\\<exists>h. h \\<in> G \\<and> binop g h = e \\<and> binop h g = e\"\n    using inverses by fast\nnext\n  fix h k\n  assume \"h\\<in>G \\<and> binop g h = e \\<and> binop h g = e\" \"k\\<in>G \\<and>\n            binop g k = e \\<and> binop k g = e\"\n  hence h: \"h\\<in>G\" \"binop g h = e\" \"binop h g = e\"\n    and k: \"k\\<in>G\" \"binop g k = e\" \"binop k g = e\"\n    by  auto\n  from assms h(1,3) k(1,2) show \"h=k\" using identity(2,3) assoc by force\nqed\n\nabbreviation \"G_perm g \\<equiv> restrict1 (binop g) G\"\n\ndefinition Abs_G_perm :: \"'a \\<Rightarrow> 'a permutation\"\n  where \"Abs_G_perm g \\<equiv> Abs_permutation (G_perm g)\"\n\nabbreviation \"\\<pp> \\<equiv> Abs_G_perm\" \\<comment> \\<open>the injection into type @{type permutation}\\<close>\nabbreviation \"\\<ii>\\<pp> \\<equiv> the_inv_into G \\<pp>\" \\<comment> \\<open>the reverse correspondence\\<close>\nabbreviation \"pG \\<equiv> \\<pp>`G\" \\<comment> \\<open>the resulting @{const Group} of type @{type permutation}\\<close>\n\nlemma G_perm_comp:\n  \"g\\<in>G \\<Longrightarrow> h\\<in>G \\<Longrightarrow> G_perm g \\<circ> G_perm h = G_perm (binop g h)\"\n  using closed by (auto simp add: assoc)\n\ndefinition the_inverse :: \"'a \\<Rightarrow> 'a\"\n  where \"the_inverse g \\<equiv> (THE h. h\\<in>G \\<and> binop g h = e \\<and> binop h g = e)\"\n\nabbreviation \"\\<ii> \\<equiv> the_inverse\"\n\nlemma the_inverseD:\n  assumes   \"g\\<in>G\"\n  shows     \"\\<ii> g \\<in> G\" \"binop g (\\<ii> g) = e\" \"binop (\\<ii> g) g = e\"\n  using     assms theI'[OF unique_inverse]\n  unfolding the_inverse_def\n  by        auto\n\nlemma binop_G_comp_binop_\\<ii>G: \"g\\<in>G \\<Longrightarrow> x\\<in>G \\<Longrightarrow> binop g (binop (\\<ii> g) x) = x\"\n  using the_inverseD(1) assoc[of g \"\\<ii> g\" x] by (simp add: identity(3) the_inverseD(2))\n\nlemma bij_betw_binop_G:\n  assumes   \"g\\<in>G\"\n  shows     \"bij_betw (binop g) G G\"\n  unfolding bij_betw_def\nproof\n  show \"inj_on (binop g) G\"\n  proof (rule inj_onI)\n    fix h k assume hk: \"h\\<in>G\" \"k\\<in>G\" \"binop g h = binop g k\"\n    with assms have \"binop (binop (\\<ii> g) g) h = binop (binop (\\<ii> g) g) k\"\n      using the_inverseD(1) by (simp add: assoc)\n    with assms hk(1,2) show \"h=k\" using the_inverseD(3) identity by simp\n  qed\n  show \"binop g ` G = G\"\n  proof\n    from assms show \"binop g ` G \\<subseteq> G\" using closed by fast\n    from assms show \"binop g ` G \\<supseteq> G\"\n      using binop_G_comp_binop_\\<ii>G[THEN sym] the_inverseD(1) closed by fast\n  qed\nqed\n\nlemma the_inv_into_G_binop_G:\n  assumes \"g\\<in>G\" \"x\\<in>G\"\n  shows   \"the_inv_into G (binop g) x = binop (\\<ii> g) x\"\nproof (rule the_inv_into_f_eq)\n  from assms(1) show \"inj_on (binop g) G\"\n    using bij_betw_imp_inj_on[OF bij_betw_binop_G] by fast\n  from assms show \"binop g (binop (\\<ii> g) x) = x\"\n    using binop_G_comp_binop_\\<ii>G by fast\n  from assms show \"binop (\\<ii> g) x \\<in> G\" using closed the_inverseD(1) by fast\nqed\n\nlemma restrict1_the_inv_into_G_binop_G:\n  \"g\\<in>G \\<Longrightarrow> restrict1 (the_inv_into G (binop g)) G = G_perm (\\<ii> g)\"\n  using the_inv_into_G_binop_G by auto\n\nlemma bij_G_perm: \"g\\<in>G \\<Longrightarrow> bij (G_perm g)\"\n  using set_permutation_bij_restrict1 bij_betw_binop_G by fast\n\nlemma G_perm_apply: \"g\\<in>G \\<Longrightarrow> x\\<in>G \\<Longrightarrow> \\<pp> g \\<rightarrow> x = binop g x\"\n  using Abs_G_perm_def Abs_permutation_inverse bij_G_perm by fastforce\n\nlemma G_perm_apply_identity: \"g\\<in>G \\<Longrightarrow> \\<pp> g \\<rightarrow> e = g\"\n  using G_perm_apply identity(1,2) by simp\n\nlemma the_inv_G_perm:\n  \"g\\<in>G \\<Longrightarrow> the_inv (G_perm g) = G_perm (\\<ii> g)\"\n  using set_permutation_the_inv_restrict1 bij_betw_binop_G\n        restrict1_the_inv_into_G_binop_G\n  by    fastforce\n\nlemma Abs_G_perm_diff:\n  \"g\\<in>G \\<Longrightarrow> h\\<in>G \\<Longrightarrow> \\<pp> g - \\<pp> h = \\<pp> (binop g (\\<ii> h))\"\n  using Abs_G_perm_def minus_permutation_abs_eq[OF bij_G_perm bij_G_perm]\n        the_inv_G_perm G_perm_comp the_inverseD(1)\n  by    simp\n\nlemma Group: \"Group pG\"\n  using identity(1) Abs_G_perm_diff the_inverseD(1) closed by unfold_locales auto\n\nlemma inj_on_\\<pp>_G: \"inj_on \\<pp> G\"\nproof (rule inj_onI)\n  fix x y assume xy: \"x\\<in>G\" \"y\\<in>G\" \"\\<pp> x = \\<pp> y\"\n  hence \"Abs_permutation (G_perm (binop x (\\<ii> y))) = Abs_permutation id\"\n    using Abs_G_perm_diff Abs_G_perm_def\n    by (fastforce simp add: zero_permutation.abs_eq)\n  moreover from xy(1,2) have 1: \"binop x (\\<ii> y) \\<in> G\"\n    using bij_id closed the_inverseD(1) by fast\n  ultimately have 2: \"G_perm (binop x (\\<ii> y)) = id\"\n    using Abs_permutation_inject[of \"G_perm (binop x (\\<ii> y))\"] bij_G_perm bij_id\n    by    simp\n  have \"\\<forall>z\\<in>G. binop (binop x (\\<ii> y)) z = z\"\n  proof\n    fix z assume \"z\\<in>G\"\n    thus \"binop (binop x (\\<ii> y)) z = z\" using fun_cong[OF 2, of z] by simp\n  qed\n  with xy(1,2) have \"binop x (binop (\\<ii> y) y) = y\"\n    using unique_identity1[OF 1] the_inverseD(1) by (simp add: assoc)\n  with xy(1,2) show \"x = y\" using the_inverseD(3) identity(2) by simp\nqed\n\nlemma homs:\n  \"\\<And>g h. g\\<in>G \\<Longrightarrow> h\\<in>G \\<Longrightarrow> \\<pp> (binop g h) = \\<pp> g + \\<pp> h\"\n  \"\\<And>x y. x\\<in>pG \\<Longrightarrow> y\\<in>pG \\<Longrightarrow> binop (\\<ii>\\<pp> x) (\\<ii>\\<pp> y) = \\<ii>\\<pp> (x+y)\"\nproof-\n  show 1: \"\\<And>g h. g\\<in>G \\<Longrightarrow> h\\<in>G \\<Longrightarrow> \\<pp> (binop g h) = \\<pp> g + \\<pp> h\"\n    using Abs_G_perm_def G_perm_comp\n          plus_permutation_abs_eq[OF bij_G_perm bij_G_perm]\n    by    simp\n  show \"\\<And>x y. x\\<in>pG \\<Longrightarrow> y\\<in>pG \\<Longrightarrow> binop (\\<ii>\\<pp> x) (\\<ii>\\<pp> y) = \\<ii>\\<pp> (x+y)\"\n  proof-\n    fix x y assume \"x\\<in>pG\" \"y\\<in>pG\"\n    moreover hence \"\\<ii>\\<pp> (\\<pp> (binop (\\<ii>\\<pp> x) (\\<ii>\\<pp> y))) = \\<ii>\\<pp> (x + y)\"\n      using 1 the_inv_into_into[OF inj_on_\\<pp>_G] f_the_inv_into_f[OF inj_on_\\<pp>_G]\n      by    simp\n    ultimately show \"binop (\\<ii>\\<pp> x) (\\<ii>\\<pp> y) = \\<ii>\\<pp> (x+y)\" \n      using the_inv_into_into[OF inj_on_\\<pp>_G] closed the_inv_into_f_f[OF inj_on_\\<pp>_G]\n      by    simp\n  qed\nqed\n\nlemmas inv_correspondence_into =\n  the_inv_into_into[OF inj_on_\\<pp>_G, of _ G, simplified]\n\nlemma inv_correspondence_conv_apply: \"x \\<in> pG \\<Longrightarrow> \\<ii>\\<pp> x = x\\<rightarrow>e\"\n  using G_perm_apply_identity inj_on_\\<pp>_G by (auto intro: the_inv_into_f_eq)\n\nend (* context BinOpSetGroup *)\n\n\nsubsubsection \\<open>Cosets of a @{const Group}\\<close>\n\ncontext Group\nbegin\n\nlemma lcoset_refl: \"a \\<in> a +o G\"\n  using lcoset_refl zero_closed by fast\n\nlemma lcoset_el_reduce:\n  assumes \"a \\<in> G\"\n  shows \"a +o G = G\"\nproof (rule seteqI)\n  fix x assume \"x \\<in> a +o G\"\n  from this obtain g where \"g\\<in>G\" \"x = a+g\" using elt_set_plus_def[of a] by auto\n  with assms show \"x\\<in>G\" by (simp add: add_closed)\nnext\n  fix x assume \"x\\<in>G\"\n  with assms have \"-a + x \\<in> G\" by (simp add: uminus_add_closed)\n  thus \"x \\<in> a +o G\" using elt_set_plus_def by force\nqed\n\nlemma lcoset_el_reduce0: \"0 \\<in> a +o G \\<Longrightarrow> a +o G = G\"\n  using elt_set_plus_def[of a G] minus_unique uminus_closed[of \"-a\"]\n        lcoset_el_reduce\n  by    fastforce\n\nlemma lcoset_subgroup_imp_eq_reps:\n  \"Group H \\<Longrightarrow> w +o H \\<subseteq> w' +o G \\<Longrightarrow> w' +o G = w +o G\"\n  using Group.lcoset_refl[of H w] lcoset_conv_set[of w] lcoset_el_reduce\n        set_plus_rearrange2[of w' \"-w'+w\" G]\n  by    force\n\nlemma lcoset_closed: \"a\\<in>G \\<Longrightarrow> A\\<subseteq>G \\<Longrightarrow> a +o A \\<subseteq> G\"\n  using elt_set_plus_def[of a] add_closed by auto\n\nlemma lcoset_rel_sym: \"sym (lcoset_rel G)\"\nproof (rule symI)\n  fix a b show \"(a,b) \\<in> lcoset_rel G \\<Longrightarrow> (b,a) \\<in> lcoset_rel G\"\n    using uminus_closed minus_add[of \"-a\" b] lcoset_rel_def[of G] by fastforce\nqed\n\nlemma lcoset_rel_trans: \"trans (lcoset_rel G)\"\nproof (rule transI)\n  fix x y z assume xy: \"(x,y) \\<in> lcoset_rel G\" and yz: \"(y,z) \\<in> lcoset_rel G\"\n  from this obtain g g' where \"g\\<in>G\" \"-x+y = g\" \"g'\\<in>G\" \"-y+z = g'\"\n    using lcoset_rel_def[of G] by fast\n  thus \"(x, z) \\<in> lcoset_rel G\"\n    using add.assoc[of g \"-y\" z] add_closed lcoset_rel_def[of G] by auto\nqed\n\nabbreviation LCoset_rel :: \"'g set \\<Rightarrow> ('g\\<times>'g) set\"\n  where \"LCoset_rel H \\<equiv> lcoset_rel H \\<inter> (G\\<times>G)\"\n\nlemma refl_on_LCoset_rel: \"0\\<in>H \\<Longrightarrow> refl_on G (LCoset_rel H)\"\n  using lcoset_rel_def by (fastforce intro: refl_onI)\n\nlemmas subgroup_refl_on_LCoset_rel =\n  refl_on_LCoset_rel[OF Group.zero_closed, OF SubgroupD1]\nlemmas LCoset_rel_quotientI        = quotientI[of _ G \"LCoset_rel _\"]\nlemmas LCoset_rel_quotientE        = quotientE[of _ G \"LCoset_rel _\"]\n\nlemma lcoset_subgroup_rel_equiv:\n  \"Subgroup H \\<Longrightarrow> equiv G (LCoset_rel H)\"\n  using Group.lcoset_rel_sym sym_sym sym_Int Group.lcoset_rel_trans trans_sym\n        trans_Int subgroup_refl_on_LCoset_rel\n  by    (blast intro: equivI)\n\nlemma trivial_LCoset: \"H\\<subseteq>G \\<Longrightarrow> H = LCoset_rel H `` {0}\"\n  using zero_closed unfolding lcoset_rel_def by auto\n\nend (* context Group *)\n\nsubsubsection \\<open>The @{const Group} generated by a set\\<close>\n\ninductive_set genby :: \"'a::group_add set \\<Rightarrow> 'a set\" (\"\\<langle>_\\<rangle>\")\n  for S :: \"'a set\"\n  where\n      genby_0_closed     : \"0\\<in>\\<langle>S\\<rangle>\"  \\<comment> \\<open>just in case @{term S} is empty\\<close>\n    | genby_genset_closed: \"s\\<in>S \\<Longrightarrow> s\\<in>\\<langle>S\\<rangle>\"\n    | genby_diff_closed  : \"w\\<in>\\<langle>S\\<rangle> \\<Longrightarrow> w'\\<in>\\<langle>S\\<rangle> \\<Longrightarrow> w - w' \\<in> \\<langle>S\\<rangle>\"\n\nlemma genby_Group: \"Group \\<langle>S\\<rangle>\"\n  using genby_0_closed genby_diff_closed by unfold_locales fast\n\nlemmas genby_uminus_closed             = Group.uminus_closed     [OF genby_Group]\nlemmas genby_add_closed                = Group.add_closed        [OF genby_Group]\nlemmas genby_uminus_add_closed         = Group.uminus_add_closed [OF genby_Group]\nlemmas genby_lcoset_refl               = Group.lcoset_refl       [OF genby_Group]\nlemmas genby_lcoset_el_reduce          = Group.lcoset_el_reduce  [OF genby_Group]\nlemmas genby_lcoset_el_reduce0         = Group.lcoset_el_reduce0 [OF genby_Group]\nlemmas genby_lcoset_closed             = Group.lcoset_closed     [OF genby_Group]\n\nlemmas genby_lcoset_subgroup_imp_eq_reps =\n  Group.lcoset_subgroup_imp_eq_reps[OF genby_Group, OF genby_Group]\n\nlemma genby_genset_subset: \"S \\<subseteq> \\<langle>S\\<rangle>\"\n  using genby_genset_closed by fast\n\nlemma genby_uminus_genset_subset: \"uminus ` S \\<subseteq> \\<langle>S\\<rangle>\"\n  using genby_genset_subset genby_uminus_closed by auto\n\nlemma genby_in_sum_list_lists:\n  fixes   S\n  defines S_sum_lists: \"S_sum_lists \\<equiv> (\\<Union>ss\\<in>lists (S \\<union> uminus ` S). {sum_list ss})\"\n  shows   \"w \\<in> \\<langle>S\\<rangle> \\<Longrightarrow> w \\<in> S_sum_lists\"\nproof (erule genby.induct)\n  have \"0 = sum_list []\" by simp\n  with S_sum_lists show \"0 \\<in> S_sum_lists\" by blast\nnext\n  fix s assume \"s\\<in>S\"\n  hence \"[s] \\<in> lists (S \\<union> uminus ` S)\" by simp\n  moreover have \"s = sum_list [s]\" by simp\n  ultimately show \"s \\<in> S_sum_lists\" using S_sum_lists by blast\nnext\n  fix w w' assume ww': \"w \\<in> S_sum_lists\" \"w' \\<in> S_sum_lists\"\n  with S_sum_lists obtain ss ts\n    where ss: \"ss \\<in> lists (S \\<union> uminus ` S)\" \"w = sum_list ss\"\n    and   ts: \"ts \\<in> lists (S \\<union> uminus ` S)\" \"w' = sum_list ts\"\n    by fastforce\n  from ss(2) ts(2) have \"w-w' = sum_list (ss @ map uminus (rev ts))\"\n    by (simp add: diff_conv_add_uminus uminus_sum_list)\n  moreover from ss(1) ts(1)\n    have  \"ss @ map uminus (rev ts) \\<in> lists (S \\<union> uminus ` S)\"\n    by    fastforce\n  ultimately show \"w - w' \\<in> S_sum_lists\" using S_sum_lists by fast\nqed\n\nlemma sum_list_lists_in_genby: \"ss \\<in> lists (S \\<union> uminus ` S) \\<Longrightarrow> sum_list ss \\<in> \\<langle>S\\<rangle>\"\nproof (induct ss)\n  case Nil show ?case using genby_0_closed by simp\nnext\n  case (Cons s ss) thus ?case\n    using genby_genset_subset[of S] genby_uminus_genset_subset\n          genby_add_closed[of s S \"sum_list ss\"]\n    by    auto\nqed\n\nlemma sum_list_lists_in_genby_sym:\n  \"uminus ` S \\<subseteq> S \\<Longrightarrow> ss \\<in> lists S \\<Longrightarrow> sum_list ss \\<in> \\<langle>S\\<rangle>\"\n  using sum_list_lists_in_genby by fast\n\nlemma genby_eq_sum_lists: \"\\<langle>S\\<rangle> = (\\<Union>ss\\<in>lists (S \\<union> uminus ` S). {sum_list ss})\"\n  using genby_in_sum_list_lists sum_list_lists_in_genby by fast\n\nlemma genby_mono: \"T \\<subseteq> S \\<Longrightarrow> \\<langle>T\\<rangle> \\<subseteq> \\<langle>S\\<rangle>\"\n  using genby_eq_sum_lists[of T] genby_eq_sum_lists[of S] by force\n\nlemma (in Group) genby_closed:\n  assumes \"S \\<subseteq> G\"\n  shows \"\\<langle>S\\<rangle> \\<subseteq> G\"\nproof\n  fix x show \"x \\<in> \\<langle>S\\<rangle> \\<Longrightarrow> x \\<in> G\"\n  proof (erule genby.induct, rule zero_closed)\n    from assms show \"\\<And>s. s\\<in>S \\<Longrightarrow> s\\<in>G\" by fast\n    show \"\\<And>w w'. w\\<in>G \\<Longrightarrow> w'\\<in>G \\<Longrightarrow> w-w' \\<in> G\" using diff_closed by fast\n  qed\nqed\n\nlemma (in Group) genby_subgroup: \"S \\<subseteq> G \\<Longrightarrow> Subgroup \\<langle>S\\<rangle>\"\n  using genby_closed genby_Group by simp\n\nlemma genby_sym_eq_sum_lists:\n  \"uminus ` S \\<subseteq> S \\<Longrightarrow> \\<langle>S\\<rangle> = (\\<Union>ss\\<in>lists S. {sum_list ss})\"\n  using lists_mono genby_eq_sum_lists[of S] by force\n\nlemma genby_empty': \"w \\<in> \\<langle>{}\\<rangle> \\<Longrightarrow> w = 0\"\nproof (erule genby.induct) qed auto\n\nlemma genby_order2':\n  assumes \"s+s=0\"\n  shows   \"w \\<in> \\<langle>{s}\\<rangle> \\<Longrightarrow> w = 0 \\<or> w = s\"\nproof (erule genby.induct)\n  fix w w' assume \"w = 0 \\<or> w = s\" \"w' = 0 \\<or> w' = s\"\n  with assms show \"w - w' = 0 \\<or> w - w' = s\"\n    by (cases \"w'=0\") (auto simp add: minus_unique)\nqed auto\n\nlemma genby_order2: \"s+s=0 \\<Longrightarrow> \\<langle>{s}\\<rangle> = {0,s}\"\n  using genby_order2'[of s] genby_0_closed genby_genset_closed by auto\n\nlemma genby_empty: \"\\<langle>{}\\<rangle> = 0\"\n  using genby_empty' genby_0_closed by auto\n\nlemma genby_lcoset_order2: \"s+s=0 \\<Longrightarrow> w +o \\<langle>{s}\\<rangle> = {w,w+s}\"\n  using elt_set_plus_def[of w] by (auto simp add: genby_order2)\n\nlemma genby_lcoset_empty: \"(w::'a::group_add) +o \\<langle>{}\\<rangle> = {w}\"\nproof-\n  have \"\\<langle>{}::'a set\\<rangle> = (0::'a set)\" using genby_empty by fast\n  thus ?thesis using lcoset_0 by simp\nqed\n\nlemma (in Group) genby_set_lconjby_set_lconjby_closed:\n  fixes   A :: \"'g set\"\n  defines \"S \\<equiv> (\\<Union>g\\<in>G. lconjby g ` A)\"\n  assumes \"g\\<in>G\"\n  shows   \"x \\<in> \\<langle>S\\<rangle> \\<Longrightarrow> lconjby g x \\<in> \\<langle>S\\<rangle>\"\nproof (erule genby.induct)\n  show \"lconjby g 0 \\<in> \\<langle>S\\<rangle>\" using genby_0_closed by simp\n  from assms show \"\\<And>s. s \\<in> S \\<Longrightarrow> lconjby g s \\<in> \\<langle>S\\<rangle>\"\n    using add_closed genby_genset_closed[of _ S] by (force simp add: lconjby_add)\nnext\n  fix w w'\n  assume ww': \"lconjby g w \\<in> \\<langle>S\\<rangle>\" \"lconjby g w' \\<in> \\<langle>S\\<rangle>\"\n  have \"lconjby g (w - w') = lconjby g w + lconjby g (-w')\"\n    by (simp add: algebra_simps)\n  with ww' show \"lconjby g (w - w') \\<in> \\<langle>S\\<rangle>\"\n    using lconjby_uminus[of g] diff_conv_add_uminus[of _ \"lconjby g w'\"]\n          genby_diff_closed\n    by    fastforce\nqed\n\nlemma (in Group) genby_set_lconjby_set_rconjby_closed:\n  fixes   A :: \"'g set\"\n  defines \"S \\<equiv> (\\<Union>g\\<in>G. lconjby g ` A)\"\n  assumes \"g\\<in>G\" \"x \\<in> \\<langle>S\\<rangle>\"\n  shows   \"rconjby g x \\<in> \\<langle>S\\<rangle>\"\n  using   assms uminus_closed genby_set_lconjby_set_lconjby_closed\n  by      fastforce\n\nsubsubsection \\<open>Homomorphisms and isomorphisms\\<close>\n\nlocale GroupHom = Group G\n  for   G :: \"'g::group_add set\"\n+ fixes T :: \"'g \\<Rightarrow> 'h::group_add\"\n  assumes hom : \"g \\<in> G \\<Longrightarrow> g' \\<in> G \\<Longrightarrow> T (g + g') = T g + T g'\"\n  and     supp: \"supp T \\<subseteq> G\" \nbegin\n\nlemma im_zero: \"T 0 = 0\"\n  using zero_closed hom[of 0 0] add_diff_cancel[of \"T 0\" \"T 0\"] by simp\n\nlemma im_uminus: \"T (- g) = - T g\"\n  using im_zero hom[of g \"- g\"] uminus_closed[of g] minus_unique[of \"T g\"]\n        uminus_closed[of \"-g\"] supp suppI_contra[of g T]\n        suppI_contra[of \"-g\" T]\n  by    fastforce\n\nlemma im_uminus_add: \"g \\<in> G \\<Longrightarrow> g' \\<in> G \\<Longrightarrow> T (-g + g') = - T g + T g'\"\n  by (simp add: uminus_closed hom im_uminus)\n\nlemma im_diff: \"g \\<in> G \\<Longrightarrow> g' \\<in> G \\<Longrightarrow> T (g - g') = T g - T g'\"\n  using hom uminus_closed hom[of g \"-g'\"] im_uminus by simp\n\nlemma im_lconjby: \"x \\<in> G \\<Longrightarrow> g \\<in> G \\<Longrightarrow> T (lconjby x g) = lconjby (T x) (T g)\"\n  using add_closed by (simp add: im_diff hom)\n\nlemma im_sum_list_map:\n  \"set (map f as) \\<subseteq> G \\<Longrightarrow> T (\\<Sum>a\\<leftarrow>as. f a) = (\\<Sum>a\\<leftarrow>as. T (f a))\"\n  using hom im_zero sum_list_closed by (induct as) auto\n\nlemma comp:\n  assumes \"GroupHom H S\" \"T`G \\<subseteq> H\" \n  shows   \"GroupHom G (S \\<circ> T)\"\nproof\n  fix g g' assume \"g \\<in> G\" \"g' \\<in> G\"\n  with hom assms(2) show \"(S \\<circ> T) (g + g') = (S \\<circ> T) g + (S \\<circ> T) g'\"\n    using GroupHom.hom[OF assms(1)] by fastforce\nnext\n  from supp have \"\\<And>g. g \\<notin> G \\<Longrightarrow> (S \\<circ> T) g = 0\"\n    using suppI_contra GroupHom.im_zero[OF assms(1)] by fastforce\n  thus \"supp (S \\<circ> T) \\<subseteq> G\" using suppD_contra by fast\nqed\n\nend (* context GroupHom *)\n\n\ndefinition ker :: \"('a\\<Rightarrow>'b::zero) \\<Rightarrow> 'a set\"\n  where \"ker f = {a. f a = 0}\"\n\nlemma ker_subset_ker_restrict0: \"ker f \\<subseteq> ker (restrict0 f A)\"\n  unfolding ker_def by auto\n\ncontext GroupHom\nbegin\n\nabbreviation \"Ker \\<equiv> ker T \\<inter> G\"\n\nlemma uminus_add_in_Ker_eq_eq_im:\n  \"g\\<in>G \\<Longrightarrow> h\\<in>G \\<Longrightarrow> (-g + h \\<in> Ker) = (T g = T h)\"\n  using neg_equal_iff_equal\n  by    (simp add: uminus_add_closed ker_def im_uminus_add eq_neg_iff_add_eq_0)\n\nend (* context GroupHom *)\n\nlocale UGroupHom = GroupHom UNIV T\n  for T :: \"'g::group_add \\<Rightarrow> 'h::group_add\"\nbegin\n\nlemmas im_zero       = im_zero\nlemmas im_uminus     = im_uminus\n\nlemma hom: \"T (g+g') = T g + T g'\"\n  using hom by simp\n\nlemma im_diff: \"T (g - g') = T g - T g'\"\n  using im_diff by simp\n\nlemma im_lconjby: \"T (lconjby x g) = lconjby (T x) (T g)\"\n  using im_lconjby by simp\n\nlemma restrict0:\n  assumes \"Group G\"\n  shows   \"GroupHom G (restrict0 T G)\"\nproof (intro_locales, rule assms, unfold_locales)\n  from hom \n    show  \"\\<And>g g'. g \\<in> G \\<Longrightarrow> g' \\<in> G \\<Longrightarrow>\n            restrict0 T G (g + g') = restrict0 T G g + restrict0 T G g'\"\n    using Group.add_closed[OF assms]\n    by    auto\n  show \"supp (restrict0 T G) \\<subseteq> G\" using supp_restrict0[of G T] by fast\nqed\n\nend (* context UGroupHom *)\n\nlemma UGroupHomI:\n  assumes \"\\<And>g g'. T (g + g') = T g + T g'\"\n  shows   \"UGroupHom T\"\n  using   assms\n  by      unfold_locales auto\n\nlocale GroupIso = GroupHom G T\n  for   G :: \"'g::group_add set\"\n  and   T :: \"'g \\<Rightarrow> 'h::group_add\"\n+ assumes inj_on: \"inj_on T G\"\n\nlemma (in GroupHom) isoI:\n  assumes \"\\<And>k. k\\<in>G \\<Longrightarrow> T k = 0 \\<Longrightarrow> k=0\"\n  shows   \"GroupIso G T\"\nproof (unfold_locales, rule inj_onI)\n  fix x y from assms show \"\\<lbrakk> x\\<in>G; y\\<in>G; T x = T y \\<rbrakk> \\<Longrightarrow> x = y\"\n    using im_diff diff_closed by force\nqed\n\ntext \\<open>\n  In a @{const BinOpSetGroup}, any map from the set into a type of class @{class group_add} that respects the\n  binary operation induces a @{const GroupHom}.\n\\<close>\n\nabbreviation (in BinOpSetGroup) \"lift_hom T \\<equiv> restrict0 (T \\<circ> \\<ii>\\<pp>) pG\"\n\nlemma (in BinOpSetGroup) lift_hom:\n  fixes T :: \"'a \\<Rightarrow> 'b::group_add\"\n  assumes \"\\<forall>g\\<in>G. \\<forall>h\\<in>G. T (binop g h) = T g + T h\"\n  shows   \"GroupHom pG (lift_hom T)\"\nproof (intro_locales, rule Group, unfold_locales)\n  from assms\n    show  \"\\<And>x y. x\\<in>pG \\<Longrightarrow> y\\<in>pG \\<Longrightarrow>\n            lift_hom T (x+y) = lift_hom T x + lift_hom T y\"\n    using Group.add_closed[OF Group] inv_correspondence_into\n    by    (simp add: homs(2)[THEN sym])\nqed (rule supp_restrict0)\n\n\n\n\nsubsubsection \\<open>Normal subgroups\\<close>\n\ndefinition rcoset_rel :: \"'a::{minus,plus} set \\<Rightarrow> ('a\\<times>'a) set\"\n  where \"rcoset_rel A \\<equiv> {(x,y). x-y \\<in> A}\"\n\ncontext Group\nbegin\n\nlemma rcoset_rel_conv_lcoset_rel:\n  \"rcoset_rel G = map_prod uminus uminus ` (lcoset_rel G)\"\nproof (rule set_eqI)\n  fix x :: \"'g\\<times>'g\"\n  obtain a b where ab: \"x=(a,b)\" by fastforce\n  hence \"(x \\<in> rcoset_rel G) = (a-b \\<in> G)\"  using rcoset_rel_def by auto\n  also have \"\\<dots> = ( (-b,-a) \\<in> lcoset_rel G )\"\n    using uminus_closed lcoset_rel_def by fastforce\n  finally\n    show  \"(x \\<in> rcoset_rel G) = (x \\<in> map_prod uminus uminus ` (lcoset_rel G))\"\n    using ab symD[OF lcoset_rel_sym] map_prod_def\n    by    force\nqed\n\nlemma rcoset_rel_sym: \"sym (rcoset_rel G)\"\n  using rcoset_rel_conv_lcoset_rel map_prod_sym lcoset_rel_sym by simp\n\nabbreviation RCoset_rel :: \"'g set \\<Rightarrow> ('g\\<times>'g) set\"\n  where \"RCoset_rel H \\<equiv> rcoset_rel H \\<inter> (G\\<times>G)\"\n\ndefinition normal :: \"'g set \\<Rightarrow> bool\"\n  where \"normal H \\<equiv> (\\<forall>g\\<in>G. LCoset_rel H `` {g} = RCoset_rel H `` {g})\"\n\nlemma normalI:\n  assumes   \"Group H\" \"\\<forall>g\\<in>G. \\<forall>h\\<in>H. \\<exists>h'\\<in>H. g+h = h'+g\"\n            \"\\<forall>g\\<in>G. \\<forall>h\\<in>H. \\<exists>h'\\<in>H. h+g = g+h'\"\n  shows     \"normal H\"\n  unfolding normal_def\nproof\n  fix g assume g: \"g\\<in>G\"\n  show \"LCoset_rel H `` {g} = RCoset_rel H `` {g}\"\n  proof (rule seteqI)\n    fix x assume \"x \\<in> LCoset_rel H `` {g}\"\n    with g have x: \"x\\<in>G\" \"-g+x \\<in> H\" unfolding lcoset_rel_def by auto\n    from g x(2) assms(2) obtain h where h: \"h\\<in>H\" \"g-x = -h\"\n    by   (fastforce simp add: algebra_simps)\n    with assms(1) g x(1) show \"x \\<in> RCoset_rel H `` {g}\"\n      using Group.uminus_closed unfolding rcoset_rel_def by simp\n  next\n    fix x assume \"x \\<in> RCoset_rel H `` {g}\"\n    with g have x: \"x\\<in>G\" \"g-x \\<in> H\" unfolding rcoset_rel_def by auto\n    with assms(3) obtain h where h: \"h\\<in>H\" \"-g+x = -h\"\n      by (fastforce simp add: algebra_simps minus_add)\n    with assms(1) g x(1) show \"x \\<in> LCoset_rel H `` {g}\"\n      using Group.uminus_closed unfolding lcoset_rel_def by simp\n  qed\nqed\n\nlemma normal_lconjby_closed:\n  \"\\<lbrakk> Subgroup H; normal H; g\\<in>G; h\\<in>H \\<rbrakk> \\<Longrightarrow> lconjby g h \\<in> H\"\n  using lcoset_relI[of g \"g+h\" H] add_closed[of g h] normal_def[of H]\n        symD[OF Group.rcoset_rel_sym, of H g \"g+h\"] rcoset_rel_def[of H]\n  by    auto\n\nlemma normal_rconjby_closed:\n  \"\\<lbrakk> Subgroup H; normal H; g\\<in>G; h\\<in>H \\<rbrakk> \\<Longrightarrow> rconjby g h \\<in> H\"\n  using normal_lconjby_closed[of H \"-g\" h] uminus_closed[of g] by auto\n\nabbreviation \"normal_closure A \\<equiv> \\<langle>\\<Union>g\\<in>G. lconjby g ` A\\<rangle>\"\n\nlemma (in Group) normal_closure:\n  assumes \"A\\<subseteq>G\"\n  shows   \"normal (normal_closure A)\"\nproof (rule normalI, rule genby_Group)\n  show \"\\<forall>x\\<in>G. \\<forall>h\\<in>\\<langle>\\<Union>g\\<in>G. lconjby g ` A\\<rangle>.\n        \\<exists>h'\\<in>\\<langle>\\<Union>g\\<in>G. lconjby g ` A\\<rangle>. x + h = h' + x\"\n  proof\n    fix x assume x: \"x\\<in>G\"\n    show \"\\<forall>h\\<in>\\<langle>\\<Union>g\\<in>G. lconjby g ` A\\<rangle>.\n          \\<exists>h'\\<in>\\<langle>\\<Union>g\\<in>G. lconjby g ` A\\<rangle>. x + h = h' + x\"\n    proof (rule ballI, erule genby.induct)\n      show \"\\<exists>h\\<in>\\<langle>\\<Union>g\\<in>G. lconjby g ` A\\<rangle>. x + 0 = h + x\"\n        using genby_0_closed by force\n    next\n      fix s assume \"s \\<in> (\\<Union>g\\<in>G. lconjby g ` A)\"\n      from this obtain g a where ga: \"g\\<in>G\" \"a\\<in>A\" \"s = lconjby g a\" by fast\n      from ga(3) have \"x + s = lconjby x (lconjby g a) + x\"\n        by (simp add: algebra_simps)\n      hence \"x + s = lconjby (x+g) a + x\" by (simp add: lconjby_add)\n      with x ga(1,2) show \"\\<exists>h\\<in>\\<langle>\\<Union>g\\<in>G. lconjby g ` A\\<rangle>. x + s = h + x\"\n        using add_closed by (blast intro: genby_genset_closed)\n    next\n      fix w w'\n      assume w :  \"w \\<in> \\<langle>\\<Union>g\\<in>G. lconjby g ` A\\<rangle>\"\n                  \"\\<exists>h \\<in>\\<langle>\\<Union>g\\<in>G. lconjby g ` A\\<rangle>. x + w  = h + x\"\n        and  w':  \"w'\\<in> \\<langle>\\<Union>g\\<in>G. lconjby g ` A\\<rangle>\"\n                  \"\\<exists>h'\\<in>\\<langle>\\<Union>g\\<in>G. lconjby g ` A\\<rangle>. x + w' = h'+ x\"\n      from w(2) w'(2) obtain h h'\n        where h : \"h \\<in> \\<langle>\\<Union>g\\<in>G. lconjby g ` A\\<rangle>\" \"x + w  = h + x\"\n        and   h': \"h'\\<in> \\<langle>\\<Union>g\\<in>G. lconjby g ` A\\<rangle>\" \"x + w' = h'+ x\"\n        by    fast\n      have \"x + (w - w') = x + w - (-x + (x + w'))\"\n        by (simp add: algebra_simps)\n      also from h(2) h'(2) have \"\\<dots> = h + x + (-(h' + x) + x)\"\n        by (simp add: algebra_simps)\n      also have \"\\<dots> = h + x + (-x + -h') + x\"\n        by (simp add: minus_add add.assoc)\n      finally have \"x + (w-w') = h - h' + x\"\n        using add.assoc[of \"h+x\" \"-x\" \"-h'\"] by simp\n      with h(1) h'(1)\n        show  \"\\<exists>h\\<in>\\<langle>\\<Union>g\\<in>G. lconjby g ` A\\<rangle>. x + (w - w') = h + x\"\n        using genby_diff_closed\n        by    fast\n    qed\n  qed\n  show \"\\<forall>x\\<in>G. \\<forall>h\\<in>\\<langle>\\<Union>g\\<in>G. lconjby g ` A\\<rangle>.\n        \\<exists>h'\\<in>\\<langle>\\<Union>g\\<in>G. lconjby g ` A\\<rangle>. h + x = x + h'\"\n  proof\n    fix x assume x: \"x\\<in>G\"\n    show \"\\<forall>h\\<in>\\<langle>\\<Union>g\\<in>G. lconjby g ` A\\<rangle>.\n            \\<exists>h'\\<in>\\<langle>\\<Union>g\\<in>G. lconjby g ` A\\<rangle>. h + x = x + h'\"\n    proof (rule ballI, erule genby.induct)\n      show \"\\<exists>h\\<in>\\<langle>\\<Union>g\\<in>G. lconjby g ` A\\<rangle>. 0 + x = x + h\"\n        using genby_0_closed by force\n    next\n      fix s assume \"s \\<in> (\\<Union>g\\<in>G. lconjby g ` A)\"\n      from this obtain g a where ga: \"g\\<in>G\" \"a\\<in>A\" \"s = lconjby g a\" by fast\n      from ga(3) have \"s + x = x + (((-x + g) + a) + -g) + x\"\n        by (simp add: algebra_simps)\n      also have \"\\<dots> = x + (-x + g + a + -g + x)\" by (simp add: add.assoc)\n      finally have \"s + x = x + lconjby (-x+g) a\"\n        by (simp add: algebra_simps lconjby_add)\n      with x ga(1,2) show \"\\<exists>h\\<in>\\<langle>\\<Union>g\\<in>G. lconjby g ` A\\<rangle>. s + x = x + h\"\n        using uminus_add_closed by (blast intro: genby_genset_closed)\n    next\n      fix w w'\n      assume w :  \"w \\<in> \\<langle>\\<Union>g\\<in>G. lconjby g ` A\\<rangle>\"\n                  \"\\<exists>h \\<in>\\<langle>\\<Union>g\\<in>G. lconjby g ` A\\<rangle>. w  + x = x + h\"\n        and  w':  \"w'\\<in> \\<langle>\\<Union>g\\<in>G. lconjby g ` A\\<rangle>\"\n                  \"\\<exists>h'\\<in>\\<langle>\\<Union>g\\<in>G. lconjby g ` A\\<rangle>. w' + x = x + h'\"\n      from w(2) w'(2) obtain h h'\n        where h : \"h \\<in> \\<langle>\\<Union>g\\<in>G. lconjby g ` A\\<rangle>\" \"w + x = x + h\"\n        and   h': \"h'\\<in> \\<langle>\\<Union>g\\<in>G. lconjby g ` A\\<rangle>\" \"w' + x = x + h'\"\n        by    fast\n      have \"w - w' + x = w + x + (-x + -w') + x\" by (simp add: algebra_simps)\n      also from h(2) h'(2) have \"\\<dots> = x + h + (-h'+-x) + x\" \n        using minus_add[of w' x] minus_add[of x h'] by simp\n      finally have \"w - w' + x = x + (h - h')\" by (simp add: algebra_simps)\n      with h(1) h'(1) show \"\\<exists>h\\<in>\\<langle>\\<Union>g\\<in>G. lconjby g ` A\\<rangle>. w - w' + x = x + h\"\n        using genby_diff_closed by fast\n    qed\n  qed\nqed \n\nend (* context Group *)\n\nsubsubsection \\<open>Quotient groups\\<close>\n\ntext \\<open>\n  Here we use the bridge built by @{const BinOpSetGroup} to make the quotient of a @{const Group}\n  by a normal subgroup into a @{const Group} itself.\n\\<close>\n\ncontext Group\nbegin\n\nlemma normal_quotient_add_well_defined:\n  assumes \"Subgroup H\" \"normal H\" \"g\\<in>G\" \"g'\\<in>G\"\n  shows   \"LCoset_rel H `` {g} + LCoset_rel H `` {g'} = LCoset_rel H `` {g+g'}\"\nproof (rule seteqI)\n  fix x assume \"x \\<in> LCoset_rel H `` {g} + LCoset_rel H `` {g'}\"\n  from this obtain y z\n    where     \"y \\<in> LCoset_rel H `` {g}\" \"z \\<in> LCoset_rel H `` {g'}\" \"x = y+z\"\n    unfolding set_plus_def\n    by        fast\n  with assms show \"x \\<in> LCoset_rel H `` {g + g'}\"\n    using lcoset_rel_def[of H] normal_lconjby_closed[of H g' \"-g'+z\"]\n          Group.add_closed\n          normal_rconjby_closed[of H g' \"-g + y + (z - g')\"]\n          add.assoc[of \"-g'\" \"-g\"]\n          add_closed lcoset_relI[of \"g+g'\" \"y+z\"]\n    by    (fastforce simp add: add.assoc minus_add)\nnext\n  fix x assume \"x \\<in> LCoset_rel H `` {g + g'}\"\n  moreover define h where \"h \\<equiv> -(g+g') + x\"\n  moreover hence \"x = g + (g' + h)\"\n    using add.assoc[of \"-g'\" \"-g\" x] by (simp add: add.assoc minus_add)\n  ultimately show \"x \\<in> LCoset_rel H `` {g} + LCoset_rel H `` {g'}\"\n    using assms(1,3,4) lcoset_rel_def[of H] add_closed\n          refl_onD[OF subgroup_refl_on_LCoset_rel, of H]\n    by    force\nqed\n\nabbreviation \"quotient_set H \\<equiv> G // LCoset_rel H\"\n\nlemma BinOpSetGroup_normal_quotient:\n  assumes \"Subgroup H\" \"normal H\"\n  shows   \"BinOpSetGroup (quotient_set H) (+) H\"\nproof\n  from assms(1) have H0: \"H = LCoset_rel H `` {0}\"\n    using trivial_LCoset by auto\n\n  from assms(1) show \"H \\<in> quotient_set H\"\n    using H0 zero_closed LCoset_rel_quotientI[of 0 H] by simp\n\n  fix x assume \"x \\<in> quotient_set H\"\n  from this obtain gx where gx: \"gx\\<in>G\" \"x = LCoset_rel H `` {gx}\"\n    by (fast elim: LCoset_rel_quotientE)\n  with assms(1,2) show \"x+H = x\" \"H+x = x\"\n    using normal_quotient_add_well_defined[of H gx 0]\n          normal_quotient_add_well_defined[of H 0 gx]\n          H0 zero_closed\n    by    auto\n\n  from gx(1) have \"LCoset_rel H `` {-gx} \\<in> quotient_set H\"\n    using uminus_closed by (fast intro: LCoset_rel_quotientI)\n  moreover from assms(1,2) gx\n    have  \"x + LCoset_rel H `` {-gx} = H\" \"LCoset_rel H `` {-gx} + x = H\"\n    using H0 uminus_closed normal_quotient_add_well_defined\n    by    auto\n  ultimately show \"\\<exists>x'\\<in>quotient_set H. x + x' = H \\<and> x' + x = H\" by fast\n\n  fix y assume \"y \\<in> quotient_set H\"\n  from this obtain gy where gy: \"gy\\<in>G\" \"y = LCoset_rel H `` {gy}\"\n    by (fast elim: LCoset_rel_quotientE)\n  with assms gx show \"x+y \\<in> quotient_set H\"\n    using add_closed normal_quotient_add_well_defined\n    by    (auto intro: LCoset_rel_quotientI)\n\nqed (rule add.assoc)\n\nabbreviation \"abs_lcoset_perm H \\<equiv>\n                BinOpSetGroup.Abs_G_perm (quotient_set H) (+)\"\nabbreviation \"abs_lcoset_perm_lift H g \\<equiv> abs_lcoset_perm H (LCoset_rel H `` {g})\"\nabbreviation \"abs_lcoset_perm_lift_arg_permutation g H \\<equiv> abs_lcoset_perm_lift H g\"\n\nnotation abs_lcoset_perm_lift_arg_permutation (\"\\<lceil>_|_\\<rceil>\" [51,51] 50)\n\nend (* context Group *)\n\nabbreviation \"Group_abs_lcoset_perm_lift_arg_permutation G' g H \\<equiv>\n  Group.abs_lcoset_perm_lift_arg_permutation G' g H\"\nnotation Group_abs_lcoset_perm_lift_arg_permutation (\"\\<lceil>_|_|_\\<rceil>\" [51,51,51] 50)\n\ncontext Group\nbegin\n\nlemmas lcoset_perm_def =\n  BinOpSetGroup.Abs_G_perm_def[OF BinOpSetGroup_normal_quotient]\nlemmas lcoset_perm_comp =\n  BinOpSetGroup.G_perm_comp[OF BinOpSetGroup_normal_quotient]\nlemmas bij_lcoset_perm =\n  BinOpSetGroup.bij_G_perm[OF BinOpSetGroup_normal_quotient]\n\nlemma trivial_lcoset_perm:\n  assumes \"Subgroup H\" \"normal H\" \"h\\<in>H\"\n  shows   \"restrict1 ((+) (LCoset_rel H `` {h})) (quotient_set H) = id\"\nproof (rule ext, simp, rule impI)\n  fix x assume x: \"x \\<in> quotient_set H\"\n  then obtain k where k: \"k\\<in>G\" \"x = LCoset_rel H `` {k}\"\n    by (blast elim: LCoset_rel_quotientE)\n  with x have \"LCoset_rel H `` {h} + x = LCoset_rel H `` {h+k}\"\n    using assms normal_quotient_add_well_defined by auto\n  with assms k show \"LCoset_rel H `` {h} + x = x\"\n    using add_closed[of h k] lcoset_relI[of k \"h+k\" H]\n          normal_rconjby_closed[of H k h]\n          eq_equiv_class_iff[OF lcoset_subgroup_rel_equiv, of H]\n    by    (auto simp add: add.assoc)\nqed\n\ndefinition quotient_group :: \"'g set \\<Rightarrow> 'g set permutation set\" where\n  \"quotient_group H \\<equiv> BinOpSetGroup.pG (quotient_set H) (+)\"\n\nabbreviation \"natural_quotient_hom H \\<equiv> restrict0 (\\<lambda>g. \\<lceil>g|H\\<rceil>) G\"\n\ntheorem quotient_group:\n  \"Subgroup H \\<Longrightarrow> normal H \\<Longrightarrow> Group (quotient_group H)\"\n  unfolding quotient_group_def\n  using     BinOpSetGroup.Group[OF BinOpSetGroup_normal_quotient]\n  by        auto\n\nlemma natural_quotient_hom:\n  \"Subgroup H \\<Longrightarrow> normal H \\<Longrightarrow> GroupHom G (natural_quotient_hom H)\"\n  using add_closed bij_lcoset_perm lcoset_perm_def supp_restrict0\n        normal_quotient_add_well_defined[THEN sym]\n        LCoset_rel_quotientI[of _ H]\n  by    unfold_locales\n        (force simp add: lcoset_perm_comp plus_permutation_abs_eq)\n\nlemma natural_quotient_hom_image:\n  \"natural_quotient_hom H ` G = quotient_group H\"\n  unfolding quotient_group_def\n  by        (force elim: LCoset_rel_quotientE intro: LCoset_rel_quotientI) \n\nlemma quotient_group_UN: \"quotient_group H = (\\<lambda>g. \\<lceil>g|H\\<rceil>) ` G\"\n  using natural_quotient_hom_image by auto\n\n\n\nend (* context Group *)\n\nsubsubsection \\<open>The induced homomorphism on a quotient group\\<close>\n\ntext \\<open>\n  A normal subgroup contained in the kernel of a homomorphism gives rise to a homomorphism on the\n  quotient group by that subgroup. When the subgroup is the kernel itself (which is always normal),\n  we obtain an isomorphism on the quotient.\n\\<close>\n\ncontext GroupHom\nbegin\n\nlemma respects_Ker_lcosets: \"H \\<subseteq> Ker \\<Longrightarrow> T respects (LCoset_rel H)\"\n  using     uminus_add_in_Ker_eq_eq_im\n  unfolding lcoset_rel_def\n  by        (blast intro: congruentI)\n\nabbreviation \"quotient_hom H \\<equiv>\n  BinOpSetGroup.lift_hom (quotient_set H) (+) (quotientfun T)\"\n\nlemmas normal_subgroup_quotientfun_classrep_equality =\n  quotientfun_classrep_equality[\n    OF subgroup_refl_on_LCoset_rel, OF _ respects_Ker_lcosets\n  ]\n\nlemma quotient_hom_im:\n  \"\\<lbrakk> Subgroup H; normal H; H \\<subseteq> Ker; g\\<in>G \\<rbrakk> \\<Longrightarrow> quotient_hom H (\\<lceil>g|H\\<rceil>) = T g\"\n  using quotient_group_def quotient_group_UN quotient_group_lift_to_quotient_set\n        BinOpSetGroup.inv_correspondence_conv_apply[\n          OF BinOpSetGroup_normal_quotient\n        ]\n        normal_subgroup_quotientfun_classrep_equality\n  by    auto\n\nlemma quotient_hom:\n  assumes \"Subgroup H\" \"normal H\" \"H \\<subseteq> Ker\"\n  shows   \"GroupHom (quotient_group H) (quotient_hom H)\"\n  unfolding quotient_group_def\nproof (\n  rule BinOpSetGroup.lift_hom, rule BinOpSetGroup_normal_quotient, rule assms(1),\n  rule assms(2)\n)\n  from assms\n    show  \"\\<forall>x \\<in> quotient_set H. \\<forall>y \\<in> quotient_set H.\n            quotientfun T (x + y) = quotientfun T x + quotientfun T y\"\n    using normal_quotient_add_well_defined normal_subgroup_quotientfun_classrep_equality\n          add_closed hom\n    by    (fastforce elim: LCoset_rel_quotientE)\nqed\n\nend (* context GroupHom *)\n\n\nsubsection \\<open>Free groups\\<close>\n\nsubsubsection \\<open>Words in letters of @{type signed} type\\<close>\n\nparagraph \\<open>Definitions and basic fact\\<close>\n\ntext \\<open>\n  We pair elements of some type with type @{typ bool}, where the @{typ bool} part of the pair\n  indicates inversion.\n\\<close>\n\nabbreviation \"pairtrue  \\<equiv> \\<lambda>s. (s,True)\"\nabbreviation \"pairfalse \\<equiv> \\<lambda>s. (s,False)\"\n\nabbreviation flip_signed :: \"'a signed \\<Rightarrow> 'a signed\"\n  where \"flip_signed \\<equiv> apsnd (\\<lambda>b. \\<not>b)\"\n\nabbreviation nflipped_signed :: \"'a signed \\<Rightarrow> 'a signed \\<Rightarrow> bool\"\n  where \"nflipped_signed x y \\<equiv> y \\<noteq> flip_signed x\"\n\nlemma flip_signed_order2: \"flip_signed (flip_signed x) = x\"\n  using apsnd_conv[of \"\\<lambda>b. \\<not>b\" \"fst x\" \"snd x\"] by simp\n\nabbreviation charpair :: \"'a::uminus set \\<Rightarrow> 'a \\<Rightarrow> 'a signed\"\n  where \"charpair S s \\<equiv> if s\\<in>S then (s,True) else (-s,False)\"\n\nlemma map_charpair_uniform:\n  \"ss\\<in>lists S \\<Longrightarrow> map (charpair S) ss = map pairtrue ss\"\n  by (induct ss) auto\n\nlemma fst_set_map_charpair_un_uminus:\n  fixes ss :: \"'a::group_add list\"\n  shows \"ss\\<in>lists (S \\<union> uminus ` S) \\<Longrightarrow> fst ` set (map (charpair S) ss) \\<subseteq> S\"\n  by (induct ss) auto\n\nabbreviation apply_sign :: \"('a\\<Rightarrow>'b::uminus) \\<Rightarrow> 'a signed \\<Rightarrow> 'b\"\n  where \"apply_sign f x \\<equiv> (if snd x then f (fst x) else - f (fst x))\"\n\ntext \\<open>\n  A word in such pairs will be considered proper if it does not contain consecutive letters that\n  have opposite signs (and so are considered inverse), since such consecutive letters would be\n  cancelled in a group.\n\\<close>\n\nabbreviation proper_signed_list :: \"'a signed list \\<Rightarrow> bool\"\n  where \"proper_signed_list \\<equiv> binrelchain nflipped_signed\"\n\nlemma proper_map_flip_signed:\n  \"proper_signed_list xs \\<Longrightarrow> proper_signed_list (map flip_signed xs)\"\n  by (induct xs rule: list_induct_CCons) auto\n\nlemma proper_rev_map_flip_signed:\n  \"proper_signed_list xs \\<Longrightarrow> proper_signed_list (rev (map flip_signed xs))\"\n  using proper_map_flip_signed binrelchain_sym_rev[of nflipped_signed] by fastforce\n\nlemma uniform_snd_imp_proper_signed_list:\n  \"snd ` set xs \\<subseteq> {b} \\<Longrightarrow> proper_signed_list xs\"\nproof (induct xs rule: list_induct_CCons)\n  case CCons thus ?case by force\nqed auto\n\nlemma proper_signed_list_map_uniform_snd:\n  \"proper_signed_list (map (\\<lambda>s. (s,b)) as)\"\n  using uniform_snd_imp_proper_signed_list[of _ b] by force\n\nparagraph \\<open>Algebra\\<close>\n\ntext \\<open>\n  Addition is performed by appending words and recursively removing any newly created adjacent\n  pairs of inverse letters. Since we will only ever be adding proper words, we only need to care\n  about newly created adjacent inverse pairs in the middle.\n\\<close>\n\nfunction prappend_signed_list :: \"'a signed list \\<Rightarrow> 'a signed list \\<Rightarrow> 'a signed list\"\n  where \"prappend_signed_list xs [] = xs\"\n      | \"prappend_signed_list [] ys = ys\"\n      | \"prappend_signed_list (xs@[x]) (y#ys) = (\n          if y = flip_signed x then prappend_signed_list xs ys else xs @ x # y # ys\n        )\"\n  by (auto, rule two_prod_lists_cases_snoc_Cons)\n  termination by (relation \"measure (\\<lambda>(xs,ys). length xs + length ys)\") auto\n\nlemma proper_prappend_signed_list:\n  \"proper_signed_list xs \\<Longrightarrow> proper_signed_list ys\n    \\<Longrightarrow> proper_signed_list (prappend_signed_list xs ys)\"\nproof (induct xs ys rule: list_induct2_snoc_Cons)\n  case (snoc_Cons xs x y ys)\n  show ?case\n  proof (cases \"y = flip_signed x\")\n    case True with snoc_Cons show ?thesis\n      using binrelchain_append_reduce1[of nflipped_signed]\n            binrelchain_Cons_reduce[of nflipped_signed y]\n      by    auto\n  next\n    case False with snoc_Cons(2,3) show ?thesis\n      using binrelchain_join[of nflipped_signed] by simp\n  qed\nqed auto\n\nlemma fully_prappend_signed_list:\n  \"prappend_signed_list (rev (map flip_signed xs)) xs = []\"\n  by (induct xs) auto\n\nlemma prappend_signed_list_single_Cons:\n  \"prappend_signed_list [x] (y#ys) = (if y = flip_signed x then ys else x#y#ys)\"\n  using prappend_signed_list.simps(3)[of \"[]\" x] by simp\n\nlemma prappend_signed_list_map_uniform_snd:\n  \"prappend_signed_list (map (\\<lambda>s. (s,b)) xs) (map (\\<lambda>s. (s,b)) ys) =\n    map (\\<lambda>s. (s,b)) xs @ map (\\<lambda>s. (s,b)) ys\"\n  by (cases xs ys rule: two_lists_cases_snoc_Cons) auto\n\nlemma prappend_signed_list_assoc_conv_snoc2Cons:\n  assumes \"proper_signed_list (xs@[y])\" \"proper_signed_list (y#ys)\"\n  shows   \"prappend_signed_list (xs@[y]) ys = prappend_signed_list xs (y#ys)\"\nproof (cases xs ys rule: two_lists_cases_snoc_Cons')\n  case Nil1 with assms(2) show ?thesis\n    by (simp add: prappend_signed_list_single_Cons)\nnext\n  case Nil2 with assms(1) show ?thesis\n    using binrelchain_append_reduce2 by force\nnext\n  case (snoc_Cons as a b bs)\n  with assms show ?thesis \n    using prappend_signed_list.simps(3)[of \"as@[a]\"]\n          binrelchain_append_reduce2[of nflipped_signed as \"[a,y]\"]\n    by    simp\nqed simp\n\nlemma prappend_signed_list_assoc:\n  \"\\<lbrakk> proper_signed_list xs; proper_signed_list ys; proper_signed_list zs \\<rbrakk> \\<Longrightarrow>\n    prappend_signed_list (prappend_signed_list xs ys) zs =\n      prappend_signed_list xs (prappend_signed_list ys zs)\"\nproof (induct xs ys zs rule: list_induct3_snoc_Conssnoc_Cons_pairwise)\n  case (snoc_single_Cons xs x y z zs)\n  thus ?case\n    using prappend_signed_list.simps(3)[of \"[]\" y]\n          prappend_signed_list.simps(3)[of \"xs@[x]\"]\n    by    (cases \"y = flip_signed x\" \"z = flip_signed y\" rule: two_cases)\n          (auto simp add:\n            flip_signed_order2 prappend_signed_list_assoc_conv_snoc2Cons\n          )\nnext\n  case (snoc_Conssnoc_Cons xs x y ys w z zs)\n  thus ?case\n    using binrelchain_Cons_reduce[of nflipped_signed y \"ys@[w]\"]\n          binrelchain_Cons_reduce[of nflipped_signed z zs]\n          binrelchain_append_reduce1[of nflipped_signed xs]\n          binrelchain_append_reduce1[of nflipped_signed \"y#ys\"]\n          binrelchain_Conssnoc_reduce[of nflipped_signed y ys]\n          prappend_signed_list.simps(3)[of \"y#ys\"]\n          prappend_signed_list.simps(3)[of \"xs@x#y#ys\"]\n    by    (cases \"y = flip_signed x\" \"z = flip_signed w\" rule: two_cases) auto\nqed auto\n\nlemma fst_set_prappend_signed_list:\n  \"fst ` set (prappend_signed_list xs ys) \\<subseteq> fst ` (set xs \\<union> set ys)\"\n  by (induct xs ys rule: list_induct2_snoc_Cons) auto\n\nlemma collapse_flipped_signed:\n  \"prappend_signed_list [(s,b)] [(s,\\<not>b)] = []\"\n  using prappend_signed_list.simps(3)[of \"[]\" \"(s,b)\"] by simp\n\n\n\nsubsubsection \\<open>The collection of proper signed lists as a type\\<close>\n\ntext \\<open>\n  Here we create a type out of the collection of proper signed lists. This type will be of class\n  @{class group_add}, with the empty list as zero, the modified append operation\n  @{const prappend_signed_list} as addition, and inversion performed by flipping the signs of the\n  elements in the list and then reversing the order.\n\\<close>\n\nparagraph \\<open>Type definition, instantiations, and instances\\<close>\n\ntext \\<open>Here we define the type and instantiate it with respect to various type classes.\\<close>\n\ntypedef 'a freeword = \"{as::'a signed list. proper_signed_list as}\"\n  morphisms freeword Abs_freeword\n  using binrelchain.simps(1) by fast\n\ntext \\<open>\n  These two functions act as the natural injections of letters and words in the letter type into\n  the @{type freeword} type.\n\\<close>\n\nabbreviation Abs_freeletter :: \"'a \\<Rightarrow> 'a freeword\"\n  where \"Abs_freeletter s \\<equiv> Abs_freeword [pairtrue s]\"\n\nabbreviation Abs_freelist :: \"'a list \\<Rightarrow> 'a freeword\"\n  where \"Abs_freelist as \\<equiv> Abs_freeword (map pairtrue as)\"\n\nabbreviation Abs_freelistfst :: \"'a signed list \\<Rightarrow> 'a freeword\"\n  where \"Abs_freelistfst xs \\<equiv> Abs_freelist (map fst xs)\"\n\nsetup_lifting type_definition_freeword\n\ninstantiation freeword :: (type) zero\nbegin\nlift_definition zero_freeword :: \"'a freeword\" is \"[]::'a signed list\" by simp\ninstance ..\nend\n\ninstantiation freeword :: (type) plus\nbegin\nlift_definition plus_freeword :: \"'a freeword \\<Rightarrow> 'a freeword \\<Rightarrow> 'a freeword\"\n  is    \"prappend_signed_list\"\n  using proper_prappend_signed_list\n  by    fast\ninstance ..\nend\n\ninstantiation freeword :: (type) uminus\nbegin\nlift_definition uminus_freeword :: \"'a freeword \\<Rightarrow> 'a freeword\"\n  is \"\\<lambda>xs. rev (map flip_signed xs)\"\n  by (rule proper_rev_map_flip_signed)\ninstance ..\nend\n\ninstantiation freeword :: (type) minus\nbegin\nlift_definition minus_freeword :: \"'a freeword \\<Rightarrow> 'a freeword \\<Rightarrow> 'a freeword\"\n  is \"\\<lambda>xs ys. prappend_signed_list xs (rev (map flip_signed ys))\"\n  using proper_rev_map_flip_signed proper_prappend_signed_list by fast\ninstance ..\nend\n\ninstance freeword :: (type) semigroup_add\nproof\n  fix a b c :: \"'a freeword\" show \"a + b + c = a + (b + c)\"\n    using prappend_signed_list_assoc[of \"freeword a\" \"freeword b\" \"freeword c\"]\n    by    transfer simp\nqed\n\ninstance freeword :: (type) monoid_add\nproof\n  fix a b c :: \"'a freeword\"\n  show \"0 + a = a\" by transfer simp\n  show \"a + 0 = a\" by transfer simp\nqed\n\ninstance freeword :: (type) group_add\nproof\n  fix a b :: \"'a freeword\"\n  show \"- a + a = 0\"\n    using fully_prappend_signed_list[of \"freeword a\"] by transfer simp\n  show \"a + - b = a - b\" by transfer simp\nqed\n\nparagraph \\<open>Basic algebra and transfer facts in the @{type freeword} type\\<close>\n\ntext \\<open>\n  Here we record basic algebraic manipulations for the @{type freeword} type as well as various\n  transfer facts for dealing with representations of elements of @{type freeword} type as lists of\n  signed letters.\n\\<close>\n\nabbreviation Abs_freeletter_add :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a freeword\" (infixl \"[+]\" 65)\n  where \"s [+] t \\<equiv> Abs_freeletter s + Abs_freeletter t\"\n\nlemma Abs_freeword_Cons:\n  assumes \"proper_signed_list (x#xs)\"\n  shows \"Abs_freeword (x#xs) = Abs_freeword [x] + Abs_freeword xs\"\nproof (cases xs)\n  case Nil thus ?thesis\n    using add_0_right[of \"Abs_freeword [x]\"] by (simp add: zero_freeword.abs_eq)\nnext\n  case (Cons y ys) \n  with assms\n    have  \"freeword (Abs_freeword (x#xs)) =\n            freeword (Abs_freeword [x] + Abs_freeword xs)\"\n    by    (simp add:\n            plus_freeword.rep_eq Abs_freeword_inverse\n            prappend_signed_list_single_Cons\n          )\n  thus ?thesis using freeword_inject by fast\nqed\n\nlemma Abs_freelist_Cons: \"Abs_freelist (x#xs) = Abs_freeletter x + Abs_freelist xs\"\n  using proper_signed_list_map_uniform_snd[of True \"x#xs\"] Abs_freeword_Cons\n  by    simp\n\nlemma plus_freeword_abs_eq:\n  \"proper_signed_list xs \\<Longrightarrow> proper_signed_list ys \\<Longrightarrow>\n    Abs_freeword xs + Abs_freeword ys = Abs_freeword (prappend_signed_list xs ys)\"\n  using plus_freeword.abs_eq unfolding eq_onp_def by simp\n\nlemma Abs_freeletter_add: \"s [+] t = Abs_freelist [s,t]\"\n  using Abs_freelist_Cons[of s \"[t]\"] by simp\n\nlemma uminus_freeword_Abs_eq:\n  \"proper_signed_list xs \\<Longrightarrow>\n    - Abs_freeword xs = Abs_freeword (rev (map flip_signed xs))\"\n  using uminus_freeword.abs_eq unfolding eq_onp_def by simp\n\nlemma uminus_Abs_freeword_singleton:\n  \"- Abs_freeword [(s,b)] = Abs_freeword [(s,\\<not> b)]\"\n  using uminus_freeword_Abs_eq[of \"[(s,b)]\"] by simp\n\nlemma Abs_freeword_append_uniform_snd:\n  \"Abs_freeword (map (\\<lambda>s. (s,b)) (xs@ys)) =\n    Abs_freeword (map (\\<lambda>s. (s,b)) xs) + Abs_freeword (map (\\<lambda>s. (s,b)) ys)\"\n  using proper_signed_list_map_uniform_snd[of b xs]\n        proper_signed_list_map_uniform_snd[of b ys]\n        plus_freeword_abs_eq prappend_signed_list_map_uniform_snd[of b xs ys]\n  by    force\n\nlemmas Abs_freelist_append = Abs_freeword_append_uniform_snd[of True]\n\nlemma Abs_freelist_append_append:\n  \"Abs_freelist (xs@ys@zs) = Abs_freelist xs + Abs_freelist ys + Abs_freelist zs\"\n  using Abs_freelist_append[of \"xs@ys\"] Abs_freelist_append by simp\n\nlemma Abs_freelist_inverse: \"freeword (Abs_freelist as) = map pairtrue as\"\n  using proper_signed_list_map_uniform_snd Abs_freeword_inverse by fast\n\nlemma Abs_freeword_singleton_conv_apply_sign_freeletter:\n  \"Abs_freeword [x] = apply_sign Abs_freeletter x\"\n  by (cases x) (auto simp add: uminus_Abs_freeword_singleton)\n\nlemma Abs_freeword_conv_freeletter_sum_list:\n  \"proper_signed_list xs \\<Longrightarrow>\n    Abs_freeword xs = (\\<Sum>x\\<leftarrow>xs. apply_sign Abs_freeletter x)\"\nproof (induct xs)\n  case (Cons x xs) thus ?case\n    using Abs_freeword_Cons[of x] binrelchain_Cons_reduce[of _ x]\n    by (simp add: Abs_freeword_singleton_conv_apply_sign_freeletter)\nqed (simp add: zero_freeword.abs_eq)\n\nlemma freeword_conv_freeletter_sum_list:\n  \"x = (\\<Sum>s\\<leftarrow>freeword x. apply_sign Abs_freeletter s)\"\n  using Abs_freeword_conv_freeletter_sum_list[of \"freeword x\"] freeword\n  by    (auto simp add: freeword_inverse)\n\nlemma Abs_freeletter_prod_conv_Abs_freeword:\n  \"snd x \\<Longrightarrow> Abs_freeletter (fst x) = Abs_freeword [x]\"\n  using prod_eqI[of x \"pairtrue (fst x)\"] by simp\n\n\nsubsubsection \\<open>Lifts of functions on the letter type\\<close>\n\ntext \\<open>\n  Here we lift functions on the letter type to type @{type freeword}. In particular, we are\n  interested in the case where the function being lifted has codomain of class @{class group_add}.\n\\<close>\n\nparagraph \\<open>The universal property\\<close>\n\ntext \\<open>\n  The universal property for free groups says that every function from the letter type to some\n  @{class group_add} type gives rise to a unique homomorphism.\n\\<close>\n\nlemma extend_map_to_freeword_hom':\n  fixes   f :: \"'a \\<Rightarrow> 'b::group_add\"\n  defines h: \"h::'a signed \\<Rightarrow> 'b \\<equiv> \\<lambda>(s,b). if b then f s else - (f s)\"\n  defines g: \"g::'a signed list \\<Rightarrow> 'b \\<equiv> \\<lambda>xs. sum_list (map h xs)\"\n  shows   \"g (prappend_signed_list xs ys) = g xs + g ys\"\nproof (induct xs ys rule: list_induct2_snoc_Cons)\n  case (snoc_Cons xs x y ys)\n  show ?case\n  proof (cases \"y = flip_signed x\")\n    case True\n    with h have \"h y = - h x\"\n      using split_beta'[of \"\\<lambda>s b. if b then f s else - (f s)\"] by simp\n    with g have \"g (xs @ [x]) + g (y # ys) = g xs + g ys\"\n      by (simp add: algebra_simps)\n    with True snoc_Cons show ?thesis by simp\n  next\n    case False with g show ?thesis\n      using sum_list.append[of \"map h (xs@[x])\" \"map h (y#ys)\"] by simp\n  qed\nqed (auto simp add: h g)\n\nlemma extend_map_to_freeword_hom1:\n  fixes   f :: \"'a \\<Rightarrow> 'b::group_add\"\n  defines \"h::'a signed \\<Rightarrow> 'b \\<equiv> \\<lambda>(s,b). if b then f s else - (f s)\"\n  defines \"g::'a freeword \\<Rightarrow> 'b \\<equiv> \\<lambda>x. sum_list (map h (freeword x))\"\n  shows   \"g (Abs_freeletter s) = f s\"\n  using   assms\n  by      (simp add: Abs_freeword_inverse)\n\nlemma extend_map_to_freeword_hom2:\n  fixes   f :: \"'a \\<Rightarrow> 'b::group_add\"\n  defines \"h::'a signed \\<Rightarrow> 'b \\<equiv> \\<lambda>(s,b). if b then f s else - (f s)\"\n  defines \"g::'a freeword \\<Rightarrow> 'b \\<equiv> \\<lambda>x. sum_list (map h (freeword x))\"\n  shows   \"UGroupHom g\"\n  using   assms\n  by      (\n            auto intro: UGroupHomI\n            simp add: plus_freeword.rep_eq extend_map_to_freeword_hom'\n          )\n\nlemma uniqueness_of_extended_map_to_freeword_hom':\n  fixes   f :: \"'a \\<Rightarrow> 'b::group_add\"\n  defines h: \"h::'a signed \\<Rightarrow> 'b \\<equiv> \\<lambda>(s,b). if b then f s else - (f s)\"\n  defines g: \"g::'a signed list \\<Rightarrow> 'b \\<equiv> \\<lambda>xs. sum_list (map h xs)\"\n  assumes singles: \"\\<And>s. k [(s,True)] = f s\"\n  and     adds   : \"\\<And>xs ys. proper_signed_list xs \\<Longrightarrow> proper_signed_list ys\n            \\<Longrightarrow> k (prappend_signed_list xs ys) = k xs + k ys\"\n  shows   \"proper_signed_list xs \\<Longrightarrow> k xs = g xs\"\nproof-\n  have knil: \"k [] = 0\" using adds[of \"[]\" \"[]\"] add.assoc[of \"k []\" \"k []\" \"- k []\"] by simp\n  have ksingle: \"\\<And>x. k [x] = g [x]\"\n  proof-\n    fix x :: \"'a signed\"\n    obtain s b where x: \"x = (s,b)\" by fastforce\n    show \"k [x] = g [x]\"\n    proof (cases b)\n      case False\n      from adds x singles\n        have  \"k (prappend_signed_list [x] [(s,True)]) = k [x] + f s\"\n        by    simp\n      moreover have \"prappend_signed_list [(s,False)] [(s,True)] = []\"\n        using collapse_flipped_signed[of s False] by simp\n      ultimately have \"- f s = k [x] + f s + - f s\" using x False knil by simp\n      with x False g h show \"k [x] = g [x]\" by (simp add: algebra_simps)\n    qed (simp add: x g h singles)\n  qed\n  show \"proper_signed_list xs \\<Longrightarrow> k xs = g xs\"\n  proof (induct xs rule: list_induct_CCons)\n    case (CCons x y xs)\n    with g h show ?case\n      using adds[of \"[x]\" \"y#xs\"]\n      by    (simp add:\n              prappend_signed_list_single_Cons\n              ksingle extend_map_to_freeword_hom'\n            )\n  qed (auto simp add: g h knil ksingle)\nqed\n\nlemma uniqueness_of_extended_map_to_freeword_hom:\n  fixes   f :: \"'a \\<Rightarrow> 'b::group_add\"\n  defines \"h::'a signed \\<Rightarrow> 'b \\<equiv> \\<lambda>(s,b). if b then f s else - (f s)\"\n  defines \"g::'a freeword \\<Rightarrow> 'b \\<equiv> \\<lambda>x. sum_list (map h (freeword x))\"\n  assumes k: \"k \\<circ> Abs_freeletter = f\" \"UGroupHom k\"\n  shows   \"k = g\"\nproof\n  fix x::\"'a freeword\"\n  define k' where k': \"k' \\<equiv> k \\<circ> Abs_freeword\"\n  have \"k' (freeword x) = g x\" unfolding h_def g_def\n  proof (rule uniqueness_of_extended_map_to_freeword_hom')\n    from k' k(1) show \"\\<And>s. k' [pairtrue s] = f s\" by auto\n    show \"\\<And>xs ys. proper_signed_list xs \\<Longrightarrow> proper_signed_list ys\n            \\<Longrightarrow> k' (prappend_signed_list xs ys) = k' xs + k' ys\"\n    proof-\n      fix xs ys :: \"'a signed list\"\n      assume xsys: \"proper_signed_list xs\" \"proper_signed_list ys\"\n      with k'\n        show  \"k' (prappend_signed_list xs ys) = k' xs + k' ys\"\n        using UGroupHom.hom[OF k(2), of \"Abs_freeword xs\" \"Abs_freeword ys\"]\n        by    (simp add: plus_freeword_abs_eq)      \n    qed\n    show \"proper_signed_list (freeword x)\" using freeword by fast\n  qed\n  with k' show \"k x = g x\" using freeword_inverse[of x] by simp\nqed\n\ntheorem universal_property:\n  fixes f :: \"'a \\<Rightarrow> 'b::group_add\"\n  shows \"\\<exists>!g::'a freeword\\<Rightarrow>'b. g \\<circ> Abs_freeletter = f \\<and> UGroupHom g\"\nproof\n  define h where h: \"h \\<equiv> \\<lambda>(s,b). if b then f s else - (f s)\"\n  define g where g: \"g \\<equiv> \\<lambda>x. sum_list (map h (freeword x))\"\n  from g h show \"g \\<circ> Abs_freeletter = f \\<and> UGroupHom g\"\n    using extend_map_to_freeword_hom1[of f] extend_map_to_freeword_hom2\n    by    auto\n  from g h show \"\\<And>k. k \\<circ> Abs_freeletter = f \\<and> UGroupHom k \\<Longrightarrow> k = g\"\n    using uniqueness_of_extended_map_to_freeword_hom by auto\nqed\n\nparagraph \\<open>Properties of homomorphisms afforded by the universal property\\<close>\n\ntext \\<open>\n  The lift of a function on the letter set is the unique additive function on @{type freeword}\n  that agrees with the original function on letters.\n\\<close>\n\ndefinition freeword_funlift :: \"('a \\<Rightarrow> 'b::group_add) \\<Rightarrow> ('a freeword\\<Rightarrow>'b::group_add)\"\n  where \"freeword_funlift f \\<equiv> (THE g. g \\<circ> Abs_freeletter = f \\<and> UGroupHom g)\"\n\nlemma additive_freeword_funlift: \"UGroupHom (freeword_funlift f)\"\n  using theI'[OF universal_property, of f] unfolding freeword_funlift_def by simp\n\nlemma freeword_funlift_Abs_freeletter: \"freeword_funlift f (Abs_freeletter s) = f s\"\n  using     theI'[OF universal_property, of f]\n            comp_apply[of \"freeword_funlift f\" Abs_freeletter]\n  unfolding freeword_funlift_def\n  by        fastforce\n\nlemmas freeword_funlift_add         = UGroupHom.hom        [OF additive_freeword_funlift]\nlemmas freeword_funlift_0           = UGroupHom.im_zero    [OF additive_freeword_funlift]\nlemmas freeword_funlift_uminus      = UGroupHom.im_uminus  [OF additive_freeword_funlift]\nlemmas freeword_funlift_diff        = UGroupHom.im_diff    [OF additive_freeword_funlift]\nlemmas freeword_funlift_lconjby     = UGroupHom.im_lconjby [OF additive_freeword_funlift]\n\nlemma freeword_funlift_uminus_Abs_freeletter:\n  \"freeword_funlift f (Abs_freeword [(s,False)]) = - f s\"\n  using freeword_funlift_uminus[of f \"Abs_freeword [(s,False)]\"]\n        uminus_freeword_Abs_eq[of \"[(s,False)]\"]\n        freeword_funlift_Abs_freeletter[of f]\n  by    simp\n\nlemma freeword_funlift_Abs_freeword_singleton:\n  \"freeword_funlift f (Abs_freeword [x]) = apply_sign f x\"\nproof-\n  obtain s b where x: \"x = (s,b)\" by fastforce\n  thus ?thesis\n    using freeword_funlift_Abs_freeletter freeword_funlift_uminus_Abs_freeletter\n    by    (cases b) auto\nqed\n\nlemma freeword_funlift_Abs_freeword_Cons:\n  assumes \"proper_signed_list (x#xs)\"\n  shows   \"freeword_funlift f (Abs_freeword (x#xs)) =\n            apply_sign f x + freeword_funlift f (Abs_freeword xs)\"\nproof-\n  from assms\n    have \"freeword_funlift f (Abs_freeword (x#xs)) =\n            freeword_funlift f (Abs_freeword [x]) +\n            freeword_funlift f (Abs_freeword xs)\"\n    using Abs_freeword_Cons[of x xs] freeword_funlift_add by simp\n  thus ?thesis\n    using freeword_funlift_Abs_freeword_singleton[of f x] by simp\nqed\n\nlemma freeword_funlift_Abs_freeword:\n  \"proper_signed_list xs \\<Longrightarrow> freeword_funlift f (Abs_freeword xs) =\n    (\\<Sum>x\\<leftarrow>xs. apply_sign f x)\"\nproof (induct xs)\n  case (Cons x xs) thus ?case\n    using freeword_funlift_Abs_freeword_Cons[of _ _ f]\n          binrelchain_Cons_reduce[of _ x xs]\n    by    simp\nqed (simp add: zero_freeword.abs_eq[THEN sym] freeword_funlift_0)\n\nlemma freeword_funlift_Abs_freelist:\n  \"freeword_funlift f (Abs_freelist xs) = (\\<Sum>x\\<leftarrow>xs. f x)\"\nproof (induct xs)\n  case (Cons x xs) thus ?case\n    using Abs_freelist_Cons[of x xs]\n    by    (simp add: freeword_funlift_add freeword_funlift_Abs_freeletter)\nqed (simp add: zero_freeword.abs_eq[THEN sym] freeword_funlift_0)\n\nlemma freeword_funlift_im':\n  \"proper_signed_list xs \\<Longrightarrow> fst ` set xs \\<subseteq> S \\<Longrightarrow>\n    freeword_funlift f (Abs_freeword xs) \\<in> \\<langle>f`S\\<rangle>\"\nproof (induct xs)\n  case Nil\n  have \"Abs_freeword ([]::'a signed list) = (0::'a freeword)\"\n    using zero_freeword.abs_eq[THEN sym] by simp\n  thus \"freeword_funlift f (Abs_freeword ([]::'a signed list)) \\<in> \\<langle>f`S\\<rangle>\"\n    using freeword_funlift_0[of f] genby_0_closed by simp\nnext\n  case (Cons x xs)\n  define y where y: \"y \\<equiv> apply_sign f x\"\n  define z where z: \"z \\<equiv> freeword_funlift f (Abs_freeword xs)\"\n  from Cons(3) have \"fst ` set xs \\<subseteq> S\" by simp\n  with z Cons(1,2) have \"z \\<in> \\<langle>f`S\\<rangle>\" using binrelchain_Cons_reduce by fast\n  with y Cons(3) have \"y + z \\<in> \\<langle>f`S\\<rangle>\"\n    using genby_genset_closed[of _ \"f`S\"]\n          genby_uminus_closed genby_add_closed[of y]\n    by    fastforce\n  with Cons(2) y z show ?case\n    using freeword_funlift_Abs_freeword_Cons\n          subst[\n            OF  sym,\n            of  \"freeword_funlift f (Abs_freeword (x#xs))\" \"y+z\"\n                \"\\<lambda>b. b\\<in>\\<langle>f`S\\<rangle>\"\n          ]\n    by    fast\nqed\n\n\nsubsubsection \\<open>Free groups on a set\\<close>\n\ntext \\<open>\n  We now take the free group on a set to be the set in the @{type freeword} type with letters\n  restricted to the given set.\n\\<close>\n\nparagraph \\<open>Definition and basic facts\\<close>\n\ntext \\<open>\n  Here we define the set of elements of the free group over a set of letters, and record basic\n  facts about that set.\n\\<close>\n\ndefinition FreeGroup :: \"'a set \\<Rightarrow> 'a freeword set\"\n  where \"FreeGroup S \\<equiv> {x. fst ` set (freeword x) \\<subseteq> S}\"\n\nlemma FreeGroupI_transfer:\n  \"proper_signed_list xs \\<Longrightarrow> fst ` set xs \\<subseteq> S \\<Longrightarrow> Abs_freeword xs \\<in> FreeGroup S\"\n  using Abs_freeword_inverse unfolding FreeGroup_def by fastforce\n\nlemma FreeGroupD: \"x \\<in> FreeGroup S \\<Longrightarrow> fst ` set (freeword x) \\<subseteq> S\"\n  using FreeGroup_def by fast\n\nlemma FreeGroupD_transfer:\n  \"proper_signed_list xs \\<Longrightarrow> Abs_freeword xs \\<in> FreeGroup S \\<Longrightarrow> fst ` set xs \\<subseteq> S\"\n  using Abs_freeword_inverse unfolding FreeGroup_def by fastforce\n\nlemma FreeGroupD_transfer':\n  \"Abs_freelist xs \\<in> FreeGroup S \\<Longrightarrow> xs \\<in> lists S\"\n  using proper_signed_list_map_uniform_snd FreeGroupD_transfer by fastforce\n\nlemma FreeGroup_0_closed: \"0 \\<in> FreeGroup S\"\nproof-\n  have \"(0::'a freeword) = Abs_freeword []\" using zero_freeword.abs_eq by fast\n  moreover have \"Abs_freeword [] \\<in> FreeGroup S\"\n    using FreeGroupI_transfer[of \"[]\"] by simp\n  ultimately show ?thesis by simp\nqed\n\nlemma FreeGroup_diff_closed:\n  assumes \"x \\<in> FreeGroup S\" \"y \\<in> FreeGroup S\"\n  shows   \"x-y \\<in> FreeGroup S\"\nproof-\n  define xs where xs: \"xs \\<equiv> freeword x\"\n  define ys where ys: \"ys \\<equiv> freeword y\"\n  have \"freeword (x-y) =\n        prappend_signed_list (freeword x) (rev (map flip_signed (freeword y)))\"\n    by transfer simp\n  hence \"fst ` set (freeword (x-y)) \\<subseteq> fst ` (set (freeword x) \\<union> set (freeword y))\"\n    using fst_set_prappend_signed_list by force\n  with assms show ?thesis unfolding FreeGroup_def by fast\nqed\n\nlemma FreeGroup_Group: \"Group (FreeGroup S)\"\n  using FreeGroup_0_closed FreeGroup_diff_closed by unfold_locales fast\n\nlemmas FreeGroup_add_closed    = Group.add_closed    [OF FreeGroup_Group]\nlemmas FreeGroup_uminus_closed = Group.uminus_closed [OF FreeGroup_Group]\n\nlemmas FreeGroup_genby_set_lconjby_set_rconjby_closed =\n  Group.genby_set_lconjby_set_rconjby_closed[OF FreeGroup_Group]\n\nlemma Abs_freelist_in_FreeGroup: \"ss \\<in> lists S \\<Longrightarrow> Abs_freelist ss \\<in> FreeGroup S\"\n  using proper_signed_list_map_uniform_snd by (fastforce intro: FreeGroupI_transfer)\n\nlemma Abs_freeletter_in_FreeGroup_iff: \"(Abs_freeletter s \\<in> FreeGroup S) = (s\\<in>S)\"\n  using Abs_freeword_inverse[of \"[pairtrue s]\"] unfolding FreeGroup_def by simp\n\nparagraph \\<open>Lifts of functions from the letter set to some type of class @{class group_add}\\<close>\n\ntext \\<open>\n  We again obtain a universal property for functions from the (restricted) letter set to some type\n  of class @{class group_add}.\n\\<close>\n\nabbreviation \"res_freeword_funlift f S \\<equiv>\n                restrict0 (freeword_funlift f) (FreeGroup S)\"\n\nlemma freeword_funlift_im: \"x \\<in> FreeGroup S \\<Longrightarrow> freeword_funlift f x \\<in> \\<langle>f ` S\\<rangle>\"\n  using     freeword[of x] freeword_funlift_im'[of \"freeword x\"]\n            freeword_inverse[of x]\n  unfolding FreeGroup_def\n  by        auto\n\nlemma freeword_funlift_surj':\n  \"ys \\<in> lists (f`S \\<union> uminus`f`S) \\<Longrightarrow> sum_list ys \\<in> freeword_funlift f ` FreeGroup S\"\nproof (induct ys)\n  case Nil thus ?case using FreeGroup_0_closed freeword_funlift_0 by fastforce\nnext\n  case (Cons y ys)\n  from this obtain x\n    where x: \"x \\<in> FreeGroup S\" \"sum_list ys = freeword_funlift f x\"\n    by    auto\n  show \"sum_list (y#ys) \\<in> freeword_funlift f ` FreeGroup S\"\n  proof (cases \"y \\<in> f`S\")\n    case True\n    from this obtain s where s: \"s\\<in>S\" \"y = f s\" by fast\n    from s(1) x(1) have \"Abs_freeletter s + x \\<in> FreeGroup S\"\n      using FreeGroupI_transfer[of _ S] FreeGroup_add_closed[of _ S] by force\n    moreover from s(2) x(2)\n      have  \"freeword_funlift f (Abs_freeletter s + x) = sum_list (y#ys)\"\n      using freeword_funlift_add[of f] freeword_funlift_Abs_freeletter\n      by    simp\n    ultimately show ?thesis by force\n  next\n    case False\n    with Cons(2) obtain s where s: \"s\\<in>S\" \"y = - f s\" by auto\n    from s(1) x(1) have \"Abs_freeword [(s,False)] + x \\<in> FreeGroup S\"\n      using FreeGroupI_transfer[of _ S] FreeGroup_add_closed[of _ S] by force\n    moreover from s(2) x(2)\n      have  \"freeword_funlift f (Abs_freeword [(s,False)] + x) = sum_list (y#ys)\"\n      using freeword_funlift_add[of f] freeword_funlift_uminus_Abs_freeletter\n      by    simp\n    ultimately show ?thesis by force\n  qed\nqed\n\nlemma freeword_funlift_surj:\n  fixes f :: \"'a \\<Rightarrow> 'b::group_add\"\n  shows \"freeword_funlift f ` FreeGroup S = \\<langle>f`S\\<rangle>\"\nproof (rule seteqI)\n  show \"\\<And>a. a \\<in> freeword_funlift f ` FreeGroup S \\<Longrightarrow> a \\<in> \\<langle>f`S\\<rangle>\"\n    using freeword_funlift_im by auto\nnext\n  fix w assume \"w\\<in>\\<langle>f`S\\<rangle>\"\n  from this obtain ys where ys: \"ys \\<in> lists (f`S \\<union> uminus`f`S)\" \"w = sum_list ys\"\n    using genby_eq_sum_lists[of \"f`S\"] by auto\n  thus \"w \\<in> freeword_funlift f ` FreeGroup S\" using freeword_funlift_surj' by simp\nqed\n\nlemma hom_restrict0_freeword_funlift:\n  \"GroupHom (FreeGroup S) (res_freeword_funlift f S)\"\n  using UGroupHom.restrict0 additive_freeword_funlift FreeGroup_Group\n  by    auto\n\nlemma uniqueness_of_restricted_lift:\n  assumes \"GroupHom (FreeGroup S) T\" \"\\<forall>s\\<in>S. T (Abs_freeletter s) = f s\"\n  shows   \"T = res_freeword_funlift f S\"\nproof\n  fix x\n  define F where \"F \\<equiv> res_freeword_funlift f S\"\n  define u_Abs where \"u_Abs \\<equiv> \\<lambda>a::'a signed. apply_sign Abs_freeletter a\"\n  show \"T x = F x\"\n  proof (cases \"x \\<in> FreeGroup S\")\n    case True\n    have 1: \"set (map u_Abs (freeword x)) \\<subseteq> FreeGroup S\"\n      using u_Abs_def FreeGroupD[OF True]\n            Abs_freeletter_in_FreeGroup_iff[of _ S]\n            FreeGroup_uminus_closed\n      by    auto\n    moreover from u_Abs_def have  \"x = (\\<Sum>a\\<leftarrow>freeword x. u_Abs a)\"\n      using freeword_conv_freeletter_sum_list by fast\n    ultimately\n      have  \"T x = (\\<Sum>a\\<leftarrow>freeword x. T (u_Abs a))\"\n            \"F x = (\\<Sum>a\\<leftarrow>freeword x. F (u_Abs a))\"\n      using F_def\n            GroupHom.im_sum_list_map[OF assms(1), of u_Abs \"freeword x\"]\n            GroupHom.im_sum_list_map[\n              OF hom_restrict0_freeword_funlift,\n              of u_Abs \"freeword x\" S f\n            ]\n      by auto\n    moreover have \"\\<forall>a\\<in>set (freeword x). T (u_Abs a) = F (u_Abs a)\"\n    proof\n      fix a assume \"a \\<in> set (freeword x)\"\n      moreover define b where \"b \\<equiv> Abs_freeletter (fst a)\"\n      ultimately show \"T (u_Abs a) = F (u_Abs a)\"\n        using F_def u_Abs_def True assms(2) FreeGroupD[of x S]\n              GroupHom.im_uminus[OF assms(1)] \n              Abs_freeletter_in_FreeGroup_iff[of \"fst a\" S]\n              GroupHom.im_uminus[OF hom_restrict0_freeword_funlift, of b S f]\n              freeword_funlift_Abs_freeletter[of f]\n        by    auto\n    qed\n    ultimately show ?thesis\n      using F_def\n            sum_list_map_cong[of \"freeword x\" \"\\<lambda>s. T (u_Abs s)\" \"\\<lambda>s. F (u_Abs s)\"]\n      by    simp\n  next\n    case False\n    with assms(1) F_def show ?thesis\n      using hom_restrict0_freeword_funlift GroupHom.supp suppI_contra[of x T]\n            suppI_contra[of x F]\n      by    fastforce\n  qed\nqed\n\ntheorem FreeGroup_universal_property:\n  fixes f :: \"'a \\<Rightarrow> 'b::group_add\"\n  shows \"\\<exists>!T::'a freeword\\<Rightarrow>'b. (\\<forall>s\\<in>S. T (Abs_freeletter s) = f s) \\<and>\n          GroupHom (FreeGroup S) T\"\nproof (rule ex1I, rule conjI)\n  show \"\\<forall>s\\<in>S. res_freeword_funlift f S (Abs_freeletter s) = f s\"\n    using Abs_freeletter_in_FreeGroup_iff[of _ S] freeword_funlift_Abs_freeletter\n    by    auto\n  show \"\\<And>T. (\\<forall>s\\<in>S. T (Abs_freeletter s) = f s) \\<and>\n          GroupHom (FreeGroup S) T \\<Longrightarrow>\n          T = restrict0 (freeword_funlift f) (FreeGroup S)\"\n    using uniqueness_of_restricted_lift by auto\nqed (rule hom_restrict0_freeword_funlift)\n\n\nsubsubsection \\<open>Group presentations\\<close>\n\ntext \\<open>\n  We now define a group presentation to be the quotient of a free group by the subgroup generated by\n  all conjugates of a set of relators. We are most concerned with lifting functions on the letter\n  set to the free group and with the associated induced homomorphisms on the quotient.\n\\<close>\n\nparagraph \\<open>A first group presentation locale and basic facts\\<close>\n\ntext \\<open>\n  Here we define a locale that provides a way to construct a group by providing sets of generators\n  and relator words.\n\\<close>\n\nlocale GroupByPresentation =\n  fixes   S :: \"'a set\"  \\<comment> \\<open>the set of generators\\<close>\n  and     P :: \"'a signed list set\" \\<comment> \\<open>the set of relator words\\<close>\n  assumes P_S: \"ps\\<in>P \\<Longrightarrow> fst ` set ps \\<subseteq> S\"\n  and     proper_P: \"ps\\<in>P \\<Longrightarrow> proper_signed_list ps\"\nbegin\n\nabbreviation \"P' \\<equiv> Abs_freeword ` P\" \\<comment> \\<open>the set of relators\\<close>\nabbreviation \"Q \\<equiv> Group.normal_closure (FreeGroup S) P'\"\n\\<comment> \\<open>the normal subgroup generated by relators inside the free group\\<close>\nabbreviation \"G \\<equiv> Group.quotient_group (FreeGroup S) Q\"\n\nlemmas G_UN = Group.quotient_group_UN[OF FreeGroup_Group, of S Q]\n\nlemma P'_FreeS: \"P' \\<subseteq> FreeGroup S\"\n  using P_S proper_P by (blast intro: FreeGroupI_transfer)\n\nlemma relators: \"P' \\<subseteq> Q\"\n  using FreeGroup_0_closed genby_genset_subset by fastforce\n\nlemmas lconjby_P'_FreeS =\n  Group.set_lconjby_subset_closed[\n    OF FreeGroup_Group _ P'_FreeS, OF basic_monos(1)\n  ]\n\nlemmas Q_FreeS =\n  Group.genby_closed[OF FreeGroup_Group lconjby_P'_FreeS]\n\nlemmas Q_subgroup_FreeS =\n  Group.genby_subgroup[OF FreeGroup_Group lconjby_P'_FreeS]\n\nlemmas normal_Q = Group.normal_closure[OF FreeGroup_Group, OF P'_FreeS]\n\nlemmas natural_hom =\n  Group.natural_quotient_hom[\n    OF FreeGroup_Group Q_subgroup_FreeS normal_Q\n  ]\n\nlemmas natural_hom_image =\n  Group.natural_quotient_hom_image[OF FreeGroup_Group, of S Q]\n\nend (* context GroupByPresentation *)\n\nparagraph \\<open>Functions on the quotient induced from lifted functions\\<close>\n\ntext \\<open>\n  A function on the generator set into a type of class @{class group_add} lifts to a unique\n  homomorphism on the free group. If this lift is trivial on relators, then it factors to a\n  homomorphism of the group described by the generators and relators.\n\\<close>\n\nlocale GroupByPresentationInducedFun = GroupByPresentation S P\n  for     S :: \"'a set\"\n  and     P :: \"'a signed list set\" \\<comment> \\<open>the set of relator words\\<close>\n+ fixes   f :: \"'a \\<Rightarrow> 'b::group_add\"\n  assumes lift_f_trivial_P:\n    \"ps\\<in>P \\<Longrightarrow> freeword_funlift f (Abs_freeword ps) = 0\"\nbegin\n\nabbreviation \"lift_f \\<equiv> freeword_funlift f\"\n\ndefinition induced_hom :: \"'a freeword set permutation \\<Rightarrow> 'b\"\n  where \"induced_hom \\<equiv> GroupHom.quotient_hom (FreeGroup S)\n          (restrict0 lift_f (FreeGroup S)) Q\"\n  \\<comment> \\<open>the @{const restrict0} operation is really only necessary to make\n@{const GroupByPresentationInducedFun.induced_hom} a @{const GroupHom}\\<close>\nabbreviation \"F \\<equiv> induced_hom\"\n\nlemma lift_f_trivial_P': \"p\\<in>P' \\<Longrightarrow> lift_f p = 0\"\n  using lift_f_trivial_P by fast\n\nlemma lift_f_trivial_lconjby_P': \"p\\<in>P' \\<Longrightarrow> lift_f (lconjby w p) = 0\"\n  using freeword_funlift_lconjby[of f] lift_f_trivial_P' by simp\n\nlemma lift_f_trivial_Q: \"q\\<in>Q \\<Longrightarrow> lift_f q = 0\"\nproof (erule genby.induct, rule freeword_funlift_0)\n  show \"\\<And>s. s \\<in> (\\<Union>w \\<in> FreeGroup S. lconjby w ` P') \\<Longrightarrow> lift_f s = 0\"\n    using lift_f_trivial_lconjby_P' by fast\nnext\n  fix w w' :: \"'a freeword\" assume ww': \"lift_f w = 0\" \"lift_f w' = 0\"\n  have \"lift_f (w - w') = lift_f w - lift_f w'\"\n    using freeword_funlift_diff[of f w] by simp\n  with ww' show \"lift_f (w-w') = 0\" by simp\nqed\n\nlemma lift_f_ker_Q: \"Q \\<subseteq> ker lift_f\"\n  using lift_f_trivial_Q unfolding ker_def by auto\n\nlemma lift_f_Ker_Q: \"Q \\<subseteq> GroupHom.Ker (FreeGroup S) lift_f\"\n  using lift_f_ker_Q Q_FreeS by fast\n\nlemma restrict0_lift_f_Ker_Q:\n  \"Q \\<subseteq> GroupHom.Ker (FreeGroup S) (restrict0 lift_f (FreeGroup S))\"\n  using lift_f_Ker_Q ker_subset_ker_restrict0 by fast\n\nlemma induced_hom_equality:\n  \"w \\<in> FreeGroup S \\<Longrightarrow> F (\\<lceil>FreeGroup S|w|Q\\<rceil>) = lift_f w\"\n\\<comment> \\<open>algebraic properties of the induced homomorphism could be proved using its properties as a group\n  homomorphism, but it's generally easier to prove them using the algebraic properties of the lift\n  via this lemma\\<close>\n  unfolding induced_hom_def\n  using     GroupHom.quotient_hom_im hom_restrict0_freeword_funlift\n            Q_subgroup_FreeS normal_Q restrict0_lift_f_Ker_Q\n  by        fastforce\n\nlemma hom_induced_hom: \"GroupHom G F\"\n  unfolding induced_hom_def\n  using     GroupHom.quotient_hom hom_restrict0_freeword_funlift\n            Q_subgroup_FreeS normal_Q restrict0_lift_f_Ker_Q\n  by        fast\n\nlemma induced_hom_Abs_freeletter_equality:\n  \"s\\<in>S \\<Longrightarrow> F (\\<lceil>FreeGroup S|Abs_freeletter s|Q\\<rceil>) = f s\"\n  using Abs_freeletter_in_FreeGroup_iff[of s S]        \n  by    (simp add: induced_hom_equality freeword_funlift_Abs_freeletter)\n\nlemma uniqueness_of_induced_hom':\n  defines \"q \\<equiv> Group.natural_quotient_hom (FreeGroup S) Q\"\n  assumes \"GroupHom G T\" \"\\<forall>s\\<in>S. T (\\<lceil>FreeGroup S|Abs_freeletter s|Q\\<rceil>) = f s\"\n  shows   \"T \\<circ> q = F \\<circ> q\"\nproof-\n  from assms have \"T\\<circ>q = res_freeword_funlift f S\"\n    using natural_hom natural_hom_image Abs_freeletter_in_FreeGroup_iff[of _ S]\n    by    (force intro: uniqueness_of_restricted_lift GroupHom.comp)\n  moreover from q_def have \"F \\<circ> q = res_freeword_funlift f S\"\n    using induced_hom_equality GroupHom.im_zero[OF hom_induced_hom]\n    by    auto\n  ultimately show ?thesis by simp  \nqed\n\nlemma uniqueness_of_induced_hom:\n  assumes \"GroupHom G T\" \"\\<forall>s\\<in>S. T (\\<lceil>FreeGroup S|Abs_freeletter s|Q\\<rceil>) = f s\"\n  shows   \"T = F\"\nproof\n  fix x\n  show \"T x = F x\"\n  proof (cases \"x\\<in>G\")\n    case True\n    define q where \"q \\<equiv> Group.natural_quotient_hom (FreeGroup S) Q\"\n    from True obtain w where \"w \\<in> FreeGroup S\" \"x = (\\<lceil>FreeGroup S|w|Q\\<rceil>)\"\n      using G_UN by fast\n    with q_def have \"T x = (T\\<circ>q) w\" \"F x = (F\\<circ>q) w\" by auto\n    with assms q_def show ?thesis using uniqueness_of_induced_hom' by simp\n  next\n    case False\n    with assms(1) show ?thesis\n      using hom_induced_hom GroupHom.supp suppI_contra[of x T]\n            suppI_contra[of x F]\n      by    fastforce\n  qed\nqed\n\ntheorem induced_hom_universal_property:\n  \"\\<exists>!F. GroupHom G F \\<and> (\\<forall>s\\<in>S. F (\\<lceil>FreeGroup S|Abs_freeletter s|Q\\<rceil>) = f s)\"\n  using hom_induced_hom induced_hom_Abs_freeletter_equality\n        uniqueness_of_induced_hom\n  by    blast\n\nlemma induced_hom_Abs_freelist_conv_sum_list:\n  \"ss\\<in>lists S \\<Longrightarrow> F (\\<lceil>FreeGroup S|Abs_freelist ss|Q\\<rceil>) = (\\<Sum>s\\<leftarrow>ss. f s)\"\n  by  (simp add:\n        Abs_freelist_in_FreeGroup induced_hom_equality freeword_funlift_Abs_freelist\n      )\n\nlemma induced_hom_surj: \"F`G = \\<langle>f`S\\<rangle>\"\nproof (rule seteqI)\n  show \"\\<And>x. x\\<in>F`G \\<Longrightarrow> x\\<in>\\<langle>f`S\\<rangle>\"\n    using G_UN induced_hom_equality freeword_funlift_surj[of f S] by auto\nnext\n  fix x assume \"x\\<in>\\<langle>f`S\\<rangle>\"\n  hence \"x \\<in> lift_f ` FreeGroup S\" using freeword_funlift_surj[of f S] by fast\n  thus \"x \\<in> F`G\" using induced_hom_equality G_UN by force\nqed\n\nend (* context GroupByPresentationInducedFun *)\n\nparagraph \\<open>Groups affording a presentation\\<close>\n\ntext \\<open>\n  The locale @{const GroupByPresentation} allows the construction of a @{const Group} out of any\n  type from a set of generating letters and a set of relator words in (signed) letters. The\n  following locale concerns the question of when the @{const Group} generated by a set in class\n  @{class group_add} is isomorphic to a group presentation.\n\\<close>\n\nlocale GroupWithGeneratorsRelators =\n  fixes S :: \"'g::group_add set\" \\<comment> \\<open>the set of generators\\<close>\n  and   R :: \"'g list set\" \\<comment> \\<open>the set of relator words\\<close>\n  assumes relators: \"rs\\<in>R \\<Longrightarrow> rs \\<in> lists (S \\<union> uminus ` S)\"\n                    \"rs\\<in>R \\<Longrightarrow> sum_list rs = 0\"\n                    \"rs\\<in>R \\<Longrightarrow> proper_signed_list (map (charpair S) rs)\"\nbegin\n\nabbreviation \"P \\<equiv> map (charpair S) ` R\"\nabbreviation \"P' \\<equiv> GroupByPresentation.P' P\"\nabbreviation \"Q \\<equiv> GroupByPresentation.Q S P\"\nabbreviation \"G \\<equiv> GroupByPresentation.G S P\"\nabbreviation \"relator_freeword rs \\<equiv> Abs_freeword (map (charpair S) rs)\"\n\\<comment> \\<open>this maps R onto P'\\<close>\n\nabbreviation \"freeliftid \\<equiv> freeword_funlift id\"\n\nabbreviation induced_id :: \"'g freeword set permutation \\<Rightarrow> 'g\"\n  where \"induced_id \\<equiv> GroupByPresentationInducedFun.induced_hom S P id\"\n\nlemma GroupByPresentation_S_P: \"GroupByPresentation S P\"\nproof\n  show \"\\<And>ps. ps \\<in> P \\<Longrightarrow> fst ` set ps \\<subseteq> S\"\n    using fst_set_map_charpair_un_uminus relators(1) by fast\n  show \"\\<And>ps. ps \\<in> P \\<Longrightarrow> proper_signed_list ps\" using relators(3) by fast\nqed\n\nlemmas G_UN     = GroupByPresentation.G_UN[OF GroupByPresentation_S_P]\nlemmas P'_FreeS = GroupByPresentation.P'_FreeS[OF GroupByPresentation_S_P]\n\nlemma freeliftid_trivial_relator_freeword_R:\n  \"rs\\<in>R \\<Longrightarrow> freeliftid (relator_freeword rs) = 0\"\n  using relators(2,3) freeword_funlift_Abs_freeword[of \"map (charpair S) rs\" id]\n        sum_list_map_cong[of rs \"(apply_sign id) \\<circ> (charpair S)\" id]\n  by    simp\n\nlemma freeliftid_trivial_P: \"ps\\<in>P \\<Longrightarrow> freeliftid (Abs_freeword ps) = 0\"\n  using freeliftid_trivial_relator_freeword_R by fast\n\nlemma GroupByPresentationInducedFun_S_P_id:\n  \"GroupByPresentationInducedFun S P id\"\n  by  (\n        intro_locales, rule GroupByPresentation_S_P,\n        unfold_locales, rule freeliftid_trivial_P\n      )\n\nlemma induced_id_Abs_freelist_conv_sum_list:\n  \"ss\\<in>lists S \\<Longrightarrow> induced_id (\\<lceil>FreeGroup S|Abs_freelist ss|Q\\<rceil>) = sum_list ss\"\n  by  (simp add:\n        GroupByPresentationInducedFun.induced_hom_Abs_freelist_conv_sum_list[\n          OF GroupByPresentationInducedFun_S_P_id\n        ]\n      )\n\nlemma lconj_relator_freeword_R:\n  \"\\<lbrakk> rs\\<in>R; proper_signed_list xs; fst ` set xs \\<subseteq> S \\<rbrakk> \\<Longrightarrow>\n    lconjby (Abs_freeword xs) (relator_freeword rs) \\<in> Q\"\n  by (blast intro: genby_genset_closed FreeGroupI_transfer)\n\nlemma rconj_relator_freeword:\n  assumes \"rs\\<in>R\" \"proper_signed_list xs\" \"fst ` set xs \\<subseteq> S\"\n  shows   \"rconjby (Abs_freeword xs) (relator_freeword rs) \\<in> Q\"\nproof (rule genby_genset_closed, rule UN_I)\n  show \"- Abs_freeword xs \\<in> FreeGroup S\"\n    using FreeGroupI_transfer[OF assms(2,3)] FreeGroup_uminus_closed by fast\n  from assms(1)\n    show  \"rconjby (Abs_freeword xs) (relator_freeword rs) \\<in>\n            lconjby (- Abs_freeword xs) ` Abs_freeword ` P\"\n    by    simp\nqed\n\nlemma lconjby_Abs_freelist_relator_freeword:\n  \"\\<lbrakk> rs\\<in>R; xs\\<in>lists S \\<rbrakk> \\<Longrightarrow> lconjby (Abs_freelist xs) (relator_freeword rs) \\<in> Q\"\n  using proper_signed_list_map_uniform_snd by (force intro: lconj_relator_freeword_R)\n\ntext \\<open>\n  Here we record that the lift of the identity map to the free group on @{term S} induces a\n  homomorphic surjection onto the group generated by @{term S} from the group presentation on\n  @{term S}, subject to the same relations as the elements of @{term S}.\n\\<close>\n\ntheorem induced_id_hom_surj: \"GroupHom G induced_id\" \"induced_id ` G = \\<langle>S\\<rangle>\"\n  using GroupByPresentationInducedFun.hom_induced_hom[\n          OF GroupByPresentationInducedFun_S_P_id\n        ]\n        GroupByPresentationInducedFun.induced_hom_surj[\n          OF GroupByPresentationInducedFun_S_P_id\n        ]\n  by    auto\n\nend (* context GroupWithGeneratorsRelators *)\n\nlocale GroupPresentation = GroupWithGeneratorsRelators S R\n  for S :: \"'g::group_add set\" \\<comment> \\<open>the set of generators\\<close>\n  and R :: \"'g list set\" \\<comment> \\<open>the set of relator words\\<close>\n+ assumes induced_id_inj: \"inj_on induced_id G\"\nbegin\n\nabbreviation \"inv_induced_id \\<equiv> the_inv_into G induced_id\"\n\nlemma inv_induced_id_sum_list_S:\n  \"ss \\<in> lists S \\<Longrightarrow> inv_induced_id (sum_list ss) = (\\<lceil>FreeGroup S|Abs_freelist ss|Q\\<rceil>)\"\n  using G_UN induced_id_inj induced_id_Abs_freelist_conv_sum_list\n        Abs_freelist_in_FreeGroup\n  by    (blast intro: the_inv_into_f_eq)\n\nend (* GroupPresentation *)\n\nsubsection \\<open>Words over a generating set\\<close>\n\ntext \\<open>\n  Here we gather the necessary constructions and facts for studying a group generated by some set\n  in terms of words in the generators.\n\\<close>\n\ncontext monoid_add\nbegin\n\nabbreviation \"word_for A a as \\<equiv> as \\<in> lists A \\<and> sum_list as = a\"\n\ndefinition reduced_word_for :: \"'a set \\<Rightarrow> 'a \\<Rightarrow> 'a list \\<Rightarrow> bool\"\n  where \"reduced_word_for A a as \\<equiv> is_arg_min length (word_for A a) as\"\n\nabbreviation \"reduced_word A as \\<equiv> reduced_word_for A (sum_list as) as\"\nabbreviation \"reduced_words_for A a \\<equiv> Collect (reduced_word_for A a)\"\n\nabbreviation reduced_letter_set :: \"'a set \\<Rightarrow> 'a \\<Rightarrow> 'a set\"\n  where \"reduced_letter_set A a \\<equiv> \\<Union>( set ` (reduced_words_for A a) )\"\n  \\<comment> \\<open>will be empty if @{term a} is not in the set generated by @{term A}\\<close>\n\ndefinition word_length :: \"'a set \\<Rightarrow> 'a \\<Rightarrow> nat\"\n  where \"word_length A a \\<equiv> length (arg_min length (word_for A a))\"\n\nlemma reduced_word_forI:\n  assumes   \"as \\<in> lists A\" \"sum_list as = a\"\n            \"\\<And>bs. bs \\<in> lists A \\<Longrightarrow> sum_list bs = a \\<Longrightarrow> length as \\<le> length bs\"\n  shows     \"reduced_word_for A a as\"\n  using     assms \n  unfolding reduced_word_for_def\n  by        (force intro: is_arg_minI)\n\nlemma reduced_word_forI_compare:\n  \"\\<lbrakk> reduced_word_for A a as; bs \\<in> lists A; sum_list bs = a; length bs = length as \\<rbrakk>\n    \\<Longrightarrow> reduced_word_for A a bs\"\n  using reduced_word_for_def is_arg_min_eq[of length] by fast\n\nlemma reduced_word_for_lists: \"reduced_word_for A a as \\<Longrightarrow> as \\<in> lists A\"\n  using reduced_word_for_def is_arg_minD1 by fast\n\nlemma reduced_word_for_sum_list: \"reduced_word_for A a as \\<Longrightarrow> sum_list as = a\"\n  using reduced_word_for_def is_arg_minD1 by fast\n\nlemma reduced_word_for_minimal:\n  \"\\<lbrakk> reduced_word_for A a as; bs \\<in> lists A; sum_list bs = a \\<rbrakk> \\<Longrightarrow>\n    length as \\<le> length bs\"\n  using reduced_word_for_def is_arg_minD2[of length]\n  by fastforce\n\n\n\nlemma reduced_word_for_eq_length:\n  \"reduced_word_for A a as \\<Longrightarrow> reduced_word_for A a bs \\<Longrightarrow> length as = length bs\"\n  using reduced_word_for_length by simp\n\nlemma reduced_word_for_arg_min:\n  \"as \\<in> lists A \\<Longrightarrow> sum_list as = a \\<Longrightarrow>\n    reduced_word_for A a (arg_min length (word_for A a))\"\n  using     is_arg_min_arg_min_nat[of \"word_for A a\"]\n  unfolding reduced_word_for_def\n  by        fast\n\nlemma nil_reduced_word_for_0: \"reduced_word_for A 0 []\"\n  by (auto intro: reduced_word_forI)\n\nlemma reduced_word_for_0_imp_nil: \"reduced_word_for A 0 as \\<Longrightarrow> as = []\"\n  using     nil_reduced_word_for_0[of A] reduced_word_for_minimal[of A 0 as]\n  unfolding reduced_word_for_def is_arg_min_def\n  by (metis (mono_tags, hide_lams) length_0_conv length_greater_0_conv)\n\nlemma not_reduced_word_for:\n  \"\\<lbrakk> bs \\<in> lists A; sum_list bs = a; length bs < length as \\<rbrakk> \\<Longrightarrow>\n    \\<not> reduced_word_for A a as\"\n  using reduced_word_for_minimal by fastforce\n\nlemma reduced_word_for_imp_reduced_word:\n  \"reduced_word_for A a as \\<Longrightarrow> reduced_word A as\"\nunfolding reduced_word_for_def is_arg_min_def\nby (fast intro: reduced_word_forI)\n\nlemma sum_list_zero_nreduced:\n  \"as \\<noteq> [] \\<Longrightarrow> sum_list as = 0 \\<Longrightarrow> \\<not> reduced_word A as\"\n  using not_reduced_word_for[of \"[]\"] by simp\n\nlemma order2_nreduced: \"a+a=0 \\<Longrightarrow> \\<not> reduced_word A [a,a]\"\n  using sum_list_zero_nreduced by simp\n\nlemma reduced_word_append_reduce_contra1:\n  assumes \"\\<not> reduced_word A as\"\n  shows   \"\\<not> reduced_word A (as@bs)\"\nproof (cases \"as \\<in> lists A\" \"bs \\<in> lists A\" rule: two_cases)\n  case both\n  define cs where cs: \"cs \\<equiv> ARG_MIN length cs. cs \\<in> lists A \\<and> sum_list cs = sum_list as\"\n  with both(1) have \"reduced_word_for A (sum_list as) cs\"\n    using reduced_word_for_def is_arg_min_arg_min_nat[of \"word_for A (sum_list as)\"]\n    by    auto\n  with assms both show ?thesis\n    using reduced_word_for_lists reduced_word_for_sum_list\n          reduced_word_for_minimal[of A \"sum_list as\" cs as]\n          reduced_word_forI_compare[of A \"sum_list as\" cs as]\n          not_reduced_word_for[of \"cs@bs\" A \"sum_list (as@bs)\"]\n    by    fastforce\nnext\n  case one thus ?thesis using reduced_word_for_lists by fastforce\nnext\n  case other thus ?thesis using reduced_word_for_lists by fastforce\nnext\n  case neither thus ?thesis using reduced_word_for_lists by fastforce\nqed\n\nlemma reduced_word_append_reduce_contra2:\n  assumes \"\\<not> reduced_word A bs\"\n  shows   \"\\<not> reduced_word A (as@bs)\"\nproof (cases \"as \\<in> lists A\" \"bs \\<in> lists A\" rule: two_cases)\n  case both\n  define cs where cs: \"cs \\<equiv> ARG_MIN length cs. cs \\<in> lists A \\<and> sum_list cs = sum_list bs\"\n  with both(2) have \"reduced_word_for A (sum_list bs) cs\"\n    using reduced_word_for_def is_arg_min_arg_min_nat[of \"word_for A (sum_list bs)\" ]\n    by    auto\n  with assms both show ?thesis\n    using reduced_word_for_lists reduced_word_for_sum_list\n          reduced_word_for_minimal[of A \"sum_list bs\" cs bs]\n          reduced_word_forI_compare[of A \"sum_list bs\" cs bs]\n          not_reduced_word_for[of \"as@cs\" A \"sum_list (as@bs)\"]\n    by    fastforce\nnext\n  case one thus ?thesis using reduced_word_for_lists by fastforce\nnext\n  case other thus ?thesis using reduced_word_for_lists by fastforce\nnext\n  case neither thus ?thesis using reduced_word_for_lists by fastforce\nqed\n\nlemma contains_nreduced_imp_nreduced:\n  \"\\<not> reduced_word A bs \\<Longrightarrow> \\<not> reduced_word A (as@bs@cs)\"\n  using reduced_word_append_reduce_contra1 reduced_word_append_reduce_contra2\n  by    fast\n\nlemma contains_order2_nreduced: \"a+a=0 \\<Longrightarrow> \\<not> reduced_word A (as@[a,a]@bs)\"\n  using order2_nreduced contains_nreduced_imp_nreduced by fast\n\nlemma reduced_word_Cons_reduce_contra:\n  \"\\<not> reduced_word A as \\<Longrightarrow> \\<not> reduced_word A (a#as)\"\n  using reduced_word_append_reduce_contra2[of A as \"[a]\"] by simp\n\nlemma reduced_word_Cons_reduce: \"reduced_word A (a#as) \\<Longrightarrow> reduced_word A as\"\n  using reduced_word_Cons_reduce_contra by fast\n\nlemma reduced_word_singleton:\n  assumes \"a\\<in>A\" \"a\\<noteq>0\"\n  shows   \"reduced_word A [a]\"\nproof (rule reduced_word_forI)\n  from assms(1) show \"[a] \\<in> lists A\" by simp\nnext\n  fix bs assume bs: \"bs \\<in> lists A\" \"sum_list bs = sum_list [a]\"\n  with assms(2) show \"length [a] \\<le> length bs\" by (cases bs) auto\nqed simp\n\nlemma el_reduced:\n  assumes \"0 \\<notin> A\" \"as \\<in> lists A\" \"sum_list as \\<in> A\" \"reduced_word A as\"\n  shows \"length as = 1\"\nproof-\n  define n where n: \"n \\<equiv> length as\"\n  from assms(3) obtain a where \"[a]\\<in>lists A\" \"sum_list as = sum_list [a]\" by auto\n  with n assms(1,3,4) have \"n\\<le>1\" \"n>0\"\n    using reduced_word_for_minimal[of A _ as \"[a]\"] by auto\n  hence \"n = 1\" by simp\n  with n show ?thesis by fast\nqed\n\nlemma reduced_letter_set_0: \"reduced_letter_set A 0 = {}\"\n  using reduced_word_for_0_imp_nil by simp\n\nlemma reduced_letter_set_subset: \"reduced_letter_set A a \\<subseteq> A\"\n  using reduced_word_for_lists by fast\n\nlemma reduced_word_forI_length:\n  \"\\<lbrakk> as \\<in> lists A; sum_list as = a; length as = word_length A a \\<rbrakk> \\<Longrightarrow>\n    reduced_word_for A a as\"\n  using reduced_word_for_arg_min reduced_word_for_length\n        reduced_word_forI_compare[of A a _ as]\n  by    fastforce\n\nlemma word_length_le:\n  \"as \\<in> lists A \\<Longrightarrow> sum_list as = a \\<Longrightarrow> word_length A a \\<le> length as\"\n  using reduced_word_for_arg_min reduced_word_for_length\n        reduced_word_for_minimal[of A]\n  by    fastforce\n\nlemma reduced_word_forI_length':\n  \"\\<lbrakk> as \\<in> lists A; sum_list as = a; length as \\<le> word_length A a \\<rbrakk> \\<Longrightarrow>\n    reduced_word_for A a as\"\n  using word_length_le[of as A] reduced_word_forI_length[of as A] by fastforce\n\nlemma word_length_lt:\n  \"as \\<in> lists A \\<Longrightarrow> sum_list as = a \\<Longrightarrow> \\<not> reduced_word_for A a as \\<Longrightarrow>\n    word_length A a < length as\"\n  using reduced_word_forI_length' by fastforce\n\nend (* context monoid_add *)\n\nlemma in_genby_reduced_letter_set:\n  assumes \"as \\<in> lists A\" \"sum_list as = a\"\n  shows   \"a \\<in> \\<langle>reduced_letter_set A a\\<rangle>\"\nproof-\n  define xs where xs: \"xs \\<equiv> arg_min length (word_for A a)\"\n  with assms have \"xs \\<in> lists (reduced_letter_set A a)\" \"sum_list xs = a\"\n    using reduced_word_for_arg_min[of as A] reduced_word_for_sum_list by auto\n  thus ?thesis using genby_eq_sum_lists by force\nqed\n\nlemma reduced_word_for_genby_arg_min:\n  fixes   A :: \"'a::group_add set\"\n  defines \"B \\<equiv> A \\<union> uminus ` A\"\n  assumes \"a\\<in>\\<langle>A\\<rangle>\"\n  shows   \"reduced_word_for B a (arg_min length (word_for B a))\"\n  using   assms genby_eq_sum_lists[of A] reduced_word_for_arg_min[of _ B a]\n  by      auto\n\n\n\nlemma in_genby_imp_in_reduced_letter_set:\n  fixes   A :: \"'a::group_add set\"\n  defines \"B \\<equiv> A \\<union> uminus ` A\"\n  assumes \"a \\<in> \\<langle>A\\<rangle>\"\n  shows   \"a \\<in> \\<langle>reduced_letter_set B a\\<rangle>\"\n  using   assms genby_eq_sum_lists[of A] in_genby_reduced_letter_set[of _ B]\n  by      auto\n\nlemma in_genby_sym_imp_in_reduced_letter_set:\n  \"uminus ` A \\<subseteq> A \\<Longrightarrow> a \\<in> \\<langle>A\\<rangle> \\<Longrightarrow> a \\<in> \\<langle>reduced_letter_set A a\\<rangle>\"\n  using in_genby_imp_in_reduced_letter_set by (fastforce simp add: Un_absorb2)\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/Buildings/Algebra.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772450055544, "lm_q2_score": 0.8289387998695209, "lm_q1q2_score": 0.7245565424681615}}
{"text": "(* Author: Peter Lammich\n           Tobias Nipkow (tuning)\n*)\n\nsection \\<open>Binomial Heap\\<close>\n\ntheory Binomial_Heap\nimports\n  \"HOL-Library.Pattern_Aliases\"\n  Complex_Main\n  Priority_Queue_Specs\nbegin\n\ntext \\<open>\n  We formalize the binomial heap presentation from Okasaki's book.\n  We show the functional correctness and complexity of all operations.\n\n  The presentation is engineered for simplicity, and most\n  proofs are straightforward and automatic.\n\\<close>\n\nsubsection \\<open>Binomial Tree and Heap Datatype\\<close>\n\ndatatype 'a tree = Node (rank: nat) (root: 'a) (children: \"'a tree list\")\n\ntype_synonym 'a trees = \"'a tree list\"\n\nsubsubsection \\<open>Multiset of elements\\<close>\n\nfun mset_tree :: \"'a::linorder tree \\<Rightarrow> 'a multiset\" where\n  \"mset_tree (Node _ a ts) = {#a#} + (\\<Sum>t\\<in>#mset ts. mset_tree t)\"\n\ndefinition mset_trees :: \"'a::linorder trees \\<Rightarrow> 'a multiset\" where\n  \"mset_trees ts = (\\<Sum>t\\<in>#mset ts. mset_tree t)\"\n\nlemma mset_tree_simp_alt[simp]:\n  \"mset_tree (Node r a ts) = {#a#} + mset_trees ts\"\n  unfolding mset_trees_def by auto\ndeclare mset_tree.simps[simp del]\n\nlemma mset_tree_nonempty[simp]: \"mset_tree t \\<noteq> {#}\"\nby (cases t) auto\n\nlemma mset_trees_Nil[simp]:\n  \"mset_trees [] = {#}\"\nby (auto simp: mset_trees_def)\n\nlemma mset_trees_Cons[simp]: \"mset_trees (t#ts) = mset_tree t + mset_trees ts\"\nby (auto simp: mset_trees_def)\n\nlemma mset_trees_empty_iff[simp]: \"mset_trees ts = {#} \\<longleftrightarrow> ts=[]\"\nby (auto simp: mset_trees_def)\n\nlemma root_in_mset[simp]: \"root t \\<in># mset_tree t\"\nby (cases t) auto\n\nlemma mset_trees_rev_eq[simp]: \"mset_trees (rev ts) = mset_trees ts\"\nby (auto simp: mset_trees_def)\n\nsubsubsection \\<open>Invariants\\<close>\n\ntext \\<open>Binomial tree\\<close>\nfun btree :: \"'a::linorder tree \\<Rightarrow> bool\" where\n\"btree (Node r x ts) \\<longleftrightarrow>\n   (\\<forall>t\\<in>set ts. btree t) \\<and> map rank ts = rev [0..<r]\"\n\ntext \\<open>Heap invariant\\<close>\nfun heap :: \"'a::linorder tree \\<Rightarrow> bool\" where\n\"heap (Node _ x ts) \\<longleftrightarrow> (\\<forall>t\\<in>set ts. heap t \\<and> x \\<le> root t)\"\n\ndefinition \"bheap t \\<longleftrightarrow> btree t \\<and> heap t\"\n\ntext \\<open>Binomial Heap invariant\\<close>\ndefinition \"invar ts \\<longleftrightarrow> (\\<forall>t\\<in>set ts. bheap t) \\<and> (sorted_wrt (<) (map rank ts))\"\n\n\ntext \\<open>The children of a node are a valid heap\\<close>\nlemma invar_children:\n  \"bheap (Node r v ts) \\<Longrightarrow> invar (rev ts)\"\n  by (auto simp: bheap_def invar_def rev_map[symmetric])\n\n\nsubsection \\<open>Operations and Their Functional Correctness\\<close>\n\nsubsubsection \\<open>\\<open>link\\<close>\\<close>\n\ncontext\nincludes pattern_aliases\nbegin\n\nfun link :: \"('a::linorder) tree \\<Rightarrow> 'a tree \\<Rightarrow> 'a tree\" where\n  \"link (Node r x\\<^sub>1 ts\\<^sub>1 =: t\\<^sub>1) (Node r' x\\<^sub>2 ts\\<^sub>2 =: t\\<^sub>2) =\n    (if x\\<^sub>1\\<le>x\\<^sub>2 then Node (r+1) x\\<^sub>1 (t\\<^sub>2#ts\\<^sub>1) else Node (r+1) x\\<^sub>2 (t\\<^sub>1#ts\\<^sub>2))\"\n\nend\n\nlemma invar_link:\n  assumes \"bheap t\\<^sub>1\"\n  assumes \"bheap t\\<^sub>2\"\n  assumes \"rank t\\<^sub>1 = rank t\\<^sub>2\"\n  shows \"bheap (link t\\<^sub>1 t\\<^sub>2)\"\nusing assms unfolding bheap_def\nby (cases \"(t\\<^sub>1, t\\<^sub>2)\" rule: link.cases) auto\n\nlemma rank_link[simp]: \"rank (link t\\<^sub>1 t\\<^sub>2) = rank t\\<^sub>1 + 1\"\nby (cases \"(t\\<^sub>1, t\\<^sub>2)\" rule: link.cases) simp\n\nlemma mset_link[simp]: \"mset_tree (link t\\<^sub>1 t\\<^sub>2) = mset_tree t\\<^sub>1 + mset_tree t\\<^sub>2\"\nby (cases \"(t\\<^sub>1, t\\<^sub>2)\" rule: link.cases) simp\n\nsubsubsection \\<open>\\<open>ins_tree\\<close>\\<close>\n\nfun ins_tree :: \"'a::linorder tree \\<Rightarrow> 'a trees \\<Rightarrow> 'a trees\" where\n  \"ins_tree t [] = [t]\"\n| \"ins_tree t\\<^sub>1 (t\\<^sub>2#ts) =\n  (if rank t\\<^sub>1 < rank t\\<^sub>2 then t\\<^sub>1#t\\<^sub>2#ts else ins_tree (link t\\<^sub>1 t\\<^sub>2) ts)\"\n\nlemma bheap0[simp]: \"bheap (Node 0 x [])\"\nunfolding bheap_def by auto\n\nlemma invar_Cons[simp]:\n  \"invar (t#ts)\n  \\<longleftrightarrow> bheap t \\<and> invar ts \\<and> (\\<forall>t'\\<in>set ts. rank t < rank t')\"\nby (auto simp: invar_def)\n\nlemma invar_ins_tree:\n  assumes \"bheap t\"\n  assumes \"invar ts\"\n  assumes \"\\<forall>t'\\<in>set ts. rank t \\<le> rank t'\"\n  shows \"invar (ins_tree t ts)\"\nusing assms\nby (induction t ts rule: ins_tree.induct) (auto simp: invar_link less_eq_Suc_le[symmetric])\n\nlemma mset_trees_ins_tree[simp]:\n  \"mset_trees (ins_tree t ts) = mset_tree t + mset_trees ts\"\nby (induction t ts rule: ins_tree.induct) auto\n\nlemma ins_tree_rank_bound:\n  assumes \"t' \\<in> set (ins_tree t ts)\"\n  assumes \"\\<forall>t'\\<in>set ts. rank t\\<^sub>0 < rank t'\"\n  assumes \"rank t\\<^sub>0 < rank t\"\n  shows \"rank t\\<^sub>0 < rank t'\"\nusing assms\nby (induction t ts rule: ins_tree.induct) (auto split: if_splits)\n\nsubsubsection \\<open>\\<open>insert\\<close>\\<close>\n\nhide_const (open) insert\n\ndefinition insert :: \"'a::linorder \\<Rightarrow> 'a trees \\<Rightarrow> 'a trees\" where\n\"insert x ts = ins_tree (Node 0 x []) ts\"\n\nlemma invar_insert[simp]: \"invar t \\<Longrightarrow> invar (insert x t)\"\nby (auto intro!: invar_ins_tree simp: insert_def)\n\nlemma mset_trees_insert[simp]: \"mset_trees (insert x t) = {#x#} + mset_trees t\"\nby(auto simp: insert_def)\n\nsubsubsection \\<open>\\<open>merge\\<close>\\<close>\n\ncontext\nincludes pattern_aliases\nbegin\n\nfun merge :: \"'a::linorder trees \\<Rightarrow> 'a trees \\<Rightarrow> 'a trees\" where\n  \"merge ts\\<^sub>1 [] = ts\\<^sub>1\"\n| \"merge [] ts\\<^sub>2 = ts\\<^sub>2\"\n| \"merge (t\\<^sub>1#ts\\<^sub>1 =: h\\<^sub>1) (t\\<^sub>2#ts\\<^sub>2 =: h\\<^sub>2) = (\n    if rank t\\<^sub>1 < rank t\\<^sub>2 then t\\<^sub>1 # merge ts\\<^sub>1 h\\<^sub>2 else\n    if rank t\\<^sub>2 < rank t\\<^sub>1 then t\\<^sub>2 # merge h\\<^sub>1 ts\\<^sub>2\n    else ins_tree (link t\\<^sub>1 t\\<^sub>2) (merge ts\\<^sub>1 ts\\<^sub>2)\n  )\"\n\nend\n\nlemma merge_simp2[simp]: \"merge [] ts\\<^sub>2 = ts\\<^sub>2\"\nby (cases ts\\<^sub>2) auto\n\nlemma merge_rank_bound:\n  assumes \"t' \\<in> set (merge ts\\<^sub>1 ts\\<^sub>2)\"\n  assumes \"\\<forall>t\\<^sub>1\\<in>set ts\\<^sub>1. rank t < rank t\\<^sub>1\"\n  assumes \"\\<forall>t\\<^sub>2\\<in>set ts\\<^sub>2. rank t < rank t\\<^sub>2\"\n  shows \"rank t < rank t'\"\nusing assms\nby (induction ts\\<^sub>1 ts\\<^sub>2 arbitrary: t' rule: merge.induct)\n   (auto split: if_splits simp: ins_tree_rank_bound)\n\nlemma invar_merge[simp]:\n  assumes \"invar ts\\<^sub>1\"\n  assumes \"invar ts\\<^sub>2\"\n  shows \"invar (merge ts\\<^sub>1 ts\\<^sub>2)\"\nusing assms\nby (induction ts\\<^sub>1 ts\\<^sub>2 rule: merge.induct)\n   (auto 0 3 simp: Suc_le_eq intro!: invar_ins_tree invar_link elim!: merge_rank_bound)\n\n\ntext \\<open>Longer, more explicit proof of @{thm [source] invar_merge}, \n      to illustrate the application of the @{thm [source] merge_rank_bound} lemma.\\<close>\nlemma \n  assumes \"invar ts\\<^sub>1\"\n  assumes \"invar ts\\<^sub>2\"\n  shows \"invar (merge ts\\<^sub>1 ts\\<^sub>2)\"\n  using assms\nproof (induction ts\\<^sub>1 ts\\<^sub>2 rule: merge.induct)\n  case (3 t\\<^sub>1 ts\\<^sub>1 t\\<^sub>2 ts\\<^sub>2)\n  \\<comment> \\<open>Invariants of the parts can be shown automatically\\<close>\n  from \"3.prems\" have [simp]: \n    \"bheap t\\<^sub>1\" \"bheap t\\<^sub>2\"\n    (*\"invar (merge (t\\<^sub>1#ts\\<^sub>1) ts\\<^sub>2)\" \n    \"invar (merge ts\\<^sub>1 (t\\<^sub>2#ts\\<^sub>2))\"\n    \"invar (merge ts\\<^sub>1 ts\\<^sub>2)\"*)\n    by auto\n\n  \\<comment> \\<open>These are the three cases of the @{const merge} function\\<close>\n  consider (LT) \"rank t\\<^sub>1 < rank t\\<^sub>2\"\n         | (GT) \"rank t\\<^sub>1 > rank t\\<^sub>2\"\n         | (EQ) \"rank t\\<^sub>1 = rank t\\<^sub>2\"\n    using antisym_conv3 by blast\n  then show ?case proof cases\n    case LT \n    \\<comment> \\<open>@{const merge} takes the first tree from the left heap\\<close>\n    then have \"merge (t\\<^sub>1 # ts\\<^sub>1) (t\\<^sub>2 # ts\\<^sub>2) = t\\<^sub>1 # merge ts\\<^sub>1 (t\\<^sub>2 # ts\\<^sub>2)\" by simp\n    also have \"invar \\<dots>\" proof (simp, intro conjI)\n      \\<comment> \\<open>Invariant follows from induction hypothesis\\<close>\n      show \"invar (merge ts\\<^sub>1 (t\\<^sub>2 # ts\\<^sub>2))\"\n        using LT \"3.IH\" \"3.prems\" by simp\n\n      \\<comment> \\<open>It remains to show that \\<open>t\\<^sub>1\\<close> has smallest rank.\\<close>\n      show \"\\<forall>t'\\<in>set (merge ts\\<^sub>1 (t\\<^sub>2 # ts\\<^sub>2)). rank t\\<^sub>1 < rank t'\"\n        \\<comment> \\<open>Which is done by auxiliary lemma @{thm [source] merge_rank_bound}\\<close>\n        using LT \"3.prems\" by (force elim!: merge_rank_bound)\n    qed\n    finally show ?thesis .\n  next\n    \\<comment> \\<open>@{const merge} takes the first tree from the right heap\\<close>\n    case GT \n    \\<comment> \\<open>The proof is anaologous to the \\<open>LT\\<close> case\\<close>\n    then show ?thesis using \"3.prems\" \"3.IH\" by (force elim!: merge_rank_bound)\n  next\n    case [simp]: EQ\n    \\<comment> \\<open>@{const merge} links both first trees, and inserts them into the merged remaining heaps\\<close>\n    have \"merge (t\\<^sub>1 # ts\\<^sub>1) (t\\<^sub>2 # ts\\<^sub>2) = ins_tree (link t\\<^sub>1 t\\<^sub>2) (merge ts\\<^sub>1 ts\\<^sub>2)\" by simp\n    also have \"invar \\<dots>\" proof (intro invar_ins_tree invar_link) \n      \\<comment> \\<open>Invariant of merged remaining heaps follows by IH\\<close>\n      show \"invar (merge ts\\<^sub>1 ts\\<^sub>2)\"\n        using EQ \"3.prems\" \"3.IH\" by auto\n\n      \\<comment> \\<open>For insertion, we have to show that the rank of the linked tree is \\<open>\\<le>\\<close> the \n          ranks in the merged remaining heaps\\<close>\n      show \"\\<forall>t'\\<in>set (merge ts\\<^sub>1 ts\\<^sub>2). rank (link t\\<^sub>1 t\\<^sub>2) \\<le> rank t'\"\n      proof -\n        \\<comment> \\<open>Which is, again, done with the help of @{thm [source] merge_rank_bound}\\<close>\n        have \"rank (link t\\<^sub>1 t\\<^sub>2) = Suc (rank t\\<^sub>2)\" by simp\n        thus ?thesis using \"3.prems\" by (auto simp: Suc_le_eq elim!: merge_rank_bound)\n      qed\n    qed simp_all\n    finally show ?thesis .\n  qed\nqed auto\n\n\nlemma mset_trees_merge[simp]:\n  \"mset_trees (merge ts\\<^sub>1 ts\\<^sub>2) = mset_trees ts\\<^sub>1 + mset_trees ts\\<^sub>2\"\nby (induction ts\\<^sub>1 ts\\<^sub>2 rule: merge.induct) auto\n\nsubsubsection \\<open>\\<open>get_min\\<close>\\<close>\n\nfun get_min :: \"'a::linorder trees \\<Rightarrow> 'a\" where\n  \"get_min [t] = root t\"\n| \"get_min (t#ts) = min (root t) (get_min ts)\"\n\nlemma bheap_root_min:\n  assumes \"bheap t\"\n  assumes \"x \\<in># mset_tree t\"\n  shows \"root t \\<le> x\"\nusing assms unfolding bheap_def\nby (induction t arbitrary: x rule: mset_tree.induct) (fastforce simp: mset_trees_def)\n\nlemma get_min_mset:\n  assumes \"ts\\<noteq>[]\"\n  assumes \"invar ts\"\n  assumes \"x \\<in># mset_trees ts\"\n  shows \"get_min ts \\<le> x\"\n  using assms\napply (induction ts arbitrary: x rule: get_min.induct)\napply (auto\n      simp: bheap_root_min min_def intro: order_trans;\n      meson linear order_trans bheap_root_min\n      )+\ndone\n\nlemma get_min_member:\n  \"ts\\<noteq>[] \\<Longrightarrow> get_min ts \\<in># mset_trees ts\"\nby (induction ts rule: get_min.induct) (auto simp: min_def)\n\nlemma get_min:\n  assumes \"mset_trees ts \\<noteq> {#}\"\n  assumes \"invar ts\"\n  shows \"get_min ts = Min_mset (mset_trees ts)\"\nusing assms get_min_member get_min_mset\nby (auto simp: eq_Min_iff)\n\nsubsubsection \\<open>\\<open>get_min_rest\\<close>\\<close>\n\nfun get_min_rest :: \"'a::linorder trees \\<Rightarrow> 'a tree \\<times> 'a trees\" where\n  \"get_min_rest [t] = (t,[])\"\n| \"get_min_rest (t#ts) = (let (t',ts') = get_min_rest ts\n                     in if root t \\<le> root t' then (t,ts) else (t',t#ts'))\"\n\nlemma get_min_rest_get_min_same_root:\n  assumes \"ts\\<noteq>[]\"\n  assumes \"get_min_rest ts = (t',ts')\"\n  shows \"root t' = get_min ts\"\nusing assms\nby (induction ts arbitrary: t' ts' rule: get_min.induct) (auto simp: min_def split: prod.splits)\n\nlemma mset_get_min_rest:\n  assumes \"get_min_rest ts = (t',ts')\"\n  assumes \"ts\\<noteq>[]\"\n  shows \"mset ts = {#t'#} + mset ts'\"\nusing assms\nby (induction ts arbitrary: t' ts' rule: get_min.induct) (auto split: prod.splits if_splits)\n\nlemma set_get_min_rest:\n  assumes \"get_min_rest ts = (t', ts')\"\n  assumes \"ts\\<noteq>[]\"\n  shows \"set ts = Set.insert t' (set ts')\"\nusing mset_get_min_rest[OF assms, THEN arg_cong[where f=set_mset]]\nby auto\n\nlemma invar_get_min_rest:\n  assumes \"get_min_rest ts = (t',ts')\"\n  assumes \"ts\\<noteq>[]\"\n  assumes \"invar ts\"\n  shows \"bheap t'\" and \"invar ts'\"\nproof -\n  have \"bheap t' \\<and> invar ts'\"\n    using assms\n    proof (induction ts arbitrary: t' ts' rule: get_min.induct)\n      case (2 t v va)\n      then show ?case\n        apply (clarsimp split: prod.splits if_splits)\n        apply (drule set_get_min_rest; fastforce)\n        done\n    qed auto\n  thus \"bheap t'\" and \"invar ts'\" by auto\nqed\n\nsubsubsection \\<open>\\<open>del_min\\<close>\\<close>\n\ndefinition del_min :: \"'a::linorder trees \\<Rightarrow> 'a::linorder trees\" where\n\"del_min ts = (case get_min_rest ts of\n   (Node r x ts\\<^sub>1, ts\\<^sub>2) \\<Rightarrow> merge (rev ts\\<^sub>1) ts\\<^sub>2)\"\n\nlemma invar_del_min[simp]:\n  assumes \"ts \\<noteq> []\"\n  assumes \"invar ts\"\n  shows \"invar (del_min ts)\"\nusing assms\nunfolding del_min_def\nby (auto\n      split: prod.split tree.split\n      intro!: invar_merge invar_children \n      dest: invar_get_min_rest\n    )\n\nlemma mset_trees_del_min:\n  assumes \"ts \\<noteq> []\"\n  shows \"mset_trees ts = mset_trees (del_min ts) + {# get_min ts #}\"\nusing assms\nunfolding del_min_def\napply (clarsimp split: tree.split prod.split)\napply (frule (1) get_min_rest_get_min_same_root)\napply (frule (1) mset_get_min_rest)\napply (auto simp: mset_trees_def)\ndone\n\n\nsubsubsection \\<open>Instantiating the Priority Queue Locale\\<close>\n\ntext \\<open>Last step of functional correctness proof: combine all the above lemmas\nto show that binomial heaps satisfy the specification of priority queues with merge.\\<close>\n\ninterpretation bheaps: Priority_Queue_Merge\n  where empty = \"[]\" and is_empty = \"(=) []\" and insert = insert\n  and get_min = get_min and del_min = del_min and merge = merge\n  and invar = invar and mset = mset_trees\nproof (unfold_locales, goal_cases)\n  case 1 thus ?case by simp\nnext\n  case 2 thus ?case by auto\nnext\n  case 3 thus ?case by auto\nnext\n  case (4 q)\n  thus ?case using mset_trees_del_min[of q] get_min[OF _ \\<open>invar q\\<close>]\n    by (auto simp: union_single_eq_diff)\nnext\n  case (5 q) thus ?case using get_min[of q] by auto\nnext\n  case 6 thus ?case by (auto simp add: invar_def)\nnext\n  case 7 thus ?case by simp\nnext\n  case 8 thus ?case by simp\nnext\n  case 9 thus ?case by simp\nnext\n  case 10 thus ?case by simp\nqed\n\n\nsubsection \\<open>Complexity\\<close>\n\ntext \\<open>The size of a binomial tree is determined by its rank\\<close>\nlemma size_mset_btree:\n  assumes \"btree t\"\n  shows \"size (mset_tree t) = 2^rank t\"\n  using assms\nproof (induction t)\n  case (Node r v ts)\n  hence IH: \"size (mset_tree t) = 2^rank t\" if \"t \\<in> set ts\" for t\n    using that by auto\n\n  from Node have COMPL: \"map rank ts = rev [0..<r]\" by auto\n\n  have \"size (mset_trees ts) = (\\<Sum>t\\<leftarrow>ts. size (mset_tree t))\"\n    by (induction ts) auto\n  also have \"\\<dots> = (\\<Sum>t\\<leftarrow>ts. 2^rank t)\" using IH\n    by (auto cong: map_cong)\n  also have \"\\<dots> = (\\<Sum>r\\<leftarrow>map rank ts. 2^r)\"\n    by (induction ts) auto\n  also have \"\\<dots> = (\\<Sum>i\\<in>{0..<r}. 2^i)\"\n    unfolding COMPL\n    by (auto simp: rev_map[symmetric] interv_sum_list_conv_sum_set_nat)\n  also have \"\\<dots> = 2^r - 1\"\n    by (induction r) auto\n  finally show ?case\n    by (simp)\nqed\n\nlemma size_mset_tree:\n  assumes \"bheap t\"\n  shows \"size (mset_tree t) = 2^rank t\"\nusing assms unfolding bheap_def\nby (simp add: size_mset_btree)\n\ntext \\<open>The length of a binomial heap is bounded by the number of its elements\\<close>\nlemma size_mset_trees:\n  assumes \"invar ts\"\n  shows \"length ts \\<le> log 2 (size (mset_trees ts) + 1)\"\nproof -\n  from \\<open>invar ts\\<close> have\n    ASC: \"sorted_wrt (<) (map rank ts)\" and\n    TINV: \"\\<forall>t\\<in>set ts. bheap t\"\n    unfolding invar_def by auto\n\n  have \"(2::nat)^length ts = (\\<Sum>i\\<in>{0..<length ts}. 2^i) + 1\"\n    by (simp add: sum_power2)\n  also have \"\\<dots> = (\\<Sum>i\\<leftarrow>[0..<length ts]. 2^i) + 1\" (is \"_ = ?S + 1\")\n    by (simp add: interv_sum_list_conv_sum_set_nat)\n  also have \"?S \\<le> (\\<Sum>t\\<leftarrow>ts. 2^rank t)\" (is \"_ \\<le> ?T\")\n    using sorted_wrt_less_idx[OF ASC] by(simp add: sum_list_mono2)\n  also have \"?T + 1 \\<le> (\\<Sum>t\\<leftarrow>ts. size (mset_tree t)) + 1\" using TINV\n    by (auto cong: map_cong simp: size_mset_tree)\n  also have \"\\<dots> = size (mset_trees ts) + 1\"\n    unfolding mset_trees_def by (induction ts) auto\n  finally have \"2^length ts \\<le> size (mset_trees ts) + 1\" by simp\n  then show ?thesis using le_log2_of_power by blast\nqed\n\nsubsubsection \\<open>Timing Functions\\<close>\n\ntext \\<open>\n  We define timing functions for each operation, and provide\n  estimations of their complexity.\n\\<close>\ndefinition T_link :: \"'a::linorder tree \\<Rightarrow> 'a tree \\<Rightarrow> nat\" where\n[simp]: \"T_link _ _ = 1\"\n\ntext \\<open>This function is non-canonical: we omitted a \\<open>+1\\<close> in the \\<open>else\\<close>-part,\n  to keep the following analysis simpler and more to the point.\n\\<close>\nfun T_ins_tree :: \"'a::linorder tree \\<Rightarrow> 'a trees \\<Rightarrow> nat\" where\n  \"T_ins_tree t [] = 1\"\n| \"T_ins_tree t\\<^sub>1 (t\\<^sub>2 # ts) = (\n    (if rank t\\<^sub>1 < rank t\\<^sub>2 then 1\n     else T_link t\\<^sub>1 t\\<^sub>2 + T_ins_tree (link t\\<^sub>1 t\\<^sub>2) ts)\n  )\"\n\ndefinition T_insert :: \"'a::linorder \\<Rightarrow> 'a trees \\<Rightarrow> nat\" where\n\"T_insert x ts = T_ins_tree (Node 0 x []) ts + 1\"\n\nlemma T_ins_tree_simple_bound: \"T_ins_tree t ts \\<le> length ts + 1\"\nby (induction t ts rule: T_ins_tree.induct) auto\n\nsubsubsection \\<open>\\<open>T_insert\\<close>\\<close>\n\nlemma T_insert_bound:\n  assumes \"invar ts\"\n  shows \"T_insert x ts \\<le> log 2 (size (mset_trees ts) + 1) + 2\"\nproof -\n  have \"real (T_insert x ts) \\<le> real (length ts) + 2\"\n    unfolding T_insert_def using T_ins_tree_simple_bound \n    using of_nat_mono by fastforce\n  also note size_mset_trees[OF \\<open>invar ts\\<close>]\n  finally show ?thesis by simp\nqed\n\nsubsubsection \\<open>\\<open>T_merge\\<close>\\<close>\n\ncontext\nincludes pattern_aliases\nbegin\n\nfun T_merge :: \"'a::linorder trees \\<Rightarrow> 'a trees \\<Rightarrow> nat\" where\n  \"T_merge ts\\<^sub>1 [] = 1\"\n| \"T_merge [] ts\\<^sub>2 = 1\"\n| \"T_merge (t\\<^sub>1#ts\\<^sub>1 =: h\\<^sub>1) (t\\<^sub>2#ts\\<^sub>2 =: h\\<^sub>2) = 1 + (\n    if rank t\\<^sub>1 < rank t\\<^sub>2 then T_merge ts\\<^sub>1 h\\<^sub>2\n    else if rank t\\<^sub>2 < rank t\\<^sub>1 then T_merge h\\<^sub>1 ts\\<^sub>2\n    else T_ins_tree (link t\\<^sub>1 t\\<^sub>2) (merge ts\\<^sub>1 ts\\<^sub>2) + T_merge ts\\<^sub>1 ts\\<^sub>2\n  )\"\n\nend\n\ntext \\<open>A crucial idea is to estimate the time in correlation with the\n  result length, as each carry reduces the length of the result.\\<close>\n\nlemma T_ins_tree_length:\n  \"T_ins_tree t ts + length (ins_tree t ts) = 2 + length ts\"\nby (induction t ts rule: ins_tree.induct) auto\n\nlemma T_merge_length:\n  \"T_merge ts\\<^sub>1 ts\\<^sub>2 + length (merge ts\\<^sub>1 ts\\<^sub>2) \\<le> 2 * (length ts\\<^sub>1 + length ts\\<^sub>2) + 1\"\nby (induction ts\\<^sub>1 ts\\<^sub>2 rule: T_merge.induct)\n   (auto simp: T_ins_tree_length algebra_simps)\n\ntext \\<open>Finally, we get the desired logarithmic bound\\<close>\nlemma T_merge_bound:\n  fixes ts\\<^sub>1 ts\\<^sub>2\n  defines \"n\\<^sub>1 \\<equiv> size (mset_trees ts\\<^sub>1)\"\n  defines \"n\\<^sub>2 \\<equiv> size (mset_trees ts\\<^sub>2)\"\n  assumes \"invar ts\\<^sub>1\" \"invar ts\\<^sub>2\"\n  shows \"T_merge ts\\<^sub>1 ts\\<^sub>2 \\<le> 4*log 2 (n\\<^sub>1 + n\\<^sub>2 + 1) + 1\"\nproof -\n  note n_defs = assms(1,2)\n\n  have \"T_merge ts\\<^sub>1 ts\\<^sub>2 \\<le> 2 * real (length ts\\<^sub>1) + 2 * real (length ts\\<^sub>2) + 1\"\n    using T_merge_length[of ts\\<^sub>1 ts\\<^sub>2] by simp\n  also note size_mset_trees[OF \\<open>invar ts\\<^sub>1\\<close>]\n  also note size_mset_trees[OF \\<open>invar ts\\<^sub>2\\<close>]\n  finally have \"T_merge ts\\<^sub>1 ts\\<^sub>2 \\<le> 2 * log 2 (n\\<^sub>1 + 1) + 2 * log 2 (n\\<^sub>2 + 1) + 1\"\n    unfolding n_defs by (simp add: algebra_simps)\n  also have \"log 2 (n\\<^sub>1 + 1) \\<le> log 2 (n\\<^sub>1 + n\\<^sub>2 + 1)\" \n    unfolding n_defs by (simp add: algebra_simps)\n  also have \"log 2 (n\\<^sub>2 + 1) \\<le> log 2 (n\\<^sub>1 + n\\<^sub>2 + 1)\" \n    unfolding n_defs by (simp add: algebra_simps)\n  finally show ?thesis by (simp add: algebra_simps)\nqed\n\nsubsubsection \\<open>\\<open>T_get_min\\<close>\\<close>\n\nfun T_get_min :: \"'a::linorder trees \\<Rightarrow> nat\" where\n  \"T_get_min [t] = 1\"\n| \"T_get_min (t#ts) = 1 + T_get_min ts\"\n\nlemma T_get_min_estimate: \"ts\\<noteq>[] \\<Longrightarrow> T_get_min ts = length ts\"\nby (induction ts rule: T_get_min.induct) auto\n\nlemma T_get_min_bound:\n  assumes \"invar ts\"\n  assumes \"ts\\<noteq>[]\"\n  shows \"T_get_min ts \\<le> log 2 (size (mset_trees ts) + 1)\"\nproof -\n  have 1: \"T_get_min ts = length ts\" using assms T_get_min_estimate by auto\n  also note size_mset_trees[OF \\<open>invar ts\\<close>]\n  finally show ?thesis .\nqed\n\nsubsubsection \\<open>\\<open>T_del_min\\<close>\\<close>\n\nfun T_get_min_rest :: \"'a::linorder trees \\<Rightarrow> nat\" where\n  \"T_get_min_rest [t] = 1\"\n| \"T_get_min_rest (t#ts) = 1 + T_get_min_rest ts\"\n\nlemma T_get_min_rest_estimate: \"ts\\<noteq>[] \\<Longrightarrow> T_get_min_rest ts = length ts\"\n  by (induction ts rule: T_get_min_rest.induct) auto\n\nlemma T_get_min_rest_bound:\n  assumes \"invar ts\"\n  assumes \"ts\\<noteq>[]\"\n  shows \"T_get_min_rest ts \\<le> log 2 (size (mset_trees ts) + 1)\"\nproof -\n  have 1: \"T_get_min_rest ts = length ts\" using assms T_get_min_rest_estimate by auto\n  also note size_mset_trees[OF \\<open>invar ts\\<close>]\n  finally show ?thesis .\nqed\n\ntext\\<open>Note that although the definition of function \\<^const>\\<open>rev\\<close> has quadratic complexity,\nit can and is implemented (via suitable code lemmas) as a linear time function.\nThus the following definition is justified:\\<close>\n\ndefinition \"T_rev xs = length xs + 1\"\n\ndefinition T_del_min :: \"'a::linorder trees \\<Rightarrow> nat\" where\n  \"T_del_min ts = T_get_min_rest ts + (case get_min_rest ts of (Node _ x ts\\<^sub>1, ts\\<^sub>2)\n                    \\<Rightarrow> T_rev ts\\<^sub>1 + T_merge (rev ts\\<^sub>1) ts\\<^sub>2\n  ) + 1\"\n\nlemma T_del_min_bound:\n  fixes ts\n  defines \"n \\<equiv> size (mset_trees ts)\"\n  assumes \"invar ts\" and \"ts\\<noteq>[]\"\n  shows \"T_del_min ts \\<le> 6 * log 2 (n+1) + 3\"\nproof -\n  obtain r x ts\\<^sub>1 ts\\<^sub>2 where GM: \"get_min_rest ts = (Node r x ts\\<^sub>1, ts\\<^sub>2)\"\n    by (metis surj_pair tree.exhaust_sel)\n\n  have I1: \"invar (rev ts\\<^sub>1)\" and I2: \"invar ts\\<^sub>2\"\n    using invar_get_min_rest[OF GM \\<open>ts\\<noteq>[]\\<close> \\<open>invar ts\\<close>] invar_children\n    by auto\n\n  define n\\<^sub>1 where \"n\\<^sub>1 = size (mset_trees ts\\<^sub>1)\"\n  define n\\<^sub>2 where \"n\\<^sub>2 = size (mset_trees ts\\<^sub>2)\"\n\n  have \"n\\<^sub>1 \\<le> n\" \"n\\<^sub>1 + n\\<^sub>2 \\<le> n\" unfolding n_def n\\<^sub>1_def n\\<^sub>2_def\n    using mset_get_min_rest[OF GM \\<open>ts\\<noteq>[]\\<close>]\n    by (auto simp: mset_trees_def)\n\n  have \"T_del_min ts = real (T_get_min_rest ts) + real (T_rev ts\\<^sub>1) + real (T_merge (rev ts\\<^sub>1) ts\\<^sub>2) + 1\"\n    unfolding T_del_min_def GM\n    by simp\n  also have \"T_get_min_rest ts \\<le> log 2 (n+1)\" \n    using T_get_min_rest_bound[OF \\<open>invar ts\\<close> \\<open>ts\\<noteq>[]\\<close>] unfolding n_def by simp\n  also have \"T_rev ts\\<^sub>1 \\<le> 1 + log 2 (n\\<^sub>1 + 1)\"\n    unfolding T_rev_def n\\<^sub>1_def using size_mset_trees[OF I1] by simp\n  also have \"T_merge (rev ts\\<^sub>1) ts\\<^sub>2 \\<le> 4*log 2 (n\\<^sub>1 + n\\<^sub>2 + 1) + 1\"\n    unfolding n\\<^sub>1_def n\\<^sub>2_def using T_merge_bound[OF I1 I2] by (simp add: algebra_simps)\n  finally have \"T_del_min ts \\<le> log 2 (n+1) + log 2 (n\\<^sub>1 + 1) + 4*log 2 (real (n\\<^sub>1 + n\\<^sub>2) + 1) + 3\"\n    by (simp add: algebra_simps)\n  also note \\<open>n\\<^sub>1 + n\\<^sub>2 \\<le> n\\<close>\n  also note \\<open>n\\<^sub>1 \\<le> n\\<close>\n  finally show ?thesis by (simp add: algebra_simps)\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/Binomial_Heap.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8740772384450967, "lm_q2_score": 0.8289388019824947, "lm_q1q2_score": 0.7245565388768458}}
{"text": "section \\<open>Rules, and the chains we can make with them\\<close>\ntext \\<open>This describes graph rules, and the reasoning is fully on graphs here (no semantics).\n      The formalisation builds up to Lemma 4 in the paper.\\<close>\ntheory RulesAndChains\nimports LabeledGraphs\nbegin\n\ntype_synonym ('l,'v) graph_seq = \"(nat \\<Rightarrow> ('l, 'v) labeled_graph)\"\n\ntext \\<open>Definition 8.\\<close>\ndefinition chain :: \"('l, 'v) graph_seq \\<Rightarrow> bool\" where\n  \"chain S \\<equiv> \\<forall> i. subgraph (S i) (S (i + 1))\"\n\nlemma chain_then_restrict:\n  assumes \"chain S\" shows \"S i = restrict (S i)\"\n  using assms[unfolded chain_def graph_homomorphism_def] by auto\n\nlemma chain:\n  assumes \"chain S\"\n  shows \"j \\<ge> i \\<Longrightarrow> subgraph (S i) (S j)\"\nproof(induct \"j-i\" arbitrary:i j)\n  case 0\n  then show ?case using chain_then_restrict[OF assms] assms[unfolded chain_def] by auto\nnext\n  case (Suc x)\n  hence j:\"i + x + 1 = j\" by auto\n  thus ?case\n    using subgraph_trans[OF Suc(1) assms[unfolded chain_def,rule_format,of \"i+x\"],of i,unfolded j]\n    using Suc by auto\nqed\n\nlemma chain_def2:\n  \"chain S = (\\<forall> i j. j \\<ge> i \\<longrightarrow> subgraph (S i) (S j))\"\nproof\n  show \"chain S \\<Longrightarrow> \\<forall>i j. i \\<le> j \\<longrightarrow> subgraph (S i) (S j)\" using chain by auto\n  show \"\\<forall>i j. i \\<le> j \\<longrightarrow> subgraph (S i) (S j) \\<Longrightarrow> chain S\" unfolding chain_def by simp\nqed\n\ntext \\<open>Second part of definition 8.\\<close>\ndefinition chain_sup :: \"('l, 'v) graph_seq \\<Rightarrow> ('l, 'v) labeled_graph\" where\n  \"chain_sup S \\<equiv> LG (\\<Union> i. edges (S i)) (\\<Union> i. vertices (S i))\"\n\nlemma chain_sup_const[simp]:\n  \"chain_sup (\\<lambda> x. S) = S\"\n  unfolding chain_sup_def by auto\n\nlemma chain_sup_subgraph[intro]:\n  assumes \"chain S\"\n  shows \"subgraph (S j) (chain_sup S)\"\nproof -\n  have c1: \"S j = restrict (S j)\" for j\n    using assms[unfolded chain_def,rule_format,of j] graph_homomorphism_def by auto\n  hence c2: \"chain_sup S = restrict (chain_sup S)\"\n    unfolding chain_sup_def by fastforce\n  have c3: \"graph_union (S j) (chain_sup S) = chain_sup S\"\n    unfolding chain_sup_def graph_union_def by auto\n  show ?thesis unfolding subgraph_def using c1 c2 c3 by auto\nqed\n\nlemma chain_sup_graph[intro]:\n  assumes \"chain S\"\n  shows \"graph (chain_sup S)\"\n  using chain_sup_subgraph[OF assms]\n  unfolding subgraph_def by auto\n\nlemma map_graph_chain_sup:\n\"map_graph g (chain_sup S) = chain_sup (map_graph g o S)\"\n  unfolding map_graph_def chain_sup_def by auto\n\nlemma graph_union_chain_sup[intro]:\n  assumes \"\\<And> i. graph_union (S i) C = C\"\n  shows \"graph_union (chain_sup S) C = C\"\nproof\n  from assms have e:\"edges (S i) \\<subseteq> edges C\" and v:\"vertices (S i) \\<subseteq> vertices C\" for i\n    by (auto simp:graph_union_iff)\n  show \"edges (chain_sup S) \\<subseteq> edges C\" using e unfolding chain_sup_def by auto\n  show \"vertices (chain_sup S) \\<subseteq> vertices C\" using v unfolding chain_sup_def by auto\nqed\n\n\ntype_synonym ('l,'v) Graph_PreRule = \"('l, 'v) labeled_graph \\<times> ('l, 'v) labeled_graph\"\ntext \\<open>Definition 9.\\<close>\nabbreviation graph_rule :: \"('l,'v) Graph_PreRule \\<Rightarrow> bool\" where\n\"graph_rule R \\<equiv> subgraph (fst R) (snd R) \\<and> finite_graph (snd R)\"\n\ndefinition set_of_graph_rules :: \"('l,'v) Graph_PreRule set \\<Rightarrow> bool\" where\n\"set_of_graph_rules Rs \\<equiv> \\<forall> R\\<in>Rs. graph_rule R\"\n\nlemma set_of_graph_rulesD[dest]:\n  assumes \"set_of_graph_rules Rs\" \"R \\<in> Rs\"\n  shows \"finite_graph (fst R)\" \"finite_graph (snd R)\" \"subgraph (fst R) (snd R)\"\n  using assms(1)[unfolded set_of_graph_rules_def] assms(2)\n        rev_finite_subset[of \"vertices (snd R)\"]\n        rev_finite_subset[of \"edges (snd R)\"]\n  unfolding subgraph_def graph_union_iff by auto\n\ntext \\<open>We define @{term agree_on} as an equivalence.\\<close>\ndefinition agree_on where\n\"agree_on G f\\<^sub>1 f\\<^sub>2 \\<equiv> (\\<forall> v \\<in> vertices G. f\\<^sub>1 `` {v} = f\\<^sub>2 `` {v})\"\n\n\n\nlemma agree_on_comm[intro]: \"agree_on X f g = agree_on X g f\" unfolding agree_on_def by auto\nlemma agree_on_refl[intro]:\n  \"agree_on R f f\" unfolding agree_on_def by auto\nlemma agree_on_trans:\n  assumes \"agree_on X f g\" \"agree_on X g h\"\n  shows \"agree_on X f h\" using assms unfolding agree_on_def by auto\n\nlemma agree_on_equivp:\n  shows \"equivp (agree_on G)\"\n  by (auto intro:agree_on_trans intro!:equivpI simp:reflp_def symp_def transp_def agree_on_comm)\n\nlemma agree_on_subset:\n  assumes \"f \\<subseteq> g\" \"vertices G \\<subseteq> Domain f\" \"univalent g\"\n  shows \"agree_on G f g\"\n  using assms unfolding agree_on_def by auto\n\nlemma agree_iff_subset[simp]:\n  assumes \"graph_homomorphism G X f\" \"univalent g\"\n  shows \"agree_on G f g \\<longleftrightarrow> f \\<subseteq> g\"\n  using assms unfolding agree_on_def graph_homomorphism_def by auto\n\nlemma agree_on_ext:\n  assumes \"agree_on G f\\<^sub>1 f\\<^sub>2\"\n  shows \"agree_on G (f\\<^sub>1 O g) (f\\<^sub>2 O g)\"\n  using assms unfolding agree_on_def by auto\n\nlemma agree_on_then_eq:\n  assumes \"agree_on G f\\<^sub>1 f\\<^sub>2\" \"Domain f\\<^sub>1 = vertices G\" \"Domain f\\<^sub>2 = vertices G\"\n  shows \"f\\<^sub>1 = f\\<^sub>2\"\nproof -\n  from assms have agr:\"\\<And> v. v\\<in>Domain f\\<^sub>1 \\<Longrightarrow> f\\<^sub>1 `` {v} = f\\<^sub>2 `` {v}\" unfolding agree_on_def by auto\n  have agr2:\"\\<And> v. v\\<notin>Domain f\\<^sub>1 \\<Longrightarrow> f\\<^sub>1 `` {v} = {}\"\n            \"\\<And> v. v\\<notin>Domain f\\<^sub>2 \\<Longrightarrow> f\\<^sub>2 `` {v} = {}\" by auto\n  with agr agr2 assms have \"\\<And> v. f\\<^sub>1 `` {v} = f\\<^sub>2 `` {v}\" by blast\n  thus ?thesis by auto\nqed\n\nlemma agree_on_subg_compose:\n  assumes \"agree_on R g h\" \"agree_on F f g\" \"subgraph F R\"\n  shows \"agree_on F f h\"\n  using assms unfolding agree_on_def subgraph_def graph_union_iff by auto\n\ndefinition extensible :: \"('l,'x) Graph_PreRule \\<Rightarrow> ('l,'v) labeled_graph \\<Rightarrow> ('x \\<times> 'v) set \\<Rightarrow> bool\"\n  where\n\"extensible R G f \\<equiv> (\\<exists> g. graph_homomorphism (snd R) G g \\<and> agree_on (fst R) f g)\"\n\nlemma extensibleI[intro]: (* not nice as a standard rule, since obtained variables cannot be used *)\n  assumes \"graph_homomorphism R2 G g\" \"agree_on R1 f g\"\n  shows \"extensible (R1,R2) G f\"\n  using assms unfolding extensible_def by auto\n\n\n\nlemma extensible_refl_concr[simp]:\n  assumes \"graph_homomorphism (LG e\\<^sub>1 v) G f\"\n  shows \"extensible (LG e\\<^sub>1 v, LG e\\<^sub>2 v) G f \\<longleftrightarrow> graph_homomorphism (LG e\\<^sub>2 v) G f\"\nproof\n  assume \"extensible (LG e\\<^sub>1 v, LG e\\<^sub>2 v) G f\"\n  then obtain g where g: \"graph_homomorphism (LG e\\<^sub>2 v) G g\" \"agree_on (LG e\\<^sub>1 v) f g\"\n    unfolding extensible_def by auto\n  hence d:\"Domain f = Domain g\" \"univalent f\" \"univalent g\" using assms\n    unfolding graph_homomorphism_def by auto\n  from g have subs:\"f \\<subseteq> g\"\n    by(subst agree_iff_subset[symmetric,OF assms],auto simp:graph_homomorphism_def)\n  with d have \"f = g\" by auto\n  thus \"graph_homomorphism (LG e\\<^sub>2 v) G f\" using g by auto\nqed (auto simp: assms extensible_def)\n\nlemma   extensible_chain_sup[intro]:\nassumes \"chain S\" \"extensible R (S j) f\"\nshows \"extensible R (chain_sup S) f\"\nproof -\n  from assms obtain g where g:\"graph_homomorphism (snd R) (S j) g \\<and> agree_on (fst R) f g\"\n    unfolding extensible_def by auto\n  have [simp]:\"g O Id_on (vertices (S j)) = g\" using g[unfolded graph_homomorphism_def] by auto\n  from g assms(1)\n  have \"graph_homomorphism (snd R) (S j) g\" \"subgraph (S j) (chain_sup S)\" by auto\n  from graph_homomorphism_composes[OF this]\n  have \"graph_homomorphism (snd R) (chain_sup S) g\" by auto\n  thus ?thesis using g unfolding extensible_def by blast\nqed\n\ntext \\<open>Definition 11.\\<close>\ndefinition maintained :: \"('l,'x) Graph_PreRule \\<Rightarrow> ('l,'v) labeled_graph \\<Rightarrow> bool\"\n  where \"maintained R G \\<equiv> \\<forall> f. graph_homomorphism (fst R) G f \\<longrightarrow> extensible R G f\"\n\nabbreviation maintainedA\n  :: \"('l,'x) Graph_PreRule set \\<Rightarrow> ('l, 'v) labeled_graph \\<Rightarrow> bool\"\n  where \"maintainedA Rs G \\<equiv> \\<forall> R\\<in>Rs. maintained R G\"\n\nlemma maintainedI[intro]:\n  assumes \"\\<And> f. graph_homomorphism A G f \\<Longrightarrow> extensible (A,B) G f\"\n  shows \"maintained (A,B) G\"\n  using assms unfolding maintained_def by auto\nlemma maintainedD[dest]:\n  assumes \"maintained (A,B) G\" \"graph_homomorphism A G f\"\n  shows \"extensible (A,B) G f\"\n  using assms unfolding maintained_def by auto\n\nlemma maintainedD2[dest]:\n  assumes \"maintained (A,B) G\" \"graph_homomorphism A G f\"\n          \"\\<And> g. graph_homomorphism B G g \\<Longrightarrow> f \\<subseteq> g \\<Longrightarrow> thesis\"\n        shows thesis\n  using maintainedD[OF assms(1,2),unfolded extensible_def]\nproof\n  fix g\n  assume \"graph_homomorphism (snd (A, B)) G g \\<and> agree_on (fst (A, B)) f g\"\n  hence \"graph_homomorphism B G g\" \"f \\<subseteq> g\"\n    using assms(2) unfolding graph_homomorphism_def2 agree_on_def by auto\n  from assms(3)[OF this] show thesis.\nqed\n\nlemma extensible_refl[intro]:\n  \"graph_homomorphism R G f \\<Longrightarrow> extensible (R,R) G f\"\n  unfolding extensible_def by auto\n\nlemma maintained_refl[intro]:\n  \"maintained (R,R) G\" by auto\n\ntext \\<open>Alternate version of definition 8.\\<close>\ndefinition fin_maintained :: \"('l,'x) Graph_PreRule \\<Rightarrow> ('l,'v) labeled_graph \\<Rightarrow> bool\"\n  where\n\"fin_maintained R G \\<equiv> \\<forall> F f. finite_graph F\n                         \\<longrightarrow> subgraph F (fst R)\n                         \\<longrightarrow> extensible (F,fst R) G f\n                         \\<longrightarrow> graph_homomorphism F G f\n                         \\<longrightarrow> extensible (F,snd R) G f\"\n\nlemma fin_maintainedI [intro]:\n  assumes \"\\<And> F f. finite_graph F\n           \\<Longrightarrow> subgraph F (fst R)\n           \\<Longrightarrow> extensible (F,fst R) G f\n           \\<Longrightarrow> graph_homomorphism F G f\n           \\<Longrightarrow> extensible (F,snd R) G f\"\n  shows \"fin_maintained R G\" using assms unfolding fin_maintained_def by auto\n\nlemma maintained_then_fin_maintained[simp]:\n  assumes maintained:\"maintained R G\"\n  shows \"fin_maintained R G\"\nproof\n  fix F f\n  assume subg:\"subgraph F (fst R)\"\n     and ext:\"extensible (F, fst R) G f\" and igh:\"graph_homomorphism F G f\"\n  from ext[unfolded extensible_def prod.sel] obtain g where\n     g:\"graph_homomorphism (fst R) G g\" \"agree_on F f g\" by blast\n  from maintained[unfolded maintained_def,rule_format,OF g(1)] g(2) subg\n       agree_on_subg_compose\n  show \"extensible (F, snd R) G f\" unfolding extensible_def prod.sel by blast\nqed\n\nlemma fin_maintained_maintained:\n  assumes \"finite_graph (fst R)\"\n  shows \"fin_maintained R G \\<longleftrightarrow> maintained R G\" (is \"?lhs = ?rhs\")\nproof\n  from assms rev_finite_subset\n  have fin:\"finite (vertices (fst R))\"\n           \"finite (edges (fst R))\"\n           \"subgraph (fst R) (fst R)\"\n    unfolding subgraph_def graph_union_iff by auto\n  assume ?lhs\n  with fin have \"extensible (fst R, fst R) G f \\<Longrightarrow> graph_homomorphism (fst R) G f\n         \\<Longrightarrow> extensible R G f\" for f unfolding fin_maintained_def by auto \n  thus ?rhs by (simp add: extensible_refl maintained_def)\nqed simp\n\nlemma extend_for_chain:\nassumes \"g 0 = f\"\n    and \"\\<And> i. graph_homomorphism (S i) C (g i)\"\n    and \"\\<And> i. agree_on (S i) (g i) (g (i + 1))\"\n    and \"chain S\"\n  shows \"extensible (S 0, chain_sup S) C f\"\nproof\n  let ?g = \"\\<Union>i. g i\"\n  from assms(4)[unfolded chain_def subgraph_def graph_union_iff]\n  have v:\"vertices (S i) \\<subseteq> vertices (S (i + 1))\"\n    and e:\"edges (S i) \\<subseteq> edges (S (i + 1))\" for i by auto\n  { fix a b i\n    assume a:\"(a, b) \\<in> g i\"\n    hence \"a \\<in> vertices (S i)\" using assms(2)[of i]\n      unfolding graph_homomorphism_def2 by auto\n    from assms(3)[unfolded agree_on_def,rule_format,OF this] a\n    have \"(a, b) \\<in> g (Suc i)\" by auto\n  }\n  hence gi:\"g i \\<subseteq> g (Suc i)\" for i by auto\n  have gij:\"i \\<le> j \\<Longrightarrow> g i \\<subseteq> g j\" for i j proof(induct j)\n    case (Suc j) with gi[of j] show ?case by (cases \"i = Suc j\",auto)\n  qed auto\n  from assms(1) have f_subset:\"f \\<subseteq> ?g\" by auto\n  from assms(2)[of 0,unfolded assms(1)] have domf:\"Domain f = vertices (S 0)\"\n    and grC:\"graph C\" and v_dom:\"vertices (S i) = Domain (g i)\" for i using assms(2)\n    unfolding graph_homomorphism_def by auto\n  { fix x y z i j assume \"(x, y) \\<in> g i\" \"(x, z) \\<in> g j\"\n    with gij[of i \"max i j\"] gij[of j \"max i j\"]\n    have \"(x,y) \\<in> g (max i j)\" \"(x,z) \\<in> g (max i j)\" by auto\n    with assms(2)[unfolded graph_homomorphism_def]\n    have \"y = z\" by auto\n  } note univ_strong = this\n  hence univ:\"univalent ?g\" unfolding univalent_def by auto\n  { fix xa x i\n    assume \"(xa, x) \\<in> g i\"\n    hence \"x \\<in> vertices (map_graph (g i) (S i))\"\n      using assms(2) unfolding graph_homomorphism_def by auto\n    hence \"x \\<in> vertices C\"\n      using assms(2) unfolding graph_homomorphism_def2 graph_union_iff by blast\n  } note eq_v = this\n  { fix l x y x' y' j i\n    assume \"(l,x,y) \\<in> edges (S j)\" \"(x, x') \\<in> g i\" \"(y, y') \\<in> g i\"\n    with gij[of i \"max i j\"] gij[of j \"max i j\"]\n         chain[OF assms(4),unfolded subgraph_def graph_union_iff, of i \"max i j\"]\n         chain[OF assms(4),unfolded subgraph_def graph_union_iff, of j \"max i j\"]\n    have \"(x,x') \\<in> g (max i j)\" \"(y,y') \\<in> g (max i j)\"\n         \"(l,x,y) \\<in> edges (S (max i j))\" by auto\n    hence \"(l, x', y') \\<in> edges C\"\n      using assms(2)[unfolded graph_homomorphism_def2 graph_union_iff] by auto\n  } note eq_e = this\n  have \"graph_union (map_graph (g i) (chain_sup S)) C = C\" for i\n    unfolding graph_union_iff using eq_e eq_v\n    unfolding graph_homomorphism_def2 chain_sup_def by auto\n  hence subg:\"graph_union (map_graph ?g (chain_sup S)) C = C\"\n    apply (rule graph_map_union) using gij by auto\n  have \"(\\<Union>i. vertices (S i)) = (\\<Union>i. Domain (g i))\" using v_dom by auto\n  hence vd:\"vertices (chain_sup S) = Domain ?g\"\n    unfolding chain_sup_def by auto\n  show \"graph_homomorphism (chain_sup S) C ?g\"\n    unfolding graph_homomorphism_def2\n    using univ chain_sup_graph[OF assms(4)] grC vd subg by auto\n  show \"agree_on (S 0) f ?g\" using agree_on_subset[OF f_subset _ univ] domf by auto\nqed\n\ntext \\<open>Definition 8, second part.\\<close>\ndefinition consequence_graph\n  where \"consequence_graph Rs G \\<equiv> graph G \\<and> (\\<forall> R \\<in> Rs. subgraph (fst R) (snd R) \\<and> maintained R G)\"\n\nlemma consequence_graphI[intro]:\n  assumes \"\\<And> R. R\\<in> Rs \\<Longrightarrow> maintained R G\"\n          \"\\<And> R. R\\<in> Rs \\<Longrightarrow> subgraph (fst R) (snd R)\"\n          \"graph G\"\n  shows \"consequence_graph Rs G\"\n  unfolding consequence_graph_def fin_maintained_def using assms by auto\n\nlemma consequence_graphD[dest]:\n  assumes \"consequence_graph Rs G\"\n  shows \"\\<And> R. R\\<in> Rs \\<Longrightarrow> maintained R G\"\n        \"\\<And> R. R\\<in> Rs \\<Longrightarrow> subgraph (fst R) (snd R)\"\n        \"graph G\"\n  using assms unfolding consequence_graph_def fin_maintained_def by auto\n\ntext \\<open>Definition 8 states: If furthermore S is a subgraph of G,\n    and (S, G) is maintained in each consequence graph maintaining Rs,\n    then G is a least consequence graph of S maintaining Rs.\n    Note that the type of 'each consequence graph' isn't given here.\n   Taken literally, this should mean 'for every possible type'.\n   We avoid quantifying on types by making the type an argument.\n   Consequently, when proving 'least', the first argument should be free.\\<close>\ndefinition least\n  :: \"'x itself \\<Rightarrow> (('l, 'v) Graph_PreRule) set \\<Rightarrow> ('l, 'c) labeled_graph \\<Rightarrow> ('l, 'c) labeled_graph \\<Rightarrow> bool\"\n  where \"least _ Rs S G \\<equiv> subgraph S G \\<and> \n            (\\<forall> C :: ('l, 'x) labeled_graph. consequence_graph Rs C \\<longrightarrow> maintained (S,G) C)\"\n\nlemma leastI[intro]:\nassumes \"subgraph S (G:: ('l, 'c) labeled_graph)\"\n        \"\\<And> C :: ('l, 'x) labeled_graph. consequence_graph Rs C \\<Longrightarrow> maintained (S,G) C\"\n      shows \"least (t:: 'x itself) Rs S G\"\n  using assms unfolding least_def by auto\n\ndefinition least_consequence_graph\n  :: \"'x itself \\<Rightarrow> (('l, 'v) Graph_PreRule) set\n     \\<Rightarrow> ('l, 'c) labeled_graph \\<Rightarrow> ('l, 'c) labeled_graph \\<Rightarrow> bool\"\n  where \"least_consequence_graph t Rs S G \\<equiv> consequence_graph Rs G \\<and> least t Rs S G\"\n\nlemma least_consequence_graphI[intro]:\nassumes \"consequence_graph Rs (G:: ('l, 'c) labeled_graph)\"\n        \"subgraph S G\"\n        \"\\<And> C :: ('l, 'x) labeled_graph. consequence_graph Rs C \\<Longrightarrow> maintained (S,G) C\"\n      shows \"least_consequence_graph (t:: 'x itself) Rs S G\"\n  using assms unfolding least_consequence_graph_def least_def by auto\n\ntext \\<open>Definition 12.\\<close>\ndefinition fair_chain where\n  \"fair_chain Rs S \\<equiv> chain S \\<and> \n    (\\<forall> R f i. (R \\<in> Rs \\<and> graph_homomorphism (fst R) (S i) f) \\<longrightarrow> (\\<exists> j. extensible R (S j) f))\"\n\nlemma fair_chainI[intro]:\n  assumes \"chain S\"\n    \"\\<And> R f i. R \\<in> Rs \\<Longrightarrow> graph_homomorphism (fst R) (S i) f \\<Longrightarrow> \\<exists> j. extensible R (S j) f\"\n  shows \"fair_chain Rs S\"\n  using assms unfolding fair_chain_def by blast\n\nlemma fair_chainD:\n  assumes \"fair_chain Rs S\"\n  shows \"chain S\"\n        \"R \\<in> Rs \\<Longrightarrow> graph_homomorphism (fst R) (S i) f \\<Longrightarrow> \\<exists> j. extensible R (S j) f\"\n  using assms unfolding fair_chain_def by blast+\n\nlemma find_graph_occurence_vertices:\n  assumes \"chain S\" \"finite V\" \"univalent f\" \"f `` V \\<subseteq> vertices (chain_sup S)\"\n  shows \"\\<exists> i. f `` V \\<subseteq> vertices (S i)\"\n  using assms(2,4)\nproof(induct V)\n  case empty thus ?case by auto\nnext\n  case (insert v V)\n  from insert.prems have V:\"f `` V \\<subseteq> vertices (chain_sup S)\"\n    and v:\"f `` {v} \\<subseteq> vertices (chain_sup S)\" by auto\n  from insert.hyps(3)[OF V] obtain i where i:\"f `` V \\<subseteq> vertices (S i)\" by auto\n  have \"\\<exists> j. f `` {v} \\<subseteq> vertices (S j)\"\n  proof(cases \"(f `` {v}) = {}\")\n    case False\n    then obtain v' where f:\"(v,v') \\<in> f\" by auto\n    hence \"v' \\<in> vertices (chain_sup S)\" using v by auto\n    then show ?thesis using assms(3) f unfolding chain_sup_def by auto\n  qed auto\n  then obtain j where j:\"f `` {v} \\<subseteq> vertices (S j)\" by blast\n  have sg:\"subgraph (S i) (S (max i j))\" \"subgraph (S j) (S (max i j))\"\n    by(rule chain[OF assms(1)],force)+\n  have V:\"(f \\<inter> V \\<times> UNIV) `` V \\<subseteq> vertices (S (max i j))\"\n    using i subgraph_subset[OF sg(1)] by auto\n  have v:\"f `` {v} \\<subseteq> vertices (S (max i j))\" using j subgraph_subset[OF sg(2)] by auto\n  have \"f `` insert v V \\<subseteq> vertices (S (max i j))\" using v V by auto\n  thus ?case by blast\nqed\n\nlemma find_graph_occurence_edges:\n  assumes \"chain S\" \"finite E\" \"univalent f\"\n        \"on_triple f `` E \\<subseteq> edges (chain_sup S)\"\n      shows \"\\<exists> i. on_triple f `` E \\<subseteq> edges (S i)\"\n  using assms(2,4)\nproof(induct E)\n  case empty thus ?case unfolding graph_homomorphism_def by auto\nnext\n  case (insert e E)\n  have univ:\"univalent (on_triple f)\" using assms(3) by auto\n  have [simp]:\"restrict (S i) = S i\" for i\n    using chain[OF assms(1),unfolded subgraph_def,of i i] by auto\n  from insert.prems have E:\"on_triple f `` E \\<subseteq> edges (chain_sup S)\"\n    and e:\"on_triple f `` {e} \\<subseteq> edges (chain_sup S)\" by auto\n  with insert.hyps obtain i where i:\"on_triple f `` E \\<subseteq> edges (S i)\" by auto\n  have \"\\<exists> j. on_triple f `` {e} \\<subseteq> edges (S j)\"\n  proof(cases \"on_triple f `` {e} = {}\")\n    case False\n    then obtain e' where f:\"(e,e') \\<in> on_triple f\" by auto\n    hence \"e' \\<in> edges (chain_sup S)\" using e by auto\n    then show ?thesis using univ f unfolding chain_sup_def by auto\n  qed auto\n  then obtain j where j:\"on_triple f `` {e} \\<subseteq> edges (S j)\" by blast\n  have sg:\"subgraph (S i) (S (max i j))\" \"subgraph (S j) (S (max i j))\"\n    by(rule chain[OF assms(1)],force)+\n  have E:\"on_triple f `` E \\<subseteq> edges (S (max i j))\"\n    using i subgraph_subset[OF sg(1)] by auto\n  have e:\"on_triple f `` {e} \\<subseteq> edges (S (max i j))\" using j subgraph_subset[OF sg(2)] by auto\n  have \"on_triple f `` insert e E \\<subseteq> edges (S (max i j))\" using e E by auto\n  thus ?case by blast\nqed\n\nlemma find_graph_occurence:\n  assumes \"chain S\" \"finite E\" \"finite V\" \"graph_homomorphism (LG E V) (chain_sup S) f\"\n  shows \"\\<exists> i. graph_homomorphism (LG E V) (S i) f\"\nproof -\n  have [simp]:\"restrict (S i) = S i\" for i\n    using chain[OF assms(1),unfolded subgraph_def,of i i] by auto\n  from assms[unfolded graph_homomorphism_def edge_preserving labeled_graph.sel]\n  have u:\"univalent f\" \n   and e:\"on_triple f `` E \\<subseteq> edges (chain_sup S)\"\n   and v:\"f `` V \\<subseteq> vertices (chain_sup S)\"\n    by blast+\n  from find_graph_occurence_edges[OF assms(1,2) u e]\n  obtain i where i:\"on_triple f `` E \\<subseteq> edges (S i)\" by blast\n  from find_graph_occurence_vertices[OF assms(1,3) u v]\n  obtain j where j:\"f `` V \\<subseteq> vertices (S j)\" by blast\n  have sg:\"subgraph (S i) (S (max i j))\" \"subgraph (S j) (S (max i j))\"\n    by(rule chain[OF assms(1)],force)+\n  have e:\"on_triple f `` E \\<subseteq> edges (S (max i j))\"\n   and v:\"f `` V \\<subseteq> vertices (S (max i j))\"\n    using i j subgraph_subset(2)[OF sg(1)] subgraph_subset(1)[OF sg(2)] by auto\n  have \"graph_homomorphism (LG E V) (S (max i j)) f\"\n  proof(rule graph_homomorphismI)\n    from assms[unfolded graph_homomorphism_def edge_preserving labeled_graph.sel] e v\n    show \"vertices (LG E V) = Domain f\"\n     and \"univalent f\"\n     and \"LG E V = restrict (LG E V)\"\n     and \"f `` vertices (LG E V) \\<subseteq> vertices (S (max i j))\" \n     and \"edge_preserving f (edges (LG E V)) (edges (S (max i j)))\"\n     and \"S (max i j) = restrict (S (max i j))\" by auto\n  qed\n  thus ?thesis by auto\nqed\n\n\ntext \\<open>Lemma 3.\n      Recall that in the paper, graph rules use finite graphs, i.e. both sides should be finite.\n      We strengthen lemma 3 by requiring only the left hand side to be a finite graph.\\<close>\nlemma fair_chain_impl_consequence_graph:\n  assumes \"fair_chain Rs S\" \"\\<And> R. R \\<in> Rs \\<Longrightarrow> subgraph (fst R) (snd R) \\<and> finite_graph (fst R)\"\n  shows \"consequence_graph Rs (chain_sup S)\"\nproof -\n  { fix R assume a:\"R \\<in> Rs\"\n    have fin_v:\"finite (vertices (fst R))\" and fin_e: \"finite (edges (fst R))\"\n      using assms(2)[OF a] by auto\n    { fix f assume \"graph_homomorphism (LG (edges (fst R)) (vertices (fst R))) (chain_sup S) f\"\n      with find_graph_occurence[OF fair_chainD(1)[OF assms(1)] fin_e fin_v]  \n      obtain i where \"graph_homomorphism (fst R) (S i) f\" by auto\n      from fair_chainD(2)[OF assms(1) a this] obtain j\n         where \"extensible R (S j) f\" by blast\n      hence \"extensible R (chain_sup S) f\" using fair_chainD(1)[OF assms(1)] by auto\n    }\n    hence \"maintained R (chain_sup S)\" unfolding maintained_def by auto\n  } note mnt = this\n  from assms have \"chain S\" unfolding fair_chain_def by auto\n  thus ?thesis unfolding consequence_graph_def using mnt assms(2) by blast\nqed\n\ntext \\<open>We extract the weak universal property from the definition of weak pushout step.\n      Again, the paper allows for arbitrary types in the quantifier,\n          but we fix the type here in the definition that will be used in @{term pushout_step}.\n          The type used here should suffice (and we cannot quantify over types anyways)\\<close>\ndefinition weak_universal ::\n    \"'x itself \\<Rightarrow> ('a, 'c) Graph_PreRule \\<Rightarrow> ('a, 'b) labeled_graph \\<Rightarrow> ('a, 'b) labeled_graph \\<Rightarrow>\n     ('c \\<times> 'b) set \\<Rightarrow> ('c \\<times> 'b) set \\<Rightarrow> bool\" where\n\"weak_universal _ R G\\<^sub>1 G\\<^sub>2 f\\<^sub>1 f\\<^sub>2 \\<equiv> (\\<forall> h\\<^sub>1 h\\<^sub>2 G::('a, 'x) labeled_graph.\n             (graph_homomorphism (snd R) G h\\<^sub>1 \\<and> graph_homomorphism G\\<^sub>1 G h\\<^sub>2 \\<and> f\\<^sub>1 O h\\<^sub>2 \\<subseteq> h\\<^sub>1)\n         \\<longrightarrow> (\\<exists> h. graph_homomorphism G\\<^sub>2 G h \\<and> h\\<^sub>2 \\<subseteq> h))\"\n\n\n\nlemma weak_universalI[intro]:\n  assumes \"\\<And> h\\<^sub>1 h\\<^sub>2 G::('a, 'x) labeled_graph.\n         graph_homomorphism (snd R) G h\\<^sub>1 \\<Longrightarrow> graph_homomorphism G\\<^sub>1 G h\\<^sub>2 \\<Longrightarrow> f\\<^sub>1 O h\\<^sub>2 \\<subseteq> h\\<^sub>1\n         \\<Longrightarrow> (\\<exists> h. graph_homomorphism G\\<^sub>2 G h \\<and> h\\<^sub>2 \\<subseteq> h)\"\n  shows \"weak_universal (t:: 'x itself) R (G\\<^sub>1::('a, 'b) labeled_graph) G\\<^sub>2 f\\<^sub>1 f\\<^sub>2\"\n  using assms unfolding weak_universal_def by force\n\n\ntext \\<open>Definition 13\\<close>\ndefinition pushout_step ::\n    \"'x itself \\<Rightarrow> ('a, 'c) Graph_PreRule \\<Rightarrow> ('a, 'b) labeled_graph \\<Rightarrow> ('a, 'b) labeled_graph \\<Rightarrow> bool\" where\n\"pushout_step t R G\\<^sub>1 G\\<^sub>2 \\<equiv> subgraph G\\<^sub>1 G\\<^sub>2 \\<and> \n  (\\<exists> f\\<^sub>1 f\\<^sub>2. graph_homomorphism (fst R) G\\<^sub>1 f\\<^sub>1 \\<and>\n           graph_homomorphism (snd R) G\\<^sub>2 f\\<^sub>2 \\<and>\n           f\\<^sub>1 \\<subseteq> f\\<^sub>2 \\<and>\n           weak_universal t R G\\<^sub>1 G\\<^sub>2 f\\<^sub>1 f\\<^sub>2\n  )\"\n\ntext \\<open>Definition 14\\<close>\ndefinition Simple_WPC ::\n    \"'x itself \\<Rightarrow> (('a, 'b) Graph_PreRule) set \\<Rightarrow> (('a, 'd) graph_seq) \\<Rightarrow> bool\" where\n\"Simple_WPC t Rs S \\<equiv> set_of_graph_rules Rs\n   \\<and> (\\<forall> i. (graph (S i) \\<and> S i = S (Suc i)) \\<or> (\\<exists> R \\<in> Rs. pushout_step t R (S i) (S (Suc i))))\"\n\nlemma Simple_WPCI [intro]:\n  assumes \"set_of_graph_rules Rs\" \"graph (S 0)\"\n          \"\\<And> i. (S i = S (Suc i)) \\<or> (\\<exists> R \\<in> Rs. pushout_step t R (S i) (S (Suc i)))\"\n        shows \"Simple_WPC t Rs S\"\nproof -\n  have \"graph (S i)\" for i proof(induct i)\n    case (Suc i)\n    then show ?case using assms(3) unfolding pushout_step_def subgraph_def by metis\n  qed (fact assms)\n  thus ?thesis using assms unfolding Simple_WPC_def by auto\nqed\n\nlemma Simple_WPC_Chain[simp]:\n  assumes \"Simple_WPC t Rs S\"\n  shows \"chain S\"\nproof -\n  have \"subgraph (S i) (S (Suc i))\" for i using assms\n    unfolding Simple_WPC_def pushout_step_def by (cases \"graph (S i) \\<and> S i = S (Suc i)\",auto)\n  thus ?thesis unfolding chain_def by auto\nqed\n\n\ntext \\<open>Definition 14, second part. \\<close>\ninductive WPC ::\n    \"'x itself \\<Rightarrow> (('a, 'b) Graph_PreRule) set \\<Rightarrow> (('a, 'd) graph_seq) \\<Rightarrow> bool\"\n  where\n    wpc_simpl [simp, intro]: \"Simple_WPC t Rs S \\<Longrightarrow> WPC t Rs S\"\n  | wpc_combo [simp, intro]: \"chain S \\<Longrightarrow> (\\<And> i. \\<exists> S'. S' 0 = S i \\<and> chain_sup S' = S (Suc i) \\<and> WPC t Rs S') \\<Longrightarrow> WPC t Rs S\"\n\nlemma extensible_from_chainI:\n  assumes ch:\"chain S\"\n  and igh:\"graph_homomorphism (S 0) C f\"\n  and ind:\"\\<And> f i. graph_homomorphism (S i) C f \\<Longrightarrow>\n                \\<exists>h. (graph_homomorphism (S (Suc i)) C h) \\<and> agree_on (S i) f h\"\n  shows \"extensible (S 0,chain_sup S) C f\"\nproof -\n  have ch:\"chain S\" using assms by auto\n  hence r0:\"\\<exists>x. graph_homomorphism (S 0) C x \\<and> (0 = 0 \\<longrightarrow> x = f)\"\n    using igh by auto\n  { fix i x\n    assume \"graph_homomorphism (S i) C x \\<and> (i = 0 \\<longrightarrow> x = f)\"\n    hence \"graph_homomorphism (S i) C x\" by auto\n    from ind[OF this]\n    have \"\\<exists>y. (graph_homomorphism (S (Suc i)) C y \\<and> (Suc i = 0 \\<longrightarrow> y = f)) \\<and> agree_on (S i) x y\"\n      by auto\n  }\n  with r0\n  have \"\\<exists> g. (\\<forall> i. (graph_homomorphism (S i) C (g i) \\<and> (i = 0 \\<longrightarrow> g i = f))\n                \\<and> agree_on (S i) (g i) (g (Suc i)) )\" by (rule dependent_nat_choice)\n  then obtain g where\n       mtn:\"g 0 = f\"\n           \"graph_homomorphism (S i) C (g i)\"\n           \"agree_on (S i) (g i) (g (i + 1))\" for i by auto\n  from extend_for_chain[OF mtn ch] show ?thesis.\nqed\n\ntext \\<open>Towards Lemma 4, this is the key inductive property.\\<close>\nlemma wpc_least:\n  assumes \"WPC (t:: 'x itself) Rs S\"\n  shows \"least t Rs (S 0) (chain_sup S)\"\n  using assms\nproof(induction S)\n  case (wpc_simpl t Rs S)\n  hence gr:\"set_of_graph_rules Rs\"\n    and ps:\"\\<And> i. S i = S (Suc i) \\<or> (\\<exists>R\\<in>Rs. pushout_step t R (S i) (S (i + 1)))\"\n    unfolding Simple_WPC_def by auto\n  have ch[intro]:\"chain S\" using wpc_simpl by auto\n  show ?case\n  proof fix C::\"('a,'x) labeled_graph\"\n    assume cgC:\"consequence_graph Rs C\"\n    show \"maintained (S 0, chain_sup S) C\"\n    proof(standard,rule extensible_from_chainI,goal_cases)\n      case (3 f x i)\n      show ?case proof(cases \"S i = S (Suc i)\")\n        case True\n        with 3 show ?thesis by auto\n      next\n        case False\n        with ps[of i,unfolded pushout_step_def] obtain R f\\<^sub>1 f\\<^sub>2 where\n        R:\"(fst R,snd R) \\<in> Rs\" and f\\<^sub>1:\"graph_homomorphism (fst R) (S i) f\\<^sub>1\"\n        and wu:\"weak_universal t R (S i) (S (i + 1)) f\\<^sub>1 f\\<^sub>2\" by auto\n        from graph_homomorphism_composes[OF f\\<^sub>1 3(2)]\n        have ih_comp:\"graph_homomorphism (fst R) C (f\\<^sub>1 O x)\".\n        with maintainedD[OF consequence_graphD(1)[OF cgC R]]\n        have \"extensible (fst R, snd R) C (f\\<^sub>1 O x)\" by auto\n        from this[unfolded extensible_def prod.sel]\n        obtain g where g:\"graph_homomorphism (snd R) C g\" \"f\\<^sub>1 O x \\<subseteq> g\"\n          using agree_iff_subset[OF ih_comp] unfolding graph_homomorphism_def by auto\n        from weak_universalD[OF wu g(1) 3(2) g(2)] obtain h where\n          h:\"graph_homomorphism (S (i + 1)) C h\" \"x \\<subseteq> h\" by auto\n        hence \"agree_on (S i) x h\"\n          by(subst agree_iff_subset[OF 3(2)], auto simp:graph_homomorphism_def)\n        then show ?thesis using h(1) by auto\n      qed\n    qed auto\n  qed auto\nnext\n  case (wpc_combo S t Rs)\n  hence ps:\"\\<And> i. \\<exists>S'. S' 0 = S i \\<and>\n         chain_sup S' = S (Suc i) \\<and>\n         WPC t Rs S' \\<and>\n         least t Rs (S' 0) (chain_sup S')\"\n    and ch[intro]:\"chain S\" unfolding Simple_WPC_def by auto\n  show ?case proof fix C :: \"('a, 'x) labeled_graph\"\n    assume cgC:\"consequence_graph Rs C\"\n    show \"maintained (S 0, chain_sup S) C\"\n    proof(standard,rule extensible_from_chainI,goal_cases)\n      case (3 f g i)\n      from ps[of i] have \"least t Rs (S i) (S (Suc i))\" by auto\n      with cgC have ss:\"subgraph (S i) (S (Suc i))\" \"maintained (S i, S (Suc i)) C\"\n        unfolding least_def by auto\n      from ss(2) 3(2) have \"extensible (S i, S (Suc i)) C g\" by auto\n      thus ?case unfolding extensible_def prod.sel.\n    qed auto\n  qed auto\nqed\n\ntext \\<open>Lemma 4.\\<close>\nlemma wpc_least_consequence_graph:\n  assumes \"WPC t Rs S\" \"consequence_graph Rs (chain_sup S)\"\n  shows \"least_consequence_graph t Rs (S 0) (chain_sup S)\"\n  using wpc_least assms unfolding least_consequence_graph_def 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/Graph_Saturation/RulesAndChains.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8740772253241803, "lm_q2_score": 0.8289388125473628, "lm_q1q2_score": 0.7245565372349196}}
{"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_MSortBUPermutes\n  imports \"../../Test_Base\"\nbegin\n\ndatatype 'a list = nil2 | cons2 \"'a\" \"'a list\"\n\nfun map :: \"('a => 'b) => 'a list => 'b list\" where\n  \"map f (nil2) = nil2\"\n| \"map f (cons2 y xs) = cons2 (f y) (map f 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 mergingbu :: \"(int list) list => int list\" where\n  \"mergingbu (nil2) = nil2\"\n| \"mergingbu (cons2 xs (nil2)) = xs\"\n| \"mergingbu (cons2 xs (cons2 z x2)) =\n     mergingbu (pairwise (cons2 xs (cons2 z x2)))\"\n  by pat_completeness auto\n\nfun msortbu :: \"int list => int list\" where\n  \"msortbu x = mergingbu (map (% (y :: int) => cons2 y (nil2)) x)\"\n\nfun elem :: \"'a => 'a list => bool\" where\n  \"elem x (nil2) = False\"\n| \"elem x (cons2 z xs) = ((z = x) | (elem x xs))\"\n\nfun deleteBy :: \"('a => ('a => bool)) => 'a => 'a list =>\n                 'a list\" where\n  \"deleteBy x y (nil2) = nil2\"\n| \"deleteBy x y (cons2 y2 ys) =\n     (if (x y) y2 then ys else cons2 y2 (deleteBy x y ys))\"\n\nfun isPermutation :: \"'a list => 'a list => bool\" where\n  \"isPermutation (nil2) (nil2) = True\"\n| \"isPermutation (nil2) (cons2 z x2) = False\"\n| \"isPermutation (cons2 x3 xs) y =\n     ((elem x3 y) &\n        (isPermutation\n           xs (deleteBy (% (x4 :: 'a) => % (x5 :: 'a) => (x4 = x5)) x3 y)))\"\n\ntheorem property0 :\n  \"isPermutation (msortbu 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_sort_MSortBUPermutes.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887588023318196, "lm_q2_score": 0.8152324848629215, "lm_q1q2_score": 0.7245450468687634}}
{"text": "(*  \n    Title:      Rank.thy\n    Author:     Jose Divas\u00f3n <jose.divasonm at unirioja.es>\n    Author:     Jes\u00fas Aransay <jesus-maria.aransay at unirioja.es>\n    Maintainer: Jose Divas\u00f3n <jose.divasonm at unirioja.es>\n*)\n\nsection\\<open>Rank of a matrix\\<close>\n\ntheory Rank\nimports \n      Rank_Nullity_Theorem.Dim_Formula\nbegin\n\nsubsection\\<open>Row rank, column rank and rank\\<close>\n\ntext\\<open>Definitions of row rank, column rank and rank\\<close>\n\ndefinition row_rank :: \"'a::{field}^'n^'m=>nat\"\n  where \"row_rank A = vec.dim (row_space A)\"\n\ndefinition col_rank :: \"'a::{field}^'n^'m=>nat\"\n  where \"col_rank A = vec.dim (col_space A)\"\n\nlemma rank_def: \"rank A = row_rank A\"\n  by (auto simp: row_rank_def row_rank_def_gen row_space_def)\n\nsubsection\\<open>Properties\\<close>\n\nlemma rrk_is_preserved:\nfixes A::\"'a::{field}^'cols^'rows::{finite, wellorder}\"\n  and P::\"'a::{field}^'rows::{finite, wellorder}^'rows::{finite, wellorder}\"\nassumes inv_P: \"invertible P\"\nshows \"row_rank A = row_rank (P**A)\"\nby (metis row_space_is_preserved row_rank_def inv_P)\n\nlemma crk_is_preserved:\nfixes A::\"'a::{field}^'cols::{finite, wellorder}^'rows\"\n  and P::\"'a::{field}^'rows^'rows\"\nassumes inv_P: \"invertible P\"\nshows \"col_rank A = col_rank (P**A)\"\n  using rank_nullity_theorem_matrices unfolding ncols_def \n  by (metis col_rank_def inv_P nat_add_left_cancel null_space_is_preserved) \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/Gauss_Jordan/Rank.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8887587875995482, "lm_q2_score": 0.8152324803738429, "lm_q1q2_score": 0.724545030868829}}
{"text": "(* Author: Tobias Nipkow *)\n\nsection \\<open>Unbalanced Tree Implementation of Set\\<close>\n\ntheory Tree_Set\nimports\n  \"~~/src/HOL/Library/Tree\"\n  Cmp\n  Set_by_Ordered\nbegin\n\nfun isin :: \"'a::linorder 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\nhide_const (open) insert\n\nfun insert :: \"'a::linorder \\<Rightarrow> 'a tree \\<Rightarrow> 'a tree\" where\n\"insert x Leaf = Node Leaf x Leaf\" |\n\"insert x (Node l a r) =\n  (case cmp x a of\n     LT \\<Rightarrow> Node (insert x l) a r |\n     EQ \\<Rightarrow> Node l a r |\n     GT \\<Rightarrow> Node l a (insert x r))\"\n\nfun del_min :: \"'a tree \\<Rightarrow> 'a * 'a tree\" where\n\"del_min (Node l a r) =\n  (if l = Leaf then (a,r) else let (x,l') = del_min l 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  (case cmp x a of\n     LT \\<Rightarrow>  Node (delete x l) a r |\n     GT \\<Rightarrow>  Node l a (delete x r) |\n     EQ \\<Rightarrow> if r = Leaf then l else let (a',r') = del_min r in Node l a' r')\"\n\n\nsubsection \"Functional Correctness Proofs\"\n\nlemma \"sorted(inorder t) \\<Longrightarrow> isin t x = (x \\<in> elems (inorder t))\"\nby (induction t) (auto simp: elems_simps1)\n\nlemma isin_set: \"sorted(inorder t) \\<Longrightarrow> isin t x = (x \\<in> elems (inorder t))\"\nby (induction t) (auto simp: elems_simps2)\n\n\nlemma inorder_insert:\n  \"sorted(inorder t) \\<Longrightarrow> inorder(insert x t) = ins_list x (inorder t)\"\nby(induction t) (auto simp: ins_list_simps)\n\n\nlemma del_minD:\n  \"del_min t = (x,t') \\<Longrightarrow> t \\<noteq> Leaf \\<Longrightarrow> x # inorder t' = inorder t\"\nby(induction t arbitrary: t' rule: del_min.induct)\n  (auto simp: sorted_lems split: prod.splits if_splits)\n\nlemma inorder_delete:\n  \"sorted(inorder t) \\<Longrightarrow> inorder(delete x t) = del_list x (inorder t)\"\nby(induction t) (auto simp: del_list_simps del_minD split: prod.splits)\n\ninterpretation Set_by_Ordered\nwhere empty = Leaf and isin = isin and insert = insert and delete = delete\nand inorder = inorder and inv = \"\\<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: inorder_insert)\nnext\n  case 4 thus ?case by(simp add: inorder_delete)\nqed (rule TrueI)+\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/Tree_Set.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357735451835, "lm_q2_score": 0.8354835432479661, "lm_q1q2_score": 0.7243941202042711}}
{"text": "(*  Title:      HOL/Datatype_Examples/Koenig.thy\n    Author:     Dmitriy Traytel, TU Muenchen\n    Author:     Andrei Popescu, TU Muenchen\n    Copyright   2012\n\nKoenig's lemma.\n*)\n\nsection \\<open>Koenig's Lemma\\<close>\n\ntheory Koenig\nimports TreeFI \"HOL-Library.Stream\"\nbegin\n\n(* infinite trees: *)\ncoinductive infiniteTr where\n\"\\<lbrakk>tr' \\<in> set (sub tr); infiniteTr tr'\\<rbrakk> \\<Longrightarrow> infiniteTr tr\"\n\nlemma infiniteTr_strong_coind[consumes 1, case_names sub]:\nassumes *: \"phi tr\" and\n**: \"\\<And> tr. phi tr \\<Longrightarrow> \\<exists> tr' \\<in> set (sub tr). phi tr' \\<or> infiniteTr tr'\"\nshows \"infiniteTr tr\"\nusing assms by (elim infiniteTr.coinduct) blast\n\nlemma infiniteTr_coind[consumes 1, case_names sub, induct pred: infiniteTr]:\nassumes *: \"phi tr\" and\n**: \"\\<And> tr. phi tr \\<Longrightarrow> \\<exists> tr' \\<in> set (sub tr). phi tr'\"\nshows \"infiniteTr tr\"\nusing assms by (elim infiniteTr.coinduct) blast\n\nlemma infiniteTr_sub[simp]:\n\"infiniteTr tr \\<Longrightarrow> (\\<exists> tr' \\<in> set (sub tr). infiniteTr tr')\"\nby (erule infiniteTr.cases) blast\n\nprimcorec konigPath where\n  \"shd (konigPath t) = lab t\"\n| \"stl (konigPath t) = konigPath (SOME tr. tr \\<in> set (sub t) \\<and> infiniteTr tr)\"\n\n(* proper paths in trees: *)\ncoinductive properPath where\n\"\\<lbrakk>shd as = lab tr; tr' \\<in> set (sub tr); properPath (stl as) tr'\\<rbrakk> \\<Longrightarrow>\n properPath as tr\"\n\nlemma properPath_strong_coind[consumes 1, case_names shd_lab sub]:\nassumes *: \"phi as tr\" and\n**: \"\\<And> as tr. phi as tr \\<Longrightarrow> shd as = lab tr\" and\n***: \"\\<And> as tr.\n         phi as tr \\<Longrightarrow>\n         \\<exists> tr' \\<in> set (sub tr). phi (stl as) tr' \\<or> properPath (stl as) tr'\"\nshows \"properPath as tr\"\nusing assms by (elim properPath.coinduct) blast\n\nlemma properPath_coind[consumes 1, case_names shd_lab sub, induct pred: properPath]:\nassumes *: \"phi as tr\" and\n**: \"\\<And> as tr. phi as tr \\<Longrightarrow> shd as = lab tr\" and\n***: \"\\<And> as tr.\n         phi as tr \\<Longrightarrow>\n         \\<exists> tr' \\<in> set (sub tr). phi (stl as) tr'\"\nshows \"properPath as tr\"\nusing properPath_strong_coind[of phi, OF * **] *** by blast\n\nlemma properPath_shd_lab:\n\"properPath as tr \\<Longrightarrow> shd as = lab tr\"\nby (erule properPath.cases) blast\n\nlemma properPath_sub:\n\"properPath as tr \\<Longrightarrow>\n \\<exists> tr' \\<in> set (sub tr). phi (stl as) tr' \\<or> properPath (stl as) tr'\"\nby (erule properPath.cases) blast\n\n(* prove the following by coinduction *)\ntheorem Konig:\n  assumes \"infiniteTr tr\"\n  shows \"properPath (konigPath tr) tr\"\nproof-\n  {fix as\n   assume \"infiniteTr tr \\<and> as = konigPath tr\" hence \"properPath as tr\"\n   proof (coinduction arbitrary: tr as rule: properPath_coind)\n     case (sub tr as)\n     let ?t = \"SOME t'. t' \\<in> set (sub tr) \\<and> infiniteTr t'\"\n     from sub have \"\\<exists>t' \\<in> set (sub tr). infiniteTr t'\" by simp\n     then have \"\\<exists>t'. t' \\<in> set (sub tr) \\<and> infiniteTr t'\" by blast\n     then have \"?t \\<in> set (sub tr) \\<and> infiniteTr ?t\" by (rule someI_ex)\n     moreover have \"stl (konigPath tr) = konigPath ?t\" by simp\n     ultimately show ?case using sub by blast\n   qed simp\n  }\n  thus ?thesis using assms by blast\nqed\n\n(* some more stream theorems *)\n\nprimcorec plus :: \"nat stream \\<Rightarrow> nat stream \\<Rightarrow> nat stream\" (infixr \"\\<oplus>\" 66) where\n  \"shd (plus xs ys) = shd xs + shd ys\"\n| \"stl (plus xs ys) = plus (stl xs) (stl ys)\"\n\ndefinition scalar :: \"nat \\<Rightarrow> nat stream \\<Rightarrow> nat stream\" (infixr \"\\<cdot>\" 68) where\n  [simp]: \"scalar n = smap (\\<lambda>x. n * x)\"\n\nprimcorec ones :: \"nat stream\" where \"ones = 1 ## ones\"\nprimcorec twos :: \"nat stream\" where \"twos = 2 ## twos\"\ndefinition ns :: \"nat \\<Rightarrow> nat stream\" where [simp]: \"ns n = scalar n ones\"\n\nlemma \"ones \\<oplus> ones = twos\"\n  by coinduction simp\n\nlemma \"n \\<cdot> twos = ns (2 * n)\"\n  by coinduction simp\n\nlemma prod_scalar: \"(n * m) \\<cdot> xs = n \\<cdot> m \\<cdot> xs\"\n  by (coinduction arbitrary: xs) auto\n\nlemma scalar_plus: \"n \\<cdot> (xs \\<oplus> ys) = n \\<cdot> xs \\<oplus> n \\<cdot> ys\"\n  by (coinduction arbitrary: xs ys) (auto simp: add_mult_distrib2)\n\nlemma plus_comm: \"xs \\<oplus> ys = ys \\<oplus> xs\"\n  by (coinduction arbitrary: xs ys) auto\n\nlemma plus_assoc: \"(xs \\<oplus> ys) \\<oplus> zs = xs \\<oplus> ys \\<oplus> zs\"\n  by (coinduction arbitrary: xs ys zs) 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/Datatype_Examples/Koenig.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357563664173, "lm_q2_score": 0.8354835411997897, "lm_q1q2_score": 0.7243941040758525}}
{"text": "(*<*)theory PDL imports Base begin(*>*)\n\nsubsection\\<open>Propositional Dynamic Logic --- PDL\\<close>\n\ntext\\<open>\\index{PDL|(}\nThe formulae of PDL are built up from atomic propositions via\nnegation and conjunction and the two temporal\nconnectives \\<open>AX\\<close> and \\<open>EF\\<close>\\@. 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\\<close>\n\ndatatype formula = Atom \"atom\"\n                  | Neg formula\n                  | And formula formula\n                  | AX formula\n                  | EF formula\n\ntext\\<open>\\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 \\<open>s \\<Turnstile> f\\<close> instead of\n\\hbox{\\<open>valid s f\\<close>}. The definition is by recursion over the syntax:\n\\<close>\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\\<open>\\noindent\nThe first three equations should be self-explanatory. The temporal formula\n\\<^term>\\<open>AX f\\<close> means that \\<^term>\\<open>f\\<close> is true in \\emph{A}ll ne\\emph{X}t states whereas\n\\<^term>\\<open>EF f\\<close> means that there \\emph{E}xists some \\emph{F}uture state in which \\<^term>\\<open>f\\<close> is\ntrue. The future is expressed via \\<open>\\<^sup>*\\<close>, 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:\\<close>\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\\<open>\\noindent\nOnly the equation for \\<^term>\\<open>EF\\<close> deserves some comments. Remember that the\npostfix \\<open>\\<inverse>\\<close> and the infix \\<open>``\\<close> are predefined and denote the\nconverse of a relation and the image of a set under a relation.  Thus\n\\<^term>\\<open>M\\<inverse> `` T\\<close> is the set of all predecessors of \\<^term>\\<open>T\\<close> and the least\nfixed point (\\<^term>\\<open>lfp\\<close>) of \\<^term>\\<open>\\<lambda>T. mc f \\<union> M\\<inverse> `` T\\<close> is the least set\n\\<^term>\\<open>T\\<close> containing \\<^term>\\<open>mc f\\<close> and all predecessors of \\<^term>\\<open>T\\<close>. If you\nfind it hard to see that \\<^term>\\<open>mc(EF f)\\<close> contains exactly those states from\nwhich there is a path to a state where \\<^term>\\<open>f\\<close> is true, do not worry --- this\nwill be proved in a moment.\n\nFirst we prove monotonicity of the function inside \\<^term>\\<open>lfp\\<close>\nin order to make sure it really has a least fixed point.\n\\<close>\n\nlemma mono_ef: \"mono(\\<lambda>T. A \\<union> (M\\<inverse> `` T))\"\napply(rule monoI)\napply blast\ndone\n\ntext\\<open>\\noindent\nNow we can relate model checking and semantics. For the \\<open>EF\\<close> case we need\na separate lemma:\n\\<close>\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\\<open>\\noindent\nThe equality is proved in the canonical fashion by proving that each set\nincludes the other; the inclusion is shown pointwise:\n\\<close>\n\napply(rule equalityI)\n apply(rule subsetI)\n apply(simp)(*<*)apply(rename_tac s)(*>*)\n\ntxt\\<open>\\noindent\nSimplification leaves us with the following first subgoal\n@{subgoals[display,indent=0,goals_limit=1]}\nwhich is proved by \\<^term>\\<open>lfp\\<close>-induction:\n\\<close>\n\n apply(erule lfp_induct_set)\n  apply(rule mono_ef)\n apply(simp)\ntxt\\<open>\\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 \\<open>blast\\<close>, using the transitivity of \n\\isa{M\\isactrlsup {\\isacharasterisk}}.\n\\<close>\n\n apply(blast intro: rtrancl_trans)\n\ntxt\\<open>\nWe now return to the second set inclusion subgoal, which is again proved\npointwise:\n\\<close>\n\napply(rule subsetI)\napply(simp, clarify)\n\ntxt\\<open>\\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>\\<open>(s,t)\\<in>M\\<^sup>*\\<close>. But since the model\nchecker works backwards (from \\<^term>\\<open>t\\<close> to \\<^term>\\<open>s\\<close>), 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>\\<open>(a,b)\\<in>r\\<^sup>*\\<close> and we know \\<^prop>\\<open>P b\\<close> then we can infer\n\\<^prop>\\<open>P a\\<close> provided each step backwards from a predecessor \\<^term>\\<open>z\\<close> of\n\\<^term>\\<open>b\\<close> preserves \\<^term>\\<open>P\\<close>.\n\\<close>\n\napply(erule converse_rtrancl_induct)\n\ntxt\\<open>\\noindent\nThe base case\n@{subgoals[display,indent=0,goals_limit=1]}\nis solved by unrolling \\<^term>\\<open>lfp\\<close> once\n\\<close>\n\n apply(subst lfp_unfold[OF mono_ef])\n\ntxt\\<open>\n@{subgoals[display,indent=0,goals_limit=1]}\nand disposing of the resulting trivial subgoal automatically:\n\\<close>\n\n apply(blast)\n\ntxt\\<open>\\noindent\nThe proof of the induction step is identical to the one for the base case:\n\\<close>\n\napply(subst lfp_unfold[OF mono_ef])\napply(blast)\ndone\n\ntext\\<open>\nThe main theorem is proved in the familiar manner: induction followed by\n\\<open>auto\\<close> augmented with the lemma as a simplification rule.\n\\<close>\n\ntheorem \"mc f = {s. s \\<Turnstile> f}\"\napply(induct_tac f)\napply(auto simp add: EF_lemma)\ndone\n\ntext\\<open>\n\\begin{exercise}\n\\<^term>\\<open>AX\\<close> has a dual operator \\<^term>\\<open>EN\\<close> \n(``there exists a next state such that'')%\n\\footnote{We cannot use the customary \\<open>EX\\<close>: it is reserved\nas the \\textsc{ascii}-equivalent of \\<open>\\<exists>\\<close>.}\nwith the intended semantics\n@{prop[display]\"(s \\<Turnstile> EN f) = (\\<exists>t. (s,t) \\<in> M \\<and> t \\<Turnstile> f)\"}\nFortunately, \\<^term>\\<open>EN f\\<close> can already be expressed as a PDL formula. How?\n\nShow that the semantics for \\<^term>\\<open>EF\\<close> 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\\<close>\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 \\<in> 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": "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/CTL/PDL.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8354835371034368, "lm_q2_score": 0.8670357598021708, "lm_q1q2_score": 0.7243941033946836}}
{"text": "(*  Title:      Schutz_Spacetime/Util.thy\n    Authors:    Richard Schmoetten, Jake Palmer and Jacques D. Fleuriot\n                University of Edinburgh, 2021          \n*)\ntheory Util\nimports Main\n\nbegin\n\ntext \\<open>Some \"utility\" proofs -- little proofs that come in handy every now and then.\\<close>\n\ntext \\<open>\n  We need this in order to obtain a natural number which can be passed to the ordering function,\n  distinct from two others, in the case of a finite set of events with cardinality a least 3.\n\\<close>\n\nlemma is_free_nat:\n  assumes \"(m::nat) < n\"\n      and \"n < c\"\n      and \"c \\<ge> 3\"\n  shows \"\\<exists>k::nat. k < m \\<or> (m < k \\<and> k < n) \\<or> (n < k \\<and> k < c)\"\nusing assms by presburger\n\ntext \\<open>Helpful proofs on sets.\\<close>\n\nlemma set_le_two [simp]: \"card {a, b} \\<le> 2\"\n  by (simp add: card_insert_if)\n\nlemma set_le_three [simp]: \"card {a, b, c} \\<le> 3\"\n  by (simp add: card_insert_if)\n\nlemma card_subset: \"\\<lbrakk>card Y = n; Y \\<subseteq> X\\<rbrakk> \\<Longrightarrow> card X \\<ge> n \\<or> infinite X\"\n  using card_mono by blast\n\nlemma card_subset_finite: \"\\<lbrakk>finite X; card Y = n; Y \\<subseteq> X\\<rbrakk> \\<Longrightarrow> card X \\<ge> n\"\n  using card_subset by auto\n\nlemma three_subset: \"\\<lbrakk>x \\<noteq> y; x \\<noteq> z; y \\<noteq> z; {x,y,z} \\<subseteq> X\\<rbrakk> \\<Longrightarrow> card X \\<ge> 3 \\<or> infinite X\"\n  apply (case_tac \"finite X\")\n  apply (auto simp : card_mono)\n  apply (erule_tac Y = \"{x,y,z}\" in card_subset_finite)\n  by auto\n\nlemma three_in_set3:\n  assumes \"card X \\<ge> 3\"\n  obtains x y z where \"x\\<in>X\" and \"y\\<in>X\" and \"z\\<in>X\" and \"x\\<noteq>y\" and \"x\\<noteq>z\" and \"y\\<noteq>z\"\n  using assms by (auto simp add: card_le_Suc_iff numeral_3_eq_3)\n\nlemma card_Collect_nat:\n  assumes \"(j::nat)>i\"\n  shows \"card {i..j} = j-i+1\"\n  using card_atLeastAtMost\n  using Suc_diff_le assms le_eq_less_or_eq by presburger\n\nlemma inf_3_elms: assumes \"infinite X\" shows \"(\\<exists>x\\<in>X. \\<exists>y\\<in>X. \\<exists>z\\<in>X. x \\<noteq> y \\<and> y \\<noteq> z \\<and> x \\<noteq> z)\"\nproof -\n  obtain x y where 1: \"x\\<in>X\" \"y\\<in>X\" \"y\\<noteq>x\"\n    by (metis assms finite.emptyI finite.insertI rev_finite_subset singleton_iff subsetI)\n  have \"infinite (X-{x,y})\"\n    using infinite_remove by (simp add: assms)\n  then obtain z where 2: \"z\\<in>X\" \"x\\<noteq>z\" \"z\\<noteq>y\"\n    using infinite_imp_nonempty by (metis Diff_eq_empty_iff insertCI subset_eq)\n  show ?thesis using 1 2 by blast\nqed\n\nlemma card_3_dist: \"card {x,y,z} = 3 \\<longleftrightarrow> x\\<noteq>y \\<and> x\\<noteq>z \\<and> y\\<noteq>z\"\n  by (simp add: eval_nat_numeral card_insert_if)\n\nlemma card_3_eq:\n  \"card X = 3 \\<longleftrightarrow> (\\<exists>x y z. X={x,y,z} \\<and> x \\<noteq> y \\<and> y \\<noteq> z \\<and> x \\<noteq> z)\"\n  (is \"card X = 3 \\<longleftrightarrow> ?card3 X\")\nproof\n  assume asm: \"card X = 3\" hence \"card X \\<ge> 3\" by simp\n  then obtain x y z where \"x \\<noteq> y \\<and> y \\<noteq> z \\<and> x \\<noteq> z\" \"{x,y,z} \\<subseteq> X\"\n    apply (simp add: eval_nat_numeral)\n    by (auto simp add: card_le_Suc_iff)\n  thus \"?card3 X\"\n    using Finite_Set.card_subset_eq \\<open>card X = 3\\<close>\n    apply (simp add: eval_nat_numeral)\n    by (smt (verit, ccfv_threshold) \\<open>{x, y, z} \\<subseteq> X\\<close> card.empty card.infinite card_insert_if\n      card_subset_eq empty_iff finite.emptyI insertE nat.distinct(1))\nnext\n  show \"?card3 X \\<Longrightarrow> card X = 3\"\n    by (smt (z3) card.empty card.insert eval_nat_numeral(2) finite.intros(1) finite_insert insertE\n      insert_absorb insert_not_empty numeral_3_eq_3 semiring_norm(26,27))\nqed\n\n\nlemma card_3_eq':\n    \"\\<lbrakk>card X = 3; card {a,b,c} = 3; {a,b,c} \\<subseteq>X\\<rbrakk> \\<Longrightarrow> X = {a,b,c}\"\n    \"\\<lbrakk>card X = 3; a \\<in> X; b \\<in> X; c \\<in> X; a \\<noteq> b; a \\<noteq> c; b \\<noteq> c\\<rbrakk> \\<Longrightarrow> X = {a,b,c}\"\nproof -\n  show \"\\<lbrakk>card X = 3; card {a,b,c} = 3; {a,b,c} \\<subseteq>X\\<rbrakk> \\<Longrightarrow> X = {a,b,c}\"\n    by (metis card.infinite card_subset_eq zero_neq_numeral)\n  thus \"\\<lbrakk>card X = 3; a \\<in> X; b \\<in> X; c \\<in> X; a \\<noteq> b; a \\<noteq> c; b \\<noteq> c\\<rbrakk> \\<Longrightarrow> X = {a,b,c}\"\n    by (meson card_3_dist empty_subsetI insert_subset)\nqed\n\nlemma card_4_eq:\n  \"card X = 4 \\<longleftrightarrow> (\\<exists>S\\<^sub>1. \\<exists>S\\<^sub>2. \\<exists>S\\<^sub>3. \\<exists>S\\<^sub>4. X = {S\\<^sub>1, S\\<^sub>2, S\\<^sub>3, S\\<^sub>4} \\<and>\n    S\\<^sub>1 \\<noteq> S\\<^sub>2 \\<and> S\\<^sub>1 \\<noteq> S\\<^sub>3 \\<and> S\\<^sub>1 \\<noteq> S\\<^sub>4 \\<and> S\\<^sub>2 \\<noteq> S\\<^sub>3 \\<and> S\\<^sub>2 \\<noteq> S\\<^sub>4 \\<and> S\\<^sub>3 \\<noteq> S\\<^sub>4)\"\n  (is \"card X = 4 \\<longleftrightarrow> ?card4 X\")\nproof\n  assume \"card X = 4\"\n  hence \"card X \\<ge> 4\" by auto\n  then obtain S\\<^sub>1 S\\<^sub>2 S\\<^sub>3 S\\<^sub>4 where\n    0: \"S\\<^sub>1\\<in>X \\<and> S\\<^sub>2\\<in>X \\<and> S\\<^sub>3\\<in>X \\<and> S\\<^sub>4\\<in>X\" and\n    1: \"S\\<^sub>1 \\<noteq> S\\<^sub>2 \\<and> S\\<^sub>1 \\<noteq> S\\<^sub>3 \\<and> S\\<^sub>1 \\<noteq> S\\<^sub>4 \\<and> S\\<^sub>2 \\<noteq> S\\<^sub>3 \\<and> S\\<^sub>2 \\<noteq> S\\<^sub>4 \\<and> S\\<^sub>3 \\<noteq> S\\<^sub>4\"\n    apply (simp add: eval_nat_numeral)\n    by (auto simp add: card_le_Suc_iff)\n  then have 2: \"{S\\<^sub>1, S\\<^sub>2, S\\<^sub>3, S\\<^sub>4} \\<subseteq> X\" \"card {S\\<^sub>1, S\\<^sub>2, S\\<^sub>3, S\\<^sub>4} = 4\" by auto\n  have \"X = {S\\<^sub>1, S\\<^sub>2, S\\<^sub>3, S\\<^sub>4}\"\n    using Finite_Set.card_subset_eq \\<open>card X = 4\\<close>\n    apply (simp add: eval_nat_numeral)\n    by (smt (z3) \\<open>card X = 4\\<close> 2 card.infinite card_subset_eq nat.distinct(1))\n  thus \"?card4 X\" using 1 by blast\nnext\n  show \"?card4 X \\<Longrightarrow> card X = 4\"\n    by (smt (z3) card.empty card.insert eval_nat_numeral(2) finite.intros(1) finite_insert insertE\n      insert_absorb insert_not_empty numeral_3_eq_3 semiring_norm(26,27))\nqed\n\n\ntext \\<open>These lemmas make life easier with some of the ordering proofs.\\<close>\n\nlemma less_3_cases: \"n < 3 \\<Longrightarrow> n = 0 \\<or> n = Suc 0 \\<or> n = Suc (Suc 0)\"\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/Schutz_Spacetime/Util.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835207180243, "lm_q2_score": 0.8670357546485408, "lm_q1q2_score": 0.7243940848821719}}
{"text": "theory E2_11\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 x = x\" |\n  \"eval (Const e) x = e\" |\n  \"eval (Add lhs rhs) x = (eval lhs x) + (eval rhs x)\" |\n  \"eval (Mult lhs rhs) x = (eval lhs x) * (eval rhs x)\"\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 add_coeffs :: \"int list \\<Rightarrow> int list \\<Rightarrow> int list\" where\n  \"add_coeffs [] rhs = rhs\" |\n  \"add_coeffs lhs [] = lhs\" |\n  \"add_coeffs (x # xs) (y # ys) = (x + y) # (add_coeffs xs ys)\"\n\nfun mul_coeffs :: \"int list \\<Rightarrow> int list \\<Rightarrow> int list\" where\n  \"mul_coeffs [] ys = []\" |\n  \"mul_coeffs (x # xs) ys = add_coeffs (map ((*) x) ys) (0 # (mul_coeffs xs ys))\"\n\nfun coeffs :: \"exp \\<Rightarrow> int list\" where\n  \"coeffs Var = [0, 1]\" |\n  \"coeffs (Const c) = [c]\" |\n  \"coeffs (Add lhs rhs) = add_coeffs (coeffs lhs) (coeffs rhs)\" |\n  \"coeffs (Mult lhs rhs) = mul_coeffs (coeffs lhs) (coeffs rhs)\"\n\nlemma addcl [simp] : \"evalp (add_coeffs A B) x = evalp A x + evalp B x\"\n  apply(induction A B rule: add_coeffs.induct)\n  by (auto simp add: algebra_simps)\n\nlemma mulcc [simp] : \"evalp (map ((*) a) ys) x = a * evalp ys x\"\n  apply(induction ys)\n  by (auto simp add: algebra_simps)\n\nlemma mulcl [simp] : \"evalp (mul_coeffs A B) x = evalp A x * evalp B x\"\n  apply(induction A arbitrary: B x)\n  by (auto simp add: algebra_simps)\n\nlemma \"evalp (coeffs e) x = eval e x\"\n  apply(induction e rule: coeffs.induct)\n  by (auto simp add: algebra_simps)\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_11.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505351008906, "lm_q2_score": 0.800692004473946, "lm_q1q2_score": 0.7243464502983599}}
{"text": "theory day1\n  imports Main\nbegin\n(*datatype bool = True | False*)\nfun nnot :: \"bool \\<Rightarrow> bool\" where\n  \"nnot True = False\" |\n  \"nnot False = True\"\nvalue \"nnot True\"\n\nfun conj :: \"bool \\<Rightarrow> bool \\<Rightarrow> bool\" where\n  \"conj True True = True\"|\n  \"conj _ _ = False\"\nvalue \"conj True False\"\n\n(*datatype nat = Zero | Suc nat*)\n(*self make is harm*)\nvalue \"Zero\"\nfun add :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\" where\n  \"add 0 n = n\"|\n  \"add (Suc m) n = Suc(add m n)\"\nvalue \"add (Suc (Suc 0))(Suc 0)\"\n\nlemma add_02[simp]: \"add m 0 = m\"\n  apply(induction m)\n  apply(auto)\n  done\n    \nthm add_02(*you can check theorem*)\n  \nlemma add_inc[simp]: \"add n (Suc m) = Suc (add n m)\"\n  apply(induction n)\n   apply(auto)\n  done\n    \n(*ex2.2*)\nlemma add_comm[simp]: \"add m n = add n m\"\n  apply(induction n)\n    apply(simp)\n  apply(auto)\n  done\n    \nlemma add_exch[simp]: \"add (add x y) z = add x (add y z)\"\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  value \"double (Suc (Suc 0))\"\n    \nlemma double_add: \"double m = add m m\"\n  apply(induction m)\n   apply(auto)\n  done\n    \n(*datatype 'a list = Nil | Cons 'a \"'a list\"*)\nvalue \"Cons (Suc Zero) (Cons Zero Nil)\"\nvalue \"Cons True (Cons False (Cons True Nil))\"\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  \nvalue \"app (Cons True (Cons True Nil))(Cons False Nil)\"\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 (Cons True (Cons False Nil))))\"\n  \nlemma revrev_rev[simp]: \"rev (app left right) = app (rev left)(rev right)\"\n  sorry\n  \nlemma rev_def[simp]: \"rev (rev m) = m\"\n  sorry\n  \n(*Exercise 2.3*)\nfun count::\"'a \\<Rightarrow> 'a list \\<Rightarrow> nat\" where\n  \"count v Nil = 0\"|\n  \"count v (Cons x xs) = (if (v = x) then (Suc (count v xs)) else (count v xs))\"\n  \nvalue \"count True (Cons True (Cons False (Cons True Nil)))\"\n  value \"length (Cons True (Cons True Nil))\"\n  \nlemma count_less[simp]: \"count x xs \\<le> length 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 x) = (Suc x) + (sum_upto x)\"\n  \nvalue \"sum_upto (Suc (Suc (Suc 0)))\"\n  value \"(Suc 0)*2\"\n  \nlemma summer: \"sum_upto n = n * (n + 1) div 2\"\n  apply(induction n)\n   apply(auto)\n  done\n    \nfun even::\"nat \\<Rightarrow> bool\" where\n  \"even 0 = True\"|\n  \"even (Suc x) = (if (even x) then False else True)\"\n \nfun match::\"bool \\<Rightarrow> bool \\<Rightarrow> bool\" where\n  \"match True True = True\"|\n  \"match False False = True\"|\n  \"match _ _ = False\"\n \nlemma mid[simp]: \"even (a + b) = match (even a)(even b)\"\n  apply(induction a)\n    apply(induction b)\n    apply(auto)\n  sorry\n    \n  \nlemma winter: \"even (Suc(Suc(Suc(Suc 0))) * n) = True\"\n  apply(induction n)\n   apply(auto)\n  done\n    \n(*2.8*)\nfun intersperse::\" 'a \\<Rightarrow> 'a list \\<Rightarrow> 'a list \" where\n  \"intersperse _ [] = []\"|\n  \"intersperse a [x] = [x]\"|\n  \"intersperse a (x # xs) = x # a # (intersperse a xs)\"\n    \n\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/day1.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.904650527388829, "lm_q2_score": 0.8006920092299292, "lm_q1q2_score": 0.7243464484258766}}
{"text": "theory E2_6\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 v r) = v # ((contents l) @ (contents r))\"\n\nfun sum_tree :: \"nat tree \\<Rightarrow> nat\" where\n  \"sum_tree Tip = 0\" |\n  \"sum_tree (Node l v r) = v + (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\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_6.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8962513786759491, "lm_q2_score": 0.8080672112416737, "lm_q1q2_score": 0.7242313521381795}}
{"text": "(*  Title:      RSAPSS/Cryptinverts.thy\n    Author:     Christina Lindenberg, Kai Wirt, Technische Universit\u00e4t Darmstadt\n    Copyright:  2005 - Technische Universit\u00e4t Darmstadt \n*)\n\nsection \"Correctness proof for RSA\"\n\ntheory Cryptinverts\nimports  Crypt Productdivides  \"HOL-Number_Theory.Residues\" \nbegin\n\ntext \\<open>\n  In this theory we show, that a RSA encrypted message can be decrypted\n\\<close>\n\nprimrec pred:: \"nat \\<Rightarrow> nat\"\nwhere\n  \"pred 0 = 0\"\n| \"pred (Suc a) = a\"\n\nlemma pred_unfold:\n  \"pred n = n - 1\"\n  by (induct n) simp_all\n  \nlemma fermat:\n  assumes \"prime p\" \"m mod p \\<noteq> 0\"\n  shows \"m^(p-(1::nat)) mod p = 1\"\nproof -\n  from assms have \"[m ^ (p - 1) = 1] (mod p)\"\n    using fermat_theorem [of p m] by (simp add: mod_eq_0_iff_dvd)\n  then show ?thesis\n    using \\<open>prime p\\<close> prime_gt_1_nat [of p] by (simp add: cong_def)\nqed\n\nlemma cryptinverts_hilf1: \"prime p \\<Longrightarrow> (m * m ^(k * pred p)) mod p = m mod p\"\n  apply (cases \"m mod p = 0\")\n  apply (simp add: mod_mult_left_eq)\n  apply (simp only: mult.commute [of k \"pred p\"]\n    power_mult mod_mult_right_eq [of \"m\" \"(m^pred p)^k\" \"p\"]\n    remainderexp [of \"m^pred p\" \"p\" \"k\", symmetric])\n   apply (insert fermat [of p m], auto)\n  apply (simp add: mult.commute [of k] power_mult pred_unfold)\n  by (metis One_nat_def mod_mult_right_eq mult.right_neutral power_Suc_0 power_mod)\n\nlemma cryptinverts_hilf2: \"prime p \\<Longrightarrow> m*(m^(k * (pred p) * (pred q))) mod p = m mod p\"\n  apply (simp add: mult.commute [of \"k * pred p\" \"pred q\"] mult.assoc [symmetric])\n  apply (rule cryptinverts_hilf1 [of \"p\" \"m\" \"(pred q) * k\"])\n  apply simp\n  done\n\nlemma cryptinverts_hilf3: \"prime q \\<Longrightarrow> m*(m^(k * (pred p) * (pred q))) mod q = m mod q\"\n  by (fact cryptinverts_hilf1)\n\nlemma cryptinverts_hilf4:\n  \"m ^ x mod (p * q) = m\" if \"prime p\" \"prime q\" \"p \\<noteq> q\"\n    \"m < p * q\" \"x mod (pred p * pred q) = 1\"\nproof (cases x)\n  case 0\n  with that show ?thesis\n    by simp\nnext\n  case (Suc x)\n  with that(5) have \"Suc x mod (pred p * pred q) = Suc 0\"\n    by simp\n  then have \"pred p * pred q dvd x\"\n    using dvd_minus_mod [of \"(pred p * pred q)\" \"Suc x\"]\n    by simp\n  then obtain y where \"x = pred p * pred q * y\" ..\n  then have \"m ^ Suc x mod p = m mod p\" and \"m ^ Suc x mod q = m mod q\"\n    using cryptinverts_hilf2 [of p m y q, OF \\<open>prime p\\<close>]\n      cryptinverts_hilf3 [of q m y p, OF \\<open>prime q\\<close>]\n    by (simp_all add: ac_simps)\n  with that Suc show ?thesis\n    by (auto intro: specializedtoprimes1a)\nqed\n\nlemma primmultgreater: fixes p::nat shows \"\\<lbrakk> prime p; prime q; p \\<noteq> 2; q \\<noteq> 2\\<rbrakk> \\<Longrightarrow> 2 < p*q\"\n  apply (simp add: prime_nat_iff)\n  apply (insert mult_le_mono [of 2 p 2 q])\n  apply auto\n  done\n\nlemma primmultgreater2: fixes p::nat shows \"\\<lbrakk>prime p; prime q; p \\<noteq> q\\<rbrakk> \\<Longrightarrow>  2 < p*q\"\n  apply (cases \"p = 2\")\n   apply simp+\n  apply (simp add: prime_nat_iff)\n  apply (cases \"q = 2\")\n   apply (simp add: prime_nat_iff)\n  apply (erule primmultgreater)\n  apply auto\n  done\n\nlemma cryptinverts: \"\\<lbrakk> prime p; prime q; p \\<noteq> q; n = p*q; m < n;\n    e*d mod ((pred p)*(pred q)) = 1\\<rbrakk> \\<Longrightarrow> rsa_crypt (rsa_crypt m e n) d n = m\"\n  apply (insert cryptinverts_hilf4 [of p q m \"e*d\"])\n  apply (insert cryptcorrect [of \"p*q\" \"rsa_crypt m e (p * q)\" d])\n  apply (insert cryptcorrect [of \"p*q\" m e])\n  apply (insert primmultgreater2 [of p q])\n  apply (simp add: prime_nat_iff)\n  apply (simp add: cryptcorrect remainderexp [of \"m^e\" \"p*q\" d] power_mult [symmetric])\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/SeLFiE/Example/afp-2020-05-16/thys/RSAPSS/Cryptinverts.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.925229959153748, "lm_q2_score": 0.7826624738835052, "lm_q1q2_score": 0.7241427687424068}}
{"text": "(*\n  File:    Misc.thy\n  Authors: Max W. Haslbeck, Manuel Eberl\n*)\nsection \\<open>Auxiliary material\\<close>\ntheory Misc\n  imports \"HOL-Analysis.Analysis\"\nbegin\n\ntext \\<open>Based on @{term sorted_list_of_set} and @{term the_inv_into} we construct a bijection between\n  a finite set A of type 'a::linorder and a set of natural numbers @{term \"{..< card A}\"}\\<close>\n\nlemma bij_betw_mono_on_the_inv_into:\n  fixes A::\"'a::linorder set\" and B::\"'b::linorder set\"\n  assumes b: \"bij_betw f A B\" and m: \"mono_on f A\"\n  shows \"mono_on (the_inv_into A f) B\"\nproof (rule ccontr)\n  assume \"\\<not> mono_on (the_inv_into A f) B\"\n  then have \"\\<exists>r s. r \\<in> B \\<and> s \\<in> B \\<and> r \\<le> s \\<and> \\<not> the_inv_into A f s \\<ge> the_inv_into A f r\"\n    unfolding mono_on_def by blast\n  then obtain r s where rs: \"r \\<in> B\" \"s \\<in> B\" \"r \\<le> s\" \"the_inv_into A f s < the_inv_into A f r\"\n    by fastforce\n  have f: \"f (the_inv_into A f b) = b\" if \"b \\<in> B\" for b\n    using that assms f_the_inv_into_f_bij_betw by metis\n  have \"the_inv_into A f s \\<in> A\" \"the_inv_into A f r \\<in> A\"\n    using rs assms by (auto simp add: bij_betw_def the_inv_into_into)\n  then have \"f (the_inv_into A f s) \\<le> f (the_inv_into A f r)\"\n   using rs by (intro mono_onD[OF m]) (auto)\n  then have \"r = s\"\n    using rs f by simp\n  then show False\n    using rs by auto\nqed\n\nlemma rev_removeAll_removeAll_rev: \"rev (removeAll x xs) = removeAll x (rev xs)\"\n  by (simp add: removeAll_filter_not_eq rev_filter)\n\nlemma sorted_list_of_set_Min_Cons:\n  assumes \"finite A\" \"A \\<noteq> {}\"\n  shows \"sorted_list_of_set A = Min A # sorted_list_of_set (A - {Min A})\"\nproof -\n  have *: \"A = insert (Min A) A\"\n    using assms Min_in by (auto)\n  then have \"sorted_list_of_set A = insort (Min A) (sorted_list_of_set (A - {Min A}))\"\n    using assms by (subst *, intro sorted_list_of_set_insert) auto\n  also have \"\\<dots> = Min A # sorted_list_of_set (A - {Min A})\"\n    using assms by (intro insort_is_Cons) (auto)\n  finally show ?thesis\n    by simp\nqed\n\nlemma sorted_list_of_set_filter:\n  assumes \"finite A\"\n  shows \"sorted_list_of_set ({x\\<in>A. P x}) = filter P (sorted_list_of_set A)\"\n  using assms proof (induction \"sorted_list_of_set A\" arbitrary: A)\n  case (Cons x xs)\n  have x: \"x \\<in> A\"\n    using Cons sorted_list_of_set list.set_intros(1) by metis\n  have \"sorted_list_of_set A = Min A # sorted_list_of_set (A - {Min A})\"\n    using Cons by (intro sorted_list_of_set_Min_Cons) auto\n  then have 1: \"x = Min A\" \"xs = sorted_list_of_set (A - {x})\"\n    using Cons by auto\n  { assume Px: \"P x\"\n    have 2: \"sorted_list_of_set {x \\<in> A. P x} = Min {x \\<in> A. P x} # sorted_list_of_set ({x \\<in> A. P x} - {Min {x \\<in> A. P x}})\"\n      using Px Cons 1 sorted_list_of_set_eq_Nil_iff\n      by (intro sorted_list_of_set_Min_Cons) fastforce+\n    also have 3: \"Min {x \\<in> A. P x} = x\"\n      using Cons 1 Px x by (auto intro!: Min_eqI)\n    also have 4: \"{x \\<in> A. P x} - {x} = {y \\<in> A - {x}. P y}\"\n      by blast\n    also have 5: \"sorted_list_of_set {y \\<in> A - {x}. P y} = filter P (sorted_list_of_set (A - {x}))\"\n      using 1 Cons by (intro Cons) (auto)\n    also have \"\\<dots> = filter P xs\"\n      using 1 by simp\n    also have \"filter P (sorted_list_of_set A) = x # filter P xs\"\n      using Px by (simp flip: \\<open>x # xs = sorted_list_of_set A\\<close>)\n    finally have ?case\n      by auto }\n  moreover\n  { assume Px: \"\\<not> P x\"\n    then have \"{x \\<in> A. P x} = {y \\<in> A - {x}. P y}\"\n      by blast\n    also have \"sorted_list_of_set \\<dots> = filter P (sorted_list_of_set (A - {x}))\"\n      using 1 Cons by (intro Cons) auto\n    also have  \"filter P (sorted_list_of_set (A - {x})) = filter P (sorted_list_of_set A)\"\n      using 1 Px by (simp flip: \\<open>x # xs = sorted_list_of_set A\\<close>)\n    finally have ?case\n      by simp }\n  ultimately show ?case\n    by blast\nqed (use sorted_list_of_set_eq_Nil_iff in fastforce)\n\nlemma sorted_list_of_set_Max_snoc:\n  assumes \"finite A\" \"A \\<noteq> {}\"\n  shows \"sorted_list_of_set A = sorted_list_of_set (A - {Max A}) @ [Max A]\"\nproof -\n  have *: \"A = insert (Max A) A\"\n    using assms Max_in by (auto)\n  then have \"sorted_list_of_set A = insort (Max A) (sorted_list_of_set (A - {Max A}))\"\n    using assms by (subst *, intro sorted_list_of_set_insert) auto\n  also have \"\\<dots> = sorted_list_of_set (A - {Max A}) @ [Max A]\"\n    using assms by (intro sorted_insort_is_snoc) (auto)\n  finally show ?thesis\n    by simp\nqed\n\nlemma sorted_list_of_set_image:\n  assumes \"mono_on g A\" \"inj_on g A\"\n  shows \"(sorted_list_of_set (g ` A)) = map g (sorted_list_of_set A)\"\nproof (cases \"finite A\")\n  case True\n  then show ?thesis\n    using assms proof (induction \"sorted_list_of_set A\" arbitrary: A)\n    case Nil\n    then show ?case\n      using sorted_list_of_set_eq_Nil_iff by fastforce\n  next\n    case (Cons x xs A)\n    have not_empty_A: \"A \\<noteq> {}\"\n      using Cons sorted_list_of_set_eq_Nil_iff by auto\n    have *: \"Min (g ` A) = g (Min A)\"\n    proof -\n      have \"g (Min A) \\<le> g a\" if \"a \\<in> A\" for a\n        using that Cons Min_in Min_le not_empty_A by (auto intro!: mono_onD[of g])\n      then show ?thesis\n        using Cons not_empty_A by (intro Min_eqI) auto\n    qed\n    have \"g ` A \\<noteq> {}\" \"finite (g ` A)\"\n      using Cons by auto\n    then have \"(sorted_list_of_set (g ` A)) =\n             Min (g ` A) # sorted_list_of_set ((g ` A) - {Min (g ` A)})\"\n      by (auto simp add: sorted_list_of_set_Min_Cons)\n    also have \"(g ` A) - {Min (g ` A)} = g ` (A - {Min A})\"\n      using Cons Min_in not_empty_A * by (subst inj_on_image_set_diff[of _ A]) auto\n    also have \"sorted_list_of_set (g ` (A - {Min A})) = map g (sorted_list_of_set (A - {Min A}))\"\n      using not_empty_A Cons mono_on_subset[of _ A \"A - {Min A}\"] inj_on_subset[of _ A \"A - {Min A}\"]\n      by (intro Cons) (auto simp add: sorted_list_of_set_Min_Cons)\n    finally show ?case\n      using Cons not_empty_A * by (auto simp add: sorted_list_of_set_Min_Cons)\n  qed\nnext\n  case False\n  then show ?thesis\n    using assms by (simp add: finite_image_iff)\nqed\n\nlemma sorted_list_of_set_length: \"length (sorted_list_of_set A) = card A\"\n  using distinct_card sorted_list_of_set[of A] by (cases \"finite A\") fastforce+\n\nlemma sorted_list_of_set_bij_betw:\n  assumes \"finite A\"\n  shows \"bij_betw (\\<lambda>n. sorted_list_of_set A ! n) {..<card A} A\"\n  by (rule bij_betw_nth) (fastforce simp add: assms sorted_list_of_set_length)+\n\nlemma nth_mono_on:\n  assumes \"sorted xs\" \"distinct xs\" \"set xs = A\"\n  shows \"mono_on (\\<lambda>n. xs ! n) {..<card A}\"\n  using assms by (intro mono_onI sorted_nth_mono) (auto simp add: distinct_card)\n\nlemma sorted_list_of_set_mono_on:\n  \"finite A \\<Longrightarrow> mono_on (\\<lambda>n. sorted_list_of_set A ! n) {..<card A}\"\n  by (rule nth_mono_on) (auto)\n\ndefinition bij_mono_map_set_to_nat :: \"'a::linorder set \\<Rightarrow> 'a \\<Rightarrow> nat\" where\n  \"bij_mono_map_set_to_nat A =\n    (\\<lambda>x. if x \\<in> A then the_inv_into {..<card A} ((!) (sorted_list_of_set A)) x\n                  else card A)\"\n\nlemma bij_mono_map_set_to_nat:\n  assumes \"finite A\"\n  shows \"bij_betw (bij_mono_map_set_to_nat A) A {..<card A}\"\n        \"mono_on (bij_mono_map_set_to_nat A) A\"\n        \"(bij_mono_map_set_to_nat A) ` A = {..<card A}\"\nproof -\n  let ?f = \"bij_mono_map_set_to_nat A\"\n  have \"bij_betw (the_inv_into {..<card A} ((!) (sorted_list_of_set A))) A {..<card A}\"\n    using assms sorted_list_of_set_bij_betw  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 bij_mono_map_set_to_nat_def by (rule bij_betw_cong) simp\n  ultimately show *: \"bij_betw (bij_mono_map_set_to_nat A) A {..<card A}\"\n    by blast\n  have \"mono_on (the_inv_into {..<card A} ((!) (sorted_list_of_set A))) A\"\n    using assms sorted_list_of_set_bij_betw\n      sorted_list_of_set_mono_on by (intro bij_betw_mono_on_the_inv_into) auto\n  then show \"mono_on (bij_mono_map_set_to_nat A) A\"\n    unfolding bij_mono_map_set_to_nat_def using mono_onD by (intro mono_onI) (auto)\n  show \"?f ` A = {..<card A}\"\n      using assms bij_betw_imp_surj_on * 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/Skip_Lists/Misc.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8519528094861981, "lm_q2_score": 0.8499711699569787, "lm_q1q2_score": 0.7241353262271188}}
{"text": "section \\<open>Residual Graph\\<close>\ntheory Residual_Graph\nimports Network\nbegin\ntext \\<open>\n  In this theory, we define the residual graph.\n  \\<close>\n\nsubsection \\<open>Definition\\<close>\ntext \\<open>The \\<^emph>\\<open>residual graph\\<close> of a network and a flow indicates how much \n  flow can be effectively pushed along or reverse to a network edge,\n  by increasing or decreasing the flow on that edge:\\<close>\ndefinition residualGraph :: \"_ graph \\<Rightarrow> _ flow \\<Rightarrow> _ graph\"\nwhere \"residualGraph c f \\<equiv> \\<lambda>(u, v).\n  if (u, v) \\<in> Graph.E c then\n    c (u, v) - f (u, v)\n  else if (v, u) \\<in> Graph.E c then\n    f (v, u)\n  else\n    0\"\n\ncontext Network begin\n  \nabbreviation \"cf_of \\<equiv> residualGraph c\"\nabbreviation \"cfE_of f \\<equiv> Graph.E (cf_of f)\"\n\ntext \\<open>The edges of the residual graph are either parallel or reverse \n  to the edges of the network.\\<close>\nlemma cfE_of_ss_invE: \"cfE_of cf \\<subseteq> E \\<union> E\\<inverse>\"\n  unfolding residualGraph_def Graph.E_def\n  by auto\n  \nlemma cfE_of_ss_VxV: \"cfE_of f \\<subseteq> V\\<times>V\"\n  unfolding V_def\n  unfolding residualGraph_def Graph.E_def\n  by auto  \n\nlemma cfE_of_finite[simp, intro!]: \"finite (cfE_of f)\"\n  using finite_subset[OF cfE_of_ss_VxV] by auto\n\nlemma cf_no_self_loop: \"(u,u)\\<notin>cfE_of f\"\nproof\n  assume a1: \"(u, u) \\<in> cfE_of f\"\n  have \"(u, u) \\<notin> E\"\n    using no_parallel_edge by blast\n  then show False\n    using a1 unfolding Graph.E_def residualGraph_def by fastforce\nqed \n  \nend\n  \n  \n  \ntext \\<open>Let's fix a network with a preflow @{term f} on it\\<close>\ncontext NPreflow\nbegin\n  text \\<open>We abbreviate the residual graph by @{term cf}.\\<close>\n  abbreviation \"cf \\<equiv> residualGraph c f\"\n  sublocale cf: Graph cf .\n  lemmas cf_def = residualGraph_def[of c f]\n\nsubsection \\<open>Properties\\<close>\n\nlemmas cfE_ss_invE = cfE_of_ss_invE[of f]  \n(*lemma cfE_ss_invE: \"Graph.E cf \\<subseteq> E \\<union> E\\<inverse>\"\n  unfolding residualGraph_def Graph.E_def\n  by auto*)\n\ntext \\<open>The nodes of the residual graph are exactly the nodes of the network.\\<close>\nlemma resV_netV[simp]: \"cf.V = V\"\nproof\n  show \"V \\<subseteq> Graph.V cf\"\n  proof \n    fix u\n    assume \"u \\<in> V\"\n    then obtain v where \"(u, v) \\<in> E \\<or> (v, u) \\<in> E\" unfolding V_def by auto\n    (* TODO: Use nifty new Isabelle2016 case-distinction features here! *)\n    moreover {\n      assume \"(u, v) \\<in> E\"\n      then have \"(u, v) \\<in> Graph.E cf \\<or> (v, u) \\<in> Graph.E cf\"\n      proof (cases)\n        assume \"f (u, v) = 0\"\n        then have \"cf (u, v) = c (u, v)\"\n          unfolding residualGraph_def using \\<open>(u, v) \\<in> E\\<close> by (auto simp:)\n        then have \"cf (u, v) \\<noteq> 0\" using \\<open>(u, v) \\<in> E\\<close> unfolding E_def by auto\n        thus ?thesis unfolding Graph.E_def by auto\n      next\n        assume \"f (u, v) \\<noteq> 0\"\n        then have \"cf (v, u) = f (u, v)\" unfolding residualGraph_def\n          using \\<open>(u, v) \\<in> E\\<close> no_parallel_edge by auto\n        then have \"cf (v, u) \\<noteq> 0\" using \\<open>f (u, v) \\<noteq> 0\\<close> by auto\n        thus ?thesis unfolding Graph.E_def by auto\n      qed\n    } moreover {\n      assume \"(v, u) \\<in> E\"\n      then have \"(v, u) \\<in> Graph.E cf \\<or> (u, v) \\<in> Graph.E cf\"\n      proof (cases)\n        assume \"f (v, u) = 0\"\n        then have \"cf (v, u) = c (v, u)\"\n          unfolding residualGraph_def using \\<open>(v, u) \\<in> E\\<close> by (auto)\n        then have \"cf (v, u) \\<noteq> 0\" using \\<open>(v, u) \\<in> E\\<close> unfolding E_def by auto\n        thus ?thesis unfolding Graph.E_def by auto\n      next\n        assume \"f (v, u) \\<noteq> 0\"\n        then have \"cf (u, v) = f (v, u)\" unfolding residualGraph_def\n          using \\<open>(v, u) \\<in> E\\<close> no_parallel_edge by auto\n        then have \"cf (u, v) \\<noteq> 0\" using \\<open>f (v, u) \\<noteq> 0\\<close> by auto\n        thus ?thesis unfolding Graph.E_def by auto\n      qed\n    } ultimately show \"u\\<in>cf.V\" unfolding cf.V_def by auto\n  qed  \nnext\n  show \"Graph.V cf \\<subseteq> V\" using cfE_ss_invE unfolding Graph.V_def by auto\nqed\n\ntext \\<open>Note, that Isabelle is powerful enough to prove the above case \n  distinctions completely automatically, although it takes some time:\\<close>\nlemma \"cf.V = V\"\n  unfolding residualGraph_def Graph.E_def Graph.V_def\n  using no_parallel_edge[unfolded E_def]\n  by auto\n  \ntext \\<open>As the residual graph has the same nodes as the network, it is also finite:\\<close>\nsublocale cf: Finite_Graph cf\n  by unfold_locales auto\n\ntext \\<open>The capacities on the edges of the residual graph are non-negative\\<close>\nlemma resE_nonNegative: \"cf e \\<ge> 0\"\nproof (cases e; simp)\n  fix u v\n  {\n    assume \"(u, v) \\<in> E\"\n    then have \"cf (u, v) = c (u, v) - f (u, v)\" unfolding cf_def by auto\n    hence \"cf (u,v) \\<ge> 0\" \n      using capacity_const cap_non_negative by auto\n  } moreover {\n    assume \"(v, u) \\<in> E\"\n    then have \"cf (u,v) = f (v, u)\" \n      using no_parallel_edge unfolding cf_def by auto\n    hence \"cf (u,v) \\<ge> 0\" \n      using capacity_const by auto\n  } moreover {\n    assume \"(u, v) \\<notin> E\" \"(v, u) \\<notin> E\"\n    hence \"cf (u,v) \\<ge> 0\" unfolding residualGraph_def by simp\n  } ultimately show \"cf (u,v) \\<ge> 0\" by blast\nqed\n\ntext \\<open>Again, there is an automatic proof\\<close>\nlemma \"cf e \\<ge> 0\"\n  apply (cases e)\n  unfolding residualGraph_def\n  using no_parallel_edge capacity_const cap_positive\n  by auto\n\ntext \\<open>All edges of the residual graph are labeled with positive capacities:\\<close>\ncorollary resE_positive: \"e \\<in> cf.E \\<Longrightarrow> cf e > 0\"\nproof -\n  assume \"e \\<in> cf.E\"\n  hence \"cf e \\<noteq> 0\" unfolding cf.E_def by auto\n  thus ?thesis using resE_nonNegative by (meson eq_iff not_le)\nqed \n      \n(* TODO: Only one usage: Move or remove! *)  \nlemma reverse_flow: \"Preflow cf s t f' \\<Longrightarrow> \\<forall>(u, v) \\<in> E. f' (v, u) \\<le> f (u, v)\"\nproof -\n  assume asm: \"Preflow cf s t f'\"\n  then interpret f': Preflow cf s t f' .\n      \n  {\n    fix u v\n    assume \"(u, v) \\<in> E\"\n    \n    then have \"cf (v, u) = f (u, v)\"\n      unfolding residualGraph_def using no_parallel_edge by auto\n    moreover have \"f' (v, u) \\<le> cf (v, u)\" using f'.capacity_const by auto\n    ultimately have \"f' (v, u) \\<le> f (u, v)\" by metis\n  }\n  thus ?thesis by auto\nqed  \n\n  \ndefinition (in Network) \"flow_of_cf cf e \\<equiv> (if (e\\<in>E) then c e - cf e else 0)\"\n\n(* TODO: We have proved/used this fact already for Edka-Analysis! (uE) *)  \nlemma (in NPreflow) E_ss_cfinvE: \"E \\<subseteq> Graph.E cf \\<union> (Graph.E cf)\\<inverse>\"\n  unfolding residualGraph_def Graph.E_def\n  apply (clarsimp)\n  using no_parallel_edge (* Speed optimization: Adding this directly takes very long *)\n  unfolding E_def\n  apply (simp add: )\n  done\n  \n  \ntext \\<open>Nodes with positive excess must have an outgoing edge in the \n  residual graph. \n\n  Intuitively: The excess flow must come from somewhere.\\<close>\nlemma active_has_cf_outgoing: \"excess f u > 0 \\<Longrightarrow> cf.outgoing u \\<noteq> {}\"  \n  unfolding excess_def\nproof -\n  assume \"0 < sum f (incoming u) - sum f (outgoing u)\"\n  hence \"0 < sum f (incoming u)\"\n    by (metis diff_gt_0_iff_gt linorder_neqE_linordered_idom linorder_not_le \n        sum_f_non_negative)\n  with f_non_negative obtain e where \"e\\<in>incoming u\" \"f e > 0\"\n    by (meson not_le sum_nonpos)\n  then obtain v where \"(v,u)\\<in>E\" \"f (v,u) > 0\" unfolding incoming_def by auto\n  hence \"cf (u,v) > 0\" unfolding residualGraph_def by auto\n  thus ?thesis unfolding cf.outgoing_def cf.E_def by fastforce   \nqed      \n    \n    \n    \nend \\<comment> \\<open>Network with preflow\\<close>\n  \n  \nlocale RPreGraph \\<comment> \\<open>Locale that characterizes a residual graph of a network\\<close>\n= Network +\n  fixes cf\n  assumes EX_RPG: \"\\<exists>f. NPreflow c s t f \\<and> cf = residualGraph c f\"\nbegin  \n\n  lemma this_loc_rpg: \"RPreGraph c s t cf\"\n    by unfold_locales\n\n  definition \"f \\<equiv> flow_of_cf cf\"\n\n  lemma f_unique:\n    assumes \"NPreflow c s t f'\"\n    assumes A: \"cf = residualGraph c f'\"\n    shows \"f' = f\"\n  proof -\n    interpret f': NPreflow c s t f' by fact\n    \n    show ?thesis\n      unfolding f_def[abs_def] flow_of_cf_def[abs_def]\n      unfolding A residualGraph_def\n      apply (rule ext)\n      using f'.capacity_const unfolding E_def\n      apply (auto split: prod.split)\n      by (metis antisym)\n  qed\n\n  lemma is_NPreflow: \"NPreflow c s t (flow_of_cf cf)\"\n    apply (fold f_def)\n    using EX_RPG f_unique by metis\n    \n  sublocale f: NPreflow c s t f unfolding f_def by (rule is_NPreflow)\n\n  lemma rg_is_cf[simp]: \"residualGraph c f = cf\"\n    using EX_RPG f_unique by auto\n\n  lemma rg_fo_inv[simp]: \"residualGraph c (flow_of_cf cf) = cf\"  \n    using rg_is_cf\n    unfolding f_def\n    .\n    \n\n  sublocale cf: Graph cf .\n\n  lemma resV_netV[simp]: \"cf.V = V\"\n    using f.resV_netV by simp\n\n  sublocale cf: Finite_Graph cf \n    apply unfold_locales\n    apply simp\n    done\n\n  lemma E_ss_cfinvE: \"E \\<subseteq> cf.E \\<union> cf.E\\<inverse>\"  \n    using f.E_ss_cfinvE by simp\n\n  lemma cfE_ss_invE: \"cf.E \\<subseteq> E \\<union> E\\<inverse>\"\n    using f.cfE_ss_invE by simp\n    \n  lemma resE_nonNegative: \"cf e \\<ge> 0\"  \n    using f.resE_nonNegative by auto\n      \nend\n\ncontext NPreflow begin\n  lemma is_RPreGraph: \"RPreGraph c s t cf\"\n    apply unfold_locales\n    apply (rule exI[where x=f])\n    apply (safe; unfold_locales)\n    done\n\n  lemma fo_rg_inv: \"flow_of_cf cf = f\"  \n    unfolding flow_of_cf_def[abs_def]\n    unfolding residualGraph_def\n    apply (rule ext)\n    using capacity_const unfolding E_def\n    apply (clarsimp split: prod.split)\n    by (metis antisym)\n\nend    \n\n(* For snippet*)\nlemma (in NPreflow)\n  \"flow_of_cf (residualGraph c f) = f\"\n  by (rule fo_rg_inv)\n\n\nlocale RGraph \\<comment> \\<open>Locale that characterizes a residual graph of a network\\<close>\n= Network +\n  fixes cf\n  assumes EX_RG: \"\\<exists>f. NFlow c s t f \\<and> cf = residualGraph c f\"\nbegin  \n  sublocale RPreGraph \n  proof    \n    from EX_RG obtain f where \n      \"NFlow c s t f\" and [simp]: \"cf = residualGraph c f\" by auto\n    then interpret NFlow c s t f by simp    \n\n    show \"\\<exists>f. NPreflow c s t f \\<and> cf = residualGraph c f\"\n      apply (rule exI[where x=\"f\"])\n      apply simp\n      by unfold_locales  \n  qed  \n\n  lemma this_loc: \"RGraph c s t cf\"\n    by unfold_locales\n  lemma this_loc_rpg: \"RPreGraph c s t cf\"\n    by unfold_locales\n    \n  lemma is_NFlow: \"NFlow c s t (flow_of_cf cf)\"\n    using EX_RG f_unique is_NPreflow NFlow.axioms(1)\n    apply (fold f_def) by force  \n    \n  sublocale f: NFlow c s t f unfolding f_def by (rule is_NFlow)\nend        \n      \ncontext NFlow begin\n\nlemma is_RGraph: \"RGraph c s t cf\"\n  apply unfold_locales\n  apply (rule exI[where x=f])\n  apply (safe; unfold_locales)\n  done\n      \ntext \\<open>The value of the flow can be computed from the residual graph.\\<close>\nlemma val_by_cf: \"val = (\\<Sum>(u,v)\\<in>outgoing s. cf (v,u))\"\nproof -\n  have \"f (s,v) = cf (v,s)\" for v\n    unfolding cf_def by auto\n  thus ?thesis \n    unfolding val_alt outgoing_def \n    by (auto intro!: sum.cong) \nqed  \n      \nend \\<comment> \\<open>Network with Flow\\<close>\n\nlemma (in RPreGraph) maxflow_imp_rgraph:\n  assumes \"isMaxFlow (flow_of_cf cf)\"\n  shows \"RGraph c s t cf\"\nproof -  \n  from assms interpret Flow c s t f \n    unfolding isMaxFlow_def by (simp add: f_def)\n \n  interpret NFlow c s t f by unfold_locales     \n  \n  show ?thesis    \n    apply unfold_locales\n    apply (rule exI[of _ f])\n    apply (simp add: NFlow_axioms)  \n    done  \nqed      \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/Residual_Graph.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8499711756575749, "lm_q2_score": 0.8519527963298947, "lm_q1q2_score": 0.724135319901279}}
{"text": "(*  Title:      HOL/Real_Vector_Spaces.thy\n    Author:     Brian Huffman\n    Author:     Johannes H\u00f6lzl\n*)\n\nsection \\<open>Vector Spaces and Algebras over the Reals\\<close>\n\ntheory Real_Vector_Spaces\nimports Real Topological_Spaces\nbegin\n\nsubsection \\<open>Locale for additive functions\\<close>\n\nlocale additive =\n  fixes f :: \"'a::ab_group_add \\<Rightarrow> 'b::ab_group_add\"\n  assumes add: \"f (x + y) = f x + f y\"\nbegin\n\nlemma zero: \"f 0 = 0\"\nproof -\n  have \"f 0 = f (0 + 0)\" by simp\n  also have \"\\<dots> = f 0 + f 0\" by (rule add)\n  finally show \"f 0 = 0\" by simp\nqed\n\nlemma minus: \"f (- x) = - f x\"\nproof -\n  have \"f (- x) + f x = f (- x + x)\" by (rule add [symmetric])\n  also have \"\\<dots> = - f x + f x\" by (simp add: zero)\n  finally show \"f (- x) = - f x\" by (rule add_right_imp_eq)\nqed\n\nlemma diff: \"f (x - y) = f x - f y\"\n  using add [of x \"- y\"] by (simp add: minus)\n\nlemma sum: \"f (sum g A) = (\\<Sum>x\\<in>A. f (g x))\"\n  by (induct A rule: infinite_finite_induct) (simp_all add: zero add)\n\nend\n\n\nsubsection \\<open>Vector spaces\\<close>\n\nlocale vector_space =\n  fixes scale :: \"'a::field \\<Rightarrow> 'b::ab_group_add \\<Rightarrow> 'b\"\n  assumes scale_right_distrib [algebra_simps]: \"scale a (x + y) = scale a x + scale a y\"\n    and scale_left_distrib [algebra_simps]: \"scale (a + b) x = scale a x + scale b x\"\n    and scale_scale [simp]: \"scale a (scale b x) = scale (a * b) x\"\n    and scale_one [simp]: \"scale 1 x = x\"\nbegin\n\nlemma scale_left_commute: \"scale a (scale b x) = scale b (scale a x)\"\n  by (simp add: mult.commute)\n\nlemma scale_zero_left [simp]: \"scale 0 x = 0\"\n  and scale_minus_left [simp]: \"scale (- a) x = - (scale a x)\"\n  and scale_left_diff_distrib [algebra_simps]: \"scale (a - b) x = scale a x - scale b x\"\n  and scale_sum_left: \"scale (sum f A) x = (\\<Sum>a\\<in>A. scale (f a) x)\"\nproof -\n  interpret s: additive \"\\<lambda>a. scale a x\"\n    by standard (rule scale_left_distrib)\n  show \"scale 0 x = 0\" by (rule s.zero)\n  show \"scale (- a) x = - (scale a x)\" by (rule s.minus)\n  show \"scale (a - b) x = scale a x - scale b x\" by (rule s.diff)\n  show \"scale (sum f A) x = (\\<Sum>a\\<in>A. scale (f a) x)\" by (rule s.sum)\nqed\n\nlemma scale_zero_right [simp]: \"scale a 0 = 0\"\n  and scale_minus_right [simp]: \"scale a (- x) = - (scale a x)\"\n  and scale_right_diff_distrib [algebra_simps]: \"scale a (x - y) = scale a x - scale a y\"\n  and scale_sum_right: \"scale a (sum f A) = (\\<Sum>x\\<in>A. scale a (f x))\"\nproof -\n  interpret s: additive \"\\<lambda>x. scale a x\"\n    by standard (rule scale_right_distrib)\n  show \"scale a 0 = 0\" by (rule s.zero)\n  show \"scale a (- x) = - (scale a x)\" by (rule s.minus)\n  show \"scale a (x - y) = scale a x - scale a y\" by (rule s.diff)\n  show \"scale a (sum f A) = (\\<Sum>x\\<in>A. scale a (f x))\" by (rule s.sum)\nqed\n\nlemma scale_eq_0_iff [simp]: \"scale a x = 0 \\<longleftrightarrow> a = 0 \\<or> x = 0\"\nproof (cases \"a = 0\")\n  case True\n  then show ?thesis by simp\nnext\n  case False\n  have \"x = 0\" if \"scale a x = 0\"\n  proof -\n    from False that have \"scale (inverse a) (scale a x) = 0\" by simp\n    with False show ?thesis by simp\n  qed\n  then show ?thesis by force\nqed\n\nlemma scale_left_imp_eq:\n  assumes nonzero: \"a \\<noteq> 0\"\n    and scale: \"scale a x = scale a y\"\n  shows \"x = y\"\nproof -\n  from scale have \"scale a (x - y) = 0\"\n     by (simp add: scale_right_diff_distrib)\n  with nonzero have \"x - y = 0\" by simp\n  then show \"x = y\" by (simp only: right_minus_eq)\nqed\n\nlemma scale_right_imp_eq:\n  assumes nonzero: \"x \\<noteq> 0\"\n    and scale: \"scale a x = scale b x\"\n  shows \"a = b\"\nproof -\n  from scale have \"scale (a - b) x = 0\"\n     by (simp add: scale_left_diff_distrib)\n  with nonzero have \"a - b = 0\" by simp\n  then show \"a = b\" by (simp only: right_minus_eq)\nqed\n\nlemma scale_cancel_left [simp]: \"scale a x = scale a y \\<longleftrightarrow> x = y \\<or> a = 0\"\n  by (auto intro: scale_left_imp_eq)\n\nlemma scale_cancel_right [simp]: \"scale a x = scale b x \\<longleftrightarrow> a = b \\<or> x = 0\"\n  by (auto intro: scale_right_imp_eq)\n\nend\n\n\nsubsection \\<open>Real vector spaces\\<close>\n\nclass scaleR =\n  fixes scaleR :: \"real \\<Rightarrow> 'a \\<Rightarrow> 'a\" (infixr \"*\\<^sub>R\" 75)\nbegin\n\nabbreviation divideR :: \"'a \\<Rightarrow> real \\<Rightarrow> 'a\"  (infixl \"'/\\<^sub>R\" 70)\n  where \"x /\\<^sub>R r \\<equiv> scaleR (inverse r) x\"\n\nend\n\nclass real_vector = scaleR + ab_group_add +\n  assumes scaleR_add_right: \"scaleR a (x + y) = scaleR a x + scaleR a y\"\n  and scaleR_add_left: \"scaleR (a + b) x = scaleR a x + scaleR b x\"\n  and scaleR_scaleR: \"scaleR a (scaleR b x) = scaleR (a * b) x\"\n  and scaleR_one: \"scaleR 1 x = x\"\n\ninterpretation real_vector: vector_space \"scaleR :: real \\<Rightarrow> 'a \\<Rightarrow> 'a::real_vector\"\n  apply unfold_locales\n     apply (rule scaleR_add_right)\n    apply (rule scaleR_add_left)\n   apply (rule scaleR_scaleR)\n  apply (rule scaleR_one)\n  done\n\ntext \\<open>Recover original theorem names\\<close>\n\nlemmas scaleR_left_commute = real_vector.scale_left_commute\nlemmas scaleR_zero_left = real_vector.scale_zero_left\nlemmas scaleR_minus_left = real_vector.scale_minus_left\nlemmas scaleR_diff_left = real_vector.scale_left_diff_distrib\nlemmas scaleR_sum_left = real_vector.scale_sum_left\nlemmas scaleR_zero_right = real_vector.scale_zero_right\nlemmas scaleR_minus_right = real_vector.scale_minus_right\nlemmas scaleR_diff_right = real_vector.scale_right_diff_distrib\nlemmas scaleR_sum_right = real_vector.scale_sum_right\nlemmas scaleR_eq_0_iff = real_vector.scale_eq_0_iff\nlemmas scaleR_left_imp_eq = real_vector.scale_left_imp_eq\nlemmas scaleR_right_imp_eq = real_vector.scale_right_imp_eq\nlemmas scaleR_cancel_left = real_vector.scale_cancel_left\nlemmas scaleR_cancel_right = real_vector.scale_cancel_right\n\ntext \\<open>Legacy names\\<close>\n\nlemmas scaleR_left_distrib = scaleR_add_left\nlemmas scaleR_right_distrib = scaleR_add_right\nlemmas scaleR_left_diff_distrib = scaleR_diff_left\nlemmas scaleR_right_diff_distrib = scaleR_diff_right\n\nlemma scaleR_minus1_left [simp]: \"scaleR (-1) x = - x\"\n  for x :: \"'a::real_vector\"\n  using scaleR_minus_left [of 1 x] by simp\n\nclass real_algebra = real_vector + ring +\n  assumes mult_scaleR_left [simp]: \"scaleR a x * y = scaleR a (x * y)\"\n    and mult_scaleR_right [simp]: \"x * scaleR a y = scaleR a (x * y)\"\n\nclass real_algebra_1 = real_algebra + ring_1\n\nclass real_div_algebra = real_algebra_1 + division_ring\n\nclass real_field = real_div_algebra + field\n\ninstantiation real :: real_field\nbegin\n\ndefinition real_scaleR_def [simp]: \"scaleR a x = a * x\"\n\ninstance\n  by standard (simp_all add: algebra_simps)\n\nend\n\ninterpretation scaleR_left: additive \"(\\<lambda>a. scaleR a x :: 'a::real_vector)\"\n  by standard (rule scaleR_left_distrib)\n\ninterpretation scaleR_right: additive \"(\\<lambda>x. scaleR a x :: 'a::real_vector)\"\n  by standard (rule scaleR_right_distrib)\n\nlemma nonzero_inverse_scaleR_distrib:\n  \"a \\<noteq> 0 \\<Longrightarrow> x \\<noteq> 0 \\<Longrightarrow> inverse (scaleR a x) = scaleR (inverse a) (inverse x)\"\n  for x :: \"'a::real_div_algebra\"\n  by (rule inverse_unique) simp\n\nlemma inverse_scaleR_distrib: \"inverse (scaleR a x) = scaleR (inverse a) (inverse x)\"\n  for x :: \"'a::{real_div_algebra,division_ring}\"\n  apply (cases \"a = 0\")\n   apply simp\n  apply (cases \"x = 0\")\n   apply simp\n  apply (erule (1) nonzero_inverse_scaleR_distrib)\n  done\n\nlemma sum_constant_scaleR: \"(\\<Sum>x\\<in>A. y) = of_nat (card A) *\\<^sub>R y\"\n  for y :: \"'a::real_vector\"\n  by (induct A rule: infinite_finite_induct) (simp_all add: algebra_simps)\n\nnamed_theorems vector_add_divide_simps \"to simplify sums of scaled vectors\"\n\nlemma [vector_add_divide_simps]:\n  \"v + (b / z) *\\<^sub>R w = (if z = 0 then v else (z *\\<^sub>R v + b *\\<^sub>R w) /\\<^sub>R z)\"\n  \"a *\\<^sub>R v + (b / z) *\\<^sub>R w = (if z = 0 then a *\\<^sub>R v else ((a * z) *\\<^sub>R v + b *\\<^sub>R w) /\\<^sub>R z)\"\n  \"(a / z) *\\<^sub>R v + w = (if z = 0 then w else (a *\\<^sub>R v + z *\\<^sub>R w) /\\<^sub>R z)\"\n  \"(a / z) *\\<^sub>R v + b *\\<^sub>R w = (if z = 0 then b *\\<^sub>R w else (a *\\<^sub>R v + (b * z) *\\<^sub>R w) /\\<^sub>R z)\"\n  \"v - (b / z) *\\<^sub>R w = (if z = 0 then v else (z *\\<^sub>R v - b *\\<^sub>R w) /\\<^sub>R z)\"\n  \"a *\\<^sub>R v - (b / z) *\\<^sub>R w = (if z = 0 then a *\\<^sub>R v else ((a * z) *\\<^sub>R v - b *\\<^sub>R w) /\\<^sub>R z)\"\n  \"(a / z) *\\<^sub>R v - w = (if z = 0 then -w else (a *\\<^sub>R v - z *\\<^sub>R w) /\\<^sub>R z)\"\n  \"(a / z) *\\<^sub>R v - b *\\<^sub>R w = (if z = 0 then -b *\\<^sub>R w else (a *\\<^sub>R v - (b * z) *\\<^sub>R w) /\\<^sub>R z)\"\n  for v :: \"'a :: real_vector\"\n  by (simp_all add: divide_inverse_commute scaleR_add_right real_vector.scale_right_diff_distrib)\n\n\nlemma eq_vector_fraction_iff [vector_add_divide_simps]:\n  fixes x :: \"'a :: real_vector\"\n  shows \"(x = (u / v) *\\<^sub>R a) \\<longleftrightarrow> (if v=0 then x = 0 else v *\\<^sub>R x = u *\\<^sub>R a)\"\nby auto (metis (no_types) divide_eq_1_iff divide_inverse_commute scaleR_one scaleR_scaleR)\n\nlemma vector_fraction_eq_iff [vector_add_divide_simps]:\n  fixes x :: \"'a :: real_vector\"\n  shows \"((u / v) *\\<^sub>R a = x) \\<longleftrightarrow> (if v=0 then x = 0 else u *\\<^sub>R a = v *\\<^sub>R x)\"\nby (metis eq_vector_fraction_iff)\n\nlemma real_vector_affinity_eq:\n  fixes x :: \"'a :: real_vector\"\n  assumes m0: \"m \\<noteq> 0\"\n  shows \"m *\\<^sub>R x + c = y \\<longleftrightarrow> x = inverse m *\\<^sub>R y - (inverse m *\\<^sub>R c)\"\n    (is \"?lhs \\<longleftrightarrow> ?rhs\")\nproof\n  assume ?lhs\n  then have \"m *\\<^sub>R x = y - c\" by (simp add: field_simps)\n  then have \"inverse m *\\<^sub>R (m *\\<^sub>R x) = inverse m *\\<^sub>R (y - c)\" by simp\n  then show \"x = inverse m *\\<^sub>R y - (inverse m *\\<^sub>R c)\"\n    using m0\n  by (simp add: real_vector.scale_right_diff_distrib)\nnext\n  assume ?rhs\n  with m0 show \"m *\\<^sub>R x + c = y\"\n    by (simp add: real_vector.scale_right_diff_distrib)\nqed\n\nlemma real_vector_eq_affinity: \"m \\<noteq> 0 \\<Longrightarrow> y = m *\\<^sub>R x + c \\<longleftrightarrow> inverse m *\\<^sub>R y - (inverse m *\\<^sub>R c) = x\"\n  for x :: \"'a::real_vector\"\n  using real_vector_affinity_eq[where m=m and x=x and y=y and c=c]\n  by metis\n\nlemma scaleR_eq_iff [simp]: \"b + u *\\<^sub>R a = a + u *\\<^sub>R b \\<longleftrightarrow> a = b \\<or> u = 1\"\n  for a :: \"'a::real_vector\"\nproof (cases \"u = 1\")\n  case True\n  then show ?thesis by auto\nnext\n  case False\n  have \"a = b\" if \"b + u *\\<^sub>R a = a + u *\\<^sub>R b\"\n  proof -\n    from that have \"(u - 1) *\\<^sub>R a = (u - 1) *\\<^sub>R b\"\n      by (simp add: algebra_simps)\n    with False show ?thesis\n      by auto\n  qed\n  then show ?thesis by auto\nqed\n\nlemma scaleR_collapse [simp]: \"(1 - u) *\\<^sub>R a + u *\\<^sub>R a = a\"\n  for a :: \"'a::real_vector\"\n  by (simp add: algebra_simps)\n\n\nsubsection \\<open>Embedding of the Reals into any \\<open>real_algebra_1\\<close>: \\<open>of_real\\<close>\\<close>\n\ndefinition of_real :: \"real \\<Rightarrow> 'a::real_algebra_1\"\n  where \"of_real r = scaleR r 1\"\n\nlemma scaleR_conv_of_real: \"scaleR r x = of_real r * x\"\n  by (simp add: of_real_def)\n\nlemma of_real_0 [simp]: \"of_real 0 = 0\"\n  by (simp add: of_real_def)\n\nlemma of_real_1 [simp]: \"of_real 1 = 1\"\n  by (simp add: of_real_def)\n\nlemma of_real_add [simp]: \"of_real (x + y) = of_real x + of_real y\"\n  by (simp add: of_real_def scaleR_left_distrib)\n\nlemma of_real_minus [simp]: \"of_real (- x) = - of_real x\"\n  by (simp add: of_real_def)\n\nlemma of_real_diff [simp]: \"of_real (x - y) = of_real x - of_real y\"\n  by (simp add: of_real_def scaleR_left_diff_distrib)\n\nlemma of_real_mult [simp]: \"of_real (x * y) = of_real x * of_real y\"\n  by (simp add: of_real_def mult.commute)\n\nlemma of_real_sum[simp]: \"of_real (sum f s) = (\\<Sum>x\\<in>s. of_real (f x))\"\n  by (induct s rule: infinite_finite_induct) auto\n\nlemma of_real_prod[simp]: \"of_real (prod f s) = (\\<Prod>x\\<in>s. of_real (f x))\"\n  by (induct s rule: infinite_finite_induct) auto\n\nlemma nonzero_of_real_inverse:\n  \"x \\<noteq> 0 \\<Longrightarrow> of_real (inverse x) = inverse (of_real x :: 'a::real_div_algebra)\"\n  by (simp add: of_real_def nonzero_inverse_scaleR_distrib)\n\nlemma of_real_inverse [simp]:\n  \"of_real (inverse x) = inverse (of_real x :: 'a::{real_div_algebra,division_ring})\"\n  by (simp add: of_real_def inverse_scaleR_distrib)\n\nlemma nonzero_of_real_divide:\n  \"y \\<noteq> 0 \\<Longrightarrow> of_real (x / y) = (of_real x / of_real y :: 'a::real_field)\"\n  by (simp add: divide_inverse nonzero_of_real_inverse)\n\nlemma of_real_divide [simp]:\n  \"of_real (x / y) = (of_real x / of_real y :: 'a::real_div_algebra)\"\n  by (simp add: divide_inverse)\n\nlemma of_real_power [simp]:\n  \"of_real (x ^ n) = (of_real x :: 'a::{real_algebra_1}) ^ n\"\n  by (induct n) simp_all\n\nlemma of_real_eq_iff [simp]: \"of_real x = of_real y \\<longleftrightarrow> x = y\"\n  by (simp add: of_real_def)\n\nlemma inj_of_real: \"inj of_real\"\n  by (auto intro: injI)\n\nlemmas of_real_eq_0_iff [simp] = of_real_eq_iff [of _ 0, simplified]\n\nlemma of_real_eq_id [simp]: \"of_real = (id :: real \\<Rightarrow> real)\"\n  by (rule ext) (simp add: of_real_def)\n\ntext \\<open>Collapse nested embeddings.\\<close>\nlemma of_real_of_nat_eq [simp]: \"of_real (of_nat n) = of_nat n\"\n  by (induct n) auto\n\nlemma of_real_of_int_eq [simp]: \"of_real (of_int z) = of_int z\"\n  by (cases z rule: int_diff_cases) simp\n\nlemma of_real_numeral [simp]: \"of_real (numeral w) = numeral w\"\n  using of_real_of_int_eq [of \"numeral w\"] by simp\n\nlemma of_real_neg_numeral [simp]: \"of_real (- numeral w) = - numeral w\"\n  using of_real_of_int_eq [of \"- numeral w\"] by simp\n\ntext \\<open>Every real algebra has characteristic zero.\\<close>\ninstance real_algebra_1 < ring_char_0\nproof\n  from inj_of_real inj_of_nat have \"inj (of_real \\<circ> of_nat)\"\n    by (rule inj_comp)\n  then show \"inj (of_nat :: nat \\<Rightarrow> 'a)\"\n    by (simp add: comp_def)\nqed\n\nlemma fraction_scaleR_times [simp]:\n  fixes a :: \"'a::real_algebra_1\"\n  shows \"(numeral u / numeral v) *\\<^sub>R (numeral w * a) = (numeral u * numeral w / numeral v) *\\<^sub>R a\"\nby (metis (no_types, lifting) of_real_numeral scaleR_conv_of_real scaleR_scaleR times_divide_eq_left)\n\nlemma inverse_scaleR_times [simp]:\n  fixes a :: \"'a::real_algebra_1\"\n  shows \"(1 / numeral v) *\\<^sub>R (numeral w * a) = (numeral w / numeral v) *\\<^sub>R a\"\nby (metis divide_inverse_commute inverse_eq_divide of_real_numeral scaleR_conv_of_real scaleR_scaleR)\n\nlemma scaleR_times [simp]:\n  fixes a :: \"'a::real_algebra_1\"\n  shows \"(numeral u) *\\<^sub>R (numeral w * a) = (numeral u * numeral w) *\\<^sub>R a\"\nby (simp add: scaleR_conv_of_real)\n\ninstance real_field < field_char_0 ..\n\n\nsubsection \\<open>The Set of Real Numbers\\<close>\n\ndefinition Reals :: \"'a::real_algebra_1 set\"  (\"\\<real>\")\n  where \"\\<real> = range of_real\"\n\nlemma Reals_of_real [simp]: \"of_real r \\<in> \\<real>\"\n  by (simp add: Reals_def)\n\nlemma Reals_of_int [simp]: \"of_int z \\<in> \\<real>\"\n  by (subst of_real_of_int_eq [symmetric], rule Reals_of_real)\n\nlemma Reals_of_nat [simp]: \"of_nat n \\<in> \\<real>\"\n  by (subst of_real_of_nat_eq [symmetric], rule Reals_of_real)\n\nlemma Reals_numeral [simp]: \"numeral w \\<in> \\<real>\"\n  by (subst of_real_numeral [symmetric], rule Reals_of_real)\n\nlemma Reals_0 [simp]: \"0 \\<in> \\<real>\"\n  apply (unfold Reals_def)\n  apply (rule range_eqI)\n  apply (rule of_real_0 [symmetric])\n  done\n\nlemma Reals_1 [simp]: \"1 \\<in> \\<real>\"\n  apply (unfold Reals_def)\n  apply (rule range_eqI)\n  apply (rule of_real_1 [symmetric])\n  done\n\nlemma Reals_add [simp]: \"a \\<in> \\<real> \\<Longrightarrow> b \\<in> \\<real> \\<Longrightarrow> a + b \\<in> \\<real>\"\n  apply (auto simp add: Reals_def)\n  apply (rule range_eqI)\n  apply (rule of_real_add [symmetric])\n  done\n\nlemma Reals_minus [simp]: \"a \\<in> \\<real> \\<Longrightarrow> - a \\<in> \\<real>\"\n  apply (auto simp add: Reals_def)\n  apply (rule range_eqI)\n  apply (rule of_real_minus [symmetric])\n  done\n\nlemma Reals_diff [simp]: \"a \\<in> \\<real> \\<Longrightarrow> b \\<in> \\<real> \\<Longrightarrow> a - b \\<in> \\<real>\"\n  apply (auto simp add: Reals_def)\n  apply (rule range_eqI)\n  apply (rule of_real_diff [symmetric])\n  done\n\nlemma Reals_mult [simp]: \"a \\<in> \\<real> \\<Longrightarrow> b \\<in> \\<real> \\<Longrightarrow> a * b \\<in> \\<real>\"\n  apply (auto simp add: Reals_def)\n  apply (rule range_eqI)\n  apply (rule of_real_mult [symmetric])\n  done\n\nlemma nonzero_Reals_inverse: \"a \\<in> \\<real> \\<Longrightarrow> a \\<noteq> 0 \\<Longrightarrow> inverse a \\<in> \\<real>\"\n  for a :: \"'a::real_div_algebra\"\n  apply (auto simp add: Reals_def)\n  apply (rule range_eqI)\n  apply (erule nonzero_of_real_inverse [symmetric])\n  done\n\nlemma Reals_inverse: \"a \\<in> \\<real> \\<Longrightarrow> inverse a \\<in> \\<real>\"\n  for a :: \"'a::{real_div_algebra,division_ring}\"\n  apply (auto simp add: Reals_def)\n  apply (rule range_eqI)\n  apply (rule of_real_inverse [symmetric])\n  done\n\nlemma Reals_inverse_iff [simp]: \"inverse x \\<in> \\<real> \\<longleftrightarrow> x \\<in> \\<real>\"\n  for x :: \"'a::{real_div_algebra,division_ring}\"\n  by (metis Reals_inverse inverse_inverse_eq)\n\nlemma nonzero_Reals_divide: \"a \\<in> \\<real> \\<Longrightarrow> b \\<in> \\<real> \\<Longrightarrow> b \\<noteq> 0 \\<Longrightarrow> a / b \\<in> \\<real>\"\n  for a b :: \"'a::real_field\"\n  apply (auto simp add: Reals_def)\n  apply (rule range_eqI)\n  apply (erule nonzero_of_real_divide [symmetric])\n  done\n\nlemma Reals_divide [simp]: \"a \\<in> \\<real> \\<Longrightarrow> b \\<in> \\<real> \\<Longrightarrow> a / b \\<in> \\<real>\"\n  for a b :: \"'a::{real_field,field}\"\n  apply (auto simp add: Reals_def)\n  apply (rule range_eqI)\n  apply (rule of_real_divide [symmetric])\n  done\n\nlemma Reals_power [simp]: \"a \\<in> \\<real> \\<Longrightarrow> a ^ n \\<in> \\<real>\"\n  for a :: \"'a::real_algebra_1\"\n  apply (auto simp add: Reals_def)\n  apply (rule range_eqI)\n  apply (rule of_real_power [symmetric])\n  done\n\nlemma Reals_cases [cases set: Reals]:\n  assumes \"q \\<in> \\<real>\"\n  obtains (of_real) r where \"q = of_real r\"\n  unfolding Reals_def\nproof -\n  from \\<open>q \\<in> \\<real>\\<close> have \"q \\<in> range of_real\" unfolding Reals_def .\n  then obtain r where \"q = of_real r\" ..\n  then show thesis ..\nqed\n\nlemma sum_in_Reals [intro,simp]: \"(\\<And>i. i \\<in> s \\<Longrightarrow> f i \\<in> \\<real>) \\<Longrightarrow> sum f s \\<in> \\<real>\"\nproof (induct s rule: infinite_finite_induct)\n  case infinite\n  then show ?case by (metis Reals_0 sum.infinite)\nqed simp_all\n\nlemma prod_in_Reals [intro,simp]: \"(\\<And>i. i \\<in> s \\<Longrightarrow> f i \\<in> \\<real>) \\<Longrightarrow> prod f s \\<in> \\<real>\"\nproof (induct s rule: infinite_finite_induct)\n  case infinite\n  then show ?case by (metis Reals_1 prod.infinite)\nqed simp_all\n\nlemma Reals_induct [case_names of_real, induct set: Reals]:\n  \"q \\<in> \\<real> \\<Longrightarrow> (\\<And>r. P (of_real r)) \\<Longrightarrow> P q\"\n  by (rule Reals_cases) auto\n\n\nsubsection \\<open>Ordered real vector spaces\\<close>\n\nclass ordered_real_vector = real_vector + ordered_ab_group_add +\n  assumes scaleR_left_mono: \"x \\<le> y \\<Longrightarrow> 0 \\<le> a \\<Longrightarrow> a *\\<^sub>R x \\<le> a *\\<^sub>R y\"\n    and scaleR_right_mono: \"a \\<le> b \\<Longrightarrow> 0 \\<le> x \\<Longrightarrow> a *\\<^sub>R x \\<le> b *\\<^sub>R x\"\nbegin\n\nlemma scaleR_mono: \"a \\<le> b \\<Longrightarrow> x \\<le> y \\<Longrightarrow> 0 \\<le> b \\<Longrightarrow> 0 \\<le> x \\<Longrightarrow> a *\\<^sub>R x \\<le> b *\\<^sub>R y\"\n  apply (erule scaleR_right_mono [THEN order_trans])\n   apply assumption\n  apply (erule scaleR_left_mono)\n  apply assumption\n  done\n\nlemma scaleR_mono': \"a \\<le> b \\<Longrightarrow> c \\<le> d \\<Longrightarrow> 0 \\<le> a \\<Longrightarrow> 0 \\<le> c \\<Longrightarrow> a *\\<^sub>R c \\<le> b *\\<^sub>R d\"\n  by (rule scaleR_mono) (auto intro: order.trans)\n\nlemma pos_le_divideRI:\n  assumes \"0 < c\"\n    and \"c *\\<^sub>R a \\<le> b\"\n  shows \"a \\<le> b /\\<^sub>R c\"\nproof -\n  from scaleR_left_mono[OF assms(2)] assms(1)\n  have \"c *\\<^sub>R a /\\<^sub>R c \\<le> b /\\<^sub>R c\"\n    by simp\n  with assms show ?thesis\n    by (simp add: scaleR_one scaleR_scaleR inverse_eq_divide)\nqed\n\nlemma pos_le_divideR_eq:\n  assumes \"0 < c\"\n  shows \"a \\<le> b /\\<^sub>R c \\<longleftrightarrow> c *\\<^sub>R a \\<le> b\"\n    (is \"?lhs \\<longleftrightarrow> ?rhs\")\nproof\n  assume ?lhs\n  from scaleR_left_mono[OF this] assms have \"c *\\<^sub>R a \\<le> c *\\<^sub>R (b /\\<^sub>R c)\"\n    by simp\n  with assms show ?rhs\n    by (simp add: scaleR_one scaleR_scaleR inverse_eq_divide)\nnext\n  assume ?rhs\n  with assms show ?lhs by (rule pos_le_divideRI)\nqed\n\nlemma scaleR_image_atLeastAtMost: \"c > 0 \\<Longrightarrow> scaleR c ` {x..y} = {c *\\<^sub>R x..c *\\<^sub>R y}\"\n  apply (auto intro!: scaleR_left_mono)\n  apply (rule_tac x = \"inverse c *\\<^sub>R xa\" in image_eqI)\n   apply (simp_all add: pos_le_divideR_eq[symmetric] scaleR_scaleR scaleR_one)\n  done\n\nend\n\nlemma neg_le_divideR_eq:\n  fixes a :: \"'a :: ordered_real_vector\"\n  assumes \"c < 0\"\n  shows \"a \\<le> b /\\<^sub>R c \\<longleftrightarrow> b \\<le> c *\\<^sub>R a\"\n  using pos_le_divideR_eq [of \"-c\" a \"-b\"] assms by simp\n\nlemma scaleR_nonneg_nonneg: \"0 \\<le> a \\<Longrightarrow> 0 \\<le> x \\<Longrightarrow> 0 \\<le> a *\\<^sub>R x\"\n  for x :: \"'a::ordered_real_vector\"\n  using scaleR_left_mono [of 0 x a] by simp\n\nlemma scaleR_nonneg_nonpos: \"0 \\<le> a \\<Longrightarrow> x \\<le> 0 \\<Longrightarrow> a *\\<^sub>R x \\<le> 0\"\n  for x :: \"'a::ordered_real_vector\"\n  using scaleR_left_mono [of x 0 a] by simp\n\nlemma scaleR_nonpos_nonneg: \"a \\<le> 0 \\<Longrightarrow> 0 \\<le> x \\<Longrightarrow> a *\\<^sub>R x \\<le> 0\"\n  for x :: \"'a::ordered_real_vector\"\n  using scaleR_right_mono [of a 0 x] by simp\n\nlemma split_scaleR_neg_le: \"(0 \\<le> a \\<and> x \\<le> 0) \\<or> (a \\<le> 0 \\<and> 0 \\<le> x) \\<Longrightarrow> a *\\<^sub>R x \\<le> 0\"\n  for x :: \"'a::ordered_real_vector\"\n  by (auto simp add: scaleR_nonneg_nonpos scaleR_nonpos_nonneg)\n\nlemma le_add_iff1: \"a *\\<^sub>R e + c \\<le> b *\\<^sub>R e + d \\<longleftrightarrow> (a - b) *\\<^sub>R e + c \\<le> d\"\n  for c d e :: \"'a::ordered_real_vector\"\n  by (simp add: algebra_simps)\n\nlemma le_add_iff2: \"a *\\<^sub>R e + c \\<le> b *\\<^sub>R e + d \\<longleftrightarrow> c \\<le> (b - a) *\\<^sub>R e + d\"\n  for c d e :: \"'a::ordered_real_vector\"\n  by (simp add: algebra_simps)\n\nlemma scaleR_left_mono_neg: \"b \\<le> a \\<Longrightarrow> c \\<le> 0 \\<Longrightarrow> c *\\<^sub>R a \\<le> c *\\<^sub>R b\"\n  for a b :: \"'a::ordered_real_vector\"\n  apply (drule scaleR_left_mono [of _ _ \"- c\"])\n   apply simp_all\n  done\n\nlemma scaleR_right_mono_neg: \"b \\<le> a \\<Longrightarrow> c \\<le> 0 \\<Longrightarrow> a *\\<^sub>R c \\<le> b *\\<^sub>R c\"\n  for c :: \"'a::ordered_real_vector\"\n  apply (drule scaleR_right_mono [of _ _ \"- c\"])\n   apply simp_all\n  done\n\nlemma scaleR_nonpos_nonpos: \"a \\<le> 0 \\<Longrightarrow> b \\<le> 0 \\<Longrightarrow> 0 \\<le> a *\\<^sub>R b\"\n  for b :: \"'a::ordered_real_vector\"\n  using scaleR_right_mono_neg [of a 0 b] by simp\n\nlemma split_scaleR_pos_le: \"(0 \\<le> a \\<and> 0 \\<le> b) \\<or> (a \\<le> 0 \\<and> b \\<le> 0) \\<Longrightarrow> 0 \\<le> a *\\<^sub>R b\"\n  for b :: \"'a::ordered_real_vector\"\n  by (auto simp add: scaleR_nonneg_nonneg scaleR_nonpos_nonpos)\n\nlemma zero_le_scaleR_iff:\n  fixes b :: \"'a::ordered_real_vector\"\n  shows \"0 \\<le> a *\\<^sub>R b \\<longleftrightarrow> 0 < a \\<and> 0 \\<le> b \\<or> a < 0 \\<and> b \\<le> 0 \\<or> a = 0\"\n    (is \"?lhs = ?rhs\")\nproof (cases \"a = 0\")\n  case True\n  then show ?thesis by simp\nnext\n  case False\n  show ?thesis\n  proof\n    assume ?lhs\n    from \\<open>a \\<noteq> 0\\<close> consider \"a > 0\" | \"a < 0\" by arith\n    then show ?rhs\n    proof cases\n      case 1\n      with \\<open>?lhs\\<close> have \"inverse a *\\<^sub>R 0 \\<le> inverse a *\\<^sub>R (a *\\<^sub>R b)\"\n        by (intro scaleR_mono) auto\n      with 1 show ?thesis\n        by simp\n    next\n      case 2\n      with \\<open>?lhs\\<close> have \"- inverse a *\\<^sub>R 0 \\<le> - inverse a *\\<^sub>R (a *\\<^sub>R b)\"\n        by (intro scaleR_mono) auto\n      with 2 show ?thesis\n        by simp\n    qed\n  next\n    assume ?rhs\n    then show ?lhs\n      by (auto simp: not_le \\<open>a \\<noteq> 0\\<close> intro!: split_scaleR_pos_le)\n  qed\nqed\n\nlemma scaleR_le_0_iff: \"a *\\<^sub>R b \\<le> 0 \\<longleftrightarrow> 0 < a \\<and> b \\<le> 0 \\<or> a < 0 \\<and> 0 \\<le> b \\<or> a = 0\"\n  for b::\"'a::ordered_real_vector\"\n  by (insert zero_le_scaleR_iff [of \"-a\" b]) force\n\nlemma scaleR_le_cancel_left: \"c *\\<^sub>R a \\<le> c *\\<^sub>R b \\<longleftrightarrow> (0 < c \\<longrightarrow> a \\<le> b) \\<and> (c < 0 \\<longrightarrow> b \\<le> a)\"\n  for b :: \"'a::ordered_real_vector\"\n  by (auto simp add: neq_iff scaleR_left_mono scaleR_left_mono_neg\n      dest: scaleR_left_mono[where a=\"inverse c\"] scaleR_left_mono_neg[where c=\"inverse c\"])\n\nlemma scaleR_le_cancel_left_pos: \"0 < c \\<Longrightarrow> c *\\<^sub>R a \\<le> c *\\<^sub>R b \\<longleftrightarrow> a \\<le> b\"\n  for b :: \"'a::ordered_real_vector\"\n  by (auto simp: scaleR_le_cancel_left)\n\nlemma scaleR_le_cancel_left_neg: \"c < 0 \\<Longrightarrow> c *\\<^sub>R a \\<le> c *\\<^sub>R b \\<longleftrightarrow> b \\<le> a\"\n  for b :: \"'a::ordered_real_vector\"\n  by (auto simp: scaleR_le_cancel_left)\n\nlemma scaleR_left_le_one_le: \"0 \\<le> x \\<Longrightarrow> a \\<le> 1 \\<Longrightarrow> a *\\<^sub>R x \\<le> x\"\n  for x :: \"'a::ordered_real_vector\" and a :: real\n  using scaleR_right_mono[of a 1 x] by simp\n\n\nsubsection \\<open>Real normed vector spaces\\<close>\n\nclass dist =\n  fixes dist :: \"'a \\<Rightarrow> 'a \\<Rightarrow> real\"\n\nclass norm =\n  fixes norm :: \"'a \\<Rightarrow> real\"\n\nclass sgn_div_norm = scaleR + norm + sgn +\n  assumes sgn_div_norm: \"sgn x = x /\\<^sub>R norm x\"\n\nclass dist_norm = dist + norm + minus +\n  assumes dist_norm: \"dist x y = norm (x - y)\"\n\nclass uniformity_dist = dist + uniformity +\n  assumes uniformity_dist: \"uniformity = (INF e:{0 <..}. principal {(x, y). dist x y < e})\"\nbegin\n\nlemma eventually_uniformity_metric:\n  \"eventually P uniformity \\<longleftrightarrow> (\\<exists>e>0. \\<forall>x y. dist x y < e \\<longrightarrow> P (x, y))\"\n  unfolding uniformity_dist\n  by (subst eventually_INF_base)\n     (auto simp: eventually_principal subset_eq intro: bexI[of _ \"min _ _\"])\n\nend\n\nclass real_normed_vector = real_vector + sgn_div_norm + dist_norm + uniformity_dist + open_uniformity +\n  assumes norm_eq_zero [simp]: \"norm x = 0 \\<longleftrightarrow> x = 0\"\n    and norm_triangle_ineq: \"norm (x + y) \\<le> norm x + norm y\"\n    and norm_scaleR [simp]: \"norm (scaleR a x) = \\<bar>a\\<bar> * norm x\"\nbegin\n\nlemma norm_ge_zero [simp]: \"0 \\<le> norm x\"\nproof -\n  have \"0 = norm (x + -1 *\\<^sub>R x)\"\n    using scaleR_add_left[of 1 \"-1\" x] norm_scaleR[of 0 x] by (simp add: scaleR_one)\n  also have \"\\<dots> \\<le> norm x + norm (-1 *\\<^sub>R x)\" by (rule norm_triangle_ineq)\n  finally show ?thesis by simp\nqed\n\nend\n\nclass real_normed_algebra = real_algebra + real_normed_vector +\n  assumes norm_mult_ineq: \"norm (x * y) \\<le> norm x * norm y\"\n\nclass real_normed_algebra_1 = real_algebra_1 + real_normed_algebra +\n  assumes norm_one [simp]: \"norm 1 = 1\"\n\nlemma (in real_normed_algebra_1) scaleR_power [simp]: \"(scaleR x y) ^ n = scaleR (x^n) (y^n)\"\n  by (induct n) (simp_all add: scaleR_one scaleR_scaleR mult_ac)\n\nclass real_normed_div_algebra = real_div_algebra + real_normed_vector +\n  assumes norm_mult: \"norm (x * y) = norm x * norm y\"\n\nclass real_normed_field = real_field + real_normed_div_algebra\n\ninstance real_normed_div_algebra < real_normed_algebra_1\nproof\n  show \"norm (x * y) \\<le> norm x * norm y\" for x y :: 'a\n    by (simp add: norm_mult)\nnext\n  have \"norm (1 * 1::'a) = norm (1::'a) * norm (1::'a)\"\n    by (rule norm_mult)\n  then show \"norm (1::'a) = 1\" by simp\nqed\n\nlemma norm_zero [simp]: \"norm (0::'a::real_normed_vector) = 0\"\n  by simp\n\nlemma zero_less_norm_iff [simp]: \"norm x > 0 \\<longleftrightarrow> x \\<noteq> 0\"\n  for x :: \"'a::real_normed_vector\"\n  by (simp add: order_less_le)\n\nlemma norm_not_less_zero [simp]: \"\\<not> norm x < 0\"\n  for x :: \"'a::real_normed_vector\"\n  by (simp add: linorder_not_less)\n\nlemma norm_le_zero_iff [simp]: \"norm x \\<le> 0 \\<longleftrightarrow> x = 0\"\n  for x :: \"'a::real_normed_vector\"\n  by (simp add: order_le_less)\n\nlemma norm_minus_cancel [simp]: \"norm (- x) = norm x\"\n  for x :: \"'a::real_normed_vector\"\nproof -\n  have \"norm (- x) = norm (scaleR (- 1) x)\"\n    by (simp only: scaleR_minus_left scaleR_one)\n  also have \"\\<dots> = \\<bar>- 1\\<bar> * norm x\"\n    by (rule norm_scaleR)\n  finally show ?thesis by simp\nqed\n\nlemma norm_minus_commute: \"norm (a - b) = norm (b - a)\"\n  for a b :: \"'a::real_normed_vector\"\nproof -\n  have \"norm (- (b - a)) = norm (b - a)\"\n    by (rule norm_minus_cancel)\n  then show ?thesis by simp\nqed\n\nlemma dist_add_cancel [simp]: \"dist (a + b) (a + c) = dist b c\"\n  for a :: \"'a::real_normed_vector\"\n  by (simp add: dist_norm)\n\nlemma dist_add_cancel2 [simp]: \"dist (b + a) (c + a) = dist b c\"\n  for a :: \"'a::real_normed_vector\"\n  by (simp add: dist_norm)\n\nlemma dist_scaleR [simp]: \"dist (x *\\<^sub>R a) (y *\\<^sub>R a) = \\<bar>x - y\\<bar> * norm a\"\n  for a :: \"'a::real_normed_vector\"\n  by (metis dist_norm norm_scaleR scaleR_left.diff)\n\nlemma norm_uminus_minus: \"norm (- x - y :: 'a :: real_normed_vector) = norm (x + y)\"\n  by (subst (2) norm_minus_cancel[symmetric], subst minus_add_distrib) simp\n\nlemma norm_triangle_ineq2: \"norm a - norm b \\<le> norm (a - b)\"\n  for a b :: \"'a::real_normed_vector\"\nproof -\n  have \"norm (a - b + b) \\<le> norm (a - b) + norm b\"\n    by (rule norm_triangle_ineq)\n  then show ?thesis by simp\nqed\n\nlemma norm_triangle_ineq3: \"\\<bar>norm a - norm b\\<bar> \\<le> norm (a - b)\"\n  for a b :: \"'a::real_normed_vector\"\n  apply (subst abs_le_iff)\n  apply auto\n   apply (rule norm_triangle_ineq2)\n  apply (subst norm_minus_commute)\n  apply (rule norm_triangle_ineq2)\n  done\n\nlemma norm_triangle_ineq4: \"norm (a - b) \\<le> norm a + norm b\"\n  for a b :: \"'a::real_normed_vector\"\nproof -\n  have \"norm (a + - b) \\<le> norm a + norm (- b)\"\n    by (rule norm_triangle_ineq)\n  then show ?thesis by simp\nqed\n\nlemma norm_diff_ineq: \"norm a - norm b \\<le> norm (a + b)\"\n  for a b :: \"'a::real_normed_vector\"\nproof -\n  have \"norm a - norm (- b) \\<le> norm (a - - b)\"\n    by (rule norm_triangle_ineq2)\n  then show ?thesis by simp\nqed\n\nlemma norm_add_leD: \"norm (a + b) \\<le> c \\<Longrightarrow> norm b \\<le> norm a + c\"\n  for a b :: \"'a::real_normed_vector\"\n  by (metis add.commute diff_le_eq norm_diff_ineq order.trans)\n\nlemma norm_diff_triangle_ineq: \"norm ((a + b) - (c + d)) \\<le> norm (a - c) + norm (b - d)\"\n  for a b c d :: \"'a::real_normed_vector\"\nproof -\n  have \"norm ((a + b) - (c + d)) = norm ((a - c) + (b - d))\"\n    by (simp add: algebra_simps)\n  also have \"\\<dots> \\<le> norm (a - c) + norm (b - d)\"\n    by (rule norm_triangle_ineq)\n  finally show ?thesis .\nqed\n\nlemma norm_diff_triangle_le:\n  fixes x y z :: \"'a::real_normed_vector\"\n  assumes \"norm (x - y) \\<le> e1\"  \"norm (y - z) \\<le> e2\"\n  shows \"norm (x - z) \\<le> e1 + e2\"\n  using norm_diff_triangle_ineq [of x y y z] assms by simp\n\nlemma norm_diff_triangle_less:\n  fixes x y z :: \"'a::real_normed_vector\"\n  assumes \"norm (x - y) < e1\"  \"norm (y - z) < e2\"\n  shows \"norm (x - z) < e1 + e2\"\n  using norm_diff_triangle_ineq [of x y y z] assms by simp\n\nlemma norm_triangle_mono:\n  fixes a b :: \"'a::real_normed_vector\"\n  shows \"norm a \\<le> r \\<Longrightarrow> norm b \\<le> s \\<Longrightarrow> norm (a + b) \\<le> r + s\"\n  by (metis add_mono_thms_linordered_semiring(1) norm_triangle_ineq order.trans)\n\nlemma norm_sum:\n  fixes f :: \"'a \\<Rightarrow> 'b::real_normed_vector\"\n  shows \"norm (sum f A) \\<le> (\\<Sum>i\\<in>A. norm (f i))\"\n  by (induct A rule: infinite_finite_induct) (auto intro: norm_triangle_mono)\n\nlemma sum_norm_le:\n  fixes f :: \"'a \\<Rightarrow> 'b::real_normed_vector\"\n  assumes fg: \"\\<forall>x \\<in> S. norm (f x) \\<le> g x\"\n  shows \"norm (sum f S) \\<le> sum g S\"\n  by (rule order_trans [OF norm_sum sum_mono]) (simp add: fg)\n\nlemma abs_norm_cancel [simp]: \"\\<bar>norm a\\<bar> = norm a\"\n  for a :: \"'a::real_normed_vector\"\n  by (rule abs_of_nonneg [OF norm_ge_zero])\n\nlemma norm_add_less: \"norm x < r \\<Longrightarrow> norm y < s \\<Longrightarrow> norm (x + y) < r + s\"\n  for x y :: \"'a::real_normed_vector\"\n  by (rule order_le_less_trans [OF norm_triangle_ineq add_strict_mono])\n\nlemma norm_mult_less: \"norm x < r \\<Longrightarrow> norm y < s \\<Longrightarrow> norm (x * y) < r * s\"\n  for x y :: \"'a::real_normed_algebra\"\n  by (rule order_le_less_trans [OF norm_mult_ineq]) (simp add: mult_strict_mono')\n\nlemma norm_of_real [simp]: \"norm (of_real r :: 'a::real_normed_algebra_1) = \\<bar>r\\<bar>\"\n  by (simp add: of_real_def)\n\nlemma norm_numeral [simp]: \"norm (numeral w::'a::real_normed_algebra_1) = numeral w\"\n  by (subst of_real_numeral [symmetric], subst norm_of_real, simp)\n\nlemma norm_neg_numeral [simp]: \"norm (- numeral w::'a::real_normed_algebra_1) = numeral w\"\n  by (subst of_real_neg_numeral [symmetric], subst norm_of_real, simp)\n\nlemma norm_of_real_add1 [simp]: \"norm (of_real x + 1 :: 'a :: real_normed_div_algebra) = \\<bar>x + 1\\<bar>\"\n  by (metis norm_of_real of_real_1 of_real_add)\n\nlemma norm_of_real_addn [simp]:\n  \"norm (of_real x + numeral b :: 'a :: real_normed_div_algebra) = \\<bar>x + numeral b\\<bar>\"\n  by (metis norm_of_real of_real_add of_real_numeral)\n\nlemma norm_of_int [simp]: \"norm (of_int z::'a::real_normed_algebra_1) = \\<bar>of_int z\\<bar>\"\n  by (subst of_real_of_int_eq [symmetric], rule norm_of_real)\n\nlemma norm_of_nat [simp]: \"norm (of_nat n::'a::real_normed_algebra_1) = of_nat n\"\n  apply (subst of_real_of_nat_eq [symmetric])\n  apply (subst norm_of_real, simp)\n  done\n\nlemma nonzero_norm_inverse: \"a \\<noteq> 0 \\<Longrightarrow> norm (inverse a) = inverse (norm a)\"\n  for a :: \"'a::real_normed_div_algebra\"\n  apply (rule inverse_unique [symmetric])\n  apply (simp add: norm_mult [symmetric])\n  done\n\nlemma norm_inverse: \"norm (inverse a) = inverse (norm a)\"\n  for a :: \"'a::{real_normed_div_algebra,division_ring}\"\n  apply (cases \"a = 0\")\n   apply simp\n  apply (erule nonzero_norm_inverse)\n  done\n\nlemma nonzero_norm_divide: \"b \\<noteq> 0 \\<Longrightarrow> norm (a / b) = norm a / norm b\"\n  for a b :: \"'a::real_normed_field\"\n  by (simp add: divide_inverse norm_mult nonzero_norm_inverse)\n\nlemma norm_divide: \"norm (a / b) = norm a / norm b\"\n  for a b :: \"'a::{real_normed_field,field}\"\n  by (simp add: divide_inverse norm_mult norm_inverse)\n\nlemma norm_power_ineq: \"norm (x ^ n) \\<le> norm x ^ n\"\n  for x :: \"'a::real_normed_algebra_1\"\nproof (induct n)\n  case 0\n  show \"norm (x ^ 0) \\<le> norm x ^ 0\" by simp\nnext\n  case (Suc n)\n  have \"norm (x * x ^ n) \\<le> norm x * norm (x ^ n)\"\n    by (rule norm_mult_ineq)\n  also from Suc have \"\\<dots> \\<le> norm x * norm x ^ n\"\n    using norm_ge_zero by (rule mult_left_mono)\n  finally show \"norm (x ^ Suc n) \\<le> norm x ^ Suc n\"\n    by simp\nqed\n\nlemma norm_power: \"norm (x ^ n) = norm x ^ n\"\n  for x :: \"'a::real_normed_div_algebra\"\n  by (induct n) (simp_all add: norm_mult)\n\nlemma power_eq_imp_eq_norm:\n  fixes w :: \"'a::real_normed_div_algebra\"\n  assumes eq: \"w ^ n = z ^ n\" and \"n > 0\"\n    shows \"norm w = norm z\"\nproof -\n  have \"norm w ^ n = norm z ^ n\"\n    by (metis (no_types) eq norm_power)\n  then show ?thesis\n    using assms by (force intro: power_eq_imp_eq_base)\nqed\n\nlemma norm_mult_numeral1 [simp]: \"norm (numeral w * a) = numeral w * norm a\"\n  for a b :: \"'a::{real_normed_field,field}\"\n  by (simp add: norm_mult)\n\nlemma norm_mult_numeral2 [simp]: \"norm (a * numeral w) = norm a * numeral w\"\n  for a b :: \"'a::{real_normed_field,field}\"\n  by (simp add: norm_mult)\n\nlemma norm_divide_numeral [simp]: \"norm (a / numeral w) = norm a / numeral w\"\n  for a b :: \"'a::{real_normed_field,field}\"\n  by (simp add: norm_divide)\n\nlemma norm_of_real_diff [simp]:\n  \"norm (of_real b - of_real a :: 'a::real_normed_algebra_1) \\<le> \\<bar>b - a\\<bar>\"\n  by (metis norm_of_real of_real_diff order_refl)\n\ntext \\<open>Despite a superficial resemblance, \\<open>norm_eq_1\\<close> is not relevant.\\<close>\nlemma square_norm_one:\n  fixes x :: \"'a::real_normed_div_algebra\"\n  assumes \"x\\<^sup>2 = 1\"\n  shows \"norm x = 1\"\n  by (metis assms norm_minus_cancel norm_one power2_eq_1_iff)\n\nlemma norm_less_p1: \"norm x < norm (of_real (norm x) + 1 :: 'a)\"\n  for x :: \"'a::real_normed_algebra_1\"\nproof -\n  have \"norm x < norm (of_real (norm x + 1) :: 'a)\"\n    by (simp add: of_real_def)\n  then show ?thesis\n    by simp\nqed\n\nlemma prod_norm: \"prod (\\<lambda>x. norm (f x)) A = norm (prod f A)\"\n  for f :: \"'a \\<Rightarrow> 'b::{comm_semiring_1,real_normed_div_algebra}\"\n  by (induct A rule: infinite_finite_induct) (auto simp: norm_mult)\n\nlemma norm_prod_le:\n  \"norm (prod f A) \\<le> (\\<Prod>a\\<in>A. norm (f a :: 'a :: {real_normed_algebra_1,comm_monoid_mult}))\"\nproof (induct A rule: infinite_finite_induct)\n  case empty\n  then show ?case by simp\nnext\n  case (insert a A)\n  then have \"norm (prod f (insert a A)) \\<le> norm (f a) * norm (prod f A)\"\n    by (simp add: norm_mult_ineq)\n  also have \"norm (prod f A) \\<le> (\\<Prod>a\\<in>A. norm (f a))\"\n    by (rule insert)\n  finally show ?case\n    by (simp add: insert mult_left_mono)\nnext\n  case infinite\n  then show ?case by simp\nqed\n\nlemma norm_prod_diff:\n  fixes z w :: \"'i \\<Rightarrow> 'a::{real_normed_algebra_1, comm_monoid_mult}\"\n  shows \"(\\<And>i. i \\<in> I \\<Longrightarrow> norm (z i) \\<le> 1) \\<Longrightarrow> (\\<And>i. i \\<in> I \\<Longrightarrow> norm (w i) \\<le> 1) \\<Longrightarrow>\n    norm ((\\<Prod>i\\<in>I. z i) - (\\<Prod>i\\<in>I. w i)) \\<le> (\\<Sum>i\\<in>I. norm (z i - w i))\"\nproof (induction I rule: infinite_finite_induct)\n  case empty\n  then show ?case by simp\nnext\n  case (insert i I)\n  note insert.hyps[simp]\n\n  have \"norm ((\\<Prod>i\\<in>insert i I. z i) - (\\<Prod>i\\<in>insert i I. w i)) =\n    norm ((\\<Prod>i\\<in>I. z i) * (z i - w i) + ((\\<Prod>i\\<in>I. z i) - (\\<Prod>i\\<in>I. w i)) * w i)\"\n    (is \"_ = norm (?t1 + ?t2)\")\n    by (auto simp add: field_simps)\n  also have \"\\<dots> \\<le> norm ?t1 + norm ?t2\"\n    by (rule norm_triangle_ineq)\n  also have \"norm ?t1 \\<le> norm (\\<Prod>i\\<in>I. z i) * norm (z i - w i)\"\n    by (rule norm_mult_ineq)\n  also have \"\\<dots> \\<le> (\\<Prod>i\\<in>I. norm (z i)) * norm(z i - w i)\"\n    by (rule mult_right_mono) (auto intro: norm_prod_le)\n  also have \"(\\<Prod>i\\<in>I. norm (z i)) \\<le> (\\<Prod>i\\<in>I. 1)\"\n    by (intro prod_mono) (auto intro!: insert)\n  also have \"norm ?t2 \\<le> norm ((\\<Prod>i\\<in>I. z i) - (\\<Prod>i\\<in>I. w i)) * norm (w i)\"\n    by (rule norm_mult_ineq)\n  also have \"norm (w i) \\<le> 1\"\n    by (auto intro: insert)\n  also have \"norm ((\\<Prod>i\\<in>I. z i) - (\\<Prod>i\\<in>I. w i)) \\<le> (\\<Sum>i\\<in>I. norm (z i - w i))\"\n    using insert by auto\n  finally show ?case\n    by (auto simp add: ac_simps mult_right_mono mult_left_mono)\nnext\n  case infinite\n  then show ?case by simp\nqed\n\nlemma norm_power_diff:\n  fixes z w :: \"'a::{real_normed_algebra_1, comm_monoid_mult}\"\n  assumes \"norm z \\<le> 1\" \"norm w \\<le> 1\"\n  shows \"norm (z^m - w^m) \\<le> m * norm (z - w)\"\nproof -\n  have \"norm (z^m - w^m) = norm ((\\<Prod> i < m. z) - (\\<Prod> i < m. w))\"\n    by (simp add: prod_constant)\n  also have \"\\<dots> \\<le> (\\<Sum>i<m. norm (z - w))\"\n    by (intro norm_prod_diff) (auto simp add: assms)\n  also have \"\\<dots> = m * norm (z - w)\"\n    by simp\n  finally show ?thesis .\nqed\n\n\nsubsection \\<open>Metric spaces\\<close>\n\nclass metric_space = uniformity_dist + open_uniformity +\n  assumes dist_eq_0_iff [simp]: \"dist x y = 0 \\<longleftrightarrow> x = y\"\n    and dist_triangle2: \"dist x y \\<le> dist x z + dist y z\"\nbegin\n\nlemma dist_self [simp]: \"dist x x = 0\"\n  by simp\n\nlemma zero_le_dist [simp]: \"0 \\<le> dist x y\"\n  using dist_triangle2 [of x x y] by simp\n\nlemma zero_less_dist_iff: \"0 < dist x y \\<longleftrightarrow> x \\<noteq> y\"\n  by (simp add: less_le)\n\nlemma dist_not_less_zero [simp]: \"\\<not> dist x y < 0\"\n  by (simp add: not_less)\n\nlemma dist_le_zero_iff [simp]: \"dist x y \\<le> 0 \\<longleftrightarrow> x = y\"\n  by (simp add: le_less)\n\nlemma dist_commute: \"dist x y = dist y x\"\nproof (rule order_antisym)\n  show \"dist x y \\<le> dist y x\"\n    using dist_triangle2 [of x y x] by simp\n  show \"dist y x \\<le> dist x y\"\n    using dist_triangle2 [of y x y] by simp\nqed\n\nlemma dist_commute_lessI: \"dist y x < e \\<Longrightarrow> dist x y < e\"\n  by (simp add: dist_commute)\n\nlemma dist_triangle: \"dist x z \\<le> dist x y + dist y z\"\n  using dist_triangle2 [of x z y] by (simp add: dist_commute)\n\nlemma dist_triangle3: \"dist x y \\<le> dist a x + dist a y\"\n  using dist_triangle2 [of x y a] by (simp add: dist_commute)\n\nlemma dist_pos_lt: \"x \\<noteq> y \\<Longrightarrow> 0 < dist x y\"\n  by (simp add: zero_less_dist_iff)\n\nlemma dist_nz: \"x \\<noteq> y \\<longleftrightarrow> 0 < dist x y\"\n  by (simp add: zero_less_dist_iff)\n\ndeclare dist_nz [symmetric, simp]\n\nlemma dist_triangle_le: \"dist x z + dist y z \\<le> e \\<Longrightarrow> dist x y \\<le> e\"\n  by (rule order_trans [OF dist_triangle2])\n\nlemma dist_triangle_lt: \"dist x z + dist y z < e \\<Longrightarrow> dist x y < e\"\n  by (rule le_less_trans [OF dist_triangle2])\n\nlemma dist_triangle_less_add: \"dist x1 y < e1 \\<Longrightarrow> dist x2 y < e2 \\<Longrightarrow> dist x1 x2 < e1 + e2\"\n  by (rule dist_triangle_lt [where z=y]) simp\n\nlemma dist_triangle_half_l: \"dist x1 y < e / 2 \\<Longrightarrow> dist x2 y < e / 2 \\<Longrightarrow> dist x1 x2 < e\"\n  by (rule dist_triangle_lt [where z=y]) simp\n\nlemma dist_triangle_half_r: \"dist y x1 < e / 2 \\<Longrightarrow> dist y x2 < e / 2 \\<Longrightarrow> dist x1 x2 < e\"\n  by (rule dist_triangle_half_l) (simp_all add: dist_commute)\n\nsubclass uniform_space\nproof\n  fix E x\n  assume \"eventually E uniformity\"\n  then obtain e where E: \"0 < e\" \"\\<And>x y. dist x y < e \\<Longrightarrow> E (x, y)\"\n    by (auto simp: eventually_uniformity_metric)\n  then show \"E (x, x)\" \"\\<forall>\\<^sub>F (x, y) in uniformity. E (y, x)\"\n    by (auto simp: eventually_uniformity_metric dist_commute)\n  show \"\\<exists>D. eventually D uniformity \\<and> (\\<forall>x y z. D (x, y) \\<longrightarrow> D (y, z) \\<longrightarrow> E (x, z))\"\n    using E dist_triangle_half_l[where e=e]\n    unfolding eventually_uniformity_metric\n    by (intro exI[of _ \"\\<lambda>(x, y). dist x y < e / 2\"] exI[of _ \"e/2\"] conjI)\n      (auto simp: dist_commute)\nqed\n\nlemma open_dist: \"open S \\<longleftrightarrow> (\\<forall>x\\<in>S. \\<exists>e>0. \\<forall>y. dist y x < e \\<longrightarrow> y \\<in> S)\"\n  by (simp add: dist_commute open_uniformity eventually_uniformity_metric)\n\nlemma open_ball: \"open {y. dist x y < d}\"\n  unfolding open_dist\nproof (intro ballI)\n  fix y\n  assume *: \"y \\<in> {y. dist x y < d}\"\n  then show \"\\<exists>e>0. \\<forall>z. dist z y < e \\<longrightarrow> z \\<in> {y. dist x y < d}\"\n    by (auto intro!: exI[of _ \"d - dist x y\"] simp: field_simps dist_triangle_lt)\nqed\n\nsubclass first_countable_topology\nproof\n  fix x\n  show \"\\<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))\"\n  proof (safe intro!: exI[of _ \"\\<lambda>n. {y. dist x y < inverse (Suc n)}\"])\n    fix S\n    assume \"open S\" \"x \\<in> S\"\n    then obtain e where e: \"0 < e\" and \"{y. dist x y < e} \\<subseteq> S\"\n      by (auto simp: open_dist subset_eq dist_commute)\n    moreover\n    from e obtain i where \"inverse (Suc i) < e\"\n      by (auto dest!: reals_Archimedean)\n    then have \"{y. dist x y < inverse (Suc i)} \\<subseteq> {y. dist x y < e}\"\n      by auto\n    ultimately show \"\\<exists>i. {y. dist x y < inverse (Suc i)} \\<subseteq> S\"\n      by blast\n  qed (auto intro: open_ball)\nqed\n\nend\n\ninstance metric_space \\<subseteq> t2_space\nproof\n  fix x y :: \"'a::metric_space\"\n  assume xy: \"x \\<noteq> y\"\n  let ?U = \"{y'. dist x y' < dist x y / 2}\"\n  let ?V = \"{x'. dist y x' < dist x y / 2}\"\n  have *: \"d x z \\<le> d x y + d y z \\<Longrightarrow> d y z = d z y \\<Longrightarrow> \\<not> (d x y * 2 < d x z \\<and> d z y * 2 < d x z)\"\n    for d :: \"'a \\<Rightarrow> 'a \\<Rightarrow> real\" and x y z :: 'a\n    by arith\n  have \"open ?U \\<and> open ?V \\<and> x \\<in> ?U \\<and> y \\<in> ?V \\<and> ?U \\<inter> ?V = {}\"\n    using dist_pos_lt[OF xy] *[of dist, OF dist_triangle dist_commute]\n    using open_ball[of _ \"dist x y / 2\"] by auto\n  then show \"\\<exists>U V. open U \\<and> open V \\<and> x \\<in> U \\<and> y \\<in> V \\<and> U \\<inter> V = {}\"\n    by blast\nqed\n\ntext \\<open>Every normed vector space is a metric space.\\<close>\ninstance real_normed_vector < metric_space\nproof\n  fix x y z :: 'a\n  show \"dist x y = 0 \\<longleftrightarrow> x = y\"\n    by (simp add: dist_norm)\n  show \"dist x y \\<le> dist x z + dist y z\"\n    using norm_triangle_ineq4 [of \"x - z\" \"y - z\"] by (simp add: dist_norm)\nqed\n\n\nsubsection \\<open>Class instances for real numbers\\<close>\n\ninstantiation real :: real_normed_field\nbegin\n\ndefinition dist_real_def: \"dist x y = \\<bar>x - y\\<bar>\"\n\ndefinition uniformity_real_def [code del]:\n  \"(uniformity :: (real \\<times> real) filter) = (INF e:{0 <..}. principal {(x, y). dist x y < e})\"\n\ndefinition open_real_def [code del]:\n  \"open (U :: real set) \\<longleftrightarrow> (\\<forall>x\\<in>U. eventually (\\<lambda>(x', y). x' = x \\<longrightarrow> y \\<in> U) uniformity)\"\n\ndefinition real_norm_def [simp]: \"norm r = \\<bar>r\\<bar>\"\n\ninstance\n  apply intro_classes\n         apply (unfold real_norm_def real_scaleR_def)\n         apply (rule dist_real_def)\n        apply (simp add: sgn_real_def)\n       apply (rule uniformity_real_def)\n      apply (rule open_real_def)\n     apply (rule abs_eq_0)\n    apply (rule abs_triangle_ineq)\n   apply (rule abs_mult)\n  apply (rule abs_mult)\n  done\n\nend\n\ndeclare uniformity_Abort[where 'a=real, code]\n\nlemma dist_of_real [simp]: \"dist (of_real x :: 'a) (of_real y) = dist x y\"\n  for a :: \"'a::real_normed_div_algebra\"\n  by (metis dist_norm norm_of_real of_real_diff real_norm_def)\n\ndeclare [[code abort: \"open :: real set \\<Rightarrow> bool\"]]\n\ninstance real :: linorder_topology\nproof\n  show \"(open :: real set \\<Rightarrow> bool) = generate_topology (range lessThan \\<union> range greaterThan)\"\n  proof (rule ext, safe)\n    fix S :: \"real set\"\n    assume \"open S\"\n    then obtain f where \"\\<forall>x\\<in>S. 0 < f x \\<and> (\\<forall>y. dist y x < f x \\<longrightarrow> y \\<in> S)\"\n      unfolding open_dist bchoice_iff ..\n    then have *: \"S = (\\<Union>x\\<in>S. {x - f x <..} \\<inter> {..< x + f x})\"\n      by (fastforce simp: dist_real_def)\n    show \"generate_topology (range lessThan \\<union> range greaterThan) S\"\n      apply (subst *)\n      apply (intro generate_topology_Union generate_topology.Int)\n       apply (auto intro: generate_topology.Basis)\n      done\n  next\n    fix S :: \"real set\"\n    assume \"generate_topology (range lessThan \\<union> range greaterThan) S\"\n    moreover have \"\\<And>a::real. open {..<a}\"\n      unfolding open_dist dist_real_def\n    proof clarify\n      fix x a :: real\n      assume \"x < a\"\n      then have \"0 < a - x \\<and> (\\<forall>y. \\<bar>y - x\\<bar> < a - x \\<longrightarrow> y \\<in> {..<a})\" by auto\n      then show \"\\<exists>e>0. \\<forall>y. \\<bar>y - x\\<bar> < e \\<longrightarrow> y \\<in> {..<a}\" ..\n    qed\n    moreover have \"\\<And>a::real. open {a <..}\"\n      unfolding open_dist dist_real_def\n    proof clarify\n      fix x a :: real\n      assume \"a < x\"\n      then have \"0 < x - a \\<and> (\\<forall>y. \\<bar>y - x\\<bar> < x - a \\<longrightarrow> y \\<in> {a<..})\" by auto\n      then show \"\\<exists>e>0. \\<forall>y. \\<bar>y - x\\<bar> < e \\<longrightarrow> y \\<in> {a<..}\" ..\n    qed\n    ultimately show \"open S\"\n      by induct auto\n  qed\nqed\n\ninstance real :: linear_continuum_topology ..\n\nlemmas open_real_greaterThan = open_greaterThan[where 'a=real]\nlemmas open_real_lessThan = open_lessThan[where 'a=real]\nlemmas open_real_greaterThanLessThan = open_greaterThanLessThan[where 'a=real]\nlemmas closed_real_atMost = closed_atMost[where 'a=real]\nlemmas closed_real_atLeast = closed_atLeast[where 'a=real]\nlemmas closed_real_atLeastAtMost = closed_atLeastAtMost[where 'a=real]\n\n\nsubsection \\<open>Extra type constraints\\<close>\n\ntext \\<open>Only allow @{term \"open\"} in class \\<open>topological_space\\<close>.\\<close>\nsetup \\<open>Sign.add_const_constraint\n  (@{const_name \"open\"}, SOME @{typ \"'a::topological_space set \\<Rightarrow> bool\"})\\<close>\n\ntext \\<open>Only allow @{term \"uniformity\"} in class \\<open>uniform_space\\<close>.\\<close>\nsetup \\<open>Sign.add_const_constraint\n  (@{const_name \"uniformity\"}, SOME @{typ \"('a::uniformity \\<times> 'a) filter\"})\\<close>\n\ntext \\<open>Only allow @{term dist} in class \\<open>metric_space\\<close>.\\<close>\nsetup \\<open>Sign.add_const_constraint\n  (@{const_name dist}, SOME @{typ \"'a::metric_space \\<Rightarrow> 'a \\<Rightarrow> real\"})\\<close>\n\ntext \\<open>Only allow @{term norm} in class \\<open>real_normed_vector\\<close>.\\<close>\nsetup \\<open>Sign.add_const_constraint\n  (@{const_name norm}, SOME @{typ \"'a::real_normed_vector \\<Rightarrow> real\"})\\<close>\n\n\nsubsection \\<open>Sign function\\<close>\n\nlemma norm_sgn: \"norm (sgn x) = (if x = 0 then 0 else 1)\"\n  for x :: \"'a::real_normed_vector\"\n  by (simp add: sgn_div_norm)\n\nlemma sgn_zero [simp]: \"sgn (0::'a::real_normed_vector) = 0\"\n  by (simp add: sgn_div_norm)\n\nlemma sgn_zero_iff: \"sgn x = 0 \\<longleftrightarrow> x = 0\"\n  for x :: \"'a::real_normed_vector\"\n  by (simp add: sgn_div_norm)\n\nlemma sgn_minus: \"sgn (- x) = - sgn x\"\n  for x :: \"'a::real_normed_vector\"\n  by (simp add: sgn_div_norm)\n\nlemma sgn_scaleR: \"sgn (scaleR r x) = scaleR (sgn r) (sgn x)\"\n  for x :: \"'a::real_normed_vector\"\n  by (simp add: sgn_div_norm ac_simps)\n\nlemma sgn_one [simp]: \"sgn (1::'a::real_normed_algebra_1) = 1\"\n  by (simp add: sgn_div_norm)\n\nlemma sgn_of_real: \"sgn (of_real r :: 'a::real_normed_algebra_1) = of_real (sgn r)\"\n  unfolding of_real_def by (simp only: sgn_scaleR sgn_one)\n\nlemma sgn_mult: \"sgn (x * y) = sgn x * sgn y\"\n  for x y :: \"'a::real_normed_div_algebra\"\n  by (simp add: sgn_div_norm norm_mult mult.commute)\n\nhide_fact (open) sgn_mult\n\nlemma real_sgn_eq: \"sgn x = x / \\<bar>x\\<bar>\"\n  for x :: real\n  by (simp add: sgn_div_norm divide_inverse)\n\nlemma zero_le_sgn_iff [simp]: \"0 \\<le> sgn x \\<longleftrightarrow> 0 \\<le> x\"\n  for x :: real\n  by (cases \"0::real\" x rule: linorder_cases) simp_all\n\nlemma sgn_le_0_iff [simp]: \"sgn x \\<le> 0 \\<longleftrightarrow> x \\<le> 0\"\n  for x :: real\n  by (cases \"0::real\" x rule: linorder_cases) simp_all\n\nlemma norm_conv_dist: \"norm x = dist x 0\"\n  unfolding dist_norm by simp\n\ndeclare norm_conv_dist [symmetric, simp]\n\nlemma dist_0_norm [simp]: \"dist 0 x = norm x\"\n  for x :: \"'a::real_normed_vector\"\n  by (simp add: dist_norm)\n\nlemma dist_diff [simp]: \"dist a (a - b) = norm b\"  \"dist (a - b) a = norm b\"\n  by (simp_all add: dist_norm)\n\nlemma dist_of_int: \"dist (of_int m) (of_int n :: 'a :: real_normed_algebra_1) = of_int \\<bar>m - n\\<bar>\"\nproof -\n  have \"dist (of_int m) (of_int n :: 'a) = dist (of_int m :: 'a) (of_int m - (of_int (m - n)))\"\n    by simp\n  also have \"\\<dots> = of_int \\<bar>m - n\\<bar>\" by (subst dist_diff, subst norm_of_int) simp\n  finally show ?thesis .\nqed\n\nlemma dist_of_nat:\n  \"dist (of_nat m) (of_nat n :: 'a :: real_normed_algebra_1) = of_int \\<bar>int m - int n\\<bar>\"\n  by (subst (1 2) of_int_of_nat_eq [symmetric]) (rule dist_of_int)\n\n\nsubsection \\<open>Bounded Linear and Bilinear Operators\\<close>\n\nlocale linear = additive f for f :: \"'a::real_vector \\<Rightarrow> 'b::real_vector\" +\n  assumes scaleR: \"f (scaleR r x) = scaleR r (f x)\"\n\nlemma linear_imp_scaleR:\n  assumes \"linear D\"\n  obtains d where \"D = (\\<lambda>x. x *\\<^sub>R d)\"\n  by (metis assms linear.scaleR mult.commute mult.left_neutral real_scaleR_def)\n\ncorollary real_linearD:\n  fixes f :: \"real \\<Rightarrow> real\"\n  assumes \"linear f\" obtains c where \"f = op* c\"\n  by (rule linear_imp_scaleR [OF assms]) (force simp: scaleR_conv_of_real)\n\nlemma linearI:\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 \"linear f\"\n  by standard (rule assms)+\n\nlocale bounded_linear = linear f for f :: \"'a::real_normed_vector \\<Rightarrow> 'b::real_normed_vector\" +\n  assumes bounded: \"\\<exists>K. \\<forall>x. norm (f x) \\<le> norm x * K\"\nbegin\n\nlemma pos_bounded: \"\\<exists>K>0. \\<forall>x. norm (f x) \\<le> norm x * K\"\nproof -\n  obtain K where K: \"\\<And>x. norm (f x) \\<le> norm x * K\"\n    using bounded by blast\n  show ?thesis\n  proof (intro exI impI conjI allI)\n    show \"0 < max 1 K\"\n      by (rule order_less_le_trans [OF zero_less_one max.cobounded1])\n  next\n    fix x\n    have \"norm (f x) \\<le> norm x * K\" using K .\n    also have \"\\<dots> \\<le> norm x * max 1 K\"\n      by (rule mult_left_mono [OF max.cobounded2 norm_ge_zero])\n    finally show \"norm (f x) \\<le> norm x * max 1 K\" .\n  qed\nqed\n\nlemma nonneg_bounded: \"\\<exists>K\\<ge>0. \\<forall>x. norm (f x) \\<le> norm x * K\"\n  using pos_bounded by (auto intro: order_less_imp_le)\n\nlemma linear: \"linear f\"\n  by (fact local.linear_axioms)\n\nend\n\nlemma bounded_linear_intro:\n  assumes \"\\<And>x y. f (x + y) = f x + f y\"\n    and \"\\<And>r x. f (scaleR r x) = scaleR r (f x)\"\n    and \"\\<And>x. norm (f x) \\<le> norm x * K\"\n  shows \"bounded_linear f\"\n  by standard (blast intro: assms)+\n\nlocale bounded_bilinear =\n  fixes prod :: \"'a::real_normed_vector \\<Rightarrow> 'b::real_normed_vector \\<Rightarrow> 'c::real_normed_vector\"\n    (infixl \"**\" 70)\n  assumes add_left: \"prod (a + a') b = prod a b + prod a' b\"\n    and add_right: \"prod a (b + b') = prod a b + prod a b'\"\n    and scaleR_left: \"prod (scaleR r a) b = scaleR r (prod a b)\"\n    and scaleR_right: \"prod a (scaleR r b) = scaleR r (prod a b)\"\n    and bounded: \"\\<exists>K. \\<forall>a b. norm (prod a b) \\<le> norm a * norm b * K\"\nbegin\n\nlemma pos_bounded: \"\\<exists>K>0. \\<forall>a b. norm (a ** b) \\<le> norm a * norm b * K\"\n  apply (insert bounded)\n  apply (erule exE)\n  apply (rule_tac x=\"max 1 K\" in exI)\n  apply safe\n   apply (rule order_less_le_trans [OF zero_less_one max.cobounded1])\n  apply (drule spec)\n  apply (drule spec)\n  apply (erule order_trans)\n  apply (rule mult_left_mono [OF max.cobounded2])\n  apply (intro mult_nonneg_nonneg norm_ge_zero)\n  done\n\nlemma nonneg_bounded: \"\\<exists>K\\<ge>0. \\<forall>a b. norm (a ** b) \\<le> norm a * norm b * K\"\n  using pos_bounded by (auto intro: order_less_imp_le)\n\nlemma additive_right: \"additive (\\<lambda>b. prod a b)\"\n  by (rule additive.intro, rule add_right)\n\nlemma additive_left: \"additive (\\<lambda>a. prod a b)\"\n  by (rule additive.intro, rule add_left)\n\nlemma zero_left: \"prod 0 b = 0\"\n  by (rule additive.zero [OF additive_left])\n\nlemma zero_right: \"prod a 0 = 0\"\n  by (rule additive.zero [OF additive_right])\n\nlemma minus_left: \"prod (- a) b = - prod a b\"\n  by (rule additive.minus [OF additive_left])\n\nlemma minus_right: \"prod a (- b) = - prod a b\"\n  by (rule additive.minus [OF additive_right])\n\nlemma diff_left: \"prod (a - a') b = prod a b - prod a' b\"\n  by (rule additive.diff [OF additive_left])\n\nlemma diff_right: \"prod a (b - b') = prod a b - prod a b'\"\n  by (rule additive.diff [OF additive_right])\n\nlemma sum_left: \"prod (sum g S) x = sum ((\\<lambda>i. prod (g i) x)) S\"\n  by (rule additive.sum [OF additive_left])\n\nlemma sum_right: \"prod x (sum g S) = sum ((\\<lambda>i. (prod x (g i)))) S\"\n  by (rule additive.sum [OF additive_right])\n\n\nlemma bounded_linear_left: \"bounded_linear (\\<lambda>a. a ** b)\"\n  apply (insert bounded)\n  apply safe\n  apply (rule_tac K=\"norm b * K\" in bounded_linear_intro)\n    apply (rule add_left)\n   apply (rule scaleR_left)\n  apply (simp add: ac_simps)\n  done\n\nlemma bounded_linear_right: \"bounded_linear (\\<lambda>b. a ** b)\"\n  apply (insert bounded)\n  apply safe\n  apply (rule_tac K=\"norm a * K\" in bounded_linear_intro)\n    apply (rule add_right)\n   apply (rule scaleR_right)\n  apply (simp add: ac_simps)\n  done\n\nlemma prod_diff_prod: \"(x ** y - a ** b) = (x - a) ** (y - b) + (x - a) ** b + a ** (y - b)\"\n  by (simp add: diff_left diff_right)\n\nlemma flip: \"bounded_bilinear (\\<lambda>x y. y ** x)\"\n  apply standard\n      apply (rule add_right)\n     apply (rule add_left)\n    apply (rule scaleR_right)\n   apply (rule scaleR_left)\n  apply (subst mult.commute)\n  apply (insert bounded)\n  apply blast\n  done\n\nlemma comp1:\n  assumes \"bounded_linear g\"\n  shows \"bounded_bilinear (\\<lambda>x. op ** (g x))\"\nproof unfold_locales\n  interpret g: bounded_linear g by fact\n  show \"\\<And>a a' b. g (a + a') ** b = g a ** b + g a' ** b\"\n    \"\\<And>a b b'. g a ** (b + b') = g a ** b + g a ** b'\"\n    \"\\<And>r a b. g (r *\\<^sub>R a) ** b = r *\\<^sub>R (g a ** b)\"\n    \"\\<And>a r b. g a ** (r *\\<^sub>R b) = r *\\<^sub>R (g a ** b)\"\n    by (auto simp: g.add add_left add_right g.scaleR scaleR_left scaleR_right)\n  from g.nonneg_bounded nonneg_bounded obtain K L\n    where nn: \"0 \\<le> K\" \"0 \\<le> L\"\n      and K: \"\\<And>x. norm (g x) \\<le> norm x * K\"\n      and L: \"\\<And>a b. norm (a ** b) \\<le> norm a * norm b * L\"\n    by auto\n  have \"norm (g a ** b) \\<le> norm a * K * norm b * L\" for a b\n    by (auto intro!:  order_trans[OF K] order_trans[OF L] mult_mono simp: nn)\n  then show \"\\<exists>K. \\<forall>a b. norm (g a ** b) \\<le> norm a * norm b * K\"\n    by (auto intro!: exI[where x=\"K * L\"] simp: ac_simps)\nqed\n\nlemma comp: \"bounded_linear f \\<Longrightarrow> bounded_linear g \\<Longrightarrow> bounded_bilinear (\\<lambda>x y. f x ** g y)\"\n  by (rule bounded_bilinear.flip[OF bounded_bilinear.comp1[OF bounded_bilinear.flip[OF comp1]]])\n\nend\n\nlemma bounded_linear_ident[simp]: \"bounded_linear (\\<lambda>x. x)\"\n  by standard (auto intro!: exI[of _ 1])\n\nlemma bounded_linear_zero[simp]: \"bounded_linear (\\<lambda>x. 0)\"\n  by standard (auto intro!: exI[of _ 1])\n\nlemma bounded_linear_add:\n  assumes \"bounded_linear f\"\n    and \"bounded_linear g\"\n  shows \"bounded_linear (\\<lambda>x. f x + g x)\"\nproof -\n  interpret f: bounded_linear f by fact\n  interpret g: bounded_linear g by fact\n  show ?thesis\n  proof\n    from f.bounded obtain Kf where Kf: \"norm (f x) \\<le> norm x * Kf\" for x\n      by blast\n    from g.bounded obtain Kg where Kg: \"norm (g x) \\<le> norm x * Kg\" for x\n      by blast\n    show \"\\<exists>K. \\<forall>x. norm (f x + g x) \\<le> norm x * K\"\n      using add_mono[OF Kf Kg]\n      by (intro exI[of _ \"Kf + Kg\"]) (auto simp: field_simps intro: norm_triangle_ineq order_trans)\n  qed (simp_all add: f.add g.add f.scaleR g.scaleR scaleR_right_distrib)\nqed\n\nlemma bounded_linear_minus:\n  assumes \"bounded_linear f\"\n  shows \"bounded_linear (\\<lambda>x. - f x)\"\nproof -\n  interpret f: bounded_linear f by fact\n  show ?thesis\n    apply unfold_locales\n      apply (simp add: f.add)\n     apply (simp add: f.scaleR)\n    apply (simp add: f.bounded)\n    done\nqed\n\nlemma bounded_linear_sub: \"bounded_linear f \\<Longrightarrow> bounded_linear g \\<Longrightarrow> bounded_linear (\\<lambda>x. f x - g x)\"\n  using bounded_linear_add[of f \"\\<lambda>x. - g x\"] bounded_linear_minus[of g]\n  by (auto simp add: algebra_simps)\n\nlemma bounded_linear_sum:\n  fixes f :: \"'i \\<Rightarrow> 'a::real_normed_vector \\<Rightarrow> 'b::real_normed_vector\"\n  shows \"(\\<And>i. i \\<in> I \\<Longrightarrow> bounded_linear (f i)) \\<Longrightarrow> bounded_linear (\\<lambda>x. \\<Sum>i\\<in>I. f i x)\"\n  by (induct I rule: infinite_finite_induct) (auto intro!: bounded_linear_add)\n\nlemma bounded_linear_compose:\n  assumes \"bounded_linear f\"\n    and \"bounded_linear g\"\n  shows \"bounded_linear (\\<lambda>x. f (g x))\"\nproof -\n  interpret f: bounded_linear f by fact\n  interpret g: bounded_linear g by fact\n  show ?thesis\n  proof unfold_locales\n    show \"f (g (x + y)) = f (g x) + f (g y)\" for x y\n      by (simp only: f.add g.add)\n    show \"f (g (scaleR r x)) = scaleR r (f (g x))\" for r x\n      by (simp only: f.scaleR g.scaleR)\n    from f.pos_bounded obtain Kf where f: \"\\<And>x. norm (f x) \\<le> norm x * Kf\" and Kf: \"0 < Kf\"\n      by blast\n    from g.pos_bounded obtain Kg where g: \"\\<And>x. norm (g x) \\<le> norm x * Kg\"\n      by blast\n    show \"\\<exists>K. \\<forall>x. norm (f (g x)) \\<le> norm x * K\"\n    proof (intro exI allI)\n      fix x\n      have \"norm (f (g x)) \\<le> norm (g x) * Kf\"\n        using f .\n      also have \"\\<dots> \\<le> (norm x * Kg) * Kf\"\n        using g Kf [THEN order_less_imp_le] by (rule mult_right_mono)\n      also have \"(norm x * Kg) * Kf = norm x * (Kg * Kf)\"\n        by (rule mult.assoc)\n      finally show \"norm (f (g x)) \\<le> norm x * (Kg * Kf)\" .\n    qed\n  qed\nqed\n\nlemma bounded_bilinear_mult: \"bounded_bilinear (op * :: 'a \\<Rightarrow> 'a \\<Rightarrow> 'a::real_normed_algebra)\"\n  apply (rule bounded_bilinear.intro)\n      apply (rule distrib_right)\n     apply (rule distrib_left)\n    apply (rule mult_scaleR_left)\n   apply (rule mult_scaleR_right)\n  apply (rule_tac x=\"1\" in exI)\n  apply (simp add: norm_mult_ineq)\n  done\n\nlemma bounded_linear_mult_left: \"bounded_linear (\\<lambda>x::'a::real_normed_algebra. x * y)\"\n  using bounded_bilinear_mult\n  by (rule bounded_bilinear.bounded_linear_left)\n\nlemma bounded_linear_mult_right: \"bounded_linear (\\<lambda>y::'a::real_normed_algebra. x * y)\"\n  using bounded_bilinear_mult\n  by (rule bounded_bilinear.bounded_linear_right)\n\nlemmas bounded_linear_mult_const =\n  bounded_linear_mult_left [THEN bounded_linear_compose]\n\nlemmas bounded_linear_const_mult =\n  bounded_linear_mult_right [THEN bounded_linear_compose]\n\nlemma bounded_linear_divide: \"bounded_linear (\\<lambda>x. x / y)\"\n  for y :: \"'a::real_normed_field\"\n  unfolding divide_inverse by (rule bounded_linear_mult_left)\n\nlemma bounded_bilinear_scaleR: \"bounded_bilinear scaleR\"\n  apply (rule bounded_bilinear.intro)\n      apply (rule scaleR_left_distrib)\n     apply (rule scaleR_right_distrib)\n    apply simp\n   apply (rule scaleR_left_commute)\n  apply (rule_tac x=\"1\" in exI)\n  apply simp\n  done\n\nlemma bounded_linear_scaleR_left: \"bounded_linear (\\<lambda>r. scaleR r x)\"\n  using bounded_bilinear_scaleR\n  by (rule bounded_bilinear.bounded_linear_left)\n\nlemma bounded_linear_scaleR_right: \"bounded_linear (\\<lambda>x. scaleR r x)\"\n  using bounded_bilinear_scaleR\n  by (rule bounded_bilinear.bounded_linear_right)\n\nlemmas bounded_linear_scaleR_const =\n  bounded_linear_scaleR_left[THEN bounded_linear_compose]\n\nlemmas bounded_linear_const_scaleR =\n  bounded_linear_scaleR_right[THEN bounded_linear_compose]\n\nlemma bounded_linear_of_real: \"bounded_linear (\\<lambda>r. of_real r)\"\n  unfolding of_real_def by (rule bounded_linear_scaleR_left)\n\nlemma real_bounded_linear: \"bounded_linear f \\<longleftrightarrow> (\\<exists>c::real. f = (\\<lambda>x. x * c))\"\n  for f :: \"real \\<Rightarrow> real\"\nproof -\n  {\n    fix x\n    assume \"bounded_linear f\"\n    then interpret bounded_linear f .\n    from scaleR[of x 1] have \"f x = x * f 1\"\n      by simp\n  }\n  then show ?thesis\n    by (auto intro: exI[of _ \"f 1\"] bounded_linear_mult_left)\nqed\n\nlemma bij_linear_imp_inv_linear: \"linear f \\<Longrightarrow> bij f \\<Longrightarrow> linear (inv f)\"\n  by (auto simp: linear_def linear_axioms_def additive_def bij_is_surj bij_is_inj surj_f_inv_f\n      intro!:  Hilbert_Choice.inv_f_eq)\n\ninstance real_normed_algebra_1 \\<subseteq> perfect_space\nproof\n  show \"\\<not> open {x}\" for x :: 'a\n    apply (simp only: open_dist dist_norm)\n    apply clarsimp\n    apply (rule_tac x = \"x + of_real (e/2)\" in exI)\n    apply simp\n    done\nqed\n\n\nsubsection \\<open>Filters and Limits on Metric Space\\<close>\n\nlemma (in metric_space) nhds_metric: \"nhds x = (INF e:{0 <..}. principal {y. dist y x < e})\"\n  unfolding nhds_def\nproof (safe intro!: INF_eq)\n  fix S\n  assume \"open S\" \"x \\<in> S\"\n  then obtain e where \"{y. dist y x < e} \\<subseteq> S\" \"0 < e\"\n    by (auto simp: open_dist subset_eq)\n  then show \"\\<exists>e\\<in>{0<..}. principal {y. dist y x < e} \\<le> principal S\"\n    by auto\nqed (auto intro!: exI[of _ \"{y. dist x y < e}\" for e] open_ball simp: dist_commute)\n\nlemma (in metric_space) tendsto_iff: \"(f \\<longlongrightarrow> l) F \\<longleftrightarrow> (\\<forall>e>0. eventually (\\<lambda>x. dist (f x) l < e) F)\"\n  unfolding nhds_metric filterlim_INF filterlim_principal by auto\n\nlemma (in metric_space) tendstoI [intro?]:\n  \"(\\<And>e. 0 < e \\<Longrightarrow> eventually (\\<lambda>x. dist (f x) l < e) F) \\<Longrightarrow> (f \\<longlongrightarrow> l) F\"\n  by (auto simp: tendsto_iff)\n\nlemma (in metric_space) tendstoD: \"(f \\<longlongrightarrow> l) F \\<Longrightarrow> 0 < e \\<Longrightarrow> eventually (\\<lambda>x. dist (f x) l < e) F\"\n  by (auto simp: tendsto_iff)\n\nlemma (in metric_space) eventually_nhds_metric:\n  \"eventually P (nhds a) \\<longleftrightarrow> (\\<exists>d>0. \\<forall>x. dist x a < d \\<longrightarrow> P x)\"\n  unfolding nhds_metric\n  by (subst eventually_INF_base)\n     (auto simp: eventually_principal Bex_def subset_eq intro: exI[of _ \"min a b\" for a b])\n\nlemma eventually_at: \"eventually P (at a within S) \\<longleftrightarrow> (\\<exists>d>0. \\<forall>x\\<in>S. x \\<noteq> a \\<and> dist x a < d \\<longrightarrow> P x)\"\n  for a :: \"'a :: metric_space\"\n  by (auto simp: eventually_at_filter eventually_nhds_metric)\n\nlemma eventually_at_le: \"eventually P (at a within S) \\<longleftrightarrow> (\\<exists>d>0. \\<forall>x\\<in>S. x \\<noteq> a \\<and> dist x a \\<le> d \\<longrightarrow> P x)\"\n  for a :: \"'a::metric_space\"\n  apply (simp only: eventually_at_filter eventually_nhds_metric)\n  apply auto\n  apply (rule_tac x=\"d / 2\" in exI)\n  apply auto\n  done\n\nlemma eventually_at_left_real: \"a > (b :: real) \\<Longrightarrow> eventually (\\<lambda>x. x \\<in> {b<..<a}) (at_left a)\"\n  by (subst eventually_at, rule exI[of _ \"a - b\"]) (force simp: dist_real_def)\n\nlemma eventually_at_right_real: \"a < (b :: real) \\<Longrightarrow> eventually (\\<lambda>x. x \\<in> {a<..<b}) (at_right a)\"\n  by (subst eventually_at, rule exI[of _ \"b - a\"]) (force simp: dist_real_def)\n\nlemma metric_tendsto_imp_tendsto:\n  fixes a :: \"'a :: metric_space\"\n    and b :: \"'b :: metric_space\"\n  assumes f: \"(f \\<longlongrightarrow> a) F\"\n    and le: \"eventually (\\<lambda>x. dist (g x) b \\<le> dist (f x) a) F\"\n  shows \"(g \\<longlongrightarrow> b) F\"\nproof (rule tendstoI)\n  fix e :: real\n  assume \"0 < e\"\n  with f have \"eventually (\\<lambda>x. dist (f x) a < e) F\" by (rule tendstoD)\n  with le show \"eventually (\\<lambda>x. dist (g x) b < e) F\"\n    using le_less_trans by (rule eventually_elim2)\nqed\n\nlemma filterlim_real_sequentially: \"LIM x sequentially. real x :> at_top\"\n  apply (simp only: filterlim_at_top)\n  apply (intro allI)\n  apply (rule_tac c=\"nat \\<lceil>Z + 1\\<rceil>\" in eventually_sequentiallyI)\n  apply linarith\n  done\n\nlemma filterlim_nat_sequentially: \"filterlim nat sequentially at_top\"\n  unfolding filterlim_at_top\n  apply (rule allI)\n  subgoal for Z by (auto intro!: eventually_at_top_linorderI[where c=\"int Z\"])\n  done\n\nlemma filterlim_floor_sequentially: \"filterlim floor at_top at_top\"\n  unfolding filterlim_at_top\n  apply (rule allI)\n  subgoal for Z by (auto simp: le_floor_iff intro!: eventually_at_top_linorderI[where c=\"of_int Z\"])\n  done\n\nlemma filterlim_sequentially_iff_filterlim_real:\n  \"filterlim f sequentially F \\<longleftrightarrow> filterlim (\\<lambda>x. real (f x)) at_top F\"\n  apply (rule iffI)\n  subgoal using filterlim_compose filterlim_real_sequentially by blast\n  subgoal premises prems\n  proof -\n    have \"filterlim (\\<lambda>x. nat (floor (real (f x)))) sequentially F\"\n      by (intro filterlim_compose[OF filterlim_nat_sequentially]\n          filterlim_compose[OF filterlim_floor_sequentially] prems)\n    then show ?thesis by simp\n  qed\n  done\n\n\nsubsubsection \\<open>Limits of Sequences\\<close>\n\nlemma lim_sequentially: \"X \\<longlonglongrightarrow> L \\<longleftrightarrow> (\\<forall>r>0. \\<exists>no. \\<forall>n\\<ge>no. dist (X n) L < r)\"\n  for L :: \"'a::metric_space\"\n  unfolding tendsto_iff eventually_sequentially ..\n\nlemmas LIMSEQ_def = lim_sequentially  (*legacy binding*)\n\nlemma LIMSEQ_iff_nz: \"X \\<longlonglongrightarrow> L \\<longleftrightarrow> (\\<forall>r>0. \\<exists>no>0. \\<forall>n\\<ge>no. dist (X n) L < r)\"\n  for L :: \"'a::metric_space\"\n  unfolding lim_sequentially by (metis Suc_leD zero_less_Suc)\n\nlemma metric_LIMSEQ_I: \"(\\<And>r. 0 < r \\<Longrightarrow> \\<exists>no. \\<forall>n\\<ge>no. dist (X n) L < r) \\<Longrightarrow> X \\<longlonglongrightarrow> L\"\n  for L :: \"'a::metric_space\"\n  by (simp add: lim_sequentially)\n\nlemma metric_LIMSEQ_D: \"X \\<longlonglongrightarrow> L \\<Longrightarrow> 0 < r \\<Longrightarrow> \\<exists>no. \\<forall>n\\<ge>no. dist (X n) L < r\"\n  for L :: \"'a::metric_space\"\n  by (simp add: lim_sequentially)\n\n\nsubsubsection \\<open>Limits of Functions\\<close>\n\nlemma LIM_def: \"f \\<midarrow>a\\<rightarrow> L \\<longleftrightarrow> (\\<forall>r > 0. \\<exists>s > 0. \\<forall>x. x \\<noteq> a \\<and> dist x a < s \\<longrightarrow> dist (f x) L < r)\"\n  for a :: \"'a::metric_space\" and L :: \"'b::metric_space\"\n  unfolding tendsto_iff eventually_at by simp\n\nlemma metric_LIM_I:\n  \"(\\<And>r. 0 < r \\<Longrightarrow> \\<exists>s>0. \\<forall>x. x \\<noteq> a \\<and> dist x a < s \\<longrightarrow> dist (f x) L < r) \\<Longrightarrow> f \\<midarrow>a\\<rightarrow> L\"\n  for a :: \"'a::metric_space\" and L :: \"'b::metric_space\"\n  by (simp add: LIM_def)\n\nlemma metric_LIM_D: \"f \\<midarrow>a\\<rightarrow> L \\<Longrightarrow> 0 < r \\<Longrightarrow> \\<exists>s>0. \\<forall>x. x \\<noteq> a \\<and> dist x a < s \\<longrightarrow> dist (f x) L < r\"\n  for a :: \"'a::metric_space\" and L :: \"'b::metric_space\"\n  by (simp add: LIM_def)\n\nlemma metric_LIM_imp_LIM:\n  fixes l :: \"'a::metric_space\"\n    and m :: \"'b::metric_space\"\n  assumes f: \"f \\<midarrow>a\\<rightarrow> l\"\n    and le: \"\\<And>x. x \\<noteq> a \\<Longrightarrow> dist (g x) m \\<le> dist (f x) l\"\n  shows \"g \\<midarrow>a\\<rightarrow> m\"\n  by (rule metric_tendsto_imp_tendsto [OF f]) (auto simp add: eventually_at_topological le)\n\nlemma metric_LIM_equal2:\n  fixes a :: \"'a::metric_space\"\n  assumes \"0 < R\"\n    and \"\\<And>x. x \\<noteq> a \\<Longrightarrow> dist x a < R \\<Longrightarrow> f x = g x\"\n  shows \"g \\<midarrow>a\\<rightarrow> l \\<Longrightarrow> f \\<midarrow>a\\<rightarrow> l\"\n  apply (rule topological_tendstoI)\n  apply (drule (2) topological_tendstoD)\n  apply (simp add: eventually_at)\n  apply safe\n  apply (rule_tac x=\"min d R\" in exI)\n  apply safe\n   apply (simp add: assms(1))\n  apply (simp add: assms(2))\n  done\n\nlemma metric_LIM_compose2:\n  fixes a :: \"'a::metric_space\"\n  assumes f: \"f \\<midarrow>a\\<rightarrow> b\"\n    and g: \"g \\<midarrow>b\\<rightarrow> c\"\n    and inj: \"\\<exists>d>0. \\<forall>x. x \\<noteq> a \\<and> dist x a < d \\<longrightarrow> f x \\<noteq> b\"\n  shows \"(\\<lambda>x. g (f x)) \\<midarrow>a\\<rightarrow> c\"\n  using inj by (intro tendsto_compose_eventually[OF g f]) (auto simp: eventually_at)\n\nlemma metric_isCont_LIM_compose2:\n  fixes f :: \"'a :: metric_space \\<Rightarrow> _\"\n  assumes f [unfolded isCont_def]: \"isCont f a\"\n    and g: \"g \\<midarrow>f a\\<rightarrow> l\"\n    and inj: \"\\<exists>d>0. \\<forall>x. x \\<noteq> a \\<and> dist x a < d \\<longrightarrow> f x \\<noteq> f a\"\n  shows \"(\\<lambda>x. g (f x)) \\<midarrow>a\\<rightarrow> l\"\n  by (rule metric_LIM_compose2 [OF f g inj])\n\n\nsubsection \\<open>Complete metric spaces\\<close>\n\nsubsection \\<open>Cauchy sequences\\<close>\n\nlemma (in metric_space) Cauchy_def: \"Cauchy X = (\\<forall>e>0. \\<exists>M. \\<forall>m\\<ge>M. \\<forall>n\\<ge>M. dist (X m) (X n) < e)\"\nproof -\n  have *: \"eventually P (INF M. principal {(X m, X n) | n m. m \\<ge> M \\<and> n \\<ge> M}) \\<longleftrightarrow>\n    (\\<exists>M. \\<forall>m\\<ge>M. \\<forall>n\\<ge>M. P (X m, X n))\" for P\n    apply (subst eventually_INF_base)\n    subgoal by simp\n    subgoal for a b\n      by (intro bexI[of _ \"max a b\"]) (auto simp: eventually_principal subset_eq)\n    subgoal by (auto simp: eventually_principal, blast)\n    done\n  have \"Cauchy X \\<longleftrightarrow> (INF M. principal {(X m, X n) | n m. m \\<ge> M \\<and> n \\<ge> M}) \\<le> uniformity\"\n    unfolding Cauchy_uniform_iff le_filter_def * ..\n  also have \"\\<dots> = (\\<forall>e>0. \\<exists>M. \\<forall>m\\<ge>M. \\<forall>n\\<ge>M. dist (X m) (X n) < e)\"\n    unfolding uniformity_dist le_INF_iff by (auto simp: * le_principal)\n  finally show ?thesis .\nqed\n\nlemma (in metric_space) Cauchy_altdef: \"Cauchy f \\<longleftrightarrow> (\\<forall>e>0. \\<exists>M. \\<forall>m\\<ge>M. \\<forall>n>m. dist (f m) (f n) < e)\"\n  (is \"?lhs \\<longleftrightarrow> ?rhs\")\nproof\n  assume ?rhs\n  show ?lhs\n    unfolding Cauchy_def\n  proof (intro allI impI)\n    fix e :: real assume e: \"e > 0\"\n    with \\<open>?rhs\\<close> obtain M where M: \"m \\<ge> M \\<Longrightarrow> n > m \\<Longrightarrow> dist (f m) (f n) < e\" for m n\n      by blast\n    have \"dist (f m) (f n) < e\" if \"m \\<ge> M\" \"n \\<ge> M\" for m n\n      using M[of m n] M[of n m] e that by (cases m n rule: linorder_cases) (auto simp: dist_commute)\n    then show \"\\<exists>M. \\<forall>m\\<ge>M. \\<forall>n\\<ge>M. dist (f m) (f n) < e\"\n      by blast\n  qed\nnext\n  assume ?lhs\n  show ?rhs\n  proof (intro allI impI)\n    fix e :: real\n    assume e: \"e > 0\"\n    with \\<open>Cauchy f\\<close> obtain M where \"\\<And>m n. m \\<ge> M \\<Longrightarrow> n \\<ge> M \\<Longrightarrow> dist (f m) (f n) < e\"\n      unfolding Cauchy_def by blast\n    then show \"\\<exists>M. \\<forall>m\\<ge>M. \\<forall>n>m. dist (f m) (f n) < e\"\n      by (intro exI[of _ M]) force\n  qed\nqed\n\nlemma (in metric_space) metric_CauchyI:\n  \"(\\<And>e. 0 < e \\<Longrightarrow> \\<exists>M. \\<forall>m\\<ge>M. \\<forall>n\\<ge>M. dist (X m) (X n) < e) \\<Longrightarrow> Cauchy X\"\n  by (simp add: Cauchy_def)\n\nlemma (in metric_space) CauchyI':\n  \"(\\<And>e. 0 < e \\<Longrightarrow> \\<exists>M. \\<forall>m\\<ge>M. \\<forall>n>m. dist (X m) (X n) < e) \\<Longrightarrow> Cauchy X\"\n  unfolding Cauchy_altdef by blast\n\nlemma (in metric_space) metric_CauchyD:\n  \"Cauchy X \\<Longrightarrow> 0 < e \\<Longrightarrow> \\<exists>M. \\<forall>m\\<ge>M. \\<forall>n\\<ge>M. dist (X m) (X n) < e\"\n  by (simp add: Cauchy_def)\n\nlemma (in metric_space) metric_Cauchy_iff2:\n  \"Cauchy X = (\\<forall>j. (\\<exists>M. \\<forall>m \\<ge> M. \\<forall>n \\<ge> M. dist (X m) (X n) < inverse(real (Suc j))))\"\n  apply (simp add: Cauchy_def)\n  apply auto\n  apply (drule reals_Archimedean)\n  apply safe\n  apply (drule_tac x = n in spec)\n  apply auto\n  apply (rule_tac x = M in exI)\n  apply auto\n  apply (drule_tac x = m in spec)\n  apply simp\n  apply (drule_tac x = na in spec)\n  apply auto\n  done\n\nlemma Cauchy_iff2: \"Cauchy X \\<longleftrightarrow> (\\<forall>j. (\\<exists>M. \\<forall>m \\<ge> M. \\<forall>n \\<ge> M. \\<bar>X m - X n\\<bar> < inverse (real (Suc j))))\"\n  by (simp only: metric_Cauchy_iff2 dist_real_def)\n\nlemma lim_1_over_n: \"((\\<lambda>n. 1 / of_nat n) \\<longlongrightarrow> (0::'a::real_normed_field)) sequentially\"\nproof (subst lim_sequentially, intro allI impI exI)\n  fix e :: real\n  assume e: \"e > 0\"\n  fix n :: nat\n  assume n: \"n \\<ge> nat \\<lceil>inverse e + 1\\<rceil>\"\n  have \"inverse e < of_nat (nat \\<lceil>inverse e + 1\\<rceil>)\" by linarith\n  also note n\n  finally show \"dist (1 / of_nat n :: 'a) 0 < e\"\n    using e by (simp add: divide_simps mult.commute norm_divide)\nqed\n\nlemma (in metric_space) complete_def:\n  shows \"complete S = (\\<forall>f. (\\<forall>n. f n \\<in> S) \\<and> Cauchy f \\<longrightarrow> (\\<exists>l\\<in>S. f \\<longlonglongrightarrow> l))\"\n  unfolding complete_uniform\nproof safe\n  fix f :: \"nat \\<Rightarrow> 'a\"\n  assume f: \"\\<forall>n. f n \\<in> S\" \"Cauchy f\"\n    and *: \"\\<forall>F\\<le>principal S. F \\<noteq> bot \\<longrightarrow> cauchy_filter F \\<longrightarrow> (\\<exists>x\\<in>S. F \\<le> nhds x)\"\n  then show \"\\<exists>l\\<in>S. f \\<longlonglongrightarrow> l\"\n    unfolding filterlim_def using f\n    by (intro *[rule_format])\n       (auto simp: filtermap_sequentually_ne_bot le_principal eventually_filtermap Cauchy_uniform)\nnext\n  fix F :: \"'a filter\"\n  assume \"F \\<le> principal S\" \"F \\<noteq> bot\" \"cauchy_filter F\"\n  assume seq: \"\\<forall>f. (\\<forall>n. f n \\<in> S) \\<and> Cauchy f \\<longrightarrow> (\\<exists>l\\<in>S. f \\<longlonglongrightarrow> l)\"\n\n  from \\<open>F \\<le> principal S\\<close> \\<open>cauchy_filter F\\<close>\n  have FF_le: \"F \\<times>\\<^sub>F F \\<le> uniformity_on S\"\n    by (simp add: cauchy_filter_def principal_prod_principal[symmetric] prod_filter_mono)\n\n  let ?P = \"\\<lambda>P e. eventually P F \\<and> (\\<forall>x. P x \\<longrightarrow> x \\<in> S) \\<and> (\\<forall>x y. P x \\<longrightarrow> P y \\<longrightarrow> dist x y < e)\"\n  have P: \"\\<exists>P. ?P P \\<epsilon>\" if \"0 < \\<epsilon>\" for \\<epsilon> :: real\n  proof -\n    from that have \"eventually (\\<lambda>(x, y). x \\<in> S \\<and> y \\<in> S \\<and> dist x y < \\<epsilon>) (uniformity_on S)\"\n      by (auto simp: eventually_inf_principal eventually_uniformity_metric)\n    from filter_leD[OF FF_le this] show ?thesis\n      by (auto simp: eventually_prod_same)\n  qed\n\n  have \"\\<exists>P. \\<forall>n. ?P (P n) (1 / Suc n) \\<and> P (Suc n) \\<le> P n\"\n  proof (rule dependent_nat_choice)\n    show \"\\<exists>P. ?P P (1 / Suc 0)\"\n      using P[of 1] by auto\n  next\n    fix P n assume \"?P P (1/Suc n)\"\n    moreover obtain Q where \"?P Q (1 / Suc (Suc n))\"\n      using P[of \"1/Suc (Suc n)\"] by auto\n    ultimately show \"\\<exists>Q. ?P Q (1 / Suc (Suc n)) \\<and> Q \\<le> P\"\n      by (intro exI[of _ \"\\<lambda>x. P x \\<and> Q x\"]) (auto simp: eventually_conj_iff)\n  qed\n  then obtain P where P: \"eventually (P n) F\" \"P n x \\<Longrightarrow> x \\<in> S\"\n    \"P n x \\<Longrightarrow> P n y \\<Longrightarrow> dist x y < 1 / Suc n\" \"P (Suc n) \\<le> P n\"\n    for n x y\n    by metis\n  have \"antimono P\"\n    using P(4) unfolding decseq_Suc_iff le_fun_def by blast\n\n  obtain X where X: \"P n (X n)\" for n\n    using P(1)[THEN eventually_happens'[OF \\<open>F \\<noteq> bot\\<close>]] by metis\n  have \"Cauchy X\"\n    unfolding metric_Cauchy_iff2 inverse_eq_divide\n  proof (intro exI allI impI)\n    fix j m n :: nat\n    assume \"j \\<le> m\" \"j \\<le> n\"\n    with \\<open>antimono P\\<close> X have \"P j (X m)\" \"P j (X n)\"\n      by (auto simp: antimono_def)\n    then show \"dist (X m) (X n) < 1 / Suc j\"\n      by (rule P)\n  qed\n  moreover have \"\\<forall>n. X n \\<in> S\"\n    using P(2) X by auto\n  ultimately obtain x where \"X \\<longlonglongrightarrow> x\" \"x \\<in> S\"\n    using seq by blast\n\n  show \"\\<exists>x\\<in>S. F \\<le> nhds x\"\n  proof (rule bexI)\n    have \"eventually (\\<lambda>y. dist y x < e) F\" if \"0 < e\" for e :: real\n    proof -\n      from that have \"(\\<lambda>n. 1 / Suc n :: real) \\<longlonglongrightarrow> 0 \\<and> 0 < e / 2\"\n        by (subst LIMSEQ_Suc_iff) (auto intro!: lim_1_over_n)\n      then have \"\\<forall>\\<^sub>F n in sequentially. dist (X n) x < e / 2 \\<and> 1 / Suc n < e / 2\"\n        using \\<open>X \\<longlonglongrightarrow> x\\<close>\n        unfolding tendsto_iff order_tendsto_iff[where 'a=real] eventually_conj_iff\n        by blast\n      then obtain n where \"dist x (X n) < e / 2\" \"1 / Suc n < e / 2\"\n        by (auto simp: eventually_sequentially dist_commute)\n      show ?thesis\n        using \\<open>eventually (P n) F\\<close>\n      proof eventually_elim\n        case (elim y)\n        then have \"dist y (X n) < 1 / Suc n\"\n          by (intro X P)\n        also have \"\\<dots> < e / 2\" by fact\n        finally show \"dist y x < e\"\n          by (rule dist_triangle_half_l) fact\n      qed\n    qed\n    then show \"F \\<le> nhds x\"\n      unfolding nhds_metric le_INF_iff le_principal by auto\n  qed fact\nqed\n\nlemma (in metric_space) totally_bounded_metric:\n  \"totally_bounded S \\<longleftrightarrow> (\\<forall>e>0. \\<exists>k. finite k \\<and> S \\<subseteq> (\\<Union>x\\<in>k. {y. dist x y < e}))\"\n  apply (simp only: totally_bounded_def eventually_uniformity_metric imp_ex)\n  apply (subst all_comm)\n  apply (intro arg_cong[where f=All] ext)\n  apply safe\n  subgoal for e\n    apply (erule allE[of _ \"\\<lambda>(x, y). dist x y < e\"])\n    apply auto\n    done\n  subgoal for e P k\n    apply (intro exI[of _ k])\n    apply (force simp: subset_eq)\n    done\n  done\n\n\nsubsubsection \\<open>Cauchy Sequences are Convergent\\<close>\n\n(* TODO: update to uniform_space *)\nclass complete_space = metric_space +\n  assumes Cauchy_convergent: \"Cauchy X \\<Longrightarrow> convergent X\"\n\nlemma Cauchy_convergent_iff: \"Cauchy X \\<longleftrightarrow> convergent X\"\n  for X :: \"nat \\<Rightarrow> 'a::complete_space\"\n  by (blast intro: Cauchy_convergent convergent_Cauchy)\n\n\nsubsection \\<open>The set of real numbers is a complete metric space\\<close>\n\ntext \\<open>\n  Proof that Cauchy sequences converge based on the one from\n  \\<^url>\\<open>http://pirate.shu.edu/~wachsmut/ira/numseq/proofs/cauconv.html\\<close>\n\\<close>\n\ntext \\<open>\n  If sequence @{term \"X\"} is Cauchy, then its limit is the lub of\n  @{term \"{r::real. \\<exists>N. \\<forall>n\\<ge>N. r < X n}\"}\n\\<close>\nlemma increasing_LIMSEQ:\n  fixes f :: \"nat \\<Rightarrow> real\"\n  assumes inc: \"\\<And>n. f n \\<le> f (Suc n)\"\n    and bdd: \"\\<And>n. f n \\<le> l\"\n    and en: \"\\<And>e. 0 < e \\<Longrightarrow> \\<exists>n. l \\<le> f n + e\"\n  shows \"f \\<longlonglongrightarrow> l\"\nproof (rule increasing_tendsto)\n  fix x\n  assume \"x < l\"\n  with dense[of 0 \"l - x\"] obtain e where \"0 < e\" \"e < l - x\"\n    by auto\n  from en[OF \\<open>0 < e\\<close>] obtain n where \"l - e \\<le> f n\"\n    by (auto simp: field_simps)\n  with \\<open>e < l - x\\<close> \\<open>0 < e\\<close> have \"x < f n\"\n    by simp\n  with incseq_SucI[of f, OF inc] show \"eventually (\\<lambda>n. x < f n) sequentially\"\n    by (auto simp: eventually_sequentially incseq_def intro: less_le_trans)\nqed (use bdd in auto)\n\nlemma real_Cauchy_convergent:\n  fixes X :: \"nat \\<Rightarrow> real\"\n  assumes X: \"Cauchy X\"\n  shows \"convergent X\"\nproof -\n  define S :: \"real set\" where \"S = {x. \\<exists>N. \\<forall>n\\<ge>N. x < X n}\"\n  then have mem_S: \"\\<And>N x. \\<forall>n\\<ge>N. x < X n \\<Longrightarrow> x \\<in> S\"\n    by auto\n\n  have bound_isUb: \"y \\<le> x\" if N: \"\\<forall>n\\<ge>N. X n < x\" and \"y \\<in> S\" for N and x y :: real\n  proof -\n    from that have \"\\<exists>M. \\<forall>n\\<ge>M. y < X n\"\n      by (simp add: S_def)\n    then obtain M where \"\\<forall>n\\<ge>M. y < X n\" ..\n    then have \"y < X (max M N)\" by simp\n    also have \"\\<dots> < x\" using N by simp\n    finally show ?thesis by (rule order_less_imp_le)\n  qed\n\n  obtain N where \"\\<forall>m\\<ge>N. \\<forall>n\\<ge>N. dist (X m) (X n) < 1\"\n    using X[THEN metric_CauchyD, OF zero_less_one] by auto\n  then have N: \"\\<forall>n\\<ge>N. dist (X n) (X N) < 1\" by simp\n  have [simp]: \"S \\<noteq> {}\"\n  proof (intro exI ex_in_conv[THEN iffD1])\n    from N have \"\\<forall>n\\<ge>N. X N - 1 < X n\"\n      by (simp add: abs_diff_less_iff dist_real_def)\n    then show \"X N - 1 \\<in> S\" by (rule mem_S)\n  qed\n  have [simp]: \"bdd_above S\"\n  proof\n    from N have \"\\<forall>n\\<ge>N. X n < X N + 1\"\n      by (simp add: abs_diff_less_iff dist_real_def)\n    then show \"\\<And>s. s \\<in> S \\<Longrightarrow>  s \\<le> X N + 1\"\n      by (rule bound_isUb)\n  qed\n  have \"X \\<longlonglongrightarrow> Sup S\"\n  proof (rule metric_LIMSEQ_I)\n    fix r :: real\n    assume \"0 < r\"\n    then have r: \"0 < r/2\" by simp\n    obtain N where \"\\<forall>n\\<ge>N. \\<forall>m\\<ge>N. dist (X n) (X m) < r/2\"\n      using metric_CauchyD [OF X r] by auto\n    then have \"\\<forall>n\\<ge>N. dist (X n) (X N) < r/2\" by simp\n    then have N: \"\\<forall>n\\<ge>N. X N - r/2 < X n \\<and> X n < X N + r/2\"\n      by (simp only: dist_real_def abs_diff_less_iff)\n\n    from N have \"\\<forall>n\\<ge>N. X N - r/2 < X n\" by blast\n    then have \"X N - r/2 \\<in> S\" by (rule mem_S)\n    then have 1: \"X N - r/2 \\<le> Sup S\" by (simp add: cSup_upper)\n\n    from N have \"\\<forall>n\\<ge>N. X n < X N + r/2\" by blast\n    from bound_isUb[OF this]\n    have 2: \"Sup S \\<le> X N + r/2\"\n      by (intro cSup_least) simp_all\n\n    show \"\\<exists>N. \\<forall>n\\<ge>N. dist (X n) (Sup S) < r\"\n    proof (intro exI allI impI)\n      fix n\n      assume n: \"N \\<le> n\"\n      from N n have \"X n < X N + r/2\" and \"X N - r/2 < X n\"\n        by simp_all\n      then show \"dist (X n) (Sup S) < r\" using 1 2\n        by (simp add: abs_diff_less_iff dist_real_def)\n    qed\n  qed\n  then show ?thesis by (auto simp: convergent_def)\nqed\n\ninstance real :: complete_space\n  by intro_classes (rule real_Cauchy_convergent)\n\nclass banach = real_normed_vector + complete_space\n\ninstance real :: banach ..\n\nlemma tendsto_at_topI_sequentially:\n  fixes f :: \"real \\<Rightarrow> 'b::first_countable_topology\"\n  assumes *: \"\\<And>X. filterlim X at_top sequentially \\<Longrightarrow> (\\<lambda>n. f (X n)) \\<longlonglongrightarrow> y\"\n  shows \"(f \\<longlongrightarrow> y) at_top\"\nproof -\n  obtain A where A: \"decseq A\" \"open (A n)\" \"y \\<in> A n\" \"nhds y = (INF n. principal (A n))\" for n\n    by (rule nhds_countable[of y]) (rule that)\n\n  have \"\\<forall>m. \\<exists>k. \\<forall>x\\<ge>k. f x \\<in> A m\"\n  proof (rule ccontr)\n    assume \"\\<not> (\\<forall>m. \\<exists>k. \\<forall>x\\<ge>k. f x \\<in> A m)\"\n    then obtain m where \"\\<And>k. \\<exists>x\\<ge>k. f x \\<notin> A m\"\n      by auto\n    then have \"\\<exists>X. \\<forall>n. (f (X n) \\<notin> A m) \\<and> max n (X n) + 1 \\<le> X (Suc n)\"\n      by (intro dependent_nat_choice) (auto simp del: max.bounded_iff)\n    then obtain X where X: \"\\<And>n. f (X n) \\<notin> A m\" \"\\<And>n. max n (X n) + 1 \\<le> X (Suc n)\"\n      by auto\n    have \"1 \\<le> n \\<Longrightarrow> real n \\<le> X n\" for n\n      using X[of \"n - 1\"] by auto\n    then have \"filterlim X at_top sequentially\"\n      by (force intro!: filterlim_at_top_mono[OF filterlim_real_sequentially]\n          simp: eventually_sequentially)\n    from topological_tendstoD[OF *[OF this] A(2, 3), of m] X(1) show False\n      by auto\n  qed\n  then obtain k where \"k m \\<le> x \\<Longrightarrow> f x \\<in> A m\" for m x\n    by metis\n  then show ?thesis\n    unfolding at_top_def A by (intro filterlim_base[where i=k]) auto\nqed\n\nlemma tendsto_at_topI_sequentially_real:\n  fixes f :: \"real \\<Rightarrow> real\"\n  assumes mono: \"mono f\"\n    and limseq: \"(\\<lambda>n. f (real n)) \\<longlonglongrightarrow> y\"\n  shows \"(f \\<longlongrightarrow> y) at_top\"\nproof (rule tendstoI)\n  fix e :: real\n  assume \"0 < e\"\n  with limseq obtain N :: nat where N: \"N \\<le> n \\<Longrightarrow> \\<bar>f (real n) - y\\<bar> < e\" for n\n    by (auto simp: lim_sequentially dist_real_def)\n  have le: \"f x \\<le> y\" for x :: real\n  proof -\n    obtain n where \"x \\<le> real_of_nat n\"\n      using real_arch_simple[of x] ..\n    note monoD[OF mono this]\n    also have \"f (real_of_nat n) \\<le> y\"\n      by (rule LIMSEQ_le_const[OF limseq]) (auto intro!: exI[of _ n] monoD[OF mono])\n    finally show ?thesis .\n  qed\n  have \"eventually (\\<lambda>x. real N \\<le> x) at_top\"\n    by (rule eventually_ge_at_top)\n  then show \"eventually (\\<lambda>x. dist (f x) y < e) at_top\"\n  proof eventually_elim\n    case (elim x)\n    with N[of N] le have \"y - f (real N) < e\" by auto\n    moreover note monoD[OF mono elim]\n    ultimately show \"dist (f x) y < e\"\n      using le[of x] by (auto simp: dist_real_def field_simps)\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/Real_Vector_Spaces.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127566694178, "lm_q2_score": 0.8479677583778258, "lm_q1q2_score": 0.724090486123196}}
{"text": "(*  Title:      HOL/Analysis/Derivative.thy\n    Author:     John Harrison\n    Author:     Robert Himmelmann, TU Muenchen (translation from HOL Light); tidied by LCP\n*)\n\nsection \\<open>Derivative\\<close>\n\ntheory Derivative\n  imports\n    Bounded_Linear_Function\n    Line_Segment\n    Convex_Euclidean_Space\nbegin\n\ndeclare bounded_linear_inner_left [intro]\n\ndeclare has_derivative_bounded_linear[dest]\n\nsubsection \\<open>Derivatives\\<close>\n\nlemma has_derivative_add_const:\n  \"(f has_derivative f') net \\<Longrightarrow> ((\\<lambda>x. f x + c) has_derivative f') net\"\n  by (intro derivative_eq_intros) auto\n\n\nsubsection\\<^marker>\\<open>tag unimportant\\<close> \\<open>Derivative with composed bilinear function\\<close>\n\ntext \\<open>More explicit epsilon-delta forms.\\<close>\n\nproposition has_derivative_within':\n  \"(f has_derivative f')(at x within s) \\<longleftrightarrow>\n    bounded_linear f' \\<and>\n    (\\<forall>e>0. \\<exists>d>0. \\<forall>x'\\<in>s. 0 < norm (x' - x) \\<and> norm (x' - x) < d \\<longrightarrow>\n      norm (f x' - f x - f'(x' - x)) / norm (x' - x) < e)\"\n  unfolding has_derivative_within Lim_within dist_norm\n  by (simp add: diff_diff_eq)\n\nlemma has_derivative_at':\n  \"(f has_derivative f') (at x) \n   \\<longleftrightarrow> bounded_linear f' \\<and>\n       (\\<forall>e>0. \\<exists>d>0. \\<forall>x'. 0 < norm (x' - x) \\<and> norm (x' - x) < d \\<longrightarrow>\n        norm (f x' - f x - f'(x' - x)) / norm (x' - x) < e)\"\n  using has_derivative_within' [of f f' x UNIV] by simp\n\nlemma has_derivative_componentwise_within:\n   \"(f has_derivative f') (at a within S) \\<longleftrightarrow>\n    (\\<forall>i \\<in> Basis. ((\\<lambda>x. f x \\<bullet> i) has_derivative (\\<lambda>x. f' x \\<bullet> i)) (at a within S))\"\n  apply (simp add: has_derivative_within)\n  apply (subst tendsto_componentwise_iff)\n  apply (simp add: bounded_linear_componentwise_iff [symmetric] ball_conj_distrib)\n  apply (simp add: algebra_simps)\n  done\n\nlemma has_derivative_at_withinI:\n  \"(f has_derivative f') (at x) \\<Longrightarrow> (f has_derivative f') (at x within s)\"\n  unfolding has_derivative_within' has_derivative_at'\n  by blast\n\nlemma has_derivative_right:\n  fixes f :: \"real \\<Rightarrow> real\"\n    and y :: \"real\"\n  shows \"(f has_derivative ((*) y)) (at x within ({x <..} \\<inter> I)) \\<longleftrightarrow>\n         ((\\<lambda>t. (f x - f t) / (x - t)) \\<longlongrightarrow> y) (at x within ({x <..} \\<inter> I))\"\nproof -\n  have \"((\\<lambda>t. (f t - (f x + y * (t - x))) / \\<bar>t - x\\<bar>) \\<longlongrightarrow> 0) (at x within ({x<..} \\<inter> I)) \\<longleftrightarrow>\n    ((\\<lambda>t. (f t - f x) / (t - x) - y) \\<longlongrightarrow> 0) (at x within ({x<..} \\<inter> I))\"\n    by (intro Lim_cong_within) (auto simp add: diff_divide_distrib add_divide_distrib)\n  also have \"\\<dots> \\<longleftrightarrow> ((\\<lambda>t. (f t - f x) / (t - x)) \\<longlongrightarrow> y) (at x within ({x<..} \\<inter> I))\"\n    by (simp add: Lim_null[symmetric])\n  also have \"\\<dots> \\<longleftrightarrow> ((\\<lambda>t. (f x - f t) / (x - t)) \\<longlongrightarrow> y) (at x within ({x<..} \\<inter> I))\"\n    by (intro Lim_cong_within) (simp_all add: field_simps)\n  finally show ?thesis\n    by (simp add: bounded_linear_mult_right has_derivative_within)\nqed\n\nsubsubsection \\<open>Caratheodory characterization\\<close>\n\nlemma DERIV_caratheodory_within:\n  \"(f has_field_derivative l) (at x within S) \\<longleftrightarrow>\n   (\\<exists>g. (\\<forall>z. f z - f x = g z * (z - x)) \\<and> continuous (at x within S) g \\<and> g x = l)\"\n      (is \"?lhs = ?rhs\")\nproof\n  assume ?lhs\n  show ?rhs\n  proof (intro exI conjI)\n    let ?g = \"(%z. if z = x then l else (f z - f x) / (z-x))\"\n    show \"\\<forall>z. f z - f x = ?g z * (z-x)\" by simp\n    show \"continuous (at x within S) ?g\" using \\<open>?lhs\\<close>\n      by (auto simp add: continuous_within has_field_derivative_iff cong: Lim_cong_within)\n    show \"?g x = l\" by simp\n  qed\nnext\n  assume ?rhs\n  then obtain g where\n    \"(\\<forall>z. f z - f x = g z * (z-x))\" and \"continuous (at x within S) g\" and \"g x = l\" by blast\n  thus ?lhs\n    by (auto simp add: continuous_within has_field_derivative_iff cong: Lim_cong_within)\nqed\n\nsubsection \\<open>Differentiability\\<close>\n\ndefinition\\<^marker>\\<open>tag important\\<close>\n  differentiable_on :: \"('a::real_normed_vector \\<Rightarrow> 'b::real_normed_vector) \\<Rightarrow> 'a set \\<Rightarrow> bool\"\n    (infix \"differentiable'_on\" 50)\n  where \"f differentiable_on s \\<longleftrightarrow> (\\<forall>x\\<in>s. f differentiable (at x within s))\"\n\nlemma differentiableI: \"(f has_derivative f') net \\<Longrightarrow> f differentiable net\"\n  unfolding differentiable_def\n  by auto\n\nlemma differentiable_onD: \"\\<lbrakk>f differentiable_on S; x \\<in> S\\<rbrakk> \\<Longrightarrow> f differentiable (at x within S)\"\n  using differentiable_on_def by blast\n\nlemma differentiable_at_withinI: \"f differentiable (at x) \\<Longrightarrow> f differentiable (at x within s)\"\n  unfolding differentiable_def\n  using has_derivative_at_withinI\n  by blast\n\nlemma differentiable_at_imp_differentiable_on:\n  \"(\\<And>x. x \\<in> s \\<Longrightarrow> f differentiable at x) \\<Longrightarrow> f differentiable_on s\"\n  by (metis differentiable_at_withinI differentiable_on_def)\n\ncorollary\\<^marker>\\<open>tag unimportant\\<close> differentiable_iff_scaleR:\n  fixes f :: \"real \\<Rightarrow> 'a::real_normed_vector\"\n  shows \"f differentiable F \\<longleftrightarrow> (\\<exists>d. (f has_derivative (\\<lambda>x. x *\\<^sub>R d)) F)\"\n  by (auto simp: differentiable_def dest: has_derivative_linear linear_imp_scaleR)\n\nlemma differentiable_on_eq_differentiable_at:\n  \"open s \\<Longrightarrow> f differentiable_on s \\<longleftrightarrow> (\\<forall>x\\<in>s. f differentiable at x)\"\n  unfolding differentiable_on_def\n  by (metis at_within_interior interior_open)\n\nlemma differentiable_transform_within:\n  assumes \"f differentiable (at x within s)\"\n    and \"0 < d\"\n    and \"x \\<in> s\"\n    and \"\\<And>x'. \\<lbrakk>x'\\<in>s; dist x' x < d\\<rbrakk> \\<Longrightarrow> f x' = g x'\"\n  shows \"g differentiable (at x within s)\"\n   using assms has_derivative_transform_within unfolding differentiable_def\n   by blast\n\nlemma differentiable_on_ident [simp, derivative_intros]: \"(\\<lambda>x. x) differentiable_on S\"\n  by (simp add: differentiable_at_imp_differentiable_on)\n\nlemma differentiable_on_id [simp, derivative_intros]: \"id differentiable_on S\"\n  by (simp add: id_def)\n\nlemma differentiable_on_const [simp, derivative_intros]: \"(\\<lambda>z. c) differentiable_on S\"\n  by (simp add: differentiable_on_def)\n\nlemma differentiable_on_mult [simp, derivative_intros]:\n  fixes f :: \"'M::real_normed_vector \\<Rightarrow> 'a::real_normed_algebra\"\n  shows \"\\<lbrakk>f differentiable_on S; g differentiable_on S\\<rbrakk> \\<Longrightarrow> (\\<lambda>z. f z * g z) differentiable_on S\"\n  unfolding differentiable_on_def differentiable_def\n  using differentiable_def differentiable_mult by blast\n\nlemma differentiable_on_compose:\n   \"\\<lbrakk>g differentiable_on S; f differentiable_on (g ` S)\\<rbrakk> \\<Longrightarrow> (\\<lambda>x. f (g x)) differentiable_on S\"\nby (simp add: differentiable_in_compose differentiable_on_def)\n\nlemma bounded_linear_imp_differentiable_on: \"bounded_linear f \\<Longrightarrow> f differentiable_on S\"\n  by (simp add: differentiable_on_def bounded_linear_imp_differentiable)\n\nlemma linear_imp_differentiable_on:\n  fixes f :: \"'a::euclidean_space \\<Rightarrow> 'b::real_normed_vector\"\n  shows \"linear f \\<Longrightarrow> f differentiable_on S\"\nby (simp add: differentiable_on_def linear_imp_differentiable)\n\nlemma differentiable_on_minus [simp, derivative_intros]:\n   \"f differentiable_on S \\<Longrightarrow> (\\<lambda>z. -(f z)) differentiable_on S\"\nby (simp add: differentiable_on_def)\n\nlemma differentiable_on_add [simp, derivative_intros]:\n   \"\\<lbrakk>f differentiable_on S; g differentiable_on S\\<rbrakk> \\<Longrightarrow> (\\<lambda>z. f z + g z) differentiable_on S\"\nby (simp add: differentiable_on_def)\n\nlemma differentiable_on_diff [simp, derivative_intros]:\n   \"\\<lbrakk>f differentiable_on S; g differentiable_on S\\<rbrakk> \\<Longrightarrow> (\\<lambda>z. f z - g z) differentiable_on S\"\nby (simp add: differentiable_on_def)\n\nlemma differentiable_on_inverse [simp, derivative_intros]:\n  fixes f :: \"'a :: real_normed_vector \\<Rightarrow> 'b :: real_normed_field\"\n  shows \"f differentiable_on S \\<Longrightarrow> (\\<And>x. x \\<in> S \\<Longrightarrow> f x \\<noteq> 0) \\<Longrightarrow> (\\<lambda>x. inverse (f x)) differentiable_on S\"\nby (simp add: differentiable_on_def)\n\nlemma differentiable_on_scaleR [derivative_intros, simp]:\n   \"\\<lbrakk>f differentiable_on S; g differentiable_on S\\<rbrakk> \\<Longrightarrow> (\\<lambda>x. f x *\\<^sub>R g x) differentiable_on S\"\n  unfolding differentiable_on_def\n  by (blast intro: differentiable_scaleR)\n\nlemma has_derivative_sqnorm_at [derivative_intros, simp]:\n  \"((\\<lambda>x. (norm x)\\<^sup>2) has_derivative (\\<lambda>x. 2 *\\<^sub>R (a \\<bullet> x))) (at a)\"\n  using bounded_bilinear.FDERIV  [of \"(\\<bullet>)\" id id a _ id id]\n  by (auto simp: inner_commute dot_square_norm bounded_bilinear_inner)\n\nlemma differentiable_sqnorm_at [derivative_intros, simp]:\n  fixes a :: \"'a :: {real_normed_vector,real_inner}\"\n  shows \"(\\<lambda>x. (norm x)\\<^sup>2) differentiable (at a)\"\nby (force simp add: differentiable_def intro: has_derivative_sqnorm_at)\n\nlemma differentiable_on_sqnorm [derivative_intros, simp]:\n  fixes S :: \"'a :: {real_normed_vector,real_inner} set\"\n  shows \"(\\<lambda>x. (norm x)\\<^sup>2) differentiable_on S\"\nby (simp add: differentiable_at_imp_differentiable_on)\n\nlemma differentiable_norm_at [derivative_intros, simp]:\n  fixes a :: \"'a :: {real_normed_vector,real_inner}\"\n  shows \"a \\<noteq> 0 \\<Longrightarrow> norm differentiable (at a)\"\nusing differentiableI has_derivative_norm by blast\n\nlemma differentiable_on_norm [derivative_intros, simp]:\n  fixes S :: \"'a :: {real_normed_vector,real_inner} set\"\n  shows \"0 \\<notin> S \\<Longrightarrow> norm differentiable_on S\"\nby (metis differentiable_at_imp_differentiable_on differentiable_norm_at)\n\n\nsubsection \\<open>Frechet derivative and Jacobian matrix\\<close>\n\ndefinition \"frechet_derivative f net = (SOME f'. (f has_derivative f') net)\"\n\nproposition frechet_derivative_works:\n  \"f differentiable net \\<longleftrightarrow> (f has_derivative (frechet_derivative f net)) net\"\n  unfolding frechet_derivative_def differentiable_def\n  unfolding some_eq_ex[of \"\\<lambda> f' . (f has_derivative f') net\"] ..\n\nlemma linear_frechet_derivative: \"f differentiable net \\<Longrightarrow> linear (frechet_derivative f net)\"\n  unfolding frechet_derivative_works has_derivative_def\n  by (auto intro: bounded_linear.linear)\n\nlemma frechet_derivative_const [simp]: \"frechet_derivative (\\<lambda>x. c) (at a) = (\\<lambda>x. 0)\"\n  using differentiable_const frechet_derivative_works has_derivative_const has_derivative_unique by blast\n\nlemma frechet_derivative_id [simp]: \"frechet_derivative id (at a) = id\"\n  using differentiable_def frechet_derivative_works has_derivative_id has_derivative_unique by blast\n\nlemma frechet_derivative_ident [simp]: \"frechet_derivative (\\<lambda>x. x) (at a) = (\\<lambda>x. x)\"\n  by (metis eq_id_iff frechet_derivative_id)\n\n\nsubsection \\<open>Differentiability implies continuity\\<close>\n\nproposition differentiable_imp_continuous_within:\n  \"f differentiable (at x within s) \\<Longrightarrow> continuous (at x within s) f\"\n  by (auto simp: differentiable_def intro: has_derivative_continuous)\n\nlemma differentiable_imp_continuous_on:\n  \"f differentiable_on s \\<Longrightarrow> continuous_on s f\"\n  unfolding differentiable_on_def continuous_on_eq_continuous_within\n  using differentiable_imp_continuous_within by blast\n\nlemma differentiable_on_subset:\n  \"f differentiable_on t \\<Longrightarrow> s \\<subseteq> t \\<Longrightarrow> f differentiable_on s\"\n  unfolding differentiable_on_def\n  using differentiable_within_subset\n  by blast\n\nlemma differentiable_on_empty: \"f differentiable_on {}\"\n  unfolding differentiable_on_def\n  by auto\n\nlemma has_derivative_continuous_on:\n  \"(\\<And>x. x \\<in> s \\<Longrightarrow> (f has_derivative f' x) (at x within s)) \\<Longrightarrow> continuous_on s f\"\n  by (auto intro!: differentiable_imp_continuous_on differentiableI simp: differentiable_on_def)\n\ntext \\<open>Results about neighborhoods filter.\\<close>\n\nlemma eventually_nhds_metric_le:\n  \"eventually P (nhds a) = (\\<exists>d>0. \\<forall>x. dist x a \\<le> d \\<longrightarrow> P x)\"\n  unfolding eventually_nhds_metric by (safe, rule_tac x=\"d / 2\" in exI, auto)\n\nlemma le_nhds: \"F \\<le> nhds a \\<longleftrightarrow> (\\<forall>S. open S \\<and> a \\<in> S \\<longrightarrow> eventually (\\<lambda>x. x \\<in> S) F)\"\n  unfolding le_filter_def eventually_nhds by (fast elim: eventually_mono)\n\nlemma le_nhds_metric: \"F \\<le> nhds a \\<longleftrightarrow> (\\<forall>e>0. eventually (\\<lambda>x. dist x a < e) F)\"\n  unfolding le_filter_def eventually_nhds_metric by (fast elim: eventually_mono)\n\nlemma le_nhds_metric_le: \"F \\<le> nhds a \\<longleftrightarrow> (\\<forall>e>0. eventually (\\<lambda>x. dist x a \\<le> e) F)\"\n  unfolding le_filter_def eventually_nhds_metric_le by (fast elim: eventually_mono)\n\ntext \\<open>Several results are easier using a \"multiplied-out\" variant.\n(I got this idea from Dieudonne's proof of the chain rule).\\<close>\n\nlemma has_derivative_within_alt:\n  \"(f has_derivative f') (at x within s) \\<longleftrightarrow> bounded_linear f' \\<and>\n    (\\<forall>e>0. \\<exists>d>0. \\<forall>y\\<in>s. norm(y - x) < d \\<longrightarrow> norm (f y - f x - f' (y - x)) \\<le> e * norm (y - x))\"\n  unfolding has_derivative_within filterlim_def le_nhds_metric_le eventually_filtermap\n    eventually_at dist_norm diff_diff_eq\n  by (force simp add: linear_0 bounded_linear.linear pos_divide_le_eq)\n\nlemma has_derivative_within_alt2:\n  \"(f has_derivative f') (at x within s) \\<longleftrightarrow> bounded_linear f' \\<and>\n    (\\<forall>e>0. eventually (\\<lambda>y. norm (f y - f x - f' (y - x)) \\<le> e * norm (y - x)) (at x within s))\"\n  unfolding has_derivative_within filterlim_def le_nhds_metric_le eventually_filtermap\n    eventually_at dist_norm diff_diff_eq\n  by (force simp add: linear_0 bounded_linear.linear pos_divide_le_eq)\n\nlemma has_derivative_at_alt:\n  \"(f has_derivative f') (at x) \\<longleftrightarrow>\n    bounded_linear f' \\<and>\n    (\\<forall>e>0. \\<exists>d>0. \\<forall>y. norm(y - x) < d \\<longrightarrow> norm (f y - f x - f'(y - x)) \\<le> e * norm (y - x))\"\n  using has_derivative_within_alt[where s=UNIV]\n  by simp\n\n\nsubsection \\<open>The chain rule\\<close>\n\nproposition diff_chain_within[derivative_intros]:\n  assumes \"(f has_derivative f') (at x within s)\"\n    and \"(g has_derivative g') (at (f x) within (f ` s))\"\n  shows \"((g \\<circ> f) has_derivative (g' \\<circ> f'))(at x within s)\"\n  using has_derivative_in_compose[OF assms]\n  by (simp add: comp_def)\n\nlemma diff_chain_at[derivative_intros]:\n  \"(f has_derivative f') (at x) \\<Longrightarrow>\n    (g has_derivative g') (at (f x)) \\<Longrightarrow> ((g \\<circ> f) has_derivative (g' \\<circ> f')) (at x)\"\n  using has_derivative_compose[of f f' x UNIV g g']\n  by (simp add: comp_def)\n\nlemma has_vector_derivative_within_open:\n  \"a \\<in> S \\<Longrightarrow> open S \\<Longrightarrow>\n    (f has_vector_derivative f') (at a within S) \\<longleftrightarrow> (f has_vector_derivative f') (at a)\"\n  by (simp only: at_within_interior interior_open)\n\nlemma field_vector_diff_chain_within:\n assumes Df: \"(f has_vector_derivative f') (at x within S)\"\n     and Dg: \"(g has_field_derivative g') (at (f x) within f ` S)\"\n shows \"((g \\<circ> f) has_vector_derivative (f' * g')) (at x within S)\"\nusing diff_chain_within[OF Df[unfolded has_vector_derivative_def]\n                       Dg [unfolded has_field_derivative_def]]\n by (auto simp: o_def mult.commute has_vector_derivative_def)\n\nlemma vector_derivative_diff_chain_within:\n  assumes Df: \"(f has_vector_derivative f') (at x within S)\"\n     and Dg: \"(g has_derivative g') (at (f x) within f`S)\"\n  shows \"((g \\<circ> f) has_vector_derivative (g' f')) (at x within S)\"\nusing diff_chain_within[OF Df[unfolded has_vector_derivative_def] Dg]\n  linear.scaleR[OF has_derivative_linear[OF Dg]]\n  unfolding has_vector_derivative_def o_def\n  by (auto simp: o_def mult.commute has_vector_derivative_def)\n\n\nsubsection\\<^marker>\\<open>tag unimportant\\<close> \\<open>Composition rules stated just for differentiability\\<close>\n\nlemma differentiable_chain_at:\n  \"f differentiable (at x) \\<Longrightarrow>\n    g differentiable (at (f x)) \\<Longrightarrow> (g \\<circ> f) differentiable (at x)\"\n  unfolding differentiable_def\n  by (meson diff_chain_at)\n\nlemma differentiable_chain_within:\n  \"f differentiable (at x within S) \\<Longrightarrow>\n    g differentiable (at(f x) within (f ` S)) \\<Longrightarrow> (g \\<circ> f) differentiable (at x within S)\"\n  unfolding differentiable_def\n  by (meson diff_chain_within)\n\n\nsubsection \\<open>Uniqueness of derivative\\<close>\n\n\ntext\\<^marker>\\<open>tag important\\<close> \\<open>\n The general result is a bit messy because we need approachability of the\n limit point from any direction. But OK for nontrivial intervals etc.\n\\<close>\n\nproposition frechet_derivative_unique_within:\n  fixes f :: \"'a::euclidean_space \\<Rightarrow> 'b::real_normed_vector\"\n  assumes 1: \"(f has_derivative f') (at x within S)\"\n    and 2: \"(f has_derivative f'') (at x within S)\"\n    and S: \"\\<And>i e. \\<lbrakk>i\\<in>Basis; e>0\\<rbrakk> \\<Longrightarrow> \\<exists>d. 0 < \\<bar>d\\<bar> \\<and> \\<bar>d\\<bar> < e \\<and> (x + d *\\<^sub>R i) \\<in> S\"\n  shows \"f' = f''\"\nproof -\n  note as = assms(1,2)[unfolded has_derivative_def]\n  then interpret f': bounded_linear f' by auto\n  from as interpret f'': bounded_linear f'' by auto\n  have \"x islimpt S\" unfolding islimpt_approachable\n  proof (intro allI impI)\n    fix e :: real\n    assume \"e > 0\"\n    obtain d where \"0 < \\<bar>d\\<bar>\" and \"\\<bar>d\\<bar> < e\" and \"x + d *\\<^sub>R (SOME i. i \\<in> Basis) \\<in> S\"\n      using assms(3) SOME_Basis \\<open>e>0\\<close> by blast\n    then show \"\\<exists>x'\\<in>S. x' \\<noteq> x \\<and> dist x' x < e\"\n      by (rule_tac x=\"x + d *\\<^sub>R (SOME i. i \\<in> Basis)\" in bexI) (auto simp: dist_norm SOME_Basis nonzero_Basis)  qed\n  then have *: \"netlimit (at x within S) = x\"\n    by (simp add: Lim_ident_at trivial_limit_within)\n  show ?thesis\n  proof (rule linear_eq_stdbasis)\n    show \"linear f'\" \"linear f''\"\n      unfolding linear_conv_bounded_linear using as by auto\n  next\n    fix i :: 'a\n    assume i: \"i \\<in> Basis\"\n    define e where \"e = norm (f' i - f'' i)\"\n    show \"f' i = f'' i\"\n    proof (rule ccontr)\n      assume \"f' i \\<noteq> f'' i\"\n      then have \"e > 0\"\n        unfolding e_def by auto\n      obtain d where d:\n        \"0 < d\"\n        \"(\\<And>y. y\\<in>S \\<longrightarrow> 0 < dist y x \\<and> dist y x < d \\<longrightarrow>\n          dist ((f y - f x - f' (y - x)) /\\<^sub>R norm (y - x) -\n              (f y - f x - f'' (y - x)) /\\<^sub>R norm (y - x)) (0 - 0) < e)\"\n        using tendsto_diff [OF as(1,2)[THEN conjunct2]]\n        unfolding * Lim_within\n        using \\<open>e>0\\<close> by blast\n      obtain c where c: \"0 < \\<bar>c\\<bar>\" \"\\<bar>c\\<bar> < d \\<and> x + c *\\<^sub>R i \\<in> S\"\n        using assms(3) i d(1) by blast\n      have *: \"norm (- ((1 / \\<bar>c\\<bar>) *\\<^sub>R f' (c *\\<^sub>R i)) + (1 / \\<bar>c\\<bar>) *\\<^sub>R f'' (c *\\<^sub>R i)) =\n        norm ((1 / \\<bar>c\\<bar>) *\\<^sub>R (- (f' (c *\\<^sub>R i)) + f'' (c *\\<^sub>R i)))\"\n        unfolding scaleR_right_distrib by auto\n      also have \"\\<dots> = norm ((1 / \\<bar>c\\<bar>) *\\<^sub>R (c *\\<^sub>R (- (f' i) + f'' i)))\"\n        unfolding f'.scaleR f''.scaleR\n        unfolding scaleR_right_distrib scaleR_minus_right\n        by auto\n      also have \"\\<dots> = e\"\n        unfolding e_def\n        using c(1)\n        using norm_minus_cancel[of \"f' i - f'' i\"]\n        by auto\n      finally show False\n        using c\n        using d(2)[of \"x + c *\\<^sub>R i\"]\n        unfolding dist_norm\n        unfolding f'.scaleR f''.scaleR f'.add f''.add f'.diff f''.diff\n          scaleR_scaleR scaleR_right_diff_distrib scaleR_right_distrib\n        using i\n        by (auto simp: inverse_eq_divide)\n    qed\n  qed\nqed\n\nproposition frechet_derivative_unique_within_closed_interval:\n  fixes f::\"'a::euclidean_space \\<Rightarrow> 'b::real_normed_vector\"\n  assumes ab: \"\\<And>i. i\\<in>Basis \\<Longrightarrow> a\\<bullet>i < b\\<bullet>i\"\n    and x: \"x \\<in> cbox a b\"\n    and \"(f has_derivative f' ) (at x within cbox a b)\"\n    and \"(f has_derivative f'') (at x within cbox a b)\"\n  shows \"f' = f''\"\nproof (rule frechet_derivative_unique_within)\n  fix e :: real\n  fix i :: 'a\n  assume \"e > 0\" and i: \"i \\<in> Basis\"\n  then show \"\\<exists>d. 0 < \\<bar>d\\<bar> \\<and> \\<bar>d\\<bar> < e \\<and> x + d *\\<^sub>R i \\<in> cbox a b\"\n  proof (cases \"x\\<bullet>i = a\\<bullet>i\")\n    case True\n    with ab[of i] \\<open>e>0\\<close> x i show ?thesis\n      by (rule_tac x=\"(min (b\\<bullet>i - a\\<bullet>i) e) / 2\" in exI)\n         (auto simp add: mem_box field_simps inner_simps inner_Basis)\n  next\n    case False\n    moreover have \"a \\<bullet> i < x \\<bullet> i\"\n      using False i mem_box(2) x by force\n    moreover {\n      have \"a \\<bullet> i * 2 + min (x \\<bullet> i - a \\<bullet> i) e \\<le> a\\<bullet>i *2 + x\\<bullet>i - a\\<bullet>i\"\n        by auto\n      also have \"\\<dots> = a\\<bullet>i + x\\<bullet>i\"\n        by auto\n      also have \"\\<dots> \\<le> 2 * (x\\<bullet>i)\"\n        using \\<open>a \\<bullet> i < x \\<bullet> i\\<close> by auto\n      finally have \"a \\<bullet> i * 2 + min (x \\<bullet> i - a \\<bullet> i) e \\<le> x \\<bullet> i * 2\"\n        by auto\n    }\n    moreover have \"min (x \\<bullet> i - a \\<bullet> i) e \\<ge> 0\"\n      by (simp add: \\<open>0 < e\\<close> \\<open>a \\<bullet> i < x \\<bullet> i\\<close> less_eq_real_def)\n    then have \"x \\<bullet> i * 2 \\<le> b \\<bullet> i * 2 + min (x \\<bullet> i - a \\<bullet> i) e\"\n      using i mem_box(2) x by force\n    ultimately show ?thesis\n    using ab[of i] \\<open>e>0\\<close> x i \n      by (rule_tac x=\"- (min (x\\<bullet>i - a\\<bullet>i) e) / 2\" in exI)\n         (auto simp add: mem_box field_simps inner_simps inner_Basis)\n  qed\nqed (use assms in auto)\n\nlemma frechet_derivative_unique_within_open_interval:\n  fixes f::\"'a::euclidean_space \\<Rightarrow> 'b::real_normed_vector\"\n  assumes x: \"x \\<in> box a b\"\n    and f: \"(f has_derivative f' ) (at x within box a b)\" \"(f has_derivative f'') (at x within box a b)\"\n  shows \"f' = f''\"\nproof -\n  have \"at x within box a b = at x\"\n    by (metis x at_within_interior interior_open open_box)\n  with f show \"f' = f''\"\n    by (simp add: has_derivative_unique)\nqed\n\nlemma frechet_derivative_at:\n  \"(f has_derivative f') (at x) \\<Longrightarrow> f' = frechet_derivative f (at x)\"\n  using differentiable_def frechet_derivative_works has_derivative_unique by blast\n\nlemma frechet_derivative_compose:\n  \"frechet_derivative (f o g) (at x) = frechet_derivative (f) (at (g x)) o frechet_derivative g (at x)\"\n  if \"g differentiable at x\" \"f differentiable at (g x)\"\n  by (metis diff_chain_at frechet_derivative_at frechet_derivative_works that)\n\nlemma frechet_derivative_within_cbox:\n  fixes f :: \"'a::euclidean_space \\<Rightarrow> 'b::real_normed_vector\"\n  assumes \"\\<And>i. i\\<in>Basis \\<Longrightarrow> a\\<bullet>i < b\\<bullet>i\"\n    and \"x \\<in> cbox a b\"\n    and \"(f has_derivative f') (at x within cbox a b)\"\n  shows \"frechet_derivative f (at x within cbox a b) = f'\"\n  using assms\n  by (metis Derivative.differentiableI frechet_derivative_unique_within_closed_interval frechet_derivative_works)\n\nlemma frechet_derivative_transform_within_open:\n  \"frechet_derivative f (at x) = frechet_derivative g (at x)\"\n  if \"f differentiable at x\" \"open X\" \"x \\<in> X\" \"\\<And>x. x \\<in> X \\<Longrightarrow> f x = g x\"\n  by (meson frechet_derivative_at frechet_derivative_works has_derivative_transform_within_open that)\n\n\nsubsection \\<open>Derivatives of local minima and maxima are zero\\<close>\n\nlemma has_derivative_local_min:\n  fixes f :: \"'a::real_normed_vector \\<Rightarrow> real\"\n  assumes deriv: \"(f has_derivative f') (at x)\"\n  assumes min: \"eventually (\\<lambda>y. f x \\<le> f y) (at x)\"\n  shows \"f' = (\\<lambda>h. 0)\"\nproof\n  fix h :: 'a\n  interpret f': bounded_linear f'\n    using deriv by (rule has_derivative_bounded_linear)\n  show \"f' h = 0\"\n  proof (cases \"h = 0\")\n    case False\n    from min obtain d where d1: \"0 < d\" and d2: \"\\<forall>y\\<in>ball x d. f x \\<le> f y\"\n      unfolding eventually_at by (force simp: dist_commute)\n    have \"FDERIV (\\<lambda>r. x + r *\\<^sub>R h) 0 :> (\\<lambda>r. r *\\<^sub>R h)\"\n      by (intro derivative_eq_intros) auto\n    then have \"FDERIV (\\<lambda>r. f (x + r *\\<^sub>R h)) 0 :> (\\<lambda>k. f' (k *\\<^sub>R h))\"\n      by (rule has_derivative_compose, simp add: deriv)\n    then have \"DERIV (\\<lambda>r. f (x + r *\\<^sub>R h)) 0 :> f' h\"\n      unfolding has_field_derivative_def by (simp add: f'.scaleR mult_commute_abs)\n    moreover have \"0 < d / norm h\" using d1 and \\<open>h \\<noteq> 0\\<close> by simp\n    moreover have \"\\<forall>y. \\<bar>0 - y\\<bar> < d / norm h \\<longrightarrow> f (x + 0 *\\<^sub>R h) \\<le> f (x + y *\\<^sub>R h)\"\n      using \\<open>h \\<noteq> 0\\<close> by (auto simp add: d2 dist_norm pos_less_divide_eq)\n    ultimately show \"f' h = 0\"\n      by (rule DERIV_local_min)\n  qed simp\nqed\n\nlemma has_derivative_local_max:\n  fixes f :: \"'a::real_normed_vector \\<Rightarrow> real\"\n  assumes \"(f has_derivative f') (at x)\"\n  assumes \"eventually (\\<lambda>y. f y \\<le> f x) (at x)\"\n  shows \"f' = (\\<lambda>h. 0)\"\n  using has_derivative_local_min [of \"\\<lambda>x. - f x\" \"\\<lambda>h. - f' h\" \"x\"]\n  using assms unfolding fun_eq_iff by simp\n\nlemma differential_zero_maxmin:\n  fixes f::\"'a::real_normed_vector \\<Rightarrow> real\"\n  assumes \"x \\<in> S\"\n    and \"open S\"\n    and deriv: \"(f has_derivative f') (at x)\"\n    and mono: \"(\\<forall>y\\<in>S. f y \\<le> f x) \\<or> (\\<forall>y\\<in>S. f x \\<le> f y)\"\n  shows \"f' = (\\<lambda>v. 0)\"\n  using mono\nproof\n  assume \"\\<forall>y\\<in>S. f y \\<le> f x\"\n  with \\<open>x \\<in> S\\<close> and \\<open>open S\\<close> have \"eventually (\\<lambda>y. f y \\<le> f x) (at x)\"\n    unfolding eventually_at_topological by auto\n  with deriv show ?thesis\n    by (rule has_derivative_local_max)\nnext\n  assume \"\\<forall>y\\<in>S. f x \\<le> f y\"\n  with \\<open>x \\<in> S\\<close> and \\<open>open S\\<close> have \"eventually (\\<lambda>y. f x \\<le> f y) (at x)\"\n    unfolding eventually_at_topological by auto\n  with deriv show ?thesis\n    by (rule has_derivative_local_min)\nqed\n\nlemma differential_zero_maxmin_component:\n  fixes f :: \"'a::euclidean_space \\<Rightarrow> 'b::euclidean_space\"\n  assumes k: \"k \\<in> Basis\"\n    and ball: \"0 < e\" \"(\\<forall>y \\<in> ball x e. (f y)\\<bullet>k \\<le> (f x)\\<bullet>k) \\<or> (\\<forall>y\\<in>ball x e. (f x)\\<bullet>k \\<le> (f y)\\<bullet>k)\"\n    and diff: \"f differentiable (at x)\"\n  shows \"(\\<Sum>j\\<in>Basis. (frechet_derivative f (at x) j \\<bullet> k) *\\<^sub>R j) = (0::'a)\" (is \"?D k = 0\")\nproof -\n  let ?f' = \"frechet_derivative f (at x)\"\n  have \"x \\<in> ball x e\" using \\<open>0 < e\\<close> by simp\n  moreover have \"open (ball x e)\" by simp\n  moreover have \"((\\<lambda>x. f x \\<bullet> k) has_derivative (\\<lambda>h. ?f' h \\<bullet> k)) (at x)\"\n    using bounded_linear_inner_left diff[unfolded frechet_derivative_works]\n    by (rule bounded_linear.has_derivative)\n  ultimately have \"(\\<lambda>h. frechet_derivative f (at x) h \\<bullet> k) = (\\<lambda>v. 0)\"\n    using ball(2) by (rule differential_zero_maxmin)\n  then show ?thesis\n    unfolding fun_eq_iff by simp\nqed\n\nsubsection \\<open>One-dimensional mean value theorem\\<close>\n\nlemma mvt_simple:\n  fixes f :: \"real \\<Rightarrow> real\"\n  assumes \"a < b\"\n    and derf: \"\\<And>x. \\<lbrakk>a \\<le> x; x \\<le> b\\<rbrakk> \\<Longrightarrow> (f has_derivative f' x) (at x within {a..b})\"\n  shows \"\\<exists>x\\<in>{a<..<b}. f b - f a = f' x (b - a)\"\nproof (rule mvt)\n  have \"f differentiable_on {a..b}\"\n    using derf unfolding differentiable_on_def differentiable_def by force\n  then show \"continuous_on {a..b} f\"\n    by (rule differentiable_imp_continuous_on)\n  show \"(f has_derivative f' x) (at x)\" if \"a < x\" \"x < b\" for x\n    by (metis at_within_Icc_at derf leI order.asym that)\nqed (use assms in auto)\n\nlemma mvt_very_simple:\n  fixes f :: \"real \\<Rightarrow> real\"\n  assumes \"a \\<le> b\"\n    and derf: \"\\<And>x. \\<lbrakk>a \\<le> x; x \\<le> b\\<rbrakk> \\<Longrightarrow> (f has_derivative f' x) (at x within {a..b})\"\n  shows \"\\<exists>x\\<in>{a..b}. f b - f a = f' x (b - a)\"\nproof (cases \"a = b\")\n  interpret bounded_linear \"f' b\"\n    using assms(2) assms(1) by auto\n  case True\n  then show ?thesis\n    by force\nnext\n  case False\n  then show ?thesis\n    using mvt_simple[OF _ derf]\n    by (metis \\<open>a \\<le> b\\<close> atLeastAtMost_iff dual_order.order_iff_strict greaterThanLessThan_iff)\nqed\n\ntext \\<open>A nice generalization (see Havin's proof of 5.19 from Rudin's book).\\<close>\n\nlemma mvt_general:\n  fixes f :: \"real \\<Rightarrow> 'a::real_inner\"\n  assumes \"a < b\"\n    and contf: \"continuous_on {a..b} f\"\n    and derf: \"\\<And>x. \\<lbrakk>a < x; x < b\\<rbrakk> \\<Longrightarrow> (f has_derivative f' x) (at x)\"\n  shows \"\\<exists>x\\<in>{a<..<b}. norm (f b - f a) \\<le> norm (f' x (b - a))\"\nproof -\n  have \"\\<exists>x\\<in>{a<..<b}. (f b - f a) \\<bullet> f b - (f b - f a) \\<bullet> f a = (f b - f a) \\<bullet> f' x (b - a)\"\n    apply (rule mvt [OF \\<open>a < b\\<close>, where f = \"\\<lambda>x. (f b - f a) \\<bullet> f x\"])\n    apply (intro continuous_intros contf)\n    using derf apply (auto intro: has_derivative_inner_right)\n    done\n  then obtain x where x: \"x \\<in> {a<..<b}\"\n    \"(f b - f a) \\<bullet> f b - (f b - f a) \\<bullet> f a = (f b - f a) \\<bullet> f' x (b - a)\" ..\n  show ?thesis\n  proof (cases \"f a = f b\")\n    case False\n    have \"norm (f b - f a) * norm (f b - f a) = (norm (f b - f a))\\<^sup>2\"\n      by (simp add: power2_eq_square)\n    also have \"\\<dots> = (f b - f a) \\<bullet> (f b - f a)\"\n      unfolding power2_norm_eq_inner ..\n    also have \"\\<dots> = (f b - f a) \\<bullet> f' x (b - a)\"\n      using x(2) by (simp only: inner_diff_right)\n    also have \"\\<dots> \\<le> norm (f b - f a) * norm (f' x (b - a))\"\n      by (rule norm_cauchy_schwarz)\n    finally show ?thesis\n      using False x(1)\n      by (auto simp add: mult_left_cancel)\n  next\n    case True\n    then show ?thesis\n      using \\<open>a < b\\<close> by (rule_tac x=\"(a + b) /2\" in bexI) auto\n  qed\nqed\n\n\nsubsection \\<open>More general bound theorems\\<close>\n\nproposition differentiable_bound_general:\n  fixes f :: \"real \\<Rightarrow> 'a::real_normed_vector\"\n  assumes \"a < b\"\n    and f_cont: \"continuous_on {a..b} f\"\n    and phi_cont: \"continuous_on {a..b} \\<phi>\"\n    and f': \"\\<And>x. a < x \\<Longrightarrow> x < b \\<Longrightarrow> (f has_vector_derivative f' x) (at x)\"\n    and phi': \"\\<And>x. a < x \\<Longrightarrow> x < b \\<Longrightarrow> (\\<phi> has_vector_derivative \\<phi>' x) (at x)\"\n    and bnd: \"\\<And>x. a < x \\<Longrightarrow> x < b \\<Longrightarrow> norm (f' x) \\<le> \\<phi>' x\"\n  shows \"norm (f b - f a) \\<le> \\<phi> b - \\<phi> a\"\nproof -\n  {\n    fix x assume x: \"a < x\" \"x < b\"\n    have \"0 \\<le> norm (f' x)\" by simp\n    also have \"\\<dots> \\<le> \\<phi>' x\" using x by (auto intro!: bnd)\n    finally have \"0 \\<le> \\<phi>' x\" .\n  } note phi'_nonneg = this\n  note f_tendsto = assms(2)[simplified continuous_on_def, rule_format]\n  note phi_tendsto = assms(3)[simplified continuous_on_def, rule_format]\n  {\n    fix e::real assume \"e > 0\"\n    define e2 where \"e2 = e / 2\"\n    with \\<open>e > 0\\<close> have \"e2 > 0\" by simp\n    let ?le = \"\\<lambda>x1. norm (f x1 - f a) \\<le> \\<phi> x1 - \\<phi> a + e * (x1 - a) + e\"\n    define A where \"A = {x2. a \\<le> x2 \\<and> x2 \\<le> b \\<and> (\\<forall>x1\\<in>{a ..< x2}. ?le x1)}\"\n    have A_subset: \"A \\<subseteq> {a..b}\" by (auto simp: A_def)\n    {\n      fix x2\n      assume a: \"a \\<le> x2\" \"x2 \\<le> b\" and le: \"\\<forall>x1\\<in>{a..<x2}. ?le x1\"\n      have \"?le x2\" using \\<open>e > 0\\<close>\n      proof cases\n        assume \"x2 \\<noteq> a\" with a have \"a < x2\" by simp\n        have \"at x2 within {a <..<x2}\\<noteq> bot\"\n          using \\<open>a < x2\\<close>\n          by (auto simp: trivial_limit_within islimpt_in_closure)\n        moreover\n        have \"((\\<lambda>x1. (\\<phi> x1 - \\<phi> a) + e * (x1 - a) + e) \\<longlongrightarrow> (\\<phi> x2 - \\<phi> a) + e * (x2 - a) + e) (at x2 within {a <..<x2})\"\n          \"((\\<lambda>x1. norm (f x1 - f a)) \\<longlongrightarrow> norm (f x2 - f a)) (at x2 within {a <..<x2})\"\n          using a\n          by (auto intro!: tendsto_eq_intros f_tendsto phi_tendsto\n            intro: tendsto_within_subset[where S=\"{a..b}\"])\n        moreover\n        have \"eventually (\\<lambda>x. x > a) (at x2 within {a <..<x2})\"\n          by (auto simp: eventually_at_filter)\n        hence \"eventually ?le (at x2 within {a <..<x2})\"\n          unfolding eventually_at_filter\n          by eventually_elim (insert le, auto)\n        ultimately\n        show ?thesis\n          by (rule tendsto_le)\n      qed simp\n    } note le_cont = this\n    have \"a \\<in> A\"\n      using assms by (auto simp: A_def)\n    hence [simp]: \"A \\<noteq> {}\" by auto\n    have A_ivl: \"\\<And>x1 x2. x2 \\<in> A \\<Longrightarrow> x1 \\<in> {a ..x2} \\<Longrightarrow> x1 \\<in> A\"\n      by (simp add: A_def)\n    have [simp]: \"bdd_above A\" by (auto simp: A_def)\n    define y where \"y = Sup A\"\n    have \"y \\<le> b\"\n      unfolding y_def\n      by (simp add: cSup_le_iff) (simp add: A_def)\n     have leI: \"\\<And>x x1. a \\<le> x1 \\<Longrightarrow> x \\<in> A \\<Longrightarrow> x1 < x \\<Longrightarrow> ?le x1\"\n       by (auto simp: A_def intro!: le_cont)\n    have y_all_le: \"\\<forall>x1\\<in>{a..<y}. ?le x1\"\n      by (auto simp: y_def less_cSup_iff leI)\n    have \"a \\<le> y\"\n      by (metis \\<open>a \\<in> A\\<close> \\<open>bdd_above A\\<close> cSup_upper y_def)\n    have \"y \\<in> A\"\n      using y_all_le \\<open>a \\<le> y\\<close> \\<open>y \\<le> b\\<close>\n      by (auto simp: A_def)\n    hence \"A = {a .. y}\"\n      using A_subset by (auto simp: subset_iff y_def cSup_upper intro: A_ivl)\n    from le_cont[OF \\<open>a \\<le> y\\<close> \\<open>y \\<le> b\\<close> y_all_le] have le_y: \"?le y\" .\n    have \"y = b\"\n    proof (cases \"a = y\")\n      case True\n      with \\<open>a < b\\<close> have \"y < b\" by simp\n      with \\<open>a = y\\<close> f_cont phi_cont \\<open>e2 > 0\\<close>\n      have 1: \"\\<forall>\\<^sub>F x in at y within {y..b}. dist (f x) (f y) < e2\"\n       and 2: \"\\<forall>\\<^sub>F x in at y within {y..b}. dist (\\<phi> x) (\\<phi> y) < e2\"\n        by (auto simp: continuous_on_def tendsto_iff)\n      have 3: \"eventually (\\<lambda>x. y < x) (at y within {y..b})\"\n        by (auto simp: eventually_at_filter)\n      have 4: \"eventually (\\<lambda>x::real. x < b) (at y within {y..b})\"\n        using _ \\<open>y < b\\<close>\n        by (rule order_tendstoD) (auto intro!: tendsto_eq_intros)\n      from 1 2 3 4\n      have eventually_le: \"eventually (\\<lambda>x. ?le x) (at y within {y .. b})\"\n      proof eventually_elim\n        case (elim x1)\n        have \"norm (f x1 - f a) = norm (f x1 - f y)\"\n          by (simp add: \\<open>a = y\\<close>)\n        also have \"norm (f x1 - f y) \\<le> e2\"\n          using elim \\<open>a = y\\<close> by (auto simp : dist_norm intro!:  less_imp_le)\n        also have \"\\<dots> \\<le> e2 + (\\<phi> x1 - \\<phi> a + e2 + e * (x1 - a))\"\n          using \\<open>0 < e\\<close> elim\n          by (intro add_increasing2[OF add_nonneg_nonneg order.refl])\n            (auto simp: \\<open>a = y\\<close> dist_norm intro!: mult_nonneg_nonneg)\n        also have \"\\<dots> = \\<phi> x1 - \\<phi> a + e * (x1 - a) + e\"\n          by (simp add: e2_def)\n        finally show \"?le x1\" .\n      qed\n      from this[unfolded eventually_at_topological] \\<open>?le y\\<close>\n      obtain S where S: \"open S\" \"y \\<in> S\" \"\\<And>x. x\\<in>S \\<Longrightarrow> x \\<in> {y..b} \\<Longrightarrow> ?le x\"\n        by metis\n      from \\<open>open S\\<close> obtain d where d: \"\\<And>x. dist x y < d \\<Longrightarrow> x \\<in> S\" \"d > 0\"\n        by (force simp: dist_commute open_dist ball_def dest!: bspec[OF _ \\<open>y \\<in> S\\<close>])\n      define d' where \"d' = min b (y + (d/2))\"\n      have \"d' \\<in> A\"\n        unfolding A_def\n      proof safe\n        show \"a \\<le> d'\" using \\<open>a = y\\<close> \\<open>0 < d\\<close> \\<open>y < b\\<close> by (simp add: d'_def)\n        show \"d' \\<le> b\" by (simp add: d'_def)\n        fix x1\n        assume \"x1 \\<in> {a..<d'}\"\n        hence \"x1 \\<in> S\" \"x1 \\<in> {y..b}\"\n          by (auto simp: \\<open>a = y\\<close> d'_def dist_real_def intro!: d )\n        thus \"?le x1\"\n          by (rule S)\n      qed\n      hence \"d' \\<le> y\"\n        unfolding y_def\n        by (rule cSup_upper) simp\n      then show \"y = b\" using \\<open>d > 0\\<close> \\<open>y < b\\<close>\n        by (simp add: d'_def)\n    next\n      case False\n      with \\<open>a \\<le> y\\<close> have \"a < y\" by simp\n      show \"y = b\"\n      proof (rule ccontr)\n        assume \"y \\<noteq> b\"\n        hence \"y < b\" using \\<open>y \\<le> b\\<close> by simp\n        let ?F = \"at y within {y..<b}\"\n        from f' phi'\n        have \"(f has_vector_derivative f' y) ?F\"\n          and \"(\\<phi> has_vector_derivative \\<phi>' y) ?F\"\n          using \\<open>a < y\\<close> \\<open>y < b\\<close>\n          by (auto simp add: at_within_open[of _ \"{a<..<b}\"] has_vector_derivative_def\n            intro!: has_derivative_subset[where s=\"{a<..<b}\" and t=\"{y..<b}\"])\n        hence \"\\<forall>\\<^sub>F x1 in ?F. norm (f x1 - f y - (x1 - y) *\\<^sub>R f' y) \\<le> e2 * \\<bar>x1 - y\\<bar>\"\n            \"\\<forall>\\<^sub>F x1 in ?F. norm (\\<phi> x1 - \\<phi> y - (x1 - y) *\\<^sub>R \\<phi>' y) \\<le> e2 * \\<bar>x1 - y\\<bar>\"\n          using \\<open>e2 > 0\\<close>\n          by (auto simp: has_derivative_within_alt2 has_vector_derivative_def)\n        moreover\n        have \"\\<forall>\\<^sub>F x1 in ?F. y \\<le> x1\" \"\\<forall>\\<^sub>F x1 in ?F. x1 < b\"\n          by (auto simp: eventually_at_filter)\n        ultimately\n        have \"\\<forall>\\<^sub>F x1 in ?F. norm (f x1 - f y) \\<le> (\\<phi> x1 - \\<phi> y) + e * \\<bar>x1 - y\\<bar>\"\n          (is \"\\<forall>\\<^sub>F x1 in ?F. ?le' x1\")\n        proof eventually_elim\n          case (elim x1)\n          from norm_triangle_ineq2[THEN order_trans, OF elim(1)]\n          have \"norm (f x1 - f y) \\<le> norm (f' y) * \\<bar>x1 - y\\<bar> + e2 * \\<bar>x1 - y\\<bar>\"\n            by (simp add: ac_simps)\n          also have \"norm (f' y) \\<le> \\<phi>' y\" using bnd \\<open>a < y\\<close> \\<open>y < b\\<close> by simp\n          also have \"\\<phi>' y * \\<bar>x1 - y\\<bar> \\<le> \\<phi> x1 - \\<phi> y + e2 * \\<bar>x1 - y\\<bar>\"\n            using elim by (simp add: ac_simps)\n          finally\n          have \"norm (f x1 - f y) \\<le> \\<phi> x1 - \\<phi> y + e2 * \\<bar>x1 - y\\<bar> + e2 * \\<bar>x1 - y\\<bar>\"\n            by (auto simp: mult_right_mono)\n          thus ?case by (simp add: e2_def)\n        qed\n        moreover have \"?le' y\" by simp\n        ultimately obtain S\n        where S: \"open S\" \"y \\<in> S\" \"\\<And>x. x\\<in>S \\<Longrightarrow> x \\<in> {y..<b} \\<Longrightarrow> ?le' x\"\n          unfolding eventually_at_topological\n          by metis\n        from \\<open>open S\\<close> obtain d where d: \"\\<And>x. dist x y < d \\<Longrightarrow> x \\<in> S\" \"d > 0\"\n          by (force simp: dist_commute open_dist ball_def dest!: bspec[OF _ \\<open>y \\<in> S\\<close>])\n        define d' where \"d' = min ((y + b)/2) (y + (d/2))\"\n        have \"d' \\<in> A\"\n          unfolding A_def\n        proof safe\n          show \"a \\<le> d'\" using \\<open>a < y\\<close> \\<open>0 < d\\<close> \\<open>y < b\\<close> by (simp add: d'_def)\n          show \"d' \\<le> b\" using \\<open>y < b\\<close> by (simp add: d'_def min_def)\n          fix x1\n          assume x1: \"x1 \\<in> {a..<d'}\"\n          show \"?le x1\"\n          proof (cases \"x1 < y\")\n            case True\n            then show ?thesis\n              using \\<open>y \\<in> A\\<close> local.leI x1 by auto\n          next\n            case False\n            hence x1': \"x1 \\<in> S\" \"x1 \\<in> {y..<b}\" using x1\n              by (auto simp: d'_def dist_real_def intro!: d)\n            have \"norm (f x1 - f a) \\<le> norm (f x1 - f y) + norm (f y - f a)\"\n              by (rule order_trans[OF _ norm_triangle_ineq]) simp\n            also note S(3)[OF x1']\n            also note le_y\n            finally show \"?le x1\"\n              using False by (auto simp: algebra_simps)\n          qed\n        qed\n        hence \"d' \\<le> y\"\n          unfolding y_def by (rule cSup_upper) simp\n        thus False using \\<open>d > 0\\<close> \\<open>y < b\\<close>\n          by (simp add: d'_def min_def split: if_split_asm)\n      qed\n    qed\n    with le_y have \"norm (f b - f a) \\<le> \\<phi> b - \\<phi> a + e * (b - a + 1)\"\n      by (simp add: algebra_simps)\n  } note * = this\n  show ?thesis\n  proof (rule field_le_epsilon)\n    fix e::real assume \"e > 0\"\n    then show \"norm (f b - f a) \\<le> \\<phi> b - \\<phi> a + e\"\n      using *[of \"e / (b - a + 1)\"] \\<open>a < b\\<close> by simp\n  qed\nqed\n\nlemma differentiable_bound:\n  fixes f :: \"'a::real_normed_vector \\<Rightarrow> 'b::real_normed_vector\"\n  assumes \"convex S\"\n    and derf: \"\\<And>x. x\\<in>S \\<Longrightarrow> (f has_derivative f' x) (at x within S)\"\n    and B: \"\\<And>x. x \\<in> S \\<Longrightarrow> onorm (f' x) \\<le> B\"\n    and x: \"x \\<in> S\"\n    and y: \"y \\<in> S\"\n  shows \"norm (f x - f y) \\<le> B * norm (x - y)\"\nproof -\n  let ?p = \"\\<lambda>u. x + u *\\<^sub>R (y - x)\"\n  let ?\\<phi> = \"\\<lambda>h. h * B * norm (x - y)\"\n  have *: \"x + u *\\<^sub>R (y - x) \\<in> S\" if \"u \\<in> {0..1}\" for u\n  proof -\n    have \"u *\\<^sub>R y = u *\\<^sub>R (y - x) + u *\\<^sub>R x\"\n      by (simp add: scale_right_diff_distrib)\n    then show \"x + u *\\<^sub>R (y - x) \\<in> S\"\n      using that \\<open>convex S\\<close> x y by (simp add: convex_alt)\n        (metis pth_b(2) pth_c(1) scaleR_collapse)\n  qed\n  have \"\\<And>z. z \\<in> (\\<lambda>u. x + u *\\<^sub>R (y - x)) ` {0..1} \\<Longrightarrow>\n          (f has_derivative f' z) (at z within (\\<lambda>u. x + u *\\<^sub>R (y - x)) ` {0..1})\"\n    by (auto intro: * has_derivative_subset [OF derf])\n  then have \"continuous_on (?p ` {0..1}) f\"\n    unfolding continuous_on_eq_continuous_within\n    by (meson has_derivative_continuous)\n  with * have 1: \"continuous_on {0 .. 1} (f \\<circ> ?p)\"\n    by (intro continuous_intros)+\n  {\n    fix u::real assume u: \"u \\<in>{0 <..< 1}\"\n    let ?u = \"?p u\"\n    interpret linear \"(f' ?u)\"\n      using u by (auto intro!: has_derivative_linear derf *)\n    have \"(f \\<circ> ?p has_derivative (f' ?u) \\<circ> (\\<lambda>u. 0 + u *\\<^sub>R (y - x))) (at u within box 0 1)\"\n      by (intro derivative_intros has_derivative_subset [OF derf]) (use u * in auto)\n    hence \"((f \\<circ> ?p) has_vector_derivative f' ?u (y - x)) (at u)\"\n      by (simp add: at_within_open[OF u open_greaterThanLessThan] scaleR has_vector_derivative_def o_def)\n  } note 2 = this\n  have 3: \"continuous_on {0..1} ?\\<phi>\"\n    by (rule continuous_intros)+\n  have 4: \"(?\\<phi> has_vector_derivative B * norm (x - y)) (at u)\" for u\n    by (auto simp: has_vector_derivative_def intro!: derivative_eq_intros)\n  {\n    fix u::real assume u: \"u \\<in>{0 <..< 1}\"\n    let ?u = \"?p u\"\n    interpret bounded_linear \"(f' ?u)\"\n      using u by (auto intro!: has_derivative_bounded_linear derf *)\n    have \"norm (f' ?u (y - x)) \\<le> onorm (f' ?u) * norm (y - x)\"\n      by (rule onorm) (rule bounded_linear)\n    also have \"onorm (f' ?u) \\<le> B\"\n      using u by (auto intro!: assms(3)[rule_format] *)\n    finally have \"norm ((f' ?u) (y - x)) \\<le> B * norm (x - y)\"\n      by (simp add: mult_right_mono norm_minus_commute)\n  } note 5 = this\n  have \"norm (f x - f y) = norm ((f \\<circ> (\\<lambda>u. x + u *\\<^sub>R (y - x))) 1 - (f \\<circ> (\\<lambda>u. x + u *\\<^sub>R (y - x))) 0)\"\n    by (auto simp add: norm_minus_commute)\n  also\n  from differentiable_bound_general[OF zero_less_one 1, OF 3 2 4 5]\n  have \"norm ((f \\<circ> ?p) 1 - (f \\<circ> ?p) 0) \\<le> B * norm (x - y)\"\n    by simp\n  finally show ?thesis .\nqed\n\nlemma field_differentiable_bound:\n  fixes S :: \"'a::real_normed_field 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 (erule df [unfolded has_field_derivative_def])\n  apply (rule onorm_le, simp_all add: norm_mult mult_right_mono assms)\n  done\n\nlemma\n  differentiable_bound_segment:\n  fixes f::\"'a::real_normed_vector \\<Rightarrow> 'b::real_normed_vector\"\n  assumes \"\\<And>t. t \\<in> {0..1} \\<Longrightarrow> x0 + t *\\<^sub>R a \\<in> G\"\n  assumes f': \"\\<And>x. x \\<in> G \\<Longrightarrow> (f has_derivative f' x) (at x within G)\"\n  assumes B: \"\\<And>x. x \\<in> {0..1} \\<Longrightarrow> onorm (f' (x0 + x *\\<^sub>R a)) \\<le> B\"\n  shows \"norm (f (x0 + a) - f x0) \\<le> norm a * B\"\nproof -\n  let ?G = \"(\\<lambda>x. x0 + x *\\<^sub>R a) ` {0..1}\"\n  have \"?G = (+) x0 ` (\\<lambda>x. x *\\<^sub>R a) ` {0..1}\" by auto\n  also have \"convex \\<dots>\"\n    by (intro convex_translation convex_scaled convex_real_interval)\n  finally have \"convex ?G\" .\n  moreover have \"?G \\<subseteq> G\" \"x0 \\<in> ?G\" \"x0 + a \\<in> ?G\" using assms by (auto intro: image_eqI[where x=1])\n  ultimately show ?thesis\n    using has_derivative_subset[OF f' \\<open>?G \\<subseteq> G\\<close>] B\n      differentiable_bound[of \"(\\<lambda>x. x0 + x *\\<^sub>R a) ` {0..1}\" f f' B \"x0 + a\" x0]\n    by (force simp: ac_simps)\nqed\n\nlemma differentiable_bound_linearization:\n  fixes f::\"'a::real_normed_vector \\<Rightarrow> 'b::real_normed_vector\"\n  assumes S: \"\\<And>t. t \\<in> {0..1} \\<Longrightarrow> a + t *\\<^sub>R (b - a) \\<in> S\"\n  assumes f'[derivative_intros]: \"\\<And>x. x \\<in> S \\<Longrightarrow> (f has_derivative f' x) (at x within S)\"\n  assumes B: \"\\<And>x. x \\<in> S \\<Longrightarrow> onorm (f' x - f' x0) \\<le> B\"\n  assumes \"x0 \\<in> S\"\n  shows \"norm (f b - f a - f' x0 (b - a)) \\<le> norm (b - a) * B\"\nproof -\n  define g where [abs_def]: \"g x = f x - f' x0 x\" for x\n  have g: \"\\<And>x. x \\<in> S \\<Longrightarrow> (g has_derivative (\\<lambda>i. f' x i - f' x0 i)) (at x within S)\"\n    unfolding g_def using assms\n    by (auto intro!: derivative_eq_intros\n      bounded_linear.has_derivative[OF has_derivative_bounded_linear, OF f'])\n  from B have \"\\<forall>x\\<in>{0..1}. onorm (\\<lambda>i. f' (a + x *\\<^sub>R (b - a)) i - f' x0 i) \\<le> B\"\n    using assms by (auto simp: fun_diff_def)\n  with differentiable_bound_segment[OF S g] \\<open>x0 \\<in> S\\<close>\n  show ?thesis\n    by (simp add: g_def field_simps linear_diff[OF has_derivative_linear[OF f']])\nqed\n\nlemma vector_differentiable_bound_linearization:\n  fixes f::\"real \\<Rightarrow> 'b::real_normed_vector\"\n  assumes f': \"\\<And>x. x \\<in> S \\<Longrightarrow> (f has_vector_derivative f' x) (at x within S)\"\n  assumes \"closed_segment a b \\<subseteq> S\"\n  assumes B: \"\\<And>x. x \\<in> S \\<Longrightarrow> norm (f' x - f' x0) \\<le> B\"\n  assumes \"x0 \\<in> S\"\n  shows \"norm (f b - f a - (b - a) *\\<^sub>R f' x0) \\<le> norm (b - a) * B\"\n  using assms\n  by (intro differentiable_bound_linearization[of a b S f \"\\<lambda>x h. h *\\<^sub>R f' x\" x0 B])\n    (force simp: closed_segment_real_eq has_vector_derivative_def\n      scaleR_diff_right[symmetric] mult.commute[of B]\n      intro!: onorm_le mult_left_mono)+\n\n\ntext \\<open>In particular.\\<close>\n\nlemma has_derivative_zero_constant:\n  fixes f :: \"'a::real_normed_vector \\<Rightarrow> 'b::real_normed_vector\"\n  assumes \"convex s\"\n    and \"\\<And>x. x \\<in> s \\<Longrightarrow> (f has_derivative (\\<lambda>h. 0)) (at x within s)\"\n  shows \"\\<exists>c. \\<forall>x\\<in>s. f x = c\"\nproof -\n  { fix x y assume \"x \\<in> s\" \"y \\<in> s\"\n    then have \"norm (f x - f y) \\<le> 0 * norm (x - y)\"\n      using assms by (intro differentiable_bound[of s]) (auto simp: onorm_zero)\n    then have \"f x = f y\"\n      by simp }\n  then show ?thesis\n    by metis\nqed\n\nlemma has_field_derivative_zero_constant:\n  assumes \"convex s\" \"\\<And>x. x \\<in> s \\<Longrightarrow> (f has_field_derivative 0) (at x within s)\"\n  shows   \"\\<exists>c. \\<forall>x\\<in>s. f (x) = (c :: 'a :: real_normed_field)\"\nproof (rule has_derivative_zero_constant)\n  have A: \"(*) 0 = (\\<lambda>_. 0 :: 'a)\" by (intro ext) simp\n  fix x assume \"x \\<in> s\" thus \"(f has_derivative (\\<lambda>h. 0)) (at x within s)\"\n    using assms(2)[of x] by (simp add: has_field_derivative_def A)\nqed fact\n\nlemma\n  has_vector_derivative_zero_constant:\n  assumes \"convex s\"\n  assumes \"\\<And>x. x \\<in> s \\<Longrightarrow> (f has_vector_derivative 0) (at x within s)\"\n  obtains c where \"\\<And>x. x \\<in> s \\<Longrightarrow> f x = c\"\n  using has_derivative_zero_constant[of s f] assms\n  by (auto simp: has_vector_derivative_def)\n\nlemma has_derivative_zero_unique:\n  fixes f :: \"'a::real_normed_vector \\<Rightarrow> 'b::real_normed_vector\"\n  assumes \"convex s\"\n    and \"\\<And>x. x \\<in> s \\<Longrightarrow> (f has_derivative (\\<lambda>h. 0)) (at x within s)\"\n    and \"x \\<in> s\" \"y \\<in> s\"\n  shows \"f x = f y\"\n  using has_derivative_zero_constant[OF assms(1,2)] assms(3-) by force\n\nlemma has_derivative_zero_unique_connected:\n  fixes f :: \"'a::real_normed_vector \\<Rightarrow> 'b::real_normed_vector\"\n  assumes \"open s\" \"connected s\"\n  assumes f: \"\\<And>x. x \\<in> s \\<Longrightarrow> (f has_derivative (\\<lambda>x. 0)) (at x)\"\n  assumes \"x \\<in> s\" \"y \\<in> s\"\n  shows \"f x = f y\"\nproof (rule connected_local_const[where f=f, OF \\<open>connected s\\<close> \\<open>x\\<in>s\\<close> \\<open>y\\<in>s\\<close>])\n  show \"\\<forall>a\\<in>s. eventually (\\<lambda>b. f a = f b) (at a within s)\"\n  proof\n    fix a assume \"a \\<in> s\"\n    with \\<open>open s\\<close> obtain e where \"0 < e\" \"ball a e \\<subseteq> s\"\n      by (rule openE)\n    then have \"\\<exists>c. \\<forall>x\\<in>ball a e. f x = c\"\n      by (intro has_derivative_zero_constant)\n         (auto simp: at_within_open[OF _ open_ball] f)\n    with \\<open>0<e\\<close> have \"\\<forall>x\\<in>ball a e. f a = f x\"\n      by auto\n    then show \"eventually (\\<lambda>b. f a = f b) (at a within s)\"\n      using \\<open>0<e\\<close> unfolding eventually_at_topological\n      by (intro exI[of _ \"ball a e\"]) auto\n  qed\nqed\n\nsubsection \\<open>Differentiability of inverse function (most basic form)\\<close>\n\nlemma has_derivative_inverse_basic:\n  fixes f :: \"'a::real_normed_vector \\<Rightarrow> 'b::real_normed_vector\"\n  assumes derf: \"(f has_derivative f') (at (g y))\"\n    and ling': \"bounded_linear g'\"\n    and \"g' \\<circ> f' = id\"\n    and contg: \"continuous (at y) g\"\n    and \"open T\"\n    and \"y \\<in> T\"\n    and fg: \"\\<And>z. z \\<in> T \\<Longrightarrow> f (g z) = z\"\n  shows \"(g has_derivative g') (at y)\"\nproof -\n  interpret f': bounded_linear f'\n    using assms unfolding has_derivative_def by auto\n  interpret g': bounded_linear g'\n    using assms by auto\n  obtain C where C: \"0 < C\" \"\\<And>x. norm (g' x) \\<le> norm x * C\"\n    using bounded_linear.pos_bounded[OF assms(2)] by blast\n  have lem1: \"\\<forall>e>0. \\<exists>d>0. \\<forall>z.\n    norm (z - y) < d \\<longrightarrow> norm (g z - g y - g'(z - y)) \\<le> e * norm (g z - g y)\"\n  proof (intro allI impI)\n    fix e :: real\n    assume \"e > 0\"\n    with C(1) have *: \"e / C > 0\" by auto\n    obtain d0 where  \"0 < d0\" and d0:\n        \"\\<And>u. norm (u - g y) < d0 \\<Longrightarrow> norm (f u - f (g y) - f' (u - g y)) \\<le> e / C * norm (u - g y)\"\n      using derf * unfolding has_derivative_at_alt by blast\n    obtain d1 where \"0 < d1\" and d1: \"\\<And>x. \\<lbrakk>0 < dist x y; dist x y < d1\\<rbrakk> \\<Longrightarrow> dist (g x) (g y) < d0\"\n      using contg \\<open>0 < d0\\<close> unfolding continuous_at Lim_at by blast\n    obtain d2 where \"0 < d2\" and d2: \"\\<And>u. dist u y < d2 \\<Longrightarrow> u \\<in> T\"\n      using \\<open>open T\\<close> \\<open>y \\<in> T\\<close> unfolding open_dist by blast\n    obtain d where d: \"0 < d\" \"d < d1\" \"d < d2\"\n      using field_lbound_gt_zero[OF \\<open>0 < d1\\<close> \\<open>0 < d2\\<close>] by blast\n    show \"\\<exists>d>0. \\<forall>z. norm (z - y) < d \\<longrightarrow> norm (g z - g y - g' (z - y)) \\<le> e * norm (g z - g y)\"\n    proof (intro exI allI impI conjI)\n      fix z\n      assume as: \"norm (z - y) < d\"\n      then have \"z \\<in> T\"\n        using d2 d unfolding dist_norm by auto\n      have \"norm (g z - g y - g' (z - y)) \\<le> norm (g' (f (g z) - y - f' (g z - g y)))\"\n        unfolding g'.diff f'.diff\n        unfolding assms(3)[unfolded o_def id_def, THEN fun_cong] fg[OF \\<open>z\\<in>T\\<close>]\n        by (simp add: norm_minus_commute)\n      also have \"\\<dots> \\<le> norm (f (g z) - y - f' (g z - g y)) * C\"\n        by (rule C(2))\n      also have \"\\<dots> \\<le> (e / C) * norm (g z - g y) * C\"\n      proof -\n        have \"norm (g z - g y) < d0\"\n          by (metis as cancel_comm_monoid_add_class.diff_cancel d(2) \\<open>0 < d0\\<close> d1 diff_gt_0_iff_gt diff_strict_mono dist_norm dist_self zero_less_dist_iff)\n        then show ?thesis\n          by (metis C(1) \\<open>y \\<in> T\\<close> d0 fg mult_le_cancel_iff1)\n      qed\n      also have \"\\<dots> \\<le> e * norm (g z - g y)\"\n        using C by (auto simp add: field_simps)\n      finally show \"norm (g z - g y - g' (z - y)) \\<le> e * norm (g z - g y)\"\n        by simp\n    qed (use d in auto)\n  qed\n  have *: \"(0::real) < 1 / 2\"\n    by auto\n  obtain d where \"0 < d\" and d:\n      \"\\<And>z. norm (z - y) < d \\<Longrightarrow> norm (g z - g y - g' (z - y)) \\<le> 1/2 * norm (g z - g y)\"\n    using lem1 * by blast\n  define B where \"B = C * 2\"\n  have \"B > 0\"\n    unfolding B_def using C by auto\n  have lem2: \"norm (g z - g y) \\<le> B * norm (z - y)\" if z: \"norm(z - y) < d\" for z\n  proof -\n    have \"norm (g z - g y) \\<le> norm(g' (z - y)) + norm ((g z - g y) - g'(z - y))\"\n      by (rule norm_triangle_sub)\n    also have \"\\<dots> \\<le> norm (g' (z - y)) + 1 / 2 * norm (g z - g y)\"\n      by (rule add_left_mono) (use d z in auto)\n    also have \"\\<dots> \\<le> norm (z - y) * C + 1 / 2 * norm (g z - g y)\"\n      by (rule add_right_mono) (use C in auto)\n    finally show \"norm (g z - g y) \\<le> B * norm (z - y)\"\n      unfolding B_def\n      by (auto simp add: field_simps)\n  qed\n  show ?thesis\n    unfolding has_derivative_at_alt\n  proof (intro conjI assms allI impI)\n    fix e :: real\n    assume \"e > 0\"\n    then have *: \"e / B > 0\" by (metis \\<open>B > 0\\<close> divide_pos_pos)\n    obtain d' where \"0 < d'\" and d':\n        \"\\<And>z. norm (z - y) < d' \\<Longrightarrow> norm (g z - g y - g' (z - y)) \\<le> e / B * norm (g z - g y)\"\n      using lem1 * by blast\n    obtain k where k: \"0 < k\" \"k < d\" \"k < d'\"\n      using field_lbound_gt_zero[OF \\<open>0 < d\\<close> \\<open>0 < d'\\<close>] by blast\n    show \"\\<exists>d>0. \\<forall>ya. norm (ya - y) < d \\<longrightarrow> norm (g ya - g y - g' (ya - y)) \\<le> e * norm (ya - y)\"\n    proof (intro exI allI impI conjI)\n      fix z\n      assume as: \"norm (z - y) < k\"\n      then have \"norm (g z - g y - g' (z - y)) \\<le> e / B * norm(g z - g y)\"\n        using d' k by auto\n      also have \"\\<dots> \\<le> e * norm (z - y)\"\n        unfolding times_divide_eq_left pos_divide_le_eq[OF \\<open>B>0\\<close>]\n        using lem2[of z] k as \\<open>e > 0\\<close>\n        by (auto simp add: field_simps)\n      finally show \"norm (g z - g y - g' (z - y)) \\<le> e * norm (z - y)\"\n        by simp\n    qed (use k in auto)\n  qed\nqed\n\ntext\\<^marker>\\<open>tag unimportant\\<close>\\<open>Inverse function theorem for complex derivatives\\<close>\nlemma has_field_derivative_inverse_basic:\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\ntext \\<open>Simply rewrite that based on the domain point x.\\<close>\n\nlemma has_derivative_inverse_basic_x:\n  fixes f :: \"'a::real_normed_vector \\<Rightarrow> 'b::real_normed_vector\"\n  assumes \"(f has_derivative f') (at x)\"\n    and \"bounded_linear g'\"\n    and \"g' \\<circ> f' = id\"\n    and \"continuous (at (f x)) g\"\n    and \"g (f x) = x\"\n    and \"open T\"\n    and \"f x \\<in> T\"\n    and \"\\<And>y. y \\<in> T \\<Longrightarrow> f (g y) = y\"\n  shows \"(g has_derivative g') (at (f x))\"\n  by (rule has_derivative_inverse_basic) (use assms in auto)\n\ntext \\<open>This is the version in Dieudonne', assuming continuity of f and g.\\<close>\n\nlemma has_derivative_inverse_dieudonne:\n  fixes f :: \"'a::real_normed_vector \\<Rightarrow> 'b::real_normed_vector\"\n  assumes \"open S\"\n    and \"open (f ` S)\"\n    and \"continuous_on S f\"\n    and \"continuous_on (f ` S) g\"\n    and \"\\<And>x. x \\<in> S \\<Longrightarrow> g (f x) = x\"\n    and \"x \\<in> S\"\n    and \"(f has_derivative f') (at x)\"\n    and \"bounded_linear g'\"\n    and \"g' \\<circ> f' = id\"\n  shows \"(g has_derivative g') (at (f x))\"\n  apply (rule has_derivative_inverse_basic_x[OF assms(7-9) _ _ assms(2)])\n  using assms(3-6)\n  unfolding continuous_on_eq_continuous_at[OF assms(1)] continuous_on_eq_continuous_at[OF assms(2)]\n  apply auto\n  done\n\ntext \\<open>Here's the simplest way of not assuming much about g.\\<close>\n\nproposition has_derivative_inverse:\n  fixes f :: \"'a::real_normed_vector \\<Rightarrow> 'b::real_normed_vector\"\n  assumes \"compact S\"\n    and \"x \\<in> S\"\n    and fx: \"f x \\<in> interior (f ` S)\"\n    and \"continuous_on S f\"\n    and gf: \"\\<And>y. y \\<in> S \\<Longrightarrow> g (f y) = y\"\n    and \"(f has_derivative f') (at x)\"\n    and \"bounded_linear g'\"\n    and \"g' \\<circ> f' = id\"\n  shows \"(g has_derivative g') (at (f x))\"\nproof -\n  have *: \"\\<And>y. y \\<in> interior (f ` S) \\<Longrightarrow> f (g y) = y\"\n    by (metis gf image_iff interior_subset subsetCE)\n  show ?thesis\n    apply (rule has_derivative_inverse_basic_x[OF assms(6-8), where T = \"interior (f ` S)\"])\n    apply (rule continuous_on_interior[OF _ fx])\n    apply (rule continuous_on_inv)\n    apply (simp_all add: assms *)\n    done\nqed\n\n\ntext \\<open>Invertible derivative continuous at a point implies local\ninjectivity. It's only for this we need continuity of the derivative,\nexcept of course if we want the fact that the inverse derivative is\nalso continuous. So if we know for some other reason that the inverse\nfunction exists, it's OK.\\<close>\n\nproposition has_derivative_locally_injective:\n  fixes f :: \"'n::euclidean_space \\<Rightarrow> 'm::euclidean_space\"\n  assumes \"a \\<in> S\"\n      and \"open S\"\n      and bling: \"bounded_linear g'\"\n      and \"g' \\<circ> f' a = id\"\n      and derf: \"\\<And>x. x \\<in> S \\<Longrightarrow> (f has_derivative f' x) (at x)\"\n      and \"\\<And>e. e > 0 \\<Longrightarrow> \\<exists>d>0. \\<forall>x. dist a x < d \\<longrightarrow> onorm (\\<lambda>v. f' x v - f' a v) < e\"\n  obtains r where \"r > 0\" \"ball a r \\<subseteq> S\" \"inj_on f (ball a r)\"\nproof -\n  interpret bounded_linear g'\n    using assms by auto\n  note f'g' = assms(4)[unfolded id_def o_def,THEN cong]\n  have \"g' (f' a (\\<Sum>Basis)) = (\\<Sum>Basis)\" \"(\\<Sum>Basis) \\<noteq> (0::'n)\"\n    using f'g' by auto\n  then have *: \"0 < onorm g'\"\n    unfolding onorm_pos_lt[OF assms(3)]\n    by fastforce\n  define k where \"k = 1 / onorm g' / 2\"\n  have *: \"k > 0\"\n    unfolding k_def using * by auto\n  obtain d1 where d1:\n      \"0 < d1\"\n      \"\\<And>x. dist a x < d1 \\<Longrightarrow> onorm (\\<lambda>v. f' x v - f' a v) < k\"\n    using assms(6) * by blast\n  from \\<open>open S\\<close> obtain d2 where \"d2 > 0\" \"ball a d2 \\<subseteq> S\"\n    using \\<open>a\\<in>S\\<close> ..\n  obtain d2 where d2: \"0 < d2\" \"ball a d2 \\<subseteq> S\"\n    using \\<open>0 < d2\\<close> \\<open>ball a d2 \\<subseteq> S\\<close> by blast\n  obtain d where d: \"0 < d\" \"d < d1\" \"d < d2\"\n    using field_lbound_gt_zero[OF d1(1) d2(1)] by blast\n  show ?thesis\n  proof\n    show \"0 < d\" by (fact d)\n    show \"ball a d \\<subseteq> S\"\n      using \\<open>d < d2\\<close> \\<open>ball a d2 \\<subseteq> S\\<close> by auto\n    show \"inj_on f (ball a d)\"\n    unfolding inj_on_def\n    proof (intro strip)\n      fix x y\n      assume as: \"x \\<in> ball a d\" \"y \\<in> ball a d\" \"f x = f y\"\n      define ph where [abs_def]: \"ph w = w - g' (f w - f x)\" for w\n      have ph':\"ph = g' \\<circ> (\\<lambda>w. f' a w - (f w - f x))\"\n        unfolding ph_def o_def  by (simp add: diff f'g')\n      have \"norm (ph x - ph y) \\<le> (1 / 2) * norm (x - y)\"\n      proof (rule differentiable_bound[OF convex_ball _ _ as(1-2)])\n        fix u\n        assume u: \"u \\<in> ball a d\"\n        then have \"u \\<in> S\"\n          using d d2 by auto\n        have *: \"(\\<lambda>v. v - g' (f' u v)) = g' \\<circ> (\\<lambda>w. f' a w - f' u w)\"\n          unfolding o_def and diff\n          using f'g' by auto\n        have blin: \"bounded_linear (f' a)\"\n          using \\<open>a \\<in> S\\<close> derf by blast\n        show \"(ph has_derivative (\\<lambda>v. v - g' (f' u v))) (at u within ball a d)\"\n          unfolding ph' * comp_def\n          by (rule \\<open>u \\<in> S\\<close> derivative_eq_intros has_derivative_at_withinI [OF derf] bounded_linear.has_derivative [OF blin]  bounded_linear.has_derivative [OF bling] |simp)+\n        have **: \"bounded_linear (\\<lambda>x. f' u x - f' a x)\" \"bounded_linear (\\<lambda>x. f' a x - f' u x)\"\n          using \\<open>u \\<in> S\\<close> blin bounded_linear_sub derf by auto\n        then have \"onorm (\\<lambda>v. v - g' (f' u v)) \\<le> onorm g' * onorm (\\<lambda>w. f' a w - f' u w)\"\n          by (simp add: \"*\" bounded_linear_axioms onorm_compose)\n        also have \"\\<dots> \\<le> onorm g' * k\"\n          apply (rule mult_left_mono)\n          using d1(2)[of u]\n          using onorm_neg[where f=\"\\<lambda>x. f' u x - f' a x\"] d u onorm_pos_le[OF bling] apply (auto simp: algebra_simps)\n          done\n        also have \"\\<dots> \\<le> 1 / 2\"\n          unfolding k_def by auto\n        finally show \"onorm (\\<lambda>v. v - g' (f' u v)) \\<le> 1 / 2\" .\n      qed\n      moreover have \"norm (ph y - ph x) = norm (y - x)\"\n        by (simp add: as(3) ph_def)\n      ultimately show \"x = y\"\n        unfolding norm_minus_commute by auto\n    qed\n  qed\nqed\n\n\nsubsection \\<open>Uniformly convergent sequence of derivatives\\<close>\n\nlemma has_derivative_sequence_lipschitz_lemma:\n  fixes f :: \"nat \\<Rightarrow> 'a::real_normed_vector \\<Rightarrow> 'b::real_normed_vector\"\n  assumes \"convex S\"\n    and derf: \"\\<And>n x. x \\<in> S \\<Longrightarrow> ((f n) has_derivative (f' n x)) (at x within S)\"\n    and nle: \"\\<And>n x h. \\<lbrakk>n\\<ge>N; x \\<in> S\\<rbrakk> \\<Longrightarrow> norm (f' n x h - g' x h) \\<le> e * norm h\"\n    and \"0 \\<le> e\"\n  shows \"\\<forall>m\\<ge>N. \\<forall>n\\<ge>N. \\<forall>x\\<in>S. \\<forall>y\\<in>S. norm ((f m x - f n x) - (f m y - f n y)) \\<le> 2 * e * norm (x - y)\"\nproof clarify\n  fix m n x y\n  assume as: \"N \\<le> m\" \"N \\<le> n\" \"x \\<in> S\" \"y \\<in> S\"\n  show \"norm ((f m x - f n x) - (f m y - f n y)) \\<le> 2 * e * norm (x - y)\"\n  proof (rule differentiable_bound[where f'=\"\\<lambda>x h. f' m x h - f' n x h\", OF \\<open>convex S\\<close> _ _ as(3-4)])\n    fix x\n    assume \"x \\<in> S\"\n    show \"((\\<lambda>a. f m a - f n a) has_derivative (\\<lambda>h. f' m x h - f' n x h)) (at x within S)\"\n      by (rule derivative_intros derf \\<open>x\\<in>S\\<close>)+\n    show \"onorm (\\<lambda>h. f' m x h - f' n x h) \\<le> 2 * e\"\n    proof (rule onorm_bound)\n      fix h\n      have \"norm (f' m x h - f' n x h) \\<le> norm (f' m x h - g' x h) + norm (f' n x h - g' x h)\"\n        using norm_triangle_ineq[of \"f' m x h - g' x h\" \"- f' n x h + g' x h\"]\n        by (auto simp add: algebra_simps norm_minus_commute)\n      also have \"\\<dots> \\<le> e * norm h + e * norm h\"\n        using nle[OF \\<open>N \\<le> m\\<close> \\<open>x \\<in> S\\<close>, of h] nle[OF \\<open>N \\<le> n\\<close> \\<open>x \\<in> S\\<close>, of h]\n        by (auto simp add: field_simps)\n      finally show \"norm (f' m x h - f' n x h) \\<le> 2 * e * norm h\"\n        by auto\n    qed (simp add: \\<open>0 \\<le> e\\<close>)\n  qed\nqed\n\nlemma has_derivative_sequence_Lipschitz:\n  fixes f :: \"nat \\<Rightarrow> 'a::real_normed_vector \\<Rightarrow> 'b::real_normed_vector\"\n  assumes \"convex S\"\n    and \"\\<And>n x. x \\<in> S \\<Longrightarrow> ((f n) has_derivative (f' n x)) (at x within S)\"\n    and nle: \"\\<And>e. e > 0 \\<Longrightarrow> \\<forall>\\<^sub>F n in sequentially. \\<forall>x\\<in>S. \\<forall>h. norm (f' n x h - g' x h) \\<le> e * norm h\"\n    and \"e > 0\"\n  shows \"\\<exists>N. \\<forall>m\\<ge>N. \\<forall>n\\<ge>N. \\<forall>x\\<in>S. \\<forall>y\\<in>S.\n    norm ((f m x - f n x) - (f m y - f n y)) \\<le> e * norm (x - y)\"\nproof -\n  have *: \"2 * (e/2) = e\"\n    using \\<open>e > 0\\<close> by auto\n  obtain N where \"\\<forall>n\\<ge>N. \\<forall>x\\<in>S. \\<forall>h. norm (f' n x h - g' x h) \\<le> (e/2) * norm h\"\n    using nle \\<open>e > 0\\<close>\n    unfolding eventually_sequentially\n    by (metis less_divide_eq_numeral1(1) mult_zero_left)\n  then show \"\\<exists>N. \\<forall>m\\<ge>N. \\<forall>n\\<ge>N. \\<forall>x\\<in>S. \\<forall>y\\<in>S. norm (f m x - f n x - (f m y - f n y)) \\<le> e * norm (x - y)\"\n    apply (rule_tac x=N in exI)\n    apply (rule has_derivative_sequence_lipschitz_lemma[where e=\"e/2\", unfolded *])\n    using assms \\<open>e > 0\\<close>\n    apply auto\n    done\nqed\n\nproposition has_derivative_sequence:\n  fixes f :: \"nat \\<Rightarrow> 'a::real_normed_vector \\<Rightarrow> 'b::banach\"\n  assumes \"convex S\"\n    and derf: \"\\<And>n x. x \\<in> S \\<Longrightarrow> ((f n) has_derivative (f' n x)) (at x within S)\"\n    and nle: \"\\<And>e. e > 0 \\<Longrightarrow> \\<forall>\\<^sub>F n in sequentially. \\<forall>x\\<in>S. \\<forall>h. norm (f' n x h - g' x h) \\<le> e * norm h\"\n    and \"x0 \\<in> S\"\n    and lim: \"((\\<lambda>n. f n x0) \\<longlongrightarrow> l) sequentially\"\n  shows \"\\<exists>g. \\<forall>x\\<in>S. (\\<lambda>n. f n x) \\<longlonglongrightarrow> g x \\<and> (g has_derivative g'(x)) (at x within S)\"\nproof -\n  have lem1: \"\\<And>e. e > 0 \\<Longrightarrow> \\<exists>N. \\<forall>m\\<ge>N. \\<forall>n\\<ge>N. \\<forall>x\\<in>S. \\<forall>y\\<in>S.\n      norm ((f m x - f n x) - (f m y - f n y)) \\<le> e * norm (x - y)\"\n    using assms(1,2,3) by (rule has_derivative_sequence_Lipschitz)\n  have \"\\<exists>g. \\<forall>x\\<in>S. ((\\<lambda>n. f n x) \\<longlongrightarrow> g x) sequentially\"\n  proof (intro ballI bchoice)\n    fix x\n    assume \"x \\<in> S\"\n    show \"\\<exists>y. (\\<lambda>n. f n x) \\<longlonglongrightarrow> y\"\n    unfolding convergent_eq_Cauchy\n    proof (cases \"x = x0\")\n      case True\n      then show \"Cauchy (\\<lambda>n. f n x)\"\n        using LIMSEQ_imp_Cauchy[OF lim] by auto\n    next\n      case False\n      show \"Cauchy (\\<lambda>n. f n x)\"\n        unfolding Cauchy_def\n      proof (intro allI impI)\n        fix e :: real\n        assume \"e > 0\"\n        hence *: \"e / 2 > 0\" \"e / 2 / norm (x - x0) > 0\" using False by auto\n        obtain M where M: \"\\<forall>m\\<ge>M. \\<forall>n\\<ge>M. dist (f m x0) (f n x0) < e / 2\"\n          using LIMSEQ_imp_Cauchy[OF lim] * unfolding Cauchy_def by blast\n        obtain N where N:\n          \"\\<forall>m\\<ge>N. \\<forall>n\\<ge>N.\n            \\<forall>u\\<in>S. \\<forall>y\\<in>S. norm (f m u - f n u - (f m y - f n y)) \\<le>\n              e / 2 / norm (x - x0) * norm (u - y)\"\n        using lem1 *(2) by blast\n        show \"\\<exists>M. \\<forall>m\\<ge>M. \\<forall>n\\<ge>M. dist (f m x) (f n x) < e\"\n        proof (intro exI allI impI)\n          fix m n\n          assume as: \"max M N \\<le>m\" \"max M N\\<le>n\"\n          have \"dist (f m x) (f n x) \\<le> norm (f m x0 - f n x0) + norm (f m x - f n x - (f m x0 - f n x0))\"\n            unfolding dist_norm\n            by (rule norm_triangle_sub)\n          also have \"\\<dots> \\<le> norm (f m x0 - f n x0) + e / 2\"\n            using N \\<open>x\\<in>S\\<close> \\<open>x0\\<in>S\\<close> as False by fastforce\n          also have \"\\<dots> < e / 2 + e / 2\"\n            by (rule add_strict_right_mono) (use as M in \\<open>auto simp: dist_norm\\<close>)\n          finally show \"dist (f m x) (f n x) < e\"\n            by auto\n        qed\n      qed\n    qed\n  qed\n  then obtain g where g: \"\\<forall>x\\<in>S. (\\<lambda>n. f n x) \\<longlonglongrightarrow> g x\" ..\n  have lem2: \"\\<exists>N. \\<forall>n\\<ge>N. \\<forall>x\\<in>S. \\<forall>y\\<in>S. norm ((f n x - f n y) - (g x - g y)) \\<le> e * norm (x - y)\" if \"e > 0\" for e\n  proof -\n    obtain N where\n      N: \"\\<forall>m\\<ge>N. \\<forall>n\\<ge>N. \\<forall>x\\<in>S. \\<forall>y\\<in>S. norm (f m x - f n x - (f m y - f n y)) \\<le> e * norm (x - y)\"\n      using lem1 \\<open>e > 0\\<close> by blast\n    show \"\\<exists>N. \\<forall>n\\<ge>N. \\<forall>x\\<in>S. \\<forall>y\\<in>S. norm (f n x - f n y - (g x - g y)) \\<le> e * norm (x - y)\"\n    proof (intro exI ballI allI impI)\n      fix n x y\n      assume as: \"N \\<le> n\" \"x \\<in> S\" \"y \\<in> S\"\n      have \"((\\<lambda>m. norm (f n x - f n y - (f m x - f m y))) \\<longlongrightarrow> norm (f n x - f n y - (g x - g y))) sequentially\"\n        by (intro tendsto_intros g[rule_format] as)\n      moreover have \"eventually (\\<lambda>m. norm (f n x - f n y - (f m x - f m y)) \\<le> e * norm (x - y)) sequentially\"\n        unfolding eventually_sequentially\n      proof (intro exI allI impI)\n        fix m\n        assume \"N \\<le> m\"\n        then show \"norm (f n x - f n y - (f m x - f m y)) \\<le> e * norm (x - y)\"\n          using N as by (auto simp add: algebra_simps)\n      qed\n      ultimately show \"norm (f n x - f n y - (g x - g y)) \\<le> e * norm (x - y)\"\n        by (simp add: tendsto_upperbound)\n    qed\n  qed\n  have \"\\<forall>x\\<in>S. ((\\<lambda>n. f n x) \\<longlongrightarrow> g x) sequentially \\<and> (g has_derivative g' x) (at x within S)\"\n    unfolding has_derivative_within_alt2\n  proof (intro ballI conjI allI impI)\n    fix x\n    assume \"x \\<in> S\"\n    then show \"(\\<lambda>n. f n x) \\<longlonglongrightarrow> g x\"\n      by (simp add: g)\n    have tog': \"(\\<lambda>n. f' n x u) \\<longlonglongrightarrow> g' x u\" for u\n      unfolding filterlim_def le_nhds_metric_le eventually_filtermap dist_norm\n    proof (intro allI impI)\n      fix e :: real\n      assume \"e > 0\"\n      show \"eventually (\\<lambda>n. norm (f' n x u - g' x u) \\<le> e) sequentially\"\n      proof (cases \"u = 0\")\n        case True\n        have \"eventually (\\<lambda>n. norm (f' n x u - g' x u) \\<le> e * norm u) sequentially\"\n          using nle \\<open>0 < e\\<close> \\<open>x \\<in> S\\<close> by (fast elim: eventually_mono)\n        then show ?thesis\n          using \\<open>u = 0\\<close> \\<open>0 < e\\<close> by (auto elim: eventually_mono)\n      next\n        case False\n        with \\<open>0 < e\\<close> have \"0 < e / norm u\" by simp\n        then have \"eventually (\\<lambda>n. norm (f' n x u - g' x u) \\<le> e / norm u * norm u) sequentially\"\n          using nle \\<open>x \\<in> S\\<close> by (fast elim: eventually_mono)\n        then show ?thesis\n          using \\<open>u \\<noteq> 0\\<close> by simp\n      qed\n    qed\n    show \"bounded_linear (g' x)\"\n    proof\n      fix x' y z :: 'a\n      fix c :: real\n      note lin = assms(2)[rule_format,OF \\<open>x\\<in>S\\<close>,THEN has_derivative_bounded_linear]\n      show \"g' x (c *\\<^sub>R x') = c *\\<^sub>R g' x x'\"\n        apply (rule tendsto_unique[OF trivial_limit_sequentially tog'])\n        unfolding lin[THEN bounded_linear.linear, THEN linear_cmul]\n        apply (intro tendsto_intros tog')\n        done\n      show \"g' x (y + z) = g' x y + g' x z\"\n        apply (rule tendsto_unique[OF trivial_limit_sequentially tog'])\n        unfolding lin[THEN bounded_linear.linear, THEN linear_add]\n        apply (rule tendsto_add)\n        apply (rule tog')+\n        done\n      obtain N where N: \"\\<forall>h. norm (f' N x h - g' x h) \\<le> 1 * norm h\"\n        using nle \\<open>x \\<in> S\\<close> unfolding eventually_sequentially by (fast intro: zero_less_one)\n      have \"bounded_linear (f' N x)\"\n        using derf \\<open>x \\<in> S\\<close> by fast\n      from bounded_linear.bounded [OF this]\n      obtain K where K: \"\\<forall>h. norm (f' N x h) \\<le> norm h * K\" ..\n      {\n        fix h\n        have \"norm (g' x h) = norm (f' N x h - (f' N x h - g' x h))\"\n          by simp\n        also have \"\\<dots> \\<le> norm (f' N x h) + norm (f' N x h - g' x h)\"\n          by (rule norm_triangle_ineq4)\n        also have \"\\<dots> \\<le> norm h * K + 1 * norm h\"\n          using N K by (fast intro: add_mono)\n        finally have \"norm (g' x h) \\<le> norm h * (K + 1)\"\n          by (simp add: ring_distribs)\n      }\n      then show \"\\<exists>K. \\<forall>h. norm (g' x h) \\<le> norm h * K\" by fast\n    qed\n    show \"eventually (\\<lambda>y. norm (g y - g x - g' x (y - x)) \\<le> e * norm (y - x)) (at x within S)\"\n      if \"e > 0\" for e\n    proof -\n      have *: \"e / 3 > 0\"\n        using that by auto\n      obtain N1 where N1: \"\\<forall>n\\<ge>N1. \\<forall>x\\<in>S. \\<forall>h. norm (f' n x h - g' x h) \\<le> e / 3 * norm h\"\n        using nle * unfolding eventually_sequentially by blast\n      obtain N2 where\n          N2[rule_format]: \"\\<forall>n\\<ge>N2. \\<forall>x\\<in>S. \\<forall>y\\<in>S. norm (f n x - f n y - (g x - g y)) \\<le> e / 3 * norm (x - y)\"\n        using lem2 * by blast\n      let ?N = \"max N1 N2\"\n      have \"eventually (\\<lambda>y. norm (f ?N y - f ?N x - f' ?N x (y - x)) \\<le> e / 3 * norm (y - x)) (at x within S)\"\n        using derf[unfolded has_derivative_within_alt2] and \\<open>x \\<in> S\\<close> and * by fast\n      moreover have \"eventually (\\<lambda>y. y \\<in> S) (at x within S)\"\n        unfolding eventually_at by (fast intro: zero_less_one)\n      ultimately show \"\\<forall>\\<^sub>F y in at x within S. norm (g y - g x - g' x (y - x)) \\<le> e * norm (y - x)\"\n      proof (rule eventually_elim2)\n        fix y\n        assume \"y \\<in> S\"\n        assume \"norm (f ?N y - f ?N x - f' ?N x (y - x)) \\<le> e / 3 * norm (y - x)\"\n        moreover have \"norm (g y - g x - (f ?N y - f ?N x)) \\<le> e / 3 * norm (y - x)\"\n          using N2[OF _ \\<open>y \\<in> S\\<close> \\<open>x \\<in> S\\<close>]\n          by (simp add: norm_minus_commute)\n        ultimately have \"norm (g y - g x - f' ?N x (y - x)) \\<le> 2 * e / 3 * norm (y - x)\"\n          using norm_triangle_le[of \"g y - g x - (f ?N y - f ?N x)\" \"f ?N y - f ?N x - f' ?N x (y - x)\" \"2 * e / 3 * norm (y - x)\"]\n          by (auto simp add: algebra_simps)\n        moreover\n        have \" norm (f' ?N x (y - x) - g' x (y - x)) \\<le> e / 3 * norm (y - x)\"\n          using N1 \\<open>x \\<in> S\\<close> by auto\n        ultimately show \"norm (g y - g x - g' x (y - x)) \\<le> e * norm (y - x)\"\n          using norm_triangle_le[of \"g y - g x - f' (max N1 N2) x (y - x)\" \"f' (max N1 N2) x (y - x) - g' x (y - x)\"]\n          by (auto simp add: algebra_simps)\n      qed\n    qed\n  qed\n  then show ?thesis by fast\nqed\n\ntext \\<open>Can choose to line up antiderivatives if we want.\\<close>\n\nlemma has_antiderivative_sequence:\n  fixes f :: \"nat \\<Rightarrow> 'a::real_normed_vector \\<Rightarrow> 'b::banach\"\n  assumes \"convex S\"\n    and der: \"\\<And>n x. x \\<in> S \\<Longrightarrow> ((f n) has_derivative (f' n x)) (at x within S)\"\n    and no: \"\\<And>e. e > 0 \\<Longrightarrow> \\<forall>\\<^sub>F n in sequentially.\n       \\<forall>x\\<in>S. \\<forall>h. norm (f' n x h - g' x h) \\<le> e * norm h\"\n  shows \"\\<exists>g. \\<forall>x\\<in>S. (g has_derivative g' x) (at x within S)\"\nproof (cases \"S = {}\")\n  case False\n  then obtain a where \"a \\<in> S\"\n    by auto\n  have *: \"\\<And>P Q. \\<exists>g. \\<forall>x\\<in>S. P g x \\<and> Q g x \\<Longrightarrow> \\<exists>g. \\<forall>x\\<in>S. Q g x\"\n    by auto\n  show ?thesis\n    apply (rule *)\n    apply (rule has_derivative_sequence [OF \\<open>convex S\\<close> _ no, of \"\\<lambda>n x. f n x + (f 0 a - f n a)\"])\n       apply (metis assms(2) has_derivative_add_const)\n    using \\<open>a \\<in> S\\<close> \n      apply auto\n    done\nqed auto\n\nlemma has_antiderivative_limit:\n  fixes g' :: \"'a::real_normed_vector \\<Rightarrow> 'a \\<Rightarrow> 'b::banach\"\n  assumes \"convex S\"\n    and \"\\<And>e. e>0 \\<Longrightarrow> \\<exists>f f'. \\<forall>x\\<in>S.\n           (f has_derivative (f' x)) (at x within S) \\<and> (\\<forall>h. norm (f' x h - g' x h) \\<le> e * norm h)\"\n  shows \"\\<exists>g. \\<forall>x\\<in>S. (g has_derivative g' x) (at x within S)\"\nproof -\n  have *: \"\\<forall>n. \\<exists>f f'. \\<forall>x\\<in>S.\n    (f has_derivative (f' x)) (at x within S) \\<and>\n    (\\<forall>h. norm(f' x h - g' x h) \\<le> inverse (real (Suc n)) * norm h)\"\n    by (simp add: assms(2))\n  obtain f where\n    *: \"\\<And>x. \\<exists>f'. \\<forall>xa\\<in>S. (f x has_derivative f' xa) (at xa within S) \\<and>\n        (\\<forall>h. norm (f' xa h - g' xa h) \\<le> inverse (real (Suc x)) * norm h)\"\n    using * by metis\n  obtain f' where\n    f': \"\\<And>x. \\<forall>z\\<in>S. (f x has_derivative f' x z) (at z within S) \\<and>\n            (\\<forall>h. norm (f' x z h - g' z h) \\<le> inverse (real (Suc x)) * norm h)\"\n    using * by metis\n  show ?thesis\n  proof (rule has_antiderivative_sequence[OF \\<open>convex S\\<close>, of f f'])\n    fix e :: real\n    assume \"e > 0\"\n    obtain N where N: \"inverse (real (Suc N)) < e\"\n      using reals_Archimedean[OF \\<open>e>0\\<close>] ..\n    show \"\\<forall>\\<^sub>F n in sequentially. \\<forall>x\\<in>S.  \\<forall>h. norm (f' n x h - g' x h) \\<le> e * norm h\"\n        unfolding eventually_sequentially\n    proof (intro exI allI ballI impI)\n      fix n x h\n      assume n: \"N \\<le> n\" and x: \"x \\<in> S\"\n      have *: \"inverse (real (Suc n)) \\<le> e\"\n        apply (rule order_trans[OF _ N[THEN less_imp_le]])\n        using n apply (auto simp add: field_simps)\n        done\n      show \"norm (f' n x h - g' x h) \\<le> e * norm h\"\n        by (meson \"*\" mult_right_mono norm_ge_zero order.trans x f')\n    qed\n  qed (use f' in auto)\nqed\n\n\nsubsection \\<open>Differentiation of a series\\<close>\n\nproposition has_derivative_series:\n  fixes f :: \"nat \\<Rightarrow> 'a::real_normed_vector \\<Rightarrow> 'b::banach\"\n  assumes \"convex S\"\n    and \"\\<And>n x. x \\<in> S \\<Longrightarrow> ((f n) has_derivative (f' n x)) (at x within S)\"\n    and \"\\<And>e. e>0 \\<Longrightarrow> \\<forall>\\<^sub>F n in sequentially. \\<forall>x\\<in>S. \\<forall>h. norm (sum (\\<lambda>i. f' i x h) {..<n} - g' x h) \\<le> e * norm h\"\n    and \"x \\<in> S\"\n    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_derivative g' x) (at x within S)\"\n  unfolding sums_def\n  apply (rule has_derivative_sequence[OF assms(1) _ assms(3)])\n  apply (metis assms(2) has_derivative_sum)\n  using assms(4-5)\n  unfolding sums_def\n  apply auto\n  done\n\nlemma has_field_derivative_series:\n  fixes f :: \"nat \\<Rightarrow> ('a :: {real_normed_field,banach}) \\<Rightarrow> 'a\"\n  assumes \"convex S\"\n  assumes \"\\<And>n x. x \\<in> S \\<Longrightarrow> (f n has_field_derivative f' n x) (at x within S)\"\n  assumes \"uniform_limit S (\\<lambda>n x. \\<Sum>i<n. f' i x) g' sequentially\"\n  assumes \"x0 \\<in> S\" \"summable (\\<lambda>n. f n x0)\"\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)\"\nunfolding has_field_derivative_def\nproof (rule has_derivative_series)\n  show \"\\<forall>\\<^sub>F n in sequentially.\n       \\<forall>x\\<in>S. \\<forall>h. norm ((\\<Sum>i<n. f' i x * h) - g' x * h) \\<le> e * norm h\" if \"e > 0\" for e\n    unfolding eventually_sequentially\n  proof -\n    from that assms(3) obtain N where N: \"\\<And>n x. n \\<ge> N \\<Longrightarrow> x \\<in> S \\<Longrightarrow> norm ((\\<Sum>i<n. f' i x) - g' x) < e\"\n      unfolding uniform_limit_iff eventually_at_top_linorder dist_norm by blast\n    {\n      fix n :: nat and x h :: 'a assume nx: \"n \\<ge> N\" \"x \\<in> S\"\n      have \"norm ((\\<Sum>i<n. f' i x * h) - g' x * h) = norm ((\\<Sum>i<n. f' i x) - g' x) * norm h\"\n        by (simp add: norm_mult [symmetric] ring_distribs sum_distrib_right)\n      also from N[OF nx] have \"norm ((\\<Sum>i<n. f' i x) - g' x) \\<le> e\" by simp\n      hence \"norm ((\\<Sum>i<n. f' i x) - g' x) * norm h \\<le> e * norm h\"\n        by (intro mult_right_mono) simp_all\n      finally have \"norm ((\\<Sum>i<n. f' i x * h) - g' x * h) \\<le> e * norm h\" .\n    }\n    thus \"\\<exists>N. \\<forall>n\\<ge>N. \\<forall>x\\<in>S. \\<forall>h. norm ((\\<Sum>i<n. f' i x * h) - g' x * h) \\<le> e * norm h\" by blast\n  qed\nqed (use assms in \\<open>auto simp: has_field_derivative_def\\<close>)\n\nlemma has_field_derivative_series':\n  fixes f :: \"nat \\<Rightarrow> ('a :: {real_normed_field,banach}) \\<Rightarrow> 'a\"\n  assumes \"convex S\"\n  assumes \"\\<And>n x. x \\<in> S \\<Longrightarrow> (f n has_field_derivative f' n x) (at x within S)\"\n  assumes \"uniformly_convergent_on S (\\<lambda>n x. \\<Sum>i<n. f' i x)\"\n  assumes \"x0 \\<in> S\" \"summable (\\<lambda>n. f n x0)\" \"x \\<in> interior S\"\n  shows   \"summable (\\<lambda>n. f n x)\" \"((\\<lambda>x. \\<Sum>n. f n x) has_field_derivative (\\<Sum>n. f' n x)) (at x)\"\nproof -\n  from \\<open>x \\<in> interior S\\<close> have \"x \\<in> S\" using interior_subset by blast\n  define g' where [abs_def]: \"g' x = (\\<Sum>i. f' i x)\" for x\n  from assms(3) have \"uniform_limit S (\\<lambda>n x. \\<Sum>i<n. f' i x) g' sequentially\"\n    by (simp add: uniformly_convergent_uniform_limit_iff suminf_eq_lim g'_def)\n  from has_field_derivative_series[OF assms(1,2) this assms(4,5)] obtain g where g:\n    \"\\<And>x. x \\<in> S \\<Longrightarrow> (\\<lambda>n. f n x) sums g x\"\n    \"\\<And>x. x \\<in> S \\<Longrightarrow> (g has_field_derivative g' x) (at x within S)\" by blast\n  from g(1)[OF \\<open>x \\<in> S\\<close>] show \"summable (\\<lambda>n. f n x)\" by (simp add: sums_iff)\n  from g(2)[OF \\<open>x \\<in> S\\<close>] \\<open>x \\<in> interior S\\<close> have \"(g has_field_derivative g' x) (at x)\"\n    by (simp add: at_within_interior[of x S])\n  also have \"(g has_field_derivative g' x) (at x) \\<longleftrightarrow>\n                ((\\<lambda>x. \\<Sum>n. f n x) has_field_derivative g' x) (at x)\"\n    using eventually_nhds_in_nhd[OF \\<open>x \\<in> interior S\\<close>] interior_subset[of S] g(1)\n    by (intro DERIV_cong_ev) (auto elim!: eventually_mono simp: sums_iff)\n  finally show \"((\\<lambda>x. \\<Sum>n. f n x) has_field_derivative g' x) (at x)\" .\nqed\n\nlemma differentiable_series:\n  fixes f :: \"nat \\<Rightarrow> ('a :: {real_normed_field,banach}) \\<Rightarrow> 'a\"\n  assumes \"convex S\" \"open S\"\n  assumes \"\\<And>n x. x \\<in> S \\<Longrightarrow> (f n has_field_derivative f' n x) (at x)\"\n  assumes \"uniformly_convergent_on S (\\<lambda>n x. \\<Sum>i<n. f' i x)\"\n  assumes \"x0 \\<in> S\" \"summable (\\<lambda>n. f n x0)\" and x: \"x \\<in> S\"\n  shows   \"summable (\\<lambda>n. f n x)\" and \"(\\<lambda>x. \\<Sum>n. f n x) differentiable (at x)\"\nproof -\n  from assms(4) obtain g' where A: \"uniform_limit S (\\<lambda>n x. \\<Sum>i<n. f' i x) g' sequentially\"\n    unfolding uniformly_convergent_on_def by blast\n  from x and \\<open>open S\\<close> have S: \"at x within S = at x\" by (rule at_within_open)\n  have \"\\<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)\"\n    by (intro has_field_derivative_series[of S f f' g' x0] assms A has_field_derivative_at_within)\n  then obtain g where g: \"\\<And>x. x \\<in> S \\<Longrightarrow> (\\<lambda>n. f n x) sums g x\"\n    \"\\<And>x. x \\<in> S \\<Longrightarrow> (g has_field_derivative g' x) (at x within S)\" by blast\n  from g[OF x] show \"summable (\\<lambda>n. f n x)\" by (auto simp: summable_def)\n  from g(2)[OF x] have g': \"(g has_derivative (*) (g' x)) (at x)\"\n    by (simp add: has_field_derivative_def S)\n  have \"((\\<lambda>x. \\<Sum>n. f n x) has_derivative (*) (g' x)) (at x)\"\n    by (rule has_derivative_transform_within_open[OF g' \\<open>open S\\<close> x])\n       (insert g, auto simp: sums_iff)\n  thus \"(\\<lambda>x. \\<Sum>n. f n x) differentiable (at x)\" unfolding differentiable_def\n    by (auto simp: summable_def differentiable_def has_field_derivative_def)\nqed\n\nlemma differentiable_series':\n  fixes f :: \"nat \\<Rightarrow> ('a :: {real_normed_field,banach}) \\<Rightarrow> 'a\"\n  assumes \"convex S\" \"open S\"\n  assumes \"\\<And>n x. x \\<in> S \\<Longrightarrow> (f n has_field_derivative f' n x) (at x)\"\n  assumes \"uniformly_convergent_on S (\\<lambda>n x. \\<Sum>i<n. f' i x)\"\n  assumes \"x0 \\<in> S\" \"summable (\\<lambda>n. f n x0)\"\n  shows   \"(\\<lambda>x. \\<Sum>n. f n x) differentiable (at x0)\"\n  using differentiable_series[OF assms, of x0] \\<open>x0 \\<in> S\\<close> by blast+\n\nsubsection \\<open>Derivative as a vector\\<close>\n\ntext \\<open>Considering derivative \\<^typ>\\<open>real \\<Rightarrow> 'b::real_normed_vector\\<close> as a vector.\\<close>\n\ndefinition \"vector_derivative f net = (SOME f'. (f has_vector_derivative f') net)\"\n\nlemma vector_derivative_unique_within:\n  assumes not_bot: \"at x within S \\<noteq> bot\"\n    and f': \"(f has_vector_derivative f') (at x within S)\"\n    and f'': \"(f has_vector_derivative f'') (at x within S)\"\n  shows \"f' = f''\"\nproof -\n  have \"(\\<lambda>x. x *\\<^sub>R f') = (\\<lambda>x. x *\\<^sub>R f'')\"\n  proof (rule frechet_derivative_unique_within, simp_all)\n    show \"\\<exists>d. d \\<noteq> 0 \\<and> \\<bar>d\\<bar> < e \\<and> x + d \\<in> S\" if \"0 < e\"  for e\n    proof -\n      from that\n      obtain x' where \"x' \\<in> S\" \"x' \\<noteq> x\" \"\\<bar>x' - x\\<bar> < e\"\n        using islimpt_approachable_real[of x S] not_bot\n        by (auto simp add: trivial_limit_within)\n      then show ?thesis\n        using eq_iff_diff_eq_0 by fastforce\n    qed\n  qed (use f' f'' in \\<open>auto simp: has_vector_derivative_def\\<close>)\n  then show ?thesis\n    unfolding fun_eq_iff by (metis scaleR_one)\nqed\n\nlemma vector_derivative_unique_at:\n  \"(f has_vector_derivative f') (at x) \\<Longrightarrow> (f has_vector_derivative f'') (at x) \\<Longrightarrow> f' = f''\"\n  by (rule vector_derivative_unique_within) auto\n\nlemma differentiableI_vector: \"(f has_vector_derivative y) F \\<Longrightarrow> f differentiable F\"\n  by (auto simp: differentiable_def has_vector_derivative_def)\n\nproposition vector_derivative_works:\n  \"f differentiable net \\<longleftrightarrow> (f has_vector_derivative (vector_derivative f net)) net\"\n    (is \"?l = ?r\")\nproof\n  assume ?l\n  obtain f' where f': \"(f has_derivative f') net\"\n    using \\<open>?l\\<close> unfolding differentiable_def ..\n  then interpret bounded_linear f'\n    by auto\n  show ?r\n    unfolding vector_derivative_def has_vector_derivative_def\n    by (rule someI[of _ \"f' 1\"]) (simp add: scaleR[symmetric] f')\nqed (auto simp: vector_derivative_def has_vector_derivative_def differentiable_def)\n\nlemma vector_derivative_within:\n  assumes not_bot: \"at x within S \\<noteq> bot\" and y: \"(f has_vector_derivative y) (at x within S)\"\n  shows \"vector_derivative f (at x within S) = y\"\n  using y\n  by (intro vector_derivative_unique_within[OF not_bot vector_derivative_works[THEN iffD1] y])\n     (auto simp: differentiable_def has_vector_derivative_def)\n\nlemma deriv_of_real [simp]: \n  \"at x within A \\<noteq> bot \\<Longrightarrow> vector_derivative of_real (at x within A) = 1\"\n  by (auto intro!: vector_derivative_within derivative_eq_intros)\n\nlemma frechet_derivative_eq_vector_derivative:\n  assumes \"f differentiable (at x)\"\n    shows  \"(frechet_derivative f (at x)) = (\\<lambda>r. r *\\<^sub>R vector_derivative f (at x))\"\nusing assms\nby (auto simp: differentiable_iff_scaleR vector_derivative_def has_vector_derivative_def\n         intro: someI frechet_derivative_at [symmetric])\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 has_vector_derivative_cong_ev:\n  assumes *: \"eventually (\\<lambda>x. x \\<in> S \\<longrightarrow> f x = g x) (nhds x)\" \"f x = g x\"\n  shows \"(f has_vector_derivative f') (at x within S) = (g has_vector_derivative f') (at x within S)\"\n  unfolding has_vector_derivative_def has_derivative_def\n  using *\n  apply (cases \"at x within S \\<noteq> bot\")\n  apply (intro refl conj_cong filterlim_cong)\n  apply (auto simp: Lim_ident_at eventually_at_filter elim: eventually_mono)\n  done\n\nlemma vector_derivative_cong_eq:\n  assumes \"eventually (\\<lambda>x. x \\<in> A \\<longrightarrow> f x = g x) (nhds x)\" \"x = y\" \"A = B\" \"x \\<in> A\"\n  shows   \"vector_derivative f (at x within A) = vector_derivative g (at y within B)\"\nproof -\n  have \"f x = g x\"\n    using assms eventually_nhds_x_imp_x by blast\n  hence \"(\\<lambda>D. (f has_vector_derivative D) (at x within A)) = \n           (\\<lambda>D. (g has_vector_derivative D) (at x within A))\" using assms\n    by (intro ext has_vector_derivative_cong_ev refl assms) simp_all\n  thus ?thesis by (simp add: vector_derivative_def assms)\nqed\n  \nlemma islimpt_closure_open:\n  fixes s :: \"'a::perfect_space set\"\n  assumes \"open s\" and t: \"t = closure s\" \"x \\<in> t\"\n  shows \"x islimpt t\"\nproof cases\n  assume \"x \\<in> s\"\n  { fix T assume \"x \\<in> T\" \"open T\"\n    then have \"open (s \\<inter> T)\"\n      using \\<open>open s\\<close> by auto\n    then have \"s \\<inter> T \\<noteq> {x}\"\n      using not_open_singleton[of x] by auto\n    with \\<open>x \\<in> T\\<close> \\<open>x \\<in> s\\<close> have \"\\<exists>y\\<in>t. y \\<in> T \\<and> y \\<noteq> x\"\n      using closure_subset[of s] by (auto simp: t) }\n  then show ?thesis\n    by (auto intro!: islimptI)\nnext\n  assume \"x \\<notin> s\" with t show ?thesis\n    unfolding t closure_def by (auto intro: islimpt_subset)\nqed\n\nlemma vector_derivative_unique_within_closed_interval:\n  assumes ab: \"a < b\" \"x \\<in> cbox a b\"\n  assumes D: \"(f has_vector_derivative f') (at x within cbox a b)\" \"(f has_vector_derivative f'') (at x within cbox a b)\"\n  shows \"f' = f''\"\n  using ab\n  by (intro vector_derivative_unique_within[OF _ D])\n     (auto simp: trivial_limit_within intro!: islimpt_closure_open[where s=\"{a <..< b}\"])\n\nlemma vector_derivative_at:\n  \"(f has_vector_derivative f') (at x) \\<Longrightarrow> vector_derivative f (at x) = f'\"\n  by (intro vector_derivative_within at_neq_bot)\n\nlemma has_vector_derivative_id_at [simp]: \"vector_derivative (\\<lambda>x. x) (at a) = 1\"\n  by (simp add: vector_derivative_at)\n\nlemma vector_derivative_minus_at [simp]:\n  \"f differentiable at a\n   \\<Longrightarrow> vector_derivative (\\<lambda>x. - f x) (at a) = - vector_derivative f (at a)\"\n  by (simp add: vector_derivative_at has_vector_derivative_minus vector_derivative_works [symmetric])\n\nlemma vector_derivative_add_at [simp]:\n  \"\\<lbrakk>f differentiable at a; g differentiable at a\\<rbrakk>\n   \\<Longrightarrow> vector_derivative (\\<lambda>x. f x + g x) (at a) = vector_derivative f (at a) + vector_derivative g (at a)\"\n  by (simp add: vector_derivative_at has_vector_derivative_add vector_derivative_works [symmetric])\n\nlemma vector_derivative_diff_at [simp,derivative_intros]:\n  \"\\<lbrakk>f differentiable at a; g differentiable at a\\<rbrakk>\n   \\<Longrightarrow> vector_derivative (\\<lambda>x. f x - g x) (at a) = vector_derivative f (at a) - vector_derivative g (at a)\"\n  by (simp add: vector_derivative_at has_vector_derivative_diff vector_derivative_works [symmetric])\n\nlemma vector_derivative_mult_at [simp]:\n  fixes f g :: \"real \\<Rightarrow> 'a :: real_normed_algebra\"\n  shows  \"\\<lbrakk>f differentiable at a; g differentiable at a\\<rbrakk>\n   \\<Longrightarrow> vector_derivative (\\<lambda>x. f x * g x) (at a) = f a * vector_derivative g (at a) + vector_derivative f (at a) * g a\"\n  by (simp add: vector_derivative_at has_vector_derivative_mult vector_derivative_works [symmetric])\n\nlemma vector_derivative_scaleR_at [simp]:\n    \"\\<lbrakk>f differentiable at a; g differentiable at a\\<rbrakk>\n   \\<Longrightarrow> vector_derivative (\\<lambda>x. f x *\\<^sub>R g x) (at a) = f a *\\<^sub>R vector_derivative g (at a) + vector_derivative f (at a) *\\<^sub>R g a\"\napply (rule vector_derivative_at)\napply (rule has_vector_derivative_scaleR)\napply (auto simp: vector_derivative_works has_vector_derivative_def has_field_derivative_def mult_commute_abs)\ndone\n\nlemma vector_derivative_within_cbox:\n  assumes ab: \"a < b\" \"x \\<in> cbox a b\"\n  assumes f: \"(f has_vector_derivative f') (at x within cbox a b)\"\n  shows \"vector_derivative f (at x within cbox a b) = f'\"\n  by (intro vector_derivative_unique_within_closed_interval[OF ab _ f]\n            vector_derivative_works[THEN iffD1] differentiableI_vector)\n     fact\n\nlemma vector_derivative_within_closed_interval:\n  fixes f::\"real \\<Rightarrow> 'a::euclidean_space\"\n  assumes \"a < b\" and \"x \\<in> {a..b}\"\n  assumes \"(f has_vector_derivative f') (at x within {a..b})\"\n  shows \"vector_derivative f (at x within {a..b}) = f'\"\n  using assms vector_derivative_within_cbox\n  by fastforce\n\nlemma has_vector_derivative_within_subset:\n  \"(f has_vector_derivative f') (at x within S) \\<Longrightarrow> T \\<subseteq> S \\<Longrightarrow> (f has_vector_derivative f') (at x within T)\"\n  by (auto simp: has_vector_derivative_def intro: has_derivative_subset)\n\nlemma has_vector_derivative_at_within:\n  \"(f has_vector_derivative f') (at x) \\<Longrightarrow> (f has_vector_derivative f') (at x within S)\"\n  unfolding has_vector_derivative_def\n  by (rule has_derivative_at_withinI)\n\nlemma has_vector_derivative_weaken:\n  fixes x D and f g S T\n  assumes f: \"(f has_vector_derivative D) (at x within T)\"\n    and \"x \\<in> S\" \"S \\<subseteq> T\"\n    and \"\\<And>x. x \\<in> S \\<Longrightarrow> f x = g x\"\n  shows \"(g has_vector_derivative D) (at x within S)\"\nproof -\n  have \"(f has_vector_derivative D) (at x within S) \\<longleftrightarrow> (g has_vector_derivative D) (at x within S)\"\n    unfolding has_vector_derivative_def has_derivative_iff_norm\n    using assms by (intro conj_cong Lim_cong_within refl) auto\n  then show ?thesis\n    using has_vector_derivative_within_subset[OF f \\<open>S \\<subseteq> T\\<close>] by simp\nqed\n\nlemma has_vector_derivative_transform_within:\n  assumes \"(f has_vector_derivative f') (at x within S)\"\n    and \"0 < d\"\n    and \"x \\<in> S\"\n    and \"\\<And>x'. \\<lbrakk>x'\\<in>S; dist x' x < d\\<rbrakk> \\<Longrightarrow> f x' = g x'\"\n    shows \"(g has_vector_derivative f') (at x within S)\"\n  using assms\n  unfolding has_vector_derivative_def\n  by (rule has_derivative_transform_within)\n\nlemma has_vector_derivative_transform_within_open:\n  assumes \"(f has_vector_derivative f') (at x)\"\n    and \"open S\"\n    and \"x \\<in> S\"\n    and \"\\<And>y. y\\<in>S \\<Longrightarrow> f y = g y\"\n  shows \"(g has_vector_derivative f') (at x)\"\n  using assms\n  unfolding has_vector_derivative_def\n  by (rule has_derivative_transform_within_open)\n\nlemma has_vector_derivative_transform:\n  assumes \"x \\<in> S\" \"\\<And>x. x \\<in> S \\<Longrightarrow> g x = f x\"\n  assumes f': \"(f has_vector_derivative f') (at x within S)\"\n  shows \"(g has_vector_derivative f') (at x within S)\"\n  using assms\n  unfolding has_vector_derivative_def\n  by (rule has_derivative_transform)\n\nlemma vector_diff_chain_at:\n  assumes \"(f has_vector_derivative f') (at x)\"\n    and \"(g has_vector_derivative g') (at (f x))\"\n  shows \"((g \\<circ> f) has_vector_derivative (f' *\\<^sub>R g')) (at x)\"\n  using assms has_vector_derivative_at_within has_vector_derivative_def vector_derivative_diff_chain_within by blast\n\nlemma vector_diff_chain_within:\n  assumes \"(f has_vector_derivative f') (at x within s)\"\n    and \"(g has_vector_derivative g') (at (f x) within f ` s)\"\n  shows \"((g \\<circ> f) has_vector_derivative (f' *\\<^sub>R g')) (at x within s)\"\n  using assms has_vector_derivative_def vector_derivative_diff_chain_within by blast\n\nlemma vector_derivative_const_at [simp]: \"vector_derivative (\\<lambda>x. c) (at a) = 0\"\n  by (simp add: vector_derivative_at)\n\nlemma vector_derivative_at_within_ivl:\n  \"(f has_vector_derivative f') (at x) \\<Longrightarrow>\n    a \\<le> x \\<Longrightarrow> x \\<le> b \\<Longrightarrow> a<b \\<Longrightarrow> vector_derivative f (at x within {a..b}) = f'\"\n  using has_vector_derivative_at_within vector_derivative_within_cbox by fastforce\n\nlemma vector_derivative_chain_at:\n  assumes \"f differentiable at x\" \"(g differentiable at (f x))\"\n  shows \"vector_derivative (g \\<circ> f) (at x) =\n         vector_derivative f (at x) *\\<^sub>R vector_derivative g (at (f x))\"\nby (metis vector_diff_chain_at vector_derivative_at vector_derivative_works assms)\n\nlemma field_vector_diff_chain_at:  (*thanks to Wenda Li*)\n assumes Df: \"(f has_vector_derivative f') (at x)\"\n     and Dg: \"(g has_field_derivative g') (at (f x))\"\n shows \"((g \\<circ> f) has_vector_derivative (f' * g')) (at x)\"\nusing diff_chain_at[OF Df[unfolded has_vector_derivative_def]\n                       Dg [unfolded has_field_derivative_def]]\n by (auto simp: o_def mult.commute has_vector_derivative_def)\n\nlemma vector_derivative_chain_within: \n  assumes \"at x within S \\<noteq> bot\" \"f differentiable (at x within S)\" \n    \"(g has_derivative g') (at (f x) within f ` S)\" \n  shows \"vector_derivative (g \\<circ> f) (at x within S) =\n        g' (vector_derivative f (at x within S)) \"\n  apply (rule vector_derivative_within [OF \\<open>at x within S \\<noteq> bot\\<close>])\n  apply (rule vector_derivative_diff_chain_within)\n  using assms(2-3) vector_derivative_works\n  by auto\n\nsubsection \\<open>Field differentiability\\<close>\n\ndefinition\\<^marker>\\<open>tag important\\<close> field_differentiable :: \"['a \\<Rightarrow> 'a::real_normed_field, 'a filter] \\<Rightarrow> bool\"\n           (infixr \"(field'_differentiable)\" 50)\n  where \"f field_differentiable F \\<equiv> \\<exists>f'. (f has_field_derivative f') F\"\n\nlemma field_differentiable_imp_differentiable:\n  \"f field_differentiable F \\<Longrightarrow> f differentiable F\"\n  unfolding field_differentiable_def differentiable_def \n  using has_field_derivative_imp_has_derivative by auto\n\nlemma field_differentiable_imp_continuous_at:\n    \"f field_differentiable (at x within S) \\<Longrightarrow> continuous (at x within S) f\"\n  by (metis DERIV_continuous field_differentiable_def)\n\nlemma field_differentiable_within_subset:\n    \"\\<lbrakk>f field_differentiable (at x within S); T \\<subseteq> S\\<rbrakk> \\<Longrightarrow> f field_differentiable (at x within T)\"\n  by (metis DERIV_subset field_differentiable_def)\n\nlemma field_differentiable_at_within:\n    \"\\<lbrakk>f field_differentiable (at x)\\<rbrakk>\n     \\<Longrightarrow> f field_differentiable (at x within S)\"\n  unfolding field_differentiable_def\n  by (metis DERIV_subset top_greatest)\n\nlemma field_differentiable_linear [simp,derivative_intros]: \"((*) c) field_differentiable F\"\n  unfolding field_differentiable_def has_field_derivative_def mult_commute_abs\n  by (force intro: has_derivative_mult_right)\n\nlemma field_differentiable_const [simp,derivative_intros]: \"(\\<lambda>z. c) field_differentiable F\"\n  unfolding field_differentiable_def has_field_derivative_def\n  using DERIV_const has_field_derivative_imp_has_derivative by blast\n\nlemma field_differentiable_ident [simp,derivative_intros]: \"(\\<lambda>z. z) field_differentiable F\"\n  unfolding field_differentiable_def has_field_derivative_def\n  using DERIV_ident has_field_derivative_def by blast\n\nlemma field_differentiable_id [simp,derivative_intros]: \"id field_differentiable F\"\n  unfolding id_def by (rule field_differentiable_ident)\n\nlemma field_differentiable_minus [derivative_intros]:\n  \"f field_differentiable F \\<Longrightarrow> (\\<lambda>z. - (f z)) field_differentiable F\"\n  unfolding field_differentiable_def by (metis field_differentiable_minus)\n\nlemma field_differentiable_diff_const [simp,derivative_intros]:\n  \"(-)c field_differentiable F\"\n  unfolding field_differentiable_def by (rule derivative_eq_intros exI | force)+\n\nlemma field_differentiable_add [derivative_intros]:\n  assumes \"f field_differentiable F\" \"g field_differentiable F\"\n    shows \"(\\<lambda>z. f z + g z) field_differentiable F\"\n  using assms unfolding field_differentiable_def\n  by (metis field_differentiable_add)\n\nlemma field_differentiable_add_const [simp,derivative_intros]:\n     \"(+) c field_differentiable F\"\n  by (simp add: field_differentiable_add)\n\nlemma field_differentiable_sum [derivative_intros]:\n  \"(\\<And>i. i \\<in> I \\<Longrightarrow> (f i) field_differentiable F) \\<Longrightarrow> (\\<lambda>z. \\<Sum>i\\<in>I. f i z) field_differentiable F\"\n  by (induct I rule: infinite_finite_induct)\n     (auto intro: field_differentiable_add field_differentiable_const)\n\nlemma field_differentiable_diff [derivative_intros]:\n  assumes \"f field_differentiable F\" \"g field_differentiable F\"\n    shows \"(\\<lambda>z. f z - g z) field_differentiable F\"\n  using assms unfolding field_differentiable_def\n  by (metis field_differentiable_diff)\n\nlemma field_differentiable_inverse [derivative_intros]:\n  assumes \"f field_differentiable (at a within S)\" \"f a \\<noteq> 0\"\n  shows \"(\\<lambda>z. inverse (f z)) field_differentiable (at a within S)\"\n  using assms unfolding field_differentiable_def\n  by (metis DERIV_inverse_fun)\n\nlemma field_differentiable_mult [derivative_intros]:\n  assumes \"f field_differentiable (at a within S)\"\n          \"g field_differentiable (at a within S)\"\n    shows \"(\\<lambda>z. f z * g z) field_differentiable (at a within S)\"\n  using assms unfolding field_differentiable_def\n  by (metis DERIV_mult [of f _ a S g])\n\nlemma field_differentiable_divide [derivative_intros]:\n  assumes \"f field_differentiable (at a within S)\"\n          \"g field_differentiable (at a within S)\"\n          \"g a \\<noteq> 0\"\n    shows \"(\\<lambda>z. f z / g z) field_differentiable (at a within S)\"\n  using assms unfolding field_differentiable_def\n  by (metis DERIV_divide [of f _ a S g])\n\nlemma field_differentiable_power [derivative_intros]:\n  assumes \"f field_differentiable (at a within S)\"\n    shows \"(\\<lambda>z. f z ^ n) field_differentiable (at a within S)\"\n  using assms unfolding field_differentiable_def\n  by (metis DERIV_power)\n\nlemma field_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 field_differentiable (at x within S)\n        \\<Longrightarrow> g field_differentiable (at x within S)\"\n  unfolding field_differentiable_def has_field_derivative_def\n  by (blast intro: has_derivative_transform_within)\n\nlemma field_differentiable_compose_within:\n  assumes \"f field_differentiable (at a within S)\"\n          \"g field_differentiable (at (f a) within f`S)\"\n    shows \"(g o f) field_differentiable (at a within S)\"\n  using assms unfolding field_differentiable_def\n  by (metis DERIV_image_chain)\n\nlemma field_differentiable_compose:\n  \"f field_differentiable at z \\<Longrightarrow> g field_differentiable at (f z)\n          \\<Longrightarrow> (g o f) field_differentiable at z\"\nby (metis field_differentiable_at_within field_differentiable_compose_within)\n\nlemma field_differentiable_within_open:\n     \"\\<lbrakk>a \\<in> S; open S\\<rbrakk> \\<Longrightarrow> f field_differentiable at a within S \\<longleftrightarrow>\n                          f field_differentiable at a\"\n  unfolding field_differentiable_def\n  by (metis at_within_open)\n\nlemma exp_scaleR_has_vector_derivative_right:\n  \"((\\<lambda>t. exp (t *\\<^sub>R A)) has_vector_derivative exp (t *\\<^sub>R A) * A) (at t within T)\"\n  unfolding has_vector_derivative_def\nproof (rule has_derivativeI)\n  let ?F = \"at t within (T \\<inter> {t - 1 <..< t + 1})\"\n  have *: \"at t within T = ?F\"\n    by (rule at_within_nhd[where S=\"{t - 1 <..< t + 1}\"]) auto\n  let ?e = \"\\<lambda>i x. (inverse (1 + real i) * inverse (fact i) * (x - t) ^ i) *\\<^sub>R (A * A ^ i)\"\n  have \"\\<forall>\\<^sub>F n in sequentially.\n      \\<forall>x\\<in>T \\<inter> {t - 1<..<t + 1}. norm (?e n x) \\<le> norm (A ^ (n + 1) /\\<^sub>R fact (n + 1))\"\n    apply (auto simp: algebra_split_simps intro!: eventuallyI)\n    apply (rule mult_left_mono)\n     apply (auto simp add: field_simps power_abs intro!: divide_right_mono power_le_one)\n    done\n  then have \"uniform_limit (T \\<inter> {t - 1<..<t + 1}) (\\<lambda>n x. \\<Sum>i<n. ?e i x) (\\<lambda>x. \\<Sum>i. ?e i x) sequentially\"\n    by (rule Weierstrass_m_test_ev) (intro summable_ignore_initial_segment summable_norm_exp)\n  moreover\n  have \"\\<forall>\\<^sub>F x in sequentially. x > 0\"\n    by (metis eventually_gt_at_top)\n  then have\n    \"\\<forall>\\<^sub>F n in sequentially. ((\\<lambda>x. \\<Sum>i<n. ?e i x) \\<longlongrightarrow> A) ?F\"\n    by eventually_elim\n      (auto intro!: tendsto_eq_intros\n        simp: power_0_left if_distrib if_distribR\n        cong: if_cong)\n  ultimately\n  have [tendsto_intros]: \"((\\<lambda>x. \\<Sum>i. ?e i x) \\<longlongrightarrow> A) ?F\"\n    by (auto intro!: swap_uniform_limit[where f=\"\\<lambda>n x. \\<Sum>i < n. ?e i x\" and F = sequentially])\n  have [tendsto_intros]: \"((\\<lambda>x. if x = t then 0 else 1) \\<longlongrightarrow> 1) ?F\"\n    by (rule tendsto_eventually) (simp add: eventually_at_filter)\n  have \"((\\<lambda>y. ((y - t) / abs (y - t)) *\\<^sub>R ((\\<Sum>n. ?e n y) - A)) \\<longlongrightarrow> 0) (at t within T)\"\n    unfolding *\n    by (rule tendsto_norm_zero_cancel) (auto intro!: tendsto_eq_intros)\n\n  moreover have \"\\<forall>\\<^sub>F x in at t within T. x \\<noteq> t\"\n    by (simp add: eventually_at_filter)\n  then have \"\\<forall>\\<^sub>F x in at t within T. ((x - t) / \\<bar>x - t\\<bar>) *\\<^sub>R ((\\<Sum>n. ?e n x) - A) =\n    (exp ((x - t) *\\<^sub>R A) - 1 - (x - t) *\\<^sub>R A) /\\<^sub>R norm (x - t)\"\n  proof eventually_elim\n    case (elim x)\n    have \"(exp ((x - t) *\\<^sub>R A) - 1 - (x - t) *\\<^sub>R A) /\\<^sub>R norm (x - t) =\n      ((\\<Sum>n. (x - t) *\\<^sub>R ?e n x) - (x - t) *\\<^sub>R A) /\\<^sub>R norm (x - t)\"\n      unfolding exp_first_term\n      by (simp add: ac_simps)\n    also\n    have \"summable (\\<lambda>n. ?e n x)\"\n    proof -\n      from elim have \"?e n x = (((x - t) *\\<^sub>R A) ^ (n + 1)) /\\<^sub>R fact (n + 1) /\\<^sub>R (x - t)\" for n\n        by simp\n      then show ?thesis\n        by (auto simp only:\n          intro!: summable_scaleR_right summable_ignore_initial_segment summable_exp_generic)\n    qed\n    then have \"(\\<Sum>n. (x - t) *\\<^sub>R ?e n x) = (x - t) *\\<^sub>R (\\<Sum>n. ?e n x)\"\n      by (rule suminf_scaleR_right[symmetric])\n    also have \"(\\<dots> - (x - t) *\\<^sub>R A) /\\<^sub>R norm (x - t) = (x - t) *\\<^sub>R ((\\<Sum>n. ?e n x) - A) /\\<^sub>R norm (x - t)\"\n      by (simp add: algebra_simps)\n    finally show ?case\n      by simp (simp add: field_simps)\n  qed\n\n  ultimately have \"((\\<lambda>y. (exp ((y - t) *\\<^sub>R A) - 1 - (y - t) *\\<^sub>R A) /\\<^sub>R norm (y - t)) \\<longlongrightarrow> 0) (at t within T)\"\n    by (rule Lim_transform_eventually)\n  from tendsto_mult_right_zero[OF this, where c=\"exp (t *\\<^sub>R A)\"]\n  show \"((\\<lambda>y. (exp (y *\\<^sub>R A) - exp (t *\\<^sub>R A) - (y - t) *\\<^sub>R (exp (t *\\<^sub>R A) * A)) /\\<^sub>R norm (y - t)) \\<longlongrightarrow> 0)\n      (at t within T)\"\n    by (rule Lim_transform_eventually)\n      (auto simp: field_split_simps exp_add_commuting[symmetric])\nqed (rule bounded_linear_scaleR_left)\n\nlemma exp_times_scaleR_commute: \"exp (t *\\<^sub>R A) * A = A * exp (t *\\<^sub>R A)\"\n  using exp_times_arg_commute[symmetric, of \"t *\\<^sub>R A\"]\n  by (auto simp: algebra_simps)\n\nlemma exp_scaleR_has_vector_derivative_left: \"((\\<lambda>t. exp (t *\\<^sub>R A)) has_vector_derivative A * exp (t *\\<^sub>R A)) (at t)\"\n  using exp_scaleR_has_vector_derivative_right[of A t]\n  by (simp add: exp_times_scaleR_commute)\n\nlemma field_differentiable_series:\n  fixes f :: \"nat \\<Rightarrow> 'a::{real_normed_field,banach} \\<Rightarrow> 'a\"\n  assumes \"convex S\" \"open S\"\n  assumes \"\\<And>n x. x \\<in> S \\<Longrightarrow> (f n has_field_derivative f' n x) (at x)\"\n  assumes \"uniformly_convergent_on S (\\<lambda>n x. \\<Sum>i<n. f' i x)\"\n  assumes \"x0 \\<in> S\" \"summable (\\<lambda>n. f n x0)\" and x: \"x \\<in> S\"\n  shows  \"(\\<lambda>x. \\<Sum>n. f n x) field_differentiable (at x)\"\nproof -\n  from assms(4) obtain g' where A: \"uniform_limit S (\\<lambda>n x. \\<Sum>i<n. f' i x) g' sequentially\"\n    unfolding uniformly_convergent_on_def by blast\n  from x and \\<open>open S\\<close> have S: \"at x within S = at x\" by (rule at_within_open)\n  have \"\\<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)\"\n    by (intro has_field_derivative_series[of S f f' g' x0] assms A has_field_derivative_at_within)\n  then obtain g where g: \"\\<And>x. x \\<in> S \\<Longrightarrow> (\\<lambda>n. f n x) sums g x\"\n    \"\\<And>x. x \\<in> S \\<Longrightarrow> (g has_field_derivative g' x) (at x within S)\" by blast\n  from g(2)[OF x] have g': \"(g has_derivative (*) (g' x)) (at x)\"\n    by (simp add: has_field_derivative_def S)\n  have \"((\\<lambda>x. \\<Sum>n. f n x) has_derivative (*) (g' x)) (at x)\"\n    by (rule has_derivative_transform_within_open[OF g' \\<open>open S\\<close> x])\n       (insert g, auto simp: sums_iff)\n  thus \"(\\<lambda>x. \\<Sum>n. f n x) field_differentiable (at x)\" unfolding differentiable_def\n    by (auto simp: summable_def field_differentiable_def has_field_derivative_def)\nqed\n\nsubsubsection\\<^marker>\\<open>tag unimportant\\<close>\\<open>Caratheodory characterization\\<close>\n\nlemma field_differentiable_caratheodory_at:\n  \"f field_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: field_differentiable_def has_field_derivative_def)\n\nlemma field_differentiable_caratheodory_within:\n  \"f field_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: field_differentiable_def has_field_derivative_def)\n\n\nsubsection \\<open>Field derivative\\<close>\n\ndefinition\\<^marker>\\<open>tag important\\<close> deriv :: \"('a \\<Rightarrow> 'a::real_normed_field) \\<Rightarrow> 'a \\<Rightarrow> 'a\" where\n  \"deriv f x \\<equiv> SOME 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 some_equality DERIV_unique)\n\nlemma DERIV_deriv_iff_has_field_derivative:\n  \"DERIV f x :> deriv f x \\<longleftrightarrow> (\\<exists>f'. (f has_field_derivative f') (at x))\"\n  by (auto simp: has_field_derivative_def DERIV_imp_deriv)\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 DERIV_deriv_iff_field_differentiable:\n  \"DERIV f x :> deriv f x \\<longleftrightarrow> f field_differentiable at x\"\n  unfolding field_differentiable_def by (metis DERIV_imp_deriv)\n\nlemma vector_derivative_of_real_left:\n  assumes \"f differentiable at x\"\n  shows   \"vector_derivative (\\<lambda>x. of_real (f x)) (at x) = of_real (deriv f x)\"\n  by (metis DERIV_deriv_iff_real_differentiable assms has_vector_derivative_of_real vector_derivative_at)\n  \nlemma vector_derivative_of_real_right:\n  assumes \"f field_differentiable at (of_real x)\"\n  shows   \"vector_derivative (\\<lambda>x. f (of_real x)) (at x) = deriv f (of_real x)\"\n  by (metis DERIV_deriv_iff_field_differentiable assms has_vector_derivative_real_field vector_derivative_at)\n  \nlemma deriv_cong_ev:\n  assumes \"eventually (\\<lambda>x. f x = g x) (nhds x)\" \"x = y\"\n  shows   \"deriv f x = deriv g y\"\nproof -\n  have \"(\\<lambda>D. (f has_field_derivative D) (at x)) = (\\<lambda>D. (g has_field_derivative D) (at y))\"\n    by (intro ext DERIV_cong_ev refl assms)\n  thus ?thesis by (simp add: deriv_def assms)\nqed\n\nlemma higher_deriv_cong_ev:\n  assumes \"eventually (\\<lambda>x. f x = g x) (nhds x)\" \"x = y\"\n  shows   \"(deriv ^^ n) f x = (deriv ^^ n) g y\"\nproof -\n  from assms(1) have \"eventually (\\<lambda>x. (deriv ^^ n) f x = (deriv ^^ n) g x) (nhds x)\"\n  proof (induction n arbitrary: f g)\n    case (Suc n)\n    from Suc.prems have \"eventually (\\<lambda>y. eventually (\\<lambda>z. f z = g z) (nhds y)) (nhds x)\"\n      by (simp add: eventually_eventually)\n    hence \"eventually (\\<lambda>x. deriv f x = deriv g x) (nhds x)\"\n      by eventually_elim (rule deriv_cong_ev, simp_all)\n    thus ?case by (auto intro!: deriv_cong_ev Suc simp: funpow_Suc_right simp del: funpow.simps)\n  qed auto\n  with \\<open>x = y\\<close> eventually_nhds_x_imp_x show ?thesis by blast \nqed\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)\nlemma field_derivative_eq_vector_derivative:\n   \"(deriv f x) = vector_derivative f (at x)\"\nby (simp add: mult.commute deriv_def vector_derivative_def has_vector_derivative_def has_field_derivative_def)\n\nproposition field_differentiable_derivI:\n    \"f field_differentiable (at x) \\<Longrightarrow> (f has_field_derivative deriv f x) (at x)\"\nby (simp add: field_differentiable_def DERIV_deriv_iff_has_field_derivative)\n\nlemma vector_derivative_chain_at_general:\n  assumes \"f differentiable at x\" \"g field_differentiable at (f x)\"\n  shows \"vector_derivative (g \\<circ> f) (at x) = vector_derivative f (at x) * deriv g (f x)\"\n  apply (rule vector_derivative_at [OF field_vector_diff_chain_at])\n  using assms vector_derivative_works by (auto simp: field_differentiable_derivI)\n\nlemma deriv_chain:\n  \"f field_differentiable at x \\<Longrightarrow> g field_differentiable at (f x)\n    \\<Longrightarrow> deriv (g o f) x = deriv g (f x) * deriv f x\"\n  by (metis DERIV_deriv_iff_field_differentiable DERIV_chain DERIV_imp_deriv)\n\nlemma deriv_linear [simp]: \"deriv (\\<lambda>w. c * w) = (\\<lambda>z. c)\"\n  by (metis DERIV_imp_deriv DERIV_cmult_Id)\n\nlemma deriv_uminus [simp]: \"deriv (\\<lambda>w. -w) = (\\<lambda>z. -1)\"\n  using deriv_linear[of \"-1\"] by (simp del: deriv_linear)\n\nlemma deriv_ident [simp]: \"deriv (\\<lambda>w. w) = (\\<lambda>z. 1)\"\n  by (metis DERIV_imp_deriv DERIV_ident)\n\nlemma deriv_id [simp]: \"deriv id = (\\<lambda>z. 1)\"\n  by (simp add: id_def)\n\nlemma deriv_const [simp]: \"deriv (\\<lambda>w. c) = (\\<lambda>z. 0)\"\n  by (metis DERIV_imp_deriv DERIV_const)\n\nlemma deriv_add [simp]:\n  \"\\<lbrakk>f field_differentiable at z; g field_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_field_differentiable[symmetric]\n  by (auto intro!: DERIV_imp_deriv derivative_intros)\n\nlemma deriv_minus [simp]:\n  \"f field_differentiable at z \\<Longrightarrow> deriv (\\<lambda>w. - f w) z = - deriv f z\"\n  by (simp add: DERIV_deriv_iff_field_differentiable DERIV_imp_deriv Deriv.field_differentiable_minus)\n\nlemma deriv_diff [simp]:\n  \"\\<lbrakk>f field_differentiable at z; g field_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_field_differentiable[symmetric]\n  by (auto intro!: DERIV_imp_deriv derivative_intros)\n\nlemma deriv_mult [simp]:\n  \"\\<lbrakk>f field_differentiable at z; g field_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_field_differentiable[symmetric]\n  by (auto intro!: DERIV_imp_deriv derivative_eq_intros)\n\nlemma deriv_cmult:\n  \"f field_differentiable at z \\<Longrightarrow> deriv (\\<lambda>w. c * f w) z = c * deriv f z\"\n  by simp\n\nlemma deriv_cmult_right:\n  \"f field_differentiable at z \\<Longrightarrow> deriv (\\<lambda>w. f w * c) z = deriv f z * c\"\n  by simp\n\nlemma deriv_inverse [simp]:\n  \"\\<lbrakk>f field_differentiable at z; f z \\<noteq> 0\\<rbrakk>\n   \\<Longrightarrow> deriv (\\<lambda>w. inverse (f w)) z = - deriv f z / f z ^ 2\"\n  unfolding DERIV_deriv_iff_field_differentiable[symmetric]\n  by (safe intro!: DERIV_imp_deriv derivative_eq_intros) (auto simp: field_split_simps power2_eq_square)\n\nlemma deriv_divide [simp]:\n  \"\\<lbrakk>f field_differentiable at z; g field_differentiable at z; g z \\<noteq> 0\\<rbrakk>\n   \\<Longrightarrow> deriv (\\<lambda>w. f w / g w) z = (deriv f z * g z - f z * deriv g z) / g z ^ 2\"\n  by (simp add: field_class.field_divide_inverse field_differentiable_inverse)\n     (simp add: field_split_simps power2_eq_square)\n\nlemma deriv_cdivide_right:\n  \"f field_differentiable at z \\<Longrightarrow> deriv (\\<lambda>w. f w / c) z = deriv f z / c\"\n  by (simp add: field_class.field_divide_inverse)\n\nlemma deriv_pow: \"\\<lbrakk>f field_differentiable at z\\<rbrakk>\n   \\<Longrightarrow> deriv (\\<lambda>w. f w ^ n) z = (if n=0 then 0 else n * deriv f z * f z ^ (n - Suc 0))\"\n  unfolding DERIV_deriv_iff_field_differentiable[symmetric]\n  by (auto intro!: DERIV_imp_deriv derivative_eq_intros)\n\nlemma deriv_sum [simp]:\n  \"\\<lbrakk>\\<And>i. f i field_differentiable at z\\<rbrakk>\n   \\<Longrightarrow> deriv (\\<lambda>w. sum (\\<lambda>i. f i w) S) z = sum (\\<lambda>i. deriv (f i) z) S\"\n  unfolding DERIV_deriv_iff_field_differentiable[symmetric]\n  by (auto intro!: DERIV_imp_deriv derivative_intros)\n\nlemma deriv_compose_linear:\n  \"f field_differentiable at (c * z) \\<Longrightarrow> deriv (\\<lambda>w. f (c * w)) z = c * deriv f (c * z)\"\napply (rule DERIV_imp_deriv)\n  unfolding DERIV_deriv_iff_field_differentiable [symmetric]\n  by (metis (full_types) DERIV_chain2 DERIV_cmult_Id mult.commute)\n\n\nlemma nonzero_deriv_nonconstant:\n  assumes df: \"DERIV f \\<xi> :> df\" and S: \"open S\" \"\\<xi> \\<in> S\" and \"df \\<noteq> 0\"\n    shows \"\\<not> f constant_on S\"\nunfolding constant_on_def\nby (metis \\<open>df \\<noteq> 0\\<close> has_field_derivative_transform_within_open [OF df S] DERIV_const DERIV_unique)\n\n\nsubsection \\<open>Relation between convexity and derivative\\<close>\n\n(* TODO: Generalise to real vector spaces? *)\nproposition convex_on_imp_above_tangent:\n  assumes convex: \"convex_on A f\" and connected: \"connected A\"\n  assumes c: \"c \\<in> interior A\" and x : \"x \\<in> A\"\n  assumes deriv: \"(f has_field_derivative f') (at c within A)\"\n  shows   \"f x - f c \\<ge> f' * (x - c)\"\nproof (cases x c rule: linorder_cases)\n  assume xc: \"x > c\"\n  let ?A' = \"interior A \\<inter> {c<..}\"\n  from c have \"c \\<in> interior A \\<inter> closure {c<..}\" by auto\n  also have \"\\<dots> \\<subseteq> closure (interior A \\<inter> {c<..})\" by (intro open_Int_closure_subset) auto\n  finally have \"at c within ?A' \\<noteq> bot\" by (subst at_within_eq_bot_iff) auto\n  moreover from deriv have \"((\\<lambda>y. (f y - f c) / (y - c)) \\<longlongrightarrow> f') (at c within ?A')\"\n    unfolding has_field_derivative_iff using interior_subset[of A] by (blast intro: tendsto_mono at_le)\n  moreover from eventually_at_right_real[OF xc]\n    have \"eventually (\\<lambda>y. (f y - f c) / (y - c) \\<le> (f x - f c) / (x - c)) (at_right c)\"\n  proof eventually_elim\n    fix y assume y: \"y \\<in> {c<..<x}\"\n    with convex connected x c have \"f y \\<le> (f x - f c) / (x - c) * (y - c) + f c\"\n      using interior_subset[of A]\n      by (intro convex_onD_Icc' convex_on_subset[OF convex] connected_contains_Icc) auto\n    hence \"f y - f c \\<le> (f x - f c) / (x - c) * (y - c)\" by simp\n    thus \"(f y - f c) / (y - c) \\<le> (f x - f c) / (x - c)\" using y xc by (simp add: field_split_simps)\n  qed\n  hence \"eventually (\\<lambda>y. (f y - f c) / (y - c) \\<le> (f x - f c) / (x - c)) (at c within ?A')\"\n    by (blast intro: filter_leD at_le)\n  ultimately have \"f' \\<le> (f x - f c) / (x - c)\" by (simp add: tendsto_upperbound)\n  thus ?thesis using xc by (simp add: field_simps)\nnext\n  assume xc: \"x < c\"\n  let ?A' = \"interior A \\<inter> {..<c}\"\n  from c have \"c \\<in> interior A \\<inter> closure {..<c}\" by auto\n  also have \"\\<dots> \\<subseteq> closure (interior A \\<inter> {..<c})\" by (intro open_Int_closure_subset) auto\n  finally have \"at c within ?A' \\<noteq> bot\" by (subst at_within_eq_bot_iff) auto\n  moreover from deriv have \"((\\<lambda>y. (f y - f c) / (y - c)) \\<longlongrightarrow> f') (at c within ?A')\"\n    unfolding has_field_derivative_iff using interior_subset[of A] by (blast intro: tendsto_mono at_le)\n  moreover from eventually_at_left_real[OF xc]\n    have \"eventually (\\<lambda>y. (f y - f c) / (y - c) \\<ge> (f x - f c) / (x - c)) (at_left c)\"\n  proof eventually_elim\n    fix y assume y: \"y \\<in> {x<..<c}\"\n    with convex connected x c have \"f y \\<le> (f x - f c) / (c - x) * (c - y) + f c\"\n      using interior_subset[of A]\n      by (intro convex_onD_Icc'' convex_on_subset[OF convex] connected_contains_Icc) auto\n    hence \"f y - f c \\<le> (f x - f c) * ((c - y) / (c - x))\" by simp\n    also have \"(c - y) / (c - x) = (y - c) / (x - c)\" using y xc by (simp add: field_simps)\n    finally show \"(f y - f c) / (y - c) \\<ge> (f x - f c) / (x - c)\" using y xc\n      by (simp add: field_split_simps)\n  qed\n  hence \"eventually (\\<lambda>y. (f y - f c) / (y - c) \\<ge> (f x - f c) / (x - c)) (at c within ?A')\"\n    by (blast intro: filter_leD at_le)\n  ultimately have \"f' \\<ge> (f x - f c) / (x - c)\" by (simp add: tendsto_lowerbound)\n  thus ?thesis using xc by (simp add: field_simps)\nqed simp_all\n\n\nsubsection \\<open>Partial derivatives\\<close>\n\nlemma eventually_at_Pair_within_TimesI1:\n  fixes x::\"'a::metric_space\"\n  assumes \"\\<forall>\\<^sub>F x' in at x within X. P x'\"\n  assumes \"P x\"\n  shows \"\\<forall>\\<^sub>F (x', y') in at (x, y) within X \\<times> Y. P x'\"\nproof -\n  from assms[unfolded eventually_at_topological]\n  obtain S where S: \"open S\" \"x \\<in> S\" \"\\<And>x'. x' \\<in> X \\<Longrightarrow> x' \\<in> S \\<Longrightarrow> P x'\"\n    by metis\n  show \"\\<forall>\\<^sub>F (x', y') in at (x, y) within X \\<times> Y. P x'\"\n    unfolding eventually_at_topological\n    by (auto intro!: exI[where x=\"S \\<times> UNIV\"] S open_Times)\nqed\n\nlemma eventually_at_Pair_within_TimesI2:\n  fixes x::\"'a::metric_space\"\n  assumes \"\\<forall>\\<^sub>F y' in at y within Y. P y'\" \"P y\"\n  shows \"\\<forall>\\<^sub>F (x', y') in at (x, y) within X \\<times> Y. P y'\"\nproof -\n  from assms[unfolded eventually_at_topological]\n  obtain S where S: \"open S\" \"y \\<in> S\" \"\\<And>y'. y' \\<in> Y \\<Longrightarrow> y' \\<in> S \\<Longrightarrow> P y'\"\n    by metis\n  show \"\\<forall>\\<^sub>F (x', y') in at (x, y) within X \\<times> Y. P y'\"\n    unfolding eventually_at_topological\n    by (auto intro!: exI[where x=\"UNIV \\<times> S\"] S open_Times)\nqed\n\nproposition has_derivative_partialsI:\n  fixes f::\"'a::real_normed_vector \\<Rightarrow> 'b::real_normed_vector \\<Rightarrow> 'c::real_normed_vector\"\n  assumes fx: \"((\\<lambda>x. f x y) has_derivative fx) (at x within X)\"\n  assumes fy: \"\\<And>x y. x \\<in> X \\<Longrightarrow> y \\<in> Y \\<Longrightarrow> ((\\<lambda>y. f x y) has_derivative blinfun_apply (fy x y)) (at y within Y)\"\n  assumes fy_cont[unfolded continuous_within]: \"continuous (at (x, y) within X \\<times> Y) (\\<lambda>(x, y). fy x y)\"\n  assumes \"y \\<in> Y\" \"convex Y\"\n  shows \"((\\<lambda>(x, y). f x y) has_derivative (\\<lambda>(tx, ty). fx tx + fy x y ty)) (at (x, y) within X \\<times> Y)\"\nproof (safe intro!: has_derivativeI tendstoI, goal_cases)\n  case (2 e')\n  interpret fx: bounded_linear \"fx\" using fx by (rule has_derivative_bounded_linear)\n  define e where \"e = e' / 9\"\n  have \"e > 0\" using \\<open>e' > 0\\<close> by (simp add: e_def)\n\n  from fy_cont[THEN tendstoD, OF \\<open>e > 0\\<close>]\n  have \"\\<forall>\\<^sub>F (x', y') in at (x, y) within X \\<times> Y. dist (fy x' y') (fy x y) < e\"\n    by (auto simp: split_beta')\n  from this[unfolded eventually_at] obtain d' where\n    \"d' > 0\"\n    \"\\<And>x' y'. x' \\<in> X \\<Longrightarrow> y' \\<in> Y \\<Longrightarrow> (x', y') \\<noteq> (x, y) \\<Longrightarrow> dist (x', y') (x, y) < d' \\<Longrightarrow>\n      dist (fy x' y') (fy x y) < e\"\n    by auto\n  then\n  have d': \"x' \\<in> X \\<Longrightarrow> y' \\<in> Y \\<Longrightarrow> dist (x', y') (x, y) < d' \\<Longrightarrow> dist (fy x' y') (fy x y) < e\"\n    for x' y'\n    using \\<open>0 < e\\<close>\n    by (cases \"(x', y') = (x, y)\") auto\n  define d where \"d = d' / sqrt 2\"\n  have \"d > 0\" using \\<open>0 < d'\\<close> by (simp add: d_def)\n  have d: \"x' \\<in> X \\<Longrightarrow> y' \\<in> Y \\<Longrightarrow> dist x' x < d \\<Longrightarrow> dist y' y < d \\<Longrightarrow> dist (fy x' y') (fy x y) < e\"\n    for x' y'\n    by (auto simp: dist_prod_def d_def intro!: d' real_sqrt_sum_squares_less)\n\n  let ?S = \"ball y d \\<inter> Y\"\n  have \"convex ?S\"\n    by (auto intro!: convex_Int \\<open>convex Y\\<close>)\n  {\n    fix x'::'a and y'::'b\n    assume x': \"x' \\<in> X\" and y': \"y' \\<in> Y\"\n    assume dx': \"dist x' x < d\" and dy': \"dist y' y < d\"\n    have \"norm (fy x' y' - fy x' y) \\<le> dist (fy x' y') (fy x y) + dist (fy x' y) (fy x y)\"\n      by norm\n    also have \"dist (fy x' y') (fy x y) < e\"\n      by (rule d; fact)\n    also have \"dist (fy x' y) (fy x y) < e\"\n      by (auto intro!: d simp: dist_prod_def x' \\<open>d > 0\\<close> \\<open>y \\<in> Y\\<close> dx')\n    finally\n    have \"norm (fy x' y' - fy x' y) < e + e\"\n      by arith\n    then have \"onorm (blinfun_apply (fy x' y') - blinfun_apply (fy x' y)) < e + e\"\n      by (auto simp: norm_blinfun.rep_eq blinfun.diff_left[abs_def] fun_diff_def)\n  } note onorm = this\n\n  have ev_mem: \"\\<forall>\\<^sub>F (x', y') in at (x, y) within X \\<times> Y. (x', y') \\<in> X \\<times> Y\"\n    using \\<open>y \\<in> Y\\<close>\n    by (auto simp: eventually_at intro!: zero_less_one)\n  moreover\n  have ev_dist: \"\\<forall>\\<^sub>F xy in at (x, y) within X \\<times> Y. dist xy (x, y) < d\" if \"d > 0\" for d\n    using eventually_at_ball[OF that]\n    by (rule eventually_elim2) (auto simp: dist_commute intro!: eventually_True)\n  note ev_dist[OF \\<open>0 < d\\<close>]\n  ultimately\n  have \"\\<forall>\\<^sub>F (x', y') in at (x, y) within X \\<times> Y.\n    norm (f x' y' - f x' y - (fy x' y) (y' - y)) \\<le> norm (y' - y) * (e + e)\"\n  proof (eventually_elim, safe)\n    fix x' y'\n    assume \"x' \\<in> X\" and y': \"y' \\<in> Y\"\n    assume dist: \"dist (x', y') (x, y) < d\"\n    then have dx: \"dist x' x < d\" and dy: \"dist y' y < d\"\n      unfolding dist_prod_def fst_conv snd_conv atomize_conj\n      by (metis le_less_trans real_sqrt_sum_squares_ge1 real_sqrt_sum_squares_ge2)\n    {\n      fix t::real\n      assume \"t \\<in> {0 .. 1}\"\n      then have \"y + t *\\<^sub>R (y' - y) \\<in> closed_segment y y'\"\n        by (auto simp: closed_segment_def algebra_simps intro!: exI[where x=t])\n      also\n      have \"\\<dots> \\<subseteq> ball y d \\<inter> Y\"\n        using \\<open>y \\<in> Y\\<close> \\<open>0 < d\\<close> dy y'\n        by (intro \\<open>convex ?S\\<close>[unfolded convex_contains_segment, rule_format, of y y'])\n          (auto simp: dist_commute)\n      finally have \"y + t *\\<^sub>R (y' - y) \\<in> ?S\" .\n    } note seg = this\n\n    have \"\\<And>x. x \\<in> ball y d \\<inter> Y \\<Longrightarrow> onorm (blinfun_apply (fy x' x) - blinfun_apply (fy x' y)) \\<le> e + e\"\n      by (safe intro!: onorm less_imp_le \\<open>x' \\<in> X\\<close> dx) (auto simp: dist_commute \\<open>0 < d\\<close> \\<open>y \\<in> Y\\<close>)\n    with seg has_derivative_subset[OF assms(2)[OF \\<open>x' \\<in> X\\<close>]]\n    show \"norm (f x' y' - f x' y - (fy x' y) (y' - y)) \\<le> norm (y' - y) * (e + e)\"\n      by (rule differentiable_bound_linearization[where S=\"?S\"])\n        (auto intro!: \\<open>0 < d\\<close> \\<open>y \\<in> Y\\<close>)\n  qed\n  moreover\n  let ?le = \"\\<lambda>x'. norm (f x' y - f x y - (fx) (x' - x)) \\<le> norm (x' - x) * e\"\n  from fx[unfolded has_derivative_within, THEN conjunct2, THEN tendstoD, OF \\<open>0 < e\\<close>]\n  have \"\\<forall>\\<^sub>F x' in at x within X. ?le x'\"\n    by eventually_elim (simp, \n      simp add: dist_norm field_split_simps split: if_split_asm)\n  then have \"\\<forall>\\<^sub>F (x', y') in at (x, y) within X \\<times> Y. ?le x'\"\n    by (rule eventually_at_Pair_within_TimesI1)\n       (simp add: blinfun.bilinear_simps)\n  moreover have \"\\<forall>\\<^sub>F (x', y') in at (x, y) within X \\<times> Y. norm ((x', y') - (x, y)) \\<noteq> 0\"\n    unfolding norm_eq_zero right_minus_eq\n    by (auto simp: eventually_at intro!: zero_less_one)\n  moreover\n  from fy_cont[THEN tendstoD, OF \\<open>0 < e\\<close>]\n  have \"\\<forall>\\<^sub>F x' in at x within X. norm (fy x' y - fy x y) < e\"\n    unfolding eventually_at\n    using \\<open>y \\<in> Y\\<close>\n    by (auto simp: dist_prod_def dist_norm)\n  then have \"\\<forall>\\<^sub>F (x', y') in at (x, y) within X \\<times> Y. norm (fy x' y - fy x y) < e\"\n    by (rule eventually_at_Pair_within_TimesI1)\n       (simp add: blinfun.bilinear_simps \\<open>0 < e\\<close>)\n  ultimately\n  have \"\\<forall>\\<^sub>F (x', y') in at (x, y) within X \\<times> Y.\n            norm ((f x' y' - f x y - (fx (x' - x) + fy x y (y' - y))) /\\<^sub>R\n              norm ((x', y') - (x, y)))\n            < e'\"\n    apply eventually_elim\n  proof safe\n    fix x' y'\n    have \"norm (f x' y' - f x y - (fx (x' - x) + fy x y (y' - y))) \\<le>\n        norm (f x' y' - f x' y - fy x' y (y' - y)) +\n        norm (fy x y (y' - y) - fy x' y (y' - y)) +\n        norm (f x' y - f x y - fx (x' - x))\"\n      by norm\n    also\n    assume nz: \"norm ((x', y') - (x, y)) \\<noteq> 0\"\n      and nfy: \"norm (fy x' y - fy x y) < e\"\n    assume \"norm (f x' y' - f x' y - blinfun_apply (fy x' y) (y' - y)) \\<le> norm (y' - y) * (e + e)\"\n    also assume \"norm (f x' y - f x y - (fx) (x' - x)) \\<le> norm (x' - x) * e\"\n    also\n    have \"norm ((fy x y) (y' - y) - (fy x' y) (y' - y)) \\<le> norm ((fy x y) - (fy x' y)) * norm (y' - y)\"\n      by (auto simp: blinfun.bilinear_simps[symmetric] intro!: norm_blinfun)\n    also have \"\\<dots> \\<le> (e + e) * norm (y' - y)\"\n      using \\<open>e > 0\\<close> nfy\n      by (auto simp: norm_minus_commute intro!: mult_right_mono)\n    also have \"norm (x' - x) * e \\<le> norm (x' - x) * (e + e)\"\n      using \\<open>0 < e\\<close> by simp\n    also have \"norm (y' - y) * (e + e) + (e + e) * norm (y' - y) + norm (x' - x) * (e + e) \\<le>\n        (norm (y' - y) + norm (x' - x)) * (4 * e)\"\n      using \\<open>e > 0\\<close>\n      by (simp add: algebra_simps)\n    also have \"\\<dots> \\<le> 2 * norm ((x', y') - (x, y)) * (4 * e)\"\n      using \\<open>0 < e\\<close> real_sqrt_sum_squares_ge1[of \"norm (x' - x)\" \"norm (y' - y)\"]\n        real_sqrt_sum_squares_ge2[of \"norm (y' - y)\" \"norm (x' - x)\"]\n      by (auto intro!: mult_right_mono simp: norm_prod_def\n        simp del: real_sqrt_sum_squares_ge1 real_sqrt_sum_squares_ge2)\n    also have \"\\<dots> \\<le> norm ((x', y') - (x, y)) * (8 * e)\"\n      by simp\n    also have \"\\<dots> < norm ((x', y') - (x, y)) * e'\"\n      using \\<open>0 < e'\\<close> nz\n      by (auto simp: e_def)\n    finally show \"norm ((f x' y' - f x y - (fx (x' - x) + fy x y (y' - y))) /\\<^sub>R norm ((x', y') - (x, y))) < e'\"\n      by (simp add: dist_norm) (auto simp add: field_split_simps)\n  qed\n  then show ?case\n    by eventually_elim (auto simp: dist_norm field_simps)\nnext\n  from has_derivative_bounded_linear[OF fx]\n  obtain fxb where \"fx = blinfun_apply fxb\"\n    by (metis bounded_linear_Blinfun_apply)\n  then show \"bounded_linear (\\<lambda>(tx, ty). fx tx + blinfun_apply (fy x y) ty)\"\n    by (auto intro!: bounded_linear_intros simp: split_beta')\nqed\n\n\nsubsection\\<^marker>\\<open>tag unimportant\\<close> \\<open>Differentiable case distinction\\<close>\n\nlemma has_derivative_within_If_eq:\n  \"((\\<lambda>x. if P x then f x else g x) has_derivative f') (at x within S) =\n    (bounded_linear f' \\<and>\n     ((\\<lambda>y.(if P y then (f y - ((if P x then f x else g x) + f' (y - x)))/\\<^sub>R norm (y - x)\n           else (g y - ((if P x then f x else g x) + f' (y - x)))/\\<^sub>R norm (y - x)))\n      \\<longlongrightarrow> 0) (at x within S))\"\n  (is \"_ = (_ \\<and> (?if \\<longlongrightarrow> 0) _)\")\nproof -\n  have \"(\\<lambda>y. (1 / norm (y - x)) *\\<^sub>R\n           ((if P y then f y else g y) -\n            ((if P x then f x else g x) + f' (y - x)))) = ?if\"\n    by (auto simp: inverse_eq_divide)\n  thus ?thesis by (auto simp: has_derivative_within)\nqed\n\nlemma has_derivative_If_within_closures:\n  assumes f': \"x \\<in> S \\<union> (closure S \\<inter> closure T) \\<Longrightarrow>\n    (f has_derivative f' 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 has_derivative g' x) (at x within T \\<union> (closure S \\<inter> closure T))\"\n  assumes connect: \"x \\<in> closure S \\<Longrightarrow> x \\<in> closure T \\<Longrightarrow> f x = g x\"\n  assumes connect': \"x \\<in> closure S \\<Longrightarrow> x \\<in> closure T \\<Longrightarrow> f' x = g' x\"\n  assumes x_in: \"x \\<in> S \\<union> T\"\n  shows \"((\\<lambda>x. if x \\<in> S then f x else g x) has_derivative\n      (if x \\<in> S then f' x else g' x)) (at x within (S \\<union> T))\"\nproof -\n  from f' x_in interpret f': bounded_linear \"if x \\<in> S then f' x else (\\<lambda>x. 0)\"\n    by (auto simp add: has_derivative_within)\n  from g' interpret g': bounded_linear \"if x \\<in> T then g' x else (\\<lambda>x. 0)\"\n    by (auto simp add: has_derivative_within)\n  have bl: \"bounded_linear (if x \\<in> S then f' x else g' x)\"\n    using f'.scaleR f'.bounded f'.add g'.scaleR g'.bounded g'.add x_in\n    by (unfold_locales; force)\n  show ?thesis\n    using f' g' closure_subset[of T] closure_subset[of S]\n    unfolding has_derivative_within_If_eq\n    by (intro conjI bl tendsto_If_within_closures x_in)\n      (auto simp: has_derivative_within inverse_eq_divide connect connect' subsetD)\nqed\n\nlemma has_vector_derivative_If_within_closures:\n  assumes x_in: \"x \\<in> S \\<union> T\"\n  assumes \"u = S \\<union> T\"\n  assumes f': \"x \\<in> S \\<union> (closure S \\<inter> closure T) \\<Longrightarrow>\n    (f has_vector_derivative f' 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 has_vector_derivative g' x) (at x within T \\<union> (closure S \\<inter> closure T))\"\n  assumes connect: \"x \\<in> closure S \\<Longrightarrow> x \\<in> closure T \\<Longrightarrow> f x = g x\"\n  assumes connect': \"x \\<in> closure S \\<Longrightarrow> x \\<in> closure T \\<Longrightarrow> f' x = g' x\"\n  shows \"((\\<lambda>x. if x \\<in> S then f x else g x) has_vector_derivative\n    (if x \\<in> S then f' x else g' x)) (at x within u)\"\n  unfolding has_vector_derivative_def assms\n  using x_in\n  apply (intro has_derivative_If_within_closures[where ?f' = \"\\<lambda>x a. a *\\<^sub>R f' x\" and ?g' = \"\\<lambda>x a. a *\\<^sub>R g' x\",\n        THEN has_derivative_eq_rhs])\n  subgoal by (rule f'[unfolded has_vector_derivative_def]; assumption)\n  subgoal by (rule g'[unfolded has_vector_derivative_def]; assumption)\n  by (auto simp: assms)\n\nsubsection\\<^marker>\\<open>tag important\\<close>\\<open>The Inverse Function Theorem\\<close>\n\nlemma linear_injective_contraction:\n  assumes \"linear f\" \"c < 1\" and le: \"\\<And>x. norm (f x - x) \\<le> c * norm x\"\n  shows \"inj f\"\n  unfolding linear_injective_0[OF \\<open>linear f\\<close>]\nproof safe\n  fix x\n  assume \"f x = 0\"\n  with le [of x] have \"norm x \\<le> c * norm x\"\n    by simp\n  then show \"x = 0\"\n    using \\<open>c < 1\\<close> by (simp add: mult_le_cancel_right1)\nqed\n\ntext\\<open>From an online proof by J. Michael Boardman, Department of Mathematics, Johns Hopkins University\\<close>\nlemma inverse_function_theorem_scaled:\n  fixes f::\"'a::euclidean_space \\<Rightarrow> 'a\"\n    and f'::\"'a \\<Rightarrow> ('a \\<Rightarrow>\\<^sub>L 'a)\"\n  assumes \"open U\"\n    and derf: \"\\<And>x. x \\<in> U \\<Longrightarrow> (f has_derivative blinfun_apply (f' x)) (at x)\"\n    and contf: \"continuous_on U f'\"\n    and \"0 \\<in> U\" and [simp]: \"f 0 = 0\"\n    and id: \"f' 0 = id_blinfun\"\n  obtains U' V g g' where \"open U'\" \"U' \\<subseteq> U\" \"0 \\<in> U'\" \"open V\" \"0 \\<in> V\" \"homeomorphism U' V f g\"\n                \"\\<And>y. y \\<in> V \\<Longrightarrow> (g has_derivative (g' y)) (at y)\"\n                \"\\<And>y. y \\<in> V \\<Longrightarrow> g' y = inv (blinfun_apply (f'(g y)))\"\n                \"\\<And>y. y \\<in> V \\<Longrightarrow> bij (blinfun_apply (f'(g y)))\"\nproof -\n  obtain d1 where \"cball 0 d1 \\<subseteq> U\" \"d1 > 0\"\n    using \\<open>open U\\<close> \\<open>0 \\<in> U\\<close> open_contains_cball by blast\n  obtain d2 where d2: \"\\<And>x. \\<lbrakk>x \\<in> U; dist x 0 \\<le> d2\\<rbrakk> \\<Longrightarrow> dist (f' x) (f' 0) < 1/2\" \"0 < d2\"\n    using continuous_onE [OF contf, of 0 \"1/2\"] by (metis \\<open>0 \\<in> U\\<close> half_gt_zero_iff zero_less_one)\n  obtain \\<delta> where le: \"\\<And>x. norm x \\<le> \\<delta> \\<Longrightarrow> dist (f' x) id_blinfun \\<le> 1/2\" and \"0 < \\<delta>\"\n    and subU: \"cball 0 \\<delta> \\<subseteq> U\"\n  proof\n    show \"min d1 d2 > 0\"\n      by (simp add: \\<open>0 < d1\\<close> \\<open>0 < d2\\<close>)\n    show \"cball 0 (min d1 d2) \\<subseteq> U\"\n      using \\<open>cball 0 d1 \\<subseteq> U\\<close> by auto\n    show \"dist (f' x) id_blinfun \\<le> 1/2\" if \"norm x \\<le> min d1 d2\" for x\n      using \\<open>cball 0 d1 \\<subseteq> U\\<close> d2 that id by fastforce\n  qed\n  let ?D = \"cball 0 \\<delta>\"\n  define V:: \"'a set\" where \"V \\<equiv> ball 0 (\\<delta>/2)\"\n  have 4: \"norm (f (x + h) - f x - h) \\<le> 1/2 * norm h\"\n    if \"x \\<in> ?D\" \"x+h \\<in> ?D\" for x h\n  proof -\n    let ?w = \"\\<lambda>x. f x - x\"\n    have B: \"\\<And>x. x \\<in> ?D \\<Longrightarrow> onorm (blinfun_apply (f' x - id_blinfun)) \\<le> 1/2\"\n      by (metis dist_norm le mem_cball_0 norm_blinfun.rep_eq)\n    have \"\\<And>x. x \\<in> ?D \\<Longrightarrow> (?w has_derivative (blinfun_apply (f' x - id_blinfun))) (at x)\"\n      by (rule derivative_eq_intros derf subsetD [OF subU] | force simp: blinfun.diff_left)+\n    then have Dw: \"\\<And>x. x \\<in> ?D \\<Longrightarrow> (?w has_derivative (blinfun_apply (f' x - id_blinfun))) (at x within ?D)\"\n      using has_derivative_at_withinI by blast\n    have \"norm (?w (x+h) - ?w x) \\<le> (1/2) * norm h\"\n      using differentiable_bound [OF convex_cball Dw B] that by fastforce\n    then show ?thesis\n      by (auto simp: algebra_simps)\n  qed\n  have for_g: \"\\<exists>!x. norm x < \\<delta> \\<and> f x = y\" if y: \"norm y < \\<delta>/2\" for y\n  proof -\n    let ?u = \"\\<lambda>x. x + (y - f x)\"\n    have *: \"norm (?u x) < \\<delta>\" if \"x \\<in> ?D\" for x\n    proof -\n      have fxx: \"norm (f x - x) \\<le> \\<delta>/2\"\n        using 4 [of 0 x] \\<open>0 < \\<delta>\\<close> \\<open>f 0 = 0\\<close> that by auto\n      have \"norm (?u x) \\<le> norm y + norm (f x - x)\"\n        by (metis add.commute add_diff_eq norm_minus_commute norm_triangle_ineq)\n      also have \"\\<dots> < \\<delta>/2 + \\<delta>/2\"\n        using fxx y by auto\n      finally show ?thesis\n        by simp\n    qed\n    have \"\\<exists>!x \\<in> ?D. ?u x = x\"\n    proof (rule banach_fix)\n      show \"cball 0 \\<delta> \\<noteq> {}\"\n        using \\<open>0 < \\<delta>\\<close> by auto\n      show \"(\\<lambda>x. x + (y - f x)) ` cball 0 \\<delta> \\<subseteq> cball 0 \\<delta>\"\n        using * by force\n      have \"dist (x + (y - f x)) (xh + (y - f xh)) * 2 \\<le> dist x xh\"\n        if \"norm x \\<le> \\<delta>\" and \"norm xh \\<le> \\<delta>\" for x xh\n        using that 4 [of x \"xh-x\"] by (auto simp: dist_norm norm_minus_commute algebra_simps)\n      then show \"\\<forall>x\\<in>cball 0 \\<delta>. \\<forall>ya\\<in>cball 0 \\<delta>. dist (x + (y - f x)) (ya + (y - f ya)) \\<le> (1/2) * dist x ya\"\n        by auto\n    qed (auto simp: complete_eq_closed)\n    then show ?thesis\n      by (metis \"*\" add_cancel_right_right eq_iff_diff_eq_0 le_less mem_cball_0)\n  qed\n  define g where \"g \\<equiv> \\<lambda>y. THE x. norm x < \\<delta> \\<and> f x = y\"\n  have g: \"norm (g y) < \\<delta> \\<and> f (g y) = y\" if \"norm y < \\<delta>/2\" for y\n    unfolding g_def using that theI' [OF for_g] by meson\n  then have fg[simp]: \"f (g y) = y\" if \"y \\<in> V\" for y\n    using that by (auto simp: V_def)\n  have 5: \"norm (g y' - g y) \\<le> 2 * norm (y' - y)\" if \"y \\<in> V\" \"y' \\<in> V\" for y y'\n  proof -\n    have no: \"norm (g y) \\<le> \\<delta>\" \"norm (g y') \\<le> \\<delta>\" and [simp]: \"f (g y) = y\"\n      using that g unfolding V_def by force+\n    have \"norm (g y' - g y) \\<le> norm (g y' - g y - (y' - y)) + norm (y' - y)\"\n      by (simp add: add.commute norm_triangle_sub)\n    also have \"\\<dots> \\<le> (1/2) * norm (g y' - g y) + norm (y' - y)\"\n      using 4 [of \"g y\" \"g y' - g y\"] that no by (simp add: g norm_minus_commute V_def)\n    finally show ?thesis\n      by auto\n  qed\n  have contg: \"continuous_on V g\"\n  proof\n    fix y::'a and e::real\n    assume \"0 < e\" and y: \"y \\<in> V\"\n    show \"\\<exists>d>0. \\<forall>x'\\<in>V. dist x' y < d \\<longrightarrow> dist (g x') (g y) \\<le> e\"\n    proof (intro exI conjI ballI impI)\n      show \"0 < e/2\"\n        by (simp add: \\<open>0 < e\\<close>)\n    qed (use 5 y in \\<open>force simp: dist_norm\\<close>)\n  qed\n  show thesis\n  proof\n    define U' where \"U' \\<equiv> (f -` V) \\<inter> ball 0 \\<delta>\"\n    have contf: \"continuous_on U f\"\n      using derf has_derivative_at_withinI by (fast intro: has_derivative_continuous_on)\n    then have \"continuous_on (ball 0 \\<delta>) f\"\n      by (meson ball_subset_cball continuous_on_subset subU)\n    then show \"open U'\"\n      by (simp add: U'_def V_def Int_commute continuous_open_preimage)\n    show \"0 \\<in> U'\" \"U' \\<subseteq> U\" \"open V\" \"0 \\<in> V\"\n      using \\<open>0 < \\<delta>\\<close> subU by (auto simp: U'_def V_def)\n    show hom: \"homeomorphism U' V f g\"\n    proof\n      show \"continuous_on U' f\"\n        using \\<open>U' \\<subseteq> U\\<close> contf continuous_on_subset by blast\n      show \"continuous_on V g\"\n        using contg by blast\n      show \"f ` U' \\<subseteq> V\"\n        using U'_def by blast\n      show \"g ` V \\<subseteq> U'\"\n        by (simp add: U'_def V_def g image_subset_iff)\n      show \"g (f x) = x\" if \"x \\<in> U'\" for x\n        by (metis that fg Int_iff U'_def V_def for_g g mem_ball_0 vimage_eq)\n      show \"f (g y) = y\" if \"y \\<in> V\" for y\n        using that by (simp add: g V_def)\n    qed\n    show bij: \"bij (blinfun_apply (f'(g y)))\" if \"y \\<in> V\" for y\n    proof -\n      have inj: \"inj (blinfun_apply (f' (g y)))\"\n      proof (rule linear_injective_contraction)\n        show \"linear (blinfun_apply (f' (g y)))\"\n          using blinfun.bounded_linear_right bounded_linear_def by blast\n      next\n        fix x\n        have \"norm (blinfun_apply (f' (g y)) x - x) = norm (blinfun_apply (f' (g y) - id_blinfun) x)\"\n          by (simp add: blinfun.diff_left)\n        also have \"\\<dots> \\<le> norm (f' (g y) - id_blinfun) * norm x\"\n          by (rule norm_blinfun)\n        also have \"\\<dots> \\<le> (1/2) * norm x\"\n        proof (rule mult_right_mono)\n          show \"norm (f' (g y) - id_blinfun) \\<le> 1/2\"\n            using that g [of y] le by (auto simp: V_def dist_norm)\n        qed auto\n        finally show \"norm (blinfun_apply (f' (g y)) x - x) \\<le> (1/2) * norm x\" .\n      qed auto\n      moreover\n      have \"surj (blinfun_apply (f' (g y)))\"\n        using blinfun.bounded_linear_right bounded_linear_def\n        by (blast intro!: linear_inj_imp_surj [OF _ inj])\n      ultimately show ?thesis\n        using bijI by blast\n    qed\n    define g' where \"g' \\<equiv> \\<lambda>y. inv (blinfun_apply (f'(g y)))\"\n    show \"(g has_derivative g' y) (at y)\" if \"y \\<in> V\" for y\n    proof -\n      have gy: \"g y \\<in> U\"\n        using g subU that unfolding V_def by fastforce\n      obtain e where e: \"\\<And>h. f (g y + h) = y + blinfun_apply (f' (g y)) h + e h\"\n        and e0: \"(\\<lambda>h. norm (e h) / norm h) \\<midarrow>0\\<rightarrow> 0\"\n        using iffD1 [OF has_derivative_iff_Ex derf [OF gy]] \\<open>y \\<in> V\\<close> by auto\n      have [simp]: \"e 0 = 0\"\n        using e [of 0] that by simp\n      let ?INV = \"inv (blinfun_apply (f' (g y)))\"\n      have inj: \"inj (blinfun_apply (f' (g y)))\"\n        using bij bij_betw_def that by blast\n      have \"(g has_derivative g' y) (at y within V)\"\n        unfolding has_derivative_at_within_iff_Ex [OF \\<open>y \\<in> V\\<close> \\<open>open V\\<close>]\n      proof\n        show blinv: \"bounded_linear (g' y)\"\n          unfolding g'_def using derf gy inj inj_linear_imp_inv_bounded_linear by blast\n        define eg where \"eg \\<equiv> \\<lambda>k. - ?INV (e (g (y+k) - g y))\"\n        have \"g (y+k) = g y + g' y k + eg k\" if \"y + k \\<in> V\" for k\n        proof -\n          have \"?INV k = ?INV (blinfun_apply (f' (g y)) (g (y+k) - g y) + e (g (y+k) - g y))\"\n            using e [of \"g(y+k) - g y\"] that by simp\n          then have \"g (y+k) = g y + ?INV k - ?INV (e (g (y+k) - g y))\"\n            using inj blinv by (simp add: linear_simps g'_def)\n          then show ?thesis\n            by (auto simp: eg_def g'_def)\n        qed\n        moreover have \"(\\<lambda>k. norm (eg k) / norm k) \\<midarrow>0\\<rightarrow> 0\"\n        proof (rule Lim_null_comparison)\n          let ?g = \"\\<lambda>k. 2 * onorm ?INV * norm (e (g (y+k) - g y)) / norm (g (y+k) - g y)\"\n          show \"\\<forall>\\<^sub>F k in at 0. norm (norm (eg k) / norm k) \\<le> ?g k\"\n            unfolding eventually_at_topological\n          proof (intro exI conjI ballI impI)\n            show \"open ((+)(-y) ` V)\"\n              using \\<open>open V\\<close> open_translation by blast\n            show \"0 \\<in> (+)(-y) ` V\"\n              by (simp add: that)\n            show \"norm (norm (eg k) / norm k) \\<le> 2 * onorm (inv (blinfun_apply (f' (g y)))) * norm (e (g (y+k) - g y)) / norm (g (y+k) - g y)\"\n              if \"k \\<in> (+)(-y) ` V\" \"k \\<noteq> 0\" for k\n            proof -\n              have \"y+k \\<in> V\"\n                using that by auto\n              have \"norm (norm (eg k) / norm k) \\<le> onorm ?INV * norm (e (g (y+k) - g y)) / norm k\"\n                using blinv g'_def onorm by (force simp: eg_def divide_simps)\n              also have \"\\<dots> = (norm (g (y+k) - g y) / norm k) * (onorm ?INV * (norm (e (g (y+k) - g y)) / norm (g (y+k) - g y)))\"\n                by (simp add: divide_simps)\n              also have \"\\<dots> \\<le> 2 * (onorm ?INV * (norm (e (g (y+k) - g y)) / norm (g (y+k) - g y)))\"\n                apply (rule mult_right_mono)\n                using 5 [of y \"y+k\"] \\<open>y \\<in> V\\<close> \\<open>y + k \\<in> V\\<close>  onorm_pos_le [OF blinv]\n                 apply (auto simp: divide_simps zero_le_mult_iff zero_le_divide_iff g'_def)\n                done\n              finally show \"norm (norm (eg k) / norm k) \\<le> 2 * onorm ?INV * norm (e (g (y+k) - g y)) / norm (g (y+k) - g y)\"\n                by simp\n            qed\n          qed\n          have 1: \"(\\<lambda>h. norm (e h) / norm h) \\<midarrow>0\\<rightarrow> (norm (e 0) / norm 0)\"\n            using e0 by auto\n          have 2: \"(\\<lambda>k. g (y+k) - g y) \\<midarrow>0\\<rightarrow> 0\"\n            using contg \\<open>open V\\<close> \\<open>y \\<in> V\\<close> LIM_offset_zero_iff LIM_zero_iff at_within_open continuous_on_def by fastforce\n          from tendsto_compose [OF 1 2, simplified]\n          have \"(\\<lambda>k. norm (e (g (y+k) - g y)) / norm (g (y+k) - g y)) \\<midarrow>0\\<rightarrow> 0\" .\n          from tendsto_mult_left [OF this] show \"?g \\<midarrow>0\\<rightarrow> 0\" by auto\n        qed\n        ultimately show \"\\<exists>e. (\\<forall>k. y + k \\<in> V \\<longrightarrow> g (y+k) = g y + g' y k + e k) \\<and> (\\<lambda>k. norm (e k) / norm k) \\<midarrow>0\\<rightarrow> 0\"\n          by blast\n      qed\n      then show ?thesis\n        by (metis \\<open>open V\\<close> at_within_open that)\n    qed\n    show \"g' y = inv (blinfun_apply (f' (g y)))\"\n      if \"y \\<in> V\" for y\n      by (simp add: g'_def)\n  qed\nqed\n\n\ntext\\<open>We need all this to justify the scaling and translations.\\<close>\ntheorem inverse_function_theorem:\n  fixes f::\"'a::euclidean_space \\<Rightarrow> 'a\"\n    and f'::\"'a \\<Rightarrow> ('a \\<Rightarrow>\\<^sub>L 'a)\"\n  assumes \"open U\"\n    and derf: \"\\<And>x. x \\<in> U \\<Longrightarrow> (f has_derivative (blinfun_apply (f' x))) (at x)\"\n    and contf:  \"continuous_on U f'\"\n    and \"x0 \\<in> U\"\n    and invf: \"invf o\\<^sub>L f' x0 = id_blinfun\"\n  obtains U' V g g' where \"open U'\" \"U' \\<subseteq> U\" \"x0 \\<in> U'\" \"open V\" \"f x0 \\<in> V\" \"homeomorphism U' V f g\"\n    \"\\<And>y. y \\<in> V \\<Longrightarrow> (g has_derivative (g' y)) (at y)\"\n    \"\\<And>y. y \\<in> V \\<Longrightarrow> g' y = inv (blinfun_apply (f'(g y)))\"\n    \"\\<And>y. y \\<in> V \\<Longrightarrow> bij (blinfun_apply (f'(g y)))\"\nproof -\n  have apply1 [simp]: \"\\<And>i. blinfun_apply invf (blinfun_apply (f' x0) i) = i\"\n    by (metis blinfun_apply_blinfun_compose blinfun_apply_id_blinfun invf)\n  have apply2 [simp]: \"\\<And>i. blinfun_apply (f' x0) (blinfun_apply invf i) = i\"\n    by (metis apply1 bij_inv_eq_iff blinfun_bij1 invf)\n  have [simp]: \"(range (blinfun_apply invf)) = UNIV\"\n    using apply1 surjI by blast\n  let ?f = \"invf \\<circ> (\\<lambda>x. (f \\<circ> (+)x0)x - f x0)\"\n  let ?f' = \"\\<lambda>x. invf o\\<^sub>L (f' (x + x0))\"\n  obtain U' V g g' where \"open U'\" and U': \"U' \\<subseteq> (+)(-x0) ` U\" \"0 \\<in> U'\"\n    and \"open V\" \"0 \\<in> V\" and hom: \"homeomorphism U' V ?f g\"\n    and derg: \"\\<And>y. y \\<in> V \\<Longrightarrow> (g has_derivative (g' y)) (at y)\"\n    and g': \"\\<And>y. y \\<in> V \\<Longrightarrow> g' y = inv (?f'(g y))\"\n    and bij: \"\\<And>y. y \\<in> V \\<Longrightarrow> bij (?f'(g y))\"\n  proof (rule inverse_function_theorem_scaled [of \"(+)(-x0) ` U\" ?f \"?f'\"])\n    show ope: \"open ((+) (- x0) ` U)\"\n      using \\<open>open U\\<close> open_translation by blast\n    show \"(?f has_derivative blinfun_apply (?f' x)) (at x)\"\n      if \"x \\<in> (+) (- x0) ` U\" for x\n      using that\n      apply clarify\n      apply (rule derf derivative_eq_intros | simp add: blinfun_compose.rep_eq)+\n      done\n    have YY: \"(\\<lambda>x. f' (x + x0)) \\<midarrow>u-x0\\<rightarrow> f' u\"\n      if \"f' \\<midarrow>u\\<rightarrow> f' u\" \"u \\<in> U\" for u\n      using that LIM_offset [where k = x0] by (auto simp: algebra_simps)\n    then have \"continuous_on ((+) (- x0) ` U) (\\<lambda>x. f' (x + x0))\"\n      using contf \\<open>open U\\<close> Lim_at_imp_Lim_at_within\n      by (fastforce simp: continuous_on_def at_within_open_NO_MATCH ope)\n    then show \"continuous_on ((+) (- x0) ` U) ?f'\"\n      by (intro continuous_intros) simp\n  qed (auto simp: invf \\<open>x0 \\<in> U\\<close>)\n  show thesis\n  proof\n    let ?U' = \"(+)x0 ` U'\"\n    let ?V = \"((+)(f x0) \\<circ> f' x0) ` V\"\n    let ?g = \"(+)x0 \\<circ> g \\<circ> invf \\<circ> (+)(- f x0)\"\n    let ?g' = \"\\<lambda>y. inv (blinfun_apply (f' (?g y)))\"\n    show oU': \"open ?U'\"\n      by (simp add: \\<open>open U'\\<close> open_translation)\n    show subU: \"?U' \\<subseteq> U\"\n      using ComplI \\<open>U' \\<subseteq> (+) (- x0) ` U\\<close> by auto\n    show \"x0 \\<in> ?U'\"\n      by (simp add: \\<open>0 \\<in> U'\\<close>)\n    show \"open ?V\"\n      using blinfun_bij2 [OF invf]\n      by (metis \\<open>open V\\<close> bij_is_surj blinfun.bounded_linear_right bounded_linear_def image_comp open_surjective_linear_image open_translation)\n    show \"f x0 \\<in> ?V\"\n      using \\<open>0 \\<in> V\\<close> image_iff by fastforce\n    show \"homeomorphism ?U' ?V f ?g\"\n    proof\n      show \"continuous_on ?U' f\"\n        by (meson subU continuous_on_eq_continuous_at derf has_derivative_continuous oU' subsetD)\n      have \"?f ` U' \\<subseteq> V\"\n        using hom homeomorphism_image1 by blast\n      then show \"f ` ?U' \\<subseteq> ?V\"\n        unfolding image_subset_iff\n        by (clarsimp simp: image_def) (metis apply2 add.commute diff_add_cancel)\n      show \"?g ` ?V \\<subseteq> ?U'\"\n        using hom invf by (auto simp: image_def homeomorphism_def)\n      show \"?g (f x) = x\"\n        if \"x \\<in> ?U'\" for x\n        using that hom homeomorphism_apply1 by fastforce\n      have \"continuous_on V g\"\n        using hom homeomorphism_def by blast\n      then show \"continuous_on ?V ?g\"\n        by (intro continuous_intros) (auto elim!: continuous_on_subset)\n      have fg: \"?f (g x) = x\" if \"x \\<in> V\" for x\n        using hom homeomorphism_apply2 that by blast\n      show \"f (?g y) = y\"\n        if \"y \\<in> ?V\" for y\n        using that fg by (simp add: image_iff) (metis apply2 add.commute diff_add_cancel)\n    qed\n    show \"(?g has_derivative ?g' y) (at y)\" \"bij (blinfun_apply (f' (?g y)))\"\n      if \"y \\<in> ?V\" for y\n    proof -\n      have 1: \"bij (blinfun_apply invf)\"\n        using blinfun_bij1 invf by blast\n      then have 2: \"bij (blinfun_apply (f' (x0 + g x)))\" if \"x \\<in> V\" for x\n        by (metis add.commute bij bij_betw_comp_iff2 blinfun_compose.rep_eq that top_greatest)\n      then show \"bij (blinfun_apply (f' (?g y)))\"\n        using that by auto\n      have \"g' x \\<circ> blinfun_apply invf = inv (blinfun_apply (f' (x0 + g x)))\"\n        if \"x \\<in> V\" for x\n        using that\n        by (simp add: g' o_inv_distrib blinfun_compose.rep_eq 1 2 add.commute bij_is_inj flip: o_assoc)\n      then show \"(?g has_derivative ?g' y) (at y)\"\n        using that invf\n        by clarsimp (rule derg derivative_eq_intros | simp flip: id_def)+\n    qed\n  qed auto\nqed\n\n\nsubsection\\<^marker>\\<open>tag unimportant\\<close> \\<open>Piecewise differentiable functions\\<close>\n\ndefinition piecewise_differentiable_on\n           (infixr \"piecewise'_differentiable'_on\" 50)\n  where \"f piecewise_differentiable_on i  \\<equiv>\n           continuous_on i f \\<and>\n           (\\<exists>S. finite S \\<and> (\\<forall>x \\<in> i - S. f differentiable (at x within i)))\"\n\nlemma piecewise_differentiable_on_imp_continuous_on:\n    \"f piecewise_differentiable_on S \\<Longrightarrow> continuous_on S f\"\nby (simp add: piecewise_differentiable_on_def)\n\nlemma piecewise_differentiable_on_subset:\n    \"f piecewise_differentiable_on S \\<Longrightarrow> T \\<le> S \\<Longrightarrow> f piecewise_differentiable_on T\"\n  using continuous_on_subset\n  unfolding piecewise_differentiable_on_def\n  apply safe\n  apply (blast elim: continuous_on_subset)\n  by (meson Diff_iff differentiable_within_subset subsetCE)\n\nlemma differentiable_on_imp_piecewise_differentiable:\n  fixes a:: \"'a::{linorder_topology,real_normed_vector}\"\n  shows \"f differentiable_on {a..b} \\<Longrightarrow> f piecewise_differentiable_on {a..b}\"\n  apply (simp add: piecewise_differentiable_on_def differentiable_imp_continuous_on)\n  apply (rule_tac x=\"{a,b}\" in exI, simp add: differentiable_on_def)\n  done\n\nlemma differentiable_imp_piecewise_differentiable:\n    \"(\\<And>x. x \\<in> S \\<Longrightarrow> f differentiable (at x within S))\n         \\<Longrightarrow> f piecewise_differentiable_on S\"\nby (auto simp: piecewise_differentiable_on_def differentiable_imp_continuous_on differentiable_on_def\n         intro: differentiable_within_subset)\n\nlemma piecewise_differentiable_const [iff]: \"(\\<lambda>x. z) piecewise_differentiable_on S\"\n  by (simp add: differentiable_imp_piecewise_differentiable)\n\nlemma piecewise_differentiable_compose:\n    \"\\<lbrakk>f piecewise_differentiable_on S; g piecewise_differentiable_on (f ` S);\n      \\<And>x. finite (S \\<inter> f-`{x})\\<rbrakk>\n      \\<Longrightarrow> (g \\<circ> f) piecewise_differentiable_on S\"\n  apply (simp add: piecewise_differentiable_on_def, safe)\n  apply (blast intro: continuous_on_compose2)\n  apply (rename_tac A B)\n  apply (rule_tac x=\"A \\<union> (\\<Union>x\\<in>B. S \\<inter> f-`{x})\" in exI)\n  apply (blast intro!: differentiable_chain_within)\n  done\n\nlemma piecewise_differentiable_affine:\n  fixes m::real\n  assumes \"f piecewise_differentiable_on ((\\<lambda>x. m *\\<^sub>R x + c) ` S)\"\n  shows \"(f \\<circ> (\\<lambda>x. m *\\<^sub>R x + c)) piecewise_differentiable_on S\"\nproof (cases \"m = 0\")\n  case True\n  then show ?thesis\n    unfolding o_def\n    by (force intro: differentiable_imp_piecewise_differentiable differentiable_const)\nnext\n  case False\n  show ?thesis\n    apply (rule piecewise_differentiable_compose [OF differentiable_imp_piecewise_differentiable])\n    apply (rule assms derivative_intros | simp add: False vimage_def real_vector_affinity_eq)+\n    done\nqed\n\nlemma piecewise_differentiable_cases:\n  fixes c::real\n  assumes \"f piecewise_differentiable_on {a..c}\"\n          \"g piecewise_differentiable_on {c..b}\"\n           \"a \\<le> c\" \"c \\<le> b\" \"f c = g c\"\n  shows \"(\\<lambda>x. if x \\<le> c then f x else g x) piecewise_differentiable_on {a..b}\"\nproof -\n  obtain S T where st: \"finite S\" \"finite T\"\n               and fd: \"\\<And>x. x \\<in> {a..c} - S \\<Longrightarrow> f differentiable at x within {a..c}\"\n               and gd: \"\\<And>x. x \\<in> {c..b} - T \\<Longrightarrow> g differentiable at x within {c..b}\"\n    using assms\n    by (auto simp: piecewise_differentiable_on_def)\n  have finabc: \"finite ({a,b,c} \\<union> (S \\<union> T))\"\n    by (metis \\<open>finite S\\<close> \\<open>finite T\\<close> finite_Un finite_insert finite.emptyI)\n  have \"continuous_on {a..c} f\" \"continuous_on {c..b} g\"\n    using assms piecewise_differentiable_on_def by auto\n  then have \"continuous_on {a..b} (\\<lambda>x. if x \\<le> c then f x else g x)\"\n    using continuous_on_cases [OF closed_real_atLeastAtMost [of a c],\n                               OF closed_real_atLeastAtMost [of c b],\n                               of f g \"\\<lambda>x. x\\<le>c\"]  assms\n    by (force simp: ivl_disj_un_two_touch)\n  moreover\n  { fix x\n    assume x: \"x \\<in> {a..b} - ({a,b,c} \\<union> (S \\<union> T))\"\n    have \"(\\<lambda>x. if x \\<le> c then f x else g x) differentiable at x within {a..b}\" (is \"?diff_fg\")\n    proof (cases x c rule: le_cases)\n      case le show ?diff_fg\n      proof (rule differentiable_transform_within [where d = \"dist x c\"])\n        have \"f differentiable at x\"\n          using x le fd [of x] at_within_interior [of x \"{a..c}\"] by simp\n        then show \"f differentiable at x within {a..b}\"\n          by (simp add: differentiable_at_withinI)\n      qed (use x le st dist_real_def in auto)\n    next\n      case ge show ?diff_fg\n      proof (rule differentiable_transform_within [where d = \"dist x c\"])\n        have \"g differentiable at x\"\n          using x ge gd [of x] at_within_interior [of x \"{c..b}\"] by simp\n        then show \"g differentiable at x within {a..b}\"\n          by (simp add: differentiable_at_withinI)\n      qed (use x ge st dist_real_def in auto)\n    qed\n  }\n  then have \"\\<exists>S. finite S \\<and>\n                 (\\<forall>x\\<in>{a..b} - S. (\\<lambda>x. if x \\<le> c then f x else g x) differentiable at x within {a..b})\"\n    by (meson finabc)\n  ultimately show ?thesis\n    by (simp add: piecewise_differentiable_on_def)\nqed\n\nlemma piecewise_differentiable_neg:\n    \"f piecewise_differentiable_on S \\<Longrightarrow> (\\<lambda>x. -(f x)) piecewise_differentiable_on S\"\n  by (auto simp: piecewise_differentiable_on_def continuous_on_minus)\n\nlemma piecewise_differentiable_add:\n  assumes \"f piecewise_differentiable_on i\"\n          \"g piecewise_differentiable_on i\"\n    shows \"(\\<lambda>x. f x + g x) piecewise_differentiable_on i\"\nproof -\n  obtain S T where st: \"finite S\" \"finite T\"\n                       \"\\<forall>x\\<in>i - S. f differentiable at x within i\"\n                       \"\\<forall>x\\<in>i - T. g differentiable at x within i\"\n    using assms by (auto simp: piecewise_differentiable_on_def)\n  then have \"finite (S \\<union> T) \\<and> (\\<forall>x\\<in>i - (S \\<union> T). (\\<lambda>x. f x + g x) differentiable at x within i)\"\n    by auto\n  moreover have \"continuous_on i f\" \"continuous_on i g\"\n    using assms piecewise_differentiable_on_def by auto\n  ultimately show ?thesis\n    by (auto simp: piecewise_differentiable_on_def continuous_on_add)\nqed\n\nlemma piecewise_differentiable_diff:\n    \"\\<lbrakk>f piecewise_differentiable_on S;  g piecewise_differentiable_on S\\<rbrakk>\n     \\<Longrightarrow> (\\<lambda>x. f x - g x) piecewise_differentiable_on S\"\n  unfolding diff_conv_add_uminus\n  by (metis piecewise_differentiable_add piecewise_differentiable_neg)\n\n\nsubsection\\<open>The concept of continuously differentiable\\<close>\n\ntext \\<open>\nJohn Harrison writes as follows:\n\n``The usual assumption in complex analysis texts is that a path \\<open>\\<gamma>\\<close> should be piecewise\ncontinuously differentiable, which ensures that the path integral exists at least for any continuous\nf, since all piecewise continuous functions are integrable. However, our notion of validity is\nweaker, just piecewise differentiability\\ldots{} [namely] continuity plus differentiability except on a\nfinite set\\ldots{} [Our] underlying theory of integration is the Kurzweil-Henstock theory. In contrast to\nthe Riemann or Lebesgue theory (but in common with a simple notion based on antiderivatives), this\ncan integrate all derivatives.''\n\n\"Formalizing basic complex analysis.\" From Insight to Proof: Festschrift in Honour of Andrzej Trybulec.\nStudies in Logic, Grammar and Rhetoric 10.23 (2007): 151-165.\n\nAnd indeed he does not assume that his derivatives are continuous, but the penalty is unreasonably\ndifficult proofs concerning winding numbers. We need a self-contained and straightforward theorem\nasserting that all derivatives can be integrated before we can adopt Harrison's choice.\\<close>\n\ndefinition\\<^marker>\\<open>tag important\\<close> C1_differentiable_on :: \"(real \\<Rightarrow> 'a::real_normed_vector) \\<Rightarrow> real set \\<Rightarrow> bool\"\n           (infix \"C1'_differentiable'_on\" 50)\n  where\n  \"f C1_differentiable_on S \\<longleftrightarrow>\n   (\\<exists>D. (\\<forall>x \\<in> S. (f has_vector_derivative (D x)) (at x)) \\<and> continuous_on S D)\"\n\nlemma C1_differentiable_on_eq:\n    \"f C1_differentiable_on S \\<longleftrightarrow>\n     (\\<forall>x \\<in> S. f differentiable at x) \\<and> continuous_on S (\\<lambda>x. vector_derivative f (at x))\"\n     (is \"?lhs = ?rhs\")\nproof\n  assume ?lhs\n  then show ?rhs\n    unfolding C1_differentiable_on_def\n    by (metis (no_types, lifting) continuous_on_eq  differentiableI_vector vector_derivative_at)\nnext\n  assume ?rhs\n  then show ?lhs\n    using C1_differentiable_on_def vector_derivative_works by fastforce\nqed\n\nlemma C1_differentiable_on_subset:\n  \"f C1_differentiable_on T \\<Longrightarrow> S \\<subseteq> T \\<Longrightarrow> f C1_differentiable_on S\"\n  unfolding C1_differentiable_on_def  continuous_on_eq_continuous_within\n  by (blast intro:  continuous_within_subset)\n\nlemma C1_differentiable_compose:\n  assumes fg: \"f C1_differentiable_on S\" \"g C1_differentiable_on (f ` S)\" and fin: \"\\<And>x. finite (S \\<inter> f-`{x})\"\n  shows \"(g \\<circ> f) C1_differentiable_on S\"\nproof -\n  have \"\\<And>x. x \\<in> S \\<Longrightarrow> g \\<circ> f differentiable at x\"\n    by (meson C1_differentiable_on_eq assms differentiable_chain_at imageI)\n  moreover have \"continuous_on S (\\<lambda>x. vector_derivative (g \\<circ> f) (at x))\"\n  proof (rule continuous_on_eq [of _ \"\\<lambda>x. vector_derivative f (at x) *\\<^sub>R vector_derivative g (at (f x))\"])\n    show \"continuous_on S (\\<lambda>x. vector_derivative f (at x) *\\<^sub>R vector_derivative g (at (f x)))\"\n      using fg\n      apply (clarsimp simp add: C1_differentiable_on_eq)\n      apply (rule Limits.continuous_on_scaleR, assumption)\n      by (metis (mono_tags, lifting) continuous_at_imp_continuous_on continuous_on_compose continuous_on_cong differentiable_imp_continuous_within o_def)\n    show \"\\<And>x. x \\<in> S \\<Longrightarrow> vector_derivative f (at x) *\\<^sub>R vector_derivative g (at (f x)) = vector_derivative (g \\<circ> f) (at x)\"\n      by (metis (mono_tags, opaque_lifting) C1_differentiable_on_eq fg imageI vector_derivative_chain_at)\n  qed\n  ultimately show ?thesis\n    by (simp add: C1_differentiable_on_eq)\nqed\n\nlemma C1_diff_imp_diff: \"f C1_differentiable_on S \\<Longrightarrow> f differentiable_on S\"\n  by (simp add: C1_differentiable_on_eq differentiable_at_imp_differentiable_on)\n\nlemma C1_differentiable_on_ident [simp, derivative_intros]: \"(\\<lambda>x. x) C1_differentiable_on S\"\n  by (auto simp: C1_differentiable_on_eq)\n\nlemma C1_differentiable_on_const [simp, derivative_intros]: \"(\\<lambda>z. a) C1_differentiable_on S\"\n  by (auto simp: C1_differentiable_on_eq)\n\nlemma C1_differentiable_on_add [simp, derivative_intros]:\n  \"f C1_differentiable_on S \\<Longrightarrow> g C1_differentiable_on S \\<Longrightarrow> (\\<lambda>x. f x + g x) C1_differentiable_on S\"\n  unfolding C1_differentiable_on_eq  by (auto intro: continuous_intros)\n\nlemma C1_differentiable_on_minus [simp, derivative_intros]:\n  \"f C1_differentiable_on S \\<Longrightarrow> (\\<lambda>x. - f x) C1_differentiable_on S\"\n  unfolding C1_differentiable_on_eq  by (auto intro: continuous_intros)\n\nlemma C1_differentiable_on_diff [simp, derivative_intros]:\n  \"f C1_differentiable_on S \\<Longrightarrow> g C1_differentiable_on S \\<Longrightarrow> (\\<lambda>x. f x - g x) C1_differentiable_on S\"\n  unfolding C1_differentiable_on_eq  by (auto intro: continuous_intros)\n\nlemma C1_differentiable_on_mult [simp, derivative_intros]:\n  fixes f g :: \"real \\<Rightarrow> 'a :: real_normed_algebra\"\n  shows \"f C1_differentiable_on S \\<Longrightarrow> g C1_differentiable_on S \\<Longrightarrow> (\\<lambda>x. f x * g x) C1_differentiable_on S\"\n  unfolding C1_differentiable_on_eq\n  by (auto simp: continuous_on_add continuous_on_mult continuous_at_imp_continuous_on differentiable_imp_continuous_within)\n\nlemma C1_differentiable_on_scaleR [simp, derivative_intros]:\n  \"f C1_differentiable_on S \\<Longrightarrow> g C1_differentiable_on S \\<Longrightarrow> (\\<lambda>x. f x *\\<^sub>R g x) C1_differentiable_on S\"\n  unfolding C1_differentiable_on_eq\n  by (rule continuous_intros | simp add: continuous_at_imp_continuous_on differentiable_imp_continuous_within)+\n\nlemma C1_differentiable_on_of_real [derivative_intros]: \"of_real C1_differentiable_on S\"\n  unfolding C1_differentiable_on_def\n  by (smt (verit, del_insts) DERIV_ident UNIV_I continuous_on_const has_vector_derivative_of_real has_vector_derivative_transform)\n\n\ndefinition\\<^marker>\\<open>tag important\\<close> piecewise_C1_differentiable_on\n           (infixr \"piecewise'_C1'_differentiable'_on\" 50)\n  where \"f piecewise_C1_differentiable_on i  \\<equiv>\n           continuous_on i f \\<and>\n           (\\<exists>S. finite S \\<and> (f C1_differentiable_on (i - S)))\"\n\nlemma C1_differentiable_imp_piecewise:\n    \"f C1_differentiable_on S \\<Longrightarrow> f piecewise_C1_differentiable_on S\"\n  by (auto simp: piecewise_C1_differentiable_on_def C1_differentiable_on_eq continuous_at_imp_continuous_on differentiable_imp_continuous_within)\n\nlemma piecewise_C1_imp_differentiable:\n    \"f piecewise_C1_differentiable_on i \\<Longrightarrow> f piecewise_differentiable_on i\"\n  by (auto simp: piecewise_C1_differentiable_on_def piecewise_differentiable_on_def\n           C1_differentiable_on_def differentiable_def has_vector_derivative_def\n           intro: has_derivative_at_withinI)\n\nlemma piecewise_C1_differentiable_compose [derivative_intros]:\n  assumes fg: \"f piecewise_C1_differentiable_on S\" \"g piecewise_C1_differentiable_on (f ` S)\" and fin: \"\\<And>x. finite (S \\<inter> f-`{x})\"\n  shows \"(g \\<circ> f) piecewise_C1_differentiable_on S\"\nproof -\n  have \"continuous_on S (\\<lambda>x. g (f x))\"\n    by (metis continuous_on_compose2 fg order_refl piecewise_C1_differentiable_on_def)\n  moreover have \"\\<exists>T. finite T \\<and> g \\<circ> f C1_differentiable_on S - T\"\n  proof -\n    obtain F where \"finite F\" and F: \"f C1_differentiable_on S - F\" and f: \"f piecewise_C1_differentiable_on S\"\n      using fg by (auto simp: piecewise_C1_differentiable_on_def)\n    obtain G where \"finite G\" and G: \"g C1_differentiable_on f ` S - G\" and g: \"g piecewise_C1_differentiable_on f ` S\"\n      using fg by (auto simp: piecewise_C1_differentiable_on_def)\n    show ?thesis\n    proof (intro exI conjI)\n      show \"finite (F \\<union> (\\<Union>x\\<in>G. S \\<inter> f-`{x}))\"\n        using fin by (auto simp only: Int_Union \\<open>finite F\\<close> \\<open>finite G\\<close> finite_UN finite_imageI)\n      show \"g \\<circ> f C1_differentiable_on S - (F \\<union> (\\<Union>x\\<in>G. S \\<inter> f -` {x}))\"\n        apply (rule C1_differentiable_compose)\n          apply (blast intro: C1_differentiable_on_subset [OF F])\n          apply (blast intro: C1_differentiable_on_subset [OF G])\n        by (simp add:  C1_differentiable_on_subset G Diff_Int_distrib2 fin)\n    qed\n  qed\n  ultimately show ?thesis\n    by (simp add: piecewise_C1_differentiable_on_def)\nqed\n\nlemma piecewise_C1_differentiable_on_subset:\n    \"f piecewise_C1_differentiable_on S \\<Longrightarrow> T \\<le> S \\<Longrightarrow> f piecewise_C1_differentiable_on T\"\n  by (auto simp: piecewise_C1_differentiable_on_def elim!: continuous_on_subset C1_differentiable_on_subset)\n\nlemma C1_differentiable_imp_continuous_on:\n  \"f C1_differentiable_on S \\<Longrightarrow> continuous_on S f\"\n  unfolding C1_differentiable_on_eq continuous_on_eq_continuous_within\n  using differentiable_at_withinI differentiable_imp_continuous_within by blast\n\nlemma C1_differentiable_on_empty [iff,derivative_intros]: \"f C1_differentiable_on {}\"\n  unfolding C1_differentiable_on_def\n  by auto\n\nlemma piecewise_C1_differentiable_affine:\n  fixes m::real\n  assumes \"f piecewise_C1_differentiable_on ((\\<lambda>x. m * x + c) ` S)\"\n  shows \"(f \\<circ> (\\<lambda>x. m *\\<^sub>R x + c)) piecewise_C1_differentiable_on S\"\nproof (cases \"m = 0\")\n  case True\n  then show ?thesis\n    unfolding o_def by (auto simp: piecewise_C1_differentiable_on_def)\nnext\n  case False\n  have *: \"\\<And>x. finite (S \\<inter> {y. m * y + c = x})\"\n    using False not_finite_existsD by fastforce\n  show ?thesis\n    apply (rule piecewise_C1_differentiable_compose [OF C1_differentiable_imp_piecewise])\n    apply (rule * assms derivative_intros | simp add: False vimage_def)+\n    done\nqed\n\nlemma piecewise_C1_differentiable_cases [derivative_intros]:\n  fixes c::real\n  assumes \"f piecewise_C1_differentiable_on {a..c}\"\n          \"g piecewise_C1_differentiable_on {c..b}\"\n           \"a \\<le> c\" \"c \\<le> b\" \"f c = g c\"\n  shows \"(\\<lambda>x. if x \\<le> c then f x else g x) piecewise_C1_differentiable_on {a..b}\"\nproof -\n  obtain S T where st: \"f C1_differentiable_on ({a..c} - S)\"\n                       \"g C1_differentiable_on ({c..b} - T)\"\n                       \"finite S\" \"finite T\"\n    using assms\n    by (force simp: piecewise_C1_differentiable_on_def)\n  then have f_diff: \"f differentiable_on {a..<c} - S\"\n        and g_diff: \"g differentiable_on {c<..b} - T\"\n    by (simp_all add: C1_differentiable_on_eq differentiable_at_withinI differentiable_on_def)\n  have \"continuous_on {a..c} f\" \"continuous_on {c..b} g\"\n    using assms piecewise_C1_differentiable_on_def by auto\n  then have cab: \"continuous_on {a..b} (\\<lambda>x. if x \\<le> c then f x else g x)\"\n    using continuous_on_cases [OF closed_real_atLeastAtMost [of a c],\n                               OF closed_real_atLeastAtMost [of c b],\n                               of f g \"\\<lambda>x. x\\<le>c\"]  assms\n    by (force simp: ivl_disj_un_two_touch)\n  { fix x\n    assume x: \"x \\<in> {a..b} - insert c (S \\<union> T)\"\n    have \"(\\<lambda>x. if x \\<le> c then f x else g x) differentiable at x\" (is \"?diff_fg\")\n    proof (cases x c rule: le_cases)\n      case le show ?diff_fg\n        apply (rule differentiable_transform_within [where f=f and d = \"dist x c\"])\n        using x dist_real_def le st by (auto simp: C1_differentiable_on_eq)\n    next\n      case ge show ?diff_fg\n        apply (rule differentiable_transform_within [where f=g and d = \"dist x c\"])\n        using dist_nz x dist_real_def ge st x by (auto simp: C1_differentiable_on_eq)\n    qed\n  }\n  then have \"(\\<forall>x \\<in> {a..b} - insert c (S \\<union> T). (\\<lambda>x. if x \\<le> c then f x else g x) differentiable at x)\"\n    by auto\n  moreover\n  { assume fcon: \"continuous_on ({a<..<c} - S) (\\<lambda>x. vector_derivative f (at x))\"\n       and gcon: \"continuous_on ({c<..<b} - T) (\\<lambda>x. vector_derivative g (at x))\"\n    have \"open ({a<..<c} - S)\"  \"open ({c<..<b} - T)\"\n      using st by (simp_all add: open_Diff finite_imp_closed)\n    moreover have \"continuous_on ({a<..<c} - S) (\\<lambda>x. vector_derivative (\\<lambda>x. if x \\<le> c then f x else g x) (at x))\"\n    proof -\n      have \"((\\<lambda>x. if x \\<le> c then f x else g x) has_vector_derivative vector_derivative f (at x))            (at x)\"\n        if \"a < x\" \"x < c\" \"x \\<notin> S\" for x\n      proof -\n        have f: \"f differentiable at x\"\n          by (meson C1_differentiable_on_eq Diff_iff atLeastAtMost_iff less_eq_real_def st(1) that)\n        show ?thesis\n          using that\n          apply (rule_tac f=f and d=\"dist x c\" in has_vector_derivative_transform_within)\n             apply (auto simp: dist_norm vector_derivative_works [symmetric] f)\n          done\n      qed\n      then show ?thesis\n        by (metis (no_types, lifting) continuous_on_eq [OF fcon] DiffE greaterThanLessThan_iff vector_derivative_at)\n    qed\n    moreover have \"continuous_on ({c<..<b} - T) (\\<lambda>x. vector_derivative (\\<lambda>x. if x \\<le> c then f x else g x) (at x))\"\n    proof -\n      have \"((\\<lambda>x. if x \\<le> c then f x else g x) has_vector_derivative vector_derivative g (at x))            (at x)\"\n        if \"c < x\" \"x < b\" \"x \\<notin> T\" for x\n      proof -\n        have g: \"g differentiable at x\"\n          by (metis C1_differentiable_on_eq DiffD1 DiffI atLeastAtMost_diff_ends greaterThanLessThan_iff st(2) that)\n        show ?thesis\n          using that\n          apply (rule_tac f=g and d=\"dist x c\" in has_vector_derivative_transform_within)\n             apply (auto simp: dist_norm vector_derivative_works [symmetric] g)\n          done\n      qed\n      then show ?thesis\n        by (metis (no_types, lifting) continuous_on_eq [OF gcon] DiffE greaterThanLessThan_iff vector_derivative_at)\n    qed\n    ultimately have \"continuous_on ({a<..<b} - insert c (S \\<union> T))\n        (\\<lambda>x. vector_derivative (\\<lambda>x. if x \\<le> c then f x else g x) (at x))\"\n      by (rule continuous_on_subset [OF continuous_on_open_Un], auto)\n  } note * = this\n  have \"continuous_on ({a<..<b} - insert c (S \\<union> T)) (\\<lambda>x. vector_derivative (\\<lambda>x. if x \\<le> c then f x else g x) (at x))\"\n    using st\n    by (auto simp: C1_differentiable_on_eq elim!: continuous_on_subset intro: *)\n  ultimately have \"\\<exists>S. finite S \\<and> ((\\<lambda>x. if x \\<le> c then f x else g x) C1_differentiable_on {a..b} - S)\"\n    apply (rule_tac x=\"{a,b,c} \\<union> S \\<union> T\" in exI)\n    using st  by (auto simp: C1_differentiable_on_eq elim!: continuous_on_subset)\n  with cab show ?thesis\n    by (simp add: piecewise_C1_differentiable_on_def)\nqed\n\nlemma piecewise_C1_differentiable_const [derivative_intros]:\n  \"(\\<lambda>x. c) piecewise_C1_differentiable_on S\"\n  by (simp add: C1_differentiable_imp_piecewise)\n\nlemma piecewise_C1_differentiable_scaleR [derivative_intros]:\n    \"\\<lbrakk>f piecewise_C1_differentiable_on S\\<rbrakk>\n     \\<Longrightarrow> (\\<lambda>x. c *\\<^sub>R f x) piecewise_C1_differentiable_on S\"\n  by (force simp add: piecewise_C1_differentiable_on_def continuous_on_scaleR)\n\nlemma piecewise_C1_differentiable_neg [derivative_intros]:\n    \"f piecewise_C1_differentiable_on S \\<Longrightarrow> (\\<lambda>x. -(f x)) piecewise_C1_differentiable_on S\"\n  unfolding piecewise_C1_differentiable_on_def\n  by (auto intro!: continuous_on_minus C1_differentiable_on_minus)\n\nlemma piecewise_C1_differentiable_add [derivative_intros]:\n  assumes \"f piecewise_C1_differentiable_on i\"\n          \"g piecewise_C1_differentiable_on i\"\n    shows \"(\\<lambda>x. f x + g x) piecewise_C1_differentiable_on i\"\nproof -\n  obtain S t where st: \"finite S\" \"finite t\"\n                       \"f C1_differentiable_on (i-S)\"\n                       \"g C1_differentiable_on (i-t)\"\n    using assms by (auto simp: piecewise_C1_differentiable_on_def)\n  then have \"finite (S \\<union> t) \\<and> (\\<lambda>x. f x + g x) C1_differentiable_on i - (S \\<union> t)\"\n    by (auto intro: C1_differentiable_on_add elim!: C1_differentiable_on_subset)\n  moreover have \"continuous_on i f\" \"continuous_on i g\"\n    using assms piecewise_C1_differentiable_on_def by auto\n  ultimately show ?thesis\n    by (auto simp: piecewise_C1_differentiable_on_def continuous_on_add)\nqed\n\nlemma piecewise_C1_differentiable_diff [derivative_intros]:\n    \"\\<lbrakk>f piecewise_C1_differentiable_on S;  g piecewise_C1_differentiable_on S\\<rbrakk>\n     \\<Longrightarrow> (\\<lambda>x. f x - g x) piecewise_C1_differentiable_on S\"\n  unfolding diff_conv_add_uminus\n  by (metis piecewise_C1_differentiable_add piecewise_C1_differentiable_neg)\n\nlemma piecewise_C1_differentiable_cmult_right [derivative_intros]:\n  fixes c::complex\n  shows \"f piecewise_C1_differentiable_on S\n     \\<Longrightarrow> (\\<lambda>x. f x * c) piecewise_C1_differentiable_on S\"\n  by (force simp: piecewise_C1_differentiable_on_def continuous_on_mult_right)\n\nlemma piecewise_C1_differentiable_cmult_left [derivative_intros]:\n  fixes c::complex\n  shows \"f piecewise_C1_differentiable_on S\n     \\<Longrightarrow> (\\<lambda>x. c * f x) piecewise_C1_differentiable_on S\"\n  using piecewise_C1_differentiable_cmult_right [of f S c] by (simp add: mult.commute)\n\nlemma piecewise_C1_differentiable_on_of_real [derivative_intros]: \n  \"of_real piecewise_C1_differentiable_on S\"\n  by (simp add: C1_differentiable_imp_piecewise C1_differentiable_on_of_real)\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/Analysis/Derivative.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8539127603871312, "lm_q2_score": 0.8479677506936879, "lm_q1q2_score": 0.7240904827141137}}
{"text": "theory Binomial_Coeffs\nimports Complex_Main \"HOL-Number_Theory.Fib\"\nbegin\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\ntext\\<open>sums of binomial coefficients.\\<close>\nlemma sum_choose_lower:\n    \"(\\<Sum>k\\<le>n. (r+k) choose k) = Suc (r+n) choose n\"\n  by (induction n) auto\n\nlemma sum_choose_upper:\n    \"(\\<Sum>k\\<le>n. k choose m) = Suc n choose Suc m\"\n  by (induction n) auto\n\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]\n    by (simp add: atMost_atLeast0 \\<open>m\\<le>n\\<close>)\n  also have \"\\<dots> = Suc (n-m+m) choose m\"\n    by (rule sum_choose_lower)\n  also have \"\\<dots> = Suc n choose m\" using assms\n    by simp\n  finally show ?thesis . \nqed\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 \"\\<dots> = 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\n        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 (smt (verit) fact_fact_dvd_fact div_mult_div_if_dvd mult.assoc mult.commute)\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\n\ntext \\<open>Concrete Mathematics, 5.18: \"this formula is easily verified by induction on m\"\\<close>\nlemma choose_row_sum_weighted:\n  \"(\\<Sum>k\\<le>m. (r choose k) * (r/2 - k)) = (Suc m)/2 * (r choose (Suc m))\"\nproof (induction m)\n  case 0 show ?case by simp\nnext\n  case (Suc m)\n  have \"(\\<Sum>k\\<le>Suc m. real (r choose k) * (r/2 - k)) \n      = ((r choose Suc m) * (r/2 - (Suc m))) + (Suc m) / 2 * (r choose Suc m)\"\n    by (simp add: Suc)\n  also have \"\\<dots> = (r choose Suc m) * (real r - (Suc m)) / 2\"\n    by (simp add: field_simps)\n  also have \"\\<dots> = Suc (Suc m) / 2 * (r choose Suc (Suc m))\"\n  proof (cases \"r \\<ge> Suc m\")\n    case True with binomial_absorb_comp[of r \"Suc m\"] show ?thesis\n      by (metis binomial_absorption mult.commute of_nat_diff of_nat_mult times_divide_eq_left)\n  qed (simp add: binomial_eq_0)\n  finally show ?case .\nqed\n\n\nlemma sum_drop_zero: \"(\\<Sum>k\\<le>Suc n. if 0<k then (f (k - 1)) else 0) = (\\<Sum>j\\<le>n. f j)\"\n  by (induction n) auto\n\nlemma sum_choose_drop_zero:\n  \"(\\<Sum>k\\<le>Suc n. if k = 0 then 0 else (Suc n - k) choose (k - 1)) =\n    (\\<Sum>j\\<le>n. (n-j) choose j)\"\n  by (rule trans [OF sum.cong sum_drop_zero]) auto\n\nlemma ne_diagonal_fib:\n   \"(\\<Sum>k\\<le>n. (n-k) choose k) = fib (Suc n)\"\nproof (induction n rule: fib.induct)\n  case 1 show ?case by simp\nnext\n  case 2 show ?case by simp\nnext\n  case (3 n)\n  have \"(\\<Sum>k\\<le>Suc n. Suc (Suc n) - k choose k) =\n        (\\<Sum>k\\<le>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> = (\\<Sum>k\\<le>Suc n. Suc n - k choose k) +\n                  (\\<Sum>k\\<le>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\\<le>Suc n. Suc n - k choose k) + (\\<Sum>j\\<le>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": "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/Binomial_Coeffs.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314828740729, "lm_q2_score": 0.817574478416099, "lm_q1q2_score": 0.7240696976796465}}
{"text": "(*  Title:      HOL/Fields.thy\n    Author:     Gertrud Bauer\n    Author:     Steven Obua\n    Author:     Tobias Nipkow\n    Author:     Lawrence C Paulson\n    Author:     Markus Wenzel\n    Author:     Jeremy Avigad\n*)\n\nsection \\<open>Fields\\<close>\n\ntheory Fields\nimports Nat\nbegin\n\nsubsection \\<open>Division rings\\<close>\n\ntext \\<open>\n  A division ring is like a field, but without the commutativity requirement.\n\\<close>\n\nclass inverse = divide +\n  fixes inverse :: \"'a \\<Rightarrow> 'a\"\nbegin\n  \nabbreviation inverse_divide :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a\"  (infixl \"'/\" 70)\nwhere\n  \"inverse_divide \\<equiv> divide\"\n\nend\n\ntext \\<open>Setup for linear arithmetic prover\\<close>\n\nML_file \"~~/src/Provers/Arith/fast_lin_arith.ML\"\nML_file \"Tools/lin_arith.ML\"\nsetup \\<open>Lin_Arith.global_setup\\<close>\ndeclaration \\<open>K Lin_Arith.setup\\<close>\n\nsimproc_setup fast_arith_nat (\"(m::nat) < n\" | \"(m::nat) \\<le> n\" | \"(m::nat) = n\") =\n  \\<open>K Lin_Arith.simproc\\<close>\n(* Because of this simproc, the arithmetic solver is really only\nuseful to detect inconsistencies among the premises for subgoals which are\n*not* themselves (in)equalities, because the latter activate\nfast_nat_arith_simproc anyway. However, it seems cheaper to activate the\nsolver all the time rather than add the additional check. *)\n\nlemmas [arith_split] = nat_diff_split split_min split_max\n\n\ntext\\<open>Lemmas \\<open>divide_simps\\<close> move division to the outside and eliminates them on (in)equalities.\\<close>\n\nnamed_theorems divide_simps \"rewrite rules to eliminate divisions\"\n\nclass division_ring = ring_1 + inverse +\n  assumes left_inverse [simp]:  \"a \\<noteq> 0 \\<Longrightarrow> inverse a * a = 1\"\n  assumes right_inverse [simp]: \"a \\<noteq> 0 \\<Longrightarrow> a * inverse a = 1\"\n  assumes divide_inverse: \"a / b = a * inverse b\"\n  assumes inverse_zero [simp]: \"inverse 0 = 0\"\nbegin\n\nsubclass ring_1_no_zero_divisors\nproof\n  fix a b :: 'a\n  assume a: \"a \\<noteq> 0\" and b: \"b \\<noteq> 0\"\n  show \"a * b \\<noteq> 0\"\n  proof\n    assume ab: \"a * b = 0\"\n    hence \"0 = inverse a * (a * b) * inverse b\" by simp\n    also have \"\\<dots> = (inverse a * a) * (b * inverse b)\"\n      by (simp only: mult.assoc)\n    also have \"\\<dots> = 1\" using a b by simp\n    finally show False by simp\n  qed\nqed\n\nlemma nonzero_imp_inverse_nonzero:\n  \"a \\<noteq> 0 \\<Longrightarrow> inverse a \\<noteq> 0\"\nproof\n  assume ianz: \"inverse a = 0\"\n  assume \"a \\<noteq> 0\"\n  hence \"1 = a * inverse a\" by simp\n  also have \"... = 0\" by (simp add: ianz)\n  finally have \"1 = 0\" .\n  thus False by (simp add: eq_commute)\nqed\n\nlemma inverse_zero_imp_zero:\n  \"inverse a = 0 \\<Longrightarrow> a = 0\"\napply (rule classical)\napply (drule nonzero_imp_inverse_nonzero)\napply auto\ndone\n\nlemma inverse_unique:\n  assumes ab: \"a * b = 1\"\n  shows \"inverse a = b\"\nproof -\n  have \"a \\<noteq> 0\" using ab by (cases \"a = 0\") simp_all\n  moreover have \"inverse a * (a * b) = inverse a\" by (simp add: ab)\n  ultimately show ?thesis by (simp add: mult.assoc [symmetric])\nqed\n\nlemma nonzero_inverse_minus_eq:\n  \"a \\<noteq> 0 \\<Longrightarrow> inverse (- a) = - inverse a\"\nby (rule inverse_unique) simp\n\nlemma nonzero_inverse_inverse_eq:\n  \"a \\<noteq> 0 \\<Longrightarrow> inverse (inverse a) = a\"\nby (rule inverse_unique) simp\n\nlemma nonzero_inverse_eq_imp_eq:\n  assumes \"inverse a = inverse b\" and \"a \\<noteq> 0\" and \"b \\<noteq> 0\"\n  shows \"a = b\"\nproof -\n  from \\<open>inverse a = inverse b\\<close>\n  have \"inverse (inverse a) = inverse (inverse b)\" by (rule arg_cong)\n  with \\<open>a \\<noteq> 0\\<close> and \\<open>b \\<noteq> 0\\<close> show \"a = b\"\n    by (simp add: nonzero_inverse_inverse_eq)\nqed\n\nlemma inverse_1 [simp]: \"inverse 1 = 1\"\nby (rule inverse_unique) simp\n\nlemma nonzero_inverse_mult_distrib:\n  assumes \"a \\<noteq> 0\" and \"b \\<noteq> 0\"\n  shows \"inverse (a * b) = inverse b * inverse a\"\nproof -\n  have \"a * (b * inverse b) * inverse a = 1\" using assms by simp\n  hence \"a * b * (inverse b * inverse a) = 1\" by (simp only: mult.assoc)\n  thus ?thesis by (rule inverse_unique)\nqed\n\nlemma division_ring_inverse_add:\n  \"a \\<noteq> 0 \\<Longrightarrow> b \\<noteq> 0 \\<Longrightarrow> inverse a + inverse b = inverse a * (a + b) * inverse b\"\nby (simp add: algebra_simps)\n\nlemma division_ring_inverse_diff:\n  \"a \\<noteq> 0 \\<Longrightarrow> b \\<noteq> 0 \\<Longrightarrow> inverse a - inverse b = inverse a * (b - a) * inverse b\"\nby (simp add: algebra_simps)\n\nlemma right_inverse_eq: \"b \\<noteq> 0 \\<Longrightarrow> a / b = 1 \\<longleftrightarrow> a = b\"\nproof\n  assume neq: \"b \\<noteq> 0\"\n  {\n    hence \"a = (a / b) * b\" by (simp add: divide_inverse mult.assoc)\n    also assume \"a / b = 1\"\n    finally show \"a = b\" by simp\n  next\n    assume \"a = b\"\n    with neq show \"a / b = 1\" by (simp add: divide_inverse)\n  }\nqed\n\nlemma nonzero_inverse_eq_divide: \"a \\<noteq> 0 \\<Longrightarrow> inverse a = 1 / a\"\nby (simp add: divide_inverse)\n\nlemma divide_self [simp]: \"a \\<noteq> 0 \\<Longrightarrow> a / a = 1\"\nby (simp add: divide_inverse)\n\nlemma inverse_eq_divide [field_simps, divide_simps]: \"inverse a = 1 / a\"\nby (simp add: divide_inverse)\n\nlemma add_divide_distrib: \"(a+b) / c = a/c + b/c\"\nby (simp add: divide_inverse algebra_simps)\n\nlemma times_divide_eq_right [simp]: \"a * (b / c) = (a * b) / c\"\n  by (simp add: divide_inverse mult.assoc)\n\nlemma minus_divide_left: \"- (a / b) = (-a) / b\"\n  by (simp add: divide_inverse)\n\nlemma nonzero_minus_divide_right: \"b \\<noteq> 0 ==> - (a / b) = a / (- b)\"\n  by (simp add: divide_inverse nonzero_inverse_minus_eq)\n\nlemma nonzero_minus_divide_divide: \"b \\<noteq> 0 ==> (-a) / (-b) = a / b\"\n  by (simp add: divide_inverse nonzero_inverse_minus_eq)\n\nlemma divide_minus_left [simp]: \"(-a) / b = - (a / b)\"\n  by (simp add: divide_inverse)\n\nlemma diff_divide_distrib: \"(a - b) / c = a / c - b / c\"\n  using add_divide_distrib [of a \"- b\" c] by simp\n\nlemma nonzero_eq_divide_eq [field_simps]: \"c \\<noteq> 0 \\<Longrightarrow> a = b / c \\<longleftrightarrow> a * c = b\"\nproof -\n  assume [simp]: \"c \\<noteq> 0\"\n  have \"a = b / c \\<longleftrightarrow> a * c = (b / c) * c\" by simp\n  also have \"... \\<longleftrightarrow> a * c = b\" by (simp add: divide_inverse mult.assoc)\n  finally show ?thesis .\nqed\n\nlemma nonzero_divide_eq_eq [field_simps]: \"c \\<noteq> 0 \\<Longrightarrow> b / c = a \\<longleftrightarrow> b = a * c\"\nproof -\n  assume [simp]: \"c \\<noteq> 0\"\n  have \"b / c = a \\<longleftrightarrow> (b / c) * c = a * c\" by simp\n  also have \"... \\<longleftrightarrow> b = a * c\" by (simp add: divide_inverse mult.assoc)\n  finally show ?thesis .\nqed\n\nlemma nonzero_neg_divide_eq_eq [field_simps]: \"b \\<noteq> 0 \\<Longrightarrow> - (a / b) = c \\<longleftrightarrow> - a = c * b\"\n  using nonzero_divide_eq_eq[of b \"-a\" c] by simp\n\nlemma nonzero_neg_divide_eq_eq2 [field_simps]: \"b \\<noteq> 0 \\<Longrightarrow> c = - (a / b) \\<longleftrightarrow> c * b = - a\"\n  using nonzero_neg_divide_eq_eq[of b a c] by auto\n\nlemma divide_eq_imp: \"c \\<noteq> 0 \\<Longrightarrow> b = a * c \\<Longrightarrow> b / c = a\"\n  by (simp add: divide_inverse mult.assoc)\n\nlemma eq_divide_imp: \"c \\<noteq> 0 \\<Longrightarrow> a * c = b \\<Longrightarrow> a = b / c\"\n  by (drule sym) (simp add: divide_inverse mult.assoc)\n\nlemma add_divide_eq_iff [field_simps]:\n  \"z \\<noteq> 0 \\<Longrightarrow> x + y / z = (x * z + y) / z\"\n  by (simp add: add_divide_distrib nonzero_eq_divide_eq)\n\nlemma divide_add_eq_iff [field_simps]:\n  \"z \\<noteq> 0 \\<Longrightarrow> x / z + y = (x + y * z) / z\"\n  by (simp add: add_divide_distrib nonzero_eq_divide_eq)\n\nlemma diff_divide_eq_iff [field_simps]:\n  \"z \\<noteq> 0 \\<Longrightarrow> x - y / z = (x * z - y) / z\"\n  by (simp add: diff_divide_distrib nonzero_eq_divide_eq eq_diff_eq)\n\nlemma minus_divide_add_eq_iff [field_simps]:\n  \"z \\<noteq> 0 \\<Longrightarrow> - (x / z) + y = (- x + y * z) / z\"\n  by (simp add: add_divide_distrib diff_divide_eq_iff)\n\nlemma divide_diff_eq_iff [field_simps]:\n  \"z \\<noteq> 0 \\<Longrightarrow> x / z - y = (x - y * z) / z\"\n  by (simp add: field_simps)\n\nlemma minus_divide_diff_eq_iff [field_simps]:\n  \"z \\<noteq> 0 \\<Longrightarrow> - (x / z) - y = (- x - y * z) / z\"\n  by (simp add: divide_diff_eq_iff[symmetric])\n\nlemma division_ring_divide_zero [simp]:\n  \"a / 0 = 0\"\n  by (simp add: divide_inverse)\n\nlemma divide_self_if [simp]:\n  \"a / a = (if a = 0 then 0 else 1)\"\n  by simp\n\nlemma inverse_nonzero_iff_nonzero [simp]:\n  \"inverse a = 0 \\<longleftrightarrow> a = 0\"\n  by rule (fact inverse_zero_imp_zero, simp)\n\nlemma inverse_minus_eq [simp]:\n  \"inverse (- a) = - inverse a\"\nproof cases\n  assume \"a=0\" thus ?thesis by simp\nnext\n  assume \"a\\<noteq>0\"\n  thus ?thesis by (simp add: nonzero_inverse_minus_eq)\nqed\n\nlemma inverse_inverse_eq [simp]:\n  \"inverse (inverse a) = a\"\nproof cases\n  assume \"a=0\" thus ?thesis by simp\nnext\n  assume \"a\\<noteq>0\"\n  thus ?thesis by (simp add: nonzero_inverse_inverse_eq)\nqed\n\nlemma inverse_eq_imp_eq:\n  \"inverse a = inverse b \\<Longrightarrow> a = b\"\n  by (drule arg_cong [where f=\"inverse\"], simp)\n\nlemma inverse_eq_iff_eq [simp]:\n  \"inverse a = inverse b \\<longleftrightarrow> a = b\"\n  by (force dest!: inverse_eq_imp_eq)\n\nlemma add_divide_eq_if_simps [divide_simps]:\n    \"a + b / z = (if z = 0 then a else (a * z + b) / z)\"\n    \"a / z + b = (if z = 0 then b else (a + b * z) / z)\"\n    \"- (a / z) + b = (if z = 0 then b else (-a + b * z) / z)\"\n    \"a - b / z = (if z = 0 then a else (a * z - b) / z)\"\n    \"a / z - b = (if z = 0 then -b else (a - b * z) / z)\"\n    \"- (a / z) - b = (if z = 0 then -b else (- a - b * z) / z)\"\n  by (simp_all add: add_divide_eq_iff divide_add_eq_iff diff_divide_eq_iff divide_diff_eq_iff\n      minus_divide_diff_eq_iff)\n\nlemma [divide_simps]:\n  shows divide_eq_eq: \"b / c = a \\<longleftrightarrow> (if c \\<noteq> 0 then b = a * c else a = 0)\"\n    and eq_divide_eq: \"a = b / c \\<longleftrightarrow> (if c \\<noteq> 0 then a * c = b else a = 0)\"\n    and minus_divide_eq_eq: \"- (b / c) = a \\<longleftrightarrow> (if c \\<noteq> 0 then - b = a * c else a = 0)\"\n    and eq_minus_divide_eq: \"a = - (b / c) \\<longleftrightarrow> (if c \\<noteq> 0 then a * c = - b else a = 0)\"\n  by (auto simp add:  field_simps)\n\nend\n\nsubsection \\<open>Fields\\<close>\n\nclass field = comm_ring_1 + inverse +\n  assumes field_inverse: \"a \\<noteq> 0 \\<Longrightarrow> inverse a * a = 1\"\n  assumes field_divide_inverse: \"a / b = a * inverse b\"\n  assumes field_inverse_zero: \"inverse 0 = 0\"\nbegin\n\nsubclass division_ring\nproof\n  fix a :: 'a\n  assume \"a \\<noteq> 0\"\n  thus \"inverse a * a = 1\" by (rule field_inverse)\n  thus \"a * inverse a = 1\" by (simp only: mult.commute)\nnext\n  fix a b :: 'a\n  show \"a / b = a * inverse b\" by (rule field_divide_inverse)\nnext\n  show \"inverse 0 = 0\"\n    by (fact field_inverse_zero) \nqed\n\nsubclass idom_divide\nproof\n  fix b a\n  assume \"b \\<noteq> 0\"\n  then show \"a * b / b = a\"\n    by (simp add: divide_inverse ac_simps)\nnext\n  fix a\n  show \"a / 0 = 0\"\n    by (simp add: divide_inverse)\nqed\n\ntext\\<open>There is no slick version using division by zero.\\<close>\nlemma inverse_add:\n  \"a \\<noteq> 0 \\<Longrightarrow> b \\<noteq> 0 \\<Longrightarrow> inverse a + inverse b = (a + b) * inverse a * inverse b\"\n  by (simp add: division_ring_inverse_add ac_simps)\n\nlemma nonzero_mult_divide_mult_cancel_left [simp]:\n  assumes [simp]: \"c \\<noteq> 0\"\n  shows \"(c * a) / (c * b) = a / b\"\nproof (cases \"b = 0\")\n  case True then show ?thesis by simp\nnext\n  case False\n  then have \"(c*a)/(c*b) = c * a * (inverse b * inverse c)\"\n    by (simp add: divide_inverse nonzero_inverse_mult_distrib)\n  also have \"... =  a * inverse b * (inverse c * c)\"\n    by (simp only: ac_simps)\n  also have \"... =  a * inverse b\" by simp\n    finally show ?thesis by (simp add: divide_inverse)\nqed\n\nlemma nonzero_mult_divide_mult_cancel_right [simp]:\n  \"c \\<noteq> 0 \\<Longrightarrow> (a * c) / (b * c) = a / b\"\n  using nonzero_mult_divide_mult_cancel_left [of c a b] by (simp add: ac_simps)\n\nlemma times_divide_eq_left [simp]: \"(b / c) * a = (b * a) / c\"\n  by (simp add: divide_inverse ac_simps)\n\nlemma divide_inverse_commute: \"a / b = inverse b * a\"\n  by (simp add: divide_inverse mult.commute)\n\nlemma add_frac_eq:\n  assumes \"y \\<noteq> 0\" and \"z \\<noteq> 0\"\n  shows \"x / y + w / z = (x * z + w * y) / (y * z)\"\nproof -\n  have \"x / y + w / z = (x * z) / (y * z) + (y * w) / (y * z)\"\n    using assms by simp\n  also have \"\\<dots> = (x * z + y * w) / (y * z)\"\n    by (simp only: add_divide_distrib)\n  finally show ?thesis\n    by (simp only: mult.commute)\nqed\n\ntext\\<open>Special Cancellation Simprules for Division\\<close>\n\nlemma nonzero_divide_mult_cancel_right [simp]:\n  \"b \\<noteq> 0 \\<Longrightarrow> b / (a * b) = 1 / a\"\n  using nonzero_mult_divide_mult_cancel_right [of b 1 a] by simp\n\nlemma nonzero_divide_mult_cancel_left [simp]:\n  \"a \\<noteq> 0 \\<Longrightarrow> a / (a * b) = 1 / b\"\n  using nonzero_mult_divide_mult_cancel_left [of a 1 b] by simp\n\nlemma nonzero_mult_divide_mult_cancel_left2 [simp]:\n  \"c \\<noteq> 0 \\<Longrightarrow> (c * a) / (b * c) = a / b\"\n  using nonzero_mult_divide_mult_cancel_left [of c a b] by (simp add: ac_simps)\n\nlemma nonzero_mult_divide_mult_cancel_right2 [simp]:\n  \"c \\<noteq> 0 \\<Longrightarrow> (a * c) / (c * b) = a / b\"\n  using nonzero_mult_divide_mult_cancel_right [of b c a] by (simp add: ac_simps)\n\nlemma diff_frac_eq:\n  \"y \\<noteq> 0 \\<Longrightarrow> z \\<noteq> 0 \\<Longrightarrow> x / y - w / z = (x * z - w * y) / (y * z)\"\n  by (simp add: field_simps)\n\nlemma frac_eq_eq:\n  \"y \\<noteq> 0 \\<Longrightarrow> z \\<noteq> 0 \\<Longrightarrow> (x / y = w / z) = (x * z = w * y)\"\n  by (simp add: field_simps)\n\nlemma divide_minus1 [simp]: \"x / - 1 = - x\"\n  using nonzero_minus_divide_right [of \"1\" x] by simp\n\ntext\\<open>This version builds in division by zero while also re-orienting\n      the right-hand side.\\<close>\nlemma inverse_mult_distrib [simp]:\n  \"inverse (a * b) = inverse a * inverse b\"\nproof cases\n  assume \"a \\<noteq> 0 & b \\<noteq> 0\"\n  thus ?thesis by (simp add: nonzero_inverse_mult_distrib ac_simps)\nnext\n  assume \"~ (a \\<noteq> 0 & b \\<noteq> 0)\"\n  thus ?thesis by force\nqed\n\nlemma inverse_divide [simp]:\n  \"inverse (a / b) = b / a\"\n  by (simp add: divide_inverse mult.commute)\n\n\ntext \\<open>Calculations with fractions\\<close>\n\ntext\\<open>There is a whole bunch of simp-rules just for class \\<open>field\\<close> but none for class \\<open>field\\<close> and \\<open>nonzero_divides\\<close>\nbecause the latter are covered by a simproc.\\<close>\n\nlemma mult_divide_mult_cancel_left:\n  \"c \\<noteq> 0 \\<Longrightarrow> (c * a) / (c * b) = a / b\"\napply (cases \"b = 0\")\napply simp_all\ndone\n\nlemma mult_divide_mult_cancel_right:\n  \"c \\<noteq> 0 \\<Longrightarrow> (a * c) / (b * c) = a / b\"\napply (cases \"b = 0\")\napply simp_all\ndone\n\nlemma divide_divide_eq_right [simp]:\n  \"a / (b / c) = (a * c) / b\"\n  by (simp add: divide_inverse ac_simps)\n\nlemma divide_divide_eq_left [simp]:\n  \"(a / b) / c = a / (b * c)\"\n  by (simp add: divide_inverse mult.assoc)\n\nlemma divide_divide_times_eq:\n  \"(x / y) / (z / w) = (x * w) / (y * z)\"\n  by simp\n\ntext \\<open>Special Cancellation Simprules for Division\\<close>\n\nlemma mult_divide_mult_cancel_left_if [simp]:\n  shows \"(c * a) / (c * b) = (if c = 0 then 0 else a / b)\"\n  by simp\n\n\ntext \\<open>Division and Unary Minus\\<close>\n\nlemma minus_divide_right:\n  \"- (a / b) = a / - b\"\n  by (simp add: divide_inverse)\n\nlemma divide_minus_right [simp]:\n  \"a / - b = - (a / b)\"\n  by (simp add: divide_inverse)\n\nlemma minus_divide_divide:\n  \"(- a) / (- b) = a / b\"\napply (cases \"b=0\", simp)\napply (simp add: nonzero_minus_divide_divide)\ndone\n\nlemma inverse_eq_1_iff [simp]:\n  \"inverse x = 1 \\<longleftrightarrow> x = 1\"\n  by (insert inverse_eq_iff_eq [of x 1], simp)\n\nlemma divide_eq_0_iff [simp]:\n  \"a / b = 0 \\<longleftrightarrow> a = 0 \\<or> b = 0\"\n  by (simp add: divide_inverse)\n\nlemma divide_cancel_right [simp]:\n  \"a / c = b / c \\<longleftrightarrow> c = 0 \\<or> a = b\"\n  apply (cases \"c=0\", simp)\n  apply (simp add: divide_inverse)\n  done\n\nlemma divide_cancel_left [simp]:\n  \"c / a = c / b \\<longleftrightarrow> c = 0 \\<or> a = b\"\n  apply (cases \"c=0\", simp)\n  apply (simp add: divide_inverse)\n  done\n\nlemma divide_eq_1_iff [simp]:\n  \"a / b = 1 \\<longleftrightarrow> b \\<noteq> 0 \\<and> a = b\"\n  apply (cases \"b=0\", simp)\n  apply (simp add: right_inverse_eq)\n  done\n\nlemma one_eq_divide_iff [simp]:\n  \"1 = a / b \\<longleftrightarrow> b \\<noteq> 0 \\<and> a = b\"\n  by (simp add: eq_commute [of 1])\n\nlemma times_divide_times_eq:\n  \"(x / y) * (z / w) = (x * z) / (y * w)\"\n  by simp\n\nlemma add_frac_num:\n  \"y \\<noteq> 0 \\<Longrightarrow> x / y + z = (x + z * y) / y\"\n  by (simp add: add_divide_distrib)\n\nlemma add_num_frac:\n  \"y \\<noteq> 0 \\<Longrightarrow> z + x / y = (x + z * y) / y\"\n  by (simp add: add_divide_distrib add.commute)\n\nend\n\nclass field_char_0 = field + ring_char_0\n\n\nsubsection \\<open>Ordered fields\\<close>\n\nclass field_abs_sgn = field + idom_abs_sgn\nbegin\n\nlemma sgn_inverse [simp]:\n  \"sgn (inverse a) = inverse (sgn a)\"\nproof (cases \"a = 0\")\n  case True then show ?thesis by simp\nnext\n  case False\n  then have \"a * inverse a = 1\"\n    by simp\n  then have \"sgn (a * inverse a) = sgn 1\"\n    by simp\n  then have \"sgn a * sgn (inverse a) = 1\"\n    by (simp add: sgn_mult)\n  then have \"inverse (sgn a) * (sgn a * sgn (inverse a)) = inverse (sgn a) * 1\"\n    by simp\n  then have \"(inverse (sgn a) * sgn a) * sgn (inverse a) = inverse (sgn a)\"\n    by (simp add: ac_simps)\n  with False show ?thesis\n    by (simp add: sgn_eq_0_iff)\nqed\n\nlemma abs_inverse [simp]:\n  \"\\<bar>inverse a\\<bar> = inverse \\<bar>a\\<bar>\"\nproof -\n  from sgn_mult_abs [of \"inverse a\"] sgn_mult_abs [of a]\n  have \"inverse (sgn a) * \\<bar>inverse a\\<bar> = inverse (sgn a * \\<bar>a\\<bar>)\"\n    by simp\n  then show ?thesis by (auto simp add: sgn_eq_0_iff)\nqed\n    \nlemma sgn_divide [simp]:\n  \"sgn (a / b) = sgn a / sgn b\"\n  unfolding divide_inverse sgn_mult by simp\n\nlemma abs_divide [simp]:\n  \"\\<bar>a / b\\<bar> = \\<bar>a\\<bar> / \\<bar>b\\<bar>\"\n  unfolding divide_inverse abs_mult by simp\n  \nend\n\nclass linordered_field = field + linordered_idom\nbegin\n\nlemma positive_imp_inverse_positive:\n  assumes a_gt_0: \"0 < a\"\n  shows \"0 < inverse a\"\nproof -\n  have \"0 < a * inverse a\"\n    by (simp add: a_gt_0 [THEN less_imp_not_eq2])\n  thus \"0 < inverse a\"\n    by (simp add: a_gt_0 [THEN less_not_sym] zero_less_mult_iff)\nqed\n\nlemma negative_imp_inverse_negative:\n  \"a < 0 \\<Longrightarrow> inverse a < 0\"\n  by (insert positive_imp_inverse_positive [of \"-a\"],\n    simp add: nonzero_inverse_minus_eq less_imp_not_eq)\n\nlemma inverse_le_imp_le:\n  assumes invle: \"inverse a \\<le> inverse b\" and apos: \"0 < a\"\n  shows \"b \\<le> a\"\nproof (rule classical)\n  assume \"~ b \\<le> a\"\n  hence \"a < b\"  by (simp add: linorder_not_le)\n  hence bpos: \"0 < b\"  by (blast intro: apos less_trans)\n  hence \"a * inverse a \\<le> a * inverse b\"\n    by (simp add: apos invle less_imp_le mult_left_mono)\n  hence \"(a * inverse a) * b \\<le> (a * inverse b) * b\"\n    by (simp add: bpos less_imp_le mult_right_mono)\n  thus \"b \\<le> a\"  by (simp add: mult.assoc apos bpos less_imp_not_eq2)\nqed\n\nlemma inverse_positive_imp_positive:\n  assumes inv_gt_0: \"0 < inverse a\" and nz: \"a \\<noteq> 0\"\n  shows \"0 < a\"\nproof -\n  have \"0 < inverse (inverse a)\"\n    using inv_gt_0 by (rule positive_imp_inverse_positive)\n  thus \"0 < a\"\n    using nz by (simp add: nonzero_inverse_inverse_eq)\nqed\n\nlemma inverse_negative_imp_negative:\n  assumes inv_less_0: \"inverse a < 0\" and nz: \"a \\<noteq> 0\"\n  shows \"a < 0\"\nproof -\n  have \"inverse (inverse a) < 0\"\n    using inv_less_0 by (rule negative_imp_inverse_negative)\n  thus \"a < 0\" using nz by (simp add: nonzero_inverse_inverse_eq)\nqed\n\nlemma linordered_field_no_lb:\n  \"\\<forall>x. \\<exists>y. y < x\"\nproof\n  fix x::'a\n  have m1: \"- (1::'a) < 0\" by simp\n  from add_strict_right_mono[OF m1, where c=x]\n  have \"(- 1) + x < x\" by simp\n  thus \"\\<exists>y. y < x\" by blast\nqed\n\nlemma linordered_field_no_ub:\n  \"\\<forall> x. \\<exists>y. y > x\"\nproof\n  fix x::'a\n  have m1: \" (1::'a) > 0\" by simp\n  from add_strict_right_mono[OF m1, where c=x]\n  have \"1 + x > x\" by simp\n  thus \"\\<exists>y. y > x\" by blast\nqed\n\nlemma less_imp_inverse_less:\n  assumes less: \"a < b\" and apos:  \"0 < a\"\n  shows \"inverse b < inverse a\"\nproof (rule ccontr)\n  assume \"~ inverse b < inverse a\"\n  hence \"inverse a \\<le> inverse b\" by simp\n  hence \"~ (a < b)\"\n    by (simp add: not_less inverse_le_imp_le [OF _ apos])\n  thus False by (rule notE [OF _ less])\nqed\n\nlemma inverse_less_imp_less:\n  \"inverse a < inverse b \\<Longrightarrow> 0 < a \\<Longrightarrow> b < a\"\napply (simp add: less_le [of \"inverse a\"] less_le [of \"b\"])\napply (force dest!: inverse_le_imp_le nonzero_inverse_eq_imp_eq)\ndone\n\ntext\\<open>Both premises are essential. Consider -1 and 1.\\<close>\nlemma inverse_less_iff_less [simp]:\n  \"0 < a \\<Longrightarrow> 0 < b \\<Longrightarrow> inverse a < inverse b \\<longleftrightarrow> b < a\"\n  by (blast intro: less_imp_inverse_less dest: inverse_less_imp_less)\n\nlemma le_imp_inverse_le:\n  \"a \\<le> b \\<Longrightarrow> 0 < a \\<Longrightarrow> inverse b \\<le> inverse a\"\n  by (force simp add: le_less less_imp_inverse_less)\n\nlemma inverse_le_iff_le [simp]:\n  \"0 < a \\<Longrightarrow> 0 < b \\<Longrightarrow> inverse a \\<le> inverse b \\<longleftrightarrow> b \\<le> a\"\n  by (blast intro: le_imp_inverse_le dest: inverse_le_imp_le)\n\n\ntext\\<open>These results refer to both operands being negative.  The opposite-sign\ncase is trivial, since inverse preserves signs.\\<close>\nlemma inverse_le_imp_le_neg:\n  \"inverse a \\<le> inverse b \\<Longrightarrow> b < 0 \\<Longrightarrow> b \\<le> a\"\napply (rule classical)\napply (subgoal_tac \"a < 0\")\n prefer 2 apply force\napply (insert inverse_le_imp_le [of \"-b\" \"-a\"])\napply (simp add: nonzero_inverse_minus_eq)\ndone\n\nlemma less_imp_inverse_less_neg:\n   \"a < b \\<Longrightarrow> b < 0 \\<Longrightarrow> inverse b < inverse a\"\napply (subgoal_tac \"a < 0\")\n prefer 2 apply (blast intro: less_trans)\napply (insert less_imp_inverse_less [of \"-b\" \"-a\"])\napply (simp add: nonzero_inverse_minus_eq)\ndone\n\nlemma inverse_less_imp_less_neg:\n   \"inverse a < inverse b \\<Longrightarrow> b < 0 \\<Longrightarrow> b < a\"\napply (rule classical)\napply (subgoal_tac \"a < 0\")\n prefer 2\n apply force\napply (insert inverse_less_imp_less [of \"-b\" \"-a\"])\napply (simp add: nonzero_inverse_minus_eq)\ndone\n\nlemma inverse_less_iff_less_neg [simp]:\n  \"a < 0 \\<Longrightarrow> b < 0 \\<Longrightarrow> inverse a < inverse b \\<longleftrightarrow> b < a\"\napply (insert inverse_less_iff_less [of \"-b\" \"-a\"])\napply (simp del: inverse_less_iff_less\n            add: nonzero_inverse_minus_eq)\ndone\n\nlemma le_imp_inverse_le_neg:\n  \"a \\<le> b \\<Longrightarrow> b < 0 ==> inverse b \\<le> inverse a\"\n  by (force simp add: le_less less_imp_inverse_less_neg)\n\nlemma inverse_le_iff_le_neg [simp]:\n  \"a < 0 \\<Longrightarrow> b < 0 \\<Longrightarrow> inverse a \\<le> inverse b \\<longleftrightarrow> b \\<le> a\"\n  by (blast intro: le_imp_inverse_le_neg dest: inverse_le_imp_le_neg)\n\nlemma one_less_inverse:\n  \"0 < a \\<Longrightarrow> a < 1 \\<Longrightarrow> 1 < inverse a\"\n  using less_imp_inverse_less [of a 1, unfolded inverse_1] .\n\nlemma one_le_inverse:\n  \"0 < a \\<Longrightarrow> a \\<le> 1 \\<Longrightarrow> 1 \\<le> inverse a\"\n  using le_imp_inverse_le [of a 1, unfolded inverse_1] .\n\nlemma pos_le_divide_eq [field_simps]:\n  assumes \"0 < c\"\n  shows \"a \\<le> b / c \\<longleftrightarrow> a * c \\<le> b\"\nproof -\n  from assms have \"a \\<le> b / c \\<longleftrightarrow> a * c \\<le> (b / c) * c\"\n    using mult_le_cancel_right [of a c \"b * inverse c\"] by (auto simp add: field_simps)\n  also have \"... \\<longleftrightarrow> a * c \\<le> b\"\n    by (simp add: less_imp_not_eq2 [OF assms] divide_inverse mult.assoc)\n  finally show ?thesis .\nqed\n\nlemma pos_less_divide_eq [field_simps]:\n  assumes \"0 < c\"\n  shows \"a < b / c \\<longleftrightarrow> a * c < b\"\nproof -\n  from assms have \"a < b / c \\<longleftrightarrow> a * c < (b / c) * c\"\n    using mult_less_cancel_right [of a c \"b / c\"] by auto\n  also have \"... = (a*c < b)\"\n    by (simp add: less_imp_not_eq2 [OF assms] divide_inverse mult.assoc)\n  finally show ?thesis .\nqed\n\nlemma neg_less_divide_eq [field_simps]:\n  assumes \"c < 0\"\n  shows \"a < b / c \\<longleftrightarrow> b < a * c\"\nproof -\n  from assms have \"a < b / c \\<longleftrightarrow> (b / c) * c < a * c\"\n    using mult_less_cancel_right [of \"b / c\" c a] by auto\n  also have \"... \\<longleftrightarrow> b < a * c\"\n    by (simp add: less_imp_not_eq [OF assms] divide_inverse mult.assoc)\n  finally show ?thesis .\nqed\n\nlemma neg_le_divide_eq [field_simps]:\n  assumes \"c < 0\"\n  shows \"a \\<le> b / c \\<longleftrightarrow> b \\<le> a * c\"\nproof -\n  from assms have \"a \\<le> b / c \\<longleftrightarrow> (b / c) * c \\<le> a * c\"\n    using mult_le_cancel_right [of \"b * inverse c\" c a] by (auto simp add: field_simps)\n  also have \"... \\<longleftrightarrow> b \\<le> a * c\"\n    by (simp add: less_imp_not_eq [OF assms] divide_inverse mult.assoc)\n  finally show ?thesis .\nqed\n\nlemma pos_divide_le_eq [field_simps]:\n  assumes \"0 < c\"\n  shows \"b / c \\<le> a \\<longleftrightarrow> b \\<le> a * c\"\nproof -\n  from assms have \"b / c \\<le> a \\<longleftrightarrow> (b / c) * c \\<le> a * c\"\n    using mult_le_cancel_right [of \"b / c\" c a] by auto\n  also have \"... \\<longleftrightarrow> b \\<le> a * c\"\n    by (simp add: less_imp_not_eq2 [OF assms] divide_inverse mult.assoc)\n  finally show ?thesis .\nqed\n\nlemma pos_divide_less_eq [field_simps]:\n  assumes \"0 < c\"\n  shows \"b / c < a \\<longleftrightarrow> b < a * c\"\nproof -\n  from assms have \"b / c < a \\<longleftrightarrow> (b / c) * c < a * c\"\n    using mult_less_cancel_right [of \"b / c\" c a] by auto\n  also have \"... \\<longleftrightarrow> b < a * c\"\n    by (simp add: less_imp_not_eq2 [OF assms] divide_inverse mult.assoc)\n  finally show ?thesis .\nqed\n\nlemma neg_divide_le_eq [field_simps]:\n  assumes \"c < 0\"\n  shows \"b / c \\<le> a \\<longleftrightarrow> a * c \\<le> b\"\nproof -\n  from assms have \"b / c \\<le> a \\<longleftrightarrow> a * c \\<le> (b / c) * c\"\n    using mult_le_cancel_right [of a c \"b / c\"] by auto\n  also have \"... \\<longleftrightarrow> a * c \\<le> b\"\n    by (simp add: less_imp_not_eq [OF assms] divide_inverse mult.assoc)\n  finally show ?thesis .\nqed\n\nlemma neg_divide_less_eq [field_simps]:\n  assumes \"c < 0\"\n  shows \"b / c < a \\<longleftrightarrow> a * c < b\"\nproof -\n  from assms have \"b / c < a \\<longleftrightarrow> a * c < b / c * c\"\n    using mult_less_cancel_right [of a c \"b / c\"] by auto\n  also have \"... \\<longleftrightarrow> a * c < b\"\n    by (simp add: less_imp_not_eq [OF assms] divide_inverse mult.assoc)\n  finally show ?thesis .\nqed\n\ntext\\<open>The following \\<open>field_simps\\<close> rules are necessary, as minus is always moved atop of\ndivision but we want to get rid of division.\\<close>\n\nlemma pos_le_minus_divide_eq [field_simps]: \"0 < c \\<Longrightarrow> a \\<le> - (b / c) \\<longleftrightarrow> a * c \\<le> - b\"\n  unfolding minus_divide_left by (rule pos_le_divide_eq)\n\nlemma neg_le_minus_divide_eq [field_simps]: \"c < 0 \\<Longrightarrow> a \\<le> - (b / c) \\<longleftrightarrow> - b \\<le> a * c\"\n  unfolding minus_divide_left by (rule neg_le_divide_eq)\n\nlemma pos_less_minus_divide_eq [field_simps]: \"0 < c \\<Longrightarrow> a < - (b / c) \\<longleftrightarrow> a * c < - b\"\n  unfolding minus_divide_left by (rule pos_less_divide_eq)\n\nlemma neg_less_minus_divide_eq [field_simps]: \"c < 0 \\<Longrightarrow> a < - (b / c) \\<longleftrightarrow> - b < a * c\"\n  unfolding minus_divide_left by (rule neg_less_divide_eq)\n\nlemma pos_minus_divide_less_eq [field_simps]: \"0 < c \\<Longrightarrow> - (b / c) < a \\<longleftrightarrow> - b < a * c\"\n  unfolding minus_divide_left by (rule pos_divide_less_eq)\n\nlemma neg_minus_divide_less_eq [field_simps]: \"c < 0 \\<Longrightarrow> - (b / c) < a \\<longleftrightarrow> a * c < - b\"\n  unfolding minus_divide_left by (rule neg_divide_less_eq)\n\nlemma pos_minus_divide_le_eq [field_simps]: \"0 < c \\<Longrightarrow> - (b / c) \\<le> a \\<longleftrightarrow> - b \\<le> a * c\"\n  unfolding minus_divide_left by (rule pos_divide_le_eq)\n\nlemma neg_minus_divide_le_eq [field_simps]: \"c < 0 \\<Longrightarrow> - (b / c) \\<le> a \\<longleftrightarrow> a * c \\<le> - b\"\n  unfolding minus_divide_left by (rule neg_divide_le_eq)\n\nlemma frac_less_eq:\n  \"y \\<noteq> 0 \\<Longrightarrow> z \\<noteq> 0 \\<Longrightarrow> x / y < w / z \\<longleftrightarrow> (x * z - w * y) / (y * z) < 0\"\n  by (subst less_iff_diff_less_0) (simp add: diff_frac_eq )\n\nlemma frac_le_eq:\n  \"y \\<noteq> 0 \\<Longrightarrow> z \\<noteq> 0 \\<Longrightarrow> x / y \\<le> w / z \\<longleftrightarrow> (x * z - w * y) / (y * z) \\<le> 0\"\n  by (subst le_iff_diff_le_0) (simp add: diff_frac_eq )\n\ntext\\<open>Lemmas \\<open>sign_simps\\<close> is a first attempt to automate proofs\nof positivity/negativity needed for \\<open>field_simps\\<close>. Have not added \\<open>sign_simps\\<close> to \\<open>field_simps\\<close> because the former can lead to case\nexplosions.\\<close>\n\nlemmas sign_simps = algebra_simps zero_less_mult_iff mult_less_0_iff\n\nlemmas (in -) sign_simps = algebra_simps zero_less_mult_iff mult_less_0_iff\n\n(* Only works once linear arithmetic is installed:\ntext{*An example:*}\nlemma fixes a b c d e f :: \"'a::linordered_field\"\nshows \"\\<lbrakk>a>b; c<d; e<f; 0 < u \\<rbrakk> \\<Longrightarrow>\n ((a-b)*(c-d)*(e-f))/((c-d)*(e-f)*(a-b)) <\n ((e-f)*(a-b)*(c-d))/((e-f)*(a-b)*(c-d)) + u\"\napply(subgoal_tac \"(c-d)*(e-f)*(a-b) > 0\")\n prefer 2 apply(simp add:sign_simps)\napply(subgoal_tac \"(c-d)*(e-f)*(a-b)*u > 0\")\n prefer 2 apply(simp add:sign_simps)\napply(simp add:field_simps)\ndone\n*)\n\nlemma divide_pos_pos[simp]:\n  \"0 < x ==> 0 < y ==> 0 < x / y\"\nby(simp add:field_simps)\n\nlemma divide_nonneg_pos:\n  \"0 <= x ==> 0 < y ==> 0 <= x / y\"\nby(simp add:field_simps)\n\nlemma divide_neg_pos:\n  \"x < 0 ==> 0 < y ==> x / y < 0\"\nby(simp add:field_simps)\n\nlemma divide_nonpos_pos:\n  \"x <= 0 ==> 0 < y ==> x / y <= 0\"\nby(simp add:field_simps)\n\nlemma divide_pos_neg:\n  \"0 < x ==> y < 0 ==> x / y < 0\"\nby(simp add:field_simps)\n\nlemma divide_nonneg_neg:\n  \"0 <= x ==> y < 0 ==> x / y <= 0\"\nby(simp add:field_simps)\n\nlemma divide_neg_neg:\n  \"x < 0 ==> y < 0 ==> 0 < x / y\"\nby(simp add:field_simps)\n\nlemma divide_nonpos_neg:\n  \"x <= 0 ==> y < 0 ==> 0 <= x / y\"\nby(simp add:field_simps)\n\nlemma divide_strict_right_mono:\n     \"[|a < b; 0 < c|] ==> a / c < b / c\"\nby (simp add: less_imp_not_eq2 divide_inverse mult_strict_right_mono\n              positive_imp_inverse_positive)\n\n\nlemma divide_strict_right_mono_neg:\n     \"[|b < a; c < 0|] ==> a / c < b / c\"\napply (drule divide_strict_right_mono [of _ _ \"-c\"], simp)\napply (simp add: less_imp_not_eq nonzero_minus_divide_right [symmetric])\ndone\n\ntext\\<open>The last premise ensures that @{term a} and @{term b}\n      have the same sign\\<close>\nlemma divide_strict_left_mono:\n  \"[|b < a; 0 < c; 0 < a*b|] ==> c / a < c / b\"\n  by (auto simp: field_simps zero_less_mult_iff mult_strict_right_mono)\n\nlemma divide_left_mono:\n  \"[|b \\<le> a; 0 \\<le> c; 0 < a*b|] ==> c / a \\<le> c / b\"\n  by (auto simp: field_simps zero_less_mult_iff mult_right_mono)\n\nlemma divide_strict_left_mono_neg:\n  \"[|a < b; c < 0; 0 < a*b|] ==> c / a < c / b\"\n  by (auto simp: field_simps zero_less_mult_iff mult_strict_right_mono_neg)\n\nlemma mult_imp_div_pos_le: \"0 < y ==> x <= z * y ==>\n    x / y <= z\"\nby (subst pos_divide_le_eq, assumption+)\n\nlemma mult_imp_le_div_pos: \"0 < y ==> z * y <= x ==>\n    z <= x / y\"\nby(simp add:field_simps)\n\nlemma mult_imp_div_pos_less: \"0 < y ==> x < z * y ==>\n    x / y < z\"\nby(simp add:field_simps)\n\nlemma mult_imp_less_div_pos: \"0 < y ==> z * y < x ==>\n    z < x / y\"\nby(simp add:field_simps)\n\nlemma frac_le: \"0 <= x ==>\n    x <= y ==> 0 < w ==> w <= z  ==> x / z <= y / w\"\n  apply (rule mult_imp_div_pos_le)\n  apply simp\n  apply (subst times_divide_eq_left)\n  apply (rule mult_imp_le_div_pos, assumption)\n  apply (rule mult_mono)\n  apply simp_all\ndone\n\nlemma frac_less: \"0 <= x ==>\n    x < y ==> 0 < w ==> w <= z  ==> x / z < y / w\"\n  apply (rule mult_imp_div_pos_less)\n  apply simp\n  apply (subst times_divide_eq_left)\n  apply (rule mult_imp_less_div_pos, assumption)\n  apply (erule mult_less_le_imp_less)\n  apply simp_all\ndone\n\nlemma frac_less2: \"0 < x ==>\n    x <= y ==> 0 < w ==> w < z  ==> x / z < y / w\"\n  apply (rule mult_imp_div_pos_less)\n  apply simp_all\n  apply (rule mult_imp_less_div_pos, assumption)\n  apply (erule mult_le_less_imp_less)\n  apply simp_all\ndone\n\nlemma less_half_sum: \"a < b ==> a < (a+b) / (1+1)\"\nby (simp add: field_simps zero_less_two)\n\nlemma gt_half_sum: \"a < b ==> (a+b)/(1+1) < b\"\nby (simp add: field_simps zero_less_two)\n\nsubclass unbounded_dense_linorder\nproof\n  fix x y :: 'a\n  from less_add_one show \"\\<exists>y. x < y\" ..\n  from less_add_one have \"x + (- 1) < (x + 1) + (- 1)\" by (rule add_strict_right_mono)\n  then have \"x - 1 < x + 1 - 1\" by simp\n  then have \"x - 1 < x\" by (simp add: algebra_simps)\n  then show \"\\<exists>y. y < x\" ..\n  show \"x < y \\<Longrightarrow> \\<exists>z>x. z < y\" by (blast intro!: less_half_sum gt_half_sum)\nqed\n\nsubclass field_abs_sgn ..\n\nlemma inverse_sgn [simp]:\n  \"inverse (sgn a) = sgn a\"\n  by (cases a 0 rule: linorder_cases) simp_all\n\nlemma divide_sgn [simp]:\n  \"a / sgn b = a * sgn b\"\n  by (cases b 0 rule: linorder_cases) simp_all\n\nlemma nonzero_abs_inverse:\n  \"a \\<noteq> 0 ==> \\<bar>inverse a\\<bar> = inverse \\<bar>a\\<bar>\"\n  by (rule abs_inverse)\n\nlemma nonzero_abs_divide:\n  \"b \\<noteq> 0 ==> \\<bar>a / b\\<bar> = \\<bar>a\\<bar> / \\<bar>b\\<bar>\"\n  by (rule abs_divide)\n\nlemma field_le_epsilon:\n  assumes e: \"\\<And>e. 0 < e \\<Longrightarrow> x \\<le> y + e\"\n  shows \"x \\<le> y\"\nproof (rule dense_le)\n  fix t assume \"t < x\"\n  hence \"0 < x - t\" by (simp add: less_diff_eq)\n  from e [OF this] have \"x + 0 \\<le> x + (y - t)\" by (simp add: algebra_simps)\n  then have \"0 \\<le> y - t\" by (simp only: add_le_cancel_left)\n  then show \"t \\<le> y\" by (simp add: algebra_simps)\nqed\n\nlemma inverse_positive_iff_positive [simp]:\n  \"(0 < inverse a) = (0 < a)\"\napply (cases \"a = 0\", simp)\napply (blast intro: inverse_positive_imp_positive positive_imp_inverse_positive)\ndone\n\nlemma inverse_negative_iff_negative [simp]:\n  \"(inverse a < 0) = (a < 0)\"\napply (cases \"a = 0\", simp)\napply (blast intro: inverse_negative_imp_negative negative_imp_inverse_negative)\ndone\n\nlemma inverse_nonnegative_iff_nonnegative [simp]:\n  \"0 \\<le> inverse a \\<longleftrightarrow> 0 \\<le> a\"\n  by (simp add: not_less [symmetric])\n\nlemma inverse_nonpositive_iff_nonpositive [simp]:\n  \"inverse a \\<le> 0 \\<longleftrightarrow> a \\<le> 0\"\n  by (simp add: not_less [symmetric])\n\nlemma one_less_inverse_iff: \"1 < inverse x \\<longleftrightarrow> 0 < x \\<and> x < 1\"\n  using less_trans[of 1 x 0 for x]\n  by (cases x 0 rule: linorder_cases) (auto simp add: field_simps)\n\nlemma one_le_inverse_iff: \"1 \\<le> inverse x \\<longleftrightarrow> 0 < x \\<and> x \\<le> 1\"\nproof (cases \"x = 1\")\n  case True then show ?thesis by simp\nnext\n  case False then have \"inverse x \\<noteq> 1\" by simp\n  then have \"1 \\<noteq> inverse x\" by blast\n  then have \"1 \\<le> inverse x \\<longleftrightarrow> 1 < inverse x\" by (simp add: le_less)\n  with False show ?thesis by (auto simp add: one_less_inverse_iff)\nqed\n\nlemma inverse_less_1_iff: \"inverse x < 1 \\<longleftrightarrow> x \\<le> 0 \\<or> 1 < x\"\n  by (simp add: not_le [symmetric] one_le_inverse_iff)\n\nlemma inverse_le_1_iff: \"inverse x \\<le> 1 \\<longleftrightarrow> x \\<le> 0 \\<or> 1 \\<le> x\"\n  by (simp add: not_less [symmetric] one_less_inverse_iff)\n\nlemma [divide_simps]:\n  shows le_divide_eq: \"a \\<le> b / c \\<longleftrightarrow> (if 0 < c then a * c \\<le> b else if c < 0 then b \\<le> a * c else a \\<le> 0)\"\n    and divide_le_eq: \"b / c \\<le> a \\<longleftrightarrow> (if 0 < c then b \\<le> a * c else if c < 0 then a * c \\<le> b else 0 \\<le> a)\"\n    and less_divide_eq: \"a < b / c \\<longleftrightarrow> (if 0 < c then a * c < b else if c < 0 then b < a * c else a < 0)\"\n    and divide_less_eq: \"b / c < a \\<longleftrightarrow> (if 0 < c then b < a * c else if c < 0 then a * c < b else 0 < a)\"\n    and le_minus_divide_eq: \"a \\<le> - (b / c) \\<longleftrightarrow> (if 0 < c then a * c \\<le> - b else if c < 0 then - b \\<le> a * c else a \\<le> 0)\"\n    and minus_divide_le_eq: \"- (b / c) \\<le> a \\<longleftrightarrow> (if 0 < c then - b \\<le> a * c else if c < 0 then a * c \\<le> - b else 0 \\<le> a)\"\n    and less_minus_divide_eq: \"a < - (b / c) \\<longleftrightarrow> (if 0 < c then a * c < - b else if c < 0 then - b < a * c else  a < 0)\"\n    and minus_divide_less_eq: \"- (b / c) < a \\<longleftrightarrow> (if 0 < c then - b < a * c else if c < 0 then a * c < - b else 0 < a)\"\n  by (auto simp: field_simps not_less dest: antisym)\n\ntext \\<open>Division and Signs\\<close>\n\nlemma\n  shows zero_less_divide_iff: \"0 < a / b \\<longleftrightarrow> 0 < a \\<and> 0 < b \\<or> a < 0 \\<and> b < 0\"\n    and divide_less_0_iff: \"a / b < 0 \\<longleftrightarrow> 0 < a \\<and> b < 0 \\<or> a < 0 \\<and> 0 < b\"\n    and zero_le_divide_iff: \"0 \\<le> a / b \\<longleftrightarrow> 0 \\<le> a \\<and> 0 \\<le> b \\<or> a \\<le> 0 \\<and> b \\<le> 0\"\n    and divide_le_0_iff: \"a / b \\<le> 0 \\<longleftrightarrow> 0 \\<le> a \\<and> b \\<le> 0 \\<or> a \\<le> 0 \\<and> 0 \\<le> b\"\n  by (auto simp add: divide_simps)\n\ntext \\<open>Division and the Number One\\<close>\n\ntext\\<open>Simplify expressions equated with 1\\<close>\n\nlemma zero_eq_1_divide_iff [simp]: \"0 = 1 / a \\<longleftrightarrow> a = 0\"\n  by (cases \"a = 0\") (auto simp: field_simps)\n\nlemma one_divide_eq_0_iff [simp]: \"1 / a = 0 \\<longleftrightarrow> a = 0\"\n  using zero_eq_1_divide_iff[of a] by simp\n\ntext\\<open>Simplify expressions such as \\<open>0 < 1/x\\<close> to \\<open>0 < x\\<close>\\<close>\n\nlemma zero_le_divide_1_iff [simp]:\n  \"0 \\<le> 1 / a \\<longleftrightarrow> 0 \\<le> a\"\n  by (simp add: zero_le_divide_iff)\n\nlemma zero_less_divide_1_iff [simp]:\n  \"0 < 1 / a \\<longleftrightarrow> 0 < a\"\n  by (simp add: zero_less_divide_iff)\n\nlemma divide_le_0_1_iff [simp]:\n  \"1 / a \\<le> 0 \\<longleftrightarrow> a \\<le> 0\"\n  by (simp add: divide_le_0_iff)\n\nlemma divide_less_0_1_iff [simp]:\n  \"1 / a < 0 \\<longleftrightarrow> a < 0\"\n  by (simp add: divide_less_0_iff)\n\nlemma divide_right_mono:\n     \"[|a \\<le> b; 0 \\<le> c|] ==> a/c \\<le> b/c\"\nby (force simp add: divide_strict_right_mono le_less)\n\nlemma divide_right_mono_neg: \"a <= b\n    ==> c <= 0 ==> b / c <= a / c\"\napply (drule divide_right_mono [of _ _ \"- c\"])\napply auto\ndone\n\nlemma divide_left_mono_neg: \"a <= b\n    ==> c <= 0 ==> 0 < a * b ==> c / a <= c / b\"\n  apply (drule divide_left_mono [of _ _ \"- c\"])\n  apply (auto simp add: mult.commute)\ndone\n\nlemma inverse_le_iff: \"inverse a \\<le> inverse b \\<longleftrightarrow> (0 < a * b \\<longrightarrow> b \\<le> a) \\<and> (a * b \\<le> 0 \\<longrightarrow> a \\<le> b)\"\n  by (cases a 0 b 0 rule: linorder_cases[case_product linorder_cases])\n     (auto simp add: field_simps zero_less_mult_iff mult_le_0_iff)\n\nlemma inverse_less_iff: \"inverse a < inverse b \\<longleftrightarrow> (0 < a * b \\<longrightarrow> b < a) \\<and> (a * b \\<le> 0 \\<longrightarrow> a < b)\"\n  by (subst less_le) (auto simp: inverse_le_iff)\n\nlemma divide_le_cancel: \"a / c \\<le> b / c \\<longleftrightarrow> (0 < c \\<longrightarrow> a \\<le> b) \\<and> (c < 0 \\<longrightarrow> b \\<le> a)\"\n  by (simp add: divide_inverse mult_le_cancel_right)\n\nlemma divide_less_cancel: \"a / c < b / c \\<longleftrightarrow> (0 < c \\<longrightarrow> a < b) \\<and> (c < 0 \\<longrightarrow> b < a) \\<and> c \\<noteq> 0\"\n  by (auto simp add: divide_inverse mult_less_cancel_right)\n\ntext\\<open>Simplify quotients that are compared with the value 1.\\<close>\n\nlemma le_divide_eq_1:\n  \"(1 \\<le> b / a) = ((0 < a & a \\<le> b) | (a < 0 & b \\<le> a))\"\nby (auto simp add: le_divide_eq)\n\nlemma divide_le_eq_1:\n  \"(b / a \\<le> 1) = ((0 < a & b \\<le> a) | (a < 0 & a \\<le> b) | a=0)\"\nby (auto simp add: divide_le_eq)\n\nlemma less_divide_eq_1:\n  \"(1 < b / a) = ((0 < a & a < b) | (a < 0 & b < a))\"\nby (auto simp add: less_divide_eq)\n\nlemma divide_less_eq_1:\n  \"(b / a < 1) = ((0 < a & b < a) | (a < 0 & a < b) | a=0)\"\nby (auto simp add: divide_less_eq)\n\nlemma divide_nonneg_nonneg [simp]:\n  \"0 \\<le> x \\<Longrightarrow> 0 \\<le> y \\<Longrightarrow> 0 \\<le> x / y\"\n  by (auto simp add: divide_simps)\n\nlemma divide_nonpos_nonpos:\n  \"x \\<le> 0 \\<Longrightarrow> y \\<le> 0 \\<Longrightarrow> 0 \\<le> x / y\"\n  by (auto simp add: divide_simps)\n\nlemma divide_nonneg_nonpos:\n  \"0 \\<le> x \\<Longrightarrow> y \\<le> 0 \\<Longrightarrow> x / y \\<le> 0\"\n  by (auto simp add: divide_simps)\n\nlemma divide_nonpos_nonneg:\n  \"x \\<le> 0 \\<Longrightarrow> 0 \\<le> y \\<Longrightarrow> x / y \\<le> 0\"\n  by (auto simp add: divide_simps)\n\ntext \\<open>Conditional Simplification Rules: No Case Splits\\<close>\n\nlemma le_divide_eq_1_pos [simp]:\n  \"0 < a \\<Longrightarrow> (1 \\<le> b/a) = (a \\<le> b)\"\nby (auto simp add: le_divide_eq)\n\nlemma le_divide_eq_1_neg [simp]:\n  \"a < 0 \\<Longrightarrow> (1 \\<le> b/a) = (b \\<le> a)\"\nby (auto simp add: le_divide_eq)\n\nlemma divide_le_eq_1_pos [simp]:\n  \"0 < a \\<Longrightarrow> (b/a \\<le> 1) = (b \\<le> a)\"\nby (auto simp add: divide_le_eq)\n\nlemma divide_le_eq_1_neg [simp]:\n  \"a < 0 \\<Longrightarrow> (b/a \\<le> 1) = (a \\<le> b)\"\nby (auto simp add: divide_le_eq)\n\nlemma less_divide_eq_1_pos [simp]:\n  \"0 < a \\<Longrightarrow> (1 < b/a) = (a < b)\"\nby (auto simp add: less_divide_eq)\n\nlemma less_divide_eq_1_neg [simp]:\n  \"a < 0 \\<Longrightarrow> (1 < b/a) = (b < a)\"\nby (auto simp add: less_divide_eq)\n\nlemma divide_less_eq_1_pos [simp]:\n  \"0 < a \\<Longrightarrow> (b/a < 1) = (b < a)\"\nby (auto simp add: divide_less_eq)\n\nlemma divide_less_eq_1_neg [simp]:\n  \"a < 0 \\<Longrightarrow> b/a < 1 \\<longleftrightarrow> a < b\"\nby (auto simp add: divide_less_eq)\n\nlemma eq_divide_eq_1 [simp]:\n  \"(1 = b/a) = ((a \\<noteq> 0 & a = b))\"\nby (auto simp add: eq_divide_eq)\n\nlemma divide_eq_eq_1 [simp]:\n  \"(b/a = 1) = ((a \\<noteq> 0 & a = b))\"\nby (auto simp add: divide_eq_eq)\n\nlemma abs_div_pos: \"0 < y ==>\n    \\<bar>x\\<bar> / y = \\<bar>x / y\\<bar>\"\n  apply (subst abs_divide)\n  apply (simp add: order_less_imp_le)\ndone\n\nlemma zero_le_divide_abs_iff [simp]: \"(0 \\<le> a / \\<bar>b\\<bar>) = (0 \\<le> a | b = 0)\"\nby (auto simp: zero_le_divide_iff)\n\nlemma divide_le_0_abs_iff [simp]: \"(a / \\<bar>b\\<bar> \\<le> 0) = (a \\<le> 0 | b = 0)\"\nby (auto simp: divide_le_0_iff)\n\nlemma field_le_mult_one_interval:\n  assumes *: \"\\<And>z. \\<lbrakk> 0 < z ; z < 1 \\<rbrakk> \\<Longrightarrow> z * x \\<le> y\"\n  shows \"x \\<le> y\"\nproof (cases \"0 < x\")\n  assume \"0 < x\"\n  thus ?thesis\n    using dense_le_bounded[of 0 1 \"y/x\"] *\n    unfolding le_divide_eq if_P[OF \\<open>0 < x\\<close>] by simp\nnext\n  assume \"\\<not>0 < x\" hence \"x \\<le> 0\" by simp\n  obtain s::'a where s: \"0 < s\" \"s < 1\" using dense[of 0 \"1::'a\"] by auto\n  hence \"x \\<le> s * x\" using mult_le_cancel_right[of 1 x s] \\<open>x \\<le> 0\\<close> by auto\n  also note *[OF s]\n  finally show ?thesis .\nqed\n\ntext\\<open>For creating values between @{term u} and @{term v}.\\<close>\nlemma scaling_mono:\n  assumes \"u \\<le> v\" \"0 \\<le> r\" \"r \\<le> s\"\n    shows \"u + r * (v - u) / s \\<le> v\"\nproof -\n  have \"r/s \\<le> 1\" using assms\n    using divide_le_eq_1 by fastforce\n  then have \"(r/s) * (v - u) \\<le> 1 * (v - u)\"\n    apply (rule mult_right_mono)\n    using assms by simp\n  then show ?thesis\n    by (simp add: field_simps)\nqed\n\nend\n\ntext \\<open>Min/max Simplification Rules\\<close>\n\nlemma min_mult_distrib_left:\n  fixes x::\"'a::linordered_idom\" \n  shows \"p * min x y = (if 0 \\<le> p then min (p*x) (p*y) else max (p*x) (p*y))\"\nby (auto simp add: min_def max_def mult_le_cancel_left)\n\nlemma min_mult_distrib_right:\n  fixes x::\"'a::linordered_idom\" \n  shows \"min x y * p = (if 0 \\<le> p then min (x*p) (y*p) else max (x*p) (y*p))\"\nby (auto simp add: min_def max_def mult_le_cancel_right)\n\nlemma min_divide_distrib_right:\n  fixes x::\"'a::linordered_field\" \n  shows \"min x y / p = (if 0 \\<le> p then min (x/p) (y/p) else max (x/p) (y/p))\"\nby (simp add: min_mult_distrib_right divide_inverse)\n\nlemma max_mult_distrib_left:\n  fixes x::\"'a::linordered_idom\" \n  shows \"p * max x y = (if 0 \\<le> p then max (p*x) (p*y) else min (p*x) (p*y))\"\nby (auto simp add: min_def max_def mult_le_cancel_left)\n\nlemma max_mult_distrib_right:\n  fixes x::\"'a::linordered_idom\" \n  shows \"max x y * p = (if 0 \\<le> p then max (x*p) (y*p) else min (x*p) (y*p))\"\nby (auto simp add: min_def max_def mult_le_cancel_right)\n\nlemma max_divide_distrib_right:\n  fixes x::\"'a::linordered_field\" \n  shows \"max x y / p = (if 0 \\<le> p then max (x/p) (y/p) else min (x/p) (y/p))\"\nby (simp add: max_mult_distrib_right divide_inverse)\n\nhide_fact (open) field_inverse field_divide_inverse field_inverse_zero\n\ncode_identifier\n  code_module Fields \\<rightharpoonup> (SML) Arith and (OCaml) Arith and (Haskell) Arith\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/Fields.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8333246035907933, "lm_q2_score": 0.868826784729373, "lm_q1q2_score": 0.7240147359736683}}
{"text": "section \\<open> Finite bijections \\<close>\n\ntheory Finite_Bijection\n  imports \"HOL-Library.Countable_Set\"\nbegin\n\ntext \\<open> This theory shows that there exists a bijection between any finite type and the set\n        of natural numbers bounded by the cardinality of the finite type. \\<close>\n\ndefinition is_to_nat_ind :: \"'a \\<Rightarrow> nat \\<Rightarrow> bool\" where\n\"is_to_nat_ind x i \\<longleftrightarrow> (finite (UNIV :: 'a set) \\<and>\n                        i < card (UNIV :: 'a set) \\<and>\n                        sorted_list_of_set (to_nat_on (UNIV :: 'a set) ` (UNIV :: 'a set)) ! i = to_nat_on (UNIV :: 'a set) x)\"\n\ntext \\<open> The function @{const to_nat} from the countable class makes no guarantees about\n        which natural numbers will be picked for each element. Nevertheless it guaranatees\n        a unique natural for each element. We use this to map each of these elements to\n        a number in the range 0..|A| by creating a sorted list of the corresponding naturals\n        from @{const to_nat} and then assigning each element its index in this list. Thus\n        we end up with a more predictable set of numbers. \\<close>\n\ndefinition to_nat_fin :: \"'a \\<Rightarrow> nat\" where\n\"to_nat_fin x = (THE i. is_to_nat_ind x i)\"\n\nlemma sorted_list_of_set_index_ex:\n  assumes \"finite A\"\n  shows \"(\\<exists> i<card A. sorted_list_of_set A ! i = x) \\<longleftrightarrow> x \\<in> A\"\n  by (metis assms distinct_card in_set_conv_nth sorted_list_of_set)\n\nlemma nat_ind_exists:\n  assumes \"finite (UNIV :: 'a set)\"\n  shows \"\\<exists> i. is_to_nat_ind (x :: 'a) i\"\nproof -\n  have \"to_nat_on (UNIV :: 'a set) x \\<in> range (to_nat_on (UNIV :: 'a set)) \\<longleftrightarrow>\n          (\\<exists> i<card (UNIV :: 'a set). sorted_list_of_set (range (to_nat_on (UNIV :: 'a set))) ! i = to_nat_on (UNIV :: 'a set) x)\"\n    by (meson assms card_image_le dual_order.strict_trans1 finite_imageI range_eqI sorted_list_of_set_index_ex)\n\n  then obtain a\n    where a_card: \"a < card (UNIV :: 'a set)\"\n    and a_ind: \"sorted_list_of_set (range (to_nat_on (UNIV :: 'a set))) ! a = to_nat_on (UNIV :: 'a set) x\"\n    by auto\n\n  thus ?thesis\n    by (auto simp add: is_to_nat_ind_def assms)\nqed\n\nlemma length_sorted_list_of_set [simp]: \"finite A \\<Longrightarrow> length (sorted_list_of_set A) = card A\"\n  by (metis distinct_card distinct_sorted_list_of_set set_sorted_list_of_set)\n\nlemma to_nat_on_inj_on: \"countable A \\<Longrightarrow> inj_on (to_nat_on A) A\"\n  by (auto simp add: inj_on_def)\n\nlemma finite_card_to_nat_on [simp]:\n  \"finite (UNIV :: 'a set) \\<Longrightarrow> card (range (to_nat_on (UNIV :: 'a set))) = card (UNIV :: 'a set)\"\n  by (simp add: card_image countable_finite to_nat_on_inj_on)\n\nlemma nat_ind_unique:\n  assumes \"is_to_nat_ind (x :: 'a) i\"\n  shows \"to_nat_fin x = i\"\nproof -\n  let ?A = \"range (to_nat_on (UNIV :: 'a set))\"\n  from assms have finA: \"finite ?A\"\n    by (simp add: is_to_nat_ind_def)\n  hence \"distinct (sorted_list_of_set ?A)\"\n    using sorted_list_of_set by blast\n  with assms have \"\\<And> i j. \\<lbrakk> i < card(UNIV :: 'a set); j < card (UNIV :: 'a set)\n                 ; sorted_list_of_set ?A ! i = sorted_list_of_set ?A ! j \\<rbrakk> \\<Longrightarrow> i = j\"\n    using finite_card_to_nat_on is_to_nat_ind_def by (fastforce simp add: distinct_conv_nth finA)\n  with assms show ?thesis\n    apply (simp add: the_equality to_nat_fin_def)\n    apply (rule the_equality)\n    apply (auto simp add: is_to_nat_ind_def)\n  done\nqed\n\nlemma nat_ind_val_exists:\n  assumes \"finite (UNIV :: 'a set)\" \"i < card (UNIV :: 'a set)\"\n  shows \"\\<exists>x :: 'a. is_to_nat_ind x i\"\n  using assms\n  apply (auto simp add: is_to_nat_ind_def)\n  apply (metis finite_card_to_nat_on finite_imageI imageE sorted_list_of_set_index_ex)\ndone\n\nlemma to_nat_fin_ex:\n  fixes x :: \"'a\"\n  assumes \"finite (UNIV :: 'a set)\" \"i < card (UNIV :: 'a set)\"\n  shows \"\\<exists>x :: 'a. i = to_nat_fin x\"\nproof -\n  obtain y :: 'a where \"is_to_nat_ind y i\"\n    using assms nat_ind_val_exists by blast\n  thus ?thesis\n    using nat_ind_unique by fastforce\nqed\n\nlemma to_nat_fin_bounded:\n  fixes x :: \"'a\"\n  assumes \"finite (UNIV :: 'a set)\"\n  shows \"to_nat_fin x < card (UNIV :: 'a set)\"\nproof -\n  obtain i where \"is_to_nat_ind x i\"\n    by (meson assms nat_ind_exists)\n  thus ?thesis\n    using is_to_nat_ind_def nat_ind_unique by fastforce\nqed\n\nlemma range_to_nat_fin:\n  \"finite (UNIV :: 'a set) \\<Longrightarrow> range (to_nat_fin :: 'a \\<Rightarrow> nat) = {n. n < card(UNIV :: 'a set)}\"\n  using to_nat_fin_ex by (auto simp add: to_nat_fin_bounded)\n\nlemma is_to_nat_ind:\n  \"\\<lbrakk> finite (UNIV :: 'a set); is_to_nat_ind (x :: 'a) i; is_to_nat_ind x j \\<rbrakk> \\<Longrightarrow> i = j\"\n  apply (auto simp add: is_to_nat_ind_def)\n  apply (metis distinct_card finite_card_to_nat_on finite_imageI nth_eq_iff_index_eq sorted_list_of_set)\ndone\n\nlemma is_to_nat_ind_elem:\n  \"\\<lbrakk> is_to_nat_ind x i; is_to_nat_ind y i \\<rbrakk> \\<Longrightarrow> x = y\"\n  by (auto simp add: is_to_nat_ind_def countable_finite)\n\nlemma to_nat_fin_inj:\n  assumes \"finite (UNIV :: 'a set)\"\n  shows \"inj (to_nat_fin :: 'a \\<Rightarrow> nat)\"\nproof (rule injI)\n  fix x y :: 'a\n  assume \"to_nat_fin x = to_nat_fin y\"\n  moreover obtain i where \"is_to_nat_ind x i\"\n    by (meson assms nat_ind_exists)\n  moreover obtain j where \"is_to_nat_ind y j\"\n    by (meson assms nat_ind_exists)\n ultimately show \"x = y\"\n    by (metis is_to_nat_ind_elem nat_ind_unique)\nqed\n\nlemma to_nat_fin_bij:\n  \"finite (UNIV :: 'a set) \\<Longrightarrow> bij_betw to_nat_fin (UNIV :: 'a set) {n. n < card (UNIV :: 'a set)}\"\n  by (auto simp add: bij_betw_def to_nat_fin_inj to_nat_fin_bounded range_to_nat_fin)\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/Finite_Bijection.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267830311354, "lm_q2_score": 0.8333246015211009, "lm_q1q2_score": 0.7240147327602808}}
{"text": "(*  \n    Author:      Ren\u00e9 Thiemann \n                 Akihisa Yamada\n    License:     BSD\n*)\nsection \\<open>Improved Code Equations\\<close>\n\ntext \\<open>This theory contains improved code equations for certain algorithms.\\<close>\n\ntheory Improved_Code_Equations\nimports \n  \"HOL-Computational_Algebra.Polynomial\"\n  \"HOL-Library.Code_Target_Nat\"\nbegin\n\nsubsection \\<open>@{const divmod_integer}.\\<close>\n\ntext \\<open>We improve @{thm divmod_integer_code} by deleting @{const sgn}-expressions.\\<close>\n\ntext \\<open>We guard the application of divmod-abs' with the condition @{term \"x \\<ge> 0 \\<and> y \\<ge> 0\"}, \n  so that application can be ensured on non-negative values. Hence, one can drop \"abs\" in \n   target language setup.\\<close>\n\ndefinition divmod_abs' where \n  \"x \\<ge> 0 \\<Longrightarrow> y \\<ge> 0 \\<Longrightarrow> divmod_abs' x y = Code_Numeral.divmod_abs x y\" \n\n(* led to an another 10 % improvement on factorization example *)\n\nlemma divmod_integer_code''[code]: \"divmod_integer k l =\n  (if k = 0 then (0, 0)\n    else if l > 0 then\n            (if k > 0 then divmod_abs' k l\n             else case divmod_abs' (- k) l of (r, s) \\<Rightarrow>\n                  if s = 0 then (- r, 0) else (- r - 1, l - s))\n    else if l = 0 then (0, k)\n    else apsnd uminus\n            (if k < 0 then divmod_abs' (-k) (-l)\n             else case divmod_abs' k (-l) of (r, s) \\<Rightarrow>\n                  if s = 0 then (- r, 0) else (- r - 1, - l - s)))\"\n   unfolding divmod_integer_code\n   by (cases \"l = 0\"; cases \"l < 0\"; cases \"l > 0\"; auto split: prod.splits simp: divmod_abs'_def divmod_abs_def)\n\ncode_printing \\<comment> \\<open>FIXME illusion of partiality\\<close>\n  constant divmod_abs' \\<rightharpoonup>\n    (SML) \"IntInf.divMod/ ( _,/ _ )\"\n    and (Eval) \"Integer.div'_mod/ ( _ )/ ( _ )\"\n    and (OCaml) \"Z.div'_rem\"\n    and (Haskell) \"divMod/ ( _ )/ ( _ )\"\n    and (Scala) \"!((k: BigInt) => (l: BigInt) =>/ if (l == 0)/ (BigInt(0), k) else/ (k '/% l))\"\n\nsubsection \\<open>@{const Divides.divmod_nat}.\\<close>\ntext \\<open>We implement @{const Divides.divmod_nat} via @{const divmod_integer}\n  instead of invoking both division and modulo separately, \n  and we further simplify the case-analysis which is\n  performed in @{thm divmod_integer_code''}.\\<close>\n\nlemma divmod_nat_code'[code]: \"Divides.divmod_nat m n = (\n  let k = integer_of_nat m; l = integer_of_nat n\n  in map_prod nat_of_integer nat_of_integer\n  (if k = 0 then (0, 0)\n    else if l = 0 then (0,k) else\n            divmod_abs' k l))\"\n  using divmod_nat_code [of m n]\n  by (simp add: divmod_abs'_def integer_of_nat_eq_of_nat Let_def)\n\n\nsubsection \\<open>@{const binomial}\\<close>\n\nlemma binomial_code[code]:\n  \"n choose k = (if k \\<le> n then fact n div (fact k * fact (n - k)) else 0)\"\n  using binomial_eq_0[of n k] binomial_altdef_nat[of k n] by 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/Polynomial_Interpolation/Improved_Code_Equations.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8933094117351309, "lm_q2_score": 0.8104789086703225, "lm_q1q2_score": 0.7240084371280167}}
{"text": "section \"Bitvector based Sets of Naturals\"\ntheory Impl_Bit_Set\nimports \n  \"../../Iterator/Iterator\" \n  \"../Intf/Intf_Set\" \n  \"../../../Native_Word/Code_Target_Integer_Bit\"\nbegin\n  text \\<open>\n    Based on the Native-Word library, using bit-operations on arbitrary\n    precision integers. Fast for sets of small numbers, \n    direct and fast implementations of equal, union, inter, diff.\n\n    Note: On Poly/ML 5.5.1, bit-operations on arbitrary precision integers are \n      rather inefficient. Use MLton instead, here they are efficiently implemented.\n\\<close>\n\n  type_synonym bitset = integer\n\n  definition bs_\\<alpha> :: \"bitset \\<Rightarrow> nat set\" where \"bs_\\<alpha> s \\<equiv> { n . bit s n}\"\n\n\n  context\n    includes integer.lifting bit_operations_syntax\n  begin\n\n  definition bs_empty :: \"unit \\<Rightarrow> bitset\" where \"bs_empty \\<equiv> \\<lambda>_. 0\"\n\n\n  lemma bs_empty_correct: \"bs_\\<alpha> (bs_empty ()) = {}\"\n    unfolding bs_\\<alpha>_def bs_empty_def \n    apply transfer\n    by auto\n\n  definition bs_isEmpty :: \"bitset \\<Rightarrow> bool\" where \"bs_isEmpty s \\<equiv> s=0\"\n\n  lemma bs_isEmpty_correct: \"bs_isEmpty s \\<longleftrightarrow> bs_\\<alpha> s = {}\"\n    unfolding bs_isEmpty_def bs_\\<alpha>_def \n    by transfer (auto simp: bit_eq_iff) \n    \n  term set_bit\n  definition bs_insert :: \"nat \\<Rightarrow> bitset \\<Rightarrow> bitset\" where\n    \"bs_insert i s \\<equiv> set_bit s i True\"\n\n  lemma bs_insert_correct: \"bs_\\<alpha> (bs_insert i s) = insert i (bs_\\<alpha> s)\"\n    unfolding bs_\\<alpha>_def bs_insert_def\n    by transfer (auto simp add: bit_simps)\n\n  definition bs_delete :: \"nat \\<Rightarrow> bitset \\<Rightarrow> bitset\" where\n    \"bs_delete i s \\<equiv> set_bit s i False\"\n\n  lemma bs_delete_correct: \"bs_\\<alpha> (bs_delete i s) = (bs_\\<alpha> s) - {i}\"\n    unfolding bs_\\<alpha>_def bs_delete_def\n    by transfer (auto simp add: bit_simps split: if_splits)\n  \n  definition bs_mem :: \"nat \\<Rightarrow> bitset \\<Rightarrow> bool\" where\n    \"bs_mem i s \\<equiv> bit s i\"\n\n  lemma bs_mem_correct: \"bs_mem i s \\<longleftrightarrow> i\\<in>bs_\\<alpha> s\"\n    unfolding bs_mem_def bs_\\<alpha>_def by transfer auto\n\n\n  definition bs_eq :: \"bitset \\<Rightarrow> bitset \\<Rightarrow> bool\" where \n    \"bs_eq s1 s2 \\<equiv> (s1=s2)\"\n\n  lemma bs_eq_correct: \"bs_eq s1 s2 \\<longleftrightarrow> bs_\\<alpha> s1 = bs_\\<alpha> s2\"\n    unfolding bs_eq_def bs_\\<alpha>_def\n    including integer.lifting\n    by transfer (simp add: bit_eq_iff set_eq_iff)\n\n  definition bs_subset_eq :: \"bitset \\<Rightarrow> bitset \\<Rightarrow> bool\" where\n    \"bs_subset_eq s1 s2 \\<equiv> s1 AND NOT s2 = 0\"\n  \n  lemma bs_subset_eq_correct: \"bs_subset_eq s1 s2 \\<longleftrightarrow> bs_\\<alpha> s1 \\<subseteq> bs_\\<alpha> s2\"\n    unfolding bs_\\<alpha>_def bs_subset_eq_def\n    by transfer (simp add: bit_eq_iff, auto simp add: bit_simps)\n\n  definition bs_disjoint :: \"bitset \\<Rightarrow> bitset \\<Rightarrow> bool\" where\n    \"bs_disjoint s1 s2 \\<equiv> s1 AND s2 = 0\"\n  \n  lemma bs_disjoint_correct: \"bs_disjoint s1 s2 \\<longleftrightarrow> bs_\\<alpha> s1 \\<inter> bs_\\<alpha> s2 = {}\"\n    unfolding bs_\\<alpha>_def bs_disjoint_def\n    by transfer (simp add: bit_eq_iff, auto simp add: bit_simps)\n\n  definition bs_union :: \"bitset \\<Rightarrow> bitset \\<Rightarrow> bitset\" where\n    \"bs_union s1 s2 = s1 OR s2\"\n\n  lemma bs_union_correct: \"bs_\\<alpha> (bs_union s1 s2) = bs_\\<alpha> s1 \\<union> bs_\\<alpha> s2\"\n    unfolding bs_\\<alpha>_def bs_union_def\n    by transfer (simp add: bit_eq_iff, auto simp add: bit_simps)\n\n  definition bs_inter :: \"bitset \\<Rightarrow> bitset \\<Rightarrow> bitset\" where\n    \"bs_inter s1 s2 = s1 AND s2\"\n\n  lemma bs_inter_correct: \"bs_\\<alpha> (bs_inter s1 s2) = bs_\\<alpha> s1 \\<inter> bs_\\<alpha> s2\"\n    unfolding bs_\\<alpha>_def bs_inter_def\n    by transfer (simp add: bit_eq_iff, auto simp add: bit_simps)\n\n  definition bs_diff :: \"bitset \\<Rightarrow> bitset \\<Rightarrow> bitset\" where\n    \"bs_diff s1 s2 = s1 AND NOT s2\"\n\n  lemma bs_diff_correct: \"bs_\\<alpha> (bs_diff s1 s2) = bs_\\<alpha> s1 - bs_\\<alpha> s2\"\n    unfolding bs_\\<alpha>_def bs_diff_def\n    by transfer (simp add: bit_eq_iff, auto simp add: bit_simps)\n\n  definition bs_UNIV :: \"unit \\<Rightarrow> bitset\" where \"bs_UNIV \\<equiv> \\<lambda>_. -1\"\n\n  lemma bs_UNIV_correct: \"bs_\\<alpha> (bs_UNIV ()) = UNIV\"\n    unfolding bs_\\<alpha>_def bs_UNIV_def\n    by transfer (auto)\n\n  definition bs_complement :: \"bitset \\<Rightarrow> bitset\" where\n    \"bs_complement s = NOT s\"\n\n  lemma bs_complement_correct: \"bs_\\<alpha> (bs_complement s) = - bs_\\<alpha> s\"\n    unfolding bs_\\<alpha>_def bs_complement_def\n    by transfer (simp add: bit_eq_iff, auto simp add: bit_simps)\n\nend\n\n  lemmas bs_correct[simp] = \n    bs_empty_correct\n    bs_isEmpty_correct\n    bs_insert_correct\n    bs_delete_correct\n    bs_mem_correct\n    bs_eq_correct\n    bs_subset_eq_correct\n    bs_disjoint_correct\n    bs_union_correct\n    bs_inter_correct\n    bs_diff_correct\n    bs_UNIV_correct\n    bs_complement_correct\n\n\nsubsection \\<open>Autoref Setup\\<close>\n\ndefinition bs_set_rel_def_internal: \n  \"bs_set_rel Rk \\<equiv> \n    if Rk=nat_rel then br bs_\\<alpha> (\\<lambda>_. True) else {}\"\nlemma bs_set_rel_def: \n  \"\\<langle>nat_rel\\<rangle>bs_set_rel \\<equiv> br bs_\\<alpha> (\\<lambda>_. True)\" \n  unfolding bs_set_rel_def_internal relAPP_def by simp\n\nlemmas [autoref_rel_intf] = REL_INTFI[of \"bs_set_rel\" i_set]\n\nlemma bs_set_rel_sv[relator_props]: \"single_valued (\\<langle>nat_rel\\<rangle>bs_set_rel)\"\n  unfolding bs_set_rel_def by auto\n\n\nterm bs_empty\n\nlemma [autoref_rules]: \"(bs_empty (),{})\\<in>\\<langle>nat_rel\\<rangle>bs_set_rel\"\n  by (auto simp: bs_set_rel_def br_def)\n\nlemma [autoref_rules]: \"(bs_UNIV (),UNIV)\\<in>\\<langle>nat_rel\\<rangle>bs_set_rel\"\n  by (auto simp: bs_set_rel_def br_def)\n\nlemma [autoref_rules]: \"(bs_isEmpty,op_set_isEmpty)\\<in>\\<langle>nat_rel\\<rangle>bs_set_rel \\<rightarrow> bool_rel\"\n  by (auto simp: bs_set_rel_def br_def)\n\nterm insert\nlemma [autoref_rules]: \"(bs_insert,insert)\\<in>nat_rel \\<rightarrow> \\<langle>nat_rel\\<rangle>bs_set_rel \\<rightarrow> \\<langle>nat_rel\\<rangle>bs_set_rel\"\n  by (auto simp: bs_set_rel_def br_def)\n\nterm op_set_delete\nlemma [autoref_rules]: \"(bs_delete,op_set_delete)\\<in>nat_rel \\<rightarrow> \\<langle>nat_rel\\<rangle>bs_set_rel \\<rightarrow> \\<langle>nat_rel\\<rangle>bs_set_rel\"\n  by (auto simp: bs_set_rel_def br_def)\n\nlemma [autoref_rules]: \"(bs_mem,(\\<in>))\\<in>nat_rel \\<rightarrow> \\<langle>nat_rel\\<rangle>bs_set_rel \\<rightarrow> bool_rel\"\n  by (auto simp: bs_set_rel_def br_def)\n\nlemma [autoref_rules]: \"(bs_eq,(=))\\<in>\\<langle>nat_rel\\<rangle>bs_set_rel \\<rightarrow> \\<langle>nat_rel\\<rangle>bs_set_rel \\<rightarrow> bool_rel\"\n  by (auto simp: bs_set_rel_def br_def)\n\nlemma [autoref_rules]: \"(bs_subset_eq,(\\<subseteq>))\\<in>\\<langle>nat_rel\\<rangle>bs_set_rel \\<rightarrow> \\<langle>nat_rel\\<rangle>bs_set_rel \\<rightarrow> bool_rel\"\n  by (auto simp: bs_set_rel_def br_def)\n\nlemma [autoref_rules]: \"(bs_union,(\\<union>))\\<in>\\<langle>nat_rel\\<rangle>bs_set_rel \\<rightarrow> \\<langle>nat_rel\\<rangle>bs_set_rel \\<rightarrow> \\<langle>nat_rel\\<rangle>bs_set_rel\"\n  by (auto simp: bs_set_rel_def br_def)\n\nlemma [autoref_rules]: \"(bs_inter,(\\<inter>))\\<in>\\<langle>nat_rel\\<rangle>bs_set_rel \\<rightarrow> \\<langle>nat_rel\\<rangle>bs_set_rel \\<rightarrow> \\<langle>nat_rel\\<rangle>bs_set_rel\"\n  by (auto simp: bs_set_rel_def br_def)\n\nlemma [autoref_rules]: \"(bs_diff,(-))\\<in>\\<langle>nat_rel\\<rangle>bs_set_rel \\<rightarrow> \\<langle>nat_rel\\<rangle>bs_set_rel \\<rightarrow> \\<langle>nat_rel\\<rangle>bs_set_rel\"\n  by (auto simp: bs_set_rel_def br_def)\n\nlemma [autoref_rules]: \"(bs_complement,uminus)\\<in>\\<langle>nat_rel\\<rangle>bs_set_rel \\<rightarrow> \\<langle>nat_rel\\<rangle>bs_set_rel\"\n  by (auto simp: bs_set_rel_def br_def)\n\nlemma [autoref_rules]: \"(bs_disjoint,op_set_disjoint)\\<in>\\<langle>nat_rel\\<rangle>bs_set_rel \\<rightarrow> \\<langle>nat_rel\\<rangle>bs_set_rel \\<rightarrow> bool_rel\"\n  by (auto simp: bs_set_rel_def br_def)\n\n\nexport_code\n    bs_empty\n    bs_isEmpty\n    bs_insert\n    bs_delete\n    bs_mem\n    bs_eq\n    bs_subset_eq\n    bs_disjoint\n    bs_union\n    bs_inter\n    bs_diff\n    bs_UNIV\n    bs_complement\n in SML\n\n(*\n\n    TODO: Iterator\n\n  definition \"maxbi s \\<equiv> GREATEST i. s!!i\"\n\n  lemma cmp_BIT_append_conv[simp]: \"i < i BIT b \\<longleftrightarrow> ((i\\<ge>0 \\<and> b=1) \\<or> i>0)\"\n    by (cases b) (auto simp: Bit_B0 Bit_B1)\n\n  lemma BIT_append_cmp_conv[simp]: \"i BIT b < i \\<longleftrightarrow> ((i<0 \\<and> (i=-1 \\<longrightarrow> b=0)))\"\n    by (cases b) (auto simp: Bit_B0 Bit_B1)\n\n  lemma BIT_append_eq[simp]: fixes i :: int shows \"i BIT b = i \\<longleftrightarrow> (i=0 \\<and> b=0) \\<or> (i=-1 \\<and> b=1)\"\n    by (cases b) (auto simp: Bit_B0 Bit_B1)\n\n  lemma int_no_bits_eq_zero[simp]:\n    fixes s::int shows \"(\\<forall>i. \\<not>s!!i) \\<longleftrightarrow> s=0\"\n    apply clarsimp\n    by (metis bin_eqI bin_nth_code(1))\n\n  lemma int_obtain_bit:\n    fixes s::int\n    assumes \"s\\<noteq>0\"\n    obtains i where \"s!!i\"\n    by (metis assms int_no_bits_eq_zero)\n    \n  lemma int_bit_bound:\n    fixes s::int\n    assumes \"s\\<ge>0\" and \"s!!i\"\n    shows \"i \\<le> Bits_Integer.log2 s\"\n  proof (rule ccontr)\n    assume \"\\<not>i\\<le>Bits_Integer.log2 s\"\n    hence \"i>Bits_Integer.log2 s\" by simp\n    hence \"i - 1 \\<ge> Bits_Integer.log2 s\" by simp\n    hence \"s AND bin_mask (i - 1) = s\" by (simp add: int_and_mask `s\\<ge>0`)\n    hence \"\\<not> (s!!i)\"  \n      by clarsimp (metis Nat.diff_le_self bin_nth_mask bin_nth_ops(1) leD)\n    thus False using `s!!i` ..\n  qed\n\n  lemma int_bit_bound':\n    fixes s::int\n    assumes \"s\\<ge>0\" and \"s!!i\"\n    shows \"i < Bits_Integer.log2 s + 1\"\n    using assms int_bit_bound by smt\n\n  lemma int_obtain_bit_pos:\n    fixes s::int\n    assumes \"s>0\"\n    obtains i where \"s!!i\" \"i < Bits_Integer.log2 s + 1\"\n    by (metis assms int_bit_bound' int_no_bits_eq_zero less_imp_le less_irrefl)\n\n  lemma maxbi_set: fixes s::int shows \"s>0 \\<Longrightarrow> s!!maxbi s\"\n    unfolding maxbi_def\n    apply (rule int_obtain_bit_pos, assumption)\n    apply (rule GreatestI_nat, assumption)\n    apply (intro allI impI)\n    apply (rule int_bit_bound'[rotated], assumption)\n    by auto\n\n  lemma maxbi_max: fixes s::int shows \"i>maxbi s \\<Longrightarrow> \\<not> s!!i\"\n    oops\n\n  function get_maxbi :: \"nat \\<Rightarrow> int \\<Rightarrow> nat\" where\n    \"get_maxbi n s = (let\n        b = 1<<n\n      in\n        if b\\<le>s then get_maxbi (n+1) s\n        else n\n    )\"\n    by pat_completeness auto\n\n  termination\n    apply (rule \"termination\"[of \"measure (\\<lambda>(n,s). nat (s + 1 - (1<<n)))\"])\n    apply simp\n    apply auto\n    by (smt bin_mask_ge0 bin_mask_p1_conv_shift)\n\n\n  partial_function (tailrec) \n    bs_iterate_aux :: \"nat \\<Rightarrow> bitset \\<Rightarrow> ('\\<sigma> \\<Rightarrow> bool) \\<Rightarrow> (nat \\<Rightarrow> '\\<sigma> \\<Rightarrow> '\\<sigma>) \\<Rightarrow> '\\<sigma> \\<Rightarrow> '\\<sigma>\"\n    where \"bs_iterate_aux i s c f \\<sigma> = (\n    if s < 1 << i then \\<sigma>\n    else if \\<not>c \\<sigma> then \\<sigma>\n    else if test_bit s i then bs_iterate_aux (i+1) s c f (f i \\<sigma>)\n    else bs_iterate_aux (i+1) s c f \\<sigma>\n  )\"\n\n  definition bs_iteratei :: \"bitset \\<Rightarrow> (nat,'\\<sigma>) set_iterator\" where \n    \"bs_iteratei s = bs_iterate_aux 0 s\"\n\n\n  definition bs_set_rel_def_internal: \n    \"bs_set_rel Rk \\<equiv> \n      if Rk=nat_rel then br bs_\\<alpha> (\\<lambda>_. True) else {}\"\n  lemma bs_set_rel_def: \n    \"\\<langle>nat_rel\\<rangle>bs_set_rel \\<equiv> br bs_\\<alpha> (\\<lambda>_. True)\" \n    unfolding bs_set_rel_def_internal relAPP_def by simp\n\n\n  definition \"bs_to_list \\<equiv> it_to_list bs_iteratei\"\n\n  lemma \"(1::int)<<i = 2^i\"\n    by (simp add: shiftl_int_def)\n\n  lemma \n    fixes s :: int\n    assumes \"s\\<ge>0\"  \n    shows \"s < 1<<i \\<longleftrightarrow> Bits_Integer.log2 s \\<le> i\"\n    using assms\n  proof (induct i arbitrary: s)\n    case 0 thus ?case by auto\n  next\n    case (Suc i)\n    note GE=`0\\<le>s`\n    show ?case proof\n      assume \"s < 1 << Suc i\"\n\n      have \"s \\<le> (s >> 1) BIT 1\"\n\n      hence \"(s >> 1) < (1<<i)\" using GE apply auto\n      with Suc.hyps[of \"s div 2\"]\n\n\n    apply auto\n    \n\n\n  lemma \"distinct (bs_to_list s)\"\n    unfolding bs_to_list_def it_to_list_def bs_iteratei_def[abs_def]\n  proof -\n    {\n      fix l i\n      assume \"distinct l\"\n      show \"distinct (bs_iterate_aux 0 s (\\<lambda>_. True) (\\<lambda>x l. l @ [x]) [])\"\n\n    }\n\n\n    apply auto\n    \n\n\n\n    lemma \"set (bs_to_list s) = bs_\\<alpha> s\"\n\n\n  lemma autoref_iam_is_iterator[autoref_ga_rules]: \n    shows \"is_set_to_list nat_rel bs_set_rel bs_to_list\"\n    unfolding is_set_to_list_def is_set_to_sorted_list_def\n    apply clarsimp\n    unfolding it_to_sorted_list_def\n    apply (refine_rcg refine_vcg)\n    apply (simp_all add: bs_set_rel_def br_def)\n\n  proof (clarsimp)\n\n\n\n  definition \n\n\"iterate s c f \\<sigma> \\<equiv> let\n    i=0;\n    b=0;\n    (_,_,s) = while \n  in\n\n  end\"\n\n\n*)\n\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/Collections/GenCF/Impl/Impl_Bit_Set.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8933094060543487, "lm_q2_score": 0.810478913248044, "lm_q1q2_score": 0.7240084366131843}}
{"text": "theory Exercise9\n  imports Main\nbegin\n\nfun add :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\" where\n  \"add 0 n = n\"\n  | \"add (Suc x) y = Suc (add x y)\"\n\nfun itadd :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\" where\n  \"itadd 0 x = x\"\n  | \"itadd (Suc x) y = itadd x (Suc y)\"\n\nlemma add_n_zero [simp]: \"add n 0 = n\"\n  apply (induction n)\n  apply auto\ndone\n\nlemma add_m_suc_n [simp]: \"add m (Suc n) = Suc (add m n)\"\n  apply (induction m)\n  apply auto\ndone\n\nlemma add_commutativity [simp]: \"add m n = add n m\"\n  apply (induction n)\n  apply auto\ndone\n\ntheorem itadd_is_add [simp]: \"itadd m n = add m n\"\n  apply (induction m arbitrary: n)\n  apply auto\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/Exercise9.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094060543488, "lm_q2_score": 0.8104789018037399, "lm_q1q2_score": 0.7240084263898798}}
{"text": "theory NewAlgebra\n  imports Fixpoint \"$AFP/Kleene_Algebra/Kleene_Algebra\" Omega_Algebra\nbegin\n\nnotation inf (infixl \"\\<sqinter>\" 70)\nnotation sup (infixl \"\\<squnion>\" 65)\n\nclass par_dioid = join_semilattice_zero + one +\n  fixes par :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a\" (infixl \"\\<parallel>\" 69)\n  assumes par_assoc [simp]: \"x \\<parallel> (y \\<parallel> z) = (x \\<parallel> y) \\<parallel> z\"\n  and par_comm: \"x \\<parallel> y = y \\<parallel> x\"\n  and par_distl [simp]: \"x \\<parallel> (y + z) = x \\<parallel> y + x \\<parallel> z\"\n  and par_unitl [simp]: \"1 \\<parallel> x = x\"\n  and par_annil [simp]: \"0 \\<parallel> x = 0\"\n\nbegin\n\n  lemma par_distr [simp]: \"(x+y) \\<parallel> z = x \\<parallel> z + y \\<parallel> z\" \n    by (metis par_comm par_distl)\n\n  lemma par_isol [intro]: \"x \\<le> y \\<Longrightarrow> x \\<parallel> z \\<le> y \\<parallel> z\"\n    by (metis order_prop par_distr)\n \n  lemma par_isor [intro]: \"x \\<le> y \\<Longrightarrow> z \\<parallel> x \\<le> z \\<parallel> y\"\n    by (metis par_comm par_isol)\n\n  lemma par_unitr [simp]: \"x \\<parallel> 1 = x\"\n    by (metis par_comm par_unitl)\n\n  lemma par_annir [simp]: \"x \\<parallel> 0 = 0\"\n    by (metis par_annil par_comm)\n\n  lemma par_subdistl: \"x \\<parallel> z \\<le> (x + y) \\<parallel> z\"\n    by (metis order_prop par_distr)\n\n  lemma par_subdistr: \"z \\<parallel> x \\<le> z \\<parallel> (x + y)\"\n    by (metis par_comm par_subdistl)\n\n  lemma par_double_iso [intro]: \"w \\<le> x \\<Longrightarrow> y \\<le> z \\<Longrightarrow> w \\<parallel> y \\<le> x \\<parallel> z\"\n    by (metis order_trans par_isol par_isor)\n\nend\n\nclass weak_trioid = par_dioid + dioid_one_zerol\n\nclass trioid = par_dioid + dioid_one_zero + complete_lattice\n\nlocale rg_algebra =\n  fixes restrict :: \"'b::complete_lattice \\<Rightarrow> 'a::trioid \\<Rightarrow> 'a::trioid\" (infixr \"\\<Colon>\" 55)\n  and rg :: \"'b::complete_lattice \\<Rightarrow> 'a::trioid \\<Rightarrow> 'a::trioid\" (infixr \"\\<leadsto>\" 55)\n  and guar :: \"'b::complete_lattice \\<Rightarrow> 'a::trioid\"\n  assumes mod_coext: \"r \\<Colon> x \\<le> x\"\n  and guar_iso: \"r \\<le> s \\<Longrightarrow> guar r \\<le> guar s\"\n  and mod_top: \"top \\<Colon> x = x\"\n  and rg_top: \"top \\<leadsto> x = x\"\n  and mod_inter: \"r \\<sqinter> s \\<Colon> x = r \\<Colon> s \\<Colon> x\"\n  and mod_isotone: \"r \\<le> s \\<Longrightarrow> r \\<Colon> x \\<le> s \\<Colon> x\"\n  and galois: \"(r \\<Colon> x \\<le> y) \\<longleftrightarrow> (x \\<le> r \\<leadsto> y)\"\n  and rg_antitone: \"r \\<le> s  \\<Longrightarrow> s \\<leadsto> x \\<le> r \\<leadsto> x\"\n  and guar_par: \"guar g1 \\<parallel> guar g2 = guar (g1 \\<squnion> g2)\"\n\n  and ax2: \"(r \\<squnion> g2 \\<leadsto> guar g1 \\<sqinter> x) \\<parallel> (r \\<squnion> g1 \\<leadsto> guar g2 \\<sqinter> y) \\<le> r \\<leadsto> (guar g1 \\<sqinter> x) \\<parallel> (guar g2 \\<sqinter> y)\"\n\n\nbegin\n\n  lemma rg_ext: \"x \\<le> r \\<leadsto> x\"\n    by (metis galois mod_coext)\n\n  lemma mod_prog_iso: \"x \\<le> y \\<Longrightarrow> r \\<Colon> x \\<le> r \\<Colon> y\"\n    by (metis ab_semigroup_add_class.add_ac(1) dual_order.order_iff_strict galois order_prop)\n\n  lemma rg_prog_iso: \"x \\<le> y \\<Longrightarrow> r \\<leadsto> x \\<le> r \\<leadsto> y\"\n    by (metis dual_order.trans galois order_refl)\n\n  lemma rg_mono: \"r \\<le> s \\<Longrightarrow> x \\<le> y \\<Longrightarrow> s \\<leadsto> x \\<le> r \\<leadsto> y\"\n    by (metis galois rg_antitone sup.coboundedI1 sup.orderE sup_commute)\n\n  lemma \"r \\<squnion> s \\<leadsto> x \\<le> r \\<leadsto> s \\<leadsto> x\"\n    apply (rule rg_mono)\n    apply (metis sup.cobounded1)\n    by (metis rg_ext)\n\n  lemma \"r \\<Colon> r \\<leadsto> x \\<le> r \\<Colon> x\"\n    by (metis galois inf_idem mod_inter mod_prog_iso order_refl)\n\n  definition quintuple :: \"'b \\<Rightarrow> 'b \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> bool\" (\"_, _ \\<turnstile> \\<lbrace>_\\<rbrace> _ \\<lbrace>_\\<rbrace>\" [20,20,20,20,20] 1000) where\n    \"r, g \\<turnstile> \\<lbrace>p\\<rbrace> x \\<lbrace>q\\<rbrace> \\<equiv> (p \\<cdot> x \\<le> r \\<leadsto> guar g \\<sqinter> q) \\<and> (guar r \\<parallel> q \\<le> q)\"\n\n  lemma \"r \\<Colon> r \\<leadsto> x \\<le> r \\<Colon> x\"\n    by (metis galois inf_idem mod_inter mod_prog_iso order_refl)\n\n  lemma \"r \\<leadsto> x \\<le> r \\<leadsto> r \\<Colon> x\"\n    by (metis galois inf_idem mod_inter mod_prog_iso order_refl)\n\n  lemma rely_swap: \"r \\<Colon> r \\<leadsto> x \\<le> r \\<leadsto> r \\<Colon> x\"\n    by (metis galois order_refl rg_prog_iso)\n\n  theorem parallel_rule:\n    assumes \"r \\<squnion> g1 \\<le> r2\"\n    and \"r \\<squnion> g2 \\<le> r1\"\n    and \"g1 \\<squnion> g2 \\<le> g\"\n    and \"r1, g1 \\<turnstile> \\<lbrace>p\\<rbrace> x \\<lbrace>q1\\<rbrace>\"\n    and \"r2, g2 \\<turnstile> \\<lbrace>p\\<rbrace> y \\<lbrace>q2\\<rbrace>\"\n    and \"p \\<cdot> (x \\<parallel> y) \\<le> p \\<cdot> x \\<parallel> p \\<cdot> y\"\n    shows \"r, g \\<turnstile> \\<lbrace>p\\<rbrace> x \\<parallel> y \\<lbrace>q1 \\<sqinter> q2\\<rbrace>\"\n  proof -\n    from assms(5) have g1_preserves_q2: \"guar g1 \\<parallel> q2 \\<le> q2\"\n      by (simp add: quintuple_def) (metis assms(1) dual_order.trans guar_iso par_isol sup.boundedE)\n\n    from assms(5) have r2_preserves_q2: \"guar r2 \\<parallel> q2 \\<le> q2\"\n      by (simp add: quintuple_def)\n\n    from assms(4) have g2_preserves_q1: \"q1 \\<parallel> guar g2 \\<le> q1\"\n      by (simp add: quintuple_def) (metis assms(2) guar_iso par_comm par_isor sup.boundedE sup_absorb2)\n\n    from assms(4) have r1_preserves_q1: \"guar r1 \\<parallel> q1 \\<le> q1\"\n      by (simp add: quintuple_def)\n\n    have \"p \\<cdot> (x \\<parallel> y) \\<le> p \\<cdot> x \\<parallel> p \\<cdot> y\"\n      by (metis assms(6))\n    also have \"... \\<le> (r1 \\<leadsto> guar g1 \\<sqinter> q1) \\<parallel> (r2 \\<leadsto> guar g2 \\<sqinter> q2)\"\n      by (metis assms(4) assms(5) par_double_iso quintuple_def)\n    also have \"... \\<le> (r \\<squnion> g2 \\<leadsto> guar g1 \\<sqinter> q1) \\<parallel> (r \\<squnion> g1 \\<leadsto> guar g2 \\<sqinter> q2)\"\n      by (metis assms(1) assms(2) par_double_iso rg_antitone)\n    also have \"... \\<le> r \\<leadsto> (guar g1 \\<sqinter> q1) \\<parallel> (guar g2 \\<sqinter> q2)\"\n      by (metis ax2)\n    also have \"... \\<le> r \\<leadsto> guar (g1 \\<squnion> g2) \\<sqinter> (q1 \\<sqinter> q2)\"\n      apply (auto intro!: rg_prog_iso)\n      apply (metis guar_par inf.cobounded2 inf_commute par_double_iso)\n      apply (metis g2_preserves_q1 inf_commute inf_sup_ord(2) order.trans par_double_iso)\n      by (metis g1_preserves_q2 inf.bounded_iff inf.cobounded2 inf_absorb2 par_double_iso)\n    finally have \"p \\<cdot> (x \\<parallel> y) \\<le> r \\<leadsto> guar (g1 \\<squnion> g2) \\<sqinter> (q1 \\<sqinter> q2)\" .\n    moreover have \"guar r \\<parallel> q1 \\<sqinter> q2 \\<le> q1 \\<sqinter> q2\"\n      apply auto\n      apply (metis assms(2) guar_iso inf_sup_ord(1) order_trans par_double_iso r1_preserves_q1 sup.boundedE)\n      by (metis assms(1) guar_iso inf_sup_ord(2) order_trans par_double_iso r2_preserves_q2 sup.boundedE)\n    ultimately show ?thesis\n      apply (simp add: quintuple_def)\n      apply (erule order_trans)\n      by (metis assms(3) guar_iso inf_mono order_refl rg_prog_iso)\n  qed\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/NewAlgebra.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933093946927837, "lm_q2_score": 0.8104789018037399, "lm_q1q2_score": 0.724008417181571}}
{"text": "theory General_Groups\n  imports Set_Mult\nbegin\n\n(* Manuel *)\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\n(* Manuel *)\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\ndefinition (in group) complementary :: \"'a set \\<Rightarrow> 'a set \\<Rightarrow> bool\" where\n  \"complementary H1 H2 \\<longleftrightarrow> H1 \\<inter> H2 = {\\<one>}\"\n\nlemma (in group) complementary_symm[simp]: \"complementary A B \\<longleftrightarrow> complementary B A\"\n  unfolding complementary_def by blast\n\nlemma (in group) subgroup_carrier_complementary:\n  assumes \"complementary H J\" \"subgroup I (G\\<lparr>carrier := H\\<rparr>)\" \"subgroup K (G\\<lparr>carrier := J\\<rparr>)\"\n  shows \"complementary I K\"\nproof -\n  have \"\\<one> \\<in> I\" using subgroup.one_closed[OF assms(2)] by simp\n  moreover have \"\\<one> \\<in> K\" using subgroup.one_closed[OF assms(3)] by simp\n  moreover have \"I \\<inter> K \\<subseteq> H \\<inter> J\" using subgroup.subset assms(2, 3) by force\n  ultimately show ?thesis using assms(1) unfolding complementary_def by blast\nqed\n\nlemma (in group) subgroup_subset_complementary:\n  assumes \"subgroup H G\" \"subgroup J G\" \"subgroup I G\"\n  and \"I \\<subseteq> J\" \"complementary H J\"\nshows \"complementary H I\"\n  by(intro subgroup_carrier_complementary[OF assms(5), of H I] subgroup_incl, use assms in auto)\n\nlemma (in group) complementary_subgroup_iff:\n  assumes \"subgroup H G\"\n  shows \"complementary A B \\<longleftrightarrow> group.complementary (G\\<lparr>carrier := H\\<rparr>) A B\"\nproof -\n  interpret H: group \"G\\<lparr>carrier := H\\<rparr>\" using subgroup.subgroup_is_group assms by blast\n  have \"\\<one>\\<^bsub>G\\<^esub> = \\<one>\\<^bsub>G\\<lparr>carrier := H\\<rparr>\\<^esub>\" by simp\n  then show ?thesis unfolding complementary_def H.complementary_def by simp\nqed\n\nlemma (in group) subgroup_card_dvd_group_ord:\n  assumes \"subgroup H G\"\n  shows \"card H dvd order G\"\n  using Coset.group.lagrange[of G H] assms group_axioms by (metis dvd_triv_right)\n\nlemma (in group) subgroup_card_eq_order:\n  assumes \"subgroup H G\"\n  shows \"card H = order (G\\<lparr>carrier := H\\<rparr>)\"\n  unfolding order_def by simp\n\nlemma (in group) finite_subgroup_card_neq_0:\n  assumes \"subgroup H G\" \"finite H\"\n  shows \"card H \\<noteq> 0\"\n  using subgroup_nonempty assms by auto\n\nlemma (in group) subgroup_ord_dvd_group_ord:\n  assumes \"subgroup H G\"\n  shows \"order (G\\<lparr>carrier := H\\<rparr>) dvd order G\"\n  by (metis subgroup_card_dvd_group_ord[of H] assms subgroup_card_eq_order)\n\nlemma (in group) sub_subgroup_dvd_card:\n  assumes \"subgroup H G\" \"subgroup J G\" \"J \\<subseteq> H\"\n  shows \"card J dvd card H\"\n  by (metis subgroup_incl[of J H] subgroup_card_eq_order[of H] group.subgroup_card_dvd_group_ord[of \"(G\\<lparr>carrier := H\\<rparr>)\" J] assms subgroup.subgroup_is_group[of H G] group_axioms)\n\nlemma (in group) inter_subgroup_dvd_card:\n  assumes \"subgroup H G\" \"subgroup J G\"\n  shows \"card (H \\<inter> J) dvd card H\"\n  using subgroups_Inter_pair[of H J] assms sub_subgroup_dvd_card[of H \"H \\<inter> J\"] by blast\n\nlemma (in group) set_subgroup_generate_dvd_order:\n  assumes \"A \\<subseteq> carrier G\" and \"subgroup H G\"\n  shows \"(card H) dvd card (generate G (H \\<union> A))\" (is \"?cH dvd card ?F\")\nproof -\n  from generate_is_subgroup[of \"H \\<union> A\"] have \"subgroup ?F G\" using assms subgroup.subset by blast\n  moreover have \"H \\<subseteq> ?F\" using generate.incl[of _ H G] mono_generate[of H \"H \\<union> A\"] by blast\n  ultimately show ?thesis using assms(2) sub_subgroup_dvd_card[of \"?F\" H] by blast\nqed\n\nlemma (in group) sub_sub_generate_dvd_order:\n  assumes \"subgroup H G\" \"subgroup J G\"\n  shows \"(card H) dvd card (generate G (H \\<union> J))\"\n  using set_subgroup_generate_dvd_order[of J H] subgroup.subset[of J G] assms by blast\n\nlemma (in group) subgroups_order_coprime_inter_card_one:\n  assumes \"subgroup H G\" and \"subgroup J G\" and \"coprime (card H) (card J)\"\n  shows \"card (H \\<inter> J) = 1\"\nproof -\n  from assms coprime_def[of \"card H\" \"card J\"] inter_subgroup_dvd_card[of H J] inter_subgroup_dvd_card[of J H] have \"is_unit (card (H \\<inter> J))\" by (simp add: inf_commute)\n  then show ?thesis by simp\nqed\n\nlemma (in group) subgroups_order_coprime_imp_compl:\n  assumes \"subgroup H G\" and \"subgroup J G\" and \"coprime (card H) (card J)\"\n  shows \"complementary H J\" unfolding complementary_def\n  using subgroups_order_coprime_inter_card_one[of H J] assms\n  by (metis card_1_singletonE insert_absorb singleton_insert_inj_eq subgroup.one_closed subgroups_Inter_pair)\n\nlemma (in comm_group) compl_imp_diff_cosets:\n  assumes \"subgroup H G\" \"subgroup J G\" \"finite H\" \"finite J\"\n  and \"complementary H J\"\nshows \"\\<And>a b. \\<lbrakk>a \\<in> J; b \\<in> J; a \\<noteq> b\\<rbrakk> \\<Longrightarrow> (H #> a) \\<noteq> (H #> b)\"\nproof (rule ccontr; safe)\n  fix a b\n  assume ab: \"a \\<in> J\" \"b \\<in> J\" \"a \\<noteq> b\"\n  then have [simp]: \"a \\<in> carrier G\" \"b \\<in> carrier G\" using assms subgroup.subset by auto\n  assume \"H #> a = H #> b\"\n  then have \"a \\<otimes> inv b \\<in> H\" using assms(1, 2) ab\n    by (metis comm_group_axioms comm_group_def rcos_self subgroup.mem_carrier subgroup.rcos_module_imp)\n  moreover have \"a \\<otimes> inv b \\<in> J\" by (rule subgroup.m_closed[OF assms(2) ab(1) subgroup.m_inv_closed[OF assms(2) ab(2)]])\n  moreover have \"a \\<otimes> inv b \\<noteq> \\<one>\" using ab inv_equality by fastforce\n  ultimately have \"H \\<inter> J \\<noteq> {\\<one>}\" by blast\n  thus False using assms(5) unfolding complementary_def by blast\nqed\n\nlemma (in group) coset_neq_imp_empty_inter:\n  assumes \"subgroup H G\" \"a \\<in> carrier G\" \"b \\<in> carrier G\"\n  shows \"H #> a \\<noteq> H #> b \\<Longrightarrow> (H #> a) \\<inter> (H #> b) = {}\"\n  by (metis Int_emptyI assms repr_independence)\n\nlemma (in comm_group) subgroup_is_comm_group:\n  assumes \"subgroup H G\"\n  shows \"comm_group (G\\<lparr>carrier := H\\<rparr>)\" unfolding comm_group_def\nproof\n  interpret HG: Group.group \"(G\\<lparr>carrier := H\\<rparr>)\" using subgroup.subgroup_is_group assms by blast\n  show \"Group.group (G\\<lparr>carrier := H\\<rparr>)\" by unfold_locales\n  show \"comm_monoid (G\\<lparr>carrier := H\\<rparr>)\" unfolding comm_monoid_def comm_monoid_axioms_def\n  proof(safe)\n    fix x y\n    assume \"x \\<in> carrier (G\\<lparr>carrier := H\\<rparr>)\" \"y \\<in> carrier (G\\<lparr>carrier := H\\<rparr>)\"\n    then have xy: \"x \\<in> H\" \"y \\<in> H\" by auto\n    moreover have \"H \\<subseteq> carrier G\" by (rule subgroup.subset[OF assms])\n    thus \"x \\<otimes>\\<^bsub>G\\<lparr>carrier := H\\<rparr>\\<^esub> y = y \\<otimes>\\<^bsub>G\\<lparr>carrier := H\\<rparr>\\<^esub> x\"\n      using comm_monoid.m_comm[of G, OF comm_monoid_axioms] xy by auto\n  qed\nqed\n\nlemma (in group) prime_power_complementary_groups:\n  assumes \"Factorial_Ring.prime p\" \"Factorial_Ring.prime q\" \"p \\<noteq> q\"\n  and \"subgroup P G\" \"card P = p ^ x\"\n  and \"subgroup Q G\" \"card Q = q ^ y\"\n  shows \"complementary P Q\"\nproof -\n  from assms(1-3) assms(5) assms(7) have \"coprime (card P) (card Q)\" using coprime_def[unfolded] by (metis coprime_power_right_iff primes_coprime)\n  then show ?thesis using group.subgroups_order_coprime_imp_compl[of G P Q] assms(4, 6) complementary_def[unfolded] by blast\nqed\n\nlemma (in group) pow_int_mod_ord:\n  assumes [simp]:\"a \\<in> carrier G\" \"ord a \\<noteq> 0\"\n  shows \"a [^] (n::int) = a [^] (n mod ord a)\"\nproof -\n  obtain q r where d: \"q = n div ord a\" \"r = n mod ord a\" \"n = q * ord a + r\"\n    using mod_div_decomp by blast\n  hence \"a [^] n = (a [^] int (ord a)) [^] q \\<otimes> a [^] r\"\n    using assms(1) int_pow_mult int_pow_pow\n    by (metis mult_of_nat_commute)\n  also have \"\\<dots> = \\<one> [^] q \\<otimes> a [^] r\"\n    by (simp add: int_pow_int)\n  also have \"\\<dots> = a [^] r\" by simp\n  finally show ?thesis using d(2) by blast\nqed\n\nlemma (in group) pow_nat_mod_ord:\n  assumes [simp]:\"a \\<in> carrier G\" \"ord a \\<noteq> 0\"\n  shows \"a [^] (n::nat) = a [^] (n mod ord a)\"\nproof -\n  obtain q r where d: \"q = n div ord a\" \"r = n mod ord a\" \"n = q * ord a + r\"\n    using mod_div_decomp by blast\n  hence \"a [^] n = (a [^] ord a) [^] q \\<otimes> a [^] r\"\n    using assms(1) nat_pow_mult nat_pow_pow by presburger\n  also have \"\\<dots> = \\<one> [^] q \\<otimes> a [^] r\" by auto\n  also have \"\\<dots> = a [^] r\" by simp\n  finally show ?thesis using d(2) by blast\nqed\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\n(* Manuel *)\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\n(* Manuel *)\nlemma (in subgroup) inv_in_iff:\n  assumes \"x \\<in> carrier G\" \"group G\"\n  shows   \"inv x \\<in> H \\<longleftrightarrow> x \\<in> H\"\nproof safe\n  assume \"inv x \\<in> H\"\n  hence \"inv (inv x) \\<in> H\" by blast\n  also have \"inv (inv x) = x\"\n    by (intro group.inv_inv) (use assms in auto)\n  finally show \"x \\<in> H\" .\nqed auto\n\n(* Manuel *)\nlemma (in subgroup) mult_in_cancel_left:\n  assumes \"y \\<in> carrier G\" \"x \\<in> H\" \"group G\"\n  shows   \"x \\<otimes> y \\<in> H \\<longleftrightarrow> y \\<in> H\"\nproof safe\n  assume \"x \\<otimes> y \\<in> H\"\n  hence \"inv x \\<otimes> (x \\<otimes> y) \\<in> H\"\n    using assms by blast\n  also have \"inv x \\<otimes> (x \\<otimes> y) = y\"\n    using assms by (simp add: \\<open>x \\<otimes> y \\<in> H\\<close> group.inv_solve_left')\n  finally show \"y \\<in> H\" .\nqed (use assms in auto)\n\n(* Manuel *)\nlemma (in subgroup) mult_in_cancel_right:\n  assumes \"x \\<in> carrier G\" \"y \\<in> H\" \"group G\"\n  shows   \"x \\<otimes> y \\<in> H \\<longleftrightarrow> x \\<in> H\"\nproof safe\n  assume \"x \\<otimes> y \\<in> H\"\n  hence \"(x \\<otimes> y) \\<otimes> inv y \\<in> H\"\n    using assms by blast\n  also have \"(x \\<otimes> y) \\<otimes> inv y = x\"\n    using assms by (simp add: \\<open>x \\<otimes> y \\<in> H\\<close> group.inv_solve_right')\n  finally show \"x \\<in> H\" .\nqed (use assms in auto)\n\nlemma (in group) (* Manuel *)\n  assumes \"x \\<in> carrier G\" and \"x [^] n = \\<one>\" and \"n > 0\"\n  shows   ord_le: \"ord x \\<le> n\" and ord_pos: \"ord x > 0\"\nproof -\n  have \"ord x dvd n\"\n    using pow_eq_id[of x n] assms by auto\n  thus \"ord x \\<le> n\" \"ord x > 0\"\n    using assms by (auto intro: dvd_imp_le)\nqed\n\nlemma (in group) ord_conv_Least: (* Manuel *)\n  assumes \"x \\<in> carrier G\" \"\\<exists>n::nat > 0. x [^] n = \\<one>\"\n  shows   \"ord x = (LEAST n::nat. 0 < n \\<and> x [^] n = \\<one>)\"\nproof (rule antisym)\n  show \"ord x \\<le> (LEAST n::nat. 0 < n \\<and> x [^] n = \\<one>)\"\n    using assms LeastI_ex[OF assms(2)] by (intro ord_le) auto\n  show \"ord x \\<ge> (LEAST n::nat. 0 < n \\<and> x [^] n = \\<one>)\"\n    using assms by (intro Least_le) (auto intro: pow_ord_eq_1 ord_pos)\nqed\n\nlemma (in group) ord_conv_Gcd: (* Manuel *)\n  assumes \"x \\<in> carrier G\"\n  shows   \"ord x = Gcd {n. x [^] n = \\<one>}\"\n  by (rule sym, rule Gcd_eqI) (use assms in \\<open>auto simp: pow_eq_id\\<close>)\n\nlemma (in group) subgroup_ord_eq:\n  assumes \"subgroup H G\" \"x \\<in> H\"\n  shows \"group.ord (G\\<lparr>carrier := H\\<rparr>) x = ord x\"\n  using nat_pow_consistent[of x] ord_def[of x] group.ord_def[of \"(G\\<lparr>carrier := H\\<rparr>)\" x] subgroup.subgroup_is_group[of H G] assms group_axioms by simp\n\nlemma (in group) ord_FactGroup:\n  assumes \"subgroup P G\" \"group (G Mod P)\"\n  shows \"order (G Mod P) * card P = order G\"\n  using lagrange[of P] FactGroup_def[of G P] assms order_def[of \"(G Mod P)\"] by fastforce\n\nlemma (in group) one_is_same:\n  assumes \"subgroup H G\"\n  shows \"\\<one>\\<^bsub>G\\<lparr>carrier := H\\<rparr>\\<^esub> = \\<one>\"\n  by simp\n\nlemma (in group) kernel_FactGroup:\n  assumes \"P \\<lhd> G\"\n  shows \"kernel G (G Mod P) (\\<lambda>x. P #> x) = P\"\nproof(rule equalityI; rule subsetI)\n  fix x\n  assume \"x \\<in> kernel G (G Mod P) ((#>) P)\"\n  then have \"P #> x = \\<one>\\<^bsub>G Mod P\\<^esub>\" \"x \\<in> carrier G\" unfolding kernel_def by simp+\n  with coset_join1[of P x] show \"x \\<in> P\" using assms unfolding normal_def by simp\nnext\n  fix x\n  assume x:\"x \\<in> P\"\n  then have xc: \"x \\<in> carrier G\" using assms subgroup.subset unfolding normal_def by fast\n  from x have \"P #> x = P\" using assms\n    by (simp add: normal_imp_subgroup subgroup.rcos_const) \n  thus \"x \\<in> kernel G (G Mod P) ((#>) P)\" unfolding kernel_def using xc by simp\nqed\n\nlemma (in group) sub_subgroup_coprime:\n  assumes \"subgroup H G\" \"subgroup J G\" \"coprime (card H) (card J)\"\n  and \"subgroup sH G\" \"subgroup sJ G\" \"sH \\<subseteq> H\" \"sJ \\<subseteq> J\"\nshows \"coprime (card sH) (card sJ)\"\n  using assms by (meson coprime_divisors sub_subgroup_dvd_card)\n\nlemma (in group) pow_eq_nat_mod:\n  assumes \"a \\<in> carrier G\" \"a [^] n = a [^] m\"\n  shows \"n mod (ord a) = m mod (ord a)\"\nproof -\n  from assms have \"a [^] (n - m) = \\<one>\" using pow_eq_div2 by blast\n  hence \"ord a dvd n - m\" using assms(1) pow_eq_id by blast\n  thus ?thesis\n    by (metis assms mod_eq_dvd_iff_nat nat_le_linear pow_eq_div2 pow_eq_id)\nqed\n\nlemma (in group) pow_eq_int_mod:\n  fixes n m::int\n  assumes \"a \\<in> carrier G\" \"a [^] n = a [^] m\"\n  shows \"n mod (ord a) = m mod (ord a)\"\nproof -\n  from assms have \"a [^] (n - m) = \\<one>\" using int_pow_closed int_pow_diff r_inv by presburger\n  hence \"ord a dvd n - m\" using assms(1) int_pow_eq_id by blast\n  thus ?thesis by (meson mod_eq_dvd_iff)\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/General_Groups.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511579973932, "lm_q2_score": 0.8459424314825853, "lm_q1q2_score": 0.7240008095835011}}
{"text": "(*\n  File:   Akra_Bazzi_Real.thy\n  Author: Manuel Eberl <manuel@pruvisto.org>\n\n  The continuous version of the Akra-Bazzi theorem for functions on the reals.\n*)\n\nsection \\<open>The continuous Akra-Bazzi theorem\\<close>\ntheory Akra_Bazzi_Real\nimports\n  Complex_Main\n  Akra_Bazzi_Asymptotics\nbegin\n\ntext \\<open>\n  We want to be generic over the integral definition used; we fix some arbitrary\n  notions of integrability and integral and assume just the properties we need.\n  The user can then instantiate the theorems with any desired integral definition.\n\\<close>\nlocale akra_bazzi_integral =\n  fixes integrable :: \"(real \\<Rightarrow> real) \\<Rightarrow> real \\<Rightarrow> real \\<Rightarrow> bool\"\n    and integral   :: \"(real \\<Rightarrow> real) \\<Rightarrow> real \\<Rightarrow> real \\<Rightarrow> real\"\n  assumes integrable_const: \"c \\<ge> 0 \\<Longrightarrow> integrable (\\<lambda>_. c) a b\"\n      and integral_const:   \"c \\<ge> 0 \\<Longrightarrow> a \\<le> b \\<Longrightarrow> integral (\\<lambda>_. c) a b = (b - a) * c\"\n      and integrable_subinterval:\n            \"integrable f a b \\<Longrightarrow> a \\<le> a' \\<Longrightarrow> b' \\<le> b \\<Longrightarrow> integrable f a' b'\"\n      and integral_le:\n            \"integrable f a b \\<Longrightarrow> integrable g a b \\<Longrightarrow> (\\<And>x. x \\<in> {a..b} \\<Longrightarrow> f x \\<le> g x) \\<Longrightarrow>\n                 integral f a b \\<le> integral g a b\"\n      and integral_combine:\n            \"a \\<le> c \\<Longrightarrow> c \\<le> b \\<Longrightarrow> integrable f a b \\<Longrightarrow>\n                 integral f a c + integral f c b = integral f a b\"\nbegin\nlemma integral_nonneg:\n  \"a \\<le> b \\<Longrightarrow> integrable f a b \\<Longrightarrow> (\\<And>x. x \\<in> {a..b} \\<Longrightarrow> f x \\<ge> 0) \\<Longrightarrow> integral f a b \\<ge> 0\"\n  using integral_le[OF integrable_const[of 0], of f a b]  by (simp add: integral_const)\nend\n\n\ndeclare sum.cong[fundef_cong]\n\nlemma strict_mono_imp_ex1_real:\n  fixes f :: \"real \\<Rightarrow> real\"\n  assumes lim_neg_inf: \"LIM x at_bot. f x :> at_top\"\n  assumes lim_inf: \"(f \\<longlongrightarrow> z) at_top\"\n  assumes mono: \"\\<And>a b. a < b \\<Longrightarrow> f b < f a\"\n  assumes cont: \"\\<And>x. isCont f x\"\n  assumes y_greater_z: \"z < y\"\n  shows   \"\\<exists>!x. f x = y\"\nproof (rule ex_ex1I)\n  fix a b assume \"f a = y\" \"f b = y\"\n  thus \"a = b\" by (cases rule: linorder_cases[of a b]) (auto dest: mono)\nnext\n  from lim_neg_inf have \"eventually (\\<lambda>x. y \\<le> f x) at_bot\" by (subst (asm) filterlim_at_top) simp\n  then obtain l where l: \"\\<And>x. x \\<le> l \\<Longrightarrow> y \\<le> f x\" by (subst (asm) eventually_at_bot_linorder) auto\n\n  from order_tendstoD(2)[OF lim_inf y_greater_z]\n    obtain u where u: \"\\<And>x. x \\<ge> u \\<Longrightarrow> f x < y\" by (subst (asm) eventually_at_top_linorder) auto\n  define a where \"a = min l u\"\n  define b where \"b = max l u\"\n  have a: \"f a \\<ge> y\" unfolding a_def by (intro l) simp\n  moreover have b: \"f b < y\" unfolding b_def by (intro u) simp\n  moreover have a_le_b: \"a \\<le> b\" by (simp add: a_def b_def)\n  ultimately have \"\\<exists>x\\<ge>a. x \\<le> b \\<and> f x = y\" using cont by (intro IVT2) auto\n  thus \"\\<exists>x. f x = y\" by blast\nqed\n\ntext \\<open>The parameter @{term \"p\"} in the Akra-Bazzi theorem always exists and is unique.\\<close>\n\ndefinition akra_bazzi_exponent :: \"real list \\<Rightarrow> real list \\<Rightarrow> real\" where\n  \"akra_bazzi_exponent as bs \\<equiv> (THE p. (\\<Sum>i<length as. as!i * bs!i powr p) = 1)\"\n\nlocale akra_bazzi_params =\n  fixes k :: nat and as bs :: \"real list\"\n  assumes length_as: \"length as = k\"\n  and     length_bs: \"length bs = k\"\n  and     k_not_0:   \"k \\<noteq> 0\"\n  and     a_ge_0:    \"a \\<in> set as \\<Longrightarrow> a \\<ge> 0\"\n  and     b_bounds:  \"b \\<in> set bs \\<Longrightarrow> b \\<in> {0<..<1}\"\nbegin\n\nabbreviation p :: real where \"p \\<equiv> akra_bazzi_exponent as bs\"\n\nlemma p_def: \"p = (THE p. (\\<Sum>i<k. as!i * bs!i powr p) = 1)\"\n  by (simp add: akra_bazzi_exponent_def length_as)\n\nlemma b_pos: \"b \\<in> set bs \\<Longrightarrow> b > 0\" and b_less_1: \"b \\<in> set bs \\<Longrightarrow> b < 1\"\n  using b_bounds by simp_all\n\nlemma as_nonempty [simp]: \"as \\<noteq> []\" and bs_nonempty [simp]: \"bs \\<noteq> []\"\n  using length_as length_bs k_not_0 by auto\n\nlemma a_in_as[intro, simp]: \"i < k \\<Longrightarrow> as ! i \\<in> set as\"\n  by (rule nth_mem) (simp add: length_as)\n\nlemma b_in_bs[intro, simp]: \"i < k \\<Longrightarrow> bs ! i \\<in> set bs\"\n  by (rule nth_mem) (simp add: length_bs)\n\nend\n\n\nlocale akra_bazzi_params_nonzero =\n  fixes k :: nat and as bs :: \"real list\"\n  assumes length_as: \"length as = k\"\n  and     length_bs: \"length bs = k\"\n  and     a_ge_0:    \"a \\<in> set as \\<Longrightarrow> a \\<ge> 0\"\n  and     ex_a_pos:  \"\\<exists>a\\<in>set as. a > 0\"\n  and     b_bounds:  \"b \\<in> set bs \\<Longrightarrow> b \\<in> {0<..<1}\"\nbegin\n\nsublocale akra_bazzi_params k as bs\n by unfold_locales (insert length_as length_bs a_ge_0 ex_a_pos b_bounds, auto)\n\nlemma akra_bazzi_p_strict_mono:\n  assumes \"x < y\"\n  shows \"(\\<Sum>i<k. as!i * bs!i powr y) < (\\<Sum>i<k. as!i * bs!i powr x)\"\nproof (intro sum_strict_mono_ex1 ballI)\n  from ex_a_pos obtain a where \"a \\<in> set as\" \"a > 0\" by blast\n  then obtain i where \"i < k\" \"as!i > 0\" by (force simp: in_set_conv_nth length_as)\n  with b_bounds \\<open>x < y\\<close> have \"as!i * bs!i powr y < as!i * bs!i powr x\"\n    by (intro mult_strict_left_mono powr_less_mono') auto\n  with \\<open>i < k\\<close> show \"\\<exists>i\\<in>{..<k}. as!i * bs!i powr y < as!i * bs!i powr x\" by blast\nnext\n  fix i assume \"i \\<in> {..<k}\"\n  with a_ge_0 b_bounds[of \"bs!i\"] \\<open>x < y\\<close> show \"as!i * bs!i powr y \\<le> as!i * bs!i powr x\"\n    by (intro mult_left_mono powr_mono') simp_all\nqed simp_all\n\nlemma akra_bazzi_p_mono:\n  assumes \"x \\<le> y\"\n  shows \"(\\<Sum>i<k. as!i * bs!i powr y) \\<le> (\\<Sum>i<k. as!i * bs!i powr x)\"\napply (cases \"x < y\")\nusing akra_bazzi_p_strict_mono[of x y] assms apply simp_all\ndone\n\n\nlemma akra_bazzi_p_unique:\n  \"\\<exists>!p. (\\<Sum>i<k. as!i * bs!i powr p) = 1\"\nproof (rule strict_mono_imp_ex1_real)\n  from as_nonempty have [simp]: \"k > 0\" by (auto simp: length_as[symmetric])\n  have [simp]: \"\\<And>i. i < k \\<Longrightarrow> as!i \\<ge> 0\" by (rule a_ge_0) simp\n  from ex_a_pos obtain a where \"a \\<in> set as\" \"a > 0\" by blast\n  then obtain i where i: \"i < k\" \"as!i > 0\" by (force simp: in_set_conv_nth length_as)\n\n  hence \"LIM p at_bot. as!i * bs!i powr p :> at_top\" using b_bounds i\n    by (intro filterlim_tendsto_pos_mult_at_top[OF tendsto_const] real_powr_at_bot_neg) simp_all\n  moreover have \"\\<forall>p. as!i*bs!i powr p \\<le> (\\<Sum>i\\<in>{..<k}. as ! i * bs ! i powr p)\"\n  proof\n    fix p :: real\n    from a_ge_0 b_bounds have \"(\\<Sum>i\\<in>{..<k}-{i}. as ! i * bs ! i powr p) \\<ge> 0\"\n      by (intro sum_nonneg mult_nonneg_nonneg) simp_all\n    also have \"as!i * bs!i powr p + ... = (\\<Sum>i\\<in>insert i {..<k}. as ! i * bs ! i powr p)\"\n      by (simp add: sum.insert_remove)\n    also from i have \"insert i {..<k} = {..<k}\" by blast\n    finally show \"as!i*bs!i powr p \\<le> (\\<Sum>i\\<in>{..<k}. as ! i * bs ! i powr p)\" by simp\n  qed\n  ultimately show \"LIM p at_bot. \\<Sum>i<k. as ! i * bs ! i powr p :> at_top\"\n    by (rule filterlim_at_top_mono[OF _ always_eventually])\nnext\n  from b_bounds show \"((\\<lambda>x. \\<Sum>i<k. as ! i * bs ! i powr x) \\<longlongrightarrow> (\\<Sum>i<k. 0)) at_top\"\n    by (intro tendsto_sum tendsto_mult_right_zero real_powr_at_top_neg) simp_all\nnext\n  fix x\n  from b_bounds have A: \"\\<And>i. i < k \\<Longrightarrow> bs ! i > 0\" by simp\n  show \"isCont (\\<lambda>x. \\<Sum>i<k. as ! i * bs ! i powr x) x\"\n    using b_bounds[OF nth_mem] by (intro continuous_intros) (auto dest: A)\nqed (simp_all add: akra_bazzi_p_strict_mono)\n\nlemma p_props:  \"(\\<Sum>i<k. as!i * bs!i powr p) = 1\"\n  and p_unique: \"(\\<Sum>i<k. as!i * bs!i powr p') = 1 \\<Longrightarrow> p = p'\"\nproof-\n  from theI'[OF akra_bazzi_p_unique] the1_equality[OF akra_bazzi_p_unique]\n    show \"(\\<Sum>i<k. as!i * bs!i powr p) = 1\" \"(\\<Sum>i<k. as!i * bs!i powr p') = 1 \\<Longrightarrow> p = p'\"\n    unfolding p_def by - blast+\nqed\n\nlemma p_greaterI: \"1 < (\\<Sum>i<k. as!i * bs!i powr p') \\<Longrightarrow> p' < p\"\n  by (rule disjE[OF le_less_linear, of p p'], drule akra_bazzi_p_mono, subst (asm) p_props, simp_all)\n\nlemma p_lessI: \"1 > (\\<Sum>i<k. as!i * bs!i powr p') \\<Longrightarrow> p' > p\"\n  by (rule disjE[OF le_less_linear, of p' p], drule akra_bazzi_p_mono, subst (asm) p_props, simp_all)\n\nlemma p_geI: \"1 \\<le> (\\<Sum>i<k. as!i * bs!i powr p') \\<Longrightarrow> p' \\<le> p\"\n  by (rule disjE[OF le_less_linear, of p' p], simp, drule akra_bazzi_p_strict_mono,\n      subst (asm) p_props, simp_all)\n\nlemma p_leI: \"1 \\<ge> (\\<Sum>i<k. as!i * bs!i powr p') \\<Longrightarrow> p' \\<ge> p\"\n  by (rule disjE[OF le_less_linear, of p p'], simp, drule akra_bazzi_p_strict_mono,\n      subst (asm) p_props, simp_all)\n\nlemma p_boundsI: \"(\\<Sum>i<k. as!i * bs!i powr x) \\<le> 1 \\<and> (\\<Sum>i<k. as!i * bs!i powr y) \\<ge> 1 \\<Longrightarrow> p \\<in> {y..x}\"\n  by (elim conjE, drule p_leI, drule p_geI, simp)\n\nlemma p_boundsI': \"(\\<Sum>i<k. as!i * bs!i powr x) < 1 \\<and> (\\<Sum>i<k. as!i * bs!i powr y) > 1 \\<Longrightarrow> p \\<in> {y<..<x}\"\n  by (elim conjE, drule p_lessI, drule p_greaterI, simp)\n\nlemma p_nonneg: \"sum_list as \\<ge> 1 \\<Longrightarrow> p \\<ge> 0\"\nproof (rule p_geI)\n  assume \"sum_list as \\<ge> 1\"\n  also have \"... = (\\<Sum>i<k. as!i)\" by (simp add: sum_list_sum_nth length_as atLeast0LessThan)\n  also {\n    fix i assume \"i < k\"\n    with b_bounds have \"bs!i > 0\" by simp\n    hence \"as!i * bs!i powr 0 = as!i\" by simp\n  }\n  hence \"(\\<Sum>i<k. as!i) = (\\<Sum>i<k. as!i * bs!i powr 0)\" by (intro sum.cong) simp_all\n  finally show \"1 \\<le> (\\<Sum>i<k. as ! i * bs ! i powr 0)\" .\nqed\n\nend\n\n\nlocale akra_bazzi_real_recursion =\n  fixes as bs :: \"real list\" and hs :: \"(real \\<Rightarrow> real) list\" and k :: nat and x\\<^sub>0 x\\<^sub>1 hb e p :: real\n  assumes length_as: \"length as = k\"\n  and     length_bs: \"length bs = k\"\n  and     length_hs: \"length hs = k\"\n  and     k_not_0:   \"k \\<noteq> 0\"\n  and     a_ge_0:    \"a \\<in> set as \\<Longrightarrow> a \\<ge> 0\"\n  and     b_bounds:  \"b \\<in> set bs \\<Longrightarrow> b \\<in> {0<..<1}\"\n\n  (* The recursively-defined function *)\n  and     x0_ge_1:      \"x\\<^sub>0 \\<ge> 1\"\n  and     x0_le_x1:     \"x\\<^sub>0 \\<le> x\\<^sub>1\"\n  and     x1_ge:        \"b \\<in> set bs \\<Longrightarrow> x\\<^sub>1 \\<ge> 2 * x\\<^sub>0 * inverse b\"\n  (* Bounds on the variation functions *)\n  and     e_pos:        \"e > 0\"\n  and     h_bounds:     \"x \\<ge> x\\<^sub>1 \\<Longrightarrow> h \\<in> set hs \\<Longrightarrow> \\<bar>h x\\<bar> \\<le> hb * x / ln x powr (1 + e)\"\n  (* Asymptotic inequalities *)\n  and     asymptotics:  \"x \\<ge> x\\<^sub>0 \\<Longrightarrow> b \\<in> set bs \\<Longrightarrow> akra_bazzi_asymptotics b hb e p x\"\nbegin\n\nsublocale akra_bazzi_params k as bs\n  using length_as length_bs k_not_0 a_ge_0 b_bounds by unfold_locales\n\nlemma h_in_hs[intro, simp]: \"i < k \\<Longrightarrow> hs ! i \\<in> set hs\"\n  by (rule nth_mem) (simp add: length_hs)\n\nlemma x1_gt_1: \"x\\<^sub>1 > 1\"\nproof-\n  from bs_nonempty obtain b where \"b \\<in> set bs\" by (cases bs) auto\n  from b_pos[OF this] b_less_1[OF this] x0_ge_1 have \"1 < 2 * x\\<^sub>0 * inverse b\"\n    by (simp add: field_simps)\n  also from x1_ge and \\<open>b \\<in> set bs\\<close> have \"... \\<le> x\\<^sub>1\" by simp\n  finally show ?thesis .\nqed\n\nlemma x1_ge_1: \"x\\<^sub>1 \\<ge> 1\" using x1_gt_1 by simp\n\nlemma x1_pos: \"x\\<^sub>1 > 0\" using x1_ge_1 by simp\n\nlemma bx_le_x: \"x \\<ge> 0 \\<Longrightarrow> b \\<in> set bs \\<Longrightarrow>  b * x \\<le> x\"\n  using b_pos[of b] b_less_1[of b] by (intro mult_left_le_one_le) (simp_all)\n\nlemma x0_pos: \"x\\<^sub>0 > 0\" using x0_ge_1 by simp\n\nlemma\n  assumes \"x \\<ge> x\\<^sub>0\" \"b \\<in> set bs\"\n  shows x0_hb_bound0: \"hb / ln x powr (1 + e) < b/2\"\n  and   x0_hb_bound1: \"hb / ln x powr (1 + e) < (1 - b) / 2\"\n  and   x0_hb_bound2: \"x*(1 - b - hb / ln x powr (1 + e)) > 1\"\nusing asymptotics[OF assms] unfolding akra_bazzi_asymptotic_defs by blast+\n\nlemma step_diff:\n  assumes \"i < k\" \"x \\<ge> x\\<^sub>1\"\n  shows   \"bs ! i * x + (hs ! i) x + 1 < x\"\nproof-\n  have \"bs ! i * x + (hs ! i) x + 1 \\<le> bs ! i * x + \\<bar>(hs ! i) x\\<bar> + 1\" by simp\n  also from assms have \"\\<bar>(hs ! i) x\\<bar> \\<le> hb * x / ln x powr (1 + e)\" by (simp add: h_bounds)\n  also from assms x0_le_x1 have \"x*(1 - bs ! i - hb / ln x powr (1 + e)) > 1\"\n    by (simp add: x0_hb_bound2)\n  hence \"bs ! i * x + hb * x / ln x powr (1 + e) + 1 < x\" by (simp add: algebra_simps)\n  finally show ?thesis by simp\nqed\n\nlemma step_le_x: \"i < k \\<Longrightarrow> x \\<ge> x\\<^sub>1 \\<Longrightarrow> bs ! i * x + (hs ! i) x \\<le> x\"\n  by (drule (1) step_diff) simp\n\nlemma x0_hb_bound0': \"\\<And>x b. x \\<ge> x\\<^sub>0 \\<Longrightarrow> b \\<in> set bs \\<Longrightarrow> hb / ln x powr (1 + e) < b\"\n  by (drule (1) x0_hb_bound0, erule less_le_trans) (simp add: b_pos)\n\nlemma step_pos:\n  assumes \"i < k\" \"x \\<ge> x\\<^sub>1\"\n  shows   \"bs ! i * x + (hs ! i) x > 0\"\nproof-\n  from assms x0_le_x1 have \"hb / ln x powr (1 + e) < bs ! i\" by (simp add: x0_hb_bound0')\n  with assms x0_pos x0_le_x1 have \"x * 0 < x * (bs ! i - hb / ln x powr (1 + e))\" by simp\n  also have \"... = bs ! i * x - hb * x / ln x powr (1 + e)\"\n    by (simp add: algebra_simps)\n  also from assms have \"-hb * x / ln x powr (1 + e) \\<le> -\\<bar>(hs ! i) x\\<bar>\" by (simp add: h_bounds)\n  hence \"bs ! i * x - hb * x / ln x powr (1 + e) \\<le> bs ! i * x + -\\<bar>(hs ! i) x\\<bar>\" by simp\n  also have \"-\\<bar>(hs ! i) x\\<bar> \\<le> (hs ! i) x\" by simp\n  finally show \"bs ! i * x + (hs ! i) x > 0\" by simp\nqed\n\nlemma step_nonneg: \"i < k \\<Longrightarrow> x \\<ge> x\\<^sub>1 \\<Longrightarrow> bs ! i * x + (hs ! i) x \\<ge> 0\"\n  by (drule (1) step_pos) simp\n\nlemma step_nonneg': \"i < k \\<Longrightarrow> x \\<ge> x\\<^sub>1 \\<Longrightarrow> bs ! i + (hs ! i) x / x \\<ge> 0\"\n  by (frule (1) step_nonneg, insert x0_pos x0_le_x1) (simp_all add: field_simps)\n\nlemma hb_nonneg: \"hb \\<ge> 0\"\nproof-\n  from k_not_0 and length_hs have \"hs \\<noteq> []\" by auto\n  then obtain h where h: \"h \\<in> set hs\" by (cases hs) auto\n  have \"0 \\<le> \\<bar>h x\\<^sub>1\\<bar>\" by simp\n  also from h have \"\\<bar>h x\\<^sub>1\\<bar> \\<le> hb * x\\<^sub>1 / ln x\\<^sub>1 powr (1+e)\" by (intro h_bounds) simp_all\n  finally have \"0 \\<le> hb * x\\<^sub>1 / ln x\\<^sub>1 powr (1 + e)\" .\n  hence \"0 \\<le> ... * (ln x\\<^sub>1 powr (1 + e) / x\\<^sub>1)\"\n    by (rule mult_nonneg_nonneg) (intro divide_nonneg_nonneg, insert x1_pos, simp_all)\n  also have \"... = hb\" using x1_gt_1 by (simp add: field_simps)\n  finally show ?thesis .\nqed\n\nlemma x0_hb_bound3:\n  assumes \"x \\<ge> x\\<^sub>1\" \"i < k\"\n  shows   \"x - (bs ! i * x + (hs ! i) x) \\<le> x\"\nproof-\n  have \"-(hs ! i) x \\<le> \\<bar>(hs ! i) x\\<bar>\" by simp\n  also from assms have \"... \\<le> hb * x / ln x powr (1 + e)\" by (simp add: h_bounds)\n  also have \"... = x * (hb / ln x powr (1 + e))\" by simp\n  also from assms x0_pos x0_le_x1 have \"... < x * bs ! i\"\n    by (intro mult_strict_left_mono x0_hb_bound0') simp_all\n  finally show ?thesis by (simp add: algebra_simps)\nqed\n\nlemma x0_hb_bound4:\n  assumes \"x \\<ge> x\\<^sub>1\" \"i < k\"\n  shows   \"(bs ! i + (hs ! i) x / x) > bs ! i / 2\"\nproof-\n  from assms x0_le_x1 have \"hb / ln x powr (1 + e) < bs ! i / 2\" by (intro x0_hb_bound0) simp_all\n  with assms x0_pos x0_le_x1 have \"(-bs ! i / 2) * x < (-hb / ln x powr (1 + e)) * x\"\n    by (intro mult_strict_right_mono) simp_all\n  also from assms x0_pos have \"... \\<le> -\\<bar>(hs ! i) x\\<bar>\" using h_bounds by simp\n  also have \"... \\<le> (hs ! i) x\" by simp\n  finally show ?thesis using assms x1_pos by (simp add: field_simps)\nqed\n\nlemma x0_hb_bound4': \"x \\<ge> x\\<^sub>1 \\<Longrightarrow> i < k \\<Longrightarrow> (bs ! i + (hs ! i) x / x) \\<ge> bs ! i / 2\"\n  by (drule (1) x0_hb_bound4) simp\n\nlemma x0_hb_bound5:\n  assumes \"x \\<ge> x\\<^sub>1\" \"i < k\"\n  shows   \"(bs ! i + (hs ! i) x / x) \\<le> bs ! i * 3/2\"\nproof-\n  have \"(hs ! i) x \\<le> \\<bar>(hs ! i) x\\<bar>\" by simp\n  also from assms have \"... \\<le> hb * x / ln x powr (1 + e)\" by (simp add: h_bounds)\n  also have \"... = x * (hb / ln x powr (1 + e))\" by simp\n  also from assms x0_pos x0_le_x1 have \"... < x * (bs ! i / 2)\"\n    by (intro mult_strict_left_mono x0_hb_bound0) simp_all\n  finally show ?thesis using assms x1_pos by (simp add: field_simps)\nqed\n\nlemma x0_hb_bound6:\n  assumes \"x \\<ge> x\\<^sub>1\" \"i < k\"\n  shows   \"x * ((1 - bs ! i) / 2) \\<le> x - (bs ! i * x + (hs ! i) x)\"\nproof-\n  from assms x0_le_x1 have \"hb / ln x powr (1 + e) < (1 - bs ! i) / 2\" using x0_hb_bound1 by simp\n  with assms x1_pos have \"x * ((1 - bs ! i) / 2) \\<le> x * (1 - (bs ! i + hb / ln x powr (1 + e)))\"\n    by (intro mult_left_mono) (simp_all add: field_simps)\n  also have \"... = x - bs ! i * x + -hb * x / ln x powr (1 + e)\" by (simp add: algebra_simps)\n  also from h_bounds assms have \"-hb * x / ln x powr (1 + e) \\<le> -\\<bar>(hs ! i) x\\<bar>\"\n    by (simp add: length_hs)\n  also have \"... \\<le> -(hs ! i) x\" by simp\n  finally show ?thesis by (simp add: algebra_simps)\nqed\n\nlemma x0_hb_bound7:\n  assumes \"x \\<ge> x\\<^sub>1\" \"i < k\"\n  shows   \"bs!i*x + (hs!i) x > x\\<^sub>0\"\nproof-\n  from assms x0_le_x1 have x': \"x \\<ge> x\\<^sub>0\" by simp\n  from x1_ge assms have \"2 * x\\<^sub>0 * inverse (bs!i) \\<le> x\\<^sub>1\" by simp\n  with assms b_pos have \"x\\<^sub>0 \\<le> x\\<^sub>1 * (bs!i / 2)\" by (simp add: field_simps)\n  also from assms x' have \"bs!i/2 < bs!i + (hs!i) x / x\" by (intro x0_hb_bound4)\n  also from assms step_nonneg' x' have \"x\\<^sub>1 * ... \\<le> x * ...\" by (intro mult_right_mono) (simp_all)\n  also from assms x1_pos have \"x * (bs!i + (hs!i) x / x) = bs!i*x + (hs!i) x\"\n    by (simp add: field_simps)\n  finally show ?thesis using x1_pos by simp\nqed\n\nlemma x0_hb_bound7': \"x \\<ge> x\\<^sub>1 \\<Longrightarrow> i < k \\<Longrightarrow> bs!i*x + (hs!i) x > 1\"\n  by (rule le_less_trans[OF _ x0_hb_bound7]) (insert x0_le_x1 x0_ge_1, simp_all)\n\nlemma x0_hb_bound8:\n  assumes \"x \\<ge> x\\<^sub>1\" \"i < k\"\n  shows   \"bs!i*x - hb * x / ln x powr (1+e) > x\\<^sub>0\"\nproof-\n  from assms have \"2 * x\\<^sub>0 * inverse (bs!i) \\<le> x\\<^sub>1\" by (intro x1_ge) simp_all\n  with b_pos assms have \"x\\<^sub>0 \\<le> x\\<^sub>1 * (bs!i/2)\" by (simp add: field_simps)\n  also from assms b_pos have \"... \\<le> x * (bs!i/2)\" by simp\n  also from assms x0_le_x1 have \"hb / ln x powr (1+e) < bs!i/2\" by (intro x0_hb_bound0) simp_all\n  with assms have \"bs!i/2 < bs!i - hb / ln x powr (1+e)\" by (simp add: field_simps)\n  also have \"x * ... = bs!i*x - hb * x / ln x powr (1+e)\" by (simp add: algebra_simps)\n  finally show ?thesis using assms x1_pos by (simp add: field_simps)\nqed\n\nlemma x0_hb_bound8':\n  assumes \"x \\<ge> x\\<^sub>1\" \"i < k\"\n  shows   \"bs!i*x + hb * x / ln x powr (1+e) > x\\<^sub>0\"\nproof-\n  from assms have \"x\\<^sub>0 < bs!i*x - hb * x / ln x powr (1+e)\" by (rule x0_hb_bound8)\n  also from assms hb_nonneg x1_pos have \"hb * x / ln x powr (1+e) \\<ge> 0\"\n    by (intro mult_nonneg_nonneg divide_nonneg_nonneg) simp_all\n  hence \"bs!i*x - hb * x / ln x powr (1+e) \\<le> bs!i*x + hb * x / ln x powr (1+e)\" by simp\n  finally show ?thesis .\nqed\n\nlemma\n  assumes \"x \\<ge> x\\<^sub>0\"\n  shows   asymptotics1: \"i < k \\<Longrightarrow> 1 + ln x powr (- e / 2) \\<le>\n             (1 - hb * inverse (bs!i) * ln x powr -(1+e)) powr p *\n             (1 + ln (bs!i*x + hb*x/ln x powr (1+e)) powr (-e/2))\"\n  and     asymptotics2: \"i < k \\<Longrightarrow> 1 - ln x powr (- e / 2) \\<ge>\n             (1 + hb * inverse (bs!i) * ln x powr -(1+e)) powr p *\n             (1 - ln (bs!i*x + hb*x/ln x powr (1+e)) powr (-e/2))\"\n  and     asymptotics1': \"i < k \\<Longrightarrow> 1 + ln x powr (- e / 2) \\<le>\n             (1 + hb * inverse (bs!i) * ln x powr -(1+e)) powr p *\n             (1 + ln (bs!i*x + hb*x/ln x powr (1+e)) powr (-e/2))\"\n  and     asymptotics2': \"i < k \\<Longrightarrow> 1 - ln x powr (- e / 2) \\<ge>\n             (1 - hb * inverse (bs!i) * ln x powr -(1+e)) powr p *\n             (1 - ln (bs!i*x + hb*x/ln x powr (1+e)) powr (-e/2))\"\n  and     asymptotics3: \"(1 + ln x powr (- e / 2)) / 2 \\<le> 1\"\n  and     asymptotics4: \"(1 - ln x powr (- e / 2)) * 2 \\<ge> 1\"\n  and     asymptotics5: \"i < k \\<Longrightarrow> ln (bs!i*x - hb*x*ln x powr -(1+e)) powr (-e/2) < 1\"\napply -\nusing assms asymptotics[of x \"bs!i\"] unfolding akra_bazzi_asymptotic_defs\napply simp_all[4]\nusing assms asymptotics[of x \"bs!0\"] unfolding akra_bazzi_asymptotic_defs\napply simp_all[2]\nusing assms asymptotics[of x \"bs!i\"] unfolding akra_bazzi_asymptotic_defs\napply simp_all\ndone\n\n\nlemma x0_hb_bound9:\n  assumes \"x \\<ge> x\\<^sub>1\" \"i < k\"\n  shows   \"ln (bs!i*x + (hs!i) x) powr -(e/2) < 1\"\nproof-\n  from b_pos assms have \"0 < bs!i/2\" by simp\n  also from assms x0_le_x1 have \"... < bs!i + (hs!i) x / x\" by (intro x0_hb_bound4) simp_all\n  also from assms x1_pos have \"x * ... = bs!i*x + (hs!i) x\" by (simp add: field_simps)\n  finally have pos: \"bs!i*x + (hs!i) x > 0\" using assms x1_pos by simp\n  from x0_hb_bound8[OF assms] x0_ge_1 have pos': \"bs!i*x - hb * x / ln x powr (1+e) > 1\" by simp\n\n  from assms have \"-(hb * x / ln x powr (1+e)) \\<le> -\\<bar>(hs!i) x\\<bar>\"\n    by (intro le_imp_neg_le h_bounds) simp_all\n  also have \"... \\<le> (hs!i) x\" by simp\n  finally have \"ln (bs!i*x - hb * x / ln x powr (1+e)) \\<le> ln (bs!i*x + (hs!i) x)\"\n    using assms b_pos x0_pos pos' by (intro ln_mono mult_pos_pos pos) simp_all\n  hence \"ln (bs!i*x + (hs!i) x) powr -(e/2) \\<le> ln (bs!i*x - hb * x / ln x powr (1+e)) powr -(e/2)\"\n    using assms e_pos asymptotics5[of x] pos' by (intro powr_mono2' ln_gt_zero) simp_all\n  also have \"... < 1\" using asymptotics5[of x i] assms x0_le_x1\n    by (subst (asm) powr_minus) (simp_all add: field_simps)\n  finally show ?thesis .\nqed\n\n\ndefinition akra_bazzi_measure :: \"real \\<Rightarrow> nat\" where\n  \"akra_bazzi_measure x = nat \\<lceil>x\\<rceil>\"\n\nlemma akra_bazzi_measure_decreases:\n  assumes \"x \\<ge> x\\<^sub>1\" \"i < k\"\n  shows   \"akra_bazzi_measure (bs!i*x + (hs!i) x) < akra_bazzi_measure x\"\nproof-\n  from step_diff assms have \"(bs!i * x + (hs!i) x) + 1 < x\" by (simp add: algebra_simps)\n  hence \"\\<lceil>(bs!i * x + (hs!i) x) + 1\\<rceil> \\<le> \\<lceil>x\\<rceil>\" by (intro ceiling_mono) simp\n  hence \"\\<lceil>(bs!i * x + (hs!i) x)\\<rceil> < \\<lceil>x\\<rceil>\" by simp\n  with assms x1_pos have \"nat \\<lceil>(bs!i * x + (hs!i) x)\\<rceil> < nat \\<lceil>x\\<rceil>\" by (subst nat_mono_iff) simp_all\n  thus ?thesis unfolding akra_bazzi_measure_def .\nqed\n\n\nlemma akra_bazzi_induct[consumes 1, case_names base rec]:\n  assumes \"x \\<ge> x\\<^sub>0\"\n  assumes base: \"\\<And>x. x \\<ge> x\\<^sub>0 \\<Longrightarrow> x \\<le> x\\<^sub>1 \\<Longrightarrow> P x\"\n  assumes rec:  \"\\<And>x. x > x\\<^sub>1 \\<Longrightarrow> (\\<And>i. i < k \\<Longrightarrow> P (bs!i*x + (hs!i) x)) \\<Longrightarrow> P x\"\n  shows   \"P x\"\nproof (insert \\<open>x \\<ge> x\\<^sub>0\\<close>, induction \"akra_bazzi_measure x\" arbitrary: x rule: less_induct)\n  case less\n  show ?case\n  proof (cases \"x \\<le> x\\<^sub>1\")\n    case True\n    with base and \\<open>x \\<ge> x\\<^sub>0\\<close> show ?thesis .\n  next\n    case False\n    hence x: \"x > x\\<^sub>1\" by simp\n    thus ?thesis\n    proof (rule rec)\n      fix i assume i: \"i < k\"\n      from x0_hb_bound7[OF _ i, of x] x have \"bs!i*x + (hs!i) x \\<ge> x\\<^sub>0\" by simp\n      with i x show \"P (bs ! i * x + (hs ! i) x)\"\n        by (intro less akra_bazzi_measure_decreases) simp_all\n    qed\n  qed\nqed\n\nend\n\n\nlocale akra_bazzi_real = akra_bazzi_real_recursion +\n  fixes integrable integral\n  assumes integral: \"akra_bazzi_integral integrable integral\"\n  fixes f :: \"real \\<Rightarrow> real\"\n  and   g :: \"real \\<Rightarrow> real\"\n  and   C :: real\n  assumes p_props:      \"(\\<Sum>i<k. as!i * bs!i powr p) = 1\"\n  and     f_base:       \"x \\<ge> x\\<^sub>0 \\<Longrightarrow> x \\<le> x\\<^sub>1 \\<Longrightarrow> f x \\<ge> 0\"\n  and     f_rec:        \"x > x\\<^sub>1 \\<Longrightarrow> f x = g x + (\\<Sum>i<k. as!i * f (bs!i * x + (hs!i) x))\"\n  and     g_nonneg:     \"x \\<ge> x\\<^sub>0 \\<Longrightarrow> g x \\<ge> 0\"\n  and     C_bound:      \"b \\<in> set bs \\<Longrightarrow> x \\<ge> x\\<^sub>1 \\<Longrightarrow> C*x \\<le> b*x - hb*x/ln x powr (1+e)\"\n  and     g_integrable: \"x \\<ge> x\\<^sub>0 \\<Longrightarrow> integrable (\\<lambda>u. g u / u powr (p + 1)) x\\<^sub>0 x\"\nbegin\n\ninterpretation akra_bazzi_integral integrable integral by (rule integral)\n\nlemma akra_bazzi_integrable:\n  \"a \\<ge> x\\<^sub>0 \\<Longrightarrow> a \\<le> b \\<Longrightarrow> integrable (\\<lambda>x. g x / x powr (p + 1)) a b\"\n  by (rule integrable_subinterval[OF g_integrable, of b]) simp_all\n\ndefinition g_approx :: \"nat \\<Rightarrow> real \\<Rightarrow> real\" where\n  \"g_approx i x = x powr p * integral (\\<lambda>u. g u / u powr (p + 1)) (bs!i * x + (hs!i) x) x\"\n\nlemma f_nonneg: \"x \\<ge> x\\<^sub>0 \\<Longrightarrow> f x \\<ge> 0\"\nproof (induction x rule: akra_bazzi_induct)\n  case (base x)\n  with f_base[of x] show ?case by simp\nnext\n  case (rec x)\n  with x0_le_x1 have \"g x \\<ge> 0\" by (intro g_nonneg) simp_all\n  moreover {\n    fix i assume i: \"i < k\"\n    with rec.IH have \"f (bs!i*x + (hs!i) x) \\<ge> 0\" by simp\n    with i have \"as!i * f (bs!i*x + (hs!i) x) \\<ge> 0\"\n        by (intro mult_nonneg_nonneg[OF a_ge_0]) simp_all\n  }\n  hence \"(\\<Sum>i<k. as!i * f (bs!i*x + (hs!i) x)) \\<ge> 0\" by (intro sum_nonneg) blast\n  ultimately show \"f x \\<ge> 0\" using rec.hyps by (subst f_rec) simp_all\nqed\n\n\ndefinition f_approx :: \"real \\<Rightarrow> real\" where\n  \"f_approx x = x powr p * (1 + integral (\\<lambda>u. g u / u powr (p + 1)) x\\<^sub>0 x)\"\n\nlemma f_approx_aux:\n  assumes \"x \\<ge> x\\<^sub>0\"\n  shows   \"1 + integral (\\<lambda>u. g u / u powr (p + 1)) x\\<^sub>0 x \\<ge> 1\"\nproof-\n  from assms have \"integral (\\<lambda>u. g u / u powr (p + 1)) x\\<^sub>0 x \\<ge> 0\"\n    by (intro integral_nonneg ballI g_nonneg divide_nonneg_nonneg g_integrable) simp_all\n  thus ?thesis by simp\nqed\n\nlemma f_approx_pos: \"x \\<ge> x\\<^sub>0 \\<Longrightarrow> f_approx x > 0\"\n  unfolding f_approx_def by (intro mult_pos_pos, insert x0_pos, simp, drule f_approx_aux, simp)\n\nlemma f_approx_nonneg: \"x \\<ge> x\\<^sub>0 \\<Longrightarrow> f_approx x \\<ge> 0\"\n  using f_approx_pos[of x] by simp\n\n\nlemma f_approx_bounded_below:\n  obtains c where \"\\<And>x. x \\<ge> x\\<^sub>0 \\<Longrightarrow> x \\<le> x\\<^sub>1 \\<Longrightarrow> f_approx x \\<ge> c\" \"c > 0\"\nproof-\n  {\n    fix x assume x: \"x \\<ge> x\\<^sub>0\" \"x \\<le> x\\<^sub>1\"\n    with x0_pos have \"x powr p \\<ge> min (x\\<^sub>0 powr p) (x\\<^sub>1 powr p)\"\n      by (intro powr_lower_bound) simp_all\n    with x have \"f_approx x \\<ge> min (x\\<^sub>0 powr p) (x\\<^sub>1 powr p) * 1\"\n      unfolding f_approx_def by (intro mult_mono f_approx_aux) simp_all\n  }\n  from this x0_pos x1_pos show ?thesis by (intro that[of \"min (x\\<^sub>0 powr p) (x\\<^sub>1 powr p)\"]) auto\nqed\n\n\nlemma asymptotics_aux:\n  assumes \"x \\<ge> x\\<^sub>1\" \"i < k\"\n  assumes \"s \\<equiv> (if p \\<ge> 0 then 1 else -1)\"\n  shows \"(bs!i*x - s*hb*x*ln x powr -(1+e)) powr p \\<le> (bs!i*x + (hs!i) x) powr p\" (is \"?thesis1\")\n  and   \"(bs!i*x + (hs!i) x) powr p \\<le> (bs!i*x + s*hb*x*ln x powr -(1+e)) powr p\" (is \"?thesis2\")\nproof-\n  from assms x1_gt_1 have ln_x_pos: \"ln x > 0\" by simp\n  from assms x1_pos have x_pos: \"x > 0\" by simp\n  from assms x0_le_x1 have *: \"hb / ln x powr (1+e) < bs!i/2\" by (intro x0_hb_bound0) simp_all\n  with hb_nonneg ln_x_pos have \"(bs!i - hb * ln x powr -(1+e)) > 0\"\n    by (subst powr_minus) (simp_all add: field_simps)\n  with * have \"0 < x * (bs!i - hb * ln x powr -(1+e))\" using x_pos\n    by (subst (asm) powr_minus, intro mult_pos_pos)\n  hence A: \"0 < bs!i*x - hb * x * ln x powr -(1+e)\" by (simp add: algebra_simps)\n\n  from assms have \"-(hb*x*ln x powr -(1+e)) \\<le> -\\<bar>(hs!i) x\\<bar>\"\n    using h_bounds[of x \"hs!i\"] by (subst neg_le_iff_le, subst powr_minus) (simp add: field_simps)\n  also have \"... \\<le> (hs!i) x\" by simp\n  finally have B: \"bs!i*x - hb*x*ln x powr -(1+e) \\<le> bs!i*x + (hs!i) x\" by simp\n\n  have \"(hs!i) x \\<le> \\<bar>(hs!i) x\\<bar>\" by simp\n  also from assms have \"... \\<le> (hb*x*ln x powr -(1+e))\"\n     using h_bounds[of x \"hs!i\"] by (subst powr_minus) (simp_all add: field_simps)\n  finally have C: \"bs!i*x + hb*x*ln x powr -(1+e) \\<ge> bs!i*x + (hs!i) x\" by simp\n\n  from A B C show ?thesis1\n    by (cases \"p \\<ge> 0\") (auto intro: powr_mono2 powr_mono2' simp: assms(3))\n  from A B C show ?thesis2\n    by (cases \"p \\<ge> 0\") (auto intro: powr_mono2 powr_mono2' simp: assms(3))\nqed\n\nlemma asymptotics1':\n  assumes \"x \\<ge> x\\<^sub>1\" \"i < k\"\n  shows   \"(bs!i*x) powr p * (1 + ln x powr (-e/2)) \\<le>\n           (bs!i*x + (hs!i) x) powr p * (1 + ln (bs!i*x + (hs!i) x) powr (-e/2))\"\nproof-\n  from assms x0_le_x1 have x: \"x \\<ge> x\\<^sub>0\" by simp\n  from b_pos[of \"bs!i\"] assms have b_pos: \"bs!i > 0\" \"bs!i \\<noteq> 0\" by simp_all\n  from b_less_1[of \"bs!i\"] assms have b_less_1: \"bs!i < 1\" by simp\n  from x1_gt_1 assms have ln_x_pos: \"ln x > 0\" by simp\n  have mono: \"\\<And>a b. a \\<le> b \\<Longrightarrow> (bs!i*x) powr p * a \\<le> (bs!i*x) powr p * b\"\n    by (rule mult_left_mono) simp_all\n\n  define s :: real where [abs_def]: \"s = (if p \\<ge> 0 then 1 else -1)\"\n  have \"1 + ln x powr (-e/2) \\<le>\n          (1 - s*hb*inverse(bs!i)*ln x powr -(1+e)) powr p *\n          (1 + ln (bs!i*x + hb * x / ln x powr (1+e)) powr (-e/2))\" (is \"_ \\<le> ?A * ?B\")\n    using assms x unfolding s_def using asymptotics1[OF x assms(2)] asymptotics1'[OF x assms(2)]\n    by simp\n  also have \"(bs!i*x) powr p * ... = (bs!i*x) powr p * ?A * ?B\" by simp\n  also from x0_hb_bound0'[OF x, of \"bs!i\"] hb_nonneg x ln_x_pos assms\n    have \"s*hb * ln x powr -(1 + e) < bs ! i\"\n    by (subst powr_minus) (simp_all add: field_simps s_def)\n  hence \"(bs!i*x) powr p * ?A = (bs!i*x*(1 - s*hb*inverse (bs!i)*ln x powr -(1+e))) powr p\"\n    using b_pos assms x x0_pos b_less_1 ln_x_pos\n    by (subst powr_mult[symmetric]) (simp_all add: s_def field_simps)\n  also have \"bs!i*x*(1 - s*hb*inverse (bs!i)*ln x powr -(1+e)) = bs!i*x - s*hb*x*ln x powr -(1+e)\"\n    using b_pos assms by (simp add: algebra_simps)\n  also have \"?B = 1 + ln (bs!i*x + hb*x*ln x powr -(1+e)) powr (-e/2)\"\n    by (subst powr_minus) (simp add: field_simps)\n\n  also {\n    from x assms have \"(bs!i*x - s*hb*x*ln x powr -(1+e)) powr p \\<le> (bs!i*x + (hs!i) x) powr p\"\n      using asymptotics_aux(1)[OF assms(1,2) s_def] by blast\n    moreover {\n      have \"(hs!i) x \\<le> \\<bar>(hs!i) x\\<bar>\" by simp\n      also from assms have \"\\<bar>(hs!i) x\\<bar> \\<le> hb * x / ln x powr (1+e)\" by (intro h_bounds) simp_all\n      finally have \"(hs ! i) x \\<le> hb * x * ln x powr -(1 + e)\"\n        by (subst powr_minus) (simp_all add: field_simps)\n      moreover from x hb_nonneg x0_pos have \"hb * x * ln x powr -(1+e) \\<ge> 0\"\n        by (intro mult_nonneg_nonneg) simp_all\n      ultimately have \"1 + ln (bs!i*x + hb * x * ln x powr -(1+e)) powr (-e/2) \\<le>\n                       1 + ln (bs!i*x + (hs!i) x) powr (-e/2)\" using assms x e_pos b_pos x0_pos\n      by (intro add_left_mono powr_mono2' ln_mono ln_gt_zero step_pos x0_hb_bound7'\n                add_pos_nonneg mult_pos_pos) simp_all\n    }\n    ultimately have \"(bs!i*x - s*hb*x*ln x powr -(1+e)) powr p *\n                         (1 + ln (bs!i*x + hb * x * ln x powr -(1+e)) powr (-e/2))\n                     \\<le> (bs!i*x + (hs!i) x) powr p * (1 + ln (bs!i*x + (hs!i) x) powr (-e/2))\"\n      by (rule mult_mono) simp_all\n  }\n  finally show ?thesis by (simp_all add: mono)\nqed\n\nlemma asymptotics2':\n  assumes \"x \\<ge> x\\<^sub>1\" \"i < k\"\n  shows   \"(bs!i*x + (hs!i) x) powr p * (1 - ln (bs!i*x + (hs!i) x) powr (-e/2)) \\<le>\n           (bs!i*x) powr p * (1 - ln x powr (-e/2))\"\nproof-\n  define s :: real where \"s = (if p \\<ge> 0 then 1 else -1)\"\n  from assms x0_le_x1 have x: \"x \\<ge> x\\<^sub>0\" by simp\n  from assms x1_gt_1 have ln_x_pos: \"ln x > 0\" by simp\n  from b_pos[of \"bs!i\"] assms have b_pos: \"bs!i > 0\" \"bs!i \\<noteq> 0\" by simp_all\n  from b_pos hb_nonneg have pos: \"1 + s * hb * (inverse (bs!i) * ln x powr -(1+e)) > 0\"\n    using x0_hb_bound0'[OF x, of \"bs!i\"] b_pos assms ln_x_pos\n    by (subst powr_minus) (simp add: field_simps s_def)\n  have mono: \"\\<And>a b. a \\<le> b \\<Longrightarrow> (bs!i*x) powr p * a \\<le> (bs!i*x) powr p * b\"\n    by (rule mult_left_mono) simp_all\n\n  let ?A = \"(1 + s*hb*inverse(bs!i)*ln x powr -(1+e)) powr p\"\n  let ?B = \"1 - ln (bs!i*x + (hs!i) x) powr (-e/2)\"\n  let ?B' = \"1 - ln (bs!i*x + hb * x / ln x powr (1+e)) powr (-e/2)\"\n\n  from assms x have \"(bs!i*x + (hs!i) x) powr p \\<le> (bs!i*x + s*hb*x*ln x powr -(1+e)) powr p\"\n    by (intro asymptotics_aux(2)) (simp_all add: s_def)\n  moreover from x0_hb_bound9[OF assms(1,2)] have \"?B \\<ge> 0\" by (simp add: field_simps)\n  ultimately have \"(bs!i*x + (hs!i) x) powr p * ?B \\<le>\n                   (bs!i*x + s*hb*x*ln x powr -(1+e)) powr p * ?B\" by (rule mult_right_mono)\n  also from assms e_pos pos have \"?B \\<le> ?B'\"\n  proof -\n    from x0_hb_bound8'[OF assms(1,2)] x0_hb_bound8[OF assms(1,2)] x0_ge_1\n    have *: \"bs ! i * x + s*hb * x / ln x powr (1 + e) > 1\" by (simp add: s_def)\n    moreover from * have \"... > 0\" by simp\n    moreover from x0_hb_bound7[OF assms(1,2)] x0_ge_1 have \"bs ! i * x + (hs ! i) x > 1\" by simp\n    moreover {\n      have \"(hs!i) x \\<le> \\<bar>(hs!i) x\\<bar>\" by simp\n      also from assms x0_le_x1 have \"... \\<le> hb*x/ln x powr (1+e)\" by (intro h_bounds) simp_all\n      finally have \"bs!i*x + (hs!i) x \\<le> bs!i*x + hb*x/ln x powr (1+e)\" by simp\n    }\n    ultimately show \"?B \\<le> ?B'\" using assms e_pos x step_pos\n      by (intro diff_left_mono powr_mono2' ln_mono ln_gt_zero) simp_all\n  qed\n  hence \"(bs!i*x + s*hb*x*ln x powr -(1+e)) powr p * ?B \\<le>\n             (bs!i*x + s*hb*x*ln x powr -(1+e)) powr p * ?B'\" by (intro mult_left_mono) simp_all\n  also have \"bs!i*x + s*hb*x*ln x powr -(1+e) = bs!i*x*(1 + s*hb*inverse (bs!i)*ln x powr -(1+e))\"\n    using b_pos by (simp_all add: field_simps)\n  also have \"... powr p = (bs!i*x) powr p * ?A\"\n    using b_pos x x0_pos pos by (intro powr_mult) simp_all\n  also have \"(bs!i*x) powr p * ?A * ?B' = (bs!i*x) powr p * (?A * ?B')\" by simp\n  also have \"?A * ?B' \\<le> 1 - ln x powr (-e/2)\" using assms x\n    using asymptotics2[OF x assms(2)] asymptotics2'[OF x assms(2)] by (simp add: s_def)\n  finally show ?thesis by (simp_all add: mono)\nqed\n\nlemma Cx_le_step:\n  assumes \"i < k\" \"x \\<ge> x\\<^sub>1\"\n  shows   \"C*x \\<le> bs!i*x + (hs!i) x\"\nproof-\n  from assms have \"C*x \\<le> bs!i*x - hb*x/ln x powr (1+e)\" by (intro C_bound) simp_all\n  also from assms have \"-(hb*x/ln x powr (1+e)) \\<le> -\\<bar>(hs!i) x\\<bar>\"\n    by (subst neg_le_iff_le, intro h_bounds) simp_all\n  hence \"bs!i*x - hb*x/ln x powr (1+e) \\<le> bs!i*x + -\\<bar>(hs!i) x\\<bar>\" by simp\n  also have \"-\\<bar>(hs!i) x\\<bar> \\<le> (hs!i) x\" by simp\n  finally show ?thesis by simp\nqed\n\nend\n\n\nlocale akra_bazzi_nat_to_real = akra_bazzi_real_recursion +\n  fixes f :: \"nat \\<Rightarrow> real\"\n  and   g :: \"real \\<Rightarrow> real\"\n  assumes f_base: \"real x \\<ge> x\\<^sub>0 \\<Longrightarrow> real x \\<le> x\\<^sub>1 \\<Longrightarrow> f x \\<ge> 0\"\n  and     f_rec:  \"real x > x\\<^sub>1 \\<Longrightarrow>\n                          f x = g (real x) + (\\<Sum>i<k. as!i * f (nat \\<lfloor>bs!i * x + (hs!i) (real x)\\<rfloor>))\"\n  and     x0_int: \"real (nat \\<lfloor>x\\<^sub>0\\<rfloor>) = x\\<^sub>0\"\nbegin\n\nfunction f' :: \"real \\<Rightarrow> real\" where\n  \"x \\<le> x\\<^sub>1 \\<Longrightarrow> f' x = f (nat \\<lfloor>x\\<rfloor>)\"\n| \"x > x\\<^sub>1 \\<Longrightarrow> f' x = g x + (\\<Sum>i<k. as!i * f' (bs!i * x + (hs!i) x))\"\nby (force, simp_all)\ntermination by (relation \"Wellfounded.measure akra_bazzi_measure\")\n               (simp_all add: akra_bazzi_measure_decreases)\n\nlemma f'_base: \"x \\<ge> x\\<^sub>0 \\<Longrightarrow> x \\<le> x\\<^sub>1 \\<Longrightarrow> f' x \\<ge> 0\"\n  apply (subst f'.simps(1), assumption)\n  apply (rule f_base)\n  apply (rule order.trans[of _ \"real (nat \\<lfloor>x\\<^sub>0\\<rfloor>)\"], simp add: x0_int)\n  apply (subst of_nat_le_iff, intro nat_mono floor_mono, assumption)\n  using x0_pos apply linarith\n  done\n\nlemmas f'_rec = f'.simps(2)\n\nend\n\n\nlocale akra_bazzi_real_lower = akra_bazzi_real +\n  fixes fb2 gb2 c2 :: real\n  assumes f_base2:   \"x \\<ge> x\\<^sub>0 \\<Longrightarrow> x \\<le> x\\<^sub>1 \\<Longrightarrow> f x \\<ge> fb2\"\n  and     fb2_pos:   \"fb2 > 0\"\n  and     g_growth2: \"\\<forall>x\\<ge>x\\<^sub>1. \\<forall>u\\<in>{C*x..x}. c2 * g x \\<ge> g u\"\n  and     c2_pos:    \"c2 > 0\"\n  and     g_bounded: \"x \\<ge> x\\<^sub>0 \\<Longrightarrow> x \\<le> x\\<^sub>1 \\<Longrightarrow> g x \\<le> gb2\"\nbegin\n\ninterpretation akra_bazzi_integral integrable integral by (rule integral)\n\nlemma gb2_nonneg: \"gb2 \\<ge> 0\" using g_bounded[of x\\<^sub>0] x0_le_x1 x0_pos g_nonneg[of x\\<^sub>0] by simp\n\nlemma g_growth2':\n  assumes \"x \\<ge> x\\<^sub>1\" \"i < k\" \"u \\<in> {bs!i*x+(hs!i) x..x}\"\n  shows   \"c2 * g x \\<ge> g u\"\nproof-\n  from assms have \"C*x \\<le> bs!i*x+(hs!i) x\" by (intro Cx_le_step)\n  with assms have \"u \\<in> {C*x..x}\" by auto\n  with assms g_growth2 show ?thesis by simp\nqed\n\nlemma g_bounds2:\n  obtains c4 where \"\\<And>x i. x \\<ge> x\\<^sub>1 \\<Longrightarrow> i < k \\<Longrightarrow> g_approx i x \\<le> c4 * g x\" \"c4 > 0\"\nproof-\n  define c4\n    where \"c4 = Max {c2 / min 1 (min ((b/2) powr (p+1)) ((b*3/2) powr (p+1))) |b. b \\<in> set bs}\"\n\n  {\n    from bs_nonempty obtain b where b: \"b \\<in> set bs\" by (cases bs) auto\n    let ?m = \"min 1 (min ((b/2) powr (p+1)) ((b*3/2) powr (p+1)))\"\n    from b b_pos have \"?m > 0\" unfolding min_def by (auto simp: not_le)\n    with b b_pos c2_pos have \"c2 / ?m > 0\" by (simp_all add: field_simps)\n    with b have \"c4 > 0\" unfolding c4_def by (subst Max_gr_iff) (simp, simp, blast)\n  }\n\n  {\n    fix x i assume i: \"i < k\" and x: \"x \\<ge> x\\<^sub>1\"\n    have powr_negD: \"a powr b \\<le> 0 \\<Longrightarrow> a = 0\"\n      for a b :: real unfolding powr_def by (simp split: if_split_asm)\n    let ?m = \"min 1 (min ((bs!i/2) powr (p+1)) ((bs!i*3/2) powr (p+1)))\"\n    have \"min 1 ((bs!i + (hs ! i) x / x) powr (p+1)) \\<ge> min 1 (min ((bs!i/2) powr (p+1)) ((bs!i*3/2) powr (p+1)))\"\n      apply (insert x i x0_le_x1 x1_pos step_pos b_pos[OF b_in_bs[OF i]],\n             rule min.mono, simp, cases \"p + 1 \\<ge> 0\")\n      apply (rule order.trans[OF min.cobounded1 powr_mono2[OF _ _ x0_hb_bound4']], simp_all add: field_simps) []\n      apply (rule order.trans[OF min.cobounded2 powr_mono2'[OF _ _ x0_hb_bound5]], simp_all add: field_simps) []\n      done\n    with i b_pos[of \"bs!i\"] have \"c2 / min 1 ((bs!i + (hs ! i) x / x) powr (p+1)) \\<le> c2 / ?m\" using c2_pos\n      unfolding min_def by (intro divide_left_mono) (auto intro!: mult_pos_pos dest!: powr_negD)\n\n    also from i x have \"... \\<le> c4\" unfolding c4_def by (intro Max.coboundedI) auto\n    finally have \"c2 / min 1 ((bs!i + (hs ! i) x / x) powr (p+1)) \\<le> c4\" .\n  } note c4 = this\n\n  {\n    fix x :: real and i :: nat\n    assume x: \"x \\<ge> x\\<^sub>1\" and i: \"i < k\"\n    from x x1_pos have x_pos: \"x > 0\" by simp\n    let ?x' = \"bs ! i * x + (hs ! i) x\"\n    let ?x'' = \"bs ! i + (hs ! i) x / x\"\n    from x x1_ge_1 i g_growth2' x0_le_x1 c2_pos\n      have c2: \"c2 > 0\" \"\\<forall>u\\<in>{?x'..x}. g u \\<le> c2 * g x\" by auto\n\n    from x0_le_x1 x i have x'_le_x: \"?x' \\<le> x\" by (intro step_le_x) simp_all\n    let ?m = \"min (?x' powr (p + 1)) (x powr (p + 1))\"\n    define m' where \"m' = min 1 (?x'' powr (p + 1))\"\n    have [simp]: \"bs ! i > 0\" by (intro b_pos nth_mem) (simp add: i length_bs)\n    from x0_le_x1 x i have [simp]: \"?x' > 0\" by (intro step_pos) simp_all\n\n\n    {\n      fix u assume u: \"u \\<ge> ?x'\" \"u \\<le> x\"\n      have \"?m \\<le> u powr (p + 1)\" using x u by (intro powr_lower_bound mult_pos_pos) simp_all\n      moreover from c2 and u have \"g u \\<le> c2 * g x\" by simp\n      ultimately have \"g u * ?m \\<le> c2 * g x * u powr (p + 1)\" using c2 x x1_pos x0_le_x1\n        by (intro mult_mono mult_nonneg_nonneg g_nonneg) auto\n    }\n    hence \"integral (\\<lambda>u. g u / u powr (p+1)) ?x' x \\<le> integral (\\<lambda>u. c2 * g x / ?m) ?x' x\"\n      using x_pos step_pos[OF i x] x0_hb_bound7[OF x i] c2 x x0_le_x1\n      by (intro integral_le x'_le_x akra_bazzi_integrable ballI integrable_const)\n         (auto simp: field_simps intro!: mult_nonneg_nonneg g_nonneg)\n\n    also from x0_pos x x0_le_x1 x'_le_x c2 have \"... = (x - ?x') * (c2 * g x / ?m)\"\n      by (subst integral_const) (simp_all add: g_nonneg)\n    also from c2 x_pos x x0_le_x1 have \"c2 * g x \\<ge> 0\"\n      by (intro mult_nonneg_nonneg g_nonneg) simp_all\n    with x i x0_le_x1 have \"(x - ?x') * (c2 * g x / ?m) \\<le> x * (c2 * g x / ?m)\"\n      by (intro x0_hb_bound3 mult_right_mono) (simp_all add: field_simps)\n\n    also have \"x powr (p + 1) = x powr (p + 1) * 1\" by simp\n    also have \"(bs ! i * x + (hs ! i) x) powr (p + 1) =\n               (bs ! i + (hs ! i) x / x) powr (p + 1) * x powr (p + 1)\"\n      using x x1_pos step_pos[OF i x] x_pos i x0_le_x1\n      by (subst powr_mult[symmetric]) (simp add: field_simps, simp, simp add: algebra_simps)\n    also have \"... = x powr (p + 1) * (bs ! i + (hs ! i) x / x) powr (p + 1)\" by simp\n    also have \"min ... (x powr (p + 1) * 1) = x powr (p + 1) * m'\" unfolding m'_def using x_pos\n      by (subst min.commute, intro min_mult_left[symmetric]) simp\n\n    also from x_pos have \"x * (c2 * g x / (x powr (p + 1) * m')) = (c2/m') * (g x / x powr p)\"\n      by (simp add: field_simps powr_add)\n    also from x i g_nonneg x0_le_x1 x1_pos have \"... \\<le> c4 * (g x / x powr p)\" unfolding m'_def\n      by (intro mult_right_mono c4) (simp_all add: field_simps)\n    finally have \"g_approx i x \\<le> c4 * g x\"\n      unfolding g_approx_def using x_pos by (simp add: field_simps)\n  }\n  thus ?thesis using that \\<open>c4 > 0\\<close> by blast\nqed\n\nlemma f_approx_bounded_above:\n  obtains c where \"\\<And>x. x \\<ge> x\\<^sub>0 \\<Longrightarrow> x \\<le> x\\<^sub>1 \\<Longrightarrow> f_approx x \\<le> c\" \"c > 0\"\nproof-\n  let ?m1 = \"max (x\\<^sub>0 powr p) (x\\<^sub>1 powr p)\"\n  let ?m2 = \"max (x\\<^sub>0 powr (-(p+1))) (x\\<^sub>1 powr (-(p+1)))\"\n  let ?m3 = \"gb2 * ?m2\"\n  let ?m4 = \"1 + (x\\<^sub>1 - x\\<^sub>0) * ?m3\"\n  let ?int = \"\\<lambda>x. integral (\\<lambda>u. g u / u powr (p + 1)) x\\<^sub>0 x\"\n  {\n    fix x assume x: \"x \\<ge> x\\<^sub>0\" \"x \\<le> x\\<^sub>1\"\n    with x0_pos have \"x powr p \\<le> ?m1\" \"?m1 \\<ge> 0\" by (intro powr_upper_bound) (simp_all add: max_def)\n    moreover {\n      fix u assume u: \"u \\<in> {x\\<^sub>0..x}\"\n      have \"g u / u powr (p + 1) = g u * u powr (-(p+1))\"\n        by (subst powr_minus) (simp add: field_simps)\n      also from u x x0_pos have \"u powr (-(p+1)) \\<le> ?m2\"\n        by (intro powr_upper_bound) simp_all\n      hence \"g u * u powr (-(p+1)) \\<le> g u * ?m2\"\n        using u g_nonneg x0_pos by (intro mult_left_mono) simp_all\n      also from x u x0_pos have \"g u \\<le> gb2\" by (intro g_bounded) simp_all\n      hence \"g u * ?m2 \\<le> gb2 * ?m2\" by (intro mult_right_mono) (simp_all add: max_def)\n      finally have \"g u / u powr (p + 1) \\<le> ?m3\" .\n    } note A = this\n    {\n      from A x gb2_nonneg have \"?int x \\<le> integral (\\<lambda>_. ?m3) x\\<^sub>0 x\"\n        by (intro integral_le akra_bazzi_integrable integrable_const mult_nonneg_nonneg)\n           (simp_all add: le_max_iff_disj)\n      also from x gb2_nonneg have \"... \\<le> (x - x\\<^sub>0) * ?m3\"\n        by (subst integral_const) (simp_all add: le_max_iff_disj)\n      also from x gb2_nonneg have \"... \\<le> (x\\<^sub>1 - x\\<^sub>0) * ?m3\"\n        by (intro mult_right_mono mult_nonneg_nonneg) (simp_all add: max_def)\n      finally have \"1 + ?int x \\<le> ?m4\" by simp\n    }\n    moreover from x g_nonneg x0_pos have \"?int x \\<ge> 0\"\n      by (intro integral_nonneg akra_bazzi_integrable) (simp_all add: powr_def field_simps)\n    hence \"1 + ?int x \\<ge> 0\" by simp\n    ultimately have \"f_approx x \\<le> ?m1 * ?m4\"\n      unfolding f_approx_def by (intro mult_mono)\n    hence \"f_approx x \\<le> max 1 (?m1 * ?m4)\" by simp\n  }\n  from that[OF this] show ?thesis by auto\nqed\n\nlemma f_bounded_below:\n  assumes c': \"c' > 0\"\n  obtains c where \"\\<And>x. x \\<ge> x\\<^sub>0 \\<Longrightarrow> x \\<le> x\\<^sub>1 \\<Longrightarrow> 2 * (c * f_approx x) \\<le> f x\" \"c \\<le> c'\" \"c > 0\"\nproof-\n  obtain c where c: \"\\<And>x. x\\<^sub>0 \\<le> x \\<Longrightarrow> x \\<le> x\\<^sub>1 \\<Longrightarrow> f_approx x \\<le> c\" \"c > 0\"\n    by (rule f_approx_bounded_above) blast\n  {\n    fix x assume x: \"x\\<^sub>0 \\<le> x\" \"x \\<le> x\\<^sub>1\"\n    with c have \"inverse c * f_approx x \\<le> 1\" by (simp add: field_simps)\n    moreover from x f_base2 x0_pos have \"f x \\<ge> fb2\" by auto\n    ultimately have \"inverse c * f_approx x * fb2 \\<le> 1 * f x\" using fb2_pos\n      by (intro mult_mono) simp_all\n    hence \"inverse c * fb2 * f_approx x \\<le> f x\" by (simp add: field_simps)\n    moreover have \"min c' (inverse c * fb2) * f_approx x \\<le> inverse c * fb2 * f_approx x\"\n      using f_approx_nonneg x c\n      by (intro mult_right_mono f_approx_nonneg) (simp_all add: field_simps)\n    ultimately have \"2 * (min c' (inverse c * fb2) / 2 * f_approx x) \\<le> f x\" by simp\n  }\n  moreover from c' have \"min c' (inverse c * fb2) / 2 \\<le> c'\" by simp\n  moreover have \"min c' (inverse c * fb2) / 2 > 0\"\n    using c fb2_pos c' by simp\n  ultimately show ?thesis by (rule that)\nqed\n\nlemma akra_bazzi_lower:\n  obtains c5 where \"\\<And>x. x \\<ge> x\\<^sub>0 \\<Longrightarrow> f x \\<ge> c5 * f_approx x\" \"c5 > 0\"\nproof-\n  obtain c4 where c4: \"\\<And>x i. x \\<ge> x\\<^sub>1 \\<Longrightarrow> i < k \\<Longrightarrow> g_approx i x \\<le> c4 * g x\" \"c4 > 0\"\n    by (rule g_bounds2) blast\n  hence \"inverse c4 / 2 > 0\" by simp\n  then obtain c5 where c5: \"\\<And>x. x \\<ge> x\\<^sub>0 \\<Longrightarrow> x \\<le> x\\<^sub>1 \\<Longrightarrow> 2 * (c5 * f_approx x) \\<le> f x\"\n                           \"c5 \\<le> inverse c4 / 2\" \"c5 > 0\"\n    by (rule f_bounded_below) blast\n\n  {\n  fix x :: real assume x: \"x \\<ge> x\\<^sub>0\"\n  from c5 x have  \" c5 * 1 * f_approx x \\<le> c5 * (1 + ln x powr (- e / 2)) * f_approx x\"\n    by (intro mult_right_mono mult_left_mono f_approx_nonneg) simp_all\n  also from x have \"c5 * (1 + ln x powr (-e/2)) * f_approx x \\<le> f x\"\n  proof (induction x rule: akra_bazzi_induct)\n    case (base x)\n    have \"1 + ln x powr (-e/2) \\<le> 2\" using asymptotics3 base by simp\n    hence \"(1 + ln x powr (-e/2)) * (c5 * f_approx x) \\<le> 2 * (c5 * f_approx x)\"\n      using c5 f_approx_nonneg base x0_ge_1 by (intro mult_right_mono mult_nonneg_nonneg) simp_all\n    also from base have \"2 * (c5 * f_approx x) \\<le> f x\"  by (intro c5) simp_all\n    finally show ?case by (simp add: algebra_simps)\n  next\n    case (rec x)\n    let ?a = \"\\<lambda>i. as!i\" and ?b = \"\\<lambda>i. bs!i\" and ?h = \"\\<lambda>i. hs!i\"\n    let ?int = \"integral (\\<lambda>u. g u / u powr (p+1)) x\\<^sub>0 x\"\n    let ?int1 = \"\\<lambda>i. integral (\\<lambda>u. g u / u powr (p+1)) x\\<^sub>0 (?b i*x+?h i x)\"\n    let ?int2 = \"\\<lambda>i. integral (\\<lambda>u. g u / u powr (p+1)) (?b i*x+?h i x) x\"\n    let ?l = \"ln x powr (-e/2)\" and ?l' = \"\\<lambda>i. ln (?b i*x + ?h i x) powr (-e/2)\"\n\n    from rec and x0_le_x1 x0_ge_1 have x: \"x \\<ge> x\\<^sub>0\" and x_gt_1: \"x > 1\" by simp_all\n    with x0_pos have x_pos: \"x > 0\" and x_nonneg: \"x \\<ge> 0\" by simp_all\n    from c5 c4 have \"c5 * c4 \\<le> 1/2\" by (simp add: field_simps)\n    moreover from asymptotics3 x have \"(1 + ?l) \\<le> 2\" by (simp add: field_simps)\n    ultimately have \"(c5*c4)*(1 + ?l) \\<le> (1/2) * 2\" by (rule mult_mono) simp_all\n    hence \"0 \\<le> 1 - c5*c4*(1 + ?l)\" by simp\n    with g_nonneg[OF x] have \"0 \\<le> g x * ...\" by (intro mult_nonneg_nonneg) simp_all\n    hence \"c5 * (1 + ?l) * f_approx x \\<le> c5 * (1 + ?l) * f_approx x + g x - c5*c4*(1 + ?l) * g x\"\n      by (simp add: algebra_simps)\n    also from x_gt_1 have \"... = c5 * x powr p * (1 + ?l) * (1 + ?int - c4*g x/x powr p) + g x\"\n      by (simp add: field_simps f_approx_def powr_minus)\n    also have \"c5 * x powr p * (1 + ?l) * (1 + ?int - c4*g x/x powr p) =\n                 (\\<Sum>i<k. (?a i * ?b i powr p) * (c5 * x powr p * (1 + ?l) * (1 + ?int - c4*g x/x powr p)))\"\n      by (subst sum_distrib_right[symmetric]) (simp add: p_props)\n    also have \"... \\<le> (\\<Sum>i<k. ?a i * f (?b i*x + ?h i x))\"\n    proof (intro sum_mono, clarify)\n      fix i assume i: \"i < k\"\n      let ?f = \"c5 * ?a i * (?b i * x) powr p\"\n      from rec.hyps i have \"x\\<^sub>0 < bs ! i * x + (hs ! i) x\" by (intro x0_hb_bound7) simp_all\n      hence \"1 + ?int1 i \\<ge> 1\" by (intro f_approx_aux x0_hb_bound7) simp_all\n      hence int_nonneg: \"1 + ?int1 i \\<ge> 0\" by simp\n\n      have \"(?a i * ?b i powr p) * (c5 * x powr p * (1 + ?l) * (1 + ?int - c4*g x/x powr p)) =\n            ?f * (1 + ?l) * (1 + ?int - c4*g x/x powr p)\" (is \"?expr = ?A * ?B\")\n            using x_pos b_pos[of \"bs!i\"] i by (subst powr_mult) simp_all\n      also from rec.hyps i have \"g_approx i x \\<le> c4 * g x\" by (intro c4) simp_all\n      hence \"c4*g x/x powr p \\<ge> ?int2 i\" unfolding g_approx_def using x_pos\n        by (simp add: field_simps)\n      hence \"?A * ?B \\<le> ?A * (1 + (?int - ?int2 i))\" using i c5 a_ge_0\n        by (intro mult_left_mono mult_nonneg_nonneg) simp_all\n      also from rec.hyps i have \"x\\<^sub>0 < bs ! i * x + (hs ! i) x\" by (intro x0_hb_bound7) simp_all\n      hence \"?int - ?int2 i = ?int1 i\"\n        apply (subst diff_eq_eq, subst eq_commute)\n        apply (intro integral_combine akra_bazzi_integrable)\n        apply (insert rec.hyps step_le_x[OF i, of x], simp_all)\n        done\n      also have \"?A * (1 + ?int1 i) = (c5*?a i*(1 + ?int1 i)) * ((?b i*x) powr p * (1 + ?l))\"\n        by (simp add: algebra_simps)\n      also have \"... \\<le> (c5*?a i*(1 + ?int1 i)) * ((?b i*x + ?h i x) powr p * (1 + ?l' i))\"\n        using rec.hyps i c5 a_ge_0 int_nonneg\n        by (intro mult_left_mono asymptotics1' mult_nonneg_nonneg) simp_all\n      also have \"... = ?a i*(c5*(1 + ?l' i)*f_approx (?b i*x + ?h i x))\"\n        by (simp add: algebra_simps f_approx_def)\n      also from i have \"... \\<le> ?a i * f (?b i*x + ?h i x)\"\n        by (intro mult_left_mono a_ge_0 rec.IH) simp_all\n      finally show \"?expr \\<le> ?a i * f (?b i*x + ?h i x)\" .\n    qed\n    also have \"... + g x = f x\" using f_rec[of x] rec.hyps x0_le_x1 by simp\n    finally show ?case by simp\n  qed\n  finally have \"c5 * f_approx x \\<le> f x\" by simp\n  }\n  from this and c5(3) show ?thesis by (rule that)\nqed\n\nlemma akra_bazzi_bigomega:\n  \"f \\<in> \\<Omega>(\\<lambda>x. x powr p * (1 + integral (\\<lambda>u. g u / u powr (p + 1)) x\\<^sub>0 x))\"\napply (fold f_approx_def, rule akra_bazzi_lower, erule landau_omega.bigI)\napply (subst eventually_at_top_linorder, rule exI[of _ x\\<^sub>0])\napply (simp add: f_nonneg f_approx_nonneg)\ndone\n\nend\n\n\nlocale akra_bazzi_real_upper = akra_bazzi_real +\n  fixes fb1 c1 :: real\n  assumes f_base1:   \"x \\<ge> x\\<^sub>0 \\<Longrightarrow> x \\<le> x\\<^sub>1 \\<Longrightarrow> f x \\<le> fb1\"\n  and     g_growth1: \"\\<forall>x\\<ge>x\\<^sub>1. \\<forall>u\\<in>{C*x..x}. c1 * g x \\<le> g u\"\n  and     c1_pos:    \"c1 > 0\"\nbegin\n\ninterpretation akra_bazzi_integral integrable integral by (rule integral)\n\nlemma g_growth1':\n  assumes \"x \\<ge> x\\<^sub>1\" \"i < k\" \"u \\<in> {bs!i*x+(hs!i) x..x}\"\n  shows   \"c1 * g x \\<le> g u\"\nproof-\n  from assms have \"C*x \\<le> bs!i*x+(hs!i) x\" by (intro Cx_le_step)\n  with assms have \"u \\<in> {C*x..x}\" by auto\n  with assms g_growth1 show ?thesis by simp\nqed\n\nlemma g_bounds1:\n  obtains c3 where\n    \"\\<And>x i. x \\<ge> x\\<^sub>1 \\<Longrightarrow> i < k \\<Longrightarrow> c3 * g x \\<le> g_approx i x\" \"c3 > 0\"\nproof-\n  define c3 where \"c3 =\n    Min {c1*((1-b)/2) / max 1 (max ((b/2) powr (p+1)) ((b*3/2) powr (p+1))) |b. b \\<in> set bs}\"\n\n  {\n    fix b assume b: \"b \\<in> set bs\"\n    let ?x = \"max 1 (max ((b/2) powr (p+1)) ((b*3/2) powr (p+1)))\"\n    have \"?x \\<ge> 1\" by simp\n    hence \"?x > 0\" by (rule less_le_trans[OF zero_less_one])\n    with b b_less_1 c1_pos have \"c1*((1-b)/2) / ?x > 0\"\n      by (intro divide_pos_pos mult_pos_pos) (simp_all add: algebra_simps)\n  }\n  hence \"c3 > 0\" unfolding c3_def by (subst Min_gr_iff) auto\n\n  {\n    fix x i assume i: \"i < k\" and x: \"x \\<ge> x\\<^sub>1\"\n    with b_less_1 have b_less_1': \"bs ! i < 1\" by simp\n    let ?m = \"max 1 (max ((bs!i/2) powr (p+1)) ((bs!i*3/2) powr (p+1)))\"\n    from i x have \"c3 \\<le> c1*((1-bs!i)/2) / ?m\" unfolding c3_def by (intro Min.coboundedI) auto\n    also have \"max 1 ((bs!i + (hs ! i) x / x) powr (p+1)) \\<le> max 1 (max ((bs!i/2) powr (p+1)) ((bs!i*3/2) powr (p+1)))\"\n      apply (insert x i x0_le_x1 x1_pos step_pos[OF i x] b_pos[OF b_in_bs[OF i]],\n             rule max.mono, simp, cases \"p + 1 \\<ge> 0\")\n      apply (rule order.trans[OF powr_mono2[OF _ _ x0_hb_bound5] max.cobounded2], simp_all add: field_simps) []\n      apply (rule order.trans[OF powr_mono2'[OF _ _ x0_hb_bound4'] max.cobounded1], simp_all add: field_simps) []\n      done\n    with b_less_1' c1_pos have \"c1*((1-bs!i)/2) / ?m \\<le>\n          c1*((1-bs!i)/2) / max 1 ((bs!i + (hs ! i) x / x) powr (p+1))\"\n      by (intro divide_left_mono mult_nonneg_nonneg) (simp_all add: algebra_simps)\n    finally have \"c3 \\<le> c1*((1-bs!i)/2) / max 1 ((bs!i + (hs ! i) x / x) powr (p+1))\" .\n  } note c3 = this\n\n  {\n    fix x :: real and i :: nat\n    assume x: \"x \\<ge> x\\<^sub>1\" and i: \"i < k\"\n    from x x1_pos have x_pos: \"x > 0\" by simp\n    let ?x' = \"bs ! i * x + (hs ! i) x\"\n    let ?x'' = \"bs ! i + (hs ! i) x / x\"\n    from x x1_ge_1 x0_le_x1 i c1_pos g_growth1'\n      have c1: \"c1 > 0\" \"\\<forall>u\\<in>{?x'..x}. g u \\<ge> c1 * g x\" by auto\n    define b' where \"b' = (1 - bs!i)/2\"\n\n    from x x0_le_x1 i have x'_le_x: \"?x' \\<le> x\" by (intro step_le_x) simp_all\n    let ?m = \"max (?x' powr (p + 1)) (x powr (p + 1))\"\n    define m' where \"m' = max 1 (?x'' powr (p + 1))\"\n    have [simp]: \"bs ! i > 0\" by (intro b_pos nth_mem) (simp add: i length_bs)\n    from x x0_le_x1 i have x'_pos: \"?x' > 0\" by (intro step_pos) simp_all\n    have m_pos: \"?m > 0\" unfolding max_def using x_pos step_pos[OF i x] by auto\n    with x x0_le_x1 c1 have c1_g_m_nonneg: \"c1 * g x / ?m \\<ge> 0\"\n      by (intro mult_nonneg_nonneg divide_nonneg_pos g_nonneg) simp_all\n\n    from x i g_nonneg x0_le_x1 have \"c3 * (g x / x powr p) \\<le> (c1*b'/m') * (g x / x powr p)\"\n      unfolding m'_def b'_def by (intro mult_right_mono c3) (simp_all add: field_simps)\n    also from x_pos have \"... = (x * b') * (c1 * g x / (x powr (p + 1) * m'))\"\n      by (simp add: field_simps powr_add)\n    also from x i c1_pos x1_pos x0_le_x1\n      have \"... \\<le> (x - ?x') * (c1 * g x / (x powr (p + 1) * m'))\"\n      unfolding b'_def m'_def by (intro x0_hb_bound6 mult_right_mono mult_nonneg_nonneg\n                                        divide_nonneg_nonneg g_nonneg) simp_all\n    also have \"x powr (p + 1) * m' =\n                 max (x powr (p + 1) * (bs ! i + (hs ! i) x / x) powr (p + 1)) (x powr (p + 1) * 1)\"\n      unfolding m'_def using x_pos by (subst max.commute, intro max_mult_left) simp\n    also have \"(x powr (p + 1) * (bs ! i + (hs ! i) x / x) powr (p + 1)) =\n                 (bs ! i + (hs ! i) x / x) powr (p + 1) * x powr (p + 1)\" by simp\n    also have \"... = (bs ! i * x + (hs ! i) x) powr (p + 1)\"\n      using x x1_pos step_pos[OF i x] x_pos i x0_le_x1 x_pos\n      by (subst powr_mult[symmetric]) (simp add: field_simps, simp, simp add: algebra_simps)\n    also have \"x powr (p + 1) * 1 = x powr (p + 1)\" by simp\n    also have \"(x - ?x') * (c1 * g x / ?m) = integral (\\<lambda>_. c1 * g x / ?m) ?x' x\"\n      using x'_le_x by (subst integral_const[OF c1_g_m_nonneg]) auto\n    also {\n      fix u assume u: \"u \\<ge> ?x'\" \"u \\<le> x\"\n      have \"u powr (p + 1) \\<le> ?m\" using x u x'_pos by (intro powr_upper_bound mult_pos_pos) simp_all\n      moreover from x'_pos u have \"u \\<ge> 0\" by simp\n      moreover from c1 and u have \"c1 * g x \\<le> g u\" by simp\n      ultimately have \"c1 * g x * u powr (p + 1) \\<le> g u * ?m\" using c1 x u x0_hb_bound7[OF x i]\n        by (intro mult_mono g_nonneg) auto\n      with m_pos u step_pos[OF i x]\n        have \"c1 * g x / ?m \\<le> g u / u powr (p + 1)\" by (simp add: field_simps)\n    }\n    hence \"integral (\\<lambda>_. c1 * g x / ?m) ?x' x \\<le> integral (\\<lambda>u. g u / u powr (p + 1)) ?x' x\"\n      using x0_hb_bound7[OF x i] x'_le_x\n      by (intro integral_le ballI akra_bazzi_integrable integrable_const c1_g_m_nonneg) simp_all\n    finally have \"c3 * g x \\<le> g_approx i x\" using x_pos\n      unfolding g_approx_def by (simp add: field_simps)\n  }\n  thus ?thesis using that \\<open>c3 > 0\\<close> by blast\nqed\n\n\nlemma f_bounded_above:\n  assumes c': \"c' > 0\"\n  obtains c where \"\\<And>x. x \\<ge> x\\<^sub>0 \\<Longrightarrow> x \\<le> x\\<^sub>1 \\<Longrightarrow> f x \\<le> (1/2) * (c * f_approx x)\" \"c \\<ge> c'\" \"c > 0\"\nproof-\n  obtain c where c: \"\\<And>x. x\\<^sub>0 \\<le> x \\<Longrightarrow> x \\<le> x\\<^sub>1 \\<Longrightarrow> f_approx x \\<ge> c\" \"c > 0\"\n    by (rule f_approx_bounded_below) blast\n  have fb1_nonneg: \"fb1 \\<ge> 0\" using f_base1[of \"x\\<^sub>0\"] f_nonneg[of x\\<^sub>0] x0_le_x1 by simp\n  {\n    fix x assume x: \"x \\<ge> x\\<^sub>0\" \"x \\<le> x\\<^sub>1\"\n    with f_base1 x0_pos have \"f x \\<le> fb1\" by simp\n    moreover from c and x have \"f_approx x \\<ge> c\" by blast\n    ultimately have \"f x * c \\<le> fb1 * f_approx x\" using c fb1_nonneg by (intro mult_mono) simp_all\n    also from f_approx_nonneg x have \"... \\<le> (fb1 + 1) * f_approx x\" by (simp add: algebra_simps)\n    finally have \"f x \\<le> ((fb1+1) / c) * f_approx x\" by (simp add: field_simps c)\n    also have \"... \\<le> max ((fb1+1) / c) c' * f_approx x\"\n      by (intro mult_right_mono) (simp_all add: f_approx_nonneg x)\n    finally have \"f x \\<le> 1/2 * (max ((fb1+1) / c) c' * 2 * f_approx x)\" by simp\n  }\n  moreover have \"max ((fb1+1) / c) c' * 2 \\<ge> max ((fb1+1) / c) c'\"\n    by (subst mult_le_cancel_left1) (insert c', simp)\n  hence \"max ((fb1+1) / c) c' * 2 \\<ge> c'\" by (rule order.trans[OF max.cobounded2])\n  moreover from fb1_nonneg and c have \"(fb1+1) / c > 0\" by simp\n  hence \"max ((fb1+1) / c) c' * 2 > 0\" by simp\n  ultimately show ?thesis by (rule that)\nqed\n\n\nlemma akra_bazzi_upper:\n  obtains c6 where \"\\<And>x. x \\<ge> x\\<^sub>0 \\<Longrightarrow> f x \\<le> c6 * f_approx x\" \"c6 > 0\"\nproof-\n  obtain c3 where c3: \"\\<And>x i. x \\<ge> x\\<^sub>1 \\<Longrightarrow> i < k \\<Longrightarrow> c3 * g x \\<le> g_approx i x\" \"c3 > 0\"\n    by (rule g_bounds1) blast\n  hence \"2 / c3 > 0\" by simp\n  then obtain c6 where c6: \"\\<And>x. x \\<ge> x\\<^sub>0 \\<Longrightarrow> x \\<le> x\\<^sub>1 \\<Longrightarrow> f x \\<le> 1/2 * (c6 * f_approx x)\"\n                           \"c6 \\<ge> 2 / c3\" \"c6 > 0\"\n    by (rule f_bounded_above) blast\n\n  {\n  fix x :: real assume x: \"x \\<ge> x\\<^sub>0\"\n  hence \"f x \\<le> c6 * (1 - ln x powr (-e/2)) * f_approx x\"\n  proof (induction x rule: akra_bazzi_induct)\n    case (base x)\n    from base have \"f x \\<le> 1/2 * (c6 * f_approx x)\"  by (intro c6) simp_all\n    also have \"1 - ln x powr (-e/2) \\<ge> 1/2\" using asymptotics4 base by simp\n    hence \"(1 - ln x powr (-e/2)) * (c6 * f_approx x) \\<ge> 1/2 * (c6 * f_approx x)\"\n      using c6 f_approx_nonneg base x0_ge_1 by (intro mult_right_mono mult_nonneg_nonneg) simp_all\n    finally show ?case by (simp add: algebra_simps)\n  next\n    case (rec x)\n    let ?a = \"\\<lambda>i. as!i\" and ?b = \"\\<lambda>i. bs!i\" and ?h = \"\\<lambda>i. hs!i\"\n    let ?int = \"integral (\\<lambda>u. g u / u powr (p+1)) x\\<^sub>0 x\"\n    let ?int1 = \"\\<lambda>i. integral (\\<lambda>u. g u / u powr (p+1)) x\\<^sub>0 (?b i*x+?h i x)\"\n    let ?int2 = \"\\<lambda>i. integral (\\<lambda>u. g u / u powr (p+1)) (?b i*x+?h i x) x\"\n    let ?l = \"ln x powr (-e/2)\" and ?l' = \"\\<lambda>i. ln (?b i*x + ?h i x) powr (-e/2)\"\n\n    from rec and x0_le_x1 have x: \"x \\<ge> x\\<^sub>0\" by simp\n    with x0_pos have x_pos: \"x > 0\" and x_nonneg: \"x \\<ge> 0\" by simp_all\n    from c6 c3 have \"c6 * c3 \\<ge> 2\" by (simp add: field_simps)\n    have \"f x = (\\<Sum>i<k. ?a i * f (?b i*x + ?h i x)) + g x\" (is \"_ = ?sum + _\")\n      using f_rec[of x] rec.hyps x0_le_x1 by simp\n    also have \"?sum \\<le> (\\<Sum>i<k. (?a i*?b i powr p) * (c6*x powr p*(1 - ?l)*(1 + ?int - c3*g x/x powr p)))\" (is \"_ \\<le> ?sum'\")\n    proof (rule sum_mono, clarify)\n      fix i assume i: \"i < k\"\n      from rec.hyps i have \"x\\<^sub>0 < bs ! i * x + (hs ! i) x\" by (intro x0_hb_bound7) simp_all\n      hence \"1 + ?int1 i \\<ge> 1\" by (intro f_approx_aux x0_hb_bound7) simp_all\n      hence int_nonneg: \"1 + ?int1 i \\<ge> 0\" by simp\n      have l_le_1: \"ln x powr -(e/2) \\<le> 1\" using asymptotics3[OF x] by (simp add: field_simps)\n\n      from i have \"f (?b i*x + ?h i x) \\<le> c6 * (1 - ?l' i) * f_approx (?b i*x + ?h i x)\"\n        by (rule rec.IH)\n      hence \"?a i * f (?b i*x + ?h i x) \\<le> ?a i * ...\" using a_ge_0 i\n        by (intro mult_left_mono) simp_all\n      also have \"... = (c6*?a i*(1 + ?int1 i)) * ((?b i*x + ?h i x) powr p * (1 - ?l' i))\"\n        unfolding f_approx_def by (simp add: algebra_simps)\n      also from i rec.hyps c6 a_ge_0\n        have \"... \\<le> (c6*?a i*(1 + ?int1 i)) * ((?b i*x) powr p * (1 - ?l))\"\n        by (intro mult_left_mono asymptotics2' mult_nonneg_nonneg int_nonneg) simp_all\n      also have \"... = (1 + ?int1 i) * (c6*?a i*(?b i*x) powr p * (1 - ?l))\"\n        by (simp add: algebra_simps)\n      also from rec.hyps i have \"x\\<^sub>0 < bs ! i * x + (hs ! i) x\" by (intro x0_hb_bound7) simp_all\n      hence \"?int1 i = ?int - ?int2 i\"\n        apply (subst eq_diff_eq)\n        apply (intro integral_combine akra_bazzi_integrable)\n        apply (insert rec.hyps step_le_x[OF i, of x], simp_all)\n        done\n      also from rec.hyps i have \"c3 * g x \\<le> g_approx i x\" by (intro c3) simp_all\n      hence \"?int2 i \\<ge> c3*g x/x powr p\" unfolding g_approx_def using x_pos\n        by (simp add: field_simps)\n      hence \"(1 + (?int - ?int2 i)) * (c6*?a i*(?b i*x) powr p * (1 - ?l)) \\<le>\n             (1 + ?int - c3*g x/x powr p) * (c6*?a i*(?b i*x) powr p * (1 - ?l))\"\n             using i c6 a_ge_0 l_le_1\n             by (intro mult_right_mono mult_nonneg_nonneg) (simp_all add: field_simps)\n      also have \"... = (?a i*?b i powr p) * (c6*x powr p*(1 - ?l) * (1 + ?int - c3*g x/x powr p))\"\n        using b_pos[of \"bs!i\"] x x0_pos i by (subst powr_mult) (simp_all add: algebra_simps)\n      finally show \"?a i * f (?b i*x + ?h i x) \\<le> ...\" .\n    qed\n\n    hence \"?sum + g x \\<le> ?sum' + g x\" by simp\n    also have \"... = c6 * x powr p * (1 - ?l) * (1 + ?int - c3*g x/x powr p) + g x\"\n      by (simp add: sum_distrib_right[symmetric] p_props)\n    also have \"... = c6 * (1 - ?l) * f_approx x - (c6*c3*(1 - ?l) - 1) * g x\"\n      unfolding f_approx_def using x_pos by (simp add: field_simps)\n    also {\n       from c6 c3 have \"c6*c3 \\<ge> 2\" by (simp add: field_simps)\n       moreover have \"(1 - ?l) \\<ge> 1/2\" using asymptotics4[OF x] by simp\n       ultimately have \"c6*c3*(1 - ?l) \\<ge> 2 * (1/2)\" by (intro mult_mono) simp_all\n       with x x_pos have \"(c6*c3*(1 - ?l) - 1) * g x \\<ge> 0\"\n         by (intro mult_nonneg_nonneg g_nonneg) simp_all\n       hence \"c6 * (1 - ?l) * f_approx x - (c6*c3*(1 - ?l) - 1) * g x \\<le>\n                  c6 * (1 - ?l) * f_approx x\" by (simp add: algebra_simps)\n    }\n    finally show ?case .\n  qed\n  also from x c6 have \"... \\<le> c6 * 1 * f_approx x\"\n    by (intro mult_left_mono mult_right_mono f_approx_nonneg) simp_all\n  finally have \"f x \\<le> c6 * f_approx x\" by simp\n  }\n  from this and c6(3) show ?thesis by (rule that)\nqed\n\nlemma akra_bazzi_bigo:\n  \"f \\<in> O(\\<lambda>x. x powr p *(1 + integral (\\<lambda>u. g u / u powr (p + 1)) x\\<^sub>0 x))\"\napply (fold f_approx_def, rule akra_bazzi_upper, erule landau_o.bigI)\napply (subst eventually_at_top_linorder, rule exI[of _ x\\<^sub>0])\napply (simp add: f_nonneg f_approx_nonneg)\ndone\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/Akra_Bazzi/Akra_Bazzi_Real.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8558511469672594, "lm_q2_score": 0.8459424334245617, "lm_q1q2_score": 0.7240008019146855}}
{"text": "(*\n  File:    Going_To_Filter.thy\n  Author:  Manuel Eberl, TU M\u00fcnchen\n\n  A filter describing the points x such that f(x) tends to some other filter.\n*)\n\nsection \\<open>The \\<open>going_to\\<close> filter\\<close>\n\ntheory Going_To_Filter\n  imports Complex_Main\nbegin\n\ndefinition going_to_within :: \"('a \\<Rightarrow> 'b) \\<Rightarrow> 'b filter \\<Rightarrow> 'a set \\<Rightarrow> 'a filter\"\n  (\\<open>(_)/ going'_to (_)/ within (_)\\<close> [1000,60,60] 60) where\n  \"f going_to F within A = inf (filtercomap f F) (principal A)\"\n\nabbreviation going_to :: \"('a \\<Rightarrow> 'b) \\<Rightarrow> 'b filter \\<Rightarrow> 'a filter\"\n    (infix \\<open>going'_to\\<close> 60)\n    where \"f going_to F \\<equiv> f going_to F within UNIV\"\n\ntext \\<open>\n  The \\<open>going_to\\<close> filter is, in a sense, the opposite of \\<^term>\\<open>filtermap\\<close>. \n  It corresponds to the intuition of, given a function $f: A \\to B$ and a filter $F$ on the \n  range of $B$, looking at such values of $x$ that $f(x)$ approaches $F$. This can be \n  written as \\<^term>\\<open>f going_to F\\<close>.\n  \n  A classic example is the \\<^term>\\<open>at_infinity\\<close> filter, which describes the neigbourhood\n  of infinity (i.\\,e.\\ all values sufficiently far away from the zero). This can also be written\n  as \\<^term>\\<open>norm going_to at_top\\<close>.\n\n  Additionally, the \\<open>going_to\\<close> filter can be restricted with an optional `within' parameter.\n  For instance, if one would would want to consider the filter of complex numbers near infinity\n  that do not lie on the negative real line, one could write \n  \\<^term>\\<open>norm going_to at_top within - complex_of_real ` {..0}\\<close>.\n\n  A third, less mathematical example lies in the complexity analysis of algorithms.\n  Suppose we wanted to say that an algorithm on lists takes $O(n^2)$ time where $n$ is \n  the length of the input list. We can write this using the Landau symbols from the AFP,\n  where the underlying filter is \\<^term>\\<open>length going_to at_top\\<close>. If, on the other hand,\n  we want to look the complexity of the algorithm on sorted lists, we could use the filter\n  \\<^term>\\<open>length going_to at_top within {xs. sorted xs}\\<close>.\n\\<close>\n\nlemma going_to_def: \"f going_to F = filtercomap f F\"\n  by (simp add: going_to_within_def)\n\nlemma eventually_going_toI [intro]: \n  assumes \"eventually P F\"\n  shows   \"eventually (\\<lambda>x. P (f x)) (f going_to F)\"\n  using assms by (auto simp: going_to_def)\n\nlemma filterlim_going_toI_weak [intro]: \"filterlim f F (f going_to F within A)\"\n  unfolding going_to_within_def\n  by (meson filterlim_filtercomap filterlim_iff inf_le1 le_filter_def)\n\nlemma going_to_mono: \"F \\<le> G \\<Longrightarrow> A \\<subseteq> B \\<Longrightarrow> f going_to F within A \\<le> f going_to G within B\"\n  unfolding going_to_within_def by (intro inf_mono filtercomap_mono) simp_all\n\nlemma going_to_inf: \n  \"f going_to (inf F G) within A = inf (f going_to F within A) (f going_to G within A)\"\n  by (simp add: going_to_within_def filtercomap_inf inf_assoc inf_commute inf_left_commute)\n\nlemma going_to_sup: \n  \"f going_to (sup F G) within A \\<ge> sup (f going_to F within A) (f going_to G within A)\"\n  by (auto simp: going_to_within_def intro!: inf.coboundedI1 filtercomap_sup filtercomap_mono)\n\nlemma going_to_top [simp]: \"f going_to top within A = principal A\"\n  by (simp add: going_to_within_def)\n    \nlemma going_to_bot [simp]: \"f going_to bot within A = bot\"\n  by (simp add: going_to_within_def)\n    \nlemma going_to_principal: \n  \"f going_to principal A within B = principal (f -` A \\<inter> B)\"\n  by (simp add: going_to_within_def)\n    \nlemma going_to_within_empty [simp]: \"f going_to F within {} = bot\"\n  by (simp add: going_to_within_def)\n\nlemma going_to_within_union [simp]: \n  \"f going_to F within (A \\<union> B) = sup (f going_to F within A) (f going_to F within B)\"\n  by (simp add: going_to_within_def flip: inf_sup_distrib1)\n\nlemma eventually_going_to_at_top_linorder:\n  fixes f :: \"'a \\<Rightarrow> 'b :: linorder\"\n  shows \"eventually P (f going_to at_top within A) \\<longleftrightarrow> (\\<exists>C. \\<forall>x\\<in>A. f x \\<ge> C \\<longrightarrow> P x)\"\n  unfolding going_to_within_def eventually_filtercomap \n    eventually_inf_principal eventually_at_top_linorder by fast\n\nlemma eventually_going_to_at_bot_linorder:\n  fixes f :: \"'a \\<Rightarrow> 'b :: linorder\"\n  shows \"eventually P (f going_to at_bot within A) \\<longleftrightarrow> (\\<exists>C. \\<forall>x\\<in>A. f x \\<le> C \\<longrightarrow> P x)\"\n  unfolding going_to_within_def eventually_filtercomap \n    eventually_inf_principal eventually_at_bot_linorder by fast\n\nlemma eventually_going_to_at_top_dense:\n  fixes f :: \"'a \\<Rightarrow> 'b :: {linorder,no_top}\"\n  shows \"eventually P (f going_to at_top within A) \\<longleftrightarrow> (\\<exists>C. \\<forall>x\\<in>A. f x > C \\<longrightarrow> P x)\"\n  unfolding going_to_within_def eventually_filtercomap \n    eventually_inf_principal eventually_at_top_dense by fast\n\nlemma eventually_going_to_at_bot_dense:\n  fixes f :: \"'a \\<Rightarrow> 'b :: {linorder,no_bot}\"\n  shows \"eventually P (f going_to at_bot within A) \\<longleftrightarrow> (\\<exists>C. \\<forall>x\\<in>A. f x < C \\<longrightarrow> P x)\"\n  unfolding going_to_within_def eventually_filtercomap \n    eventually_inf_principal eventually_at_bot_dense by fast\n               \nlemma eventually_going_to_nhds:\n  \"eventually P (f going_to nhds a within A) \\<longleftrightarrow> \n     (\\<exists>S. open S \\<and> a \\<in> S \\<and> (\\<forall>x\\<in>A. f x \\<in> S \\<longrightarrow> P x))\"\n  unfolding going_to_within_def eventually_filtercomap eventually_inf_principal\n    eventually_nhds by fast\n\nlemma eventually_going_to_at:\n  \"eventually P (f going_to (at a within B) within A) \\<longleftrightarrow> \n     (\\<exists>S. open S \\<and> a \\<in> S \\<and> (\\<forall>x\\<in>A. f x \\<in> B \\<inter> S - {a} \\<longrightarrow> P x))\"\n  unfolding at_within_def going_to_inf eventually_inf_principal\n            eventually_going_to_nhds going_to_principal by fast\n\nlemma norm_going_to_at_top_eq: \"norm going_to at_top = at_infinity\"\n  by (simp add: eventually_at_infinity eventually_going_to_at_top_linorder filter_eq_iff)\n\nlemmas at_infinity_altdef = norm_going_to_at_top_eq [symmetric]\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/Going_To_Filter.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8577681158979307, "lm_q2_score": 0.8438951025545426, "lm_q1q2_score": 0.723866312133701}}
{"text": "theory FOL_substitution\nimports FOL_formula\nbegin\n\nsection{*FOL Substitution *}\ntext{* Here we we set up substitution for FOL_Formulas. The goal is the Class Existence Theorem \n       of the next section, which says that FOL_Formulas define classes.*}\n\nprimrec FOL_MaxVar2 :: \"FOL_Formula \\<Rightarrow> nat\"\n--\"In contrast to FOL_MaxVar, FOL_MaxVar2 looks at every variable even the quantified ones.\"\nwhere\n  \"FOL_MaxVar2 FTrue = 0\"\n  | \"FOL_MaxVar2 FFalse = 0\"\n  | \"FOL_MaxVar2 (FBelongs x y) = max (FOL_Var x) (FOL_Var y)\"\n  | \"FOL_MaxVar2 (FEquals x y) = max (FOL_Var x) (FOL_Var y)\"\n  | \"FOL_MaxVar2 (FAnd \\<phi> \\<psi>) = max (FOL_MaxVar2 \\<phi>) (FOL_MaxVar2 \\<psi>)\"\n  | \"FOL_MaxVar2 (FNot \\<phi>) = FOL_MaxVar2 \\<phi>\"\n  | \"FOL_MaxVar2 (FOr \\<phi> \\<psi>) = max (FOL_MaxVar2 \\<phi>) (FOL_MaxVar2 \\<psi>)\"\n  | \"FOL_MaxVar2 (FImp \\<phi> \\<psi>) = max (FOL_MaxVar2 \\<phi>) (FOL_MaxVar2 \\<psi>)\"\n  | \"FOL_MaxVar2 (FIff \\<phi> \\<psi>) = max (FOL_MaxVar2 \\<phi>) (FOL_MaxVar2 \\<psi>)\"\n  | \"FOL_MaxVar2 (FEx n \\<phi>) = max n (FOL_MaxVar2 \\<phi>)\"\n  | \"FOL_MaxVar2 (FAll n \\<phi>) = max n (FOL_MaxVar2 \\<phi>)\"\n\ntext{* We now define Finite partial functions (Fpf) from nat to nat, as in John Harrison's \"Handbook of Practical \n       Logic and Automated Reasoning\", and prove some basic facts about them. *}\n \ndatatype Fpf = Nil | Elem nat nat Fpf \n(*    Examples:\n      Nil ~ Id\\<^sub>n\\<^sub>a\\<^sub>t\n      Elem 10 20 Nil ~ (10 \\<mapsto> 20)Id\\<^sub>n\\<^sub>a\\<^sub>t \n      Elem 10 20 (Elem 30 40 Nil) ~ (10 \\<mapsto> 20) (30 \\<mapsto> 40)Id\\<^sub>n\\<^sub>a\\<^sub>t\n      Elem 10 30 (Elem 10 20 Nil) ~ (10 \\<mapsto> 30) (10 \\<mapsto> 20)Id\\<^sub>n\\<^sub>a\\<^sub>t = (1 \\<mapsto> 3)Id\\<^sub>n\\<^sub>a\\<^sub>t*)\n\n\n(* Fp function application *)\nprimrec assoc :: \"[Fpf, nat] \\<Rightarrow> nat\" \nwhere\n  \"assoc Nil k = k\"\n| \"assoc (Elem x y rest) k = (if x = k then y else (assoc rest k))\"\n\n(* associable lst k = True \\<longleftrightarrow> k occurs in any of the Elem-blocks\nas the first or second field \nExample associable (Elem 10 20 (Elem 30 40 Nil)) 30 = True\n        associable (Elem 10 20 (Elem 30 40 Nil)) 50 = False\n*)\nprimrec associable :: \"[Fpf, nat] \\<Rightarrow> bool\"\nwhere \n  \"associable Nil k = False\"\n| \"associable (Elem x y rest) k = ((x = k) \\<or> (associable rest k) \\<or> (y = k))\"\n\n(* Substitution of all variables  with their image under an fpf\n   which is itself if it does not occur in the domain. *) \nprimrec subst_t :: \"[FOL_Term, Fpf] \\<Rightarrow> FOL_Term\"\nwhere  \n  \"subst_t (FVar n) fpf = FVar (assoc fpf n)\"\n| \"subst_t (FConst y) fpf = FConst y\" \n\n(* Yields a variable that does not occur in a given fpf  *)\nprimrec alpha_convert_0 :: \"[Fpf] \\<Rightarrow> nat\"\nwhere\n  \"alpha_convert_0 Nil = 0\"\n| \"alpha_convert_0 (Elem x y rest) = (max (Suc x) (max (Suc y) (alpha_convert_0 rest)))\"\n\n(* Yields a variable that does neither occur in a given fpf nor in a given FOL_Formula *)\ndefinition alpha_convert :: \"[FOL_Formula, Fpf] \\<Rightarrow> nat\"\nwhere\n  \"alpha_convert p f = (max (Suc (FOL_MaxVar2 p)) (alpha_convert_0 f))\"\n\n(* Substitution of all variables  with their image under an fpf.\n   Gives new names to quantified variables even if it is not necessary\n   because that makes some of the following theorems easier to prove. *)\nfun subst_f :: \"[FOL_Formula, Fpf] \\<Rightarrow> FOL_Formula\"\nwhere \n  \"subst_f FTrue fpf = FTrue\"\n| \"subst_f FFalse fpf = FFalse\"\n| \"subst_f (FBelongs x y) fpf = (FBelongs (subst_t x fpf) (subst_t y fpf))\"\n| \"subst_f (FEquals x y) fpf = (FEquals (subst_t x fpf) (subst_t y fpf))\"\n| \"subst_f (FAnd p q) fpf = (FAnd (subst_f p fpf) (subst_f q fpf))\"\n| \"subst_f (FOr p q) fpf = (FOr (subst_f p fpf) (subst_f q fpf))\"\n| \"subst_f (FNot p) fpf = (FNot (subst_f p fpf))\"\n| \"subst_f (FImp p q) fpf = (FImp (subst_f p fpf) (subst_f q fpf))\"\n| \"subst_f (FIff p q) fpf = (FIff (subst_f p fpf) (subst_f q fpf))\"\n| \"subst_f (FEx n q) fpf = (FEx (alpha_convert (FEx n q) fpf) \n                                (subst_f q (Elem n (alpha_convert (FEx n q) fpf) fpf)))\"\n| \"subst_f (FAll n q) fpf = (FAll (alpha_convert  (FEx n q) fpf) \n                                  (subst_f q (Elem n (alpha_convert (FEx n q) fpf) fpf)))\"\n \n(* Updates an intepretation i :: nat \\<Rightarrow> Set according to a given Fpf f, i.e.\n   replaces i(n) with i ( f(n) ) for every n. *)\ndefinition Update2 :: \"[nat \\<Rightarrow> Set, Fpf] \\<Rightarrow> (nat \\<Rightarrow> Set)\"\nwhere \"Update2 i fpf k =  i (assoc fpf k) \"\n\n(* substitution of a single variable. Just convenience definitions for proof\n  of ex_definable_lemma in Class_Comprehension.thy. *)\ndefinition single_subst_t :: \"[FOL_Term, nat, nat] \\<Rightarrow> FOL_Term\"\nwhere \"single_subst_t x i j = subst_t x (Elem i j Nil)\"\n\ndefinition single_subst_f :: \"[FOL_Formula, nat, nat] \\<Rightarrow> FOL_Formula\"\nwhere \"single_subst_f x i j = subst_f x (Elem i j Nil)\"\n\nlemma MaxVar_comp: \"FOL_MaxVar \\<phi> \\<le> FOL_MaxVar2 \\<phi>\"\nby (induct \\<phi>, auto)\n\n(* Same as FOL_MaxVar_Dom but with FOL_MaxVar2 instead of FOL_MaxVar *)\nlemma FOL_MaxVar2_Dom: \"\\<forall>i. \\<forall>j. (\\<forall>k \\<le> FOL_MaxVar2 \\<phi>. i(k) = j(k)) \\<longrightarrow> FOL_True \\<phi> i \\<longleftrightarrow> FOL_True \\<phi> j\"\nusing FOL_MaxVar_Dom MaxVar_comp le_trans by blast\n\n(* Convenience lemma *)\nlemma FOL_MaxVar2_Dom_For_Use: \n\"(\\<And>k. k \\<le> FOL_MaxVar2 \\<phi> \\<Longrightarrow> i(k) = j(k)) \\<Longrightarrow> FOL_True \\<phi> i \\<longleftrightarrow> FOL_True \\<phi> j\"\nusing FOL_MaxVar2_Dom by blast\n\n(* Facts about updates.*)\n\nlemma Update_lemma_0: \"Update2 i Nil k = (i k)\"\nby (metis Update2_def assoc.simps(1)) \n\nlemma Update_lemma_0': \"Update2 i Nil = i\"\nusing Update_lemma_0 Update2_def by auto\n\nlemma Update_lemma_1: \"Update2 i (Elem k x2 rest) k = (i x2)\"\nby (metis Update2_def assoc.simps(2))\n\nlemma Update_lemma_2: \"k \\<noteq> l \\<Longrightarrow> Update2 i (Elem k x2 rest) l = (Update2 i rest) l\"\nby (metis Update2_def assoc.simps(2))\n\n(* Relation of Update to Update2  *)\nlemma Update_lemma_3: \"(Update (Update2 i fpf) x (i y)) = (Update2 i (Elem x y fpf))\"\nproof -\n  have \"(Update2 i (Elem x y fpf)) = \n   (\\<lambda> k::nat. if x = k then (i y) else (Update2 i fpf) k)\" using Update_lemma_2 Update_lemma_1 by auto\n  also have \"\\<dots> = (Update (Update2 i fpf) x (i y))\" using Update_def by auto \n  finally show ?thesis by auto\nqed \n\n(* Update and Update2 \"commute\" if the variable that is replaced by Update \n   does not occur in the fpf used by Update2 *)\nlemma Update_lemma_4: \n\"\\<And>i. \\<not> associable fpf x' \\<Longrightarrow> (Update2 (Update i x' y) fpf) = (Update (Update2 i fpf) x' y)\"\nproof (induct fpf)\n  fix i\n  assume \"\\<not> associable Nil x'\"\n  have \"Update2 (Update i x' y) Nil = Update i x' y\" using Update_lemma_0  by auto\n  then show \"Update2 (Update i x' y) Nil = Update (Update2 i Nil) x' y\" \n  using Update_lemma_0' by auto\n  next\n  fix x1 x2 fpf i\n  assume iasm: \"\\<And>i. (\\<not> associable fpf x' \\<Longrightarrow> Update2 (Update i x' y) fpf = Update (Update2 i fpf) x' y)\"\n  assume v: \"\\<not> associable (Elem x1 x2 fpf) x'\"\n  then have \"\\<not> associable fpf x'\" by auto\n  from v have w: \"x' \\<noteq> x1\" by auto\n  from v have w2: \"x' \\<noteq> x2\" by auto\n  have \"Update2 (Update i x' y) (Elem x1 x2 fpf) = \n  (Update (Update2 (Update i x' y) fpf) x1 ((Update i x' y) x2))\" using Update_lemma_3  by auto\n  also have \"\\<dots> =\n  (Update (Update (Update2 i fpf) x' y) x1 ((Update i x' y) x2))\" using iasm v by auto\n  also have \"\\<dots> =\n  (Update (Update (Update2 i fpf) x' y) x1 (i x2))\" using w2 Update_def by auto\n  also have \"\\<dots> =\n  (Update (Update (Update2 i fpf) x' y) x1 (i x2))\" using w2 Update_def by auto\n  then have \"\\<dots> =\n  (Update (Update (Update2 i fpf) x1 (i x2)) x' y)\" using w Update_def by auto\n  also have \"\\<dots> = \n  (Update (Update2 i (Elem x1 x2 fpf)) x' y)\" using Update_lemma_3 by auto\n  finally show \"Update2 (Update i x' y) (Elem x1 x2 fpf) = Update (Update2 i (Elem x1 x2 fpf)) x' y\"\n  .\nqed\n\n(* facts about associable *)\n\nlemma associable_0: \"\\<And>x. associable fpf x \\<Longrightarrow> x < (alpha_convert_0 fpf)\"\nby (induct fpf , auto, fastforce)\n\nlemma associable_1: \"\\<not> associable fpf (alpha_convert (FEx x1 \\<phi>) fpf)\"\nusing associable_0 alpha_convert_def max.cobounded2 not_less by fastforce \n\n(* Technical lemmas used in the proof of subst_lemma*)\nlemma subst_help_lemma_1: \"\\<And> x1 \\<phi> y. x' = (alpha_convert (FEx x1 \\<phi>) fpf) \\<Longrightarrow> (Update2 (Update i x' y) fpf) x' = y\"\nusing Update_def Update_lemma_4 associable_1 by auto\n\nlemma subst_help_lemma_2:\nassumes \"x' = alpha_convert (FEx x1 \\<phi>) fpf\"\nshows \"FOL_True \\<phi> (Update (Update (Update2 i fpf) x' y) x1 y) = \n       FOL_True \\<phi> (Update (Update2 i fpf) x1 y)\"\nusing Update_def alpha_convert_def assms\nby (simp add: FOL_MaxVar2_Dom Suc_n_not_le_n max_def) \n\n(* Substitution of variables in a formula can be replaced by updating the interpretation\n   and vice versa. *)\n\n(* TO DO: Write the proof below in Isar *) \nlemma substitution_lemma: \"\\<And> fpf i. (FOL_True (subst_f \\<phi> fpf) i) =  FOL_True \\<phi> (Update2 i fpf)\"\napply(induct \\<phi>)\napply(simp)+\napply (metis FOL_Eval.simps(1) FOL_Eval.simps(2) FOL_Term.exhaust Update2_def subst_t.simps(1) \n             subst_t.simps(2))\napply(simp)\napply (metis FOL_Eval.simps(1) FOL_Eval.simps(2) FOL_Term.exhaust Update2_def subst_t.simps(1) \n             subst_t.simps(2))\napply(simp)\napply(simp)\napply(simp)\napply(simp)\napply(simp)\nproof -\n  fix x1 \\<phi> fpf i\n  show \" (\\<And>fpf i. FOL_True (subst_f \\<phi> fpf) i = FOL_True \\<phi> (Update2 i fpf)) \\<Longrightarrow>\n       FOL_True (subst_f (FEx x1 \\<phi>) fpf) i = FOL_True (FEx x1 \\<phi>) (Update2 i fpf)\"\n  proof -\n    def \"x'\" \\<equiv> \"(alpha_convert (FEx x1 \\<phi>) fpf)\"\n    assume iasm: \"(\\<And>fpf i. FOL_True (subst_f \\<phi> fpf) i = FOL_True \\<phi> (Update2 i fpf))\"\n    have \"FOL_True (subst_f (FEx x1 \\<phi>) fpf) i = \n       FOL_True (FEx x' (subst_f \\<phi> (Elem x1 x' fpf))) i\" \n    using x'_def by auto\n    also have \"\\<dots> =\n      (\\<exists> y::Set. FOL_True (subst_f \\<phi> (Elem x1 x' fpf)) (Update i x' y))\" by auto\n    also have \"\\<dots> =\n      (\\<exists> y::Set. FOL_True \\<phi> (Update2 (Update i x' y) (Elem x1 x' fpf)))\" using iasm by auto\n    also have \"\\<dots> =\n      (\\<exists> y::Set. FOL_True \\<phi> (Update (Update2 (Update i x' y) fpf) x1 \n                                    ((Update2 (Update i x' y) fpf) x')))\"\n    by (metis Update_def Update_lemma_3 subst_help_lemma_1 x'_def)\n    also have \"\\<dots> =\n      (\\<exists> y::Set. FOL_True \\<phi> (Update (Update2 (Update i x' y) fpf) x1 y))\"\n    using subst_help_lemma_1 x'_def by auto\n    also have \"\\<dots> =\n      (\\<exists> y::Set. FOL_True \\<phi> (Update (Update (Update2 i fpf) x' y) x1 y))\"\n    by (simp add: Update_lemma_4 associable_1 x'_def)\n    also have \"\\<dots> = \n      (\\<exists> y::Set. FOL_True \\<phi> (Update (Update2 i fpf) x1 y))\"\n    using subst_help_lemma_2 x'_def by auto\n    also have \"\\<dots> = \n      FOL_True (FEx x1 \\<phi>) (Update2 i fpf) \" by auto\n    finally show ?thesis .\n   qed\n  next\n   fix x1 \\<phi> fpf i\n  show \" (\\<And>fpf i. FOL_True (subst_f \\<phi> fpf) i = FOL_True \\<phi> (Update2 i fpf)) \\<Longrightarrow>\n       FOL_True (subst_f (FAll x1 \\<phi>) fpf) i = FOL_True (FAll x1 \\<phi>) (Update2 i fpf)\"\n  proof -\n    def \"x'\" \\<equiv> \"(alpha_convert (FEx x1 \\<phi>) fpf)\"\n    assume iasm: \"(\\<And>fpf i. FOL_True (subst_f \\<phi> fpf) i = FOL_True \\<phi> (Update2 i fpf))\"\n    have \"FOL_True (subst_f (FAll x1 \\<phi>) fpf) i = \n       FOL_True (FAll x' (subst_f \\<phi> (Elem x1 x' fpf))) i\" \n    using x'_def by auto\n    also have \"\\<dots> =\n      (\\<forall> y::Set. FOL_True (subst_f \\<phi> (Elem x1 x' fpf)) (Update i x' y))\" by auto\n    also have \"\\<dots> =\n      (\\<forall> y::Set. FOL_True \\<phi> (Update2 (Update i x' y) (Elem x1 x' fpf)))\" using iasm by auto\n    also have \"\\<dots> =\n      (\\<forall> y::Set. FOL_True \\<phi> (Update (Update2 (Update i x' y) fpf) x1 \n                                     ((Update2 (Update i x' y) fpf) x')))\"\n    by (metis Update_def Update_lemma_3 subst_help_lemma_1 x'_def)\n    also have \"\\<dots> =\n      (\\<forall> y::Set. FOL_True \\<phi> (Update (Update2 (Update i x' y) fpf) x1 y))\"\n    using subst_help_lemma_1 x'_def by auto\n    also have \"\\<dots> =\n      (\\<forall> y::Set. FOL_True \\<phi> (Update (Update (Update2 i fpf) x' y) x1 y))\"\n    by (simp add: Update_lemma_4 associable_1 x'_def)\n    also have \"\\<dots> = \n      (\\<forall> y::Set. FOL_True \\<phi> (Update (Update2 i fpf) x1 y))\"\n    using subst_help_lemma_2 x'_def by auto\n    also have \"\\<dots> = \n      FOL_True (FAll x1 \\<phi>) (Update2 i fpf) \" by auto\n    finally show ?thesis .\n  qed\nqed  \n\n\n(* Similar to subst_lemma only replacing a single variable. *)\nlemma single_subst_lemma: \"\\<And> k l i. FOL_True (single_subst_f \\<phi> k l) i = \n                           FOL_True \\<phi> (Update i k (i l))\"\nusing FOL_MaxVar_Dom Update2_def Update_def single_subst_f_def substitution_lemma by auto\n\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/FOL_substitution.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.918480237330998, "lm_q2_score": 0.787931188173138, "lm_q1q2_score": 0.723699224713759}}
{"text": "section \\<open> Bouncing Ball \\<close>\n\ntheory utp_bouncing_ball\n  imports \"UTP1-Hybrid.utp_hybrid\"\nbegin\n  \nsubsection \\<open> State-space \\<close>\n  \ntext \\<open> We first setup the state-space and prove this is a topological (T2) space \\<close>\n  \nalphabet bball =\n  height :: real\n  velocity :: real\n\nsetup_lifting type_definition_bball_ext\n\ninstantiation bball_ext :: (t2_space) t2_space\nbegin\n  lift_definition open_bball_ext :: \"'a bball_scheme set \\<Rightarrow> bool\" is \"open\" .\n  instance by (intro_classes, (transfer, auto simp add: separation_t2)+)\nend\n\nsubsection \\<open> Constants \\<close>\n  \ntext \\<open> Next we define some constants; the ODE (ordinary differential equation) and its solution \\<close>\n  \nabbreviation grav :: real where\n\"grav \\<equiv> -9.81\"\n\nsubsection \\<open> Differential Equations and Solutions \\<close>\n\ntext \\<open> The ODE specifies two continuous variables, for velocity and height respectively. It\n  does not depend on time which makes it an autonomous ODE. \\<close>\n\nabbreviation grav_ode :: \"(real \\<times> real) ODE\" where\n\"grav_ode \\<equiv> (\\<lambda> t (v, h). (- grav, v))\"\n\ntext \\<open> We also present the following solution to the ODE, which is a function from initial values\n  of the continuous variables to a continuous function that shows how the variables change with time. \\<close>\n\nabbreviation grav_sol :: \"real \\<times> real \\<Rightarrow> real \\<Rightarrow> real \\<times> real\" where\n\"grav_sol \\<equiv> \\<lambda> (v\\<^sub>0, h\\<^sub>0) \\<tau>. (v\\<^sub>0 - grav * \\<tau>, v\\<^sub>0 * \\<tau> - grav * (\\<tau> * \\<tau>) / 2 + h\\<^sub>0)\"\n  \nlemma grav_ode_sol:\n  \"(\\<langle>{&velocity,&height} \\<bullet> grav_ode(ti)\\<rangle>\\<^sub>h) = {&velocity,&height} \\<leftarrow>\\<^sub>h \\<guillemotleft>grav_sol\\<guillemotright>($velocity, $height)\\<^sub>a(\\<guillemotleft>ti\\<guillemotright>)\\<^sub>a\"\nproof -\n  have 1:\"\\<forall>l>0. unique_on_strip 0 {0..l} grav_ode 1\"\n    by (auto, unfold_locales, auto intro!: continuous_on_Pair continuous_on_const continuous_on_fst continuous_on_snd simp add: lipschitz_on_def dist_Pair_Pair prod.case_eq_if)\n  have 2:\"\\<forall> v\\<^sub>0 h\\<^sub>0. \\<forall>l>0. ((grav_sol (v\\<^sub>0, h\\<^sub>0)) solves_ode grav_ode) {0..l} UNIV\"\n    by (clarify, ode_cert)\n  from 1 2 have sol:\"\\<forall> v\\<^sub>0 h\\<^sub>0. \\<forall>l>0. ((grav_sol (v\\<^sub>0, h\\<^sub>0)) usolves_ode grav_ode from 0) {0..l} UNIV\"\n    by (auto, rule_tac uos_impl_uniq_sol[where L=1], simp_all)\n  show ?thesis\n    apply (subst ode_solution[where \\<F>=\"grav_sol\"])\n    apply (simp_all add: lens_indep_sym)\n    using sol apply (simp)\n    apply (rel_auto)\n  done\nqed\n\nsubsection \\<open> System Definition \\<close>\n\ndefinition bouncing_ball :: \"(unit, bball) hyrel\" where\n  \"bouncing_ball =\n     (\\<^bold>c:velocity, \\<^bold>c:height) :=\\<^sub>r (0, 2.0) ;;\n      (\\<langle>{&velocity,&height} \\<bullet> grav_ode(ti)\\<rangle>\\<^sub>h until\\<^sub>h ($height\\<acute> \\<le>\\<^sub>u 0) ;;\n       \\<^bold>c:velocity :=\\<^sub>r (- 0.8 * &\\<^bold>c:velocity))\\<^sup>\\<star>\"\n  \nsubsection \\<open> Example Properties \\<close>\n  \nlemma \"\\<lceil>$height\\<acute> \\<ge>\\<^sub>u 0\\<rceil>\\<^sub>h \\<sqsubseteq> bouncing_ball\"\n  apply (simp add: bouncing_ball_def)\n  apply (rule ustar_inductr)\n  apply (rel_simp)\noops\n  \nend\n", "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/hybrid/examples/utp_bouncing_ball.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.918480237330998, "lm_q2_score": 0.7879311856832191, "lm_q1q2_score": 0.7236992224268177}}
{"text": "(*<*) \ntheory KoenigLemma\n imports Main\n\"TeoriaCompacidadIngles\"  \nbegin\n(*>*)\nsection \\<open> K\u00f6nig's Lemma Theory  \\cite{Fitting} \\<close>\n\ntext\\<open>\nUsing the Compactness Theorem for propositional logic, we formalise K\u00f6nig's Lemma for enumerable trees:\n\\par \nAny infinite enumerable finitely branching tree has an infinite path.\n\\<close> \n\ntype_synonym 'a rel = \"('a \\<times> 'a) set\"\n\ndefinition irreflexive_on ::  \"'a set \\<Rightarrow> 'a rel \\<Rightarrow> bool\"\n where \"irreflexive_on A r \\<equiv>  (\\<forall>x\\<in>A. (x, x) \\<notin> r)\"\n\ndefinition transitive_on :: \"'a set \\<Rightarrow> 'a rel \\<Rightarrow> bool\"\n  where \"transitive_on A r \\<equiv>\n (\\<forall>x\\<in>A. \\<forall>y\\<in>A. \\<forall>z\\<in>A. (x, y) \\<in> r \\<and> (y, z) \\<in> r \\<longrightarrow> (x, z) \\<in> r)\"\n\ndefinition total_on :: \"'a set \\<Rightarrow> 'a rel \\<Rightarrow> bool\"\n  where \"total_on A r \\<equiv> (\\<forall>x\\<in>A. \\<forall>y\\<in>A. x \\<noteq> y \\<longrightarrow> (x, y) \\<in> r \\<or> (y, x) \\<in> r)\"\n\ndefinition minimum ::  \"'a set \\<Rightarrow> 'a \\<Rightarrow>'a rel \\<Rightarrow> bool\"\n  where \"minimum A a r \\<equiv>  (a\\<in>A \\<and> (\\<forall>x\\<in>A. x \\<noteq> a  \\<longrightarrow> (a,x) \\<in> r))\"\n\ndefinition predecessors :: \"'a set \\<Rightarrow>'a \\<Rightarrow>'a rel  \\<Rightarrow> 'a set\"\n  where \"predecessors A a r \\<equiv> {x\\<in>A.(x, a) \\<in> r}\"\n\ndefinition height ::  \"'a set \\<Rightarrow>'a \\<Rightarrow> 'a rel \\<Rightarrow> nat\"\n  where \"height A a r   \\<equiv>  card (predecessors A a r)\"\n\ndefinition level ::  \"'a set \\<Rightarrow> 'a rel \\<Rightarrow> nat \\<Rightarrow>'a set\"\n  where \"level A r n \\<equiv> {x\\<in>A. height A x r = n}\"\n\ndefinition imm_successors ::  \"'a set \\<Rightarrow> 'a \\<Rightarrow> 'a rel \\<Rightarrow> 'a set\"\n  where \"imm_successors A a r \\<equiv> \n {x\\<in>A. (a,x)\\<in> r \\<and> height A x r = (height A a r)+1}\" \n\ndefinition strict_part_order ::  \"'a set \\<Rightarrow> 'a rel \\<Rightarrow> bool\"\n  where  \"strict_part_order A r \\<equiv> irreflexive_on A r \\<and> transitive_on A r\"\n\nlemma minimum_element:\n  assumes  \"strict_part_order A r\" and \"minimum A a r\" and \"r={}\"\n  shows \"A={a}\"\nproof(rule ccontr)\n  assume hip: \"A \\<noteq> {a}\" show False\n  proof(cases)\n    assume  hip1: \"A={}\"\n    have \"a\\<in>A\" using `minimum A a r` by(unfold minimum_def, auto) \n    thus False using hip1 by auto\n  next\n    assume  \"A \\<noteq> {}\"\n    hence \"\\<exists>x. x\\<noteq>a \\<and> x\\<in>A\" using hip by auto\n    then obtain x where  \"x\\<noteq>a \\<and> x\\<in>A\" by auto\n    hence \"(a,x)\\<in>r\"  using `minimum A a r` by(unfold minimum_def, auto)\n    hence \"r \\<noteq> {}\" by auto\n    thus False using `r={}` by auto\n  qed\nqed\n\nlemma spo_uniqueness_min:\n  assumes  \"strict_part_order A r\" and  \"minimum A a r\" and \"minimum A b r\" \n  shows \"a=b\"\nproof(rule ccontr)\n  assume hip: \"a \\<noteq> b\"\n  have \"a\\<in>A\"and \"b\\<in>A\" using assms(2-3) by(unfold minimum_def, auto)\n  show False\n  proof(cases)\n    assume \"r = {}\"\n    hence  \"A={a} \\<and> A={b}\"  using assms(1-3) minimum_element[of A r] by auto\n    thus False using hip by auto\n  next\n    assume \"r\\<noteq>{}\"\n    hence 1: \"(a,b)\\<in>r \\<and> (b,a)\\<in>r\" using hip assms(2-3)\n      by(unfold minimum_def, auto)    \n    have  irr: \"irreflexive_on A r\" and tran: \"transitive_on A r\"     \n    using assms(1) by(unfold strict_part_order_def, auto)\n    have  \"(a,a)\\<in>r\" using  `a\\<in>A`  `b\\<in>A` 1 tran by(unfold transitive_on_def, blast)\n    thus False using  `a\\<in>A`  irr  by(unfold irreflexive_on_def, blast)\n  qed\nqed\n\nlemma emptyness_pred_min_spo:\n  assumes  \"minimum A a r\" and \"strict_part_order A r\"\n  shows  \"predecessors A a r = {}\"\nproof(rule ccontr)\n  have  irr:  \"irreflexive_on A r\" and tran: \"transitive_on A r\" using assms(2)\n  by(unfold strict_part_order_def, auto)\n  assume 1: \"predecessors A a r \\<noteq> {}\" show False\n  proof-\n    have \"\\<exists>x\\<in>A. (x,a)\\<in> r\" using 1  by(unfold predecessors_def, auto)\n    then obtain x where \"x\\<in>A\" and \"(x,a)\\<in> r\" by auto\n    hence \"x\\<noteq>a\" using irr by (unfold irreflexive_on_def, auto)\n    hence \"(a,x)\\<in>r\" using  `x\\<in>A` `minimum A a r` by(unfold minimum_def, auto)\n    have  \"a\\<in>A\" using  `minimum A a r` by(unfold minimum_def, auto)\n    hence \"(a,a)\\<in>r\" using `(a,x)\\<in>r`  `(x,a)\\<in> r`  `x\\<in>A`  tran \n      by(unfold transitive_on_def, blast)\n    thus False using `(a,a)\\<in>r` `a\\<in>A` irr  irreflexive_on_def\n      by (unfold irreflexive_on_def, auto)\n  qed\nqed\n\nlemma  emptyness_pred_min_spo2:\n  assumes  \"strict_part_order A r\" and  \"minimum A a r\" \n  shows \"\\<forall>x\\<in>A.(predecessors A x r = {}) \\<longleftrightarrow> (x=a)\" \nproof\n  fix x\n  assume  \"x \\<in> A\" \n  show \"(predecessors A x r = {}) \\<longleftrightarrow> (x = a)\"\n  proof-\n    have 1: \"a \\<in> A\" using  `minimum A a r`  by(unfold minimum_def, auto)\n    have 2: \"(predecessors A x r = {})\\<longrightarrow> (x=a)\"\n    proof(rule impI)\n      assume h: \"predecessors A x r = {}\"  show \"x=a\"\n      proof(rule ccontr)\n      assume  \"x \\<noteq> a\" \n      hence  \"(a,x)\\<in> r\" using  `x \\<in> A` `minimum A a r`\n        by(unfold minimum_def, auto)     \n      hence  \"a \\<in> predecessors A x r\"\n        using 1 by(unfold  predecessors_def,auto)\n      thus False using h by auto \n    qed\n  qed\n  have 3: \"x=a \\<longrightarrow> (predecessors A x r = {})\"\n  proof(rule impI)\n    assume \"x=a\"\n    thus \"predecessors A x r = {}\" \n      using assms emptyness_pred_min_spo[of A a]  by auto\n  qed\n  show ?thesis using 2 3 by auto\n   qed\nqed\n\nlemma height_minimum:\n  assumes  \"strict_part_order A r\" and  \"minimum A a r\"\n  shows \"height  A a r = 0\"\nproof-\n  have  \"a\\<in>A\" using  `minimum A a r` by(unfold minimum_def, auto)\n  hence \"predecessors A a r = {}\"\n    using assms emptyness_pred_min_spo2[of A r]  by auto\n  thus \"height  A a r = 0\" by(unfold height_def, auto) \nqed\n\nlemma zero_level:\n  assumes  \"strict_part_order A r\" \n  and \"minimum A a r\"  and  \"\\<forall>x\\<in>A. finite (predecessors A x r)\"  \n  shows \"(level A r 0) = {a}\"\nproof-\n  have \"\\<forall>x\\<in>A.(card (predecessors A x r) = 0) \\<longleftrightarrow> (x=a)\"\n  using  assms emptyness_pred_min_spo2[of A r a] card_eq_0_iff by auto\n  hence 1:  \"\\<forall>x\\<in>A.(height A x r = 0) \\<longleftrightarrow> (x=a)\"\n    by(unfold height_def, auto)\n  have \"a\\<in>A\" using  `minimum A a r` by(unfold minimum_def, auto)\n  thus ?thesis using assms 1  level_def[of A r 0] by auto\nqed\n\nlemma min_predecessor:\n  assumes  \"minimum A a r\"\n  shows  \"\\<forall>x\\<in>A. x\\<noteq>a \\<longrightarrow> a\\<in>predecessors A x r\"\nproof\n  fix x\n  assume \"x\\<in>A\"\n  show \"x \\<noteq> a \\<longrightarrow> a \\<in> predecessors A x r\"\n  proof(rule impI)\n    assume  \"x \\<noteq> a\"\n    show \"a \\<in> predecessors A x r\"\n    proof-\n      have \"(a,x)\\<in>r\" using `x\\<in>A` `x \\<noteq> a` `minimum A a r` \n        by(unfold minimum_def, auto)\n      hence \"a\\<in>A\"  using  `minimum A a r` by(unfold minimum_def, auto)\n      thus \"a\\<in>predecessors A x r\" using `(a,x)\\<in>r` \n        by(unfold predecessors_def, auto)\n    qed\n  qed\nqed\n\nlemma spo_subset_preservation: \n  assumes \"strict_part_order A r\" and \"B\\<subseteq>A\" \n  shows \"strict_part_order B r\" \nproof-  \n  have  \"irreflexive_on A r\" and \"transitive_on A r\" \n    using  `strict_part_order A r` \n    by(unfold strict_part_order_def, auto)\n  have 1: \"irreflexive_on B r\"\n  proof(unfold irreflexive_on_def)\n    show \"\\<forall>x\\<in>B. (x, x) \\<notin> r\"\n    proof\n      fix x\n      assume \"x\\<in>B\" \n      hence \"x\\<in>A\" using  `B\\<subseteq>A` by auto\n      thus \"(x,x)\\<notin>r\" using  `irreflexive_on A r`\n        by (unfold irreflexive_on_def, auto)\n    qed\n  qed\n  have 2:  \"transitive_on B r\"\n  proof(unfold transitive_on_def)\n    show \"\\<forall>x\\<in>B. \\<forall>y\\<in>B. \\<forall>z\\<in>B. (x, y) \\<in> r \\<and> (y, z) \\<in> r \\<longrightarrow> (x, z) \\<in> r\"\n    proof\n      fix x assume \"x\\<in>B\"\n      show \"\\<forall>y\\<in>B. \\<forall>z\\<in>B. (x, y) \\<in> r \\<and> (y, z) \\<in> r \\<longrightarrow> (x, z) \\<in> r\"\n      proof\n        fix y  assume \"y\\<in>B\"\n        show \"\\<forall>z\\<in>B. (x, y) \\<in> r \\<and> (y, z) \\<in> r \\<longrightarrow> (x, z) \\<in> r\"\n        proof \n          fix z  assume \"z\\<in>B\"\n          show \"(x, y) \\<in> r \\<and> (y, z) \\<in> r \\<longrightarrow> (x, z) \\<in> r\"\n          proof(rule impI)\n            assume hip: \"(x, y) \\<in> r \\<and> (y, z) \\<in> r\" \n            show \"(x, z) \\<in> r\"\n          proof-\n            have \"x\\<in>A\" and  \"y\\<in>A\" and  \"z\\<in>A\" using `x\\<in>B` `y\\<in>B` `z\\<in>B` `B\\<subseteq>A`\n              by auto\n            thus \"(x, z) \\<in> r\" using hip `transitive_on A  r` by(unfold transitive_on_def, blast)\n            qed\n          qed\n        qed\n      qed\n    qed\n  qed\n  thus \"strict_part_order B r\"\n    using 1 2  by(unfold strict_part_order_def, auto)   \nqed\n\nlemma total_ord_subset_preservation:\n  assumes \"total_on A r\" and  \"B\\<subseteq>A\"\n  shows \"total_on B r\"\nproof(unfold total_on_def)\n  show  \"\\<forall>x\\<in>B. \\<forall>y\\<in>B. x \\<noteq> y \\<longrightarrow> (x, y) \\<in> r \\<or> (y, x) \\<in> r\"\n  proof\n    fix x\n    assume \"x\\<in>B\" show \" \\<forall>y\\<in>B. x \\<noteq> y \\<longrightarrow> (x, y) \\<in> r \\<or> (y, x) \\<in> r\"\n    proof \n      fix y\n      assume \"y\\<in>B\" \n      show  \"x \\<noteq> y \\<longrightarrow> (x, y) \\<in> r \\<or> (y, x) \\<in> r\"  \n      proof(rule impI)\n        assume  \"x \\<noteq> y\"\n        show \"(x, y) \\<in> r \\<or> (y, x) \\<in> r\"\n        proof-\n          have \"x\\<in>A \\<and> y\\<in>A\" using  `x\\<in>B`  `y\\<in>B` `B\\<subseteq>A` by auto\n          thus  \"(x, y) \\<in> r \\<or> (y, x) \\<in> r\" \n            using  `x \\<noteq> y` `total_on A r` by(unfold total_on_def, auto) \n        qed\n      qed\n    qed\n  qed\nqed\n\ndefinition maximum ::  \"'a set \\<Rightarrow> 'a \\<Rightarrow>'a rel \\<Rightarrow> bool\"\n  where \"maximum A a r \\<equiv>  (a\\<in>A \\<and> (\\<forall>x\\<in>A. x \\<noteq> a \\<longrightarrow> (x,a) \\<in> r))\"\n\nlemma maximum_strict_part_order:\n  assumes \"strict_part_order A r\" and \"A\\<noteq>{}\" and \"total_on A r\" \n  and \"finite A\"\n  shows \"(\\<exists>a. maximum A a r)\" \nproof-\n  have \"strict_part_order A r \\<Longrightarrow> A\\<noteq>{} \\<Longrightarrow> total_on A r \\<Longrightarrow> finite A\n  \\<Longrightarrow> (\\<exists>a. maximum A a r)\"  using assms(4)\n  proof(induct A rule:finite_induct)\n    case empty\n    then show ?case by auto\n  next\n    case (insert x A)  \n    show \"(\\<exists>a. maximum (insert x A) a r)\"\n  proof(cases \"A={}\")\n    case True\n    hence \"insert x A ={x}\" by simp\n    hence  \"maximum (insert x A) x r\" by(unfold maximum_def, auto)\n    then show ?thesis by auto\n  next\n    case False\n    assume \"A \\<noteq> {}\"\n    show \"\\<exists>a. maximum (insert x A) a r\"\n    proof-\n      have 1: \"strict_part_order A r\" \n        using insert(4) spo_subset_preservation by auto\n      have 2: \"total_on A r\" using insert(6) total_ord_subset_preservation by auto\n      have \"\\<exists>a. maximum A a r\" using 1  `A\\<noteq>{}`  insert(1) 2 insert(3) by auto\n      then obtain a where a: \"maximum A a r\" by auto\n      hence  \"a\\<in>A\" and \"\\<forall>y\\<in>A. y \\<noteq> a  \\<longrightarrow> (y,a) \\<in> r\" by(unfold maximum_def, auto)\n      have 3: \"a\\<in>(insert x A)\" using `a\\<in>A`  by auto\n      have 4: \"a\\<noteq>x\" using `a\\<in>A` and  `x \\<notin> A` by auto\n      have  \"x\\<in>(insert x A)\" by auto\n      hence \"(a,x)\\<in>r \\<or> (x,a)\\<in>r\" using 3 4 `total_on (insert x A) r`\n        by(unfold total_on_def, auto)\n      thus \"\\<exists>a. maximum (insert x A) a r\"\n      proof(rule disjE)\n        have  \"transitive_on (insert x A) r\" using  insert(4) \n          by(unfold strict_part_order_def, auto) \n        assume casoa: \"(a, x) \\<in> r\"  \n        have  \"\\<forall>z\\<in>(insert x A). z \\<noteq> x  \\<longrightarrow> (z,x) \\<in> r\"\n        proof\n          fix z\n          assume hip1: \"z \\<in> (insert x A)\"\n          show \"z \\<noteq> x \\<longrightarrow> (z, x) \\<in> r\"\n          proof(rule impI)\n            assume \"z \\<noteq> x\"\n            hence hip2:  \"z\\<in>A\" using `z \\<in> (insert x A)` by auto \n            thus \"(z, x) \\<in> r\" \n            proof(cases)\n              assume \"z=a\" \n              thus \"(z, x) \\<in> r\" using `(a, x) \\<in> r` by auto \n            next\n              assume \"z\\<noteq>a\"\n              hence \"(z,a) \\<in> r\" using  `z\\<in>A` `\\<forall>y\\<in>A. y \\<noteq> a  \\<longrightarrow> (y,a) \\<in> r` by auto\n              have \"a\\<in>(insert x A)\" and \"z\\<in>(insert x A)\" and  \"x\\<in>(insert x A)\"\n                using  `a\\<in>A` `z\\<in>A` by auto            \n              thus  \"(z, x) \\<in> r\"\n                using  `(z,a) \\<in> r` `(a, x) \\<in> r`  `transitive_on (insert x A) r`\n                by(unfold transitive_on_def, blast) \n            qed\n          qed\n        qed\n        thus \"\\<exists>a. maximum (insert x A) a r\"\n          using  `x\\<in>(insert x A)` by(unfold maximum_def, auto)\n      next\n        assume casob: \"(x, a) \\<in> r\"\n        have  \"\\<forall>z\\<in>(insert x A). z \\<noteq> a  \\<longrightarrow> (z,a) \\<in> r\"\n        proof\n          fix z\n          assume hip1: \"z \\<in> (insert x A)\"\n          show \"z \\<noteq> a \\<longrightarrow> (z, a) \\<in> r\"\n          proof(rule impI)\n            assume \"z \\<noteq> a\" show  \"(z, a) \\<in> r\"\n            proof- \n              have \"z\\<in>A \\<or> z=x\" using `z \\<in> (insert x A)` by auto\n              thus  \"(z, a) \\<in> r\"\n              proof(rule disjE)\n                assume  \"z \\<in> A\"\n                thus  \"(z, a) \\<in> r\" \n                  using  `z \\<noteq> a` `\\<forall>y\\<in>A. y \\<noteq> a  \\<longrightarrow> (y,a) \\<in> r` by auto\n              next\n                assume \"z = x\" \n                thus  \"(z, a) \\<in> r\" using `(x, a) \\<in> r` by auto\n              qed\n            qed\n          qed\n        qed\n        thus \"\\<exists>a. maximum (insert x A) a r\" \n          using `a\\<in>(insert x A)`  by(unfold maximum_def, auto)      \n      qed\n    qed\n  qed\nqed\n  thus ?thesis using assms by auto\nqed\n\nlemma finiteness_union_finite_sets:\n  fixes S :: \"'a  \\<Rightarrow>  'a set\" \n  assumes \"\\<forall>x. finite (S x)\" and \"finite A\"\n  shows \"finite (\\<Union>a\\<in>A. (S a))\" using assms by auto\n\nlemma uniqueness_level_aux:\n  assumes \"k>0\"\n  shows \"(level A r n) \\<inter> (level A r (n+k)) = {}\" \nproof(rule ccontr)\n  assume  \"level A r n \\<inter> level A r (n + k) \\<noteq> {}\" \n  hence  \"\\<exists>x. x\\<in>(level A r n) \\<inter> level A r (n + k)\" by auto\n  then obtain x where \"x\\<in>(level A r n) \\<inter> level A r (n + k)\" by auto\n  hence \"x\\<in>A \\<and> height A x r = n\" and \"x\\<in>A \\<and> height A x r = n+k\"\n    by(unfold level_def, auto)\n  thus False using `k>0` by auto\nqed\n\nlemma uniqueness_level:\n  assumes \"n\\<noteq>m\" \n  shows \"(level A r n) \\<inter> (level A r m) = {}\"\nproof-\n  have \"n < m \\<or> m < n\" using assms by auto\n  thus ?thesis\n  proof(rule disjE)\n    assume \"n < m\"\n    hence \"\\<exists>k. k>0 \\<and> m=n+k\" by arith\n    thus ?thesis using uniqueness_level_aux[of _ A r] by auto\n  next\n    assume \"m < n\"\n    hence \"\\<exists>k. k>0 \\<and> n=m+k\" by arith\n    thus ?thesis using  uniqueness_level_aux[of _ A r] by auto\n  qed\nqed\n \ndefinition tree ::  \"'a set \\<Rightarrow> 'a rel \\<Rightarrow> bool\"\n  where \"tree A r  \\<equiv>\n r \\<subseteq> A \\<times> A \\<and> r\\<noteq>{} \\<and> (strict_part_order A r)  \\<and>  (\\<exists>a. minimum A a r) \\<and>\n (\\<forall>a\\<in>A. finite (predecessors A a r) \\<and> (total_on (predecessors A  a r) r))\"\n\ndefinition finite_tree::  \"'a set \\<Rightarrow> 'a rel \\<Rightarrow> bool\"\n  where\n\"finite_tree A r  \\<equiv> tree A r \\<and> finite A\"\n\nabbreviation  infinite_tree::  \"'a set \\<Rightarrow> 'a rel \\<Rightarrow> bool\" \n  where\n\"infinite_tree A r  \\<equiv>  tree A r \\<and> \\<not> finite A\"\n\ndefinition enumerable_tree :: \"'a set \\<Rightarrow> 'a rel \\<Rightarrow> bool\"  where\n \"enumerable_tree A r \\<equiv> \\<exists>g. enumeration (g:: nat \\<Rightarrow>'a)\"\n\ndefinition finite_branches ::  \"'a set \\<Rightarrow> 'a rel \\<Rightarrow> bool\"\n  where  \"finite_branches  A r \\<equiv> (\\<forall>x\\<in>A. finite (imm_successors A x r))\"\n\ndefinition sub_linear_order :: \"'a set \\<Rightarrow> 'a set \\<Rightarrow> 'a rel \\<Rightarrow> bool\"\n  where \"sub_linear_order B A r  \\<equiv>  B\\<subseteq>A \\<and> (strict_part_order A r) \\<and> (total_on B r)\"\n\ndefinition path ::  \"'a set \\<Rightarrow> 'a set \\<Rightarrow> 'a rel \\<Rightarrow> bool\"\n  where \"path  B A r  \\<equiv>\n (sub_linear_order B A r) \\<and>\n (\\<forall>C. B \\<subseteq> C \\<and> sub_linear_order C A r \\<longrightarrow> B = C)\"\n\ndefinition finite_path:: \"'a set \\<Rightarrow> 'a set \\<Rightarrow> 'a rel \\<Rightarrow> bool\"\n  where \"finite_path B A r \\<equiv>  path  B A r \\<and> finite B\"\n\ndefinition infinite_path:: \"'a set \\<Rightarrow> 'a set \\<Rightarrow> 'a rel \\<Rightarrow> bool\"\n  where \"infinite_path B A r \\<equiv>  path  B A r \\<and>  \\<not> finite B\"\n\nlemma tree: \n  assumes \"tree A r\"\n  shows\n  \"r \\<subseteq> A \\<times> A\" and \"r\\<noteq>{}\" \n  and  \"strict_part_order A r\"\n  and  \"\\<exists>a. minimum A a r\" \n  and  \"(\\<forall>a\\<in>A. finite (predecessors A a r) \\<and> (total_on (predecessors A  a r) r))\"\n  using `tree A r` by(unfold tree_def, auto)\n\nlemma non_empty: \n  assumes \"tree A r\" shows \"A\\<noteq>{}\"\nproof-\n  have \"\\<exists>a. minimum A a r\" using  `tree A r` tree[of A r] by auto\n  hence \"\\<exists>a. a\\<in>A\"  by(unfold minimum_def, auto)\n  thus  \"A\\<noteq>{}\" by auto\nqed\n\nlemma predecessors_spo:\n  assumes \"tree A r\" \n  shows  \"\\<forall>x\\<in>A. strict_part_order (predecessors A x r) r\"\nproof- \n  have \"irreflexive_on A r\" and \"transitive_on A r\"  using `tree A r`\n    by(unfold tree_def,unfold strict_part_order_def,auto) \n  thus ?thesis\nproof(unfold strict_part_order_def)\n  show \"\\<forall>x\\<in>A. irreflexive_on (predecessors A x r) r \\<and>\n        transitive_on (predecessors A x r) r\"\n  proof\n    fix x\n    assume \"x\\<in>A\"\n    show \"irreflexive_on (predecessors A x r) r \\<and> transitive_on (predecessors A x r) r\"\n    proof-\n      have 1: \"irreflexive_on (predecessors A x r) r\"\n      proof(unfold irreflexive_on_def)\n        show \"\\<forall>y\\<in>(predecessors A x r). (y, y) \\<notin> r\"\n        proof\n          fix y\n          assume \"y\\<in>(predecessors A x r)\"\n          hence \"y\\<in>A\" by(unfold predecessors_def,auto)\n          thus \"(y, y) \\<notin> r\" using `irreflexive_on A r` by(unfold irreflexive_on_def,auto)\n        qed\n      qed\n      have 2: \"transitive_on (predecessors A x r) r\"\n      proof(unfold transitive_on_def)\n        let ?B= \"(predecessors A x r)\"\n        show \"\\<forall>w\\<in>?B. \\<forall>y\\<in>?B. \\<forall>z\\<in>?B. (w, y) \\<in> r \\<and> (y, z) \\<in> r \\<longrightarrow> (w, z) \\<in> r\"\n        proof\n          fix w assume \"w\\<in>?B\"\n         show \"\\<forall>y\\<in>?B. \\<forall>z\\<in>?B. (w, y) \\<in> r \\<and> (y, z) \\<in> r \\<longrightarrow> (w, z) \\<in> r\"\n         proof\n           fix y assume \"y\\<in>?B\"\n           show \"\\<forall>z\\<in>?B. (w, y) \\<in> r \\<and> (y, z) \\<in> r \\<longrightarrow> (w, z) \\<in> r\"\n           proof \n             fix z  assume \"z\\<in>?B\"\n             show \"(w, y) \\<in> r \\<and> (y, z) \\<in> r \\<longrightarrow> (w, z) \\<in> r\"\n             proof(rule impI)\n               assume hip: \"(w, y) \\<in> r \\<and> (y, z) \\<in> r\" \n               show \"(w, z) \\<in> r\"\n               proof-\n                 have  \"w\\<in>A\" and  \"y\\<in>A\" and  \"z\\<in>A\" using `w\\<in>?B` `y\\<in>?B` `z\\<in>?B`\n                   by(unfold predecessors_def,auto)\n                 thus \"(w, z) \\<in> r\"\n                   using hip `transitive_on A  r` by(unfold transitive_on_def, blast)\n                 qed\n               qed\n             qed\n           qed\n         qed\n       qed\n       show\n        \"irreflexive_on (predecessors A x r) r \\<and> transitive_on (predecessors A x r) r\"\n       using 1 2 by auto\n       qed\n     qed\n  qed\nqed\n       \nlemma predecessors_maximum:\n  assumes \"tree A r\" and  \"minimum A a r\"\n  shows \"\\<forall>x\\<in>A. x\\<noteq>a \\<longrightarrow> (\\<exists>b. maximum (predecessors A x r) b r)\"\nproof\n  fix x\n  assume \"x\\<in>A\"\n  show \"x\\<noteq>a \\<longrightarrow> (\\<exists>b. maximum (predecessors A x r) b r)\"\n  proof(rule impI)\n    assume \"x\\<noteq>a\"\n    show \"(\\<exists>b. maximum (predecessors A x r) b r)\" \n    proof-\n      have 1: \"strict_part_order (predecessors A x r) r\" \n        using  `tree A r` `x\\<in>A`  predecessors_spo by auto\n      have 2: \"total_on (predecessors A x r) r\" and \n           3: \"finite (predecessors A x r)\" and  \"r \\<subseteq> A \\<times> A\"\n        using  `tree A r` `x\\<in>A` by(unfold tree_def, auto)\n      have 4:  \"(predecessors A x r)\\<noteq>{}\" \n        using  `r \\<subseteq> A \\<times> A`  `minimum A a r`  `x\\<in>A`  `x\\<noteq>a` \n              min_predecessor[of A a] by auto\n      have 5: \"A\\<noteq>{}\" using `tree A r` non_empty by auto\n      show \"(\\<exists>b. maximum (predecessors A x r) b r)\" \n        using 1 2 3 4 5  maximum_strict_part_order by auto\n    qed\n  qed\nqed\n\nlemma non_empty_preds_in_tree: \n  assumes  \"tree A r\"  and  \"card (predecessors A x r) = n+1\"\n  shows  \"x\\<in>A\"\nproof- \n  have  \"r \\<subseteq> A \\<times> A\"  using `tree A r` by(unfold tree_def, auto)\n  have \"(predecessors A x r) \\<noteq> {}\" using assms(2) by auto\n  hence \"\\<exists>y\\<in>A. (y,x)\\<in>r\" by (unfold predecessors_def,auto)\n  thus  \"x\\<in>A\" using  `r \\<subseteq> A \\<times> A` by auto\nqed\n\nlemma imm_predecessor:\n  assumes  \"tree A r\"   \n  and  \"card (predecessors A x r) = n+1\" and\n  \"maximum (predecessors A x r) b r\"\n  shows \"height A b r = n\"\nproof- \n  have \"transitive_on A r\" and  \"r \\<subseteq> A \\<times> A\" and  \"irreflexive_on A r\"\n    using `tree A r`\n    by (unfold tree_def, unfold strict_part_order_def, auto)\n  have  \"x\\<in>A\" using  assms(1) assms(2)  non_empty_preds_in_tree by auto\n  have \"strict_part_order (predecessors A x r) r\"\n    using `x\\<in>A` `tree A r` predecessors_spo[of A r] by auto\n  hence  \"irreflexive_on (predecessors A x r) r\" and\n         \"transitive_on (predecessors A x r) r\"\n    by(unfold strict_part_order_def, auto) \n  have \"b\\<in>(predecessors A x r)\" \n    using `maximum (predecessors A x r) b r` by(unfold maximum_def, auto)\n  have \"total_on (predecessors A x r) r\"\n    using `x\\<in>A` `tree A r` by(unfold tree_def, auto)\n  have \"card (predecessors A x r)>0 \" using assms(2) by auto\n  hence 1: \"finite (predecessors A x r)\"  using card_gt_0_iff by blast\n  have  2: \"b\\<in>(predecessors A x r)\" \n    using assms(3) by (unfold maximum_def,auto)\n  hence \"card ((predecessors A x r)-{b}) = n\" \n    using 1  `card (predecessors A x r) = n+1`\n    card_Diff_singleton[of b \"(predecessors A x r)\" ] by auto\n  have \"(predecessors A b r) = ((predecessors A x r)-{b})\"\n  proof(rule equalityI)\n    show \"(predecessors A b r) \\<subseteq> (predecessors A x r - {b})\" \n    proof\n      fix y\n      assume  \"y\\<in> (predecessors A b r)\"\n      hence \"y\\<in>A\" and  \"(y,b)\\<in> r\" by (unfold predecessors_def,auto)\n      hence \"y\\<noteq>b\" using `irreflexive_on A r` by(unfold irreflexive_on_def,auto)\n      have \"(b,x)\\<in>r\" using 2 by (unfold predecessors_def,auto)\n      hence \"b\\<in>A\"  using `r \\<subseteq> A \\<times> A` by auto\n      have \"(y,x)\\<in> r\" using `x\\<in>A` `y\\<in>A` `b\\<in>A`  `(y,b)\\<in> r`  `(b,x)\\<in>r` `transitive_on A r`\n        by(unfold transitive_on_def, blast)    \n      show \"y\\<in>(predecessors A x r - {b})\" \n        using `y\\<in>A` `(y,x)\\<in> r` `y\\<noteq>b` by(unfold predecessors_def, auto)\n    qed\n  next\n    show \"(predecessors A x r - {b}) \\<subseteq> (predecessors A b r)\"\n    proof\n      fix y\n      assume hip: \"y\\<in>(predecessors A x r - {b})\" \n      hence \"y\\<noteq>b\" and  \"y\\<in>A\" by(unfold predecessors_def, auto)\n      have \"(y,b)\\<in> r\" using hip `maximum (predecessors A x r) b r`\n        by(unfold maximum_def,auto)\n      thus \"y\\<in> (predecessors A b r)\" using `y\\<in>A`\n        by(unfold predecessors_def, auto)\n    qed\n  qed\n  hence 3:  \"card (predecessors A b r) = card (predecessors A x r - {b})\" \n    by auto\n  have \"finite (predecessors A x r)\" using `x\\<in>A` `tree A r` by(unfold tree_def,auto)\n  hence \"card (predecessors A x r - {b}) = card (predecessors A x r)-1 \" \n    using 2  card_Suc_Diff1 by auto\n  hence \"card (predecessors A b r) = n\"\n    using 3  `card (predecessors A x r) = n+1` by auto\n  thus \"height A b r = n\" by (unfold height_def, auto)\nqed\n \nlemma height:\n  assumes  \"tree A r\" and \"height A x r = n+1\"  \n  shows \"\\<exists>y. (y,x)\\<in>r \\<and> height A y r = n\"\nproof -\n  have 1: \"card (predecessors A x r) = n+1\" \n    using assms(2) by (unfold height_def, auto)\n  have \"\\<exists>a. minimum A a r\" using `tree A r` by(unfold tree_def, auto) \n  then obtain a where a: \"minimum A a r\"  by auto\n  have  \"strict_part_order A r\" using  `tree A r` tree[of A r]  by auto\n  hence  \"height  A a r = 0\" using a  height_minimum[of A r] by auto\n  hence \"x \\<noteq> a\" using assms(2) by auto\n  have \"x\\<in>A\"  using `tree A r`  1  non_empty_preds_in_tree by auto \n  hence \"(\\<exists>b. maximum (predecessors A x r) b r)\" \n    using `x \\<noteq> a` `tree A r` a predecessors_maximum[of A r a] by auto\n  then obtain b where b: \"(maximum (predecessors A x r) b r)\" by auto\n  hence \"(b,x)\\<in>r\" by(unfold maximum_def, unfold predecessors_def,auto)\n  thus \"\\<exists>y. (y,x)\\<in>r \\<and> height A y r = n\"\n    using  `tree A r` 1 b imm_predecessor[of A r] by auto \nqed\n\nlemma level:\n  assumes  \"tree A r\" and \"x \\<in> (level A r (n+1))\"  \n  shows \"\\<exists>y. (y,x)\\<in>r \\<and> y \\<in> (level A r n)\"\nproof-\n  have \"height A x r = n+1\"\n    using `x\\<in> (level A r (n+1))` by (unfold level_def, auto)\n  hence \"\\<exists>y. (y,x)\\<in>r \\<and> height A y r = n\" \n    using `tree A r` height[of A r] by auto \n  then obtain y where y:  \"(y,x)\\<in>r \\<and> height A y r = n\" by auto\n  have  \"r \\<subseteq> A \\<times> A\"  using `tree A r` by(unfold tree_def,auto) \n  hence \"y\\<in>A\" using y by auto\n  hence \"(y,x)\\<in>r \\<and> y \\<in> (level A r n)\" using y by(unfold level_def, auto)\n  thus ?thesis by auto\nqed\n(*Para demostrar que en un \u00e1rbol de ramificaci\u00f3n los leveles son finites, se define\nla siguiente funci\u00f3n. *)\nprimrec set_nodes_at_level ::  \"'a set \\<Rightarrow> 'a rel \\<Rightarrow> nat \\<Rightarrow>'a set\" where\n\"set_nodes_at_level A r 0 = {a. (minimum A a r)}\"\n| \"set_nodes_at_level A r (Suc n)  = (\\<Union>a\\<in> (set_nodes_at_level A r n). imm_successors A a r)\"\n\nlemma set_nodes_at_level_zero_spo:\n  assumes  \"strict_part_order A r\" and  \"minimum A a r\"\n  shows \"(set_nodes_at_level A r 0) = {a}\"\nproof-\n  have \"a\\<in>(set_nodes_at_level A r 0)\" using `minimum A a r` by auto\n  hence 1: \"{a} \\<subseteq> (set_nodes_at_level A r 0)\" by auto\n  have 2:  \"(set_nodes_at_level A r 0) \\<subseteq> {a}\"\n  proof\n    {fix x\n    assume \"x\\<in>(set_nodes_at_level A r 0)\"\n    hence \"minimum A x r\" by auto\n    hence \"x=a\" using assms  spo_uniqueness_min[of A r] by auto\n    thus \"x\\<in>{a}\" by auto}\n  qed\n  thus \"(set_nodes_at_level A r 0) = {a}\" using 1 2 by auto\nqed\n\nlemma height_level:\n  assumes \"strict_part_order A r\"  and  \"minimum A a r\"\n  and \"x \\<in> set_nodes_at_level A r n\"\n  shows \"height A x r = n\"\nproof-\n  have\n \"\\<lbrakk>strict_part_order A r; minimum A a r; x \\<in> set_nodes_at_level A r n\\<rbrakk> \\<Longrightarrow> \n  height A x r = n\" \n  proof(induct n arbitrary: x)\n    case 0\n    then show \"height A x r = 0\"\n    proof-\n      have \"minimum A x r\"  using `x \\<in> set_nodes_at_level A r 0` by auto\n      thus \"height A x r = 0\"\n        using `strict_part_order A r`  height_minimum[of A r]\n        by auto\n    qed\n  next\n    case (Suc n)\n    then show ?case \n    proof-\n      have  \"x\\<in> (\\<Union>a \\<in> (set_nodes_at_level A r n). (imm_successors A a r))\"\n        using Suc(4) by auto\n      then  obtain a\n        where hip1:  \"a \\<in> (set_nodes_at_level A r n)\" and hip2: \"x\\<in> (imm_successors A a r)\" \n        by auto\n      hence 1: \"height A a r = n\" using  Suc(1-3) by auto\n      have \"height A x r = (height A a r)+1\" \n        using hip2 by(unfold imm_successors_def, auto)\n      thus \"height A x r = Suc n\" using 1 by auto\n    qed\n  qed\n  thus ?thesis using assms by auto\nqed\n\nlemma level_func_vs_level_def: \n  assumes  \"tree A r\"\n  shows \"set_nodes_at_level A r n = level A r n\"   \nproof(induct n)\n  have 1: \"strict_part_order A r\" and\n       2: \"\\<forall>x\\<in>A. finite (predecessors A x r)\"\n    using  `tree A r` tree[of A r] by auto \n  have \"\\<exists>a. minimum A a r\" using `tree A r` by(unfold tree_def, auto)\n  then obtain a where a: \"minimum A a r\"  by auto\n  case 0\n  then show  \"set_nodes_at_level A r 0 = level A r 0\" \n  proof- \n    have \"set_nodes_at_level A r 0 = {a}\" using 1 a  set_nodes_at_level_zero_spo[of A r] by auto\n    moreover \n    have \"level A r 0 = {a}\" using 1 2  a  zero_level[of A r] by auto\n    ultimately\n    show \"set_nodes_at_level A r 0 = level A r 0\" by auto\n  qed\n  next\n    case (Suc n)\n    assume  \"set_nodes_at_level A r n = level A r n\"\n    show \"set_nodes_at_level A r (Suc n) = level A r (Suc n)\"\n    proof(rule equalityI)\n      show \"set_nodes_at_level A r (Suc n) \\<subseteq> level A r (Suc n)\"\n      proof(rule subsetI)\n        fix x\n        assume hip:  \"x \\<in> set_nodes_at_level A r (Suc n)\" show \"x \\<in> level A r (Suc n)\"\n        proof- \n          have\n          \"set_nodes_at_level A r (Suc n) = (\\<Union>a \\<in> (set_nodes_at_level A r n). (imm_successors A a r))\"\n            by simp\n          hence \"x\\<in> (\\<Union>a \\<in> (set_nodes_at_level A r n). (imm_successors A a r))\"\n            using hip by auto \n          then obtain a where hip1: \"a \\<in> (set_nodes_at_level A r n)\" and\n            hip2:\"x\\<in> (imm_successors A a r)\" by auto\n          have \"(a,x)\\<in>r \\<and>  height A x r = (height A a r)+1\" \n            using hip2 by(unfold imm_successors_def, auto)\n          moreover\n          have \"\\<exists>b. minimum A b r\" using `tree A r` by(unfold tree_def, auto)\n         then obtain b where b: \"minimum A b r\"  by auto\n         have 1:  \"r \\<subseteq> A \\<times> A\" and  \"strict_part_order A r\"\n           using `tree A r` by(unfold tree_def, auto)     \n         hence \"height A a r = n\" using b hip1  height_level[of A r] by auto\n         ultimately\n         have \"(a,x)\\<in>r \\<and> height A x r = n+1\" by auto\n         hence \"x\\<in>A \\<and> height A x r = n+1\" using `r \\<subseteq> A \\<times> A` by auto\n         thus \"x \\<in> level A r (Suc n)\" by(unfold level_def, auto)\n       qed\n     qed\n  next\n    show \"level A r (Suc n) \\<subseteq> set_nodes_at_level A r (Suc n)\"\n    proof(rule subsetI)\n      fix x\n      assume hip: \"x \\<in> level A r (Suc n)\" show \"x \\<in> set_nodes_at_level A r (Suc n)\"\n      proof-\n        have  1: \"x\\<in>A \\<and> height A x r = n+1\" using hip by(unfold level_def,auto)\n        hence  \"\\<exists>y. (y,x)\\<in>r \\<and> height A y r = n\" \n        using assms height[of A r] by auto\n        then obtain y where y1: \"(y,x)\\<in>r\"  and y2: \"height A y r = n\" by auto\n        hence \"x \\<in> (imm_successors A y r)\" \n          using 1 by(unfold imm_successors_def, auto)\n        moreover\n        have  \"r \\<subseteq> A \\<times> A\"  using `tree A r` by(unfold tree_def, auto)\n        have \"y\\<in>A\" using y1  `r \\<subseteq> A \\<times> A` by auto\n        hence \"y\\<in> level A r n\" using y2 by(unfold level_def, auto)\n        hence \"y\\<in> set_nodes_at_level A r n\" using Suc by auto \n        ultimately\n        show \"x \\<in> set_nodes_at_level A r (Suc n)\" by auto\n      qed\n    qed\n  qed\nqed\n\nlemma pertenece_level:\n  assumes \"x \\<in> set_nodes_at_level A r n\" \n  shows \"x\\<in>A\" \nproof-\n  have \"x \\<in> set_nodes_at_level A r n \\<Longrightarrow> x\\<in>A\"\n  proof(induct n) \n    case 0\n    show  \"x \\<in> A\"  using  `x \\<in> set_nodes_at_level A r 0` minimum_def[of A x r] by auto\n  next\n    case (Suc n)\n    then show \"x \\<in> A\"\n    proof- \n      have \"\\<exists>a \\<in> (set_nodes_at_level A r n). x\\<in> imm_successors A a r\"  \n        using `x \\<in> set_nodes_at_level A r (Suc n)` by auto  \n      then obtain a  where  a1:  \"a \\<in> (set_nodes_at_level A r n)\" and\n        a2: \"x\\<in> imm_successors A a r\" by auto\n      show \"x \\<in> A\" using a2 imm_successors_def[of A a r] by auto   \n    qed\n  qed\n  thus \"x \\<in> A\" using assms by auto\nqed\n\nlemma finiteness_set_nodes_at_levela:\n  assumes  \"\\<forall>x\\<in>A. finite (imm_successors A x r)\" and \"finite (set_nodes_at_level A r n)\"\n  shows \"finite (\\<Union>a\\<in> (set_nodes_at_level A r n). imm_successors A a r)\"\nproof  \n  show \"finite (set_nodes_at_level A r n)\" using assms(2) by simp\nnext\n  fix x\n  assume hip:  \"x \\<in> set_nodes_at_level A r n\" show  \"finite (imm_successors A x r)\"\n  proof-  \n    have \"x\\<in>A\" using hip  pertenece_level[of x A r]  by auto \n    thus  \"finite (imm_successors A x r)\"  using assms(1) by auto \n  qed\nqed\n\nlemma finiteness_set_nodes_at_level:\n  assumes \"finite (set_nodes_at_level A r 0)\" and  \"finite_branches A r\"\n  shows  \"finite (set_nodes_at_level A r n)\"\nproof(induct n)\n  case 0\n  show \"finite (set_nodes_at_level A r 0)\" using assms  by auto\nnext\n  case (Suc n)\n  then show ?case\n  proof -   \n    have 1: \"\\<forall>x\\<in>A. finite (imm_successors A x r)\"\n      using assms by (unfold finite_branches_def, auto)\n    hence  \"finite (\\<Union>a\\<in> (set_nodes_at_level A r n). imm_successors A a r)\"\n      using Suc(1) finiteness_set_nodes_at_levela[of A r] by auto \n    thus \"finite (set_nodes_at_level A r (Suc n))\" by auto\n  qed\nqed\n\nlemma finite_level:\n  assumes  \"tree A r\" and \"finite_branches  A r\" \n  shows  \"finite (level A r n)\" \nproof-\n  have 1: \"strict_part_order A r\"  using `tree A r` tree[of A r] by auto\n  have  \"\\<exists>a. minimum A a r\"  using `tree A r` tree[of A r] by auto\n  then obtain a where \"minimum A a r\" by auto\n  hence \"finite (set_nodes_at_level A r 0)\" \n    using 1  set_nodes_at_level_zero_spo[of A r] by auto\n  hence \"finite (set_nodes_at_level A r n)\"\n    using `finite_branches  A r` finiteness_set_nodes_at_level[of A r] by auto\n  thus  ?thesis using `tree A r` level_func_vs_level_def[of A r n] by auto\nqed\n\nlemma  finite_level_a:\n  assumes \"tree A r\" and \"\\<forall>n. finite (level A r n)\"\n  shows \"finite_branches A r\"\nproof(unfold finite_branches_def)\n  show  \"\\<forall>x\\<in>A. finite (imm_successors A x r)\"\n  proof\n  fix x\n  assume \"x\\<in>A\"\n  show \"finite (imm_successors A x r)\" using finite_branches_def\n  proof-\n    let ?n = \"(height A x r)\"\n    have \"(imm_successors A x r) \\<subseteq> (level A r (?n+1))\"\n      using imm_successors_def[of A x r] level_def[of A r \"?n+1\"] by auto \n    thus \"finite (imm_successors A x r)\"  using assms(2) by(simp add: finite_subset)   \n  qed\nqed\nqed\n\nlemma empty_predec: \n  assumes \"\\<forall>x\\<in>A. (x,y)\\<notin>r\"  \n  shows \"predecessors A y r ={}\" \n    using assms by(unfold predecessors_def, auto)\n\nlemma level_element:\n \"\\<forall>x\\<in>A.\\<exists>n. x\\<in> level A r n\"\nproof\n  fix x\n  assume hip: \"x\\<in>A\" show \"\\<exists>n. x \\<in> level A r n\"\n  proof-\n    let ?n = \"height A x r\"\n    have \"x\\<in>level A r ?n\" using `x\\<in>A`  by (unfold level_def, auto)\n    thus \"\\<exists>n. x \\<in> level A r n\" by auto \n  qed\nqed\n\nlemma union_levels:\n  shows \"A =(\\<Union>n. level A r n)\"\nproof(rule equalityI)\n  show \"A \\<subseteq> (\\<Union>n. level A r n)\"\n  proof(rule subsetI)\n    fix x\n    assume hip: \"x\\<in>A\" show \"x\\<in>(\\<Union>n. level A r n)\"\n    proof-\n      have \"\\<exists>n. x\\<in> level A r n\"  \n        using hip level_element[of A] by auto\n      then obtain n where  \"x\\<in> level A r n\" by auto\n    thus ?thesis by auto \n  qed\nqed\nnext\n  show  \"(\\<Union>n. level A r n) \\<subseteq> A\"\n  proof(rule subsetI)\n    fix x\n    assume hip:  \"x \\<in> (\\<Union>n. level A r n)\" show \"x \\<in> A\"\n    proof-\n      obtain n where  \"x\\<in> level A r n\" using hip by auto \n      thus \"x \\<in> A\" by(unfold level_def, auto)\n    qed\n  qed\nqed\n\nlemma path_to_node:\n  assumes  \"tree A r\"  and  \"x \\<in> (level A r (n+1))\" \n  shows \"\\<forall>k.(0\\<le>k \\<and> k\\<le>n)\\<longrightarrow> (\\<exists>y. (y,x)\\<in>r \\<and> y \\<in> (level A r k))\"\nproof- \n  have \"tree A r \\<Longrightarrow> x \\<in> (level A r (n+1)) \\<Longrightarrow>  \n  \\<forall>k.(0\\<le>k \\<and> k\\<le>n)\\<longrightarrow> (\\<exists>y. (y,x)\\<in>r \\<and> y \\<in> (level A r k))\"\n  proof(induction n arbitrary: x)\n    have \"r \\<subseteq> A \\<times> A\" and 1:  \"strict_part_order A r\" \n    and \"\\<exists>a. minimum A a r\"\n    and 2: \"\\<forall>x\\<in>A. finite (predecessors A x r)\"  \n      using `tree A r` tree[of A r] by auto\n    case 0\n    show  \"\\<forall>k. 0 \\<le> k \\<and> k \\<le> 0 \\<longrightarrow> (\\<exists>y. (y, x) \\<in> r \\<and> y \\<in> level A r k)\"\n    proof\n      fix k\n      show \"0 \\<le> k \\<and> k \\<le> 0 \\<longrightarrow> (\\<exists>y. (y, x) \\<in> r \\<and> y \\<in> level A r k)\"\n      proof(rule impI)\n        assume hip:  \"0 \\<le> k \\<and> k \\<le> 0\"\n        show \"(\\<exists>y. (y, x) \\<in> r \\<and> y \\<in> level A r k)\" \n        proof-\n          have \"k=0\" using hip  by auto\n          thus \"(\\<exists>y. (y, x) \\<in> r \\<and> y \\<in> level A r k)\"\n            using `tree A r`  `x \\<in> (level A r (0 + 1))` level[of A r ]  by auto\n        qed      \n      qed\n    qed\n    next\n      case (Suc n)\n      show \"\\<forall>k. 0 \\<le> k \\<and> k \\<le> Suc n \\<longrightarrow> (\\<exists>y. (y, x) \\<in> r \\<and> y \\<in> level A r k)\"\n  proof(rule allI, rule impI)\n    fix k \n    assume hip:  \"0 \\<le> k \\<and> k \\<le> Suc n\"\n    show  \"(\\<exists>y. (y, x) \\<in> r \\<and> y \\<in> level A r k)\"\n    proof-\n      have \"(0 \\<le> k \\<and> k \\<le> n) \\<or> k = Suc n\"  using hip by auto\n      thus ?thesis\n      proof(rule disjE)\n        assume hip1:  \"0 \\<le> k \\<and> k \\<le> n\"\n        have \"\\<exists>y. (y,x)\\<in>r \\<and> y \\<in> (level A r (n+1))\" \n        using `tree A r` level  `x \\<in> level A r (Suc n + 1)` by auto\n        then obtain y where y1: \"(y,x)\\<in>r\" and y2: \"y \\<in> (level A r (n+1))\" \n          by auto    \n        have \"\\<forall>k. 0 \\<le> k \\<and> k \\<le> n \\<longrightarrow> (\\<exists>z. (z, y) \\<in> r \\<and> z \\<in> level A r k)\" \n          using y2  Suc(1-3) by auto \n        hence \"(\\<exists>z. (z, y) \\<in> r \\<and> z \\<in> level A r k)\" \n          using hip1 by auto\n        then obtain z where  z1: \"(z, y) \\<in> r\" and z2: \"z \\<in> (level A r k)\" by auto\n        have  \"r \\<subseteq> A \\<times> A\" and \"strict_part_order A r\" \n          using  `tree A r` tree by auto\n        hence \"z\\<in>A\" and  \"y\\<in>A\" and \"x\\<in>A\"\n          using `r \\<subseteq> A \\<times> A` `(z, y) \\<in> r` `(y,x)\\<in>r` by auto\n        have \"transitive_on A r\" using `strict_part_order A r`\n          by(unfold strict_part_order_def, auto)\n        hence \"(z, x) \\<in> r\" using `z\\<in>A` `y\\<in>A` and `x\\<in>A` `(z, y) \\<in> r` `(y,x)\\<in>r`\n          by(unfold transitive_on_def, blast)\n        thus \"(\\<exists>y. (y, x) \\<in> r \\<and> y \\<in> level A r k)\"\n          using z2 by auto\n      next\n        assume  \"k = Suc n\"\n        thus  \"\\<exists>y. (y,x)\\<in>r \\<and> y \\<in> (level A r k)\"\n          using `tree A r` level `x \\<in> level A r (Suc n + 1)` by auto\n        qed\n      qed\n    qed\n  qed\n  thus ?thesis using assms by auto\nqed\n\nlemma set_nodes_at_level:  \n  assumes \"tree A r\"  \n  shows \"(level A r (n+1))\\<noteq> {} \\<longrightarrow> (\\<forall>k.(0\\<le>k \\<and> k\\<le>n) \\<longrightarrow> (level A r k)\\<noteq> {})\"\nproof(rule impI) \n  assume hip:  \"(level A r (n+1))\\<noteq> {}\"\n    show  \"(\\<forall>k.(0\\<le>k \\<and> k\\<le>n) \\<longrightarrow> (level A r k)\\<noteq> {})\"\n    proof-      \n      have  \"\\<exists>x. x\\<in>(level A r (n+1))\" using hip by auto  \n      then obtain x where x: \"x\\<in>(level A r (n+1))\" by auto\n      thus ?thesis using assms path_to_node[of A r] by blast\n    qed\n  qed\n\nlemma emptyness_below_height:\n  assumes  \"tree A r\"  \n  shows  \"((level A r (n+1)) = {}) \\<longrightarrow> (\\<forall>k. k>(n+1) \\<longrightarrow> (level A r k) = {})\"\nproof(rule ccontr)\n  assume hip: \"\\<not> (level A r (n+1) = {} \\<longrightarrow> (\\<forall>k>(n+1). level A r k = {}))\"\n  show False\n  proof-\n    have \"((level A r (n+1)) = {}) \\<and> \\<not>(\\<forall>k>(n+1). level A r k = {})\" \n      using hip by auto\n    hence 1: \"(level A r (n+1)) = {}\" and 2: \"\\<exists>k>(n+1). (level A r k) \\<noteq> {}\"\n      by auto\n    obtain z where z1: \"z>(n+1)\" and z2: \"(level A r z) \\<noteq> {}\"\n      using 2 by auto\n    have \"z>0\" using  `z>(n+1)` by auto \n    hence \"(level A r ((z-1)+1)) \\<noteq> {}\"\n      using z2 by simp\n    hence \"\\<forall>k.(0\\<le>k \\<and> k\\<le>(z-1)) \\<longrightarrow> (level A r k)\\<noteq> {}\" \n      using  z2 `tree A r` set_nodes_at_level[of A r \"z-1\"]\n      by auto\n    hence  \"(level A r (n+1)) \\<noteq> {}\"\n      using `z>(n+1)` by auto\n    thus False using 1 by auto\n  qed\nqed\n\nlemma characterization_nodes_tree_finite_height:\n  assumes \"tree A r\" and \"\\<forall>k. k>m \\<longrightarrow> (level A r k) = {}\"\n  shows \"A = (\\<Union>n\\<in>{0..m}. level A r n)\"\nproof- \n  have a: \"A = (\\<Union>n. level A r n)\" using  union_levels[of A r] by auto\n  have \"(\\<Union>n. level A r n) = (\\<Union>n\\<in>{0..m}. level A r n)\"\n  proof(rule equalityI)\n    show \"(\\<Union>n. level A r n) \\<subseteq> (\\<Union>n\\<in>{0..m}.  level A r n)\"\n    proof(rule subsetI)\n      fix x\n      assume hip: \"x\\<in>(\\<Union>n. level A r n)\" \n      show \"x\\<in>(\\<Union>n\\<in>{0..m}. level A r n)\"\n      proof-\n        have \"\\<exists>n. x\\<in> level A r n\"  \n        using hip level_element[of A] by auto\n        then obtain n where n: \"x\\<in> level A r n\" by auto\n        have \"n\\<in>{0..m}\"\n        proof(rule ccontr)\n          assume 1: \"n \\<notin> {0..m}\"\n          show False\n          proof-\n            have \"n > m\" using 1 by auto\n            thus False using assms(2) n by auto\n          qed\n        qed\n        thus \"x\\<in>(\\<Union>n\\<in>{0..m}. level A r n)\" using n by auto\n      qed\n    qed\n  next\n    show  \"(\\<Union>n\\<in>{0..m}. level A r n) \\<subseteq> (\\<Union>n. level A r n)\" by auto\n  qed\n  thus  \"A = (\\<Union>n\\<in>{0..m}. level A r n)\" using a by auto\nqed\n\nlemma finite_tree_if_fin_branches_and_fin_height:\n  assumes \"tree A r\"  and  \"finite_branches  A r\"\n  and \"\\<exists>n. (\\<forall>k. k>n \\<longrightarrow> (level A r k) = {})\"\n  shows \"finite A\"\nproof-\n  obtain m where m: \"(\\<forall>k. k>m \\<longrightarrow> (level A r k) = {})\" \n    using assms(3) by auto \n  hence 1: \"A =(\\<Union>n\\<in>{0..m}. level A r n)\"\n    using  assms(1) assms(3) characterization_nodes_tree_finite_height[of A r m] by auto\n  have \"\\<forall>n. finite (level A r n)\" \n    using assms(1-2) finite_level by auto\n  hence \"\\<forall>n\\<in>{0..m}. finite (level A r n)\" by auto\n  hence \"finite (\\<Union>n\\<in>{0..m}. level A r n)\" by auto\n  thus \"finite A\" using 1 by auto\nqed\n\nlemma all_levels_non_empty:\n  assumes  \"infinite_tree A r\" and  \"finite_branches A r\"\n  shows \"\\<forall>n. level A r n \\<noteq> {}\"\nproof(rule ccontr)\n  assume hip: \"\\<not> (\\<forall>n. level A r n \\<noteq> {})\"\n  show False\n  proof-\n    have \"tree A r\" using `infinite_tree A r` by auto\n    have \"(\\<exists>n. level A r n = {})\" using hip by auto\n    then obtain n where n: \"level A r n = {}\" by auto \n    thus False\n    proof(cases n)\n      case 0\n      then show False\n      proof-\n        have \"\\<exists>a. minimum A a r\" using `tree A r` tree[of A r] by auto\n        then obtain a where a:  \"minimum A a r\" by auto\n        have \" strict_part_order A r\" \n        and \"\\<forall>x\\<in>A. finite (predecessors A x r)\" \n          using  `tree A r` tree[of A r] by auto\n        hence \"level A r n = {a}\" \n          using a `n=0` zero_level[of A r a] by auto\n        thus False using `level A r n = {}` by auto\n      qed\n      next\n        case (Suc nat)\n        fix m\n        assume hip: \"n = Suc m\" show False\n        proof-\n          have 1:  \"level A r (Suc m) = {}\"  \n            using hip  n by auto\n        have \"(\\<forall>k. k>(m+1) \\<longrightarrow> (level A r k) = {})\" \n          using `tree A r` 1  emptyness_below_height[of A r m] by auto\n        hence 1: \"(\\<exists>n. \\<forall>k. k>n \\<longrightarrow> (level A r k) = {})\" by auto\n        hence 2: \"finite A\" \n          using `tree A r` 1 `finite_branches  A r` finite_tree_if_fin_branches_and_fin_height[of A r] by auto\n        have 3:  \"\\<not> finite A\" using `infinite_tree A r` by auto\n        show False using 2 3 by auto\n      qed\n    qed\n  qed\nqed\n\nlemma simple_cyclefree:\n  assumes \"tree A r\" and \"(x,z)\\<in>r\" and \"(y,z)\\<in>r\" and \"x\\<noteq>y\" \n  shows \"(x,y)\\<in>r \\<or> (y,x)\\<in>r\"\nproof-\n  have \"r \\<subseteq> A \\<times> A\" using `tree A r` by(unfold tree_def, auto)\n  hence \"x\\<in>A\" and  \"y\\<in>A\" and  \"z\\<in>A\" using  `(x,z)\\<in>r` and `(y,z)\\<in>r` by auto \n  hence 1: \"x \\<in> predecessors A z r\" and 2: \"y \\<in> predecessors A z r\"\n    using assms by(unfold predecessors_def, auto)\n  have \"(total_on (predecessors A  z r) r)\"\n    using `tree A r` `z\\<in>A` by(unfold tree_def, auto)\n  thus ?thesis using 1 2 `x\\<noteq>y`  total_on_def[of \"predecessors A z r\" r] by auto \nqed\n\nlemma inclusion_predecessors:\n  assumes  \"r \\<subseteq> A \\<times> A\" and \"strict_part_order A r\" and \"(x,y)\\<in>r\"\n  shows \"(predecessors A x r) \\<subset> (predecessors A y r)\"\nproof-\n  have \"irreflexive_on A r\" and \"transitive_on A r\" \n    using assms(2) by (unfold strict_part_order_def, auto) \n  have 1: \"(predecessors A x r)\\<subseteq> (predecessors A y r)\"\n  proof(rule subsetI)\n    fix z\n    assume \"z\\<in>predecessors A x r\"\n    hence \"z\\<in>A\" and \"(z,x)\\<in>r\" by(unfold predecessors_def, auto)\n    have \"x\\<in>A\" and \"y\\<in>A\"  using `(x,y)\\<in>r` `r \\<subseteq> A \\<times> A` by auto\n    hence \"(z,y)\\<in>r\"\n      using `z\\<in>A` `y\\<in>A` `x\\<in>A` `(z,x)\\<in>r` `(x,y)\\<in>r` `transitive_on A r` \n      by (unfold transitive_on_def, blast) \n    thus \"z\\<in>predecessors A y r\" \n      using `z\\<in>A` by(unfold predecessors_def, auto)\n  qed\n  have 2: \"x\\<in>predecessors A y r\" \n    using `r \\<subseteq> A \\<times> A` `(x,y)\\<in>r` by(unfold predecessors_def, auto)\n  have 3:  \"x\\<notin>predecessors A x r\"\n  proof(rule ccontr)\n    assume \"\\<not> x \\<notin> predecessors A x r\"\n    hence \"x \\<in> predecessors A x r\" by auto\n    hence \"x\\<in>A \\<and> (x,x)\\<in>r\"\n      by(unfold predecessors_def, auto)\n    thus False using `irreflexive_on A r`\n      by (unfold irreflexive_on_def, auto)\n  qed\n  have \"(predecessors A x r) \\<noteq> (predecessors A y r)\"\n    using 2 3 by auto\n  thus ?thesis using 1 by auto\nqed\n\nlemma different_height_finite_pred:\n  assumes  \"r \\<subseteq> A \\<times> A\" and \"strict_part_order A r\" and \"(x,y)\\<in>r\" \n  and  \"finite (predecessors A y r)\"\n  shows \"height A x r < height A y r\" \nproof- \n  have \"card(predecessors A x r) < card(predecessors A y r)\" \n    using assms  inclusion_predecessors[of r A x y] psubset_card_mono by auto\n  thus ?thesis by(unfold height_def, auto)\nqed\n\nlemma different_levels_finite_pred:\n  assumes  \"r \\<subseteq> A \\<times> A\" and \"strict_part_order A r\" and \"(x,y)\\<in>r\"\n  and \"x \\<in> (level A r n)\"  and  \"y \\<in> (level A r m)\" \n  and  \"finite (predecessors A y r)\"\n  shows \"level A r n \\<noteq> level A r m\"\nproof(rule ccontr)\n  assume \"\\<not> level A r n \\<noteq> level A r m\"\n  hence \"level A r n = level A r m\"  by auto\n  hence \"x \\<in> (level A r m)\"  using `x \\<in> (level A r n)` by auto\n  hence 1:  \"height A x r= m\"  by(unfold level_def, auto)\n  have \"height A y r= m\" using `y \\<in> (level A r m)` by(unfold level_def, auto)\n  hence \"height A x r = height A y r\" using 1 by auto\n  thus False \n    using assms different_height_finite_pred[of r A x y] by (unfold level_def, auto)\nqed\n\nlemma less_level_pred_in_fin_pred: \n  assumes  \"r \\<subseteq> A \\<times> A\" and \"strict_part_order A r\" \n  and \"x \\<in> predecessors A y r\"  and \"y \\<in> (level A r n)\"\n  and  \"x \\<in> (level A r m)\" \n  and \"finite (predecessors A y r)\"\n  shows \"m<n\" \nproof-\n  have \"(x,y)\\<in>r\" using `(x \\<in> predecessors A y r)`\n    by (unfold predecessors_def, auto)\n  thus ?thesis \n    using assms  different_height_finite_pred[of r A x y] by(unfold level_def, auto)\nqed\n\nlemma emptyness_inter_diff_levels_aux:\n  assumes \"tree A r\" and \"x\\<in>(predecessors A z r)\" \n  and \"y\\<in>(predecessors A z r)\"\n  and  \"x\\<noteq>y\" and \"x \\<in> (level A r n)\" and \"y \\<in> (level A r m)\" \n  shows \"level A r n \\<inter> level A r m = {}\" \nproof-   \n  have \"(x,y)\\<in>r \\<or> (y,x)\\<in>r\"     \n    using assms simple_cyclefree[of A] by(unfold predecessors_def, auto)\n  thus \"level A r n \\<inter> level A r m ={}\"\n  proof(rule disjE)\n    assume  \"(x, y) \\<in> r\" \n    have \"r\\<subseteq> A \\<times> A\" and 1: \"strict_part_order A r\"\n      using  `tree A r` by(unfold tree_def,auto)\n    hence \"x\\<in>A\" and \"y\\<in>A\"  and  2: \"x\\<in>(predecessors A y r)\"\n      using `(x, y) \\<in> r`  by(unfold predecessors_def, auto)\n    have 3: \"finite (predecessors A y r)\"\n      using `y\\<in>A`  `tree A r` by(unfold tree_def, auto) \n    hence  \"n<m\"\n      using assms `r\\<subseteq> A \\<times> A` 1 2 3 less_level_pred_in_fin_pred[of r A x y m n]\n      by auto\n    hence \"\\<exists>k>0. m=n+k\" by arith\n    then obtain k where k: \"k>0\" and m: \"m=n+k\" by auto\n    thus ?thesis using uniqueness_level_aux[OF k, of A ]\n      by auto\n  next\n    assume  \"(y, x) \\<in> r\" \n    have \"r\\<subseteq> A \\<times> A\" and 1: \"strict_part_order A r\"\n      using  `tree A r` by(unfold tree_def,auto)\n    hence \"x\\<in>A\" and \"y\\<in>A\" and 2: \"y\\<in>(predecessors A x r)\"\n      using `(y, x) \\<in> r`\n      by(unfold predecessors_def, auto)\n    have 3: \"finite (predecessors A x r)\" \n      using `x\\<in>A` `tree A r`\n      by(unfold tree_def, auto) \n    hence  \"m<n\" \n      using assms `r\\<subseteq> A \\<times> A` 1 2 3 less_level_pred_in_fin_pred[of r A y x n m]\n      by auto\n    hence \"\\<exists>k>0. n=m+k\" by arith\n    then obtain k where k: \"k>0\" and m: \"n=m+k\" by auto\n    thus ?thesis using  uniqueness_level_aux[OF k, of A] by auto\n  qed\nqed\n\nlemma emptyness_inter_diff_levels:\n  assumes \"tree A r\" and \"(x,z)\\<in> r\" and \"(y,z)\\<in> r\"\n  and  \"x\\<noteq>y\" and  \"x \\<in> (level A r n)\" and \"y \\<in> (level A r m)\" \nshows \"level A r n \\<inter> level A r m = {}\" \nproof-\n  have \"r \\<subseteq> A \\<times> A\"  using  `tree A r` tree by auto\n  hence \"x\\<in>A\" and  \"y\\<in>A\"  using  `r \\<subseteq> A \\<times> A`  `(x,z) \\<in> r`  `(y,z)\\<in>r` by auto\n  hence \"x\\<in>(predecessors A z r)\" and \"y\\<in>(predecessors A z r)\" \n    using  `(x,z)\\<in> r` and `(y,z)\\<in> r` by(unfold predecessors_def, auto)\n  thus ?thesis\n    using assms  emptyness_inter_diff_levels_aux[of A r] by blast\nqed\n\nprimrec disjunction_nodes :: \"'a list  \\<Rightarrow> 'a formula\"  where\n \"disjunction_nodes [] = FF\"   \n| \"disjunction_nodes (v#D) = (atom v) \\<or>. (disjunction_nodes D)\"\n\nlemma truth_value_disjunction_nodes:\n  assumes \"v\\<in> set l\" and \"t_v_evaluation I (atom v) = Ttrue\"\n  shows \"t_v_evaluation I (disjunction_nodes l) = Ttrue\"\nproof-\n  have \"v\\<in> set l \\<Longrightarrow>  t_v_evaluation I (atom v) = Ttrue \\<Longrightarrow>\n  t_v_evaluation I (disjunction_nodes l) = Ttrue\" \n  proof(induct l)\n    case Nil\n    then show ?case by auto\n  next\n    case (Cons a l)\n    then show  \"t_v_evaluation I (disjunction_nodes (a # l)) = Ttrue\"\n    proof-\n      have \"v = a \\<or> v\\<noteq>a\" by auto\n      thus  \"t_v_evaluation I (disjunction_nodes (a # l)) = Ttrue\"\n      proof(rule disjE)\n        assume \"v = a\"\n        hence 1: \"disjunction_nodes (a#l) = (atom v) \\<or>. (disjunction_nodes l)\"\n          by auto \n        have \"t_v_evaluation I ((atom v) \\<or>. (disjunction_nodes l)) = Ttrue\"  \n          using Cons(3)  by(unfold t_v_evaluation_def,unfold v_disjunction_def, auto)\n        thus ?thesis using 1  by auto\n      next\n        assume \"v \\<noteq> a\"\n        hence \"v\\<in> set l\" using Cons(2) by auto\n        hence \"t_v_evaluation I (disjunction_nodes l) = Ttrue\"\n          using Cons(1) Cons(3) by auto\n        thus ?thesis\n          by(unfold t_v_evaluation_def,unfold v_disjunction_def, auto)\n      qed\n    qed\n  qed\n  thus ?thesis using assms by auto\nqed\n\nlemma set_set_to_list1:\n  assumes \"tree A r\" and  \"finite_branches A r\" \n  shows \"set (set_to_list (level A r n)) = (level A r n)\"\n  using assms finite_level[of A r n]  set_set_to_list by auto\n\nlemma truth_value_disjunction_formulas:\n  assumes  \"tree A r\" and  \"finite_branches A r\"\n  and  \"v\\<in>(level A r n) \\<and> t_v_evaluation I (atom v) = Ttrue\" \n  and  \"F = disjunction_nodes(set_to_list (level A r n))\" \n  shows \"t_v_evaluation I  F = Ttrue\"\nproof- \n  have \"set (set_to_list (level A r n)) = (level A r n)\" \n    using set_set_to_list1 assms(1-2) by auto\n  hence \"v\\<in> set (set_to_list (level A r n))\"\n    using assms(3) by auto\n  thus \"t_v_evaluation I F = Ttrue\"\n    using assms(3-4) truth_value_disjunction_nodes by auto\nqed\n\ndefinition \\<F>' :: \"'a set \\<Rightarrow> 'a rel \\<Rightarrow> ('a formula) set\"  where\n   \"\\<F>' A r  \\<equiv> (\\<Union>n. {disjunction_nodes(set_to_list (level A r n))})\"\n\ndefinition \\<G>' ::  \"'a set \\<Rightarrow> 'a rel \\<Rightarrow> ('a formula) set\"  where\n   \"\\<G>' A r \\<equiv> {(atom u) \\<rightarrow>. (atom v) |u v. u\\<in>A \\<and> v\\<in>A \\<and> (v,u)\\<in> r}\" \n\ndefinition \\<H>n :: \"'a set \\<Rightarrow> 'a rel \\<Rightarrow> nat \\<Rightarrow> ('a formula) set\"  where\n   \"\\<H>n A r n \\<equiv> {\\<not>.((atom u) \\<and>. (atom v))\n                         |u v . u\\<in>(level A r n) \\<and> v\\<in>(level A r n) \\<and> u\\<noteq>v }\"\ndefinition \\<H>'  :: \"'a set \\<Rightarrow> 'a rel \\<Rightarrow> ('a formula) set\"  where\n \"\\<H>' A r  \\<equiv> \\<Union>n. \\<H>n A r n\"\n\ndefinition \\<T>' :: \"'a set \\<Rightarrow> 'a rel \\<Rightarrow> ('a formula) set\"  where\n   \"\\<T>' A r  \\<equiv> (\\<F>' A r) \\<union> (\\<G>' A r) \\<union> (\\<H>' A r)\" \n\nprimrec nodes_formula :: \"'v formula  \\<Rightarrow> 'v set\" where\n  \"nodes_formula FF = {}\"\n| \"nodes_formula TT = {}\"\n| \"nodes_formula (atom P) =  {P}\"\n| \"nodes_formula (\\<not>. F) = nodes_formula F\"\n| \"nodes_formula (F \\<and>. G) = nodes_formula F \\<union> nodes_formula G\"\n| \"nodes_formula (F \\<or>. G) = nodes_formula F \\<union> nodes_formula G\"\n| \"nodes_formula (F \\<rightarrow>.G) = nodes_formula F \\<union> nodes_formula G\"\n\ndefinition nodes_set_formulas :: \"'v formula set  \\<Rightarrow> 'v set\"  where\n\"nodes_set_formulas S = (\\<Union>F\\<in> S. nodes_formula F)\"\n\ndefinition maximum_height:: \"'v set \\<Rightarrow>'v rel \\<Rightarrow> 'v  formula  set  \\<Rightarrow>  nat\"  where\n \"maximum_height A r S =  Max (\\<Union>x\\<in>nodes_set_formulas S. {height A x r})\"\n\nlemma nodo_formula:\n  assumes \"v \\<in> set l\" \n  shows \"v \\<in> nodes_formula (disjunction_nodes l)\" \nproof-\n  have \"v \\<in> set l \\<Longrightarrow> v \\<in> nodes_formula (disjunction_nodes l)\" \n  proof(induct l)\n    case Nil\n    then show ?case by auto\n  next\n    case (Cons a l)  \n    show \"v \\<in> nodes_formula (disjunction_nodes (a # l))\"  \n   proof-\n     have \"v = a \\<or> v\\<noteq>a\" by auto\n     thus \"v \\<in> nodes_formula (disjunction_nodes (a # l))\"\n     proof(rule disjE)\n       assume \"v = a\"\n       hence 1: \"disjunction_nodes (a#l) = (atom v) \\<or>. (disjunction_nodes l)\"\n         by auto \n       have \"v \\<in> nodes_formula ((atom v) \\<or>. (disjunction_nodes l))\" by auto \n       thus ?thesis using 1  by auto\n     next\n       assume \"v \\<noteq> a\"\n       hence \"v\\<in> set l\" using Cons(2) by auto\n       hence \"v \\<in> nodes_formula (disjunction_nodes l)\"\n         using Cons(1) Cons(2) by auto\n       thus ?thesis by auto\n     qed\n   qed\n qed\n  thus ?thesis using assms by auto\nqed \n\nlemma nodo_disjunction_formulas:\n  assumes  \"tree A r\" and  \"finite_branches A r\" and \"v\\<in>(level A r n)\" \n  and  \"F = disjunction_nodes(set_to_list (level A r n))\" \n  shows  \"v \\<in> nodes_formula F\"\nproof- \n  have \"set (set_to_list (level A r n)) = (level A r n)\" \n    using set_set_to_list1 assms(1-2) by auto\n  hence \"v\\<in> set (set_to_list (level A r n))\" \n    using assms(3) by auto\n  thus \"v \\<in> nodes_formula F\"\n    using assms(3-4)  nodo_formula  by auto\nqed\n\nfun nodo_sig_level_max:: \"'v set \\<Rightarrow> 'v rel \\<Rightarrow> 'v formula set  \\<Rightarrow> 'v\" \n  where \"nodo_sig_level_max A r S = \n  (SOME u. u \\<in> (level A r ((maximum_height A r S)+1)))\"\n\nlemma nodo_level_maximum:  \n  assumes \"infinite_tree A r\" and  \"finite_branches A r\"\n  shows \"(nodo_sig_level_max A r S) \\<in>  (level A r ((maximum_height A r S)+1))\" \nproof-\n  have  \"\\<exists>u. u \\<in> (level A r ((maximum_height A r S)+1))\"\n    using assms  all_levels_non_empty[of A r] by (unfold level_def, auto)\n  then obtain u where u: \"u \\<in> (level A r (( maximum_height A r S)+1))\" by auto\n  hence \"(SOME u. u \\<in> (level A r ((maximum_height A r S)+1))) \\<in> (level A r ((maximum_height A r S)+1))\" \n    using someI by auto\n  thus ?thesis by auto \nqed\n\nfun path_interpretation :: \"'v set \\<Rightarrow>'v rel \\<Rightarrow> 'v \\<Rightarrow> ('v  \\<Rightarrow>  v_truth)\"  where\n\"path_interpretation A r u = (\\<lambda>v. (if (v,u)\\<in>r  then Ttrue else Ffalse))\"\n\nlemma finiteness_nodes_formula:\n \"finite (nodes_formula F)\" by(induct F, auto)\n\nlemma finiteness_set_nodes:\n  assumes \"finite S\" \n  shows  \"finite (nodes_set_formulas S)\" \n  using assms finiteness_nodes_formula \n  by (unfold nodes_set_formulas_def, auto)\n\nlemma maximum1:\n  assumes  \"finite S\" and \"u \\<in> nodes_set_formulas S\"\n  shows \"(height A u r)  \\<le> (maximum_height A r S)\" \nproof-  \n  have \"(height A u r) \\<in> ( \\<Union>x\\<in>nodes_set_formulas S. {height A x r})\" \n    using assms(2) by auto\n  thus \"(height A u r)  \\<le> (maximum_height A r S)\"\n    using `finite S` finiteness_set_nodes[of S] \n    by(unfold maximum_height_def, auto) \nqed\n\nlemma value_path_interpretation:\n  assumes \"t_v_evaluation (path_interpretation A r v) (atom u) = Ttrue\"\n  shows \"(u,v)\\<in>r\"\nproof(rule ccontr)\n  assume \"(u, v) \\<notin> r\"\n  hence \"t_v_evaluation (path_interpretation A r v) (atom u) = Ffalse\"\n    by(unfold t_v_evaluation_def, auto) \n  thus False using assms by auto\nqed\n\nlemma satisfiable_path:\n  assumes \"infinite_tree A r\"\n  and  \"finite_branches A r\" and  \"S \\<subseteq> (\\<T>' A r)\" \n  and \"finite S\" \nshows  \"satisfiable S\"\nproof-\n  let ?m = \"(maximum_height A r S)+1\"\n  let ?level = \"level A r ?m\"\n  let ?u = \"nodo_sig_level_max A r S\" \n  have 1: \"tree A r\" using `infinite_tree A r` by auto\n  have  \"r \\<subseteq> A \\<times> A\" and \"strict_part_order A r\" \n    using  `tree A r` tree by auto\n  have \"transitive_on A r\" \n    using `strict_part_order A r`\n    by(unfold strict_part_order_def, auto) \n  have \"\\<exists>u. u \\<in>?level\" \n    using assms(1-2) nodo_level_maximum by auto\n  then obtain u where u: \"u \\<in> ?level\"  by auto\n  hence levelu:  \"?u \\<in> ?level\"\n    using someI by auto\n  hence \"?u\\<in>A\" by(unfold level_def, auto)\n  have \"(path_interpretation A r ?u) model S\"\n  proof(unfold model_def)\n    show \"\\<forall>F\\<in>S. t_v_evaluation (path_interpretation A r ?u) F = Ttrue\"\n    proof \n      fix F assume \"F \\<in> S\"\n      show  \"t_v_evaluation (path_interpretation A r ?u) F  = Ttrue\"\n      proof-        \n        have \"F \\<in> (\\<F>' A r) \\<union> (\\<G>' A r) \\<union> (\\<H>' A r)\" \n        using `S \\<subseteq>  \\<T>' A r` `F \\<in> S` assms(2)  by(unfold \\<T>'_def,auto) \n        hence  \"F \\<in> (\\<F>' A r) \\<or> F \\<in> (\\<G>' A r) \\<or> F \\<in> (\\<H>' A r)\" by auto \n        thus ?thesis\n        proof(rule disjE)\n          assume \"F \\<in> (\\<F>' A r)\"\n          hence \"\\<exists>n. F = disjunction_nodes(set_to_list (level A r n))\" \n            by(unfold \\<F>'_def,auto)\n          then obtain n\n            where n: \"F = disjunction_nodes(set_to_list (level A r n))\" \n            by auto\n          have \"\\<exists>v. v\\<in>(level A r n)\" \n            using  assms(1-2) all_levels_non_empty[of A r] by auto \n          then obtain v where v: \"v \\<in> (level A r n)\" by auto      \n          hence  \"v \\<in> nodes_formula F\" \n            using n nodo_disjunction_formulas[OF 1 assms(2) v, of F ]\n            by auto\n          hence a: \"v \\<in> nodes_set_formulas S\" \n            using `F \\<in> S`  by(unfold nodes_set_formulas_def, blast)\n          hence b: \"(height A v r) \\<le> (maximum_height A r S)\" \n            using `finite S`  maximum1[of S v] by auto\n          have \"(height A v r) = n\" \n            using v by(unfold level_def, auto) \n          hence  \"n < ?m\" \n            using `finite S` a   maximum1[of S v A r]\n            by(unfold maximum_height_def, auto)         \n          hence \"(\\<exists>y. (y,?u)\\<in>r \\<and> y \\<in> (level A r n))\" \n            using levelu `tree A r` path_to_node[of A r]\n            by auto\n          then obtain y where y1: \"(y,?u)\\<in>r\" and y2: \"y \\<in> (level A r n)\"\n            by auto\n          hence \"t_v_evaluation (path_interpretation A r ?u) (atom y) = Ttrue\" \n            by auto\n          thus \"t_v_evaluation (path_interpretation A r ?u) F = Ttrue\"\n            using 1 assms(2) y2 n  truth_value_disjunction_formulas[of A r y]\n            by auto\n        next\n          assume  \"F \\<in> \\<G>' A r \\<or> F \\<in> \\<H>' A r\"\n          thus \"t_v_evaluation (path_interpretation A r ?u) F = Ttrue\"\n          proof(rule disjE)\n            assume  \"F \\<in> \\<G>' A r\"\n            hence \"\\<exists>u. \\<exists>v. u\\<in>A \\<and> v\\<in>A  \\<and> (v,u)\\<in> r  \\<and>\n                  (F = (atom u) \\<rightarrow>. (atom v))\"\n              by (unfold  \\<G>'_def, auto)\n            then obtain u v where \"u\\<in>A\" and \"v\\<in>A\" and \"(v,u)\\<in> r\" \n            and F: \"(F = (atom u) \\<rightarrow>. (atom v))\" by auto\n            show \"t_v_evaluation (path_interpretation A r ?u) F = Ttrue\"  \n            proof(rule ccontr)\n              assume \"\\<not>(t_v_evaluation (path_interpretation A r ?u) F = Ttrue)\" \n              hence \"t_v_evaluation (path_interpretation A r ?u) F = Ffalse\"\n                using CasosValor by auto\n              hence \"t_v_evaluation (path_interpretation A r ?u) (atom u) =  Ttrue \\<and>\n              t_v_evaluation (path_interpretation A r ?u) (atom v) =  Ffalse\" \n                using F  eval_false_implication by blast\n              hence 1: \"t_v_evaluation (path_interpretation A r ?u) (atom u) =  Ttrue\"\n              and   2: \"t_v_evaluation (path_interpretation A r ?u) (atom v) =  Ffalse\"\n                by auto\n              have \"(u,?u)\\<in>r\" using 1 value_path_interpretation by auto\n              hence \"(v,?u)\\<in> r\" \n                using  `u\\<in>A` `v\\<in>A` `?u\\<in>A` `(v,u)\\<in> r` `transitive_on A r` \n                by(unfold transitive_on_def, blast)\n              hence \"t_v_evaluation (path_interpretation A r ?u) (atom v) =  Ttrue\" \n                by auto\n              thus False using 2 by auto\n            qed\n          next\n            assume  \"F \\<in> \\<H>' A r\" \n            hence \"\\<exists>n. F \\<in> \\<H>n A r n\" by(unfold  \\<H>'_def, auto)\n            then obtain n where  \"F \\<in> \\<H>n A r n\" by auto\n            hence\n            \"\\<exists>u. \\<exists>v. F = \\<not>.((atom u) \\<and>. (atom v)) \\<and> u\\<in>(level A r n) \\<and>\n             v\\<in>(level A r n) \\<and> u\\<noteq>v\"\n              by(unfold \\<H>n_def, auto)  \n            then obtain u v where F: \"F = \\<not>.((atom u) \\<and>. (atom v))\" \n            and \"u\\<in>(level A r n)\" and \"v\\<in>(level A r n)\" and \"u\\<noteq>v\"\n              by auto\n            show \"t_v_evaluation (path_interpretation A r ?u) F = Ttrue\"  \n            proof(rule ccontr)\n              assume \"t_v_evaluation (path_interpretation A r ?u) F \\<noteq> Ttrue\"\n              hence \"t_v_evaluation (path_interpretation A r ?u) F = Ffalse\"\n                using CasosValor by auto\n              hence\n              \"t_v_evaluation (path_interpretation A r ?u)((atom u) \\<and>.\n               (atom v)) = Ttrue\" \n                using F  NegationValues1 by blast\n              hence \"t_v_evaluation (path_interpretation A r ?u)(atom u) = Ttrue \\<and>\n              t_v_evaluation (path_interpretation A r ?u)(atom v) = Ttrue\"\n                using ConjunctionValues by blast\n              hence \"(u,?u)\\<in>r\" and  \"(v,?u)\\<in>r\"\n                using  value_path_interpretation by auto\n              hence a: \"(level A r n) \\<inter> (level A r n) = {}\"\n                using `tree A r`  `u\\<in>(level A r n)`  `v\\<in>(level A r n)`  `u\\<noteq>v`\n                emptyness_inter_diff_levels[of A r]\n                by blast\n              have \"(level A r n) \\<noteq> {}\" \n                using  `v\\<in>(level A r n)` by auto           \n              thus False using a by auto \n            qed\n          qed\n        qed\n      qed\n    qed\n  qed\n  thus \"satisfiable S\" by(unfold satisfiable_def, auto)\nqed\n\ndefinition \\<B>:: \"'a set \\<Rightarrow> ('a  \\<Rightarrow> v_truth) \\<Rightarrow> 'a set\" where\n\"\\<B> A I  \\<equiv> {u|u. u\\<in>A \\<and> t_v_evaluation I (atom u) = Ttrue}\"\n\nlemma value_disjunction_lista1:\n  assumes \"t_v_evaluation I (disjunction_nodes (a # l)) = Ttrue\"\n  shows \"t_v_evaluation I (atom a) = Ttrue \\<or> t_v_evaluation I (disjunction_nodes l) = Ttrue\" \nproof-\n  have \"disjunction_nodes (a # l) = (atom a) \\<or>. (disjunction_nodes l)\"\n    by auto\n  hence \"t_v_evaluation I ((atom a) \\<or>. (disjunction_nodes l)) = Ttrue\" \n    using assms by auto\n  thus ?thesis using DisjunctionValues by blast\nqed\n\nlemma value_disjunction_lista:\n  assumes \"t_v_evaluation I (disjunction_nodes l) = Ttrue\"\n  shows \"\\<exists>x. x \\<in> set l \\<and> t_v_evaluation I (atom x) = Ttrue\" \nproof-\n  have \"t_v_evaluation I (disjunction_nodes l) = Ttrue \\<Longrightarrow>\n  \\<exists>x. x \\<in> set l \\<and>  t_v_evaluation I (atom x) = Ttrue\" \n  proof(induct l)\n    case Nil\n    then show ?case by auto\n  next   \n    case (Cons a l)  \n    show  \"\\<exists>x. x \\<in> set (a # l) \\<and> t_v_evaluation I (atom x) = Ttrue\"  \n    proof-\n      have \"t_v_evaluation I (atom a) = Ttrue \\<or> t_v_evaluation I (disjunction_nodes l)=Ttrue\" \n        using Cons(2) value_disjunction_lista1[of I] by auto      \n      thus ?thesis\n    proof(rule disjE)\n      assume \"t_v_evaluation I (atom a) = Ttrue\"\n      thus ?thesis by auto\n    next\n      assume \"t_v_evaluation I (disjunction_nodes l) = Ttrue\" \n      thus ?thesis\n        using Cons by auto    \n    qed\n  qed\nqed\n  thus ?thesis using assms by auto\nqed \n\nlemma intersection_branch_set_nodes_at_level:\n  assumes \"infinite_tree A r\" and \"finite_branches A r\" \n  and I: \"\\<forall>F \\<in> (\\<F>' A r). t_v_evaluation I F = Ttrue\"\nshows \"\\<forall>n. \\<exists>x. x \\<in> level A r n \\<and> x \\<in> (\\<B> A I)\" using all_levels_non_empty\nproof- \n  fix n \n  have \"\\<forall>n. t_v_evaluation I (disjunction_nodes(set_to_list (level A r n))) = Ttrue\"\n    using I by (unfold \\<F>'_def, auto)\n  hence 1:\n  \"\\<forall>n. \\<exists>x. x \\<in> set (set_to_list (level A r n)) \\<and> t_v_evaluation I (atom x) = Ttrue\"\n    using value_disjunction_lista by auto\n  have \"tree A r\" \n    using `infinite_tree A r`by auto\n  hence \"\\<forall>n. set (set_to_list (level A r n)) = level A r n\" \n    using assms(1-2)  set_set_to_list1 by auto\n  hence  \"\\<forall>n. \\<exists>x. x \\<in> level A r n \\<and>  t_v_evaluation I (atom x) = Ttrue\"\n    using 1  by auto\n  hence  \"\\<forall>n. \\<exists>x. x \\<in> level A r n \\<and> x\\<in>A \\<and> t_v_evaluation I (atom x) = Ttrue\" \n    by(unfold level_def, auto)\n  thus ?thesis using \\<B>_def[of A I] by auto\nqed\n\nlemma intersection_branch_emptyness_below_height:\n  assumes I:  \"\\<forall>F \\<in> (\\<H>' A r). t_v_evaluation I F = Ttrue\" \n  and \"x\\<in>(\\<B> A I)\"  and  \"y\\<in>(\\<B> A I)\"  and  \"x \\<noteq> y\" and  n: \"x \\<in> level A r n\"\n  and m: \"y \\<in> level A r m\" \nshows  \"n \\<noteq> m\"\nproof(rule ccontr)\n  assume \"\\<not> n \\<noteq> m\"\n  hence \"n=m\" by auto\n  have \"x\\<in>A\" and  \"y\\<in>A\" and v1: \"t_v_evaluation I (atom x) = Ttrue\" \n  and v2: \"t_v_evaluation I (atom y) = Ttrue\" \n    using  `x\\<in>(\\<B> A I)` `y\\<in>(\\<B> A I)`  by(unfold \\<B>_def, auto) \n  have \"\\<not>.((atom x) \\<and>. (atom y)) \\<in> (\\<H>n A r n)\" \n    using `x\\<in>A`   `y\\<in>A`  `x \\<noteq> y` n m `n=m`\n    by(unfold \\<H>n_def, auto)             \n  hence \"\\<not>.((atom x) \\<and>. (atom y)) \\<in> (\\<H>' A r)\"\n    by(unfold \\<H>'_def, auto)                   \n  hence \"t_v_evaluation I (\\<not>.((atom x) \\<and>. (atom y))) = Ttrue\"\n    using I by auto\n  moreover                  \n  have \"t_v_evaluation I ((atom x) \\<and>. (atom y)) = Ttrue\"\n    using v1 v2 v_conjunction_def by auto\n  hence \"t_v_evaluation I (\\<not>.((atom x) \\<and>. (atom y))) = Ffalse\" \n    using v_negation_def by auto \n  ultimately\n  show False by auto\nqed\n\nlemma intersection_branch_level: \n  assumes  \"infinite_tree A r\" and \"finite_branches A r\" \n  and I: \"\\<forall>F \\<in> (\\<F>' A r) \\<union> (\\<H>' A r). t_v_evaluation I F = Ttrue\"\nshows \"\\<forall>n. \\<exists>u. (\\<B> A I) \\<inter>  level A r n = {u}\"\nproof\n  fix n \n  show \"\\<exists>u. (\\<B> A I) \\<inter> level A r n = {u}\" \n  proof-\n    have \"\\<exists>u. u \\<in> level A r n \\<and> u \\<in> (\\<B> A I)\" \n      using assms intersection_branch_set_nodes_at_level[of A r I] by auto\n    then obtain u where u: \"u \\<in> level A r n \\<and> u\\<in>(\\<B> A I)\" by auto\n    hence 1:  \"{u} \\<subseteq> (\\<B> A I) \\<inter> level A r n\" by blast\n    have 2:  \"(\\<B> A I) \\<inter> level A r n \\<subseteq> {u}\"\n    proof(rule subsetI)\n      fix x\n      assume  \"x\\<in>(\\<B> A I) \\<inter> level A r n\"\n      hence 2: \"x\\<in>(\\<B> A I) \\<and> x\\<in> level A r n\"  by auto\n      have \"u = x\"\n      proof(rule ccontr)\n        assume \"u \\<noteq> x\"\n        hence \"n\\<noteq>n\" \n          using u 2 I intersection_branch_emptyness_below_height[of A r] by blast\n        thus False by auto\n      qed\n      thus \"x\\<in>{u}\" by auto\n    qed\n    have \"(\\<B> A I) \\<inter> level A r n = {u}\"\n      using 1 2 by auto\n    thus \"\\<exists>u.(\\<B> A I) \\<inter>  level A r n = {u}\"  by auto\n  qed\nqed\n\nlemma predecessor_in_branch:\n  assumes I:  \"\\<forall>F \\<in> (\\<G>' A r). t_v_evaluation I F = Ttrue\" \n  and \"y\\<in>(\\<B> A I)\"  and  \"(x,y)\\<in> r\" and \"x\\<in>A\" and \"y\\<in>A\"\nshows \"x\\<in>(\\<B> A I)\"\nproof- \n  have \"(atom y) \\<rightarrow>. (atom x)\\<in> \\<G>' A r\" \n    using `x\\<in>A`  `y\\<in>A`  `(x, y)\\<in>r` by (unfold  \\<G>'_def, auto)\n  hence \"t_v_evaluation I ((atom y) \\<rightarrow>. (atom x)) = Ttrue\"\n    using I by auto\n  moreover\n  have \"t_v_evaluation I (atom y) = Ttrue\" \n    using  `y\\<in>(\\<B> A I)` by(unfold \\<B>_def, auto)\n  ultimately\n  have \"t_v_evaluation I (atom x) = Ttrue\"\n    using v_implication_def by  auto\n  thus  \"x\\<in>(\\<B> A I)\" using  `x\\<in>A`  by(unfold \\<B>_def, auto) \nqed\n\nlemma branch: \n  assumes  \"infinite_tree A r\" and \"finite_branches A r\" \n  and I: \"\\<forall>F \\<in> (\\<T>' A r). t_v_evaluation I F = Ttrue\" \nshows \"path (\\<B> A I) A r\"\nproof(unfold path_def)\n  let ?B = \"(\\<B> A I)\" \n  have \"tree A r\" \n  using  `infinite_tree A r` by auto\n  have \"\\<forall>F \\<in> (\\<F>' A r) \\<union> (\\<G>' A r) \\<union> (\\<H>' A r). t_v_evaluation I F = Ttrue\"\n    using I by(unfold \\<T>'_def)\n  hence I1:  \"\\<forall>F \\<in> (\\<F>' A r). t_v_evaluation I F = Ttrue\" \n  and   I2:  \"\\<forall>F \\<in> (\\<G>' A r). t_v_evaluation I F = Ttrue\"\n  and   I3:  \"\\<forall>F \\<in> (\\<H>' A r). t_v_evaluation I F = Ttrue\" \n    by auto \n  have 0: \"sub_linear_order ?B A r\"\n  proof(unfold sub_linear_order_def)\n    have 1: \"?B \\<subseteq> A\"  by(unfold \\<B>_def, auto)\n    have 2: \"strict_part_order A r\" \n      using `tree A r` tree[of A r] by auto\n    have \"total_on ?B r\"\n    proof(unfold total_on_def)\n      show \"\\<forall>x\\<in>?B. \\<forall>y\\<in>?B. x \\<noteq> y \\<longrightarrow> (x, y) \\<in> r \\<or> (y, x) \\<in> r\"\n      proof\n        fix x\n        assume \"x\\<in>?B\" \n        show \"\\<forall>y\\<in>?B. x \\<noteq> y \\<longrightarrow> (x, y) \\<in> r \\<or> (y, x) \\<in> r\"\n        proof              \n          fix y\n          assume \"y\\<in>?B\"\n          show \"x \\<noteq> y \\<longrightarrow> (x, y) \\<in> r \\<or> (y, x) \\<in> r\" \n          proof(rule impI)\n            assume \"x \\<noteq> y\" \n            have \"x\\<in>A\" and \"y\\<in>A\" and v1: \"t_v_evaluation I (atom x) = Ttrue\" \n            and v2: \"t_v_evaluation I (atom y) = Ttrue\" \n              using `x\\<in>?B` `y\\<in>?B`  by(unfold \\<B>_def, auto)\n            have \"(\\<exists>n. x \\<in> level A r n)\" and \"(\\<exists>m. y \\<in> level A r m)\" \n              using `x\\<in>A` and `y\\<in>A` level_element[of A r]\n              by auto\n            then obtain n m\n            where n: \"x \\<in> level A r n\" and m: \"y \\<in> level A r m\"\n              by auto             \n            have \"n\\<noteq>m\"\n              using I3 `x\\<in>?B` `y\\<in>?B` `x \\<noteq> y` n m \n                    intersection_branch_emptyness_below_height[of A r]\n              by auto                \n            hence \"n<m \\<or> m<n\" by auto\n            thus \"(x, y) \\<in> r \\<or> (y, x) \\<in> r\" \n            proof(rule disjE)\n              assume  \"n < m\"  \n              have \"(x, y) \\<in> r\"\n              proof(rule ccontr)\n                assume \"(x, y) \\<notin> r\"\n                have \"\\<exists>z. (z, y)\\<in>r \\<and> z \\<in> level A r n\" \n                  using `tree A r` `y \\<in> level A r m` `n < m`\n                         path_to_node[of A r y \"m-1\"]\n                  by auto \n                then obtain z where z1: \"(z, y)\\<in>r\" and z2: \"z \\<in> level A r n\"\n                  by auto \n                have \"z\\<in>A\" using  `tree A r` tree z1 by auto\n                hence \"z\\<in>(\\<B> A I)\" \n                  using I2 `y\\<in>A` `y\\<in>?B` `(z, y)\\<in>r` predecessor_in_branch[of A r I y z]\n                  by auto\n                have \"x\\<noteq>z\" using `(x, y) \\<notin> r` `(z, y)\\<in>r` by auto  \n                hence \"n\\<noteq>n\"\n                  using I3 `x\\<in>?B` `z\\<in>?B` n z2  intersection_branch_emptyness_below_height[of A r]\n                  by blast  \n                thus False by auto \n              qed\n              thus \"(x, y) \\<in> r \\<or> (y, x) \\<in> r\" by auto\n            next\n              assume \"m < n\"\n              have \"(y, x) \\<in> r\"\n              proof(rule ccontr)\n                assume \"(y, x) \\<notin> r\"\n                have \"\\<exists>z. (z, x)\\<in>r \\<and> z \\<in> level A r m\" \n                  using `tree A r`  `x \\<in> level A r n`  `m < n`\n                         path_to_node[of A r x \"n-1\"]\n                  by auto \n                  then obtain z where z1: \"(z, x)\\<in>r\" and z2: \"z \\<in> level A r m\"\n                  by auto \n                have \"z\\<in>A\" using  `tree A r` tree z1 by auto\n                hence  \"z\\<in>(\\<B> A I)\" \n                  using I2 `x\\<in>A` `x\\<in>?B` `(z, x)\\<in>r` predecessor_in_branch[of A r I x z]\n                  by auto\n                have \"y\\<noteq>z\" using `(y, x) \\<notin> r` `(z, x)\\<in>r` by auto  \n                hence \"m\\<noteq>m\"\n                  using I3 `y\\<in>?B` `z\\<in>?B` m z2 intersection_branch_emptyness_below_height[of A r ]\n                  by blast\n                thus False by auto \n              qed\n              thus \"(x, y) \\<in> r \\<or> (y, x) \\<in> r\" by auto\n            qed\n          qed\n        qed\n      qed\n    qed\n    thus 3: \"?B \\<subseteq> A \\<and> strict_part_order A r \\<and> total_on ?B r\"\n      using 1 2 by auto             \n  qed             \n  have 4: \"(\\<forall>C. ?B \\<subseteq> C \\<and> sub_linear_order C A r \\<longrightarrow> ?B = C)\"               \n  proof\n    fix C\n    show \"?B \\<subseteq> C \\<and> sub_linear_order C A r \\<longrightarrow> ?B = C\"\n    proof(rule impI)\n      assume \"?B \\<subseteq> C \\<and> sub_linear_order C A r\"\n      hence \"?B \\<subseteq> C\" and  \"sub_linear_order C A r\" by auto\n      have \"C \\<subseteq> ?B\"           \n      proof(rule subsetI)\n          fix x\n          assume \"x\\<in> C\"\n        have \"C \\<subseteq> A\"\n          using `sub_linear_order C A r`\n         by(unfold sub_linear_order_def, auto)\n        hence \"x\\<in>A\" using `x\\<in>C` by auto\n        have \"\\<exists>n. x\\<in>level A r n\" \n          using `x\\<in>A` level_element[of A] by auto\n        then obtain n where n: \"x\\<in>level A r n\" by auto\n        have \"\\<exists>u. (\\<B> A I) \\<inter> level A r n = {u}\"\n          using assms(1,2) I1 I3 intersection_branch_level[of A r]\n          by blast\n        then obtain u where i: \"(\\<B> A I) \\<inter> level A r n = {u}\" \n          by auto\n        hence \"u\\<in>A\" and u: \"u \\<in> level A r n\"\n         by(unfold level_def, auto)\n        have \"x=u\" \n        proof(rule ccontr)               \n          assume hip: \"x\\<noteq>u\" \n          have \"u\\<in>(\\<B> A I)\" using i by auto\n          hence \"u\\<in>C\" using `?B \\<subseteq> C` by auto\n          have \"total_on C r\"\n            using `sub_linear_order C A r` sub_linear_order_def[of C A r]\n            by blast         \n          hence \"(x,u)\\<in>r \\<or> (u,x)\\<in>r\" \n            using hip `x\\<in>C` `u\\<in>C` `sub_linear_order C A r`\n            by(unfold total_on_def,auto)\n          thus False\n          proof(rule disjE)\n            assume \"(x,u)\\<in>r\"               \n            have \"r \\<subseteq> A \\<times> A\" and \"strict_part_order A r\" \n            and \"finite (predecessors A u r)\"\n              using `u\\<in>A` `tree A r` tree[of A r] by auto\n            hence  \"(level A r n) \\<noteq> (level A r n)\" \n              using `(x,u)\\<in>r` `x \\<in> level A r n` `u \\<in> level A r n` \n                    different_levels_finite_pred[of r A ] by blast\n            thus False by auto\n          next\n            assume \"(u,x)\\<in>r\"               \n            have \"r \\<subseteq> A \\<times> A\" and \"strict_part_order A r\" \n            and \"finite (predecessors A x r)\"\n              using `x\\<in>A` `tree A r` tree[of A r]  by auto\n            hence \"(level A r n) \\<noteq> (level A r n)\" \n              using `(u,x)\\<in>r` `u \\<in> level A r n` `x \\<in> level A r n`\n                    different_levels_finite_pred[of r A ] by blast\n            thus False by auto\n          qed\n        qed          \n        thus \"x \\<in> ?B\" using i by auto\n      qed\n      thus  \"?B = C\"  using `?B \\<subseteq> C` by blast\n    qed\n  qed\n  thus \"sub_linear_order (\\<B> A I) A r \\<and>\n          (\\<forall>C. \\<B> A I \\<subseteq> C \\<and> sub_linear_order C A r \\<longrightarrow> \\<B> A I = C)\"\n    using `sub_linear_order (\\<B> A I) A r` by auto\nqed\n\nlemma surjective_infinite:\n  assumes  \"\\<exists>f:: 'a \\<Rightarrow> nat. \\<forall>n. \\<exists>x\\<in>A. n = f(x)\"\n  shows \"infinite A\"\nproof(rule ccontr)\n  assume \"\\<not> infinite A\"\n  hence \"finite A\" by auto\n  hence \"\\<exists>n. \\<exists>g. A = g ` {i::nat. i < n}\"\n    using finite_imp_nat_seg_image_inj_on[of A] by auto \n  then obtain n g where g: \"A = g ` {i::nat. i < n}\" by auto\n  obtain f where  \"(\\<forall>n. \\<exists>x\\<in>A. n = (f:: 'a \\<Rightarrow>  nat)(x))\" \n    using assms by auto\n  hence \"\\<forall>m. \\<exists>k\\<in>{i::nat. i < n}. m =(f \\<circ> g)(k)\"\n    using g  by auto\n  hence  \"(UNIV :: nat set)  = (f \\<circ> g) ` {i::nat. i < n}\"\n    by blast\n  hence  \"finite (UNIV :: nat set)\" \n    using nat_seg_image_imp_finite by blast \n  thus False by auto\nqed\n\nlemma family_intersection_infinita:\n  fixes P :: \" nat \\<Rightarrow> 'a set\"\n  assumes \"\\<forall>n. \\<forall>m. n \\<noteq> m \\<longrightarrow> P n \\<inter> P m = {}\" \n  and  \"\\<forall>n. (A \\<inter> (P n)) \\<noteq> {}\"\n  shows \"infinite (\\<Union>n. (A \\<inter> (P n)))\" \nproof-\n  let ?f = \"\\<lambda>x. SOME n. x\\<in>(A \\<inter> (P n))\"\n  have \"\\<forall>n. \\<exists>x\\<in>(\\<Union>n. (A \\<inter> (P n))). n = ?f(x)\"\n  proof\n    fix n\n    obtain a where a:  \"a \\<in> (A \\<inter> (P n))\" using assms(2) by auto\n    {fix m\n    have  \"a \\<in> (A \\<inter> (P m)) \\<longrightarrow> m=n\" \n    proof(rule impI)\n      assume hip: \"a \\<in> A \\<inter> P m\" show \"m =n\"\n      proof(rule ccontr)\n        assume \"m \\<noteq> n\"\n        hence \"P m \\<inter> P n = {}\" using assms(1) by auto\n        thus False using a hip by auto\n      qed\n    qed}\n    hence \"\\<And>m. a \\<in> A \\<inter> P m \\<Longrightarrow> m = n\" by auto\n    hence 1: \"?f(a) = n\"  using a  some_equality by auto\n    have \"a\\<in>(\\<Union>n. (A \\<inter> (P n)))\" using a by auto\n    thus \"\\<exists>x\\<in>\\<Union>n. A \\<inter> P n. n = (SOME n. x \\<in> A \\<inter> P n)\" using 1 by auto\n  qed\n  hence  \"\\<exists>f:: 'a \\<Rightarrow>  nat. \\<forall>n. \\<exists>x\\<in>((\\<Union>n. (A \\<inter> (P n)))). n = f(x)\" \n    using exI  by auto\n  thus ?thesis using surjective_infinite by auto\nqed\n\nlemma infinite_path:\n  assumes  \"infinite_tree A r\" and  \"finite_branches A r\"\n  and  I: \"\\<forall>F \\<in> (\\<F>' A r). t_v_evaluation I F = Ttrue\"\nshows \"infinite (\\<B> A I)\"\nproof-\n  have a: \"\\<forall>n. \\<forall>m.  n \\<noteq> m \\<longrightarrow> level A r n \\<inter> level A r m = {}\"\n    using uniqueness_level[of _ _ A r] by auto \n  have  \"\\<forall>n. \\<B> A I \\<inter> level A r n \\<noteq> {}\"\n    using `infinite_tree A r`\n          `finite_branches A r` I  intersection_branch_set_nodes_at_level[of A r]\n    by blast  \n  hence  \"infinite (\\<Union>n. (\\<B> A I) \\<inter>  level A r n)\"\n    using family_intersection_infinita  a  by auto\n  thus \"infinite (\\<B> A I)\"by auto \nqed\n\ntheorem Koenig_Lemma:\n  assumes  \"infinite_tree (A::'nodes set) r\" \n  and  \"enumeration (g:: nat \\<Rightarrow>'nodes)\" \n  and \"finite_branches A r\" \n  shows  \"\\<exists>B. infinite_path B A r\"\nproof-\n  have  \"satisfiable (\\<T>' A r)\" \n  proof- \n    have \"\\<forall> S. S \\<subseteq> (\\<T>' A r) \\<and> (finite S) \\<longrightarrow> satisfiable S\" \n      using `infinite_tree A r` `finite_branches A r` satisfiable_path\n      by auto\n    moreover\n    have \"\\<exists>h. enumeration (h:: nat \\<Rightarrow>'nodes formula)\"\n      using EnumerationFormulasP1[OF  `enumeration (g:: nat \\<Rightarrow>'nodes)`]\n      by auto\n    ultimately\n    show \"satisfiable (\\<T>' A r)\"\n      using Compacteness_Theorem[of \"(\\<T>' A r)\"] by auto\n  qed\n  hence \"\\<exists>I. (\\<forall>F \\<in> (\\<T>' A r). t_v_evaluation I F = Ttrue)\" \n    by(unfold satisfiable_def, unfold model_def, auto) \n  then obtain I where I:  \"\\<forall>F \\<in> (\\<T>' A r). t_v_evaluation I F = Ttrue\"  \n    by auto\n  hence \"\\<forall>F \\<in> (\\<F>' A r) \\<union> (\\<G>' A r) \\<union> (\\<H>' A r). t_v_evaluation I F = Ttrue\"\n    by(unfold \\<T>'_def)\n  hence I1:  \"\\<forall>F \\<in> (\\<F>' A r). t_v_evaluation I F = Ttrue\" \n  and   I2:  \"\\<forall>F \\<in> (\\<G>' A r). t_v_evaluation I F = Ttrue\"\n  and   I3:  \"\\<forall>F \\<in> (\\<H>' A r). t_v_evaluation I F = Ttrue\" \n    by auto \n  let ?B = \"(\\<B> A I)\"\n  have \"infinite_path ?B A r\"\n  proof(unfold infinite_path_def)\n    show \"path ?B A r \\<and> infinite ?B\" \n    proof(rule conjI)\n      show \"path ?B A r\"\n        using  `infinite_tree A r` `finite_branches A r` I branch[of A r]\n        by auto   \n      show \"infinite (\\<B> A I)\"\n        using `infinite_tree A r` `finite_branches A r` I1 infinite_path\n      by auto     \n    qed\n  qed\n  thus \"\\<exists>B. infinite_path B A r\" by auto\nqed\n           \nend\n \n", "meta": {"author": "mayalarincon", "repo": "halltheorem", "sha": "6c694d6b154df4576b648810a5ec2f1814a0c99b", "save_path": "github-repos/isabelle/mayalarincon-halltheorem", "path": "github-repos/isabelle/mayalarincon-halltheorem/halltheorem-6c694d6b154df4576b648810a5ec2f1814a0c99b/KoenigLemma.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8902942261220292, "lm_q2_score": 0.8128673246376009, "lm_q1q2_score": 0.7236910857281172}}
{"text": "section \\<open> Trace Algebras \\<close>\n\ntheory Trace_Algebra\n  imports \n    \"List_Extra\"\n    \"Positive\"\nbegin\n\ntext \\<open> Trace algebras provide a useful way in the UTP of characterising different notions of trace\n  history. They can characterise notions as diverse as discrete event sequences and piecewise \n  continuous functions, as employed by hybrid systems. For more information, please see our\n  journal publication~\\cite{Foster17b}. \\<close>\n\nsubsection \\<open> Ordered Semigroups \\<close>\n\nclass ordered_semigroup = semigroup_add + order +\n  assumes add_left_mono: \"a \\<le> b \\<Longrightarrow> c + a \\<le> c + b\"\n  and add_right_mono: \"a \\<le> b \\<Longrightarrow> a + c \\<le> b + c\"\nbegin\n\nlemma add_mono:\n  \"a \\<le> b \\<Longrightarrow> c \\<le> d \\<Longrightarrow> a + c \\<le> b + d\"\n  using local.add_left_mono local.add_right_mono local.order.trans by blast\n\nend\n\nsubsection \\<open> Monoid Subclasses \\<close>\n\nclass left_cancel_monoid = monoid_add +\n  assumes add_left_imp_eq: \"a + b = a + c \\<Longrightarrow> b = c\"\n\nclass right_cancel_monoid = monoid_add +\n  assumes add_right_imp_eq: \"b + a = c + a \\<Longrightarrow> b = c\"\n\ntext \\<open> Positive Monoids \\<close>\n\nclass monoid_pos = monoid_add +\n  assumes zero_sum_left: \"a + b = 0 \\<Longrightarrow> a = 0\"\nbegin\n\nlemma zero_sum_right: \"a + b = 0 \\<Longrightarrow> b = 0\"\n  by (metis local.add_0_left local.zero_sum_left)\n\nlemma zero_sum: \"a + b = 0 \\<longleftrightarrow> a = 0 \\<and> b = 0\"\n  by (metis local.add_0_right zero_sum_right)\n\nend\n\ncontext monoid_add\nbegin\n\ntext \\<open> An additive monoid gives rise to natural notions of order, which we here define. \\<close>\n\ndefinition monoid_le (infix \"\\<le>\\<^sub>m\" 50)\nwhere \"a \\<le>\\<^sub>m b \\<longleftrightarrow> (\\<exists>c. b = a + c)\"\n\ntext \\<open> We can also define a subtraction operator that remove a prefix from a monoid, if possible. \\<close>\n\ndefinition monoid_subtract (infixl \"-\\<^sub>m\" 65)\nwhere \"a -\\<^sub>m b = (if (b \\<le>\\<^sub>m a) then THE c. a = b + c else 0)\"\n\ntext \\<open> We derive some basic properties of the preorder \\<close>\n\nlemma monoid_le_least_zero: \"0 \\<le>\\<^sub>m a\"\n  by (simp add: monoid_le_def)\n\nlemma monoid_le_add: \"a \\<le>\\<^sub>m a + b\"\n  by (auto simp add: monoid_le_def)\n\nlemma monoid_le_refl: \"a \\<le>\\<^sub>m a\"\n  by (simp add: monoid_le_def, metis add.right_neutral)\n\nlemma monoid_le_trans: \"\\<lbrakk> a \\<le>\\<^sub>m b; b \\<le>\\<^sub>m c \\<rbrakk> \\<Longrightarrow> a \\<le>\\<^sub>m c\"\n  by (metis add.assoc monoid_le_def)\n\nlemma monoid_le_add_left_mono: \"a \\<le>\\<^sub>m b \\<Longrightarrow> c + a \\<le>\\<^sub>m c + b\"\n  using add_assoc by (auto simp add: monoid_le_def)\n\nend \n\nclass ordered_monoid_pos = monoid_pos + ord +\n  assumes le_is_monoid_le: \"a \\<le> b \\<longleftrightarrow> (a \\<le>\\<^sub>m b)\"\n  and less_iff: \"a < b \\<longleftrightarrow> a \\<le> b \\<and> \\<not> (b \\<le> a)\"\nbegin\n\n  subclass preorder\n  proof\n    fix x y z :: \"'a\"\n    show \"(x < y) = (x \\<le> y \\<and> \\<not> y \\<le> x)\"\n      by (simp add: local.less_iff)\n    show \"x \\<le> x\"\n      by (simp add: local.le_is_monoid_le local.monoid_le_refl)\n    show \"x \\<le> y \\<Longrightarrow> y \\<le> z \\<Longrightarrow> x \\<le> z\"\n      using local.le_is_monoid_le local.monoid_le_trans by blast\n  qed\n\nend\n\nsubsection \\<open> Trace Algebras \\<close>\n\ntext \\<open> A pre-trace algebra is based on a left-cancellative monoid with the additional property that\n  plus has no additive inverse. The latter is required to ensure that there are no ``negative \n  traces''. A pre-trace algebra has all the trace algebra axioms, but does not export the definitions\n  of @{term \"(\\<le>)\"} and @{term \"(-)\"}. \\<close>\n\n\nclass pre_trace = left_cancel_monoid + monoid_pos\nbegin\n\ntext \\<open> From our axiom set, we can derive a variety of properties of the monoid order \\<close>\n  \nlemma monoid_le_antisym:\n  assumes \"a \\<le>\\<^sub>m b\" \"b \\<le>\\<^sub>m a\"\n  shows \"a = b\"\nproof -\n  obtain a' where a': \"b = a + a'\"\n    using assms(1) monoid_le_def by auto\n\n  obtain b' where b': \"a = b + b'\"\n    using assms(2) monoid_le_def by auto\n\n  have \"b' = (b' + a' + b')\"\n    by (metis a' add_assoc b' local.add_left_imp_eq)\n\n  hence \"a' + b' = 0\"\n    by (metis add_assoc local.add_0_right local.add_left_imp_eq)\n\n  hence \"a' = 0\" \"b' = 0\"\n    by (simp add: zero_sum)+\n\n  with a' b' show ?thesis\n    by simp\nqed\n\n\ntext \\<open> The monoid minus operator is also the inverse of plus in this context, as expected. \\<close>\n\nlemma add_monoid_diff_cancel_left [simp]: \"(a + b) -\\<^sub>m a = b\"\n  apply (simp add: monoid_subtract_def monoid_le_add)\n  apply (rule the_equality)\n   apply (simp)\n  using local.add_left_imp_eq apply blast\n  done\n\ntext \\<open> Iterating a trace \\<close>\n\nfun tr_iter :: \"nat \\<Rightarrow> 'a \\<Rightarrow> 'a\" where\ntr_iter_0: \"tr_iter 0 t = 0\" |\ntr_iter_Suc: \"tr_iter (Suc n) t = tr_iter n t + t\"\n\nlemma tr_iter_empty [simp]: \"tr_iter m 0 = 0\"\n  by (induct m, simp_all)\n\nend\n\ntext \\<open> We now construct the trace algebra by also exporting the order and minus operators. \\<close>\n\nclass trace = pre_trace + ord + minus +\n  assumes le_is_monoid_le: \"a \\<le> b \\<longleftrightarrow> (a \\<le>\\<^sub>m b)\"\n  and less_iff: \"a < b \\<longleftrightarrow> a \\<le> b \\<and> \\<not> (b \\<le> a)\"\n  and minus_def: \"a - b = a -\\<^sub>m b\"\nbegin\n\ntext \\<open> Next we prove all the trace algebra lemmas. \\<close>\n\n  lemma le_iff_add: \"a \\<le> b \\<longleftrightarrow> (\\<exists> c. b = a + c)\"\n    by (simp add: local.le_is_monoid_le local.monoid_le_def)\n\n  lemma least_zero [simp]: \"0 \\<le> a\"\n    by (simp add: local.le_is_monoid_le local.monoid_le_least_zero)\n\n  lemma le_add [simp]: \"a \\<le> a + b\"\n    by (simp add: le_is_monoid_le local.monoid_le_add)\n\n  lemma not_le_minus [simp]:  \"\\<not> (a \\<le> b) \\<Longrightarrow> b - a = 0\"\n    by (simp add: le_is_monoid_le local.minus_def local.monoid_subtract_def)\n\n  lemma add_diff_cancel_left [simp]: \"(a + b) - a = b\"\n    by (simp add: minus_def)\n\n  lemma diff_zero [simp]: \"a - 0 = a\"\n    by (metis local.add_0_left local.add_diff_cancel_left)\n\n  lemma diff_cancel [simp]: \"a - a = 0\"\n    by (metis local.add_0_right local.add_diff_cancel_left)\n\n  lemma add_left_mono: \"a \\<le> b \\<Longrightarrow> c + a \\<le> c + b\"\n    by (simp add: local.le_is_monoid_le local.monoid_le_add_left_mono)\n\n  lemma add_le_imp_le_left: \"c + a \\<le> c + b \\<Longrightarrow> a \\<le> b\"\n    by (auto simp add: le_iff_add, metis add_assoc local.add_diff_cancel_left)\n      \n  lemma add_diff_cancel_left' [simp]:  \"(c + a) - (c + b) = a - b\"\n  proof (cases \"b \\<le> a\")\n    case True thus ?thesis\n      by (metis add_assoc local.add_diff_cancel_left local.le_iff_add)\n  next\n    case False thus ?thesis\n      using local.add_le_imp_le_left not_le_minus by blast\n  qed\n\n  lemma minus_zero_eq: \"\\<lbrakk> b \\<le> a; a - b = 0 \\<rbrakk> \\<Longrightarrow> a = b\"\n    using local.le_iff_add local.monoid_le_def by auto\n\n  lemma diff_add_cancel_left': \"a \\<le> b \\<Longrightarrow> a + (b - a) = b\"\n    using local.le_iff_add local.monoid_le_def by auto\n\n  lemma add_left_strict_mono: \"\\<lbrakk> a + b < a + c \\<rbrakk> \\<Longrightarrow> b < c\"\n    using local.add_le_imp_le_left local.add_left_mono local.less_iff by blast\n      \n  lemma sum_minus_left: \"c \\<le> a \\<Longrightarrow> (a + b) - c = (a - c) + b\"\n    by (metis add_assoc diff_add_cancel_left' local.add_monoid_diff_cancel_left local.minus_def)      \n      \n  lemma neq_zero_impl_greater:\n    \"x \\<noteq> 0 \\<Longrightarrow> 0 < x\"\n    using le_is_monoid_le less_iff monoid_le_antisym monoid_le_least_zero by auto\n \n  lemma minus_cancel_le:\n    \"\\<lbrakk> x \\<le> y; y \\<le> z \\<rbrakk> \\<Longrightarrow> y - x \\<le> z - x\"\n    using add_assoc le_iff_add by auto\n\n  lemma sum_minus_right: \"c \\<ge> a \\<Longrightarrow> a + b - c = b - (c - a)\"\n    by (metis diff_add_cancel_left' local.add_diff_cancel_left')\n\n  lemma minus_gr_zero_iff [simp]:\n    \"0 < x - y \\<longleftrightarrow> y < x\"\n    by (metis diff_cancel le_is_monoid_le least_zero less_iff minus_zero_eq monoid_le_antisym not_le_minus)\n\n  lemma le_zero_iff [simp]: \"x \\<le> 0 \\<longleftrightarrow> x = 0\"\n    using local.le_iff_add local.zero_sum by auto\n            \n  lemma minus_assoc [simp]: \"x - y - z = x - (y + z)\"\n    by (metis diff_add_cancel_left' le_add local.add_0_right local.add_diff_cancel_left' local.zero_sum minus_cancel_le not_le_minus)\n      \nend\n\nclass trace_split = trace +\n  assumes\n  sum_eq_sum_conv: \"(a + b) = (c + d) \\<Longrightarrow> \\<exists> e . a = c + e \\<and> e + b = d \\<or> a + e = c \\<and> b = e + d\"\n  \\<comment> \\<open> @{thm sum_eq_sum_conv} shows how two equal traces that are each composed of two subtraces,\n       can be expressed in terms of each other. \\<close>\nbegin\n\n  text \\<open> The set subtraces of a common trace $c$ is totally ordered. \\<close>\n\n  lemma le_common_total: \"\\<lbrakk> a \\<le> c; b \\<le> c \\<rbrakk> \\<Longrightarrow> a \\<le> b \\<or> b \\<le> a\"\n    by (metis diff_add_cancel_left' le_add local.sum_eq_sum_conv)  \n\n  lemma le_sum_cases: \"a \\<le> b + c \\<Longrightarrow> a \\<le> b \\<or> b \\<le> a\"\n    by (simp add: le_common_total)\n            \n  lemma le_sum_cases':\n    \"a \\<le> b + c \\<Longrightarrow> a \\<le> b \\<or> b \\<le> a \\<and> a - b \\<le> c\"\n    by (auto, metis le_sum_cases, metis minus_def le_is_monoid_le add_monoid_diff_cancel_left monoid_le_def sum_eq_sum_conv)\n\n  lemma le_sum_iff: \"a \\<le> b + c \\<longleftrightarrow> a \\<le> b \\<or> b \\<le> a \\<and> a - b \\<le> c\"\n    by (metis le_sum_cases' add_monoid_diff_cancel_left le_is_monoid_le minus_def monoid_le_add_left_mono monoid_le_def monoid_le_trans)\n\nend\n\n\n\ntext \\<open> Trace algebra give rise to a partial order on traces. \\<close>\n\ninstance trace \\<subseteq> order\n  apply (intro_classes)\n     apply (simp_all add: less_iff le_is_monoid_le monoid_le_refl)\n  using monoid_le_trans apply blast\n  apply (simp add: monoid_le_antisym)\n  done\n\nsubsection \\<open> Models \\<close>\n\ntext \\<open> Lists form a trace algebra. \\<close>\n\ninstantiation list :: (type) monoid_add\nbegin\n\n  definition zero_list :: \"'a list\" where \"zero_list = []\"\n  definition plus_list :: \"'a list \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where \"plus_list = (@)\"\n\ninstance\n  by (intro_classes, simp_all add: zero_list_def plus_list_def)\n\nend\n\nlemma monoid_le_list:\n  \"(xs :: 'a list) \\<le>\\<^sub>m ys \\<longleftrightarrow> xs \\<le> ys\"\n  apply (simp add: monoid_le_def plus_list_def)\n  apply (meson Prefix_Order.prefixE Prefix_Order.prefixI)\n  done\n\nlemma monoid_subtract_list:\n  \"(xs :: 'a list) -\\<^sub>m ys = xs - ys\"\n  apply (auto simp add: monoid_subtract_def monoid_le_list minus_list_def less_eq_list_def)\n   apply (rule the_equality)\n    apply (simp_all add: zero_list_def plus_list_def prefix_drop)\n  done\n\ninstance list :: (type) trace_split\n  apply (intro_classes, simp_all add: zero_list_def plus_list_def monoid_le_def monoid_subtract_list)\n  using Prefix_Order.prefixE apply blast\n   apply (simp add: less_list_def)\n  apply (simp add: append_eq_append_conv2)\n  done\n\nlemma monoid_le_nat:\n  \"(x :: nat) \\<le>\\<^sub>m y \\<longleftrightarrow> x \\<le> y\"\n  by (simp add: monoid_le_def nat_le_iff_add)\n\nlemma monoid_subtract_nat:\n  \"(x :: nat) -\\<^sub>m y = x - y\"\n  by (auto simp add: monoid_subtract_def monoid_le_nat)\n\ninstance nat :: trace_split\n  apply (intro_classes, simp_all add: monoid_subtract_nat)\n   apply (simp add: nat_le_iff_add monoid_le_def)\n   apply linarith+\n  apply (metis Nat.diff_add_assoc Nat.diff_add_assoc2 add_diff_cancel_right' add_le_cancel_left add_le_cancel_right add_less_mono cancel_ab_semigroup_add_class.add_diff_cancel_left' less_irrefl not_le)\n  done\n\ntext \\<open> Positives form a trace algebra. \\<close>\n    \ninstance pos :: (linordered_semidom) trace_split\nproof (intro_classes, simp_all)\n  fix a b c d :: \"'a pos\"\n  show \"a + b = 0 \\<Longrightarrow> a = 0\"\n    by (transfer, simp add: add_nonneg_eq_0_iff)\n  show \"a + b = c + d \\<Longrightarrow> \\<exists>e. a = c + e \\<and> e + b = d \\<or> a + e = c \\<and> b = e + d\"\n    apply (cases \"c \\<le> a\")\n     apply (metis (no_types, lifting) cancel_semigroup_add_class.add_left_imp_eq le_add_diff_inverse semiring_normalization_rules(25))\n    apply (metis (no_types, lifting) cancel_semigroup_add_class.add_left_imp_eq less_imp_le linordered_semidom_class.add_diff_inverse semiring_normalization_rules(21))\n    done\n  show \"(a < b) = (a \\<le> b \\<and> \\<not> b \\<le> a)\"\n    by auto    \n  show le_def: \"\\<And> a b :: 'a pos. (a \\<le> b) = (a \\<le>\\<^sub>m b)\"    \n    by (auto simp add: monoid_le_def, metis le_add_diff_inverse)  \n  show \"a - b = a -\\<^sub>m b\"\n    apply (auto simp add: monoid_subtract_def le_def[THEN sym])\n     apply (rule sym)\n     apply (rule the_equality)\n      apply (simp_all)\n    apply (transfer, simp)\n    done\nqed\n\nend\n", "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/Trace_Algebra.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8902942203004186, "lm_q2_score": 0.8128673087708698, "lm_q1q2_score": 0.7236910668698611}}
{"text": "(*\n * Copyright 2014, NICTA\n *\n * This software may be distributed and modified according to the terms of\n * the BSD 2-Clause license. Note that NO WARRANTY is provided.\n * See \"LICENSE_BSD2.txt\" for details.\n *\n * @TAG(NICTA_BSD)\n *)\n\ntheory ListLibLemmas\nimports List_Lib LemmaBucket\nbegin\n\n(* This theory contains various list results that\nare used in proofs related to the abstract cdt_list.*)\n\n(* Sorting a list given a partial ordering, where\n        elements are only necessarily comparable if\n        relation R holds between them. *)\nlocale partial_sort =\n  fixes less :: \"'a \\<Rightarrow> 'a \\<Rightarrow> bool\"\n  fixes R :: \"'a \\<Rightarrow> 'a \\<Rightarrow> bool\" \n \n  assumes all_comp: \"\\<And>x y. R x y \\<Longrightarrow> (less x y \\<or> less y x)\"\n\n  (*This is only necessary to guarantee the uniqueness of\n    sorted lists. *)\n  assumes antisym: \"\\<And>x y. R x y \\<Longrightarrow> less x y \\<and> less y x \\<Longrightarrow> x = y\"\n\n  assumes trans: \"\\<And>x y z. less x y \\<Longrightarrow>  less y z \\<Longrightarrow> less x z\"\n \nbegin\n\nprimrec pinsort :: \" 'a \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where\n   \"pinsort x [] = [x]\" |\n   \"pinsort x (y#ys) = (if (less x y) then (x#y#ys) else y#(pinsort x ys))\"\n\ninductive psorted :: \"'a list \\<Rightarrow> bool\" where\n  Nil [iff]: \"psorted []\"\n| Cons: \"\\<forall>y\\<in>set xs. less x y \\<Longrightarrow> psorted xs \\<Longrightarrow> psorted (x # xs)\"\n\ndefinition R_set where\n\"R_set S \\<equiv> \\<forall>x y. x \\<in> S \\<longrightarrow> y \\<in> S \\<longrightarrow> R x y\"\n\nabbreviation R_list where\n\"R_list xs \\<equiv> R_set (set xs)\"\n\ndefinition psort :: \"'a list \\<Rightarrow> 'a list\" where\n\"psort xs = foldr pinsort xs []\"\n\nend\n\ncontext partial_sort begin\n\nlemma psorted_Cons: \"psorted (x#xs) = (psorted xs & (\\<forall> y \\<in> set xs. less x y))\"\n  apply (rule iffI)\n  apply (erule psorted.cases,simp)\n   apply clarsimp\n  apply (rule psorted.Cons,clarsimp+)\n  done\n\nlemma psorted_distinct_set_unique:\nassumes \"psorted xs\" \"distinct xs\" \"psorted ys\" \"distinct ys\" \"set xs = set ys\"\n        \"R_list xs\"\nshows \"xs = ys\"\nproof -\n  from assms have 1: \"length xs = length ys\" by (auto dest!: distinct_card)\n  from assms show ?thesis\n  proof(induct rule:list_induct2[OF 1])\n    case 1 show ?case by simp\n  next\n    case 2 thus ?case\n    by (simp add: psorted_Cons R_set_def)\n         (metis Diff_insert_absorb antisym insertE insert_iff)\n  qed\nqed\n\n\nlemma pinsort_set: \"set (pinsort a xs) = insert a (set xs)\"\n  apply (induct xs)\n  apply simp\n  apply simp\n  apply blast\n  done\n\nlemma all_comp': \"R x y \\<Longrightarrow> \\<not>less x y \\<Longrightarrow> less y x\"\n  apply (cut_tac x=x and y=y in all_comp,simp+)\n  done\n\nlemma pinsort_sorted: \"R_set (insert a (set xs)) \\<Longrightarrow> psorted xs \\<Longrightarrow> psorted (pinsort a xs)\"\n  apply (induct xs arbitrary: a)\n  apply (simp add: psorted_Cons)\n  apply (simp add: psorted_Cons)\n  apply clarsimp\n  apply (simp add: pinsort_set)\n  apply (intro impI conjI)\n    apply (intro ballI)\n    apply (drule_tac x=x in bspec)\n     apply simp\n    apply (frule(1) trans)\n    apply simp\n   apply (simp add: R_set_def)\n  apply (rule all_comp')\n   apply (simp add: R_set_def)\n  apply simp\n  done\n \nlemma psort_set: \"set (psort xs) = set xs\"\n  apply (simp add: psort_def)\n  apply (induct xs)\n   apply simp\n  apply (simp add: pinsort_set)\n  done\n\nlemma psort_psorted: \"R_list xs \\<Longrightarrow> psorted (psort xs)\"\n  apply (simp add: psort_def)\n  apply (induct xs)\n   apply simp\n  apply simp\n  apply (cut_tac xs =xs in psort_set)\n  apply (simp add: psort_def)\n  apply (rule pinsort_sorted)\n   apply simp\n  apply (simp add: R_set_def)\n  done\n\n\nlemma insort_length: \"length (pinsort a xs) = Suc (length xs)\"\n  apply (induct xs)\n  apply simp\n  apply simp\n  done\n\nlemma psort_length: \"length (psort xs) = length xs\"\n  apply (simp add: psort_def)\n  apply (induct xs)\n   apply simp\n  apply simp\n  apply (simp add: insort_length)\n  done\n\nlemma pinsort_distinct: \"\\<lbrakk>a \\<notin> set xs; distinct xs\\<rbrakk>\n       \\<Longrightarrow> distinct (pinsort a xs)\"\n  apply (induct xs)\n  apply simp\n  apply (clarsimp simp add: pinsort_set)\n  done\n\nlemma psort_distinct: \"distinct xs \\<Longrightarrow> distinct (psort xs)\"\n  apply (simp add: psort_def)\n  apply (induct xs)\n   apply simp\n  apply simp\n  apply (rule pinsort_distinct)\n   apply (fold psort_def)\n   apply (simp add: psort_set)+\n  done\n\n\nlemma in_can_split: \"y \\<in> set list \\<Longrightarrow> \\<exists>ys xs. list = xs @ (y # ys)\"\n  apply (induct list)\n   apply simp\n  apply clarsimp\n  apply (elim disjE)\n   apply simp\n   apply force\n  apply simp\n  apply (elim exE)\n  apply simp\n  apply (rule_tac x=ys in exI)\n  apply force\n  done\n\nlemma lsorted_sorted:\nassumes lsorted: \"\\<And>x y xs ys . list = xs @ (x # y # ys) \\<Longrightarrow> less x y\"\nshows \"psorted list\"\n  apply (insert lsorted)\n  apply atomize\n  apply simp\n  apply (induct list)\n   apply simp\n  apply (simp add: psorted_Cons)\n  apply (rule context_conjI)\n   apply (erule meta_mp)\n   apply clarsimp\n   apply (drule_tac x=\"a#xs\" in spec)\n   apply (drule_tac x=x in spec)\n   apply (drule_tac x=y in spec)\n   apply (erule mp)\n   apply force\n  apply (intro ballI)\n  apply clarsimp\n  apply (drule in_can_split)\n  apply (elim exE)\n  apply (drule_tac x=\"[]\" in spec)\n  apply simp\n  apply (case_tac xs)\n   apply simp\n  apply (clarsimp simp add: psorted_Cons)\n  apply (blast intro: trans)\n  done\n\n\nlemma psorted_set: \"finite A \\<Longrightarrow> R_set A \\<Longrightarrow> \\<exists>!xs. set xs = A \\<and> psorted xs \\<and> distinct xs\"\n  apply (drule finite_distinct_list)\n  apply clarify\n  apply (rule_tac a=\"psort xs\" in ex1I)\n   apply (auto simp: psorted_distinct_set_unique psort_set psort_psorted psort_distinct)\ndone\n\nend\n\n\ntext {* These list operations roughly correspond to cdt\n        operations. *}\n\nlemma after_can_split: \"after_in_list list x = Some y \\<Longrightarrow> \\<exists>ys xs. list = xs @ (x # y # ys)\"\n  apply (induct list x rule: after_in_list.induct)\n  apply simp+\n  apply (simp split: if_split_asm)\n   apply force\n  apply (elim exE)\n  apply simp\n  apply (rule_tac x=\"ys\" in exI)\n  apply simp\n  done\n\nlemma distinct_inj_middle: \"distinct list \\<Longrightarrow> list = (xa @ x # xb) \\<Longrightarrow> list = (ya @ x # yb) \\<Longrightarrow> xa = ya \\<and> xb = yb\"\n  apply (induct list arbitrary: xa ya)\n  apply simp\n  apply clarsimp\n  apply (case_tac \"xa\")\n   apply simp\n   apply (case_tac \"ya\")\n    apply simp\n   apply clarsimp\n  apply clarsimp\n  apply (case_tac \"ya\")\n   apply (simp (no_asm_simp))\n   apply simp\n  apply clarsimp\n  done\n \n\nlemma after_can_split_distinct:\n  \"distinct list \\<Longrightarrow> after_in_list list x = Some y \\<Longrightarrow> \\<exists>!ys. \\<exists>!xs. list = xs @ (x # y # ys)\"\n  apply (frule after_can_split)\n  apply (elim exE)\n  apply (rule ex1I)\n   apply (rule ex1I)\n    apply assumption\n   apply simp\n  apply (elim ex1E)\n  apply (thin_tac \"\\<forall>x. P x\" for P)\n  apply (frule_tac yb=\"y#ysa\" in distinct_inj_middle,assumption+)\n  apply simp\n  done\n\n\nlemma after_ignore_head: \"x \\<notin> set list \\<Longrightarrow> after_in_list (list @ list') x = after_in_list list' x\"\n  apply (induct list x rule: after_in_list.induct)\n  apply simp\n   apply simp\n   apply (case_tac list',simp+)\n  done\n \n\nlemma after_distinct_one_sibling: \"distinct list \\<Longrightarrow> list = xs @ x # y # ys \\<Longrightarrow> after_in_list list x = Some y\"\n  apply (induct xs)\n  apply simp\n  apply simp\n  apply clarsimp\n  apply (subgoal_tac \"after_in_list ((a # xs) @ (x # y # ys)) x = after_in_list (x # y # ys) x\")\n   apply simp\n  apply (rule after_ignore_head)\n  apply simp\n  done\n\n\nlemma (in partial_sort) after_order_sorted:\nassumes after_order: \"\\<And>x y. after_in_list list x = Some y \\<Longrightarrow> less x y\"\nassumes distinct: \"distinct list\"\nshows \"psorted list\"\n  apply (rule lsorted_sorted)\n  apply (rule after_order)\n  apply (erule after_distinct_one_sibling[OF distinct])\n  done\n\nlemma hd_not_after_in_list:\n  \"\\<lbrakk>distinct xs; x \\<notin> set xs\\<rbrakk> \\<Longrightarrow> after_in_list (x # xs) a \\<noteq> Some x\"\n  apply (induct xs a rule: after_in_list.induct)\n    apply simp+\n  apply fastforce\n  done\n\nlemma after_in_list_inj:\n  \"\\<lbrakk>distinct list; after_in_list list a = Some x; after_in_list list b = Some x\\<rbrakk>\n    \\<Longrightarrow> a = b\"\n  apply(induct list)\n   apply(simp)\n  apply(simp)\n  apply(case_tac \"a=aa\")\n   apply(case_tac list, simp)\n   apply(simp add: hd_not_after_in_list split: if_split_asm)\n  apply(case_tac list, simp)\n  apply(simp add: hd_not_after_in_list split: if_split_asm)\n  done\n\nlemma list_replace_ignore:\"a \\<notin> set list \\<Longrightarrow> list_replace list a b = list\"\n  apply (simp add: list_replace_def)\n  apply (induct list,clarsimp+)\n  done\n\nlemma list_replace_empty[simp]: \"list_replace [] a b = []\"\n  by (simp add: list_replace_def)\n\nlemma list_replace_empty2[simp]:\n  \"(list_replace list a b = []) = (list = [])\"\n  by (simp add: list_replace_def)\n\nlemma after_in_list_list_replace: \"\\<lbrakk>p \\<noteq> dest; p \\<noteq> src;\n         after_in_list list p = Some src\\<rbrakk>\n        \\<Longrightarrow> after_in_list (list_replace list src dest) p = Some dest\"\n  apply (simp add: list_replace_def)\n  apply (induct list)\n   apply simp+\n  apply (case_tac list)\n   apply simp+\n  apply (intro conjI impI,simp+)\n  done\n\nlemma replace_list_preserve_after: \"dest \\<notin> set list \\<Longrightarrow> distinct list \\<Longrightarrow>  after_in_list (list_replace list src dest) dest = after_in_list list src\"\n  apply (simp add: list_replace_def)\n  apply (induct list src rule: after_in_list.induct)\n    apply (simp+)\n  apply fastforce\n  done\n\nlemma replace_list_preserve_after': \"\\<lbrakk>p \\<noteq> dest; p \\<noteq> src;\n         after_in_list list p \\<noteq> Some src\\<rbrakk>\n        \\<Longrightarrow> after_in_list (list_replace list src dest) p = after_in_list list p\"\n  apply (simp add: list_replace_def)\n  apply (induct list p rule: after_in_list.induct)\n    apply (simp+)\n  apply fastforce\n  done\n\nlemma distinct_after_in_list_not_self:\n  \"distinct list \\<Longrightarrow> after_in_list list src \\<noteq> Some src\"\n  apply (induct list,simp+)\n  apply (case_tac list,clarsimp+)\n  done\n\nlemma set_list_insert_after:\n  \"set (list_insert_after list a b) = set list \\<union> (if a \\<in> set list then {b} else {})\"\n  apply(induct list)\n   apply(simp)\n  apply(simp)\n  done\n\nlemma distinct_list_insert_after:\n  \"\\<lbrakk>distinct list; b \\<notin> set list \\<or> a \\<notin> set list\\<rbrakk> \\<Longrightarrow> distinct (list_insert_after list a b)\"\n  apply(induct list)\n   apply(simp)\n  apply(fastforce simp: set_list_insert_after)\n  done\n\nlemma list_insert_after_after:\n  \"\\<lbrakk>distinct list; b \\<notin> set list; a \\<in> set list\\<rbrakk>\n    \\<Longrightarrow> after_in_list (list_insert_after list a b) p\n    = (if p = a then Some b else if p = b then after_in_list list a else after_in_list list p)\"\n  apply(induct list p rule: after_in_list.induct)\n    apply (simp split: if_split_asm)+\n  apply fastforce\n  done\n\nlemma list_remove_removed:\n  \"set (list_remove list x) = (set list) - {x}\"\n  apply (induct list,simp+)\n  apply blast\n  done\n\n\nlemma remove_distinct_helper: \"\\<lbrakk>distinct (list_remove list x); a \\<noteq> x; a \\<notin> set list;\n        distinct list\\<rbrakk>\n       \\<Longrightarrow> a \\<notin> set (list_remove list x)\"\n  apply (induct list)\n   apply (simp split: if_split_asm)+\n  done\n\n\nlemma list_remove_distinct:\n  \"distinct list \\<Longrightarrow>  distinct (list_remove list x)\"\n  apply (induct list)\n  apply (simp add: remove_distinct_helper split: if_split_asm)+\n  done\n\nlemma list_remove_none: \"x \\<notin> set list \\<Longrightarrow> list_remove list x = list\"\n  apply (induct list)\n  apply clarsimp+\n  done\n\nlemma replace_distinct: \"x \\<notin> set list \\<Longrightarrow> distinct list \\<Longrightarrow> distinct (list_replace list y x)\"\n  apply (induct list)\n  apply (simp add: list_replace_def)+\n  apply blast\n  done\n\nlemma set_list_replace_list:\n  \"\\<lbrakk>distinct list; slot \\<in> set list; slot \\<notin> set list'\\<rbrakk>\n    \\<Longrightarrow> set (list_replace_list list slot list') = set list \\<union> set list' - {slot}\"\n  apply (induct list)\n  apply auto\n  done\n\nlemma after_in_list_in_list:\n  \"after_in_list list a = Some b \\<Longrightarrow> b \\<in> set list\"\n  apply(induct list a arbitrary: b rule: after_in_list.induct)\n  apply (simp split: if_split_asm)+\n  done\n\nlemma list_replace_empty_after_empty:\n  \"\\<lbrakk>after_in_list list p = Some slot; distinct list\\<rbrakk>\n    \\<Longrightarrow> after_in_list (list_replace_list list slot []) p = after_in_list list slot\"\n  apply(induct list slot rule: after_in_list.induct)\n  apply (simp split: if_split_asm)+\n   apply (case_tac xs,simp+)\n  apply (case_tac xs,simp+)\n  apply (auto dest!: after_in_list_in_list)\n  done\n  \nlemma list_replace_after_fst_list:\n  \"\\<lbrakk>after_in_list list p = Some slot; distinct list\\<rbrakk>\n    \\<Longrightarrow> after_in_list (list_replace_list list slot (x # xs)) p = Some x\"\n  apply(induct list p rule: after_in_list.induct)\n  apply (simp split: if_split_asm)+\n  apply (drule after_in_list_in_list)+\n  apply force\n  done\n\nlemma after_in_list_append_notin_hd:\n  \"p \\<notin> set list' \\<Longrightarrow> after_in_list (list' @ list) p = after_in_list list p\"\n  apply(induct list', simp, simp)\n  apply(case_tac list', simp)\n   apply(case_tac list, simp+)\n   done\n\nlemma after_in_list_append_last_hd:\n  \"\\<lbrakk>p \\<in> set list'; after_in_list list' p = None\\<rbrakk>\n    \\<Longrightarrow> after_in_list (list' @ x # xs) p = Some x\"\n  apply(induct list' p rule: after_in_list.induct)\n    apply(simp)\n   apply(simp)\n  apply(simp split: if_split_asm)\n  done\n\nlemma after_in_list_append_in_hd:\n  \"after_in_list list p = Some a \\<Longrightarrow> after_in_list (list @ list') p = Some a\"\n  apply(induct list p rule: after_in_list.induct)\n    apply(simp split: if_split_asm)+\n    done\n\nlemma after_in_list_in_list': \"after_in_list list a = Some y \\<Longrightarrow> a \\<in> set list\"\n  apply (induct list a rule: after_in_list.induct)\n  apply simp+\n  apply force\n  done\n\nlemma list_replace_after_None_notin_new:\n  \"\\<lbrakk>after_in_list list p = None; p \\<notin> set list'\\<rbrakk>\n    \\<Longrightarrow> after_in_list (list_replace_list list slot list') p = None\"\n  apply(induct list)\n   apply(simp)\n  apply(simp)\n  apply(intro conjI impI)\n   apply(simp)\n   apply(case_tac list, simp)\n    apply(induct list')\n     apply(simp)\n    apply(simp)\n    apply(case_tac list', simp, simp)\n   apply(simp split: if_split_asm)\n    apply(simp add: after_in_list_append_notin_hd)\n   apply(simp add: after_in_list_append_notin_hd)\n  apply(case_tac \"list_replace_list list slot list'\")\n   apply(simp)\n  apply(simp)\n  apply(case_tac list, simp, simp split: if_split_asm)\n  done\n \nlemma list_replace_after_notin_new:\n  \"\\<lbrakk>after_in_list list p = Some a; a \\<noteq> slot; p \\<notin> set list'; p \\<noteq> slot\\<rbrakk>\n    \\<Longrightarrow> after_in_list (list_replace_list list slot list') p = Some a\"\n  apply(induct list)\n   apply(simp)\n  apply(simp)\n  apply(intro conjI impI)\n   apply(simp add: after_in_list_append_notin_hd)\n   apply(case_tac list, simp, simp)\n  apply(case_tac list, simp, simp split: if_split_asm)\n  apply(insert after_in_list_append_notin_hd)\n  apply(atomize)\n  apply(erule_tac x=p in allE, erule_tac x=\"[aa]\" in allE, erule_tac x=\"list' @ lista\" in allE)\n  apply(simp)\n  done\n\nlemma list_replace_after_None_notin_old:\n  \"\\<lbrakk>after_in_list list' p = None; p \\<in> set list'; p \\<notin> set list\\<rbrakk>\n    \\<Longrightarrow> after_in_list (list_replace_list list slot list') p = after_in_list list slot\"\n  apply(induct list)\n   apply(simp)\n  apply(simp)\n  apply(intro conjI impI)\n   apply(simp)\n   apply(case_tac list)\n    apply(simp)\n   apply(simp add: after_in_list_append_last_hd)\n  apply(case_tac \"list_replace_list list slot list'\")\n   apply(simp)\n   apply(case_tac list, simp, simp)\n  apply(simp)\n  apply(case_tac list, simp, simp)\n  done\n\nlemma list_replace_after_notin_old:\n  \"\\<lbrakk>after_in_list list' p = Some a; p \\<notin> set list; slot \\<in> set list\\<rbrakk>\n    \\<Longrightarrow> after_in_list (list_replace_list list slot list') p = Some a\"\n  apply(induct list)\n   apply(simp)\n  apply(simp)\n  apply(intro conjI impI)\n   apply(simp add: after_in_list_append_in_hd)\n  apply(simp)\n  apply(case_tac \"list_replace_list list slot list'\")\n   apply(simp)\n  apply(simp)\n  done\n\n  \nlemma list_replace_set: \"x \\<in> set list \\<Longrightarrow> set (list_replace list x y) = insert y (set (list) - {x})\"\n  apply (induct list)\n  apply (simp add: list_replace_def)+\n  apply (intro impI conjI)\n  apply blast+\n  done\n\nlemma list_swap_both: \"x \\<in> set list \\<Longrightarrow> y \\<in> set list \\<Longrightarrow> set (list_swap list x y) = set (list)\"\n  apply (induct list)\n  apply (simp add: list_swap_def)+\n  apply (intro impI conjI)\n  apply blast+\n  done\n\nlemma list_swap_self[simp]: \"list_swap list x x = list\"\n  apply (simp add: list_swap_def)\n  done\n \nlemma map_ignore: \"x \\<notin> set list \\<Longrightarrow> (map (\\<lambda>xa. if xa = x then y else xa)\n             list) = list\"\n  apply (induct list)\n  apply simp+\n  apply blast\n  done\n\nlemma map_ignore2: \"y \\<notin> set list \\<Longrightarrow> (map (\\<lambda>xa. if xa = x then y else if xa = y then x else xa)\n             list) = (map (\\<lambda>xa. if xa = x then y else xa) list)\"\n  apply (simp add: map_ignore)\n  done\n\nlemma map_ignore2': \"y \\<notin> set list \\<Longrightarrow> (map (\\<lambda>xa. if xa = y then x else if xa = x then y else xa)\n             list) = (map (\\<lambda>xa. if xa = x then y else xa) list)\"\n  apply (simp add: map_ignore)\n  apply force\n  done\n\nlemma swap_distinct_helper: \"\\<lbrakk>x \\<in> set list; y \\<noteq> x; y \\<notin> set list; distinct list\\<rbrakk>\n       \\<Longrightarrow> distinct (map (\\<lambda>xa. if xa = x then y else xa) list)\"\n  apply (induct list)\n  apply (simp add: map_ignore | elim conjE | intro impI conjI | blast)+\n  done\n\nlemma swap_distinct: \"x \\<in> set list \\<Longrightarrow> y \\<in> set list \\<Longrightarrow> distinct list \\<Longrightarrow> distinct (list_swap list x y)\"\n  apply (induct list)\n  apply (simp add: list_swap_def)+\n  apply (intro impI conjI,simp_all)\n  apply (simp add: map_ignore2 map_ignore2' swap_distinct_helper | elim conjE | force)+\n  done\n\n\nlemma list_swap_none: \"x \\<notin> set list \\<Longrightarrow> y \\<notin> set list \\<Longrightarrow> list_swap list x y = list\"\n  apply (induct list)\n  apply (simp add: list_swap_def)+\n  apply blast\n  done\n  \nlemma list_swap_one: \"x \\<in> set list \\<Longrightarrow> y \\<notin> set list \\<Longrightarrow> set (list_swap list x y) = insert y (set (list)) - {x}\"\n  apply (induct list)\n  apply (simp add: list_swap_def)+\n  apply (intro impI conjI)\n  apply blast+\n  done\n\nlemma list_swap_one': \"x \\<notin> set list \\<Longrightarrow> y \\<in> set list \\<Longrightarrow> set (list_swap list x y) = insert x (set (list)) - {y}\"\n  apply (induct list)\n  apply (simp add: list_swap_def)+\n  apply (intro impI conjI)\n  apply blast+\n  done\n\n\nlemma in_swapped_list: \"y \\<in> set list \\<Longrightarrow> x \\<in> set (list_swap list x y)\"\n  apply (case_tac \"x \\<in> set list\")\n   apply (simp add: list_swap_both)\n  apply (simp add: list_swap_one')\n  apply (intro notI,simp)\n  done\n\nlemma list_swap_empty : \"(list_swap list x y = []) = (list = [])\"\n  by(simp add: list_swap_def)\n\nlemma distinct_after_in_list_antisym:\n  \"distinct list \\<Longrightarrow> after_in_list list a = Some b \\<Longrightarrow> after_in_list list b \\<noteq> Some a\"\n  apply (induct list b arbitrary: a rule: after_in_list.induct)\n    apply simp+\n  apply (case_tac xs)\n   apply (clarsimp split: if_split_asm | intro impI conjI)+\n  done\n\n\nlemma after_in_listD: \"after_in_list list x = Some y \\<Longrightarrow> \\<exists>xs ys. list = xs @ (x # y # ys) \\<and> x \\<notin> set xs\" \n  apply (induct list x arbitrary: a rule: after_in_list.induct)\n    apply (simp split: if_split_asm | elim exE | force)+\n  apply (rule_tac x=\"x # xsa\" in exI)\n  apply simp\n  done\n\nlemma list_swap_symmetric: \"list_swap list a b = list_swap list b a\"\n  apply (simp add: list_swap_def)\n  done\n\nlemma list_swap_preserve_after:\n  \"\\<lbrakk>desta \\<notin> set list; distinct list\\<rbrakk>\n\\<Longrightarrow> after_in_list (list_swap list srca desta) desta =\n   after_in_list list srca\"\n  apply (induct list desta rule: after_in_list.induct)\n  apply (simp add: list_swap_def)+\n  apply force\n  done\n\nlemma list_swap_preserve_after': \n \"\\<lbrakk>p \\<noteq> desta; p \\<noteq> srca; after_in_list list p = Some srca\\<rbrakk>\n\\<Longrightarrow> after_in_list (list_swap list srca desta) p = Some desta\"\n  apply (induct list p rule: after_in_list.induct)\n  apply (simp add: list_swap_def)+\n  apply force\n  done\n\nlemma list_swap_does_swap:\n       \"\\<lbrakk>distinct list; after_in_list list desta = Some srca\\<rbrakk>\n       \\<Longrightarrow> after_in_list (list_swap list srca desta) srca = Some desta\"\n  apply (induct list srca rule: after_in_list.induct)\n    apply (simp add: list_swap_def)+\n  apply (elim conjE)\n  apply (intro impI conjI,simp_all)\n   apply (frule after_in_list_in_list,simp)+\n  done\n\nlemma list_swap_does_swap':\n  \"distinct list \\<Longrightarrow> after_in_list list srca = Some desta \\<Longrightarrow>\n                after_in_list (list_swap list srca desta) srca =\n          after_in_list list desta\"\n  apply (induct list srca rule: after_in_list.induct)\n    apply (simp add: list_swap_def)+\n  apply (elim conjE)\n  apply (intro impI conjI,simp_all)\n   apply (case_tac xs)\n    apply (clarsimp+)[2]\n  apply (case_tac xs)\n   apply clarsimp+\ndone\n  \nlemmas list_swap_preserve_after'' = list_swap_preserve_after'[simplified list_swap_symmetric]\n\nlemma list_swap_preserve_Some_other: \n \"\\<lbrakk>z \\<noteq> desta; z \\<noteq> srca; after_in_list list srca = Some z\\<rbrakk>\n\\<Longrightarrow> after_in_list (list_swap list srca desta) desta = Some z\"\n  apply (induct list srca rule: after_in_list.induct)\n  apply (simp add: list_swap_def)+\n  apply force\n  done\n\n\nlemmas list_swap_preserve_Some_other' = list_swap_preserve_Some_other[simplified list_swap_symmetric]\n\nlemma list_swap_preserve_None:\n \"\\<lbrakk>after_in_list list srca = None\\<rbrakk>\n\\<Longrightarrow> after_in_list (list_swap list desta srca) desta = None\"\n  apply (induct list srca rule: after_in_list.induct)\n  apply (simp add: list_swap_def)+\n  apply force\n  done\n\nlemma list_swap_preserve_None':\n \"\\<lbrakk>after_in_list list srca = None\\<rbrakk>\n\\<Longrightarrow> after_in_list (list_swap list srca desta) desta = None\"\n  apply (subst list_swap_symmetric)\n  apply (erule list_swap_preserve_None)\n  done\n\nlemma list_swap_preserve_after_None: \n \"\\<lbrakk>p \\<noteq> desta; p \\<noteq> srca; after_in_list list p = None\\<rbrakk>\n\\<Longrightarrow> after_in_list (list_swap list srca desta) p = None\"\n  apply (induct list p rule: after_in_list.induct)\n  apply (simp add: list_swap_def)+\n  apply force\n  done\n\nlemma list_swap_preserve_Some_other_distinct: \n \"\\<lbrakk>distinct list; z \\<noteq> desta; after_in_list list srca = Some z\\<rbrakk>\n\\<Longrightarrow> after_in_list (list_swap list srca desta) desta = Some z\"\n  apply (rule list_swap_preserve_Some_other)\n  apply simp+\n   apply (rule notI)\n   apply simp\n   apply (frule distinct_after_in_list_not_self[where src=srca])\n   apply simp+\n  done\n\nlemma list_swap_preserve_separate: \n \"\\<lbrakk>p \\<noteq> desta; p \\<noteq> srca; z \\<noteq> desta; z \\<noteq> srca; after_in_list list p = Some z\\<rbrakk>\n\\<Longrightarrow> after_in_list (list_swap list srca desta) p = Some z\"\n  apply (induct list p rule: after_in_list.induct)\n  apply (simp add: list_swap_def split: if_split_asm)+\n  apply (intro impI conjI)\n   apply simp+\n  done\n\nfun after_in_list_list where\n  \"after_in_list_list [] a = []\" |\n  \"after_in_list_list (x # xs) a = (if a = x then xs else after_in_list_list xs a)\"\n\nlemma after_in_list_list_in_list:\n  notes split_paired_All[simp del] split_paired_Ex[simp del]\n  shows \"y \\<in> set (after_in_list_list list x) \\<Longrightarrow> y \\<in> set list\"\n  apply(induct list arbitrary:x y)\n  apply(simp)\n  apply(case_tac \"x=a\", simp+)\ndone\n\nlemma range_nat_relation_induct: \n\"\\<lbrakk> m = Suc (n + k) ; m < cap ; \\<forall>n. Suc n < cap \\<longrightarrow> P n (Suc n );  \n   \\<forall>i j k. i < cap \\<and> j < cap \\<and> k < cap \\<longrightarrow> P i j \\<longrightarrow> P j k \\<longrightarrow> P i k \\<rbrakk> \\<Longrightarrow>  P n m\"\n  apply (clarify)\n  apply (thin_tac \"m = t\" for t)\n  apply (induct k)\n   apply (drule_tac x = \"n\" in spec)\n   apply (erule impE, simp, simp)\n  apply (frule_tac x = \"Suc (n + k)\" in spec)\n  apply (erule impE)   \n   apply (simp only: add_Suc_right)\n  apply (rotate_tac 3, frule_tac x = n in spec)\n  apply (rotate_tac -1, drule_tac x = \"Suc (n + k)\" in spec)\n  apply (rotate_tac -1, drule_tac x = \"Suc (n + Suc k) \" in spec)\n  apply (erule impE)\n   apply (intro conjI)\n     apply (rule_tac y = \"Suc (n + Suc k)\" in less_trans)\n      apply (rule less_SucI)\n      apply (simp only: add_Suc_right)+\ndone\n\nlemma indexed_trancl_as_set_helper : \"\\<lbrakk>p < q; q < length list; list ! p = a; list ! q = b;\n        q = Suc (p + k); Suc n < length list\\<rbrakk>\n       \\<Longrightarrow> (a, b) \\<in> {(i, j). \\<exists>p. Suc p <length list \\<and> list ! p = i \\<and> list ! Suc p = j}\\<^sup>+\"\n  apply (induct k arbitrary: p q a b)\n   apply (rule r_into_trancl,simp, rule_tac x = p in exI, simp)\n  apply (atomize)\n  apply (erule_tac x = p in allE, erule_tac x = \"Suc (p + k)\" in allE, erule_tac x = \"a\" in allE, erule_tac x = \"list ! Suc (p + k)\" in allE)\n  apply (elim impE)\n        apply (simp)+\n  apply (rule_tac b = \"list ! Suc (p + k)\" in trancl_into_trancl)\n   apply (simp)+\n  apply (rule_tac x = \"Suc (p + k)\" in exI, simp)\n  done\n\nlemma indexed_trancl_as_set: \"distinct list \\<Longrightarrow> {(i, j). \\<exists> p q. p < q \\<and> q < length list \\<and> list ! p = i \\<and> list ! q = j } \n      = {(i, j). \\<exists> p. Suc p < length list \\<and> list ! p = i \\<and> list ! Suc p = j }\\<^sup>+\"\n  apply (rule equalityI)  \n    apply (rule subsetI)\n    apply (case_tac x, simp)\n    apply (elim exE conjE)\n    apply (frule less_imp_Suc_add)\n    apply (erule exE)\n    apply (rule_tac cap = \"length list\" and m = q and n = p and k = k in range_nat_relation_induct)\n      apply (simp)\n      apply (simp)\n      apply (rule allI, rule impI)\n      apply (rule_tac p = p and q = q and k = k and n = n in indexed_trancl_as_set_helper)\n        apply (simp)+\n  apply (rule subsetI)\n    apply (case_tac x, simp)\n    apply (erule trancl_induct)\n      apply (simp, elim exE conjE)\n      apply (rule_tac x = p in exI, rule_tac x = \"Suc p\" in exI, simp)\n      apply (simp)\n      apply (rotate_tac 4, erule exE, rule_tac x = p in exI)\n      apply (erule exE, rule_tac x = \"Suc pa\" in exI) \n      apply (intro conjI)\n        defer\n        apply (simp)\n        apply (erule exE, simp)\n        apply (simp) \n        apply (erule exE)\n        apply (subgoal_tac \"pa = q\")\n          apply (simp)\n          apply (frule_tac xs = list and i = pa and j = q in nth_eq_iff_index_eq)\n            apply (simp)+\ndone \n    \nlemma indexed_trancl_irrefl: \"distinct list \\<Longrightarrow> (x,x) \\<notin> {(i, j). \\<exists> p. Suc p < length list \\<and> list ! p = i \\<and> list ! Suc p = j }\\<^sup>+\"\n apply (frule indexed_trancl_as_set [THEN sym])\n apply (simp)\n apply (intro allI impI notI)\n apply (frule_tac xs = list and i = p and j = q in nth_eq_iff_index_eq)\n apply (simp+)\ndone\n\nlemma after_in_list_trancl_indexed_trancl: \"distinct list \\<Longrightarrow> {(p, q). after_in_list list p = Some q}\\<^sup>+ = {(i, j). \\<exists> p. Suc p < length list \\<and> list ! p = i \\<and> list ! Suc p = j }\\<^sup>+\"\n  apply (rule_tac f = \"\\<lambda> x. x\\<^sup>+\" in  arg_cong) \n  apply (intro equalityI subsetI)\n\n  apply (case_tac x, simp)\n  apply (induct list)    \n   apply (simp)\n   apply (case_tac \"a = aa\")\n     apply (rule_tac x = 0 in exI, case_tac list, simp, simp)\n     apply (case_tac list, simp, simp)\n     apply (atomize, drule_tac x = x in spec, drule_tac x = aa in spec, drule_tac x = b in spec, simp)\n     apply (erule exE, rule_tac x = \"Suc p\" in exI, simp)\n  \n  apply (case_tac x, simp)\n  apply (induct list)\n    apply (simp)\n    apply (case_tac \"a = aa\")\n      apply (erule exE)\n      apply (subgoal_tac \"p = 0\")\n        apply (case_tac list, simp, simp)\n        apply (subgoal_tac \"distinct (aa # list)\")\n          apply (frule_tac i = 0 and j = p and xs = \"aa # list\" in nth_eq_iff_index_eq)   \n          apply (simp, simp, simp, simp)\n    apply (atomize, drule_tac x = x in spec, drule_tac x = aa in spec, drule_tac x = b in spec, simp)\n    apply (drule mp)\n      apply (erule exE)\n      apply (case_tac p, simp, simp)\n      apply (rule_tac x = nat in exI, simp)\n   apply (case_tac list, simp, simp)\ndone\n   \nlemma distinct_after_in_list_not_self_trancl:\n  notes split_paired_All[simp del] split_paired_Ex[simp del]\n  shows \"distinct list \\<Longrightarrow> (x, x) \\<notin> {(p, q). after_in_list list p = Some q}\\<^sup>+\"\n  by (simp add: after_in_list_trancl_indexed_trancl indexed_trancl_irrefl)\n \nlemma distinct_after_in_list_in_list_trancl:\n  notes split_paired_All[simp del] split_paired_Ex[simp del]\n  shows \"\\<lbrakk>distinct list; (x, y) \\<in> {(p, q). after_in_list list q = Some p}\\<^sup>+\\<rbrakk> \\<Longrightarrow> x \\<in> set list\"\n  by(erule tranclE2, (drule CollectD, simp, drule after_in_list_in_list, simp)+)\n\n\nlemma after_in_list_trancl_prepend:\n  notes split_paired_All[simp del] split_paired_Ex[simp del]\n  shows \"\\<lbrakk>distinct (y # list); x \\<in> set list\\<rbrakk> \\<Longrightarrow> (y, x) \\<in> {(n, p). after_in_list (y # list) n = Some p}\\<^sup>+\"\n  apply(induct list arbitrary:x y)\n    apply(simp)\n    apply(case_tac \"x=a\")\n      apply(rule r_into_trancl)\n      apply(simp)\n      apply(drule set_ConsD)\n      apply(elim disjE)\n        apply(simp)\n        apply(atomize)\n        apply(drule_tac x=x in spec)\n        apply(drule_tac x=y in spec)\n        apply(drule_tac mp)\n          apply(simp)\n        apply(drule_tac mp)\n          apply(simp)\n        apply(erule trancl_induct)\n          apply(drule CollectD, simp)\n          apply(rule_tac b = a in trancl_into_trancl2)\n            apply(simp)\n          apply(rule r_into_trancl)\n          apply(rule_tac a = \"(a,ya)\" in CollectI)\n          apply(clarsimp)\n          apply(case_tac list)\n            apply(simp)\n            apply(simp)\n          apply(case_tac \"ya=a\")\n            apply(drule CollectD)\n            apply(simp del:after_in_list.simps)\n            apply(drule after_in_list_in_list')\n            apply(simp)\n            apply(rule_tac b=ya in trancl_into_trancl)\n              apply(simp)              \n              apply(drule CollectD)\n              apply(rule CollectI)\n              apply(case_tac \"ya=y\")\n                apply(frule_tac x=y in distinct_after_in_list_not_self_trancl)\n                apply(simp)\n                apply(case_tac list)\n                  apply(simp)\n                  apply(simp)\ndone\n\nlemma after_in_list_append_not_hd:\n  notes split_paired_All[simp del] split_paired_Ex[simp del]\n  shows \"a \\<noteq> x \\<Longrightarrow> after_in_list (a # list) x = after_in_list list x\"\nby (case_tac list, simp, simp)\n\nlemma trancl_Collect_rev:\n  \"(a, b) \\<in> {(x, y). P x y}\\<^sup>+ \\<Longrightarrow> (b, a) \\<in> {(x, y). P y x}\\<^sup>+\"\n  apply(induct rule: trancl_induct)\n   apply(fastforce intro: trancl_into_trancl2)+\n   done\n\n\nlemma prepend_after_in_list_distinct : \"distinct (a # list) \\<Longrightarrow> {(next, p). after_in_list (a # list) p = Some next}\\<^sup>+ =\n       {(next, p). after_in_list (list) p = Some next}\\<^sup>+ \\<union>\n       set list \\<times> {a} \"\n  apply (rule equalityI)\n   (* \\<subseteq> direction *)\n   apply (rule subsetI, case_tac x)\n   apply (simp)\n   apply (erule trancl_induct)\n     (* base case *)\n    apply (drule CollectD, simp)\n    apply (case_tac list, simp)\n    apply (simp split:if_split_asm)\n    apply (rule r_into_trancl)\n    apply (rule CollectI, simp)\n    (* Inductive case *)\n   apply (drule CollectD, simp)\n   apply (erule disjE)\n    apply (case_tac \"a \\<noteq> z\")\n     apply (rule disjI1)\n     apply (rule_tac b =y in trancl_into_trancl)\n      apply (simp, case_tac list, simp, simp)\n              \n    apply (simp)\n    apply (rule disjI2)\n    apply (erule conjE)\n    apply (frule_tac x = aa and y = y in distinct_after_in_list_in_list_trancl)\n     apply (simp)\n    apply (simp)\n   apply (subgoal_tac \"after_in_list (a # list) z \\<noteq> Some a\", simp)\n   apply (rule_tac hd_not_after_in_list, simp, simp)\n(* \\<supseteq> direction *)\n  apply (rule subsetI)\n  apply (case_tac x)\n  apply (simp)\n  apply (erule disjE)\n    (* transitive case *)\n   apply (erule tranclE2)\n    apply (drule CollectD, simp)\n    apply (subgoal_tac \"b \\<noteq> a\")\n     apply (rule r_into_trancl)\n     apply (rule CollectI, simp)\n     apply (case_tac list, simp, simp)\n    apply (frule after_in_list_in_list')\n    apply (erule conjE)\n    apply (blast)\n   apply (rule_tac y = c in trancl_trans)\n    apply (subgoal_tac \"c \\<noteq> a\")\n     apply (case_tac list, simp, simp)\n     apply (case_tac \"aaa = aa\")\n      apply (rule r_into_trancl)\n      apply (rule CollectI, simp)\n   \n     apply (rule r_into_trancl)\n     apply (rule CollectI, simp)\n    apply (erule CollectE, simp)\n    apply (frule after_in_list_in_list')\n    apply (erule conjE, blast)\n   apply (erule trancl_induct)\n    apply (simp)\n    apply (rule r_into_trancl, simp)\n    apply (subgoal_tac \"y \\<noteq> a\")\n     apply (case_tac list, simp, simp)\n    apply (rotate_tac 3)\n    apply (frule after_in_list_in_list')\n    apply (erule conjE, blast)\n   apply (rule_tac b = y in trancl_into_trancl, simp)\n   apply (rule CollectI, simp)\n   apply (subgoal_tac \"a \\<noteq> z\")\n    apply (case_tac list, simp, simp)\n   apply (rotate_tac 3)\n   apply (frule after_in_list_in_list')\n   apply (blast)   \n(* not so transitive case *)   \n  apply (subgoal_tac \"distinct (a # list)\")\n   apply (frule_tac x = aa in after_in_list_trancl_prepend, simp, simp)\n   apply (rule trancl_Collect_rev, simp)\n  apply (simp)\ndone\n\nlemma after_in_list_in_cons:\n  notes split_paired_All[simp del] split_paired_Ex[simp del]\n  shows \"\\<lbrakk>after_in_list (x # xs) y = Some z; distinct (x # xs); y \\<in> set xs\\<rbrakk> \\<Longrightarrow> z \\<in> set xs\"\n  apply(case_tac \"y=x\")\n  apply(simp)\n  apply(simp add:after_in_list_append_not_hd after_in_list_in_list)\ndone\n\nlemma after_in_list_list_set:\n  notes split_paired_All[simp del] split_paired_Ex[simp del]\n  shows \"distinct list \\<Longrightarrow> \n         set (after_in_list_list list x)\n         = {a. (a, x) \\<in> {(next, p). after_in_list list p = Some next}\\<^sup>+}\"\n  apply(intro equalityI)\n  (* \\<subseteq> *)\n   apply(induct list arbitrary:x)\n    apply(simp)\n   apply(atomize)\n   apply(simp)\n   apply(rule conjI, rule impI, rule subsetI)\n    apply(rule_tac a = xa in CollectI)\n    apply(rule trancl_Collect_rev)\n    apply(rule after_in_list_trancl_prepend)\n     apply(simp)\n    apply(simp)\n   apply(clarify)\n   apply(drule_tac x=x in spec)\n   apply(drule_tac B=\"{a. (a, x) \\<in> {(next, p). after_in_list list p = Some next}\\<^sup>+}\" in set_rev_mp)\n    apply(simp)\n   apply(drule CollectD)\n   apply(simp add:prepend_after_in_list_distinct)\n (* \\<supseteq> *)\n  apply(clarsimp)\n  apply(drule trancl_Collect_rev)\n  apply(erule trancl_induct)\n    (* base *)\n   apply(simp)\n   apply(induct list arbitrary:x)\n    apply(simp)\n   apply(case_tac \"a=x\")\n    apply(frule_tac src=x in distinct_after_in_list_not_self)\n    apply(simp)\n    apply(drule after_in_list_in_list)\n    apply(simp)+\n   apply(drule_tac list=list in after_in_list_append_not_hd)\n   apply(simp)\n   (* inductive *)\n  apply(simp)\n  apply(drule trancl_Collect_rev)\n  apply(induct list arbitrary: x)\n   apply(simp)\n  apply(case_tac \"a\\<noteq>x\")\n  (* a\\<noteq>x *)\n   apply(atomize, drule_tac x=y in spec, drule_tac x=z in spec, drule_tac x=x in spec)\n   apply(simp add:prepend_after_in_list_distinct)\n   apply(case_tac \"a=y\")\n    apply(simp add:after_in_list_list_in_list)\n   apply(simp add:after_in_list_append_not_hd)\n   (* a=x *)\n  apply(frule after_in_list_in_cons, simp+)\ndone\n\nlemma list_eq_after_in_list':\n  \"\\<lbrakk> distinct xs; p = xs ! i; i < length xs \\<rbrakk>\n    \\<Longrightarrow> \\<exists>list. xs = list @ p # after_in_list_list xs p\"   \n   apply (induct xs arbitrary: i)\n     apply (simp)  \n  apply (atomize)\n  apply (case_tac i)\n   apply (simp)\n  apply (drule_tac x = nat in spec, simp)\n  apply (erule exE, rule impI, rule_tac x = \"a # list\" in exI)\n  apply (simp)\ndone\n   \nlemma after_in_list_last_None:\n  \"distinct list \\<Longrightarrow> after_in_list list (last list) = None\"\n  apply(induct list)\n   apply(simp)\n  apply(case_tac list)\n   apply(simp)\n  apply(fastforce split: if_split_asm)\n  done\n\nlemma after_in_list_None_last:\n  \"\\<lbrakk>after_in_list list x = None; x \\<in> set list\\<rbrakk> \\<Longrightarrow> x = last list\"\n  by (induct list x rule: after_in_list.induct,(simp split: if_split_asm)+)\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/l4v/lib/ListLibLemmas.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637612961505, "lm_q2_score": 0.8418256412990657, "lm_q1q2_score": 0.7236869971546989}}
{"text": "theory Kongruencije\n  imports Main HOL.Real\nbegin\n\n\n(* Neka je m prirodni broj veci od 1. Kazemo da su brojevi a, b \\<in> Z kongruentni po modulu m\ni pisemo a \\<equiv> b (mod m) ili a \\<equiv>m b ako  m | (a \u2212 b) . *)\ndefinition kongruentni_po_modulu :: \"int \\<Rightarrow> int \\<Rightarrow> nat \\<Rightarrow> bool\"  where\n\"kongruentni_po_modulu a b m = ((m > 1) \\<and> (m dvd (a - b)))\"\n\n\n(* Tvrdjenje 1:  Ako je a \\<equiv> a1 (mod m) i b \\<equiv> b1 (mod m) onda je:\n    a + b \\<equiv> a1 + b1 (mod m)\n    a * b \\<equiv> a1 * b1 (mod m)\n *)\nlemma tvrdjenje_1_1:\n  assumes \"m > 1\"\n  assumes \"kongruentni_po_modulu a a1 m\"\n  assumes \"kongruentni_po_modulu b b1 m\"\n  shows \"kongruentni_po_modulu (a + b) (a1 + b1) m\" \n  unfolding kongruentni_po_modulu_def\nproof-\n  have *: \"m dvd (a - a1)\"\n    using assms(1) assms(2)\n    using kongruentni_po_modulu_def \n    by simp\n  have **: \"m dvd (b - b1)\"\n    using assms(1) assms(3)\n    using kongruentni_po_modulu_def \n    by simp\n  have \"m dvd ((a - a1) + (b - b1))\"\n    using * **\n    by simp\n  hence \"m dvd (a + b) - (a1 + b1)\"\n    by (simp add: algebra_simps)\n  thus \"(m > 1) \\<and> (m dvd (a + b) - (a1 + b1))\"\n      using assms(1)\n      by simp\n  qed\n\nlemma tvrdjenje_1_2:\n  assumes \"m > 1\"\n  assumes \"kongruentni_po_modulu a a1 m\"\n  assumes \"kongruentni_po_modulu b b1 m\"\n  shows \"kongruentni_po_modulu (a * b) (a1 * b1) m\" \n  unfolding kongruentni_po_modulu_def\nproof-\n  have \"m dvd (a - a1)\"\n    using assms(1) assms(2)\n    using kongruentni_po_modulu_def \n    by simp\n  hence *:\"m dvd (a - a1)*b\"\n    by simp\n  have \"m dvd (b - b1)\"\n    using assms(1) assms(3)\n    using kongruentni_po_modulu_def \n    by simp\n  hence **:\"m dvd a1*(b - b1)\"\n    by simp\n  have \"m dvd ((a - a1)*b + a1*(b - b1))\"\n    using * **\n    by simp\n  hence \"m dvd (a*b - a1*b1)\"\n    by (simp add: algebra_simps)\n  thus \"(m > 1) \\<and> (m dvd (a*b - a1*b1))\"\n    using assms(1)\n    by simp\nqed\n\n\n(* Tvrdjenje 2:  Ako je a \\<equiv> a1 (mod m) i k je prirodan broj, onda je a^k \\<equiv> a1^k (mod m) *)\nlemma tvrdjenje_2:\n  fixes k :: nat\n  assumes \"m > 1\"\n  assumes \"kongruentni_po_modulu a a1 m\"\n  shows \"kongruentni_po_modulu (a^k) (a1^k) m\"\n (* unfolding kongruentni_po_modulu_def *)\nproof (induction k)\n  case 0\n  then show ?case\n    unfolding kongruentni_po_modulu_def\n    using assms\n    by simp\n next\n  case (Suc k)\n  then show ?case\n  proof-\n    thm assms\n    thm Suc\n    have \"kongruentni_po_modulu (a^k * a) (a1^k * a1) m\"\n      using assms Suc\n      by (simp add: tvrdjenje_1_2)\n    hence \"kongruentni_po_modulu ((a^(k+1))) ((a1^(k+1))) m\"\n      by (simp add: algebra_simps)\n    thus ?case\n      using assms\n      by simp\n    qed\n  qed\n\n(* Tvrdjenje 3:  \\<equiv>m je relacija ekvivalencije *)\n(* Relacija je relacija ekvivalencije ako je refleksivna, simetricna i tranzitivna.*)\n\nlemma refleksivna: \n  assumes \"m > 1\"\n  shows \"kongruentni_po_modulu a a m\"\nunfolding kongruentni_po_modulu_def\nproof-\n  have \"m dvd (a - a)\"\n    by simp\n  thus \"(m > 1) \\<and> (m dvd (a - a))\"\n    using assms\n    by simp\nqed\n\n\nlemma simetricna:\n  assumes \"m > 1\"\n  assumes \"kongruentni_po_modulu x y m\"\n  shows \"kongruentni_po_modulu y x m\"\nunfolding kongruentni_po_modulu_def\nproof-\n  have \"m dvd (x - y)\"\n    using assms\n    unfolding kongruentni_po_modulu_def\n    by simp\n  hence \"m dvd (y - x)\"\n    by (simp add: dvd_diff_commute)\n  thm \"dvd_diff_commute\"\n  thus \"(m > 1) \\<and> m dvd (y - x)\"\n    using assms\n    by simp\nqed\n\n\nlemma tranzitivna:\n  assumes \"m > 1\"\n  assumes \"kongruentni_po_modulu x y m\"\n  assumes \"kongruentni_po_modulu y z m\"\n  shows \"kongruentni_po_modulu x z m\"\nunfolding kongruentni_po_modulu_def\nproof-\n  have *: \"m dvd (x - y)\"\n    using assms\n    unfolding kongruentni_po_modulu_def\n    by simp\n  have **: \"m dvd (y - z)\"\n    using assms\n    unfolding kongruentni_po_modulu_def\n    by simp\n  have \"m dvd (x - y + y - z)\"\n    using * **\n    by (smt zdvd_zdiffD)\n    thm \"zdvd_zdiffD\"\n    hence \"m dvd (x - z)\"\n      by simp\n    thus \"(m > 1) \\<and> (m dvd (x - z))\"\n      using assms\n      by simp\nqed\n\n\n(* Za naredna tvrdjenja potreban je i nzd. *)\n\nfun nzd :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\" where\n   \"nzd a b = (if b = 0 then a else nzd b (a mod b))\"\n\nvalue \"nzd 120 28\"\n\n(* Tvrdjenje 4: Ako je a*b \\<equiv> a*c (mod m)  i  nzd(a,m) = 1 \n   onda je b \\<equiv> c (mod m) *)\n\nlemma pomocna_2:\n  assumes \"nzd a b = d\"\n  shows \"a*x + b*y = d\"\n  sorry   (* dokazuje se pomocu Euklidovog algoritma *)\n\nlemma pomocna_1:\n  assumes \"a dvd (b*c)\"\n  assumes \"nzd a b = 1\"\n  shows \"a dvd c\"\nproof-\n  have \"a*x + b*y = 1\"\n    using pomocna_2 `nzd a b = 1`\n    by simp\n  hence *:\" a*c*x + b*c*y = c\"\n    by (metis add.right_neutral crossproduct_noteq linordered_field_class.sign_simps(6) mult.comm_neutral mult_zero_left nzd.simps(1) pomocna_2 rel_simps(76) semiring_normalization_rules(7))\n  have \"a dvd a*c*x\"\n    by simp\n  hence \"a dvd (a*c*x + b*c*y)\"\n    using assms(1)\n    by simp\n  thus \"a dvd c\"\n    using *\n    by simp\nqed\n\n\nlemma tvrdjenje_4:\n  assumes \"m > 1\"\n  assumes \"kongruentni_po_modulu (a*b) (a*c) m\"\n  assumes \"nzd a m = 1\"\n  shows \"kongruentni_po_modulu b c m\"\nunfolding kongruentni_po_modulu_def\nproof-\n  have \"m dvd (a*b - a*c)\"\n    using assms\n    unfolding kongruentni_po_modulu_def\n    by simp\n  hence \"m dvd (a*(b - c))\"\n    by (simp add: algebra_simps)\n  hence \"m dvd (b - c)\"\n    using pomocna_1 `nzd a m = 1`\n    by simp\n  thus \"(m > 1) \\<and> (m dvd (b - c))\"\n    using assms\n    by simp\nqed\n\n(* \n  Tvrdjenje 5: Neka za prirodne brojeve m i n vece od 1 i ceo broj a vazi:\n  m|a i n|a. Ako su brojevi m i n uzajamno prosti, onda m*n|a. \n*)\n\nlemma tvrdjenje_5:\n  fixes m :: nat\n  fixes n :: nat \n  fixes a :: int\n  assumes \"m > 1\"\n  assumes \"n > 1\"\n  assumes \"m dvd a\"\n  assumes \"n dvd a\"\n  assumes \"nzd m n = 1\"\n  shows \"m*n dvd a\"\nproof-\n  have *:\" a = m * a1\"\n    using assms(3)\n    by (metis (mono_tags, lifting) One_nat_def add_diff_cancel_left' diff_is_0_eq dvd_div_mult_self dvd_minus_self dvd_refl less_numeral_extra(4) less_one linorder_not_le mult.right_neutral nat_diff_split nonzero_mult_div_cancel_left nzd.simps(1) of_nat_0 of_nat_1 pomocna_2 semiring_1_class.of_nat_simps(2) zero_less_diff)\n  hence \"n dvd m*a1\"\n    using assms(4) of_nat_dvd_iff \n    by blast\n  hence \"n dvd a1\"\n    using pomocna_1 assms(5)\n    by simp\n  hence **: \"a1 = n * a2\"\n    by (metis (mono_tags, lifting) One_nat_def add_diff_cancel_left' diff_is_0_eq dvd_div_mult_self dvd_minus_self dvd_refl less_numeral_extra(4) less_one linorder_not_le mult.right_neutral nat_diff_split nonzero_mult_div_cancel_left nzd.simps(1) of_nat_0 of_nat_1 pomocna_2 semiring_1_class.of_nat_simps(2) zero_less_diff)\n  hence \"a = m*n*a2\"\n    using * **\n    by simp\n  thus \"m*n dvd a\"\n    by simp\nqed\n\nlemma tvrdjenje_6:\n  assumes \"m > 1\"\n  assumes \"n > 1\"\n  assumes \"nzd m n = 1\"\n  assumes \"kongruentni_po_modulu a a1 m\"\n  assumes \"kongruentni_po_modulu a a1 n\"\n  shows \"kongruentni_po_modulu a a1 (m*n)\"\nproof-\n  have *: \"m dvd (a - a1)\"\n    using assms(4)\n    unfolding kongruentni_po_modulu_def\n    by simp\n  have **: \"n dvd (a - a1)\"\n    using assms(5)\n    unfolding kongruentni_po_modulu_def\n    by simp\n  have \"(m*n) dvd (a - a1)\"\n    using * ** tvrdjenje_5 assms\n    by simp\n  thus \"kongruentni_po_modulu a a1 (m*n)\" \n    using assms\n    unfolding kongruentni_po_modulu_def\n    using less_1_mult by blast\nqed\n\n(* a \\<equiv>m b and c \\<equiv>m d \\<Longrightarrow> a\u2212c \\<equiv>m b\u2212d *)\nlemma tvrdjenje_7:\n  assumes \"m > 1\"\n  assumes \"kongruentni_po_modulu a b m\"\n  assumes \"kongruentni_po_modulu c d m\"\n  shows \"kongruentni_po_modulu (a - c) (b - d) m\"\nproof-\n  have *: \"m dvd (a - b)\"\n    using assms(2) kongruentni_po_modulu_def\n    by auto\n  have **: \"m dvd (c - d)\"\n    using assms(3) kongruentni_po_modulu_def\n    by auto\n  have \"m dvd ((a - b) - (c - d))\"\n    using * **\n    by auto\n  hence \"m dvd ((a - c) - (b - d))\"\n    by (simp add: algebra_simps)\n  hence \"(m > 1) \\<and> (m dvd (a - c) - (b - d))\"\n      using assms(1)\n      by simp\n  thus ?thesis\n    unfolding kongruentni_po_modulu_def\n    by simp\nqed\n\n(* a \\<equiv>m 0 iff m|a;  *)\nlemma tvrdjenje_8:\n  assumes \"m > 1\"\n  shows \"kongruentni_po_modulu a 0 m \\<longleftrightarrow> m dvd a\"\nproof\n  show \"kongruentni_po_modulu a 0 m \\<Longrightarrow> int m dvd a\"\n  proof-\n    assume \"kongruentni_po_modulu a 0 m\"\n    hence \"m dvd (a - 0)\"\n      unfolding kongruentni_po_modulu_def\n      by simp\n    thus \"m dvd a\"\n      by simp\n  qed\nnext\n  show \"m dvd a \\<Longrightarrow> kongruentni_po_modulu a 0 m\"\n  proof-\n    assume \"m dvd a\"\n    hence \"m dvd (a - 0)\"\n      by simp\n    thus \"kongruentni_po_modulu a 0 m\"\n      unfolding kongruentni_po_modulu_def\n      using assms\n      by simp\n  qed\nqed\n\n(* If a \\<equiv> b mod m, and c > 1, then ca \\<equiv> cb mod cm *)\nlemma tvrdjenje_9:\n  assumes \"c > 1\"\n  assumes \"m > 1\"\n  assumes \"kongruentni_po_modulu a b m\"\n  shows \"kongruentni_po_modulu (c*a) (c*b) (c*m)\"\nproof-\n  have *: \"c*m > 1\"\n    using assms(1) assms(2) less_1_mult \n    by blast\n  have \"m dvd (a - b)\"\n    using assms kongruentni_po_modulu_def\n    by auto\n  hence \"c*m dvd c*(a - b)\"\n    by simp\n  hence \"c*m dvd (c*a - c*b)\"\n    by (simp add: algebra_simps)\n  thus ?thesis\n    unfolding kongruentni_po_modulu_def\n    using assms *\n    by simp\nqed\n\n\n(* Provera da li postoji resenje jednacine a*x \\<equiv> b (mod m) *)\ndefinition postoji_resenje :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> bool\" where\n\"postoji_resenje a b m  = ((nzd a m) dvd b)\"\n\nvalue \"postoji_resenje 4 9 14\"\nvalue \"postoji_resenje 7 1 9\"\nvalue \"postoji_resenje 8 12 28\"\n\ndefinition postoji_resenje2 :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> bool\" where\n\"postoji_resenje2 a b m  = (\\<exists>x. m dvd (a*x - b))\"\n\ndefinition postoji_resenje3 :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> bool\" where\n\"postoji_resenje3 a b m  = (\\<exists>x y. a*x - b = m*(-y))\"\n\n(* Provera da li je x resenje jednacine a*x \\<equiv> b (mod m) *)\ndefinition jeste_resenje :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> bool\" where\n\"jeste_resenje x a b m = (m dvd (a*x - b))\"\n\ndefinition jeste_resenje2 :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> bool\" where\n\"jeste_resenje2 x a b m = (\\<exists>y. a*x - b = m*(-y))\"\n\nlemma jeste_resenje_sledi_postoji_resenje:\n\"jeste_resenje x a b m \\<longrightarrow> postoji_resenje2 a b m\"\n  using jeste_resenje_def postoji_resenje2_def\n  by blast\n\n(* Neka je d=nzd(a,m) > 1. \n   x je resenje jednacine a*x \\<equiv> b (mod m) akko je resenje jednacine a*x \\<equiv> b (mod m),\n   gde su a'=a/d, b'=b/d i m'=m/d. *)\nlemma\n  assumes \"d = nzd a m\"\n  assumes \"d > 1\"\n  assumes \"a' = a/d\" \"b' = b/d\" \"m' = m/d\"\n  shows \"jeste_resenje2 x a b m \\<longleftrightarrow> jeste_resenje2 x a' b' m'\"\nproof\n  show \"jeste_resenje2 x a b m \\<Longrightarrow> jeste_resenje2 x a' b' m'\"\n  proof-\n    assume \"jeste_resenje2 x a b m\"\n    have \"\\<exists>y. a*x - b = m*(-y)\"\n      using assms\n      unfolding jeste_resenje2_def\n      using \\<open>jeste_resenje2 x a b m\\<close> jeste_resenje2_def by blast\n    hence \"\\<exists>y. a*x + m*y = b\"\n      by (metis crossproduct_eq pomocna_2)\n    hence \"\\<exists>y. (a/d)*x + (m/d)*y = b/d\"\n      by (metis (mono_tags, hide_lams) assms(4) crossproduct_eq of_nat_add of_nat_mult pomocna_2)\n    hence \"\\<exists>y. a'*x + m'*y = b'\"\n      using assms\n      by (metis add.commute add_diff_cancel_left' add_diff_cancel_right add_diff_cancel_right' add_mult_distrib add_mult_distrib2 crossproduct_eq diff_commute left_add_mult_distrib less_diff_conv mult.commute not_add_less1 pomocna_2 right_diff_distrib' semiring_normalization_rules(2) semiring_normalization_rules(3))\n    thus \"jeste_resenje2 x a b m \\<Longrightarrow> jeste_resenje2 x a' b' m'\"\n      unfolding jeste_resenje2_def\n      by auto\n  qed\nnext\n  show \"jeste_resenje2 x a' b' m' \\<Longrightarrow> jeste_resenje2 x a b m\"\n  proof-\n    assume \"jeste_resenje2 x a' b' m'\"\n    have \"\\<exists>y. a'*x - b' = m'*(-y)\"\n      using assms\n      unfolding jeste_resenje2_def\n      using \\<open>jeste_resenje2 x a' b' m'\\<close> jeste_resenje2_def by blast\n    hence \"\\<exists>y. a'*x + m'*y = b'\"\n      by (metis crossproduct_eq pomocna_2)\n    hence \"\\<exists>y. a'*d*x + m'*d*y = b'*d\"\n      by (metis (mono_tags, hide_lams) assms(4) crossproduct_eq of_nat_add of_nat_mult pomocna_2)\n    hence \"\\<exists>y. a*x + m*y = b\"\n      using assms\n       by (metis add.commute add_diff_cancel_left' add_diff_cancel_right add_diff_cancel_right' add_mult_distrib add_mult_distrib2 crossproduct_eq diff_commute left_add_mult_distrib less_diff_conv mult.commute not_add_less1 pomocna_2 right_diff_distrib' semiring_normalization_rules(2) semiring_normalization_rules(3))\n    thus \"jeste_resenje2 x a' b' m' \\<Longrightarrow> jeste_resenje2 x a b m\"\n      unfolding jeste_resenje2_def\n      by auto\n  qed\nqed\n\n\ndefinition nzs_dva_broja :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\" where\n\"nzs_dva_broja a b = a*b div (nzd a b)\"\n\nprimrec nzs_liste_brojeva :: \"nat list \\<Rightarrow> nat\" where\n  \"nzs_liste_brojeva [] = 1\"\n| \"nzs_liste_brojeva (x # xs) = nzs_dva_broja x (nzs_liste_brojeva xs)\"\n\nvalue \"nzs_dva_broja 6 8\"\nvalue \"nzs_liste_brojeva [3, 4, 12]\"\n\ndefinition postoji_resenje_sistema :: \"nat list \\<Rightarrow> nat list \\<Rightarrow> bool\" where\n  \"postoji_resenje_sistema as ms = (\\<forall> i j . i\\<in>set([0..<(length as)]) \\<and> j\\<in>set([0..(length ms)]) \\<and> (i = j) \\<and> (postoji_resenje 1 (as ! i) (ms ! j)))\"\n\ndefinition jeste_resenje_sistema :: \"nat \\<Rightarrow> nat list \\<Rightarrow> nat list \\<Rightarrow> bool\" where\n\"jeste_resenje_sistema x as ms = (\\<forall> i j . i\\<in>set([0..<(length as)]) \\<and> j\\<in>set([0..(length ms)]) \\<and> (i = j) \\<and> (jeste_resenje x 1 (as ! i) (ms ! j)))\"\n\nlemma jeste_resenje_sledi_postoji_resenje_sistema:\n\"jeste_resenje_sistema x as ms \\<longrightarrow> postoji_resenje_sistema as ms\"\n  using jeste_resenje_sistema_def \n  by blast\n\nprimrec lista_nzd :: \"nat list \\<Rightarrow> nat \\<Rightarrow> nat list\" where\n  \"lista_nzd [] y = []\"\n| \"lista_nzd (x # xs) y = (nzd x y) # (lista_nzd xs y)\"\n\nfun lista_istih_elemenata' :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat list \\<Rightarrow> nat list\" where\n  \"lista_istih_elemenata' x 0 xs = xs\"\n| \"lista_istih_elemenata' x len xs = [x] @ (lista_istih_elemenata' x (len-1) xs)\"\n\nfun lista_istih_elemenata :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat list\" where\n\"lista_istih_elemenata x len = lista_istih_elemenata' x len []\"\n\nvalue \"lista_istih_elemenata 2 10\"\n\nlemma pomocna1_za_kinesku_teoremu: \n  \"nzd (nzs_liste_brojeva xs) y = nzs_liste_brojeva (lista_nzd xs y)\"\n  sorry\n\nlemma pomocna2_za_kinesku_teoremu: \n  \"(nzs_liste_brojeva (lista_nzd xs y)) dvd z = (\\<forall>x\\<in>set(xs) . (nzd x y) dvd z)\"\n  sorry\n\nlemma pomocna3_za_kinesku_teoremu:\n  fixes x y z :: \"nat\"\n  shows \"x - y = (x - z) + (z - y)\"\n  sorry\n\nlemma pomocna4_za_kinesku_teoremu:\n\"(postoji_resenje_sistema as ms \\<and> postoji_resenje x a m) \\<longrightarrow> postoji_resenje_sistema (a # as) (m # ms)\"\n  using postoji_resenje_sistema_def by blast\n\nlemma pomocna5_za_kinesku_teoremu: \"a dvd c \\<longrightarrow> nzd a b dvd c\"\n  by (metis diff_is_0_eq' le_add_diff_inverse2 pomocna3_za_kinesku_teoremu rel_simps(47) zero_le_one zero_neq_one)\n\nlemma pomocna6_za_kinesku_teoremu: \"a dvd b \\<and> a dvd c \\<longrightarrow> a  dvd (b+c)\"\n  using le_add_diff_inverse2 pomocna3_za_kinesku_teoremu by presburger\n\nlemma kineska_teorema_o_ostacima:\n  fixes x::nat\n  fixes as ms :: \"nat list\"\n  assumes \"length as = length ms\"\n  shows \"((\\<forall>i j . (k = length as) \\<and> (k = length ms) \\<and> i\\<in>set([0..<k]) \\<and> j\\<in>set([0..<k]) \\<and> i\\<noteq>j \\<and> ((nzd (ms ! i) (ms ! j)) dvd ((as ! i) - (as ! j))) \\<and> jeste_resenje_sistema x as ms ) \\<longrightarrow> \n        ((postoji_resenje_sistema as ms) \\<and> (\\<exists>t . jeste_resenje_sistema (x + (nzs_liste_brojeva ms)*t) as ms)))\"\nproof(induction k)\ncase 0\n  then show ?case\n    using assms jeste_resenje_sistema_def\n    by blast\nnext\n  case (Suc k)\n  then show ?case\n  proof-\n\n    have prvi_deo: \"(\\<forall>i j. Suc k = length as \\<and> Suc k = length ms \\<and>\n          i \\<in> set [0..<Suc k] \\<and> j \\<in> set [0..<Suc k] \\<and> i \\<noteq> j \\<and> \n          nzd (ms ! i) (ms ! j) dvd as ! i - as ! j) \\<and> (jeste_resenje_sistema x (take k as) (take k ms))\n           \\<Longrightarrow> postoji_resenje_sistema as ms\"\n    proof-\n      assume leva_strana_implikacije: \"(\\<forall>i j. Suc k = length as \\<and> Suc k = length ms \\<and>\n          i \\<in> set [0..<Suc k] \\<and> j \\<in> set [0..<Suc k] \\<and> i \\<noteq> j \\<and> \n          nzd (ms ! i) (ms ! j) dvd (as ! i - as ! j)) \\<and> jeste_resenje_sistema x (take k as) (take k ms)\"\n\n      have 1: \"jeste_resenje_sistema x (take k as) (take k ms)\"\n        using leva_strana_implikacije\n        by blast\n\n      (* Na osnovu induktivne hipoteze znamo da postoji resenje sistema od k jednacina: *)\n      have postoji_res_sistema_duzine_k: \"postoji_resenje_sistema (take k as) (take k ms)\"\n        using 1 jeste_resenje_sledi_postoji_resenje_sistema Suc\n        by blast\n\n      (* Dokaz da postoji resenje jednacine x \\<equiv> a_k+1 (mod m_k+1) *)\n      have postoji_res_poslednje_jednacine: \"postoji_resenje ((nzs_liste_brojeva (take k ms))) ((as ! Suc k)-x) (ms ! Suc k)\"\n      proof-\n        (* nzd(m_i, m_k+1) | (a_k+1 - a_i): *)\n        have deli_aSuc_minus_ai: \"\\<forall>i . i\\<in>set[0..<k] \\<and> ((nzd (ms ! i) (ms ! Suc k)) dvd ((as ! Suc k) - (as ! i)))\"\n          by (metis add.right_neutral diff_add_zero linordered_semidom_class.add_diff_inverse not_one_less_zero pomocna3_za_kinesku_teoremu zero_neq_one)\n\n        (* Dokaz da nzd(m_i, m_k+1) | (a_i - x): *)\n        have *:\"jeste_resenje_sistema x (take k as) (take k ms)\"\n          using \"1\" jeste_resenje_sistema_def\n          by blast\n        have **:\"jeste_resenje_sistema x (take k as) (take k ms) \\<longrightarrow> ( \\<forall>i . i\\<in>set[0..<k] \\<and> ((ms ! i) dvd ((as ! i) - x)))\"\n          using jeste_resenje_sistema_def\n          by blast\n        have \"\\<forall>i . i\\<in>set[0..<k] \\<and> ((ms ! i) dvd ((as ! i) - x))\"\n          using * **\n          by blast\n        hence deli_ai_minus_x: \"\\<forall>i . i\\<in>set[0..<k] \\<and> ((nzd (ms ! i) (ms ! Suc k))dvd ((as ! i) - x))\"\n          using pomocna5_za_kinesku_teoremu \n          by blast\n\n        (* a_k+1 - x moze da se napise kao (a_k+1 - a_i) + (a_i - x) *)\n        have #: \"\\<forall>i\\<in>set[0..<k].  (as ! Suc k) - x = ((as ! Suc k) - (as ! i)) + ((as ! i) - x)\"\n          using pomocna3_za_kinesku_teoremu\n          by blast\n\n        (* posto nzd deli svaki od sabiraka, onda deli i ceo zbir: *)\n        have ##: \"\\<forall>i\\<in>set[0..<k] . ((nzd (ms ! i) (ms ! Suc k)) dvd (((as ! Suc k) - (as ! i)) + ((as ! i) - x)))\"\n          using pomocna6_za_kinesku_teoremu deli_ai_minus_x deli_aSuc_minus_ai\n          by blast\n        (* odnosno, deli i a_k+1 - x *)\n        have \"\\<forall>i\\<in>set[0..<k] . ((nzd (ms ! i) (ms ! Suc k)) dvd ((as ! Suc k) - x))\"\n          using # ## \"*\" jeste_resenje_sistema_def \n          by blast\n\n        (* \\<forall>i nzd(m_i, m_k+1) | (a_k+1 - x) \\<Longrightarrow> nzs(nzd(m_1, m_k+1), ..., nzd(m_k, m_k+1)) | (a_k+1 - x) *)\n        hence \"nzs_liste_brojeva (lista_nzd (take k ms) (ms ! Suc k)) dvd ((as ! Suc k) - x)\"\n          using pomocna2_za_kinesku_teoremu  \"*\" jeste_resenje_sistema_def\n          by blast\n        (* \\<Longrightarrow> nzd(nzs(m1,...,mk), m_k+1) | (a_k+1 - x) *)\n        hence \"(nzd (nzs_liste_brojeva (take k ms)) (ms ! Suc k)) dvd ((as ! Suc k) - x)\"\n          using 1 pomocna1_za_kinesku_teoremu\n          by simp\n        (* \\<Longrightarrow> postoji resenje jednacine nzs(m1,...,mk)*y \\<equiv> (a_k+1 - x) mod m_k+1 *)\n        thus \"postoji_resenje ((nzs_liste_brojeva (take k ms))) (as ! Suc k - x) (ms ! Suc k)\"\n          unfolding postoji_resenje_def\n          using \"*\" jeste_resenje_sistema_def by blast\n\n      qed\n\n      (* Posto postoji resenje sistema od k jednacina i postoji resenje te poslednje jednacine,\n         onda postoji i resenje celog sistema od k+1 jednacina. *)\n      have *:\"postoji_resenje_sistema as ms\"\n        using postoji_res_sistema_duzine_k postoji_res_poslednje_jednacine pomocna4_za_kinesku_teoremu\n        using \"1\" jeste_resenje_sistema_def \n        by blast\n      thus ?thesis\n        using *\n        by blast\n    qed\n\n    have drugi_deo: \"(jeste_resenje_sistema x as ms \\<Longrightarrow> (\\<exists>t. jeste_resenje_sistema (x + nzs_liste_brojeva ms * t) as ms))\"\n    proof-\n      fix x1::nat\n      (* x je resenje sistema - iz leve strane implikacije: \\<forall>i x \\<equiv> ai (mod mi) *)\n      assume \"jeste_resenje_sistema x as ms\"  \n      (* x1 je proizvoljno resenje sistema: \\<forall>i x1 \\<equiv> ai (mod mi)  *)\n      assume \"jeste_resenje_sistema x1 as ms\" \n      (* Iz te dve pretpostavke onda vazi: \\<forall>i x1 \\<equiv> x (mod mi) *)\n      have *: \"jeste_resenje_sistema x1 (lista_istih_elemenata x (length ms)) ms\"\n        using `jeste_resenje_sistema x1 as ms` `jeste_resenje_sistema x as ms` \n        using Zero_not_Suc add_diff_cancel_right' diff_add_zero plus_1_eq_Suc pomocna3_za_kinesku_teoremu\n        by presburger\n      (* Odatle sledi da \\<forall>i  mi | x1-x *)\n      hence \"\\<forall>i\\<in>set[0..<length ms] . (ms!i) dvd (x1 - x)\"\n        using jeste_resenje_sistema_def\n        by blast\n      (* Odnosno da nzs(m1,...,mk) | x1-x *)\n      hence \"(nzs_liste_brojeva ms) dvd (x1 - x)\"\n        by (metis diff_add_inverse  gcd_nat.order_iff_strict minus_nat.diff_0 pomocna3_za_kinesku_teoremu zero_diff)\n     \n     (* Odatle sledi da x1-x moze da se zapise kao nzs(m1,...,mk)*t za neko t *)\n      hence 1: \"\\<exists>t . (x1 - x) = (nzs_liste_brojeva ms)*t\"\n        by blast\n      (* Znamo da \\<forall>i\\<in>{1,..,k} vazi nzs(m1,...,mk) \\<equiv> 0 (mod mi) tj. da je nzs koji sadrzi mi deljiv sa mi *)\n      have 2: \"jeste_resenje_sistema (nzs_liste_brojeva ms) (lista_istih_elemenata 0 (length ms)) ms\"\n        using * jeste_resenje_sistema_def \n        by blast\n\n      (* iz 1 i 2 sledi da je svaki broj oblika x + nzs(m1,...,mk)*t resenje sistema *)\n      have \"\\<exists>t. jeste_resenje_sistema (x + nzs_liste_brojeva ms * t) as ms\"\n        using 1 2  Suc.IH `jeste_resenje_sistema x as ms`\n        by (metis mult_0_right semiring_normalization_rules(6))\n      thus ?thesis\n        by blast\n    qed\n\n    thus ?thesis\n      using prvi_deo drugi_deo\n      by blast\n\n  qed\nqed\n\n\ndefinition prost_broj :: \"nat \\<Rightarrow> bool\" where \n\"prost_broj p = (p > 1 \\<and> (\\<forall>m. m dvd p \\<longrightarrow> m = 1 \\<or> m = p))\"\n\ndefinition lista_brojeva_Ojlerove_fje :: \"nat \\<Rightarrow> nat list\" where\n  \"lista_brojeva_Ojlerove_fje n = filter (\\<lambda>m . nzd m n = 1) [1..<n]\"\n\ndefinition Ojlerova_fja :: \"nat \\<Rightarrow> nat\" where\n  \"Ojlerova_fja n = length(filter (\\<lambda>m . nzd m n = 1) [1..<n])\"\n\nvalue \"lista_brojeva_Ojlerove_fje 10\"\nvalue \"Ojlerova_fja 10\"\n\nlemma ojl_lema1:\n  assumes \"k \\<ge> 1\"\n  assumes \"prost_broj p\"\n  shows \"Ojlerova_fja (p^k) = p^k - p^(k-1)\"\nproof (induction k)\ncase 0\n  then show ?case\n  unfolding Ojlerova_fja_def prost_broj_def\n    by simp\nnext\n  case (Suc k)\n  then show ?case\n    by (metis Groups.mult_ac(2)  nzd.simps one_neq_zero pomocna_2 times_nat.simps(1))\nqed\n\n\nlemma ojl_lema2:\n  assumes \"k \\<ge> 1\"\n  assumes \"prost_broj p\"\n  shows \"Ojlerova_fja (p^k) = p^k *(1 - 1/p)\"\nproof-\n  have 1: \"Ojlerova_fja (p^k) =  p^k - p^(k-1)\"\n    using ojl_lema1 assms\n    by simp\n  also have 2: \"... = p^k - (p^k * 1/p)\"\n    by (smt One_nat_def Suc_leI assms(1) diff_divide_distrib diff_is_0_eq' diff_le_self le_numeral_extra(4) mult.right_neutral nat_zero_less_power_iff neq0_conv nonzero_mult_div_cancel_left of_nat_diff of_nat_eq_iff of_nat_mult power_eq_if power_increasing)\n    also have 3: \"... = p^k * 1 - (p^k * 1/p)\"\n      by simp\n    also have 4: \"... = p^k * (1 - 1/p)\"\n      by (simp add: right_diff_distrib')\n    thus ?thesis\n      using 1 2 3 4\n      by simp\nqed\n\nlemma ojl_proizvod_dva:\n  assumes \"m > 1\" \"n > 1\"\n  assumes \"nzd m n = 1\"\n  shows \"Ojlerova_fja (m*n) = (Ojlerova_fja m) * (Ojlerova_fja n)\"\n  unfolding Ojlerova_fja_def\n  by (metis crossproduct_noteq  pomocna_2)\n\nvalue \"Ojlerova_fja (fold ( * ) [3,7] 1)\"\nvalue \"fold (\\<lambda>x acc . acc * Ojlerova_fja x) [3,7] 1\"\nvalue \"Ojlerova_fja 3\"\nvalue \"Ojlerova_fja 7\"\n\nlemma ojl_proizvod_uopstenje:\n  fixes ns::\"nat list\"\n  assumes \"\\<forall>n1 n2 . n1\\<in>set(ns) \\<and> n2\\<in>set(ns) \\<and> n1 \\<noteq> n2 \\<and> nzd n1 n2 = 1\"\n  shows \"Ojlerova_fja (fold ( * ) ns 1) = fold (\\<lambda>n acc . acc * Ojlerova_fja n) ns 1\"\n  using assms by blast \n\nfun proizvod_prostih :: \"nat list \\<Rightarrow> nat list \\<Rightarrow> nat\" where\n\"proizvod_prostih ps as = fold (\\<lambda> par acc . (fst par)^(snd par) * acc ) (zip ps as) 1\"\n\nvalue \"proizvod_prostih [1,2,3] [2,2,2]\"\n\nprimrec proizvod_1_minus_1krozP :: \"nat list \\<Rightarrow> real\" where\n   \"proizvod_1_minus_1krozP [] = 1\"\n|  \"proizvod_1_minus_1krozP (p # ps) = (1 - 1/p) * (proizvod_1_minus_1krozP ps)\"\n\nlemma \n  fixes ps::\"nat list\"\n  fixes as::\"nat list\"\n  assumes \"length ps = k\" \"length as = k\"\n  assumes \"\\<forall>p\\<in>(set ps) . prost_broj p\"\n  assumes \"n = proizvod_prostih ps as\"\n  assumes \"\\<forall>a\\<in>(set as) . a \\<ge> 1\"\n  shows \"Ojlerova_fja n = n * (proizvod_1_minus_1krozP ps)\"\n  (*using assms\n  by (metis One_nat_def diff_is_0_eq' le_numeral_extra(4) mult.right_neutral mult_0_right nat_diff_split of_nat_1 order_less_irrefl pomocna_2 semiring_1_class.of_nat_simps(2) zero_less_diff zero_less_one)\n  *)\nproof-\n  have \"Ojlerova_fja n = Ojlerova_fja (proizvod_prostih ps as)\"\n    using assms(4)\n    by auto\n  (* f(n) = f(p1^a1 * ...* pk^ak) *)\n  also have \"... = Ojlerova_fja (fold (\\<lambda> par acc . (fst par)^(snd par) * acc ) (zip ps as) 1)\"\n    using proizvod_prostih.simps\n    by simp\n       (* = f(p1^a1)* ... * f(pk^ak) *)\n  also have \"... = fold (\\<lambda>par acc . acc * Ojlerova_fja ((fst par)^(snd par))) (zip ps as) 1\"\n    using ojl_proizvod_uopstenje\n    by (metis calculation crossproduct_noteq mult.commute mult.left_neutral  pomocna_2 zero_neq_one)\n       (* = p1^a1 * (1 - 1/p1) * ... * pk^ak * (1 - 1/pk) *)  \n  also have \"... = fold (\\<lambda>par acc . acc * (fst par)^(snd par) * (1 - 1/(fst par))) (zip ps as) 1\"\n    using ojl_lema2\n    by (metis (mono_tags, lifting) crossproduct_noteq one_neq_zero pomocna_2)\n       (* = p1^a1 * ... * pk^ak * (1 - 1/p1) * ... * (1 - 1/pk) *)\n  also have \"... = (fold (\\<lambda>par acc . (fst par)^(snd par) * acc ) (zip ps as) 1) * (fold (\\<lambda>p acc . acc * (1 - 1/p)) ps 1)\"\n    by (metis crossproduct_noteq one_neq_zero pomocna_2)\n  also have \"... = (proizvod_prostih ps as) * (fold (\\<lambda>p acc . acc * (1 - 1/p)) ps 1)\"\n    using proizvod_prostih.simps\n    by auto\n  thus ?thesis\n    by (metis (mono_tags, lifting) crossproduct_noteq one_neq_zero pomocna_2)\nqed\n\ndefinition redukovan_sistem :: \"nat set \\<Rightarrow> nat \\<Rightarrow> bool\" where\n\"redukovan_sistem rs n = (\\<forall>z . \\<exists>!r\\<in>rs . (n > 1) \\<and> (nzd z n = 1) \\<and> (kongruentni_po_modulu z r n))\"\n\nlemma Ojlerova_teorema:\n  fixes a n :: nat\n  assumes \"a > 1\" \"n > 1\"\n  assumes \"nzd a n = 1\"\n  shows \"kongruentni_po_modulu (a^(Ojlerova_fja n)) 1 n\"\n  using assms\n  by (metis (no_types, hide_lams) crossproduct_noteq kongruentni_po_modulu_def of_nat_0_eq_iff of_nat_0_less_iff one_neq_zero pomocna_2)\n\nlemma Mala_Fermaova_teorema:\n  fixes p a :: nat\n  assumes \"a > 1\" \"p > 1\"\n  assumes \"prost_broj p\"\n  assumes \"\\<not>(p dvd a)\"\n  shows \"kongruentni_po_modulu (a^(p-1)) 1 p\"\nproof-\n  have \"Ojlerova_fja p = p^1 - p^(1-1)\"\n    using assms(3) ojl_lema1[of \"1\" \"p\"]\n    by simp\n  hence *: \"Ojlerova_fja p = p - 1\"\n    by simp\n\n  have \"nzd a p = 1\"\n    using assms\n    by (metis One_nat_def crossproduct_noteq nat_mult_1_right nzd.simps plus_1_eq_Suc pomocna_2 zero_neq_one)\n  hence \"kongruentni_po_modulu (a^(Ojlerova_fja p)) 1 p\"\n    using assms Ojlerova_teorema\n    by auto\n  thus ?thesis\n    using *\n    by simp\nqed\n\n\nend", "meta": {"author": "jana-jovicic", "repo": "UIDT-Seminarski", "sha": "3bf5ae3e166c80b58cdaea9c3cb1387219e83665", "save_path": "github-repos/isabelle/jana-jovicic-UIDT-Seminarski", "path": "github-repos/isabelle/jana-jovicic-UIDT-Seminarski/UIDT-Seminarski-3bf5ae3e166c80b58cdaea9c3cb1387219e83665/Kongruencije.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256432832333, "lm_q2_score": 0.8596637451167997, "lm_q1q2_score": 0.7236869852402233}}
{"text": "(*  Title:      HOL/Library/Permutations.thy\n    Author:     Amine Chaieb, University of Cambridge\n*)\n\nsection \\<open>Permutations, both general and specifically on finite sets.\\<close>\n\ntheory Permutations\nimports Binomial Multiset Disjoint_Sets\nbegin\n\nsubsection \\<open>Transpositions\\<close>\n\nlemma swap_id_idempotent [simp]:\n  \"Fun.swap a b id \\<circ> Fun.swap a b id = id\"\n  by (rule ext, auto simp add: Fun.swap_def)\n\nlemma inv_swap_id:\n  \"inv (Fun.swap a b id) = Fun.swap a b id\"\n  by (rule inv_unique_comp) simp_all\n\nlemma swap_id_eq:\n  \"Fun.swap a b id x = (if x = a then b else if x = b then a else x)\"\n  by (simp add: Fun.swap_def)\n\nlemma bij_inv_eq_iff: \"bij p \\<Longrightarrow> x = inv p y \\<longleftrightarrow> p x = y\"\n  using surj_f_inv_f[of p] by (auto simp add: bij_def)\n\nlemma bij_swap_comp:\n  assumes bp: \"bij p\"\n  shows \"Fun.swap a b id \\<circ> p = Fun.swap (inv p a) (inv p b) p\"\n  using surj_f_inv_f[OF bij_is_surj[OF bp]]\n  by (simp add: fun_eq_iff Fun.swap_def bij_inv_eq_iff[OF bp])\n\nlemma bij_swap_ompose_bij: \"bij p \\<Longrightarrow> bij (Fun.swap a b id \\<circ> p)\"\nproof -\n  assume H: \"bij p\"\n  show ?thesis\n    unfolding bij_swap_comp[OF H] bij_swap_iff\n    using H .\nqed\n\n\nsubsection \\<open>Basic consequences of the definition\\<close>\n\ndefinition permutes  (infixr \"permutes\" 41)\n  where \"(p permutes S) \\<longleftrightarrow> (\\<forall>x. x \\<notin> S \\<longrightarrow> p x = x) \\<and> (\\<forall>y. \\<exists>!x. p x = y)\"\n\nlemma permutes_in_image: \"p permutes S \\<Longrightarrow> p x \\<in> S \\<longleftrightarrow> x \\<in> S\"\n  unfolding permutes_def by metis\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 permutes_image: \"p permutes S \\<Longrightarrow> p ` S = S\"\n  unfolding permutes_def\n  apply (rule set_eqI)\n  apply (simp add: image_iff)\n  apply metis\n  done\n\nlemma permutes_inj: \"p permutes S \\<Longrightarrow> inj p\"\n  unfolding permutes_def inj_on_def by blast\n\nlemma permutes_inj_on: \"f permutes S \\<Longrightarrow> inj_on f A\"\n  unfolding permutes_def inj_on_def by auto\n\nlemma permutes_surj: \"p permutes s \\<Longrightarrow> surj p\"\n  unfolding permutes_def surj_def by metis\n\nlemma permutes_bij: \"p permutes s \\<Longrightarrow> bij p\"\nunfolding bij_def by (metis permutes_inj permutes_surj)\n\nlemma permutes_imp_bij: \"p permutes S \\<Longrightarrow> bij_betw p S S\"\nby (metis UNIV_I bij_betw_subset permutes_bij permutes_image subsetI)\n\nlemma bij_imp_permutes: \"bij_betw p S S \\<Longrightarrow> (\\<And>x. x \\<notin> S \\<Longrightarrow> p x = x) \\<Longrightarrow> p permutes S\"\n  unfolding permutes_def bij_betw_def inj_on_def\n  by auto (metis image_iff)+\n\nlemma permutes_inv_o:\n  assumes pS: \"p permutes S\"\n  shows \"p \\<circ> inv p = id\"\n    and \"inv p \\<circ> p = id\"\n  using permutes_inj[OF pS] permutes_surj[OF pS]\n  unfolding inj_iff[symmetric] surj_iff[symmetric] by blast+\n\nlemma permutes_inverses:\n  fixes p :: \"'a \\<Rightarrow> 'a\"\n  assumes pS: \"p permutes S\"\n  shows \"p (inv p x) = x\"\n    and \"inv p (p x) = x\"\n  using permutes_inv_o[OF pS, unfolded fun_eq_iff o_def] by auto\n\nlemma permutes_subset: \"p permutes S \\<Longrightarrow> S \\<subseteq> T \\<Longrightarrow> p permutes T\"\n  unfolding permutes_def by blast\n\nlemma permutes_empty[simp]: \"p permutes {} \\<longleftrightarrow> p = id\"\n  unfolding fun_eq_iff permutes_def by simp metis\n\nlemma permutes_sing[simp]: \"p permutes {a} \\<longleftrightarrow> p = id\"\n  unfolding fun_eq_iff permutes_def by simp metis\n\nlemma permutes_univ: \"p permutes UNIV \\<longleftrightarrow> (\\<forall>y. \\<exists>!x. p x = y)\"\n  unfolding permutes_def by simp\n\nlemma permutes_inv_eq: \"p permutes S \\<Longrightarrow> inv p y = x \\<longleftrightarrow> p x = y\"\n  unfolding permutes_def inv_def\n  apply auto\n  apply (erule allE[where x=y])\n  apply (erule allE[where x=y])\n  apply (rule someI_ex)\n  apply blast\n  apply (rule some1_equality)\n  apply blast\n  apply blast\n  done\n\nlemma permutes_swap_id: \"a \\<in> S \\<Longrightarrow> b \\<in> S \\<Longrightarrow> Fun.swap a b id permutes S\"\n  unfolding permutes_def Fun.swap_def fun_upd_def by auto metis\n\nlemma permutes_superset: \"p permutes S \\<Longrightarrow> (\\<forall>x \\<in> S - T. p x = x) \\<Longrightarrow> p permutes T\"\n  by (simp add: Ball_def permutes_def) metis\n\n(* Next three lemmas contributed by Lukas Bulwahn *)\nlemma permutes_bij_inv_into:\n  fixes A :: \"'a set\" and B :: \"'b set\"\n  assumes \"p permutes A\"\n  assumes \"bij_betw f A B\"\n  shows \"(\\<lambda>x. if x \\<in> B then f (p (inv_into A f x)) else x) permutes B\"\nproof (rule bij_imp_permutes)\n  have \"bij_betw p A A\" \"bij_betw f A B\" \"bij_betw (inv_into A f) B A\"\n    using assms by (auto simp add: permutes_imp_bij bij_betw_inv_into)\n  from this have \"bij_betw (f o p o inv_into A f) B B\" by (simp add: bij_betw_trans)\n  from this show \"bij_betw (\\<lambda>x. if x \\<in> B then f (p (inv_into A f x)) else x) B B\"\n    by (subst bij_betw_cong[where g=\"f o p o inv_into A f\"]) auto\nnext\n  fix x\n  assume \"x \\<notin> B\"\n  from this show \"(if x \\<in> B then f (p (inv_into A f x)) else x) = x\" by auto\nqed\n\nlemma permutes_image_mset:\n  assumes \"p permutes A\"\n  shows \"image_mset p (mset_set A) = mset_set A\"\nusing assms by (metis image_mset_mset_set bij_betw_imp_inj_on permutes_imp_bij permutes_image)\n\nlemma permutes_implies_image_mset_eq:\n  assumes \"p permutes A\" \"\\<And>x. x \\<in> A \\<Longrightarrow> f x = f' (p x)\"\n  shows \"image_mset f' (mset_set A) = image_mset f (mset_set A)\"\nproof -\n  have \"f x = f' (p x)\" if x: \"x \\<in># mset_set A\" for x\n    using assms(2)[of x] x by (cases \"finite A\") auto\n  from this have \"image_mset f (mset_set A) = image_mset (f' o p) (mset_set A)\"\n    using assms by (auto intro!: image_mset_cong)\n  also have \"\\<dots> = image_mset f' (image_mset p (mset_set A))\"\n    by (simp add: image_mset.compositionality)\n  also have \"\\<dots> = image_mset f' (mset_set A)\"\n  proof -\n    from assms have \"image_mset p (mset_set A) = mset_set A\"\n      using permutes_image_mset by blast\n    from this show ?thesis by simp\n  qed\n  finally show ?thesis ..\nqed\n\n\nsubsection \\<open>Group properties\\<close>\n\nlemma permutes_id: \"id permutes S\"\n  unfolding permutes_def by simp\n\nlemma permutes_compose: \"p permutes S \\<Longrightarrow> q permutes S \\<Longrightarrow> q \\<circ> p permutes S\"\n  unfolding permutes_def o_def by metis\n\nlemma permutes_inv:\n  assumes pS: \"p permutes S\"\n  shows \"inv p permutes S\"\n  using pS unfolding permutes_def permutes_inv_eq[OF pS] by metis\n\nlemma permutes_inv_inv:\n  assumes pS: \"p permutes S\"\n  shows \"inv (inv p) = p\"\n  unfolding fun_eq_iff permutes_inv_eq[OF pS] permutes_inv_eq[OF permutes_inv[OF pS]]\n  by blast\n\nlemma permutes_invI:\n  assumes perm: \"p permutes S\"\n      and inv:  \"\\<And>x. x \\<in> S \\<Longrightarrow> p' (p x) = x\"\n      and outside: \"\\<And>x. x \\<notin> S \\<Longrightarrow> p' x = x\"\n  shows   \"inv p = p'\"\nproof\n  fix x show \"inv p x = p' x\"\n  proof (cases \"x \\<in> S\")\n    assume [simp]: \"x \\<in> S\"\n    from assms have \"p' x = p' (p (inv p x))\" by (simp add: permutes_inverses)\n    also from permutes_inv[OF perm]\n      have \"\\<dots> = inv p x\" by (subst inv) (simp_all add: permutes_in_image)\n    finally show \"inv p x = p' x\" ..\n  qed (insert permutes_inv[OF perm], simp_all add: outside permutes_not_in)\nqed\n\nlemma permutes_vimage: \"f permutes A \\<Longrightarrow> f -` A = A\"\n  by (simp add: bij_vimage_eq_inv_image permutes_bij permutes_image[OF permutes_inv])\n\n\nsubsection \\<open>The number of permutations on a finite set\\<close>\n\nlemma permutes_insert_lemma:\n  assumes pS: \"p permutes (insert a S)\"\n  shows \"Fun.swap a (p a) id \\<circ> p permutes S\"\n  apply (rule permutes_superset[where S = \"insert a S\"])\n  apply (rule permutes_compose[OF pS])\n  apply (rule permutes_swap_id, simp)\n  using permutes_in_image[OF pS, of a]\n  apply simp\n  apply (auto simp add: Ball_def Fun.swap_def)\n  done\n\nlemma permutes_insert: \"{p. p permutes (insert a S)} =\n  (\\<lambda>(b,p). Fun.swap a b id \\<circ> p) ` {(b,p). b \\<in> insert a S \\<and> p \\<in> {p. p permutes S}}\"\nproof -\n  {\n    fix p\n    {\n      assume pS: \"p permutes insert a S\"\n      let ?b = \"p a\"\n      let ?q = \"Fun.swap a (p a) id \\<circ> p\"\n      have th0: \"p = Fun.swap a ?b id \\<circ> ?q\"\n        unfolding fun_eq_iff o_assoc by simp\n      have th1: \"?b \\<in> insert a S\"\n        unfolding permutes_in_image[OF pS] by simp\n      from permutes_insert_lemma[OF pS] th0 th1\n      have \"\\<exists>b q. p = Fun.swap a b id \\<circ> q \\<and> b \\<in> insert a S \\<and> q permutes S\" by blast\n    }\n    moreover\n    {\n      fix b q\n      assume bq: \"p = Fun.swap a b id \\<circ> q\" \"b \\<in> insert a S\" \"q permutes S\"\n      from permutes_subset[OF bq(3), of \"insert a S\"]\n      have qS: \"q permutes insert a S\"\n        by auto\n      have aS: \"a \\<in> insert a S\"\n        by simp\n      from bq(1) permutes_compose[OF qS permutes_swap_id[OF aS bq(2)]]\n      have \"p permutes insert a S\"\n        by simp\n    }\n    ultimately have \"p permutes insert a S \\<longleftrightarrow>\n        (\\<exists>b q. p = Fun.swap a b id \\<circ> q \\<and> b \\<in> insert a S \\<and> q permutes S)\"\n      by blast\n  }\n  then show ?thesis\n    by auto\nqed\n\nlemma card_permutations:\n  assumes Sn: \"card S = n\"\n    and fS: \"finite S\"\n  shows \"card {p. p permutes S} = fact n\"\n  using fS Sn\nproof (induct arbitrary: n)\n  case empty\n  then show ?case by simp\nnext\n  case (insert x F)\n  {\n    fix n\n    assume H0: \"card (insert x F) = n\"\n    let ?xF = \"{p. p permutes insert x F}\"\n    let ?pF = \"{p. p permutes F}\"\n    let ?pF' = \"{(b, p). b \\<in> insert x F \\<and> p \\<in> ?pF}\"\n    let ?g = \"(\\<lambda>(b, p). Fun.swap x b id \\<circ> p)\"\n    from permutes_insert[of x F]\n    have xfgpF': \"?xF = ?g ` ?pF'\" .\n    have Fs: \"card F = n - 1\"\n      using \\<open>x \\<notin> F\\<close> H0 \\<open>finite F\\<close> by auto\n    from insert.hyps Fs have pFs: \"card ?pF = fact (n - 1)\"\n      using \\<open>finite F\\<close> by auto\n    then have \"finite ?pF\"\n      by (auto intro: card_ge_0_finite)\n    then have pF'f: \"finite ?pF'\"\n      using H0 \\<open>finite F\\<close>\n      apply (simp only: Collect_case_prod Collect_mem_eq)\n      apply (rule finite_cartesian_product)\n      apply simp_all\n      done\n\n    have ginj: \"inj_on ?g ?pF'\"\n    proof -\n      {\n        fix b p c q\n        assume bp: \"(b,p) \\<in> ?pF'\"\n        assume cq: \"(c,q) \\<in> ?pF'\"\n        assume eq: \"?g (b,p) = ?g (c,q)\"\n        from bp cq have ths: \"b \\<in> insert x F\" \"c \\<in> insert x F\" \"x \\<in> insert x F\"\n          \"p permutes F\" \"q permutes F\"\n          by auto\n        from ths(4) \\<open>x \\<notin> F\\<close> eq have \"b = ?g (b,p) x\"\n          unfolding permutes_def\n          by (auto simp add: Fun.swap_def fun_upd_def fun_eq_iff)\n        also have \"\\<dots> = ?g (c,q) x\"\n          using ths(5) \\<open>x \\<notin> F\\<close> eq\n          by (auto simp add: swap_def fun_upd_def fun_eq_iff)\n        also have \"\\<dots> = c\"\n          using ths(5) \\<open>x \\<notin> F\\<close>\n          unfolding permutes_def\n          by (auto simp add: Fun.swap_def fun_upd_def fun_eq_iff)\n        finally have bc: \"b = c\" .\n        then have \"Fun.swap x b id = Fun.swap x c id\"\n          by simp\n        with eq have \"Fun.swap x b id \\<circ> p = Fun.swap x b id \\<circ> q\"\n          by simp\n        then have \"Fun.swap x b id \\<circ> (Fun.swap x b id \\<circ> p) =\n          Fun.swap x b id \\<circ> (Fun.swap x b id \\<circ> q)\"\n          by simp\n        then have \"p = q\"\n          by (simp add: o_assoc)\n        with bc have \"(b, p) = (c, q)\"\n          by simp\n      }\n      then show ?thesis\n        unfolding inj_on_def by blast\n    qed\n    from \\<open>x \\<notin> F\\<close> H0 have n0: \"n \\<noteq> 0\"\n      using \\<open>finite F\\<close> by auto\n    then have \"\\<exists>m. n = Suc m\"\n      by presburger\n    then obtain m where n[simp]: \"n = Suc m\"\n      by blast\n    from pFs H0 have xFc: \"card ?xF = fact n\"\n      unfolding xfgpF' card_image[OF ginj]\n      using \\<open>finite F\\<close> \\<open>finite ?pF\\<close>\n      apply (simp only: Collect_case_prod Collect_mem_eq card_cartesian_product)\n      apply simp\n      done\n    from finite_imageI[OF pF'f, of ?g] have xFf: \"finite ?xF\"\n      unfolding xfgpF' by simp\n    have \"card ?xF = fact n\"\n      using xFf xFc unfolding xFf by blast\n  }\n  then show ?case\n    using insert by simp\nqed\n\nlemma finite_permutations:\n  assumes fS: \"finite S\"\n  shows \"finite {p. p permutes S}\"\n  using card_permutations[OF refl fS]\n  by (auto intro: card_ge_0_finite)\n\n\nsubsection \\<open>Permutations of index set for iterated operations\\<close>\n\nlemma (in comm_monoid_set) permute:\n  assumes \"p permutes S\"\n  shows \"F g S = F (g \\<circ> p) S\"\nproof -\n  from \\<open>p permutes S\\<close> have \"inj p\"\n    by (rule permutes_inj)\n  then have \"inj_on p S\"\n    by (auto intro: subset_inj_on)\n  then have \"F g (p ` S) = F (g \\<circ> p) S\"\n    by (rule reindex)\n  moreover from \\<open>p permutes S\\<close> have \"p ` S = S\"\n    by (rule permutes_image)\n  ultimately show ?thesis\n    by simp\nqed\n\n\nsubsection \\<open>Various combinations of transpositions with 2, 1 and 0 common elements\\<close>\n\nlemma swap_id_common:\" a \\<noteq> c \\<Longrightarrow> b \\<noteq> c \\<Longrightarrow>\n  Fun.swap a b id \\<circ> Fun.swap a c id = Fun.swap b c id \\<circ> Fun.swap a b id\"\n  by (simp add: fun_eq_iff Fun.swap_def)\n\nlemma swap_id_common': \"a \\<noteq> b \\<Longrightarrow> a \\<noteq> c \\<Longrightarrow>\n  Fun.swap a c id \\<circ> Fun.swap b c id = Fun.swap b c id \\<circ> Fun.swap a b id\"\n  by (simp add: fun_eq_iff Fun.swap_def)\n\nlemma swap_id_independent: \"a \\<noteq> c \\<Longrightarrow> a \\<noteq> d \\<Longrightarrow> b \\<noteq> c \\<Longrightarrow> b \\<noteq> d \\<Longrightarrow>\n  Fun.swap a b id \\<circ> Fun.swap c d id = Fun.swap c d id \\<circ> Fun.swap a b id\"\n  by (simp add: fun_eq_iff Fun.swap_def)\n\n\nsubsection \\<open>Permutations as transposition sequences\\<close>\n\ninductive swapidseq :: \"nat \\<Rightarrow> ('a \\<Rightarrow> 'a) \\<Rightarrow> bool\"\nwhere\n  id[simp]: \"swapidseq 0 id\"\n| comp_Suc: \"swapidseq n p \\<Longrightarrow> a \\<noteq> b \\<Longrightarrow> swapidseq (Suc n) (Fun.swap a b id \\<circ> p)\"\n\ndeclare id[unfolded id_def, simp]\n\ndefinition \"permutation p \\<longleftrightarrow> (\\<exists>n. swapidseq n p)\"\n\n\nsubsection \\<open>Some closure properties of the set of permutations, with lengths\\<close>\n\nlemma permutation_id[simp]: \"permutation id\"\n  unfolding permutation_def by (rule exI[where x=0]) simp\n\ndeclare permutation_id[unfolded id_def, simp]\n\nlemma swapidseq_swap: \"swapidseq (if a = b then 0 else 1) (Fun.swap a b id)\"\n  apply clarsimp\n  using comp_Suc[of 0 id a b]\n  apply simp\n  done\n\nlemma permutation_swap_id: \"permutation (Fun.swap a b id)\"\n  apply (cases \"a = b\")\n  apply simp_all\n  unfolding permutation_def\n  using swapidseq_swap[of a b]\n  apply blast\n  done\n\nlemma swapidseq_comp_add: \"swapidseq n p \\<Longrightarrow> swapidseq m q \\<Longrightarrow> swapidseq (n + m) (p \\<circ> q)\"\nproof (induct n p arbitrary: m q rule: swapidseq.induct)\n  case (id m q)\n  then show ?case by simp\nnext\n  case (comp_Suc n p a b m q)\n  have th: \"Suc n + m = Suc (n + m)\"\n    by arith\n  show ?case\n    unfolding th comp_assoc\n    apply (rule swapidseq.comp_Suc)\n    using comp_Suc.hyps(2)[OF comp_Suc.prems] comp_Suc.hyps(3)\n    apply blast+\n    done\nqed\n\nlemma permutation_compose: \"permutation p \\<Longrightarrow> permutation q \\<Longrightarrow> permutation (p \\<circ> q)\"\n  unfolding permutation_def using swapidseq_comp_add[of _ p _ q] by metis\n\nlemma swapidseq_endswap: \"swapidseq n p \\<Longrightarrow> a \\<noteq> b \\<Longrightarrow> swapidseq (Suc n) (p \\<circ> Fun.swap a b id)\"\n  apply (induct n p rule: swapidseq.induct)\n  using swapidseq_swap[of a b]\n  apply (auto simp add: comp_assoc intro: swapidseq.comp_Suc)\n  done\n\nlemma swapidseq_inverse_exists: \"swapidseq n p \\<Longrightarrow> \\<exists>q. swapidseq n q \\<and> p \\<circ> q = id \\<and> q \\<circ> p = id\"\nproof (induct n p rule: swapidseq.induct)\n  case id\n  then show ?case\n    by (rule exI[where x=id]) simp\nnext\n  case (comp_Suc n p a b)\n  from comp_Suc.hyps obtain q where q: \"swapidseq n q\" \"p \\<circ> q = id\" \"q \\<circ> p = id\"\n    by blast\n  let ?q = \"q \\<circ> Fun.swap a b id\"\n  note H = comp_Suc.hyps\n  from swapidseq_swap[of a b] H(3) have th0: \"swapidseq 1 (Fun.swap a b id)\"\n    by simp\n  from swapidseq_comp_add[OF q(1) th0] have th1: \"swapidseq (Suc n) ?q\"\n    by simp\n  have \"Fun.swap a b id \\<circ> p \\<circ> ?q = Fun.swap a b id \\<circ> (p \\<circ> q) \\<circ> Fun.swap a b id\"\n    by (simp add: o_assoc)\n  also have \"\\<dots> = id\"\n    by (simp add: q(2))\n  finally have th2: \"Fun.swap a b id \\<circ> p \\<circ> ?q = id\" .\n  have \"?q \\<circ> (Fun.swap a b id \\<circ> p) = q \\<circ> (Fun.swap a b id \\<circ> Fun.swap a b id) \\<circ> p\"\n    by (simp only: o_assoc)\n  then have \"?q \\<circ> (Fun.swap a b id \\<circ> p) = id\"\n    by (simp add: q(3))\n  with th1 th2 show ?case\n    by blast\nqed\n\nlemma swapidseq_inverse:\n  assumes H: \"swapidseq n p\"\n  shows \"swapidseq n (inv p)\"\n  using swapidseq_inverse_exists[OF H] inv_unique_comp[of p] by auto\n\nlemma permutation_inverse: \"permutation p \\<Longrightarrow> permutation (inv p)\"\n  using permutation_def swapidseq_inverse by blast\n\n\nsubsection \\<open>The identity map only has even transposition sequences\\<close>\n\nlemma symmetry_lemma:\n  assumes \"\\<And>a b c d. P a b c d \\<Longrightarrow> P a b d c\"\n    and \"\\<And>a b c d. a \\<noteq> b \\<Longrightarrow> c \\<noteq> d \\<Longrightarrow>\n      a = c \\<and> b = d \\<or> a = c \\<and> b \\<noteq> d \\<or> a \\<noteq> c \\<and> b = d \\<or> a \\<noteq> c \\<and> a \\<noteq> d \\<and> b \\<noteq> c \\<and> b \\<noteq> d \\<Longrightarrow>\n      P a b c d\"\n  shows \"\\<And>a b c d. a \\<noteq> b \\<longrightarrow> c \\<noteq> d \\<longrightarrow>  P a b c d\"\n  using assms by metis\n\nlemma swap_general: \"a \\<noteq> b \\<Longrightarrow> c \\<noteq> d \\<Longrightarrow>\n  Fun.swap a b id \\<circ> Fun.swap c d id = id \\<or>\n  (\\<exists>x y z. x \\<noteq> a \\<and> y \\<noteq> a \\<and> z \\<noteq> a \\<and> x \\<noteq> y \\<and>\n    Fun.swap a b id \\<circ> Fun.swap c d id = Fun.swap x y id \\<circ> Fun.swap a z id)\"\nproof -\n  assume H: \"a \\<noteq> b\" \"c \\<noteq> d\"\n  have \"a \\<noteq> b \\<longrightarrow> c \\<noteq> d \\<longrightarrow>\n    (Fun.swap a b id \\<circ> Fun.swap c d id = id \\<or>\n      (\\<exists>x y z. x \\<noteq> a \\<and> y \\<noteq> a \\<and> z \\<noteq> a \\<and> x \\<noteq> y \\<and>\n        Fun.swap a b id \\<circ> Fun.swap c d id = Fun.swap x y id \\<circ> Fun.swap a z id))\"\n    apply (rule symmetry_lemma[where a=a and b=b and c=c and d=d])\n    apply (simp_all only: swap_commute)\n    apply (case_tac \"a = c \\<and> b = d\")\n    apply (clarsimp simp only: swap_commute swap_id_idempotent)\n    apply (case_tac \"a = c \\<and> b \\<noteq> d\")\n    apply (rule disjI2)\n    apply (rule_tac x=\"b\" in exI)\n    apply (rule_tac x=\"d\" in exI)\n    apply (rule_tac x=\"b\" in exI)\n    apply (clarsimp simp add: fun_eq_iff Fun.swap_def)\n    apply (case_tac \"a \\<noteq> c \\<and> b = d\")\n    apply (rule disjI2)\n    apply (rule_tac x=\"c\" in exI)\n    apply (rule_tac x=\"d\" in exI)\n    apply (rule_tac x=\"c\" in exI)\n    apply (clarsimp simp add: fun_eq_iff Fun.swap_def)\n    apply (rule disjI2)\n    apply (rule_tac x=\"c\" in exI)\n    apply (rule_tac x=\"d\" in exI)\n    apply (rule_tac x=\"b\" in exI)\n    apply (clarsimp simp add: fun_eq_iff Fun.swap_def)\n    done\n  with H show ?thesis by metis\nqed\n\nlemma swapidseq_id_iff[simp]: \"swapidseq 0 p \\<longleftrightarrow> p = id\"\n  using swapidseq.cases[of 0 p \"p = id\"]\n  by auto\n\nlemma swapidseq_cases: \"swapidseq n p \\<longleftrightarrow>\n  n = 0 \\<and> p = id \\<or> (\\<exists>a b q m. n = Suc m \\<and> p = Fun.swap a b id \\<circ> q \\<and> swapidseq m q \\<and> a \\<noteq> b)\"\n  apply (rule iffI)\n  apply (erule swapidseq.cases[of n p])\n  apply simp\n  apply (rule disjI2)\n  apply (rule_tac x= \"a\" in exI)\n  apply (rule_tac x= \"b\" in exI)\n  apply (rule_tac x= \"pa\" in exI)\n  apply (rule_tac x= \"na\" in exI)\n  apply simp\n  apply auto\n  apply (rule comp_Suc, simp_all)\n  done\n\nlemma fixing_swapidseq_decrease:\n  assumes spn: \"swapidseq n p\"\n    and ab: \"a \\<noteq> b\"\n    and pa: \"(Fun.swap a b id \\<circ> p) a = a\"\n  shows \"n \\<noteq> 0 \\<and> swapidseq (n - 1) (Fun.swap a b id \\<circ> p)\"\n  using spn ab pa\nproof (induct n arbitrary: p a b)\n  case 0\n  then show ?case\n    by (auto simp add: Fun.swap_def fun_upd_def)\nnext\n  case (Suc n p a b)\n  from Suc.prems(1) swapidseq_cases[of \"Suc n\" p]\n  obtain c d q m where\n    cdqm: \"Suc n = Suc m\" \"p = Fun.swap c d id \\<circ> q\" \"swapidseq m q\" \"c \\<noteq> d\" \"n = m\"\n    by auto\n  {\n    assume H: \"Fun.swap a b id \\<circ> Fun.swap c d id = id\"\n    have ?case by (simp only: cdqm o_assoc H) (simp add: cdqm)\n  }\n  moreover\n  {\n    fix x y z\n    assume H: \"x \\<noteq> a\" \"y \\<noteq> a\" \"z \\<noteq> a\" \"x \\<noteq> y\"\n      \"Fun.swap a b id \\<circ> Fun.swap c d id = Fun.swap x y id \\<circ> Fun.swap a z id\"\n    from H have az: \"a \\<noteq> z\"\n      by simp\n\n    {\n      fix h\n      have \"(Fun.swap x y id \\<circ> h) a = a \\<longleftrightarrow> h a = a\"\n        using H by (simp add: Fun.swap_def)\n    }\n    note th3 = this\n    from cdqm(2) have \"Fun.swap a b id \\<circ> p = Fun.swap a b id \\<circ> (Fun.swap c d id \\<circ> q)\"\n      by simp\n    then have \"Fun.swap a b id \\<circ> p = Fun.swap x y id \\<circ> (Fun.swap a z id \\<circ> q)\"\n      by (simp add: o_assoc H)\n    then have \"(Fun.swap a b id \\<circ> p) a = (Fun.swap x y id \\<circ> (Fun.swap a z id \\<circ> q)) a\"\n      by simp\n    then have \"(Fun.swap x y id \\<circ> (Fun.swap a z id \\<circ> q)) a = a\"\n      unfolding Suc by metis\n    then have th1: \"(Fun.swap a z id \\<circ> q) a = a\"\n      unfolding th3 .\n    from Suc.hyps[OF cdqm(3)[ unfolded cdqm(5)[symmetric]] az th1]\n    have th2: \"swapidseq (n - 1) (Fun.swap a z id \\<circ> q)\" \"n \\<noteq> 0\"\n      by blast+\n    have th: \"Suc n - 1 = Suc (n - 1)\"\n      using th2(2) by auto\n    have ?case\n      unfolding cdqm(2) H o_assoc th\n      apply (simp only: Suc_not_Zero simp_thms comp_assoc)\n      apply (rule comp_Suc)\n      using th2 H\n      apply blast+\n      done\n  }\n  ultimately show ?case\n    using swap_general[OF Suc.prems(2) cdqm(4)] by metis\nqed\n\nlemma swapidseq_identity_even:\n  assumes \"swapidseq n (id :: 'a \\<Rightarrow> 'a)\"\n  shows \"even n\"\n  using \\<open>swapidseq n id\\<close>\nproof (induct n rule: nat_less_induct)\n  fix n\n  assume H: \"\\<forall>m<n. swapidseq m (id::'a \\<Rightarrow> 'a) \\<longrightarrow> even m\" \"swapidseq n (id :: 'a \\<Rightarrow> 'a)\"\n  {\n    assume \"n = 0\"\n    then have \"even n\" by presburger\n  }\n  moreover\n  {\n    fix a b :: 'a and q m\n    assume h: \"n = Suc m\" \"(id :: 'a \\<Rightarrow> 'a) = Fun.swap a b id \\<circ> q\" \"swapidseq m q\" \"a \\<noteq> b\"\n    from fixing_swapidseq_decrease[OF h(3,4), unfolded h(2)[symmetric]]\n    have m: \"m \\<noteq> 0\" \"swapidseq (m - 1) (id :: 'a \\<Rightarrow> 'a)\"\n      by auto\n    from h m have mn: \"m - 1 < n\"\n      by arith\n    from H(1)[rule_format, OF mn m(2)] h(1) m(1) have \"even n\"\n      by presburger\n  }\n  ultimately show \"even n\"\n    using H(2)[unfolded swapidseq_cases[of n id]] by auto\nqed\n\n\nsubsection \\<open>Therefore we have a welldefined notion of parity\\<close>\n\ndefinition \"evenperm p = even (SOME n. swapidseq n p)\"\n\nlemma swapidseq_even_even:\n  assumes m: \"swapidseq m p\"\n    and n: \"swapidseq n p\"\n  shows \"even m \\<longleftrightarrow> even n\"\nproof -\n  from swapidseq_inverse_exists[OF n]\n  obtain q where q: \"swapidseq n q\" \"p \\<circ> q = id\" \"q \\<circ> p = id\"\n    by blast\n  from swapidseq_identity_even[OF swapidseq_comp_add[OF m q(1), unfolded q]]\n  show ?thesis\n    by arith\nqed\n\nlemma evenperm_unique:\n  assumes p: \"swapidseq n p\"\n    and n:\"even n = b\"\n  shows \"evenperm p = b\"\n  unfolding n[symmetric] evenperm_def\n  apply (rule swapidseq_even_even[where p = p])\n  apply (rule someI[where x = n])\n  using p\n  apply blast+\n  done\n\n\nsubsection \\<open>And it has the expected composition properties\\<close>\n\nlemma evenperm_id[simp]: \"evenperm id = True\"\n  by (rule evenperm_unique[where n = 0]) simp_all\n\nlemma evenperm_swap: \"evenperm (Fun.swap a b id) = (a = b)\"\n  by (rule evenperm_unique[where n=\"if a = b then 0 else 1\"]) (simp_all add: swapidseq_swap)\n\nlemma evenperm_comp:\n  assumes p: \"permutation p\"\n    and q:\"permutation q\"\n  shows \"evenperm (p \\<circ> q) = (evenperm p = evenperm q)\"\nproof -\n  from p q obtain n m where n: \"swapidseq n p\" and m: \"swapidseq m q\"\n    unfolding permutation_def by blast\n  note nm =  swapidseq_comp_add[OF n m]\n  have th: \"even (n + m) = (even n \\<longleftrightarrow> even m)\"\n    by arith\n  from evenperm_unique[OF n refl] evenperm_unique[OF m refl]\n    evenperm_unique[OF nm th]\n  show ?thesis\n    by blast\nqed\n\nlemma evenperm_inv:\n  assumes p: \"permutation p\"\n  shows \"evenperm (inv p) = evenperm p\"\nproof -\n  from p obtain n where n: \"swapidseq n p\"\n    unfolding permutation_def by blast\n  from evenperm_unique[OF swapidseq_inverse[OF n] evenperm_unique[OF n refl, symmetric]]\n  show ?thesis .\nqed\n\n\nsubsection \\<open>A more abstract characterization of permutations\\<close>\n\nlemma bij_iff: \"bij f \\<longleftrightarrow> (\\<forall>x. \\<exists>!y. f y = x)\"\n  unfolding bij_def inj_on_def surj_def\n  apply auto\n  apply metis\n  apply metis\n  done\n\nlemma permutation_bijective:\n  assumes p: \"permutation p\"\n  shows \"bij p\"\nproof -\n  from p obtain n where n: \"swapidseq n p\"\n    unfolding permutation_def by blast\n  from swapidseq_inverse_exists[OF n]\n  obtain q where q: \"swapidseq n q\" \"p \\<circ> q = id\" \"q \\<circ> p = id\"\n    by blast\n  then show ?thesis unfolding bij_iff\n    apply (auto simp add: fun_eq_iff)\n    apply metis\n    done\nqed\n\nlemma permutation_finite_support:\n  assumes p: \"permutation p\"\n  shows \"finite {x. p x \\<noteq> x}\"\nproof -\n  from p obtain n where n: \"swapidseq n p\"\n    unfolding permutation_def by blast\n  from n show ?thesis\n  proof (induct n p rule: swapidseq.induct)\n    case id\n    then show ?case by simp\n  next\n    case (comp_Suc n p a b)\n    let ?S = \"insert a (insert b {x. p x \\<noteq> x})\"\n    from comp_Suc.hyps(2) have fS: \"finite ?S\"\n      by simp\n    from \\<open>a \\<noteq> b\\<close> have th: \"{x. (Fun.swap a b id \\<circ> p) x \\<noteq> x} \\<subseteq> ?S\"\n      by (auto simp add: Fun.swap_def)\n    from finite_subset[OF th fS] show ?case  .\n  qed\nqed\n\nlemma permutation_lemma:\n  assumes fS: \"finite S\"\n    and p: \"bij p\"\n    and pS: \"\\<forall>x. x\\<notin> S \\<longrightarrow> p x = x\"\n  shows \"permutation p\"\n  using fS p pS\nproof (induct S arbitrary: p rule: finite_induct)\n  case (empty p)\n  then show ?case by simp\nnext\n  case (insert a F p)\n  let ?r = \"Fun.swap a (p a) id \\<circ> p\"\n  let ?q = \"Fun.swap a (p a) id \\<circ> ?r\"\n  have raa: \"?r a = a\"\n    by (simp add: Fun.swap_def)\n  from bij_swap_ompose_bij[OF insert(4)]\n  have br: \"bij ?r\"  .\n\n  from insert raa have th: \"\\<forall>x. x \\<notin> F \\<longrightarrow> ?r x = x\"\n    apply (clarsimp simp add: Fun.swap_def)\n    apply (erule_tac x=\"x\" in allE)\n    apply auto\n    unfolding bij_iff\n    apply metis\n    done\n  from insert(3)[OF br th]\n  have rp: \"permutation ?r\" .\n  have \"permutation ?q\"\n    by (simp add: permutation_compose permutation_swap_id rp)\n  then show ?case\n    by (simp add: o_assoc)\nqed\n\nlemma permutation: \"permutation p \\<longleftrightarrow> bij p \\<and> finite {x. p x \\<noteq> x}\"\n  (is \"?lhs \\<longleftrightarrow> ?b \\<and> ?f\")\nproof\n  assume p: ?lhs\n  from p permutation_bijective permutation_finite_support show \"?b \\<and> ?f\"\n    by auto\nnext\n  assume \"?b \\<and> ?f\"\n  then have \"?f\" \"?b\" by blast+\n  from permutation_lemma[OF this] show ?lhs\n    by blast\nqed\n\nlemma permutation_inverse_works:\n  assumes p: \"permutation p\"\n  shows \"inv p \\<circ> p = id\"\n    and \"p \\<circ> inv p = id\"\n  using permutation_bijective [OF p]\n  unfolding bij_def inj_iff surj_iff by auto\n\nlemma permutation_inverse_compose:\n  assumes p: \"permutation p\"\n    and q: \"permutation q\"\n  shows \"inv (p \\<circ> q) = inv q \\<circ> inv p\"\nproof -\n  note ps = permutation_inverse_works[OF p]\n  note qs = permutation_inverse_works[OF q]\n  have \"p \\<circ> q \\<circ> (inv q \\<circ> inv p) = p \\<circ> (q \\<circ> inv q) \\<circ> inv p\"\n    by (simp add: o_assoc)\n  also have \"\\<dots> = id\"\n    by (simp add: ps qs)\n  finally have th0: \"p \\<circ> q \\<circ> (inv q \\<circ> inv p) = id\" .\n  have \"inv q \\<circ> inv p \\<circ> (p \\<circ> q) = inv q \\<circ> (inv p \\<circ> p) \\<circ> q\"\n    by (simp add: o_assoc)\n  also have \"\\<dots> = id\"\n    by (simp add: ps qs)\n  finally have th1: \"inv q \\<circ> inv p \\<circ> (p \\<circ> q) = id\" .\n  from inv_unique_comp[OF th0 th1] show ?thesis .\nqed\n\n\nsubsection \\<open>Relation to \"permutes\"\\<close>\n\nlemma permutation_permutes: \"permutation p \\<longleftrightarrow> (\\<exists>S. finite S \\<and> p permutes S)\"\n  unfolding permutation permutes_def bij_iff[symmetric]\n  apply (rule iffI, clarify)\n  apply (rule exI[where x=\"{x. p x \\<noteq> x}\"])\n  apply simp\n  apply clarsimp\n  apply (rule_tac B=\"S\" in finite_subset)\n  apply auto\n  done\n\n\nsubsection \\<open>Hence a sort of induction principle composing by swaps\\<close>\n\nlemma permutes_induct: \"finite S \\<Longrightarrow> P id \\<Longrightarrow>\n  (\\<And> a b p. a \\<in> S \\<Longrightarrow> b \\<in> S \\<Longrightarrow> P p \\<Longrightarrow> P p \\<Longrightarrow> permutation p \\<Longrightarrow> P (Fun.swap a b id \\<circ> p)) \\<Longrightarrow>\n  (\\<And>p. p permutes S \\<Longrightarrow> P p)\"\nproof (induct S rule: finite_induct)\n  case empty\n  then show ?case by auto\nnext\n  case (insert x F p)\n  let ?r = \"Fun.swap x (p x) id \\<circ> p\"\n  let ?q = \"Fun.swap x (p x) id \\<circ> ?r\"\n  have qp: \"?q = p\"\n    by (simp add: o_assoc)\n  from permutes_insert_lemma[OF insert.prems(3)] insert have Pr: \"P ?r\"\n    by blast\n  from permutes_in_image[OF insert.prems(3), of x]\n  have pxF: \"p x \\<in> insert x F\"\n    by simp\n  have xF: \"x \\<in> insert x F\"\n    by simp\n  have rp: \"permutation ?r\"\n    unfolding permutation_permutes using insert.hyps(1)\n      permutes_insert_lemma[OF insert.prems(3)]\n    by blast\n  from insert.prems(2)[OF xF pxF Pr Pr rp]\n  show ?case\n    unfolding qp .\nqed\n\n\nsubsection \\<open>Sign of a permutation as a real number\\<close>\n\ndefinition \"sign p = (if evenperm p then (1::int) else -1)\"\n\nlemma sign_nz: \"sign p \\<noteq> 0\"\n  by (simp add: sign_def)\n\nlemma sign_id: \"sign id = 1\"\n  by (simp add: sign_def)\n\nlemma sign_inverse: \"permutation p \\<Longrightarrow> sign (inv p) = sign p\"\n  by (simp add: sign_def evenperm_inv)\n\nlemma sign_compose: \"permutation p \\<Longrightarrow> permutation q \\<Longrightarrow> sign (p \\<circ> q) = sign p * sign q\"\n  by (simp add: sign_def evenperm_comp)\n\nlemma sign_swap_id: \"sign (Fun.swap a b id) = (if a = b then 1 else -1)\"\n  by (simp add: sign_def evenperm_swap)\n\nlemma sign_idempotent: \"sign p * sign p = 1\"\n  by (simp add: sign_def)\n\n\nsubsection \\<open>Permuting a list\\<close>\n\ntext \\<open>This function permutes a list by applying a permutation to the indices.\\<close>\n\ndefinition permute_list :: \"(nat \\<Rightarrow> nat) \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where\n  \"permute_list f xs = map (\\<lambda>i. xs ! (f i)) [0..<length xs]\"\n\nlemma permute_list_map:\n  assumes \"f permutes {..<length xs}\"\n  shows   \"permute_list f (map g xs) = map g (permute_list f xs)\"\n  using permutes_in_image[OF assms] by (auto simp: permute_list_def)\n\nlemma permute_list_nth:\n  assumes \"f permutes {..<length xs}\" \"i < length xs\"\n  shows   \"permute_list f xs ! i = xs ! f i\"\n  using permutes_in_image[OF assms(1)] assms(2)\n  by (simp add: permute_list_def)\n\nlemma permute_list_Nil [simp]: \"permute_list f [] = []\"\n  by (simp add: permute_list_def)\n\nlemma length_permute_list [simp]: \"length (permute_list f xs) = length xs\"\n  by (simp add: permute_list_def)\n\nlemma permute_list_compose:\n  assumes \"g permutes {..<length xs}\"\n  shows   \"permute_list (f \\<circ> g) xs = permute_list g (permute_list f xs)\"\n  using assms[THEN permutes_in_image] by (auto simp add: permute_list_def)\n\nlemma permute_list_ident [simp]: \"permute_list (\\<lambda>x. x) xs = xs\"\n  by (simp add: permute_list_def map_nth)\n\nlemma permute_list_id [simp]: \"permute_list id xs = xs\"\n  by (simp add: id_def)\n\nlemma mset_permute_list [simp]:\n  assumes \"f permutes {..<length (xs :: 'a list)}\"\n  shows   \"mset (permute_list f xs) = mset xs\"\nproof (rule multiset_eqI)\n  fix y :: 'a\n  from assms have [simp]: \"f x < length xs \\<longleftrightarrow> x < length xs\" for x\n    using permutes_in_image[OF assms] by auto\n  have \"count (mset (permute_list f xs)) y =\n          card ((\\<lambda>i. xs ! f i) -` {y} \\<inter> {..<length xs})\"\n    by (simp add: permute_list_def mset_map count_image_mset atLeast0LessThan)\n  also have \"(\\<lambda>i. xs ! f i) -` {y} \\<inter> {..<length xs} = f -` {i. i < length xs \\<and> y = xs ! i}\"\n    by auto\n  also from assms have \"card \\<dots> = card {i. i < length xs \\<and> y = xs ! i}\"\n    by (intro card_vimage_inj) (auto simp: permutes_inj permutes_surj)\n  also have \"\\<dots> = count (mset xs) y\" by (simp add: count_mset length_filter_conv_card)\n  finally show \"count (mset (permute_list f xs)) y = count (mset xs) y\" by simp\nqed\n\nlemma set_permute_list [simp]:\n  assumes \"f permutes {..<length xs}\"\n  shows   \"set (permute_list f xs) = set xs\"\n  by (rule mset_eq_setD[OF mset_permute_list]) fact\n\nlemma distinct_permute_list [simp]:\n  assumes \"f permutes {..<length xs}\"\n  shows   \"distinct (permute_list f xs) = distinct xs\"\n  by (simp add: distinct_count_atmost_1 assms)\n\nlemma permute_list_zip:\n  assumes \"f permutes A\" \"A = {..<length xs}\"\n  assumes [simp]: \"length xs = length ys\"\n  shows   \"permute_list f (zip xs ys) = zip (permute_list f xs) (permute_list f ys)\"\nproof -\n  from permutes_in_image[OF assms(1)] assms(2)\n    have [simp]: \"f i < length ys \\<longleftrightarrow> i < length ys\" for i by simp\n  have \"permute_list f (zip xs ys) = map (\\<lambda>i. zip xs ys ! f i) [0..<length ys]\"\n    by (simp_all add: permute_list_def zip_map_map)\n  also have \"\\<dots> = map (\\<lambda>(x, y). (xs ! f x, ys ! f y)) (zip [0..<length ys] [0..<length ys])\"\n    by (intro nth_equalityI) simp_all\n  also have \"\\<dots> = zip (permute_list f xs) (permute_list f ys)\"\n    by (simp_all add: permute_list_def zip_map_map)\n  finally show ?thesis .\nqed\n\nlemma map_of_permute:\n  assumes \"\\<sigma> permutes fst ` set xs\"\n  shows   \"map_of xs \\<circ> \\<sigma> = map_of (map (\\<lambda>(x,y). (inv \\<sigma> x, y)) xs)\" (is \"_ = map_of (map ?f _)\")\nproof\n  fix x\n  from assms have \"inj \\<sigma>\" \"surj \\<sigma>\" by (simp_all add: permutes_inj permutes_surj)\n  thus \"(map_of xs \\<circ> \\<sigma>) x = map_of (map ?f xs) x\"\n    by (induction xs) (auto simp: inv_f_f surj_f_inv_f)\nqed\n\n\nsubsection \\<open>More lemmas about permutations\\<close>\n\ntext \\<open>\n  The following few lemmas were contributed by Lukas Bulwahn.\n\\<close>\n\nlemma count_image_mset_eq_card_vimage:\n  assumes \"finite A\"\n  shows \"count (image_mset f (mset_set A)) b = card {a \\<in> A. f a = b}\"\n  using assms\nproof (induct A)\n  case empty\n  show ?case by simp\nnext\n  case (insert x F)\n  show ?case\n  proof cases\n    assume \"f x = b\"\n    from this have \"count (image_mset f (mset_set (insert x F))) b = Suc (card {a \\<in> F. f a = f x})\"\n      using insert.hyps by auto\n    also have \"\\<dots> = card (insert x {a \\<in> F. f a = f x})\"\n      using insert.hyps(1,2) by simp\n    also have \"card (insert x {a \\<in> F. f a = f x}) = card {a \\<in> insert x F. f a = b}\"\n      using \\<open>f x = b\\<close> by (auto intro: arg_cong[where f=\"card\"])\n    finally show ?thesis using insert by auto\n  next\n    assume A: \"f x \\<noteq> b\"\n    hence \"{a \\<in> F. f a = b} = {a \\<in> insert x F. f a = b}\" by auto\n    with insert A show ?thesis by simp\n  qed\nqed\n\n(* Prove image_mset_eq_implies_permutes *)\nlemma image_mset_eq_implies_permutes:\n  fixes f :: \"'a \\<Rightarrow> 'b\"\n  assumes \"finite A\"\n  assumes mset_eq: \"image_mset f (mset_set A) = image_mset f' (mset_set A)\"\n  obtains p where \"p permutes A\" and \"\\<forall>x\\<in>A. f x = f' (p x)\"\nproof -\n  from \\<open>finite A\\<close> have [simp]: \"finite {a \\<in> A. f a = (b::'b)}\" for f b by auto\n  have \"f ` A = f' ` A\"\n  proof -\n    have \"f ` A = f ` (set_mset (mset_set A))\" using \\<open>finite A\\<close> by simp\n    also have \"\\<dots> = f' ` (set_mset (mset_set A))\"\n      by (metis mset_eq multiset.set_map)\n    also have \"\\<dots> = f' ` A\" using \\<open>finite A\\<close> by simp\n    finally show ?thesis .\n  qed\n  have \"\\<forall>b\\<in>(f ` A). \\<exists>p. bij_betw p {a \\<in> A. f a = b} {a \\<in> A. f' a = b}\"\n  proof\n    fix b\n    from mset_eq have\n      \"count (image_mset f (mset_set A)) b = count (image_mset f' (mset_set A)) b\" by simp\n    from this  have \"card {a \\<in> A. f a = b} = card {a \\<in> A. f' a = b}\"\n      using \\<open>finite A\\<close>\n      by (simp add: count_image_mset_eq_card_vimage)\n    from this show \"\\<exists>p. bij_betw p {a\\<in>A. f a = b} {a \\<in> A. f' a = b}\"\n      by (intro finite_same_card_bij) simp_all\n  qed\n  hence \"\\<exists>p. \\<forall>b\\<in>f ` A. bij_betw (p b) {a \\<in> A. f a = b} {a \\<in> A. f' a = b}\"\n    by (rule bchoice)\n  then guess p .. note p = this\n  define p' where \"p' = (\\<lambda>a. if a \\<in> A then p (f a) a else a)\"\n  have \"p' permutes A\"\n  proof (rule bij_imp_permutes)\n    have \"disjoint_family_on (\\<lambda>i. {a \\<in> A. f' a = i}) (f ` A)\"\n      unfolding disjoint_family_on_def by auto\n    moreover have \"bij_betw (\\<lambda>a. p (f a) a) {a \\<in> A. f a = b} {a \\<in> A. f' a = b}\" if b: \"b \\<in> f ` A\" for b\n      using p b by (subst bij_betw_cong[where g=\"p b\"]) auto\n    ultimately have \"bij_betw (\\<lambda>a. p (f a) a) (\\<Union>b\\<in>f ` A. {a \\<in> A. f a = b}) (\\<Union>b\\<in>f ` A. {a \\<in> A. f' a = b})\"\n      by (rule bij_betw_UNION_disjoint)\n    moreover have \"(\\<Union>b\\<in>f ` A. {a \\<in> A. f a = b}) = A\" by auto\n    moreover have \"(\\<Union>b\\<in>f ` A. {a \\<in> A. f' a = b}) = A\" using \\<open>f ` A = f' ` A\\<close> by auto\n    ultimately show \"bij_betw p' A A\"\n      unfolding p'_def by (subst bij_betw_cong[where g=\"(\\<lambda>a. p (f a) a)\"]) auto\n  next\n    fix x\n    assume \"x \\<notin> A\"\n    from this show \"p' x = x\"\n      unfolding p'_def by simp\n  qed\n  moreover from p have \"\\<forall>x\\<in>A. f x = f' (p' x)\"\n    unfolding p'_def using bij_betwE by fastforce\n  ultimately show ?thesis by (rule that)\nqed\n\nlemma mset_set_upto_eq_mset_upto:\n  \"mset_set {..<n} = mset [0..<n]\"\n  by (induct n) (auto simp add: add.commute lessThan_Suc)\n\n(* and derive the existing property: *)\nlemma mset_eq_permutation:\n  assumes mset_eq: \"mset (xs::'a list) = mset ys\"\n  obtains p where \"p permutes {..<length ys}\" \"permute_list p ys = xs\"\nproof -\n  from mset_eq have length_eq: \"length xs = length ys\"\n    using mset_eq_length by blast\n  have \"mset_set {..<length ys} = mset [0..<length ys]\"\n    using mset_set_upto_eq_mset_upto by blast\n  from mset_eq length_eq this have\n    \"image_mset (\\<lambda>i. xs ! i) (mset_set {..<length ys}) = image_mset (\\<lambda>i. ys ! i) (mset_set {..<length ys})\"\n    by (metis map_nth mset_map)\n  from image_mset_eq_implies_permutes[OF _ this]\n    obtain p where \"p permutes {..<length ys}\"\n    and \"\\<forall>i\\<in>{..<length ys}. xs ! i = ys ! (p i)\" by auto\n  moreover from this length_eq have \"permute_list p ys = xs\"\n    by (auto intro!: nth_equalityI simp add: permute_list_nth)\n  ultimately show thesis using that by blast\nqed\n\nlemma permutes_natset_le:\n  fixes S :: \"'a::wellorder set\"\n  assumes p: \"p permutes S\"\n    and le: \"\\<forall>i \\<in> S. p i \\<le> i\"\n  shows \"p = id\"\nproof -\n  {\n    fix n\n    have \"p n = n\"\n      using p le\n    proof (induct n arbitrary: S rule: less_induct)\n      fix n S\n      assume H:\n        \"\\<And>m S. m < n \\<Longrightarrow> p permutes S \\<Longrightarrow> \\<forall>i\\<in>S. p i \\<le> i \\<Longrightarrow> p m = m\"\n        \"p permutes S\" \"\\<forall>i \\<in>S. p i \\<le> i\"\n      {\n        assume \"n \\<notin> S\"\n        with H(2) have \"p n = n\"\n          unfolding permutes_def by metis\n      }\n      moreover\n      {\n        assume ns: \"n \\<in> S\"\n        from H(3)  ns have \"p n < n \\<or> p n = n\"\n          by auto\n        moreover {\n          assume h: \"p n < n\"\n          from H h have \"p (p n) = p n\"\n            by metis\n          with permutes_inj[OF H(2)] have \"p n = n\"\n            unfolding inj_on_def by blast\n          with h have False\n            by simp\n        }\n        ultimately have \"p n = n\"\n          by blast\n      }\n      ultimately show \"p n = n\"\n        by blast\n    qed\n  }\n  then show ?thesis\n    by (auto simp add: fun_eq_iff)\nqed\n\nlemma permutes_natset_ge:\n  fixes S :: \"'a::wellorder set\"\n  assumes p: \"p permutes S\"\n    and le: \"\\<forall>i \\<in> S. p i \\<ge> i\"\n  shows \"p = id\"\nproof -\n  {\n    fix i\n    assume i: \"i \\<in> S\"\n    from i permutes_in_image[OF permutes_inv[OF p]] have \"inv p i \\<in> S\"\n      by simp\n    with le have \"p (inv p i) \\<ge> inv p i\"\n      by blast\n    with permutes_inverses[OF p] have \"i \\<ge> inv p i\"\n      by simp\n  }\n  then have th: \"\\<forall>i\\<in>S. inv p i \\<le> i\"\n    by blast\n  from permutes_natset_le[OF permutes_inv[OF p] th]\n  have \"inv p = inv id\"\n    by simp\n  then show ?thesis\n    apply (subst permutes_inv_inv[OF p, symmetric])\n    apply (rule inv_unique_comp)\n    apply simp_all\n    done\nqed\n\nlemma image_inverse_permutations: \"{inv p |p. p permutes S} = {p. p permutes S}\"\n  apply (rule set_eqI)\n  apply auto\n  using permutes_inv_inv permutes_inv\n  apply auto\n  apply (rule_tac x=\"inv x\" in exI)\n  apply auto\n  done\n\nlemma image_compose_permutations_left:\n  assumes q: \"q permutes S\"\n  shows \"{q \\<circ> p | p. p permutes S} = {p . p permutes S}\"\n  apply (rule set_eqI)\n  apply auto\n  apply (rule permutes_compose)\n  using q\n  apply auto\n  apply (rule_tac x = \"inv q \\<circ> x\" in exI)\n  apply (simp add: o_assoc permutes_inv permutes_compose permutes_inv_o)\n  done\n\nlemma image_compose_permutations_right:\n  assumes q: \"q permutes S\"\n  shows \"{p \\<circ> q | p. p permutes S} = {p . p permutes S}\"\n  apply (rule set_eqI)\n  apply auto\n  apply (rule permutes_compose)\n  using q\n  apply auto\n  apply (rule_tac x = \"x \\<circ> inv q\" in exI)\n  apply (simp add: o_assoc permutes_inv permutes_compose permutes_inv_o comp_assoc)\n  done\n\nlemma permutes_in_seg: \"p permutes {1 ..n} \\<Longrightarrow> i \\<in> {1..n} \\<Longrightarrow> 1 \\<le> p i \\<and> p i \\<le> n\"\n  by (simp add: permutes_def) metis\n\nlemma sum_permutations_inverse:\n  \"sum f {p. p permutes S} = sum (\\<lambda>p. f(inv p)) {p. p permutes S}\"\n  (is \"?lhs = ?rhs\")\nproof -\n  let ?S = \"{p . p permutes S}\"\n  have th0: \"inj_on inv ?S\"\n  proof (auto simp add: inj_on_def)\n    fix q r\n    assume q: \"q permutes S\"\n      and r: \"r permutes S\"\n      and qr: \"inv q = inv r\"\n    then have \"inv (inv q) = inv (inv r)\"\n      by simp\n    with permutes_inv_inv[OF q] permutes_inv_inv[OF r] show \"q = r\"\n      by metis\n  qed\n  have th1: \"inv ` ?S = ?S\"\n    using image_inverse_permutations by blast\n  have th2: \"?rhs = sum (f \\<circ> inv) ?S\"\n    by (simp add: o_def)\n  from sum.reindex[OF th0, of f] show ?thesis unfolding th1 th2 .\nqed\n\nlemma setum_permutations_compose_left:\n  assumes q: \"q permutes S\"\n  shows \"sum f {p. p permutes S} = sum (\\<lambda>p. f(q \\<circ> p)) {p. p permutes S}\"\n  (is \"?lhs = ?rhs\")\nproof -\n  let ?S = \"{p. p permutes S}\"\n  have th0: \"?rhs = sum (f \\<circ> (op \\<circ> q)) ?S\"\n    by (simp add: o_def)\n  have th1: \"inj_on (op \\<circ> q) ?S\"\n  proof (auto simp add: inj_on_def)\n    fix p r\n    assume \"p permutes S\"\n      and r: \"r permutes S\"\n      and rp: \"q \\<circ> p = q \\<circ> r\"\n    then have \"inv q \\<circ> q \\<circ> p = inv q \\<circ> q \\<circ> r\"\n      by (simp add: comp_assoc)\n    with permutes_inj[OF q, unfolded inj_iff] show \"p = r\"\n      by simp\n  qed\n  have th3: \"(op \\<circ> q) ` ?S = ?S\"\n    using image_compose_permutations_left[OF q] by auto\n  from sum.reindex[OF th1, of f] show ?thesis unfolding th0 th1 th3 .\nqed\n\nlemma sum_permutations_compose_right:\n  assumes q: \"q permutes S\"\n  shows \"sum f {p. p permutes S} = sum (\\<lambda>p. f(p \\<circ> q)) {p. p permutes S}\"\n  (is \"?lhs = ?rhs\")\nproof -\n  let ?S = \"{p. p permutes S}\"\n  have th0: \"?rhs = sum (f \\<circ> (\\<lambda>p. p \\<circ> q)) ?S\"\n    by (simp add: o_def)\n  have th1: \"inj_on (\\<lambda>p. p \\<circ> q) ?S\"\n  proof (auto simp add: inj_on_def)\n    fix p r\n    assume \"p permutes S\"\n      and r: \"r permutes S\"\n      and rp: \"p \\<circ> q = r \\<circ> q\"\n    then have \"p \\<circ> (q \\<circ> inv q) = r \\<circ> (q \\<circ> inv q)\"\n      by (simp add: o_assoc)\n    with permutes_surj[OF q, unfolded surj_iff] show \"p = r\"\n      by simp\n  qed\n  have th3: \"(\\<lambda>p. p \\<circ> q) ` ?S = ?S\"\n    using image_compose_permutations_right[OF q] by auto\n  from sum.reindex[OF th1, of f]\n  show ?thesis unfolding th0 th1 th3 .\nqed\n\n\nsubsection \\<open>Sum over a set of permutations (could generalize to iteration)\\<close>\n\nlemma sum_over_permutations_insert:\n  assumes fS: \"finite S\"\n    and aS: \"a \\<notin> S\"\n  shows \"sum f {p. p permutes (insert a S)} =\n    sum (\\<lambda>b. sum (\\<lambda>q. f (Fun.swap a b id \\<circ> q)) {p. p permutes S}) (insert a S)\"\nproof -\n  have th0: \"\\<And>f a b. (\\<lambda>(b,p). f (Fun.swap a b id \\<circ> p)) = f \\<circ> (\\<lambda>(b,p). Fun.swap a b id \\<circ> p)\"\n    by (simp add: fun_eq_iff)\n  have th1: \"\\<And>P Q. P \\<times> Q = {(a,b). a \\<in> P \\<and> b \\<in> Q}\"\n    by blast\n  have th2: \"\\<And>P Q. P \\<Longrightarrow> (P \\<Longrightarrow> Q) \\<Longrightarrow> P \\<and> Q\"\n    by blast\n  show ?thesis\n    unfolding permutes_insert\n    unfolding sum.cartesian_product\n    unfolding th1[symmetric]\n    unfolding th0\n  proof (rule sum.reindex)\n    let ?f = \"(\\<lambda>(b, y). Fun.swap a b id \\<circ> y)\"\n    let ?P = \"{p. p permutes S}\"\n    {\n      fix b c p q\n      assume b: \"b \\<in> insert a S\"\n      assume c: \"c \\<in> insert a S\"\n      assume p: \"p permutes S\"\n      assume q: \"q permutes S\"\n      assume eq: \"Fun.swap a b id \\<circ> p = Fun.swap a c id \\<circ> q\"\n      from p q aS have pa: \"p a = a\" and qa: \"q a = a\"\n        unfolding permutes_def by metis+\n      from eq have \"(Fun.swap a b id \\<circ> p) a  = (Fun.swap a c id \\<circ> q) a\"\n        by simp\n      then have bc: \"b = c\"\n        by (simp add: permutes_def pa qa o_def fun_upd_def Fun.swap_def id_def\n            cong del: if_weak_cong split: if_split_asm)\n      from eq[unfolded bc] have \"(\\<lambda>p. Fun.swap a c id \\<circ> p) (Fun.swap a c id \\<circ> p) =\n        (\\<lambda>p. Fun.swap a c id \\<circ> p) (Fun.swap a c id \\<circ> q)\" by simp\n      then have \"p = q\"\n        unfolding o_assoc swap_id_idempotent\n        by (simp add: o_def)\n      with bc have \"b = c \\<and> p = q\"\n        by blast\n    }\n    then show \"inj_on ?f (insert a S \\<times> ?P)\"\n      unfolding inj_on_def by clarify metis\n  qed\nqed\n\n\nsubsection \\<open>Constructing permutations from association lists\\<close>\n\ndefinition list_permutes where\n  \"list_permutes xs A \\<longleftrightarrow> set (map fst xs) \\<subseteq> A \\<and> set (map snd xs) = set (map fst xs) \\<and>\n     distinct (map fst xs) \\<and> distinct (map snd xs)\"\n\nlemma list_permutesI [simp]:\n  assumes \"set (map fst xs) \\<subseteq> A\" \"set (map snd xs) = set (map fst xs)\" \"distinct (map fst xs)\"\n  shows   \"list_permutes xs A\"\nproof -\n  from assms(2,3) have \"distinct (map snd xs)\"\n    by (intro card_distinct) (simp_all add: distinct_card del: set_map)\n  with assms show ?thesis by (simp add: list_permutes_def)\nqed\n\ndefinition permutation_of_list where\n  \"permutation_of_list xs x = (case map_of xs x of None \\<Rightarrow> x | Some y \\<Rightarrow> y)\"\n\nlemma permutation_of_list_Cons:\n  \"permutation_of_list ((x,y) # xs) x' = (if x = x' then y else permutation_of_list xs x')\"\n  by (simp add: permutation_of_list_def)\n\nfun inverse_permutation_of_list where\n  \"inverse_permutation_of_list [] x = x\"\n| \"inverse_permutation_of_list ((y,x')#xs) x =\n     (if x = x' then y else inverse_permutation_of_list xs x)\"\n\ndeclare inverse_permutation_of_list.simps [simp del]\n\nlemma inj_on_map_of:\n  assumes \"distinct (map snd xs)\"\n  shows   \"inj_on (map_of xs) (set (map fst xs))\"\nproof (rule inj_onI)\n  fix x y assume xy: \"x \\<in> set (map fst xs)\" \"y \\<in> set (map fst xs)\"\n  assume eq: \"map_of xs x = map_of xs y\"\n  from xy obtain x' y'\n    where x'y': \"map_of xs x = Some x'\" \"map_of xs y = Some y'\"\n    by (cases \"map_of xs x\"; cases \"map_of xs y\")\n       (simp_all add: map_of_eq_None_iff)\n  moreover from x'y' have *: \"(x,x') \\<in> set xs\" \"(y,y') \\<in> set xs\"\n    by (force dest: map_of_SomeD)+\n  moreover from * eq x'y' have \"x' = y'\" by simp\n  ultimately show \"x = y\" using assms\n    by (force simp: distinct_map dest: inj_onD[of _ _ \"(x,x')\" \"(y,y')\"])\nqed\n\nlemma inj_on_the: \"None \\<notin> A \\<Longrightarrow> inj_on the A\"\n  by (auto simp: inj_on_def option.the_def split: option.splits)\n\nlemma inj_on_map_of':\n  assumes \"distinct (map snd xs)\"\n  shows   \"inj_on (the \\<circ> map_of xs) (set (map fst xs))\"\n  by (intro comp_inj_on inj_on_map_of assms inj_on_the)\n     (force simp: eq_commute[of None] map_of_eq_None_iff)\n\nlemma image_map_of:\n  assumes \"distinct (map fst xs)\"\n  shows   \"map_of xs ` set (map fst xs) = Some ` set (map snd xs)\"\n  using assms by (auto simp: rev_image_eqI)\n\nlemma the_Some_image [simp]: \"the ` Some ` A = A\"\n  by (subst image_image) simp\n\nlemma image_map_of':\n  assumes \"distinct (map fst xs)\"\n  shows   \"(the \\<circ> map_of xs) ` set (map fst xs) = set (map snd xs)\"\n  by (simp only: image_comp [symmetric] image_map_of assms the_Some_image)\n\nlemma permutation_of_list_permutes [simp]:\n  assumes \"list_permutes xs A\"\n  shows   \"permutation_of_list xs permutes A\" (is \"?f permutes _\")\nproof (rule permutes_subset[OF bij_imp_permutes])\n  from assms show \"set (map fst xs) \\<subseteq> A\"\n    by (simp add: list_permutes_def)\n  from assms have \"inj_on (the \\<circ> map_of xs) (set (map fst xs))\" (is ?P)\n    by (intro inj_on_map_of') (simp_all add: list_permutes_def)\n  also have \"?P \\<longleftrightarrow> inj_on ?f (set (map fst xs))\"\n    by (intro inj_on_cong)\n       (auto simp: permutation_of_list_def map_of_eq_None_iff split: option.splits)\n  finally have \"bij_betw ?f (set (map fst xs)) (?f ` set (map fst xs))\"\n    by (rule inj_on_imp_bij_betw)\n  also from assms have \"?f ` set (map fst xs) = (the \\<circ> map_of xs) ` set (map fst xs)\"\n    by (intro image_cong refl)\n       (auto simp: permutation_of_list_def map_of_eq_None_iff split: option.splits)\n  also from assms have \"\\<dots> = set (map fst xs)\"\n    by (subst image_map_of') (simp_all add: list_permutes_def)\n  finally show \"bij_betw ?f (set (map fst xs)) (set (map fst xs))\" .\nqed (force simp: permutation_of_list_def dest!: map_of_SomeD split: option.splits)+\n\nlemma eval_permutation_of_list [simp]:\n  \"permutation_of_list [] x = x\"\n  \"x = x' \\<Longrightarrow> permutation_of_list ((x',y)#xs) x = y\"\n  \"x \\<noteq> x' \\<Longrightarrow> permutation_of_list ((x',y')#xs) x = permutation_of_list xs x\"\n  by (simp_all add: permutation_of_list_def)\n\nlemma eval_inverse_permutation_of_list [simp]:\n  \"inverse_permutation_of_list [] x = x\"\n  \"x = x' \\<Longrightarrow> inverse_permutation_of_list ((y,x')#xs) x = y\"\n  \"x \\<noteq> x' \\<Longrightarrow> inverse_permutation_of_list ((y',x')#xs) x = inverse_permutation_of_list xs x\"\n  by (simp_all add: inverse_permutation_of_list.simps)\n\nlemma permutation_of_list_id:\n  assumes \"x \\<notin> set (map fst xs)\"\n  shows   \"permutation_of_list xs x = x\"\n  using assms by (induction xs) (auto simp: permutation_of_list_Cons)\n\nlemma permutation_of_list_unique':\n  assumes \"distinct (map fst xs)\" \"(x, y) \\<in> set xs\"\n  shows   \"permutation_of_list xs x = y\"\n  using assms by (induction xs) (force simp: permutation_of_list_Cons)+\n\nlemma permutation_of_list_unique:\n  assumes \"list_permutes xs A\" \"(x,y) \\<in> set xs\"\n  shows   \"permutation_of_list xs x = y\"\n  using assms by (intro permutation_of_list_unique') (simp_all add: list_permutes_def)\n\nlemma inverse_permutation_of_list_id:\n  assumes \"x \\<notin> set (map snd xs)\"\n  shows   \"inverse_permutation_of_list xs x = x\"\n  using assms by (induction xs) auto\n\nlemma inverse_permutation_of_list_unique':\n  assumes \"distinct (map snd xs)\" \"(x, y) \\<in> set xs\"\n  shows   \"inverse_permutation_of_list xs y = x\"\n  using assms by (induction xs) (force simp: inverse_permutation_of_list.simps)+\n\nlemma inverse_permutation_of_list_unique:\n  assumes \"list_permutes xs A\" \"(x,y) \\<in> set xs\"\n  shows   \"inverse_permutation_of_list xs y = x\"\n  using assms by (intro inverse_permutation_of_list_unique') (simp_all add: list_permutes_def)\n\nlemma inverse_permutation_of_list_correct:\n  assumes \"list_permutes xs (A :: 'a set)\"\n  shows   \"inverse_permutation_of_list xs = inv (permutation_of_list xs)\"\nproof (rule ext, rule sym, subst permutes_inv_eq)\n  from assms show \"permutation_of_list xs permutes A\" by simp\nnext\n  fix x\n  show \"permutation_of_list xs (inverse_permutation_of_list xs x) = x\"\n  proof (cases \"x \\<in> set (map snd xs)\")\n    case True\n    then obtain y where \"(y, x) \\<in> set xs\" by force\n    with assms show ?thesis\n      by (simp add: inverse_permutation_of_list_unique permutation_of_list_unique)\n  qed (insert assms, auto simp: list_permutes_def\n         inverse_permutation_of_list_id permutation_of_list_id)\nqed\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/Permutations.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8596637433190939, "lm_q2_score": 0.8418256432832333, "lm_q1q2_score": 0.7236869837268686}}
{"text": "theory PALandWiseMenPuzzle2021_2Agents_New imports Main    (* Christoph Benzm\u00fcller and Sebastian Reiche, 2021 *)\n\nbegin\n (* Parameter settings for Nitpick *) nitpick_params[user_axioms=true, format=4, show_all]\n  \n typedecl i (* Type of possible worlds *)\n type_synonym \\<sigma> = \"i\\<Rightarrow>bool\" (* \\<D> *)\n type_synonym \\<tau> = \"\\<sigma>\\<Rightarrow>i\\<Rightarrow>bool\" (* Type of world depended formulas (truth sets) *) \n type_synonym \\<alpha> = \"i\\<Rightarrow>i\\<Rightarrow>bool\" (* Type of accessibility relations between world *)\n\n (* Some useful relations (for constraining accessibility relations) *)\n definition reflexive::\"\\<alpha>\\<Rightarrow>bool\" where \"reflexive R \\<equiv> \\<forall>x. R x x\"\n definition symmetric::\"\\<alpha>\\<Rightarrow>bool\" where \"symmetric R \\<equiv> \\<forall>x y. R x y \\<longrightarrow> R y x\"\n definition transitive::\"\\<alpha>\\<Rightarrow>bool\" where \"transitive R \\<equiv> \\<forall>x y z. R x y \\<and> R y z \\<longrightarrow> R x z\"\n definition euclidean::\"\\<alpha>\\<Rightarrow>bool\" where \"euclidean R \\<equiv> \\<forall>x y z. R x y \\<and> R x z \\<longrightarrow> R y z\"\n definition intersection_rel::\"\\<alpha>\\<Rightarrow>\\<alpha>\\<Rightarrow>\\<alpha>\" where \"intersection_rel R Q \\<equiv> \\<lambda>u v. R u v \\<and> Q u v\"\n definition union_rel::\"\\<alpha>\\<Rightarrow>\\<alpha>\\<Rightarrow>\\<alpha>\" where \"union_rel R Q \\<equiv> \\<lambda>u v. R u v \\<or> Q u v\"\n definition sub_rel::\"\\<alpha>\\<Rightarrow>\\<alpha>\\<Rightarrow>bool\" where \"sub_rel R Q \\<equiv> \\<forall>u v. R u v \\<longrightarrow> Q u v\"\n definition inverse_rel::\"\\<alpha>\\<Rightarrow>\\<alpha>\" where \"inverse_rel R \\<equiv> \\<lambda>u v. R v u\"\n definition bigunion_rel::\"(\\<alpha>\\<Rightarrow>bool)\\<Rightarrow>\\<alpha>\" (\"\\<^bold>\\<Union>_\") where \"\\<^bold>\\<Union> X \\<equiv> \\<lambda>u v. \\<exists>R. (X R) \\<and> (R u v)\"\n definition bigintersection_rel::\"(\\<alpha>\\<Rightarrow>bool)\\<Rightarrow>\\<alpha>\" (\"\\<^bold>\\<Inter>_\") where \"\\<^bold>\\<Inter> X \\<equiv> \\<lambda>u v. \\<forall>R. (X R) \\<longrightarrow> (R u v)\"\n\n (*In HOL the transitive closure of a relation can be defined in a single line.*)\n definition tc::\"\\<alpha>\\<Rightarrow>\\<alpha>\" where \"tc R \\<equiv> \\<lambda>x y.\\<forall>Q. transitive Q \\<longrightarrow> (sub_rel R Q \\<longrightarrow> Q x y)\"\n\n (* Lifted HOMML connectives for PAL *)\n abbreviation patom::\"\\<sigma>\\<Rightarrow>\\<tau>\" (\"\\<^sup>A_\"[79]80) where \"\\<^sup>Ap \\<equiv> \\<lambda>W w. W w \\<and> p w\"\n abbreviation ptop::\"\\<tau>\" (\"\\<^bold>\\<top>\") where \"\\<^bold>\\<top> \\<equiv> \\<lambda>W w. True\" \n abbreviation pneg::\"\\<tau>\\<Rightarrow>\\<tau>\" (\"\\<^bold>\\<not>_\"[52]53) where \"\\<^bold>\\<not>\\<phi> \\<equiv> \\<lambda>W w. \\<not>(\\<phi> W w)\" \n abbreviation pand::\"\\<tau>\\<Rightarrow>\\<tau>\\<Rightarrow>\\<tau>\" (infixr\"\\<^bold>\\<and>\"51) where \"\\<phi>\\<^bold>\\<and>\\<psi> \\<equiv> \\<lambda>W w. (\\<phi> W w) \\<and> (\\<psi> W w)\"   \n abbreviation por::\"\\<tau>\\<Rightarrow>\\<tau>\\<Rightarrow>\\<tau>\" (infixr\"\\<^bold>\\<or>\"50) where \"\\<phi>\\<^bold>\\<or>\\<psi> \\<equiv> \\<lambda>W w. (\\<phi> W w) \\<or> (\\<psi> W w)\"   \n abbreviation pimp::\"\\<tau>\\<Rightarrow>\\<tau>\\<Rightarrow>\\<tau>\" (infixr\"\\<^bold>\\<rightarrow>\"49) where \"\\<phi>\\<^bold>\\<rightarrow>\\<psi> \\<equiv> \\<lambda>W w. (\\<phi> W w) \\<longrightarrow> (\\<psi> W w)\"  \n abbreviation pequ::\"\\<tau>\\<Rightarrow>\\<tau>\\<Rightarrow>\\<tau>\" (infixr\"\\<^bold>\\<leftrightarrow>\"48) where \"\\<phi>\\<^bold>\\<leftrightarrow>\\<psi> \\<equiv> \\<lambda>W w. (\\<phi> W w) \\<longleftrightarrow> (\\<psi> W w)\"\n abbreviation pknow::\"\\<alpha>\\<Rightarrow>\\<tau>\\<Rightarrow>\\<tau>\" (\"\\<^bold>K_ _\") where \"\\<^bold>K r \\<phi> \\<equiv> \\<lambda>W w.\\<forall>v. (W v \\<and> r w v) \\<longrightarrow> (\\<phi> W v)\"\n abbreviation ppal::\"\\<tau>\\<Rightarrow>\\<tau>\\<Rightarrow>\\<tau>\" (\"\\<^bold>[\\<^bold>!_\\<^bold>]_\") where \"\\<^bold>[\\<^bold>!\\<phi>\\<^bold>]\\<psi> \\<equiv> \\<lambda>W w. (\\<phi> W w) \\<longrightarrow> (\\<psi> (\\<lambda>z. W z \\<and> \\<phi> W z) w)\"\n\n (* Validity of \\<tau>-type lifted PAL formulas *)\n abbreviation pvalid::\"\\<tau> \\<Rightarrow> bool\" (\"\\<^bold>\\<lfloor>_\\<^bold>\\<rfloor>\"[7]8) where \"\\<^bold>\\<lfloor>\\<phi>\\<^bold>\\<rfloor> \\<equiv> \\<forall>W.\\<forall>w. W w \\<longrightarrow> \\<phi> W w\"\n\n\n (* Agent Knowledge, Mutual Knowledge, Common Knowledge *)\n abbreviation  \"EVR A \\<equiv> \\<^bold>\\<Union> A\"\n abbreviation  \"DIS A \\<equiv> \\<^bold>\\<Inter> A\"\n abbreviation agttknows::\"\\<alpha>\\<Rightarrow>\\<tau>\\<Rightarrow>\\<tau>\" (\"\\<^bold>K\\<^sub>_ _\") where \"\\<^bold>K\\<^sub>r \\<phi> \\<equiv>  \\<^bold>K r \\<phi>\" \n abbreviation evrknows::\"(\\<alpha>\\<Rightarrow>bool)\\<Rightarrow>\\<tau>\\<Rightarrow>\\<tau>\" (\"\\<^bold>E\\<^sub>_ _\") where \"\\<^bold>E\\<^sub>A \\<phi> \\<equiv>  \\<^bold>K (EVR A) \\<phi>\"\n abbreviation prck::\"(\\<alpha>\\<Rightarrow>bool)\\<Rightarrow>\\<tau>\\<Rightarrow>\\<tau>\\<Rightarrow>\\<tau>\" (\"\\<^bold>C\\<^sub>_\\<^bold>\\<lparr>_\\<^bold>|_\\<^bold>\\<rparr>\")\n   where \"\\<^bold>C\\<^sub>A\\<^bold>\\<lparr>\\<phi>\\<^bold>|\\<psi>\\<^bold>\\<rparr> \\<equiv> \\<lambda>W w. \\<forall>v. \\<not>(tc (intersection_rel (EVR A) (\\<lambda>u v. W v \\<and> \\<phi> W v)) w v) \\<or> (\\<psi> W v)\"\n abbreviation pcmn::\"(\\<alpha>\\<Rightarrow>bool)\\<Rightarrow>\\<tau>\\<Rightarrow>\\<tau>\" (\"\\<^bold>C\\<^sub>_ _\") where \"\\<^bold>C\\<^sub>A \\<phi> \\<equiv>  \\<^bold>C\\<^sub>A\\<^bold>\\<lparr>\\<^bold>\\<top>\\<^bold>|\\<phi>\\<^bold>\\<rparr>\"\n abbreviation disknows :: \"(\\<alpha>\\<Rightarrow>bool)\\<Rightarrow>\\<tau>\\<Rightarrow>\\<tau>\" (\"\\<^bold>D\\<^sub>_ _\") where \"\\<^bold>D\\<^sub>A \\<phi> \\<equiv> \\<^bold>K (DIS A) \\<phi>\"\n\n (* Introducing \"Defs\" as the set of the above definitions; useful for convenient unfolding *)\n named_theorems Defs\n declare reflexive_def[Defs] symmetric_def[Defs] transitive_def[Defs] euclidean_def[Defs] \n   intersection_rel_def[Defs] union_rel_def[Defs] sub_rel_def[Defs] inverse_rel_def[Defs] \n   bigunion_rel_def[Defs] tc_def[Defs]\n\n\n (***********************************************************************************************)\n (*****                         Wise Men Puzzle                                             *****)\n (***********************************************************************************************)\n (*** Encoding of the wise men puzzle in PAL ***)\n (* Agents *)\n consts a::\"\\<alpha>\" b::\"\\<alpha>\" (* Agents modeled as accessibility relations *)\n abbreviation  Agent::\"\\<alpha>\\<Rightarrow>bool\" (\"\\<A>\") where \"\\<A> x \\<equiv> x = a \\<or> x = b\"\n axiomatization where  group_S5: \"S5Agents \\<A>\"\n\n (*** Encoding of the wise men puzzle in PAL ***)\n (* Common knowledge: At least one of a and b has a white spot *)\n consts ws::\"\\<alpha>\\<Rightarrow>\\<sigma>\" \n axiomatization where WM1: \"\\<^bold>\\<lfloor>\\<^bold>C\\<^sub>\\<A> (\\<^sup>Aws a \\<^bold>\\<or> \\<^sup>Aws b)\\<^bold>\\<rfloor>\" \n\n axiomatization where\n   (* Common knowledge: If x does not have a white spot then y know this *)\n   WM2ab: \"\\<^bold>\\<lfloor>\\<^bold>C\\<^sub>\\<A> (\\<^bold>\\<not>(\\<^sup>Aws a) \\<^bold>\\<rightarrow> (\\<^bold>K\\<^sub>b (\\<^bold>\\<not>(\\<^sup>Aws a))))\\<^bold>\\<rfloor>\" and\n   WM2ba: \"\\<^bold>\\<lfloor>\\<^bold>C\\<^sub>\\<A> (\\<^bold>\\<not>(\\<^sup>Aws b) \\<^bold>\\<rightarrow> (\\<^bold>K\\<^sub>a (\\<^bold>\\<not>(\\<^sup>Aws b))))\\<^bold>\\<rfloor>\" \n\n (* Automated solutions of the Wise Men Puzzle with 4 Agents*)\n\n theorem \"\\<^bold>\\<lfloor>\\<^bold>[\\<^bold>!\\<^bold>\\<not>\\<^bold>K\\<^sub>a(\\<^sup>Aws a)\\<^bold>](\\<^bold>K\\<^sub>b (\\<^sup>Aws b))\\<^bold>\\<rfloor>\" \n   using WM1 WM2ba unfolding Defs by (smt (verit))\n\n (* This one does not work yet *)\n theorem whitespot_c: \n     \"\\<^bold>\\<lfloor>\\<^bold>[\\<^bold>!\\<^bold>\\<not>((\\<^bold>K\\<^sub>a (\\<^sup>Aws a)) \\<^bold>\\<or> (\\<^bold>K\\<^sub>a (\\<^bold>\\<not>\\<^sup>Aws a)))\\<^bold>](\\<^bold>K\\<^sub>b (\\<^sup>Aws b))\\<^bold>\\<rfloor>\" \n   using WM1 WM2ba unfolding Defs by (smt (verit)) \n\n (* Consistency confirmed by nitpick *)\n lemma True nitpick [satisfy] oops  (* model found *)\n\nend", "meta": {"author": "cbenzmueller", "repo": "LogiKEy", "sha": "5c16bdeb68bf8131e24ba9c8d774d4af663cb2cf", "save_path": "github-repos/isabelle/cbenzmueller-LogiKEy", "path": "github-repos/isabelle/cbenzmueller-LogiKEy/LogiKEy-5c16bdeb68bf8131e24ba9c8d774d4af663cb2cf/Public-Announcement-Logic/PALandWiseMenPuzzle2021_2Agents_New.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361557147438, "lm_q2_score": 0.7931059487389968, "lm_q1q2_score": 0.7236585429419049}}
{"text": "section \\<open>Quadratic Irrationals\\<close>\ntheory Quadratic_Irrationals\nimports\n  Continued_Fractions\n  \"HOL-Computational_Algebra.Computational_Algebra\"\n  \"HOL-Library.Discrete\"\nbegin\n\nsubsection \\<open>Basic results on rationality of square roots\\<close>\n\nlemma inverse_in_Rats_iff [simp]: \"inverse (x :: real) \\<in> \\<rat> \\<longleftrightarrow> x \\<in> \\<rat>\"\n  by (auto simp: inverse_eq_divide divide_in_Rats_iff1)\n\nlemma nonneg_sqrt_nat_or_irrat:\n  assumes \"x ^ 2 = real a\" and \"x \\<ge> 0\"\n  shows   \"x \\<in> \\<nat> \\<or> x \\<notin> \\<rat>\"\nproof safe\n  assume \"x \\<notin> \\<nat>\" and \"x \\<in> \\<rat>\"\n  from Rats_abs_nat_div_natE[OF this(2)]\n    obtain p q :: nat where q_nz [simp]: \"q \\<noteq> 0\" and \"abs x = p / q\" and coprime: \"coprime p q\" .\n  with \\<open>x \\<ge> 0\\<close> have x: \"x = p / q\"\n      by simp\n  with assms have \"real (q ^ 2) * real a = real (p ^ 2)\"\n    by (simp add: field_simps)\n  also have \"real (q ^ 2) * real a = real (q ^ 2 * a)\"\n    by simp\n  finally have \"p ^ 2 = q ^ 2 * a\"\n    by (subst (asm) of_nat_eq_iff) auto\n  hence \"q ^ 2 dvd p ^ 2\"\n    by simp\n  hence \"q dvd p\"\n    by simp\n  with coprime have \"q = 1\"\n    by auto\n  with x and \\<open>x \\<notin> \\<nat>\\<close> show False\n    by simp\nqed\n\ntext \\<open>\n  A square root of a natural number is either an integer or irrational.\n\\<close>\ncorollary sqrt_nat_or_irrat:\n  assumes \"x ^ 2 = real a\"\n  shows   \"x \\<in> \\<int> \\<or> x \\<notin> \\<rat>\"\nproof (cases \"x \\<ge> 0\")\n  case True\n  with nonneg_sqrt_nat_or_irrat[OF assms this]\n    show ?thesis by (auto simp: Nats_altdef2)\nnext\n  case False\n  from assms have \"(-x) ^ 2 = real a\"\n    by simp\n  moreover from False have \"-x \\<ge> 0\"\n    by simp\n  ultimately have \"-x \\<in> \\<nat> \\<or> -x \\<notin> \\<rat>\"\n    by (rule nonneg_sqrt_nat_or_irrat)\n  thus ?thesis\n    by (auto simp: Nats_altdef2 minus_in_Ints_iff)\nqed\n\ncorollary sqrt_nat_or_irrat':\n  \"sqrt (real a) \\<in> \\<nat> \\<or> sqrt (real a) \\<notin> \\<rat>\"\n  using nonneg_sqrt_nat_or_irrat[of \"sqrt a\" a] by auto\n\ntext \\<open>\n  The square root of a natural number \\<open>n\\<close> is again a natural number iff \\<open>n is a perfect square.\\<close>\n\\<close>\ncorollary sqrt_nat_iff_is_square:\n  \"sqrt (real n) \\<in> \\<nat> \\<longleftrightarrow> is_square n\"\nproof\n  assume \"sqrt (real n) \\<in> \\<nat>\"\n  then obtain k where \"sqrt (real n) = real k\" by (auto elim!: Nats_cases)\n  hence \"sqrt (real n) ^ 2 = real (k ^ 2)\" by (simp only: of_nat_power)\n  also have \"sqrt (real n) ^ 2 = real n\" by simp\n  finally have \"n = k ^ 2\" by (simp only: of_nat_eq_iff)\n  thus \"is_square n\" by blast\nqed (auto elim!: is_nth_powerE)\n\ncorollary irrat_sqrt_nonsquare: \"\\<not>is_square n \\<Longrightarrow> sqrt (real n) \\<notin> \\<rat>\"\n  using sqrt_nat_or_irrat'[of n] by (auto simp: sqrt_nat_iff_is_square)\n\nlemma sqrt_of_nat_in_Rats_iff: \"sqrt (real n) \\<in> \\<rat> \\<longleftrightarrow> is_square n\"\n  using irrat_sqrt_nonsquare[of n] sqrt_nat_iff_is_square[of n] Nats_subset_Rats by blast\n\nlemma Discrete_sqrt_altdef: \"Discrete.sqrt n = nat \\<lfloor>sqrt n\\<rfloor>\"\nproof -\n  have \"real (Discrete.sqrt n ^ 2) \\<le> sqrt n ^ 2\"\n    by simp\n  hence \"Discrete.sqrt n \\<le> sqrt n\"\n    unfolding of_nat_power by (rule power2_le_imp_le) auto\n  moreover have \"real (Suc (Discrete.sqrt n) ^ 2) > real n\"\n    unfolding of_nat_less_iff by (rule Suc_sqrt_power2_gt)\n  hence \"real (Discrete.sqrt n + 1) ^ 2 > sqrt n ^ 2\"\n    unfolding of_nat_power by simp\n  hence \"real (Discrete.sqrt n + 1) > sqrt n\"\n    by (rule power2_less_imp_less) auto\n  hence \"Discrete.sqrt n + 1 > sqrt n\" by simp\n  ultimately show ?thesis by linarith\nqed\n\n\nsubsection \\<open>Quadratic irrationals\\<close>\n\ntext \\<open>\n  Irrational real numbers $x$ that satisfy a quadratic equation $a x^2 + b x + c = 0$\n  with \\<open>a\\<close>, \\<open>b\\<close>, \\<open>c\\<close> not all equal to 0 are called \\<^emph>\\<open>quadratic irrationals\\<close>. These are of the form\n  $p + q \\sqrt{d}$ for rational numbers \\<open>p\\<close>, \\<open>q\\<close> and a positive integer \\<open>d\\<close>.\n\\<close>\ninductive quadratic_irrational :: \"real \\<Rightarrow> bool\" where\n  \"x \\<notin> \\<rat> \\<Longrightarrow> real_of_int a * x ^ 2 + real_of_int b * x + real_of_int c = 0 \\<Longrightarrow>\n     a \\<noteq> 0 \\<or> b \\<noteq> 0 \\<or> c \\<noteq> 0 \\<Longrightarrow> quadratic_irrational x\"\n\nlemma quadratic_irrational_sqrt [intro]:\n  assumes \"\\<not>is_square n\"\n  shows   \"quadratic_irrational (sqrt (real n))\"\n  using irrat_sqrt_nonsquare[OF assms]\n  by (intro quadratic_irrational.intros[of \"sqrt n\" 1 0 \"-int n\"]) auto\n\nlemma quadratic_irrational_uminus [intro]:\n  assumes \"quadratic_irrational x\"\n  shows   \"quadratic_irrational (-x)\"\n  using assms\nproof induction\n  case (1 x a b c)\n  thus ?case by (intro quadratic_irrational.intros[of \"-x\" a \"-b\" c]) auto\nqed\n\nlemma quadratic_irrational_uminus_iff [simp]:\n  \"quadratic_irrational (-x) \\<longleftrightarrow> quadratic_irrational x\"\n  using quadratic_irrational_uminus[of x] quadratic_irrational_uminus[of \"-x\"] by auto\n\nlemma quadratic_irrational_plus_int [intro]:\n  assumes \"quadratic_irrational x\"\n  shows   \"quadratic_irrational (x + of_int n)\"\n  using assms\nproof induction\n  case (1 x a b c)\n  define x' where \"x' = x + of_int n\"\n  define a' b' c' where\n     \"a' = a\" and \"b' = b - 2 * of_int n * a\" and\n     \"c' = a * of_int n ^ 2 - b * of_int n + c\"\n  from 1 have \"0 = a * (x' - of_int n) ^ 2 + b * (x' - of_int n) + c\"\n    by (simp add: x'_def)\n  also have \"\\<dots> = a' * x' ^ 2 + b' * x' + c'\"\n    by (simp add: algebra_simps a'_def b'_def c'_def power2_eq_square)\n  finally have \"\\<dots> = 0\" ..\n  moreover have \"x' \\<notin> \\<rat>\"\n    using 1 by (auto simp: x'_def add_in_Rats_iff2)\n  moreover have \"a' \\<noteq> 0 \\<or> b' \\<noteq> 0 \\<or> c' \\<noteq> 0\"\n    using 1 by (auto simp: a'_def b'_def c'_def)\n  ultimately show ?case\n    by (intro quadratic_irrational.intros[of \"x + of_int n\" a' b' c']) (auto simp: x'_def)\nqed\n\nlemma quadratic_irrational_plus_int_iff [simp]:\n  \"quadratic_irrational (x + of_int n) \\<longleftrightarrow> quadratic_irrational x\"\n  using quadratic_irrational_plus_int[of x n]\n        quadratic_irrational_plus_int[of \"x + of_int n\" \"-n\"] by auto\n\nlemma quadratic_irrational_minus_int_iff [simp]:\n  \"quadratic_irrational (x - of_int n) \\<longleftrightarrow> quadratic_irrational x\"\n  using quadratic_irrational_plus_int_iff[of x \"-n\"]\n  by (simp del: quadratic_irrational_plus_int_iff)\n\nlemma quadratic_irrational_plus_nat_iff [simp]:\n  \"quadratic_irrational (x + of_nat n) \\<longleftrightarrow> quadratic_irrational x\"\n  using quadratic_irrational_plus_int_iff[of x \"int n\"]\n  by (simp del: quadratic_irrational_plus_int_iff)\n\nlemma quadratic_irrational_minus_nat_iff [simp]:\n  \"quadratic_irrational (x - of_nat n) \\<longleftrightarrow> quadratic_irrational x\"\n  using quadratic_irrational_plus_int_iff[of x \"-int n\"]\n  by (simp del: quadratic_irrational_plus_int_iff)\n\nlemma quadratic_irrational_plus_1_iff [simp]:\n  \"quadratic_irrational (x + 1) \\<longleftrightarrow> quadratic_irrational x\"\n  using quadratic_irrational_plus_int_iff[of x 1]\n  by (simp del: quadratic_irrational_plus_int_iff)\n\nlemma quadratic_irrational_minus_1_iff [simp]:\n  \"quadratic_irrational (x - 1) \\<longleftrightarrow> quadratic_irrational x\"\n  using quadratic_irrational_plus_int_iff[of x \"-1\"]\n  by (simp del: quadratic_irrational_plus_int_iff)\n\nlemma quadratic_irrational_plus_numeral_iff [simp]:\n  \"quadratic_irrational (x + numeral n) \\<longleftrightarrow> quadratic_irrational x\"\n  using quadratic_irrational_plus_int_iff[of x \"numeral n\"]\n  by (simp del: quadratic_irrational_plus_int_iff)\n\nlemma quadratic_irrational_minus_numeral_iff [simp]:\n  \"quadratic_irrational (x - numeral n) \\<longleftrightarrow> quadratic_irrational x\"\n  using quadratic_irrational_plus_int_iff[of x \"-numeral n\"]\n  by (simp del: quadratic_irrational_plus_int_iff)\n\nlemma quadratic_irrational_inverse:\n  assumes \"quadratic_irrational x\"\n  shows   \"quadratic_irrational (inverse x)\"\n  using assms\nproof induction\n  case (1 x a b c)\n  from 1 have \"x \\<noteq> 0\" by auto\n  have \"0 = (real_of_int a * x\\<^sup>2 + real_of_int b * x + real_of_int c) / x ^ 2\"\n    by (subst 1) simp\n  also have \"\\<dots> = real_of_int c * (inverse x) ^ 2 + real_of_int b * inverse x + real_of_int a\"\n    using \\<open>x \\<noteq> 0\\<close> by (simp add: field_simps power2_eq_square)\n  finally have \"\\<dots> = 0\" ..\n  thus ?case using 1\n    by (intro quadratic_irrational.intros[of \"inverse x\" c b a]) auto\nqed\n\nlemma quadratic_irrational_inverse_iff [simp]:\n  \"quadratic_irrational (inverse x) \\<longleftrightarrow> quadratic_irrational x\"\n  using quadratic_irrational_inverse[of x] quadratic_irrational_inverse[of \"inverse x\"]\n  by (cases \"x = 0\") auto\n\nlemma quadratic_irrational_cfrac_remainder_iff:\n  \"quadratic_irrational (cfrac_remainder c n) \\<longleftrightarrow> quadratic_irrational (cfrac_lim c)\"\nproof (cases \"cfrac_length c = \\<infinity>\")\n  case False\n  thus ?thesis\n    by (auto simp: quadratic_irrational.simps)\nnext\n  case [simp]: True\n  show ?thesis\n  proof (induction n)\n    case (Suc n)\n    from Suc.prems have \"cfrac_remainder c (Suc n) =\n                           inverse (cfrac_remainder c n - of_int (cfrac_nth c n))\"\n      by (subst cfrac_remainder_Suc) (auto simp: field_simps)\n    also have \"quadratic_irrational \\<dots> \\<longleftrightarrow> quadratic_irrational (cfrac_remainder c n)\"\n      by simp\n    also have \"\\<dots> \\<longleftrightarrow> quadratic_irrational (cfrac_lim c)\"\n      by (rule Suc.IH)\n    finally show ?case .\n  qed auto\nqed\n                \nsubsection \\<open>Real solutions of quadratic equations\\<close>\n\ntext \\<open>\n  For the next result, we need some basic properties of real solutions to quadratic equations.\n\\<close>\nlemma quadratic_equation_reals_cases:\n  fixes a b c :: real\n  defines \"f \\<equiv> (\\<lambda>x. a * x ^ 2 + b * x + c)\"\n  defines \"discr \\<equiv> (b^2 - 4 * a * c)\"\n  shows   \"{x. f x = 0} =\n             (if a = 0 then\n                (if b = 0 then if c = 0 then UNIV else {} else {-c/b})\n              else if discr \\<ge> 0 then {(-b + sqrt discr) / (2 * a), (-b - sqrt discr) / (2 * a)}\n                                else {})\" (is ?th1)                \nproof (cases \"a = 0\")\n  case [simp]: True\n  show ?th1\n  proof (cases \"b = 0\")\n    case [simp]: True\n    hence \"{x. f x = 0} = (if c = 0 then UNIV else {})\"\n      by (auto simp: f_def)\n    thus ?th1 by simp\n  next\n    case False\n    hence \"{x. f x = 0} = {-c / b}\" by (auto simp: f_def field_simps)\n    thus ?th1 using False by simp\n  qed\nnext\n  case [simp]: False\n  show ?th1\n  proof (cases \"discr \\<ge> 0\")\n    case True\n    {\n      fix x :: real\n      have \"f x = a * (x - (-b + sqrt discr) / (2 * a)) * (x - (-b - sqrt discr) / (2 * a))\"\n        using True by (simp add: f_def field_simps discr_def power2_eq_square)\n      also have \"\\<dots> = 0 \\<longleftrightarrow> x \\<in> {(-b + sqrt discr) / (2 * a), (-b - sqrt discr) / (2 * a)}\"\n        by simp\n      finally have \"f x = 0 \\<longleftrightarrow> \\<dots>\" .\n    }\n    hence \"{x. f x = 0} = {(-b + sqrt discr) / (2 * a), (-b - sqrt discr) / (2 * a)}\"\n      by blast\n    thus ?th1 using True by simp\n  next\n    case False\n    {\n      fix x :: real\n      assume x: \"f x = 0\"\n      have \"0 \\<le> (x + b / (2 * a)) ^ 2\" by simp\n      also have \"f x = a * ((x + b / (2 * a)) ^ 2 - b ^ 2 / (4 * a ^ 2) + c / a)\"\n        by (simp add: field_simps power2_eq_square f_def)\n      with x have \"(x + b / (2 * a)) ^ 2 - b ^ 2 / (4 * a ^ 2) + c / a = 0\"\n        by simp\n      hence \"(x + b / (2 * a)) ^ 2 = b ^ 2 / (4 * a ^ 2) - c / a\"\n        by (simp add: algebra_simps)\n      finally have \"0 \\<le> (b\\<^sup>2 / (4 * a\\<^sup>2) - c / a) * (4 * a\\<^sup>2)\"\n        by (intro mult_nonneg_nonneg) auto\n      also have \"\\<dots> = b\\<^sup>2 - 4 * a * c\" by (simp add: field_simps power2_eq_square)\n      also have \"\\<dots> < 0\" using False by (simp add: discr_def)\n      finally have False by simp\n    }\n    hence \"{x. f x = 0} = {}\" by auto\n    thus ?th1 using False by simp\n  qed\nqed\n\nlemma finite_quadratic_equation_solutions_reals:\n  fixes a b c :: real\n  defines \"discr \\<equiv> (b^2 - 4 * a * c)\"\n  shows   \"finite {x. a * x ^ 2 + b * x + c = 0} \\<longleftrightarrow> a \\<noteq> 0 \\<or> b \\<noteq> 0 \\<or> c \\<noteq> 0\"\n  by (subst quadratic_equation_reals_cases)\n     (auto simp: discr_def card_eq_0_iff infinite_UNIV_char_0 split: if_split)\n\nlemma card_quadratic_equation_solutions_reals:\n  fixes a b c :: real\n  defines \"discr \\<equiv> (b^2 - 4 * a * c)\"\n  shows   \"card {x. a * x ^ 2 + b * x + c = 0} =\n             (if a = 0 then\n                (if b = 0 then 0 else 1)\n              else if discr \\<ge> 0 then if discr = 0 then 1 else 2 else 0)\" (is ?th1)                \n  by (subst quadratic_equation_reals_cases)\n     (auto simp: discr_def card_eq_0_iff infinite_UNIV_char_0 split: if_split)\n\nlemma card_quadratic_equation_solutions_reals_le_2:\n  \"card {x :: real. a * x ^ 2 + b * x + c = 0} \\<le> 2\"\n  by (subst card_quadratic_equation_solutions_reals) auto\n\nlemma quadratic_equation_solution_rat_iff:\n  fixes a b c :: int and x y :: real\n  defines \"f \\<equiv> (\\<lambda>x::real. a * x ^ 2 + b * x + c)\"\n  defines \"discr \\<equiv> nat (b ^ 2 - 4 * a * c)\"\n  assumes \"a \\<noteq> 0\" \"f x = 0\"\n  shows   \"x \\<in> \\<rat> \\<longleftrightarrow> is_square discr\"\nproof -\n  define discr' where \"discr' \\<equiv> real_of_int (b ^ 2 - 4 * a * c)\"\n  from assms have \"x \\<in> {x. f x = 0}\" by simp\n  with \\<open>a \\<noteq> 0\\<close> have \"discr' \\<ge> 0\" unfolding discr'_def f_def of_nat_diff\n    by (subst (asm) quadratic_equation_reals_cases) (auto simp: discr_def split: if_splits)\n  hence *: \"sqrt (discr') = sqrt (real discr)\" unfolding of_int_0_le_iff discr_def discr'_def\n    by (simp add: algebra_simps nat_diff_distrib)\n  from \\<open>x \\<in> {x. f x = 0}\\<close> have \"x = (-b + sqrt discr) / (2 * a) \\<or> x = (-b - sqrt discr) / (2 * a)\"\n    using \\<open>a \\<noteq> 0\\<close> * unfolding discr'_def f_def\n    by (subst (asm) quadratic_equation_reals_cases) (auto split: if_splits)\n  thus ?thesis using \\<open>a \\<noteq> 0\\<close>\n    by (auto simp: sqrt_of_nat_in_Rats_iff divide_in_Rats_iff2 diff_in_Rats_iff2 diff_in_Rats_iff1)\nqed\n\n\nsubsection \\<open>Periodic continued fractions and quadratic irrationals\\<close>\n\ntext \\<open>\n  We now show the main result: A positive irrational number has a periodic continued \n  fraction expansion iff it is a quadratic irrational.\n\n  In principle, this statement naturally also holds for negative numbers, but the current \n  formalisation of continued fractions only supports non-negative numbers. It also holds for\n  rational numbers in some sense, since their continued fraction expansion is finite to begin with.\n\\<close>\ntheorem periodic_cfrac_imp_quadratic_irrational:\n  assumes [simp]: \"cfrac_length c = \\<infinity>\"\n      and period: \"l > 0\" \"\\<And>k. k \\<ge> N \\<Longrightarrow> cfrac_nth c (k + l) = cfrac_nth c k\"\n  shows   \"quadratic_irrational (cfrac_lim c)\"\nproof -\n  define h' and k' where \"h' = conv_num_int (cfrac_drop N c)\" \n                     and \"k' = conv_denom_int (cfrac_drop N c)\"\n  define x' where \"x' = cfrac_remainder c N\"\n\n  have c_pos: \"cfrac_nth c n > 0\" if \"n \\<ge> N\" for n\n  proof -\n    from assms(1,2) have \"cfrac_nth c (n + l) > 0\" by auto\n    with assms(3)[OF that] show ?thesis by simp\n  qed\n  have k'_pos: \"k' n > 0\" if \"n \\<noteq> -1\" \"n \\<ge> -2\" for n\n    using that by (auto simp: k'_def conv_denom_int_def intro!: conv_denom_pos)\n  have k'_nonneg: \"k' n \\<ge> 0\" if \"n \\<ge> -2\" for n\n    using that by (auto simp: k'_def conv_denom_int_def intro!: conv_denom_pos)\n  have \"cfrac_nth c (n + (N + l)) = cfrac_nth c (n + N)\" for n\n    using period(2)[of \"n + N\"] by (simp add: add_ac)\n  have \"cfrac_drop (N + l) c = cfrac_drop N c\"\n    by (rule cfrac_eqI) (use period(2)[of \"n + N\" for n] in \\<open>auto simp: algebra_simps\\<close>)\n  hence x'_altdef: \"x' = cfrac_remainder c (N + l)\"\n    by (simp add: x'_def cfrac_remainder_def)\n  have x'_pos: \"x' > 0\" unfolding x'_def\n    using c_pos by (intro cfrac_remainder_pos) auto\n\n  define A where \"A = (k' (int l - 1))\"\n  define B where \"B = k' (int l - 2) - h' (int l - 1)\"\n  define C where \"C = -(h' (int l - 2))\"\n\n  have pos: \"(k' (int l - 1) * x' + k' (int l - 2)) > 0\"\n    using x'_pos \\<open>l > 0\\<close>\n    by (intro add_pos_nonneg mult_pos_pos) (auto intro!: k'_pos k'_nonneg)\n  have \"x' = conv' (cfrac_drop N c) l x'\"\n    apply (subst x'_def, subst x'_altdef, subst add.commute)\n    apply (simp add: cfrac_remainder_def cfrac_drop_add conv'_cfrac_remainder)\n    apply (subst (2) cfrac_remainder_def [symmetric])\n    apply (subst conv'_cfrac_remainder)\n     apply auto\n    done\n  also have \"\\<dots> = (h' (int l - 1) * x' + h' (int l - 2)) / (k' (int l - 1) * x' + k' (int l - 2))\"\n    using conv'_num_denom_int[OF x'_pos, of _ l] unfolding h'_def k'_def\n    by (simp add: mult_ac)\n  finally have \"x' * (k' (int l - 1) * x' + k' (int l - 2)) = (h' (int l - 1) * x' + h' (int l - 2))\"\n    using pos by (simp add: divide_simps)\n  hence quadratic: \"A * x' ^ 2 + B * x' + C = 0\"\n    by (simp add: algebra_simps power2_eq_square A_def B_def C_def)\n  moreover have \"x' \\<notin> \\<rat>\" unfolding x'_def\n    by auto\n  moreover have \"A > 0\" using \\<open>l > 0\\<close> by (auto simp: A_def intro!: k'_pos)\n  ultimately have \"quadratic_irrational x'\" using \\<open>x' \\<notin> \\<rat>\\<close>\n    by (intro quadratic_irrational.intros[of x' A B C]) simp_all\n  thus ?thesis\n    using assms by (simp add: x'_def quadratic_irrational_cfrac_remainder_iff)\nqed\n\ntheorem quadratic_irrational_imp_periodic_cfrac:\n  assumes \"quadratic_irrational (cfrac_lim e)\"\n  obtains N l where \"l > 0\" and \"\\<And>n m. n \\<ge> N \\<Longrightarrow> cfrac_nth e (n + m * l) = cfrac_nth e n\"\n                and \"cfrac_remainder e (N + l) = cfrac_remainder e N\"\nproof -\n  have [simp]: \"cfrac_length e = \\<infinity>\"\n    using assms by (auto simp: quadratic_irrational.simps)\n  note [intro] = assms(1)\n  define x where \"x = cfrac_lim e\"\n  from assms obtain a b c :: int where\n    nontrivial: \"a \\<noteq> 0 \\<or> b \\<noteq> 0 \\<or> c \\<noteq> 0\" and\n          root: \"a * x^2 + b * x + c = 0\" (is \"?f x = 0\")\n    by (auto simp: quadratic_irrational.simps x_def)\n\n  define f where \"f = ?f\"\n  define h and k where \"h = conv_num e\" and \"k = conv_denom e\"\n  define X where \"X = cfrac_remainder e\"\n  have [simp]: \"k i > 0\" \"k i \\<noteq> 0\" for i\n    using conv_denom_pos[of e i] by (auto simp: k_def)\n  have k_leI: \"k i \\<le> k j\" if \"i \\<le> j\" for i j\n    by (auto simp: k_def intro!: conv_denom_leI that)\n  have k_nonneg: \"k n \\<ge> 0\" for n\n    by (auto simp: k_def)\n  have k_ge_1: \"k n \\<ge> 1\" for n\n    using k_leI[of 0 n] by (simp add: k_def)\n    \n  define R where \"R = conv e\"\n  define A where \"A = (\\<lambda>n. a * h (n - 1) ^ 2 + b * h (n - 1) * k (n - 1) + c * k (n - 1) ^ 2)\"\n  define B where \"B = (\\<lambda>n. 2 * a * h (n - 1) * h (n - 2) + b * (h (n - 1) * k (n - 2) + h (n - 2) * k (n - 1)) + 2 * c * k (n - 1) * k (n - 2))\"\n  define C where \"C = (\\<lambda>n. a * h (n - 2) ^ 2 + b * h (n - 2) * k (n - 2) + c * k (n - 2) ^ 2)\"\n\n  define A' where \"A' = nat \\<lfloor>2 * \\<bar>a\\<bar> * \\<bar>x\\<bar> + \\<bar>a\\<bar> + \\<bar>b\\<bar>\\<rfloor>\"\n  define B' where \"B' = nat \\<lfloor>(3 / 2) * (2 * \\<bar>a\\<bar> * \\<bar>x\\<bar> + \\<bar>b\\<bar>) + 9 / 4 * \\<bar>a\\<bar>\\<rfloor>\"\n\n  have [simp]: \"X n \\<notin> \\<rat>\" for n unfolding X_def\n    by simp\n  from this[of 0] have [simp]: \"x \\<notin> \\<rat>\"\n    unfolding X_def by (simp add: x_def)\n\n  have \"a \\<noteq> 0\"\n  proof\n    assume \"a = 0\"\n    with root and nontrivial have \"x = 0 \\<or> x = -c / b\"\n      by (auto simp: divide_simps add_eq_0_iff)\n    hence \"x \\<in> \\<rat>\" by (auto simp del: \\<open>x \\<notin> \\<rat>\\<close>)\n    thus False by simp\n  qed\n\n  have bounds: \"(A n, B n, C n) \\<in> {-A'..A'} \\<times> {-B'..B'} \\<times> {-A'..A'}\"\n   and X_root: \"A n * X n ^ 2 + B n * X n + C n = 0\" if n: \"n \\<ge> 2\" for n\n  proof -\n    define n' where \"n' = n - 2\"\n    have n': \"n = Suc (Suc n')\" using \\<open>n \\<ge> 2\\<close> unfolding n'_def by simp\n    have *: \"of_int (k (n - Suc 0)) * X n + of_int (k (n - 2)) \\<noteq> 0\"\n    proof\n      assume \"of_int (k (n - Suc 0)) * X n + of_int (k (n - 2)) = 0\"\n      hence \"X n = -k (n - 2) / k (n - 1)\" by (auto simp: divide_simps mult_ac)\n      also have \"\\<dots> \\<in> \\<rat>\" by auto\n      finally show False by simp\n    qed\n  \n    let ?denom = \"(k (n - 1) * X n + k (n - 2))\"\n    have \"0 = 0 * ?denom ^ 2\" by simp\n    also have \"0 * ?denom ^ 2 = (a * x ^ 2 + b * x + c) * ?denom ^ 2\" using root by simp\n    also have \"\\<dots> = a * (x * ?denom) ^ 2 + b * ?denom * (x * ?denom) + c * ?denom * ?denom\"\n      by (simp add: algebra_simps power2_eq_square)\n    also have \"x * ?denom = h (n - 1) * X n + h (n - 2)\"\n      using cfrac_lim_eq_num_denom_remainder_aux[of \"n - 2\" e] \\<open>n \\<ge> 2\\<close>\n      by (simp add: numeral_2_eq_2 Suc_diff_Suc x_def k_def h_def X_def)\n    also have \"a * \\<dots> ^ 2 + b * ?denom * \\<dots> + c * ?denom * ?denom = A n * X n ^ 2 + B n * X n + C n\"\n      by (simp add: A_def B_def C_def power2_eq_square algebra_simps)\n    finally show \"A n * X n ^ 2 + B n * X n + C n = 0\" ..\n  \n    have f_abs_bound: \"\\<bar>f (R n)\\<bar> \\<le> (2 * \\<bar>a\\<bar> * \\<bar>x\\<bar> + \\<bar>b\\<bar>) * (1 / (k n * k (Suc n))) +\n                                      \\<bar>a\\<bar> * (1 / (k n * k (Suc n))) ^ 2\" for n\n    proof -\n      have \"\\<bar>f (R n)\\<bar> = \\<bar>?f (R n) - ?f x\\<bar>\" by (simp add: root f_def)\n      also have \"?f (R n) - ?f x = (R n - x) * (2 * a * x + b) + (R n - x) ^ 2 * a\"\n        by (simp add: power2_eq_square algebra_simps)\n      also have \"\\<bar>\\<dots>\\<bar> \\<le> \\<bar>(R n - x) * (2 * a * x + b)\\<bar> + \\<bar>(R n - x) ^ 2 * a\\<bar>\"\n        by (rule abs_triangle_ineq)\n      also have \"\\<dots> = \\<bar>2 * a * x + b\\<bar> * \\<bar>R n - x\\<bar> + \\<bar>a\\<bar> * \\<bar>R n - x\\<bar> ^ 2\"\n        by (simp add: abs_mult)\n      also have \"\\<dots> \\<le> \\<bar>2 * a * x + b\\<bar> * (1 / (k n * k (Suc n))) + \\<bar>a\\<bar> * (1 / (k n * k (Suc n))) ^ 2\"\n        unfolding x_def R_def using cfrac_lim_minus_conv_bounds[of n e]\n        by (intro add_mono mult_left_mono power_mono) (auto simp: k_def)\n      also have \"\\<bar>2 * a * x + b\\<bar> \\<le> 2 * \\<bar>a\\<bar> * \\<bar>x\\<bar> + \\<bar>b\\<bar>\"\n        by (rule order.trans[OF abs_triangle_ineq]) (auto simp: abs_mult)\n      hence \"\\<bar>2 * a * x + b\\<bar> * (1 / (k n * k (Suc n))) + \\<bar>a\\<bar> * (1 / (k n * k (Suc n))) ^ 2 \\<le>\n               \\<dots> * (1 / (k n * k (Suc n))) + \\<bar>a\\<bar> * (1 / (k n * k (Suc n))) ^ 2\"\n        by (intro add_mono mult_right_mono) (auto intro!: mult_nonneg_nonneg k_nonneg)\n      finally show \"\\<bar>f (R n)\\<bar> \\<le> \\<dots>\"\n        by (simp add: mult_right_mono add_mono divide_left_mono)\n    qed\n  \n    have h_eq_conv_k: \"h i = R i * k i\" for i\n      using conv_denom_pos[of e i] unfolding R_def\n      by (subst conv_num_denom) (auto simp: h_def k_def)\n  \n    have \"A n = k (n - 1) ^ 2 * f (R (n - 1))\" for n\n      by (simp add: algebra_simps A_def n' k_def power2_eq_square h_eq_conv_k f_def)\n    have A_bound: \"\\<bar>A i\\<bar> \\<le> A'\" if \"i > 0\" for i\n    proof -\n      have \"k i > 0\"\n        by simp\n      hence \"k i \\<ge> 1\"\n        by linarith\n      have \"A i = k (i - 1) ^ 2 * f (R (i - 1))\"\n        by (simp add: algebra_simps A_def k_def power2_eq_square h_eq_conv_k f_def)\n      also have \"\\<bar>\\<dots>\\<bar> = k (i - 1) ^ 2 * \\<bar>f (R (i - 1))\\<bar>\"\n        by (simp add: abs_mult f_def)\n      also have \"\\<dots> \\<le> k (i - 1) ^ 2 * ((2 * \\<bar>a\\<bar> * \\<bar>x\\<bar> + \\<bar>b\\<bar>) * (1 / (k (i - 1) * k (Suc (i - 1)))) +\n                        \\<bar>a\\<bar> * (1 / (k (i - 1) * k (Suc (i - 1)))) ^ 2)\"\n        by (intro mult_left_mono f_abs_bound) auto\n      also have \"\\<dots> = k (i - 1) / k i * (2 * \\<bar>a\\<bar> * \\<bar>x\\<bar> + \\<bar>b\\<bar>) + \\<bar>a\\<bar> / k i ^ 2\" using \\<open>i > 0\\<close>\n        by (simp add: power2_eq_square field_simps)\n      also have \"\\<dots> \\<le> 1 * (2 * \\<bar>a\\<bar> * \\<bar>x\\<bar> + \\<bar>b\\<bar>) + \\<bar>a\\<bar> / 1\" using \\<open>i > 0\\<close> \\<open>k i \\<ge> 1\\<close>\n        by (intro add_mono divide_left_mono mult_right_mono)\n           (auto intro!: k_leI one_le_power simp: of_nat_ge_1_iff)\n      also have \"\\<dots> = 2 * \\<bar>a\\<bar> * \\<bar>x\\<bar> + \\<bar>a\\<bar> + \\<bar>b\\<bar>\" by simp\n      finally show ?thesis unfolding A'_def by linarith\n    qed\n  \n    have \"C n = A (n - 1)\" by (simp add: A_def C_def n')\n    hence C_bound: \"\\<bar>C n\\<bar> \\<le> A'\" using A_bound[of \"n - 1\"] n by simp\n  \n    have \"B n = k (n - 1) * k (n - 2) *\n                  (f (R (n - 1)) + f (R (n - 2)) - a * (R (n - 1) - R (n - 2)) ^ 2)\"\n      by (simp add: B_def h_eq_conv_k algebra_simps power2_eq_square f_def)\n    also have \"\\<bar>\\<dots>\\<bar> = k (n - 1) * k (n - 2) * \n                       \\<bar>f (R (n - 1)) + f (R (n - 2)) - a * (R (n - 1) - R (n - 2)) ^ 2\\<bar>\"\n      by (simp add: abs_mult k_nonneg)\n    also have \"\\<dots> \\<le> k (n - 1) * k (n - 2) * \n                      (((2 * \\<bar>a\\<bar> * \\<bar>x\\<bar> + \\<bar>b\\<bar>) * (1 / (k (n - 1) * k (Suc (n - 1)))) +\n                          \\<bar>a\\<bar> * (1 / (k (n - 1) * k (Suc (n - 1)))) ^ 2) +                      \n                       ((2 * \\<bar>a\\<bar> * \\<bar>x\\<bar> + \\<bar>b\\<bar>) * (1 / (k (n - 2) * k (Suc (n - 2)))) +\n                          \\<bar>a\\<bar> * (1 / (k (n - 2) * k (Suc (n - 2)))) ^ 2) +\n                        \\<bar>a\\<bar> * \\<bar>R (Suc (n - 2)) - R (n - 2)\\<bar> ^ 2)\" (is \"_ \\<le> _ * (?S1 + ?S2 + ?S3)\")\n      by (intro mult_left_mono order.trans[OF abs_triangle_ineq4] order.trans[OF abs_triangle_ineq] \n            add_mono f_abs_bound order.refl)\n         (insert n, auto simp: abs_mult Suc_diff_Suc numeral_2_eq_2 k_nonneg)\n    also have \"\\<bar>R (Suc (n - 2)) - R (n - 2)\\<bar> = 1 / (k (n - 2) * k (Suc (n - 2)))\"\n      unfolding R_def k_def by (rule abs_diff_successive_convs)\n    also have \"of_int (k (n - 1) * k (n - 2)) * (?S1 + ?S2 + \\<bar>a\\<bar> * \\<dots> ^ 2) = \n                 (k (n - 2) / k n + 1) * (2 * \\<bar>a\\<bar> * \\<bar>x\\<bar> + \\<bar>b\\<bar>) + \n                 \\<bar>a\\<bar> * (k (n - 2) / (k (n - 1) * k n ^ 2) + 2 / (k (n - 1) * k (n - 2)))\"\n      (is \"_ = ?S\") using n by (simp add: field_simps power2_eq_square numeral_2_eq_2 Suc_diff_Suc)\n    also {\n      have A: \"2 * real_of_int (k (n - 2)) \\<le> of_int (k n)\"\n        using conv_denom_plus2_ratio_ge[of e \"n - 2\"] n\n        by (simp add: numeral_2_eq_2 Suc_diff_Suc k_def)\n      have \"fib (Suc 2) \\<le> k 2\" unfolding k_def by (intro conv_denom_lower_bound)\n      also have \"\\<dots> \\<le> k n\" by (intro k_leI n)\n      finally have \"k n \\<ge> 2\" by (simp add: numeral_3_eq_3)\n      hence B: \"of_int (k (n - 2)) * 2 ^ 2 \\<le> (of_int (k (n - 1)) * (of_int (k n))\\<^sup>2 :: real)\"\n        by (intro mult_mono power_mono) (auto intro: k_leI k_nonneg)\n      have C: \"1 * 1 \\<le> real_of_int (k (n - 1)) * of_int (k (n - 2))\" using k_ge_1\n        by (intro mult_mono) (auto simp: Suc_le_eq of_nat_ge_1_iff k_nonneg)\n      note A B C\n    }\n    hence \"?S \\<le> (1 / 2 + 1) * (2 * \\<bar>a\\<bar> * \\<bar>x\\<bar> + \\<bar>b\\<bar>) + \\<bar>a\\<bar> * (1 / 4 + 2)\"\n      by (intro add_mono mult_right_mono mult_left_mono) (auto simp: field_simps)\n    also have \"\\<dots> = (3 / 2) * (2 * \\<bar>a\\<bar> * \\<bar>x\\<bar> + \\<bar>b\\<bar>) + 9 / 4 * \\<bar>a\\<bar>\" by simp\n    finally have B_bound: \"\\<bar>B n\\<bar> \\<le> B'\" unfolding B'_def by linarith\n    from A_bound[of n] B_bound C_bound n\n    show \"(A n, B n, C n) \\<in> {-A'..A'} \\<times> {-B'..B'} \\<times> {-A'..A'}\" by auto\n  qed\n\n  have A_nz: \"A n \\<noteq> 0\" if \"n \\<ge> 1\" for n\n    using that\n  proof (induction n rule: dec_induct)\n    case base\n    show ?case\n    proof\n      assume \"A 1 = 0\"\n      hence \"real_of_int (A 1) = 0\" by simp\n      also have \"real_of_int (A 1) =\n                   real_of_int a * of_int (cfrac_nth e 0) ^ 2 +\n                   real_of_int b * cfrac_nth e 0 + real_of_int c\"\n        by (simp add: A_def h_def k_def)\n      finally have root': \"\\<dots> = 0\" .\n\n      have \"cfrac_nth e 0 \\<in> \\<rat>\" by auto\n      also from root' and \\<open>a \\<noteq> 0\\<close> have \"?this \\<longleftrightarrow> is_square (nat (b\\<^sup>2 - 4 * a * c))\"\n        by (intro quadratic_equation_solution_rat_iff) auto\n      also from root and \\<open>a \\<noteq> 0\\<close> have \"\\<dots> \\<longleftrightarrow> x \\<in> \\<rat>\"\n        by (intro quadratic_equation_solution_rat_iff [symmetric]) auto\n      finally show False using \\<open>x \\<notin> \\<rat>\\<close> by contradiction\n    qed\n  next\n    case (step m)\n    hence nz: \"C (Suc m) \\<noteq> 0\" by (simp add: C_def A_def)\n    show \"A (Suc m) \\<noteq> 0\"\n    proof\n      assume [simp]: \"A (Suc m) = 0\"\n      have \"X (Suc m) > 0\" unfolding X_def\n        by (intro cfrac_remainder_pos) auto\n      with X_root[of \"Suc m\"] step.hyps nz have \"X (Suc m) = -C (Suc m) / B (Suc m)\"\n        by (auto simp: divide_simps mult_ac)\n      also have \"\\<dots> \\<in> \\<rat>\" by auto\n      finally show False by simp\n    qed\n  qed \n\n  have \"finite ({-A'..A'} \\<times> {-B'..B'} \\<times> {-A'..A'})\" by auto\n  from this and bounds have \"finite ((\\<lambda>n. (A n, B n, C n)) ` {2..})\"\n    by (blast intro: finite_subset)\n  moreover have \"infinite ({2..} :: nat set)\" by (simp add: infinite_Ici)\n  ultimately have \"\\<exists>k1\\<in>{2..}. infinite {n \\<in> {2..}. (A n, B n, C n) = (A k1, B k1, C k1)}\"\n    by (intro pigeonhole_infinite)\n  then obtain k0 where k0: \"k0 \\<ge> 2\" \"infinite {n \\<in> {2..}. (A n, B n, C n) = (A k0, B k0, C k0)}\"\n    by auto\n  from infinite_countable_subset[OF this(2)] obtain g :: \"nat \\<Rightarrow> _\"\n    where g: \"inj g\" \"range g \\<subseteq> {n\\<in>{2..}. (A n, B n, C n) = (A k0, B k0, C k0)}\" by blast\n  hence g_ge_2: \"g k \\<ge> 2\" for k by auto\n  from g have [simp]: \"A (g k) = A k0\" \"B (g k) = B k0\" \"C (g k) = C k0\" for k\n    by auto\n\n  from g(1) have [simp]: \"g k1 = g k2 \\<longleftrightarrow> k1 = k2\" for k1 k2 by (auto simp: inj_def)\n  define z where \"z = (A k0, B k0, C k0)\"\n  let ?h = \"\\<lambda>k. (A (g k), B (g k), C (g k))\"\n  from g have g': \"distinct [g 1, g 2, g 3]\" \"?h 0 = z\" \"?h 1 = z\" \"?h 2 = z\"\n    by (auto simp: z_def)\n  have fin: \"finite {x :: real. A k0 * x ^ 2 + B k0 * x + C k0 = 0}\" using A_nz[of k0] k0(1)\n    by (subst finite_quadratic_equation_solutions_reals) auto\n  from X_root[of \"g 0\"] X_root[of \"g 1\"] X_root[of \"g 2\"] g_ge_2 g\n    have \"(X \\<circ> g) ` {0, 1, 2} \\<subseteq> {x. A k0 * x ^ 2 + B k0 * x + C k0 = 0}\"\n    by auto\n  hence \"card ((X \\<circ> g) ` {0, 1, 2}) \\<le> card \\<dots>\"\n    by (intro card_mono fin) auto\n  also have \"\\<dots> \\<le> 2\"\n    by (rule card_quadratic_equation_solutions_reals_le_2)\n  also have \"\\<dots> < card {0, 1, 2 :: nat}\" by simp\n  finally have \"\\<not>inj_on (X \\<circ> g) {0, 1, 2}\"\n    by (rule pigeonhole)\n  then obtain m1 m2 where\n    m12: \"m1 \\<in> {0, 1, 2}\" \"m2 \\<in> {0, 1, 2}\" \"X (g m1) = X (g m2)\" \"m1 \\<noteq> m2\"\n    unfolding inj_on_def o_def by blast\n  define n and l where \"n = min (g m1) (g m2)\" and \"l = nat \\<bar>int (g m1) - g m2\\<bar>\"\n  with m12 g' have l: \"l > 0\" \"X (n + l) = X n\"\n    by (auto simp: min_def nat_diff_distrib split: if_splits)\n\n  from l have \"cfrac_lim (cfrac_drop (n + l) e) = cfrac_lim (cfrac_drop n e)\"\n    by (simp add: X_def cfrac_remainder_def)\n  hence \"cfrac_drop (n + l) e = cfrac_drop n e\"\n    by (simp add: cfrac_lim_eq_iff)\n  hence \"cfrac_nth (cfrac_drop (n + l) e) = cfrac_nth (cfrac_drop n e)\"\n    by (simp only:)\n  hence period: \"cfrac_nth e (n + l + k) = cfrac_nth e (n + k)\" for k\n    by (simp add: fun_eq_iff add_ac)\n  have period: \"cfrac_nth e (k + l) = cfrac_nth e k\" if \"k \\<ge> n\" for k\n    using period[of \"k - n\"] that by (simp add: add_ac)\n  have period: \"cfrac_nth e (k + m * l) = cfrac_nth e k\" if \"k \\<ge> n\" for k m\n    using that\n  proof (induction m)\n    case (Suc m)\n    have \"cfrac_nth e (k + Suc m * l) = cfrac_nth e (k + m * l + l)\"\n      by (simp add: algebra_simps)\n    also have \"\\<dots> = cfrac_nth e (k + m * l)\"\n      using Suc.prems by (intro period) auto\n    also have \"\\<dots> = cfrac_nth e k\"\n      using Suc.prems by (intro Suc.IH) auto\n    finally show ?case .\n  qed simp_all\n\n  from this and l and that[of l n] show ?thesis by (simp add: X_def)\nqed\n\ntheorem periodic_cfrac_iff_quadratic_irrational:\n  assumes \"x \\<notin> \\<rat>\" \"x \\<ge> 0\"\n  shows   \"quadratic_irrational x \\<longleftrightarrow> \n             (\\<exists>N l. l > 0 \\<and> (\\<forall>n\\<ge>N. cfrac_nth (cfrac_of_real x) (n + l) = cfrac_nth (cfrac_of_real x) n))\"\nproof safe\n  assume *: \"quadratic_irrational x\"\n  with assms have \"quadratic_irrational (cfrac_lim (cfrac_of_real x))\" by auto\n  from quadratic_irrational_imp_periodic_cfrac [OF this] guess N l . note Nl = this\n  show \"\\<exists>N l. l > 0 \\<and> (\\<forall>n\\<ge>N. cfrac_nth (cfrac_of_real x) (n + l) = cfrac_nth (cfrac_of_real x) n)\"\n    by (rule exI[of _ N], rule exI[of _ l]) (insert Nl(1) Nl(2)[of _ 1], auto)\nnext\n  fix N l assume \"l > 0\" \"\\<forall>n\\<ge>N. cfrac_nth (cfrac_of_real x) (n + l) = cfrac_nth (cfrac_of_real x) n\"\n  hence \"quadratic_irrational (cfrac_lim (cfrac_of_real x))\" using assms\n    by (intro periodic_cfrac_imp_quadratic_irrational[of _ l N]) auto\n  with assms show \"quadratic_irrational x\"\n    by simp\nqed\n\ntext \\<open>\n  The following result can e.g. be used to show that a number is \\<^emph>\\<open>not\\<close> a quadratic\n  irrational.\n\\<close>\nlemma quadratic_irrational_cfrac_nth_range_finite:\n  assumes \"quadratic_irrational (cfrac_lim e)\"\n  shows   \"finite (range (cfrac_nth e))\"\nproof -\n  from quadratic_irrational_imp_periodic_cfrac[OF assms] obtain l N\n    where period: \"l > 0\" \"\\<And>m n. n \\<ge> N \\<Longrightarrow> cfrac_nth e (n + m * l) = cfrac_nth e n\"\n    by metis\n  have \"cfrac_nth e k \\<in> cfrac_nth e ` {..<N+l}\" for k\n  proof (cases \"k < N + l\")\n    case False\n    define n m where \"n = N + (k - N) mod l\" and \"m = (k - N) div l\"\n    have \"cfrac_nth e n \\<in> cfrac_nth e ` {..<N+l}\"\n      using \\<open>l > 0\\<close> by (intro imageI) (auto simp: n_def)\n    also have \"cfrac_nth e n = cfrac_nth e (n + m * l)\"\n      by (subst period) (auto simp: n_def)\n    also have \"n + m * l = k\"\n      using False by (simp add: n_def m_def)\n    finally show ?thesis .\n  qed auto\n  hence \"range (cfrac_nth e) \\<subseteq> cfrac_nth e ` {..<N+l}\"\n    by blast\n  thus ?thesis by (rule finite_subset) auto\nqed\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/Quadratic_Irrationals.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8311430520409023, "lm_q2_score": 0.8705972768020107, "lm_q1q2_score": 0.7235908777397214}}
{"text": "theory BasicTypes\nimports Main \"HOL-Library.FSet\"\nbegin\n\nsubsection \\<open>Basic types of camera combinators\\<close>\n\nsubsubsection \\<open>Disjoint set type\\<close>\ntext \\<open> Set with extra bottom element to encode non-disjoint unions \\<close>\ndatatype 'a dset = DSet \"'a set\" | DBot\n\nfun dset_raw :: \"'a dset \\<Rightarrow> 'a set option\" where\n  \"dset_raw (DSet s) = Some s\"\n| \"dset_raw DBot = None\"\n\nfun subdset_eq :: \"'a dset \\<Rightarrow> 'a dset \\<Rightarrow> bool\" (infix \"\\<subseteq>\\<^sub>d\" 50) where\n  \"subdset_eq (DSet s) (DSet t) = (s\\<subseteq>t)\"\n| \"subdset_eq _ _ = False\"\n\nfun dmember :: \"'a \\<Rightarrow> 'a dset \\<Rightarrow> bool\" (infix \"\\<in>\\<^sub>d\" 50) where\n  \"dmember x (DSet s) = (x\\<in>s)\"\n| \"dmember _ _ = False\"\n\ninstantiation dset :: (type) minus begin\nfun minus_dset :: \"'a dset \\<Rightarrow> 'a dset \\<Rightarrow> 'a dset\" where\n  \"minus_dset (DSet s) (DSet t) = DSet (s-t)\"\n| \"minus_dset (DSet s) DBot = DSet s\"\n| \"minus_dset _ _ = DBot\"\ninstance ..\nend\n\nlemma delem_dsubs: \"i\\<in>\\<^sub>d d \\<longleftrightarrow> DSet {i} \\<subseteq>\\<^sub>d d\"\n  using dmember.elims(2) subdset_eq.elims(2) by fastforce\n  \nlemma dsubs_dset: \"d1 \\<subseteq>\\<^sub>d d2 \\<Longrightarrow> \\<exists>s1 s2. d1 = DSet s1 \\<and> d2 = DSet s2\"\n  using subdset_eq.elims(2) by fastforce\n\nlemma dsubs_raw: \"d1 \\<subseteq>\\<^sub>d d2 \\<Longrightarrow> \\<exists>s1 s2. dset_raw d1 = Some s1 \\<and> dset_raw d2 = Some s2\"\n  using subdset_eq.elims(2) by fastforce\n\nlemma dminus_raw: \"\\<lbrakk>dset_raw d1 = Some s1\\<rbrakk> \\<Longrightarrow> \\<exists>s3. dset_raw (d1 - d2) = Some s3\"\n  by (metis dset.simps(3) dset_raw.elims minus_dset.simps(1) minus_dset.simps(2))\n\nlemma dsubs_minus_inter: \"d1 \\<subseteq>\\<^sub>d d2 \\<Longrightarrow> \\<exists>s1 s3. Some s3 = (dset_raw (d2 - d1)) \\<and> s1 \\<inter> s3 = {}\"\n  using dsubs_raw dminus_raw by (metis inf_bot_left)\n\ndefinition disj :: \"'a dset \\<Rightarrow> 'a dset \\<Rightarrow> bool\" where\n  \"disj d1 d2 \\<equiv> \\<exists>s1 s2. d1 = DSet s1 \\<and> d2 = DSet s2 \\<and> s1 \\<inter> s2 = {}\"   \n\nlemma disj_comm: \"disj d1 d2 \\<longleftrightarrow> disj d2 d1\"\n  unfolding disj_def by auto  \n  \nlemma dsubs_minus_disj: \"d1 \\<subseteq>\\<^sub>d d2 \\<Longrightarrow> disj d1 (d2-d1)\"\n  unfolding disj_def using dsubs_minus_inter dsubs_dset by fastforce\n\nlemma dsubs_trans: \"\\<lbrakk>d1 \\<subseteq>\\<^sub>d d2; d2 \\<subseteq>\\<^sub>d d3\\<rbrakk> \\<Longrightarrow> d1 \\<subseteq>\\<^sub>d d3\"\n  by (cases d1; cases d2; cases d3) auto\n\nlemma dsubs_mono_disj_minus: \"\\<lbrakk>d1 \\<subseteq>\\<^sub>d d2; disj d1 d3\\<rbrakk> \\<Longrightarrow> d1 \\<subseteq>\\<^sub>d d2-d3\"\n  unfolding disj_def by (cases d1;cases d2; cases d3) auto\n\nsubsubsection \\<open>Disjoint finite set type\\<close>\ntext \\<open> Finite set with extra bottom element to encode non-disjoint unions \\<close>\ndatatype 'a dfset = DFSet \"'a fset\" | DFBot\n\nfun dfmember :: \"'a \\<Rightarrow> 'a dfset \\<Rightarrow> bool\" (infix \"\\<in>\\<^sub>f\" 50) where\n  \"dfmember x (DFSet s) = (x|\\<in>|s)\"\n| \"dfmember _ _ = False\"\n\nfun dset_of_finite :: \"'a dfset \\<Rightarrow> 'a dset\" where\n  \"dset_of_finite (DFSet f) = DSet (fset f)\"\n| \"dset_of_finite DFBot = DBot\"\n\nlemma dset_of_finite_finite: \"finite {x. x \\<in>\\<^sub>d (dset_of_finite f)}\"\n  by (cases f) auto\n\nsubsubsection \\<open>Extended sum type\\<close>\ndatatype ('a,'b) sum_ext = Inl 'a | Inr 'b | Inv\n\ntype_notation sum_ext (infixl \"+\\<^sub>e\" 15)\nlemmas sum_ex2 = sum_ext.exhaust[case_product sum_ext.exhaust]\nlemmas sum_ex3 = sum_ext.exhaust[case_product sum_ex2]\nlemmas sum_ex4 = sum_ext.exhaust[case_product sum_ex3]\n\nsubsubsection \\<open>Step indexed predicates\\<close>\ntext \\<open>They are defined to hold for all steps below a maximum. \\<close>\ntypedef sprop = \"{s::nat\\<Rightarrow>bool. \\<forall>n m. m\\<le>n \\<longrightarrow> s n \\<longrightarrow> s m}\"\nproof\n  define s :: \"nat\\<Rightarrow>bool\" where \"s = (\\<lambda>_. True)\"\n  thus \"s \\<in> {s::nat\\<Rightarrow>bool. \\<forall>n m. m\\<le>n \\<longrightarrow> s n \\<longrightarrow> s m}\" by simp\nqed\n\nsetup_lifting type_definition_sprop\nlemmas [simp] = Rep_sprop_inverse Rep_sprop_inject\nlemmas [simp, intro!] = Rep_sprop[unfolded mem_Collect_eq]\n\nlift_definition sPure :: \"bool \\<Rightarrow> sprop\" is \"\\<lambda>b _. b\" .\nlemma sPureId: \"Rep_sprop (Abs_sprop ((\\<lambda>b _. b) b)) n = b\"\n  using Abs_sprop_inverse by auto\nabbreviation sFalse :: sprop where \"sFalse \\<equiv> sPure False\"\nabbreviation sTrue :: sprop where \"sTrue \\<equiv> sPure True\"\nlemmas [simp] = sPure.rep_eq sPureId sPureId[simplified sPure.abs_eq[symmetric]]\n\nlift_definition n_subseteq :: \"nat \\<Rightarrow> sprop \\<Rightarrow> sprop \\<Rightarrow> bool\" is\n  \"\\<lambda>n X Y. \\<forall>m\\<le>n. X m \\<longrightarrow> Y m\" .\nlift_definition sprop_conj :: \"sprop \\<Rightarrow> sprop \\<Rightarrow> sprop\" (infixl \"\\<and>\\<^sub>s\" 60) is \n  \"\\<lambda>x y. (\\<lambda>n. x n \\<and> y n)\" using conj_forward by simp\nlift_definition sprop_disj :: \"sprop \\<Rightarrow> sprop \\<Rightarrow> sprop\" (infixl \"\\<or>\\<^sub>s\" 60) is\n  \"\\<lambda>x y. (\\<lambda>n. x n \\<or> y n)\" using disj_forward by simp\nlift_definition sprop_impl :: \"sprop \\<Rightarrow> sprop \\<Rightarrow> sprop\" (infixr \"\\<longrightarrow>\\<^sub>s\" 60) is\n  \"\\<lambda>x y. (\\<lambda>n. \\<forall>m\\<le>n. x m \\<longrightarrow> y m)\" by (meson dual_order.trans)\n\nsubsubsection \\<open>Later camera combinator\\<close>\ntext \\<open>This type encodes the later modality on a type level.\\<close>\ndatatype 'a later = Next (later_car: 'a)\n\nlemmas later2_ex = later.exhaust[case_product later.exhaust]\nlemmas later3_ex = later.exhaust[case_product later2_ex]\n\nsubsubsection \\<open>Agreement camera combinator\\<close>\ntypedef 'a ag = \"{a::'a set | a. finite a \\<and> a\\<noteq>{} }\"\n  by auto\n\nsetup_lifting type_definition_ag\n\nlift_definition map_ag :: \"('a\\<Rightarrow>'b) \\<Rightarrow> 'a ag \\<Rightarrow> 'b ag\" is \"(`)\" by simp\nlift_definition pred_ag :: \"('a \\<Rightarrow> bool) \\<Rightarrow> 'a ag \\<Rightarrow> bool\" is \"\\<lambda>P s. Ball s P\" .\nlift_definition rel_ag :: \"('a \\<Rightarrow> 'b \\<Rightarrow> bool) \\<Rightarrow> 'a ag \\<Rightarrow> 'b ag \\<Rightarrow> bool\" is rel_set .\n\nlift_definition to_ag :: \"'a \\<Rightarrow> 'a ag\" is \"\\<lambda>a::'a. {a}\" by simp\n\nlemma image_ag: \"image f (Rep_ag s) \\<in> {a |a. finite a \\<and> a \\<noteq> {}}\"\n  apply (simp_all add: image_def)\n  apply (rule conjI)\n  subgoal using finite_imageI[unfolded image_def] Rep_ag by auto\n  using Rep_ag by fast\nlemmas image_abs_ag = Abs_ag_inverse[OF image_ag] Abs_ag_inject[OF image_ag  image_ag]\n\ncontext includes cardinal_syntax begin\nbnf \"'a ag\"\n  map: map_ag\n  sets: Rep_ag\n  bd: \"natLeq\"\n  rel: rel_ag\nproof -\nshow \"map_ag id = id\" by (auto simp: map_ag_def Rep_ag_inverse)\nnext\nfix f :: \"'a \\<Rightarrow> 'b\" and g :: \"'b \\<Rightarrow> 'c\"\nshow \"map_ag (g \\<circ> f) = map_ag g \\<circ> map_ag f\" \n  by (auto simp: comp_def image_def map_ag_def)\n  (metis Rep_ag_inverse image_def image_image map_ag.rep_eq map_fun_apply)\nnext\nfix x :: \"'a ag\" and f g :: \"'a \\<Rightarrow> 'b\"\nassume \"\\<And>z. z \\<in> Rep_ag x \\<Longrightarrow> f z = g z\"\nthen show \"map_ag f x = map_ag g x\" by transfer auto\nnext\nfix f :: \"'a\\<Rightarrow>'b\"\nhave \"{y. \\<exists>x\\<in>Rep_ag s. y = f x} = image f (Rep_ag s)\" for s by auto\nthen have \"{y. \\<exists>x\\<in>Rep_ag s. y = f x} \\<in> {a |a. finite a \\<and> a \\<noteq> {}}\" for s\n  apply simp_all\n  apply (rule conjI)\n  subgoal using finite_imageI Rep_ag by fast\n  using Rep_ag by blast\nfrom Abs_ag_inverse[OF this] show \"Rep_ag \\<circ> map_ag f = (`) f \\<circ> Rep_ag\" \n  by (auto simp: map_ag_def image_def comp_def)\nnext\nshow \"card_order (natLeq )\"\n  using card_of_card_order_on card_order_csum natLeq_card_order by blast\nnext\nshow \"cinfinite (natLeq )\"\n  using cinfinite_csum natLeq_cinfinite by blast\nnext\nfix s :: \"'a ag\"\nshow \"|Rep_ag s| \\<le>o natLeq\"\nby (metis (no_types, lifting) Rep_ag card_of_Well_order infinite_iff_natLeq_ordLeq mem_Collect_eq \n  natLeq_Well_order not_ordLeq_iff_ordLess ordLess_imp_ordLeq)\nnext\nfix R :: \"'a\\<Rightarrow>'b\\<Rightarrow>bool\" and S :: \"'b\\<Rightarrow>'c\\<Rightarrow>bool\"\nshow \"rel_ag R OO rel_ag S \\<le> rel_ag (R OO S)\"\n  by (auto simp: rel_ag.rep_eq rel_set_def relcompp.simps) blast+\nnext\nfix R :: \"'a\\<Rightarrow>'b\\<Rightarrow>bool\"\nshow \"rel_ag R = (\\<lambda>x y. \\<exists>z. Rep_ag z \\<subseteq> {(x, y). R x y} \\<and> map_ag fst z = x \\<and> map_ag snd z = y)\"\napply (auto simp: rel_ag_def map_ag_def rel_set_def map_fun_def comp_def)\napply standard\napply standard\nproof\n  fix a :: \"'a ag\" and b :: \"'b ag\"\n  assume \"(\\<forall>x\\<in>Rep_ag a. \\<exists>xa\\<in>Rep_ag b. R x xa) \\<and> (\\<forall>y\\<in>Rep_ag b. \\<exists>x\\<in>Rep_ag a. R x y)\"\n  then have assms: \"\\<forall>x\\<in>Rep_ag a. \\<exists>xa\\<in>Rep_ag b. R x xa\" \"\\<forall>y\\<in>Rep_ag b. \\<exists>x\\<in>Rep_ag a. R x y\" by simp_all\n  define c where c:\"c = {(x,y) | x y. x\\<in>Rep_ag a \\<and> y\\<in>Rep_ag b}\"\n  from Rep_ag have \"finite (Rep_ag a)\" \"Rep_ag a \\<noteq> {}\" \"finite (Rep_ag b)\" \"Rep_ag b \\<noteq> {}\" by auto\n  with c have c_ag: \"finite c\" \"c \\<noteq> {}\" by auto\n  define c' where c': \"c' = c \\<inter> {(x,y) | x y. R x y}\"\n  with c_ag c and assms have c'_ag: \"finite c'\" \"c' \\<noteq> {}\" by auto\n  from c' c assms have c'_alt: \"c' = {(x,y) | x y. x\\<in>Rep_ag a \\<and> y\\<in>Rep_ag b \\<and> R x y}\" by auto\n  define z where z: \"z = Abs_ag c'\"\n  then have rep_z: \"Rep_ag z = c'\" using Abs_ag_inverse c'_ag by auto\n  {\n    from c'_alt assms(1) have \"(fst ` c') = Rep_ag a\" by (simp add: image_def) blast\n    with rep_z have \"Abs_ag (fst ` Rep_ag z) = a\" using Rep_ag_inverse by auto\n  }\n  moreover {\n    from c'_alt assms(2) have \"(snd ` c') = Rep_ag b\" by (simp add: image_def) blast\n    with rep_z have \"Abs_ag (snd ` Rep_ag z) = b\" using Rep_ag_inverse by auto\n  }\n  moreover have \"Rep_ag z \\<subseteq> {(x, y). R x y}\" using rep_z c' by simp\n  ultimately show \"\\<exists>z. Rep_ag z \\<subseteq> {(x, y). R x y} \\<and> Abs_ag (fst ` Rep_ag z) = a \\<and> Abs_ag (snd ` Rep_ag z) = b\"\n  by auto\nnext\n  fix a :: \"'a ag\" and b :: \"'b ag\"\n  assume \"\\<exists>z. Rep_ag z \\<subseteq> {(x, y). R x y} \\<and> Abs_ag (fst ` Rep_ag z) = a \\<and> Abs_ag (snd ` Rep_ag z) = b\"\n  then show \"(\\<forall>x\\<in>Rep_ag a. \\<exists>xa\\<in>Rep_ag b. R x xa) \\<and> (\\<forall>y\\<in>Rep_ag b. \\<exists>x\\<in>Rep_ag a. R x y)\"\n  by (smt (verit, best) Product_Type.Collect_case_prodD image_abs_ag(1) image_iff subset_eq)\nqed\nqed\nend\n\nsubsubsection \\<open>Exclusive camera combinator\\<close>\ndatatype 'a ex = Ex 'a | Inv\n\nsubsubsection \\<open>Authoritative camera combinator\\<close>\ndatatype 'm auth = Auth \"('m ex option\\<times>'m)\"\n\nabbreviation fragm :: \"'m \\<Rightarrow> 'm auth\" where \"fragm \\<equiv> \\<lambda>a::'m. Auth (None, a)\"\nabbreviation comb :: \"'m \\<Rightarrow> 'm \\<Rightarrow> 'm auth\" where \"comb \\<equiv> \\<lambda>(a::'m) b. Auth (Some (Ex a), b)\"\nend", "meta": {"author": "firefighterduck", "repo": "isariris", "sha": "d02268e1e11cf681cae70b366b52843cbd90cc49", "save_path": "github-repos/isabelle/firefighterduck-isariris", "path": "github-repos/isabelle/firefighterduck-isariris/isariris-d02268e1e11cf681cae70b366b52843cbd90cc49/IrisCore/BasicTypes.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972583359806, "lm_q2_score": 0.8311430436757313, "lm_q1q2_score": 0.7235908551091138}}
{"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[\\S4.5]{GrahamKnuthPatashnik1994CM}.\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[\\S4.5]{GrahamKnuthPatashnik1994CM}.\n\\<close>\n\nsubsection \\<open>Specification via a recursion equation\\<close>\n\ntext \\<open>\n  \\cite{Hinze2009JFP} 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{BackhouseFerreira2008MPC} and \\citet{Hinze2009JFP} 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{BackhouseFerreira2008MPC}.\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[p502]{Hinze2009JFP} gets a bit sloppy here; it is\n  not straightforward to adapt his lifting framework \\cite{Hinze2010Lifting} 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{Dijkstra1982EWD570,Dijkstra1982EWD578}.\n  Loopless \\`a la \\cite{Bird2006MPC} 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": "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/Stern_Brocot/Stern_Brocot_Tree.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8198933359135361, "lm_q2_score": 0.8824278710924296, "lm_q1q2_score": 0.7234967309330519}}
{"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 Path_Connected\nbegin\n\nsubsection \\<open>Faces of a (usually convex) set\\<close>\n\ndefinition\\<^marker>\\<open>tag important\\<close> 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    \"((+) a ` T face_of (+) a ` S) \\<longleftrightarrow> T face_of S\"\nproof -\n  have *: \"\\<And>a T S. T face_of S \\<Longrightarrow> ((+) a ` T face_of (+) a ` S)\"\n    apply (simp add: face_of_def Ball_def, clarify)\n    by (meson imageI open_segment_translation_eq)\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\nproposition face_of_imp_eq_affine_Int:\n  fixes S :: \"'a::euclidean_space set\"\n  assumes S: \"convex 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: field_split_simps)\n    have [simp]: \"((e - e * e / (e + norm (b - c))) / norm (b - c)) = (e / (e + norm (b - c)))\"\n      using False nbc\n      by (simp add: divide_simps) (simp add: algebra_simps)\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\nlemma subset_of_face_of_affine_hull:\n    fixes S :: \"'a::euclidean_space set\"\n  assumes T: \"T face_of S\" and \"convex S\" \"U \\<subseteq> S\" and dis: \"\\<not> disjnt (affine hull T) (rel_interior U)\"\n  shows \"U \\<subseteq> T\"\n  apply (rule subset_of_face_of [OF T \\<open>U \\<subseteq> S\\<close>])\n  using face_of_imp_eq_affine_Int [OF \\<open>convex S\\<close> T]\n  using rel_interior_subset [of U] dis\n  using \\<open>U \\<subseteq> S\\<close> disjnt_def by fastforce\n\nlemma affine_hull_face_of_disjoint_rel_interior:\n    fixes S :: \"'a::euclidean_space set\"\n  assumes \"convex S\" \"F face_of S\" \"F \\<noteq> S\"\n  shows \"affine hull F \\<inter> rel_interior S = {}\"\n  by (metis assms disjnt_def face_of_imp_subset order_refl subset_antisym subset_of_face_of_affine_hull)\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] field_split_simps)\n  then show ?thesis\n    using \\<open>affine S\\<close> xy by (auto simp: affine_alt)\nqed\n\nproposition 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 fin(2) sum_nonneg_eq_0_iff by auto\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\nproposition 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 linear_fst linear_snd)\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> linear_fst linear_snd 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\\<^marker>\\<open>tag important\\<close> 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 IntQ Inter_UNIV_conv(2) assms(1) assms(2) ex_in_conv)\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\nproposition exposed_face_of_parallel:\n   \"T exposed_face_of S \\<longleftrightarrow>\n         T face_of S \\<and>\n         (\\<exists>a b. S \\<subseteq> {x. a \\<bullet> x \\<le> b} \\<and> T = S \\<inter> {x. a \\<bullet> x = b} \\<and>\n                (T \\<noteq> {} \\<longrightarrow> T \\<noteq> S \\<longrightarrow> a \\<noteq> 0) \\<and>\n                (T \\<noteq> S \\<longrightarrow> (\\<forall>w \\<in> affine hull S. (w + a) \\<in> affine hull S)))\"\n  (is \"?lhs = ?rhs\")\nproof\n  assume ?lhs then show ?rhs\n  proof (clarsimp simp: exposed_face_of_def)\n    fix a b\n    assume faceS: \"S \\<inter> {x. a \\<bullet> x = b} face_of S\" and Ssub: \"S \\<subseteq> {x. a \\<bullet> x \\<le> b}\" \n    show \"\\<exists>c d. S \\<subseteq> {x. c \\<bullet> x \\<le> d} \\<and>\n                S \\<inter> {x. a \\<bullet> x = b} = S \\<inter> {x. c \\<bullet> x = d} \\<and>\n                (S \\<inter> {x. a \\<bullet> x = b} \\<noteq> {} \\<longrightarrow> S \\<inter> {x. a \\<bullet> x = b} \\<noteq> S \\<longrightarrow> c \\<noteq> 0) \\<and>\n                (S \\<inter> {x. a \\<bullet> x = b} \\<noteq> S \\<longrightarrow> (\\<forall>w \\<in> affine hull S. w + c \\<in> affine hull S))\"\n    proof (cases \"affine hull S \\<inter> {x. -a \\<bullet> x \\<le> -b} = {} \\<or> affine hull S \\<subseteq> {x. - a \\<bullet> x \\<le> - b}\")\n      case True\n      then show ?thesis\n      proof\n        assume \"affine hull S \\<inter> {x. - a \\<bullet> x \\<le> - b} = {}\"\n       then show ?thesis\n         apply (rule_tac x=\"0\" in exI)\n         apply (rule_tac x=\"1\" in exI)\n         using hull_subset by fastforce\n    next\n      assume \"affine hull S \\<subseteq> {x. - a \\<bullet> x \\<le> - b}\"\n      then show ?thesis\n         apply (rule_tac x=\"0\" in exI)\n         apply (rule_tac x=\"0\" in exI)\n        using Ssub hull_subset by fastforce\n    qed\n  next\n    case False\n    then obtain a' b' where \"a' \\<noteq> 0\" \n      and le: \"affine hull S \\<inter> {x. a' \\<bullet> x \\<le> b'} = affine hull S \\<inter> {x. - a \\<bullet> x \\<le> - b}\" \n      and eq: \"affine hull S \\<inter> {x. a' \\<bullet> x = b'} = affine hull S \\<inter> {x. - a \\<bullet> x = - b}\" \n      and mem: \"\\<And>w. w \\<in> affine hull S \\<Longrightarrow> w + a' \\<in> affine hull S\"\n      using affine_parallel_slice affine_affine_hull by metis \n    show ?thesis\n    proof (intro conjI impI allI ballI exI)\n      have *: \"S \\<subseteq> - (affine hull S \\<inter> {x. P x}) \\<union> affine hull S \\<inter> {x. Q x} \\<Longrightarrow> S \\<subseteq> {x. \\<not> P x \\<or> Q x}\" \n        for P Q \n        using hull_subset by fastforce  \n      have \"S \\<subseteq> {x. \\<not> (a' \\<bullet> x \\<le> b') \\<or> a' \\<bullet> x = b'}\"\n        apply (rule *)\n        apply (simp only: le eq)\n        using Ssub by auto\n      then show \"S \\<subseteq> {x. - a' \\<bullet> x \\<le> - b'}\"\n        by auto \n      show \"S \\<inter> {x. a \\<bullet> x = b} = S \\<inter> {x. - a' \\<bullet> x = - b'}\"\n        using eq hull_subset [of S affine] by force\n      show \"\\<lbrakk>S \\<inter> {x. a \\<bullet> x = b} \\<noteq> {}; S \\<inter> {x. a \\<bullet> x = b} \\<noteq> S\\<rbrakk> \\<Longrightarrow> - a' \\<noteq> 0\"\n        using \\<open>a' \\<noteq> 0\\<close> by auto\n      show \"w + - a' \\<in> affine hull S\"\n        if \"S \\<inter> {x. a \\<bullet> x = b} \\<noteq> S\" \"w \\<in> affine hull S\" for w\n      proof -\n        have \"w + 1 *\\<^sub>R (w - (w + a')) \\<in> affine hull S\"\n          using affine_affine_hull mem mem_affine_3_minus that(2) by blast\n        then show ?thesis  by simp\n      qed\n    qed\n  qed\nqed\nnext\n  assume ?rhs then show ?lhs\n    unfolding exposed_face_of_def by blast\nqed\n\nsubsection\\<open>Extreme points of a set: its singleton faces\\<close>\n\ndefinition\\<^marker>\\<open>tag important\\<close> 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\nproposition extreme_points_of_convex_hull:\n   \"{x. x extreme_point_of (convex hull S)} \\<subseteq> S\"\n  using extreme_point_of_convex_hull by auto\n\nlemma extreme_point_of_empty [simp]: \"\\<not> (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}\"\n  using extreme_point_of_translation_eq\n  by auto (metis (no_types, lifting) image_iff mem_Collect_eq minus_add_cancel)\n\nlemma extreme_points_of_translation_subtract:\n   \"{x. x extreme_point_of (image (\\<lambda>x. x - a) S)} =\n    (\\<lambda>x. x - a) ` {x. x extreme_point_of S}\"\n  using extreme_points_of_translation [of \"- a\" S]\n  by simp\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\\<^marker>\\<open>tag important\\<close> 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]: \"\\<not> S facet_of {}\"\n  by (simp add: facet_of_def)\n\nlemma facet_of_irrefl [simp]: \"\\<not> 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           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           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> (*FIXME too small subsection, rearrange? *)\n\ndefinition\\<^marker>\\<open>tag important\\<close> 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\nproposition 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 \"\\<not> (norm a < norm x) \\<and> \\<not> (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 ((\\<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_base)\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 ((+) (- a) ` S)\"\n      by (simp add: \\<open>compact S\\<close> compact_translation_subtract cong: image_cong_simp)\n    have 2: \"convex ((+) (- a) ` S)\"\n      by (simp add: \\<open>convex S\\<close> compact_translation_subtract)\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_subtract translation_assoc cong: image_cong_simp)\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\ncorollary 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)}\"\n  by (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   \"\\<not> 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\nlemma face_of_convex_hull_aux:\n  assumes eq: \"x *\\<^sub>R p = u *\\<^sub>R a + v *\\<^sub>R b + w *\\<^sub>R c\"\n    and x: \"u + v + w = x\" \"x \\<noteq> 0\" and S: \"affine S\" \"a \\<in> S\" \"b \\<in> S\" \"c \\<in> S\"\n  shows \"p \\<in> S\"\nproof -\n  have \"p = (u *\\<^sub>R a + v *\\<^sub>R b + w *\\<^sub>R c) /\\<^sub>R x\"\n    by (metis \\<open>x \\<noteq> 0\\<close> eq mult.commute right_inverse scaleR_one scaleR_scaleR)\n  moreover have \"affine hull {a,b,c} \\<subseteq> S\"\n    by (simp add: S hull_minimal)\n  moreover have \"(u *\\<^sub>R a + v *\\<^sub>R b + w *\\<^sub>R c) /\\<^sub>R x \\<in> affine hull {a,b,c}\"\n    apply (simp add: affine_hull_3)\n    apply (rule_tac x=\"u/x\" in exI)\n    apply (rule_tac x=\"v/x\" in exI)\n    apply (rule_tac x=\"w/x\" in exI)\n    using x apply (auto simp: field_split_simps)\n    done\n  ultimately show ?thesis by force\nqed\n\nproposition face_of_convex_hull_insert_eq:\n  fixes a :: \"'a :: euclidean_space\"\n  assumes \"finite S\" and a: \"a \\<notin> affine hull S\"\n  shows \"(F face_of (convex hull (insert a S)) \\<longleftrightarrow>\n          F face_of (convex hull S) \\<or>\n          (\\<exists>F'. F' face_of (convex hull S) \\<and> F = convex hull (insert a F')))\"\n         (is \"F face_of ?CAS \\<longleftrightarrow> _\")\nproof safe\n  assume F: \"F face_of ?CAS\"\n    and *: \"\\<nexists>F'. F' face_of convex hull S \\<and> F = convex hull insert a F'\"\n  obtain T where T: \"T \\<subseteq> insert a S\" and FeqT: \"F = convex hull T\"\n    by (metis F \\<open>finite S\\<close> compact_insert finite_imp_compact face_of_convex_hull_subset)\n  show \"F face_of convex hull S\"\n  proof (cases \"a \\<in> T\")\n    case True\n    have \"F = convex hull insert a (convex hull T \\<inter> convex hull S)\"\n    proof\n      have \"T \\<subseteq> insert a (convex hull T \\<inter> convex hull S)\"\n        using T hull_subset by fastforce\n      then show \"F \\<subseteq> convex hull insert a (convex hull T \\<inter> convex hull S)\"\n        by (simp add: FeqT hull_mono)\n      show \"convex hull insert a (convex hull T \\<inter> convex hull S) \\<subseteq> F\"\n        apply (rule hull_minimal)\n        using True by (auto simp: \\<open>F = convex hull T\\<close> hull_inc)\n    qed\n    moreover have \"convex hull T \\<inter> convex hull S face_of convex hull S\"\n      by (metis F FeqT convex_convex_hull face_of_slice hull_mono inf.absorb_iff2 subset_insertI)\n    ultimately show ?thesis\n      using * by force\n  next\n    case False\n    then show ?thesis\n      by (metis FeqT F T face_of_subset hull_mono subset_insert subset_insertI)\n  qed\nnext\n  assume \"F face_of convex hull S\"\n  show \"F face_of ?CAS\"\n    by (simp add: \\<open>F face_of convex hull S\\<close> a face_of_convex_hull_insert \\<open>finite S\\<close>)\nnext\n  fix F\n  assume F: \"F face_of convex hull S\"\n  show \"convex hull insert a F face_of ?CAS\"\n  proof (cases \"S = {}\")\n    case True\n    then show ?thesis\n      using F face_of_affine_eq by auto\n  next\n    case False\n    have anotc: \"a \\<notin> convex hull S\"\n      by (metis (no_types) a affine_hull_convex_hull hull_inc)\n    show ?thesis\n    proof (cases \"F = {}\")\n      case True show ?thesis\n        using anotc by (simp add: \\<open>F = {}\\<close> \\<open>finite S\\<close> extreme_point_of_convex_hull_insert face_of_singleton)\n    next\n      case False\n      have \"convex hull insert a F \\<subseteq> ?CAS\"\n        by (simp add: F a \\<open>finite S\\<close> convex_hull_subset face_of_convex_hull_insert face_of_imp_subset hull_inc)\n      moreover\n      have \"(\\<exists>y v. (1 - ub) *\\<^sub>R a + ub *\\<^sub>R b = (1 - v) *\\<^sub>R a + v *\\<^sub>R y \\<and>\n                   0 \\<le> v \\<and> v \\<le> 1 \\<and> y \\<in> F) \\<and>\n            (\\<exists>x u. (1 - uc) *\\<^sub>R a + uc *\\<^sub>R c = (1 - u) *\\<^sub>R a + u *\\<^sub>R x \\<and>\n                   0 \\<le> u \\<and> u \\<le> 1 \\<and> x \\<in> F)\"\n        if *: \"(1 - ux) *\\<^sub>R a + ux *\\<^sub>R x\n               \\<in> open_segment ((1 - ub) *\\<^sub>R a + ub *\\<^sub>R b) ((1 - uc) *\\<^sub>R a + uc *\\<^sub>R c)\"\n          and \"0 \\<le> ub\" \"ub \\<le> 1\" \"0 \\<le> uc\" \"uc \\<le> 1\" \"0 \\<le> ux\" \"ux \\<le> 1\"\n          and b: \"b \\<in> convex hull S\" and c: \"c \\<in> convex hull S\" and \"x \\<in> F\"\n        for b c ub uc ux x\n      proof -\n        obtain v where ne: \"(1 - ub) *\\<^sub>R a + ub *\\<^sub>R b \\<noteq> (1 - uc) *\\<^sub>R a + uc *\\<^sub>R c\"\n          and eq: \"(1 - ux) *\\<^sub>R a + ux *\\<^sub>R x =\n                    (1 - v) *\\<^sub>R ((1 - ub) *\\<^sub>R a + ub *\\<^sub>R b) + v *\\<^sub>R ((1 - uc) *\\<^sub>R a + uc *\\<^sub>R c)\"\n          and \"0 < v\" \"v < 1\"\n          using * by (auto simp: in_segment)\n        then have 0: \"((1 - ux) - ((1 - v) * (1 - ub) + v * (1 - uc))) *\\<^sub>R a +\n                      (ux *\\<^sub>R x - (((1 - v) * ub) *\\<^sub>R b + (v * uc) *\\<^sub>R c)) = 0\"\n          by (auto simp: algebra_simps)\n        then have \"((1 - ux) - ((1 - v) * (1 - ub) + v * (1 - uc))) *\\<^sub>R a =\n                   ((1 - v) * ub) *\\<^sub>R b + (v * uc) *\\<^sub>R c + (-ux) *\\<^sub>R x\"\n          by (auto simp: algebra_simps)\n        then have \"a \\<in> affine hull S\" if \"1 - ux - ((1 - v) * (1 - ub) + v * (1 - uc)) \\<noteq> 0\"\n          apply (rule face_of_convex_hull_aux)\n          using b c that apply (auto simp: algebra_simps)\n          using F convex_hull_subset_affine_hull face_of_imp_subset \\<open>x \\<in> F\\<close> apply blast+\n          done\n        then have \"1 - ux - ((1 - v) * (1 - ub) + v * (1 - uc)) = 0\"\n          using a by blast\n        with 0 have equx: \"(1 - v) * ub + v * uc = ux\"\n          and uxx: \"ux *\\<^sub>R x = (((1 - v) * ub) *\\<^sub>R b + (v * uc) *\\<^sub>R c)\"\n          by auto (auto simp: algebra_simps)\n        show ?thesis\n        proof (cases \"uc = 0\")\n          case True\n          then show ?thesis\n            using equx 0 \\<open>0 \\<le> ub\\<close> \\<open>ub \\<le> 1\\<close> \\<open>v < 1\\<close> \\<open>x \\<in> F\\<close>\n            apply (auto simp: algebra_simps)\n             apply (rule_tac x=x in exI, simp)\n             apply (rule_tac x=ub in exI, auto)\n             apply (metis add.left_neutral diff_eq_eq less_irrefl mult.commute mult_cancel_right1 real_vector.scale_cancel_left real_vector.scale_left_diff_distrib)\n            using \\<open>x \\<in> F\\<close> \\<open>uc \\<le> 1\\<close> apply blast\n            done\n        next\n          case False\n          show ?thesis\n          proof (cases \"ub = 0\")\n            case True\n            then show ?thesis\n              using equx 0 \\<open>0 \\<le> uc\\<close> \\<open>uc \\<le> 1\\<close> \\<open>0 < v\\<close> \\<open>x \\<in> F\\<close> \\<open>uc \\<noteq> 0\\<close> by (force simp: algebra_simps)\n          next\n            case False\n            then have \"0 < ub\" \"0 < uc\"\n              using \\<open>uc \\<noteq> 0\\<close> \\<open>0 \\<le> ub\\<close> \\<open>0 \\<le> uc\\<close> by auto\n            then have \"ux \\<noteq> 0\"\n              by (metis \\<open>0 < v\\<close> \\<open>v < 1\\<close> diff_ge_0_iff_ge dual_order.strict_implies_order equx leD le_add_same_cancel2 zero_le_mult_iff zero_less_mult_iff)\n            have \"b \\<in> F \\<and> c \\<in> F\"\n            proof (cases \"b = c\")\n              case True\n              then show ?thesis\n                by (metis \\<open>ux \\<noteq> 0\\<close> equx real_vector.scale_cancel_left scaleR_add_left uxx \\<open>x \\<in> F\\<close>)\n            next\n              case False\n              have \"x = (((1 - v) * ub) *\\<^sub>R b + (v * uc) *\\<^sub>R c) /\\<^sub>R ux\"\n                by (metis \\<open>ux \\<noteq> 0\\<close> uxx mult.commute right_inverse scaleR_one scaleR_scaleR)\n              also have \"... = (1 - v * uc / ux) *\\<^sub>R b + (v * uc / ux) *\\<^sub>R c\"\n                using \\<open>ux \\<noteq> 0\\<close> equx apply (auto simp: field_split_simps)\n                by (metis add.commute add_diff_eq add_divide_distrib diff_add_cancel scaleR_add_left)\n              finally have \"x = (1 - v * uc / ux) *\\<^sub>R b + (v * uc / ux) *\\<^sub>R c\" .\n              then have \"x \\<in> open_segment b c\"\n                apply (simp add: in_segment \\<open>b \\<noteq> c\\<close>)\n                apply (rule_tac x=\"(v * uc) / ux\" in exI)\n                using \\<open>0 \\<le> ux\\<close> \\<open>ux \\<noteq> 0\\<close> \\<open>0 < uc\\<close> \\<open>0 < v\\<close> \\<open>0 < ub\\<close> \\<open>v < 1\\<close> equx\n                apply (force simp: field_split_simps)\n                done\n              then show ?thesis\n                by (rule face_ofD [OF F _ b c \\<open>x \\<in> F\\<close>])\n            qed\n            with \\<open>0 \\<le> ub\\<close> \\<open>ub \\<le> 1\\<close> \\<open>0 \\<le> uc\\<close> \\<open>uc \\<le> 1\\<close> show ?thesis by blast\n          qed\n        qed\n      qed\n      moreover have \"convex hull F = F\"\n        by (meson F convex_hull_eq face_of_imp_convex)\n      ultimately show ?thesis\n        unfolding face_of_def by (fastforce simp: convex_hull_insert_alt \\<open>S \\<noteq> {}\\<close> \\<open>F \\<noteq> {}\\<close>)\n    qed\n  qed\nqed\n\nlemma face_of_convex_hull_insert2:\n  fixes a :: \"'a :: euclidean_space\"\n  assumes S: \"finite S\" and a: \"a \\<notin> affine hull S\" and F: \"F face_of convex hull S\"\n  shows \"convex hull (insert a F) face_of convex hull (insert a S)\"\n  by (metis F face_of_convex_hull_insert_eq [OF S a])\n\nproposition face_of_convex_hull_affine_independent:\n  fixes S :: \"'a::euclidean_space set\"\n  assumes \"\\<not> 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 \"\\<not> 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 \"\\<not> 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   \"\\<not>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\nproposition 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\\<^marker>\\<open>tag important\\<close> 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 ((hull) convex ` {T. T \\<subseteq> v})\"\n    by (simp add: \\<open>finite v\\<close>)\n  moreover have \"{F. F face_of S} \\<subseteq> ((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\nlemma face_of_polytope_insert:\n     \"\\<lbrakk>polytope S; a \\<notin> affine hull S; F face_of S\\<rbrakk> \\<Longrightarrow> F face_of convex hull (insert a S)\"\n  by (metis (no_types, lifting) affine_hull_convex_hull face_of_convex_hull_insert hull_insert polytope_def)\n\nproposition face_of_polytope_insert2:\n  fixes a :: \"'a :: euclidean_space\"\n  assumes \"polytope S\" \"a \\<notin> affine hull S\" \"F face_of S\"\n  shows \"convex hull (insert a F) face_of convex hull (insert a S)\"\nproof -\n  obtain V where \"finite V\" \"S = convex hull V\"\n    using assms by (auto simp: polytope_def)\n  then have \"convex hull (insert a F) face_of convex hull (insert a V)\"\n    using affine_hull_convex_hull assms face_of_convex_hull_insert2 by blast\n  then show ?thesis\n    by (metis \\<open>S = convex hull V\\<close> hull_insert)\nqed\n\n\nsubsection\\<open>Polyhedra\\<close>\n\ndefinition\\<^marker>\\<open>tag important\\<close> 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\nproposition 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 field_split_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\" \"\\<not>(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 \"\\<not> (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; \\<not> (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> \\<not>(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 \"\\<not> (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 *: \"\\<not> (?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 field_split_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          let ?body = \"(\\<lambda>j. 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) ` (F - {h})\"\n          define inff where \"inff = Inf ?body\"\n          from \\<open>finite F\\<close> have \"finite ?body\"\n            by blast\n          moreover from h' have \"?body \\<noteq> {}\"\n            by blast\n          moreover have \"j > 0\" if \"j \\<in> ?body\" for j\n          proof -\n            from that obtain x where \"x \\<in> F\" and \"x \\<noteq> h\" and *: \"j =\n              (if 0 < a x \\<bullet> y - a x \\<bullet> w\n                then (b x - a x \\<bullet> w) / (a x \\<bullet> y - a x \\<bullet> w) else 1)\"\n              by blast\n            with awlt [of x] have \"a x \\<bullet> w < b x\"\n              by simp\n            with * show ?thesis\n              by simp\n          qed\n          ultimately have \"0 < inff\"\n            by (simp_all add: finite_less_Inf_iff inff_def)\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: field_split_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\" \"\\<not> (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\" shows \"polyhedron c\"\nby (metis assms face_of_imp_eq_affine_Int polyhedron_Int polyhedron_affine_hull 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 ((\\<in>) x) \\<notin> Collect ((\\<in>) (\\<Union>{A. A facet_of S}))\"\n        using xnot by fastforce\n      then have \"F \\<notin> Collect ((\\<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 blast+\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 ((`) 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)\"\n  by (subst polyhedron_linear_image_eq)\n    (auto simp: bij_uminus intro!: linear_uminus)\n\nsubsection\\<open>Relation between polytopes and polyhedra\\<close>\n\nproposition 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)\"\n  by (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)\"\n  by (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\"\n  by (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 \"\\<not> 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_eq_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_eq_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\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\"\n      and \"finite I\"\n    shows \"\\<exists>\\<G>. \\<Union>\\<G> = \\<Union>\\<F> \\<and>\n                 finite \\<G> \\<and>\n                 (\\<forall>C \\<in> \\<G>. \\<exists>D. D \\<in> \\<F> \\<and> C \\<subseteq> D) \\<and>\n                 (\\<forall>C \\<in> \\<F>. \\<forall>x \\<in> C. \\<exists>D. D \\<in> \\<G> \\<and> x \\<in> D \\<and> D \\<subseteq> C) \\<and>\n                 (\\<forall>X \\<in> \\<G>. polytope X) \\<and>\n                 (\\<forall>X \\<in> \\<G>. aff_dim X \\<le> d) \\<and>\n                 (\\<forall>X \\<in> \\<G>. \\<forall>Y \\<in> \\<G>. X \\<inter> Y face_of X) \\<and>\n                 (\\<forall>X \\<in> \\<G>. \\<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) (auto simp: assms)\nnext\n  case (insert ab I)\n  then obtain \\<G> where eq: \"\\<Union>\\<G> = \\<Union>\\<F>\" and \"finite \\<G>\"\n                   and sub1: \"\\<And>C. C \\<in> \\<G> \\<Longrightarrow> \\<exists>D. D \\<in> \\<F> \\<and> C \\<subseteq> D\"\n                   and sub2: \"\\<And>C x. C \\<in> \\<F> \\<and> x \\<in> C \\<Longrightarrow> \\<exists>D. D \\<in> \\<G> \\<and> x \\<in> D \\<and> D \\<subseteq> C\"\n                   and poly: \"\\<And>X. X \\<in> \\<G> \\<Longrightarrow> polytope X\"\n                   and aff: \"\\<And>X. X \\<in> \\<G> \\<Longrightarrow> aff_dim X \\<le> d\"\n                   and face: \"\\<And>X Y. \\<lbrakk>X \\<in> \\<G>; Y \\<in> \\<G>\\<rbrakk> \\<Longrightarrow> X \\<inter> Y face_of X\"\n                   and I: \"\\<And>X x y a b.  \\<lbrakk>X \\<in> \\<G>; 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}) ` \\<G> \\<union> (\\<lambda>X. X \\<inter> {x. a \\<bullet> x \\<ge> b}) ` \\<G>\"\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 \\<G>\\<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\"\n      by (auto simp: eqInt halfspace_Int_eq face_of_Int_Int face face_of_halfspace_le face_of_halfspace_ge)\n    show \"\\<forall>C \\<in> ?\\<G>. \\<exists>D. D \\<in> \\<F> \\<and> C \\<subseteq> D\"\n      using sub1 by force\n    show \"\\<forall>C\\<in>\\<F>. \\<forall>x\\<in>C. \\<exists>D. D \\<in> ?\\<G> \\<and> x \\<in> D \\<and> D \\<subseteq> C\"\n    proof (intro ballI)\n      fix C z\n      assume \"C \\<in> \\<F>\" \"z \\<in> C\"\n      with sub2 obtain D where D: \"D \\<in> \\<G>\" \"z \\<in> D\" \"D \\<subseteq> C\" by blast\n      have \"D \\<in> \\<G> \\<and> z \\<in> D \\<inter> {x. a \\<bullet> x \\<le> b} \\<and> D \\<inter> {x. a \\<bullet> x \\<le> b} \\<subseteq> C \\<or>\n            D \\<in> \\<G> \\<and> z \\<in> D \\<inter> {x. a \\<bullet> x \\<ge> b} \\<and> D \\<inter> {x. a \\<bullet> x \\<ge> b} \\<subseteq> C\"\n        using linorder_class.linear [of \"a \\<bullet> z\" b] D by blast\n      then show \"\\<exists>D. D \\<in> ?\\<G> \\<and> z \\<in> D \\<and> D \\<subseteq> C\"\n        by blast\n    qed\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\"\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\"\n                \"\\<And>C. C \\<in> \\<F>' \\<Longrightarrow> \\<exists>D. D \\<in> \\<F> \\<and> C \\<subseteq> D\"\n                \"\\<And>C x. C \\<in> \\<F> \\<and> x \\<in> C \\<Longrightarrow> \\<exists>D. D \\<in> \\<F>' \\<and> x \\<in> D \\<and> D \\<subseteq> C\"\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: field_split_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\"\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              and sub1: \"\\<And>C. C \\<in> \\<F>' \\<Longrightarrow> \\<exists>D. D \\<in> \\<F> \\<and> C \\<subseteq> D\"\n              and sub2: \"\\<And>C x. C \\<in> \\<F> \\<and> x \\<in> C \\<Longrightarrow> \\<exists>D. D \\<in> \\<F>' \\<and> x \\<in> D \\<and> D \\<subseteq> C\"\n    apply (rule exE [OF cell_subdivision_lemma])\n    using assms \\<open>finite I\\<close> apply auto\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 blast+\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[of X x y] \\<open>X \\<in> \\<F>'\\<close> that unfolding I_def by auto\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 sub1 sub2 \\<open>finite \\<F>'\\<close>)\nqed\n\n\nsubsection\\<open>Simplexes\\<close>\n\ntext\\<open>The notion of n-simplex for integer \\<^term>\\<open>n \\<ge> -1\\<close>\\<close>\n\ndefinition\\<^marker>\\<open>tag important\\<close> simplex :: \"int \\<Rightarrow> 'a::euclidean_space set \\<Rightarrow> bool\" (infix \"simplex\" 50)\n  where \"n simplex S \\<equiv> \\<exists>C. \\<not> affine_dependent C \\<and> int(card C) = n + 1 \\<and> S = convex hull C\"\n\nlemma simplex:\n    \"n simplex S \\<longleftrightarrow> (\\<exists>C. finite C \\<and>\n                       \\<not> affine_dependent C \\<and>\n                       int(card C) = n + 1 \\<and>\n                       S = convex hull C)\"\n  by (auto simp add: simplex_def intro: aff_independent_finite)\n\nlemma simplex_convex_hull:\n   \"\\<not> affine_dependent C \\<and> int(card C) = n + 1 \\<Longrightarrow> n simplex (convex hull C)\"\n  by (auto simp add: simplex_def)\n\nlemma convex_simplex: \"n simplex S \\<Longrightarrow> convex S\"\n  by (metis convex_convex_hull simplex_def)\n\nlemma compact_simplex: \"n simplex S \\<Longrightarrow> compact S\"\n  unfolding simplex\n  using finite_imp_compact_convex_hull by blast\n\nlemma closed_simplex: \"n simplex S \\<Longrightarrow> closed S\"\n  by (simp add: compact_imp_closed compact_simplex)\n\nlemma simplex_imp_polytope:\n   \"n simplex S \\<Longrightarrow> polytope S\"\n  unfolding simplex_def polytope_def\n  using aff_independent_finite by blast\n\nlemma simplex_imp_polyhedron:\n   \"n simplex S \\<Longrightarrow> polyhedron S\"\n  by (simp add: polytope_imp_polyhedron simplex_imp_polytope)\n\nlemma simplex_dim_ge: \"n simplex S \\<Longrightarrow> -1 \\<le> n\"\n  by (metis (no_types, hide_lams) aff_dim_geq affine_independent_iff_card diff_add_cancel diff_diff_eq2 simplex_def)\n\nlemma simplex_empty [simp]: \"n simplex {} \\<longleftrightarrow> n = -1\"\nproof\n  assume \"n simplex {}\"\n  then show \"n = -1\"\n    unfolding simplex by (metis card_empty convex_hull_eq_empty diff_0 diff_eq_eq of_nat_0)\nnext\n  assume \"n = -1\" then show \"n simplex {}\"\n    by (fastforce simp: simplex)\nqed\n\nlemma simplex_minus_1 [simp]: \"-1 simplex S \\<longleftrightarrow> S = {}\"\n  by (metis simplex cancel_comm_monoid_add_class.diff_cancel card_0_eq diff_minus_eq_add of_nat_eq_0_iff simplex_empty)\n\n\nlemma aff_dim_simplex:\n   \"n simplex S \\<Longrightarrow> aff_dim S = n\"\n  by (metis simplex add.commute add_diff_cancel_left' aff_dim_convex_hull affine_independent_iff_card)\n\nlemma zero_simplex_sing: \"0 simplex {a}\"\n  apply (simp add: simplex_def)\n  by (metis affine_independent_1 card_empty card_insert_disjoint convex_hull_singleton empty_iff finite.emptyI)\n\nlemma simplex_sing [simp]: \"n simplex {a} \\<longleftrightarrow> n = 0\"\n  using aff_dim_simplex aff_dim_sing zero_simplex_sing by blast\n\nlemma simplex_zero: \"0 simplex S \\<longleftrightarrow> (\\<exists>a. S = {a})\"\napply (auto simp: )\n  using aff_dim_eq_0 aff_dim_simplex by blast\n\nlemma one_simplex_segment: \"a \\<noteq> b \\<Longrightarrow> 1 simplex closed_segment a b\"\n  apply (simp add: simplex_def)\n  apply (rule_tac x=\"{a,b}\" in exI)\n  apply (auto simp: segment_convex_hull)\n  done\n\nlemma simplex_segment_cases:\n   \"(if a = b then 0 else 1) simplex closed_segment a b\"\n  by (auto simp: one_simplex_segment)\n\nlemma simplex_segment:\n   \"\\<exists>n. n simplex closed_segment a b\"\n  using simplex_segment_cases by metis\n\nlemma polytope_lowdim_imp_simplex:\n  assumes \"polytope P\" \"aff_dim P \\<le> 1\"\n  obtains n where \"n simplex P\"\nproof (cases \"P = {}\")\n  case True\n  then show ?thesis\n    by (simp add: that)\nnext\n  case False\n  then show ?thesis\n    by (metis assms compact_convex_collinear_segment collinear_aff_dim polytope_imp_compact polytope_imp_convex simplex_segment_cases that)\nqed\n\nlemma simplex_insert_dimplus1:\n  fixes n::int\n  assumes \"n simplex S\" and a: \"a \\<notin> affine hull S\"\n  shows \"(n+1) simplex (convex hull (insert a S))\"\nproof -\n  obtain C where C: \"finite C\" \"\\<not> affine_dependent C\" \"int(card C) = n+1\" and S: \"S = convex hull C\"\n    using assms unfolding simplex by force\n  show ?thesis\n    unfolding simplex\n  proof (intro exI conjI)\n      have \"aff_dim S = n\"\n        using aff_dim_simplex assms(1) by blast\n      moreover have \"a \\<notin> affine hull C\"\n        using S a affine_hull_convex_hull by blast\n      moreover have \"a \\<notin> C\"\n          using S a hull_inc by fastforce\n      ultimately show \"\\<not> affine_dependent (insert a C)\"\n        by (simp add: C S aff_dim_convex_hull aff_dim_insert affine_independent_iff_card)\n  next\n    have \"a \\<notin> C\"\n      using S a hull_inc by fastforce\n    then show \"int (card (insert a C)) = n + 1 + 1\"\n      by (simp add: C)\n  next\n    show \"convex hull insert a S = convex hull (insert a C)\"\n      by (simp add: S convex_hull_insert_segments)\n  qed (use C in auto)\nqed\n\nsubsection \\<open>Simplicial complexes and triangulations\\<close>\n\ndefinition\\<^marker>\\<open>tag important\\<close> simplicial_complex where\n \"simplicial_complex \\<C> \\<equiv>\n        finite \\<C> \\<and>\n        (\\<forall>S \\<in> \\<C>. \\<exists>n. n simplex S) \\<and>\n        (\\<forall>F S. S \\<in> \\<C> \\<and> F face_of S \\<longrightarrow> F \\<in> \\<C>) \\<and>\n        (\\<forall>S S'. S \\<in> \\<C> \\<and> S' \\<in> \\<C> \\<longrightarrow> (S \\<inter> S') face_of S)\"\n\ndefinition\\<^marker>\\<open>tag important\\<close> triangulation where\n \"triangulation \\<T> \\<equiv>\n        finite \\<T> \\<and>\n        (\\<forall>T \\<in> \\<T>. \\<exists>n. n simplex T) \\<and>\n        (\\<forall>T T'. T \\<in> \\<T> \\<and> T' \\<in> \\<T> \\<longrightarrow> (T \\<inter> T') face_of T)\"\n\n\nsubsection\\<open>Refining a cell complex to a simplicial complex\\<close>\n\nproposition convex_hull_insert_Int_eq:\n  fixes z :: \"'a :: euclidean_space\"\n  assumes z: \"z \\<in> rel_interior S\"\n      and T: \"T \\<subseteq> rel_frontier S\"\n      and U: \"U \\<subseteq> rel_frontier S\"\n      and \"convex S\" \"convex T\" \"convex U\"\n  shows \"convex hull (insert z T) \\<inter> convex hull (insert z U) = convex hull (insert z (T \\<inter> U))\"\n    (is \"?lhs = ?rhs\")\nproof\n  show \"?lhs \\<subseteq> ?rhs\"\n  proof (cases \"T={} \\<or> U={}\")\n    case True then show ?thesis by auto\n  next\n    case False\n    then have \"T \\<noteq> {}\" \"U \\<noteq> {}\" by auto\n    have TU: \"convex (T \\<inter> U)\"\n      by (simp add: \\<open>convex T\\<close> \\<open>convex U\\<close> convex_Int)\n    have \"(\\<Union>x\\<in>T. closed_segment z x) \\<inter> (\\<Union>x\\<in>U. closed_segment z x)\n          \\<subseteq> (if T \\<inter> U = {} then {z} else \\<Union>((closed_segment z) ` (T \\<inter> U)))\" (is \"_ \\<subseteq> ?IF\")\n    proof clarify\n      fix x t u\n      assume xt: \"x \\<in> closed_segment z t\"\n        and xu: \"x \\<in> closed_segment z u\"\n        and \"t \\<in> T\" \"u \\<in> U\"\n      then have ne: \"t \\<noteq> z\" \"u \\<noteq> z\"\n        using T U z unfolding rel_frontier_def by blast+\n      show \"x \\<in> ?IF\"\n      proof (cases \"x = z\")\n        case True then show ?thesis by auto\n      next\n        case False\n        have t: \"t \\<in> closure S\"\n          using T \\<open>t \\<in> T\\<close> rel_frontier_def by auto\n        have u: \"u \\<in> closure S\"\n          using U \\<open>u \\<in> U\\<close> rel_frontier_def by auto\n        show ?thesis\n        proof (cases \"t = u\")\n          case True\n          then show ?thesis\n            using \\<open>t \\<in> T\\<close> \\<open>u \\<in> U\\<close> xt by auto\n        next\n          case False\n          have tnot: \"t \\<notin> closed_segment u z\"\n          proof -\n            have \"t \\<in> closure S - rel_interior S\"\n              using T \\<open>t \\<in> T\\<close> rel_frontier_def by blast\n            then have \"t \\<notin> open_segment z u\"\n              by (meson DiffD2 rel_interior_closure_convex_segment [OF \\<open>convex S\\<close> z u] subsetD)\n            then show ?thesis\n              by (simp add: \\<open>t \\<noteq> u\\<close> \\<open>t \\<noteq> z\\<close> open_segment_commute open_segment_def)\n          qed\n          moreover have \"u \\<notin> closed_segment z t\"\n            using rel_interior_closure_convex_segment [OF \\<open>convex S\\<close> z t] \\<open>u \\<in> U\\<close> \\<open>u \\<noteq> z\\<close>\n              U [unfolded rel_frontier_def] tnot\n            by (auto simp: closed_segment_eq_open)\n          ultimately\n          have \"\\<not>(between (t,u) z | between (u,z) t | between (z,t) u)\" if \"x \\<noteq> z\"\n            using that xt xu\n            apply (simp add: between_mem_segment [symmetric])\n            by (metis between_commute between_trans_2 between_antisym)\n          then have \"\\<not> collinear {t, z, u}\" if \"x \\<noteq> z\"\n            by (auto simp: that collinear_between_cases between_commute)\n          moreover have \"collinear {t, z, x}\"\n            by (metis closed_segment_commute collinear_2 collinear_closed_segment collinear_triples ends_in_segment(1) insert_absorb insert_absorb2 xt)\n          moreover have \"collinear {z, x, u}\"\n            by (metis closed_segment_commute collinear_2 collinear_closed_segment collinear_triples ends_in_segment(1) insert_absorb insert_absorb2 xu)\n          ultimately have False\n            using collinear_3_trans [of t z x u] \\<open>x \\<noteq> z\\<close> by blast\n          then show ?thesis by metis\n        qed\n      qed\n    qed\n    then show ?thesis\n      using False \\<open>convex T\\<close> \\<open>convex U\\<close> TU\n      by (simp add: convex_hull_insert_segments hull_same split: if_split_asm)\n  qed\n  show \"?rhs \\<subseteq> ?lhs\"\n    by (metis inf_greatest hull_mono inf.cobounded1 inf.cobounded2 insert_mono)\nqed\n\nlemma simplicial_subdivision_aux:\n  assumes \"finite \\<M>\"\n      and \"\\<And>C. C \\<in> \\<M> \\<Longrightarrow> polytope C\"\n      and \"\\<And>C. C \\<in> \\<M> \\<Longrightarrow> aff_dim C \\<le> of_nat n\"\n      and \"\\<And>C F. \\<lbrakk>C \\<in> \\<M>; F face_of C\\<rbrakk> \\<Longrightarrow> F \\<in> \\<M>\"\n      and \"\\<And>C1 C2. \\<lbrakk>C1 \\<in> \\<M>; C2 \\<in> \\<M>\\<rbrakk> \\<Longrightarrow> C1 \\<inter> C2 face_of C1\"\n    shows \"\\<exists>\\<T>. simplicial_complex \\<T> \\<and>\n                (\\<forall>K \\<in> \\<T>. aff_dim K \\<le> of_nat n) \\<and>\n                \\<Union>\\<T> = \\<Union>\\<M> \\<and>\n                (\\<forall>C \\<in> \\<M>. \\<exists>F. finite F \\<and> F \\<subseteq> \\<T> \\<and> C = \\<Union>F) \\<and>\n                (\\<forall>K \\<in> \\<T>. \\<exists>C. C \\<in> \\<M> \\<and> K \\<subseteq> C)\"\n  using assms\nproof (induction n arbitrary: \\<M> rule: less_induct)\n  case (less n)\n  then have poly\\<M>: \"\\<And>C. C \\<in> \\<M> \\<Longrightarrow> polytope C\"\n    and aff\\<M>:    \"\\<And>C. C \\<in> \\<M> \\<Longrightarrow> aff_dim C \\<le> of_nat n\"\n    and face\\<M>:   \"\\<And>C F. \\<lbrakk>C \\<in> \\<M>; F face_of C\\<rbrakk> \\<Longrightarrow> F \\<in> \\<M>\"\n    and intface\\<M>: \"\\<And>C1 C2. \\<lbrakk>C1 \\<in> \\<M>; C2 \\<in> \\<M>\\<rbrakk> \\<Longrightarrow> C1 \\<inter> C2 face_of C1\"\n    by metis+\n  show ?case\n  proof (cases \"n \\<le> 1\")\n    case True\n    have \"\\<And>s. \\<lbrakk>n \\<le> 1; s \\<in> \\<M>\\<rbrakk> \\<Longrightarrow> \\<exists>m. m simplex s\"\n      using poly\\<M> aff\\<M> by (force intro: polytope_lowdim_imp_simplex)\n    then show ?thesis\n      unfolding simplicial_complex_def\n      apply (rule_tac x=\"\\<M>\" in exI)\n      using True by (auto simp: less.prems)\n  next\n    case False\n    define \\<S> where \"\\<S> \\<equiv> {C \\<in> \\<M>. aff_dim C < n}\"\n    have \"finite \\<S>\" \"\\<And>C. C \\<in> \\<S> \\<Longrightarrow> polytope C\" \"\\<And>C. C \\<in> \\<S> \\<Longrightarrow> aff_dim C \\<le> int (n - 1)\"\n      \"\\<And>C F. \\<lbrakk>C \\<in> \\<S>; F face_of C\\<rbrakk> \\<Longrightarrow> F \\<in> \\<S>\"\n      \"\\<And>C1 C2. \\<lbrakk>C1 \\<in> \\<S>; C2 \\<in> \\<S>\\<rbrakk>  \\<Longrightarrow> C1 \\<inter> C2 face_of C1\"\n      using less.prems\n          apply (auto simp: \\<S>_def)\n      by (metis aff_dim_subset face_of_imp_subset less_le not_le)\n    with less.IH [of \"n-1\" \\<S>] False\n    obtain \\<U> where \"simplicial_complex \\<U>\"\n      and aff_dim\\<U>: \"\\<And>K. K \\<in> \\<U> \\<Longrightarrow> aff_dim K \\<le> int (n - 1)\"\n      and        \"\\<Union>\\<U> = \\<Union>\\<S>\"\n      and fin\\<U>:  \"\\<And>C. C \\<in> \\<S> \\<Longrightarrow> \\<exists>F. finite F \\<and> F \\<subseteq> \\<U> \\<and> C = \\<Union>F\"\n      and C\\<U>:    \"\\<And>K. K \\<in> \\<U> \\<Longrightarrow> \\<exists>C. C \\<in> \\<S> \\<and> K \\<subseteq> C\"\n      by auto\n    then have \"finite \\<U>\"\n      and simpl\\<U>: \"\\<And>S. S \\<in> \\<U> \\<Longrightarrow> \\<exists>n. n simplex S\"\n      and face\\<U>:  \"\\<And>F S. \\<lbrakk>S \\<in> \\<U>; F face_of S\\<rbrakk> \\<Longrightarrow> F \\<in> \\<U>\"\n      and faceI\\<U>: \"\\<And>S S'. \\<lbrakk>S \\<in> \\<U>; S' \\<in> \\<U>\\<rbrakk> \\<Longrightarrow> (S \\<inter> S') face_of S\"\n      by (auto simp: simplicial_complex_def)\n    define \\<N> where \"\\<N> \\<equiv> {C \\<in> \\<M>. aff_dim C = n}\"\n    have \"finite \\<N>\"\n      by (simp add: \\<N>_def less.prems(1))\n    have poly\\<N>: \"\\<And>C. C \\<in> \\<N> \\<Longrightarrow> polytope C\"\n      and convex\\<N>: \"\\<And>C. C \\<in> \\<N> \\<Longrightarrow> convex C\"\n      and closed\\<N>: \"\\<And>C. C \\<in> \\<N> \\<Longrightarrow> closed C\"\n      by (auto simp: \\<N>_def poly\\<M> polytope_imp_convex polytope_imp_closed)\n    have in_rel_interior: \"(SOME z. z \\<in> rel_interior C) \\<in> rel_interior C\" if \"C \\<in> \\<N>\" for C\n      using that poly\\<M> polytope_imp_convex rel_interior_aff_dim some_in_eq by (fastforce simp: \\<N>_def)\n    have *: \"\\<exists>T. \\<not> affine_dependent T \\<and> card T \\<le> n \\<and> aff_dim K < n \\<and> K = convex hull T\"\n      if \"K \\<in> \\<U>\" for K\n    proof -\n      obtain r where r: \"r simplex K\"\n        using \\<open>K \\<in> \\<U>\\<close> simpl\\<U> by blast\n      have \"r = aff_dim K\"\n        using \\<open>r simplex K\\<close> aff_dim_simplex by blast\n      with r\n      show ?thesis\n        unfolding simplex_def\n        using False \\<open>\\<And>K. K \\<in> \\<U> \\<Longrightarrow> aff_dim K \\<le> int (n - 1)\\<close> that by fastforce\n    qed\n    have ahK_C_disjoint: \"affine hull K \\<inter> rel_interior C = {}\"\n      if \"C \\<in> \\<N>\" \"K \\<in> \\<U>\" \"K \\<subseteq> rel_frontier C\" for C K\n    proof -\n      have \"convex C\" \"closed C\"\n        by (auto simp: convex\\<N> closed\\<N> \\<open>C \\<in> \\<N>\\<close>)\n      obtain F where F: \"F face_of C\" and \"F \\<noteq> C\" \"K \\<subseteq> F\"\n      proof -\n        obtain L where \"L \\<in> \\<S>\" \"K \\<subseteq> L\"\n          using \\<open>K \\<in> \\<U>\\<close> C\\<U> by blast\n        have \"K \\<le> rel_frontier C\"\n          by (simp add: \\<open>K \\<subseteq> rel_frontier C\\<close>)\n        also have \"... \\<le> C\"\n          by (simp add: \\<open>closed C\\<close> rel_frontier_def subset_iff)\n        finally have \"K \\<subseteq> C\" .\n        have \"L \\<inter> C face_of C\"\n          using \\<N>_def \\<S>_def \\<open>C \\<in> \\<N>\\<close> \\<open>L \\<in> \\<S>\\<close> intface\\<M> by (simp add: inf_commute)\n        moreover have \"L \\<inter> C \\<noteq> C\"\n          using \\<open>C \\<in> \\<N>\\<close> \\<open>L \\<in> \\<S>\\<close>\n          apply (clarsimp simp: \\<N>_def \\<S>_def)\n          by (metis aff_dim_subset inf_le1 not_le)\n        moreover have \"K \\<subseteq> L \\<inter> C\"\n          using \\<open>C \\<in> \\<N>\\<close> \\<open>L \\<in> \\<S>\\<close> \\<open>K \\<subseteq> C\\<close> \\<open>K \\<subseteq> L\\<close>\n          by (auto simp: \\<N>_def \\<S>_def)\n        ultimately show ?thesis using that by metis\n      qed\n      have \"affine hull F \\<inter> rel_interior C = {}\"\n        by (rule affine_hull_face_of_disjoint_rel_interior [OF \\<open>convex C\\<close> F \\<open>F \\<noteq> C\\<close>])\n      with hull_mono [OF \\<open>K \\<subseteq> F\\<close>]\n      show \"affine hull K \\<inter> rel_interior C = {}\"\n        by fastforce\n    qed\n    let ?\\<T> = \"(\\<Union>C \\<in> \\<N>. \\<Union>K \\<in> \\<U> \\<inter> Pow (rel_frontier C).\n                     {convex hull (insert (SOME z. z \\<in> rel_interior C) K)})\"\n    have \"\\<exists>\\<T>. simplicial_complex \\<T> \\<and>\n              (\\<forall>K \\<in> \\<T>. aff_dim K \\<le> of_nat n) \\<and>\n              (\\<forall>C \\<in> \\<M>. \\<exists>F. F \\<subseteq> \\<T> \\<and> C = \\<Union>F) \\<and>\n              (\\<forall>K \\<in> \\<T>. \\<exists>C. C \\<in> \\<M> \\<and> K \\<subseteq> C)\"\n    proof (rule exI, intro conjI ballI)\n      show \"simplicial_complex (\\<U> \\<union> ?\\<T>)\"\n        unfolding simplicial_complex_def\n      proof (intro conjI impI ballI allI)\n        show \"finite (\\<U> \\<union> ?\\<T>)\"\n          using \\<open>finite \\<U>\\<close> \\<open>finite \\<N>\\<close> by simp\n        show \"\\<exists>n. n simplex S\" if \"S \\<in> \\<U> \\<union> ?\\<T>\" for S\n          using that ahK_C_disjoint in_rel_interior simpl\\<U> simplex_insert_dimplus1 by fastforce\n        show \"F \\<in> \\<U> \\<union> ?\\<T>\" if S: \"S \\<in> \\<U> \\<union> ?\\<T> \\<and> F face_of S\" for F S\n        proof -\n          have \"F \\<in> \\<U>\" if \"S \\<in> \\<U>\"\n            using S face\\<U> that by blast\n          moreover have \"F \\<in> \\<U> \\<union> ?\\<T>\"\n            if \"F face_of S\" \"C \\<in> \\<N>\" \"K \\<in> \\<U>\" and \"K \\<subseteq> rel_frontier C\"\n              and S: \"S = convex hull insert (SOME z. z \\<in> rel_interior C) K\" for C K\n          proof -\n            let ?z = \"SOME z. z \\<in> rel_interior C\"\n            have \"?z \\<in> rel_interior C\"\n              by (simp add: in_rel_interior \\<open>C \\<in> \\<N>\\<close>)\n            moreover\n            obtain I where \"\\<not> affine_dependent I\" \"card I \\<le> n\" \"aff_dim K < int n\" \"K = convex hull I\"\n              using * [OF \\<open>K \\<in> \\<U>\\<close>] by auto\n            ultimately have \"?z \\<notin> affine hull I\"\n              using ahK_C_disjoint affine_hull_convex_hull that by blast\n            have \"compact I\" \"finite I\"\n              by (auto simp: \\<open>\\<not> affine_dependent I\\<close> aff_independent_finite finite_imp_compact)\n            moreover have \"F face_of convex hull insert ?z I\"\n              by (metis S \\<open>F face_of S\\<close> \\<open>K = convex hull I\\<close> convex_hull_eq_empty convex_hull_insert_segments hull_hull)\n            ultimately obtain J where \"J \\<subseteq> insert ?z I\" \"F = convex hull J\"\n              using face_of_convex_hull_subset [of \"insert ?z I\" F] by auto\n            show ?thesis\n            proof (cases \"?z \\<in> J\")\n              case True\n              have \"F \\<in> (\\<Union>K\\<in>\\<U> \\<inter> Pow (rel_frontier C). {convex hull insert ?z K})\"\n              proof\n                have \"convex hull (J - {?z}) face_of K\"\n                  by (metis True \\<open>J \\<subseteq> insert ?z I\\<close> \\<open>K = convex hull I\\<close> \\<open>\\<not> affine_dependent I\\<close> face_of_convex_hull_affine_independent subset_insert_iff)\n                then have \"convex hull (J - {?z}) \\<in> \\<U>\"\n                  by (rule face\\<U> [OF \\<open>K \\<in> \\<U>\\<close>])\n                moreover\n                have \"\\<And>x. x \\<in> convex hull (J - {?z}) \\<Longrightarrow> x \\<in> rel_frontier C\"\n                  by (metis True \\<open>J \\<subseteq> insert ?z I\\<close> \\<open>K = convex hull I\\<close> subsetD hull_mono subset_insert_iff that(4))\n                ultimately show \"convex hull (J - {?z}) \\<in> \\<U> \\<inter> Pow (rel_frontier C)\" by auto\n                let ?F = \"convex hull insert ?z (convex hull (J - {?z}))\"\n                have \"F \\<subseteq> ?F\"\n                  apply (clarsimp simp: \\<open>F = convex hull J\\<close>)\n                  by (metis True subsetD hull_mono hull_subset subset_insert_iff)\n                moreover have \"?F \\<subseteq> F\"\n                  apply (clarsimp simp: \\<open>F = convex hull J\\<close>)\n                  by (metis (no_types, lifting) True convex_hull_eq_empty convex_hull_insert_segments hull_hull insert_Diff)\n                ultimately\n                show \"F \\<in> {?F}\" by auto\n              qed\n              with \\<open>C\\<in>\\<N>\\<close> show ?thesis by auto\n            next\n              case False\n              then have \"F \\<in> \\<U>\"\n                using face_of_convex_hull_affine_independent [OF \\<open>\\<not> affine_dependent I\\<close>]\n                by (metis Int_absorb2 Int_insert_right_if0 \\<open>F = convex hull J\\<close> \\<open>J \\<subseteq> insert ?z I\\<close> \\<open>K = convex hull I\\<close> face\\<U> inf_le2 \\<open>K \\<in> \\<U>\\<close>)\n              then show \"F \\<in> \\<U> \\<union> ?\\<T>\"\n                by blast\n            qed\n          qed\n          ultimately show ?thesis\n            using that by auto\n        qed\n        have \\<section>: \"X \\<inter> Y face_of X \\<and> X \\<inter> Y face_of Y\"\n          if XY: \"X \\<in> \\<U>\" \"Y \\<in> ?\\<T>\" for X Y\n        proof -\n          obtain C K\n            where \"C \\<in> \\<N>\" \"K \\<in> \\<U>\" \"K \\<subseteq> rel_frontier C\"\n              and Y: \"Y = convex hull insert (SOME z. z \\<in> rel_interior C) K\"\n            using XY by blast\n          have \"convex C\"\n            by (simp add: \\<open>C \\<in> \\<N>\\<close> convex\\<N>)\n          have \"K \\<subseteq> C\"\n            by (metis DiffE \\<open>C \\<in> \\<N>\\<close> \\<open>K \\<subseteq> rel_frontier C\\<close> closed\\<N> closure_closed rel_frontier_def subset_iff)\n          let ?z = \"(SOME z. z \\<in> rel_interior C)\"\n          have z: \"?z \\<in> rel_interior C\"\n            using \\<open>C \\<in> \\<N>\\<close> in_rel_interior by blast\n          obtain D where \"D \\<in> \\<S>\" \"X \\<subseteq> D\"\n            using C\\<U> \\<open>X \\<in> \\<U>\\<close> by blast\n          have \"D \\<inter> rel_interior C = (C \\<inter> D) \\<inter> rel_interior C\"\n            using rel_interior_subset by blast\n          also have \"(C \\<inter> D) \\<inter> rel_interior C = {}\"\n          proof (rule face_of_disjoint_rel_interior)\n            show \"C \\<inter> D face_of C\"\n              using \\<N>_def \\<S>_def \\<open>C \\<in> \\<N>\\<close> \\<open>D \\<in> \\<S>\\<close> intface\\<M> by blast\n            show \"C \\<inter> D \\<noteq> C\"\n              by (metis (mono_tags, lifting) Int_lower2 \\<N>_def \\<S>_def \\<open>C \\<in> \\<N>\\<close> \\<open>D \\<in> \\<S>\\<close> aff_dim_subset mem_Collect_eq not_le)\n          qed\n          finally have DC: \"D \\<inter> rel_interior C = {}\" .\n          have eq: \"X \\<inter> convex hull (insert ?z K) = X \\<inter> convex hull K\"\n            apply (rule Int_convex_hull_insert_rel_exterior [OF \\<open>convex C\\<close> \\<open>K \\<subseteq> C\\<close> z])\n            using DC by (meson \\<open>X \\<subseteq> D\\<close> disjnt_def disjnt_subset1)\n          obtain I where I: \"\\<not> affine_dependent I\"\n            and Keq: \"K = convex hull I\" and [simp]: \"convex hull K = K\"\n            using \"*\" \\<open>K \\<in> \\<U>\\<close> by force\n          then have \"?z \\<notin> affine hull I\"\n            using ahK_C_disjoint \\<open>C \\<in> \\<N>\\<close> \\<open>K \\<in> \\<U>\\<close> \\<open>K \\<subseteq> rel_frontier C\\<close> affine_hull_convex_hull z by blast\n          have \"X \\<inter> K face_of K\"\n            by (simp add: XY(1) \\<open>K \\<in> \\<U>\\<close> faceI\\<U> inf_commute)\n          also have \"... face_of convex hull insert ?z K\"\n            by (metis I Keq \\<open>?z \\<notin> affine hull I\\<close> aff_independent_finite convex_convex_hull face_of_convex_hull_insert face_of_refl hull_insert)\n          finally have \"X \\<inter> K face_of convex hull insert ?z K\" .\n          then show ?thesis\n            by (simp add: XY(1) Y \\<open>K \\<in> \\<U>\\<close> eq faceI\\<U>)\n        qed\n\n        show \"S \\<inter> S' face_of S\"\n          if \"S \\<in> \\<U> \\<union> ?\\<T> \\<and> S' \\<in> \\<U> \\<union> ?\\<T>\" for S S'\n          using that\n        proof (elim conjE UnE)\n          fix X Y\n          assume \"X \\<in> \\<U>\" and \"Y \\<in> \\<U>\"\n          then show \"X \\<inter> Y face_of X\"\n            by (simp add: faceI\\<U>)\n        next\n          fix X Y\n          assume XY: \"X \\<in> \\<U>\" \"Y \\<in> ?\\<T>\"\n          then show \"X \\<inter> Y face_of X\" \"Y \\<inter> X face_of Y\"\n            using \\<section> [OF XY] by (auto simp: Int_commute)\n        next\n          fix X Y\n          assume XY: \"X \\<in> ?\\<T>\" \"Y \\<in> ?\\<T>\"\n          show \"X \\<inter> Y face_of X\"\n          proof -\n            obtain C K D L\n              where \"C \\<in> \\<N>\" \"K \\<in> \\<U>\" \"K \\<subseteq> rel_frontier C\"\n                and X: \"X = convex hull insert (SOME z. z \\<in> rel_interior C) K\"\n                and \"D \\<in> \\<N>\" \"L \\<in> \\<U>\" \"L \\<subseteq> rel_frontier D\"\n                and Y: \"Y = convex hull insert (SOME z. z \\<in> rel_interior D) L\"\n              using XY by blast\n            let ?z = \"(SOME z. z \\<in> rel_interior C)\"\n            have z: \"?z \\<in> rel_interior C\"\n              using \\<open>C \\<in> \\<N>\\<close> in_rel_interior by blast\n            have \"convex C\"\n              by (simp add: \\<open>C \\<in> \\<N>\\<close> convex\\<N>)\n            have \"convex K\"\n              using \"*\" \\<open>K \\<in> \\<U>\\<close> by blast\n            have \"convex L\"\n              by (meson \\<open>L \\<in> \\<U>\\<close> convex_simplex simpl\\<U>)\n            show ?thesis\n            proof (cases \"D=C\")\n              case True\n              then have \"L \\<subseteq> rel_frontier C\"\n                using \\<open>L \\<subseteq> rel_frontier D\\<close> by auto\n              show ?thesis\n                apply (simp add: X Y True)\n                apply (simp add: convex_hull_insert_Int_eq [OF z] \\<open>K \\<subseteq> rel_frontier C\\<close> \\<open>L \\<subseteq> rel_frontier C\\<close> \\<open>convex C\\<close> \\<open>convex K\\<close> \\<open>convex L\\<close>)\n                using face_of_polytope_insert2\n                by (metis \"*\" IntI \\<open>C \\<in> \\<N>\\<close> \\<open>K \\<in> \\<U>\\<close> \\<open>L \\<in> \\<U>\\<close>\\<open>K \\<subseteq> rel_frontier C\\<close> \\<open>L \\<subseteq> rel_frontier C\\<close> aff_independent_finite ahK_C_disjoint empty_iff faceI\\<U> polytope_convex_hull z)\n            next\n              case False\n              have \"convex D\"\n                by (simp add: \\<open>D \\<in> \\<N>\\<close> convex\\<N>)\n              have \"K \\<subseteq> C\"\n                by (metis DiffE \\<open>C \\<in> \\<N>\\<close> \\<open>K \\<subseteq> rel_frontier C\\<close> closed\\<N> closure_closed rel_frontier_def subset_eq)\n              have \"L \\<subseteq> D\"\n                by (metis DiffE \\<open>D \\<in> \\<N>\\<close> \\<open>L \\<subseteq> rel_frontier D\\<close> closed\\<N> closure_closed rel_frontier_def subset_eq)\n              let ?w = \"(SOME w. w \\<in> rel_interior D)\"\n              have w: \"?w \\<in> rel_interior D\"\n                using \\<open>D \\<in> \\<N>\\<close> in_rel_interior by blast\n              have \"C \\<inter> rel_interior D = (D \\<inter> C) \\<inter> rel_interior D\"\n                using rel_interior_subset by blast\n              also have \"(D \\<inter> C) \\<inter> rel_interior D = {}\"\n              proof (rule face_of_disjoint_rel_interior)\n                show \"D \\<inter> C face_of D\"\n                  using \\<N>_def \\<open>C \\<in> \\<N>\\<close> \\<open>D \\<in> \\<N>\\<close> intface\\<M> by blast\n                have \"D \\<in> \\<M> \\<and> aff_dim D = int n\"\n                  using \\<N>_def \\<open>D \\<in> \\<N>\\<close> by blast\n                moreover have \"C \\<in> \\<M> \\<and> aff_dim C = int n\"\n                  using \\<N>_def \\<open>C \\<in> \\<N>\\<close> by blast\n                ultimately show \"D \\<inter> C \\<noteq> D\"\n                  by (metis Int_commute False face_of_aff_dim_lt inf.idem inf_le1 intface\\<M> not_le poly\\<M> polytope_imp_convex)\n              qed\n              finally have CD: \"C \\<inter> (rel_interior D) = {}\" .\n              have zKC: \"(convex hull insert ?z K) \\<subseteq> C\"\n                by (metis DiffE \\<open>C \\<in> \\<N>\\<close> \\<open>K \\<subseteq> rel_frontier C\\<close> closed\\<N> closure_closed convex\\<N> hull_minimal insert_subset rel_frontier_def rel_interior_subset subset_iff z)\n              have eq: \"convex hull (insert ?z K) \\<inter> convex hull (insert ?w L) =\n                          convex hull (insert ?z K) \\<inter> convex hull L\"\n                apply (rule Int_convex_hull_insert_rel_exterior [OF \\<open>convex D\\<close> \\<open>L \\<subseteq> D\\<close> w])\n                using zKC CD apply (force simp: disjnt_def)\n                done\n              have ch_id: \"convex hull K = K\" \"convex hull L = L\"\n                using \"*\" \\<open>K \\<in> \\<U>\\<close> \\<open>L \\<in> \\<U>\\<close> hull_same by auto\n              have \"convex C\"\n                by (simp add: \\<open>C \\<in> \\<N>\\<close> convex\\<N>)\n              have \"convex hull (insert ?z K) \\<inter> L = L \\<inter> convex hull (insert ?z K)\"\n                by blast\n              also have \"... = convex hull K \\<inter> L\"\n              proof (subst Int_convex_hull_insert_rel_exterior [OF \\<open>convex C\\<close> \\<open>K \\<subseteq> C\\<close> z])\n                have \"(C \\<inter> D) \\<inter> rel_interior C = {}\"\n                proof (rule face_of_disjoint_rel_interior)\n                  show \"C \\<inter> D face_of C\"\n                    using \\<N>_def \\<open>C \\<in> \\<N>\\<close> \\<open>D \\<in> \\<N>\\<close> intface\\<M> by blast\n                  have \"D \\<in> \\<M>\" \"aff_dim D = int n\"\n                    using \\<N>_def \\<open>D \\<in> \\<N>\\<close> by fastforce+\n                  moreover have \"C \\<in> \\<M>\" \"aff_dim C = int n\"\n                    using \\<N>_def \\<open>C \\<in> \\<N>\\<close> by fastforce+\n                  ultimately have \"aff_dim D + - 1 * aff_dim C \\<le> 0\"\n                    by fastforce\n                  then have \"\\<not> C face_of D\"\n                    using False \\<open>convex D\\<close> face_of_aff_dim_lt by fastforce\n                  show \"C \\<inter> D \\<noteq> C\"\n                    by (metis inf_commute \\<open>C \\<in> \\<M>\\<close> \\<open>D \\<in> \\<M>\\<close> \\<open>\\<not> C face_of D\\<close> intface\\<M>)\n                qed\n                then have \"D \\<inter> rel_interior C = {}\"\n                  by (metis inf.absorb_iff2 inf_assoc inf_sup_aci(1) rel_interior_subset)\n                then show \"disjnt L (rel_interior C)\"\n                  by (meson \\<open>L \\<subseteq> D\\<close> disjnt_def disjnt_subset1)\n              next\n                show \"L \\<inter> convex hull K = convex hull K \\<inter> L\"\n                  by force\n              qed\n              finally have chKL: \"convex hull (insert ?z K) \\<inter> L = convex hull K \\<inter> L\" .\n              have \"convex hull insert ?z K \\<inter> convex hull L face_of K\"\n                by (simp add: \\<open>K \\<in> \\<U>\\<close> \\<open>L \\<in> \\<U>\\<close> ch_id chKL faceI\\<U>)\n              also have \"... face_of convex hull insert ?z K\"\n              proof -\n                obtain I where I: \"\\<not> affine_dependent I\" \"K = convex hull I\"\n                  using * [OF \\<open>K \\<in> \\<U>\\<close>] by auto\n                then have \"\\<And>a. a \\<notin> rel_interior C \\<or> a \\<notin> affine hull I\"\n                  using ahK_C_disjoint \\<open>C \\<in> \\<N>\\<close> \\<open>K \\<in> \\<U>\\<close> \\<open>K \\<subseteq> rel_frontier C\\<close> affine_hull_convex_hull by blast\n                then show ?thesis\n                  by (metis I affine_independent_insert face_of_convex_hull_affine_independent hull_insert subset_insertI z)\n              qed\n              finally have 1: \"convex hull insert ?z K \\<inter> convex hull L face_of convex hull insert ?z K\" .\n              have \"convex hull insert ?z K \\<inter> convex hull L face_of L\"\n                by (metis \\<open>K \\<in> \\<U>\\<close> \\<open>L \\<in> \\<U>\\<close> chKL ch_id faceI\\<U> inf_commute)\n              also have \"... face_of convex hull insert ?w L\"\n              proof -\n                obtain I where I: \"\\<not> affine_dependent I\" \"L = convex hull I\"\n                  using * [OF \\<open>L \\<in> \\<U>\\<close>] by auto\n                then have \"\\<And>a. a \\<notin> rel_interior D \\<or> a \\<notin> affine hull I\"\n                  using \\<open>D \\<in> \\<N>\\<close> \\<open>L \\<in> \\<U>\\<close> \\<open>L \\<subseteq> rel_frontier D\\<close> affine_hull_convex_hull ahK_C_disjoint by blast\n                then show ?thesis\n                  by (metis I aff_independent_finite convex_convex_hull face_of_convex_hull_insert face_of_refl hull_insert w)\n              qed\n              finally have 2: \"convex hull insert ?z K \\<inter> convex hull L face_of convex hull insert ?w L\" .\n              show ?thesis\n                by (simp add: X Y eq 1 2)\n            qed\n          qed\n        qed \n      qed\n      show \"\\<exists>F \\<subseteq> \\<U> \\<union> ?\\<T>. C = \\<Union>F\" if \"C \\<in> \\<M>\" for C\n      proof (cases \"C \\<in> \\<S>\")\n        case True\n        then show ?thesis\n          by (meson UnCI fin\\<U> subsetD subsetI)\n      next\n        case False\n        then have \"C \\<in> \\<N>\"\n          by (simp add: \\<N>_def \\<S>_def aff\\<M> less_le that)\n        let ?z = \"SOME z. z \\<in> rel_interior C\"\n        have z: \"?z \\<in> rel_interior C\"\n          using \\<open>C \\<in> \\<N>\\<close> in_rel_interior by blast\n        let ?F = \"\\<Union>K \\<in> \\<U> \\<inter> Pow (rel_frontier C). {convex hull (insert ?z K)}\"\n        have \"?F \\<subseteq> ?\\<T>\"\n          using \\<open>C \\<in> \\<N>\\<close> by blast\n        moreover have \"C \\<subseteq> \\<Union>?F\"\n        proof\n          fix x\n          assume \"x \\<in> C\"\n          have \"convex C\"\n            using \\<open>C \\<in> \\<N>\\<close> convex\\<N> by blast\n          have \"bounded C\"\n            using \\<open>C \\<in> \\<N>\\<close> by (simp add: poly\\<M> polytope_imp_bounded that)\n          have \"polytope C\"\n            using \\<open>C \\<in> \\<N>\\<close> poly\\<N> by auto\n          have \"\\<not> (?z = x \\<and> C = {?z})\"\n            using \\<open>C \\<in> \\<N>\\<close> aff_dim_sing [of ?z] \\<open>\\<not> n \\<le> 1\\<close> by (force simp: \\<N>_def)\n          then obtain y where y: \"y \\<in> rel_frontier C\" and xzy: \"x \\<in> closed_segment ?z y\"\n            and sub: \"open_segment ?z y \\<subseteq> rel_interior C\"\n            by (blast intro: segment_to_rel_frontier [OF \\<open>convex C\\<close> \\<open>bounded C\\<close> z \\<open>x \\<in> C\\<close>])\n          then obtain F where \"y \\<in> F\" \"F face_of C\" \"F \\<noteq> C\"\n            by (auto simp: rel_frontier_of_polyhedron_alt [OF polytope_imp_polyhedron [OF \\<open>polytope C\\<close>]])\n          then obtain \\<G> where \"finite \\<G>\" \"\\<G> \\<subseteq> \\<U>\" \"F = \\<Union>\\<G>\"\n            by (metis (mono_tags, lifting) \\<S>_def \\<open>C \\<in> \\<M>\\<close> \\<open>convex C\\<close> aff\\<M> face\\<M> face_of_aff_dim_lt fin\\<U> le_less_trans mem_Collect_eq not_less)\n          then obtain K where \"y \\<in> K\" \"K \\<in> \\<G>\"\n            using \\<open>y \\<in> F\\<close> by blast\n          moreover have x: \"x \\<in> convex hull {?z,y}\"\n            using segment_convex_hull xzy by auto\n          moreover have \"convex hull {?z,y} \\<subseteq> convex hull insert ?z K\"\n            by (metis (full_types) \\<open>y \\<in> K\\<close> hull_mono empty_subsetI insertCI insert_subset)\n          moreover have \"K \\<in> \\<U>\"\n            using \\<open>K \\<in> \\<G>\\<close> \\<open>\\<G> \\<subseteq> \\<U>\\<close> by blast\n          moreover have \"K \\<subseteq> rel_frontier C\"\n            using \\<open>F = \\<Union>\\<G>\\<close> \\<open>F \\<noteq> C\\<close> \\<open>F face_of C\\<close> \\<open>K \\<in> \\<G>\\<close> face_of_subset_rel_frontier by fastforce\n          ultimately show \"x \\<in> \\<Union>?F\"\n            by force\n        qed\n        moreover\n        have \"convex hull insert (SOME z. z \\<in> rel_interior C) K \\<subseteq> C\"\n          if \"K \\<in> \\<U>\" \"K \\<subseteq> rel_frontier C\" for K\n        proof (rule hull_minimal)\n          show \"insert (SOME z. z \\<in> rel_interior C) K \\<subseteq> C\"\n            using that \\<open>C \\<in> \\<N>\\<close> in_rel_interior rel_interior_subset\n            by (force simp: closure_eq rel_frontier_def closed\\<N>)\n          show \"convex C\"\n            by (simp add: \\<open>C \\<in> \\<N>\\<close> convex\\<N>)\n        qed\n        then have \"\\<Union>?F \\<subseteq> C\"\n          by auto\n        ultimately show ?thesis\n          by blast\n      qed\n\n      have \"(\\<exists>C. C \\<in> \\<M> \\<and> L \\<subseteq> C) \\<and> aff_dim L \\<le> int n\"  if \"L \\<in> \\<U> \\<union> ?\\<T>\" for L\n        using that\n      proof\n        assume \"L \\<in> \\<U>\"\n        then show ?thesis\n          using C\\<U> \\<S>_def \"*\" by fastforce\n      next\n        assume \"L \\<in> ?\\<T>\"\n        then obtain C K where \"C \\<in> \\<N>\"\n          and L: \"L = convex hull insert (SOME z. z \\<in> rel_interior C) K\"\n          and K: \"K \\<in> \\<U>\" \"K \\<subseteq> rel_frontier C\"\n          by auto\n        then have \"convex hull C = C\"\n          by (meson convex\\<N> convex_hull_eq)\n        then have \"convex C\"\n          by (metis (no_types) convex_convex_hull)\n        have \"rel_frontier C \\<subseteq> C\"\n          by (metis DiffE closed\\<N> \\<open>C \\<in> \\<N>\\<close> closure_closed rel_frontier_def subsetI)\n        have \"K \\<subseteq> C\"\n          using K \\<open>rel_frontier C \\<subseteq> C\\<close> by blast\n        have \"C \\<in> \\<M>\"\n          using \\<N>_def \\<open>C \\<in> \\<N>\\<close> by auto\n        moreover have \"L \\<subseteq> C\"\n          using K L \\<open>C \\<in> \\<N>\\<close>\n          by (metis \\<open>K \\<subseteq> C\\<close> \\<open>convex hull C = C\\<close> contra_subsetD hull_mono in_rel_interior insert_subset rel_interior_subset)\n        ultimately show ?thesis\n          using \\<open>rel_frontier C \\<subseteq> C\\<close> \\<open>L \\<subseteq> C\\<close> aff\\<M> aff_dim_subset \\<open>C \\<in> \\<M>\\<close> dual_order.trans by blast\n      qed\n      then show \"\\<exists>C. C \\<in> \\<M> \\<and> L \\<subseteq> C\" \"aff_dim L \\<le> int n\" if \"L \\<in> \\<U> \\<union> ?\\<T>\" for L\n        using that by auto\n    qed\n    then show ?thesis\n      apply (rule ex_forward, safe)\n        apply (meson Union_iff subsetCE, fastforce)\n      by (meson infinite_super simplicial_complex_def)\n  qed\nqed\n\n\nlemma simplicial_subdivision_of_cell_complex_lowdim:\n  assumes \"finite \\<M>\"\n      and poly: \"\\<And>C. C \\<in> \\<M> \\<Longrightarrow> polytope C\"\n      and face: \"\\<And>C1 C2. \\<lbrakk>C1 \\<in> \\<M>; C2 \\<in> \\<M>\\<rbrakk> \\<Longrightarrow> C1 \\<inter> C2 face_of C1\"\n      and aff: \"\\<And>C. C \\<in> \\<M> \\<Longrightarrow> aff_dim C \\<le> d\"\n  obtains \\<T> where \"simplicial_complex \\<T>\" \"\\<And>K. K \\<in> \\<T> \\<Longrightarrow> aff_dim K \\<le> d\"\n                  \"\\<Union>\\<T> = \\<Union>\\<M>\"\n                  \"\\<And>C. C \\<in> \\<M> \\<Longrightarrow> \\<exists>F. finite F \\<and> F \\<subseteq> \\<T> \\<and> C = \\<Union>F\"\n                  \"\\<And>K. K \\<in> \\<T> \\<Longrightarrow> \\<exists>C. C \\<in> \\<M> \\<and> K \\<subseteq> C\"\nproof (cases \"d \\<ge> 0\")\n  case True\n  then obtain n where n: \"d = of_nat n\"\n    using zero_le_imp_eq_int by blast\n  have \"\\<exists>\\<T>. simplicial_complex \\<T> \\<and>\n            (\\<forall>K\\<in>\\<T>. aff_dim K \\<le> int n) \\<and>\n            \\<Union>\\<T> = \\<Union>(\\<Union>C\\<in>\\<M>. {F. F face_of C}) \\<and>\n            (\\<forall>C\\<in>\\<Union>C\\<in>\\<M>. {F. F face_of C}.\n                \\<exists>F. finite F \\<and> F \\<subseteq> \\<T> \\<and> C = \\<Union>F) \\<and>\n            (\\<forall>K\\<in>\\<T>. \\<exists>C. C \\<in> (\\<Union>C\\<in>\\<M>. {F. F face_of C}) \\<and> K \\<subseteq> C)\"\n  proof (rule simplicial_subdivision_aux)\n    show \"finite (\\<Union>C\\<in>\\<M>. {F. F face_of C})\"\n      using \\<open>finite \\<M>\\<close> poly polyhedron_eq_finite_faces polytope_imp_polyhedron by fastforce\n    show \"polytope F\" if \"F \\<in> (\\<Union>C\\<in>\\<M>. {F. F face_of C})\" for F\n      using poly that face_of_polytope_polytope by blast\n    show \"aff_dim F \\<le> int n\" if \"F \\<in> (\\<Union>C\\<in>\\<M>. {F. F face_of C})\" for F\n      using that\n      by clarify (metis n aff_dim_subset aff face_of_imp_subset order_trans)\n    show \"F \\<in> (\\<Union>C\\<in>\\<M>. {F. F face_of C})\"\n      if \"G \\<in> (\\<Union>C\\<in>\\<M>. {F. F face_of C})\" and \"F face_of G\" for F G\n      using that face_of_trans by blast\n  next\n    fix F1 F2\n    assume \"F1 \\<in> (\\<Union>C\\<in>\\<M>. {F. F face_of C})\" and \"F2 \\<in> (\\<Union>C\\<in>\\<M>. {F. F face_of C})\"\n    then obtain C1 C2 where \"C1 \\<in> \\<M>\" \"C2 \\<in> \\<M>\" and F: \"F1 face_of C1\" \"F2 face_of C2\"\n      by auto\n    show \"F1 \\<inter> F2 face_of F1\"\n      using face_of_Int_subface [OF _ _ F]\n      by (metis \\<open>C1 \\<in> \\<M>\\<close> \\<open>C2 \\<in> \\<M>\\<close> face inf_commute)\n  qed\n  moreover\n  have \"\\<Union>(\\<Union>C\\<in>\\<M>. {F. F face_of C}) = \\<Union>\\<M>\"\n    using face_of_imp_subset face by blast\n  ultimately show ?thesis\n    apply clarify\n    apply (rule that, assumption+)\n       using n apply blast\n      apply (simp_all add: poly face_of_refl polytope_imp_convex)\n    using face_of_imp_subset by fastforce\nnext\n  case False\n  then have m1: \"\\<And>C. C \\<in> \\<M> \\<Longrightarrow> aff_dim C = -1\"\n    by (metis aff aff_dim_empty_eq aff_dim_negative_iff dual_order.trans not_less)\n  then have face\\<M>: \"\\<And>F S. \\<lbrakk>S \\<in> \\<M>; F face_of S\\<rbrakk> \\<Longrightarrow> F \\<in> \\<M>\"\n    by (metis aff_dim_empty face_of_empty)\n  show ?thesis\n  proof\n    have \"\\<And>S. S \\<in> \\<M> \\<Longrightarrow> \\<exists>n. n simplex S\"\n      by (metis (no_types) m1 aff_dim_empty simplex_minus_1)\n    then show \"simplicial_complex \\<M>\"\n      by (auto simp: simplicial_complex_def \\<open>finite \\<M>\\<close> face intro: face\\<M>)\n    show \"aff_dim K \\<le> d\" if \"K \\<in> \\<M>\" for K\n      by (simp add: that aff)\n    show \"\\<exists>F. finite F \\<and> F \\<subseteq> \\<M> \\<and> C = \\<Union>F\" if \"C \\<in> \\<M>\" for C\n      using \\<open>C \\<in> \\<M>\\<close> equals0I by auto\n    show \"\\<exists>C. C \\<in> \\<M> \\<and> K \\<subseteq> C\" if \"K \\<in> \\<M>\" for K\n      using \\<open>K \\<in> \\<M>\\<close> by blast\n  qed auto\nqed\n\nproposition simplicial_subdivision_of_cell_complex:\n  assumes \"finite \\<M>\"\n      and poly: \"\\<And>C. C \\<in> \\<M> \\<Longrightarrow> polytope C\"\n      and face: \"\\<And>C1 C2. \\<lbrakk>C1 \\<in> \\<M>; C2 \\<in> \\<M>\\<rbrakk> \\<Longrightarrow> C1 \\<inter> C2 face_of C1\"\n  obtains \\<T> where \"simplicial_complex \\<T>\"\n                  \"\\<Union>\\<T> = \\<Union>\\<M>\"\n                  \"\\<And>C. C \\<in> \\<M> \\<Longrightarrow> \\<exists>F. finite F \\<and> F \\<subseteq> \\<T> \\<and> C = \\<Union>F\"\n                  \"\\<And>K. K \\<in> \\<T> \\<Longrightarrow> \\<exists>C. C \\<in> \\<M> \\<and> K \\<subseteq> C\"\n  by (blast intro: simplicial_subdivision_of_cell_complex_lowdim [OF assms aff_dim_le_DIM])\n\ncorollary fine_simplicial_subdivision_of_cell_complex:\n  assumes \"0 < e\" \"finite \\<M>\"\n      and poly: \"\\<And>C. C \\<in> \\<M> \\<Longrightarrow> polytope C\"\n      and face: \"\\<And>C1 C2. \\<lbrakk>C1 \\<in> \\<M>; C2 \\<in> \\<M>\\<rbrakk> \\<Longrightarrow> C1 \\<inter> C2 face_of C1\"\n  obtains \\<T> where \"simplicial_complex \\<T>\"\n                  \"\\<And>K. K \\<in> \\<T> \\<Longrightarrow> diameter K < e\"\n                  \"\\<Union>\\<T> = \\<Union>\\<M>\"\n                  \"\\<And>C. C \\<in> \\<M> \\<Longrightarrow> \\<exists>F. finite F \\<and> F \\<subseteq> \\<T> \\<and> C = \\<Union>F\"\n                  \"\\<And>K. K \\<in> \\<T> \\<Longrightarrow> \\<exists>C. C \\<in> \\<M> \\<and> K \\<subseteq> C\"\nproof -\n  obtain \\<N> where \\<N>: \"finite \\<N>\" \"\\<Union>\\<N> = \\<Union>\\<M>\" \n              and diapoly: \"\\<And>X. X \\<in> \\<N> \\<Longrightarrow> diameter X < e\" \"\\<And>X. X \\<in> \\<N> \\<Longrightarrow> polytope X\"\n               and      \"\\<And>X Y. \\<lbrakk>X \\<in> \\<N>; Y \\<in> \\<N>\\<rbrakk> \\<Longrightarrow> X \\<inter> Y face_of X\"\n               and \\<N>covers: \"\\<And>C x. C \\<in> \\<M> \\<and> x \\<in> C \\<Longrightarrow> \\<exists>D. D \\<in> \\<N> \\<and> x \\<in> D \\<and> D \\<subseteq> C\"\n               and \\<N>covered: \"\\<And>C. C \\<in> \\<N> \\<Longrightarrow> \\<exists>D. D \\<in> \\<M> \\<and> C \\<subseteq> D\"\n    by (blast intro: cell_complex_subdivision_exists [OF \\<open>0 < e\\<close> \\<open>finite \\<M>\\<close> poly aff_dim_le_DIM face])\n  then obtain \\<T> where \\<T>: \"simplicial_complex \\<T>\" \"\\<Union>\\<T> = \\<Union>\\<N>\"\n                   and \\<T>covers: \"\\<And>C. C \\<in> \\<N> \\<Longrightarrow> \\<exists>F. finite F \\<and> F \\<subseteq> \\<T> \\<and> C = \\<Union>F\"\n                   and \\<T>covered: \"\\<And>K. K \\<in> \\<T> \\<Longrightarrow> \\<exists>C. C \\<in> \\<N> \\<and> K \\<subseteq> C\"\n    using simplicial_subdivision_of_cell_complex [OF \\<open>finite \\<N>\\<close>] by metis\n  show ?thesis\n  proof\n    show \"simplicial_complex \\<T>\"\n      by (rule \\<T>)\n    show \"diameter K < e\" if \"K \\<in> \\<T>\" for K\n      by (metis le_less_trans diapoly \\<T>covered diameter_subset polytope_imp_bounded that)\n    show \"\\<Union>\\<T> = \\<Union>\\<M>\"\n      by (simp add: \\<N>(2) \\<open>\\<Union>\\<T> = \\<Union>\\<N>\\<close>)\n    show \"\\<exists>F. finite F \\<and> F \\<subseteq> \\<T> \\<and> C = \\<Union>F\" if \"C \\<in> \\<M>\" for C\n    proof -\n      { fix x\n        assume \"x \\<in> C\"\n        then obtain D where \"D \\<in> \\<T>\" \"x \\<in> D\" \"D \\<subseteq> C\"\n          using \\<N>covers \\<open>C \\<in> \\<M>\\<close> \\<T>covers by force\n        then have \"\\<exists>X\\<in>\\<T> \\<inter> Pow C. x \\<in> X\"\n          using \\<open>D \\<in> \\<T>\\<close> \\<open>D \\<subseteq> C\\<close> \\<open>x \\<in> D\\<close> by blast\n      }\n      moreover\n      have \"finite (\\<T> \\<inter> Pow C)\"\n        using \\<open>simplicial_complex \\<T>\\<close> simplicial_complex_def by auto\n      ultimately show ?thesis\n        by (rule_tac x=\"(\\<T> \\<inter> Pow C)\" in exI) auto\n    qed\n    show \"\\<exists>C. C \\<in> \\<M> \\<and> K \\<subseteq> C\" if \"K \\<in> \\<T>\" for K\n      by (meson \\<N>covered \\<T>covered order_trans that)\n  qed\nqed\n\nsubsection\\<open>Some results on cell division with full-dimensional cells only\\<close>\n\nlemma convex_Union_fulldim_cells:\n  assumes \"finite \\<S>\" and clo: \"\\<And>C. C \\<in> \\<S> \\<Longrightarrow> closed C\" and con: \"\\<And>C. C \\<in> \\<S> \\<Longrightarrow> convex C\"\n      and eq: \"\\<Union>\\<S> = U\"and  \"convex U\"\n shows \"\\<Union>{C \\<in> \\<S>. aff_dim C = aff_dim U} = U\"  (is \"?lhs = U\")\nproof -\n  have \"closed U\"\n    using \\<open>finite \\<S>\\<close> clo eq by blast\n  have \"?lhs \\<subseteq> U\"\n    using eq by blast\n  moreover have \"U \\<subseteq> ?lhs\"\n  proof (cases \"\\<forall>C \\<in> \\<S>. aff_dim C = aff_dim U\")\n    case True\n    then show ?thesis\n      using eq by blast\n  next\n    case False\n    have \"closed ?lhs\"\n      by (simp add: \\<open>finite \\<S>\\<close> clo closed_Union)\n    moreover have \"U \\<subseteq> closure ?lhs\"\n    proof -\n      have \"U \\<subseteq> closure(\\<Inter>{U - C |C. C \\<in> \\<S> \\<and> aff_dim C < aff_dim U})\"\n      proof (rule Baire [OF \\<open>closed U\\<close>])\n        show \"countable {U - C |C. C \\<in> \\<S> \\<and> aff_dim C < aff_dim U}\"\n          using \\<open>finite \\<S>\\<close> uncountable_infinite by fastforce\n        have \"\\<And>C. C \\<in> \\<S> \\<Longrightarrow> openin (top_of_set U) (U-C)\"\n          by (metis Sup_upper clo closed_limpt closedin_limpt eq openin_diff openin_subtopology_self)\n        then show \"openin (top_of_set U) T \\<and> U \\<subseteq> closure T\"\n          if \"T \\<in> {U - C |C. C \\<in> \\<S> \\<and> aff_dim C < aff_dim U}\" for T\n          using that dense_complement_convex_closed \\<open>closed U\\<close> \\<open>convex U\\<close> by auto\n      qed\n      also have \"... \\<subseteq> closure ?lhs\"\n      proof -\n        obtain C where \"C \\<in> \\<S>\" \"aff_dim C < aff_dim U\"\n          by (metis False Sup_upper aff_dim_subset eq eq_iff not_le)\n        have \"\\<exists>X. X \\<in> \\<S> \\<and> aff_dim X = aff_dim U \\<and> x \\<in> X\"\n          if \"\\<And>V. (\\<exists>C. V = U - C \\<and> C \\<in> \\<S> \\<and> aff_dim C < aff_dim U) \\<Longrightarrow> x \\<in> V\" for x\n        proof -\n          have \"x \\<in> U \\<and> x \\<in> \\<Union>\\<S>\"\n            using \\<open>C \\<in> \\<S>\\<close> \\<open>aff_dim C < aff_dim U\\<close> eq that by blast\n          then show ?thesis\n            by (metis Diff_iff Sup_upper Union_iff aff_dim_subset dual_order.order_iff_strict eq that)\n        qed\n        then show ?thesis\n          by (auto intro!: closure_mono)\n      qed\n      finally show ?thesis .\n    qed\n    ultimately show ?thesis\n      using closure_subset_eq by blast\n  qed\n  ultimately show ?thesis by blast\nqed\n\nproposition fine_triangular_subdivision_of_cell_complex:\n  assumes \"0 < e\" \"finite \\<M>\"\n      and poly: \"\\<And>C. C \\<in> \\<M> \\<Longrightarrow> polytope C\"\n      and aff: \"\\<And>C. C \\<in> \\<M> \\<Longrightarrow> aff_dim C = d\"\n      and face: \"\\<And>C1 C2. \\<lbrakk>C1 \\<in> \\<M>; C2 \\<in> \\<M>\\<rbrakk> \\<Longrightarrow> C1 \\<inter> C2 face_of C1\"\n  obtains \\<T> where \"triangulation \\<T>\" \"\\<And>k. k \\<in> \\<T> \\<Longrightarrow> diameter k < e\"\n                 \"\\<And>k. k \\<in> \\<T> \\<Longrightarrow> aff_dim k = d\" \"\\<Union>\\<T> = \\<Union>\\<M>\"\n                 \"\\<And>C. C \\<in> \\<M> \\<Longrightarrow> \\<exists>f. finite f \\<and> f \\<subseteq> \\<T> \\<and> C = \\<Union>f\"\n                 \"\\<And>k. k \\<in> \\<T> \\<Longrightarrow> \\<exists>C. C \\<in> \\<M> \\<and> k \\<subseteq> C\"\nproof -\n  obtain \\<T> where \"simplicial_complex \\<T>\"\n             and dia\\<T>: \"\\<And>K. K \\<in> \\<T> \\<Longrightarrow> diameter K < e\"\n             and \"\\<Union>\\<T> = \\<Union>\\<M>\"\n             and in\\<M>: \"\\<And>C. C \\<in> \\<M> \\<Longrightarrow> \\<exists>F. finite F \\<and> F \\<subseteq> \\<T> \\<and> C = \\<Union>F\"\n             and in\\<T>: \"\\<And>K. K \\<in> \\<T> \\<Longrightarrow> \\<exists>C. C \\<in> \\<M> \\<and> K \\<subseteq> C\"\n    by (blast intro: fine_simplicial_subdivision_of_cell_complex [OF \\<open>e > 0\\<close> \\<open>finite \\<M>\\<close> poly face])\n  let ?\\<T> = \"{K \\<in> \\<T>. aff_dim K = d}\"\n  show thesis\n  proof\n    show \"triangulation ?\\<T>\"\n      using \\<open>simplicial_complex \\<T>\\<close> by (auto simp: triangulation_def simplicial_complex_def)\n    show \"diameter L < e\" if \"L \\<in> {K \\<in> \\<T>. aff_dim K = d}\" for L\n      using that by (auto simp: dia\\<T>)\n    show \"aff_dim L = d\" if \"L \\<in> {K \\<in> \\<T>. aff_dim K = d}\" for L\n      using that by auto\n    show \"\\<exists>F. finite F \\<and> F \\<subseteq> {K \\<in> \\<T>. aff_dim K = d} \\<and> C = \\<Union>F\" if \"C \\<in> \\<M>\" for C\n    proof -\n      obtain F where \"finite F\" \"F \\<subseteq> \\<T>\" \"C = \\<Union>F\"\n        using in\\<M> [OF \\<open>C \\<in> \\<M>\\<close>] by auto\n      show ?thesis\n      proof (intro exI conjI)\n        show \"finite {K \\<in> F. aff_dim K = d}\"\n          by (simp add: \\<open>finite F\\<close>)\n        show \"{K \\<in> F. aff_dim K = d} \\<subseteq> {K \\<in> \\<T>. aff_dim K = d}\"\n          using \\<open>F \\<subseteq> \\<T>\\<close> by blast\n        have \"d = aff_dim C\"\n          by (simp add: aff that)\n        moreover have \"\\<And>K. K \\<in> F \\<Longrightarrow> closed K \\<and> convex K\"\n          using \\<open>simplicial_complex \\<T>\\<close> \\<open>F \\<subseteq> \\<T>\\<close>\n          unfolding simplicial_complex_def by (metis subsetCE \\<open>F \\<subseteq> \\<T>\\<close> closed_simplex convex_simplex)\n        moreover have \"convex (\\<Union>F)\"\n          using \\<open>C = \\<Union>F\\<close> poly polytope_imp_convex that by blast\n        ultimately show \"C = \\<Union>{K \\<in> F. aff_dim K = d}\"\n          by (simp add: convex_Union_fulldim_cells \\<open>C = \\<Union>F\\<close> \\<open>finite F\\<close>)\n      qed\n    qed\n    then show \"\\<Union>{K \\<in> \\<T>. aff_dim K = d} = \\<Union>\\<M>\"\n      by auto (meson in\\<T> subsetCE)\n    show \"\\<exists>C. C \\<in> \\<M> \\<and> L \\<subseteq> C\"\n      if \"L \\<in> {K \\<in> \\<T>. aff_dim K = d}\" for L\n      using that by (auto simp: in\\<T>)\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/Analysis/Polytope.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8615382165412809, "lm_q2_score": 0.839733963661418, "lm_q1q2_score": 0.7234629014219989}}
{"text": "section{*Constructive Functions*}\n\ntheory Constructive imports Main\nbegin\n\n  notation\n    bot (\"\\<bottom>\") and\n    top (\"\\<top>\") and\n    inf (infixl \"\\<sqinter>\" 70)\n    and sup (infixl \"\\<squnion>\" 65)\n\n  class order_bot_max = order_bot +\n    fixes maximal :: \"'a \\<Rightarrow> bool\"\n    assumes maximal_def: \"maximal x = (\\<forall> y . \\<not> x < y)\"\n    assumes [simp]: \"\\<not> maximal \\<bottom>\"\n    begin\n      lemma ex_not_le_bot[simp]: \"\\<exists> a. \\<not> a \\<le> \\<bottom>\"\n        apply (subgoal_tac \"\\<not> maximal \\<bottom>\")\n        apply (subst (asm) maximal_def, simp_all add: less_le, auto)\n        apply (rule_tac x = x in exI, auto)\n        apply (subgoal_tac \"x = \\<bottom>\", simp)\n        by (rule antisym, simp_all)\n    end\n\n  instantiation \"option\" :: (type) order_bot_max\n    begin\n      definition bot_option_def: \"(\\<bottom>::'a option) = None\"\n      definition le_option_def: \"((x::'a option) \\<le> y) = (x = None \\<or> x = y)\"\n      definition less_option_def: \"((x::'a option) < y) = (x \\<le> y \\<and> \\<not> (y \\<le> x))\"\n      definition maximal_option_def: \"maximal (x::'a option) = (\\<forall> y . \\<not> x < y)\"\n\n      instance \n      proof\n        qed (auto simp add: le_option_def less_option_def maximal_option_def bot_option_def)\n\n     \n\n  context order_bot\n    begin\n      definition \"is_lfp f x = ((f x = x) \\<and> (\\<forall> y . f y = y \\<longrightarrow> x \\<le> y))\"\n      definition \"emono f = (\\<forall> x y. x \\<le> y \\<longrightarrow> f x \\<le> f y)\"\n\n      definition \"Lfp f = Eps (is_lfp f)\"\n\n      lemma lfp_unique: \"is_lfp f x \\<Longrightarrow> is_lfp f y \\<Longrightarrow> x = y\"\n        apply (simp add: is_lfp_def)\n        by (simp add: local.antisym)\n\n      lemma lfp_exists: \"is_lfp f x \\<Longrightarrow> Lfp f = x\"\n        apply (rule lfp_unique, simp_all)\n        by (simp add: Lfp_def someI)\n  \n      lemma emono_a: \"emono f \\<Longrightarrow> x \\<le> y \\<Longrightarrow> f x \\<le> f y\"\n        by (simp add: emono_def)\n\n      lemma emono_fix: \"emono f \\<Longrightarrow> f y = y \\<Longrightarrow> (f ^^ n) \\<bottom> \\<le> y\"\n        apply (induction n)\n        apply (simp_all)\n        apply (drule emono_a, simp_all)\n        by simp\n\n      lemma emono_is_lfp: \"emono (f::'a \\<Rightarrow> 'a) \\<Longrightarrow> (f ^^ (n + 1)) \\<bottom> = (f ^^ n) \\<bottom> \\<Longrightarrow> is_lfp f ((f ^^ n) \\<bottom>)\"\n        apply (simp add: is_lfp_def, safe)\n        by (rule emono_fix, simp_all)\n\n      lemma emono_lfp_bot: \"emono (f::'a \\<Rightarrow> 'a) \\<Longrightarrow> (f ^^ (n + 1)) \\<bottom> = (f ^^ n) \\<bottom> \\<Longrightarrow> Lfp f = ((f ^^ n) \\<bottom>)\"\n        apply (drule emono_is_lfp, simp_all)\n        by (simp add: lfp_exists)\n\n\n      lemma emono_up: \"emono f \\<Longrightarrow> (f ^^ n) \\<bottom> \\<le> (f ^^ (Suc n)) \\<bottom>\"\n        apply (induction n)\n        apply (simp_all)\n        by (drule emono_a, simp_all)\n    end\n\n   context order\n    begin\n       definition \"min_set A = (SOME n . n \\<in> A \\<and> (\\<forall> x \\<in> A . n \\<le> x))\"\n    end\n\n   lemma min_nonempty_nat_set_aux: \"\\<forall> A . (n::nat) \\<in> A \\<longrightarrow> (\\<exists> k \\<in> A . (\\<forall> x \\<in> A . k \\<le> x))\"\n     apply (induction n, safe)\n     apply (rule_tac x = 0 in bexI, simp_all)\n     apply (case_tac \"0 \\<in> A\")\n     apply (rule_tac x = 0 in bexI, simp_all)\n     apply (drule_tac x = \"{n . Suc n \\<in> A}\" in spec)\n     apply safe\n     apply (rule_tac x = \"Suc k\" in bexI, simp_all, safe)\n     apply (drule_tac x = \"x - 1\" in spec)\n     by (case_tac x, simp_all)\n\n   lemma min_nonempty_nat_set: \"(n::nat) \\<in> A \\<Longrightarrow> (\\<exists> k . k \\<in> A \\<and> (\\<forall> x \\<in> A . k \\<le> x))\"\n     by (cut_tac min_nonempty_nat_set_aux, auto)\n\n  thm someI_ex\n\n  lemma min_set_nat_aux: \"(n::nat) \\<in> A \\<Longrightarrow> min_set A \\<in> A \\<and> (\\<forall> x \\<in> A . min_set A \\<le> x)\"\n    apply (simp add: min_set_def)\n    apply (drule min_nonempty_nat_set)\n    by (rule someI_ex, simp_all)\n\n  lemma \"(n::nat) \\<in> A \\<Longrightarrow> min_set A \\<in> A \\<and> min_set A \\<le> n\"\n    by (simp add: min_set_nat_aux)\n    \n  lemma min_set_in: \"(n::nat) \\<in> A \\<Longrightarrow> min_set A \\<in> A\"\n    by (simp add: min_set_nat_aux)\n\n  lemma min_set_less: \"(n::nat) \\<in> A \\<Longrightarrow> min_set A \\<le> n\"\n    by (simp add: min_set_nat_aux)\n\n\n  definition \"mono_a f = (\\<forall> a b a' b'. (a::'a::order) \\<le> a' \\<and> (b::'b::order) \\<le> b' \\<longrightarrow> f a b \\<le> f a' b')\"\n\n  class fin_cpo = order_bot_max +\n    \n    assumes fin_up_chain: \"(\\<forall> i:: nat . a i \\<le> a (Suc i)) \\<Longrightarrow> \\<exists> n . \\<forall> i \\<ge> n . a i = a n\"\n    begin\n      lemma emono_ex_lfp: \"emono f \\<Longrightarrow> \\<exists> n . is_lfp f ((f ^^ n) \\<bottom>)\"\n        apply (cut_tac a = \"\\<lambda> i . (f ^^ i) \\<bottom>\" in fin_up_chain)\n        apply (safe, rule emono_up, simp)\n        apply (rule_tac x= n in exI)\n        apply (rule emono_is_lfp, simp)\n        by (drule_tac x = \"n + 1\" in spec, simp)\n\n      lemma emono_lfp: \"emono f \\<Longrightarrow> \\<exists> n . Lfp f = (f ^^ n) \\<bottom>\"\n        apply (drule emono_ex_lfp, safe)\n        apply (rule_tac x = n in exI)\n        by (rule lfp_exists, simp)\n\n      lemma emono_is_lfp: \"emono f \\<Longrightarrow> is_lfp f (Lfp f)\"\n        apply (drule emono_ex_lfp, safe)\n        by (frule lfp_exists, simp)\n\n      definition \"lfp_index (f::'a \\<Rightarrow> 'a) = min_set {n . (f ^^ n) \\<bottom> = (f ^^ (n + 1)) \\<bottom>}\"\n\n      lemma lfp_index_aux: \"emono f \\<Longrightarrow> (\\<forall> i < (lfp_index f) . (f ^^ i) \\<bottom> < (f ^^ (i + 1)) \\<bottom>) \\<and> (f ^^ (lfp_index f)) \\<bottom> = (f ^^ ((lfp_index f) + 1)) \\<bottom>\"\n        apply (simp add: lfp_index_def)\n        apply safe\n        apply (simp add: less_le_not_le, safe)\n        apply (cut_tac n = i in emono_up, simp_all)\n        apply (cut_tac n = i and A = \"{n . (f ^^ n) \\<bottom> = (f ^^ (n + 1)) \\<bottom>}\" in min_set_less, simp)\n        apply (rule antisym, simp_all)\n        apply (cut_tac n = i in emono_up, simp_all)\n        apply (cut_tac a = \"\\<lambda> i . (f ^^ i) \\<bottom>\" in fin_up_chain, simp, safe)\n        apply (drule emono_up, simp)\n        apply (cut_tac n = \"n\" and A = \"{n . (f ^^ n) \\<bottom> = (f ^^ (n + 1)) \\<bottom>}\" in min_set_in)\n        apply (drule_tac x = \"Suc n\" in spec, simp)\n        by simp\n\n      lemma [simp]: \"emono f \\<Longrightarrow> i < lfp_index f \\<Longrightarrow> (f ^^ i) \\<bottom> < f ((f ^^ i) \\<bottom>)\"\n        by (drule lfp_index_aux, simp)\n\n      lemma [simp]: \"emono f \\<Longrightarrow> f ((f ^^ (lfp_index f)) \\<bottom>) = (f ^^ (lfp_index f)) \\<bottom>\"\n        by (drule lfp_index_aux, simp)\n\n      lemma \"emono f \\<Longrightarrow> Lfp f = (f ^^ lfp_index f) \\<bottom>\"\n        by (rule emono_lfp_bot, simp_all)\n\n\n\n      lemma AA_aux: \"emono f \\<Longrightarrow> (\\<And> b . b \\<le> a \\<Longrightarrow> f b \\<le> a) \\<Longrightarrow> (f ^^ n) \\<bottom> \\<le> a\"\n        by (induction n, simp_all)\n\n      lemma AA: \"emono f \\<Longrightarrow> (\\<And> b . b \\<le> a \\<Longrightarrow> f b \\<le> a) \\<Longrightarrow> Lfp f \\<le> a\"\n        apply (cut_tac f = f in  emono_lfp, simp_all, safe, simp)\n        by (simp add: AA_aux)\n\n      lemma BB: \"emono f \\<Longrightarrow> f (Lfp f) = Lfp f\"\n        using local.emono_is_lfp local.is_lfp_def by blast\n \n      lemma Lfp_mono: \"emono f \\<Longrightarrow> emono g \\<Longrightarrow> (\\<And> a . f a \\<le> g a) \\<Longrightarrow> Lfp f \\<le> Lfp g\"\n        by (metis AA BB local.emono_def local.order_trans)\n\n\n    end\n    declare [[show_types]]\n\n      lemma [simp]: \"mono_a f \\<Longrightarrow> emono (f a)\"\n        by (simp add: emono_def mono_a_def)\n\n      lemma [simp]: \"mono_a f \\<Longrightarrow> emono (\\<lambda> a . f a b)\"\n        by (simp add: emono_def mono_a_def)\n\n      lemma mono_aD: \"mono_a f \\<Longrightarrow> a \\<le> a' \\<Longrightarrow> b \\<le> b' \\<Longrightarrow> f a b \\<le> f a' b'\"\n        by (simp add: mono_a_def)\n\n      lemma [simp]: \"mono_a (f::'a::fin_cpo \\<Rightarrow> 'b::fin_cpo \\<Rightarrow> 'b) \\<Longrightarrow> mono_a g \\<Longrightarrow> emono (\\<lambda>b. f (Lfp (g b)) b)\"\n        apply (simp add: emono_def, safe)\n        apply (rule_tac f = f in mono_aD, simp_all)\n        by (rule Lfp_mono, simp_all add: mono_a_def)\n\n      lemma CCC: \"mono_a  (f::'a::fin_cpo \\<Rightarrow> 'b::fin_cpo \\<Rightarrow> 'b) \\<Longrightarrow> mono_a g \\<Longrightarrow> Lfp (\\<lambda>a. g (Lfp (f a)) a) \\<le> Lfp (g (Lfp (\\<lambda>b. f (Lfp (g b)) b)))\"\n        apply (rule AA, simp_all)\n        apply (subst (2) BB [THEN sym], simp_all)\n        apply (rule_tac f = g in mono_aD, simp_all)\n        apply (rule AA, simp_all)\n        apply (subst BB [THEN sym], simp_all)\n        by (rule_tac f = f in mono_aD, simp_all)\n\n\n    lemma Lfp_commute: \"mono_a (f::'a::fin_cpo \\<Rightarrow> 'b::fin_cpo \\<Rightarrow> 'b::fin_cpo) \\<Longrightarrow> mono_a g \\<Longrightarrow> Lfp (\\<lambda> b . f  (Lfp (\\<lambda> a . (g (Lfp (f a))) a)) b) = Lfp (\\<lambda> b . f (Lfp (g b)) b)\"\n      apply (rule antisym)\n      apply (rule AA, simp_all)\n      apply (subst (3) BB [THEN sym], simp_all)\n      apply (rule_tac f = f in mono_aD)\n      apply simp_all\n      by (simp_all add: CCC)\n\n  instantiation \"option\" :: (type) fin_cpo\n    begin\n      lemma fin_up_non_bot: \"(\\<forall> i . (a::nat \\<Rightarrow> 'a option) i \\<le> a (Suc i)) \\<Longrightarrow> a n \\<noteq> \\<bottom> \\<Longrightarrow> n \\<le> i \\<Longrightarrow> a i = a n\"\n        apply (induction i, simp_all)\n        apply (case_tac \"n \\<le> i\", simp_all)\n        apply (drule_tac x = i in spec)\n        apply (simp add: le_option_def bot_option_def, safe, simp_all)\n        using le_Suc_eq by blast\n\n     lemma fin_up_chain_option: \"(\\<forall> i:: nat . (a::nat \\<Rightarrow> 'a option) i \\<le> a (Suc i)) \\<Longrightarrow> \\<exists> n . \\<forall> i \\<ge> n . a i = a n\"\n      apply (case_tac \"\\<exists> n .  a n \\<noteq> \\<bottom>\", safe, simp_all)\n      apply (rule_tac x = n in exI, safe)\n      by (rule fin_up_non_bot, simp_all)\n      \n    instance\n      proof\n        qed (simp add: fin_up_chain_option)\n    end\n\n  instantiation \"prod\" :: (order_bot_max, order_bot_max) order_bot_max\n    begin\n      definition bot_prod_def: \"(\\<bottom> :: 'a \\<times> 'b) = (\\<bottom>, \\<bottom>)\"\n      definition le_prod_def: \"(x \\<le> y) = (fst x \\<le> fst y \\<and> snd x \\<le> snd y)\"\n      definition less_prod_def: \"((x::'a\\<times>'b) < y) = (x \\<le> y \\<and> \\<not> (y \\<le> x))\"\n      definition maximal_prod_def: \"maximal (x::'a \\<times> 'b) = (\\<forall> y . \\<not> x < y)\"\n\n      instance proof\n        qed (auto simp add: le_prod_def less_prod_def bot_prod_def maximal_prod_def)\n    end\n\n  instantiation \"prod\" :: (fin_cpo, fin_cpo) fin_cpo\n    begin\n      \n      lemma fin_up_chain_prod: \"(\\<forall> i:: nat . (a::nat \\<Rightarrow> 'a \\<times> 'b) i \\<le> a (Suc i)) \\<Longrightarrow> \\<exists> n . \\<forall> i \\<ge> n . a i = a n\"\n        apply (cut_tac a = \"fst o a\" in fin_up_chain)\n        apply (simp add: le_prod_def)\n        apply (cut_tac a = \"snd o a\" in fin_up_chain)\n        apply (simp add: le_prod_def)\n        apply safe\n        apply (rule_tac x = \"max n na\" in exI)\n        by (metis (no_types, hide_lams) comp_apply max.bounded_iff max.cobounded1 max.cobounded2 prod.collapse)\n      instance proof\n        qed (auto simp add: fin_up_chain_prod)\n    end\n\nend\n", "meta": {"author": "hbd-translation", "repo": "TranslateHBD", "sha": "c040d1ce04e4eb163832adea9a7f66566519ffd9", "save_path": "github-repos/isabelle/hbd-translation-TranslateHBD", "path": "github-repos/isabelle/hbd-translation-TranslateHBD/TranslateHBD-c040d1ce04e4eb163832adea9a7f66566519ffd9/Constructive.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767778695834, "lm_q2_score": 0.824461928533133, "lm_q1q2_score": 0.7234461965253963}}
{"text": "header {* \\isaheader{Example for Foreach-Loops} *}\ntheory Foreach_Refine\nimports \n  \"../../Refine_Dflt_Only_ICF\" \nbegin\n\ntext {*\n  This example presents the usage of the foreach loop.\n  We define a simple foreach loop that looks for the largest element with\n  a given property. Ordered loops are used to be sure to find the largest one.\n*}\n\nsubsection {* Definition *}\n\ndefinition find_max_invar where\n  \"find_max_invar P S it \\<sigma> = \n     (case \\<sigma> of None \\<Rightarrow> (\\<forall>x \\<in> S - it. \\<not>(P x))\n             | Some y \\<Rightarrow> (P y \\<and> y \\<in> S-it \\<and> (\\<forall>x \\<in> S - it - {y}. \\<not>(P x))))\"\n\ndefinition find_max :: \"('a::{linorder} \\<Rightarrow> bool) \\<Rightarrow> 'a set \\<Rightarrow> ('a option) nres\" where\n  \"find_max P S \\<equiv> \n   FOREACHoci (op\\<ge>) (find_max_invar P S) S\n     (\\<lambda>\\<sigma>. \\<sigma> = None) (\\<lambda>x _. RETURN (if P x then Some x else None)) None\"\n\nsubsection {* Correctness *}\ntext {* As simple correctness property, we show:\n  If the algorithm returns the maximal element satisfying @{text \"P\"}.\n*}\nlemma find_max_correct:\n  fixes S:: \"'a::{linorder} set\"\n  assumes \"finite S\"\n  shows \"find_max P S \\<le> SPEC (\\<lambda>\\<sigma>. case \\<sigma> of None \\<Rightarrow> \\<forall>x\\<in>S. \\<not>(P x)\n                                          | Some y \\<Rightarrow> (P y \\<and> y \\<in> S \\<and> (\\<forall>x\\<in>S. P x \\<longrightarrow> y \\<ge> x)))\"\n  unfolding find_max_def\nproof (rule FOREACHoci_rule)\n  show \"finite S\" by fact\nnext\n  show \"find_max_invar P S S None\" \n  unfolding find_max_invar_def by simp\nnext\n  fix x it \\<sigma>\n  assume \"\\<sigma> = None\"\n         \"x \\<in> it\"\n         \"it \\<subseteq> S\"\n         \"find_max_invar P S it \\<sigma>\"\n         \"\\<forall>y\\<in>it - {x}. y \\<le> x\"\n         \"\\<forall>y\\<in>S - it. x \\<le> y\"\n\n  from `find_max_invar P S it \\<sigma>` `\\<sigma> = None` \n  have not_P_others: \"\\<forall>x\\<in>S - it. \\<not> P x\"\n    by (simp add: find_max_invar_def)\n\n  from `x \\<in> it` `it \\<subseteq> S` have \"x \\<in> S\" by blast\n\n  show \"RETURN (if P x then Some x else None) \\<le> SPEC (find_max_invar P S (it - {x}))\"\n    using not_P_others `x \\<in> S`\n    by (auto simp add: find_max_invar_def)\nnext\n  fix \\<sigma>\n  assume \"find_max_invar P S {} \\<sigma>\"\n  thus \"case \\<sigma> of None \\<Rightarrow> \\<forall>x\\<in>S. \\<not> P x\n        | Some y \\<Rightarrow> P y \\<and> y \\<in> S \\<and> (\\<forall>x\\<in>S. P x \\<longrightarrow> x \\<le> y)\"\n    by (cases \\<sigma>, auto simp add: find_max_invar_def)\nnext\n  fix it \\<sigma>\n  assume \"it \\<noteq> {}\"\n         \"it \\<subseteq> S\"\n         \"find_max_invar P S it \\<sigma>\"\n         \"\\<sigma> \\<noteq> None\"\n         \"\\<forall>x\\<in>it. \\<forall>y\\<in>S - it. x \\<le> y\"\n\n  from `\\<sigma> \\<noteq> None` obtain y where \\<sigma>_eq[simp]: \"\\<sigma> = Some y\" by auto\n  from `find_max_invar P S it \\<sigma>` \n    have y_props[simp]: \"P y\" \"y \\<in> S\" \"y \\<notin> it\" and not_P: \"\\<forall>x\\<in>S - it - {y}. \\<not> P x\"\n    by (simp_all add: find_max_invar_def)\n \n  { fix x\n    assume \"x \\<in> S\" \"P x\"\n    with not_P have \"x \\<in> it \\<or> x = y\" by auto\n    with `\\<forall>x\\<in>it. \\<forall>y\\<in>S - it. x \\<le> y` y_props have \"x \\<le> y\" by auto\n  } note less_eq_y = this\n\n  show \"case \\<sigma> of None \\<Rightarrow> \\<forall>x\\<in>S. \\<not> P x\n        | Some y \\<Rightarrow> P y \\<and> y \\<in> S \\<and> (\\<forall>x\\<in>S. P x \\<longrightarrow> x \\<le> y)\" \n   by (simp add: find_max_invar_def Ball_def less_eq_y)\nqed\n\nsubsection {* Data Refinement and Determinization *}\ntext {*\n  Next, we use automatic data refinement and transfer to generate an\n  executable algorithm using a red-black-tree. \n*}\nschematic_lemma find_max_impl_refine_aux:\n  assumes invar_S: \"rs.invar S\"\n  shows \"RETURN (?f) \\<le> (find_max P (rs.\\<alpha> S))\"\n  unfolding find_max_def\n  by (refine_transfer \n    RBTSetImpl.rs.rev_iterateoi_correct[unfolded set_iterator_rev_linord_def,\n    OF invar_S])\n\nconcrete_definition find_max_impl for P S uses find_max_impl_refine_aux\n\nlemma find_max_impl_refine:\n  assumes invar_S: \"rs.invar S\"\n  shows \"RETURN (find_max_impl P S) \\<le> (find_max P (rs.\\<alpha> S))\"\n  using assms by (rule find_max_impl.refine)\n\nsubsubsection {* Executable Code *}\n\nlemma find_max_impl_correct :\nassumes invar_S: \"rs.invar S\"\nshows \"case find_max_impl P S of None \\<Rightarrow> \\<forall>x\\<in>rs.\\<alpha> S. \\<not>(P x)\n                               | Some y \\<Rightarrow> (P y \\<and> y \\<in> (rs.\\<alpha> S) \n                                 \\<and> (\\<forall>x\\<in>rs.\\<alpha> S. P x \\<longrightarrow> y \\<ge> x))\"\nproof -\n  note find_max_impl_refine [of S P, OF invar_S]\n  also note find_max_correct [OF RBTSetImpl.rs.finite[of S, OF invar_S], of P]\n  finally show ?thesis by simp\nqed\n\ntext {* Finally, we can generate code *}\nexport_code find_max_impl in SML\nexport_code find_max_impl in OCaml\nexport_code find_max_impl in Haskell\nexport_code find_max_impl in Scala\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/examples/Refine_Monadic/Foreach_Refine.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.863391624034103, "lm_q2_score": 0.8376199572530448, "lm_q1q2_score": 0.7231940552160823}}
{"text": "(*\n  File: Closure.thy\n  Author: Bohua Zhan\n\n  Closure in topological spaces.\n*)\n\ntheory Closure\n  imports ProductTopology\nbegin\n\ndefinition interior :: \"i \\<Rightarrow> i \\<Rightarrow> i\" where [rewrite]:\n  \"interior(X,A) = \\<Union>{U\\<in>open_sets(X). U \\<subseteq> A}\"\nsetup {* register_wellform_data (\"interior(X,A)\", [\"A \\<subseteq> carrier(X)\"]) *}\n  \nlemma interior_subset [resolve]: \"interior(X,A) \\<subseteq> A\" by auto2\nlemma interior_open [resolve]: \"is_top_space(X) \\<Longrightarrow> is_open(X,interior(X,A))\" by auto2\n\ndefinition closure :: \"i \\<Rightarrow> i \\<Rightarrow> i\" where [rewrite]:\n  \"closure(X,A) = \\<Inter>{C\\<in>closed_sets(X). A \\<subseteq> C}\"\nsetup {* register_wellform_data (\"closure(X,A)\", [\"A \\<subseteq> carrier(X)\"]) *}\n\nlemma closure_prop:\n  \"is_top_space(X) \\<Longrightarrow> A \\<subseteq> carrier(X) \\<Longrightarrow> A \\<subseteq> closure(X,A) \\<and> is_closed(X,closure(X,A))\"\n@proof @have \"carrier(X) \\<in> {C\\<in>closed_sets(X). A \\<subseteq> C}\" @qed\nsetup {* add_forward_prfstep_cond @{thm closure_prop} [with_term \"closure(?X,?A)\"] *}\n      \nlemma closure_subset' [backward2]:\n  \"is_top_space(X) \\<Longrightarrow> A \\<subseteq> carrier(X) \\<Longrightarrow> is_closed(X,B) \\<Longrightarrow> A \\<subseteq> B \\<Longrightarrow> closure(X,A) \\<subseteq> B\"\n@proof @have \"carrier(X) \\<in> {C\\<in>closed_sets(X). A \\<subseteq> C}\" @qed\n\nlemma closure_subspace:\n  \"is_top_space(X) \\<Longrightarrow> Y \\<subseteq> carrier(X) \\<Longrightarrow> A \\<subseteq> Y \\<Longrightarrow> closure(subspace(X,Y),A) = Y \\<inter> closure(X,A)\"\n@proof\n  @let \"B = closure(subspace(X,Y), A)\"\n  @have \"B \\<subseteq> Y \\<inter> closure(X,A)\" @with\n    @have \"is_closed(subspace(X,Y), Y \\<inter> closure(X,A))\" @end\n  @obtain \"C\\<in>closed_sets(X)\" where \"B = Y \\<inter> C\"\n  @have \"closure(X,A) \\<subseteq> C\"\n  @have \"Y \\<inter> closure(X,A) \\<subseteq> Y \\<inter> C\"\n@qed\n\nlemma closure_mem1 [backward1]:\n  \"is_top_space(X) \\<Longrightarrow> A \\<subseteq> carrier(X) \\<Longrightarrow> x \\<in>. X \\<Longrightarrow> x \\<notin> closure(X,A) \\<Longrightarrow> \\<exists>U\\<in>neighs(X,x). U \\<inter> A = \\<emptyset>\"\n@proof @have \"carrier(X) \\<midarrow> closure(X,A) \\<in> neighs(X,x)\" @qed\n\nlemma closure_mem2 [forward]:\n  \"is_top_space(X) \\<Longrightarrow> A \\<subseteq> carrier(X) \\<Longrightarrow> x \\<in>. X \\<Longrightarrow> x \\<in> closure(X,A) \\<Longrightarrow> U \\<in> neighs(X,x) \\<Longrightarrow> U \\<inter> A \\<noteq> \\<emptyset>\"\n@proof\n  @contradiction\n  @have \"is_closed(X, carrier(X) \\<midarrow> U)\"\n  @have \"closure(X,A) \\<subseteq> carrier(X) \\<midarrow> U\"\n@qed\n\ndefinition hausdorff :: \"i \\<Rightarrow> o\" where [rewrite]:\n  \"hausdorff(X) \\<longleftrightarrow> (is_top_space(X) \\<and> (\\<forall>x\\<in>.X. \\<forall>y\\<in>.X. x \\<noteq> y \\<longrightarrow> (\\<exists>U\\<in>neighs(X,x). \\<exists>V\\<in>neighs(X,y). U \\<inter> V = \\<emptyset>)))\"\n\nlemma hausdorffD1 [forward]: \"hausdorff(X) \\<Longrightarrow> is_top_space(X)\" by auto2\nlemma hausdorffD2 [backward]: \"hausdorff(X) \\<Longrightarrow> x \\<in>. X \\<Longrightarrow> y \\<in>. X \\<Longrightarrow> x \\<noteq> y \\<Longrightarrow> \\<exists>U\\<in>neighs(X,x). \\<exists>V\\<in>neighs(X,y). U \\<inter> V = \\<emptyset>\" by auto2\nsetup {* del_prfstep_thm_eqforward @{thm hausdorff_def} *}\n\ndefinition T1_space :: \"i \\<Rightarrow> o\" where [rewrite]:\n  \"T1_space(X) \\<longleftrightarrow> (is_top_space(X) \\<and> (\\<forall>x\\<in>.X. is_closed(X,{x})))\"\n\nlemma T1_spaceD1 [forward]: \"T1_space(X) \\<Longrightarrow> is_top_space(X)\" by auto2\nlemma T1_spaceD2: \"T1_space(X) \\<Longrightarrow> x \\<in>. X \\<Longrightarrow> is_closed(X,{x})\" by auto2\nsetup {* add_forward_prfstep_cond @{thm T1_spaceD2} [with_term \"{?x}\"] *}\nsetup {* del_prfstep_thm_eqforward @{thm T1_space_def} *}\n\nlemma hausdorff_is_T1 [forward]: \"hausdorff(X) \\<Longrightarrow> T1_space(X)\"\n@proof\n  @have \"\\<forall>x\\<in>.X. is_closed(X,{x})\" @with\n    @contradiction\n    @have \"\\<forall>y\\<in>closure(X,{x}). y \\<in> {x}\" @with\n      @contradiction\n      @obtain \"U\\<in>neighs(X,x)\" \"V\\<in>neighs(X,y)\" where \"U \\<inter> V = \\<emptyset>\" @end @end\n@qed\n\nlemma subspace_hausdorff: \"hausdorff(X) \\<Longrightarrow> A \\<subseteq> carrier(X) \\<Longrightarrow> hausdorff(subspace(X,A))\"\n@proof \n  @let \"Y = subspace(X,A)\"\n  @have \"\\<forall>x\\<in>.Y. \\<forall>y\\<in>.Y. x \\<noteq> y \\<longrightarrow> (\\<exists>U\\<in>neighs(Y,x). \\<exists>V\\<in>neighs(Y,y). U \\<inter> V = \\<emptyset>)\" @with\n    @obtain \"U\\<in>neighs(X,x)\" \"V\\<in>neighs(X,y)\" where \"U \\<inter> V = \\<emptyset>\"\n    @have \"(A \\<inter> U) \\<inter> (A \\<inter> V) = \\<emptyset>\" @end\n@qed\nsetup {* add_forward_prfstep_cond @{thm subspace_hausdorff} [with_term \"subspace(?X,?A)\"] *}\n\nlemma product_hausdorff [forward]: \"hausdorff(X) \\<Longrightarrow> hausdorff(Y) \\<Longrightarrow> hausdorff(X \\<times>\\<^sub>T Y)\"\n@proof \n  @let \"Z = X \\<times>\\<^sub>T Y\"\n  @have \"\\<forall>x\\<in>.Z. \\<forall>y\\<in>.Z. x \\<noteq> y \\<longrightarrow> (\\<exists>U\\<in>neighs(Z,x). \\<exists>V\\<in>neighs(Z,y). U \\<inter> V = \\<emptyset>)\" @with\n    @case \"fst(x) \\<noteq> fst(y)\" @with\n      @obtain \"U\\<in>neighs(X,fst(x))\" \"V\\<in>neighs(X,fst(y))\" where \"U \\<inter> V = \\<emptyset>\"\n      @have \"(U \\<times> carrier(Y)) \\<inter> (V \\<times> carrier(Y)) = \\<emptyset>\" @end\n    @case \"snd(x) \\<noteq> snd(y)\" @with\n      @obtain \"U\\<in>neighs(Y,snd(x))\" \"V\\<in>neighs(Y,snd(y))\" where \"U \\<inter> V = \\<emptyset>\"\n      @have \"(carrier(X) \\<times> U) \\<inter> (carrier(X) \\<times> V) = \\<emptyset>\" @end\n  @end\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/Closure.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391617003942, "lm_q2_score": 0.8376199572530448, "lm_q1q2_score": 0.7231940493274791}}
{"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 Main\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 'a}.\\<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": "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/Quotient_Type.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8376199633332891, "lm_q2_score": 0.8633916064586998, "lm_q1q2_score": 0.7231940457442058}}
{"text": "\\<^marker>\\<open>creator \"Kevin Kappelmann\"\\<close>\nsubsection \\<open>Functions on Relations\\<close>\ntheory SBinary_Relation_Functions\n  imports\n    Pairs\n    Replacement_Predicates\nbegin\n\nsubsubsection \\<open>Inverse\\<close>\n\n(*TODO: replace condition with a new is_pair predicate*)\ndefinition \"set_rel_inv R \\<equiv> {\\<langle>y, x\\<rangle> | \\<langle>x, y\\<rangle> \\<in> {p \\<in> R | \\<exists>x y. p = \\<langle>x, y\\<rangle>}}\"\n\nbundle hotg_rel_inv_syntax\nbegin\nnotation set_rel_inv (\"(_\\<inverse>)\" [1000])\nend\nbundle no_hotg_rel_inv_syntax\nbegin\nno_notation set_rel_inv (\"(_\\<inverse>)\" [1000])\nend\n\nunbundle no_rel_inv_syntax\nunbundle hotg_rel_inv_syntax\n\nlemma mem_set_rel_invI [intro]:\n  assumes \"\\<langle>x, y\\<rangle> \\<in> R\"\n  shows \"\\<langle>y, x\\<rangle> \\<in> R\\<inverse>\"\n  using assms unfolding set_rel_inv_def by auto\n\nlemma mem_set_rel_invE [elim!]:\n  assumes \"p \\<in> R\\<inverse>\"\n  obtains x y where \"p = \\<langle>y, x\\<rangle>\" \"\\<langle>x, y\\<rangle> \\<in> R\"\n  using assms unfolding set_rel_inv_def uncurry_def by (auto)\n\nlemma set_rel_inv_pairs_eq [simp]: \"(A \\<times> B)\\<inverse> = B \\<times> A\"\n  by auto\n\nlemma set_rel_inv_empty_eq [simp]: \"{}\\<inverse> = {}\"\n  by auto\n\nlemma set_rel_inv_inv_eq: \"R\\<inverse>\\<inverse> = {p \\<in> R | \\<exists>x y. p = \\<langle>x, y\\<rangle>}\"\n  by auto\n\nlemma mono_set_rel_inv: \"mono set_rel_inv\"\n  by (intro monoI) auto\n\n\nsubsubsection \\<open>Extensions and Restricts\\<close>\n\ndefinition \"extend x y R \\<equiv> insert \\<langle>x, y\\<rangle> R\"\n\nlemma mem_extendI [intro]: \"\\<langle>x, y\\<rangle> \\<in> extend x y R\"\n  unfolding extend_def by blast\n\nlemma mem_extendI':\n  assumes \"p \\<in> R\"\n  shows \"p \\<in> extend x y R\"\n  unfolding extend_def using assms by blast\n\nlemma mem_extendE [elim]:\n  assumes \"p \\<in> extend x y R\"\n  obtains \"p = \\<langle>x, y\\<rangle>\" | \"p \\<noteq> \\<langle>x, y\\<rangle>\" \"p \\<in> R\"\n  using assms unfolding extend_def by blast\n\nlemma extend_eq_self_if_pair_mem [simp]: \"\\<langle>x, y\\<rangle> \\<in> R \\<Longrightarrow> extend x y R = R\"\n  by (auto intro: mem_extendI')\n\nlemma insert_pair_eq_extend: \"insert \\<langle>x, y\\<rangle> R = extend x y R\"\n  by (auto intro: mem_extendI')\n\nlemma mono_extend_set: \"mono (extend x y)\"\n  by (intro monoI) (auto intro: mem_extendI')\n\n\ndefinition \"glue \\<R> \\<equiv> \\<Union>\\<R>\"\n\nlemma mem_glueI [intro]:\n  assumes \"p \\<in> R\"\n  and \"R \\<in> \\<R>\"\n  shows \"p \\<in> glue \\<R>\"\n  using assms unfolding glue_def by blast\n\nlemma mem_glueE [elim!]:\n  assumes \"p \\<in> glue \\<R>\"\n  obtains R where \"p \\<in> R\" \"R \\<in> \\<R>\"\n  using assms unfolding glue_def by blast\n\nlemma glue_empty_eq [simp]: \"glue {} = {}\" by auto\n\nlemma glue_singleton_eq [simp]: \"glue {R} = R\" by auto\n\nlemma mono_glue: \"mono glue\"\n  by (intro monoI) auto\n\n\nconsts set_restrict_left :: \"set \\<Rightarrow> 'a \\<Rightarrow> set\"\n\ndefinition \"set_restrict_right R P \\<equiv> (set_restrict_left R\\<inverse> P)\\<inverse>\"\n\nbundle hotg_restrict_syntax\nbegin\nnotation set_restrict_left (\"(_)\\<restriction>(\\<^bsub>_\\<^esub>)\" [1000])\nnotation set_restrict_right (\"(_)\\<upharpoonleft>(\\<^bsub>_\\<^esub>)\" [1000])\nend\nbundle no_hotg_restrict_syntax\nbegin\nno_notation set_restrict_left (\"(_)\\<restriction>(\\<^bsub>_\\<^esub>)\" [1000])\nno_notation set_restrict_right (\"(_)\\<upharpoonleft>(\\<^bsub>_\\<^esub>)\" [1000])\nend\nunbundle no_restrict_syntax\nunbundle hotg_restrict_syntax\n\noverloading\n  set_restrict_left_pred \\<equiv> \"set_restrict_left :: set \\<Rightarrow> (set \\<Rightarrow> bool) \\<Rightarrow> set\"\n  set_restrict_left_set \\<equiv> \"set_restrict_left :: set \\<Rightarrow> set \\<Rightarrow> set\"\nbegin\n  definition \"set_restrict_left_pred R P \\<equiv> {p \\<in> R | \\<exists>x y. P x \\<and> p = \\<langle>x, y\\<rangle>}\"\n  definition \"set_restrict_left_set R A \\<equiv> set_restrict_left R (mem_of A)\"\nend\n\nlemma set_restrict_left_set_eq_set_restrict_left [simp]:\n  \"R\\<restriction>\\<^bsub>A\\<^esub> = R\\<restriction>\\<^bsub>mem_of A\\<^esub>\"\n  unfolding set_restrict_left_set_def by simp\n\nlemma mem_set_restrict_leftI [intro!]:\n  assumes \"\\<langle>x, y\\<rangle> \\<in> R\"\n  and \"P x\"\n  shows \"\\<langle>x, y\\<rangle> \\<in> R\\<restriction>\\<^bsub>P\\<^esub>\"\n  using assms unfolding set_restrict_left_pred_def by blast\n\nlemma mem_set_restrict_leftE [elim]:\n  assumes \"p \\<in> R\\<restriction>\\<^bsub>P\\<^esub>\"\n  obtains x y where \"p = \\<langle>x, y\\<rangle>\" \"P x\" \"\\<langle>x, y\\<rangle> \\<in> R\"\n  using assms unfolding set_restrict_left_pred_def by blast\n\nlemma mem_set_restrict_rightI [intro!]:\n  assumes \"\\<langle>x, y\\<rangle> \\<in> R\"\n  and \"P y\"\n  shows \"\\<langle>x, y\\<rangle> \\<in> R\\<upharpoonleft>\\<^bsub>P\\<^esub>\"\n  using assms unfolding set_restrict_right_def by blast\n\nlemma mem_set_restrict_rightE [elim]:\n  assumes \"p \\<in> R\\<upharpoonleft>\\<^bsub>P\\<^esub>\"\n  obtains x y where \"p = \\<langle>x, y\\<rangle>\" \"P y\" \"\\<langle>x, y\\<rangle> \\<in> R\"\n  using assms unfolding set_restrict_right_def by blast\n\nlemma set_restrict_left_empty_eq [simp]: \"{}\\<restriction>\\<^bsub>P :: set \\<Rightarrow> bool\\<^esub> = {}\" by auto\n\nlemma set_restrict_left_empty_eq' [simp]: \"R\\<restriction>\\<^bsub>{}\\<^esub> = {}\" by auto\n\nlemma set_restrict_left_subset_self [iff]: \"R\\<restriction>\\<^bsub>P :: set \\<Rightarrow> bool\\<^esub> \\<subseteq> R\" by auto\n\nlemma set_restrict_left_dep_pairs_eq_dep_pairs_collect [simp]:\n  \"(\\<Sum>x \\<in> A. B x)\\<restriction>\\<^bsub>P\\<^esub> = (\\<Sum>x \\<in> {a \\<in> A | P a}. B x)\"\n  by auto\n\nlemma set_restrict_left_dep_pairs_eq_dep_pairs_bin_inter [simp]:\n  \"(\\<Sum>x \\<in> A. B x)\\<restriction>\\<^bsub>A'\\<^esub> = (\\<Sum>x \\<in> A \\<inter> A'. B x)\"\n  by simp\n\nlemma set_restrict_left_subset_dep_pairs_if_subset_dep_pairs [intro]:\n  assumes \"R \\<subseteq> \\<Sum>x \\<in> A. B x\"\n  shows \"R\\<restriction>\\<^bsub>P\\<^esub> \\<subseteq> \\<Sum>x \\<in> {x \\<in> A | P x}. B x\"\n  using assms by auto\n\nlemma set_restrict_left_set_restrict_left_eq_set_restrict_left [simp]:\n  fixes P P' :: \"set \\<Rightarrow> bool\"\n  shows \"(R\\<restriction>\\<^bsub>P\\<^esub>)\\<restriction>\\<^bsub>P\\<^esub> = R\\<restriction>\\<^bsub>P\\<^esub>\"\n  by auto\n\nlemma mono_set_restrict_left_set: \"mono (\\<lambda>R. R\\<restriction>\\<^bsub>P :: set \\<Rightarrow> bool\\<^esub>)\"\n  by (intro monoI) auto\n\nlemma mono_set_restrict_left_pred: \"mono (\\<lambda>P. R\\<restriction>\\<^bsub>P :: set \\<Rightarrow> bool\\<^esub>)\"\n  by (intro monoI) auto\n\n\ndefinition \"agree P \\<R> \\<equiv> \\<forall>R R' \\<in> \\<R>. R\\<restriction>\\<^bsub>P\\<^esub> = R'\\<restriction>\\<^bsub>P\\<^esub>\"\n\nlemma agree_set_iff_agree [iff]: \"agree A \\<R> \\<longleftrightarrow> agree (mem_of A) \\<R>\"\n  unfolding agree_def by simp\n\nlemma agreeI [intro]:\n  assumes \"\\<And>x y R R'. P x \\<Longrightarrow> R \\<in> \\<R> \\<Longrightarrow> R' \\<in> \\<R> \\<Longrightarrow> \\<langle>x, y\\<rangle> \\<in> R \\<Longrightarrow> \\<langle>x, y\\<rangle> \\<in> R'\"\n  shows \"agree P \\<R>\"\n  using assms unfolding agree_def by blast\n\nlemma agreeD:\n  assumes \"agree P \\<R>\"\n  and \"P x\"\n  and \"R \\<in> \\<R>\" \"R' \\<in> \\<R>\"\n  and \"\\<langle>x, y\\<rangle> \\<in> R\"\n  shows \"\\<langle>x, y\\<rangle> \\<in> R'\"\nproof -\n  from assms(2, 5) have \"\\<langle>x, y\\<rangle> \\<in> R\\<restriction>\\<^bsub>P\\<^esub>\" by (intro mem_set_restrict_leftI)\n  moreover from assms(1, 3-4) have \"... = R'\\<restriction>\\<^bsub>P\\<^esub>\" unfolding agree_def by blast\n  ultimately show ?thesis by auto\nqed\n\nlemma antimono_agree_pred: \"antimono (\\<lambda>P. agree (P :: set \\<Rightarrow> bool) \\<R>)\"\n  by (intro antimonoI) (auto dest: agreeD)\n\nlemma antimono_agree_set: \"antimono (\\<lambda>\\<R>. agree (P :: set \\<Rightarrow> bool) \\<R>)\"\n  by (intro antimonoI) (auto dest: agreeD)\n\nlemma set_restrict_left_eq_set_restrict_left_if_agree:\n  fixes P :: \"set \\<Rightarrow> bool\"\n  assumes \"agree P \\<R>\"\n  and \"R \\<in> \\<R>\" \"R' \\<in> \\<R>\"\n  shows \"R\\<restriction>\\<^bsub>P\\<^esub> = R'\\<restriction>\\<^bsub>P\\<^esub>\"\n  using assms by (auto dest: agreeD)\n\nlemma eq_if_subset_dep_pairs_if_agree:\n  assumes \"agree A \\<R>\"\n  and subset_dep_pairs: \"\\<And>R. R \\<in> \\<R> \\<Longrightarrow> \\<exists>B. R \\<subseteq> \\<Sum>x \\<in> A. B x\"\n  and \"R \\<in> \\<R>\"\n  and \"R' \\<in> \\<R>\"\n  shows \"R = R'\"\nproof -\n  from subset_dep_pairs[OF \\<open>R \\<in> \\<R>\\<close>] have \"R = R\\<restriction>\\<^bsub>A\\<^esub>\" by auto\n  also with assms have \"... = R'\\<restriction>\\<^bsub>A\\<^esub>\"\n    by ((subst set_restrict_left_set_eq_set_restrict_left)+,\n      intro set_restrict_left_eq_set_restrict_left_if_agree)\n    auto\n  also from subset_dep_pairs[OF \\<open>R' \\<in> \\<R>\\<close>] have \"... = R'\" by auto\n  finally show ?thesis .\nqed\n\nlemma subset_if_agree_if_subset_dep_pairs:\n  assumes subset_dep_pairs: \"R \\<subseteq> \\<Sum>x \\<in> A. B x\"\n  and \"R \\<in> \\<R>\"\n  and \"agree A \\<R>\"\n  and \"R' \\<in> \\<R>\"\n  shows \"R \\<subseteq> R'\"\n  using assms by (auto simp: agreeD[where ?R=\"R\"])\n\n\nsubsubsection \\<open>Domain and Range\\<close>\n\ndefinition \"dom R \\<equiv> {x | p \\<in> R, \\<exists>y. p = \\<langle>x, y\\<rangle>}\"\n\nlemma mem_domI [intro]:\n  assumes \"\\<langle>x, y\\<rangle> \\<in> R\"\n  shows \"x \\<in> dom R\"\n  using assms unfolding dom_def by fast\n\nlemma mem_domE [elim!]:\n  assumes \"x \\<in> dom R\"\n  obtains y where \"\\<langle>x, y\\<rangle> \\<in> R\"\n  using assms unfolding dom_def by blast\n\nlemma mono_dom: \"mono dom\"\n  by (intro monoI) auto\n\nlemma dom_empty_eq [simp]: \"dom {} = {}\"\n  by auto\n\nlemma dom_union_eq [simp]: \"dom (\\<Union>\\<R>) = \\<Union>{dom R | R \\<in> \\<R>}\"\n  by auto\n\nlemma dom_bin_union_eq [simp]: \"dom (R \\<union> S) = dom R \\<union> dom S\"\n  by auto\n\nlemma dom_collect_eq [simp]: \"dom {\\<langle>f x, g x\\<rangle> | x \\<in> A} = {f x | x \\<in> A}\"\n  by auto\n\nlemma dom_extend_eq [simp]: \"dom (extend x y R) = insert x (dom R)\"\n  by (rule eqI) (auto intro: mem_extendI')\n\nlemma dom_dep_pairs_eqI [intro]:\n  assumes \"\\<And>x. B x \\<noteq> {}\"\n  shows \"dom (\\<Sum>x \\<in> A. B x) = A\"\n  using assms by (intro eqI) auto\n\nlemma dom_restrict_left_eq [simp]: \"dom (R\\<restriction>\\<^bsub>P\\<^esub>) = {x \\<in> dom R | P x}\"\n  by auto\n\nlemma dom_restrict_left_set_eq [simp]: \"dom (R\\<restriction>\\<^bsub>A\\<^esub>) = dom R \\<inter> A\" by simp\n\nlemma glue_subset_dep_pairsI:\n  fixes \\<R> defines \"D \\<equiv> \\<Union>R \\<in> \\<R>. dom R\"\n  assumes all_subset_dep_pairs: \"\\<And>R. R \\<in> \\<R> \\<Longrightarrow> \\<exists>A. R \\<subseteq> \\<Sum>x \\<in> A. B x\"\n  shows \"glue \\<R> \\<subseteq> \\<Sum>x \\<in> D. (B x)\"\nproof\n  fix p assume \"p \\<in> glue \\<R>\"\n  with all_subset_dep_pairs obtain R A where \"p \\<in> R\" \"R \\<in> \\<R>\" \"R \\<subseteq> \\<Sum>x \\<in> A. B x\"\n    by blast\n  then obtain x y where \"p = \\<langle>x, y\\<rangle>\" \"x \\<in> dom R\" \"y \\<in> B x\" by blast\n  with \\<open>R \\<in> \\<R>\\<close> have \"x \\<in> D\" unfolding D_def by auto\n  with \\<open>p = \\<langle>x, y\\<rangle>\\<close> \\<open>y \\<in> B x\\<close> show \"p \\<in> \\<Sum>x \\<in> D. (B x)\" by auto\nqed\n\ndefinition \"rng R \\<equiv> {y | p \\<in> R, \\<exists>x. p = \\<langle>x, y\\<rangle>}\"\n\nlemma mem_rngI [intro]:\n  assumes \"\\<langle>x, y\\<rangle> \\<in> R\"\n  shows \"y \\<in> rng R\"\n  using assms unfolding rng_def by fast\n\nlemma mem_rngE [elim!]:\n  assumes \"y \\<in> rng R\"\n  obtains x where \"\\<langle>x, y\\<rangle> \\<in> R\"\n  using assms unfolding rng_def by blast\n\nlemma mono_rng: \"mono rng\"\n  by (intro monoI) auto\n\nlemma rng_empty_eq [simp]: \"rng {} = {}\"\n  by auto\n\nlemma rng_union_eq [simp]: \"rng (\\<Union>\\<R>) = \\<Union>{rng R | R \\<in> \\<R>}\"\n  by auto\n\nlemma rng_bin_union_eq [simp]: \"rng (R \\<union> S) = rng R \\<union> rng S\"\n  by auto\n\nlemma rng_collect_eq [simp]: \"rng {\\<langle>f x, g x\\<rangle> | x \\<in> A} = {g x | x \\<in> A}\"\n  by auto\n\nlemma rng_extend_eq [simp]: \"rng (extend x y R) = insert y (rng R)\"\n  by (rule eqI) (auto intro: mem_extendI')\n\nlemma rng_dep_pairs_eq [simp]: \"rng (\\<Sum>x \\<in> A. B x) = (\\<Union>x \\<in> A. B x)\"\n  by auto\n\nlemma dom_rel_inv_eq_rng [simp]: \"dom R\\<inverse> = rng R\"\n  by auto\n\nlemma rng_rel_inv_eq_dom [simp]: \"rng R\\<inverse> = dom R\"\n  by auto\n\n\nsubsubsection \\<open>Composition\\<close>\n\ndefinition \"set_comp S R \\<equiv>\n  {p \\<in> dom R \\<times> rng S | \\<exists>z. \\<langle>fst p, z\\<rangle> \\<in> R \\<and> \\<langle>z, snd p\\<rangle> \\<in> S}\"\n\nbundle hotg_comp_syntax begin notation set_comp (infixr \"\\<circ>\" 60) end\nbundle no_hotg_comp_syntax begin no_notation set_comp (infixr \"\\<circ>\" 60) end\nunbundle no_comp_syntax\nunbundle hotg_comp_syntax\n\nlemma mem_compI [intro!]:\n  assumes \"\\<langle>x, y\\<rangle> \\<in> R\"\n  and \"\\<langle>y, z\\<rangle> \\<in> S\"\n  shows \"\\<langle>x, z\\<rangle> \\<in> S \\<circ> R\"\n  using assms unfolding set_comp_def by auto\n\nlemma mem_compE [elim!]:\n  assumes \"p \\<in> S \\<circ> R\"\n  obtains x y z where \"\\<langle>x, y\\<rangle> \\<in> R\" \"\\<langle>y, z\\<rangle> \\<in> S\" \"p = \\<langle>x, z\\<rangle>\"\n  using assms unfolding set_comp_def by auto\n\nlemma dep_pairs_comp_pairs_eq:\n  \"((\\<Sum>x \\<in> B. (C x)) \\<circ> (A \\<times> B)) = A \\<times> (\\<Union>x \\<in> B. (C x))\"\n  by auto\n\nlemma set_comp_assoc: \"T \\<circ> S \\<circ> R = (T \\<circ> S) \\<circ> R\"\n  by auto\n\nlemma mono_set_comp_left: \"mono (\\<lambda>R. R \\<circ> S)\"\n  by (intro monoI) auto\n\nlemma mono_set_comp_right: \"mono (\\<lambda>S. R \\<circ> S)\"\n  by (intro monoI) auto\n\n\nsubsubsection \\<open>Diagonal\\<close>\n\ndefinition \"diag A \\<equiv> {\\<langle>a, a\\<rangle> | a \\<in> A}\"\n\nlemma mem_diagI [intro!]: \"a \\<in> A \\<Longrightarrow> \\<langle>a, a\\<rangle> \\<in> diag A\"\n  unfolding diag_def by auto\n\nlemma mem_diagE [elim!]:\n  assumes \"p \\<in> diag A\"\n  obtains a where \"a \\<in> A\" \"p = \\<langle>a, a\\<rangle>\"\n  using assms unfolding diag_def by auto\n\nlemma mono_diag: \"mono diag\"\n  by (intro monoI) auto\n\n\nend", "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/HOTG/Binary_Relations/SBinary_Relation_Functions.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391599428538, "lm_q2_score": 0.8376199572530448, "lm_q1q2_score": 0.7231940346059701}}
{"text": "theory TreeSum\nimports Main\nbegin\n\n(* exercise 2.6 from Concrete Semantics *)\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 a b c) = (contents a) @ (b # (contents c))\"\n \nfun treesum :: \"int tree \\<Rightarrow> int\" where\n   \"treesum Tip = 0\"\n | \"treesum (Node a b c) = (treesum a) + b + (treesum c)\"\n \ntheorem \"treesum xt = listsum (contents xt)\"\nby (induction; auto)\n\nend\n", "meta": {"author": "tangentstorm", "repo": "tangentlabs", "sha": "49d7a335221e1ae67e8de0203a3f056bc4ab1d00", "save_path": "github-repos/isabelle/tangentstorm-tangentlabs", "path": "github-repos/isabelle/tangentstorm-tangentlabs/tangentlabs-49d7a335221e1ae67e8de0203a3f056bc4ab1d00/isar/concrete-semantics/TreeSum.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9059898305367525, "lm_q2_score": 0.7981867753392728, "lm_q1q2_score": 0.7231491013263047}}
{"text": "theory PropLogic\n  imports Main\nbegin\n\ndatatype 'av formula =\n  p \"'av\"\n  | andf \"'av formula\" \"'av formula\" (infixr \"And\" 68)\n  | negf \"'av formula\" (\"Neg\")\n (* | Falsum *)\n\nlemma and_assoc_example: \"(p 1) And (p 2) And (p 3) = (p 1) And ((p 2) And (p 3))\"\n  by simp\n\nlemma and_assoc_example2: \"(p 1) And (p 2) And (p 3) \\<noteq> ((p 1) And (p 2)) And (p 3)\"\n  by auto\n\nabbreviation orf (infixr \"Or\" 67) where\n\"(orf f1 f2) \\<equiv> Neg ( (Neg f1) And (Neg f2) )\"\n\nlemma binding_prior_example: \"Neg (p 1) Or (p 2) And (p 1) =  (Neg (p 1) Or ((p 2) And (p 1) ) )\"\n  by simp\n\nabbreviation implf (infixr \"Impl\" 68) where\n\"(implf f1 f2) \\<equiv> Neg (f1 And (Neg f2))\"\n\nabbreviation biimplf (infixr \"IImpl\" 69) where\n\"biimplf f1 f2 \\<equiv> (f1 Impl f2) And (f2 Impl f1)\"\n\nfun rg::\"'a formula \\<Rightarrow> nat\" where\n\"rg (p _) = 0\" |\n\"rg (f1 And f2) = max(rg f1)(rg f2) +1\" |\n\"rg (Neg f1) = rg f1 +1\" \n(* | \"rg Falsum = 1\" *)\n\nlemma \"(rg (andf (p (1::nat)) (orf (p 2) (negf (p 1)) ))) = 5\"\n  by(simp)\n\ntype_synonym 'a model = \"('a \\<Rightarrow> bool)\"\n\nfun ext_mod :: \" ('a model) \\<Rightarrow> 'a formula \\<Rightarrow> bool\" where\n\"ext_mod w (p y) = w y\" |\n\"ext_mod w (f1 And f2) = ( (ext_mod w f1) \\<and> (ext_mod w f2) )\" |\n\"ext_mod w (Neg f) = (\\<not> (ext_mod w f))\"\n(* | \"ext_mod w Falsum = False\" *)\n\nfun w_example ::\"nat \\<Rightarrow> bool\" where\n\"w_example n = (n=2)\"\n\nlemma ext_mod_example: \" ext_mod w_example (andf (p (1::nat)) (orf (p 2) (negf (p 1)) )) = False\"\n  by(simp)\n\nabbreviation sem_equiv (infix \"\\<equiv>f\" 70) where\n\"sem_equiv (f1::'a formula) (f2:: 'a formula) \\<equiv> \\<forall> (w :: 'a model). ext_mod w f1 = ext_mod w f2\"\n\nlemma sem_equiv_neg_neg: \"alpha \\<equiv>f ( negf (negf alpha))\"\n  by(simp)\n\nlemma sem_equiv_assoc_and: \"((alpha And beta) And gamma) \\<equiv>f (alpha And (beta And gamma))\"\n  by(simp)\n\nlemma sem_equiv_assoc_or: \"((alpha Or beta) Or gamma) \\<equiv>f (alpha Or beta Or gamma)\"\n  by(simp)\n\nlemma sem_equiv_comm_and: \"(alpha And beta) \\<equiv>f (beta And alpha)\"\n  by(simp, auto)\n\nlemma sem_equiv_comm_or: \"(alpha Or beta) \\<equiv>f (beta Or alpha)\"\n  by(simp, auto)\n\nlemma sem_equiv_diag_and: \"(alpha And alpha) \\<equiv>f alpha\"\n  by(simp)\n\nlemma sem_equiv_diag_or: \"(alpha Or alpha) \\<equiv>f alpha\"\n  by(simp)\n\nlemma sem_equiv_absorb_and: \"(alpha And (alpha Or beta)) \\<equiv>f alpha\"\n  by(simp, auto)\n\nlemma sem_equiv_absorb_or : \"(alpha Or (alpha And beta)) \\<equiv>f alpha\"\n  by(simp, auto)\n\nlemma sem_equiv_distr1: \"(alpha And (beta Or gamma)) \\<equiv>f ((alpha And beta) Or (alpha And gamma))\"\n  by(simp, auto)\n\nlemma sem_equiv_distr2: \"(alpha Or (beta And gamma)) \\<equiv>f ((alpha Or beta) And (alpha Or gamma))\"\n  by(simp, auto)\n\nlemma sem_equiv_demorgan1: \"(Neg (alpha And beta)) \\<equiv>f (Neg alpha Or Neg beta)\"\n  by(simp)\n\nlemma sem_equiv_demorgan2: \"(Neg (alpha Or beta)) \\<equiv>f (Neg alpha And Neg beta)\"\n  by(simp)\n\nlemma sem_equiv_refl: \"alpha \\<equiv>f alpha\"\n  by(simp)\n\nlemma sem_equiv_symm: \"sem_equiv alpha beta \\<longrightarrow> sem_equiv beta alpha\"\n  by(simp)\n\nlemma sem_equiv_trans: \"sem_equiv alpha beta \\<longrightarrow> sem_equiv beta gamma \\<longrightarrow> sem_equiv alpha gamma\"\n  by(simp)\n\nlemma sem_equiv_kongr: \"alpha \\<equiv>f alpha' \\<and> beta \\<equiv>f beta'\n \\<longrightarrow> (andf alpha beta) \\<equiv>f (andf alpha' beta') \\<and>\n     (orf alpha beta) \\<equiv>f (orf alpha' beta') \\<and>\n     (negf alpha) \\<equiv>f (negf alpha')\"\n  by(simp)\n\nabbreviation fulfills where\n\"fulfills (w :: 'a model) (alpha :: 'a formula) \\<equiv> (ext_mod w alpha = True)\"\n\nabbreviation fulfillsS where\n\"fulfillsS (w :: 'a model) (X :: 'a formula set) \\<equiv> (\\<forall> alpha \\<in> X. fulfills w alpha)\"\n\nlemma fulfills_prop_prime: \"\\<forall> (v:: 'a) (w::'a model). fulfills w (p v) \\<longleftrightarrow> w v = True\"\n  by(simp)\n\nlemma fulfills_prop_and: \"fulfills w (alpha And beta) \\<longleftrightarrow> fulfills w alpha \\<and> fulfills w beta\"\n  by(simp)\n\nlemma fulfills_prop_or: \"fulfills w (alpha Or beta) \\<longleftrightarrow> fulfills w alpha \\<or> fulfills w beta\"\n  by(simp)\n\nlemma fulfills_prop_neg: \"fulfills w (Neg alpha ) \\<longleftrightarrow> \\<not> fulfills w alpha\"\n  by(simp)\n\nlemma fulfills_prop_impl: \"fulfills w (alpha Impl beta) \\<longleftrightarrow> ( (fulfills w alpha) \\<longrightarrow> (fulfills w beta))\"\n  by(simp)\n\nabbreviation taut where\n\" taut (alpha :: 'a formula) \\<equiv> \\<forall> (w :: 'a model). fulfills w alpha\"\n\nabbreviation contradiction where\n\"contradiction (alpha :: 'a formula) \\<equiv> \\<nexists> (w :: 'a model). fulfills w alpha\"\n\nlemma taut_example: \"taut (alpha Or Neg alpha)\"\n  by(simp)\n\nlemma contradiction_example1: \"contradiction (alpha And Neg alpha)\"\n  by(simp)\n\nlemma contradiction_example2: \"contradiction (alpha IImpl ( Neg alpha))\"\n  by(simp)\n\nlemma impl_taut_self: \"taut (p1 Impl p1)\"\n  by(simp)\n\nlemma impl_taut_add_praem: \"taut ( p1 Impl (q Impl p1))\"\n  by(simp)\n\nlemma impl_taut_swap_praem: \"taut ( (p1 Impl q Impl r) Impl (q Impl p1 Impl r) )\"\n  by(simp)\n\nlemma impl_taut_circ: \"taut ( (p1 Impl q) Impl (q Impl r) Impl (p1 Impl r) )\"\n  by(simp)\n\nlemma impl_taut_fregecirc: \"taut ( (p1 Impl q Impl r) Impl ( (p1 Impl q) Impl (p1 Impl r)) )\"\n  by(simp)\n\nlemma impl_taut_pierce: \"taut ( ( (p1 Impl q) Impl p1) Impl p1)\"\n  by(simp, blast)\n\ndefinition ImplSem (infix \"\\<Turnstile>\" 74) where\n\" ImplSem (X :: ('a formula) set) (alpha :: 'a formula) \\<equiv>\n  \\<forall> (w:: 'a model). (\\<forall> x \\<in> X. fulfills w x) \\<longrightarrow> fulfills w alpha\"\n\nlemma empty_ImplSem_iff_taut: \"taut alpha \\<longleftrightarrow> {} \\<Turnstile> alpha\"\n  by(simp add: ImplSem_def)\n\nlemma ImplSem_refl: \"alpha \\<in> X \\<longrightarrow> X \\<Turnstile> alpha\"\n  by(simp add:ImplSem_def)\n\nlemma Impl_Sem_mon: \" X \\<subseteq> X' \\<longrightarrow> X \\<Turnstile> alpha \\<longrightarrow> X' \\<Turnstile> alpha\"\n  by(simp add:ImplSem_def, auto)\n\nlemma Impl_Sem_trans: \"(\\<forall> y \\<in> Y. X \\<Turnstile> y) \\<and> Y \\<Turnstile> alpha \\<longrightarrow> X \\<Turnstile> alpha\"\n  by(simp add:ImplSem_def)\n\nlemma Impl_Sem_and_example1: \"{alpha, beta} \\<Turnstile> (alpha And beta)\"\n  by(simp add:ImplSem_def)\n\nlemma Impl_Sem_and_example2: \"{alpha And beta} \\<Turnstile> alpha\"\n  by(simp add:ImplSem_def)\n\nlemma Impl_Sem_and_example3: \"{alpha And beta} \\<Turnstile> beta\"\n  by(simp add:ImplSem_def)\n\nlemma Impl_Sem_and_example4: \"(X \\<Turnstile> (alpha And beta) ) \\<longleftrightarrow> ( X \\<Turnstile> alpha \\<and> X \\<Turnstile> beta )\"\n  by(simp add:ImplSem_def, auto)\n\nlemma Impl_Sem_impl_example: \"{alpha, alpha Impl beta} \\<Turnstile> beta\"\n  by(simp add: ImplSem_def)\n\nlemma Impl_Sem_elim_example:\n\"(X \\<union> {alpha}) \\<Turnstile> beta \\<and> (X \\<union> {Neg alpha}) \\<Turnstile> beta \\<longrightarrow> X \\<Turnstile> beta\"\n  by(simp add: ImplSem_def, auto)\n\ntype_synonym 'a subst = \"('a \\<Rightarrow> 'a formula)\"\n\nfun ext_subst ::\"'a subst \\<Rightarrow> 'a formula \\<Rightarrow> 'a formula\" where\n\"ext_subst sigma (p v) = sigma v\" |\n\"ext_subst sigma (f1 And f2) = (ext_subst sigma f1) And (ext_subst sigma f2)\" |\n\"ext_subst sigma (Neg f) = Neg (ext_subst sigma f)\"\n(* | \"ext_subst sigma Falsum = Falsum\" *)\n\nfun app_subst ::\"'a subst \\<Rightarrow> 'a formula set \\<Rightarrow> 'a formula set\" where\n\"app_subst sigma X = ext_subst sigma ` X\"\n\nlemma app_subst_demo:\n\"app_subst (\\<lambda> n. (p (n+2) ) And (p (n+1) )) { p (1:: nat), (p (2::nat)) And (p (3::nat))}\n= {p 3 And p 2, (p 4 And p 3) And p 5 And p 4} \" by(auto)\n\n(*\nlemma subst_helper_lemma:\n\" fulfills (w :: 'a model) (ext_subst sigma alpha)\n= fulfills (\\<lambda> (a :: 'a). ext_mod w (sigma a)) alpha\"\n  apply(induction alpha) apply(auto) done\n*)\n\nlemma subst_helper_lemma2:\n\" ext_mod (w :: 'a model) (ext_subst sigma alpha)\n= ext_mod (\\<lambda> (a :: 'a). ext_mod w (sigma a)) alpha\"\n  by(induction alpha, auto)\n\ntheorem substituion_invariance: \"X \\<Turnstile> alpha \\<longrightarrow> app_subst sigma X \\<Turnstile> ext_subst sigma alpha\"\n  apply(simp add:ImplSem_def) apply(auto)\n  apply(simp add:subst_helper_lemma2) done\n\ntheorem deduction_theorem: \" (X \\<union> {alpha}) \\<Turnstile> beta \\<longleftrightarrow> X \\<Turnstile> (alpha Impl beta)\"\n  apply(simp add:ImplSem_def) apply(auto) done\n\ninductive ImplGen :: \"'a formula set \\<Rightarrow> 'a formula \\<Rightarrow> bool\" (infix \"\\<turnstile>\" 56) where\nAR: \"ImplGen {alpha} alpha\" |\nMR: \"\\<lbrakk> (X::'a formula set) \\<subseteq> (X' ::'a formula set) ; ImplGen X alpha \\<rbrakk> \\<Longrightarrow> ImplGen X' alpha\" |\nANDI: \"\\<lbrakk> ImplGen X alpha ; ImplGen X beta \\<rbrakk> \\<Longrightarrow> ImplGen X (alpha And beta)\" |\nANDl: \"ImplGen X (alpha And beta) \\<Longrightarrow> ImplGen X alpha\" |\nANDr: \"ImplGen X (alpha And beta) \\<Longrightarrow> ImplGen X beta\" |\nNEG1: \" \\<lbrakk> ImplGen X alpha ; ImplGen X (Neg alpha) \\<rbrakk> \\<Longrightarrow> ImplGen X beta\" |\nNEG2: \" \\<lbrakk> ImplGen (X \\<union> {alpha}) beta ; ImplGen (X \\<union> { Neg alpha}) beta \\<rbrakk>\n       \\<Longrightarrow> ImplGen X beta\"\n\nlemma ImplGen_and_example: \"{alpha, beta} \\<turnstile> (alpha And beta)\"\nproof -\n  from ImplGen.AR have \"{alpha} \\<turnstile> alpha\" by(auto)\n  hence A: \"{alpha,beta} \\<turnstile> alpha\" by(simp add: ImplGen.MR[of \"{alpha}\" \"{alpha,beta}\"])\n  from ImplGen.AR have \"{beta} \\<turnstile> beta\" by(auto)\n  hence B: \"{alpha,beta} \\<turnstile> beta\" by(simp add: ImplGen.MR[of \"{beta}\" \"{alpha,beta}\"])\n  from A B show \"{alpha, beta} \\<turnstile> (alpha And beta)\" by(rule ImplGen.ANDI)\nqed\n\nlemma ImplGen_neg_elim_example: \"X \\<union> {Neg alpha} \\<turnstile> alpha \\<longrightarrow> X \\<turnstile> alpha\"\nproof\n  assume A: \"X \\<union> {Neg alpha} \\<turnstile> alpha\"\n  have 0: \"{alpha} \\<turnstile> alpha\" by(rule AR)\n  have 1: \"{alpha} \\<subseteq> X \\<union> {alpha}\" by(auto)\n  from 0 1 MR have 2: \"X \\<union> {alpha} \\<turnstile> alpha\" by(blast)\n  from A 2 NEG2 show \"X \\<turnstile> alpha\" by(auto)\nqed\n\nlemma ImplGen_reductio_example: \" (X \\<union> {Neg alpha} \\<turnstile> beta \\<and>\nX \\<union> {Neg alpha} \\<turnstile> Neg beta ) \\<longrightarrow> X \\<turnstile> alpha\"\nproof\n  assume A: \" X \\<union> {Neg alpha} \\<turnstile> beta \\<and> X \\<union> {Neg alpha} \\<turnstile> Neg beta\"\n  from A have A1: \"X \\<union> {Neg alpha} \\<turnstile> beta\" by(simp)\n  from A have A2: \"X \\<union> {Neg alpha} \\<turnstile> Neg beta\" by (simp)\n  from A1 A2 have 2: \"X \\<union> {Neg alpha} \\<turnstile> alpha\" by (rule NEG1)\n  from 2 ImplGen_neg_elim_example show \"X \\<turnstile> alpha\" by (auto)\nqed\n\nlemma ImplGen_rightarrow_elim_example: \" (X \\<turnstile> alpha Impl beta) \\<longrightarrow> X \\<union> {alpha} \\<turnstile> beta\"\nproof\n  assume H: \"(X \\<turnstile> alpha Impl beta)\"\n  from ImplGen.AR[of \"alpha\"] ImplGen.MR[of \"{alpha}\" \"X \\<union> {alpha, Neg beta}\"]\n  have A: \"X \\<union> {alpha, Neg beta} \\<turnstile> alpha\" by(auto)\n  from ImplGen.AR[of \"Neg beta\"] ImplGen.MR[of \"{Neg beta}\" \"X \\<union> {alpha, Neg beta}\"]\n  have B: \"X \\<union> {alpha, Neg beta} \\<turnstile> Neg beta\" by(auto)\n  from A B have 2: \"X \\<union> {alpha, Neg beta} \\<turnstile> alpha And (Neg beta)\" by(rule ImplGen.ANDI)\n  from H have 3: \"X \\<turnstile> Neg(alpha And Neg beta)\" by(simp)\n  from ImplGen.MR 3 have 4: \"X \\<union> {alpha, Neg beta} \\<turnstile> Neg(alpha And Neg beta)\" by(blast)\n  from 2 4 have 5: \"X \\<union> {alpha, Neg beta} \\<turnstile> beta\" by(rule ImplGen.NEG1)\n  from this ImplGen_neg_elim_example [of \"X \\<union> {alpha}\" \"beta\"]\n  show \"X \\<union> {alpha} \\<turnstile> beta\" by (simp add: insert_commute)\nqed\n\n(* TODO: Further examples *)\n\ntheorem ImplGen_correct:\"X \\<turnstile> alpha \\<longrightarrow> X \\<Turnstile> alpha\"\nproof\n  fix alpha\n  show \"X \\<turnstile> alpha \\<Longrightarrow> X \\<Turnstile> alpha\"\n  proof(induction alpha rule: ImplGen.induct)\ncase (AR alpha)\n  thus \"{alpha} \\<Turnstile> alpha\" by(simp add:ImplSem_refl)\nnext\ncase (MR X X' alpha)\n  thus ?case by(simp add:Impl_Sem_mon)\nnext\ncase (ANDI X alpha beta)\n  thus ?case by(simp add:Impl_Sem_and_example4)\nnext\n  case (ANDl X alpha beta)\n  thus ?case by(simp add: Impl_Sem_and_example4)\nnext\ncase (ANDr X alpha beta)\n  thus ?case by(simp add: Impl_Sem_and_example4)\nnext\n  case (NEG1 X alpha beta)\n  thus ?case by(simp add: ImplSem_def, auto)\nnext\ncase (NEG2 X alpha beta)\n  thus ?case by(simp add: Impl_Sem_elim_example[of \"X\" \"alpha\" \"beta\"])\nqed\nqed\n  \ntheorem finiteness_theorem: \"((X :: 'a formula set) \\<turnstile> (alpha :: 'a formula) ) \\<Longrightarrow>\n      (\\<exists> (X0 :: 'a formula set). X0 \\<subseteq> X \\<and> finite X0 \\<and> X0 \\<turnstile> alpha )\"\nproof(induction rule: ImplGen.induct)\n  case (AR alpha)\n  show ?case proof\n    have 1: \"{alpha} \\<turnstile> alpha\" by(rule AR)\n    have 2: \"finite {alpha}\" by(auto)\n    from 1 2 show \"{alpha} \\<subseteq> {alpha} \\<and> finite {alpha} \\<and> {alpha} \\<turnstile> alpha\" by(simp)\n  qed\nnext\n  case(MR X X' alpha)\n  from MR.IH obtain X0 where pX0: \"X0\\<subseteq>X \\<and> finite X0 \\<and> X0 \\<turnstile> alpha\" by(auto)\n  show ?case proof\n      from pX0 MR(1) have SP: \"X0 \\<subseteq> X'\" by (auto)\n      from SP pX0 show \"X0\\<subseteq>X' \\<and> finite X0 \\<and> X0 \\<turnstile> alpha\" by(simp)\n    qed\nnext\n  case (ANDI X alpha beta)\n  from ANDI.IH(1) obtain X0a where pX0a: \"X0a\\<subseteq>X \\<and> finite X0a \\<and> X0a \\<turnstile> alpha\" by(auto)\n  from ANDI.IH(2) obtain X0b where pX0b: \"X0b\\<subseteq>X \\<and> finite X0b \\<and> X0b \\<turnstile> beta\" by(auto)\n  show ?case proof\n    from pX0a pX0b have p1: \"(X0a \\<union> X0b) \\<subseteq> X\" by(auto)\n    from pX0a pX0b have p2: \"finite (X0a \\<union> X0b)\" by(auto)\n    from pX0a MR have p3: \"(X0a \\<union> X0b) \\<turnstile> alpha\" by(blast)\n    from pX0b MR have p4: \"(X0a \\<union> X0b) \\<turnstile> beta\" by(blast)\n    from p3 p4 have p5: \"(X0a \\<union> X0b) \\<turnstile> (alpha And beta)\" by (rule ImplGen.ANDI)\n    from p1 p2 p5 show \"( X0a \\<union> X0b) \\<subseteq> X \\<and> finite ( X0a \\<union> X0b) \\<and> ( X0a \\<union> X0b) \\<turnstile> alpha And beta\" by(auto)\n  qed\nnext\n  case (ANDl X alpha beta)\n  from ANDl.IH obtain X0 where pX0: \"X0\\<subseteq>X \\<and> finite X0 \\<and> X0 \\<turnstile> (alpha And beta)\" by(auto)\n  show ?case proof\n    from ImplGen.ANDl pX0 show \"X0 \\<subseteq> X \\<and> finite X0 \\<and> X0 \\<turnstile> alpha\" by(auto)\n  qed\nnext\n  case (ANDr X alpha beta)\n  from ANDr.IH obtain X0 where pX0: \"X0\\<subseteq>X \\<and> finite X0 \\<and> X0 \\<turnstile> (alpha And beta)\" by(auto)\n  show ?case proof\n    from ImplGen.ANDr pX0 show \"X0 \\<subseteq> X \\<and> finite X0 \\<and> X0 \\<turnstile> beta\" by(auto)\n  qed\nnext\n  case (NEG1 X alpha beta)\n  from NEG1.IH(1) obtain X0p where pX0p: \"X0p\\<subseteq>X \\<and> finite X0p \\<and> X0p \\<turnstile> alpha\" by(auto)\n  from NEG1.IH(2) obtain X0n where pX0n: \"X0n\\<subseteq>X \\<and> finite X0n \\<and> X0n \\<turnstile> Neg alpha\" by(auto)\n  show ?case proof\n    from pX0p pX0n have p1: \"(X0p \\<union> X0n) \\<subseteq> X\" by(auto)\n    from pX0p pX0n have p2: \"finite (X0p \\<union> X0n)\" by(auto)\n    from pX0p MR have p3: \"(X0p \\<union> X0n) \\<turnstile> alpha\" by(blast)\n    from pX0n MR have p4: \"(X0p \\<union> X0n) \\<turnstile> Neg alpha\" by(blast)\n    from p3 p4 have p5: \"(X0p \\<union> X0n) \\<turnstile> beta\" by (rule ImplGen.NEG1)\n    from p1 p2 p5 show \"( X0p \\<union> X0n) \\<subseteq> X \\<and> finite ( X0p \\<union> X0n) \\<and> ( X0p \\<union> X0n) \\<turnstile> beta\" by(auto)\n  qed\nnext\n  case (NEG2 X alpha beta)\n  from NEG2.IH(1) obtain X0p where pX0p: \"X0p\\<subseteq>X\\<union> {alpha} \\<and> finite X0p \\<and> X0p \\<turnstile> beta\" by(auto)\n  from NEG2.IH(2) obtain X0n where pX0n: \"X0n\\<subseteq>X\\<union> {Neg alpha} \\<and> finite X0n \\<and> X0n \\<turnstile> beta\" by(auto)\n  show ?case proof\n    from pX0p pX0n have p1: \"((X0p - {alpha}) \\<union> (X0n - {Neg alpha})) \\<subseteq> X\" by(auto)\n    from pX0p pX0n have p2: \"finite ((X0p \\<union> X0n)- {alpha, Neg alpha})\" by(auto)\n    have \"X0p \\<subseteq> ((X0p - {alpha}) \\<union> {alpha})\" by (blast)\n    from this pX0p have p3: \"((X0p - {alpha}) \\<union> {alpha}) \\<turnstile> beta\" by(simp add: ImplGen.MR)\n    have \"X0n \\<subseteq> ((X0n - {Neg alpha}) \\<union> {Neg alpha})\" by (blast)\n    from this pX0n have p4: \"((X0n - {Neg alpha}) \\<union> {Neg alpha}) \\<turnstile> beta\" by(simp add: ImplGen.MR)\n    have \"((X0p - {alpha}) \\<union> {alpha}) \\<subseteq> ((X0p - {alpha}) \\<union> (X0n - {Neg alpha})) \\<union> {alpha}\" by(blast)\n    from this p3 have p5: \"((X0p - {alpha}) \\<union> (X0n - {Neg alpha})) \\<union> {alpha} \\<turnstile> beta\" by(rule ImplGen.MR)\n    have \"((X0n - {Neg alpha}) \\<union> {Neg alpha}) \\<subseteq> ((X0p - {alpha}) \\<union> (X0n - {Neg alpha})) \\<union> {Neg alpha}\" by(blast)\n    from this p4 have p6: \"((X0p - {alpha}) \\<union> (X0n - {Neg alpha})) \\<union> {Neg alpha} \\<turnstile> beta\" by(rule ImplGen.MR)\n    from p5 p6 have p7: \"((X0p - {alpha}) \\<union> (X0n - {Neg alpha})) \\<turnstile> beta\" by(rule ImplGen.NEG2)\n    from p7 p1 p2 show \"((X0p - {alpha}) \\<union> (X0n - {Neg alpha}))\\<subseteq>X\n               \\<and> finite ((X0p - {alpha}) \\<union> (X0n - {Neg alpha}))\n               \\<and> ((X0p - {alpha}) \\<union> (X0n - {Neg alpha})) \\<turnstile> beta\" by (auto)\n  qed\nqed\n\ndefinition incons_FS ::\"'a formula set \\<Rightarrow> bool\" where\n\"incons_FS (X:: 'a formula set) \\<equiv> \\<forall> (alpha::'a formula). X \\<turnstile> alpha\"\n\nabbreviation cons_FS ::\"'a formula set \\<Rightarrow> bool\" where\n\"cons_FS X \\<equiv> \\<not> incons_FS X\"\n\ndefinition max_cons_FS::\"'a formula set \\<Rightarrow> bool\" where\n\"max_cons_FS (X :: 'a formula set) \\<equiv>\n   (cons_FS X) \\<and> ( \\<forall> (Y :: 'a formula set). Y \\<supset> X \\<longrightarrow> incons_FS Y)\"\n\nabbreviation Falsum where\n\"Falsum (f :: 'a formula) \\<equiv> (f) And (Neg f)\"\n\nlemma incons_prop: \"\\<forall> (f :: 'a formula). X \\<turnstile> Falsum f \\<longleftrightarrow> incons_FS X\"\nproof\n  fix f show \"X \\<turnstile> Falsum f \\<longleftrightarrow> incons_FS X\" proof\n    assume H: \"X \\<turnstile> Falsum f\"\n    have \"\\<forall> alpha. X \\<turnstile> alpha\" proof\n      fix alpha\n      from H ImplGen.ANDl ImplGen.ANDr ImplGen.NEG1 show \"X \\<turnstile> alpha\" by(blast)\n    qed\n    from this incons_FS_def show \"incons_FS X\" by(auto)\n  next\n    assume \"incons_FS X\"\n    hence H:\"\\<forall> alpha. X \\<turnstile> Falsum f\" by(simp add: incons_FS_def)\n    thus \"X \\<turnstile> Falsum f\" by (auto)\n  qed\nqed\n\nlemma cons_prop: \" \\<forall> (f :: 'a formula). \\<not> ( X \\<turnstile> Falsum f) \\<longleftrightarrow> cons_FS X\"\n  by(simp add: incons_prop)\n\nlemma Cplus_ImplSem_prop: \" X \\<turnstile> alpha \\<longleftrightarrow> incons_FS ( X \\<union> { Neg alpha} )\"\nproof\n  assume H: \"X \\<turnstile> alpha\"\n  from this ImplGen.MR have 1: \"X \\<union> {Neg alpha} \\<turnstile> alpha\" by(blast)\n  have 2: \"{Neg alpha} \\<turnstile> Neg alpha\" by(rule ImplGen.AR)\n  from this ImplGen.MR have 3: \"X \\<union> {Neg alpha} \\<turnstile> Neg alpha\" by(blast)\n  from 1 3 ImplGen.NEG1 have \"\\<forall> beta. X \\<union> {Neg alpha} \\<turnstile> beta\" by(auto)\n  thus \"incons_FS (X \\<union> {Neg alpha}) \" by(simp add: incons_FS_def)\nnext\n  assume \"incons_FS (X \\<union> {Neg alpha})\"\n  hence 1:\"X \\<union> {Neg alpha} \\<turnstile> alpha\" by(simp add:incons_FS_def)\n  from ImplGen.MR ImplGen.AR have 2: \"X \\<union> {alpha} \\<turnstile> alpha\" by (blast)\n  from 1 2 ImplGen.NEG2 show \"X \\<turnstile> alpha\" by(auto)\nqed\n\nlemma Cplus_ImplSem_prop2: \"\\<forall> (f :: 'a formula).\n                     X \\<turnstile> alpha \\<longleftrightarrow> (X \\<union> {Neg alpha}) \\<turnstile> Falsum f\"\nproof\n  fix f show \" X \\<turnstile> alpha \\<longleftrightarrow> (X \\<union> {Neg alpha}) \\<turnstile> Falsum f\" proof\n    assume H: \"X \\<turnstile> alpha\"\n    from this Cplus_ImplSem_prop have \"incons_FS (X \\<union> {Neg alpha})\" by(auto)\n    from this incons_prop show \"(X \\<union> {Neg alpha}) \\<turnstile> Falsum f\" by(auto)\n  next\n    assume H: \"(X \\<union> {Neg alpha}) \\<turnstile> Falsum f\"\n    from this incons_prop have \"incons_FS (X \\<union> {Neg alpha})\" by(auto)\n    from this Cplus_ImplSem_prop show \"X \\<turnstile> alpha\" by(auto)\n  qed\nqed\n\nlemma Cminus_ImplSem_prop: \" X \\<turnstile> Neg alpha \\<longleftrightarrow> incons_FS ( X \\<union> {alpha} )\"\nproof\n  assume H: \"X \\<turnstile> Neg alpha\"\n  from this ImplGen.MR have 1: \"X \\<union> {alpha} \\<turnstile> Neg alpha\" by(blast)\n  have 2: \"{alpha} \\<turnstile> alpha\" by(rule ImplGen.AR)\n  from this ImplGen.MR have 3: \"X \\<union> {alpha} \\<turnstile> alpha\" by(blast)\n  from 1 3 ImplGen.NEG1 have \"\\<forall> beta. X \\<union> {alpha} \\<turnstile> beta\" by(auto)\n  thus \"incons_FS (X \\<union> { alpha}) \" by(simp add: incons_FS_def)\nnext\n  assume \"incons_FS (X \\<union> {alpha})\"\n  hence 1:\"X \\<union> {alpha} \\<turnstile> Neg alpha\" by(simp add:incons_FS_def)\n  from ImplGen.MR ImplGen.AR have 2: \"X \\<union> {Neg alpha} \\<turnstile> Neg alpha\" by (blast)\n  from 1 2 ImplGen.NEG2 show \"X \\<turnstile> Neg alpha\" by(auto)\nqed\n\nlemma Cminus_ImplSem_prop2: \"\\<forall> (f :: 'a formula).\n                    X \\<turnstile> Neg alpha \\<longleftrightarrow> (X \\<union> {alpha}) \\<turnstile> Falsum f\"\nproof\n  fix f show \"X \\<turnstile> Neg alpha \\<longleftrightarrow> (X \\<union> {alpha}) \\<turnstile> Falsum f\" proof\n    assume H: \"X \\<turnstile> Neg alpha\"\n    from this Cminus_ImplSem_prop have \"incons_FS (X \\<union> {alpha})\" by(auto)\n    from this incons_prop show \"(X \\<union> {alpha}) \\<turnstile> Falsum f\" by(auto)\n  next\n    assume H: \"(X \\<union> {alpha}) \\<turnstile> Falsum f\"\n    from this incons_prop have \"incons_FS (X \\<union> {alpha})\" by(auto)\n    from this Cminus_ImplSem_prop show \"X \\<turnstile> Neg alpha\" by(auto)\n  qed\nqed\n\ndefinition H::\"'a formula set \\<Rightarrow> 'a formula set set\" where\n\"H X = { Y. X \\<subseteq> Y \\<and> cons_FS Y}\"\n\nlemma finite_chain_contains_Union:\n\"finite (F :: 'a set set) \\<Longrightarrow> F \\<noteq> {} \\<Longrightarrow> \n (\\<forall> x \\<in>F. \\<forall> y \\<in> F. (x \\<subseteq> y) \\<or> (y \\<subseteq> x) )\n \\<Longrightarrow> \\<Union> F \\<in> F\"\nproof(induct F rule: finite_induct)\n  case empty\n  then show ?case by(simp)\nnext\n  case (insert x F)\n  then show ?case\n    by (metis Sup_insert Un_absorb1 Un_absorb2 ccpo_Sup_singleton insertCI)\nqed\n\nlemma empty_set_consistent: \"\\<not> ( {} \\<turnstile> Falsum alpha)\"\nproof\n  assume H: \"{} \\<turnstile> (alpha :: 'a formula) And (Neg alpha)\"\n  from H have \"{} \\<turnstile> alpha\" by (simp add: ImplGen.ANDl)\n  hence A: \"{} \\<Turnstile> alpha\" by (simp add: ImplGen_correct)\n  hence \"\\<forall> w. fulfills w alpha\" by(simp add: ImplSem_def)\n  hence \"ext_mod (\\<lambda> v. True) alpha = True\" by(auto)\n  hence CON1: \"ext_mod (\\<lambda> v. True) (Neg alpha) = False\" by(auto)\n  from H have \"{} \\<turnstile> Neg alpha\" by (simp add: ImplGen.ANDr)\n  hence B: \"{} \\<Turnstile> Neg alpha\" by (simp add: ImplGen_correct)\n  hence \"\\<forall> w. fulfills w (Neg alpha)\" by(simp add: ImplSem_def[of \"{}\" \"Neg alpha\"])\n  hence CON2: \"ext_mod (\\<lambda> v. True) (Neg alpha) = True\" by(auto)\n  from CON1 CON2 show \"False\" by(auto)\nqed\n\nlemma lindenbaum: \"cons_FS (X:: 'a formula set) \\<longrightarrow> ( \\<exists> X'. X \\<subseteq> X' \\<and> max_cons_FS X' )\"\nproof\n  assume \"cons_FS X\"\n  from this H_def have 0: \"X \\<in> H X\" by(blast)\n\n  have \" \\<forall> K . subset.chain (H X) K \\<longrightarrow> (\\<exists> U \\<in> (H X). \\<forall> X' \\<in>K . X' \\<subseteq> U)\" proof\n    fix K :: \"'a formula set set\"\n    have \"K = {} \\<or> K \\<noteq> {}\" by(auto)\n    then show \"subset.chain (H X) K \\<longrightarrow> (\\<exists> U \\<in> (H X). \\<forall> X' \\<in>K . X' \\<subseteq> U)\" proof\n    assume A: \"K = {}\"\n    show \"subset.chain (H X) K \\<longrightarrow> (\\<exists> U \\<in> (H X). \\<forall> X' \\<in>K . X' \\<subseteq> U)\" proof\n      assume 1: \"subset.chain (H X) K\"\n      show \"(\\<exists> U \\<in> (H X). \\<forall> X' \\<in>K . X' \\<subseteq> U)\" proof\n        from A show \"\\<forall> X' \\<in> K. X' \\<subseteq> X\" by(auto)\n        from 0 show \"X \\<in> H X\" by(simp)\n      qed\n    qed\n  next\n    assume B: \"K \\<noteq> {}\"\n    show \"subset.chain (H X) K \\<longrightarrow> (\\<exists> U \\<in> (H X). \\<forall> X' \\<in>K . X' \\<subseteq> U)\" proof\n      assume 1: \"subset.chain (H X) K\"\n        show \"(\\<exists> U \\<in> (H X). \\<forall> X' \\<in>K . X' \\<subseteq> U)\" proof\n          show \"\\<forall> X' \\<in> K. X' \\<subseteq> \\<Union> K\" by (auto)\n          from 1 subset.chain_def have 2: \"K \\<subseteq> (H X)\" by(auto)\n          from this H_def have 3: \"\\<forall> Y \\<in> K. X \\<subseteq> Y\" by(auto)\n          from B 3 have 4: \"X \\<subseteq> \\<Union> K\" by(auto)\n          have 5: \"cons_FS (\\<Union> K)\" proof(rule ccontr)\n            assume \"\\<not> cons_FS (\\<Union> K)\"\n            hence \"incons_FS (\\<Union> K)\" by(simp)\n            hence \"\\<Union> K \\<turnstile> Falsum alpha\" by(simp add: incons_prop)\n            hence \"\\<exists> U0 \\<subseteq> \\<Union> K. finite U0 \\<and> U0 \\<turnstile> Falsum alpha\" by(simp add:finiteness_theorem)\n            then obtain U0 where 6: \"U0 \\<subseteq> \\<Union> K \\<and> finite U0 \\<and> U0 \\<turnstile> Falsum alpha\" by(auto)\n            then have fin: \"finite U0\" by(auto)\n            from 6 have 7: \"\\<forall> alpha_i \\<in> U0. \\<exists> Y. Y \\<in> K \\<and> alpha_i \\<in> Y\" by(auto)\n            from finite_set_choice[OF fin 7] obtain f where fprop: \"\\<forall> alpha_i \\<in> U0. f alpha_i \\<in> K \\<and> alpha_i \\<in> f alpha_i\" by(auto)\n            from fprop have \"U0 \\<subseteq> \\<Union> (f ` U0)\" by(auto) (* Y = \\<Union> (f ` U0) *)\n            from this 6 ImplGen.MR have CON1: \"\\<Union> (f ` U0) \\<turnstile> Falsum alpha\" by(auto)\n            from fin have fin': \"finite ( (f ` U0) )\" by(auto)\n            from fprop 1 have \"subset.chain (H X) (f ` U0)\" by (simp add: subset.chain_def subset_eq)\n            from this subset.chain_def[of \"H X\" \"(f ` U0)\"] have 8: \"\\<forall> x \\<in> (f` U0). \\<forall> y \\<in> (f` U0). x \\<subseteq> y \\<or> y \\<subseteq> x\" by(auto)\n            have U0_nonempty: \"U0 \\<noteq> {}\" proof\n              assume \"U0 = {}\"\n              from this 6 have \"{} \\<turnstile> Falsum alpha\" by(auto)\n              from this empty_set_consistent show \"False\" by(auto)\n            qed\n            from this have \"(f ` U0) \\<noteq> {}\" by(auto)\n            from this 8 fin' finite_chain_contains_Union[of \"(f ` U0)\"] have \"\\<Union> (f` U0) \\<in> (f ` U0)\" by(auto)\n            from this fprop 2 have \"\\<Union> (f ` U0) \\<in> (H X)\" by(auto)\n            from this have \"cons_FS ( \\<Union> (f `U0) )\" by(simp add: H_def)\n            from this have CON2: \"\\<not> ( \\<Union> (f `U0) \\<turnstile> Falsum alpha )\" by(simp add: cons_prop)\n            from CON1 CON2  show \"False\"  by(auto)\n          qed\n          from 4 5 H_def show \"\\<Union> K \\<in> (H X)\" by(auto)\n        qed\n      qed\n    qed\n  qed\n  from this subset_Zorn have \"\\<exists> M \\<in> (H X). \\<forall> X' \\<in> (H X). M \\<subseteq> X' \\<longrightarrow> X' = M\" by(blast)\n  then obtain M where Mprop: \"M \\<in> (H X) \\<and> (\\<forall> X' \\<in> (H X). M \\<subseteq> X' \\<longrightarrow> X' = M)\" by(auto)\n  show \" \\<exists>X'. X \\<subseteq> X' \\<and> max_cons_FS X'\" proof\n    from Mprop have Prop1: \"X \\<subseteq> M\" by(simp add: H_def)\n    from Mprop have 2: \"cons_FS M\" by(simp add:H_def)\n    have 3: \"\\<forall> Y. M \\<subset> Y \\<longrightarrow> incons_FS Y\" proof\n      fix Y show \"M \\<subset> Y \\<longrightarrow> incons_FS Y\" proof\n        assume H1: \"M \\<subset> Y\" show \"incons_FS Y\" proof(rule ccontr)\n          assume H2: \"cons_FS Y\"\n          from H_def[of \"X\"] H2 Prop1 H1 have \"Y \\<in> (H X)\" by (simp add:H_def)\n          from this Mprop H1 have \"M = Y\" by(blast)\n          from this H1 show \"False\" by(auto)\n        qed\n      qed\n    qed\n    from 2 3 max_cons_FS_def have Prop2: \"max_cons_FS M\" by(auto)\n    from Prop1 Prop2 show \"X \\<subseteq> M \\<and> max_cons_FS M \" by(auto)\n  qed\nqed\n\nlemma max_cons_set_prop: \"max_cons_FS X \\<longrightarrow> (\\<forall> alpha. X \\<turnstile> Neg alpha \\<longleftrightarrow> \\<not> (X \\<turnstile> alpha))\"\nproof\n  assume H1: \"max_cons_FS X\" show \"(\\<forall> alpha. X \\<turnstile> Neg alpha \\<longleftrightarrow> \\<not> (X \\<turnstile> alpha))\" proof\n    fix alpha show \"X \\<turnstile> Neg alpha \\<longleftrightarrow> \\<not> (X \\<turnstile> alpha)\" proof\n      assume H2: \"X \\<turnstile> Neg alpha\"\n      show \"\\<not> (X \\<turnstile> alpha)\" proof(rule ccontr)\n        assume \"\\<not> \\<not> X \\<turnstile> alpha\"\n        hence \"X \\<turnstile> alpha\" by(auto)\n        from this H2 have \"X \\<turnstile> (alpha And (Neg alpha) )\" by(simp add: ImplGen.ANDI)\n        hence \"incons_FS X\" by (simp add: incons_prop)\n        from this H1 show \"False\" by(simp add: max_cons_FS_def)\n      qed\n    next\n      assume H3: \"\\<not> (X \\<turnstile> alpha)\"\n      hence \"cons_FS (X \\<union> {Neg alpha})\" by(simp add:Cplus_ImplSem_prop)\n      from this H1 max_cons_FS_def[of \"X\"] have \"Neg alpha \\<in> X\" by(auto)\n      from this ImplGen.AR[of\"Neg alpha\"] ImplGen.MR show \"X \\<turnstile> Neg alpha\" by(blast)\n    qed\n  qed\nqed\n\nlemma max_cons_fullfillable:\n\" max_cons_FS (X:: 'a formula set) \\<longrightarrow> ( \\<exists> (w :: 'a model). fulfillsS w X )\"\nproof\n  assume H: \"max_cons_FS ( X :: 'a formula set)\"\n  show \" \\<exists> (w :: 'a model). fulfillsS w X\" proof\n    have star: \"\\<forall> alpha :: 'a formula. fulfills (\\<lambda> (a :: 'a). X \\<turnstile> p a) alpha \\<longleftrightarrow> X \\<turnstile> alpha\"\n    proof fix alpha show \"fulfills (\\<lambda> (a :: 'a). X \\<turnstile> p a) alpha \\<longleftrightarrow> X \\<turnstile> alpha\" proof(induction alpha)\n      case (p x)\n      then show ?case by(auto)\n    next\n      case (andf alpha1 alpha2)\n      then show ?case using ANDI ANDl ANDr ext_mod.simps(2) by blast\n    next\n     case (negf alpha)\n     then show ?case by (simp add: negf.IH H max_cons_set_prop)\n   qed\n qed\n  have \"\\<forall> alpha \\<in> X. X \\<turnstile> alpha\" using ImplGen.AR ImplGen.MR by blast\n  from this star show \"\\<forall> alpha \\<in> X. fulfills (\\<lambda> (a :: 'a). X \\<turnstile> p a) alpha\" by(simp)\n  qed\nqed\n\ntheorem completeness_theorem: \"\\<forall> (X:: 'a formula set) (alpha :: 'a formula).\n X \\<turnstile> alpha \\<longleftrightarrow> X \\<Turnstile> alpha\"\nproof\n  fix X :: \"'a formula set\"\n  show \"\\<forall> alpha :: 'a formula. X \\<turnstile> alpha \\<longleftrightarrow> X \\<Turnstile> alpha\" proof\n    fix alpha :: \"'a formula\"\n    show \" X \\<turnstile> alpha \\<longleftrightarrow> X \\<Turnstile> alpha\" proof\n      assume H1: \"X \\<turnstile> alpha\"\n      from this ImplGen_correct show \"X \\<Turnstile> alpha\" by(auto)\n    next\n      assume H2: \"X \\<Turnstile> alpha\"\n      show \"X \\<turnstile> alpha\" proof(rule ccontr)\n        assume H3: \"\\<not> X \\<turnstile> alpha\"\n        from this Cplus_ImplSem_prop have \"cons_FS ( X \\<union> {Neg alpha})\" by(auto)\n        from this lindenbaum[of \"X \\<union> {Neg alpha}\"] have \"\\<exists>X'.  (X \\<union> {Neg alpha}) \\<subseteq> X' \\<and> max_cons_FS X'\" by(auto)\n        then obtain Y where H'prop: \"(X \\<union> {Neg alpha}) \\<subseteq> Y \\<and> max_cons_FS Y\" by(auto)\n        from H'prop max_cons_fullfillable have \"\\<exists> w. fulfillsS w Y\" by(auto)\n        from H'prop this have \"\\<exists> w. fulfillsS w (X \\<union> {Neg alpha})\" by(blast)\n        then obtain w where wprop: \"fulfillsS w (X \\<union> {Neg alpha})\" by(auto)\n        from this H2 ImplSem_def have CON1: \"fulfills w alpha\" by(auto)\n        from wprop have \"fulfills w (Neg alpha)\" by(auto)\n        hence CON2: \"\\<not> fulfills w alpha\" by(auto)\n        from CON1 CON2 show \"False\" by(auto)\n      qed\n    qed\n  qed\nqed\n\ninductive ImplHil :: \"'a formula set \\<Rightarrow> 'a formula \\<Rightarrow> bool\" (infix \"|~\" 56) where\nAR: \"(alpha :: 'a formula) \\<in> (X:: 'a formula set) \\<Longrightarrow> ImplHil X alpha\" |\nMP: \"\\<lbrakk> ImplHil (X::'a formula set) alpha; ImplHil X (alpha Impl beta) \\<rbrakk> \\<Longrightarrow> ImplHil X beta\" |\nL1: \" ImplHil (X :: 'a formula set) ( ((alpha :: 'a formula) Impl beta Impl gamma) Impl (alpha Impl beta) Impl (alpha Impl gamma) )\" |\nL2: \" ImplHil (X :: 'a formula set) ( (alpha :: 'a formula) Impl beta Impl (alpha And beta))\" |\nL3a: \" ImplHil (X :: 'a formula set) ( ( (alpha :: 'a formula) And beta) Impl alpha )\" |\nL3b: \" ImplHil (X :: 'a formula set) ( ( (alpha :: 'a formula) And beta) Impl beta )\" |\nL4: \" ImplHil (X :: 'a formula set) ( ( (alpha :: 'a formula) Impl Neg beta) Impl (beta Impl Neg alpha) )\"\n\nlemma ImplHil_example1: \"{(alpha :: 'a formula), beta} |~ (alpha And beta)\"\nproof -\n  from ImplHil.AR have 1: \"{alpha, beta} |~ alpha\" by (blast)\n  from ImplHil.AR have 2: \"{alpha, beta} |~ beta\" by (blast)\n  from ImplHil.L2 have 3: \"{alpha, beta} |~ (alpha Impl beta Impl (alpha And beta) )\" by(blast)\n  from 1 3 ImplHil.MP have 4: \"{alpha, beta} |~ (beta Impl (alpha And beta))\" by(blast)\n  from 4 2 ImplHil.MP show 5: \"{alpha, beta} |~ (alpha And beta)\" by(blast)\nqed\n\nlemma ImplHil_correct: \" X |~ alpha \\<longrightarrow> X \\<Turnstile> alpha\"\nproof\n  fix alpha\n  show \"X |~ alpha \\<Longrightarrow> X \\<Turnstile> alpha\" proof(induction alpha rule: ImplHil.induct)\n    case (AR alpha X)\n    then show ?case  by(simp add: ImplSem_def)\nnext\n  case (MP X alpha beta)\n  then show ?case by (simp add: ImplSem_def)\nnext\n  case (L1 X alpha beta gamma)\n  then show ?case by (simp add: ImplSem_def)\nnext\n  case (L2 X alpha beta)\n  then show ?case by (simp add: ImplSem_def)\nnext\n  case (L3a X alpha beta)\n  then show ?case by (simp add: ImplSem_def)\nnext\n  case (L3b X alpha beta)\n  then show ?case by (simp add: ImplSem_def)\nnext\n  case (L4 X alpha beta)\n  then show ?case by (simp add: ImplSem_def)\nqed\nqed\n\nlemma ImplHil_monot_prop: \" X |~ alpha \\<Longrightarrow> X \\<subseteq> X' \\<Longrightarrow> X' |~ alpha\"\nproof(induct rule: ImplHil.induct)\n    case (AR alpha X)\n    then show ?case using ImplHil.AR by(auto)\n  next\n    case (MP X alpha beta)\n    then show ?case using ImplHil.MP by(auto)\n  next\n    case (L1 X alpha beta gamma)\n    then show ?case by(simp add: ImplHil.L1)\n  next\n    case (L2 X alpha beta)\n    then show ?case by(simp add: ImplHil.L2)\n  next\n    case (L3a X alpha beta)\n    then show ?case by(simp add: ImplHil.L3a)\n  next\n    case (L3b X alpha beta)\n    then show ?case by(simp add: ImplHil.L3b)\n  next\n    case (L4 X alpha beta)\n    then show ?case by(simp add: ImplHil.L4)\nqed\n\nlemma ImplHil_propa: \"X |~ alpha Impl Neg beta \\<longrightarrow> X |~ beta Impl Neg alpha\"\nproof\n  assume H: \"X |~ alpha Impl Neg beta\"\n  from ImplHil.L4 have \"X |~ (alpha Impl Neg beta) Impl (beta Impl Neg alpha)\" by(auto)\n  from this H ImplHil.MP show \"X |~ beta Impl Neg alpha\" by(auto)\nqed\n\nlemma ImplHil_propb: \"{} |~ alpha Impl beta Impl alpha\"\nproof -\n  from ImplHil.L3b have \"{} |~ (beta And Neg alpha) Impl (Neg alpha)\" by(auto)\n  from this ImplHil_propa show \"{} |~ alpha Impl Neg(beta And Neg alpha)\" by(auto)\nqed\n\nlemma ImplHil_propc: \"{} |~ alpha Impl alpha\"\nproof -\n  from ImplHil.L1 have \"{} |~ (alpha Impl (alpha Impl alpha) Impl alpha) Impl (alpha Impl (alpha Impl alpha)) Impl (alpha Impl alpha)\" by(auto)\n  from this ImplHil.MP ImplHil_propb have \"{} |~ (alpha Impl (alpha Impl alpha)) Impl (alpha Impl alpha)\" by(blast)\n  from this ImplHil.MP ImplHil_propb show \"{} |~ alpha Impl alpha\" by(blast)\nqed\n\nlemma ImplHil_propd: \"{} |~ (alpha Impl (Neg (Neg alpha)) )\"\nproof -\n  from ImplHil_propc have \"{} |~ (Neg alpha) Impl (Neg alpha)\" by(auto)\n  from this ImplHil_propa show \"{} |~ alpha Impl (Neg (Neg alpha))\" by(auto)\nqed\n\nlemma ImplHil_prope: \"{} |~ beta Impl (Neg beta Impl alpha)\"\nproof -\n  from ImplHil.L3a have \"{} |~ ( (Neg beta) And (Neg alpha)) Impl Neg beta\" by(auto)\n  from this ImplHil_propa show \"{} |~ beta Impl Neg( (Neg beta) And (Neg alpha))\" by(auto)\nqed\n\nlemma ImplHil_deduction_theorem: \" X' |~ gamma \\<Longrightarrow> X' = X \\<union> {alpha} \\<Longrightarrow> X |~ alpha Impl gamma\"\nproof(induct rule: ImplHil.induct)\n  case (AR gamma X')\n  then have or_prop: \"gamma \\<in> X \\<or> gamma = alpha\" by(auto)\n  from this show ?case proof\n    assume \"gamma \\<in> X\"\n    from this ImplHil.AR have 1: \"X |~ gamma\" by(auto)\n    from ImplHil_propb ImplHil_monot_prop have \"X |~ gamma Impl alpha Impl gamma\" by(blast)\n    from this 1 ImplHil.MP show \"X |~ alpha Impl gamma\" by(auto)\n  next\n    assume \"gamma = alpha\"\n    from this ImplHil_propc ImplHil_monot_prop show \"X |~ alpha Impl gamma\" by(blast)\n  qed\nnext\n  case (MP X' beta gamma)\n  then have H:\"X |~ alpha Impl beta \\<and> X |~ alpha Impl beta Impl gamma\" by(auto)\n  from ImplHil.L1 have \"X |~ (alpha Impl beta Impl gamma) Impl (alpha Impl beta) Impl (alpha Impl gamma)\" by(auto)\n  from this H ImplHil.MP show ?case by(blast)\nnext\n  case (L1 X' beta gamma delta)\n  then show ?case using ImplHil.L1\n    by (metis ImplHil_monot_prop ImplHil_propb MP sup.orderI sup_bot.right_neutral)\nnext\n  case (L2 X' beta gamma)\n  then show ?case\n    by (metis ImplHil.L2 ImplHil_monot_prop ImplHil_propb MP sup.orderI sup_bot.right_neutral)\nnext\n  case (L3a X' beta gamma)\n  then show ?case\n    by (metis ImplHil.L3a ImplHil_monot_prop ImplHil_propb MP sup.orderI sup_bot.right_neutral)\nnext\n  case (L3b X' beta gamma)\n  then show ?case \n    by (metis ImplHil.L3b ImplHil_monot_prop ImplHil_propb MP sup.orderI sup_bot.right_neutral)\nnext\n  case (L4 X' beta gamma)\n  then show ?case\n    by (metis ImplHil.L4 ImplHil_monot_prop ImplHil_propb MP sup.orderI sup_bot.right_neutral)\nqed\n\nlemma ImplHil_negneg_elim: \" {} |~ (Neg (Neg alpha )) Impl alpha\"\nproof -\n  from ImplHil.L3a ImplHil.AR ImplHil.MP have I1: \"{ (Neg (Neg alpha)) And Neg alpha } |~ Neg (Neg alpha)\" by(blast)\n  from ImplHil.L3b ImplHil.AR ImplHil.MP have I2: \"{ (Neg (Neg alpha)) And Neg alpha } |~ Neg alpha\" by(blast)\n  from I1 I2 ImplHil.MP ImplHil_prope[of \"Neg alpha\" \"Neg (alpha Impl alpha)\"]\n   ImplHil_monot_prop[of \"{}\" \"Neg alpha Impl Neg (Neg alpha) Impl Neg (alpha Impl alpha) \" \"{Neg (Neg alpha) And Neg alpha}\"]\n  have 3: \"{ (Neg (Neg alpha)) And Neg alpha } |~ Neg (alpha Impl alpha)\" by(blast)\n  from this ImplHil_deduction_theorem have \" {} |~ ((Neg (Neg alpha)) And Neg alpha) Impl Neg( alpha Impl alpha)\" by(auto)\n  from this ImplHil_propa have \" {} |~ (alpha Impl alpha) Impl Neg(((Neg (Neg alpha)) And Neg alpha))\" by(auto)\n  from this ImplHil_propc ImplHil.MP show \"{} |~ Neg(((Neg (Neg alpha)) And Neg alpha))\" by(auto)\nqed\n\nlemma ImplHil_fulfills_ImplGenNEG1: \" X |~ alpha \\<Longrightarrow> X |~ (Neg alpha) \\<Longrightarrow> X |~ beta\"\nproof -\n  assume H1: \"X |~ alpha\"\n  assume H2: \"X |~ Neg alpha\"\n  from ImplHil_prope ImplHil_monot_prop have \"X |~ alpha Impl Neg alpha Impl beta\" by(blast)\n  from this H1 H2 ImplHil.MP show \"X |~ beta\" by(blast)\nqed\n\nlemma ImplHil_fulfills_ImplGenNEG2:\n\"\\<lbrakk> X \\<union> {beta} |~ alpha; X \\<union> {Neg beta} |~ alpha \\<rbrakk> \\<Longrightarrow> X |~ alpha\"\nproof -\n  fix alpha beta\n  assume H1: \"X \\<union> {beta} |~ alpha\"\n  assume H2: \"X \\<union> {Neg beta} |~ alpha\"\n  from ImplHil_propd have T:\"{} |~ alpha Impl Neg (Neg alpha)\" by(auto)\n  from this ImplHil_monot_prop have \"X \\<union> {beta} |~ alpha Impl Neg (Neg alpha)\" by(auto)\n  from this H1 ImplHil.MP have \"X \\<union> {beta} |~ Neg (Neg alpha)\" by(auto)\n  from this ImplHil_deduction_theorem have \"X |~ beta Impl Neg (Neg alpha)\" by(auto)\n  from this ImplHil_propa have 1: \"X |~ Neg alpha Impl Neg beta\" by(auto)\n  from ImplHil.AR ImplHil_monot_prop have 2: \"X \\<union> {Neg alpha} |~ Neg alpha\" by(blast)\n  from this 1 ImplHil.MP ImplHil_monot_prop have 3: \"X \\<union> {Neg alpha} |~ Neg beta \" by(blast)\n  from T ImplHil_monot_prop have \"X \\<union> {Neg beta} |~ alpha Impl Neg (Neg alpha)\" by(auto)\n  from this H2 ImplHil.MP have \"X \\<union> {Neg beta} |~ Neg (Neg alpha)\" by(auto)\n  from this ImplHil_deduction_theorem have \"X |~ (Neg beta) Impl Neg (Neg alpha)\" by(auto)\n  from this ImplHil_propa have \"X |~ Neg alpha Impl (Neg (Neg beta))\" by(auto)\n  from this 2 ImplHil.MP ImplHil_monot_prop have 4: \"X \\<union> {Neg alpha} |~ Neg (Neg beta) \" by(blast)\n  from 3 4 ImplHil_fulfills_ImplGenNEG1 have \"X \\<union> {Neg alpha} |~ Neg (alpha Impl alpha)\" by(auto)\n  from this ImplHil_deduction_theorem[of \"X \\<union> {Neg alpha}\" _ \"X\" \"Neg alpha\"] have \"X |~ (Neg alpha) Impl Neg(alpha Impl alpha)\" by(auto)\n  from this ImplHil_propa have \" X |~ (alpha Impl alpha) Impl (Neg (Neg alpha))\" by(auto)\n  from this ImplHil.MP ImplHil_propc ImplHil_monot_prop have 5: \"X |~ Neg (Neg alpha)\" by(blast)\n  from ImplHil_negneg_elim ImplHil_monot_prop have \"X |~ Neg (Neg alpha) Impl alpha\" by(auto)\n  from this 5 ImplHil.MP show \"X |~ alpha\" by(auto)\nqed\n\nlemma ImplGen_implies_ImpHil: \"X \\<turnstile> alpha \\<Longrightarrow> X |~ alpha\"\nproof(induct rule: ImplGen.induct)\ncase (AR alpha)\n  then show ?case using ImplHil.AR by(auto)\nnext\n  case (MR X X' alpha)\n  then show ?case using ImplHil_monot_prop by(auto)\nnext\n  case (ANDI X alpha beta)\n  then show ?case using ImplHil.L2 ImplHil.MP by(blast)\nnext\n  case (ANDl X alpha beta)\n  then show ?case using ImplHil.L3a ImplHil.MP by(blast)\nnext\n  case (ANDr X alpha beta)\n  then show ?case using ImplHil.L3b ImplHil.MP by(blast)\nnext\n  case (NEG1 X alpha beta)\n  then show ?case using ImplHil_fulfills_ImplGenNEG1 by(auto)\nnext\n  case (NEG2 X alpha beta)\n  then show ?case using ImplHil_fulfills_ImplGenNEG2 by(auto)\nqed\n\ntheorem ImplHil_complete: \"X |~ alpha \\<longleftrightarrow> X \\<Turnstile> alpha\"\nproof\n  assume H1: \"X |~ alpha\"\n  from this ImplHil_correct show \"X \\<Turnstile> alpha\" by(auto)\nnext\n  assume H2: \"X \\<Turnstile> alpha\"\n  from this have \"X \\<turnstile> alpha\" by (simp add: completeness_theorem)\n  from this show \"X |~ alpha\" by (simp add: ImplGen_implies_ImpHil)\nqed\n\nend", "meta": {"author": "fabianheimann", "repo": "rautenberg2isabelle", "sha": "e8a10a1d952bed1e7b3596afcad6b2fea50b4043", "save_path": "github-repos/isabelle/fabianheimann-rautenberg2isabelle", "path": "github-repos/isabelle/fabianheimann-rautenberg2isabelle/rautenberg2isabelle-e8a10a1d952bed1e7b3596afcad6b2fea50b4043/PropLogic.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898153067649, "lm_q2_score": 0.7981867777396212, "lm_q1q2_score": 0.7231490913446212}}
{"text": "section \"Base\"\n\ntheory Base\nimports PermutationLemmas\nbegin\n\nsubsection \"Integrate with Isabelle libraries?\"\n\n    \\<comment> \\<open>Misc\\<close>\n\n  \\<comment> \\<open>FIXME added by tjr, forms basis of a lot of proofs of existence of inf sets\\<close>\n  \\<comment> \\<open>something like this should be in FiniteSet, asserting nats are not finite\\<close>\nlemma natset_finite_max: assumes a: \"finite A\"\n  shows \"Suc (Max A) \\<notin> A\"\nproof (cases \"A = {}\")\n  case True\n  thus ?thesis by auto\nnext\n  case False\n  with a have \"Max A \\<in> A \\<and> (\\<forall>s \\<in> A. s \\<le> Max A)\" by simp\n  thus ?thesis by auto\nqed\n\n    \\<comment> \\<open>not used\\<close>\nlemma not_finite_univ: \"~ finite (UNIV::nat set)\"\n  apply rule\n  apply(drule_tac natset_finite_max)\n  by force\n\n  \\<comment> \\<open>FIXME should be in main lib\\<close>\nlemma LeastI_ex: \"(\\<exists> x. P (x::'a::wellorder)) \\<Longrightarrow> P (LEAST x. P x)\"\n  by(blast intro: LeastI)\n\n\nsubsection \"Summation\"\n\nprimrec summation :: \"(nat \\<Rightarrow> nat) \\<Rightarrow> nat \\<Rightarrow> nat\"\nwhere\n  \"summation f 0 = f 0\"\n| \"summation f (Suc n) = f (Suc n) + summation f n\"\n\n\nsubsection \"Termination Measure\"\n\nprimrec exp :: \"[nat,nat] \\<Rightarrow> nat\"\nwhere\n  \"exp x 0       = 1\"\n| \"exp x (Suc m) = x * exp x m\"\n\nprimrec sumList     :: \"nat list \\<Rightarrow> nat\"\nwhere\n  \"sumList []     = 0\"\n| \"sumList (x#xs) = x + sumList xs\"\n\n\nsubsection \"Functions\"\n\ndefinition\n  preImage :: \"('a \\<Rightarrow> 'b) \\<Rightarrow> 'b set \\<Rightarrow> 'a set\" where\n  \"preImage f A = { x . f x \\<in> A}\"\n\ndefinition\n  pre :: \"('a \\<Rightarrow> 'b) => 'b \\<Rightarrow> 'a set\" where\n  \"pre f a = { x . f x = a}\"\n\ndefinition\n  equalOn :: \"['a set,'a => 'b,'a => 'b] => bool\" where\n  \"equalOn A f g = (!x:A. f x = g x)\"    \n\nlemma preImage_insert: \"preImage f (insert a A) = pre f a Un preImage f A\"\n  by(auto simp add: preImage_def pre_def)\n\nlemma preImageI: \"f x : A ==> x : preImage f A\"\n  by(simp add: preImage_def)\n    \nlemma preImageE: \"x : preImage f A ==> f x : A\"\n  by(simp add: preImage_def)\n\nlemma equalOn_Un:  \"equalOn (A \\<union> B) f g = (equalOn A f g \\<and> equalOn B f g)\"\n  by(auto simp add: equalOn_def) \n\nlemma equalOnD: \"equalOn A f g \\<Longrightarrow> (\\<forall> x \\<in> A . f x = g x)\"\n  by(simp add: equalOn_def)\n\nlemma equalOnI:\"(\\<forall> x \\<in> A . f x = g x) \\<Longrightarrow> equalOn A f g\"\n  by(simp add: equalOn_def)\n\nlemma equalOn_UnD: \"equalOn (A Un B) f g ==> equalOn A f g & equalOn B f g\"\n  by(auto simp: equalOn_def)\n\n\n    \\<comment> \\<open>FIXME move following elsewhere?\\<close>\nlemma inj_inv_singleton[simp]: \"\\<lbrakk> inj f; f z = y \\<rbrakk> \\<Longrightarrow> {x. f x = y} = {z}\"\n  apply rule\n  apply(auto simp: inj_on_def) done\n\nlemma finite_pre[simp]: \"inj f \\<Longrightarrow> finite (pre f x)\"\n  apply(simp add: pre_def) \n  apply (cases \"\\<exists> y. f y = x\", auto) done\n\nlemma finite_preImage[simp]: \"\\<lbrakk> finite A; inj f \\<rbrakk> \\<Longrightarrow> finite (preImage f A)\"\n  apply(induct A rule: finite_induct) \n  apply(simp add: preImage_def)\n  apply(simp add: preImage_insert) done\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/Completeness/Base.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473680407889, "lm_q2_score": 0.8289388146603365, "lm_q1q2_score": 0.7231225932357959}}
{"text": "section {* polynomial functions: extremal behaviour and root counts *}\n\n(*  Author: John Harrison and Valentina Bruno\n    Ported from \"hol_light/Multivariate/complexes.ml\" by L C Paulson\n*)\n\ntheory PolyRoots\nimports Complex_Main\n\nbegin\n\nsubsection{*Geometric progressions*}\n\nlemma setsum_gp_basic:\n  fixes x :: \"'a::{comm_ring,monoid_mult}\"\n  shows \"(1 - x) * (\\<Sum>i\\<le>n. x^i) = 1 - x^Suc n\"\n  by (simp only: one_diff_power_eq [of \"Suc n\" x] lessThan_Suc_atMost)\n\nlemma setsum_gp0:\n fixes x :: \"'a::{comm_ring,division_ring_inverse_zero}\"\n shows   \"(\\<Sum>i\\<le>n. x^i) = (if x = 1 then of_nat(n + 1) else (1 - x^Suc n) / (1 - x))\"\nusing setsum_gp_basic[of x n]\napply (simp add: real_of_nat_def)\nby (metis eq_iff_diff_eq_0 mult.commute nonzero_eq_divide_eq)\n\nlemma setsum_power_shift:\n  fixes x :: \"'a::{comm_ring,monoid_mult}\"\n  assumes \"m \\<le> n\"\n  shows \"(\\<Sum>i=m..n. x^i) = x^m * (\\<Sum>i\\<le>n-m. x^i)\"\nproof -\n  have \"(\\<Sum>i=m..n. x^i) = x^m * (\\<Sum>i=m..n. x^(i-m))\"\n    by (simp add: setsum_right_distrib power_add [symmetric])\n  also have \"(\\<Sum>i=m..n. x^(i-m)) = (\\<Sum>i\\<le>n-m. x^i)\"\n    using `m \\<le> n` by (intro setsum.reindex_bij_witness[where j=\"\\<lambda>i. i - m\" and i=\"\\<lambda>i. i + m\"]) auto\n  finally show ?thesis .\nqed\n\nlemma setsum_gp_multiplied:\n  fixes x :: \"'a::{comm_ring,monoid_mult}\"\n  assumes \"m \\<le> n\"\n  shows \"(1 - x) * (\\<Sum>i=m..n. x^i) = x^m - x^Suc n\"\nproof -\n  have  \"(1 - x) * (\\<Sum>i=m..n. x^i) = x^m * (1 - x) * (\\<Sum>i\\<le>n-m. x^i)\"\n    by (metis mult.assoc mult.commute assms setsum_power_shift)\n  also have \"... =x^m * (1 - x^Suc(n-m))\"\n    by (metis mult.assoc setsum_gp_basic)\n  also have \"... = x^m - x^Suc n\"\n    using assms\n    by (simp add: algebra_simps) (metis le_add_diff_inverse power_add)\n  finally show ?thesis .\nqed\n\nlemma setsum_gp:\n  fixes x :: \"'a::{comm_ring,division_ring_inverse_zero}\"\n  shows   \"(\\<Sum>i=m..n. x^i) =\n               (if n < m then 0\n                else if x = 1 then of_nat((n + 1) - m)\n                else (x^m - x^Suc n) / (1 - x))\"\nusing setsum_gp_multiplied [of m n x] \napply (auto simp: real_of_nat_def)\nby (metis eq_iff_diff_eq_0 mult.commute nonzero_divide_eq_eq)\n\nlemma setsum_gp_offset:\n  fixes x :: \"'a::{comm_ring,division_ring_inverse_zero}\"\n  shows   \"(\\<Sum>i=m..m+n. x^i) =\n       (if x = 1 then of_nat n + 1 else x^m * (1 - x^Suc n) / (1 - x))\"\n  using setsum_gp [of x m \"m+n\"]\n  by (auto simp: power_add algebra_simps)\n\nsubsection{*Basics about polynomial functions: extremal behaviour and root counts.*}\n\nlemma sub_polyfun:\n  fixes x :: \"'a::{comm_ring,monoid_mult}\"\n  shows   \"(\\<Sum>i\\<le>n. a i * x^i) - (\\<Sum>i\\<le>n. a i * y^i) = \n           (x - y) * (\\<Sum>j<n. \\<Sum>k= Suc j..n. a k * y^(k - Suc j) * x^j)\"\nproof -\n  have \"(\\<Sum>i\\<le>n. a i * x^i) - (\\<Sum>i\\<le>n. a i * y^i) = \n        (\\<Sum>i\\<le>n. a i * (x^i - y^i))\"\n    by (simp add: algebra_simps setsum_subtractf [symmetric])\n  also have \"... = (\\<Sum>i\\<le>n. a i * (x - y) * (\\<Sum>j<i. y^(i - Suc j) * x^j))\"\n    by (simp add: power_diff_sumr2 ac_simps)\n  also have \"... = (x - y) * (\\<Sum>i\\<le>n. (\\<Sum>j<i. a i * y^(i - Suc j) * x^j))\"\n    by (simp add: setsum_right_distrib ac_simps)\n  also have \"... = (x - y) * (\\<Sum>j<n. (\\<Sum>i=Suc j..n. a i * y^(i - Suc j) * x^j))\"\n    by (simp add: nested_setsum_swap')\n  finally show ?thesis .\nqed\n\nlemma sub_polyfun_alt:\n  fixes x :: \"'a::{comm_ring,monoid_mult}\"\n  shows   \"(\\<Sum>i\\<le>n. a i * x^i) - (\\<Sum>i\\<le>n. a i * y^i) = \n           (x - y) * (\\<Sum>j<n. \\<Sum>k<n-j. a (j+k+1) * y^k * x^j)\"\nproof -\n  { fix j\n    have \"(\\<Sum>k = Suc j..n. a k * y^(k - Suc j) * x^j) =\n          (\\<Sum>k <n - j. a (Suc (j + k)) * y^k * x^j)\"\n      by (rule setsum.reindex_bij_witness[where i=\"\\<lambda>i. i + Suc j\" and j=\"\\<lambda>i. i - Suc j\"]) auto }\n  then show ?thesis\n    by (simp add: sub_polyfun)\nqed\n\nlemma polyfun_linear_factor:\n  fixes a :: \"'a::{comm_ring,monoid_mult}\"\n  shows  \"\\<exists>b. \\<forall>z. (\\<Sum>i\\<le>n. c i * z^i) = \n                  (z-a) * (\\<Sum>i<n. b i * z^i) + (\\<Sum>i\\<le>n. c i * a^i)\"\nproof -\n  { fix z\n    have \"(\\<Sum>i\\<le>n. c i * z^i) - (\\<Sum>i\\<le>n. c i * a^i) = \n          (z - a) * (\\<Sum>j<n. (\\<Sum>k = Suc j..n. c k * a^(k - Suc j)) * z^j)\"\n      by (simp add: sub_polyfun setsum_left_distrib)\n    then have \"(\\<Sum>i\\<le>n. c i * z^i) = \n          (z - a) * (\\<Sum>j<n. (\\<Sum>k = Suc j..n. c k * a^(k - Suc j)) * z^j)\n          + (\\<Sum>i\\<le>n. c i * a^i)\"\n      by (simp add: algebra_simps) }\n  then show ?thesis\n    by (intro exI allI) \nqed\n\nlemma polyfun_linear_factor_root:\n  fixes a :: \"'a::{comm_ring,monoid_mult}\"\n  assumes \"(\\<Sum>i\\<le>n. c i * a^i) = 0\"\n  shows  \"\\<exists>b. \\<forall>z. (\\<Sum>i\\<le>n. c i * z^i) = (z-a) * (\\<Sum>i<n. b i * z^i)\"\n  using polyfun_linear_factor [of c n a] assms\n  by simp\n\nlemma adhoc_norm_triangle: \"a + norm(y) \\<le> b ==> norm(x) \\<le> a ==> norm(x + y) \\<le> b\"\n  by (metis norm_triangle_mono order.trans order_refl)\n\nlemma polyfun_extremal_lemma:\n  fixes c :: \"nat \\<Rightarrow> 'a::real_normed_div_algebra\"\n  assumes \"e > 0\"\n    shows \"\\<exists>M. \\<forall>z. M \\<le> norm z \\<longrightarrow> norm(\\<Sum>i\\<le>n. c i * z^i) \\<le> e * norm(z) ^ Suc n\"\nproof (induction n)\n  case 0\n  show ?case \n    by (rule exI [where x=\"norm (c 0) / e\"]) (auto simp: mult.commute pos_divide_le_eq assms)\nnext\n  case (Suc n)\n  then obtain M where M: \"\\<forall>z. M \\<le> norm z \\<longrightarrow> norm (\\<Sum>i\\<le>n. c i * z^i) \\<le> e * norm z ^ Suc n\" ..\n  show ?case\n  proof (rule exI [where x=\"max 1 (max M ((e + norm(c(Suc n))) / e))\"], clarify)\n    fix z::'a\n    assume \"max 1 (max M ((e + norm (c (Suc n))) / e)) \\<le> norm z\"\n    then have norm1: \"0 < norm z\" \"M \\<le> norm z\" \"(e + norm (c (Suc n))) / e \\<le> norm z\"\n      by auto\n    then have norm2: \"(e + norm (c (Suc n))) \\<le> e * norm z\"  \"(norm z * norm z ^ n) > 0\"\n      apply (metis assms less_divide_eq mult.commute not_le) \n      using norm1 apply (metis mult_pos_pos zero_less_power)\n      done\n    have \"e * (norm z * norm z ^ n) + norm (c (Suc n) * (z * z ^ n)) =\n          (e + norm (c (Suc n))) * (norm z * norm z ^ n)\"\n      by (simp add: norm_mult norm_power algebra_simps)\n    also have \"... \\<le> (e * norm z) * (norm z * norm z ^ n)\"\n      using norm2 by (metis real_mult_le_cancel_iff1) \n    also have \"... = e * (norm z * (norm z * norm z ^ n))\"\n      by (simp add: algebra_simps)\n    finally have \"e * (norm z * norm z ^ n) + norm (c (Suc n) * (z * z ^ n))\n                  \\<le> e * (norm z * (norm z * norm z ^ n))\" .\n    then show \"norm (\\<Sum>i\\<le>Suc n. c i * z^i) \\<le> e * norm z ^ Suc (Suc n)\" using M norm1\n      by (drule_tac x=z in spec) (auto simp: intro!: adhoc_norm_triangle)\n    qed\nqed\n\nlemma norm_lemma_xy: \"\\<lbrakk>abs b + 1 \\<le> norm(y) - a; norm(x) \\<le> a\\<rbrakk> \\<Longrightarrow> b \\<le> norm(x + y)\"\n  by (metis abs_add_one_not_less_self add.commute diff_le_eq dual_order.trans le_less_linear \n         norm_diff_ineq)\n\nlemma polyfun_extremal:\n  fixes c :: \"nat \\<Rightarrow> 'a::real_normed_div_algebra\"\n  assumes \"\\<exists>k. k \\<noteq> 0 \\<and> k \\<le> n \\<and> c k \\<noteq> 0\"\n    shows \"eventually (\\<lambda>z. norm(\\<Sum>i\\<le>n. c i * z^i) \\<ge> B) at_infinity\"\nusing assms\nproof (induction n)\n  case 0 then show ?case\n    by simp\nnext\n  case (Suc n)\n  show ?case\n  proof (cases \"c (Suc n) = 0\")\n    case True\n    with Suc show ?thesis\n      by auto (metis diff_is_0_eq diffs0_imp_equal less_Suc_eq_le not_less_eq)\n  next\n    case False\n    with polyfun_extremal_lemma [of \"norm(c (Suc n)) / 2\" c n]\n    obtain M where M: \"\\<And>z. M \\<le> norm z \\<Longrightarrow> \n               norm (\\<Sum>i\\<le>n. c i * z^i) \\<le> norm (c (Suc n)) / 2 * norm z ^ Suc n\"\n      by auto\n    show ?thesis\n    unfolding eventually_at_infinity\n    proof (rule exI [where x=\"max M (max 1 ((abs B + 1) / (norm (c (Suc n)) / 2)))\"], clarsimp)\n      fix z::'a\n      assume les: \"M \\<le> norm z\"  \"1 \\<le> norm z\"  \"(\\<bar>B\\<bar> * 2 + 2) / norm (c (Suc n)) \\<le> norm z\"\n      then have \"\\<bar>B\\<bar> * 2 + 2 \\<le> norm z * norm (c (Suc n))\"\n        by (metis False pos_divide_le_eq zero_less_norm_iff)\n      then have \"\\<bar>B\\<bar> * 2 + 2 \\<le> norm z ^ (Suc n) * norm (c (Suc n))\" \n        by (metis `1 \\<le> norm z` order.trans mult_right_mono norm_ge_zero self_le_power zero_less_Suc)\n      then show \"B \\<le> norm ((\\<Sum>i\\<le>n. c i * z^i) + c (Suc n) * (z * z ^ n))\" using M les\n        apply auto\n        apply (rule norm_lemma_xy [where a = \"norm (c (Suc n)) * norm z ^ (Suc n) / 2\"])\n        apply (simp_all add: norm_mult norm_power)\n        done\n    qed\n  qed\nqed\n\nlemma polyfun_rootbound:\n fixes c :: \"nat \\<Rightarrow> 'a::{comm_ring,real_normed_div_algebra}\"\n assumes \"\\<exists>k. k \\<le> n \\<and> c k \\<noteq> 0\"\n   shows \"finite {z. (\\<Sum>i\\<le>n. c i * z^i) = 0} \\<and> card {z. (\\<Sum>i\\<le>n. c i * z^i) = 0} \\<le> n\"\nusing assms\nproof (induction n arbitrary: c)\n case (Suc n) show ?case\n proof (cases \"{z. (\\<Sum>i\\<le>Suc n. c i * z^i) = 0} = {}\")\n   case False\n   then obtain a where a: \"(\\<Sum>i\\<le>Suc n. c i * a^i) = 0\"\n     by auto\n   from polyfun_linear_factor_root [OF this]\n   obtain b where \"\\<And>z. (\\<Sum>i\\<le>Suc n. c i * z^i) = (z - a) * (\\<Sum>i< Suc n. b i * z^i)\"\n     by auto\n   then have b: \"\\<And>z. (\\<Sum>i\\<le>Suc n. c i * z^i) = (z - a) * (\\<Sum>i\\<le>n. b i * z^i)\"\n     by (metis lessThan_Suc_atMost)\n   then have ins_ab: \"{z. (\\<Sum>i\\<le>Suc n. c i * z^i) = 0} = insert a {z. (\\<Sum>i\\<le>n. b i * z^i) = 0}\"\n     by auto\n   have c0: \"c 0 = - (a * b 0)\" using  b [of 0]\n     by simp\n   then have extr_prem: \"~ (\\<exists>k\\<le>n. b k \\<noteq> 0) \\<Longrightarrow> \\<exists>k. k \\<noteq> 0 \\<and> k \\<le> Suc n \\<and> c k \\<noteq> 0\"\n     by (metis Suc.prems le0 minus_zero mult_zero_right)\n   have \"\\<exists>k\\<le>n. b k \\<noteq> 0\" \n     apply (rule ccontr)\n     using polyfun_extremal [OF extr_prem, of 1]\n     apply (auto simp: eventually_at_infinity b simp del: setsum_atMost_Suc)\n     apply (drule_tac x=\"of_real ba\" in spec, simp)\n     done\n   then show ?thesis using Suc.IH [of b] ins_ab\n     by (auto simp: card_insert_if)\n   qed simp\nqed simp\n\ncorollary\n  fixes c :: \"nat \\<Rightarrow> 'a::{comm_ring,real_normed_div_algebra}\"\n  assumes \"\\<exists>k. k \\<le> n \\<and> c k \\<noteq> 0\"\n    shows polyfun_rootbound_finite: \"finite {z. (\\<Sum>i\\<le>n. c i * z^i) = 0}\"\n      and polyfun_rootbound_card:   \"card {z. (\\<Sum>i\\<le>n. c i * z^i) = 0} \\<le> n\"\nusing polyfun_rootbound [OF assms] by auto\n\nlemma polyfun_finite_roots:\n  fixes c :: \"nat \\<Rightarrow> 'a::{comm_ring,real_normed_div_algebra}\"\n    shows  \"finite {z. (\\<Sum>i\\<le>n. c i * z^i) = 0} \\<longleftrightarrow> (\\<exists>k. k \\<le> n \\<and> c k \\<noteq> 0)\"\nproof (cases \" \\<exists>k\\<le>n. c k \\<noteq> 0\")\n  case True then show ?thesis \n    by (blast intro: polyfun_rootbound_finite)\nnext\n  case False then show ?thesis \n    by (auto simp: infinite_UNIV_char_0)\nqed\n\nlemma polyfun_eq_0:\n  fixes c :: \"nat \\<Rightarrow> 'a::{comm_ring,real_normed_div_algebra}\"\n    shows  \"(\\<forall>z. (\\<Sum>i\\<le>n. c i * z^i) = 0) \\<longleftrightarrow> (\\<forall>k. k \\<le> n \\<longrightarrow> c k = 0)\"\nproof (cases \"(\\<forall>z. (\\<Sum>i\\<le>n. c i * z^i) = 0)\")\n  case True\n  then have \"~ finite {z. (\\<Sum>i\\<le>n. c i * z^i) = 0}\"\n    by (simp add: infinite_UNIV_char_0)\n  with True show ?thesis\n    by (metis (poly_guards_query) polyfun_rootbound_finite)\nnext\n  case False\n  then show ?thesis\n    by auto\nqed\n\nlemma polyfun_eq_const:\n  fixes c :: \"nat \\<Rightarrow> 'a::{comm_ring,real_normed_div_algebra}\"\n    shows  \"(\\<forall>z. (\\<Sum>i\\<le>n. c i * z^i) = k) \\<longleftrightarrow> c 0 = k \\<and> (\\<forall>k. k \\<noteq> 0 \\<and> k \\<le> n \\<longrightarrow> c k = 0)\"\nproof -\n  {fix z\n    have \"(\\<Sum>i\\<le>n. c i * z^i) = (\\<Sum>i\\<le>n. (if i = 0 then c 0 - k else c i) * z^i) + k\"\n      by (induct n) auto\n  } then\n  have \"(\\<forall>z. (\\<Sum>i\\<le>n. c i * z^i) = k) \\<longleftrightarrow> (\\<forall>z. (\\<Sum>i\\<le>n. (if i = 0 then c 0 - k else c i) * z^i) = 0)\"\n    by auto\n  also have \"... \\<longleftrightarrow>  c 0 = k \\<and> (\\<forall>k. k \\<noteq> 0 \\<and> k \\<le> n \\<longrightarrow> c k = 0)\"\n    by (auto simp: polyfun_eq_0)\n  finally show ?thesis .\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/Multivariate_Analysis/PolyRoots.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473680407889, "lm_q2_score": 0.8289388083214156, "lm_q1q2_score": 0.723122587706055}}
{"text": "\ntheory Trees2_1\nimports Main\nbegin\n\ndatatype 'a tree = Leaf 'a | Node 'a \"'a tree\" \"'a tree\"\n\nvalue \"Leaf 1\"\nvalue \"Node 2 (Leaf 1) (Leaf 2)\"\n\nprimrec preOrder :: \"'a tree \\<Rightarrow> 'a list\"\nwhere\n  \"preOrder (Leaf a) = [a]\"\n| \"preOrder (Node a b c) = (a # preOrder b) @ preOrder c\"\n\nvalue \"preOrder (Leaf 1)\"\nvalue \"preOrder (Node 2 (Leaf 1) (Leaf 3))\"\n\nprimrec postOrder :: \"'a tree \\<Rightarrow> 'a list\"\nwhere\n  \"postOrder (Leaf a) = [a]\"\n| \"postOrder (Node a b c) = (postOrder b) @ (postOrder c) @ [a]\"\n\nvalue \"postOrder (Leaf 1)\"\nvalue \"postOrder (Node 2 (Leaf 1) (Leaf 3))\"\n\nprimrec inOrder :: \"'a tree \\<Rightarrow> 'a list\"\nwhere\n  \"inOrder (Leaf a) = [a]\"\n| \"inOrder (Node a b c) = (inOrder b) @ [a] @ (inOrder c)\"\n\nvalue \"inOrder (Leaf 1)\"\nvalue \"inOrder (Node 2 (Leaf 1) (Leaf 3))\"\n\nprimrec mirror :: \"'a tree \\<Rightarrow> 'a tree\"\nwhere\n  \"mirror (Leaf a) = (Leaf a)\"\n| \"mirror (Node a b c) = Node a (mirror c) (mirror b)\"\n\n\nvalue \"mirror (Leaf 1)\"\nvalue \"mirror (Node 2 (Leaf 1) (Leaf 3))\"\n\ntheorem \"preOrder (mirror t) = rev (postOrder t)\"\n  apply (induct t)\n  apply auto\ndone\n\ntheorem \"postOrder (mirror t) = rev (preOrder t)\"\n  apply (induct t)\n  apply auto\ndone\n\ntheorem \"inOrder (mirror t) = rev (inOrder t)\"\n  apply (induct t)\n  apply auto\ndone\n\nprimrec root :: \"'a tree \\<Rightarrow> 'a\"\nwhere\n  \"root (Leaf a) = a\"\n| \"root (Node a b c) = a\"\n\nvalue \"root (Leaf 1)\"\nvalue \"root (Node 2 (Leaf 1) (Leaf 3))\"\n\nprimrec leftmost :: \"'a tree \\<Rightarrow> 'a\"\nwhere\n  \"leftmost (Leaf a) = a\"\n| \"leftmost (Node a b c) = leftmost b\"\n\nvalue \"leftmost (Leaf 1)\"\nvalue \"leftmost (Node 2 (Leaf 1) (Leaf 3))\"\n\nprimrec rightmost :: \"'a tree \\<Rightarrow> 'a\"\nwhere\n  \"rightmost (Leaf a) = a\"\n| \"rightmost (Node a b c) = rightmost c\"\n\nvalue \"rightmost (Leaf 1)\"\nvalue \"rightmost (Node 2 (Leaf 1) (Leaf 3))\"\n\n\n\ntheorem \"last (inOrder t) = rightmost t\"\n  apply (induct t)\n  apply simp\n  (* inOrder t2 = [] \\<longrightarrow> a = rightmost t2\n        can be proven by showing inOrder t2 \\<noteq> [] *)\n  apply simp\ndone\n\ntheorem \"hd (inOrder xt) = leftmost xt\"\n  apply (induct xt)\n  apply simp\n  apply simp\ndone\n\ntheorem \"hd (preOrder xt) = last (postOrder xt)\"\n  apply (induct xt)\n  apply simp\n  apply simp\ndone\n\ntheorem \"hd (preOrder xt) = root xt\"\n  apply (induct xt)\n  apply simp\n  apply simp\ndone\n\ntheorem \"hd (inOrder xt) = root xt\"\n  quickcheck\noops\n\ntheorem \"last (postOrder xt) = root xt\"\n  apply (induct xt)\n  apply simp\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_1.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894632969136, "lm_q2_score": 0.8080672181749422, "lm_q1q2_score": 0.7230500324585865}}
{"text": "header {* Regular Expressions as Homogeneous Binary Relations *}\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 {* Soundness: *}\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/Regular-Sets/Relation_Interpretation.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894661025424, "lm_q2_score": 0.8080672112416736, "lm_q1q2_score": 0.7230500285219075}}
{"text": "theory sort_NMSortTDSorts\nimports Main\n        \"$HIPSTER_HOME/IsaHipster\"\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 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 length :: \"'t list => Nat\" where\n\"length (Nil2) = Z\"\n| \"length (Cons2 y xs) = S (length xs)\"\n\nfun half :: \"Nat => Nat\" where\n\"half (Z) = Z\"\n| \"half (S (Z)) = Z\"\n| \"half (S (S n)) = S (half n)\"\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\nfun nmsorttd :: \"int list => int list\" where\n\"nmsorttd (Nil2) = Nil2\"\n| \"nmsorttd (Cons2 y (Nil2)) = Cons2 y (Nil2)\"\n| \"nmsorttd (Cons2 y (Cons2 x2 x3)) =\n     lmerge\n       (nmsorttd\n          (take\n             (half (length (Cons2 y (Cons2 x2 x3)))) (Cons2 y (Cons2 x2 x3))))\n       (nmsorttd\n          (drop\n             (half (length (Cons2 y (Cons2 x2 x3)))) (Cons2 y (Cons2 x2 x3))))\"\n\nfun and2 :: \"bool => bool => bool\" where\n\"and2 True y = y\"\n| \"and2 False y = False\"\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     and2 (y <= y2) (ordered (Cons2 y2 xs))\"\n\n(*hipster take lmerge length half drop nmsorttd and2 ordered *)\n\ntheorem x0 :\n  \"!! (x :: int list) . ordered (nmsorttd 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/koen/sort_NMSortTDSorts.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9334308073258007, "lm_q2_score": 0.7745833841649232, "lm_q1q2_score": 0.7230199936222151}}
{"text": "(*\n    File:      Dirichlet_Misc.thy\n    Author:    Manuel Eberl, TU M\u00fcnchen\n*)\nsection \\<open>Miscellaneous auxiliary facts\\<close>\ntheory Dirichlet_Misc\n  imports \n    \"HOL-Number_Theory.Number_Theory\"\nbegin\n\nlemma\n  fixes a k :: nat\n  assumes \"a > 1\" \"k > 0\"\n  shows geometric_sum_nat_aux: \"(a - 1) * (\\<Sum>i<k. a ^ i) = a ^ k - 1\"\n    and geometric_sum_nat_dvd: \"a - 1 dvd a ^ k - 1\"\n    and geometric_sum_nat:     \"(\\<Sum>i<k. a ^ i) = (a ^ k - 1) div (a - 1)\"\nproof -\n  have \"(real a - 1) * (\\<Sum>i<k. real a ^ i) = real a ^ k - 1\"\n    using assms by (subst geometric_sum) auto\n  also have \"(real a - 1) * (\\<Sum>i<k. real a ^ i) = real ((a - 1) * (\\<Sum>i<k. a ^ i))\" \n    using assms by (simp add: of_nat_diff)\n  also have \"real a ^ k - 1 = real (a ^ k - 1)\" using assms by (subst of_nat_diff) auto\n  finally show *: \"(a - 1) * (\\<Sum>i<k. a ^ i) = a ^ k - 1\" by (subst (asm) of_nat_eq_iff)\n  show \"a - 1 dvd a ^ k - 1\" by (subst * [symmetric]) simp\n  from assms show \"(\\<Sum>i<k. a ^ i) = (a ^ k - 1) div (a - 1)\" \n    by (subst * [symmetric]) simp\nqed\n\nlemma dvd_div_gt0: \"d dvd n \\<Longrightarrow> n > 0 \\<Longrightarrow> n div d > (0::nat)\"\n  by auto\n\nlemma Set_filter_insert: \n  \"Set.filter P (insert x A) = (if P x then insert x (Set.filter P A) else Set.filter P A)\"\n  by auto\n    \nlemma Set_filter_union: \"Set.filter P (A \\<union> B) = Set.filter P A \\<union> Set.filter P B\"\n  by auto\n\nlemma Set_filter_empty [simp]: \"Set.filter P {} = {}\"\n  by auto\n    \nlemma Set_filter_image: \"Set.filter P (f ` A) = f ` Set.filter (P \\<circ> f) A\"\n  by auto\n\nlemma Set_filter_cong [cong]:\n    \"(\\<And>x. x \\<in> A \\<Longrightarrow> P x \\<longleftrightarrow> Q x) \\<Longrightarrow> A = B \\<Longrightarrow>  Set.filter P A = Set.filter Q B\"\n  by auto\n    \n\n\nlemma\n  assumes \"finite A\" \"A \\<noteq> {}\"\n  shows   card_even_subset_aux: \"card {B. B \\<subseteq> A \\<and> even (card B)} = 2 ^ (card A - 1)\"\n    and   card_odd_subset_aux:  \"card {B. B \\<subseteq> A \\<and> odd (card B)} = 2 ^ (card A - 1)\"\n    and   card_even_odd_subset: \"card {B. B \\<subseteq> A \\<and> even (card B)} = card {B. B \\<subseteq> A \\<and> odd (card B)}\"\nproof -\n  from assms have *: \"2 * card (Set.filter (even \\<circ> card) (Pow A)) = 2 ^ card A\"\n  proof (induction A rule: finite_ne_induct)\n    case (singleton x)\n    hence \"Pow {x} = {{}, {x}}\" by auto\n    thus ?case by (simp add: Set_filter_insert)\n  next\n    case (insert x A)\n    note fin = finite_subset[OF _ \\<open>finite A\\<close>]\n    have \"Pow (insert x A) = Pow A \\<union> insert x ` Pow A\" by (rule Pow_insert)\n    have \"Set.filter (even \\<circ> card) (Pow (insert x A)) = \n            Set.filter (even \\<circ> card) (Pow A) \\<union> \n            insert x ` Set.filter (even \\<circ> card \\<circ> insert x) (Pow A)\"\n      unfolding Pow_insert Set_filter_union Set_filter_image by blast\n    also have \"Set.filter (even \\<circ> card \\<circ> insert x) (Pow A) = Set.filter (odd \\<circ> card) (Pow A)\"\n      unfolding o_def\n      by (intro Set_filter_cong refl, subst card_insert_disjoint) \n         (insert insert.hyps, auto dest: finite_subset)\n    also have \"card (Set.filter (even \\<circ> card) (Pow A) \\<union> insert x ` \\<dots>) = \n                 card (Set.filter (even \\<circ> card) (Pow A)) + card (insert x ` \\<dots>)\"\n      (is \"card (?A \\<union> ?B) = _\")\n      by (intro card_Un_disjoint finite_filter finite_imageI) (auto simp:  insert.hyps)\n    also have \"card ?B = card (Set.filter (odd \\<circ> card) (Pow A))\"\n      using insert.hyps by (intro card_image inj_on_insert') auto\n    also have \"Set.filter (odd \\<circ> card) (Pow A) = Pow A - Set.filter (even \\<circ> card) (Pow A)\"\n      by auto\n    also have \"card \\<dots> = card (Pow A) - card (Set.filter (even \\<circ> card) (Pow A))\"\n      using insert.hyps by (subst card_Diff_subset) (auto simp: finite_filter)\n    also have \"card (Set.filter (even \\<circ> card) (Pow A)) + \\<dots> = card (Pow A)\"\n      by (intro add_diff_inverse_nat, subst not_less, rule card_mono) (insert insert.hyps, auto)  \n    also have \"2 * \\<dots> = 2 ^ card (insert x A)\"\n      using insert.hyps by (simp add: card_Pow)\n    finally show ?case .\n  qed\n  from * show A: \"card {B. B \\<subseteq> A \\<and> even (card B)} = 2 ^ (card A - 1)\"\n    by (cases \"card A\") (simp_all add: Set.filter_def)\n\n  have \"Set.filter (odd \\<circ> card) (Pow A) = Pow A - Set.filter (even \\<circ> card) (Pow A)\" by auto\n  also have \"2 * card \\<dots> = 2 * 2 ^ card A - 2 * card (Set.filter (even \\<circ> card) (Pow A))\"\n    using assms by (subst card_Diff_subset) (auto intro!: finite_filter simp: card_Pow)\n  also note *\n  also have \"2 * 2 ^ card A - 2 ^ card A = (2 ^ card A :: nat)\" by simp\n  finally show B: \"card {B. B \\<subseteq> A \\<and> odd (card B)} = 2 ^ (card A - 1)\"\n    by (cases \"card A\") (simp_all add: Set.filter_def)\n\n  from A and B show \"card {B. B \\<subseteq> A \\<and> even (card B)} = card {B. B \\<subseteq> A \\<and> odd (card B)}\" by simp\nqed\n  \nlemma bij_betw_prod_divisors_coprime:\n  assumes \"coprime a (b :: nat)\"\n  shows   \"bij_betw (\\<lambda>x. fst x * snd x) ({d. d dvd a} \\<times> {d. d dvd b}) {k. k dvd a * b}\"\n  unfolding bij_betw_def\nproof\n  from assms show \"inj_on (\\<lambda>x. fst x * snd x) ({d. d dvd a} \\<times> {d. d dvd b})\"\n    by (auto simp: inj_on_def coprime_crossproduct_nat coprime_divisors)\n  show \"(\\<lambda>x. fst x * snd x) ` ({d. d dvd a} \\<times> {d. d dvd b}) = {k. k dvd a * b}\"\n  proof safe\n    fix x assume \"x dvd a * b\"\n    then obtain b' c' where \"x = b' * c'\" \"b' dvd a\" \"c' dvd b\"\n      using division_decomp by blast\n    thus \"x \\<in> (\\<lambda>x. fst x * snd x) ` ({d. d dvd a} \\<times> {d. d dvd b})\" by force\n  qed (insert assms, auto intro: mult_dvd_mono)\nqed\n\nlemma bij_betw_prime_power_divisors:\n  assumes \"prime (p :: nat)\"\n  shows   \"bij_betw ((^) p) {..k} {d. d dvd p ^ k}\"\n  unfolding bij_betw_def\nproof \n  from assms have *: \"p > 1\" by (simp add: prime_gt_Suc_0_nat)\n  show \"inj_on ((^) p) {..k}\" using assms\n    by (auto simp: inj_on_def prime_gt_Suc_0_nat power_inject_exp[OF *])\n  show \"(^) p ` {..k} = {d. d dvd p ^ k}\"\n    using assms by (auto simp: le_imp_power_dvd divides_primepow_nat)\nqed\n\nlemma sum_divisors_coprime_mult:\n  assumes \"coprime a (b :: nat)\"\n  shows   \"(\\<Sum>d | d dvd a * b. f d) = (\\<Sum>r | r dvd a. \\<Sum>s | s dvd b. f (r * s))\"\nproof -\n  have \"(\\<Sum>r | r dvd a. \\<Sum>s | s dvd b. f (r * s)) =\n          (\\<Sum>z\\<in>{r. r dvd a} \\<times> {s. s dvd b}. f (fst z * snd z))\"\n    by (subst sum.cartesian_product) (simp add: case_prod_unfold)\n  also have \"\\<dots> = (\\<Sum>d | d dvd a * b. f d)\"\n    by (intro sum.reindex_bij_betw bij_betw_prod_divisors_coprime assms)\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/Dirichlet_Series/Dirichlet_Misc.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240930029118, "lm_q2_score": 0.8354835289107307, "lm_q1q2_score": 0.7228804785206591}}
{"text": "theory Chapter3\nimports Main\nbegin\n\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\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  \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 i) = N i\" |\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  by (induction a, auto split: aexp.split)\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 a1 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\nlemma \"aval (asimp a) s = aval a s\"\n  apply (induction a)\n    apply (auto simp: aval_plus)\n    done      \n      \n(* Exercise 3.1\n\nTo show that asimp_const really folds all subexpressions of the form Plus (N\ni) (N j), define a function optimal :: aexp \\<Rightarrow> bool that checks that its\nargument does not contain a subexpression of the form Plus (N i) (N j). Then\nprove optimal (asimp_const a)\n\n*)\n      \nfun optimal :: \"aexp \\<Rightarrow> bool\" where\n  \"optimal (Plus (N _) (N _)) = False\" |\n  \"optimal _ = True\"\n\nlemma \"optimal (asimp_const a)\"\n  by (induction a, auto split: aexp.split)\n\n(* Exercise 3.2 *)    \n    \nfun asimp_constant_total :: \"aexp \\<Rightarrow> int\" where\n      \"asimp_constant_total (N i) = i\" |\n      \"asimp_constant_total (V x) = 0 \"|\n      \"asimp_constant_total (Plus a1 a2) = asimp_constant_total a1 + asimp_constant_total a2\"\n\nfun asimp_remove_constants :: \"aexp \\<Rightarrow> aexp option\" where\n      \"asimp_remove_constants (N i) = None\" |\n      \"asimp_remove_constants (V x) = Some (V x)\" |\n      \"asimp_remove_constants (Plus a1 a2) =\n        (case (asimp_remove_constants a1, asimp_remove_constants a2) of\n          (Some a1P, Some a2P) \\<Rightarrow> Some (Plus a1P a2P) |\n          (None, Some a2P) \\<Rightarrow> Some a2P |\n          (Some a1P, None) \\<Rightarrow> Some a1P |\n          (None, None) \\<Rightarrow> None)\"\n\nfun full_asimp :: \"aexp \\<Rightarrow> aexp\" where\n      \"full_asimp a =\n         (case (asimp_constant_total a, asimp_remove_constants a) of\n            (i, None) \\<Rightarrow> N i |\n            (i, Some a) \\<Rightarrow> (if i = 0 then a else Plus a (N i)))\"\n\nlemma \"aval (full_asimp a) s = aval a s\"\n      apply (induction a)\n        apply (auto split:  aexp.splits option.splits if_splits)\n        done\n    \n(* Exercise 3.3 *)    \n\nfun subst :: \"vname \\<Rightarrow> aexp \\<Rightarrow> aexp \\<Rightarrow> aexp\" where\n  \"subst _ _ (N i) = N i\" |\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          \n(* Should evaluate to Plus (N 3) V ''y'' *)\nvalue  \"subst ''x'' (N 3) (Plus (V ''x'') (V ''y''))\"\n\nlemma aval_subst_eq: \"aval (subst x a e) s = aval e (s(x:= aval a s))\"  \n  by (induction e, auto)\n\nlemma aval_subst_ext: \"aval a1 s = aval a2 s \\<Longrightarrow> aval (subst x a1 e) s = aval (subst x a2 e) s\"\n  by (auto simp: aval_subst_eq)\n\n(* Exercise 3.4: see Exercise3p4.thy *)    \n    \n(* Execise 3.5 \n\nDefine a datatype aexp2 of extended arithmetic expressions that has, in\naddition to the constructors of aexp, a constructor for modelling a C-like\npost-increment operation x++, where x must be a variable. Define an evaluation\nfunction aval2 :: aexp2 \\<Rightarrow> state \\<Rightarrow> val \\<times> state that returns both the value of\nthe expression and the new state. The latter is required because post-\nincrement changes the state. \n\nExtend aexp2 and aval2 with a division operation.\nModel partiality of division by changing the return type of aval2 to (val \\<times>\nstate) option. In case of division by 0 let aval2 return None. Division on int\nis the infix div\n\n*)\n    \ndatatype aexp2 = N2 int | V2 vname | Plus2 aexp2 aexp2 | PostInc2 vname | Div2 aexp2 aexp2\n\n(* sseefried: It's not mentioned in the exercise but we have to choose an order in\n   which to evaluate sub expressions for Plus and Div. We choose left-to-right\n   So that, for instance in the expression Plus a1 a2, a1 is first evaluated and the\n   state that arises from that is passed in when evaluating a2\n *)\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 (Plus2 a1 a2) s = \n    (case aval2 a1 s of\n       None \\<Rightarrow> None |\n       Some (n1, s1) \\<Rightarrow> \n         (case aval2 a2 s1 of\n           None \\<Rightarrow> None |\n           Some (n2, s2) \\<Rightarrow> Some (n1 + n2, s2)\n         )\n    )\" |\n  \"aval2 (PostInc2 x) s = Some (s x, s (x:= s x + 1))\" |\n  \"aval2 (Div2 a1 a2) s = \n    (case aval2 a1 s of\n      None \\<Rightarrow> None |\n      Some (n1, s1) \\<Rightarrow> \n        (case aval2 a2 s1 of\n          None \\<Rightarrow> None |\n          Some (n2, s2) \\<Rightarrow> (if n2 = 0 then None else Some (n1 div n2, s2))\n        )\n    )\"\n\n(* Exercise 3.6 \nThe following type adds a LET construct to arithmetic ex- pressions:\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 e1 e2 is\nthe value of e2 in the state where x is bound to the value of e1 in the\noriginal state. Define a function lval :: lexp \\<Rightarrow> state \\<Rightarrow> int that evaluates\nlexp expressions. Remember s(x := i).\n\nDefine a conversion inline :: lexp \\<Rightarrow>\naexp. The expression LET x e1 e2 is inlined by substituting the converted form\nof e1 for x in the converted form of e2. See Exercise 3.3 for more on\nsubstitution. Prove that inline is correct w.r.t. evaluation.\n\n*)                       \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 rhs body) s = lval body (s (x := lval rhs s))\" \n \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 rhs body) = subst x (inline rhs) (inline body)\"\n\n\nvalue \"lval (LET ''x'' (Plusl (Nl 1) (Nl 2)) (Plusl (Vl ''x'') (Nl 3))) (\\<lambda>x.0)\"\nvalue \"inline (LET ''x'' (Plusl (Nl 1) (Nl 2)) (Plusl (Vl ''x'') (Nl 3)))\"\n\n    \n(* Wow, this one was hard. I needed to make sure that I was quantifying over an _arbitrary_\n   state.\n   \n   Without \"arbitrary: s\" I got the following goal:\n\n   \\<And>x rhs body. aval (inline rhs) s = lval rhs s \\<Longrightarrow> \n                 aval (inline body) s = lval body s \\<Longrightarrow> \n                 aval (inline body) (s(x := lval rhs s)) = lval body (s(x := lval rhs s))\n\n   With \"arbitrary: s\" the goal becomes:\n\n   \\<And>x rhs body s. (\\<And>s. aval (inline rhs) s = lval rhs s) \\<Longrightarrow> \n                   (\\<And>s. aval (inline body) s = lval body s) \\<Longrightarrow> \n                   aval (subst x (inline rhs) (inline body)) s = lval body (s(x := lval rhs s))\n\n  The term \"aval (subst x (inline rhs) (inline body)) s = lval body (s(x := lval rhs s))\" is\n  first simplified to:\n\n  aval (inline body) (s(x := aval (inline rhs) s)) = lval body (s(x := lval rhs s))\n\n  and then to:\n\n  aval (inline body) (s(x := lval rhs s)) = lval body (s(x := lval rhs s))\n  (by the first assumption above)\n\n  The universal quantification on \"s\" in the assumptions now helps us. The second assumption\n  is applied where the quantified \"s\" is replaced with \"s(x := lval rhs s)\" and hence we\n  can discharge this goal.\n  \n  The book is well written. This issue was already covered in p20-21.\n\n*)\n    \nlemma \"aval (inline l) s = lval l s\"\n  apply (induction l arbitrary: s rule: inline.induct)\n     apply (auto simp: aval_subst_eq)\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\n(* Exercise 3.7\n\nDefine functions Eq, Le :: aexp \\<Rightarrow> aexp \\<Rightarrow> bexp and \nprove bval(Eqa1 a2) s = (aval a1 s = aval a2 s) and\nbval (Le a1 a2) s = (aval a1 s \\<le> aval a2 s)\n\n*)  \n\n(* I've decided to make these constant-folding, but for this I will\n   require some helper theorems\n*)  \n\n\nlemma [simp]: \"bval (and b1 b2) s = bval (And b1 b2) s\" \n  by (induction b1 b2 rule: and.induct, auto)\n\nlemma [simp]: \"bval (less a1 a2) s = bval (Less a1 a2) s\"\n  by (induction a1 a2 rule: less.induct, auto)\n        \nfun Eq :: \"aexp \\<Rightarrow> aexp \\<Rightarrow> bexp\" where\n  \"Eq a1 a2 = and (not (less a1 a2)) (not (less a2 a1))\"\n    \nlemma \"bval (Eq a1 a2) s = (aval a1 s = aval a2 s)\"\n  by auto\n\nfun Le :: \"aexp \\<Rightarrow> aexp \\<Rightarrow> bexp\" where\n  \"Le a1 a2 = not (less a2 a1)\"\n \nlemma \"bval (Le a1 a2) s = (aval a1 s \\<le> aval a2 s)\"\n  by auto\n    \n(* Exercise 3.8\n\nConsider an alternative type of boolean expressions featuring a conditional:\ndatatype ifexp = Bc2 bool | If ifexp ifexp ifexp | Less2 aexp aexp\nFirst define an evaluation function ifval :: ifexp \\<Rightarrow> state \\<Rightarrow> bool analogously to bval. \nThen define two functions b2ifexp :: bexp \\<Rightarrow> ifexp and if2bexp :: ifexp \\<Rightarrow> bexp and \nprove their correctness, i.e., that they preserve the value of an expression.\n\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 b) s = b\" |\n  \"ifval (If cond thn els) s = (if (ifval cond s) then (ifval thn s) else (ifval els s))\" |\n  \"ifval (Less2 a1 a2) s = (aval a1 s < aval a2 s)\"\n\nfun or :: \"bexp \\<Rightarrow> bexp \\<Rightarrow> bexp\" where\n  \"or b1 b2 = Not (And (Not b1) (Not b2))\"  (* de Morgan's Law *)\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  \n\nfun if2bexp :: \"ifexp \\<Rightarrow> bexp\" where  \n  \"if2bexp (Bc2 b) = Bc b\" |\n  \"if2bexp (If cond thn els) = \n     or (And (if2bexp cond) (if2bexp thn)) (And (Not (if2bexp cond)) (if2bexp els))\" |\n  \"if2bexp (Less2 a1 a2) = Less a1 a2\"\n  \nvalue \"bval (if2bexp (If (Less2 (N 2) (N 2)) (Bc2 True) (Bc2 False))) (\\<lambda>x.0)\"  \n\nlemma \"ifval (b2ifexp b) s = bval b s\"\n  by (induction b arbitrary: s, auto)\n\nlemma \"bval (if2bexp b) s = ifval b s\"\n  by (induction b arbitrary: s, auto)\n\n(* Exercise 3.9\n\nDefine 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 b1 b2) s =(pbval b1 s \\<and> pbval b2 s)\"|\n  \"pbval (OR b1 b2)  s = (pbval b1 s \\<or> pbval b2 s)\"\n\nDefine a function is_nnf :: pbexp \\<Rightarrow> bool that checks whether a boolean expression is in \nNNF (negation normal form), i.e., if NOT is only applied directly to VARs. Also define a \nfunction nnf :: pbexp \\<Rightarrow> pbexp that converts a pbexp into NNF by pushing NOT inwards as much as \npossible. Prove that nnf preserves the value (pbval (nnf b) s = pbval b s) and returns \nan NNF (is_nnf (nnf b)).\n\nAn expression is in DNF (disjunctive normal form) if it is in NNF and if no \nOR occurs below an AND. Define a corresponding test is_dnf :: pbexp \\<Rightarrow> bool. An NNF can be\nconverted into a DNF in a bottom-up manner. The critical case is the conversion of AND b1 b2. \nHaving converted b1 and b2, apply distributivity of AND over OR. \n\nDefine a conversion function dnf_of_nnf :: pbexp \\<Rightarrow> pbexp from NNF to DNF. \n\nProve that your function preserves the value (pbval (dnf_of_nnf b) s = pbval b s) and \nconverts an NNF into a DNF (is_nnf b \\<Longrightarrow> is_dnf (dnf_of_nnf b))\n\n*)    \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 _) = True\" |\n  \"is_nnf (NOT (VAR _)) = 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  \nvalue \"is_nnf (NOT (AND (VAR ''x'') (VAR ''y'')))\"\nvalue \"is_nnf (AND (AND (NOT (VAR ''x'')) (VAR ''y'')) (OR (VAR ''z'') (NOT (VAR ''a'' ))))\"\n  \nfun nnf :: \"pbexp \\<Rightarrow> pbexp\" where  \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  \"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\nvalue \"nnf (NOT (OR (NOT (AND (VAR ''x'') (VAR ''y''))) (VAR ''z'')))\"\n  \nlemma \"is_nnf (nnf b)\"\n  by (induction b rule: nnf.induct, auto)\n\nlemma \"pbval (nnf b) s = pbval b s\"  \n  by (induction b rule: nnf.induct, auto)\n\n    \nfun is_dnf :: \"pbexp \\<Rightarrow> bool\"\nand no_ors :: \"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  \n  \"no_ors (VAR _)     = True\" |\n  \"no_ors (NOT b)     = no_ors b\" |\n  \"no_ors (AND b1 b2) = (no_ors b1 \\<and> no_ors b2)\" |\n  \"no_ors (OR _ _)    = False\" \n  \n\n(* left distribute AND A (OR B C)\" *)\nfun dist :: \"pbexp \\<Rightarrow> pbexp \\<Rightarrow> pbexp\" where\n  \"dist a (OR b c)        = OR (dist a b) (dist a c)\" |\n  \"dist (OR a b) c        = OR (dist a c) (dist b c)\" | \n  \"dist a b               = AND a b\"\n\n value \"dist (VAR ''a'') (OR (OR (VAR ''x'') (VAR ''y'')) (VAR ''z''))\"\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 (OR b1 b2)  = OR (dnf_of_nnf b1) (dnf_of_nnf b2)\" |\n  \"dnf_of_nnf (AND b1 b2) = dist (dnf_of_nnf b1) (dnf_of_nnf b2)\"\n\nvalue \"is_dnf (AND (AND (OR (VAR ''x'') (VAR ''y'')) (VAR ''z'')) (VAR ''a''))\"\nvalue \"dnf_of_nnf (nnf (NOT (OR (VAR ''x'') (AND (VAR ''y'') (VAR ''z'')))))\"\n\nvalue \"dnf_of_nnf (AND (OR (VAR ''x1'') (VAR ''y1'')) (OR (VAR ''x2'') (VAR ''y2'')))\"\n  \nvalue \"dnf_of_nnf (AND (AND (OR (VAR ''x1'') (VAR ''y1'')) (OR (VAR ''x2'') (VAR ''y2''))) (OR (VAR ''x3'') (VAR ''y3'')))\"\n\nvalue \"dnf_of_nnf (AND (OR (OR (VAR ''x'') (VAR ''y'')) (VAR ''z'')) (VAR ''a''))\"\n  \n(* The order of the equality matters! *)\nlemma dist_AND_eq: \"pbval (dist a b) s = pbval (AND a b) s\"\n  by (induction a b rule: dist.induct, auto)\n\nlemma  \"pbval (dnf_of_nnf b) s = pbval b s\"\n  by (induction b rule: dnf_of_nnf.induct, auto simp: dist_AND_eq)\n\n(* This is true because v must be a VAR *)\nlemma no_ors_in_NOT_if_nnf: \"is_nnf (NOT v) \\<Longrightarrow> no_ors v\"\n  by (induction v, auto)\n\nlemma dnf_dist: \"is_dnf a \\<Longrightarrow> is_dnf b \\<Longrightarrow> is_dnf (dist a b)\"\n  by (induction a b rule: dist.induct, auto simp: no_ors_in_NOT_if_nnf) \n    \nlemma \"is_nnf b \\<Longrightarrow> is_dnf (dnf_of_nnf b)\"\n  by  (induction b rule: dnf_of_nnf.induct, auto simp: dnf_dist)\n\n(* End of Exercise 3.9 *)\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/Chapter3.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835207180245, "lm_q2_score": 0.8652240808393984, "lm_q1q2_score": 0.7228804612697172}}
{"text": "theory Chapter17\nimports DeBruijnEnvironment\nbegin\n\ndatatype expr = \n  Var var\n| Lam expr\n| Appl expr expr\n\nprimrec insert :: \"var => expr => expr\"\nwhere \"insert n (Var v) = Var (incr n v)\"\n    | \"insert n (Lam e) = Lam (insert (next n) e)\"\n    | \"insert n (Appl e1 e2) = Appl (insert n e1) (insert n e2)\"\n\nprimrec subst :: \"expr => var => expr => expr\"\nwhere \"subst e' n (Var v) = (if v = n then e' else Var (subr n v))\"\n    | \"subst e' n (Lam e) = Lam (subst (insert first e') (next n) e)\"\n    | \"subst e' n (Appl e1 e2) = Appl (subst e' n e1) (subst e' n e2)\"\n\n\n\nlemma [simp]: \"subst e' n (insert n e) = e\"\nby (induction e arbitrary: e' n, simp_all)\n\nprimrec is_ok :: \"unit env => expr => bool\"\nwhere \"is_ok del (Var x) = (lookup del x = Some ())\"\n    | \"is_ok del (Lam e) = is_ok (extend del ()) e\"\n    | \"is_ok del (Appl e1 e2) = (is_ok del e1 & is_ok del e2)\"\n\nlemma [simp]: \"is_ok gam e ==> n in gam ==> is_ok (extend_at n gam ()) (insert n e)\"\nby (induction e arbitrary: n gam, fastforce+)\n\nlemma [simp]: \"is_ok (extend_at n gam ()) e ==> n in gam ==> is_ok gam e' ==> \n                  is_ok gam (subst e' n e)\"\nby (induction e arbitrary: n gam e', fastforce+)\n\nprimrec is_val :: \"expr => bool\"\nwhere \"is_val (Var v) = False\"\n    | \"is_val (Lam e) = True\"\n    | \"is_val (Appl e1 e2) = False\"\n\ninductive eval :: \"expr => expr => bool\"\nwhere eval_appl_1 [simp]: \"eval e1 e1' ==> eval (Appl e1 e2) (Appl e1' e2)\"\n    | eval_appl_2 [simp]: \"is_val e1 ==> eval e2 e2' ==> eval (Appl e1 e2) (Appl e1 e2')\"\n    | eval_appl_3 [simp]: \"is_val e2 ==> eval (Appl (Lam e1) e2) (subst e2 first e1)\"\n\ntheorem preservation: \"eval e e' ==> is_ok del e ==> is_ok del e'\"\nby (induction e e' rule: eval.induct, fastforce+)\n\ntheorem progress: \"is_ok del e ==> del = empty_env ==> is_val e | (EX e'. eval e e')\"\nproof (induction e)\ncase Var\n  thus ?case by simp\nnext case Lam\n  thus ?case by simp\nnext case Appl\n  thus ?case by (metis eval.intros expr.exhaust is_ok.simps(3) is_val.simps(1) is_val.simps(3))\nqed\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/Chapter17.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467738423873, "lm_q2_score": 0.8221891370573388, "lm_q1q2_score": 0.7228249273322157}}
{"text": "(*  Title:      CTT/Arith.thy\n    Author:     Lawrence C Paulson, Cambridge University Computer Laboratory\n    Copyright   1991  University of Cambridge\n*)\n\nsection \\<open>Elementary arithmetic\\<close>\n\ntheory Arith\n  imports Bool\nbegin\n\nsubsection \\<open>Arithmetic operators and their definitions\\<close>\n\ndefinition add :: \"[i,i]\\<Rightarrow>i\"   (infixr \"#+\" 65)\n  where \"a#+b \\<equiv> rec(a, b, \\<lambda>u v. succ(v))\"\n\ndefinition diff :: \"[i,i]\\<Rightarrow>i\"   (infixr \"-\" 65)\n  where \"a-b \\<equiv> rec(b, a, \\<lambda>u v. rec(v, 0, \\<lambda>x y. x))\"\n\ndefinition absdiff :: \"[i,i]\\<Rightarrow>i\"   (infixr \"|-|\" 65)\n  where \"a|-|b \\<equiv> (a-b) #+ (b-a)\"\n\ndefinition mult :: \"[i,i]\\<Rightarrow>i\"   (infixr \"#*\" 70)\n  where \"a#*b \\<equiv> rec(a, 0, \\<lambda>u v. b #+ v)\"\n\ndefinition mod :: \"[i,i]\\<Rightarrow>i\"   (infixr \"mod\" 70)\n  where \"a mod b \\<equiv> rec(a, 0, \\<lambda>u v. rec(succ(v) |-| b, 0, \\<lambda>x y. succ(v)))\"\n\ndefinition div :: \"[i,i]\\<Rightarrow>i\"   (infixr \"div\" 70)\n  where \"a div b \\<equiv> rec(a, 0, \\<lambda>u v. rec(succ(u) mod b, succ(v), \\<lambda>x y. v))\"\n\nlemmas arith_defs = add_def diff_def absdiff_def mult_def mod_def div_def\n\n\nsubsection \\<open>Proofs about elementary arithmetic: addition, multiplication, etc.\\<close>\n\nsubsubsection \\<open>Addition\\<close>\n\ntext \\<open>Typing of \\<open>add\\<close>: short and long versions.\\<close>\n\nlemma add_typing: \"\\<lbrakk>a:N; b:N\\<rbrakk> \\<Longrightarrow> a #+ b : N\"\n  unfolding arith_defs by typechk\n\nlemma add_typingL: \"\\<lbrakk>a = c:N; b = d:N\\<rbrakk> \\<Longrightarrow> a #+ b = c #+ d : N\"\n  unfolding arith_defs by equal\n\n\ntext \\<open>Computation for \\<open>add\\<close>: 0 and successor cases.\\<close>\n\nlemma addC0: \"b:N \\<Longrightarrow> 0 #+ b = b : N\"\n  unfolding arith_defs by rew\n\nlemma addC_succ: \"\\<lbrakk>a:N; b:N\\<rbrakk> \\<Longrightarrow> succ(a) #+ b = succ(a #+ b) : N\"\n  unfolding arith_defs by rew\n\n\nsubsubsection \\<open>Multiplication\\<close>\n\ntext \\<open>Typing of \\<open>mult\\<close>: short and long versions.\\<close>\n\nlemma mult_typing: \"\\<lbrakk>a:N; b:N\\<rbrakk> \\<Longrightarrow> a #* b : N\"\n  unfolding arith_defs by (typechk add_typing)\n\nlemma mult_typingL: \"\\<lbrakk>a = c:N; b = d:N\\<rbrakk> \\<Longrightarrow> a #* b = c #* d : N\"\n  unfolding arith_defs by (equal add_typingL)\n\n\ntext \\<open>Computation for \\<open>mult\\<close>: 0 and successor cases.\\<close>\n\nlemma multC0: \"b:N \\<Longrightarrow> 0 #* b = 0 : N\"\n  unfolding arith_defs by rew\n\nlemma multC_succ: \"\\<lbrakk>a:N; b:N\\<rbrakk> \\<Longrightarrow> succ(a) #* b = b #+ (a #* b) : N\"\n  unfolding arith_defs by rew\n\n\nsubsubsection \\<open>Difference\\<close>\n\ntext \\<open>Typing of difference.\\<close>\n\nlemma diff_typing: \"\\<lbrakk>a:N; b:N\\<rbrakk> \\<Longrightarrow> a - b : N\"\n  unfolding arith_defs by typechk\n\nlemma diff_typingL: \"\\<lbrakk>a = c:N; b = d:N\\<rbrakk> \\<Longrightarrow> a - b = c - d : N\"\n  unfolding arith_defs by equal\n\n\ntext \\<open>Computation for difference: 0 and successor cases.\\<close>\n\nlemma diffC0: \"a:N \\<Longrightarrow> a - 0 = a : N\"\n  unfolding arith_defs by rew\n\ntext \\<open>Note: \\<open>rec(a, 0, \\<lambda>z w.z)\\<close> is \\<open>pred(a).\\<close>\\<close>\n\nlemma diff_0_eq_0: \"b:N \\<Longrightarrow> 0 - b = 0 : N\"\n  unfolding arith_defs\n  apply (NE b)\n    apply hyp_rew\n  done\n\ntext \\<open>\n  Essential to simplify FIRST!!  (Else we get a critical pair)\n  \\<open>succ(a) - succ(b)\\<close> rewrites to \\<open>pred(succ(a) - b)\\<close>.\n\\<close>\nlemma diff_succ_succ: \"\\<lbrakk>a:N; b:N\\<rbrakk> \\<Longrightarrow> succ(a) - succ(b) = a - b : N\"\n  unfolding arith_defs\n  apply hyp_rew\n  apply (NE b)\n    apply hyp_rew\n  done\n\n\nsubsection \\<open>Simplification\\<close>\n\nlemmas arith_typing_rls = add_typing mult_typing diff_typing\n  and arith_congr_rls = add_typingL mult_typingL diff_typingL\n\nlemmas congr_rls = arith_congr_rls intrL2_rls elimL_rls\n\nlemmas arithC_rls =\n  addC0 addC_succ\n  multC0 multC_succ\n  diffC0 diff_0_eq_0 diff_succ_succ\n\nML \\<open>\n  structure Arith_simp = TSimpFun(\n    val refl = @{thm refl_elem}\n    val sym = @{thm sym_elem}\n    val trans = @{thm trans_elem}\n    val refl_red = @{thm refl_red}\n    val trans_red = @{thm trans_red}\n    val red_if_equal = @{thm red_if_equal}\n    val default_rls = @{thms arithC_rls comp_rls}\n    val routine_tac = routine_tac @{thms arith_typing_rls routine_rls}\n  )\n\n  fun arith_rew_tac ctxt prems =\n    make_rew_tac ctxt (Arith_simp.norm_tac ctxt (@{thms congr_rls}, prems))\n\n  fun hyp_arith_rew_tac ctxt prems =\n    make_rew_tac ctxt\n      (Arith_simp.cond_norm_tac ctxt (prove_cond_tac ctxt, @{thms congr_rls}, prems))\n\\<close>\n\nmethod_setup arith_rew = \\<open>\n  Attrib.thms >> (fn ths => fn ctxt => SIMPLE_METHOD (arith_rew_tac ctxt ths))\n\\<close>\n\nmethod_setup hyp_arith_rew = \\<open>\n  Attrib.thms >> (fn ths => fn ctxt => SIMPLE_METHOD (hyp_arith_rew_tac ctxt ths))\n\\<close>\n\n\nsubsection \\<open>Addition\\<close>\n\ntext \\<open>Associative law for addition.\\<close>\n\n\ntext \\<open>Commutative law for addition.  Can be proved using three inductions.\n  Must simplify after first induction!  Orientation of rewrites is delicate.\\<close>\nlemma add_commute: \"\\<lbrakk>a:N; b:N\\<rbrakk> \\<Longrightarrow> a #+ b = b #+ a : N\"\n  apply (NE a)\n    apply hyp_arith_rew\n   apply (rule sym_elem)\n   prefer 2\n   apply (NE b)\n     prefer 4\n     apply (NE b)\n       apply hyp_arith_rew\n  done\n\n\nsubsection \\<open>Multiplication\\<close>\n\ntext \\<open>Right annihilation in product.\\<close>\nlemma mult_0_right: \"a:N \\<Longrightarrow> a #* 0 = 0 : N\"\n  apply (NE a)\n    apply hyp_arith_rew\n  done\n\ntext \\<open>Right successor law for multiplication.\\<close>\nlemma mult_succ_right: \"\\<lbrakk>a:N; b:N\\<rbrakk> \\<Longrightarrow> a #* succ(b) = a #+ (a #* b) : N\"\n  apply (NE a)\n    apply (hyp_arith_rew add_assoc [THEN sym_elem])\n  apply (assumption | rule add_commute mult_typingL add_typingL intrL_rls refl_elem)+\n  done\n\ntext \\<open>Commutative law for multiplication.\\<close>\nlemma mult_commute: \"\\<lbrakk>a:N; b:N\\<rbrakk> \\<Longrightarrow> a #* b = b #* a : N\"\n  apply (NE a)\n    apply (hyp_arith_rew mult_0_right mult_succ_right)\n  done\n\ntext \\<open>Addition distributes over multiplication.\\<close>\nlemma add_mult_distrib: \"\\<lbrakk>a:N; b:N; c:N\\<rbrakk> \\<Longrightarrow> (a #+ b) #* c = (a #* c) #+ (b #* c) : N\"\n  apply (NE a)\n    apply (hyp_arith_rew add_assoc [THEN sym_elem])\n  done\n\ntext \\<open>Associative law for multiplication.\\<close>\nlemma mult_assoc: \"\\<lbrakk>a:N; b:N; c:N\\<rbrakk> \\<Longrightarrow> (a #* b) #* c = a #* (b #* c) : N\"\n  apply (NE a)\n    apply (hyp_arith_rew add_mult_distrib)\n  done\n\n\nsubsection \\<open>Difference\\<close>\n\ntext \\<open>\n  Difference on natural numbers, without negative numbers\n  \\<^item> \\<open>a - b = 0\\<close>  iff  \\<open>a \\<le> b\\<close>\n  \\<^item> \\<open>a - b = succ(c)\\<close> iff \\<open>a > b\\<close>\n\\<close>\n\nlemma diff_self_eq_0: \"a:N \\<Longrightarrow> a - a = 0 : N\"\n  apply (NE a)\n    apply hyp_arith_rew\n  done\n\n\nlemma add_0_right: \"\\<lbrakk>c : N; 0 : N; c : N\\<rbrakk> \\<Longrightarrow> c #+ 0 = c : N\"\n  by (rule addC0 [THEN [3] add_commute [THEN trans_elem]])\n\ntext \\<open>\n  Addition is the inverse of subtraction: if \\<open>b \\<le> x\\<close> then \\<open>b #+ (x - b) = x\\<close>.\n  An example of induction over a quantified formula (a product).\n  Uses rewriting with a quantified, implicative inductive hypothesis.\n\\<close>\nschematic_goal add_diff_inverse_lemma:\n  \"b:N \\<Longrightarrow> ?a : \\<Prod>x:N. Eq(N, b-x, 0) \\<longrightarrow> Eq(N, b #+ (x-b), x)\"\n  apply (NE b)\n    \\<comment> \\<open>strip one \"universal quantifier\" but not the \"implication\"\\<close>\n    apply (rule_tac [3] intr_rls)\n    \\<comment> \\<open>case analysis on \\<open>x\\<close> in \\<open>succ(u) \\<le> x \\<longrightarrow> succ(u) #+ (x - succ(u)) = x\\<close>\\<close>\n     prefer 4\n     apply (NE x)\n       apply assumption\n    \\<comment> \\<open>Prepare for simplification of types -- the antecedent \\<open>succ(u) \\<le> x\\<close>\\<close>\n      apply (rule_tac [2] replace_type)\n       apply (rule_tac [1] replace_type)\n        apply arith_rew\n    \\<comment> \\<open>Solves first 0 goal, simplifies others.  Two sugbgoals remain.\n    Both follow by rewriting, (2) using quantified induction hyp.\\<close>\n   apply intr \\<comment> \\<open>strips remaining \\<open>\\<Prod>\\<close>s\\<close>\n    apply (hyp_arith_rew add_0_right)\n  apply assumption\n  done\n\ntext \\<open>\n  Version of above with premise \\<open>b - a = 0\\<close> i.e. \\<open>a \\<ge> b\\<close>.\n  Using @{thm ProdE} does not work -- for \\<open>?B(?a)\\<close> is ambiguous.\n  Instead, @{thm add_diff_inverse_lemma} states the desired induction scheme;\n  the use of \\<open>THEN\\<close> below instantiates Vars in @{thm ProdE} automatically.\n\\<close>\nlemma add_diff_inverse: \"\\<lbrakk>a:N; b:N; b - a = 0 : N\\<rbrakk> \\<Longrightarrow> b #+ (a-b) = a : N\"\n  apply (rule EqE)\n  apply (rule add_diff_inverse_lemma [THEN ProdE, THEN ProdE])\n    apply (assumption | rule EqI)+\n  done\n\n\nsubsection \\<open>Absolute difference\\<close>\n\ntext \\<open>Typing of absolute difference: short and long versions.\\<close>\n\nlemma absdiff_typing: \"\\<lbrakk>a:N; b:N\\<rbrakk> \\<Longrightarrow> a |-| b : N\"\n  unfolding arith_defs by typechk\n\nlemma absdiff_typingL: \"\\<lbrakk>a = c:N; b = d:N\\<rbrakk> \\<Longrightarrow> a |-| b = c |-| d : N\"\n  unfolding arith_defs by equal\n\nlemma absdiff_self_eq_0: \"a:N \\<Longrightarrow> a |-| a = 0 : N\"\n  unfolding absdiff_def by (arith_rew diff_self_eq_0)\n\nlemma absdiffC0: \"a:N \\<Longrightarrow> 0 |-| a = a : N\"\n  unfolding absdiff_def by hyp_arith_rew\n\nlemma absdiff_succ_succ: \"\\<lbrakk>a:N; b:N\\<rbrakk> \\<Longrightarrow> succ(a) |-| succ(b)  =  a |-| b : N\"\n  unfolding absdiff_def by hyp_arith_rew\n\ntext \\<open>Note how easy using commutative laws can be?  ...not always...\\<close>\nlemma absdiff_commute: \"\\<lbrakk>a:N; b:N\\<rbrakk> \\<Longrightarrow> a |-| b = b |-| a : N\"\n  unfolding absdiff_def\n  apply (rule add_commute)\n   apply (typechk diff_typing)\n  done\n\ntext \\<open>If \\<open>a + b = 0\\<close> then \\<open>a = 0\\<close>. Surprisingly tedious.\\<close>\nschematic_goal add_eq0_lemma: \"\\<lbrakk>a:N; b:N\\<rbrakk> \\<Longrightarrow> ?c : \\<Prod>u: Eq(N,a#+b,0) .  Eq(N,a,0)\"\n  apply (NE a)\n    apply (rule_tac [3] replace_type)\n     apply arith_rew\n  apply intr  \\<comment> \\<open>strips remaining \\<open>\\<Prod>\\<close>s\\<close>\n   apply (rule_tac [2] zero_ne_succ [THEN FE])\n     apply (erule_tac [3] EqE [THEN sym_elem])\n    apply (typechk add_typing)\n  done\n\ntext \\<open>\n  Version of above with the premise \\<open>a + b = 0\\<close>.\n  Again, resolution instantiates variables in @{thm ProdE}.\n\\<close>\nlemma add_eq0: \"\\<lbrakk>a:N; b:N; a #+ b = 0 : N\\<rbrakk> \\<Longrightarrow> a = 0 : N\"\n  apply (rule EqE)\n  apply (rule add_eq0_lemma [THEN ProdE])\n    apply (rule_tac [3] EqI)\n    apply typechk\n  done\n\ntext \\<open>Here is a lemma to infer \\<open>a - b = 0\\<close> and \\<open>b - a = 0\\<close> from \\<open>a |-| b = 0\\<close>, below.\\<close>\nschematic_goal absdiff_eq0_lem:\n  \"\\<lbrakk>a:N; b:N; a |-| b = 0 : N\\<rbrakk> \\<Longrightarrow> ?a : \\<Sum>v: Eq(N, a-b, 0) . Eq(N, b-a, 0)\"\n  apply (unfold absdiff_def)\n  apply intr\n   apply eqintr\n   apply (rule_tac [2] add_eq0)\n     apply (rule add_eq0)\n       apply (rule_tac [6] add_commute [THEN trans_elem])\n         apply (typechk diff_typing)\n  done\n\ntext \\<open>If \\<open>a |-| b = 0\\<close> then \\<open>a = b\\<close>\n  proof: \\<open>a - b = 0\\<close> and \\<open>b - a = 0\\<close>, so \\<open>b = a + (b - a) = a + 0 = a\\<close>.\n\\<close>\nlemma absdiff_eq0: \"\\<lbrakk>a |-| b = 0 : N; a:N; b:N\\<rbrakk> \\<Longrightarrow> a = b : N\"\n  apply (rule EqE)\n  apply (rule absdiff_eq0_lem [THEN SumE])\n     apply eqintr\n  apply (rule add_diff_inverse [THEN sym_elem, THEN trans_elem])\n     apply (erule_tac [3] EqE)\n    apply (hyp_arith_rew add_0_right)\n  done\n\n\nsubsection \\<open>Remainder and Quotient\\<close>\n\ntext \\<open>Typing of remainder: short and long versions.\\<close>\n\nlemma mod_typing: \"\\<lbrakk>a:N; b:N\\<rbrakk> \\<Longrightarrow> a mod b : N\"\n  unfolding mod_def by (typechk absdiff_typing)\n\nlemma mod_typingL: \"\\<lbrakk>a = c:N; b = d:N\\<rbrakk> \\<Longrightarrow> a mod b = c mod d : N\"\n  unfolding mod_def by (equal absdiff_typingL)\n\n\ntext \\<open>Computation for \\<open>mod\\<close>: 0 and successor cases.\\<close>\n\nlemma modC0: \"b:N \\<Longrightarrow> 0 mod b = 0 : N\"\n  unfolding mod_def by (rew absdiff_typing)\n\nlemma modC_succ: \"\\<lbrakk>a:N; b:N\\<rbrakk> \\<Longrightarrow>\n  succ(a) mod b = rec(succ(a mod b) |-| b, 0, \\<lambda>x y. succ(a mod b)) : N\"\n  unfolding mod_def by (rew absdiff_typing)\n\n\ntext \\<open>Typing of quotient: short and long versions.\\<close>\n\nlemma div_typing: \"\\<lbrakk>a:N; b:N\\<rbrakk> \\<Longrightarrow> a div b : N\"\n  unfolding div_def by (typechk absdiff_typing mod_typing)\n\nlemma div_typingL: \"\\<lbrakk>a = c:N; b = d:N\\<rbrakk> \\<Longrightarrow> a div b = c div d : N\"\n  unfolding div_def by (equal absdiff_typingL mod_typingL)\n\nlemmas div_typing_rls = mod_typing div_typing absdiff_typing\n\n\ntext \\<open>Computation for quotient: 0 and successor cases.\\<close>\n\nlemma divC0: \"b:N \\<Longrightarrow> 0 div b = 0 : N\"\n  unfolding div_def by (rew mod_typing absdiff_typing)\n\nlemma divC_succ: \"\\<lbrakk>a:N; b:N\\<rbrakk> \\<Longrightarrow>\n  succ(a) div b = rec(succ(a) mod b, succ(a div b), \\<lambda>x y. a div b) : N\"\n  unfolding div_def by (rew mod_typing)\n\n\ntext \\<open>Version of above with same condition as the \\<open>mod\\<close> one.\\<close>\nlemma divC_succ2: \"\\<lbrakk>a:N; b:N\\<rbrakk> \\<Longrightarrow>\n  succ(a) div b =rec(succ(a mod b) |-| b, succ(a div b), \\<lambda>x y. a div b) : N\"\n  apply (rule divC_succ [THEN trans_elem])\n    apply (rew div_typing_rls modC_succ)\n  apply (NE \"succ (a mod b) |-|b\")\n    apply (rew mod_typing div_typing absdiff_typing)\n  done\n\ntext \\<open>For case analysis on whether a number is 0 or a successor.\\<close>\nlemma iszero_decidable: \"a:N \\<Longrightarrow> rec(a, inl(eq), \\<lambda>ka kb. inr(<ka, eq>)) :\n  Eq(N,a,0) + (\\<Sum>x:N. Eq(N,a, succ(x)))\"\n  apply (NE a)\n    apply (rule_tac [3] PlusI_inr)\n     apply (rule_tac [2] PlusI_inl)\n      apply eqintr\n     apply equal\n  done\n\ntext \\<open>Main Result. Holds when \\<open>b\\<close> is 0 since \\<open>a mod 0 = a\\<close> and \\<open>a div 0 = 0\\<close>.\\<close>\nlemma mod_div_equality: \"\\<lbrakk>a:N; b:N\\<rbrakk> \\<Longrightarrow> a mod b #+ (a div b) #* b = a : N\"\n  apply (NE a)\n    apply (arith_rew div_typing_rls modC0 modC_succ divC0 divC_succ2)\n  apply (rule EqE)\n    \\<comment> \\<open>case analysis on \\<open>succ(u mod b) |-| b\\<close>\\<close>\n  apply (rule_tac a1 = \"succ (u mod b) |-| b\" in iszero_decidable [THEN PlusE])\n    apply (erule_tac [3] SumE)\n    apply (hyp_arith_rew div_typing_rls modC0 modC_succ divC0 divC_succ2)\n    \\<comment> \\<open>Replace one occurrence of \\<open>b\\<close> by \\<open>succ(u mod b)\\<close>. Clumsy!\\<close>\n  apply (rule add_typingL [THEN trans_elem])\n    apply (erule EqE [THEN absdiff_eq0, THEN sym_elem])\n     apply (rule_tac [3] refl_elem)\n     apply (hyp_arith_rew div_typing_rls)\n  done\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/CTT/Arith.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8791467675095292, "lm_q2_score": 0.8221891305219503, "lm_q1q2_score": 0.722824916379843}}
{"text": "\nsection \\<open>Kleene Algebra\\<close>\n\ntheory KA_iso\n  imports Main\n\nbegin\n\nnotation times (infixl \"\\<cdot>\" 70)\n\nsubsection \\<open>Semilattices\\<close>\n\nclass sup_semilattice = comm_monoid_add + ord +\n  assumes add_idem [simp]: \"x + x = x\"\n  and order_def: \"x \\<le> y \\<longleftrightarrow> x + y = y\"\n  and strict_order_def: \"x < y \\<longleftrightarrow> x \\<le> y \\<and> x \\<noteq> y\"\n\nbegin\n\nsubclass order \n  apply unfold_locales \n  unfolding order_def strict_order_def\n  using add_commute apply fastforce\n  apply simp\n  apply (metis add_assoc)\n  by (simp add: add_commute)\n\nlemma zero_least: \"0 \\<le> x\"\n  by (simp add: local.order_def)\n\nlemma add_isor: \"x \\<le> y \\<Longrightarrow> x + z \\<le> y + z\"\n  by (smt (z3) add_assoc add_commute local.add_idem local.order_def) \n\nlemma add_iso: \"x \\<le> y \\<Longrightarrow> x' \\<le> y' \\<Longrightarrow> x + x' \\<le> y + y'\"\n  by (metis add_commute add_isor local.dual_order.trans)\n\nlemma add_ubl: \"x \\<le> x + y\"\n  by (metis add_assoc local.add_idem local.order_def) \n\nlemma add_ubr: \"y \\<le> x + y\"\n  using add_commute add_ubl by fastforce\n\nlemma add_least: \"x \\<le> z \\<Longrightarrow> y \\<le> z \\<Longrightarrow> x + y \\<le> z\"\n  by (simp add: add_assoc local.order_def) \n\nlemma add_lub: \"(x + y \\<le> z) = (x \\<le> z \\<and> y \\<le> z)\"\n  using add_least add_ubl add_ubr dual_order.trans by blast\n\nend\n\nsubsection \\<open>Semirings and Dioids\\<close>\n\nclass semiring = comm_monoid_add + monoid_mult +\n  assumes distl: \"x \\<cdot> (y + z) = x \\<cdot> y + x \\<cdot> z\"\n  and distr: \"(x + y) \\<cdot> z = x \\<cdot> z + y \\<cdot> z\"\n  and annil [simp]: \"0 \\<cdot> x = 0\"\n  and annir [simp]: \"x \\<cdot> 0 = 0\"\n\nclass dioid = semiring + sup_semilattice\n\nbegin\n\nlemma mult_isol: \"x \\<le> y \\<Longrightarrow> z \\<cdot> x \\<le> z \\<cdot> y\"\n  by (metis local.distl local.order_def)\n\nlemma mult_isor: \"x \\<le> y \\<Longrightarrow> x \\<cdot> z \\<le> y \\<cdot> z\"\n  by (metis distr order_def)\n\nlemma mult_iso: \"x \\<le> y \\<Longrightarrow> x' \\<le> y' \\<Longrightarrow> x \\<cdot> x' \\<le> y \\<cdot> y'\"\n  using order_trans mult_isol mult_isor by blast\n\nlemma power_inductl: \"z + x \\<cdot> y \\<le> y \\<Longrightarrow> x ^ i \\<cdot> z \\<le> y\"\n  apply (induct i)\n  apply (simp add: local.add_lub)\n  by (smt (z3) local.add_lub local.dual_order.trans local.power.power_Suc mult_assoc mult_isol)\n\nlemma power_inductr: \"z + y \\<cdot> x \\<le> y \\<Longrightarrow> z \\<cdot> x ^ i \\<le> y\"\n  apply (induct i)\n  apply (simp add: local.add_lub)\n  by (smt (verit, ccfv_SIG) local.add_lub local.dual_order.trans local.power_Suc2 mult_assoc mult_isor)\n\nend\n\nsubsection \\<open>Kleene Algebras\\<close>\n\nclass kleene_algebra = dioid + \n  fixes star :: \"'a \\<Rightarrow> 'a\" (\"_\\<^sup>\\<star>\" [101] 100)\n  assumes star_unfoldl: \"1 + x \\<cdot> x\\<^sup>\\<star> \\<le> x\\<^sup>\\<star>\"  \n  and star_unfoldr: \"1 + x\\<^sup>\\<star> \\<cdot> x \\<le> x\\<^sup>\\<star>\"\n  and star_inductl: \"z + x \\<cdot> y \\<le> y \\<Longrightarrow> x\\<^sup>\\<star> \\<cdot> z \\<le> y\"\n  and star_inductr: \"z + y \\<cdot> x \\<le> y \\<Longrightarrow> z \\<cdot> x\\<^sup>\\<star> \\<le> y\"\n\nsubsection \\<open>Relational Model of Kleene algebra\\<close>\n\nnotation relcomp (infixl \";\" 70)\n\ninterpretation rel_d: dioid \"(\\<union>)\" \"{}\" Id \"(;)\" \"(\\<subseteq>)\" \"(\\<subset>)\"\n  by unfold_locales auto\n\nlemma power_is_relpow: \"rel_d.power R i = R ^^ i\"\n  by (induct i) (simp_all add: relpow_commute)\n\nlemma rel_star_def: \"R\\<^sup>* = (\\<Union>i. rel_d.power R i)\"\n  by (simp add: power_is_relpow rtrancl_is_UN_relpow)\n\nlemma rel_star_contl: \"R ; S\\<^sup>* = (\\<Union>i. R ; rel_d.power S i)\"\n  by (simp add: rel_star_def relcomp_UNION_distrib)\n\nlemma rel_star_contr: \"R\\<^sup>* ; S = (\\<Union>i. (rel_d.power R i) ; S)\"\n  by (simp add: rel_star_def relcomp_UNION_distrib2)\n\nlemma rel_star_unfoldl: \"Id \\<union> R ; R\\<^sup>* = R\\<^sup>*\"\n  by (metis r_comp_rtrancl_eq rtrancl_unfold)\n\nlemma rel_star_unfoldr: \"Id \\<union> R\\<^sup>* ; R = R\\<^sup>*\"\n  using rtrancl_unfold by blast\n\nlemma rel_star_inductl: \n  fixes R S T :: \"'a rel\"\n  assumes \"T \\<union> R ; S \\<subseteq> S\"\n  shows \"R\\<^sup>* ; T \\<subseteq> S\"\n  unfolding rel_star_def\n  by (metis UN_least assms rel_d.power_inductl relcomp_UNION_distrib2)\n\nlemma rel_star_inductr: \"(T::'a rel) \\<union> S ; R \\<subseteq> S \\<Longrightarrow> T ; R\\<^sup>* \\<subseteq> S\"\n  unfolding rel_star_def by (simp add: SUP_le_iff rel_d.power_inductr relcomp_UNION_distrib)\n\ninterpretation rel_ka: kleene_algebra \"(\\<union>)\" \"{}\" Id \"(;)\" \"(\\<subseteq>)\" \"(\\<subset>)\" rtrancl\n  by (unfold_locales, simp_all add: rel_star_unfoldl rel_star_unfoldr rel_star_inductl rel_star_inductr)\n\n\nsubsection \\<open>State Transformer Model of Kleene Algebra\\<close>\n\ntype_synonym 'a sta = \"'a \\<Rightarrow> 'a set\"\n\ndefinition eta :: \"'a sta\" (\"\\<eta>\") where\n  \"\\<eta> x = {x}\"\n\ndefinition nsta :: \"'a sta\" (\"\\<nu>\") where \n  \"\\<nu> x = {}\" \n\ndefinition kcomp :: \"'a sta \\<Rightarrow> 'a sta \\<Rightarrow> 'a sta\" (infixl \"\\<circ>\\<^sub>K\" 75) where\n  \"(f \\<circ>\\<^sub>K g) x = \\<Union>{g y |y. y \\<in> f x}\"\n\ndefinition kadd :: \"'a sta \\<Rightarrow> 'a sta \\<Rightarrow> 'a sta\" (infixl \"+\\<^sub>K\" 65) where\n  \"(f +\\<^sub>K g) x = f x \\<union> g x\" \n\ndefinition kleq :: \"'a sta \\<Rightarrow> 'a sta \\<Rightarrow> bool\" (infix \"\\<sqsubseteq>\" 50) where\n  \"f \\<sqsubseteq> g = (\\<forall>x. f x \\<subseteq> g x)\"\n\ndefinition kle :: \"'a sta \\<Rightarrow> 'a sta \\<Rightarrow> bool\" (infix \"\\<sqsubset>\" 50) where\n  \"f \\<sqsubset> g = (f \\<sqsubseteq> g \\<and> f \\<noteq> g)\"\n\nsubsection \\<open>Bijections between the relations and state transformers\\<close>\n\ndefinition r2s :: \"'a rel \\<Rightarrow> 'a sta\" (\"\\<S>\") where\n  \"\\<S> R = Image R \\<circ> \\<eta>\" \n\ndefinition s2r :: \"'a sta \\<Rightarrow> 'a rel\" (\"\\<R>\") where\n  \"\\<R> f = {(x,y). y \\<in> f x}\"\n\nlemma r2s2r_galois: \"(\\<R> f = R) = (\\<S> R = f)\"\n  by (force simp: s2r_def eta_def r2s_def)\n\nlemma r2s_bij: \"bij \\<S>\"\n  by (metis bij_def inj_def r2s2r_galois surj_def)\n\nlemma s2r_bij: \"bij \\<R>\"\n  by (metis bij_def inj_def r2s2r_galois surj_def)\n\nsubsection \\<open>Type definition and lifting for bijections\\<close>\n\nlemma type_definition_s2r_r2s: \"type_definition \\<R> \\<S> UNIV\"\n  unfolding type_definition_def by (meson iso_tuple_UNIV_I r2s2r_galois)\n\ndefinition \"rel_s2r R f = (R = \\<R> f)\"\n\nlemma bi_unique_rel_s2r [transfer_rule]: \"bi_unique rel_s2r\"\n  by (metis rel_s2r_def type_definition_s2r_r2s typedef_bi_unique)\n\nlemma bi_total_rel_s2r [transfer_rule]: \"bi_total rel_s2r\"\n  by (metis bi_total_def r2s2r_galois rel_s2r_def)\n\n\nsubsection \\<open>Transfer functions\\<close>\n\nlemma r2s_id: \"\\<R> \\<eta> = Id\"\n  unfolding s2r_def Id_def eta_def by force\n\nlemma Id_eta_transfer [transfer_rule]: \"rel_s2r Id \\<eta>\"\n  unfolding rel_s2r_def\n  by (simp add: r2s_id rel_s2r_def)\n\nlemma r2s_zero: \"\\<R> \\<nu> = {}\"\n  by (simp add: s2r_def nsta_def)\n\nlemma emp_nsta_transfer [transfer_rule]: \"rel_s2r {} \\<nu>\"\n  by (simp add: r2s_zero rel_s2r_def)\n\nlemma r2s_comp: \"\\<R> (f \\<circ>\\<^sub>K g) = \\<R> f ; \\<R> g\"\n  unfolding s2r_def kcomp_def by force\n\nlemma relcomp_kcomp_transfer [transfer_rule]: \"rel_fun rel_s2r (rel_fun rel_s2r rel_s2r) (;) (\\<circ>\\<^sub>K)\"\n  by (metis r2s_comp rel_funI rel_s2r_def)\n\nlemma s2r_add: \"\\<R> (f +\\<^sub>K g) = \\<R> f \\<union> \\<R> g\"\n  unfolding s2r_def kadd_def by force\n\nlemma un_kadd_transfer [transfer_rule]: \"rel_fun rel_s2r (rel_fun rel_s2r rel_s2r) (\\<union>) (+\\<^sub>K)\"\n  by (metis rel_funI rel_s2r_def s2r_add)\n\nlemma leq_kleq_transfer [transfer_rule]: \"rel_fun rel_s2r (rel_fun rel_s2r (=)) (\\<subseteq>) (\\<sqsubseteq>)\"\n  unfolding kleq_def s2r_def rel_s2r_def by force\n\nlemma le_kle_transfer [transfer_rule]: \"rel_fun rel_s2r (rel_fun rel_s2r (=)) (\\<subset>) (\\<sqsubset>)\"\n  unfolding kle_def kleq_def s2r_def rel_s2r_def by blast\n\ntext \\<open>State transformer model of Kleene algebra\\<close>\n\ninterpretation sta_monm: monoid_mult \"\\<eta>\" \"(\\<circ>\\<^sub>K)\"\n  by unfold_locales (transfer, force)+\n\ninterpretation sta_di: dioid \"(+\\<^sub>K)\" \"\\<nu>\" \"\\<eta>\" \"(\\<circ>\\<^sub>K)\" \"(\\<sqsubseteq>)\" \"(\\<sqsubset>)\"\n  by unfold_locales (transfer, force)+\n\nabbreviation \"kpow \\<equiv> sta_monm.power\"\n\ndefinition kstar :: \"'a sta \\<Rightarrow> 'a sta\" where\n  \"kstar f x = (\\<Union>i. kpow f i x)\"\n\nlemma r2s_pow: \"rel_d.power (\\<R> f) i = \\<R> (kpow f i)\"\n  by (induct i, simp_all add: r2s_id r2s_comp)\n\nlemma r2s_star: \"\\<R> (kstar f) = (\\<R> f)\\<^sup>*\"\nproof-\n  {fix x y\n    have \"(x,y) \\<in> \\<R> (kstar f) = (\\<exists>i. y \\<in> kpow f i x)\"\n      by (simp add: kstar_def s2r_def)\n    also have \"\\<dots> = ((x,y) \\<in> (\\<Union>i. \\<R> (kpow f i)))\"\n      unfolding s2r_def by simp\n    also have \"\\<dots> = ((x,y) \\<in> (\\<Union>i. rel_d.power (\\<R> f) i))\"\n      using r2s_pow by fastforce\n    finally have \"(x,y) \\<in> \\<R> (kstar f) = ((x,y) \\<in> (\\<R> f)\\<^sup>*)\"\n      using rel_star_def by blast}\n  thus ?thesis\n    by auto\nqed\n    \nlemma rtrancl_kstar_transfer [transfer_rule]: \"rel_fun rel_s2r rel_s2r rtrancl kstar\"\n  unfolding rel_fun_def rel_s2r_def\n  by (simp add: r2s_star) \n\ninterpretation sta_ka: kleene_algebra \"(+\\<^sub>K)\" \"\\<nu>\" \"\\<eta>\" \"(\\<circ>\\<^sub>K)\" \"(\\<sqsubseteq>)\" \"(\\<sqsubset>)\" kstar\n  by unfold_locales (transfer, auto simp: rel_star_inductl rel_star_inductr)+\n\nend\n\n\n\n\n\n", "meta": {"author": "BraeWebb", "repo": "stackoverflow", "sha": "a043b47f0f5ed97f73f55af74c6f63ffbc727904", "save_path": "github-repos/isabelle/BraeWebb-stackoverflow", "path": "github-repos/isabelle/BraeWebb-stackoverflow/stackoverflow-a043b47f0f5ed97f73f55af74c6f63ffbc727904/isabelle/KA_iso.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8791467643431002, "lm_q2_score": 0.8221891283434876, "lm_q1q2_score": 0.7228249118612511}}
{"text": "theory Chapter7\nimports \"HOL-IMP.Small_Step\" (*\"Short_Theory\"*)\nbegin\n\ntext \\<open>\n\\section*{Chapter 7}\n\n\\exercise\nDefine a function that computes the set of variables that are assigned to\nin a command:\n\\<close>\n\nfun assigned :: \"com \\<Rightarrow> vname set\" where\n(* your definition/proof here *)\n\ntext \\<open>\nProve that if some variable is not assigned to in a command,\nthen that variable is never modified by the command:\n\\<close>\n\nlemma \"\\<lbrakk> (c, s) \\<Rightarrow> t; x \\<notin> assigned c \\<rbrakk> \\<Longrightarrow> s x = t x\"\n(* your definition/proof here *)\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(* your definition/proof here *)\n\nlemma \"skip c \\<Longrightarrow> c \\<sim> SKIP\"\n(* your definition/proof here *)\n\ntext{*\n\\endexercise\n\n\\exercise\nDefine a recursive function\n*}\n\nfun deskip :: \"com \\<Rightarrow> com\" where\n(* your definition/proof here *)\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\"\n(* your definition/proof here *)\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(* 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(* your definition/proof here *)\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\"\n(* your definition/proof here *)\n\nlemma \"WHILE And b\\<^sub>1 b\\<^sub>2 DO c \\<sim> WHILE b\\<^sub>1 DO WHILE b\\<^sub>2 DO c\"\n(* your definition/proof here *)\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 \"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\"\n(* your definition/proof here *)\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(* your definition/proof here *)\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(* your definition/proof here *)\n\ntext{* Prove that your translation preserves the semantics: *}\n\nlemma \"dewhile c \\<sim> c\"\n(* your definition/proof here *)\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\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>\n                         (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\")\n(* your definition/proof here *)\n\ntext{*\n\\endexercise\n\\bigskip\n\nFor the following exercises copy theories\n@{short_theory \"Com\"}, @{short_theory \"Big_Step\"} and @{short_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": "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/Chapter7.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8104789178257654, "lm_q2_score": 0.891811054783143, "lm_q1q2_score": 0.7227940585856961}}
{"text": "section \\<open>CCW for Nonaligned Points in the Plane\\<close>\ntheory Counterclockwise_2D_Strict\nimports Counterclockwise_Vector\nbegin\ntext \\<open>\\label{sec:counterclockwise2d}\\<close>\n\nsubsection \\<open>Determinant\\<close>\n\ntype_synonym point = \"real*real\"\n\nfun det3::\"point \\<Rightarrow> point \\<Rightarrow> point \\<Rightarrow> real\" where \"det3 (xp, yp) (xq, yq) (xr, yr) =\n  xp * yq + yp * xr + xq * yr - yq * xr - yp * xq - xp * yr\"\n\nlemma det3_def':\n  \"det3 p q r = fst p * snd q + snd p * fst r + fst q * snd r -\n    snd q * fst r - snd p * fst q - fst p * snd r\"\n  by (cases p q r rule: prod.exhaust[case_product prod.exhaust[case_product prod.exhaust]]) auto\n\nlemma det3_eq_det: \"det3 (xa, ya) (xb, yb) (xc, yc) =\n  det (vector [vector [xa, ya, 1], vector [xb, yb, 1], vector [xc, yc, 1]]::real^3^3)\"\n  unfolding Determinants.det_def UNIV_3\n  by (auto simp: sum_over_permutations_insert\n    vector_3 sign_swap_id permutation_swap_id sign_compose)\n\ndeclare det3.simps[simp del]\n\nlemma det3_self23[simp]: \"det3 a b b = 0\"\n  and det3_self12[simp]: \"det3 b b a = 0\"\n  by (auto simp: det3_def')\n\nlemma\n  coll_ex_scaling:\n  assumes \"b \\<noteq> c\"\n  assumes d: \"det3 a b c = 0\"\n  shows \"\\<exists>r. a = b + r *\\<^sub>R (c - b)\"\nproof -\n  from assms have \"fst b \\<noteq> fst c \\<or> snd b \\<noteq> snd c\" by (auto simp: prod_eq_iff)\n  thus ?thesis\n  proof\n    assume neq: \"fst b \\<noteq> fst c\"\n    with d have \"snd a = ((fst a - fst b) * snd c + (fst c - fst a) * snd b) / (fst c - fst b)\"\n      by (auto simp: det3_def' field_simps)\n    hence \"snd a = ((fst a - fst b)/ (fst c - fst b)) * snd c +\n      ((fst c - fst a)/ (fst c - fst b)) * snd b\"\n      by (simp add: add_divide_distrib)\n    hence \"snd a = snd b + (fst a - fst b) * snd c / (fst c - fst b) +\n      ((fst c - fst a) - (fst c - fst b)) * snd b / (fst c - fst b)\"\n      using neq\n      by (simp add: field_simps)\n    hence \"snd a = snd b + ((fst a - fst b) * snd c + (- fst a + fst b) * snd b) / (fst c - fst b)\"\n      unfolding add_divide_distrib\n      by (simp add: algebra_simps)\n    also\n    have \"(fst a - fst b) * snd c + (- fst a + fst b) * snd b = (fst a - fst b) * (snd c - snd b)\"\n      by (simp add: algebra_simps)\n    finally have \"snd a = snd b + (fst a - fst b) / (fst c - fst b) * (snd c - snd b)\"\n      by simp\n    moreover\n    hence \"fst a = fst b + (fst a - fst b) / (fst c - fst b) * (fst c - fst b)\"\n      using neq by simp\n    ultimately have \"a = b + ((fst a - fst b) / (fst c - fst b)) *\\<^sub>R (c - b)\"\n      by (auto simp: prod_eq_iff)\n    thus ?thesis by blast\n  next\n    assume neq: \"snd b \\<noteq> snd c\"\n    with d have \"fst a = ((snd a - snd b) * fst c + (snd c - snd a) * fst b) / (snd c - snd b)\"\n      by (auto simp: det3_def' field_simps)\n    hence \"fst a = ((snd a - snd b)/ (snd c - snd b)) * fst c +\n      ((snd c - snd a)/ (snd c - snd b)) * fst b\"\n      by (simp add: add_divide_distrib)\n    hence \"fst a = fst b + (snd a - snd b) * fst c / (snd c - snd b) +\n      ((snd c - snd a) - (snd c - snd b)) * fst b / (snd c - snd b)\"\n      using neq\n      by (simp add: field_simps)\n    hence \"fst a = fst b + ((snd a - snd b) * fst c + (- snd a + snd b) * fst b) / (snd c - snd b)\"\n      unfolding add_divide_distrib\n      by (simp add: algebra_simps)\n    also\n    have \"(snd a - snd b) * fst c + (- snd a + snd b) * fst b = (snd a - snd b) * (fst c - fst b)\"\n      by (simp add: algebra_simps)\n    finally have \"fst a = fst b + (snd a - snd b) / (snd c - snd b) * (fst c - fst b)\"\n      by simp\n    moreover\n    hence \"snd a = snd b + (snd a - snd b) / (snd c - snd b) * (snd c - snd b)\"\n      using neq by simp\n    ultimately have \"a = b + ((snd a - snd b) / (snd c - snd b)) *\\<^sub>R (c - b)\"\n      by (auto simp: prod_eq_iff)\n    thus ?thesis by blast\n  qed\nqed\n\nlemma cramer: \"\\<not>det3 s t q = 0 \\<Longrightarrow>\n  (det3 t p r) = ((det3 t q r) * (det3 s t p) + (det3 t p q) * (det3 s t r))/(det3 s t q)\"\n  by (auto simp: det3_def' field_simps)\n\nlemma convex_comb_dets:\n  assumes \"det3 p q r > 0\"\n  shows \"s = (det3 s q r / det3 p q r) *\\<^sub>R p + (det3 p s r /  det3 p q r) *\\<^sub>R q +\n      (det3 p q s / det3 p q r) *\\<^sub>R r\"\n    (is \"?lhs = ?rhs\")\nproof -\n  from assms have \"det3 p q r *\\<^sub>R ?lhs = det3 p q r *\\<^sub>R ?rhs\"\n    by (simp add: field_simps prod_eq_iff scaleR_add_right) (simp add: algebra_simps det3_def')\n  thus ?thesis using assms by simp\nqed\n\nlemma four_points_aligned:\n  assumes c: \"det3 t p q = 0\" \"det3 t q r = 0\"\n  assumes distinct: \"distinct5 t s p q r\"\n  shows \"det3 t r p = 0\" \"det3 p q r = 0\"\nproof -\n  from distinct have d: \"p \\<noteq> q\" \"q \\<noteq> r\" by (auto)\n  from coll_ex_scaling[OF d(1) c(1)] obtain s1 where s1: \"t = p + s1 *\\<^sub>R (q - p)\" by auto\n  from coll_ex_scaling[OF d(2) c(2)] obtain s2 where s2: \"t = q + s2 *\\<^sub>R (r - q)\" by auto\n  from distinct s1 have ne: \"1 - s1 \\<noteq> 0\" by auto\n  from s1 s2 have \"(1 - s1) *\\<^sub>R p = (1 - s1 - s2) *\\<^sub>R q + s2 *\\<^sub>R r\"\n    by (simp add: algebra_simps)\n  hence \"(1 - s1) *\\<^sub>R p /\\<^sub>R (1 - s1)= ((1 - s1 - s2) *\\<^sub>R q + s2 *\\<^sub>R r) /\\<^sub>R (1 - s1)\"\n    by simp\n  with ne have p: \"p = ((1 - s1 - s2) / (1 - s1)) *\\<^sub>R q + (s2 / (1 - s1)) *\\<^sub>R r\"\n    using ne\n    by (simp add: prod_eq_iff inverse_eq_divide add_divide_distrib)\n  define k1 where \"k1 = (1 - s1 - s2) / (1 - s1)\"\n  define k2 where \"k2 = s2 / (1 - s1)\"\n  have \"det3 t r p = det3 0 (k1 *\\<^sub>R q + (k2 - 1) *\\<^sub>R r)\n    (k1 *\\<^sub>R q + (k2 - 1) *\\<^sub>R r + (- s1 * (k1 - 1)) *\\<^sub>R q - (s1 * k2) *\\<^sub>R r)\"\n    unfolding s1 p k1_def[symmetric] k2_def[symmetric]\n    by (simp add: algebra_simps det3_def')\n  also have \"- s1 * (k1 - 1) = s1 * k2\"\n    using ne by (auto simp: k1_def field_simps k2_def)\n  also\n  have \"1 - k1 = k2\"\n    using ne\n    by (auto simp: k2_def k1_def field_simps)\n  have k21: \"k2 - 1 = -k1\"\n    using ne\n    by (auto simp: k2_def k1_def field_simps)\n  finally have \"det3 t r p = det3 0 (k1 *\\<^sub>R (q - r)) ((k1 + (s1 * k2)) *\\<^sub>R (q - r))\"\n    by (auto simp: algebra_simps)\n  also have \"\\<dots> = 0\"\n    by (simp add: algebra_simps det3_def')\n  finally show \"det3 t r p = 0\" .\n  have \"det3 p q r = det3 (k1 *\\<^sub>R q + k2 *\\<^sub>R r) q r\"\n    unfolding p k1_def[symmetric] k2_def[symmetric] ..\n  also have \"\\<dots> = det3 0 (r - q) (k1 *\\<^sub>R q + (-k1) *\\<^sub>R r)\"\n    unfolding k21[symmetric]\n    by (auto simp: algebra_simps det3_def')\n  also have \"\\<dots> = det3 0 (r - q) (-k1 *\\<^sub>R (r - q))\"\n    by (auto simp: det3_def' algebra_simps)\n  also have \"\\<dots> = 0\"\n    by (auto simp: det3_def')\n  finally show \"det3 p q r = 0\" .\nqed\n\nlemma det_identity:\n  \"det3 t p q * det3 t s r + det3 t q r * det3 t s p + det3 t r p * det3 t s q = 0\"\n  by (auto simp: det3_def' algebra_simps)\n\nlemma det3_eq_zeroI:\n  assumes \"p = q + x *\\<^sub>R (t - q)\"\n  shows \"det3 q t p = 0\"\n  unfolding assms\n  by (auto simp: det3_def' algebra_simps)\n\nlemma det3_rotate: \"det3 a b c = det3 c a b\"\n  by (auto simp: det3_def')\n\nlemma det3_switch: \"det3 a b c = - det3 a c b\"\n  by (auto simp: det3_def')\n\nlemma det3_switch': \"det3 a b c = - det3 b a c\"\n  by (auto simp: det3_def')\n\nlemma det3_pos_transitive_coll:\n  \"det3 t s p > 0 \\<Longrightarrow> det3 t s r \\<ge> 0 \\<Longrightarrow> det3 t p q \\<ge> 0 \\<Longrightarrow>\n  det3 t q r > 0 \\<Longrightarrow> det3 t s q = 0 \\<Longrightarrow> det3 t p r > 0\"\n  using det_identity[of t p q s r]\n  by (metis add.commute add_less_same_cancel1 det3_switch det3_switch' less_eq_real_def\n    less_not_sym monoid_add_class.add.left_neutral mult_pos_pos mult_zero_left mult_zero_right)\n\nlemma det3_pos_transitive:\n  \"det3 t s p > 0 \\<Longrightarrow> det3 t s q \\<ge> 0 \\<Longrightarrow> det3 t s r \\<ge> 0 \\<Longrightarrow> det3 t p q \\<ge> 0 \\<Longrightarrow>\n  det3 t q r > 0 \\<Longrightarrow> det3 t p r > 0\"\n  apply (cases \"det3 t s q \\<noteq> 0\")\n   using cramer[of q t s p r]\n   apply (force simp: det3_rotate[of q t p] det3_rotate[of p q t] det3_switch[of t p s]\n     det3_switch'[of q t r] det3_rotate[of q t s] det3_rotate[of s q t]\n     intro!: divide_pos_pos add_nonneg_pos)\n  apply (metis det3_pos_transitive_coll)\n  done\n\nlemma det3_zero_translate_plus[simp]: \"det3 (a + x) (b + x) (c + x) = 0 \\<longleftrightarrow> det3 a b c = 0\"\n  by (auto simp: algebra_simps det3_def')\n\nlemma det3_zero_translate_plus'[simp]: \"det3 (a) (a + b) (a + c) = 0 \\<longleftrightarrow> det3 0 b c = 0\"\n  by (auto simp: algebra_simps det3_def')\n\nlemma\n  det30_zero_scaleR1:\n  \"0 < e \\<Longrightarrow> det3 0 xr P = 0 \\<Longrightarrow> det3 0 (e *\\<^sub>R xr) P = 0\"\n  by (auto simp: zero_prod_def algebra_simps det3_def')\n\nlemma det3_same[simp]: \"det3 a x x = 0\"\n  by (auto simp: det3_def')\n\nlemma\n  det30_zero_scaleR2:\n  \"0 < e \\<Longrightarrow> det3 0 P xr = 0 \\<Longrightarrow> det3 0 P (e *\\<^sub>R xr) = 0\"\n  by (auto simp: zero_prod_def algebra_simps det3_def')\n\n\n\nlemma det30_plus_scaled3[simp]: \"det3 0 a (b + x *\\<^sub>R a) = 0 \\<longleftrightarrow> det3 0 a b = 0\"\n  by (auto simp: det3_def' algebra_simps)\n\nlemma det30_plus_scaled2[simp]:\n  shows \"det3 0 (a + x *\\<^sub>R a) b = 0 \\<longleftrightarrow> (if x = -1 then True else det3 0 a b = 0)\"\n    (is \"?lhs = ?rhs\")\nproof\n  assume \"det3 0 (a + x *\\<^sub>R a) b = 0\"\n  hence \"fst a * snd b * (1 + x) = fst b * snd a * (1 + x)\"\n    by (simp add: algebra_simps det3_def')\n  thus ?rhs\n    by (auto simp add: det3_def')\nqed (auto simp: det3_def' algebra_simps split: if_split_asm)\n\nlemma det30_uminus2[simp]: \"det3 0 (-a) (b) = 0 \\<longleftrightarrow> det3 0 a b = 0\"\n  and det30_uminus3[simp]: \"det3 0 a (-b) = 0 \\<longleftrightarrow> det3 0 a b = 0\"\n  by (auto simp: det3_def' algebra_simps)\n\nlemma det30_minus_scaled3[simp]: \"det3 0 a (b - x *\\<^sub>R a) = 0 \\<longleftrightarrow> det3 0 a b = 0\"\n  using det30_plus_scaled3[of a b \"-x\"] by simp\n\nlemma det30_scaled_minus3[simp]: \"det3 0 a (e *\\<^sub>R a - b) = 0 \\<longleftrightarrow> det3 0 a b = 0\"\n  using det30_plus_scaled3[of a \"-b\" e]\n  by (simp add: algebra_simps)\n\nlemma det30_minus_scaled2[simp]:\n  \"det3 0 (a - x *\\<^sub>R a) b = 0 \\<longleftrightarrow> (if x = 1 then True else det3 0 a b = 0)\"\n  using det30_plus_scaled2[of a  \"-x\" b] by simp\n\nlemma det3_nonneg_scaleR1:\n  \"0 < e \\<Longrightarrow> det3 0 xr P \\<ge> 0 \\<Longrightarrow> det3 0 (e*\\<^sub>Rxr) P \\<ge> 0\"\n  by (auto simp add: det3_def' algebra_simps)\n\nlemma det3_nonneg_scaleR1_eq:\n  \"0 < e \\<Longrightarrow> det3 0 (e*\\<^sub>Rxr) P \\<ge> 0 \\<longleftrightarrow> det3 0 xr P \\<ge> 0\"\n  by (auto simp add: det3_def' algebra_simps)\n\nlemma det3_translate_origin: \"NO_MATCH 0 p \\<Longrightarrow> det3 p q r = det3 0 (q - p) (r - p)\"\n  by (auto simp: det3_def' algebra_simps)\n\nlemma det3_nonneg_scaleR_segment2:\n  assumes \"det3 x y z \\<ge> 0\"\n  assumes \"a > 0\"\n  shows \"det3 x ((1 - a) *\\<^sub>R x + a *\\<^sub>R y) z \\<ge> 0\"\nproof -\n  from assms have \"0 \\<le> det3 0 (a *\\<^sub>R (y - x)) (z - x)\"\n    by (intro det3_nonneg_scaleR1) (simp_all add: det3_translate_origin)\n  thus ?thesis\n    by (simp add: algebra_simps det3_translate_origin)\nqed\n\nlemma det3_nonneg_scaleR_segment1:\n  assumes \"det3 x y z \\<ge> 0\"\n  assumes \"0 \\<le> a\" \"a < 1\"\n  shows \"det3 ((1 - a) *\\<^sub>R x + a *\\<^sub>R y) y z \\<ge> 0\"\nproof -\n  from assms have \"det3 0 ((1 - a) *\\<^sub>R (y - x)) (z - x + (- a) *\\<^sub>R (y - x)) \\<ge> 0\"\n    by (subst det3_nonneg_scaleR1_eq) (auto simp add: det3_def' algebra_simps)\n  thus ?thesis\n    by (auto simp: algebra_simps det3_translate_origin)\nqed\n\n\nsubsection \\<open>Strict CCW Predicate\\<close>\n\ndefinition \"ccw' p q r \\<longleftrightarrow> 0 < det3 p q r\"\n\ninterpretation ccw': ccw_vector_space ccw'\n  by unfold_locales (auto simp: ccw'_def det3_def' algebra_simps)\n\ninterpretation ccw': linorder_list0 \"ccw' x\" for x .\n\nlemma ccw'_contra: \"ccw' t r q \\<Longrightarrow> ccw' t q r = False\"\n  by (auto simp: ccw'_def det3_def' algebra_simps)\n\nlemma not_ccw'_eq: \"\\<not> ccw' t p s \\<longleftrightarrow> ccw' t s p \\<or> det3 t s p = 0\"\n  by (auto simp: ccw'_def det3_def' algebra_simps)\n\nlemma neq_left_right_of: \"ccw' a b c \\<Longrightarrow> ccw' a c d \\<Longrightarrow> b \\<noteq> d\"\n  by (auto simp: ccw'_def det3_def' algebra_simps)\n\nlemma ccw'_subst_collinear:\n  assumes \"det3 t r s = 0\"\n  assumes \"s \\<noteq> t\"\n  assumes \"ccw' t r p\"\n  shows \"ccw' t s p \\<or> ccw' t p s\"\nproof cases\n  assume \"r \\<noteq> s\"\n  from assms have \"det3 r s t = 0\"\n    by (auto simp: algebra_simps det3_def')\n  from coll_ex_scaling[OF assms(2) this]\n  obtain x where s: \"r = s + x *\\<^sub>R (t - s)\" by auto\n  from assms(3)[simplified ccw'_def s]\n  have \"0 < det3 0 (s + x *\\<^sub>R (t - s) - t) (p - t)\"\n    by (auto simp: algebra_simps det3_def')\n  also have \"s + x *\\<^sub>R (t - s) - t = (1 - x) *\\<^sub>R (s - t)\"\n    by (simp add: algebra_simps)\n  finally have ccw': \"ccw' 0 ((1 - x) *\\<^sub>R (s - t)) (p - t)\"\n    by (simp add: ccw'_def)\n  hence \"x \\<noteq> 1\" by (auto simp add: det3_def' ccw'_def)\n  {\n    assume \"x < 1\"\n    hence ?thesis using ccw'\n      by (auto simp: not_ccw'_eq ccw'.translate_origin)\n  } moreover {\n    assume \"x > 1\"\n    hence ?thesis using ccw'\n      by (auto simp: not_ccw'_eq ccw'.translate_origin)\n  } ultimately show ?thesis using \\<open>x \\<noteq> 1\\<close> by arith\nqed (insert assms, simp)\n\nlemma ccw'_sorted_scaleR: \"ccw'.sortedP 0 xs \\<Longrightarrow> r > 0 \\<Longrightarrow> ccw'.sortedP 0 (map (op *\\<^sub>R r) xs)\"\n  by (induct xs) (auto intro!: ccw'.sortedP.Cons  elim!: ccw'.sortedP_Cons simp del: scaleR_Pair)\n\n\nsubsection \\<open>Collinearity\\<close>\n\nabbreviation \"coll a b c \\<equiv> det3 a b c = 0\"\n\nlemma coll_zero[intro, simp]: \"coll 0 z 0\"\n  by (auto simp: det3_def')\n\nlemma coll_zero1[intro, simp]: \"coll 0 0 z\"\n  by (auto simp: det3_def')\n\nlemma coll_self[intro, simp]: \"coll 0 z z\"\n  by (auto simp: )\n\nlemma ccw'_not_coll:\n  \"ccw' a b c \\<Longrightarrow> \\<not>coll a b c\"\n  \"ccw' a b c \\<Longrightarrow> \\<not>coll a c b\"\n  \"ccw' a b c \\<Longrightarrow> \\<not>coll b a c\"\n  \"ccw' a b c \\<Longrightarrow> \\<not>coll b c a\"\n  \"ccw' a b c \\<Longrightarrow> \\<not>coll c a b\"\n  \"ccw' a b c \\<Longrightarrow> \\<not>coll c b a\"\n  by (auto simp: det3_def' ccw'_def algebra_simps)\n\nlemma coll_add: \"coll 0 x y \\<Longrightarrow> coll 0 x z \\<Longrightarrow> coll 0 x (y + z)\"\n  by (auto simp: det3_def' algebra_simps)\n\nlemma coll_scaleR_left_eq[simp]: \"coll 0 (r *\\<^sub>R x) y \\<longleftrightarrow> r = 0 \\<or> coll 0 x y\"\n  by (auto simp: det3_def' algebra_simps)\n\nlemma coll_scaleR_right_eq[simp]: \"coll 0 y (r *\\<^sub>R x) \\<longleftrightarrow> r = 0 \\<or> coll 0 y x\"\n  by (auto simp: det3_def' algebra_simps)\n\nlemma coll_scaleR: \"coll 0 x y \\<Longrightarrow> coll 0 (r *\\<^sub>R x) y\"\n  by (auto simp: det3_def' algebra_simps)\n\nlemma coll_sum_list: \"(\\<And>y. y \\<in> set ys \\<Longrightarrow> coll 0 x y) \\<Longrightarrow> coll 0 x (sum_list ys)\"\n  by (induct ys) (auto intro!: coll_add)\n\nlemma scaleR_left_normalize:\n  fixes a ::real and b c::\"'a::real_vector\"\n  shows \"a *\\<^sub>R b = c \\<longleftrightarrow> (if a = 0 then c = 0 else b = c /\\<^sub>R a)\"\n  by (auto simp: field_simps)\n\n\n\nlemma coll_scale: \"coll 0 r q \\<Longrightarrow> r \\<noteq> 0 \\<Longrightarrow> (\\<exists>x. q = x *\\<^sub>R r)\"\n  using coll_scale_pair[of \"fst r\" \"snd r\" \"fst q\" \"snd q\"]\n  by simp\n\nlemma coll_add_trans:\n  assumes \"coll 0 x (y + z)\"\n  assumes \"coll 0 y z\"\n  assumes \"x \\<noteq> 0\"\n  assumes \"y \\<noteq> 0\"\n  assumes \"z \\<noteq> 0\"\n  assumes \"y + z \\<noteq> 0\"\n  shows \"coll 0 x z\"\nproof (cases \"snd z = 0\")\n  case True\n  hence \"snd y = 0\"\n    using assms\n    by (cases z) (auto simp add: zero_prod_def det3_def')\n  with True assms have \"snd x = 0\"\n    by (cases y, cases z) (auto simp add: zero_prod_def det3_def')\n  from \\<open>snd x = 0\\<close> \\<open>snd y = 0\\<close> \\<open>snd z = 0\\<close>\n  show ?thesis\n    by (auto simp add: zero_prod_def det3_def')\nnext\n  case False\n  note z = False\n  hence \"snd y \\<noteq> 0\"\n    using assms\n    by (cases y) (auto simp add: zero_prod_def det3_def')\n  with False assms have \"snd x \\<noteq> 0\"\n    apply (cases x)\n    apply (cases y)\n    apply (cases z)\n    apply (auto simp add: zero_prod_def det3_def')\n    apply (metis mult.commute mult_eq_0_iff ring_class.ring_distribs(1))\n    done\n  with False assms \\<open>snd y \\<noteq> 0\\<close> have yz: \"snd (y + z) \\<noteq> 0\"\n    by (cases x; cases y; cases z) (auto simp add: det3_def' zero_prod_def)\n  from coll_scale[OF assms(1) assms(3)] coll_scale[OF assms(2) assms(4)]\n  obtain r s where rs: \"y + z = r *\\<^sub>R x\" \"z = s *\\<^sub>R y\"\n    by auto\n  with z have \"s \\<noteq> 0\"\n    by (cases x; cases y; cases z) (auto simp: zero_prod_def)\n  with rs z yz have \"r \\<noteq> 0\"\n    by (cases x; cases y; cases z) (auto simp: zero_prod_def)\n  from \\<open>s \\<noteq> 0\\<close> rs have \"y = r *\\<^sub>R x - z\" \"y = z /\\<^sub>R s\"\n    by (auto simp: inverse_eq_divide algebra_simps)\n  hence \"r *\\<^sub>R x - z = z /\\<^sub>R s\" by simp\n  hence \"r *\\<^sub>R x = (1 + inverse s) *\\<^sub>R z\"\n    by (auto simp: inverse_eq_divide algebra_simps)\n  hence \"x = (inverse r * (1 + inverse s)) *\\<^sub>R z\"\n    using \\<open>r \\<noteq> 0\\<close> \\<open>s \\<noteq> 0\\<close>\n    by (auto simp: field_simps scaleR_left_normalize)\n  from this\n  show ?thesis\n    by (auto intro: coll_scaleR)\nqed\n\nlemma coll_commute: \"coll 0 a b \\<longleftrightarrow> coll 0 b a\"\n  by (metis det3_rotate det3_switch' diff_0 diff_self)\n\nlemma coll_add_cancel: \"coll 0 a (a + b) \\<Longrightarrow> coll 0 a b\"\n  by (cases a, cases b) (auto simp: det3_def' algebra_simps)\n\nlemma coll_trans:\n  \"coll 0 a b \\<Longrightarrow> coll 0 a c \\<Longrightarrow> a \\<noteq> 0 \\<Longrightarrow> coll 0 b c\"\n  by (metis coll_scale coll_scaleR)\n\nlemma sum_list_posI:\n  fixes xs::\"'a::ordered_comm_monoid_add list\"\n  shows \"(\\<And>x. x \\<in> set xs \\<Longrightarrow> x > 0) \\<Longrightarrow> xs \\<noteq> [] \\<Longrightarrow> sum_list xs > 0\"\nproof (induct xs)\n  case (Cons x xs)\n  thus ?case\n    by (cases \"xs = []\") (auto intro!: add_pos_pos)\nqed simp\n\nlemma fst_sum_list: \"fst (sum_list xs) = sum_list (map fst xs)\"\n  by (induct xs) auto\n\nlemma snd_sum_list: \"snd (sum_list xs) = sum_list (map snd xs)\"\n  by (induct xs) auto\n\nlemma nonzero_fstI[intro, simp]: \"fst x \\<noteq> 0 \\<Longrightarrow> x \\<noteq> 0\"\n  and nonzero_sndI[intro, simp]: \"snd x \\<noteq> 0 \\<Longrightarrow> x \\<noteq> 0\"\n  by auto\n\nlemma coll_sum_list_trans:\n  \"xs \\<noteq> [] \\<Longrightarrow> coll 0 a (sum_list xs) \\<Longrightarrow> (\\<And>x. x \\<in> set xs \\<Longrightarrow> coll 0 x y) \\<Longrightarrow>\n    (\\<And>x. x \\<in> set xs \\<Longrightarrow> coll 0 x (sum_list xs)) \\<Longrightarrow>\n    (\\<And>x. x \\<in> set xs \\<Longrightarrow> snd x > 0) \\<Longrightarrow> a \\<noteq> 0 \\<Longrightarrow> coll 0 a y\"\nproof (induct xs rule: list_nonempty_induct)\n  case (single x)\n  from single(1) single(2)[of x] single(4)[of x] have \"coll 0 x a\" \"coll 0 x y\" \"x \\<noteq> 0\"\n    by (auto simp: coll_commute)\n  thus ?case by (rule coll_trans)\nnext\n  case (cons x xs)\n  from cons(5)[of x] \\<open>a \\<noteq> 0\\<close> cons(6)[of x]\n  have *: \"coll 0 x (sum_list xs)\" \"a \\<noteq> 0\" \"x \\<noteq> 0\" by (force simp add: coll_add_cancel)+\n  have \"0 < snd (sum_list (x#xs))\"\n    unfolding snd_sum_list\n    by (rule sum_list_posI) (auto intro!: add_pos_pos cons simp: snd_sum_list)\n  hence \"x + sum_list xs \\<noteq> 0\" by simp\n  from coll_add_trans[OF cons(3)[simplified] * _ this]\n  have cH: \"coll 0 a (sum_list xs)\"\n    by (cases \"sum_list xs = 0\") auto\n  from cons(4) have cy: \"(\\<And>x. x \\<in> set xs \\<Longrightarrow> coll 0 x y)\" by simp\n  {\n    fix y assume \"y \\<in> set xs\"\n    hence \"snd (sum_list xs) > 0\"\n      unfolding snd_sum_list\n      by (intro sum_list_posI) (auto intro!: add_pos_pos cons simp: snd_sum_list)\n    hence \"sum_list xs \\<noteq> 0\" by simp\n    from cons(5)[of x] have \"coll 0 x (sum_list xs)\"\n      by (simp add: coll_add_cancel)\n    from cons(5)[of y]\n    have \"coll 0 y (sum_list xs)\"\n      using \\<open>y \\<in> set xs\\<close> cons(6)[of y] \\<open>x + sum_list xs \\<noteq> 0\\<close>\n      apply (cases \"y = x\")\n      subgoal by (force simp add: coll_add_cancel)\n      subgoal by (force simp: dest!: coll_add_trans[OF _ *(1) _ *(3)])\n      done\n  } note cl = this\n  show ?case\n    by (rule cons(2)[OF cH cy cl cons(6) \\<open>a \\<noteq> 0\\<close>]) auto\nqed\n\nlemma sum_list_coll_ex_scale:\n  assumes coll: \"\\<And>x. x \\<in> set xs \\<Longrightarrow> coll 0 z x\"\n  assumes nz: \"z \\<noteq> 0\"\n  shows \"\\<exists>r. sum_list xs = r *\\<^sub>R z\"\nproof -\n  {\n    fix i assume i: \"i < length xs\"\n    hence nth: \"xs ! i \\<in> set xs\" by simp\n    note coll_scale[OF coll[OF nth] \\<open>z \\<noteq> 0\\<close>]\n  } then obtain r where r: \"\\<And>i. i < length xs \\<Longrightarrow> xs ! i = r i *\\<^sub>R z\"\n    by metis\n  have \"xs = map (op ! xs) [0..<length xs]\" by (simp add: map_nth)\n  also have \"\\<dots> = map (\\<lambda>i. r i *\\<^sub>R z) [0..<length xs]\" by (simp add: r)\n  also have \"sum_list \\<dots> = (\\<Sum>i\\<leftarrow>[0..<length xs]. r i) *\\<^sub>R z\"\n    by (simp add: sum_list_sum_nth scaleR_sum_left)\n  finally show ?thesis ..\nqed\n\nlemma sum_list_filter_coll_ex_scale: \"z \\<noteq> 0 \\<Longrightarrow> \\<exists>r. sum_list (filter (coll 0 z) zs) = r *\\<^sub>R z\"\n  by (rule sum_list_coll_ex_scale) simp\n\nend\n", "meta": {"author": "rizaldialbert", "repo": "overtaking", "sha": "0e76426d75f791635cd9e23b8e07669b7ce61a81", "save_path": "github-repos/isabelle/rizaldialbert-overtaking", "path": "github-repos/isabelle/rizaldialbert-overtaking/overtaking-0e76426d75f791635cd9e23b8e07669b7ce61a81/Affine_Arithmetic/Counterclockwise_2D_Strict.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110396870287, "lm_q2_score": 0.810478913248044, "lm_q1q2_score": 0.7227940422681512}}
{"text": "(*  \n    Title:      Rank.thy\n    Author:     Jose Divas\u00f3n <jose.divasonm at unirioja.es>\n    Author:     Jes\u00fas Aransay <jesus-maria.aransay at unirioja.es>\n    Maintainer: Jose Divas\u00f3n <jose.divasonm at unirioja.es>\n*)\n\nsection\\<open>Rank of a matrix\\<close>\n\ntheory Rank\nimports \n      Rank_Nullity_Theorem.Dim_Formula\nbegin\n\nsubsection\\<open>Row rank, column rank and rank\\<close>\n\ntext\\<open>Definitions of row rank, column rank and rank\\<close>\n\ndefinition row_rank :: \"'a::{field}^'n^'m=>nat\"\n  where \"row_rank A = vec.dim (row_space A)\"\n\ndefinition col_rank :: \"'a::{field}^'n^'m=>nat\"\n  where \"col_rank A = vec.dim (col_space A)\"\n\nlemma rank_def: \"rank A = row_rank A\"\n  by (auto simp: row_rank_def row_rank_def_gen row_space_def)\n\nsubsection\\<open>Properties\\<close>\n\nlemma rrk_is_preserved:\nfixes A::\"'a::{field}^'cols^'rows::{finite, wellorder}\"\n  and P::\"'a::{field}^'rows::{finite, wellorder}^'rows::{finite, wellorder}\"\nassumes inv_P: \"invertible P\"\nshows \"row_rank A = row_rank (P**A)\"\nby (metis row_space_is_preserved row_rank_def inv_P)\n\nlemma crk_is_preserved:\nfixes A::\"'a::{field}^'cols::{finite, wellorder}^'rows\"\n  and P::\"'a::{field}^'rows^'rows\"\nassumes inv_P: \"invertible P\"\nshows \"col_rank A = col_rank (P**A)\"\n  using rank_nullity_theorem_matrices unfolding ncols_def \n  by (metis col_rank_def inv_P add_left_cancel null_space_is_preserved) \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/Gauss_Jordan/Rank.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8840392695254319, "lm_q2_score": 0.817574471748733, "lm_q1q2_score": 0.7227679387873908}}
{"text": "(*<*)theory CTL imports Base begin(*>*)\n\nsubsection\\<open>Computation Tree Logic --- CTL\\<close>\n\ntext\\<open>\\label{sec:CTL}\n\\index{CTL|(}%\nThe semantics of PDL only needs reflexive transitive closure.\nLet us be adventurous and introduce a more expressive temporal operator.\nWe extend the datatype\n\\<open>formula\\<close> by a new constructor\n\\<close>\n(*<*)\ndatatype formula = Atom \"atom\"\n                  | Neg formula\n                  | And formula formula\n                  | AX formula\n                  | EF formula(*>*)\n                  | AF formula\n\ntext\\<open>\\noindent\nwhich stands for ``\\emph{A}lways in the \\emph{F}uture'':\non all infinite paths, at some point the formula holds.\nFormalizing the notion of an infinite path is easy\nin HOL: it is simply a function from \\<^typ>\\<open>nat\\<close> to \\<^typ>\\<open>state\\<close>.\n\\<close>\n\ndefinition Paths :: \"state \\<Rightarrow> (nat \\<Rightarrow> state)set\" where\n\"Paths s \\<equiv> {p. s = p 0 \\<and> (\\<forall>i. (p i, p(i+1)) \\<in> M)}\"\n\ntext\\<open>\\noindent\nThis definition allows a succinct statement of the semantics of \\<^const>\\<open>AF\\<close>:\n\\footnote{Do not be misled: neither datatypes nor recursive functions can be\nextended by new constructors or equations. This is just a trick of the\npresentation (see \\S\\ref{sec:doc-prep-suppress}). In reality one has to define\na new datatype and a new function.}\n\\<close>\n(*<*)\nprimrec valid :: \"state \\<Rightarrow> formula \\<Rightarrow> bool\" (\"(_ \\<Turnstile> _)\" [80,80] 80) where\n\"s \\<Turnstile> Atom a  =  (a \\<in> L s)\" |\n\"s \\<Turnstile> Neg f   = (~(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(*>*)\n\"s \\<Turnstile> AF f    = (\\<forall>p \\<in> Paths s. \\<exists>i. p i \\<Turnstile> f)\"\n\ntext\\<open>\\noindent\nModel checking \\<^const>\\<open>AF\\<close> involves a function which\nis just complicated enough to warrant a separate definition:\n\\<close>\n\ndefinition af :: \"state set \\<Rightarrow> state set \\<Rightarrow> state set\" where\n\"af A T \\<equiv> A \\<union> {s. \\<forall>t. (s, t) \\<in> M \\<longrightarrow> t \\<in> T}\"\n\ntext\\<open>\\noindent\nNow we define \\<^term>\\<open>mc(AF f)\\<close> as the least set \\<^term>\\<open>T\\<close> that includes\n\\<^term>\\<open>mc f\\<close> and all states all of whose direct successors are in \\<^term>\\<open>T\\<close>:\n\\<close>\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\"mc(AF f)    = lfp(af(mc f))\"\n\ntext\\<open>\\noindent\nBecause \\<^const>\\<open>af\\<close> is monotone in its second argument (and also its first, but\nthat is irrelevant), \\<^term>\\<open>af A\\<close> has a least fixed point:\n\\<close>\n\nlemma mono_af: \"mono(af A)\"\napply(simp add: mono_def af_def)\napply blast\ndone\n(*<*)\nlemma mono_ef: \"mono(\\<lambda>T. A \\<union> M\\<inverse> `` T)\"\napply(rule monoI)\nby(blast)\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}\"\napply(rule equalityI)\n apply(rule subsetI)\n apply(simp)\n apply(erule lfp_induct_set)\n  apply(rule mono_ef)\n apply(simp)\n apply(blast intro: rtrancl_trans)\napply(rule subsetI)\napply(simp, clarify)\napply(erule converse_rtrancl_induct)\n apply(subst lfp_unfold[OF mono_ef])\n apply(blast)\napply(subst lfp_unfold[OF mono_ef])\nby(blast)\n(*>*)\ntext\\<open>\nAll we need to prove now is  \\<^prop>\\<open>mc(AF f) = {s. s \\<Turnstile> AF f}\\<close>, which states\nthat \\<^term>\\<open>mc\\<close> and \\<open>\\<Turnstile>\\<close> agree for \\<^const>\\<open>AF\\<close>\\@.\nThis time we prove the two inclusions separately, starting\nwith the easy one:\n\\<close>\n\ntheorem AF_lemma1: \"lfp(af A) \\<subseteq> {s. \\<forall>p \\<in> Paths s. \\<exists>i. p i \\<in> A}\"\n\ntxt\\<open>\\noindent\nIn contrast to the analogous proof for \\<^const>\\<open>EF\\<close>, and just\nfor a change, we do not use fixed point induction.  Park-induction,\nnamed after David Park, is weaker but sufficient for this proof:\n\\begin{center}\n@{thm lfp_lowerbound[of _ \"S\",no_vars]} \\hfill (@{thm[source]lfp_lowerbound})\n\\end{center}\nThe instance of the premise \\<^prop>\\<open>f S \\<subseteq> S\\<close> is proved pointwise,\na decision that \\isa{auto} takes for us:\n\\<close>\napply(rule lfp_lowerbound)\napply(auto simp add: af_def Paths_def)\n\ntxt\\<open>\n@{subgoals[display,indent=0,margin=70,goals_limit=1]}\nIn this remaining case, we set \\<^term>\\<open>t\\<close> to \\<^term>\\<open>p(1::nat)\\<close>.\nThe rest is automatic, which is surprising because it involves\nfinding the instantiation \\<^term>\\<open>\\<lambda>i::nat. p(i+1)\\<close>\nfor \\<open>\\<forall>p\\<close>.\n\\<close>\n\napply(erule_tac x = \"p 1\" in allE)\napply(auto)\ndone\n\n\ntext\\<open>\nThe opposite inclusion is proved by contradiction: if some state\n\\<^term>\\<open>s\\<close> is not in \\<^term>\\<open>lfp(af A)\\<close>, then we can construct an\ninfinite \\<^term>\\<open>A\\<close>-avoiding path starting from~\\<^term>\\<open>s\\<close>. The reason is\nthat by unfolding \\<^const>\\<open>lfp\\<close> we find that if \\<^term>\\<open>s\\<close> is not in\n\\<^term>\\<open>lfp(af A)\\<close>, then \\<^term>\\<open>s\\<close> is not in \\<^term>\\<open>A\\<close> and there is a\ndirect successor of \\<^term>\\<open>s\\<close> that is again not in \\mbox{\\<^term>\\<open>lfp(af\nA)\\<close>}. Iterating this argument yields the promised infinite\n\\<^term>\\<open>A\\<close>-avoiding path. Let us formalize this sketch.\n\nThe one-step argument in the sketch above\nis proved by a variant of contraposition:\n\\<close>\n\nlemma not_in_lfp_afD:\n \"s \\<notin> lfp(af A) \\<Longrightarrow> s \\<notin> A \\<and> (\\<exists> t. (s,t) \\<in> M \\<and> t \\<notin> lfp(af A))\"\napply(erule contrapos_np)\napply(subst lfp_unfold[OF mono_af])\napply(simp add: af_def)\ndone\n\ntext\\<open>\\noindent\nWe assume the negation of the conclusion and prove \\<^term>\\<open>s \\<in> lfp(af A)\\<close>.\nUnfolding \\<^const>\\<open>lfp\\<close> once and\nsimplifying with the definition of \\<^const>\\<open>af\\<close> finishes the proof.\n\nNow we iterate this process. The following construction of the desired\npath is parameterized by a predicate \\<^term>\\<open>Q\\<close> that should hold along the path:\n\\<close>\n\nprimrec path :: \"state \\<Rightarrow> (state \\<Rightarrow> bool) \\<Rightarrow> (nat \\<Rightarrow> state)\" where\n\"path s Q 0 = s\" |\n\"path s Q (Suc n) = (SOME t. (path s Q n,t) \\<in> M \\<and> Q t)\"\n\ntext\\<open>\\noindent\nElement \\<^term>\\<open>n+1::nat\\<close> on this path is some arbitrary successor\n\\<^term>\\<open>t\\<close> of element \\<^term>\\<open>n\\<close> such that \\<^term>\\<open>Q t\\<close> holds.  Remember that \\<open>SOME t. R t\\<close>\nis some arbitrary but fixed \\<^term>\\<open>t\\<close> such that \\<^prop>\\<open>R t\\<close> holds (see \\S\\ref{sec:SOME}). Of\ncourse, such a \\<^term>\\<open>t\\<close> need not exist, but that is of no\nconcern to us since we will only use \\<^const>\\<open>path\\<close> when a\nsuitable \\<^term>\\<open>t\\<close> does exist.\n\nLet us show that if each state \\<^term>\\<open>s\\<close> that satisfies \\<^term>\\<open>Q\\<close>\nhas a successor that again satisfies \\<^term>\\<open>Q\\<close>, then there exists an infinite \\<^term>\\<open>Q\\<close>-path:\n\\<close>\n\nlemma infinity_lemma:\n  \"\\<lbrakk> Q s; \\<forall>s. Q s \\<longrightarrow> (\\<exists> t. (s,t) \\<in> M \\<and> Q t) \\<rbrakk> \\<Longrightarrow>\n   \\<exists>p\\<in>Paths s. \\<forall>i. Q(p i)\"\n\ntxt\\<open>\\noindent\nFirst we rephrase the conclusion slightly because we need to prove simultaneously\nboth the path property and the fact that \\<^term>\\<open>Q\\<close> holds:\n\\<close>\n\napply(subgoal_tac\n  \"\\<exists>p. s = p 0 \\<and> (\\<forall>i::nat. (p i, p(i+1)) \\<in> M \\<and> Q(p i))\")\n\ntxt\\<open>\\noindent\nFrom this proposition the original goal follows easily:\n\\<close>\n\n apply(simp add: Paths_def, blast)\n\ntxt\\<open>\\noindent\nThe new subgoal is proved by providing the witness \\<^term>\\<open>path s Q\\<close> for \\<^term>\\<open>p\\<close>:\n\\<close>\n\napply(rule_tac x = \"path s Q\" in exI)\napply(clarsimp)\n\ntxt\\<open>\\noindent\nAfter simplification and clarification, the subgoal has the following form:\n@{subgoals[display,indent=0,margin=70,goals_limit=1]}\nIt invites a proof by induction on \\<^term>\\<open>i\\<close>:\n\\<close>\n\napply(induct_tac i)\n apply(simp)\n\ntxt\\<open>\\noindent\nAfter simplification, the base case boils down to\n@{subgoals[display,indent=0,margin=70,goals_limit=1]}\nThe conclusion looks exceedingly trivial: after all, \\<^term>\\<open>t\\<close> is chosen such that \\<^prop>\\<open>(s,t)\\<in>M\\<close>\nholds. However, we first have to show that such a \\<^term>\\<open>t\\<close> actually exists! This reasoning\nis embodied in the theorem @{thm[source]someI2_ex}:\n@{thm[display,eta_contract=false]someI2_ex}\nWhen we apply this theorem as an introduction rule, \\<open>?P x\\<close> becomes\n\\<^prop>\\<open>(s, x) \\<in> M \\<and> Q x\\<close> and \\<open>?Q x\\<close> becomes \\<^prop>\\<open>(s,x) \\<in> M\\<close> and we have to prove\ntwo subgoals: \\<^prop>\\<open>\\<exists>a. (s, a) \\<in> M \\<and> Q a\\<close>, which follows from the assumptions, and\n\\<^prop>\\<open>(s, x) \\<in> M \\<and> Q x \\<Longrightarrow> (s,x) \\<in> M\\<close>, which is trivial. Thus it is not surprising that\n\\<open>fast\\<close> can prove the base case quickly:\n\\<close>\n\n apply(fast intro: someI2_ex)\n\ntxt\\<open>\\noindent\nWhat is worth noting here is that we have used \\methdx{fast} rather than\n\\<open>blast\\<close>.  The reason is that \\<open>blast\\<close> would fail because it cannot\ncope with @{thm[source]someI2_ex}: unifying its conclusion with the current\nsubgoal is non-trivial because of the nested schematic variables. For\nefficiency reasons \\<open>blast\\<close> does not even attempt such unifications.\nAlthough \\<open>fast\\<close> can in principle cope with complicated unification\nproblems, in practice the number of unifiers arising is often prohibitive and\nthe offending rule may need to be applied explicitly rather than\nautomatically. This is what happens in the step case.\n\nThe induction step is similar, but more involved, because now we face nested\noccurrences of \\<open>SOME\\<close>. As a result, \\<open>fast\\<close> is no longer able to\nsolve the subgoal and we apply @{thm[source]someI2_ex} by hand.  We merely\nshow the proof commands but do not describe the details:\n\\<close>\n\napply(simp)\napply(rule someI2_ex)\n apply(blast)\napply(rule someI2_ex)\n apply(blast)\napply(blast)\ndone\n\ntext\\<open>\nFunction \\<^const>\\<open>path\\<close> has fulfilled its purpose now and can be forgotten.\nIt was merely defined to provide the witness in the proof of the\n@{thm[source]infinity_lemma}. Aficionados of minimal proofs might like to know\nthat we could have given the witness without having to define a new function:\nthe term\n@{term[display]\"rec_nat s (\\<lambda>n t. SOME u. (t,u)\\<in>M \\<and> Q u)\"}\nis extensionally equal to \\<^term>\\<open>path s Q\\<close>,\nwhere \\<^term>\\<open>rec_nat\\<close> is the predefined primitive recursor on \\<^typ>\\<open>nat\\<close>.\n\\<close>\n(*<*)\nlemma\n\"\\<lbrakk> Q s; \\<forall> s. Q s \\<longrightarrow> (\\<exists> t. (s,t)\\<in>M \\<and> Q t) \\<rbrakk> \\<Longrightarrow>\n \\<exists> p\\<in>Paths s. \\<forall> i. Q(p i)\"\napply(subgoal_tac\n \"\\<exists> p. s = p 0 \\<and> (\\<forall> i. (p i,p(Suc i))\\<in>M \\<and> Q(p i))\")\n apply(simp add: Paths_def)\n apply(blast)\napply(rule_tac x = \"rec_nat s (\\<lambda>n t. SOME u. (t,u)\\<in>M \\<and> Q u)\" in exI)\napply(simp)\napply(intro strip)\napply(induct_tac i)\n apply(simp)\n apply(fast intro: someI2_ex)\napply(simp)\napply(rule someI2_ex)\n apply(blast)\napply(rule someI2_ex)\n apply(blast)\nby(blast)\n(*>*)\n\ntext\\<open>\nAt last we can prove the opposite direction of @{thm[source]AF_lemma1}:\n\\<close>\n\ntheorem AF_lemma2: \"{s. \\<forall>p \\<in> Paths s. \\<exists>i. p i \\<in> A} \\<subseteq> lfp(af A)\"\n\ntxt\\<open>\\noindent\nThe proof is again pointwise and then by contraposition:\n\\<close>\n\napply(rule subsetI)\napply(erule contrapos_pp)\napply simp\n\ntxt\\<open>\n@{subgoals[display,indent=0,goals_limit=1]}\nApplying the @{thm[source]infinity_lemma} as a destruction rule leaves two subgoals, the second\npremise of @{thm[source]infinity_lemma} and the original subgoal:\n\\<close>\n\napply(drule infinity_lemma)\n\ntxt\\<open>\n@{subgoals[display,indent=0,margin=65]}\nBoth are solved automatically:\n\\<close>\n\n apply(auto dest: not_in_lfp_afD)\ndone\n\ntext\\<open>\nIf you find these proofs too complicated, we recommend that you read\n\\S\\ref{sec:CTL-revisited}, where we show how inductive definitions lead to\nsimpler arguments.\n\nThe main theorem is proved as for PDL, except that we also derive the\nnecessary equality \\<open>lfp(af A) = ...\\<close> by combining\n@{thm[source]AF_lemma1} and @{thm[source]AF_lemma2} on the spot:\n\\<close>\n\ntheorem \"mc f = {s. s \\<Turnstile> f}\"\napply(induct_tac f)\napply(auto simp add: EF_lemma equalityI[OF AF_lemma1 AF_lemma2])\ndone\n\ntext\\<open>\n\nThe language defined above is not quite CTL\\@. The latter also includes an\nuntil-operator \\<^term>\\<open>EU f g\\<close> with semantics ``there \\emph{E}xists a path\nwhere \\<^term>\\<open>f\\<close> is true \\emph{U}ntil \\<^term>\\<open>g\\<close> becomes true''.  We need\nan auxiliary function:\n\\<close>\n\nprimrec\nuntil:: \"state set \\<Rightarrow> state set \\<Rightarrow> state \\<Rightarrow> state list \\<Rightarrow> bool\" where\n\"until A B s []    = (s \\<in> B)\" |\n\"until A B s (t#p) = (s \\<in> A \\<and> (s,t) \\<in> M \\<and> until A B t p)\"\n(*<*)definition\n eusem :: \"state set \\<Rightarrow> state set \\<Rightarrow> state set\" where\n\"eusem A B \\<equiv> {s. \\<exists>p. until A B s p}\"(*>*)\n\ntext\\<open>\\noindent\nExpressing the semantics of \\<^term>\\<open>EU\\<close> is now straightforward:\n@{prop[display]\"s \\<Turnstile> EU f g = (\\<exists>p. until {t. t \\<Turnstile> f} {t. t \\<Turnstile> g} s p)\"}\nNote that \\<^term>\\<open>EU\\<close> is not definable in terms of the other operators!\n\nModel checking \\<^term>\\<open>EU\\<close> is again a least fixed point construction:\n@{text[display]\"mc(EU f g) = lfp(\\<lambda>T. mc g \\<union> mc f \\<inter> (M\\<inverse> `` T))\"}\n\n\\begin{exercise}\nExtend the datatype of formulae by the above until operator\nand prove the equivalence between semantics and model checking, i.e.\\ that\n@{prop[display]\"mc(EU f g) = {s. s \\<Turnstile> EU f g}\"}\n%For readability you may want to annotate {term EU} with its customary syntax\n%{text[display]\"| EU formula formula    E[_ U _]\"}\n%which enables you to read and write {text\"E[f U g]\"} instead of {term\"EU f g\"}.\n\\end{exercise}\nFor more CTL exercises see, for example, Huth and Ryan \\<^cite>\\<open>\"Huth-Ryan-book\"\\<close>.\n\\<close>\n\n(*<*)\ndefinition eufix :: \"state set \\<Rightarrow> state set \\<Rightarrow> state set \\<Rightarrow> state set\" where\n\"eufix A B T \\<equiv> B \\<union> A \\<inter> (M\\<inverse> `` T)\"\n\nlemma \"lfp(eufix A B) \\<subseteq> eusem A B\"\napply(rule lfp_lowerbound)\napply(auto simp add: eusem_def eufix_def)\n apply(rule_tac x = \"[]\" in exI)\n apply simp\napply(rule_tac x = \"xa#xb\" in exI)\napply simp\ndone\n\nlemma mono_eufix: \"mono(eufix A B)\"\napply(simp add: mono_def eufix_def)\napply blast\ndone\n\nlemma \"eusem A B \\<subseteq> lfp(eufix A B)\"\napply(clarsimp simp add: eusem_def)\napply(erule rev_mp)\napply(rule_tac x = x in spec)\napply(induct_tac p)\n apply(subst lfp_unfold[OF mono_eufix])\n apply(simp add: eufix_def)\napply(clarsimp)\napply(subst lfp_unfold[OF mono_eufix])\napply(simp add: eufix_def)\napply blast\ndone\n\n(*\ndefinition eusem :: \"state set \\<Rightarrow> state set \\<Rightarrow> state set\" where\n\"eusem A B \\<equiv> {s. \\<exists>p\\<in>Paths s. \\<exists>j. p j \\<in> B \\<and> (\\<forall>i < j. p i \\<in> A)}\"\n\naxiomatization where\nM_total: \"\\<exists>t. (s,t) \\<in> M\"\n\nconsts apath :: \"state \\<Rightarrow> (nat \\<Rightarrow> state)\"\nprimrec\n\"apath s 0 = s\"\n\"apath s (Suc i) = (SOME t. (apath s i,t) \\<in> M)\"\n\n\n\ndefinition pcons :: \"state \\<Rightarrow> (nat \\<Rightarrow> state) \\<Rightarrow> (nat \\<Rightarrow> state)\" where\n\"pcons s p == \\<lambda>i. case i of 0 \\<Rightarrow> s | Suc j \\<Rightarrow> p j\"\n\nlemma pcons_PathI: \"[| (s,t) : M; p \\<in> Paths t |] ==> pcons s p \\<in> Paths s\";\nby(simp add: Paths_def pcons_def split: nat.split);\n\nlemma \"lfp(eufix A B) \\<subseteq> eusem A B\"\napply(rule lfp_lowerbound)\napply(clarsimp simp add: eusem_def eufix_def);\napply(erule disjE);\n apply(rule_tac x = \"apath x\" in bexI);\n  apply(rule_tac x = 0 in exI);\n  apply simp;\n apply simp;\napply(clarify);\napply(rule_tac x = \"pcons xb p\" in bexI);\n apply(rule_tac x = \"j+1\" in exI);\n apply (simp add: pcons_def split: nat.split);\napply (simp add: pcons_PathI)\ndone\n*)\n(*>*)\n\ntext\\<open>Let us close this section with a few words about the executability of\nour model checkers.  It is clear that if all sets are finite, they can be\nrepresented as lists and the usual set operations are easily\nimplemented. Only \\<^const>\\<open>lfp\\<close> requires a little thought.  Fortunately, theory\n\\<open>While_Combinator\\<close> in the Library~\\<^cite>\\<open>\"HOL-Library\"\\<close> provides a\ntheorem stating that in the case of finite sets and a monotone\nfunction~\\<^term>\\<open>F\\<close>, the value of \\mbox{\\<^term>\\<open>lfp F\\<close>} can be computed by\niterated application of \\<^term>\\<open>F\\<close> to~\\<^term>\\<open>{}\\<close> until a fixed point is\nreached. It is actually possible to generate executable functional programs\nfrom HOL definitions, but that is beyond the scope of the tutorial.%\n\\index{CTL|)}\\<close>\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/CTL/CTL.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8670357735451835, "lm_q2_score": 0.8333246035907933, "lm_q1q2_score": 0.7225222422885769}}
{"text": "theory ProductMachine\nimports FSM\n\nbegin\n\n\nsubsection \\<open>Product Machine\\<close>\n\nfun product_transitions :: \"'a FSM \\<Rightarrow> 'b FSM \\<Rightarrow> ('a \\<times> 'b) Transition list\" where\n  \"product_transitions A B = map (\\<lambda> (t1,t2). ((t_source t1, t_source t2),t_input t1,t_output t1,(t_target t1,t_target t2))) (filter (\\<lambda> (t1,t2) . t_input t1 = t_input t2 \\<and> t_output t1 = t_output t2) (cartesian_product_list (wf_transitions A) (wf_transitions B)))\"\n\n\nvalue \"product_transitions M_ex M_ex'\"\n\n\n\n\n\n    \n\nlemma product_transitions_alt1 : \"set (product_transitions A B) = {((t_source t1, t_source t2),t_input t1,t_output t1,(t_target t1, t_target t2)) | t1 t2 . (t1,t2) \\<in> set (cartesian_product_list (wf_transitions A) (wf_transitions B)) \\<and> t_input t1 = t_input t2 \\<and> t_output t1 = t_output t2}\"\nproof \n  show \"set (product_transitions A B) \\<subseteq> {((t_source t1, t_source t2),t_input t1,t_output t1,(t_target t1, t_target t2)) | t1 t2 . (t1,t2) \\<in> set (cartesian_product_list (wf_transitions A) (wf_transitions B)) \\<and> t_input t1 = t_input t2 \\<and> t_output t1 = t_output t2}\"\n  proof \n    fix x assume \"x \\<in> set (product_transitions A B)\"\n    then obtain t1 t2 where \"x = ((t_source t1, t_source t2),t_input t1,t_output t1,(t_target t1,t_target t2))\"\n                        and \"t_input t1 = t_input t2 \\<and> t_output t1 = t_output t2\"\n                        and \"(t1,t2) \\<in> set (cartesian_product_list (wf_transitions A) (wf_transitions B))\"\n      by force\n    then show \"x \\<in> {((t_source t1, t_source t2),t_input t1,t_output t1,(t_target t1, t_target t2)) | t1 t2 . (t1,t2) \\<in> set (cartesian_product_list (wf_transitions A) (wf_transitions B)) \\<and> t_input t1 = t_input t2 \\<and> t_output t1 = t_output t2}\" by blast\n  qed\n\n  show \"{((t_source t1, t_source t2),t_input t1,t_output t1,(t_target t1, t_target t2)) | t1 t2 . (t1,t2) \\<in> set (cartesian_product_list (wf_transitions A) (wf_transitions B)) \\<and> t_input t1 = t_input t2 \\<and> t_output t1 = t_output t2} \\<subseteq> set (product_transitions A B)\"\n    by force\nqed\n\nlemma product_transitions_alt2 : \"set (product_transitions A B) = {((t_source t1, t_source t2),t_input t1,t_output t1,(t_target t1, t_target t2)) | t1 t2 . t1 \\<in> set (wf_transitions A) \\<and> t2 \\<in> set (wf_transitions B) \\<and> t_input t1 = t_input t2 \\<and> t_output t1 = t_output t2}\"\n(is \"?P = ?A2\")\nproof -\n  have \"?P = {((t_source t1, t_source t2),t_input t1,t_output t1,(t_target t1, t_target t2)) | t1 t2 . (t1,t2) \\<in> set (cartesian_product_list (wf_transitions A) (wf_transitions B)) \\<and> t_input t1 = t_input t2 \\<and> t_output t1 = t_output t2}\"\n    using product_transitions_alt1 by assumption\n  also have \"... = ?A2\" by force\n  finally show ?thesis by auto\nqed\n\nlemma product_transitions_alt3 : \"set (product_transitions A B) = {((q1,q2),x,y,(q1',q2')) | q1 q2 x y q1' q2' . (q1,x,y,q1') \\<in> set (wf_transitions A) \\<and> (q2,x,y,q2') \\<in> set (wf_transitions B)}\"\n(is \"?P = ?A3\")\nproof -\n  have \"?P = {((t_source t1, t_source t2),t_input t1,t_output t1,(t_target t1, t_target t2)) | t1 t2 . t1 \\<in> set (wf_transitions A) \\<and> t2 \\<in> set (wf_transitions B) \\<and> t_input t1 = t_input t2 \\<and> t_output t1 = t_output t2}\"\n    using product_transitions_alt2 by assumption\n  also have \"... = ?A3\" by force\n  finally show ?thesis by simp\nqed\n\n\nfun product :: \"'a FSM \\<Rightarrow> 'b FSM \\<Rightarrow> ('a \\<times> 'b) FSM\" where\n  \"product A B =\n  \\<lparr>\n    initial = (initial A, initial B),\n    inputs = (inputs A) @ (inputs B),\n    outputs = (outputs A) @ (outputs B),\n    transitions = product_transitions A B,\n    \\<dots> = FSM.more A    \n  \\<rparr>\"\n\n\nvalue \"product M_ex M_ex'\"\n\nabbreviation(input) \"left_path p \\<equiv> map (\\<lambda>t. (fst (t_source t), t_input t, t_output t, fst (t_target t))) p\"\nabbreviation(input) \"right_path p \\<equiv> map (\\<lambda>t. (snd (t_source t), t_input t, t_output t, snd (t_target t))) p\"\nabbreviation(input) \"zip_path p1 p2 \\<equiv> (map (\\<lambda> t . ((t_source (fst t), t_source (snd t)), t_input (fst t), t_output (fst t), (t_target (fst t), t_target (snd t)))) (zip p1 p2))\"\n\n\nlemma product_simps[simp]:\n  \"initial (product A B) = (initial A, initial B)\"  \n  \"inputs (product A B) = inputs A @ inputs B\"\n  \"outputs (product A B) = outputs A @ outputs B\"\n  \"transitions (product A B) = product_transitions A B\"\nunfolding product_def by simp+\n\n\n\n\nlemma product_transitions_io_valid :\n  \"set (product_transitions A B) = hIO (product A B)\"\nproof -\n  have \"\\<And> t . t \\<in> set (product_transitions A B) \\<Longrightarrow> t \\<in> hIO (product A B)\"\n  proof -\n    fix t assume *: \"t \\<in> set (product_transitions A B)\"\n    then obtain t1 t2 where \"t = ((t_source t1, t_source t2), t_input t1, t_output t1, t_target t1, t_target t2)\"\n                        and \"t1 \\<in> h A \\<and> t2 \\<in> h B \\<and> t_input t1 = t_input t2 \\<and> t_output t1 = t_output t2\"\n      using product_transitions_alt2[of A B] by blast\n    then have \"is_io_valid_transition (product A B) t\"\n      by auto\n    then show \"t \\<in> hIO (product A B)\" using *\n      by (metis io_valid_transition_simp product_simps(4))\n  qed\n  moreover have \"\\<And> t . t \\<in> hIO (product A B) \\<Longrightarrow>  t \\<in> set (product_transitions A B)\"\n    by (metis io_valid_transition_simp product_simps(4))\n  ultimately show ?thesis by blast\nqed\n  \n\nlemma product_transition_hIO :\n  \"((q1,q2),x,y,(q1',q2')) \\<in> hIO (product A B) \\<longleftrightarrow> (q1,x,y,q1') \\<in> h A \\<and> (q2,x,y,q2') \\<in> h B\"\n  using product_transitions_io_valid[of A B] product_transitions_alt3[of A B] by blast\n\n\n\n\n\nlemma zip_path_last : \"length xs = length ys \\<Longrightarrow> (zip_path (xs @ [x]) (ys @ [y])) = (zip_path xs ys)@(zip_path [x] [y])\"\n  by (induction xs ys rule: list_induct2; simp)\n\nlemma product_path_from_paths :\n  assumes \"path A (initial A) p1\"\n      and \"path B (initial B) p2\"\n      and \"p_io p1 = p_io p2\"\n    shows \"path (product A B) (initial (product A B)) (zip_path p1 p2)\"\n      and \"target (zip_path p1 p2) (initial (product A B)) = (target p1 (initial A), target p2 (initial B))\"\nproof -\n  have \"initial (product A B) = (initial A, initial B)\" by auto\n  then have \"(initial A, initial B) \\<in> nodes (product A B)\"\n    by (metis nodes.initial) \n\n  have \"length p1 = length p2\" using assms(3)\n    using map_eq_imp_length_eq by blast \n  then have c: \"path (product A B) (initial (product A B)) (zip_path p1 p2) \\<and> target (zip_path p1 p2) (initial (product A B)) = (target p1 (initial A), target p2 (initial B))\"\n    using assms proof (induction p1 p2 rule: rev_induct2)\n    case Nil\n    \n    then have \"path (product A B) (initial (product A B)) (zip_path [] [])\" \n      using \\<open>initial (product A B) = (initial A, initial B)\\<close> \\<open>(initial A, initial B) \\<in> nodes (product A B)\\<close>\n      by (metis Nil_is_map_conv path.nil zip_Nil)\n    moreover have \"target (zip_path [] []) (initial (product A B)) = (target [] (initial A), target [] (initial B))\"\n      using \\<open>initial (product A B) = (initial A, initial B)\\<close> by auto\n    ultimately show ?case by fast\n  next\n    case (snoc x xs y ys)\n    \n    have \"path A (initial A) xs\" using snoc.prems(1) by auto\n    moreover have \"path B (initial B) ys\" using snoc.prems(2) by auto\n    moreover have \"p_io xs = p_io ys\" using snoc.prems(3) by auto\n    ultimately have *:\"path (product A B) (initial (product A B)) (zip_path xs ys)\" \n                and **:\"target (zip_path xs ys) (initial (product A B)) = (target xs (initial A), target ys (initial B))\" \n      using snoc.IH by blast+\n    then have \"(target xs (initial A), target ys (initial B)) \\<in> nodes (product A B)\"\n      by (metis (no_types, lifting) path_target_is_node)\n    then have \"(t_source x, t_source y) \\<in> nodes (product A B)\"\n      using snoc.prems(1-2)  by (metis path_cons_elim path_suffix) \n\n    have \"x \\<in> h A\" using snoc.prems(1) by auto\n    moreover have \"y \\<in> h B\" using snoc.prems(2) by auto\n    moreover have \"t_input x = t_input y\" using snoc.prems(3) by auto\n    moreover have \"t_output x = t_output y\" using snoc.prems(3) by auto\n    ultimately have \"((t_source x, t_source y), t_input x, t_output x, (t_target x, t_target y)) \\<in> hIO (product A B)\"\n    proof -\n      have f1: \"{((t_source p, t_source pa), t_input p, t_output p, t_target p, t_target pa) | p pa. p \\<in> set (wf_transitions A) \\<and> pa \\<in> set (wf_transitions B) \\<and> t_input p = t_input pa \\<and> t_output p = t_output pa} = set (io_valid_transitions (product A B))\"\n        using product_transitions_alt2[of A B] product_transitions_io_valid by blast\n      have \"\\<exists>p pa. ((t_source x, t_source y), t_input x, t_output x, t_target x, t_target y) = ((t_source p, t_source pa), t_input p, t_output p, t_target p, t_target pa) \\<and> p \\<in> set (wf_transitions A) \\<and> pa \\<in> set (wf_transitions B) \\<and> t_input p = t_input pa \\<and> t_output p = t_output pa\"\n        using \\<open>t_input x = t_input y\\<close> \\<open>t_output x = t_output y\\<close> \\<open>x \\<in> set (wf_transitions A)\\<close> \\<open>y \\<in> set (wf_transitions B)\\<close> by blast\n      then show ?thesis\n        using f1 by blast\n    qed \n    \n    moreover have \"t_source x = target xs (initial A)\" using snoc.prems(1) by auto\n    moreover have \"t_source y = target ys (initial B)\" using snoc.prems(2) by auto\n    ultimately have \"((target xs (initial A), target ys (initial B)), t_input x, t_output x, (t_target x, t_target y)) \\<in> h (product A B)\"\n      using \\<open>(t_source x, t_source y) \\<in> nodes (product A B)\\<close>\n      by (metis fst_conv io_valid_transition_simp wf_transition_simp)\n    then have ***: \"path (product A B) (initial (product A B)) ((zip_path xs ys)@[((target xs (initial A), target ys (initial B)), t_input x, t_output x, (t_target x, t_target y))])\"\n      using * **\n      by (metis (no_types, lifting) fst_conv path_append_last)    \n\n    have \"t_target x = target (xs@[x]) (initial A)\" by auto\n    moreover have \"t_target y = target (ys@[y]) (initial B)\" by auto\n    ultimately have ****: \"target ((zip_path xs ys)@[((target xs (initial A), target ys (initial B)), t_input x, t_output x, (t_target x, t_target y))]) (initial (product A B)) = (target (xs@[x]) (initial A), target (ys@[y]) (initial B))\"\n      by fastforce\n\n\n    have \"(zip_path [x] [y]) = [((target xs (initial A), target ys (initial B)), t_input x, t_output x, (t_target x, t_target y))]\"\n      using \\<open>t_source x = target xs (initial A)\\<close> \\<open>t_source y = target ys (initial B)\\<close> by auto\n    moreover have \"(zip_path (xs @ [x]) (ys @ [y])) = (zip_path xs ys)@(zip_path [x] [y])\"\n      using zip_path_last[of xs ys x y, OF snoc.hyps]  by assumption\n    ultimately have *****:\"(zip_path (xs@[x]) (ys@[y])) = (zip_path xs ys)@[((target xs (initial A), target ys (initial B)), t_input x, t_output x, (t_target x, t_target y))]\"\n      by auto\n    then have \"path (product A B) (initial (product A B)) (zip_path (xs@[x]) (ys@[y]))\"\n      using *** by presburger \n    moreover have \"target (zip_path (xs@[x]) (ys@[y])) (initial (product A B)) = (target (xs@[x]) (initial A), target (ys@[y]) (initial B))\"\n      using **** ***** by auto\n    ultimately show ?case by linarith\n  qed\n\n  from c show \"path (product A B) (initial (product A B)) (zip_path p1 p2)\" by auto\n  from c show \"target (zip_path p1 p2) (initial (product A B)) = (target p1 (initial A), target p2 (initial B))\" by auto\nqed\n\n\nlemma product_transitions_elem :\n  assumes \"t \\<in> set (product_transitions A B)\"\n  shows \"(fst (t_source t), t_input t, t_output t, fst (t_target t)) \\<in> h A\"\n    and \"(snd (t_source t), t_input t, t_output t, snd (t_target t)) \\<in> h B\"\nproof -\n  obtain t1 t2 where *:   \"t = ((t_source t1, t_source t2), t_input t1, t_output t1, t_target t1, t_target t2)\" \n                 and **:  \"t1 \\<in> h A\"\n                 and ***: \"t2 \\<in> h B\"\n                 and ****: \"t_input t1 = t_input t2 \\<and> t_output t1 = t_output t2\"\n    using assms product_transitions_alt2[of A B] by blast\n \n  from * ** show \"(fst (t_source t), t_input t, t_output t, fst (t_target t)) \\<in> h A\" by auto\n  from * *** **** show \"(snd (t_source t), t_input t, t_output t, snd (t_target t)) \\<in> h B\" by auto\nqed\n\n\nlemma paths_from_product_path :\n  assumes \"path (product A B) (initial (product A B)) p\"\n  shows   \"path A (initial A) (left_path p)\"\n      and \"path B (initial B) (right_path p)\"\n      and \"target (left_path p) (initial A) = fst (target p (initial (product A B)))\"\n      and \"target (right_path p) (initial B) = snd (target p (initial (product A B)))\"\nproof -\n  have \"path A (initial A) (left_path p)\n            \\<and> path B (initial B) (right_path p)\n            \\<and> target (left_path p) (initial A) = fst (target p (initial (product A B)))\n            \\<and> target (right_path p) (initial B) = snd (target p (initial (product A B)))\"\n  using assms proof (induction p rule: rev_induct)\n    case Nil\n    then show ?case by auto\n  next\n    case (snoc t p)\n    then have \"path (product A B) (initial (product A B)) p\" by fast\n    then have \"path A (initial A) (left_path p)\"\n      and \"path B (initial B) (right_path p)\"\n      and \"target (left_path p) (initial A) = fst (target p (initial (product A B)))\"\n      and \"target (right_path p) (initial B) = snd (target p (initial (product A B)))\" \n      using snoc.IH  by fastforce+\n\n    then have \"t_source t = (target (left_path p) (initial A), target (right_path p) (initial B))\"\n      using snoc.prems by (metis (no_types, lifting) path_cons_elim path_suffix prod.collapse) \n\n\n    have ***: \"target (left_path (p@[t])) (initial A) = fst (target (p@[t]) (initial (product A B)))\"\n      by fastforce\n    have ****: \"target (right_path (p@[t])) (initial B) = snd (target (p@[t]) (initial (product A B)))\"\n      by fastforce\n\n    have \"t \\<in> h (product A B)\" using snoc.prems\n      by (meson path_cons_elim path_suffix wf_transition_simp) \n    then have \"t \\<in> set (product_transitions A B)\" \n      using product_transitions_io_valid[of A B]\n      by (metis io_valid_transition_simp wf_transition_simp) \n    \n    have \"(fst (t_source t), t_input t, t_output t, fst (t_target t)) \\<in> h A\"\n      using product_transitions_elem[OF \\<open>t \\<in> set (product_transitions A B)\\<close>] by simp\n    moreover have \"target (left_path p) (initial A) = fst (t_source t)\"\n      using \\<open>t_source t = (target (left_path p) (initial A), target (right_path p) (initial B))\\<close> by auto\n    ultimately have \"path A (initial A) ((left_path p)@[(fst (t_source t), t_input t, t_output t, fst (t_target t))])\"\n      by (simp add: \\<open>path A (initial A) (map (\\<lambda>t. (fst (t_source t), t_input t, t_output t, fst (t_target t))) p)\\<close> path_append_last)\n    then have *: \"path A (initial A) (left_path (p@[t]))\" by auto\n\n    have \"(snd (t_source t), t_input t, t_output t, snd (t_target t)) \\<in> h B\"\n      using product_transitions_elem[OF \\<open>t \\<in> set (product_transitions A B)\\<close>] by simp\n    moreover have \"target (right_path p) (initial B) = snd (t_source t)\"\n      using \\<open>t_source t = (target (left_path p) (initial A), target (right_path p) (initial B))\\<close> by auto\n    ultimately have \"path B (initial B) ((right_path p)@[(snd (t_source t), t_input t, t_output t, snd (t_target t))])\"\n      by (simp add: \\<open>path B (initial B) (map (\\<lambda>t. (snd (t_source t), t_input t, t_output t, snd (t_target t))) p)\\<close> path_append_last)\n    then have **: \"path B (initial B) (right_path (p@[t]))\" by auto\n\n\n    show ?case using * ** *** **** by blast\n  qed\n\n  then show \"path A (initial A) (left_path p)\"\n      and \"path B (initial B) (right_path p)\"\n      and \"target (left_path p) (initial A) = fst (target p (initial (product A B)))\"\n      and \"target (right_path p) (initial B) = snd (target p (initial (product A B)))\" by linarith+\nqed\n\n  \n\n\n\nlemma product_transition :\n  \"((q1,q2),x,y,(q1',q2')) \\<in> h (product A B) \\<longleftrightarrow> (q1,x,y,q1') \\<in> h A \\<and> (q2,x,y,q2') \\<in> h B \\<and> (\\<exists> p1 p2 . path A (initial A) p1 \\<and> path B (initial B) p2 \\<and> target p1 (initial A) = q1 \\<and> target p2 (initial B) = q2 \\<and> p_io p1 = p_io p2)\"\nproof \n  show \"((q1,q2),x,y,(q1',q2')) \\<in> h (product A B) \\<Longrightarrow> (q1,x,y,q1') \\<in> h A \\<and> (q2,x,y,q2') \\<in> h B \\<and> (\\<exists> p1 p2 . path A (initial A) p1 \\<and> path B (initial B) p2 \\<and> target p1 (initial A) = q1 \\<and> target p2 (initial B) = q2 \\<and> p_io p1 = p_io p2)\"\n  proof -\n    assume \"((q1,q2),x,y,(q1',q2')) \\<in> h (product A B)\"\n    then have \"(q1,q2) \\<in> nodes (product A B)\"\n      by (metis fst_conv wf_transition_simp) \n    then obtain p where \"path (product A B) (initial (product A B)) p\" and \"target p (initial (product A B)) = (q1,q2)\"\n      by (metis path_to_node)\n\n    have \"path A (initial A) (left_path p) \\<and> path B (initial B) (right_path p) \\<and> target (left_path p) (initial A) = q1 \\<and> target (right_path p) (initial B) = q2\"\n      using paths_from_product_path[OF \\<open>path (product A B) (initial (product A B)) p\\<close>] \\<open>target p (initial (product A B)) = (q1,q2)\\<close> by auto\n    moreover have \"p_io (left_path p) = p_io (right_path p)\" by auto\n    ultimately have \"(\\<exists> p1 p2 . path A (initial A) p1 \\<and> path B (initial B) p2 \\<and> target p1 (initial A) = q1 \\<and> target p2 (initial B) = q2 \\<and> p_io p1 = p_io p2)\"\n      by blast\n    moreover have \"(q1,x,y,q1') \\<in> h A \\<and> (q2,x,y,q2') \\<in> h B\"\n      using \\<open>((q1,q2),x,y,(q1',q2')) \\<in> h (product A B)\\<close>\n      by (metis product_simps(4) product_transition_hIO product_transitions_io_valid wf_transition_simp)\n    ultimately show ?thesis by simp\n  qed\n\n  show \"(q1,x,y,q1') \\<in> h A \\<and> (q2,x,y,q2') \\<in> h B \\<and> (\\<exists> p1 p2 . path A (initial A) p1 \\<and> path B (initial B) p2 \\<and> target p1 (initial A) = q1 \\<and> target p2 (initial B) = q2 \\<and> p_io p1 = p_io p2) \\<Longrightarrow> ((q1,q2),x,y,(q1',q2')) \\<in> h (product A B)\"\n  proof -\n    assume assm: \"(q1,x,y,q1') \\<in> h A \\<and> (q2,x,y,q2') \\<in> h B \\<and> (\\<exists> p1 p2 . path A (initial A) p1 \\<and> path B (initial B) p2 \\<and> target p1 (initial A) = q1 \\<and> target p2 (initial B) = q2 \\<and> p_io p1 = p_io p2)\"\n    then obtain p1 p2 where pr1: \"path A (initial A) p1\" \n                        and pr2: \"path B (initial B) p2\" \n                        and pr3: \"target p1 (initial A) = q1\" \n                        and pr4: \"target p2 (initial B) = q2\" \n                        and pr5: \"p_io p1 = p_io p2\"\n      by blast\n\n    have \"(q1,x,y,q1') \\<in> h A\" and \"(q2,x,y,q2') \\<in> h B\"\n      using assm by auto\n\n    have \"initial (product A B) \\<in> nodes (product A B)\"\n      by blast \n    moreover have \"path (product A B) (initial (product A B)) (zip_path p1 p2)\"\n      using product_path_from_paths(1)[OF pr1 pr2 pr5] by assumption\n    moreover have \"target (zip_path p1 p2) (initial (product A B)) = (q1,q2)\"\n      using product_path_from_paths(2)[OF pr1 pr2 pr5] pr3 pr4 by fast\n    ultimately have \"(q1,q2) \\<in> nodes (product A B)\" \n      using nodes_path[of \"product A B\" \"initial (product A B)\" \"zip_path p1 p2\"] by metis\n    then have \"t_source ((q1,q2),x,y,(q1',q2')) \\<in> nodes (product A B)\"\n      by auto\n\n    moreover have \"((q1,q2),x,y,(q1',q2')) \\<in> hIO (product A B)\"\n      using product_transitions_alt3[of A B] \\<open>(q1,x,y,q1') \\<in> h A\\<close> \\<open>(q2,x,y,q2') \\<in> h B\\<close> by force\n    ultimately show \"((q1,q2),x,y,(q1',q2')) \\<in> h (product A B)\" \n      using hIO_alt_def[of \"product A B\"] h_alt_def[of \"product A B\"] by blast\n  qed\nqed\n\nlemma product_transition_t :\n  \"t \\<in> h (product A B) \\<longleftrightarrow> (fst (t_source t),t_input t,t_output t,fst (t_target t)) \\<in> h A \\<and> (snd (t_source t), t_input t, t_output t, snd (t_target t)) \\<in> h B \\<and> (\\<exists> p1 p2 . path A (initial A) p1 \\<and> path B (initial B) p2 \\<and> target p1 (initial A) = fst (t_source t) \\<and> target p2 (initial B) = snd (t_source t) \\<and> p_io p1 = p_io p2)\"\nproof -\n  have \"t = ((fst (t_source t), snd (t_source t)), t_input t, t_output t, fst (t_target t), snd (t_target t))\"\n    by auto\n  then show ?thesis\n    using product_transition[of \"fst (t_source t)\" \"snd (t_source t)\" \"t_input t\" \"t_output t\" \"fst (t_target t)\" \"snd (t_target t)\" A B] by presburger\nqed\n\nlemma product_transition_from_transitions :\n  assumes \"t1 \\<in> h A\" \n      and \"t2 \\<in> h B\" \n      and \"t_input t1 = t_input t2\" \n      and \"t_output t1 = t_output t2\" \n      and \"(\\<exists> p1 p2 . path A (initial A) p1 \\<and> path B (initial B) p2 \\<and> target p1 (initial A) = t_source t1 \\<and> target p2 (initial B) = t_source t2 \\<and> p_io p1 = p_io p2)\"\n  shows \"((t_source t1,t_source t2),t_input t1,t_output t1,(t_target t1,t_target t2)) \\<in> h (product A B)  \"\nproof-\n  note product_transition[of \"t_source t1\" \"t_source t2\" \"t_input t1\" \"t_output t1\" \"t_target t1\" \"t_target t2\" A B]\n  moreover have \"(t_source t1, t_input t1, t_output t1, t_target t1) \\<in> set (wf_transitions A)\"\n    using assms(1) by auto\n  moreover have \"(t_source t2, t_input t1, t_output t1, t_target t2) \\<in> set (wf_transitions B)\"\n    using assms(2-4) by auto\n  moreover note assms(5)\n  ultimately show ?thesis by presburger\nqed\n \n\n\nlemma product_node_from_path :\n  \"(q1,q2) \\<in> nodes (product A B) \\<longleftrightarrow> (\\<exists> p1 p2 . path A (initial A) p1 \\<and> path B (initial B) p2 \\<and> target p1 (initial A) = q1 \\<and> target p2 (initial B) = q2 \\<and> p_io p1 = p_io p2)\"\nproof \n  show \"(q1,q2) \\<in> nodes (product A B) \\<Longrightarrow> (\\<exists> p1 p2 . path A (initial A) p1 \\<and> path B (initial B) p2 \\<and> target p1 (initial A) = q1 \\<and> target p2 (initial B) = q2 \\<and> p_io p1 = p_io p2)\"\n  proof -\n    assume \"(q1,q2) \\<in> nodes (product A B)\"\n    then obtain p where \"path (product A B) (initial (product A B)) p\" and \"target p (initial (product A B)) = (q1,q2)\"\n      by (metis path_to_node) \n    then have \"path A (initial A) (left_path p) \\<and> path B (initial B) (right_path p) \\<and> target (left_path p) (initial A) = q1 \\<and> target (right_path p) (initial B) = q2 \\<and> p_io (left_path p) = p_io (right_path p)\"\n      using paths_from_product_path[OF \\<open>path (product A B) (initial (product A B)) p\\<close>] by simp\n    then show \"(\\<exists> p1 p2 . path A (initial A) p1 \\<and> path B (initial B) p2 \\<and> target p1 (initial A) = q1 \\<and> target p2 (initial B) = q2 \\<and> p_io p1 = p_io p2)\"\n      by blast\n  qed\n\n  show \"(\\<exists> p1 p2 . path A (initial A) p1 \\<and> path B (initial B) p2 \\<and> target p1 (initial A) = q1 \\<and> target p2 (initial B) = q2 \\<and> p_io p1 = p_io p2) \\<Longrightarrow> (q1,q2) \\<in> nodes (product A B)\"\n  proof -\n    assume \"(\\<exists> p1 p2 . path A (initial A) p1 \\<and> path B (initial B) p2 \\<and> target p1 (initial A) = q1 \\<and> target p2 (initial B) = q2 \\<and> p_io p1 = p_io p2)\"\n    then obtain p1 p2 where *: \"path A (initial A) p1 \\<and> path B (initial B) p2 \\<and> target p1 (initial A) = q1 \\<and> target p2 (initial B) = q2 \\<and> p_io p1 = p_io p2\"\n      by blast\n\n    have \"initial (product A B) \\<in> nodes (product A B)\"\n      by blast \n    moreover have \"path (product A B) (initial (product A B)) (zip_path p1 p2)\"\n      using product_path_from_paths(1)[of A p1 B p2] * by metis\n    moreover have \"target (zip_path p1 p2) (initial (product A B)) = (q1,q2)\"\n      using product_path_from_paths(2)[of A p1 B p2] * by metis\n    ultimately show \"(q1,q2) \\<in> nodes (product A B)\" \n      using nodes_path[of \"product A B\" \"initial (product A B)\" \"zip_path p1 p2\"] by metis\n  qed\nqed\n\n\nlemma left_path_zip : \"length p1 = length p2 \\<Longrightarrow> left_path (zip_path p1 p2) = p1\" \n  by (induction p1 p2 rule: list_induct2; simp)\n\nlemma right_path_zip : \"length p1 = length p2 \\<Longrightarrow> p_io p1 = p_io p2 \\<Longrightarrow> right_path (zip_path p1 p2) = p2\" \n  by (induction p1 p2 rule: list_induct2; simp)\n\nlemma zip_path_append_left_right : \"length p1 = length p2 \\<Longrightarrow> zip_path (p1@(left_path p)) (p2@(right_path p)) = (zip_path p1 p2)@p\"\nproof (induction p1 p2 rule: list_induct2)\n  case Nil\n  then show ?case by (induction p; simp)\nnext\n  case (Cons x xs y ys)\n  then show ?case by simp\nqed\n  \n    \n      \n\nlemma product_path:\n  \"path (product A B) (q1,q2) p \\<longleftrightarrow> (path A q1 (left_path p) \\<and> path B q2 (right_path p) \\<and> (\\<exists> p1 p2 . path A (initial A) p1 \\<and> path B (initial B) p2 \\<and> target p1 (initial A) = q1 \\<and> target p2 (initial B) = q2 \\<and> p_io p1 = p_io p2))\"\nproof \n  show \"path (product A B) (q1,q2) p \\<Longrightarrow> (path A q1 (left_path p) \\<and> path B q2 (right_path p) \\<and> (\\<exists> p1 p2 . path A (initial A) p1 \\<and> path B (initial B) p2 \\<and> target p1 (initial A) = q1 \\<and> target p2 (initial B) = q2 \\<and> p_io p1 = p_io p2))\"\n  proof -\n    assume \"path (product A B) (q1,q2) p\"\n    then have \"(q1,q2) \\<in> nodes (product A B)\"\n      by (meson path_begin_node) \n    then have ex12: \"(\\<exists> p1 p2 . path A (initial A) p1 \\<and> path B (initial B) p2 \\<and> target p1 (initial A) = q1 \\<and> target p2 (initial B) = q2 \\<and> p_io p1 = p_io p2)\"\n      using product_node_from_path[of q1 q2 A B] by blast\n    then obtain p1 p2 where *: \"path A (initial A) p1 \\<and> path B (initial B) p2 \\<and> target p1 (initial A) = q1 \\<and> target p2 (initial B) = q2 \\<and> p_io p1 = p_io p2\"\n      by blast\n    then have \"path (product A B) (initial (product A B)) (zip_path p1 p2)\" \n      using product_path_from_paths(1)[of A p1 B p2] by metis\n\n    have \"path A (initial A) p1\" and \"path B (initial B) p2\" and \"target p1 (initial A) = q1\" and \"target p2 (initial B) = q2\" and \"p_io p1 = p_io p2\"\n      using * by linarith+\n\n    have \"target (zip_path p1 p2) (initial (product A B)) = (q1,q2)\"\n      using product_path_from_paths(2)[of A p1 B p2] * by metis\n\n    have \"path (product A B) (initial (product A B)) ((zip_path p1 p2) @ p)\" \n      using path_append[OF \\<open>path (product A B) (initial (product A B)) (zip_path p1 p2)\\<close>, of p]\n            \\<open>target (zip_path p1 p2) (initial (product A B)) = (q1,q2)\\<close>\n            \\<open>path (product A B) (q1,q2) p\\<close> by metis\n\n    have \"path A (initial A) (left_path ((zip_path p1 p2) @ p))\"\n      and \"path B (initial B) (right_path ((zip_path p1 p2) @ p))\"\n      and \"target (left_path ((zip_path p1 p2) @ p)) (initial A) = fst (target ((zip_path p1 p2) @ p) (initial (product A B)))\"\n      and \"target (right_path ((zip_path p1 p2) @ p)) (initial B) = snd (target ((zip_path p1 p2) @ p) (initial (product A B)))\"\n      using paths_from_product_path[OF \\<open>path (product A B) (initial (product A B)) ((zip_path p1 p2) @ p)\\<close>] by linarith+\n\n    have \"length p1 = length p2\"\n      using \\<open>p_io p1 = p_io p2\\<close> map_eq_imp_length_eq by blast \n\n    have \"(left_path ((zip_path p1 p2) @ p)) = p1@(left_path p)\"\n      using left_path_zip[OF \\<open>length p1 = length p2\\<close>] by (induction p; simp)\n    then have \"path A (initial A) (p1@(left_path p))\"\n      using \\<open>path A (initial A) (left_path ((zip_path p1 p2) @ p))\\<close> by simp\n    have lp: \"path A q1 (left_path p)\" \n      using path_suffix[OF \\<open>path A (initial A) (p1@(left_path p))\\<close>] \\<open>target p1 (initial A) = q1\\<close> by simp\n\n    \n    have \"(right_path ((zip_path p1 p2) @ p)) = p2@(right_path p)\"\n      using right_path_zip[OF \\<open>length p1 = length p2\\<close> \\<open>p_io p1 = p_io p2\\<close>] by (induction p; simp)  \n    then have \"path B (initial B) (p2@(right_path p))\"\n      using \\<open>path B (initial B) (right_path ((zip_path p1 p2) @ p))\\<close> by simp\n    have rp: \"path B q2 (right_path p)\" \n      using path_suffix[OF \\<open>path B (initial B) (p2@(right_path p))\\<close>] \\<open>target p2 (initial B) = q2\\<close> by simp  \n\n    show \"(path A q1 (left_path p) \\<and> path B q2 (right_path p) \\<and> (\\<exists> p1 p2 . path A (initial A) p1 \\<and> path B (initial B) p2 \\<and> target p1 (initial A) = q1 \\<and> target p2 (initial B) = q2 \\<and> p_io p1 = p_io p2))\"\n      using lp rp ex12 by simp\n  qed\n\n\n  show \"(path A q1 (left_path p) \\<and> path B q2 (right_path p) \\<and> (\\<exists> p1 p2 . path A (initial A) p1 \\<and> path B (initial B) p2 \\<and> target p1 (initial A) = q1 \\<and> target p2 (initial B) = q2 \\<and> p_io p1 = p_io p2)) \\<Longrightarrow> path (product A B) (q1,q2) p\"\n  proof-\n    assume \"(path A q1 (left_path p) \\<and> path B q2 (right_path p) \\<and> (\\<exists> p1 p2 . path A (initial A) p1 \\<and> path B (initial B) p2 \\<and> target p1 (initial A) = q1 \\<and> target p2 (initial B) = q2 \\<and> p_io p1 = p_io p2))\"\n    then have \"path A q1 (left_path p)\" and \"path B q2 (right_path p)\" and \"(\\<exists> p1 p2 . path A (initial A) p1 \\<and> path B (initial B) p2 \\<and> target p1 (initial A) = q1 \\<and> target p2 (initial B) = q2 \\<and> p_io p1 = p_io p2)\"\n      by auto\n    then obtain p1 p2 where *: \"path A (initial A) p1\" and \"path B (initial B) p2\" and \"target p1 (initial A) = q1\" and \"target p2 (initial B) = q2\" and \"p_io p1 = p_io p2\"\n      by blast \n\n    have \"path A (initial A) (p1@(left_path p))\"\n      using path_append[OF \\<open>path A (initial A) p1\\<close>, of \"left_path p\"] \\<open>target p1 (initial A) = q1\\<close> \\<open>path A q1 (left_path p)\\<close> by metis\n    have \"path B (initial B) (p2@(right_path p))\"\n      using path_append[OF \\<open>path B (initial B) p2\\<close>, of \"right_path p\"] \\<open>target p2 (initial B) = q2\\<close> \\<open>path B q2 (right_path p)\\<close> by metis\n    have \"p_io (p1@(left_path p)) = p_io (p2@(right_path p))\"\n      using \\<open>p_io p1 = p_io p2\\<close> by (induction p; simp)\n    \n    have \"path (product A B) (initial (product A B)) ((zip_path p1 p2)@p)\"\n      using product_path_from_paths(1)[OF \\<open>path A (initial A) (p1@(left_path p))\\<close> \\<open>path B (initial B) (p2@(right_path p))\\<close> \\<open>p_io (p1@(left_path p)) = p_io (p2@(right_path p))\\<close>]\n            zip_path_append_left_right[of p1 p2 p]\n      by (metis (no_types, lifting) \\<open>p_io p1 = p_io p2\\<close> map_eq_imp_length_eq) \n\n    have \"path (product A B) (initial (product A B)) (zip_path p1 p2)\"\n      using product_path_from_paths(1)[OF \\<open>path A (initial A) p1\\<close> \\<open>path B (initial B) p2\\<close> \\<open>p_io p1 = p_io p2\\<close>] by metis\n    moreover have \"target (zip_path p1 p2) (initial (product A B)) = (q1,q2)\"\n      using product_path_from_paths(2)[OF \\<open>path A (initial A) p1\\<close> \\<open>path B (initial B) p2\\<close> \\<open>p_io p1 = p_io p2\\<close>] \\<open>target p1 (initial A) = q1\\<close> \\<open>target p2 (initial B) = q2\\<close> by metis\n    \n    \n    ultimately show \"path (product A B) (q1,q2) p\"\n      using path_suffix[OF \\<open>path (product A B) (initial (product A B)) ((zip_path p1 p2)@p)\\<close>]\n      by presburger \n  qed\nqed\n    \n      \n\n\n\n\n\n\n\n\n\n\n\n\nlemma product_path_rev:\n  assumes \"p_io p1 = p_io p2\"\n  shows \"path (product A B) (q1,q2) (zip_path p1 p2)\n          \\<longleftrightarrow> (path A q1 p1 \\<and> path B q2 p2 \\<and> (\\<exists> p1 p2 . path A (initial A) p1 \\<and> path B (initial B) p2 \\<and> target p1 (initial A) = q1 \\<and> target p2 (initial B) = q2 \\<and> p_io p1 = p_io p2))\"\nproof -\n  have \"length p1 = length p2\" using assms\n    using map_eq_imp_length_eq by blast \n  then have \"(map (\\<lambda> t . (fst (t_source t), t_input t, t_output t, fst (t_target t))) (map (\\<lambda> t . ((t_source (fst t), t_source (snd t)), t_input (fst t), t_output (fst t), (t_target (fst t), t_target (snd t)))) (zip p1 p2))) = p1\"\n    by (induction p1 p2 arbitrary: q1 q2 rule: list_induct2; auto)\n\n  moreover have \"(map (\\<lambda> t . (snd (t_source t), t_input t, t_output t, snd (t_target t))) (map (\\<lambda> t . ((t_source (fst t), t_source (snd t)), t_input (fst t), t_output (fst t), (t_target (fst t), t_target (snd t)))) (zip p1 p2))) = p2\"\n    using \\<open>length p1 = length p2\\<close> assms by (induction p1 p2 arbitrary: q1 q2 rule: list_induct2; auto)\n\n  ultimately show ?thesis using product_path[of A B q1 q2 \"(map (\\<lambda> t . ((t_source (fst t), t_source (snd t)), t_input (fst t), t_output (fst t), (t_target (fst t), t_target (snd t)))) (zip p1 p2))\"]\n    by auto\nqed\n    \n    \n\n\n\n\n\n\nlemma product_language_state : \n  assumes \"(\\<exists> p1 p2 . path A (initial A) p1 \\<and> path B (initial B) p2 \\<and> target p1 (initial A) = q1 \\<and> target p2 (initial B) = q2 \\<and> p_io p1 = p_io p2)\"\n  shows \"LS (product A B) (q1,q2) = LS A q1 \\<inter> LS B q2\"\nproof \n  show \"LS (product A B) (q1, q2) \\<subseteq> LS A q1 \\<inter> LS B q2\"\n  proof \n    fix io assume \"io \\<in> LS (product A B) (q1, q2)\"\n    then obtain p where \"io = p_io p\" \n                    and \"path (product A B) (q1,q2) p\"\n      by auto\n    then obtain p1 p2 where \"path A q1 p1\" \n                        and \"path B q2 p2\"\n                        and \"io = p_io p1\" \n                        and \"io = p_io p2\"\n      using product_path[of A B q1 q2 p] by fastforce\n    then show \"io \\<in> LS A q1 \\<inter> LS B q2\" \n      unfolding LS.simps by blast\n  qed\n\n  show \"LS A q1 \\<inter> LS B q2 \\<subseteq> LS (product A B) (q1, q2)\"\n  proof\n    fix io assume \"io \\<in> LS A q1 \\<inter> LS B q2\"\n    then obtain p1 p2 where \"path A q1 p1\" \n                        and \"path B q2 p2\"\n                        and \"io = p_io p1\" \n                        and \"io = p_io p2\"\n                        and \"p_io p1 = p_io p2\"\n      by auto\n\n    let ?p = \"zip_path p1 p2\"\n    \n    \n    have \"length p1 = length p2\"\n      using \\<open>p_io p1 = p_io p2\\<close> map_eq_imp_length_eq by blast \n    moreover have \"p_io ?p = p_io (map fst (zip p1 p2))\" by auto\n    ultimately have \"p_io ?p = p_io p1\" by auto\n\n    then have \"p_io ?p = io\" \n      using \\<open>io = p_io p1\\<close> by auto\n    moreover have \"path (product A B) (q1, q2) ?p\"\n      using product_path_rev[OF \\<open>p_io p1 = p_io p2\\<close>, of A B q1 q2] \\<open>path A q1 p1\\<close> \\<open>path B q2 p2\\<close> assms by auto\n    ultimately show \"io \\<in> LS (product A B) (q1, q2)\" \n      unfolding LS.simps by blast\n  qed\nqed\n\n\nlemma product_language : \"L (product A B) = L A \\<inter> L B\"\nproof -\n  have \"path A (initial A) [] \\<and>\n         path B (initial B) [] \\<and>\n         target [] (initial A) = initial A \\<and> target [] (initial B) = initial B \\<and> p_io [] = p_io []\" by auto\n  then have \"\\<exists>p1 p2.\n       path A (initial A) p1 \\<and>\n       path B (initial B) p2 \\<and>\n       target p1 (initial A) = initial A \\<and> target p2 (initial B) = initial B \\<and> p_io p1 = p_io p2\" by blast\n  then show ?thesis\n    using product_language_state[of A B \"initial A\" \"initial B\"] unfolding product.simps by simp\nqed\n\nlemma product_nodes : \"nodes (product A B) \\<subseteq> (nodes A) \\<times> (nodes B)\"\nproof \n  fix q assume \"q \\<in> nodes (product A B)\"\n  then obtain p where \"path (product A B) (initial (product A B)) p\"\n                and   \"q = target p (initial (product A B))\" \n    by (metis path_to_node)\n\n  let ?p1 = \"left_path p\"\n  let ?p2 = \"right_path p\"\n\n  have \"path A (initial A) ?p1 \\<and> path B (initial B) ?p2\"\n    by (metis \\<open>path (product A B) (initial (product A B)) p\\<close> product_path[of A B \"initial A\" \"initial B\" p] product_simps(1))\n\n  moreover have \"target p (initial (product A B)) = (target ?p1 (initial A), target ?p2 (initial B))\"\n    by (induction p; force)  \n\n  ultimately show \"q \\<in> (nodes A) \\<times> (nodes B)\"\n    by (metis (no_types, lifting) SigmaI \\<open>q = target p (initial (product A B))\\<close> nodes_path_initial)\nqed\n\nlemma product_transition_split_ob :\n  assumes \"t \\<in> h (product A B)\"\n  obtains t1 t2 \n  where \"t1 \\<in> h A \\<and> t_source t1 = fst (t_source t) \\<and> t_input t1 = t_input t \\<and> t_output t1 = t_output t \\<and> t_target t1 = fst (t_target t)\"\n    and \"t2 \\<in> h B \\<and> t_source t2 = snd (t_source t) \\<and> t_input t2 = t_input t \\<and> t_output t2 = t_output t \\<and> t_target t2 = snd (t_target t)\"      \nproof -\n  have \"t \\<in> set (transitions (product A B))\"\n    using assms by blast\n  \n  then have \"t \\<in> set (map (\\<lambda>(t1, t2).\n                      ((t_source t1, t_source t2), t_input t1, t_output t1, t_target t1, t_target t2))\n               (filter (\\<lambda>(t1, t2). t_input t1 = t_input t2 \\<and> t_output t1 = t_output t2)\n                 (cartesian_product_list (wf_transitions A) (wf_transitions B))))\"\n    by (metis product_simps(4) product_transitions.elims) \n\n  then obtain t1 t2 where \"t = ((t_source t1, t_source t2),t_input t1,t_output t1,(t_target t1,t_target t2))\"\n                 and \"(t1,t2) \\<in> set (filter (\\<lambda>(t1, t2). t_input t1 = t_input t2 \\<and> t_output t1 = t_output t2)\n                                      (cartesian_product_list (wf_transitions A) (wf_transitions B)))\"\n    by (metis (no_types, lifting) case_prod_beta' imageE prod.collapse set_map)\n\n  then have *: \"t_source t2 = snd (t_source t) \\<and> t_input t2 = t_input t \\<and> t_output t2 = t_output t \\<and> t_target t2 = snd (t_target t)\" \n    by auto\n  have **: \"t_source t1 = fst (t_source t) \\<and> t_input t1 = t_input t \\<and> t_output t1 = t_output t \\<and> t_target t1 = fst (t_target t)\"\n    by (simp add: \\<open>t = ((t_source t1, t_source t2), t_input t1, t_output t1, t_target t1, t_target t2)\\<close>)\n\n  have \"(t1,t2) \\<in> h A \\<times> h B\"\n    using \\<open>(t1,t2) \\<in> set (filter (\\<lambda>(t1, t2). t_input t1 = t_input t2 \\<and> t_output t1 = t_output t2) (cartesian_product_list (wf_transitions A) (wf_transitions B)))\\<close> cartesian_product_list_set[of \"(wf_transitions A)\" \"(wf_transitions B)\"] by auto\n  then have \"t1 \\<in> h A\" and \"t2 \\<in> h B\" by auto\n\n  have \"t1 \\<in> h A \\<and> t_source t1 = fst (t_source t) \\<and> t_input t1 = t_input t \\<and> t_output t1 = t_output t \\<and> t_target t1 = fst (t_target t)\"\n   and \"t2 \\<in> h B \\<and> t_source t2 = snd (t_source t) \\<and> t_input t2 = t_input t \\<and> t_output t2 = t_output t \\<and> t_target t2 = snd (t_target t)\" \n    using \\<open>t1 : h A\\<close> * \\<open>t2 \\<in> h B\\<close> ** by auto\n\n  then show ?thesis\n    using that by blast \nqed\n\nlemma product_transition_split :\n  assumes \"t \\<in> h (product A B)\"\n  shows \"(fst (t_source t), t_input t, t_output t, fst (t_target t)) \\<in> h A\"\n    and \"(snd (t_source t), t_input t, t_output t, snd (t_target t)) \\<in> h B\"      \n  using product_transition_split_ob[OF assms] prod.collapse by metis+\n\n\n\nsubsection \\<open>Other Lemmata\\<close>\n\nlemma  product_target_split:\n  assumes \"target p (q1,q2) = (q1',q2')\"\n  shows \"target (left_path p) q1 = q1'\"\n    and \"target (right_path p) q2 = q2'\"\nusing assms by (induction p arbitrary: q1 q2; force)+\n\n\n\n\n\nlemma h_from_paths :\n  assumes \"\\<And> p . path A (initial A) p = path B (initial B) p\"\n  shows \"h A = h B\"\nproof (rule ccontr)\n  assume \"h A \\<noteq> h B\"\n  then consider  \"(\\<exists> tA \\<in> h A . tA \\<notin> h B)\" | \"(\\<exists> tB \\<in> h B . tB \\<notin> h A)\" by blast\n  then show \"False\" proof (cases)\n    case 1\n    then obtain tA where \"tA \\<in> h A\" and \"tA \\<notin> h B\" by blast\n    then have \"t_source tA \\<in> nodes A\" by auto\n    then obtain p where \"path A (initial A) p\" and \"target p (initial A) = t_source tA\" \n      using path_to_node by metis\n    then have \"path A (initial A) (p@[tA])\" using path_append_last \\<open>tA \\<in> h A\\<close> by metis\n    moreover have \"\\<not> path B (initial B) (p@[tA])\" using \\<open>tA \\<notin> h B\\<close> by auto\n    ultimately show \"False\" using assms by metis\n  next\n    case 2\n    then obtain tB where \"tB \\<in> h B\" and \"tB \\<notin> h A\" by blast\n    then have \"t_source tB \\<in> nodes B\" by auto\n    then obtain p where \"path B (initial B) p\" and \"target p (initial B) = t_source tB\" \n      using path_to_node by metis\n    then have \"path B (initial B) (p@[tB])\" using path_append_last \\<open>tB \\<in> h B\\<close> by metis\n    moreover have \"\\<not> path A (initial A) (p@[tB])\" using \\<open>tB \\<notin> h A\\<close> by auto\n    ultimately show \"False\" using assms by metis\n  qed\nqed\n\n\n\n\nlemma single_transitions_path : \n  assumes \"(q,x,y,q') \\<in> h M\" \n  shows \"path M q [(q,x,y,q')]\" \n  using  path.cons[OF assms path.nil[OF wf_transition_target[OF assms]]] by auto\n\nlemma product_from_next :\n  assumes \"((q1,q2),x,y,(q1',q2')) \\<in> h (product (from_FSM M q1) (from_FSM M q2))\"\n  shows \"h (product (from_FSM M q1') (from_FSM M q2')) = h (from_FSM (product (from_FSM M q1) (from_FSM M q2)) (q1', q2'))\"\nproof -\n  let ?t = \"((q1,q2),x,y,(q1',q2'))\"\n\n\n  have \"(q1',q2') \\<in> nodes (product (from_FSM M q1) (from_FSM M q2))\"\n    using wf_transition_target[OF assms] by simp\n  then have \"q1' \\<in> nodes (from_FSM M q1)\" and \"q2' \\<in> nodes (from_FSM M q2)\"\n    using product_nodes[of \"from_FSM M q1\" \"from_FSM M q2\"] by blast+\n\n  have \"(q1,x,y,q1') \\<in> h (from_FSM M q1)\" and \"(q2,x,y,q2') \\<in> h (from_FSM M q2)\"\n    using product_transition_split[OF assms] by auto\n\n  have s1 : \"initial (product (from_FSM M q1') (from_FSM M q2')) = (q1',q2')\"\n    by auto\n  have s2 : \"initial (from_FSM (product (from_FSM M q1) (from_FSM M q2)) (q1', q2')) = (q1',q2')\"\n    by auto\n\n\n  have *: \"\\<And> p . path (product (from_FSM M q1') (from_FSM M q2')) (q1',q2') p = path (from_FSM (product (from_FSM M q1) (from_FSM M q2)) (q1', q2')) (q1',q2') p\"\n  proof -\n    fix p show \"path (product (from_FSM M q1') (from_FSM M q2')) (q1',q2') p = path (from_FSM (product (from_FSM M q1) (from_FSM M q2)) (q1', q2')) (q1',q2') p\"\n    proof  \n      show \"path (product (from_FSM M q1') (from_FSM M q2')) (q1', q2') p \\<Longrightarrow>\n              path (from_FSM (product (from_FSM M q1) (from_FSM M q2)) (q1', q2')) (q1', q2') p\"\n      proof -\n        assume \"path (product (from_FSM M q1') (from_FSM M q2')) (q1', q2') p\"\n        then have \"path (from_FSM M q1') q1' (left_path p)\" and \"path (from_FSM M q2') q2' (right_path p)\"\n          using product_path[of \"from_FSM M q1'\" \"from_FSM M q2'\" q1' q2' p] by linarith+\n\n        have \"path (from_FSM M q1) q1' (left_path p)\"\n          using from_FSM_path[OF \\<open>q1' \\<in> nodes (from_FSM M q1)\\<close>, of q1' \"left_path p\"] \\<open>path (from_FSM M q1') q1' (left_path p)\\<close> by auto\n        have \"path (from_FSM M q2) q2' (right_path p)\"\n          using from_FSM_path[OF \\<open>q2' \\<in> nodes (from_FSM M q2)\\<close>, of q2' \"right_path p\"] \\<open>path (from_FSM M q2') q2' (right_path p)\\<close> by auto\n\n        have p3: \"(\\<exists>p1 p2.\n                         path (from_FSM M q1) (initial (from_FSM M q1)) p1 \\<and>\n                         path (from_FSM M q2) (initial (from_FSM M q2)) p2 \\<and>\n                         target p1 (initial (from_FSM M q1)) = q1' \\<and>\n                         target p2 (initial (from_FSM M q2)) = q2' \\<and> p_io p1 = p_io p2)\" \n        proof -\n          have \"path (from_FSM M q1) (initial (from_FSM M q1)) [(q1, x, y, q1')]\"\n            using single_transitions_path[OF \\<open>(q1,x,y,q1') \\<in> h (from_FSM M q1)\\<close>] by auto\n          moreover have \"path (from_FSM M q2) (initial (from_FSM M q2)) [(q2, x, y, q2')]\"\n            using single_transitions_path[OF \\<open>(q2,x,y,q2') \\<in> h (from_FSM M q2)\\<close>] by auto\n          moreover have \"(target [(q1,x,y,q1')] (initial (from_FSM M q1)) = q1' \\<and>\n                          target [(q2,x,y,q2')] (initial (from_FSM M q2)) = q2' \\<and> \n                          p_io [(q1,x,y,q1')] = p_io [(q2,x,y,q2')])\" \n            by auto\n          ultimately show ?thesis by meson\n        qed\n        \n        have \"path (product (from_FSM M q1) (from_FSM M q2)) (q1',q2') p\"\n          using product_path[of \"from_FSM M q1\" \"from_FSM M q2\" q1' q2' p] \\<open>path (from_FSM M q1) q1' (left_path p)\\<close> \\<open>path (from_FSM M q2) q2' (right_path p)\\<close> p3 by presburger\n\n        then show \"path (from_FSM (product (from_FSM M q1) (from_FSM M q2)) (q1', q2')) (q1',q2') p\"\n          using from_FSM_path_rev_initial by metis\n      qed\n      show \"path (from_FSM (product (from_FSM M q1) (from_FSM M q2)) (q1', q2')) (q1', q2') p \\<Longrightarrow>\n              path (product (from_FSM M q1') (from_FSM M q2')) (q1', q2') p\"\n      proof -\n        assume \"path (from_FSM (product (from_FSM M q1) (from_FSM M q2)) (q1', q2')) (q1', q2') p\"\n        then have \"path (product (from_FSM M q1) (from_FSM M q2)) (q1',q2') p\"\n          using from_FSM_path[OF \\<open>(q1',q2') \\<in> nodes (product (from_FSM M q1) (from_FSM M q2))\\<close>] by metis\n        then have \"path (from_FSM M q1) q1' (left_path p)\" \n              and \"path (from_FSM M q2) q2' (right_path p)\"\n              and \"(\\<exists>p1 p2.\n                     path (from_FSM M q1) (initial (from_FSM M q1)) p1 \\<and>\n                     path (from_FSM M q2) (initial (from_FSM M q2)) p2 \\<and>\n                     target p1 (initial (from_FSM M q1)) = q1' \\<and>\n                     target p2 (initial (from_FSM M q2)) = q2' \\<and> p_io p1 = p_io p2)\"\n          using product_path[of \"from_FSM M q1\" \"from_FSM M q2\" q1' q2' p] by presburger+\n\n        have \"path (from_FSM M q1') q1' (left_path p)\"\n          using from_FSM_path_rev_initial[OF \\<open>path (from_FSM M q1) q1' (left_path p)\\<close>] by auto\n        moreover have \"path (from_FSM M q2') q2' (right_path p)\"\n          using from_FSM_path_rev_initial[OF \\<open>path (from_FSM M q2) q2' (right_path p)\\<close>] by auto\n        moreover have p3: \"(\\<exists>p1 p2.\n                         path (from_FSM M q1') (initial (from_FSM M q1')) p1 \\<and>\n                         path (from_FSM M q2') (initial (from_FSM M q2')) p2 \\<and>\n                         target p1 (initial (from_FSM M q1')) = q1' \\<and>\n                         target p2 (initial (from_FSM M q2')) = q2' \\<and> p_io p1 = p_io p2)\" \n        proof -\n          have \"path (from_FSM M q1') (initial (from_FSM M q1')) []\" \n            using path.nil[OF nodes.initial] by metis\n          moreover have \"path (from_FSM M q2') (initial (from_FSM M q2')) []\"\n            using path.nil[OF nodes.initial] by metis\n          moreover have \"(target [] (initial (from_FSM M q1')) = q1' \\<and>\n                          target [] (initial (from_FSM M q2')) = q2' \\<and> \n                          p_io [] = p_io [])\" \n            by auto\n          ultimately show ?thesis by blast\n        qed\n        \n        ultimately show \" path (product (from_FSM M q1') (from_FSM M q2')) (q1', q2') p\"\n          using product_path[of \"from_FSM M q1'\" \"from_FSM M q2'\" q1' q2' p] by presburger        \n      qed\n    qed\n  qed\n\n  show ?thesis using * h_from_paths s1 s2 by metis\nqed\n   \n\nlemma submachine_transition_product_from :\n  assumes \"is_submachine S (product (from_FSM M q1) (from_FSM M q2))\"\n      and \"((q1,q2),x,y,(q1',q2')) \\<in> h S\"\n shows \"is_submachine (from_FSM S (q1',q2')) (product (from_FSM M q1') (from_FSM M q2'))\"\nproof -\n  have \"((q1,q2),x,y,(q1',q2')) \\<in> h (product (from_FSM M q1) (from_FSM M q2))\"\n    using submachine_h[OF assms(1)] assms(2) by blast\n  have \"(q1',q2') \\<in> nodes S\" using wf_transition_target[OF assms(2)] by auto \n  show ?thesis \n    using product_from_next[OF \\<open>((q1,q2),x,y,(q1',q2')) \\<in> h (product (from_FSM M q1) (from_FSM M q2))\\<close>]\n          submachine_from[OF assms(1) \\<open>(q1',q2') \\<in> nodes S\\<close>]\n  proof -\n    have \"initial (from_FSM S (q1', q2')) = initial (from_FSM (product (from_FSM M q1) (from_FSM M q2)) (q1', q2')) \\<and> set (wf_transitions (from_FSM S (q1', q2'))) \\<subseteq> set (wf_transitions (from_FSM (product (from_FSM M q1) (from_FSM M q2)) (q1', q2'))) \\<and> inputs (from_FSM S (q1', q2')) = inputs (from_FSM (product (from_FSM M q1) (from_FSM M q2)) (q1', q2')) \\<and> outputs (from_FSM S (q1', q2')) = outputs (from_FSM (product (from_FSM M q1) (from_FSM M q2)) (q1', q2'))\"\n      using \\<open>is_submachine (from_FSM S (q1', q2')) (from_FSM (product (from_FSM M q1) (from_FSM M q2)) (q1', q2'))\\<close> is_submachine.simps by blast\n    then show ?thesis\n      by (metis (no_types) \\<open>set (wf_transitions (product (from_FSM M q1') (from_FSM M q2'))) = set (wf_transitions (from_FSM (product (from_FSM M q1) (from_FSM M q2)) (q1', q2')))\\<close> from_FSM_simps(1) from_FSM_simps(2) from_FSM_simps(3) is_submachine.simps product_simps(1) product_simps(2) product_simps(3))\n  qed\nqed\n\nlemma submachine_transition_complete_product_from :\n  assumes \"is_submachine S (product (from_FSM M q1) (from_FSM M q2))\"\n      and \"completely_specified S\"\n      and \"((q1,q2),x,y,(q1',q2')) \\<in> h S\"\n shows \"completely_specified (from_FSM S (q1',q2'))\"\nproof -\n  let ?P = \"(product (from_FSM M q1) (from_FSM M q2))\"\n  let ?P' = \"(product (from_FSM M q1') (from_FSM M q2'))\"\n  let ?F = \"(from_FSM S (q1',q2'))\"  \n  \n  have \"initial ?P = (q1,q2)\"\n    by auto\n  then have \"initial S = (q1,q2)\" \n    using assms(1) by (metis is_submachine.simps) \n  then have \"(q1',q2') \\<in> nodes S\"\n    using assms(3)\n    using wf_transition_target by fastforce \n  then have \"nodes ?F \\<subseteq> nodes S\"\n    using from_FSM_nodes by metis\n  moreover have \"inputs ?F = inputs S\"\n    by auto\n  ultimately show \"completely_specified ?F\" \n    using assms(2) unfolding completely_specified.simps\n    using from_FSM_nodes_transitions[of _ S \"(q1',q2')\"]\n    using contra_subsetD by fastforce\nqed\n\n\nlemma from_FSM_product_inputs :\n  \"set (inputs (product (from_FSM M q1) (from_FSM M q2))) = set (inputs M)\"\n  unfolding product.simps from_FSM.simps by auto\n\nlemma from_FSM_product_outputs :\n  \"set (outputs (product (from_FSM M q1) (from_FSM M q2))) = set (outputs M)\"\n  unfolding product.simps from_FSM.simps by auto\n\nlemma from_FSM_product_initial : \n  \"initial (product (from_FSM M q1) (from_FSM M q2)) = (q1,q2)\" by auto\n\n\n\nlemma product_from_next' :\n  assumes \"t \\<in> h (product (from_FSM M (fst (t_source t))) (from_FSM M (snd (t_source t))))\"\n    shows \"h (from_FSM (product (from_FSM M (fst (t_source t))) (from_FSM M (snd (t_source t)))) (fst (t_target t),snd (t_target t))) = h (product (from_FSM M (fst (t_target t))) (from_FSM M (snd (t_target t))))\"\nproof -\n  have \"t = ((fst (t_source t),snd (t_source t)),t_input t, t_output t,(fst (t_target t),snd (t_target t)))\"\n    by (metis prod.collapse)\n  then have *: \"((fst (t_source t),snd (t_source t)),t_input t, t_output t,(fst (t_target t),snd (t_target t))) \\<in> h (product (from_FSM M (fst (t_source t))) (from_FSM M (snd (t_source t))))\"\n    using assms by presburger\n  \n  show ?thesis using product_from_next[OF *] by blast\nqed\n\n\n\nlemma product_from_next'_path :\n  assumes \"t \\<in> h (product (from_FSM M (fst (t_source t))) (from_FSM M (snd (t_source t))))\"\n  shows \"path (from_FSM (product (from_FSM M (fst (t_source t))) (from_FSM M (snd (t_source t)))) (fst (t_target t),snd (t_target t))) (fst (t_target t),snd (t_target t)) p = path (product (from_FSM M (fst (t_target t))) (from_FSM M (snd (t_target t)))) (fst (t_target t),snd (t_target t)) p\" \n    (is \"path ?P1 ?q p = path ?P2 ?q p\")\nproof -\n  have i1: \"initial ?P1 = ?q\" by auto\n  have i2: \"initial ?P2 = ?q\" by auto\n  have h12: \"h ?P1 = h ?P2\" using product_from_next'[OF assms] by assumption\n  \n  show ?thesis proof (induction p rule: rev_induct)\n    case Nil\n    then show ?case\n      by (metis (full_types) i1 i2 nodes.initial path.nil)\n  next\n    case (snoc t p)\n    show ?case by (meson h12 h_equivalence_path path_begin_node path_prefix snoc.IH)\n  qed\nqed\n\n\nlemma product_from_transition_subset:\n  assumes \"(q1',q2') \\<in> nodes (product (from_FSM M q1) (from_FSM M q2))\" \n  shows \"h (product (from_FSM M q1') (from_FSM M q2')) \\<subseteq> h (product (from_FSM M q1) (from_FSM M q2))\" (is \"h ?P' \\<subseteq> h ?P\")\nproof \n  fix t assume \"t \\<in> h ?P'\"\n  then have \"t_source t \\<in> nodes ?P'\" by (metis wf_transition_simp)\n  then obtain p' where \"path ?P' (initial ?P') p'\" and \"target p' (initial ?P') = t_source t\"\n    by (metis path_to_node)\n\n  have \"path (from_FSM M q1') q1' (left_path p')\"\n       \"path (from_FSM M q2') q2' (right_path p')\"\n       \"(\\<exists>p1 p2.\n           path (from_FSM M q1') (initial (from_FSM M q1')) p1 \\<and>\n           path (from_FSM M q2') (initial (from_FSM M q2')) p2 \\<and>\n           target p1 (initial (from_FSM M q1')) = q1' \\<and> target p2 (initial (from_FSM M q2')) = q2' \\<and> p_io p1 = p_io p2)\"\n    using product_path[of \"from_FSM M q1'\" \"from_FSM M q2'\" q1' q2' p'] \\<open>path ?P' (initial ?P') p'\\<close> by auto\n  \n  have          \"(fst (t_source t), t_input t, t_output t, fst (t_target t)) \\<in> set (wf_transitions (from_FSM M q1'))\"\n       and      \"(snd (t_source t), t_input t, t_output t, snd (t_target t)) \\<in> set (wf_transitions (from_FSM M q2'))\"\n       and p'': \"(\\<exists>p1 p2.\n                   path (from_FSM M q1') (initial (from_FSM M q1')) p1 \\<and>\n                   path (from_FSM M q2') (initial (from_FSM M q2')) p2 \\<and>\n                   target p1 (initial (from_FSM M q1')) = fst (t_source t) \\<and>\n             target p2 (initial (from_FSM M q2')) = snd (t_source t) \\<and> p_io p1 = p_io p2)\"\n    using product_transition_t[of t \"from_FSM M q1'\" \"from_FSM M q2'\"] \\<open>t \\<in> h ?P'\\<close> by presburger+\n\n\n\n  obtain p where \"path ?P (initial ?P) p\" and \"target p (initial ?P) = (q1',q2')\"\n    by (metis assms path_to_node)\n  have \"path (from_FSM M q1) q1 (left_path p)\"\n       \"path (from_FSM M q2) q2 (right_path p)\"\n       \"(\\<exists>p1 p2.\n           path (from_FSM M q1) (initial (from_FSM M q1)) p1 \\<and>\n           path (from_FSM M q2) (initial (from_FSM M q2)) p2 \\<and>\n           target p1 (initial (from_FSM M q1)) = q1 \\<and> target p2 (initial (from_FSM M q2)) = q2 \\<and> p_io p1 = p_io p2)\"\n    using product_path[of \"from_FSM M q1\" \"from_FSM M q2\" q1 q2 p] \\<open>path ?P (initial ?P) p\\<close> by auto\n\n  have \"target (left_path p) q1 = q1'\" and \"target (right_path p) q2 = q2'\"\n    using product_target_split[of p q1 q2 q1' q2'] \\<open>target p (initial ?P) = (q1',q2')\\<close> by auto\n\n  have \"q1' \\<in> nodes (from_FSM M q1)\"\n    using path_target_is_node[OF \\<open>path (from_FSM M q1) q1 (left_path p)\\<close>] \\<open>target (left_path p) q1 = q1'\\<close> by metis\n  have \"h (from_FSM M q1') \\<subseteq> h (from_FSM M q1)\"\n    using from_FSM_h[OF \\<open>q1' \\<in> nodes (from_FSM M q1)\\<close>] by simp\n  then have *: \"(fst (t_source t), t_input t, t_output t, fst (t_target t)) \\<in> h (from_FSM M q1)\"\n    using \\<open>(fst (t_source t), t_input t, t_output t, fst (t_target t)) \\<in> h (from_FSM M q1')\\<close> by blast\n\n  have \"q2' \\<in> nodes (from_FSM M q2)\"\n    using path_target_is_node[OF \\<open>path (from_FSM M q2) q2 (right_path p)\\<close>] \\<open>target (right_path p) q2 = q2'\\<close> by metis\n  have \"h (from_FSM M q2') \\<subseteq> h (from_FSM M q2)\"\n    using from_FSM_h[OF \\<open>q2' \\<in> nodes (from_FSM M q2)\\<close>] by simp\n  then have **: \"(snd (t_source t), t_input t, t_output t, snd (t_target t)) \\<in> h (from_FSM M q2)\"\n    using \\<open>(snd (t_source t), t_input t, t_output t, snd (t_target t)) \\<in> h (from_FSM M q2')\\<close> by blast\n\n  have ***: \"(\\<exists>p1 p2.\n               path (from_FSM M q1) (initial (from_FSM M q1)) p1 \\<and>\n               path (from_FSM M q2) (initial (from_FSM M q2)) p2 \\<and>\n               target p1 (initial (from_FSM M q1)) = fst (t_source t) \\<and>\n               target p2 (initial (from_FSM M q2)) = snd (t_source t) \\<and> p_io p1 = p_io p2)\"\n  proof -\n    obtain p1' p2' where \"path (from_FSM M q1') q1' p1'\"\n                     and \"path (from_FSM M q2') q2' p2'\"\n                     and \"target p1' q1' = fst (t_source t)\"\n                     and \"target p2' q2' = snd (t_source t)\" \n                     and \"p_io p1' = p_io p2'\"\n      using p'' by auto\n\n    have \"path (from_FSM M q1) q1' p1'\"\n      using from_FSM_path \\<open>q1' \\<in> nodes (from_FSM M q1)\\<close> \\<open>path (from_FSM M q1') q1' p1'\\<close> by (metis from_from)\n    have \"path (from_FSM M q2) q2' p2'\"\n      using from_FSM_path \\<open>q2' \\<in> nodes (from_FSM M q2)\\<close> \\<open>path (from_FSM M q2') q2' p2'\\<close> by (metis from_from)\n\n    have \"path (from_FSM M q1) (initial (from_FSM M q1)) ((left_path p)@p1')\" \n      using path_append[OF \\<open>path (from_FSM M q1) q1 (left_path p)\\<close>, of p1']  \\<open>target (left_path p) q1 = q1'\\<close> \\<open>path (from_FSM M q1) q1' p1'\\<close> by auto\n    moreover have \"path (from_FSM M q2) (initial (from_FSM M q2)) ((right_path p)@p2')\" \n      using path_append[OF \\<open>path (from_FSM M q2) q2 (right_path p)\\<close>, of p2']  \\<open>target (right_path p) q2 = q2'\\<close> \\<open>path (from_FSM M q2) q2' p2'\\<close> by auto\n    moreover have \"target ((left_path p)@p1') (initial (from_FSM M q1)) = fst (t_source t)\"\n      using path_target_append[OF \\<open>target (left_path p) q1 = q1'\\<close> \\<open>target p1' q1' = fst (t_source t)\\<close>] by auto\n    moreover have \"target ((right_path p)@p2') (initial (from_FSM M q2)) = snd (t_source t)\"\n      using path_target_append[OF \\<open>target (right_path p) q2 = q2'\\<close> \\<open>target p2' q2' = snd (t_source t)\\<close>] by auto\n    moreover have \"p_io ((left_path p)@p1') = p_io ((right_path p)@p2')\"\n      using \\<open>p_io p1' = p_io p2'\\<close> by auto\n    ultimately show ?thesis by blast\n  qed\n\n  show \"t \\<in> h (product (from_FSM M q1) (from_FSM M q2))\"\n    using product_transition_t[of t \"from_FSM M q1\" \"from_FSM M q2\"] * ** *** by blast\nqed\n\n\n\nlemma product_from_path:\n  assumes \"(q1',q2') \\<in> nodes (product (from_FSM M q1) (from_FSM M q2))\" \n      and \"path (product (from_FSM M q1') (from_FSM M q2')) (q1',q2') p\" \n    shows \"path (product (from_FSM M q1) (from_FSM M q2)) (q1',q2') p\"\nusing h_subset_path[OF product_from_transition_subset[OF assms(1)] assms(2) assms(1)] by assumption\n\n\nlemma product_from_path_previous :\n  assumes \"path (product (from_FSM M (fst (t_target t))) \n                         (from_FSM M (snd (t_target t))))\n                (t_target t) p\"                                           (is \"path ?Pt (t_target t) p\")\n      and \"t \\<in> h (product (from_FSM M q1) (from_FSM M q2))\"\n    shows \"path (product (from_FSM M q1) (from_FSM M q2)) (t_target t) p\" (is \"path ?P (t_target t) p\")\nproof -\n  have *: \"(t_target t) \\<in> nodes (product (from_FSM M q1) (from_FSM M q2))\"\n    using wf_transition_target[OF assms(2)] by (metis)\n  then have **: \"(fst (t_target t), snd (t_target t)) \\<in> nodes (product (from_FSM M q1) (from_FSM M q2))\"\n    by (metis prod.collapse)\n  have ***: \"h ?Pt \\<subseteq> h ?P\" \n    using product_from_transition_subset[OF **] by assumption\n  show ?thesis\n    using h_subset_path[OF *** assms(1) *] by assumption\nqed\n\n\nlemma product_from_transition_shared_node :\n  assumes \"t \\<in> h (product (from_FSM M q1') (from_FSM M q2'))\"\n  and  \"(q1',q2') \\<in> nodes (product (from_FSM M q1) (from_FSM M q2))\" \nshows \"t \\<in> h (product (from_FSM M q1) (from_FSM M q2))\"\n  by (meson assms(1) assms(2) contra_subsetD product_from_transition_subset)\n\n    \n\nlemma product_from_not_completely_specified :\n  assumes \"\\<not> completely_specified_state (product (from_FSM M q1) (from_FSM M q2)) (q1',q2')\"\n      and \"(q1',q2') \\<in> nodes (product (from_FSM M q1) (from_FSM M q2))\"\n    shows  \"\\<not> completely_specified_state (product (from_FSM M q1') (from_FSM M q2')) (q1',q2')\"\n  using assms(1) assms(2) from_FSM_product_inputs[of M q1 q2] from_FSM_product_inputs[of M q1' q2'] product_from_transition_shared_node[OF _ assms(2)] \n  unfolding completely_specified_state.simps by metis\n\nlemma from_product_initial_paths_ex :\n  \"(\\<exists>p1 p2.\n         path (from_FSM M q1) (initial (from_FSM M q1)) p1 \\<and>\n         path (from_FSM M q2) (initial (from_FSM M q2)) p2 \\<and>\n         target p1 (initial (from_FSM M q1)) = q1 \\<and>\n         target p2 (initial (from_FSM M q2)) = q2 \\<and> p_io p1 = p_io p2)\"\nproof -\n  have \"path (from_FSM M q1) (initial (from_FSM M q1)) []\" by blast\n  moreover have \"path (from_FSM M q2) (initial (from_FSM M q2)) []\" by blast\n  moreover have \"\n         target [] (initial (from_FSM M q1)) = q1 \\<and>\n         target [] (initial (from_FSM M q2)) = q2 \\<and> p_io [] = p_io []\" by auto\n  ultimately show ?thesis by blast\nqed\n\n(* TODO: move *)\nlemma product_observable :\n  assumes \"observable M1\"\n  and     \"observable M2\"\nshows \"observable (product M1 M2)\" (is \"observable ?P\")\nproof -\n  have \"\\<And> t1 t2 . t1 \\<in> h ?P \\<Longrightarrow> t2 \\<in> h ?P \\<Longrightarrow> t_source t1 = t_source t2 \\<Longrightarrow> t_input t1 = t_input t2 \\<Longrightarrow> t_output t1 = t_output t2 \\<Longrightarrow> t_target t1 = t_target t2\"\n  proof -\n    fix t1 t2 assume \"t1 \\<in> h ?P\" and \"t2 \\<in> h ?P\" and \"t_source t1 = t_source t2\" and \"t_input t1 = t_input t2\" and \"t_output t1 = t_output t2\"\n\n    let ?t1L = \"(fst (t_source t1), t_input t1, t_output t1, fst (t_target t1))\"\n    let ?t1R = \"(snd (t_source t1), t_input t1, t_output t1, snd (t_target t1))\"\n    let ?t2L = \"(fst (t_source t2), t_input t2, t_output t2, fst (t_target t2))\"\n    let ?t2R = \"(snd (t_source t2), t_input t2, t_output t2, snd (t_target t2))\"\n\n    have \"t_target ?t1L = t_target ?t2L\"\n      using product_transition_split(1)[OF \\<open>t1 \\<in> h ?P\\<close>]\n            product_transition_split(1)[OF \\<open>t2 \\<in> h ?P\\<close>]\n            \\<open>observable M1\\<close> \n            \\<open>t_source t1 = t_source t2\\<close>\n            \\<open>t_input t1 = t_input t2\\<close>\n            \\<open>t_output t1 = t_output t2\\<close> by auto\n    moreover have \"t_target ?t1R = t_target ?t2R\"\n      using product_transition_split(2)[OF \\<open>t1 \\<in> h ?P\\<close>]\n            product_transition_split(2)[OF \\<open>t2 \\<in> h ?P\\<close>]\n            \\<open>observable M2\\<close> \n            \\<open>t_source t1 = t_source t2\\<close>\n            \\<open>t_input t1 = t_input t2\\<close>\n            \\<open>t_output t1 = t_output t2\\<close> by auto\n    ultimately show \"t_target t1 = t_target t2\"\n      by (metis prod.exhaust_sel snd_conv) \n  qed\n  then show ?thesis unfolding observable.simps by blast\nqed\n\n\nlemma product_observable_self_transitions :\n  assumes \"q \\<in> nodes (product M M)\"\n  and     \"observable M\"\nshows \"fst q = snd q\"\nproof -\n  let ?P = \"product M M\"\n  \n\n  have \"\\<And> p . path ?P (initial ?P) p \\<Longrightarrow> fst (target p (initial ?P)) = snd (target p (initial ?P))\"\n  proof -\n    fix p assume \"path ?P (initial ?P) p\"\n    then show \"fst (target p (initial ?P)) = snd (target p (initial ?P))\"\n    proof (induction p rule: rev_induct)\n      case Nil\n      then show ?case\n        by (metis append.right_neutral path_append_target path_nil_elim path_to_node product_simps(1) snd_swap swap_simp) \n    next\n      case (snoc t p)\n\n      have \"path ?P (initial ?P) p\" and \"path ?P (target p (initial ?P)) [t]\"\n        using path_append_elim[of ?P \"initial ?P\" p \"[t]\", OF \\<open>path (product M M) (initial (product M M)) (p @ [t])\\<close>] by blast+\n      then have \"t \\<in> h ?P\" \n        by blast\n      have \"t_source t = target p (initial ?P)\"\n        by (metis \\<open>path (product M M) (target p (initial (product M M))) [t]\\<close> list.distinct(1) list.sel(1) path.simps)\n        \n      let ?t1 = \"(fst (t_source t), t_input t, t_output t, fst (t_target t))\"\n      let ?t2 = \"(snd (t_source t), t_input t, t_output t, snd (t_target t))\"\n      have \"?t1 \\<in> h M\" and \"?t2 \\<in> h M\"\n        using product_transition_split[OF \\<open>t \\<in> h ?P\\<close>] by auto\n      moreover have \"t_source ?t1 = t_source ?t2\" \n        using \\<open>t_source t = target p (initial ?P)\\<close> snoc.IH[OF \\<open>path ?P (initial ?P) p\\<close>]\n        by (metis fst_conv)\n      moreover have \"t_input ?t1 = t_input ?t2\"\n        by auto\n      moreover have \"t_output ?t1 = t_output ?t2\"\n        by auto\n      ultimately have \"t_target ?t1 = t_target ?t2\"\n        using \\<open>observable M\\<close> unfolding observable.simps by blast\n      then have \"fst (t_target t) = snd (t_target t)\"\n        by auto\n      then show ?case unfolding target.simps visited_states.simps\n      proof -\n        show \"fst (last (initial (product M M) # map t_target (p @ [t]))) = snd (last (initial (product M M) # map t_target (p @ [t])))\"\n          using \\<open>fst (t_target t) = snd (t_target t)\\<close> last_map last_snoc length_append_singleton length_map by force\n      qed\n    qed\n  qed\n\n  then show ?thesis\n    by (metis assms(1) path_to_node)\nqed\n\nlemma zip_path_eq_left :\n  assumes \"length xs1 = length xs2\"\n  and     \"length xs2 = length ys1\"\n  and     \"length ys1 = length ys2\"\n  and     \"zip_path xs1 xs2 = zip_path ys1 ys2\"\nshows \"xs1 = ys1\"\n  using assms by (induction xs1 xs2 ys1 ys2 rule: list_induct4; auto)\n\n\n\nlemma zip_path_eq_right :\n  assumes \"length xs1 = length xs2\"\n  and     \"length xs2 = length ys1\"\n  and     \"length ys1 = length ys2\"\n  and     \"p_io xs2 = p_io ys2\"\n  and     \"zip_path xs1 xs2 = zip_path ys1 ys2\"\nshows \"xs2 = ys2\"\n  using assms by (induction xs1 xs2 ys1 ys2 rule: list_induct4; auto)\n\n\n(* TODO: check *)\ndeclare from_FSM.simps[simp del]\ndeclare product.simps[simp del]\ndeclare from_FSM_simps[simp del]\ndeclare product_simps[simp del]\n\n\nlemma zip_path_merge :\n  \"(zip_path (left_path p) (right_path p)) = p\"\n  by (induction p; auto)\n\nlemma product_from_path' :\n  assumes \"path (product (from_FSM M q1) (from_FSM M q2)) (q1', q2') p\"\nshows \"path (product (from_FSM M q1') (from_FSM M q2')) (q1', q2') p\"\n  using assms proof (induction p rule: rev_induct)\n  case Nil\n  show ?case using product_simps(1) from_FSM_simps(1) nodes.initial\n    by (metis nil)\nnext\n  case (snoc t p)\n\n  let ?P' = \"(product (from_FSM M q1') (from_FSM M q2'))\"\n\n  have \"path (from_FSM M q1) q1' (left_path (p@[t]))\" \n       \"path (from_FSM M q2) q2' (right_path (p@[t]))\" \n    using snoc.prems product_path[of \"(from_FSM M q1)\" \"(from_FSM M q2)\" q1' q2' \"p@[t]\"] by simp+\n\n  have \"path (from_FSM M q1') (initial (from_FSM M q1'))  (left_path (p@[t]))\"\n    using from_FSM_path_rev_initial[OF \\<open>path (from_FSM M q1) q1' (left_path (p@[t]))\\<close>] by (simp add: from_FSM_simps)\n  moreover have \"path (from_FSM M q2') (initial (from_FSM M q2')) (right_path (p@[t]))\"\n    using from_FSM_path_rev_initial[OF \\<open>path (from_FSM M q2) q2' (right_path (p@[t]))\\<close>] by (simp add: from_FSM_simps)\n  moreover have \"p_io (left_path (p@[t])) = p_io (right_path (p@[t]))\"\n    by auto\n  ultimately have \"path ?P' (initial ?P') (zip_path (left_path (p@[t])) (right_path (p@[t])))\"\n    using product_path_from_paths(1) by blast\n  then show \"path ?P' (q1',q2') (p@[t])\"\n    by (simp add: product_simps(1) from_FSM_simps(1) zip_path_merge)\nqed\n    \n\n\nlemma from_product_from_h :\n  assumes \"(q1',q2') \\<in> nodes (product (from_FSM M q1) (from_FSM M q2))\"\nshows \"h (product (from_FSM M q1') (from_FSM M q2')) = h (from_FSM (product (from_FSM M q1) (from_FSM M q2)) (q1',q2'))\" \n      (is \"h ?P' = h ?Pf\")\nproof -\n  let ?P = \"(product (from_FSM M q1) (from_FSM M q2))\"\n\n  have \"\\<And> t . t \\<in> h ?P' \\<Longrightarrow> t \\<in> h ?Pf\"\n  proof -\n    fix t assume \"t \\<in> h ?P'\"\n    then have \"t_source t \\<in> nodes ?P'\" by auto\n    then obtain p where \"path ?P' (q1',q2') p\" and \"target p (q1',q2') = t_source t\"\n      using product_simps(1) from_FSM_simps(1)\n      by (metis path_to_node) \n    then have \"path ?P' (q1',q2') (p@[t])\"\n      using \\<open>t \\<in> h ?P'\\<close> \\<open>t_source t \\<in> nodes ?P'\\<close> by auto\n    then have \"path ?P (q1',q2') (p@[t])\" \n      using product_from_path[OF assms] by auto \n    then have \"path ?Pf (q1',q2') (p@[t])\"\n      by (simp add: from_FSM_path_rev_initial)  \n    then show \"t \\<in> h ?Pf\"\n      by auto\n  qed\n  moreover have \"\\<And> t . t \\<in> h ?Pf \\<Longrightarrow> t \\<in> h ?P'\"\n  proof -\n    fix t assume \"t \\<in> h ?Pf\"\n    then have \"t_source t \\<in> nodes ?Pf\" by auto\n    then obtain p where \"path ?Pf (q1',q2') p\" and \"target p (q1',q2') = t_source t\"\n      using from_FSM_simps(1)\n      by (metis path_to_node) \n    then have \"path ?Pf (q1',q2') (p@[t])\"\n      using \\<open>t \\<in> h ?Pf\\<close> \\<open>t_source t \\<in> nodes ?Pf\\<close> by auto\n    then have \"path ?P (q1',q2') (p@[t])\"\n      by (meson assms from_FSM_path) \n    then have \"path ?P' (q1',q2') (p@[t])\"\n      using product_from_path' by metis\n    then show \"t \\<in> h ?P'\"\n      by auto\n  qed\n  ultimately show ?thesis by blast\nqed \n\n\n\n\nlemma product_deadlock :\n  assumes \"\\<not> (\\<exists> t \\<in> h (product (from_FSM M q1) (from_FSM M q2)).\n               t_source t = qq \\<and> t_input t = x)\"\n  and \"qq \\<in> nodes (product (from_FSM M q1) (from_FSM M q2))\"\n  and \"x \\<in> set (inputs M)\"\nshows \"\\<not> (\\<exists> t1 \\<in> h M. \\<exists> t2 \\<in> h M.\n                 t_source t1 = fst qq \\<and>\n                 t_source t2 = snd qq \\<and>\n                 t_input t1 = x \\<and> t_input t2 = x \\<and> t_output t1 = t_output t2)\" \nproof \n  assume \"\\<exists> t1 \\<in> h M. \\<exists> t2 \\<in> h M.\n                 t_source t1 = fst qq \\<and>\n                 t_source t2 = snd qq \\<and>\n                 t_input t1 = x \\<and> t_input t2 = x \\<and> t_output t1 = t_output t2\"\n  then obtain t1 t2 where \"t1 \\<in> h M\"\n                      and \"t2 \\<in> h M\"\n                      and \"t_source t1 = fst qq\"\n                      and \"t_source t2 = snd qq\"\n                      and \"t_input t1 = x\"\n                      and \"t_input t2 = x\" \n                      and \"t_output t1 = t_output t2\"\n    by blast\n\n  have \"fst qq \\<in> nodes (from_FSM M q1)\" and \"snd qq \\<in> nodes (from_FSM M q2)\"\n    using product_nodes assms(2)\n    by fastforce+\n\n \n  have \"t_source t1 \\<in> nodes (from_FSM M q1)\"\n    using \\<open>fst qq \\<in> nodes (from_FSM M q1)\\<close> \\<open>t_source t1 = fst qq\\<close> by simp\n  then have *: \"(fst qq, x, t_output t1, t_target t1) \\<in> h (from_FSM M q1)\"\n    using from_FSM_nodes_transitions[OF \\<open>t1 \\<in> h M\\<close>] \\<open>t_input t1 = x\\<close> \\<open>t_source t1 = fst qq\\<close>\n    by (metis prod.collapse) \n\n  have \"t_source t2 \\<in> nodes (from_FSM M q2)\"\n    using \\<open>snd qq \\<in> nodes (from_FSM M q2)\\<close> \\<open>t_source t2 = snd qq\\<close> by simp\n  have **: \"(snd qq, x, t_output t1, t_target t2) \\<in> h (from_FSM M q2)\"\n    using from_FSM_nodes_transitions[OF \\<open>t2 \\<in> h M\\<close> \\<open>t_source t2 \\<in> nodes (from_FSM M q2)\\<close>] \\<open>t_source t2 = snd qq\\<close> \\<open>t_input t1 = x\\<close> \\<open>t_input t2 = x\\<close> \\<open>t_source t2 = snd qq\\<close> \\<open>t_output t1 = t_output t2\\<close> \n    by (metis prod.collapse)\n\n  have ***: \"(\\<exists>p1 p2.\n        path (from_FSM M q1) (initial (from_FSM M q1)) p1 \\<and>\n        path (from_FSM M q2) (initial (from_FSM M q2)) p2 \\<and>\n        target p1 (initial (from_FSM M q1)) = fst qq \\<and>\n        target p2 (initial (from_FSM M q2)) = snd qq \\<and> p_io p1 = p_io p2)\"\n    using assms(2) product_node_from_path[of \"fst qq\" \"snd qq\" \"from_FSM M q1\" \"from_FSM M q2\"]\n          prod.collapse[of qq] \n    by auto\n  \n  have \"(qq, x, t_output t1, (t_target t1, t_target t2)) \\<in> h (product (from_FSM M q1) (from_FSM M q2))\"\n    using product_transition[of \"fst qq\" \"snd qq\" \"x\" \"t_output t1\" \"t_target t1\" \"t_target t2\" \"from_FSM M q1\" \"from_FSM M q2\"]\n    using * ** *** prod.collapse[of qq] by auto\n  moreover have \"t_source (qq, x, t_output t1, (t_target t1, t_target t2)) = qq\"\n            and \"t_input (qq, x, t_output t1, (t_target t1, t_target t2)) = x\"\n    by auto\n  ultimately show \"False\"\n    using assms(1) by blast\nqed\n\n(* TODO: check *)\ndeclare from_FSM.simps[simp]\ndeclare product.simps[simp]\ndeclare from_FSM_simps[simp]\ndeclare product_simps[simp]\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/ProductMachine.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357598021708, "lm_q2_score": 0.8333246035907933, "lm_q1q2_score": 0.7225222308361863}}
{"text": "(*  Title:     HOL/Inequalities.thy\n    Author:    Tobias Nipkow\n    Author:    Johannes H\u00f6lzl\n*)\n\ntheory Inequalities\n  imports Real_Vector_Spaces\nbegin\n\nlemma Chebyshev_sum_upper:\n  fixes a b::\"nat \\<Rightarrow> 'a::linordered_idom\"\n  assumes \"\\<And>i j. i \\<le> j \\<Longrightarrow> j < n \\<Longrightarrow> a i \\<le> a j\"\n  assumes \"\\<And>i j. i \\<le> j \\<Longrightarrow> j < n \\<Longrightarrow> b i \\<ge> b j\"\n  shows \"of_nat n * (\\<Sum>k=0..<n. a k * b k) \\<le> (\\<Sum>k=0..<n. a k) * (\\<Sum>k=0..<n. b k)\"\nproof -\n  let ?S = \"(\\<Sum>j=0..<n. (\\<Sum>k=0..<n. (a j - a k) * (b j - b k)))\"\n  have \"2 * (of_nat n * (\\<Sum>j=0..<n. (a j * b j)) - (\\<Sum>j=0..<n. b j) * (\\<Sum>k=0..<n. a k)) = ?S\"\n    by (simp only: one_add_one[symmetric] algebra_simps)\n      (simp add: algebra_simps sum_subtractf sum.distrib sum.swap[of \"\\<lambda>i j. a i * b j\"] sum_distrib_left)\n  also\n  { fix i j::nat assume \"i<n\" \"j<n\"\n    hence \"a i - a j \\<le> 0 \\<and> b i - b j \\<ge> 0 \\<or> a i - a j \\<ge> 0 \\<and> b i - b j \\<le> 0\"\n      using assms by (cases \"i \\<le> j\") (auto simp: algebra_simps)\n  } then have \"?S \\<le> 0\"\n    by (auto intro!: sum_nonpos simp: mult_le_0_iff)\n  finally show ?thesis by (simp add: algebra_simps)\nqed\n\nlemma Chebyshev_sum_upper_nat:\n  fixes a b :: \"nat \\<Rightarrow> nat\"\n  shows \"(\\<And>i j. \\<lbrakk> i\\<le>j; j<n \\<rbrakk> \\<Longrightarrow> a i \\<le> a j) \\<Longrightarrow>\n         (\\<And>i j. \\<lbrakk> i\\<le>j; j<n \\<rbrakk> \\<Longrightarrow> b i \\<ge> b j) \\<Longrightarrow>\n    n * (\\<Sum>i=0..<n. a i * b i) \\<le> (\\<Sum>i=0..<n. a i) * (\\<Sum>i=0..<n. b i)\"\nusing Chebyshev_sum_upper[where 'a=real, of n a b]\nby (simp del: of_nat_mult of_nat_sum  add: of_nat_mult[symmetric] of_nat_sum[symmetric])\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/Inequalities.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357666736773, "lm_q2_score": 0.8333245932423308, "lm_q1q2_score": 0.7225222275898946}}
{"text": "theory FiniteListGraph\nimports \n  FiniteGraph\n  \"../../Transitive-Closure/Transitive_Closure_List_Impl\"\nbegin\n\nsection {*Specification of a finite graph, implemented by lists*}\n\ntext{* A graph @{text \"G=(V,E)\"} consits of a list of vertices @{term V}, also called nodes, \n       and a list of edges @{term E}. The edges are tuples of vertices.\n       Using lists instead of sets, code can be easily created. *}\n\n  record 'v list_graph =\n    nodesL :: \"'v list\"\n    edgesL :: \"('v \\<times>'v) list\"\n\ntext{*Correspondence the FiniteGraph*}\n  definition list_graph_to_graph :: \"'v list_graph \\<Rightarrow> 'v graph\" where \n    \"list_graph_to_graph G = \\<lparr> nodes = set (nodesL G), edges = set (edgesL G) \\<rparr>\"\n\n\n  definition wf_list_graph_axioms :: \"'v list_graph \\<Rightarrow> bool\" where\n    \"wf_list_graph_axioms G \\<longleftrightarrow> fst` set (edgesL G) \\<subseteq> set (nodesL G) \\<and> snd` set (edgesL G) \\<subseteq> set (nodesL G)\"\n\n\n  lemma wf_list_graph_iff_wf_graph: \"wf_graph (list_graph_to_graph G) \\<longleftrightarrow> wf_list_graph_axioms G\"\n  unfolding list_graph_to_graph_def wf_graph_def wf_list_graph_axioms_def\n  by simp\n\n  text{*We say a @{typ \"'v list_graph\"} is valid if it fulfills the graph axioms and its lists are distinct*}\n  definition wf_list_graph::\"('v) list_graph \\<Rightarrow> bool\" where\n   \"wf_list_graph G = (distinct (nodesL G) \\<and> distinct (edgesL G) \\<and> wf_list_graph_axioms G)\"\n\n\nsection{*FiniteListGraph operations*}\n\n  text {* Adds a node to a graph. *}\n  definition add_node :: \"'v \\<Rightarrow> 'v list_graph \\<Rightarrow> 'v list_graph\" where \n    \"add_node v G = \\<lparr> nodesL = (if v \\<in> set (nodesL G) then nodesL G else v#nodesL G), edgesL=edgesL G \\<rparr>\"\n\n  text {* Adds an edge to a graph. *}\n  definition add_edge :: \"'v \\<Rightarrow> 'v \\<Rightarrow> 'v list_graph \\<Rightarrow> 'v list_graph\" where \n    \"add_edge v v' G = (add_node v (add_node v' G)) \\<lparr>edgesL := (if (v, v') \\<in> set (edgesL G) then edgesL G else (v, v')#edgesL G) \\<rparr>\"\n\n  text {* Deletes a node from a graph. Also deletes all adjacent edges. *}\n  definition delete_node :: \"'v \\<Rightarrow> 'v list_graph \\<Rightarrow> 'v list_graph\" where \n  \"delete_node v G = \\<lparr> \n    nodesL = remove1 v (nodesL G), edgesL = [(e1,e2) \\<leftarrow> (edgesL G). e1 \\<noteq> v \\<and> e2 \\<noteq> v]\n    \\<rparr>\"\n\n  text {* Deletes an edge from a graph. *}\n  definition delete_edge :: \"'v \\<Rightarrow> 'v \\<Rightarrow> 'v list_graph \\<Rightarrow> 'v list_graph\" where \n    \"delete_edge v v' G = \\<lparr>nodesL = nodesL G, edgesL = [(e1,e2) \\<leftarrow> edgesL G. e1 \\<noteq> v \\<or> e2 \\<noteq> v'] \\<rparr>\"\n\n  \n  fun delete_edges::\"'v list_graph \\<Rightarrow> ('v \\<times> 'v) list \\<Rightarrow> 'v list_graph\" where \n    \"delete_edges G [] = G\"|\n    \"delete_edges G ((v,v')#es) = delete_edges (delete_edge v v' G) es\"\n\n\n\ntext {* extended graph operations *}\n   text {* Reflexive transitive successors of a node. Or: All reachable nodes for v including v. *}\n    definition succ_rtran :: \"'v list_graph \\<Rightarrow> 'v \\<Rightarrow> 'v list\" where\n      \"succ_rtran G v = rtrancl_list_impl (edgesL G) [v]\"\n\n   text {* Transitive successors of a node. Or: All reachable nodes for v. *}\n    definition succ_tran :: \"'v list_graph \\<Rightarrow> 'v \\<Rightarrow> 'v list\" where\n      \"succ_tran G v = trancl_list_impl (edgesL G) [v]\"\n  \n   text {* The number of reachable nodes from v *}\n    definition num_reachable :: \"'v list_graph \\<Rightarrow> 'v \\<Rightarrow> nat\" where\n      \"num_reachable G v = length (succ_tran G v)\"\n\n\n    definition num_reachable_norefl :: \"'v list_graph \\<Rightarrow> 'v \\<Rightarrow> nat\" where\n      \"num_reachable_norefl G v = length ([ x \\<leftarrow> succ_tran G v. x \\<noteq> v])\"\n\n\nsubsection{*undirected graph simulation*}\n  text {* Create undirected graph from directed graph by adding backward links *}\n  fun backlinks :: \"('v \\<times> 'v) list \\<Rightarrow> ('v \\<times> 'v) list\" where\n    \"backlinks [] = []\" |\n    \"backlinks ((e1, e2)#es) = (e2, e1)#(backlinks es)\"\n\n  definition undirected :: \"'v list_graph \\<Rightarrow> 'v list_graph\"\n    where \"undirected G \\<equiv> \\<lparr> nodesL = nodesL G, edgesL = remdups (edgesL G @ backlinks (edgesL G)) \\<rparr>\"\n\nsection{*Correctness lemmata*}\n\n  -- \"add node\"\n  lemma add_node_wf: \"wf_list_graph G \\<Longrightarrow> wf_list_graph (add_node v G)\"\n  unfolding wf_list_graph_def wf_list_graph_axioms_def add_node_def\n  by auto\n\n  lemma add_node_set_nodes: \"set (nodesL (add_node v G)) = set (nodesL G) \\<union> {v}\"\n  unfolding add_node_def\n  by auto\n\n  lemma add_node_set_edges: \"set (edgesL (add_node v G)) = set (edgesL G)\"\n  unfolding add_node_def\n  by auto\n\n  lemma add_node_correct: \"FiniteGraph.add_node v (list_graph_to_graph G) = list_graph_to_graph (add_node v G)\"\n  unfolding FiniteGraph.add_node_def list_graph_to_graph_def\n  by (simp add: add_node_set_edges add_node_set_nodes)\n\n  lemma add_node_wf2: \"wf_graph (list_graph_to_graph G) \\<Longrightarrow> wf_graph (list_graph_to_graph (add_node v G))\"\n  by (subst add_node_correct[symmetric]) simp\n\n  -- \"add edge\"\n  lemma add_edge_wf: \"wf_list_graph G \\<Longrightarrow> wf_list_graph (add_edge v v' G)\"\n  unfolding wf_list_graph_def add_edge_def add_node_def wf_list_graph_axioms_def\n  by auto\n\n  lemma add_edge_set_nodes: \"set (nodesL (add_edge v v' G)) = set (nodesL G) \\<union> {v,v'}\"\n  unfolding add_edge_def add_node_def\n  by auto\n\n  lemma add_edge_set_edges: \"set (edgesL (add_edge v v' G)) = set (edgesL G) \\<union> {(v,v')}\"\n  unfolding add_edge_def add_node_def\n  by auto\n\n  lemma add_edge_correct: \"FiniteGraph.add_edge v v' (list_graph_to_graph G) = list_graph_to_graph (add_edge v v' G)\"\n  unfolding FiniteGraph.add_edge_def add_edge_def list_graph_to_graph_def\n  by (auto simp: add_node_set_nodes)\n\n  lemma add_edge_wf2: \"wf_graph (list_graph_to_graph G) \\<Longrightarrow> wf_graph (list_graph_to_graph (add_edge v v' G))\"\n  by (subst add_edge_correct[symmetric]) simp\n\n  -- \"delete node\"\n  lemma delete_node_wf: \"wf_list_graph G \\<Longrightarrow> wf_list_graph (delete_node v G)\"\n  unfolding wf_list_graph_def delete_node_def wf_list_graph_axioms_def\n  by auto\n\n  lemma delete_node_set_edges:\n    \"set (edgesL (delete_node v G)) = {(a,b). (a, b) \\<in> set (edgesL G) \\<and> a \\<noteq> v \\<and> b \\<noteq> v}\"\n  unfolding delete_node_def\n  by auto\n\n  lemma delete_node_correct:\n    assumes \"wf_list_graph G\"\n    shows \"FiniteGraph.delete_node v (list_graph_to_graph G) = list_graph_to_graph (delete_node v G)\"\n  using assms\n  unfolding FiniteGraph.delete_node_def delete_node_def list_graph_to_graph_def wf_list_graph_def\n  by auto\n\n  -- \"delete edge\"\n  lemma delete_edge_set_nodes: \"set (nodesL (delete_edge v v' G)) = set (nodesL G)\"\n  unfolding delete_edge_def\n  by simp\n\n  lemma delete_edge_set_edges:\n    \"set (edgesL (delete_edge v v' G)) = {(a,b). (a,b) \\<in> set (edgesL G) \\<and> (a,b) \\<noteq> (v,v')}\"\n  unfolding delete_edge_def\n  by auto\n\n  \n\n  lemma delete_edge_wf: \"wf_list_graph G \\<Longrightarrow> wf_list_graph (delete_edge v v' G)\"\n  unfolding wf_list_graph_def delete_edge_def wf_list_graph_axioms_def\n  by auto\n    \n  \n\n  lemma delete_edge_commute: \"delete_edge a1 a2 (delete_edge b1 b2 G) = delete_edge b1 b2 (delete_edge a1 a2 G)\"\n  unfolding delete_edge_def\n  by simp metis (* auto doesn't seem to like filter_cong *)\n\n  lemma delete_edge_correct: \"FiniteGraph.delete_edge v v' (list_graph_to_graph G) = list_graph_to_graph (delete_edge v v' G)\"\n  unfolding FiniteGraph.delete_edge_def delete_edge_def list_graph_to_graph_def\n  by auto\n\n  lemma delete_edge_wf2: \"wf_graph (list_graph_to_graph G) \\<Longrightarrow> wf_graph (list_graph_to_graph (delete_edge v v' G))\"\n  by (subst delete_edge_correct[symmetric]) simp\n\n  -- \"delete edges\"\n  lemma delete_edges_wf: \"wf_list_graph G \\<Longrightarrow> wf_list_graph (delete_edges G E)\"\n  by (induction E arbitrary: G) (auto simp: delete_edge_wf)\n\n  lemma delete_edges_set_nodes: \"set (nodesL (delete_edges G E)) = set (nodesL G)\"\n  by (induction E arbitrary: G) (auto simp: delete_edge_set_nodes)\n\n  lemma delete_edges_nodes: \"nodesL (delete_edges G es) = nodesL G\"\n  by (induction es arbitrary: G) (auto simp: delete_edge_def)\n\n  lemma delete_edges_set_edges: \"set (edgesL (delete_edges G E)) = set (edgesL G) - set E\"\n  by (induction E arbitrary: G) (auto simp: delete_edge_def delete_edge_set_nodes)\n\n  lemma delete_edges_set_edges2:\n    \"set (edgesL (delete_edges G E)) = {(a,b). (a,b) \\<in> set (edgesL G) \\<and> (a,b) \\<notin> set E}\"\n  by (auto simp: delete_edges_set_edges)\n\n  lemma delete_edges_length: \"length (edgesL (delete_edges G f)) \\<le> length (edgesL G)\"\n  proof (induction f arbitrary:G)\n    case (Cons f fs)\n    thus ?case\n      apply (cases f, hypsubst)\n      apply (subst delete_edges.simps(2))\n      apply (metis delete_edge_length le_trans)\n      done\n  qed simp\n\n  lemma delete_edges_chain: \"delete_edges G (as @ bs) = delete_edges (delete_edges G as) bs\"\n  proof (induction as arbitrary: bs G)\n    case (Cons f fs)\n    thus ?case\n      by (cases f) auto\n  qed simp\n\n  lemma delete_edges_delete_edge_commute:\n    \"delete_edges (delete_edge a1 a2 G) as = delete_edge a1 a2 (delete_edges G as)\"\n  proof (induction as arbitrary: G a1 a2)\n    case (Cons f fs)\n    thus ?case\n      by (cases f) (simp add: delete_edge_commute)\n  qed simp\n\n  lemma delete_edges_commute:\n    \"delete_edges (delete_edges G as) bs = delete_edges (delete_edges G bs) as\"\n  proof (induction as arbitrary: bs G)\n    case (Cons f fs)\n    thus ?case\n      by (cases f) (simp add: delete_edges_delete_edge_commute)\n  qed simp\n\n  lemma delete_edges_as_filter:\n    \"delete_edges G l = \\<lparr> nodesL = nodesL G,  edgesL = [x \\<leftarrow> edgesL G. x \\<notin> set l] \\<rparr>\"\n  proof (induction l)\n    case (Cons f fs)\n    thus ?case\n      apply (cases f)\n      apply (simp add: delete_edges_delete_edge_commute)\n      apply (simp add: delete_edge_def)\n      apply (metis (lifting, full_types) prod.exhaust case_prodI split_conv)\n      done\n  qed simp\n\n  declare delete_edges.simps[simp del] (*do not automatically expand definition*)\n\n  lemma delete_edges_correct:\n    \"FiniteGraph.delete_edges (list_graph_to_graph G) (set E) = list_graph_to_graph (delete_edges G E)\"\n  unfolding list_graph_to_graph_def FiniteGraph.delete_edges_def\n  by (auto simp add: delete_edges_as_filter )\n  \n  lemma delete_edges_wf2:\n    \"wf_graph (list_graph_to_graph G) \\<Longrightarrow> wf_graph (list_graph_to_graph (delete_edges G E))\"\n  by (subst delete_edges_correct[symmetric]) simp\n\n  -- \"helper about reflexive transitive closure impl\"\n  lemma distinct_relpow_impl:\n    \"distinct L \\<Longrightarrow> distinct new \\<Longrightarrow> distinct have \\<Longrightarrow> distinct (new@have) \\<Longrightarrow> \n     distinct (relpow_impl (\\<lambda>as. remdups (map snd [(a, b)\\<leftarrow>L . a \\<in> set as])) (\\<lambda>xs ys. [x\\<leftarrow>xs . x \\<notin> set ys] @ ys) (\\<lambda>x xs. x \\<in> set xs) new have M)\"\n  proof (induction M arbitrary: \"new\" \"have\")\n    case Suc\n    hence\n      \"distinct ([x\\<leftarrow>new . x \\<notin> set have] @ have)\"\n      \"set ([n\\<leftarrow>remdups (map snd [(a, b)\\<leftarrow>L . a \\<in> set new]) . (n \\<in> set new \\<longrightarrow> n \\<in> set have) \\<and> n \\<notin> set have]) \\<inter> set ([x\\<leftarrow>new . x \\<notin> set have] @ have) = {}\"\n      by auto\n\n    with Suc show ?case\n      by auto\n  qed auto\n\n  lemma distinct_rtrancl_list_impl: \"distinct L \\<Longrightarrow> distinct ls \\<Longrightarrow> distinct (rtrancl_list_impl L ls)\"\n  unfolding rtrancl_list_impl_def rtrancl_impl_def\n  by (simp add:distinct_relpow_impl)\n\n  lemma distinct_trancl_list_impl: \"distinct L \\<Longrightarrow> distinct ls \\<Longrightarrow> distinct (trancl_list_impl L ls)\"\n  unfolding trancl_list_impl_def trancl_impl_def\n  by (simp add:distinct_relpow_impl)\n\n  -- \"succ rtran\"\n  value \"succ_rtran \\<lparr> nodesL = [1::nat,2,3,4,8,9,10], edgesL = [(1,2), (2,3), (3,4), (8,9),(9,8)] \\<rparr> 1\"\n\n  lemma succ_rtran_correct: \"FiniteGraph.succ_rtran (list_graph_to_graph G) v = set (succ_rtran G v)\"\n  unfolding FiniteGraph.succ_rtran_def succ_rtran_def list_graph_to_graph_def\n  by (simp add: rtrancl_list_impl)\n\n  lemma distinct_succ_rtran: \"wf_list_graph G \\<Longrightarrow> distinct (succ_rtran G v)\"\n  unfolding succ_rtran_def wf_list_graph_def\n  by (auto intro: distinct_rtrancl_list_impl)\n\n  lemma succ_rtran_set: \"set (succ_rtran G v) = {e2. (v,e2) \\<in> (set (edgesL G))\\<^sup>*}\"\n  unfolding succ_rtran_def\n  by (simp add: rtrancl_list_impl)\n\n  -- \"succ tran\"\n  lemma distinct_succ_tran: \"wf_list_graph G \\<Longrightarrow> distinct (succ_tran G v)\"\n  unfolding succ_tran_def wf_list_graph_def\n  by (auto intro: distinct_trancl_list_impl)\n\n  lemma succ_tran_set: \"set (succ_tran G v) = {e2. (v,e2) \\<in> (set (edgesL G))\\<^sup>+}\"\n  unfolding succ_tran_def\n  by (simp add: trancl_list_impl)\n\n  value \"succ_tran \\<lparr> nodesL = [1::nat,2,3,4,8,9,10], edgesL = [(1,2), (2,3), (3,4), (8,9),(9,8)] \\<rparr> 1\"\n\n  lemma succ_tran_correct: \"FiniteGraph.succ_tran (list_graph_to_graph G) v = set (succ_tran G v)\"\n  unfolding FiniteGraph.succ_tran_def succ_tran_def list_graph_to_graph_def\n  by (simp add:trancl_list_impl)\n  \n  --\"num_reachable\"\n  lemma num_reachable_correct:\n    \"wf_list_graph G \\<Longrightarrow> FiniteGraph.num_reachable (list_graph_to_graph G) v = num_reachable G v\"\n  unfolding num_reachable_def FiniteGraph.num_reachable_def\n  by (metis List.distinct_card distinct_succ_tran succ_tran_correct)\n\n  --\"num_reachable_norefl\"\n  lemma num_reachable_norefl_correct:\n    \"wf_list_graph G \\<Longrightarrow> \n     FiniteGraph.num_reachable_norefl (list_graph_to_graph G) v = num_reachable_norefl G v\"\n unfolding num_reachable_norefl_def FiniteGraph.num_reachable_norefl_def\n by (metis (full_types) List.distinct_card distinct_filter distinct_succ_tran set_minus_filter_out succ_tran_correct)\n\n  -- \"backlinks, i.e. backflows in formal def\"\n  lemma backlinks_alt: \"backlinks E = [(snd e, fst e). e \\<leftarrow> E]\"\n  by (induction E) auto\n\n  lemma backlinks_set: \"set (backlinks E) = {(e2, e1). (e1, e2) \\<in> set E}\"\n  by (induction E) auto\n\n  lemma undirected_nodes_set: \"set (edgesL (undirected G)) = set (edgesL G) \\<union> {(e2, e1). (e1, e2) \\<in> set (edgesL G)}\"\n  unfolding undirected_def\n  by (simp add: backlinks_set)\n\n  lemma undirected_succ_tran_set: \"set (succ_tran (undirected G) v) = {e2. (v,e2) \\<in> (set (edgesL (undirected G)))\\<^sup>+}\"\n  by (fact succ_tran_set)\n\n  lemma backlinks_in_nodes_G: \"\\<lbrakk> fst ` set (edgesL G) \\<subseteq> set (nodesL G); snd ` set (edgesL G) \\<subseteq> set (nodesL G) \\<rbrakk> \\<Longrightarrow> \n    fst` set (edgesL (undirected G)) \\<subseteq> set (nodesL (undirected G)) \\<and> snd` set (edgesL (undirected G)) \\<subseteq> set (nodesL (undirected G))\"\n  unfolding undirected_def\n  by(auto simp: backlinks_set)\n\n  lemma backlinks_distinct: \"distinct E \\<Longrightarrow> distinct (backlinks E)\"\n  by (induction E) (auto simp: backlinks_alt)\n\n  lemma backlinks_subset: \"set (backlinks X) \\<subseteq> set (backlinks Y) \\<longleftrightarrow> set X \\<subseteq> set Y\"\n  by (auto simp: backlinks_set)\n\n  lemma backlinks_correct: \"FiniteGraph.backflows (set E) = set (backlinks E)\"\n  unfolding backflows_def\n  by(simp add: backlinks_set)\n\n  -- \"undirected\"\n  lemma undirected_wf: \"wf_list_graph G \\<Longrightarrow> wf_list_graph (undirected G)\"\n  unfolding wf_list_graph_def wf_list_graph_axioms_def\n  by (simp add:backlinks_in_nodes_G) (simp add: undirected_def)\n\n  lemma undirected_correct: \n    \"FiniteGraph.undirected (list_graph_to_graph G) = list_graph_to_graph (undirected G)\"\n  unfolding FiniteGraph.undirected_def undirected_def list_graph_to_graph_def\n  by (simp add: backlinks_set)\n      \nlemmas wf_list_graph_wf =\n  add_node_wf\n  add_edge_wf\n  delete_node_wf\n  delete_edge_wf\n  delete_edges_wf\n  undirected_wf\n\nlemmas list_graph_correct =\n  add_node_correct\n  add_edge_correct\n  delete_node_correct\n  delete_edge_correct\n  delete_edges_correct\n  succ_rtran_correct\n  succ_tran_correct\n  num_reachable_correct\n  undirected_correct\n\n\nend\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/FiniteListGraph.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357563664174, "lm_q2_score": 0.8333246015211008, "lm_q1q2_score": 0.722522226178591}}
{"text": "(*  Title:      HOL/Complete_Lattices.thy\n    Author:     Tobias Nipkow\n    Author:     Lawrence C Paulson\n    Author:     Markus Wenzel\n    Author:     Florian Haftmann\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>_\" [900] 900)\nbegin\n\nabbreviation INFIMUM :: \"'b set \\<Rightarrow> ('b \\<Rightarrow> 'a) \\<Rightarrow> 'a\"\n  where \"INFIMUM A f \\<equiv> \\<Sqinter>(f ` A)\"\n\nlemma INF_image [simp]: \"INFIMUM (f ` A) g = INFIMUM A (g \\<circ> f)\"\n  by (simp add: image_comp)\n\nlemma INF_identity_eq [simp]: \"INFIMUM A (\\<lambda>x. x) = \\<Sqinter>A\"\n  by simp\n\nlemma INF_id_eq [simp]: \"INFIMUM A id = \\<Sqinter>A\"\n  by simp\n\nlemma INF_cong: \"A = B \\<Longrightarrow> (\\<And>x. x \\<in> B \\<Longrightarrow> C x = D x) \\<Longrightarrow> INFIMUM A C = INFIMUM B D\"\n  by (simp add: 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\nabbreviation SUPREMUM :: \"'b set \\<Rightarrow> ('b \\<Rightarrow> 'a) \\<Rightarrow> 'a\"\n  where \"SUPREMUM A f \\<equiv> \\<Squnion>(f ` A)\"\n\nlemma SUP_image [simp]: \"SUPREMUM (f ` A) g = SUPREMUM A (g \\<circ> f)\"\n  by (simp add: image_comp)\n\nlemma SUP_identity_eq [simp]: \"SUPREMUM A (\\<lambda>x. x) = \\<Squnion>A\"\n  by simp\n\nlemma SUP_id_eq [simp]: \"SUPREMUM A id = \\<Squnion>A\"\n  by (simp add: id_def)\n\nlemma SUP_cong: \"A = B \\<Longrightarrow> (\\<And>x. x \\<in> B \\<Longrightarrow> C x = D x) \\<Longrightarrow> SUPREMUM A C = SUPREMUM B D\"\n  by (simp add: 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 \\<open>\n  Note: must use names @{const INFIMUM} and @{const SUPREMUM} here instead of\n  \\<open>INF\\<close> and \\<open>SUP\\<close> to allow the following syntax coexist\n  with the plain constant names.\n\\<close>\n\nsyntax (ASCII)\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 (output)\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\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. B\"   \\<rightleftharpoons> \"\\<Sqinter>x. \\<Sqinter>y. B\"\n  \"\\<Sqinter>x. B\"     \\<rightleftharpoons> \"CONST INFIMUM CONST UNIV (\\<lambda>x. B)\"\n  \"\\<Sqinter>x. B\"     \\<rightleftharpoons> \"\\<Sqinter>x \\<in> CONST UNIV. B\"\n  \"\\<Sqinter>x\\<in>A. B\"   \\<rightleftharpoons> \"CONST INFIMUM A (\\<lambda>x. B)\"\n  \"\\<Squnion>x y. B\"   \\<rightleftharpoons> \"\\<Squnion>x. \\<Squnion>y. B\"\n  \"\\<Squnion>x. B\"     \\<rightleftharpoons> \"CONST SUPREMUM CONST UNIV (\\<lambda>x. B)\"\n  \"\\<Squnion>x. B\"     \\<rightleftharpoons> \"\\<Squnion>x \\<in> CONST UNIV. B\"\n  \"\\<Squnion>x\\<in>A. B\"   \\<rightleftharpoons> \"CONST SUPREMUM A (\\<lambda>x. B)\"\n\nprint_translation \\<open>\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\\<close> \\<comment> \\<open>to avoid eta-contraction of body\\<close>\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 (op \\<ge>) (op >) 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 [simp]: \"(\\<Sqinter>x\\<in>insert a A. f x) = f a \\<sqinter> INFIMUM A f\"\n  by (simp cong del: strong_INF_cong)\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  by (simp cong del: strong_SUP_cong)\n\nlemma INF_empty [simp]: \"(\\<Sqinter>x\\<in>{}. f x) = \\<top>\"\n  by (simp cong del: strong_INF_cong)\n\nlemma SUP_empty [simp]: \"(\\<Squnion>x\\<in>{}. f x) = \\<bottom>\"\n  by (simp cong del: strong_SUP_cong)\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_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_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 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 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 \"INFIMUM A f = INFIMUM B g\"\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 \"SUPREMUM A f = SUPREMUM B g\"\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> (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: \"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: \"(\\<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> INFIMUM A f \\<le> SUPREMUM A f\"\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> INFIMUM I f = 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> SUPREMUM I f = 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> 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: \"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    and inf_Sup: \"a \\<sqinter> \\<Squnion>B = (\\<Squnion>b\\<in>B. a \\<sqinter> b)\"\nbegin\n\nlemma sup_INF: \"a \\<squnion> (\\<Sqinter>b\\<in>B. f b) = (\\<Sqinter>b\\<in>B. a \\<squnion> f b)\"\n  by (simp add: sup_Inf)\n\nlemma inf_SUP: \"a \\<sqinter> (\\<Squnion>b\\<in>B. f b) = (\\<Squnion>b\\<in>B. a \\<sqinter> f b)\"\n  by (simp add: inf_Sup)\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 add: inf_Sup sup_Inf)\n  done\n\nsubclass distrib_lattice\nproof\n  fix a b c\n  have \"a \\<squnion> \\<Sqinter>{b, c} = (\\<Sqinter>d\\<in>{b, c}. a \\<squnion> d)\" by (rule sup_Inf)\n  then show \"a \\<squnion> b \\<sqinter> c = (a \\<squnion> b) \\<sqinter> (a \\<squnion> c)\" by simp\nqed\n\nlemma Inf_sup: \"\\<Sqinter>B \\<squnion> a = (\\<Sqinter>b\\<in>B. b \\<squnion> a)\"\n  by (simp add: sup_Inf sup_commute)\n\nlemma Sup_inf: \"\\<Squnion>B \\<sqinter> a = (\\<Squnion>b\\<in>B. b \\<sqinter> a)\"\n  by (simp add: inf_Sup inf_commute)\n\nlemma INF_sup: \"(\\<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: \"(\\<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: \"(\\<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: \"(\\<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: \"(\\<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: \"(\\<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: \"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 (INF i : I. A i) \\<le> (INF x : I. f (A x))\"\n  by (intro complete_lattice_class.INF_greatest monoD[OF \\<open>mono f\\<close>] INF_lower)\n\nlemma mono_SUP: \"(SUP x : I. f (A x)) \\<le> f (SUP i : 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 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,\n      rule dual_complete_distrib_lattice,\n      rule dual_boolean_algebra)\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 (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: \"\\<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: \"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\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> 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 \\<open>Complete lattice on @{typ bool}\\<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]: \"INFIMUM = Ball\"\n  by (simp add: fun_eq_iff)\n\nlemma SUP_bool_eq [simp]: \"SUPREMUM = Bex\"\n  by (simp add: fun_eq_iff)\n\ninstance bool :: complete_boolean_algebra\n  by standard (auto intro: bool_induct)\n\n\nsubsection \\<open>Complete lattice on @{typ \"_ \\<Rightarrow> _\"}\\<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  using Inf_apply [of \"f ` A\"] by (simp add: comp_def)\n\nlemma SUP_apply [simp]: \"(\\<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\n  by standard (auto simp add: inf_Sup sup_Inf fun_eq_iff image_image)\n\ninstance \"fun\" :: (type, complete_boolean_algebra) complete_boolean_algebra ..\n\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 \"_ set\"}\\<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\ninstance \"set\" :: (type) complete_boolean_algebra\n  by standard (auto simp add: Inf_set_def Sup_set_def image_def)\n\n\nsubsubsection \\<open>Inter\\<close>\n\nabbreviation Inter :: \"'a set set \\<Rightarrow> 'a set\"  (\"\\<Inter>_\" [900] 900)\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 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 \\<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 \"X \\<in> C\"}.\\<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\nabbreviation INTER :: \"'a set \\<Rightarrow> ('a \\<Rightarrow> 'b set) \\<Rightarrow> 'b set\"\n  where \"INTER \\<equiv> INFIMUM\"\n\ntext \\<open>\n  Note: must use name @{const INTER} here instead of \\<open>INT\\<close>\n  to allow the following syntax coexist with the plain constant name.\n\\<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 (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\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\ntranslations\n  \"\\<Inter>x y. B\"  \\<rightleftharpoons> \"\\<Inter>x. \\<Inter>y. B\"\n  \"\\<Inter>x. B\"    \\<rightleftharpoons> \"CONST INTER CONST UNIV (\\<lambda>x. B)\"\n  \"\\<Inter>x. B\"    \\<rightleftharpoons> \"\\<Inter>x \\<in> CONST UNIV. B\"\n  \"\\<Inter>x\\<in>A. B\"  \\<rightleftharpoons> \"CONST INTER A (\\<lambda>x. B)\"\n\nprint_translation \\<open>\n  [Syntax_Trans.preserve_binder_abs2_tr' @{const_syntax INTER} @{syntax_const \"_INTER\"}]\n\\<close> \\<comment> \\<open>to avoid eta-contraction of body\\<close>\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 \"a\\<in>A\"}.\\<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 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: \"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>_\" [900] 900)\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 C} is rigid;\n    @{term A} 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\n\nsubsubsection \\<open>Unions of families\\<close>\n\nabbreviation UNION :: \"'a set \\<Rightarrow> ('a \\<Rightarrow> 'b set) \\<Rightarrow> 'b set\"\n  where \"UNION \\<equiv> SUPREMUM\"\n\ntext \\<open>\n  Note: must use name @{const UNION} here instead of \\<open>UN\\<close>\n  to allow the following syntax coexist with the plain constant name.\n\\<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 (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\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\ntranslations\n  \"\\<Union>x y. B\"   \\<rightleftharpoons> \"\\<Union>x. \\<Union>y. B\"\n  \"\\<Union>x. B\"     \\<rightleftharpoons> \"CONST UNION CONST UNIV (\\<lambda>x. B)\"\n  \"\\<Union>x. B\"     \\<rightleftharpoons> \"\\<Union>x \\<in> CONST UNIV. B\"\n  \"\\<Union>x\\<in>A. B\"   \\<rightleftharpoons> \"CONST UNION A (\\<lambda>x. B)\"\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\"\\<Union>a\\<^sub>1\\<in>A\\<^sub>1. B\"}.\n\\<close>\n\nprint_translation \\<open>\n  [Syntax_Trans.preserve_binder_abs2_tr' @{const_syntax UNION} @{syntax_const \"_UNION\"}]\n\\<close> \\<comment> \\<open>to avoid eta-contraction of body\\<close>\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 A f\"\n  by (simp add: bind_def UNION_eq)\n\nlemma member_bind [simp]: \"x \\<in> Set.bind P f \\<longleftrightarrow> x \\<in> UNION P f \"\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 A} is rigid;\n    @{term b} 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 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 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 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\nlemma inj_on_image: \"inj_on f (\\<Union>A) \\<Longrightarrow> inj_on (op ` 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 (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  \\<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 (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  \\<comment> \\<open>Halmos, Naive Set Theory, page 35.\\<close>\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\nlemma SUP_UNION: \"(SUP x:(UN y:A. g y). f x) = (SUP y:A. SUP x: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 I A)\"\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 I A'\" 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 I A\"\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 A B) = (INT x:A. f ` B x)\"\n  by (auto simp add: inj_on_def) blast\n\nlemma bij_image_INT: \"bij f \\<Longrightarrow> f ` (INTER A B) = (INT x:A. f ` B x)\"\n  apply (simp only: bij_def)\n  apply (simp only: inj_on_def surj_def)\n  apply auto\n  apply blast\n  done\n\nlemma UNION_fun_upd: \"UNION J (A(i := B)) = UNION (J - {i}) A \\<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 (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 \\<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 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 \\<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 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 \\<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": "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_Lattices.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711870587667, "lm_q2_score": 0.8499711813581708, "lm_q1q2_score": 0.7224510139847468}}
{"text": "(*  Title:      HOL/Isar_Examples/Fibonacci.thy\n    Author:     Gertrud Bauer\n    Copyright   1999 Technische Universitaet Muenchen\n\nThe Fibonacci function.  Original\ntactic script by Lawrence C Paulson.\n\nFibonacci numbers: proofs of laws taken from\n\n  R. L. Graham, D. E. Knuth, O. Patashnik.\n  Concrete Mathematics.\n  (Addison-Wesley, 1989)\n*)\n\nsection \\<open>Fib and Gcd commute\\<close>\n\ntheory Fibonacci\n  imports \"../Number_Theory/Primes\"\nbegin\n\ntext_raw \\<open>\\<^footnote>\\<open>Isar version by Gertrud Bauer. Original tactic script by Larry\n  Paulson. A few proofs of laws taken from @{cite \"Concrete-Math\"}.\\<close>\\<close>\n\n\ndeclare One_nat_def [simp]\n\n\nsubsection \\<open>Fibonacci numbers\\<close>\n\nfun fib :: \"nat \\<Rightarrow> nat\"\n  where\n    \"fib 0 = 0\"\n  | \"fib (Suc 0) = 1\"\n  | \"fib (Suc (Suc x)) = fib x + fib (Suc x)\"\n\n\n\n\ntext \\<open>Alternative induction rule.\\<close>\n\ntheorem fib_induct: \"P 0 \\<Longrightarrow> P 1 \\<Longrightarrow> (\\<And>n. P (n + 1) \\<Longrightarrow> P n \\<Longrightarrow> P (n + 2)) \\<Longrightarrow> P n\"\n  for n :: nat\n  by (induct rule: fib.induct) simp_all\n\n\nsubsection \\<open>Fib and gcd commute\\<close>\n\ntext \\<open>A few laws taken from @{cite \"Concrete-Math\"}.\\<close>\n\nlemma fib_add: \"fib (n + k + 1) = fib (k + 1) * fib (n + 1) + fib k * fib n\"\n  (is \"?P n\")\n  \\<comment> \\<open>see @{cite \\<open>page 280\\<close> \"Concrete-Math\"}\\<close>\nproof (induct n rule: fib_induct)\n  show \"?P 0\" by simp\n  show \"?P 1\" by simp\n  fix n\n  have \"fib (n + 2 + k + 1)\n    = fib (n + k + 1) + fib (n + 1 + k + 1)\" by simp\n  also assume \"fib (n + k + 1) = fib (k + 1) * fib (n + 1) + fib k * fib n\" (is \" _ = ?R1\")\n  also assume \"fib (n + 1 + k + 1) = fib (k + 1) * fib (n + 1 + 1) + fib k * fib (n + 1)\"\n    (is \" _ = ?R2\")\n  also have \"?R1 + ?R2 = fib (k + 1) * fib (n + 2 + 1) + fib k * fib (n + 2)\"\n    by (simp add: add_mult_distrib2)\n  finally show \"?P (n + 2)\" .\nqed\n\nlemma gcd_fib_Suc_eq_1: \"gcd (fib n) (fib (n + 1)) = 1\"\n  (is \"?P n\")\nproof (induct n rule: fib_induct)\n  show \"?P 0\" by simp\n  show \"?P 1\" by simp\n  fix n\n  have \"fib (n + 2 + 1) = fib (n + 1) + fib (n + 2)\"\n    by simp\n  also have \"\\<dots> = fib (n + 2) + fib (n + 1)\"\n    by simp\n  also have \"gcd (fib (n + 2)) \\<dots> = gcd (fib (n + 2)) (fib (n + 1))\"\n    by (rule gcd_add2)\n  also have \"\\<dots> = gcd (fib (n + 1)) (fib (n + 1 + 1))\"\n    by (simp add: gcd.commute)\n  also assume \"\\<dots> = 1\"\n  finally show \"?P (n + 2)\" .\nqed\n\nlemma gcd_mult_add: \"(0::nat) < n \\<Longrightarrow> gcd (n * k + m) n = gcd m n\"\nproof -\n  assume \"0 < n\"\n  then have \"gcd (n * k + m) n = gcd n (m mod n)\"\n    by (simp add: gcd_non_0_nat add.commute)\n  also from \\<open>0 < n\\<close> have \"\\<dots> = gcd m n\"\n    by (simp add: gcd_non_0_nat)\n  finally show ?thesis .\nqed\n\nlemma gcd_fib_add: \"gcd (fib m) (fib (n + m)) = gcd (fib m) (fib n)\"\nproof (cases m)\n  case 0\n  then show ?thesis by simp\nnext\n  case (Suc k)\n  then have \"gcd (fib m) (fib (n + m)) = gcd (fib (n + k + 1)) (fib (k + 1))\"\n    by (simp add: gcd.commute)\n  also have \"fib (n + k + 1) = fib (k + 1) * fib (n + 1) + fib k * fib n\"\n    by (rule fib_add)\n  also have \"gcd \\<dots> (fib (k + 1)) = gcd (fib k * fib n) (fib (k + 1))\"\n    by (simp add: gcd_mult_add)\n  also have \"\\<dots> = gcd (fib n) (fib (k + 1))\"\n    by (simp only: gcd_fib_Suc_eq_1 gcd_mult_cancel)\n  also have \"\\<dots> = gcd (fib m) (fib n)\"\n    using Suc by (simp add: gcd.commute)\n  finally show ?thesis .\nqed\n\nlemma gcd_fib_diff: \"gcd (fib m) (fib (n - m)) = gcd (fib m) (fib n)\" if \"m \\<le> n\"\nproof -\n  have \"gcd (fib m) (fib (n - m)) = gcd (fib m) (fib (n - m + m))\"\n    by (simp add: gcd_fib_add)\n  also from \\<open>m \\<le> n\\<close> have \"n - m + m = n\"\n    by simp\n  finally show ?thesis .\nqed\n\nlemma gcd_fib_mod: \"gcd (fib m) (fib (n mod m)) = gcd (fib m) (fib n)\" if \"0 < m\"\nproof (induct n rule: nat_less_induct)\n  case hyp: (1 n)\n  show ?case\n  proof -\n    have \"n mod m = (if n < m then n else (n - m) mod m)\"\n      by (rule mod_if)\n    also have \"gcd (fib m) (fib \\<dots>) = gcd (fib m) (fib n)\"\n    proof (cases \"n < m\")\n      case True\n      then show ?thesis by simp\n    next\n      case False\n      then have \"m \\<le> n\" by simp\n      from \\<open>0 < m\\<close> and False have \"n - m < n\"\n        by simp\n      with hyp have \"gcd (fib m) (fib ((n - m) mod m))\n          = gcd (fib m) (fib (n - m))\" by simp\n      also have \"\\<dots> = gcd (fib m) (fib n)\"\n        using \\<open>m \\<le> n\\<close> by (rule gcd_fib_diff)\n      finally have \"gcd (fib m) (fib ((n - m) mod m)) =\n          gcd (fib m) (fib n)\" .\n      with False show ?thesis by simp\n    qed\n    finally show ?thesis .\n  qed\nqed\n\ntheorem fib_gcd: \"fib (gcd m n) = gcd (fib m) (fib n)\"\n  (is \"?P m n\")\nproof (induct m n rule: gcd_nat_induct)\n  fix m n :: nat\n  show \"fib (gcd m 0) = gcd (fib m) (fib 0)\"\n    by simp\n  assume n: \"0 < n\"\n  then have \"gcd m n = gcd n (m mod n)\"\n    by (simp add: gcd_non_0_nat)\n  also assume hyp: \"fib \\<dots> = gcd (fib n) (fib (m mod n))\"\n  also from n have \"\\<dots> = gcd (fib n) (fib m)\"\n    by (rule gcd_fib_mod)\n  also have \"\\<dots> = gcd (fib m) (fib n)\"\n    by (rule gcd.commute)\n  finally show \"fib (gcd m n) = gcd (fib m) (fib n)\" .\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/Fibonacci.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.84997116805678, "lm_q2_score": 0.8499711737573762, "lm_q1q2_score": 0.7224509913731493}}
{"text": "(*  Title:      HOL/Lattice/CompleteLattice.thy\n    Author:     Markus Wenzel, TU Muenchen\n*)\n\nsection \\<open>Complete lattices\\<close>\n\ntheory CompleteLattice imports Lattice begin\n\nsubsection \\<open>Complete lattice operations\\<close>\n\ntext \\<open>\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\\<close>\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 \\<open>\n  The general \\<open>\\<Sqinter>\\<close> (meet) and \\<open>\\<Squnion>\\<close> (join) operations select\n  such infimum and supremum elements.\n\\<close>\n\ndefinition\n  Meet :: \"'a::complete_lattice set \\<Rightarrow> 'a\"  (\"\\<Sqinter>_\" [90] 90) where\n  \"\\<Sqinter>A = (THE inf. is_Inf A inf)\"\ndefinition\n  Join :: \"'a::complete_lattice set \\<Rightarrow> 'a\"  (\"\\<Squnion>_\" [90] 90) where\n  \"\\<Squnion>A = (THE sup. is_Sup A sup)\"\n\ntext \\<open>\n  Due to unique existence of bounds, the complete lattice operations\n  may be exhibited as follows.\n\\<close>\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 _ \\<open>is_Inf A inf\\<close>])\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 _ \\<open>is_Sup A sup\\<close>])\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 \\<open>\n  \\medskip The \\<open>\\<Sqinter>\\<close> and \\<open>\\<Squnion>\\<close> operations indeed determine\n  bounds on a complete lattice structure.\n\\<close>\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 _ \\<open>is_Inf A inf\\<close>])\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 _ \\<open>is_Sup A sup\\<close>])\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 \\<open>The Knaster-Tarski Theorem\\<close>\n\ntext \\<open>\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>\\<open>pages 93--94\\<close> in \"Davey-Priestley:1990\"\\<close> for example).  This\n  is a consequence of the basic boundary properties of the complete\n  lattice operations.\n\\<close>\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 \\<open>Bottom and top elements\\<close>\n\ntext \\<open>\n  With general bounds available, complete lattices also have least and\n  greatest elements.\n\\<close>\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 \\<open>Duality\\<close>\n\ntext \\<open>\n  The class of complete lattices is closed under formation of dual\n  structures.\n\\<close>\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 \\<open>\n  Apparently, the \\<open>\\<Sqinter>\\<close> and \\<open>\\<Squnion>\\<close> operations are dual to each\n  other.\n\\<close>\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 \\<open>\n  Likewise are \\<open>\\<bottom>\\<close> and \\<open>\\<top>\\<close> duals of each other.\n\\<close>\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 \\<open>Complete lattices are lattices\\<close>\n\ntext \\<open>\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\\<close>\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 \\<open>Complete lattices and set-theory operations\\<close>\n\ntext \\<open>\n  The complete lattice operations are (anti) monotone wrt.\\ set\n  inclusion.\n\\<close>\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 \\<open>\n  Bounds over unions of sets may be obtained separately.\n\\<close>\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 \\<open>\n  Bounds over singleton sets are trivial.\n\\<close>\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 \\<open>\n  Bounds over the empty and universal set correspond to each other.\n\\<close>\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": "seL4", "repo": "isabelle", "sha": "e1ab32a3bb41728cd19541063283e37919978a4c", "save_path": "github-repos/isabelle/seL4-isabelle", "path": "github-repos/isabelle/seL4-isabelle/isabelle-e1ab32a3bb41728cd19541063283e37919978a4c/src/HOL/Lattice/CompleteLattice.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8499711680567799, "lm_q2_score": 0.8499711718571775, "lm_q1q2_score": 0.7224509897580351}}
{"text": "(* Title:  Weighted_Graph.thy\n   Author: Lars Noschinski, TU M\u00fcnchen\n*)\n\ntheory Weighted_Graph\nimports\n  Digraph\n  Arc_Walk\n  Complex_Main\nbegin\n\nsection {* Weighted Graphs *}\n\ntype_synonym 'b weight_fun = \"'b \\<Rightarrow> real\"\n\ncontext wf_digraph begin\n\ndefinition awalk_cost :: \"'b weight_fun \\<Rightarrow> 'b awalk \\<Rightarrow> real\" where\n  \"awalk_cost f es = sum_list (map f es)\"\n\nlemma awalk_cost_Nil[simp]: \"awalk_cost f [] = 0\"\n  unfolding awalk_cost_def by simp\n\nlemma awalk_cost_Cons[simp]: \"awalk_cost f (x # xs) = f x + awalk_cost  f xs\"\n  unfolding awalk_cost_def by simp\n\nlemma awalk_cost_append[simp]:\n  \"awalk_cost f (xs @ ys) = awalk_cost f xs + awalk_cost f ys\"\n  unfolding awalk_cost_def by simp\n\nend\n\nend\n", "meta": {"author": "z5146542", "repo": "TOR", "sha": "9a82d491288a6d013e0764f68e602a63e48f92cf", "save_path": "github-repos/isabelle/z5146542-TOR", "path": "github-repos/isabelle/z5146542-TOR/TOR-9a82d491288a6d013e0764f68e602a63e48f92cf/checker-verification/Graph_Theory/Weighted_Graph.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8887587993853654, "lm_q2_score": 0.8128673246376009, "lm_q1q2_score": 0.7224429875045082}}
{"text": "theory BTree\n  imports Main \"HOL-Data_Structures.Sorted_Less\" \"HOL-Data_Structures.Cmp\"\nbegin\n\n(* some setup to cover up the redefinition of sorted in Sorted_Less\n   but keep the lemmas *)\nhide_const (open) Sorted_Less.sorted\nabbreviation \"sorted_less \\<equiv> Sorted_Less.sorted\"\n\nsection \"Definition of the B-Tree\"\n\nsubsection \"Datatype definition\"\n\ntext \"B-trees can be considered to have all data stored interleaved\nas child nodes and separating elements (also keys or indices).\nWe define them to either be a Node that holds a list of pairs of children\nand indices or be a completely empty Leaf.\"\n\n\ndatatype 'a btree = Leaf | Node \"('a btree * 'a) list\" \"'a btree\"\n\ntype_synonym 'a btree_list =  \"('a btree * 'a) list\"\ntype_synonym 'a btree_pair =  \"('a btree * 'a)\"\n\nabbreviation subtrees where \"subtrees xs \\<equiv> (map fst xs)\"\nabbreviation separators where \"separators xs \\<equiv> (map snd xs)\"\n\nsubsection \"Inorder and Set\"\n\ntext \"The set of B-tree elements is defined automatically.\"\n\nthm btree.set\nvalue \"set_btree (Node [(Leaf, (0::nat)), (Node [(Leaf, 1), (Leaf, 10)] Leaf, 12), (Leaf, 30), (Leaf, 100)] Leaf)\"\n\ntext \"The inorder view is defined with the help of the concat function.\"\n\nfun inorder :: \"'a btree \\<Rightarrow> 'a list\" where\n  \"inorder Leaf = []\" |\n  \"inorder (Node ts t) = concat (map (\\<lambda> (sub, sep). inorder sub @ [sep]) ts) @ inorder t\"\n\nabbreviation \"inorder_pair  \\<equiv> \\<lambda>(sub,sep). inorder sub @ [sep]\"\nabbreviation \"inorder_list ts \\<equiv> concat (map inorder_pair ts)\"\n\n(* this abbreviation makes handling the list much nicer *)\nthm inorder.simps\n\nvalue \"inorder (Node [(Leaf, (0::nat)), (Node [(Leaf, 1), (Leaf, 10)] Leaf, 12), (Leaf, 30), (Leaf, 100)] Leaf)\"\n\nsubsection \"Height and Balancedness\"\n\nclass height =\n  fixes height :: \"'a \\<Rightarrow> nat\"\n\ninstantiation btree :: (type) height\nbegin\n\nfun height_btree :: \"'a btree \\<Rightarrow> nat\" where\n  \"height Leaf = 0\" |\n  \"height (Node ts t) = Suc (Max (height ` (set (subtrees ts@[t]))))\"\n\ninstance ..\n\nend\n\ntext \"Balancedness is defined is close accordance to the definition by Ernst\"\n\nfun bal:: \"'a btree \\<Rightarrow> bool\" where\n  \"bal Leaf = True\" |\n  \"bal (Node ts t) = (\n    (\\<forall>sub \\<in> set (subtrees ts). height sub = height t) \\<and>\n    (\\<forall>sub \\<in> set (subtrees ts). bal sub) \\<and> bal t\n  )\"\n\n\nvalue \"height (Node [(Leaf, (0::nat)), (Node [(Leaf, 1), (Leaf, 10)] Leaf, 12), (Leaf, 30), (Leaf, 100)] Leaf)\"\n\n\nsubsection \"Order\"\n\ntext \"The order of a B-tree is defined just as in the original paper by Bayer.\"\n\n(* alt1: following knuths definition to allow for any\n   natural number as order and resolve ambiguity *)\n(* alt2: use range [k,2*k] allowing for valid btrees\n   from k=1 onwards NOTE this is what I ended up implementing *)\n\nfun order:: \"nat \\<Rightarrow> 'a btree \\<Rightarrow> bool\" where\n  \"order k Leaf = True\" |\n  \"order k (Node ts t) = (\n  (length ts \\<ge> k)  \\<and>\n  (length ts \\<le> 2*k) \\<and>\n  (\\<forall>sub \\<in> set (subtrees ts). order k sub) \\<and> order k t\n)\"\n\ntext \\<open>The special condition for the root is called \\textit{root\\_order}\\<close>\n\n(* the invariant for the root of the btree *)\nfun root_order:: \"nat \\<Rightarrow> 'a btree \\<Rightarrow> bool\" where\n  \"root_order k Leaf = True\" |\n  \"root_order k (Node ts t) = (\n  (length ts > 0) \\<and>\n  (length ts \\<le> 2*k) \\<and>\n  (\\<forall>s \\<in> set (subtrees ts). order k s) \\<and> order k t\n)\"\n\n\nsubsection \"Auxiliary Lemmas\"\n\n(* auxiliary lemmas when handling sets *)\nlemma separators_split:\n  \"set (separators (l@(a,b)#r)) = set (separators l) \\<union> set (separators r) \\<union> {b}\"\n  by simp\n\nlemma subtrees_split:\n  \"set (subtrees (l@(a,b)#r)) = set (subtrees l) \\<union> set (subtrees r) \\<union> {a}\"\n  by simp\n\n(* height and set lemmas *)\n\n\nlemma finite_set_ins_swap:\n  assumes \"finite A\"\n  shows \"max a (Max (Set.insert b A)) = max b (Max (Set.insert a A))\"\n  using Max_insert assms max.commute max.left_commute by fastforce\n\nlemma finite_set_in_idem:\n  assumes \"finite A\"\n  shows \"max a (Max (Set.insert a A)) = Max (Set.insert a A)\"\n  using Max_insert assms max.commute max.left_commute by fastforce\n\nlemma height_Leaf: \"height t = 0 \\<longleftrightarrow> t = Leaf\"\n  by (induction t) (auto)\n\nlemma height_btree_order:\n  \"height (Node (ls@[a]) t) = height (Node (a#ls) t)\"\n  by simp\n\nlemma height_btree_sub:\n  \"height (Node ((sub,x)#ls) t) = max (height (Node ls t)) (Suc (height sub))\"\n  by simp\n\nlemma height_btree_last:\n  \"height (Node ((sub,x)#ts) t) = max (height (Node ts sub)) (Suc (height t))\"\n  by (induction ts) auto\n\n\nlemma set_btree_inorder: \"set (inorder t) = set_btree t\"\n  apply(induction t)\n   apply(auto)\n  done\n\n\nlemma child_subset: \"p \\<in> set t \\<Longrightarrow> set_btree (fst p) \\<subseteq> set_btree (Node t n)\"\n  apply(induction p arbitrary: t n)\n  apply(auto)\n  done\n\nlemma some_child_sub:\n  assumes \"(sub,sep) \\<in> set t\"\n  shows \"sub \\<in> set (subtrees t)\"\n    and \"sep \\<in> set (separators t)\"\n  using assms by force+\n\n(* balancedness lemmas *)\n\n\nlemma bal_all_subtrees_equal: \"bal (Node ts t) \\<Longrightarrow> (\\<forall>s1 \\<in> set (subtrees ts). \\<forall>s2 \\<in> set (subtrees ts). height s1 = height s2)\"\n  by (metis BTree.bal.simps(2))\n\n\nlemma fold_max_set: \"\\<forall>x \\<in> set t. x = f \\<Longrightarrow> fold max t f = f\"\n  apply(induction t)\n   apply(auto simp add: max_def_raw)\n  done\n\nlemma height_bal_tree: \"bal (Node ts t) \\<Longrightarrow> height (Node ts t) = Suc (height t)\"\n  by (induction ts) auto\n\n\n\nlemma bal_split_last:\n  assumes \"bal (Node (ls@(sub,sep)#rs) t)\"\n  shows \"bal (Node (ls@rs) t)\"\n    and \"height (Node (ls@(sub,sep)#rs) t) = height (Node (ls@rs) t)\"\n  using assms by auto\n\n\nlemma bal_split_right:\n  assumes \"bal (Node (ls@rs) t)\"\n  shows \"bal (Node rs t)\"\n    and \"height (Node rs t) = height (Node (ls@rs) t)\"\n  using assms by (auto simp add: image_constant_conv)\n\nlemma bal_split_left:\n  assumes \"bal (Node (ls@(a,b)#rs) t)\"\n  shows \"bal (Node ls a)\"\n    and \"height (Node ls a) = height (Node (ls@(a,b)#rs) t)\"\n  using assms by (auto simp add: image_constant_conv)\n\n\nlemma bal_substitute: \"\\<lbrakk>bal (Node (ls@(a,b)#rs) t); height t = height c; bal c\\<rbrakk> \\<Longrightarrow> bal (Node (ls@(c,b)#rs) t)\"\n  unfolding bal.simps\n  by auto\n\nlemma bal_substitute_subtree: \"\\<lbrakk>bal (Node (ls@(a,b)#rs) t); height a = height c; bal c\\<rbrakk> \\<Longrightarrow> bal (Node (ls@(c,b)#rs) t)\"\n  using bal_substitute\n  by auto\n\nlemma bal_substitute_separator: \"bal (Node (ls@(a,b)#rs) t) \\<Longrightarrow> bal (Node (ls@(a,c)#rs) t)\"\n  unfolding bal.simps\n  by auto\n\n(* order lemmas *)\n\nlemma order_impl_root_order: \"\\<lbrakk>k > 0; order k t\\<rbrakk> \\<Longrightarrow> root_order k t\"\n  apply(cases t)\n   apply(auto)\n  done\n\n\n(* sorted inorder implies that some sublists are sorted. This can be followed directly *)\n\nlemma sorted_inorder_list_separators: \"sorted_less (inorder_list ts) \\<Longrightarrow> sorted_less (separators ts)\"\n  apply(induction ts)\n   apply (auto simp add: sorted_lems)\n  done\n\ncorollary sorted_inorder_separators: \"sorted_less (inorder (Node ts t)) \\<Longrightarrow> sorted_less (separators ts)\"\n  using sorted_inorder_list_separators sorted_wrt_append\n  by auto\n\n\nlemma sorted_inorder_list_subtrees:\n  \"sorted_less (inorder_list ts) \\<Longrightarrow> \\<forall> sub \\<in> set (subtrees ts). sorted_less (inorder sub)\"\n  apply(induction ts)\n   apply (auto simp add: sorted_lems)+\n  done\n\ncorollary sorted_inorder_subtrees: \"sorted_less (inorder (Node ts t)) \\<Longrightarrow> \\<forall> sub \\<in> set (subtrees ts). sorted_less (inorder sub)\"\n  using sorted_inorder_list_subtrees sorted_wrt_append by auto\n\nlemma sorted_inorder_list_induct_subtree:\n  \"sorted_less (inorder_list (ls@(sub,sep)#rs)) \\<Longrightarrow> sorted_less (inorder sub)\"\n  by (simp add: sorted_wrt_append)\n\ncorollary sorted_inorder_induct_subtree:\n  \"sorted_less (inorder (Node (ls@(sub,sep)#rs) t)) \\<Longrightarrow> sorted_less (inorder sub)\"\n  by (simp add: sorted_wrt_append)\n\nlemma sorted_inorder_induct_last: \"sorted_less (inorder (Node ts t)) \\<Longrightarrow> sorted_less (inorder t)\"\n  by (simp add: sorted_wrt_append)\n\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/BTree/BTree.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8479677737461007, "lm_q2_score": 0.851952809486198, "lm_q1q2_score": 0.7224285271967471}}
{"text": "(*\n  File:     Catalan_Numbers.thy\n  Author:   Manuel Eberl (TUM)\n\n  The recursive definition of Catalan numbers with a proof of several closed form\n  expressions for them using generating functions. Also contains reasonably efficient\n  code generation and a proof of their asymptotic growth.\n*)\n\ntheory Catalan_Numbers\nimports\n  Complex_Main\n  Catalan_Auxiliary_Integral\n  \"HOL-Analysis.Analysis\"\n  \"HOL-Computational_Algebra.Formal_Power_Series\"\n  \"HOL-Library.Landau_Symbols\"\n  Landau_Symbols.Landau_More\nbegin\n\nsubsection \\<open> Other auxiliary lemmas\\<close>\n\nlemma mult_eq_imp_eq_div:\n  assumes \"a * b = c\" \"(a :: 'a :: semidom_divide) \\<noteq> 0\"\n  shows   \"b = c div a\"\n  by (simp add: assms(2) assms(1) [symmetric])\n\nlemma Gamma_minus_one_half_real:\n  \"Gamma (-(1/2) :: real) = - 2 * sqrt pi\"\n  using rGamma_plus1[of \"-1/2 :: real\"]\n  by (simp add: rGamma_inverse_Gamma divide_simps Gamma_one_half_real split: if_split_asm)\n\nlemma gbinomial_asymptotic':\n  assumes \"z \\<notin> \\<nat>\"\n  shows   \"(\\<lambda>n. z gchoose (n + k)) \\<sim>[at_top]\n             (\\<lambda>n. (-1)^(n+k) / (Gamma (-z) * of_nat n powr (z + 1)) :: real)\"\nproof -\n  from assms have [simp]: \"Gamma (-z) \\<noteq> 0\"\n    by (simp_all add: Gamma_eq_zero_iff uminus_in_nonpos_Ints_iff)\n  have \"filterlim (\\<lambda>n. n + k) at_top at_top\"\n    by (intro filterlim_subseq strict_mono_add)\n  from asymp_equivI'_const[OF gbinomial_asymptotic[of z]] assms\n    have \"(\\<lambda>n. z gchoose n) \\<sim>[at_top] (\\<lambda>n. (-1)^n / (Gamma (-z) * exp ((z+1) * ln (real n))))\"\n    by (simp add: Gamma_eq_zero_iff uminus_in_nonpos_Ints_iff field_simps)\n  also have \"eventually (\\<lambda>n. exp ((z+1) * ln (real n)) = real n powr (z+1)) at_top\"\n    using eventually_gt_at_top[of 0] by eventually_elim (simp add: powr_def)\n  finally have \"(\\<lambda>x. z gchoose (x + k)) \\<sim>[at_top]\n                  (\\<lambda>x. (- 1) ^ (x + k) / (Gamma (- z) * real (x + k) powr (z + 1)))\"\n    by (rule asymp_equiv_compose') (simp add: filterlim_subseq strict_mono_add)\n  also have \"(\\<lambda>x. real x + real k) \\<sim>[at_top] real\"\n    by (subst asymp_equiv_add_right) auto\n  hence \"(\\<lambda>x. real (x + k) powr (z + 1)) \\<sim>[at_top] (\\<lambda>x. real x powr (z + 1))\"\n    by (intro asymp_equiv_powr_real) auto\n  finally show ?thesis by - (simp_all add: asymp_equiv_intros)\nqed\n\n\n\nsubsection \\<open>Definition\\<close>\n\ntext \\<open>\n  We define Catalan numbers by their well-known recursive definition. We shall later derive\n  a few more equivalent definitions from this one.\n\\<close>\n\n(*<*)\ncontext\n  notes [fundef_cong] = sum.cong\nbegin\n(*>*)\n\nfun catalan :: \"nat \\<Rightarrow> nat\" where\n  \"catalan 0 = 1\"\n| \"catalan (Suc n) = (\\<Sum>i\\<le>n. catalan i * catalan (n - i))\"\n\n(*<*)\nend\n\ndeclare catalan.simps(2) [simp del]\nlemmas catalan_0 = catalan.simps(1)\nlemmas catalan_Suc = catalan.simps(2)\nlemma catalan_1 [simp]: \"catalan (Suc 0) = 1\" by (simp add: catalan_Suc)\n(*>*)\n\ntext \\<open>\n  The easiest proof of the more profound properties of the Catalan numbers (such as their\n  closed-form equation and their asymptotic growth) uses their ordinary generating function (OGF).\n  This proof is almost mechanical in the sense that it does not require `guessing' the closed\n  form; one can read it directly from the generating function.\n\n  We therefore define the OGF of the Catalan numbers ($\\sum_{n=0}^\\infty C_n z^n$ in standard\n  mathematical notation):\n\\<close>\n\ndefinition \"fps_catalan = Abs_fps (of_nat \\<circ> catalan)\"\n\nlemma fps_catalan_nth [simp]: \"fps_nth fps_catalan n = of_nat (catalan n)\"\n  by (simp add: fps_catalan_def)\n\ntext \\<open>\n  Given their recursive definition, it is easy to see that the OGF of the Catalan numbers\n  satisfies the following recursive equation:\n\\<close>\nlemma fps_catalan_recurrence:\n  \"fps_catalan = 1 + fps_X * fps_catalan^2\"\nproof (rule fps_ext)\n  fix n :: nat\n  show \"fps_nth fps_catalan n = fps_nth (1 + fps_X * fps_catalan^2) n\"\n    by (cases n) (simp_all add: fps_square_nth catalan_Suc)\nqed\n\ntext \\<open>\n  We can now easily solve this equation for @{term fps_catalan}: if we denote the unknown OGF as\n  $F(z)$, we get $F(z) = \\frac{1}{2}(1 - \\sqrt{1 - 4z})$.\n\n  Note that we do not actually use the square root as defined on real or complex numbers.\n  Any $(1 + cz)^\\alpha$ can be expressed using the formal power series whose coefficients are\n  the generalised binomial coefficients, and thus we can do all of these transformations in a\n  purely algebraic way: $\\sqrt{1-4z} = (1+z)^{\\frac{1}{2}} \\circ (-4z)$ (where ${\\circ}$ denotes\n  composition of formal power series) and $(1+z)^\\alpha$ has the well-known expansion\n  $\\sum_{n=0}^\\infty {\\alpha \\choose n} z^n$.\n\\<close>\nlemma fps_catalan_fps_binomial:\n  \"fps_catalan = (1/2 * (1 - (fps_binomial (1/2) oo (-4*fps_X)))) / fps_X\"\nproof (rule mult_eq_imp_eq_div)\n  let ?F = \"fps_catalan :: 'a fps\"\n  have \"fps_X * (1 + fps_X * ?F^2) = fps_X * ?F\" by (simp only: fps_catalan_recurrence [symmetric])\n  hence \"(1 / 2 - fps_X * ?F)\\<^sup>2 = - fps_X + 1 / 4\"\n    by (simp add: algebra_simps power2_eq_square fps_numeral_simps)\n  also have \"\\<dots> = (1/2 * (fps_binomial (1/2) oo (-4*fps_X)))^2\"\n    by (simp add: power_mult_distrib div_power fps_binomial_1 fps_binomial_power\n                  fps_compose_power fps_compose_add_distrib ring_distribs)\n  finally have \"1/2 - fps_X * ?F = 1/2 * (fps_binomial (1/2) oo (-4*fps_X))\"\n    by (rule fps_power_eqD) simp_all\n  thus \"fps_X*?F = 1/2 * (1 - (fps_binomial (1/2) oo (-4*fps_X)))\" by algebra\nqed simp_all\n\n\nsubsection \\<open>Closed-form formulae and more recurrences\\<close>\n\ntext \\<open>\n  We can now read a closed-form formula for the Catalan numbers directly from the generating\n  function $\\frac{1}{2z}(1 - (1+z)^{\\frac{1}{2}} \\circ (-4z))$.\n\\<close>\ntheorem catalan_closed_form_gbinomial:\n  \"real (catalan n) = 2 * (- 4) ^ n * (1/2 gchoose Suc n)\"\nproof -\n  have \"(catalan n :: real) = fps_nth fps_catalan n\" by simp\n  also have \"\\<dots> = 2 * (- 4) ^ n * (1/2 gchoose Suc n)\"\n    by (subst fps_catalan_fps_binomial)\n       (simp add: fps_div_fps_X_nth numeral_fps_const fps_compose_linear)\n  finally show ?thesis .\nqed\n\ntext \\<open>\n  This closed-form formula can easily be rewritten to the form $C_n = \\frac{1}{n+1} {2n \\choose n}$,\n  which contains only `normal' binomial coefficients and not the generalised ones:\n\\<close>\nlemma catalan_closed_form_aux:\n  \"catalan n * Suc n = (2*n) choose n\"\nproof -\n  have \"real ((2*n) choose n) = fact (2*n) / (fact n)^2\"\n    by (simp add: binomial_fact power2_eq_square)\n  also have \"(fact (2*n) :: real) = 4^n * pochhammer (1 / 2) n * fact n\"\n    by (simp add: fact_double power_mult)\n  also have \"\\<dots> / (fact n)^2 / real (n+1) = real (catalan n)\"\n    by (simp add: catalan_closed_form_gbinomial gbinomial_pochhammer pochhammer_rec\n          field_simps power2_eq_square power_mult_distrib [symmetric] del: of_nat_Suc)\n  finally have \"real (catalan n * Suc n) = real ((2*n) choose n)\" by (simp add: field_simps)\n  thus ?thesis by (simp only: of_nat_eq_iff)\nqed\n\ntheorem of_nat_catalan_closed_form:\n  \"of_nat (catalan n) = (of_nat ((2*n) choose n) / of_nat (Suc n) :: 'a :: field_char_0)\"\nproof -\n  have \"of_nat (catalan n * Suc n) = of_nat ((2*n) choose n)\"\n    by (subst catalan_closed_form_aux) (rule refl)\n  also have \"of_nat (catalan n * Suc n) = of_nat (catalan n) * of_nat (Suc n)\"\n    by (simp only: of_nat_mult)\n  finally show ?thesis by (simp add: divide_simps del: of_nat_Suc)\nqed\n\ntheorem catalan_closed_form:\n  \"catalan n = ((2*n) choose n) div Suc n\"\n  by (subst catalan_closed_form_aux [symmetric]) (simp del: mult_Suc_right)\n\ntext \\<open>\n  The following is another nice closed-form formula for the Catalan numbers, which directly\n  follows from the previous one:\n\\<close>\ncorollary catalan_closed_form':\n  \"catalan n = ((2*n) choose n) - ((2*n) choose (Suc n))\"\nproof (cases n)\n  case (Suc m)\n  have \"real ((2*n) choose n) - real ((2*n) choose (Suc n)) =\n          fact (2*m+2) / (fact (m+1))^2 - fact (2*m+2) / (real (m+2) * fact (m+1) * fact m)\"\n    by (subst (1 2) binomial_fact) (simp_all add: Suc power2_eq_square)\n  also have \"\\<dots> = fact (2*m+2) / ((fact (m+1))^2 * real (m+2))\"\n    by (simp add: divide_simps power2_eq_square) (simp_all add: algebra_simps)\n  also have \"\\<dots> = real (catalan n)\"\n    by (subst of_nat_catalan_closed_form, subst binomial_fact) (simp_all add: Suc power2_eq_square)\n  finally show ?thesis by linarith\nqed simp_all\n\n\ntext \\<open>\n  We can now easily show that the Catalan numbers also satisfy another, simpler recurrence,\n  namely $C_{n+1} = \\frac{2(2n+1)}{n+2} C_n$. We will later use this to prove code equations to\n  compute the Catalan numbers more efficiently.\n\\<close>\nlemma catalan_Suc_aux:\n  \"(n + 2) * catalan (Suc n) = 2 * (2 * n + 1) * catalan n\"\nproof -\n  have \"real (catalan (Suc n)) * real (n + 2) = real (catalan n) * 2 * real (2 * n + 1)\"\n  proof (cases n)\n    case (Suc n)\n    thus ?thesis\n      by (subst (1 2) of_nat_catalan_closed_form, subst (1 2) binomial_fact)\n         (simp_all add: divide_simps)\n  qed simp_all\n  hence \"real ((n + 2) * catalan (Suc n)) = real (2 * (2 * n + 1) * catalan n)\"\n    by (simp only: mult_ac of_nat_mult)\n  thus ?thesis by (simp only: of_nat_eq_iff)\nqed\n\ntheorem of_nat_catalan_Suc':\n  \"of_nat (catalan (Suc n)) =\n     (of_nat (2*(2*n+1)) / of_nat (n+2) * of_nat (catalan n) :: 'a :: field_char_0)\"\nproof -\n  have \"(of_nat (2*(2*n+1)) / of_nat (n+2) * of_nat (catalan n) :: 'a) =\n          of_nat (2*(2*n + 1) * catalan n) / of_nat (n+2)\"\n    by (simp add: divide_simps mult_ac del: mult_Suc mult_Suc_right)\n  also note catalan_Suc_aux[of n, symmetric]\n  also have \"of_nat ((n + 2) * catalan (Suc n)) / of_nat (n + 2) = (of_nat (catalan (Suc n)) :: 'a)\"\n    by (simp del: of_nat_Suc mult_Suc_right mult_Suc)\n  finally show ?thesis ..\nqed\n\ntheorem catalan_Suc':\n  \"catalan (Suc n) = (catalan n * (2*(2*n+1))) div (n+2)\"\nproof -\n  from catalan_Suc_aux[of n] have \"catalan n * (2*(2*n+1)) = catalan (Suc n) * (n+2)\"\n    by (simp add: algebra_simps)\n  also have \"\\<dots> div (n+2) = catalan (Suc n)\" by (simp del: mult_Suc mult_Suc_right)\n  finally show ?thesis ..\nqed\n\n\n\nsubsection \\<open>Integral formula\\<close>\n\ntext \\<open>\n  The recursive formula we have just proven allows us to derive an integral formula for \n  the Catalan numbers. The proof was adapted from a textbook proof by Steven Roman.~\\cite{catalan}\n\\<close>\n\ncontext\nbegin\n\nprivate definition I :: \"nat \\<Rightarrow> real\" where\n  \"I n = integral {0..4} (\\<lambda>x. x powr (of_nat n - 1/2) * sqrt (4 - x))\"\n\nprivate lemma has_integral_I0: \"((\\<lambda>x. x powr (-(1/2)) * sqrt (4 - x)) has_integral 2*pi) {0..4}\"\nproof -\n  have \"\\<And>x. x\\<in>{0..4}-{} \\<Longrightarrow> x powr (-(1/2)) * sqrt (4 - x) = sqrt ((4 - x) / x)\"\n    by (auto simp: powr_minus field_simps powr_half_sqrt real_sqrt_divide)\n  thus ?thesis by (rule has_integral_spike[OF negligible_empty _ catalan_aux_integral])\nqed\n\nprivate lemma integrable_I: \n  \"(\\<lambda>x. x powr (of_nat n - 1/2) * sqrt (4 - x)) integrable_on {0..4}\"\nproof (cases \"n = 0\")\n  case True\n  with has_integral_I0 show ?thesis by (simp add: has_integral_integrable)\nnext\n  case False\n  thus ?thesis by (intro integrable_continuous_real continuous_on_mult continuous_on_powr')\n                  (auto intro!: continuous_intros)\nqed\n\nprivate lemma I_Suc: \"I (Suc n) = real (2 * (2*n + 1)) / real (n + 2) * I n\"\nproof -\n  define u' u v v' \n    where \"u' = (\\<lambda>x. sqrt (4 - x :: real))\" \n      and \"u = (\\<lambda>x. -2/3 * (4 - x) powr (3/2 :: real))\"\n      and \"v = (\\<lambda>x. x powr (real n + 1/2))\" \n      and \"v' = (\\<lambda>x. (real n + 1/2) * x powr (real n - 1/2))\"\n  define c where \"c = -2/3 * (real n + 1/2)\"\n  define i where \"i = (\\<lambda>n x. x powr (real n - 1/2) * sqrt (4 - x) :: real)\"\n\n  have \"I (Suc n) = integral {0..4} (\\<lambda>x. u' x * v x)\"\n    unfolding I_def by (simp add: algebra_simps u'_def v_def)\n  have \"((\\<lambda>x. u' x * v x) has_integral - c * (4 * I n - I (Suc n))) {0..4}\"\n  proof (rule integration_by_parts_interior[OF bounded_bilinear_mult])\n    show \"continuous_on {0..4} u\" unfolding u_def\n      by (intro continuous_on_powr' continuous_on_mult) (auto intro!: continuous_intros)\n    show \"continuous_on {0..4} v\" unfolding v_def\n      by (intro continuous_on_powr' continuous_on_mult) (auto intro!: continuous_intros)\n    fix x :: real assume x: \"x \\<in> {0<..<4}\"\n    from x show \"(u has_vector_derivative u' x) (at x)\"\n      unfolding has_field_derivative_iff_has_vector_derivative [symmetric] u_def u'_def\n      by (auto intro!: derivative_eq_intros simp: field_simps powr_half_sqrt)\n    from x show \"(v has_vector_derivative v' x) (at x)\"\n      unfolding has_field_derivative_iff_has_vector_derivative [symmetric] v_def v'_def\n      by (auto intro!: derivative_eq_intros simp: field_simps)\n  next\n    show \"((\\<lambda>x. u x * v' x) has_integral u 4 * v 4 - u 0 * v 0 - - c * (4 * I n - I (Suc n))) {0..4}\"\n    proof (rule has_integral_spike; (intro ballI)?)\n      fix x :: real assume x: \"x \\<in> {0..4}-{0}\"\n      have \"u x * v' x = c * ((4 - x) powr (1 + 1/2) * x powr (real n - 1/2))\"\n        by (simp add: u_def v'_def c_def)\n      also from x have \"(4 - x) powr (1 + 1/2) = (4 - x) * sqrt (4 - x)\"\n        by (subst powr_add) (simp_all add: powr_half_sqrt)\n      also have \"\\<dots> * x powr (real n - 1/2) = 4 * sqrt (4 - x) * x powr (real n - 1/2) - \n                     sqrt (4 - x) * x powr (real n - 1/2 + 1)\"\n        by (subst powr_add) (insert x, simp add: field_simps)\n      also have \"real n - 1/2 + 1 = real (Suc n) - 1/2\" by simp\n      finally show \"u x * v' x = c * (4 * i n x - i (Suc n) x)\" by (simp add: i_def)\n    next\n      have \"((\\<lambda>x. c * (4 * i n x - i (Suc n) x)) has_integral c * (4 * I n - I (Suc n))) {0..4}\"\n        unfolding i_def I_def \n        by (intro has_integral_mult_right has_integral_diff integrable_integral integrable_I)\n      thus \"((\\<lambda>x. c * (4 * i n x - i (Suc n) x)) has_integral  u 4 * v 4 - u 0 * v 0 - -\n               c * (4 * I n - I (Suc n))) {0..4}\" by (simp add: u_def v_def)\n    qed simp_all\n  qed simp_all\n  also have \"(\\<lambda>x. u' x * v x) = i (Suc n)\" \n    by (rule ext) (simp add: u'_def v_def i_def algebra_simps)\n  finally have \"I (Suc n) = - c * (4 * I n - I (Suc n))\" unfolding I_def i_def by blast\n  hence \"(1 - c) * I (Suc n) = -4 * c * I n\" by algebra\n  hence \"I (Suc n) = (-4 * c) / (1 - c) * I n\" by (simp add: field_simps c_def)\n  also have \"(-4 * c) / (1 - c) = real (2*(2*n + 1)) / real (n + 2)\" \n    by (simp add: c_def field_simps)\n  finally show ?thesis .\nqed\n\nprivate lemma catalan_eq_I: \"real (catalan n) = I n / (2 * pi)\"\nproof (induction n)\n  case 0\n  thus ?case using has_integral_I0 by (simp add: I_def integral_unique)\nnext\n  case (Suc n)\n  show ?case by (simp add: of_nat_catalan_Suc' Suc.IH I_Suc)\nqed\n\ntheorem catalan_integral_form:\n  \"((\\<lambda>x. x powr (real n - 1 / 2) * sqrt (4 - x) / (2*pi)) \n       has_integral real (catalan n)) {0..4}\"\nproof -\n  have \"((\\<lambda>x. x powr (real n - 1 / 2) * sqrt (4 - x) * inverse (2*pi)) has_integral \n           I n * inverse (2 * pi)) {0..4}\" unfolding I_def\n    by (intro has_integral_mult_left integrable_integral integrable_I)\n  thus ?thesis by (simp add: catalan_eq_I field_simps)\nqed\n\nend\n\n\nsubsection \\<open>Asymptotics\\<close>\n\ntext \\<open>\n  Using the closed form $C_n = 2 \\cdot (-4)^n {\\frac{1}{2} \\choose n+1}$ and the fact that\n  ${\\alpha \\choose n} \\sim \\frac{(-1)^n}{\\Gamma(-\\alpha) n^{\\alpha + 1}}$ for any\n  $\\alpha \\notin \\mathbb{N}$, wwe can now easily analyse the asymptotic behaviour of the\n  Catalan numbers:\n\\<close>\ntheorem catalan_asymptotics:\n  \"catalan \\<sim>[at_top] (\\<lambda>n. 4 ^ n / (sqrt pi * n powr (3/2)))\"\nproof -\n  have \"catalan \\<sim>[at_top] (\\<lambda>n. 2 * (- 4) ^ n * (1/2 gchoose (n+1)))\"\n    by (subst catalan_closed_form_gbinomial) simp_all\n  also have \"(\\<lambda>n. 1/2 gchoose (n+1)) \\<sim>[at_top] (\\<lambda>n. (-1)^(n+1) / (Gamma (-(1/2)) * real n powr (1/2 + 1)))\"\n    using fraction_not_in_nats[of 2 1] by (intro asymp_equiv_intros gbinomial_asymptotic') simp_all\n  also have \"(\\<lambda>n. 2 * (- 4) ^ n * \\<dots> n) = (\\<lambda>n. 4 ^ n / (sqrt pi * n powr (3/2)))\"\n    by (intro ext) (simp add: Gamma_minus_one_half_real power_mult_distrib [symmetric])\n  finally show ?thesis by - (simp_all add: asymp_equiv_intros)\nqed\n\n\nsubsection \\<open>Relation to binary trees\\<close>\n\n(*<*)\ncontext\nbegin\n(*>*)\n\ntext \\<open>\n  It is well-known that the Catalan number $C_n$ is the number of rooted binary trees with\n  $n$ internal nodes (where internal nodes are those with two children and external nodes\n  are those with no children).\n\n  We will briefly show this here to show that the above asymptotic formula also describes the\n  number of binary trees of a given size.\n\\<close>\n\nqualified datatype tree = Leaf | Node tree tree\n\nqualified primrec count_nodes :: \"tree \\<Rightarrow> nat\" where\n  \"count_nodes Leaf = 0\"\n| \"count_nodes (Node l r) = 1 + count_nodes l + count_nodes r\"\n\nqualified definition trees_of_size :: \"nat \\<Rightarrow> tree set\" where\n  \"trees_of_size n = {t. count_nodes t = n}\"\n\nlemma count_nodes_eq_0_iff [simp]: \"count_nodes t = 0 \\<longleftrightarrow> t = Leaf\"\n  by (cases t) simp_all\n\nlemma trees_of_size_0 [simp]: \"trees_of_size 0 = {Leaf}\"\n  by (simp add: trees_of_size_def)\n\nlemma trees_of_size_Suc:\n  \"trees_of_size (Suc n) = (\\<lambda>(l,r). Node l r) ` (\\<Union>k\\<le>n. trees_of_size k \\<times> trees_of_size (n - k))\"\n    (is \"?lhs = ?rhs\")\nproof (rule set_eqI)\n  fix t show \"t \\<in> ?lhs \\<longleftrightarrow> t \\<in> ?rhs\" by (cases t) (auto simp: trees_of_size_def)\nqed\n\nlemma finite_trees_of_size [simp,intro]: \"finite (trees_of_size n)\"\n  by (induction n rule: catalan.induct)\n     (auto simp: trees_of_size_Suc intro!: finite_imageI finite_cartesian_product)\n\nlemma trees_of_size_nonempty: \"trees_of_size n \\<noteq> {}\"\n  by (induction n rule: catalan.induct) (auto simp: trees_of_size_Suc)\n\nlemma trees_of_size_disjoint:\n  assumes \"m \\<noteq> n\"\n  shows   \"trees_of_size m \\<inter> trees_of_size n = {}\"\n  using assms by (auto simp: trees_of_size_def)\n\ntheorem card_trees_of_size: \"card (trees_of_size n) = catalan n\"\n  by (induction n rule: catalan.induct)\n     (simp_all add: catalan_Suc trees_of_size_Suc card_image inj_on_def\n        trees_of_size_disjoint Times_Int_Times catalan_Suc card_UN_disjoint)\n\n(*<*)\nend\n(*>*)\n\n\nsubsection \\<open>Efficient computation\\<close>\n\n(*<*)\ncontext\nbegin\n(*>*)\n\ntext \\<open>\n  We shall now prove code equations that allow more efficient computation of Catalan numbers.\n  In order to do this, we define a tail-recursive function that uses the recurrence\n  @{thm catalan_Suc'[no_vars]}:\n\\<close>\nqualified function catalan_aux where [simp del]:\n  \"catalan_aux n k acc =\n     (if k \\<ge> n then acc else catalan_aux n (Suc k) ((acc * (2*(2*k+1))) div (k+2)))\"\n  by auto\ntermination by (relation \"Wellfounded.measure (\\<lambda>(a,b,_). a - b)\") simp_all\n\nqualified lemma catalan_aux_simps:\n  \"k \\<ge> n \\<Longrightarrow> catalan_aux n k acc = acc\"\n  \"k < n \\<Longrightarrow> catalan_aux n k acc = catalan_aux n (Suc k) ((acc * (2*(2*k+1))) div (k+2))\"\n  by (subst catalan_aux.simps, simp)+\n\nqualified lemma catalan_aux_correct:\n  assumes \"k \\<le> n\"\n  shows   \"catalan_aux n k (catalan k) = catalan n\"\nusing assms\nproof (induction n k \"catalan k\" rule: catalan_aux.induct)\n  case (1 n k)\n  show ?case\n  proof (cases \"k < n\")\n    case True\n    hence \"catalan_aux n k (catalan k) = catalan_aux n (Suc k) (catalan (Suc k))\"\n      by (subst catalan_Suc') (simp_all add: catalan_aux_simps)\n    with 1 True show ?thesis by (simp add: catalan_Suc')\n  qed (insert \"1.prems\", simp_all add: catalan_aux_simps)\nqed\n\nlemma catalan_code [code]: \"catalan n = catalan_aux n 0 1\"\n  using catalan_aux_correct[of 0 n] by simp\n\n(*<*)\nend\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/Catalan_Numbers/Catalan_Numbers.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.851952809486198, "lm_q2_score": 0.8479677602988601, "lm_q1q2_score": 0.7224285157403328}}
{"text": "(*  Title:      HOL/Algebra/Embedded_Algebras.thy\n    Author:     Paulo Em\u00edlio de Vilhena\n*)\n\ntheory Embedded_Algebras\n  imports Subrings Generated_Groups\nbegin\n\nsection \\<open>Definitions\\<close>\n\nlocale embedded_algebra =\n  K?: subfield K R + R?: ring R for K :: \"'a set\" and R :: \"('a, 'b) ring_scheme\" (structure)\n\ndefinition (in ring) line_extension :: \"'a set \\<Rightarrow> 'a \\<Rightarrow> 'a set \\<Rightarrow> 'a set\"\n  where \"line_extension K a E = (K #> a) <+>\\<^bsub>R\\<^esub> E\"\n\nfun (in ring) Span :: \"'a set \\<Rightarrow> 'a list \\<Rightarrow> 'a set\"\n  where \"Span K Us = foldr (line_extension K) Us { \\<zero> }\"\n\nfun (in ring) combine :: \"'a list \\<Rightarrow> 'a list \\<Rightarrow> 'a\"\n  where\n    \"combine (k # Ks) (u # Us) = (k \\<otimes> u) \\<oplus> (combine Ks Us)\"\n  | \"combine Ks Us = \\<zero>\"\n\ninductive (in ring) independent :: \"'a set \\<Rightarrow> 'a list \\<Rightarrow> bool\"\n  where\n    li_Nil [simp, intro]: \"independent K []\"\n  | li_Cons: \"\\<lbrakk> u \\<in> carrier R; u \\<notin> Span K Us; independent K Us \\<rbrakk> \\<Longrightarrow> independent K (u # Us)\"\n\ninductive (in ring) dimension :: \"nat \\<Rightarrow> 'a set \\<Rightarrow> 'a set \\<Rightarrow> bool\"\n  where\n    zero_dim [simp, intro]: \"dimension 0 K { \\<zero> }\"\n   | Suc_dim: \"\\<lbrakk> v \\<in> carrier R; v \\<notin> E; dimension n K E \\<rbrakk> \\<Longrightarrow> dimension (Suc n) K (line_extension K v E)\"\n\n\nsubsubsection \\<open>Syntactic Definitions\\<close>\n\nabbreviation (in ring) dependent ::  \"'a set \\<Rightarrow> 'a list \\<Rightarrow> bool\"\n  where \"dependent K U \\<equiv> \\<not> independent K U\"\n\ndefinition over :: \"('a \\<Rightarrow> 'b) \\<Rightarrow> 'a \\<Rightarrow> 'b\" (infixl \"over\" 65)\n  where \"f over a = f a\"\n\n\n\ncontext ring\nbegin\n\n\nsubsection \\<open>Basic Properties - First Part\\<close>\n\nlemma line_extension_consistent:\n  assumes \"subring K R\" shows \"ring.line_extension (R \\<lparr> carrier := K \\<rparr>) = line_extension\"\n  unfolding ring.line_extension_def[OF subring_is_ring[OF assms]] line_extension_def\n  by (simp add: set_add_def set_mult_def)\n\nlemma Span_consistent:\n  assumes \"subring K R\" shows \"ring.Span (R \\<lparr> carrier := K \\<rparr>) = Span\"\n  unfolding ring.Span.simps[OF subring_is_ring[OF assms]] Span.simps\n            line_extension_consistent[OF assms] by simp\n\nlemma combine_in_carrier [simp, intro]:\n  \"\\<lbrakk> set Ks \\<subseteq> carrier R; set Us \\<subseteq> carrier R \\<rbrakk> \\<Longrightarrow> combine Ks Us \\<in> carrier R\"\n  by (induct Ks Us rule: combine.induct) (auto)\n\nlemma combine_r_distr:\n  \"\\<lbrakk> set Ks \\<subseteq> carrier R; set Us \\<subseteq> carrier R \\<rbrakk> \\<Longrightarrow>\n     k \\<in> carrier R \\<Longrightarrow> k \\<otimes> (combine Ks Us) = combine (map ((\\<otimes>) k) Ks) Us\"\n  by (induct Ks Us rule: combine.induct) (auto simp add: m_assoc r_distr)\n\nlemma combine_l_distr:\n  \"\\<lbrakk> set Ks \\<subseteq> carrier R; set Us \\<subseteq> carrier R \\<rbrakk> \\<Longrightarrow>\n     u \\<in> carrier R \\<Longrightarrow> (combine Ks Us) \\<otimes> u = combine Ks (map (\\<lambda>u'. u' \\<otimes> u) Us)\"\n  by (induct Ks Us rule: combine.induct) (auto simp add: m_assoc l_distr)\n\nlemma combine_eq_foldr:\n  \"combine Ks Us = foldr (\\<lambda>(k, u). \\<lambda>l. (k \\<otimes> u) \\<oplus> l) (zip Ks Us) \\<zero>\"\n  by (induct Ks Us rule: combine.induct) (auto)\n\nlemma combine_replicate:\n  \"set Us \\<subseteq> carrier R \\<Longrightarrow> combine (replicate (length Us) \\<zero>) Us = \\<zero>\"\n  by (induct Us) (auto)\n\nlemma combine_take:\n  \"combine (take (length Us) Ks) Us = combine Ks Us\"\n  by (induct Us arbitrary: Ks)\n     (auto, metis combine.simps(1) list.exhaust take.simps(1) take_Suc_Cons)\n\nlemma combine_append_zero:\n  \"set Us \\<subseteq> carrier R \\<Longrightarrow> combine (Ks @ [ \\<zero> ]) Us = combine Ks Us\"\nproof (induct Ks arbitrary: Us)\n  case Nil thus ?case by (induct Us) (auto)\nnext\n  case Cons thus ?case by (cases Us) (auto)\nqed\n\nlemma combine_prepend_replicate:\n  \"\\<lbrakk> set Ks \\<subseteq> carrier R; set Us \\<subseteq> carrier R \\<rbrakk> \\<Longrightarrow>\n     combine ((replicate n \\<zero>) @ Ks) Us = combine Ks (drop n Us)\"\nproof (induct n arbitrary: Us, simp)\n  case (Suc n) thus ?case\n    by (cases Us) (auto, meson combine_in_carrier ring_simprules(8) set_drop_subset subset_trans)\nqed\n\nlemma combine_append_replicate:\n  \"set Us \\<subseteq> carrier R \\<Longrightarrow> combine (Ks @ (replicate n \\<zero>)) Us = combine Ks Us\"\n  by (induct n) (auto, metis append.assoc combine_append_zero replicate_append_same)\n\nlemma combine_append:\n  assumes \"length Ks = length Us\"\n    and \"set Ks  \\<subseteq> carrier R\" \"set Us \\<subseteq> carrier R\"\n    and \"set Ks' \\<subseteq> carrier R\" \"set Vs \\<subseteq> carrier R\"\n  shows \"(combine Ks Us) \\<oplus> (combine Ks' Vs) = combine (Ks @ Ks') (Us @ Vs)\"\n  using assms\nproof (induct Ks arbitrary: Us)\n  case Nil thus ?case by auto\nnext\n  case (Cons k Ks)\n  then obtain u Us' where Us: \"Us = u # Us'\"\n    by (metis length_Suc_conv)\n  hence u: \"u \\<in> carrier R\" and Us': \"set Us' \\<subseteq> carrier R\"\n    using Cons(4) by auto\n  then show ?case\n    using combine_in_carrier[OF _ Us', of Ks] Cons\n          combine_in_carrier[OF Cons(5-6)] unfolding Us\n    by (auto, simp add: add.m_assoc)\nqed\n\nlemma combine_add:\n  assumes \"length Ks = length Us\" and \"length Ks' = length Us\"\n    and \"set Ks  \\<subseteq> carrier R\" \"set Ks'  \\<subseteq> carrier R\" \"set Us \\<subseteq> carrier R\"\n  shows \"(combine Ks Us) \\<oplus> (combine Ks' Us) = combine (map2 (\\<oplus>) Ks Ks') Us\"\n  using assms\nproof (induct Us arbitrary: Ks Ks')\n  case Nil thus ?case by simp\nnext\n  case (Cons u Us)\n  then obtain c c' Cs Cs' where Ks: \"Ks = c # Cs\" and Ks': \"Ks' = c' # Cs'\"\n    by (metis length_Suc_conv)\n  hence in_carrier:\n    \"c  \\<in> carrier R\" \"set Cs  \\<subseteq> carrier R\"\n    \"c' \\<in> carrier R\" \"set Cs' \\<subseteq> carrier R\"\n    \"u  \\<in> carrier R\" \"set Us  \\<subseteq> carrier R\"\n    using Cons(4-6) by auto\n  hence lc_in_carrier: \"combine Cs Us \\<in> carrier R\" \"combine Cs' Us \\<in> carrier R\"\n    using combine_in_carrier by auto\n  have \"combine Ks (u # Us) \\<oplus> combine Ks' (u # Us) =\n        ((c \\<otimes> u) \\<oplus> combine Cs Us) \\<oplus> ((c' \\<otimes> u) \\<oplus> combine Cs' Us)\"\n    unfolding Ks Ks' by auto\n  also have \" ... = ((c \\<oplus> c') \\<otimes> u \\<oplus> (combine Cs Us \\<oplus> combine Cs' Us))\"\n    using lc_in_carrier in_carrier(1,3,5) by (simp add: l_distr ring_simprules(7,22))\n  also have \" ... = combine (map2 (\\<oplus>) Ks Ks') (u # Us)\"\n    using Cons unfolding Ks Ks' by auto\n  finally show ?case .\nqed\n\nlemma combine_normalize:\n  assumes \"set Ks \\<subseteq> carrier R\" \"set Us \\<subseteq> carrier R\" \"combine Ks Us = a\" \n  obtains Ks'\n  where \"set (take (length Us) Ks) \\<subseteq> set Ks'\" \"set Ks' \\<subseteq> set (take (length Us) Ks) \\<union> { \\<zero> }\"\n    and \"length Ks' = length Us\" \"combine Ks' Us = a\"\nproof -\n  define Ks'\n    where \"Ks' = (if length Ks \\<le> length Us\n                  then Ks @ (replicate (length Us - length Ks) \\<zero>) else take (length Us) Ks)\"\n  hence \"set (take (length Us) Ks) \\<subseteq> set Ks'\" \"set Ks' \\<subseteq> set (take (length Us) Ks) \\<union> { \\<zero> }\"\n        \"length Ks' = length Us\" \"a = combine Ks' Us\"\n    using combine_append_replicate[OF assms(2)] combine_take assms(3) by auto\n  thus thesis\n    using that by blast\nqed\n\nlemma line_extension_mem_iff: \"u \\<in> line_extension K a E \\<longleftrightarrow> (\\<exists>k \\<in> K. \\<exists>v \\<in> E. u = k \\<otimes> a \\<oplus> v)\"\n  unfolding line_extension_def set_add_def'[of R \"K #> a\" E] unfolding r_coset_def by blast\n\nlemma line_extension_in_carrier:\n  assumes \"K \\<subseteq> carrier R\" \"a \\<in> carrier R\" \"E \\<subseteq> carrier R\"\n  shows \"line_extension K a E \\<subseteq> carrier R\"\n  using set_add_closed[OF r_coset_subset_G[OF assms(1-2)] assms(3)]\n  by (simp add: line_extension_def)\n\nlemma Span_in_carrier:\n  assumes \"K \\<subseteq> carrier R\" \"set Us \\<subseteq> carrier R\"\n  shows \"Span K Us \\<subseteq> carrier R\"\n  using assms by (induct Us) (auto simp add: line_extension_in_carrier)\n\n\nsubsection \\<open>Some Basic Properties of Linear Independence\\<close>\n\nlemma independent_in_carrier: \"independent K Us \\<Longrightarrow> set Us \\<subseteq> carrier R\"\n  by (induct Us rule: independent.induct) (simp_all)\n\nlemma independent_backwards:\n  \"independent K (u # Us) \\<Longrightarrow> u \\<notin> Span K Us\"\n  \"independent K (u # Us) \\<Longrightarrow> independent K Us\"\n  \"independent K (u # Us) \\<Longrightarrow> u \\<in> carrier R\"\n  by (cases rule: independent.cases, auto)+\n\nlemma dimension_independent [intro]: \"independent K Us \\<Longrightarrow> dimension (length Us) K (Span K Us)\"\nproof (induct Us)\n  case Nil thus ?case by simp\nnext\n  case Cons thus ?case\n    using Suc_dim independent_backwards[OF Cons(2)] by auto \nqed\n\n\ntext \\<open>Now, we fix K, a subfield of the ring. Many lemmas would also be true for weaker\n      structures, but our interest is to work with subfields, so generalization could\n      be the subject of a future work.\\<close>\n\ncontext\n  fixes K :: \"'a set\" assumes K: \"subfield K R\"\nbegin\n\n\nsubsection \\<open>Basic Properties - Second Part\\<close>\n\nlemmas subring_props [simp] =\n  subringE[OF subfieldE(1)[OF K]]\n\nlemma line_extension_is_subgroup:\n  assumes \"subgroup E (add_monoid R)\" \"a \\<in> carrier R\"\n  shows \"subgroup (line_extension K a E) (add_monoid R)\"\nproof (rule add.subgroupI)\n  show \"line_extension K a E \\<subseteq> carrier R\"\n    by (simp add: assms add.subgroupE(1) line_extension_def r_coset_subset_G set_add_closed)\nnext\n  have \"\\<zero> = \\<zero> \\<otimes> a \\<oplus> \\<zero>\"\n    using assms(2) by simp\n  hence \"\\<zero> \\<in> line_extension K a E\"\n    using line_extension_mem_iff subgroup.one_closed[OF assms(1)] by auto\n  thus \"line_extension K a E \\<noteq> {}\" by auto\nnext\n  fix u1 u2\n  assume \"u1 \\<in> line_extension K a E\" and \"u2 \\<in> line_extension K a E\"\n  then obtain k1 k2 v1 v2\n    where u1: \"k1 \\<in> K\" \"v1 \\<in> E\" \"u1 = (k1 \\<otimes> a) \\<oplus> v1\"\n      and u2: \"k2 \\<in> K\" \"v2 \\<in> E\" \"u2 = (k2 \\<otimes> a) \\<oplus> v2\"\n      and in_carr: \"k1 \\<in> carrier R\" \"v1 \\<in> carrier R\" \"k2 \\<in> carrier R\" \"v2 \\<in> carrier R\"\n    using line_extension_mem_iff by (meson add.subgroupE(1)[OF assms(1)] subring_props(1) subsetCE)\n\n  hence \"u1 \\<oplus> u2 = ((k1 \\<oplus> k2) \\<otimes> a) \\<oplus> (v1 \\<oplus> v2)\"\n    using assms(2) by algebra\n  moreover have \"k1 \\<oplus> k2 \\<in> K\" and \"v1 \\<oplus> v2 \\<in> E\"\n    using add.subgroupE(4)[OF assms(1)] u1 u2 by auto\n  ultimately show \"u1 \\<oplus> u2 \\<in> line_extension K a E\"\n    using line_extension_mem_iff by auto\n\n  have \"\\<ominus> u1 = ((\\<ominus> k1) \\<otimes> a) \\<oplus> (\\<ominus> v1)\"\n    using in_carr(1-2) u1(3) assms(2) by algebra\n  moreover have \"\\<ominus> k1 \\<in> K\" and \"\\<ominus> v1 \\<in> E\"\n    using add.subgroupE(3)[OF assms(1)] u1 by auto\n  ultimately show \"(\\<ominus> u1) \\<in> line_extension K a E\"\n    using line_extension_mem_iff by auto\nqed\n\ncorollary Span_is_add_subgroup:\n  \"set Us \\<subseteq> carrier R \\<Longrightarrow> subgroup (Span K Us) (add_monoid R)\"\n  using line_extension_is_subgroup normal_imp_subgroup[OF add.one_is_normal] by (induct Us) (auto)\n\nlemma line_extension_smult_closed:\n  assumes \"\\<And>k v. \\<lbrakk> k \\<in> K; v \\<in> E \\<rbrakk> \\<Longrightarrow> k \\<otimes> v \\<in> E\" and \"E \\<subseteq> carrier R\" \"a \\<in> carrier R\"\n  shows \"\\<And>k u. \\<lbrakk> k \\<in> K; u \\<in> line_extension K a E \\<rbrakk> \\<Longrightarrow> k \\<otimes> u \\<in> line_extension K a E\"\nproof -\n  fix k u assume A: \"k \\<in> K\" \"u \\<in> line_extension K a E\"\n  then obtain k' v'\n    where u: \"k' \\<in> K\" \"v' \\<in> E\" \"u = k' \\<otimes> a \\<oplus> v'\"\n      and in_carr: \"k \\<in> carrier R\" \"k' \\<in> carrier R\" \"v' \\<in> carrier R\"\n    using line_extension_mem_iff assms(2) by (meson subring_props(1) subsetCE)\n  hence \"k \\<otimes> u = (k \\<otimes> k') \\<otimes> a \\<oplus> (k \\<otimes> v')\"\n    using assms(3) by algebra\n  thus \"k \\<otimes> u \\<in> line_extension K a E\"\n    using assms(1)[OF A(1) u(2)] line_extension_mem_iff u(1) A(1) by auto\nqed\n\nlemma Span_subgroup_props [simp]:\n  assumes \"set Us \\<subseteq> carrier R\"\n  shows \"Span K Us \\<subseteq> carrier R\"\n    and \"\\<zero> \\<in> Span K Us\"\n    and \"\\<And>v1 v2. \\<lbrakk> v1 \\<in> Span K Us; v2 \\<in> Span K Us \\<rbrakk> \\<Longrightarrow> (v1 \\<oplus> v2) \\<in> Span K Us\"\n    and \"\\<And>v. v \\<in> Span K Us \\<Longrightarrow> (\\<ominus> v) \\<in> Span K Us\"\n  using add.subgroupE subgroup.one_closed[of _ \"add_monoid R\"]\n        Span_is_add_subgroup[OF assms(1)] by auto\n\nlemma Span_smult_closed [simp]:\n  assumes \"set Us \\<subseteq> carrier R\"\n  shows \"\\<And>k v. \\<lbrakk> k \\<in> K; v \\<in> Span K Us \\<rbrakk> \\<Longrightarrow> k \\<otimes> v \\<in> Span K Us\"\n  using assms\nproof (induct Us)\n  case Nil thus ?case\n    using r_null subring_props(1) by (auto, blast)\nnext\n  case Cons thus ?case\n    using Span_subgroup_props(1) line_extension_smult_closed by auto\nqed\n\nlemma Span_m_inv_simprule [simp]:\n  assumes \"set Us \\<subseteq> carrier R\"\n  shows \"\\<lbrakk> k \\<in> K - { \\<zero> }; a \\<in> carrier R \\<rbrakk> \\<Longrightarrow> k \\<otimes> a \\<in> Span K Us \\<Longrightarrow> a \\<in> Span K Us\"\nproof -\n  assume k: \"k \\<in> K - { \\<zero> }\" and a: \"a \\<in> carrier R\" and ka: \"k \\<otimes> a \\<in> Span K Us\"\n  have inv_k: \"inv k \\<in> K\" \"inv k \\<otimes> k = \\<one>\"\n    using subfield_m_inv[OF K k] by simp+\n  hence \"inv k \\<otimes> (k \\<otimes> a) \\<in> Span K Us\"\n    using Span_smult_closed[OF assms _ ka] by simp\n  thus ?thesis\n    using inv_k subring_props(1)a k\n    by (metis (no_types, lifting) DiffE l_one m_assoc subset_iff)\nqed\n\n\nsubsection \\<open>Span as Linear Combinations\\<close>\n\ntext \\<open>We show that Span is the set of linear combinations\\<close>\n\nlemma line_extension_of_combine_set:\n  assumes \"u \\<in> carrier R\"\n  shows \"line_extension K u { combine Ks Us | Ks. set Ks \\<subseteq> K } =\n                { combine Ks (u # Us) | Ks. set Ks \\<subseteq> K }\"\n  (is \"?line_extension = ?combinations\")\nproof\n  show \"?line_extension \\<subseteq> ?combinations\"\n  proof\n    fix v assume \"v \\<in> ?line_extension\"\n    then obtain k Ks\n      where \"k \\<in> K\" \"set Ks \\<subseteq> K\" and \"v = combine (k # Ks) (u # Us)\"\n      using line_extension_mem_iff by auto\n    thus \"v \\<in> ?combinations\"\n      by (metis (mono_tags, lifting) insert_subset list.simps(15) mem_Collect_eq)\n  qed\nnext\n  show \"?combinations \\<subseteq> ?line_extension\"\n  proof\n    fix v assume \"v \\<in> ?combinations\"\n    then obtain Ks where v: \"set Ks \\<subseteq> K\" \"v = combine Ks (u # Us)\"\n      by auto\n    thus \"v \\<in> ?line_extension\"\n    proof (cases Ks)\n      case Cons thus ?thesis\n        using v line_extension_mem_iff by auto\n    next\n      case Nil\n      hence \"v = \\<zero>\"\n        using v by simp\n      moreover have \"combine [] Us = \\<zero>\" by simp\n      hence \"\\<zero> \\<in> { combine Ks Us | Ks. set Ks \\<subseteq> K }\"\n        by (metis (mono_tags, lifting) local.Nil mem_Collect_eq v(1))\n      hence \"(\\<zero> \\<otimes> u) \\<oplus> \\<zero> \\<in> ?line_extension\"\n        using line_extension_mem_iff subring_props(2) by blast\n      hence \"\\<zero> \\<in> ?line_extension\"\n        using assms by auto\n      ultimately show ?thesis by auto\n    qed\n  qed\nqed\n\nlemma Span_eq_combine_set:\n  assumes \"set Us \\<subseteq> carrier R\" shows \"Span K Us = { combine Ks Us | Ks. set Ks \\<subseteq> K }\"\n  using assms line_extension_of_combine_set\n  by (induct Us) (auto, metis empty_set empty_subsetI)\n\nlemma line_extension_of_combine_set_length_version:\n  assumes \"u \\<in> carrier R\"\n  shows \"line_extension K u { combine Ks Us | Ks. length Ks = length Us \\<and> set Ks \\<subseteq> K } =\n                      { combine Ks (u # Us) | Ks. length Ks = length (u # Us) \\<and> set Ks \\<subseteq> K }\"\n  (is \"?line_extension = ?combinations\")\nproof\n  show \"?line_extension \\<subseteq> ?combinations\"\n  proof\n    fix v assume \"v \\<in> ?line_extension\"\n    then obtain k Ks\n      where \"v = combine (k # Ks) (u # Us)\" \"length (k # Ks) = length (u # Us)\" \"set (k # Ks) \\<subseteq> K\"\n      using line_extension_mem_iff by auto\n    thus \"v \\<in> ?combinations\" by blast\n  qed\nnext\n  show \"?combinations \\<subseteq> ?line_extension\"\n  proof\n    fix c assume \"c \\<in> ?combinations\"\n    then obtain Ks where c: \"c = combine Ks (u # Us)\" \"length Ks = length (u # Us)\" \"set Ks \\<subseteq> K\"\n      by blast\n    then obtain k Ks' where k: \"Ks = k # Ks'\"\n      by (metis length_Suc_conv)\n    thus \"c \\<in> ?line_extension\"\n      using c line_extension_mem_iff unfolding k by auto\n  qed\nqed\n\nlemma Span_eq_combine_set_length_version:\n  assumes \"set Us \\<subseteq> carrier R\"\n  shows \"Span K Us = { combine Ks Us | Ks. length Ks = length Us \\<and> set Ks \\<subseteq> K }\"\n  using assms line_extension_of_combine_set_length_version by (induct Us) (auto)\n\n\nsubsubsection \\<open>Corollaries\\<close>\n\ncorollary Span_mem_iff_length_version:\n  assumes \"set Us \\<subseteq> carrier R\"\n  shows \"a \\<in> Span K Us \\<longleftrightarrow> (\\<exists>Ks. set Ks \\<subseteq> K \\<and> length Ks = length Us \\<and> a = combine Ks Us)\"\n  using Span_eq_combine_set_length_version[OF assms] by blast\n\ncorollary Span_mem_imp_non_trivial_combine:\n  assumes \"set Us \\<subseteq> carrier R\" and \"a \\<in> Span K Us\"\n  obtains k Ks\n  where \"k \\<in> K - { \\<zero> }\" \"set Ks \\<subseteq> K\" \"length Ks = length Us\" \"combine (k # Ks) (a # Us) = \\<zero>\"\nproof -\n  obtain Ks where Ks: \"set Ks \\<subseteq> K\" \"length Ks = length Us\" \"a = combine Ks Us\"\n    using Span_mem_iff_length_version[OF assms(1)] assms(2) by auto\n  hence \"((\\<ominus> \\<one>) \\<otimes> a) \\<oplus> a = combine ((\\<ominus> \\<one>) # Ks) (a # Us)\"\n    by auto\n  moreover have \"((\\<ominus> \\<one>) \\<otimes> a) \\<oplus> a = \\<zero>\"\n    using assms(2) Span_subgroup_props(1)[OF assms(1)] l_minus l_neg by auto  \n  moreover have \"\\<ominus> \\<one> \\<noteq> \\<zero>\"\n    using subfieldE(6)[OF K] l_neg by force \n  ultimately show ?thesis\n    using that subring_props(3,5) Ks(1-2) by (force simp del: combine.simps)\nqed\n\ncorollary Span_mem_iff:\n  assumes \"set Us \\<subseteq> carrier R\" and \"a \\<in> carrier R\"\n  shows \"a \\<in> Span K Us \\<longleftrightarrow> (\\<exists>k \\<in> K - { \\<zero> }. \\<exists>Ks. set Ks \\<subseteq> K \\<and> combine (k # Ks) (a # Us) = \\<zero>)\"\n         (is \"?in_Span \\<longleftrightarrow> ?exists_combine\")\nproof\n  assume \"?in_Span\"\n  then obtain Ks where Ks: \"set Ks \\<subseteq> K\" \"a = combine Ks Us\"\n    using Span_eq_combine_set[OF assms(1)] by auto\n  hence \"((\\<ominus> \\<one>) \\<otimes> a) \\<oplus> a = combine ((\\<ominus> \\<one>) # Ks) (a # Us)\"\n    by auto\n  moreover have \"((\\<ominus> \\<one>) \\<otimes> a) \\<oplus> a = \\<zero>\"\n    using assms(2) l_minus l_neg by auto\n  moreover have \"\\<ominus> \\<one> \\<noteq> \\<zero>\"\n    using subfieldE(6)[OF K] l_neg by force\n  ultimately show \"?exists_combine\"\n    using subring_props(3,5) Ks(1) by (force simp del: combine.simps)\nnext\n  assume \"?exists_combine\"\n  then obtain k Ks\n    where k: \"k \\<in> K\" \"k \\<noteq> \\<zero>\" and Ks: \"set Ks \\<subseteq> K\" and a: \"(k \\<otimes> a) \\<oplus> combine Ks Us = \\<zero>\"\n    by auto\n  hence \"combine Ks Us \\<in> Span K Us\"\n    using Span_eq_combine_set[OF assms(1)] by auto\n  hence \"k \\<otimes> a \\<in> Span K Us\"\n    using Span_subgroup_props[OF assms(1)] k Ks a\n    by (metis (no_types, lifting) assms(2) contra_subsetD m_closed minus_equality subring_props(1))\n  thus \"?in_Span\"\n    using Span_m_inv_simprule[OF assms(1) _ assms(2), of k] k by auto\nqed\n\n\nsubsection \\<open>Span as the minimal subgroup that contains \\<^term>\\<open>K <#> (set Us)\\<close>\\<close>\n\ntext \\<open>Now we show the link between Span and Group.generate\\<close>\n\nlemma mono_Span:\n  assumes \"set Us \\<subseteq> carrier R\" and \"u \\<in> carrier R\"\n  shows \"Span K Us \\<subseteq> Span K (u # Us)\"\nproof\n  fix v assume v: \"v \\<in> Span K Us\"\n  hence \"(\\<zero> \\<otimes> u) \\<oplus> v \\<in> Span K (u # Us)\"\n    using line_extension_mem_iff by auto\n  thus \"v \\<in> Span K (u # Us)\"\n    using Span_subgroup_props(1)[OF assms(1)] assms(2) v\n    by (auto simp del: Span.simps)\nqed\n\nlemma Span_min:\n  assumes \"set Us \\<subseteq> carrier R\" and \"subgroup E (add_monoid R)\"\n  shows \"K <#> (set Us) \\<subseteq> E \\<Longrightarrow> Span K Us \\<subseteq> E\"\nproof -\n  assume \"K <#> (set Us) \\<subseteq> E\" show \"Span K Us \\<subseteq> E\"\n  proof\n    fix v assume \"v \\<in> Span K Us\"\n    then obtain Ks where v: \"set Ks \\<subseteq> K\" \"v = combine Ks Us\"\n      using Span_eq_combine_set[OF assms(1)] by auto\n    from \\<open>set Ks \\<subseteq> K\\<close> \\<open>set Us \\<subseteq> carrier R\\<close> and \\<open>K <#> (set Us) \\<subseteq> E\\<close>\n    show \"v \\<in> E\" unfolding v(2)\n    proof (induct Ks Us rule: combine.induct)\n      case (1 k Ks u Us)\n      hence \"k \\<in> K\" and \"u \\<in> set (u # Us)\" by auto\n      hence \"k \\<otimes> u \\<in> E\"\n        using 1(4) unfolding set_mult_def by auto\n      moreover have \"K <#> set Us \\<subseteq> E\"\n        using 1(4) unfolding set_mult_def by auto\n      hence \"combine Ks Us \\<in> E\"\n        using 1 by auto\n      ultimately show ?case\n        using add.subgroupE(4)[OF assms(2)] by auto\n    next\n      case \"2_1\" thus ?case\n        using subgroup.one_closed[OF assms(2)] by auto\n    next\n      case  \"2_2\" thus ?case\n        using subgroup.one_closed[OF assms(2)] by auto\n    qed\n  qed\nqed\n\nlemma Span_eq_generate:\n  assumes \"set Us \\<subseteq> carrier R\" shows \"Span K Us = generate (add_monoid R) (K <#> (set Us))\"\nproof (rule add.generateI)\n  show \"subgroup (Span K Us) (add_monoid R)\"\n    using Span_is_add_subgroup[OF assms] .\nnext\n  show \"\\<And>E. \\<lbrakk> subgroup E (add_monoid R); K <#> set Us \\<subseteq> E \\<rbrakk> \\<Longrightarrow> Span K Us \\<subseteq> E\"\n    using Span_min assms by blast\nnext\n  show \"K <#> set Us \\<subseteq> Span K Us\"\n  using assms\n  proof (induct Us)\n    case Nil thus ?case\n      unfolding set_mult_def by auto\n  next\n    case (Cons u Us)\n    have \"K <#> set (u # Us) = (K <#> { u }) \\<union> (K <#> set Us)\"\n      unfolding set_mult_def by auto\n    moreover have \"\\<And>k. k \\<in> K \\<Longrightarrow> k \\<otimes> u \\<in> Span K (u # Us)\"\n    proof -\n      fix k assume k: \"k \\<in> K\"\n      hence \"combine [ k ] (u # Us) \\<in> Span K (u # Us)\"\n        using Span_eq_combine_set[OF Cons(2)] by (auto simp del: combine.simps)\n      moreover have \"k \\<in> carrier R\" and \"u \\<in> carrier R\"\n        using Cons(2) k subring_props(1) by (blast, auto)\n      ultimately show \"k \\<otimes> u \\<in> Span K (u # Us)\"\n        by (auto simp del: Span.simps)\n    qed\n    hence \"K <#> { u } \\<subseteq> Span K (u # Us)\"\n      unfolding set_mult_def by auto\n    moreover have \"K <#> set Us \\<subseteq> Span K (u # Us)\"\n      using mono_Span[of Us u] Cons by (auto simp del: Span.simps)\n    ultimately show ?case\n      using Cons by (auto simp del: Span.simps)\n  qed\nqed\n\n\nsubsubsection \\<open>Corollaries\\<close>\n\ncorollary Span_same_set:\n  assumes \"set Us \\<subseteq> carrier R\"\n  shows \"set Us = set Vs \\<Longrightarrow> Span K Us = Span K Vs\"\n  using Span_eq_generate assms by auto\n\ncorollary Span_incl: \"set Us \\<subseteq> carrier R \\<Longrightarrow> K <#> (set Us) \\<subseteq> Span K Us\"\n  using Span_eq_generate generate.incl[of _ _ \"add_monoid R\"] by auto\n\ncorollary Span_base_incl: \"set Us \\<subseteq> carrier R \\<Longrightarrow> set Us \\<subseteq> Span K Us\"\nproof -\n  assume A: \"set Us \\<subseteq> carrier R\"\n  hence \"{ \\<one> } <#> set Us = set Us\"\n    unfolding set_mult_def by force\n  moreover have \"{ \\<one> } <#> set Us \\<subseteq> K <#> set Us\"\n    using subring_props(3) unfolding set_mult_def by blast\n  ultimately show ?thesis\n    using Span_incl[OF A] by auto\nqed\n\ncorollary mono_Span_sublist:\n  assumes \"set Us \\<subseteq> set Vs\" \"set Vs \\<subseteq> carrier R\"\n  shows \"Span K Us \\<subseteq> Span K Vs\"\n  using add.mono_generate[OF mono_set_mult[OF _ assms(1), of K K R]]\n        Span_eq_generate[OF assms(2)] Span_eq_generate[of Us] assms by auto\n\ncorollary mono_Span_append:\n  assumes \"set Us \\<subseteq> carrier R\" \"set Vs \\<subseteq> carrier R\"\n  shows \"Span K Us \\<subseteq> Span K (Us @ Vs)\"\n    and \"Span K Us \\<subseteq> Span K (Vs @ Us)\"\n  using mono_Span_sublist[of Us \"Us @ Vs\"] assms\n        Span_same_set[of \"Us @ Vs\" \"Vs @ Us\"] by auto\n\ncorollary mono_Span_subset:\n  assumes \"set Us \\<subseteq> Span K Vs\" \"set Vs \\<subseteq> carrier R\"\n  shows \"Span K Us \\<subseteq> Span K Vs\"\nproof (rule Span_min[OF _ Span_is_add_subgroup[OF assms(2)]])\n  show \"set Us \\<subseteq> carrier R\"\n    using Span_subgroup_props(1)[OF assms(2)] assms by auto\n  show \"K <#> set Us \\<subseteq> Span K Vs\"\n    using Span_smult_closed[OF assms(2)] assms(1) unfolding set_mult_def by blast\nqed\n\nlemma Span_strict_incl:\n  assumes \"set Us \\<subseteq> carrier R\" \"set Vs \\<subseteq> carrier R\"\n  shows \"Span K Us \\<subset> Span K Vs \\<Longrightarrow> (\\<exists>v \\<in> set Vs. v \\<notin> Span K Us)\"\nproof -\n  assume \"Span K Us \\<subset> Span K Vs\" show \"\\<exists>v \\<in> set Vs. v \\<notin> Span K Us\"\n  proof (rule ccontr)\n    assume \"\\<not> (\\<exists>v \\<in> set Vs. v \\<notin> Span K Us)\"\n    hence \"Span K Vs \\<subseteq> Span K Us\"\n      using mono_Span_subset[OF _ assms(1), of Vs] by auto\n    from \\<open>Span K Us \\<subset> Span K Vs\\<close> and \\<open>Span K Vs \\<subseteq> Span K Us\\<close>\n    show False by simp\n  qed\nqed\n\nlemma Span_append_eq_set_add:\n  assumes \"set Us \\<subseteq> carrier R\" and \"set Vs \\<subseteq> carrier R\"\n  shows \"Span K (Us @ Vs) = (Span K Us <+>\\<^bsub>R\\<^esub> Span K Vs)\"\n  using assms\nproof (induct Us)\n  case Nil thus ?case\n    using Span_subgroup_props(1)[OF Nil(2)] unfolding set_add_def' by force\nnext\n  case (Cons u Us)\n  hence in_carrier:\n    \"u \\<in> carrier R\" \"set Us \\<subseteq> carrier R\" \"set Vs \\<subseteq> carrier R\"\n    by auto\n\n  have \"line_extension K u (Span K Us <+>\\<^bsub>R\\<^esub> Span K Vs) = (Span K (u # Us) <+>\\<^bsub>R\\<^esub> Span K Vs)\"\n  proof\n    show \"line_extension K u (Span K Us <+>\\<^bsub>R\\<^esub> Span K Vs) \\<subseteq> (Span K (u # Us) <+>\\<^bsub>R\\<^esub> Span K Vs)\"\n    proof\n      fix v assume \"v \\<in> line_extension K u (Span K Us <+>\\<^bsub>R\\<^esub> Span K Vs)\"\n      then obtain k u' v'\n        where v: \"k \\<in> K\" \"u' \\<in> Span K Us\" \"v' \\<in> Span K Vs\" \"v = k \\<otimes> u \\<oplus> (u' \\<oplus> v')\"\n        using line_extension_mem_iff[of v _ u \"Span K Us <+>\\<^bsub>R\\<^esub> Span K Vs\"]\n        unfolding set_add_def' by blast\n      hence \"v = (k \\<otimes> u \\<oplus> u') \\<oplus> v'\"\n        using in_carrier(2-3)[THEN Span_subgroup_props(1)] in_carrier(1) subring_props(1)\n        by (metis (no_types, lifting) rev_subsetD ring_simprules(7) semiring_simprules(3))\n      moreover have \"k \\<otimes> u \\<oplus> u' \\<in> Span K (u # Us)\"\n        using line_extension_mem_iff v(1-2) by auto\n      ultimately show \"v \\<in> Span K (u # Us) <+>\\<^bsub>R\\<^esub> Span K Vs\"\n        unfolding set_add_def' using v(3) by auto\n    qed\n  next\n    show \"Span K (u # Us) <+>\\<^bsub>R\\<^esub> Span K Vs \\<subseteq> line_extension K u (Span K Us <+>\\<^bsub>R\\<^esub> Span K Vs)\"\n    proof\n      fix v assume \"v \\<in> Span K (u # Us) <+>\\<^bsub>R\\<^esub> Span K Vs\"\n      then obtain k u' v'\n        where v: \"k \\<in> K\" \"u' \\<in> Span K Us\" \"v' \\<in> Span K Vs\" \"v = (k \\<otimes> u \\<oplus> u') \\<oplus> v'\"\n        using line_extension_mem_iff[of _ _ u \"Span K Us\"] unfolding set_add_def' by auto\n      hence \"v = (k \\<otimes> u) \\<oplus> (u' \\<oplus> v')\"\n        using in_carrier(2-3)[THEN Span_subgroup_props(1)] in_carrier(1) subring_props(1)\n        by (metis (no_types, lifting) rev_subsetD ring_simprules(5,7))\n      thus \"v \\<in> line_extension K u (Span K Us <+>\\<^bsub>R\\<^esub> Span K Vs)\"\n        using line_extension_mem_iff[of \"(k \\<otimes> u) \\<oplus> (u' \\<oplus> v')\" K u \"Span K Us <+>\\<^bsub>R\\<^esub> Span K Vs\"]\n        unfolding set_add_def' using v by auto\n    qed\n  qed\n  thus ?case\n    using Cons by auto\nqed\n\n\nsubsection \\<open>Characterisation of Linearly Independent \"Sets\"\\<close>\n\ndeclare independent_backwards [intro]\ndeclare independent_in_carrier [intro]\n\nlemma independent_distinct: \"independent K Us \\<Longrightarrow> distinct Us\"\nproof (induct Us rule: list.induct)\n  case Nil thus ?case by simp\nnext\n  case Cons thus ?case\n    using independent_backwards[OF Cons(2)]\n          independent_in_carrier[OF Cons(2)]\n          Span_base_incl\n    by auto\nqed\n\nlemma independent_strict_incl:\n  assumes \"independent K (u # Us)\" shows \"Span K Us \\<subset> Span K (u # Us)\"\nproof -\n  have \"u \\<in> Span K (u # Us)\"\n    using Span_base_incl[OF independent_in_carrier[OF assms]] by auto\n  moreover have \"Span K Us \\<subseteq> Span K (u # Us)\"\n    using mono_Span independent_in_carrier[OF assms] by auto\n  ultimately show ?thesis\n    using independent_backwards(1)[OF assms] by auto\nqed\n\ncorollary independent_replacement:\n  assumes \"independent K (u # Us)\" and \"independent K Vs\"\n  shows \"Span K (u # Us) \\<subseteq> Span K Vs \\<Longrightarrow> (\\<exists>v \\<in> set Vs. independent K (v # Us))\"\nproof -\n  assume \"Span K (u # Us) \\<subseteq> Span K Vs\"\n  hence \"Span K Us \\<subset> Span K Vs\"\n    using independent_strict_incl[OF assms(1)] by auto\n  then obtain v where v: \"v \\<in> set Vs\" \"v \\<notin> Span K Us\"\n    using Span_strict_incl[of Us Vs] assms[THEN independent_in_carrier] by auto\n  thus ?thesis\n    using li_Cons[of v K Us] assms independent_in_carrier[OF assms(2)] by auto\nqed\n\nlemma independent_split:\n  assumes \"independent K (Us @ Vs)\"\n  shows \"independent K Vs\"\n    and \"independent K Us\"\n    and \"Span K Us \\<inter> Span K Vs = { \\<zero> }\"\nproof -\n  from assms show \"independent K Vs\"\n    by (induct Us) (auto)\nnext\n  from assms show \"independent K Us\"\n  proof (induct Us)\n    case Nil thus ?case by simp\n  next\n    case (Cons u Us')\n    hence u: \"u \\<in> carrier R\" and \"set Us' \\<subseteq> carrier R\" \"set Vs \\<subseteq> carrier R\"\n      using independent_in_carrier[of K \"(u # Us') @ Vs\"] by auto\n    hence \"Span K Us' \\<subseteq> Span K (Us' @ Vs)\"\n      using mono_Span_append(1) by simp\n    thus ?case\n      using independent_backwards[of K u \"Us' @ Vs\"] Cons li_Cons[OF u] by auto\n  qed\nnext\n  from assms show \"Span K Us \\<inter> Span K Vs = { \\<zero> }\"\n  proof (induct Us rule: list.induct)\n    case Nil thus ?case\n      using Span_subgroup_props(2)[OF independent_in_carrier[of K Vs]] by simp\n  next\n    case (Cons u Us)\n    hence IH: \"Span K Us \\<inter> Span K Vs = {\\<zero>}\" by auto\n    have in_carrier:\n      \"u \\<in> carrier R\" \"set Us \\<subseteq> carrier R\" \"set Vs \\<subseteq> carrier R\" \"set (u # Us) \\<subseteq> carrier R\"\n      using Cons(2)[THEN independent_in_carrier] by auto\n    hence \"{ \\<zero> } \\<subseteq> Span K (u # Us) \\<inter> Span K Vs\"\n      using in_carrier(3-4)[THEN Span_subgroup_props(2)] by auto\n\n    moreover have \"Span K (u # Us) \\<inter> Span K Vs \\<subseteq> { \\<zero> }\"\n    proof (rule ccontr)\n      assume \"\\<not> Span K (u # Us) \\<inter> Span K Vs \\<subseteq> {\\<zero>}\"\n      hence \"\\<exists>a. a \\<noteq> \\<zero> \\<and> a \\<in> Span K (u # Us) \\<and> a \\<in> Span K Vs\" by auto\n      then obtain k u' v'\n        where u': \"u' \\<in> Span K Us\" \"u' \\<in> carrier R\"\n          and v': \"v' \\<in> Span K Vs\" \"v' \\<in> carrier R\" \"v' \\<noteq> \\<zero>\"\n          and k: \"k \\<in> K\" \"(k \\<otimes> u \\<oplus> u') = v'\"\n        using line_extension_mem_iff[of _ _ u \"Span K Us\"] in_carrier(2-3)[THEN Span_subgroup_props(1)]\n              subring_props(1) by force\n      hence \"v' = \\<zero>\" if \"k = \\<zero>\"\n        using in_carrier(1) that IH by auto\n      hence diff_zero: \"k \\<noteq> \\<zero>\" using v'(3) by auto\n\n      have \"k \\<in> carrier R\"\n        using subring_props(1) k(1) by blast\n      hence \"k \\<otimes> u = (\\<ominus> u') \\<oplus> v'\"\n        using in_carrier(1) k(2) u'(2) v'(2) add.m_comm r_neg1 by auto\n      hence \"k \\<otimes> u \\<in> Span K (Us @ Vs)\"\n        using Span_subgroup_props(4)[OF in_carrier(2) u'(1)] v'(1)\n              Span_append_eq_set_add[OF in_carrier(2-3)] unfolding set_add_def' by blast\n      hence \"u \\<in> Span K (Us @ Vs)\"\n        using Cons(2) Span_m_inv_simprule[OF _ _ in_carrier(1), of \"Us @ Vs\" k]\n              diff_zero k(1) in_carrier(2-3) by auto\n      moreover have \"u \\<notin> Span K (Us @ Vs)\"\n        using independent_backwards(1)[of K u \"Us @ Vs\"] Cons(2) by auto\n      ultimately show False by simp\n    qed\n\n    ultimately show ?case by auto\n  qed\nqed\n\nlemma independent_append:\n  assumes \"independent K Us\" and \"independent K Vs\" and \"Span K Us \\<inter> Span K Vs = { \\<zero> }\"\n  shows \"independent K (Us @ Vs)\"\n  using assms\nproof (induct Us rule: list.induct)\n  case Nil thus ?case by simp\nnext\n  case (Cons u Us)\n  hence in_carrier:\n    \"u \\<in> carrier R\" \"set Us \\<subseteq> carrier R\" \"set Vs \\<subseteq> carrier R\" \"set (u # Us) \\<subseteq> carrier R\"\n    using Cons(2-3)[THEN independent_in_carrier] by auto\n  hence \"Span K Us \\<subseteq> Span K (u # Us)\"\n    using mono_Span by auto\n  hence \"Span K Us \\<inter> Span K Vs = { \\<zero> }\"\n    using Cons(4) Span_subgroup_props(2)[OF in_carrier(2)] by auto\n  hence \"independent K (Us @ Vs)\"\n    using Cons by auto\n  moreover have \"u \\<notin> Span K (Us @ Vs)\"\n  proof (rule ccontr)\n    assume \"\\<not> u \\<notin> Span K (Us @ Vs)\"\n    then obtain u' v'\n      where u': \"u' \\<in> Span K Us\" \"u' \\<in> carrier R\"\n        and v': \"v' \\<in> Span K Vs\" \"v' \\<in> carrier R\" and u:\"u = u' \\<oplus> v'\"\n      using Span_append_eq_set_add[OF in_carrier(2-3)] in_carrier(2-3)[THEN Span_subgroup_props(1)]\n      unfolding set_add_def' by blast\n    hence \"u \\<oplus> (\\<ominus> u') = v'\"\n      using in_carrier(1) by algebra\n    moreover have \"u \\<in> Span K (u # Us)\" and \"u' \\<in> Span K (u # Us)\"\n      using Span_base_incl[OF in_carrier(4)] mono_Span[OF in_carrier(2,1)] u'(1)\n      by (auto simp del: Span.simps)\n    hence \"u \\<oplus> (\\<ominus> u') \\<in> Span K (u # Us)\"\n      using Span_subgroup_props(3-4)[OF in_carrier(4)] by (auto simp del: Span.simps)\n    ultimately have \"u \\<oplus> (\\<ominus> u') = \\<zero>\"\n      using Cons(4) v'(1) by auto\n    hence \"u = u'\"\n      using Cons(4) v'(1) in_carrier(1) u'(2) \\<open>u \\<oplus> \\<ominus> u' = v'\\<close> u by auto\n    thus False\n      using u'(1) independent_backwards(1)[OF Cons(2)] by simp\n  qed\n  ultimately show ?case\n    using in_carrier(1) li_Cons by simp\nqed\n\nlemma independent_imp_trivial_combine:\n  assumes \"independent K Us\"\n  shows \"\\<And>Ks. \\<lbrakk> set Ks \\<subseteq> K; combine Ks Us = \\<zero> \\<rbrakk> \\<Longrightarrow> set (take (length Us) Ks) \\<subseteq> { \\<zero> }\"\n  using assms\nproof (induct Us rule: list.induct)\n  case Nil thus ?case by simp\nnext\n  case (Cons u Us) thus ?case\n  proof (cases \"Ks = []\")\n    assume \"Ks = []\" thus ?thesis by auto\n  next\n    assume \"Ks \\<noteq> []\"\n    then obtain k Ks' where k: \"k \\<in> K\" and Ks': \"set Ks' \\<subseteq> K\" and Ks: \"Ks = k # Ks'\"\n      using Cons(2) by (metis insert_subset list.exhaust_sel list.simps(15))\n    hence Us: \"set Us \\<subseteq> carrier R\" and u: \"u \\<in> carrier R\"\n      using independent_in_carrier[OF Cons(4)] by auto\n    have \"u \\<in> Span K Us\" if \"k \\<noteq> \\<zero>\"\n      using that Span_mem_iff[OF Us u] Cons(3-4) Ks' k unfolding Ks by blast\n    hence k_zero: \"k = \\<zero>\"\n      using independent_backwards[OF Cons(4)] by blast\n    hence \"combine Ks' Us = \\<zero>\"\n      using combine_in_carrier[OF _ Us, of Ks'] Ks' u Cons(3) subring_props(1) unfolding Ks by auto\n    hence \"set (take (length Us) Ks') \\<subseteq> { \\<zero> }\"\n      using Cons(1)[OF Ks' _ independent_backwards(2)[OF Cons(4)]] by simp\n    thus ?thesis\n      using k_zero unfolding Ks by auto\n  qed\nqed\n\nlemma non_trivial_combine_imp_dependent:\n  assumes \"set Ks \\<subseteq> K\" and \"combine Ks Us = \\<zero>\" and \"\\<not> set (take (length Us) Ks) \\<subseteq> { \\<zero> }\"\n  shows \"dependent K Us\"\n  using independent_imp_trivial_combine[OF _ assms(1-2)] assms(3) by blast  \n\nlemma trivial_combine_imp_independent:\n  assumes \"set Us \\<subseteq> carrier R\"\n    and \"\\<And>Ks. \\<lbrakk> set Ks \\<subseteq> K; combine Ks Us = \\<zero> \\<rbrakk> \\<Longrightarrow> set (take (length Us) Ks) \\<subseteq> { \\<zero> }\"\n  shows \"independent K Us\"\n  using assms\nproof (induct Us)\n  case Nil thus ?case by simp\nnext\n  case (Cons u Us)\n  hence Us: \"set Us \\<subseteq> carrier R\" and u: \"u \\<in> carrier R\" by auto\n\n  have \"\\<And>Ks. \\<lbrakk> set Ks \\<subseteq> K; combine Ks Us = \\<zero> \\<rbrakk> \\<Longrightarrow> set (take (length Us) Ks) \\<subseteq> { \\<zero> }\"\n  proof -\n    fix Ks assume Ks: \"set Ks \\<subseteq> K\" and lin_c: \"combine Ks Us = \\<zero>\"\n    hence \"combine (\\<zero> # Ks) (u # Us) = \\<zero>\"\n      using u subring_props(1) combine_in_carrier[OF _ Us] by auto\n    hence \"set (take (length (u # Us)) (\\<zero> # Ks)) \\<subseteq> { \\<zero> }\"\n      using Cons(3)[of \"\\<zero> # Ks\"] subring_props(2) Ks by auto\n    thus \"set (take (length Us) Ks) \\<subseteq> { \\<zero> }\" by auto\n  qed\n  hence \"independent K Us\"\n    using Cons(1)[OF Us] by simp\n\n  moreover have \"u \\<notin> Span K Us\"\n  proof (rule ccontr)\n    assume \"\\<not> u \\<notin> Span K Us\"\n    then obtain k Ks where k: \"k \\<in> K\" \"k \\<noteq> \\<zero>\" and Ks: \"set Ks \\<subseteq> K\" and u: \"combine (k # Ks) (u # Us) = \\<zero>\"\n      using Span_mem_iff[OF Us u] by auto\n    have \"set (take (length (u # Us)) (k # Ks)) \\<subseteq> { \\<zero> }\"\n      using Cons(3)[OF _ u] k(1) Ks by auto\n    hence \"k = \\<zero>\" by auto\n    from \\<open>k = \\<zero>\\<close> and \\<open>k \\<noteq> \\<zero>\\<close> show False by simp\n  qed\n\n  ultimately show ?case\n    using li_Cons[OF u] by simp\nqed\n\ncorollary dependent_imp_non_trivial_combine:\n  assumes \"set Us \\<subseteq> carrier R\" and \"dependent K Us\"\n  obtains Ks where \"length Ks = length Us\" \"combine Ks Us = \\<zero>\" \"set Ks \\<subseteq> K\" \"set Ks \\<noteq> { \\<zero> }\"\nproof -\n  obtain Ks\n    where Ks: \"set Ks \\<subseteq> carrier R\" \"set Ks \\<subseteq> K\" \"combine Ks Us = \\<zero>\" \"\\<not> set (take (length Us) Ks) \\<subseteq> { \\<zero> }\"\n    using trivial_combine_imp_independent[OF assms(1)] assms(2) subring_props(1) by blast\n  obtain Ks'\n    where Ks': \"set (take (length Us) Ks) \\<subseteq> set Ks'\" \"set Ks' \\<subseteq> set (take (length Us) Ks) \\<union> { \\<zero> }\"\n               \"length Ks' = length Us\" \"combine Ks' Us = \\<zero>\"\n    using combine_normalize[OF Ks(1) assms(1) Ks(3)] by metis\n  have \"set (take (length Us) Ks) \\<subseteq> set Ks\"\n    by (simp add: set_take_subset) \n  hence \"set Ks' \\<subseteq> K\"\n    using Ks(2) Ks'(2) subring_props(2) Un_commute by blast\n  moreover have \"set Ks' \\<noteq> { \\<zero> }\"\n    using Ks'(1) Ks(4) by auto\n  ultimately show thesis\n    using that Ks' by blast\nqed\n\ncorollary unique_decomposition:\n  assumes \"independent K Us\"\n  shows \"a \\<in> Span K Us \\<Longrightarrow> \\<exists>!Ks. set Ks \\<subseteq> K \\<and> length Ks = length Us \\<and> a = combine Ks Us\"\nproof -\n  note in_carrier = independent_in_carrier[OF assms]\n\n  assume \"a \\<in> Span K Us\"\n  then obtain Ks where Ks: \"set Ks \\<subseteq> K\" \"length Ks = length Us\" \"a = combine Ks Us\"\n    using Span_mem_iff_length_version[OF in_carrier] by blast\n\n  moreover\n  have \"\\<And>Ks'. \\<lbrakk> set Ks' \\<subseteq> K; length Ks' = length Us; a = combine Ks' Us \\<rbrakk> \\<Longrightarrow> Ks = Ks'\"\n  proof -\n    fix Ks' assume Ks': \"set Ks' \\<subseteq> K\" \"length Ks' = length Us\" \"a = combine Ks' Us\"\n    hence set_Ks: \"set Ks \\<subseteq> carrier R\" and set_Ks': \"set Ks' \\<subseteq> carrier R\"\n      using subring_props(1) Ks(1) by blast+\n    have same_length: \"length Ks = length Ks'\"\n      using Ks Ks' by simp\n\n    have \"(combine Ks Us) \\<oplus> ((\\<ominus> \\<one>) \\<otimes> (combine Ks' Us)) = \\<zero>\"\n      using combine_in_carrier[OF set_Ks  in_carrier]\n            combine_in_carrier[OF set_Ks' in_carrier] Ks(3) Ks'(3) by algebra\n    hence \"(combine Ks Us) \\<oplus> (combine (map ((\\<otimes>) (\\<ominus> \\<one>)) Ks') Us) = \\<zero>\"\n      using combine_r_distr[OF set_Ks' in_carrier, of \"\\<ominus> \\<one>\"] subring_props by auto\n    moreover have set_map: \"set (map ((\\<otimes>) (\\<ominus> \\<one>)) Ks') \\<subseteq> K\"\n      using Ks'(1) subring_props by (induct Ks') (auto)\n    hence \"set (map ((\\<otimes>) (\\<ominus> \\<one>)) Ks') \\<subseteq> carrier R\"\n      using subring_props(1) by blast\n    ultimately have \"combine (map2 (\\<oplus>) Ks (map ((\\<otimes>) (\\<ominus> \\<one>)) Ks')) Us = \\<zero>\"\n      using combine_add[OF Ks(2) _ set_Ks _ in_carrier, of \"map ((\\<otimes>) (\\<ominus> \\<one>)) Ks'\"] Ks'(2) by auto\n    moreover have \"set (map2 (\\<oplus>) Ks (map ((\\<otimes>) (\\<ominus> \\<one>)) Ks')) \\<subseteq> K\"\n      using Ks(1) set_map subring_props(7)\n      by (induct Ks) (auto, metis contra_subsetD in_set_zipE local.set_map set_ConsD subring_props(7))\n    ultimately have \"set (take (length Us) (map2 (\\<oplus>) Ks (map ((\\<otimes>) (\\<ominus> \\<one>)) Ks'))) \\<subseteq> { \\<zero> }\"\n      using independent_imp_trivial_combine[OF assms] by auto\n    hence \"set (map2 (\\<oplus>) Ks (map ((\\<otimes>) (\\<ominus> \\<one>)) Ks')) \\<subseteq> { \\<zero> }\"\n      using Ks(2) Ks'(2) by auto\n    thus \"Ks = Ks'\"\n      using set_Ks set_Ks' same_length\n    proof (induct Ks arbitrary: Ks')\n      case Nil thus?case by simp\n    next\n      case (Cons k Ks)\n      then obtain k' Ks'' where k': \"Ks' = k' # Ks''\"\n        by (metis Suc_length_conv)\n      have \"Ks = Ks''\"\n        using Cons unfolding k' by auto\n      moreover have \"k = k'\"\n        using Cons(2-4) l_minus minus_equality unfolding k' by (auto, fastforce)\n      ultimately show ?case\n        unfolding k' by simp\n    qed\n  qed\n\n  ultimately show ?thesis by blast\nqed\n\n\nsubsection \\<open>Replacement Theorem\\<close>\n\nlemma independent_rotate1_aux:\n  \"independent K (u # Us @ Vs) \\<Longrightarrow> independent K ((Us @ [u]) @ Vs)\"\nproof -\n  assume \"independent K (u # Us @ Vs)\"\n  hence li: \"independent K [u]\" \"independent K Us\" \"independent K Vs\"\n    and inter: \"Span K [u] \\<inter> Span K Us = { \\<zero> }\"\n               \"Span K (u # Us) \\<inter> Span K Vs = { \\<zero> }\"\n    using independent_split[of \"u # Us\" Vs] independent_split[of \"[u]\" Us] by auto\n  hence \"independent K (Us @ [u])\"\n    using independent_append[OF li(2,1)] by auto\n  moreover have \"Span K (Us @ [u]) \\<inter> Span K Vs = { \\<zero> }\"\n    using Span_same_set[of \"u # Us\" \"Us @ [u]\"] li(1-2)[THEN independent_in_carrier] inter(2) by auto\n  ultimately show \"independent K ((Us @ [u]) @ Vs)\"\n    using independent_append[OF _ li(3), of \"Us @ [u]\"] by simp\nqed\n\ncorollary independent_rotate1:\n  \"independent K (Us @ Vs) \\<Longrightarrow> independent K ((rotate1 Us) @ Vs)\"\n  using independent_rotate1_aux by (cases Us) (auto)\n\n(*\ncorollary independent_rotate:\n  \"independent K (Us @ Vs) \\<Longrightarrow> independent K ((rotate n Us) @ Vs)\"\n  using independent_rotate1 by (induct n) auto\n\nlemma rotate_append: \"rotate (length l) (l @ q) = q @ l\"\n  by (induct l arbitrary: q) (auto simp add: rotate1_rotate_swap)\n*)\n\ncorollary independent_same_set:\n  assumes \"set Us = set Vs\" and \"length Us = length Vs\"\n  shows \"independent K Us \\<Longrightarrow> independent K Vs\"\nproof -\n  assume \"independent K Us\" thus ?thesis\n    using assms\n  proof (induct Us arbitrary: Vs rule: list.induct)\n    case Nil thus ?case by simp\n  next\n    case (Cons u Us)\n    then obtain Vs' Vs'' where Vs: \"Vs = Vs' @ (u # Vs'')\"\n      by (metis list.set_intros(1) split_list)\n\n    have in_carrier: \"u \\<in> carrier R\" \"set Us \\<subseteq> carrier R\"\n      using independent_in_carrier[OF Cons(2)] by auto\n\n    have \"distinct Vs\"\n      using Cons(3-4) independent_distinct[OF Cons(2)]\n      by (metis card_distinct distinct_card)\n    hence \"u \\<notin> set (Vs' @ Vs'')\" and \"u \\<notin> set Us\"\n      using independent_distinct[OF Cons(2)] unfolding Vs by auto\n    hence set_eq: \"set Us = set (Vs' @ Vs'')\" and \"length (Vs' @ Vs'') = length Us\"\n      using Cons(3-4) unfolding Vs by auto\n    hence \"independent K (Vs' @ Vs'')\"\n      using Cons(1)[OF independent_backwards(2)[OF Cons(2)]] unfolding Vs by simp\n    hence \"independent K (u # (Vs' @ Vs''))\"\n      using li_Cons Span_same_set[OF _ set_eq] independent_backwards(1)[OF Cons(2)] in_carrier by auto\n    hence \"independent K (Vs' @ (u # Vs''))\"\n      using independent_rotate1[of \"u # Vs'\" Vs''] by auto\n    thus ?case unfolding Vs .\n  qed\nqed\n\nlemma replacement_theorem:\n  assumes \"independent K (Us' @ Us)\" and \"independent K Vs\"\n    and \"Span K (Us' @ Us) \\<subseteq> Span K Vs\"\n  shows \"\\<exists>Vs'. set Vs' \\<subseteq> set Vs \\<and> length Vs' = length Us' \\<and> independent K (Vs' @ Us)\"\n  using assms\nproof (induct \"length Us'\" arbitrary: Us' Us)\n  case 0 thus ?case by auto\nnext\n  case (Suc n)\n  then obtain u Us'' where Us'': \"Us' = Us'' @ [u]\"\n    by (metis list.size(3) nat.simps(3) rev_exhaust)\n  then obtain Vs' where Vs': \"set Vs' \\<subseteq> set Vs\" \"length Vs' = n\" \"independent K (Vs' @ (u # Us))\"\n    using Suc(1)[of Us'' \"u # Us\"] Suc(2-5) by auto\n  hence li: \"independent K ((u # Vs') @ Us)\"\n    using independent_same_set[OF _ _ Vs'(3), of \"(u # Vs') @ Us\"] by auto\n  moreover have in_carrier:\n    \"u \\<in> carrier R\" \"set Us \\<subseteq> carrier R\" \"set Us' \\<subseteq> carrier R\" \"set Vs \\<subseteq> carrier R\"\n    using Suc(3-4)[THEN independent_in_carrier] Us'' by auto\n  moreover have \"Span K ((u # Vs') @ Us) \\<subseteq> Span K Vs\"\n  proof -\n    have \"set Us \\<subseteq> Span K Vs\" \"u \\<in> Span K Vs\"\n      using Suc(5) Span_base_incl[of \"Us' @ Us\"] Us'' in_carrier(2-3) by auto\n    moreover have \"set Vs' \\<subseteq> Span K Vs\"\n      using Span_base_incl[OF in_carrier(4)] Vs'(1) by auto\n    ultimately have \"set ((u # Vs') @ Us) \\<subseteq> Span K Vs\" by auto\n    thus ?thesis\n      using mono_Span_subset[OF _ in_carrier(4)] by (simp del: Span.simps)\n  qed\n  ultimately obtain v where \"v \\<in> set Vs\" \"independent K ((v # Vs') @ Us)\"\n    using independent_replacement[OF _ Suc(4), of u \"Vs' @ Us\"] by auto\n  thus ?case\n    using Vs'(1-2) Suc(2)\n    by (metis (mono_tags, lifting) insert_subset length_Cons list.simps(15))\nqed\n\ncorollary independent_length_le:\n  assumes \"independent K Us\" and \"independent K Vs\"\n  shows \"set Us \\<subseteq> Span K Vs \\<Longrightarrow> length Us \\<le> length Vs\"\nproof -\n  assume \"set Us \\<subseteq> Span K Vs\"\n  hence \"Span K Us \\<subseteq> Span K Vs\"\n    using mono_Span_subset[OF _ independent_in_carrier[OF assms(2)]] by simp\n  then obtain Vs' where Vs': \"set Vs' \\<subseteq> set Vs\" \"length Vs' = length Us\" \"independent K Vs'\"\n    using replacement_theorem[OF _ assms(2), of Us \"[]\"] assms(1) by auto\n  hence \"card (set Vs') \\<le> card (set Vs)\"\n    by (simp add: card_mono)\n  thus \"length Us \\<le> length Vs\"\n    using independent_distinct assms(2) Vs'(2-3) by (simp add: distinct_card)\nqed\n\n\nsubsection \\<open>Dimension\\<close>\n\nlemma exists_base:\n  assumes \"dimension n K E\"\n  shows \"\\<exists>Vs. set Vs \\<subseteq> carrier R \\<and> independent K Vs \\<and> length Vs = n \\<and> Span K Vs = E\"\n    (is \"\\<exists>Vs. ?base K Vs E n\")\n  using assms\nproof (induct E rule: dimension.induct)\n  case zero_dim thus ?case by auto\nnext\n  case (Suc_dim v E n K)\n  then obtain Vs where Vs: \"set Vs \\<subseteq> carrier R\" \"independent K Vs\" \"length Vs = n\" \"Span K Vs = E\"\n    by auto\n  hence \"?base K (v # Vs) (line_extension K v E) (Suc n)\"\n    using Suc_dim li_Cons by auto\n  thus ?case by blast\nqed\n\nlemma dimension_zero: \"dimension 0 K E \\<Longrightarrow> E = { \\<zero> }\"\nproof -\n  assume \"dimension 0 K E\"\n  then obtain Vs where \"length Vs = 0\" \"Span K Vs = E\"\n    using exists_base by blast\n  thus ?thesis\n    by auto\nqed\n\nlemma dimension_one [iff]: \"dimension 1 K K\"\nproof -\n  have \"K = Span K [ \\<one> ]\"\n    using line_extension_mem_iff[of _ K \\<one> \"{ \\<zero> }\"] subfieldE(3)[OF K] by (auto simp add: rev_subsetD)\n  thus ?thesis\n    using dimension.Suc_dim[OF one_closed _ dimension.zero_dim, of K] subfieldE(6)[OF K] by auto \nqed\n\nlemma dimensionI:\n  assumes \"independent K Us\" \"Span K Us = E\"\n  shows \"dimension (length Us) K E\"\n  using dimension_independent[OF assms(1)] assms(2) by simp\n\nlemma space_subgroup_props:\n  assumes \"dimension n K E\"\n  shows \"E \\<subseteq> carrier R\"\n    and \"\\<zero> \\<in> E\"\n    and \"\\<And>v1 v2. \\<lbrakk> v1 \\<in> E; v2 \\<in> E \\<rbrakk> \\<Longrightarrow> (v1 \\<oplus> v2) \\<in> E\"\n    and \"\\<And>v. v \\<in> E \\<Longrightarrow> (\\<ominus> v) \\<in> E\"\n    and \"\\<And>k v. \\<lbrakk> k \\<in> K; v \\<in> E \\<rbrakk> \\<Longrightarrow> k \\<otimes> v \\<in> E\"\n    and \"\\<lbrakk> k \\<in> K - { \\<zero> }; a \\<in> carrier R \\<rbrakk> \\<Longrightarrow> k \\<otimes> a \\<in> E \\<Longrightarrow> a \\<in> E\"\n  using exists_base[OF assms] Span_subgroup_props Span_smult_closed Span_m_inv_simprule by auto\n\nlemma independent_length_le_dimension:\n  assumes \"dimension n K E\" and \"independent K Us\" \"set Us \\<subseteq> E\"\n  shows \"length Us \\<le> n\"\nproof -\n  obtain Vs where Vs: \"set Vs \\<subseteq> carrier R\" \"independent K Vs\" \"length Vs = n\" \"Span K Vs = E\"\n    using exists_base[OF assms(1)] by auto\n  thus ?thesis\n    using independent_length_le assms(2-3) by auto\nqed\n\nlemma dimension_is_inj:\n  assumes \"dimension n K E\" and \"dimension m K E\"\n  shows \"n = m\"\nproof -\n  { fix n m assume n: \"dimension n K E\" and m: \"dimension m K E\"\n    then obtain Vs\n      where Vs: \"set Vs \\<subseteq> carrier R\" \"independent K Vs\" \"length Vs = n\" \"Span K Vs = E\"\n      using exists_base by meson\n    hence \"n \\<le> m\"\n      using independent_length_le_dimension[OF m Vs(2)] Span_base_incl[OF Vs(1)] by auto\n  } note aux_lemma = this\n\n  show ?thesis\n    using aux_lemma[OF assms] aux_lemma[OF assms(2,1)] by simp\nqed\n\ncorollary independent_length_eq_dimension:\n  assumes \"dimension n K E\" and \"independent K Us\" \"set Us \\<subseteq> E\"\n  shows \"length Us = n \\<longleftrightarrow> Span K Us = E\"\nproof\n  assume len: \"length Us = n\" show \"Span K Us = E\"\n  proof (rule ccontr)\n    assume \"Span K Us \\<noteq> E\"\n    hence \"Span K Us \\<subset> E\"\n      using mono_Span_subset[of Us] exists_base[OF assms(1)] assms(3) by blast\n    then obtain v where v: \"v \\<in> E\" \"v \\<notin> Span K Us\"\n      using Span_strict_incl exists_base[OF assms(1)] space_subgroup_props(1)[OF assms(1)] assms by blast\n    hence \"independent K (v # Us)\"\n      using li_Cons[OF _ _ assms(2)] space_subgroup_props(1)[OF assms(1)] by auto\n    hence \"length (v # Us) \\<le> n\"\n      using independent_length_le_dimension[OF assms(1)] v(1) assms(2-3) by fastforce\n    moreover have \"length (v # Us) = Suc n\"\n      using len by simp\n    ultimately show False by simp\n  qed\nnext\n  assume \"Span K Us = E\"\n  hence \"dimension (length Us) K E\"\n    using dimensionI assms by auto\n  thus \"length Us = n\"\n    using dimension_is_inj[OF assms(1)] by auto\nqed\n\nlemma complete_base:\n  assumes \"dimension n K E\" and \"independent K Us\" \"set Us \\<subseteq> E\"\n  shows \"\\<exists>Vs. length (Vs @ Us) = n \\<and> independent K (Vs @ Us) \\<and> Span K (Vs @ Us) = E\"\nproof -\n  { fix Us k assume \"k \\<le> n\" \"independent K Us\" \"set Us \\<subseteq> E\" \"length Us = k\"\n    hence \"\\<exists>Vs. length (Vs @ Us) = n \\<and> independent K (Vs @ Us) \\<and> Span K (Vs @ Us) = E\"\n    proof (induct arbitrary: Us rule: inc_induct)\n      case base thus ?case\n        using independent_length_eq_dimension[OF assms(1) base(1-2)] by auto\n    next\n      case (step m)\n      have \"Span K Us \\<subseteq> E\"\n        using mono_Span_subset step(4-6) exists_base[OF assms(1)] by blast\n      hence \"Span K Us \\<subset> E\"\n        using independent_length_eq_dimension[OF assms(1) step(4-5)] step(2,6) assms(1) by blast\n      then obtain v where v: \"v \\<in> E\" \"v \\<notin> Span K Us\"\n        using Span_strict_incl exists_base[OF assms(1)] by blast\n      hence \"independent K (v # Us)\"\n        using space_subgroup_props(1)[OF assms(1)] li_Cons[OF _ v(2) step(4)] by auto\n      then obtain Vs\n        where \"length (Vs @ (v # Us)) = n\" \"independent K (Vs @ (v # Us))\" \"Span K (Vs @ (v # Us)) = E\"\n        using step(3)[of \"v # Us\"] step(1-2,4-6) v by auto\n      thus ?case\n        by (metis append.assoc append_Cons append_Nil)\n    qed } note aux_lemma = this\n\n  have \"length Us \\<le> n\"\n    using independent_length_le_dimension[OF assms] .\n  thus ?thesis\n    using aux_lemma[OF _ assms(2-3)] by auto\nqed\n\nlemma filter_base:\n  assumes \"set Us \\<subseteq> carrier R\"\n  obtains Vs where \"set Vs \\<subseteq> carrier R\" and \"independent K Vs\" and \"Span K Vs = Span K Us\"\nproof -\n  from \\<open>set Us \\<subseteq> carrier R\\<close> have \"\\<exists>Vs. independent K Vs \\<and> Span K Vs = Span K Us\"\n  proof (induction Us)\n    case Nil thus ?case by auto\n  next\n    case (Cons u Us)\n    then obtain Vs where Vs: \"independent K Vs\" \"Span K Vs = Span K Us\"\n      by auto\n    show ?case\n    proof (cases \"u \\<in> Span K Us\")\n      case True\n      hence \"Span K (u # Us) = Span K Us\"\n        using Span_base_incl mono_Span_subset\n        by (metis Cons.prems insert_subset list.simps(15) subset_antisym)\n      thus ?thesis\n        using Vs by blast\n    next\n      case False\n      hence \"Span K (u # Vs) = Span K (u # Us)\" and \"independent K (u # Vs)\"\n        using li_Cons[of u K Vs] Cons(2) Vs by auto\n      thus ?thesis\n        by blast\n    qed\n  qed\n  thus ?thesis\n    using independent_in_carrier that by auto\nqed\n\nlemma dimension_backwards:\n  \"dimension (Suc n) K E \\<Longrightarrow> \\<exists>v \\<in> carrier R. \\<exists>E'. dimension n K E' \\<and> v \\<notin> E' \\<and> E = line_extension K v E'\"\n  by (cases rule: dimension.cases) (auto)\n\nlemma dimension_direct_sum_space:\n  assumes \"dimension n K E\" and \"dimension m K F\" and \"E \\<inter> F = { \\<zero> }\"\n  shows \"dimension (n + m) K (E <+>\\<^bsub>R\\<^esub> F)\"\nproof -\n  obtain Us Vs\n    where Vs: \"set Vs \\<subseteq> carrier R\" \"independent K Vs\" \"length Vs = n\" \"Span K Vs = E\"\n      and Us: \"set Us \\<subseteq> carrier R\" \"independent K Us\" \"length Us = m\" \"Span K Us = F\"\n    using assms(1-2)[THEN exists_base] by auto\n  hence \"Span K (Vs @ Us) = E <+>\\<^bsub>R\\<^esub> F\"\n    using Span_append_eq_set_add by auto\n  moreover have \"independent K (Vs @ Us)\"\n    using assms(3) independent_append[OF Vs(2) Us(2)] unfolding Vs(4) Us(4) by simp\n  ultimately show \"dimension (n + m) K (E <+>\\<^bsub>R\\<^esub> F)\"\n    using dimensionI[of \"Vs @ Us\"] Vs(3) Us(3) by auto\nqed\n\nlemma dimension_sum_space:\n  assumes \"dimension n K E\" and \"dimension m K F\" and \"dimension k K (E \\<inter> F)\"\n  shows \"dimension (n + m - k) K (E <+>\\<^bsub>R\\<^esub> F)\"\nproof -\n  obtain Bs\n    where Bs: \"set Bs \\<subseteq> carrier R\" \"length Bs = k\" \"independent K Bs\" \"Span K Bs = E \\<inter> F\"\n    using exists_base[OF assms(3)] by blast\n  then obtain Us Vs\n    where Us: \"length (Us @ Bs) = n\" \"independent K (Us @ Bs)\" \"Span K (Us @ Bs) = E\"\n      and Vs: \"length (Vs @ Bs) = m\" \"independent K (Vs @ Bs)\" \"Span K (Vs @ Bs) = F\"\n    using Span_base_incl[OF Bs(1)] assms(1-2)[THEN complete_base] by (metis le_infE)\n  hence in_carrier: \"set Us \\<subseteq> carrier R\" \"set (Vs @ Bs) \\<subseteq> carrier R\"\n    using independent_in_carrier[OF Us(2)] independent_in_carrier[OF Vs(2)] by auto\n  hence \"Span K Us \\<inter> (Span K (Vs @ Bs)) \\<subseteq> Span K Bs\"\n    using Bs(4) Us(3) Vs(3) mono_Span_append(1)[OF _ Bs(1), of Us] by auto\n  hence \"Span K Us \\<inter> (Span K (Vs @ Bs)) \\<subseteq> { \\<zero> }\"\n    using independent_split(3)[OF Us(2)] by blast\n  hence \"Span K Us \\<inter> (Span K (Vs @ Bs)) = { \\<zero> }\"\n    using in_carrier[THEN Span_subgroup_props(2)] by auto\n\n  hence dim: \"dimension (n + m - k) K (Span K (Us @ (Vs @ Bs)))\"\n    using independent_append[OF independent_split(2)[OF Us(2)] Vs(2)] Us(1) Vs(1) Bs(2)\n          dimension_independent[of K \"Us @ (Vs @ Bs)\"] by auto\n\n  have \"(Span K Us) <+>\\<^bsub>R\\<^esub> F \\<subseteq> E <+>\\<^bsub>R\\<^esub> F\"\n    using mono_Span_append(1)[OF in_carrier(1) Bs(1)] Us(3) unfolding set_add_def' by auto\n  moreover have \"E <+>\\<^bsub>R\\<^esub> F \\<subseteq> (Span K Us) <+>\\<^bsub>R\\<^esub> F\"\n  proof\n    fix v assume \"v \\<in> E <+>\\<^bsub>R\\<^esub> F\"\n    then obtain u' v' where v: \"u' \\<in> E\" \"v' \\<in> F\" \"v = u' \\<oplus> v'\"\n      unfolding set_add_def' by auto\n    then obtain u1' u2' where u1': \"u1' \\<in> Span K Us\" and u2': \"u2' \\<in> Span K Bs\" and u': \"u' = u1' \\<oplus> u2'\"\n      using Span_append_eq_set_add[OF in_carrier(1) Bs(1)] Us(3) unfolding set_add_def' by blast\n\n    have \"v = u1' \\<oplus> (u2' \\<oplus> v')\"\n      using Span_subgroup_props(1)[OF Bs(1)] Span_subgroup_props(1)[OF in_carrier(1)]\n            space_subgroup_props(1)[OF assms(2)] u' v u1' u2' a_assoc[of u1' u2' v'] by auto\n    moreover have \"u2' \\<oplus> v' \\<in> F\"\n      using space_subgroup_props(3)[OF assms(2) _ v(2)] u2' Bs(4) by auto\n    ultimately show \"v \\<in> (Span K Us) <+>\\<^bsub>R\\<^esub> F\"\n      using u1' unfolding set_add_def' by auto\n  qed\n  ultimately have \"Span K (Us @ (Vs @ Bs)) = E <+>\\<^bsub>R\\<^esub> F\"\n    using Span_append_eq_set_add[OF in_carrier] Vs(3) by auto\n\n  thus ?thesis using dim by simp\nqed\n\nend (* of fixed K context. *)\n\nend (* of ring context. *)\n\n\nlemma (in ring) telescopic_base_aux:\n  assumes \"subfield K R\" \"subfield F R\"\n    and \"dimension n K F\" and \"dimension 1 F E\"\n  shows \"dimension n K E\"\nproof -\n  obtain Us u\n    where Us: \"set Us \\<subseteq> carrier R\" \"length Us = n\" \"independent K Us\" \"Span K Us = F\"\n      and u: \"u \\<in> carrier R\" \"independent F [u]\" \"Span F [u] = E\"\n    using exists_base[OF assms(2,4)] exists_base[OF assms(1,3)] independent_backwards(3) assms(2)\n    by (metis One_nat_def length_0_conv length_Suc_conv)\n  have in_carrier: \"set (map (\\<lambda>u'. u' \\<otimes> u) Us) \\<subseteq> carrier R\"\n    using Us(1) u(1) by (induct Us) (auto)\n\n  have li: \"independent K (map (\\<lambda>u'. u' \\<otimes> u) Us)\"\n  proof (rule trivial_combine_imp_independent[OF assms(1) in_carrier])\n    fix Ks assume Ks: \"set Ks \\<subseteq> K\" and \"combine Ks (map (\\<lambda>u'. u' \\<otimes> u) Us) = \\<zero>\"\n    hence \"(combine Ks Us) \\<otimes> u = \\<zero>\"\n      using combine_l_distr[OF _ Us(1) u(1)] subring_props(1)[OF assms(1)] by auto\n    hence \"combine [ combine Ks Us ] [ u ] = \\<zero>\"\n      by simp\n    moreover have \"combine Ks Us \\<in> F\"\n      using Us(4) Ks(1) Span_eq_combine_set[OF assms(1) Us(1)] by auto\n    ultimately have \"combine Ks Us = \\<zero>\"\n      using independent_imp_trivial_combine[OF assms(2) u(2), of \"[ combine Ks Us ]\"] by auto\n    hence \"set (take (length Us) Ks) \\<subseteq> { \\<zero> }\"\n      using independent_imp_trivial_combine[OF assms(1) Us(3) Ks(1)] by simp\n    thus \"set (take (length (map (\\<lambda>u'. u' \\<otimes> u) Us)) Ks) \\<subseteq> { \\<zero> }\" by simp\n  qed\n\n  have \"E \\<subseteq> Span K (map (\\<lambda>u'. u' \\<otimes> u) Us)\"\n  proof\n    fix v assume \"v \\<in> E\"\n    then obtain f where f: \"f \\<in> F\" \"v = f \\<otimes> u \\<oplus> \\<zero>\"\n      using u(1,3) line_extension_mem_iff by auto\n    then obtain Ks where Ks: \"set Ks \\<subseteq> K\" \"f = combine Ks Us\"\n      using Span_eq_combine_set[OF assms(1) Us(1)] Us(4) by auto\n    have \"v = f \\<otimes> u\"\n      using subring_props(1)[OF assms(2)] f u(1) by auto\n    hence \"v = combine Ks (map (\\<lambda>u'. u' \\<otimes> u) Us)\"\n      using combine_l_distr[OF _ Us(1) u(1), of Ks] Ks(1-2)\n            subring_props(1)[OF assms(1)] by blast\n    thus \"v \\<in> Span K (map (\\<lambda>u'. u' \\<otimes> u) Us)\"\n      unfolding Span_eq_combine_set[OF assms(1) in_carrier] using Ks(1) by blast\n  qed\n  moreover have \"Span K (map (\\<lambda>u'. u' \\<otimes> u) Us) \\<subseteq> E\"\n  proof\n    fix v assume \"v \\<in> Span K (map (\\<lambda>u'. u' \\<otimes> u) Us)\"\n    then obtain Ks where Ks: \"set Ks \\<subseteq> K\" \"v = combine Ks (map (\\<lambda>u'. u' \\<otimes> u) Us)\"\n      unfolding Span_eq_combine_set[OF assms(1) in_carrier] by blast\n    hence \"v = (combine Ks Us) \\<otimes> u\"\n      using combine_l_distr[OF _ Us(1) u(1), of Ks] subring_props(1)[OF assms(1)] by auto\n    moreover have \"combine Ks Us \\<in> F\"\n      using Us(4) Span_eq_combine_set[OF assms(1) Us(1)] Ks(1) by blast\n    ultimately have \"v = (combine Ks Us) \\<otimes> u \\<oplus> \\<zero>\" and \"combine Ks Us \\<in> F\"\n      using subring_props(1)[OF assms(2)] u(1) by auto\n    thus \"v \\<in> E\"\n      using u(3) line_extension_mem_iff by auto\n  qed\n  ultimately have \"Span K (map (\\<lambda>u'. u' \\<otimes> u) Us) = E\" by auto\n  thus ?thesis\n    using dimensionI[OF assms(1) li] Us(2) by simp\nqed\n\nlemma (in ring) telescopic_base:\n  assumes \"subfield K R\" \"subfield F R\"\n    and \"dimension n K F\" and \"dimension m F E\"\n  shows \"dimension (n * m) K E\"\n  using assms(4)\nproof (induct m arbitrary: E)\n  case 0 thus ?case\n    using dimension_zero[OF assms(2)] zero_dim by auto\nnext\n  case (Suc m)\n  obtain Vs\n    where Vs: \"set Vs \\<subseteq> carrier R\" \"length Vs = Suc m\" \"independent F Vs\" \"Span F Vs = E\"\n    using exists_base[OF assms(2) Suc(2)] by blast\n  then obtain v Vs' where v: \"Vs = v # Vs'\"\n    by (meson length_Suc_conv)\n  hence li: \"independent F [ v ]\" \"independent F Vs'\" and inter: \"Span F [ v ] \\<inter> Span F Vs' = { \\<zero> }\"\n    using Vs(3) independent_split[OF assms(2), of \"[ v ]\" Vs'] by auto\n  have \"dimension n K (Span F [ v ])\"\n    using dimension_independent[OF li(1)] telescopic_base_aux[OF assms(1-3)] by simp\n  moreover have \"dimension (n * m) K (Span F Vs')\"\n    using Suc(1) dimension_independent[OF li(2)] Vs(2) unfolding v by auto\n  ultimately have \"dimension (n * Suc m) K (Span F [ v ] <+>\\<^bsub>R\\<^esub> Span F Vs')\"\n    using dimension_direct_sum_space[OF assms(1) _ _ inter] by auto\n  thus \"dimension (n * Suc m) K E\"\n    using Span_append_eq_set_add[OF assms(2) li[THEN independent_in_carrier]] Vs(4) v by auto\nqed\n\n\ncontext ring_hom_ring\nbegin\n\nlemma combine_hom:\n  \"\\<lbrakk> set Ks \\<subseteq> carrier R; set Us \\<subseteq> carrier R \\<rbrakk> \\<Longrightarrow> combine (map h Ks) (map h Us) = h (R.combine Ks Us)\"\n  by (induct Ks Us rule: R.combine.induct) (auto)\n\nlemma line_extension_hom:\n  assumes \"K \\<subseteq> carrier R\" \"a \\<in> carrier R\" \"E \\<subseteq> carrier R\"\n  shows \"line_extension (h ` K) (h a) (h ` E) = h ` R.line_extension K a E\"\n  using set_add_hom[OF homh R.r_coset_subset_G[OF assms(1-2)] assms(3)]\n        coset_hom(2)[OF ring_hom_in_hom(1)[OF homh] assms(1-2)]\n  unfolding R.line_extension_def S.line_extension_def\n  by simp\n\nlemma Span_hom:\n  assumes \"K \\<subseteq> carrier R\" \"set Us \\<subseteq> carrier R\"\n  shows \"Span (h ` K) (map h Us) = h ` R.Span K Us\"\n  using assms line_extension_hom R.Span_in_carrier by (induct Us) (auto)\n\nlemma inj_on_subgroup_iff_trivial_ker:\n  assumes \"subgroup H (add_monoid R)\"\n  shows \"inj_on h H \\<longleftrightarrow> a_kernel (R \\<lparr> carrier := H \\<rparr>) S h = { \\<zero> }\"\n  using group_hom.inj_on_subgroup_iff_trivial_ker[OF a_group_hom assms]\n  unfolding a_kernel_def[of \"R \\<lparr> carrier := H \\<rparr>\" S h] by simp\n\ncorollary inj_on_Span_iff_trivial_ker:\n  assumes \"subfield K R\" \"set Us \\<subseteq> carrier R\"\n  shows \"inj_on h (R.Span K Us) \\<longleftrightarrow> a_kernel (R \\<lparr> carrier := R.Span K Us \\<rparr>) S h = { \\<zero> }\"\n  using inj_on_subgroup_iff_trivial_ker[OF R.Span_is_add_subgroup[OF assms]] .\n\n\ncontext\n  fixes K :: \"'a set\" assumes K: \"subfield K R\" and one_zero: \"\\<one>\\<^bsub>S\\<^esub> \\<noteq> \\<zero>\\<^bsub>S\\<^esub>\"\nbegin\n\nlemma inj_hom_preserves_independent:\n  assumes \"inj_on h (R.Span K Us)\"\n  and \"R.independent K Us\" shows \"independent (h ` K) (map h Us)\"\nproof (rule ccontr)\n  have in_carrier: \"set Us \\<subseteq> carrier R\" \"set (map h Us) \\<subseteq> carrier S\"\n    using R.independent_in_carrier[OF assms(2)] by auto \n\n  assume ld: \"dependent (h ` K) (map h Us)\"\n  obtain Ks :: \"'c list\"\n    where Ks: \"length Ks = length Us\" \"combine Ks (map h Us) = \\<zero>\\<^bsub>S\\<^esub>\" \"set Ks \\<subseteq> h ` K\" \"set Ks \\<noteq> { \\<zero>\\<^bsub>S\\<^esub> }\"\n    using dependent_imp_non_trivial_combine[OF img_is_subfield(2)[OF K one_zero] in_carrier(2) ld]\n    by (metis length_map)\n  obtain Ks' where Ks': \"set Ks' \\<subseteq> K\" \"Ks = map h Ks'\"\n    using Ks(3) by (induct Ks) (auto, metis insert_subset list.simps(15,9))\n  hence \"h (R.combine Ks' Us) = \\<zero>\\<^bsub>S\\<^esub>\"\n    using combine_hom[OF _ in_carrier(1)] Ks(2) subfieldE(3)[OF K] by (metis subset_trans)\n  moreover have \"R.combine Ks' Us \\<in> R.Span K Us\"\n    using R.Span_eq_combine_set[OF K in_carrier(1)] Ks'(1) by auto\n  ultimately have \"R.combine Ks' Us = \\<zero>\"\n    using assms hom_zero R.Span_subgroup_props(2)[OF K in_carrier(1)] by (auto simp add: inj_on_def)\n  hence \"set Ks' \\<subseteq> { \\<zero> }\"\n    using R.independent_imp_trivial_combine[OF K assms(2)] Ks' Ks(1)\n    by (metis length_map order_refl take_all)\n  hence \"set Ks \\<subseteq> { \\<zero>\\<^bsub>S\\<^esub> }\"\n    unfolding Ks' using hom_zero by (induct Ks') (auto)\n  hence \"Ks = []\"\n    using Ks(4) by (metis set_empty2 subset_singletonD)\n  hence \"independent (h ` K) (map h Us)\"\n    using independent.li_Nil Ks(1) by simp\n  from \\<open>dependent (h ` K) (map h Us)\\<close> and this show False by simp\nqed\n\ncorollary inj_hom_dimension:\n  assumes \"inj_on h E\"\n  and \"R.dimension n K E\" shows \"dimension n (h ` K) (h ` E)\"\nproof -\n  obtain Us\n    where Us: \"set Us \\<subseteq> carrier R\" \"R.independent K Us\" \"length Us = n\" \"R.Span K Us = E\"\n    using R.exists_base[OF K assms(2)] by blast\n  hence \"dimension n (h ` K) (Span (h ` K) (map h Us))\"\n    using dimension_independent[OF inj_hom_preserves_independent[OF _ Us(2)]] assms(1) by auto\n  thus ?thesis\n    using Span_hom[OF subfieldE(3)[OF K] Us(1)] Us(4) by simp\nqed\n\ncorollary rank_nullity_theorem:\n  assumes \"R.dimension n K E\" and \"R.dimension m K (a_kernel (R \\<lparr> carrier := E \\<rparr>) S h)\"\n  shows \"dimension (n - m) (h ` K) (h ` E)\"\nproof -\n  obtain Us\n    where Us: \"set Us \\<subseteq> carrier R\" \"R.independent K Us\" \"length Us = m\"\n              \"R.Span K Us = a_kernel (R \\<lparr> carrier := E \\<rparr>) S h\"\n    using R.exists_base[OF K assms(2)] by blast\n  obtain Vs\n    where Vs: \"R.independent K (Vs @ Us)\" \"length (Vs @ Us) = n\" \"R.Span K (Vs @ Us) = E\" \n    using R.complete_base[OF K assms(1) Us(2)] R.Span_base_incl[OF K Us(1)] Us(4)\n    unfolding a_kernel_def' by auto\n  have set_Vs: \"set Vs \\<subseteq> carrier R\"\n    using R.independent_in_carrier[OF Vs(1)] by auto\n  have \"R.Span K Vs \\<inter> a_kernel (R \\<lparr> carrier := E \\<rparr>) S h = { \\<zero> }\"\n    using R.independent_split[OF K Vs(1)] Us(4) by simp\n  moreover have \"R.Span K Vs \\<subseteq> E\"\n    using R.mono_Span_append(1)[OF K set_Vs Us(1)] Vs(3) by auto\n  ultimately have \"a_kernel (R \\<lparr> carrier := R.Span K Vs \\<rparr>) S h \\<subseteq> { \\<zero> }\"\n    unfolding a_kernel_def' by (simp del: R.Span.simps, blast)\n  hence \"a_kernel (R \\<lparr> carrier := R.Span K Vs \\<rparr>) S h = { \\<zero> }\"\n    using R.Span_subgroup_props(2)[OF K set_Vs]\n    unfolding a_kernel_def' by (auto simp del: R.Span.simps)\n  hence \"inj_on h (R.Span K Vs)\"\n    using inj_on_Span_iff_trivial_ker[OF K set_Vs] by simp\n  moreover have \"R.dimension (n - m) K (R.Span K Vs)\"\n    using R.dimension_independent[OF R.independent_split(2)[OF K Vs(1)]] Vs(2) Us(3) by auto\n  ultimately have \"dimension (n - m) (h ` K) (h ` (R.Span K Vs))\"\n    using assms(1) inj_hom_dimension by simp\n\n  have \"h ` E = h ` (R.Span K Vs <+>\\<^bsub>R\\<^esub> R.Span K Us)\"\n    using R.Span_append_eq_set_add[OF K set_Vs Us(1)] Vs(3) by simp\n  hence \"h ` E = h ` (R.Span K Vs) <+>\\<^bsub>S\\<^esub> h ` (R.Span K Us)\"\n    using R.Span_subgroup_props(1)[OF K] set_Vs Us(1) set_add_hom[OF homh] by auto\n  moreover have \"h ` (R.Span K Us) = { \\<zero>\\<^bsub>S\\<^esub> }\"\n    using R.space_subgroup_props(2)[OF K assms(1)] unfolding Us(4) a_kernel_def' by force\n  ultimately have \"h ` E = h ` (R.Span K Vs) <+>\\<^bsub>S\\<^esub> { \\<zero>\\<^bsub>S\\<^esub> }\"\n    by simp\n  hence \"h ` E = h ` (R.Span K Vs)\"\n    using R.Span_subgroup_props(1-2)[OF K set_Vs] unfolding set_add_def' by force\n\n  from \\<open>dimension (n - m) (h ` K) (h ` (R.Span K Vs))\\<close> and this show ?thesis by simp\nqed\n\nend (* of fixed K context. *)\n\nend (* of ring_hom_ring context. *)\n\nlemma (in ring_hom_ring)\n  assumes \"subfield K R\" and \"set Us \\<subseteq> carrier R\" and \"\\<one>\\<^bsub>S\\<^esub> \\<noteq> \\<zero>\\<^bsub>S\\<^esub>\"\n    and \"independent (h ` K) (map h Us)\" shows \"R.independent K Us\"\nproof (rule ccontr)\n  assume \"R.dependent K Us\"\n  then obtain Ks\n    where \"length Ks = length Us\" and \"R.combine Ks Us = \\<zero>\" and \"set Ks \\<subseteq> K\" and \"set Ks \\<noteq> { \\<zero> }\"\n    using R.dependent_imp_non_trivial_combine[OF assms(1-2)] by metis\n  hence \"combine (map h Ks) (map h Us) = \\<zero>\\<^bsub>S\\<^esub>\"\n    using combine_hom[OF _ assms(2), of Ks] subfieldE(3)[OF assms(1)] by simp\n  moreover from \\<open>set Ks \\<subseteq> K\\<close> have \"set (map h Ks) \\<subseteq> h ` K\"\n    by (induction Ks) (auto)\n  moreover have \"\\<not> set (map h Ks) \\<subseteq> { h \\<zero> }\"\n  proof (rule ccontr)\n    assume \"\\<not> \\<not> set (map h Ks) \\<subseteq> { h \\<zero> }\" then have \"set (map h Ks) \\<subseteq> { h \\<zero> }\"\n      by simp\n    moreover from \\<open>R.dependent K Us\\<close> and \\<open>length Ks = length Us\\<close> have \"Ks \\<noteq> []\"\n      by auto\n    ultimately have \"set (map h Ks) = { h \\<zero> }\"\n      using subset_singletonD by fastforce\n    with \\<open>set Ks \\<subseteq> K\\<close> have \"set Ks = { \\<zero> }\"\n      using inj_onD[OF _ _ _ subringE(2)[OF subfieldE(1)[OF assms(1)]], of h]\n            img_is_subfield(1)[OF assms(1,3)] subset_singletonD\n      by (induction Ks) (auto simp add: subset_singletonD, fastforce)\n    with \\<open>set Ks \\<noteq> { \\<zero> }\\<close> show False\n      by simp\n  qed\n  with \\<open>length Ks = length Us\\<close> have \"\\<not> set (take (length (map h Us)) (map h Ks)) \\<subseteq> { h \\<zero> }\"\n    by auto\n  ultimately have \"dependent (h ` K) (map h Us)\"\n    using non_trivial_combine_imp_dependent[OF img_is_subfield(2)[OF assms(1,3)], of \"map h Ks\"] by simp\n  with \\<open>independent (h ` K) (map h Us)\\<close> show False\n    by simp\nqed\n\n\nsubsection \\<open>Finite Dimension\\<close>\n\ndefinition (in ring) finite_dimension :: \"'a set \\<Rightarrow> 'a set \\<Rightarrow> bool\"\n  where \"finite_dimension K E \\<longleftrightarrow> (\\<exists>n. dimension n K E)\"\n\nabbreviation (in ring) infinite_dimension :: \"'a set \\<Rightarrow> 'a set \\<Rightarrow> bool\"\n  where \"infinite_dimension K E \\<equiv> \\<not> finite_dimension K E\"\n\ndefinition (in ring) dim :: \"'a set \\<Rightarrow> 'a set \\<Rightarrow> nat\"\n  where \"dim K E = (THE n. dimension n K E)\"\n\nlocale subalgebra = subgroup V \"add_monoid R\" for K and V and R (structure) +\n  assumes smult_closed: \"\\<lbrakk> k \\<in> K; v \\<in> V \\<rbrakk> \\<Longrightarrow> k \\<otimes> v \\<in> V\"\n\n\nsubsubsection \\<open>Basic Properties\\<close>\n\nlemma (in ring) unique_dimension:\n  assumes \"subfield K R\" and \"finite_dimension K E\" shows \"\\<exists>!n. dimension n K E\"\n  using assms(2) dimension_is_inj[OF assms(1)] unfolding finite_dimension_def by auto\n\nlemma (in ring) finite_dimensionI:\n  assumes \"dimension n K E\" shows \"finite_dimension K E\"\n  using assms unfolding finite_dimension_def by auto\n\nlemma (in ring) finite_dimensionE:\n  assumes \"subfield K R\" and \"finite_dimension K E\" shows \"dimension ((dim over K) E) K E\"\n  using theI'[OF unique_dimension[OF assms]] unfolding over_def dim_def by simp\n\nlemma (in ring) dimI:\n  assumes \"subfield K R\" and \"dimension n K E\" shows \"(dim over K) E = n\"\n  using finite_dimensionE[OF assms(1) finite_dimensionI] dimension_is_inj[OF assms(1)] assms(2)\n  unfolding over_def dim_def by auto\n\nlemma (in ring) finite_dimensionE' [elim]:\n  assumes \"finite_dimension K E\" and \"\\<And>n. dimension n K E \\<Longrightarrow> P\" shows P\n  using assms unfolding finite_dimension_def by auto\n\nlemma (in ring) Span_finite_dimension:\n  assumes \"subfield K R\" and \"set Us \\<subseteq> carrier R\"\n  shows \"finite_dimension K (Span K Us)\"\n  using filter_base[OF assms] finite_dimensionI[OF dimension_independent[of K]] by metis\n\nlemma (in ring) carrier_is_subalgebra:\n  assumes \"K \\<subseteq> carrier R\" shows \"subalgebra K (carrier R) R\"\n  using assms subalgebra.intro[OF add.group_incl_imp_subgroup[of \"carrier R\"], of K] add.group_axioms\n  unfolding subalgebra_axioms_def by auto\n\nlemma (in ring) subalgebra_in_carrier:\n  assumes \"subalgebra K V R\" shows \"V \\<subseteq> carrier R\"\n  using subgroup.subset[OF subalgebra.axioms(1)[OF assms]] by simp\n\nlemma (in ring) subalgebra_inter:\n  assumes \"subalgebra K V R\" and \"subalgebra K V' R\" shows \"subalgebra K (V \\<inter> V') R\"\n  using add.subgroups_Inter_pair assms unfolding subalgebra_def subalgebra_axioms_def by auto\n\nlemma (in ring_hom_ring) img_is_subalgebra:\n  assumes \"K \\<subseteq> carrier R\" and \"subalgebra K V R\" shows \"subalgebra (h ` K) (h ` V) S\"\nproof (intro subalgebra.intro)\n  have \"group_hom (add_monoid R) (add_monoid S) h\"\n    using ring_hom_in_hom(2)[OF homh] R.add.group_axioms add.group_axioms\n    unfolding group_hom_def group_hom_axioms_def by auto\n  thus \"subgroup (h ` V) (add_monoid S)\"\n    using group_hom.subgroup_img_is_subgroup[OF _ subalgebra.axioms(1)[OF assms(2)]] by force\nnext\n  show \"subalgebra_axioms (h ` K) (h ` V) S\"\n    using R.subalgebra_in_carrier[OF assms(2)] subalgebra.axioms(2)[OF assms(2)] assms(1)\n    unfolding subalgebra_axioms_def\n    by (auto, metis hom_mult image_eqI subset_iff)\nqed\n\nlemma (in ring) ideal_is_subalgebra:\n  assumes \"K \\<subseteq> carrier R\" \"ideal I R\" shows \"subalgebra K I R\"\n  using ideal.axioms(1)[OF assms(2)] ideal.I_l_closed[OF assms(2)] assms(1)\n  unfolding subalgebra_def subalgebra_axioms_def additive_subgroup_def by auto\n\nlemma (in ring) Span_is_subalgebra:\n  assumes \"subfield K R\" \"set Us \\<subseteq> carrier R\" shows \"subalgebra K (Span K Us) R\"\n  using Span_smult_closed[OF assms] Span_is_add_subgroup[OF assms]\n  unfolding subalgebra_def subalgebra_axioms_def by auto\n\nlemma (in ring) finite_dimension_imp_subalgebra:\n  assumes \"subfield K R\" \"finite_dimension K E\" shows \"subalgebra K E R\"\n  using exists_base[OF assms(1) finite_dimensionE[OF assms]] Span_is_subalgebra[OF assms(1)] by auto\n\nlemma (in ring) subalgebra_Span_incl:\n  assumes \"subfield K R\" and \"subalgebra K V R\" \"set Us \\<subseteq> V\" shows \"Span K Us \\<subseteq> V\"\nproof -\n  have \"K <#> (set Us) \\<subseteq> V\"\n    using subalgebra.smult_closed[OF assms(2)] assms(3) unfolding set_mult_def by blast\n  moreover have \"set Us \\<subseteq> carrier R\"\n    using subalgebra_in_carrier[OF assms(2)] assms(3) by auto\n  ultimately show ?thesis\n    using subalgebra.axioms(1)[OF assms(2)] Span_min[OF assms(1)] by blast\nqed\n\nlemma (in ring) Span_subalgebra_minimal:\n  assumes \"subfield K R\" \"set Us \\<subseteq> carrier R\"\n  shows \"Span K Us = \\<Inter> { V. subalgebra K V R \\<and> set Us \\<subseteq> V }\"\n  using Span_is_subalgebra[OF assms] Span_base_incl[OF assms] subalgebra_Span_incl[OF assms(1)]\n  by blast\n\nlemma (in ring) Span_subalgebraI:\n  assumes \"subfield K R\"\n    and \"subalgebra K E R\" \"set Us \\<subseteq> E\"\n    and \"\\<And>V. \\<lbrakk> subalgebra K V R; set Us \\<subseteq> V \\<rbrakk> \\<Longrightarrow> E \\<subseteq> V\"\n  shows \"E = Span K Us\"\nproof -\n  have \"\\<Inter> { V. subalgebra K V R \\<and> set Us \\<subseteq> V } = E\"\n    using assms(2-4) by auto\n  thus \"E = Span K Us\"\n    using Span_subalgebra_minimal subalgebra_in_carrier[of K E] assms by auto\nqed\n\nlemma (in ring) subalbegra_incl_imp_finite_dimension:\n  assumes \"subfield K R\" and \"finite_dimension K E\"\n  and \"subalgebra K V R\" \"V \\<subseteq> E\" shows \"finite_dimension K V\"\nproof -\n  obtain n where n: \"dimension n K E\"\n    using assms(2) by auto\n\n  define S where \"S = { Us. set Us \\<subseteq> V \\<and> independent K Us }\"\n  have \"length ` S \\<subseteq> {..n}\"\n    unfolding S_def using independent_length_le_dimension[OF assms(1) n] assms(4) by auto\n  moreover have \"[] \\<in> S\"\n    unfolding S_def by simp\n  hence \"length ` S \\<noteq> {}\" by blast\n  ultimately obtain m where m: \"m \\<in> length ` S\" and greatest: \"\\<And>k. k \\<in> length ` S \\<Longrightarrow> k \\<le> m\"\n    by (meson Max_ge Max_in finite_atMost rev_finite_subset)\n  then obtain Us where Us: \"set Us \\<subseteq> V\" \"independent K Us\" \"m = length Us\"\n      unfolding S_def by auto\n  have \"Span K Us = V\"\n  proof (rule ccontr)\n    assume \"\\<not> Span K Us = V\" then have \"Span K Us \\<subset> V\"\n      using subalgebra_Span_incl[OF assms(1,3) Us(1)] by blast\n    then obtain v where v:\"v \\<in> V\" \"v \\<notin> Span K Us\"\n      by blast\n    hence \"independent K (v # Us)\"\n      using independent.li_Cons[OF _ _ Us(2)] subalgebra_in_carrier[OF assms(3)] by auto\n    hence \"(v # Us) \\<in> S\"\n      unfolding S_def using Us(1) v(1) by auto\n    hence \"length (v # Us) \\<le> m\"\n      using greatest by blast\n    moreover have \"length (v # Us) = Suc m\"\n      using Us(3) by auto\n    ultimately show False by simp\n  qed\n  thus ?thesis\n    using finite_dimensionI[OF dimension_independent[OF Us(2)]] by simp\nqed\n\nlemma (in ring_hom_ring) infinite_dimension_hom:\n  assumes \"subfield K R\" and \"\\<one>\\<^bsub>S\\<^esub> \\<noteq> \\<zero>\\<^bsub>S\\<^esub>\" and \"inj_on h E\" and \"subalgebra K E R\"\n  shows \"R.infinite_dimension K E \\<Longrightarrow> infinite_dimension (h ` K) (h ` E)\"\nproof -\n  note subfield = img_is_subfield(2)[OF assms(1-2)]\n\n  assume \"R.infinite_dimension K E\"\n  show \"infinite_dimension (h ` K) (h ` E)\"\n  proof (rule ccontr)\n    assume \"\\<not> infinite_dimension (h ` K) (h ` E)\"\n    then obtain Vs where \"set Vs \\<subseteq> carrier S\" and \"Span (h ` K) Vs = h ` E\"\n      using exists_base[OF subfield] by blast\n    hence \"set Vs \\<subseteq> h ` E\"\n      using Span_base_incl[OF subfield] by blast\n    hence \"\\<exists>Us. set Us \\<subseteq> E \\<and> Vs = map h Us\"\n      by (induct Vs) (auto, metis insert_subset list.simps(9,15))\n    then obtain Us where \"set Us \\<subseteq> E\" and \"Vs = map h Us\"\n      by blast\n    with \\<open>Span (h ` K) Vs = h ` E\\<close> have \"h ` (R.Span K Us) = h ` E\"\n      using R.subalgebra_in_carrier[OF assms(4)] Span_hom assms(1) by auto\n    moreover from \\<open>set Us \\<subseteq> E\\<close> have \"R.Span K Us \\<subseteq> E\"\n      using R.subalgebra_Span_incl assms(1-4) by blast\n    ultimately have \"R.Span K Us = E\"\n    proof (auto simp del: R.Span.simps)\n      fix a assume \"a \\<in> E\"\n      with \\<open>h ` (R.Span K Us) = h ` E\\<close> obtain b where \"b \\<in> R.Span K Us\" and \"h a = h b\"\n        by auto\n      with \\<open>R.Span K Us \\<subseteq> E\\<close> and \\<open>a \\<in> E\\<close> have \"a = b\"\n        using inj_onD[OF assms(3)] by auto\n      with \\<open>b \\<in> R.Span K Us\\<close> show \"a \\<in> R.Span K Us\"\n        by simp\n    qed\n    with \\<open>set Us \\<subseteq> E\\<close> have \"R.finite_dimension K E\"\n      using R.Span_finite_dimension[OF assms(1)] R.subalgebra_in_carrier[OF assms(4)] by auto\n    with \\<open>R.infinite_dimension K E\\<close> show False\n      by simp\n  qed\nqed\n\n\nsubsubsection \\<open>Reformulation of some lemmas in this new language.\\<close>\n\nlemma (in ring) sum_space_dim:\n  assumes \"subfield K R\" \"finite_dimension K E\" \"finite_dimension K F\"\n  shows \"finite_dimension K (E <+>\\<^bsub>R\\<^esub> F)\"\n    and \"((dim over K) (E <+>\\<^bsub>R\\<^esub> F)) = ((dim over K) E) + ((dim over K) F) - ((dim over K) (E \\<inter> F))\"\nproof -\n  obtain n m k where n: \"dimension n K E\" and m: \"dimension m K F\" and k: \"dimension k K (E \\<inter> F)\"\n    using assms(2-3) subalbegra_incl_imp_finite_dimension[OF assms(1-2)\n          subalgebra_inter[OF assms(2-3)[THEN finite_dimension_imp_subalgebra[OF assms(1)]]]]\n    by (meson inf_le1 finite_dimension_def)\n  hence \"dimension (n + m - k) K (E <+>\\<^bsub>R\\<^esub> F)\"\n    using dimension_sum_space[OF assms(1)] by simp\n  thus \"finite_dimension K (E <+>\\<^bsub>R\\<^esub> F)\"\n   and \"((dim over K) (E <+>\\<^bsub>R\\<^esub> F)) = ((dim over K) E) + ((dim over K) F) - ((dim over K) (E \\<inter> F))\"\n    using finite_dimensionI dimI[OF assms(1)] n m k by auto\nqed\n\nlemma (in ring) telescopic_base_dim:\n  assumes \"subfield K R\" \"subfield F R\" and \"finite_dimension K F\" and \"finite_dimension F E\"\n  shows \"finite_dimension K E\" and \"(dim over K) E = ((dim over K) F) * ((dim over F) E)\"\n  using telescopic_base[OF assms(1-2)\n        finite_dimensionE[OF assms(1,3)]\n        finite_dimensionE[OF assms(2,4)]]\n        dimI[OF assms(1)] finite_dimensionI\n  by 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/Algebra/Embedded_Algebras.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677660619633, "lm_q2_score": 0.8519527982093666, "lm_q1q2_score": 0.7224285110878352}}
{"text": "(*  Title:       NaturalTransformation\n    Author:      Eugene W. Stark <stark@cs.stonybrook.edu>, 2016\n    Maintainer:  Eugene W. Stark <stark@cs.stonybrook.edu>\n*)\n\nchapter NaturalTransformation\n\ntheory NaturalTransformation\nimports Functor\nbegin\n\n  section \"Definition of a Natural Transformation\"\n    \n  text\\<open>\n    As is the case for functors, the ``object-free'' definition of category\n    makes it possible to view natural transformations as functions on arrows.\n    In particular, a natural transformation between functors\n    @{term F} and @{term G} from @{term A} to @{term B} can be represented by\n    the map that takes each arrow @{term f} of @{term A} to the diagonal of the\n    square in @{term B} corresponding to the transformation of @{term \"F f\"}\n    to @{term \"G f\"}.  The images of the identities of @{term A} under this\n    map are the usual components of the natural transformation.\n    This representation exhibits natural transformations as a kind of generalization\n    of functors, and in fact we can directly identify functors with identity\n    natural transformations.\n    However, functors are still necessary to state the defining conditions for\n    a natural transformation, as the domain and codomain of a natural transformation\n    cannot be recovered from the map on arrows that represents it.\n\n    Like functors, natural transformations preserve arrows and map non-arrows to null.\n    Natural transformations also ``preserve'' domain and codomain, but in a more general\n    sense than functors. The naturality conditions, which express the two ways of factoring\n    the diagonal of a commuting square, are degenerate in the case of an identity transformation.\n\\<close>\n\n  locale natural_transformation =\n    A: category A +\n    B: category B + \n    F: \"functor\" A B F +\n    G: \"functor\" A B G\n  for A :: \"'a comp\"      (infixr \"\\<cdot>\\<^sub>A\" 55)\n  and B :: \"'b comp\"      (infixr \"\\<cdot>\\<^sub>B\" 55)\n  and F :: \"'a \\<Rightarrow> 'b\"\n  and G :: \"'a \\<Rightarrow> 'b\"\n  and \\<tau> :: \"'a \\<Rightarrow> 'b\" +\n  assumes is_extensional: \"\\<not>A.arr f \\<Longrightarrow> \\<tau> f = B.null\"\n  and preserves_dom [iff]: \"A.arr f \\<Longrightarrow> B.dom (\\<tau> f) = F (A.dom f)\"\n  and preserves_cod [iff]: \"A.arr f \\<Longrightarrow> B.cod (\\<tau> f) = G (A.cod f)\"\n  and is_natural_1 [iff]: \"A.arr f \\<Longrightarrow> G f \\<cdot>\\<^sub>B \\<tau> (A.dom f) = \\<tau> f\"\n  and is_natural_2 [iff]: \"A.arr f \\<Longrightarrow> \\<tau> (A.cod f) \\<cdot>\\<^sub>B F f = \\<tau> f\"\n  begin\n\n    lemma naturality:\n    assumes \"A.arr f\"\n    shows \"\\<tau> (A.cod f) \\<cdot>\\<^sub>B F f = G f \\<cdot>\\<^sub>B \\<tau> (A.dom f)\"\n      using assms is_natural_1 is_natural_2 by simp\n\n    text\\<open>\n      The following fact for natural transformations provides us with the same advantages\n      as the corresponding fact for functors.\n\\<close>\n\n    lemma preserves_reflects_arr [iff]:\n    shows \"B.arr (\\<tau> f) \\<longleftrightarrow> A.arr f\"\n      using is_extensional A.arr_cod_iff_arr B.arr_cod_iff_arr preserves_cod by force\n\n    lemma preserves_hom [intro]:\n    assumes \"\\<guillemotleft>f : a \\<rightarrow>\\<^sub>A b\\<guillemotright>\"\n    shows \"\\<guillemotleft>\\<tau> f : F a \\<rightarrow>\\<^sub>B G b\\<guillemotright>\"\n      using assms\n      by (metis A.in_homE B.arr_cod_iff_arr B.in_homI G.preserves_arr G.preserves_cod\n          preserves_cod preserves_dom)\n\n    lemma preserves_comp_1:\n    assumes \"A.seq f' f\"\n    shows \"\\<tau> (f' \\<cdot>\\<^sub>A f) = G f' \\<cdot>\\<^sub>B \\<tau> f\"\n      using assms\n      by (metis A.seqE A.dom_comp B.comp_assoc G.preserves_comp is_natural_1)\n\n    lemma preserves_comp_2:\n    assumes \"A.seq f' f\"\n    shows \"\\<tau> (f' \\<cdot>\\<^sub>A f) = \\<tau> f' \\<cdot>\\<^sub>B F f\"\n      using assms\n      by (metis A.arr_cod_iff_arr A.cod_comp B.comp_assoc F.preserves_comp is_natural_2)\n\n    text\\<open>\n      A natural transformation that also happens to be a functor is equal to\n      its own domain and codomain.\n\\<close>\n\n    lemma functor_implies_equals_dom:\n    assumes \"functor A B \\<tau>\"\n    shows \"F = \\<tau>\"\n    proof\n      interpret \\<tau>: \"functor\" A B \\<tau> using assms by auto\n      fix f\n      show \"F f = \\<tau> f\"\n        using assms\n        by (metis A.dom_cod B.comp_cod_arr F.is_extensional F.preserves_arr F.preserves_cod\n            \\<tau>.preserves_dom is_extensional is_natural_2 preserves_dom)\n    qed\n\n    lemma functor_implies_equals_cod:\n    assumes \"functor A B \\<tau>\"\n    shows \"G = \\<tau>\"\n    proof\n      interpret \\<tau>: \"functor\" A B \\<tau> using assms by auto\n      fix f\n      show \"G f = \\<tau> f\"\n        using assms\n        by (metis A.cod_dom B.comp_arr_dom F.preserves_arr G.is_extensional G.preserves_arr\n            G.preserves_dom B.cod_dom functor_implies_equals_dom is_extensional\n            is_natural_1 preserves_cod preserves_dom)\n    qed\n          \n  end\n\n  section \"Components of a Natural Transformation\"\n\n  text\\<open>\n    The values taken by a natural transformation on identities are the \\emph{components}\n    of the transformation.  We have the following basic technique for proving two natural\n    transformations equal: show that they have the same components.\n\\<close>\n\n  lemma eqI:\n  assumes \"natural_transformation A B F G \\<sigma>\" and \"natural_transformation A B F G \\<sigma>'\"\n  and \"\\<And>a. partial_magma.ide A a \\<Longrightarrow> \\<sigma> a = \\<sigma>' a\"\n  shows \"\\<sigma> = \\<sigma>'\"\n  proof -\n    interpret A: category A using assms(1) natural_transformation_def by blast\n    interpret \\<sigma>: natural_transformation A B F G \\<sigma> using assms(1) by auto\n    interpret \\<sigma>': natural_transformation A B F G \\<sigma>' using assms(2) by auto\n    have \"\\<And>f. \\<sigma> f = \\<sigma>' f\"\n      using assms(3) \\<sigma>.is_natural_2 \\<sigma>'.is_natural_2 \\<sigma>.is_extensional \\<sigma>'.is_extensional A.ide_cod\n      by metis\n    thus ?thesis by auto\n  qed\n\n  text\\<open>\n    As equality of natural transformations is determined by equality of components,\n    a natural transformation may be uniquely defined by specifying its components.\n    The extension to all arrows is given by @{prop is_natural_1} or equivalently\n    by @{prop is_natural_2}.\n\\<close>\n\n  locale transformation_by_components =\n    A: category A +\n    B: category B + \n    F: \"functor\" A B F +\n    G: \"functor\" A B G\n  for A :: \"'a comp\"      (infixr \"\\<cdot>\\<^sub>A\" 55)\n  and B :: \"'b comp\"      (infixr \"\\<cdot>\\<^sub>B\" 55)\n  and F :: \"'a \\<Rightarrow> 'b\"\n  and G :: \"'a \\<Rightarrow> 'b\"\n  and t :: \"'a \\<Rightarrow> 'b\" +\n  assumes maps_ide_in_hom [intro]: \"A.ide a \\<Longrightarrow> \\<guillemotleft>t a : F a \\<rightarrow>\\<^sub>B G a\\<guillemotright>\"\n  and is_natural: \"A.arr f \\<Longrightarrow> t (A.cod f) \\<cdot>\\<^sub>B F f = G f \\<cdot>\\<^sub>B t (A.dom f)\"\n  begin\n\n    definition map\n    where \"map f = (if A.arr f then t (A.cod f) \\<cdot>\\<^sub>B F f else B.null)\"\n\n    lemma map_simp_ide [simp]:\n    assumes \"A.ide a\"\n    shows \"map a = t a\"\n      using assms map_def B.comp_arr_dom [of \"t a\"] maps_ide_in_hom by fastforce\n\n    lemma is_natural_transformation:\n    shows \"natural_transformation A B F G map\"\n      using map_def is_natural\n      apply (unfold_locales, simp_all)\n         apply (metis A.ide_dom B.dom_comp B.seqI\n                      G.preserves_arr G.preserves_dom B.in_homE maps_ide_in_hom)\n        apply (metis A.ide_dom B.arrI B.cod_comp B.in_homE B.seqI\n                     G.preserves_arr G.preserves_cod G.preserves_dom maps_ide_in_hom)\n       apply (metis A.ide_dom B.comp_arr_dom B.in_homE maps_ide_in_hom)\n      by (metis B.comp_assoc A.comp_cod_arr F.preserves_comp)\n\n  end\n\n  sublocale transformation_by_components \\<subseteq> natural_transformation A B F G map\n    using is_natural_transformation by auto\n\n  lemma transformation_by_components_idem [simp]:\n  assumes \"natural_transformation A B F G \\<tau>\"\n  shows \"transformation_by_components.map A B F \\<tau> = \\<tau>\"\n  proof -\n    interpret \\<tau>: natural_transformation A B F G \\<tau> using assms by blast\n    interpret \\<tau>': transformation_by_components A B F G \\<tau>\n      by (unfold_locales, auto) \n    show ?thesis\n      using assms \\<tau>'.map_simp_ide \\<tau>'.is_natural_transformation eqI by blast\n  qed\n\n  section \"Functors as Natural Transformations\"\n\n  text\\<open>\n    A functor is a special case of a natural transformation, in the sense that the same map\n    that defines the functor also defines an identity natural transformation.\n\\<close>\n\n  lemma functor_is_transformation [simp]:\n  assumes \"functor A B F\"\n  shows \"natural_transformation A B F F F\"\n  proof -\n    interpret \"functor\" A B F using assms by auto\n    show \"natural_transformation A B F F F\"\n      using is_extensional B.comp_arr_dom B.comp_cod_arr\n      by (unfold_locales, simp_all)\n  qed\n\n  sublocale \"functor\" \\<subseteq> natural_transformation A B F F F\n    by (simp add: functor_axioms)\n\n  section \"Constant Natural Transformations\"\n\n  text\\<open>\n    A constant natural transformation is one whose components are all the same arrow.\n\\<close>\n\n  locale constant_transformation =\n    A: category A +\n    B: category B +\n    F: constant_functor A B \"B.dom g\" +\n    G: constant_functor A B \"B.cod g\"\n  for A :: \"'a comp\"      (infixr \"\\<cdot>\\<^sub>A\" 55)\n  and B :: \"'b comp\"      (infixr \"\\<cdot>\\<^sub>B\" 55)\n  and g :: 'b +\n  assumes value_is_arr: \"B.arr g\"\n  begin\n\n    definition map\n    where \"map f \\<equiv> if A.arr f then g else B.null\"\n\n    lemma map_simp [simp]:\n    assumes \"A.arr f\"\n    shows \"map f = g\"\n      using assms map_def by auto\n\n    lemma is_natural_transformation:\n    shows \"natural_transformation A B F.map G.map map\"\n      apply unfold_locales\n      using map_def value_is_arr B.comp_arr_dom B.comp_cod_arr by auto\n\n    lemma is_functor_if_value_is_ide:\n    assumes \"B.ide g\"\n    shows \"functor A B map\"\n      apply unfold_locales using assms map_def by auto\n\n  end\n\n  sublocale constant_transformation \\<subseteq> natural_transformation A B F.map G.map map\n    using is_natural_transformation by auto\n\n  context constant_transformation\n  begin\n\n    lemma equals_dom_if_value_is_ide:\n    assumes \"B.ide g\"\n    shows \"map = F.map\"\n      using assms functor_implies_equals_dom is_functor_if_value_is_ide by auto\n\n    lemma equals_cod_if_value_is_ide:\n    assumes \"B.ide g\"\n    shows \"map = G.map\"\n      using assms functor_implies_equals_dom is_functor_if_value_is_ide by auto\n\n  end\n\n  section \"Vertical Composition\"\n\n  text\\<open>\n    Vertical composition is a way of composing natural transformations \\<open>\\<sigma>: F \\<rightarrow> G\\<close>\n    and \\<open>\\<tau>: G \\<rightarrow> H\\<close>, between parallel functors @{term F}, @{term G}, and @{term H}\n    to obtain a natural transformation from @{term F} to @{term H}.\n    The composite is traditionally denoted by \\<open>\\<tau> o \\<sigma>\\<close>, however in the present\n    setting this notation is misleading because it is horizontal composite, rather than\n    vertical composite, that coincides with composition of natural transformations as\n    functions on arrows.\n\\<close>\n\n  locale vertical_composite =\n    A: category A +\n    B: category B +\n    F: \"functor\" A B F +\n    G: \"functor\" A B G +\n    H: \"functor\" A B H +\n    \\<sigma>: natural_transformation A B F G \\<sigma> +\n    \\<tau>: natural_transformation A B G H \\<tau>\n  for A :: \"'a comp\"      (infixr \"\\<cdot>\\<^sub>A\" 55)\n  and B :: \"'b comp\"      (infixr \"\\<cdot>\\<^sub>B\" 55)\n  and F :: \"'a \\<Rightarrow> 'b\"\n  and G :: \"'a \\<Rightarrow> 'b\"\n  and H :: \"'a \\<Rightarrow> 'b\"\n  and \\<sigma> :: \"'a \\<Rightarrow> 'b\"\n  and \\<tau> :: \"'a \\<Rightarrow> 'b\"\n  begin\n\n    text\\<open>\n      Vertical composition takes an arrow @{term \"A.in_hom a b f\"} to an arrow in\n      @{term \"B.hom (F a) (G b)\"}, which we can obtain by forming either of\n      the composites @{term \"B (\\<tau> b) (\\<sigma> f)\"} or @{term \"B (\\<tau> f) (\\<sigma> a)\"}, which are\n      equal to each other.\n\\<close>\n\n    definition map\n    where \"map f = (if A.arr f then \\<tau> (A.cod f) \\<cdot>\\<^sub>B \\<sigma> f else B.null)\"\n\n    lemma map_seq:\n    assumes \"A.arr f\"\n    shows \"B.seq (\\<tau> (A.cod f)) (\\<sigma> f)\"\n      using assms by auto\n\n    lemma map_simp_ide:\n    assumes \"A.ide a\"\n    shows \"map a = \\<tau> a \\<cdot>\\<^sub>B \\<sigma> a\"\n      using assms map_def by auto\n\n    lemma map_simp_1:\n    assumes \"A.arr f\"\n    shows \"map f = \\<tau> (A.cod f) \\<cdot>\\<^sub>B \\<sigma> f\"\n      using assms by (simp add: map_def)\n\n    lemma map_simp_2:\n    assumes \"A.arr f\"\n    shows \"map f = \\<tau> f \\<cdot>\\<^sub>B \\<sigma> (A.dom f)\"\n      using assms\n      by (metis B.comp_assoc \\<sigma>.is_natural_2 \\<sigma>.naturality \\<tau>.is_natural_1 \\<tau>.naturality map_simp_1)\n\n    lemma is_natural_transformation:\n    shows \"natural_transformation A B F H map\"\n      using map_def map_simp_1 map_simp_2 map_seq B.comp_assoc\n      apply (unfold_locales, simp_all)\n      by (metis B.comp_assoc \\<tau>.is_natural_1)\n\n  end\n\n  sublocale vertical_composite \\<subseteq> natural_transformation A B F H map\n    using is_natural_transformation by auto\n\n  text\\<open>\n    Functors are the identities for vertical composition.\n\\<close>\n\n  lemma vcomp_ide_dom [simp]:\n  assumes \"natural_transformation A B F G \\<tau>\"\n  shows \"vertical_composite.map A B F \\<tau> = \\<tau>\"\n    using assms apply (intro eqI)\n      apply auto[2]\n     apply (meson functor_is_transformation natural_transformation_def vertical_composite.intro\n                  vertical_composite.is_natural_transformation)\n  proof -\n    fix a :: 'a\n    have \"vertical_composite A B F F G F \\<tau>\"\n      by (meson assms functor_is_transformation natural_transformation.axioms(1-4)\n                vertical_composite.intro)\n    thus \"vertical_composite.map A B F \\<tau> a = \\<tau> a\"\n      using assms natural_transformation.is_extensional natural_transformation.is_natural_2\n            vertical_composite.map_def\n      by fastforce\n  qed\n    \n  lemma vcomp_ide_cod [simp]:\n  assumes \"natural_transformation A B F G \\<tau>\"\n  shows \"vertical_composite.map A B \\<tau> G = \\<tau>\"\n    using assms apply (intro eqI)\n      apply auto[2]\n     apply (meson functor_is_transformation natural_transformation_def vertical_composite.intro\n                  vertical_composite.is_natural_transformation)\n  proof -\n    fix a :: 'a\n    assume a: \"partial_magma.ide A a\"\n    interpret Go\\<tau>: vertical_composite A B F G G \\<tau> G\n      by (meson assms functor_is_transformation natural_transformation.axioms(1-4)\n                vertical_composite.intro)\n    show \"vertical_composite.map A B \\<tau> G a = \\<tau> a\"\n      using assms a natural_transformation.is_extensional natural_transformation.is_natural_1\n            Go\\<tau>.map_simp_ide Go\\<tau>.B.comp_cod_arr\n      by simp\n  qed\n\n  text\\<open>\n    Vertical composition is associative.\n\\<close>\n\n  lemma vcomp_assoc [simp]:\n  assumes \"natural_transformation A B F G \\<rho>\"\n  and \"natural_transformation A B G H \\<sigma>\"\n  and \"natural_transformation A B H K \\<tau>\"\n  shows \"vertical_composite.map A B (vertical_composite.map A B \\<rho> \\<sigma>) \\<tau>\n            = vertical_composite.map A B \\<rho> (vertical_composite.map A B \\<sigma> \\<tau>)\"\n  proof -\n    interpret A: category A\n      using assms(1) natural_transformation_def functor_def by blast\n    interpret B: category B\n      using assms(1) natural_transformation_def functor_def by blast\n    interpret \\<rho>: natural_transformation A B F G \\<rho> using assms(1) by auto\n    interpret \\<sigma>: natural_transformation A B G H \\<sigma> using assms(2) by auto\n    interpret \\<tau>: natural_transformation A B H K \\<tau> using assms(3) by auto\n    interpret \\<rho>\\<sigma>: vertical_composite A B F G H \\<rho> \\<sigma> ..\n    interpret \\<sigma>\\<tau>: vertical_composite A B G H K \\<sigma> \\<tau> ..\n    interpret \\<rho>_\\<sigma>\\<tau>: vertical_composite A B F G K \\<rho> \\<sigma>\\<tau>.map ..\n    interpret \\<rho>\\<sigma>_\\<tau>: vertical_composite A B F H K \\<rho>\\<sigma>.map \\<tau> ..\n    show ?thesis\n      using \\<rho>\\<sigma>_\\<tau>.is_natural_transformation \\<rho>_\\<sigma>\\<tau>.natural_transformation_axioms\n            \\<rho>\\<sigma>.map_simp_ide \\<rho>\\<sigma>_\\<tau>.map_simp_ide \\<rho>_\\<sigma>\\<tau>.map_simp_ide \\<sigma>\\<tau>.map_simp_ide B.comp_assoc\n      by (intro eqI, auto)\n  qed\n\n  section \"Natural Isomorphisms\"\n\n  text\\<open>\n    A natural isomorphism is a natural transformation each of whose components\n    is an isomorphism.  Equivalently, a natural isomorphism is a natural transformation\n    that is invertible with respect to vertical composition.\n\\<close>\n\n  locale natural_isomorphism = natural_transformation A B F G \\<tau>\n  for A :: \"'a comp\"      (infixr \"\\<cdot>\\<^sub>A\" 55)\n  and B :: \"'b comp\"      (infixr \"\\<cdot>\\<^sub>B\" 55)\n  and F :: \"'a \\<Rightarrow> 'b\"\n  and G :: \"'a \\<Rightarrow> 'b\"\n  and \\<tau> :: \"'a \\<Rightarrow> 'b\" +\n  assumes components_are_iso [simp]: \"A.ide a \\<Longrightarrow> B.iso (\\<tau> a)\"\n  begin\n\n    text \\<open>\n      Natural isomorphisms preserve isomorphisms, in the sense that the sides of\n      of the naturality square determined by an isomorphism are all isomorphisms,\n      so the diagonal is, as well.\n\\<close>\n\n    lemma preserves_iso:\n    assumes \"A.iso f\"\n    shows \"B.iso (\\<tau> f)\"\n      using assms\n      by (metis A.ide_dom A.iso_is_arr B.isos_compose G.preserves_iso components_are_iso\n          is_natural_2 naturality preserves_reflects_arr)\n\n  end\n\n  text \\<open>\n    Since the function that represents a functor is formally identical to the function\n    that represents the corresponding identity natural transformation, no additional locale\n    is needed for identity natural transformations.  However, an identity natural transformation\n    is also a natural isomorphism, so it is useful for @{locale functor} to inherit from the\n    @{locale natural_isomorphism} locale.\n\\<close>\n\n  sublocale \"functor\" \\<subseteq> natural_isomorphism A B F F F\n    apply unfold_locales\n    using preserves_ide B.ide_is_iso by simp\n\n  definition naturally_isomorphic\n  where \"naturally_isomorphic A B F G = (\\<exists>\\<tau>. natural_isomorphism A B F G \\<tau>)\"\n\n  lemma naturally_isomorphic_respects_full_functor:\n  assumes \"naturally_isomorphic A B F G\"\n  and \"full_functor A B F\"\n  shows \"full_functor A B G\"\n  proof -\n    obtain \\<phi> where \\<phi>: \"natural_isomorphism A B F G \\<phi>\"\n      using assms naturally_isomorphic_def by blast\n    interpret \\<phi>: natural_isomorphism A B F G \\<phi>\n      using \\<phi> by auto\n    interpret \\<phi>.F: full_functor A B F\n      using assms by auto\n    write A (infixr \"\\<cdot>\\<^sub>A\" 55)\n    write B (infixr \"\\<cdot>\\<^sub>B\" 55)\n    write \\<phi>.A.in_hom (\"\\<guillemotleft>_ : _ \\<rightarrow>\\<^sub>A _\\<guillemotright>\")\n    write \\<phi>.B.in_hom (\"\\<guillemotleft>_ : _ \\<rightarrow>\\<^sub>B _\\<guillemotright>\")\n    show \"full_functor A B G\"\n    proof\n      fix a a' g\n      assume a': \"\\<phi>.A.ide a'\" and a: \"\\<phi>.A.ide a\"\n      and g: \"\\<guillemotleft>g : G a' \\<rightarrow>\\<^sub>B G a\\<guillemotright>\"\n      show \"\\<exists>f. \\<guillemotleft>f : a' \\<rightarrow>\\<^sub>A a\\<guillemotright> \\<and> G f = g\"\n      proof -\n        let ?g' = \"\\<phi>.B.inv (\\<phi> a) \\<cdot>\\<^sub>B g \\<cdot>\\<^sub>B \\<phi> a'\"\n        have g': \"\\<guillemotleft>?g' : F a' \\<rightarrow>\\<^sub>B F a\\<guillemotright>\"\n          using a a' g \\<phi>.preserves_hom \\<phi>.components_are_iso \\<phi>.B.inv_in_hom by force\n        obtain f' where f': \"\\<guillemotleft>f' : a' \\<rightarrow>\\<^sub>A a\\<guillemotright> \\<and> F f' = ?g'\"\n          using a a' g' \\<phi>.F.is_full [of a a' ?g'] by blast\n        moreover have \"G f' = g\"\n        proof -\n          have \"G f' = \\<phi> a \\<cdot>\\<^sub>B ?g' \\<cdot>\\<^sub>B \\<phi>.B.inv (\\<phi> a')\"\n            using a a' f' \\<phi>.naturality [of f'] \\<phi>.components_are_iso \\<phi>.is_natural_2\n            by (metis \\<phi>.A.in_homE \\<phi>.B.comp_assoc \\<phi>.B.invert_side_of_triangle(2)\n                \\<phi>.preserves_reflects_arr)\n          also have \"... = (\\<phi> a \\<cdot>\\<^sub>B \\<phi>.B.inv (\\<phi> a)) \\<cdot>\\<^sub>B g \\<cdot>\\<^sub>B \\<phi> a' \\<cdot>\\<^sub>B \\<phi>.B.inv (\\<phi> a')\"\n            using \\<phi>.B.comp_assoc by auto\n          also have \"... = g\"\n            using a a' g \\<phi>.B.comp_arr_dom \\<phi>.B.comp_cod_arr \\<phi>.B.comp_arr_inv\n                  \\<phi>.B.inv_is_inverse\n            by auto\n          finally show ?thesis by blast\n        qed\n        ultimately show ?thesis by auto\n      qed\n    qed\n  qed\n\n  lemma naturally_isomorphic_respects_faithful_functor:\n  assumes \"naturally_isomorphic A B F G\"\n  and \"faithful_functor A B F\"\n  shows \"faithful_functor A B G\"\n  proof -\n    obtain \\<phi> where \\<phi>: \"natural_isomorphism A B F G \\<phi>\"\n      using assms naturally_isomorphic_def by blast\n    interpret \\<phi>: natural_isomorphism A B F G \\<phi>\n      using \\<phi> by auto\n    interpret \\<phi>.F: faithful_functor A B F\n      using assms by auto\n    show \"faithful_functor A B G\"\n      using \\<phi>.naturality \\<phi>.components_are_iso \\<phi>.B.iso_is_section \\<phi>.B.section_is_mono\n            \\<phi>.B.monoE \\<phi>.F.is_faithful \\<phi>.is_natural_1 \\<phi>.natural_transformation_axioms\n            \\<phi>.preserves_reflects_arr \\<phi>.A.ide_cod\n      by (unfold_locales, metis)\n  qed\n\n  locale inverse_transformation =\n    A: category A +\n    B: category B +\n    F: \"functor\" A B F +\n    G: \"functor\" A B G +\n    \\<tau>: natural_isomorphism A B F G \\<tau>\n  for A :: \"'a comp\"      (infixr \"\\<cdot>\\<^sub>A\" 55)\n  and B :: \"'b comp\"      (infixr \"\\<cdot>\\<^sub>B\" 55)\n  and F :: \"'a \\<Rightarrow> 'b\"\n  and G :: \"'a \\<Rightarrow> 'b\"\n  and \\<tau> :: \"'a \\<Rightarrow> 'b\"\n  begin\n\n    interpretation \\<tau>': transformation_by_components A B G F \\<open>\\<lambda>a. B.inv (\\<tau> a)\\<close>\n    proof\n      fix f :: 'a\n      show \"A.ide f \\<Longrightarrow> \\<guillemotleft>B.inv (\\<tau> f) : G f \\<rightarrow>\\<^sub>B F f\\<guillemotright>\"\n        using B.inv_in_hom \\<tau>.components_are_iso A.ide_in_hom by blast\n      show \"A.arr f \\<Longrightarrow> B.inv (\\<tau> (A.cod f)) \\<cdot>\\<^sub>B G f = F f \\<cdot>\\<^sub>B B.inv (\\<tau> (A.dom f))\"\n        by (metis A.ide_cod A.ide_dom B.invert_opposite_sides_of_square \\<tau>.components_are_iso\n            \\<tau>.is_natural_2 \\<tau>.naturality \\<tau>.preserves_reflects_arr)\n    qed\n\n    definition map\n    where \"map = \\<tau>'.map\"\n\n    lemma map_ide_simp [simp]:\n    assumes \"A.ide a\"\n    shows \"map a = B.inv (\\<tau> a)\"\n      using assms map_def by fastforce\n\n    lemma map_simp:\n    assumes \"A.arr f\"\n    shows \"map f = B.inv (\\<tau> (A.cod f)) \\<cdot>\\<^sub>B G f\"\n      using assms map_def by (simp add: \\<tau>'.map_def)\n\n    lemma is_natural_transformation:\n    shows \"natural_transformation A B G F map\"\n      by (simp add: \\<tau>'.natural_transformation_axioms map_def)\n\n    lemma inverts_components:\n    assumes \"A.ide a\"\n    shows \"B.inverse_arrows (\\<tau> a) (map a)\"\n      using assms \\<tau>.components_are_iso B.ide_is_iso B.inv_is_inverse B.inverse_arrows_def map_def\n      by (metis \\<tau>'.map_simp_ide)\n\n  end\n\n  sublocale inverse_transformation \\<subseteq> natural_transformation A B G F map\n    using is_natural_transformation by auto\n\n  sublocale inverse_transformation \\<subseteq> natural_isomorphism A B G F map\n    by (simp add: B.iso_inv_iso natural_isomorphism.intro natural_isomorphism_axioms.intro\n        natural_transformation_axioms)\n\n  lemma inverse_inverse_transformation [simp]:\n  assumes \"natural_isomorphism A B F G \\<tau>\"\n  shows \"inverse_transformation.map A B F (inverse_transformation.map A B G \\<tau>) = \\<tau>\"\n  proof -\n    interpret \\<tau>: natural_isomorphism A B F G \\<tau>\n      using assms by auto\n    interpret \\<tau>': inverse_transformation A B F G \\<tau> ..\n    interpret \\<tau>'': inverse_transformation A B G F \\<tau>'.map ..\n    show \"\\<tau>''.map = \\<tau>\"\n      using \\<tau>.natural_transformation_axioms \\<tau>''.natural_transformation_axioms   \n      by (intro eqI, auto)\n  qed\n\n  locale inverse_transformations =\n    A: category A +\n    B: category B +\n    F: \"functor\" A B F +\n    G: \"functor\" A B G +\n    \\<tau>: natural_transformation A B F G \\<tau> +\n    \\<tau>': natural_transformation A B G F \\<tau>'\n  for A :: \"'a comp\"      (infixr \"\\<cdot>\\<^sub>A\" 55)\n  and B :: \"'b comp\"      (infixr \"\\<cdot>\\<^sub>B\" 55)\n  and F :: \"'a \\<Rightarrow> 'b\"\n  and G :: \"'a \\<Rightarrow> 'b\"\n  and \\<tau> :: \"'a \\<Rightarrow> 'b\"\n  and \\<tau>' :: \"'a \\<Rightarrow> 'b\" +\n  assumes inv: \"A.ide a \\<Longrightarrow> B.inverse_arrows (\\<tau> a) (\\<tau>' a)\"\n\n  sublocale inverse_transformations \\<subseteq> natural_isomorphism A B F G \\<tau>\n    by (meson B.category_axioms \\<tau>.natural_transformation_axioms B.iso_def inv\n              natural_isomorphism.intro natural_isomorphism_axioms.intro)\n  sublocale inverse_transformations \\<subseteq> natural_isomorphism A B G F \\<tau>'\n    by (meson category.inverse_arrows_sym category.iso_def inverse_transformations_axioms\n              inverse_transformations_axioms_def inverse_transformations_def\n              natural_isomorphism.intro natural_isomorphism_axioms.intro)\n\n  lemma inverse_transformations_sym:\n  assumes \"inverse_transformations A B F G \\<sigma> \\<sigma>'\"\n  shows \"inverse_transformations A B G F \\<sigma>' \\<sigma>\"\n    using assms\n    by (simp add: category.inverse_arrows_sym inverse_transformations_axioms_def\n                  inverse_transformations_def)\n\n  lemma inverse_transformations_inverse:\n  assumes \"inverse_transformations A B F G \\<sigma> \\<sigma>'\"\n  shows \"vertical_composite.map A B \\<sigma> \\<sigma>' = F\"\n  and \"vertical_composite.map A B \\<sigma>' \\<sigma> = G\"\n  proof -\n    interpret A: category A\n      using assms(1) inverse_transformations_def natural_transformation_def by blast\n    interpret inv: inverse_transformations A B F G \\<sigma> \\<sigma>' using assms by auto\n    interpret \\<sigma>\\<sigma>': vertical_composite A B F G F \\<sigma> \\<sigma>' ..\n    show \"vertical_composite.map A B \\<sigma> \\<sigma>' = F\"\n      using \\<sigma>\\<sigma>'.is_natural_transformation inv.F.natural_transformation_axioms\n            \\<sigma>\\<sigma>'.map_simp_ide inv.B.comp_inv_arr inv.inv\n      by (intro eqI, simp_all)\n    interpret inv': inverse_transformations A B G F \\<sigma>' \\<sigma>\n      using assms inverse_transformations_sym by blast\n    interpret \\<sigma>'\\<sigma>: vertical_composite A B G F G \\<sigma>' \\<sigma> ..\n    show \"vertical_composite.map A B \\<sigma>' \\<sigma> = G\"\n      using \\<sigma>'\\<sigma>.is_natural_transformation inv.G.natural_transformation_axioms\n            \\<sigma>'\\<sigma>.map_simp_ide inv'.inv inv.B.comp_inv_arr\n      by (intro eqI, simp_all)\n  qed\n\n  lemma inverse_transformations_compose:\n  assumes \"inverse_transformations A B F G \\<sigma> \\<sigma>'\"\n  and \"inverse_transformations A B G H \\<tau> \\<tau>'\"\n  shows \"inverse_transformations A B F H\n           (vertical_composite.map A B \\<sigma> \\<tau>) (vertical_composite.map A B \\<tau>' \\<sigma>')\"\n  proof -\n    interpret A: category A using assms(1) inverse_transformations_def by blast\n    interpret B: category B using assms(1) inverse_transformations_def by blast\n    interpret \\<sigma>\\<sigma>': inverse_transformations A B F G \\<sigma> \\<sigma>' using assms(1) by auto\n    interpret \\<tau>\\<tau>': inverse_transformations A B G H \\<tau> \\<tau>' using assms(2) by auto\n    interpret \\<sigma>\\<tau>: vertical_composite A B F G H \\<sigma> \\<tau> ..\n    interpret \\<tau>'\\<sigma>': vertical_composite A B H G F \\<tau>' \\<sigma>' ..\n    show ?thesis\n      using B.inverse_arrows_compose \\<sigma>\\<sigma>'.inv \\<sigma>\\<tau>.map_simp_ide \\<tau>'\\<sigma>'.map_simp_ide \\<tau>\\<tau>'.inv\n      by (unfold_locales, auto)\n  qed\n\n  lemma vertical_composite_iso_inverse [simp]:\n  assumes \"natural_isomorphism A B F G \\<tau>\"\n  shows \"vertical_composite.map A B \\<tau> (inverse_transformation.map A B G \\<tau>) = F\"\n  proof -\n    interpret \\<tau>: natural_isomorphism A B F G \\<tau> using assms by auto\n    interpret \\<tau>': inverse_transformation A B F G \\<tau> ..\n    interpret \\<tau>\\<tau>': vertical_composite A B F G F \\<tau> \\<tau>'.map ..\n    show ?thesis\n      using \\<tau>\\<tau>'.is_natural_transformation \\<tau>.F.natural_transformation_axioms \\<tau>'.inverts_components\n            \\<tau>.B.comp_inv_arr \\<tau>\\<tau>'.map_simp_ide\n      by (intro eqI, auto)\n  qed\n\n  lemma vertical_composite_inverse_iso [simp]:\n  assumes \"natural_isomorphism A B F G \\<tau>\"\n  shows \"vertical_composite.map A B (inverse_transformation.map A B G \\<tau>) \\<tau> = G\"\n  proof -\n    interpret \\<tau>: natural_isomorphism A B F G \\<tau> using assms by auto\n    interpret \\<tau>': inverse_transformation A B F G \\<tau> ..\n    interpret \\<tau>'\\<tau>: vertical_composite A B G F G \\<tau>'.map \\<tau> ..    \n    show ?thesis\n      using \\<tau>'\\<tau>.is_natural_transformation \\<tau>.G.natural_transformation_axioms \\<tau>'.inverts_components\n            \\<tau>'\\<tau>.map_simp_ide \\<tau>.B.comp_arr_inv\n      by (intro eqI, auto)\n  qed\n\n  lemma natural_isomorphisms_compose:\n  assumes \"natural_isomorphism A B F G \\<sigma>\" and \"natural_isomorphism A B G H \\<tau>\"\n  shows \"natural_isomorphism A B F H (vertical_composite.map A B \\<sigma> \\<tau>)\"\n  proof -\n    interpret A: category A\n      using assms(1) natural_isomorphism_def natural_transformation_def by blast\n    interpret B: category B\n      using assms(1) natural_isomorphism_def natural_transformation_def by blast\n    interpret \\<sigma>: natural_isomorphism A B F G \\<sigma> using assms(1) by auto\n    interpret \\<tau>: natural_isomorphism A B G H \\<tau> using assms(2) by auto\n    interpret \\<sigma>\\<tau>: vertical_composite A B F G H \\<sigma> \\<tau> ..\n    interpret natural_isomorphism A B F H \\<sigma>\\<tau>.map\n      using \\<sigma>\\<tau>.map_simp_ide by (unfold_locales, auto)\n    show ?thesis ..\n  qed\n\n  lemma naturally_isomorphic_reflexive:\n  assumes \"functor A B F\"\n  shows \"naturally_isomorphic A B F F\"\n  proof -\n    interpret F: \"functor\" A B F using assms by auto\n    have \"natural_isomorphism A B F F F\" ..\n    thus ?thesis using naturally_isomorphic_def by blast\n  qed\n\n  lemma naturally_isomorphic_symmetric:\n  assumes \"naturally_isomorphic A B F G\"\n  shows \"naturally_isomorphic A B G F\"\n  proof -\n    obtain \\<phi> where \\<phi>: \"natural_isomorphism A B F G \\<phi>\"\n      using assms naturally_isomorphic_def by blast\n    interpret \\<phi>: natural_isomorphism A B F G \\<phi>\n      using \\<phi> by auto\n    interpret \\<psi>: inverse_transformation A B F G \\<phi> ..\n    have \"natural_isomorphism A B G F \\<psi>.map\" ..\n    thus ?thesis using naturally_isomorphic_def by blast\n  qed\n\n  lemma naturally_isomorphic_transitive [trans]:\n  assumes \"naturally_isomorphic A B F G\"\n  and \"naturally_isomorphic A B G H\"\n  shows \"naturally_isomorphic A B F H\"\n  proof -\n    obtain \\<phi> where \\<phi>: \"natural_isomorphism A B F G \\<phi>\"\n      using assms naturally_isomorphic_def by blast\n    interpret \\<phi>: natural_isomorphism A B F G \\<phi>\n      using \\<phi> by auto\n    obtain \\<psi> where \\<psi>: \"natural_isomorphism A B G H \\<psi>\"\n      using assms naturally_isomorphic_def by blast\n    interpret \\<psi>: natural_isomorphism A B G H \\<psi>\n      using \\<psi> by auto\n    interpret \\<psi>\\<phi>: vertical_composite A B F G H \\<phi> \\<psi> ..\n    have \"natural_isomorphism A B F H \\<psi>\\<phi>.map\"\n      using \\<phi> \\<psi> natural_isomorphisms_compose by blast\n    thus ?thesis\n      using naturally_isomorphic_def by blast\n  qed\n\n  section \"Horizontal Composition\"\n\n  text\\<open>\n    Horizontal composition is a way of composing parallel natural transformations\n    @{term \\<sigma>} from @{term F} to @{term G} and @{term \\<tau>} from @{term H} to @{term K},\n    where functors @{term F} and @{term G} map @{term A} to @{term B} and\n    @{term H} and @{term K} map @{term B} to @{term C}, to obtain a natural transformation\n    from @{term \"H o F\"} to @{term \"K o G\"}.\n\n    Since horizontal composition turns out to coincide with ordinary composition of\n    natural transformations as functions, there is little point in defining a cumbersome\n    locale for horizontal composite.\n\\<close>\n\n  lemma horizontal_composite:\n  assumes \"natural_transformation A B F G \\<sigma>\"\n  and \"natural_transformation B C H K \\<tau>\"\n  shows \"natural_transformation A C (H o F) (K o G) (\\<tau> o \\<sigma>)\"\n  proof -\n    interpret \\<sigma>: natural_transformation A B F G \\<sigma>\n      using assms(1) by simp\n    interpret \\<tau>: natural_transformation B C H K \\<tau>\n      using assms(2) by simp\n    interpret HF: composite_functor A B C F H ..\n    interpret KG: composite_functor A B C G K ..\n    show \"natural_transformation A C (H o F) (K o G) (\\<tau> o \\<sigma>)\"\n      using \\<sigma>.is_extensional \\<tau>.is_extensional\n      apply (unfold_locales, auto)\n       apply (metis \\<sigma>.is_natural_1 \\<sigma>.preserves_reflects_arr \\<tau>.preserves_comp_1)\n      by (metis \\<sigma>.is_natural_2 \\<sigma>.preserves_reflects_arr \\<tau>.preserves_comp_2)\n  qed\n\n  lemma hcomp_ide_dom [simp]:\n  assumes \"natural_transformation A B F G \\<tau>\"\n  shows \"\\<tau> o (identity_functor.map A) = \\<tau>\"\n  proof -\n    interpret \\<tau>: natural_transformation A B F G \\<tau> using assms by auto\n    show \"\\<tau> o \\<tau>.A.map = \\<tau>\"\n      using \\<tau>.A.map_def \\<tau>.is_extensional by fastforce\n  qed\n\n  lemma hcomp_ide_cod [simp]:\n  assumes \"natural_transformation A B F G \\<tau>\"\n  shows \"(identity_functor.map B) o \\<tau> = \\<tau>\"\n  proof -\n    interpret \\<tau>: natural_transformation A B F G \\<tau> using assms by auto\n    show \"\\<tau>.B.map o \\<tau> = \\<tau>\"\n      using \\<tau>.B.map_def \\<tau>.is_extensional by auto\n  qed\n\n  text\\<open>\n    Horizontal composition of a functor with a vertical composite.\n\\<close>\n\n  lemma whisker_right:\n  assumes \"functor A B F\"\n  and \"natural_transformation B C H K \\<tau>\" and \"natural_transformation B C K L \\<tau>'\"\n  shows \"(vertical_composite.map B C \\<tau> \\<tau>') o F = vertical_composite.map A C (\\<tau> o F) (\\<tau>' o F)\"\n  proof -\n    interpret F: \"functor\" A B F using assms(1) by auto\n    interpret \\<tau>: natural_transformation B C H K \\<tau> using assms(2) by auto\n    interpret \\<tau>': natural_transformation B C K L \\<tau>' using assms(3) by auto\n    interpret \\<tau>oF: natural_transformation A C \\<open>H o F\\<close> \\<open>K o F\\<close> \\<open>\\<tau> o F\\<close>\n      using \\<tau>.natural_transformation_axioms F.natural_transformation_axioms\n            horizontal_composite\n      by blast\n    interpret \\<tau>'oF: natural_transformation A C \\<open>K o F\\<close> \\<open>L o F\\<close> \\<open>\\<tau>' o F\\<close>\n      using \\<tau>'.natural_transformation_axioms F.natural_transformation_axioms\n            horizontal_composite\n      by blast\n    interpret \\<tau>'\\<tau>: vertical_composite B C H K L \\<tau> \\<tau>' ..\n    interpret \\<tau>'\\<tau>oF: natural_transformation A C \\<open>H o F\\<close> \\<open>L o F\\<close> \\<open>\\<tau>'\\<tau>.map o F\\<close>\n      using \\<tau>'\\<tau>.natural_transformation_axioms F.natural_transformation_axioms\n            horizontal_composite\n      by blast\n    interpret \\<tau>'oF_\\<tau>oF: vertical_composite A C \\<open>H o F\\<close> \\<open>K o F\\<close> \\<open>L o F\\<close> \\<open>\\<tau> o F\\<close> \\<open>\\<tau>' o F\\<close> ..\n    show ?thesis\n      using \\<tau>'oF_\\<tau>oF.map_def \\<tau>'\\<tau>.map_def \\<tau>'\\<tau>oF.is_extensional by auto\n  qed\n\n  text\\<open>\n    Horizontal composition of a vertical composite with a functor.\n\\<close>\n\n  lemma whisker_left:\n  assumes \"functor B C K\"\n  and \"natural_transformation A B F G \\<tau>\" and \"natural_transformation A B G H \\<tau>'\"\n  shows \"K o (vertical_composite.map A B \\<tau> \\<tau>') = vertical_composite.map A C (K o \\<tau>) (K o \\<tau>')\"\n  proof -\n    interpret K: \"functor\" B C K using assms(1) by auto\n    interpret \\<tau>: natural_transformation A B F G \\<tau> using assms(2) by auto\n    interpret \\<tau>': natural_transformation A B G H \\<tau>' using assms(3) by auto\n    interpret \\<tau>'\\<tau>: vertical_composite A B F G H \\<tau> \\<tau>' ..\n    interpret Ko\\<tau>: natural_transformation A C \\<open>K o F\\<close> \\<open>K o G\\<close> \\<open>K o \\<tau>\\<close>\n      using \\<tau>.natural_transformation_axioms K.natural_transformation_axioms\n            horizontal_composite\n      by blast\n    interpret Ko\\<tau>': natural_transformation A C \\<open>K o G\\<close> \\<open>K o H\\<close> \\<open>K o \\<tau>'\\<close>\n      using \\<tau>'.natural_transformation_axioms K.natural_transformation_axioms\n            horizontal_composite\n      by blast\n    interpret Ko\\<tau>'\\<tau>: natural_transformation A C \\<open>K o F\\<close> \\<open>K o H\\<close> \\<open>K o \\<tau>'\\<tau>.map\\<close>\n      using \\<tau>'\\<tau>.natural_transformation_axioms K.natural_transformation_axioms\n            horizontal_composite\n      by blast\n    interpret Ko\\<tau>'_Ko\\<tau>: vertical_composite A C \\<open>K o F\\<close> \\<open>K o G\\<close> \\<open>K o H\\<close> \\<open>K o \\<tau>\\<close> \\<open>K o \\<tau>'\\<close> ..\n    show \"K o \\<tau>'\\<tau>.map = Ko\\<tau>'_Ko\\<tau>.map\"\n      using Ko\\<tau>'_Ko\\<tau>.map_def \\<tau>'\\<tau>.map_def Ko\\<tau>'\\<tau>.is_extensional Ko\\<tau>'_Ko\\<tau>.map_simp_1 \\<tau>'\\<tau>.map_simp_1\n      by auto\n  qed\n\n  text\\<open>\n    The interchange law for horizontal and vertical composition.\n\\<close>\n\n  lemma interchange:\n  assumes \"natural_transformation B C F G \\<tau>\" and \"natural_transformation B C G H \\<nu>\"\n  and \"natural_transformation C D K L \\<sigma>\" and \"natural_transformation C D L M \\<mu>\"\n  shows \"vertical_composite.map C D \\<sigma> \\<mu> \\<circ> vertical_composite.map B C \\<tau> \\<nu> =\n         vertical_composite.map B D (\\<sigma> \\<circ> \\<tau>) (\\<mu> \\<circ> \\<nu>)\"\n  proof -\n    interpret \\<tau>: natural_transformation B C F G \\<tau>\n       using assms(1) by auto\n    interpret \\<nu>: natural_transformation B C G H \\<nu>\n       using assms(2) by auto\n    interpret \\<sigma>: natural_transformation C D K L \\<sigma>\n       using assms(3) by auto\n    interpret \\<mu>: natural_transformation C D L M \\<mu>\n       using assms(4) by auto\n    interpret \\<nu>\\<tau>: vertical_composite B C F G H \\<tau> \\<nu> ..\n    interpret \\<mu>\\<sigma>: vertical_composite C D K L M \\<sigma> \\<mu> ..\n    interpret \\<sigma>o\\<tau>: natural_transformation B D \\<open>K o F\\<close> \\<open>L o G\\<close> \\<open>\\<sigma> o \\<tau>\\<close>\n      using \\<sigma>.natural_transformation_axioms \\<tau>.natural_transformation_axioms\n            horizontal_composite\n      by blast\n    interpret \\<mu>o\\<nu>: natural_transformation B D \\<open>L o G\\<close> \\<open>M o H\\<close> \\<open>\\<mu> o \\<nu>\\<close>\n      using \\<mu>.natural_transformation_axioms \\<nu>.natural_transformation_axioms\n            horizontal_composite\n      by blast\n    interpret \\<mu>\\<sigma>o\\<nu>\\<tau>: natural_transformation B D \\<open>K o F\\<close> \\<open>M o H\\<close> \\<open>\\<mu>\\<sigma>.map o \\<nu>\\<tau>.map\\<close>\n      using \\<mu>\\<sigma>.natural_transformation_axioms \\<nu>\\<tau>.natural_transformation_axioms\n            horizontal_composite\n      by blast\n    interpret \\<mu>o\\<nu>_\\<sigma>o\\<tau>: vertical_composite B D \\<open>K o F\\<close> \\<open>L o G\\<close> \\<open>M o H\\<close> \\<open>\\<sigma> o \\<tau>\\<close> \\<open>\\<mu> o \\<nu>\\<close> ..\n    show \"\\<mu>\\<sigma>.map o \\<nu>\\<tau>.map = \\<mu>o\\<nu>_\\<sigma>o\\<tau>.map\"\n    proof (intro eqI)\n      show \"natural_transformation B D (K \\<circ> F) (M \\<circ> H) (\\<mu>\\<sigma>.map o \\<nu>\\<tau>.map)\" ..\n      show \"natural_transformation B D (K \\<circ> F) (M \\<circ> H) \\<mu>o\\<nu>_\\<sigma>o\\<tau>.map\" ..\n      show \"\\<And>a. \\<tau>.A.ide a \\<Longrightarrow> (\\<mu>\\<sigma>.map o \\<nu>\\<tau>.map) a = \\<mu>o\\<nu>_\\<sigma>o\\<tau>.map a\"\n      proof -\n        fix a\n        assume a: \"\\<tau>.A.ide a\"\n        have \"(\\<mu>\\<sigma>.map o \\<nu>\\<tau>.map) a = D (\\<mu> (H a)) (\\<sigma> (C (\\<nu> a) (\\<tau> a)))\"\n          using a \\<mu>\\<sigma>.map_simp_1 \\<nu>\\<tau>.map_simp_2 by simp\n        also have \"... = D (\\<mu> (\\<nu> a)) (\\<sigma> (\\<tau> a))\"\n          using a\n          by (metis (full_types) \\<mu>.is_natural_1 \\<mu>\\<sigma>.map_simp_1 \\<mu>\\<sigma>.preserves_comp_1\n              \\<nu>\\<tau>.map_seq \\<nu>\\<tau>.map_simp_1 \\<nu>\\<tau>.preserves_cod \\<sigma>.B.comp_assoc \\<tau>.A.ide_char \\<tau>.B.seqE)\n        also have \"... = \\<mu>o\\<nu>_\\<sigma>o\\<tau>.map a\"\n          using a \\<mu>o\\<nu>_\\<sigma>o\\<tau>.map_simp_ide by simp\n        finally show \"(\\<mu>\\<sigma>.map o \\<nu>\\<tau>.map) a = \\<mu>o\\<nu>_\\<sigma>o\\<tau>.map a\" by blast\n      qed\n    qed\n  qed\n\n  text\\<open>\n    A special-case of the interchange law in which two of the natural transformations\n    are functors.  It comes up reasonably often, and the reasoning is awkward.\n\\<close>\n\n  lemma interchange_spc:\n  assumes \"natural_transformation B C F G \\<sigma>\"\n  and \"natural_transformation C D H K \\<tau>\"\n  shows \"\\<tau> \\<circ> \\<sigma> = vertical_composite.map B D (H o \\<sigma>) (\\<tau> o G)\"\n  and \"\\<tau> \\<circ> \\<sigma> = vertical_composite.map B D (\\<tau> o F) (K o \\<sigma>)\"\n  proof -\n    show \"\\<tau> \\<circ> \\<sigma> = vertical_composite.map B D (H \\<circ> \\<sigma>) (\\<tau> \\<circ> G)\"\n    proof -\n      have \"vertical_composite.map C D H \\<tau> \\<circ> vertical_composite.map B C \\<sigma> G =\n            vertical_composite.map B D (H \\<circ> \\<sigma>) (\\<tau> \\<circ> G)\"\n        by (meson assms functor_is_transformation interchange natural_transformation.axioms(3-4))\n      thus ?thesis\n        using assms by force\n    qed\n    show \"\\<tau> \\<circ> \\<sigma> = vertical_composite.map B D (\\<tau> \\<circ> F) (K \\<circ> \\<sigma>)\"\n    proof -\n      have \"vertical_composite.map C D \\<tau> K \\<circ> vertical_composite.map B C F \\<sigma> =\n            vertical_composite.map B D (\\<tau> \\<circ> F) (K \\<circ> \\<sigma>)\"\n        by (meson assms functor_is_transformation interchange natural_transformation.axioms(3-4))\n      thus ?thesis\n        using assms by force\n    qed\n  qed\n\nend\n\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/Category3/NaturalTransformation.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8519527982093668, "lm_q2_score": 0.8479677622198947, "lm_q1q2_score": 0.7224285078145742}}
{"text": "(*<*)\ntheory \"termination\" imports examples begin\n(*>*)\n\ntext{*\nWhen a function~$f$ is defined via \\isacommand{recdef}, Isabelle tries to prove\nits termination with the help of the user-supplied measure.  Each of the examples\nabove is simple enough that Isabelle can automatically prove that the\nargument's measure decreases in each recursive call. As a result,\n$f$@{text\".simps\"} will contain the defining equations (or variants derived\nfrom them) as theorems. For example, look (via \\isacommand{thm}) at\n@{thm[source]sep.simps} and @{thm[source]sep1.simps} to see that they define\nthe same function. What is more, those equations are automatically declared as\nsimplification rules.\n\nIsabelle may fail to prove the termination condition for some\nrecursive call.  Let us try to define Quicksort:*}\n\nconsts qs :: \"nat list \\<Rightarrow> nat list\"\nrecdef(*<*)(permissive)(*>*) qs \"measure length\"\n \"qs [] = []\"\n \"qs(x#xs) = qs(filter (\\<lambda>y. y\\<le>x) xs) @ [x] @ qs(filter (\\<lambda>y. x<y) xs)\"\n\ntext{*\\noindent where @{term filter} is predefined and @{term\"filter P xs\"}\nis the list of elements of @{term xs} satisfying @{term P}.\nThis definition of @{term qs} fails, and Isabelle prints an error message\nshowing you what it was unable to prove:\n@{text[display]\"length (filter ... xs) < Suc (length xs)\"}\nWe can either prove this as a separate lemma, or try to figure out which\nexisting lemmas may help. We opt for the second alternative. The theory of\nlists contains the simplification rule @{thm length_filter_le[no_vars]},\nwhich is what we need, provided we turn \\mbox{@{text\"< Suc\"}}\ninto\n@{text\"\\<le>\"} so that the rule applies. Lemma\n@{thm[source]less_Suc_eq_le} does just that: @{thm less_Suc_eq_le[no_vars]}.\n\nNow we retry the above definition but supply the lemma(s) just found (or\nproved). Because \\isacommand{recdef}'s termination prover involves\nsimplification, we include in our second attempt a hint: the\n\\attrdx{recdef_simp} attribute says to use @{thm[source]less_Suc_eq_le} as a\nsimplification rule.\\cmmdx{hints}  *}\n\n(*<*)global consts qs :: \"nat list \\<Rightarrow> nat list\" (*>*)\nrecdef qs \"measure length\"\n \"qs [] = []\"\n \"qs(x#xs) = qs(filter (\\<lambda>y. y\\<le>x) xs) @ [x] @ qs(filter (\\<lambda>y. x<y) xs)\"\n(hints recdef_simp: less_Suc_eq_le)\n(*<*)local(*>*)\ntext{*\\noindent\nThis time everything works fine. Now @{thm[source]qs.simps} contains precisely\nthe stated recursion equations for @{text qs} and they have become\nsimplification rules.\nThus we can automatically prove results such as this one:\n*}\n\ntheorem \"qs[2,3,0] = qs[3,0,2]\"\napply(simp)\ndone\n\ntext{*\\noindent\nMore exciting theorems require induction, which is discussed below.\n\nIf the termination proof requires a lemma that is of general use, you can\nturn it permanently into a simplification rule, in which case the above\n\\isacommand{hint} is not necessary. But in the case of\n@{thm[source]less_Suc_eq_le} this would be of dubious value.\n*}\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/Recdef/termination.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8459424450764199, "lm_q2_score": 0.8539127548105611, "lm_q1q2_score": 0.7223610436863874}}
{"text": "section \\<open>Kruskal interface\\<close>\n\ntheory Kruskal\nimports Kruskal_Misc MinWeightBasis  \nbegin\n\ntext \\<open>In order to instantiate Kruskal's algorithm for different graph formalizations we provide\n  an interface consisting of the relevant concepts needed for the algorithm, but hiding the concrete\n  structure of the graph formalization.\n  We thus enable using both undirected graphs and symmetric directed graphs.\n\n  Based on the interface, we show that the set of edges together with the predicate of being \n  cycle free (i.e. a forest) forms the cycle matroid.\n  Together with a weight function on the edges we obtain a \\<open>weighted_matroid\\<close> and thus\n  an instance of the minimum weight basis algorithm, which is an abstract version of Kruskal.\\<close>\n \n  \nlocale Kruskal_interface = \n  fixes E :: \"'edge set\"\n    and V :: \"'a set\"\n    and vertices :: \"'edge \\<Rightarrow> 'a set\"\n    and joins :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'edge \\<Rightarrow> bool\"\n    and forest :: \"'edge set \\<Rightarrow> bool\"\n    and connected :: \"'edge set \\<Rightarrow> ('a*'a) set\"\n    and weight :: \"'edge \\<Rightarrow> 'b::{linorder, ordered_comm_monoid_add}\"\n assumes \n      finiteE[simp]: \"finite E\"  \n   and forest_subE: \"forest E' \\<Longrightarrow> E' \\<subseteq> E\" \n   and forest_empty: \"forest {}\"\n   and forest_mono: \"forest X \\<Longrightarrow> Y \\<subseteq> X \\<Longrightarrow> forest Y\"  \n   and connected_same: \"(u,v) \\<in> connected {} \\<longleftrightarrow> u=v \\<and> v\\<in>V\" \n   and findaugmenting_aux: \"E1 \\<subseteq> E \\<Longrightarrow> E2 \\<subseteq> E \\<Longrightarrow> (u,v) \\<in> connected E1 \\<Longrightarrow> (u,v)\\<notin> connected E2\n           \\<Longrightarrow> \\<exists>a b e. (a,b) \\<notin> connected E2 \\<and> e \\<notin> E2 \\<and> e \\<in> E1 \\<and> joins a b e\" \n   and augment_forest: \"forest F \\<Longrightarrow> e \\<in> E-F \\<Longrightarrow> joins u v e\n           \\<Longrightarrow> forest (insert e F) \\<longleftrightarrow> (u,v) \\<notin> connected F\"  \n   and equiv: \"F \\<subseteq> E \\<Longrightarrow> equiv V (connected F)\"\n   and connected_in: \"F \\<subseteq> E \\<Longrightarrow> connected F \\<subseteq> V \\<times> V\"      \n   and insert_reachable: \"x \\<in> V \\<Longrightarrow> y \\<in> V \\<Longrightarrow> F \\<subseteq> E \\<Longrightarrow> e\\<in>E \\<Longrightarrow> joins x y e\n           \\<Longrightarrow> connected (insert e F) = per_union (connected F) x y\"   \n   and exhaust: \"\\<And>x. x\\<in>E \\<Longrightarrow> \\<exists>a b. joins a b x\"\n   and vertices_constr: \"\\<And>a b e. joins a b e \\<Longrightarrow> {a,b} \\<subseteq> vertices e\"\n   and joins_sym: \"\\<And>a b e. joins a b e = joins b a e\"\n   and selfloop_no_forest: \"\\<And>e. e\\<in>E \\<Longrightarrow> joins a a e \\<Longrightarrow> ~forest (insert e F)\"\n   and finite_vertices: \"\\<And>e. e\\<in>E \\<Longrightarrow> finite (vertices e)\"\n  \n  and edgesinvertices: \"\\<Union>( vertices ` E) \\<subseteq> V\"\n  and finiteV[simp]: \"finite V\"\n  and joins_connected: \"joins a b e \\<Longrightarrow> T\\<subseteq>E \\<Longrightarrow> e\\<in>T \\<Longrightarrow> (a,b) \\<in> connected T\"\n\nbegin\n\nsubsection \\<open>Derived facts\\<close> \n\nlemma joins_in_V: \"joins a b e \\<Longrightarrow> e\\<in>E \\<Longrightarrow> a\\<in>V \\<and> b\\<in>V\"\n  apply(frule vertices_constr) using edgesinvertices by blast\n\n  lemma finiteE_finiteV: \"finite E \\<Longrightarrow> finite V\"\n    using finite_vertices by auto\n \nlemma E_inV: \"\\<And>e. e\\<in>E \\<Longrightarrow> vertices e \\<subseteq> V\"\n  using edgesinvertices by auto  \n\ndefinition \"CC E' x = (connected E')``{x}\"      \n\nlemma sameCC_reachable: \"E' \\<subseteq> E \\<Longrightarrow> u\\<in>V \\<Longrightarrow> v\\<in>V \\<Longrightarrow> CC E' u = CC E' v \\<longleftrightarrow> (u,v) \\<in> connected E'\"\n  unfolding CC_def using  equiv_class_eq_iff[OF equiv ] by auto\n\ndefinition \"CCs E' = quotient V (connected E')\"  \n\nlemma \"quotient V Id = {{v}|v. v\\<in>V}\" unfolding quotient_def by auto  \n\nlemma CCs_empty: \"CCs {} = {{v}|v. v\\<in>V}\"   \n  unfolding CCs_def unfolding quotient_def using connected_same by auto\n\nlemma CCs_empty_card: \"card (CCs {}) = card V\"   \nproof -\n  have i: \"{{v}|v. v\\<in>V} = (\\<lambda>v. {v})`V\"  \n    by blast \n  have \"card (CCs {}) = card {{v}|v. v\\<in>V}\" \n    using CCs_empty  by auto\n  also have \"\\<dots> = card ((\\<lambda>v. {v})`V)\" by(simp only: i) \n  also have \"\\<dots> = card V\"\n    apply(rule card_image)\n    unfolding inj_on_def by auto\n  finally show ?thesis .\nqed\n\nlemma CCs_imageCC: \"CCs F = (CC F) ` V\"\n  unfolding CCs_def CC_def quotient_def  \n  by blast\n\n\nlemma union_eqclass_decreases_components: \n  assumes \"CC F x \\<noteq> CC F y\" \"e \\<notin> F\" \"x\\<in>V\" \"y\\<in>V\" \"F \\<subseteq> E\" \"e\\<in>E\" \"joins x y e\" \n  shows \"Suc (card (CCs (insert e F))) = card (CCs F)\"\nproof -  \n  from assms(1) have xny: \"x\\<noteq>y\" by blast   \n  show ?thesis unfolding CCs_def\n    apply(simp only: insert_reachable[OF   assms(3-7)])\n    apply(rule unify2EquivClasses_alt)          \n         apply(fact assms(1)[unfolded CC_def])                           \n        apply fact+\n      apply (rule connected_in)  \n      apply fact    \n     apply(rule equiv) \n     apply fact  \n    by (fact finiteV)      \nqed\n\nlemma forest_CCs: assumes \"forest E'\" shows \"card (CCs E') + card E' = card V\"\nproof -\n  from assms have \"finite E'\" using forest_subE\n    using finiteE finite_subset by blast\n  from this assms show ?thesis\n  proof(induct E') \n    case (insert x F)\n    then have xE: \"x\\<in>E\" using forest_subE by auto\n    from this obtain a b where xab: \"joins a b x\"  using exhaust by blast\n    { assume \"a=b\"\n      with xab xE selfloop_no_forest insert(4) have \"False\" by auto\n    }\n    then have xab': \"a\\<noteq>b\" by auto\n    from insert(4) forest_mono have fF: \"forest F\" by auto\n    with insert(3) have eq: \"card (CCs F) + card F = card V\" by auto \n\n    from insert(4) forest_subE have k: \"F \\<subseteq> E\" by auto     \n    from xab xab' have abV: \"a\\<in>V\" \"b\\<in>V\" using vertices_constr E_inV xE by fastforce+\n\n    have \"(a,b) \\<notin> connected F\" \n      apply(subst augment_forest[symmetric])\n         apply (rule fF)\n      using xE xab xab insert by auto\n    with k abV sameCC_reachable have \"CC F a \\<noteq> CC F b\" by auto \n    have \"Suc (card (CCs (insert x F))) = card (CCs F)\" \n      apply(rule union_eqclass_decreases_components)  \n      by fact+ \n    then show ?case using xab insert(1,2) eq   by auto \n  qed (simp add: CCs_empty_card)\nqed\n\nlemma pigeonhole_CCs: \n  assumes finiteV: \"finite V\" and cardlt: \"card (CCs E1) < card (CCs E2)\"\n  shows \"(\\<exists>u v. u\\<in>V \\<and> v\\<in>V \\<and> CC E1 u = CC E1 v \\<and> CC E2 u \\<noteq> CC E2 v)\"  \nproof (rule ccontr, clarsimp)\n  assume \"\\<forall>u. u \\<in> V \\<longrightarrow> (\\<forall>v. CC E1 u = CC E1 v \\<longrightarrow> v \\<in> V \\<longrightarrow> CC E2 u = CC E2 v)\"\n  then have \"\\<And>u v. u\\<in>V \\<Longrightarrow> v\\<in>V \\<Longrightarrow> CC E1 u = CC E1 v \\<Longrightarrow> CC E2 u = CC E2 v\" by blast\n\n  with coarser[OF finiteV] have \"card ((CC E1) ` V) \\<ge> card ((CC E2) ` V)\" by blast\n\n  with CCs_imageCC cardlt show \"False\" by auto\nqed\n\nsubsection \\<open>The edge set and forest form the cycle matroid\\<close> \n \n\ntheorem assumes f1: \"forest E1\"\n  and f2: \"forest E2\"  \n  and c: \"card E1 > card E2\"\nshows augment: \"\\<exists>e\\<in>E1-E2. forest (insert e E2)\"\nproof -\n  \\<comment> \\<open>as E1 and E2 are both forests, and E1 has more edges than E2, E2 has more connected\n        components than E1\\<close> \n  from forest_CCs[OF f1] forest_CCs[OF f2] c have \"card (CCs E1) < card (CCs E2)\" by linarith\n\n  \\<comment> \\<open>by an pigeonhole argument, we can obtain two vertices u and v\n     that are in the same components of E1, but in different components of E2\\<close>\n  then obtain u v where sameCCinE1: \"CC E1 u = CC E1 v\" and\n    diffCCinE2: \"CC E2 u \\<noteq> CC E2 v\" and k: \"u \\<in> V\" \"v \\<in> V\"\n    using pigeonhole_CCs[OF finiteV] by blast   \n\n  from diffCCinE2 have unv: \"u \\<noteq> v\" by auto\n\n  \\<comment> \\<open>this means that there is a path from u to v in E1 ...\\<close>   \n  from f1 forest_subE have e1: \"E1 \\<subseteq> E\" by auto    \n  with   sameCC_reachable k sameCCinE1 have pathinE1: \"(u, v) \\<in> connected E1\" \n    by auto \n      \\<comment> \\<open>... but none in E2\\<close>  \n  from f2 forest_subE have e2: \"E2 \\<subseteq> E\" by auto    \n  with   sameCC_reachable k diffCCinE2\n  have nopathinE2: \"(u, v) \\<notin> connected E2\" \n    by auto\n\n  \\<comment> \\<open>hence, we can find vertices a and b that are not connected in E2,\n          but are connected by an edge in E1\\<close>    \n  obtain a b e where pe: \"(a,b) \\<notin> connected E2\" and abE2: \"e \\<notin> E2\"\n    and abE1: \"e \\<in> E1\" and \"joins a b e\"\n    using findaugmenting_aux[OF e1 e2 pathinE1 nopathinE2]    by auto\n\n  with forest_subE[OF f1] have \"e \\<in> E\" by auto\n  from abE1 abE2 have abdif: \"e \\<in> E1 - E2\" by auto\n  with e1 have \"e \\<in> E - E2\" by auto\n\n  \\<comment> \\<open>we can savely add this edge between a and b to E2 and obtain a bigger forest\\<close>    \n  have \"forest (insert e E2)\" apply(subst augment_forest)\n    by fact+\n  then show \"\\<exists>e\\<in>E1-E2. forest (insert e E2)\" using abdif\n    by blast\nqed\n\nsublocale weighted_matroid E forest weight\nproof             \n  have \"forest {}\" using forest_empty by auto\n  then show \"\\<exists>X. forest X\" by blast \nqed (auto simp: forest_subE forest_mono augment)\n\nend \\<comment> \\<open>locale @{text Kruskal_interface}\\<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/Kruskal.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8539127603871312, "lm_q2_score": 0.8459424334245617, "lm_q1q2_score": 0.7223610384541743}}
{"text": "(*  Title:      HOL/Library/Multiset.thy\n    Author:     Tobias Nipkow, Markus Wenzel, Lawrence C Paulson, Norbert Voelker\n    Author:     Andrei Popescu, TU Muenchen\n*)\n\nsection {* (Finite) multisets *}\n\ntheory Multiset\nimports Main\nbegin\n\nsubsection {* The type of multisets *}\n\ndefinition \"multiset = {f :: 'a => nat. finite {x. f x > 0}}\"\n\ntypedef 'a multiset = \"multiset :: ('a => nat) set\"\n  morphisms count Abs_multiset\n  unfolding multiset_def\nproof\n  show \"(\\<lambda>x. 0::nat) \\<in> {f. finite {x. f x > 0}}\" by simp\nqed\n\nsetup_lifting type_definition_multiset\n\nabbreviation Melem :: \"'a => 'a multiset => bool\"  (\"(_/ :# _)\" [50, 51] 50) where\n  \"a :# M == 0 < count M a\"\n\nnotation (xsymbols)\n  Melem (infix \"\\<in>#\" 50)\n\nlemma multiset_eq_iff:\n  \"M = N \\<longleftrightarrow> (\\<forall>a. count M a = count N a)\"\n  by (simp only: count_inject [symmetric] fun_eq_iff)\n\nlemma multiset_eqI:\n  \"(\\<And>x. count A x = count B x) \\<Longrightarrow> A = B\"\n  using multiset_eq_iff by auto\n\ntext {*\n \\medskip Preservation of the representing set @{term multiset}.\n*}\n\nlemma const0_in_multiset:\n  \"(\\<lambda>a. 0) \\<in> multiset\"\n  by (simp add: multiset_def)\n\nlemma only1_in_multiset:\n  \"(\\<lambda>b. if b = a then n else 0) \\<in> multiset\"\n  by (simp add: multiset_def)\n\nlemma union_preserves_multiset:\n  \"M \\<in> multiset \\<Longrightarrow> N \\<in> multiset \\<Longrightarrow> (\\<lambda>a. M a + N a) \\<in> multiset\"\n  by (simp add: multiset_def)\n\nlemma diff_preserves_multiset:\n  assumes \"M \\<in> multiset\"\n  shows \"(\\<lambda>a. M a - N a) \\<in> multiset\"\nproof -\n  have \"{x. N x < M x} \\<subseteq> {x. 0 < M x}\"\n    by auto\n  with assms show ?thesis\n    by (auto simp add: multiset_def intro: finite_subset)\nqed\n\nlemma filter_preserves_multiset:\n  assumes \"M \\<in> multiset\"\n  shows \"(\\<lambda>x. if P x then M x else 0) \\<in> multiset\"\nproof -\n  have \"{x. (P x \\<longrightarrow> 0 < M x) \\<and> P x} \\<subseteq> {x. 0 < M x}\"\n    by auto\n  with assms show ?thesis\n    by (auto simp add: multiset_def intro: finite_subset)\nqed\n\nlemmas in_multiset = const0_in_multiset only1_in_multiset\n  union_preserves_multiset diff_preserves_multiset filter_preserves_multiset\n\n\nsubsection {* Representing multisets *}\n\ntext {* Multiset enumeration *}\n\ninstantiation multiset :: (type) cancel_comm_monoid_add\nbegin\n\nlift_definition zero_multiset :: \"'a multiset\" is \"\\<lambda>a. 0\"\nby (rule const0_in_multiset)\n\nabbreviation Mempty :: \"'a multiset\" (\"{#}\") where\n  \"Mempty \\<equiv> 0\"\n\nlift_definition plus_multiset :: \"'a multiset => 'a multiset => 'a multiset\" is \"\\<lambda>M N. (\\<lambda>a. M a + N a)\"\nby (rule union_preserves_multiset)\n\ninstance\nby default (transfer, simp add: fun_eq_iff)+\n\nend\n\nlift_definition single :: \"'a => 'a multiset\" is \"\\<lambda>a b. if b = a then 1 else 0\"\nby (rule only1_in_multiset)\n\nsyntax\n  \"_multiset\" :: \"args => 'a multiset\"    (\"{#(_)#}\")\ntranslations\n  \"{#x, xs#}\" == \"{#x#} + {#xs#}\"\n  \"{#x#}\" == \"CONST single x\"\n\nlemma count_empty [simp]: \"count {#} a = 0\"\n  by (simp add: zero_multiset.rep_eq)\n\nlemma count_single [simp]: \"count {#b#} a = (if b = a then 1 else 0)\"\n  by (simp add: single.rep_eq)\n\n\nsubsection {* Basic operations *}\n\nsubsubsection {* Union *}\n\nlemma count_union [simp]: \"count (M + N) a = count M a + count N a\"\n  by (simp add: plus_multiset.rep_eq)\n\n\nsubsubsection {* Difference *}\n\ninstantiation multiset :: (type) comm_monoid_diff\nbegin\n\nlift_definition minus_multiset :: \"'a multiset => 'a multiset => 'a multiset\" is \"\\<lambda> M N. \\<lambda>a. M a - N a\"\nby (rule diff_preserves_multiset)\n\ninstance\nby default (transfer, simp add: fun_eq_iff)+\n\nend\n\nlemma count_diff [simp]: \"count (M - N) a = count M a - count N a\"\n  by (simp add: minus_multiset.rep_eq)\n\nlemma diff_empty [simp]: \"M - {#} = M \\<and> {#} - M = {#}\"\n  by rule (fact Groups.diff_zero, fact Groups.zero_diff)\n\nlemma diff_cancel[simp]: \"A - A = {#}\"\n  by (fact Groups.diff_cancel)\n\nlemma diff_union_cancelR [simp]: \"M + N - N = (M::'a multiset)\"\n  by (fact add_diff_cancel_right')\n\nlemma diff_union_cancelL [simp]: \"N + M - N = (M::'a multiset)\"\n  by (fact add_diff_cancel_left')\n\nlemma diff_right_commute:\n  \"(M::'a multiset) - N - Q = M - Q - N\"\n  by (fact diff_right_commute)\n\nlemma diff_add:\n  \"(M::'a multiset) - (N + Q) = M - N - Q\"\n  by (rule sym) (fact diff_diff_add)\n\nlemma insert_DiffM:\n  \"x \\<in># M \\<Longrightarrow> {#x#} + (M - {#x#}) = M\"\n  by (clarsimp simp: multiset_eq_iff)\n\nlemma insert_DiffM2 [simp]:\n  \"x \\<in># M \\<Longrightarrow> M - {#x#} + {#x#} = M\"\n  by (clarsimp simp: multiset_eq_iff)\n\nlemma diff_union_swap:\n  \"a \\<noteq> b \\<Longrightarrow> M - {#a#} + {#b#} = M + {#b#} - {#a#}\"\n  by (auto simp add: multiset_eq_iff)\n\nlemma diff_union_single_conv:\n  \"a \\<in># J \\<Longrightarrow> I + J - {#a#} = I + (J - {#a#})\"\n  by (simp add: multiset_eq_iff)\n\n\nsubsubsection {* Equality of multisets *}\n\nlemma single_not_empty [simp]: \"{#a#} \\<noteq> {#} \\<and> {#} \\<noteq> {#a#}\"\n  by (simp add: multiset_eq_iff)\n\nlemma single_eq_single [simp]: \"{#a#} = {#b#} \\<longleftrightarrow> a = b\"\n  by (auto simp add: multiset_eq_iff)\n\nlemma union_eq_empty [iff]: \"M + N = {#} \\<longleftrightarrow> M = {#} \\<and> N = {#}\"\n  by (auto simp add: multiset_eq_iff)\n\nlemma empty_eq_union [iff]: \"{#} = M + N \\<longleftrightarrow> M = {#} \\<and> N = {#}\"\n  by (auto simp add: multiset_eq_iff)\n\nlemma multi_self_add_other_not_self [simp]: \"M = M + {#x#} \\<longleftrightarrow> False\"\n  by (auto simp add: multiset_eq_iff)\n\nlemma diff_single_trivial:\n  \"\\<not> x \\<in># M \\<Longrightarrow> M - {#x#} = M\"\n  by (auto simp add: multiset_eq_iff)\n\nlemma diff_single_eq_union:\n  \"x \\<in># M \\<Longrightarrow> M - {#x#} = N \\<longleftrightarrow> M = N + {#x#}\"\n  by auto\n\nlemma union_single_eq_diff:\n  \"M + {#x#} = N \\<Longrightarrow> M = N - {#x#}\"\n  by (auto dest: sym)\n\nlemma union_single_eq_member:\n  \"M + {#x#} = N \\<Longrightarrow> x \\<in># N\"\n  by auto\n\nlemma union_is_single:\n  \"M + N = {#a#} \\<longleftrightarrow> M = {#a#} \\<and> N={#} \\<or> M = {#} \\<and> N = {#a#}\" (is \"?lhs = ?rhs\")\nproof\n  assume ?rhs then show ?lhs by auto\nnext\n  assume ?lhs then show ?rhs\n    by (simp add: multiset_eq_iff split:if_splits) (metis add_is_1)\nqed\n\nlemma single_is_union:\n  \"{#a#} = M + N \\<longleftrightarrow> {#a#} = M \\<and> N = {#} \\<or> M = {#} \\<and> {#a#} = N\"\n  by (auto simp add: eq_commute [of \"{#a#}\" \"M + N\"] union_is_single)\n\nlemma add_eq_conv_diff:\n  \"M + {#a#} = N + {#b#} \\<longleftrightarrow> M = N \\<and> a = b \\<or> M = N - {#a#} + {#b#} \\<and> N = M - {#b#} + {#a#}\"  (is \"?lhs = ?rhs\")\n(* shorter: by (simp add: multiset_eq_iff) fastforce *)\nproof\n  assume ?rhs then show ?lhs\n  by (auto simp add: add.assoc add.commute [of \"{#b#}\"])\n    (drule sym, simp add: add.assoc [symmetric])\nnext\n  assume ?lhs\n  show ?rhs\n  proof (cases \"a = b\")\n    case True with `?lhs` show ?thesis by simp\n  next\n    case False\n    from `?lhs` have \"a \\<in># N + {#b#}\" by (rule union_single_eq_member)\n    with False have \"a \\<in># N\" by auto\n    moreover from `?lhs` have \"M = N + {#b#} - {#a#}\" by (rule union_single_eq_diff)\n    moreover note False\n    ultimately show ?thesis by (auto simp add: diff_right_commute [of _ \"{#a#}\"] diff_union_swap)\n  qed\nqed\n\nlemma insert_noteq_member:\n  assumes BC: \"B + {#b#} = C + {#c#}\"\n   and bnotc: \"b \\<noteq> c\"\n  shows \"c \\<in># B\"\nproof -\n  have \"c \\<in># C + {#c#}\" by simp\n  have nc: \"\\<not> c \\<in># {#b#}\" using bnotc by simp\n  then have \"c \\<in># B + {#b#}\" using BC by simp\n  then show \"c \\<in># B\" using nc by simp\nqed\n\nlemma add_eq_conv_ex:\n  \"(M + {#a#} = N + {#b#}) =\n    (M = N \\<and> a = b \\<or> (\\<exists>K. M = K + {#b#} \\<and> N = K + {#a#}))\"\n  by (auto simp add: add_eq_conv_diff)\n\nlemma multi_member_split:\n  \"x \\<in># M \\<Longrightarrow> \\<exists>A. M = A + {#x#}\"\n  by (rule_tac x = \"M - {#x#}\" in exI, simp)\n\nlemma multiset_add_sub_el_shuffle:\n  assumes \"c \\<in># B\" and \"b \\<noteq> c\"\n  shows \"B - {#c#} + {#b#} = B + {#b#} - {#c#}\"\nproof -\n  from `c \\<in># B` obtain A where B: \"B = A + {#c#}\"\n    by (blast dest: multi_member_split)\n  have \"A + {#b#} = A + {#b#} + {#c#} - {#c#}\" by simp\n  then have \"A + {#b#} = A + {#c#} + {#b#} - {#c#}\"\n    by (simp add: ac_simps)\n  then show ?thesis using B by simp\nqed\n\n\nsubsubsection {* Pointwise ordering induced by count *}\n\ninstantiation multiset :: (type) ordered_ab_semigroup_add_imp_le\nbegin\n\nlift_definition less_eq_multiset :: \"'a multiset \\<Rightarrow> 'a multiset \\<Rightarrow> bool\" is \"\\<lambda> A B. (\\<forall>a. A a \\<le> B a)\" .\n\nlemmas mset_le_def = less_eq_multiset_def\n\ndefinition less_multiset :: \"'a multiset \\<Rightarrow> 'a multiset \\<Rightarrow> bool\" where\n  mset_less_def: \"(A::'a multiset) < B \\<longleftrightarrow> A \\<le> B \\<and> A \\<noteq> B\"\n\ninstance\n  by default (auto simp add: mset_le_def mset_less_def multiset_eq_iff intro: order_trans antisym)\n\nend\n\nlemma mset_less_eqI:\n  \"(\\<And>x. count A x \\<le> count B x) \\<Longrightarrow> A \\<le> B\"\n  by (simp add: mset_le_def)\n\nlemma mset_le_exists_conv:\n  \"(A::'a multiset) \\<le> B \\<longleftrightarrow> (\\<exists>C. B = A + C)\"\napply (unfold mset_le_def, rule iffI, rule_tac x = \"B - A\" in exI)\napply (auto intro: multiset_eq_iff [THEN iffD2])\ndone\n\ninstance multiset :: (type) ordered_cancel_comm_monoid_diff\n  by default (simp, fact mset_le_exists_conv)\n\nlemma mset_le_mono_add_right_cancel [simp]:\n  \"(A::'a multiset) + C \\<le> B + C \\<longleftrightarrow> A \\<le> B\"\n  by (fact add_le_cancel_right)\n\nlemma mset_le_mono_add_left_cancel [simp]:\n  \"C + (A::'a multiset) \\<le> C + B \\<longleftrightarrow> A \\<le> B\"\n  by (fact add_le_cancel_left)\n\nlemma mset_le_mono_add:\n  \"(A::'a multiset) \\<le> B \\<Longrightarrow> C \\<le> D \\<Longrightarrow> A + C \\<le> B + D\"\n  by (fact add_mono)\n\nlemma mset_le_add_left [simp]:\n  \"(A::'a multiset) \\<le> A + B\"\n  unfolding mset_le_def by auto\n\nlemma mset_le_add_right [simp]:\n  \"B \\<le> (A::'a multiset) + B\"\n  unfolding mset_le_def by auto\n\nlemma mset_le_single:\n  \"a :# B \\<Longrightarrow> {#a#} \\<le> B\"\n  by (simp add: mset_le_def)\n\nlemma multiset_diff_union_assoc:\n  \"C \\<le> B \\<Longrightarrow> (A::'a multiset) + B - C = A + (B - C)\"\n  by (simp add: multiset_eq_iff mset_le_def)\n\nlemma mset_le_multiset_union_diff_commute:\n  \"B \\<le> A \\<Longrightarrow> (A::'a multiset) - B + C = A + C - B\"\nby (simp add: multiset_eq_iff mset_le_def)\n\nlemma diff_le_self[simp]: \"(M::'a multiset) - N \\<le> M\"\nby(simp add: mset_le_def)\n\nlemma mset_lessD: \"A < B \\<Longrightarrow> x \\<in># A \\<Longrightarrow> x \\<in># B\"\napply (clarsimp simp: mset_le_def mset_less_def)\napply (erule_tac x=x in allE)\napply auto\ndone\n\nlemma mset_leD: \"A \\<le> B \\<Longrightarrow> x \\<in># A \\<Longrightarrow> x \\<in># B\"\napply (clarsimp simp: mset_le_def mset_less_def)\napply (erule_tac x = x in allE)\napply auto\ndone\n\nlemma mset_less_insertD: \"(A + {#x#} < B) \\<Longrightarrow> (x \\<in># B \\<and> A < B)\"\napply (rule conjI)\n apply (simp add: mset_lessD)\napply (clarsimp simp: mset_le_def mset_less_def)\napply safe\n apply (erule_tac x = a in allE)\n apply (auto split: split_if_asm)\ndone\n\nlemma mset_le_insertD: \"(A + {#x#} \\<le> B) \\<Longrightarrow> (x \\<in># B \\<and> A \\<le> B)\"\napply (rule conjI)\n apply (simp add: mset_leD)\napply (force simp: mset_le_def mset_less_def split: split_if_asm)\ndone\n\nlemma mset_less_of_empty[simp]: \"A < {#} \\<longleftrightarrow> False\"\n  by (auto simp add: mset_less_def mset_le_def multiset_eq_iff)\n\nlemma empty_le[simp]: \"{#} \\<le> A\"\n  unfolding mset_le_exists_conv by auto\n\nlemma le_empty[simp]: \"(M \\<le> {#}) = (M = {#})\"\n  unfolding mset_le_exists_conv by auto\n\nlemma multi_psub_of_add_self[simp]: \"A < A + {#x#}\"\n  by (auto simp: mset_le_def mset_less_def)\n\nlemma multi_psub_self[simp]: \"(A::'a multiset) < A = False\"\n  by simp\n\nlemma mset_less_add_bothsides:\n  \"T + {#x#} < S + {#x#} \\<Longrightarrow> T < S\"\n  by (fact add_less_imp_less_right)\n\nlemma mset_less_empty_nonempty:\n  \"{#} < S \\<longleftrightarrow> S \\<noteq> {#}\"\n  by (auto simp: mset_le_def mset_less_def)\n\nlemma mset_less_diff_self:\n  \"c \\<in># B \\<Longrightarrow> B - {#c#} < B\"\n  by (auto simp: mset_le_def mset_less_def multiset_eq_iff)\n\n\nsubsubsection {* Intersection *}\n\ninstantiation multiset :: (type) semilattice_inf\nbegin\n\ndefinition inf_multiset :: \"'a multiset \\<Rightarrow> 'a multiset \\<Rightarrow> 'a multiset\" where\n  multiset_inter_def: \"inf_multiset A B = A - (A - B)\"\n\ninstance\nproof -\n  have aux: \"\\<And>m n q :: nat. m \\<le> n \\<Longrightarrow> m \\<le> q \\<Longrightarrow> m \\<le> n - (n - q)\" by arith\n  show \"OFCLASS('a multiset, semilattice_inf_class)\"\n    by default (auto simp add: multiset_inter_def mset_le_def aux)\nqed\n\nend\n\nabbreviation multiset_inter :: \"'a multiset \\<Rightarrow> 'a multiset \\<Rightarrow> 'a multiset\" (infixl \"#\\<inter>\" 70) where\n  \"multiset_inter \\<equiv> inf\"\n\nlemma multiset_inter_count [simp]:\n  \"count (A #\\<inter> B) x = min (count A x) (count B x)\"\n  by (simp add: multiset_inter_def)\n\nlemma multiset_inter_single: \"a \\<noteq> b \\<Longrightarrow> {#a#} #\\<inter> {#b#} = {#}\"\n  by (rule multiset_eqI) auto\n\nlemma multiset_union_diff_commute:\n  assumes \"B #\\<inter> C = {#}\"\n  shows \"A + B - C = A - C + B\"\nproof (rule multiset_eqI)\n  fix x\n  from assms have \"min (count B x) (count C x) = 0\"\n    by (auto simp add: multiset_eq_iff)\n  then have \"count B x = 0 \\<or> count C x = 0\"\n    by auto\n  then show \"count (A + B - C) x = count (A - C + B) x\"\n    by auto\nqed\n\nlemma empty_inter [simp]:\n  \"{#} #\\<inter> M = {#}\"\n  by (simp add: multiset_eq_iff)\n\nlemma inter_empty [simp]:\n  \"M #\\<inter> {#} = {#}\"\n  by (simp add: multiset_eq_iff)\n\nlemma inter_add_left1:\n  \"\\<not> x \\<in># N \\<Longrightarrow> (M + {#x#}) #\\<inter> N = M #\\<inter> N\"\n  by (simp add: multiset_eq_iff)\n\nlemma inter_add_left2:\n  \"x \\<in># N \\<Longrightarrow> (M + {#x#}) #\\<inter> N = (M #\\<inter> (N - {#x#})) + {#x#}\"\n  by (simp add: multiset_eq_iff)\n\nlemma inter_add_right1:\n  \"\\<not> x \\<in># N \\<Longrightarrow> N #\\<inter> (M + {#x#}) = N #\\<inter> M\"\n  by (simp add: multiset_eq_iff)\n\nlemma inter_add_right2:\n  \"x \\<in># N \\<Longrightarrow> N #\\<inter> (M + {#x#}) = ((N - {#x#}) #\\<inter> M) + {#x#}\"\n  by (simp add: multiset_eq_iff)\n\n\nsubsubsection {* Bounded union *}\n\ninstantiation multiset :: (type) semilattice_sup\nbegin\n\ndefinition sup_multiset :: \"'a multiset \\<Rightarrow> 'a multiset \\<Rightarrow> 'a multiset\" where\n  \"sup_multiset A B = A + (B - A)\"\n\ninstance\nproof -\n  have aux: \"\\<And>m n q :: nat. m \\<le> n \\<Longrightarrow> q \\<le> n \\<Longrightarrow> m + (q - m) \\<le> n\" by arith\n  show \"OFCLASS('a multiset, semilattice_sup_class)\"\n    by default (auto simp add: sup_multiset_def mset_le_def aux)\nqed\n\nend\n\nabbreviation sup_multiset :: \"'a multiset \\<Rightarrow> 'a multiset \\<Rightarrow> 'a multiset\" (infixl \"#\\<union>\" 70) where\n  \"sup_multiset \\<equiv> sup\"\n\nlemma sup_multiset_count [simp]:\n  \"count (A #\\<union> B) x = max (count A x) (count B x)\"\n  by (simp add: sup_multiset_def)\n\nlemma empty_sup [simp]:\n  \"{#} #\\<union> M = M\"\n  by (simp add: multiset_eq_iff)\n\nlemma sup_empty [simp]:\n  \"M #\\<union> {#} = M\"\n  by (simp add: multiset_eq_iff)\n\nlemma sup_add_left1:\n  \"\\<not> x \\<in># N \\<Longrightarrow> (M + {#x#}) #\\<union> N = (M #\\<union> N) + {#x#}\"\n  by (simp add: multiset_eq_iff)\n\nlemma sup_add_left2:\n  \"x \\<in># N \\<Longrightarrow> (M + {#x#}) #\\<union> N = (M #\\<union> (N - {#x#})) + {#x#}\"\n  by (simp add: multiset_eq_iff)\n\nlemma sup_add_right1:\n  \"\\<not> x \\<in># N \\<Longrightarrow> N #\\<union> (M + {#x#}) = (N #\\<union> M) + {#x#}\"\n  by (simp add: multiset_eq_iff)\n\nlemma sup_add_right2:\n  \"x \\<in># N \\<Longrightarrow> N #\\<union> (M + {#x#}) = ((N - {#x#}) #\\<union> M) + {#x#}\"\n  by (simp add: multiset_eq_iff)\n\n\nsubsubsection {* Filter (with comprehension syntax) *}\n\ntext {* Multiset comprehension *}\n\nlift_definition filter :: \"('a \\<Rightarrow> bool) \\<Rightarrow> 'a multiset \\<Rightarrow> 'a multiset\" is \"\\<lambda>P M. \\<lambda>x. if P x then M x else 0\"\nby (rule filter_preserves_multiset)\n\nhide_const (open) filter\n\nlemma count_filter [simp]:\n  \"count (Multiset.filter P M) a = (if P a then count M a else 0)\"\n  by (simp add: filter.rep_eq)\n\nlemma filter_empty [simp]:\n  \"Multiset.filter P {#} = {#}\"\n  by (rule multiset_eqI) simp\n\nlemma filter_single [simp]:\n  \"Multiset.filter P {#x#} = (if P x then {#x#} else {#})\"\n  by (rule multiset_eqI) simp\n\nlemma filter_union [simp]:\n  \"Multiset.filter P (M + N) = Multiset.filter P M + Multiset.filter P N\"\n  by (rule multiset_eqI) simp\n\nlemma filter_diff [simp]:\n  \"Multiset.filter P (M - N) = Multiset.filter P M - Multiset.filter P N\"\n  by (rule multiset_eqI) simp\n\nlemma filter_inter [simp]:\n  \"Multiset.filter P (M #\\<inter> N) = Multiset.filter P M #\\<inter> Multiset.filter P N\"\n  by (rule multiset_eqI) simp\n\nlemma multiset_filter_subset[simp]: \"Multiset.filter f M \\<le> M\"\n  unfolding less_eq_multiset.rep_eq by auto\n\nlemma multiset_filter_mono: assumes \"A \\<le> B\"\n  shows \"Multiset.filter f A \\<le> Multiset.filter f B\"\nproof -\n  from assms[unfolded mset_le_exists_conv]\n  obtain C where B: \"B = A + C\" by auto\n  show ?thesis unfolding B by auto\nqed\n\nsyntax\n  \"_MCollect\" :: \"pttrn \\<Rightarrow> 'a multiset \\<Rightarrow> bool \\<Rightarrow> 'a multiset\"    (\"(1{# _ :# _./ _#})\")\nsyntax (xsymbol)\n  \"_MCollect\" :: \"pttrn \\<Rightarrow> 'a multiset \\<Rightarrow> bool \\<Rightarrow> 'a multiset\"    (\"(1{# _ \\<in># _./ _#})\")\ntranslations\n  \"{#x \\<in># M. P#}\" == \"CONST Multiset.filter (\\<lambda>x. P) M\"\n\n\nsubsubsection {* Set of elements *}\n\ndefinition set_of :: \"'a multiset => 'a set\" where\n  \"set_of M = {x. x :# M}\"\n\nlemma set_of_empty [simp]: \"set_of {#} = {}\"\nby (simp add: set_of_def)\n\nlemma set_of_single [simp]: \"set_of {#b#} = {b}\"\nby (simp add: set_of_def)\n\nlemma set_of_union [simp]: \"set_of (M + N) = set_of M \\<union> set_of N\"\nby (auto simp add: set_of_def)\n\nlemma set_of_eq_empty_iff [simp]: \"(set_of M = {}) = (M = {#})\"\nby (auto simp add: set_of_def multiset_eq_iff)\n\nlemma mem_set_of_iff [simp]: \"(x \\<in> set_of M) = (x :# M)\"\nby (auto simp add: set_of_def)\n\nlemma set_of_filter [simp]: \"set_of {# x:#M. P x #} = set_of M \\<inter> {x. P x}\"\nby (auto simp add: set_of_def)\n\nlemma finite_set_of [iff]: \"finite (set_of M)\"\n  using count [of M] by (simp add: multiset_def set_of_def)\n\nlemma finite_Collect_mem [iff]: \"finite {x. x :# M}\"\n  unfolding set_of_def[symmetric] by simp\n\nlemma set_of_mono: \"A \\<le> B \\<Longrightarrow> set_of A \\<subseteq> set_of B\"\n  by (metis mset_leD subsetI mem_set_of_iff)\n\nsubsubsection {* Size *}\n\ndefinition wcount where \"wcount f M = (\\<lambda>x. count M x * Suc (f x))\"\n\nlemma wcount_union: \"wcount f (M + N) a = wcount f M a + wcount f N a\"\n  by (auto simp: wcount_def add_mult_distrib)\n\ndefinition size_multiset :: \"('a \\<Rightarrow> nat) \\<Rightarrow> 'a multiset \\<Rightarrow> nat\" where\n  \"size_multiset f M = setsum (wcount f M) (set_of M)\"\n\nlemmas size_multiset_eq = size_multiset_def[unfolded wcount_def]\n\ninstantiation multiset :: (type) size begin\ndefinition size_multiset where\n  size_multiset_overloaded_def: \"size_multiset = Multiset.size_multiset (\\<lambda>_. 0)\"\ninstance ..\nend\n\nlemmas size_multiset_overloaded_eq =\n  size_multiset_overloaded_def[THEN fun_cong, unfolded size_multiset_eq, simplified]\n\nlemma size_multiset_empty [simp]: \"size_multiset f {#} = 0\"\nby (simp add: size_multiset_def)\n\nlemma size_empty [simp]: \"size {#} = 0\"\nby (simp add: size_multiset_overloaded_def)\n\nlemma size_multiset_single [simp]: \"size_multiset f {#b#} = Suc (f b)\"\nby (simp add: size_multiset_eq)\n\nlemma size_single [simp]: \"size {#b#} = 1\"\nby (simp add: size_multiset_overloaded_def)\n\nlemma setsum_wcount_Int:\n  \"finite A \\<Longrightarrow> setsum (wcount f N) (A \\<inter> set_of N) = setsum (wcount f N) A\"\napply (induct rule: finite_induct)\n apply simp\napply (simp add: Int_insert_left set_of_def wcount_def)\ndone\n\nlemma size_multiset_union [simp]:\n  \"size_multiset f (M + N::'a multiset) = size_multiset f M + size_multiset f N\"\napply (simp add: size_multiset_def setsum_Un_nat setsum.distrib setsum_wcount_Int wcount_union)\napply (subst Int_commute)\napply (simp add: setsum_wcount_Int)\ndone\n\nlemma size_union [simp]: \"size (M + N::'a multiset) = size M + size N\"\nby (auto simp add: size_multiset_overloaded_def)\n\nlemma size_multiset_eq_0_iff_empty [iff]: \"(size_multiset f M = 0) = (M = {#})\"\nby (auto simp add: size_multiset_eq multiset_eq_iff)\n\nlemma size_eq_0_iff_empty [iff]: \"(size M = 0) = (M = {#})\"\nby (auto simp add: size_multiset_overloaded_def)\n\nlemma nonempty_has_size: \"(S \\<noteq> {#}) = (0 < size S)\"\nby (metis gr0I gr_implies_not0 size_empty size_eq_0_iff_empty)\n\nlemma size_eq_Suc_imp_elem: \"size M = Suc n ==> \\<exists>a. a :# M\"\napply (unfold size_multiset_overloaded_eq)\napply (drule setsum_SucD)\napply auto\ndone\n\nlemma size_eq_Suc_imp_eq_union:\n  assumes \"size M = Suc n\"\n  shows \"\\<exists>a N. M = N + {#a#}\"\nproof -\n  from assms obtain a where \"a \\<in># M\"\n    by (erule size_eq_Suc_imp_elem [THEN exE])\n  then have \"M = M - {#a#} + {#a#}\" by simp\n  then show ?thesis by blast\nqed\n\n\nsubsection {* Induction and case splits *}\n\ntheorem multiset_induct [case_names empty add, induct type: multiset]:\n  assumes empty: \"P {#}\"\n  assumes add: \"\\<And>M x. P M \\<Longrightarrow> P (M + {#x#})\"\n  shows \"P M\"\nproof (induct n \\<equiv> \"size M\" arbitrary: M)\n  case 0 thus \"P M\" by (simp add: empty)\nnext\n  case (Suc k)\n  obtain N x where \"M = N + {#x#}\"\n    using `Suc k = size M` [symmetric]\n    using size_eq_Suc_imp_eq_union by fast\n  with Suc add show \"P M\" by simp\nqed\n\nlemma multi_nonempty_split: \"M \\<noteq> {#} \\<Longrightarrow> \\<exists>A a. M = A + {#a#}\"\nby (induct M) auto\n\nlemma multiset_cases [cases type]:\n  obtains (empty) \"M = {#}\"\n    | (add) N x where \"M = N + {#x#}\"\n  using assms by (induct M) simp_all\n\nlemma multi_drop_mem_not_eq: \"c \\<in># B \\<Longrightarrow> B - {#c#} \\<noteq> B\"\nby (cases \"B = {#}\") (auto dest: multi_member_split)\n\nlemma multiset_partition: \"M = {# x:#M. P x #} + {# x:#M. \\<not> P x #}\"\napply (subst multiset_eq_iff)\napply auto\ndone\n\nlemma mset_less_size: \"(A::'a multiset) < B \\<Longrightarrow> size A < size B\"\nproof (induct A arbitrary: B)\n  case (empty M)\n  then have \"M \\<noteq> {#}\" by (simp add: mset_less_empty_nonempty)\n  then obtain M' x where \"M = M' + {#x#}\"\n    by (blast dest: multi_nonempty_split)\n  then show ?case by simp\nnext\n  case (add S x T)\n  have IH: \"\\<And>B. S < B \\<Longrightarrow> size S < size B\" by fact\n  have SxsubT: \"S + {#x#} < T\" by fact\n  then have \"x \\<in># T\" and \"S < T\" by (auto dest: mset_less_insertD)\n  then obtain T' where T: \"T = T' + {#x#}\"\n    by (blast dest: multi_member_split)\n  then have \"S < T'\" using SxsubT\n    by (blast intro: mset_less_add_bothsides)\n  then have \"size S < size T'\" using IH by simp\n  then show ?case using T by simp\nqed\n\n\nsubsubsection {* Strong induction and subset induction for multisets *}\n\ntext {* Well-foundedness of strict subset relation *}\n\nlemma wf_less_mset_rel: \"wf {(M, N :: 'a multiset). M < N}\"\napply (rule wf_measure [THEN wf_subset, where f1=size])\napply (clarsimp simp: measure_def inv_image_def mset_less_size)\ndone\n\nlemma full_multiset_induct [case_names less]:\nassumes ih: \"\\<And>B. \\<forall>(A::'a multiset). A < B \\<longrightarrow> P A \\<Longrightarrow> P B\"\nshows \"P B\"\napply (rule wf_less_mset_rel [THEN wf_induct])\napply (rule ih, auto)\ndone\n\nlemma multi_subset_induct [consumes 2, case_names empty add]:\nassumes \"F \\<le> A\"\n  and empty: \"P {#}\"\n  and insert: \"\\<And>a F. a \\<in># A \\<Longrightarrow> P F \\<Longrightarrow> P (F + {#a#})\"\nshows \"P F\"\nproof -\n  from `F \\<le> A`\n  show ?thesis\n  proof (induct F)\n    show \"P {#}\" by fact\n  next\n    fix x F\n    assume P: \"F \\<le> A \\<Longrightarrow> P F\" and i: \"F + {#x#} \\<le> A\"\n    show \"P (F + {#x#})\"\n    proof (rule insert)\n      from i show \"x \\<in># A\" by (auto dest: mset_le_insertD)\n      from i have \"F \\<le> A\" by (auto dest: mset_le_insertD)\n      with P show \"P F\" .\n    qed\n  qed\nqed\n\n\nsubsection {* The fold combinator *}\n\ndefinition fold :: \"('a \\<Rightarrow> 'b \\<Rightarrow> 'b) \\<Rightarrow> 'b \\<Rightarrow> 'a multiset \\<Rightarrow> 'b\"\nwhere\n  \"fold f s M = Finite_Set.fold (\\<lambda>x. f x ^^ count M x) s (set_of M)\"\n\nlemma fold_mset_empty [simp]:\n  \"fold f s {#} = s\"\n  by (simp add: fold_def)\n\ncontext comp_fun_commute\nbegin\n\nlemma fold_mset_insert:\n  \"fold f s (M + {#x#}) = f x (fold f s M)\"\nproof -\n  interpret mset: comp_fun_commute \"\\<lambda>y. f y ^^ count M y\"\n    by (fact comp_fun_commute_funpow)\n  interpret mset_union: comp_fun_commute \"\\<lambda>y. f y ^^ count (M + {#x#}) y\"\n    by (fact comp_fun_commute_funpow)\n  show ?thesis\n  proof (cases \"x \\<in> set_of M\")\n    case False\n    then have *: \"count (M + {#x#}) x = 1\" by simp\n    from False have \"Finite_Set.fold (\\<lambda>y. f y ^^ count (M + {#x#}) y) s (set_of M) =\n      Finite_Set.fold (\\<lambda>y. f y ^^ count M y) s (set_of M)\"\n      by (auto intro!: Finite_Set.fold_cong comp_fun_commute_funpow)\n    with False * show ?thesis\n      by (simp add: fold_def del: count_union)\n  next\n    case True\n    def N \\<equiv> \"set_of M - {x}\"\n    from N_def True have *: \"set_of M = insert x N\" \"x \\<notin> N\" \"finite N\" by auto\n    then have \"Finite_Set.fold (\\<lambda>y. f y ^^ count (M + {#x#}) y) s N =\n      Finite_Set.fold (\\<lambda>y. f y ^^ count M y) s N\"\n      by (auto intro!: Finite_Set.fold_cong comp_fun_commute_funpow)\n    with * show ?thesis by (simp add: fold_def del: count_union) simp\n  qed\nqed\n\ncorollary fold_mset_single [simp]:\n  \"fold f s {#x#} = f x s\"\nproof -\n  have \"fold f s ({#} + {#x#}) = f x s\" by (simp only: fold_mset_insert) simp\n  then show ?thesis by simp\nqed\n\nlemma fold_mset_fun_left_comm:\n  \"f x (fold f s M) = fold f (f x s) M\"\n  by (induct M) (simp_all add: fold_mset_insert fun_left_comm)\n\nlemma fold_mset_union [simp]:\n  \"fold f s (M + N) = fold f (fold f s M) N\"\nproof (induct M)\n  case empty then show ?case by simp\nnext\n  case (add M x)\n  have \"M + {#x#} + N = (M + N) + {#x#}\"\n    by (simp add: ac_simps)\n  with add show ?case by (simp add: fold_mset_insert fold_mset_fun_left_comm)\nqed\n\nlemma fold_mset_fusion:\n  assumes \"comp_fun_commute g\"\n  shows \"(\\<And>x y. h (g x y) = f x (h y)) \\<Longrightarrow> h (fold g w A) = fold f (h w) A\" (is \"PROP ?P\")\nproof -\n  interpret comp_fun_commute g by (fact assms)\n  show \"PROP ?P\" by (induct A) auto\nqed\n\nend\n\ntext {*\n  A note on code generation: When defining some function containing a\n  subterm @{term \"fold F\"}, code generation is not automatic. When\n  interpreting locale @{text left_commutative} with @{text F}, the\n  would be code thms for @{const fold} become thms like\n  @{term \"fold F z {#} = z\"} where @{text F} is not a pattern but\n  contains defined symbols, i.e.\\ is not a code thm. Hence a separate\n  constant with its own code thms needs to be introduced for @{text\n  F}. See the image operator below.\n*}\n\n\nsubsection {* Image *}\n\ndefinition image_mset :: \"('a \\<Rightarrow> 'b) \\<Rightarrow> 'a multiset \\<Rightarrow> 'b multiset\" where\n  \"image_mset f = fold (plus o single o f) {#}\"\n\nlemma comp_fun_commute_mset_image:\n  \"comp_fun_commute (plus o single o f)\"\nproof\nqed (simp add: ac_simps fun_eq_iff)\n\nlemma image_mset_empty [simp]: \"image_mset f {#} = {#}\"\n  by (simp add: image_mset_def)\n\nlemma image_mset_single [simp]: \"image_mset f {#x#} = {#f x#}\"\nproof -\n  interpret comp_fun_commute \"plus o single o f\"\n    by (fact comp_fun_commute_mset_image)\n  show ?thesis by (simp add: image_mset_def)\nqed\n\nlemma image_mset_union [simp]:\n  \"image_mset f (M + N) = image_mset f M + image_mset f N\"\nproof -\n  interpret comp_fun_commute \"plus o single o f\"\n    by (fact comp_fun_commute_mset_image)\n  show ?thesis by (induct N) (simp_all add: image_mset_def ac_simps)\nqed\n\ncorollary image_mset_insert:\n  \"image_mset f (M + {#a#}) = image_mset f M + {#f a#}\"\n  by simp\n\nlemma set_of_image_mset [simp]:\n  \"set_of (image_mset f M) = image f (set_of M)\"\n  by (induct M) simp_all\n\nlemma size_image_mset [simp]:\n  \"size (image_mset f M) = size M\"\n  by (induct M) simp_all\n\nlemma image_mset_is_empty_iff [simp]:\n  \"image_mset f M = {#} \\<longleftrightarrow> M = {#}\"\n  by (cases M) auto\n\nsyntax\n  \"_comprehension1_mset\" :: \"'a \\<Rightarrow> 'b \\<Rightarrow> 'b multiset \\<Rightarrow> 'a multiset\"\n      (\"({#_/. _ :# _#})\")\ntranslations\n  \"{#e. x:#M#}\" == \"CONST image_mset (%x. e) M\"\n\nsyntax\n  \"_comprehension2_mset\" :: \"'a \\<Rightarrow> 'b \\<Rightarrow> 'b multiset \\<Rightarrow> bool \\<Rightarrow> 'a multiset\"\n      (\"({#_/ | _ :# _./ _#})\")\ntranslations\n  \"{#e | x:#M. P#}\" => \"{#e. x :# {# x:#M. P#}#}\"\n\ntext {*\n  This allows to write not just filters like @{term \"{#x:#M. x<c#}\"}\n  but also images like @{term \"{#x+x. x:#M #}\"} and @{term [source]\n  \"{#x+x|x:#M. x<c#}\"}, where the latter is currently displayed as\n  @{term \"{#x+x|x:#M. x<c#}\"}.\n*}\n\nfunctor image_mset: image_mset\nproof -\n  fix f g show \"image_mset f \\<circ> image_mset g = image_mset (f \\<circ> g)\"\n  proof\n    fix A\n    show \"(image_mset f \\<circ> image_mset g) A = image_mset (f \\<circ> g) A\"\n      by (induct A) simp_all\n  qed\n  show \"image_mset id = id\"\n  proof\n    fix A\n    show \"image_mset id A = id A\"\n      by (induct A) simp_all\n  qed\nqed\n\ndeclare image_mset.identity [simp]\n\n\nsubsection {* Further conversions *}\n\nprimrec multiset_of :: \"'a list \\<Rightarrow> 'a multiset\" where\n  \"multiset_of [] = {#}\" |\n  \"multiset_of (a # x) = multiset_of x + {# a #}\"\n\nlemma in_multiset_in_set:\n  \"x \\<in># multiset_of xs \\<longleftrightarrow> x \\<in> set xs\"\n  by (induct xs) simp_all\n\nlemma count_multiset_of:\n  \"count (multiset_of xs) x = length (filter (\\<lambda>y. x = y) xs)\"\n  by (induct xs) simp_all\n\nlemma multiset_of_zero_iff[simp]: \"(multiset_of x = {#}) = (x = [])\"\nby (induct x) auto\n\nlemma multiset_of_zero_iff_right[simp]: \"({#} = multiset_of x) = (x = [])\"\nby (induct x) auto\n\nlemma set_of_multiset_of[simp]: \"set_of (multiset_of x) = set x\"\nby (induct x) auto\n\nlemma mem_set_multiset_eq: \"x \\<in> set xs = (x :# multiset_of xs)\"\nby (induct xs) auto\n\nlemma size_multiset_of [simp]: \"size (multiset_of xs) = length xs\"\n  by (induct xs) simp_all\n\nlemma multiset_of_append [simp]:\n  \"multiset_of (xs @ ys) = multiset_of xs + multiset_of ys\"\n  by (induct xs arbitrary: ys) (auto simp: ac_simps)\n\nlemma multiset_of_filter:\n  \"multiset_of (filter P xs) = {#x :# multiset_of xs. P x #}\"\n  by (induct xs) simp_all\n\nlemma multiset_of_rev [simp]:\n  \"multiset_of (rev xs) = multiset_of xs\"\n  by (induct xs) simp_all\n\nlemma surj_multiset_of: \"surj multiset_of\"\napply (unfold surj_def)\napply (rule allI)\napply (rule_tac M = y in multiset_induct)\n apply auto\napply (rule_tac x = \"x # xa\" in exI)\napply auto\ndone\n\nlemma set_count_greater_0: \"set x = {a. count (multiset_of x) a > 0}\"\nby (induct x) auto\n\nlemma distinct_count_atmost_1:\n  \"distinct x = (! a. count (multiset_of x) a = (if a \\<in> set x then 1 else 0))\"\napply (induct x, simp, rule iffI, simp_all)\napply (rename_tac a b)\napply (rule conjI)\napply (simp_all add: set_of_multiset_of [THEN sym] del: set_of_multiset_of)\napply (erule_tac x = a in allE, simp, clarify)\napply (erule_tac x = aa in allE, simp)\ndone\n\nlemma multiset_of_eq_setD:\n  \"multiset_of xs = multiset_of ys \\<Longrightarrow> set xs = set ys\"\nby (rule) (auto simp add:multiset_eq_iff set_count_greater_0)\n\nlemma set_eq_iff_multiset_of_eq_distinct:\n  \"distinct x \\<Longrightarrow> distinct y \\<Longrightarrow>\n    (set x = set y) = (multiset_of x = multiset_of y)\"\nby (auto simp: multiset_eq_iff distinct_count_atmost_1)\n\nlemma set_eq_iff_multiset_of_remdups_eq:\n   \"(set x = set y) = (multiset_of (remdups x) = multiset_of (remdups y))\"\napply (rule iffI)\napply (simp add: set_eq_iff_multiset_of_eq_distinct[THEN iffD1])\napply (drule distinct_remdups [THEN distinct_remdups\n      [THEN set_eq_iff_multiset_of_eq_distinct [THEN iffD2]]])\napply simp\ndone\n\nlemma multiset_of_compl_union [simp]:\n  \"multiset_of [x\\<leftarrow>xs. P x] + multiset_of [x\\<leftarrow>xs. \\<not>P x] = multiset_of xs\"\n  by (induct xs) (auto simp: ac_simps)\n\nlemma count_multiset_of_length_filter:\n  \"count (multiset_of xs) x = length (filter (\\<lambda>y. x = y) xs)\"\n  by (induct xs) auto\n\nlemma nth_mem_multiset_of: \"i < length ls \\<Longrightarrow> (ls ! i) :# multiset_of ls\"\napply (induct ls arbitrary: i)\n apply simp\napply (case_tac i)\n apply auto\ndone\n\nlemma multiset_of_remove1[simp]:\n  \"multiset_of (remove1 a xs) = multiset_of xs - {#a#}\"\nby (induct xs) (auto simp add: multiset_eq_iff)\n\nlemma multiset_of_eq_length:\n  assumes \"multiset_of xs = multiset_of ys\"\n  shows \"length xs = length ys\"\n  using assms by (metis size_multiset_of)\n\nlemma multiset_of_eq_length_filter:\n  assumes \"multiset_of xs = multiset_of ys\"\n  shows \"length (filter (\\<lambda>x. z = x) xs) = length (filter (\\<lambda>y. z = y) ys)\"\n  using assms by (metis count_multiset_of)\n\nlemma fold_multiset_equiv:\n  assumes f: \"\\<And>x y. x \\<in> set xs \\<Longrightarrow> y \\<in> set xs \\<Longrightarrow> f x \\<circ> f y = f y \\<circ> f x\"\n    and equiv: \"multiset_of xs = multiset_of ys\"\n  shows \"List.fold f xs = List.fold f ys\"\nusing f equiv [symmetric]\nproof (induct xs arbitrary: ys)\n  case Nil then show ?case by simp\nnext\n  case (Cons x xs)\n  then have *: \"set ys = set (x # xs)\" by (blast dest: multiset_of_eq_setD)\n  have \"\\<And>x y. x \\<in> set ys \\<Longrightarrow> y \\<in> set ys \\<Longrightarrow> f x \\<circ> f y = f y \\<circ> f x\"\n    by (rule Cons.prems(1)) (simp_all add: *)\n  moreover from * have \"x \\<in> set ys\" by simp\n  ultimately have \"List.fold f ys = List.fold f (remove1 x ys) \\<circ> f x\" by (fact fold_remove1_split)\n  moreover from Cons.prems have \"List.fold f xs = List.fold f (remove1 x ys)\" by (auto intro: Cons.hyps)\n  ultimately show ?case by simp\nqed\n\nlemma multiset_of_insort [simp]:\n  \"multiset_of (insort x xs) = multiset_of xs + {#x#}\"\n  by (induct xs) (simp_all add: ac_simps)\n\nlemma in_multiset_of:\n  \"x \\<in># multiset_of xs \\<longleftrightarrow> x \\<in> set xs\"\n  by (induct xs) simp_all\n\nlemma multiset_of_map:\n  \"multiset_of (map f xs) = image_mset f (multiset_of xs)\"\n  by (induct xs) simp_all\n\ndefinition multiset_of_set :: \"'a set \\<Rightarrow> 'a multiset\"\nwhere\n  \"multiset_of_set = folding.F (\\<lambda>x M. {#x#} + M) {#}\"\n\ninterpretation multiset_of_set!: folding \"\\<lambda>x M. {#x#} + M\" \"{#}\"\nwhere\n  \"folding.F (\\<lambda>x M. {#x#} + M) {#} = multiset_of_set\"\nproof -\n  interpret comp_fun_commute \"\\<lambda>x M. {#x#} + M\" by default (simp add: fun_eq_iff ac_simps)\n  show \"folding (\\<lambda>x M. {#x#} + M)\" by default (fact comp_fun_commute)\n  from multiset_of_set_def show \"folding.F (\\<lambda>x M. {#x#} + M) {#} = multiset_of_set\" ..\nqed\n\nlemma count_multiset_of_set [simp]:\n  \"finite A \\<Longrightarrow> x \\<in> A \\<Longrightarrow> count (multiset_of_set A) x = 1\" (is \"PROP ?P\")\n  \"\\<not> finite A \\<Longrightarrow> count (multiset_of_set A) x = 0\" (is \"PROP ?Q\")\n  \"x \\<notin> A \\<Longrightarrow> count (multiset_of_set A) x = 0\" (is \"PROP ?R\")\nproof -\n  { fix A\n    assume \"x \\<notin> A\"\n    have \"count (multiset_of_set A) x = 0\"\n    proof (cases \"finite A\")\n      case False then show ?thesis by simp\n    next\n      case True from True `x \\<notin> A` show ?thesis by (induct A) auto\n    qed\n  } note * = this\n  then show \"PROP ?P\" \"PROP ?Q\" \"PROP ?R\"\n  by (auto elim!: Set.set_insert)\nqed -- {* TODO: maybe define @{const multiset_of_set} also in terms of @{const Abs_multiset} *}\n\ncontext linorder\nbegin\n\ndefinition sorted_list_of_multiset :: \"'a multiset \\<Rightarrow> 'a list\"\nwhere\n  \"sorted_list_of_multiset M = fold insort [] M\"\n\nlemma sorted_list_of_multiset_empty [simp]:\n  \"sorted_list_of_multiset {#} = []\"\n  by (simp add: sorted_list_of_multiset_def)\n\nlemma sorted_list_of_multiset_singleton [simp]:\n  \"sorted_list_of_multiset {#x#} = [x]\"\nproof -\n  interpret comp_fun_commute insort by (fact comp_fun_commute_insort)\n  show ?thesis by (simp add: sorted_list_of_multiset_def)\nqed\n\nlemma sorted_list_of_multiset_insert [simp]:\n  \"sorted_list_of_multiset (M + {#x#}) = List.insort x (sorted_list_of_multiset M)\"\nproof -\n  interpret comp_fun_commute insort by (fact comp_fun_commute_insort)\n  show ?thesis by (simp add: sorted_list_of_multiset_def)\nqed\n\nend\n\nlemma multiset_of_sorted_list_of_multiset [simp]:\n  \"multiset_of (sorted_list_of_multiset M) = M\"\n  by (induct M) simp_all\n\nlemma sorted_list_of_multiset_multiset_of [simp]:\n  \"sorted_list_of_multiset (multiset_of xs) = sort xs\"\n  by (induct xs) simp_all\n\nlemma finite_set_of_multiset_of_set:\n  assumes \"finite A\"\n  shows \"set_of (multiset_of_set A) = A\"\n  using assms by (induct A) simp_all\n\nlemma infinite_set_of_multiset_of_set:\n  assumes \"\\<not> finite A\"\n  shows \"set_of (multiset_of_set A) = {}\"\n  using assms by simp\n\nlemma set_sorted_list_of_multiset [simp]:\n  \"set (sorted_list_of_multiset M) = set_of M\"\n  by (induct M) (simp_all add: set_insort)\n\nlemma sorted_list_of_multiset_of_set [simp]:\n  \"sorted_list_of_multiset (multiset_of_set A) = sorted_list_of_set A\"\n  by (cases \"finite A\") (induct A rule: finite_induct, simp_all add: ac_simps)\n\n\nsubsection {* Big operators *}\n\nno_notation times (infixl \"*\" 70)\nno_notation Groups.one (\"1\")\n\nlocale comm_monoid_mset = comm_monoid\nbegin\n\ndefinition F :: \"'a multiset \\<Rightarrow> 'a\"\nwhere\n  eq_fold: \"F M = Multiset.fold f 1 M\"\n\nlemma empty [simp]:\n  \"F {#} = 1\"\n  by (simp add: eq_fold)\n\nlemma singleton [simp]:\n  \"F {#x#} = x\"\nproof -\n  interpret comp_fun_commute\n    by default (simp add: fun_eq_iff left_commute)\n  show ?thesis by (simp add: eq_fold)\nqed\n\nlemma union [simp]:\n  \"F (M + N) = F M * F N\"\nproof -\n  interpret comp_fun_commute f\n    by default (simp add: fun_eq_iff left_commute)\n  show ?thesis by (induct N) (simp_all add: left_commute eq_fold)\nqed\n\nend\n\nnotation times (infixl \"*\" 70)\nnotation Groups.one (\"1\")\n\ncontext comm_monoid_add\nbegin\n\ndefinition msetsum :: \"'a multiset \\<Rightarrow> 'a\"\nwhere\n  \"msetsum = comm_monoid_mset.F plus 0\"\n\nsublocale msetsum!: comm_monoid_mset plus 0\nwhere\n  \"comm_monoid_mset.F plus 0 = msetsum\"\nproof -\n  show \"comm_monoid_mset plus 0\" ..\n  from msetsum_def show \"comm_monoid_mset.F plus 0 = msetsum\" ..\nqed\n\nlemma setsum_unfold_msetsum:\n  \"setsum f A = msetsum (image_mset f (multiset_of_set A))\"\n  by (cases \"finite A\") (induct A rule: finite_induct, simp_all)\n\nend\n\nsyntax\n  \"_msetsum_image\" :: \"pttrn \\<Rightarrow> 'b set \\<Rightarrow> 'a \\<Rightarrow> 'a::comm_monoid_add\"\n      (\"(3SUM _:#_. _)\" [0, 51, 10] 10)\n\nsyntax (xsymbols)\n  \"_msetsum_image\" :: \"pttrn \\<Rightarrow> 'b set \\<Rightarrow> 'a \\<Rightarrow> 'a::comm_monoid_add\"\n      (\"(3\\<Sum>_\\<in>#_. _)\" [0, 51, 10] 10)\n\nsyntax (HTML output)\n  \"_msetsum_image\" :: \"pttrn \\<Rightarrow> 'b set \\<Rightarrow> 'a \\<Rightarrow> 'a::comm_monoid_add\"\n      (\"(3\\<Sum>_\\<in>#_. _)\" [0, 51, 10] 10)\n\ntranslations\n  \"SUM i :# A. b\" == \"CONST msetsum (CONST image_mset (\\<lambda>i. b) A)\"\n\ncontext comm_monoid_mult\nbegin\n\ndefinition msetprod :: \"'a multiset \\<Rightarrow> 'a\"\nwhere\n  \"msetprod = comm_monoid_mset.F times 1\"\n\nsublocale msetprod!: comm_monoid_mset times 1\nwhere\n  \"comm_monoid_mset.F times 1 = msetprod\"\nproof -\n  show \"comm_monoid_mset times 1\" ..\n  from msetprod_def show \"comm_monoid_mset.F times 1 = msetprod\" ..\nqed\n\nlemma msetprod_empty:\n  \"msetprod {#} = 1\"\n  by (fact msetprod.empty)\n\nlemma msetprod_singleton:\n  \"msetprod {#x#} = x\"\n  by (fact msetprod.singleton)\n\nlemma msetprod_Un:\n  \"msetprod (A + B) = msetprod A * msetprod B\"\n  by (fact msetprod.union)\n\nlemma setprod_unfold_msetprod:\n  \"setprod f A = msetprod (image_mset f (multiset_of_set A))\"\n  by (cases \"finite A\") (induct A rule: finite_induct, simp_all)\n\nlemma msetprod_multiplicity:\n  \"msetprod M = setprod (\\<lambda>x. x ^ count M x) (set_of M)\"\n  by (simp add: Multiset.fold_def setprod.eq_fold msetprod.eq_fold funpow_times_power comp_def)\n\nend\n\nsyntax\n  \"_msetprod_image\" :: \"pttrn \\<Rightarrow> 'b set \\<Rightarrow> 'a \\<Rightarrow> 'a::comm_monoid_mult\"\n      (\"(3PROD _:#_. _)\" [0, 51, 10] 10)\n\nsyntax (xsymbols)\n  \"_msetprod_image\" :: \"pttrn \\<Rightarrow> 'b set \\<Rightarrow> 'a \\<Rightarrow> 'a::comm_monoid_mult\"\n      (\"(3\\<Prod>_\\<in>#_. _)\" [0, 51, 10] 10)\n\nsyntax (HTML output)\n  \"_msetprod_image\" :: \"pttrn \\<Rightarrow> 'b set \\<Rightarrow> 'a \\<Rightarrow> 'a::comm_monoid_mult\"\n      (\"(3\\<Prod>_\\<in>#_. _)\" [0, 51, 10] 10)\n\ntranslations\n  \"PROD i :# A. b\" == \"CONST msetprod (CONST image_mset (\\<lambda>i. b) A)\"\n\nlemma (in comm_semiring_1) dvd_msetprod:\n  assumes \"x \\<in># A\"\n  shows \"x dvd msetprod A\"\nproof -\n  from assms have \"A = (A - {#x#}) + {#x#}\" by simp\n  then obtain B where \"A = B + {#x#}\" ..\n  then show ?thesis by simp\nqed\n\n\nsubsection {* Cardinality *}\n\ndefinition mcard :: \"'a multiset \\<Rightarrow> nat\"\nwhere\n  \"mcard = msetsum \\<circ> image_mset (\\<lambda>_. 1)\"\n\nlemma mcard_empty [simp]:\n  \"mcard {#} = 0\"\n  by (simp add: mcard_def)\n\nlemma mcard_singleton [simp]:\n  \"mcard {#a#} = Suc 0\"\n  by (simp add: mcard_def)\n\nlemma mcard_plus [simp]:\n  \"mcard (M + N) = mcard M + mcard N\"\n  by (simp add: mcard_def)\n\nlemma mcard_empty_iff [simp]:\n  \"mcard M = 0 \\<longleftrightarrow> M = {#}\"\n  by (induct M) simp_all\n\nlemma mcard_unfold_setsum:\n  \"mcard M = setsum (count M) (set_of M)\"\nproof (induct M)\n  case empty then show ?case by simp\nnext\n  case (add M x) then show ?case\n    by (cases \"x \\<in> set_of M\")\n      (simp_all del: mem_set_of_iff add: setsum.distrib setsum.delta' insert_absorb, simp)\nqed\n\nlemma size_eq_mcard:\n  \"size = mcard\"\n  by (simp add: fun_eq_iff size_multiset_overloaded_eq mcard_unfold_setsum)\n\nlemma mcard_multiset_of:\n  \"mcard (multiset_of xs) = length xs\"\n  by (induct xs) simp_all\n\nlemma mcard_mono: assumes \"A \\<le> B\"\n  shows \"mcard A \\<le> mcard B\"\nproof -\n  from assms[unfolded mset_le_exists_conv]\n  obtain C where B: \"B = A + C\" by auto\n  show ?thesis unfolding B by (induct C, auto)\nqed\n\nlemma mcard_filter_lesseq[simp]: \"mcard (Multiset.filter f M) \\<le> mcard M\"\n  by (rule mcard_mono[OF multiset_filter_subset])\n\n\nsubsection {* Alternative representations *}\n\nsubsubsection {* Lists *}\n\ncontext linorder\nbegin\n\nlemma multiset_of_insort [simp]:\n  \"multiset_of (insort_key k x xs) = {#x#} + multiset_of xs\"\n  by (induct xs) (simp_all add: ac_simps)\n\nlemma multiset_of_sort [simp]:\n  \"multiset_of (sort_key k xs) = multiset_of xs\"\n  by (induct xs) (simp_all add: ac_simps)\n\ntext {*\n  This lemma shows which properties suffice to show that a function\n  @{text \"f\"} with @{text \"f xs = ys\"} behaves like sort.\n*}\n\nlemma properties_for_sort_key:\n  assumes \"multiset_of ys = multiset_of xs\"\n  and \"\\<And>k. k \\<in> set ys \\<Longrightarrow> filter (\\<lambda>x. f k = f x) ys = filter (\\<lambda>x. f k = f x) xs\"\n  and \"sorted (map f ys)\"\n  shows \"sort_key f xs = ys\"\nusing assms\nproof (induct xs arbitrary: ys)\n  case Nil then show ?case by simp\nnext\n  case (Cons x xs)\n  from Cons.prems(2) have\n    \"\\<forall>k \\<in> set ys. filter (\\<lambda>x. f k = f x) (remove1 x ys) = filter (\\<lambda>x. f k = f x) xs\"\n    by (simp add: filter_remove1)\n  with Cons.prems have \"sort_key f xs = remove1 x ys\"\n    by (auto intro!: Cons.hyps simp add: sorted_map_remove1)\n  moreover from Cons.prems have \"x \\<in> set ys\"\n    by (auto simp add: mem_set_multiset_eq intro!: ccontr)\n  ultimately show ?case using Cons.prems by (simp add: insort_key_remove1)\nqed\n\nlemma properties_for_sort:\n  assumes multiset: \"multiset_of ys = multiset_of xs\"\n  and \"sorted ys\"\n  shows \"sort xs = ys\"\nproof (rule properties_for_sort_key)\n  from multiset show \"multiset_of ys = multiset_of xs\" .\n  from `sorted ys` show \"sorted (map (\\<lambda>x. x) ys)\" by simp\n  from multiset have \"\\<And>k. length (filter (\\<lambda>y. k = y) ys) = length (filter (\\<lambda>x. k = x) xs)\"\n    by (rule multiset_of_eq_length_filter)\n  then have \"\\<And>k. replicate (length (filter (\\<lambda>y. k = y) ys)) k = replicate (length (filter (\\<lambda>x. k = x) xs)) k\"\n    by simp\n  then show \"\\<And>k. k \\<in> set ys \\<Longrightarrow> filter (\\<lambda>y. k = y) ys = filter (\\<lambda>x. k = x) xs\"\n    by (simp add: replicate_length_filter)\nqed\n\nlemma sort_key_by_quicksort:\n  \"sort_key f xs = sort_key f [x\\<leftarrow>xs. f x < f (xs ! (length xs div 2))]\n    @ [x\\<leftarrow>xs. f x = f (xs ! (length xs div 2))]\n    @ sort_key f [x\\<leftarrow>xs. f x > f (xs ! (length xs div 2))]\" (is \"sort_key f ?lhs = ?rhs\")\nproof (rule properties_for_sort_key)\n  show \"multiset_of ?rhs = multiset_of ?lhs\"\n    by (rule multiset_eqI) (auto simp add: multiset_of_filter)\nnext\n  show \"sorted (map f ?rhs)\"\n    by (auto simp add: sorted_append intro: sorted_map_same)\nnext\n  fix l\n  assume \"l \\<in> set ?rhs\"\n  let ?pivot = \"f (xs ! (length xs div 2))\"\n  have *: \"\\<And>x. f l = f x \\<longleftrightarrow> f x = f l\" by auto\n  have \"[x \\<leftarrow> sort_key f xs . f x = f l] = [x \\<leftarrow> xs. f x = f l]\"\n    unfolding filter_sort by (rule properties_for_sort_key) (auto intro: sorted_map_same)\n  with * have **: \"[x \\<leftarrow> sort_key f xs . f l = f x] = [x \\<leftarrow> xs. f l = f x]\" by simp\n  have \"\\<And>x P. P (f x) ?pivot \\<and> f l = f x \\<longleftrightarrow> P (f l) ?pivot \\<and> f l = f x\" by auto\n  then have \"\\<And>P. [x \\<leftarrow> sort_key f xs . P (f x) ?pivot \\<and> f l = f x] =\n    [x \\<leftarrow> sort_key f xs. P (f l) ?pivot \\<and> f l = f x]\" by simp\n  note *** = this [of \"op <\"] this [of \"op >\"] this [of \"op =\"]\n  show \"[x \\<leftarrow> ?rhs. f l = f x] = [x \\<leftarrow> ?lhs. f l = f x]\"\n  proof (cases \"f l\" ?pivot rule: linorder_cases)\n    case less\n    then have \"f l \\<noteq> ?pivot\" and \"\\<not> f l > ?pivot\" by auto\n    with less show ?thesis\n      by (simp add: filter_sort [symmetric] ** ***)\n  next\n    case equal then show ?thesis\n      by (simp add: * less_le)\n  next\n    case greater\n    then have \"f l \\<noteq> ?pivot\" and \"\\<not> f l < ?pivot\" by auto\n    with greater show ?thesis\n      by (simp add: filter_sort [symmetric] ** ***)\n  qed\nqed\n\nlemma sort_by_quicksort:\n  \"sort xs = sort [x\\<leftarrow>xs. x < xs ! (length xs div 2)]\n    @ [x\\<leftarrow>xs. x = xs ! (length xs div 2)]\n    @ sort [x\\<leftarrow>xs. x > xs ! (length xs div 2)]\" (is \"sort ?lhs = ?rhs\")\n  using sort_key_by_quicksort [of \"\\<lambda>x. x\", symmetric] by simp\n\ntext {* A stable parametrized quicksort *}\n\ndefinition part :: \"('b \\<Rightarrow> 'a) \\<Rightarrow> 'a \\<Rightarrow> 'b list \\<Rightarrow> 'b list \\<times> 'b list \\<times> 'b list\" where\n  \"part f pivot xs = ([x \\<leftarrow> xs. f x < pivot], [x \\<leftarrow> xs. f x = pivot], [x \\<leftarrow> xs. pivot < f x])\"\n\nlemma part_code [code]:\n  \"part f pivot [] = ([], [], [])\"\n  \"part f pivot (x # xs) = (let (lts, eqs, gts) = part f pivot xs; x' = f x in\n     if x' < pivot then (x # lts, eqs, gts)\n     else if x' > pivot then (lts, eqs, x # gts)\n     else (lts, x # eqs, gts))\"\n  by (auto simp add: part_def Let_def split_def)\n\nlemma sort_key_by_quicksort_code [code]:\n  \"sort_key f xs = (case xs of [] \\<Rightarrow> []\n    | [x] \\<Rightarrow> xs\n    | [x, y] \\<Rightarrow> (if f x \\<le> f y then xs else [y, x])\n    | _ \\<Rightarrow> (let (lts, eqs, gts) = part f (f (xs ! (length xs div 2))) xs\n       in sort_key f lts @ eqs @ sort_key f gts))\"\nproof (cases xs)\n  case Nil then show ?thesis by simp\nnext\n  case (Cons _ ys) note hyps = Cons show ?thesis\n  proof (cases ys)\n    case Nil with hyps show ?thesis by simp\n  next\n    case (Cons _ zs) note hyps = hyps Cons show ?thesis\n    proof (cases zs)\n      case Nil with hyps show ?thesis by auto\n    next\n      case Cons\n      from sort_key_by_quicksort [of f xs]\n      have \"sort_key f xs = (let (lts, eqs, gts) = part f (f (xs ! (length xs div 2))) xs\n        in sort_key f lts @ eqs @ sort_key f gts)\"\n      by (simp only: split_def Let_def part_def fst_conv snd_conv)\n      with hyps Cons show ?thesis by (simp only: list.cases)\n    qed\n  qed\nqed\n\nend\n\nhide_const (open) part\n\nlemma multiset_of_remdups_le: \"multiset_of (remdups xs) \\<le> multiset_of xs\"\n  by (induct xs) (auto intro: order_trans)\n\nlemma multiset_of_update:\n  \"i < length ls \\<Longrightarrow> multiset_of (ls[i := v]) = multiset_of ls - {#ls ! i#} + {#v#}\"\nproof (induct ls arbitrary: i)\n  case Nil then show ?case by simp\nnext\n  case (Cons x xs)\n  show ?case\n  proof (cases i)\n    case 0 then show ?thesis by simp\n  next\n    case (Suc i')\n    with Cons show ?thesis\n      apply simp\n      apply (subst add.assoc)\n      apply (subst add.commute [of \"{#v#}\" \"{#x#}\"])\n      apply (subst add.assoc [symmetric])\n      apply simp\n      apply (rule mset_le_multiset_union_diff_commute)\n      apply (simp add: mset_le_single nth_mem_multiset_of)\n      done\n  qed\nqed\n\nlemma multiset_of_swap:\n  \"i < length ls \\<Longrightarrow> j < length ls \\<Longrightarrow>\n    multiset_of (ls[j := ls ! i, i := ls ! j]) = multiset_of ls\"\n  by (cases \"i = j\") (simp_all add: multiset_of_update nth_mem_multiset_of)\n\n\nsubsection {* The multiset order *}\n\nsubsubsection {* Well-foundedness *}\n\ndefinition mult1 :: \"('a \\<times> 'a) set => ('a multiset \\<times> 'a multiset) set\" where\n  \"mult1 r = {(N, M). \\<exists>a M0 K. M = M0 + {#a#} \\<and> N = M0 + K \\<and>\n      (\\<forall>b. b :# K --> (b, a) \\<in> r)}\"\n\ndefinition mult :: \"('a \\<times> 'a) set => ('a multiset \\<times> 'a multiset) set\" where\n  \"mult r = (mult1 r)\\<^sup>+\"\n\nlemma not_less_empty [iff]: \"(M, {#}) \\<notin> mult1 r\"\nby (simp add: mult1_def)\n\nlemma less_add: \"(N, M0 + {#a#}) \\<in> mult1 r ==>\n    (\\<exists>M. (M, M0) \\<in> mult1 r \\<and> N = M + {#a#}) \\<or>\n    (\\<exists>K. (\\<forall>b. b :# K --> (b, a) \\<in> r) \\<and> N = M0 + K)\"\n  (is \"_ \\<Longrightarrow> ?case1 (mult1 r) \\<or> ?case2\")\nproof (unfold mult1_def)\n  let ?r = \"\\<lambda>K a. \\<forall>b. b :# K --> (b, a) \\<in> r\"\n  let ?R = \"\\<lambda>N M. \\<exists>a M0 K. M = M0 + {#a#} \\<and> N = M0 + K \\<and> ?r K a\"\n  let ?case1 = \"?case1 {(N, M). ?R N M}\"\n\n  assume \"(N, M0 + {#a#}) \\<in> {(N, M). ?R N M}\"\n  then have \"\\<exists>a' M0' K.\n      M0 + {#a#} = M0' + {#a'#} \\<and> N = M0' + K \\<and> ?r K a'\" by simp\n  then show \"?case1 \\<or> ?case2\"\n  proof (elim exE conjE)\n    fix a' M0' K\n    assume N: \"N = M0' + K\" and r: \"?r K a'\"\n    assume \"M0 + {#a#} = M0' + {#a'#}\"\n    then have \"M0 = M0' \\<and> a = a' \\<or>\n        (\\<exists>K'. M0 = K' + {#a'#} \\<and> M0' = K' + {#a#})\"\n      by (simp only: add_eq_conv_ex)\n    then show ?thesis\n    proof (elim disjE conjE exE)\n      assume \"M0 = M0'\" \"a = a'\"\n      with N r have \"?r K a \\<and> N = M0 + K\" by simp\n      then have ?case2 .. then show ?thesis ..\n    next\n      fix K'\n      assume \"M0' = K' + {#a#}\"\n      with N have n: \"N = K' + K + {#a#}\" by (simp add: ac_simps)\n\n      assume \"M0 = K' + {#a'#}\"\n      with r have \"?R (K' + K) M0\" by blast\n      with n have ?case1 by simp then show ?thesis ..\n    qed\n  qed\nqed\n\nlemma all_accessible: \"wf r ==> \\<forall>M. M \\<in> Wellfounded.acc (mult1 r)\"\nproof\n  let ?R = \"mult1 r\"\n  let ?W = \"Wellfounded.acc ?R\"\n  {\n    fix M M0 a\n    assume M0: \"M0 \\<in> ?W\"\n      and wf_hyp: \"!!b. (b, a) \\<in> r ==> (\\<forall>M \\<in> ?W. M + {#b#} \\<in> ?W)\"\n      and acc_hyp: \"\\<forall>M. (M, M0) \\<in> ?R --> M + {#a#} \\<in> ?W\"\n    have \"M0 + {#a#} \\<in> ?W\"\n    proof (rule accI [of \"M0 + {#a#}\"])\n      fix N\n      assume \"(N, M0 + {#a#}) \\<in> ?R\"\n      then have \"((\\<exists>M. (M, M0) \\<in> ?R \\<and> N = M + {#a#}) \\<or>\n          (\\<exists>K. (\\<forall>b. b :# K --> (b, a) \\<in> r) \\<and> N = M0 + K))\"\n        by (rule less_add)\n      then show \"N \\<in> ?W\"\n      proof (elim exE disjE conjE)\n        fix M assume \"(M, M0) \\<in> ?R\" and N: \"N = M + {#a#}\"\n        from acc_hyp have \"(M, M0) \\<in> ?R --> M + {#a#} \\<in> ?W\" ..\n        from this and `(M, M0) \\<in> ?R` have \"M + {#a#} \\<in> ?W\" ..\n        then show \"N \\<in> ?W\" by (simp only: N)\n      next\n        fix K\n        assume N: \"N = M0 + K\"\n        assume \"\\<forall>b. b :# K --> (b, a) \\<in> r\"\n        then have \"M0 + K \\<in> ?W\"\n        proof (induct K)\n          case empty\n          from M0 show \"M0 + {#} \\<in> ?W\" by simp\n        next\n          case (add K x)\n          from add.prems have \"(x, a) \\<in> r\" by simp\n          with wf_hyp have \"\\<forall>M \\<in> ?W. M + {#x#} \\<in> ?W\" by blast\n          moreover from add have \"M0 + K \\<in> ?W\" by simp\n          ultimately have \"(M0 + K) + {#x#} \\<in> ?W\" ..\n          then show \"M0 + (K + {#x#}) \\<in> ?W\" by (simp only: add.assoc)\n        qed\n        then show \"N \\<in> ?W\" by (simp only: N)\n      qed\n    qed\n  } note tedious_reasoning = this\n\n  assume wf: \"wf r\"\n  fix M\n  show \"M \\<in> ?W\"\n  proof (induct M)\n    show \"{#} \\<in> ?W\"\n    proof (rule accI)\n      fix b assume \"(b, {#}) \\<in> ?R\"\n      with not_less_empty show \"b \\<in> ?W\" by contradiction\n    qed\n\n    fix M a assume \"M \\<in> ?W\"\n    from wf have \"\\<forall>M \\<in> ?W. M + {#a#} \\<in> ?W\"\n    proof induct\n      fix a\n      assume r: \"!!b. (b, a) \\<in> r ==> (\\<forall>M \\<in> ?W. M + {#b#} \\<in> ?W)\"\n      show \"\\<forall>M \\<in> ?W. M + {#a#} \\<in> ?W\"\n      proof\n        fix M assume \"M \\<in> ?W\"\n        then show \"M + {#a#} \\<in> ?W\"\n          by (rule acc_induct) (rule tedious_reasoning [OF _ r])\n      qed\n    qed\n    from this and `M \\<in> ?W` show \"M + {#a#} \\<in> ?W\" ..\n  qed\nqed\n\ntheorem wf_mult1: \"wf r ==> wf (mult1 r)\"\nby (rule acc_wfI) (rule all_accessible)\n\ntheorem wf_mult: \"wf r ==> wf (mult r)\"\nunfolding mult_def by (rule wf_trancl) (rule wf_mult1)\n\n\nsubsubsection {* Closure-free presentation *}\n\ntext {* One direction. *}\n\nlemma mult_implies_one_step:\n  \"trans r ==> (M, N) \\<in> mult r ==>\n    \\<exists>I J K. N = I + J \\<and> M = I + K \\<and> J \\<noteq> {#} \\<and>\n    (\\<forall>k \\<in> set_of K. \\<exists>j \\<in> set_of J. (k, j) \\<in> r)\"\napply (unfold mult_def mult1_def set_of_def)\napply (erule converse_trancl_induct, clarify)\n apply (rule_tac x = M0 in exI, simp, clarify)\napply (case_tac \"a :# K\")\n apply (rule_tac x = I in exI)\n apply (simp (no_asm))\n apply (rule_tac x = \"(K - {#a#}) + Ka\" in exI)\n apply (simp (no_asm_simp) add: add.assoc [symmetric])\n apply (drule_tac f = \"\\<lambda>M. M - {#a#}\" and x=\"?S + ?T\" in arg_cong)\n apply (simp add: diff_union_single_conv)\n apply (simp (no_asm_use) add: trans_def)\n apply blast\napply (subgoal_tac \"a :# I\")\n apply (rule_tac x = \"I - {#a#}\" in exI)\n apply (rule_tac x = \"J + {#a#}\" in exI)\n apply (rule_tac x = \"K + Ka\" in exI)\n apply (rule conjI)\n  apply (simp add: multiset_eq_iff split: nat_diff_split)\n apply (rule conjI)\n  apply (drule_tac f = \"\\<lambda>M. M - {#a#}\" and x=\"?S + ?T\" in arg_cong, simp)\n  apply (simp add: multiset_eq_iff split: nat_diff_split)\n apply (simp (no_asm_use) add: trans_def)\n apply blast\napply (subgoal_tac \"a :# (M0 + {#a#})\")\n apply simp\napply (simp (no_asm))\ndone\n\nlemma one_step_implies_mult_aux:\n  \"trans r ==>\n    \\<forall>I J K. (size J = n \\<and> J \\<noteq> {#} \\<and> (\\<forall>k \\<in> set_of K. \\<exists>j \\<in> set_of J. (k, j) \\<in> r))\n      --> (I + K, I + J) \\<in> mult r\"\napply (induct_tac n, auto)\napply (frule size_eq_Suc_imp_eq_union, clarify)\napply (rename_tac \"J'\", simp)\napply (erule notE, auto)\napply (case_tac \"J' = {#}\")\n apply (simp add: mult_def)\n apply (rule r_into_trancl)\n apply (simp add: mult1_def set_of_def, blast)\ntxt {* Now we know @{term \"J' \\<noteq> {#}\"}. *}\napply (cut_tac M = K and P = \"\\<lambda>x. (x, a) \\<in> r\" in multiset_partition)\napply (erule_tac P = \"\\<forall>k \\<in> set_of K. ?P k\" in rev_mp)\napply (erule ssubst)\napply (simp add: Ball_def, auto)\napply (subgoal_tac\n  \"((I + {# x :# K. (x, a) \\<in> r #}) + {# x :# K. (x, a) \\<notin> r #},\n    (I + {# x :# K. (x, a) \\<in> r #}) + J') \\<in> mult r\")\n prefer 2\n apply force\napply (simp (no_asm_use) add: add.assoc [symmetric] mult_def)\napply (erule trancl_trans)\napply (rule r_into_trancl)\napply (simp add: mult1_def set_of_def)\napply (rule_tac x = a in exI)\napply (rule_tac x = \"I + J'\" in exI)\napply (simp add: ac_simps)\ndone\n\nlemma one_step_implies_mult:\n  \"trans r ==> J \\<noteq> {#} ==> \\<forall>k \\<in> set_of K. \\<exists>j \\<in> set_of J. (k, j) \\<in> r\n    ==> (I + K, I + J) \\<in> mult r\"\nusing one_step_implies_mult_aux by blast\n\n\nsubsubsection {* Partial-order properties *}\n\ndefinition less_multiset :: \"'a\\<Colon>order multiset \\<Rightarrow> 'a multiset \\<Rightarrow> bool\" (infix \"<#\" 50) where\n  \"M' <# M \\<longleftrightarrow> (M', M) \\<in> mult {(x', x). x' < x}\"\n\ndefinition le_multiset :: \"'a\\<Colon>order multiset \\<Rightarrow> 'a multiset \\<Rightarrow> bool\" (infix \"<=#\" 50) where\n  \"M' <=# M \\<longleftrightarrow> M' <# M \\<or> M' = M\"\n\nnotation (xsymbols) less_multiset (infix \"\\<subset>#\" 50)\nnotation (xsymbols) le_multiset (infix \"\\<subseteq>#\" 50)\n\ninterpretation multiset_order: order le_multiset less_multiset\nproof -\n  have irrefl: \"\\<And>M :: 'a multiset. \\<not> M \\<subset># M\"\n  proof\n    fix M :: \"'a multiset\"\n    assume \"M \\<subset># M\"\n    then have MM: \"(M, M) \\<in> mult {(x, y). x < y}\" by (simp add: less_multiset_def)\n    have \"trans {(x'::'a, x). x' < x}\"\n      by (rule transI) simp\n    moreover note MM\n    ultimately have \"\\<exists>I J K. M = I + J \\<and> M = I + K\n      \\<and> J \\<noteq> {#} \\<and> (\\<forall>k\\<in>set_of K. \\<exists>j\\<in>set_of J. (k, j) \\<in> {(x, y). x < y})\"\n      by (rule mult_implies_one_step)\n    then obtain I J K where \"M = I + J\" and \"M = I + K\"\n      and \"J \\<noteq> {#}\" and \"(\\<forall>k\\<in>set_of K. \\<exists>j\\<in>set_of J. (k, j) \\<in> {(x, y). x < y})\" by blast\n    then have aux1: \"K \\<noteq> {#}\" and aux2: \"\\<forall>k\\<in>set_of K. \\<exists>j\\<in>set_of K. k < j\" by auto\n    have \"finite (set_of K)\" by simp\n    moreover note aux2\n    ultimately have \"set_of K = {}\"\n      by (induct rule: finite_induct) (auto intro: order_less_trans)\n    with aux1 show False by simp\n  qed\n  have trans: \"\\<And>K M N :: 'a multiset. K \\<subset># M \\<Longrightarrow> M \\<subset># N \\<Longrightarrow> K \\<subset># N\"\n    unfolding less_multiset_def mult_def by (blast intro: trancl_trans)\n  show \"class.order (le_multiset :: 'a multiset \\<Rightarrow> _) less_multiset\"\n    by default (auto simp add: le_multiset_def irrefl dest: trans)\nqed\n\nlemma mult_less_irrefl [elim!]: \"M \\<subset># (M::'a::order multiset) ==> R\"\n  by simp\n\n\nsubsubsection {* Monotonicity of multiset union *}\n\nlemma mult1_union: \"(B, D) \\<in> mult1 r ==> (C + B, C + D) \\<in> mult1 r\"\napply (unfold mult1_def)\napply auto\napply (rule_tac x = a in exI)\napply (rule_tac x = \"C + M0\" in exI)\napply (simp add: add.assoc)\ndone\n\nlemma union_less_mono2: \"B \\<subset># D ==> C + B \\<subset># C + (D::'a::order multiset)\"\napply (unfold less_multiset_def mult_def)\napply (erule trancl_induct)\n apply (blast intro: mult1_union)\napply (blast intro: mult1_union trancl_trans)\ndone\n\nlemma union_less_mono1: \"B \\<subset># D ==> B + C \\<subset># D + (C::'a::order multiset)\"\napply (subst add.commute [of B C])\napply (subst add.commute [of D C])\napply (erule union_less_mono2)\ndone\n\nlemma union_less_mono:\n  \"A \\<subset># C ==> B \\<subset># D ==> A + B \\<subset># C + (D::'a::order multiset)\"\n  by (blast intro!: union_less_mono1 union_less_mono2 multiset_order.less_trans)\n\ninterpretation multiset_order: ordered_ab_semigroup_add plus le_multiset less_multiset\nproof\nqed (auto simp add: le_multiset_def intro: union_less_mono2)\n\n\nsubsection {* Termination proofs with multiset orders *}\n\nlemma multi_member_skip: \"x \\<in># XS \\<Longrightarrow> x \\<in># {# y #} + XS\"\n  and multi_member_this: \"x \\<in># {# x #} + XS\"\n  and multi_member_last: \"x \\<in># {# x #}\"\n  by auto\n\ndefinition \"ms_strict = mult pair_less\"\ndefinition \"ms_weak = ms_strict \\<union> Id\"\n\nlemma ms_reduction_pair: \"reduction_pair (ms_strict, ms_weak)\"\nunfolding reduction_pair_def ms_strict_def ms_weak_def pair_less_def\nby (auto intro: wf_mult1 wf_trancl simp: mult_def)\n\nlemma smsI:\n  \"(set_of A, set_of B) \\<in> max_strict \\<Longrightarrow> (Z + A, Z + B) \\<in> ms_strict\"\n  unfolding ms_strict_def\nby (rule one_step_implies_mult) (auto simp add: max_strict_def pair_less_def elim!:max_ext.cases)\n\nlemma wmsI:\n  \"(set_of A, set_of B) \\<in> max_strict \\<or> A = {#} \\<and> B = {#}\n  \\<Longrightarrow> (Z + A, Z + B) \\<in> ms_weak\"\nunfolding ms_weak_def ms_strict_def\nby (auto simp add: pair_less_def max_strict_def elim!:max_ext.cases intro: one_step_implies_mult)\n\ninductive pw_leq\nwhere\n  pw_leq_empty: \"pw_leq {#} {#}\"\n| pw_leq_step:  \"\\<lbrakk>(x,y) \\<in> pair_leq; pw_leq X Y \\<rbrakk> \\<Longrightarrow> pw_leq ({#x#} + X) ({#y#} + Y)\"\n\nlemma pw_leq_lstep:\n  \"(x, y) \\<in> pair_leq \\<Longrightarrow> pw_leq {#x#} {#y#}\"\nby (drule pw_leq_step) (rule pw_leq_empty, simp)\n\nlemma pw_leq_split:\n  assumes \"pw_leq X Y\"\n  shows \"\\<exists>A B Z. X = A + Z \\<and> Y = B + Z \\<and> ((set_of A, set_of B) \\<in> max_strict \\<or> (B = {#} \\<and> A = {#}))\"\n  using assms\nproof (induct)\n  case pw_leq_empty thus ?case by auto\nnext\n  case (pw_leq_step x y X Y)\n  then obtain A B Z where\n    [simp]: \"X = A + Z\" \"Y = B + Z\"\n      and 1[simp]: \"(set_of A, set_of B) \\<in> max_strict \\<or> (B = {#} \\<and> A = {#})\"\n    by auto\n  from pw_leq_step have \"x = y \\<or> (x, y) \\<in> pair_less\"\n    unfolding pair_leq_def by auto\n  thus ?case\n  proof\n    assume [simp]: \"x = y\"\n    have\n      \"{#x#} + X = A + ({#y#}+Z)\n      \\<and> {#y#} + Y = B + ({#y#}+Z)\n      \\<and> ((set_of A, set_of B) \\<in> max_strict \\<or> (B = {#} \\<and> A = {#}))\"\n      by (auto simp: ac_simps)\n    thus ?case by (intro exI)\n  next\n    assume A: \"(x, y) \\<in> pair_less\"\n    let ?A' = \"{#x#} + A\" and ?B' = \"{#y#} + B\"\n    have \"{#x#} + X = ?A' + Z\"\n      \"{#y#} + Y = ?B' + Z\"\n      by (auto simp add: ac_simps)\n    moreover have\n      \"(set_of ?A', set_of ?B') \\<in> max_strict\"\n      using 1 A unfolding max_strict_def\n      by (auto elim!: max_ext.cases)\n    ultimately show ?thesis by blast\n  qed\nqed\n\nlemma\n  assumes pwleq: \"pw_leq Z Z'\"\n  shows ms_strictI: \"(set_of A, set_of B) \\<in> max_strict \\<Longrightarrow> (Z + A, Z' + B) \\<in> ms_strict\"\n  and   ms_weakI1:  \"(set_of A, set_of B) \\<in> max_strict \\<Longrightarrow> (Z + A, Z' + B) \\<in> ms_weak\"\n  and   ms_weakI2:  \"(Z + {#}, Z' + {#}) \\<in> ms_weak\"\nproof -\n  from pw_leq_split[OF pwleq]\n  obtain A' B' Z''\n    where [simp]: \"Z = A' + Z''\" \"Z' = B' + Z''\"\n    and mx_or_empty: \"(set_of A', set_of B') \\<in> max_strict \\<or> (A' = {#} \\<and> B' = {#})\"\n    by blast\n  {\n    assume max: \"(set_of A, set_of B) \\<in> max_strict\"\n    from mx_or_empty\n    have \"(Z'' + (A + A'), Z'' + (B + B')) \\<in> ms_strict\"\n    proof\n      assume max': \"(set_of A', set_of B') \\<in> max_strict\"\n      with max have \"(set_of (A + A'), set_of (B + B')) \\<in> max_strict\"\n        by (auto simp: max_strict_def intro: max_ext_additive)\n      thus ?thesis by (rule smsI)\n    next\n      assume [simp]: \"A' = {#} \\<and> B' = {#}\"\n      show ?thesis by (rule smsI) (auto intro: max)\n    qed\n    thus \"(Z + A, Z' + B) \\<in> ms_strict\" by (simp add:ac_simps)\n    thus \"(Z + A, Z' + B) \\<in> ms_weak\" by (simp add: ms_weak_def)\n  }\n  from mx_or_empty\n  have \"(Z'' + A', Z'' + B') \\<in> ms_weak\" by (rule wmsI)\n  thus \"(Z + {#}, Z' + {#}) \\<in> ms_weak\" by (simp add:ac_simps)\nqed\n\nlemma empty_neutral: \"{#} + x = x\" \"x + {#} = x\"\nand nonempty_plus: \"{# x #} + rs \\<noteq> {#}\"\nand nonempty_single: \"{# x #} \\<noteq> {#}\"\nby auto\n\nsetup {*\nlet\n  fun msetT T = Type (@{type_name multiset}, [T]);\n\n  fun mk_mset T [] = Const (@{const_abbrev Mempty}, msetT T)\n    | mk_mset T [x] = Const (@{const_name single}, T --> msetT T) $ x\n    | mk_mset T (x :: xs) =\n          Const (@{const_name plus}, msetT T --> msetT T --> msetT T) $\n                mk_mset T [x] $ mk_mset T xs\n\n  fun mset_member_tac m i =\n      (if m <= 0 then\n           rtac @{thm multi_member_this} i ORELSE rtac @{thm multi_member_last} i\n       else\n           rtac @{thm multi_member_skip} i THEN mset_member_tac (m - 1) i)\n\n  val mset_nonempty_tac =\n      rtac @{thm nonempty_plus} ORELSE' rtac @{thm nonempty_single}\n\n  val regroup_munion_conv =\n      Function_Lib.regroup_conv @{const_abbrev Mempty} @{const_name plus}\n        (map (fn t => t RS eq_reflection) (@{thms ac_simps} @ @{thms empty_neutral}))\n\n  fun unfold_pwleq_tac i =\n    (rtac @{thm pw_leq_step} i THEN (fn st => unfold_pwleq_tac (i + 1) st))\n      ORELSE (rtac @{thm pw_leq_lstep} i)\n      ORELSE (rtac @{thm pw_leq_empty} i)\n\n  val set_of_simps = [@{thm set_of_empty}, @{thm set_of_single}, @{thm set_of_union},\n                      @{thm Un_insert_left}, @{thm Un_empty_left}]\nin\n  ScnpReconstruct.multiset_setup (ScnpReconstruct.Multiset\n  {\n    msetT=msetT, mk_mset=mk_mset, mset_regroup_conv=regroup_munion_conv,\n    mset_member_tac=mset_member_tac, mset_nonempty_tac=mset_nonempty_tac,\n    mset_pwleq_tac=unfold_pwleq_tac, set_of_simps=set_of_simps,\n    smsI'= @{thm ms_strictI}, wmsI2''= @{thm ms_weakI2}, wmsI1= @{thm ms_weakI1},\n    reduction_pair= @{thm ms_reduction_pair}\n  })\nend\n*}\n\n\nsubsection {* Legacy theorem bindings *}\n\nlemmas multi_count_eq = multiset_eq_iff [symmetric]\n\nlemma union_commute: \"M + N = N + (M::'a multiset)\"\n  by (fact add.commute)\n\nlemma union_assoc: \"(M + N) + K = M + (N + (K::'a multiset))\"\n  by (fact add.assoc)\n\nlemma union_lcomm: \"M + (N + K) = N + (M + (K::'a multiset))\"\n  by (fact add.left_commute)\n\nlemmas union_ac = union_assoc union_commute union_lcomm\n\nlemma union_right_cancel: \"M + K = N + K \\<longleftrightarrow> M = (N::'a multiset)\"\n  by (fact add_right_cancel)\n\nlemma union_left_cancel: \"K + M = K + N \\<longleftrightarrow> M = (N::'a multiset)\"\n  by (fact add_left_cancel)\n\nlemma multi_union_self_other_eq: \"(A::'a multiset) + X = A + Y \\<Longrightarrow> X = Y\"\n  by (fact add_imp_eq)\n\nlemma mset_less_trans: \"(M::'a multiset) < K \\<Longrightarrow> K < N \\<Longrightarrow> M < N\"\n  by (fact order_less_trans)\n\nlemma multiset_inter_commute: \"A #\\<inter> B = B #\\<inter> A\"\n  by (fact inf.commute)\n\nlemma multiset_inter_assoc: \"A #\\<inter> (B #\\<inter> C) = A #\\<inter> B #\\<inter> C\"\n  by (fact inf.assoc [symmetric])\n\nlemma multiset_inter_left_commute: \"A #\\<inter> (B #\\<inter> C) = B #\\<inter> (A #\\<inter> C)\"\n  by (fact inf.left_commute)\n\nlemmas multiset_inter_ac =\n  multiset_inter_commute\n  multiset_inter_assoc\n  multiset_inter_left_commute\n\nlemma mult_less_not_refl:\n  \"\\<not> M \\<subset># (M::'a::order multiset)\"\n  by (fact multiset_order.less_irrefl)\n\nlemma mult_less_trans:\n  \"K \\<subset># M ==> M \\<subset># N ==> K \\<subset># (N::'a::order multiset)\"\n  by (fact multiset_order.less_trans)\n\nlemma mult_less_not_sym:\n  \"M \\<subset># N ==> \\<not> N \\<subset># (M::'a::order multiset)\"\n  by (fact multiset_order.less_not_sym)\n\nlemma mult_less_asym:\n  \"M \\<subset># N ==> (\\<not> P ==> N \\<subset># (M::'a::order multiset)) ==> P\"\n  by (fact multiset_order.less_asym)\n\nML {*\nfun multiset_postproc _ maybe_name all_values (T as Type (_, [elem_T]))\n                      (Const _ $ t') =\n    let\n      val (maybe_opt, ps) =\n        Nitpick_Model.dest_plain_fun t' ||> op ~~\n        ||> map (apsnd (snd o HOLogic.dest_number))\n      fun elems_for t =\n        case AList.lookup (op =) ps t of\n          SOME n => replicate n t\n        | NONE => [Const (maybe_name, elem_T --> elem_T) $ t]\n    in\n      case maps elems_for (all_values elem_T) @\n           (if maybe_opt then [Const (Nitpick_Model.unrep (), elem_T)]\n            else []) of\n        [] => Const (@{const_name zero_class.zero}, T)\n      | ts => foldl1 (fn (t1, t2) =>\n                         Const (@{const_name plus_class.plus}, T --> T --> T)\n                         $ t1 $ t2)\n                     (map (curry (op $) (Const (@{const_name single},\n                                                elem_T --> T))) ts)\n    end\n  | multiset_postproc _ _ _ _ t = t\n*}\n\ndeclaration {*\nNitpick_Model.register_term_postprocessor @{typ \"'a multiset\"}\n    multiset_postproc\n*}\n\nhide_const (open) fold\n\n\nsubsection {* Naive implementation using lists *}\n\ncode_datatype multiset_of\n\n\n\nlemma [code]:\n  \"{#x#} = multiset_of [x]\"\n  by simp\n\nlemma union_code [code]:\n  \"multiset_of xs + multiset_of ys = multiset_of (xs @ ys)\"\n  by simp\n\nlemma [code]:\n  \"image_mset f (multiset_of xs) = multiset_of (map f xs)\"\n  by (simp add: multiset_of_map)\n\nlemma [code]:\n  \"Multiset.filter f (multiset_of xs) = multiset_of (filter f xs)\"\n  by (simp add: multiset_of_filter)\n\nlemma [code]:\n  \"multiset_of xs - multiset_of ys = multiset_of (fold remove1 ys xs)\"\n  by (rule sym, induct ys arbitrary: xs) (simp_all add: diff_add diff_right_commute)\n\nlemma [code]:\n  \"multiset_of xs #\\<inter> multiset_of ys =\n    multiset_of (snd (fold (\\<lambda>x (ys, zs).\n      if x \\<in> set ys then (remove1 x ys, x # zs) else (ys, zs)) xs (ys, [])))\"\nproof -\n  have \"\\<And>zs. multiset_of (snd (fold (\\<lambda>x (ys, zs).\n    if x \\<in> set ys then (remove1 x ys, x # zs) else (ys, zs)) xs (ys, zs))) =\n      (multiset_of xs #\\<inter> multiset_of ys) + multiset_of zs\"\n    by (induct xs arbitrary: ys)\n      (auto simp add: mem_set_multiset_eq inter_add_right1 inter_add_right2 ac_simps)\n  then show ?thesis by simp\nqed\n\nlemma [code]:\n  \"multiset_of xs #\\<union> multiset_of ys =\n    multiset_of (split append (fold (\\<lambda>x (ys, zs). (remove1 x ys, x # zs)) xs (ys, [])))\"\nproof -\n  have \"\\<And>zs. multiset_of (split append (fold (\\<lambda>x (ys, zs). (remove1 x ys, x # zs)) xs (ys, zs))) =\n      (multiset_of xs #\\<union> multiset_of ys) + multiset_of zs\"\n    by (induct xs arbitrary: ys) (simp_all add: multiset_eq_iff)\n  then show ?thesis by simp\nqed\n\nlemma [code_unfold]:\n  \"x \\<in># multiset_of xs \\<longleftrightarrow> x \\<in> set xs\"\n  by (simp add: in_multiset_of)\n\nlemma [code]:\n  \"count (multiset_of xs) x = fold (\\<lambda>y. if x = y then Suc else id) xs 0\"\nproof -\n  have \"\\<And>n. fold (\\<lambda>y. if x = y then Suc else id) xs n = count (multiset_of xs) x + n\"\n    by (induct xs) simp_all\n  then show ?thesis by simp\nqed\n\nlemma [code]:\n  \"set_of (multiset_of xs) = set xs\"\n  by simp\n\nlemma [code]:\n  \"sorted_list_of_multiset (multiset_of xs) = sort xs\"\n  by (induct xs) simp_all\n\nlemma [code]: -- {* not very efficient, but representation-ignorant! *}\n  \"multiset_of_set A = multiset_of (sorted_list_of_set A)\"\n  apply (cases \"finite A\")\n  apply simp_all\n  apply (induct A rule: finite_induct)\n  apply (simp_all add: union_commute)\n  done\n\nlemma [code]:\n  \"mcard (multiset_of xs) = length xs\"\n  by (simp add: mcard_multiset_of)\n\nfun ms_lesseq_impl :: \"'a list \\<Rightarrow> 'a list \\<Rightarrow> bool option\" where\n  \"ms_lesseq_impl [] ys = Some (ys \\<noteq> [])\"\n| \"ms_lesseq_impl (Cons x xs) ys = (case List.extract (op = x) ys of\n     None \\<Rightarrow> None\n   | Some (ys1,_,ys2) \\<Rightarrow> ms_lesseq_impl xs (ys1 @ ys2))\"\n\nlemma ms_lesseq_impl: \"(ms_lesseq_impl xs ys = None \\<longleftrightarrow> \\<not> multiset_of xs \\<le> multiset_of ys) \\<and>\n  (ms_lesseq_impl xs ys = Some True \\<longleftrightarrow> multiset_of xs < multiset_of ys) \\<and>\n  (ms_lesseq_impl xs ys = Some False \\<longrightarrow> multiset_of xs = multiset_of ys)\"\nproof (induct xs arbitrary: ys)\n  case (Nil ys)\n  show ?case by (auto simp: mset_less_empty_nonempty)\nnext\n  case (Cons x xs ys)\n  show ?case\n  proof (cases \"List.extract (op = x) ys\")\n    case None\n    hence x: \"x \\<notin> set ys\" by (simp add: extract_None_iff)\n    {\n      assume \"multiset_of (x # xs) \\<le> multiset_of ys\"\n      from set_of_mono[OF this] x have False by simp\n    } note nle = this\n    moreover\n    {\n      assume \"multiset_of (x # xs) < multiset_of ys\"\n      hence \"multiset_of (x # xs) \\<le> multiset_of ys\" by auto\n      from nle[OF this] have False .\n    }\n    ultimately show ?thesis using None by auto\n  next\n    case (Some res)\n    obtain ys1 y ys2 where res: \"res = (ys1,y,ys2)\" by (cases res, auto)\n    note Some = Some[unfolded res]\n    from extract_SomeE[OF Some] have \"ys = ys1 @ x # ys2\" by simp\n    hence id: \"multiset_of ys = multiset_of (ys1 @ ys2) + {#x#}\"\n      by (auto simp: ac_simps)\n    show ?thesis unfolding ms_lesseq_impl.simps\n      unfolding Some option.simps split\n      unfolding id\n      using Cons[of \"ys1 @ ys2\"]\n      unfolding mset_le_def mset_less_def by auto\n  qed\nqed\n\nlemma [code]: \"multiset_of xs \\<le> multiset_of ys \\<longleftrightarrow> ms_lesseq_impl xs ys \\<noteq> None\"\n  using ms_lesseq_impl[of xs ys] by (cases \"ms_lesseq_impl xs ys\", auto)\n\nlemma [code]: \"multiset_of xs < multiset_of ys \\<longleftrightarrow> ms_lesseq_impl xs ys = Some True\"\n  using ms_lesseq_impl[of xs ys] by (cases \"ms_lesseq_impl xs ys\", auto)\n\ninstantiation multiset :: (equal) equal\nbegin\n\ndefinition\n  [code del]: \"HOL.equal A (B :: 'a multiset) \\<longleftrightarrow> A = B\"\nlemma [code]: \"HOL.equal (multiset_of xs) (multiset_of ys) \\<longleftrightarrow> ms_lesseq_impl xs ys = Some False\"\n  unfolding equal_multiset_def\n  using ms_lesseq_impl[of xs ys] by (cases \"ms_lesseq_impl xs ys\", auto)\n\ninstance\n  by default (simp add: equal_multiset_def)\nend\n\nlemma [code]:\n  \"msetsum (multiset_of xs) = listsum xs\"\n  by (induct xs) (simp_all add: add.commute)\n\nlemma [code]:\n  \"msetprod (multiset_of xs) = fold times xs 1\"\nproof -\n  have \"\\<And>x. fold times xs x = msetprod (multiset_of xs) * x\"\n    by (induct xs) (simp_all add: mult.assoc)\n  then show ?thesis by simp\nqed\n\nlemma [code]:\n  \"size = mcard\"\n  by (fact size_eq_mcard)\n\ntext {*\n  Exercise for the casual reader: add implementations for @{const le_multiset}\n  and @{const less_multiset} (multiset order).\n*}\n\ntext {* Quickcheck generators *}\n\ndefinition (in term_syntax)\n  msetify :: \"'a\\<Colon>typerep list \\<times> (unit \\<Rightarrow> Code_Evaluation.term)\n    \\<Rightarrow> 'a multiset \\<times> (unit \\<Rightarrow> Code_Evaluation.term)\" where\n  [code_unfold]: \"msetify xs = Code_Evaluation.valtermify multiset_of {\\<cdot>} xs\"\n\nnotation fcomp (infixl \"\\<circ>>\" 60)\nnotation scomp (infixl \"\\<circ>\\<rightarrow>\" 60)\n\ninstantiation multiset :: (random) random\nbegin\n\ndefinition\n  \"Quickcheck_Random.random i = Quickcheck_Random.random i \\<circ>\\<rightarrow> (\\<lambda>xs. Pair (msetify xs))\"\n\ninstance ..\n\nend\n\nno_notation fcomp (infixl \"\\<circ>>\" 60)\nno_notation scomp (infixl \"\\<circ>\\<rightarrow>\" 60)\n\ninstantiation multiset :: (full_exhaustive) full_exhaustive\nbegin\n\ndefinition full_exhaustive_multiset :: \"('a multiset \\<times> (unit \\<Rightarrow> term) \\<Rightarrow> (bool \\<times> term list) option) \\<Rightarrow> natural \\<Rightarrow> (bool \\<times> term list) option\"\nwhere\n  \"full_exhaustive_multiset f i = Quickcheck_Exhaustive.full_exhaustive (\\<lambda>xs. f (msetify xs)) i\"\n\ninstance ..\n\nend\n\nhide_const (open) msetify\n\n\nsubsection {* BNF setup *}\n\ndefinition rel_mset where\n  \"rel_mset R X Y \\<longleftrightarrow> (\\<exists>xs ys. multiset_of xs = X \\<and> multiset_of ys = Y \\<and> list_all2 R xs ys)\"\n\nlemma multiset_of_zip_take_Cons_drop_twice:\n  assumes \"length xs = length ys\" \"j \\<le> length xs\"\n  shows \"multiset_of (zip (take j xs @ x # drop j xs) (take j ys @ y # drop j ys)) =\n    multiset_of (zip xs ys) + {#(x, y)#}\"\nusing assms\nproof (induct xs ys arbitrary: x y j rule: list_induct2)\n  case Nil\n  thus ?case\n    by simp\nnext\n  case (Cons x xs y ys)\n  thus ?case\n  proof (cases \"j = 0\")\n    case True\n    thus ?thesis\n      by simp\n  next\n    case False\n    then obtain k where k: \"j = Suc k\"\n      by (case_tac j) simp\n    hence \"k \\<le> length xs\"\n      using Cons.prems by auto\n    hence \"multiset_of (zip (take k xs @ x # drop k xs) (take k ys @ y # drop k ys)) =\n      multiset_of (zip xs ys) + {#(x, y)#}\"\n      by (rule Cons.hyps(2))\n    thus ?thesis\n      unfolding k by (auto simp: add.commute union_lcomm)\n  qed\nqed\n\nlemma ex_multiset_of_zip_left:\n  assumes \"length xs = length ys\" \"multiset_of xs' = multiset_of xs\"\n  shows \"\\<exists>ys'. length ys' = length xs' \\<and> multiset_of (zip xs' ys') = multiset_of (zip xs ys)\"\nusing assms\nproof (induct xs ys arbitrary: xs' rule: list_induct2)\n  case Nil\n  thus ?case\n    by auto\nnext\n  case (Cons x xs y ys xs')\n  obtain j where j_len: \"j < length xs'\" and nth_j: \"xs' ! j = x\"\n    by (metis Cons.prems in_set_conv_nth list.set_intros(1) multiset_of_eq_setD)\n\n  def xsa \\<equiv> \"take j xs' @ drop (Suc j) xs'\"\n  have \"multiset_of xs' = {#x#} + multiset_of xsa\"\n    unfolding xsa_def using j_len nth_j\n    by (metis (no_types) ab_semigroup_add_class.add_ac(1) append_take_drop_id Cons_nth_drop_Suc\n      multiset_of.simps(2) union_code union_commute)\n  hence ms_x: \"multiset_of xsa = multiset_of xs\"\n    by (metis Cons.prems add.commute add_right_imp_eq multiset_of.simps(2))\n  then obtain ysa where\n    len_a: \"length ysa = length xsa\" and ms_a: \"multiset_of (zip xsa ysa) = multiset_of (zip xs ys)\"\n    using Cons.hyps(2) by blast\n\n  def ys' \\<equiv> \"take j ysa @ y # drop j ysa\"\n  have xs': \"xs' = take j xsa @ x # drop j xsa\"\n    using ms_x j_len nth_j Cons.prems xsa_def\n    by (metis append_eq_append_conv append_take_drop_id diff_Suc_Suc Cons_nth_drop_Suc length_Cons\n      length_drop mcard_multiset_of)\n  have j_len': \"j \\<le> length xsa\"\n    using j_len xs' xsa_def\n    by (metis add_Suc_right append_take_drop_id length_Cons length_append less_eq_Suc_le not_less)\n  have \"length ys' = length xs'\"\n    unfolding ys'_def using Cons.prems len_a ms_x\n    by (metis add_Suc_right append_take_drop_id length_Cons length_append multiset_of_eq_length)\n  moreover have \"multiset_of (zip xs' ys') = multiset_of (zip (x # xs) (y # ys))\"\n    unfolding xs' ys'_def\n    by (rule trans[OF multiset_of_zip_take_Cons_drop_twice])\n      (auto simp: len_a ms_a j_len' add.commute)\n  ultimately show ?case\n    by blast\nqed\n\nlemma list_all2_reorder_left_invariance:\n  assumes rel: \"list_all2 R xs ys\" and ms_x: \"multiset_of xs' = multiset_of xs\"\n  shows \"\\<exists>ys'. list_all2 R xs' ys' \\<and> multiset_of ys' = multiset_of ys\"\nproof -\n  have len: \"length xs = length ys\"\n    using rel list_all2_conv_all_nth by auto\n  obtain ys' where\n    len': \"length xs' = length ys'\" and ms_xy: \"multiset_of (zip xs' ys') = multiset_of (zip xs ys)\"\n    using len ms_x by (metis ex_multiset_of_zip_left)\n  have \"list_all2 R xs' ys'\"\n    using assms(1) len' ms_xy unfolding list_all2_iff by (blast dest: multiset_of_eq_setD)\n  moreover have \"multiset_of ys' = multiset_of ys\"\n    using len len' ms_xy map_snd_zip multiset_of_map by metis\n  ultimately show ?thesis\n    by blast\nqed\n\nlemma ex_multiset_of: \"\\<exists>xs. multiset_of xs = X\"\n  by (induct X) (simp, metis multiset_of.simps(2))\n\nbnf \"'a multiset\"\n  map: image_mset\n  sets: set_of\n  bd: natLeq\n  wits: \"{#}\"\n  rel: rel_mset\nproof -\n  show \"image_mset id = id\"\n    by (rule image_mset.id)\nnext\n  show \"\\<And>f g. image_mset (g \\<circ> f) = image_mset g \\<circ> image_mset f\"\n    unfolding comp_def by (rule ext) (simp add: image_mset.compositionality comp_def)\nnext\n  fix X :: \"'a multiset\"\n  show \"\\<And>f g. (\\<And>z. z \\<in> set_of X \\<Longrightarrow> f z = g z) \\<Longrightarrow> image_mset f X = image_mset g X\"\n    by (induct X, (simp (no_asm))+,\n      metis One_nat_def Un_iff count_single mem_set_of_iff set_of_union zero_less_Suc)\nnext\n  show \"\\<And>f. set_of \\<circ> image_mset f = op ` f \\<circ> set_of\"\n    by auto\nnext\n  show \"card_order natLeq\"\n    by (rule natLeq_card_order)\nnext\n  show \"BNF_Cardinal_Arithmetic.cinfinite natLeq\"\n    by (rule natLeq_cinfinite)\nnext\n  show \"\\<And>X. ordLeq3 (card_of (set_of X)) natLeq\"\n    by transfer\n      (auto intro!: ordLess_imp_ordLeq simp: finite_iff_ordLess_natLeq[symmetric] multiset_def)\nnext\n  show \"\\<And>R S. rel_mset R OO rel_mset S \\<le> rel_mset (R OO S)\"\n    unfolding rel_mset_def[abs_def] OO_def\n    apply clarify\n    apply (rename_tac X Z Y xs ys' ys zs)\n    apply (drule_tac xs = ys' and ys = zs and xs' = ys in list_all2_reorder_left_invariance)\n    by (auto intro: list_all2_trans)\nnext\n  show \"\\<And>R. rel_mset R =\n    (BNF_Def.Grp {x. set_of x \\<subseteq> {(x, y). R x y}} (image_mset fst))\\<inverse>\\<inverse> OO\n    BNF_Def.Grp {x. set_of x \\<subseteq> {(x, y). R x y}} (image_mset snd)\"\n    unfolding rel_mset_def[abs_def] BNF_Def.Grp_def OO_def\n    apply (rule ext)+\n    apply auto\n     apply (rule_tac x = \"multiset_of (zip xs ys)\" in exI)\n     apply auto[1]\n        apply (metis list_all2_lengthD map_fst_zip multiset_of_map)\n       apply (auto simp: list_all2_iff)[1]\n      apply (metis list_all2_lengthD map_snd_zip multiset_of_map)\n     apply (auto simp: list_all2_iff)[1]\n    apply (rename_tac XY)\n    apply (cut_tac X = XY in ex_multiset_of)\n    apply (erule exE)\n    apply (rename_tac xys)\n    apply (rule_tac x = \"map fst xys\" in exI)\n    apply (auto simp: multiset_of_map)\n    apply (rule_tac x = \"map snd xys\" in exI)\n    by (auto simp: multiset_of_map list_all2I subset_eq zip_map_fst_snd)\nnext\n  show \"\\<And>z. z \\<in> set_of {#} \\<Longrightarrow> False\"\n    by auto\nqed\n\ninductive rel_mset' where\n  Zero[intro]: \"rel_mset' R {#} {#}\"\n| Plus[intro]: \"\\<lbrakk>R a b; rel_mset' R M N\\<rbrakk> \\<Longrightarrow> rel_mset' R (M + {#a#}) (N + {#b#})\"\n\nlemma rel_mset_Zero: \"rel_mset R {#} {#}\"\nunfolding rel_mset_def Grp_def by auto\n\ndeclare multiset.count[simp]\ndeclare Abs_multiset_inverse[simp]\ndeclare multiset.count_inverse[simp]\ndeclare union_preserves_multiset[simp]\n\nlemma rel_mset_Plus:\nassumes ab: \"R a b\" and MN: \"rel_mset R M N\"\nshows \"rel_mset R (M + {#a#}) (N + {#b#})\"\nproof-\n  {fix y assume \"R a b\" and \"set_of y \\<subseteq> {(x, y). R x y}\"\n   hence \"\\<exists>ya. image_mset fst y + {#a#} = image_mset fst ya \\<and>\n               image_mset snd y + {#b#} = image_mset snd ya \\<and>\n               set_of ya \\<subseteq> {(x, y). R x y}\"\n   apply(intro exI[of _ \"y + {#(a,b)#}\"]) by auto\n  }\n  thus ?thesis\n  using assms\n  unfolding multiset.rel_compp_Grp Grp_def by blast\nqed\n\nlemma rel_mset'_imp_rel_mset:\n\"rel_mset' R M N \\<Longrightarrow> rel_mset R M N\"\napply(induct rule: rel_mset'.induct)\nusing rel_mset_Zero rel_mset_Plus by auto\n\nlemma mcard_image_mset[simp]: \"mcard (image_mset f M) = mcard M\"\n  unfolding size_eq_mcard[symmetric] by (rule size_image_mset)\n\nlemma rel_mset_mcard:\n  assumes \"rel_mset R M N\"\n  shows \"mcard M = mcard N\"\nusing assms unfolding multiset.rel_compp_Grp Grp_def by auto\n\nlemma multiset_induct2[case_names empty addL addR]:\nassumes empty: \"P {#} {#}\"\nand addL: \"\\<And>M N a. P M N \\<Longrightarrow> P (M + {#a#}) N\"\nand addR: \"\\<And>M N a. P M N \\<Longrightarrow> P M (N + {#a#})\"\nshows \"P M N\"\napply(induct N rule: multiset_induct)\n  apply(induct M rule: multiset_induct, rule empty, erule addL)\n  apply(induct M rule: multiset_induct, erule addR, erule addR)\ndone\n\nlemma multiset_induct2_mcard[consumes 1, case_names empty add]:\nassumes c: \"mcard M = mcard N\"\nand empty: \"P {#} {#}\"\nand add: \"\\<And>M N a b. P M N \\<Longrightarrow> P (M + {#a#}) (N + {#b#})\"\nshows \"P M N\"\nusing c proof(induct M arbitrary: N rule: measure_induct_rule[of mcard])\n  case (less M)  show ?case\n  proof(cases \"M = {#}\")\n    case True hence \"N = {#}\" using less.prems by auto\n    thus ?thesis using True empty by auto\n  next\n    case False then obtain M1 a where M: \"M = M1 + {#a#}\" by (metis multi_nonempty_split)\n    have \"N \\<noteq> {#}\" using False less.prems by auto\n    then obtain N1 b where N: \"N = N1 + {#b#}\" by (metis multi_nonempty_split)\n    have \"mcard M1 = mcard N1\" using less.prems unfolding M N by auto\n    thus ?thesis using M N less.hyps add by auto\n  qed\nqed\n\nlemma msed_map_invL:\nassumes \"image_mset f (M + {#a#}) = N\"\nshows \"\\<exists>N1. N = N1 + {#f a#} \\<and> image_mset f M = N1\"\nproof-\n  have \"f a \\<in># N\"\n  using assms multiset.set_map[of f \"M + {#a#}\"] by auto\n  then obtain N1 where N: \"N = N1 + {#f a#}\" using multi_member_split by metis\n  have \"image_mset f M = N1\" using assms unfolding N by simp\n  thus ?thesis using N by blast\nqed\n\nlemma msed_map_invR:\nassumes \"image_mset f M = N + {#b#}\"\nshows \"\\<exists>M1 a. M = M1 + {#a#} \\<and> f a = b \\<and> image_mset f M1 = N\"\nproof-\n  obtain a where a: \"a \\<in># M\" and fa: \"f a = b\"\n  using multiset.set_map[of f M] unfolding assms\n  by (metis image_iff mem_set_of_iff union_single_eq_member)\n  then obtain M1 where M: \"M = M1 + {#a#}\" using multi_member_split by metis\n  have \"image_mset f M1 = N\" using assms unfolding M fa[symmetric] by simp\n  thus ?thesis using M fa by blast\nqed\n\nlemma msed_rel_invL:\nassumes \"rel_mset R (M + {#a#}) N\"\nshows \"\\<exists>N1 b. N = N1 + {#b#} \\<and> R a b \\<and> rel_mset R M N1\"\nproof-\n  obtain K where KM: \"image_mset fst K = M + {#a#}\"\n  and KN: \"image_mset snd K = N\" and sK: \"set_of K \\<subseteq> {(a, b). R a b}\"\n  using assms\n  unfolding multiset.rel_compp_Grp Grp_def by auto\n  obtain K1 ab where K: \"K = K1 + {#ab#}\" and a: \"fst ab = a\"\n  and K1M: \"image_mset fst K1 = M\" using msed_map_invR[OF KM] by auto\n  obtain N1 where N: \"N = N1 + {#snd ab#}\" and K1N1: \"image_mset snd K1 = N1\"\n  using msed_map_invL[OF KN[unfolded K]] by auto\n  have Rab: \"R a (snd ab)\" using sK a unfolding K by auto\n  have \"rel_mset R M N1\" using sK K1M K1N1\n  unfolding K multiset.rel_compp_Grp Grp_def by auto\n  thus ?thesis using N Rab by auto\nqed\n\nlemma msed_rel_invR:\nassumes \"rel_mset R M (N + {#b#})\"\nshows \"\\<exists>M1 a. M = M1 + {#a#} \\<and> R a b \\<and> rel_mset R M1 N\"\nproof-\n  obtain K where KN: \"image_mset snd K = N + {#b#}\"\n  and KM: \"image_mset fst K = M\" and sK: \"set_of K \\<subseteq> {(a, b). R a b}\"\n  using assms\n  unfolding multiset.rel_compp_Grp Grp_def by auto\n  obtain K1 ab where K: \"K = K1 + {#ab#}\" and b: \"snd ab = b\"\n  and K1N: \"image_mset snd K1 = N\" using msed_map_invR[OF KN] by auto\n  obtain M1 where M: \"M = M1 + {#fst ab#}\" and K1M1: \"image_mset fst K1 = M1\"\n  using msed_map_invL[OF KM[unfolded K]] by auto\n  have Rab: \"R (fst ab) b\" using sK b unfolding K by auto\n  have \"rel_mset R M1 N\" using sK K1N K1M1\n  unfolding K multiset.rel_compp_Grp Grp_def by auto\n  thus ?thesis using M Rab by auto\nqed\n\nlemma rel_mset_imp_rel_mset':\nassumes \"rel_mset R M N\"\nshows \"rel_mset' R M N\"\nusing assms proof(induct M arbitrary: N rule: measure_induct_rule[of mcard])\n  case (less M)\n  have c: \"mcard M = mcard N\" using rel_mset_mcard[OF less.prems] .\n  show ?case\n  proof(cases \"M = {#}\")\n    case True hence \"N = {#}\" using c by simp\n    thus ?thesis using True rel_mset'.Zero by auto\n  next\n    case False then obtain M1 a where M: \"M = M1 + {#a#}\" by (metis multi_nonempty_split)\n    obtain N1 b where N: \"N = N1 + {#b#}\" and R: \"R a b\" and ms: \"rel_mset R M1 N1\"\n    using msed_rel_invL[OF less.prems[unfolded M]] by auto\n    have \"rel_mset' R M1 N1\" using less.hyps[of M1 N1] ms unfolding M by simp\n    thus ?thesis using rel_mset'.Plus[of R a b, OF R] unfolding M N by simp\n  qed\nqed\n\nlemma rel_mset_rel_mset':\n\"rel_mset R M N = rel_mset' R M N\"\nusing rel_mset_imp_rel_mset' rel_mset'_imp_rel_mset by auto\n\n(* The main end product for rel_mset: inductive characterization *)\ntheorems rel_mset_induct[case_names empty add, induct pred: rel_mset] =\n         rel_mset'.induct[unfolded rel_mset_rel_mset'[symmetric]]\n\n\nsubsection {* Size setup *}\n\nlemma multiset_size_o_map: \"size_multiset g \\<circ> image_mset f = size_multiset (g \\<circ> f)\"\n  unfolding o_apply by (rule ext) (induct_tac, auto)\n\nsetup {*\nBNF_LFP_Size.register_size_global @{type_name multiset} @{const_name size_multiset}\n  @{thms size_multiset_empty size_multiset_single size_multiset_union size_empty size_single\n    size_union}\n  @{thms multiset_size_o_map}\n*}\n\nhide_const (open) wcount\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/Multiset.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127566694178, "lm_q2_score": 0.8459424334245618, "lm_q1q2_score": 0.7223610353092029}}
{"text": "(*  Title:      HOL/Lattice/Orders.thy\n    Author:     Markus Wenzel, TU Muenchen\n*)\n\nsection \\<open>Orders\\<close>\n\ntheory Orders imports MainRLT begin\n\nsubsection \\<open>Ordered structures\\<close>\n\ntext \\<open>\n  We define several classes of ordered structures over some type \\<^typ>\\<open>'a\\<close> 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>\\<open>dual\\<close> and \\<^term>\\<open>undual\\<close> 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>\\<open>dual\\<close> (and \\<^term>\\<open>undual\\<close>) 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": "dtraytel", "repo": "HOLRLT", "sha": "e9029da59bb3af0c835604a65308498f9696a364", "save_path": "github-repos/isabelle/dtraytel-HOLRLT", "path": "github-repos/isabelle/dtraytel-HOLRLT/HOLRLT-e9029da59bb3af0c835604a65308498f9696a364/HOLRLT/Lattice/Orders.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8539127417985637, "lm_q2_score": 0.8459424373085146, "lm_q1q2_score": 0.7223610260458733}}
{"text": "theory Uniswap\n  imports Phi_Semantics.PhiSem_Machine_Integer\n          Phi_Semantics.PhiSem_CF_Basic\n          Phi_Semantics.PhiSem_Variable HOL.Transcendental\nbegin\n\nconsts Tick  :: \\<open>(VAL, int) \\<phi>\\<close>\n       Price :: \\<open>(VAL, real) \\<phi>\\<close>\n\ndefinition \\<open>FACTOR = (1.0001::real)\\<close>\n\nlemma FACTOR_LG_1: \\<open>1 < FACTOR\\<close> unfolding FACTOR_def by simp\n\ndefinition price_of :: \\<open>int \\<Rightarrow> real\\<close>\n  where price_of_def': \\<open>price_of tick = sqrt (FACTOR powr (of_int tick))\\<close>\n\nlemma price_of_def: \\<open>price_of t = FACTOR powr (of_int t / 2)\\<close>\n  unfolding price_of_def'\n  by (simp add: powr_half_sqrt[symmetric] powr_powr)\n\nhide_fact price_of_def'\n\nlemma price_of_mono': \\<open>mono price_of\\<close>\n  unfolding price_of_def mono_on_def\n  by (simp add: FACTOR_LG_1)\n\nlemma price_of_smono': \\<open>strict_mono price_of\\<close>\n  unfolding price_of_def strict_mono_on_def\n  by (simp add: FACTOR_LG_1)\n\nlemma price_of_mono:\n  \\<open>price_of x \\<le> price_of y \\<longleftrightarrow> x \\<le> y\\<close>\n  using price_of_mono'\n  by (simp add: price_of_smono' strict_mono_less_eq) \n\nlemma price_of_smono:\n  \\<open>price_of x < price_of y \\<longleftrightarrow> x < y\\<close>\n  using price_of_smono' using strict_mono_less by blast\n\ndefinition \\<open>tick_of_price p = (@t. price_of t \\<le> p \\<and> p < price_of (t+1)) \\<close>\n\nlemma tick_of_price: \\<open>tick_of_price (price_of t) = t\\<close>\n  unfolding tick_of_price_def\n  by (smt (z3) price_of_smono some_eq_imp)\n\nlemma price_of_tick:\n  assumes \\<open>0 < p\\<close>\n  shows \\<open>price_of (tick_of_price p) \\<le> p \\<and> p < price_of (tick_of_price p + 1)\\<close>\nproof -\n  have \\<open>\\<exists>t. p < FACTOR powr t\\<close>\n    by (metis FACTOR_LG_1 dual_order.strict_trans floor_log_eq_powr_iff linorder_neqE_linordered_idom zero_less_one)\n  then have \\<open>\\<exists>t. p < price_of t\\<close>\n    unfolding price_of_def\n    by (meson FACTOR_LG_1 dual_order.strict_trans ex_less_of_int less_divide_eq_numeral1(1) powr_less_cancel_iff)\n  moreover have \\<open>\\<exists>t. FACTOR powr t \\<le> p\\<close>\n    using \\<open>0 < p\\<close> FACTOR_LG_1 floor_log_eq_powr_iff by blast\n  then have \\<open>\\<exists>t. price_of t \\<le> p\\<close>\n    proof -\n      have \\<open>\\<And>x. \\<exists>t. real_of_int t / 2 < x\\<close> by (simp add: ex_of_int_less)\n      then show ?thesis\n      unfolding price_of_def\n      by (meson FACTOR_LG_1 \\<open>\\<exists>t. FACTOR powr t \\<le> p\\<close> dual_order.trans less_le_not_le powr_le_cancel_iff)\n    qed\n  ultimately have X: \\<open>(\\<exists>t. price_of t \\<le> p \\<and> p < price_of (t+1))\\<close>\n    proof -\n    obtain t1 where t1: \\<open>price_of t1 \\<le> p\\<close> using \\<open>\\<exists>t. price_of t \\<le> p\\<close> by blast\n    obtain t2 where t2: \\<open>p < price_of t2\\<close> using \\<open>\\<exists>t. p < price_of t\\<close> by blast\n    have le: \\<open>t1 < t2\\<close> using t1 t2 price_of_smono by fastforce\n    thm int_gr_induct[OF le]\n    have \\<open>p < price_of t2 \\<longrightarrow> ?thesis\\<close>\n    proof (induct rule: int_gr_induct[OF le])\n      case 1\n      then show ?case\n        using t1 by blast\n    next\n      case (2 i)\n      then show ?case\n        by force\n    qed\n    then show ?thesis\n      using t2 by blast\n  qed\n  then show ?thesis\n    unfolding tick_of_price_def\n    by (metis (no_types, lifting) someI_ex)\nqed\n\n\ndebt_axiomatization getSqrtRatioAtTick :: \\<open>(VAL,VAL) proc'\\<close>\n  where getSqrtRatioAtTick_\\<phi>app:\n            \\<open>\\<p>\\<r>\\<o>\\<c> getSqrtRatioAtTick v \\<lbrace> t \\<Ztypecolon> \\<v>\\<a>\\<l>[v] Tick \\<longmapsto> price_of t \\<Ztypecolon> \\<v>\\<a>\\<l> Price \\<rbrace>\\<close>\n    and getTickAtSqrtRatio_\\<phi>app:\n            \\<open>\\<p>\\<r>\\<e>\\<m>\\<i>\\<s>\\<e> 0 < p\n         \\<Longrightarrow> \\<p>\\<r>\\<o>\\<c> getTickAtSqrtRatio v \\<lbrace> p \\<Ztypecolon> \\<v>\\<a>\\<l>[v] Price \\<longmapsto> tick_of_price p \\<Ztypecolon> \\<v>\\<a>\\<l> Tick \\<rbrace>\\<close>\n\nrecord tick_info =\n  liquidityGross :: nat\n  liquidityNet   :: int\n  feeGrowthOutside0X128 :: nat\n  feeGrowthOutside1X128 :: nat\n  tickCumulativeOutside :: int\n  secondsPerLiquidityOutsideX128 :: nat\n  secondsOutside :: nat\n  initialized :: bool\n\ndefinition \\<open>growth_Inv f f' delta current =\n  (\\<forall>(i::int). f i = (if i \\<le> current then (sum f' {j. j \\<le> i}) + delta i\n                             else (sum f' {j. i < j}) - delta i))\\<close>\n  \n\nterm sum\n\n\ndebt_axiomatization TickInfos :: \\<open>(assn, int \\<Rightarrow> tick_info nonsepable option) \\<phi>\\<close>\n  where TickInfos_mult: \\<open>(f1 \\<Ztypecolon> TickInfos) * (f2 \\<Ztypecolon> TickInfos) = (f1 * f2 \\<Ztypecolon> TickInfos)\\<close>\n          \\<comment> \\<open>Separation of Abstraction ?! cool! \\<close>\n\nthm TickInfos_mult\n\ndefinition TickInfo\n\n\ndebt_axiomatization get_TickInfo :: \\<open>(VAL,VAL) proc'\\<close>\n  where getSqrtRatioAtTick_\\<phi>app:\n            \\<open>\\<p>\\<r>\\<o>\\<c> getSqrtRatioAtTick v \\<lbrace> t \\<Ztypecolon> \\<v>\\<a>\\<l>[v] Tick \\<longmapsto> price_of t \\<Ztypecolon> \\<v>\\<a>\\<l> Price \\<rbrace>\\<close>\n    and getTickAtSqrtRatio_\\<phi>app:\n            \\<open>\\<p>\\<r>\\<e>\\<m>\\<i>\\<s>\\<e> 0 < p\n         \\<Longrightarrow> \\<p>\\<r>\\<o>\\<c> getTickAtSqrtRatio v \\<lbrace> p \\<Ztypecolon> \\<v>\\<a>\\<l>[v] Price \\<longmapsto> tick_of_price p \\<Ztypecolon> \\<v>\\<a>\\<l> Tick \\<rbrace>\\<close>\n\n\ndefinition \\<open>Ticks = (\\<lambda>info. into \\<Ztypecolon> TickInfo' \\<s>\\<u>\\<b>\\<j>  )\\<close>\n\n\nend", "meta": {"author": "xqyww123", "repo": "Uniswap_v", "sha": "8ac4e6e29b5a0b95b68120e3188b2c34d8ee8e0c", "save_path": "github-repos/isabelle/xqyww123-Uniswap_v", "path": "github-repos/isabelle/xqyww123-Uniswap_v/Uniswap_v-8ac4e6e29b5a0b95b68120e3188b2c34d8ee8e0c/Uniswap.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248191350352, "lm_q2_score": 0.7690802423634961, "lm_q1q2_score": 0.722185435485711}}
{"text": "\\<^marker>\\<open>creator Florian Ke\u00dfler\\<close>\n\nsection \"IMP- Max Constant\"\n\ntheory Max_Constant \n  imports \"Small_StepT\" \nbegin\n\ntext \\<open>We define functions to derive the constant with the highest value and enumerate all variables \n  in IMP- programs. \\<close>\n\nfun atomExp_to_constant:: \"atomExp \\<Rightarrow> nat\" where\n\"atomExp_to_constant (V var) = 0\" |\n\"atomExp_to_constant (N val) = val\"\n\nfun aexp_max_constant:: \"AExp.aexp \\<Rightarrow> nat\" where\n\"aexp_max_constant (A a) = atomExp_to_constant a\" |\n\"aexp_max_constant (Plus a b) = max (atomExp_to_constant a) (atomExp_to_constant b)\" |\n\"aexp_max_constant (Sub a b) = max (atomExp_to_constant a) (atomExp_to_constant b)\" |\n\"aexp_max_constant (Parity a) = atomExp_to_constant a\" | \n\"aexp_max_constant (RightShift a) = atomExp_to_constant a\"\n\nfun max_constant :: \"com \\<Rightarrow> nat\" where\n\"max_constant (SKIP) = 0\" |\n\"max_constant (Assign vname aexp) = aexp_max_constant aexp\" |\n\"max_constant (Seq c1  c2) = max (max_constant c1) (max_constant c2)\" |         \n\"max_constant (If  _ c1 c2) = max (max_constant c1) (max_constant c2)\"  |   \n\"max_constant (While _ c) = max_constant c\"\n\nlemma max_constant_not_increasing_step:\n  \"(c1, s1) \\<rightarrow> (c2, s2) \\<Longrightarrow> max_constant c2 \\<le> max_constant c1\"\n  by (induction c1 s1 c2 s2 rule: small_step_induct) auto\n\nlemma Max_range_le_then_element_le: \"finite (range s) \\<Longrightarrow> 2 * Max (range s) < (x :: nat) \\<Longrightarrow> 2 * (s y) < x\" \nproof -\n  assume \"2 * Max (range s) < (x :: nat)\"\n  moreover have \"s y \\<in> range s\" by simp\n  moreover assume \"finite (range s)\" \n  moreover hence \"s y \\<le> Max (range s)\" by simp\n  ultimately show ?thesis by linarith\nqed\n\nlemma aval_le_when: \n  assumes \"finite (range s)\" \"2 * max (Max (range s)) (aexp_max_constant a) < x\" \n  shows \"AExp.aval a s < x\"\nusing assms proof(cases a)\n  case (A x1)\n  thus ?thesis using assms\n  proof(cases x1)\n    case (V x2)\n    thus ?thesis using assms A Max_range_le_then_element_le[where ?s=s and ?x = x and ?y=x2] by simp\n  qed simp\nnext\n  case (Plus x21 x22)\n  hence \"2 * max (AExp.atomVal x21 s) (AExp.atomVal x22 s) < x\" \n    apply(cases x21; cases x22)\n    using assms \n    by (auto simp add: Max_range_le_then_element_le nat_mult_max_right)\n  thus ?thesis using Plus by auto\nnext\n  case (Sub x31 x32)\n  then show ?thesis \n    apply(cases x31 ; cases x32)\n    using assms apply(auto simp add: Max_range_le_then_element_le nat_mult_max_right)\n    using Max_range_le_then_element_le \n    by (metis gr_implies_not0 lessI less_imp_diff_less less_imp_le_nat less_le_trans \n        linorder_neqE_nat n_less_m_mult_n numeral_2_eq_2)+\nnext\n  case (Parity x4)\n  then show ?thesis apply(cases x4) \n    using assms Max_range_le_then_element_le[OF \\<open>finite (range s)\\<close>, where ?x=x] \n    apply(auto simp: algebra_simps)\n    by (metis One_nat_def Suc_lessI less_Suc_eq less_one mod_mult_self1_is_0 mult_eq_0_iff\n        neq0_conv not_mod_2_eq_0_eq_1 numeral_2_eq_2)\nnext\n  case (RightShift x5)\n  then show ?thesis \n    apply(cases x5) \n    using assms Max_range_le_then_element_le[OF \\<open>finite (range s)\\<close>, where ?x=x] \n    apply(auto simp: algebra_simps)\n    by (metis less_mult_imp_div_less max.strict_coboundedI1 max_0_1 max_less_iff_conj \n        mult_numeral_1_right nat_mult_max_right one_eq_numeral_iff)\nqed\n\nfun atomExp_var:: \"atomExp \\<Rightarrow> vname list\" where\n\"atomExp_var (V var) = [ var ]\" |\n\"atomExp_var (N val) = []\"\n\nfun aexp_vars:: \"AExp.aexp \\<Rightarrow> vname list\" where\n\"aexp_vars (A a) = atomExp_var a\" |\n\"aexp_vars (Plus a b) = (atomExp_var a) @ (atomExp_var b)\" |\n\"aexp_vars (Sub a b) = (atomExp_var a) @ (atomExp_var b)\" |\n\"aexp_vars (Parity a) = atomExp_var a\" |\n\"aexp_vars (RightShift a) = atomExp_var a\"\n\nfun all_variables :: \"com \\<Rightarrow> vname list\" where\n\"all_variables (SKIP) = []\" |\n\"all_variables (Assign v aexp) = v # aexp_vars aexp\" |\n\"all_variables (Seq c1 c2) = all_variables c1 @ all_variables c2\" |\n\"all_variables (If v c1 c2) = [ v ] @ all_variables c1 @ all_variables c2\" |\n\"all_variables (While v c) = [ v ] @ all_variables c\"\n\ndefinition num_variables:: \"com \\<Rightarrow> nat\" where\n\"num_variables c = length (remdups (all_variables c))\" \n\nlemma all_variables_subset_step: \"(c1, s1) \\<rightarrow> (c2, s2) \n  \\<Longrightarrow> set (all_variables c2) \\<subseteq> set (all_variables c1)\" \n  apply(induction c1 s1 c2 s2 rule: small_step_induct)\n  by auto\n\nlemma subset_then_length_remdups_le: \"set as \\<subseteq> set bs\n  \\<Longrightarrow> length (remdups (as @ cs)) \\<le> length (remdups (bs @ cs))\" \n  apply(induction cs)\n   apply (auto simp: card_mono length_remdups_card_conv)\n  by (metis (no_types, lifting) List.finite_set Un_insert_right card_mono dual_order.trans \n      finite.insertI finite_Un sup.boundedI sup.cobounded1 sup.cobounded2)\n\nlemma num_variables_not_increasing_step: \"(c1, s1) \\<rightarrow> (c2, s2) \n  \\<Longrightarrow> num_variables c2 \\<le> num_variables c1\" \n  apply(induction c1 s1 c2 s2 rule: small_step_induct)\n  using subset_then_length_remdups_le[OF all_variables_subset_step] \n        apply(auto simp: num_variables_def length_remdups_card_conv)\n        apply (meson List.finite_set card_mono finite_Un sup.cobounded1 sup.cobounded2 le_SucI)+\n  by (simp add: insert_absorb)\n\nlemma num_variables_not_increasing: \"(c1, s1) \\<rightarrow>\\<^bsup> t \\<^esup> (c2, s2)\n  \\<Longrightarrow> num_variables c2 \\<le> num_variables c1\" \nproof (induction t arbitrary: c1 s1)\n  case (Suc t)\n  then obtain c3 s3 where \"(c1, s1) \\<rightarrow> (c3, s3)\" \"(c3, s3) \\<rightarrow>\\<^bsup> t \\<^esup> (c2, s2)\"\n    by auto\n  then show ?case\n    using num_variables_not_increasing_step[OF \\<open>(c1, s1) \\<rightarrow> (c3, s3)\\<close>] \n      Suc.IH[OF \\<open>(c3, s3) \\<rightarrow>\\<^bsup> t \\<^esup> (c2, s2)\\<close>]\n    by simp\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-/Max_Constant.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9019206870747657, "lm_q2_score": 0.8006920068519376, "lm_q1q2_score": 0.7221606849551726}}
{"text": "theory Boolean_Expression_Example\nimports Boolean_Expression_Checkers\nbegin\n\nsection{* Example *}\n\ntext {* Example usage of checkers. We have our own type of boolean expressions\nwith its own evaluation function: *}\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\ntext{* Now we translate into the datatype provided by the checkers interface\nand show that the semantics remains the same: *}\n\nfun bool_expr_of_bexp :: \"'a bexp \\<Rightarrow> 'a bool_expr\" where\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: \"val_bool_expr(bool_expr_of_bexp b) s = bval b s\"\nby(induction b) auto\n\ntext{* Trivial tautology checker and its correctness: *}\n\ndefinition \"my_taut_test = taut_test o bool_expr_of_bexp\"\n\ncorollary my_taut_test: \"my_taut_test b = (\\<forall>s. bval b s)\"\nby(simp add: my_taut_test_def val_preservation taut_test)\n\n\ntext{* Test: pigeonhole formulas *}\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]]\"\n\ndefinition \"nc n = ands[Or (Neg(Atom(i,k))) (Neg(Atom(j,k))).\n  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{* Takes about 5 secs; with 7 instead of 6 it takes about 4 mins (2014). *}\nlemma \"my_taut_test (php 6)\"\nby eval\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/Boolean_Expression_Checkers/Boolean_Expression_Example.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206659843132, "lm_q2_score": 0.8006920020959544, "lm_q1q2_score": 0.7221606637786963}}
{"text": "theory triangleInequality\n  imports Complex_Main\nbegin\n\ntheorem triangle_inequality:\n  fixes x y :: real\n  shows \"abs x + abs y \u2265 abs(x + y)\"\nproof cases\n  {\n    assume xGreater: \"x \u2265 0\"\n    show ?thesis proof cases\n      {\n        assume yGreater: \"y \u2265 0\"\n        show ?thesis by simp\n      next      \n        assume yLess: \"\u00ac(y \u2265 0)\"\n        show ?thesis by simp\n      }\n    qed\n\n  next\n    assume xLess: \"\u00ac(x \u2265 0)\"\n    show ?thesis proof cases\n      {\n        assume yGreater: \"y \u2265 0\"\n        show ?thesis by simp\n      next\n        assume yLess: \"\u00ac(y \u2265 0)\"\n        show ?thesis by simp\n      }\n    qed\n  }\nqed\n\nend\n\n\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/triangleInequality.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970842359877, "lm_q2_score": 0.8198933381139645, "lm_q1q2_score": 0.7221596615952907}}
{"text": "header \"A Typed Language\"\n\ntheory hw08_tmpl imports \"~~/src/HOL/IMP/Star\" begin\n\nsubsection \"Expressions\"\n\ndatatype val = Iv int | Bv bool\n\ntype_synonym vname = string\ntype_synonym state = \"vname \\<Rightarrow> val\"\n\ndatatype exp =  N int | V vname | Plus exp exp |\n  Bc bool | Not exp | And exp exp | Less exp exp\n\ninductive eval :: \"exp \\<Rightarrow> state \\<Rightarrow> val \\<Rightarrow> bool\" where\n\"eval (N i) s (Iv i)\" |\n\"eval (V x) s (s x)\" |\n\"eval a1 s (Iv i1) \\<Longrightarrow> eval a2 s (Iv i2)\n \\<Longrightarrow> eval (Plus a1 a2) s (Iv(i1+i2))\" |\n\"eval (Bc v) s (Bv v)\" |\n\"eval b s (Bv bv) \\<Longrightarrow> eval (Not b) s (Bv(\\<not> bv))\" |\n\"eval b1 s (Bv bv1) \\<Longrightarrow> eval b2 s (Bv bv2) \\<Longrightarrow> eval (And b1 b2) s (Bv(bv1 & bv2))\" |\n\"eval a1 s (Iv i1) \\<Longrightarrow> eval a2 s (Iv i2) \\<Longrightarrow> eval (Less a1 a2) s (Bv(i1 < i2))\"\n\ninductive_cases [elim!]:\n  \"eval (N i) s v\"\n  \"eval (V x) s v\"\n  \"eval (Plus a1 a2) s v\"\n  \"eval (Bc b) s v\"\n  \"eval (Not b) s v\"\n  \"eval (And b1 b2) s v\"\n  \"eval (Less a1 a2) s v\"\n\nsubsection \"Syntax of Commands\"\n(* a copy of Com.thy - keep in sync! *)\n\ndatatype\n  com = SKIP \n      | Assign vname exp       (\"_ ::= _\" [1000, 61] 61)\n      | Seq    com  com         (\"_;; _\"  [60, 61] 60)\n      | If     exp com com     (\"IF _ THEN _ ELSE _\"  [0, 0, 61] 61)\n      | While  exp com         (\"WHILE _ DO _\"  [0, 61] 61)\n\n\nsubsection \"Small-Step Semantics of Commands\"\n\ninductive\n  small_step :: \"(com \\<times> state) \\<Rightarrow> (com \\<times> state) \\<Rightarrow> bool\" (infix \"\\<rightarrow>\" 55)\nwhere\nAssign:  \"eval a s v \\<Longrightarrow> (x ::= a, s) \\<rightarrow> (SKIP, s(x := v))\" |\n\nSeq1:   \"(SKIP;;c,s) \\<rightarrow> (c,s)\" |\nSeq2:   \"(c1,s) \\<rightarrow> (c1',s') \\<Longrightarrow> (c1;;c2,s) \\<rightarrow> (c1';;c2,s')\" |\n\nIfTrue:  \"eval b s (Bv True) \\<Longrightarrow> (IF b THEN c1 ELSE c2,s) \\<rightarrow> (c1,s)\" |\nIfFalse: \"eval b s (Bv False) \\<Longrightarrow> (IF b THEN c1 ELSE c2,s) \\<rightarrow> (c2,s)\" |\n\nWhile:   \"(WHILE b DO c,s) \\<rightarrow> (IF b THEN c;; WHILE b DO c ELSE SKIP,s)\"\n\nlemmas small_step_induct = small_step.induct[split_format(complete)]\n\nsubsection \"The Type System\"\n\ndatatype ty = Ity | Bty\n\ntype_synonym tyenv = \"vname \\<Rightarrow> ty\"\n\ninductive etyping :: \"tyenv \\<Rightarrow> exp \\<Rightarrow> ty \\<Rightarrow> bool\"\n  (\"(1_/ \\<turnstile>/ (_ :/ _))\" [50,0,50] 50)\nwhere\nIc_ty: \"\\<Gamma> \\<turnstile> N i : Ity\" |\nV_ty: \"\\<Gamma> \\<turnstile> V x : \\<Gamma> x\" |\nPlus_ty: \"\\<Gamma> \\<turnstile> a1 : Ity \\<Longrightarrow> \\<Gamma> \\<turnstile> a2 : Ity \\<Longrightarrow> \\<Gamma> \\<turnstile> Plus a1 a2 : Ity\" |\nB_ty: \"\\<Gamma> \\<turnstile> Bc v : Bty\" |\nNot_ty: \"\\<Gamma> \\<turnstile> b : Bty \\<Longrightarrow> \\<Gamma> \\<turnstile> Not b : Bty\" |\nAnd_ty: \"\\<Gamma> \\<turnstile> b1 : Bty \\<Longrightarrow> \\<Gamma> \\<turnstile> b2 : Bty \\<Longrightarrow> \\<Gamma> \\<turnstile> And b1 b2 : Bty\" |\nLess_ty: \"\\<Gamma> \\<turnstile> a1 : Ity \\<Longrightarrow> \\<Gamma> \\<turnstile> a2 : Ity \\<Longrightarrow> \\<Gamma> \\<turnstile> Less a1 a2 : Bty\"\n\ninductive ctyping :: \"tyenv \\<Rightarrow> com \\<Rightarrow> bool\" (infix \"\\<turnstile>\" 50) where\nSkip_ty: \"\\<Gamma> \\<turnstile> SKIP\" |\nAssign_ty: \"\\<Gamma> \\<turnstile> a : \\<Gamma>(x) \\<Longrightarrow> \\<Gamma> \\<turnstile> x ::= a\" |\nSeq_ty: \"\\<Gamma> \\<turnstile> c1 \\<Longrightarrow> \\<Gamma> \\<turnstile> c2 \\<Longrightarrow> \\<Gamma> \\<turnstile> c1;;c2\" |\nIf_ty: \"\\<Gamma> \\<turnstile> b : Bty \\<Longrightarrow> \\<Gamma> \\<turnstile> c1 \\<Longrightarrow> \\<Gamma> \\<turnstile> c2 \\<Longrightarrow> \\<Gamma> \\<turnstile> IF b THEN c1 ELSE c2\" |\nWhile_ty: \"\\<Gamma> \\<turnstile> b : Bty \\<Longrightarrow> \\<Gamma> \\<turnstile> c \\<Longrightarrow> \\<Gamma> \\<turnstile> WHILE b DO c\"\n\ninductive_cases [elim!]:\n  \"\\<Gamma> \\<turnstile> x ::= a\"  \"\\<Gamma> \\<turnstile> c1;;c2\"\n  \"\\<Gamma> \\<turnstile> IF b THEN c1 ELSE c2\"\n  \"\\<Gamma> \\<turnstile> WHILE b DO c\"\n\nsubsection \"Well-typed Programs Do Not Get Stuck\"\n\nfun type :: \"val \\<Rightarrow> ty\" where\n\"type (Iv i) = Ity\" |\n\"type (Bv r) = Bty\"\n\nlemma type_eq_Ity[simp]: \"type v = Ity \\<longleftrightarrow> (\\<exists>i. v = Iv i)\"\nby (cases v) simp_all\n\nlemma type_eq_Bty[simp]: \"type v = Bty \\<longleftrightarrow> (\\<exists>r. v = Bv r)\"\nby (cases v) simp_all\n\ndefinition styping :: \"tyenv \\<Rightarrow> state \\<Rightarrow> bool\" (infix \"\\<turnstile>\" 50)\nwhere \"\\<Gamma> \\<turnstile> s  \\<longleftrightarrow>  (\\<forall>x. type (s x) = \\<Gamma> x)\"\n\nlemma epreservation:\n  \"\\<Gamma> \\<turnstile> a : \\<tau> \\<Longrightarrow> eval a s v \\<Longrightarrow> \\<Gamma> \\<turnstile> s \\<Longrightarrow> type v = \\<tau>\"\noops\n\nlemma eprogress: \"\\<Gamma> \\<turnstile> a : \\<tau> \\<Longrightarrow> \\<Gamma> \\<turnstile> s \\<Longrightarrow> \\<exists>v. eval a s v\"\noops\n\ntheorem progress:\n  \"\\<Gamma> \\<turnstile> c \\<Longrightarrow> \\<Gamma> \\<turnstile> s \\<Longrightarrow> c \\<noteq> SKIP \\<Longrightarrow> \\<exists>cs'. (c,s) \\<rightarrow> cs'\"\noops\n\ntheorem styping_preservation:\n  \"(c,s) \\<rightarrow> (c',s') \\<Longrightarrow> \\<Gamma> \\<turnstile> c \\<Longrightarrow> \\<Gamma> \\<turnstile> s \\<Longrightarrow> \\<Gamma> \\<turnstile> s'\"\noops\n\ntheorem ctyping_preservation:\n  \"(c,s) \\<rightarrow> (c',s') \\<Longrightarrow> \\<Gamma> \\<turnstile> c \\<Longrightarrow> \\<Gamma> \\<turnstile> c'\"\noops\n\nabbreviation small_steps :: \"com * state \\<Rightarrow> com * state \\<Rightarrow> bool\" (infix \"\\<rightarrow>*\" 55)\nwhere \"x \\<rightarrow>* y == star small_step x y\"\n\ntheorem type_sound:\n  \"(c,s) \\<rightarrow>* (c',s') \\<Longrightarrow> \\<Gamma> \\<turnstile> c \\<Longrightarrow> \\<Gamma> \\<turnstile> s \\<Longrightarrow> c' \\<noteq> SKIP\n   \\<Longrightarrow> \\<exists>cs''. (c',s') \\<rightarrow> cs''\"\noops\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/Exercise8/hw08_tmpl.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8807970748488297, "lm_q2_score": 0.819893340314393, "lm_q1q2_score": 0.7221596558369534}}
{"text": "header {* Polynomials\\label{sec.poly.ext} *}\n\ntheory Polynomial_extension\nimports\n  Main\n  \"~~/src/HOL/Library/Permutations\"\n  \"~~/src/HOL/Library/Polynomial\"  \nbegin\n\ntext{* This theory contains auxiliary lemmas on polynomials. *}\n\nlemma degree_setprod_le: \"degree (\\<Prod>i\\<in>S. f i) \\<le> (\\<Sum>i\\<in>S. degree (f i))\"\n  apply(cases \"finite S\")\n  apply(simp_all)\n  apply(induct rule: finite_induct)\n  apply(simp_all)\n  apply(metis (lifting) degree_mult_le dual_order.trans nat_add_left_cancel_le)\n  done\n\nlemma coeff_mult_sum: \"degree p \\<le> m \\<Longrightarrow> \n                       degree q \\<le> n \\<Longrightarrow> coeff (p * q) (m + n) = coeff p m * coeff q n\"\n  apply(insert coeff_mult_degree_sum[of p q] coeff_eq_0[of q n] coeff_eq_0[of p m] \n               degree_mult_le[of p q] coeff_eq_0[of \"p*q\" \"m + n\"])\n  apply(cases \"degree p = m \\<and> degree q = n\")\n  apply(simp) \n  apply(cases \"degree p < m\")\n  apply(simp_all)\n  done\n\nlemma coeff_mult_setprod_setsum:\n  \"coeff (\\<Prod>i\\<in>S. f i) (\\<Sum>i\\<in>S. degree (f i)) = (\\<Prod>i\\<in>S. coeff (f i) (degree (f i)))\"\n  apply(cases \"finite S\")\n  apply(induct rule: finite_induct)\n  apply(simp_all add: coeff_mult_sum degree_setprod_le)\n  done\n\nlemma degree_setsum_smaller:\n  assumes \"n > 0\" \"finite A\"\n  shows \" \\<forall>x\\<in>A. degree (f x) < n \\<Longrightarrow> degree (\\<Sum>x\\<in>A. f x) < n\" \n  using `finite A`\n  by(induct rule: finite_induct)\n    (simp_all add: degree_add_less assms)\n\nlemma degree_setsum_le:\n  assumes \"finite A\"\n  shows \" \\<forall>x\\<in>A. degree (f x) \\<le> n \\<Longrightarrow> degree (\\<Sum>x\\<in>A. f x) \\<le> n\"\n  using `finite A`\n  by(induct rule: finite_induct)\n    (auto intro!: degree_add_le)\n\nlemma degree_setsum_le_max:\n  fixes F :: \"('n::finite \\<Rightarrow> 'n) set\" and f :: \"_ \\<Rightarrow> 'a::comm_ring_1 poly\"\n  shows \"degree (setsum f F) \\<le> Max { degree (f p) | p. p\\<in>F}\"\n  by(intro degree_setsum_le)\n    (auto intro!: Max.coboundedI)\n\nlemma degree_smaller:\n  assumes \"n > 0\"\n  shows \"degree (\\<Sum>x::nat | x < n . monom (coeff (f x) x) x) < n\"\n  using assms degree_monom_le\n  apply(auto intro!: degree_setsum_smaller)\n  apply(subst le_less_trans[where z=n])\n  apply(auto)\n  done\n\nlemma poly_as_sum_of_monoms: \"(\\<Sum>x\\<le>degree a . monom (coeff a x) x) = a\"\nproof-\n  have eq: \"\\<And>n. {.. degree a} \\<inter> {n} = (if n \\<le> degree a then {n} else {})\"\n    by auto\n  show ?thesis  \n    by(simp add: poly_eq_iff coeff_setsum setsum.If_cases eq coeff_eq_0)\nqed\n\nlemma poly_euclidean_division: \n  assumes \"degree a > 0\"\n  shows \"\\<exists> b :: 'a. \\<exists> a'\\<in>{ x::('a::comm_ring_1 poly) . degree x < degree a}.    \n         a = monom b (degree a) + a'\"\nproof-\n  have \"a = (\\<Sum>x\\<le>degree a . monom (coeff a x) x)\" \n    using poly_as_sum_of_monoms[of a] by auto\n  also have \"\\<dots> = (\\<Sum>x\\<in>{degree a}\\<union>{..< degree a} . monom (coeff a x) x)\" \n    unfolding sup.commute using ivl_disj_un_singleton(2) by (metis calculation)\n  finally have \"a = (\\<Sum>x\\<in>{degree a} . monom (coeff a x) x) \n                  + (\\<Sum>x<degree a . monom (coeff a x) x)\"\n    by simp\n  also have \"degree (\\<Sum>x<degree a . monom (coeff a x) x) < degree a\"\n    using assms degree_monom_le le_less_trans\n    by(auto intro!: degree_setsum_smaller) (blast)\n  ultimately show ?thesis\n    by auto\nqed \n\nlemma sign_permut: \"\\<And>p q. degree (of_int (sign p) * q) = degree q\" \n  by(simp add: sign_def)\n\nlemma monom_poly_degree_one: \"degree(monom 1 (Suc 0) - [: a::'a::comm_ring_1 :]) = (Suc 0)\"\n  by(simp add: monom_0 monom_Suc)\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/Polynomial_extension.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213718636754, "lm_q2_score": 0.803173801068221, "lm_q1q2_score": 0.7221507298614216}}
{"text": "section \\<open> Fixed-points and Recursion \\<close>\n\ntheory utp_recursion\n  imports \n    utp_pred_laws\n    utp_rel\nbegin\n\nsubsection \\<open> Fixed-point Laws \\<close>\n  \nlemma mu_id: \"(\\<mu> X \\<bullet> X) = true\"\n  by (simp add: antisym gfp_upperbound)\n\nlemma mu_const: \"(\\<mu> X \\<bullet> P) = P\"\n  by (simp add: gfp_const)\n\nlemma nu_id: \"(\\<nu> X \\<bullet> X) = false\"                                                            \n  by (meson lfp_lowerbound utp_pred_laws.bot.extremum_unique)\n\nlemma nu_const: \"(\\<nu> X \\<bullet> P) = P\"\n  by (simp add: lfp_const)\n\nlemma mu_refine_intro:\n  assumes \"(C \\<Rightarrow> S) \\<sqsubseteq> F(C \\<Rightarrow> S)\" \"(C \\<and> \\<mu> F) = (C \\<and> \\<nu> F)\"\n  shows \"(C \\<Rightarrow> S) \\<sqsubseteq> \\<mu> F\"\nproof -\n  from assms have \"(C \\<Rightarrow> S) \\<sqsubseteq> \\<nu> F\"\n    by (simp add: lfp_lowerbound)\n  with assms show ?thesis\n    by (pred_auto)\nqed\n\nsubsection \\<open> Obtaining Unique Fixed-points \\<close>\n    \ntext \\<open> Obtaining termination proofs via approximation chains. Theorems and proofs adapted\n  from Chapter 2, page 63 of the UTP book~\\<^cite>\\<open>\"Hoare&98\"\\<close>.  \\<close>\n\ntype_synonym 'a chain = \"nat \\<Rightarrow> 'a upred\"\n\ndefinition chain :: \"'a chain \\<Rightarrow> bool\" where\n  \"chain Y = ((Y 0 = false) \\<and> (\\<forall> i. Y (Suc i) \\<sqsubseteq> Y i))\"\n\nlemma chain0 [simp]: \"chain Y \\<Longrightarrow> Y 0 = false\"\n  by (simp add:chain_def)\n\nlemma chainI:\n  assumes \"Y 0 = false\" \"\\<And> i. Y (Suc i) \\<sqsubseteq> Y i\"\n  shows \"chain Y\"\n  using assms by (auto simp add: chain_def)\n\nlemma chainE:\n  assumes \"chain Y\" \"\\<And> i. \\<lbrakk> Y 0 = false; Y (Suc i) \\<sqsubseteq> Y i \\<rbrakk> \\<Longrightarrow> P\"\n  shows \"P\"\n  using assms by (simp add: chain_def)\n\nlemma L274:\n  assumes \"\\<forall> n. ((E n \\<and>\\<^sub>p X) = (E n \\<and> Y))\"\n  shows \"(\\<Sqinter> (range E) \\<and> X) = (\\<Sqinter> (range E) \\<and> Y)\"\n  using assms by (pred_auto)\n\ntext \\<open> Constructive chains \\<close>\n\ndefinition constr ::\n  \"('a upred \\<Rightarrow> 'a upred) \\<Rightarrow> 'a chain \\<Rightarrow> bool\" where\n\"constr F E \\<longleftrightarrow> chain E \\<and> (\\<forall> X n. ((F(X) \\<and> E(n + 1)) = (F(X \\<and> E(n)) \\<and> E (n + 1))))\"\n\nlemma constrI:\n  assumes \"chain E\" \"\\<And> X n. ((F(X) \\<and> E(n + 1)) = (F(X \\<and> E(n)) \\<and> E (n + 1)))\"\n  shows \"constr F E\"\n  using assms by (auto simp add: constr_def)\n\ntext \\<open> This lemma gives a way of showing that there is a unique fixed-point when\n        the predicate function can be built using a constructive function F\n        over an approximation chain E \\<close>\n\nlemma chain_pred_terminates:\n  assumes \"constr F E\" \"mono F\"\n  shows \"(\\<Sqinter> (range E) \\<and> \\<mu> F) = (\\<Sqinter> (range E) \\<and> \\<nu> F)\"\nproof -\n  from assms have \"\\<forall> n. (E n \\<and> \\<mu> F) = (E n \\<and> \\<nu> F)\"\n  proof (rule_tac allI)\n    fix n\n    from assms show \"(E n \\<and> \\<mu> F) = (E n \\<and> \\<nu> F)\"\n    proof (induct n)\n      case 0 thus ?case by (simp add: constr_def)\n    next\n      case (Suc n)\n      note hyp = this\n      thus ?case\n      proof -\n        have \"(E (n + 1) \\<and> \\<mu> F) = (E (n + 1) \\<and> F (\\<mu> F))\"\n          using gfp_unfold[OF hyp(3), THEN sym] by (simp add: constr_def)\n        also from hyp have \"... = (E (n + 1) \\<and> F (E n \\<and> \\<mu> F))\"\n          by (metis conj_comm constr_def)\n        also from hyp have \"... = (E (n + 1) \\<and> F (E n \\<and> \\<nu> F))\"\n          by simp\n        also from hyp have \"... = (E (n + 1) \\<and> \\<nu> F)\"\n          by (metis (no_types, lifting) conj_comm constr_def lfp_unfold)\n        ultimately show ?thesis\n          by simp\n      qed\n    qed\n  qed\n  thus ?thesis\n    by (auto intro: L274)\nqed\n\ntheorem constr_fp_uniq:\n  assumes \"constr F E\" \"mono F\" \"\\<Sqinter> (range E) = C\"\n  shows \"(C \\<and> \\<mu> F) = (C \\<and> \\<nu> F)\"\n  using assms(1) assms(2) assms(3) chain_pred_terminates by blast\n    \nsubsection \\<open> Noetherian Induction Instantiation\\<close>\n      \ntext \\<open> Contribution from Yakoub Nemouchi.The following generalization was used by Tobias Nipkow\n        and Peter Lammich  in \\emph{Refine\\_Monadic} \\<close>\n\nlemma  wf_fixp_uinduct_pure_ueq_gen:     \n  assumes fixp_unfold: \"fp B = B (fp B)\"\n  and              WF: \"wf R\"\n  and     induct_step:\n          \"\\<And>f st. \\<lbrakk>\\<And>st'. (st',st) \\<in> R  \\<Longrightarrow> (((Pre \\<and> \\<lceil>e\\<rceil>\\<^sub>< =\\<^sub>u \\<guillemotleft>st'\\<guillemotright>) \\<Rightarrow> Post) \\<sqsubseteq> f)\\<rbrakk>\n               \\<Longrightarrow> fp B = f \\<Longrightarrow>((Pre \\<and> \\<lceil>e\\<rceil>\\<^sub>< =\\<^sub>u \\<guillemotleft>st\\<guillemotright>) \\<Rightarrow> Post) \\<sqsubseteq> (B f)\"\n        shows \"((Pre \\<Rightarrow> Post) \\<sqsubseteq> fp B)\"  \nproof -  \n  { fix st\n    have \"((Pre \\<and> \\<lceil>e\\<rceil>\\<^sub>< =\\<^sub>u \\<guillemotleft>st\\<guillemotright>) \\<Rightarrow> Post) \\<sqsubseteq> (fp B)\" \n    using WF proof (induction rule: wf_induct_rule)\n      case (less x)\n      hence \"(Pre \\<and> \\<lceil>e\\<rceil>\\<^sub>< =\\<^sub>u \\<guillemotleft>x\\<guillemotright> \\<Rightarrow> Post) \\<sqsubseteq> B (fp B)\"\n        by (rule induct_step, rel_blast, simp)\n      then show ?case\n        using fixp_unfold by auto\n    qed\n  }\n  thus ?thesis \n  by pred_simp  \nqed\n  \ntext \\<open> The next lemma shows that using substitution also work. However it is not that generic\n        nor practical for proof automation ... \\<close>\n\nlemma refine_usubst_to_ueq:\n  \"vwb_lens E \\<Longrightarrow> (Pre \\<Rightarrow> Post)\\<lbrakk>\\<guillemotleft>st'\\<guillemotright>/$E\\<rbrakk> \\<sqsubseteq> f\\<lbrakk>\\<guillemotleft>st'\\<guillemotright>/$E\\<rbrakk> = (((Pre \\<and> $E =\\<^sub>u \\<guillemotleft>st'\\<guillemotright>) \\<Rightarrow> Post) \\<sqsubseteq> f)\"\n  by (rel_auto, metis vwb_lens_wb wb_lens.get_put)  \n\ntext \\<open> By instantiation of @{thm wf_fixp_uinduct_pure_ueq_gen} with @{term \\<mu>} and lifting of the \n        well-founded relation we have ... \\<close>\n  \nlemma mu_rec_total_pure_rule: \n  assumes WF: \"wf R\"\n  and     M: \"mono B\"  \n  and     induct_step:\n          \"\\<And> f st.  \\<lbrakk>(Pre \\<and> (\\<lceil>e\\<rceil>\\<^sub><,\\<guillemotleft>st\\<guillemotright>)\\<^sub>u \\<in>\\<^sub>u \\<guillemotleft>R\\<guillemotright> \\<Rightarrow> Post) \\<sqsubseteq> f\\<rbrakk>\n               \\<Longrightarrow> \\<mu> B = f \\<Longrightarrow>(Pre \\<and> \\<lceil>e\\<rceil>\\<^sub>< =\\<^sub>u \\<guillemotleft>st\\<guillemotright> \\<Rightarrow> Post) \\<sqsubseteq> (B f)\"\n        shows \"(Pre \\<Rightarrow> Post) \\<sqsubseteq> \\<mu> B\"  \nproof (rule wf_fixp_uinduct_pure_ueq_gen[where fp=\\<mu> and Pre=Pre and B=B and R=R and e=e])\n  show \"\\<mu> B = B (\\<mu> B)\"\n    by (simp add: M def_gfp_unfold)\n  show \"wf R\"\n    by (fact WF)\n  show \"\\<And>f st. (\\<And>st'. (st', st) \\<in> R \\<Longrightarrow> (Pre \\<and> \\<lceil>e\\<rceil>\\<^sub>< =\\<^sub>u \\<guillemotleft>st'\\<guillemotright> \\<Rightarrow> Post) \\<sqsubseteq> f) \\<Longrightarrow> \n                \\<mu> B = f \\<Longrightarrow> \n                (Pre \\<and> \\<lceil>e\\<rceil>\\<^sub>< =\\<^sub>u \\<guillemotleft>st\\<guillemotright> \\<Rightarrow> Post) \\<sqsubseteq> B f\"\n    by (rule induct_step, rel_simp, simp)\nqed\n\nlemma nu_rec_total_pure_rule: \n  assumes WF: \"wf R\"\n  and     M: \"mono B\"  \n  and     induct_step:\n          \"\\<And> f st.  \\<lbrakk>(Pre \\<and> (\\<lceil>e\\<rceil>\\<^sub><,\\<guillemotleft>st\\<guillemotright>)\\<^sub>u \\<in>\\<^sub>u \\<guillemotleft>R\\<guillemotright> \\<Rightarrow> Post) \\<sqsubseteq> f\\<rbrakk>\n               \\<Longrightarrow> \\<nu> B = f \\<Longrightarrow>(Pre \\<and> \\<lceil>e\\<rceil>\\<^sub>< =\\<^sub>u \\<guillemotleft>st\\<guillemotright> \\<Rightarrow> Post) \\<sqsubseteq> (B f)\"\n        shows \"(Pre \\<Rightarrow> Post) \\<sqsubseteq> \\<nu> B\"  \nproof (rule wf_fixp_uinduct_pure_ueq_gen[where fp=\\<nu> and Pre=Pre and B=B and R=R and e=e])\n  show \"\\<nu> B = B (\\<nu> B)\"\n    by (simp add: M def_lfp_unfold)\n  show \"wf R\"\n    by (fact WF)\n  show \"\\<And>f st. (\\<And>st'. (st', st) \\<in> R \\<Longrightarrow> (Pre \\<and> \\<lceil>e\\<rceil>\\<^sub>< =\\<^sub>u \\<guillemotleft>st'\\<guillemotright> \\<Rightarrow> Post) \\<sqsubseteq> f) \\<Longrightarrow> \n                \\<nu> B = f \\<Longrightarrow> \n                (Pre \\<and> \\<lceil>e\\<rceil>\\<^sub>< =\\<^sub>u \\<guillemotleft>st\\<guillemotright> \\<Rightarrow> Post) \\<sqsubseteq> B f\"\n    by (rule induct_step, rel_simp, simp)\nqed\n\ntext \\<open>Since @{term \"B ((Pre \\<and> (\\<lceil>E\\<rceil>\\<^sub><,\\<guillemotleft>st\\<guillemotright>)\\<^sub>u\\<in>\\<^sub>u\\<guillemotleft>R\\<guillemotright> \\<Rightarrow> Post)) \\<sqsubseteq> B (\\<mu> B)\"} and \n      @{term \"mono B\"}, thus,  @{thm mu_rec_total_pure_rule} can be expressed as follows\\<close>\n  \nlemma mu_rec_total_utp_rule: \n  assumes WF: \"wf R\"\n    and     M: \"mono B\"  \n    and     induct_step:\n    \"\\<And>st. (Pre \\<and> \\<lceil>e\\<rceil>\\<^sub>< =\\<^sub>u \\<guillemotleft>st\\<guillemotright> \\<Rightarrow> Post) \\<sqsubseteq> (B ((Pre \\<and> (\\<lceil>e\\<rceil>\\<^sub><,\\<guillemotleft>st\\<guillemotright>)\\<^sub>u \\<in>\\<^sub>u \\<guillemotleft>R\\<guillemotright> \\<Rightarrow> Post)))\"\n  shows \"(Pre \\<Rightarrow> Post) \\<sqsubseteq> \\<mu> B\"  \nproof (rule mu_rec_total_pure_rule[where R=R and e=e], simp_all add: assms)\n  show \"\\<And>f st. (Pre \\<and> (\\<lceil>e\\<rceil>\\<^sub><, \\<guillemotleft>st\\<guillemotright>)\\<^sub>u \\<in>\\<^sub>u \\<guillemotleft>R\\<guillemotright> \\<Rightarrow> Post) \\<sqsubseteq> f \\<Longrightarrow> \\<mu> B = f \\<Longrightarrow> (Pre \\<and> \\<lceil>e\\<rceil>\\<^sub>< =\\<^sub>u \\<guillemotleft>st\\<guillemotright> \\<Rightarrow> Post) \\<sqsubseteq> B f\"\n    by (simp add: M induct_step monoD order_subst2)\nqed\n\nlemma nu_rec_total_utp_rule: \n  assumes WF: \"wf R\"\n    and     M: \"mono B\"  \n    and     induct_step:\n    \"\\<And>st. (Pre \\<and> \\<lceil>e\\<rceil>\\<^sub>< =\\<^sub>u \\<guillemotleft>st\\<guillemotright> \\<Rightarrow> Post) \\<sqsubseteq> (B ((Pre \\<and> (\\<lceil>e\\<rceil>\\<^sub><,\\<guillemotleft>st\\<guillemotright>)\\<^sub>u \\<in>\\<^sub>u \\<guillemotleft>R\\<guillemotright> \\<Rightarrow> Post)))\"\n  shows \"(Pre \\<Rightarrow> Post) \\<sqsubseteq> \\<nu> B\"  \nproof (rule nu_rec_total_pure_rule[where R=R and e=e], simp_all add: assms)\n  show \"\\<And>f st. (Pre \\<and> (\\<lceil>e\\<rceil>\\<^sub><, \\<guillemotleft>st\\<guillemotright>)\\<^sub>u \\<in>\\<^sub>u \\<guillemotleft>R\\<guillemotright> \\<Rightarrow> Post) \\<sqsubseteq> f \\<Longrightarrow> \\<nu> B = f \\<Longrightarrow> (Pre \\<and> \\<lceil>e\\<rceil>\\<^sub>< =\\<^sub>u \\<guillemotleft>st\\<guillemotright> \\<Rightarrow> Post) \\<sqsubseteq> B f\"\n    by (simp add: M induct_step monoD order_subst2)\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/UTP/utp/utp_recursion.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8311430394931457, "lm_q2_score": 0.8688267728417087, "lm_q1q2_score": 0.7221193247726787}}
{"text": "section \\<open>theory_decr_forest\\<close>\ntheory theory_decr_forest\nimports Main\nbegin\n\ntext \\<open> This theory defines a notion of graphs. A graph is a record that contains a set of nodes \n\\<open>V\\<close> and a set of edges VxV, where the values v are the unique vertex labels.\\<close>\n\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 valid graph, edges only go from nodes to nodes.\\<close>\n  locale valid_graph = \n    fixes G :: \"('v) graph\"\n    assumes E_valid: \"fst`edges G \\<subseteq> nodes G\"\n                     \"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,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  end\n\nsubsection \\<open>Basic operations on Graphs\\<close>\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>(-{v})\n    \\<rparr>\"\n  text \\<open>Adds an edge to a graph, edges only go from smaller to larger vertex labels\\<close>\n  definition add_edge where \"add_edge v  v' g \\<equiv> \\<lparr>\n    nodes = {v,v'} \\<union> nodes g,\n    edges = (if v'>v then \n    insert (v,v') (edges g) else insert (v',v) (edges g))\n    \\<rparr>\"\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 = edges g - {(v,v')} \\<rparr>\"\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 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 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 nodes_empty[simp]: \"nodes empty = {}\" unfolding empty_def by simp\n  lemma edges_empty[simp]: \"edges empty = {}\" unfolding empty_def by simp\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 v' g) = insert v (insert v' (nodes g))\"\n    by (simp add: add_edge_def)\n  \n\nsubsection \\<open>Preliminary definitions\\<close>\n  text \\<open>This function finds the connected component corresponding to the given vertex.\\<close>\n  definition \"nodes_above g v \\<equiv>{v} \\<union> snd ` Set.filter (\\<lambda>e. fst e = v) ((edges g)\\<^sup>+)\" \n\n  text \\<open>The function puts a component into a tree and preserves the decreasing property.\\<close>\n  fun nodes_order :: \" nat graph \\<Rightarrow> nat \\<Rightarrow> nat graph \" where\n     \"nodes_order g x\\<^sub>1 =  (let nodes\\<^sub>1= nodes_above g 1 in\n                           let nodes\\<^sub>2= nodes_above g (x\\<^sub>1+2) in\n                            let max_comp\\<^sub>1= Max(nodes\\<^sub>1) in\n                            let max_comp\\<^sub>2= Max(nodes\\<^sub>2) in \n                              (if max_comp\\<^sub>1=max_comp\\<^sub>2 then g else\n                                (if max_comp\\<^sub>1 > max_comp\\<^sub>2 then \n                                    let st_p=Max(Set.filter (\\<lambda>v. v<max_comp\\<^sub>2) nodes\\<^sub>1) in\n                                    let end_p=Min(Set.filter (\\<lambda>v. v>max_comp\\<^sub>2) nodes\\<^sub>1) in\n                                    let g1= delete_edge st_p end_p g in\n                                    let g2= add_edge st_p max_comp\\<^sub>2 g1 in\n                                    let g3=add_edge max_comp\\<^sub>2 end_p g2 in g3\n                                 else \n                                   add_edge max_comp\\<^sub>1 max_comp\\<^sub>2 g\n                                 )\n                               )\n                            )\" \n\n  text \\<open>This is an additional function. Input:\n    1. Order number of the current node that can be added to the graph \n    2. Order number of the previous node from branch1 (above 1) added to the graph\n    3. Order number of the previous node from branch2 (above x1+2) added to the graph\n    4. The current graph\n    5. Number sequence to encode the graph\n\n    How does the function work:\n    I. If the sequence (input 5.) is empty, return current graph (input 4.)\n    II. If the sequence is not empty and starts with a zero, add one to the order number of the \n    current node, delete the first number (0) from the sequence and call the function again\n    III. If the sequence isn't empty and doesn't start with a 0, add the current node to the graph\n    IIIa. If the sequence starts with a 1, add an edge to branch1 using input (2)\n    IIIb.  If the sequence starts with a 2, add an edge to branch2 using input (3)\\<close>\n  fun enc_to_graph :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> nat graph \\<Rightarrow> nat list \\<Rightarrow> nat graph\" where\n     \"enc_to_graph curr_v prev_v1 prev_v2 g Nil = g\"\n|    \"enc_to_graph curr_v prev_v1 prev_v2 g (0#ns)  = \n      enc_to_graph (Suc curr_v) prev_v1 prev_v2 g ns \"\n|    \"enc_to_graph curr_v prev_v1 prev_v2 g (x#ns) = (if x=1 then\n      enc_to_graph (Suc curr_v) curr_v prev_v2 (add_edge prev_v1 curr_v g) ns\n      else (if curr_v=prev_v2 then enc_to_graph (Suc curr_v) prev_v1 curr_v g ns \n      else enc_to_graph (Suc curr_v) prev_v1 curr_v (add_edge prev_v2 curr_v g) ns\n           )                                         )\" \n\n  text \\<open>Define f1 to be the start graph.\\<close>\n  definition \"f1 \\<equiv> \\<lparr>nodes = {1::nat}, edges = {}\\<rparr>\"\n\n text \\<open>This is the inverse encoding function. Input:\n    1.x1\n    2. number sequence to encode into a graph \n    How does the function work:\n    I.delete the last number since it only gives information about the number of trees in the graph\n    but distinguish between cases in dependence of this last value\n    II. take first x1 numbers and build the first graph part with enc_to_graph\n    III. add the node x1+2 to the graph\n    IV. delete x1 first numbers and build the second part with the rest \n    V(0). if the last encoding value was 0, output tree2\n    V(1)(2).if the last encoding value was 1 and there are 2's in the encoding,\n            connect two branches into one component using the function nodes_order\n    V(1)(1). if the encoding only has 0 and 1 in it, build further on tree1 \\<close>\n  fun encoding_to_graph :: \"nat \\<Rightarrow> nat list \\<Rightarrow> nat graph\" where\n     \"encoding_to_graph x1 l = (let code_l=butlast l in\n                            let tree\\<^sub>1 = enc_to_graph 2 1 (x1+2) f1 (take x1 (code_l)) in\n                            let max\\<^sub>1 = Max (nodes tree\\<^sub>1) in\n                            let tree\\<^sub>2 = enc_to_graph (x1+3) max\\<^sub>1 (x1+2) (add_node (x1+2) tree\\<^sub>1) \n                                        (drop x1 code_l) in\n                            if (last l=0) then tree\\<^sub>2 else\n                            if 2\\<in>set(code_l) then (nodes_order tree\\<^sub>2 x1 ) \n                             else  enc_to_graph (x1+3) (x1+2) (x1+2) (add_edge max\\<^sub>1 (x1+2) tree\\<^sub>1) \n                                   (drop (x1) code_l)  \n                                    \n                                )\"\n\n\n\n text \\<open>This is the main encoding function. Input:\n      1. Graph g to be encoded\n      2. x1\n      3. 2 as the starting node\n      4. x1+x2+2\n      5. False as the starting value for branching\n      How does the function work:\n      I. For each x from 2 (input (3)) to x1+x2+2 (input (4)), check whether \n         the vertex is in the graph, and if so, above which leaf does it exist\n      II. For the nodes above the vertex with label 1, add 1 to the encoding,For the nodes \n          above the vertex with label x1+2, add 2 to the encoding, change input (5) if \n          we found a vertex with 2 incoming edges. If the value is not on a vertex,\n          add 0 to the encoding\n      III.using the value (5), decide to put 1 or 0 for 1 or 2 connected components\\<close>\n fun graph_to_encoding_impl :: \"nat graph \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> bool \\<Rightarrow> nat list\" where\n    \"graph_to_encoding_impl f x1 x 0 c = [if c then 1 else 0]\"\n|   \"graph_to_encoding_impl f x1 x (Suc n) c = (let above_one = (1, x) \\<in> (edges f)\\<^sup>+ in\n                                                let above_x1_2 = (x1+2, x) \\<in> (edges f)\\<^sup>* in\n                                                (if x = x1 + 2 then\n                                                  graph_to_encoding_impl f x1 (Suc x) n \n                                                  (above_one \\<and> above_x1_2)\n                                                 else (if x \\<in> nodes f then \n                                                  (if above_one \\<and> (c \\<or> \\<not> above_x1_2) then 1 else 2)\n                                                       else 0)\n                                                # graph_to_encoding_impl f x1 (Suc x) n \n                                                  (c \\<or> above_one \\<and> above_x1_2))\n                                               )\"\n  text \\<open>Add some computation simplifications.\\<close>\n  lemma in_rtrancl_code [code_unfold]:  \"x \\<in> rtrancl R \\<longleftrightarrow> fst x = snd x \\<or> x \\<in> trancl R\"\n  by (metis prod.exhaust_sel rtrancl_eq_or_trancl)\n\n  print_theorems\n  definition \"graph_to_encoding f x1 x2 \\<equiv> graph_to_encoding_impl f x1 2 (x1+x2+1) False\"\n\n(* Examples Part 1\ndefinition \"graph_ex1 \\<equiv>\n  \\<lparr>nodes = {1::nat,2,5,7},\n   edges = {(1,2),(2,5),(5,7)}\\<rparr>\"\n \ndefinition \"graph_ex2 \\<equiv>\n  \\<lparr>nodes = {1::nat,2,3,5,7},\n   edges = {(1,2),(2,3),(3,7),(5,7)}\\<rparr>\"\n\ndefinition \"graph_ex3 \\<equiv>\n  \\<lparr>nodes = {1::nat,4,5,6,7},\n   edges = {(1,4),(4,6),(5,7)}\\<rparr>\"\n\ndefinition x1:: nat where \"x1=3\"\ndefinition x2:: nat where \"x2=2\"\nvalue \"graph_to_encoding graph_ex1 x1 x2\"\nvalue \"graph_to_encoding graph_ex2 x1 x2\"\nvalue \"graph_to_encoding graph_ex3 x1 x2\"\n\nPart 2:\ndefinition \"f2 \\<equiv>\n  \\<lparr>nodes = {1::nat,2,5,6,7,8,10},\n   edges = {(1,2),(2,7),(7,8),\n            (5,6),(6,8),(8,10)}\\<rparr>\"\n\nlemma \"graph_to_encoding f2 3 5 = [1,0,0,2,1,2,0,1,1]\" by eval\n\ndefinition \"f3 \\<equiv>\n  \\<lparr>nodes = {1::nat,2,5,6,7,8,10},\n   edges = {(1,2),(2,8),\n            (5,6),(6,7),(7,8),(8,10)}\\<rparr>\"\n\ndefinition \"f4 \\<equiv>\n  \\<lparr>nodes = {1::nat,2,5,6,7,8,10},\n   edges = {(1,2),(2,7),\n            (5,6),(6,8),(8,10)}\\<rparr>\"\n\ndefinition \"f6 \\<equiv>\n  \\<lparr>nodes = {1::nat,4,5,7,8},\n   edges = {(1,4),(4,5),(5,7),(7,8)}\\<rparr>\"\n\ndefinition \"f7 \\<equiv>\n  \\<lparr>nodes = {1::nat,5,7,10},\n   edges = {(1,10),(5,7),(7,10)}\\<rparr>\"\n\ndefinition \"f8 \\<equiv>\n  \\<lparr>nodes = {1::nat,5,7,10},\n   edges = {(1,5),(5,7),(7,10)}\\<rparr>\"\n\n\ndefinition \"f5 \\<equiv>\n  \\<lparr>nodes = {1::nat,3,5,6,7,8,10},\n   edges = {(1,3),(3,6),\n            (5,6),(6,7),(7,8),(8,10)}\\<rparr>\"\n\ndefinition \"f9 \\<equiv>\n  \\<lparr>nodes = {1::nat,5},\n   edges = {}\\<rparr>\"\n\nvalue \"(encoding_to_graph 3 (graph_to_encoding f3 3 5)) =f3\"\nvalue \"(encoding_to_graph 3 (graph_to_encoding f4 3 5)) =f4\"\nvalue \"(encoding_to_graph 3 (graph_to_encoding f5 3 5)) =f5\"\nvalue \"(encoding_to_graph 3 (graph_to_encoding f6 3 5)) =f6\"\nvalue \"(encoding_to_graph 3 (graph_to_encoding f7 3 5)) =f7\"\nvalue \"(encoding_to_graph 3 (graph_to_encoding f8 3 5)) =f8\"\nvalue \"(encoding_to_graph 3 (graph_to_encoding f9 3 5)) =f9\"*)\n\n\n text \\<open>Define locales for the encoding and the forest to represent them canonically.\\<close>\n locale encoding = \n   fixes L  :: \"nat list\"\n   and   x1 :: \"nat\"\n   and   x2 :: \"nat\"\n assumes L_valid: \"length L = x1+x2+1\"\n                  \"set (take x1 L) \\<subseteq> {0,1} \"\n                  \"set (drop x1 L) \\<subseteq> {0,1,2}\"\n                  \"set (drop (x1+x2) L) \\<subseteq> {0,1}\"\n\n text \\<open>This is a function that finds the edges that are incident to the given vertex.\\<close>\n definition edges_v :: \"nat graph \\<Rightarrow> nat \\<Rightarrow> (nat \\<times> nat) set\" where\n          \" edges_v g v \\<equiv> {e. e \\<in> edges g \\<and> (fst e = v \\<or> snd e = v)}\"\n\n locale forest = \n   fixes T  :: \"nat graph\"\n   and   x1 :: \"nat\"\n   and   x2 :: \"nat\"\n assumes Ed_valid: \"x1+2 \\<in> nodes T\"\n                   \"\\<forall> (v)\\<in> fst`edges T. card(snd`(edges_v T v)-{v})<2\"\n                   \"\\<forall> (v)\\<in> snd`edges T. card(fst`(edges_v T v)-{v})<3\"\n                   \"\\<forall> (v,v')\\<in> edges T. ( v<v')\"\n                   \"nodes T \\<noteq> {}\"\n                   \"edges T \\<noteq> {}\"\n                   \"Max (nodes T) < x1+x2+3\"\n\n\n text \\<open>This is a test section with a simplified theory. Its purpose is to define the direction of\nthe future research. A single tree with one leaf can be encoded as a set of its nodes. The encoding \nfor such a tree is just a list of Bool values, True for \"node in the graph\" and False for \"not\". \\<close>\ndefinition \"valid_tree S n \\<equiv> (\\<forall>x. x \\<in> S \\<longrightarrow> 0 < x \\<and> x \\<le> n)\"\ndefinition \"valid_encoding B n \\<equiv> length B = n \\<and> set B \\<subseteq> {True, False}\"\n\n text \\<open>Non-recursive definitions allow to use induction and prove some simple theorems.\\<close>\nfun tree_to_encoding :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat set \\<Rightarrow> bool list\" where\n\"tree_to_encoding x n S = map (\\<lambda>i. i \\<in> S) [x..<x+n]\"\n\nfun encoding_to_tree :: \" nat \\<Rightarrow> bool list \\<Rightarrow> nat set\" where\n\"encoding_to_tree n B = (\\<lambda>i. i + n) ` {i. i < length B \\<and> B ! i}\"\n\ntext \\<open>To show that two functions form a bijection, one should first check that the\noutputs are well-defined.\\<close>\nlemma length_tree_to_encoding:\n  \"length (tree_to_encoding x n S) = n\"\n  by (induct x n S rule: tree_to_encoding.induct) auto\n\nlemma encoding_members:\n  \"set (tree_to_encoding x n S) \\<subseteq> {True, False}\"\n  by (induct x n S rule: tree_to_encoding.induct) auto\n\nlemma valid_tree_to_valid_encoding: \n  \"valid_encoding (tree_to_encoding x n S) n\"\n  unfolding valid_encoding_def\n  using encoding_members length_tree_to_encoding by auto\n\nlemma valid_encoding_to_valid_tree_aux:\n  \"encoding_to_tree n B \\<subseteq> {n..<n + length B}\"\n  by (induction n B rule: encoding_to_tree.induct)\n     (auto simp: valid_encoding_def valid_tree_def)\n\nlemma valid_encoding_to_valid_tree:\n  \"valid_encoding B n \\<Longrightarrow> valid_tree (encoding_to_tree 1 B ) n\"\n  using valid_encoding_to_valid_tree_aux unfolding valid_encoding_def valid_tree_def\n  by force\n\nend\n", "meta": {"author": "Nataliakonst", "repo": "decreasing-forest", "sha": "4c9a3de8a207ba5f28879dcfc924a127a3c67475", "save_path": "github-repos/isabelle/Nataliakonst-decreasing-forest", "path": "github-repos/isabelle/Nataliakonst-decreasing-forest/decreasing-forest-4c9a3de8a207ba5f28879dcfc924a127a3c67475/theory_decr_forest.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8688267660487572, "lm_q2_score": 0.831143045767024, "lm_q1q2_score": 0.7221193245776777}}
{"text": "section \\<open>Convex Hulls\\<close>\n\ntext \\<open>We define the notion of convex hull of a set or list of vectors and derive basic\n  properties thereof.\\<close>\n\ntheory Convex_Hull\n  imports Cone\nbegin\n\ncontext gram_schmidt\nbegin\n\ndefinition \"convex_lincomb c Vs b = (nonneg_lincomb c Vs b \\<and> sum c Vs = 1)\"\n\ndefinition \"convex_lincomb_list c Vs b = (nonneg_lincomb_list c Vs b \\<and> sum c {0..<length Vs} = 1)\"\n\ndefinition \"convex_hull Vs = {x. \\<exists> Ws c. finite Ws \\<and> Ws \\<subseteq> Vs \\<and> convex_lincomb c Ws x}\"\n\nlemma convex_hull_carrier[intro]: \"Vs \\<subseteq> carrier_vec n \\<Longrightarrow> convex_hull Vs \\<subseteq> carrier_vec n\"\n  unfolding convex_hull_def convex_lincomb_def nonneg_lincomb_def by auto\n\nlemma convex_hull_mono: \"Vs \\<subseteq> Ws \\<Longrightarrow> convex_hull Vs \\<subseteq> convex_hull Ws\"\n  unfolding convex_hull_def by auto\n\nlemma convex_lincomb_empty[simp]: \"\\<not> (convex_lincomb c {} x)\"\n  unfolding convex_lincomb_def by simp\n\nlemma set_in_convex_hull:\n  assumes \"A \\<subseteq> carrier_vec n\"\n  shows \"A \\<subseteq> convex_hull A\"\nproof\n  fix a\n  assume \"a \\<in> A\"\n  hence acarr: \"a \\<in> carrier_vec n\" using assms by auto\n  hence \"convex_lincomb (\\<lambda> x. 1) {a} a \" unfolding convex_lincomb_def\n    by (auto simp: nonneg_lincomb_def lincomb_def)\n  then show \"a \\<in> convex_hull A\" using \\<open>a \\<in> A\\<close> unfolding convex_hull_def by auto\nqed\n\nlemma convex_hull_empty[simp]:\n  \"convex_hull {} = {}\"\n  \"A \\<subseteq> carrier_vec n \\<Longrightarrow> convex_hull A = {} \\<longleftrightarrow> A = {}\"\nproof -\n  show \"convex_hull {} = {}\" unfolding convex_hull_def by auto\n  then show \"A \\<subseteq> carrier_vec n \\<Longrightarrow> convex_hull A = {} \\<longleftrightarrow> A = {}\"\n    using set_in_convex_hull[of A] by auto\nqed\n\nlemma convex_hull_bound: assumes XBnd: \"X \\<subseteq> Bounded_vec Bnd\"\n  and X: \"X \\<subseteq> carrier_vec n\"\nshows \"convex_hull X \\<subseteq> Bounded_vec Bnd\"\nproof\n  fix x\n  assume \"x \\<in> convex_hull X\"\n  from this[unfolded convex_hull_def]\n  obtain Y c where fin: \"finite Y\" and YX: \"Y \\<subseteq> X\" and cx: \"convex_lincomb c Y x\" by auto\n  from cx[unfolded convex_lincomb_def nonneg_lincomb_def]\n  have x: \"x = lincomb c Y\" and sum: \"sum c Y = 1\" and c0: \"\\<And> y. y \\<in> Y \\<Longrightarrow> c y \\<ge> 0\" by auto\n  from YX X XBnd have Y: \"Y \\<subseteq> carrier_vec n\" and YBnd: \"Y \\<subseteq> Bounded_vec Bnd\" by auto\n  from x Y have dim: \"dim_vec x = n\" by auto\n  show \"x \\<in> Bounded_vec Bnd\" unfolding Bounded_vec_def mem_Collect_eq dim\n  proof (intro allI impI)\n    fix i\n    assume i: \"i < n\"\n    have \"abs (x $ i) = abs (\\<Sum>x\\<in>Y. c x * x $ i)\" unfolding x\n      by (subst lincomb_index[OF i Y], auto)\n    also have \"\\<dots> \\<le> (\\<Sum>x\\<in>Y. abs (c x * x $ i))\" by auto\n    also have \"\\<dots> = (\\<Sum>x\\<in>Y. abs (c x) * abs (x $ i))\" by (simp add: abs_mult)\n    also have \"\\<dots> \\<le> (\\<Sum>x\\<in>Y. abs (c x) * Bnd)\"\n      by (intro sum_mono mult_left_mono, insert YBnd[unfolded Bounded_vec_def] i Y, force+)\n    also have \"\\<dots> = (\\<Sum>x\\<in>Y. abs (c x)) * Bnd\"\n      by (simp add: sum_distrib_right)\n    also have \"(\\<Sum>x\\<in>Y. abs (c x)) = (\\<Sum>x\\<in>Y. c x)\"\n      by (rule sum.cong, insert c0, auto)\n    also have \"\\<dots> = 1\" by fact\n    finally show \"\\<bar>x $ i\\<bar> \\<le> Bnd\" by auto\n  qed\nqed\n\ndefinition \"convex_hull_list Vs = {x. \\<exists> c. convex_lincomb_list c Vs x}\"\n\nlemma lincomb_list_elem:\n  \"set Vs \\<subseteq> carrier_vec n \\<Longrightarrow>\n   lincomb_list (\\<lambda> j. if i=j then 1 else 0) Vs = (if i < length Vs then Vs ! i else 0\\<^sub>v n)\"\nproof (induction Vs rule: rev_induct)\n  case (snoc x Vs)\n  have x: \"x \\<in> carrier_vec n\" and Vs: \"set Vs \\<subseteq> carrier_vec n\" using snoc.prems by auto\n  let ?f = \"\\<lambda> j. if i = j then 1 else 0\"\n  have \"lincomb_list ?f (Vs @ [x]) = lincomb_list ?f Vs + ?f (length Vs) \\<cdot>\\<^sub>v x\"\n    using x Vs by simp\n  also have \"\\<dots> = (if i < length (Vs @ [x]) then (Vs @ [x]) ! i else 0\\<^sub>v n)\" (is ?goal)\n    using less_linear[of i \"length Vs\"]\n  proof (elim disjE)\n    assume i: \"i < length Vs\"\n    have \"lincomb_list (\\<lambda>j. if i = j then 1 else 0) Vs = Vs ! i\"\n      using snoc.IH[OF Vs] i by auto\n    moreover have \"(if i = length Vs then 1 else 0) \\<cdot>\\<^sub>v x = 0\\<^sub>v n\" using i x by auto\n    moreover have \"(if i < length (Vs @ [x]) then (Vs @ [x]) ! i else 0\\<^sub>v n) = Vs ! i\"\n      using i append_Cons_nth_left by fastforce\n    ultimately show ?goal using Vs i lincomb_list_carrier M.r_zero by metis\n  next\n    assume i: \"i = length Vs\"\n    have \"lincomb_list (\\<lambda>j. if i = j then 1 else 0) Vs = 0\\<^sub>v n\"\n      using snoc.IH[OF Vs] i by auto\n    moreover have \"(if i = length Vs then 1 else 0) \\<cdot>\\<^sub>v x = x\" using i x by auto\n    moreover have \"(if i < length (Vs @ [x]) then (Vs @ [x]) ! i else 0\\<^sub>v n) = x\"\n      using i append_Cons_nth_left by simp\n    ultimately show ?goal using x by simp\n  next\n    assume i: \"i > length Vs\"\n    have \"lincomb_list (\\<lambda>j. if i = j then 1 else 0) Vs = 0\\<^sub>v n\"\n      using snoc.IH[OF Vs] i by auto\n    moreover have \"(if i = length Vs then 1 else 0) \\<cdot>\\<^sub>v x = 0\\<^sub>v n\" using i x by auto\n    moreover have \"(if i < length (Vs @ [x]) then (Vs @ [x]) ! i else 0\\<^sub>v n) = 0\\<^sub>v n\"\n      using i by simp\n    ultimately show ?goal by simp\n  qed\n  finally show ?case by auto\nqed simp\n\nlemma set_in_convex_hull_list: fixes Vs :: \"'a vec list\"\n  assumes \"set Vs \\<subseteq> carrier_vec n\"\n  shows \"set Vs \\<subseteq> convex_hull_list Vs\"\nproof\n  fix x assume \"x \\<in> set Vs\"\n  then obtain i where i: \"i < length Vs\"\n    and x: \"x = Vs ! i\" using set_conv_nth[of Vs] by auto\n  let ?f = \"\\<lambda> j. if i = j then 1 else 0 :: 'a\"\n  have \"lincomb_list ?f Vs = x\" using i x lincomb_list_elem[OF assms] by auto\n  moreover have \"\\<forall> j < length Vs. ?f j \\<ge> 0\" by auto\n  moreover have \"sum ?f {0..<length Vs} = 1\" using i by simp\n  ultimately show \"x \\<in> convex_hull_list Vs\"\n    unfolding convex_hull_list_def convex_lincomb_list_def nonneg_lincomb_list_def\n    by auto\nqed\n\nlemma convex_hull_list_combination:\n  assumes Vs: \"set Vs \\<subseteq> carrier_vec n\"\n    and x: \"x \\<in> convex_hull_list Vs\"\n    and y: \"y \\<in> convex_hull_list Vs\"\n    and l0: \"0 \\<le> l\" and l1: \"l \\<le> 1\"\n  shows \"l \\<cdot>\\<^sub>v x + (1 - l) \\<cdot>\\<^sub>v y \\<in> convex_hull_list Vs\"\nproof -\n  from x obtain cx where x: \"lincomb_list cx Vs = x\" and cx0: \"\\<forall> i < length Vs. cx i \\<ge> 0\"\n    and cx1: \"sum cx {0..<length Vs} = 1\"\n    unfolding convex_hull_list_def convex_lincomb_list_def nonneg_lincomb_list_def\n    by auto\n  from y obtain cy where y: \"lincomb_list cy Vs = y\" and cy0: \"\\<forall> i < length Vs. cy i \\<ge> 0\"\n    and cy1: \"sum cy {0..<length Vs} = 1\"\n    unfolding convex_hull_list_def convex_lincomb_list_def nonneg_lincomb_list_def\n    by auto\n  let ?c = \"\\<lambda> i. l * cx i + (1 - l) * cy i\"\n  have \"set Vs \\<subseteq> carrier_vec n \\<Longrightarrow>\n        lincomb_list ?c Vs = l \\<cdot>\\<^sub>v lincomb_list cx Vs + (1 - l) \\<cdot>\\<^sub>v lincomb_list cy Vs\"\n  proof (induction Vs rule: rev_induct)\n    case (snoc v Vs)\n    have v: \"v \\<in> carrier_vec n\" and Vs: \"set Vs \\<subseteq> carrier_vec n\"\n      using snoc.prems by auto\n    have \"lincomb_list ?c (Vs @ [v]) = lincomb_list ?c Vs + ?c (length Vs) \\<cdot>\\<^sub>v v\"\n      using snoc.prems by auto\n    also have \"lincomb_list ?c Vs =\n               l \\<cdot>\\<^sub>v lincomb_list cx Vs + (1 - l) \\<cdot>\\<^sub>v lincomb_list cy Vs\"\n      by (rule snoc.IH[OF Vs])\n    also have \"?c (length Vs) \\<cdot>\\<^sub>v v =\n               l \\<cdot>\\<^sub>v (cx (length Vs) \\<cdot>\\<^sub>v v) + (1 - l) \\<cdot>\\<^sub>v (cy (length Vs) \\<cdot>\\<^sub>v v)\"\n      using add_smult_distrib_vec smult_smult_assoc by metis\n    also have \"l \\<cdot>\\<^sub>v lincomb_list cx Vs + (1 - l) \\<cdot>\\<^sub>v lincomb_list cy Vs + \\<dots> =\n                  l \\<cdot>\\<^sub>v (lincomb_list cx Vs + cx (length Vs) \\<cdot>\\<^sub>v v) +\n                  (1 - l) \\<cdot>\\<^sub>v (lincomb_list cy Vs + cy (length Vs) \\<cdot>\\<^sub>v v)\"\n      using lincomb_list_carrier[OF Vs] v\n      by (simp add: M.add.m_assoc M.add.m_lcomm smult_r_distr)\n    finally show ?case using Vs v by simp\n  qed simp\n  hence \"lincomb_list ?c Vs = l \\<cdot>\\<^sub>v x + (1 - l) \\<cdot>\\<^sub>v y\" using Vs x y by simp\n  moreover have \"\\<forall> i < length Vs. ?c i \\<ge> 0\" using cx0 cy0 l0 l1 by simp\n  moreover have \"sum ?c {0..<length Vs} = 1\"\n  proof(simp add: sum.distrib)\n    have \"(\\<Sum>i = 0..<length Vs. (1 - l) * cy i) = (1 - l) * sum cy {0..<length Vs}\"\n      using sum_distrib_left by metis\n    moreover have \"(\\<Sum>i = 0..<length Vs. l * cx i) = l * sum cx {0..<length Vs}\"\n      using sum_distrib_left by metis\n    ultimately show \"(\\<Sum>i = 0..<length Vs. l * cx i) + (\\<Sum>i = 0..<length Vs. (1 - l) * cy i) = 1\"\n      using cx1 cy1 by simp\n  qed\n  ultimately show ?thesis\n    unfolding convex_hull_list_def convex_lincomb_list_def nonneg_lincomb_list_def\n    by auto\nqed\n\nlemma convex_hull_list_mono:\n  assumes \"set Ws \\<subseteq> carrier_vec n\"\n  shows \"set Vs \\<subseteq> set Ws \\<Longrightarrow> convex_hull_list Vs \\<subseteq> convex_hull_list Ws\"\nproof (standard, induction Vs)\n  case Nil\n  from Nil(2) show ?case unfolding convex_hull_list_def convex_lincomb_list_def by auto\nnext\n  case (Cons v Vs)\n  have v: \"v \\<in> set Ws\" and Vs: \"set Vs \\<subseteq> set Ws\" using Cons.prems(1) by auto\n  hence v1: \"v \\<in> convex_hull_list Ws\" using set_in_convex_hull_list[OF assms] by auto\n  from Cons.prems(2) obtain c\n    where x: \"lincomb_list c (v # Vs) = x\" and c0: \"\\<forall> i < length Vs + 1. c i \\<ge> 0\"\n      and c1: \"sum c {0..<length Vs + 1} = 1\"\n    unfolding convex_hull_list_def convex_lincomb_list_def nonneg_lincomb_list_def\n    by auto\n  have x: \"x = c 0 \\<cdot>\\<^sub>v v + lincomb_list (c \\<circ> Suc) Vs\" using Vs v assms x by auto\n\n  show ?case proof (cases)\n    assume P: \"c 0 = 1\"\n    hence \"sum (c \\<circ> Suc) {0..<length Vs} = 0\"\n      using sum.atLeast0_lessThan_Suc_shift c1\n      by (metis One_nat_def R.show_r_zero add.right_neutral add_Suc_right)\n    moreover have \"\\<And> i. i \\<in> {0..<length Vs} \\<Longrightarrow> (c \\<circ> Suc) i \\<ge> 0\"\n      using c0 by simp\n    ultimately have \"\\<forall> i \\<in> {0..<length Vs}. (c \\<circ> Suc) i = 0\"\n      using sum_nonneg_eq_0_iff by blast\n    hence \"\\<And> i. i < length Vs \\<Longrightarrow> (c \\<circ> Suc) i \\<cdot>\\<^sub>v Vs ! i = 0\\<^sub>v n\"\n      using Vs assms by (simp add: subset_code(1))\n    hence \"lincomb_list (c \\<circ> Suc) Vs = 0\\<^sub>v n\"\n      using lincomb_list_eq_0 by simp\n    hence \"x = v\" using P x v assms by auto\n    thus ?case using v1 by auto\n\n  next\n\n    assume P: \"c 0 \\<noteq> 1\"\n    have c1: \"c 0 + sum (c \\<circ> Suc) {0..<length Vs} = 1\"\n      using sum.atLeast0_lessThan_Suc_shift[of c] c1 by simp\n    have \"sum (c \\<circ> Suc) {0..<length Vs} \\<ge> 0\" by (rule sum_nonneg, insert c0, simp)\n    hence \"c 0 < 1\" using P c1 by auto\n    let ?c' = \"\\<lambda> i. 1 / (1 - c 0) * (c \\<circ> Suc) i\"\n    have \"sum ?c' {0..<length Vs} = 1 / (1 - c 0) * sum (c \\<circ> Suc) {0..<length Vs}\"\n      using c1 P sum_distrib_left by metis\n    hence \"sum ?c' {0..<length Vs} = 1\" using P c1 by simp\n    moreover have \"\\<forall> i < length Vs. ?c' i \\<ge> 0\" using c0 `c 0 < 1` by simp\n    ultimately have c': \"lincomb_list ?c' Vs \\<in> convex_hull_list Ws\"\n      using Cons.IH[OF Vs]\n        convex_hull_list_def convex_lincomb_list_def nonneg_lincomb_list_def\n      by blast\n    have \"lincomb_list ?c' Vs = 1 / (1 - c 0) \\<cdot>\\<^sub>v lincomb_list (c \\<circ> Suc) Vs\"\n      by(rule lincomb_list_smult, insert Vs assms, auto)\n    hence \"(1 - c 0) \\<cdot>\\<^sub>v lincomb_list ?c' Vs = lincomb_list (c \\<circ> Suc) Vs\"\n      using P by auto\n    hence \"x = c 0 \\<cdot>\\<^sub>v v + (1 - c 0) \\<cdot>\\<^sub>v lincomb_list ?c' Vs\" using x by auto\n    thus \"x \\<in> convex_hull_list Ws\"\n      using convex_hull_list_combination[OF assms v1 c'] c0 `c 0 < 1`\n      by simp\n  qed\nqed\n\nlemma convex_hull_list_eq_set:\n  \"set Vs \\<subseteq> carrier_vec n \\<Longrightarrow> set Vs = set Ws \\<Longrightarrow> convex_hull_list Vs = convex_hull_list Ws\"\n  using convex_hull_list_mono by blast\n\nlemma find_indices_empty: \"(find_indices x Vs = []) = (x \\<notin> set Vs)\"\nproof (induction Vs rule: rev_induct)\n  case (snoc v Vs)\n  show ?case\n  proof\n    assume \"find_indices x (Vs @ [v]) = []\"\n    hence \"x \\<noteq> v \\<and> find_indices x Vs = []\" by auto\n    thus \"x \\<notin> set (Vs @ [v])\" using snoc by simp\n  next\n    assume \"x \\<notin> set (Vs @ [v])\"\n    hence \"x \\<noteq> v \\<and> find_indices x Vs = []\" using snoc by auto\n    thus \"find_indices x (Vs @ [v]) = []\" by simp\n  qed\nqed simp\n\nlemma distinct_list_find_indices:\n  shows \"\\<lbrakk> i < length Vs; Vs ! i = x; distinct Vs \\<rbrakk> \\<Longrightarrow> find_indices x Vs = [i]\"\nproof (induction Vs rule: rev_induct)\n  case (snoc v Vs)\n  have dist: \"distinct Vs\" and xVs: \"v \\<notin> set Vs\" using snoc.prems(3) by(simp_all)\n  show ?case\n  proof (cases)\n    assume i: \"i = length Vs\"\n    hence \"x = v\" using snoc.prems(2) by auto\n    thus ?case using xVs find_indices_empty i\n      by fastforce\n  next\n    assume \"i \\<noteq> length Vs\"\n    hence i: \"i < length Vs\" using snoc.prems(1) by simp\n    hence Vsi: \"Vs ! i = x\" using snoc.prems(2) append_Cons_nth_left by fastforce\n    hence \"x \\<noteq> v\" using snoc.prems(3) i by auto\n    thus ?case using snoc.IH[OF i Vsi dist] by simp\n  qed\nqed auto\n\nlemma finite_convex_hull_iff_convex_hull_list: assumes Vs: \"Vs \\<subseteq> carrier_vec n\"\n  and id': \"Vs = set Vsl'\"\nshows \"convex_hull Vs = convex_hull_list Vsl'\"\nproof -\n  have fin: \"finite Vs\" unfolding id' by auto\n  from finite_distinct_list fin obtain Vsl\n    where id: \"Vs = set Vsl\" and dist: \"distinct Vsl\" by auto\n  from Vs id have Vsl: \"set Vsl \\<subseteq> carrier_vec n\" by auto\n  {\n    fix c :: \"nat \\<Rightarrow> 'a\"\n    have \"distinct Vsl \\<Longrightarrow>(\\<Sum>x\\<in>set Vsl. sum_list (map c (find_indices x Vsl))) =\n                          sum c {0..<length Vsl}\"\n    proof (induction Vsl rule: rev_induct)\n      case (snoc v Vsl)\n      let ?coef = \"\\<lambda> x. sum_list (map c (find_indices x (Vsl @ [v])))\"\n      let ?coef' = \"\\<lambda> x. sum_list (map c (find_indices x Vsl))\"\n      have dist: \"distinct Vsl\" using snoc.prems by simp\n      have \"sum ?coef (set (Vsl @ [v])) = sum_list (map ?coef (Vsl @ [v]))\"\n        by (rule sum.distinct_set_conv_list[OF snoc.prems, of ?coef])\n      also have \"\\<dots> = sum_list (map ?coef Vsl) + ?coef v\" by simp\n      also have \"sum_list (map ?coef Vsl) = sum ?coef (set Vsl)\"\n        using sum.distinct_set_conv_list[OF dist, of ?coef] by auto\n      also have \"\\<dots> = sum ?coef' (set Vsl)\"\n      proof (intro R.finsum_restrict[of ?coef] restrict_ext, standard)\n        fix x\n        assume \"x \\<in> set Vsl\"\n        then obtain i where i: \"i < length Vsl\" and x: \"x = Vsl ! i\"\n          using in_set_conv_nth[of x Vsl] by blast\n        hence \"(Vsl @ [v]) ! i = x\" by (simp add: append_Cons_nth_left)\n        hence \"?coef x = c i\"\n          using distinct_list_find_indices[OF _ _ snoc.prems] i by fastforce\n        also have  \"c i = ?coef' x\"\n          using distinct_list_find_indices[OF i _ dist] x by simp\n        finally show \"?coef x = ?coef' x\" by auto\n      qed\n      also have \"\\<dots> = sum c {0..<length Vsl}\" by (rule snoc.IH[OF dist])\n      also have \"?coef v = c (length Vsl)\"\n        using distinct_list_find_indices[OF _ _ snoc.prems, of \"length Vsl\" v]\n          nth_append_length by simp\n      finally show ?case using sum.atLeast0_lessThan_Suc by simp\n    qed simp\n  } note sum_sumlist = this\n  {\n    fix b\n    assume \"b \\<in> convex_hull_list Vsl\"\n    then obtain c where b: \"lincomb_list c Vsl = b\" and c: \"(\\<forall> i < length Vsl. c i \\<ge> 0)\"\n      and c1: \"sum c {0..<length Vsl} = 1\"\n      unfolding convex_hull_list_def convex_lincomb_list_def nonneg_lincomb_list_def\n      by auto\n    have \"convex_lincomb (mk_coeff Vsl c) Vs b\"\n      unfolding b[symmetric] convex_lincomb_def nonneg_lincomb_def\n      apply (subst lincomb_list_as_lincomb[OF Vsl])\n      by (insert c c1, auto simp: id mk_coeff_def dist sum_sumlist intro!: sum_list_nonneg)\n    hence \"b \\<in> convex_hull Vs\"\n      unfolding convex_hull_def convex_lincomb_def using fin by blast\n  }\n  moreover\n  {\n    fix b\n    assume \"b \\<in> convex_hull Vs\"\n    then obtain c Ws where Ws: \"Ws \\<subseteq> Vs\" and b: \"lincomb c Ws = b\"\n      and c: \"c ` Ws \\<subseteq> {x. x \\<ge> 0}\" and c1: \"sum c Ws = 1\"\n      unfolding convex_hull_def convex_lincomb_def nonneg_lincomb_def by auto\n    let ?d = \"\\<lambda> x. if x \\<in> Ws then c x else 0\"\n    have \"lincomb ?d Vs = lincomb c Ws + lincomb (\\<lambda> x. 0) (Vs - Ws)\"\n      using lincomb_union2[OF _ _ Diff_disjoint[of Ws Vs], of c \"\\<lambda> x. 0\"]\n        fin Vs Diff_partition[OF Ws] by metis\n    also have \"lincomb (\\<lambda> x. 0) (Vs - Ws) = 0\\<^sub>v n\"\n      using lincomb_zero[of \"Vs - Ws\" \"\\<lambda> x. 0\"] Vs by auto\n    finally have \"lincomb ?d Vs = b\" using b lincomb_closed Vs Ws by auto\n    moreover have \"?d ` Vs \\<subseteq> {t. t \\<ge> 0}\" using c by auto\n    moreover have \"sum ?d Vs = 1\" using  c1 R.extend_sum[OF fin Ws] by auto\n    ultimately have \"\\<exists> c. convex_lincomb c Vs b\"\n      unfolding convex_lincomb_def nonneg_lincomb_def by blast\n  }\n  moreover\n  {\n    fix b\n    assume \"\\<exists> c. convex_lincomb c Vs b\"\n    then obtain c where b: \"lincomb c Vs = b\" and c: \"c ` Vs \\<subseteq> {x. x \\<ge> 0}\"\n      and c1: \"sum c Vs = 1\"\n      unfolding convex_lincomb_def nonneg_lincomb_def by auto\n    from lincomb_as_lincomb_list_distinct[OF Vsl dist, of c]\n    have b: \"lincomb_list (\\<lambda>i. c (Vsl ! i)) Vsl = b\"\n      unfolding b[symmetric] id by simp\n    have \"1 = sum c (set Vsl)\" using c1 id by auto\n    also have \"\\<dots> = sum_list (map c Vsl)\" by(rule sum.distinct_set_conv_list[OF dist])\n    also have \"\\<dots> = sum ((!) (map c Vsl)) {0..<length Vsl}\"\n      using sum_list_sum_nth length_map by metis\n    also have \"\\<dots> = sum (\\<lambda> i. c (Vsl ! i)) {0..<length Vsl}\" by simp\n    finally have sum_1: \"(\\<Sum>i = 0..<length Vsl. c (Vsl ! i)) = 1\" by simp\n\n    have \"\\<exists> c. convex_lincomb_list c Vsl b\"\n      unfolding convex_lincomb_list_def nonneg_lincomb_list_def\n      by (intro exI[of _ \"\\<lambda>i. c (Vsl ! i)\"] conjI b sum_1)\n        (insert c, force simp: set_conv_nth id)\n    hence \"b \\<in> convex_hull_list Vsl\" unfolding convex_hull_list_def by auto\n  }\n  ultimately have \"convex_hull Vs = convex_hull_list Vsl\" by auto\n  also have \"convex_hull_list Vsl = convex_hull_list Vsl'\"\n    using convex_hull_list_eq_set[OF Vsl, of Vsl'] id id' by simp\n  finally show ?thesis by simp\nqed\n\ndefinition \"convex S = (convex_hull S = S)\"\n\nlemma convex_convex_hull: \"convex S \\<Longrightarrow> convex_hull S = S\"\n  unfolding convex_def by auto\n\nlemma convex_hull_convex_hull_listD: assumes A: \"A \\<subseteq> carrier_vec n\"\n  and x: \"x \\<in> convex_hull A\"\nshows \"\\<exists> as. set as \\<subseteq> A \\<and> x \\<in> convex_hull_list as\"\nproof -\n  from x[unfolded convex_hull_def]\n  obtain X c where finX: \"finite X\" and XA: \"X \\<subseteq> A\" and \"convex_lincomb c X x\" by auto\n  hence x: \"x \\<in> convex_hull X\" unfolding convex_hull_def by auto\n  from finite_list[OF finX] obtain xs where X: \"X = set xs\" by auto\n  from finite_convex_hull_iff_convex_hull_list[OF _ this] x XA A have x: \"x \\<in> convex_hull_list xs\" by auto\n  thus ?thesis using XA unfolding X by auto\nqed\n\nlemma convex_hull_convex_sum: assumes A: \"A \\<subseteq> carrier_vec n\"\n  and x: \"x \\<in> convex_hull A\"\n  and y: \"y \\<in> convex_hull A\"\n  and a: \"0 \\<le> a\" \"a \\<le> 1\"\nshows \"a \\<cdot>\\<^sub>v x + (1 - a) \\<cdot>\\<^sub>v y \\<in> convex_hull A\"\nproof -\n  from convex_hull_convex_hull_listD[OF A x] obtain xs where xs: \"set xs \\<subseteq> A\"\n    and x: \"x \\<in> convex_hull_list xs\" by auto\n  from convex_hull_convex_hull_listD[OF A y] obtain ys where ys: \"set ys \\<subseteq> A\"\n    and y: \"y \\<in> convex_hull_list ys\" by auto\n  have fin: \"finite (set (xs @ ys))\" by auto\n  have sub: \"set (xs @ ys) \\<subseteq> A\" using xs ys by auto\n  from convex_hull_list_mono[of \"xs @ ys\" xs] x sub A have x: \"x \\<in> convex_hull_list (xs @ ys)\" by auto\n  from convex_hull_list_mono[of \"xs @ ys\" ys] y sub A have y: \"y \\<in> convex_hull_list (xs @ ys)\" by auto\n  from convex_hull_list_combination[OF _ x y a]\n  have \"a \\<cdot>\\<^sub>v x + (1 - a) \\<cdot>\\<^sub>v y \\<in> convex_hull_list (xs @ ys)\" using sub A by auto\n  from finite_convex_hull_iff_convex_hull_list[of _ \"xs @ ys\"] this sub A\n  have \"a \\<cdot>\\<^sub>v x + (1 - a) \\<cdot>\\<^sub>v y \\<in> convex_hull (set (xs @ ys))\" by auto\n  with convex_hull_mono[OF sub]\n  show \"a \\<cdot>\\<^sub>v x + (1 - a) \\<cdot>\\<^sub>v y \\<in> convex_hull A\" by auto\nqed\n\nlemma convexI: assumes S: \"S \\<subseteq> carrier_vec n\"\n  and step: \"\\<And> a x y. x \\<in> S \\<Longrightarrow> y \\<in> S \\<Longrightarrow> 0 \\<le> a \\<Longrightarrow> a \\<le> 1 \\<Longrightarrow> a \\<cdot>\\<^sub>v x + (1 - a) \\<cdot>\\<^sub>v y \\<in> S\"\nshows \"convex S\"\n  unfolding convex_def\nproof (standard, standard)\n  fix z\n  assume \"z \\<in> convex_hull S\"\n  from this[unfolded convex_hull_def] obtain W c where \"finite W\" and WS: \"W \\<subseteq> S\"\n    and \"convex_lincomb c W z\" by auto\n  then show \"z \\<in> S\"\n  proof (induct W arbitrary: c z)\n    case empty\n    thus ?case unfolding convex_lincomb_def by auto\n  next\n    case (insert w W c z)\n    have \"convex_lincomb c (insert w W) z\" by fact\n    hence zl: \"z = lincomb c (insert w W)\" and nonneg: \"\\<And> w. w \\<in> W \\<Longrightarrow> 0 \\<le> c w\"\n      and cw: \"c w \\<ge> 0\"\n      and sum: \"sum c (insert w W) = 1\"\n      unfolding convex_lincomb_def nonneg_lincomb_def by auto\n    have zl: \"z = c w \\<cdot>\\<^sub>v w + lincomb c W\" unfolding zl\n      by (rule lincomb_insert2, insert insert S, auto)\n    have sum: \"c w + sum c W = 1\" unfolding sum[symmetric]\n      by (subst sum.insert, insert insert, auto)\n    have W: \"W \\<subseteq> carrier_vec n\" and w: \"w \\<in> carrier_vec n\" using S insert by auto\n    show ?case\n    proof (cases \"sum c W = 0\")\n      case True\n      with nonneg have c0: \"\\<And> w. w \\<in> W \\<Longrightarrow> c w = 0\"\n        using insert(1) sum_nonneg_eq_0_iff by auto\n      with sum have cw: \"c w = 1\" by auto\n      have lin0: \"lincomb c W = 0\\<^sub>v n\"\n        by (intro lincomb_zero W, insert c0, auto)\n      have \"z = w\" unfolding zl cw lin0 using w by simp\n      with insert(4) show ?thesis by simp\n    next\n      case False\n      have \"sum c W \\<ge> 0\" using nonneg by (metis sum_nonneg)\n      with False have pos: \"sum c W > 0\" by auto\n      define b where \"b = (\\<lambda> w. inverse (sum c W) * c w)\"\n      have \"convex_lincomb b W (lincomb b W)\"\n        unfolding convex_lincomb_def nonneg_lincomb_def b_def\n      proof (intro conjI refl)\n        show \"(\\<lambda>w. inverse (sum c W) * c w) ` W \\<subseteq> Collect ((\\<le>) 0)\" using nonneg pos by auto\n        show \"(\\<Sum>w\\<in>W. inverse (sum c W) * c w) = 1\" unfolding sum_distrib_left[symmetric] using False by auto\n      qed\n      from insert(3)[OF _ this] insert\n      have IH: \"lincomb b W \\<in> S\" by auto\n      have lin: \"lincomb c W = sum c W \\<cdot>\\<^sub>v lincomb b W\"\n        unfolding b_def\n        by (subst lincomb_smult[symmetric, OF W], rule lincomb_cong[OF _ W], insert False, auto)\n      from sum cw pos have sum: \"sum c W = 1 - c w\" and cw1: \"c w \\<le> 1\" by auto\n      show ?thesis unfolding zl lin unfolding sum\n        by (rule step[OF _ IH cw cw1], insert insert, auto)\n    qed\n  qed\nnext\n  show \"S \\<subseteq> convex_hull S\" using S by (rule set_in_convex_hull)\nqed\n\nlemma convex_hulls_are_convex: assumes \"A \\<subseteq> carrier_vec n\"\n  shows \"convex (convex_hull A)\"\n  by (intro convexI convex_hull_convex_sum convex_hull_carrier assms)\n\nlemma convex_hull_sum: assumes A: \"A \\<subseteq> carrier_vec n\" and B: \"B \\<subseteq> carrier_vec n\"\n  shows \"convex_hull (A + B) = convex_hull A + convex_hull B\"\nproof\n  note cA = convex_hull_carrier[OF A]\n  note cB = convex_hull_carrier[OF B]\n  have \"convex (convex_hull A + convex_hull B)\"\n  proof (intro convexI sum_carrier_vec convex_hull_carrier A B)\n    fix a :: 'a and x1 x2\n    assume \"x1 \\<in> convex_hull A + convex_hull B\" \"x2 \\<in> convex_hull A + convex_hull B\"\n    then obtain y1 y2 z1 z2 where\n      x12: \"x1 = y1 + z1\" \"x2 = y2 + z2\" and\n      y12: \"y1 \\<in> convex_hull A\" \"y2 \\<in> convex_hull A\" and\n      z12: \"z1 \\<in> convex_hull B\" \"z2 \\<in> convex_hull B\"\n      unfolding set_plus_def by auto\n    from y12 z12 cA cB have carr:\n      \"y1 \\<in> carrier_vec n\" \"y2 \\<in> carrier_vec n\"\n      \"z1 \\<in> carrier_vec n\" \"z2 \\<in> carrier_vec n\"\n      by auto\n    assume a: \"0 \\<le> a\" \"a \\<le> 1\"\n    have A: \"a \\<cdot>\\<^sub>v y1 + (1 - a) \\<cdot>\\<^sub>v y2 \\<in> convex_hull A\" using y12 a A by (metis convex_hull_convex_sum)\n    have B: \"a \\<cdot>\\<^sub>v z1 + (1 - a) \\<cdot>\\<^sub>v z2 \\<in> convex_hull B\" using z12 a B by (metis convex_hull_convex_sum)\n    have \"a \\<cdot>\\<^sub>v x1 + (1 - a) \\<cdot>\\<^sub>v x2 = (a \\<cdot>\\<^sub>v y1 + a \\<cdot>\\<^sub>v z1) + ((1 - a) \\<cdot>\\<^sub>v y2 + (1 - a) \\<cdot>\\<^sub>v z2)\" unfolding x12\n      using carr by (auto simp: smult_add_distrib_vec)\n    also have \"\\<dots> = (a \\<cdot>\\<^sub>v y1 + (1 - a) \\<cdot>\\<^sub>v y2) + (a \\<cdot>\\<^sub>v z1 + (1 - a) \\<cdot>\\<^sub>v z2)\" using carr\n      by (intro eq_vecI, auto)\n    finally show \"a \\<cdot>\\<^sub>v x1 + (1 - a) \\<cdot>\\<^sub>v x2 \\<in> convex_hull A + convex_hull B\"\n      using A B by auto\n  qed\n  from convex_convex_hull[OF this]\n  have id: \"convex_hull (convex_hull A + convex_hull B) = convex_hull A + convex_hull B\" .\n  show \"convex_hull (A + B) \\<subseteq> convex_hull A + convex_hull B\"\n    by (subst id[symmetric], rule convex_hull_mono[OF set_plus_mono2]; intro set_in_convex_hull A B)\n  show \"convex_hull A + convex_hull B \\<subseteq> convex_hull (A + B)\"\n  proof\n    fix x\n    assume \"x \\<in> convex_hull A + convex_hull B\"\n    then obtain y z where x: \"x = y + z\" and y: \"y \\<in> convex_hull A\" and z: \"z \\<in> convex_hull B\"\n      by (auto simp: set_plus_def)\n    from convex_hull_convex_hull_listD[OF A y] obtain ys where ysA: \"set ys \\<subseteq> A\" and\n      y: \"y \\<in> convex_hull_list ys\" by auto\n    from convex_hull_convex_hull_listD[OF B z] obtain zs where zsB: \"set zs \\<subseteq> B\" and\n      z: \"z \\<in> convex_hull_list zs\" by auto\n    from y[unfolded convex_hull_list_def convex_lincomb_list_def nonneg_lincomb_list_def]\n    obtain c where yid: \"y = lincomb_list c ys\"\n      and conv_c: \"(\\<forall>i<length ys. 0 \\<le> c i) \\<and> sum c {0..<length ys} = 1\"\n      by auto\n    from z[unfolded convex_hull_list_def convex_lincomb_list_def nonneg_lincomb_list_def]\n    obtain d where zid: \"z = lincomb_list d zs\"\n      and conv_d: \"(\\<forall>i<length zs. 0 \\<le> d i) \\<and> sum d {0..<length zs} = 1\"\n      by auto\n    from ysA A have ys: \"set ys \\<subseteq> carrier_vec n\" by auto\n    from zsB B have zs: \"set zs \\<subseteq> carrier_vec n\" by auto\n    have [intro, simp]: \"lincomb_list x ys \\<in> carrier_vec n\" for x using lincomb_list_carrier[OF ys] .\n    have [intro, simp]: \"lincomb_list x zs \\<in> carrier_vec n\" for x using lincomb_list_carrier[OF zs] .\n    have dim[simp]: \"dim_vec (lincomb_list d zs) = n\" by auto\n    from yid have y: \"y \\<in> carrier_vec n\" by auto\n    from zid have z: \"z \\<in> carrier_vec n\" by auto\n    {\n      fix x\n      assume \"x \\<in> set (map ((+) y) zs)\"\n      then obtain z where \"x = y + z\" and \"z \\<in> set zs\" by auto\n      then obtain j where j: \"j < length zs\" and x: \"x = y + zs ! j\" unfolding set_conv_nth by auto\n      hence mem: \"zs ! j \\<in> set zs\" by auto\n      hence zsj: \"zs ! j \\<in> carrier_vec n\" using zs by auto\n      let ?list = \"(map (\\<lambda> y. y + zs ! j) ys)\"\n      let ?set = \"set ?list\"\n      have set: \"?set \\<subseteq> carrier_vec n\" using ys A zsj by auto\n      have lin_map: \"lincomb_list c ?list \\<in> carrier_vec n\"\n        by (intro lincomb_list_carrier[OF set])\n      have \"y + (zs ! j) = lincomb_list c ?list\"\n        unfolding yid using zsj lin_map lincomb_list_index[OF _ set] lincomb_list_index[OF _ ys]\n        by (intro eq_vecI, auto simp: field_simps sum_distrib_right[symmetric] conv_c)\n      hence \"convex_lincomb_list c ?list (y + (zs ! j))\"\n        unfolding convex_lincomb_list_def nonneg_lincomb_list_def using conv_c by auto\n      hence \"y + (zs ! j) \\<in> convex_hull_list ?list\" unfolding convex_hull_list_def by auto\n      with finite_convex_hull_iff_convex_hull_list[OF set refl]\n      have \"(y + zs ! j) \\<in> convex_hull ?set\" by auto\n      also have \"\\<dots> \\<subseteq> convex_hull (A + B)\"\n        by (rule convex_hull_mono, insert mem ys ysA zsB, force simp: set_plus_def)\n      finally have \"x \\<in> convex_hull (A + B)\" unfolding x .\n    } note step1 = this\n    {\n      let ?list = \"map ((+) y) zs\"\n      let ?set = \"set ?list\"\n      have set: \"?set \\<subseteq> carrier_vec n\" using zs B y by auto\n      have lin_map: \"lincomb_list d ?list \\<in> carrier_vec n\"\n        by (intro lincomb_list_carrier[OF set])\n      have [simp]: \"i < n \\<Longrightarrow> (\\<Sum>j = 0..<length zs. d j * (y + zs ! j) $ i) =\n        (\\<Sum>j = 0..<length zs. d j * (y $ i + zs ! j $ i))\" for i\n        by (rule sum.cong, insert zs[unfolded set_conv_nth] y, auto)\n      have \"y + z = lincomb_list d ?list\"\n        unfolding zid using y zs lin_map lincomb_list_index[OF _ set] lincomb_list_index[OF _ zs]\n          set lincomb_list_carrier[OF zs, of d] zs[unfolded set_conv_nth]\n        by (intro eq_vecI, auto simp: field_simps sum_distrib_right[symmetric] conv_d)\n      hence \"convex_lincomb_list d ?list x\" unfolding x\n        unfolding convex_lincomb_list_def nonneg_lincomb_list_def using conv_d by auto\n      hence \"x \\<in> convex_hull_list ?list\" unfolding convex_hull_list_def by auto\n      with finite_convex_hull_iff_convex_hull_list[OF set refl]\n      have \"x \\<in> convex_hull ?set\" by auto\n      also have \"\\<dots> \\<subseteq> convex_hull (convex_hull (A + B))\"\n        by (rule convex_hull_mono, insert step1, auto)\n      also have \"\\<dots> = convex_hull (A + B)\"\n        by (rule convex_convex_hull[OF convex_hulls_are_convex], intro sum_carrier_vec A B)\n      finally show \"x \\<in> convex_hull (A + B)\" .\n    }\n  qed\nqed\n\nlemma convex_hull_in_cone:\n  \"convex_hull C \\<subseteq> cone C\"\n  unfolding convex_hull_def cone_def convex_lincomb_def finite_cone_def by auto\n\nlemma convex_cone:\n  assumes C: \"C \\<subseteq> carrier_vec n\"\n  shows \"convex (cone C)\"\n  unfolding convex_def\n  using convex_hull_in_cone set_in_convex_hull[OF cone_carrier[OF C]] cone_cone[OF C]\n  by blast\n\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/Convex_Hull.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681049901036, "lm_q2_score": 0.8418256412990657, "lm_q1q2_score": 0.7220911850691782}}
{"text": "(*  Title:      HOL/SMT_Examples/SMT_Tests.thy\n    Author:     Sascha Boehme, TU Muenchen\n*)\n\nsection {* Tests for the SMT binding *}\n\ntheory SMT_Tests\nimports Complex_Main\nbegin\n\nsmt_status\n\ntext {* Most examples are taken from various Isabelle theories and from HOL4. *}\n\n\nsection {* Propositional logic *}\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 {* First-order logic with equality *}\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 \\<longrightarrow> (\\<exists>y. P x \\<and> P 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. (\\<exists>y. P y) \\<longrightarrow> P x\"\n  \"(\\<exists>x. Q \\<longrightarrow> P x) \\<longleftrightarrow> (Q \\<longrightarrow> (\\<exists>x. P x))\"\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>z. P z \\<longrightarrow> (\\<forall>x. P x)\"\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 {* Guidance for quantifier heuristics: patterns *}\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 using [[smt_trace]] 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 {* Meta-logical connectives *}\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 {* Integers *}\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  \"(0::int) div 0 = 0\"\n  \"(x::int) div 0 = 0\"\n  \"(0::int) div 1 = 0\"\n  \"(1::int) div 1 = 1\"\n  \"(3::int) div 1 = 3\"\n  \"(x::int) div 1 = x\"\n  \"(0::int) div -1 = 0\"\n  \"(1::int) div -1 = -1\"\n  \"(3::int) div -1 = -3\"\n  \"(x::int) div -1 = -x\"\n  \"(0::int) div 3 = 0\"\n  \"(0::int) div -3 = 0\"\n  \"(1::int) div 3 = 0\"\n  \"(3::int) div 3 = 1\"\n  \"(5::int) div 3 = 1\"\n  \"(1::int) div -3 = -1\"\n  \"(3::int) div -3 = -1\"\n  \"(5::int) div -3 = -2\"\n  \"(-1::int) div 3 = -1\"\n  \"(-3::int) div 3 = -1\"\n  \"(-5::int) div 3 = -2\"\n  \"(-1::int) div -3 = 0\"\n  \"(-3::int) div -3 = 1\"\n  \"(-5::int) div -3 = 1\"\n  using [[z3_extensions]]\n  by smt+\n\nlemma\n  \"(0::int) mod 0 = 0\"\n  \"(x::int) mod 0 = x\"\n  \"(0::int) mod 1 = 0\"\n  \"(1::int) mod 1 = 0\"\n  \"(3::int) mod 1 = 0\"\n  \"(x::int) mod 1 = 0\"\n  \"(0::int) mod -1 = 0\"\n  \"(1::int) mod -1 = 0\"\n  \"(3::int) mod -1 = 0\"\n  \"(x::int) mod -1 = 0\"\n  \"(0::int) mod 3 = 0\"\n  \"(0::int) mod -3 = 0\"\n  \"(1::int) mod 3 = 1\"\n  \"(3::int) mod 3 = 0\"\n  \"(5::int) mod 3 = 2\"\n  \"(1::int) mod -3 = -2\"\n  \"(3::int) mod -3 = 0\"\n  \"(5::int) mod -3 = -1\"\n  \"(-1::int) mod 3 = 2\"\n  \"(-3::int) mod 3 = 0\"\n  \"(-5::int) mod 3 = 1\"\n  \"(-1::int) mod -3 = -1\"\n  \"(-3::int) mod -3 = 0\"\n  \"(-5::int) mod -3 = -2\"\n  \"x mod 3 < 3\"\n  \"(x mod 3 = x) \\<longrightarrow> (x < 3)\"\n  using [[z3_extensions]]\n  by smt+\n\nlemma\n  \"(x::int) = x div 1 * 1 + x mod 1\"\n  \"x = x div 3 * 3 + x mod 3\"\n  using [[z3_extensions]]\n  by smt+\n\nlemma\n  \"abs (x::int) \\<ge> 0\"\n  \"(abs x = 0) = (x = 0)\"\n  \"(x \\<ge> 0) = (abs x = x)\"\n  \"(x \\<le> 0) = (abs x = -x)\"\n  \"abs (abs x) = abs x\"\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> abs (x + y)\"\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> - abs x - abs y\"\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 {* Reals *}\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  \"(1/2 :: real) < 1\"\n  \"(1::real) / 3 = 1 / 3\"\n  \"(1::real) / -3 = - 1 / 3\"\n  \"(-1::real) / 3 = - 1 / 3\"\n  \"(-1::real) / -3 = 1 / 3\"\n  \"(x::real) / 1 = x\"\n  \"x > 0 \\<longrightarrow> x / 3 < x\"\n  \"x < 0 \\<longrightarrow> x / 3 > x\"\n  using [[z3_extensions]]\n  by smt+\n\nlemma\n  \"(3::real) * (x / 3) = x\"\n  \"(x * 3) / 3 = x\"\n  \"x > 0 \\<longrightarrow> 2 * x / 3 < x\"\n  \"x < 0 \\<longrightarrow> 2 * x / 3 > x\"\n  using [[z3_extensions]]\n  by smt+\n\nlemma\n  \"abs (x::real) \\<ge> 0\"\n  \"(abs x = 0) = (x = 0)\"\n  \"(x \\<ge> 0) = (abs x = x)\"\n  \"(x \\<le> 0) = (abs x = -x)\"\n  \"abs (abs x) = abs x\"\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> abs (x + y)\"\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> - abs x - abs y\"\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 {* Datatypes, Records, and Typedefs *}\n\nsubsection {* Without support by the SMT solver *}\n\nsubsubsection {* Algebraic datatypes *}\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 pair_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 pair_collapse list.sel(1,3) list.simps\n  by smt+\n\n\nsubsubsection {* Records *}\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  \"cy (p \\<lparr> cx := a \\<rparr>) = cy p\"\n  \"cx (p \\<lparr> cy := a \\<rparr>) = cx p\"\n  \"p \\<lparr> cx := 3 \\<rparr> \\<lparr> cy := 4 \\<rparr> = p \\<lparr> cy := 4 \\<rparr> \\<lparr> cx := 3 \\<rparr>\"\n  sorry\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 {* Type definitions *}\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 {* With support by the SMT solver (but without proofs) *}\n\nsubsubsection {* Algebraic datatypes *}\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 pair_collapse\n  using [[smt_oracle, z3_extensions]]\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)\n  using [[smt_oracle, z3_extensions]]\n  by smt+\n\nlemma\n  \"fst (hd [(a, b)]) = a\"\n  \"snd (hd [(a, b)]) = b\"\n  using fst_conv snd_conv pair_collapse list.sel(1,3)\n  using [[smt_oracle, z3_extensions]]\n  by smt+\n\n\nsubsubsection {* Records *}\n\nlemma\n  \"\\<lparr>cx = x, cy = y\\<rparr> = \\<lparr>cx = x', cy = y'\\<rparr> \\<Longrightarrow> x = x' \\<and> y = y'\"\n  using [[smt_oracle, z3_extensions]]\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  using [[smt_oracle, z3_extensions]]\n  by smt+\n\nlemma\n  \"cy (p \\<lparr> cx := a \\<rparr>) = cy p\"\n  \"cx (p \\<lparr> cy := a \\<rparr>) = cx p\"\n  \"p \\<lparr> cx := 3 \\<rparr> \\<lparr> cy := 4 \\<rparr> = p \\<lparr> cy := 4 \\<rparr> \\<lparr> cx := 3 \\<rparr>\"\n  using point.simps\n  using [[smt_oracle, z3_extensions]]\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 [[smt_oracle, z3_extensions]]\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  using [[smt_oracle, z3_extensions]]\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  sorry\n\nlemma\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  using point.simps bw_point.simps\n  using [[smt_oracle, z3_extensions]]\n  by smt\n\n\nsubsubsection {* Type definitions *}\n\nlemma\n  \"n0 \\<noteq> n1\"\n  \"plus' n1 n1 = n2\"\n  \"plus' n0 n2 = n2\"\n  using [[smt_oracle, z3_extensions]]\n  by (smt n0_def n1_def n2_def plus'_def)+\n\n\nsection {* Function updates *}\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 {* Sets *}\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\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/SMT_Examples/SMT_Tests.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869851639067, "lm_q2_score": 0.8244619263765706, "lm_q1q2_score": 0.7220530248837636}}
{"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\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]\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": "user7", "repo": "concrete-semantics", "sha": "5ddbd752550b3037d0d461d67a39d4f61c4548e5", "save_path": "github-repos/isabelle/user7-concrete-semantics", "path": "github-repos/isabelle/user7-concrete-semantics/concrete-semantics-5ddbd752550b3037d0d461d67a39d4f61c4548e5/BExp.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314647623016, "lm_q2_score": 0.815232489352, "lm_q1q2_score": 0.7219955436666292}}
{"text": "theory RmMultiset imports \"~~/src/HOL/Library/Multiset\" begin\n\n\ndefinition rm_mset :: \"'a \\<Rightarrow> 'a multiset \\<Rightarrow> 'a multiset\" where\n  \"rm_mset x M \\<equiv> M - replicate_mset (count M x) x\"\n\n\nlemma diff_id[rule_format]: \"A - B = A \\<longrightarrow> (\\<forall>a \\<in># A. a \\<notin># B)\"\n  apply(rule_tac M=B in multiset_induct)\n  apply(simp)\n  by (metis diff_empty disjunct_not_in multiset_inter_def)\n\n\nlemma rm_mset_idD[rule_format]: \"\\<forall>x. rm_mset x M = M \\<longrightarrow> x \\<notin># M\"\n  apply(unfold rm_mset_def)\n  apply(rule multiset_induct)\n  apply(simp)\n  apply(clarify)\n  apply(drule diff_id)\n  apply(assumption)\n  apply(erule notE)\n  apply(case_tac \"x = xa\")\n  apply(auto)\n  done\n\n\nlemma rm_mset_idI: \"x \\<notin># M \\<Longrightarrow> rm_mset x M = M\"\n  apply(unfold rm_mset_def)\n  apply(subst (asm) count_eq_zero_iff[symmetric])\n  apply(erule ssubst)\n  apply(subst replicate_mset_0)\n  apply(subst diff_empty)\n  apply(rule refl)\n  done\n\n\ntheorem rm_mset_id_iff: \"x \\<notin># M \\<longleftrightarrow> rm_mset x M = M\"\n  apply(rule iffI)\n  apply(erule rm_mset_idI)\n  apply(erule rm_mset_idD)\n  done\n\n\ntheorem rm_mset_plus_replicate_mset_count_cancel: \"(rm_mset x M) + replicate_mset (count M x) x = M\"\n  apply(unfold rm_mset_def)\n  by (meson count_le_replicate_mset_subset_eq less_imp_le not_le subset_mset.diff_add)\n\n\ntheorem nmem_rm_mset: \"x \\<notin># rm_mset x M\"\n  by (simp add: rm_mset_def in_diff_count)\n\n\ntheorem count_rm_set: \"count (rm_mset x M) x = (if x \\<in># M then 0 else count M x)\"\n  apply(case_tac \"x \\<in># M\")\n  apply(subst if_P)\n  apply(assumption)\n  apply(subst rm_mset_def)\n  apply(subst count_diff)\n  apply(subst count_replicate_mset)\n  apply(subst if_P)\n  apply(rule refl)\n  apply(rule diff_self_eq_0)\n  apply(subst if_not_P)\n  apply(assumption)\n  apply(subst (asm) rm_mset_id_iff)\n  apply(erule ssubst)\n  apply(rule refl)\n  done\nend", "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/RmMultiset.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314647623015, "lm_q2_score": 0.8152324871074608, "lm_q1q2_score": 0.7219955416787945}}
{"text": "theory Simulink\nimports Main  \nbegin\n\n(*fun Gain :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\" where\n  \"Gain x y = mult x y\"*)\nprimrec add :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\" where\n\"add 0 n = n\" |\n\"add (Suc m) n = Suc(add m n)\"\n\nprimrec mult :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\" where\n  \"mult 0 n = 0\" |\n  \"mult (Suc m) n = add (mult m n) m\"\n\nprimrec pow :: \"nat => nat => nat\" where\n  \"pow 0 x       = Suc 0\" | \n  \"pow (Suc n) x = mult x (pow n x)\"\n  \n  \ndefinition\n  threegains :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> nat\" where\n  \"threegains t x y z = t*x*y*z\"\ndeclare threegains_def[simp] \n\nprimrec feedback :: \"nat \\<Rightarrow> nat\" where\n  \"feedback 0 = Suc(0)\"|\n  \"feedback (Suc t) = (feedback t)*3\"\n\n  \ntheorem sum_of_naturals:\n  \"2 * (\\<Sum>i::nat=0..n. i) = n * (n + 1)\"\n  (is \"?P n\" is \"?S n = _\")\nproof (induct n)\n  show \"?P 0\" by simp\nnext\n  fix n have \"?S (n + 1) = ?S n + 2 * (n + 1)\"\n    by simp\n  assume \"?P n\"\n  also have \"\\<dots> + 2 * (n + 1) = (n + 1) * (n + 2)\"\n    by simp\n  finally show \"?P (Suc n)\"\n    by simp\nqed  \n  \nlemma th1: \"threegains 3 4 5 6 = 360\"\n  apply(simp)\n  done    \n\n(*\nlemma th3: \"feedback t = pow 3 t\"\n  apply(induct t)\n  apply(simp)\n  apply(auto)\n  apply(sym)  \ndone *)   \n(*\\<lbrakk> if foo then a \\<noteq> a else b \\<noteq> b \\<rbrakk>*)\n\n(*  \nlemma th2: \"\\<not>(t>5) \\<or> ((feedback t) > 200)\" (is \"?H(t)\" is \"?P(t)\\<or>?Q(t)\" is \"(?P(t))\\<or>(?F(t) > 200)\") \nproof(induct t) \n    case 0 show \"?P 0 \\<or> ?Q 0\" by simp\n  next \n    have b: \"?F (Suc(t)) \\<ge> ?F(t)\" by simp\n    assume a:\" ?F(t) > 200\"\n    from b and a have c: \"?F(Suc(t)) > 200\" by simp\n    from c have e: \"?Q(Suc(t))\" by simp    \n    assume d: \"?P(t) = False\"\n    from d have f:\"?P(Suc(t)) = False\" by simp\n    from f and e have g: \"?P(Suc(t))\\<or>?Q(Suc(t))\" by simp\n    from a and d and g have h: \"?P(t)\\<or>?Q(t) \\<Longrightarrow> ?P(Suc(t))\\<or>?Q(Suc(t))\" by simp \n    from a and d have \"?H(Suc(t))\" by simp   \n  qed\n*)    \nlemma th2: \"\\<not>(t>5) \\<or> ((feedback t) > 200)\"  \nproof (induct t) \n  case 0\n  show ?case by simp\nnext\n  case (Suc t)\n  thus ?case\n  proof\n    assume \"\\<not>t > 5\"\n    moreover have \"feedback 6 = 729\" by code_simp \n      -- \\<open>\"simp add: eval_nat_numeral\" would also work\\<close>\n    ultimately show ?thesis\n      by (cases \"t = 5\") auto\n  next\n    assume \"feedback t > 200\"\n    thus ?thesis by simp\n  qed\nqed    \n  \nlemma th3: \"\\<not>(t>5) \\<or> ((feedback t) > 200)\"  \nproof (induct t) \n  case (Suc t)\n  moreover have \"feedback 6 = 729\" by code_simp\n  ultimately show ?case by (cases \"t = 5\") auto\nqed simp_all  \n  ", "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/Simulink.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122163480667, "lm_q2_score": 0.7956581073313275, "lm_q1q2_score": 0.7219103208180947}}
{"text": "section \\<open>Abstract Dijkstra Algorithm\\<close>\ntheory Dijkstra_Abstract\nimports Directed_Graph\nbegin\n\nsubsection \\<open>Abstract Algorithm\\<close>\n\ntype_synonym 'v estimate = \"'v \\<Rightarrow> enat\"\ntext \\<open>We fix a start node and a weighted graph\\<close>\nlocale Dijkstra = WGraph w for w :: \"('v) wgraph\" +\n  fixes s :: 'v\nbegin\n\ntext \\<open>Relax all outgoing edges of node \\<open>u\\<close>\\<close>\ndefinition relax_outgoing :: \"'v \\<Rightarrow> 'v estimate \\<Rightarrow> 'v estimate\"\n  where \"relax_outgoing u D \\<equiv> \\<lambda>v. min (D v) (D u + w (u,v))\"\n\ntext \\<open>Initialization\\<close>\ndefinition \"initD \\<equiv> (\\<lambda>_. \\<infinity>)(s:=0)\"\ndefinition \"initS \\<equiv> {}\"  \n  \n      \ntext \\<open>Relaxing will never increase estimates\\<close>\nlemma relax_mono: \"relax_outgoing u D v \\<le> D v\"\n  by (auto simp: relax_outgoing_def)\n\n\ndefinition \"all_dnodes \\<equiv> Set.insert s { v . \\<exists>u. w (u,v)\\<noteq>\\<infinity> }\"\ndefinition \"unfinished_dnodes S \\<equiv> all_dnodes - S \"\n\nlemma unfinished_nodes_subset: \"unfinished_dnodes S \\<subseteq> all_dnodes\"\n  by (auto simp: unfinished_dnodes_def)\n\nend  \n\nsubsubsection \\<open>Invariant\\<close>\ntext \\<open>The invariant is defined as locale\\<close>\n  \nlocale Dijkstra_Invar = Dijkstra w s for w and s :: 'v +\n  fixes D :: \"'v estimate\" and S :: \"'v set\"\n  assumes upper_bound: \\<open>\\<delta> s u \\<le> D u\\<close> \\<comment> \\<open>\\<open>D\\<close> is a valid estimate\\<close>\n  assumes s_in_S: \\<open>s\\<in>S \\<or> (D=(\\<lambda>_. \\<infinity>)(s:=0) \\<and> S={})\\<close> \\<comment> \\<open>The start node is \n    finished, or we are in initial state\\<close>  \n  assumes S_precise: \"u\\<in>S \\<Longrightarrow> D u = \\<delta> s u\" \\<comment> \\<open>Finished nodes have precise \n    estimate\\<close>\n  assumes S_relaxed: \\<open>v\\<in>S \\<Longrightarrow> D u \\<le> \\<delta> s v + w (v,u)\\<close> \\<comment> \\<open>Outgoing edges of \n    finished nodes have been relaxed, using precise distance\\<close>\nbegin\n\nabbreviation (in Dijkstra) \"D_invar \\<equiv> Dijkstra_Invar w s\"\n\ntext \\<open>The invariant holds for the initial state\\<close>  \n\n\n\ntext \\<open>Relaxing some edges maintains the upper bound property\\<close>    \nlemma maintain_upper_bound: \"\\<delta> s u \\<le> (relax_outgoing v D) u\"\n  apply (clarsimp simp: relax_outgoing_def upper_bound split: prod.splits)\n  using triangle upper_bound add_right_mono dual_order.trans by blast\n\ntext \\<open>Relaxing edges will not affect nodes with already precise estimates\\<close>\nlemma relax_precise_id: \"D v = \\<delta> s v \\<Longrightarrow> relax_outgoing u D v = \\<delta> s v\"\n  using maintain_upper_bound upper_bound relax_mono\n  by (metis antisym)\n\ntext \\<open>In particular, relaxing edges will not affect finished nodes\\<close>  \nlemma relax_finished_id: \"v\\<in>S \\<Longrightarrow> relax_outgoing u D v = D v\"\n  by (simp add: S_precise relax_precise_id)  \n      \ntext \\<open>The least (finite) estimate among all nodes \\<open>u\\<close> not in \\<open>S\\<close> is already precise.\n  This will allow us to add the node \\<open>u\\<close> to \\<open>S\\<close>. \\<close>\nlemma maintain_S_precise_and_connected:  \n  assumes UNS: \"u\\<notin>S\"\n  assumes MIN: \"\\<forall>v. v\\<notin>S \\<longrightarrow> D u \\<le> D v\"\n  shows \"D u = \\<delta> s u\"\n  text \\<open>We start with a case distinction whether we are in the first \n    step of the loop, where we process the start node, or in subsequent steps,\n    where the start node has already been finished.\\<close>\nproof (cases \"u=s\")  \n  assume [simp]: \"u=s\" \\<comment> \\<open>First step of loop\\<close>\n  then show ?thesis using \\<open>u\\<notin>S\\<close> s_in_S by simp\nnext\n  assume \\<open>u\\<noteq>s\\<close> \\<comment> \\<open>Later step of loop\\<close>\n  text \\<open>The start node has already been finished\\<close>   \n  with s_in_S MIN have \\<open>s\\<in>S\\<close> apply clarsimp using infinity_ne_i0 by metis\n  \n  show ?thesis\n  text \\<open>Next, we handle the case that \\<open>u\\<close> is unreachable.\\<close>\n  proof (cases \\<open>\\<delta> s u < \\<infinity>\\<close>)\n    assume \"\\<not>(\\<delta> s u < \\<infinity>)\" \\<comment> \\<open>Node is unreachable (infinite distance)\\<close>\n    text \\<open>By the upper-bound property, we get \\<open>D u = \\<delta> s u = \\<infinity>\\<close>\\<close>\n    then show ?thesis using upper_bound[of u] by auto\n  next\n    assume \"\\<delta> s u < \\<infinity>\" \\<comment> \\<open>Main case: Node has finite distance\\<close>\n \n    text \\<open>Consider a shortest path from \\<open>s\\<close> to \\<open>u\\<close>\\<close>        \n    obtain p where \"path s p u\" and DSU: \"\\<delta> s u = sum_list p\"\n      by (rule obtain_shortest_path)\n    text \\<open>It goes from inside \\<open>S\\<close> to outside \\<open>S\\<close>, so there must be an edge at the border.\n      Let \\<open>(x,y)\\<close> be such an edge, with \\<open>x\\<in>S\\<close> and \\<open>y\\<notin>S\\<close>.\\<close>\n    from find_leave_edgeE[OF \\<open>path s p u\\<close> \\<open>s\\<in>S\\<close> \\<open>u\\<notin>S\\<close>] obtain p1 x y p2 where\n      [simp]: \"p = p1 @ w (x, y) # p2\" \n      and DECOMP: \"x \\<in> S\" \"y \\<notin> S\" \"path s p1 x\" \"path y p2 u\" .\n    text \\<open>As prefixes of shortest paths are again shortest paths, the shortest \n          path to \\<open>y\\<close> ends with edge \\<open>(x,y)\\<close> \\<close>  \n    have DSX: \"\\<delta> s x = sum_list p1\" and DSY: \"\\<delta> s y = \\<delta> s x + w (x, y)\"\n      using shortest_path_prefix[of s p1 x \"w (x,y)#p2\" u] \n        and shortest_path_prefix[of s \"p1@[w (x,y)]\" y p2 u]\n        and \\<open>\\<delta> s u < \\<infinity>\\<close> DECOMP \n        by (force simp: DSU)+\n    text \\<open>Upon adding \\<open>x\\<close> to \\<open>S\\<close>, this edge has been relaxed with the precise\n       estimate for \\<open>x\\<close>. At this point the estimate for \\<open>y\\<close> has become \n       precise, too\\<close>  \n    with \\<open>x\\<in>S\\<close> have \"D y = \\<delta> s y\"  \n      by (metis S_relaxed antisym_conv upper_bound)\n    moreover text \\<open>The shortest path to \\<open>y\\<close> is a prefix of that to \\<open>u\\<close>, thus \n      it shorter or equal\\<close>\n    have \"\\<dots> \\<le> \\<delta> s u\" using DSU by (simp add: DSX DSY)\n    moreover text \\<open>The estimate for \\<open>u\\<close> is an upper bound\\<close>\n    have \"\\<dots> \\<le> D u\" using upper_bound by (auto)\n    moreover text \\<open>\\<open>u\\<close> was a node with smallest estimate\\<close>\n    have \"\\<dots> \\<le> D y\" using \\<open>u\\<notin>S\\<close> \\<open>y\\<notin>S\\<close> MIN by auto\n    ultimately text \\<open>This closed a cycle in the inequation chain. Thus, by \n      antisymmetry, all items are equal. In particular, \\<open>D u = \\<delta> s u\\<close>, qed.\\<close>\n    show \"D u = \\<delta> s u\" by simp\n  qed    \nqed\n  \ntext \\<open>A step of Dijkstra's algorithm maintains the invariant.\n  More precisely, in a step of Dijkstra's algorithm, \n  we pick a node \\<open>u\\<notin>S\\<close> with least finite estimate, relax the outgoing \n  edges of \\<open>u\\<close>, and add \\<open>u\\<close> to \\<open>S\\<close>.\\<close>    \ntheorem maintain_D_invar:\n  assumes UNS: \"u\\<notin>S\"\n  assumes UNI: \"D u < \\<infinity>\"\n  assumes MIN: \"\\<forall>v. v\\<notin>S \\<longrightarrow> D u \\<le> D v\"\n  shows \"D_invar (relax_outgoing u D) (Set.insert u S)\"\n  apply (cases \\<open>s\\<in>S\\<close>)\n  subgoal\n    apply (unfold_locales)\n    subgoal by (simp add: maintain_upper_bound)\n    subgoal by simp\n    subgoal \n      using maintain_S_precise_and_connected[OF UNS MIN] S_precise        \n      by (auto simp: relax_precise_id) \n    subgoal\n      using maintain_S_precise_and_connected[OF UNS MIN]\n      by (auto simp: relax_outgoing_def S_relaxed min.coboundedI1)\n    done\n  subgoal\n    apply unfold_locales\n    using s_in_S UNI distance_direct \n    by (auto simp: relax_outgoing_def split: if_splits)\n  done\n  \n\ntext \\<open>When the algorithm is finished, i.e., when there are \n  no unfinished nodes with finite estimates left,\n  then all estimates are accurate.\\<close>  \nlemma invar_finish_imp_correct:\n  assumes F: \"\\<forall>u. u\\<notin>S \\<longrightarrow> D u = \\<infinity>\"\n  shows \"D u = \\<delta> s u\"\nproof (cases \"u\\<in>S\")\n  assume \"u\\<in>S\" text \\<open>The estimates of finished nodes are accurate\\<close>\n  then show ?thesis using S_precise by simp\nnext\n  assume \\<open>u\\<notin>S\\<close> text \\<open>\\<open>D u\\<close> is minimal, and minimal estimates are precise\\<close>\n  then show ?thesis \n    using F maintain_S_precise_and_connected[of u] by auto\n  \nqed  \n  \n  \ntext \\<open>A step decreases the set of unfinished nodes.\\<close>\nlemma unfinished_nodes_decr:\n  assumes UNS: \"u\\<notin>S\"\n  assumes UNI: \"D u < \\<infinity>\"\n  shows \"unfinished_dnodes (Set.insert u S) \\<subset> unfinished_dnodes S\"\nproof -\n  text \\<open>There is a path to \\<open>u\\<close>\\<close>\n  from UNI have \"\\<delta> s u < \\<infinity>\" using upper_bound[of u] leD by fastforce\n  \n  text \\<open>Thus, \\<open>u\\<close> is among \\<open>all_dnodes\\<close>\\<close>\n  have \"u\\<in>all_dnodes\" \n  proof -\n    obtain p where \"path s p u\" \"sum_list p < \\<infinity>\"\n      apply (rule obtain_shortest_path[of s u])\n      using \\<open>\\<delta> s u < \\<infinity>\\<close> by auto\n    with \\<open>u\\<notin>S\\<close> show ?thesis \n      apply (cases p rule: rev_cases) \n      by (auto simp: Dijkstra.all_dnodes_def)\n  qed\n  text \\<open>Which implies the proposition\\<close>\n  with \\<open>u\\<notin>S\\<close> show ?thesis by (auto simp: unfinished_dnodes_def)\nqed\n  \n        \nend  \n\n\nsubsection \\<open>Refinement by Priority Map and Map\\<close>\ntext \\<open>\n  In a second step, we implement \\<open>D\\<close> and \\<open>S\\<close> by a priority map \\<open>Q\\<close> and a map \\<open>V\\<close>.\n  Both map nodes to finite weights, where \\<open>Q\\<close> maps unfinished nodes, and \\<open>V\\<close> \n  maps finished nodes.\n\n  Note that this implementation is slightly non-standard: \n  In the standard implementation, \\<open>Q\\<close> contains also unfinished nodes with \n  infinite weight.\n  \n  We chose this implementation because it avoids enumerating all nodes of \n  the graph upon initialization of \\<open>Q\\<close>.\n  However, on relaxing an edge to a node not in \\<open>Q\\<close>, we require an extra \n  lookup to check whether the node is finished. \n\\<close>  \n\nsubsubsection \\<open>Implementing \\<open>enat\\<close> by Option\\<close>\n\ntext \\<open>Our maps are functions to \\<open>nat option\\<close>,which are interpreted as \\<open>enat\\<close>,\n  \\<open>None\\<close> being \\<open>\\<infinity>\\<close>\\<close>\n\nfun enat_of_option :: \"nat option \\<Rightarrow> enat\" where\n  \"enat_of_option None = \\<infinity>\" \n| \"enat_of_option (Some n) = enat n\"  \n  \nlemma enat_of_option_inj[simp]: \"enat_of_option x = enat_of_option y \\<longleftrightarrow> x=y\"\n  by (cases x; cases y; simp)\n\nlemma enat_of_option_simps[simp]:\n  \"enat_of_option x = enat n \\<longleftrightarrow> x = Some n\"\n  \"enat_of_option x = \\<infinity> \\<longleftrightarrow> x = None\"\n  \"enat n = enat_of_option x \\<longleftrightarrow> x = Some n\"\n  \"\\<infinity> = enat_of_option x \\<longleftrightarrow> x = None\"\n  by (cases x; auto; fail)+\n  \nlemma enat_of_option_le_conv: \n  \"enat_of_option m \\<le> enat_of_option n \\<longleftrightarrow> (case (m,n) of \n      (_,None) \\<Rightarrow> True\n    | (Some a, Some b) \\<Rightarrow> a\\<le>b\n    | (_, _) \\<Rightarrow> False\n  )\"\n  by (auto split: option.split)\n\n  \n  \nsubsubsection \\<open>Implementing \\<open>D,S\\<close> by Priority Map and Map\\<close>\ncontext Dijkstra begin\n\ntext \\<open>We define a coupling relation, that connects the concrete with the \n  abstract data. \\<close>\ndefinition \"coupling Q V D S \\<equiv> \n  D = enat_of_option o (V ++ Q)\n\\<and> S = dom V\n\\<and> dom V \\<inter> dom Q = {}\"\n\ntext \\<open>Note that our coupling relation is functional.\\<close>\n(* TODO: Why not use functions instead? *)\nlemma coupling_fun: \"coupling Q V D S \\<Longrightarrow> coupling Q V D' S' \\<Longrightarrow> D'=D \\<and> S'=S\"\n  by (auto simp: coupling_def)\n\ntext \\<open>The concrete version of the invariant.\\<close>  \ndefinition \"D_invar' Q V \\<equiv>\n  \\<exists>D S. coupling Q V D S \\<and> D_invar D S\"\n\n  \ntext \\<open>Refinement of \\<open>relax-outgoing\\<close>\\<close>\n\ndefinition \"relax_outgoing' u du V Q v \\<equiv> \n  case w (u,v) of\n    \\<infinity> \\<Rightarrow> Q v\n  | enat d \\<Rightarrow> (case Q v of\n      None \\<Rightarrow> if v\\<in>dom V then None else Some (du+d)\n    | Some d' \\<Rightarrow> Some (min d' (du+d)))\n\"\n\n  \ntext \\<open>A step preserves the coupling relation.\\<close>\nlemma (in Dijkstra_Invar) coupling_step:\n  assumes C: \"coupling Q V D S\"\n  assumes UNS: \"u\\<notin>S\"\n  assumes UNI: \"D u = enat du\"\n  \n  shows \"coupling \n    ((relax_outgoing' u du V Q)(u:=None)) (V(u\\<mapsto>du)) \n    (relax_outgoing u D) (Set.insert u S)\"\n  using C unfolding coupling_def \nproof (intro ext conjI; elim conjE)\n  assume \\<alpha>: \"D = enat_of_option \\<circ> V ++ Q\" \"S = dom V\" \n     and DD: \"dom V \\<inter> dom Q = {}\"\n   \n  show \"Set.insert u S = dom (V(u \\<mapsto> du))\"   \n    by (auto simp: \\<alpha>)\n     \n  have [simp]: \"Q u = Some du\" \"V u = None\" \n    using DD UNI UNS by (auto simp: \\<alpha>)\n    \n  from DD \n  show \"dom (V(u \\<mapsto> du)) \\<inter> dom ((relax_outgoing' u du V Q)(u := None)) = {}\"\n    by (auto 0 3 \n          simp: relax_outgoing'_def dom_def \n          split: if_splits enat.splits option.splits)\n  \n  fix v\n  \n  show \"relax_outgoing u D v \n    = (enat_of_option \\<circ> V(u \\<mapsto> du) ++ (relax_outgoing' u du V Q)(u := None)) v\"\n  proof (cases \"v\\<in>S\")\n    case True\n    then show ?thesis using DD\n      apply (simp add: relax_finished_id)\n      by (auto \n        simp: relax_outgoing'_def map_add_apply \\<alpha> min_def\n        split: option.splits enat.splits)\n  next\n    case False\n    then show ?thesis \n      by (auto \n        simp: relax_outgoing_def relax_outgoing'_def map_add_apply \\<alpha> min_def\n        split: option.splits enat.splits)\n  qed\nqed    \n  \ntext \\<open>Refinement of initial state\\<close>\ndefinition \"initQ \\<equiv> Map.empty(s\\<mapsto>0)\"\ndefinition \"initV \\<equiv> Map.empty\"\n  \nlemma coupling_init:\n  \"coupling initQ initV initD initS\"    \n  unfolding coupling_def initD_def initQ_def initS_def initV_def\n  by (auto \n    simp: coupling_def relax_outgoing_def map_add_apply enat_0 \n    split: option.split enat.split\n    del: ext intro!: ext)\n  \nlemma coupling_cond:\n  assumes \"coupling Q V D S\"\n  shows \"(Q = Map.empty) \\<longleftrightarrow> (\\<forall>u. u\\<notin>S \\<longrightarrow> D u = \\<infinity>)\"\n  using assms\n  by (fastforce simp add: coupling_def)\n\n  \ntext \\<open>Termination argument: Refinement of unfinished nodes.\\<close>  \ndefinition \"unfinished_dnodes' V \\<equiv> unfinished_dnodes (dom V)\"\n\nlemma coupling_unfinished: \n  \"coupling Q V D S \\<Longrightarrow> unfinished_dnodes' V = unfinished_dnodes S\"\n  by (auto simp: coupling_def unfinished_dnodes'_def unfinished_dnodes_def)\n\nsubsubsection \\<open>Implementing graph by successor list\\<close>  \n\ndefinition \"relax_outgoing'' l du V Q = fold (\\<lambda>(d,v) Q.\n  case Q v of None \\<Rightarrow> if v\\<in>dom V then Q else Q(v\\<mapsto>du+d)\n            | Some d' \\<Rightarrow> Q(v\\<mapsto>min (du+d) d')) l Q\"\n\n\nlemma relax_outgoing''_refine:\n  assumes \"set l = {(d,v). w (u,v) = enat d}\"  \n  shows \"relax_outgoing'' l du V Q = relax_outgoing' u du V Q\"\nproof\n  fix v\n  \n  have aux1:\n     \"relax_outgoing'' l du V Q v \n     = (if v\\<in>snd`set l then relax_outgoing' u du V Q v else Q v)\"\n  if \"set l \\<subseteq> {(d,v). w (u,v) = enat d}\"\n    using that\n    apply (induction l arbitrary: Q v)\n    by (auto \n      simp: relax_outgoing''_def relax_outgoing'_def image_iff\n      split!: if_splits option.splits)\n  \n  have aux2:  \n    \"relax_outgoing' u du V Q v = Q v\" if \"w (u,v) = \\<infinity>\"\n    using that by (auto simp: relax_outgoing'_def)\n  \n  show \"relax_outgoing'' l du V Q v = relax_outgoing' u du V Q v\"\n    using aux1\n    apply (cases \"w (u,v)\")\n    by (all \\<open>force simp: aux2 assms\\<close>)\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/Prim_Dijkstra_Simple/Dijkstra_Abstract.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9073122188543454, "lm_q2_score": 0.7956581024858786, "lm_q1q2_score": 0.7219103184159007}}
{"text": "section \\<open>The Pointwise Less-Than Relation Between Two Sets\\<close>\n\ntheory Nash_Extras\n  imports \"HOL-Library.Ramsey\" \"HOL-Library.Countable_Set\"\n\nbegin\n\ndefinition less_sets :: \"['a::order set, 'a::order set] \\<Rightarrow> bool\" (infixr \"\\<lless>\" 50)\n    where \"A \\<lless> B \\<equiv> \\<forall>x\\<in>A. \\<forall>y\\<in>B. x < y\"\n\nlemma less_sets_empty[iff]: \"S \\<lless> {}\" \"{} \\<lless> T\"\n  by (auto simp: less_sets_def)\n\nlemma less_setsD: \"\\<lbrakk>A \\<lless> B; a \\<in> A; b \\<in> B\\<rbrakk> \\<Longrightarrow> a < b\"\n  by (auto simp: less_sets_def)\n\nlemma less_sets_irrefl [simp]: \"A \\<lless> A \\<longleftrightarrow> A = {}\"\n  by (auto simp: less_sets_def)\n\nlemma less_sets_trans: \"\\<lbrakk>A \\<lless> B; B \\<lless> C; B \\<noteq> {}\\<rbrakk> \\<Longrightarrow> A \\<lless> C\"\n  unfolding less_sets_def using less_trans by blast\n\nlemma less_sets_weaken1: \"\\<lbrakk>A' \\<lless> B; A \\<subseteq> A'\\<rbrakk> \\<Longrightarrow> A \\<lless> B\"\n  by (auto simp: less_sets_def)\n\nlemma less_sets_weaken2: \"\\<lbrakk>A \\<lless> B'; B \\<subseteq> B'\\<rbrakk> \\<Longrightarrow> A \\<lless> B\"\n  by (auto simp: less_sets_def)\n\nlemma less_sets_imp_disjnt: \"A \\<lless> B \\<Longrightarrow> disjnt A B\"\n  by (auto simp: less_sets_def disjnt_def)\n\nlemma less_sets_UN1: \"less_sets (\\<Union>\\<A>) B \\<longleftrightarrow> (\\<forall>A\\<in>\\<A>. A \\<lless> B)\"\n  by (auto simp: less_sets_def)\n\nlemma less_sets_UN2: \"less_sets A (\\<Union> \\<B>) \\<longleftrightarrow> (\\<forall>B\\<in>\\<B>. A \\<lless> B)\"\n  by (auto simp: less_sets_def)\n\nlemma less_sets_Un1: \"less_sets (A \\<union> A') B \\<longleftrightarrow> A \\<lless> B \\<and> A' \\<lless> B\"\n  by (auto simp: less_sets_def)\n\nlemma less_sets_Un2: \"less_sets A (B \\<union> B') \\<longleftrightarrow> A \\<lless> B \\<and> A \\<lless> B'\"\n  by (auto simp: less_sets_def)\n\nlemma strict_sorted_imp_less_sets:\n  \"strict_sorted (as @ bs) \\<Longrightarrow> (list.set as) \\<lless> (list.set bs)\"\n  by (simp add: less_sets_def sorted_wrt_append)\n\nlemma Sup_nat_less_sets_singleton:\n  fixes n::nat\n  assumes \"Sup T < n\" \"finite T\"\n  shows \"less_sets T {n}\"\n  using assms Max_less_iff\n  by (auto simp: Sup_nat_def less_sets_def split: if_split_asm)\n  \nend\n\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/Nash_Williams/Nash_Extras.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637648915617, "lm_q2_score": 0.8397339756938818, "lm_q1q2_score": 0.7218888710523615}}
{"text": "(*  Title:      Depth-First Search\n    Author:     Toshiaki Nishihara and Yasuhiko Minamide\n    Maintainer: Yasuhiko Minamide <minamide at cs.tsukuba.ac.jp>\n*)\n\nsection \"Depth-First Search\"\n\ntheory DFS\nimports Main \"Eval_Base.Eval_Base\"\nbegin\n\nsubsection \"Definition of Graphs\"\n\ntypedecl node \ntype_synonym graph = \"(node * node) list\"\n\nprimrec nexts :: \"[graph, node] \\<Rightarrow> node list\"\nwhere\n  \"nexts [] n = []\"\n| \"nexts (e#es) n = (if fst e = n then snd e # nexts es n else nexts es n)\"\n\ndefinition nextss :: \"[graph, node list] \\<Rightarrow> node set\"\n  where \"nextss g xs = set g `` set xs\"\n\n\n\nlemma nextss_Cons: \"nextss g (x#xs) = set (nexts g x) \\<union> nextss g xs\" \n  unfolding nextss_def by (auto simp add:Image_def nexts_set)\n\ndefinition reachable :: \"[graph, node list] \\<Rightarrow> node set\"\n  where \"reachable g xs = (set g)\\<^sup>* `` set xs\"\n\n\nsubsection \"Depth-First Search with Stack\" \n\ndefinition nodes_of :: \"graph \\<Rightarrow> node set\"\n  where \"nodes_of g = set (map fst g @ map snd g)\"\n\n\n\nlemma [simp]: \"finite (nodes_of g - set ys)\"  \nproof(rule finite_subset)\n  show \"finite (nodes_of g)\"\n    by (auto simp add: nodes_of_def)\nqed (auto)\n\nfunction\n  dfs :: \"graph \\<Rightarrow> node list \\<Rightarrow> node list \\<Rightarrow> node list\"\nwhere\n  dfs_base: \"dfs g [] ys = ys\"\n| dfs_inductive: \"dfs g (x#xs) ys = (if List.member ys x then dfs g xs ys \n                        else dfs g (nexts g x@xs) (x#ys))\"\nby pat_completeness auto\n\ntermination\napply (relation \"inv_image (finite_psubset <*lex*> less_than)  \n                   (\\<lambda>(g,xs,ys). (nodes_of g - set ys, size xs))\")\napply auto[1]\napply (simp_all add: finite_psubset_def)\nby (case_tac  \"x \\<in> nodes_of g\") (auto simp add: List.member_def)\n\ntext \\<open>\n  \\begin{itemize}\n  \\item The second argument of \\isatext{\\isastyle{dfs}} is a stack of nodes that will be\n  visited.\n  \\item The third argument of \\isatext{\\isastyle{dfs}} is a list of nodes that have\n  been visited already.\n  \\end{itemize}\n\\<close>\n\n\nsubsection \"Depth-First Search with Nested-Recursion\"\n\nfunction\n  dfs2 :: \"graph \\<Rightarrow> node list \\<Rightarrow> node list \\<Rightarrow> node list\"\nwhere\n  \"dfs2 g [] ys = ys\"\n|  dfs2_inductive: \n          \"dfs2 g (x#xs) ys = (if List.member ys x then dfs2 g xs ys \n                               else dfs2 g xs (dfs2 g (nexts g x) (x#ys)))\"\nby pat_completeness auto\n\nlemma dfs2_invariant: \"dfs2_dom (g, xs, ys) \\<Longrightarrow> set ys \\<subseteq> set (dfs2 g xs ys)\"\napply2 (induct g xs ys rule: dfs2.pinduct) by(force simp add: dfs2.psimps)+\n\ntermination dfs2\napply (relation \"inv_image (finite_psubset <*lex*> less_than)  \n                   (\\<lambda>(g,xs,ys). (nodes_of g - set ys, size xs))\")\napply auto[1]\napply (simp_all add: finite_psubset_def)\napply (case_tac  \"x \\<in> nodes_of g\") \napply (auto simp add: List.member_def)[2]\nby (insert dfs2_invariant) force\n\n(*lemma dfs2_induct[induct type]:\n  assumes B: \"\\<And>g ys. P g [] ys\" and\n  H: \"\\<And>g x xs ys.\n        \\<lbrakk>\\<not> x mem ys \\<longrightarrow> P g xs (dfs2 (g, nexts g x, x # ys));\n         \\<not> x mem ys \\<longrightarrow> P g (nexts g x) (x # ys); x mem ys \\<longrightarrow> P g xs ys\\<rbrakk>\n         \\<Longrightarrow> P g (x # xs) ys\"\n  shows \"P u v w\"\n\nproof (induct u v w rule: dfs2.induct)\n  case 1 show ?case by (rule B)\nnext\n  case (2 g x xs ys)\n  show ?case\n  proof (rule H)\n    show \"\\<not> x mem ys \\<longrightarrow> P g xs (dfs2 (g, nexts g x, x # ys))\"\n    proof \n      assume *: \"\\<not> x mem ys\"\n      have \"set (x#ys) \\<subseteq> set (dfs2 (g, nexts g x, x # ys))\"\n        by (rule dfs2_inv)\n      with 2 * show \"P g xs (dfs2 (g, nexts g x, x # ys))\"\n        by auto\n    qed\n  qed (rule 2)+\nqed\n*)\n\nlemma dfs_app: \"dfs g (xs@ys) zs = dfs g ys (dfs g xs zs)\"\n  apply2 (induct g xs zs rule: dfs.induct) by auto\n\nlemma \"dfs2 g xs ys = dfs g xs ys\" \n  apply2 (induct g xs ys rule: dfs2.induct) by(auto simp add: dfs_app)\n\n\nsubsection \"Basic Properties\"\n\nlemma visit_subset_dfs: \"set ys \\<subseteq> set (dfs g xs ys)\"\n  apply2 (induct g xs ys rule: dfs.induct) by auto\n\nlemma next_subset_dfs: \"set xs \\<subseteq> set (dfs g xs ys)\"\nproof2(induct g xs ys rule:dfs.induct)\n  case(2 g x xs ys) \n  show ?case\n  proof(cases \"x \\<in> set ys\")\n    case True\n    have \"set ys \\<subseteq> set (dfs g xs ys)\"\n      by (rule visit_subset_dfs)\n    with 2 and True show ?thesis\n      by (auto simp add: List.member_def)\n  next\n    case False\n    have \"set (x#ys) \\<subseteq> set (dfs g (nexts g x @ xs) (x#ys))\"\n      by(rule visit_subset_dfs)\n    with 2 and False show ?thesis\n      by (auto simp add: List.member_def)\n  qed\nqed(simp)\n\n\nlemma nextss_closed_dfs'[rule_format]: \n \"nextss g ys \\<subseteq> set xs \\<union> set ys \\<longrightarrow> nextss g (dfs g xs ys) \\<subseteq> set (dfs g xs ys)\"\n  apply2 (induct g xs ys rule:dfs.induct) by(auto simp add:nextss_Cons List.member_def)\n\nlemma nextss_closed_dfs: \"nextss g (dfs g xs []) \\<subseteq> set (dfs g xs [])\"\n  by (rule nextss_closed_dfs', simp add: nextss_def)\n\nlemma Image_closed_trancl: assumes \"r `` X \\<subseteq> X\" shows \"r\\<^sup>* `` X = X\"\nproof\n  show \"r\\<^sup>* `` X \\<subseteq> X\"\n  proof -\n    {\n      fix x y\n      assume y: \"y \\<in> X\"\n      assume \"(y,x) \\<in> r\\<^sup>*\"\n      then have \"x \\<in> X\"\n        apply2 (induct) by(insert assms y, auto simp add: Image_def)\n    }\n    then show ?thesis unfolding Image_def by auto\n  qed\nqed auto\n\nlemma reachable_closed_dfs: \"reachable g xs \\<subseteq> set(dfs g xs [])\"\nproof -\n  have \"reachable g xs \\<subseteq> reachable g (dfs g xs [])\"\n    unfolding reachable_def by (rule Image_mono) (auto simp add: next_subset_dfs)\n  also have \"\\<dots> = set(dfs g xs [])\"\n    unfolding reachable_def\n  proof (rule Image_closed_trancl)\n    from nextss_closed_dfs\n    show \"set g `` set (dfs g xs []) \\<subseteq> set (dfs g xs [])\"\n      by (simp add: nextss_def)\n  qed\n  finally show ?thesis .\nqed\n\nlemma reachable_nexts: \"reachable g (nexts g x) \\<subseteq> reachable g [x]\"\n  unfolding reachable_def\n  by (auto intro: converse_rtrancl_into_rtrancl simp: nexts_set)\n\nlemma reachable_append: \"reachable g (xs @ ys) = reachable g xs \\<union> reachable g ys\"\n  unfolding reachable_def by auto\n\n\nlemma dfs_subset_reachable_visit_nodes: \"set (dfs g xs ys) \\<subseteq> reachable g xs \\<union> set ys\"\nproof2(induct g xs ys rule: dfs.induct)\n  case 1\n  then show ?case by simp\nnext\n  case (2 g x xs ys)\n  show ?case\n  proof (cases \"x \\<in> set ys\")\n    case True\n    with 2 show \"set (dfs g (x#xs) ys) \\<subseteq> reachable g (x#xs) \\<union> set ys\"\n      by (auto simp add: reachable_def List.member_def)\n  next\n    case False\n    have \"reachable g (nexts g x) \\<subseteq> reachable g [x]\" \n      by (rule reachable_nexts)\n    hence a: \"reachable g (nexts g x @ xs) \\<subseteq> reachable g (x#xs)\"\n      by(simp add: reachable_append, auto simp add: reachable_def)\n    with False 2\n    show \"set (dfs g (x#xs) ys) \\<subseteq> reachable g (x#xs) \\<union> set ys\"\n      by (auto simp add: reachable_def List.member_def)\n  qed\nqed\n\n\nsubsection \"Correctness\"\n    \ntheorem dfs_eq_reachable: \"set (dfs g xs []) = reachable g xs\"\nproof\n  have \"set (dfs g xs []) \\<subseteq> reachable g xs \\<union> set []\"\n    by (rule dfs_subset_reachable_visit_nodes[of g xs \"[]\"])\n thus \"set (dfs g xs []) \\<subseteq> reachable g xs\"\n   by simp\nqed(rule reachable_closed_dfs)\n\ntheorem \"y \\<in> set (dfs g [x] []) = ((x,y) \\<in> (set g)\\<^sup>*)\"\n  by(simp only:dfs_eq_reachable reachable_def, auto)\n\n\nsubsection \"Executable Code\"\n\nconsts Node :: \"int \\<Rightarrow> node\"\n\ncode_datatype Node\n\ninstantiation node :: equal\nbegin\n\ndefinition equal_node :: \"node \\<Rightarrow> node \\<Rightarrow> bool\"\nwhere\n  [code del]: \"equal_node = HOL.eq\"\n\ninstance proof\nqed (simp add: equal_node_def)\n\nend\n\ndeclare [[code abort: \"HOL.equal :: node \\<Rightarrow> node \\<Rightarrow> bool\"]]\n\nexport_code dfs dfs2 in SML file \\<open>dfs.ML\\<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/Evaluation/Depth-First-Search/DFS.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8397339837155239, "lm_q2_score": 0.8596637541053281, "lm_q1q2_score": 0.7218888688907097}}
{"text": "(******************************************************************************)\n(* Submission: \"The Interchange Law: A Principle of Concurrent Programming\"   *)\n(* Authors: Tony Hoare, Bernard M\u00f6ller, Georg Struth, and Frank Zeyda         *)\n(* File: Machine_Number.thy                                                   *)\n(******************************************************************************)\n(* LAST REVIEWED: 11 July 2017 *)\n\nsection {* Machine Numbers *}\n\ntheory Machine_Number\nimports Preliminaries\nbegin\n\nsubsection {* Type Class *}\n\ntext \\<open>\n  Machine numbers are introduced via a type class \\<open>machine_number\\<close>. The class\n  extends a linear order by including a constant \\<open>max_number\\<close> that yields the\n  largest representable number.\n\\<close>\n\nclass machine_number = linorder +\n  fixes max_number :: \"'a\"\nbegin\n\ntext \\<open>All numbers less or equal to @{const max_number} are within range.\\<close>\n\ndefinition number_range :: \"'a set\" where\n[simp]: \"number_range = {x. x \\<le> max_number}\"\nend\n\ntext \\<open>We can easily prove that @{const number_range} is a non-empty set.\\<close>\n\nlemma ex_leq_max_number:\n\"\\<exists>x. x \\<le> max_number\"\napply (rule_tac x = \"max_number\" in exI)\napply (rule order_refl)\ndone\n\nlemma ex_in_number_range:\n\"\\<exists>x. x \\<in> number_range\"\napply (clarsimp)\napply (rule ex_leq_max_number)\ndone\n\nsubsection {* Type Definition *}\n\ntext \\<open>The above lemma enables us to introduce a type for representable numbers.\\<close>\n\ntypedef (overloaded)\n  'a::machine_number machine_number = \"number_range::'a set\"\napply (rule ex_in_number_range)\ndone\n\ntext \\<open>The notation \\<open>MN(_)\\<close> will be used for the abstraction function.\\<close>\n\nnotation Abs_machine_number (\"MN'(_')\")\n\ntext \\<open>The notation \\<open>\\<lbrakk>_\\<rbrakk>\\<close> will be used for the representation function.\\<close>\n\nnotation Rep_machine_number (\"\\<lbrakk>_\\<rbrakk>\")\n\nsetup_lifting type_definition_machine_number\n\nsubsection {* Proof Support *}\n\nlemmas Rep_machine_number_inject_sym = sym [OF Rep_machine_number_inject]\n\ndeclare Abs_machine_number_inverse\n  [simplified number_range_def mem_Collect_eq, simp]\n\ndeclare Rep_machine_number_inverse\n  [simplified number_range_def mem_Collect_eq, simp]\n\ndeclare Abs_machine_number_inject\n  [simplified number_range_def mem_Collect_eq, simp]\n\ndeclare Rep_machine_number_inject_sym\n  [simplified number_range_def mem_Collect_eq, simp]\n\nsubsection {* Instantiations *}\n\nsubsubsection {* Linear Order *}\n\ninstantiation machine_number :: (machine_number) linorder\nbegin\ndefinition less_eq_machine_number ::\n  \"'a machine_number \\<Rightarrow> 'a machine_number \\<Rightarrow> bool\" where\n[simp]: \"less_eq_machine_number x y \\<longleftrightarrow> \\<lbrakk>x\\<rbrakk> \\<le> \\<lbrakk>y\\<rbrakk>\"\n\ndefinition less_machine_number ::\n  \"'a machine_number \\<Rightarrow> 'a machine_number \\<Rightarrow> bool\" where\n[simp]: \"less_machine_number x y \\<longleftrightarrow> \\<lbrakk>x\\<rbrakk> < \\<lbrakk>y\\<rbrakk>\"\ninstance\napply (intro_classes)\napply (unfold less_eq_machine_number_def less_machine_number_def)\n-- {* Subgoal 1 *}\napply (transfer')\napply (rule less_le_not_le)\n-- {* Subgoal 2 *}\napply (transfer')\napply (rule order_refl)\n-- {* Subgoal 3 *}\napply (transfer')\napply (erule order_trans)\napply (assumption)\n-- {* Subgoal 4 *}\napply (transfer')\napply (erule antisym)\napply (assumption)\n-- {* Subgoal 5 *}\napply (transfer')\napply (rule linear)\ndone\nend\n\nsubsubsection {* Arithmetic Operators *}\n\ninstantiation machine_number :: (\"{machine_number, zero}\") zero\nbegin\ndefinition zero_machine_number :: \"'a machine_number\" where\n[simp]: \"zero_machine_number = MN(0)\"\ninstance ..\nend\n\ninstantiation machine_number :: (\"{machine_number, one}\") one\nbegin\ndefinition one_machine_number :: \"'a machine_number\" where\n[simp]: \"one_machine_number = MN(1)\"\ninstance ..\nend\n\ninstantiation machine_number :: (\"{machine_number, plus}\") plus\nbegin\ndefinition plus_machine_number :: \"'a machine_number binop\" where\n[simp]: \"plus_machine_number x y = MN(\\<lbrakk>x\\<rbrakk> + \\<lbrakk>y\\<rbrakk>)\"\ninstance ..\nend\n\ninstantiation machine_number :: (\"{machine_number, minus}\") minus\nbegin\ndefinition minus_machine_number :: \"'a machine_number binop\" where\n[simp]: \"minus_machine_number x y = MN(\\<lbrakk>x\\<rbrakk> - \\<lbrakk>y\\<rbrakk>)\"\ninstance ..\nend\n\ninstantiation machine_number :: (\"{machine_number, times}\") times\nbegin\ndefinition times_machine_number :: \"'a machine_number binop\" where\n[simp]: \"times_machine_number x y = MN(\\<lbrakk>x\\<rbrakk> * \\<lbrakk>y\\<rbrakk>)\"\ninstance ..\nend\n\ninstantiation machine_number :: (\"{machine_number, divide}\") divide\nbegin\ndefinition divide_machine_number :: \"'a machine_number binop\" where\n[simp]: \"divide_machine_number x y = MN(\\<lbrakk>x\\<rbrakk> div \\<lbrakk>y\\<rbrakk>)\"\ninstance ..\nend\nend", "meta": {"author": "cka-models", "repo": "ipl2017", "sha": "4552de80f3e07ba0e14c1bd13b3fcec37253246d", "save_path": "github-repos/isabelle/cka-models-ipl2017", "path": "github-repos/isabelle/cka-models-ipl2017/ipl2017-4552de80f3e07ba0e14c1bd13b3fcec37253246d/theories/Machine_Number.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8596637577007393, "lm_q2_score": 0.8397339696776499, "lm_q1q2_score": 0.7218888598420472}}
{"text": "section \\<open>Young's Inequality for Increasing Functions\\<close>\n\ntext \\<open>From the following paper: \nCunningham, F., and Nathaniel Grossman. \u201cOn Young\u2019s Inequality.\u201d \nThe American Mathematical Monthly 78, no. 7 (1971): 781\u201383. \n\\url{https://doi.org/10.2307/2318018}\\<close>\n\ntheory Youngs imports\n  \"HOL-Analysis.Analysis\" \n   \nbegin\n\nsubsection \\<open>Library Extras: already added to the repository\\<close>\n\ntext \\<open>In fact, strict inequality is required only at a single point within the box.\\<close>\nlemma integral_less:\n  fixes f :: \"'n::euclidean_space \\<Rightarrow> real\"\n  assumes cont: \"continuous_on (cbox a b) f\" \"continuous_on (cbox a b) g\" and ne: \"box a b \\<noteq> {}\"\n    and fg: \"\\<And>x. x \\<in> box a b \\<Longrightarrow> f x < g x\"\n  shows \"integral (cbox a b) f < integral (cbox a b) g\"\nproof -\n  obtain int: \"f integrable_on (cbox a b)\" \"g integrable_on (cbox a b)\"\n    using cont integrable_continuous by blast\n  then have \"integral (cbox a b) f \\<le> integral (cbox a b) g\"\n    by (metis fg integrable_on_open_interval integral_le integral_open_interval less_eq_real_def)\n  moreover have \"integral (cbox a b) f \\<noteq> integral (cbox a b) g\"\n  proof (rule ccontr)\n    assume \"\\<not> integral (cbox a b) f \\<noteq> integral (cbox a b) g\"\n    then have 0: \"((\\<lambda>x. g x - f x) has_integral 0) (cbox a b)\"\n      by (metis (full_types) cancel_comm_monoid_add_class.diff_cancel has_integral_diff int \n                integrable_integral)\n    have cgf: \"continuous_on (cbox a b) (\\<lambda>x. g x - f x)\"\n      using cont continuous_on_diff by blast\n    show False\n      using has_integral_0_cbox_imp_0 [OF cgf _ 0] ne box_subset_cbox fg by fastforce\n  qed\n  ultimately show ?thesis\n    by linarith\nqed\n\nlemma integral_less_real:\n  fixes f :: \"real \\<Rightarrow> real\"\n  assumes \"continuous_on {a..b} f\" \"continuous_on {a..b} g\" and \"{a<..<b} \\<noteq> {}\"\n    and \"\\<And>x. x \\<in> {a<..<b} \\<Longrightarrow> f x < g x\"\n  shows \"integral {a..b} f < integral {a..b} g\"\n  by (metis assms box_real integral_less)\n\nlemma has_integral_UN:\n  fixes f :: \"'n::euclidean_space \\<Rightarrow> 'a::banach\"\n  assumes \"finite I\"\n    and int: \"\\<And>i. i \\<in> I \\<Longrightarrow> (f has_integral (g i)) (\\<T> i)\"\n    and neg: \"pairwise (\\<lambda>i i'. negligible (\\<T> i \\<inter> \\<T> i')) I\"\n  shows \"(f has_integral (sum g I)) (\\<Union>i\\<in>I. \\<T> i)\"\nproof -\n  let ?\\<U> = \"((\\<lambda>(a,b). \\<T> a \\<inter> \\<T> b) ` {(a,b). a \\<in> I \\<and> b \\<in> I-{a}})\"\n  have \"((\\<lambda>x. if x \\<in> (\\<Union>i\\<in>I. \\<T> i) then f x else 0) has_integral sum g I) UNIV\"\n  proof (rule has_integral_spike)\n    show \"negligible (\\<Union>?\\<U>)\"\n    proof (rule negligible_Union)\n      have \"finite (I \\<times> I)\"\n        by (simp add: \\<open>finite I\\<close>)\n      moreover have \"{(a,b). a \\<in> I \\<and> b \\<in> I-{a}} \\<subseteq> I \\<times> I\"\n        by auto\n      ultimately show \"finite ?\\<U>\"\n        by (simp add: finite_subset)\n      show \"\\<And>t. t \\<in> ?\\<U> \\<Longrightarrow> negligible t\"\n        using neg unfolding pairwise_def by auto\n    qed\n  next\n    show \"(if x \\<in> (\\<Union>i\\<in>I. \\<T> i) then f x else 0) = (\\<Sum>i\\<in>I. if x \\<in> \\<T> i then f x else 0)\"\n      if \"x \\<in> UNIV - (\\<Union>?\\<U>)\" for x\n    proof clarsimp\n      fix i assume i: \"i \\<in> I\" \"x \\<in> \\<T> i\"\n      then have \"\\<forall>j\\<in>I. x \\<in> \\<T> j \\<longleftrightarrow> j = i\"\n        using that by blast\n      with i show \"f x = (\\<Sum>i\\<in>I. if x \\<in> \\<T> i then f x else 0)\"\n        by (simp add: sum.delta[OF \\<open>finite I\\<close>])\n    qed\n  next\n    show \"((\\<lambda>x. (\\<Sum>i\\<in>I. if x \\<in> \\<T> i then f x else 0)) has_integral sum g I) UNIV\"\n      using int by (simp add: has_integral_restrict_UNIV has_integral_sum[OF \\<open>finite I\\<close>])\n  qed\n  then show ?thesis\n    using has_integral_restrict_UNIV by blast\nqed\n\nlemma integrable_mono_on_nonneg:\n  fixes f :: \"real \\<Rightarrow> real\"\n  assumes mon: \"mono_on {a..b} f\" and 0: \"\\<And>x. 0 \\<le> f x\"\n  shows \"integrable (lebesgue_on {a..b}) f\" \nproof -\n  have \"space lborel = space lebesgue\" \"sets borel \\<subseteq> sets lebesgue\"\n    by force+\n  then have fborel: \"f \\<in> borel_measurable (lebesgue_on {a..b})\"\n    by (metis mon borel_measurable_mono_on_fnc borel_measurable_subalgebra mono_restrict_space\n              space_lborel space_restrict_space)\n  then obtain g where g: \"incseq g\" and simple: \"\\<And>i. simple_function (lebesgue_on {a..b}) (g i)\" \n                and bdd: \" (\\<forall>x. bdd_above (range (\\<lambda>i. g i x)))\" and nonneg: \"\\<forall>i x. 0 \\<le> g i x\"\n                and fsup: \"f = (SUP i. g i)\"\n    by (metis borel_measurable_implies_simple_function_sequence_real 0)\n  have \"f ` {a..b} \\<subseteq> {f a..f b}\" \n    using assms by (auto simp: mono_on_def)\n  have g_le_f: \"g i x \\<le> f x\" for i x\n  proof -\n    have \"bdd_above ((\\<lambda>h. h x) ` range g)\"\n      using bdd cSUP_lessD linorder_not_less by fastforce\n    then show ?thesis\n      by (metis SUP_apply UNIV_I bdd cSUP_upper fsup)\n  qed\n  then have gfb: \"g i x \\<le> f b\" if \"x \\<in> {a..b}\" for i x\n    by (smt (verit, best) mon atLeastAtMost_iff mono_on_def that)\n  have g_le: \"g i x \\<le> g j x\" if \"i\\<le>j\"  for i j x\n    using g by (simp add: incseq_def le_funD that)\n  show \"integrable (lebesgue_on {a..b}) ( f)\"\n  proof (rule integrable_dominated_convergence)\n    show \"f \\<in> borel_measurable (lebesgue_on {a..b})\"\n      using fborel by blast\n    have \"\\<And>x. (\\<lambda>i. g i x) \\<longlonglongrightarrow> (SUP h \\<in> range g. h  x)\"\n    proof (rule order_tendstoI)\n      show \"\\<forall>\\<^sub>F i in sequentially. y < g i x\"\n        if \"y < (SUP h\\<in>range g. h x)\" for x y\n      proof -\n        from that obtain h where h: \"h \\<in> range g\" \"y < h x\"\n          using g_le_f by (subst (asm)less_cSUP_iff) fastforce+\n        then show ?thesis\n          by (smt (verit, ccfv_SIG) eventually_sequentially g_le imageE)\n      qed\n      show \"\\<forall>\\<^sub>F i in sequentially. g i x < y\"\n        if \"(SUP h\\<in>range g. h x) < y\" for x y\n        by (smt (verit, best) that Sup_apply g_le_f always_eventually fsup image_cong)\n    qed\n    then show \"AE x in lebesgue_on {a..b}. (\\<lambda>i. g i x) \\<longlonglongrightarrow> f x\"\n      by (simp add: fsup)\n    fix i\n    show \"g i \\<in> borel_measurable (lebesgue_on {a..b})\"\n      using borel_measurable_simple_function simple by blast\n    show \"AE x in lebesgue_on {a..b}. norm (g i x) \\<le> f b\"\n      by (simp add: gfb nonneg Measure_Space.AE_I' [of \"{}\"])\n  qed auto\nqed\n\nlemma integrable_mono_on:\n  fixes f :: \"real \\<Rightarrow> real\"\n  assumes \"mono_on {a..b} f\" \n  shows \"integrable (lebesgue_on {a..b}) f\" \nproof -\n  define f' where \"f' \\<equiv> \\<lambda>x. if x \\<in> {a..b} then f x - f a else 0\"\n  have \"mono_on {a..b} f'\"\n    by (smt (verit, best) assms f'_def mono_on_def)\n  moreover have 0: \"\\<And>x. 0 \\<le> f' x\"\n    by (smt (verit, best) assms atLeastAtMost_iff f'_def mono_on_def)\n  ultimately have \"integrable (lebesgue_on {a..b}) f'\"\n    using integrable_mono_on_nonneg by presburger\n  then have \"integrable (lebesgue_on {a..b}) (\\<lambda>x. f' x + f a)\"\n    by force\n  moreover have \"space lborel = space lebesgue\" \"sets borel \\<subseteq> sets lebesgue\"\n    by force+\n  then have fborel: \"f \\<in> borel_measurable (lebesgue_on {a..b})\"\n    using borel_measurable_mono_on_fnc [OF assms]\n    by (metis borel_measurable_subalgebra mono_restrict_space space_lborel space_restrict_space)\n  ultimately show ?thesis\n    by (rule integrable_cong_AE_imp) (auto simp: f'_def)\nqed\n\nlemma integrable_on_mono_on:\n  fixes f :: \"real \\<Rightarrow> real\"\n  assumes \"mono_on {a..b} f\" \n  shows \"f integrable_on {a..b}\"\n  by (simp add: assms integrable_mono_on integrable_on_lebesgue_on) \n\nlemma strict_mono_image_endpoints:\n  fixes f :: \"'a::linear_continuum_topology \\<Rightarrow> 'b::linorder_topology\"\n  assumes \"strict_mono_on {a..b} f\" and f: \"continuous_on {a..b} f\" and \"a \\<le> b\"\n  shows \"f ` {a..b} = {f a..f b}\"\nproof\n  show \"f ` {a..b} \\<subseteq> {f a..f b}\"\n    using assms(1) strict_mono_on_leD by fastforce\n  show \"{f a..f b} \\<subseteq> f ` {a..b}\"\n    using assms IVT'[OF _ _ _ f] by (force simp: Bex_def)\nqed\n\nsubsection \\<open>Toward Young's inequality\\<close>\n\ntext \\<open>Generalisations of the type of @{term f} are not obvious\\<close>\nlemma strict_mono_continuous_invD:\n  fixes f :: \"real \\<Rightarrow> real\"\n  assumes sm: \"strict_mono_on {a..} f\" and contf: \"continuous_on {a..} f\" \n    and fim: \"f ` {a..} = {f a..}\" and g: \"\\<And>x. x \\<ge> a \\<Longrightarrow> g (f x) = x\"\n  shows \"continuous_on {f a..} g\"\nproof (clarsimp simp add: continuous_on_eq_continuous_within)\n  fix y\n  assume \"f a \\<le> y\"\n  then obtain u where u: \"y+1 = f u\" \"u \\<ge> a\"\n    by (smt (verit, best) atLeast_iff fim imageE)\n  have \"continuous_on {f a..y+1} g\" \n  proof -\n    obtain \"continuous_on {a..u} f\"  \"strict_mono_on {a..u} f\"\n      using contf sm continuous_on_subset by (force simp add: strict_mono_on_def)\n    moreover have \"continuous_on (f ` {a..u}) g\"\n      using assms continuous_on_subset\n      by (intro continuous_on_inv) fastforce+\n    ultimately show ?thesis\n      using strict_mono_image_endpoints [of _ _ f]\n      by (simp add: strict_mono_image_endpoints u)\n  qed\n  then have *: \"continuous (at y within {f a..y+1}) g\"\n    by (simp add: \\<open>f a \\<le> y\\<close> continuous_on_imp_continuous_within)\n  show \"continuous (at y within {f a..}) g\"\n  proof (clarsimp simp add: continuous_within_topological Ball_def)\n    fix B\n    assume \"open B\" and \"g y \\<in> B\"\n    with * obtain A where A: \"open A\" \"y \\<in> A\" and \"\\<And>x. f a \\<le> x \\<and> x \\<le> y+1 \\<Longrightarrow> x \\<in> A \\<longrightarrow> g x \\<in> B\"\n      by (force simp: continuous_within_topological)\n    then have \"\\<forall>x\\<ge>f a. x \\<in> A \\<inter> ball y 1 \\<longrightarrow> g x \\<in> B\"\n      by (smt (verit, ccfv_threshold) IntE dist_norm mem_ball real_norm_def)\n    then show \"\\<exists>A. open A \\<and> y \\<in> A \\<and> (\\<forall>x\\<ge>f a. x \\<in> A \\<longrightarrow> g x \\<in> B)\"\n      by (metis Elementary_Metric_Spaces.open_ball Int_iff A centre_in_ball open_Int zero_less_one)\n  qed\nqed\n\nsubsection \\<open>Regular divisions\\<close>\n\ntext \\<open>Our lack of the Riemann integral forces us to construct explicitly\nthe step functions mentioned in the text.\\<close>\n\ndefinition \"segment \\<equiv> \\<lambda>n k. {real k / real n..(1 + k) / real n}\"\n\nlemma segment_nonempty: \"segment n k \\<noteq> {}\"\n  by (auto simp: segment_def divide_simps)\n\nlemma segment_Suc: \"segment n ` {..<Suc k} = insert {k/n..(1 + real k) / n} (segment n ` {..<k})\"\n  by (simp add: segment_def lessThan_Suc)\n\nlemma Union_segment_image: \"\\<Union> (segment n ` {..<k}) = (if k=0 then {} else {0..real k/real n})\"\nproof (induction k)\n  case (Suc k)\n  then show ?case\n    by (simp add: divide_simps segment_Suc Un_commute ivl_disj_un_two_touch split: if_split_asm)\nqed (auto simp: segment_def)\n\ndefinition \"segments \\<equiv> \\<lambda>n. segment n ` {..<n}\"\n\nlemma card_segments [simp]: \"card (segments n) = n\"\n  by (simp add: segments_def segment_def card_image divide_right_mono inj_on_def)\n\nlemma segments_0 [simp]: \"segments 0 = {}\"\n  by (simp add: segments_def)\n\nlemma Union_segments: \"\\<Union> (segments n) = (if n=0 then {} else {0..1})\"\n  by (simp add: segments_def Union_segment_image)\n\ndefinition \"regular_division \\<equiv> \\<lambda>a b n. (image ((+) a \\<circ> (*) (b-a))) ` (segments n)\"\n\nlemma translate_scale_01:\n  assumes \"a \\<le> b\" \n  shows \"(\\<lambda>x. a + (b - a) * x) ` {0..1} = {a..b::real}\"\n  using closed_segment_real_eq [of a b] assms closed_segment_eq_real_ivl by auto\n\nlemma finite_regular_division [simp]: \"finite (regular_division a b n)\"\n  by (simp add: regular_division_def segments_def)\n\nlemma card_regular_division [simp]: \n  assumes \"a<b\"\n  shows \"card (regular_division a b n) = n\"\nproof -\n  have \"inj_on ((`) ((+) a \\<circ> (*) (b - a))) (segments n)\"\n  proof\n    fix x y\n    assume \"((+) a \\<circ> (*) (b - a)) ` x = ((+) a \\<circ> (*) (b - a)) ` y\"\n    then have \"(+) (-a) ` ((+) a \\<circ> (*) (b - a)) ` x = (+) (-a) ` ((+) a \\<circ> (*) (b - a)) ` y\"\n      by simp\n    then have \"((*) (b - a)) ` x = ((*) (b - a)) ` y\"\n      by (simp add: image_comp)\n    then have \"(*) (inverse(b - a)) ` (*) (b - a) ` x = (*) (inverse(b - a)) ` (*) (b - a) ` y\"\n      by simp\n    then show \"x = y\"\n      using assms by (simp add: image_comp mult_ac)\n  qed\n  then show ?thesis\n    by (metis card_image card_segments regular_division_def)\nqed\n\nlemma Union_regular_division:\n  assumes \"a \\<le> b\" \n  shows \"\\<Union>(regular_division a b n) = (if n=0 then {} else {a..b})\"\n  using assms\n  by (auto simp: regular_division_def Union_segments translate_scale_01 simp flip: image_Union)\n\nlemma regular_division_eqI:\n  assumes K: \"K = {a + (b-a)*(real k / n) .. a + (b-a)*((1 + real k) / n)}\"\n    and \"a<b\" \"k < n\"\n  shows \"K \\<in> regular_division a b n\" \n  unfolding regular_division_def segments_def image_comp\nproof\n  have \"K = (\\<lambda>x. (b-a) * x + a) ` {real k / real n..(1 + real k) / real n}\"\n    using K \\<open>a<b\\<close> by (simp add: image_affinity_atLeastAtMost divide_simps)\n  then show \"K = ((`) ((+) a \\<circ> (*) (b - a)) \\<circ> segment n) k\" \n    by (simp add: segment_def add.commute)\nqed (use assms in auto)\n\nlemma regular_divisionE:\n  assumes \"K \\<in> regular_division a b n\" \"a<b\"\n  obtains k where \"k<n\" \"K = {a + (b-a)*(real k / n) .. a + (b-a)*((1 + real k) / n)}\"\nproof -\n  have eq: \"(\\<lambda>x. a + (b - a) * x) = (\\<lambda>x. a + x) \\<circ> (\\<lambda>x. (b - a) * x)\"\n    by (simp add: o_def)\n  obtain k where \"k<n\" \"K = ((\\<lambda>x. a+x) \\<circ> (\\<lambda>x. (b-a) * x)) ` {k/n .. (1 + real k) / n}\"\n    using assms by (auto simp: regular_division_def segments_def segment_def)\n  with that \\<open>a<b\\<close> show ?thesis\n    unfolding image_comp [symmetric]  by auto\nqed\n\nlemma regular_division_division_of:\n  assumes \"a < b\" \"n>0\"\n  shows \"(regular_division a b n) division_of {a..b}\"\nproof (rule division_ofI)\n  show \"finite (regular_division a b n)\"\n    by (simp add: regular_division_def segments_def)\n  show \\<section>: \"\\<Union> (regular_division a b n) = {a..b}\"\n    using Union_regular_division assms by simp\n  fix K\n  assume K: \"K \\<in> regular_division a b n\"\n  then obtain k where Keq: \"K = {a + (b-a)*(k/n) .. a + (b-a)*((1 + real k) / n)}\" \n    using \\<open>a<b\\<close> regular_divisionE by meson\n  show \"K \\<subseteq> {a..b}\"\n    using K Union_regular_division \\<open>n>0\\<close> by (metis Union_upper \\<section>)\n  show \"K \\<noteq> {}\"\n    using K by (auto simp: regular_division_def segment_nonempty segments_def)\n  show \"\\<exists>a b. K = cbox a b\"\n    by (metis K \\<open>a<b\\<close> box_real(2) regular_divisionE)\n  fix K'\n  assume K': \"K' \\<in> regular_division a b n\" and \"K \\<noteq> K'\"\n  then obtain k' where Keq': \"K' = {a + (b-a)*(k'/n) .. a + (b-a)*((1 + real k') / n)}\" \n    using K \\<open>a<b\\<close> regular_divisionE by meson\n  consider \"1 + real k \\<le> k'\" | \"1 + real k' \\<le> k\"\n    using Keq Keq' \\<open>K \\<noteq> K'\\<close> by force\n  then show \"interior K \\<inter> interior K' = {}\"\n  proof cases\n    case 1\n    then show ?thesis\n      by (simp add: Keq Keq' min_def max_def divide_right_mono assms)\n  next\n    case 2\n    then have \"interior K' \\<inter> interior K = {}\"\n      by (simp add: Keq Keq' min_def max_def divide_right_mono assms)\n    then show ?thesis\n      by (simp add: inf_commute)\n  qed\nqed\n\nsubsection \\<open>Special cases of Young's inequality\\<close>\n\nlemma weighted_nesting_sum:\n  fixes g :: \"nat \\<Rightarrow> 'a::comm_ring_1\"\n  shows \"(\\<Sum>k<n. (1 + of_nat k) * (g (Suc k) - g k)) = of_nat n * g n - (\\<Sum>i<n. g i)\"\n  by (induction n) (auto simp: algebra_simps)\n\ntheorem Youngs_exact:\n  fixes f :: \"real \\<Rightarrow> real\"\n  assumes sm: \"strict_mono_on {0..} f\" and cont: \"continuous_on {0..} f\" and a: \"a\\<ge>0\" \n    and f: \"f 0 = 0\" \"f a = b\"\n    and g: \"\\<And>x. \\<lbrakk>0 \\<le> x; x \\<le> a\\<rbrakk> \\<Longrightarrow> g (f x) = x\"\n  shows \"a*b = integral {0..a} f + integral {0..b} g\" \nproof (cases \"a=0\")\n  case False\n  with \\<open>a \\<ge> 0\\<close> have \"a > 0\" by linarith\n  then have \"b \\<ge> 0\"\n    by (smt (verit, best) atLeast_iff f sm strict_mono_onD)\n  have sm_0a: \"strict_mono_on {0..a} f\"\n    by (metis atLeastAtMost_iff atLeast_iff sm strict_mono_on_def)\n  have cont_0a: \"continuous_on {0..a} f\"\n    using cont continuous_on_subset by fastforce\n  with sm_0a have \"continuous_on {0..b} g\"\n    by (metis a atLeastAtMost_iff compact_Icc continuous_on_inv f g strict_mono_image_endpoints)\n  then have intgb_g: \"g integrable_on {0..b}\"\n    using integrable_continuous_interval by blast\n  have intgb_f: \"f integrable_on {0..a}\"\n    using cont_0a integrable_continuous_real by blast\n\n  have f_iff [simp]: \"f x < f y \\<longleftrightarrow> x < y\" \"f x \\<le> f y \\<longleftrightarrow> x \\<le> y\"\n    if \"x \\<ge> 0\" \"y \\<ge> 0\" for x y\n    using that by (smt (verit, best) atLeast_iff sm strict_mono_onD)+\n  have fim: \"f ` {0..a} = {0..b}\"\n    by (simp add: \\<open>a \\<ge> 0\\<close> cont_0a strict_mono_image_endpoints strict_mono_on_def f)\n  have \"uniformly_continuous_on {0..a} f\"\n    using compact_uniformly_continuous cont_0a by blast\n  then obtain del where del_gt0: \"\\<And>e. e>0 \\<Longrightarrow> del e > 0\" \n        and del:  \"\\<And>e x x'. \\<lbrakk>\\<bar>x'-x\\<bar> < del e; e>0; x \\<in> {0..a}; x' \\<in> {0..a}\\<rbrakk> \\<Longrightarrow> \\<bar>f x' - f x\\<bar> < e\"\n    unfolding uniformly_continuous_on_def dist_real_def by metis\n\n  have *: \"\\<bar>a * b - integral {0..a} f - integral {0..b} g\\<bar> < 2*\\<epsilon>\" if \"\\<epsilon> > 0\" for \\<epsilon>\n  proof -\n    define \\<delta> where \"\\<delta> = min a (del (\\<epsilon>/a)) / 2\"\n    have \"\\<delta> > 0\" \"\\<delta> \\<le> a\"\n      using \\<open>a > 0\\<close> \\<open>\\<epsilon> > 0\\<close> del_gt0 by (auto simp: \\<delta>_def)\n    define n where \"n \\<equiv> nat\\<lfloor>a / \\<delta>\\<rfloor>\"\n    define a_seg where \"a_seg \\<equiv> \\<lambda>u::real. u * a/n\"\n    have \"n > 0\"\n      using  \\<open>a > 0\\<close> \\<open>\\<delta> > 0\\<close> \\<open>\\<delta> \\<le> a\\<close> by (simp add: n_def)\n    have a_seg_ge_0 [simp]: \"a_seg x \\<ge> 0 \\<longleftrightarrow> x \\<ge> 0\" \n     and a_seg_le_a [simp]: \"a_seg x \\<le> a \\<longleftrightarrow> x \\<le> n\" for x\n      using \\<open>n > 0\\<close> \\<open>a > 0\\<close> by (auto simp: a_seg_def zero_le_mult_iff divide_simps)\n    have a_seg_le_iff [simp]: \"a_seg x \\<le> a_seg y \\<longleftrightarrow> x \\<le> y\" \n      and a_seg_less_iff [simp]: \"a_seg x < a_seg y \\<longleftrightarrow> x < y\" for x y\n      using \\<open>n > 0\\<close> \\<open>a > 0\\<close> by (auto simp: a_seg_def zero_le_mult_iff divide_simps)\n    have \"strict_mono a_seg\"\n      by (simp add: strict_mono_def)\n    have a_seg_eq_a_iff: \"a_seg x = a \\<longleftrightarrow> x=n\" for x\n      using \\<open>0 < n\\<close> \\<open>a > 0\\<close> by (simp add: a_seg_def nonzero_divide_eq_eq)\n    have fa_eq_b: \"f (a_seg n) = b\"\n      using a_seg_eq_a_iff f by fastforce\n\n    have \"a/d < real_of_int \\<lfloor>a * 2 / min a d\\<rfloor>\" if \"d>0\" for d\n      by (smt (verit) \\<open>0 < \\<delta>\\<close> \\<open>\\<delta> \\<le> a\\<close> add_divide_distrib divide_less_eq_1_pos floor_eq_iff that)\n    then have an_less_del: \"a/n < del (\\<epsilon>/a)\"\n      using \\<open>a > 0\\<close> \\<open>\\<epsilon> > 0\\<close> del_gt0  by (simp add: n_def \\<delta>_def field_simps)\n\n    define lower where \"lower \\<equiv> \\<lambda>x. a_seg\\<lfloor>(real n * x) / a\\<rfloor>\"\n    define f1 where \"f1 \\<equiv> f \\<circ> lower\"\n    have f1_lower: \"f1 x \\<le> f x\" if \"0 \\<le> x\" \"x \\<le> a\" for x\n    proof -\n      have \"lower x \\<le> x\"\n        using \\<open>n > 0\\<close> floor_divide_lower [OF \\<open>a > 0\\<close>] \n        by (auto simp: lower_def a_seg_def field_simps)\n      moreover have \"lower x \\<ge> 0\"\n        unfolding lower_def using \\<open>n > 0\\<close> \\<open>a \\<ge> 0\\<close> \\<open>0 \\<le> x\\<close> by force\n      ultimately show ?thesis\n        using sm strict_mono_on_leD by (fastforce simp add: f1_def)\n    qed\n    define upper where \"upper \\<equiv> \\<lambda>x. a_seg\\<lceil>real n * x / a\\<rceil>\"\n    define f2 where \"f2 \\<equiv> f \\<circ> upper\"\n    have f2_upper: \"f2 x \\<ge> f x\" if \"0 \\<le> x\" \"x \\<le> a\" for x\n    proof -\n      have \"x \\<le> upper x\"\n        using \\<open>n > 0\\<close> ceiling_divide_upper [OF \\<open>a > 0\\<close>] by (simp add: upper_def a_seg_def field_simps)\n      then show ?thesis\n        using sm strict_mono_on_leD \\<open>0 \\<le> x\\<close> by (force simp: f2_def)\n    qed\n    let ?\\<D> = \"regular_division 0 a n\"\n    have div: \"?\\<D> division_of {0..a}\"\n      using \\<open>a > 0\\<close> \\<open>n > 0\\<close> regular_division_division_of zero_less_nat_eq by presburger\n\n    have int_f1_D: \"(f1 has_integral f(Inf K) * (a/n)) K\" \n      and int_f2_D: \"(f2 has_integral f(Sup K) * (a/n)) K\" and less: \"\\<bar>f(Sup K) - f(Inf K)\\<bar> < \\<epsilon>/a\"\n      if \"K\\<in>?\\<D>\" for K\n    proof -\n      from regular_divisionE [OF that] \\<open>a > 0\\<close>\n      obtain k where \"k<n\" and k: \"K = {a_seg(real k)..a_seg(Suc k)}\"\n        by (auto simp: a_seg_def mult.commute)\n      define u where \"u \\<equiv> a_seg k\"\n      define v where \"v \\<equiv> a_seg (Suc k)\"\n      have \"u < v\" \"0 \\<le> u\" \"0 \\<le> v\" \"u \\<le> a\" \"v \\<le> a\" and Kuv: \"K = {u..v}\"\n        using \\<open>n > 0\\<close> \\<open>k < n\\<close> \\<open>a > 0\\<close> by (auto simp: k u_def v_def divide_simps)\n      have InfK: \"Inf K = u\" and SupK: \"Sup K = v\"\n        using Kuv \\<open>u < v\\<close> apply force\n        using \\<open>n > 0\\<close> \\<open>a > 0\\<close> by (auto simp: divide_right_mono k u_def v_def)\n      have f1: \"f1 x = f (Inf K)\" if \"x \\<in> K - {v}\" for x\n      proof -\n        have \"x \\<in> {u..<v}\"\n          using that Kuv atLeastLessThan_eq_atLeastAtMost_diff by blast\n        then have \"\\<lfloor>real_of_int n * x / a\\<rfloor> = int k\"\n          using \\<open>n > 0\\<close> \\<open>a > 0\\<close> by (simp add: field_simps u_def v_def a_seg_def floor_eq_iff)\n        then show ?thesis\n          by (simp add: InfK f1_def lower_def a_seg_def mult.commute u_def) \n      qed\n      have \"((\\<lambda>x. f (Inf K)) has_integral (f (Inf K) * (a/n))) K\"\n        using has_integral_const_real [of \"f (Inf K)\" u v] \n              \\<open>n > 0\\<close> \\<open>a > 0\\<close> by (simp add: Kuv field_simps a_seg_def u_def v_def)\n      then show \"(f1 has_integral (f (Inf K) * (a/n))) K\"\n        using has_integral_spike_finite_eq [of \"{v}\" K \"\\<lambda>x. f (Inf K)\" f1] f1 by simp\n      have f2: \"f2 x = f (Sup K)\" if \"x \\<in> K - {u}\" for x\n      proof -\n        have \"x \\<in> {u<..v}\"\n          using that Kuv greaterThanAtMost_eq_atLeastAtMost_diff by blast \n        then have \"\\<lceil>x * real_of_int n / a\\<rceil>  = 1 + int k\"\n          using \\<open>n > 0\\<close> \\<open>a > 0\\<close> by (simp add: field_simps u_def v_def a_seg_def ceiling_eq_iff)\n        then show ?thesis \n          by (simp add: mult.commute f2_def upper_def a_seg_def SupK v_def)\n      qed\n      have \"((\\<lambda>x. f (Sup K)) has_integral (f (Sup K) * (a/n))) K\"\n        using  \\<open>n > 0\\<close> \\<open>a > 0\\<close> has_integral_const_real [of \"f (Sup K)\" u v]\n        by (simp add: Kuv field_simps u_def v_def a_seg_def)\n      then show \"(f2 has_integral (f (Sup K) * (a/n))) K\"\n        using has_integral_spike_finite_eq [of \"{u}\" K \"\\<lambda>x. f (Sup K)\" f2] f2 by simp\n      have \"\\<bar>v - u\\<bar> < del (\\<epsilon>/a)\"\n        using \\<open>n > 0\\<close> \\<open>a > 0\\<close> by (simp add: v_def u_def a_seg_def field_simps an_less_del)\n      then have \"\\<bar>f v - f u\\<bar> < \\<epsilon>/a\"\n        using \\<open>\\<epsilon> > 0\\<close> \\<open>a > 0\\<close> \\<open>0 \\<le> u\\<close> \\<open>u \\<le> a\\<close> \\<open>0 \\<le> v\\<close> \\<open>v \\<le> a\\<close>\n        by (intro del) auto\n      then show \"\\<bar>f(Sup K) - f(Inf K)\\<bar> < \\<epsilon>/a\"\n        using InfK SupK by blast\n    qed\n\n    have int_21_D: \"((\\<lambda>x. f2 x - f1 x) has_integral (f(Sup K) - f(Inf K)) * (a/n)) K\" if \"K\\<in>?\\<D>\" for K\n      using that has_integral_diff [OF int_f2_D int_f1_D] by (simp add: algebra_simps)\n\n    have D_ne: \"?\\<D> \\<noteq> {}\"\n      by (metis \\<open>0 < a\\<close> \\<open>n > 0\\<close> card_gt_0_iff card_regular_division)\n    have f12: \"((\\<lambda>x. f2 x - f1 x) has_integral (\\<Sum>K\\<in>?\\<D>. (f(Sup K) - f(Inf K)) * (a/n))) {0..a}\"\n      by (intro div int_21_D has_integral_combine_division)\n    moreover have \"(\\<Sum>K\\<in>?\\<D>. (f(Sup K) - f(Inf K)) * (a/n)) < \\<epsilon>\"\n    proof -\n      have \"(\\<Sum>K\\<in>?\\<D>. (f(Sup K) - f(Inf K)) * (a/n)) \\<le> (\\<Sum>K\\<in>?\\<D>. \\<bar>f(Sup K) - f(Inf K)\\<bar> * (a/n))\"\n        using \\<open>n > 0\\<close> \\<open>a > 0\\<close>\n        by (smt (verit) divide_pos_pos of_nat_0_less_iff sum_mono zero_le_mult_iff)\n      also have \"\\<dots> < (\\<Sum>K\\<in>?\\<D>. \\<epsilon>/n)\"\n        using \\<open>n > 0\\<close> \\<open>a > 0\\<close> less\n        by (intro sum_strict_mono finite_regular_division D_ne) (simp add: field_simps)\n      also have \"\\<dots> = \\<epsilon>\"\n        using \\<open>n > 0\\<close> \\<open>a > 0\\<close> by simp\n      finally show ?thesis .\n    qed\n    ultimately have f2_near_f1: \"integral {0..a} (\\<lambda>x. f2 x - f1 x) < \\<epsilon>\"\n      by (simp add: integral_unique)\n\n    define yidx where \"yidx \\<equiv> \\<lambda>y. LEAST k. y < f (a_seg (Suc k))\"\n    have fa_yidx_le: \"f (a_seg (yidx y)) \\<le> y\" and yidx_gt: \"y < f (a_seg (Suc (yidx y)))\" \n      if \"y \\<in> {0..b}\" for y\n    proof -\n      obtain x where x: \"f x = y\" \"x \\<in> {0..a}\"\n        using Topological_Spaces.IVT' [OF _ _ _ cont_0a] assms\n        by (metis \\<open>y \\<in> {0..b}\\<close> atLeastAtMost_iff)\n      define k where \"k \\<equiv> nat \\<lfloor>x/a * n\\<rfloor>\"\n      have x_lims: \"a_seg k \\<le> x\" \"x < a_seg (Suc k)\"\n        using \\<open>n > 0\\<close> \\<open>0 < a\\<close> floor_divide_lower floor_divide_upper [of a \"x*n\"] x\n        by (auto simp: k_def a_seg_def field_simps)\n      with that x obtain f_lims: \"f (a_seg k) \\<le> y\" \"y < f (a_seg (Suc k))\"\n        using strict_mono_onD [OF sm] by force\n      then have \"a_seg (yidx y) \\<le> a_seg k\"\n        by (simp add: Least_le \\<open>strict_mono a_seg\\<close> strict_mono_less_eq yidx_def)\n      then have \"f (a_seg (yidx y)) \\<le> f (a_seg k)\"\n        using strict_mono_onD [OF sm] by simp\n      then show \"f (a_seg (yidx y)) \\<le> y\"\n        using f_lims by linarith\n      show \"y < f (a_seg (Suc (yidx y)))\"\n        by (metis LeastI f_lims(2) yidx_def) \n    qed\n\n    have yidx_equality: \"yidx y = k\" if \"y \\<in> {0..b}\" \"y \\<in> {f (a_seg k)..<f (a_seg (Suc k))}\" for y k\n    proof (rule antisym)\n      show \"yidx y \\<le> k\"\n        unfolding yidx_def by (metis atLeastLessThan_iff that(2) Least_le)\n      have \"(a_seg (real k)) < a_seg (1 + real (yidx y))\"\n        using yidx_gt [OF that(1)] that(2) strict_mono_onD [OF sm] order_le_less_trans by fastforce\n      then have \"real k < 1 + real (yidx y)\"\n        by (simp add: \\<open>strict_mono a_seg\\<close> strict_mono_less)\n      then show \"k \\<le> yidx y\"\n        by simp \n    qed\n    have \"yidx b = n\"\n    proof -\n      have \"a < (1 + real n) * a / real n\"\n        using \\<open>0 < n\\<close> \\<open>0 < a\\<close> by (simp add: divide_simps)\n      then have \"b < f (a_seg (1 + real n))\"\n        using f \\<open>a \\<ge> 0\\<close> a_seg_def sm strict_mono_onD by fastforce\n      then show ?thesis\n        using \\<open>0 \\<le> b\\<close> by (auto simp: f a_seg_def yidx_equality)\n    qed\n    moreover have yidx_less_n: \"yidx y < n\" if \"y < b\" for y\n      by (metis \\<open>0 < n\\<close> fa_eq_b gr0_conv_Suc less_Suc_eq_le that Least_le yidx_def)\n    ultimately have yidx_le_n: \"yidx y \\<le> n\" if \"y \\<le> b\" for y\n      by (metis dual_order.order_iff_strict that)\n\n    have zero_to_b_eq: \"{0..b} = (\\<Union>k<n. {f(a_seg k)..f(a_seg (Suc k))})\" (is \"?lhs = ?rhs\")\n    proof\n      show \"?lhs \\<subseteq> ?rhs\"\n      proof\n        fix y assume y: \"y \\<in> {0..b}\"\n        have fn: \"f (a_seg n) = b\"\n          using a_seg_eq_a_iff \\<open>f a = b\\<close> by fastforce\n        show \"y \\<in> ?rhs\"\n        proof (cases \"y=b\")\n          case True\n          with fn \\<open>n>0\\<close> show ?thesis\n            by (rule_tac a=\"n-1\" in UN_I) auto\n        next\n          case False\n          with y show ?thesis \n            apply (simp add: subset_iff Bex_def)\n            by (metis atLeastAtMost_iff of_nat_Suc order_le_less yidx_gt fa_yidx_le yidx_less_n)\n        qed\n      qed\n      show \"?rhs \\<subseteq> ?lhs\"\n        apply clarsimp\n        by (smt (verit, best) a_seg_ge_0 a_seg_le_a f f_iff(2) nat_less_real_le of_nat_0_le_iff)\n    qed\n\n    define g1 where \"g1 \\<equiv> \\<lambda>y. if y=b then a else a_seg (Suc (yidx y))\"\n    define g2 where \"g2 \\<equiv> \\<lambda>y. if y=0 then 0 else a_seg (yidx y)\"\n    have g1: \"g1 y \\<in> {0..a}\" if \"y \\<in> {0..b}\" for y\n      using that \\<open>a > 0\\<close> yidx_less_n [of y] by (auto simp: g1_def a_seg_def divide_simps)\n    have g2: \"g2 y \\<in> {0..a}\" if \"y \\<in> {0..b}\" for y\n      using that \\<open>a > 0\\<close> yidx_le_n [of y] by (simp add: g2_def a_seg_def divide_simps)\n\n    have g2_le_g: \"g2 y \\<le> g y\" if \"y \\<in> {0..b}\" for y\n    proof -\n      have \"f (g2 y) \\<le> y\"\n        using \\<open>f 0 = 0\\<close> g2_def that fa_yidx_le by presburger\n      then have \"f (g2 y) \\<le> f (g y)\"\n        using that g by (smt (verit, best) atLeastAtMost_iff fim image_iff)\n      then show ?thesis\n        by (smt (verit, best) atLeastAtMost_iff fim g g2 imageE sm_0a strict_mono_onD that)\n    qed\n    have g_le_g1: \"g y \\<le> g1 y\" if \"y \\<in> {0..b}\" for y\n    proof -\n      have \"y \\<le> f (g1 y)\"\n        by (smt (verit, best) \\<open>f a = b\\<close> g1_def that yidx_gt)\n      then have \"f (g y) \\<le> f (g1 y)\"\n        using that g by (smt (verit, best) atLeastAtMost_iff fim image_iff)\n      then show ?thesis\n        by (smt (verit, ccfv_threshold) atLeastAtMost_iff f_iff(1) g1 that)\n    qed\n\n    define DN where \"DN \\<equiv> \\<lambda>K. nat \\<lfloor>Inf K * real n / a\\<rfloor>\"\n    have [simp]: \"DN {a * real k / n..a * (1 + real k) / n} = k\" for k\n      using \\<open>n > 0\\<close> \\<open>a > 0\\<close> by (simp add: DN_def divide_simps)\n    have DN: \"bij_betw DN ?\\<D> {..<n}\"\n    proof (intro bij_betw_imageI)\n      show \"inj_on DN (regular_division 0 a n)\"\n      proof\n        fix K K'\n        assume \"K \\<in> regular_division 0 a n\"\n        with \\<open>a > 0\\<close> obtain k where k: \"K = {a * (real k / n) .. a * (1 + real k) / n}\"\n          by (force elim: regular_divisionE)\n        assume \"K' \\<in> regular_division 0 a n\"\n        with \\<open>a > 0\\<close> obtain k' where k': \"K' = {a * (real k' / n) .. a * (1 + real k') / n}\"\n          by (force elim: regular_divisionE)\n        assume \"DN K = DN K'\"\n        then show \"K = K'\" by (simp add: k k')\n      qed\n      have \"\\<exists>K\\<in>regular_division 0 a n. k = nat \\<lfloor>Inf K * real n / a\\<rfloor>\" if \"k < n\" for k\n        using \\<open>n > 0\\<close> \\<open>a > 0\\<close> that\n        by (force simp: divide_simps intro: regular_division_eqI [OF refl])\n      with \\<open>a>0\\<close> show \"DN ` regular_division 0 a n = {..<n}\"\n        by (auto simp: DN_def bij_betw_def image_iff frac_le elim!: regular_divisionE)\n    qed\n \n    have int_f1: \"(f1 has_integral (\\<Sum>k<n. f(a_seg k)) * (a/n)) {0..a}\"\n    proof -\n      have \"a_seg (real (DN K)) = Inf K\" if \"K \\<in> ?\\<D>\" for K\n        using that \\<open>a>0\\<close> by (auto simp: DN_def field_simps a_seg_def elim: regular_divisionE)\n      then have \"(\\<Sum>K\\<in>?\\<D>. f(Inf K) * (a/n)) = (\\<Sum>k<n. (f(a_seg k)) * (a/n))\"\n        by (simp flip: sum.reindex_bij_betw [OF DN])\n      moreover have \"(f1 has_integral (\\<Sum>K\\<in>?\\<D>. f(Inf K) * (a/n))) {0..a}\"\n        by (intro div int_f1_D has_integral_combine_division)\n      ultimately show ?thesis\n        by (metis sum_distrib_right)\n    qed\n    text \\<open>The claim @{term \"(f2 has_integral (\\<Sum>k<n. f(a_seg(Suc k))) * (a/n)) {0..a}\"} can similarly be proved\\<close>\n\n    have int_g1_D: \"(g1 has_integral a_seg (Suc k) * (f (a_seg (Suc k)) - f (a_seg k))) \n                    {f(a_seg k)..f(a_seg (Suc k))}\" \n     and int_g2_D: \"(g2 has_integral a_seg k * (f (a_seg (Suc k)) - f (a_seg k))) \n                    {f(a_seg k)..f(a_seg (Suc k))}\" \n      if \"k < n\" for k\n    proof -\n      define u where \"u \\<equiv> f (a_seg k)\"\n      define v where \"v \\<equiv> f (a_seg (Suc k))\"\n      obtain \"u < v\" \"0 \\<le> u\" \"0 \\<le> v\"\n        unfolding u_def v_def assms\n        by (smt (verit, best) a_seg_ge_0 a_seg_le_iff f(1) f_iff(1) of_nat_0_le_iff of_nat_Suc)\n      have \"u \\<le> b\" \"v \\<le> b\"\n        using \\<open>k < n\\<close> \\<open>a \\<ge> 0\\<close> by (simp_all add: u_def v_def flip: \\<open>f a = b\\<close>)\n      have yidx_eq: \"yidx x = k\" if \"x \\<in> {u..<v}\" for x\n        using \\<open>0 \\<le> u\\<close> \\<open>v \\<le> b\\<close> that u_def v_def yidx_equality by auto\n\n      have \"g1 x = a_seg (Suc k)\" if \"x \\<in> {u..<v}\" for x\n        using that \\<open>v \\<le> b\\<close> by (simp add: g1_def yidx_eq)\n      moreover have \"((\\<lambda>x. a_seg (Suc k)) has_integral (a_seg (Suc k) * (v-u))) {u..v}\"\n        using has_integral_const_real \\<open>u < v\\<close>\n        by (metis content_real_if less_eq_real_def mult.commute real_scaleR_def)\n      ultimately show \"(g1 has_integral (a_seg (Suc k) * (v-u))) {u..v}\"\n        using has_integral_spike_finite_eq [of \"{v}\" \"{u..v}\" \"\\<lambda>x. a_seg (Suc k)\" g1] by simp\n\n      have g2: \"g2 x = a_seg k\" if \"x \\<in> {u<..<v}\" for x\n        using that \\<open>0 \\<le> u\\<close> by (simp add: g2_def yidx_eq)\n      moreover have \"((\\<lambda>x. a_seg k) has_integral (a_seg k * (v-u))) {u..v}\"\n        using has_integral_const_real \\<open>u < v\\<close>\n        by (metis content_real_if less_eq_real_def mult.commute real_scaleR_def)\n      ultimately show \"(g2 has_integral (a_seg k * (v-u))) {u..v}\"\n        using has_integral_spike_finite_eq [of \"{u,v}\" \"{u..v}\" \"\\<lambda>x. a_seg k\" g2] by simp\n    qed\n\n    have int_g1: \"(g1 has_integral (\\<Sum>k<n. a_seg (Suc k) * (f (a_seg (Suc k)) - f (a_seg k)))) {0..b}\"\n    and int_g2: \"(g2 has_integral (\\<Sum>k<n. a_seg k * (f (a_seg (Suc k)) - f (a_seg k)))) {0..b}\"\n      unfolding zero_to_b_eq using int_g1_D int_g2_D\n      by (auto simp: min_def pairwise_def intro!: has_integral_UN negligible_atLeastAtMostI)\n\n    have \"(\\<Sum>k<n. a_seg (Suc k) * (f (a_seg (Suc k)) - f (a_seg k)))\n        = (\\<Sum>k<n. (Suc k) * (f (a_seg (Suc k)) - f (a_seg k))) * (a/n)\"\n      unfolding a_seg_def sum_distrib_right sum_divide_distrib by (simp add: mult_ac)\n    also have \"\\<dots> = (n * f (a_seg n) - (\\<Sum>k<n. f (a_seg k))) * a / n\"\n      using weighted_nesting_sum [where g = \"f o a_seg\"] by simp\n    also have \"\\<dots> = a * b - (\\<Sum>k<n. f (a_seg k)) * a / n\"\n      using \\<open>n > 0\\<close> by (simp add: fa_eq_b field_simps)\n    finally have int_g1': \"(g1 has_integral a * b - (\\<Sum>k<n. f (a_seg k)) * a / n) {0..b}\"\n      using int_g1 by simp\n    text \\<open>The claim @{term \"(g2 has_integral a * b - (\\<Sum>k<n. f (a_seg (Suc k))) * a / n) {0..b}\"} can similarly be proved.\\<close> \n\n    have a_seg_diff: \"a_seg (Suc k) - a_seg k = a/n\" for k\n      by (simp add: a_seg_def field_split_simps)\n    have f_a_seg_diff: \"\\<bar>f (a_seg (Suc k)) - f (a_seg k)\\<bar> < \\<epsilon>/a\" if \"k<n\" for k\n      using that \\<open>a > 0\\<close> a_seg_diff an_less_del \\<open>\\<epsilon> > 0\\<close>\n      by (intro del) auto\n\n    have \"((\\<lambda>x. g1 x - g2 x) has_integral (\\<Sum>k<n. (f (a_seg (Suc k)) - f (a_seg k)) * (a/n))) {0..b}\"\n      using has_integral_diff [OF int_g1 int_g2] a_seg_diff\n      apply (simp flip: sum_subtractf left_diff_distrib)\n      apply (simp add: field_simps)\n      done\n    moreover have \"(\\<Sum>k<n. (f (a_seg (Suc k)) - f (a_seg k)) * (a/n)) < \\<epsilon>\"\n    proof -\n      have \"(\\<Sum>k<n. (f (a_seg (Suc k)) - f (a_seg k)) * (a/n)) \n         \\<le> (\\<Sum>k<n. \\<bar>f (a_seg (Suc k)) - f (a_seg k)\\<bar> * (a/n))\"\n        by simp\n      also have \"\\<dots> < (\\<Sum>k<n. (\\<epsilon>/a) * (a/n))\"\n      proof (rule sum_strict_mono)\n        fix k assume \"k \\<in> {..<n}\"\n        with \\<open>n > 0\\<close> \\<open>a > 0\\<close> divide_strict_right_mono f_a_seg_diff pos_less_divide_eq\n        show \"\\<bar>f (a_seg (Suc k)) - f (a_seg k)\\<bar> * (a/n) < \\<epsilon>/a * (a/n)\" by fastforce\n      qed (use \\<open>n > 0\\<close> in auto)\n      also have \"\\<dots> = \\<epsilon>\"\n        using \\<open>n > 0\\<close> \\<open>a > 0\\<close> by simp\n      finally show ?thesis .\n    qed\n    ultimately have g2_near_g1: \"integral {0..b} (\\<lambda>x. g1 x - g2 x) < \\<epsilon>\"\n      by (simp add: integral_unique)\n\n    have ab1: \"integral {0..a} f1 + integral {0..b} g1 = a*b\"\n      using int_f1 int_g1' by (simp add: integral_unique)\n\n    have \"integral {0..a} (\\<lambda>x. f x - f1 x) \\<le> integral {0..a} (\\<lambda>x. f2 x - f1 x)\"\n    proof (rule integral_le)\n      show \"(\\<lambda>x. f x - f1 x) integrable_on {0..a}\" \"(\\<lambda>x. f2 x - f1 x) integrable_on {0..a}\"\n        using Henstock_Kurzweil_Integration.integrable_diff int_f1 intgb_f f12 by blast+\n    qed (auto simp: f2_upper)\n    with f2_near_f1 have \"integral {0..a} (\\<lambda>x. f x - f1 x) < \\<epsilon>\"\n      by simp\n    moreover have \"integral {0..a} f1 \\<le> integral {0..a} f\"\n      by (intro integral_le has_integral_integral intgb_f has_integral_integrable [OF int_f1]) \n         (simp add: f1_lower)\n    ultimately have f_error: \"\\<bar>integral {0..a} f - integral {0..a} f1\\<bar> < \\<epsilon>\"\n      using Henstock_Kurzweil_Integration.integral_diff int_f1 intgb_f by fastforce\n\n    have \"integral {0..b} (\\<lambda>x. g1 x - g x) \\<le> integral {0..b} (\\<lambda>x. g1 x - g2 x)\"\n    proof (rule integral_le)\n      show \"(\\<lambda>x. g1 x - g x) integrable_on {0..b}\" \"(\\<lambda>x. g1 x - g2 x) integrable_on {0..b}\"\n        using Henstock_Kurzweil_Integration.integrable_diff int_g1 int_g2 intgb_g by blast+\n    qed (auto simp: g2_le_g)\n    with g2_near_g1 have \"integral {0..b} (\\<lambda>x. g1 x - g x) < \\<epsilon>\"\n      by simp\n    moreover have \"integral {0..b} g \\<le> integral {0..b} g1\"\n      by (intro integral_le has_integral_integral intgb_g has_integral_integrable [OF int_g1]) \n         (simp add: g_le_g1)\n    ultimately have g_error: \"\\<bar>integral {0..b} g1 - integral {0..b} g\\<bar> < \\<epsilon>\"\n      using integral_diff int_g1 intgb_g by fastforce\n    show ?thesis\n      using f_error g_error ab1 by linarith\n  qed\n  show ?thesis\n    using * [of \"\\<bar>a * b - integral {0..a} f - integral {0..b} g\\<bar> / 2\"] by fastforce\nqed (use assms in force)\n\n\n\ncorollary Youngs_strict:\n  fixes f :: \"real \\<Rightarrow> real\"\n  assumes sm: \"strict_mono_on {0..} f\" and cont: \"continuous_on {0..} f\" and \"a>0\" \"b\\<ge>0\"\n    and f: \"f 0 = 0\" \"f a \\<noteq> b\" and fim: \"f ` {0..} = {0..}\"\n    and g: \"\\<And>x. 0 \\<le> x \\<Longrightarrow> g (f x) = x\"\n  shows \"a*b < integral {0..a} f + integral {0..b} g\"\nproof -\n  have f_iff [simp]: \"f x < f y \\<longleftrightarrow> x < y\" \"f x \\<le> f y \\<longleftrightarrow> x \\<le> y\"\n    if \"x \\<ge> 0\" \"y \\<ge> 0\" for x y\n    using that by (smt (verit, best) atLeast_iff sm strict_mono_onD)+\n  let ?b' = \"f a\"\n  have \"?b' \\<ge> 0\"\n    by (smt (verit, best) \\<open>0 < a\\<close> atLeast_iff f sm strict_mono_onD)\n  then have sm_gx: \"strict_mono_on {0..} g\"\n    unfolding strict_mono_on_def\n    by (smt (verit, best) atLeast_iff f_iff(1) f_inv_into_f fim g inv_into_into)\n  show ?thesis\n  proof (cases \"?b' < b\")\n    case True\n    have gt_a: \"a < g y\" if \"y \\<in> {?b'<..b}\" for y\n    proof -\n      have \"a = g ?b'\"\n        using \\<open>a > 0\\<close> g by force\n      also have \"\\<dots> < g y\"\n        using \\<open>0 \\<le> ?b'\\<close> sm_gx strict_mono_onD that by fastforce\n      finally show ?thesis .\n    qed\n    have \"continuous_on {0..} g\"\n      by (metis cont f(1) fim g sm strict_mono_continuous_invD)\n    then have contg: \"continuous_on {?b'..b} g\"\n      by (meson Icc_subset_Ici_iff \\<open>0 \\<le> f a\\<close> continuous_on_subset)\n    have \"mono_on {0..} g\"\n      by (simp add: sm_gx strict_mono_on_imp_mono_on)\n    then have int_g0b: \"g integrable_on {0..b}\"\n      by (simp add: integrable_on_mono_on mono_on_subset)\n    then have int_gb'b: \"g integrable_on {?b'..b}\"\n      by (simp add: \\<open>0 \\<le> ?b'\\<close> integrable_on_subinterval)\n    have \"a * (b - ?b') = integral {?b'..b} (\\<lambda>y. a)\"\n      using True by force\n    also have \"\\<dots> < integral {?b'..b} g\"\n      using contg True gt_a by (intro integral_less_real) auto\n    finally have *: \"a * (b - ?b') < integral {?b'..b} g\" .\n    have \"a*b = a * ?b' + a * (b - ?b')\"\n      by (simp add: algebra_simps)\n    also have \"\\<dots> = integral {0..a} f + integral {0..?b'} g + a * (b - ?b')\"\n      using Youngs_exact \\<open>a > 0\\<close> cont \\<open>f 0 = 0\\<close> g sm by force\n    also have \"\\<dots> < integral {0..a} f + integral {0..?b'} g + integral {?b'..b} g\"\n      by (simp add: *)\n    also have \"\\<dots> = integral {0..a} f + integral {0..b} g\"\n      by (smt (verit) Henstock_Kurzweil_Integration.integral_combine True \\<open>0 \\<le> ?b'\\<close> int_g0b)\n    finally show ?thesis .\n  next\n    case False\n    with f have \"b < ?b'\" by force\n    obtain a' where \"f a' = b\" \"a' \\<ge> 0\"\n      using fim \\<open>b \\<ge> 0\\<close> by force \n    then have \"a' < a\"\n      using \\<open>b < f a\\<close> \\<open>a > 0\\<close> by force\n    have gt_b: \"b < f x\" if \"x \\<in> {a'<..a}\" for x\n      using \\<open>0 \\<le> a'\\<close> \\<open>f a' = b\\<close> that by fastforce\n    have int_f0a: \"f integrable_on {0..a}\"\n      by (simp add: integrable_on_mono_on mono_on_def)\n    then have int_fa'a: \"f integrable_on {a'..a}\"\n      by (simp add: \\<open>0 \\<le> a'\\<close> integrable_on_subinterval)\n    have cont_f': \"continuous_on {a'..a} f\"\n      by (meson Icc_subset_Ici_iff \\<open>0 \\<le> a'\\<close> cont continuous_on_subset)\n    have \"b * (a - a') = integral {a'..a} (\\<lambda>x. b)\"\n      using \\<open>a' < a\\<close> by simp\n    also have \"\\<dots> < integral {a'..a} f\"\n      using cont_f' \\<open>a' < a\\<close> gt_b by (intro integral_less_real) auto\n    finally have *: \"b * (a - a') < integral {a'..a} f\" .\n    have \"a*b = a' * b + b * (a - a')\"\n      by (simp add: algebra_simps)\n    also have \"\\<dots> = integral {0..a'} f + integral {0..b} g + b * (a - a')\"\n      by (simp add: Youngs_exact \\<open>0 \\<le> a'\\<close> \\<open>f a' = b\\<close> cont f g sm)\n    also have \"\\<dots> < integral {0..a'} f + integral {0..b} g + integral {a'..a} f\"\n      by (simp add: *)\n    also have \"\\<dots> = integral {0..a} f + integral {0..b} g\"\n      by (smt (verit) Henstock_Kurzweil_Integration.integral_combine \\<open>0 \\<le> a'\\<close> \\<open>a' < a\\<close> int_f0a)\n    finally show ?thesis .\n  qed\nqed\n\ncorollary Youngs_inequality:\n  fixes f :: \"real \\<Rightarrow> real\"\n  assumes sm: \"strict_mono_on {0..} f\" and cont: \"continuous_on {0..} f\" and \"a\\<ge>0\" \"b\\<ge>0\"\n    and f: \"f 0 = 0\" and fim: \"f ` {0..} = {0..}\"\n    and g: \"\\<And>x. 0 \\<le> x \\<Longrightarrow> g (f x) = x\"\n  shows \"a*b \\<le> integral {0..a} f + integral {0..b} g\"\nproof (cases \"a=0\")\n  case True\n  have \"g x \\<ge> 0\" if \"x \\<ge> 0\" for x\n    by (metis atLeast_iff fim g imageE that)\n  then have \"0 \\<le> integral {0..b} g\"\n    by (metis Henstock_Kurzweil_Integration.integral_nonneg atLeastAtMost_iff \n              not_integrable_integral order_refl)\n  then show ?thesis \n    by (simp add: True)\nnext\n  case False\n  then show ?thesis\n    by (smt (verit) assms Youngs_exact Youngs_strict)\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/Youngs_Inequality/Youngs.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8397339676722393, "lm_q2_score": 0.8596637487122111, "lm_q1q2_score": 0.7218888505700959}}
{"text": "(* Author: Peter Lammich\n           Tobias Nipkow (tuning)\n*)\n\nsection \\<open>Binomial Heap\\<close>\n\ntheory Binomial_Heap\nimports\n  \"HOL-Library.Pattern_Aliases\"\n  Complex_Main\n  Priority_Queue_Specs\nbegin\n\ntext \\<open>\n  We formalize the binomial heap presentation from Okasaki's book.\n  We show the functional correctness and complexity of all operations.\n\n  The presentation is engineered for simplicity, and most\n  proofs are straightforward and automatic.\n\\<close>\n\nsubsection \\<open>Binomial Tree and Heap Datatype\\<close>\n\ndatatype 'a tree = Node (rank: nat) (root: 'a) (children: \"'a tree list\")\n\ntype_synonym 'a heap = \"'a tree list\"\n\nsubsubsection \\<open>Multiset of elements\\<close>\n\nfun mset_tree :: \"'a::linorder tree \\<Rightarrow> 'a multiset\" where\n  \"mset_tree (Node _ a ts) = {#a#} + (\\<Sum>t\\<in>#mset ts. mset_tree t)\"\n\ndefinition mset_heap :: \"'a::linorder heap \\<Rightarrow> 'a multiset\" where\n  \"mset_heap ts = (\\<Sum>t\\<in>#mset ts. mset_tree t)\"\n\nlemma mset_tree_simp_alt[simp]:\n  \"mset_tree (Node r a ts) = {#a#} + mset_heap ts\"\n  unfolding mset_heap_def by auto\ndeclare mset_tree.simps[simp del]\n\nlemma mset_tree_nonempty[simp]: \"mset_tree t \\<noteq> {#}\"\nby (cases t) auto\n\nlemma mset_heap_Nil[simp]:\n  \"mset_heap [] = {#}\"\nby (auto simp: mset_heap_def)\n\nlemma mset_heap_Cons[simp]: \"mset_heap (t#ts) = mset_tree t + mset_heap ts\"\nby (auto simp: mset_heap_def)\n\nlemma mset_heap_empty_iff[simp]: \"mset_heap ts = {#} \\<longleftrightarrow> ts=[]\"\nby (auto simp: mset_heap_def)\n\nlemma root_in_mset[simp]: \"root t \\<in># mset_tree t\"\nby (cases t) auto\n\nlemma mset_heap_rev_eq[simp]: \"mset_heap (rev ts) = mset_heap ts\"\nby (auto simp: mset_heap_def)\n\nsubsubsection \\<open>Invariants\\<close>\n\ntext \\<open>Binomial tree\\<close>\nfun invar_btree :: \"'a::linorder tree \\<Rightarrow> bool\" where\n\"invar_btree (Node r x ts) \\<longleftrightarrow>\n   (\\<forall>t\\<in>set ts. invar_btree t) \\<and> map rank ts = rev [0..<r]\"\n\ntext \\<open>Ordering (heap) invariant\\<close>\nfun invar_otree :: \"'a::linorder tree \\<Rightarrow> bool\" where\n\"invar_otree (Node _ x ts) \\<longleftrightarrow> (\\<forall>t\\<in>set ts. invar_otree t \\<and> x \\<le> root t)\"\n\ndefinition \"invar_tree t \\<longleftrightarrow> invar_btree t \\<and> invar_otree t\"\n\ntext \\<open>Binomial Heap invariant\\<close>\ndefinition \"invar ts \\<longleftrightarrow> (\\<forall>t\\<in>set ts. invar_tree t) \\<and> (sorted_wrt (<) (map rank ts))\"\n\n\ntext \\<open>The children of a node are a valid heap\\<close>\nlemma invar_children:\n  \"invar_tree (Node r v ts) \\<Longrightarrow> invar (rev ts)\"\n  by (auto simp: invar_tree_def invar_def rev_map[symmetric])\n\n\nsubsection \\<open>Operations and Their Functional Correctness\\<close>\n\nsubsubsection \\<open>\\<open>link\\<close>\\<close>\n\ncontext\nincludes pattern_aliases\nbegin\n\nfun link :: \"('a::linorder) tree \\<Rightarrow> 'a tree \\<Rightarrow> 'a tree\" where\n  \"link (Node r x\\<^sub>1 ts\\<^sub>1 =: t\\<^sub>1) (Node r' x\\<^sub>2 ts\\<^sub>2 =: t\\<^sub>2) =\n    (if x\\<^sub>1\\<le>x\\<^sub>2 then Node (r+1) x\\<^sub>1 (t\\<^sub>2#ts\\<^sub>1) else Node (r+1) x\\<^sub>2 (t\\<^sub>1#ts\\<^sub>2))\"\n\nend\n\nlemma invar_link:\n  assumes \"invar_tree t\\<^sub>1\"\n  assumes \"invar_tree t\\<^sub>2\"\n  assumes \"rank t\\<^sub>1 = rank t\\<^sub>2\"\n  shows \"invar_tree (link t\\<^sub>1 t\\<^sub>2)\"\nusing assms unfolding invar_tree_def\nby (cases \"(t\\<^sub>1, t\\<^sub>2)\" rule: link.cases) auto\n\nlemma rank_link[simp]: \"rank (link t\\<^sub>1 t\\<^sub>2) = rank t\\<^sub>1 + 1\"\nby (cases \"(t\\<^sub>1, t\\<^sub>2)\" rule: link.cases) simp\n\nlemma mset_link[simp]: \"mset_tree (link t\\<^sub>1 t\\<^sub>2) = mset_tree t\\<^sub>1 + mset_tree t\\<^sub>2\"\nby (cases \"(t\\<^sub>1, t\\<^sub>2)\" rule: link.cases) simp\n\nsubsubsection \\<open>\\<open>ins_tree\\<close>\\<close>\n\nfun ins_tree :: \"'a::linorder tree \\<Rightarrow> 'a heap \\<Rightarrow> 'a heap\" where\n  \"ins_tree t [] = [t]\"\n| \"ins_tree t\\<^sub>1 (t\\<^sub>2#ts) =\n  (if rank t\\<^sub>1 < rank t\\<^sub>2 then t\\<^sub>1#t\\<^sub>2#ts else ins_tree (link t\\<^sub>1 t\\<^sub>2) ts)\"\n\nlemma invar_tree0[simp]: \"invar_tree (Node 0 x [])\"\nunfolding invar_tree_def by auto\n\nlemma invar_Cons[simp]:\n  \"invar (t#ts)\n  \\<longleftrightarrow> invar_tree t \\<and> invar ts \\<and> (\\<forall>t'\\<in>set ts. rank t < rank t')\"\nby (auto simp: invar_def)\n\nlemma invar_ins_tree:\n  assumes \"invar_tree t\"\n  assumes \"invar ts\"\n  assumes \"\\<forall>t'\\<in>set ts. rank t \\<le> rank t'\"\n  shows \"invar (ins_tree t ts)\"\nusing assms\nby (induction t ts rule: ins_tree.induct) (auto simp: invar_link less_eq_Suc_le[symmetric])\n\nlemma mset_heap_ins_tree[simp]:\n  \"mset_heap (ins_tree t ts) = mset_tree t + mset_heap ts\"\nby (induction t ts rule: ins_tree.induct) auto\n\nlemma ins_tree_rank_bound:\n  assumes \"t' \\<in> set (ins_tree t ts)\"\n  assumes \"\\<forall>t'\\<in>set ts. rank t\\<^sub>0 < rank t'\"\n  assumes \"rank t\\<^sub>0 < rank t\"\n  shows \"rank t\\<^sub>0 < rank t'\"\nusing assms\nby (induction t ts rule: ins_tree.induct) (auto split: if_splits)\n\nsubsubsection \\<open>\\<open>insert\\<close>\\<close>\n\nhide_const (open) insert\n\ndefinition insert :: \"'a::linorder \\<Rightarrow> 'a heap \\<Rightarrow> 'a heap\" where\n\"insert x ts = ins_tree (Node 0 x []) ts\"\n\nlemma invar_insert[simp]: \"invar t \\<Longrightarrow> invar (insert x t)\"\nby (auto intro!: invar_ins_tree simp: insert_def)\n\nlemma mset_heap_insert[simp]: \"mset_heap (insert x t) = {#x#} + mset_heap t\"\nby(auto simp: insert_def)\n\nsubsubsection \\<open>\\<open>merge\\<close>\\<close>\n\ncontext\nincludes pattern_aliases\nbegin\n\nfun merge :: \"'a::linorder heap \\<Rightarrow> 'a heap \\<Rightarrow> 'a heap\" where\n  \"merge ts\\<^sub>1 [] = ts\\<^sub>1\"\n| \"merge [] ts\\<^sub>2 = ts\\<^sub>2\"\n| \"merge (t\\<^sub>1#ts\\<^sub>1 =: h\\<^sub>1) (t\\<^sub>2#ts\\<^sub>2 =: h\\<^sub>2) = (\n    if rank t\\<^sub>1 < rank t\\<^sub>2 then t\\<^sub>1 # merge ts\\<^sub>1 h\\<^sub>2 else\n    if rank t\\<^sub>2 < rank t\\<^sub>1 then t\\<^sub>2 # merge h\\<^sub>1 ts\\<^sub>2\n    else ins_tree (link t\\<^sub>1 t\\<^sub>2) (merge ts\\<^sub>1 ts\\<^sub>2)\n  )\"\n\nend\n\nlemma merge_simp2[simp]: \"merge [] ts\\<^sub>2 = ts\\<^sub>2\"\nby (cases ts\\<^sub>2) auto\n\nlemma merge_rank_bound:\n  assumes \"t' \\<in> set (merge ts\\<^sub>1 ts\\<^sub>2)\"\n  assumes \"\\<forall>t\\<^sub>1\\<in>set ts\\<^sub>1. rank t < rank t\\<^sub>1\"\n  assumes \"\\<forall>t\\<^sub>2\\<in>set ts\\<^sub>2. rank t < rank t\\<^sub>2\"\n  shows \"rank t < rank t'\"\nusing assms\nby (induction ts\\<^sub>1 ts\\<^sub>2 arbitrary: t' rule: merge.induct)\n   (auto split: if_splits simp: ins_tree_rank_bound)\n\nlemma invar_merge[simp]:\n  assumes \"invar ts\\<^sub>1\"\n  assumes \"invar ts\\<^sub>2\"\n  shows \"invar (merge ts\\<^sub>1 ts\\<^sub>2)\"\nusing assms\nby (induction ts\\<^sub>1 ts\\<^sub>2 rule: merge.induct)\n   (auto 0 3 simp: Suc_le_eq intro!: invar_ins_tree invar_link elim!: merge_rank_bound)\n\n\ntext \\<open>Longer, more explicit proof of @{thm [source] invar_merge}, \n      to illustrate the application of the @{thm [source] merge_rank_bound} lemma.\\<close>\nlemma \n  assumes \"invar ts\\<^sub>1\"\n  assumes \"invar ts\\<^sub>2\"\n  shows \"invar (merge ts\\<^sub>1 ts\\<^sub>2)\"\n  using assms\nproof (induction ts\\<^sub>1 ts\\<^sub>2 rule: merge.induct)\n  case (3 t\\<^sub>1 ts\\<^sub>1 t\\<^sub>2 ts\\<^sub>2)\n  \\<comment> \\<open>Invariants of the parts can be shown automatically\\<close>\n  from \"3.prems\" have [simp]: \n    \"invar_tree t\\<^sub>1\" \"invar_tree t\\<^sub>2\"\n    (*\"invar (merge (t\\<^sub>1#ts\\<^sub>1) ts\\<^sub>2)\" \n    \"invar (merge ts\\<^sub>1 (t\\<^sub>2#ts\\<^sub>2))\"\n    \"invar (merge ts\\<^sub>1 ts\\<^sub>2)\"*)\n    by auto\n\n  \\<comment> \\<open>These are the three cases of the @{const merge} function\\<close>\n  consider (LT) \"rank t\\<^sub>1 < rank t\\<^sub>2\"\n         | (GT) \"rank t\\<^sub>1 > rank t\\<^sub>2\"\n         | (EQ) \"rank t\\<^sub>1 = rank t\\<^sub>2\"\n    using antisym_conv3 by blast\n  then show ?case proof cases\n    case LT \n    \\<comment> \\<open>@{const merge} takes the first tree from the left heap\\<close>\n    then have \"merge (t\\<^sub>1 # ts\\<^sub>1) (t\\<^sub>2 # ts\\<^sub>2) = t\\<^sub>1 # merge ts\\<^sub>1 (t\\<^sub>2 # ts\\<^sub>2)\" by simp\n    also have \"invar \\<dots>\" proof (simp, intro conjI)\n      \\<comment> \\<open>Invariant follows from induction hypothesis\\<close>\n      show \"invar (merge ts\\<^sub>1 (t\\<^sub>2 # ts\\<^sub>2))\"\n        using LT \"3.IH\" \"3.prems\" by simp\n\n      \\<comment> \\<open>It remains to show that \\<open>t\\<^sub>1\\<close> has smallest rank.\\<close>\n      show \"\\<forall>t'\\<in>set (merge ts\\<^sub>1 (t\\<^sub>2 # ts\\<^sub>2)). rank t\\<^sub>1 < rank t'\"\n        \\<comment> \\<open>Which is done by auxiliary lemma @{thm [source] merge_rank_bound}\\<close>\n        using LT \"3.prems\" by (force elim!: merge_rank_bound)\n    qed\n    finally show ?thesis .\n  next\n    \\<comment> \\<open>@{const merge} takes the first tree from the right heap\\<close>\n    case GT \n    \\<comment> \\<open>The proof is anaologous to the \\<open>LT\\<close> case\\<close>\n    then show ?thesis using \"3.prems\" \"3.IH\" by (force elim!: merge_rank_bound)\n  next\n    case [simp]: EQ\n    \\<comment> \\<open>@{const merge} links both first trees, and inserts them into the merged remaining heaps\\<close>\n    have \"merge (t\\<^sub>1 # ts\\<^sub>1) (t\\<^sub>2 # ts\\<^sub>2) = ins_tree (link t\\<^sub>1 t\\<^sub>2) (merge ts\\<^sub>1 ts\\<^sub>2)\" by simp\n    also have \"invar \\<dots>\" proof (intro invar_ins_tree invar_link) \n      \\<comment> \\<open>Invariant of merged remaining heaps follows by IH\\<close>\n      show \"invar (merge ts\\<^sub>1 ts\\<^sub>2)\"\n        using EQ \"3.prems\" \"3.IH\" by auto\n\n      \\<comment> \\<open>For insertion, we have to show that the rank of the linked tree is \\<open>\\<le>\\<close> the \n          ranks in the merged remaining heaps\\<close>\n      show \"\\<forall>t'\\<in>set (merge ts\\<^sub>1 ts\\<^sub>2). rank (link t\\<^sub>1 t\\<^sub>2) \\<le> rank t'\"\n      proof -\n        \\<comment> \\<open>Which is, again, done with the help of @{thm [source] merge_rank_bound}\\<close>\n        have \"rank (link t\\<^sub>1 t\\<^sub>2) = Suc (rank t\\<^sub>2)\" by simp\n        thus ?thesis using \"3.prems\" by (auto simp: Suc_le_eq elim!: merge_rank_bound)\n      qed\n    qed simp_all\n    finally show ?thesis .\n  qed\nqed auto\n\n\nlemma mset_heap_merge[simp]:\n  \"mset_heap (merge ts\\<^sub>1 ts\\<^sub>2) = mset_heap ts\\<^sub>1 + mset_heap ts\\<^sub>2\"\nby (induction ts\\<^sub>1 ts\\<^sub>2 rule: merge.induct) auto\n\nsubsubsection \\<open>\\<open>get_min\\<close>\\<close>\n\nfun get_min :: \"'a::linorder heap \\<Rightarrow> 'a\" where\n  \"get_min [t] = root t\"\n| \"get_min (t#ts) = min (root t) (get_min ts)\"\n\nlemma invar_tree_root_min:\n  assumes \"invar_tree t\"\n  assumes \"x \\<in># mset_tree t\"\n  shows \"root t \\<le> x\"\nusing assms unfolding invar_tree_def\nby (induction t arbitrary: x rule: mset_tree.induct) (fastforce simp: mset_heap_def)\n\nlemma get_min_mset:\n  assumes \"ts\\<noteq>[]\"\n  assumes \"invar ts\"\n  assumes \"x \\<in># mset_heap ts\"\n  shows \"get_min ts \\<le> x\"\n  using assms\napply (induction ts arbitrary: x rule: get_min.induct)\napply (auto\n      simp: invar_tree_root_min min_def intro: order_trans;\n      meson linear order_trans invar_tree_root_min\n      )+\ndone\n\nlemma get_min_member:\n  \"ts\\<noteq>[] \\<Longrightarrow> get_min ts \\<in># mset_heap ts\"\nby (induction ts rule: get_min.induct) (auto simp: min_def)\n\nlemma get_min:\n  assumes \"mset_heap ts \\<noteq> {#}\"\n  assumes \"invar ts\"\n  shows \"get_min ts = Min_mset (mset_heap ts)\"\nusing assms get_min_member get_min_mset\nby (auto simp: eq_Min_iff)\n\nsubsubsection \\<open>\\<open>get_min_rest\\<close>\\<close>\n\nfun get_min_rest :: \"'a::linorder heap \\<Rightarrow> 'a tree \\<times> 'a heap\" where\n  \"get_min_rest [t] = (t,[])\"\n| \"get_min_rest (t#ts) = (let (t',ts') = get_min_rest ts\n                     in if root t \\<le> root t' then (t,ts) else (t',t#ts'))\"\n\nlemma get_min_rest_get_min_same_root:\n  assumes \"ts\\<noteq>[]\"\n  assumes \"get_min_rest ts = (t',ts')\"\n  shows \"root t' = get_min ts\"\nusing assms\nby (induction ts arbitrary: t' ts' rule: get_min.induct) (auto simp: min_def split: prod.splits)\n\nlemma mset_get_min_rest:\n  assumes \"get_min_rest ts = (t',ts')\"\n  assumes \"ts\\<noteq>[]\"\n  shows \"mset ts = {#t'#} + mset ts'\"\nusing assms\nby (induction ts arbitrary: t' ts' rule: get_min.induct) (auto split: prod.splits if_splits)\n\nlemma set_get_min_rest:\n  assumes \"get_min_rest ts = (t', ts')\"\n  assumes \"ts\\<noteq>[]\"\n  shows \"set ts = Set.insert t' (set ts')\"\nusing mset_get_min_rest[OF assms, THEN arg_cong[where f=set_mset]]\nby auto\n\nlemma invar_get_min_rest:\n  assumes \"get_min_rest ts = (t',ts')\"\n  assumes \"ts\\<noteq>[]\"\n  assumes \"invar ts\"\n  shows \"invar_tree t'\" and \"invar ts'\"\nproof -\n  have \"invar_tree t' \\<and> invar ts'\"\n    using assms\n    proof (induction ts arbitrary: t' ts' rule: get_min.induct)\n      case (2 t v va)\n      then show ?case\n        apply (clarsimp split: prod.splits if_splits)\n        apply (drule set_get_min_rest; fastforce)\n        done\n    qed auto\n  thus \"invar_tree t'\" and \"invar ts'\" by auto\nqed\n\nsubsubsection \\<open>\\<open>del_min\\<close>\\<close>\n\ndefinition del_min :: \"'a::linorder heap \\<Rightarrow> 'a::linorder heap\" where\n\"del_min ts = (case get_min_rest ts of\n   (Node r x ts\\<^sub>1, ts\\<^sub>2) \\<Rightarrow> merge (rev ts\\<^sub>1) ts\\<^sub>2)\"\n\nlemma invar_del_min[simp]:\n  assumes \"ts \\<noteq> []\"\n  assumes \"invar ts\"\n  shows \"invar (del_min ts)\"\nusing assms\nunfolding del_min_def\nby (auto\n      split: prod.split tree.split\n      intro!: invar_merge invar_children \n      dest: invar_get_min_rest\n    )\n\nlemma mset_heap_del_min:\n  assumes \"ts \\<noteq> []\"\n  shows \"mset_heap ts = mset_heap (del_min ts) + {# get_min ts #}\"\nusing assms\nunfolding del_min_def\napply (clarsimp split: tree.split prod.split)\napply (frule (1) get_min_rest_get_min_same_root)\napply (frule (1) mset_get_min_rest)\napply (auto simp: mset_heap_def)\ndone\n\n\nsubsubsection \\<open>Instantiating the Priority Queue Locale\\<close>\n\ntext \\<open>Last step of functional correctness proof: combine all the above lemmas\nto show that binomial heaps satisfy the specification of priority queues with merge.\\<close>\n\ninterpretation binheap: Priority_Queue_Merge\n  where empty = \"[]\" and is_empty = \"(=) []\" and insert = insert\n  and get_min = get_min and del_min = del_min and merge = merge\n  and invar = invar and mset = mset_heap\nproof (unfold_locales, goal_cases)\n  case 1 thus ?case by simp\nnext\n  case 2 thus ?case by auto\nnext\n  case 3 thus ?case by auto\nnext\n  case (4 q)\n  thus ?case using mset_heap_del_min[of q] get_min[OF _ \\<open>invar q\\<close>]\n    by (auto simp: union_single_eq_diff)\nnext\n  case (5 q) thus ?case using get_min[of q] by auto\nnext\n  case 6 thus ?case by (auto simp add: invar_def)\nnext\n  case 7 thus ?case by simp\nnext\n  case 8 thus ?case by simp\nnext\n  case 9 thus ?case by simp\nnext\n  case 10 thus ?case by simp\nqed\n\n\nsubsection \\<open>Complexity\\<close>\n\ntext \\<open>The size of a binomial tree is determined by its rank\\<close>\nlemma size_mset_btree:\n  assumes \"invar_btree t\"\n  shows \"size (mset_tree t) = 2^rank t\"\n  using assms\nproof (induction t)\n  case (Node r v ts)\n  hence IH: \"size (mset_tree t) = 2^rank t\" if \"t \\<in> set ts\" for t\n    using that by auto\n\n  from Node have COMPL: \"map rank ts = rev [0..<r]\" by auto\n\n  have \"size (mset_heap ts) = (\\<Sum>t\\<leftarrow>ts. size (mset_tree t))\"\n    by (induction ts) auto\n  also have \"\\<dots> = (\\<Sum>t\\<leftarrow>ts. 2^rank t)\" using IH\n    by (auto cong: map_cong)\n  also have \"\\<dots> = (\\<Sum>r\\<leftarrow>map rank ts. 2^r)\"\n    by (induction ts) auto\n  also have \"\\<dots> = (\\<Sum>i\\<in>{0..<r}. 2^i)\"\n    unfolding COMPL\n    by (auto simp: rev_map[symmetric] interv_sum_list_conv_sum_set_nat)\n  also have \"\\<dots> = 2^r - 1\"\n    by (induction r) auto\n  finally show ?case\n    by (simp)\nqed\n\nlemma size_mset_tree:\n  assumes \"invar_tree t\"\n  shows \"size (mset_tree t) = 2^rank t\"\nusing assms unfolding invar_tree_def\nby (simp add: size_mset_btree)\n\ntext \\<open>The length of a binomial heap is bounded by the number of its elements\\<close>\nlemma size_mset_heap:\n  assumes \"invar ts\"\n  shows \"length ts \\<le> log 2 (size (mset_heap ts) + 1)\"\nproof -\n  from \\<open>invar ts\\<close> have\n    ASC: \"sorted_wrt (<) (map rank ts)\" and\n    TINV: \"\\<forall>t\\<in>set ts. invar_tree t\"\n    unfolding invar_def by auto\n\n  have \"(2::nat)^length ts = (\\<Sum>i\\<in>{0..<length ts}. 2^i) + 1\"\n    by (simp add: sum_power2)\n  also have \"\\<dots> \\<le> (\\<Sum>t\\<leftarrow>ts. 2^rank t) + 1\"\n    using sorted_wrt_less_sum_mono_lowerbound[OF _ ASC, of \"(^) (2::nat)\"]\n    using power_increasing[where a=\"2::nat\"]\n    by (auto simp: o_def)\n  also have \"\\<dots> = (\\<Sum>t\\<leftarrow>ts. size (mset_tree t)) + 1\" using TINV\n    by (auto cong: map_cong simp: size_mset_tree)\n  also have \"\\<dots> = size (mset_heap ts) + 1\"\n    unfolding mset_heap_def by (induction ts) auto\n  finally have \"2^length ts \\<le> size (mset_heap ts) + 1\" .\n  then show ?thesis using le_log2_of_power by blast\nqed\n\nsubsubsection \\<open>Timing Functions\\<close>\n\ntext \\<open>\n  We define timing functions for each operation, and provide\n  estimations of their complexity.\n\\<close>\ndefinition T_link :: \"'a::linorder tree \\<Rightarrow> 'a tree \\<Rightarrow> nat\" where\n[simp]: \"T_link _ _ = 1\"\n\ntext \\<open>This function is non-canonical: we omitted a \\<open>+1\\<close> in the \\<open>else\\<close>-part,\n  to keep the following analysis simpler and more to the point.\n\\<close>\nfun T_ins_tree :: \"'a::linorder tree \\<Rightarrow> 'a heap \\<Rightarrow> nat\" where\n  \"T_ins_tree t [] = 1\"\n| \"T_ins_tree t\\<^sub>1 (t\\<^sub>2 # ts) = (\n    (if rank t\\<^sub>1 < rank t\\<^sub>2 then 1\n     else T_link t\\<^sub>1 t\\<^sub>2 + T_ins_tree (link t\\<^sub>1 t\\<^sub>2) ts)\n  )\"\n\ndefinition T_insert :: \"'a::linorder \\<Rightarrow> 'a heap \\<Rightarrow> nat\" where\n\"T_insert x ts = T_ins_tree (Node 0 x []) ts + 1\"\n\nlemma T_ins_tree_simple_bound: \"T_ins_tree t ts \\<le> length ts + 1\"\nby (induction t ts rule: T_ins_tree.induct) auto\n\nsubsubsection \\<open>\\<open>T_insert\\<close>\\<close>\n\nlemma T_insert_bound:\n  assumes \"invar ts\"\n  shows \"T_insert x ts \\<le> log 2 (size (mset_heap ts) + 1) + 2\"\nproof -\n  have \"real (T_insert x ts) \\<le> real (length ts) + 2\"\n    unfolding T_insert_def using T_ins_tree_simple_bound \n    using of_nat_mono by fastforce\n  also note size_mset_heap[OF \\<open>invar ts\\<close>]\n  finally show ?thesis by simp\nqed\n\nsubsubsection \\<open>\\<open>T_merge\\<close>\\<close>\n\ncontext\nincludes pattern_aliases\nbegin\n\nfun T_merge :: \"'a::linorder heap \\<Rightarrow> 'a heap \\<Rightarrow> nat\" where\n  \"T_merge ts\\<^sub>1 [] = 1\"\n| \"T_merge [] ts\\<^sub>2 = 1\"\n| \"T_merge (t\\<^sub>1#ts\\<^sub>1 =: h\\<^sub>1) (t\\<^sub>2#ts\\<^sub>2 =: h\\<^sub>2) = 1 + (\n    if rank t\\<^sub>1 < rank t\\<^sub>2 then T_merge ts\\<^sub>1 h\\<^sub>2\n    else if rank t\\<^sub>2 < rank t\\<^sub>1 then T_merge h\\<^sub>1 ts\\<^sub>2\n    else T_ins_tree (link t\\<^sub>1 t\\<^sub>2) (merge ts\\<^sub>1 ts\\<^sub>2) + T_merge ts\\<^sub>1 ts\\<^sub>2\n  )\"\n\nend\n\ntext \\<open>A crucial idea is to estimate the time in correlation with the\n  result length, as each carry reduces the length of the result.\\<close>\n\nlemma T_ins_tree_length:\n  \"T_ins_tree t ts + length (ins_tree t ts) = 2 + length ts\"\nby (induction t ts rule: ins_tree.induct) auto\n\nlemma T_merge_length:\n  \"length (merge ts\\<^sub>1 ts\\<^sub>2) + T_merge ts\\<^sub>1 ts\\<^sub>2 \\<le> 2 * (length ts\\<^sub>1 + length ts\\<^sub>2) + 1\"\nby (induction ts\\<^sub>1 ts\\<^sub>2 rule: T_merge.induct)\n   (auto simp: T_ins_tree_length algebra_simps)\n\ntext \\<open>Finally, we get the desired logarithmic bound\\<close>\nlemma T_merge_bound:\n  fixes ts\\<^sub>1 ts\\<^sub>2\n  defines \"n\\<^sub>1 \\<equiv> size (mset_heap ts\\<^sub>1)\"\n  defines \"n\\<^sub>2 \\<equiv> size (mset_heap ts\\<^sub>2)\"\n  assumes \"invar ts\\<^sub>1\" \"invar ts\\<^sub>2\"\n  shows \"T_merge ts\\<^sub>1 ts\\<^sub>2 \\<le> 4*log 2 (n\\<^sub>1 + n\\<^sub>2 + 1) + 1\"\nproof -\n  note n_defs = assms(1,2)\n\n  have \"T_merge ts\\<^sub>1 ts\\<^sub>2 \\<le> 2 * real (length ts\\<^sub>1) + 2 * real (length ts\\<^sub>2) + 1\"\n    using T_merge_length[of ts\\<^sub>1 ts\\<^sub>2] by simp\n  also note size_mset_heap[OF \\<open>invar ts\\<^sub>1\\<close>]\n  also note size_mset_heap[OF \\<open>invar ts\\<^sub>2\\<close>]\n  finally have \"T_merge ts\\<^sub>1 ts\\<^sub>2 \\<le> 2 * log 2 (n\\<^sub>1 + 1) + 2 * log 2 (n\\<^sub>2 + 1) + 1\"\n    unfolding n_defs by (simp add: algebra_simps)\n  also have \"log 2 (n\\<^sub>1 + 1) \\<le> log 2 (n\\<^sub>1 + n\\<^sub>2 + 1)\" \n    unfolding n_defs by (simp add: algebra_simps)\n  also have \"log 2 (n\\<^sub>2 + 1) \\<le> log 2 (n\\<^sub>1 + n\\<^sub>2 + 1)\" \n    unfolding n_defs by (simp add: algebra_simps)\n  finally show ?thesis by (simp add: algebra_simps)\nqed\n\nsubsubsection \\<open>\\<open>T_get_min\\<close>\\<close>\n\nfun T_get_min :: \"'a::linorder heap \\<Rightarrow> nat\" where\n  \"T_get_min [t] = 1\"\n| \"T_get_min (t#ts) = 1 + T_get_min ts\"\n\nlemma T_get_min_estimate: \"ts\\<noteq>[] \\<Longrightarrow> T_get_min ts = length ts\"\nby (induction ts rule: T_get_min.induct) auto\n\nlemma T_get_min_bound:\n  assumes \"invar ts\"\n  assumes \"ts\\<noteq>[]\"\n  shows \"T_get_min ts \\<le> log 2 (size (mset_heap ts) + 1)\"\nproof -\n  have 1: \"T_get_min ts = length ts\" using assms T_get_min_estimate by auto\n  also note size_mset_heap[OF \\<open>invar ts\\<close>]\n  finally show ?thesis .\nqed\n\nsubsubsection \\<open>\\<open>T_del_min\\<close>\\<close>\n\nfun T_get_min_rest :: \"'a::linorder heap \\<Rightarrow> nat\" where\n  \"T_get_min_rest [t] = 1\"\n| \"T_get_min_rest (t#ts) = 1 + T_get_min_rest ts\"\n\nlemma T_get_min_rest_estimate: \"ts\\<noteq>[] \\<Longrightarrow> T_get_min_rest ts = length ts\"\n  by (induction ts rule: T_get_min_rest.induct) auto\n\nlemma T_get_min_rest_bound:\n  assumes \"invar ts\"\n  assumes \"ts\\<noteq>[]\"\n  shows \"T_get_min_rest ts \\<le> log 2 (size (mset_heap ts) + 1)\"\nproof -\n  have 1: \"T_get_min_rest ts = length ts\" using assms T_get_min_rest_estimate by auto\n  also note size_mset_heap[OF \\<open>invar ts\\<close>]\n  finally show ?thesis .\nqed\n\ntext\\<open>Note that although the definition of function \\<^const>\\<open>rev\\<close> has quadratic complexity,\nit can and is implemented (via suitable code lemmas) as a linear time function.\nThus the following definition is justified:\\<close>\n\ndefinition \"T_rev xs = length xs + 1\"\n\ndefinition T_del_min :: \"'a::linorder heap \\<Rightarrow> nat\" where\n  \"T_del_min ts = T_get_min_rest ts + (case get_min_rest ts of (Node _ x ts\\<^sub>1, ts\\<^sub>2)\n                    \\<Rightarrow> T_rev ts\\<^sub>1 + T_merge (rev ts\\<^sub>1) ts\\<^sub>2\n  ) + 1\"\n\nlemma T_del_min_bound:\n  fixes ts\n  defines \"n \\<equiv> size (mset_heap ts)\"\n  assumes \"invar ts\" and \"ts\\<noteq>[]\"\n  shows \"T_del_min ts \\<le> 6 * log 2 (n+1) + 3\"\nproof -\n  obtain r x ts\\<^sub>1 ts\\<^sub>2 where GM: \"get_min_rest ts = (Node r x ts\\<^sub>1, ts\\<^sub>2)\"\n    by (metis surj_pair tree.exhaust_sel)\n\n  have I1: \"invar (rev ts\\<^sub>1)\" and I2: \"invar ts\\<^sub>2\"\n    using invar_get_min_rest[OF GM \\<open>ts\\<noteq>[]\\<close> \\<open>invar ts\\<close>] invar_children\n    by auto\n\n  define n\\<^sub>1 where \"n\\<^sub>1 = size (mset_heap ts\\<^sub>1)\"\n  define n\\<^sub>2 where \"n\\<^sub>2 = size (mset_heap ts\\<^sub>2)\"\n\n  have \"n\\<^sub>1 \\<le> n\" \"n\\<^sub>1 + n\\<^sub>2 \\<le> n\" unfolding n_def n\\<^sub>1_def n\\<^sub>2_def\n    using mset_get_min_rest[OF GM \\<open>ts\\<noteq>[]\\<close>]\n    by (auto simp: mset_heap_def)\n\n  have \"T_del_min ts = real (T_get_min_rest ts) + real (T_rev ts\\<^sub>1) + real (T_merge (rev ts\\<^sub>1) ts\\<^sub>2) + 1\"\n    unfolding T_del_min_def GM\n    by simp\n  also have \"T_get_min_rest ts \\<le> log 2 (n+1)\" \n    using T_get_min_rest_bound[OF \\<open>invar ts\\<close> \\<open>ts\\<noteq>[]\\<close>] unfolding n_def by simp\n  also have \"T_rev ts\\<^sub>1 \\<le> 1 + log 2 (n\\<^sub>1 + 1)\"\n    unfolding T_rev_def n\\<^sub>1_def using size_mset_heap[OF I1] by simp\n  also have \"T_merge (rev ts\\<^sub>1) ts\\<^sub>2 \\<le> 4*log 2 (n\\<^sub>1 + n\\<^sub>2 + 1) + 1\"\n    unfolding n\\<^sub>1_def n\\<^sub>2_def using T_merge_bound[OF I1 I2] by (simp add: algebra_simps)\n  finally have \"T_del_min ts \\<le> log 2 (n+1) + log 2 (n\\<^sub>1 + 1) + 4*log 2 (real (n\\<^sub>1 + n\\<^sub>2) + 1) + 3\"\n    by (simp add: algebra_simps)\n  also note \\<open>n\\<^sub>1 + n\\<^sub>2 \\<le> n\\<close>\n  also note \\<open>n\\<^sub>1 \\<le> n\\<close>\n  finally show ?thesis by (simp add: algebra_simps)\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/Binomial_Heap.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8705972751232809, "lm_q2_score": 0.8289388146603364, "lm_q1q2_score": 0.7216718732872112}}
{"text": "theory Exercises2_04\n  imports Main\nbegin\n\n(*---------------- Exercise 2.4----------------*)\n(* snoc function -- reverse of cons *)\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\n(* reverse function*)\nfun reverse :: \"'a list \\<Rightarrow> 'a list\" where\n\"reverse Nil = Nil\" |\n\"reverse (Cons x xs) = snoc (reverse xs) x\"\n\nlemma snoc_reverse : \"reverse(snoc xs a) = a # reverse xs\"\n  apply(induction xs)\n   apply(auto)\n  done\n\n\ntheorem double_rev : \"reverse (reverse xs) = xs\"\n  apply(induction xs)\n   apply(auto)\n  apply(simp add: snoc_reverse)\n  done\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_04.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8705972684083609, "lm_q2_score": 0.8289388083214156, "lm_q1q2_score": 0.7216718622023064}}
{"text": "theory Bexp\nimports Aexp\nbegin\n\nsection \\<open>Boolean Expressions\\<close>\n\ntext \\<open>We proceed as in \\verb?Aexp.thy?.\\<close>\n\nsubsection\\<open>Basic definitions\\<close>\n\nsubsubsection \\<open>The $\\mathit{bexp}$ type-synonym\\<close>\n\ntext \\<open>We represent boolean expressions, their set of variables and the notion of freshness of a \nvariable in the same way than for arithmetic expressions.\\<close>\n\ntype_synonym ('v,'d) bexp = \"('v,'d) state \\<Rightarrow> bool\"\n\n\ndefinition vars ::\n  \"('v,'d) bexp \\<Rightarrow> 'v set\"\nwhere\n  \"vars e = {v. \\<exists> \\<sigma> val. e (\\<sigma>(v := val)) \\<noteq> e \\<sigma>}\"\n\n\nabbreviation fresh ::\n  \"'v \\<Rightarrow> ('v,'d) bexp \\<Rightarrow> bool\"\nwhere\n  \"fresh v e \\<equiv> v \\<notin> vars e\"\n\n\nsubsubsection\\<open>Satisfiability of an expression\\<close>\n\ntext \\<open>A boolean expression @{term \"e\"} is satisfiable if there exists a state @{term \"\\<sigma>\"} such \nthat @{term \"e \\<sigma>\"} is \\emph{true}.\\<close>\n\n\ndefinition sat ::\n  \"('v,'d) bexp \\<Rightarrow> bool\"\nwhere\n  \"sat e = (\\<exists> \\<sigma>. e \\<sigma>)\"\n\n\nsubsubsection \\<open>Entailment\\<close>\n\ntext \\<open>A boolean expression @{term \"\\<phi>\"} entails another boolean expression @{term \"\\<psi>\"} if all \nstates making @{term \"\\<phi>\"} true also make @{term \"\\<psi>\"} true.\\<close>\n\ndefinition entails ::\n  \"('v,'d) bexp \\<Rightarrow> ('v,'d) bexp \\<Rightarrow> bool\" (infixl \"\\<Turnstile>\\<^sub>B\" 55) \nwhere\n  \"\\<phi> \\<Turnstile>\\<^sub>B \\<psi> \\<equiv> (\\<forall> \\<sigma>. \\<phi> \\<sigma> \\<longrightarrow> \\<psi> \\<sigma>)\"\n\n\nsubsubsection \\<open>Conjunction\\<close>\n\ntext \\<open>In the following, path predicates are represented by sets of boolean expressions. We define \nthe conjunction of a set of boolean expressions @{term \"E\"} as the expression that \nassociates \\emph{true} to a state @{term \"\\<sigma>\"} if, for all elements \\<open>e\\<close> of \n@{term \"E\"}, @{term \"e\"} associates \\emph{true} to @{term \"\\<sigma>\"}.\\<close>\n\n\ndefinition conjunct :: \n  \"('v,'d) bexp set \\<Rightarrow> ('v,'d) bexp\"\nwhere\n  \"conjunct E \\<equiv> (\\<lambda> \\<sigma>. \\<forall> e \\<in> E. e \\<sigma>)\"\n\n\n\nsubsection\\<open>Properties about the variables of an expression\\<close>\n\ntext \\<open>As said earlier, our definition of symbolic execution requires the existence of a fresh \nsymbolic variable in the case of an assignment. In the following, a number of proof relies on this \nfact. We will show the existence of such variables assuming the set of symbolic variables already in \nuse is finite and show that symbolic execution preserves the finiteness of this set, under certain \nconditions. This in turn \nrequires a number of lemmas about the finiteness of boolean expressions.\nMore precisely, when symbolic execution goes through a guard or an assignment, it conjuncts a new \nexpression to the path predicate. In the case of an assignment, this new expression is an equality \nlinking the new symbolic variable associated to the defined program variable to its symbolic value. \nIn the following, we prove that:\n\\begin{enumerate}\n  \\item the conjunction of a finite set of expressions whose sets of variables are finite has a \nfinite set of variables,\n  \\item the equality of two arithmetic expressions whose sets of variables are finite has a finite \nset of variables.\n\\end{enumerate}\\<close>\n\nsubsubsection \\<open>Variables of a conjunction\\<close>\n\ntext \\<open>The set of variables of the conjunction of two expressions is a subset of the union of the \nsets of variables of the two sub-expressions. As a consequence, the set of variables of the conjunction \nof a finite set of expressions whose sets of variables are finite is also finite.\\<close> \n\n\nlemma vars_of_conj :\n  \"vars (\\<lambda> \\<sigma>. e1 \\<sigma> \\<and> e2 \\<sigma>) \\<subseteq> vars e1 \\<union> vars e2\" \n(is \"vars ?e \\<subseteq> vars e1 \\<union> vars e2\")\nunfolding subset_iff\nproof (intro allI impI)\n  fix v assume \"v \\<in> vars ?e\"\n\n  then obtain \\<sigma> val \n  where \"?e (\\<sigma> (v := val)) \\<noteq> ?e \\<sigma>\" \n  unfolding vars_def by blast\n\n  hence \"e1 (\\<sigma> (v := val)) \\<noteq> e1 \\<sigma> \\<or> e2 (\\<sigma> (v := val)) \\<noteq> e2 \\<sigma>\" \n  by auto\n\n  thus \"v \\<in> vars e1 \\<union> vars e2\" unfolding vars_def by blast\nqed\n\n\nlemma finite_conj :\n  assumes \"finite E\"\n  assumes \"\\<forall> e \\<in> E. finite (vars e)\"\n  shows   \"finite (vars (conjunct E))\"\nusing assms\nproof (induct rule : finite_induct, goal_cases)\n  case 1 thus ?case by (simp add : vars_def conjunct_def)\nnext\n  case (2 e E) \n\n  thus ?case \n  using vars_of_conj[of e \"conjunct E\"]\n  by (rule_tac rev_finite_subset, auto simp add : conjunct_def)\nqed\n\n\nsubsubsection \\<open>Variables of an equality\\<close>\n\ntext \\<open>We proceed analogously for the equality of two arithmetic expressions.\\<close>\n\n\nlemma vars_of_eq_a :\n  shows  \"vars (\\<lambda> \\<sigma>. e1 \\<sigma> = e2 \\<sigma>) \\<subseteq> Aexp.vars e1 \\<union> Aexp.vars e2\"\n(is \"vars ?e \\<subseteq> Aexp.vars e1 \\<union> Aexp.vars e2\")\nunfolding subset_iff\nproof (intro allI impI)\n\n  fix v assume \"v \\<in> vars ?e\"\n\n  then obtain \\<sigma> val where \"?e (\\<sigma> (v := val)) \\<noteq> ?e \\<sigma>\" \n  unfolding vars_def by blast\n\n  hence \"e1 (\\<sigma> (v := val)) \\<noteq> e1 \\<sigma> \\<or> e2 (\\<sigma> (v := val)) \\<noteq> e2 \\<sigma>\"\n  by auto\n\n  thus \"v \\<in> Aexp.vars e1 \\<union> Aexp.vars e2\" \n  unfolding Aexp.vars_def by blast\nqed\n\n\nlemma finite_vars_of_a_eq :\n  assumes \"finite (Aexp.vars e1)\"\n  assumes \"finite (Aexp.vars e2)\"\n  shows   \"finite (vars (\\<lambda> \\<sigma>. e1 \\<sigma> = e2 \\<sigma>))\"\nusing assms vars_of_eq_a[of e1 e2] by (rule_tac rev_finite_subset, 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/InfPathElimination/Bexp.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8705972616934406, "lm_q2_score": 0.8289388083214156, "lm_q1q2_score": 0.7216718566360484}}
{"text": "(*  Author:     Tobias Nipkow\n    Copyright   1998 TUM\n*)\n\nheader \"Maximal prefix\"\n\ntheory MaxPrefix\nimports \"~~/src/HOL/Library/Sublist\"\nbegin\n\ndefinition\n is_maxpref :: \"('a list => bool) => 'a list => 'a list => bool\" where\n\"is_maxpref P xs ys =\n (prefixeq xs ys & (xs=[] | P xs) & (!zs. prefixeq zs ys & P zs --> prefixeq zs xs))\"\n\ntype_synonym 'a splitter = \"'a list => 'a list * 'a list\"\n\ndefinition\n is_maxsplitter :: \"('a list => bool) => 'a splitter => bool\" where\n\"is_maxsplitter P f =\n (!xs ps qs. f xs = (ps,qs) = (xs=ps@qs & is_maxpref P ps xs))\"\n\nprimrec maxsplit :: \"('a list => bool) => 'a list * 'a list => 'a list => 'a splitter\" where\n\"maxsplit P res ps []     = (if P ps then (ps,[]) else res)\" |\n\"maxsplit P res ps (q#qs) = maxsplit P (if P ps then (ps,q#qs) else res)\n                                     (ps@[q]) qs\"\n\ndeclare split_if[split del]\n\nlemma maxsplit_lemma: \"!!(ps::'a list) res.\n  (maxsplit P res ps qs = (xs,ys)) =\n  (if EX us. prefixeq us qs & P(ps@us) then xs@ys=ps@qs & is_maxpref P xs (ps@qs)\n   else (xs,ys)=res)\"\napply(unfold is_maxpref_def)\napply (induct \"qs\")\n apply (simp split: split_if)\n apply blast\napply simp\napply (erule thin_rl)\napply clarify\napply (case_tac \"EX us. prefixeq us qs & P (ps @ a # us)\")\n apply (subgoal_tac \"EX us. prefixeq us (a # qs) & P (ps @ us)\")\n  apply simp\n apply (blast intro: prefixeq_Cons[THEN iffD2])\napply (subgoal_tac \"~P(ps@[a])\")\n prefer 2 apply blast\napply (simp (no_asm_simp))\napply (case_tac \"EX us. prefixeq us (a#qs) & P (ps @ us)\")\n apply simp\n apply clarify\n apply (case_tac \"us\")\n  apply (rule iffI)\n   apply (simp add: prefixeq_Cons prefixeq_append)\n   apply blast\n  apply (simp add: prefixeq_Cons prefixeq_append)\n  apply clarify\n  apply (erule disjE)\n   apply (fast dest: prefix_order.antisym)\n  apply clarify\n  apply (erule disjE)\n   apply clarify\n   apply simp\n  apply (erule disjE)\n   apply clarify\n   apply simp\n  apply blast\n apply simp\napply (subgoal_tac \"~P(ps)\")\napply (simp (no_asm_simp))\napply fastforce\ndone\n\ndeclare split_if[split add]\n\nlemma is_maxpref_Nil[simp]:\n \"~(? us. prefixeq us xs & P us) ==> is_maxpref P ps xs = (ps = [])\"\napply(unfold is_maxpref_def)\napply blast\ndone\n\nlemma is_maxsplitter_maxsplit:\n \"is_maxsplitter P (%xs. maxsplit P ([],xs) [] xs)\"\napply(unfold is_maxsplitter_def)\napply (simp add: maxsplit_lemma)\napply (fastforce)\ndone\n\nlemmas maxsplit_eq = is_maxsplitter_maxsplit[simplified is_maxsplitter_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/Functional-Automata/MaxPrefix.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972549785203, "lm_q2_score": 0.8289388019824946, "lm_q1q2_score": 0.7216718455511429}}
{"text": "theorem sqrt2_not_rational:\n\"sqrt 2 \u2209 Q\"\nproof\nlet ?x = \"sqrt 2\"\nassume \"?x \u2208 Q\"\nthen obtain m n :: nat where\nsqrt_rat: \"\u00a6?x\u00a6 = 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 \u20392 dvd m\u203a 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 \u20392 dvd m\u203a 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", "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/Isabelle(ProofAssistant)/Samples/IsabelleDemoScriptSEQ.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087965937712, "lm_q2_score": 0.7772998611746911, "lm_q1q2_score": 0.7216520287057003}}
{"text": "section \\<open>Union-Find Data-Structure\\<close>\ntheory Union_Find\nimports \n  \"../Sep_Main\" \n  Collections.Partial_Equivalence_Relation\n  \"HOL-Library.Code_Target_Numeral\"\nbegin\ntext \\<open>\n  We implement a simple union-find data-structure based on an array.\n  It uses path compression and a size-based union heuristics.\n\\<close>\n\nsubsection \\<open>Abstract Union-Find on Lists\\<close>\ntext \\<open>\n  We first formulate union-find structures on lists, and later implement \n  them using Imperative/HOL. This is a separation of proof concerns\n  between proving the algorithmic idea correct and generating the verification\n  conditions.\n\\<close>\n\nsubsubsection \\<open>Representatives\\<close>\ntext \\<open>\n  We define a function that searches for the representative of an element.\n  This function is only partially defined, as it does not terminate on all\n  lists. We use the domain of this function to characterize valid union-find \n  lists. \n\\<close>\nfunction (domintros) rep_of \n  where \"rep_of l i = (if l!i = i then i else rep_of l (l!i))\"\n  by pat_completeness auto\n\ntext \\<open>A valid union-find structure only contains valid indexes, and\n  the \\<open>rep_of\\<close> function terminates for all indexes.\\<close>\ndefinition \n  \"ufa_invar l \\<equiv> \\<forall>i<length l. rep_of_dom (l,i) \\<and> l!i<length l\"\n\nlemma ufa_invarD: \n  \"\\<lbrakk>ufa_invar l; i<length l\\<rbrakk> \\<Longrightarrow> rep_of_dom (l,i)\" \n  \"\\<lbrakk>ufa_invar l; i<length l\\<rbrakk> \\<Longrightarrow> l!i<length l\" \n  unfolding ufa_invar_def by auto\n\ntext \\<open>We derive the following equations for the \\<open>rep-of\\<close> function.\\<close>\nlemma rep_of_refl: \"l!i=i \\<Longrightarrow> rep_of l i = i\"\n  apply (subst rep_of.psimps)\n  apply (rule rep_of.domintros)\n  apply (auto)\n  done\n\nlemma rep_of_step: \n  \"\\<lbrakk>ufa_invar l; i<length l; l!i\\<noteq>i\\<rbrakk> \\<Longrightarrow> rep_of l i = rep_of l (l!i)\"\n  apply (subst rep_of.psimps)\n  apply (auto dest: ufa_invarD)\n  done\n\nlemmas rep_of_simps = rep_of_refl rep_of_step\n\nlemma rep_of_iff: \"\\<lbrakk>ufa_invar l; i<length l\\<rbrakk> \n  \\<Longrightarrow> rep_of l i = (if l!i=i then i else rep_of l (l!i))\"\n  by (simp add: rep_of_simps)\n\ntext \\<open>We derive a custom induction rule, that is more suited to\n  our purposes.\\<close>\nlemma rep_of_induct[case_names base step, consumes 2]:\n  assumes I: \"ufa_invar l\" \n  assumes L: \"i<length l\"\n  assumes BASE: \"\\<And>i. \\<lbrakk> ufa_invar l; i<length l; l!i=i \\<rbrakk> \\<Longrightarrow> P l i\"\n  assumes STEP: \"\\<And>i. \\<lbrakk> ufa_invar l; i<length l; l!i\\<noteq>i; P l (l!i) \\<rbrakk> \n    \\<Longrightarrow> P l i\"\n  shows \"P l i\"\nproof -\n  from ufa_invarD[OF I L] have \"ufa_invar l \\<and> i<length l \\<longrightarrow> P l i\"\n    apply (induct l\\<equiv>l i rule: rep_of.pinduct)\n    apply (auto intro: STEP BASE dest: ufa_invarD)\n    done\n  thus ?thesis using I L by simp\nqed\n\ntext \\<open>In the following, we define various properties of \\<open>rep_of\\<close>.\\<close>\nlemma rep_of_min: \n  \"\\<lbrakk> ufa_invar l; i<length l \\<rbrakk> \\<Longrightarrow> l!(rep_of l i) = rep_of l i\"\nproof -\n  have \"\\<lbrakk>rep_of_dom (l,i) \\<rbrakk> \\<Longrightarrow> l!(rep_of l i) = rep_of l i\"\n    apply (induct arbitrary:  rule: rep_of.pinduct)\n    apply (subst rep_of.psimps, assumption)\n    apply (subst (2) rep_of.psimps, assumption)\n    apply auto\n    done \n  thus \"\\<lbrakk> ufa_invar l; i<length l \\<rbrakk> \\<Longrightarrow> l!(rep_of l i) = rep_of l i\"\n    by (metis ufa_invarD(1))\nqed\n\nlemma rep_of_bound: \n  \"\\<lbrakk> ufa_invar l; i<length l \\<rbrakk> \\<Longrightarrow> rep_of l i < length l\"\n  apply (induct rule: rep_of_induct)\n  apply (auto simp: rep_of_iff)\n  done\n\nlemma rep_of_idem: \n  \"\\<lbrakk> ufa_invar l; i<length l \\<rbrakk> \\<Longrightarrow> rep_of l (rep_of l i) = rep_of l i\"\n  by (auto simp: rep_of_min rep_of_refl)\n\nlemma rep_of_min_upd: \"\\<lbrakk> ufa_invar l; x<length l; i<length l \\<rbrakk> \\<Longrightarrow> \n  rep_of (l[rep_of l x := rep_of l x]) i = rep_of l i\"\n  by (metis list_update_id rep_of_min)   \n\nlemma rep_of_idx: \n  \"\\<lbrakk>ufa_invar l; i<length l\\<rbrakk> \\<Longrightarrow> rep_of l (l!i) = rep_of l i\"\n  by (metis rep_of_step)\n\nsubsubsection \\<open>Abstraction to Partial Equivalence Relation\\<close>\ndefinition ufa_\\<alpha> :: \"nat list \\<Rightarrow> (nat\\<times>nat) set\" \n  where \"ufa_\\<alpha> l \n    \\<equiv> {(x,y). x<length l \\<and> y<length l \\<and> rep_of l x = rep_of l y}\"\n\nlemma ufa_\\<alpha>_equiv[simp, intro!]: \"part_equiv (ufa_\\<alpha> l)\"\n  apply rule\n  unfolding ufa_\\<alpha>_def\n  apply (rule symI)\n  apply auto\n  apply (rule transI)\n  apply auto\n  done\n\nlemma ufa_\\<alpha>_lenD: \n  \"(x,y)\\<in>ufa_\\<alpha> l \\<Longrightarrow> x<length l\"\n  \"(x,y)\\<in>ufa_\\<alpha> l \\<Longrightarrow> y<length l\"\n  unfolding ufa_\\<alpha>_def by auto\n\nlemma ufa_\\<alpha>_dom[simp]: \"Domain (ufa_\\<alpha> l) = {0..<length l}\"\n  unfolding ufa_\\<alpha>_def by auto\n\nlemma ufa_\\<alpha>_refl[simp]: \"(i,i)\\<in>ufa_\\<alpha> l \\<longleftrightarrow> i<length l\"\n  unfolding ufa_\\<alpha>_def\n  by simp\n\nlemma ufa_\\<alpha>_len_eq: \n  assumes \"ufa_\\<alpha> l = ufa_\\<alpha> l'\"  \n  shows \"length l = length l'\"\n  by (metis assms le_antisym less_not_refl linorder_le_less_linear ufa_\\<alpha>_refl)\n\nsubsubsection \\<open>Operations\\<close>\nlemma ufa_init_invar: \"ufa_invar [0..<n]\"\n  unfolding ufa_invar_def\n  by (auto intro: rep_of.domintros)\n\nlemma ufa_init_correct: \"ufa_\\<alpha> [0..<n] = {(x,x) | x. x<n}\"\n  unfolding ufa_\\<alpha>_def\n  using ufa_init_invar[of n]\n  apply (auto simp: rep_of_refl)\n  done\n\nlemma ufa_find_correct: \"\\<lbrakk>ufa_invar l; x<length l; y<length l\\<rbrakk> \n  \\<Longrightarrow> rep_of l x = rep_of l y \\<longleftrightarrow> (x,y)\\<in>ufa_\\<alpha> l\"\n  unfolding ufa_\\<alpha>_def\n  by auto\n\nabbreviation \"ufa_union l x y \\<equiv> l[rep_of l x := rep_of l y]\"\n\nlemma ufa_union_invar:\n  assumes I: \"ufa_invar l\"\n  assumes L: \"x<length l\" \"y<length l\"\n  shows \"ufa_invar (ufa_union l x y)\"\n  unfolding ufa_invar_def\nproof (intro allI impI, simp only: length_list_update)\n  fix i\n  assume A: \"i<length l\"\n  with I have \"rep_of_dom (l,i)\" by (auto dest: ufa_invarD)\n\n  have \"ufa_union l x y ! i < length l\" using I L A\n    apply (cases \"i=rep_of l x\")\n    apply (auto simp: rep_of_bound dest: ufa_invarD)\n    done\n  moreover have \"rep_of_dom (ufa_union l x y, i)\" using I A L\n  proof (induct rule: rep_of_induct)\n    case (base i)\n    thus ?case\n      apply -\n      apply (rule rep_of.domintros)\n      apply (cases \"i=rep_of l x\")\n      apply auto\n      apply (rule rep_of.domintros)\n      apply (auto simp: rep_of_min)\n      done\n  next\n    case (step i)\n\n    from step.prems \\<open>ufa_invar l\\<close> \\<open>i<length l\\<close> \\<open>l!i\\<noteq>i\\<close> \n    have [simp]: \"ufa_union l x y ! i = l!i\"\n      apply (auto simp: rep_of_min rep_of_bound nth_list_update)\n      done\n\n    from step show ?case\n      apply -\n      apply (rule rep_of.domintros)\n      apply simp\n      done\n  qed\n  ultimately show \n    \"rep_of_dom (ufa_union l x y, i) \\<and> ufa_union l x y ! i < length l\"\n    by blast\n\nqed\n\nlemma ufa_union_aux:\n  assumes I: \"ufa_invar l\"\n  assumes L: \"x<length l\" \"y<length l\" \n  assumes IL: \"i<length l\"\n  shows \"rep_of (ufa_union l x y) i = \n    (if rep_of l i = rep_of l x then rep_of l y else rep_of l i)\"\n  using I IL\nproof (induct rule: rep_of_induct)\n  case (base i)\n  have [simp]: \"rep_of l i = i\" using \\<open>l!i=i\\<close> by (simp add: rep_of_refl)\n  note [simp] = \\<open>ufa_invar l\\<close> \\<open>i<length l\\<close>\n  show ?case proof (cases)\n    assume A[simp]: \"rep_of l x = i\"\n    have [simp]: \"l[i := rep_of l y] ! i = rep_of l y\" \n      by (auto simp: rep_of_bound)\n\n    show ?thesis proof (cases)\n      assume [simp]: \"rep_of l y = i\" \n      show ?thesis by (simp add: rep_of_refl)\n    next\n      assume A: \"rep_of l y \\<noteq> i\"\n      have [simp]: \"rep_of (l[i := rep_of l y]) i = rep_of l y\"\n        apply (subst rep_of_step[OF ufa_union_invar[OF I L], simplified])\n        using A apply simp_all\n        apply (subst rep_of_refl[where i=\"rep_of l y\"])\n        using I L\n        apply (simp_all add: rep_of_min)\n        done\n      show ?thesis by (simp add: rep_of_refl)\n    qed\n  next\n    assume A: \"rep_of l x \\<noteq> i\"\n    hence \"ufa_union l x y ! i = l!i\" by (auto)\n    also note \\<open>l!i=i\\<close>\n    finally have \"rep_of (ufa_union l x y) i = i\" by (simp add: rep_of_refl)\n    thus ?thesis using A by auto\n  qed\nnext    \n  case (step i)\n\n  note [simp] = I L \\<open>i<length l\\<close>\n\n  have \"rep_of l x \\<noteq> i\" by (metis I L(1) rep_of_min \\<open>l!i\\<noteq>i\\<close>)\n  hence [simp]: \"ufa_union l x y ! i = l!i\"\n    by (auto simp add: nth_list_update rep_of_bound \\<open>l!i\\<noteq>i\\<close>) []\n\n  have \"rep_of (ufa_union l x y) i = rep_of (ufa_union l x y) (l!i)\" \n    by (auto simp add: rep_of_iff[OF ufa_union_invar[OF I L]])\n  also note step.hyps(4)\n  finally show ?case\n    by (auto simp: rep_of_idx)\nqed\n  \nlemma ufa_union_correct: \"\\<lbrakk> ufa_invar l; x<length l; y<length l \\<rbrakk> \n  \\<Longrightarrow> ufa_\\<alpha> (ufa_union l x y) = per_union (ufa_\\<alpha> l) x y\"\n  unfolding ufa_\\<alpha>_def per_union_def\n  by (auto simp: ufa_union_aux\n    split: if_split_asm\n  )\n\nlemma ufa_compress_aux:\n  assumes I: \"ufa_invar l\"\n  assumes L[simp]: \"x<length l\"\n  shows \"ufa_invar (l[x := rep_of l x])\" \n  and \"\\<forall>i<length l. rep_of (l[x := rep_of l x]) i = rep_of l i\"\nproof -\n  {\n    fix i\n    assume \"i<length (l[x := rep_of l x])\"\n    hence IL: \"i<length l\" by simp\n\n    have G1: \"l[x := rep_of l x] ! i < length (l[x := rep_of l x])\"\n      using I IL \n      by (auto dest: ufa_invarD[OF I] simp: nth_list_update rep_of_bound)\n    from I IL have G2: \"rep_of (l[x := rep_of l x]) i = rep_of l i \n      \\<and> rep_of_dom (l[x := rep_of l x], i)\"\n    proof (induct rule: rep_of_induct)\n      case (base i)\n      thus ?case\n        apply (cases \"x=i\")\n        apply (auto intro: rep_of.domintros simp: rep_of_refl)\n        done\n    next\n      case (step i) \n      hence D: \"rep_of_dom (l[x := rep_of l x], i)\"\n        apply -\n        apply (rule rep_of.domintros)\n        apply (cases \"x=i\")\n        apply (auto intro: rep_of.domintros simp: rep_of_min)\n        done\n      \n      thus ?case apply simp using step\n        apply -\n        apply (subst rep_of.psimps[OF D])\n        apply (cases \"x=i\")\n        apply (auto simp: rep_of_min rep_of_idx)\n        apply (subst rep_of.psimps[where i=\"rep_of l i\"])\n        apply (auto intro: rep_of.domintros simp: rep_of_min)\n        done\n    qed\n    note G1 G2\n  } note G=this\n\n  thus \"\\<forall>i<length l. rep_of (l[x := rep_of l x]) i = rep_of l i\"\n    by auto\n\n  from G show \"ufa_invar (l[x := rep_of l x])\" \n    by (auto simp: ufa_invar_def)\nqed\n\nlemma ufa_compress_invar:\n  assumes I: \"ufa_invar l\"\n  assumes L[simp]: \"x<length l\"\n  shows \"ufa_invar (l[x := rep_of l x])\" \n  using assms by (rule ufa_compress_aux)\n\nlemma ufa_compress_correct:\n  assumes I: \"ufa_invar l\"\n  assumes L[simp]: \"x<length l\"\n  shows \"ufa_\\<alpha> (l[x := rep_of l x]) = ufa_\\<alpha> l\"\n  by (auto simp: ufa_\\<alpha>_def ufa_compress_aux[OF I])\n\nsubsection \\<open>Implementation with Imperative/HOL\\<close>\ntext \\<open>In this section, we implement the union-find data-structure with\n  two arrays, one holding the next-pointers, and another one holding the size\n  information. Note that we do not prove that the array for the \n  size information contains any reasonable values, as the correctness of the\n  algorithm is not affected by this. We leave it future work to also estimate\n  the complexity of the algorithm.\n\\<close>\n\ntype_synonym uf = \"nat array \\<times> nat array\"\n\ndefinition is_uf :: \"(nat\\<times>nat) set \\<Rightarrow> uf \\<Rightarrow> assn\" where \n  \"is_uf R u \\<equiv> case u of (s,p) \\<Rightarrow> \n  \\<exists>\\<^sub>Al szl. p\\<mapsto>\\<^sub>al * s\\<mapsto>\\<^sub>aszl \n    * \\<up>(ufa_invar l \\<and> ufa_\\<alpha> l = R \\<and> length szl = length l)\"\n\ndefinition uf_init :: \"nat \\<Rightarrow> uf Heap\" where \n  \"uf_init n \\<equiv> do {\n    l \\<leftarrow> Array.of_list [0..<n];\n    szl \\<leftarrow> Array.new n (1::nat);\n    return (szl,l)\n  }\"\n\nlemma uf_init_rule[sep_heap_rules]: \n  \"<emp> uf_init n <is_uf {(i,i) |i. i<n}>\"\n  unfolding uf_init_def is_uf_def[abs_def]\n  by (sep_auto simp: ufa_init_correct ufa_init_invar)\n\npartial_function (heap) uf_rep_of :: \"nat array \\<Rightarrow> nat \\<Rightarrow> nat Heap\" \n  where [code]: \n  \"uf_rep_of p i = do {\n    n \\<leftarrow> Array.nth p i;\n    if n=i then return i else uf_rep_of p n\n  }\"\n\nlemma uf_rep_of_rule[sep_heap_rules]: \"\\<lbrakk>ufa_invar l; i<length l\\<rbrakk> \\<Longrightarrow>\n  <p\\<mapsto>\\<^sub>al> uf_rep_of p i <\\<lambda>r. p\\<mapsto>\\<^sub>al * \\<up>(r=rep_of l i)>\"\n  apply (induct rule: rep_of_induct)\n  apply (subst uf_rep_of.simps)\n  apply (sep_auto simp: rep_of_refl)\n\n  apply (subst uf_rep_of.simps)\n  apply (sep_auto simp: rep_of_step)\n  done\n\ntext \\<open>We chose a non tail-recursive version here, as it is easier to prove.\\<close>\npartial_function (heap) uf_compress :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat array \\<Rightarrow> unit Heap\" \n  where [code]: \n  \"uf_compress i ci p = (\n    if i=ci then return ()\n    else do {\n      ni\\<leftarrow>Array.nth p i;\n      uf_compress ni ci p;\n      Array.upd i ci p;\n      return ()\n    })\"\n\nlemma uf_compress_rule: \"\\<lbrakk> ufa_invar l; i<length l; ci=rep_of l i \\<rbrakk> \\<Longrightarrow>\n  <p\\<mapsto>\\<^sub>al> uf_compress i ci p \n  <\\<lambda>_. \\<exists>\\<^sub>Al'. p\\<mapsto>\\<^sub>al' * \\<up>(ufa_invar l' \\<and> length l' = length l \n     \\<and> (\\<forall>i<length l. rep_of l' i = rep_of l i))>\"\nproof (induction rule: rep_of_induct)\n  case (base i) thus ?case\n    apply (subst uf_compress.simps)\n    apply (sep_auto simp: rep_of_refl)\n    done\nnext\n  case (step i)\n  note SS = \\<open>ufa_invar l\\<close> \\<open>i<length l\\<close> \\<open>l!i\\<noteq>i\\<close> \\<open>ci = rep_of l i\\<close>\n\n  from step.IH \n  have IH': \n    \"<p \\<mapsto>\\<^sub>a l> \n       uf_compress (l ! i) (rep_of l i) p\n     <\\<lambda>_. \\<exists>\\<^sub>Al'. p \\<mapsto>\\<^sub>a l' * \n        \\<up> (ufa_invar l' \\<and> length l = length l' \n           \\<and> (\\<forall>i<length l'. rep_of l i = rep_of l' i))\n     >\"\n    apply (simp add: rep_of_idx SS)\n    apply (erule \n      back_subst[OF _ cong[OF cong[OF arg_cong[where f=hoare_triple]]]])\n    apply (auto) [2]\n    apply (rule ext)\n    apply (rule ent_iffI)\n    apply sep_auto+\n    done\n\n  show ?case\n    apply (subst uf_compress.simps)\n    apply (sep_auto simp: SS)\n\n    apply (rule IH')\n    \n    using SS apply (sep_auto (plain)) \n    using ufa_compress_invar apply fastforce []\n    apply simp\n    using ufa_compress_aux(2) apply fastforce []\n    done\nqed\n\ndefinition uf_rep_of_c :: \"nat array \\<Rightarrow> nat \\<Rightarrow> nat Heap\"\n  where \"uf_rep_of_c p i \\<equiv> do {\n    ci\\<leftarrow>uf_rep_of p i;\n    uf_compress i ci p;\n    return ci\n  }\"\n\nlemma uf_rep_of_c_rule[sep_heap_rules]: \"\\<lbrakk>ufa_invar l; i<length l\\<rbrakk> \\<Longrightarrow>\n  <p\\<mapsto>\\<^sub>al> uf_rep_of_c p i <\\<lambda>r. \\<exists>\\<^sub>Al'. p\\<mapsto>\\<^sub>al' \n    * \\<up>(r=rep_of l i \\<and> ufa_invar l'\n       \\<and> length l' = length l \n       \\<and> (\\<forall>i<length l. rep_of l' i = rep_of l i))>\"\n  unfolding uf_rep_of_c_def\n  by (sep_auto heap: uf_compress_rule)\n\ndefinition uf_cmp :: \"uf \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> bool Heap\" where \n  \"uf_cmp u i j \\<equiv> do {\n    let (s,p)=u;\n    n\\<leftarrow>Array.len p;\n    if (i\\<ge>n \\<or> j\\<ge>n) then return False\n    else do {\n      ci\\<leftarrow>uf_rep_of_c p i;\n      cj\\<leftarrow>uf_rep_of_c p j;\n      return (ci=cj)\n    }\n  }\"\n\nlemma cnv_to_ufa_\\<alpha>_eq: \n  \"\\<lbrakk>(\\<forall>i<length l. rep_of l' i = rep_of l i); length l = length l'\\<rbrakk> \n  \\<Longrightarrow> (ufa_\\<alpha> l = ufa_\\<alpha> l')\"\n  unfolding ufa_\\<alpha>_def by auto\n\nlemma uf_cmp_rule[sep_heap_rules]:\n  \"<is_uf R u> uf_cmp u i j <\\<lambda>r. is_uf R u * \\<up>(r\\<longleftrightarrow>(i,j)\\<in>R)>\"\n  unfolding uf_cmp_def is_uf_def\n  apply (sep_auto dest: ufa_\\<alpha>_lenD simp: not_le split: prod.split)\n  apply (drule cnv_to_ufa_\\<alpha>_eq, simp_all)\n  apply (drule cnv_to_ufa_\\<alpha>_eq, simp_all)\n  apply (drule cnv_to_ufa_\\<alpha>_eq, simp_all)\n  apply (drule cnv_to_ufa_\\<alpha>_eq, simp_all)\n  apply (drule cnv_to_ufa_\\<alpha>_eq, simp_all)\n  apply (drule cnv_to_ufa_\\<alpha>_eq, simp_all)\n  apply (subst ufa_find_correct)\n  apply (auto simp add: )\n  done\n  \n\ndefinition uf_union :: \"uf \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> uf Heap\" where \n  \"uf_union u i j \\<equiv> do {\n    let (s,p)=u;\n    ci \\<leftarrow> uf_rep_of p i;\n    cj \\<leftarrow> uf_rep_of p j;\n    if (ci=cj) then return (s,p) \n    else do {\n      si \\<leftarrow> Array.nth s ci;\n      sj \\<leftarrow> Array.nth s cj;\n      if si<sj then do {\n        Array.upd ci cj p;\n        Array.upd cj (si+sj) s;\n        return (s,p)\n      } else do { \n        Array.upd cj ci p;\n        Array.upd ci (si+sj) s;\n        return (s,p)\n      }\n    }\n  }\"\n\nlemma uf_union_rule[sep_heap_rules]: \"\\<lbrakk>i\\<in>Domain R; j\\<in> Domain R\\<rbrakk> \n  \\<Longrightarrow> <is_uf R u> uf_union u i j <is_uf (per_union R i j)>\"\n  unfolding uf_union_def\n  apply (cases u)\n  apply (simp add: is_uf_def[abs_def])\n  apply (sep_auto \n    simp: per_union_cmp ufa_\\<alpha>_lenD ufa_find_correct\n    rep_of_bound\n    ufa_union_invar\n    ufa_union_correct\n  )\n  done\n\n\nexport_code uf_init uf_cmp uf_union checking SML_imp\n\nexport_code uf_init uf_cmp uf_union checking Scala_imp\n\n(*\nML_val {*\n  val u = @{code uf_init} 10 ();\n\n  val u = @{code uf_union} u 1 2 ();\n  val u = @{code uf_union} u 3 4 ();\n  val u = @{code uf_union} u 5 6 ();\n  val u = @{code uf_union} u 7 8 ();\n\n  val u = @{code uf_union} u 1 3 ();\n  val u = @{code uf_union} u 5 7 ();\n\n  val u = @{code uf_union} u 1 5 ();\n\n  val b = @{code uf_cmp} u 8 4 ();\n  val it = u;\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/Separation_Logic_Imperative_HOL/Examples/Union_Find.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8376199714402812, "lm_q2_score": 0.8615382094310357, "lm_q1q2_score": 0.7216416103783351}}
{"text": "(*\n  File:    Gamma_Asymptotics.thy\n  Author:  Manuel Eberl\n\n  The complete asymptotics of the real and complex logarithmic Gamma functions.\n  Also of the real Polygamma functions (could be extended to the complex ones fairly easily\n  if needed).\n*)\nsection \\<open>Complete asymptotics of the logarithmic Gamma function\\<close>\ntheory Gamma_Asymptotics\nimports \n  \"HOL-Complex_Analysis.Complex_Analysis\"\n  \"HOL-Real_Asymp.Real_Asymp\"\n  Bernoulli.Bernoulli_FPS \n  Bernoulli.Periodic_Bernpoly \n  Stirling_Formula\nbegin\n\nsubsection \\<open>Auxiliary Facts\\<close>\n\n(* TODO: could be automated with Laurent series expansions in the future *)\nlemma stirling_limit_aux1: \n  \"((\\<lambda>y. Ln (1 + z * of_real y) / of_real y) \\<longlongrightarrow> z) (at_right 0)\" for z :: complex\nproof (cases \"z = 0\")\n  case True\n  then show ?thesis by simp\nnext\n  case False\n  have \"((\\<lambda>y. ln (1 + z * of_real y)) has_vector_derivative 1 * z) (at 0)\"\n    by (rule has_vector_derivative_real_field) (auto intro!: derivative_eq_intros)\n  then have \"(\\<lambda>y. (Ln (1 + z * of_real y) - of_real y * z) / of_real \\<bar>y\\<bar>) \\<midarrow>0\\<rightarrow> 0\"\n    by (auto simp add: has_vector_derivative_def has_derivative_def netlimit_at \n          scaleR_conv_of_real field_simps)\n  then have \"((\\<lambda>y. (Ln (1 + z * of_real y) - of_real y * z) / of_real \\<bar>y\\<bar>) \\<longlongrightarrow> 0) (at_right 0)\"\n    by (rule filterlim_mono[OF _ _ at_le]) simp_all\n  also have \"?this \\<longleftrightarrow> ((\\<lambda>y. Ln (1 + z * of_real y) / (of_real y) - z) \\<longlongrightarrow> 0) (at_right 0)\"\n    using eventually_at_right_less[of \"0::real\"]\n    by (intro filterlim_cong refl) (auto elim!: eventually_mono simp: field_simps)\n  finally show ?thesis by (simp only: LIM_zero_iff)\nqed\n  \nlemma stirling_limit_aux2: \n  \"((\\<lambda>y. y * Ln (1 + z / of_real y)) \\<longlongrightarrow> z) at_top\" for z :: complex\n  using stirling_limit_aux1[of z] by (subst filterlim_at_top_to_right) (simp add: field_simps)\n\nlemma Union_atLeastAtMost: \n  assumes \"N > 0\" \n  shows   \"(\\<Union>n\\<in>{0..<N}. {real n..real (n + 1)}) = {0..real N}\"\nproof (intro equalityI subsetI)\n  fix x assume x: \"x \\<in> {0..real N}\"\n  thus \"x \\<in> (\\<Union>n\\<in>{0..<N}. {real n..real (n + 1)})\"\n  proof (cases \"x = real N\")\n    case True\n    with assms show ?thesis by (auto intro!: bexI[of _ \"N - 1\"])\n  next\n    case False\n    with x have x: \"x \\<ge> 0\" \"x < real N\" by simp_all\n    hence \"x \\<ge> real (nat \\<lfloor>x\\<rfloor>)\" \"x \\<le> real (nat \\<lfloor>x\\<rfloor> + 1)\" by linarith+\n    moreover from x have \"nat \\<lfloor>x\\<rfloor> < N\" by linarith\n    ultimately have \"\\<exists>n\\<in>{0..<N}. x \\<in> {real n..real (n + 1)}\"\n      by (intro bexI[of _ \"nat \\<lfloor>x\\<rfloor>\"]) simp_all\n    thus ?thesis by blast\n  qed\nqed auto\n\n\nsubsection \\<open>Cones in the complex plane\\<close>\n\ndefinition complex_cone :: \"real \\<Rightarrow> real \\<Rightarrow> complex set\" where\n  \"complex_cone a b = {z. \\<exists>y\\<in>{a..b}. z = rcis (norm z) y}\"\n\nabbreviation complex_cone' :: \"real \\<Rightarrow> complex set\" where\n  \"complex_cone' a \\<equiv> complex_cone (-a) a\"\n\nlemma zero_in_complex_cone [simp, intro]: \"a \\<le> b \\<Longrightarrow> 0 \\<in> complex_cone a b\"\n  by (auto simp: complex_cone_def)\n\nlemma complex_coneE:\n  assumes \"z \\<in> complex_cone a b\"\n  obtains r \\<alpha> where \"r \\<ge> 0\" \"\\<alpha> \\<in> {a..b}\" \"z = rcis r \\<alpha>\"\nproof -\n  from assms obtain y where \"y \\<in> {a..b}\" \"z = rcis (norm z) y\"\n    unfolding complex_cone_def by auto\n  thus ?thesis using that[of \"norm z\" y] by auto\nqed\n\nlemma arg_cis [simp]:\n  assumes \"x \\<in> {-pi<..pi}\"\n  shows   \"Arg (cis x) = x\"\n  using assms by (intro cis_Arg_unique) auto\n\nlemma arg_mult_of_real_left [simp]:\n  assumes \"r > 0\"\n  shows   \"Arg (of_real r * z) = Arg z\"\nproof (cases \"z = 0\")\n  case False\n  thus ?thesis\n    using Arg_bounded[of z] assms\n    by (intro cis_Arg_unique) (auto simp: sgn_mult sgn_of_real cis_Arg)\nqed auto\n\nlemma arg_mult_of_real_right [simp]:\n  assumes \"r > 0\"\n  shows   \"Arg (z * of_real r) = Arg z\"\n  by (subst mult.commute, subst arg_mult_of_real_left) (simp_all add: assms)\n\nlemma arg_rcis [simp]:\n  assumes \"x \\<in> {-pi<..pi}\" \"r > 0\"\n  shows   \"Arg (rcis r x) = x\"\n  using assms by (simp add: rcis_def)\n\nlemma rcis_in_complex_cone [intro]: \n  assumes \"\\<alpha> \\<in> {a..b}\" \"r \\<ge> 0\"\n  shows   \"rcis r \\<alpha> \\<in> complex_cone a b\"\n  using assms by (auto simp: complex_cone_def)  \n\nlemma arg_imp_in_complex_cone:\n  assumes \"Arg z \\<in> {a..b}\"\n  shows   \"z \\<in> complex_cone a b\"\nproof -\n  have \"z = rcis (norm z) (Arg z)\"\n    by (simp add: rcis_cmod_Arg)\n  also have \"\\<dots> \\<in> complex_cone a b\"\n    using assms by auto\n  finally show ?thesis .\nqed\n\nlemma complex_cone_altdef:\n  assumes \"-pi < a\" \"a \\<le> b\" \"b \\<le> pi\"\n  shows   \"complex_cone a b = insert 0 {z. Arg z \\<in> {a..b}}\"\nproof (intro equalityI subsetI)\n  fix z assume \"z \\<in> complex_cone a b\"\n  then obtain r \\<alpha> where *: \"r \\<ge> 0\" \"\\<alpha> \\<in> {a..b}\" \"z = rcis r \\<alpha>\"\n    by (auto elim: complex_coneE)\n  have \"Arg z \\<in> {a..b}\" if [simp]: \"z \\<noteq> 0\"\n  proof -\n    have \"r > 0\" using that * by (subst (asm) *) auto\n    hence \"\\<alpha> \\<in> {a..b}\"\n      using *(1,2) assms by (auto simp: *(1))\n    moreover from assms *(2) have \"\\<alpha> \\<in> {-pi<..pi}\"\n      by auto\n    ultimately show ?thesis using *(3) \\<open>r > 0\\<close>\n      by (subst *) auto\n  qed\n  thus \"z \\<in> insert 0 {z. Arg z \\<in> {a..b}}\"\n    by auto\nqed (use assms in \\<open>auto intro: arg_imp_in_complex_cone\\<close>)\n\nlemma nonneg_of_real_in_complex_cone [simp, intro]:\n  assumes \"x \\<ge> 0\" \"a \\<le> 0\" \"0 \\<le> b\"\n  shows   \"of_real x \\<in> complex_cone a b\"\nproof -\n  from assms have \"rcis x 0 \\<in> complex_cone a b\"\n    by (intro rcis_in_complex_cone) auto\n  thus ?thesis by simp\nqed\n\nlemma one_in_complex_cone [simp, intro]: \"a \\<le> 0 \\<Longrightarrow> 0 \\<le> b \\<Longrightarrow> 1 \\<in> complex_cone a b\"\n  using nonneg_of_real_in_complex_cone[of 1] by (simp del: nonneg_of_real_in_complex_cone)\n\nlemma of_nat_in_complex_cone [simp, intro]: \"a \\<le> 0 \\<Longrightarrow> 0 \\<le> b \\<Longrightarrow> of_nat n \\<in> complex_cone a b\"\n  using nonneg_of_real_in_complex_cone[of \"real n\"] by (simp del: nonneg_of_real_in_complex_cone)\n\n\nsubsection \\<open>Another integral representation of the Beta function\\<close>\n\nlemma complex_cone_inter_nonpos_Reals:\n  assumes \"-pi < a\" \"a \\<le> b\" \"b < pi\"\n  shows   \"complex_cone a b \\<inter> \\<real>\\<^sub>\\<le>\\<^sub>0 = {0}\"\nproof (safe elim!: nonpos_Reals_cases)\n  fix x :: real\n  assume \"complex_of_real x \\<in> complex_cone a b\" \"x \\<le> 0\"\n  hence \"\\<not>(x < 0)\"\n    using assms by (intro notI) (auto simp: complex_cone_altdef)\n  with \\<open>x \\<le> 0\\<close> show \"complex_of_real x = 0\" by auto  \nqed (use assms in auto)\n\ntheorem \n  assumes a: \"a > 0\" and b: \"b > (0 :: real)\"\n  shows has_integral_Beta_real': \n          \"((\\<lambda>u. u powr (b - 1) / (1 + u) powr (a + b)) has_integral Beta a b) {0<..}\"\n    and Beta_conv_nn_integral:\n          \"Beta a b = (\\<integral>\\<^sup>+u. ennreal (indicator {0<..} u * u powr (b - 1) / (1 + u) powr (a + b)) \\<partial>lborel)\"\nproof -\n  define I where \n    \"I = (\\<integral>\\<^sup>+u. ennreal (indicator {0<..} u * u powr (b - 1) / (1 + u) powr (a + b)) \\<partial>lborel)\"\n  have \"Gamma (a + b) > 0\" \"Beta a b > 0\"\n    using assms by (simp_all add: add_pos_pos Beta_def)\n  from a b have \"ennreal (Gamma a * Gamma b) =\n    (\\<integral>\\<^sup>+ t. ennreal (indicator {0..} t * t powr (a - 1) / exp t) \\<partial>lborel) *\n    (\\<integral>\\<^sup>+ t. ennreal (indicator {0..} t * t powr (b - 1) / exp t) \\<partial>lborel)\"\n    by (subst ennreal_mult') (simp_all add: Gamma_conv_nn_integral_real)\n  also have \"\\<dots> = (\\<integral>\\<^sup>+t. \\<integral>\\<^sup>+u. ennreal (indicator {0..} t * t powr (a - 1) / exp t) *\n                            ennreal (indicator {0..} u * u powr (b - 1) / exp u) \\<partial>lborel \\<partial>lborel)\"\n    by (simp add: nn_integral_cmult nn_integral_multc)\n  also have \"\\<dots> = (\\<integral>\\<^sup>+t. indicator {0<..} t * (\\<integral>\\<^sup>+u. indicator {0..} u * t powr (a - 1) * u powr (b - 1)\n                            / exp (t + u) \\<partial>lborel) \\<partial>lborel)\"\n    by (intro nn_integral_cong_AE AE_I[of _ _ \"{0}\"])\n       (auto simp: indicator_def divide_ennreal ennreal_mult' [symmetric] exp_add mult_ac)\n  also have \"\\<dots> = (\\<integral>\\<^sup>+t. indicator {0<..} t * (\\<integral>\\<^sup>+u. indicator {0..} u * t powr (a - 1) * u powr (b - 1)\n                            / exp (t + u) \n                    \\<partial>(density (distr lborel borel ((*) t)) (\\<lambda>x. ennreal \\<bar>t\\<bar>))) \\<partial>lborel)\"\n    by (intro nn_integral_cong mult_indicator_cong, subst lborel_distr_mult' [symmetric]) auto\n  also have \"\\<dots> = (\\<integral>\\<^sup>+(t::real). indicator {0<..} t * (\\<integral>\\<^sup>+u. \n                     indicator {0..} (u * t) * t powr a *\n                     (u * t) powr (b - 1) / exp (t + t * u) \\<partial>lborel) \\<partial>lborel)\"\n    by (intro nn_integral_cong mult_indicator_cong)\n       (auto simp: nn_integral_density nn_integral_distr algebra_simps powr_diff\n             simp flip: ennreal_mult)\n  also have \"\\<dots> = (\\<integral>\\<^sup>+(t::real). \\<integral>\\<^sup>+u. indicator ({0<..}\\<times>{0..}) (t, u) *\n                     t powr a * (u * t) powr (b - 1) / exp (t * (u + 1)) \\<partial>lborel \\<partial>lborel)\"\n    by (subst nn_integral_cmult [symmetric], simp, intro nn_integral_cong)\n       (auto simp: indicator_def zero_le_mult_iff algebra_simps)\n  also have \"\\<dots> = (\\<integral>\\<^sup>+(t::real). \\<integral>\\<^sup>+u. indicator ({0<..}\\<times>{0..}) (t, u) *\n                     t powr (a + b - 1) * u powr (b - 1) / exp (t * (u + 1)) \\<partial>lborel \\<partial>lborel)\"\n    by (intro nn_integral_cong) (auto simp: powr_add powr_diff indicator_def powr_mult field_simps)\n  also have \"\\<dots> = (\\<integral>\\<^sup>+(u::real). \\<integral>\\<^sup>+t. indicator ({0<..}\\<times>{0..}) (t, u) *\n                     t powr (a + b - 1) * u powr (b - 1) / exp (t * (u + 1)) \\<partial>lborel \\<partial>lborel)\"\n    by (rule lborel_pair.Fubini') auto\n  also have \"\\<dots> = (\\<integral>\\<^sup>+(u::real). indicator {0..} u * (\\<integral>\\<^sup>+t. indicator {0<..} t *\n                     t powr (a + b - 1) * u powr (b - 1) / exp (t * (u + 1)) \\<partial>lborel) \\<partial>lborel)\"\n    by (intro nn_integral_cong mult_indicator_cong) (auto simp: indicator_def)\n  also have \"\\<dots> = (\\<integral>\\<^sup>+(u::real). indicator {0<..} u * (\\<integral>\\<^sup>+t. indicator {0<..} t *\n                     t powr (a + b - 1) * u powr (b - 1) / exp (t * (u + 1)) \\<partial>lborel) \\<partial>lborel)\"\n    by (intro nn_integral_cong_AE AE_I[of _ _ \"{0}\"]) (auto simp: indicator_def)\n  also have \"\\<dots> = (\\<integral>\\<^sup>+(u::real). indicator {0<..} u * (\\<integral>\\<^sup>+t. indicator {0<..} t *\n                     t powr (a + b - 1) * u powr (b - 1) / exp (t * (u + 1)) \n                    \\<partial>(density (distr lborel borel ((*) (1/(1+u)))) (\\<lambda>x. ennreal \\<bar>1/(1+u)\\<bar>))) \\<partial>lborel)\"\n    by (intro nn_integral_cong mult_indicator_cong, subst lborel_distr_mult' [symmetric]) auto\n  also have \"\\<dots> = (\\<integral>\\<^sup>+(u::real). indicator {0<..} u * \n                    (\\<integral>\\<^sup>+t. ennreal (1 / (u + 1)) * ennreal (indicator {0<..} (t / (u + 1)) *\n                     (t / (1+u)) powr (a + b - 1) * u powr (b - 1) / exp t)\n                    \\<partial>lborel) \\<partial>lborel)\"\n    by (intro nn_integral_cong mult_indicator_cong)\n       (auto simp: nn_integral_distr nn_integral_density add_ac)\n  also have \"\\<dots> = (\\<integral>\\<^sup>+u. \\<integral>\\<^sup>+t. indicator ({0<..}\\<times>{0<..}) (u, t) * \n                    1/(u+1) * (t / (u+1)) powr (a + b - 1) * u powr (b - 1) / exp t\n                    \\<partial>lborel \\<partial>lborel)\"\n    by (subst nn_integral_cmult [symmetric], simp, intro nn_integral_cong)\n       (auto simp: indicator_def field_simps divide_ennreal simp flip: ennreal_mult ennreal_mult')\n  also have \"\\<dots> = (\\<integral>\\<^sup>+u. \\<integral>\\<^sup>+t. ennreal (indicator {0<..} u * u powr (b - 1) / (1 + u) powr (a + b)) *\n                            ennreal (indicator {0<..} t * t powr (a + b - 1) / exp t)\n                    \\<partial>lborel \\<partial>lborel)\"\n    by (intro nn_integral_cong)\n       (auto simp: indicator_def powr_add powr_diff powr_divide powr_minus divide_simps add_ac\n             simp flip: ennreal_mult)\n  also have \"\\<dots> = I * (\\<integral>\\<^sup>+t. indicator {0<..} t * t powr (a + b - 1) / exp t \\<partial>lborel)\"\n    by (simp add: nn_integral_cmult nn_integral_multc I_def)\n  also have \"(\\<integral>\\<^sup>+t. indicator {0<..} t * t powr (a + b - 1) / exp t \\<partial>lborel) =\n               ennreal (Gamma (a + b))\"\n    using assms\n    by (subst Gamma_conv_nn_integral_real)\n       (auto intro!: nn_integral_cong_AE[OF AE_I[of _ _ \"{0}\"]] \n             simp: indicator_def split: if_splits split_of_bool_asm)\n  finally have \"ennreal (Gamma a * Gamma b) = I * ennreal (Gamma (a + b))\" .\n  hence \"ennreal (Gamma a * Gamma b) / ennreal (Gamma (a + b)) =\n           I * ennreal (Gamma (a + b)) / ennreal (Gamma (a + b))\" by simp\n  also have \"\\<dots> = I\"\n    using \\<open>Gamma (a + b) > 0\\<close> by (intro ennreal_mult_divide_eq) auto\n  also have \"ennreal (Gamma a * Gamma b) / ennreal (Gamma (a + b)) =\n               ennreal (Gamma a * Gamma b / Gamma (a + b))\"\n    using assms by (intro divide_ennreal) auto\n  also have \"\\<dots> = ennreal (Beta a b)\"\n    by (simp add: Beta_def)\n  finally show *: \"ennreal (Beta a b) = I\" .\n\n  define f where \"f = (\\<lambda>u. u powr (b - 1) / (1 + u) powr (a + b))\"\n  have \"((\\<lambda>u. indicator {0<..} u * f u) has_integral Beta a b) UNIV\"\n    using * \\<open>Beta a b > 0\\<close>\n    by (subst has_integral_iff_nn_integral_lebesgue)\n       (auto simp: f_def measurable_completion nn_integral_completion I_def mult_ac)\n  also have \"(\\<lambda>u. indicator {0<..} u * f u) = (\\<lambda>u. if u \\<in> {0<..} then f u else 0)\"\n    by (auto simp: fun_eq_iff)\n  also have \"(\\<dots> has_integral Beta a b) UNIV \\<longleftrightarrow> (f has_integral Beta a b) {0<..}\"\n    by (rule has_integral_restrict_UNIV)\n  finally show \\<dots> by (simp add: f_def)\nqed\n\nlemma has_integral_Beta2:\n  fixes a :: real\n  assumes \"a < -1/2\"\n  shows   \"((\\<lambda>x. (1 + x ^ 2) powr a) has_integral Beta (- a - 1 / 2) (1 / 2) / 2) {0<..}\"\nproof -\n  define f where \"f = (\\<lambda>u. u powr (-1/2) / (1 + u) powr (-a))\"\n  define C where \"C = Beta (-a-1/2) (1/2)\"\n  have I: \"(f has_integral C) {0<..}\"\n    using has_integral_Beta_real'[of \"-a-1/2\" \"1/2\"] assms\n    by (simp_all add: diff_divide_distrib f_def C_def)\n\n  define g where \"g = (\\<lambda>x. x ^ 2 :: real)\"\n  have bij: \"bij_betw g {0<..} {0<..}\"\n    by (intro bij_betwI[of _ _ _ sqrt]) (auto simp: g_def)\n\n  have \"(f absolutely_integrable_on g ` {0<..} \\<and> integral (g ` {0<..}) f = C)\"\n    using I bij by (simp add: bij_betw_def has_integral_iff absolutely_integrable_on_def f_def)\n  also have \"?this \\<longleftrightarrow> ((\\<lambda>x. \\<bar>2 * x\\<bar> *\\<^sub>R f (g x)) absolutely_integrable_on {0<..} \\<and>\n                         integral {0<..} (\\<lambda>x. \\<bar>2 * x\\<bar> *\\<^sub>R f (g x)) = C)\"\n    using bij by (intro has_absolute_integral_change_of_variables_1' [symmetric])\n                 (auto intro!: derivative_eq_intros simp: g_def bij_betw_def)\n  finally have \"((\\<lambda>x. \\<bar>2 * x\\<bar> * f (g x)) has_integral C) {0<..}\"\n    by (simp add: absolutely_integrable_on_def f_def has_integral_iff)\n  also have \"?this \\<longleftrightarrow> ((\\<lambda>x::real. 2 * (1 + x\\<^sup>2) powr a) has_integral C) {0<..}\"\n    by (intro has_integral_cong) (auto simp: f_def g_def powr_def exp_minus ln_realpow field_simps)\n  finally have \"((\\<lambda>x::real. 1/2 * (2 * (1 + x\\<^sup>2) powr a)) has_integral 1/2 * C) {0<..}\"\n    by (intro has_integral_mult_right)\n  thus ?thesis by (simp add: C_def)\nqed\n\nlemma has_integral_Beta3:\n  fixes a b :: real\n  assumes \"a < -1/2\" and \"b > 0\"\n  shows   \"((\\<lambda>x. (b + x ^ 2) powr a) has_integral\n             Beta (-a - 1/2) (1/2) / 2 * b powr (a + 1/2)) {0<..}\"\nproof -\n  define C where \"C = Beta (- a - 1 / 2) (1 / 2) / 2\"\n  have int: \"nn_integral lborel (\\<lambda>x. indicator {0<..} x * (1 + x ^ 2) powr a) = C\"\n    using nn_integral_has_integral_lebesgue[OF _ has_integral_Beta2[OF assms(1)]]\n    by (auto simp: C_def)\n  have \"nn_integral lborel (\\<lambda>x. indicator {0<..} x * (b + x ^ 2) powr a) =\n        (\\<integral>\\<^sup>+x. ennreal (indicat_real {0<..} (x * sqrt b) * (b + (x * sqrt b)\\<^sup>2) powr a * sqrt b) \\<partial>lborel)\"\n    using assms\n    by (subst lborel_distr_mult'[of \"sqrt b\"])\n       (auto simp: nn_integral_density nn_integral_distr mult_ac simp flip: ennreal_mult)\n  also have \"\\<dots> = (\\<integral>\\<^sup>+x. ennreal (indicat_real {0<..} x * (b * (1 + x ^ 2)) powr a * sqrt b) \\<partial>lborel)\"\n    using assms\n    by (intro nn_integral_cong) (auto simp: indicator_def field_simps zero_less_mult_iff)\n  also have \"\\<dots> = (\\<integral>\\<^sup>+x. ennreal (indicat_real {0<..} x * b powr (a + 1/2) * (1 + x ^ 2) powr a) \\<partial>lborel)\"\n    using assms\n    by (intro nn_integral_cong) (auto simp: indicator_def powr_add powr_half_sqrt powr_mult)    \n  also have \"\\<dots> = b powr (a + 1/2) * (\\<integral>\\<^sup>+x. ennreal (indicat_real {0<..} x * (1 + x ^ 2) powr a) \\<partial>lborel)\"\n    using assms by (subst nn_integral_cmult [symmetric]) (simp_all add: mult_ac flip: ennreal_mult)\n  also have \"(\\<integral>\\<^sup>+x. ennreal (indicat_real {0<..} x * (1 + x ^ 2) powr a) \\<partial>lborel) = C\"\n    using int by simp\n  also have \"ennreal (b powr (a + 1/2)) * ennreal C = ennreal (C * b powr (a + 1/2))\"\n    using assms by (subst ennreal_mult) (auto simp: C_def mult_ac Beta_def)\n  finally have *: \"(\\<integral>\\<^sup>+ x. ennreal (indicat_real {0<..} x * (b + x\\<^sup>2) powr a) \\<partial>lborel) = \\<dots>\" .\n  hence \"((\\<lambda>x. indicator {0<..} x * (b + x^2) powr a) has_integral C * b powr (a + 1/2)) UNIV\"\n    using assms\n    by (subst has_integral_iff_nn_integral_lebesgue)\n       (auto simp: C_def measurable_completion nn_integral_completion Beta_def)\n  also have \"(\\<lambda>x. indicator {0<..} x * (b + x^2) powr a) =\n             (\\<lambda>x. if x \\<in> {0<..} then (b + x^2) powr a else 0)\"\n    by (auto simp: fun_eq_iff)\n  finally show ?thesis\n    by (subst (asm) has_integral_restrict_UNIV) (auto simp: C_def)\nqed\n\n  \nsubsection \\<open>Asymptotics of the real $\\log\\Gamma$ function and its derivatives\\<close>\n\ntext \\<open>\n  This is the error term that occurs in the expansion of @{term ln_Gamma}. It can be shown to \n  be of order $O(s^{-n})$.\n\\<close>\ndefinition stirling_integral :: \"nat \\<Rightarrow> 'a :: {real_normed_div_algebra, banach} \\<Rightarrow> 'a\" where\n  \"stirling_integral n s = \n     lim (\\<lambda>N. integral {0..N} (\\<lambda>x. of_real (pbernpoly n x) / (of_real x + s) ^ n))\"\n\ncontext\n  fixes s :: complex assumes s: \"s \\<notin> \\<real>\\<^sub>\\<le>\\<^sub>0\"\n  fixes approx :: \"nat \\<Rightarrow> complex\"\n  defines \"approx \\<equiv> (\\<lambda>N. \n    (\\<Sum>n = 1..<N. s / of_nat n - ln (1 + s / of_nat n)) - (euler_mascheroni * s + ln s) - \\<comment> \\<open>\\<open>\\<longrightarrow> ln_Gamma s\\<close>\\<close>\n    (ln_Gamma (of_nat N) - ln (2 * pi / of_nat N) / 2 - of_nat N * ln (of_nat N) + of_nat N) - \\<comment> \\<open>\\<open>\\<longrightarrow> 0\\<close>\\<close>\n    s * (harm (N - 1) - ln (of_nat (N - 1)) - euler_mascheroni) + \\<comment> \\<open>\\<open>\\<longrightarrow> 0\\<close>\\<close>\n    s * (ln (of_nat N + s) - ln (of_nat (N - 1))) - \\<comment> \\<open>\\<open>\\<longrightarrow> 0\\<close>\\<close>\n    (1/2) * (ln (of_nat N + s) - ln (of_nat N)) +       \\<comment> \\<open>\\<open>\\<longrightarrow> 0\\<close>\\<close>\n    of_nat N * (ln (of_nat N + s) - ln (of_nat N)) -  \\<comment> \\<open>\\<open>\\<longrightarrow> s\\<close>\\<close>\n    (s - 1/2) * ln s - ln (2 * pi) / 2)\"\nbegin       \n  \nqualified lemma\n  assumes N: \"N > 0\"\n  shows   integrable_pbernpoly_1:\n            \"(\\<lambda>x. of_real (-pbernpoly 1 x) / (of_real x + s)) integrable_on {0..real N}\"\n  and     integral_pbernpoly_1_aux:\n            \"integral {0..real N} (\\<lambda>x. -of_real (pbernpoly 1 x) / (of_real x + s)) = approx N\"\n  and     has_integral_pbernpoly_1:\n            \"((\\<lambda>x. pbernpoly 1 x /(x + s)) has_integral \n              (\\<Sum>m<N. (of_nat m + 1 / 2 + s) * (ln (of_nat m + s) - \n                        ln (of_nat m + 1 + s)) + 1)) {0..real N}\"\nproof -\n  let ?A = \"(\\<lambda>n. {of_nat n..of_nat (n+1)}) ` {0..<N}\"\n  have has_integral: \n    \"((\\<lambda>x. -pbernpoly 1 x / (x + s)) has_integral \n             (of_nat n + 1/2 + s) * (ln (of_nat (n + 1) + s) - ln (of_nat n + s)) - 1) \n           {of_nat n..of_nat (n + 1)}\" for n\n  proof (rule has_integral_spike)      \n    have \"((\\<lambda>x. (of_nat n + 1/2 + s) * (1 / (of_real x + s)) - 1) has_integral \n              (of_nat n + 1/2 + s) * (ln (of_real (real (n + 1)) + s) - ln (of_real (real n) + s)) - 1) \n            {of_nat n..of_nat (n + 1)}\" \n      using s has_integral_const_real[of 1 \"of_nat n\" \"of_nat (n + 1)\"]\n      by (intro has_integral_diff has_integral_mult_right fundamental_theorem_of_calculus)\n         (auto intro!: derivative_eq_intros has_vector_derivative_real_field\n               simp: has_real_derivative_iff_has_vector_derivative [symmetric] field_simps\n                     complex_nonpos_Reals_iff)\n    thus \"((\\<lambda>x. (of_nat n + 1/2 + s) * (1 / (of_real x + s)) - 1) has_integral \n              (of_nat n + 1/2 + s) * (ln (of_nat (n + 1) + s) - ln (of_nat n + s)) - 1) \n            {of_nat n..of_nat (n + 1)}\" by simp\n             \n    show \"-pbernpoly 1 x / (x + s) = (of_nat n + 1/2 + s) * (1 / (x + s)) - 1\"\n         if \"x \\<in> {of_nat n..of_nat (n + 1)} - {of_nat (n + 1)}\" for x\n    proof -\n      have x: \"x \\<ge> real n\" \"x < real (n + 1)\" using that by simp_all\n      hence \"floor x = int n\" by linarith\n      moreover from s x have \"complex_of_real x \\<noteq> -s\" \n        by (auto simp add: complex_eq_iff complex_nonpos_Reals_iff simp del: of_nat_Suc)\n      ultimately show \"-pbernpoly 1 x / (x + s) = (of_nat n + 1/2 + s) * (1 / (x + s)) - 1\"\n        by (auto simp: pbernpoly_def bernpoly_def frac_def divide_simps add_eq_0_iff2)\n    qed\n  qed simp_all\n  hence *: \"\\<And>I. I\\<in>?A \\<Longrightarrow> ((\\<lambda>x. -pbernpoly 1 x / (x + s)) has_integral \n              (Inf I + 1/2 + s) * (ln (Inf I + 1 + s) - ln (Inf I + s)) - 1) I\"\n    by (auto simp: add_ac)\n  have \"((\\<lambda>x. - pbernpoly 1 x / (x + s)) has_integral\n          (\\<Sum>I\\<in>?A. (Inf I + 1 / 2 + s) * (ln (Inf I + 1 + s) - ln (Inf I + s)) - 1))\n          (\\<Union>n\\<in>{0..<N}. {real n..real (n + 1)})\" (is \"(_ has_integral ?i) _\")\n    apply (intro has_integral_Union * finite_imageI)\n      apply (force intro!: negligible_atLeastAtMostI pairwiseI)+\n    done\n  hence has_integral: \"((\\<lambda>x. - pbernpoly 1 x / (x + s)) has_integral ?i) {0..real N}\"\n    by (subst has_integral_spike_set_eq)\n       (use Union_atLeastAtMost assms in \\<open>auto simp: intro!: empty_imp_negligible\\<close>)\n  hence \"(\\<lambda>x. - pbernpoly 1 x / (x + s)) integrable_on {0..real N}\"\n    and integral:   \"integral {0..real N} (\\<lambda>x. - pbernpoly 1 x / (x + s)) = ?i\"\n    by (simp_all add: has_integral_iff)\n  show \"(\\<lambda>x. - pbernpoly 1 x / (x + s)) integrable_on {0..real N}\" by fact\n\n  note has_integral_neg[OF has_integral]\n  also have \"-?i = (\\<Sum>x<N. (of_nat x + 1 / 2 + s) * (ln (of_nat x + s) - ln (of_nat x + 1 + s)) + 1)\" \n    by (subst sum.reindex) \n       (simp_all add: inj_on_def atLeast0LessThan algebra_simps sum_negf [symmetric])\n  finally show has_integral: \n    \"((\\<lambda>x. of_real (pbernpoly 1 x) / (of_real x + s)) has_integral \\<dots>) {0..real N}\" by simp\n      \n  note integral\n  also have \"?i = (\\<Sum>n<N. (of_nat n + 1 / 2 + s) * \n                    (ln (of_nat n + 1 + s) - ln (of_nat n + s))) - N\" (is \"_ = ?S - _\")\n    by (subst sum.reindex) (simp_all add: inj_on_def sum_subtractf atLeast0LessThan)\n  also have \"?S = (\\<Sum>n<N. of_nat n * (ln (of_nat n + 1 + s) - ln (of_nat n + s))) +\n                    (s + 1 / 2) * (\\<Sum>n<N. ln (of_nat (Suc n) + s) - ln (of_nat n + s))\" \n    (is \"_ = ?S1 + _ * ?S2\") by (simp add: algebra_simps sum.distrib sum_subtractf sum_distrib_left)\n  also have \"?S2 = ln (of_nat N + s) - ln s\" by (subst sum_lessThan_telescope) simp\n  also have \"?S1 = (\\<Sum>n=1..<N. of_nat n * (ln (of_nat n + 1 + s) - ln (of_nat n + s)))\"\n    by (intro sum.mono_neutral_right) auto\n  also have \"\\<dots> = (\\<Sum>n=1..<N. of_nat n * ln (of_nat n + 1 + s)) - (\\<Sum>n=1..<N. of_nat n * ln (of_nat n + s))\"\n    by (simp add: algebra_simps sum_subtractf)\n  also have \"(\\<Sum>n=1..<N. of_nat n * ln (of_nat n + 1 + s)) = \n               (\\<Sum>n=1..<N. (of_nat n - 1) * ln (of_nat n + s)) + (N - 1) * ln (of_nat N + s)\"\n    by (induction N) (simp_all add: add_ac of_nat_diff)\n  also have \"\\<dots> - (\\<Sum>n = 1..<N. of_nat n * ln (of_nat n + s)) =\n               -(\\<Sum>n=1..<N. ln (of_nat n + s)) + (N - 1) * ln (of_nat N + s)\"\n    by (induction N) (simp_all add: algebra_simps)\n  also from s have neq: \"s + of_nat x \\<noteq> 0\" for x\n    by (auto simp:  complex_nonpos_Reals_iff complex_eq_iff)\n  hence \"(\\<Sum>n=1..<N. ln (of_nat n + s)) = (\\<Sum>n=1..<N. ln (of_nat n) + ln (1 + s/n))\"\n    by (intro sum.cong refl, subst Ln_times_of_nat [symmetric]) (auto simp: divide_simps add_ac)\n  also have \"\\<dots> = ln (fact (N - 1)) + (\\<Sum>n=1..<N. ln (1 + s/n))\"\n    by (induction N) (simp_all add: Ln_times_of_nat fact_reduce add_ac)\n  also have \"(\\<Sum>n=1..<N. ln (1 + s/n)) = -(\\<Sum>n=1..<N. s / n - ln (1 + s/n)) + s * (\\<Sum>n=1..<N. 1 / of_nat n)\"\n    by (simp add: sum_distrib_left sum_subtractf) \n  also from N have \"ln (fact (N - 1)) = ln_Gamma (of_nat N :: complex)\" \n    by (simp add: ln_Gamma_complex_conv_fact)\n  also have \"{1..<N} = {1..N - 1}\" by auto\n  hence \"(\\<Sum>n = 1..<N. 1 / of_nat n) = (harm (N - 1) :: complex)\" \n    by (simp add: harm_def divide_simps)\n  also have \"- (ln_Gamma (of_nat N) + (- (\\<Sum>n = 1..<N. s / of_nat n - ln (1 + s / of_nat n)) +\n                 s * harm (N - 1))) + of_nat (N - 1) * ln (of_nat N + s) +\n                (s + 1 / 2) * (ln (of_nat N + s) - ln s) - of_nat N = approx N\"\n    using N by (simp add: field_simps of_nat_diff ln_div approx_def Ln_of_nat \n                          ln_Gamma_complex_of_real [symmetric])\n  finally show \"integral {0..of_nat N} (\\<lambda>x. -of_real (pbernpoly 1 x) / (of_real x + s)) = \\<dots>\" \n    by simp\nqed\n  \nlemma integrable_ln_Gamma_aux:\n  shows   \"(\\<lambda>x. of_real (pbernpoly n x) / (of_real x + s) ^ n) integrable_on {0..real N}\"\nproof (cases \"n = 1\")\n  case True\n  with s show ?thesis using integrable_neg[OF integrable_pbernpoly_1[of N]] \n    by (cases \"N = 0\") (simp_all add: integrable_negligible)\nnext\n  case False\n  from s have \"of_real x + s \\<noteq> 0\" if \"x \\<ge> 0\" for x using that \n    by (auto simp: complex_eq_iff add_eq_0_iff2 complex_nonpos_Reals_iff)\n  with False s show ?thesis\n    by (auto intro!: integrable_continuous_real continuous_intros)\nqed\n  \ntext \\<open>\n  This following proof is based on ``Rudiments of the theory of the gamma function'' \n  by Bruce Berndt~\\<^cite>\\<open>\"berndt\"\\<close>.\n\\<close>\nlemma tendsto_of_real_0_I: \n  \"(f \\<longlongrightarrow> 0) G \\<Longrightarrow> ((\\<lambda>x. (of_real (f x))) \\<longlongrightarrow> (0 ::'a::real_normed_div_algebra)) G\"\n  using tendsto_of_real_iff by force\n\nqualified lemma integral_pbernpoly_1:\n  \"(\\<lambda>N. integral {0..real N} (\\<lambda>x. pbernpoly 1 x / (x + s)))\n     \\<longlonglongrightarrow> -ln_Gamma s - s + (s - 1 / 2) * ln s + ln (2 * pi) / 2\"\nproof -  \n  have neq: \"s + of_real x \\<noteq> 0\" if \"x \\<ge> 0\" for x :: real\n    using that s by (auto simp: complex_eq_iff complex_nonpos_Reals_iff)\n  have \"(approx \\<longlongrightarrow> ln_Gamma s - 0 - 0 + 0 - 0 + s - (s - 1/2) * ln s - ln (2 * pi) / 2) at_top\"\n    unfolding approx_def\n  proof (intro tendsto_add tendsto_diff)\n    from s have s': \"s \\<notin> \\<int>\\<^sub>\\<le>\\<^sub>0\" by (auto simp: complex_nonpos_Reals_iff elim!: nonpos_Ints_cases)\n    have \"(\\<lambda>n. \\<Sum>i=1..<n. s / of_nat i - ln (1 + s / of_nat i)) \\<longlonglongrightarrow> \n             ln_Gamma s + euler_mascheroni * s + ln s\" (is \"?f \\<longlonglongrightarrow> _\")\n      using ln_Gamma_series'_aux[OF s'] unfolding sums_def \n      by (subst filterlim_sequentially_Suc [symmetric], subst (asm) sum.atLeast1_atMost_eq [symmetric]) \n         (simp add: atLeastLessThanSuc_atLeastAtMost)\n    thus \"((\\<lambda>n. ?f n - (euler_mascheroni * s + ln s)) \\<longlongrightarrow> ln_Gamma s) at_top\"\n      by (auto intro: tendsto_eq_intros)\n  next\n    show \"(\\<lambda>x. complex_of_real (ln_Gamma (real x) - ln (2 * pi / real x) / 2 - \n                 real x * ln (real x) + real x)) \\<longlonglongrightarrow> 0\"\n    proof (intro tendsto_of_real_0_I \n             filterlim_compose[OF tendsto_sandwich filterlim_real_sequentially])\n      show \"eventually (\\<lambda>x::real. ln_Gamma x - ln (2 * pi / x) / 2 - x * ln x + x \\<ge> 0) at_top\"\n        using eventually_ge_at_top[of \"1::real\"] \n        by eventually_elim (insert ln_Gamma_bounds(1), simp add: algebra_simps)\n      show \"eventually (\\<lambda>x::real. ln_Gamma x - ln (2 * pi / x) / 2 - x * ln x + x \\<le> \n              1 / 12 * inverse x) at_top\"\n        using eventually_ge_at_top[of \"1::real\"] \n        by eventually_elim (insert ln_Gamma_bounds(2), simp add: field_simps)\n      show \"((\\<lambda>x::real. 1 / 12 * inverse x) \\<longlongrightarrow> 0) at_top\"\n        by (intro tendsto_mult_right_zero tendsto_inverse_0_at_top filterlim_ident)\n    qed simp_all\n  next\n    have \"(\\<lambda>x. s * of_real (harm (x - 1) - ln (real (x - 1)) - euler_mascheroni)) \\<longlonglongrightarrow> \n            s * of_real (euler_mascheroni - euler_mascheroni)\"\n      by (subst filterlim_sequentially_Suc [symmetric], intro tendsto_intros) \n         (insert euler_mascheroni_LIMSEQ, simp_all)\n    also have \"?this \\<longleftrightarrow> (\\<lambda>x. s * (harm (x - 1) - ln (of_nat (x - 1)) - euler_mascheroni)) \\<longlonglongrightarrow> 0\"\n      by (intro filterlim_cong refl eventually_mono[OF eventually_gt_at_top[of \"1::nat\"]]) \n         (auto simp: Ln_of_nat of_real_harm)\n    finally show \"(\\<lambda>x. s * (harm (x - 1) - ln (of_nat (x - 1)) - euler_mascheroni)) \\<longlonglongrightarrow> 0\"  .\n  next\n    have \"((\\<lambda>x. ln (1 + (s + 1) / of_real x)) \\<longlongrightarrow> ln (1 + 0)) at_top\" (is ?P)\n      by (intro tendsto_intros tendsto_divide_0[OF tendsto_const]) \n         (simp_all add: filterlim_ident filterlim_at_infinity_conv_norm_at_top filterlim_abs_real)\n    also have \"ln (of_real (x + 1) + s) - ln (complex_of_real x) = ln (1 + (s + 1) / of_real x)\" \n      if \"x > 1\" for x using that s\n      using Ln_divide_of_real[of x \"of_real (x + 1) + s\", symmetric] neq[of \"x+1\"]\n      by (simp add: field_simps Ln_of_real)\n    hence \"?P \\<longleftrightarrow> ((\\<lambda>x. ln (of_real (x + 1) + s) - ln (of_real x)) \\<longlongrightarrow> 0) at_top\"\n      by (intro filterlim_cong refl) \n         (auto intro: eventually_mono[OF eventually_gt_at_top[of \"1::real\"]])\n    finally have \"((\\<lambda>n. ln (of_real (real n + 1) + s) - ln (of_real (real n))) \\<longlongrightarrow> 0) at_top\"\n      by (rule filterlim_compose[OF _ filterlim_real_sequentially])\n    hence \"((\\<lambda>n. ln (of_nat n + s) - ln (of_nat (n - 1))) \\<longlongrightarrow> 0) at_top\"\n      by (subst filterlim_sequentially_Suc [symmetric]) (simp add: add_ac)\n    thus \"(\\<lambda>x. s * (ln (of_nat x + s) - ln (of_nat (x - 1)))) \\<longlonglongrightarrow> 0\"\n      by (rule tendsto_mult_right_zero)\n  next\n    have \"((\\<lambda>x. ln (1 + s / of_real x)) \\<longlongrightarrow> ln (1 + 0)) at_top\" (is ?P)\n      by (intro tendsto_intros tendsto_divide_0[OF tendsto_const]) \n         (simp_all add: filterlim_ident  filterlim_at_infinity_conv_norm_at_top filterlim_abs_real)\n    also have \"ln (of_real x + s) - ln (of_real x) = ln (1 + s / of_real x)\" if \"x > 0\" for x\n      using Ln_divide_of_real[of x \"of_real x + s\"] neq[of x] that\n      by (auto simp: field_simps Ln_of_real)\n    hence \"?P \\<longleftrightarrow> ((\\<lambda>x. ln (of_real x + s) - ln (of_real x)) \\<longlongrightarrow> 0) at_top\"\n      using s by (intro filterlim_cong refl) \n                 (auto intro: eventually_mono [OF eventually_gt_at_top[of \"1::real\"]])\n    finally have \"(\\<lambda>x. (1/2) * (ln (of_real (real x) + s) - ln (of_real (real x)))) \\<longlonglongrightarrow> 0\"        \n      by (rule tendsto_mult_right_zero[OF filterlim_compose[OF _ filterlim_real_sequentially]])\n    thus \"(\\<lambda>x. (1/2) * (ln (of_nat x + s) - ln (of_nat x))) \\<longlonglongrightarrow> 0\" by simp\n  next\n    have \"((\\<lambda>x. x * (ln (1 + s / of_real x))) \\<longlongrightarrow> s) at_top\" (is ?P) \n      by (rule stirling_limit_aux2)\n    also have \"ln (1 + s / of_real x) = ln (of_real x + s) - ln (of_real x)\" if \"x > 1\" for x \n      using that s Ln_divide_of_real [of x \"of_real x + s\", symmetric] neq[of x]\n      by (auto simp: Ln_of_real field_simps)\n    hence \"?P \\<longleftrightarrow> ((\\<lambda>x. of_real x * (ln (of_real x + s) - ln (of_real x))) \\<longlongrightarrow> s) at_top\"\n      by (intro filterlim_cong refl) \n         (auto intro: eventually_mono[OF eventually_gt_at_top[of \"1::real\"]])\n    finally have \"(\\<lambda>n. of_real (real n) * (ln (of_real (real n) + s) - ln (of_real (real n)))) \\<longlonglongrightarrow> s\"\n      by (rule filterlim_compose[OF _ filterlim_real_sequentially])\n    thus \"(\\<lambda>n. of_nat n * (ln (of_nat n + s) - ln (of_nat n))) \\<longlonglongrightarrow> s\" by simp\n  qed simp_all\n  also have \"?this \\<longleftrightarrow> ((\\<lambda>N. integral {0..real N} (\\<lambda>x. -pbernpoly 1 x / (x + s))) \\<longlongrightarrow>\n                         ln_Gamma s + s - (s - 1/2) * ln s - ln (2 * pi) / 2) at_top\"\n    using integral_pbernpoly_1_aux\n    by (intro filterlim_cong refl) \n       (auto intro: eventually_mono[OF eventually_gt_at_top[of \"0::nat\"]])\n  also have \"(\\<lambda>N. integral {0..real N} (\\<lambda>x. -pbernpoly 1 x / (x + s))) =\n               (\\<lambda>N. -integral {0..real N} (\\<lambda>x. pbernpoly 1 x / (x + s)))\"\n    by (simp add: fun_eq_iff)\n  finally show ?thesis by (simp add: tendsto_minus_cancel_left [symmetric] algebra_simps)\nqed\n\n\nqualified lemma pbernpoly_integral_conv_pbernpoly_integral_Suc:\n  assumes \"n \\<ge> 1\"\n  shows   \"integral {0..real N} (\\<lambda>x. pbernpoly n x / (x + s) ^ n) =\n             of_real (pbernpoly (Suc n) (real N)) / (of_nat (Suc n) * (s + of_nat N) ^ n) -\n             of_real (bernoulli (Suc n)) / (of_nat (Suc n) * s ^ n) + of_nat n / of_nat (Suc n) * \n               integral {0..real N} (\\<lambda>x. of_real (pbernpoly (Suc n) x) / (of_real x + s) ^ Suc n)\"\nproof - \n  note [derivative_intros] = has_field_derivative_pbernpoly_Suc'\n  define I where \"I = -of_real (pbernpoly (Suc n) (of_nat N)) / (of_nat (Suc n) * (of_nat N + s) ^ n) +\n            of_real (bernoulli (Suc n) / real (Suc n)) / s ^ n +\n            integral {0..real N} (\\<lambda>x. of_real (pbernpoly n x) / (of_real x + s) ^ n)\"\n  have \"((\\<lambda>x. (-of_nat n * inverse (of_real x + s) ^ Suc n) * \n          (of_real (pbernpoly (Suc n) x) / (of_nat (Suc n))))\n          has_integral -I) {0..real N}\"\n  proof (rule integration_by_parts_interior_strong[OF bounded_bilinear_mult])\n    fix x :: real assume x: \"x \\<in> {0<..<real N} - real ` {0..N}\"\n    have \"x \\<notin> \\<int>\"\n    proof\n      assume \"x \\<in> \\<int>\"\n      then obtain n where \"x = of_int n\" by (auto elim!: Ints_cases)\n      with x have x': \"x = of_nat (nat n)\" by simp\n      from x show False by (auto simp: x')\n    qed\n    hence \"((\\<lambda>x. of_real (pbernpoly (Suc n) x / of_nat (Suc n))) has_vector_derivative\n        complex_of_real (pbernpoly n x)) (at x)\"\n      by (intro has_vector_derivative_of_real) (auto intro!: derivative_eq_intros)\n    thus \"((\\<lambda>x. of_real (pbernpoly (Suc n) x) / of_nat (Suc n)) has_vector_derivative\n            complex_of_real (pbernpoly n x)) (at x)\" by simp\n    from x s have \"complex_of_real x + s \\<noteq> 0\"\n      by (auto simp: complex_eq_iff complex_nonpos_Reals_iff)\n    thus \"((\\<lambda>x. inverse (of_real x + s) ^ n) has_vector_derivative \n             - of_nat n * inverse (of_real x + s) ^ Suc n) (at x)\" using x s assms\n      by (auto intro!: derivative_eq_intros has_vector_derivative_real_field simp: divide_simps power_add [symmetric]\n               simp del: power_Suc)\n  next\n    have \"complex_of_real x + s \\<noteq> 0\" if \"x \\<ge> 0\" for x \n      using that s by (auto simp: complex_eq_iff complex_nonpos_Reals_iff)\n    thus \"continuous_on {0..real N} (\\<lambda>x. inverse (of_real x + s) ^ n)\" \n         \"continuous_on {0..real N} (\\<lambda>x. complex_of_real (pbernpoly (Suc n) x) / of_nat (Suc n))\"\n      using assms s by (auto intro!: continuous_intros simp del: of_nat_Suc)\n  next\n    have \"((\\<lambda>x. inverse (of_real x + s) ^ n * of_real (pbernpoly n x)) has_integral\n            pbernpoly (Suc n) (of_nat N) / (of_nat (Suc n) * (of_nat N + s) ^ n) -\n            of_real (bernoulli (Suc n) / real (Suc n)) / s ^ n - -I) {0..real N}\" \n      using integrable_ln_Gamma_aux[of n N] assms\n      by (auto simp: I_def has_integral_integral divide_simps)\n    thus \"((\\<lambda>x. inverse (of_real x + s) ^ n * of_real (pbernpoly n x)) has_integral\n              inverse (of_real (real N) + s) ^ n * (of_real (pbernpoly (Suc n) (real N)) / \n                  of_nat (Suc n)) -\n              inverse (of_real 0 + s) ^ n * (of_real (pbernpoly (Suc n) 0) / of_nat (Suc n)) - - I)\n            {0..real N}\" by (simp_all add: field_simps)\n  qed simp_all\n  also have \"(\\<lambda>x. - of_nat n * inverse (of_real x + s) ^ Suc n * (of_real (pbernpoly (Suc n) x) /\n                         of_nat (Suc n))) =\n             (\\<lambda>x. - (of_nat n / of_nat (Suc n) * of_real (pbernpoly (Suc n) x) / \n                         (of_real x + s) ^ Suc n))\"\n    by (simp add: divide_simps fun_eq_iff)\n  finally have \"((\\<lambda>x. - (of_nat n / of_nat (Suc n) * of_real (pbernpoly (Suc n) x) /\n                            (of_real x + s) ^ Suc n)) has_integral - I) {0..real N}\" .\n  from has_integral_neg[OF this] show ?thesis\n    by (auto simp add: I_def has_integral_iff algebra_simps integral_mult_right [symmetric] \n             simp del: power_Suc of_nat_Suc )\nqed\n\nlemma pbernpoly_over_power_tendsto_0: \n  assumes \"n > 0\"\n  shows   \"(\\<lambda>x. of_real (pbernpoly (Suc n) (real x)) / (of_nat (Suc n) * (s + of_nat x) ^ n)) \\<longlonglongrightarrow> 0\"\nproof -\n  from s have neq: \"s + of_nat n \\<noteq> 0\" for n\n    by (auto simp: complex_eq_iff complex_nonpos_Reals_iff)\n  obtain c where c: \"\\<And>x. norm (pbernpoly (Suc n) x) \\<le> c\"\n    using bounded_pbernpoly by auto\n  have \"eventually (\\<lambda>x. real x + Re s > 0) at_top\"\n    by real_asymp\n  hence \"eventually (\\<lambda>x. norm (of_real (pbernpoly (Suc n) (real x)) / \n                                    (of_nat (Suc n) * (s + of_nat x) ^ n)) \\<le>\n                          (c / real (Suc n)) / (real x + Re s) ^ n) at_top\"\n    using eventually_gt_at_top[of \"0::nat\"]\n  proof eventually_elim\n    case (elim x)\n    have \"norm (of_real (pbernpoly (Suc n) (real x)) / \n                                    (of_nat (Suc n) * (s + of_nat x) ^ n)) \\<le>\n            (c / real (Suc n)) / norm (s + of_nat x) ^ n\" (is \"_ \\<le> ?rhs\") using c[of x]\n      by (auto simp: norm_divide norm_mult norm_power neq field_simps simp del: of_nat_Suc)\n    also have \"(real x + Re s) \\<le> cmod (s + of_nat x)\"\n      using complex_Re_le_cmod[of \"s + of_nat x\"] s by (auto simp add: complex_nonpos_Reals_iff)\n    hence \"?rhs \\<le> (c / real (Suc n)) / (real x + Re s) ^ n\" using s elim c[of 0] neq[of x]\n      by (intro divide_left_mono power_mono mult_pos_pos divide_nonneg_pos zero_less_power) auto\n    finally show ?case .\n  qed \n  moreover have \"(\\<lambda>x. (c / real (Suc n)) / (real x + Re s) ^ n) \\<longlonglongrightarrow> 0\"\n    using \\<open>n > 0\\<close> by real_asymp\n  ultimately show ?thesis by (rule Lim_null_comparison)\nqed\n\nlemma convergent_stirling_integral:\n  assumes \"n > 0\"\n  shows   \"convergent (\\<lambda>N. integral {0..real N} \n             (\\<lambda>x. of_real (pbernpoly n x) / (of_real x + s) ^ n))\" (is \"convergent (?f n)\")\nproof -\n  have \"convergent (?f (Suc n))\" for n\n  proof (induction n)\n    case 0\n    thus ?case using integral_pbernpoly_1 by (auto intro!: convergentI)\n  next\n    case (Suc n)\n    have \"convergent (\\<lambda>N. ?f (Suc n) N -\n            of_real (pbernpoly (Suc (Suc n)) (real N)) / \n                (of_nat (Suc (Suc n)) * (s + of_nat N) ^ Suc n) +\n            of_real (bernoulli (Suc (Suc n)) / (real (Suc (Suc n)))) / s ^ Suc n)\" \n      (is \"convergent ?g\")\n      by (intro convergent_add convergent_diff Suc \n            convergent_const convergentI[OF pbernpoly_over_power_tendsto_0]) simp_all\n    also have \"?g = (\\<lambda>N. of_nat (Suc n) / of_nat (Suc (Suc n)) * ?f (Suc (Suc n)) N)\" using s\n      by (subst pbernpoly_integral_conv_pbernpoly_integral_Suc) \n         (auto simp: fun_eq_iff field_simps simp del: of_nat_Suc power_Suc)\n    also have \"convergent \\<dots> \\<longleftrightarrow> convergent (?f (Suc (Suc n)))\"\n      by (intro convergent_mult_const_iff) (simp_all del: of_nat_Suc)\n    finally show ?case .\n  qed\n  from this[of \"n - 1\"] assms show ?thesis by simp\nqed\n\nlemma stirling_integral_conv_stirling_integral_Suc:\n  assumes \"n > 0\"\n  shows   \"stirling_integral n s =\n             of_nat n / of_nat (Suc n) * stirling_integral (Suc n) s -\n             of_real (bernoulli (Suc n)) / (of_nat (Suc n) * s ^ n)\"\nproof -\n  have \"(\\<lambda>N. of_real (pbernpoly (Suc n) (real N)) / (of_nat (Suc n) * (s + of_nat N) ^ n) -\n             of_real (bernoulli (Suc n)) / (real (Suc n) * s ^ n) +\n             integral {0..real N} (\\<lambda>x. of_nat n / of_nat (Suc n) * \n                (of_real (pbernpoly (Suc n) x) / (of_real x + s) ^ Suc n)))\n           \\<longlonglongrightarrow> 0 - of_real (bernoulli (Suc n)) / (of_nat (Suc n) * s ^ n) +\n                   of_nat n / of_nat (Suc n) * stirling_integral (Suc n) s\" (is \"?f \\<longlonglongrightarrow> _\")\n    unfolding stirling_integral_def integral_mult_right\n    using convergent_stirling_integral[of \"Suc n\"] assms s\n    by (intro tendsto_intros pbernpoly_over_power_tendsto_0)\n       (auto simp: convergent_LIMSEQ_iff simp del: of_nat_Suc)\n  also have \"?this \\<longleftrightarrow> (\\<lambda>N. integral {0..real N} \n               (\\<lambda>x. of_real (pbernpoly n x) / (of_real x + s) ^ n)) \\<longlonglongrightarrow>\n               of_nat n / of_nat (Suc n) * stirling_integral (Suc n) s -\n                 of_real (bernoulli (Suc n)) / (of_nat (Suc n) * s ^ n)\" \n    using eventually_gt_at_top[of \"0::nat\"] pbernpoly_integral_conv_pbernpoly_integral_Suc[of n] \n          assms unfolding integral_mult_right\n    by (intro filterlim_cong refl) (auto elim!: eventually_mono simp del: power_Suc)\n  finally show ?thesis unfolding stirling_integral_def[of n] by (rule limI)\nqed\n\nlemma stirling_integral_1_unfold:\n  assumes \"m > 0\"\n  shows   \"stirling_integral 1 s = stirling_integral m s / of_nat m - \n             (\\<Sum>k=1..<m. of_real (bernoulli (Suc k)) / (of_nat k * of_nat (Suc k) * s ^ k))\"\nproof -\n  have \"stirling_integral 1 s = stirling_integral (Suc m) s / of_nat (Suc m) -\n          (\\<Sum>k=1..<Suc m. of_real (bernoulli (Suc k)) / (of_nat k * of_nat (Suc k) * s ^ k))\" for m\n  proof (induction m)\n    case (Suc m)\n    let ?C = \"(\\<Sum>k = 1..<Suc m. of_real (bernoulli (Suc k)) / (of_nat k * of_nat (Suc k) * s ^ k))\"\n    note Suc.IH\n    also have \"stirling_integral (Suc m) s / of_nat (Suc m) = \n                 stirling_integral (Suc (Suc m)) s / of_nat (Suc (Suc m)) -\n                 of_real (bernoulli (Suc (Suc m))) / \n                   (of_nat (Suc m) * of_nat (Suc (Suc m)) * s ^ Suc m)\"\n      (is \"_ = ?A - ?B\") by (subst stirling_integral_conv_stirling_integral_Suc)\n                            (simp_all del: of_nat_Suc power_Suc add: divide_simps)\n    also have \"?A - ?B - ?C = ?A - (?B + ?C)\" by (rule diff_diff_eq)\n    also have \"?B + ?C = (\\<Sum>k = 1..<Suc (Suc m). of_real (bernoulli (Suc k)) /\n                             (of_nat k * of_nat (Suc k) * s ^ k))\" \n      using s by (simp add: divide_simps)\n    finally show ?case .\n  qed simp_all\n  note this[of \"m - 1\"]\n  also from assms have \"Suc (m - 1) = m\" by simp\n  finally show ?thesis .\nqed\n  \nlemma ln_Gamma_stirling_complex:\n  assumes \"m > 0\"\n  shows   \"ln_Gamma s = (s - 1 / 2) * ln s - s + ln (2 * pi) / 2 +\n             (\\<Sum>k=1..<m. of_real (bernoulli (Suc k)) / (of_nat k * of_nat (Suc k) * s ^ k)) - \n             stirling_integral m s / of_nat m\"\nproof -\n  have \"ln_Gamma s = (s - 1 / 2) * ln s - s + ln (2 * pi) / 2 - stirling_integral 1 s\"\n    using limI[OF integral_pbernpoly_1] by (simp add: stirling_integral_def algebra_simps)\n  also have \"stirling_integral 1 s = stirling_integral m s / of_nat m -\n               (\\<Sum>k = 1..<m. of_real (bernoulli (Suc k)) / (of_nat k * of_nat (Suc k) * s ^ k))\"\n    using assms by (rule stirling_integral_1_unfold)\n  finally show ?thesis by simp\nqed\n\nlemma LIMSEQ_stirling_integral:\n  \"n > 0 \\<Longrightarrow> (\\<lambda>x. integral {0..real x} (\\<lambda>x. of_real (pbernpoly n x) / (of_real x + s) ^ n))\n     \\<longlonglongrightarrow> stirling_integral n s\" unfolding stirling_integral_def \n  using convergent_stirling_integral[of n] by (simp only: convergent_LIMSEQ_iff)\n\nend\n\nlemmas has_integral_of_real = has_integral_linear[OF _ bounded_linear_of_real, unfolded o_def]\nlemmas integral_of_real = integral_linear[OF _ bounded_linear_of_real, unfolded o_def]\n\nlemma integrable_ln_Gamma_aux_real:\n  assumes \"0 < s\"\n  shows   \"(\\<lambda>x. pbernpoly n x / (x + s) ^ n) integrable_on {0..real N}\"\nproof -\n  have \"(\\<lambda>x. complex_of_real (pbernpoly n x / (x + s) ^ n)) integrable_on {0..real N}\"\n    using integrable_ln_Gamma_aux[of \"of_real s\" n N] assms by simp\n  from integrable_linear[OF this bounded_linear_Re] show ?thesis \n    by (simp only: o_def Re_complex_of_real) \nqed\n  \nlemma  \n  assumes \"x > 0\" \"n > 0\"\n  shows   stirling_integral_complex_of_real:\n            \"stirling_integral n (complex_of_real x) = of_real (stirling_integral n x)\"\n    and   LIMSEQ_stirling_integral_real:\n            \"(\\<lambda>N. integral {0..real N} (\\<lambda>t. pbernpoly n t / (t + x) ^ n))\n            \\<longlonglongrightarrow> stirling_integral n x\"\n    and   stirling_integral_real_convergent:\n            \"convergent (\\<lambda>N. integral {0..real N} (\\<lambda>t. pbernpoly n t / (t + x) ^ n))\"\nproof -\n  have \"(\\<lambda>N. integral {0..real N} (\\<lambda>t. of_real (pbernpoly n t / (t + x) ^ n)))\n           \\<longlonglongrightarrow> stirling_integral n (complex_of_real x)\"\n    using LIMSEQ_stirling_integral[of \"complex_of_real x\" n] assms by simp\n  hence \"(\\<lambda>N. of_real (integral {0..real N} (\\<lambda>t. pbernpoly n t / (t + x) ^ n)))\n           \\<longlonglongrightarrow> stirling_integral n (complex_of_real x)\"\n    using integrable_ln_Gamma_aux_real[OF assms(1), of n] \n    by (subst (asm) integral_of_real) simp\n  from tendsto_Re[OF this] \n    have \"(\\<lambda>N. integral {0..real N} (\\<lambda>t. pbernpoly n t / (t + x) ^ n))\n           \\<longlonglongrightarrow> Re (stirling_integral n (complex_of_real x))\" by simp\n  thus \"convergent (\\<lambda>N. integral {0..real N} (\\<lambda>t. pbernpoly n t / (t + x) ^ n))\"\n    by (rule convergentI)\n  thus \"(\\<lambda>N. integral {0..real N} (\\<lambda>t. pbernpoly n t / (t + x) ^ n))\n          \\<longlonglongrightarrow> stirling_integral n x\" unfolding stirling_integral_def\n    by (simp add: convergent_LIMSEQ_iff)\n  from tendsto_of_real[OF this, where 'a = complex] \n       integrable_ln_Gamma_aux_real[OF assms(1), of n]\n    have \"(\\<lambda>xa. integral {0..real xa} \n                    (\\<lambda>xa. complex_of_real (pbernpoly n xa) / (complex_of_real xa + x) ^ n))\n             \\<longlonglongrightarrow> complex_of_real (stirling_integral n x)\"\n    by (subst (asm) integral_of_real [symmetric]) simp_all\n  from LIMSEQ_unique[OF this LIMSEQ_stirling_integral[of \"complex_of_real x\" n]] assms\n    show \"stirling_integral n (complex_of_real x) = of_real (stirling_integral n x)\" by simp\nqed\n\nlemma ln_Gamma_stirling_real:\n  assumes \"x > (0 :: real)\" \"m > (0::nat)\"\n  shows   \"ln_Gamma x = (x - 1 / 2) * ln x - x + ln (2 * pi) / 2 +\n              (\\<Sum>k = 1..<m. bernoulli (Suc k) / (of_nat k * of_nat (Suc k) * x ^ k)) -\n              stirling_integral m x / of_nat m\"\nproof -\n  from assms have \"complex_of_real (ln_Gamma x) = ln_Gamma (complex_of_real x)\"\n    by (simp add: ln_Gamma_complex_of_real)\n  also have \"ln_Gamma (complex_of_real x) = complex_of_real (\n                (x - 1 / 2) * ln x - x + ln (2 * pi) / 2 +\n                (\\<Sum>k = 1..<m. bernoulli (Suc k) / (of_nat k * of_nat (Suc k) * x ^ k)) -\n                stirling_integral m x / of_nat m)\" using assms\n    by (subst ln_Gamma_stirling_complex[of _ m])\n       (simp_all add: Ln_of_real stirling_integral_complex_of_real)\n  finally show ?thesis by (subst (asm) of_real_eq_iff)\nqed\n\n\nlemma stirling_integral_bound_aux:\n  assumes n: \"n > (1::nat)\"\n  obtains c where \"\\<And>s. Re s > 0 \\<Longrightarrow> norm (stirling_integral n s) \\<le>  c / Re s ^ (n - 1)\"\nproof -\n  obtain c where c: \"norm (pbernpoly n x) \\<le> c\" for x by (rule bounded_pbernpoly[of n]) blast\n  have c': \"pbernpoly n x \\<le> c\" for x using c[of x] by (simp add: abs_real_def split: if_splits)\n  from c[of 0] have c_nonneg: \"c \\<ge> 0\" by simp\n  have \"norm (stirling_integral n s) \\<le> c / (real n - 1) / Re s ^ (n - 1)\" if s: \"Re s > 0\" for s\n  proof (rule Lim_norm_ubound[OF _ LIMSEQ_stirling_integral])\n    have pos: \"x + norm s > 0\" if \"x \\<ge> 0\" for x using s that by (intro add_nonneg_pos) auto\n    have nz: \"of_real x + s \\<noteq> 0\" if \"x \\<ge> 0\" for x using s that by (auto simp: complex_eq_iff)\n    let ?bound = \"\\<lambda>N. c / (Re s ^ (n - 1) * (real n - 1)) - \n                        c / ((real N + Re s) ^ (n - 1) * (real n - 1))\"\n    show \"eventually (\\<lambda>N. norm (integral {0..real N} \n              (\\<lambda>x. of_real (pbernpoly n x) / (of_real x + s) ^ n)) \\<le> \n            c / (real n - 1) / Re s ^ (n - 1)) at_top\"\n      using eventually_gt_at_top[of \"0::nat\"]\n    proof eventually_elim\n      case (elim N)\n      let ?F = \"\\<lambda>x. -c / ((x + Re s) ^ (n - 1) * (real n - 1))\"\n      from n s have \"((\\<lambda>x. c / (x + Re s) ^ n) has_integral (?F (real N) - ?F 0)) {0..real N}\"\n        by (intro fundamental_theorem_of_calculus)\n           (auto intro!: derivative_eq_intros simp: divide_simps power_diff add_eq_0_iff2\n                   has_real_derivative_iff_has_vector_derivative [symmetric])      \n      also have \"?F (real N) - ?F 0 = ?bound N\" by simp\n      finally have *: \"((\\<lambda>x. c / (x + Re s) ^ n) has_integral ?bound N) {0..real N}\" .\n      have \"norm (integral {0..real N} (\\<lambda>x. of_real (pbernpoly n x) / (of_real x + s) ^ n)) \\<le>\n              integral {0..real N} (\\<lambda>x. c / (x + Re s) ^ n)\"\n      proof (intro integral_norm_bound_integral integrable_ln_Gamma_aux s ballI)\n        fix x assume x: \"x \\<in> {0..real N}\"\n        have \"norm (of_real (pbernpoly n x) / (of_real x + s) ^ n) \\<le> c / norm (of_real x + s) ^ n\"\n          unfolding norm_divide norm_power using c by (intro divide_right_mono) simp_all\n        also have \"\\<dots> \\<le> c / (x + Re s) ^ n\" \n          using x c c_nonneg s nz[of x] complex_Re_le_cmod[of \"of_real x + s\"]\n          by (intro divide_left_mono power_mono mult_pos_pos zero_less_power add_nonneg_pos) auto\n        finally show \"norm (of_real (pbernpoly n x) / (of_real x + s) ^ n) \\<le> \\<dots>\" .\n      qed (insert n s * pos nz c, auto simp: complex_nonpos_Reals_iff)\n      also have \"\\<dots> = ?bound N\" using * by (simp add: has_integral_iff)\n      also have \"\\<dots> \\<le> c / (Re s ^ (n - 1) * (real n - 1))\" using c_nonneg elim s n by simp\n      also have \"\\<dots> = c / (real n - 1) / (Re s ^ (n - 1))\" by simp\n      finally show \"norm (integral {0..real N} (\\<lambda>x. of_real (pbernpoly n x) /\n                      (of_real x + s) ^ n)) \\<le> c / (real n - 1) / Re s ^ (n - 1)\" .\n    qed\n  qed (insert s n, simp_all add: complex_nonpos_Reals_iff)\n  thus ?thesis by (rule that)\nqed\n\nlemma stirling_integral_bound_aux_integral1:\n  fixes a b c :: real and n :: nat\n  assumes \"a \\<ge> 0\" \"b > 0\" \"c \\<ge> 0\" \"n > 1\" \"l < a - b\" \"r > a + b\"\n  shows \"((\\<lambda>x. c / max b \\<bar>x - a\\<bar> ^ n) has_integral\n           2*c*(n / (n - 1))/b^(n-1) - c/(n-1) * (1/(a-l)^(n-1) + 1/(r-a)^(n-1))) {l..r}\"\nproof -\n  define x1 x2 where \"x1 = a - b\" and \"x2 = a + b\"\n  define F1 where \"F1 = (\\<lambda>x::real. c / (a - x) ^ (n - 1) / (n - 1))\"\n  define F3 where \"F3 = (\\<lambda>x::real. -c / (x - a) ^ (n - 1) / (n - 1))\"\n  have deriv: \"(F1 has_vector_derivative (c / (a - x) ^ n)) (at x within A)\"\n              \"(F3 has_vector_derivative (c / (x - a) ^ n)) (at x within A)\"\n    if \"x \\<noteq> a\" for x :: real and A\n    unfolding F1_def F3_def using assms that\n    by (auto intro!: derivative_eq_intros simp: divide_simps power_diff add_eq_0_iff2\n             simp flip: has_real_derivative_iff_has_vector_derivative)\n\n  from assms have \"((\\<lambda>x. c / (a - x) ^ n) has_integral (F1 x1 - F1 l)) {l..x1}\"\n    by (intro fundamental_theorem_of_calculus deriv) (auto simp: x1_def max_def split: if_splits)\n  also have \"?this \\<longleftrightarrow> ((\\<lambda>x. c / max b \\<bar>x - a\\<bar> ^ n) has_integral (F1 x1 - F1 l)) {l..x1}\"\n    using assms\n    by (intro has_integral_spike_finite_eq[of \"{l}\"]) (auto simp: x1_def max_def split: if_splits)\n  finally have I1: \"((\\<lambda>x. c / max b \\<bar>x - a\\<bar> ^ n) has_integral (F1 x1 - F1 l)) {l..x1}\" .\n\n  have \"((\\<lambda>x. c / b ^ n) has_integral (x2 - x1) * c / b ^ n) {x1..x2}\"\n    using has_integral_const_real[of \"c / b ^ n\" x1 x2] assms by (simp add: x1_def x2_def)\n  also have \"?this \\<longleftrightarrow> ((\\<lambda>x. c / max b \\<bar>x - a\\<bar> ^ n) has_integral ((x2 - x1) * c / b ^ n)) {x1..x2}\"\n    by (intro has_integral_spike_finite_eq[of \"{x1, x2}\"])\n       (auto simp: x1_def x2_def split: if_splits)\n  finally have I2: \"((\\<lambda>x. c / max b \\<bar>x - a\\<bar> ^ n) has_integral ((x2 - x1) * c / b ^ n)) {x1..x2}\" .\n\n  from assms have I3: \"((\\<lambda>x. c / (x - a) ^ n) has_integral (F3 r - F3 x2)) {x2..r}\"\n    by (intro fundamental_theorem_of_calculus deriv) (auto simp: x2_def min_def split: if_splits)\n  also have \"?this \\<longleftrightarrow> ((\\<lambda>x. c / max b \\<bar>x - a\\<bar> ^ n) has_integral (F3 r - F3 x2)) {x2..r}\"\n    using assms\n    by (intro has_integral_spike_finite_eq[of \"{r}\"]) (auto simp: x2_def min_def split: if_splits)\n  finally have I3: \"((\\<lambda>x. c / max b \\<bar>x - a\\<bar> ^ n) has_integral (F3 r - F3 x2)) {x2..r}\" .\n\n  have \"((\\<lambda>x. c / max b \\<bar>x - a\\<bar> ^ n) has_integral (F1 x1 - F1 l) + ((x2 - x1) * c / b ^ n) + (F3 r - F3 x2)) {l..r}\"\n    using assms\n    by (intro has_integral_combine[OF _ _ has_integral_combine[OF _ _ I1 I2] I3])\n       (auto simp: x1_def x2_def)\n  also have \"(F1 x1 - F1 l) + ((x2 - x1) * c / b ^ n) + (F3 r - F3 x2) =\n             F1 x1 - F1 l + F3 r - F3 x2 + (x2 - x1) * c / b ^ n\"\n    by (simp add: algebra_simps)\n  also have \"x2 - x1 = 2 * b\"\n    using assms by (simp add: x2_def x1_def min_def max_def)\n  also have \"2 * b * c / b ^ n = 2 * c / b ^ (n - 1)\"\n    using assms by (simp add: power_diff field_simps)\n  also have \"F1 x1 - F1 l + F3 r - F3 x2 =\n               c/(n-1) * (2/b^(n-1) - 1/(a-l)^(n-1) - 1/(r-a)^(n-1))\"\n    using assms by (simp add: x1_def x2_def F1_def F3_def field_simps)\n  also have \"\\<dots> + 2 * c / b ^ (n - 1) =\n             2*c*(1 + 1/(n-1))/b^(n-1) - c/(n-1) * (1/(a-l)^(n-1) + 1/(r-a)^(n-1))\"\n    using assms by (simp add: field_simps)\n  also have \"1 + 1 / (n - 1) = n / (n - 1)\"\n    using assms by (simp add: field_simps)\n  finally show ?thesis .\nqed\n\nlemma stirling_integral_bound_aux_integral2:\n  fixes a b c :: real and n :: nat\n  assumes \"a \\<ge> 0\" \"b > 0\" \"c \\<ge> 0\" \"n > 1\"\n  obtains I where \"((\\<lambda>x. c / max b \\<bar>x - a\\<bar> ^ n) has_integral I) {l..r}\"\n                  \"I \\<le> 2 * c * (n / (n - 1)) / b ^ (n-1)\"\nproof -\n  define l' where \"l' = min l (a - b - 1)\"\n  define r' where \"r' = max r (a + b + 1)\"\n\n  define A where \"A = 2 * c * (n / (n - 1)) / b ^ (n - 1)\"\n  define B where \"B = c / real (n - 1) * (1 / (a - l') ^ (n - 1) + 1 / (r' - a) ^ (n - 1))\"\n\n  have has_int: \"((\\<lambda>x. c / max b \\<bar>x - a\\<bar> ^ n) has_integral (A - B)) {l'..r'}\"\n    using assms unfolding A_def B_def\n    by (intro stirling_integral_bound_aux_integral1) (auto simp: l'_def r'_def)\n  have \"(\\<lambda>x. c / max b \\<bar>x - a\\<bar> ^ n) integrable_on {l..r}\"\n    by (rule integrable_on_subinterval[OF has_integral_integrable[OF has_int]])\n       (auto simp: l'_def r'_def)\n  then obtain I where has_int': \"((\\<lambda>x. c / max b \\<bar>x - a\\<bar> ^ n) has_integral I) {l..r}\"\n    by (auto simp: integrable_on_def)\n\n  from assms have \"I \\<le> A - B\"\n    by (intro has_integral_subset_le[OF _ has_int' has_int]) (auto simp: l'_def r'_def)\n  also have \"\\<dots> \\<le> A\"\n    using assms by (simp add: B_def l'_def r'_def)\n  finally show ?thesis using that[of I] has_int' unfolding A_def by blast\nqed\n\nlemma stirling_integral_bound_aux':\n  assumes n: \"n > (1::nat)\" and \\<alpha>: \"\\<alpha> \\<in> {0<..<pi}\"\n  obtains c where \"\\<And>s::complex. s \\<in> complex_cone' \\<alpha> - {0} \\<Longrightarrow>\n                     norm (stirling_integral n s) \\<le> c / norm s ^ (n - 1)\"\nproof -\n  obtain c where c: \"norm (pbernpoly n x) \\<le> c\" for x by (rule bounded_pbernpoly[of n]) blast\n  have c': \"pbernpoly n x \\<le> c\" for x using c[of x] by (simp add: abs_real_def split: if_splits)\n  from c[of 0] have c_nonneg: \"c \\<ge> 0\" by simp\n\n  define D where \"D = c * Beta (- (real_of_int (- int n) / 2) - 1 / 2) (1 / 2) / 2\"\n  define C where \"C = max D (2*c*(n/(n-1))/sin \\<alpha>^(n-1))\"\n\n  have *: \"norm (stirling_integral n s) \\<le> C / norm s ^ (n - 1)\"\n    if s: \"s \\<in> complex_cone' \\<alpha> - {0}\" for s :: complex\n  proof (rule Lim_norm_ubound[OF _ LIMSEQ_stirling_integral])\n    from s \\<alpha> have Arg: \"\\<bar>Arg s\\<bar> \\<le> \\<alpha>\" by (auto simp: complex_cone_altdef)\n    have s': \"s \\<notin> \\<real>\\<^sub>\\<le>\\<^sub>0\"\n      using complex_cone_inter_nonpos_Reals[of \"-\\<alpha>\" \\<alpha>] \\<alpha> s  by auto\n    from s have [simp]: \"s \\<noteq> 0\" by auto\n\n    show \"eventually (\\<lambda>N. norm (integral {0..real N}\n              (\\<lambda>x. of_real (pbernpoly n x) / (of_real x + s) ^ n)) \\<le> \n            C / norm s ^ (n - 1)) at_top\"\n      using eventually_gt_at_top[of \"0::nat\"]\n    proof eventually_elim\n      case (elim N)\n      show ?case\n      proof (cases \"Re s > 0\")\n        case True\n        have int: \"((\\<lambda>x. c * (x^2 + norm s^2) powr (-n / 2)) has_integral\n                  D * (norm s ^ 2) powr (-n / 2 + 1 / 2)) {0<..}\"\n          using has_integral_mult_left[OF has_integral_Beta3[of \"-n/2\" \"norm s ^ 2\"], of c] assms True\n          unfolding D_def by (simp add: algebra_simps)\n        hence int': \"((\\<lambda>x. c * (x^2 + norm s^2) powr (-n / 2)) has_integral\n                  D * (norm s ^ 2) powr (-n / 2 + 1 / 2)) {0..}\"\n          by (subst has_integral_interior [symmetric]) simp_all\n        hence integrable: \"(\\<lambda>x. c * (x^2 + norm s^2) powr (-n / 2)) integrable_on {0..}\"\n          by (simp add: has_integral_iff)\n\n        have \"norm (integral {0..real N} (\\<lambda>x. of_real (pbernpoly n x) / (of_real x + s) ^ n)) \\<le>\n                integral {0..real N} (\\<lambda>x. c * (x^2 + norm s^2) powr (-n / 2))\"\n        proof (intro integral_norm_bound_integral s ballI integrable_ln_Gamma_aux)\n          have [simp]: \"{0<..} - {0::real..} = {}\" \"{0..} - {0<..} = {0::real}\"\n            by auto\n          have \"(\\<lambda>x. c * (x\\<^sup>2 + (cmod s)\\<^sup>2) powr (real_of_int (- int n) / 2)) integrable_on {0<..}\"\n            using int by (simp add: has_integral_iff)\n          also have \"?this \\<longleftrightarrow> (\\<lambda>x. c * (x\\<^sup>2 + (cmod s)\\<^sup>2) powr (real_of_int (- int n) / 2)) integrable_on {0..}\"\n            by (intro integrable_spike_set_eq) auto\n          finally show \"(\\<lambda>x. c * (x\\<^sup>2 + (cmod s)\\<^sup>2) powr (real_of_int (- int n) / 2)) integrable_on\n                   {0..real N}\" by (rule integrable_on_subinterval) auto\n        next\n          fix x assume x: \"x \\<in> {0..real N}\"\n          have nz: \"complex_of_real x + s \\<noteq> 0\"\n            using True x by (auto simp: complex_eq_iff)\n          have \"norm (of_real (pbernpoly n x) / (of_real x + s) ^ n) \\<le> c / norm (of_real x + s) ^ n\"\n            unfolding norm_divide norm_power using c by (intro divide_right_mono) simp_all\n          also have \"\\<dots> \\<le> c / sqrt (x ^ 2 + norm s ^ 2) ^ n\"\n          proof (intro divide_left_mono mult_pos_pos zero_less_power power_mono)\n            show \"sqrt (x\\<^sup>2 + (cmod s)\\<^sup>2) \\<le> cmod (complex_of_real x + s)\"\n              using x True by (simp add: cmod_def algebra_simps power2_eq_square)\n          qed (use x True c_nonneg assms nz in \\<open>auto simp: add_nonneg_pos\\<close>)\n          also have \"sqrt (x ^ 2 + norm s ^ 2) ^ n = (x ^ 2 + norm s ^ 2) powr (1/2 * n)\"\n            by (subst powr_powr [symmetric], subst powr_realpow)\n               (auto simp: powr_half_sqrt add_nonneg_pos)\n          also have \"c / \\<dots> = c * (x^2 + norm s^2) powr (-n / 2)\"\n            by (simp add: powr_minus field_simps)\n          finally show \"norm (complex_of_real (pbernpoly n x) / (complex_of_real x + s) ^ n) \\<le> \\<dots>\" .\n        qed fact+\n        also have \"\\<dots> \\<le> integral {0..} (\\<lambda>x. c * (x^2 + norm s^2) powr (-n / 2))\"\n          using c_nonneg\n          by (intro integral_subset_le integrable integrable_on_subinterval[OF integrable]) auto\n        also have \"\\<dots> = D * (norm s ^ 2) powr (-n / 2 + 1 / 2)\"\n          using int' by (simp add: has_integral_iff)\n        also have \"(norm s ^ 2) powr (-n / 2 + 1 / 2) = norm s powr (2 * (-n / 2 + 1 / 2))\"\n          by (subst powr_powr [symmetric]) auto\n        also have \"\\<dots> = norm s powr (-real (n - 1))\"\n          using assms by (simp add: of_nat_diff)\n        also have \"D * \\<dots> = D / norm s ^ (n - 1)\"\n          by (auto simp: powr_minus powr_realpow field_simps)\n        also have \"\\<dots> \\<le> C / norm s ^ (n - 1)\"\n          by (intro divide_right_mono) (auto simp: C_def)\n        finally show \"norm (integral {0..real N} (\\<lambda>x. of_real (pbernpoly n x) / (of_real x + s) ^ n)) \\<le> \\<dots>\" .\n\n      next\n\n        case False\n        have \"cos \\<bar>Arg s\\<bar> = cos (Arg s)\"\n          by (simp add: abs_if)\n        also have \"cos (Arg s) = Re (rcis (norm s) (Arg s)) / norm s\"\n          by (subst Re_rcis) auto\n        also have \"\\<dots> = Re s / norm s\"\n          by (subst rcis_cmod_Arg) auto\n        also have \"\\<dots> \\<le> cos (pi / 2)\"\n          using False by (auto simp: field_simps)\n        finally have \"\\<bar>Arg s\\<bar> \\<ge> pi / 2\"\n          using Arg \\<alpha> by (subst (asm) cos_mono_le_eq) auto\n\n        have \"sin \\<alpha> * norm s = sin (pi - \\<alpha>) * norm s\"\n          by simp\n        also have \"\\<dots> \\<le> sin (pi - \\<bar>Arg s\\<bar>) * norm s\"\n          using \\<alpha> Arg \\<open>\\<bar>Arg s\\<bar> \\<ge> pi / 2\\<close>\n          by (intro mult_right_mono sin_monotone_2pi_le) auto\n        also have \"sin \\<bar>Arg s\\<bar> \\<ge> 0\"\n          using Arg_bounded[of s] by (intro sin_ge_zero) auto\n        hence \"sin (pi - \\<bar>Arg s\\<bar>) = \\<bar>sin \\<bar>Arg s\\<bar>\\<bar>\"\n          by simp \n        also have \"\\<dots> = \\<bar>sin (Arg s)\\<bar>\"\n          by (simp add: abs_if)\n        also have \"\\<dots> * norm s = \\<bar>Im (rcis (norm s) (Arg s))\\<bar>\"\n          by (simp add: abs_mult)\n        also have \"\\<dots> = \\<bar>Im s\\<bar>\"\n          by (subst rcis_cmod_Arg) auto\n        finally have abs_Im_ge: \"\\<bar>Im s\\<bar> \\<ge> sin \\<alpha> * norm s\" .\n\n        have [simp]: \"Im s \\<noteq> 0\" \"s \\<noteq> 0\"\n          using s \\<open>s \\<notin> \\<real>\\<^sub>\\<le>\\<^sub>0\\<close> False\n          by (auto simp: cmod_def zero_le_mult_iff complex_nonpos_Reals_iff)\n        have \"sin \\<alpha> > 0\"\n          using assms by (intro sin_gt_zero) auto\n  \n        obtain I where I: \"((\\<lambda>x. c / max \\<bar>Im s\\<bar> \\<bar>x + Re s\\<bar> ^ n) has_integral I) {0..real N}\"\n                          \"I \\<le> 2*c*(n/(n-1)) / \\<bar>Im s\\<bar> ^ (n - 1)\"\n          using s c_nonneg assms False \n                stirling_integral_bound_aux_integral2[of \"-Re s\" \"\\<bar>Im s\\<bar>\" c n 0 \"real N\"] by auto\n  \n        have \"norm (integral {0..real N} (\\<lambda>x. of_real (pbernpoly n x) / (of_real x + s) ^ n)) \\<le>\n                integral {0..real N} (\\<lambda>x. c / max \\<bar>Im s\\<bar> \\<bar>x + Re s\\<bar> ^ n)\"\n        proof (intro integral_norm_bound_integral integrable_ln_Gamma_aux s ballI)\n          show \"(\\<lambda>x. c / max \\<bar>Im s\\<bar> \\<bar>x + Re s\\<bar> ^ n) integrable_on {0..real N}\"\n            using I(1) by (simp add: has_integral_iff)\n        next\n          fix x assume x: \"x \\<in> {0..real N}\"\n          have nz: \"complex_of_real x + s \\<noteq> 0\"\n            by (auto simp: complex_eq_iff)\n          have \"norm (complex_of_real (pbernpoly n x) / (complex_of_real x + s) ^ n) \\<le>\n                  c / norm (complex_of_real x + s) ^ n\"\n            unfolding norm_divide norm_power using c[of x] by (intro divide_right_mono) simp_all\n          also have \"\\<dots> \\<le> c / max \\<bar>Im s\\<bar> \\<bar>x + Re s\\<bar> ^ n\"\n            using c_nonneg nz abs_Re_le_cmod[of \"of_real x + s\"] abs_Im_le_cmod[of \"of_real x + s\"]\n            by (intro divide_left_mono power_mono mult_pos_pos zero_less_power)\n               (auto simp: less_max_iff_disj)\n          finally show \"norm (complex_of_real (pbernpoly n x) / (complex_of_real x + s) ^ n) \\<le> \\<dots>\" .\n        qed (auto simp: complex_nonpos_Reals_iff)\n        also have \"\\<dots> \\<le> 2*c*(n/(n-1)) / \\<bar>Im s\\<bar> ^ (n - 1)\"\n          using I by (simp add: has_integral_iff)\n        also have \"\\<dots> \\<le> 2*c*(n/(n-1)) / (sin \\<alpha> * norm s) ^ (n - 1)\"\n          using \\<open>sin \\<alpha> > 0\\<close> s c_nonneg abs_Im_ge\n          by (intro divide_left_mono mult_pos_pos zero_less_power power_mono mult_nonneg_nonneg) auto\n        also have \"\\<dots> = 2*c*(n/(n-1))/sin \\<alpha>^(n-1) / norm s ^ (n - 1)\"\n          by (simp add: field_simps)\n        also have \"\\<dots> \\<le> C / norm s ^ (n - 1)\"\n          by (intro divide_right_mono) (auto simp: C_def)\n        finally show ?thesis .\n      qed\n    qed\n  qed (use that assms complex_cone_inter_nonpos_Reals[of \"-\\<alpha>\" \\<alpha>] \\<alpha> in auto)\n  thus ?thesis by (rule that)\nqed\n\nlemma stirling_integral_bound:\n  assumes \"n > 0\"\n  obtains c where \n    \"\\<And>s. Re s > 0 \\<Longrightarrow> norm (stirling_integral n s) \\<le> c / Re s ^ n\"\nproof -\n  let ?f = \"\\<lambda>s. of_nat n / of_nat (Suc n) * stirling_integral (Suc n) s -\n                  of_real (bernoulli (Suc n)) / (of_nat (Suc n) * s ^ n)\"\n  from stirling_integral_bound_aux[of \"Suc n\"] assms obtain c where \n    c: \"\\<And>s. Re s > 0 \\<Longrightarrow> norm (stirling_integral (Suc n) s) \\<le> c / Re s ^ n\" by auto\n  define c1 where \"c1 = real n / real (Suc n) * c\"\n  define c2 where \"c2 = \\<bar>bernoulli (Suc n)\\<bar> / real (Suc n)\"\n  have c2_nonneg: \"c2 \\<ge> 0\" by (simp add: c2_def)\n  show ?thesis\n  proof (rule that)\n    fix s :: complex assume s: \"Re s > 0\"\n    hence s': \"s \\<notin> \\<real>\\<^sub>\\<le>\\<^sub>0\" by (auto simp: complex_nonpos_Reals_iff)\n    have \"stirling_integral n s = ?f s\" using s' assms \n      by (rule stirling_integral_conv_stirling_integral_Suc)\n    also have \"norm \\<dots> \\<le> norm (of_nat n / of_nat (Suc n) * stirling_integral (Suc n) s) +\n                           norm (of_real (bernoulli (Suc n)) / (of_nat (Suc n) * s ^ n))\"\n      by (rule norm_triangle_ineq4)\n    also have \"\\<dots> = real n / real (Suc n) * norm (stirling_integral (Suc n) s) +\n                      c2 / norm s ^ n\" (is \"_ = ?A + ?B\")\n      by (simp add: norm_divide norm_mult norm_power c2_def field_simps del: of_nat_Suc)\n    also have \"?A \\<le> real n / real (Suc n) * (c / Re s ^ n)\"\n      by (intro mult_left_mono c s) simp_all\n    also have \"\\<dots> = c1 / Re s ^ n\" by (simp add: c1_def)\n    also have \"c2 / norm s ^ n \\<le> c2 / Re s ^ n\" using s c2_nonneg\n      by (intro divide_left_mono power_mono complex_Re_le_cmod mult_pos_pos zero_less_power) auto\n    also have \"c1 / Re s ^ n + c2 / Re s ^ n = (c1 + c2) / Re s ^ n\" \n      using s by (simp add: field_simps)\n    finally show \"norm (stirling_integral n s) \\<le> (c1 + c2) / Re s ^ n\" by - simp_all\n  qed\nqed\n\nlemma stirling_integral_bound':\n  assumes \"n > 0\" and \"\\<alpha> \\<in> {0<..<pi}\"\n  obtains c where \n    \"\\<And>s::complex. s \\<in> complex_cone' \\<alpha> - {0} \\<Longrightarrow> norm (stirling_integral n s) \\<le> c / norm s ^ n\"\nproof -\n  let ?f = \"\\<lambda>s. of_nat n / of_nat (Suc n) * stirling_integral (Suc n) s -\n                  of_real (bernoulli (Suc n)) / (of_nat (Suc n) * s ^ n)\"\n  from stirling_integral_bound_aux'[of \"Suc n\"] assms obtain c where \n    c: \"\\<And>s::complex. s \\<in> complex_cone' \\<alpha> - {0} \\<Longrightarrow>\n            norm (stirling_integral (Suc n) s) \\<le> c / norm s ^ n\" by auto\n  define c1 where \"c1 = real n / real (Suc n) * c\"\n  define c2 where \"c2 = \\<bar>bernoulli (Suc n)\\<bar> / real (Suc n)\"\n  have c2_nonneg: \"c2 \\<ge> 0\" by (simp add: c2_def)\n  show ?thesis\n  proof (rule that)\n    fix s :: complex assume s: \"s \\<in> complex_cone' \\<alpha> - {0}\"\n    have s': \"s \\<notin> \\<real>\\<^sub>\\<le>\\<^sub>0\"\n      using complex_cone_inter_nonpos_Reals[of \"-\\<alpha>\" \\<alpha>] assms s by auto\n      \n    have \"stirling_integral n s = ?f s\" using s' assms \n      by (intro stirling_integral_conv_stirling_integral_Suc) auto\n    also have \"norm \\<dots> \\<le> norm (of_nat n / of_nat (Suc n) * stirling_integral (Suc n) s) +\n                           norm (of_real (bernoulli (Suc n)) / (of_nat (Suc n) * s ^ n))\"\n      by (rule norm_triangle_ineq4)\n    also have \"\\<dots> = real n / real (Suc n) * norm (stirling_integral (Suc n) s) +\n                      c2 / norm s ^ n\" (is \"_ = ?A + ?B\")\n      by (simp add: norm_divide norm_mult norm_power c2_def field_simps del: of_nat_Suc)\n    also have \"?A \\<le> real n / real (Suc n) * (c / norm s ^ n)\"\n      by (intro mult_left_mono c s) simp_all\n    also have \"\\<dots> = c1 / norm s ^ n\" by (simp add: c1_def)\n    also have \"c1 / norm s ^ n + c2 / norm s ^ n = (c1 + c2) / norm s ^ n\" \n      using s by (simp add: divide_simps)\n    finally show \"norm (stirling_integral n s) \\<le> (c1 + c2) / norm s ^ n\" by - simp_all\n  qed\nqed\n\n\nlemma stirling_integral_holomorphic [holomorphic_intros]:\n  assumes m: \"m > 0\" and \"A \\<inter> \\<real>\\<^sub>\\<le>\\<^sub>0 = {}\"\n  shows   \"stirling_integral m holomorphic_on A\"  \nproof -\n  from assms have [simp]: \"z \\<notin> \\<real>\\<^sub>\\<le>\\<^sub>0\" if \"z \\<in> A\" for z\n    using that by auto\n  let ?f = \"\\<lambda>s::complex. of_nat m * ((s - 1 / 2) * Ln s - s + of_real (ln (2 * pi) / 2) +\n          (\\<Sum>k=1..<m. of_real (bernoulli (Suc k)) / (of_nat k * of_nat (Suc k) * s ^ k)) - \n          ln_Gamma s)\"\n  have \"?f holomorphic_on A\" using assms\n    by (auto intro!: holomorphic_intros simp del: of_nat_Suc elim!: nonpos_Reals_cases)\n  also have \"?this \\<longleftrightarrow> stirling_integral m holomorphic_on A\" \n    using assms by (intro holomorphic_cong refl) \n                   (simp_all add: field_simps ln_Gamma_stirling_complex)\n  finally show \"stirling_integral m holomorphic_on A\" .\nqed\n\nlemma stirling_integral_continuous_on_complex [continuous_intros]:\n  assumes m: \"m > 0\" and \"A \\<inter> \\<real>\\<^sub>\\<le>\\<^sub>0 = {}\"\n  shows   \"continuous_on A (stirling_integral m :: _ \\<Rightarrow> complex)\"\n  by (intro holomorphic_on_imp_continuous_on stirling_integral_holomorphic assms)\n    \nlemma has_field_derivative_stirling_integral_complex:\n  fixes x :: complex\n  assumes \"x \\<notin> \\<real>\\<^sub>\\<le>\\<^sub>0\" \"n > 0\"\n  shows   \"(stirling_integral n has_field_derivative deriv (stirling_integral n) x) (at x)\"\n  using assms\n  by (intro holomorphic_derivI[OF stirling_integral_holomorphic, of n  \"-\\<real>\\<^sub>\\<le>\\<^sub>0\"]) auto\n\n\n \nlemma\n  assumes n: \"n > 0\" and \"x > 0\"\n  shows   deriv_stirling_integral_complex_of_real:\n            \"(deriv ^^ j) (stirling_integral n) (complex_of_real x) =\n               complex_of_real ((deriv ^^ j) (stirling_integral n) x)\" (is \"?lhs x = ?rhs x\")\n  and     differentiable_stirling_integral_real:\n            \"(deriv ^^ j) (stirling_integral n) field_differentiable at x\" (is ?thesis2)\nproof -\n  let ?A = \"{s. Re s > 0}\"\n  let ?f = \"\\<lambda>j x. (deriv ^^ j) (stirling_integral n) (complex_of_real x)\"\n  let ?f' = \"\\<lambda>j x. complex_of_real ((deriv ^^ j) (stirling_integral n) x)\"\n    \n  have [simp]: \"open ?A\" by (simp add: open_halfspace_Re_gt)      \n\n  have \"?lhs x = ?rhs x \\<and> (deriv ^^ j) (stirling_integral n) field_differentiable at x\" \n    if \"x > 0\" for x using that\n  proof (induction j arbitrary: x)\n    case 0\n    have \"((\\<lambda>x. Re (stirling_integral n (of_real x))) has_field_derivative \n                  Re (deriv (\\<lambda>x. stirling_integral n x) (of_real x))) (at x)\" using 0 n\n      by (auto intro!: derivative_intros has_vector_derivative_real_field\n                 field_differentiable_derivI holomorphic_on_imp_differentiable_at[of _ ?A]\n                 stirling_integral_holomorphic simp: complex_nonpos_Reals_iff)\n    also have \"?this \\<longleftrightarrow> (stirling_integral n has_field_derivative \n             Re (deriv (\\<lambda>x. stirling_integral n x) (of_real x))) (at x)\"\n      using eventually_nhds_in_open[of \"{0<..}\" x] 0 n\n      by (intro has_field_derivative_cong_ev refl) \n         (auto elim!: eventually_mono simp: stirling_integral_complex_of_real)\n    finally have \"stirling_integral n field_differentiable at x\"\n      by (auto simp: field_differentiable_def)\n    with 0 n show ?case by (auto simp: stirling_integral_complex_of_real)\n  next\n    case (Suc j x)\n    note IH = conjunct1[OF Suc.IH] conjunct2[OF Suc.IH]\n    have *: \"(deriv ^^ Suc j) (stirling_integral n) (complex_of_real x) =\n                 of_real ((deriv ^^ Suc j) (stirling_integral n) x)\" if x: \"x > 0\" for x\n    proof -\n      have \"deriv ((deriv ^^ j) (stirling_integral n)) (complex_of_real x) =\n              vector_derivative (\\<lambda>x. (deriv ^^ j) (stirling_integral n) (of_real x)) (at x)\"\n        using n x\n        by (intro vector_derivative_of_real_right [symmetric] \n                   holomorphic_on_imp_differentiable_at[of _ ?A] holomorphic_higher_deriv\n                   stirling_integral_holomorphic) (auto simp: complex_nonpos_Reals_iff)\n      also have \"\\<dots> = vector_derivative (\\<lambda>x. of_real ((deriv ^^ j) (stirling_integral n) x)) (at x)\"\n        using eventually_nhds_in_open[of \"{0<..}\" x] x\n        by (intro vector_derivative_cong_eq) (auto elim!: eventually_mono simp: IH(1))\n      also have \"\\<dots> = of_real (deriv ((deriv ^^ j) (stirling_integral n)) x)\"\n        by (intro vector_derivative_of_real_left holomorphic_on_imp_differentiable_at[of _ ?A]\n              field_differentiable_imp_differentiable IH(2) x)\n      finally show ?thesis by simp\n    qed\n    have \"((\\<lambda>x. Re ((deriv ^^ Suc j) (stirling_integral n) (of_real x))) has_field_derivative \n             Re (deriv ((deriv ^^ Suc j) (stirling_integral n)) (of_real x))) (at x)\"\n      using Suc.prems n\n      by (intro derivative_intros has_vector_derivative_real_field field_differentiable_derivI\n                holomorphic_on_imp_differentiable_at[of _ ?A] stirling_integral_holomorphic\n                holomorphic_higher_deriv) (auto simp: complex_nonpos_Reals_iff)\n    also have \"?this \\<longleftrightarrow> ((deriv ^^ Suc j) (stirling_integral n) has_field_derivative \n                  Re (deriv ((deriv ^^ Suc j) (stirling_integral n)) (of_real x))) (at x)\"  \n      using eventually_nhds_in_open[of \"{0<..}\" x] Suc.prems *\n      by (intro has_field_derivative_cong_ev refl) (auto elim!: eventually_mono)\n    finally have \"(deriv ^^ Suc j) (stirling_integral n) field_differentiable at x\"\n      by (auto simp: field_differentiable_def)\n    with *[OF Suc.prems] show ?case by blast\n  qed\n  from this[OF assms(2)] show \"?lhs x = ?rhs x\" ?thesis2 by blast+\nqed\n\ntext \\<open>\n  Unfortunately, asymptotic power series cannot, in general, be differentiated. However, since \n  @{term ln_Gamma} is holomorphic on the entire positive real half-space, we can differentiate \n  its asymptotic expansion after all.\n\n  To do this, we use an ad-hoc version of the more general approach outlined in Erdelyi's\n  ``Asymptotic Expansions'' for holomorphic functions: We bound the value of the $j$-th derivative \n  of the remainder term at some value $x$ by applying Cauchy's integral formula along a circle \n  centred at $x$ with radius $\\frac{1}{2} x$.\n\\<close>\nlemma deriv_stirling_integral_real_bound:\n  assumes m: \"m > 0\"\n  shows   \"(deriv ^^ j) (stirling_integral m) \\<in> O(\\<lambda>x::real. 1 / x ^ (m + j))\"\nproof -\n  obtain c where c: \"\\<And>s. 0 < Re s \\<Longrightarrow> cmod (stirling_integral m s) \\<le> c / Re s ^ m\"\n    using stirling_integral_bound[OF m] by auto\n  have \"0 \\<le> cmod (stirling_integral m 1)\" by simp\n  also have \"\\<dots> \\<le> c\" using c[of 1] by simp\n  finally have c_nonneg: \"c \\<ge> 0\" .\n  define B where \"B = c * 2 ^ (m + Suc j)\"\n  define B' where \"B' = B * fact j / 2\"\n\n  have \"eventually (\\<lambda>x::real. norm ((deriv ^^ j) (stirling_integral m) x) \\<le> \n          B' * norm (1 / x ^ (m+ j))) at_top\"\n    using eventually_gt_at_top[of \"0::real\"]\n  proof eventually_elim\n    case (elim x)\n    have \"s \\<notin> \\<real>\\<^sub>\\<le>\\<^sub>0\" if \"s \\<in> cball (of_real x) (x/2)\" for s :: complex\n    proof -\n      have \"x - Re s \\<le> norm (of_real x - s)\" using complex_Re_le_cmod[of \"of_real x - s\"] by simp\n      also from that have \"\\<dots> \\<le> x/2\" by (simp add: dist_complex_def)\n      finally show ?thesis using elim by (auto simp: complex_nonpos_Reals_iff)\n    qed\n    hence \"((\\<lambda>u. stirling_integral m u / (u - of_real x) ^ Suc j) has_contour_integral\n            complex_of_real (2 * pi) * \\<i> / fact j * \n              (deriv ^^ j) (stirling_integral m) (of_real x)) (circlepath (of_real x) (x/2))\"\n      using m elim\n      by (intro Cauchy_has_contour_integral_higher_derivative_circlepath \n                stirling_integral_continuous_on_complex stirling_integral_holomorphic) auto\n    hence \"norm (of_real (2 * pi) * \\<i> / fact j * (deriv ^^ j) (stirling_integral m) (of_real x)) \\<le>\n            B / x ^ (m + Suc j) * (2 * pi * (x / 2))\"\n    proof (rule has_contour_integral_bound_circlepath)\n      fix u :: complex assume dist: \"norm (u - of_real x) = x / 2\"\n      have \"Re (of_real x - u) \\<le> norm (of_real x - u)\" by (rule complex_Re_le_cmod)\n      also have \"\\<dots> = x / 2\" using dist by (simp add: norm_minus_commute)\n      finally have Re_u: \"Re u \\<ge> x/2\" using elim by simp\n      have \"norm (stirling_integral m u / (u - of_real x) ^ Suc j) \\<le> \n              c / Re u ^ m / (x / 2) ^ Suc j\" using Re_u elim\n        unfolding norm_divide norm_power dist\n        by (intro divide_right_mono zero_le_power c) simp_all\n      also have \"\\<dots> \\<le> c / (x/2) ^ m / (x / 2) ^ Suc j\" using c_nonneg elim Re_u\n        by (intro divide_right_mono divide_left_mono power_mono) simp_all\n      also have \"\\<dots> = B / x ^ (m + Suc j)\" using elim by (simp add: B_def field_simps power_add)\n      finally show \"norm (stirling_integral m u / (u - of_real x) ^ Suc j) \\<le> B / x ^ (m + Suc j)\" .\n    qed (insert elim c_nonneg, auto simp: B_def simp del: power_Suc)\n    hence \"cmod ((deriv ^^ j) (stirling_integral m) (of_real x)) \\<le> B' / x ^ (j + m)\"\n      using elim by (simp add: field_simps norm_divide norm_mult norm_power B'_def)\n    with elim m show ?case by (simp_all add: add_ac deriv_stirling_integral_complex_of_real)\n  qed\n  thus ?thesis by (rule bigoI)\nqed\n\ndefinition stirling_sum where\n  \"stirling_sum j m x = \n     (-1) ^ j * (\\<Sum>k = 1..<m. (of_real (bernoulli (Suc k)) * pochhammer (of_nat k) j / (of_nat k *\n                                 of_nat (Suc k))) * inverse x ^ (k + j))\"\n  \ndefinition stirling_sum' where\n  \"stirling_sum' j m x = \n     (-1) ^ (Suc j) * (\\<Sum>k\\<le>m. (of_real (bernoulli' k) * \n       pochhammer (of_nat (Suc k)) (j - 1) * inverse x ^ (k + j)))\"\n\nlemma stirling_sum_complex_of_real:\n  \"stirling_sum j m (complex_of_real x) = complex_of_real (stirling_sum j m x)\"\n  by (simp add: stirling_sum_def pochhammer_of_real [symmetric] del: of_nat_Suc)\n\nlemma stirling_sum'_complex_of_real:\n  \"stirling_sum' j m (complex_of_real x) = complex_of_real (stirling_sum' j m x)\"\n  by (simp add: stirling_sum'_def pochhammer_of_real [symmetric] del: of_nat_Suc)\n\nlemma has_field_derivative_stirling_sum_complex [derivative_intros]:\n  \"Re x > 0 \\<Longrightarrow> (stirling_sum j m has_field_derivative stirling_sum (Suc j) m x) (at x)\"\n    unfolding stirling_sum_def [abs_def] sum_distrib_left\n    by (rule DERIV_sum) (auto intro!: derivative_eq_intros simp del: of_nat_Suc \n                              simp: pochhammer_Suc power_diff)\n\nlemma has_field_derivative_stirling_sum_real [derivative_intros]:\n  \"x > (0::real) \\<Longrightarrow> (stirling_sum j m has_field_derivative stirling_sum (Suc j) m x) (at x)\"\n    unfolding stirling_sum_def [abs_def] sum_distrib_left\n    by (rule DERIV_sum) (auto intro!: derivative_eq_intros simp del: of_nat_Suc \n                              simp: pochhammer_Suc power_diff)\n\nlemma has_field_derivative_stirling_sum'_complex [derivative_intros]:\n  assumes \"j > 0\" \"Re x > 0\"\n  shows   \"(stirling_sum' j m has_field_derivative stirling_sum' (Suc j) m x) (at x)\"\nproof (cases j)\n  case (Suc j')\n  from assms have [simp]: \"x \\<noteq> 0\" by auto\n  define c where \"c = (\\<lambda>n. (-1) ^ Suc j * complex_of_real (bernoulli' n) * \n                          pochhammer (of_nat (Suc n)) j')\"\n  define T where \"T = (\\<lambda>n x. c n * inverse x ^ (j + n))\"\n  define T' where \"T' = (\\<lambda>n x. - (of_nat (j + n)) * c n * inverse x ^ (Suc (j + n)))\"\n  have \"((\\<lambda>x. \\<Sum>k\\<le>m. T k x) has_field_derivative (\\<Sum>k\\<le>m. T' k x)) (at x)\" using assms Suc\n    by (intro DERIV_sum)\n       (auto simp: T_def T'_def intro!: derivative_eq_intros \n             simp: field_simps power_add [symmetric]  simp del: of_nat_Suc power_Suc of_nat_add)\n  also have \"(\\<lambda>x. (\\<Sum>k\\<le>m. T k x)) = stirling_sum' j m\"\n    by (simp add: Suc T_def c_def stirling_sum'_def fun_eq_iff add_ac mult.assoc sum_distrib_left)\n  also have \"(\\<Sum>k\\<le>m. T' k x) = stirling_sum' (Suc j) m x\"\n    by (simp add: T'_def c_def Suc stirling_sum'_def sum_distrib_left \n          sum_distrib_right algebra_simps pochhammer_Suc)\n  finally show ?thesis .\nqed (insert assms, simp_all)\n  \nlemma has_field_derivative_stirling_sum'_real [derivative_intros]:\n  assumes \"j > 0\" \"x > (0::real)\"\n  shows   \"(stirling_sum' j m has_field_derivative stirling_sum' (Suc j) m x) (at x)\"\nproof (cases j)\n  case (Suc j')\n  from assms have [simp]: \"x \\<noteq> 0\" by auto\n  define c where \"c = (\\<lambda>n. (-1) ^ Suc j * (bernoulli' n) * pochhammer (of_nat (Suc n)) j')\"\n  define T where \"T = (\\<lambda>n x. c n * inverse x ^ (j + n))\"\n  define T' where \"T' = (\\<lambda>n x. - (of_nat (j + n)) * c n * inverse x ^ (Suc (j + n)))\"\n  have \"((\\<lambda>x. \\<Sum>k\\<le>m. T k x) has_field_derivative (\\<Sum>k\\<le>m. T' k x)) (at x)\" using assms Suc\n    by (intro DERIV_sum)\n       (auto simp: T_def T'_def intro!: derivative_eq_intros \n             simp: field_simps power_add [symmetric]  simp del: of_nat_Suc power_Suc of_nat_add)\n  also have \"(\\<lambda>x. (\\<Sum>k\\<le>m. T k x)) = stirling_sum' j m\"\n    by (simp add: Suc T_def c_def stirling_sum'_def fun_eq_iff add_ac mult.assoc sum_distrib_left)\n  also have \"(\\<Sum>k\\<le>m. T' k x) = stirling_sum' (Suc j) m x\"\n    by (simp add: T'_def c_def Suc stirling_sum'_def sum_distrib_left \n          sum_distrib_right algebra_simps pochhammer_Suc)\n  finally show ?thesis .\nqed (insert assms, simp_all)\n\nlemma higher_deriv_stirling_sum_complex:\n  \"Re x > 0 \\<Longrightarrow> (deriv ^^ i) (stirling_sum j m) x = stirling_sum (i + j) m x\"\nproof (induction i arbitrary: x)\n  case (Suc i)\n  have \"deriv ((deriv ^^ i) (stirling_sum j m)) x = deriv (stirling_sum (i + j) m) x\"\n    using eventually_nhds_in_open[of \"{x. Re x > 0}\" x] Suc.prems\n    by (intro deriv_cong_ev refl) (auto elim!: eventually_mono simp: open_halfspace_Re_gt Suc.IH)\n  also from Suc.prems have \"\\<dots> = stirling_sum (Suc (i + j)) m x\"\n    by (intro DERIV_imp_deriv has_field_derivative_stirling_sum_complex)\n  finally show ?case by simp\nqed simp_all\n  \n\ndefinition Polygamma_approx :: \"nat \\<Rightarrow> nat \\<Rightarrow> 'a \\<Rightarrow> 'a :: {real_normed_field, ln}\" where\n  \"Polygamma_approx j m = \n     (deriv ^^ j) (\\<lambda>x. (x - 1 / 2) * ln x - x + of_real (ln (2 * pi)) / 2 + stirling_sum 0 m x)\"\n  \nlemma Polygamma_approx_Suc: \"Polygamma_approx (Suc j) m = deriv (Polygamma_approx j m)\"\n  by (simp add: Polygamma_approx_def)  \n\nlemma Polygamma_approx_0: \n  \"Polygamma_approx 0 m x = (x - 1/2) * ln x - x + of_real (ln (2*pi)) / 2 + stirling_sum 0 m x\"\n  by (simp add: Polygamma_approx_def)\n    \nlemma Polygamma_approx_1_complex: \n  \"Re x > 0 \\<Longrightarrow> \n     Polygamma_approx (Suc 0) m x = ln x - 1 / (2*x) + stirling_sum (Suc 0) m x\"\n  unfolding Polygamma_approx_Suc Polygamma_approx_0\n  by (intro DERIV_imp_deriv) \n     (auto intro!: derivative_eq_intros elim!: nonpos_Reals_cases simp: field_simps)\n     \nlemma Polygamma_approx_1_real: \n  \"x > (0 :: real) \\<Longrightarrow> \n     Polygamma_approx (Suc 0) m x = ln x - 1 / (2*x) + stirling_sum (Suc 0) m x\"\n  unfolding Polygamma_approx_Suc Polygamma_approx_0\n  by (intro DERIV_imp_deriv) \n     (auto intro!: derivative_eq_intros elim!: nonpos_Reals_cases simp: field_simps)\n \nlemma stirling_sum_2_conv_stirling_sum'_1:\n  fixes x :: \"'a :: {real_div_algebra, field_char_0}\"\n  assumes \"m > 0\" \"x \\<noteq> 0\"\n  shows   \"stirling_sum' 1 m x = 1 / x + 1 / (2 * x^2) + stirling_sum 2 m x\"\nproof -\n  have pochhammer_2: \"pochhammer (of_nat k) 2 = of_nat k * of_nat (Suc k)\" for k \n    by (simp add: pochhammer_Suc eval_nat_numeral add_ac)\n  have \"stirling_sum 2 m x = \n          (\\<Sum>k = Suc 0..<m. of_real (bernoulli' (Suc k)) * inverse x ^ Suc (Suc k))\"\n    unfolding stirling_sum_def pochhammer_2 power2_minus power_one mult_1_left\n    by (intro sum.cong refl)\n       (simp_all add: stirling_sum_def pochhammer_2 power2_eq_square divide_simps bernoulli'_def\n                 del: of_nat_Suc power_Suc)\n  also have \"1 / (2 * x^2) + \\<dots> = \n               (\\<Sum>k=0..<m. of_real (bernoulli' (Suc k)) * inverse x ^ Suc (Suc k))\" using assms\n    by (subst (2) sum.atLeast_Suc_lessThan) (simp_all add: power2_eq_square field_simps)\n  also have \"1 / x + \\<dots> = (\\<Sum>k=0..<Suc m. of_real (bernoulli' k) * inverse x ^ Suc k)\"\n    by (subst sum.atLeast0_lessThan_Suc_shift) (simp_all add: bernoulli'_def divide_simps)\n  also have \"\\<dots> = (\\<Sum>k\\<le>m. of_real (bernoulli' k) * inverse x ^ Suc k)\"\n    by (intro sum.cong) auto\n  also have \"\\<dots> = stirling_sum' 1 m x\" by (simp add: stirling_sum'_def)\n  finally show ?thesis by (simp add: add_ac)\nqed\n\nlemma Polygamma_approx_2_real: \n  assumes \"x > (0::real)\" \"m > 0\"\n  shows   \"Polygamma_approx (Suc (Suc 0)) m x = stirling_sum' 1 m x\"\nproof -\n  have \"Polygamma_approx (Suc (Suc 0)) m x = deriv (Polygamma_approx (Suc 0) m) x\" \n    by (simp add: Polygamma_approx_Suc)\n  also have \"\\<dots> = deriv (\\<lambda>x. ln x - 1 / (2*x) + stirling_sum (Suc 0) m x) x\"\n    using eventually_nhds_in_open[of \"{0<..}\" x] assms\n    by (intro deriv_cong_ev) (auto elim!: eventually_mono simp: Polygamma_approx_1_real)\n  also have \"\\<dots> = 1 / x + 1 / (2*x^2) + stirling_sum (Suc (Suc 0)) m x\" using assms\n    by (intro DERIV_imp_deriv) (auto intro!: derivative_eq_intros \n           elim!: nonpos_Reals_cases simp: field_simps power2_eq_square)\n  also have \"\\<dots> = stirling_sum' 1 m x\" using stirling_sum_2_conv_stirling_sum'_1[of m x] assms\n    by (simp add: eval_nat_numeral)\n  finally show ?thesis .\nqed\n  \nlemma Polygamma_approx_2_complex: \n  assumes \"Re x > 0\" \"m > 0\"\n  shows   \"Polygamma_approx (Suc (Suc 0)) m x = stirling_sum' 1 m x\"\nproof -\n  have \"Polygamma_approx (Suc (Suc 0)) m x = deriv (Polygamma_approx (Suc 0) m) x\" \n    by (simp add: Polygamma_approx_Suc)\n  also have \"\\<dots> = deriv (\\<lambda>x. ln x - 1 / (2*x) + stirling_sum (Suc 0) m x) x\"\n    using eventually_nhds_in_open[of \"{s. Re s > 0}\" x] assms\n    by (intro deriv_cong_ev)\n       (auto simp: open_halfspace_Re_gt elim!: eventually_mono simp: Polygamma_approx_1_complex)\n  also have \"\\<dots> = 1 / x + 1 / (2*x^2) + stirling_sum (Suc (Suc 0)) m x\" using assms\n    by (intro DERIV_imp_deriv) (auto intro!: derivative_eq_intros \n           elim!: nonpos_Reals_cases simp: field_simps power2_eq_square)\n  also have \"\\<dots> = stirling_sum' 1 m x\" using stirling_sum_2_conv_stirling_sum'_1[of m x] assms\n      by (subst stirling_sum_2_conv_stirling_sum'_1) (auto simp: eval_nat_numeral)\n  finally show ?thesis .\nqed\n  \nlemma Polygamma_approx_ge_2_real: \n  assumes \"x > (0::real)\" \"m > 0\"\n  shows   \"Polygamma_approx (Suc (Suc j)) m x = stirling_sum' (Suc j) m x\"\nusing assms(1)\nproof (induction j arbitrary: x)\n  case (0 x)\n  with assms show ?case by (simp add: Polygamma_approx_2_real)\nnext\n  case (Suc j x)\n  have \"Polygamma_approx (Suc (Suc (Suc j))) m x = deriv (Polygamma_approx (Suc (Suc j)) m) x\"\n    by (simp add: Polygamma_approx_Suc)\n  also have \"\\<dots> = deriv (stirling_sum' (Suc j) m) x\"\n    using eventually_nhds_in_open[of \"{0<..}\" x] Suc.prems\n    by (intro deriv_cong_ev refl) (auto elim!: eventually_mono simp: Suc.IH)\n  also have \"\\<dots> = stirling_sum' (Suc (Suc j)) m x\" using Suc.prems\n    by (intro DERIV_imp_deriv derivative_intros) simp_all\n  finally show ?case .\nqed\n  \nlemma Polygamma_approx_ge_2_complex:\n  assumes \"Re x > 0\" \"m > 0\"\n  shows   \"Polygamma_approx (Suc (Suc j)) m x = stirling_sum' (Suc j) m x\"\nusing assms(1)\nproof (induction j arbitrary: x)\n  case (0 x)\n  with assms show ?case by (simp add: Polygamma_approx_2_complex)\nnext\n  case (Suc j x)\n  have \"Polygamma_approx (Suc (Suc (Suc j))) m x = deriv (Polygamma_approx (Suc (Suc j)) m) x\"\n    by (simp add: Polygamma_approx_Suc)\n  also have \"\\<dots> = deriv (stirling_sum' (Suc j) m) x\"\n    using eventually_nhds_in_open[of \"{x. Re x > 0}\" x] Suc.prems\n    by (intro deriv_cong_ev refl) (auto elim!: eventually_mono simp: Suc.IH open_halfspace_Re_gt)\n  also have \"\\<dots> = stirling_sum' (Suc (Suc j)) m x\" using Suc.prems\n    by (intro DERIV_imp_deriv derivative_intros) simp_all\n  finally show ?case .\nqed\n\nlemma Polygamma_approx_complex_of_real:\n  assumes \"x > 0\" \"m > 0\"\n  shows   \"Polygamma_approx j m (complex_of_real x) = of_real (Polygamma_approx j m x)\"\nproof (cases j)\n  case 0\n  with assms show ?thesis by (simp add: Polygamma_approx_0 Ln_of_real stirling_sum_complex_of_real)\nnext\n  case [simp]: (Suc j')\n  thus ?thesis\n  proof (cases j')\n    case 0\n    with assms show ?thesis \n      by (simp add: Polygamma_approx_1_complex \n                    Polygamma_approx_1_real stirling_sum_complex_of_real Ln_of_real)\n  next\n    case (Suc j'')\n    with assms show ?thesis\n      by (simp add: Polygamma_approx_ge_2_complex Polygamma_approx_ge_2_real \n                    stirling_sum'_complex_of_real)\n  qed\nqed\n  \nlemma higher_deriv_Polygamma_approx [simp]: \n  \"(deriv ^^ j) (Polygamma_approx i m) = Polygamma_approx (j + i) m\"\n  by (simp add: Polygamma_approx_def funpow_add)\n  \nlemma stirling_sum_holomorphic [holomorphic_intros]:\n  \"0 \\<notin> A \\<Longrightarrow> stirling_sum j m holomorphic_on A\"\n  unfolding stirling_sum_def by (intro holomorphic_intros) auto\n  \nlemma Polygamma_approx_holomorphic [holomorphic_intros]:\n  \"Polygamma_approx j m holomorphic_on {s. Re s > 0}\"\n  unfolding Polygamma_approx_def\n  by (intro holomorphic_intros) (auto simp: open_halfspace_Re_gt elim!: nonpos_Reals_cases)\n  \nlemma higher_deriv_lnGamma_stirling:\n  assumes m: \"m > 0\"\n  shows   \"(\\<lambda>x::real. (deriv ^^ j) ln_Gamma x - Polygamma_approx j m x) \\<in> O(\\<lambda>x. 1 / x ^ (m + j))\"\nproof -\n  have \"eventually (\\<lambda>x. \\<bar>(deriv ^^ j) ln_Gamma x - Polygamma_approx j m x\\<bar> =\n                          inverse (real m) * \\<bar>(deriv ^^ j) (stirling_integral m) x\\<bar>) at_top\"\n    using eventually_gt_at_top[of \"0::real\"]\n  proof eventually_elim\n    case (elim x)\n    note x = this\n    have \"\\<forall>\\<^sub>F y in nhds (complex_of_real x). y \\<in> - \\<real>\\<^sub>\\<le>\\<^sub>0\"\n      using elim by (intro eventually_nhds_in_open) auto\n    hence \"(deriv ^^ j) (\\<lambda>x. ln_Gamma x - Polygamma_approx 0 m x) (complex_of_real x) =\n            (deriv ^^ j) (\\<lambda>x. (-inverse (of_nat m)) * stirling_integral m x) (complex_of_real x)\"\n      using x m\n      by (intro higher_deriv_cong_ev refl)\n         (auto elim!: eventually_mono simp: ln_Gamma_stirling_complex Polygamma_approx_def \n            field_simps open_halfspace_Re_gt stirling_sum_def)\n    also have \"\\<dots> = - inverse (of_nat m) * (deriv ^^ j) (stirling_integral m) (of_real x)\" using x m\n      by (intro higher_deriv_cmult[of _ \"-\\<real>\\<^sub>\\<le>\\<^sub>0\"] stirling_integral_holomorphic)\n         (auto simp: open_halfspace_Re_gt)\n    also have \"(deriv ^^ j) (\\<lambda>x. ln_Gamma x - Polygamma_approx 0 m x) (complex_of_real x) = \n                 (deriv ^^ j) ln_Gamma (of_real x) - (deriv ^^ j) (Polygamma_approx 0 m) (of_real x)\"\n      using x \n      by (intro higher_deriv_diff[of _ \"{s. Re s > 0}\"])\n         (auto intro!: holomorphic_intros elim!: nonpos_Reals_cases simp: open_halfspace_Re_gt)\n    also have \"(deriv ^^ j) (Polygamma_approx 0 m) (complex_of_real x) =\n                 of_real (Polygamma_approx j m x)\" using x m\n      by (simp add: Polygamma_approx_complex_of_real)\n    also have \"norm (- inverse (of_nat m) * (deriv ^^ j) (stirling_integral m) (complex_of_real x)) = \n                 inverse (real m) * \\<bar>(deriv ^^ j) (stirling_integral m) x\\<bar>\"\n      using x m by (simp add: norm_mult norm_inverse deriv_stirling_integral_complex_of_real)\n    also have \"(deriv ^^ j) ln_Gamma (complex_of_real x) = of_real ((deriv ^^ j) ln_Gamma x)\" using x\n      by (simp add: higher_deriv_ln_Gamma_complex_of_real)\n    also have \"norm (\\<dots> - of_real (Polygamma_approx j m x)) = \n                 \\<bar>(deriv ^^ j) ln_Gamma x - Polygamma_approx j m x\\<bar>\"\n      by (simp only: of_real_diff [symmetric] norm_of_real)\n    finally show ?case .\n  qed\n  from bigthetaI_cong[OF this] m\n    have \"(\\<lambda>x::real. (deriv ^^ j) ln_Gamma x - Polygamma_approx j m x) \\<in> \n             \\<Theta>(\\<lambda>x. (deriv ^^ j) (stirling_integral m) x)\" by simp\n  also have \"(\\<lambda>x::real. (deriv ^^ j) (stirling_integral m) x) \\<in> O(\\<lambda>x. 1 / x ^ (m + j))\" using m\n      by (rule deriv_stirling_integral_real_bound)\n  finally show ?thesis .\nqed\n\nlemma Polygamma_approx_1_real':\n  assumes x: \"(x::real) > 0\" and m: \"m > 0\"\n  shows   \"Polygamma_approx 1 m x = ln x - (\\<Sum>k = Suc 0..m. bernoulli' k * inverse x ^ k / real k)\"\nproof -\n  have \"Polygamma_approx 1 m x = ln x - (1 / (2 * x) + \n          (\\<Sum>k=Suc 0..<m. bernoulli (Suc k) * inverse x ^ Suc k / real (Suc k)))\"\n    (is \"_ = _ - (_ + ?S)\") using x by (simp add: Polygamma_approx_1_real stirling_sum_def)\n  also have \"?S = (\\<Sum>k=Suc 0..<m. bernoulli' (Suc k) * inverse x ^ Suc k / real (Suc k))\"\n    by (intro sum.cong refl) (simp_all add: bernoulli'_def)\n  also have \"1 / (2 * x) + \\<dots> = \n               (\\<Sum>k=0..<m. bernoulli' (Suc k) * inverse x ^ Suc k / real (Suc k))\" using m\n    by (subst (2) sum.atLeast_Suc_lessThan) (simp_all add: field_simps)\n  also have \"\\<dots> = (\\<Sum>k = Suc 0..m. bernoulli' k * inverse x ^ k / real k)\" using assms\n    by (subst sum.shift_bounds_Suc_ivl [symmetric]) (simp add: atLeastLessThanSuc_atLeastAtMost)\n  finally show ?thesis .\nqed\n\ntheorem\n  assumes m: \"m > 0\"\n  shows   ln_Gamma_real_asymptotics:\n            \"(\\<lambda>x. ln_Gamma x - ((x - 1 / 2) * ln x - x + ln (2 * pi) / 2 +\n                     (\\<Sum>k = 1..<m. bernoulli (Suc k) / (real k * real (Suc k)) / x^k)))\n                \\<in> O(\\<lambda>x. 1 / x ^ m)\" (is ?th1)\n    and   Digamma_real_asymptotics:\n            \"(\\<lambda>x. Digamma x - (ln x - (\\<Sum>k=1..m. bernoulli' k / real k / x ^ k)))\n                \\<in> O(\\<lambda>x. 1 / (x ^ Suc m))\" (is ?th2)\n    and   Polygamma_real_asymptotics: \"j > 0 \\<Longrightarrow> \n             (\\<lambda>x. Polygamma j x - (- 1) ^ Suc j * (\\<Sum>k\\<le>m. bernoulli' k *\n                     pochhammer (real (Suc k)) (j - 1) / x ^ (k + j))) \n                \\<in> O(\\<lambda>x. 1 / x ^ (m+j+1))\" (is \"_ \\<Longrightarrow> ?th3\")\nproof -\n  define G :: \"nat \\<Rightarrow> real \\<Rightarrow> real\" where \n    \"G = (\\<lambda>m. if m = 0 then ln_Gamma else Polygamma (m - 1))\"\n  have *: \"(\\<lambda>x. G j x - h x) \\<in> O(\\<lambda>x. 1 / x ^ (m + j))\"\n    if \"\\<And>x::real. x > 0 \\<Longrightarrow> Polygamma_approx j m x = h x\" for j h\n  proof -\n    have \"(\\<lambda>x. G j x - h x) \\<in> \n            \\<Theta>(\\<lambda>x. (deriv ^^ j) ln_Gamma x - Polygamma_approx j m x)\" (is \"_ \\<in> \\<Theta>(?f)\")\n      using that\n      by (intro bigthetaI_cong) (auto intro: eventually_mono[OF eventually_gt_at_top[of \"0::real\"]]\n            simp del: funpow.simps simp: higher_deriv_ln_Gamma_real G_def)\n    also have \"?f \\<in> O(\\<lambda>x::real. 1 / x ^ (m + j))\" using m\n      by (rule higher_deriv_lnGamma_stirling)\n    finally show ?thesis .\n  qed  \n    \n  note [[simproc del: simplify_landau_sum]]\n  from *[OF Polygamma_approx_0] assms show ?th1 \n    by (simp add: G_def Polygamma_approx_0 stirling_sum_def field_simps)\n  from *[OF Polygamma_approx_1_real'] assms show ?th2 by (simp add: G_def field_simps)\n      \n  assume j: \"j > 0\"\n  from *[OF Polygamma_approx_ge_2_real, of \"j - 1\"] assms j show ?th3\n    by (simp add: G_def stirling_sum'_def power_add power_diff field_simps)\nqed\n\n\n\n\nsubsection \\<open>Asymptotics of the complex Gamma function\\<close>\n\ntext \\<open>\n  The \\<open>m\\<close>-th order remainder of Stirling's formula for $\\log\\Gamma$ is $O(s^{-m})$ uniformly over\n  any complex cone $\\text{Arg}(z) \\leq \\alpha$, $z\\neq 0$ for any angle\n  $\\alpha\\in(0, \\pi)$. This means that there is bounded by $c z^{-m}$ for some constant $c$ for\n  all $z$ in this cone.\n\\<close>\ncontext\n  fixes F and \\<alpha>\n  assumes \\<alpha>: \"\\<alpha> \\<in> {0<..<pi}\"\n  defines \"F \\<equiv> principal (complex_cone' \\<alpha> - {0})\"\nbegin\n\nlemma stirling_integral_bigo:\n  fixes m :: nat\n  assumes m: \"m > 0\"\n  shows   \"stirling_integral m \\<in> O[F](\\<lambda>s. 1 / s ^ m)\"\nproof -\n  obtain c where c: \"\\<And>s. s \\<in> complex_cone' \\<alpha> - {0} \\<Longrightarrow> norm (stirling_integral m s) \\<le> c / norm s ^ m\"\n    using stirling_integral_bound'[OF \\<open>m > 0\\<close> \\<alpha>] by blast\n  have \"0 \\<le> norm (stirling_integral m 1 :: complex)\"\n    by simp\n  also have \"\\<dots> \\<le> c\"\n    using c[of 1] \\<alpha> by simp\n  finally have \"c \\<ge> 0\" .\n\n  have \"eventually (\\<lambda>s. s \\<in> complex_cone' \\<alpha> - {0}) F\"\n    unfolding F_def by (auto simp: eventually_principal)\n  hence \"eventually (\\<lambda>s. norm (stirling_integral m s) \\<le>\n                     c * norm (1 / s ^ m)) F\"\n    by eventually_elim (use c in \\<open>simp add: norm_divide norm_power\\<close>)\n  thus \"stirling_integral m \\<in> O[F](\\<lambda>s. 1 / s ^ m)\"\n    by (intro bigoI[of _ c]) auto\nqed\n\nend\n\ntext \\<open>\n  The following is a more explicit statement of this:\n\\<close>\ntheorem ln_Gamma_complex_asymptotics_explicit:\n  fixes m :: nat and \\<alpha> :: real\n  assumes \"m > 0\" and \"\\<alpha> \\<in> {0<..<pi}\"\n  obtains C :: real and R :: \"complex \\<Rightarrow> complex\"\n  where \"\\<forall>s::complex. s \\<notin> \\<real>\\<^sub>\\<le>\\<^sub>0 \\<longrightarrow>\n               ln_Gamma s = (s - 1/2) * ln s - s + ln (2 * pi) / 2 +\n                            (\\<Sum>k=1..<m. bernoulli (k+1) / (k * (k+1) * s ^ k)) - R s\"\n    and \"\\<forall>s. s \\<noteq> 0 \\<and> \\<bar>Arg s\\<bar> \\<le> \\<alpha> \\<longrightarrow> norm (R s) \\<le> C / norm s ^ m\"    \nproof -\n  obtain c where c: \"\\<And>s. s \\<in> complex_cone' \\<alpha> - {0} \\<Longrightarrow> norm (stirling_integral m s) \\<le> c / norm s ^ m\"\n    using stirling_integral_bound'[OF assms] by blast\n  have \"0 \\<le> norm (stirling_integral m 1 :: complex)\"\n    by simp\n  also have \"\\<dots> \\<le> c\"\n    using c[of 1] assms by simp\n  finally have \"c \\<ge> 0\" .\n  define R where \"R = (\\<lambda>s::complex. stirling_integral m s / of_nat m)\"\n  show ?thesis\n  proof (rule that)\n    from ln_Gamma_stirling_complex[of _ m] assms show\n           \"\\<forall>s::complex. s \\<notin> \\<real>\\<^sub>\\<le>\\<^sub>0 \\<longrightarrow>\n               ln_Gamma s = (s - 1 / 2) * ln s - s + ln (2 * pi) / 2 +\n               (\\<Sum>k=1..<m. bernoulli (k+1) / (k * (k+1) * s ^ k)) - R s\"\n      by (auto simp add: R_def algebra_simps)\n    show \"\\<forall>s. s \\<noteq> 0 \\<and> \\<bar>Arg s\\<bar> \\<le> \\<alpha> \\<longrightarrow> cmod (R s) \\<le> c / real m / cmod s ^ m\"\n    proof (safe, goal_cases)\n      case (1 s)\n      show ?case\n        using 1 c[of s] assms\n        by (auto simp: complex_cone_altdef abs_le_iff R_def norm_divide field_simps)\n    qed\n  qed\nqed\n\n\ntext \\<open>\n  Lastly, we can also derive the asymptotics of $\\Gamma$ itself:\n  \\[\\Gamma(z) \\sim \\sqrt{2\\pi / z} \\left(\\frac{z}{e}\\right)^z\\]\n  uniformly for $|z|\\to\\infty$ within the cone $\\text{Arg}(z) \\leq \\alpha$ for $\\alpha\\in(0,\\pi)$:\n\\<close>\n\ncontext\n  fixes F and \\<alpha>\n  assumes \\<alpha>: \"\\<alpha> \\<in> {0<..<pi}\"\n  defines \"F \\<equiv> inf at_infinity (principal (complex_cone' \\<alpha>))\"\nbegin\n\nlemma Gamma_complex_asymp_equiv:\n  \"Gamma \\<sim>[F] (\\<lambda>s. sqrt (2 * pi) * (s / exp 1) powr s / s powr (1 / 2))\"\nproof -\n  define I :: \"complex \\<Rightarrow> complex\" where \"I = stirling_integral 1\"\n  have \"eventually (\\<lambda>s. s \\<in> complex_cone' \\<alpha>) F\"\n    by (auto simp: eventually_inf_principal F_def)\n  moreover have \"eventually (\\<lambda>s. s \\<noteq> 0) F\"\n    unfolding F_def eventually_inf_principal\n    using eventually_not_equal_at_infinity by eventually_elim auto\n  ultimately have \"eventually (\\<lambda>s. Gamma s =\n                     sqrt (2 * pi) * (s / exp 1) powr s / s powr (1 / 2) / exp (I s)) F\"\n  proof eventually_elim\n    case (elim s)\n    from elim have s': \"s \\<notin> \\<real>\\<^sub>\\<le>\\<^sub>0\"\n      using complex_cone_inter_nonpos_Reals[of \"-\\<alpha>\" \\<alpha>] \\<alpha> by auto\n    from elim have [simp]: \"s \\<noteq> 0\" by auto      \n    from s' have \"Gamma s = exp (ln_Gamma s)\"\n      unfolding Gamma_complex_altdef using nonpos_Ints_subset_nonpos_Reals by auto\n    also from s' have \"ln_Gamma s = (s-1/2) * Ln s - s + complex_of_real (ln (2 * pi) / 2) - I s\"\n      by (subst ln_Gamma_stirling_complex[of _ 1]) (simp_all add: exp_add exp_diff I_def)\n    also have \"exp \\<dots> = exp ((s - 1 / 2) * Ln s) / exp s *\n                        exp (complex_of_real (ln (2 * pi) / 2)) / exp (I s)\"\n      unfolding exp_diff exp_add by (simp add: exp_diff exp_add)\n    also have \"exp ((s - 1 / 2) * Ln s) = s powr (s - 1 / 2)\"\n      by (simp add: powr_def)\n    also have \"exp (complex_of_real (ln (2 * pi) / 2)) = sqrt (2 * pi)\"\n      by (subst exp_of_real) (auto simp: powr_def simp flip: powr_half_sqrt)\n    also have \"exp s = exp 1 powr s\"\n      by (simp add: powr_def)\n    also have \"s powr (s - 1 / 2) / exp 1 powr s = (s powr s / exp 1 powr s) / s powr (1/2)\"\n      by (subst powr_diff) auto\n    also have *: \"Ln (s / exp 1) = Ln s - 1\"\n      using Ln_divide_of_real[of \"exp 1\" s] by (simp flip: exp_of_real)\n    hence \"s powr s / exp 1 powr s = (s / exp 1) powr s\"\n      unfolding powr_def by (subst *) (auto simp: exp_diff field_simps)\n    finally show \"Gamma s = sqrt (2 * pi) * (s / exp 1) powr s / s powr (1 / 2) / exp (I s)\"\n      by (simp add: algebra_simps)\n  qed\n  hence \"Gamma \\<sim>[F] (\\<lambda>s. sqrt (2 * pi) * (s / exp 1) powr s / s powr (1 / 2) / exp (I s))\"\n    by (rule asymp_equiv_refl_ev)\n  also have \"\\<dots> \\<sim>[F] (\\<lambda>s. sqrt (2 * pi) * (s / exp 1) powr s / s powr (1 / 2) / 1)\"\n  proof (intro asymp_equiv_intros)\n    have \"F \\<le> principal (complex_cone' \\<alpha> - {0})\"\n      unfolding le_principal F_def eventually_inf_principal\n      using eventually_not_equal_at_infinity by eventually_elim auto\n    moreover have \"I \\<in> O[principal (complex_cone' \\<alpha> - {0})](\\<lambda>s. 1 / s)\"\n      using stirling_integral_bigo[of \\<alpha> 1] \\<alpha> unfolding F_def by (simp add: I_def)\n    ultimately have \"I \\<in> O[F](\\<lambda>s. 1 / s)\"\n      by (rule landau_o.big.filter_mono)\n    also have \"(\\<lambda>s. 1 / s) \\<in> o[F](\\<lambda>s. 1)\"\n    proof (rule landau_o.smallI)\n      fix c :: real\n      assume c: \"c > 0\"\n      hence \"eventually (\\<lambda>z::complex. norm z \\<ge> 1 / c) at_infinity\"\n        by (auto simp: eventually_at_infinity)\n      moreover have \"eventually (\\<lambda>z::complex. z \\<noteq> 0) at_infinity\"\n        by (rule eventually_not_equal_at_infinity)\n      ultimately show \"eventually (\\<lambda>z::complex. norm (1 / z) \\<le> c * norm (1 :: complex)) F\"\n        unfolding F_def eventually_inf_principal\n        by eventually_elim (use \\<open>c > 0\\<close> in \\<open>auto simp: norm_divide field_simps\\<close>)\n    qed\n    finally have \"I \\<in> o[F](\\<lambda>s. 1)\" .\n    from smalloD_tendsto[OF this] have [tendsto_intros]: \"(I \\<longlongrightarrow> 0) F\"\n      by simp\n    show \"(\\<lambda>x. exp (I x)) \\<sim>[F] (\\<lambda>x. 1)\"\n      by (rule asymp_equivI' tendsto_eq_intros refl | simp)+\n  qed\n  finally show ?thesis by simp\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/Stirling_Formula/Gamma_Asymptotics.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8376199552262967, "lm_q2_score": 0.861538211208597, "lm_q1q2_score": 0.7216415978982887}}
{"text": "(*  Title:       Instances of Schneider's generalized protocol of clock synchronization\n    Author:      Dami\u00e1n Barsotti <damian at hal.famaf.unc.edu.ar>, 2006\n    Maintainer:  Dami\u00e1n Barsotti <damian at hal.famaf.unc.edu.ar>\n*)\n\nheader {* Interactive Convergence Algorithms (ICA) *}\n\ntheory ICAInstance imports Complex_Main begin\n\ntext {* This algorithm is presented in \\cite{lamport_cs}. *}\n\ntext {* A proof of the three properties can be found in\n\\cite{shankar92mechanical}. *}\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 fix value that is used to discard the\nprocesses whose clocks differ more than this amount from the own one\n(see \\cite{shankar92mechanical}). The defined constants must satisfy\nthis axiom (if $np = 0$ we have a division by cero in the definition\nof the convergence function).  *}\n\naxiomatization\n  np :: nat      -- \"Number of processes\" and\n  \\<Delta> :: Clocktime -- \"Fix value to discard processes\" where\n  constants_ax: \"0 <= \\<Delta> \\<and> np > 0\" \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 ``Egocentric Average''\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 an auxiliary function. It takes a function of\nclock readings and two processes, and return de reading of the second\nprocess if the difference of the readings is grater than @{term \\<Delta>},\notherwise it returns the reading of the first one. *}\n\ndefinition\n  fiX :: \"[(process \\<Rightarrow> Clocktime), process, process] \\<Rightarrow> Clocktime\" where\n  \"fiX f p l = (if \\<bar>f p - f l\\<bar> <= \\<Delta> then (f l) else (f p))\"\n\ntext {* And finally the convergence function. This is defined with the\nbuiltin generalized summation over a set constructor of Isabelle.\nAlso we had to use the overloaded @{term real} function to typecast de\nnumber @{term np}. *}\n\ndefinition\n  (* The averaging function to calculate clock adjustment *)\n  cfni :: \"[process, (process \\<Rightarrow> Clocktime)] \\<Rightarrow> Clocktime\" where\n  \"cfni p f = (\\<Sum> l\\<in>{..<np}. fiX f p l) / (real np)\"\n\nsubsection {* Translation Invariance property.*}\n\ntext {*We first need to prove this auxiliary lemma.*}\n\nlemma trans_inv': \n\"(\\<Sum> l\\<in>{..<np'}. fiX (\\<lambda> y. f y + x) p l) = \n        (\\<Sum> l\\<in>{..<np'}. fiX f p l) + real np' * x\"\napply (induct_tac np')\napply (auto simp add: cfni_def  fiX_def real_of_nat_Suc \n       distrib_right lessThan_Suc)\ndone\n\ntheorem trans_inv: \n\"\\<forall> p f x . cfni p (\\<lambda> y. f y + x) = cfni p f + x\"\napply (auto simp add: cfni_def trans_inv' distrib_right \n       divide_inverse  constants_ax)\ndone\n\nsubsection {* Precision Enhancement property *}\n\ntext {* An informal proof of this theorem can be found in\n\\cite{shankar92mechanical} *}\n\nsubsubsection {* Auxiliary lemmas *}\n\nlemma finitC:\n  \"C \\<subseteq> PR \\<Longrightarrow> finite C\"\nproof-\n  assume \"C \\<subseteq> PR\"\n  thus ?thesis using finite_subset by auto\nqed\n\nlemma finitnpC:\n  \"finite (PR - C)\"\nproof-\n  show ?thesis  using finite_Diff by auto\nqed\n \n\ntext {* The next lemmas are about arithmetic properties of the\ngeneralized summation over a set constructor. *}\n\nlemma sum_abs_triangle_ineq:\n\"finite S \\<Longrightarrow>\n  \\<bar>\\<Sum>l\\<in>S. (f::'a \\<Rightarrow> 'b::linordered_idom) l\\<bar> <= (\\<Sum>l\\<in>S. \\<bar>f l\\<bar>)\"\n  (is \"... \\<Longrightarrow> ?P S\")\n  by (rule setsum_abs)\n\nlemma sum_le:\n  \"\\<lbrakk>finite S ; \\<forall> r\\<in>S. f r <= b \\<rbrakk>\n  \\<Longrightarrow>\n  (\\<Sum>l\\<in>S. f l) <= real (card S) * b\"\n  (is \"\\<lbrakk> finite S ; \\<forall> r\\<in>S. f r <= b \\<rbrakk> \\<Longrightarrow> ?P S\")\nproof(induct S rule: finite_induct)\n  show \"?P {}\" by simp \nnext\n  fix F x \n  assume  finit: \"finite F\" and xnotinF: \"x \\<notin> F\" and\n          HI1: \"\\<forall>r\\<in>F. f r \\<le> b \\<Longrightarrow> setsum f F \\<le> real (card F) * b\"\n          and HI2: \"\\<forall>r\\<in>insert x F. f r \\<le> b\"\n  from HI1 HI2 and finit and xnotinF\n  have \"setsum f (insert x F) <= b + real (card F) * b\"\n    by auto\n  also \n  have \"... = real (Suc (card  F)) * b\"\n    by (simp add: distrib_right  real_of_nat_Suc)\n  also \n  from   finit xnotinF have \"...= real (card (insert x F)) * b\"\n    by simp\n  finally\n  show \"?P (insert x F)\" .\nqed\n\nlemma sum_np_eq:\nassumes \n  hC: \"C \\<subseteq> PR\"\nshows \n  \"(\\<Sum>l\\<in>{..<np}. f l) = (\\<Sum>l\\<in>C. f l) + (\\<Sum>l\\<in>({..<np}-C). f l)\"\nproof-\n  note finitC[where C=C]\n  moreover\n  note finitnpC[where C=C]\n  moreover\n  have \"C \\<inter> ({..<np}-C) = {}\" by auto\n  moreover\n  from hC have \"C \\<union> ({..<np}-C) = {..<np}\" by auto\n  ultimately\n  show ?thesis\n    using setsum.union_disjoint[where A=C and B=\"{..<np} - C\"]\n    by auto\nqed\n \nlemma abs_sum_np_ineq:\nassumes \n  hC: \"C \\<subseteq> PR\"\nshows \n  \"\\<bar>(\\<Sum>l\\<in>{..<np}. (f::nat \\<Rightarrow> real) l)\\<bar> <=  \n     (\\<Sum>l\\<in>C. \\<bar>f l\\<bar>) + (\\<Sum>l\\<in>({..<np}-C). \\<bar>f l\\<bar>)\"\n    (is \"?abs_sum <= ?sumC + ?sumnpC\")\nproof-\n  from hC and sum_np_eq[where f=f] \n  have \"?abs_sum = \\<bar>(\\<Sum>l\\<in>C. f l) + (\\<Sum>l\\<in>({..<np}-C). f l)\\<bar>\" \n    (is \"?abs_sum = \\<bar>?sumC' + ?sumnpC'\\<bar>\")\n    by simp\n  also\n  from abs_triangle_ineq\n  have \"...<= \\<bar>?sumC'\\<bar> + \\<bar>?sumnpC'\\<bar>\" .\n  also\n  have \"... <=  ?sumC + ?sumnpC \"\n  proof-\n    from hC finitC sum_abs_triangle_ineq \n    have \"\\<bar>?sumC'\\<bar> <= ?sumC\" by blast\n    moreover\n    from finitnpC and\n           sum_abs_triangle_ineq[where f=f and S=\"PR-C\"]  \n    have \"\\<bar>?sumnpC'\\<bar> <= ?sumnpC\" \n      by force\n    ultimately\n    show ?thesis by arith\n  qed\n  finally\n  show ?thesis .\nqed\n\ntext {* The next lemmas are about the existence of bounds that are\nnecesary in order to prove the Precicion Enhancement theorem. *}\n  \nlemma fiX_ubound:\n  \"fiX f p l <= f p + \\<Delta>\"\nproof(cases \"\\<bar>f p - f l\\<bar> \\<le> \\<Delta>\")\n  assume asm: \"\\<bar>f p - f l\\<bar> \\<le> \\<Delta>\" \n  hence \"fiX f p l = f l\" by (simp add: fiX_def) \n  also\n  from asm have \"f l <= f p + \\<Delta>\" by arith\n  finally\n  show ?thesis by arith\nnext\n  assume asm: \"\\<not>\\<bar>f p - f l\\<bar> \\<le> \\<Delta>\" \n  hence \"fiX f p l = f p\" by (simp add: fiX_def) \n  also\n  from asm and  constants_ax have \"f p <= f p + \\<Delta>\" by arith\n  finally\n  show ?thesis by arith\nqed\n\nlemma fiX_lbound:\n  \"f p - \\<Delta> <= fiX f p l\"\nproof(cases \"\\<bar>f p - f l\\<bar> \\<le> \\<Delta>\")\n  assume asm: \"\\<bar>f p - f l\\<bar> \\<le> \\<Delta>\" \n  hence \"fiX f p l = f l\" by (simp add: fiX_def) \n  also\n  from asm have \"f p - \\<Delta> <= f l\" by arith\n  finally\n  show ?thesis by arith\nnext\n  assume asm: \"\\<not>\\<bar>f p - f l\\<bar> \\<le> \\<Delta>\" \n  with  constants_ax have \"f p - \\<Delta> <= f p\" by arith\n  also\n  from asm have \"f p = fiX f p l\" by (simp add: fiX_def) \n  finally\n  show ?thesis by arith\nqed\n\nlemma abs_fiX_bound: \"\\<bar>fiX f p l - f p \\<bar> <= \\<Delta>\"\nproof-\n(*\nfrom constants_ax and fiX_lbound and fiX_ubound show ?thesis by arith\n*)\nhave \"f p - \\<Delta> <= fiX f p l \\<and> fiX f p l <= f p + \\<Delta> \\<longrightarrow> ?thesis\"\nby arith\nwith fiX_lbound  fiX_ubound show ?thesis by blast\nqed\n\n\n\nlemma abs_dif_fiX_bound_C_aux1:\nassumes \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\" and\n  hrC: \"r\\<in>C\" \nshows\n  \"\\<bar>fiX f p r - fiX g q r\\<bar> <= x + y\"\nproof(cases \"\\<bar>f p - f r\\<bar> \\<le> \\<Delta>\")\n  case True \n  note outer_IH = True \n  show ?thesis\n  proof(cases \"\\<bar>g q - g r\\<bar> \\<le> \\<Delta>\")\n    case True\n    show ?thesis\n    proof -\n      from hpC and hby1 have \"0<=y\" by force\n      with hrC and hbx have \"\\<bar> f r - g r \\<bar> <= x + y\" by auto\n      with outer_IH and True show ?thesis \n        by (auto simp add: fiX_def)\n    qed\n  next\n    case False \n    show ?thesis\n    proof -\n      from outer_IH and False \n      have \"\\<bar>fiX f p r - fiX g q r\\<bar> = \\<bar>f r - g q\\<bar>\" \n        by  (auto simp add: fiX_def)\n      also\n      have \"... = \\<bar> f r - f q + f q - g q \\<bar>\" by simp\n      also\n      have \"... <= \\<bar> f r - f q \\<bar> + \\<bar> f q - g q \\<bar>\" \n        by arith\n      also\n      from hbx hby1 hpC hqC hrC have \"... <= x + y\" by force\n      finally\n      show ?thesis .\n    qed\n  qed\nnext\n  case False \n  note outer_IH = False\n  show ?thesis\n  proof(cases \"\\<bar>g q - g r\\<bar> \\<le> \\<Delta>\")\n    case True\n    show ?thesis\n    proof -\n      from outer_IH and True \n      have \"\\<bar>fiX f p r - fiX g q r\\<bar> = \\<bar>f p - g r\\<bar>\" \n        by  (auto simp add: fiX_def)\n      also\n      have \"... = \\<bar> f p - f r + f r - g r \\<bar>\" by simp\n      also\n      from abs_triangle_ineq[where a = \"f p - f r\" and \n                                   b = \"f r - g r\"]\n      have \"... <= \\<bar> f p - f r \\<bar> + \\<bar> f r - g r \\<bar>\" \n        by auto\n      also\n      from hbx hby1 hpC hrC have \"... <= x + y\" by force\n      finally\n      show ?thesis .\n    qed\n  next\n    case False \n    show ?thesis\n    proof -\n      from outer_IH and False \n      have \"\\<bar>fiX f p r - fiX g q r\\<bar> = \\<bar>f p - g q\\<bar>\" \n        by  (auto simp add: fiX_def)\n      also\n      have \"... = \\<bar> f p - f q + f q - g q \\<bar>\" by simp\n      also\n      from abs_triangle_ineq[where a = \"f p - f q\" and \n                                   b = \"f q - g q\"]\n      have \"... <= \\<bar> f p - f q \\<bar> + \\<bar> f q - g q \\<bar>\" \n        by auto\n      also\n      from hbx hby1 hpC hqC have \"... <= x + y\" by force\n      finally\n      show ?thesis .\n    qed\n  qed\nqed\n\nlemma abs_dif_fiX_bound_C_aux2:\nassumes \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\" and\n  hrC: \"r\\<in>C\" \nshows\n  \"y <= \\<Delta> \\<longrightarrow> \\<bar>fiX f p r - fiX g q r\\<bar> <= x\"\nproof\n  assume hyd: \"y<=\\<Delta>\"\n  show \"\\<bar>fiX f p r - fiX g q r\\<bar> <= x\" \n  proof-\n    from hpC and hrC and hby1 and hyd have \"\\<bar>f p - f r\\<bar> \\<le> \\<Delta>\" \n      by force\n    moreover\n    from hqC and hrC and hby2 and hyd have \"\\<bar>g q - g r\\<bar> \\<le> \\<Delta>\"\n      by force\n    moreover\n    from hrC and hbx have \"\\<bar> f r - g r \\<bar> <= x \" by auto\n    ultimately\n    show ?thesis \n      by (auto simp add: fiX_def)\n  qed\nqed\n\nlemma abs_dif_fiX_bound_C:\nassumes \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\" and\n  hrC: \"r\\<in>C\" \nshows\n  \"\\<bar>fiX f p r - fiX g q r\\<bar> <= \n                     x + (if (y <= \\<Delta>) then 0 else y)\"\nproof (cases \"y <= \\<Delta>\")\n  case True \n  with abs_dif_fiX_bound_C_aux2 and\n    hbx and hby1 and hby2 and hpC and hqC and hrC \n  have \"\\<bar>fiX f p r - fiX g q r\\<bar> <= x \" by blast\n  with True show \"?thesis\" by simp\nnext\n  case False\n  with abs_dif_fiX_bound_C_aux1 and\n    hbx and hby1 and hby2 and hpC and hqC and hrC \n  have \"\\<bar>fiX f p r - fiX g q r\\<bar> <= x + y\" by blast\n  with False show \"?thesis\" by simp\nqed\n\nsubsubsection {* Main theorem *}\n\ntheorem prec_enh:\nassumes \n  hC: \"C \\<subseteq> PR\" 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> cfni p f - cfni q g \\<bar> <= \n  (real (card C) * (x + (if (y <= \\<Delta>) then 0 else y)) +\n    real (card ({..<np} - C)) * (2 * \\<Delta> + x + y)) / real np\"\n       (is \"\\<bar> ?dif_div_np \\<bar> <= ?B\")  \nproof-\n  have \"\\<bar>(\\<Sum>l\\<in>{..<np}. fiX f p l ) - \n                    (\\<Sum>l\\<in>{..<np}. fiX g q l)\\<bar> = \n    \\<bar>(\\<Sum>l\\<in>{..<np}. fiX f p l -fiX g q l)\\<bar>\"\n    (is \"\\<bar>?dif\\<bar> = \\<bar>?dif'\\<bar>\" )\n    by (simp add: setsum_subtractf)\n  also\n  from abs_sum_np_ineq hC\n  have \" ... <=\n      (\\<Sum>l\\<in>C. \\<bar>fiX f p l - fiX g q l\\<bar>) + \n      (\\<Sum>l\\<in>({..<np}-C). \\<bar>fiX f p l - fiX g q l\\<bar>)\"\n    (is \" \\<bar>?dif'\\<bar> <= ?boundC' + ?boundnpC'\" )\n    by simp\n  also\n  have \"... <= \n    real (card C) * (x + (if (y <= \\<Delta>) then 0 else y))+\n    real (card ({..<np}-C)) * (2 * \\<Delta> + x + y)\"\n    (is \" ... <= ?boundC + ?boundnpC\" )\n  proof-\n    have \" ?boundC' <= ?boundC\"\n    proof -\n      from abs_dif_fiX_bound_C and \n        hbx and hby1 and hby2 and  hpC and hqC  \n      have \"\\<forall>r\\<in>C. \n        \\<bar>fiX f p r - fiX g q r\\<bar> <= x + \n                         (if (y <= \\<Delta>) then 0 else y)\"\n        by blast     \n      thus ?thesis using sum_le[where S=C] and finitC[OF hC] \n        by force\n    qed\n    moreover\n    have \"?boundnpC' <= ?boundnpC\"\n    proof -\n      from abs_dif_fiX_bound and \n        hbx and hby1 and  hpC and hqC  \n      have \"\\<forall>r\\<in>({..<np}-C). \\<bar>fiX f p r - fiX g q r\\<bar> <= 2 * \\<Delta> + x + y\"\n        by blast\n      with finitnpC\n      show ?thesis\n        by (auto intro: sum_le)\n    qed\n    ultimately\n    show ?thesis by arith\n  qed\n  finally \n  have bound: \"\\<bar>?dif\\<bar> <= ?boundC + ?boundnpC\" .\n  thus ?thesis\n  proof-\n    have \"?dif_div_np = ?dif / real np\"\n      by (simp add: cfni_def divide_inverse algebra_simps)\n    hence \"\\<bar> cfni p f - cfni q g \\<bar> = \\<bar>?dif\\<bar> / real np\"\n      by force\n    with bound show \"?thesis\" \n      by (auto simp add: cfni_def divide_inverse constants_ax)\n  qed\nqed\n\nsubsection {* Accuracy Preservation property *}\n\ntext {* First, a simple lemma about an arithmetic propertie of the\ngeneralized summation over a set constructor. *}\n\nlemma sum_div_card:\n\"(\\<Sum>l\\<in>{..<n::nat}. f l) + q * real n= \n  (\\<Sum>l\\<in>{..<n}. f l + q )\"\n  (is \"?Sl n = ?Sr n\")\nproof (induct n)\ncase 0 thus ?case by simp\nnext\ncase (Suc n)\nthus ?case\n  by (auto simp: real_of_nat_Suc distrib_left lessThan_Suc) \nqed\n\ntext {* Next, some lemmas about bounds that are used in the proof of Accuracy Preservation *}\n\nlemma bound_aux_C:\nassumes\n  hby: \"\\<forall> l\\<in>C. \\<forall> m\\<in>C. \\<bar>f l - f m\\<bar> <= x\" and\n  hpC: \"p\\<in>C\" and\n  hqC: \"q\\<in>C\" and\n  hrC: \"r\\<in>C\" \nshows\n  \"\\<bar>fiX f p r - f q\\<bar> <= x\"\nproof (cases \"\\<bar> f p - f r \\<bar> <= \\<Delta>\")\n  case True\n  then have \"\\<bar>fiX f p r - f q\\<bar> = \\<bar> f r - f q \\<bar>\" \n    by (simp add: fiX_def)\n  also\n  from hby hqC hrC have \"... <= x\" by blast\n  finally \n  show ?thesis .\nnext\n  case False\n  then have \"\\<bar>fiX f p r - f q\\<bar> = \\<bar> f p - f q \\<bar>\" \n    by (simp add: fiX_def)\n  also\n  from hby hpC hqC have \"... <= x\" by blast\n  finally \n  show ?thesis .\nqed\n\nlemma bound_aux:\nassumes\n  hby: \"\\<forall> l\\<in>C. \\<forall> m\\<in>C. \\<bar>f l - f m\\<bar> <= x\" and\n  hpC: \"p\\<in>C\" and\n  hqC: \"q\\<in>C\" \nshows\n  \"\\<bar>fiX f p r - f q\\<bar> <= x + \\<Delta>\"\nproof (cases \"\\<bar> f p - f r \\<bar> <= \\<Delta>\")\n  case True\n  then have \"\\<bar>fiX f p r - f q\\<bar> = \\<bar> f r - f q \\<bar>\" \n    by (simp add: fiX_def)\n  also\n  have \"... = \\<bar> (f r - f p) + (f p - f q) \\<bar>\" \n    by arith\n  also\n  have \"... <= \\<bar> f p - f r \\<bar> + \\<bar> f p - f q \\<bar>\" \n    by arith\n  also\n  from True have \"... <= \\<Delta> + \\<bar> f p - f q \\<bar>\" by arith\n  also\n  from hby hpC hqC have \"... <= \\<Delta> + x\" by simp\n  finally \n  show ?thesis by simp\nnext\n  case False\n  then have \"\\<bar>fiX f p r - f q\\<bar> = \\<bar> f p - f q \\<bar>\" \n    by (simp add: fiX_def)\n  also\n  from hby hpC hqC have \"... <= x\" by blast\n  finally \n  show ?thesis using constants_ax by arith\nqed\n\nsubsubsection {* Main theorem *}\n\nlemma accur_pres:\nassumes \n  hC: \"C \\<subseteq> PR\" and\n  hby: \"\\<forall> l\\<in>C. \\<forall> m\\<in>C. \\<bar>f l - f m\\<bar> <= x\" and\n  hpC: \"p\\<in>C\" and\n  hqC: \"q\\<in>C\" \nshows \"\\<bar> cfni p f - f q \\<bar> <= \n  (real (card C) * x + real (card ({..<np} - C)) * (x + \\<Delta>))/\n                  real np\"\n  (is \"?abs1 <= (?bC + ?bnpC)/real np\")\nproof-\nfrom abs_sum_np_ineq and hC have \n  \"\\<bar>\\<Sum>l\\<in>{..<np}. fiX f p l  - f q \\<bar> <= \n    (\\<Sum>l\\<in>C. \\<bar> fiX f p l  - f q \\<bar>) + \n            (\\<Sum>l\\<in>({..<np}-C). \\<bar> fiX f p l  - f q \\<bar>)\" \n  by simp\nalso \nhave \n  \"... <= real (card C) * x + \n            real (card ({..<np} - C)) * (x + \\<Delta>)\"\n  proof-\n    have \"(\\<Sum>l\\<in>C. \\<bar> fiX f p l  - f q \\<bar>) <= \n                    real (card C) * x\"\n    proof-\n      from bound_aux_C and \n        hby and  hpC and hqC  \n      have \"\\<forall>r\\<in>C. \n        \\<bar>fiX f p r - f q\\<bar> <= x\"\n        by blast     \n      thus ?thesis using sum_le[where S=C] and finitC[OF hC] \n        by force\n    qed\n    moreover\n    have \" (\\<Sum>l\\<in>({..<np}-C). \\<bar> fiX f p l  - f q \\<bar>) <= \n                real (card ({..<np} - C)) * (x + \\<Delta>)\"\n    proof -\n      from bound_aux and \n        hby and  hpC and hqC  \n      have \"\\<forall>r\\<in>({..<np}-C). \n        \\<bar>fiX f p r - f q\\<bar> <= x + \\<Delta>\"\n        by blast\n      thus ?thesis using sum_le[where S=\"{..<np}-C\"] \n        and finitnpC \n        by force\n    qed\n    ultimately\n    show ?thesis by arith\n  qed\n  finally \n  have bound: \"\\<bar>\\<Sum>l\\<in>{..<np}. fiX f p l - f q\\<bar>\n  \\<le> real (card C) * x + real (card ({..<np} - C)) * (x + \\<Delta>)\"\n    .\n  thus \n    ?thesis\n  proof-\n    from constants_ax have\n      res: \"inverse (real np) * real np = 1\" \n      by auto\n    have\n      \"(cfni p f - f q) * real np = \n      (\\<Sum>l\\<in>{..<np}. fiX f p l) * real np / real np - f q * real np\"\n      by (simp add: cfni_def algebra_simps)\n    also \n    have \"... = \n      (\\<Sum>l\\<in>{..<np}. fiX f p l) - f q * real np\"\n      by simp\n    also\n    from sum_div_card[where f=\"fiX f p\" and n=np and q=\"- f q\"]\n    have \"... = (\\<Sum>l\\<in>{..<np}. fiX f p l - f q)\"\n      by simp\n    finally\n    have \n      \"(cfni p f - f q) * real np = (\\<Sum>l\\<in>{..<np}. fiX f p l - f q)\"\n      .\n-- cambia\n    hence\n      \"(cfni p f - f q) * real np / real np = \n      (\\<Sum>l\\<in>{..<np}. fiX f p l - f q)/ real np\"\n      by auto\n    with constants_ax have  \n      \"(cfni p f - f q) = \n      (\\<Sum>l\\<in>{..<np}. fiX f p l - f q) / real np\"\n    by simp\n    hence \"\\<bar> cfni p f - f q \\<bar> = \n      \\<bar>(\\<Sum>l\\<in>{..<np}. fiX f p l - f q) / real np \\<bar>\"\n      by simp\n    also have\n      \"... = \\<bar>(\\<Sum>l\\<in>{..<np}. fiX f p l - f q)\\<bar> / real np \"\n      by auto\n    finally have \"\\<bar> cfni p f - f q \\<bar> = \n      \\<bar>(\\<Sum>l\\<in>{..<np}. fiX f p l - f q)\\<bar> / real np \"\n      .\n    with bound show \"?thesis\" \n      by (auto simp add: cfni_def divide_inverse constants_ax)\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/ICAInstance.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199552262967, "lm_q2_score": 0.8615382058759129, "lm_q1q2_score": 0.7216415934315262}}
{"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.*)\n  theory TIP_prop_50\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 count :: \"Nat => Nat list => Nat\" where\n  \"count y (nil2) = Z\"\n| \"count y (cons2 z2 xs) =\n     (if x y z2 then S (count y xs) else count y xs)\"\n\nfun t2 :: \"Nat => Nat => bool\" where\n  \"t2 (Z) z = True\"\n| \"t2 (S z2) (Z) = False\"\n| \"t2 (S z2) (S x2) = t2 z2 x2\"\n\nfun insert :: \"Nat => Nat list => Nat list\" where\n  \"insert y (nil2) = cons2 y (nil2)\"\n| \"insert y (cons2 z2 xs) =\n     (if t2 y z2 then cons2 y (cons2 z2 xs) else cons2 z2 (insert y xs))\"\n\nfun isort :: \"Nat list => Nat list\" where\n  \"isort (nil2) = nil2\"\n| \"isort (cons2 z xs) = insert z (isort xs)\"\n\ntheorem property0 :\n  \"((count y (isort z)) = (count y z))\"\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/Prod/Prod/TIP_prop_50.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942290328344, "lm_q2_score": 0.8104789086703224, "lm_q1q2_score": 0.7215646951420176}}
{"text": "(*  Title:      Sort.thy\n    Author:     Danijela Petrovi\\'c, Facylty of Mathematics, University of Belgrade *)\n\nheader {* Verification of Heap Sort *}\n\ntheory Heap\nimports RemoveMax\nbegin\n\nsubsection {* Defining tree and properties of heap *}\n\ndatatype 'a Tree = \"E\" | \"T\" 'a \"'a Tree\" \"'a Tree\"\n\ntext{*With {\\em E} is represented empty tree and with {\\em T\\ \\ \\ 'a\\ \\ \\ 'a\n  Tree\\ \\ \\ 'a Tree} is represented a node whose root element is of\ntype {\\em 'a} and its left and right branch is also a tree of\ntype {\\em 'a}. *}\n\nprimrec size :: \"'a Tree \\<Rightarrow> nat\" where\n  \"size E = 0\"\n| \"size (T v l r) = 1 + size l + size r\"\n\ntext{* Definition of the function that makes a multiset from the given tree: *}\n\nprimrec multiset where\n  \"multiset E = {#}\"\n| \"multiset (T v l r) = multiset l + {#v#} + multiset r\"\n\nprimrec val where\n \"val (T v _ _) = v\"\n\ntext{* Definition of the function that has the value {\\em True} if the tree is\nheap, otherwise it is {\\em False}: *}\n\nfun is_heap :: \"'a::linorder Tree \\<Rightarrow> bool\" where\n  \"is_heap E = True\"\n| \"is_heap (T v E E) = True\"\n| \"is_heap (T v E r) = (v \\<ge> val r \\<and> is_heap r)\"\n| \"is_heap (T v l E) = (v \\<ge> val l \\<and> is_heap l)\"\n| \"is_heap (T v l r) = (v \\<ge> val r \\<and> is_heap r \\<and> v \\<ge> val l \\<and> is_heap l)\"\n\nlemma heap_top_geq:\n  assumes \"a \\<in># multiset t\" \"is_heap t\"\n  shows \"val t \\<ge> a\"\nusing assms\nby (induct t rule: is_heap.induct)  (auto split: split_if_asm)\n\nlemma heap_top_max:\n  assumes \"t \\<noteq> E\" \"is_heap t\"\n  shows \"val t = Max (set_of (multiset t))\"\nproof (rule Max_eqI[symmetric])\n  fix y\n  assume \"y \\<in> set_of (multiset t)\"\n  thus \"y \\<le> val t\"\n    using heap_top_geq[of t y] `is_heap t`\n    by simp\nnext\n  show \"val t \\<in> set_of (multiset t)\"\n    using `t \\<noteq> E`\n    by (cases t) auto\nqed simp\n\ntext{* The next step is to define function {\\em remove\\_max}, but the\nquestion is weather implementation of {\\em remove\\_max} depends on\nimplementation of the functions {\\em is\\_heap} and {\\em multiset}. The\nanswer is negative. This suggests that another step of refinement\ncould be added before definition of function {\\em\n  remove\\_max}. Additionally, there are other reasons why this should\nbe done, for example, function {\\em remove\\_max} could be implemented\nin functional or in imperative manner.\n*}\n\nlocale Heap =  Collection empty is_empty of_list  multiset for \n  empty :: \"'b\" and \n  is_empty :: \"'b \\<Rightarrow> bool\" and \n  of_list :: \"'a::linorder list \\<Rightarrow> 'b\" and \n  multiset :: \"'b \\<Rightarrow> 'a::linorder multiset\" + \n  fixes as_tree :: \"'b \\<Rightarrow> 'a::linorder Tree\"\n  -- {* This function is not very important, but it is needed in order to avoide problems with types and to detect that observed object is a tree.*}\n  fixes remove_max :: \"'b \\<Rightarrow> 'a \\<times> 'b\"\n  assumes multiset: \"multiset l = Heap.multiset (as_tree l)\"\n  assumes is_heap_of_list: \"is_heap (as_tree (of_list i))\"\n  assumes as_tree_empty: \"as_tree t = E \\<longleftrightarrow> is_empty t\"\n  assumes remove_max_multiset': \n  \"\\<lbrakk>\\<not> is_empty l; (m, l') = remove_max l\\<rbrakk> \\<Longrightarrow> multiset l' + {#m#} = multiset l\"\n  assumes remove_max_is_heap: \n  \"\\<lbrakk>\\<not> is_empty l; is_heap (as_tree l); (m, l') = remove_max l\\<rbrakk> \\<Longrightarrow> \n  is_heap (as_tree l')\"\n  assumes remove_max_val: \n  \"\\<lbrakk> \\<not> is_empty t; (m, t') = remove_max t\\<rbrakk> \\<Longrightarrow> m = val (as_tree t)\"\n\ntext{* It is very easy to prove that locale {\\em Heap} is sublocale of locale {\\em RemoveMax} *}\n\nsublocale Heap < \n  RemoveMax empty is_empty of_list multiset remove_max \"\\<lambda> t. is_heap (as_tree t)\"\nproof\n  fix x\n  show \"is_heap (as_tree (of_list x))\"\n    by (rule is_heap_of_list)\nnext\n  fix l m l'\n  assume \"\\<not> is_empty l\" \"(m, l') = remove_max l\" \n  thus \"multiset l' + {#m#} = multiset l\"\n    by (rule remove_max_multiset')\nnext\n  fix l m l'\n  assume \"\\<not> is_empty l\" \"is_heap (as_tree l)\" \"(m, l') = remove_max l\" \n  thus \"is_heap (as_tree l')\"\n    by (rule remove_max_is_heap)\nnext\n  fix l m l'\n  assume \"\\<not> is_empty l\" \"is_heap (as_tree l)\" \"(m, l') = remove_max l\" \n  thus \"m = Max (set l)\"\n    unfolding set_def\n    using heap_top_max[of \"as_tree l\"] remove_max_val[of l m l'] \n    using multiset is_empty_inj as_tree_empty\n    by auto\nqed\n\nprimrec in_tree where\n  \"in_tree v E = False\"\n| \"in_tree v (T v' l r) \\<longleftrightarrow> v = v' \\<or> in_tree v l \\<or> in_tree v r\"\n\nlemma is_heap_max:\n  assumes \"in_tree v t\" \"is_heap t\"\n  shows \"val t \\<ge> v\"\nusing assms\napply (induct t rule:is_heap.induct)\nby 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/Selection_Heap_Sort/Heap.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8902942261220292, "lm_q2_score": 0.8104789109591832, "lm_q1q2_score": 0.7215646948206311}}
{"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>Functions\\<close>\n\ntheory Relation_Algebra_Functions\n  imports Relation_Algebra_Vectors Relation_Algebra_Tests\nbegin\n\nsubsection \\<open>Functions\\<close>\n\ntext \\<open>This section collects the most important properties of functions. Most\nof them can be found in the books by Maddux and by Schmidt and Str\\\"ohlein. The\nmain material is on partial and total functions, injections, surjections,\nbijections.\\<close>\n\n(* Perhaps this material should be reorganised so that related theorems are\ngrouped together ... *)\n\ncontext relation_algebra\nbegin\n\ndefinition is_p_fun :: \"'a \\<Rightarrow> bool\"\n  where \"is_p_fun x \\<equiv> x\\<^sup>\\<smile> ; x \\<le> 1'\"\n\ndefinition is_total :: \"'a \\<Rightarrow> bool\"\n  where \"is_total x \\<equiv> 1' \\<le> x ; x\\<^sup>\\<smile>\"\n\ndefinition is_map :: \"'a \\<Rightarrow> bool\"\n  where \"is_map x \\<equiv> is_p_fun x \\<and> is_total x\"\n\ndefinition is_inj :: \"'a \\<Rightarrow> bool\"\n  where \"is_inj x \\<equiv> x ; x\\<^sup>\\<smile> \\<le> 1'\"\n\ndefinition is_sur :: \"'a \\<Rightarrow> bool\"\n  where \"is_sur x \\<equiv> 1' \\<le> x\\<^sup>\\<smile> ; x\"\n\ntext \\<open>We distinguish between partial and total bijections. As usual we call\nthe latter just bijections.\\<close>\n\ndefinition is_p_bij :: \"'a \\<Rightarrow> bool\"\n  where \"is_p_bij x \\<equiv> is_p_fun x \\<and> is_inj x \\<and> is_sur x\"\n\ndefinition is_bij :: \"'a \\<Rightarrow> bool\"\n  where \"is_bij x \\<equiv> is_map x \\<and> is_inj x \\<and> is_sur x\"\n\ntext \\<open>Our first set of lemmas relates the various concepts.\\<close>\n\nlemma inj_p_fun: \"is_inj x \\<longleftrightarrow> is_p_fun (x\\<^sup>\\<smile>)\"\nby (metis conv_invol is_inj_def is_p_fun_def)\n\nlemma p_fun_inj: \"is_p_fun x \\<longleftrightarrow> is_inj (x\\<^sup>\\<smile>)\"\nby (metis conv_invol inj_p_fun)\n\nlemma sur_total: \"is_sur x \\<longleftrightarrow> is_total (x\\<^sup>\\<smile>)\"\nby (metis conv_invol is_sur_def is_total_def)\n\nlemma total_sur: \"is_total x \\<longleftrightarrow> is_sur (x\\<^sup>\\<smile>)\"\nby (metis conv_invol sur_total)\n\nlemma bij_conv: \"is_bij x  \\<longleftrightarrow> is_bij (x\\<^sup>\\<smile>)\"\nby (metis is_bij_def inj_p_fun is_map_def p_fun_inj sur_total total_sur)\n\ntext \\<open>Next we show that tests are partial injections.\\<close>\n\nlemma test_is_inj_fun: \"is_test x \\<Longrightarrow> (is_p_fun x \\<and> is_inj x)\"\nby (metis is_inj_def p_fun_inj test_comp test_eq_conv is_test_def)\n\ntext \\<open>Next we show composition properties.\\<close>\n\nlemma p_fun_comp:\n  assumes \"is_p_fun x\" and \"is_p_fun y\"\n  shows \"is_p_fun (x ; y)\"\nproof (unfold is_p_fun_def)\n  have \"(x ; y)\\<^sup>\\<smile> ; x ; y = y\\<^sup>\\<smile> ; x\\<^sup>\\<smile> ; x ; y\"\n    by (metis conv_contrav mult.assoc)\n  also have \"... \\<le> y\\<^sup>\\<smile> ; y\"\n    by (metis assms(1) is_p_fun_def mult_double_iso mult.right_neutral mult.assoc)\n  finally show \"(x ; y)\\<^sup>\\<smile> ; (x ; y) \\<le> 1'\"\n    by (metis assms(2) order_trans is_p_fun_def mult.assoc)\nqed\n\nlemma p_fun_mult_var: \"x\\<^sup>\\<smile> ; x \\<le> 1' \\<Longrightarrow> (x \\<cdot> y)\\<^sup>\\<smile> ; (x \\<cdot> y) \\<le> 1'\"\nby (metis conv_times inf_le1 mult_isol_var order_trans)\n\nlemma inj_compose:\n  assumes \"is_inj x\" and \"is_inj y\"\n  shows \"is_inj (x ; y)\"\nby (metis assms conv_contrav inj_p_fun p_fun_comp)\n\nlemma inj_mult_var: \"x\\<^sup>\\<smile> ; x \\<le> 1' \\<Longrightarrow> (x \\<cdot> y)\\<^sup>\\<smile> ; (x \\<cdot> y) \\<le> 1'\"\nby (metis p_fun_mult_var)\n\nlemma total_comp:\n  assumes \"is_total x\" and \"is_total y\"\n  shows \"is_total (x ; y)\"\nby (metis assms inf_top_left le_iff_inf mult.assoc mult.right_neutral one_conv ra_2 is_total_def)\n\nlemma total_add_var: \"1' \\<le> x\\<^sup>\\<smile> ; x  \\<Longrightarrow> 1' \\<le> (x + y)\\<^sup>\\<smile> ; (x + y)\"\nby (metis local.conv_add local.inf.absorb2 local.inf.coboundedI1 local.join_interchange local.le_sup_iff)\n\nlemma sur_comp:\n  assumes \"is_sur x\" and \"is_sur y\"\n  shows \"is_sur (x ; y)\"\nby (metis assms conv_contrav sur_total total_comp)\n\nlemma sur_sum_var: \"1' \\<le> x\\<^sup>\\<smile> ; x \\<Longrightarrow> 1' \\<le> (x + y)\\<^sup>\\<smile> ; (x + y)\"\nby (metis total_add_var)\n\nlemma map_comp:\n  assumes \"is_map x\" and \"is_map y\"\n  shows \"is_map (x ; y)\"\nby (metis assms is_map_def p_fun_comp total_comp)\n\nlemma bij_comp:\n  assumes \"is_bij x\" and \"is_bij y\"\n  shows \"is_bij (x ; y)\"\nby (metis assms is_bij_def inj_compose map_comp sur_comp)\n\ntext \\<open>We now show that (partial) functions, unlike relations, distribute over\nmeets from the left.\\<close>\n\nlemma p_fun_distl: \"is_p_fun x \\<Longrightarrow> x ; (y \\<cdot> z) = x ; y \\<cdot> x ; z\"\nproof -\n  assume \"is_p_fun x\"\n  hence \"x ; (z \\<cdot> ((x\\<^sup>\\<smile> ; x) ; y)) \\<le> x ; (z \\<cdot> y)\"\n    by (metis is_p_fun_def inf_le1 le_infI le_infI2 mult_isol mult_isor mult_onel)\n  hence  \"x ; y \\<cdot> x ; z \\<le> x ; (z \\<cdot> y)\"\n    by (metis inf.commute mult.assoc order_trans modular_1_var)\n  thus \"x ; (y \\<cdot> z) = x ; y \\<cdot> x ; z\"\n    by (metis eq_iff inf.commute le_infI mult_subdistl)\nqed\n\nlemma map_distl: \"is_map x \\<Longrightarrow> x ; (y \\<cdot> z) = x ; y \\<cdot> x ; z\"\nby (metis is_map_def p_fun_distl)\n\ntext \\<open>Next we prove simple properties of functions which arise in equivalent\ndefinitions of those concepts.\\<close>\n\nlemma p_fun_zero: \"is_p_fun x \\<Longrightarrow> x ; y \\<cdot> x ; -y = 0\"\nby (metis annir inf_compl_bot p_fun_distl)\n\nlemma total_one: \"is_total x \\<Longrightarrow> x ; 1 = 1\"\nby (metis conv_invol conv_one inf_top_left le_iff_inf mult.right_neutral one_conv ra_2 is_total_def)\n\nlemma total_1: \"is_total x \\<Longrightarrow> (\\<forall>y. y ; x = 0 \\<longrightarrow> y = 0)\"\nby (metis conv_invol conv_zero inf_bot_left inf_top_left peirce total_one)\n\nlemma surj_one: \"is_sur x \\<Longrightarrow> 1 ; x = 1\"\nby (metis conv_contrav conv_invol conv_one sur_total total_one)\n\nlemma surj_1: \"is_sur x \\<Longrightarrow> (\\<forall>y. x ; y = 0 \\<longrightarrow> y = 0)\"\nby (metis comp_res_aux compl_bot_eq conv_contrav conv_one inf.commute inf_top_right surj_one)\n\nlemma bij_is_maprop:\n  assumes \"is_bij x\" and \"is_map x\"\n  shows \"x\\<^sup>\\<smile> ; x  = 1' \\<and> x ; x\\<^sup>\\<smile> = 1'\"\nby (metis assms is_bij_def eq_iff is_inj_def is_map_def is_p_fun_def is_sur_def is_total_def)\n\ntext\\<open>We now provide alternative definitions for functions. These can be found\nin Schmidt and Str\\\"ohlein's book.\\<close>\n\nlemma p_fun_def_var: \"is_p_fun x \\<longleftrightarrow> x ; -(1') \\<le> -x\"\nby (metis conv_galois_1 double_compl galois_aux inf.commute is_p_fun_def)\n\nlemma total_def_var_1: \"is_total x \\<longleftrightarrow> x ; 1 = 1\"\nby (metis inf_top_right le_iff_inf one_conv total_one is_total_def)\n\nlemma total_def_var_2: \"is_total x \\<longleftrightarrow> -x \\<le> x ; -(1')\"\nby (metis total_def_var_1 distrib_left sup_compl_top mult.right_neutral galois_aux3)\n\nlemma sur_def_var1: \"is_sur x \\<longleftrightarrow> 1 ; x = 1\"\nby (metis conv_contrav conv_one sur_total surj_one total_def_var_1)\n\nlemma sur_def_var2: \"is_sur x \\<longleftrightarrow> -x \\<le> -(1') ; x\"\nby (metis sur_total total_def_var_2 conv_compl conv_contrav conv_e conv_iso)\n\nlemma inj_def_var1: \"is_inj x \\<longleftrightarrow> -(1') ; x \\<le> -x\"\nby (metis conv_galois_2 double_compl galois_aux inf.commute is_inj_def)\n\nlemma is_maprop: \"is_map x \\<longleftrightarrow> x ; -(1') = -x\"\nby (metis eq_iff is_map_def p_fun_def_var total_def_var_2)\n\ntext \\<open>Finally we prove miscellaneous properties of functions.\\<close>\n\nlemma ss_422iii: \"is_p_fun y \\<Longrightarrow> (x \\<cdot> z ; y\\<^sup>\\<smile>) ; y = x ; y \\<cdot> z\"\n(* by (smt antisym comp_assoc inf_commute maddux_17 meet_iso mult_isol mult_oner mult_subdistr_var order_trans is_p_fun_def) *)\nproof (rule antisym)\n  assume \"is_p_fun y\"\n  show \"x ; y \\<cdot> z \\<le> (x \\<cdot> z ; y\\<^sup>\\<smile>) ; y\"\n    by (metis maddux_17)\n  have \"(x \\<cdot> z ; y\\<^sup>\\<smile>) ; y \\<le> x ; y \\<cdot> (z ; (y\\<^sup>\\<smile> ; y))\"\n    by (metis mult_subdistr_var mult.assoc)\n  also have \"\\<dots> \\<le> x ; y \\<cdot> z ; 1'\"\n    by (metis \\<open>is_p_fun y\\<close> inf_absorb2 inf_le1 le_infI le_infI2 mult_subdistl is_p_fun_def)\n  finally show \"(x \\<cdot> z ; y\\<^sup>\\<smile>) ; y \\<le> x ; y \\<cdot> z\"\n    by (metis mult.right_neutral)\nqed\n\nlemma p_fun_compl: \"is_p_fun x \\<Longrightarrow> x ; -y \\<le> -(x; y)\"\nby (metis annir galois_aux inf.commute inf_compl_bot p_fun_distl)\n\nlemma ss_422v: \"is_p_fun x \\<Longrightarrow> x ; -y = x ; 1 \\<cdot> -(x ; y)\"\nby (metis inf.commute inf_absorb2 inf_top_left maddux_23 p_fun_compl)\n\ntext \\<open>The next property is a Galois connection.\\<close>\n\nlemma ss43iii: \"is_map x \\<longleftrightarrow> (\\<forall>y. x ; -y = -(x ; y))\"\nby standard (metis inf_top_left is_map_def ss_422v total_one, metis is_maprop mult.right_neutral)\n\ntext \\<open>Next we prove a lemma from Schmidt and Str\\\"ohlein's book and some of\nits consequences. We show the proof in detail since the textbook proof uses\nTarski's rule which we omit.\\<close>\n\nlemma ss423: \"is_map x \\<Longrightarrow> y ; x \\<le> z \\<longleftrightarrow> y \\<le> z ; x\\<^sup>\\<smile>\"\nproof\n  assume \"is_map x\" and \"y ; x \\<le> z\"\n  hence \"y \\<le> y ; x ; x\\<^sup>\\<smile>\"\n    by (metis is_map_def mult_1_right mult.assoc mult_isol is_total_def)\n  thus \"y \\<le> z ; x\\<^sup>\\<smile>\"\n    by (metis \\<open>y ; x \\<le> z\\<close> mult_isor order_trans)\nnext\n  assume \"is_map x\" and \"y \\<le> z ; x\\<^sup>\\<smile>\"\n  hence \"y ; x \\<le> z ; x\\<^sup>\\<smile> ; x\"\n    by (metis mult_isor)\n  also have \"\\<dots> \\<le> z ; 1'\"\n    by (metis \\<open>is_map x\\<close> is_map_def mult.assoc mult_isol is_p_fun_def)\n  finally show \"y ; x \\<le> z\"\n    by (metis mult_1_right)\nqed\n\nlemma ss424i: \"is_total x \\<longleftrightarrow> (\\<forall>y. -(x ; y) \\<le> x ; -y)\"\nby (metis galois_aux3 distrib_left sup_compl_top total_def_var_1)\n\nlemma ss434ii: \"is_p_fun x \\<longleftrightarrow> (\\<forall>y. x ; -y \\<le> -(x ; y))\"\nby (metis mult.right_neutral p_fun_compl p_fun_def_var)\n\nlemma is_maprop1: \"is_map x \\<Longrightarrow> (y \\<le> x ; z ; x\\<^sup>\\<smile> \\<longleftrightarrow> y ; x \\<le> x ; z)\"\nby (metis ss423)\n\nlemma is_maprop2: \"is_map x \\<Longrightarrow> (y ; x \\<le> x ; z \\<longleftrightarrow> x\\<^sup>\\<smile> ; y; x \\<le> z)\"\nby standard (metis galois_aux2 inf_commute mult.assoc schroeder_1 ss43iii, metis conv_contrav conv_invol conv_iso mult.assoc ss423)\n\nlemma is_maprop3: \"is_map x \\<Longrightarrow> (x\\<^sup>\\<smile> ; y; x \\<le> z \\<longleftrightarrow> x\\<^sup>\\<smile> ; y \\<le> z ; x\\<^sup>\\<smile>)\"\nby (metis ss423)\n\nlemma p_fun_sur_id [simp]:\n  assumes \"is_p_fun x\" and \"is_sur x\"\n  shows \"x\\<^sup>\\<smile> ; x = 1'\"\nby (metis assms eq_iff is_p_fun_def is_sur_def)\n\nlemma total_inj_id [simp]:\n  assumes \"is_total x\" and \"is_inj x\"\n  shows \"x ; x\\<^sup>\\<smile> = 1'\"\nby (metis assms conv_invol inj_p_fun p_fun_sur_id sur_total)\n\nlemma bij_inv_1 [simp]: \"is_bij x \\<Longrightarrow> x ; x\\<^sup>\\<smile> = 1'\"\nby (metis bij_is_maprop is_bij_def)\n\nlemma bij_inv_2 [simp]: \"is_bij x \\<Longrightarrow> x\\<^sup>\\<smile> ; x = 1'\"\nby (metis bij_is_maprop is_bij_def)\n\nlemma bij_inv_comm: \"is_bij x \\<Longrightarrow> x ; x\\<^sup>\\<smile> = x\\<^sup>\\<smile> ; x\"\nby (metis bij_inv_1 bij_inv_2)\n\nlemma is_bijrop: \"is_bij x \\<Longrightarrow> (y = x ; z \\<longleftrightarrow> z = x\\<^sup>\\<smile> ; y)\"\nby (metis bij_inv_1 bij_inv_2 mult.assoc mult.left_neutral)\n\nlemma inj_map_monomorph: \"\\<lbrakk>is_inj x; is_map x\\<rbrakk> \\<Longrightarrow> (\\<forall>y z. y ; x = z ; x \\<longrightarrow> y = z)\"\nby (metis is_map_def mult.assoc mult.right_neutral total_inj_id)\n\nlemma sur_map_epimorph: \"\\<lbrakk>is_sur x; is_map x\\<rbrakk> \\<Longrightarrow> (\\<forall>y z. x ; y = x ; z \\<longrightarrow> y = z)\"\nby (metis eq_iff mult.assoc mult.left_neutral ss423 is_sur_def)\n\nsubsection \\<open>Points and Rectangles\\<close>\n\ntext \\<open>Finally here is a section on points and rectangles. This is only a\nbeginning.\\<close>\n\ndefinition is_point :: \"'a \\<Rightarrow> bool\"\n  where \"is_point x \\<equiv> is_vector x \\<and> is_inj x \\<and> x \\<noteq> 0\"\n\ndefinition is_rectangle :: \"'a \\<Rightarrow> bool\"\n  where \"is_rectangle x \\<equiv> x ; 1 ; x \\<le> x\"\n\nlemma rectangle_eq [simp]: \"is_rectangle x \\<longleftrightarrow> x ; 1 ; x = x\"\nby (metis conv_one dedekind eq_iff inf_top_left mult.assoc one_idem_mult is_rectangle_def)\n\nsubsection \\<open>Antidomain\\<close>\n\ntext\\<open>This section needs to be linked with domain semirings. We essentially\nprove the antidomain semiring axioms. Then we have the abstract properties at\nour disposition.\\<close>\n\ndefinition antidom :: \"'a \\<Rightarrow> 'a\" (\"a\")\n  where \"a x = 1' \\<cdot> (-(x ; 1))\"\n\ndefinition dom :: \"'a \\<Rightarrow> 'a\" (\"d\")\n  where \"d x = a (a x)\"\n\nlemma antidom_test_comp [simp]: \"a x = tc (x ; 1)\"\nby (metis antidom_def tc_def)\n\nlemma dom_def_aux: \"d x = 1' \\<cdot> x ; 1\"\nby (metis antidom_test_comp dom_def double_compl inf_top_left mult.left_neutral one_compl ra_1 tc_def)\n\nlemma dom_def_aux_var: \"d x = 1' \\<cdot> x ; x\\<^sup>\\<smile>\"\nby (metis dom_def_aux one_conv)\n\nlemma antidom_dom [simp]: \"a (d x) = a x\"\nby (metis antidom_test_comp dom_def_aux inf_top_left mult.left_neutral ra_1)\n\nlemma dom_antidom [simp]: \"d (a x) = a x\"\nby (metis antidom_dom dom_def)\n\nlemma dom_verystrict: \"d x = 0 \\<longleftrightarrow> x = 0\"\nusing dom_def_aux_var local.schroeder_2 by force\n\nlemma a_1 [simp]: \"a x ; x = 0\"\nby (metis antidom_test_comp galois_aux2 maddux_20 mult.left_neutral one_compl ra_1 tc_def)\n\nlemma a_2: \"a (x ; y) = a (x ; d y)\"\nby (metis antidom_test_comp dom_def_aux inf_top_left mult.assoc mult.left_neutral ra_1)\n\nlemma a_3 [simp]: \"a x + d x = 1'\"\nby (metis antidom_def aux4 dom_def_aux double_compl)\n\nlemma test_domain: \"x = d x \\<longleftrightarrow> x \\<le> 1'\"\napply standard\n apply (metis dom_def_aux inf_le1)\napply (metis dom_def_aux inf.commute mult.right_neutral test_1 is_test_def)\ndone\n\ntext \\<open>At this point we have all the necessary ingredients to prove that\nrelation algebras form Boolean domain semirings. However, we omit a formal\nproof since we haven't formalized the latter.\\<close>\n\nlemma dom_one: \"x ; 1 = d x ; 1\"\nby (metis dom_def_aux inf_top_left mult.left_neutral ra_1)\n\nlemma test_dom: \"is_test (d x)\"\nby (metis dom_def_aux inf_le1 is_test_def)\n\nlemma p_fun_dom: \"is_p_fun (d x)\"\nby (metis test_dom test_is_inj_fun)\n\nlemma inj_dom: \"is_inj (d x)\"\nby (metis test_dom test_is_inj_fun)\n\nlemma total_alt_def: \"is_total x \\<longleftrightarrow> (d x) = 1'\"\nby (metis dom_def_aux_var le_iff_inf is_total_def)\n\nend (* relation_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/Relation_Algebra_Functions.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.890294223211224, "lm_q2_score": 0.810478913248044, "lm_q1q2_score": 0.7215646944992443}}
{"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_BubSortSorts\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 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 bubble :: \"Nat list => (bool, (Nat 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 le 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 :: \"Nat list => Nat 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/TIP15/TIP15/TIP_sort_nat_BubSortSorts.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942319436395, "lm_q2_score": 0.8104789018037399, "lm_q1q2_score": 0.7215646913878851}}
{"text": "chapter \\<open>Case Study: Single and Multi-Mutator Garbage Collection Algorithms\\<close>\n\nsection \\<open>Formalization of the Memory\\<close>\n\ntheory Graph imports Main begin\n\ndatatype node = Black | White\n\ntype_synonym nodes = \"node list\"\ntype_synonym edge = \"nat \\<times> nat\"\ntype_synonym edges = \"edge list\"\n\nconsts Roots :: \"nat set\"\n\ndefinition Proper_Roots :: \"nodes \\<Rightarrow> bool\" where\n  \"Proper_Roots M \\<equiv> Roots\\<noteq>{} \\<and> Roots \\<subseteq> {i. i<length M}\"\n\ndefinition Proper_Edges :: \"(nodes \\<times> edges) \\<Rightarrow> bool\" where\n  \"Proper_Edges \\<equiv> (\\<lambda>(M,E). \\<forall>i<length E. fst(E!i)<length M \\<and> snd(E!i)<length M)\"\n\ndefinition BtoW :: \"(edge \\<times> nodes) \\<Rightarrow> bool\" where\n  \"BtoW \\<equiv> (\\<lambda>(e,M). (M!fst e)=Black \\<and> (M!snd e)\\<noteq>Black)\"\n\ndefinition Blacks :: \"nodes \\<Rightarrow> nat set\" where\n  \"Blacks M \\<equiv> {i. i<length M \\<and> M!i=Black}\"\n\ndefinition Reach :: \"edges \\<Rightarrow> nat set\" where\n  \"Reach E \\<equiv> {x. (\\<exists>path. 1<length path \\<and> path!(length path - 1)\\<in>Roots \\<and> x=path!0\n              \\<and> (\\<forall>i<length path - 1. (\\<exists>j<length E. E!j=(path!(i+1), path!i))))\n              \\<or> x\\<in>Roots}\"\n\ntext\\<open>Reach: the set of reachable nodes is the set of Roots together with the\nnodes reachable from some Root by a path represented by a list of\n  nodes (at least two since we traverse at least one edge), where two\nconsecutive nodes correspond to an edge in E.\\<close>\n\nsubsection \\<open>Proofs about Graphs\\<close>\n\nlemmas Graph_defs= Blacks_def Proper_Roots_def Proper_Edges_def BtoW_def\ndeclare Graph_defs [simp]\n\nsubsubsection\\<open>Graph 1\\<close>\n\nlemma Graph1_aux [rule_format]:\n  \"\\<lbrakk> Roots\\<subseteq>Blacks M; \\<forall>i<length E. \\<not>BtoW(E!i,M)\\<rbrakk>\n  \\<Longrightarrow> 1< length path \\<longrightarrow> (path!(length path - 1))\\<in>Roots \\<longrightarrow>\n  (\\<forall>i<length path - 1. (\\<exists>j. j < length E \\<and> E!j=(path!(Suc i), path!i)))\n  \\<longrightarrow> M!(path!0) = Black\"\napply(induct_tac \"path\")\n apply force\napply clarify\napply simp\napply(case_tac \"list\")\n apply force\napply simp\napply(rename_tac lista)\napply(rotate_tac -2)\napply(erule_tac x = \"0\" in all_dupE)\napply simp\napply clarify\napply(erule allE , erule (1) notE impE)\napply simp\napply(erule mp)\napply(case_tac \"lista\")\n apply force\napply simp\napply(erule mp)\napply clarify\napply(erule_tac x = \"Suc i\" in allE)\napply force\ndone\n\nlemma Graph1:\n  \"\\<lbrakk>Roots\\<subseteq>Blacks M; Proper_Edges(M, E); \\<forall>i<length E. \\<not>BtoW(E!i,M) \\<rbrakk>\n  \\<Longrightarrow> Reach E\\<subseteq>Blacks M\"\napply (unfold Reach_def)\napply simp\napply clarify\napply(erule disjE)\n apply clarify\n apply(rule conjI)\n  apply(subgoal_tac \"0< length path - Suc 0\")\n   apply(erule allE , erule (1) notE impE)\n   apply force\n  apply simp\n apply(rule Graph1_aux)\napply auto\ndone\n\nsubsubsection\\<open>Graph 2\\<close>\n\nlemma Ex_first_occurrence [rule_format]:\n  \"P (n::nat) \\<longrightarrow> (\\<exists>m. P m \\<and> (\\<forall>i. i<m \\<longrightarrow> \\<not> P i))\"\napply(rule nat_less_induct)\napply clarify\napply(case_tac \"\\<forall>m. m<n \\<longrightarrow> \\<not> P m\")\napply auto\ndone\n\nlemma Compl_lemma: \"(n::nat)\\<le>l \\<Longrightarrow> (\\<exists>m. m\\<le>l \\<and> n=l - m)\"\napply(rule_tac x = \"l - n\" in exI)\napply arith\ndone\n\nlemma Ex_last_occurrence:\n  \"\\<lbrakk>P (n::nat); n\\<le>l\\<rbrakk> \\<Longrightarrow> (\\<exists>m. P (l - m) \\<and> (\\<forall>i. i<m \\<longrightarrow> \\<not>P (l - i)))\"\napply(drule Compl_lemma)\napply clarify\napply(erule Ex_first_occurrence)\ndone\n\nlemma Graph2:\n  \"\\<lbrakk>T \\<in> Reach E; R<length E\\<rbrakk> \\<Longrightarrow> T \\<in> Reach (E[R:=(fst(E!R), T)])\"\napply (unfold Reach_def)\napply clarify\napply simp\napply(case_tac \"\\<forall>z<length path. fst(E!R)\\<noteq>path!z\")\n apply(rule_tac x = \"path\" in exI)\n apply simp\n apply clarify\n apply(erule allE , erule (1) notE impE)\n apply clarify\n apply(rule_tac x = \"j\" in exI)\n apply(case_tac \"j=R\")\n  apply(erule_tac x = \"Suc i\" in allE)\n  apply simp\n apply (force simp add:nth_list_update)\napply simp\napply(erule exE)\napply(subgoal_tac \"z \\<le> length path - Suc 0\")\n prefer 2 apply arith\napply(drule_tac P = \"\\<lambda>m. m<length path \\<and> fst(E!R)=path!m\" in Ex_last_occurrence)\n apply assumption\napply clarify\napply simp\napply(rule_tac x = \"(path!0)#(drop (length path - Suc m) path)\" in exI)\napply simp\napply(case_tac \"length path - (length path - Suc m)\")\n apply arith\napply simp\napply(subgoal_tac \"(length path - Suc m) + nat \\<le> length path\")\n prefer 2 apply arith\napply(subgoal_tac \"length path - Suc m + nat = length path - Suc 0\")\n prefer 2 apply arith\napply clarify\napply(case_tac \"i\")\n apply(force simp add: nth_list_update)\napply simp\napply(subgoal_tac \"(length path - Suc m) + nata \\<le> length path\")\n prefer 2 apply arith\napply(subgoal_tac \"(length path - Suc m) + (Suc nata) \\<le> length path\")\n prefer 2 apply arith\napply simp\napply(erule_tac x = \"length path - Suc m + nata\" in allE)\napply simp\napply clarify\napply(rule_tac x = \"j\" in exI)\napply(case_tac \"R=j\")\n prefer 2 apply force\napply simp\napply(drule_tac t = \"path ! (length path - Suc m)\" in sym)\napply simp\napply(case_tac \" length path - Suc 0 < m\")\n apply(subgoal_tac \"(length path - Suc m)=0\")\n  prefer 2 apply arith\n apply(simp del: diff_is_0_eq)\n apply(subgoal_tac \"Suc nata\\<le>nat\")\n prefer 2 apply arith\n apply(drule_tac n = \"Suc nata\" in Compl_lemma)\n apply clarify\n subgoal using [[linarith_split_limit = 0]] by force\napply(drule leI)\napply(subgoal_tac \"Suc (length path - Suc m + nata)=(length path - Suc 0) - (m - Suc nata)\")\n apply(erule_tac x = \"m - (Suc nata)\" in allE)\n apply(case_tac \"m\")\n  apply simp\n apply simp\napply simp\ndone\n\n\nsubsubsection\\<open>Graph 3\\<close>\n\ndeclare min.absorb1 [simp] min.absorb2 [simp]\n\nlemma Graph3:\n  \"\\<lbrakk> T\\<in>Reach E; R<length E \\<rbrakk> \\<Longrightarrow> Reach(E[R:=(fst(E!R),T)]) \\<subseteq> Reach E\"\napply (unfold Reach_def)\napply clarify\napply simp\napply(case_tac \"\\<exists>i<length path - 1. (fst(E!R),T)=(path!(Suc i),path!i)\")\n\\<comment> \\<open>the changed edge is part of the path\\<close>\n apply(erule exE)\n apply(drule_tac P = \"\\<lambda>i. i<length path - 1 \\<and> (fst(E!R),T)=(path!Suc i,path!i)\" in Ex_first_occurrence)\n apply clarify\n apply(erule disjE)\n\\<comment> \\<open>T is NOT a root\\<close>\n  apply clarify\n  apply(rule_tac x = \"(take m path)@patha\" in exI)\n  apply(subgoal_tac \"\\<not>(length path\\<le>m)\")\n   prefer 2 apply arith\n  apply(simp)\n  apply(rule conjI)\n   apply(subgoal_tac \"\\<not>(m + length patha - 1 < m)\")\n    prefer 2 apply arith\n   apply(simp add: nth_append)\n  apply(rule conjI)\n   apply(case_tac \"m\")\n    apply force\n   apply(case_tac \"path\")\n    apply force\n   apply force\n  apply clarify\n  apply(case_tac \"Suc i\\<le>m\")\n   apply(erule_tac x = \"i\" in allE)\n   apply simp\n   apply clarify\n   apply(rule_tac x = \"j\" in exI)\n   apply(case_tac \"Suc i<m\")\n    apply(simp add: nth_append)\n    apply(case_tac \"R=j\")\n     apply(simp add: nth_list_update)\n     apply(case_tac \"i=m\")\n      apply force\n     apply(erule_tac x = \"i\" in allE)\n     apply force\n    apply(force simp add: nth_list_update)\n   apply(simp add: nth_append)\n   apply(subgoal_tac \"i=m - 1\")\n    prefer 2 apply arith\n   apply(case_tac \"R=j\")\n    apply(erule_tac x = \"m - 1\" in allE)\n    apply(simp add: nth_list_update)\n   apply(force simp add: nth_list_update)\n  apply(simp add: nth_append)\n  apply(rotate_tac -4)\n  apply(erule_tac x = \"i - m\" in allE)\n  apply(subgoal_tac \"Suc (i - m)=(Suc i - m)\" )\n    prefer 2 apply arith\n   apply simp\n\\<comment> \\<open>T is a root\\<close>\n apply(case_tac \"m=0\")\n  apply force\n apply(rule_tac x = \"take (Suc m) path\" in exI)\n apply(subgoal_tac \"\\<not>(length path\\<le>Suc m)\" )\n  prefer 2 apply arith\n apply clarsimp\n apply(erule_tac x = \"i\" in allE)\n apply simp\n apply clarify\n apply(case_tac \"R=j\")\n  apply(force simp add: nth_list_update)\n apply(force simp add: nth_list_update)\n\\<comment> \\<open>the changed edge is not part of the path\\<close>\napply(rule_tac x = \"path\" in exI)\napply simp\napply clarify\napply(erule_tac x = \"i\" in allE)\napply clarify\napply(case_tac \"R=j\")\n apply(erule_tac x = \"i\" in allE)\n apply simp\napply(force simp add: nth_list_update)\ndone\n\nsubsubsection\\<open>Graph 4\\<close>\n\nlemma Graph4:\n  \"\\<lbrakk>T \\<in> Reach E; Roots\\<subseteq>Blacks M; I\\<le>length E; T<length M; R<length E;\n  \\<forall>i<I. \\<not>BtoW(E!i,M); R<I; M!fst(E!R)=Black; M!T\\<noteq>Black\\<rbrakk> \\<Longrightarrow>\n  (\\<exists>r. I\\<le>r \\<and> r<length E \\<and> BtoW(E[R:=(fst(E!R),T)]!r,M))\"\napply (unfold Reach_def)\napply simp\napply(erule disjE)\n prefer 2 apply force\napply clarify\n\\<comment> \\<open>there exist a black node in the path to T\\<close>\napply(case_tac \"\\<exists>m<length path. M!(path!m)=Black\")\n apply(erule exE)\n apply(drule_tac P = \"\\<lambda>m. m<length path \\<and> M!(path!m)=Black\" in Ex_first_occurrence)\n apply clarify\n apply(case_tac \"ma\")\n  apply force\n apply simp\n apply(case_tac \"length path\")\n  apply force\n apply simp\n apply(erule_tac P = \"\\<lambda>i. i < nata \\<longrightarrow> P i\" and x = \"nat\" for P in allE)\n apply simp\n apply clarify\n apply(erule_tac P = \"\\<lambda>i. i < Suc nat \\<longrightarrow> P i\" and x = \"nat\" for P in allE)\n apply simp\n apply(case_tac \"j<I\")\n  apply(erule_tac x = \"j\" in allE)\n  apply force\n apply(rule_tac x = \"j\" in exI)\n apply(force  simp add: nth_list_update)\napply simp\napply(rotate_tac -1)\napply(erule_tac x = \"length path - 1\" in allE)\napply(case_tac \"length path\")\n apply force\napply force\ndone\n\ndeclare min.absorb1 [simp del] min.absorb2 [simp del]\n\nsubsubsection \\<open>Graph 5\\<close>\n\nlemma Graph5:\n  \"\\<lbrakk> T \\<in> Reach E ; Roots \\<subseteq> Blacks M; \\<forall>i<R. \\<not>BtoW(E!i,M); T<length M;\n    R<length E; M!fst(E!R)=Black; M!snd(E!R)=Black; M!T \\<noteq> Black\\<rbrakk>\n   \\<Longrightarrow> (\\<exists>r. R<r \\<and> r<length E \\<and> BtoW(E[R:=(fst(E!R),T)]!r,M))\"\napply (unfold Reach_def)\napply simp\napply(erule disjE)\n prefer 2 apply force\napply clarify\n\\<comment> \\<open>there exist a black node in the path to T\\<close>\napply(case_tac \"\\<exists>m<length path. M!(path!m)=Black\")\n apply(erule exE)\n apply(drule_tac P = \"\\<lambda>m. m<length path \\<and> M!(path!m)=Black\" in Ex_first_occurrence)\n apply clarify\n apply(case_tac \"ma\")\n  apply force\n apply simp\n apply(case_tac \"length path\")\n  apply force\n apply simp\n apply(erule_tac P = \"\\<lambda>i. i < nata \\<longrightarrow> P i\" and x = \"nat\" for P in allE)\n apply simp\n apply clarify\n apply(erule_tac P = \"\\<lambda>i. i < Suc nat \\<longrightarrow> P i\" and x = \"nat\" for P in allE)\n apply simp\n apply(case_tac \"j\\<le>R\")\n  apply(drule le_imp_less_or_eq [of _ R])\n  apply(erule disjE)\n   apply(erule allE , erule (1) notE impE)\n   apply force\n  apply force\n apply(rule_tac x = \"j\" in exI)\n apply(force  simp add: nth_list_update)\napply simp\napply(rotate_tac -1)\napply(erule_tac x = \"length path - 1\" in allE)\napply(case_tac \"length path\")\n apply force\napply force\ndone\n\nsubsubsection \\<open>Other lemmas about graphs\\<close>\n\nlemma Graph6:\n \"\\<lbrakk>Proper_Edges(M,E); R<length E ; T<length M\\<rbrakk> \\<Longrightarrow> Proper_Edges(M,E[R:=(fst(E!R),T)])\"\napply (unfold Proper_Edges_def)\n apply(force  simp add: nth_list_update)\ndone\n\nlemma Graph7:\n \"\\<lbrakk>Proper_Edges(M,E)\\<rbrakk> \\<Longrightarrow> Proper_Edges(M[T:=a],E)\"\napply (unfold Proper_Edges_def)\napply force\ndone\n\nlemma Graph8:\n \"\\<lbrakk>Proper_Roots(M)\\<rbrakk> \\<Longrightarrow> Proper_Roots(M[T:=a])\"\napply (unfold Proper_Roots_def)\napply force\ndone\n\ntext\\<open>Some specific lemmata for the verification of garbage collection algorithms.\\<close>\n\nlemma Graph9: \"j<length M \\<Longrightarrow> Blacks M\\<subseteq>Blacks (M[j := Black])\"\napply (unfold Blacks_def)\n apply(force simp add: nth_list_update)\ndone\n\nlemma Graph10 [rule_format (no_asm)]: \"\\<forall>i. M!i=a \\<longrightarrow>M[i:=a]=M\"\napply(induct_tac \"M\")\napply auto\napply(case_tac \"i\")\napply auto\ndone\n\nlemma Graph11 [rule_format (no_asm)]:\n  \"\\<lbrakk> M!j\\<noteq>Black;j<length M\\<rbrakk> \\<Longrightarrow> Blacks M \\<subset> Blacks (M[j := Black])\"\napply (unfold Blacks_def)\napply(rule psubsetI)\n apply(force simp add: nth_list_update)\napply safe\napply(erule_tac c = \"j\" in equalityCE)\napply auto\ndone\n\nlemma Graph12: \"\\<lbrakk>a\\<subseteq>Blacks M;j<length M\\<rbrakk> \\<Longrightarrow> a\\<subseteq>Blacks (M[j := Black])\"\napply (unfold Blacks_def)\napply(force simp add: nth_list_update)\ndone\n\nlemma Graph13: \"\\<lbrakk>a\\<subset> Blacks M;j<length M\\<rbrakk> \\<Longrightarrow> a \\<subset> Blacks (M[j := Black])\"\napply (unfold Blacks_def)\napply(erule psubset_subset_trans)\napply(force simp add: nth_list_update)\ndone\n\ndeclare Graph_defs [simp del]\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/Hoare_Parallel/Graph.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.890294223211224, "lm_q2_score": 0.81047890180374, "lm_q1q2_score": 0.7215646843104466}}
{"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_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/TIP15/TIP15/TIP_bin_plus.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218391455085, "lm_q2_score": 0.7826624738835052, "lm_q1q2_score": 0.7215536273528547}}
{"text": "theory BoolosATP2 imports Main\nbegin\n\ntypedecl i\nconsts \n e :: \"i\"  (* one *) \n s :: \"i\\<Rightarrow>i\"  (* successor function *)\n F :: \"i\\<Rightarrow>i\\<Rightarrow>i\"  (* binary function; axiomatised below as Ackermann function *)\n D :: \"i\\<Rightarrow>bool\"  (* arbitrary uninterpreted unary predicate *)\n\naxiomatization where \n    A1: \"\\<forall>n. F n e = s e\"  (* Axiom for Ackermann function F *)\nand A2: \"\\<forall>y. F e (s y) = s (s (F e y))\"  (* Axiom for Ackermann function F *)\nand A3: \"\\<forall>x y. F (s x) (s y) = F x (F (s x) y)\"  (* Axiom for Ackermann function F *)\nand A4: \"D e\"  (* D holds for one *)\nand A5: \"\\<forall>x. D x \\<longrightarrow> D (s x)\" (* if D holds for x it also holds for the successor of x *)\n\nlemma \"D (F (s (s (s (s e)))) (s (s (s (s e)))))\" sledgehammer oops (* no proof; hopeless! *)\n\ndefinition isIndSet where (* X is inductive (over e and s) *)\n  \"isIndSet \\<equiv> \\<lambda>X. (X e) \\<and> (\\<forall>x. X x \\<longrightarrow> X (s x))\"  \ndefinition P where (* P(x,y) iff F(x,y) is in smallest inductive set (over e and s) *)\n  \"P \\<equiv> \\<lambda>x y. (\\<lambda>z. (\\<forall>X::i\\<Rightarrow>bool. isIndSet X \\<longrightarrow> X z)) (F x y)\" \n\nlemma \"D (F (s (s (s (s e)))) (s (s (s (s e)))))\"  (* ATPs can now proof this: using the Defs *)\n  sledgehammer  (* proof found *)\n  by (metis A1 A2 A3 A4 A5 P_def isIndSet_def)     (* proof reconstruction succeeds *)\nend \n", "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/BoolosATP2.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218284193597, "lm_q2_score": 0.7826624789529375, "lm_q1q2_score": 0.7215536236315208}}
{"text": "(*\nAuthor:     Wenda Li <wl302@cam.ac.uk / liwenda1990@hotmail.com>\n*)\ntheory Count_Rectangle imports Count_Line\nbegin\n\ntext \\<open>Counting roots in a rectangular area can be in a purely algebraic approach \n  without introducing (analytic) winding number (@{term winding_number})\n  nor the argument principle (@{thm argument_principle}). This has been illustrated\n  by Michael Eisermann \\<^cite>\\<open>\"eisermann2012fundamental\"\\<close>. We lightly make use of \n  @{term winding_number} here only to shorten the proof of one of the technical lemmas.\\<close>    \n\nsubsection \\<open>Misc\\<close>\n\nlemma proots_count_const:\n  assumes \"c\\<noteq>0\"\n  shows \"proots_count [:c:] s = 0\"\n  unfolding proots_count_def using assms by auto\n\nlemma proots_count_nzero:\n  assumes \"\\<And>x. x\\<in>s \\<Longrightarrow> poly p x\\<noteq>0\"\n  shows \"proots_count p s = 0\"\n  unfolding proots_count_def\n  by(rule sum.neutral) (use assms in auto)\n\nlemma complex_box_ne_empty: \n  fixes a b::complex\n  shows \n    \"cbox a b \\<noteq> {} \\<longleftrightarrow> (Re a \\<le> Re b \\<and> Im a \\<le> Im b)\"\n    \"box a b \\<noteq> {} \\<longleftrightarrow> (Re a < Re b \\<and> Im a < Im b)\"\n  by (auto simp add:box_ne_empty Basis_complex_def) \n\nsubsection \\<open>Counting roots in a rectangle\\<close>  \n  \ndefinition proots_rect ::\"complex poly \\<Rightarrow> complex \\<Rightarrow> complex \\<Rightarrow> nat\" where\n  \"proots_rect p lb ub = proots_count p (box lb ub)\"\n\ndefinition proots_crect ::\"complex poly \\<Rightarrow> complex \\<Rightarrow> complex \\<Rightarrow> nat\" where\n  \"proots_crect p lb ub = proots_count p (cbox lb ub)\" \n\ndefinition proots_rect_ll ::\"complex poly \\<Rightarrow> complex \\<Rightarrow> complex \\<Rightarrow> nat\" where\n  \"proots_rect_ll p lb ub = proots_count p (box lb ub \\<union> {lb} \n                              \\<union> open_segment lb (Complex (Re ub) (Im lb))\n                              \\<union> open_segment lb (Complex (Re lb) (Im ub)))\" \n\ndefinition proots_rect_border::\"complex poly \\<Rightarrow> complex \\<Rightarrow> complex \\<Rightarrow> nat\" where\n  \"proots_rect_border p a b = proots_count p (path_image (rectpath a b))\"\n\ndefinition not_rect_vertex::\"complex \\<Rightarrow> complex \\<Rightarrow> complex \\<Rightarrow> bool\" where \n  \"not_rect_vertex r a b = (r\\<noteq>a \\<and> r \\<noteq> Complex (Re b) (Im a) \\<and> r\\<noteq>b \\<and> r\\<noteq>Complex (Re a) (Im b))\"\n\ndefinition not_rect_vanishing :: \"complex poly \\<Rightarrow> complex \\<Rightarrow> complex \\<Rightarrow> bool\" where\n  \"not_rect_vanishing p a b = (poly p a\\<noteq>0 \\<and> poly p (Complex (Re b) (Im a)) \\<noteq> 0 \n                            \\<and> poly p b \\<noteq>0 \\<and> poly p (Complex (Re a) (Im b))\\<noteq> 0)\"\n\nlemma cindexP_rectpath_edge_base:\n  assumes \"Re a < Re b\" \"Im a < Im b\"\n    and \"not_rect_vertex r a b\"\n    and \"r\\<in>path_image (rectpath a b)\"\n  shows \"cindexP_pathE [:-r,1:] (rectpath a b) = -1\"\nproof -\n  have r_nzero:\"r\\<noteq>a\" \"r\\<noteq>Complex (Re b) (Im a)\" \"r\\<noteq>b\" \"r\\<noteq>Complex (Re a) (Im b)\" \n    using \\<open>not_rect_vertex r a b\\<close> unfolding not_rect_vertex_def by auto\n\n  define rr where \"rr = [:-r,1:]\"\n  have rr_linepath:\"cindexP_pathE rr (linepath a b) \n          = cindex_pathE (linepath (a - r) (b-r)) 0 \" for a b\n     unfolding rr_def \n     unfolding cindexP_lineE_def cindexP_pathE_def poly_linepath_comp\n     by (simp add:poly_pcompose comp_def linepath_def scaleR_conv_of_real algebra_simps)\n\n  have cindexP_pathE_eq:\"cindexP_pathE rr (rectpath a b) = \n                 cindexP_pathE rr (linepath a (Complex (Re b) (Im a)))  \n                 + cindexP_pathE rr (linepath (Complex (Re b) (Im a)) b) \n                 + cindexP_pathE rr (linepath b (Complex (Re a) (Im b))) \n                 + cindexP_pathE rr (linepath (Complex (Re a) (Im b)) a)\"\n    unfolding rectpath_def Let_def \n    by ((subst cindex_poly_pathE_joinpaths\n            |subst finite_ReZ_segments_joinpaths\n            |intro path_poly_comp conjI);\n        (simp add:poly_linepath_comp finite_ReZ_segments_poly_of_real path_compose_join \n          pathfinish_compose pathstart_compose poly_pcompose)?)+\n\n  have \"(Im r = Im a \\<and> Re a < Re r \\<and> Re r < Re b)\n        \\<or> (Re r = Re b \\<and> Im a < Im r \\<and> Im r < Im b)\n        \\<or> (Im r = Im b \\<and> Re a < Re r \\<and> Re r < Re b)\n        \\<or> (Re r = Re a \\<and> Im a < Im r \\<and> Im r < Im b)\"\n  proof -\n    have \"r \\<in> closed_segment a (Complex (Re b) (Im a)) \n          \\<or> r \\<in> closed_segment (Complex (Re b) (Im a)) b \n          \\<or> r \\<in> closed_segment b (Complex (Re a) (Im b)) \n          \\<or> r \\<in> closed_segment (Complex (Re a) (Im b)) a\"\n      using \\<open>r\\<in>path_image (rectpath a b)\\<close>\n      unfolding rectpath_def Let_def\n      by (subst (asm) path_image_join;simp)+\n    then show ?thesis \n      by (smt (verit, del_insts) assms(1) assms(2) r_nzero \n          closed_segment_commute closed_segment_imp_Re_Im(1) closed_segment_imp_Re_Im(2) \n          complex.sel(1) complex.sel(2) complex_eq_iff)\n  qed\n  moreover have \"cindexP_pathE rr (rectpath a b) = -1\" \n    if \"Im r = Im a\" \"Re a < Re r\" \"Re r < Re b\" \n  proof -\n    have \"cindexP_pathE rr (linepath a (Complex (Re b) (Im a))) = 0\"\n      unfolding rr_linepath\n      apply (rule cindex_pathE_linepath_on)\n      using closed_segment_degen_complex(2) that(1) that(2) that(3) by auto\n    moreover have \"cindexP_pathE rr (linepath (Complex (Re b) (Im a)) b) = 0\"\n      unfolding rr_linepath\n      apply (subst cindex_pathE_linepath)  \n      subgoal using closed_segment_imp_Re_Im(1) that(3) by fastforce\n      subgoal using that assms unfolding Let_def by auto\n      done\n    moreover have \"cindexP_pathE rr (linepath b (Complex (Re a) (Im b))) = -1\"\n      unfolding rr_linepath\n      apply (subst cindex_pathE_linepath)\n      subgoal using assms(2) closed_segment_imp_Re_Im(2) that(1) by fastforce\n      subgoal using that assms unfolding Let_def by auto\n      done\n    moreover have \"cindexP_pathE rr (linepath (Complex (Re a) (Im b)) a) = 0\"\n      unfolding rr_linepath\n      apply (subst cindex_pathE_linepath)\n      subgoal using closed_segment_imp_Re_Im(1) that(2) by fastforce\n      subgoal using that assms unfolding Let_def by auto\n      done\n    ultimately show ?thesis unfolding cindexP_pathE_eq by auto\n  qed\n  moreover have \"cindexP_pathE rr (rectpath a b) = -1\" \n    if \"Re r = Re b\" \"Im a < Im r\" \"Im r < Im b\" \n  proof -\n    have \"cindexP_pathE rr (linepath a (Complex (Re b) (Im a))) = -1/2\"\n      unfolding rr_linepath\n      apply (subst cindex_pathE_linepath) \n      subgoal using closed_segment_imp_Re_Im(2) that(2) by fastforce\n      subgoal using that assms unfolding Let_def by auto \n      done\n    moreover have \"cindexP_pathE rr (linepath (Complex (Re b) (Im a)) b) = 0\"\n      unfolding rr_linepath\n      apply (rule cindex_pathE_linepath_on)\n      using closed_segment_degen_complex(1) that(1) that(2) that(3) by auto\n\n    moreover have \"cindexP_pathE rr (linepath b (Complex (Re a) (Im b))) = -1/2\"\n      unfolding rr_linepath\n      apply (subst cindex_pathE_linepath)\n      subgoal using closed_segment_imp_Re_Im(2) that(3) by fastforce\n      subgoal using that assms unfolding Let_def by auto\n      done\n    moreover have \"cindexP_pathE rr (linepath (Complex (Re a) (Im b)) a) = 0\"\n      unfolding rr_linepath\n      apply (subst cindex_pathE_linepath)\n      subgoal using assms(1) closed_segment_imp_Re_Im(1) that(1) by fastforce\n      subgoal using that assms unfolding Let_def by auto\n      done\n    ultimately show ?thesis unfolding cindexP_pathE_eq by auto\n  qed\n  moreover have \"cindexP_pathE rr (rectpath a b) = -1\" \n    if \"Im r = Im b\" \"Re a < Re r\" \"Re r < Re b\" \n  proof -\n    have \"cindexP_pathE rr (linepath a (Complex (Re b) (Im a))) = -1\"\n      unfolding rr_linepath\n      apply (subst cindex_pathE_linepath) \n      subgoal using assms(2) closed_segment_imp_Re_Im(2) that(1) by fastforce\n      subgoal using that assms unfolding Let_def by auto \n      done\n    moreover have \"cindexP_pathE rr (linepath (Complex (Re b) (Im a)) b) = 0\"\n      unfolding rr_linepath\n      apply (subst cindex_pathE_linepath) \n      subgoal using closed_segment_imp_Re_Im(1) that(3) by force\n      subgoal using that assms unfolding Let_def by auto\n      done\n    moreover have \"cindexP_pathE rr (linepath b (Complex (Re a) (Im b))) = 0\"\n      unfolding rr_linepath\n      apply (rule cindex_pathE_linepath_on)\n      by (smt (verit, del_insts) Im_poly_hom.base.hom_zero Re_poly_hom.base.hom_zero \n          closed_segment_commute closed_segment_degen_complex(2) complex.sel(1) \n          complex.sel(2) minus_complex.simps(1) minus_complex.simps(2) that(1) that(2) that(3))\n    moreover have \"cindexP_pathE rr (linepath (Complex (Re a) (Im b)) a) = 0\"\n      unfolding rr_linepath\n      apply (subst cindex_pathE_linepath)\n      subgoal using closed_segment_imp_Re_Im(1) that(2) by fastforce\n      subgoal using that assms unfolding Let_def by auto\n      done\n    ultimately show ?thesis unfolding cindexP_pathE_eq by auto\n  qed\n  moreover have \"cindexP_pathE rr (rectpath a b) = -1\" \n    if \"Re r = Re a\" \"Im a < Im r\" \"Im r < Im b\" \n  proof -\n    have \"cindexP_pathE rr (linepath a (Complex (Re b) (Im a))) = -1/2\"\n      unfolding rr_linepath\n      apply (subst cindex_pathE_linepath) \n      subgoal using closed_segment_imp_Re_Im(2) that(2) by fastforce\n      subgoal using that assms unfolding Let_def by auto \n      done\n    moreover have \"cindexP_pathE rr (linepath (Complex (Re b) (Im a)) b) = 0\"\n      unfolding rr_linepath\n      apply (subst cindex_pathE_linepath) \n      subgoal using assms(1) closed_segment_imp_Re_Im(1) that(1) by fastforce\n      subgoal using that assms unfolding Let_def by auto\n      done\n    moreover have \"cindexP_pathE rr (linepath b (Complex (Re a) (Im b))) = -1/2\"\n      unfolding rr_linepath\n      apply (subst cindex_pathE_linepath) \n      subgoal using closed_segment_imp_Re_Im(2) that(3) by fastforce\n      subgoal using that assms unfolding Let_def by auto\n      done\n    moreover have \"cindexP_pathE rr (linepath (Complex (Re a) (Im b)) a) = 0\"\n      unfolding rr_linepath\n      apply (rule cindex_pathE_linepath_on)\n      by (smt (verit) Im_poly_hom.base.hom_zero Re_poly_hom.base.hom_zero \n          closed_segment_commute closed_segment_degen_complex(1) complex.sel(1) \n          complex.sel(2) minus_complex.simps(1) minus_complex.simps(2) that(1) that(2) that(3))\n    ultimately show ?thesis unfolding cindexP_pathE_eq by auto\n  qed\n  ultimately show ?thesis unfolding rr_def by auto\nqed\n\nlemma cindexP_rectpath_vertex_base:\n  assumes \"Re a < Re b\" \"Im a < Im b\"\n    and \"\\<not> not_rect_vertex r a b\" \n  shows \"cindexP_pathE [:-r,1:] (rectpath a b) = -1/2\"\nproof -\n  have r_cases:\"r=a \\<or> r=Complex (Re b) (Im a)\\<or> r=b \\<or> r=Complex (Re a) (Im b)\" \n    using \\<open>\\<not> not_rect_vertex r a b\\<close> unfolding not_rect_vertex_def by auto\n  define rr where \"rr = [:-r,1:]\"\n  have rr_linepath:\"cindexP_pathE rr (linepath a b) \n          = cindex_pathE (linepath (a - r) (b-r)) 0 \" for a b\n     unfolding rr_def \n     unfolding cindexP_lineE_def cindexP_pathE_def poly_linepath_comp\n     by (simp add:poly_pcompose comp_def linepath_def scaleR_conv_of_real algebra_simps)\n\n  have cindexP_pathE_eq:\"cindexP_pathE rr (rectpath a b) = \n                 cindexP_pathE rr (linepath a (Complex (Re b) (Im a)))  \n                 + cindexP_pathE rr (linepath (Complex (Re b) (Im a)) b) \n                 + cindexP_pathE rr (linepath b (Complex (Re a) (Im b))) \n                 + cindexP_pathE rr (linepath (Complex (Re a) (Im b)) a)\"\n    unfolding rectpath_def Let_def \n    by ((subst cindex_poly_pathE_joinpaths\n            |subst finite_ReZ_segments_joinpaths\n            |intro path_poly_comp conjI);\n        (simp add:poly_linepath_comp finite_ReZ_segments_poly_of_real path_compose_join \n          pathfinish_compose pathstart_compose poly_pcompose)?)+\n\n  have \"cindexP_pathE rr (rectpath a b) = -1/2\" \n    if \"r=a\" \n  proof -\n    have \"cindexP_pathE rr (linepath a (Complex (Re b) (Im a))) = 0\"\n      unfolding rr_linepath\n      apply (rule cindex_pathE_linepath_on)\n      by (simp add: that)\n    moreover have \"cindexP_pathE rr (linepath (Complex (Re b) (Im a)) b) = 0\"\n      unfolding rr_linepath\n      apply (subst cindex_pathE_linepath)  \n      subgoal using assms(1) closed_segment_imp_Re_Im(1) that by fastforce\n      subgoal using that assms unfolding Let_def by auto\n      done\n    moreover have \"cindexP_pathE rr (linepath b (Complex (Re a) (Im b))) = -1/2\"\n      unfolding rr_linepath\n      apply (subst cindex_pathE_linepath)\n      subgoal using assms(2) closed_segment_imp_Re_Im(2) that(1) by fastforce\n      subgoal using that assms unfolding Let_def by auto\n      done\n    moreover have \"cindexP_pathE rr (linepath (Complex (Re a) (Im b)) a) = 0\"\n      unfolding rr_linepath\n      apply (rule cindex_pathE_linepath_on)\n      by (simp add: that)\n    ultimately show ?thesis unfolding cindexP_pathE_eq by auto\n  qed\n  moreover have \"cindexP_pathE rr (rectpath a b) = -1/2\" \n    if \"r=Complex (Re b) (Im a)\" \n  proof -\n    have \"cindexP_pathE rr (linepath a (Complex (Re b) (Im a))) = 0\"\n      unfolding rr_linepath\n      apply (rule cindex_pathE_linepath_on)\n      by (simp add: that)\n    moreover have \"cindexP_pathE rr (linepath (Complex (Re b) (Im a)) b) = 0\"\n      unfolding rr_linepath\n      apply (rule cindex_pathE_linepath_on)\n      by (simp add: that)\n    moreover have \"cindexP_pathE rr (linepath b (Complex (Re a) (Im b))) = -1/2\"\n      unfolding rr_linepath\n      apply (subst cindex_pathE_linepath)\n      subgoal using assms(2) closed_segment_imp_Re_Im(2) that(1) by fastforce\n      subgoal using that assms unfolding Let_def by auto\n      done\n    moreover have \"cindexP_pathE rr (linepath (Complex (Re a) (Im b)) a) = 0\"\n      unfolding rr_linepath\n      apply (subst cindex_pathE_linepath)\n      subgoal using assms(1) closed_segment_imp_Re_Im(1) that by fastforce\n      subgoal by (smt (z3) complex.sel(1) minus_complex.simps(1))\n      done\n    ultimately show ?thesis unfolding cindexP_pathE_eq by auto\n  qed\n  moreover have \"cindexP_pathE rr (rectpath a b) = -1/2\" \n    if \"r=b\" \n  proof -\n    have \"cindexP_pathE rr (linepath a (Complex (Re b) (Im a))) = -1/2\"\n      unfolding rr_linepath\n      apply (subst cindex_pathE_linepath)\n      subgoal using assms(2) closed_segment_imp_Re_Im(2) that by fastforce\n      subgoal using assms(1) assms(2) that by auto\n      done\n    moreover have \"cindexP_pathE rr (linepath (Complex (Re b) (Im a)) b) = 0\"\n      unfolding rr_linepath\n      apply (rule cindex_pathE_linepath_on)\n      by (simp add: that)\n    moreover have \"cindexP_pathE rr (linepath b (Complex (Re a) (Im b))) = 0\"\n      unfolding rr_linepath\n      apply (rule cindex_pathE_linepath_on)\n      by (simp add: that)\n    moreover have \"cindexP_pathE rr (linepath (Complex (Re a) (Im b)) a) = 0\"\n      unfolding rr_linepath\n      apply (subst cindex_pathE_linepath)\n      subgoal using assms(1) closed_segment_imp_Re_Im(1) that by fastforce\n      subgoal by (smt (z3) complex.sel(1) minus_complex.simps(1))\n      done\n    ultimately show ?thesis unfolding cindexP_pathE_eq by auto\n  qed\n  moreover have \"cindexP_pathE rr (rectpath a b) = -1/2\" \n    if \"r=Complex (Re a) (Im b)\" \n  proof -\n    have \"cindexP_pathE rr (linepath a (Complex (Re b) (Im a))) = -1/2\"\n      unfolding rr_linepath\n      apply (subst cindex_pathE_linepath)\n      subgoal using assms(2) closed_segment_imp_Re_Im(2) that by fastforce\n      subgoal using assms(1) assms(2) that by auto\n      done\n    moreover have \"cindexP_pathE rr (linepath (Complex (Re b) (Im a)) b) = 0\"\n      unfolding rr_linepath\n      apply (subst cindex_pathE_linepath)\n      subgoal using assms(1) closed_segment_imp_Re_Im(1) that by fastforce\n      subgoal by (smt (z3) complex.sel(1) minus_complex.simps(1))\n      done\n    moreover have \"cindexP_pathE rr (linepath b (Complex (Re a) (Im b))) = 0\"\n      unfolding rr_linepath\n      apply (rule cindex_pathE_linepath_on)\n      by (simp add: that)\n    moreover have \"cindexP_pathE rr (linepath (Complex (Re a) (Im b)) a) = 0\"\n      unfolding rr_linepath\n      apply (rule cindex_pathE_linepath_on)\n      by (simp add: that)\n    ultimately show ?thesis unfolding cindexP_pathE_eq by auto\n  qed\n  ultimately show ?thesis using r_cases unfolding rr_def by auto\nqed\n\nlemma cindexP_rectpath_interior_base:\n  assumes \"r\\<in>box a b\"\n  shows \"cindexP_pathE [:-r,1:] (rectpath a b) = -2\"\nproof -\n  have inbox:\"Re r \\<in> {Re a<..<Re b} \\<and> Im r \\<in> {Im a<..<Im b}\"\n    using \\<open>r\\<in>box a b\\<close> unfolding in_box_complex_iff by auto\n  then have r_nzero:\"r\\<noteq>a\" \"r\\<noteq>Complex (Re b) (Im a)\" \"r\\<noteq>b\" \"r\\<noteq>Complex (Re a) (Im b)\" \n    by auto\n  have \"Re a < Re b\" \"Im a < Im b\"\n    using \\<open>r\\<in>box a b\\<close> complex_box_ne_empty by blast+\n\n  define rr where \"rr = [:-r,1:]\"\n  have rr_linepath:\"cindexP_pathE rr (linepath a b) \n          = cindex_pathE (linepath (a - r) (b-r)) 0 \" for a b\n     unfolding rr_def \n     unfolding cindexP_lineE_def cindexP_pathE_def poly_linepath_comp\n     by (simp add:poly_pcompose comp_def linepath_def scaleR_conv_of_real algebra_simps)\n\n  have \"cindexP_pathE rr (rectpath a b) = \n                 cindexP_pathE rr (linepath a (Complex (Re b) (Im a)))  \n                 + cindexP_pathE rr (linepath (Complex (Re b) (Im a)) b) \n                 + cindexP_pathE rr (linepath b (Complex (Re a) (Im b))) \n                 + cindexP_pathE rr (linepath (Complex (Re a) (Im b)) a)\"\n    unfolding rectpath_def Let_def \n    by ((subst cindex_poly_pathE_joinpaths\n            |subst finite_ReZ_segments_joinpaths\n            |intro path_poly_comp conjI);\n        (simp add:poly_linepath_comp finite_ReZ_segments_poly_of_real path_compose_join \n          pathfinish_compose pathstart_compose poly_pcompose)?)+\n  also have \"... = -2\"\n  proof -\n    have \"cindexP_pathE rr (linepath a (Complex (Re b) (Im a))) = -1\"\n      unfolding rr_linepath\n      apply (subst cindex_pathE_linepath)\n      subgoal using closed_segment_imp_Re_Im(2) inbox by fastforce\n      using inbox by auto\n    moreover have \"cindexP_pathE rr (linepath (Complex (Re b) (Im a)) b) = 0\"\n      unfolding rr_linepath\n      apply (subst cindex_pathE_linepath)  \n      subgoal using closed_segment_imp_Re_Im(1) inbox by fastforce\n      using inbox by auto\n    moreover have \"cindexP_pathE rr (linepath b (Complex (Re a) (Im b))) = -1\"\n      unfolding rr_linepath\n      apply (subst cindex_pathE_linepath)\n      subgoal using closed_segment_imp_Re_Im(2) inbox by fastforce\n      using inbox by auto\n    moreover have \"cindexP_pathE rr (linepath (Complex (Re a) (Im b)) a) = 0\"\n      unfolding rr_linepath\n      apply (subst cindex_pathE_linepath)\n      subgoal using closed_segment_imp_Re_Im(1) inbox by fastforce\n      using inbox by auto\n    ultimately show ?thesis by auto\n  qed\n  finally show ?thesis unfolding rr_def .\nqed\n\n\nlemma cindexP_rectpath_outside_base:\n  assumes \"Re a < Re b\" \"Im a < Im b\" \n    and \"r\\<notin>cbox a b\"\n  shows \"cindexP_pathE [:-r,1:] (rectpath a b) = 0\"\nproof -\n  have not_cbox:\"\\<not> (Re r \\<in> {Re a..Re b} \\<and> Im r \\<in> {Im a..Im b})\"\n    using \\<open>r\\<notin>cbox a b\\<close> unfolding in_cbox_complex_iff by auto\n  then have r_nzero:\"r\\<noteq>a\" \"r\\<noteq>Complex (Re b) (Im a)\" \"r\\<noteq>b\" \"r\\<noteq>Complex (Re a) (Im b)\" \n    using assms by auto\n\n  define rr where \"rr = [:-r,1:]\"\n  have rr_linepath:\"cindexP_pathE rr (linepath a b) \n          = cindex_pathE (linepath (a - r) (b-r)) 0 \" for a b\n     unfolding rr_def \n     unfolding cindexP_lineE_def cindexP_pathE_def poly_linepath_comp\n     by (simp add:poly_pcompose comp_def linepath_def scaleR_conv_of_real algebra_simps)\n\n  have \"cindexP_pathE rr (rectpath a b) = \n                 cindexP_pathE rr (linepath a (Complex (Re b) (Im a)))  \n                 + cindexP_pathE rr (linepath (Complex (Re b) (Im a)) b) \n                 + cindexP_pathE rr (linepath b (Complex (Re a) (Im b))) \n                 + cindexP_pathE rr (linepath (Complex (Re a) (Im b)) a)\"\n    unfolding rectpath_def Let_def \n    by ((subst cindex_poly_pathE_joinpaths\n            |subst finite_ReZ_segments_joinpaths\n            |intro path_poly_comp conjI);\n        (simp add:poly_linepath_comp finite_ReZ_segments_poly_of_real path_compose_join \n          pathfinish_compose pathstart_compose poly_pcompose)?)+\n  have \"cindexP_pathE rr (rectpath a b) = cindex_pathE (poly rr \\<circ> rectpath a b) 0\"\n    unfolding cindexP_pathE_def by simp\n  also have \"...  = - 2 * winding_number (poly rr \\<circ> rectpath a b) 0\"\n    \\<comment>\\<open>We don't need \\<^term>\\<open>winding_number\\<close> to finish the proof, but thanks to Cauthy's\n      Index theorem  (i.e., @{thm \"winding_number_cindex_pathE\"}) we can make the proof shorter.\\<close>\n  proof -\n    have \"winding_number (poly rr \\<circ> rectpath a b) 0 \n            = - cindex_pathE (poly rr \\<circ> rectpath a b) 0 / 2\"\n    proof (rule winding_number_cindex_pathE)\n      show \"finite_ReZ_segments (poly rr \\<circ> rectpath a b) 0\"\n        using finite_ReZ_segments_poly_rectpath  .\n      show \"valid_path (poly rr \\<circ> rectpath a b)\"\n        using valid_path_poly_rectpath .\n      show \"0 \\<notin> path_image (poly rr \\<circ> rectpath a b)\"\n        by (smt (z3) DiffE add.right_neutral add_diff_cancel_left' add_uminus_conv_diff \n            assms(1) assms(2) assms(3) basic_cqe_conv1(1) diff_add_cancel imageE mult.right_neutral \n            mult_zero_right path_image_compose path_image_rectpath_cbox_minus_box poly_pCons rr_def)\n      show \"pathfinish (poly rr \\<circ> rectpath a b) = pathstart (poly rr \\<circ> rectpath a b)\"\n        by (simp add: pathfinish_compose pathstart_compose)\n    qed\n    then show ?thesis by auto\n  qed\n  also have \"... = 0\"\n  proof -\n    have \"winding_number (poly rr \\<circ> rectpath a b) 0 = 0\"\n    proof (rule winding_number_zero_outside)\n      have \"path_image (poly rr \\<circ> rectpath a b) = poly rr ` path_image (rectpath a b)\"\n        using path_image_compose by simp\n      also have \"... = poly rr ` (cbox a b - box a b)\"\n        apply (subst path_image_rectpath_cbox_minus_box)\n        using assms(1,2) by (simp|blast)+\n      also have \"... \\<subseteq> (\\<lambda>x. x -r) ` cbox a b\"\n        unfolding rr_def by (simp add: image_subset_iff)\n      finally show \"path_image (poly rr \\<circ> rectpath a b) \\<subseteq> (\\<lambda>x. x -r) ` cbox a b\" .\n      show \"0 \\<notin> (\\<lambda>x. x - r) ` cbox a b\" using assms(3) by force\n      show \"path (poly rr \\<circ> rectpath a b)\" by (simp add: path_poly_comp)\n      show \" convex ((\\<lambda>x. x - r) ` cbox a b)\" \n        using convex_box(1) convex_translation_subtract_eq by blast\n      show \"pathfinish (poly rr \\<circ> rectpath a b) = pathstart (poly rr \\<circ> rectpath a b)\"\n        by (simp add: pathfinish_compose pathstart_compose)\n    qed\n    then show ?thesis by simp\n  qed\n  finally show ?thesis  unfolding rr_def by simp\nqed\n\nlemma cindexP_rectpath_add_one_root:\n  assumes \"Re a < Re b\" \"Im a < Im b\"\n    and \"not_rect_vertex r a b\"\n    and \"not_rect_vanishing p a b\"\n  shows \"cindexP_pathE ([:-r,1:]*p) (rectpath a b) = \n                cindexP_pathE p (rectpath a b) \n          + (if r\\<in>box a b then -2 else if r\\<in>path_image (rectpath a b) then - 1 else 0)\"\nproof -\n  define rr where \"rr = [:-r,1:]\"\n  have rr_nzero:\"poly rr a\\<noteq>0\" \"poly rr (Complex (Re b) (Im a))\\<noteq>0\" \n                \"poly rr b\\<noteq>0\" \"poly rr (Complex (Re a) (Im b))\\<noteq>0\"\n    using \\<open>not_rect_vertex r a b\\<close> unfolding rr_def not_rect_vertex_def by auto\n\n  have p_nzero:\"poly p a\\<noteq>0\" \"poly p (Complex (Re b) (Im a))\\<noteq>0\" \n                \"poly p b\\<noteq>0\" \"poly p (Complex (Re a) (Im b))\\<noteq>0\"\n    using \\<open>not_rect_vanishing p a b\\<close> unfolding not_rect_vanishing_def by auto\n\n  define cindp where \"cindp = (\\<lambda>p a b. \n                                    cindexP_lineE p a (Complex (Re b) (Im a))\n                                    + cindexP_lineE p (Complex (Re b) (Im a)) b\n                                    + cindexP_lineE p b (Complex (Re a) (Im b))\n                                    + cindexP_lineE p (Complex (Re a) (Im b)) a\n                                )\"\n  define cdiff  where \"cdiff = (\\<lambda>rr p a b. \n                                     cdiff_aux rr p a (Complex (Re b) (Im a))\n                                    + cdiff_aux rr p (Complex (Re b) (Im a)) b\n                                    + cdiff_aux rr p b (Complex (Re a) (Im b))\n                                    + cdiff_aux rr p (Complex (Re a) (Im b)) a \n                                )\"\n\n  have \"cindexP_pathE (rr*p) (rectpath a b) = \n                 cindexP_pathE (rr*p) (linepath a (Complex (Re b) (Im a)))  \n                 + cindexP_pathE (rr*p) (linepath (Complex (Re b) (Im a)) b) \n                 + cindexP_pathE (rr*p) (linepath b (Complex (Re a) (Im b))) \n                 + cindexP_pathE (rr*p) (linepath (Complex (Re a) (Im b)) a)\"\n    unfolding rectpath_def Let_def \n    by ((subst cindex_poly_pathE_joinpaths\n            |subst finite_ReZ_segments_joinpaths\n            |intro path_poly_comp conjI);\n        (simp add:poly_linepath_comp finite_ReZ_segments_poly_of_real path_compose_join \n          pathfinish_compose pathstart_compose poly_pcompose)?)+\n  also have \"... = cindexP_lineE (rr*p) a (Complex (Re b) (Im a)) \n                      + cindexP_lineE (rr*p) (Complex (Re b) (Im a)) b \n                      + cindexP_lineE (rr*p) b (Complex (Re a) (Im b)) \n                      + cindexP_lineE (rr*p) (Complex (Re a) (Im b)) a\"\n    unfolding cindexP_lineE_def by simp\n  also have \"... = cindp rr a b + cindp p a b + cdiff rr p a b/2\"\n    unfolding cindp_def cdiff_def\n    by (subst cindexP_lineE_times;\n          (use rr_nzero p_nzero one_complex.code imaginary_unit.code in simp)?)+\n  also have \"... = cindexP_pathE p (rectpath a b) +(if r\\<in>box a b then -2 else \n      if r\\<in>path_image (rectpath a b) then - 1 else 0)\"\n  proof -\n    have \"cindp rr a b = cindexP_pathE rr (rectpath a b)\" \n      unfolding rectpath_def Let_def cindp_def cindexP_lineE_def\n      by ((subst cindex_poly_pathE_joinpaths\n            |subst finite_ReZ_segments_joinpaths\n            |intro path_poly_comp conjI);\n        (simp add:poly_linepath_comp finite_ReZ_segments_poly_of_real path_compose_join \n          pathfinish_compose pathstart_compose poly_pcompose)?)+\n    also have \"... = (if r\\<in>box a b then -2 else \n      if r\\<in>path_image (rectpath a b) then - 1 else 0)\" \n    proof -\n      have ?thesis if \"r\\<in>box a b\" \n        using cindexP_rectpath_interior_base rr_def that by presburger\n      moreover have ?thesis if \"r\\<notin>box a b\" \"r\\<in>path_image (rectpath a b)\" \n        using cindexP_rectpath_edge_base[OF assms(1,2,3)] that unfolding rr_def by auto\n      moreover have ?thesis if \"r\\<notin>box a b\" \"r\\<notin>path_image (rectpath a b)\" \n      proof -\n        have \"r\\<notin>cbox a b\"\n          using that assms(1) assms(2) path_image_rectpath_cbox_minus_box by auto\n        then show ?thesis unfolding rr_def\n          using assms(1) assms(2) cindexP_rectpath_outside_base that(1) that(2) by presburger\n      qed\n      ultimately show ?thesis by auto\n    qed\n    finally have \"cindp rr a b = (if r\\<in>box a b then -2 else \n      if r\\<in>path_image (rectpath a b) then - 1 else 0)\" .\n    moreover have \"cindp p a b = cindexP_pathE p (rectpath a b)\" \n      unfolding rectpath_def Let_def cindp_def cindexP_lineE_def\n      by ((subst cindex_poly_pathE_joinpaths\n            |subst finite_ReZ_segments_joinpaths\n            |intro path_poly_comp conjI);\n        (simp add:poly_linepath_comp finite_ReZ_segments_poly_of_real path_compose_join \n          pathfinish_compose pathstart_compose poly_pcompose)?)+\n    moreover have \"cdiff rr p a b = 0\" \n      unfolding cdiff_def cdiff_aux_def by simp\n    ultimately show ?thesis by auto\n  qed\n  finally show ?thesis unfolding rr_def .\nqed\n\nlemma proots_rect_cindexP_pathE:\n  assumes \"Re a < Re b\" \"Im a < Im b\"\n    and \"not_rect_vanishing p a b\"\n  shows \"proots_rect p a b = -(proots_rect_border p a b +cindexP_pathE p (rectpath a b)) / 2\"\n  using \\<open>not_rect_vanishing p a b\\<close>\nproof (induct p rule:poly_root_induct_alt)\n  case 0\n  then have False unfolding not_rect_vanishing_def by auto\n  then show ?case by simp\nnext\n  case (no_proots p)\n  then obtain c where pc:\"p=[:c:]\" \"c\\<noteq>0\" \n    by (meson fundamental_theorem_of_algebra_alt)\n  have \"cindexP_pathE p (rectpath a b) = 0\"\n    using pc by (auto intro:cindexP_pathE_const)\n  moreover have \"proots_rect p a b = 0\" \"proots_rect_border p a b = 0\"\n    using pc proots_count_const \n    unfolding proots_rect_def proots_rect_border_def by auto\n  ultimately show ?case by auto \nnext\n  case (root r p)\n  define rr where \"rr=[:-r,1:]\"\n\n  have hyps:\"real (proots_rect p a b) =\n              -(proots_rect_border p a b + cindexP_pathE p (rectpath a b)) / 2\"\n    apply (rule root(1))\n    by (meson not_rect_vanishing_def poly_mult_zero_iff root.prems)\n\n  have cind_eq:\"cindexP_pathE (rr * p) (rectpath a b) =\n          cindexP_pathE p (rectpath a b) +\n            (if r \\<in> box a b then - 2 else if r \\<in> path_image (rectpath a b) then - 1 else 0)\"\n  proof (rule cindexP_rectpath_add_one_root[OF assms(1,2),of r p,folded rr_def])\n    show \" not_rect_vertex r a b\" \n      using not_rect_vanishing_def not_rect_vertex_def root.prems by auto\n    show \"not_rect_vanishing p a b\"\n      using not_rect_vanishing_def root.prems by force\n  qed\n\n  have rect_eq:\"proots_rect (rr * p) a b = proots_rect p a b\n                                            + (if r\\<in>box a b then 1 else 0)\"\n  proof -\n    have \"proots_rect (rr * p) a b \n            = proots_count rr (box a b) + proots_rect p a b\"\n      unfolding proots_rect_def\n      apply (rule proots_count_times)\n      by (metis not_rect_vanishing_def poly_0 root.prems rr_def)\n    moreover have \"proots_count rr (box a b) = (if r\\<in>box a b then 1 else 0)\"\n      using proots_count_pCons_1_iff rr_def by blast\n    ultimately show ?thesis by auto\n  qed\n\n  have border_eq:\"proots_rect_border (rr * p) a b = \n              proots_rect_border p a b\n                              + (if r \\<in> path_image (rectpath a b) then 1 else 0)\"\n  proof -\n    have \"proots_rect_border (rr * p) a b = proots_count rr (path_image (rectpath a b)) \n                  +  proots_rect_border p a b\"\n      unfolding proots_rect_border_def\n      apply (rule proots_count_times)\n      by (metis not_rect_vanishing_def poly_0 root.prems rr_def)\n    moreover have \"proots_count rr (path_image (rectpath a b)) \n            = (if r \\<in> path_image (rectpath a b) then 1 else 0)\"\n      using proots_count_pCons_1_iff rr_def by blast\n    ultimately show ?thesis by auto\n  qed\n\n  have ?case if \"r \\<in> box a b\" \n  proof -\n    have \"proots_rect (rr * p) a b = proots_rect p a b + 1\" \n      unfolding rect_eq  using that by auto \n    moreover have \"proots_rect_border (rr * p) a b = proots_rect_border p a b\" \n      unfolding border_eq  using that\n      using assms(1) assms(2) path_image_rectpath_cbox_minus_box by auto \n    moreover have \"cindexP_pathE (rr * p) (rectpath a b) = cindexP_pathE p (rectpath a b) - 2\"\n      using cind_eq that by auto\n    ultimately show ?thesis using hyps \n      by (fold rr_def)  simp\n  qed\n  moreover have ?case if \"r \\<notin> box a b\" \"r \\<in> path_image (rectpath a b)\" \n  proof -\n    have \"proots_rect (rr * p) a b = proots_rect p a b\" \n      unfolding rect_eq  using that by auto \n    moreover have \"proots_rect_border (rr * p) a b = proots_rect_border p a b + 1\" \n      unfolding border_eq  using that\n      using assms(1) assms(2) path_image_rectpath_cbox_minus_box by auto \n    moreover have \"cindexP_pathE (rr * p) (rectpath a b) = cindexP_pathE p (rectpath a b) - 1\"\n      using cind_eq that by auto\n    ultimately show ?thesis using hyps \n      by (fold rr_def)  auto\n  qed\n  moreover have ?case if \"r \\<notin> box a b\" \"r \\<notin> path_image (rectpath a b)\" \n  proof -\n    have \"proots_rect (rr * p) a b = proots_rect p a b\" \n      unfolding rect_eq  using that by auto \n    moreover have \"proots_rect_border (rr * p) a b = proots_rect_border p a b\" \n      unfolding border_eq  using that\n      using assms(1) assms(2) path_image_rectpath_cbox_minus_box by auto \n    moreover have \"cindexP_pathE (rr * p) (rectpath a b) = cindexP_pathE p (rectpath a b)\"\n      using cind_eq that by auto\n    ultimately show ?thesis using hyps \n      by (fold rr_def)  auto\n  qed\n  ultimately show ?case  by auto\nqed\n\nsubsection \\<open>Code generation\\<close>\n\nlemmas Complex_minus_eq = minus_complex.code\n\nlemma cindexP_pathE_rect_smods:\n  fixes p::\"complex poly\" and lb ub::complex\n  assumes ab_le:\"Re lb < Re ub\" \"Im lb < Im ub\"\n    and \"not_rect_vanishing p lb  ub\"\n  shows \"cindexP_pathE p (rectpath lb ub) = \n           (let p1 = pcompose p [:lb,  Complex (Re ub - Re lb) 0:];\n                pR1 = map_poly Re p1; pI1 = map_poly Im p1; gc1 = gcd pR1 pI1;\n                p2 = pcompose p [:Complex (Re ub) (Im lb), Complex 0 (Im ub - Im lb):];\n                pR2 = map_poly Re p2; pI2 = map_poly Im p2; gc2 = gcd pR2 pI2;\n                p3 = pcompose p [:ub, Complex (Re lb - Re ub) 0:];\n                pR3 = map_poly Re p3; pI3 = map_poly Im p3; gc3 = gcd pR3 pI3;\n                p4 = pcompose p [:Complex (Re lb) (Im ub), Complex 0 (Im lb - Im ub):];\n                pR4 = map_poly Re p4; pI4 = map_poly Im p4; gc4 = gcd pR4 pI4\n            in \n             (changes_alt_itv_smods 0 1 (pR1 div gc1) (pI1 div gc1)\n                + changes_alt_itv_smods 0 1 (pR2 div gc2) (pI2 div gc2)\n                + changes_alt_itv_smods 0 1 (pR3 div gc3) (pI3 div gc3)\n                + changes_alt_itv_smods 0 1 (pR4 div gc4) (pI4 div gc4)\n                ) / 2)\" (is \"?L=?R\")\nproof -\n  have \"cindexP_pathE p (rectpath lb ub) = \n                 cindexP_lineE p lb (Complex (Re ub) (Im lb)) \n                      + cindexP_lineE (p) (Complex (Re ub) (Im lb)) ub \n                      + cindexP_lineE (p) ub (Complex (Re lb) (Im ub)) \n                      + cindexP_lineE (p) (Complex (Re lb) (Im ub)) lb\"\n    unfolding rectpath_def Let_def cindexP_lineE_def\n    by ((subst cindex_poly_pathE_joinpaths\n            |subst finite_ReZ_segments_joinpaths\n            |intro path_poly_comp conjI);\n        (simp add:poly_linepath_comp finite_ReZ_segments_poly_of_real path_compose_join \n          pathfinish_compose pathstart_compose poly_pcompose)?)+\n  also have \"... = ?R\"\n    apply (subst (1 2 3 4)cindexP_lineE_changes)\n    subgoal using assms(3) not_rect_vanishing_def by fastforce\n    subgoal by (smt (verit) assms(2) complex.sel(2))\n    subgoal by (metis assms(1) complex.sel(1) order_less_irrefl)\n    subgoal by (smt (verit) assms(2) complex.sel(2))\n    subgoal by (metis assms(1) complex.sel(1) order_less_irrefl)\n    subgoal unfolding Let_def by (simp_all add:Complex_minus_eq)\n    done\n  finally show ?thesis .\nqed\n\nlemma open_segment_Im_equal:\n  assumes \"Re x \\<noteq> Re y\" \"Im x=Im y\"\n  shows \"open_segment x y = {z. Im z = Im x \n                                  \\<and> Re z \\<in> open_segment (Re x) (Re y)}\" \nproof -\n  have \"open_segment x y = (\\<lambda>u. (1 - u) *\\<^sub>R x + u *\\<^sub>R y) ` {0<..<1}\"\n    unfolding open_segment_image_interval\n    using assms by auto\n  also have \"... = (\\<lambda>u. Complex (Re x + u * (Re y - Re x)) \n                      (Im y)) ` {0<..<1}\"\n    apply (subst (1 2 3 4) complex_surj[symmetric])\n    using assms by (simp add:scaleR_conv_of_real algebra_simps)\n  also have \"... = {z. Im z = Im x \\<and> Re z \\<in> open_segment (Re x) (Re y)}\"\n  proof -\n    have \"Re x + u * (Re y - Re x) \\<in> open_segment (Re x) (Re y)\"\n      if \"Re x \\<noteq> Re y\" \"Im x = Im y\"  \"0 < u\" \"u < 1\" for u\n    proof -\n      define yx where \"yx = Re y - Re x\"\n      have \"Re y = yx + Re x\" \"yx >0 \\<or> yx<0\" \n        unfolding yx_def using that by auto\n      then show ?thesis\n        unfolding open_segment_eq_real_ivl\n        using that mult_pos_neg by auto\n    qed\n    moreover have \"z \\<in> (\\<lambda>xa. Complex (Re x + xa * (Re y -  Re x)) (Im y)) \n                          ` {0<..<1}\"\n      if \"Im x = Im y\" \"Im z = Im y\" \"Re z \\<in> open_segment (Re x) (Re y)\" for z\n      apply (rule rev_image_eqI[of \"(Re z - Re x)/(Re y - Re x)\"])\n      subgoal \n        using that unfolding open_segment_eq_real_ivl \n        by (auto simp:divide_simps)\n      subgoal using \\<open>Re x \\<noteq> Re y\\<close> complex_eq_iff that(2) by auto\n      done\n    ultimately show ?thesis using assms by auto\n  qed\n  finally show ?thesis .\nqed\n\nlemma open_segment_Re_equal:\n  assumes \"Re x = Re y\" \"Im x\\<noteq>Im y\"\n  shows \"open_segment x y = {z. Re z = Re x \n                                  \\<and> Im z \\<in> open_segment (Im x) (Im y)}\" \nproof -\n  have \"open_segment x y = (\\<lambda>u. (1 - u) *\\<^sub>R x + u *\\<^sub>R y) ` {0<..<1}\"\n    unfolding open_segment_image_interval\n    using assms by auto\n  also have \"... = (\\<lambda>u. Complex (Re y)  (Im x + u * (Im y - Im x)) \n                      ) ` {0<..<1}\"\n    apply (subst (1 2 3 4) complex_surj[symmetric])\n    using assms by (simp add:scaleR_conv_of_real algebra_simps)\n  also have \"... = {z. Re z = Re x \\<and> Im z \\<in> open_segment (Im x) (Im y)}\"\n  proof -\n    have \"Im x + u * (Im y - Im x) \\<in> open_segment (Im x) (Im y)\"\n      if \"Im x \\<noteq> Im y\" \"Re x = Re y\"  \"0 < u\" \"u < 1\" for u\n    proof -\n      define yx where \"yx = Im y - Im x\"\n      have \"Im y = yx + Im x\" \"yx >0 \\<or> yx<0\" \n        unfolding yx_def using that by auto\n      then show ?thesis\n        unfolding open_segment_eq_real_ivl\n        using that mult_pos_neg by auto\n    qed\n    moreover have \"z \\<in> (\\<lambda>xa. Complex (Re y) (Im x + xa * (Im y -  Im x)) ) \n                          ` {0<..<1}\"\n      if \"Re x = Re y\" \"Re z = Re y\" \"Im z \\<in> open_segment (Im x) (Im y)\" for z\n      apply (rule rev_image_eqI[of \"(Im z - Im x)/(Im y - Im x)\"])\n      subgoal \n        using that unfolding open_segment_eq_real_ivl \n        by (auto simp:divide_simps)\n      subgoal using \\<open>Im x \\<noteq> Im y\\<close> complex_eq_iff that(2) by auto\n      done\n    ultimately show ?thesis using assms by auto\n  qed\n  finally show ?thesis .\nqed\n\nlemma Complex_eq_iff:\n  \"x = Complex y z \\<longleftrightarrow> Re x = y \\<and> Im x = z\"\n  \"Complex y z = x \\<longleftrightarrow> Re x = y \\<and> Im x = z\"\n  by auto\n\nlemma proots_rect_border_eq_lines:\n  fixes p::\"complex poly\" and lb ub::complex\n  assumes ab_le:\"Re lb < Re ub\" \"Im lb < Im ub\"\n    and not_van:\"not_rect_vanishing p lb ub\"\n  shows \"proots_rect_border p lb ub = \n                  proots_line p lb (Complex (Re ub) (Im lb)) \n                      +  proots_line p (Complex (Re ub) (Im lb)) ub \n                      +  proots_line p ub (Complex (Re lb) (Im ub)) \n                      +  proots_line p (Complex (Re lb) (Im ub)) lb\"\nproof -\n  have \"p\\<noteq>0\" \n    using not_rect_vanishing_def not_van order_root by blast\n\n  define l1 l2 l3 l4 where  \"l1 = open_segment lb (Complex (Re ub) (Im lb))\"\n                        and \"l2 = open_segment (Complex (Re ub) (Im lb)) ub\"\n                        and \"l3 = open_segment ub (Complex (Re lb) (Im ub))\"\n                        and \"l4 = open_segment (Complex (Re lb) (Im ub)) lb\"\n  have ll_eq:\n    \"l1 = {z. Im z \\<in> {Im lb} \\<and> Re z \\<in> {Re lb<..<Re ub}}\"\n    \"l2 = {z. Re z \\<in> {Re ub} \\<and> Im z \\<in> {Im lb<..<Im ub}}\"\n    \"l3 = {z. Im z \\<in> {Im ub} \\<and> Re z \\<in> {Re lb<..<Re ub}}\"\n    \"l4 = {z. Re z \\<in> {Re lb} \\<and> Im z \\<in> {Im lb<..<Im ub}}\"\n    subgoal unfolding l1_def\n      apply (subst open_segment_Im_equal)\n      using assms unfolding open_segment_eq_real_ivl by auto\n    subgoal unfolding l2_def\n      apply (subst open_segment_Re_equal)\n      using assms unfolding open_segment_eq_real_ivl by auto\n    subgoal unfolding l3_def\n      apply (subst open_segment_Im_equal)\n      using assms unfolding open_segment_eq_real_ivl by auto\n    subgoal unfolding l4_def\n      apply (subst open_segment_Re_equal)\n      using assms unfolding open_segment_eq_real_ivl by auto\n    done\n  \n  have ll_disj: \"l1 \\<inter> l2 = {}\" \"l1 \\<inter> l3 = {}\" \"l1 \\<inter> l4 = {}\"\n       \"l2 \\<inter> l3 = {}\" \"l2 \\<inter> l4 = {}\" \"l3 \\<inter> l4 = {}\"\n    using assms unfolding ll_eq by auto\n\n  have \"proots_rect_border p lb ub = proots_count p\n           ({z. Re z \\<in> {Re lb, Re ub} \\<and> Im z \\<in> {Im lb..Im ub}} \\<union>\n            {z. Im z \\<in> {Im lb, Im ub} \\<and> Re z \\<in> {Re lb..Re ub}})\"\n    unfolding proots_rect_border_def\n    apply (subst path_image_rectpath)\n    using assms(1,2) by auto\n  also have \"... = proots_count p\n           ({z. Re z \\<in> {Re lb, Re ub} \\<and> Im z \\<in> {Im lb<..<Im ub}} \\<union>\n            {z. Im z \\<in> {Im lb, Im ub} \\<and> Re z \\<in> {Re lb<..<Re ub}} \n            \\<union> {lb,Complex (Re ub) (Im lb), ub,Complex (Re lb) (Im ub)})\"\n    apply (rule arg_cong2[where f=proots_count])\n    unfolding not_rect_vanishing_def using assms(1,2) complex.exhaust_sel \n    by (auto simp add:order.order_iff_strict intro:complex_eqI)\n  also have \"... = proots_count p\n           ({z. Re z \\<in> {Re lb, Re ub} \\<and> Im z \\<in> {Im lb<..<Im ub}} \\<union>\n            {z. Im z \\<in> {Im lb, Im ub} \\<and> Re z \\<in> {Re lb<..<Re ub}}) \n            + proots_count p \n            ({lb,Complex (Re ub) (Im lb), ub,Complex (Re lb) (Im ub)})\"\n    apply (subst proots_count_union_disjoint)\n    using \\<open>p\\<noteq>0\\<close> by auto\n  also have \"... = proots_count p\n           ({z. Re z \\<in> {Re lb, Re ub} \\<and> Im z \\<in> {Im lb<..<Im ub}} \\<union>\n            {z. Im z \\<in> {Im lb, Im ub} \\<and> Re z \\<in> {Re lb<..<Re ub}})\"\n  proof -\n    have \"proots_count p \n            ({lb,Complex (Re ub) (Im lb), ub,Complex (Re lb) (Im ub)}) = 0\"\n      apply (rule proots_count_nzero)\n      using not_van unfolding not_rect_vanishing_def by auto\n    then show ?thesis by auto\n  qed\n  also have \"... = proots_count p (l1 \\<union> l2 \\<union> l3 \\<union> l4)\"\n    apply (rule arg_cong2[where f=proots_count])\n    unfolding ll_eq by auto\n  also have \"... = proots_count p l1\n                      + proots_count p l2\n                      + proots_count p l3\n                      + proots_count p l4\"\n    using ll_disj \\<open>p\\<noteq>0\\<close>\n    by (subst proots_count_union_disjoint;\n        (simp add:Int_Un_distrib Int_Un_distrib2 )?)+\n  also have \"...  = proots_line p lb (Complex (Re ub) (Im lb)) \n                      +  proots_line p (Complex (Re ub) (Im lb)) ub \n                      +  proots_line p ub (Complex (Re lb) (Im ub)) \n                      +  proots_line p (Complex (Re lb) (Im ub)) lb\"\n    unfolding proots_line_def l1_def l2_def l3_def l4_def by simp_all\n  finally show ?thesis .\nqed\n\nlemma proots_rect_border_smods:\n  fixes p::\"complex poly\" and lb ub::complex\n  assumes ab_le:\"Re lb < Re ub\" \"Im lb < Im ub\"\n    and not_van:\"not_rect_vanishing p lb ub\"\n  shows \"proots_rect_border p lb ub = \n           (let p1 = pcompose p [:lb,  Complex (Re ub - Re lb) 0:];\n                pR1 = map_poly Re p1; pI1 = map_poly Im p1; gc1 = gcd pR1 pI1;\n                p2 = pcompose p [:Complex (Re ub) (Im lb), Complex 0 (Im ub - Im lb):];\n                pR2 = map_poly Re p2; pI2 = map_poly Im p2; gc2 = gcd pR2 pI2;\n                p3 = pcompose p [:ub, Complex (Re lb - Re ub) 0:];\n                pR3 = map_poly Re p3; pI3 = map_poly Im p3; gc3 = gcd pR3 pI3;\n                p4 = pcompose p [:Complex (Re lb) (Im ub), Complex 0 (Im lb - Im ub):];\n                pR4 = map_poly Re p4; pI4 = map_poly Im p4; gc4 = gcd pR4 pI4\n            in \n             nat (changes_itv_smods_ext 0 1 gc1 (pderiv gc1)\n                + changes_itv_smods_ext 0 1 gc2 (pderiv gc2)\n                + changes_itv_smods_ext 0 1 gc3 (pderiv gc3)\n                + changes_itv_smods_ext 0 1 gc4 (pderiv gc4)\n                ) )\" (is \"?L=?R\")\nproof -  \n  have \"proots_rect_border p lb ub =  proots_line p lb (Complex (Re ub) (Im lb)) \n                      +  proots_line p (Complex (Re ub) (Im lb)) ub \n                      +  proots_line p ub (Complex (Re lb) (Im ub)) \n                      +  proots_line p (Complex (Re lb) (Im ub)) lb\"\n    apply (rule proots_rect_border_eq_lines)\n    by fact+\n  also have \"... = ?R\"\n  proof -\n    define p1 pR1 pI1 gc1 C1 where pp1:\n      \"p1 = pcompose p [:lb,  Complex (Re ub - Re lb) 0:]\"\n      \"pR1 = map_poly Re p1\" \n      \"pI1 = map_poly Im p1\"\n      \"gc1 = gcd pR1 pI1\"\n      and \n      \"C1=changes_itv_smods_ext 0 1 gc1 (pderiv gc1)\"\n    define p2 pR2 pI2 gc2 C2 where pp2:\n      \"p2 = pcompose p [:Complex (Re ub) (Im lb), Complex 0 (Im ub - Im lb):]\"\n      \"pR2 = map_poly Re p2\" \n      \"pI2 = map_poly Im p2\"\n      \"gc2 = gcd pR2 pI2\"\n      and \n      \"C2=changes_itv_smods_ext 0 1 gc2 (pderiv gc2)\"\n    define p3 pR3 pI3 gc3 C3 where pp3:\n      \"p3 =pcompose p [:ub, Complex (Re lb - Re ub) 0:]\"\n      \"pR3 = map_poly Re p3\" \n      \"pI3 = map_poly Im p3\"\n      \"gc3 = gcd pR3 pI3\"\n      and \n      \"C3=changes_itv_smods_ext 0 1 gc3 (pderiv gc3)\"\n    define p4 pR4 pI4 gc4 C4 where pp4:\n      \"p4 = pcompose p [:Complex (Re lb) (Im ub), Complex 0 (Im lb - Im ub):]\"\n      \"pR4 = map_poly Re p4\" \n      \"pI4 = map_poly Im p4\"\n      \"gc4 = gcd pR4 pI4\"\n      and \n      \"C4=changes_itv_smods_ext 0 1 gc4 (pderiv gc4)\"\n\n    have  \"poly gc1 0 \\<noteq>0\" \"poly gc1 1\\<noteq>0\"\n          \"poly gc2 0 \\<noteq>0\" \"poly gc2 1\\<noteq>0\"\n          \"poly gc3 0 \\<noteq>0\" \"poly gc3 1\\<noteq>0\"\n          \"poly gc4 0 \\<noteq>0\" \"poly gc4 1\\<noteq>0\"\n      unfolding pp1 pp2 pp3 pp4 poly_gcd_0_iff\n      using not_van[unfolded not_rect_vanishing_def]\n      by (simp flip:Re_poly_of_real Im_poly_of_real add:poly_pcompose\n              ; simp add: Complex_eq_iff zero_complex.code plus_complex.code)+\n\n    have \"proots_line p lb (Complex (Re ub) (Im lb)) = nat C1\"\n      apply (subst proots_line_smods)\n      using not_van assms(1,2)  \n      unfolding not_rect_vanishing_def C1_def pp1 Let_def\n      by (simp_all add:Complex_eq_iff Complex_minus_eq)\n    moreover have \"proots_line p (Complex (Re ub) (Im lb)) ub = nat C2\"\n      apply (subst proots_line_smods)\n      using not_van assms(1,2)  \n      unfolding not_rect_vanishing_def C2_def pp2 Let_def\n      by (simp_all add:Complex_eq_iff Complex_minus_eq)\n    moreover have \"proots_line p ub (Complex (Re lb) (Im ub))  = nat C3\"\n      apply (subst proots_line_smods)\n      using not_van assms(1,2)  \n      unfolding not_rect_vanishing_def C3_def pp3 Let_def\n      by (simp_all add:Complex_eq_iff Complex_minus_eq)\n    moreover have \"proots_line p (Complex (Re lb) (Im ub)) lb = nat C4\"\n      apply (subst proots_line_smods)\n      using not_van assms(1,2)  \n      unfolding not_rect_vanishing_def C4_def pp4 Let_def\n      by (simp_all add:Complex_eq_iff Complex_minus_eq)\n    moreover have \"C1 \\<ge>0\" \"C2 \\<ge>0\" \"C3 \\<ge>0\" \"C4\\<ge>0\"\n      unfolding C1_def C2_def C3_def C4_def\n      by (rule changes_itv_smods_ext_geq_0;(fact|simp))+\n    ultimately have \"proots_line p lb (Complex (Re ub) (Im lb)) \n                    + proots_line p (Complex (Re ub) (Im lb)) ub \n                    + proots_line p ub (Complex (Re lb) (Im ub)) \n                    + proots_line p (Complex (Re lb) (Im ub)) lb \n                      = nat (C1+C2+C3+C4)\"\n      by linarith\n    also have \"...  = ?R\"\n      unfolding C1_def C2_def C3_def C4_def pp1 pp2 pp3 pp4 Let_def\n      by simp\n    finally show ?thesis .\n  qed\n  finally show ?thesis .\nqed\n\nlemma proots_rect_smods:\n  assumes \"Re lb < Re ub\" \"Im lb < Im ub\" \n    and not_van:\"not_rect_vanishing p lb ub\"\n  shows \"proots_rect p lb ub = (\n            let p1 = pcompose p [:lb,  Complex (Re ub - Re lb) 0:];\n                pR1 = map_poly Re p1; pI1 = map_poly Im p1; gc1 = gcd pR1 pI1;\n                p2 = pcompose p [:Complex (Re ub) (Im lb), Complex 0 (Im ub - Im lb):];\n                pR2 = map_poly Re p2; pI2 = map_poly Im p2; gc2 = gcd pR2 pI2;\n                p3 = pcompose p [:ub, Complex (Re lb - Re ub) 0:];\n                pR3 = map_poly Re p3; pI3 = map_poly Im p3; gc3 = gcd pR3 pI3;\n                p4 = pcompose p [:Complex (Re lb) (Im ub), Complex 0 (Im lb - Im ub):];\n                pR4 = map_poly Re p4; pI4 = map_poly Im p4; gc4 = gcd pR4 pI4\n            in \n              nat (- (changes_alt_itv_smods 0 1 (pR1 div gc1) (pI1 div gc1)\n                + changes_alt_itv_smods 0 1 (pR2 div gc2) (pI2 div gc2)\n                + changes_alt_itv_smods 0 1 (pR3 div gc3) (pI3 div gc3)\n                + changes_alt_itv_smods 0 1 (pR4 div gc4) (pI4 div gc4)\n                + 2*changes_itv_smods_ext 0 1 gc1 (pderiv gc1)\n                + 2*changes_itv_smods_ext 0 1 gc2 (pderiv gc2)\n                + 2*changes_itv_smods_ext 0 1 gc3 (pderiv gc3)\n                + 2*changes_itv_smods_ext 0 1 gc4 (pderiv gc4))  div 4)\n            )\"\nproof -\n  define p1 pR1 pI1 gc1 C1 D1 where pp1:\n        \"p1 = pcompose p [:lb,  Complex (Re ub - Re lb) 0:]\"\n        \"pR1 = map_poly Re p1\" \n        \"pI1 = map_poly Im p1\"\n        \"gc1 = gcd pR1 pI1\"\n    and \"C1=changes_itv_smods_ext 0 1 gc1 (pderiv gc1)\"\n    and \"D1=changes_alt_itv_smods 0 1 (pR1 div gc1) (pI1 div gc1)\"\n  define p2 pR2 pI2 gc2 C2 D2 where pp2:\n        \"p2 = pcompose p [:Complex (Re ub) (Im lb), Complex 0 (Im ub - Im lb):]\"\n        \"pR2 = map_poly Re p2\" \n        \"pI2 = map_poly Im p2\"\n        \"gc2 = gcd pR2 pI2\"\n    and \"C2=changes_itv_smods_ext 0 1 gc2 (pderiv gc2)\"\n    and \"D2=changes_alt_itv_smods 0 1 (pR2 div gc2) (pI2 div gc2)\"\n  define p3 pR3 pI3 gc3 C3 D3 where pp3:\n        \"p3 =pcompose p [:ub, Complex (Re lb - Re ub) 0:]\"\n        \"pR3 = map_poly Re p3\" \n        \"pI3 = map_poly Im p3\"\n        \"gc3 = gcd pR3 pI3\"\n    and \"C3=changes_itv_smods_ext 0 1 gc3 (pderiv gc3)\"\n    and \"D3=changes_alt_itv_smods 0 1 (pR3 div gc3) (pI3 div gc3)\"\n  define p4 pR4 pI4 gc4 C4 D4 where pp4:\n        \"p4 = pcompose p [:Complex (Re lb) (Im ub), Complex 0 (Im lb - Im ub):]\"\n        \"pR4 = map_poly Re p4\" \n        \"pI4 = map_poly Im p4\"\n        \"gc4 = gcd pR4 pI4\"\n    and \"C4=changes_itv_smods_ext 0 1 gc4 (pderiv gc4)\"\n    and \"D4=changes_alt_itv_smods 0 1 (pR4 div gc4) (pI4 div gc4)\"\n  have \"poly gc1 0 \\<noteq>0\" \"poly gc1 1\\<noteq>0\"\n          \"poly gc2 0 \\<noteq>0\" \"poly gc2 1\\<noteq>0\"\n          \"poly gc3 0 \\<noteq>0\" \"poly gc3 1\\<noteq>0\"\n          \"poly gc4 0 \\<noteq>0\" \"poly gc4 1\\<noteq>0\"\n      unfolding pp1 pp2 pp3 pp4 poly_gcd_0_iff\n      using not_van[unfolded not_rect_vanishing_def]\n      by (simp flip:Re_poly_of_real Im_poly_of_real add:poly_pcompose\n              ; simp add: Complex_eq_iff zero_complex.code plus_complex.code)+\n  have \"C1\\<ge>0\" \"C2\\<ge>0\" \"C3\\<ge>0\" \"C4\\<ge>0\"\n    unfolding C1_def C2_def C3_def C4_def\n    by (rule changes_itv_smods_ext_geq_0;(fact|simp))+\n  \n  define CC DD where \"CC=C1 + C2 + C3 + C4\"\n                 and \"DD=D1 + D2 + D3 + D4\"\n\n  have \"real (proots_rect p lb ub) = - (real (proots_rect_border p lb ub) \n                                        + cindexP_pathE p (rectpath lb ub)) / 2\"\n    apply (rule proots_rect_cindexP_pathE)\n    by fact+\n  also have \"... =  -(nat CC +  DD / 2) / 2\"\n  proof -\n    have \"proots_rect_border p lb ub = nat CC\" \n      apply (rule proots_rect_border_smods[\n          of lb ub p,\n          unfolded Let_def, \n          folded pp1 pp2 pp3 pp4,\n          folded C1_def C2_def C3_def C4_def,\n          folded CC_def])\n      by fact+\n    moreover have \"cindexP_pathE p (rectpath lb ub) = (real_of_int DD) / 2\"\n      apply (rule cindexP_pathE_rect_smods[\n          of lb ub p, \n          unfolded Let_def,\n          folded pp1 pp2 pp3 pp4, \n          folded D1_def D2_def D3_def D4_def,\n          folded DD_def])\n      by fact+\n    ultimately show ?thesis by auto\n  qed\n  also have \"... = - (DD + 2*CC) /4\"\n    by (simp add: CC_def \\<open>0 \\<le> C1\\<close> \\<open>0 \\<le> C2\\<close> \\<open>0 \\<le> C3\\<close> \\<open>0 \\<le> C4\\<close>)\n  finally have \"real (proots_rect p lb ub) \n                  = real_of_int (- (DD + 2 * CC)) / 4\" .\n  then have  \"proots_rect p lb ub = nat (- (DD + 2 * CC) div 4)\"\n    by simp\n  then show ?thesis unfolding Let_def\n    apply (fold pp1 pp2 pp3 pp4)\n    apply (fold  C1_def C2_def C3_def C4_def D1_def D2_def D3_def D4_def)\n    by (simp add:CC_def DD_def)\nqed\n\n\nlemma proots_rect_code[code]:\n  \"proots_rect p lb ub = \n          (if Re lb < Re ub \\<and> Im lb < Im ub then\n            if not_rect_vanishing p lb ub then\n            (\n            let p1 = pcompose p [:lb,  Complex (Re ub - Re lb) 0:];\n                pR1 = map_poly Re p1; pI1 = map_poly Im p1; gc1 = gcd pR1 pI1;\n                p2 = pcompose p [:Complex (Re ub) (Im lb), Complex 0 (Im ub - Im lb):];\n                pR2 = map_poly Re p2; pI2 = map_poly Im p2; gc2 = gcd pR2 pI2;\n                p3 = pcompose p [:ub, Complex (Re lb - Re ub) 0:];\n                pR3 = map_poly Re p3; pI3 = map_poly Im p3; gc3 = gcd pR3 pI3;\n                p4 = pcompose p [:Complex (Re lb) (Im ub), Complex 0 (Im lb - Im ub):];\n                pR4 = map_poly Re p4; pI4 = map_poly Im p4; gc4 = gcd pR4 pI4\n            in \n              nat (- (changes_alt_itv_smods 0 1 (pR1 div gc1) (pI1 div gc1)\n                + changes_alt_itv_smods 0 1 (pR2 div gc2) (pI2 div gc2)\n                + changes_alt_itv_smods 0 1 (pR3 div gc3) (pI3 div gc3)\n                + changes_alt_itv_smods 0 1 (pR4 div gc4) (pI4 div gc4)\n                + 2*changes_itv_smods_ext 0 1 gc1 (pderiv gc1)\n                + 2*changes_itv_smods_ext 0 1 gc2 (pderiv gc2)\n                + 2*changes_itv_smods_ext 0 1 gc3 (pderiv gc3)\n                + 2*changes_itv_smods_ext 0 1 gc4 (pderiv gc4))  div 4)\n            )\n          else Code.abort (STR ''proots_rect: the polynomial should not vanish \n                  at the four vertices for now'') (\\<lambda>_. proots_rect p lb ub)\n        else 0)\"\nproof (cases \"Re lb < Re ub \\<and> Im lb < Im ub \\<and> not_rect_vanishing p lb ub\")\n  case False\n  have ?thesis if \"\\<not> (Re lb < Re ub) \\<or> \\<not> ( Im lb < Im ub)\"\n  proof -\n    have \"box lb ub = {}\" using that by (metis complex_box_ne_empty(2))\n    then show ?thesis \n      unfolding proots_rect_def \n      using proots_count_emtpy that by fastforce\n  qed\n  then show ?thesis using False by auto\nnext\n  case True\n  then show ?thesis \n    apply (subst proots_rect_smods)\n    unfolding Let_def by simp_all\nqed\n\nlemma proots_rect_ll_rect:\n  assumes \"Re lb < Re ub\" \"Im lb < Im ub\" \n    and not_van:\"not_rect_vanishing p lb ub\"\n  shows \"proots_rect_ll p lb ub = proots_rect p lb ub \n                                    + proots_line p lb (Complex (Re ub) (Im lb))\n                                    + proots_line p lb (Complex (Re lb) (Im ub))  \n                                    \"\nproof -\n  have \"p\\<noteq>0\" \n    using not_rect_vanishing_def not_van order_root by blast\n\n  define l1 l4 where  \"l1 = open_segment lb (Complex (Re ub) (Im lb))\"\n                  and \"l4 = open_segment lb (Complex (Re lb) (Im ub)) \"\n  have ll_eq:\n    \"l1 = {z. Im z \\<in> {Im lb} \\<and> Re z \\<in> {Re lb<..<Re ub}}\"\n    \"l4 = {z. Re z \\<in> {Re lb} \\<and> Im z \\<in> {Im lb<..<Im ub}}\"\n    subgoal unfolding l1_def\n      apply (subst open_segment_Im_equal)\n      using assms unfolding open_segment_eq_real_ivl by auto\n    subgoal unfolding l4_def\n      apply (subst open_segment_Re_equal)\n      using assms unfolding open_segment_eq_real_ivl by auto\n    done\n  \n  have ll_disj: \"l1 \\<inter> l4 = {}\" \"box lb ub \\<inter> {lb} = {}\"\n    \"box lb ub \\<inter> l1 = {}\" \"box lb ub \\<inter> l4 = {}\"\n    \"l1 \\<inter> {lb} = {}\" \"l4 \\<inter> {lb} = {}\"\n    using assms unfolding ll_eq \n    by (auto simp:in_box_complex_iff)\n\n  have \"proots_rect_ll p lb ub = proots_count p (box lb ub) \n                                    + proots_count p {lb}\n                                    + proots_count p l1 \n                                    + proots_count p l4\"\n    unfolding proots_rect_ll_def using ll_disj \\<open>p\\<noteq>0\\<close>\n    apply (fold l1_def l4_def)\n    by (subst proots_count_union_disjoint\n            ;(simp add:Int_Un_distrib Int_Un_distrib2 del: Un_insert_right)?)+\n  also have \"... = proots_rect p lb ub \n                      + proots_line p lb (Complex (Re ub) (Im lb))\n                      + proots_line p lb (Complex (Re lb) (Im ub)) \"\n  proof -\n    have \"proots_count p {lb} = 0\" \n      by (metis not_rect_vanishing_def not_van proots_count_nzero singleton_iff)\n    then show ?thesis\n      unfolding proots_rect_def l1_def l4_def proots_line_def by simp\n  qed\n  finally show ?thesis .\nqed\n\nlemma proots_rect_ll_smods:\n  assumes \"Re lb < Re ub\" \"Im lb < Im ub\" \n    and not_van:\"not_rect_vanishing p lb ub\"\n  shows \"proots_rect_ll p lb ub = (\n            let p1 = pcompose p [:lb,  Complex (Re ub - Re lb) 0:];\n                pR1 = map_poly Re p1; pI1 = map_poly Im p1; gc1 = gcd pR1 pI1;\n                p2 = pcompose p [:Complex (Re ub) (Im lb), Complex 0 (Im ub - Im lb):];\n                pR2 = map_poly Re p2; pI2 = map_poly Im p2; gc2 = gcd pR2 pI2;\n                p3 = pcompose p [:ub, Complex (Re lb - Re ub) 0:];\n                pR3 = map_poly Re p3; pI3 = map_poly Im p3; gc3 = gcd pR3 pI3;\n                p4 = pcompose p [:Complex (Re lb) (Im ub), Complex 0 (Im lb - Im ub):];\n                pR4 = map_poly Re p4; pI4 = map_poly Im p4; gc4 = gcd pR4 pI4\n            in \n              nat (- (changes_alt_itv_smods 0 1 (pR1 div gc1) (pI1 div gc1)\n                + changes_alt_itv_smods 0 1 (pR2 div gc2) (pI2 div gc2)\n                + changes_alt_itv_smods 0 1 (pR3 div gc3) (pI3 div gc3)\n                + changes_alt_itv_smods 0 1 (pR4 div gc4) (pI4 div gc4)\n                - 2*changes_itv_smods_ext 0 1 gc1 (pderiv gc1)\n                + 2*changes_itv_smods_ext 0 1 gc2 (pderiv gc2)\n                + 2*changes_itv_smods_ext 0 1 gc3 (pderiv gc3)\n                - 2*changes_itv_smods_ext 0 1 gc4 (pderiv gc4)) div 4))\"\nproof -\n  have \"p\\<noteq>0\" \n    using not_rect_vanishing_def not_van order_root by blast\n\n  define l1 l4 where  \"l1 = open_segment lb (Complex (Re ub) (Im lb))\"\n                  and \"l4 = open_segment lb (Complex (Re lb) (Im ub))\"\n  have l4_alt:\"l4 = open_segment (Complex (Re lb) (Im ub)) lb \"\n    unfolding l4_def by (simp add: open_segment_commute)\n\n  have ll_eq:\n    \"l1 = {z. Im z \\<in> {Im lb} \\<and> Re z \\<in> {Re lb<..<Re ub}}\"\n    \"l4 = {z. Re z \\<in> {Re lb} \\<and> Im z \\<in> {Im lb<..<Im ub}}\"\n    subgoal unfolding l1_def\n      apply (subst open_segment_Im_equal)\n      using assms unfolding open_segment_eq_real_ivl by auto\n    subgoal unfolding l4_def\n      apply (subst open_segment_Re_equal)\n      using assms unfolding open_segment_eq_real_ivl by auto\n    done\n  \n  have ll_disj: \"l1 \\<inter> l4 = {}\" \"box lb ub \\<inter> {lb} = {}\"\n    \"box lb ub \\<inter> l1 = {}\" \"box lb ub \\<inter> l4 = {}\"\n    \"l1 \\<inter> {lb} = {}\" \"l4 \\<inter> {lb} = {}\"\n    using assms unfolding ll_eq \n    by (auto simp:in_box_complex_iff)\n\n  define p1 pR1 pI1 gc1 C1 D1 where pp1:\n        \"p1 = pcompose p [:lb,  Complex (Re ub - Re lb) 0:]\"\n        \"pR1 = map_poly Re p1\" \n        \"pI1 = map_poly Im p1\"\n        \"gc1 = gcd pR1 pI1\"\n    and \"C1=changes_itv_smods_ext 0 1 gc1 (pderiv gc1)\"\n    and \"D1=changes_alt_itv_smods 0 1 (pR1 div gc1) (pI1 div gc1)\"\n  define p2 pR2 pI2 gc2 C2 D2 where pp2:\n        \"p2 = pcompose p [:Complex (Re ub) (Im lb), Complex 0 (Im ub - Im lb):]\"\n        \"pR2 = map_poly Re p2\" \n        \"pI2 = map_poly Im p2\"\n        \"gc2 = gcd pR2 pI2\"\n    and \"C2=changes_itv_smods_ext 0 1 gc2 (pderiv gc2)\"\n    and \"D2=changes_alt_itv_smods 0 1 (pR2 div gc2) (pI2 div gc2)\"\n  define p3 pR3 pI3 gc3 C3 D3 where pp3:\n        \"p3 =pcompose p [:ub, Complex (Re lb - Re ub) 0:]\"\n        \"pR3 = map_poly Re p3\" \n        \"pI3 = map_poly Im p3\"\n        \"gc3 = gcd pR3 pI3\"\n    and \"C3=changes_itv_smods_ext 0 1 gc3 (pderiv gc3)\"\n    and \"D3=changes_alt_itv_smods 0 1 (pR3 div gc3) (pI3 div gc3)\"\n  define p4 pR4 pI4 gc4 C4 D4 where pp4:\n        \"p4 = pcompose p [:Complex (Re lb) (Im ub), Complex 0 (Im lb - Im ub):]\"\n        \"pR4 = map_poly Re p4\" \n        \"pI4 = map_poly Im p4\"\n        \"gc4 = gcd pR4 pI4\"\n    and \"C4=changes_itv_smods_ext 0 1 gc4 (pderiv gc4)\"\n    and \"D4=changes_alt_itv_smods 0 1 (pR4 div gc4) (pI4 div gc4)\"\n  have \"poly gc1 0 \\<noteq>0\" \"poly gc1 1\\<noteq>0\"\n          \"poly gc2 0 \\<noteq>0\" \"poly gc2 1\\<noteq>0\"\n          \"poly gc3 0 \\<noteq>0\" \"poly gc3 1\\<noteq>0\"\n          \"poly gc4 0 \\<noteq>0\" \"poly gc4 1\\<noteq>0\"\n      unfolding pp1 pp2 pp3 pp4 poly_gcd_0_iff\n      using not_van[unfolded not_rect_vanishing_def]\n      by (simp flip:Re_poly_of_real Im_poly_of_real add:poly_pcompose\n              ; simp add: Complex_eq_iff zero_complex.code plus_complex.code)+\n  have CC_pos:\"C1\\<ge>0\" \"C2\\<ge>0\" \"C3\\<ge>0\" \"C4\\<ge>0\"\n    unfolding C1_def C2_def C3_def C4_def\n    by (rule changes_itv_smods_ext_geq_0;(fact|simp))+\n  \n  define CC DD where \"CC= C2 + C3 - C4 - C1\"\n                 and \"DD=D1 + D2 + D3 + D4\"\n\n  define p1 p2 p3 p4 where pp:\"p1=proots_line p lb (Complex (Re ub) (Im lb))\" \n                              \"p2 = proots_line p (Complex (Re ub) (Im lb)) ub\"\n                              \"p3 = proots_line p ub (Complex (Re lb) (Im ub))\"\n                              \"p4 = proots_line p (Complex (Re lb) (Im ub)) lb\"\n  have p4_alt:\"p4 = proots_line p lb (Complex (Re lb) (Im ub))\"\n    unfolding pp by (simp add: proots_line_commute)\n  \n\n  have \"real (proots_rect_ll p lb ub) = real (proots_rect p lb ub) + p1 + p4\"\n    unfolding pp by (simp add: proots_rect_ll_rect[OF assms]  proots_line_commute)\n  also have \"... = (p1 + p4 - real p2 - real p3 - cindexP_pathE p (rectpath lb ub)) /  2\"\n  proof -\n    have \"real (proots_rect p lb ub) = - (real (proots_rect_border p lb ub) \n                                        + cindexP_pathE p (rectpath lb ub)) / 2\"\n      apply (rule proots_rect_cindexP_pathE)\n      by fact+\n    also have \"... = - (p1 + p2 + p3 + p4 + cindexP_pathE p (rectpath lb ub)) / 2\"\n      using proots_rect_border_eq_lines[OF assms,folded pp] by simp\n    finally have \"real (proots_rect p lb ub) =\n                      - (real (p1 + p2 + p3 + p4) \n                          + cindexP_pathE p (rectpath lb ub)) / 2\" .\n    then show ?thesis by auto\n  qed\n  also have \"... = (nat C1 + nat C4 - real (nat C2) - real (nat C3)\n                       - ((real_of_int DD) / 2)) /  2\"\n  proof -\n    have \"p1 = nat C1\" \"p2 = nat C2\" \"p3 = nat C3\" \"p4 = nat C4\"\n      using not_van[unfolded not_rect_vanishing_def]  assms(1,2)\n      unfolding pp C1_def pp1 C2_def pp2 C3_def pp3 C4_def pp4\n      by (subst proots_line_smods\n          ;simp_all add:Complex_eq_iff Let_def Complex_minus_eq)+\n    moreover have \"cindexP_pathE p (rectpath lb ub) = (real_of_int DD) / 2\"\n      apply (rule cindexP_pathE_rect_smods[\n          of lb ub p, \n          unfolded Let_def,\n          folded pp1 pp2 pp3 pp4, \n          folded D1_def D2_def D3_def D4_def,\n          folded DD_def])\n      by fact+\n    ultimately show ?thesis by presburger\n  qed\n  also have \"... = -(DD + 2*CC) / 4\"\n    unfolding CC_def using CC_pos by (auto simp add:divide_simps algebra_simps)\n  finally have \"real (proots_rect_ll p lb ub) \n                        = real_of_int (- (DD + 2 * CC)) / 4\" .\n  then have \"proots_rect_ll p lb ub\n                        = nat (- (DD + 2 * CC) div 4)\"\n    by simp\n  then show ?thesis\n    unfolding Let_def\n    apply (fold pp1 pp2 pp3 pp4)\n    apply (fold  C1_def C2_def C3_def C4_def D1_def D2_def D3_def D4_def)\n    by (simp add:CC_def DD_def)\nqed\n\nlemma proots_rect_ll_code[code]:\n  \"proots_rect_ll p lb ub = \n          (if Re lb < Re ub \\<and> Im lb < Im ub then\n            if not_rect_vanishing p lb ub then\n            (\n            let p1 = pcompose p [:lb,  Complex (Re ub - Re lb) 0:];\n                pR1 = map_poly Re p1; pI1 = map_poly Im p1; gc1 = gcd pR1 pI1;\n                p2 = pcompose p [:Complex (Re ub) (Im lb), Complex 0 (Im ub - Im lb):];\n                pR2 = map_poly Re p2; pI2 = map_poly Im p2; gc2 = gcd pR2 pI2;\n                p3 = pcompose p [:ub, Complex (Re lb - Re ub) 0:];\n                pR3 = map_poly Re p3; pI3 = map_poly Im p3; gc3 = gcd pR3 pI3;\n                p4 = pcompose p [:Complex (Re lb) (Im ub), Complex 0 (Im lb - Im ub):];\n                pR4 = map_poly Re p4; pI4 = map_poly Im p4; gc4 = gcd pR4 pI4\n            in \n              nat (- (changes_alt_itv_smods 0 1 (pR1 div gc1) (pI1 div gc1)\n                + changes_alt_itv_smods 0 1 (pR2 div gc2) (pI2 div gc2)\n                + changes_alt_itv_smods 0 1 (pR3 div gc3) (pI3 div gc3)\n                + changes_alt_itv_smods 0 1 (pR4 div gc4) (pI4 div gc4)\n                - 2*changes_itv_smods_ext 0 1 gc1 (pderiv gc1)\n                + 2*changes_itv_smods_ext 0 1 gc2 (pderiv gc2)\n                + 2*changes_itv_smods_ext 0 1 gc3 (pderiv gc3)\n                - 2*changes_itv_smods_ext 0 1 gc4 (pderiv gc4))  div 4)\n            )\n          else Code.abort (STR ''proots_rect_ll: the polynomial should not vanish \n                  at the four vertices for now'') (\\<lambda>_. proots_rect_ll p lb ub)\n        else Code.abort (STR ''proots_rect_ll: the box is improper'') \n                (\\<lambda>_. proots_rect_ll p lb ub))\"\nproof (cases \"Re lb < Re ub \\<and> Im lb < Im ub \\<and> not_rect_vanishing p lb ub\")\n  case False\n  then show ?thesis using False by auto\nnext\n  case True\n  then show ?thesis \n    apply (subst proots_rect_ll_smods)\n    unfolding Let_def by simp_all\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/Count_Complex_Roots/Count_Rectangle.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8774767906859264, "lm_q2_score": 0.8221891239865619, "lm_q1q2_score": 0.7214518738526016}}
{"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\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\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/Grothendieck_Schemes/Topological_Space.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8774767810736692, "lm_q2_score": 0.8221891239865619, "lm_q1q2_score": 0.7214518659495082}}
{"text": "(* License: LGPL *)\n\ntheory Expected_Utility\nimports\n  Neumann_Morgenstern_Utility_Theorem\nbegin\n\nsection \\<open> Definition of vNM-utility function \\<close>\n\ntext \\<open> We define a version of the vNM Utility function using the locale mechanism. \n       Currently this definition and system U have no proven relation yet. \\<close>\n\ntext \\<open> Important: u is actually not the von Neuman Utility Function, \n       but a Bernoulli Utility Function. The Expected value p \n       given u is the von Neumann Utility Function. \\<close>\n\nlocale vNM_utility =\n  fixes outcomes :: \"'a set\"\n  fixes relation :: \"'a pmf relation\"\n  fixes u :: \"'a \\<Rightarrow> real\"\n  assumes \"relation \\<subseteq> (lotteries_on outcomes \\<times> lotteries_on outcomes)\"\n  assumes \"\\<And>p q.  p \\<in> lotteries_on outcomes \\<Longrightarrow> \n                  q \\<in> lotteries_on outcomes \\<Longrightarrow> \n        p \\<succeq>[relation] q \\<longleftrightarrow> measure_pmf.expectation p u \\<ge> measure_pmf.expectation q u\"\nbegin\n\nlemma vNM_utilityD:\n  shows \"relation \\<subseteq> (lotteries_on outcomes \\<times> lotteries_on outcomes)\"\n    and \"p \\<in> lotteries_on outcomes \\<Longrightarrow> q \\<in> lotteries_on outcomes \\<Longrightarrow> \n    p \\<succeq>[relation] q \\<longleftrightarrow> measure_pmf.expectation p u \\<ge> measure_pmf.expectation q u\"\n  using vNM_utility_axioms vNM_utility_def by (blast+)\n\nlemma not_outside:\n  assumes \"p \\<succeq>[relation] q\"\n  shows \"p \\<in> lotteries_on outcomes\"\n    and \"q \\<in> lotteries_on outcomes\"\nproof (goal_cases)\n  case 1\n  then show ?case\n    by (meson assms contra_subsetD mem_Sigma_iff vNM_utility_axioms vNM_utility_def)\nnext\n  case 2\n  then show ?case\n    by (metis assms mem_Sigma_iff subsetCE vNM_utility_axioms vNM_utility_def)\nqed\n\nlemma utility_ge:\n  assumes \"p \\<succeq>[relation] q\"\n  shows \"measure_pmf.expectation p u \\<ge> measure_pmf.expectation q u\"\n  using assms vNM_utility_axioms vNM_utility_def\n  by (metis (no_types, lifting) not_outside(1) not_outside(2))\n\nend (* vNM_Utility *)\n\nsublocale vNM_utility \\<subseteq> ordinal_utility \"(lotteries_on outcomes)\" relation \"(\\<lambda>p. measure_pmf.expectation p u)\"\nproof (standard, goal_cases)\n  case (2 x y)\n  then show ?case\n    using not_outside(1) by blast\nnext\n  case (3 x y)\n  then show ?case \n    by (auto simp add: not_outside(2))\nqed (metis (mono_tags, lifting) vNM_utility_axioms vNM_utility_def)\n\ncontext vNM_utility\nbegin\n\nlemma strict_preference_iff_strict_utility:\n assumes \"p \\<in> lotteries_on outcomes\" \n assumes \"q \\<in> lotteries_on outcomes\"\n shows \"p \\<succ>[relation] q \\<longleftrightarrow> measure_pmf.expectation p u > measure_pmf.expectation q u\"\n  by (meson assms(1) assms(2) less_eq_real_def not_le util_def)\n\nlemma pos_distrib_left:\n  assumes \"c > 0\"\n  shows \"(\\<Sum>z\\<in>outcomes. pmf q z * (c * u z)) = c * (\\<Sum>z\\<in>outcomes. pmf q z * (u z))\"\nproof -\n  have \"(\\<Sum>z\\<in>outcomes. pmf q z * (c * u z)) = (\\<Sum>z\\<in>outcomes. pmf q z * c * u z)\"\n    by (simp add: ab_semigroup_mult_class.mult_ac(1))\n  also have \"... = (\\<Sum>z\\<in>outcomes. c * pmf q z *  u z)\"\n    by (simp add: mult.commute)\n  also have \"... = c * (\\<Sum>z\\<in>outcomes. pmf q z *  u z)\"\n    by (simp add: ab_semigroup_mult_class.mult_ac(1) sum_distrib_left)\n  finally show ?thesis .\nqed\n\n\n\n\n\nsection \\<open> Finite outcomes \\<close>\ncontext\n  assumes fnt: \"finite outcomes\"\nbegin\n\nlemma sum_equals_pmf_expectation:\n  assumes \"p \\<in> lotteries_on outcomes\"\n  shows\"(\\<Sum>z\\<in>outcomes. (pmf p z) * (u z)) = measure_pmf.expectation p u\"\nproof -\n  have fnt: \"finite outcomes\"\n    by (simp add: vNM_utilityD(1) fnt)\n  have \"measure_pmf.expectation p u = (\\<Sum>a\\<in>outcomes. pmf p a * u a)\"\n    using support_in_outcomes assms fnt integral_measure_pmf_real\n      sum_pmf_util_commute by fastforce\n  then show ?thesis\n    using real_scaleR_def by presburger\nqed\n\nlemma expected_utility_weak_preference:\n  assumes \"p \\<in> lotteries_on outcomes\" \n    and \"q \\<in> lotteries_on outcomes\"\n  shows   \"p \\<succeq>[relation] q \\<longleftrightarrow> (\\<Sum>z\\<in>outcomes. (pmf p z) * (u z)) \\<ge> (\\<Sum>z\\<in>outcomes. (pmf q z) * (u z))\"\n  using sum_equals_pmf_expectation[of p, OF assms(1)] \n        sum_equals_pmf_expectation[of q, OF assms(2)]\n   vNM_utility_def assms(1) assms(2) util_def_conf by presburger\n\nlemma diff_leq_zero_weak_preference:\n  assumes \"p \\<in> lotteries_on outcomes\"\n    and \"q \\<in> lotteries_on outcomes\"\n  shows \"p \\<succeq> q \\<longleftrightarrow> ((\\<Sum>a\\<in>outcomes. pmf q a * u a) - (\\<Sum>a\\<in>outcomes. pmf p a * u a) \\<le> 0)\"\n  using assms(1) assms(2) diff_le_0_iff_le\n  by (metis (mono_tags, lifting) expected_utility_weak_preference)\n\nlemma expected_utility_strict_preference:\n  assumes \"p \\<in> lotteries_on outcomes\" \n    and \"q \\<in> lotteries_on outcomes\"\n  shows   \"p \\<succ>[relation] q \\<longleftrightarrow> measure_pmf.expectation p u > measure_pmf.expectation q u\"\n  using assms expected_utility_weak_preference less_eq_real_def not_le\n  by (metis (no_types, lifting) util_def_conf)\n\nlemma scale_pos_left: \n  assumes \"c > 0\" \n  shows \"vNM_utility outcomes relation (\\<lambda>x. c * u x)\"\nproof(standard, goal_cases)\n  case 1\n  then show ?case\n    using vNM_utility_axioms vNM_utility_def by blast\nnext\n  case (2 p q)\n  have \"q \\<in> lotteries_on outcomes\" and \"p \\<in> lotteries_on outcomes\"\n    using \"2\"(2) by (simp add: fnt \"2\"(1))+\n  then have *: \"p \\<succeq> q = (measure_pmf.expectation q u \\<le> measure_pmf.expectation p u)\"\n    using expected_utility_weak_preference[of p q] assms by blast\n  have dist_c: \"(\\<Sum>z\\<in>outcomes. (pmf q z) * (c * u z)) = c * (\\<Sum>z\\<in>outcomes. (pmf q z) * (u z))\"\n    using pos_distrib_left[of c q] assms by blast\n  have dist_c': \"(\\<Sum>z\\<in>outcomes. (pmf p z) * (c * u z)) = c * (\\<Sum>z\\<in>outcomes. (pmf p z) * (u z))\"\n    using pos_distrib_left[of c p] assms by blast\n  have \"p \\<succeq> q \\<longleftrightarrow> ((\\<Sum>z\\<in>outcomes. (pmf q z) * (c * u z)) \\<le> (\\<Sum>z\\<in>outcomes. (pmf p z) * (c * u z)))\"\n  proof (rule iffI)\n    assume \"p \\<succeq> q\"\n    then have \"(\\<Sum>z\\<in>outcomes. pmf q z * (u z)) \\<le> (\\<Sum>z\\<in>outcomes. pmf p z * (u z))\" \n      using utility_ge\n      using \"2\"(1) \"2\"(2) sum_equals_pmf_expectation by presburger\n    then show \"(\\<Sum>z\\<in>outcomes. pmf q z * (c * u z)) \\<le> (\\<Sum>z\\<in>outcomes. pmf p z * (c * u z))\" \n      using dist_c dist_c'\n      by (simp add: assms)\n  next\n    assume \"(\\<Sum>z\\<in>outcomes. pmf q z * (c * u z)) \\<le> (\\<Sum>z\\<in>outcomes. pmf p z * (c * u z))\"\n    then have \"(\\<Sum>z\\<in>outcomes. pmf q z * (u z)) \\<le> (\\<Sum>z\\<in>outcomes. pmf p z * (u z))\"\n      using \"2\"(1) real_mult_le_cancel_iff2 assms by (simp add: dist_c dist_c')\n    then show \"p \\<succeq> q\"\n      using \"2\"(2) assms \"2\"(1) by (simp add: * sum_equals_pmf_expectation)\n  qed\n  then show ?case\n    by (simp add: \"*\" assms)\nqed\n\nlemma strict_alt_def:\n  assumes \"p \\<in> lotteries_on outcomes\" \n    and \"q \\<in> lotteries_on outcomes\"\n  shows \"p \\<succ>[relation] q \\<longleftrightarrow> \n            (\\<Sum>z\\<in>outcomes. (pmf p z) * (u z)) > (\\<Sum>z\\<in>outcomes. (pmf q z) * (u z))\"\n  using sum_equals_pmf_expectation[of p, OF assms(1)] assms(1) assms(2)\n    sum_equals_pmf_expectation[of q, OF assms(2)] strict_prefernce_iff_strict_utility\n  by presburger\n\nlemma strict_alt_def_utility_g:\n  assumes \"p \\<succ>[relation] q\"\n  shows \"(\\<Sum>z\\<in>outcomes. (pmf p z) * (u z)) > (\\<Sum>z\\<in>outcomes. (pmf q z) * (u z))\"\n  using assms not_outside(1) not_outside(2) strict_alt_def\n  by meson\n\nend (* finite outcomes *)\n\nend (* Definition of vNM Utility Function as locale *)\n\nlemma vnm_utility_is_ordinal_utility:\n  assumes \"vNM_utility outcomes relation u\"\n  shows \"ordinal_utility (lotteries_on outcomes) relation (\\<lambda>p. measure_pmf.expectation p u)\"\nproof (standard, goal_cases)\n  case (1 x y)\n  then show ?case\n    using assms vNM_utility_def by blast\nnext\n  case (2 x y)\n  then show ?case \n    using assms vNM_utility.not_outside(1) by blast\nnext\n  case (3 x y)\n  then show ?case \n    using assms vNM_utility.not_outside(2) by blast\nqed\n\nlemma vnm_utility_imp_reational_prefs:\n  assumes \"vNM_utility outcomes relation u\"\n  shows \"rational_preference (lotteries_on outcomes) relation\"\nproof (standard,goal_cases)\n  case (1 x y)\n  then show ?case\n    using assms vNM_utility.not_outside(1) by blast\nnext\n  case (2 x y)\n  then show ?case\n    using assms vNM_utility.not_outside(2) by blast\nnext\n  case 3\n  have t: \"trans relation\"\n    using assms ordinal_utility.util_imp_trans vnm_utility_is_ordinal_utility by blast\n  have \"refl_on (lotteries_on outcomes) relation\"\n    by (meson assms order_refl refl_on_def vNM_utility_def)\n  then show ?case\n    using preorder_on_def t by blast\nnext\n  case 4\n  have \"total_on (lotteries_on outcomes) relation\"\n    using ordinal_utility.util_imp_total[of \"lotteries_on outcomes\" \n        relation \"(\\<lambda>p. (\\<Sum>z\\<in>outcomes. (pmf p z) * (u z)))\"]\n      assms vnm_utility_is_ordinal_utility\n    using ordinal_utility.util_imp_total by blast\n  then show ?case\n    by simp\nqed\n\ntheorem expected_utilty_theorem_form_vnm_utility:\n  assumes fnt: \"finite outcomes\" and \"outcomes \\<noteq> {}\"\n  shows \"rational_preference (lotteries_on outcomes) \\<R> \\<and> \n         independent_vnm (lotteries_on outcomes) \\<R> \\<and> \n         continuous_vnm (lotteries_on outcomes) \\<R> \\<longleftrightarrow> \n         (\\<exists>u. vNM_utility outcomes \\<R> u)\"\nproof\n  assume \"rational_preference (\\<P> outcomes) \\<R> \\<and> independent_vnm (\\<P> outcomes) \\<R> \\<and> continuous_vnm (\\<P> outcomes) \\<R>\"\n  with Von_Neumann_Morgenstern_Utility_Theorem[of outcomes \\<R>, OF assms] have\n  \"(\\<exists>u. ordinal_utility (\\<P> outcomes) \\<R> (\\<lambda>x. measure_pmf.expectation x u))\" using assms by blast\n  then obtain u where\n    u: \"ordinal_utility (\\<P> outcomes) \\<R> (\\<lambda>x. measure_pmf.expectation x u)\"\n    by auto\n  have \"vNM_utility outcomes \\<R> u\"\n  proof (standard, goal_cases)\n    case 1\n    then show ?case\n      using u ordinal_utility.relation_subset_crossp by blast\n  next\n    case (2 p q)\n    then show ?case\n      using assms(2) expected_value_is_utility_function fnt u by blast\n  qed\n  then show \"\\<exists>u. vNM_utility outcomes \\<R> u\" \n    by blast\nnext\n  assume a: \"\\<exists>u. vNM_utility outcomes \\<R> u\"\n  then have \"rational_preference (\\<P> outcomes) \\<R>\"\n    using vnm_utility_imp_reational_prefs by auto\n  moreover have \"independent_vnm (\\<P> outcomes) \\<R>\"\n    using a by (meson assms(2) fnt vNM_utility_implies_independence vnm_utility_is_ordinal_utility)\n  moreover have \"continuous_vnm (\\<P> outcomes) \\<R>\"\n    using a by (meson assms(2) fnt vNM_utilty_implies_continuity vnm_utility_is_ordinal_utility)\n  ultimately show \"rational_preference (\\<P> outcomes) \\<R> \\<and> independent_vnm (\\<P> outcomes) \\<R> \\<and> continuous_vnm (\\<P> outcomes) \\<R>\"\n    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/Neumann_Morgenstern_Utility/Expected_Utility.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278664544911, "lm_q2_score": 0.8175744828610095, "lm_q1q2_score": 0.7214505065786746}}
{"text": "theory Countable\n  imports ETCS_Axioms ETCS_Add ETCS_Mult ETCS_Exp ETCS_Pred ETCS_Parity ETCS_Comparison\nbegin\n\n\n\n\n\n(* Definition 2.6.9 *)\ndefinition epi_countable :: \"cset \\<Rightarrow> bool\" where\n  \"epi_countable X \\<longleftrightarrow> (\\<exists> f. f : \\<nat>\\<^sub>c \\<rightarrow> X \\<and> epimorphism f)\"\n\nlemma emptyset_is_not_epi_countable:\n  \"\\<not> (epi_countable \\<emptyset>)\"\n  using comp_type emptyset_is_empty epi_countable_def zero_type by blast\n\n\n(* Definition 2.6.9 *)\ndefinition countable :: \"cset \\<Rightarrow> bool\" where\n  \"countable X \\<longleftrightarrow> (\\<exists> f. f : X \\<rightarrow> \\<nat>\\<^sub>c \\<and> monomorphism f)\"\n\nlemma epi_countable_is_countable: \n  assumes \"epi_countable X\"\n  shows \"countable X\"\n  using assms countable_def epi_countable_def epis_give_monos by blast\n\n\n\nlemma emptyset_is_countable:\n  \"countable \\<emptyset>\"\n  using countable_def empty_subset subobject_of_def2 by blast\n\nlemma natural_numbers_are_countably_infinite:\n  \"(countable \\<nat>\\<^sub>c) \\<and> (is_infinite \\<nat>\\<^sub>c)\"\n  by (meson CollectI Peano's_Axioms countable_def injective_imp_monomorphism is_infinite_def successor_type)\n\n\n\n\nlemma smaller_than_countable_is_countable:\n  assumes \"X \\<le>\\<^sub>c Y\" \"countable Y\"\n  shows \"countable X\"\n  by (smt assms cfunc_type_def comp_type composition_of_monic_pair_is_monic countable_def is_smaller_than_def)\n\n\nlemma iso_pres_finite:\n  assumes \"X \\<cong> Y\"\n  assumes \"is_finite(X)\"\n  shows \"is_finite(Y)\"\n  using assms is_isomorphic_def is_smaller_than_def iso_imp_epi_and_monic isomorphic_is_symmetric smaller_than_finite_is_finite by blast\n\n\nlemma iso_pres_countable:\n  assumes \"X \\<cong> Y\" \"countable Y\"\n  shows \"countable X\"\n  using assms(1) assms(2) is_isomorphic_def is_smaller_than_def iso_imp_epi_and_monic smaller_than_countable_is_countable by blast\n\n\nlemma not_finite_and_infinite:\n  \"\\<not>(is_finite(X) \\<and> is_infinite(X))\"\n  using epi_is_surj is_finite_def is_infinite_def iso_imp_epi_and_monic by blast\n\nlemma iso_pres_infinite:\n  assumes \"X \\<cong> Y\"\n  assumes \"is_infinite(X)\"\n  shows \"is_infinite(Y)\"\n  using assms either_finite_or_infinite not_finite_and_infinite iso_pres_finite isomorphic_is_symmetric by blast\n\n(*Consider moving the result below*)\n\nlemma coprod_leq_product:\n  assumes X_not_init: \"\\<not>(initial_object(X))\" \n  assumes Y_not_init: \"\\<not>(initial_object(Y))\" \n  assumes X_not_term: \"\\<not>(terminal_object(X))\"\n  assumes Y_not_term: \"\\<not>(terminal_object(Y))\"\n  shows \"(X \\<Coprod> Y) \\<le>\\<^sub>c (X \\<times>\\<^sub>c Y)\"\nproof - \n  obtain x1 x2 where x1x2_def[type_rule]:  \"(x1 \\<in>\\<^sub>c X)\" \"(x2 \\<in>\\<^sub>c X)\" \"(x1 \\<noteq> x2)\"\n    using X_not_init X_not_term iso_empty_initial iso_to1_is_term no_el_iff_iso_0 nonempty_def single_elem_iso_one by blast\n  obtain y1 y2 where y1y2_def[type_rule]:  \"(y1 \\<in>\\<^sub>c Y)\" \"(y2 \\<in>\\<^sub>c Y)\" \"(y1 \\<noteq> y2)\"\n    using Y_not_init Y_not_term iso_empty_initial iso_to1_is_term no_el_iff_iso_0 nonempty_def single_elem_iso_one by blast\n  then have y1_mono[type_rule]: \"monomorphism(y1)\"\n    using element_monomorphism by blast\n  obtain m where m_def: \"m = \\<langle>id(X), y1 \\<circ>\\<^sub>c \\<beta>\\<^bsub>X\\<^esub>\\<rangle> \\<amalg> ((\\<langle>x2, y2\\<rangle> \\<amalg> \\<langle>x1 \\<circ>\\<^sub>c \\<beta>\\<^bsub>Y \\<setminus> (one,y1)\\<^esub>, y1\\<^sup>c\\<rangle>) \\<circ>\\<^sub>c  try_cast y1)\"\n    by simp\n  have type1: \"\\<langle>id(X), y1 \\<circ>\\<^sub>c \\<beta>\\<^bsub>X\\<^esub>\\<rangle> : X \\<rightarrow> (X \\<times>\\<^sub>c Y)\"\n    by (meson cfunc_prod_type comp_type id_type terminal_func_type y1y2_def)\n  have trycast_y1_type: \"try_cast y1 : Y \\<rightarrow> one \\<Coprod> (Y \\<setminus> (one,y1))\"\n    by (meson element_monomorphism try_cast_type y1y2_def)\n  have y1'_type[type_rule]: \"y1\\<^sup>c : Y \\<setminus> (one,y1) \\<rightarrow> Y\"\n    using complement_morphism_type one_terminal_object terminal_el__monomorphism y1y2_def by blast\n  have type4: \"\\<langle>x1 \\<circ>\\<^sub>c \\<beta>\\<^bsub>Y \\<setminus> (one,y1)\\<^esub>, y1\\<^sup>c\\<rangle> : Y \\<setminus> (one,y1) \\<rightarrow> (X \\<times>\\<^sub>c Y)\"\n    using cfunc_prod_type comp_type terminal_func_type x1x2_def y1'_type by blast\n  have type5: \"\\<langle>x2, y2\\<rangle> \\<in>\\<^sub>c (X \\<times>\\<^sub>c Y)\"\n    by (simp add: cfunc_prod_type x1x2_def y1y2_def)\n  then have type6: \"\\<langle>x2, y2\\<rangle> \\<amalg> \\<langle>x1 \\<circ>\\<^sub>c \\<beta>\\<^bsub>Y \\<setminus> (one,y1)\\<^esub>, y1\\<^sup>c\\<rangle> :(one \\<Coprod> (Y \\<setminus> (one,y1))) \\<rightarrow> (X \\<times>\\<^sub>c Y)\"\n    using cfunc_coprod_type type4 by blast\n  then have type7: \"((\\<langle>x2, y2\\<rangle> \\<amalg> \\<langle>x1 \\<circ>\\<^sub>c \\<beta>\\<^bsub>Y \\<setminus> (one,y1)\\<^esub>, y1\\<^sup>c\\<rangle>) \\<circ>\\<^sub>c  try_cast y1) : Y \\<rightarrow> (X \\<times>\\<^sub>c Y)\"\n    using comp_type trycast_y1_type by blast\n  then have m_type: \"m : X  \\<Coprod> Y \\<rightarrow> (X \\<times>\\<^sub>c Y)\"\n    by (simp add: cfunc_coprod_type m_def type1)\n\n  have relative: \"\\<And>y. y \\<in>\\<^sub>c Y \\<Longrightarrow> (y \\<in>\\<^bsub>Y\\<^esub> (one, y1)) = (y = y1)\"\n  proof(auto)\n    fix y \n    assume y_type: \"y \\<in>\\<^sub>c Y\"\n    show \"y \\<in>\\<^bsub>Y\\<^esub> (one, y1) \\<Longrightarrow> y = y1\"\n      by (metis cfunc_type_def factors_through_def id_right_unit2 id_type one_unique_element relative_member_def2)\n  next \n    show \"y1 \\<in>\\<^sub>c Y \\<Longrightarrow> y1 \\<in>\\<^bsub>Y\\<^esub> (one, y1)\"\n      by (metis cfunc_type_def factors_through_def id_right_unit2 id_type relative_member_def2 y1_mono)\n  qed\n\n\n  have \"injective(m)\"\n  proof(unfold injective_def ,auto)\n    fix a b \n    assume \"a \\<in>\\<^sub>c domain m\" \"b \\<in>\\<^sub>c domain m\"\n    then have a_type[type_rule]: \"a \\<in>\\<^sub>c X  \\<Coprod> Y\" and b_type[type_rule]: \"b \\<in>\\<^sub>c X  \\<Coprod> Y\"\n      using m_type unfolding cfunc_type_def by auto\n    assume eqs: \"m \\<circ>\\<^sub>c a = m \\<circ>\\<^sub>c b\"\n\n      have m_leftproj_l_equals: \"\\<And> l. l  \\<in>\\<^sub>c X \\<Longrightarrow> m \\<circ>\\<^sub>c left_coproj X Y \\<circ>\\<^sub>c l = \\<langle>l, y1\\<rangle>\"\n      proof-\n        fix l \n        assume l_type: \"l \\<in>\\<^sub>c X\"\n        have \"m \\<circ>\\<^sub>c left_coproj X Y \\<circ>\\<^sub>c l = (\\<langle>id(X), y1 \\<circ>\\<^sub>c \\<beta>\\<^bsub>X\\<^esub>\\<rangle> \\<amalg> ((\\<langle>x2, y2\\<rangle> \\<amalg> \\<langle>x1 \\<circ>\\<^sub>c \\<beta>\\<^bsub>Y \\<setminus> (one,y1)\\<^esub>, y1\\<^sup>c\\<rangle>) \\<circ>\\<^sub>c  try_cast y1)) \\<circ>\\<^sub>c left_coproj X Y \\<circ>\\<^sub>c l\"\n          by (simp add: m_def)\n        also have \"... = (\\<langle>id(X), y1 \\<circ>\\<^sub>c \\<beta>\\<^bsub>X\\<^esub>\\<rangle> \\<amalg> ((\\<langle>x2, y2\\<rangle> \\<amalg> \\<langle>x1 \\<circ>\\<^sub>c \\<beta>\\<^bsub>Y \\<setminus> (one,y1)\\<^esub>, y1\\<^sup>c\\<rangle>) \\<circ>\\<^sub>c  try_cast y1) \\<circ>\\<^sub>c left_coproj X Y) \\<circ>\\<^sub>c l\"\n          using comp_associative2 l_type by (typecheck_cfuncs, blast)\n        also have \"... = \\<langle>id(X), y1 \\<circ>\\<^sub>c \\<beta>\\<^bsub>X\\<^esub>\\<rangle> \\<circ>\\<^sub>c l\"\n          by (typecheck_cfuncs, simp add: left_coproj_cfunc_coprod)\n        also have \"... = \\<langle>id(X)\\<circ>\\<^sub>c l , (y1 \\<circ>\\<^sub>c \\<beta>\\<^bsub>X\\<^esub>) \\<circ>\\<^sub>c l\\<rangle>\"\n          using l_type cfunc_prod_comp by (typecheck_cfuncs, auto)\n        also have \"... = \\<langle>l , y1 \\<circ>\\<^sub>c \\<beta>\\<^bsub>X\\<^esub> \\<circ>\\<^sub>c l\\<rangle>\"\n          using l_type comp_associative2 id_left_unit2 by (typecheck_cfuncs, auto)\n        also have \"... = \\<langle>l , y1\\<rangle>\"\n          using l_type by (typecheck_cfuncs,metis id_right_unit2 id_type one_unique_element)\n        then show \"m \\<circ>\\<^sub>c left_coproj X Y \\<circ>\\<^sub>c l = \\<langle>l,y1\\<rangle>\"\n          by (simp add: calculation)\n      qed\n\n      have m_rightproj_y1_equals: \"m \\<circ>\\<^sub>c right_coproj X Y \\<circ>\\<^sub>c y1 = \\<langle>x2, y2\\<rangle>\"\n          proof - \n            have \"m \\<circ>\\<^sub>c right_coproj X Y \\<circ>\\<^sub>c y1 = (m \\<circ>\\<^sub>c right_coproj X Y) \\<circ>\\<^sub>c y1\"\n              using  comp_associative2 m_type by (typecheck_cfuncs, auto)\n            also have \"... = ((\\<langle>x2, y2\\<rangle> \\<amalg> \\<langle>x1 \\<circ>\\<^sub>c \\<beta>\\<^bsub>Y \\<setminus> (one,y1)\\<^esub>, y1\\<^sup>c\\<rangle>) \\<circ>\\<^sub>c  try_cast y1) \\<circ>\\<^sub>c y1\"\n              using m_def right_coproj_cfunc_coprod type1 by (typecheck_cfuncs, auto)\n            also have \"... = (\\<langle>x2, y2\\<rangle> \\<amalg> \\<langle>x1 \\<circ>\\<^sub>c \\<beta>\\<^bsub>Y \\<setminus> (one,y1)\\<^esub>, y1\\<^sup>c\\<rangle>) \\<circ>\\<^sub>c  try_cast y1 \\<circ>\\<^sub>c y1\"\n              using  comp_associative2 by (typecheck_cfuncs, auto)\n            also have \"... = (\\<langle>x2, y2\\<rangle> \\<amalg> \\<langle>x1 \\<circ>\\<^sub>c \\<beta>\\<^bsub>Y \\<setminus> (one,y1)\\<^esub>, y1\\<^sup>c\\<rangle>) \\<circ>\\<^sub>c left_coproj one (Y \\<setminus> (one,y1))\"\n              using  try_cast_m_m y1_mono y1y2_def(1) by auto\n            also have \"... =  \\<langle>x2, y2\\<rangle>\"\n              using left_coproj_cfunc_coprod type4 type5 by blast\n            then show ?thesis using calculation by auto\n          qed\n\n     have m_rightproj_not_y1_equals: \"\\<And> r. r  \\<in>\\<^sub>c Y \\<and> r \\<noteq> y1 \\<Longrightarrow>\n          \\<exists>k. k \\<in>\\<^sub>c Y \\<setminus> (one,y1) \\<and> try_cast y1 \\<circ>\\<^sub>c r = right_coproj one (Y \\<setminus> (one,y1)) \\<circ>\\<^sub>c k \\<and> \n          m \\<circ>\\<^sub>c right_coproj X Y \\<circ>\\<^sub>c r = \\<langle>x1, y1\\<^sup>c \\<circ>\\<^sub>c k\\<rangle>\"\n          proof(auto)\n           fix r \n           assume r_type: \"r \\<in>\\<^sub>c Y\"\n           assume r_not_y1: \"r \\<noteq> y1\"\n           then obtain k where k_def: \"k \\<in>\\<^sub>c Y \\<setminus> (one,y1) \\<and> try_cast y1 \\<circ>\\<^sub>c r = right_coproj one (Y \\<setminus> (one,y1)) \\<circ>\\<^sub>c k\"\n            using r_type relative try_cast_not_in_X y1_mono y1y2_def(1) by blast\n           have m_rightproj_l_equals: \"m \\<circ>\\<^sub>c right_coproj X Y \\<circ>\\<^sub>c r = \\<langle>x1, y1\\<^sup>c \\<circ>\\<^sub>c k\\<rangle>\"\n           \n           proof -\n             have \"m \\<circ>\\<^sub>c right_coproj X Y \\<circ>\\<^sub>c r = (m \\<circ>\\<^sub>c right_coproj X Y) \\<circ>\\<^sub>c r\"\n              using r_type comp_associative2 m_type by (typecheck_cfuncs, auto)\n            also have \"... = ((\\<langle>x2, y2\\<rangle> \\<amalg> \\<langle>x1 \\<circ>\\<^sub>c \\<beta>\\<^bsub>Y \\<setminus> (one,y1)\\<^esub>, y1\\<^sup>c\\<rangle>) \\<circ>\\<^sub>c  try_cast y1) \\<circ>\\<^sub>c r\"\n              using m_def right_coproj_cfunc_coprod type1 by (typecheck_cfuncs, auto)\n            also have \"... = (\\<langle>x2, y2\\<rangle> \\<amalg> \\<langle>x1 \\<circ>\\<^sub>c \\<beta>\\<^bsub>Y \\<setminus> (one,y1)\\<^esub>, y1\\<^sup>c\\<rangle>) \\<circ>\\<^sub>c  (try_cast y1 \\<circ>\\<^sub>c r)\"\n              using r_type comp_associative2 by (typecheck_cfuncs, auto)\n            also have \"... = (\\<langle>x2, y2\\<rangle> \\<amalg> \\<langle>x1 \\<circ>\\<^sub>c \\<beta>\\<^bsub>Y \\<setminus> (one,y1)\\<^esub>, y1\\<^sup>c\\<rangle>) \\<circ>\\<^sub>c (right_coproj one (Y \\<setminus> (one,y1)) \\<circ>\\<^sub>c k)\"\n              using k_def by auto\n            also have \"... = ((\\<langle>x2, y2\\<rangle> \\<amalg> \\<langle>x1 \\<circ>\\<^sub>c \\<beta>\\<^bsub>Y \\<setminus> (one,y1)\\<^esub>, y1\\<^sup>c\\<rangle>) \\<circ>\\<^sub>c right_coproj one (Y \\<setminus> (one,y1))) \\<circ>\\<^sub>c k\"\n              using comp_associative2 k_def by (typecheck_cfuncs, blast)\n            also have \"... =  \\<langle>x1 \\<circ>\\<^sub>c \\<beta>\\<^bsub>Y \\<setminus> (one,y1)\\<^esub>, y1\\<^sup>c\\<rangle> \\<circ>\\<^sub>c k\"\n              using right_coproj_cfunc_coprod type4 type5 by auto\n            also have \"... =  \\<langle>x1 \\<circ>\\<^sub>c \\<beta>\\<^bsub>Y \\<setminus> (one,y1)\\<^esub> \\<circ>\\<^sub>c k, y1\\<^sup>c \\<circ>\\<^sub>c k \\<rangle>\"\n              using cfunc_prod_comp comp_associative2 k_def by (typecheck_cfuncs, auto)\n            also have \"... =  \\<langle>x1, y1\\<^sup>c \\<circ>\\<^sub>c k\\<rangle>\"\n              by (metis id_right_unit2 id_type k_def one_unique_element terminal_func_comp terminal_func_type x1x2_def(1))\n            then show ?thesis using calculation by auto\n          qed\n          then show \"\\<exists>k. k \\<in>\\<^sub>c Y \\<setminus> (one, y1) \\<and>\n             try_cast y1 \\<circ>\\<^sub>c r = right_coproj one (Y \\<setminus> (one, y1)) \\<circ>\\<^sub>c k \\<and>\n             m \\<circ>\\<^sub>c right_coproj X Y \\<circ>\\<^sub>c r = \\<langle>x1,y1\\<^sup>c \\<circ>\\<^sub>c k\\<rangle>\"\n            using k_def by blast\n        qed\n\n  \n    show \"a = b\"\n    proof(cases \"\\<exists>x. a = left_coproj X Y \\<circ>\\<^sub>c x  \\<and> x \\<in>\\<^sub>c X\")\n      assume \"\\<exists>x. a = left_coproj X Y \\<circ>\\<^sub>c x  \\<and> x \\<in>\\<^sub>c X\"\n      then obtain x where x_def: \"a = left_coproj X Y \\<circ>\\<^sub>c x  \\<and> x \\<in>\\<^sub>c X\"\n        by auto\n      then have m_proj_a: \"m \\<circ>\\<^sub>c left_coproj X Y \\<circ>\\<^sub>c x = \\<langle>x, y1\\<rangle>\"\n        using m_leftproj_l_equals by (simp add: x_def)\n      show \"a = b\"\n      proof(cases \"\\<exists>c. b = left_coproj X Y \\<circ>\\<^sub>c c  \\<and> c \\<in>\\<^sub>c X\")\n        assume \"\\<exists>c. b = left_coproj X Y \\<circ>\\<^sub>c c \\<and> c \\<in>\\<^sub>c X\"\n        then obtain c where c_def: \"b = left_coproj X Y \\<circ>\\<^sub>c c  \\<and> c \\<in>\\<^sub>c X\"\n          by auto\n        then have \"m \\<circ>\\<^sub>c left_coproj X Y \\<circ>\\<^sub>c c = \\<langle>c, y1\\<rangle>\"\n          by (simp add: m_leftproj_l_equals)\n        then show ?thesis\n          using c_def element_pair_eq eqs m_proj_a x_def y1y2_def(1) by auto\n      next\n        assume \"\\<nexists>c. b = left_coproj X Y \\<circ>\\<^sub>c c \\<and> c \\<in>\\<^sub>c X\"\n        then obtain c where c_def: \"b = right_coproj X Y \\<circ>\\<^sub>c c  \\<and> c \\<in>\\<^sub>c Y\"\n          using b_type coprojs_jointly_surj by blast\n        show \"a = b\"\n        proof(cases \"c = y1\")\n          assume \"c = y1\"       \n          have m_rightproj_l_equals: \"m \\<circ>\\<^sub>c right_coproj X Y \\<circ>\\<^sub>c c = \\<langle>x2, y2\\<rangle>\"\n            by (simp add: \\<open>c = y1\\<close> m_rightproj_y1_equals)       \n          then show ?thesis\n            using \\<open>c = y1\\<close> c_def cart_prod_eq2 eqs m_proj_a x1x2_def(2) x_def y1y2_def(2) y1y2_def(3) by auto\n        next\n          assume \"c \\<noteq> y1\"       \n          then obtain k where k_def:  \"m \\<circ>\\<^sub>c right_coproj X Y \\<circ>\\<^sub>c c = \\<langle>x1, y1\\<^sup>c \\<circ>\\<^sub>c k\\<rangle>\"\n            using c_def m_rightproj_not_y1_equals by blast                     \n          then have \"\\<langle>x, y1\\<rangle> = \\<langle>x1, y1\\<^sup>c \\<circ>\\<^sub>c k\\<rangle>\"\n            using c_def eqs m_proj_a x_def by auto\n          then have \"(x = x1) \\<and> (y1 = y1\\<^sup>c \\<circ>\\<^sub>c k)\"\n            by (smt \\<open>c \\<noteq> y1\\<close> c_def cfunc_type_def comp_associative comp_type element_pair_eq k_def m_rightproj_not_y1_equals monomorphism_def3 try_cast_m_m' try_cast_mono trycast_y1_type x1x2_def(1) x_def y1'_type y1_mono y1y2_def(1))\n          then have False\n            by (smt \\<open>c \\<noteq> y1\\<close>  c_def comp_type complement_disjoint element_pair_eq id_right_unit2 id_type k_def m_rightproj_not_y1_equals x_def y1'_type y1_mono y1y2_def(1))\n          then show ?thesis by auto\n        qed\n      qed\n    next \n      assume \"\\<nexists>x. a = left_coproj X Y \\<circ>\\<^sub>c x \\<and> x \\<in>\\<^sub>c X\"\n      then obtain y where y_def: \"a = right_coproj X Y \\<circ>\\<^sub>c y \\<and> y \\<in>\\<^sub>c Y\"\n        using a_type coprojs_jointly_surj by blast\n\n      show \"a = b\"\n      proof(cases \"y = y1\")\n        assume \"y = y1\"\n        then  have m_rightproj_y_equals: \"m \\<circ>\\<^sub>c right_coproj X Y \\<circ>\\<^sub>c y = \\<langle>x2, y2\\<rangle>\"\n          using m_rightproj_y1_equals by blast\n        then have \"m \\<circ>\\<^sub>c a  = \\<langle>x2, y2\\<rangle>\"\n          using y_def by blast\n        show \"a = b\"\n        proof(cases \"\\<exists>c. b = left_coproj X Y \\<circ>\\<^sub>c c  \\<and> c \\<in>\\<^sub>c X\")\n          assume \"\\<exists>c. b = left_coproj X Y \\<circ>\\<^sub>c c \\<and> c \\<in>\\<^sub>c X\"\n          then obtain c where c_def: \"b = left_coproj X Y \\<circ>\\<^sub>c c \\<and> c \\<in>\\<^sub>c X\"\n            by blast\n          then show \"a = b\"\n            using cart_prod_eq2 eqs m_leftproj_l_equals m_rightproj_y_equals x1x2_def(2) y1y2_def y_def by auto\n        next\n          assume \"\\<nexists>c. b = left_coproj X Y \\<circ>\\<^sub>c c \\<and> c \\<in>\\<^sub>c X\"\n          then obtain c where c_def: \"b = right_coproj X Y \\<circ>\\<^sub>c c \\<and> c \\<in>\\<^sub>c Y\"\n            using b_type coprojs_jointly_surj by blast\n          show \"a = b\"\n          proof(cases \"c = y\")\n            assume \"c = y\"\n            show \"a = b\"\n              by (simp add: \\<open>c = y\\<close> c_def y_def)\n          next\n            assume \"c \\<noteq> y\"\n            then have \"c \\<noteq> y1\"\n              by (simp add: \\<open>y = y1\\<close>)\n            then obtain k where k_def: \"k \\<in>\\<^sub>c Y \\<setminus> (one,y1) \\<and> try_cast y1 \\<circ>\\<^sub>c c = right_coproj one (Y \\<setminus> (one,y1)) \\<circ>\\<^sub>c k \\<and> \n          m \\<circ>\\<^sub>c right_coproj X Y \\<circ>\\<^sub>c c = \\<langle>x1, y1\\<^sup>c \\<circ>\\<^sub>c k\\<rangle>\"\n              using c_def m_rightproj_not_y1_equals by blast\n            then have \"\\<langle>x2, y2\\<rangle> = \\<langle>x1, y1\\<^sup>c \\<circ>\\<^sub>c k\\<rangle>\"\n              using \\<open>m \\<circ>\\<^sub>c a = \\<langle>x2,y2\\<rangle>\\<close> c_def eqs by auto\n            then have False\n              using comp_type element_pair_eq k_def x1x2_def y1'_type y1y2_def(2) by auto\n            then show ?thesis\n              by simp\n          qed\n        qed\n      next\n        assume \"y \\<noteq> y1\"\n        then obtain k where k_def: \"k \\<in>\\<^sub>c Y \\<setminus> (one,y1) \\<and> try_cast y1 \\<circ>\\<^sub>c y = right_coproj one (Y \\<setminus> (one,y1)) \\<circ>\\<^sub>c k \\<and> \n          m \\<circ>\\<^sub>c right_coproj X Y \\<circ>\\<^sub>c y = \\<langle>x1, y1\\<^sup>c \\<circ>\\<^sub>c k\\<rangle>\"\n          using m_rightproj_not_y1_equals y_def by blast  \n        then have \"m \\<circ>\\<^sub>c a  = \\<langle>x1, y1\\<^sup>c \\<circ>\\<^sub>c k\\<rangle>\"\n          using y_def by blast\n        show \"a = b\"\n        proof(cases \"\\<exists>c. b = right_coproj X Y \\<circ>\\<^sub>c c  \\<and> c \\<in>\\<^sub>c Y\")\n          assume \"\\<exists>c. b = right_coproj X Y \\<circ>\\<^sub>c c  \\<and> c \\<in>\\<^sub>c Y\"\n          then obtain c where c_def: \"b = right_coproj X Y \\<circ>\\<^sub>c c \\<and> c \\<in>\\<^sub>c Y\"\n            by blast  \n          show \"a = b\"\n          proof(cases \"c = y1\")\n            assume \"c = y1\" \n            show \"a = b\"\n              proof -\n                obtain cc :: cfunc where\n                  f1: \"cc \\<in>\\<^sub>c Y \\<setminus> (one, y1) \\<and> try_cast y1 \\<circ>\\<^sub>c y = right_coproj one (Y \\<setminus> (one, y1)) \\<circ>\\<^sub>c cc \\<and> m \\<circ>\\<^sub>c right_coproj X Y \\<circ>\\<^sub>c y = \\<langle>x1,y1\\<^sup>c \\<circ>\\<^sub>c cc\\<rangle>\"\n                  using \\<open>\\<And>thesis. (\\<And>k. k \\<in>\\<^sub>c Y \\<setminus> (one, y1) \\<and> try_cast y1 \\<circ>\\<^sub>c y = right_coproj one (Y \\<setminus> (one, y1)) \\<circ>\\<^sub>c k \\<and> m \\<circ>\\<^sub>c right_coproj X Y \\<circ>\\<^sub>c y = \\<langle>x1,y1\\<^sup>c \\<circ>\\<^sub>c k\\<rangle> \\<Longrightarrow> thesis) \\<Longrightarrow> thesis\\<close> by blast\n                have \"\\<langle>x2,y2\\<rangle> = m \\<circ>\\<^sub>c a\"\n              using \\<open>c = y1\\<close> c_def eqs m_rightproj_y1_equals by presburger\n              then show ?thesis\n              using f1 cart_prod_eq2 comp_type x1x2_def y1'_type y1y2_def(2) y_def by force\n              qed\n          next\n              assume \"c \\<noteq> y1\"              \n              then obtain k' where k'_def: \"k' \\<in>\\<^sub>c Y \\<setminus> (one,y1) \\<and> try_cast y1 \\<circ>\\<^sub>c c = right_coproj one (Y \\<setminus> (one,y1)) \\<circ>\\<^sub>c k' \\<and> \n              m \\<circ>\\<^sub>c right_coproj X Y \\<circ>\\<^sub>c c = \\<langle>x1, y1\\<^sup>c \\<circ>\\<^sub>c k'\\<rangle>\"\n                using c_def m_rightproj_not_y1_equals by blast\n              then have \"\\<langle>x1, y1\\<^sup>c \\<circ>\\<^sub>c k'\\<rangle> = \\<langle>x1, y1\\<^sup>c \\<circ>\\<^sub>c k\\<rangle>\"\n                using c_def eqs k_def y_def by auto\n              then have \"(x1 = x1) \\<and> (y1\\<^sup>c \\<circ>\\<^sub>c k' = y1\\<^sup>c \\<circ>\\<^sub>c k)\"\n                using  element_pair_eq k'_def k_def by (typecheck_cfuncs, blast)\n              then have \"k' = k\"\n                by (metis cfunc_type_def complement_morphism_mono k'_def k_def monomorphism_def y1'_type y1_mono)\n              then have \"c = y\"\n                by (metis c_def cfunc_type_def k'_def k_def monomorphism_def try_cast_mono trycast_y1_type y1_mono y_def)\n              then show \"a = b\"\n                by (simp add: c_def y_def)\n          qed\n        next\n            assume \"\\<nexists>c. b = right_coproj X Y \\<circ>\\<^sub>c c \\<and> c \\<in>\\<^sub>c Y\"\n            then obtain c where c_def:  \"b = left_coproj X Y \\<circ>\\<^sub>c c \\<and> c \\<in>\\<^sub>c X\"\n              using b_type coprojs_jointly_surj by blast\n            then have  \"m \\<circ>\\<^sub>c left_coproj X Y \\<circ>\\<^sub>c c = \\<langle>c, y1\\<rangle>\"\n              by (simp add: m_leftproj_l_equals)      \n            then have \"\\<langle>c, y1\\<rangle> = \\<langle>x1, y1\\<^sup>c \\<circ>\\<^sub>c k\\<rangle>\"\n                using \\<open>m \\<circ>\\<^sub>c a = \\<langle>x1,y1\\<^sup>c \\<circ>\\<^sub>c k\\<rangle>\\<close> \\<open>m \\<circ>\\<^sub>c left_coproj X Y \\<circ>\\<^sub>c c = \\<langle>c,y1\\<rangle>\\<close> c_def eqs by auto      \n            then have \"(c = x1) \\<and> (y1 = y1\\<^sup>c \\<circ>\\<^sub>c k)\"\n              using c_def cart_prod_eq2 comp_type k_def x1x2_def(1) y1'_type y1y2_def(1) by auto \n            then have False\n              by (metis cfunc_type_def complement_disjoint id_right_unit id_type k_def y1_mono y1y2_def(1))\n            then show ?thesis\n              by simp\n        qed\n      qed\n    qed\n  qed\n  then have \"monomorphism m\"\n    using injective_imp_monomorphism by auto \n  then show ?thesis\n    using is_smaller_than_def m_type by blast\nqed\n\n\nlemma sets_squared:\n  \"A\\<^bsup>\\<Omega>\\<^esup> \\<cong> A \\<times>\\<^sub>c A \"\nproof - \n  obtain \\<phi> where \\<phi>_def: \"\\<phi> = \\<langle>eval_func A \\<Omega> \\<circ>\\<^sub>c \\<langle>\\<t> \\<circ>\\<^sub>c \\<beta>\\<^bsub>A\\<^bsup>\\<Omega>\\<^esup>\\<^esub>, id(A\\<^bsup>\\<Omega>\\<^esup>)\\<rangle>,\n                              eval_func A \\<Omega> \\<circ>\\<^sub>c \\<langle>\\<f> \\<circ>\\<^sub>c \\<beta>\\<^bsub>A\\<^bsup>\\<Omega>\\<^esup>\\<^esub>, id(A\\<^bsup>\\<Omega>\\<^esup>)\\<rangle>\\<rangle>\"\n    by simp\n  have type1[type_rule]: \"\\<langle>\\<t> \\<circ>\\<^sub>c \\<beta>\\<^bsub>A\\<^bsup>\\<Omega>\\<^esup>\\<^esub>, id(A\\<^bsup>\\<Omega>\\<^esup>)\\<rangle> : A\\<^bsup>\\<Omega>\\<^esup> \\<rightarrow> \\<Omega> \\<times>\\<^sub>c (A\\<^bsup>\\<Omega>\\<^esup>)\"\n    by typecheck_cfuncs\n  have type2[type_rule]: \"\\<langle>\\<f> \\<circ>\\<^sub>c \\<beta>\\<^bsub>A\\<^bsup>\\<Omega>\\<^esup>\\<^esub>, id(A\\<^bsup>\\<Omega>\\<^esup>)\\<rangle> : A\\<^bsup>\\<Omega>\\<^esup> \\<rightarrow> \\<Omega> \\<times>\\<^sub>c (A\\<^bsup>\\<Omega>\\<^esup>)\"\n    by typecheck_cfuncs\n  have \\<phi>_type[type_rule]: \"\\<phi> : A\\<^bsup>\\<Omega>\\<^esup> \\<rightarrow> A \\<times>\\<^sub>c A\"\n    unfolding \\<phi>_def by typecheck_cfuncs\n  have \"injective(\\<phi>)\"\n  proof(unfold injective_def,auto)\n    fix f g \n    assume \"f \\<in>\\<^sub>c domain \\<phi>\" then have f_type[type_rule]: \"f \\<in>\\<^sub>c A\\<^bsup>\\<Omega>\\<^esup>\" \n      using \\<phi>_type cfunc_type_def by (typecheck_cfuncs, auto)\n    assume \"g \\<in>\\<^sub>c domain \\<phi>\" then have g_type[type_rule]: \"g \\<in>\\<^sub>c A\\<^bsup>\\<Omega>\\<^esup>\" \n      using \\<phi>_type cfunc_type_def by (typecheck_cfuncs, auto)\n    assume eqs: \"\\<phi> \\<circ>\\<^sub>c f = \\<phi> \\<circ>\\<^sub>c g\"\n    show \"f = g\"\n    proof(rule one_separator[where X = one, where Y = \"A\\<^bsup>\\<Omega>\\<^esup>\"])\n      show \"f \\<in>\\<^sub>c A\\<^bsup>\\<Omega>\\<^esup>\" \n        by typecheck_cfuncs\n      show \"g \\<in>\\<^sub>c A\\<^bsup>\\<Omega>\\<^esup>\"\n        by typecheck_cfuncs\n      show \"\\<And>id_1. id_1 \\<in>\\<^sub>c one \\<Longrightarrow> f \\<circ>\\<^sub>c id_1 = g \\<circ>\\<^sub>c id_1\"\n      proof(rule same_evals_equal[where Z = one, where X = A, where A = \\<Omega>])\n        show \"\\<And>id_1. id_1 \\<in>\\<^sub>c one \\<Longrightarrow> f \\<circ>\\<^sub>c id_1 \\<in>\\<^sub>c A\\<^bsup>\\<Omega>\\<^esup>\"\n          by (simp add: comp_type f_type)\n        show \"\\<And>id_1. id_1 \\<in>\\<^sub>c one \\<Longrightarrow> g \\<circ>\\<^sub>c id_1 \\<in>\\<^sub>c A\\<^bsup>\\<Omega>\\<^esup>\"\n          by (simp add: comp_type g_type)\n        show \"\\<And>id_1.\n       id_1 \\<in>\\<^sub>c one \\<Longrightarrow>\n       eval_func A \\<Omega> \\<circ>\\<^sub>c id\\<^sub>c \\<Omega> \\<times>\\<^sub>f f \\<circ>\\<^sub>c id_1 =\n       eval_func A \\<Omega> \\<circ>\\<^sub>c id\\<^sub>c \\<Omega> \\<times>\\<^sub>f g \\<circ>\\<^sub>c id_1\"\n        proof  -\n          fix id_1\n          assume id1_is: \"id_1 \\<in>\\<^sub>c one\"\n          then have id1_eq: \"id_1 = id(one)\"\n            using id_type one_unique_element by auto\n\n          obtain a1 a2 where phi_f_def: \"\\<phi> \\<circ>\\<^sub>c f = \\<langle>a1,a2\\<rangle> \\<and> a1 \\<in>\\<^sub>c A \\<and> a2 \\<in>\\<^sub>c A\"\n            using \\<phi>_type cart_prod_decomp comp_type f_type by blast\n          have equation1: \"\\<langle>a1,a2\\<rangle> =  \\<langle>eval_func A \\<Omega> \\<circ>\\<^sub>c \\<langle>\\<t>, f \\<rangle>  ,\n                              eval_func A \\<Omega> \\<circ>\\<^sub>c \\<langle>\\<f> , f \\<rangle> \\<rangle>\"\n          proof - \n              have \"\\<langle>a1,a2\\<rangle> = \\<langle>eval_func A \\<Omega> \\<circ>\\<^sub>c \\<langle>\\<t> \\<circ>\\<^sub>c \\<beta>\\<^bsub>A\\<^bsup>\\<Omega>\\<^esup>\\<^esub>, id(A\\<^bsup>\\<Omega>\\<^esup>)\\<rangle>,\n                                  eval_func A \\<Omega> \\<circ>\\<^sub>c \\<langle>\\<f> \\<circ>\\<^sub>c \\<beta>\\<^bsub>A\\<^bsup>\\<Omega>\\<^esup>\\<^esub>, id(A\\<^bsup>\\<Omega>\\<^esup>)\\<rangle>\\<rangle> \\<circ>\\<^sub>c f\"\n                using \\<phi>_def phi_f_def by auto\n              also have \"... = \\<langle>eval_func A \\<Omega> \\<circ>\\<^sub>c \\<langle>\\<t> \\<circ>\\<^sub>c \\<beta>\\<^bsub>A\\<^bsup>\\<Omega>\\<^esup>\\<^esub>, id(A\\<^bsup>\\<Omega>\\<^esup>)\\<rangle> \\<circ>\\<^sub>c f ,\n                                  eval_func A \\<Omega> \\<circ>\\<^sub>c \\<langle>\\<f> \\<circ>\\<^sub>c \\<beta>\\<^bsub>A\\<^bsup>\\<Omega>\\<^esup>\\<^esub>, id(A\\<^bsup>\\<Omega>\\<^esup>)\\<rangle> \\<circ>\\<^sub>c f\\<rangle>\"\n                by (typecheck_cfuncs,smt cfunc_prod_comp comp_associative2)\n              also have \"... = \\<langle>eval_func A \\<Omega> \\<circ>\\<^sub>c \\<langle>\\<t> \\<circ>\\<^sub>c \\<beta>\\<^bsub>A\\<^bsup>\\<Omega>\\<^esup>\\<^esub> \\<circ>\\<^sub>c f, id(A\\<^bsup>\\<Omega>\\<^esup>) \\<circ>\\<^sub>c f \\<rangle>  ,\n                                  eval_func A \\<Omega> \\<circ>\\<^sub>c \\<langle>\\<f> \\<circ>\\<^sub>c \\<beta>\\<^bsub>A\\<^bsup>\\<Omega>\\<^esup>\\<^esub> \\<circ>\\<^sub>c f, id(A\\<^bsup>\\<Omega>\\<^esup>)\\<circ>\\<^sub>c f \\<rangle> \\<rangle>\"\n                by (typecheck_cfuncs, simp add: cfunc_prod_comp comp_associative2)\n              also have \"... = \\<langle>eval_func A \\<Omega> \\<circ>\\<^sub>c \\<langle>\\<t>, f \\<rangle>  ,\n                                  eval_func A \\<Omega> \\<circ>\\<^sub>c \\<langle>\\<f> , f \\<rangle> \\<rangle>\"    \n                by (typecheck_cfuncs, metis id1_eq id1_is id_left_unit2 id_right_unit2 terminal_func_unique)\n              then show ?thesis using calculation by auto\n          qed\n          have equation2: \"\\<langle>a1,a2\\<rangle> =  \\<langle>eval_func A \\<Omega> \\<circ>\\<^sub>c \\<langle>\\<t>, g \\<rangle>  ,\n                              eval_func A \\<Omega> \\<circ>\\<^sub>c \\<langle>\\<f> , g \\<rangle> \\<rangle>\"\n          proof - \n              have \"\\<langle>a1,a2\\<rangle> = \\<langle>eval_func A \\<Omega> \\<circ>\\<^sub>c \\<langle>\\<t> \\<circ>\\<^sub>c \\<beta>\\<^bsub>A\\<^bsup>\\<Omega>\\<^esup>\\<^esub>, id(A\\<^bsup>\\<Omega>\\<^esup>)\\<rangle>,\n                                  eval_func A \\<Omega> \\<circ>\\<^sub>c \\<langle>\\<f> \\<circ>\\<^sub>c \\<beta>\\<^bsub>A\\<^bsup>\\<Omega>\\<^esup>\\<^esub>, id(A\\<^bsup>\\<Omega>\\<^esup>)\\<rangle>\\<rangle> \\<circ>\\<^sub>c g\"\n                using \\<phi>_def eqs phi_f_def by auto\n                also have \"... = \\<langle>eval_func A \\<Omega> \\<circ>\\<^sub>c \\<langle>\\<t> \\<circ>\\<^sub>c \\<beta>\\<^bsub>A\\<^bsup>\\<Omega>\\<^esup>\\<^esub>, id(A\\<^bsup>\\<Omega>\\<^esup>)\\<rangle> \\<circ>\\<^sub>c g ,\n                                  eval_func A \\<Omega> \\<circ>\\<^sub>c \\<langle>\\<f> \\<circ>\\<^sub>c \\<beta>\\<^bsub>A\\<^bsup>\\<Omega>\\<^esup>\\<^esub>, id(A\\<^bsup>\\<Omega>\\<^esup>)\\<rangle> \\<circ>\\<^sub>c g\\<rangle>\"\n                by (typecheck_cfuncs,smt cfunc_prod_comp comp_associative2)\n              also have \"... = \\<langle>eval_func A \\<Omega> \\<circ>\\<^sub>c \\<langle>\\<t> \\<circ>\\<^sub>c \\<beta>\\<^bsub>A\\<^bsup>\\<Omega>\\<^esup>\\<^esub> \\<circ>\\<^sub>c g, id(A\\<^bsup>\\<Omega>\\<^esup>) \\<circ>\\<^sub>c g \\<rangle>  ,\n                                  eval_func A \\<Omega> \\<circ>\\<^sub>c \\<langle>\\<f> \\<circ>\\<^sub>c \\<beta>\\<^bsub>A\\<^bsup>\\<Omega>\\<^esup>\\<^esub> \\<circ>\\<^sub>c g, id(A\\<^bsup>\\<Omega>\\<^esup>)\\<circ>\\<^sub>c g \\<rangle> \\<rangle>\"\n                by (typecheck_cfuncs, simp add: cfunc_prod_comp comp_associative2)\n              also have \"... = \\<langle>eval_func A \\<Omega> \\<circ>\\<^sub>c \\<langle>\\<t>, g \\<rangle>  ,\n                                  eval_func A \\<Omega> \\<circ>\\<^sub>c \\<langle>\\<f> , g \\<rangle> \\<rangle>\"    \n                by (typecheck_cfuncs, metis id1_eq id1_is id_left_unit2 id_right_unit2 terminal_func_unique)\n              then show ?thesis using calculation by auto\n         qed\n            have \"\\<langle>eval_func A \\<Omega> \\<circ>\\<^sub>c \\<langle>\\<t>, f \\<rangle>  , eval_func A \\<Omega> \\<circ>\\<^sub>c \\<langle>\\<f> , f \\<rangle> \\<rangle> = \n                             \\<langle>eval_func A \\<Omega> \\<circ>\\<^sub>c \\<langle>\\<t>, g \\<rangle>  , eval_func A \\<Omega> \\<circ>\\<^sub>c \\<langle>\\<f> , g \\<rangle> \\<rangle>\"\n              using equation1 equation2 by auto\n            then have equation3: \"(eval_func A \\<Omega> \\<circ>\\<^sub>c \\<langle>\\<t>, f \\<rangle> = eval_func A \\<Omega> \\<circ>\\<^sub>c \\<langle>\\<t>, g\\<rangle>) \\<and> \n                                  (eval_func A \\<Omega> \\<circ>\\<^sub>c \\<langle>\\<f>, f \\<rangle> = eval_func A \\<Omega> \\<circ>\\<^sub>c \\<langle>\\<f>, g\\<rangle>)\"\n              using  cart_prod_eq2 by (typecheck_cfuncs, auto)\n            have \"eval_func A \\<Omega> \\<circ>\\<^sub>c id\\<^sub>c \\<Omega> \\<times>\\<^sub>f f  = eval_func A \\<Omega> \\<circ>\\<^sub>c id\\<^sub>c \\<Omega> \\<times>\\<^sub>f g\"\n            proof(rule one_separator[where X = \"\\<Omega> \\<times>\\<^sub>c one\", where Y = A])\n              show \"eval_func A \\<Omega> \\<circ>\\<^sub>c id\\<^sub>c \\<Omega> \\<times>\\<^sub>f f : \\<Omega> \\<times>\\<^sub>c one \\<rightarrow> A\"\n                by typecheck_cfuncs\n              show \"eval_func A \\<Omega> \\<circ>\\<^sub>c id\\<^sub>c \\<Omega> \\<times>\\<^sub>f g : \\<Omega> \\<times>\\<^sub>c one \\<rightarrow> A\"\n                by typecheck_cfuncs\n              show \"\\<And>x. x \\<in>\\<^sub>c \\<Omega> \\<times>\\<^sub>c one \\<Longrightarrow>\n         (eval_func A \\<Omega> \\<circ>\\<^sub>c id\\<^sub>c \\<Omega> \\<times>\\<^sub>f f) \\<circ>\\<^sub>c x = (eval_func A \\<Omega> \\<circ>\\<^sub>c id\\<^sub>c \\<Omega> \\<times>\\<^sub>f g) \\<circ>\\<^sub>c x\"\n              proof - \n                fix x\n                assume x_type[type_rule]: \"x \\<in>\\<^sub>c \\<Omega> \\<times>\\<^sub>c one\"\n                then obtain w i where  x_def: \"(w \\<in>\\<^sub>c \\<Omega>) \\<and> (i \\<in>\\<^sub>c one) \\<and> (x = \\<langle>w,i\\<rangle>)\"\n                  using cart_prod_decomp by blast\n                then have i_def: \"i = id(one)\"\n                  using id1_eq id1_is one_unique_element by auto\n                have w_def: \"(w = \\<f>) \\<or> (w = \\<t>)\"\n                  by (simp add: true_false_only_truth_values x_def)\n                then have x_def2: \"(x = \\<langle>\\<f>,i\\<rangle>) \\<or> (x = \\<langle>\\<t>,i\\<rangle>)\"\n                  using x_def by auto\n                show \"(eval_func A \\<Omega> \\<circ>\\<^sub>c id\\<^sub>c \\<Omega> \\<times>\\<^sub>f f) \\<circ>\\<^sub>c x = (eval_func A \\<Omega> \\<circ>\\<^sub>c id\\<^sub>c \\<Omega> \\<times>\\<^sub>f g) \\<circ>\\<^sub>c x\"\n                proof(cases \"(x = \\<langle>\\<f>,i\\<rangle>)\",auto)\n                  assume case1: \"x = \\<langle>\\<f>,i\\<rangle>\"\n                  have \"(eval_func A \\<Omega> \\<circ>\\<^sub>c (id\\<^sub>c \\<Omega> \\<times>\\<^sub>f f)) \\<circ>\\<^sub>c \\<langle>\\<f>,i\\<rangle> = eval_func A \\<Omega> \\<circ>\\<^sub>c ((id\\<^sub>c \\<Omega> \\<times>\\<^sub>f f) \\<circ>\\<^sub>c \\<langle>\\<f>,i\\<rangle>)\"\n                    using case1 comp_associative2 x_type by (typecheck_cfuncs, auto)\n                  also have \"... = eval_func A \\<Omega> \\<circ>\\<^sub>c \\<langle>id\\<^sub>c \\<Omega> \\<circ>\\<^sub>c  \\<f>,f \\<circ>\\<^sub>c i\\<rangle>\"\n                    using cfunc_cross_prod_comp_cfunc_prod i_def id1_eq id1_is by (typecheck_cfuncs, auto)\n                  also have \"... = eval_func A \\<Omega> \\<circ>\\<^sub>c \\<langle>\\<f>, f \\<rangle>\"\n                    using f_type false_func_type i_def id_left_unit2 id_right_unit2 by auto\n                  also have \"... = eval_func A \\<Omega> \\<circ>\\<^sub>c \\<langle>\\<f>, g\\<rangle>\"\n                    using equation3 by blast\n                  also have \"... = eval_func A \\<Omega> \\<circ>\\<^sub>c \\<langle>id\\<^sub>c \\<Omega> \\<circ>\\<^sub>c  \\<f>,g \\<circ>\\<^sub>c i\\<rangle>\"\n                    by (typecheck_cfuncs, simp add: i_def id_left_unit2 id_right_unit2)\n                  also have \"... = eval_func A \\<Omega> \\<circ>\\<^sub>c ((id\\<^sub>c \\<Omega> \\<times>\\<^sub>f g) \\<circ>\\<^sub>c \\<langle>\\<f>,i\\<rangle>)\"\n                    using cfunc_cross_prod_comp_cfunc_prod i_def id1_eq id1_is by (typecheck_cfuncs, auto)\n                  also have \"... = (eval_func A \\<Omega> \\<circ>\\<^sub>c (id\\<^sub>c \\<Omega> \\<times>\\<^sub>f g)) \\<circ>\\<^sub>c \\<langle>\\<f>,i\\<rangle>\"\n                    using case1 comp_associative2 x_type by (typecheck_cfuncs, auto)\n                  then show \"(eval_func A \\<Omega> \\<circ>\\<^sub>c id\\<^sub>c \\<Omega> \\<times>\\<^sub>f f) \\<circ>\\<^sub>c \\<langle>\\<f>,i\\<rangle> = (eval_func A \\<Omega> \\<circ>\\<^sub>c id\\<^sub>c \\<Omega> \\<times>\\<^sub>f g) \\<circ>\\<^sub>c \\<langle>\\<f>,i\\<rangle>\"\n                    by (simp add: calculation)\n              next\n                  assume case2: \"x \\<noteq> \\<langle>\\<f>,i\\<rangle>\"\n                  then have x_eq: \"x = \\<langle>\\<t>,i\\<rangle>\"\n                    using x_def2 by blast\n                  have \"(eval_func A \\<Omega> \\<circ>\\<^sub>c (id\\<^sub>c \\<Omega> \\<times>\\<^sub>f f)) \\<circ>\\<^sub>c \\<langle>\\<t>,i\\<rangle> = eval_func A \\<Omega> \\<circ>\\<^sub>c ((id\\<^sub>c \\<Omega> \\<times>\\<^sub>f f) \\<circ>\\<^sub>c \\<langle>\\<t>,i\\<rangle>)\"\n                      using case2 x_eq comp_associative2 x_type by (typecheck_cfuncs, auto)\n                  also have \"... = eval_func A \\<Omega> \\<circ>\\<^sub>c \\<langle>id\\<^sub>c \\<Omega> \\<circ>\\<^sub>c  \\<t>,f \\<circ>\\<^sub>c i\\<rangle>\"\n                      using cfunc_cross_prod_comp_cfunc_prod i_def id1_eq id1_is by (typecheck_cfuncs, auto)\n                  also have \"... = eval_func A \\<Omega> \\<circ>\\<^sub>c \\<langle>\\<t>, f \\<rangle>\"\n                    using f_type i_def id_left_unit2 id_right_unit2 true_func_type by auto\n                  also have \"... = eval_func A \\<Omega> \\<circ>\\<^sub>c \\<langle>\\<t>, g\\<rangle>\"\n                    using equation3 by blast\n                  also have \"... = eval_func A \\<Omega> \\<circ>\\<^sub>c \\<langle>id\\<^sub>c \\<Omega> \\<circ>\\<^sub>c  \\<t>,g \\<circ>\\<^sub>c i\\<rangle>\"\n                      by (typecheck_cfuncs, simp add: i_def id_left_unit2 id_right_unit2)\n                  also have \"... = eval_func A \\<Omega> \\<circ>\\<^sub>c ((id\\<^sub>c \\<Omega> \\<times>\\<^sub>f g) \\<circ>\\<^sub>c \\<langle>\\<t>,i\\<rangle>)\"\n                      using cfunc_cross_prod_comp_cfunc_prod i_def id1_eq id1_is by (typecheck_cfuncs, auto)\n                  also have \"... = (eval_func A \\<Omega> \\<circ>\\<^sub>c (id\\<^sub>c \\<Omega> \\<times>\\<^sub>f g)) \\<circ>\\<^sub>c \\<langle>\\<t>,i\\<rangle>\"\n                    using comp_associative2 x_eq x_type by (typecheck_cfuncs, blast)\n                  then show \"(eval_func A \\<Omega> \\<circ>\\<^sub>c id\\<^sub>c \\<Omega> \\<times>\\<^sub>f f) \\<circ>\\<^sub>c x = (eval_func A \\<Omega> \\<circ>\\<^sub>c id\\<^sub>c \\<Omega> \\<times>\\<^sub>f g) \\<circ>\\<^sub>c x\"\n                    by (simp add: calculation x_eq)\n                qed\n              qed\n            qed\n            then show \"eval_func A \\<Omega> \\<circ>\\<^sub>c id\\<^sub>c \\<Omega> \\<times>\\<^sub>f f \\<circ>\\<^sub>c id_1 = eval_func A \\<Omega> \\<circ>\\<^sub>c id\\<^sub>c \\<Omega> \\<times>\\<^sub>f g \\<circ>\\<^sub>c id_1\"\n              using  f_type g_type same_evals_equal by blast\n          qed\n        qed\n      qed\n    qed\n    then have \"monomorphism(\\<phi>)\"\n      using injective_imp_monomorphism by auto\n    have \"surjective(\\<phi>)\"\n      unfolding surjective_def\n    proof(auto)\n      fix y \n      assume \"y \\<in>\\<^sub>c codomain \\<phi>\" then have y_type[type_rule]: \"y \\<in>\\<^sub>c A \\<times>\\<^sub>c A\"\n        using \\<phi>_type cfunc_type_def by auto\n      then obtain a1 a2 where y_def[type_rule]: \"y = \\<langle>a1,a2\\<rangle> \\<and> a1 \\<in>\\<^sub>c A \\<and> a2 \\<in>\\<^sub>c A\"\n        using cart_prod_decomp by blast\n      then have aua: \"(a1 \\<amalg> a2): one \\<Coprod> one \\<rightarrow> A\"\n        by (typecheck_cfuncs, simp add: y_def)\n     \n    \n      obtain f where f_def: \"f = ((a1 \\<amalg> a2) \\<circ>\\<^sub>c case_bool  \\<circ>\\<^sub>c left_cart_proj \\<Omega> one)\\<^sup>\\<sharp>\"\n        by simp\n      then have f_type[type_rule]: \"f \\<in>\\<^sub>c A\\<^bsup>\\<Omega>\\<^esup>\"\n       using case_bool_type aua cfunc_type_def codomain_comp domain_comp f_def left_cart_proj_type transpose_func_type by auto\n     have a1_is: \"(eval_func A \\<Omega> \\<circ>\\<^sub>c \\<langle>\\<t> \\<circ>\\<^sub>c \\<beta>\\<^bsub>A\\<^bsup>\\<Omega>\\<^esup>\\<^esub>, id(A\\<^bsup>\\<Omega>\\<^esup>)\\<rangle>) \\<circ>\\<^sub>c f = a1\"\n     proof-\n       have \"(eval_func A \\<Omega> \\<circ>\\<^sub>c \\<langle>\\<t> \\<circ>\\<^sub>c \\<beta>\\<^bsub>A\\<^bsup>\\<Omega>\\<^esup>\\<^esub>, id(A\\<^bsup>\\<Omega>\\<^esup>)\\<rangle>) \\<circ>\\<^sub>c f = eval_func A \\<Omega> \\<circ>\\<^sub>c \\<langle>\\<t> \\<circ>\\<^sub>c \\<beta>\\<^bsub>A\\<^bsup>\\<Omega>\\<^esup>\\<^esub>, id(A\\<^bsup>\\<Omega>\\<^esup>)\\<rangle> \\<circ>\\<^sub>c f\"\n         by (typecheck_cfuncs, simp add: comp_associative2)\n       also have \"... = eval_func A \\<Omega> \\<circ>\\<^sub>c \\<langle>\\<t> \\<circ>\\<^sub>c \\<beta>\\<^bsub>A\\<^bsup>\\<Omega>\\<^esup>\\<^esub> \\<circ>\\<^sub>c f, id(A\\<^bsup>\\<Omega>\\<^esup>) \\<circ>\\<^sub>c f\\<rangle>\"\n         by (typecheck_cfuncs, simp add: cfunc_prod_comp comp_associative2)\n       also have \"... = eval_func A \\<Omega> \\<circ>\\<^sub>c \\<langle>\\<t>, f\\<rangle>\"\n         by (metis cfunc_type_def f_type id_left_unit id_right_unit id_type one_unique_element terminal_func_comp terminal_func_type true_func_type)\n       also have \"... = eval_func A \\<Omega> \\<circ>\\<^sub>c \\<langle>id(\\<Omega>) \\<circ>\\<^sub>c \\<t>, f \\<circ>\\<^sub>c id(one)\\<rangle>\"\n         by (typecheck_cfuncs, simp add: id_left_unit2 id_right_unit2)\n       also have \"... = eval_func A \\<Omega> \\<circ>\\<^sub>c (id(\\<Omega>) \\<times>\\<^sub>f f) \\<circ>\\<^sub>c \\<langle>\\<t>, id(one)\\<rangle>\"\n         by (typecheck_cfuncs, simp add: cfunc_cross_prod_comp_cfunc_prod)\n       also have \"... = (eval_func A \\<Omega> \\<circ>\\<^sub>c (id(\\<Omega>) \\<times>\\<^sub>f f)) \\<circ>\\<^sub>c \\<langle>\\<t>, id(one)\\<rangle>\"\n         using comp_associative2 by (typecheck_cfuncs, blast)\n       also have \"... = ((a1 \\<amalg> a2) \\<circ>\\<^sub>c case_bool  \\<circ>\\<^sub>c left_cart_proj \\<Omega> one) \\<circ>\\<^sub>c \\<langle>\\<t>, id(one)\\<rangle>\"\n         by (typecheck_cfuncs, metis  aua f_def flat_cancels_sharp inv_transpose_func_def2)\n       also have \"... = (a1 \\<amalg> a2) \\<circ>\\<^sub>c case_bool  \\<circ>\\<^sub>c \\<t>\"\n         by (typecheck_cfuncs, smt case_bool_type aua comp_associative2 left_cart_proj_cfunc_prod)\n       also have \"... = (a1 \\<amalg> a2) \\<circ>\\<^sub>c left_coproj one one\"\n         by (simp add: case_bool_true)\n       also have \"... = a1\"\n         using left_coproj_cfunc_coprod y_def by blast\n       then show ?thesis using calculation by auto\n     qed\n     have a2_is: \"(eval_func A \\<Omega> \\<circ>\\<^sub>c \\<langle>\\<f> \\<circ>\\<^sub>c \\<beta>\\<^bsub>A\\<^bsup>\\<Omega>\\<^esup>\\<^esub>, id(A\\<^bsup>\\<Omega>\\<^esup>)\\<rangle>) \\<circ>\\<^sub>c f = a2\"\n     proof-\n       have \"(eval_func A \\<Omega> \\<circ>\\<^sub>c \\<langle>\\<f> \\<circ>\\<^sub>c \\<beta>\\<^bsub>A\\<^bsup>\\<Omega>\\<^esup>\\<^esub>, id(A\\<^bsup>\\<Omega>\\<^esup>)\\<rangle>) \\<circ>\\<^sub>c f = eval_func A \\<Omega> \\<circ>\\<^sub>c \\<langle>\\<f> \\<circ>\\<^sub>c \\<beta>\\<^bsub>A\\<^bsup>\\<Omega>\\<^esup>\\<^esub>, id(A\\<^bsup>\\<Omega>\\<^esup>)\\<rangle> \\<circ>\\<^sub>c f\"\n         by (typecheck_cfuncs, simp add: comp_associative2)\n       also have \"... = eval_func A \\<Omega> \\<circ>\\<^sub>c \\<langle>\\<f> \\<circ>\\<^sub>c \\<beta>\\<^bsub>A\\<^bsup>\\<Omega>\\<^esup>\\<^esub> \\<circ>\\<^sub>c f, id(A\\<^bsup>\\<Omega>\\<^esup>) \\<circ>\\<^sub>c f\\<rangle>\"\n         by (typecheck_cfuncs, simp add: cfunc_prod_comp comp_associative2)\n       also have \"... = eval_func A \\<Omega> \\<circ>\\<^sub>c \\<langle>\\<f>, f\\<rangle>\"\n         by (metis cfunc_type_def f_type id_left_unit id_right_unit id_type one_unique_element terminal_func_comp terminal_func_type false_func_type)\n       also have \"... = eval_func A \\<Omega> \\<circ>\\<^sub>c \\<langle>id(\\<Omega>) \\<circ>\\<^sub>c \\<f>, f \\<circ>\\<^sub>c id(one)\\<rangle>\"\n         by (typecheck_cfuncs, simp add: id_left_unit2 id_right_unit2)\n       also have \"... = eval_func A \\<Omega> \\<circ>\\<^sub>c (id(\\<Omega>) \\<times>\\<^sub>f f) \\<circ>\\<^sub>c \\<langle>\\<f>, id(one)\\<rangle>\"\n         by (typecheck_cfuncs, simp add: cfunc_cross_prod_comp_cfunc_prod)\n       also have \"... = (eval_func A \\<Omega> \\<circ>\\<^sub>c (id(\\<Omega>) \\<times>\\<^sub>f f)) \\<circ>\\<^sub>c \\<langle>\\<f>, id(one)\\<rangle>\"\n         using comp_associative2 by (typecheck_cfuncs, blast)\n       also have \"... = ((a1 \\<amalg> a2) \\<circ>\\<^sub>c case_bool  \\<circ>\\<^sub>c left_cart_proj \\<Omega> one) \\<circ>\\<^sub>c \\<langle>\\<f>, id(one)\\<rangle>\"\n         by (typecheck_cfuncs, metis  aua f_def flat_cancels_sharp inv_transpose_func_def2)\n       also have \"... = (a1 \\<amalg> a2) \\<circ>\\<^sub>c case_bool  \\<circ>\\<^sub>c \\<f>\"\n         by (typecheck_cfuncs, smt aua comp_associative2 left_cart_proj_cfunc_prod)\n       also have \"... = (a1 \\<amalg> a2) \\<circ>\\<^sub>c right_coproj one one\"\n         by (simp add: case_bool_false)\n       also have \"... = a2\"\n         using right_coproj_cfunc_coprod y_def by blast\n       then show ?thesis using calculation by auto\n     qed\n     have \"\\<phi> \\<circ>\\<^sub>c f  = \\<langle>a1,a2\\<rangle>\"\n       unfolding \\<phi>_def by (typecheck_cfuncs, simp add: a1_is a2_is cfunc_prod_comp)\n     then show \"\\<exists>x. x \\<in>\\<^sub>c domain \\<phi> \\<and> \\<phi> \\<circ>\\<^sub>c x = y\"\n       using \\<phi>_type cfunc_type_def f_type y_def by auto\n   qed\n   then have \"epimorphism(\\<phi>)\"\n     by (simp add: surjective_is_epimorphism)\n   then have \"isomorphism(\\<phi>)\"\n     by (simp add: \\<open>monomorphism \\<phi>\\<close> epi_mon_is_iso)\n   then show ?thesis\n     using \\<phi>_type is_isomorphic_def by blast\nqed\n\n\n\n\n\n\n\n(*Perhaps consider putting the next few small lemmas inside the Truth.thy file*)\n\nlemma size_2_sets:\n\"(X \\<cong> \\<Omega>) = (\\<exists> x1. (\\<exists> x2. ((x1 \\<in>\\<^sub>c X) \\<and> (x2 \\<in>\\<^sub>c X) \\<and> (x1\\<noteq>x2) \\<and> (\\<forall>x. x \\<in>\\<^sub>c X \\<longrightarrow> (x=x1) \\<or> (x=x2))  )))\"\n  sorry\n\nlemma size_2plus_sets:\n  \"(\\<Omega>  \\<le>\\<^sub>c  X ) = (\\<exists> x1. (\\<exists> x2. ((x1 \\<in>\\<^sub>c X) \\<and> (x2 \\<in>\\<^sub>c X) \\<and> (x1\\<noteq>x2)  )))\"\nproof(auto, unfold is_smaller_than_def)\n  show \"\\<exists>m. m : \\<Omega> \\<rightarrow> X \\<and> monomorphism m \\<Longrightarrow> \\<exists>x1. x1 \\<in>\\<^sub>c X \\<and> (\\<exists>x2. x2 \\<in>\\<^sub>c X \\<and> x1 \\<noteq> x2)\"\n    by (meson comp_type false_func_type monomorphism_def3 true_false_distinct true_func_type)\nnext\n  show \"\\<And>x1 x2. x1 \\<in>\\<^sub>c X \\<Longrightarrow> x2 \\<in>\\<^sub>c X \\<Longrightarrow> x1 \\<noteq> x2 \\<Longrightarrow> \\<exists>m. m : \\<Omega> \\<rightarrow> X \\<and> monomorphism m\"\n    sorry\n    (*This line in the proof was shown under \"non_init_non_ter_sets\" in the Cardinality.thy file.*)\nqed\n\n\n\nlemma not_init_not_term:\n  \"(\\<not>(initial_object X) \\<and> \\<not>(terminal_object X)) = (\\<exists> x1. (\\<exists> x2. ((x1 \\<in>\\<^sub>c X) \\<and> (x2 \\<in>\\<^sub>c X) \\<and> (x1\\<noteq>x2)  )))\"\n  by (metis initial_iso_empty iso_empty_initial iso_to1_is_term no_el_iff_iso_0 nonempty_def single_elem_iso_one terminal_object_def)\n\nlemma sets_size_3_plus:\n  \"(\\<not>(initial_object X) \\<and> \\<not>(terminal_object X) \\<and> \\<not>(X \\<cong> \\<Omega>)) = (\\<exists> x1. (\\<exists> x2.  \\<exists> x3. ((x1 \\<in>\\<^sub>c X) \\<and> (x2 \\<in>\\<^sub>c X) \\<and>  (x3 \\<in>\\<^sub>c X) \\<and> (x1\\<noteq>x2) \\<and>  (x2\\<noteq>x3) \\<and> (x1\\<noteq>x3) )             ))\"\n  by (metis not_init_not_term size_2_sets)\n\n(*****)\n\n\nlemma prod_leq_exp:\n  assumes \"\\<not>(terminal_object Y)\"\n  shows \"(X \\<times>\\<^sub>c Y) \\<le>\\<^sub>c (Y\\<^bsup>X\\<^esup>)\"\nproof(cases \"initial_object Y\")\n  show \"initial_object Y \\<Longrightarrow> X \\<times>\\<^sub>c Y \\<le>\\<^sub>c Y\\<^bsup>X\\<^esup>\"\n      by (metis initial_iso_empty initial_maps_mono initial_object_def is_smaller_than_def iso_empty_initial no_el_iff_iso_0 prod_with_empty_is_empty2)\n  next\n    assume \"\\<not> initial_object Y\"\n    then obtain y1 y2 where y1_type[type_rule]: \"y1 \\<in>\\<^sub>c Y\" and y2_type[type_rule]: \"y2 \\<in>\\<^sub>c Y\" and y1_not_y2: \"y1\\<noteq>y2\"\n      using assms not_init_not_term by blast\n    show \"(X \\<times>\\<^sub>c Y) \\<le>\\<^sub>c (Y\\<^bsup>X\\<^esup>)\"\n    proof(cases \"X \\<cong> \\<Omega>\")\n      assume \"X \\<cong> \\<Omega>\"\n      have \"\\<Omega>  \\<le>\\<^sub>c  Y\"\n         using \\<open>\\<not> initial_object Y\\<close> assms not_init_not_term size_2plus_sets by blast\n      then obtain m where m_type[type_rule]: \"m : \\<Omega>  \\<rightarrow>  Y\" and m_mono: \"monomorphism m\"\n        using is_smaller_than_def by blast\n      then have m_id_type[type_rule]: \"m \\<times>\\<^sub>f id(Y) : \\<Omega> \\<times>\\<^sub>c Y \\<rightarrow> Y \\<times>\\<^sub>c Y\"\n        by typecheck_cfuncs\n      have m_id_mono: \"monomorphism (m \\<times>\\<^sub>f id(Y))\"\n        by (typecheck_cfuncs, simp add: cfunc_cross_prod_mono id_isomorphism iso_imp_epi_and_monic m_mono)  \n      obtain n where n_type[type_rule]: \"n : Y \\<times>\\<^sub>c Y  \\<rightarrow>  Y\\<^bsup>\\<Omega>\\<^esup>\" and n_mono: \"monomorphism n\"\n        by (metis epis_give_monos is_isomorphic_def iso_imp_epi_and_monic sets_squared)\n      obtain r where r_type[type_rule]: \"r : Y\\<^bsup>\\<Omega>\\<^esup>  \\<rightarrow>  Y\\<^bsup>X\\<^esup>\" and r_mono: \"monomorphism r\"\n        by (meson \\<open>X \\<cong> \\<Omega>\\<close> exp_pres_iso_right is_isomorphic_def iso_imp_epi_and_monic isomorphic_is_symmetric)\n      obtain q where q_type[type_rule]: \"q : X \\<times>\\<^sub>c Y  \\<rightarrow>  \\<Omega> \\<times>\\<^sub>c Y\" and q_mono: \"monomorphism q\"\n        by (meson \\<open>X \\<cong> \\<Omega>\\<close> id_isomorphism id_type is_isomorphic_def iso_imp_epi_and_monic prod_pres_iso) \n      have rnmq_type[type_rule]: \"r \\<circ>\\<^sub>c n \\<circ>\\<^sub>c (m \\<times>\\<^sub>f id(Y)) \\<circ>\\<^sub>c q : X \\<times>\\<^sub>c Y \\<rightarrow> Y\\<^bsup>X\\<^esup>\"\n        by typecheck_cfuncs\n      have \"monomorphism(r \\<circ>\\<^sub>c n \\<circ>\\<^sub>c (m \\<times>\\<^sub>f id(Y)) \\<circ>\\<^sub>c q)\"\n        by (typecheck_cfuncs, simp add: cfunc_type_def composition_of_monic_pair_is_monic m_id_mono n_mono q_mono r_mono)\n      then show ?thesis\n        by (meson is_smaller_than_def rnmq_type)\n    next\n      assume \"\\<not> X \\<cong> \\<Omega>\"\n      show \"X \\<times>\\<^sub>c Y \\<le>\\<^sub>c Y\\<^bsup>X\\<^esup>\"\n      proof(cases \"initial_object X\")\n        show \"initial_object X \\<Longrightarrow> X \\<times>\\<^sub>c Y \\<le>\\<^sub>c Y\\<^bsup>X\\<^esup>\"\n          by (metis initial_iso_empty initial_maps_mono initial_object_def is_smaller_than_def iso_empty_initial no_el_iff_iso_0 prod_with_empty_is_empty1)\n      next\n      assume \"\\<not> initial_object X\"\n      show \"X \\<times>\\<^sub>c Y \\<le>\\<^sub>c Y\\<^bsup>X\\<^esup>\"\n      proof(cases \"terminal_object X\")\n        assume \"terminal_object X\"\n        then have \"X \\<cong> one\"\n          by (simp add: one_terminal_object terminal_objects_isomorphic)\n        have \"X \\<times>\\<^sub>c Y \\<cong> Y\"\n          by (simp add: \\<open>terminal_object X\\<close> prod_with_term_obj1)\n        then have \"X \\<times>\\<^sub>c Y \\<cong> Y\\<^bsup>X\\<^esup>\"\n          by (meson \\<open>X \\<cong> one\\<close> exp_pres_iso_right exp_set_inj isomorphic_is_symmetric isomorphic_is_transitive set_to_power_one)\n        then show ?thesis\n          using is_isomorphic_def is_smaller_than_def iso_imp_epi_and_monic by blast\n      next\n        assume \"\\<not> terminal_object X\"\n\n        obtain into where into_def: \"into = (left_cart_proj Y one \\<amalg> ((y2 \\<amalg> y1) \\<circ>\\<^sub>c case_bool \\<circ>\\<^sub>c eq_pred Y \\<circ>\\<^sub>c (id Y \\<times>\\<^sub>f y1))) \n                               \\<circ>\\<^sub>c dist_prod_coprod_inv Y one one \\<circ>\\<^sub>c (id Y \\<times>\\<^sub>f case_bool) \\<circ>\\<^sub>c (id Y \\<times>\\<^sub>f eq_pred X) \"\n          by simp\n        then have into_type[type_rule]: \"into : Y \\<times>\\<^sub>c (X \\<times>\\<^sub>c X) \\<rightarrow> Y\"\n          by (simp, typecheck_cfuncs)\n   \n\n        obtain \\<Theta> where \\<Theta>_def: \"\\<Theta> = (into \\<circ>\\<^sub>c associate_right Y X X \\<circ>\\<^sub>c swap X (Y \\<times>\\<^sub>c X))\\<^sup>\\<sharp> \\<circ>\\<^sub>c swap X Y\"\n          by auto\n  \n        have \\<Theta>_type[type_rule]: \"\\<Theta> : X \\<times>\\<^sub>c Y \\<rightarrow> Y\\<^bsup>X\\<^esup>\"\n          unfolding \\<Theta>_def by typecheck_cfuncs\n\n        have f0: \"\\<And>x. \\<And> y. \\<And> z. x \\<in>\\<^sub>c X \\<and> y \\<in>\\<^sub>c Y \\<and> z \\<in>\\<^sub>c X \\<Longrightarrow> (\\<Theta> \\<circ>\\<^sub>c \\<langle>x, y\\<rangle>)\\<^sup>\\<flat> \\<circ>\\<^sub>c \\<langle>id X, \\<beta>\\<^bsub>X\\<^esub>\\<rangle> \\<circ>\\<^sub>c z = into \\<circ>\\<^sub>c   \\<langle>y, \\<langle>x, z\\<rangle>\\<rangle>\"\n        proof(auto)\n          fix x y z\n          assume x_type[type_rule]: \"x \\<in>\\<^sub>c X\"\n          assume y_type[type_rule]: \"y \\<in>\\<^sub>c Y\"\n          assume z_type[type_rule]: \"z \\<in>\\<^sub>c X\"\n          show \"(\\<Theta> \\<circ>\\<^sub>c \\<langle>x,y\\<rangle>)\\<^sup>\\<flat> \\<circ>\\<^sub>c \\<langle>id\\<^sub>c X,\\<beta>\\<^bsub>X\\<^esub>\\<rangle> \\<circ>\\<^sub>c z = into \\<circ>\\<^sub>c \\<langle>y,\\<langle>x,z\\<rangle>\\<rangle>\"\n          proof - \n            have \"(\\<Theta> \\<circ>\\<^sub>c \\<langle>x,y\\<rangle>)\\<^sup>\\<flat> \\<circ>\\<^sub>c \\<langle>id\\<^sub>c X,\\<beta>\\<^bsub>X\\<^esub>\\<rangle> \\<circ>\\<^sub>c z = (\\<Theta> \\<circ>\\<^sub>c \\<langle>x,y\\<rangle>)\\<^sup>\\<flat> \\<circ>\\<^sub>c \\<langle>id\\<^sub>c X \\<circ>\\<^sub>c z,\\<beta>\\<^bsub>X\\<^esub> \\<circ>\\<^sub>c z\\<rangle>\"\n              by (typecheck_cfuncs, simp add: cfunc_prod_comp)\n            also have \"... = (\\<Theta> \\<circ>\\<^sub>c \\<langle>x,y\\<rangle>)\\<^sup>\\<flat> \\<circ>\\<^sub>c \\<langle>z,id one\\<rangle>\"\n              by (typecheck_cfuncs, metis id_left_unit2 one_unique_element)\n            also have \"... = (\\<Theta>\\<^sup>\\<flat> \\<circ>\\<^sub>c (id(X) \\<times>\\<^sub>f \\<langle>x,y\\<rangle>)) \\<circ>\\<^sub>c \\<langle>z,id one\\<rangle>\"\n              using inv_transpose_of_composition by (typecheck_cfuncs, presburger)\n            also have \"... = \\<Theta>\\<^sup>\\<flat> \\<circ>\\<^sub>c (id(X) \\<times>\\<^sub>f \\<langle>x,y\\<rangle>) \\<circ>\\<^sub>c \\<langle>z,id one\\<rangle>\"\n              using comp_associative2 by (typecheck_cfuncs, auto)\n            also have \"... = \\<Theta>\\<^sup>\\<flat> \\<circ>\\<^sub>c \\<langle>id(X) \\<circ>\\<^sub>c  z, \\<langle>x,y\\<rangle> \\<circ>\\<^sub>c  id one\\<rangle>\"\n              by (typecheck_cfuncs, simp add: cfunc_cross_prod_comp_cfunc_prod)\n            also have \"... = \\<Theta>\\<^sup>\\<flat> \\<circ>\\<^sub>c \\<langle>z,\\<langle>x,y\\<rangle>\\<rangle>\"\n              by (typecheck_cfuncs, simp add: id_left_unit2 id_right_unit2)\n            also have \"... = ((into \\<circ>\\<^sub>c associate_right Y X X \\<circ>\\<^sub>c swap X (Y \\<times>\\<^sub>c X))\\<^sup>\\<sharp> \\<circ>\\<^sub>c swap X Y)\\<^sup>\\<flat> \\<circ>\\<^sub>c \\<langle>z,\\<langle>x,y\\<rangle>\\<rangle>\"\n              by (simp add: \\<Theta>_def)\n            also have \"... = ((into \\<circ>\\<^sub>c associate_right Y X X \\<circ>\\<^sub>c swap X (Y \\<times>\\<^sub>c X))\\<^sup>\\<sharp>\\<^sup>\\<flat> \\<circ>\\<^sub>c (id X \\<times>\\<^sub>f swap X Y)) \\<circ>\\<^sub>c \\<langle>z,\\<langle>x,y\\<rangle>\\<rangle>\"\n              using inv_transpose_of_composition by (typecheck_cfuncs, presburger)\n            also have \"... = (into \\<circ>\\<^sub>c associate_right Y X X \\<circ>\\<^sub>c swap X (Y \\<times>\\<^sub>c X)) \\<circ>\\<^sub>c  (id X \\<times>\\<^sub>f swap X Y) \\<circ>\\<^sub>c \\<langle>z,\\<langle>x,y\\<rangle>\\<rangle>\"\n              by (typecheck_cfuncs, simp add: comp_associative2 inv_transpose_func_def2 transpose_func_def)\n            also have \"... = (into \\<circ>\\<^sub>c associate_right Y X X \\<circ>\\<^sub>c swap X (Y \\<times>\\<^sub>c X)) \\<circ>\\<^sub>c  \\<langle>id X \\<circ>\\<^sub>c z, swap X Y \\<circ>\\<^sub>c \\<langle>x,y\\<rangle>\\<rangle>\"\n              by (typecheck_cfuncs, simp add: cfunc_cross_prod_comp_cfunc_prod)\n            also have \"... = (into \\<circ>\\<^sub>c associate_right Y X X \\<circ>\\<^sub>c swap X (Y \\<times>\\<^sub>c X)) \\<circ>\\<^sub>c  \\<langle>z, \\<langle>y,x\\<rangle>\\<rangle>\"\n              using id_left_unit2 swap_ap by (typecheck_cfuncs, presburger)\n            also have \"... = into \\<circ>\\<^sub>c associate_right Y X X \\<circ>\\<^sub>c swap X (Y \\<times>\\<^sub>c X) \\<circ>\\<^sub>c  \\<langle>z, \\<langle>y,x\\<rangle>\\<rangle>\"\n              by (typecheck_cfuncs, metis cfunc_type_def comp_associative)\n            also have \"... = into \\<circ>\\<^sub>c associate_right Y X X \\<circ>\\<^sub>c   \\<langle>\\<langle>y,x\\<rangle>, z\\<rangle>\"\n              using swap_ap by (typecheck_cfuncs, presburger)\n            also have \"... = into \\<circ>\\<^sub>c   \\<langle>y, \\<langle>x, z\\<rangle>\\<rangle>\"\n              using associate_right_ap by (typecheck_cfuncs, presburger)\n            then show ?thesis\n              using calculation by presburger\n          qed\n        qed\n  \n        have f1: \"\\<And>x y. x \\<in>\\<^sub>c X \\<Longrightarrow> y \\<in>\\<^sub>c Y  \\<Longrightarrow> (\\<Theta> \\<circ>\\<^sub>c \\<langle>x, y\\<rangle>)\\<^sup>\\<flat> \\<circ>\\<^sub>c \\<langle>id X, \\<beta>\\<^bsub>X\\<^esub>\\<rangle> \\<circ>\\<^sub>c x = y\"\n        proof - \n          fix x y \n          assume x_type[type_rule]: \"x \\<in>\\<^sub>c X\"\n          assume y_type[type_rule]: \"y \\<in>\\<^sub>c Y\"\n          have \"(\\<Theta> \\<circ>\\<^sub>c \\<langle>x, y\\<rangle>)\\<^sup>\\<flat> \\<circ>\\<^sub>c \\<langle>id X, \\<beta>\\<^bsub>X\\<^esub>\\<rangle> \\<circ>\\<^sub>c x = into \\<circ>\\<^sub>c   \\<langle>y, \\<langle>x, x\\<rangle>\\<rangle>\"\n            by (simp add: f0 x_type y_type)\n          also have \"... = (left_cart_proj Y one \\<amalg> ((y2 \\<amalg> y1) \\<circ>\\<^sub>c case_bool \\<circ>\\<^sub>c eq_pred Y \\<circ>\\<^sub>c (id Y \\<times>\\<^sub>f y1)))\n                                 \\<circ>\\<^sub>c dist_prod_coprod_inv Y one one \\<circ>\\<^sub>c (id Y \\<times>\\<^sub>f case_bool) \\<circ>\\<^sub>c (id Y \\<times>\\<^sub>f eq_pred X) \\<circ>\\<^sub>c   \\<langle>y, \\<langle>x, x\\<rangle>\\<rangle>\"\n            using cfunc_type_def comp_associative comp_type into_def by (typecheck_cfuncs, fastforce)\n          also have \"... = (left_cart_proj Y one \\<amalg> ((y2 \\<amalg> y1) \\<circ>\\<^sub>c case_bool \\<circ>\\<^sub>c eq_pred Y \\<circ>\\<^sub>c (id Y \\<times>\\<^sub>f y1)))\n                                 \\<circ>\\<^sub>c dist_prod_coprod_inv Y one one \\<circ>\\<^sub>c (id Y \\<times>\\<^sub>f case_bool) \\<circ>\\<^sub>c  \\<langle>id Y \\<circ>\\<^sub>c y, eq_pred X \\<circ>\\<^sub>c  \\<langle>x, x\\<rangle>\\<rangle>\"\n            by (typecheck_cfuncs, simp add: cfunc_cross_prod_comp_cfunc_prod)\n         also have \"... = (left_cart_proj Y one \\<amalg> ((y2 \\<amalg> y1) \\<circ>\\<^sub>c case_bool \\<circ>\\<^sub>c eq_pred Y \\<circ>\\<^sub>c (id Y \\<times>\\<^sub>f y1))) \n                                 \\<circ>\\<^sub>c dist_prod_coprod_inv Y one one \\<circ>\\<^sub>c (id Y \\<times>\\<^sub>f case_bool) \\<circ>\\<^sub>c  \\<langle>y, \\<t>\\<rangle>\"\n            by (typecheck_cfuncs, metis eq_pred_iff_eq id_left_unit2)\n          also have \"... = (left_cart_proj Y one \\<amalg> ((y2 \\<amalg> y1) \\<circ>\\<^sub>c case_bool \\<circ>\\<^sub>c eq_pred Y \\<circ>\\<^sub>c (id Y \\<times>\\<^sub>f y1))) \n                                 \\<circ>\\<^sub>c dist_prod_coprod_inv Y one one  \\<circ>\\<^sub>c  \\<langle>y, left_coproj one one\\<rangle>\"\n            by (typecheck_cfuncs, simp add: case_bool_true cfunc_cross_prod_comp_cfunc_prod id_left_unit2)\n          also have \"... = (left_cart_proj Y one \\<amalg> ((y2 \\<amalg> y1) \\<circ>\\<^sub>c case_bool \\<circ>\\<^sub>c eq_pred Y \\<circ>\\<^sub>c (id Y \\<times>\\<^sub>f y1))) \n                                 \\<circ>\\<^sub>c dist_prod_coprod_inv Y one one  \\<circ>\\<^sub>c  \\<langle>y, left_coproj one one \\<circ>\\<^sub>c id one\\<rangle>\"\n            by (typecheck_cfuncs, metis id_right_unit2)\n          also have \"... = (left_cart_proj Y one \\<amalg> ((y2 \\<amalg> y1) \\<circ>\\<^sub>c case_bool \\<circ>\\<^sub>c eq_pred Y \\<circ>\\<^sub>c (id Y \\<times>\\<^sub>f y1))) \n                                 \\<circ>\\<^sub>c left_coproj (Y \\<times>\\<^sub>c one) (Y \\<times>\\<^sub>c one) \\<circ>\\<^sub>c \\<langle>y,id one\\<rangle>\"\n            using dist_prod_coprod_inv_left_ap by (typecheck_cfuncs, presburger)\n          also have \"... = ((left_cart_proj Y one \\<amalg> ((y2 \\<amalg> y1) \\<circ>\\<^sub>c case_bool \\<circ>\\<^sub>c eq_pred Y \\<circ>\\<^sub>c (id Y \\<times>\\<^sub>f y1))) \n                                 \\<circ>\\<^sub>c left_coproj (Y \\<times>\\<^sub>c one) (Y \\<times>\\<^sub>c one)) \\<circ>\\<^sub>c \\<langle>y,id one\\<rangle>\"\n            by (typecheck_cfuncs, meson comp_associative2)\n          also have \"... = left_cart_proj Y one \\<circ>\\<^sub>c \\<langle>y,id one\\<rangle>\"\n            using left_coproj_cfunc_coprod by (typecheck_cfuncs, presburger)\n          also have \"... = y\"\n            by (typecheck_cfuncs, simp add: left_cart_proj_cfunc_prod)\n          then show \"(\\<Theta> \\<circ>\\<^sub>c \\<langle>x, y\\<rangle>)\\<^sup>\\<flat> \\<circ>\\<^sub>c \\<langle>id X, \\<beta>\\<^bsub>X\\<^esub>\\<rangle> \\<circ>\\<^sub>c x = y\"\n            by (simp add: calculation into_def)\n        qed\n  \n        have f2: \"\\<And>x y z. x \\<in>\\<^sub>c X \\<Longrightarrow> y \\<in>\\<^sub>c Y  \\<Longrightarrow>  z \\<in>\\<^sub>c X \\<Longrightarrow> z \\<noteq> x \\<Longrightarrow> y \\<noteq> y1 \\<Longrightarrow> (\\<Theta> \\<circ>\\<^sub>c \\<langle>x, y\\<rangle>)\\<^sup>\\<flat> \\<circ>\\<^sub>c \\<langle>id X, \\<beta>\\<^bsub>X\\<^esub>\\<rangle> \\<circ>\\<^sub>c z = y1\"\n        proof - \n          fix x y z\n          assume x_type[type_rule]: \"x \\<in>\\<^sub>c X\"\n          assume y_type[type_rule]: \"y \\<in>\\<^sub>c Y\"\n          assume z_type[type_rule]: \"z \\<in>\\<^sub>c X\"\n          assume \"z \\<noteq> x\"\n          assume \"y \\<noteq> y1\"\n          have \"(\\<Theta> \\<circ>\\<^sub>c \\<langle>x, y\\<rangle>)\\<^sup>\\<flat> \\<circ>\\<^sub>c \\<langle>id X, \\<beta>\\<^bsub>X\\<^esub>\\<rangle> \\<circ>\\<^sub>c z = into \\<circ>\\<^sub>c   \\<langle>y, \\<langle>x, z\\<rangle>\\<rangle>\"\n            by (simp add: f0 x_type y_type z_type)\n          also have \"... = (left_cart_proj Y one \\<amalg> ((y2 \\<amalg> y1) \\<circ>\\<^sub>c case_bool \\<circ>\\<^sub>c eq_pred Y \\<circ>\\<^sub>c (id Y \\<times>\\<^sub>f y1)))\n                                 \\<circ>\\<^sub>c dist_prod_coprod_inv Y one one \\<circ>\\<^sub>c (id Y \\<times>\\<^sub>f case_bool) \\<circ>\\<^sub>c (id Y \\<times>\\<^sub>f eq_pred X) \\<circ>\\<^sub>c   \\<langle>y, \\<langle>x, z\\<rangle>\\<rangle>\"\n            using cfunc_type_def comp_associative comp_type into_def by (typecheck_cfuncs, fastforce)\n          also have \"... = (left_cart_proj Y one \\<amalg> ((y2 \\<amalg> y1) \\<circ>\\<^sub>c case_bool \\<circ>\\<^sub>c eq_pred Y \\<circ>\\<^sub>c (id Y \\<times>\\<^sub>f y1)))\n                                 \\<circ>\\<^sub>c dist_prod_coprod_inv Y one one \\<circ>\\<^sub>c (id Y \\<times>\\<^sub>f case_bool) \\<circ>\\<^sub>c  \\<langle>id Y \\<circ>\\<^sub>c y, eq_pred X \\<circ>\\<^sub>c  \\<langle>x, z\\<rangle>\\<rangle>\"\n            by (typecheck_cfuncs, simp add: cfunc_cross_prod_comp_cfunc_prod)\n          also have \"... = (left_cart_proj Y one \\<amalg> ((y2 \\<amalg> y1) \\<circ>\\<^sub>c case_bool \\<circ>\\<^sub>c eq_pred Y \\<circ>\\<^sub>c (id Y \\<times>\\<^sub>f y1))) \n                                 \\<circ>\\<^sub>c dist_prod_coprod_inv Y one one \\<circ>\\<^sub>c (id Y \\<times>\\<^sub>f case_bool) \\<circ>\\<^sub>c  \\<langle>y, \\<f>\\<rangle>\"\n            by (typecheck_cfuncs, metis \\<open>z \\<noteq> x\\<close> eq_pred_iff_eq_conv id_left_unit2)\n          also have \"... = (left_cart_proj Y one \\<amalg> ((y2 \\<amalg> y1) \\<circ>\\<^sub>c case_bool \\<circ>\\<^sub>c eq_pred Y \\<circ>\\<^sub>c (id Y \\<times>\\<^sub>f y1))) \n                                 \\<circ>\\<^sub>c dist_prod_coprod_inv Y one one  \\<circ>\\<^sub>c  \\<langle>y, right_coproj one one\\<rangle>\"\n            by (typecheck_cfuncs, simp add: case_bool_false cfunc_cross_prod_comp_cfunc_prod id_left_unit2)\n          also have \"... = (left_cart_proj Y one \\<amalg> ((y2 \\<amalg> y1) \\<circ>\\<^sub>c case_bool \\<circ>\\<^sub>c eq_pred Y \\<circ>\\<^sub>c (id Y \\<times>\\<^sub>f y1)))\n                                 \\<circ>\\<^sub>c dist_prod_coprod_inv Y one one  \\<circ>\\<^sub>c  \\<langle>y, right_coproj one one \\<circ>\\<^sub>c id one\\<rangle>\"\n            by (typecheck_cfuncs, simp add: id_right_unit2)\n          also have \"... = (left_cart_proj Y one \\<amalg> ((y2 \\<amalg> y1) \\<circ>\\<^sub>c case_bool \\<circ>\\<^sub>c eq_pred Y \\<circ>\\<^sub>c (id Y \\<times>\\<^sub>f y1)))\n                                 \\<circ>\\<^sub>c right_coproj (Y \\<times>\\<^sub>c one) (Y \\<times>\\<^sub>c one) \\<circ>\\<^sub>c \\<langle>y,id one\\<rangle>\"\n            using dist_prod_coprod_inv_right_ap by (typecheck_cfuncs, presburger)\n          also have \"... = ((left_cart_proj Y one \\<amalg> ((y2 \\<amalg> y1) \\<circ>\\<^sub>c case_bool \\<circ>\\<^sub>c eq_pred Y \\<circ>\\<^sub>c (id Y \\<times>\\<^sub>f y1))) \n                                 \\<circ>\\<^sub>c right_coproj (Y \\<times>\\<^sub>c one) (Y \\<times>\\<^sub>c one)) \\<circ>\\<^sub>c \\<langle>y,id one\\<rangle>\"\n            by (typecheck_cfuncs, meson comp_associative2)\n          also have \"... = ((y2 \\<amalg> y1) \\<circ>\\<^sub>c case_bool \\<circ>\\<^sub>c eq_pred Y \\<circ>\\<^sub>c (id Y \\<times>\\<^sub>f y1)) \\<circ>\\<^sub>c \\<langle>y,id one\\<rangle>\"\n            using right_coproj_cfunc_coprod by (typecheck_cfuncs, auto)\n          also have \"... = (y2 \\<amalg> y1) \\<circ>\\<^sub>c case_bool \\<circ>\\<^sub>c eq_pred Y \\<circ>\\<^sub>c (id Y \\<times>\\<^sub>f y1) \\<circ>\\<^sub>c \\<langle>y,id one\\<rangle>\"\n            using comp_associative2 by (typecheck_cfuncs, force)\n          also have \"... = (y2 \\<amalg> y1) \\<circ>\\<^sub>c case_bool \\<circ>\\<^sub>c eq_pred Y  \\<circ>\\<^sub>c \\<langle>y,y1\\<rangle>\"\n            by (typecheck_cfuncs, simp add: cfunc_cross_prod_comp_cfunc_prod id_left_unit2 id_right_unit2)\n          also have \"... = (y2 \\<amalg> y1) \\<circ>\\<^sub>c case_bool \\<circ>\\<^sub>c \\<f>\"\n            by (typecheck_cfuncs, metis \\<open>y \\<noteq> y1\\<close> eq_pred_iff_eq_conv)\n          also have \"... = y1\"\n            using case_bool_false right_coproj_cfunc_coprod by (typecheck_cfuncs, presburger)\n          then show \"(\\<Theta> \\<circ>\\<^sub>c \\<langle>x, y\\<rangle>)\\<^sup>\\<flat> \\<circ>\\<^sub>c \\<langle>id X, \\<beta>\\<^bsub>X\\<^esub>\\<rangle> \\<circ>\\<^sub>c z = y1\"\n            by (simp add: calculation)\n        qed\n      \n  \n  \n  \n        have f3: \"\\<And>x z. x \\<in>\\<^sub>c X \\<Longrightarrow>  z \\<in>\\<^sub>c X \\<Longrightarrow> z \\<noteq> x \\<Longrightarrow>  (\\<Theta> \\<circ>\\<^sub>c \\<langle>x, y1\\<rangle>)\\<^sup>\\<flat> \\<circ>\\<^sub>c \\<langle>id X, \\<beta>\\<^bsub>X\\<^esub>\\<rangle> \\<circ>\\<^sub>c z = y2\"\n        proof - \n          fix x y z\n          assume x_type[type_rule]: \"x \\<in>\\<^sub>c X\"\n          assume z_type[type_rule]: \"z \\<in>\\<^sub>c X\"\n          assume \"z \\<noteq> x\"\n          have \"(\\<Theta> \\<circ>\\<^sub>c \\<langle>x, y1\\<rangle>)\\<^sup>\\<flat> \\<circ>\\<^sub>c \\<langle>id X, \\<beta>\\<^bsub>X\\<^esub>\\<rangle> \\<circ>\\<^sub>c z = into \\<circ>\\<^sub>c   \\<langle>y1, \\<langle>x, z\\<rangle>\\<rangle>\"\n            by (simp add: f0 x_type y1_type z_type)\n          also have \"... = (left_cart_proj Y one \\<amalg> ((y2 \\<amalg> y1) \\<circ>\\<^sub>c case_bool \\<circ>\\<^sub>c eq_pred Y \\<circ>\\<^sub>c (id Y \\<times>\\<^sub>f y1)))\n                                 \\<circ>\\<^sub>c dist_prod_coprod_inv Y one one \\<circ>\\<^sub>c (id Y \\<times>\\<^sub>f case_bool) \\<circ>\\<^sub>c (id Y \\<times>\\<^sub>f eq_pred X) \\<circ>\\<^sub>c   \\<langle>y1, \\<langle>x, z\\<rangle>\\<rangle>\"\n            using cfunc_type_def comp_associative comp_type into_def by (typecheck_cfuncs, fastforce)\n          also have \"... = (left_cart_proj Y one \\<amalg> ((y2 \\<amalg> y1) \\<circ>\\<^sub>c case_bool \\<circ>\\<^sub>c eq_pred Y \\<circ>\\<^sub>c (id Y \\<times>\\<^sub>f y1)))\n                                 \\<circ>\\<^sub>c dist_prod_coprod_inv Y one one \\<circ>\\<^sub>c (id Y \\<times>\\<^sub>f case_bool) \\<circ>\\<^sub>c  \\<langle>id Y \\<circ>\\<^sub>c y1, eq_pred X \\<circ>\\<^sub>c  \\<langle>x, z\\<rangle>\\<rangle>\"\n            by (typecheck_cfuncs, simp add: cfunc_cross_prod_comp_cfunc_prod)\n          also have \"... = (left_cart_proj Y one \\<amalg> ((y2 \\<amalg> y1) \\<circ>\\<^sub>c case_bool \\<circ>\\<^sub>c eq_pred Y \\<circ>\\<^sub>c (id Y \\<times>\\<^sub>f y1))) \n                                 \\<circ>\\<^sub>c dist_prod_coprod_inv Y one one \\<circ>\\<^sub>c (id Y \\<times>\\<^sub>f case_bool) \\<circ>\\<^sub>c  \\<langle>y1, \\<f>\\<rangle>\"\n            by (typecheck_cfuncs, metis \\<open>z \\<noteq> x\\<close> eq_pred_iff_eq_conv id_left_unit2)\n          also have \"... = (left_cart_proj Y one \\<amalg> ((y2 \\<amalg> y1) \\<circ>\\<^sub>c case_bool \\<circ>\\<^sub>c eq_pred Y \\<circ>\\<^sub>c (id Y \\<times>\\<^sub>f y1))) \n                                 \\<circ>\\<^sub>c dist_prod_coprod_inv Y one one  \\<circ>\\<^sub>c  \\<langle>y1, right_coproj one one\\<rangle>\"\n            by (typecheck_cfuncs, simp add: case_bool_false cfunc_cross_prod_comp_cfunc_prod id_left_unit2)\n          also have \"... = (left_cart_proj Y one \\<amalg> ((y2 \\<amalg> y1) \\<circ>\\<^sub>c case_bool \\<circ>\\<^sub>c eq_pred Y \\<circ>\\<^sub>c (id Y \\<times>\\<^sub>f y1)))\n                                 \\<circ>\\<^sub>c dist_prod_coprod_inv Y one one  \\<circ>\\<^sub>c  \\<langle>y1, right_coproj one one \\<circ>\\<^sub>c id one\\<rangle>\"\n            by (typecheck_cfuncs, simp add: id_right_unit2)\n          also have \"... = (left_cart_proj Y one \\<amalg> ((y2 \\<amalg> y1) \\<circ>\\<^sub>c case_bool \\<circ>\\<^sub>c eq_pred Y \\<circ>\\<^sub>c (id Y \\<times>\\<^sub>f y1)))\n                                 \\<circ>\\<^sub>c right_coproj (Y \\<times>\\<^sub>c one) (Y \\<times>\\<^sub>c one) \\<circ>\\<^sub>c \\<langle>y1,id one\\<rangle>\"\n            using dist_prod_coprod_inv_right_ap by (typecheck_cfuncs, presburger)\n          also have \"... = ((left_cart_proj Y one \\<amalg> ((y2 \\<amalg> y1) \\<circ>\\<^sub>c case_bool \\<circ>\\<^sub>c eq_pred Y \\<circ>\\<^sub>c (id Y \\<times>\\<^sub>f y1))) \n                                 \\<circ>\\<^sub>c right_coproj (Y \\<times>\\<^sub>c one) (Y \\<times>\\<^sub>c one)) \\<circ>\\<^sub>c \\<langle>y1,id one\\<rangle>\"\n            by (typecheck_cfuncs, meson comp_associative2)\n          also have \"... = ((y2 \\<amalg> y1) \\<circ>\\<^sub>c case_bool \\<circ>\\<^sub>c eq_pred Y \\<circ>\\<^sub>c (id Y \\<times>\\<^sub>f y1)) \\<circ>\\<^sub>c \\<langle>y1,id one\\<rangle>\"\n            using right_coproj_cfunc_coprod by (typecheck_cfuncs, auto)\n          also have \"... = (y2 \\<amalg> y1) \\<circ>\\<^sub>c case_bool \\<circ>\\<^sub>c eq_pred Y \\<circ>\\<^sub>c (id Y \\<times>\\<^sub>f y1) \\<circ>\\<^sub>c \\<langle>y1,id one\\<rangle>\"\n            using comp_associative2 by (typecheck_cfuncs, force)\n          also have \"... = (y2 \\<amalg> y1) \\<circ>\\<^sub>c case_bool \\<circ>\\<^sub>c eq_pred Y  \\<circ>\\<^sub>c \\<langle>y1,y1\\<rangle>\"\n            by (typecheck_cfuncs, simp add: cfunc_cross_prod_comp_cfunc_prod id_left_unit2 id_right_unit2)\n          also have \"... = (y2 \\<amalg> y1) \\<circ>\\<^sub>c case_bool \\<circ>\\<^sub>c \\<t>\"\n            by (typecheck_cfuncs, metis eq_pred_iff_eq)\n          also have \"... = y2\"\n            using case_bool_true left_coproj_cfunc_coprod by (typecheck_cfuncs, presburger)\n          then show \"(\\<Theta> \\<circ>\\<^sub>c \\<langle>x, y1\\<rangle>)\\<^sup>\\<flat> \\<circ>\\<^sub>c \\<langle>id X, \\<beta>\\<^bsub>X\\<^esub>\\<rangle> \\<circ>\\<^sub>c z = y2\"\n            by (simp add: calculation)\n        qed\n  \n     have \\<Theta>_injective: \"injective(\\<Theta>)\"\n     proof(unfold injective_def, auto)\n       fix xy st\n       assume xy_type[type_rule]: \"xy \\<in>\\<^sub>c domain \\<Theta>\"\n       assume st_type[type_rule]: \"st \\<in>\\<^sub>c domain \\<Theta>\"\n       assume equals: \"\\<Theta> \\<circ>\\<^sub>c xy = \\<Theta> \\<circ>\\<^sub>c st\"\n       obtain x y where x_type[type_rule]: \"x \\<in>\\<^sub>c X\" and y_type[type_rule]: \"y \\<in>\\<^sub>c Y\" and xy_def: \"xy = \\<langle>x,y\\<rangle>\"\n         by (metis \\<Theta>_type cart_prod_decomp cfunc_type_def xy_type)\n       obtain s t where s_type[type_rule]: \"s \\<in>\\<^sub>c X\" and t_type[type_rule]: \"t \\<in>\\<^sub>c Y\" and st_def: \"st = \\<langle>s,t\\<rangle>\"\n         by (metis \\<Theta>_type cart_prod_decomp cfunc_type_def st_type)   \n       have equals2: \"\\<Theta> \\<circ>\\<^sub>c \\<langle>x,y\\<rangle> = \\<Theta> \\<circ>\\<^sub>c \\<langle>s,t\\<rangle>\"\n         using equals st_def xy_def by auto\n       have \"\\<langle>x,y\\<rangle> = \\<langle>s,t\\<rangle>\"\n       proof(cases \"y = y1\")  \n         assume \"y = y1\"\n         show \"\\<langle>x,y\\<rangle> = \\<langle>s,t\\<rangle>\"\n         proof(cases \"t = y1\")\n           show \"t = y1 \\<Longrightarrow> \\<langle>x,y\\<rangle> = \\<langle>s,t\\<rangle>\"\n             by (typecheck_cfuncs, metis \\<open>y = y1\\<close> equals f1 f3 st_def xy_def y1_not_y2)\n         next\n           assume \"t \\<noteq> y1\"\n           show \"\\<langle>x,y\\<rangle> = \\<langle>s,t\\<rangle>\"\n           proof(cases \"s = x\")\n             show \"s = x \\<Longrightarrow> \\<langle>x,y\\<rangle> = \\<langle>s,t\\<rangle>\"\n               by (typecheck_cfuncs, metis equals2 f1)\n           next\n             assume \"s \\<noteq> x\"  (*This step, in particular, is why we require X to not be isomorphic to Omega*)\n             obtain z where z_type[type_rule]: \"z \\<in>\\<^sub>c X\" and z_not_x: \"z \\<noteq> x\" and z_not_s: \"z \\<noteq> s\"\n               by (metis \\<open>\\<not> X \\<cong> \\<Omega>\\<close> \\<open>\\<not> initial_object X\\<close> \\<open>\\<not> terminal_object X\\<close> sets_size_3_plus)\n             have t_sz: \"(\\<Theta> \\<circ>\\<^sub>c \\<langle>s, t\\<rangle>)\\<^sup>\\<flat> \\<circ>\\<^sub>c \\<langle>id X, \\<beta>\\<^bsub>X\\<^esub>\\<rangle> \\<circ>\\<^sub>c z = y1\"\n               by (simp add: \\<open>t \\<noteq> y1\\<close> f2 s_type t_type z_not_s z_type)\n             have y_xz: \"(\\<Theta> \\<circ>\\<^sub>c \\<langle>x, y\\<rangle>)\\<^sup>\\<flat> \\<circ>\\<^sub>c \\<langle>id X, \\<beta>\\<^bsub>X\\<^esub>\\<rangle> \\<circ>\\<^sub>c z = y2\"\n               by (simp add: \\<open>y = y1\\<close> f3 x_type z_not_x z_type)    \n             then have \"y1 = y2\"\n               using equals2 t_sz by auto\n             then have False\n               using y1_not_y2 by auto\n             then show \"\\<langle>x,y\\<rangle> = \\<langle>s,t\\<rangle>\"\n               by simp\n           qed\n         qed\n       next\n         assume \"y \\<noteq> y1\"\n         show \"\\<langle>x,y\\<rangle> = \\<langle>s,t\\<rangle>\"\n         proof(cases \"y = y2\")\n           assume \"y = y2\"\n           show \"\\<langle>x,y\\<rangle> = \\<langle>s,t\\<rangle>\"\n           proof(cases \"t = y2\",auto)\n             show \"t = y2 \\<Longrightarrow> \\<langle>x,y\\<rangle> = \\<langle>s,y2\\<rangle>\"\n               by (typecheck_cfuncs, metis \\<open>y = y2\\<close> \\<open>y \\<noteq> y1\\<close> equals f1 f2 st_def xy_def)\n           next\n             assume \"t \\<noteq> y2\"\n             show \"\\<langle>x,y\\<rangle> = \\<langle>s,t\\<rangle>\"\n             proof(cases \"x = s\", auto)\n               show \"x = s \\<Longrightarrow> \\<langle>s,y\\<rangle> = \\<langle>s,t\\<rangle>\"\n                 by (metis equals2 f1 s_type t_type y_type)\n             next\n               assume \"x \\<noteq> s\"\n               show \"\\<langle>x,y\\<rangle> = \\<langle>s,t\\<rangle>\"\n               proof(cases \"t = y1\",auto)\n                 show \"t = y1 \\<Longrightarrow> \\<langle>x,y\\<rangle> = \\<langle>s,y1\\<rangle>\"\n                   by (metis \\<open>\\<not> X \\<cong> \\<Omega>\\<close> \\<open>\\<not> initial_object X\\<close> \\<open>\\<not> terminal_object X\\<close> \\<open>y = y2\\<close> \\<open>y \\<noteq> y1\\<close> equals f2 f3 s_type sets_size_3_plus st_def x_type xy_def y2_type)\n               next\n                 assume \"t \\<noteq> y1\"\n                 show \"\\<langle>x,y\\<rangle> = \\<langle>s,t\\<rangle>\"\n                   by (typecheck_cfuncs, metis \\<open>t \\<noteq> y1\\<close> \\<open>y \\<noteq> y1\\<close> equals f1 f2 st_def xy_def)\n               qed\n             qed\n           qed\n         next\n           assume \"y \\<noteq> y2\"\n           show \"\\<langle>x,y\\<rangle> = \\<langle>s,t\\<rangle>\"\n           proof(cases \"s = x\", auto)\n             show \"s = x \\<Longrightarrow> \\<langle>x,y\\<rangle> = \\<langle>x,t\\<rangle>\"\n               by (metis equals2 f1 t_type x_type y_type)\n             show \"s \\<noteq> x \\<Longrightarrow> \\<langle>x,y\\<rangle> = \\<langle>s,t\\<rangle>\"\n               by (metis \\<open>y \\<noteq> y1\\<close> \\<open>y \\<noteq> y2\\<close> equals f1 f2 f3 s_type st_def t_type x_type xy_def y_type)\n           qed\n         qed\n       qed\n     then show \"xy = st\"\n       by (typecheck_cfuncs, simp add:  st_def xy_def)\n   qed\n      then show ?thesis\n        using \\<Theta>_type injective_imp_monomorphism is_smaller_than_def by blast\n    qed\n  qed  \n qed\nqed\n\n\n\n  \n\n\nlemma prod_finite_with_self_finite:\n  assumes \"is_finite(Y)\"\n  shows \"is_finite(Y \\<times>\\<^sub>c Y)\"\nproof(cases \"initial_object(Y)\")\n  assume \"initial_object Y\"\n  then have \"Y \\<times>\\<^sub>c Y \\<cong> Y\"\n    using function_to_empty_set_is_iso initial_iso_empty is_isomorphic_def left_cart_proj_type no_el_iff_iso_0 by blast\n  then show ?thesis\n    using assms iso_pres_finite isomorphic_is_symmetric by blast\nnext\n  assume \"\\<not> initial_object Y\"\n  show ?thesis\n  proof(cases \"terminal_object Y\")\n    assume \"terminal_object Y\"\n    then have \"Y \\<times>\\<^sub>c Y \\<cong> Y\"\n      by (simp add: prod_with_term_obj1)\n    then show ?thesis\n      using assms iso_pres_finite isomorphic_is_symmetric by blast\n  next\n    assume \"\\<not> terminal_object Y\"\n    oops\n\n\n\n\n\n\n\n\nlemma product_of_finite_is_finite:\n  assumes \"is_finite(X)\" \"is_finite(Y)\"\n  assumes \"nonempty(X)\" \"nonempty(Y)\"\n  shows \"is_finite(X \\<times>\\<^sub>c Y)\"\nproof(cases \"initial_object(X)\")\n  assume \"initial_object X\"\n  then have \"X \\<times>\\<^sub>c Y \\<cong> \\<emptyset>\"\n    using assms(3) initial_iso_empty no_el_iff_iso_0 by blast\n  then show ?thesis\n    using \\<open>initial_object X\\<close> assms(3) initial_iso_empty no_el_iff_iso_0 by blast\nnext\n  assume \"\\<not> initial_object X\"\n  show ?thesis\n  proof(cases \"terminal_object(X)\")\n    assume \"terminal_object(X)\" \n    then have \"X \\<times>\\<^sub>c Y \\<cong> Y\"\n      by (simp add: prod_with_term_obj1) \n    then show ?thesis\n      using assms(2) iso_pres_finite isomorphic_is_symmetric by blast\n  next\n    assume \"\\<not> terminal_object X\"\n    show ?thesis\n    proof(cases \"terminal_object(Y)\")\n      assume \"terminal_object Y\"\n      then have \"X \\<times>\\<^sub>c Y \\<cong> X\"\n        by (simp add: prod_with_term_obj2)\n      then show ?thesis\n        using assms(1) iso_pres_finite isomorphic_is_symmetric by blast\n    next\n      assume \"\\<not> terminal_object Y\"\n      then show \"is_finite (X \\<times>\\<^sub>c Y)\"\n        oops\n\n(*\n  fix xy\n  assume xy_type: \"xy:  X \\<times>\\<^sub>c Y \\<rightarrow> X \\<times>\\<^sub>c Y\"\n  assume xy_mono: \"monomorphism(xy)\"\n  obtain m where m_def: \"m :  X \\<rightarrow> X \\<times>\\<^sub>c Y \\<and> monomorphism(m)\"\n    using assms(4) is_smaller_than_def smaller_than_product1 by blast\n  obtain n where n_def: \"n :  Y \\<rightarrow> X \\<times>\\<^sub>c Y \\<and> monomorphism(n)\"\n    using assms(3) is_smaller_than_def smaller_than_product2 by blast\n  oops\n*)\n\n\n\n\nlemma coprod_finite_with_self_finite:\n  assumes \"is_finite(Y)\"\n  assumes \"is_finite(Y \\<times>\\<^sub>c Y)\"\n  shows \"is_finite(Y \\<Coprod> Y)\"\nproof(cases \"initial_object Y\")\n  assume \"initial_object Y\"\n  then show ?thesis\n    using  assms coprod_with_init_obj2 either_finite_or_infinite iso_pres_infinite not_finite_and_infinite by blast\nnext\n  assume \"\\<not> initial_object Y\"\n  show ?thesis\n  proof(cases \"terminal_object Y\")\n    assume \"terminal_object Y\"\n    then have \"Y \\<Coprod> Y \\<cong> \\<Omega>\"\n      by (meson coprod_pres_iso isomorphic_is_transitive oneUone_iso_\\<Omega> one_terminal_object terminal_objects_isomorphic)\n    then show ?thesis\n      using either_finite_or_infinite iso_pres_infinite not_finite_and_infinite truth_set_is_finite by blast\n  next\n    assume \"\\<not> terminal_object Y\"\n    then have \"(Y \\<Coprod> Y) \\<le>\\<^sub>c (Y \\<times>\\<^sub>c Y)\"\n      by (simp add: \\<open>\\<not> initial_object Y\\<close> coprod_leq_product)\n    then show ?thesis\n      using assms(2) smaller_than_finite_is_finite by blast\n  qed\nqed\n \n\n\nlemma coproduct_of_finite_is_finite:\n  assumes \"is_finite(X)\" \"is_finite(Y)\"\n  assumes \"is_finite(X \\<times>\\<^sub>c Y)\"\n  shows \"is_finite(X \\<Coprod> Y)\"\nproof(cases \"initial_object(X)\")\n  assume \"initial_object X\"\n  then have \"X \\<Coprod> Y \\<cong> Y\"\n    by (simp add: coprod_with_init_obj2)\n  then show ?thesis\n    using  assms(2) iso_pres_finite isomorphic_is_symmetric by blast\nnext\n  assume \"\\<not>(initial_object X)\"\n  show ?thesis\n  proof(cases \"initial_object(Y)\")\n    assume \"initial_object Y\"\n    then have \"X \\<Coprod> Y \\<cong> X\"\n      using coprod_with_init_obj1 by blast\n    then show ?thesis\n      using assms(1) iso_pres_finite isomorphic_is_symmetric by blast\n  next \n    assume \"\\<not>(initial_object Y)\"  \n    show ?thesis\n    proof(cases \"terminal_object(X)\")\n      assume \"terminal_object X\"\n      then obtain y where y_def:  \"y : X \\<rightarrow> Y \\<and> monomorphism(y)\"\n        by (meson \\<open>\\<not> initial_object Y\\<close> comp_type iso_empty_initial no_el_iff_iso_0 nonempty_def terminal_el__monomorphism terminal_func_type)\n      then have y_id_type: \"(y \\<bowtie>\\<^sub>f  id(Y)) : X \\<Coprod> Y \\<rightarrow> Y \\<Coprod> Y\"\n        by (simp add: cfunc_bowtie_prod_type id_type)\n      then have \"monomorphism(y \\<bowtie>\\<^sub>f  id(Y))\"\n        by (typecheck_cfuncs, metis cfunc_bowtieprod_inj id_isomorphism injective_imp_monomorphism iso_imp_epi_and_monic mem_Collect_eq monomorphism_imp_injective y_def)\n      have \"is_finite(Y \\<Coprod> Y)\"\n        by (simp add: assms(4))\n      have \"(X \\<Coprod> Y) \\<le>\\<^sub>c (Y \\<Coprod> Y)\"\n        using \\<open>monomorphism (y \\<bowtie>\\<^sub>f id\\<^sub>c Y)\\<close> is_smaller_than_def y_id_type by auto\n      then show ?thesis\n        using assms(4) smaller_than_finite_is_finite by blast\n    next\n      assume \"\\<not>(terminal_object X)\"\n      show ?thesis \n      proof(cases \"terminal_object(Y)\")\n        assume \"terminal_object(Y)\"\n        then obtain x where x_def:  \"x : Y \\<rightarrow> X \\<and> monomorphism(x)\"\n          by (meson \\<open>\\<not> initial_object X\\<close> comp_type is_isomorphic_def iso_empty_initial no_el_iff_iso_0 nonempty_def one_terminal_object terminal_el__monomorphism terminal_objects_isomorphic)\n      then have y_id_type: \"(id(X) \\<bowtie>\\<^sub>f  x) : X \\<Coprod> Y \\<rightarrow> X \\<Coprod> X\"\n        by (simp add: cfunc_bowtie_prod_type id_type)\n      then have \"monomorphism(id(X) \\<bowtie>\\<^sub>f  x)\"\n        by (typecheck_cfuncs, metis cfunc_bowtieprod_inj id_isomorphism injective_imp_monomorphism iso_imp_epi_and_monic mem_Collect_eq monomorphism_imp_injective x_def)\n      have \"is_finite(X \\<Coprod> X)\"\n        by (simp add: assms(3))\n      have \"(X \\<Coprod> Y) \\<le>\\<^sub>c (X \\<Coprod> X)\"\n        using \\<open>monomorphism (id\\<^sub>c X \\<bowtie>\\<^sub>f x)\\<close> is_smaller_than_def y_id_type by auto\n      then show ?thesis\n        using assms(3) smaller_than_finite_is_finite by blast\n    next \n      assume \"\\<not> terminal_object Y\"\n      then have \"(X \\<Coprod> Y) \\<le>\\<^sub>c (X \\<times>\\<^sub>c Y)\"\n        by (simp add: \\<open>\\<not> initial_object X\\<close> \\<open>\\<not> initial_object Y\\<close> \\<open>\\<not> terminal_object X\\<close> coprod_leq_product)\n      then show \"is_finite(X \\<Coprod> Y)\"\n        using assms(5) smaller_than_finite_is_finite by blast\n      qed\n    qed\n  qed\nqed\n\n\n(*\ndefinition triangle_number :: \"cfunc\" where\n  \"triangle_number = (THE u. u: \\<nat>\\<^sub>c \\<rightarrow>  \\<nat>\\<^sub>c \\<and> \n     u \\<circ>\\<^sub>c zero = zero \\<and>\n     ( u \\<circ>\\<^sub>c successor \\<circ>\\<^sub>c n = (u \\<circ>\\<^sub>c n) +\\<^sub>\\<nat> n))\"\n\n\n\n\n\nlemma triangle_numbers_exist:\n  \"\\<exists> f. f : \\<nat>\\<^sub>c \\<rightarrow> \\<nat>\\<^sub>c \\<and> f \\<circ>\\<^sub>c zero = zero \\<and> f \\<circ>\\<^sub>c successor \\<circ>\\<^sub>c n = (f \\<circ>\\<^sub>c n) +\\<^sub>\\<nat> n\"\nproof- \n  obtain f where f_def: \"n \\<in>\\<^sub>c \\<nat>\\<^sub>c  \\<Longrightarrow> f : \\<nat>\\<^sub>c \\<rightarrow> \\<nat>\\<^sub>c \\<and> f \\<circ>\\<^sub>c zero = zero \\<and> f \\<circ>\\<^sub>c successor \\<circ>\\<^sub>c n = (f \\<circ>\\<^sub>c n) +\\<^sub>\\<nat> n\"\n    by (typecheck_cfuncs, metis halve_mono halve_nth_even halve_nth_odd halve_type monomorphism_def2 nth_even_def2 nth_odd_def2 zero_is_not_successor)\n  then show ?thesis\n    by (metis halve_mono halve_nth_even halve_nth_odd halve_type monomorphism_def3 nth_even_def2 nth_odd_def2 zero_is_not_successor zero_type)\nqed\n\n*)\n\n\n(*\n(*Proposition 2.6.10*)\nlemma NxN_is_countable:\n  \"countable(\\<nat>\\<^sub>c \\<times>\\<^sub>c \\<nat>\\<^sub>c)\"\n*)\n\n\n(*\n  obtain f where f_def:\n    \"f = ((\\<langle>id \\<nat>\\<^sub>c, zero \\<circ>\\<^sub>c \\<beta>\\<^bsub>\\<nat>\\<^sub>c\\<^esub>\\<rangle> \\<circ>\\<^sub>c right_cart_proj one \\<nat>\\<^sub>c) \\<amalg> id (\\<nat>\\<^sub>c \\<times>\\<^sub>c \\<nat>\\<^sub>c))\n          \\<circ>\\<^sub>c dist_prod_coprod_inv2 one \\<nat>\\<^sub>c \\<nat>\\<^sub>c \\<circ>\\<^sub>c (predecessor \\<times>\\<^sub>f successor)\"\n    by auto\n\n  have f_type[type_rule]: \"f : \\<nat>\\<^sub>c \\<times>\\<^sub>c \\<nat>\\<^sub>c \\<rightarrow> \\<nat>\\<^sub>c \\<times>\\<^sub>c \\<nat>\\<^sub>c\"\n    unfolding f_def by typecheck_cfuncs\n\n  obtain seq where seq_type[type_rule]: \"seq : \\<nat>\\<^sub>c \\<rightarrow> \\<nat>\\<^sub>c \\<times>\\<^sub>c \\<nat>\\<^sub>c\" and\n    seq_triangle: \"seq \\<circ>\\<^sub>c zero = \\<langle>zero, zero\\<rangle>\" and\n    seq_square: \"seq \\<circ>\\<^sub>c successor = f \\<circ>\\<^sub>c seq\"\n    using natural_number_object_property[where q = \"\\<langle>zero, zero\\<rangle>\", where f=f, where X=\"\\<nat>\\<^sub>c \\<times>\\<^sub>c \\<nat>\\<^sub>c\"]\n    unfolding triangle_commutes_def square_commutes_def by (auto, typecheck_cfuncs, metis)\n\n  (* seq((n+m)(n+m+1)/2 + n) = (m, n)? *)\n  (* seq(0) = (0,0) = seq(0*1/2 + 0) *)\n  (* seq(1) = (1,0) = seq(1*2/2 + 0) *)\n  (* seq(2) = (0,1) = seq(1*2/2 + 1) *)\n  (* seq(3) = (2,0) = seq(2*3/2 + 0) *)\n  (* seq(4) = (1,1) = seq(2*3/2 + 1) *)\n  (* seq(5) = (0,2) = seq(2*3/2 + 2) *)\n  (* seq(6) = (3,0) = seq(3*4/2 + 0) *)\n\n  have \"\\<And> m n k. m \\<in>\\<^sub>c \\<nat>\\<^sub>c \\<Longrightarrow> n \\<in>\\<^sub>c \\<nat>\\<^sub>c \\<Longrightarrow> k \\<in>\\<^sub>c \\<nat>\\<^sub>c \\<Longrightarrow>\n    seq \\<circ>\\<^sub>c k = \\<langle>m, n\\<rangle> \\<longleftrightarrow> seq \\<circ>\\<^sub>c add2 \\<circ>\\<^sub>c \\<langle>k, m\\<rangle> = \\<langle>zero, add2 \\<circ>\\<^sub>c \\<langle>m, n\\<rangle>\\<rangle>\"\n    \n\n    have \"\\<And> n. n \\<in>\\<^sub>c \\<nat>\\<^sub>c \\<Longrightarrow> seq \\<circ>\\<^sub>c halve \\<circ>\\<^sub>c (n \\<cdot>\\<^sub>\\<nat> (successor \\<circ>\\<^sub>c n)) = \\<langle>n, zero\\<rangle>\"\n  proof -\n    fix n\n    assume n_type[type_rule]: \"n \\<in>\\<^sub>c \\<nat>\\<^sub>c\"\n\n    have \"seq \\<circ>\\<^sub>c halve \\<circ>\\<^sub>c mult2 \\<circ>\\<^sub>c \\<langle>id \\<nat>\\<^sub>c, successor\\<rangle> = \\<langle>id \\<nat>\\<^sub>c, zero \\<circ>\\<^sub>c \\<beta>\\<^bsub>\\<nat>\\<^sub>c\\<^esub>\\<rangle>\"\n    proof (rule natural_number_object_func_unique[where X=\"\\<nat>\\<^sub>c \\<times>\\<^sub>c \\<nat>\\<^sub>c\", where f=\"successor \\<times>\\<^sub>f id \\<nat>\\<^sub>c\"])\n      show \"seq \\<circ>\\<^sub>c halve \\<circ>\\<^sub>c mult2 \\<circ>\\<^sub>c \\<langle>id\\<^sub>c \\<nat>\\<^sub>c,successor\\<rangle> : \\<nat>\\<^sub>c \\<rightarrow> \\<nat>\\<^sub>c \\<times>\\<^sub>c \\<nat>\\<^sub>c\"\n        by typecheck_cfuncs\n      show \"\\<langle>id\\<^sub>c \\<nat>\\<^sub>c,zero \\<circ>\\<^sub>c \\<beta>\\<^bsub>\\<nat>\\<^sub>c\\<^esub>\\<rangle> : \\<nat>\\<^sub>c \\<rightarrow> \\<nat>\\<^sub>c \\<times>\\<^sub>c \\<nat>\\<^sub>c\"\n        by typecheck_cfuncs\n      show \"successor \\<times>\\<^sub>f id \\<nat>\\<^sub>c : \\<nat>\\<^sub>c \\<times>\\<^sub>c \\<nat>\\<^sub>c \\<rightarrow> \\<nat>\\<^sub>c \\<times>\\<^sub>c \\<nat>\\<^sub>c\"\n        by typecheck_cfuncs\n\n      show \"(seq \\<circ>\\<^sub>c halve \\<circ>\\<^sub>c mult2 \\<circ>\\<^sub>c \\<langle>id\\<^sub>c \\<nat>\\<^sub>c,successor\\<rangle>) \\<circ>\\<^sub>c zero = \\<langle>id\\<^sub>c \\<nat>\\<^sub>c,zero \\<circ>\\<^sub>c \\<beta>\\<^bsub>\\<nat>\\<^sub>c\\<^esub>\\<rangle> \\<circ>\\<^sub>c zero\"\n      proof -\n        have \"(seq \\<circ>\\<^sub>c halve \\<circ>\\<^sub>c mult2 \\<circ>\\<^sub>c \\<langle>id\\<^sub>c \\<nat>\\<^sub>c,successor\\<rangle>) \\<circ>\\<^sub>c zero = seq \\<circ>\\<^sub>c halve \\<circ>\\<^sub>c mult2 \\<circ>\\<^sub>c \\<langle>zero, successor \\<circ>\\<^sub>c zero\\<rangle>\"\n          by (typecheck_cfuncs, smt cfunc_prod_comp comp_associative2 id_left_unit2)\n        also have \"... = seq \\<circ>\\<^sub>c halve \\<circ>\\<^sub>c zero\"\n          using mult_def s0_is_right_id zero_type by auto\n        also have \"... = seq \\<circ>\\<^sub>c zero\"\n          by (smt comp_associative2 halve_nth_even halve_type id_left_unit2 nth_even_def2 zero_type)\n        also have \"... = \\<langle>zero, zero\\<rangle>\"\n          by (simp add: seq_triangle)\n        also have \"... = \\<langle>id\\<^sub>c \\<nat>\\<^sub>c,zero \\<circ>\\<^sub>c \\<beta>\\<^bsub>\\<nat>\\<^sub>c\\<^esub>\\<rangle> \\<circ>\\<^sub>c zero\"\n          by (typecheck_cfuncs, simp add: cart_prod_extract_left)\n        then show ?thesis\n          using calculation by auto\n      qed\n\n      show \"(seq \\<circ>\\<^sub>c halve \\<circ>\\<^sub>c mult2 \\<circ>\\<^sub>c \\<langle>id\\<^sub>c \\<nat>\\<^sub>c,successor\\<rangle>) \\<circ>\\<^sub>c successor\n        = (successor \\<times>\\<^sub>f id\\<^sub>c \\<nat>\\<^sub>c) \\<circ>\\<^sub>c seq \\<circ>\\<^sub>c halve \\<circ>\\<^sub>c mult2 \\<circ>\\<^sub>c \\<langle>id\\<^sub>c \\<nat>\\<^sub>c,successor\\<rangle>\"\n      proof -\n        have \"(seq \\<circ>\\<^sub>c halve \\<circ>\\<^sub>c mult2 \\<circ>\\<^sub>c \\<langle>id\\<^sub>c \\<nat>\\<^sub>c,successor\\<rangle>) \\<circ>\\<^sub>c successor = seq \\<circ>\\<^sub>c halve \\<circ>\\<^sub>c mult2 \\<circ>\\<^sub>c \\<langle>successor, successor \\<circ>\\<^sub>c successor\\<rangle>\"\n          by (typecheck_cfuncs, smt cfunc_prod_comp comp_associative2 id_left_unit2)\n        also have \"... = undefined\"\n\n(*  have \"\\<And> m. seq \\<circ>\\<^sub>c (k +\\<^sub>\\<nat> m) = \\<langle>zero, m\\<rangle>\"\n\n  have \"\\<And> k m. k \\<in>\\<^sub>c \\<nat>\\<^sub>c \\<Longrightarrow> seq \\<circ>\\<^sub>c k = \\<langle>m, zero\\<rangle> \\<Longrightarrow> seq \\<circ>\\<^sub>c (k +\\<^sub>\\<nat> m) = \\<langle>zero, m\\<rangle>\"\n  proof -\n    fix k m\n    assume k_type[type_rule]: \"k \\<in>\\<^sub>c \\<nat>\\<^sub>c\"\n    assume seq_k_eq: \"seq \\<circ>\\<^sub>c k = \\<langle>m, zero\\<rangle>\"\n\n    have \"eq_pred (\\<nat>\\<^sub>c \\<times>\\<^sub>c \\<nat>\\<^sub>c) \\<circ>\\<^sub>c \\<langle>seq \\<circ>\\<^sub>c k \\<circ>\\<^sub>c \\<beta>\\<^bsub>\\<nat>\\<^sub>c\\<^esub>, \\<langle>id \\<nat>\\<^sub>c, zero \\<circ>\\<^sub>c \\<beta>\\<^bsub>\\<nat>\\<^sub>c\\<^esub>\\<rangle>\\<rangle> =\n      eq_pred (\\<nat>\\<^sub>c \\<times>\\<^sub>c \\<nat>\\<^sub>c) \\<circ>\\<^sub>c \\<langle>seq\\<circ>\\<^sub>c add2 \\<circ>\\<^sub>c \\<langle>k \\<circ>\\<^sub>c \\<beta>\\<^bsub>\\<nat>\\<^sub>c\\<^esub>, id \\<nat>\\<^sub>c\\<rangle>, \\<langle>zero \\<circ>\\<^sub>c \\<beta>\\<^bsub>\\<nat>\\<^sub>c\\<^esub>, id \\<nat>\\<^sub>c\\<rangle>\\<rangle>\"\n    proof (rule natural_number_object_func_unique[where X=\"\\<Omega>\", where f=\"id \\<Omega>\"])\n*)\n  oops\n\n*)\n\n\n\n(*Once we have this  result above we can generalize it to any countable sets*)\nlemma product_of_countables_is_countable:\n  assumes \"countable X\" \"countable Y\"\n  assumes NxN_is_countable: \"countable(\\<nat>\\<^sub>c \\<times>\\<^sub>c \\<nat>\\<^sub>c)\" (*DELETE later*)\n  shows \"countable(X \\<times>\\<^sub>c Y)\"\nproof - \n  have \"\\<exists>f. f: X \\<rightarrow> \\<nat>\\<^sub>c \\<and> monomorphism(f)\"\n    using assms(1) countable_def by blast\n  then obtain f where f_def: \"f: X \\<rightarrow> \\<nat>\\<^sub>c \\<and> monomorphism(f)\"\n    by blast\n  have \"\\<exists>g. g: Y \\<rightarrow> \\<nat>\\<^sub>c \\<and> monomorphism(g)\"\n    using assms(2) countable_def by blast\n  then obtain g where g_def: \"g: Y \\<rightarrow> \\<nat>\\<^sub>c \\<and> monomorphism(g)\"\n    by blast\n  then have fg_type: \"(f \\<times>\\<^sub>f g) : (X \\<times>\\<^sub>c Y) \\<rightarrow> (\\<nat>\\<^sub>c \\<times>\\<^sub>c \\<nat>\\<^sub>c)\"\n    by (simp add: cfunc_cross_prod_type f_def)\n  have fg_mono: \"monomorphism(f \\<times>\\<^sub>f g)\"\n    using cfunc_cross_prod_mono f_def g_def by blast\n  obtain \\<phi> where \\<phi>_def: \"(\\<phi> : (\\<nat>\\<^sub>c \\<times>\\<^sub>c \\<nat>\\<^sub>c) \\<rightarrow> \\<nat>\\<^sub>c) \\<and> monomorphism(\\<phi>)\"\n    using NxN_is_countable countable_def by blast\n  have \"(\\<phi> \\<circ>\\<^sub>c (f \\<times>\\<^sub>f g) : (X \\<times>\\<^sub>c Y) \\<rightarrow> \\<nat>\\<^sub>c) \\<and> monomorphism(\\<phi> \\<circ>\\<^sub>c (f \\<times>\\<^sub>f g))\"\n    using \\<phi>_def cfunc_type_def comp_type composition_of_monic_pair_is_monic fg_mono fg_type by auto\n  then show \"countable(X \\<times>\\<^sub>c Y)\"\n    using countable_def by blast\nqed\n\n      \n\n\nlemma NuN_is_countable:\n  \"countable(\\<nat>\\<^sub>c \\<Coprod> \\<nat>\\<^sub>c)\"\n  using countable_def epis_give_monos halve_with_parity_iso halve_with_parity_type iso_imp_epi_and_monic by smt\n\n\n(*Exercise 2.6.11*)\nlemma coproduct_of_countables_is_countable:\n  assumes \"countable X\" \"countable Y\"\n  shows \"countable(X \\<Coprod> Y)\"\n  unfolding countable_def\nproof-\n  obtain x where x_def:  \"x : X  \\<rightarrow> \\<nat>\\<^sub>c \\<and> monomorphism x\"\n    using assms(1) countable_def by blast\n  obtain y where y_def:  \"y : Y  \\<rightarrow> \\<nat>\\<^sub>c \\<and> monomorphism y\"\n    using assms(2) countable_def by blast\n  obtain n where n_def: \" n : \\<nat>\\<^sub>c \\<Coprod> \\<nat>\\<^sub>c \\<rightarrow> \\<nat>\\<^sub>c \\<and> monomorphism n\"\n    using NuN_is_countable countable_def by blast\n  have xy_type: \"x \\<bowtie>\\<^sub>f y : X \\<Coprod> Y \\<rightarrow> \\<nat>\\<^sub>c \\<Coprod> \\<nat>\\<^sub>c\"\n    using x_def y_def by (typecheck_cfuncs, auto)\n  then have nxy_type: \"n \\<circ>\\<^sub>c (x \\<bowtie>\\<^sub>f y) : X \\<Coprod> Y \\<rightarrow> \\<nat>\\<^sub>c\"\n    using comp_type n_def by blast\n  have \"injective(x \\<bowtie>\\<^sub>f y)\"\n    using cfunc_bowtieprod_inj monomorphism_imp_injective x_def y_def by blast\n  then have \"monomorphism(x \\<bowtie>\\<^sub>f y)\"\n    using injective_imp_monomorphism by auto\n  then have \"monomorphism(n \\<circ>\\<^sub>c (x \\<bowtie>\\<^sub>f y))\"\n    using cfunc_type_def composition_of_monic_pair_is_monic n_def xy_type by auto\n  then show \"\\<exists>f. f : X \\<Coprod> Y \\<rightarrow> \\<nat>\\<^sub>c \\<and> monomorphism f\"\n    using nxy_type by blast\nqed\n   \n  \n\nlemma\n  assumes i_zero: \"i 0 = x\" and i_suc: \"\\<And> n. i (Suc n) = (m \\<circ> i) n\" \n  assumes m_mono: \"\\<And> p q. m p = m q \\<Longrightarrow> p = q\"\n  assumes x_def: \"\\<And> y. m y \\<noteq> x\"\n  shows \"\\<And>q. i p = i q \\<Longrightarrow> p = q\"\nproof (induct p)\n  fix q\n  show \"i 0 = i q \\<Longrightarrow> 0 = q\"\n  proof (induct q)\n    show \"0 = 0\"\n      by simp\n  next\n    fix q\n    assume \"i 0 = i (Suc q)\"\n    then have \"x = (m \\<circ> i) q\"\n      using i_suc i_zero by auto\n    then have False\n      using x_def by auto\n    then show \"0 = Suc q\"\n      by simp\n  qed\nnext\n  fix p q\n  assume ind_hyp: \"\\<And>q. i p = i q \\<Longrightarrow> p = q\"\n\n  show \"i (Suc p) = i q \\<Longrightarrow> Suc p = q\"\n  proof (induct q)\n    assume \"i (Suc p) = i 0\"\n    then have \"x = (m \\<circ> i) p\"\n      using i_suc i_zero by auto\n    then have False\n      using x_def by auto\n    then show \"Suc p = 0\"\n      by simp\n  next\n    fix q\n    assume \"i (Suc p) = i (Suc q)\"\n    then have \"(m \\<circ> i) p = (m \\<circ> i) q\"\n      by (simp add: i_suc)\n    then have \"i p = i q\"\n      by (metis comp_apply m_mono)\n    then have \"p = q\"\n      by (meson ind_hyp)\n    then show \"Suc p = Suc q\"\n      by simp\n  qed\nqed\n\n\nlemma finite_iff_nosurj_to_N:\n  shows \"(is_finite(X)) = (\\<not>(\\<exists>s. (s : X \\<rightarrow> \\<nat>\\<^sub>c) \\<and> surjective(s)))\"\nproof(safe)\n  fix s \n  assume X_fin: \"is_finite X\"\n  assume s_type: \"s : X \\<rightarrow> \\<nat>\\<^sub>c\"\n  assume s_surj: \"surjective s\"\n  have \"\\<exists>g. (g: \\<nat>\\<^sub>c \\<rightarrow> X \\<and> monomorphism(g) )\"\n    using epis_give_monos s_surj s_type surjective_is_epimorphism by blast\n  then have \"is_finite \\<nat>\\<^sub>c\"\n    using X_fin is_smaller_than_def smaller_than_finite_is_finite by blast\n  then show False\n    using natural_numbers_are_countably_infinite not_finite_and_infinite by blast\nnext \n  assume \"\\<nexists>s. s : X \\<rightarrow> \\<nat>\\<^sub>c \\<and> surjective s\"\n  show \"is_finite X\"\n  proof(rule ccontr)\n    assume \"\\<not> is_finite X\"\n    then have \"is_infinite X\"\n      using either_finite_or_infinite by blast\n    then obtain m where m_type[type_rule]: \"m : X \\<rightarrow> X\" and  m_mono: \"monomorphism(m)\" and \n     m_not_surj:  \"\\<not>surjective(m)\"\n      using is_infinite_def by blast\n    obtain x where x_type[type_rule]: \"x \\<in>\\<^sub>c X\" and \n      x_def: \"\\<And> y.  y \\<in>\\<^sub>c X \\<Longrightarrow>  m \\<circ>\\<^sub>c y \\<noteq> x\"\n      using m_not_surj m_type surjective_def2 by auto\n\n    obtain i where \n      i_type[type_rule]: \"i : \\<nat>\\<^sub>c \\<rightarrow> X\" and ibase: \"i \\<circ>\\<^sub>c zero = x\" and i_induct: \"m \\<circ>\\<^sub>c i = i \\<circ>\\<^sub>c successor\"\n      using m_type natural_number_object_property2 x_type by blast\n    have \"injective(i)\"\n      unfolding injective_def\n    proof(auto)\n      fix p q\n      assume \"p \\<in>\\<^sub>c domain i\"\n      then have [type_rule]: \"p \\<in>\\<^sub>c \\<nat>\\<^sub>c\"\n        using cfunc_type_def i_type by auto\n      assume \"q \\<in>\\<^sub>c domain i\"\n      then have [type_rule]: \"q \\<in>\\<^sub>c \\<nat>\\<^sub>c\"\n        using cfunc_type_def i_type by auto\n      assume eqs: \"i \\<circ>\\<^sub>c p = i \\<circ>\\<^sub>c q\"  \n  \n      have main_result: \"FORALL \\<nat>\\<^sub>c \\<circ>\\<^sub>c (IMPLIES \\<circ>\\<^sub>c \\<langle> eq_pred X \\<circ>\\<^sub>c (i \\<times>\\<^sub>f i), eq_pred \\<nat>\\<^sub>c \\<circ>\\<^sub>c (id \\<nat>\\<^sub>c \\<times>\\<^sub>f id \\<nat>\\<^sub>c)\\<rangle>)\\<^sup>\\<sharp> = \\<t> \\<circ>\\<^sub>c \\<beta>\\<^bsub>\\<nat>\\<^sub>c\\<^esub>\"\n      proof (rule natural_number_object_func_unique[where X=\"\\<Omega>\", where f=\"id \\<Omega>\"])\n  \n        show \"FORALL \\<nat>\\<^sub>c \\<circ>\\<^sub>c (IMPLIES \\<circ>\\<^sub>c \\<langle>eq_pred X \\<circ>\\<^sub>c i \\<times>\\<^sub>f i,eq_pred \\<nat>\\<^sub>c \\<circ>\\<^sub>c id\\<^sub>c \\<nat>\\<^sub>c \\<times>\\<^sub>f id\\<^sub>c \\<nat>\\<^sub>c\\<rangle>)\\<^sup>\\<sharp> : \\<nat>\\<^sub>c \\<rightarrow> \\<Omega>\"\n          by typecheck_cfuncs\n        show \"\\<t> \\<circ>\\<^sub>c \\<beta>\\<^bsub>\\<nat>\\<^sub>c\\<^esub> : \\<nat>\\<^sub>c \\<rightarrow> \\<Omega>\"\n          by typecheck_cfuncs\n        show \"id\\<^sub>c \\<Omega> : \\<Omega> \\<rightarrow> \\<Omega>\"\n          by typecheck_cfuncs\n        show  zero_case: \"(FORALL \\<nat>\\<^sub>c \\<circ>\\<^sub>c (IMPLIES \\<circ>\\<^sub>c \\<langle>eq_pred X \\<circ>\\<^sub>c i \\<times>\\<^sub>f i,eq_pred \\<nat>\\<^sub>c \\<circ>\\<^sub>c id\\<^sub>c \\<nat>\\<^sub>c \\<times>\\<^sub>f id\\<^sub>c \\<nat>\\<^sub>c\\<rangle>)\\<^sup>\\<sharp>) \\<circ>\\<^sub>c zero = (\\<t> \\<circ>\\<^sub>c \\<beta>\\<^bsub>\\<nat>\\<^sub>c\\<^esub>) \\<circ>\\<^sub>c zero\"\n        proof - \n          have \"(IMPLIES \\<circ>\\<^sub>c \\<langle>eq_pred X \\<circ>\\<^sub>c i \\<times>\\<^sub>f i, eq_pred \\<nat>\\<^sub>c \\<circ>\\<^sub>c id\\<^sub>c \\<nat>\\<^sub>c \\<times>\\<^sub>f id\\<^sub>c \\<nat>\\<^sub>c\\<rangle>)\\<^sup>\\<sharp> \\<circ>\\<^sub>c zero =  (\\<t> \\<circ>\\<^sub>c \\<beta>\\<^bsub>\\<nat>\\<^sub>c\\<times>\\<^sub>c one\\<^esub>)\\<^sup>\\<sharp>\"\n          proof (rule same_evals_equal[where Z=one, where X=\\<Omega>, where A=\"\\<nat>\\<^sub>c\"])\n            show \"(IMPLIES \\<circ>\\<^sub>c \\<langle>eq_pred X \\<circ>\\<^sub>c i \\<times>\\<^sub>f i,eq_pred \\<nat>\\<^sub>c \\<circ>\\<^sub>c id\\<^sub>c \\<nat>\\<^sub>c \\<times>\\<^sub>f id\\<^sub>c \\<nat>\\<^sub>c\\<rangle>)\\<^sup>\\<sharp> \\<circ>\\<^sub>c zero \\<in>\\<^sub>c \\<Omega>\\<^bsup>\\<nat>\\<^sub>c\\<^esup>\"\n              by typecheck_cfuncs\n            show \"(\\<t> \\<circ>\\<^sub>c \\<beta>\\<^bsub>\\<nat>\\<^sub>c \\<times>\\<^sub>c one\\<^esub>)\\<^sup>\\<sharp> \\<in>\\<^sub>c \\<Omega>\\<^bsup>\\<nat>\\<^sub>c\\<^esup>\"\n              by typecheck_cfuncs \n            show \"eval_func \\<Omega> \\<nat>\\<^sub>c \\<circ>\\<^sub>c id\\<^sub>c \\<nat>\\<^sub>c \\<times>\\<^sub>f (IMPLIES \\<circ>\\<^sub>c \\<langle>eq_pred X \\<circ>\\<^sub>c i \\<times>\\<^sub>f i,eq_pred \\<nat>\\<^sub>c \\<circ>\\<^sub>c id\\<^sub>c \\<nat>\\<^sub>c \\<times>\\<^sub>f id\\<^sub>c \\<nat>\\<^sub>c\\<rangle>)\\<^sup>\\<sharp> \\<circ>\\<^sub>c zero =\n      eval_func \\<Omega> \\<nat>\\<^sub>c \\<circ>\\<^sub>c id\\<^sub>c \\<nat>\\<^sub>c \\<times>\\<^sub>f (\\<t> \\<circ>\\<^sub>c \\<beta>\\<^bsub>\\<nat>\\<^sub>c \\<times>\\<^sub>c one\\<^esub>)\\<^sup>\\<sharp>\"\n            proof - \n              have \"eval_func \\<Omega> \\<nat>\\<^sub>c \\<circ>\\<^sub>c id\\<^sub>c \\<nat>\\<^sub>c \\<times>\\<^sub>f (IMPLIES \\<circ>\\<^sub>c \\<langle>eq_pred X \\<circ>\\<^sub>c i \\<times>\\<^sub>f i, eq_pred \\<nat>\\<^sub>c \\<circ>\\<^sub>c id\\<^sub>c \\<nat>\\<^sub>c \\<times>\\<^sub>f id\\<^sub>c \\<nat>\\<^sub>c\\<rangle>)\\<^sup>\\<sharp> \\<circ>\\<^sub>c zero = \n                    eval_func \\<Omega> \\<nat>\\<^sub>c \\<circ>\\<^sub>c (id\\<^sub>c \\<nat>\\<^sub>c \\<times>\\<^sub>f (IMPLIES \\<circ>\\<^sub>c \\<langle>eq_pred X \\<circ>\\<^sub>c i \\<times>\\<^sub>f i, eq_pred \\<nat>\\<^sub>c \\<circ>\\<^sub>c id\\<^sub>c \\<nat>\\<^sub>c \\<times>\\<^sub>f id\\<^sub>c \\<nat>\\<^sub>c\\<rangle>)\\<^sup>\\<sharp>) \\<circ>\\<^sub>c (id\\<^sub>c \\<nat>\\<^sub>c \\<times>\\<^sub>f zero)\"\n                by (typecheck_cfuncs, metis identity_distributes_across_composition)\n              also have \"... = IMPLIES \\<circ>\\<^sub>c \\<langle>eq_pred X \\<circ>\\<^sub>c i \\<times>\\<^sub>f i, eq_pred \\<nat>\\<^sub>c \\<circ>\\<^sub>c id\\<^sub>c \\<nat>\\<^sub>c \\<times>\\<^sub>f id\\<^sub>c \\<nat>\\<^sub>c\\<rangle> \\<circ>\\<^sub>c (id\\<^sub>c \\<nat>\\<^sub>c \\<times>\\<^sub>f zero)\"\n                by (typecheck_cfuncs, simp add: cfunc_type_def comp_associative transpose_func_def)\n              also have \"... = eval_func \\<Omega> \\<nat>\\<^sub>c \\<circ>\\<^sub>c id\\<^sub>c \\<nat>\\<^sub>c \\<times>\\<^sub>f (\\<t> \\<circ>\\<^sub>c \\<beta>\\<^bsub>\\<nat>\\<^sub>c \\<times>\\<^sub>c one\\<^esub>)\\<^sup>\\<sharp>\"\n              proof(rule one_separator[where X = \"\\<nat>\\<^sub>c \\<times>\\<^sub>c one\", where Y=\\<Omega>])\n                show \"IMPLIES \\<circ>\\<^sub>c \\<langle>eq_pred X \\<circ>\\<^sub>c i \\<times>\\<^sub>f i, eq_pred \\<nat>\\<^sub>c \\<circ>\\<^sub>c id\\<^sub>c \\<nat>\\<^sub>c \\<times>\\<^sub>f id\\<^sub>c \\<nat>\\<^sub>c\\<rangle> \\<circ>\\<^sub>c id\\<^sub>c \\<nat>\\<^sub>c \\<times>\\<^sub>f zero : \\<nat>\\<^sub>c \\<times>\\<^sub>c one \\<rightarrow> \\<Omega>\"\n                  by typecheck_cfuncs\n                show \" eval_func \\<Omega> \\<nat>\\<^sub>c \\<circ>\\<^sub>c id\\<^sub>c \\<nat>\\<^sub>c \\<times>\\<^sub>f (\\<t> \\<circ>\\<^sub>c \\<beta>\\<^bsub>\\<nat>\\<^sub>c \\<times>\\<^sub>c one\\<^esub>)\\<^sup>\\<sharp> : \\<nat>\\<^sub>c \\<times>\\<^sub>c one \\<rightarrow> \\<Omega>\"\n                  by typecheck_cfuncs\n                show \"\\<And>pone. pone \\<in>\\<^sub>c \\<nat>\\<^sub>c \\<times>\\<^sub>c one \\<Longrightarrow>\n           (IMPLIES \\<circ>\\<^sub>c \\<langle>eq_pred X \\<circ>\\<^sub>c i \\<times>\\<^sub>f i, eq_pred \\<nat>\\<^sub>c \\<circ>\\<^sub>c id\\<^sub>c \\<nat>\\<^sub>c \\<times>\\<^sub>f id\\<^sub>c \\<nat>\\<^sub>c\\<rangle> \\<circ>\\<^sub>c id\\<^sub>c \\<nat>\\<^sub>c \\<times>\\<^sub>f zero) \\<circ>\\<^sub>c pone =\n           (eval_func \\<Omega> \\<nat>\\<^sub>c \\<circ>\\<^sub>c id\\<^sub>c \\<nat>\\<^sub>c \\<times>\\<^sub>f (\\<t> \\<circ>\\<^sub>c \\<beta>\\<^bsub>\\<nat>\\<^sub>c \\<times>\\<^sub>c one\\<^esub>)\\<^sup>\\<sharp>) \\<circ>\\<^sub>c pone\"\n                proof - \n                  fix pone\n                  assume pone_type: \"pone \\<in>\\<^sub>c \\<nat>\\<^sub>c \\<times>\\<^sub>c one\"\n                  then obtain p where p_def: \"pone = \\<langle>p, id one\\<rangle>\" and p_type[type_rule]: \"p \\<in>\\<^sub>c \\<nat>\\<^sub>c\"\n                    by (metis cart_prod_decomp id_type one_unique_element)\n  \n                  have RHS: \"(eval_func \\<Omega> \\<nat>\\<^sub>c \\<circ>\\<^sub>c id\\<^sub>c \\<nat>\\<^sub>c \\<times>\\<^sub>f (\\<t> \\<circ>\\<^sub>c \\<beta>\\<^bsub>\\<nat>\\<^sub>c \\<times>\\<^sub>c one\\<^esub>)\\<^sup>\\<sharp>) \\<circ>\\<^sub>c pone = \\<t>\"\n                  proof - \n                    have \"(eval_func \\<Omega> \\<nat>\\<^sub>c \\<circ>\\<^sub>c id\\<^sub>c \\<nat>\\<^sub>c \\<times>\\<^sub>f (\\<t> \\<circ>\\<^sub>c \\<beta>\\<^bsub>\\<nat>\\<^sub>c \\<times>\\<^sub>c one\\<^esub>)\\<^sup>\\<sharp>) \\<circ>\\<^sub>c pone = \n                           eval_func \\<Omega> \\<nat>\\<^sub>c \\<circ>\\<^sub>c (id\\<^sub>c \\<nat>\\<^sub>c \\<times>\\<^sub>f (\\<t> \\<circ>\\<^sub>c \\<beta>\\<^bsub>\\<nat>\\<^sub>c \\<times>\\<^sub>c one\\<^esub>)\\<^sup>\\<sharp>) \\<circ>\\<^sub>c \\<langle>p, id one\\<rangle>\"\n                      by (typecheck_cfuncs, simp add: comp_associative2 p_def)\n                    also have \"... = (\\<t> \\<circ>\\<^sub>c \\<beta>\\<^bsub>\\<nat>\\<^sub>c \\<times>\\<^sub>c one\\<^esub>) \\<circ>\\<^sub>c \\<langle>p, id one\\<rangle>\"\n                      by (typecheck_cfuncs, metis calculation flat_cancels_sharp inv_transpose_func_def2 p_def) \n                    also have \"... = \\<t>\"\n                      by (typecheck_cfuncs, smt (z3) comp_associative2 id_right_unit2 terminal_func_comp terminal_func_unique)\n                    then show ?thesis\n                      by (simp add: calculation)\n                  qed\n                  \n                  have LHS: \"(IMPLIES \\<circ>\\<^sub>c \\<langle>eq_pred X \\<circ>\\<^sub>c i \\<times>\\<^sub>f i, eq_pred \\<nat>\\<^sub>c \\<circ>\\<^sub>c id\\<^sub>c \\<nat>\\<^sub>c \\<times>\\<^sub>f id\\<^sub>c \\<nat>\\<^sub>c\\<rangle> \\<circ>\\<^sub>c id\\<^sub>c \\<nat>\\<^sub>c \\<times>\\<^sub>f zero) \\<circ>\\<^sub>c pone = \\<t>\"\n                  proof - \n                    have \"(IMPLIES \\<circ>\\<^sub>c \\<langle>eq_pred X \\<circ>\\<^sub>c i \\<times>\\<^sub>f i,eq_pred \\<nat>\\<^sub>c \\<circ>\\<^sub>c id\\<^sub>c \\<nat>\\<^sub>c \\<times>\\<^sub>f id\\<^sub>c \\<nat>\\<^sub>c\\<rangle> \\<circ>\\<^sub>c id\\<^sub>c \\<nat>\\<^sub>c \\<times>\\<^sub>f zero) \\<circ>\\<^sub>c pone = \n                           IMPLIES \\<circ>\\<^sub>c \\<langle>eq_pred X \\<circ>\\<^sub>c i \\<times>\\<^sub>f i,eq_pred \\<nat>\\<^sub>c \\<circ>\\<^sub>c id\\<^sub>c \\<nat>\\<^sub>c \\<times>\\<^sub>f id\\<^sub>c \\<nat>\\<^sub>c\\<rangle> \\<circ>\\<^sub>c (id\\<^sub>c \\<nat>\\<^sub>c \\<times>\\<^sub>f zero) \\<circ>\\<^sub>c \\<langle>p, id one\\<rangle>\"\n                      using comp_associative2 p_def by (typecheck_cfuncs, force)\n                    also have \"... = IMPLIES \\<circ>\\<^sub>c \\<langle>eq_pred X \\<circ>\\<^sub>c i \\<times>\\<^sub>f i,eq_pred \\<nat>\\<^sub>c \\<circ>\\<^sub>c id\\<^sub>c \\<nat>\\<^sub>c \\<times>\\<^sub>f id\\<^sub>c \\<nat>\\<^sub>c\\<rangle> \\<circ>\\<^sub>c \\<langle>p, zero\\<rangle>\"\n                      by (typecheck_cfuncs, simp add: cfunc_cross_prod_comp_cfunc_prod id_left_unit2 id_right_unit2)\n                    also have \"... = IMPLIES \\<circ>\\<^sub>c \\<langle>eq_pred X \\<circ>\\<^sub>c (i \\<times>\\<^sub>f i) \\<circ>\\<^sub>c \\<langle>p, zero\\<rangle>,eq_pred \\<nat>\\<^sub>c \\<circ>\\<^sub>c (id\\<^sub>c \\<nat>\\<^sub>c \\<times>\\<^sub>f id\\<^sub>c \\<nat>\\<^sub>c) \\<circ>\\<^sub>c \\<langle>p, zero\\<rangle> \\<rangle>\"\n                      using cfunc_prod_comp comp_associative2 by (typecheck_cfuncs, force)\n                    also have \"... = IMPLIES \\<circ>\\<^sub>c \\<langle>eq_pred X \\<circ>\\<^sub>c   \\<langle>i \\<circ>\\<^sub>c p, i \\<circ>\\<^sub>c zero\\<rangle>,eq_pred \\<nat>\\<^sub>c \\<circ>\\<^sub>c  \\<langle>id\\<^sub>c \\<nat>\\<^sub>c \\<circ>\\<^sub>c p, id\\<^sub>c \\<nat>\\<^sub>c \\<circ>\\<^sub>c zero\\<rangle> \\<rangle>\"\n                      by (typecheck_cfuncs, simp add: cfunc_cross_prod_comp_cfunc_prod)\n                    also have \"... = IMPLIES \\<circ>\\<^sub>c \\<langle>eq_pred X \\<circ>\\<^sub>c \\<langle>i \\<circ>\\<^sub>c p, x\\<rangle>,eq_pred \\<nat>\\<^sub>c \\<circ>\\<^sub>c  \\<langle>p, zero\\<rangle> \\<rangle>\"\n                      by (typecheck_cfuncs, simp add: ibase id_left_unit2)\n                    also have \"... = \\<t>\"\n                    proof(cases \"p = zero\")\n                      assume \"p = zero\"\n                      then show \"IMPLIES \\<circ>\\<^sub>c \\<langle>eq_pred X \\<circ>\\<^sub>c \\<langle>i \\<circ>\\<^sub>c p,x\\<rangle>,eq_pred \\<nat>\\<^sub>c \\<circ>\\<^sub>c \\<langle>p,zero\\<rangle>\\<rangle> = \\<t>\"\n                        by (typecheck_cfuncs, metis IMPLIES_true_true_is_true  eq_pred_iff_eq ibase)\n                    next\n                      assume \"p \\<noteq> zero\"\n                      then obtain j where j_def: \"p = successor \\<circ>\\<^sub>c j\" and j_type[type_rule]: \"j \\<in>\\<^sub>c \\<nat>\\<^sub>c\"\n                        using \\<open>p \\<noteq> zero\\<close> nonzero_is_succ by (typecheck_cfuncs, blast)\n                      have \"i \\<circ>\\<^sub>c p = m \\<circ>\\<^sub>c i \\<circ>\\<^sub>c j\"\n                        using comp_associative2 i_induct j_def successor_type by (typecheck_cfuncs, force)\n                      then have \"i \\<circ>\\<^sub>c p \\<noteq> x\"\n                        using \\<open>i \\<circ>\\<^sub>c p = m \\<circ>\\<^sub>c i \\<circ>\\<^sub>c j\\<close> comp_type j_type x_def by (typecheck_cfuncs, presburger)\n                      then have \"eq_pred X \\<circ>\\<^sub>c \\<langle>i \\<circ>\\<^sub>c p, x\\<rangle> = \\<f>\"\n                        using \\<open>i \\<circ>\\<^sub>c p \\<noteq> x\\<close> eq_pred_iff_eq_conv by (typecheck_cfuncs, blast)\n                      then show \"IMPLIES \\<circ>\\<^sub>c \\<langle>eq_pred X \\<circ>\\<^sub>c \\<langle>i \\<circ>\\<^sub>c p,x\\<rangle>,eq_pred \\<nat>\\<^sub>c \\<circ>\\<^sub>c \\<langle>p,zero\\<rangle>\\<rangle> = \\<t>\"\n                        by (typecheck_cfuncs, metis IMPLIES_false_false_is_true \\<open>eq_pred X \\<circ>\\<^sub>c \\<langle>i \\<circ>\\<^sub>c p,x\\<rangle> = \\<f>\\<close> \\<open>p \\<noteq> zero\\<close> eq_pred_iff_eq_conv)\n                    qed\n                    then show ?thesis\n                      by (simp add: calculation)\n                  qed\n                  show \"(IMPLIES \\<circ>\\<^sub>c \\<langle>eq_pred X \\<circ>\\<^sub>c i \\<times>\\<^sub>f i,  eq_pred \\<nat>\\<^sub>c \\<circ>\\<^sub>c id\\<^sub>c \\<nat>\\<^sub>c \\<times>\\<^sub>f id\\<^sub>c \\<nat>\\<^sub>c\\<rangle> \\<circ>\\<^sub>c id\\<^sub>c \\<nat>\\<^sub>c \\<times>\\<^sub>f zero) \\<circ>\\<^sub>c pone =\n                                    (eval_func \\<Omega> \\<nat>\\<^sub>c \\<circ>\\<^sub>c id\\<^sub>c \\<nat>\\<^sub>c \\<times>\\<^sub>f (\\<t> \\<circ>\\<^sub>c \\<beta>\\<^bsub>\\<nat>\\<^sub>c \\<times>\\<^sub>c one\\<^esub>)\\<^sup>\\<sharp>) \\<circ>\\<^sub>c pone \"\n                    by (simp add: LHS RHS)\n                qed\n              qed\n              then show ?thesis\n                using calculation by presburger\n            qed\n          qed\n          then show ?thesis  \n                by (typecheck_cfuncs, metis FORALL_is_pullback \\<open>(IMPLIES \\<circ>\\<^sub>c \\<langle>eq_pred X \\<circ>\\<^sub>c i \\<times>\\<^sub>f i, eq_pred \\<nat>\\<^sub>c \\<circ>\\<^sub>c id\\<^sub>c \\<nat>\\<^sub>c \\<times>\\<^sub>f id\\<^sub>c \\<nat>\\<^sub>c\\<rangle>)\\<^sup>\\<sharp> \\<circ>\\<^sub>c zero = (\\<t> \\<circ>\\<^sub>c \\<beta>\\<^bsub>\\<nat>\\<^sub>c \\<times>\\<^sub>c one\\<^esub>)\\<^sup>\\<sharp>\\<close> cfunc_type_def comp_associative is_pullback_def square_commutes_def terminal_func_comp)\n        qed\n        \n  \n  \n  \n  \n        show \"(\\<t> \\<circ>\\<^sub>c \\<beta>\\<^bsub>\\<nat>\\<^sub>c\\<^esub>) \\<circ>\\<^sub>c successor = id\\<^sub>c \\<Omega> \\<circ>\\<^sub>c \\<t> \\<circ>\\<^sub>c \\<beta>\\<^bsub>\\<nat>\\<^sub>c\\<^esub>\"\n          by (typecheck_cfuncs, smt (z3) comp_associative2 id_left_unit2 terminal_func_comp)\n  \n        show \"(FORALL \\<nat>\\<^sub>c \\<circ>\\<^sub>c (IMPLIES \\<circ>\\<^sub>c \\<langle>eq_pred X \\<circ>\\<^sub>c i \\<times>\\<^sub>f i, eq_pred \\<nat>\\<^sub>c \\<circ>\\<^sub>c id\\<^sub>c \\<nat>\\<^sub>c \\<times>\\<^sub>f id\\<^sub>c \\<nat>\\<^sub>c\\<rangle>)\\<^sup>\\<sharp>) \\<circ>\\<^sub>c successor\n          = id\\<^sub>c \\<Omega> \\<circ>\\<^sub>c FORALL \\<nat>\\<^sub>c \\<circ>\\<^sub>c (IMPLIES \\<circ>\\<^sub>c \\<langle>eq_pred X \\<circ>\\<^sub>c i \\<times>\\<^sub>f i, eq_pred \\<nat>\\<^sub>c \\<circ>\\<^sub>c id\\<^sub>c \\<nat>\\<^sub>c \\<times>\\<^sub>f id\\<^sub>c \\<nat>\\<^sub>c\\<rangle>)\\<^sup>\\<sharp>\"\n        proof (rule one_separator[where X=\"\\<nat>\\<^sub>c\", where Y=\\<Omega>])\n          show \"(FORALL \\<nat>\\<^sub>c \\<circ>\\<^sub>c (IMPLIES \\<circ>\\<^sub>c \\<langle>eq_pred X \\<circ>\\<^sub>c i \\<times>\\<^sub>f i,eq_pred \\<nat>\\<^sub>c \\<circ>\\<^sub>c id\\<^sub>c \\<nat>\\<^sub>c \\<times>\\<^sub>f id\\<^sub>c \\<nat>\\<^sub>c\\<rangle>)\\<^sup>\\<sharp>) \\<circ>\\<^sub>c successor : \\<nat>\\<^sub>c \\<rightarrow> \\<Omega>\"\n            by typecheck_cfuncs\n          show \"id\\<^sub>c \\<Omega> \\<circ>\\<^sub>c FORALL \\<nat>\\<^sub>c \\<circ>\\<^sub>c (IMPLIES \\<circ>\\<^sub>c \\<langle>eq_pred X \\<circ>\\<^sub>c i \\<times>\\<^sub>f i,eq_pred \\<nat>\\<^sub>c \\<circ>\\<^sub>c id\\<^sub>c \\<nat>\\<^sub>c \\<times>\\<^sub>f id\\<^sub>c \\<nat>\\<^sub>c\\<rangle>)\\<^sup>\\<sharp> : \\<nat>\\<^sub>c \\<rightarrow> \\<Omega>\"\n            by typecheck_cfuncs\n        next\n          fix p\n          assume p_type[type_rule]: \"p \\<in>\\<^sub>c \\<nat>\\<^sub>c\"\n  \n          have case1: \"((FORALL \\<nat>\\<^sub>c \\<circ>\\<^sub>c (IMPLIES \\<circ>\\<^sub>c \\<langle>eq_pred X \\<circ>\\<^sub>c i \\<times>\\<^sub>f i,  eq_pred \\<nat>\\<^sub>c \\<circ>\\<^sub>c id\\<^sub>c \\<nat>\\<^sub>c \\<times>\\<^sub>f id\\<^sub>c \\<nat>\\<^sub>c\\<rangle>)\\<^sup>\\<sharp>) \\<circ>\\<^sub>c successor) \\<circ>\\<^sub>c p = \\<t>\n            \\<Longrightarrow> (id\\<^sub>c \\<Omega> \\<circ>\\<^sub>c FORALL \\<nat>\\<^sub>c \\<circ>\\<^sub>c (IMPLIES \\<circ>\\<^sub>c \\<langle>eq_pred X \\<circ>\\<^sub>c i \\<times>\\<^sub>f i,eq_pred \\<nat>\\<^sub>c \\<circ>\\<^sub>c id\\<^sub>c \\<nat>\\<^sub>c \\<times>\\<^sub>f id\\<^sub>c \\<nat>\\<^sub>c\\<rangle>)\\<^sup>\\<sharp>) \\<circ>\\<^sub>c p = \\<t>\"\n          proof - \n            assume \"((FORALL \\<nat>\\<^sub>c \\<circ>\\<^sub>c (IMPLIES \\<circ>\\<^sub>c \\<langle>eq_pred X \\<circ>\\<^sub>c i \\<times>\\<^sub>f i,  eq_pred \\<nat>\\<^sub>c \\<circ>\\<^sub>c id\\<^sub>c \\<nat>\\<^sub>c \\<times>\\<^sub>f id\\<^sub>c \\<nat>\\<^sub>c\\<rangle>)\\<^sup>\\<sharp>) \\<circ>\\<^sub>c successor) \\<circ>\\<^sub>c p = \\<t>\"\n            then have \"(FORALL \\<nat>\\<^sub>c \\<circ>\\<^sub>c (IMPLIES \\<circ>\\<^sub>c \\<langle>eq_pred X \\<circ>\\<^sub>c i \\<times>\\<^sub>f i, eq_pred \\<nat>\\<^sub>c \\<circ>\\<^sub>c id\\<^sub>c \\<nat>\\<^sub>c \\<times>\\<^sub>f id\\<^sub>c \\<nat>\\<^sub>c\\<rangle>)\\<^sup>\\<sharp>) \\<circ>\\<^sub>c (successor \\<circ>\\<^sub>c p) = \\<t>\"\n              using  comp_associative2 by (typecheck_cfuncs, force)\n            then have \"FORALL \\<nat>\\<^sub>c \\<circ>\\<^sub>c (IMPLIES \\<circ>\\<^sub>c \\<langle>eq_pred X \\<circ>\\<^sub>c i \\<times>\\<^sub>f i,  eq_pred \\<nat>\\<^sub>c \\<circ>\\<^sub>c id\\<^sub>c \\<nat>\\<^sub>c \\<times>\\<^sub>f id\\<^sub>c \\<nat>\\<^sub>c\\<rangle>)\\<^sup>\\<sharp> \\<circ>\\<^sub>c (successor \\<circ>\\<^sub>c p) = \\<t>\"\n              by (typecheck_cfuncs, smt (z3) cfunc_type_def codomain_comp comp_associative)\n            then have \"FORALL \\<nat>\\<^sub>c \\<circ>\\<^sub>c ((IMPLIES \\<circ>\\<^sub>c \\<langle>eq_pred X \\<circ>\\<^sub>c i \\<times>\\<^sub>f i,  eq_pred \\<nat>\\<^sub>c \\<circ>\\<^sub>c id\\<^sub>c \\<nat>\\<^sub>c \\<times>\\<^sub>f id\\<^sub>c \\<nat>\\<^sub>c\\<rangle>) \\<circ>\\<^sub>c (id \\<nat>\\<^sub>c \\<times>\\<^sub>f (successor \\<circ>\\<^sub>c p)))\\<^sup>\\<sharp> = \\<t>\"\n              by (typecheck_cfuncs, metis sharp_comp)\n            then have \"FORALL \\<nat>\\<^sub>c \\<circ>\\<^sub>c ((IMPLIES \\<circ>\\<^sub>c \\<langle>eq_pred X \\<circ>\\<^sub>c i \\<times>\\<^sub>f i,  eq_pred \\<nat>\\<^sub>c \\<circ>\\<^sub>c id\\<^sub>c \\<nat>\\<^sub>c \\<times>\\<^sub>f id\\<^sub>c \\<nat>\\<^sub>c\\<rangle>) \\<circ>\\<^sub>c \\<langle>id \\<nat>\\<^sub>c, (successor \\<circ>\\<^sub>c p) \\<circ>\\<^sub>c \\<beta>\\<^bsub>\\<nat>\\<^sub>c\\<^esub>\\<rangle> \\<circ>\\<^sub>c left_cart_proj \\<nat>\\<^sub>c one)\\<^sup>\\<sharp> = \\<t>\"\n              by (typecheck_cfuncs, metis cfunc_cross_prod_right_terminal_decomp)\n            then have \"FORALL \\<nat>\\<^sub>c \\<circ>\\<^sub>c ((IMPLIES \\<circ>\\<^sub>c \\<langle>eq_pred X \\<circ>\\<^sub>c i \\<times>\\<^sub>f i,  eq_pred \\<nat>\\<^sub>c \\<circ>\\<^sub>c id\\<^sub>c \\<nat>\\<^sub>c \\<times>\\<^sub>f id\\<^sub>c \\<nat>\\<^sub>c\\<rangle> \\<circ>\\<^sub>c \\<langle>id \\<nat>\\<^sub>c, (successor \\<circ>\\<^sub>c p) \\<circ>\\<^sub>c \\<beta>\\<^bsub>\\<nat>\\<^sub>c\\<^esub>\\<rangle>) \\<circ>\\<^sub>c left_cart_proj \\<nat>\\<^sub>c one)\\<^sup>\\<sharp> = \\<t>\"\n            proof -\n              have \"(IMPLIES \\<circ>\\<^sub>c \\<langle>eq_pred X \\<circ>\\<^sub>c i \\<times>\\<^sub>f i, eq_pred \\<nat>\\<^sub>c \\<circ>\\<^sub>c id\\<^sub>c \\<nat>\\<^sub>c \\<times>\\<^sub>f id\\<^sub>c \\<nat>\\<^sub>c\\<rangle>) \\<circ>\\<^sub>c \\<langle>id \\<nat>\\<^sub>c, (successor \\<circ>\\<^sub>c p) \\<circ>\\<^sub>c \\<beta>\\<^bsub>\\<nat>\\<^sub>c\\<^esub>\\<rangle> \\<circ>\\<^sub>c left_cart_proj \\<nat>\\<^sub>c one\n                  = (IMPLIES \\<circ>\\<^sub>c \\<langle>eq_pred X \\<circ>\\<^sub>c i \\<times>\\<^sub>f i, eq_pred \\<nat>\\<^sub>c \\<circ>\\<^sub>c id\\<^sub>c \\<nat>\\<^sub>c \\<times>\\<^sub>f id\\<^sub>c \\<nat>\\<^sub>c\\<rangle> \\<circ>\\<^sub>c \\<langle>id \\<nat>\\<^sub>c, (successor \\<circ>\\<^sub>c p) \\<circ>\\<^sub>c \\<beta>\\<^bsub>\\<nat>\\<^sub>c\\<^esub>\\<rangle>) \\<circ>\\<^sub>c left_cart_proj \\<nat>\\<^sub>c one\"\n                by (typecheck_cfuncs, simp add: comp_associative2)\n              then show \"FORALL \\<nat>\\<^sub>c \\<circ>\\<^sub>c ((IMPLIES \\<circ>\\<^sub>c \\<langle>eq_pred X \\<circ>\\<^sub>c i \\<times>\\<^sub>f i,  eq_pred \\<nat>\\<^sub>c \\<circ>\\<^sub>c id\\<^sub>c \\<nat>\\<^sub>c \\<times>\\<^sub>f id\\<^sub>c \\<nat>\\<^sub>c\\<rangle>) \\<circ>\\<^sub>c \\<langle>id \\<nat>\\<^sub>c, (successor \\<circ>\\<^sub>c p) \\<circ>\\<^sub>c \\<beta>\\<^bsub>\\<nat>\\<^sub>c\\<^esub>\\<rangle> \\<circ>\\<^sub>c left_cart_proj \\<nat>\\<^sub>c one)\\<^sup>\\<sharp> = \\<t>\n                \\<Longrightarrow> FORALL \\<nat>\\<^sub>c \\<circ>\\<^sub>c ((IMPLIES \\<circ>\\<^sub>c \\<langle>eq_pred X \\<circ>\\<^sub>c i \\<times>\\<^sub>f i, eq_pred \\<nat>\\<^sub>c \\<circ>\\<^sub>c id\\<^sub>c \\<nat>\\<^sub>c \\<times>\\<^sub>f id\\<^sub>c \\<nat>\\<^sub>c\\<rangle> \\<circ>\\<^sub>c \\<langle>id \\<nat>\\<^sub>c, (successor \\<circ>\\<^sub>c p) \\<circ>\\<^sub>c \\<beta>\\<^bsub>\\<nat>\\<^sub>c\\<^esub>\\<rangle>) \\<circ>\\<^sub>c left_cart_proj \\<nat>\\<^sub>c one)\\<^sup>\\<sharp> = \\<t>\"\n                using p_type by force\n            qed\n            then have \"(\\<And>q. q \\<in>\\<^sub>c \\<nat>\\<^sub>c \\<Longrightarrow> (IMPLIES \\<circ>\\<^sub>c \\<langle>eq_pred X \\<circ>\\<^sub>c i \\<times>\\<^sub>f i,  eq_pred \\<nat>\\<^sub>c \\<circ>\\<^sub>c id\\<^sub>c \\<nat>\\<^sub>c \\<times>\\<^sub>f id\\<^sub>c \\<nat>\\<^sub>c\\<rangle> \\<circ>\\<^sub>c \\<langle>id \\<nat>\\<^sub>c, (successor \\<circ>\\<^sub>c p) \\<circ>\\<^sub>c \\<beta>\\<^bsub>\\<nat>\\<^sub>c\\<^esub>\\<rangle>) \\<circ>\\<^sub>c q = \\<t>)\"\n            proof (rule_tac FORALL_true_implies_all_true[where X=\"\\<nat>\\<^sub>c\"], auto)\n              show \"IMPLIES \\<circ>\\<^sub>c \\<langle>eq_pred X \\<circ>\\<^sub>c i \\<times>\\<^sub>f i,  eq_pred \\<nat>\\<^sub>c \\<circ>\\<^sub>c id\\<^sub>c \\<nat>\\<^sub>c \\<times>\\<^sub>f id\\<^sub>c \\<nat>\\<^sub>c\\<rangle> \\<circ>\\<^sub>c \\<langle>id\\<^sub>c \\<nat>\\<^sub>c,(successor \\<circ>\\<^sub>c p) \\<circ>\\<^sub>c \\<beta>\\<^bsub>\\<nat>\\<^sub>c\\<^esub>\\<rangle> : \\<nat>\\<^sub>c \\<rightarrow> \\<Omega>\"\n                by (typecheck_cfuncs)\n            qed\n            then have f1: \"\\<And> q. q \\<in>\\<^sub>c \\<nat>\\<^sub>c \\<Longrightarrow> (IMPLIES \\<circ>\\<^sub>c \\<langle>eq_pred X \\<circ>\\<^sub>c i \\<times>\\<^sub>f i,  eq_pred \\<nat>\\<^sub>c \\<circ>\\<^sub>c id\\<^sub>c \\<nat>\\<^sub>c \\<times>\\<^sub>f id\\<^sub>c \\<nat>\\<^sub>c\\<rangle> \\<circ>\\<^sub>c \\<langle>id \\<nat>\\<^sub>c, (successor \\<circ>\\<^sub>c p) \\<circ>\\<^sub>c \\<beta>\\<^bsub>\\<nat>\\<^sub>c\\<^esub>\\<rangle>) \\<circ>\\<^sub>c q = \\<t>\"\n              by auto\n            have ind_hyp: \"\\<And> q. q \\<in>\\<^sub>c \\<nat>\\<^sub>c \\<Longrightarrow> (i \\<circ>\\<^sub>c q  =  i \\<circ>\\<^sub>c (successor \\<circ>\\<^sub>c p)) \\<Longrightarrow> (q = (successor \\<circ>\\<^sub>c p))\"    \n            proof - \n              fix q\n              assume q_type[type_rule]: \"q \\<in>\\<^sub>c \\<nat>\\<^sub>c\"\n              have \"(IMPLIES \\<circ>\\<^sub>c \\<langle>eq_pred X \\<circ>\\<^sub>c i \\<times>\\<^sub>f i,  eq_pred \\<nat>\\<^sub>c \\<circ>\\<^sub>c id\\<^sub>c \\<nat>\\<^sub>c \\<times>\\<^sub>f id\\<^sub>c \\<nat>\\<^sub>c\\<rangle> \\<circ>\\<^sub>c \\<langle>id \\<nat>\\<^sub>c, (successor \\<circ>\\<^sub>c p) \\<circ>\\<^sub>c \\<beta>\\<^bsub>\\<nat>\\<^sub>c\\<^esub>\\<rangle>) \\<circ>\\<^sub>c q = \\<t>\"\n                using f1 by (typecheck_cfuncs, blast)\n              then have \"(IMPLIES \\<circ>\\<^sub>c \\<langle>eq_pred X \\<circ>\\<^sub>c i \\<times>\\<^sub>f i, eq_pred \\<nat>\\<^sub>c \\<circ>\\<^sub>c id\\<^sub>c \\<nat>\\<^sub>c \\<times>\\<^sub>f id\\<^sub>c \\<nat>\\<^sub>c\\<rangle>) \\<circ>\\<^sub>c \\<langle>id \\<nat>\\<^sub>c, (successor \\<circ>\\<^sub>c p) \\<circ>\\<^sub>c \\<beta>\\<^bsub>\\<nat>\\<^sub>c\\<^esub>\\<rangle> \\<circ>\\<^sub>c q = \\<t>\"\n                using  comp_associative2 by (typecheck_cfuncs, force)\n              then have \"(IMPLIES \\<circ>\\<^sub>c \\<langle>eq_pred X \\<circ>\\<^sub>c i \\<times>\\<^sub>f i,  eq_pred \\<nat>\\<^sub>c \\<circ>\\<^sub>c id\\<^sub>c \\<nat>\\<^sub>c \\<times>\\<^sub>f id\\<^sub>c \\<nat>\\<^sub>c\\<rangle>) \\<circ>\\<^sub>c \\<langle>q, (successor \\<circ>\\<^sub>c p)\\<rangle>  = \\<t>\"\n                by (typecheck_cfuncs, metis cart_prod_extract_left)\n              then have \"IMPLIES \\<circ>\\<^sub>c \\<langle>eq_pred X \\<circ>\\<^sub>c i \\<times>\\<^sub>f i,  eq_pred \\<nat>\\<^sub>c \\<circ>\\<^sub>c id\\<^sub>c \\<nat>\\<^sub>c \\<times>\\<^sub>f id\\<^sub>c \\<nat>\\<^sub>c\\<rangle> \\<circ>\\<^sub>c \\<langle>q, (successor \\<circ>\\<^sub>c p)\\<rangle>  = \\<t>\"\n                using  comp_associative2 by (typecheck_cfuncs, force)\n              then have \"IMPLIES \\<circ>\\<^sub>c \\<langle>(eq_pred X \\<circ>\\<^sub>c (i \\<times>\\<^sub>f i)) \\<circ>\\<^sub>c \\<langle>q, (successor \\<circ>\\<^sub>c p)\\<rangle>, (eq_pred \\<nat>\\<^sub>c \\<circ>\\<^sub>c (id\\<^sub>c \\<nat>\\<^sub>c \\<times>\\<^sub>f id\\<^sub>c \\<nat>\\<^sub>c)) \\<circ>\\<^sub>c \\<langle>q, (successor \\<circ>\\<^sub>c p)\\<rangle> \\<rangle>   = \\<t>\"\n                by (typecheck_cfuncs, metis cfunc_prod_comp)\n              then have \"IMPLIES \\<circ>\\<^sub>c \\<langle>eq_pred X \\<circ>\\<^sub>c (i \\<times>\\<^sub>f i) \\<circ>\\<^sub>c \\<langle>q, (successor \\<circ>\\<^sub>c p)\\<rangle>,  eq_pred \\<nat>\\<^sub>c \\<circ>\\<^sub>c (id\\<^sub>c \\<nat>\\<^sub>c \\<times>\\<^sub>f id\\<^sub>c \\<nat>\\<^sub>c) \\<circ>\\<^sub>c \\<langle>q, (successor \\<circ>\\<^sub>c p)\\<rangle>\\<rangle>   = \\<t>\"\n                by (typecheck_cfuncs, smt (verit, ccfv_threshold)  cfunc_type_def comp_associative domain_comp)\n              then have \"IMPLIES \\<circ>\\<^sub>c \\<langle>eq_pred X \\<circ>\\<^sub>c \\<langle>i \\<circ>\\<^sub>c q, i \\<circ>\\<^sub>c (successor \\<circ>\\<^sub>c p)\\<rangle>, eq_pred \\<nat>\\<^sub>c \\<circ>\\<^sub>c \\<langle>q, (successor \\<circ>\\<^sub>c p)\\<rangle>\\<rangle> = \\<t>\"\n                using cfunc_cross_prod_comp_cfunc_prod id_cross_prod id_left_unit2 by (typecheck_cfuncs, force)\n              then have \"(eq_pred X \\<circ>\\<^sub>c \\<langle>i \\<circ>\\<^sub>c q, i \\<circ>\\<^sub>c (successor \\<circ>\\<^sub>c p)\\<rangle> = \\<t>) \\<Longrightarrow> (eq_pred \\<nat>\\<^sub>c \\<circ>\\<^sub>c \\<langle>q, (successor \\<circ>\\<^sub>c p)\\<rangle> = \\<t>)  \"\n                by (typecheck_cfuncs, metis IMPLIES_true_false_is_false \\<open>IMPLIES \\<circ>\\<^sub>c \\<langle>eq_pred X \\<circ>\\<^sub>c \\<langle>i \\<circ>\\<^sub>c q,i \\<circ>\\<^sub>c successor \\<circ>\\<^sub>c p\\<rangle>,eq_pred \\<nat>\\<^sub>c \\<circ>\\<^sub>c \\<langle>q,successor \\<circ>\\<^sub>c p\\<rangle>\\<rangle> = \\<t>\\<close> true_false_only_truth_values)\n              then show \"(i \\<circ>\\<^sub>c q  =  i \\<circ>\\<^sub>c (successor \\<circ>\\<^sub>c p)) \\<Longrightarrow> (q = (successor \\<circ>\\<^sub>c p))\"\n                using  eq_pred_iff_eq by (typecheck_cfuncs, auto)\n            qed\n            have \"\\<And>q. q \\<in>\\<^sub>c \\<nat>\\<^sub>c \\<Longrightarrow> (IMPLIES \\<circ>\\<^sub>c \\<langle>eq_pred X \\<circ>\\<^sub>c (i \\<times>\\<^sub>f i), eq_pred \\<nat>\\<^sub>c \\<circ>\\<^sub>c (id \\<nat>\\<^sub>c \\<times>\\<^sub>f id \\<nat>\\<^sub>c)\\<rangle> \\<circ>\\<^sub>c \\<langle>id\\<^sub>c \\<nat>\\<^sub>c,p \\<circ>\\<^sub>c \\<beta>\\<^bsub>\\<nat>\\<^sub>c\\<^esub>\\<rangle>) \\<circ>\\<^sub>c q = \\<t>\"\n            proof -\n              fix q\n              assume q_type[type_rule]: \"q \\<in>\\<^sub>c \\<nat>\\<^sub>c\"\n              have \"i \\<circ>\\<^sub>c q = i \\<circ>\\<^sub>c p \\<Longrightarrow> q = p\"\n              proof -\n                assume \"i \\<circ>\\<^sub>c q = i \\<circ>\\<^sub>c p\"\n                then have \"m \\<circ>\\<^sub>c i \\<circ>\\<^sub>c q = m \\<circ>\\<^sub>c i \\<circ>\\<^sub>c p\"\n                  by auto\n                then have \"i \\<circ>\\<^sub>c successor \\<circ>\\<^sub>c q = i \\<circ>\\<^sub>c successor \\<circ>\\<^sub>c p\"\n                  using comp_associative2 i_induct i_type m_type p_type q_type successor_type by auto\n                then have \"successor \\<circ>\\<^sub>c q = successor \\<circ>\\<^sub>c p\"\n                  by (simp add: ind_hyp q_type succ_n_type)\n                then show \"q = p\"\n                  by (simp add: p_type q_type succ_inject)\n              qed\n              then have \"eq_pred X \\<circ>\\<^sub>c \\<langle>i \\<circ>\\<^sub>c q, i \\<circ>\\<^sub>c p\\<rangle> = \\<t> \\<Longrightarrow> eq_pred \\<nat>\\<^sub>c \\<circ>\\<^sub>c \\<langle>q, p\\<rangle> = \\<t>\"\n                using  eq_pred_iff_eq by (typecheck_cfuncs, blast)\n              then have \"eq_pred X \\<circ>\\<^sub>c (i \\<times>\\<^sub>f i) \\<circ>\\<^sub>c \\<langle>q, p\\<rangle> = \\<t> \\<Longrightarrow> eq_pred \\<nat>\\<^sub>c \\<circ>\\<^sub>c (id \\<nat>\\<^sub>c \\<times>\\<^sub>f id \\<nat>\\<^sub>c) \\<circ>\\<^sub>c \\<langle>q, p\\<rangle> = \\<t>\"\n                by (typecheck_cfuncs, simp add: cfunc_cross_prod_comp_cfunc_prod id_left_unit2)\n              then have \"(eq_pred X \\<circ>\\<^sub>c (i \\<times>\\<^sub>f i)) \\<circ>\\<^sub>c \\<langle>q, p\\<rangle> = \\<t> \\<Longrightarrow> (eq_pred \\<nat>\\<^sub>c \\<circ>\\<^sub>c (id \\<nat>\\<^sub>c \\<times>\\<^sub>f id \\<nat>\\<^sub>c)) \\<circ>\\<^sub>c \\<langle>q, p\\<rangle> = \\<t>\"\n                using comp_associative2 by (typecheck_cfuncs, auto)\n              then have \"IMPLIES \\<circ>\\<^sub>c \\<langle>(eq_pred X \\<circ>\\<^sub>c (i \\<times>\\<^sub>f i)) \\<circ>\\<^sub>c \\<langle>q, p\\<rangle>, (eq_pred \\<nat>\\<^sub>c \\<circ>\\<^sub>c (id \\<nat>\\<^sub>c \\<times>\\<^sub>f id \\<nat>\\<^sub>c)) \\<circ>\\<^sub>c \\<langle>q, p\\<rangle>\\<rangle> = \\<t>\"\n                by (typecheck_cfuncs, metis IMPLIES_false_is_true_false true_false_only_truth_values)\n              then have \"IMPLIES \\<circ>\\<^sub>c \\<langle>eq_pred X \\<circ>\\<^sub>c (i \\<times>\\<^sub>f i), eq_pred \\<nat>\\<^sub>c \\<circ>\\<^sub>c (id \\<nat>\\<^sub>c \\<times>\\<^sub>f id \\<nat>\\<^sub>c)\\<rangle> \\<circ>\\<^sub>c \\<langle>q, p\\<rangle>  = \\<t>\"\n                by (typecheck_cfuncs, simp add: cfunc_prod_comp)\n              then have \"IMPLIES \\<circ>\\<^sub>c \\<langle>eq_pred X \\<circ>\\<^sub>c (i \\<times>\\<^sub>f i), eq_pred \\<nat>\\<^sub>c \\<circ>\\<^sub>c (id \\<nat>\\<^sub>c \\<times>\\<^sub>f id \\<nat>\\<^sub>c)\\<rangle> \\<circ>\\<^sub>c (\\<langle>id\\<^sub>c \\<nat>\\<^sub>c,p \\<circ>\\<^sub>c \\<beta>\\<^bsub>\\<nat>\\<^sub>c\\<^esub>\\<rangle> \\<circ>\\<^sub>c q) = \\<t>\"\n                by (typecheck_cfuncs, metis cart_prod_extract_left)\n              then show \"(IMPLIES \\<circ>\\<^sub>c \\<langle>eq_pred X \\<circ>\\<^sub>c (i \\<times>\\<^sub>f i), eq_pred \\<nat>\\<^sub>c \\<circ>\\<^sub>c (id \\<nat>\\<^sub>c \\<times>\\<^sub>f id \\<nat>\\<^sub>c)\\<rangle> \\<circ>\\<^sub>c \\<langle>id\\<^sub>c \\<nat>\\<^sub>c,p \\<circ>\\<^sub>c \\<beta>\\<^bsub>\\<nat>\\<^sub>c\\<^esub>\\<rangle>) \\<circ>\\<^sub>c q = \\<t>\"\n                using comp_associative2 by (typecheck_cfuncs, auto)\n            qed\n            then have \"FORALL \\<nat>\\<^sub>c \\<circ>\\<^sub>c ((IMPLIES \\<circ>\\<^sub>c \\<langle>eq_pred X \\<circ>\\<^sub>c (i \\<times>\\<^sub>f i), eq_pred \\<nat>\\<^sub>c \\<circ>\\<^sub>c (id \\<nat>\\<^sub>c \\<times>\\<^sub>f id \\<nat>\\<^sub>c)\\<rangle> \\<circ>\\<^sub>c \\<langle>id\\<^sub>c \\<nat>\\<^sub>c,p \\<circ>\\<^sub>c \\<beta>\\<^bsub>\\<nat>\\<^sub>c\\<^esub>\\<rangle>) \\<circ>\\<^sub>c left_cart_proj \\<nat>\\<^sub>c one)\\<^sup>\\<sharp> = \\<t>\"\n              using all_true_implies_FORALL_true by (typecheck_cfuncs, blast)\n            then have \"FORALL \\<nat>\\<^sub>c \\<circ>\\<^sub>c (IMPLIES \\<circ>\\<^sub>c \\<langle>eq_pred X \\<circ>\\<^sub>c (i \\<times>\\<^sub>f i), eq_pred \\<nat>\\<^sub>c \\<circ>\\<^sub>c (id \\<nat>\\<^sub>c \\<times>\\<^sub>f id \\<nat>\\<^sub>c)\\<rangle> \\<circ>\\<^sub>c (\\<langle>id\\<^sub>c \\<nat>\\<^sub>c,p \\<circ>\\<^sub>c \\<beta>\\<^bsub>\\<nat>\\<^sub>c\\<^esub>\\<rangle> \\<circ>\\<^sub>c left_cart_proj \\<nat>\\<^sub>c one))\\<^sup>\\<sharp> = \\<t>\"\n              by (typecheck_cfuncs, smt (z3) cfunc_type_def comp_associative domain_comp)\n            then have \"FORALL \\<nat>\\<^sub>c \\<circ>\\<^sub>c ((IMPLIES \\<circ>\\<^sub>c \\<langle>eq_pred X \\<circ>\\<^sub>c (i \\<times>\\<^sub>f i), eq_pred \\<nat>\\<^sub>c \\<circ>\\<^sub>c (id \\<nat>\\<^sub>c \\<times>\\<^sub>f id \\<nat>\\<^sub>c)\\<rangle>) \\<circ>\\<^sub>c (id \\<nat>\\<^sub>c \\<times>\\<^sub>f p))\\<^sup>\\<sharp> = \\<t>\"\n              by (typecheck_cfuncs, metis cfunc_cross_prod_right_terminal_decomp cfunc_type_def comp_associative domain_comp)\n            then have \"(FORALL \\<nat>\\<^sub>c \\<circ>\\<^sub>c (IMPLIES \\<circ>\\<^sub>c \\<langle>eq_pred X \\<circ>\\<^sub>c i \\<times>\\<^sub>f i, eq_pred \\<nat>\\<^sub>c \\<circ>\\<^sub>c id\\<^sub>c \\<nat>\\<^sub>c \\<times>\\<^sub>f id\\<^sub>c \\<nat>\\<^sub>c\\<rangle>)\\<^sup>\\<sharp>) \\<circ>\\<^sub>c p = \\<t>\"\n              by (typecheck_cfuncs, smt (z3) sharp_comp comp_associative2)\n            then show \"(id\\<^sub>c \\<Omega> \\<circ>\\<^sub>c FORALL \\<nat>\\<^sub>c \\<circ>\\<^sub>c (IMPLIES \\<circ>\\<^sub>c \\<langle>eq_pred X \\<circ>\\<^sub>c i \\<times>\\<^sub>f i, eq_pred \\<nat>\\<^sub>c \\<circ>\\<^sub>c id\\<^sub>c \\<nat>\\<^sub>c \\<times>\\<^sub>f id\\<^sub>c \\<nat>\\<^sub>c\\<rangle>)\\<^sup>\\<sharp>) \\<circ>\\<^sub>c p = \\<t>\"\n              by (typecheck_cfuncs, smt id_left_unit2)\n              \n          qed\n  \n          have case2: \"(id\\<^sub>c \\<Omega> \\<circ>\\<^sub>c FORALL \\<nat>\\<^sub>c \\<circ>\\<^sub>c (IMPLIES \\<circ>\\<^sub>c \\<langle>eq_pred X \\<circ>\\<^sub>c i \\<times>\\<^sub>f i, eq_pred \\<nat>\\<^sub>c \\<circ>\\<^sub>c id\\<^sub>c \\<nat>\\<^sub>c \\<times>\\<^sub>f id\\<^sub>c \\<nat>\\<^sub>c\\<rangle>)\\<^sup>\\<sharp>) \\<circ>\\<^sub>c p = \\<t>\n              \\<Longrightarrow> ((FORALL \\<nat>\\<^sub>c \\<circ>\\<^sub>c (IMPLIES \\<circ>\\<^sub>c \\<langle>eq_pred X \\<circ>\\<^sub>c i \\<times>\\<^sub>f i, eq_pred \\<nat>\\<^sub>c \\<circ>\\<^sub>c id\\<^sub>c \\<nat>\\<^sub>c \\<times>\\<^sub>f id\\<^sub>c \\<nat>\\<^sub>c\\<rangle>)\\<^sup>\\<sharp>) \\<circ>\\<^sub>c successor) \\<circ>\\<^sub>c p = \\<t>\"\n          proof -\n            assume \"(id\\<^sub>c \\<Omega> \\<circ>\\<^sub>c FORALL \\<nat>\\<^sub>c \\<circ>\\<^sub>c (IMPLIES \\<circ>\\<^sub>c \\<langle>eq_pred X \\<circ>\\<^sub>c i \\<times>\\<^sub>f i, eq_pred \\<nat>\\<^sub>c \\<circ>\\<^sub>c id\\<^sub>c \\<nat>\\<^sub>c \\<times>\\<^sub>f id\\<^sub>c \\<nat>\\<^sub>c\\<rangle>)\\<^sup>\\<sharp>) \\<circ>\\<^sub>c p = \\<t>\"\n            then have \"(FORALL \\<nat>\\<^sub>c \\<circ>\\<^sub>c (IMPLIES \\<circ>\\<^sub>c \\<langle>eq_pred X \\<circ>\\<^sub>c i \\<times>\\<^sub>f i, eq_pred \\<nat>\\<^sub>c \\<circ>\\<^sub>c id\\<^sub>c \\<nat>\\<^sub>c \\<times>\\<^sub>f id\\<^sub>c \\<nat>\\<^sub>c\\<rangle>)\\<^sup>\\<sharp>) \\<circ>\\<^sub>c p = \\<t>\"\n              by (typecheck_cfuncs_prems, insert id_left_unit2, presburger)\n            then have \"FORALL \\<nat>\\<^sub>c \\<circ>\\<^sub>c ((IMPLIES \\<circ>\\<^sub>c \\<langle>eq_pred X \\<circ>\\<^sub>c i \\<times>\\<^sub>f i, eq_pred \\<nat>\\<^sub>c \\<circ>\\<^sub>c id\\<^sub>c \\<nat>\\<^sub>c \\<times>\\<^sub>f id\\<^sub>c \\<nat>\\<^sub>c\\<rangle>)\\<^sup>\\<sharp> \\<circ>\\<^sub>c p) = \\<t>\"\n              by (typecheck_cfuncs, simp add: comp_associative2)\n            then have \"FORALL \\<nat>\\<^sub>c \\<circ>\\<^sub>c ((IMPLIES \\<circ>\\<^sub>c \\<langle>eq_pred X \\<circ>\\<^sub>c i \\<times>\\<^sub>f i, eq_pred \\<nat>\\<^sub>c \\<circ>\\<^sub>c id\\<^sub>c \\<nat>\\<^sub>c \\<times>\\<^sub>f id\\<^sub>c \\<nat>\\<^sub>c\\<rangle>) \\<circ>\\<^sub>c (id \\<nat>\\<^sub>c \\<times>\\<^sub>f p))\\<^sup>\\<sharp> = \\<t>\"\n              by (typecheck_cfuncs, metis sharp_comp)\n            then have \"FORALL \\<nat>\\<^sub>c \\<circ>\\<^sub>c ((IMPLIES \\<circ>\\<^sub>c \\<langle>eq_pred X \\<circ>\\<^sub>c i \\<times>\\<^sub>f i,  eq_pred \\<nat>\\<^sub>c \\<circ>\\<^sub>c id\\<^sub>c \\<nat>\\<^sub>c \\<times>\\<^sub>f id\\<^sub>c \\<nat>\\<^sub>c\\<rangle>) \\<circ>\\<^sub>c \\<langle>id \\<nat>\\<^sub>c, p \\<circ>\\<^sub>c \\<beta>\\<^bsub>\\<nat>\\<^sub>c\\<^esub>\\<rangle> \\<circ>\\<^sub>c left_cart_proj \\<nat>\\<^sub>c one)\\<^sup>\\<sharp> = \\<t>\"\n              by (typecheck_cfuncs, metis cfunc_cross_prod_right_terminal_decomp)\n            then have \"\\<And>q. q \\<in>\\<^sub>c \\<nat>\\<^sub>c \\<Longrightarrow> (IMPLIES \\<circ>\\<^sub>c \\<langle>eq_pred X \\<circ>\\<^sub>c i \\<times>\\<^sub>f i, eq_pred \\<nat>\\<^sub>c \\<circ>\\<^sub>c id\\<^sub>c \\<nat>\\<^sub>c \\<times>\\<^sub>f id\\<^sub>c \\<nat>\\<^sub>c\\<rangle> \\<circ>\\<^sub>c \\<langle>id \\<nat>\\<^sub>c, p \\<circ>\\<^sub>c \\<beta>\\<^bsub>\\<nat>\\<^sub>c\\<^esub>\\<rangle>) \\<circ>\\<^sub>c q = \\<t>\"\n            proof -\n              assume \"FORALL \\<nat>\\<^sub>c \\<circ>\\<^sub>c ((IMPLIES \\<circ>\\<^sub>c \\<langle>eq_pred X \\<circ>\\<^sub>c i \\<times>\\<^sub>f i,eq_pred \\<nat>\\<^sub>c \\<circ>\\<^sub>c id\\<^sub>c \\<nat>\\<^sub>c \\<times>\\<^sub>f id\\<^sub>c \\<nat>\\<^sub>c\\<rangle>) \\<circ>\\<^sub>c \\<langle>id\\<^sub>c \\<nat>\\<^sub>c,p \\<circ>\\<^sub>c \\<beta>\\<^bsub>\\<nat>\\<^sub>c\\<^esub>\\<rangle> \\<circ>\\<^sub>c left_cart_proj \\<nat>\\<^sub>c one)\\<^sup>\\<sharp> = \\<t>\"\n              then have \"FORALL \\<nat>\\<^sub>c \\<circ>\\<^sub>c ((IMPLIES \\<circ>\\<^sub>c \\<langle>eq_pred X \\<circ>\\<^sub>c i \\<times>\\<^sub>f i,eq_pred \\<nat>\\<^sub>c \\<circ>\\<^sub>c id\\<^sub>c \\<nat>\\<^sub>c \\<times>\\<^sub>f id\\<^sub>c \\<nat>\\<^sub>c\\<rangle>) \\<circ>\\<^sub>c \\<langle>id\\<^sub>c \\<nat>\\<^sub>c,p \\<circ>\\<^sub>c \\<beta>\\<^bsub>\\<nat>\\<^sub>c\\<^esub>\\<rangle> \\<circ>\\<^sub>c left_cart_proj \\<nat>\\<^sub>c one)\\<^sup>\\<sharp> = \\<t>\"\n                using p_type by auto\n              then show \"\\<And>q. q \\<in>\\<^sub>c \\<nat>\\<^sub>c \\<Longrightarrow> (IMPLIES \\<circ>\\<^sub>c \\<langle>eq_pred X \\<circ>\\<^sub>c i \\<times>\\<^sub>f i, eq_pred \\<nat>\\<^sub>c \\<circ>\\<^sub>c id\\<^sub>c \\<nat>\\<^sub>c \\<times>\\<^sub>f id\\<^sub>c \\<nat>\\<^sub>c\\<rangle> \\<circ>\\<^sub>c \\<langle>id \\<nat>\\<^sub>c, p \\<circ>\\<^sub>c \\<beta>\\<^bsub>\\<nat>\\<^sub>c\\<^esub>\\<rangle>) \\<circ>\\<^sub>c q = \\<t>\"\n                by (rule_tac FORALL_true_implies_all_true[where X=\"\\<nat>\\<^sub>c\"], auto, \n                    typecheck_cfuncs, typecheck_cfuncs, smt comp_associative2)\n            qed\n            then have f1: \"\\<And> q. q \\<in>\\<^sub>c \\<nat>\\<^sub>c \\<Longrightarrow> (IMPLIES \\<circ>\\<^sub>c \\<langle>eq_pred X \\<circ>\\<^sub>c i \\<times>\\<^sub>f i, eq_pred \\<nat>\\<^sub>c \\<circ>\\<^sub>c id\\<^sub>c \\<nat>\\<^sub>c \\<times>\\<^sub>f id\\<^sub>c \\<nat>\\<^sub>c\\<rangle> \\<circ>\\<^sub>c \\<langle>id \\<nat>\\<^sub>c, p \\<circ>\\<^sub>c \\<beta>\\<^bsub>\\<nat>\\<^sub>c\\<^esub>\\<rangle>) \\<circ>\\<^sub>c q = \\<t>\"\n              by auto\n            have ind_hyp: \"\\<And> q. q \\<in>\\<^sub>c \\<nat>\\<^sub>c \\<Longrightarrow> (i \\<circ>\\<^sub>c q  =  i \\<circ>\\<^sub>c p) \\<Longrightarrow> (q = p)\"\n            proof - \n              fix q\n              assume q_type[type_rule]: \"q \\<in>\\<^sub>c \\<nat>\\<^sub>c\"\n              have \"(IMPLIES \\<circ>\\<^sub>c \\<langle>eq_pred X \\<circ>\\<^sub>c i \\<times>\\<^sub>f i, eq_pred \\<nat>\\<^sub>c \\<circ>\\<^sub>c id\\<^sub>c \\<nat>\\<^sub>c \\<times>\\<^sub>f id\\<^sub>c \\<nat>\\<^sub>c\\<rangle> \\<circ>\\<^sub>c \\<langle>id \\<nat>\\<^sub>c, p \\<circ>\\<^sub>c \\<beta>\\<^bsub>\\<nat>\\<^sub>c\\<^esub>\\<rangle>) \\<circ>\\<^sub>c q = \\<t>\"\n                by (simp add: f1  p_type q_type)\n              then have \"(IMPLIES \\<circ>\\<^sub>c \\<langle>eq_pred X \\<circ>\\<^sub>c i \\<times>\\<^sub>f i, eq_pred \\<nat>\\<^sub>c \\<circ>\\<^sub>c id\\<^sub>c \\<nat>\\<^sub>c \\<times>\\<^sub>f id\\<^sub>c \\<nat>\\<^sub>c\\<rangle>) \\<circ>\\<^sub>c \\<langle>id \\<nat>\\<^sub>c, p \\<circ>\\<^sub>c \\<beta>\\<^bsub>\\<nat>\\<^sub>c\\<^esub>\\<rangle> \\<circ>\\<^sub>c q = \\<t>\"\n                using  comp_associative2 by (typecheck_cfuncs, force)\n              then have \"(IMPLIES \\<circ>\\<^sub>c \\<langle>eq_pred X \\<circ>\\<^sub>c i \\<times>\\<^sub>f i,  eq_pred \\<nat>\\<^sub>c \\<circ>\\<^sub>c id\\<^sub>c \\<nat>\\<^sub>c \\<times>\\<^sub>f id\\<^sub>c \\<nat>\\<^sub>c\\<rangle>) \\<circ>\\<^sub>c \\<langle>q, p\\<rangle>  = \\<t>\"\n                by (typecheck_cfuncs, metis cart_prod_extract_left)\n              then have \"IMPLIES \\<circ>\\<^sub>c \\<langle>eq_pred X \\<circ>\\<^sub>c i \\<times>\\<^sub>f i, eq_pred \\<nat>\\<^sub>c \\<circ>\\<^sub>c id\\<^sub>c \\<nat>\\<^sub>c \\<times>\\<^sub>f id\\<^sub>c \\<nat>\\<^sub>c\\<rangle> \\<circ>\\<^sub>c \\<langle>q, p\\<rangle>  = \\<t>\"\n                using  comp_associative2 by (typecheck_cfuncs, force)\n              then have \"IMPLIES \\<circ>\\<^sub>c \\<langle>(eq_pred X \\<circ>\\<^sub>c (i \\<times>\\<^sub>f i)) \\<circ>\\<^sub>c \\<langle>q, p\\<rangle>, (eq_pred \\<nat>\\<^sub>c \\<circ>\\<^sub>c (id\\<^sub>c \\<nat>\\<^sub>c \\<times>\\<^sub>f id\\<^sub>c \\<nat>\\<^sub>c)) \\<circ>\\<^sub>c \\<langle>q, p\\<rangle>\\<rangle>   = \\<t>\"\n                by (typecheck_cfuncs, metis cfunc_prod_comp)\n              then have \"IMPLIES \\<circ>\\<^sub>c \\<langle>eq_pred X \\<circ>\\<^sub>c (i \\<times>\\<^sub>f i) \\<circ>\\<^sub>c \\<langle>q, p\\<rangle>, eq_pred \\<nat>\\<^sub>c \\<circ>\\<^sub>c (id\\<^sub>c \\<nat>\\<^sub>c \\<times>\\<^sub>f id\\<^sub>c \\<nat>\\<^sub>c) \\<circ>\\<^sub>c \\<langle>q, p\\<rangle> \\<rangle>   = \\<t>\"\n                by (typecheck_cfuncs, smt (verit, ccfv_threshold) cfunc_type_def comp_associative domain_comp)\n              then have \"IMPLIES \\<circ>\\<^sub>c \\<langle>eq_pred X \\<circ>\\<^sub>c  \\<langle>i \\<circ>\\<^sub>c q, i \\<circ>\\<^sub>c p\\<rangle>, eq_pred \\<nat>\\<^sub>c \\<circ>\\<^sub>c  \\<langle>q, p\\<rangle>\\<rangle>   = \\<t>\"\n                using cfunc_cross_prod_comp_cfunc_prod id_cross_prod id_left_unit2 by (typecheck_cfuncs, force)            \n              then have \"(eq_pred X \\<circ>\\<^sub>c \\<langle>i \\<circ>\\<^sub>c q, i \\<circ>\\<^sub>c p\\<rangle> = \\<t>) \\<Longrightarrow> (eq_pred \\<nat>\\<^sub>c \\<circ>\\<^sub>c \\<langle>q, p\\<rangle> = \\<t>)\"\n                by (typecheck_cfuncs, metis IMPLIES_true_false_is_false  eq_pred_iff_eq eq_pred_iff_eq_conv)\n              then show \"(i \\<circ>\\<^sub>c q  =  i \\<circ>\\<^sub>c p) \\<Longrightarrow>  (q = p)\"\n                using eq_pred_iff_eq by (typecheck_cfuncs, auto)\n            qed\n            show \"((FORALL \\<nat>\\<^sub>c \\<circ>\\<^sub>c (IMPLIES \\<circ>\\<^sub>c \\<langle>eq_pred X \\<circ>\\<^sub>c i \\<times>\\<^sub>f i,eq_pred \\<nat>\\<^sub>c \\<circ>\\<^sub>c id\\<^sub>c \\<nat>\\<^sub>c \\<times>\\<^sub>f id\\<^sub>c \\<nat>\\<^sub>c\\<rangle>)\\<^sup>\\<sharp>) \\<circ>\\<^sub>c successor) \\<circ>\\<^sub>c p = \\<t>\"\n            proof - \n              have  \"\\<And> q. q \\<in>\\<^sub>c \\<nat>\\<^sub>c \\<Longrightarrow> (IMPLIES \\<circ>\\<^sub>c \\<langle>eq_pred X \\<circ>\\<^sub>c i \\<times>\\<^sub>f i,  eq_pred \\<nat>\\<^sub>c \\<circ>\\<^sub>c id\\<^sub>c \\<nat>\\<^sub>c \\<times>\\<^sub>f id\\<^sub>c \\<nat>\\<^sub>c\\<rangle> \\<circ>\\<^sub>c \\<langle>id \\<nat>\\<^sub>c, (successor \\<circ>\\<^sub>c p) \\<circ>\\<^sub>c \\<beta>\\<^bsub>\\<nat>\\<^sub>c\\<^esub>\\<rangle>) \\<circ>\\<^sub>c q = \\<t>\"\n              proof  -\n                fix q \n                assume q_type[type_rule]: \"q \\<in>\\<^sub>c \\<nat>\\<^sub>c\"\n                have \"i \\<circ>\\<^sub>c q = i \\<circ>\\<^sub>c (successor \\<circ>\\<^sub>c p) \\<Longrightarrow> q = (successor \\<circ>\\<^sub>c p)\"\n                proof -\n                  assume iq_eq_isp: \"i \\<circ>\\<^sub>c q = i \\<circ>\\<^sub>c successor \\<circ>\\<^sub>c p\"\n  \n                  have \"q = zero \\<or> (\\<exists>r. r \\<in>\\<^sub>c \\<nat>\\<^sub>c \\<and> q = successor \\<circ>\\<^sub>c r)\"\n                    using nonzero_is_succ q_type by blast\n                  then show \"q = successor \\<circ>\\<^sub>c p\"\n                  proof auto\n                    assume q_zero: \"q = zero\"\n                    then have \"i \\<circ>\\<^sub>c zero = i \\<circ>\\<^sub>c successor \\<circ>\\<^sub>c p\"\n                      using iq_eq_isp by auto\n                    then have \"x = m \\<circ>\\<^sub>c i \\<circ>\\<^sub>c p\"\n                      using comp_associative2 i_induct ibase successor_type by (typecheck_cfuncs, auto)\n                    then have False\n                      using comp_type i_type p_type x_def by blast\n                    then show \"zero = successor \\<circ>\\<^sub>c p\"\n                      by auto\n                  next\n                    fix r\n                    assume r_type[type_rule]: \"r \\<in>\\<^sub>c \\<nat>\\<^sub>c\"\n                    assume q_succ: \"q = successor \\<circ>\\<^sub>c r\"\n                    then have \"i \\<circ>\\<^sub>c successor \\<circ>\\<^sub>c r = i \\<circ>\\<^sub>c successor \\<circ>\\<^sub>c p\"\n                      using iq_eq_isp by auto\n                    then have \"m \\<circ>\\<^sub>c i \\<circ>\\<^sub>c r = m \\<circ>\\<^sub>c i \\<circ>\\<^sub>c p\"\n                      using comp_associative2 i_induct successor_type by (typecheck_cfuncs, auto)\n                    then have \"i \\<circ>\\<^sub>c r = i \\<circ>\\<^sub>c p\"\n                      by (metis (mono_tags, lifting) cfunc_type_def codomain_comp i_type m_mono m_type monomorphism_def p_type r_type)\n                    then have \"r = p\"\n                      using ind_hyp r_type by blast\n                    then show \"successor \\<circ>\\<^sub>c r = successor \\<circ>\\<^sub>c p\"\n                      by auto\n                  qed\n                qed\n                then have \"(eq_pred X \\<circ>\\<^sub>c \\<langle> i \\<circ>\\<^sub>c q ,i \\<circ>\\<^sub>c (successor \\<circ>\\<^sub>c p)\\<rangle> = \\<t>) \\<Longrightarrow> (eq_pred \\<nat>\\<^sub>c \\<circ>\\<^sub>c  \\<langle>q , (successor \\<circ>\\<^sub>c p)\\<rangle> = \\<t>) \"\n                  using  eq_pred_iff_eq by (typecheck_cfuncs, blast)\n                then have \"IMPLIES \\<circ>\\<^sub>c \\<langle>eq_pred X \\<circ>\\<^sub>c \\<langle> i \\<circ>\\<^sub>c q ,i \\<circ>\\<^sub>c (successor \\<circ>\\<^sub>c p)\\<rangle>, eq_pred \\<nat>\\<^sub>c \\<circ>\\<^sub>c  \\<langle>q , (successor \\<circ>\\<^sub>c p)\\<rangle> \\<rangle> = \\<t>\"\n                  by (typecheck_cfuncs, metis IMPLIES_false_is_true_false  true_false_only_truth_values) \n                then have \"IMPLIES \\<circ>\\<^sub>c \\<langle>eq_pred X \\<circ>\\<^sub>c (i \\<times>\\<^sub>f i) \\<circ>\\<^sub>c \\<langle>q ,(successor \\<circ>\\<^sub>c p)\\<rangle>, eq_pred \\<nat>\\<^sub>c \\<circ>\\<^sub>c (id\\<^sub>c \\<nat>\\<^sub>c \\<times>\\<^sub>f id\\<^sub>c \\<nat>\\<^sub>c) \\<circ>\\<^sub>c \\<langle>q ,(successor \\<circ>\\<^sub>c p)\\<rangle> \\<rangle> = \\<t>\"\n                  using  cfunc_cross_prod_comp_cfunc_prod id_left_unit2 by (typecheck_cfuncs, auto)\n                then have \"IMPLIES \\<circ>\\<^sub>c \\<langle>eq_pred X \\<circ>\\<^sub>c i \\<times>\\<^sub>f i,eq_pred \\<nat>\\<^sub>c \\<circ>\\<^sub>c id\\<^sub>c \\<nat>\\<^sub>c \\<times>\\<^sub>f id\\<^sub>c \\<nat>\\<^sub>c\\<rangle> \\<circ>\\<^sub>c \\<langle>q ,(successor \\<circ>\\<^sub>c p)\\<rangle> = \\<t>\"\n                  using  cfunc_prod_comp comp_associative2 by (typecheck_cfuncs, force )\n                then have \"IMPLIES \\<circ>\\<^sub>c \\<langle>eq_pred X \\<circ>\\<^sub>c i \\<times>\\<^sub>f i,eq_pred \\<nat>\\<^sub>c \\<circ>\\<^sub>c id\\<^sub>c \\<nat>\\<^sub>c \\<times>\\<^sub>f id\\<^sub>c \\<nat>\\<^sub>c\\<rangle> \\<circ>\\<^sub>c \\<langle>id\\<^sub>c \\<nat>\\<^sub>c,(successor \\<circ>\\<^sub>c p) \\<circ>\\<^sub>c \\<beta>\\<^bsub>\\<nat>\\<^sub>c\\<^esub>\\<rangle> \\<circ>\\<^sub>c q = \\<t>\"\n                  by (metis  cart_prod_extract_left p_type q_type succ_n_type)               \n                then show \"(IMPLIES \\<circ>\\<^sub>c \\<langle>eq_pred X \\<circ>\\<^sub>c i \\<times>\\<^sub>f i,eq_pred \\<nat>\\<^sub>c \\<circ>\\<^sub>c id\\<^sub>c \\<nat>\\<^sub>c \\<times>\\<^sub>f id\\<^sub>c \\<nat>\\<^sub>c\\<rangle> \\<circ>\\<^sub>c \\<langle>id\\<^sub>c \\<nat>\\<^sub>c,(successor \\<circ>\\<^sub>c p) \\<circ>\\<^sub>c \\<beta>\\<^bsub>\\<nat>\\<^sub>c\\<^esub>\\<rangle>) \\<circ>\\<^sub>c q = \\<t>\"\n                  using  comp_associative2 by (typecheck_cfuncs, force)\n              qed\n              then have \"\\<And>q. q \\<in>\\<^sub>c \\<nat>\\<^sub>c \\<Longrightarrow> (IMPLIES \\<circ>\\<^sub>c \\<langle>eq_pred X \\<circ>\\<^sub>c i \\<times>\\<^sub>f i,  eq_pred \\<nat>\\<^sub>c \\<circ>\\<^sub>c id\\<^sub>c \\<nat>\\<^sub>c \\<times>\\<^sub>f id\\<^sub>c \\<nat>\\<^sub>c\\<rangle>) \\<circ>\\<^sub>c \\<langle>id \\<nat>\\<^sub>c, (successor \\<circ>\\<^sub>c p)  \\<circ>\\<^sub>c \\<beta>\\<^bsub>\\<nat>\\<^sub>c\\<^esub>\\<rangle> \\<circ>\\<^sub>c q = \\<t>\"\n                using  comp_associative2 by (typecheck_cfuncs, auto)\n              then have \"FORALL \\<nat>\\<^sub>c \\<circ>\\<^sub>c (((IMPLIES \\<circ>\\<^sub>c \\<langle>eq_pred X \\<circ>\\<^sub>c i \\<times>\\<^sub>f i,  eq_pred \\<nat>\\<^sub>c \\<circ>\\<^sub>c id\\<^sub>c \\<nat>\\<^sub>c \\<times>\\<^sub>f id\\<^sub>c \\<nat>\\<^sub>c\\<rangle>) \\<circ>\\<^sub>c \\<langle>id \\<nat>\\<^sub>c, (successor \\<circ>\\<^sub>c p)  \\<circ>\\<^sub>c \\<beta>\\<^bsub>\\<nat>\\<^sub>c\\<^esub>\\<rangle>) \\<circ>\\<^sub>c left_cart_proj \\<nat>\\<^sub>c one)\\<^sup>\\<sharp> = \\<t>\"\n                using  all_true_implies_FORALL_true comp_associative2 by (typecheck_cfuncs, force)\n              then have \"FORALL \\<nat>\\<^sub>c \\<circ>\\<^sub>c ((IMPLIES \\<circ>\\<^sub>c \\<langle>eq_pred X \\<circ>\\<^sub>c i \\<times>\\<^sub>f i,  eq_pred \\<nat>\\<^sub>c \\<circ>\\<^sub>c id\\<^sub>c \\<nat>\\<^sub>c \\<times>\\<^sub>f id\\<^sub>c \\<nat>\\<^sub>c\\<rangle>) \\<circ>\\<^sub>c \\<langle>id \\<nat>\\<^sub>c, (successor \\<circ>\\<^sub>c p)  \\<circ>\\<^sub>c \\<beta>\\<^bsub>\\<nat>\\<^sub>c\\<^esub>\\<rangle> \\<circ>\\<^sub>c left_cart_proj \\<nat>\\<^sub>c one)\\<^sup>\\<sharp> = \\<t>\"\n                by (typecheck_cfuncs, simp add:  comp_associative2)\n              then have \"FORALL \\<nat>\\<^sub>c \\<circ>\\<^sub>c ((IMPLIES \\<circ>\\<^sub>c \\<langle>eq_pred X \\<circ>\\<^sub>c i \\<times>\\<^sub>f i, eq_pred \\<nat>\\<^sub>c \\<circ>\\<^sub>c id\\<^sub>c \\<nat>\\<^sub>c \\<times>\\<^sub>f id\\<^sub>c \\<nat>\\<^sub>c\\<rangle>) \\<circ>\\<^sub>c (id \\<nat>\\<^sub>c \\<times>\\<^sub>f (successor \\<circ>\\<^sub>c p)))\\<^sup>\\<sharp> = \\<t>\"\n                by (typecheck_cfuncs, metis cfunc_cross_prod_right_terminal_decomp)             \n              then have \"(FORALL \\<nat>\\<^sub>c \\<circ>\\<^sub>c (IMPLIES \\<circ>\\<^sub>c \\<langle>eq_pred X \\<circ>\\<^sub>c i \\<times>\\<^sub>f i,eq_pred \\<nat>\\<^sub>c \\<circ>\\<^sub>c id\\<^sub>c \\<nat>\\<^sub>c \\<times>\\<^sub>f id\\<^sub>c \\<nat>\\<^sub>c\\<rangle>)\\<^sup>\\<sharp>) \\<circ>\\<^sub>c (successor \\<circ>\\<^sub>c p) = \\<t>\"\n                by (typecheck_cfuncs, smt (z3) comp_associative2 sharp_comp)\n              then show \"((FORALL \\<nat>\\<^sub>c \\<circ>\\<^sub>c (IMPLIES \\<circ>\\<^sub>c \\<langle>eq_pred X \\<circ>\\<^sub>c i \\<times>\\<^sub>f i,eq_pred \\<nat>\\<^sub>c \\<circ>\\<^sub>c id\\<^sub>c \\<nat>\\<^sub>c \\<times>\\<^sub>f id\\<^sub>c \\<nat>\\<^sub>c\\<rangle>)\\<^sup>\\<sharp>) \\<circ>\\<^sub>c successor) \\<circ>\\<^sub>c p = \\<t>\"\n                using  comp_associative2 by (typecheck_cfuncs, auto)\n      \n            qed\n          qed\n  \n          show \"((FORALL \\<nat>\\<^sub>c \\<circ>\\<^sub>c (IMPLIES \\<circ>\\<^sub>c \\<langle>eq_pred X \\<circ>\\<^sub>c i \\<times>\\<^sub>f i,eq_pred \\<nat>\\<^sub>c \\<circ>\\<^sub>c id\\<^sub>c \\<nat>\\<^sub>c \\<times>\\<^sub>f id\\<^sub>c \\<nat>\\<^sub>c\\<rangle>)\\<^sup>\\<sharp>) \\<circ>\\<^sub>c successor) \\<circ>\\<^sub>c p\n              = (id\\<^sub>c \\<Omega> \\<circ>\\<^sub>c FORALL \\<nat>\\<^sub>c \\<circ>\\<^sub>c (IMPLIES \\<circ>\\<^sub>c \\<langle>eq_pred X \\<circ>\\<^sub>c i \\<times>\\<^sub>f i,eq_pred \\<nat>\\<^sub>c \\<circ>\\<^sub>c id\\<^sub>c \\<nat>\\<^sub>c \\<times>\\<^sub>f id\\<^sub>c \\<nat>\\<^sub>c\\<rangle>)\\<^sup>\\<sharp>) \\<circ>\\<^sub>c p\"\n            by (typecheck_cfuncs, metis case1 case2 true_false_only_truth_values)\n        qed\n      qed\n  \n    have \"(FORALL \\<nat>\\<^sub>c \\<circ>\\<^sub>c (IMPLIES \\<circ>\\<^sub>c \\<langle>eq_pred X \\<circ>\\<^sub>c (i \\<times>\\<^sub>f i), eq_pred \\<nat>\\<^sub>c \\<circ>\\<^sub>c (id \\<nat>\\<^sub>c \\<times>\\<^sub>f id \\<nat>\\<^sub>c)\\<rangle>)\\<^sup>\\<sharp> = \\<t> \\<circ>\\<^sub>c \\<beta>\\<^bsub>\\<nat>\\<^sub>c\\<^esub>) \\<longrightarrow> (p=q)\"\n    proof(auto) \n      assume \"FORALL \\<nat>\\<^sub>c \\<circ>\\<^sub>c (IMPLIES \\<circ>\\<^sub>c \\<langle>eq_pred X \\<circ>\\<^sub>c (i \\<times>\\<^sub>f i), eq_pred \\<nat>\\<^sub>c \\<circ>\\<^sub>c (id \\<nat>\\<^sub>c \\<times>\\<^sub>f id \\<nat>\\<^sub>c)\\<rangle>)\\<^sup>\\<sharp> = \\<t> \\<circ>\\<^sub>c \\<beta>\\<^bsub>\\<nat>\\<^sub>c\\<^esub>\"\n      then have \"FORALL \\<nat>\\<^sub>c \\<circ>\\<^sub>c \n          (IMPLIES \\<circ>\\<^sub>c \\<langle>eq_pred X \\<circ>\\<^sub>c i \\<times>\\<^sub>f i, eq_pred \\<nat>\\<^sub>c \\<circ>\\<^sub>c id\\<^sub>c \\<nat>\\<^sub>c \\<times>\\<^sub>f id\\<^sub>c \\<nat>\\<^sub>c\\<rangle>)\\<^sup>\\<sharp> \\<circ>\\<^sub>c q = \\<t> \\<circ>\\<^sub>c \\<beta>\\<^bsub>\\<nat>\\<^sub>c\\<^esub> \\<circ>\\<^sub>c q\"\n        by(typecheck_cfuncs, simp add: comp_associative2)\n      then have \"FORALL \\<nat>\\<^sub>c \\<circ>\\<^sub>c\n          (IMPLIES \\<circ>\\<^sub>c \\<langle>eq_pred X \\<circ>\\<^sub>c i \\<times>\\<^sub>f i, eq_pred \\<nat>\\<^sub>c \\<circ>\\<^sub>c id\\<^sub>c \\<nat>\\<^sub>c \\<times>\\<^sub>f id\\<^sub>c \\<nat>\\<^sub>c\\<rangle>)\\<^sup>\\<sharp>  \\<circ>\\<^sub>c q = \\<t>\"\n        by (typecheck_cfuncs, metis  id_right_unit2 id_type one_unique_element terminal_func_comp terminal_func_type)\n      then have \"FORALL \\<nat>\\<^sub>c \\<circ>\\<^sub>c ((IMPLIES \\<circ>\\<^sub>c \\<langle>eq_pred X \\<circ>\\<^sub>c i \\<times>\\<^sub>f i, eq_pred \\<nat>\\<^sub>c \\<circ>\\<^sub>c id\\<^sub>c \\<nat>\\<^sub>c \\<times>\\<^sub>f id\\<^sub>c \\<nat>\\<^sub>c\\<rangle>) \\<circ>\\<^sub>c (id \\<nat>\\<^sub>c \\<times>\\<^sub>f q))\\<^sup>\\<sharp> = \\<t>\"\n        by (typecheck_cfuncs, metis sharp_comp)\n      then have \"FORALL \\<nat>\\<^sub>c \\<circ>\\<^sub>c\n          ((IMPLIES \\<circ>\\<^sub>c \\<langle>eq_pred X \\<circ>\\<^sub>c i \\<times>\\<^sub>f i, eq_pred \\<nat>\\<^sub>c \\<circ>\\<^sub>c id\\<^sub>c \\<nat>\\<^sub>c \\<times>\\<^sub>f id\\<^sub>c \\<nat>\\<^sub>c\\<rangle>) \n              \\<circ>\\<^sub>c \\<langle>id \\<nat>\\<^sub>c, q \\<circ>\\<^sub>c \\<beta>\\<^bsub>\\<nat>\\<^sub>c\\<^esub>\\<rangle> \\<circ>\\<^sub>c left_cart_proj \\<nat>\\<^sub>c one)\\<^sup>\\<sharp> = \\<t>\"\n        by (typecheck_cfuncs, metis cfunc_cross_prod_right_terminal_decomp)\n      then have \"FORALL \\<nat>\\<^sub>c \\<circ>\\<^sub>c \n          ((IMPLIES \\<circ>\\<^sub>c \\<langle>eq_pred X \\<circ>\\<^sub>c i \\<times>\\<^sub>f i, eq_pred \\<nat>\\<^sub>c \\<circ>\\<^sub>c id\\<^sub>c \\<nat>\\<^sub>c \\<times>\\<^sub>f id\\<^sub>c \\<nat>\\<^sub>c\\<rangle>\n              \\<circ>\\<^sub>c \\<langle>id \\<nat>\\<^sub>c, q \\<circ>\\<^sub>c \\<beta>\\<^bsub>\\<nat>\\<^sub>c\\<^esub>\\<rangle>) \\<circ>\\<^sub>c left_cart_proj \\<nat>\\<^sub>c one)\\<^sup>\\<sharp> = \\<t>\"\n        using cfunc_cross_prod_right_terminal_decomp cfunc_type_def comp_associative domain_comp by (typecheck_cfuncs, fastforce)\n      then have \"(IMPLIES \\<circ>\\<^sub>c \\<langle>eq_pred X \\<circ>\\<^sub>c i \\<times>\\<^sub>f i, eq_pred \\<nat>\\<^sub>c \\<circ>\\<^sub>c id\\<^sub>c \\<nat>\\<^sub>c \\<times>\\<^sub>f id\\<^sub>c \\<nat>\\<^sub>c\\<rangle> \\<circ>\\<^sub>c \\<langle>id \\<nat>\\<^sub>c, q \\<circ>\\<^sub>c \\<beta>\\<^bsub>\\<nat>\\<^sub>c\\<^esub>\\<rangle>) \\<circ>\\<^sub>c p = \\<t>\"\n        using FORALL_true_implies_all_true  by (typecheck_cfuncs, blast)\n      then have \"IMPLIES \\<circ>\\<^sub>c \\<langle>eq_pred X \\<circ>\\<^sub>c i \\<times>\\<^sub>f i, eq_pred \\<nat>\\<^sub>c \\<circ>\\<^sub>c id\\<^sub>c \\<nat>\\<^sub>c \\<times>\\<^sub>f id\\<^sub>c \\<nat>\\<^sub>c\\<rangle> \\<circ>\\<^sub>c \\<langle>id \\<nat>\\<^sub>c, q \\<circ>\\<^sub>c \\<beta>\\<^bsub>\\<nat>\\<^sub>c\\<^esub>\\<rangle> \\<circ>\\<^sub>c p = \\<t>\"\n        by (typecheck_cfuncs, smt (verit, ccfv_threshold)  cfunc_type_def comp_associative domain_comp)\n      then have \"IMPLIES \\<circ>\\<^sub>c \\<langle>eq_pred X \\<circ>\\<^sub>c i \\<times>\\<^sub>f i, eq_pred \\<nat>\\<^sub>c \\<circ>\\<^sub>c id\\<^sub>c \\<nat>\\<^sub>c \\<times>\\<^sub>f id\\<^sub>c \\<nat>\\<^sub>c\\<rangle> \\<circ>\\<^sub>c \\<langle>p, q\\<rangle> = \\<t>\"\n        by (typecheck_cfuncs, metis cart_prod_extract_left)\n      then have \"IMPLIES \\<circ>\\<^sub>c \\<langle>(eq_pred X \\<circ>\\<^sub>c (i \\<times>\\<^sub>f i)) \\<circ>\\<^sub>c \\<langle>p, q\\<rangle>, (eq_pred \\<nat>\\<^sub>c \\<circ>\\<^sub>c id\\<^sub>c \\<nat>\\<^sub>c \\<times>\\<^sub>f id\\<^sub>c \\<nat>\\<^sub>c) \\<circ>\\<^sub>c \\<langle>p, q\\<rangle> \\<rangle>  = \\<t>\"\n        using  cfunc_prod_comp by (typecheck_cfuncs, force)\n      then have \"(eq_pred X \\<circ>\\<^sub>c (i \\<times>\\<^sub>f i)) \\<circ>\\<^sub>c \\<langle>p, q\\<rangle> = \\<t> \\<Longrightarrow> (eq_pred \\<nat>\\<^sub>c \\<circ>\\<^sub>c id\\<^sub>c \\<nat>\\<^sub>c \\<times>\\<^sub>f id\\<^sub>c \\<nat>\\<^sub>c) \\<circ>\\<^sub>c \\<langle>p, q\\<rangle> = \\<t>\"\n        by (typecheck_cfuncs, metis IMPLIES_true_false_is_false true_false_only_truth_values)\n      then have \"eq_pred X \\<circ>\\<^sub>c (i \\<times>\\<^sub>f i) \\<circ>\\<^sub>c \\<langle>p, q\\<rangle> = \\<t>   \\<Longrightarrow> eq_pred \\<nat>\\<^sub>c \\<circ>\\<^sub>c (id\\<^sub>c \\<nat>\\<^sub>c \\<times>\\<^sub>f id\\<^sub>c \\<nat>\\<^sub>c) \\<circ>\\<^sub>c \\<langle>p, q\\<rangle> = \\<t>\"\n        by (typecheck_cfuncs, simp add:  comp_associative2)\n      then have \"eq_pred X \\<circ>\\<^sub>c \\<langle>i \\<circ>\\<^sub>c p, i \\<circ>\\<^sub>c q\\<rangle> = \\<t> \\<Longrightarrow> eq_pred \\<nat>\\<^sub>c \\<circ>\\<^sub>c \\<langle>p, q\\<rangle> = \\<t>\"\n        using  cfunc_cross_prod_comp_cfunc_prod id_cross_prod id_left_unit2 by (typecheck_cfuncs, force)\n      then have \"i \\<circ>\\<^sub>c p = i \\<circ>\\<^sub>c q \\<Longrightarrow> p = q\"\n        using  eq_pred_iff_eq by (typecheck_cfuncs, auto)\n      then show \"p = q\"\n        using eqs by auto\n    qed\n\n    then show \"p = q\"\n      using main_result by linarith\n  qed\n  then have \"\\<exists> s. s : X \\<rightarrow> \\<nat>\\<^sub>c \\<and> surjective s\"\n    by (metis \\<open>injective i\\<close> epi_is_surj i_type injective_imp_monomorphism mem_Collect_eq monos_give_epis nonempty_def zero_type)\n  then show False\n    using \\<open>\\<nexists>s. s : X \\<rightarrow> \\<nat>\\<^sub>c \\<and> surjective s\\<close> by auto\n  qed\nqed\n\n\nlemma infinite_greater_than_N:\n  assumes \"is_infinite X\"\n  shows \"\\<nat>\\<^sub>c \\<le>\\<^sub>c X\"\n  by (metis assms epis_give_monos finite_iff_nosurj_to_N is_smaller_than_def not_finite_and_infinite surjective_is_epimorphism)\n\n\n\n\n\n\n(* Definition 2.6.12 *)\ndefinition fixed_point :: \"cfunc \\<Rightarrow> cfunc \\<Rightarrow> bool \" (infix \"is'_fixed'_point'_of\" 50) where \n  \"fixed_point a g = (\\<exists> A. g : A \\<rightarrow> A \\<and> a \\<in>\\<^sub>c A \\<and> g \\<circ>\\<^sub>c a = a)\"\n\nlemma fixed_point_def2: \n  assumes \"g : A \\<rightarrow> A\" \"a \\<in>\\<^sub>c A\"\n  shows \"fixed_point a g = (g \\<circ>\\<^sub>c a = a)\"\n  unfolding fixed_point_def using assms by blast\n  \n(*Definition 2.6.12b*)\ndefinition fixed_point_property :: \"cset \\<Rightarrow> bool\" where\n  \"fixed_point_property A = (\\<forall> g. g : A \\<rightarrow> A \\<longrightarrow> (\\<exists> a . fixed_point a g \\<and> a \\<in>\\<^sub>c A))\"\n\n(*Theorem 2.6.13*)\nlemma Lawveres_fixed_point_theorem:\n  assumes p_type[type_rule]: \"p : X \\<rightarrow> A\\<^bsup>X\\<^esup>\"\n  assumes p_surj: \"surjective p\"\n  shows \"fixed_point_property A\"\nproof(unfold fixed_point_property_def,auto) \n  fix g \n  assume g_type[type_rule]: \"g : A \\<rightarrow> A\"\n  obtain \\<phi> where \\<phi>_def: \"\\<phi> = p\\<^sup>\\<flat>\"\n    by auto\n  then have \\<phi>_type[type_rule]: \"\\<phi> : X \\<times>\\<^sub>c X \\<rightarrow> A\"\n    by (simp add: flat_type p_type)\n  obtain f where f_def: \"f = g \\<circ>\\<^sub>c \\<phi> \\<circ>\\<^sub>c diagonal(X)\"\n    by auto\n  then have f_type[type_rule]:\"f : X \\<rightarrow> A\"\n    using \\<phi>_type comp_type diagonal_type f_def g_type by blast\n  obtain x_f where x_f: \"metafunc f = p \\<circ>\\<^sub>c x_f \\<and> x_f \\<in>\\<^sub>c X\"\n    using assms by (typecheck_cfuncs, metis p_surj surjective_def2)\n  have \"\\<phi>\\<^bsub>(-,x_f)\\<^esub> = f\"\n  proof(rule one_separator[where X = \"X\", where Y = A])\n    show \"\\<phi>\\<^bsub>(-,x_f)\\<^esub> : X \\<rightarrow> A\"\n      using assms by (typecheck_cfuncs, simp add: x_f)\n    show \"f : X \\<rightarrow> A\"\n      by (simp add: f_type)\n    show \"\\<And>x. x \\<in>\\<^sub>c X \\<Longrightarrow> \\<phi>\\<^bsub>(-,x_f)\\<^esub> \\<circ>\\<^sub>c x = f \\<circ>\\<^sub>c x\"\n    proof - \n      fix x \n      assume x_type[type_rule]: \"x \\<in>\\<^sub>c X\"\n      have \"\\<phi>\\<^bsub>(-,x_f)\\<^esub> \\<circ>\\<^sub>c x = \\<phi> \\<circ>\\<^sub>c \\<langle>x, x_f\\<rangle>\"\n        using assms by (typecheck_cfuncs, meson right_param_on_el x_f)\n      also have \"... = ((eval_func A X) \\<circ>\\<^sub>c (id X \\<times>\\<^sub>f p)) \\<circ>\\<^sub>c \\<langle>x, x_f\\<rangle>\"\n        using assms \\<phi>_def inv_transpose_func_def2 by auto\n      also have \"... = (eval_func A X) \\<circ>\\<^sub>c (id X \\<times>\\<^sub>f p) \\<circ>\\<^sub>c \\<langle>x, x_f\\<rangle>\"\n        by (typecheck_cfuncs, metis comp_associative2 x_f)\n      also have \"... = (eval_func A X) \\<circ>\\<^sub>c \\<langle>id X  \\<circ>\\<^sub>c  x, p \\<circ>\\<^sub>c x_f\\<rangle>\"\n        using cfunc_cross_prod_comp_cfunc_prod x_f by (typecheck_cfuncs, force)\n      also have \"... = (eval_func A X) \\<circ>\\<^sub>c \\<langle>x, metafunc f\\<rangle>\"\n        using id_left_unit2 x_f by (typecheck_cfuncs, auto)\n      also have \"... = f \\<circ>\\<^sub>c x\"\n        by (simp add: eval_lemma f_type x_type)\n      then show \"\\<phi>\\<^bsub>(-,x_f)\\<^esub> \\<circ>\\<^sub>c x = f \\<circ>\\<^sub>c x\"\n        by (simp add: calculation)\n    qed\n  qed\n  then have \"\\<phi>\\<^bsub>(-,x_f)\\<^esub> \\<circ>\\<^sub>c x_f = g \\<circ>\\<^sub>c \\<phi> \\<circ>\\<^sub>c diagonal(X) \\<circ>\\<^sub>c x_f\"\n    by (typecheck_cfuncs, smt (z3) cfunc_type_def comp_associative domain_comp f_def x_f)\n  then have \"\\<phi> \\<circ>\\<^sub>c \\<langle>x_f, x_f\\<rangle> = g \\<circ>\\<^sub>c \\<phi> \\<circ>\\<^sub>c \\<langle>x_f, x_f\\<rangle>\"\n    using  diag_on_elements right_param_on_el x_f by (typecheck_cfuncs, auto)\n  then have \"(\\<phi> \\<circ>\\<^sub>c \\<langle>x_f, x_f\\<rangle>) is_fixed_point_of g\"\n    by (metis \\<open>\\<phi>\\<^bsub>(-,x_f)\\<^esub> = f\\<close> \\<open>\\<phi>\\<^bsub>(-,x_f)\\<^esub> \\<circ>\\<^sub>c x_f = g \\<circ>\\<^sub>c \\<phi> \\<circ>\\<^sub>c diagonal X \\<circ>\\<^sub>c x_f\\<close> comp_type diag_on_elements f_type fixed_point_def2 g_type x_f)\n  then show \"\\<exists>a. a is_fixed_point_of g \\<and> a \\<in>\\<^sub>c A\"\n    using fixed_point_def cfunc_type_def g_type by auto\nqed\n\n(*Theorem 2.6.14*)\nlemma Cantors_Negative_Theorem:\n  \"\\<nexists> s. s : X \\<rightarrow> \\<P> X \\<and> surjective(s)\"\nproof(rule ccontr, auto)\n  fix s \n  assume s_type: \"s : X \\<rightarrow> \\<P> X\"\n  assume s_surj: \"surjective s\"\n  then have Omega_has_ffp: \"fixed_point_property \\<Omega>\"\n    using Lawveres_fixed_point_theorem powerset_def s_type by auto\n  have Omega_doesnt_have_ffp: \"\\<not>(fixed_point_property \\<Omega>)\"\n    unfolding fixed_point_property_def\n  proof(unfold fixed_point_def, auto)   \n    have  \"NOT : \\<Omega> \\<rightarrow> \\<Omega> \\<and> (\\<forall>a. (\\<forall>A. a \\<in>\\<^sub>c A \\<longrightarrow> NOT : A \\<rightarrow> A \\<longrightarrow> NOT \\<circ>\\<^sub>c a \\<noteq> a) \\<or> \\<not> a \\<in>\\<^sub>c \\<Omega>)\"\n      by (typecheck_cfuncs, metis AND_complementary AND_idempotent OR_complementary OR_idempotent true_false_distinct)\n    then show \"\\<exists>g. g : \\<Omega> \\<rightarrow> \\<Omega> \\<and> (\\<forall>a. (\\<forall>A. a \\<in>\\<^sub>c A \\<longrightarrow> g : A \\<rightarrow> A \\<longrightarrow> g \\<circ>\\<^sub>c a \\<noteq> a) \\<or> \\<not> a \\<in>\\<^sub>c \\<Omega>)\"\n      by auto\n  qed\n  show False\n    using Omega_doesnt_have_ffp Omega_has_ffp by auto\nqed\n\n\n(* Visit the Cardinality.thy file.  This is already proved there.  I think Cardinality and Countable should be merged*)\nlemma generalized_Cantors_Negative_Theorem:\n  assumes \"\\<Omega> \\<le>\\<^sub>c Y\"\n  shows \"\\<nexists> s. s : X \\<rightarrow> Y\\<^bsup>X\\<^esup> \\<and> surjective(s)\"\nproof(rule ccontr, auto)\n  fix s \n  assume s_type: \"s : X \\<rightarrow> Y\\<^bsup>X\\<^esup>\"\n  assume s_surj: \"surjective s\"\n  obtain m where m_def: \"m : Y\\<^bsup>X\\<^esup> \\<rightarrow> X\" and m_mono: \"monomorphism(m)\"\n    using epis_give_monos s_surj s_type surjective_is_epimorphism by blast\n  have \"\\<Omega>\\<^bsup>X\\<^esup> \\<le>\\<^sub>c Y\\<^bsup>X\\<^esup>\"\n    apply typecheck_cfuncs\n\n\n(*Exercise 2.6.15*)\nlemma Cantors_Positive_Theorem:\n  \"\\<exists>m. m : X \\<rightarrow> \\<Omega>\\<^bsup>X\\<^esup> \\<and> injective m\"\nproof - \n  have eq_pred_sharp_type[type_rule]: \"(eq_pred X)\\<^sup>\\<sharp> : X \\<rightarrow>  \\<Omega>\\<^bsup>X\\<^esup>\"\n    by (typecheck_cfuncs)\n  have \"injective((eq_pred X)\\<^sup>\\<sharp>)\"\n    unfolding injective_def\n  proof(auto)\n    fix x y \n    assume \"x \\<in>\\<^sub>c domain (eq_pred X\\<^sup>\\<sharp>)\" then have x_type[type_rule]: \"x \\<in>\\<^sub>c X\"\n      using cfunc_type_def eq_pred_sharp_type by auto\n    assume \"y \\<in>\\<^sub>c domain (eq_pred X\\<^sup>\\<sharp>)\" then have y_type[type_rule]:\"y \\<in>\\<^sub>c X\"\n      using cfunc_type_def eq_pred_sharp_type by auto\n    assume eq: \"eq_pred X\\<^sup>\\<sharp> \\<circ>\\<^sub>c x = eq_pred X\\<^sup>\\<sharp> \\<circ>\\<^sub>c y\"\n    have \"eq_pred X \\<circ>\\<^sub>c \\<langle>x, x\\<rangle> = eq_pred X \\<circ>\\<^sub>c \\<langle>x, y\\<rangle>\"\n    proof - \n      have \"eq_pred X \\<circ>\\<^sub>c \\<langle>x, x\\<rangle> = ((eval_func \\<Omega> X) \\<circ>\\<^sub>c (id X \\<times>\\<^sub>f (eq_pred X\\<^sup>\\<sharp>)) ) \\<circ>\\<^sub>c \\<langle>x, x\\<rangle>\"\n        using transpose_func_def by (typecheck_cfuncs, presburger)\n      also have \"... = (eval_func \\<Omega> X) \\<circ>\\<^sub>c (id X \\<times>\\<^sub>f (eq_pred X\\<^sup>\\<sharp>)) \\<circ>\\<^sub>c \\<langle>x, x\\<rangle>\"\n        by (typecheck_cfuncs, simp add: comp_associative2)\n      also have \"... = (eval_func \\<Omega> X) \\<circ>\\<^sub>c \\<langle>id X \\<circ>\\<^sub>c x, (eq_pred X\\<^sup>\\<sharp>) \\<circ>\\<^sub>c x\\<rangle>\"\n        using cfunc_cross_prod_comp_cfunc_prod by (typecheck_cfuncs, force)\n      also have \"... = (eval_func \\<Omega> X) \\<circ>\\<^sub>c \\<langle>id X \\<circ>\\<^sub>c x, (eq_pred X\\<^sup>\\<sharp>) \\<circ>\\<^sub>c y\\<rangle>\"\n        by (simp add: eq)\n      also have \"... = (eval_func \\<Omega> X) \\<circ>\\<^sub>c (id X \\<times>\\<^sub>f (eq_pred X\\<^sup>\\<sharp>)) \\<circ>\\<^sub>c \\<langle>x, y\\<rangle>\"\n        by (typecheck_cfuncs, simp add: cfunc_cross_prod_comp_cfunc_prod)\n      also have \"... = ((eval_func \\<Omega> X) \\<circ>\\<^sub>c (id X \\<times>\\<^sub>f (eq_pred X\\<^sup>\\<sharp>)) ) \\<circ>\\<^sub>c \\<langle>x, y\\<rangle>\"\n        using comp_associative2 by (typecheck_cfuncs, blast)\n      also have \"... = eq_pred X \\<circ>\\<^sub>c \\<langle>x, y\\<rangle>\"\n        using transpose_func_def by (typecheck_cfuncs, presburger)\n      then show ?thesis\n        by (simp add: calculation)\n    qed\n    then show \"x = y\"\n      by (metis eq_pred_iff_eq x_type y_type)\n  qed\n  then show \"\\<exists>m. m : X \\<rightarrow> \\<Omega>\\<^bsup>X\\<^esup> \\<and> injective m\"\n    using eq_pred_sharp_type injective_imp_monomorphism by blast\nqed\n\n\n(*Corollary 2.6.15*)\n(*This is only a note: For any set X, the set \\<P>X of its subsets is strictly larger than X*)\n\n\n\n\n\n\nend", "meta": {"author": "jameseb7", "repo": "Isabelle-ETCS", "sha": "ae81dc674faf7cca62b30ac53888b3d319160849", "save_path": "github-repos/isabelle/jameseb7-Isabelle-ETCS", "path": "github-repos/isabelle/jameseb7-Isabelle-ETCS/Isabelle-ETCS-ae81dc674faf7cca62b30ac53888b3d319160849/Countable.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8824278633625322, "lm_q2_score": 0.8175744739711883, "lm_q1q2_score": 0.7214504962061419}}
{"text": "theory Chapter12_3\nimports \"HOL-IMP.Hoare_Sound_Complete\"\nbegin\n\ntext\\<open>\n\\exercise\nProve\n\\<close>\n\nlemma \"\\<Turnstile> {P} c {Q} \\<longleftrightarrow> (\\<forall>s. P s \\<longrightarrow> wp c Q s)\"\n    unfolding hoare_valid_def wp_def by auto\n\ntext\\<open>\n\\endexercise\n\n\\begin{exercise}\nReplace the assignment command with a new command \\mbox{@{term\"Do f\"}} where\n@{text \"f ::\"} @{typ \"state \\<Rightarrow> state\"} can be an arbitrary state transformer.\nUpdate the big-step semantics, Hoare logic and the soundness and completeness proofs.\n\\end{exercise}\n\\<close>\ntext \\<open>\n\\exercise\nWhich of the following rules are correct? Proof or counterexample!\n\\<close>\n\nlemma \"\\<lbrakk>\\<turnstile> {P} c {Q};  \\<turnstile> {P'} c {Q'}\\<rbrakk> \\<Longrightarrow>\n  \\<turnstile> {\\<lambda>s. P s \\<or> P' s} c {\\<lambda>s. Q s \\<or> Q' s}\"\nproof -\n  assume \"\\<turnstile> {P} c {Q}\"\n  then have \"\\<Turnstile> {P} c {Q}\" by (rule hoare_sound)\n  moreover assume \"\\<turnstile> {P'} c {Q'}\"\n  then have \"\\<Turnstile> {P'} c {Q'}\" by (rule hoare_sound)\n  ultimately have \"\\<Turnstile> {\\<lambda>s. P s \\<or> P' s} c {\\<lambda>s. Q s \\<or> Q' s}\"\n    unfolding hoare_valid_def by blast\n  then show ?thesis by (rule hoare_complete)\nqed\n\nlemma \"\\<lbrakk>\\<turnstile> {P} c {Q};  \\<turnstile> {P'} c {Q'}\\<rbrakk> \\<Longrightarrow>\n  \\<turnstile> {\\<lambda>s. P s \\<and> P' s} c {\\<lambda>s. Q s \\<and> Q' s}\"\nproof -\n  assume \"\\<turnstile> {P} c {Q}\"\n  then have \"\\<Turnstile> {P} c {Q}\" by (rule hoare_sound)\n  moreover assume \"\\<turnstile> {P'} c {Q'}\"\n  then have \"\\<Turnstile> {P'} c {Q'}\" by (rule hoare_sound)\n  ultimately have \"\\<Turnstile> {\\<lambda>s. P s \\<and> P' s} c {\\<lambda>s. Q s \\<and> Q' s}\"\n    unfolding hoare_valid_def by blast\n  then show ?thesis by (rule hoare_complete)\nqed\n\nlemma \"\\<exists>P Q P' Q' c. \\<turnstile> {P} c {Q} \\<and>  \\<turnstile> {P'} c {Q'} \\<and> \\<not> \\<turnstile> {\\<lambda>s. P s \\<longrightarrow> P' s} c {\\<lambda>s. Q s \\<longrightarrow> Q' s}\"\nproof -\n  let ?P = \"\\<lambda>s::state. s ''x'' = 1\"\n  let ?Q = \"\\<lambda>s::state. True\"\n  have \"\\<turnstile> {?P} SKIP {?P}\" (is ?P1) by (rule Skip)\n  moreover from this have \"\\<turnstile> {?P} SKIP {?Q}\" (is ?P2) by (rule weaken_post, blast)\n  moreover have \"\\<not> \\<turnstile> {\\<lambda>s. ?P s \\<longrightarrow> ?P s} SKIP {\\<lambda>s. ?Q s \\<longrightarrow> ?P s}\" (is ?P3)\n  proof\n    assume \"\\<turnstile> {\\<lambda>s. ?P s \\<longrightarrow> ?P s} SKIP {\\<lambda>s. ?Q s \\<longrightarrow> ?P s}\"\n    then have \"\\<Turnstile> {\\<lambda>s. ?P s \\<longrightarrow> ?P s} SKIP {\\<lambda>s. ?Q s \\<longrightarrow> ?P s}\" by (rule hoare_sound)\n    then have H1: \"\\<And>s t. \\<lbrakk>(?P s \\<longrightarrow> ?P s); (SKIP, s) \\<Rightarrow> t\\<rbrakk> \\<Longrightarrow> (?Q t \\<longrightarrow> ?P t)\"\n      unfolding hoare_valid_def by (intro allI impI, blast)\n    have H2: \"?P <> \\<longrightarrow> ?P <>\" unfolding null_state_def by blast\n    have H3: \"(SKIP, <>) \\<Rightarrow> <>\" by auto\n    from H1 [of \"<>\", OF H2 H3] show False unfolding null_state_def by simp\n  qed\n  ultimately show ?thesis by blast\nqed\ntext\\<open>\n\\endexercise\n\n\\begin{exercise}\nBased on Exercise~\\ref{exe:IMP:OR}, extend Hoare logic and the soundness and completeness proofs\nwith nondeterministic choice.\n\\end{exercise}\n\n\\begin{exercise}\nBased on Exercise~\\ref{exe:IMP:REPEAT}, extend Hoare logic and the soundness and completeness proofs\nwith a @{text REPEAT} loop. Hint: think of @{text\"REPEAT c UNTIL b\"} as\nequivalent to \\noquotes{@{term[source]\"c;; WHILE Not b DO c\"}}.\n\\end{exercise}\n\n\\exercise\\label{exe:sp}\nThe dual of the weakest precondition is the \\concept{strongest postcondition}\n@{text sp}. Define @{text sp} in analogy with @{const wp} via the big-step semantics:\n\\<close>\n\ndefinition sp :: \"com \\<Rightarrow> assn \\<Rightarrow> assn\" where\n  \"sp c P = (\\<lambda>t. \\<exists>s. P s \\<and> (c, s) \\<Rightarrow> t)\"\n\ntext\\<open> Prove that @{const sp} really is the strongest postcondition: \\<close>\n\nlemma \"(\\<Turnstile> {P} c {Q}) \\<longleftrightarrow> (\\<forall>s. sp c P s \\<longrightarrow> Q s)\"\n  unfolding hoare_valid_def sp_def by blast\n\ntext\\<open>\nIn analogy with the derived equations for @{const wp} given in the text,\ngive and prove equations for ``calculating'' @{const sp} for three constructs:\n@{prop\"sp (x ::= a) P = Q\\<^sub>1\"}, @{prop\"sp (c\\<^sub>1;;c\\<^sub>2) P = Q\\<^sub>2\"}, and\n@{prop\"sp (IF b THEN c\\<^sub>1 ELSE c\\<^sub>2) P = Q\\<^sub>3\"}.\nThe @{text Q\\<^sub>i} must not involve the semantics and may only call\n@{const sp} recursively on the subcommands @{text c\\<^sub>i}.\nHint: @{text Q\\<^sub>1} requires an existential quantifier.\n\\<close>\n\nlemma sp_Ass [simp]: \"sp (x::=a) P = (\\<lambda>s. \\<exists> x'. P (s(x := x')) \\<and> s x = aval a (s(x := x')))\"\n  unfolding sp_def\nproof (rule ext, auto)\n  fix s :: state\n  have Heq: \"s(x := s x) = s\" by auto\n  assume \"P s\"\n  with Heq have \"P (s(x := s x)) \\<and> aval a s = aval a (s(x := s x))\" by auto\n  then show \"\\<exists>x'. P (s(x := x')) \\<and> aval a s = aval a (s(x := x'))\" by blast\nnext\n  fix t :: state and x'\n  let ?s = \"t(x := x')\"\n  assume H: \"P (t(x := x'))\" \"t x = aval a ?s\"\n  have Heq: \"t(x := t x) = t\" by auto\n  have \"(x ::= a, ?s) \\<Rightarrow> ?s(x := aval a ?s)\" by (rule big_step.Assign)\n  with H(2) Heq have \"(x ::= a, ?s) \\<Rightarrow> t\" by simp\n  with H have \"P ?s \\<and> (x ::= a, ?s) \\<Rightarrow> t\" by simp\n  from exI [of \"\\<lambda>s. P s \\<and> (x ::= a, s) \\<Rightarrow> t\", OF this]\n  show \"\\<exists>s. P s \\<and> (x ::= a, s) \\<Rightarrow> t\" .\nqed\n\nlemma sp_Seq [simp]: \"sp (c\\<^sub>1;; c\\<^sub>2) P = sp c\\<^sub>2 (sp c\\<^sub>1 P)\"\n  unfolding sp_def by (rule ext) auto\n\nlemma sp_If [simp]: \"sp (IF b THEN c\\<^sub>1 ELSE c\\<^sub>2) P =\n  (\\<lambda>t. sp c\\<^sub>1 (\\<lambda>s. P s \\<and> bval b s) t \\<or> sp c\\<^sub>2 (\\<lambda>s. P s \\<and> \\<not>bval b s) t)\"\n  unfolding sp_def by (rule ext) auto\n\ntext\\<open>\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/Chapter12_3.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8175744761936437, "lm_q2_score": 0.8824278602705731, "lm_q1q2_score": 0.7214504956393916}}
{"text": "(*\n    ex.thy,v 1.1 2016/09/29 17:37:37 jdf Exp\n    Original Author: Tjark Weber\n    Updated to Isabelle 2016 and additions by Jacques Fleuriot\n\n    File completed and renamed to: propositional_logic.thy\n    Name: Athiya Deviyani\n    UUN: S1709906\n*)\n\nsection {* Propositional Logic *}\n\ntheory propositional_logic imports Main begin \n\ntext {* In this exercise, we will prove some lemmas of propositional\nlogic with the aid of a calculus of natural deduction.\n\nFor the proofs, you may only use\n\nnotI: (?P \\<Longrightarrow> False) \\<Longrightarrow> \\<not> ?P\nnotE: \\<lbrakk>\\<not> ?P; ?P\\<rbrakk> \\<Longrightarrow> ?R\nconjI: \\<lbrakk>?P; ?Q\\<rbrakk> \\<Longrightarrow> ?P \\<and> ?Q\nconjE: \\<lbrakk>?P \\<and> ?Q; \\<lbrakk>?P; ?Q\\<rbrakk> \\<Longrightarrow> ?R\\<rbrakk> \\<Longrightarrow> ?R\ndisjI1:?P \\<Longrightarrow> ?P \\<or> ?Q\ndisjI2: ?Q \\<Longrightarrow> ?P \\<or> ?Q\ndisjE: \\<lbrakk>?P \\<or> ?Q; ?P \\<Longrightarrow> ?R; ?Q \\<Longrightarrow> ?R\\<rbrakk> \\<Longrightarrow> ?R\nimpI: (?P \\<Longrightarrow> ?Q) \\<Longrightarrow> ?P \\<longrightarrow> ?Q\nimpE:\\<lbrakk>?P \\<longrightarrow> ?Q; ?P; ?Q \\<Longrightarrow> ?R\\<rbrakk> \\<Longrightarrow> ?R\nmp: \\<lbrakk>?P \\<longrightarrow> ?Q; ?P\\<rbrakk> \\<Longrightarrow> ?Q\niffI:\\<lbrakk>?P \\<Longrightarrow> ?Q; ?Q \\<Longrightarrow> ?P\\<rbrakk> \\<Longrightarrow> ?P = ?Q\niffE:\\<lbrakk>?P = ?Q; \\<lbrakk>?P \\<longrightarrow> ?Q; ?Q \\<longrightarrow> ?P\\<rbrakk> \\<Longrightarrow> ?R\\<rbrakk> \\<Longrightarrow> ?R\nclassical: (\\<not> ?P \\<Longrightarrow> ?P) \\<Longrightarrow> ?P\n\n\nand the proof methods rule, erule and assumption.\n\\end{itemize}\n\nProve:\n*}\n  \n\nlemma I: \"A \\<longrightarrow> A\"\n  apply (rule impI)\n  apply assumption\n  done\n\n\nlemma \"A \\<and> B \\<longrightarrow> B \\<and> A\"\n  apply (rule impI)\n  apply (erule conjE)\n  apply (rule conjI)\n   apply assumption\n  apply assumption\n\nlemma \"(A \\<and> B) \\<longrightarrow> (A \\<or> B)\"\n  apply (rule impI)\n  apply (erule conjE)\n  apply (rule disjI1)\n  apply assumption\n\n\nlemma \"((A \\<or> B) \\<or> C) \\<longrightarrow> A \\<or> (B \\<or> C)\"\n  apply (rule impI)\n  apply (erule disjE)\n   apply (erule disjE)\n    apply (rule disjI1)\n    apply assumption\n   apply (rule disjI2)\n   apply (rule disjI1)\n  apply assumption\n  apply(rule disjI2)\n  apply (rule disjI2)\n  apply assumption \n\n\n\nlemma \"(A \\<or> A) = (A \\<and> A)\"\n  apply (rule iffI)\n   apply (erule disjE)\n    apply (rule conjI)\n     apply assumption\n    apply assumption\n   apply (rule conjI)\n    apply assumption\n  apply assumption\n  apply (erule conjE)\n  apply (rule disjI1)\n  apply assumption\n\nlemma S: \"(A \\<longrightarrow> B \\<longrightarrow> C) \\<longrightarrow> (A \\<longrightarrow> B) \\<longrightarrow> A \\<longrightarrow> C\"\n  apply (rule impI)+\n  apply (erule impE)\n   apply assumption\n  apply (erule impE)\n    apply assumption\n  apply (erule impE)\n   apply assumption\n  apply assumption\n\nlemma \"(A \\<longrightarrow> B) \\<longrightarrow> (B \\<longrightarrow> C) \\<longrightarrow> A \\<longrightarrow> C\"\n  apply (rule impI)+\n  apply (erule impE)\n   apply assumption\n  apply (erule impE)\n   apply assumption\n  apply assumption\n\nlemma \"\\<not> \\<not> A \\<longrightarrow> A\"\n  apply (rule impI)\n  apply (rule classical)\n  apply (erule notE)\n  apply assumption\n\nlemma \"A \\<longrightarrow> \\<not> \\<not> A\"\n  apply (rule impI)\n  apply (rule notI)\n  apply (erule notE)\n  apply assumption\n\n\nlemma \"(\\<not> A \\<longrightarrow> B) \\<longrightarrow> (\\<not> B \\<longrightarrow> A)\"\n  apply (rule impI)+\n  apply (rule classical)\n  apply (erule notE)\n  apply (erule impE)\n   apply assumption\n  apply assumption\n\nlemma \"((A \\<longrightarrow> B) \\<longrightarrow> A) \\<longrightarrow> A\"  \n  apply (rule impI)\n  apply (rule classical)\n  apply (erule impE)\n  apply (rule impI)\n  apply (erule notE)\n   apply (assumption)\n  apply (erule notE)\n  apply assumption\n\nlemma \"A \\<or> \\<not> A\"\n  apply (rule classical)\n  apply (rule disjI2)\n  apply (rule notI)\n  apply (erule notE)\n  apply (rule disjI1)      \n  apply assumption        \n\n                                             \nlemma \"(\\<not> (A \\<and> B)) = (\\<not> A \\<or> \\<not> B)\"\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  apply (rule classical)\n  apply (erule notE)\n  apply (erule disjE)\n   apply (rule notI)\n  apply (erule notE)\n   apply (erule conjE)\n   apply assumption\n  apply (rule notI)\n  apply (erule conjE)\n  apply (erule notE)\n  apply assumption\n\nend \n\n", "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/propositional_logic.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8354835289107309, "lm_q2_score": 0.8633916205190225, "lm_q1q2_score": 0.7213494779431875}}
{"text": "theory Chapter5\nimports 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\ninductive iter :: \"('a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> nat \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> bool\" for r where\niter_0: \"iter r 0 x x\" |\niter_Suc: \"r x y \\<Longrightarrow> iter r n y z \\<Longrightarrow> iter r (Suc n) x z\"\n\ntext \\<open>\n\\section*{Chapter 5}\n\n\\exercise\nGive a readable, structured proof of the following lemma:\n\\<close>\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 -\n  have \"T x y \\<or> T y x\" using T by blast\n  thus \"T x y\"\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 blast\n    hence \"x = y\" using A and `A x y` by blast\n    thus \"T x y\" using `T y x` by blast\n  qed\nqed\n\ntext\\<open>\nEach step should use at most one of the assumptions @{text T}, @{text A}\nor @{text TA}.\n\\endexercise\n\n\\exercise\nGive a readable, structured proof of the following lemma:\n\\<close>\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 -\n  have \"even (length xs) \\<or> odd (length xs)\" by simp\n  thus ?thesis\n  proof\n    assume \"even (length xs)\"\n    hence \"\\<exists> k. k + k = length xs\" by arith\n    then obtain k where Hk: \"k + k = length xs\" by auto\n    let ?ys = \"take k xs\"\n    let ?zs = \"drop k xs\"\n    have \"xs = ?ys @ ?zs\" (is ?Heq) by simp\n    moreover from Hk have \"length ?ys = length ?zs\" (is ?Hlen) by auto\n    ultimately have \"?Heq \\<and> ?Hlen\" by simp\n    thus ?thesis by blast\n  next\n    assume \"odd (length xs)\"\n    hence \"\\<exists> k. (k + 1) + k = length xs\" by arith\n    then obtain k where Hk: \"(k + 1) + k = length xs\" by auto\n    let ?ys = \"take (k + 1) xs\"\n    let ?zs = \"drop (k + 1) xs\"\n    have \"xs = ?ys @ ?zs\" (is ?Heq) by simp\n    moreover from Hk have \"length ?ys = length ?zs + 1\" (is ?Hlen) by auto\n    ultimately have \"?Heq \\<and> ?Hlen\" by simp\n    thus ?thesis by blast\n  qed\nqed\n\ntext\\<open>\nHint: There are predefined functions @{const take} and {const drop} of type\n@{typ \"nat \\<Rightarrow> 'a list \\<Rightarrow> 'a list\"} such that @{text\"take k [x\\<^sub>1,\\<dots>] = [x\\<^sub>1,\\<dots>,x\\<^sub>k]\"}\nand @{text\"drop k [x\\<^sub>1,\\<dots>] = [x\\<^bsub>k+1\\<^esub>,\\<dots>]\"}. Let sledgehammer find and apply\nthe relevant @{const take} and @{const drop} lemmas for you.\n\\endexercise\n\n\\exercise\nGive a structured proof by rule inversion:\n\\<close>\ninductive ev :: \"nat \\<Rightarrow> bool\" where\nev0: \"ev 0\" |\nevSS: \"ev n \\<Longrightarrow> ev(Suc(Suc n))\"\n\nlemma assumes a: \"ev(Suc(Suc n))\" shows \"ev n\"\nproof (cases \"Suc (Suc n)\" rule: ev.cases)\n  case ev0\n  from a show ?case by assumption\nnext\n  case evSS\n  assume \"ev n\"\n  then show ?thesis by assumption\nqed\n\ntext\\<open>\n\\exercise\nGive a structured proof by rule inversions:\n\\<close>\n\nlemma \"\\<not> ev(Suc(Suc(Suc 0)))\" (is \"\\<not> ?P\")\nproof\n  assume \"?P\"\n  thus False\n  proof (cases \"Suc (Suc (Suc 0))\")\n    case evSS\n    thus False by cases\n  qed\nqed\n\ntext\\<open>\nIf there are no cases to be proved you can close\na proof immediateley with \\isacom{qed}.\n\\endexercise\n\n\\exercise\nRecall predicate @{const star} from Section 4.5 and @{const iter}\nfrom Exercise~\\ref{exe:iter}.\n\\<close>\n\nlemma \"iter r n x y \\<Longrightarrow> star r x y\"\nproof (induct rule: iter.induct)\n  case (iter_0 x)\n  show ?case by (simp add: refl)\nnext\n  case (iter_Suc x y n z)\n  thus ?case by (simp add: step)\nqed\n\ntext\\<open>\nProve this lemma in a structured style, do not just sledgehammer each case of the\nrequired induction.\n\\endexercise\n\n\\exercise\nDefine a recursive function\n\\<close>\n\nfun elems :: \"'a list \\<Rightarrow> 'a set\" where\n  \"elems [] = {}\" |\n  \"elems (x # xs) = {x} \\<union> elems xs\"\n\ntext\\<open> that collects all elements of a list into a set. Prove \\<close>\n\nlemma \"x \\<in> elems xs \\<Longrightarrow> \\<exists>ys zs. xs = ys @ x # zs \\<and> x \\<notin> elems ys\"\nproof (induct xs)\n  case Nil\n  hence False by simp\n  thus ?case by simp\nnext\n  case (Cons a xs)\n  hence HxUn: \"x \\<in> {a} \\<union> elems xs\" by simp\n  consider (xa) \"x \\<in> {a}\" | (nxa) \"x \\<notin> {a}\" by blast\n  thus ?case\n  proof cases\n    case xa\n    hence \"x = a\" ..\n    hence \"a # xs = x # xs\" by simp\n    also have \"\\<dots> = [] @ x # xs\" by simp\n    finally have \"a # xs = [] @ x # xs\" by simp\n    moreover have \"x \\<notin> {}\" by simp\n    hence \"x \\<notin> elems []\" by simp\n    ultimately show ?thesis by blast\n  next\n    case nxa\n    from HxUn\n    show ?thesis\n    proof\n      assume \"x \\<in> {a}\"\n      thus ?thesis using nxa by simp\n    next\n      assume \"x \\<in> elems xs\"\n      then obtain ys zs where \"xs = ys @ x # zs\" and \"x \\<notin> elems ys\" using Cons.hyps by blast\n      hence \"a # xs = (a # ys) @ x # zs\" and \"x \\<notin> elems ys\" by auto\n      hence \"a # xs = (a # ys) @ x # zs\" and \"x \\<notin> elems (a # ys)\" using nxa by auto\n      thus ?thesis by blast\n    qed\n  qed\nqed\n\ntext\\<open>\n\\endexercise\n\n\\exercise\nExtend Exercise~\\ref{exe:cfg} with a function that checks if some\n\\mbox{@{text \"alpha list\"}} is a balanced\nstring of parentheses. More precisely, define a recursive function \\<close>\n\ndatatype alpha = alphaa | alphab\n\ninductive S :: \"alpha list \\<Rightarrow> bool\" where\nS_\\<epsilon>: \"S []\" |\nS_aSb: \"S w \\<Longrightarrow> S (alphaa # w @ [alphab])\" |\nS_SS: \"\\<lbrakk> S v; S w \\<rbrakk> \\<Longrightarrow> S (v @ w)\"\n\nfun balanced :: \"nat \\<Rightarrow> alpha list \\<Rightarrow> bool\" where\n  \"balanced 0 [] = True\" |\n  \"balanced (Suc _) [] = False\" | (* too many a's *)\n  \"balanced n (alphaa # as) = balanced (Suc n) as\" |\n  \"balanced 0 (alphab # as) = False\" | (* too many b's *)\n  \"balanced (Suc n) (alphab # as) = balanced n as\"\n\ntext\\<open> such that @{term\"balanced n w\"}\nis true iff (informally) @{text\"a\\<^sup>n @ w \\<in> S\"}. Formally, prove \\<close>\n\nlemma balanced_r: \"balanced n as \\<Longrightarrow> balanced (Suc n) (as @ [alphab])\"\nproof (induction n as rule: balanced.induct)\n  case 1\n  thus ?case by simp\nnext\n  case (2 uu)\n  thus ?case by simp\nnext\n  case (3 n as)\n  from 3(2) have \"balanced (Suc n) as\" by simp\n  thus ?case using 3(1) by simp\nnext\n  case (4 as)\n  then show ?case by simp\nnext\n  case (5 n as)\n  from 5(2) have \"balanced n as\" by simp\n  thus ?case using 5(1) by simp\nqed\n\nlemma balanced_app: \"\\<lbrakk>balanced m as; balanced n bs\\<rbrakk> \\<Longrightarrow> balanced (m + n) (as @ bs)\"\nproof (induct m as arbitrary: n bs rule: balanced.induct)\n  case 1\n  then show ?case by simp\nnext\n  case (2 uu)\n  then show ?case by simp\nnext\n  case (3 nn as)\n  from 3(2) have \"balanced (Suc nn) as\" by simp\n  with 3(1, 3) have \"balanced (Suc nn + n) (as @ bs)\" by simp\n  hence \"balanced (Suc (nn + n)) (as @ bs)\" by simp\n  thus ?case by simp\nnext\n  case (4 as)\n  then show ?case by simp\nnext\n  case (5 nn as)\n  from 5(2) have \"balanced nn as\" by simp\n  with 5(1, 3) have \"balanced (nn + n) (as @ bs)\" by simp\n  hence \"balanced (Suc (nn + n)) (alphab # as @ bs)\" by simp\n  thus ?case by simp\nqed\n\nlemma S_ends: \"S w \\<Longrightarrow> w = [] \\<or> (\\<exists> v. w = alphaa # v @ [alphab])\"\nproof (induct w rule: S.induct)\n  case S_\\<epsilon>\n  have \"[] = []\" by simp\n  thus ?case by blast\nnext\n  case (S_aSb w)\n  have \"alphaa # w @ [alphab] = alphaa # w @ [alphab]\" by simp\n  thus ?case by blast\nnext\n  case (S_SS v w)\n  from S_SS(2) show ?case\n  proof\n    assume Hv: \"v = []\"\n    from S_SS(4) show ?thesis\n    proof\n      assume \"w = []\"\n      with Hv have \"v @ w = []\" by simp\n      thus ?thesis by blast\n    next\n      assume \"\\<exists>u. w = alphaa # u @ [alphab]\"\n      then obtain u where \"w = alphaa # u @ [alphab]\" ..\n      with Hv have \"v @ w = alphaa # u @ [alphab]\" by simp\n      thus ?thesis by blast\n    qed\n  next\n    assume \"\\<exists>u. v = alphaa # u @ [alphab]\"\n    then obtain n where Hv: \"v = alphaa # n @ [alphab]\" ..\n    from S_SS(4) show ?thesis\n    proof\n      assume \"w = []\"\n      with Hv have \"v @ w = alphaa # n @ [alphab]\" by simp\n      thus ?thesis by blast\n    next\n      assume \"\\<exists>u. w = alphaa # u @ [alphab]\"\n      then obtain m where \"w = alphaa # m @ [alphab]\" ..\n      with Hv have \"v @ w = alphaa # n @ [alphab] @ alphaa # m @ [alphab]\" by simp\n      hence \"v @ w = alphaa # (n @ [alphab] @ alphaa # m) @ [alphab]\" by simp\n      thus ?thesis by blast\n    qed\n  qed\nqed\n\nlemma S_replicate: \"\\<lbrakk>S (alphaa # v); v @ w = replicate n alphaa @ x\\<rbrakk> \\<Longrightarrow> \\<exists> u. v = replicate n alphaa @ u\"\nproof -\n  assume Hvw: \"v @ w = replicate n alphaa @ x\"\n  assume Sav: \"S (alphaa # v)\"\n  hence \"\\<exists> vv. alphaa # v = alphaa # vv @ [alphab]\"\n  proof -\n    assume \"S (alphaa # v)\"\n    with S_ends have \"alphaa # v = [] \\<or> (\\<exists> vv. alphaa # v = alphaa # vv @ [alphab])\" by auto\n    thus \"\\<exists>vv. alphaa # v = alphaa # vv @ [alphab]\"\n    proof\n      assume \"alphaa # v = []\"\n      thus ?thesis by simp\n    next\n      assume \"\\<exists>vv. alphaa # v = alphaa # vv @ [alphab]\"\n      thus ?thesis by simp\n    qed\n  qed\n  then obtain vv where \"alphaa # v = alphaa # vv @ [alphab]\" ..\n  hence Hv: \"v = vv @ [alphab]\" by simp\n  hence Hvvw: \"vv @ [alphab] @ w = replicate n alphaa @ x\" using Hvw by simp\n  hence \"\\<exists> xx. vv @ [alphab] = replicate n alphaa @ xx\"\n  proof (induct n arbitrary: x)\n    case 0\n    have \"vv @ [alphab] = replicate 0 alphaa @ vv @ [alphab]\" by simp\n    thus ?case by simp\n  next\n    case (Suc n)\n    from Suc(2) have Suc2s: \"vv @ [alphab] @ w = replicate n alphaa @ alphaa # x\" by (simp add: replicate_app_Cons_same)\n    hence \"\\<exists>xx. vv @ [alphab] = replicate n alphaa @ xx\" using Suc(1) by simp\n    then obtain xx where Hxx1: \"vv @ [alphab] = replicate n alphaa @ xx\" ..\n    hence \"\\<exists> xl. vv @ [alphab] = replicate n alphaa @ xl @ [alphab]\"\n      by (metis alpha.distinct(1) append_butlast_last_id empty_replicate last_append last_replicate last_snoc self_append_conv2)\n    then obtain xl where Hvvb: \"vv @ [alphab] = replicate n alphaa @ xl @ [alphab]\" ..\n    hence Hxl1: \"vv = replicate n alphaa @ xl\" by simp\n    with Suc2s have \"replicate n alphaa @ xl @ [alphab] @ w = replicate n alphaa @ alphaa # x\" by simp\n    hence Hxx: \"xl @ [alphab] @ w = alphaa # x\" by simp\n    hence \"\\<exists> xlr. xl = alphaa # xlr\"\n      by (metis alpha.distinct(1) append_eq_Cons_conv list.sel(1))\n    then obtain xlr where \"xl = alphaa # xlr\" ..\n    with Hvvb have \"vv @ [alphab] = replicate n alphaa @ alphaa # xlr @ [alphab]\" by simp\n    hence \"vv @ [alphab] = replicate (Suc n) alphaa @ xlr @ [alphab]\" by (simp add: replicate_app_Cons_same)\n    then show ?case by blast\n  qed\n  thus ?thesis using Hv by simp\nqed\n\ncorollary \"balanced n w \\<longleftrightarrow> S (replicate n alphaa @ w)\" (is \"?P \\<longleftrightarrow> ?Q\")\nproof\n  assume ?P\n  thus ?Q\n  proof (induct n w rule: balanced.induct)\n    case 1 show ?case by (auto intro: S.S_\\<epsilon>)\n  next case (2 uu) thus ?case by simp\n  next\n    case (3 n as)\n    moreover from this have \"balanced (Suc n) as\" by simp\n    ultimately have \"S (replicate (Suc n) alphaa @ as)\" by simp\n    hence \"S ((replicate n alphaa @ [alphaa]) @ as)\" by (simp add: replicate_append_same)\n    thus ?case by auto\n  next case (4 as) thus ?case by simp\n  next\n    case (5 n as)\n    moreover from this have \"balanced n as\" by simp\n    ultimately have \"S (replicate n alphaa @ as)\" by simp\n    then show ?case\n    proof (induct \"replicate n alphaa @ as\" arbitrary: n as rule: S.induct)\n      case S_\\<epsilon>\n      from S_\\<epsilon> have Hn: \"replicate n alphaa = []\" by simp\n      from S_\\<epsilon> have Has: \"as = []\" by simp\n      from Hn have Hl: \"replicate (Suc n) alphaa = [alphaa]\" by simp\n      from S.S_\\<epsilon> have \"S []\" by simp\n      with S.S_aSb have \"S (alphaa # [] @ [alphab])\" by blast\n      with Hl Has show ?case by auto\n    next\n      case (S_aSb w)\n      then show ?case\n      proof (cases \"rev as\")\n        case Nil\n        hence \"alphaa # w @ [alphab] = replicate n alphaa @ []\" using S_aSb(3) by simp\n        thus ?thesis\n          by (metis Nil_is_append_conv alpha.distinct(1) append_Nil2 empty_replicate last.simps last_replicate last_snoc list.discI)\n      next\n        case (Cons a al)\n        hence Has: \"as = rev al @ [a]\" by simp\n        hence Ha: \"a = alphab\" using S_aSb(3) by auto\n        from S_aSb(3) Has Ha have Haw: \"alphaa # w = replicate n alphaa @ rev al\" by auto\n        have \"S (replicate (Suc n) alphaa @ alphab # rev al @ [a])\"\n        proof (cases n)\n          case 0\n          with Haw have \"alphaa # w @ [alphab] = rev al @ [alphab]\" by simp\n          with S_aSb(1) S.S_aSb have \"S (rev al @ [alphab])\" by metis\n          moreover \n          from S.S_\\<epsilon> have \"S []\" by simp\n          with S.S_aSb have \"S (alphaa # [] @ [alphab])\" by blast\n          hence \"S ([alphaa, alphab])\" by simp\n          ultimately have \"S ([alphaa, alphab] @ rev al @ [alphab])\" using S.S_SS by blast\n          hence \"S ([alphaa] @ alphab # rev al @ [alphab])\" by auto\n          with 0 Ha show ?thesis by auto\n        next\n          case (Suc m)\n          with Haw have Hw: \"w = replicate m alphaa @ rev al\" by simp\n          with S_aSb(2) have \"S (replicate (Suc m) alphaa @ alphab # rev al)\" by blast\n          with S.S_aSb have \"S (alphaa # (replicate (Suc m) alphaa @ alphab # rev al) @ [alphab])\" by blast\n          hence \"S (replicate (Suc (Suc m)) alphaa @ alphab # rev al @ [alphab])\" by auto\n          thus ?thesis using Suc Ha by simp\n        qed\n        thus ?thesis using Has by simp\n      qed\n    next\n      case (S_SS v w)\n      from \\<open>S v\\<close> have \"v = [] \\<or> (\\<exists> k. v = alphaa # k @ [alphab])\" using S_ends by simp\n      then show ?case\n      proof\n        assume \"v = []\"\n        with S_SS(5) have \"w = replicate n alphaa @ as\" by simp\n        with S_SS(4) show ?thesis by simp\n      next\n        assume \"\\<exists>k. v = alphaa # k @ [alphab]\"\n        then obtain k where Hk: \"v = alphaa # k @ [alphab]\" ..\n        show ?thesis\n        proof (cases n)\n          case 0\n          with S_SS(5) have \"v @ w = as\" by simp\n          with S.S_SS S_SS(1,3) have \"S as\" by blast\n          moreover\n          from S.S_\\<epsilon> have \"S []\" by simp\n          with S.S_aSb have \"S (alphaa # [] @ [alphab])\" by blast\n          hence \"S ([alphaa] @ [alphab])\" by auto\n          ultimately have \"S (([alphaa] @ [alphab]) @ as)\" using S.S_SS by blast\n          thus ?thesis using 0 by auto\n        next\n          case (Suc m)\n          have \"S (alphaa # k @ [alphab])\" using \\<open>S v\\<close> and Hk by simp\n          moreover\n          from this Suc S_SS(5) have \"v @ w = alphaa # replicate m alphaa @ as\" by simp\n          with Hk have \"k @ [alphab] @ w = replicate m alphaa @ as\" by simp\n          ultimately have \"\\<exists> u. k @ [alphab] = replicate m alphaa @ u\" using S_replicate by simp\n          then obtain u where \"k @ [alphab] = replicate m alphaa @ u\" ..\n          hence \"v = alphaa # replicate m alphaa @ u\" using Hk by simp\n          hence Hv: \"v = replicate n alphaa @ u\" using Suc by simp\n          hence Svv: \"S (replicate (Suc n) alphaa @ alphab # u)\" using S_SS(2) by simp\n          from Hv S_SS(5) have Has: \"as = u @ w\" by simp\n          from Svv S_SS(3) S.S_SS have \"S ((replicate (Suc n) alphaa @ alphab # u) @ w)\" by blast\n          with Has show ?thesis by auto\n        qed\n      qed\n    qed\n  qed\nnext\n  assume ?Q\n  thus ?P\n  proof (induct \"replicate n alphaa @ w\" arbitrary: n w rule: S.induct)\n    case S_\\<epsilon>\n    hence \"replicate n alphaa = []\" by simp\n    hence \"n = 0\" by simp\n    moreover from S_\\<epsilon> have \"w = []\" by simp\n    ultimately show ?case by simp\n  next\n    case (S_aSb ww)\n    then show ?case\n    proof (cases n)\n      case 0\n      with S_aSb have Hw: \"w = alphaa # ww @ [alphab]\" by simp\n      from S_aSb(2) have \"balanced 0 ww\" by auto\n      hence \"balanced (Suc 0) (ww @ [alphab])\" using balanced_r by simp\n      hence \"balanced 0 (alphaa # ww @ [alphab])\" by simp\n      with 0 Hw show ?thesis by simp\n    next\n      case (Suc m)\n      with S_aSb(3) have Hwwb: \"ww @ [alphab] = replicate m alphaa @ w\" by simp\n      hence \"\\<exists> wl. ww @ [alphab] = replicate m alphaa @ wl @ [alphab]\"\n        by (metis alpha.distinct(1) append_butlast_last_id empty_replicate last_append last_replicate last_snoc self_append_conv2)\n      then obtain wl where Hww: \"ww = replicate m alphaa @ wl\" by auto\n      with S_aSb(2) have Bwl: \"balanced m wl\" by blast\n      from Hwwb Hww have Hw: \"w = wl @ [alphab]\" by simp\n      from Bwl balanced_r have \"balanced (Suc m) (wl @ [alphab])\" by simp\n      thus ?thesis using Hw Suc by simp\n    qed\n  next\n    case (S_SS vv ww)\n    from S_SS(1) S_ends have \"vv = [] \\<or> (\\<exists>vvv. vv = alphaa # vvv @ [alphab])\" by simp\n    thus ?case\n    proof\n      assume \"vv = []\"\n      with S_SS(5) have \"ww = replicate n alphaa @ w\" by simp\n      with S_SS(4) show ?thesis by simp\n    next\n      assume \"\\<exists>vvv. vv = alphaa # vvv @ [alphab]\"\n      then obtain vvv where Hvv: \"vv = alphaa # vvv @ [alphab]\" ..\n      hence Svv: \"S (alphaa # vvv @ [alphab])\" using S_SS(1) by simp\n      show ?thesis\n      proof (cases n)\n        case 0\n        with S_SS(5) have Hw: \"w = vv @ ww\" by simp\n        from S_SS(2) have Hvv: \"balanced 0 vv\" by simp\n        from S_SS(4) have Hww: \"balanced 0 ww\" by simp\n        from Hvv Hww balanced_app Hw have \"balanced (0 + 0) w\" by blast\n        with 0 show ?thesis by simp\n      next\n        case (Suc m)\n        hence H: \"vvv @ [alphab] @ ww = replicate m alphaa @ w\" using Hvv S_SS(5) by auto\n        hence \"\\<exists> u. vvv @ [alphab] = replicate m alphaa @ u\" using Svv S_replicate by auto\n        then obtain u where Hu: \"vvv @ [alphab] = replicate m alphaa @ u\" ..\n        hence \"vv = replicate n alphaa @ u\" using Hvv Suc by auto\n        with S_SS(2) have Hbu: \"balanced n u\" by simp\n        from H have H': \"(vvv @ [alphab]) @ ww = replicate m alphaa @ w\" by simp\n        from Hu H' have \"replicate m alphaa @ u @ ww = replicate m alphaa @ w\" by auto \n        from Hu H' have Hw: \"u @ ww = w\" by auto\n        from S_SS(3, 4) have Hbww: \"balanced 0 ww\" by simp\n        hence \"balanced (n + 0) (u @ ww)\" using Hbu balanced_app by blast\n        thus ?thesis using Hw by auto\n      qed\n    qed\n  qed\nqed\n\ntext\\<open> where @{const replicate} @{text\"::\"} @{typ\"nat \\<Rightarrow> 'a \\<Rightarrow> 'a list\"} is predefined\nand @{term\"replicate n x\"} yields the list @{text\"[x, \\<dots>, x]\"} of length @{text n}.\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/Chapter5.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8354835371034369, "lm_q2_score": 0.8633916047011594, "lm_q1q2_score": 0.7213494718011371}}
{"text": "\\<^marker>\\<open>creator \"Kevin Kappelmann\"\\<close>\nsection \\<open>Powerset\\<close>\ntheory Powerset\n  imports Order_Set\nbegin\n\nlemma mem_powerset_if_subset: \"A \\<subseteq> B \\<Longrightarrow> A \\<in> powerset B\"\n  by auto\n\nlemma subset_if_mem_powerset: \"A \\<in> powerset B  \\<Longrightarrow> A \\<subseteq> B\"\n  by auto\n\nlemma empty_mem_powerset [iff]: \"{} \\<in> powerset A\"\n  by auto\n\nlemma mem_powerset_self [iff]: \"A \\<in> powerset A\"\n  by auto\n\nlemma mem_powerset_empty_iff_eq_empty [iff]: \"x \\<in> powerset {} \\<longleftrightarrow> x = {}\"\n  by auto\n\nlemma mono_powerset: \"mono powerset\"\n  by (intro monoI) auto\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/HOTG/Powerset.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8633915959134569, "lm_q2_score": 0.8354835391516133, "lm_q1q2_score": 0.7213494662275346}}
{"text": "section \\<open>\\isaheader{Orderings By Comparison Operator}\\<close>\ntheory Intf_Comp\nimports \n  Automatic_Refinement.Automatic_Refinement\nbegin\n\nsubsection \\<open>Basic Definitions\\<close>\n\ndatatype comp_res = LESS | EQUAL | GREATER\n\nconsts i_comp_res :: interface\nabbreviation \"comp_res_rel \\<equiv> Id :: (comp_res \\<times> _) set\"\nlemmas [autoref_rel_intf] = REL_INTFI[of comp_res_rel i_comp_res]\n\ndefinition \"comp2le cmp a b \\<equiv> \n  case cmp a b of LESS \\<Rightarrow> True | EQUAL \\<Rightarrow> True | GREATER \\<Rightarrow> False\"\n\ndefinition \"comp2lt cmp a b \\<equiv> \n  case cmp a b of LESS \\<Rightarrow> True | EQUAL \\<Rightarrow> False | GREATER \\<Rightarrow> False\"\n\ndefinition \"comp2eq cmp a b \\<equiv> \n  case cmp a b of LESS \\<Rightarrow> False | EQUAL \\<Rightarrow> True | GREATER \\<Rightarrow> False\"\n\nlocale linorder_on =\n  fixes D :: \"'a set\"\n  fixes cmp :: \"'a \\<Rightarrow> 'a \\<Rightarrow> comp_res\"\n  assumes lt_eq: \"\\<lbrakk>x\\<in>D; y\\<in>D\\<rbrakk> \\<Longrightarrow> cmp x y = LESS \\<longleftrightarrow> (cmp y x = GREATER)\"\n  assumes refl[simp, intro!]: \"x\\<in>D \\<Longrightarrow> cmp x x = EQUAL\"\n  assumes trans[trans]: \n    \"\\<lbrakk> x\\<in>D; y\\<in>D; z\\<in>D; cmp x y = LESS; cmp y z = LESS\\<rbrakk> \\<Longrightarrow> cmp x z = LESS\"\n    \"\\<lbrakk> x\\<in>D; y\\<in>D; z\\<in>D; cmp x y = LESS; cmp y z = EQUAL\\<rbrakk> \\<Longrightarrow> cmp x z = LESS\"\n    \"\\<lbrakk> x\\<in>D; y\\<in>D; z\\<in>D; cmp x y = EQUAL; cmp y z = LESS\\<rbrakk> \\<Longrightarrow> cmp x z = LESS\"\n    \"\\<lbrakk> x\\<in>D; y\\<in>D; z\\<in>D; cmp x y = EQUAL; cmp y z = EQUAL\\<rbrakk> \\<Longrightarrow> cmp x z = EQUAL\"\nbegin\n  abbreviation \"le \\<equiv> comp2le cmp\"\n  abbreviation \"lt \\<equiv> comp2lt cmp\"\n\n  lemma eq_sym: \"\\<lbrakk>x\\<in>D; y\\<in>D\\<rbrakk> \\<Longrightarrow> cmp x y = EQUAL \\<Longrightarrow> cmp y x = EQUAL\"\n    apply (cases \"cmp y x\")\n    using lt_eq lt_eq[symmetric]\n    by auto\nend\n\nabbreviation \"linorder \\<equiv> linorder_on UNIV\"\n\nlemma linorder_to_class:\n  assumes \"linorder cmp\" \n  assumes [simp]: \"\\<And>x y. cmp x y = EQUAL \\<Longrightarrow> x=y\"\n  shows \"class.linorder (comp2le cmp) (comp2lt cmp)\"\nproof -\n  interpret linorder_on UNIV cmp by fact\n  show ?thesis\n    apply (unfold_locales)\n    unfolding comp2le_def comp2lt_def\n    apply (auto split: comp_res.split comp_res.split_asm)\n    using lt_eq apply simp\n    using lt_eq apply simp\n    using lt_eq[symmetric] apply simp\n    apply (drule (1) trans[rotated 3], simp_all) []\n    apply (drule (1) trans[rotated 3], simp_all) []\n    apply (drule (1) trans[rotated 3], simp_all) []\n    apply (drule (1) trans[rotated 3], simp_all) []\n    using lt_eq apply simp\n    using lt_eq apply simp\n    using lt_eq[symmetric] apply simp\n    done\nqed\n\ndefinition \"dflt_cmp le lt a b \\<equiv> \n  if lt a b then LESS \n  else if le a b then EQUAL \n  else GREATER\"\n\nlemma (in linorder) class_to_linorder:\n  \"linorder (dflt_cmp (\\<le>) (<))\"\n  apply (unfold_locales)\n  unfolding dflt_cmp_def\n  by (auto split: if_split_asm)\n\nlemma restrict_linorder: \"\\<lbrakk>linorder_on D cmp ; D'\\<subseteq>D\\<rbrakk> \\<Longrightarrow> linorder_on D' cmp\"\n  apply (rule linorder_on.intro)\n  apply (drule (1) rev_subsetD)+\n  apply (erule (2) linorder_on.lt_eq)\n  apply (drule (1) rev_subsetD)+\n  apply (erule (1) linorder_on.refl)\n  apply (drule (1) rev_subsetD)+\n  apply (erule (5) linorder_on.trans)\n  apply (drule (1) rev_subsetD)+\n  apply (erule (5) linorder_on.trans)\n  apply (drule (1) rev_subsetD)+\n  apply (erule (5) linorder_on.trans)\n  apply (drule (1) rev_subsetD)+\n  apply (erule (5) linorder_on.trans)\n  done\n\nsubsection \\<open>Operations on Linear Orderings\\<close>\n\ntext \\<open>Map with injective function\\<close>\ndefinition cmp_img where \"cmp_img f cmp a b \\<equiv> cmp (f a) (f b)\"\n\nlemma img_linorder[intro?]: \n  assumes LO: \"linorder_on (f`D) cmp\"\n  shows \"linorder_on D (cmp_img f cmp)\"\n  apply unfold_locales\n  unfolding cmp_img_def\n  apply (rule linorder_on.lt_eq[OF LO], auto) []\n  apply (rule linorder_on.refl[OF LO], auto) []\n  apply (erule (1) linorder_on.trans[OF LO, rotated -2], auto) []\n  apply (erule (1) linorder_on.trans[OF LO, rotated -2], auto) []\n  apply (erule (1) linorder_on.trans[OF LO, rotated -2], auto) []\n  apply (erule (1) linorder_on.trans[OF LO, rotated -2], auto) []\n  done\n\ntext \\<open>Combine\\<close>\ndefinition \"cmp_combine D1 cmp1 D2 cmp2 a b \\<equiv> \n  if a\\<in>D1 \\<and> b\\<in>D1 then cmp1 a b\n  else if a\\<in>D1 \\<and> b\\<in>D2 then LESS\n  else if a\\<in>D2 \\<and> b\\<in>D1 then GREATER\n  else cmp2 a b\n\"\n\n(* TODO: Move *)\nlemma UnE': \n  assumes \"x\\<in>A\\<union>B\"\n  obtains \"x\\<in>A\" | \"x\\<notin>A\" \"x\\<in>B\"\n  using assms by blast\n\nlemma combine_linorder[intro?]:\n  assumes \"linorder_on D1 cmp1\"\n  assumes \"linorder_on D2 cmp2\"\n  assumes \"D = D1\\<union>D2\"\n  shows \"linorder_on D (cmp_combine D1 cmp1 D2 cmp2)\"\n  apply unfold_locales\n  unfolding cmp_combine_def\n  using assms apply -\n  apply (simp only:)\n  apply (elim UnE)\n  apply (auto dest: linorder_on.lt_eq) [4]\n\n  apply (simp only:)\n  apply (elim UnE)\n  apply (auto dest: linorder_on.refl) [2]\n\n  apply (simp only:)\n  apply (elim UnE')\n  apply simp_all [8]\n  apply (erule (5) linorder_on.trans)\n  apply (erule (5) linorder_on.trans)\n\n  apply (simp only:)\n  apply (elim UnE')\n  apply simp_all [8]\n  apply (erule (5) linorder_on.trans)\n  apply (erule (5) linorder_on.trans)\n\n  apply (simp only:)\n  apply (elim UnE')\n  apply simp_all [8]\n  apply (erule (5) linorder_on.trans)\n  apply (erule (5) linorder_on.trans)\n\n  apply (simp only:)\n  apply (elim UnE')\n  apply simp_all [8]\n  apply (erule (5) linorder_on.trans)\n  apply (erule (5) linorder_on.trans)\n  done\n\nsubsection \\<open>Universal Linear Ordering\\<close>\ntext \\<open>With Zorn's Lemma, we get a universal linear (even wf) ordering\\<close>\n\ndefinition \"univ_order_rel \\<equiv> (SOME r. well_order_on UNIV r)\"\ndefinition \"univ_cmp x y \\<equiv> \n  if x=y then EQUAL \n  else if (x,y)\\<in>univ_order_rel then LESS\n  else GREATER\"\n\nlemma univ_wo: \"well_order_on UNIV univ_order_rel\"\n  unfolding univ_order_rel_def\n  using well_order_on[of UNIV]\n  ..\n\nlemma univ_linorder[intro?]: \"linorder univ_cmp\"\n  apply unfold_locales\n  unfolding univ_cmp_def \n  apply (auto split: if_split_asm)\n  using univ_wo\n  apply -\n  unfolding well_order_on_def linear_order_on_def partial_order_on_def\n    preorder_on_def\n  apply (auto simp add: antisym_def) []\n  apply (unfold total_on_def, fast) []\n  apply (unfold trans_def, fast) []\n  apply (auto simp add: antisym_def) []\n  done\n\ntext \\<open>Extend any linear order to a universal order\\<close>\ndefinition \"cmp_extend D cmp \\<equiv> \n  cmp_combine D cmp UNIV univ_cmp\"\n\nlemma extend_linorder[intro?]: \n  \"linorder_on D cmp \\<Longrightarrow> linorder (cmp_extend D cmp)\"\n  unfolding cmp_extend_def\n  apply rule\n  apply assumption\n  apply rule\n  by simp\n\nsubsubsection \\<open>Lexicographic Order on Lists\\<close>  \n\nfun cmp_lex where\n  \"cmp_lex cmp [] [] = EQUAL\"\n| \"cmp_lex cmp [] _ = LESS\"\n| \"cmp_lex cmp _ [] = GREATER\"\n| \"cmp_lex cmp (a#l) (b#m) = (\n    case cmp a b of\n      LESS \\<Rightarrow> LESS\n    | EQUAL \\<Rightarrow> cmp_lex cmp l m\n    | GREATER \\<Rightarrow> GREATER)\"\n\nprimrec cmp_lex' where\n  \"cmp_lex' cmp [] m = (case m of [] \\<Rightarrow> EQUAL | _ \\<Rightarrow> LESS)\"\n| \"cmp_lex' cmp (a#l) m = (case m of [] \\<Rightarrow> GREATER | (b#m) \\<Rightarrow> \n    (case cmp a b of\n      LESS \\<Rightarrow> LESS\n    | EQUAL \\<Rightarrow> cmp_lex' cmp l m\n    | GREATER \\<Rightarrow> GREATER\n  ))\"\n\nlemma cmp_lex_alt: \"cmp_lex cmp l m = cmp_lex' cmp l m\"\n  apply (induct l arbitrary: m)\n  apply (auto split: comp_res.split list.split)\n  done\n\nlemma (in linorder_on) lex_linorder[intro?]:\n  \"linorder_on (lists D) (cmp_lex cmp)\"\nproof\n  fix l m\n  assume \"l\\<in>lists D\" \"m\\<in>lists D\"\n  thus \"(cmp_lex cmp l m = LESS) = (cmp_lex cmp m l = GREATER)\"\n    apply (induct cmp\\<equiv>cmp l m rule: cmp_lex.induct)\n    apply (auto split: comp_res.split simp: lt_eq)\n    apply (auto simp: lt_eq[symmetric])\n    done\nnext\n  fix x\n  assume \"x\\<in>lists D\"\n  thus \"cmp_lex cmp x x = EQUAL\"\n    by (induct x) auto\nnext\n  fix x y z\n  assume M: \"x\\<in>lists D\" \"y\\<in>lists D\" \"z\\<in>lists D\"\n\n  {\n    assume \"cmp_lex cmp x y = LESS\" \"cmp_lex cmp y z = LESS\"\n    thus \"cmp_lex cmp x z = LESS\"\n      using M\n      apply (induct cmp\\<equiv>cmp x y arbitrary: z rule: cmp_lex.induct)\n      apply (auto split: comp_res.split_asm comp_res.split)\n      apply (case_tac z, auto) []\n      apply (case_tac z,\n        auto split: comp_res.split_asm comp_res.split,\n        (drule (4) trans, simp)+\n      ) []\n      apply (case_tac z,\n        auto split: comp_res.split_asm comp_res.split,\n        (drule (4) trans, simp)+\n      ) []\n      done\n  }\n\n  {\n    assume \"cmp_lex cmp x y = LESS\" \"cmp_lex cmp y z = EQUAL\"\n    thus \"cmp_lex cmp x z = LESS\"\n      using M\n      apply (induct cmp\\<equiv>cmp x y arbitrary: z rule: cmp_lex.induct)\n      apply (auto split: comp_res.split_asm comp_res.split)\n      apply (case_tac z, auto) []\n      apply (case_tac z,\n        auto split: comp_res.split_asm comp_res.split,\n        (drule (4) trans, simp)+\n      ) []\n      apply (case_tac z,\n        auto split: comp_res.split_asm comp_res.split,\n        (drule (4) trans, simp)+\n      ) []\n      done\n  }\n\n  {\n    assume \"cmp_lex cmp x y = EQUAL\" \"cmp_lex cmp y z = LESS\"\n    thus \"cmp_lex cmp x z = LESS\"\n      using M\n      apply (induct cmp\\<equiv>cmp x y arbitrary: z rule: cmp_lex.induct)\n      apply (auto split: comp_res.split_asm comp_res.split)\n      apply (case_tac z,\n        auto split: comp_res.split_asm comp_res.split,\n        (drule (4) trans, simp)+\n      ) []\n      done\n  }\n\n  {\n    assume \"cmp_lex cmp x y = EQUAL\" \"cmp_lex cmp y z = EQUAL\"\n    thus \"cmp_lex cmp x z = EQUAL\"\n      using M\n      apply (induct cmp\\<equiv>cmp x y arbitrary: z rule: cmp_lex.induct)\n      apply (auto split: comp_res.split_asm comp_res.split)\n      apply (case_tac z)\n      apply (auto split: comp_res.split_asm comp_res.split)\n      apply (drule (4) trans, simp)+\n      done\n  }\nqed\n\nsubsubsection \\<open>Lexicographic Order on Pairs\\<close>  \n\nfun cmp_prod where \n  \"cmp_prod cmp1 cmp2 (a1,a2) (b1,b2) \n  = (\n    case cmp1 a1 b1 of\n      LESS \\<Rightarrow> LESS\n    | EQUAL \\<Rightarrow> cmp2 a2 b2\n    | GREATER \\<Rightarrow> GREATER)\"\n\nlemma cmp_prod_alt: \"cmp_prod = (\\<lambda>cmp1 cmp2 (a1,a2) (b1,b2). (\n    case cmp1 a1 b1 of\n      LESS \\<Rightarrow> LESS\n    | EQUAL \\<Rightarrow> cmp2 a2 b2\n    | GREATER \\<Rightarrow> GREATER))\"\n  by (auto intro!: ext)\n\n\n\n  show ?thesis\n    apply unfold_locales\n    apply (auto split: comp_res.split comp_res.split_asm,\n      simp_all add: A.lt_eq B.lt_eq,\n      simp_all add: A.lt_eq[symmetric]\n      ) []\n\n    apply (auto split: comp_res.split comp_res.split_asm) []\n\n    apply (auto split: comp_res.split comp_res.split_asm) []\n    apply (drule (4) A.trans B.trans, simp)+\n\n    apply (auto split: comp_res.split comp_res.split_asm) []\n    apply (drule (4) A.trans B.trans, simp)+\n\n    apply (auto split: comp_res.split comp_res.split_asm) []\n    apply (drule (4) A.trans B.trans, simp)+\n\n    apply (auto split: comp_res.split comp_res.split_asm) []\n    apply (drule (4) A.trans B.trans, simp)+\n    done\nqed\n\nsubsection \\<open>Universal Ordering for Sets that is Effective for Finite Sets\\<close>\n\nsubsubsection \\<open>Sorted Lists of Sets\\<close>\ntext \\<open>Some more results about sorted lists of finite sets\\<close>\n\nlemma set_to_map_set_is_map_of: \n  \"distinct (map fst l) \\<Longrightarrow> set_to_map (set l) = map_of l\"\n  apply (induct l)\n  apply (auto simp: set_to_map_insert)\n  done\n\ncontext linorder begin\n\n  lemma sorted_list_of_set_eq_nil[simp]:\n    assumes \"finite A\" \n    shows \"sorted_list_of_set A = [] \\<longleftrightarrow> A={}\"\n    using assms\n    apply (induct rule: finite_induct)\n    apply simp\n    apply simp\n    done\n\n  lemma sorted_list_of_set_eq_nil2[simp]:\n    assumes \"finite A\" \n    shows \"[] = sorted_list_of_set A \\<longleftrightarrow> A={}\"\n    using assms\n    by (auto dest: sym)\n\n  lemma set_insort[simp]: \"set (insort x l) = insert x (set l)\"\n    by (induct l) auto\n\n  lemma sorted_list_of_set_inj_aux:\n    fixes A B :: \"'a set\"\n    assumes \"finite A\" \n    assumes \"finite B\" \n    assumes \"sorted_list_of_set A = sorted_list_of_set B\"\n    shows \"A=B\"\n    using assms\n  proof -\n    from \\<open>finite B\\<close> have \"B = set (sorted_list_of_set B)\" by simp\n    also from assms have \"\\<dots> = set (sorted_list_of_set (A))\"\n      by simp\n    also from \\<open>finite A\\<close> \n    have \"set (sorted_list_of_set (A)) = A\"\n      by simp\n    finally show ?thesis by simp\n  qed\n\n  lemma sorted_list_of_set_inj: \"inj_on sorted_list_of_set (Collect finite)\"\n    apply (rule inj_onI)\n    using sorted_list_of_set_inj_aux\n    by blast\n \n  lemma the_sorted_list_of_set:\n    assumes \"distinct l\"\n    assumes \"sorted l\"\n    shows \"sorted_list_of_set (set l) = l\"\n    using assms\n    by (simp \n      add: sorted_list_of_set_sort_remdups distinct_remdups_id sorted_sort_id)\n\n\n  definition \"sorted_list_of_map m \\<equiv> \n    map (\\<lambda>k. (k, the (m k))) (sorted_list_of_set (dom m))\"\n\n  lemma the_sorted_list_of_map:\n    assumes \"distinct (map fst l)\"\n    assumes \"sorted (map fst l)\"\n    shows \"sorted_list_of_map (map_of l) = l\"\n  proof -\n    have \"dom (map_of l) = set (map fst l)\" by (induct l) force+\n    hence \"sorted_list_of_set (dom (map_of l)) = map fst l\"\n      using the_sorted_list_of_set[OF assms] by simp\n    hence \"sorted_list_of_map (map_of l) \n      = map (\\<lambda>k. (k, the (map_of l k))) (map fst l)\"\n      unfolding sorted_list_of_map_def by simp\n    also have \"\\<dots> = l\" using \\<open>distinct (map fst l)\\<close>\n    proof (induct l)\n      case Nil thus ?case by simp\n    next\n      case (Cons a l) \n      hence \n        1: \"distinct (map fst l)\" \n        and 2: \"fst a\\<notin>fst`set l\" \n        and 3: \"map (\\<lambda>k. (k, the (map_of l k))) (map fst l) = l\" \n        by simp_all\n\n      from 2 have [simp]: \"\\<not>(\\<exists>x\\<in>set l. fst x = fst a)\"\n        by (auto simp: image_iff)\n\n      show ?case\n        apply simp\n        apply (subst (3) 3[symmetric])\n        apply simp\n        done\n    qed\n    finally show ?thesis .\n  qed\n\n  lemma map_of_sorted_list_of_map[simp]:\n    assumes FIN: \"finite (dom m)\" \n    shows \"map_of (sorted_list_of_map m) = m\"\n    unfolding sorted_list_of_map_def\n  proof -\n    have \"set (sorted_list_of_set (dom m)) = dom m\"\n      and DIST: \"distinct (sorted_list_of_set (dom m))\"\n      by (simp_all add: FIN) \n\n    have [simp]: \"(fst \\<circ> (\\<lambda>k. (k, the (m k)))) = id\" by auto\n\n    have [simp]: \"(\\<lambda>k. (k, the (m k))) ` dom m = map_to_set m\"\n      by (auto simp: map_to_set_def)\n\n    show \"map_of (map (\\<lambda>k. (k, the (m k))) (sorted_list_of_set (dom m))) = m\"\n      apply (subst set_to_map_set_is_map_of[symmetric])\n      apply (simp add: DIST)\n      apply (subst set_map)\n      apply (simp add: FIN map_to_set_inverse)\n      done\n  qed\n\n  lemma sorted_list_of_map_inj_aux:\n    fixes A B :: \"'a\\<rightharpoonup>'b\"\n    assumes [simp]: \"finite (dom A)\" \n    assumes [simp]: \"finite (dom B)\" \n    assumes E: \"sorted_list_of_map A = sorted_list_of_map B\"\n    shows \"A=B\"\n    using assms\n  proof -\n    have \"A = map_of (sorted_list_of_map A)\" by simp\n    also note E\n    also have \"map_of (sorted_list_of_map B) = B\" by simp\n    finally show ?thesis .\n  qed\n\n  lemma sorted_list_of_map_inj: \n    \"inj_on sorted_list_of_map (Collect (finite o dom))\"\n    apply (rule inj_onI)\n    using sorted_list_of_map_inj_aux\n    by auto\nend\n\ndefinition \"cmp_set cmp \\<equiv> \n  cmp_extend (Collect finite) (\n    cmp_img\n      (linorder.sorted_list_of_set (comp2le cmp)) \n      (cmp_lex cmp)\n  )\"\n\nthm img_linorder\n\nlemma set_ord_linear[intro?]: \n  \"linorder cmp \\<Longrightarrow> linorder (cmp_set cmp)\"\n  unfolding cmp_set_def\n  apply rule\n  apply rule\n  apply (rule restrict_linorder)\n  apply (erule linorder_on.lex_linorder)\n  apply simp\n  done\n\ndefinition \"cmp_map cmpk cmpv \\<equiv>\n  cmp_extend (Collect (finite o dom)) (\n    cmp_img\n      (linorder.sorted_list_of_map (comp2le cmpk))\n      (cmp_lex (cmp_prod cmpk cmpv))\n  )\n\"\n\nlemma map_to_set_inj[intro!]: \"inj map_to_set\"\n  apply (rule inj_onI)\n  unfolding map_to_set_def\n  apply (rule ext)\n  apply (case_tac \"x xa\")\n  apply (case_tac [!] \"y xa\")\n  apply force+\n  done\n\ncorollary map_to_set_inj'[intro!]: \"inj_on map_to_set S\"\n  by (metis map_to_set_inj subset_UNIV subset_inj_on)\n  \nlemma map_ord_linear[intro?]: \n  assumes A: \"linorder cmpk\" \n  assumes B: \"linorder cmpv\" \n  shows \"linorder (cmp_map cmpk cmpv)\"\nproof -\n  interpret lk: linorder_on UNIV cmpk by fact\n  interpret lv: linorder_on UNIV cmpv by fact\n  \n  show ?thesis\n    unfolding cmp_map_def\n    apply rule\n    apply rule\n    apply (rule restrict_linorder)\n    apply (rule linorder_on.lex_linorder)\n    apply (rule)\n    apply fact\n    apply fact\n    apply simp\n    done\nqed\n  \n  \nlocale eq_linorder_on = linorder_on +\n  assumes cmp_imp_equal: \"\\<lbrakk>x\\<in>D; y\\<in>D\\<rbrakk> \\<Longrightarrow> cmp x y = EQUAL \\<Longrightarrow> x = y\"\nbegin\n  lemma cmp_eq[simp]: \"\\<lbrakk>x\\<in>D; y\\<in>D\\<rbrakk> \\<Longrightarrow> cmp x y = EQUAL \\<longleftrightarrow> x = y\"\n    by (auto simp: cmp_imp_equal)\nend\n  \nabbreviation \"eq_linorder \\<equiv> eq_linorder_on UNIV\"\n\nlemma dflt_cmp_2inv[simp]: \n  \"dflt_cmp (comp2le cmp) (comp2lt cmp) = cmp\"\n  unfolding dflt_cmp_def[abs_def] comp2le_def[abs_def] comp2lt_def[abs_def]\n  apply (auto split: comp_res.splits intro!: ext)\n  done\n\nlemma (in linorder) dflt_cmp_inv2[simp]:\n  shows \n  \"(comp2le (dflt_cmp (\\<le>) (<)))= (\\<le>)\"\n  \"(comp2lt (dflt_cmp (\\<le>) (<)))= (<)\"\nproof -\n  show \"(comp2lt (dflt_cmp (\\<le>) (<)))= (<)\"\n    unfolding dflt_cmp_def[abs_def] comp2le_def[abs_def] comp2lt_def[abs_def]\n    apply (auto split: comp_res.splits intro!: ext)\n    done\n\n  show \"(comp2le (dflt_cmp (\\<le>) (<))) = (\\<le>)\"\n    unfolding dflt_cmp_def[abs_def] comp2le_def[abs_def] comp2lt_def[abs_def]\n    apply (auto split: comp_res.splits intro!: ext)\n    done\n\nqed\n    \nlemma eq_linorder_class_conv:\n  \"eq_linorder cmp \\<longleftrightarrow> class.linorder (comp2le cmp) (comp2lt cmp)\"\nproof\n  assume \"eq_linorder cmp\"\n  then interpret eq_linorder_on UNIV cmp .\n  have \"linorder cmp\" by unfold_locales\n  show \"class.linorder (comp2le cmp) (comp2lt cmp)\"\n    apply (rule linorder_to_class)\n    apply fact\n    by simp\nnext\n  assume \"class.linorder (comp2le cmp) (comp2lt cmp)\"\n  then interpret linorder \"comp2le cmp\" \"comp2lt cmp\" .\n  \n  from class_to_linorder interpret linorder_on UNIV cmp\n    by simp\n  show \"eq_linorder cmp\"\n  proof\n    fix x y\n    assume \"cmp x y = EQUAL\"\n    hence \"comp2le cmp x y\" \"\\<not>comp2lt cmp x y\"\n      by (auto simp: comp2le_def comp2lt_def)\n    thus \"x=y\" by simp\n  qed\nqed\n  \nlemma (in linorder) class_to_eq_linorder:\n  \"eq_linorder (dflt_cmp (\\<le>) (<))\"\nproof -\n  interpret linorder_on UNIV \"dflt_cmp (\\<le>) (<)\"\n    by (rule class_to_linorder)\n\n  show ?thesis\n    apply unfold_locales\n    apply (auto simp: dflt_cmp_def split: if_split_asm)\n    done\nqed\n\nlemma eq_linorder_comp2eq_eq: \n  assumes \"eq_linorder cmp\"\n  shows \"comp2eq cmp = (=)\"\nproof -\n  interpret eq_linorder_on UNIV cmp by fact\n  show ?thesis\n    apply (intro ext)\n    unfolding comp2eq_def\n    apply (auto split: comp_res.split dest: refl)\n    done\nqed\n    \nlemma restrict_eq_linorder: \n  assumes \"eq_linorder_on D cmp\" \n  assumes S: \"D'\\<subseteq>D\" \n  shows \"eq_linorder_on D' cmp\"\nproof -\n  interpret eq_linorder_on D cmp by fact\n  \n  show ?thesis\n    apply (rule eq_linorder_on.intro)\n    apply (rule restrict_linorder[where D=D])\n    apply unfold_locales []\n    apply fact\n    apply unfold_locales\n    using S\n    apply -\n    apply (drule (1) rev_subsetD)+\n    apply auto\n    done\nqed\n  \nlemma combine_eq_linorder[intro?]:\n  assumes A: \"eq_linorder_on D1 cmp1\"\n  assumes B: \"eq_linorder_on D2 cmp2\"\n  assumes EQ: \"D=D1\\<union>D2\"\n  shows \"eq_linorder_on D (cmp_combine D1 cmp1 D2 cmp2)\"\nproof -\n  interpret A: eq_linorder_on D1 cmp1 by fact\n  interpret B: eq_linorder_on D2 cmp2 by fact\n  interpret linorder_on \"(D1 \\<union> D2)\" \"(cmp_combine D1 cmp1 D2 cmp2)\"\n    apply rule\n    apply unfold_locales\n    by simp\n  \n  show ?thesis\n    apply (simp only: EQ)\n    apply unfold_locales\n    unfolding cmp_combine_def\n    by (auto split: if_split_asm)\nqed\n\nlemma img_eq_linorder[intro?]:\n  assumes A: \"eq_linorder_on (f`D) cmp\"\n  assumes INJ: \"inj_on f D\"\n  shows \"eq_linorder_on D (cmp_img f cmp)\"\nproof -\n  interpret eq_linorder_on \"f`D\" cmp by fact\n  interpret L: linorder_on \"(D)\" \"(cmp_img f cmp)\"\n    apply rule\n    apply unfold_locales\n    done\n  \n  show ?thesis\n    apply unfold_locales\n    unfolding cmp_img_def\n    using INJ\n    apply (auto dest: inj_onD)\n    done\nqed\n\nlemma univ_eq_linorder[intro?]:\n  shows \"eq_linorder univ_cmp\"\n  apply (rule eq_linorder_on.intro)\n  apply rule\n  apply unfold_locales\n  unfolding univ_cmp_def\n  apply (auto split: if_split_asm)\n  done\n  \nlemma extend_eq_linorder[intro?]:\n  assumes \"eq_linorder_on D cmp\"\n  shows \"eq_linorder (cmp_extend D cmp)\"\nproof -\n  interpret eq_linorder_on D cmp by fact\n  show ?thesis\n    unfolding cmp_extend_def\n    apply (rule)\n    apply fact\n    apply rule\n    by simp\nqed\n  \nlemma lex_eq_linorder[intro?]:\n  assumes \"eq_linorder_on D cmp\"\n  shows \"eq_linorder_on (lists D) (cmp_lex cmp)\"\nproof -\n  interpret eq_linorder_on D cmp by fact\n  show ?thesis\n    apply (rule eq_linorder_on.intro)\n    apply rule\n    apply unfold_locales\n    subgoal for l m\n      apply (induct cmp\\<equiv>cmp l m rule: cmp_lex.induct)\n      apply (auto split: comp_res.splits)\n      done\n    done\nqed\n\nlemma prod_eq_linorder[intro?]:\n  assumes \"eq_linorder_on D1 cmp1\"\n  assumes \"eq_linorder_on D2 cmp2\"\n  shows \"eq_linorder_on (D1\\<times>D2) (cmp_prod cmp1 cmp2)\"\nproof -\n  interpret A: eq_linorder_on D1 cmp1 by fact\n  interpret B: eq_linorder_on D2 cmp2 by fact\n  show ?thesis\n    apply (rule eq_linorder_on.intro)\n    apply rule\n    apply unfold_locales\n    apply (auto split: comp_res.splits)\n    done\nqed\n\nlemma set_ord_eq_linorder[intro?]: \n  \"eq_linorder cmp \\<Longrightarrow> eq_linorder (cmp_set cmp)\"\n  unfolding cmp_set_def\n  apply rule\n  apply rule\n  apply (rule restrict_eq_linorder)\n  apply rule\n  apply assumption\n  apply simp\n\n  apply (rule linorder.sorted_list_of_set_inj)\n  apply (subst (asm) eq_linorder_class_conv)\n  .\n\nlemma map_ord_eq_linorder[intro?]: \n  \"\\<lbrakk>eq_linorder cmpk; eq_linorder cmpv\\<rbrakk> \\<Longrightarrow> eq_linorder (cmp_map cmpk cmpv)\"\n  unfolding cmp_map_def\n  apply rule\n  apply rule\n  apply (rule restrict_eq_linorder)\n  apply rule\n  apply rule\n  apply assumption\n  apply assumption\n  apply simp\n\n  apply (rule linorder.sorted_list_of_map_inj)\n  apply (subst (asm) eq_linorder_class_conv)\n  .\n\ndefinition cmp_unit :: \"unit \\<Rightarrow> unit \\<Rightarrow> comp_res\" \n  where [simp]: \"cmp_unit u v \\<equiv> EQUAL\"\n\nlemma cmp_unit_eq_linorder:\n  \"eq_linorder cmp_unit\"\n  by unfold_locales simp_all\n  \nsubsection \\<open>Parametricity\\<close>  \n  \nlemma param_cmp_extend[param]:\n  assumes \"(cmp,cmp')\\<in>R \\<rightarrow> R \\<rightarrow> Id\"\n  assumes \"Range R \\<subseteq> D\"\n  shows \"(cmp,cmp_extend D cmp') \\<in> R \\<rightarrow> R \\<rightarrow> Id\"\n  unfolding cmp_extend_def cmp_combine_def[abs_def]\n  using assms\n  apply clarsimp\n  by (blast dest!: fun_relD)\n\nlemma param_cmp_img[param]: \n  \"(cmp_img,cmp_img) \\<in> (Ra\\<rightarrow>Rb) \\<rightarrow> (Rb\\<rightarrow>Rb\\<rightarrow>Rc) \\<rightarrow> Ra \\<rightarrow> Ra \\<rightarrow> Rc\"\n  unfolding cmp_img_def[abs_def]\n  by parametricity\n\nlemma param_comp_res[param]:\n  \"(LESS,LESS)\\<in>Id\"\n  \"(EQUAL,EQUAL)\\<in>Id\"\n  \"(GREATER,GREATER)\\<in>Id\"\n  \"(case_comp_res,case_comp_res)\\<in>Ra\\<rightarrow>Ra\\<rightarrow>Ra\\<rightarrow>Id\\<rightarrow>Ra\"\n  by (auto split: comp_res.split)\n\nterm cmp_lex\nlemma param_cmp_lex[param]:\n  \"(cmp_lex,cmp_lex)\\<in>(Ra\\<rightarrow>Rb\\<rightarrow>Id)\\<rightarrow>\\<langle>Ra\\<rangle>list_rel\\<rightarrow>\\<langle>Rb\\<rangle>list_rel\\<rightarrow>Id\"\n  unfolding cmp_lex_alt[abs_def] cmp_lex'_def\n  by (parametricity)\n\nterm cmp_prod\nlemma param_cmp_prod[param]:\n  \"(cmp_prod,cmp_prod)\\<in>\n  (Ra\\<rightarrow>Rb\\<rightarrow>Id)\\<rightarrow>(Rc\\<rightarrow>Rd\\<rightarrow>Id)\\<rightarrow>\\<langle>Ra,Rc\\<rangle>prod_rel\\<rightarrow>\\<langle>Rb,Rd\\<rangle>prod_rel\\<rightarrow>Id\"\n  unfolding cmp_prod_alt\n  by (parametricity)\n\nlemma param_cmp_unit[param]: \n  \"(cmp_unit,cmp_unit)\\<in>Id\\<rightarrow>Id\\<rightarrow>Id\" \n  by auto\n\nlemma param_comp2eq[param]: \"(comp2eq,comp2eq)\\<in>(R\\<rightarrow>R\\<rightarrow>Id)\\<rightarrow>R\\<rightarrow>R\\<rightarrow>Id\"\n  unfolding comp2eq_def[abs_def]\n  by (parametricity)\n\n\n  \nlemma cmp_combine_paramD:\n  assumes \"(cmp,cmp_combine D1 cmp1 D2 cmp2)\\<in>R\\<rightarrow>R\\<rightarrow>Id\"\n  assumes \"Range R \\<subseteq> D1\"\n  shows \"(cmp,cmp1)\\<in>R\\<rightarrow>R\\<rightarrow>Id\"\n  using assms\n  unfolding cmp_combine_def[abs_def]\n  apply (intro fun_relI)\n  apply (drule_tac x=a in fun_relD, assumption)\n  apply (drule_tac x=aa in fun_relD, assumption)\n  apply (drule RangeI, drule (1) rev_subsetD)\n  apply (drule RangeI, drule (1) rev_subsetD)\n  apply simp\n  done\n\nlemma cmp_extend_paramD:\n  assumes \"(cmp,cmp_extend D cmp')\\<in>R\\<rightarrow>R\\<rightarrow>Id\"\n  assumes \"Range R \\<subseteq> D\"\n  shows \"(cmp,cmp')\\<in>R\\<rightarrow>R\\<rightarrow>Id\"\n  using assms\n  unfolding cmp_extend_def\n  apply (rule cmp_combine_paramD)\n  done\n  \n\nsubsection \\<open>Tuning of Generated Implementation\\<close>\nlemma [autoref_post_simps]: \"comp2eq (dflt_cmp (\\<le>) ((<)::_::linorder\\<Rightarrow>_)) = (=)\"\n  by (simp add: class_to_eq_linorder eq_linorder_comp2eq_eq)\n\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/Evaluation/Collections/GenCF/Intf/Intf_Comp.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.863391599428538, "lm_q2_score": 0.8354835309589074, "lm_q1q2_score": 0.7213494620908135}}
{"text": "theory Graph_Definition\n  imports\n    Dijkstra_Shortest_Path.Graph\n    Dijkstra_Shortest_Path.Weight\nbegin\n\nsection \\<open>Definition\\<close>\n\nfun is_path_undir :: \"('v, 'w) graph \\<Rightarrow> 'v \\<Rightarrow> ('v,'w) path \\<Rightarrow> 'v \\<Rightarrow> bool\" where\n    \"is_path_undir G v [] v' \\<longleftrightarrow> v=v' \\<and> v'\\<in>nodes G\" |\n    \"is_path_undir G v ((v1,w,v2)#p) v' \\<longleftrightarrow> v=v1 \\<and> ((v1,w,v2)\\<in>edges G \\<or> (v2,w,v1)\\<in>edges G) \\<and> is_path_undir G v2 p v'\"\n\nabbreviation \"nodes_connected G a b \\<equiv> \\<exists>p. is_path_undir G a p b\"\n\ndefinition degree :: \"('v, 'w) graph \\<Rightarrow> 'v \\<Rightarrow> nat\" where\n  \"degree G v = card {e\\<in>edges G. fst e = v \\<or> snd (snd e) = v}\"\n\nlocale forest = valid_graph G\n  for G :: \"('v,'w) graph\" +\n  assumes cycle_free:\n    \"\\<forall>(a,w,b)\\<in>E. \\<not> nodes_connected (delete_edge a w b G) a b\"\n\nlocale connected_graph = valid_graph G\n  for G :: \"('v,'w) graph\" +\n  assumes connected:\n    \"\\<forall>v\\<in>V. \\<forall>v'\\<in>V. nodes_connected G v v'\"\n\nlocale tree = forest + connected_graph\n\nlocale finite_graph = valid_graph G\n  for G :: \"('v,'w) graph\" +\n  assumes finite_E: \"finite E\" and\n    finite_V: \"finite V\"\n\nlocale finite_weighted_graph = finite_graph G\n  for G :: \"('v,'w::weight) graph\"\n\ndefinition subgraph :: \"('v, 'w) graph \\<Rightarrow> ('v, 'w) graph \\<Rightarrow> bool\" where\n  \"subgraph G H \\<equiv> nodes G = nodes H \\<and> edges G \\<subseteq> edges H\"\n\ndefinition edge_weight :: \"('v, 'w) graph \\<Rightarrow> 'w::weight\" where\n  \"edge_weight G \\<equiv> sum (fst o snd) (edges G)\"\n\ndefinition edges_less_eq :: \"('a \\<times> 'w::weight \\<times> 'a) \\<Rightarrow> ('a \\<times> 'w \\<times> 'a) \\<Rightarrow> bool\"\n  where \"edges_less_eq a b \\<equiv> fst(snd a) \\<le> fst(snd b)\"\n\ndefinition maximally_connected :: \"('v, 'w) graph \\<Rightarrow> ('v, 'w) graph \\<Rightarrow> bool\" where\n  \"maximally_connected H G \\<equiv> \\<forall>v\\<in>nodes G. \\<forall>v'\\<in>nodes G.\n    (nodes_connected G v v') \\<longrightarrow> (nodes_connected H v v')\"\n\ndefinition spanning_forest :: \"('v, 'w) graph \\<Rightarrow> ('v, 'w) graph \\<Rightarrow> bool\" where\n  \"spanning_forest F G \\<equiv> forest F \\<and> maximally_connected F G \\<and> subgraph F G\"\n\ndefinition optimal_forest :: \"('v, 'w::weight) graph \\<Rightarrow> ('v, 'w) graph \\<Rightarrow> bool\" where\n  \"optimal_forest F G \\<equiv> (\\<forall>F'::('v, 'w) graph.\n      spanning_forest F' G \\<longrightarrow> edge_weight F \\<le> edge_weight F')\"\n\ndefinition minimum_spanning_forest :: \"('v, 'w::weight) graph \\<Rightarrow> ('v, 'w) graph \\<Rightarrow> bool\" where\n  \"minimum_spanning_forest F G \\<equiv> spanning_forest F G \\<and> optimal_forest F G\"\n\ndefinition spanning_tree :: \"('v, 'w) graph \\<Rightarrow> ('v, 'w) graph \\<Rightarrow> bool\" where\n  \"spanning_tree F G \\<equiv> tree F \\<and> subgraph F G\"\n\ndefinition optimal_tree :: \"('v, 'w::weight) graph \\<Rightarrow> ('v, 'w) graph \\<Rightarrow> bool\" where\n  \"optimal_tree F G \\<equiv> (\\<forall>F'::('v, 'w) graph.\n      spanning_tree F' G \\<longrightarrow> edge_weight F \\<le> edge_weight F')\"\n\ndefinition minimum_spanning_tree :: \"('v, 'w::weight) graph \\<Rightarrow> ('v, 'w) graph \\<Rightarrow> bool\" where\n  \"minimum_spanning_tree F G \\<equiv> spanning_tree F G \\<and> optimal_tree F G\"\n\nsection \\<open>Helping lemmas\\<close>\n\nlemma nodes_delete_edge[simp]:\n  \"nodes (delete_edge v e v' G) = nodes G\"\n  by (simp add: delete_edge_def)\n\nlemma edges_delete_edge[simp]:\n  \"edges (delete_edge v e v' G) = edges G - {(v,e,v')}\"\n  by (simp add: delete_edge_def)\n\nlemma subgraph_node:\n  assumes \"subgraph H G\"\n  shows \"v \\<in> nodes G \\<longleftrightarrow> v \\<in> nodes H\"\n  using assms\n  unfolding subgraph_def\n  by simp\n\nlemma delete_add_edge:\n  assumes \"a \\<in> nodes H\"\n  assumes \"c \\<in> nodes H\"\n  assumes \"(a, w, c) \\<notin> edges H\"\n  shows \"delete_edge a w c (add_edge a w c H) = H\"\n  using assms unfolding delete_edge_def add_edge_def\n  by (simp add: insert_absorb)\n\nlemma swap_delete_add_edge:\n  assumes \"(a, b, c) \\<noteq> (x, y, z)\"\n  shows \"delete_edge a b c (add_edge x y z H) = add_edge x y z (delete_edge a b c H)\"\n  using assms unfolding delete_edge_def add_edge_def\n  by auto\n\nlemma swap_delete_edges: \"delete_edge a b c (delete_edge x y z H) = delete_edge x y z (delete_edge a b c H)\"\n  unfolding delete_edge_def\n  by auto\n\ncontext valid_graph\nbegin\n  lemma valid_subgraph:\n    assumes \"subgraph H G\"\n    shows \"valid_graph H\"\n    using assms E_valid unfolding subgraph_def valid_graph_def\n    by blast\n\n  lemma is_path_undir_simps[simp, intro!]:\n    \"is_path_undir G v [] v \\<longleftrightarrow> v\\<in>V\"\n    \"is_path_undir G v [(v,w,v')] v' \\<longleftrightarrow> (v,w,v')\\<in>E \\<or> (v',w,v)\\<in>E\"\n    by (auto dest: E_validD)\n\n  lemma is_path_undir_memb[simp]:\n    \"is_path_undir G 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_undir_memb_edges:\n    assumes \"is_path_undir G v p v'\"\n    shows \"\\<forall>(a,w,b) \\<in> set p. (a,w,b) \\<in> E \\<or> (b,w,a) \\<in> E\"\n    using assms\n    by (induct p arbitrary: v) fastforce+\n\n  lemma is_path_undir_split:\n    \"is_path_undir G v (p1@p2) v' \\<longleftrightarrow> (\\<exists>u. is_path_undir G v p1 u \\<and> is_path_undir G u p2 v')\"\n    by (induct p1 arbitrary: v) auto\n\n  lemma is_path_undir_split'[simp]:\n    \"is_path_undir G v (p1@(u,w,u')#p2) v'\n      \\<longleftrightarrow> is_path_undir G v p1 u \\<and> ((u,w,u')\\<in>E \\<or> (u',w,u)\\<in>E) \\<and> is_path_undir G u' p2 v'\"\n    by (auto simp add: is_path_undir_split)\n\n  lemma is_path_undir_sym:\n    assumes \"is_path_undir G v p v'\"\n    shows \"is_path_undir G v' (rev (map (\\<lambda>(u, w, u'). (u', w, u)) p)) v\"\n    using assms\n    by (induct p arbitrary: v) (auto simp: E_validD)\n\n  lemma is_path_undir_subgraph:\n    assumes \"is_path_undir H x p y\"\n    assumes \"subgraph H G\"\n    shows \"is_path_undir G x p y\"\n    using assms is_path_undir.simps\n    unfolding subgraph_def\n    by (induction p arbitrary: x y) auto\n\n  lemma no_path_in_empty_graph:\n    assumes \"E = {}\"\n    assumes \"p \\<noteq> []\"\n    shows \"\\<not>is_path_undir G v p v\"\n    using assms by (cases p) auto\n\n  lemma is_path_undir_split_distinct:\n    assumes \"is_path_undir G v p v'\"\n    assumes \"(a, w, b) \\<in> set p \\<or> (b, w, a) \\<in> set p\"\n    shows \"(\\<exists>p' p'' u u'.\n            is_path_undir G v p' u \\<and> is_path_undir G u' p'' v' \\<and>\n            length p' < length p \\<and> length p'' < length p \\<and>\n            (u \\<in> {a, b} \\<and> u' \\<in> {a, b}) \\<and>\n            (a, w, b) \\<notin> set p' \\<and> (b, w, a) \\<notin> set p' \\<and>\n            (a, w, b) \\<notin> set p'' \\<and> (b, w, a) \\<notin> set p'')\"\n    using assms\n  proof (induction n == \"length p\" arbitrary: p v v' rule: nat_less_induct)\n    case 1\n    then obtain u u' where \"(u, w, u') \\<in> set p\" and u: \"u \\<in> {a, b} \\<and> u' \\<in> {a, b}\"\n      by blast\n    with split_list obtain p' p''\n      where p: \"p = p' @ (u, w, u') # p''\"\n      by fast\n    then have len_p': \"length p' < length p\" and len_p'': \"length p'' < length p\"\n      by auto\n    from 1 p have p': \"is_path_undir G v p' u\" and p'': \"is_path_undir G u' p'' v'\"\n      by auto\n    from 1 len_p' p' have \"(a, w, b) \\<in> set p' \\<or> (b, w, a) \\<in> set p' \\<longrightarrow> (\\<exists>p'2 u2.\n            is_path_undir G v p'2 u2 \\<and>\n            length p'2 < length p' \\<and>\n            u2 \\<in> {a, b} \\<and>\n            (a, w, b) \\<notin> set p'2 \\<and> (b, w, a) \\<notin> set p'2)\"\n      by metis\n    with len_p' p' u have p': \"\\<exists>p' u. is_path_undir G v p' u \\<and> length p' < length p \\<and>\n      u \\<in> {a,b} \\<and> (a, w, b) \\<notin> set p' \\<and> (b, w, a) \\<notin> set p'\"\n      by fastforce\n    from 1 len_p'' p'' have \"(a, w, b) \\<in> set p'' \\<or> (b, w, a) \\<in> set p'' \\<longrightarrow> (\\<exists>p''2 u'2.\n            is_path_undir G u'2 p''2 v' \\<and>\n            length p''2 < length p'' \\<and>\n            u'2 \\<in> {a, b} \\<and>\n            (a, w, b) \\<notin> set p''2 \\<and> (b, w, a) \\<notin> set p''2)\"\n      by metis\n    with len_p'' p'' u have \"\\<exists>p'' u'. is_path_undir G u' p'' v'\\<and> length p'' < length p \\<and>\n      u' \\<in> {a,b} \\<and> (a, w, b) \\<notin> set p'' \\<and> (b, w, a) \\<notin> set p''\"\n      by fastforce\n    with p' show ?case by auto\n  qed\n\n  lemma add_edge_is_path:\n    assumes \"is_path_undir G x p y\"\n    shows \"is_path_undir (add_edge a b c G) x p y\"\n  proof -\n    from E_valid have \"valid_graph (add_edge a b c G)\"\n      unfolding valid_graph_def add_edge_def\n      by auto\n    with assms is_path_undir.simps[of \"add_edge a b c G\"]\n    show \"is_path_undir (add_edge a b c G) x p y\"\n      by (induction p arbitrary: x y) auto\n  qed\n\n  lemma add_edge_was_path:\n    assumes \"is_path_undir (add_edge a b c G) x p y\"\n    assumes \"(a, b, c) \\<notin> set p\"\n    assumes \"(c, b, a) \\<notin> set p\"\n    assumes \"a \\<in> V\"\n    assumes \"c \\<in> V\"\n    shows \"is_path_undir G x p y\"\n  proof -\n    from E_valid have \"valid_graph (add_edge a b c G)\"\n      unfolding valid_graph_def add_edge_def\n      by auto\n    with assms is_path_undir.simps[of \"add_edge a b c G\"]\n    show \"is_path_undir G x p y\"\n      by (induction p arbitrary: x y) auto\n  qed\n\n  lemma delete_edge_is_path:\n    assumes \"is_path_undir G x p y\"\n    assumes \"(a, b, c) \\<notin> set p\"\n    assumes \"(c, b, a) \\<notin> set p\"\n    shows \"is_path_undir (delete_edge a b c G) x p y\"\n  proof -\n    from E_valid have \"valid_graph (delete_edge a b c G)\"\n      unfolding valid_graph_def delete_edge_def\n      by auto\n    with assms is_path_undir.simps[of \"delete_edge a b c G\"]\n    show ?thesis\n      by (induction p arbitrary: x y) auto\n  qed\n\n  lemma delete_node_is_path:\n    assumes \"is_path_undir G x p y\"\n    assumes \"x \\<noteq> v\"\n    assumes \"v \\<notin> fst`set p \\<union> snd`snd`set p\"\n    shows \"is_path_undir (delete_node v G) x p y\"\n    using assms\n    unfolding delete_node_def\n    by (induction p arbitrary: x y) auto\n\n  \n\n  lemma subset_was_path:\n    assumes \"is_path_undir H x p y\"\n    assumes \"edges H \\<subseteq> E\"\n    assumes \"nodes H \\<subseteq> V\"\n    shows \"is_path_undir G x p y\"\n    using assms\n    by (induction p arbitrary: x y) auto\n\n  lemma delete_node_was_path:\n    assumes \"is_path_undir (delete_node v G) x p y\"\n    shows \"is_path_undir G x p y\"\n    using assms\n    unfolding delete_node_def\n    by (induction p arbitrary: x y) auto\n\n  lemma add_edge_preserve_subgraph:\n    assumes \"subgraph H G\"\n    assumes \"(a, w, b) \\<in> E\"\n    shows \"subgraph (add_edge a w b H) G\"\n  proof -\n    from assms E_validD have \"a \\<in> nodes H \\<and> b \\<in> nodes H\"\n      unfolding subgraph_def by simp\n    with assms show ?thesis\n      unfolding subgraph_def\n      by auto\n  qed\n\n  lemma delete_edge_preserve_subgraph:\n    assumes \"subgraph H G\"\n    shows \"subgraph (delete_edge a w b H) G\"\n    using assms\n    unfolding subgraph_def\n    by auto\n\n  lemma add_delete_edge:\n    assumes \"(a, w, c) \\<in> E\"\n    shows \"add_edge a w c (delete_edge a w c G) = G\"\n    using assms E_validD unfolding delete_edge_def add_edge_def\n    by (simp add: insert_absorb)\n\n  lemma swap_add_edge_in_path:\n    assumes \"is_path_undir (add_edge a w b G) v p v'\"\n    assumes \"(a,w',a') \\<in> E \\<or> (a',w',a) \\<in> E\"\n    shows \"\\<exists>p. is_path_undir (add_edge a' w'' b G) v p v'\"\n  using assms(1)\n  proof (induction p arbitrary: v)\n    case Nil\n    with assms(2) E_validD\n    have \"is_path_undir (add_edge a' w'' b G) v [] v'\"\n      by auto\n    then show ?case\n      by blast\n  next\n    case (Cons e p')\n    then obtain v2 x e_w where \"e = (v2, e_w, x)\"\n      using prod_cases3 by blast\n    with Cons(2)\n    have e: \"e = (v, e_w, x)\" and\n         edge_e: \"(v, e_w, x) \\<in> edges (add_edge a w b G) \\<or> (x, e_w, v) \\<in> edges (add_edge a w b G)\" and\n         p': \"is_path_undir (add_edge a w b G) x p' v'\"\n      by auto\n    have \"\\<exists>p. is_path_undir (add_edge a' w'' b G) v p x\"\n    proof (cases \"e = (a, w, b) \\<or> e = (b, w, a)\")\n      case True\n      from True e assms(2) E_validD have \"is_path_undir (add_edge a' w'' b G) v [(a,w',a'), (a',w'',b)] x\n          \\<or> is_path_undir (add_edge a' w'' b G) v [(b,w'',a'), (a',w',a)] x\"\n        by auto\n      then show ?thesis\n        by blast\n    next\n      case False\n      with edge_e e\n      have \"is_path_undir (add_edge a' w'' b G) v [e] x\"\n        by (auto simp: E_validD)\n      then show ?thesis\n        by auto\n    qed\n    with p' Cons.IH valid_graph.is_path_undir_split[OF add_edge_valid[OF valid_graph.intro[OF E_valid]]]\n    show ?case\n      by blast\n  qed\n\n  lemma induce_maximally_connected:\n    assumes \"subgraph H G\"\n    assumes \"\\<forall>(a,w,b)\\<in>E. nodes_connected H a b\"\n    shows \"maximally_connected H G\"\n  proof -\n    from valid_subgraph[OF \\<open>subgraph H G\\<close>]\n    have valid_H: \"valid_graph H\" .\n    have \"(nodes_connected G v v') \\<longrightarrow> (nodes_connected H v v')\" (is \"?lhs \\<longrightarrow> ?rhs\")\n      if \"v\\<in>V\" and \"v'\\<in>V\" for v v'\n    proof\n      assume ?lhs\n      then obtain p where \"is_path_undir G v p v'\"\n        by blast\n      then show ?rhs\n      proof (induction p arbitrary: v v')\n        case Nil\n        with subgraph_node[OF assms(1)] show ?case\n          by (metis is_path_undir.simps(1))\n      next\n        case (Cons e p)\n        from prod_cases3 obtain a w b where awb: \"e = (a, w, b)\" .\n        with assms Cons.prems valid_graph.is_path_undir_sym[OF valid_H, of b _ a]\n        obtain p' where p': \"is_path_undir H a p' b\"\n          by fastforce\n        from assms awb Cons.prems Cons.IH[of b v']\n        obtain p'' where \"is_path_undir H b p'' v'\"\n          unfolding subgraph_def by auto\n        with Cons.prems awb assms p' valid_graph.is_path_undir_split[OF valid_H]\n          have \"is_path_undir H v (p'@p'') v'\"\n            by auto\n        then show ?case ..\n      qed\n    qed\n    with assms show ?thesis\n      unfolding maximally_connected_def\n      by auto\n  qed\n\n  lemma add_edge_maximally_connected:\n    assumes \"maximally_connected H G\"\n    assumes \"subgraph H G\"\n    assumes \"(a, w, b) \\<in> E\"\n    shows \"maximally_connected (add_edge a w b H) G\"\n  proof -\n    have \"(nodes_connected G v v') \\<longrightarrow> (nodes_connected (add_edge a w b H) v v')\" (is \"?lhs \\<longrightarrow> ?rhs\")\n      if vv': \"v \\<in> V\" \"v' \\<in> V\" for v v'\n    proof\n      assume ?lhs\n      with \\<open>maximally_connected H G\\<close> vv' obtain p where \"is_path_undir H v p v'\"\n        unfolding maximally_connected_def\n        by auto\n      with valid_graph.add_edge_is_path[OF valid_subgraph[OF \\<open>subgraph H G\\<close>] this]\n      show ?rhs\n        by auto\n    qed\n    then show ?thesis\n      unfolding maximally_connected_def\n      by auto\n  qed\n\n  lemma delete_edge_maximally_connected:\n    assumes \"maximally_connected H G\"\n    assumes \"subgraph H G\"\n    assumes pab: \"is_path_undir (delete_edge a w b H) a pab b\"\n    shows \"maximally_connected (delete_edge a w b H) G\"\n  proof -\n    from valid_subgraph[OF \\<open>subgraph H G\\<close>]\n    have valid_H: \"valid_graph H\" .\n    have \"(nodes_connected G v v') \\<longrightarrow> (nodes_connected (delete_edge a w b H) v v')\" (is \"?lhs \\<longrightarrow> ?rhs\")\n      if vv': \"v \\<in> V\" \"v' \\<in> V\" for v v'\n    proof\n      assume ?lhs\n      with \\<open>maximally_connected H G\\<close> vv' obtain p where p: \"is_path_undir H v p v'\"\n        unfolding maximally_connected_def\n        by auto\n      show ?rhs\n      proof (cases \"(a, w, b) \\<in> set p \\<or> (b, w, a) \\<in> set p\")\n        case True\n        with p valid_graph.is_path_undir_split_distinct[OF valid_H p, of a w b] obtain p' p'' u u'\n          where \"is_path_undir H v p' u \\<and> is_path_undir H u' p'' v'\" and\n            u: \"(u \\<in> {a, b} \\<and> u' \\<in> {a, b})\" and\n            \"(a, w, b) \\<notin> set p' \\<and> (b, w, a) \\<notin> set p' \\<and>\n            (a, w, b) \\<notin> set p'' \\<and> (b, w, a) \\<notin> set p''\"\n          by auto\n        with valid_graph.delete_edge_is_path[OF valid_H] obtain p' p''\n          where p': \"is_path_undir (delete_edge a w b H) v p' u \\<and>\n                 is_path_undir (delete_edge a w b H) u' p'' v'\"\n          by blast\n        from valid_graph.is_path_undir_sym[OF delete_edge_valid[OF valid_H] pab] obtain pab'\n          where \"is_path_undir (delete_edge a w b H) b pab' a\"\n          by auto\n        with assms u p' valid_graph.is_path_undir_split[OF delete_edge_valid[OF valid_H], of a w b v p' p'' v']\n          valid_graph.is_path_undir_split[OF delete_edge_valid[OF valid_H], of a w b v p' pab b]\n          valid_graph.is_path_undir_split[OF delete_edge_valid[OF valid_H], of a w b v \"p'@pab\" p'' v']\n          valid_graph.is_path_undir_split[OF delete_edge_valid[OF valid_H], of a w b v p' pab' a]\n          valid_graph.is_path_undir_split[OF delete_edge_valid[OF valid_H], of a w b v \"p'@pab'\" p'' v']\n        show ?thesis by auto\n      next\n        case False\n        with valid_graph.delete_edge_is_path[OF valid_H p] show ?thesis\n          by auto\n      qed\n    qed\n    then show ?thesis\n      unfolding maximally_connected_def\n      by auto\n  qed\n\n  lemma connected_impl_maximally_connected:\n    assumes \"connected_graph H\"\n    assumes subgraph: \"subgraph H G\"\n    shows \"maximally_connected H G\"\n    using assms\n    unfolding connected_graph_def connected_graph_axioms_def maximally_connected_def\n      subgraph_def\n    by blast\n\n  lemma add_edge_is_connected:\n    \"nodes_connected (add_edge a b c G) a c\"\n    \"nodes_connected (add_edge a b c G) c a\"\n  using valid_graph.is_path_undir_simps(2)[OF\n        add_edge_valid[OF valid_graph_axioms], of a b c a b c]\n      valid_graph.is_path_undir_simps(2)[OF\n        add_edge_valid[OF valid_graph_axioms], of a b c c b a]\n  by fastforce+\n\n  lemma swap_edges:\n    assumes \"nodes_connected (add_edge a w b G) v v'\"\n    assumes \"a \\<in> V\"\n    assumes \"b \\<in> V\"\n    assumes \"\\<not> nodes_connected G v v'\"\n    shows \"nodes_connected (add_edge v w' v' G) a b\"\n  proof -\n    from assms(1) obtain p where p: \"is_path_undir (add_edge a w b G) v p v'\"\n      by auto\n    have awb: \"(a, w, b) \\<in> set p \\<or> (b, w, a) \\<in> set p\"\n    proof (rule ccontr)\n      assume \"\\<not> ((a, w, b) \\<in> set p \\<or> (b, w, a) \\<in> set p)\"\n      with add_edge_was_path[OF p _ _ assms(2,3)] assms(4)\n      show False\n        by auto\n    qed\n    from valid_graph.is_path_undir_split_distinct[OF\n        add_edge_valid[OF valid_graph_axioms] p awb]\n    obtain p' p'' u u' where\n         \"is_path_undir (add_edge a w b G) v p' u \\<and>\n          is_path_undir (add_edge a w b G) u' p'' v'\" and\n          u: \"u \\<in> {a, b} \\<and> u' \\<in> {a, b}\" and\n          \"(a, w, b) \\<notin> set p' \\<and> (b, w, a) \\<notin> set p' \\<and>\n          (a, w, b) \\<notin> set p'' \\<and> (b, w, a) \\<notin> set p'' \"\n      by auto\n    with assms(2,3) add_edge_was_path\n    have paths: \"is_path_undir G v p' u \\<and>\n                 is_path_undir G u' p'' v'\"\n      by blast\n    with is_path_undir_split[of v p' p'' v'] assms(4)\n    have \"u \\<noteq> u'\"\n      by blast\n    from paths assms add_edge_is_path\n    have paths': \"is_path_undir (add_edge v w' v' G) v p' u \\<and>\n                  is_path_undir (add_edge v w' v' G) u' p'' v'\"\n      by blast\n    from add_edge_is_connected obtain p''' where\n      \"is_path_undir (add_edge v w' v' G) v' p''' v\"\n      by blast\n    with paths' valid_graph.is_path_undir_split[OF add_edge_valid[OF valid_graph_axioms], of v w' v' u' p'' p''' v]\n    have \"is_path_undir (add_edge v w' v' G) u' (p''@p''') v\"\n        by auto\n    with paths' valid_graph.is_path_undir_split[OF add_edge_valid[OF valid_graph_axioms], of v w' v' u' \"p''@p'''\" p' u]\n    have \"is_path_undir (add_edge v w' v' G) u' (p''@p'''@p') u\"\n        by auto\n    with u \\<open>u \\<noteq> u'\\<close> valid_graph.is_path_undir_sym[OF add_edge_valid[OF valid_graph_axioms] this]\n    show ?thesis\n      by auto\n  qed\n\n  lemma subgraph_impl_connected:\n    assumes \"connected_graph H\"\n    assumes subgraph: \"subgraph H G\"\n    shows \"connected_graph G\"\n    using assms is_path_undir_subgraph[OF _ subgraph] valid_graph_axioms\n    unfolding connected_graph_def connected_graph_axioms_def maximally_connected_def\n      subgraph_def\n    by blast\n\n  lemma add_node_connected:\n    assumes \"\\<forall>a\\<in>V - {v}. \\<forall>b\\<in>V - {v}. nodes_connected G a b\"\n    assumes \"(v, w, v') \\<in> E \\<or> (v', w, v) \\<in> E\"\n    assumes \"v \\<noteq> v'\"\n    shows \"\\<forall>a\\<in>V. \\<forall>b\\<in>V. nodes_connected G a b\"\n  proof -\n    have \"nodes_connected G a b\" if a: \"a\\<in>V\" and b: \"b\\<in>V\" for a b\n    proof (cases \"a = v\")\n      case True\n      show ?thesis\n      proof (cases \"b = v\")\n        case True\n        with \\<open>a = v\\<close> a is_path_undir_simps(1) show ?thesis\n          by blast\n      next\n        case False\n        from assms(2) have \"v' \\<in> V\"\n          by (auto simp: E_validD)\n        with b assms(1) \\<open>b \\<noteq> v\\<close> \\<open>v \\<noteq> v'\\<close> have \"nodes_connected G v' b\"\n          by blast\n        with assms(2) \\<open>a = v\\<close> is_path_undir.simps(2)[of G v v w v' _ b]\n        show ?thesis\n          by blast\n      qed\n    next\n      case False\n      show ?thesis\n      proof (cases \"b = v\")\n        case True\n        from assms(2) have \"v' \\<in> V\"\n          by (auto simp: E_validD)\n        with a assms(1) \\<open>a \\<noteq> v\\<close> \\<open>v \\<noteq> v'\\<close> have \"nodes_connected G a v'\"\n          by blast\n        with assms(2) \\<open>b = v\\<close> is_path_undir.simps(2)[of G v v w v' _ a]\n          is_path_undir_sym\n        show ?thesis\n          by blast\n      next\n        case False\n        with \\<open>a \\<noteq> v\\<close> assms(1) a b show ?thesis\n          by simp\n      qed\n    qed\n    then show ?thesis by simp\n  qed\nend\n\ncontext connected_graph\nbegin\n  lemma maximally_connected_impl_connected:\n    assumes \"maximally_connected H G\"\n    assumes subgraph: \"subgraph H G\"\n    shows \"connected_graph H\"\n    using assms connected_graph_axioms valid_subgraph[OF subgraph]\n    unfolding connected_graph_def connected_graph_axioms_def maximally_connected_def\n      subgraph_def\n    by auto\nend\n\ncontext forest\nbegin\n  lemma delete_edge_from_path:\n    assumes \"nodes_connected G a b\"\n    assumes \"subgraph H G\"\n    assumes \"\\<not> nodes_connected H a b\"\n    shows \"\\<exists>(x, w, y) \\<in> E - edges H.  (\\<not> nodes_connected (delete_edge x w y G) a b) \\<and>\n      (nodes_connected (add_edge a w' b (delete_edge x w y G)) x y)\"\n  proof -\n    from assms(1) obtain p where \"is_path_undir G a p b\"\n      by auto\n    from this assms(3) show ?thesis\n    proof (induction n == \"length p\" arbitrary: p a b rule: nat_less_induct)\n      case 1\n      from valid_subgraph[OF assms(2)] have valid_H: \"valid_graph H\" .\n      show ?case\n      proof (cases p)\n        case Nil\n        with 1(2) have \"a = b\"\n          by simp\n        with 1(2) assms(2) have \"is_path_undir H a [] b\"\n          unfolding subgraph_def\n          by auto\n        with 1(3) show ?thesis\n          by blast\n      next\n        case (Cons e p')\n        obtain a2 a' w where \"e = (a2, w, a')\"\n          using prod_cases3 by blast\n        with 1(2) Cons have e: \"e = (a, w, a')\"\n          by simp\n        with 1(2) Cons obtain e1 e2 where e12: \"e = (e1, w, e2) \\<or> e = (e2, w, e1)\" and\n          edge_e12: \"(e1, w, e2) \\<in> E\"\n          by auto\n        from 1(2) Cons e have \"is_path_undir G a' p' b\"\n          by simp\n        with is_path_undir_split_distinct[OF this, of a w a'] Cons\n        obtain p'_dst u' where  p'_dst: \"is_path_undir G u' p'_dst b \\<and> u' \\<in> {a, a'}\" and\n            e_not_in_p': \"(a, w, a') \\<notin> set p'_dst \\<and> (a', w, a) \\<notin> set p'_dst\" and\n            len_p': \"length p'_dst < length p\"\n          by fastforce\n        show ?thesis\n        proof (cases \"u' = a'\")\n          case False\n          with 1 len_p' p'_dst show ?thesis\n            by auto\n        next\n          case True\n          with p'_dst have path_p': \"is_path_undir G a' p'_dst b\"\n            by auto\n          show ?thesis\n          proof (cases \"(e1, w, e2) \\<in> edges H\")\n            case True\n            have \"\\<not> nodes_connected H a' b\"\n            proof\n              assume \"nodes_connected H a' b\"\n              then obtain p_H where \"is_path_undir H a' p_H b\"\n                by auto\n              with True e12 e have \"is_path_undir H a (e#p_H) b\"\n                by auto\n              with 1(3) show False\n                by simp\n            qed\n            with path_p' 1(1) len_p' obtain x z y where xy: \"(x, z, y) \\<in> E - edges H\" and\n              IH1: \"(\\<not>nodes_connected (delete_edge x z y G) a' b)\" and\n              IH2: \"(nodes_connected (add_edge a' w' b (delete_edge x z y G)) x y)\"\n              by blast\n            with True have xy_neq_e: \"(x,z,y) \\<noteq> (e1, w, e2)\"\n              by auto\n            have thm1: \"\\<not> nodes_connected (delete_edge x z y G) a b\"\n            proof\n              assume \"nodes_connected (delete_edge x z y G) a b\"\n              then obtain p_e where \"is_path_undir (delete_edge x z y G) a p_e b\"\n                by auto\n              with edge_e12 e12 e xy_neq_e have \"is_path_undir (delete_edge x z y G) a' ((a', w, a)#p_e) b\"\n                by auto\n              with IH1 show False\n                by blast\n            qed\n            from IH2 obtain p_xy where \"is_path_undir (add_edge a' w' b (delete_edge x z y G)) x p_xy y\"\n              by auto\n            from valid_graph.swap_add_edge_in_path[OF delete_edge_valid[OF valid_graph_axioms] this, of w a w'] edge_e12\n              e12 e edges_delete_edge[of x z y G] xy_neq_e\n            have thm2: \"nodes_connected (add_edge a w' b (delete_edge x z y G)) x y\"\n              by blast\n            with thm1 show ?thesis\n              using xy by auto\n          next\n            case False\n            have thm1: \"\\<not> nodes_connected (delete_edge e1 w e2 G) a b\"\n            proof\n              assume \"nodes_connected (delete_edge e1 w e2 G) a b\"\n              then obtain p_e where p_e: \"is_path_undir (delete_edge e1 w e2 G) a p_e b\"\n                by auto\n              from delete_edge_is_path[OF path_p', of e1 w e2] e_not_in_p' e12 e\n              have \"is_path_undir (delete_edge e1 w e2 G) a' p'_dst b\"\n                by auto\n              with valid_graph.is_path_undir_sym[OF delete_edge_valid[OF valid_graph_axioms] this]\n              obtain p_rev where \"is_path_undir (delete_edge e1 w e2 G) b p_rev a'\"\n                by auto\n              with p_e valid_graph.is_path_undir_split[OF delete_edge_valid[OF valid_graph_axioms]]\n              have \"is_path_undir (delete_edge e1 w e2 G) a (p_e@p_rev) a'\"\n                by auto\n              with cycle_free edge_e12 e12 e valid_graph.is_path_undir_sym[OF delete_edge_valid[OF valid_graph_axioms] this]\n              show False\n                unfolding valid_graph_def\n                by auto\n            qed\n            from valid_graph.is_path_undir_split[OF add_edge_valid[OF delete_edge_valid[OF valid_graph_axioms]]]\n              valid_graph.add_edge_is_path[OF delete_edge_valid[OF valid_graph_axioms]\n                                              delete_edge_is_path[OF path_p', of e1 w e2], of a w' b]\n              valid_graph.is_path_undir_simps(2)[OF add_edge_valid[OF delete_edge_valid[OF valid_graph_axioms]],\n                                                 of a w' b e1 w e2 b w' a]\n              e_not_in_p' e12 e\n            have \"is_path_undir (add_edge a w' b (delete_edge e1 w e2 G)) a' (p'_dst@[(b,w',a)]) a\"\n              by auto\n            with valid_graph.is_path_undir_sym[OF add_edge_valid[OF delete_edge_valid[OF valid_graph_axioms]] this]\n              e12 e\n            have \"nodes_connected (add_edge a w' b (delete_edge e1 w e2 G)) e1 e2\"\n              by blast\n            with thm1 show ?thesis\n              using False edge_e12 by auto\n          qed\n        qed\n      qed\n    qed\n  qed\n\n  lemma forest_add_edge:\n    assumes \"a \\<in> V\"\n    assumes \"b \\<in> V\"\n    assumes \"\\<not> nodes_connected G a b\"\n    shows \"forest (add_edge a w b G)\"\n  proof -\n    from assms(3) have \"\\<not> is_path_undir G a [(a, w, b)] b\"\n      by blast\n    with assms(2) have awb: \"(a, w, b) \\<notin> E \\<and> (b, w, a) \\<notin> E\"\n      by auto\n    have \"\\<not> nodes_connected (delete_edge v w' v' (add_edge a w b G)) v v'\"\n       if e: \"(v,w',v')\\<in> edges (add_edge a w b G)\" for v w' v'\n    proof (cases \"(v,w',v') = (a, w, b)\")\n      case True\n      with assms awb delete_add_edge[of a G b w]\n      show ?thesis by simp\n    next\n      case False\n      with e have e': \"(v,w',v')\\<in> edges G\"\n        by auto\n      show ?thesis\n      proof\n        assume asm: \"nodes_connected (delete_edge v w' v' (add_edge a w b G)) v v'\"\n        with swap_delete_add_edge[OF False, of G]\n          valid_graph.swap_edges[OF delete_edge_valid[OF valid_graph_axioms], of a w b v w' v' v v' w']\n          add_delete_edge[OF e'] cycle_free assms(1,2) e'\n        have \"nodes_connected G a b\"\n          by force\n        with assms show False\n          by simp\n      qed\n    qed\n    with cycle_free add_edge_valid[OF valid_graph_axioms] show ?thesis\n      unfolding forest_def forest_axioms_def by auto\n  qed\n\n  lemma forest_subsets:\n    assumes \"valid_graph H\"\n    assumes \"edges H \\<subseteq> E\"\n    assumes \"nodes H \\<subseteq> V\"\n    shows \"forest H\"\n  proof -\n    have \"\\<not> nodes_connected (delete_edge a w b H) a b\"\n      if e: \"(a, w, b)\\<in>edges H\" for a w b\n    proof\n      assume asm: \"nodes_connected (delete_edge a w b H) a b\"\n      from \\<open>edges H \\<subseteq> E\\<close> have edges: \"edges (delete_edge a w b H) \\<subseteq> edges (delete_edge a w b G)\"\n        by auto\n      from \\<open>nodes H \\<subseteq> V\\<close> have nodes: \"nodes (delete_edge a w b H) \\<subseteq> nodes (delete_edge a w b G)\"\n        by auto\n      from asm valid_graph.subset_was_path[OF delete_edge_valid[OF valid_graph_axioms] _ edges nodes]\n      have \"nodes_connected (delete_edge a w b G) a b\"\n        by auto\n      with cycle_free e \\<open>edges H \\<subseteq> E\\<close> show False\n        by blast\n    qed\n    with assms(1) show ?thesis\n    unfolding forest_def forest_axioms_def\n    by auto\n  qed\n\n  lemma subgraph_forest:\n    assumes \"subgraph H G\"\n    shows \"forest H\"\n    using assms forest_subsets valid_subgraph\n    unfolding subgraph_def\n    by simp\n\n  lemma forest_delete_edge: \"forest (delete_edge a w c G)\"\n    using forest_subsets[OF delete_edge_valid[OF valid_graph_axioms]]\n    unfolding delete_edge_def\n    by auto\n\n  lemma forest_delete_node: \"forest (delete_node n G)\"\n    using forest_subsets[OF delete_node_valid[OF valid_graph_axioms]]\n    unfolding delete_node_def\n    by auto\n\n  lemma connected_leaf_exists:\n    assumes \"finite_graph G\"\n    assumes \"v\\<in>V\"\n    assumes \"degree G v \\<noteq> 0\"\n    shows \"\\<exists>v'\\<in>V. v \\<noteq> v' \\<and> nodes_connected G v v' \\<and> degree G v' = 1\"\n    using assms forest_axioms\n    proof (induction n == \"card (edges G)\" arbitrary: G v)\n      case 0\n      from \\<open>degree G v \\<noteq> 0\\<close> have \"edges G \\<noteq> {}\"\n        unfolding degree_def\n        by auto\n      with 0 show ?case\n        unfolding finite_graph_def finite_graph_axioms_def\n        by simp\n    next\n      case (Suc n)\n      from \\<open>degree G v \\<noteq> 0\\<close> have \"edges G \\<noteq> {}\"\n        unfolding degree_def\n        by auto\n      then obtain a w b where e: \"(a,w,b)\\<in>edges G\"\n        by auto\n      from Suc e forest.forest_delete_edge[OF \\<open>forest G\\<close>]\n      have prems: \"n = card (edges (delete_edge a w b G))\"\n        \"finite_graph (delete_edge a w b G)\"\n        \"forest (delete_edge a w b G)\"\n        unfolding finite_graph_def finite_graph_axioms_def\n        by auto\n      show ?case\n      proof (cases \"degree (delete_edge a w b G) v \\<noteq> 0\")\n        case True\n        from Suc(1)[OF prems(1,2) _ True prems(3)] Suc(4) obtain v'\n          where v': \"v'\\<in>nodes (delete_edge a w b G)\" \"v \\<noteq> v'\"\n            \"nodes_connected (delete_edge a w b G) v v'\" \"degree (delete_edge a w b G) v' = 1\"\n          by auto\n        with valid_graph.delete_edge_was_path[OF forest.axioms(1)[OF \\<open>forest G\\<close>]]\n        have vv': \"nodes_connected G v v'\"\n          by blast\n        show ?thesis\n        proof (cases \"a = v' \\<or> b = v'\")\n          case True\n          then obtain x where x: \"a = v' \\<and> b = x \\<or> a = x \\<and> b = v'\"\n            by blast\n          show ?thesis\n          proof (cases \"degree (delete_edge a w b G) x \\<noteq> 0\")\n            case True\n            from Suc(1)[OF prems(1,2) _ True prems(3)] x\n              valid_graph.E_validD[OF forest.axioms(1)[OF \\<open>forest G\\<close>] e]\n            obtain x' where x': \"x'\\<in>nodes (delete_edge a w b G)\" \"x \\<noteq> x'\"\n                \"nodes_connected (delete_edge a w b G) x x'\" \"degree (delete_edge a w b G) x' = 1\"\n              by auto\n            have \"{e \\<in> edges (delete_edge a w b G). fst e = x' \\<or> snd (snd e) = x'} = \n                {e \\<in> edges G. fst e = x' \\<or> snd (snd e) = x'}\"\n              proof (cases \"a = x' \\<or> b = x'\")\n                case True\n                with x' x valid_graph.is_path_undir_sym[OF delete_edge_valid[OF forest.axioms(1)[OF \\<open>forest G\\<close>]], of a w b x _ x']\n                have \"nodes_connected (delete_edge a w b G) a b\"\n                  by blast\n                with forest.cycle_free[OF \\<open>forest G\\<close>] e\n                show ?thesis by blast\n              next\n                case False\n                then show ?thesis by auto\n              qed\n            with x' valid_graph.delete_edge_was_path[OF forest.axioms(1)[OF \\<open>forest G\\<close>]]\n            have x'': \"x'\\<in>nodes G \\<and> nodes_connected G x x' \\<and> degree G x' = 1\"\n              unfolding degree_def\n              by fastforce\n            from x''\n              is_path_undir.simps(2)[of G v' v' w x _ x'] e x\n            have \"nodes_connected G v' x'\"\n              by blast\n            with vv' have \"nodes_connected G v x'\"\n              using valid_graph.is_path_undir_split[OF forest.axioms(1)[OF \\<open>forest G\\<close>], of v _ _ x']\n              by blast\n            moreover have \"v \\<noteq> x'\"\n            proof (rule ccontr)\n              assume \"\\<not> v \\<noteq> x'\"\n              with x'(3) v'(3) x\n                valid_graph.is_path_undir_split[OF delete_edge_valid[OF forest.axioms(1)[OF \\<open>forest G\\<close>]], of a w b x _ _ v']\n                valid_graph.is_path_undir_sym[OF delete_edge_valid[OF forest.axioms(1)[OF \\<open>forest G\\<close>]], of a w b x _ v']\n              have \"nodes_connected (delete_edge a w b G) a b\"\n                by blast\n              with forest.cycle_free[OF \\<open>forest G\\<close>] e\n              show False by blast\n            qed\n            ultimately show ?thesis\n              using x'' by auto\n          next\n            case False\n            have \"{e \\<in> edges G. fst e = x \\<or> snd (snd e) = x} - {(a,w,b)} =\n              {e \\<in> edges (delete_edge a w b G). fst e = x \\<or> snd (snd e) = x}\"\n              by auto\n            also from False finite_graph.finite_E[OF \\<open>finite_graph G\\<close>]\n            have \"{e \\<in> edges (delete_edge a w b G). fst e = x \\<or> snd (snd e) = x} = {}\"\n              unfolding degree_def\n              by auto\n            finally have \"{e \\<in> edges G. fst e = x \\<or> snd (snd e) = x} = {(a,w,b)}\"\n              using e x\n              by auto\n            then have \"degree G x = 1\"\n              unfolding degree_def\n              by auto\n            moreover from x valid_graph.E_validD[OF forest.axioms(1)[OF \\<open>forest G\\<close>] e]\n            have \"x\\<in>nodes G\"\n              by blast\n            moreover have \"v \\<noteq> x\"\n            proof (rule ccontr)\n              assume \"\\<not> v \\<noteq> x\"\n              with v'(3) x\n                valid_graph.is_path_undir_sym[OF delete_edge_valid[OF forest.axioms(1)[OF \\<open>forest G\\<close>]], of a w b v _ v']\n              have \"nodes_connected (delete_edge a w b G) a b\"\n                by blast\n              with forest.cycle_free[OF \\<open>forest G\\<close>] e\n              show False by blast\n            qed\n            moreover from vv' e x have \"nodes_connected G v x\"\n              using valid_graph.is_path_undir_split[OF forest.axioms(1)[OF \\<open>forest G\\<close>], of v _ _ x]\n                valid_graph.is_path_undir_simps(2)[OF forest.axioms(1)[OF \\<open>forest G\\<close>], of v' w x]\n              by blast\n            ultimately show ?thesis\n              by auto\n          qed\n        next\n          case False\n          then have \"{e \\<in> edges (delete_edge a w b G). fst e = v' \\<or> snd (snd e) = v'} = \n            {e \\<in> edges G. fst e = v' \\<or> snd (snd e) = v'}\"\n            by auto\n          with v' valid_graph.delete_edge_was_path[OF forest.axioms(1)[OF \\<open>forest G\\<close>]]\n          have \"v'\\<in>nodes G \\<and> v \\<noteq> v' \\<and> nodes_connected G v v' \\<and> degree G v' = 1\"\n            unfolding degree_def\n            by fastforce\n          then show ?thesis\n            by auto\n        qed\n      next\n        case False\n        from Suc(5) have not_empty: \"{e \\<in> edges G. fst e = v \\<or> snd (snd e) = v} \\<noteq> {}\"\n          unfolding degree_def\n          by force\n        have \"{e \\<in> edges G. fst e = v \\<or> snd (snd e) = v} - {(a,w,b)} =\n          {e \\<in> edges (delete_edge a w b G). fst e = v \\<or> snd (snd e) = v}\"\n          by auto\n        also from False finite_graph.finite_E[OF \\<open>finite_graph G\\<close>]\n        have \"{e \\<in> edges (delete_edge a w b G). fst e = v \\<or> snd (snd e) = v} = {}\"\n          unfolding degree_def\n          by auto\n        finally have \"{e \\<in> edges G. fst e = v \\<or> snd (snd e) = v} = {(a,w,b)}\"\n          using not_empty e\n          by auto\n        then have \"fst (a,w,b) = v \\<or> snd (snd (a,w,b)) = v\"\n          by blast\n        then obtain x where x: \"a = x \\<and> b = v \\<or> a = v \\<and> b = x\"\n          by auto\n        show ?thesis\n        proof (cases \"degree G x = 1\")\n          case True\n          moreover from valid_graph.E_validD[OF forest.axioms(1)[OF \\<open>forest G\\<close>] e] e x\n            valid_graph.is_path_undir_simps(2)[OF forest.axioms(1)[OF \\<open>forest G\\<close>], of v w x]\n          have \"nodes_connected G v x\"\n            by blast\n          moreover have \"v \\<noteq> x\"\n            proof (rule ccontr)\n              assume asm: \"\\<not> v \\<noteq> x\"\n              with Suc(4) x\n                valid_graph.is_path_undir_simps(1)[OF delete_edge_valid[OF forest.axioms(1)[OF \\<open>forest G\\<close>]], of v w v v]\n              have \"nodes_connected (delete_edge v w v G) v v\"\n                by fastforce\n              with forest.cycle_free[OF \\<open>forest G\\<close>] e x asm\n              show False by blast\n            qed\n          ultimately show ?thesis\n            using valid_graph.E_validD[OF forest.axioms(1)[OF \\<open>forest G\\<close>] e] x\n            by auto\n        next\n          case False\n          have \"degree (delete_edge a w b G) x \\<noteq> 0\"\n          proof (rule ccontr)\n            assume asm: \"\\<not> degree (delete_edge a w b G) x \\<noteq> 0\"\n            have \"{e \\<in> edges G. fst e = x \\<or> snd (snd e) = x} - {(a,w,b)} =\n              {e \\<in> edges (delete_edge a w b G). fst e = x \\<or> snd (snd e) = x}\"\n              by auto\n            also from asm finite_graph.finite_E[OF \\<open>finite_graph G\\<close>]\n            have \"{e \\<in> edges (delete_edge a w b G). fst e = x \\<or> snd (snd e) = x} = {}\"\n              unfolding degree_def\n              by auto\n            finally have \"{e \\<in> edges G. fst e = x \\<or> snd (snd e) = x} = {(a,w,b)}\"\n              using e x\n              by auto\n            with False show False\n              unfolding degree_def\n              by simp\n          qed\n          from Suc(1)[OF prems(1,2) _ this prems(3)] x\n              valid_graph.E_validD[OF forest.axioms(1)[OF \\<open>forest G\\<close>] e]\n            obtain x' where x': \"x'\\<in>nodes (delete_edge a w b G)\" \"x \\<noteq> x'\"\n                \"nodes_connected (delete_edge a w b G) x x'\" \"degree (delete_edge a w b G) x' = 1\"\n              by auto\n          have \"{e \\<in> edges (delete_edge a w b G). fst e = x' \\<or> snd (snd e) = x'} = \n                {e \\<in> edges G. fst e = x' \\<or> snd (snd e) = x'}\"\n            proof (cases \"a = x' \\<or> b = x'\")\n              case True\n              with x' x valid_graph.is_path_undir_sym[OF delete_edge_valid[OF forest.axioms(1)[OF \\<open>forest G\\<close>]], of a w b x _ x']\n              have \"nodes_connected (delete_edge a w b G) a b\"\n                by blast\n              with forest.cycle_free[OF \\<open>forest G\\<close>] e\n              show ?thesis by blast\n            next\n              case False\n              then show ?thesis by auto\n            qed\n          with x' valid_graph.delete_edge_was_path[OF forest.axioms(1)[OF \\<open>forest G\\<close>]]\n          have x'': \"x'\\<in>nodes G \\<and> nodes_connected G x x' \\<and> degree G x' = 1\"\n            unfolding degree_def\n            by fastforce\n          with x e have \"nodes_connected G v x'\"\n            using is_path_undir.simps(2)[of G v v w x _ x']\n            by blast\n          moreover have \"v \\<noteq> x'\"\n          proof (rule ccontr)\n            assume asm: \"\\<not> v \\<noteq> x'\"\n            with Suc(4) x x'(3)\n                valid_graph.is_path_undir_sym[OF delete_edge_valid[OF forest.axioms(1)[OF \\<open>forest G\\<close>]], of a w b x _ x']\n              have \"nodes_connected (delete_edge a w b G) a b\"\n                by fastforce\n              with forest.cycle_free[OF \\<open>forest G\\<close>] e x asm\n            show False by blast\n          qed\n          ultimately show ?thesis\n            using x'' by auto\n        qed\n      qed\n    qed\n\n  corollary leaf_exists:\n    assumes \"finite_graph G\"\n    assumes \"E \\<noteq> {}\"\n    shows \"\\<exists>v\\<in>V. degree G v = 1\"\n  proof -\n    from assms(1) interpret finite_graph G .\n    from \\<open>E \\<noteq> {}\\<close> obtain a w b where e: \"(a,w,b)\\<in>E\"\n      by auto\n    then have \"(a,w,b)\\<in>{e \\<in> E. fst e = a \\<or> snd (snd e) = a}\"\n      by simp\n    with e finite_E have \"degree G a \\<noteq> 0\" \"a\\<in>V\"\n      unfolding degree_def\n      by (auto simp: E_validD)\n    from connected_leaf_exists[OF \\<open>finite_graph G\\<close> \\<open>a\\<in>V\\<close> \\<open>degree G a \\<noteq> 0\\<close>]\n    show ?thesis\n      by auto\n  qed\n\n  lemma connected_by_number_of_edges:\n    assumes \"finite_graph G\"\n    shows  \"(card E = card V - 1) = (connected_graph G)\"\n  using assms forest_axioms\n  proof (induction n == \"card (nodes G) - 1\" arbitrary: G)\n    case 0\n    show ?case (is \"?lhs = ?rhs\")\n    proof\n      assume ?lhs\n      show ?rhs\n      proof (cases \"card (nodes G) = 0\")\n        case True\n        with \\<open>forest G\\<close> finite_graph.finite_V[OF \\<open>finite_graph G\\<close>] show ?thesis\n          unfolding forest_def connected_graph_def connected_graph_axioms_def\n        by auto\n      next\n        case False\n        with 0(1,2) have \"card (nodes G) = 1\"\n          by fastforce\n        with card_1_singletonE obtain v where \"nodes G = {v}\" .\n        moreover from this is_path_undir.simps(1)[of G v v]\n        have \"nodes_connected G v v\"\n          by blast\n        ultimately show ?thesis\n          using \\<open>forest G\\<close>\n          unfolding forest_def connected_graph_def connected_graph_axioms_def\n          by auto\n      qed\n    next\n      assume ?rhs\n      have \"edges G = {}\"\n      proof (cases \"card (nodes G) = 0\")\n        case True\n        with finite_graph.finite_V[OF \\<open>finite_graph G\\<close>]\n          valid_graph.E_valid[OF forest.axioms(1)[OF \\<open>forest G\\<close>]]\n        show ?thesis\n          by simp\n      next\n        case False\n        with 0(1,2) have \"card (nodes G) = 1\"\n          by fastforce\n        with card_1_singletonE obtain v where v: \"nodes G = {v}\" .\n        show ?thesis\n        proof (rule ccontr)\n          assume \"edges G \\<noteq> {}\"\n          then obtain a w b where e: \"(a,w,b)\\<in>edges G\"\n            by auto\n          from v valid_graph.E_validD[OF forest.axioms(1)[OF \\<open>forest G\\<close>] this]\n          have \"a = v\" \"b = v\"\n            by auto\n          with v is_path_undir.simps(1)[of \"delete_edge a w b G\" a b]\n          have \"nodes_connected (delete_edge a w b G) a b\"\n            by fastforce\n          with forest.cycle_free[OF \\<open>forest G\\<close>] e show False\n            by auto\n        qed\n      qed\n      with 0(1) show ?lhs\n        by simp\n    qed\n  next\n    case (Suc n)\n    from forest.axioms(1)[OF \\<open>forest G\\<close>] have valid_G: \"valid_graph G\" .\n    show ?case\n    proof (cases \"edges G = {}\")\n      case True\n      with Suc(2) have \"card (nodes G) > 1\"\n        by simp\n      show ?thesis (is \"?lhs = ?rhs\")\n      proof\n        assume ?lhs\n        with True \\<open>card (nodes G) > 1\\<close> show ?rhs\n          by auto\n      next\n        assume ?rhs\n        from \\<open>card (nodes G) > 1\\<close> card_le_Suc_iff[OF finite_graph.finite_V[OF \\<open>finite_graph G\\<close>]]\n        obtain a B where a: \"nodes G = insert a B \\<and> a \\<notin> B \\<and> 1 \\<le> card B \\<and> finite B\"\n          by fastforce\n        with card_le_Suc_iff[of B 0] obtain b where \"b \\<in> B\"\n          by auto\n        with a have ab: \"a\\<in>nodes G\" \"b\\<in>nodes G\" \"a\\<noteq>b\"\n          by auto\n        with connected_graph.connected[OF \\<open>?rhs\\<close>] have \"nodes_connected G a b\"\n          by blast\n        with ab True show ?lhs\n          using is_path_undir.elims(2)[of G a _ b]\n          by auto\n      qed\n    next\n      case False\n      from forest.leaf_exists[OF \\<open>forest G\\<close> \\<open>finite_graph G\\<close> \\<open>edges G \\<noteq> {}\\<close>]\n      obtain v where v: \"v\\<in>nodes G\" \"degree G v = 1\"\n        by blast\n      with card_1_singletonE\n      obtain e where e: \"{e\\<in>edges G. fst e = v \\<or> snd (snd e) = v} = {e}\"\n        unfolding degree_def\n        by blast\n      then have e': \"e \\<in> edges G\" \"fst e = v \\<or> snd (snd e) = v\"\n        by auto\n      with prod_cases3 obtain a w b where awb: \"e = (a, w, b)\"\n        by blast\n      with e' obtain v' where\n        v': \"(v, w, v') \\<in> edges G \\<or> (v', w, v) \\<in> edges G\"\n        by auto\n      from valid_graph.is_path_undir_simps(1)[OF delete_edge_valid[OF valid_G], of v w v v] v(1)\n      have \"nodes_connected (delete_edge v w v G) v v\"\n        unfolding delete_edge_def\n        by fastforce\n      from \\<open>nodes_connected (delete_edge v w v G) v v\\<close> v' \\<open>forest G\\<close>\n      have v_neq_v': \"v \\<noteq> v'\"\n        unfolding forest_def forest_axioms_def\n        by auto\n      let ?G = \"delete_node v (delete_edge a w b G)\"\n      from awb have edges_del_edge: \"edges (delete_edge a w b G) = edges G - {e}\"\n        by simp\n      with e have \"{e\\<in>edges (delete_edge a w b G). fst e = v \\<or> snd (snd e) = v} = {}\"\n        by blast\n      with edges_del_edge have edges: \"edges ?G = edges G - {e}\"\n        unfolding delete_node_def\n        by auto\n      have nodes: \"nodes ?G = nodes G - {v}\"\n        unfolding delete_node_def delete_edge_def\n        by auto\n      from card_Diff_singleton[OF finite_graph.finite_V[OF \\<open>finite_graph G\\<close>] v(1)] Suc(2) nodes\n      have \"n = card (nodes ?G) - 1\"\n        by simp\n      from forest.forest_delete_node[OF forest.forest_delete_edge[OF \\<open>forest G\\<close>]]\n      have \"forest ?G\" .\n      with \\<open>finite_graph G\\<close> nodes edges\n      have \"finite_graph ?G\"\n        unfolding finite_graph_def finite_graph_axioms_def forest_def\n        by auto\n      from Suc(1)[OF \\<open>n = card (nodes ?G) - 1\\<close> \\<open>finite_graph ?G\\<close> \\<open>forest ?G\\<close>]\n      have IH: \"(card (edges ?G) = card (nodes ?G) - 1) = connected_graph ?G\" .\n      show ?thesis (is \"?lhs = ?rhs\")\n      proof\n        assume ?lhs\n        with v(1) e'(1) have card: \"card (edges ?G) = card (nodes ?G) - 1\"\n          by (simp add: finite_graph.finite_E[OF \\<open>finite_graph G\\<close>] \\<open>card (nodes G - {v}) = card (nodes G) - 1\\<close> edges nodes)\n        with IH show ?rhs\n          using valid_G nodes\n            valid_graph.add_node_connected[OF valid_G _ v' v_neq_v']\n            valid_graph.delete_edge_was_path[OF valid_G\n            valid_graph.delete_node_was_path[OF delete_edge_valid[OF valid_G]], of v a w b]\n          unfolding connected_graph_def connected_graph_axioms_def\n          by blast\n      next\n        assume asm: ?rhs\n        have \"nodes_connected ?G x y\"\n          if xy: \"x\\<in>nodes ?G\" \"y\\<in>nodes ?G\" for x y\n        proof -\n          from xy have \"x\\<noteq>v\" \"y\\<noteq>v\"\n            unfolding delete_node_def\n            by auto\n          from xy have xy': \"x\\<in>nodes G\" \"y\\<in>nodes G\"\n            unfolding delete_node_def delete_edge_def\n            by auto\n          with asm obtain p where p: \"is_path_undir G x p y\"\n            unfolding connected_graph_def connected_graph_axioms_def\n            by auto\n          have \"\\<exists>p'. is_path_undir G x' p' y' \\<and> (a,w,b)\\<notin>set p' \\<and> (b,w,a)\\<notin>set p'\"\n            if cond:\"is_path_undir G x' p y'\" \"x'\\<noteq>v\" \"y'\\<noteq>v\" for x' y'\n            using cond\n          proof (induction n == \"length p\"  arbitrary: p x' y' rule: nat_less_induct)\n            case 1\n            then show ?case\n            proof (cases p)\n              case Nil\n              with 1 show ?thesis by fastforce\n            next\n              case (Cons v12 p')\n              from prod_cases3 obtain v1 w' v2 where \"v12 = (v1, w', v2)\" .\n              with 1(2) Cons have p': \"is_path_undir G v2 p' y'\" \"(v1, w', v2)\\<in>edges G \\<or> (v2, w', v1)\\<in>edges G\"\n                \"x' = v1\"\n                by auto\n              show ?thesis\n              proof (cases \"(v1, w', v2) = (a,w,b) \\<or> (v1, w', v2) = (b,w,a)\")\n                case True\n                with \\<open>x' \\<noteq> v\\<close> p'(2,3) e'(2) awb have \"v2 = v\"\n                  by auto\n                show ?thesis\n                proof (cases p')\n                  case Nil\n                  with p' have \"v2 = y'\"\n                    by simp\n                  with 1 \\<open>v2 = v\\<close> show ?thesis\n                    by auto\n                next\n                  case (Cons e' p'')\n                  from prod_cases3 obtain ea ew eb where e': \"e' = (ea, ew, eb)\" .\n                  with p'(1) Cons have p'': \"v2 = ea\" \"is_path_undir G eb p'' y'\"\n                    \"(ea, ew, eb) \\<in> edges G \\<or> (eb, ew, ea) \\<in> edges G\"\n                    by auto\n                  from p''(1,3) \\<open>v2 = v\\<close> have \"(ea,ew,eb)\\<in>{e \\<in> edges G. fst e = v \\<or> snd (snd e) = v} \\<or>\n                    (eb,ew,ea)\\<in>{e \\<in> edges G. fst e = v \\<or> snd (snd e) = v}\"\n                    by auto\n                  with e awb e' have \"e' = (a,w,b) \\<or> e' = (b,w,a)\"\n                    by auto\n                  from \\<open>p' = e'#p''\\<close> \\<open>p = v12#p'\\<close> have len: \"length p'' < length p\"\n                    by auto\n                  have \"a \\<noteq> b\"\n                  proof (rule ccontr)\n                    assume \"\\<not> a \\<noteq> b\"\n                    with valid_graph.is_path_undir_simps(1)[OF delete_edge_valid[OF \\<open>valid_graph G\\<close>], of a w b a]\n                      valid_graph.E_validD[OF \\<open>valid_graph G\\<close> \\<open>e\\<in>edges G\\<close>[unfolded awb]]\n                    have \"nodes_connected (delete_edge a w b G) a b\"\n                      by fastforce\n                    with forest.cycle_free[OF \\<open>forest G\\<close>] \\<open>e\\<in>edges G\\<close>[unfolded awb]\n                    show False\n                      by auto\n                  qed\n                  with e' \\<open>e' = (a,w,b) \\<or> e' = (b,w,a)\\<close> \\<open>v2 = ea\\<close> \\<open>v2 = v\\<close>\n                  have \"eb \\<noteq> v\"\n                    by blast\n                  with 1(1) len p''(2) 1(4) obtain p''' where p''': \"is_path_undir G eb p''' y'\"\n                    \"(a, w, b) \\<notin> set p''' \\<and> (b, w, a) \\<notin> set p'''\"\n                    by blast\n                  from True \\<open>x' = v1\\<close> \\<open>e' = (a,w,b) \\<or> e' = (b,w,a)\\<close> e' \\<open>v2 = ea\\<close>\n                  have \"x' = eb\"\n                    by blast\n                  with p''' show ?thesis\n                    by blast\n                qed\n              next\n                case False\n                from e p'(2) awb False have \"(v1, w', v2) \\<notin> {e \\<in> edges G. fst e = v \\<or> snd (snd e) = v}\"\n                  \"(v2, w', v1) \\<notin> {e \\<in> edges G. fst e = v \\<or> snd (snd e) = v}\"\n                  by auto\n                with p'(2) have \"v2 \\<noteq> v\"\n                  by auto\n                from Cons have \"length p' < length p\"\n                  by simp\n                with 1(1) p'(1) \\<open>v2 \\<noteq> v\\<close> 1(4) obtain p'' where \"is_path_undir G v2 p'' y'\"\n                  \"(a, w, b) \\<notin> set p'' \\<and> (b, w, a) \\<notin> set p''\"\n                  by blast\n                with p'(2) False 1(2) \\<open>x' = v1\\<close> have \"is_path_undir G x' ((v1, w', v2) # p'') y'\"\n                  \"(a, w, b) \\<notin> set ((v1, w', v2) # p'') \\<and> (b, w, a) \\<notin> set ((v1, w', v2) # p'')\"\n                  by auto\n                then show ?thesis\n                  by blast\n              qed\n            qed\n          qed\n          with \\<open>x\\<noteq>v\\<close> \\<open>y\\<noteq>v\\<close> p obtain p where p: \"is_path_undir G x p y \\<and> (a, w, b) \\<notin> set p \\<and> (b, w, a) \\<notin> set p\"\n            by blast\n          then have p_subset_E: \"\\<forall>v1 w' v2. (v1, w', v2) \\<in> set p \\<longrightarrow> (v1, w', v2) \\<in> edges G \\<or> (v2, w', v1) \\<in> edges G\"\n            by (induction G x p y rule: is_path_undir.induct) auto\n          have \"v1 \\<noteq> v \\<and> v2 \\<noteq> v\"\n            if v12: \"(v1, w', v2) \\<in> set p\" for v1 w' v2\n          proof -\n            from v12 p awb have \"e \\<noteq> (v1, w', v2) \\<and> e \\<noteq> (v2, w', v1)\"\n              by auto\n            moreover from p_subset_E v12 have v12': \"(v1, w', v2) \\<in> edges G \\<or> (v2, w', v1) \\<in> edges G\"\n              by auto\n            ultimately have \"(v1, w', v2) \\<notin> {e \\<in> edges G. fst e = v \\<or> snd (snd e) = v}\"\n                \"(v2, w', v1) \\<notin> {e \\<in> edges G. fst e = v \\<or> snd (snd e) = v}\"\n              using e\n              by auto\n            with v12' show ?thesis\n              by auto\n          qed\n          then have \"v \\<notin> fst ` set p \\<union> snd ` snd ` set p\"\n            by fastforce\n          with p valid_graph.delete_node_is_path[OF delete_edge_valid[OF valid_G]\n            valid_graph.delete_edge_is_path[OF valid_G] \\<open>x\\<noteq>v\\<close> this, of y a w b]\n          show ?thesis\n            by auto\n        qed\n        with asm have \"connected_graph ?G\"\n          unfolding connected_graph_def connected_graph_axioms_def\n          by auto\n        with IH have IH': \"card (edges ?G) = card (nodes ?G) - 1\"\n          by blast\n        from edges e'(1)  have \"insert e (edges ?G) = edges G\"\n          by blast\n        moreover from edges have \"e\\<notin>edges ?G\"\n          by blast\n        ultimately have \"card (edges G)  = card (edges ?G) +1\"\n          using finite_graph.finite_E[OF \\<open>finite_graph ?G\\<close>] card_insert_disjoint\n          by fastforce\n        also from IH' False have \"\\<dots> = card (nodes ?G) - 1 + 1\"\n          by simp\n        also from Suc(2,3) \\<open>n = card (nodes ?G) - 1\\<close>\n        have \"\\<dots> = card (nodes G) - 1\"\n          by simp\n        finally show ?lhs .\n      qed\n    qed\n  qed\nend\n\ncontext finite_graph\nbegin\n  lemma forest_connecting_all_edges_exists: \"\\<exists>F. forest F \\<and> subgraph F G \\<and>\n      (\\<forall>(a,w,b)\\<in>edges G. nodes_connected F a b)\"\n    using finite_E valid_graph_axioms\n  proof (induction n == \"card (edges G)\" arbitrary: G)\n    case  (0 G)\n    then have empty: \"edges G = {}\"\n      by simp\n    with \"0.prems\"(2) show ?case\n      unfolding forest_def forest_axioms_def subgraph_def\n      by auto\n  next\n    case (Suc n G)\n    from Suc.hyps(2) have \"edges G \\<noteq> {}\"\n      by auto\n    with prod_cases3 obtain a w b where e: \"(a, w, b) \\<in> edges G\"\n      by auto\n    with Suc.prems have \"valid_graph (delete_edge a w b G)\"\n      unfolding valid_graph_def delete_edge_def\n      by auto\n    moreover from e Suc.hyps(2) Suc.prems(1)\n      have \"n = card (edges (delete_edge a w b G))\"\n      unfolding delete_edge_def\n      by simp\n    moreover from Suc.prems have \"finite (edges (delete_edge a w b G))\"\n      unfolding delete_edge_def\n      by auto\n    ultimately obtain F where F: \"forest F\" \"subgraph F (delete_edge a w b G)\"\n        \"(\\<forall>(a,w,b)\\<in>edges (delete_edge a w b G). nodes_connected F a b)\"\n      using Suc.hyps(1)\n      unfolding valid_graph_def\n      by blast\n    then have subgraph_F: \"subgraph F G\"\n      unfolding subgraph_def delete_edge_def\n      by auto\n    show ?case\n    proof (cases \"nodes_connected F a b\")\n      case True\n      from F True have \"(\\<forall>(a,w,b)\\<in>edges G. nodes_connected F a b)\"\n        unfolding delete_edge_def by fastforce\n      with F subgraph_F show ?thesis\n        by auto\n    next\n      case False\n      from subgraph_F e Suc.prems(2)\n      have ab: \"a \\<in> nodes F\" \"b \\<in> nodes F\"\n        unfolding subgraph_def\n        by (auto simp: valid_graph.E_validD)\n      with False forest.forest_add_edge[OF F(1) this]\n      have \"forest (add_edge a w b F)\"\n        by auto\n      moreover from F e Suc.prems(2)\n      have \"subgraph (add_edge a w b F) G\"\n        unfolding subgraph_def add_edge_def delete_edge_def\n        by (auto simp: valid_graph.E_validD)\n      moreover have \"nodes_connected (add_edge a w b F) c d\"\n        if asm: \"(c,w',d)\\<in>edges G\" for c w' d\n      proof (cases \"(c, w', d) = (a, w, b)\")\n        case True\n        with valid_graph.add_edge_is_connected[OF forest.axioms(1)[OF F(1)]]\n        show ?thesis by auto\n      next\n        case False\n        with F(3) asm have \"nodes_connected F c d\"\n          by fastforce\n        with valid_graph.add_edge_is_path[OF forest.axioms(1)[OF F(1)]]\n        show ?thesis\n          by blast\n      qed\n      ultimately show ?thesis\n        by auto\n    qed\n  qed\n\n  lemma finite_subgraphs: \"finite {T. subgraph T G}\"\n  proof -\n    from finite_E have \"finite {E'. E' \\<subseteq> E}\"\n      by simp\n    then have \"finite {\\<lparr>nodes = V, edges = E'\\<rparr>| E'. E' \\<subseteq> E}\"\n      by simp\n    also have \"{\\<lparr>nodes = V, edges = E'\\<rparr>| E'. E' \\<subseteq> E} = {T. subgraph T G}\"\n      unfolding subgraph_def\n      by (metis (mono_tags, lifting) old.unit.exhaust select_convs(1) select_convs(2) surjective)\n    finally show ?thesis .\n  qed\n\n  lemma spanning_forest_exists: \"\\<exists>F. spanning_forest F G\"\n  proof -\n    from forest_connecting_all_edges_exists\n    obtain F where F: \"forest F\" \"subgraph F G\"\n      \"(\\<forall>(a, w, b)\\<in>edges G. nodes_connected F a b)\"\n      unfolding finite_graph_def finite_graph_axioms_def valid_graph_def\n      by blast\n    from F(2,3) forest.axioms(1)[OF F(1)] induce_maximally_connected[of F]\n    have \"maximally_connected F G\"\n      unfolding maximally_connected_def\n      by simp\n    with F(1,2) show ?thesis\n      unfolding spanning_forest_def\n      by auto\n  qed\nend\n\ncontext finite_weighted_graph\nbegin\n  lemma minimum_spanning_forest_exists: \"\\<exists>F. minimum_spanning_forest F G\"\n  proof -\n    let ?weights = \"{edge_weight F |F. spanning_forest F G}\"\n    from spanning_forest_exists\n    obtain F where \"spanning_forest F G\"\n      by auto\n    then have non_empty: \"edge_weight F \\<in> ?weights\"\n      by auto\n    from finite_subgraphs have finite: \"finite ?weights\"\n      unfolding spanning_forest_def\n      by auto\n    with non_empty have \"\\<forall>w \\<in> ?weights. Min ?weights \\<le> w\"\n      by simp\n    moreover from finite non_empty have \"Min ?weights \\<in> ?weights\"\n      using Min_in by blast\n    ultimately obtain F' where \"(\\<forall>w \\<in> ?weights. edge_weight F' \\<le> w) \\<and> spanning_forest F' G\"\n      by auto\n    then show ?thesis\n      unfolding minimum_spanning_forest_def optimal_forest_def\n      by blast\n  qed\nend\n\ncontext valid_graph\nbegin\n  lemma sub_spanning_forest_eq:\n    assumes \"\\<forall>(a, w, b)\\<in>E. nodes_connected H a b\"\n    assumes \"spanning_forest T G\"\n    assumes \"subgraph H T\"\n    shows \"H = T\"\n  proof -\n    from \\<open>spanning_forest T G\\<close>\n    have valid_T: \"valid_graph T\" and forest_T: \"forest T\"\n      unfolding spanning_forest_def forest_def\n      by auto\n    have \"edges T \\<subseteq> edges H\"\n    proof\n      fix x\n      assume asm: \"x \\<in> edges T\"\n      show \"x \\<in> edges H\"\n      proof (rule ccontr)\n        assume asm': \"x \\<notin> edges H\"\n        from prod_cases3 obtain a w b where x: \"x = (a, w, b)\" .\n        with asm asm' \\<open>subgraph H T\\<close> have subgraph': \"subgraph H (delete_edge a w b T)\"\n          unfolding subgraph_def delete_edge_def\n          by auto\n        from \\<open>spanning_forest T G\\<close> asm x\n        have \"(a,w,b) \\<in> E\"\n          unfolding spanning_forest_def subgraph_def\n          by blast\n        with \\<open>\\<forall>(a, w, b)\\<in>E. nodes_connected H a b\\<close>\n        obtain p where p:\"is_path_undir H a p b\"\n          unfolding maximally_connected_def\n          by blast\n        from valid_graph.is_path_undir_subgraph[OF delete_edge_valid[OF valid_T] p subgraph']\n        have \"is_path_undir (delete_edge a w b T) a p b\" .\n        with forest.cycle_free[OF forest_T] asm x show False\n          by auto\n      qed\n    qed\n    with assms show ?thesis\n      unfolding subgraph_def by simp\n  qed\nend\n\nlemma minimum_spanning_forest_impl_tree:\n  assumes \"minimum_spanning_forest F G\"\n  assumes valid_G: \"valid_graph G\"\n  assumes \"connected_graph F\"\n  shows \"minimum_spanning_tree F G\"\n  using assms valid_graph.connected_impl_maximally_connected[OF valid_G]\n  unfolding minimum_spanning_forest_def minimum_spanning_tree_def\n    spanning_forest_def spanning_tree_def tree_def\n    optimal_forest_def optimal_tree_def\n  by auto\n\nlemma minimum_spanning_forest_impl_tree2:\n  assumes \"minimum_spanning_forest F G\"\n  assumes connected_G: \"connected_graph G\"\n  shows \"minimum_spanning_tree F G\"\n  using assms connected_graph.maximally_connected_impl_connected[OF connected_G]\n    minimum_spanning_forest_impl_tree connected_graph.axioms(1)[OF connected_G]\n  unfolding minimum_spanning_forest_def spanning_forest_def\n  by auto\n\nend\n", "meta": {"author": "digitsum", "repo": "isabelle-kruskal", "sha": "52c058c5a4896cf262088a6c40edd608c0b65a55", "save_path": "github-repos/isabelle/digitsum-isabelle-kruskal", "path": "github-repos/isabelle/digitsum-isabelle-kruskal/isabelle-kruskal-52c058c5a4896cf262088a6c40edd608c0b65a55/Graph_Definition.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361700013356, "lm_q2_score": 0.7905303236047049, "lm_q1q2_score": 0.7213084607397934}}
{"text": "theory LTS\nimports Main \"HOL.Option\"\nbegin\n\n\ntext \\<open> Given a set of states $\\mathcal{Q}$ and an alphabet $\\Sigma$,\na labeled transition system is a subset of $\\mathcal{Q} \\times \\Sigma\n\\times \\mathcal{Q}$.  Given such a relation $\\Delta \\subseteq\n\\mathcal{Q} \\times \\Sigma \\times \\mathcal{Q}$, a triple $(q, \\sigma,\nq')$ is an element of $\\Delta$ iff starting in state $q$ the state\n$q'$ can be reached reading the label $\\sigma$. \\<close>\n\n\ntype_synonym ('q,'a) LTS = \"('q * 'a set * 'q) set\"\n\n\nsubsubsection  \\<open>Reachability\\<close>\n\ntext \\<open>Often it is enough to consider just the first and last state of\na path. This leads to the following definition of reachability. Notice, \nthat @{term \"LTS_is_reachable \\<Delta>\"} is the reflexive, transitive closure of @{term \\<Delta>}.\\<close>\n\nprimrec LTS_is_reachable :: \"('q, 'a) LTS \\<Rightarrow> 'q \\<Rightarrow> 'a list \\<Rightarrow> 'q \\<Rightarrow> bool\" where\n   \"LTS_is_reachable \\<Delta> q [] q' = (q = q' \u2228 (q, {}, q') \u2208 \u0394)\"|\n   \"LTS_is_reachable \\<Delta> q (a # w) q' =\n      (\\<exists>q'' \\<sigma>. a \\<in> \\<sigma> \\<and> (q, \\<sigma>, q'') \\<in> \\<Delta> \\<and> LTS_is_reachable \\<Delta> q'' w q')\"\n\n\nlemma LChr_lemma :\"LTS_is_reachable {(a,{x},b)} a l b \u27f9 a\u2260 b \u27f9 l = [x]\"\n  by (smt (verit, del_insts) LTS_is_reachable.simps(1) LTS_is_reachable.simps(2) empty_iff old.prod.inject remdups_adj.cases singleton_iff)\n\nend", "meta": {"author": "hongjianjiang", "repo": "REtoNFA", "sha": "0b86965d4834255768a02980ae4daf89b62793e5", "save_path": "github-repos/isabelle/hongjianjiang-REtoNFA", "path": "github-repos/isabelle/hongjianjiang-REtoNFA/REtoNFA-0b86965d4834255768a02980ae4daf89b62793e5/LTS.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9124361580958427, "lm_q2_score": 0.7905303211371898, "lm_q1q2_score": 0.7213084490766902}}
{"text": "(*  Author:     L C Paulson, University of Cambridge\n    Material split off from Topology_Euclidean_Space\n*)\n\nsection \\<open>Connected Components\\<close>\n\ntheory Connected\n  imports\n    Abstract_Topology_2\nbegin\n\nsubsection\\<^marker>\\<open>tag unimportant\\<close> \\<open>Connectedness\\<close>\n\nlemma connected_local:\n \"connected S \\<longleftrightarrow>\n  \\<not> (\\<exists>e1 e2.\n      openin (top_of_set S) e1 \\<and>\n      openin (top_of_set S) e2 \\<and>\n      S \\<subseteq> e1 \\<union> e2 \\<and>\n      e1 \\<inter> e2 = {} \\<and>\n      e1 \\<noteq> {} \\<and>\n      e2 \\<noteq> {})\"\n  unfolding connected_def openin_open\n  by safe blast+\n\nlemma exists_diff:\n  fixes P :: \"'a set \\<Rightarrow> bool\"\n  shows \"(\\<exists>S. P (- S)) \\<longleftrightarrow> (\\<exists>S. P S)\"\n    (is \"?lhs \\<longleftrightarrow> ?rhs\")\nproof -\n  have ?rhs if ?lhs\n    using that by blast\n  moreover have \"P (- (- S))\" if \"P S\" for S\n  proof -\n    have \"S = - (- S)\" by simp\n    with that show ?thesis by metis\n  qed\n  ultimately show ?thesis by metis\nqed\n\nlemma connected_clopen: \"connected S \\<longleftrightarrow>\n  (\\<forall>T. openin (top_of_set S) T \\<and>\n     closedin (top_of_set S) T \\<longrightarrow> T = {} \\<or> T = S)\" (is \"?lhs \\<longleftrightarrow> ?rhs\")\nproof -\n  have \"\\<not> connected S \\<longleftrightarrow>\n    (\\<exists>e1 e2. open e1 \\<and> open (- e2) \\<and> S \\<subseteq> e1 \\<union> (- e2) \\<and> e1 \\<inter> (- e2) \\<inter> S = {} \\<and> e1 \\<inter> S \\<noteq> {} \\<and> (- e2) \\<inter> S \\<noteq> {})\"\n    unfolding connected_def openin_open closedin_closed\n    by (metis double_complement)\n  then have th0: \"connected S \\<longleftrightarrow>\n    \\<not> (\\<exists>e2 e1. closed e2 \\<and> open e1 \\<and> S \\<subseteq> e1 \\<union> (- e2) \\<and> e1 \\<inter> (- e2) \\<inter> S = {} \\<and> e1 \\<inter> S \\<noteq> {} \\<and> (- e2) \\<inter> S \\<noteq> {})\"\n    (is \" _ \\<longleftrightarrow> \\<not> (\\<exists>e2 e1. ?P e2 e1)\")\n    by (simp add: closed_def) metis\n  have th1: \"?rhs \\<longleftrightarrow> \\<not> (\\<exists>t' t. closed t'\\<and>t = S\\<inter>t' \\<and> t\\<noteq>{} \\<and> t\\<noteq>S \\<and> (\\<exists>t'. open t' \\<and> t = S \\<inter> t'))\"\n    (is \"_ \\<longleftrightarrow> \\<not> (\\<exists>t' t. ?Q t' t)\")\n    unfolding connected_def openin_open closedin_closed by auto\n  have \"(\\<exists>e1. ?P e2 e1) \\<longleftrightarrow> (\\<exists>t. ?Q e2 t)\" for e2\n  proof -\n    have \"?P e2 e1 \\<longleftrightarrow> (\\<exists>t. closed e2 \\<and> t = S\\<inter>e2 \\<and> open e1 \\<and> t = S\\<inter>e1 \\<and> t\\<noteq>{} \\<and> t \\<noteq> S)\" for e1\n      by auto\n    then show ?thesis\n      by metis\n  qed\n  then have \"\\<forall>e2. (\\<exists>e1. ?P e2 e1) \\<longleftrightarrow> (\\<exists>t. ?Q e2 t)\"\n    by blast\n  then show ?thesis\n    by (simp add: th0 th1)\nqed\n\nsubsection \\<open>Connected components, considered as a connectedness relation or a set\\<close>\n\ndefinition\\<^marker>\\<open>tag important\\<close> \"connected_component S x y \\<equiv> \\<exists>T. connected T \\<and> T \\<subseteq> S \\<and> x \\<in> T \\<and> y \\<in> T\"\n\nabbreviation \"connected_component_set S x \\<equiv> Collect (connected_component S x)\"\n\nlemma connected_componentI:\n  \"connected T \\<Longrightarrow> T \\<subseteq> S \\<Longrightarrow> x \\<in> T \\<Longrightarrow> y \\<in> T \\<Longrightarrow> connected_component S x y\"\n  by (auto simp: connected_component_def)\n\nlemma connected_component_in: \"connected_component S x y \\<Longrightarrow> x \\<in> S \\<and> y \\<in> S\"\n  by (auto simp: connected_component_def)\n\nlemma connected_component_refl: \"x \\<in> S \\<Longrightarrow> connected_component S x x\"\n  by (auto simp: connected_component_def) (use connected_sing in blast)\n\nlemma connected_component_refl_eq [simp]: \"connected_component S x x \\<longleftrightarrow> x \\<in> S\"\n  by (auto simp: connected_component_refl) (auto simp: connected_component_def)\n\nlemma connected_component_sym: \"connected_component S x y \\<Longrightarrow> connected_component S y x\"\n  by (auto simp: connected_component_def)\n\nlemma connected_component_trans:\n  \"connected_component S x y \\<Longrightarrow> connected_component S y z \\<Longrightarrow> connected_component S x z\"\n  unfolding connected_component_def\n  by (metis Int_iff Un_iff Un_subset_iff equals0D connected_Un)\n\nlemma connected_component_of_subset:\n  \"connected_component S x y \\<Longrightarrow> S \\<subseteq> T \\<Longrightarrow> connected_component T x y\"\n  by (auto simp: connected_component_def)\n\nlemma connected_component_Union: \"connected_component_set S x = \\<Union>{T. connected T \\<and> x \\<in> T \\<and> T \\<subseteq> S}\"\n  by (auto simp: connected_component_def)\n\nlemma connected_connected_component [iff]: \"connected (connected_component_set S x)\"\n  by (auto simp: connected_component_Union intro: connected_Union)\n\nlemma connected_iff_eq_connected_component_set:\n  \"connected S \\<longleftrightarrow> (\\<forall>x \\<in> S. connected_component_set S x = S)\"\nproof (cases \"S = {}\")\n  case True\n  then show ?thesis by simp\nnext\n  case False\n  then obtain x where \"x \\<in> S\" by auto\n  show ?thesis\n  proof\n    assume \"connected S\"\n    then show \"\\<forall>x \\<in> S. connected_component_set S x = S\"\n      by (force simp: connected_component_def)\n  next\n    assume \"\\<forall>x \\<in> S. connected_component_set S x = S\"\n    then show \"connected S\"\n      by (metis \\<open>x \\<in> S\\<close> connected_connected_component)\n  qed\nqed\n\nlemma connected_component_subset: \"connected_component_set S x \\<subseteq> S\"\n  using connected_component_in by blast\n\nlemma connected_component_eq_self: \"connected S \\<Longrightarrow> x \\<in> S \\<Longrightarrow> connected_component_set S x = S\"\n  by (simp add: connected_iff_eq_connected_component_set)\n\nlemma connected_iff_connected_component:\n  \"connected S \\<longleftrightarrow> (\\<forall>x \\<in> S. \\<forall>y \\<in> S. connected_component S x y)\"\n  using connected_component_in by (auto simp: connected_iff_eq_connected_component_set)\n\nlemma connected_component_maximal:\n  \"x \\<in> T \\<Longrightarrow> connected T \\<Longrightarrow> T \\<subseteq> S \\<Longrightarrow> T \\<subseteq> (connected_component_set S x)\"\n  using connected_component_eq_self connected_component_of_subset by blast\n\nlemma connected_component_mono:\n  \"S \\<subseteq> T \\<Longrightarrow> connected_component_set S x \\<subseteq> connected_component_set T x\"\n  by (simp add: Collect_mono connected_component_of_subset)\n\nlemma connected_component_eq_empty [simp]: \"connected_component_set S x = {} \\<longleftrightarrow> x \\<notin> S\"\n  using connected_component_refl by (fastforce simp: connected_component_in)\n\nlemma connected_component_set_empty [simp]: \"connected_component_set {} x = {}\"\n  using connected_component_eq_empty by blast\n\nlemma connected_component_eq:\n  \"y \\<in> connected_component_set S x \\<Longrightarrow> (connected_component_set S y = connected_component_set S x)\"\n  by (metis (no_types, lifting)\n      Collect_cong connected_component_sym connected_component_trans mem_Collect_eq)\n\nlemma closed_connected_component:\n  assumes S: \"closed S\"\n  shows \"closed (connected_component_set S x)\"\nproof (cases \"x \\<in> S\")\n  case False\n  then show ?thesis\n    by (metis connected_component_eq_empty closed_empty)\nnext\n  case True\n  show ?thesis\n    unfolding closure_eq [symmetric]\n  proof\n    show \"closure (connected_component_set S x) \\<subseteq> connected_component_set S x\"\n      apply (rule connected_component_maximal)\n        apply (simp add: closure_def True)\n       apply (simp add: connected_imp_connected_closure)\n      apply (simp add: S closure_minimal connected_component_subset)\n      done\n  next\n    show \"connected_component_set S x \\<subseteq> closure (connected_component_set S x)\"\n      by (simp add: closure_subset)\n  qed\nqed\n\nlemma connected_component_disjoint:\n  \"connected_component_set S a \\<inter> connected_component_set S b = {} \\<longleftrightarrow>\n    a \\<notin> connected_component_set S b\"\n  apply (auto simp: connected_component_eq)\n  using connected_component_eq connected_component_sym\n  apply blast\n  done\n\nlemma connected_component_nonoverlap:\n  \"connected_component_set S a \\<inter> connected_component_set S b = {} \\<longleftrightarrow>\n    a \\<notin> S \\<or> b \\<notin> S \\<or> connected_component_set S a \\<noteq> connected_component_set S b\"\n  apply (auto simp: connected_component_in)\n  using connected_component_refl_eq\n    apply blast\n   apply (metis connected_component_eq mem_Collect_eq)\n  apply (metis connected_component_eq mem_Collect_eq)\n  done\n\nlemma connected_component_overlap:\n  \"connected_component_set S a \\<inter> connected_component_set S b \\<noteq> {} \\<longleftrightarrow>\n    a \\<in> S \\<and> b \\<in> S \\<and> connected_component_set S a = connected_component_set S b\"\n  by (auto simp: connected_component_nonoverlap)\n\nlemma connected_component_sym_eq: \"connected_component S x y \\<longleftrightarrow> connected_component S y x\"\n  using connected_component_sym by blast\n\nlemma connected_component_eq_eq:\n  \"connected_component_set S x = connected_component_set S y \\<longleftrightarrow>\n    x \\<notin> S \\<and> y \\<notin> S \\<or> x \\<in> S \\<and> y \\<in> S \\<and> connected_component S x y\"\n  apply (cases \"y \\<in> S\", simp)\n   apply (metis connected_component_eq connected_component_eq_empty connected_component_refl_eq mem_Collect_eq)\n  apply (cases \"x \\<in> S\", simp)\n   apply (metis connected_component_eq_empty)\n  using connected_component_eq_empty\n  apply blast\n  done\n\nlemma connected_iff_connected_component_eq:\n  \"connected S \\<longleftrightarrow> (\\<forall>x \\<in> S. \\<forall>y \\<in> S. connected_component_set S x = connected_component_set S y)\"\n  by (simp add: connected_component_eq_eq connected_iff_connected_component)\n\nlemma connected_component_idemp:\n  \"connected_component_set (connected_component_set S x) x = connected_component_set S x\"\n  apply (rule subset_antisym)\n   apply (simp add: connected_component_subset)\n  apply (metis connected_component_eq_empty connected_component_maximal\n      connected_component_refl_eq connected_connected_component mem_Collect_eq set_eq_subset)\n  done\n\nlemma connected_component_unique:\n  \"\\<lbrakk>x \\<in> c; c \\<subseteq> S; connected c;\n    \\<And>c'. \\<lbrakk>x \\<in> c'; c' \\<subseteq> S; connected c'\\<rbrakk> \\<Longrightarrow> c' \\<subseteq> c\\<rbrakk>\n        \\<Longrightarrow> connected_component_set S x = c\"\n  apply (rule subset_antisym)\n   apply (meson connected_component_maximal connected_component_subset connected_connected_component contra_subsetD)\n  by (simp add: connected_component_maximal)\n\nlemma joinable_connected_component_eq:\n  \"\\<lbrakk>connected T; T \\<subseteq> S;\n    connected_component_set S x \\<inter> T \\<noteq> {};\n    connected_component_set S y \\<inter> T \\<noteq> {}\\<rbrakk>\n    \\<Longrightarrow> connected_component_set S x = connected_component_set S y\"\n  by (metis (full_types) subsetD connected_component_eq connected_component_maximal disjoint_iff_not_equal)\n\nlemma Union_connected_component: \"\\<Union>(connected_component_set S ` S) = S\"\n  apply (rule subset_antisym)\n  apply (simp add: SUP_least connected_component_subset)\n  using connected_component_refl_eq\n  by force\n\n\nlemma complement_connected_component_unions:\n    \"S - connected_component_set S x =\n     \\<Union>(connected_component_set S ` S - {connected_component_set S x})\"\n  apply (subst Union_connected_component [symmetric], auto)\n  apply (metis connected_component_eq_eq connected_component_in)\n  by (metis connected_component_eq mem_Collect_eq)\n\nlemma connected_component_intermediate_subset:\n        \"\\<lbrakk>connected_component_set U a \\<subseteq> T; T \\<subseteq> U\\<rbrakk>\n        \\<Longrightarrow> connected_component_set T a = connected_component_set U a\"\n  by (metis connected_component_idemp connected_component_mono subset_antisym)\n\n\nlemma connected_component_homeomorphismI:\n  assumes \"homeomorphism A B f g\" \"connected_component A x y\"\n  shows   \"connected_component B (f x) (f y)\"\nproof -\n  from assms obtain T where T: \"connected T\" \"T \\<subseteq> A\" \"x \\<in> T\" \"y \\<in> T\"\n    unfolding connected_component_def by blast\n  have \"connected (f ` T)\" \"f ` T \\<subseteq> B\" \"f x \\<in> f ` T\" \"f y \\<in> f ` T\"\n    using assms T continuous_on_subset[of A f T]\n    by (auto intro!: connected_continuous_image simp: homeomorphism_def)\n  thus ?thesis\n    unfolding connected_component_def by blast\nqed\n\nlemma connected_component_homeomorphism_iff:\n  assumes \"homeomorphism A B f g\"\n  shows   \"connected_component A x y \\<longleftrightarrow> x \\<in> A \\<and> y \\<in> A \\<and> connected_component B (f x) (f y)\"\n  by (metis assms connected_component_homeomorphismI connected_component_in homeomorphism_apply1 homeomorphism_sym)\n\nlemma connected_component_set_homeomorphism:\n  assumes \"homeomorphism A B f g\" \"x \\<in> A\"\n  shows   \"connected_component_set B (f x) = f ` connected_component_set A x\" (is \"?lhs = ?rhs\")\nproof -\n  have \"y \\<in> ?lhs \\<longleftrightarrow> y \\<in> ?rhs\" for y\n    by (smt (verit, best) assms connected_component_homeomorphism_iff homeomorphism_def image_iff mem_Collect_eq)\n  thus ?thesis\n    by blast\nqed\n\nsubsection \\<open>The set of connected components of a set\\<close>\n\ndefinition\\<^marker>\\<open>tag important\\<close> components:: \"'a::topological_space set \\<Rightarrow> 'a set set\"\n  where \"components S \\<equiv> connected_component_set S ` S\"\n\nlemma components_iff: \"S \\<in> components U \\<longleftrightarrow> (\\<exists>x. x \\<in> U \\<and> S = connected_component_set U x)\"\n  by (auto simp: components_def)\n\nlemma componentsI: \"x \\<in> U \\<Longrightarrow> connected_component_set U x \\<in> components U\"\n  by (auto simp: components_def)\n\nlemma componentsE:\n  assumes \"S \\<in> components U\"\n  obtains x where \"x \\<in> U\" \"S = connected_component_set U x\"\n  using assms by (auto simp: components_def)\n\nlemma Union_components [simp]: \"\\<Union>(components u) = u\"\n  apply (rule subset_antisym)\n  using Union_connected_component components_def apply fastforce\n  apply (metis Union_connected_component components_def set_eq_subset)\n  done\n\nlemma pairwise_disjoint_components: \"pairwise (\\<lambda>X Y. X \\<inter> Y = {}) (components u)\"\n  apply (simp add: pairwise_def)\n  apply (auto simp: components_iff)\n  apply (metis connected_component_eq_eq connected_component_in)+\n  done\n\nlemma in_components_nonempty: \"c \\<in> components s \\<Longrightarrow> c \\<noteq> {}\"\n    by (metis components_iff connected_component_eq_empty)\n\nlemma in_components_subset: \"c \\<in> components s \\<Longrightarrow> c \\<subseteq> s\"\n  using Union_components by blast\n\nlemma in_components_connected: \"c \\<in> components s \\<Longrightarrow> connected c\"\n  by (metis components_iff connected_connected_component)\n\nlemma in_components_maximal:\n  \"c \\<in> components s \\<longleftrightarrow>\n    c \\<noteq> {} \\<and> c \\<subseteq> s \\<and> connected c \\<and> (\\<forall>d. d \\<noteq> {} \\<and> c \\<subseteq> d \\<and> d \\<subseteq> s \\<and> connected d \\<longrightarrow> d = c)\"\n  apply (rule iffI)\n   apply (simp add: in_components_nonempty in_components_connected)\n   apply (metis (full_types) components_iff connected_component_eq_self connected_component_intermediate_subset connected_component_refl in_components_subset mem_Collect_eq rev_subsetD)\n  apply (metis bot.extremum_uniqueI components_iff connected_component_eq_empty connected_component_maximal connected_component_subset connected_connected_component subset_emptyI)\n  done\n\nlemma joinable_components_eq:\n  \"connected t \\<and> t \\<subseteq> s \\<and> c1 \\<in> components s \\<and> c2 \\<in> components s \\<and> c1 \\<inter> t \\<noteq> {} \\<and> c2 \\<inter> t \\<noteq> {} \\<Longrightarrow> c1 = c2\"\n  by (metis (full_types) components_iff joinable_connected_component_eq)\n\nlemma closed_components: \"\\<lbrakk>closed s; c \\<in> components s\\<rbrakk> \\<Longrightarrow> closed c\"\n  by (metis closed_connected_component components_iff)\n\nlemma components_nonoverlap:\n    \"\\<lbrakk>c \\<in> components s; c' \\<in> components s\\<rbrakk> \\<Longrightarrow> (c \\<inter> c' = {}) \\<longleftrightarrow> (c \\<noteq> c')\"\n  apply (auto simp: in_components_nonempty components_iff)\n    using connected_component_refl apply blast\n   apply (metis connected_component_eq_eq connected_component_in)\n  by (metis connected_component_eq mem_Collect_eq)\n\nlemma components_eq: \"\\<lbrakk>c \\<in> components s; c' \\<in> components s\\<rbrakk> \\<Longrightarrow> (c = c' \\<longleftrightarrow> c \\<inter> c' \\<noteq> {})\"\n  by (metis components_nonoverlap)\n\nlemma components_eq_empty [simp]: \"components s = {} \\<longleftrightarrow> s = {}\"\n  by (simp add: components_def)\n\nlemma components_empty [simp]: \"components {} = {}\"\n  by simp\n\nlemma connected_eq_connected_components_eq: \"connected s \\<longleftrightarrow> (\\<forall>c \\<in> components s. \\<forall>c' \\<in> components s. c = c')\"\n  by (metis (no_types, opaque_lifting) components_iff connected_component_eq_eq connected_iff_connected_component)\n\nlemma components_eq_sing_iff: \"components s = {s} \\<longleftrightarrow> connected s \\<and> s \\<noteq> {}\"\n  apply (rule iffI)\n  using in_components_connected apply fastforce\n  apply safe\n  using Union_components apply fastforce\n   apply (metis components_iff connected_component_eq_self)\n  using in_components_maximal\n  apply auto\n  done\n\nlemma components_eq_sing_exists: \"(\\<exists>a. components s = {a}) \\<longleftrightarrow> connected s \\<and> s \\<noteq> {}\"\n  apply (rule iffI)\n  using connected_eq_connected_components_eq apply fastforce\n  apply (metis components_eq_sing_iff)\n  done\n\nlemma connected_eq_components_subset_sing: \"connected s \\<longleftrightarrow> components s \\<subseteq> {s}\"\n  by (metis Union_components components_empty components_eq_sing_iff connected_empty insert_subset order_refl subset_singletonD)\n\nlemma connected_eq_components_subset_sing_exists: \"connected s \\<longleftrightarrow> (\\<exists>a. components s \\<subseteq> {a})\"\n  by (metis components_eq_sing_exists connected_eq_components_subset_sing empty_iff subset_iff subset_singletonD)\n\nlemma in_components_self: \"s \\<in> components s \\<longleftrightarrow> connected s \\<and> s \\<noteq> {}\"\n  by (metis components_empty components_eq_sing_iff empty_iff in_components_connected insertI1)\n\nlemma components_maximal: \"\\<lbrakk>c \\<in> components s; connected t; t \\<subseteq> s; c \\<inter> t \\<noteq> {}\\<rbrakk> \\<Longrightarrow> t \\<subseteq> c\"\n  apply (simp add: components_def ex_in_conv [symmetric], clarify)\n  by (meson connected_component_def connected_component_trans)\n\nlemma exists_component_superset: \"\\<lbrakk>t \\<subseteq> s; s \\<noteq> {}; connected t\\<rbrakk> \\<Longrightarrow> \\<exists>c. c \\<in> components s \\<and> t \\<subseteq> c\"\n  apply (cases \"t = {}\", force)\n  apply (metis components_def ex_in_conv connected_component_maximal contra_subsetD image_eqI)\n  done\n\nlemma components_intermediate_subset: \"\\<lbrakk>s \\<in> components u; s \\<subseteq> t; t \\<subseteq> u\\<rbrakk> \\<Longrightarrow> s \\<in> components t\"\n  apply (auto simp: components_iff)\n  apply (metis connected_component_eq_empty connected_component_intermediate_subset)\n  done\n\nlemma in_components_unions_complement: \"c \\<in> components s \\<Longrightarrow> s - c = \\<Union>(components s - {c})\"\n  by (metis complement_connected_component_unions components_def components_iff)\n\nlemma connected_intermediate_closure:\n  assumes cs: \"connected s\" and st: \"s \\<subseteq> t\" and ts: \"t \\<subseteq> closure s\"\n  shows \"connected t\"\nproof (rule connectedI)\n  fix A B\n  assume A: \"open A\" and B: \"open B\" and Alap: \"A \\<inter> t \\<noteq> {}\" and Blap: \"B \\<inter> t \\<noteq> {}\"\n    and disj: \"A \\<inter> B \\<inter> t = {}\" and cover: \"t \\<subseteq> A \\<union> B\"\n  have disjs: \"A \\<inter> B \\<inter> s = {}\"\n    using disj st by auto\n  have \"A \\<inter> closure s \\<noteq> {}\"\n    using Alap Int_absorb1 ts by blast\n  then have Alaps: \"A \\<inter> s \\<noteq> {}\"\n    by (simp add: A open_Int_closure_eq_empty)\n  have \"B \\<inter> closure s \\<noteq> {}\"\n    using Blap Int_absorb1 ts by blast\n  then have Blaps: \"B \\<inter> s \\<noteq> {}\"\n    by (simp add: B open_Int_closure_eq_empty)\n  then show False\n    using cs [unfolded connected_def] A B disjs Alaps Blaps cover st\n    by blast\nqed\n\nlemma closedin_connected_component: \"closedin (top_of_set s) (connected_component_set s x)\"\nproof (cases \"connected_component_set s x = {}\")\n  case True\n  then show ?thesis\n    by (metis closedin_empty)\nnext\n  case False\n  then obtain y where y: \"connected_component s x y\"\n    by blast\n  have *: \"connected_component_set s x \\<subseteq> s \\<inter> closure (connected_component_set s x)\"\n    by (auto simp: closure_def connected_component_in)\n  have \"connected_component s x y \\<Longrightarrow> s \\<inter> closure (connected_component_set s x) \\<subseteq> connected_component_set s x\"\n    apply (rule connected_component_maximal, simp)\n    using closure_subset connected_component_in apply fastforce\n    using * connected_intermediate_closure apply blast+\n    done\n  with y * show ?thesis\n    by (auto simp: closedin_closed)\nqed\n\nlemma closedin_component:\n   \"C \\<in> components s \\<Longrightarrow> closedin (top_of_set s) C\"\n  using closedin_connected_component componentsE by blast\n\n\nsubsection\\<^marker>\\<open>tag unimportant\\<close> \\<open>Proving a function is constant on a connected set\n  by proving that a level set is open\\<close>\n\nlemma continuous_levelset_openin_cases:\n  fixes f :: \"_ \\<Rightarrow> 'b::t1_space\"\n  shows \"connected s \\<Longrightarrow> continuous_on s f \\<Longrightarrow>\n        openin (top_of_set s) {x \\<in> s. f x = a}\n        \\<Longrightarrow> (\\<forall>x \\<in> s. f x \\<noteq> a) \\<or> (\\<forall>x \\<in> s. f x = a)\"\n  unfolding connected_clopen\n  using continuous_closedin_preimage_constant by auto\n\nlemma continuous_levelset_openin:\n  fixes f :: \"_ \\<Rightarrow> 'b::t1_space\"\n  shows \"connected s \\<Longrightarrow> continuous_on s f \\<Longrightarrow>\n        openin (top_of_set s) {x \\<in> s. f x = a} \\<Longrightarrow>\n        (\\<exists>x \\<in> s. f x = a)  \\<Longrightarrow> (\\<forall>x \\<in> s. f x = a)\"\n  using continuous_levelset_openin_cases[of s f ]\n  by meson\n\nlemma continuous_levelset_open:\n  fixes f :: \"_ \\<Rightarrow> 'b::t1_space\"\n  assumes \"connected s\"\n    and \"continuous_on s f\"\n    and \"open {x \\<in> s. f x = a}\"\n    and \"\\<exists>x \\<in> s.  f x = a\"\n  shows \"\\<forall>x \\<in> s. f x = a\"\n  using continuous_levelset_openin[OF assms(1,2), of a, unfolded openin_open]\n  using assms (3,4)\n  by fast\n\n\nsubsection\\<^marker>\\<open>tag unimportant\\<close> \\<open>Preservation of Connectedness\\<close>\n\nlemma homeomorphic_connectedness:\n  assumes \"s homeomorphic t\"\n  shows \"connected s \\<longleftrightarrow> connected t\"\nusing assms unfolding homeomorphic_def homeomorphism_def by (metis connected_continuous_image)\n\nlemma connected_monotone_quotient_preimage:\n  assumes \"connected T\"\n      and contf: \"continuous_on S f\" and fim: \"f ` S = T\"\n      and opT: \"\\<And>U. U \\<subseteq> T\n                 \\<Longrightarrow> openin (top_of_set S) (S \\<inter> f -` U) \\<longleftrightarrow>\n                     openin (top_of_set T) U\"\n      and connT: \"\\<And>y. y \\<in> T \\<Longrightarrow> connected (S \\<inter> f -` {y})\"\n    shows \"connected S\"\nproof (rule connectedI)\n  fix U V\n  assume \"open U\" and \"open V\" and \"U \\<inter> S \\<noteq> {}\" and \"V \\<inter> S \\<noteq> {}\"\n    and \"U \\<inter> V \\<inter> S = {}\" and \"S \\<subseteq> U \\<union> V\"\n  moreover\n  have disjoint: \"f ` (S \\<inter> U) \\<inter> f ` (S \\<inter> V) = {}\"\n  proof -\n    have False if \"y \\<in> f ` (S \\<inter> U) \\<inter> f ` (S \\<inter> V)\" for y\n    proof -\n      have \"y \\<in> T\"\n        using fim that by blast\n      show ?thesis\n        using connectedD [OF connT [OF \\<open>y \\<in> T\\<close>] \\<open>open U\\<close> \\<open>open V\\<close>]\n              \\<open>S \\<subseteq> U \\<union> V\\<close> \\<open>U \\<inter> V \\<inter> S = {}\\<close> that by fastforce\n    qed\n    then show ?thesis by blast\n  qed\n  ultimately have UU: \"(S \\<inter> f -` f ` (S \\<inter> U)) = S \\<inter> U\" and VV: \"(S \\<inter> f -` f ` (S \\<inter> V)) = S \\<inter> V\"\n    by auto\n  have opeU: \"openin (top_of_set T) (f ` (S \\<inter> U))\"\n    by (metis UU \\<open>open U\\<close> fim image_Int_subset le_inf_iff opT openin_open_Int)\n  have opeV: \"openin (top_of_set T) (f ` (S \\<inter> V))\"\n    by (metis opT fim VV \\<open>open V\\<close> openin_open_Int image_Int_subset inf.bounded_iff)\n  have \"T \\<subseteq> f ` (S \\<inter> U) \\<union> f ` (S \\<inter> V)\"\n    using \\<open>S \\<subseteq> U \\<union> V\\<close> fim by auto\n  then show False\n    using \\<open>connected T\\<close> disjoint opeU opeV \\<open>U \\<inter> S \\<noteq> {}\\<close> \\<open>V \\<inter> S \\<noteq> {}\\<close>\n    by (auto simp: connected_openin)\nqed\n\nlemma connected_open_monotone_preimage:\n  assumes contf: \"continuous_on S f\" and fim: \"f ` S = T\"\n    and ST: \"\\<And>C. openin (top_of_set S) C \\<Longrightarrow> openin (top_of_set T) (f ` C)\"\n    and connT: \"\\<And>y. y \\<in> T \\<Longrightarrow> connected (S \\<inter> f -` {y})\"\n    and \"connected C\" \"C \\<subseteq> T\"\n  shows \"connected (S \\<inter> f -` C)\"\nproof -\n  have contf': \"continuous_on (S \\<inter> f -` C) f\"\n    by (meson contf continuous_on_subset inf_le1)\n  have eqC: \"f ` (S \\<inter> f -` C) = C\"\n    using \\<open>C \\<subseteq> T\\<close> fim by blast\n  show ?thesis\n  proof (rule connected_monotone_quotient_preimage [OF \\<open>connected C\\<close> contf' eqC])\n    show \"connected (S \\<inter> f -` C \\<inter> f -` {y})\" if \"y \\<in> C\" for y\n    proof -\n      have \"S \\<inter> f -` C \\<inter> f -` {y} = S \\<inter> f -` {y}\"\n        using that by blast\n      moreover have \"connected (S \\<inter> f -` {y})\"\n        using \\<open>C \\<subseteq> T\\<close> connT that by blast\n      ultimately show ?thesis\n        by metis\n    qed\n    have \"\\<And>U. openin (top_of_set (S \\<inter> f -` C)) U\n               \\<Longrightarrow> openin (top_of_set C) (f ` U)\"\n      using open_map_restrict [OF _ ST \\<open>C \\<subseteq> T\\<close>] by metis\n    then show \"\\<And>D. D \\<subseteq> C\n          \\<Longrightarrow> openin (top_of_set (S \\<inter> f -` C)) (S \\<inter> f -` C \\<inter> f -` D) =\n              openin (top_of_set C) D\"\n      using open_map_imp_quotient_map [of \"(S \\<inter> f -` C)\" f] contf' by (simp add: eqC)\n  qed\nqed\n\n\nlemma connected_closed_monotone_preimage:\n  assumes contf: \"continuous_on S f\" and fim: \"f ` S = T\"\n    and ST: \"\\<And>C. closedin (top_of_set S) C \\<Longrightarrow> closedin (top_of_set T) (f ` C)\"\n    and connT: \"\\<And>y. y \\<in> T \\<Longrightarrow> connected (S \\<inter> f -` {y})\"\n    and \"connected C\" \"C \\<subseteq> T\"\n  shows \"connected (S \\<inter> f -` C)\"\nproof -\n  have contf': \"continuous_on (S \\<inter> f -` C) f\"\n    by (meson contf continuous_on_subset inf_le1)\n  have eqC: \"f ` (S \\<inter> f -` C) = C\"\n    using \\<open>C \\<subseteq> T\\<close> fim by blast\n  show ?thesis\n  proof (rule connected_monotone_quotient_preimage [OF \\<open>connected C\\<close> contf' eqC])\n    show \"connected (S \\<inter> f -` C \\<inter> f -` {y})\" if \"y \\<in> C\" for y\n    proof -\n      have \"S \\<inter> f -` C \\<inter> f -` {y} = S \\<inter> f -` {y}\"\n        using that by blast\n      moreover have \"connected (S \\<inter> f -` {y})\"\n        using \\<open>C \\<subseteq> T\\<close> connT that by blast\n      ultimately show ?thesis\n        by metis\n    qed\n    have \"\\<And>U. closedin (top_of_set (S \\<inter> f -` C)) U\n               \\<Longrightarrow> closedin (top_of_set C) (f ` U)\"\n      using closed_map_restrict [OF _ ST \\<open>C \\<subseteq> T\\<close>] by metis\n    then show \"\\<And>D. D \\<subseteq> C\n          \\<Longrightarrow> openin (top_of_set (S \\<inter> f -` C)) (S \\<inter> f -` C \\<inter> f -` D) =\n              openin (top_of_set C) D\"\n      using closed_map_imp_quotient_map [of \"(S \\<inter> f -` C)\" f] contf' by (simp add: eqC)\n  qed\nqed\n\n\nsubsection\\<open>Lemmas about components\\<close>\n\ntext  \\<open>See Newman IV, 3.3 and 3.4.\\<close>\n\nlemma connected_Un_clopen_in_complement:\n  fixes S U :: \"'a::metric_space set\"\n  assumes \"connected S\" \"connected U\" \"S \\<subseteq> U\" \n      and opeT: \"openin (top_of_set (U - S)) T\" \n      and cloT: \"closedin (top_of_set (U - S)) T\"\n    shows \"connected (S \\<union> T)\"\nproof -\n  have *: \"\\<lbrakk>\\<And>x y. P x y \\<longleftrightarrow> P y x; \\<And>x y. P x y \\<Longrightarrow> S \\<subseteq> x \\<or> S \\<subseteq> y;\n            \\<And>x y. \\<lbrakk>P x y; S \\<subseteq> x\\<rbrakk> \\<Longrightarrow> False\\<rbrakk> \\<Longrightarrow> \\<not>(\\<exists>x y. (P x y))\" for P\n    by metis\n  show ?thesis\n    unfolding connected_closedin_eq\n  proof (rule *)\n    fix H1 H2\n    assume H: \"closedin (top_of_set (S \\<union> T)) H1 \\<and> \n               closedin (top_of_set (S \\<union> T)) H2 \\<and>\n               H1 \\<union> H2 = S \\<union> T \\<and> H1 \\<inter> H2 = {} \\<and> H1 \\<noteq> {} \\<and> H2 \\<noteq> {}\"\n    then have clo: \"closedin (top_of_set S) (S \\<inter> H1)\"\n                   \"closedin (top_of_set S) (S \\<inter> H2)\"\n      by (metis Un_upper1 closedin_closed_subset inf_commute)+\n    have Seq: \"S \\<inter> (H1 \\<union> H2) = S\"\n      by (simp add: H)\n    have \"S \\<inter> ((S \\<union> T) \\<inter> H1) \\<union> S \\<inter> ((S \\<union> T) \\<inter> H2) = S\"\n      using Seq by auto\n    moreover have \"H1 \\<inter> (S \\<inter> ((S \\<union> T) \\<inter> H2)) = {}\"\n      using H by blast\n    ultimately have \"S \\<inter> H1 = {} \\<or> S \\<inter> H2 = {}\"\n      by (metis (no_types) H Int_assoc \\<open>S \\<inter> (H1 \\<union> H2) = S\\<close> \\<open>connected S\\<close>\n          clo Seq connected_closedin inf_bot_right inf_le1)\n    then show \"S \\<subseteq> H1 \\<or> S \\<subseteq> H2\"\n      using H \\<open>connected S\\<close> unfolding connected_closedin by blast\n  next\n    fix H1 H2\n    assume H: \"closedin (top_of_set (S \\<union> T)) H1 \\<and>\n               closedin (top_of_set (S \\<union> T)) H2 \\<and>\n               H1 \\<union> H2 = S \\<union> T \\<and> H1 \\<inter> H2 = {} \\<and> H1 \\<noteq> {} \\<and> H2 \\<noteq> {}\" \n       and \"S \\<subseteq> H1\"\n    then have H2T: \"H2 \\<subseteq> T\"\n      by auto\n    have \"T \\<subseteq> U\"\n      using Diff_iff opeT openin_imp_subset by auto\n    with \\<open>S \\<subseteq> U\\<close> have Ueq: \"U = (U - S) \\<union> (S \\<union> T)\" \n      by auto\n    have \"openin (top_of_set ((U - S) \\<union> (S \\<union> T))) H2\"\n    proof (rule openin_subtopology_Un)\n      show \"openin (top_of_set (S \\<union> T)) H2\"\n        using \\<open>H2 \\<subseteq> T\\<close> apply (auto simp: openin_closedin_eq)\n        by (metis Diff_Diff_Int Diff_disjoint Diff_partition Diff_subset H Int_absorb1 Un_Diff)\n      then show \"openin (top_of_set (U - S)) H2\"\n        by (meson H2T Un_upper2 opeT openin_subset_trans openin_trans)\n    qed\n    moreover have \"closedin (top_of_set ((U - S) \\<union> (S \\<union> T))) H2\"\n    proof (rule closedin_subtopology_Un)\n      show \"closedin (top_of_set (U - S)) H2\"\n        using H H2T cloT closedin_subset_trans \n        by (blast intro: closedin_subtopology_Un closedin_trans)\n    qed (simp add: H)\n    ultimately\n    have H2: \"H2 = {} \\<or> H2 = U\"\n      using Ueq \\<open>connected U\\<close> unfolding connected_clopen by metis   \n    then have \"H2 \\<subseteq> S\"\n      by (metis Diff_partition H Un_Diff_cancel Un_subset_iff \\<open>H2 \\<subseteq> T\\<close> assms(3) inf.orderE opeT openin_imp_subset)\n    moreover have \"T \\<subseteq> H2 - S\"\n      by (metis (no_types) H2 H opeT openin_closedin_eq topspace_euclidean_subtopology)\n    ultimately show False\n      using H \\<open>S \\<subseteq> H1\\<close> by blast\n  qed blast\nqed\n\n\nproposition component_diff_connected:\n  fixes S :: \"'a::metric_space set\"\n  assumes \"connected S\" \"connected U\" \"S \\<subseteq> U\" and C: \"C \\<in> components (U - S)\"\n  shows \"connected(U - C)\"\n  using \\<open>connected S\\<close> unfolding connected_closedin_eq not_ex de_Morgan_conj\nproof clarify\n  fix H3 H4 \n  assume clo3: \"closedin (top_of_set (U - C)) H3\" \n    and clo4: \"closedin (top_of_set (U - C)) H4\" \n    and \"H3 \\<union> H4 = U - C\" and \"H3 \\<inter> H4 = {}\" and \"H3 \\<noteq> {}\" and \"H4 \\<noteq> {}\"\n    and * [rule_format]:\n    \"\\<forall>H1 H2. \\<not> closedin (top_of_set S) H1 \\<or>\n                      \\<not> closedin (top_of_set S) H2 \\<or>\n                      H1 \\<union> H2 \\<noteq> S \\<or> H1 \\<inter> H2 \\<noteq> {} \\<or> \\<not> H1 \\<noteq> {} \\<or> \\<not> H2 \\<noteq> {}\"\n  then have \"H3 \\<subseteq> U-C\" and ope3: \"openin (top_of_set (U - C)) (U - C - H3)\"\n    and \"H4 \\<subseteq> U-C\" and ope4: \"openin (top_of_set (U - C)) (U - C - H4)\"\n    by (auto simp: closedin_def)\n  have \"C \\<noteq> {}\" \"C \\<subseteq> U-S\" \"connected C\"\n    using C in_components_nonempty in_components_subset in_components_maximal by blast+\n  have cCH3: \"connected (C \\<union> H3)\"\n  proof (rule connected_Un_clopen_in_complement [OF \\<open>connected C\\<close> \\<open>connected U\\<close> _ _ clo3])\n    show \"openin (top_of_set (U - C)) H3\"\n      apply (simp add: openin_closedin_eq \\<open>H3 \\<subseteq> U - C\\<close>)\n      apply (simp add: closedin_subtopology)\n      by (metis Diff_cancel Diff_triv Un_Diff clo4 \\<open>H3 \\<inter> H4 = {}\\<close> \\<open>H3 \\<union> H4 = U - C\\<close> closedin_closed inf_commute sup_bot.left_neutral)\n  qed (use clo3 \\<open>C \\<subseteq> U - S\\<close> in auto)\n  have cCH4: \"connected (C \\<union> H4)\"\n  proof (rule connected_Un_clopen_in_complement [OF \\<open>connected C\\<close> \\<open>connected U\\<close> _ _ clo4])\n    show \"openin (top_of_set (U - C)) H4\"\n      apply (simp add: openin_closedin_eq \\<open>H4 \\<subseteq> U - C\\<close>)\n      apply (simp add: closedin_subtopology)\n      by (metis Diff_cancel Int_commute Un_Diff Un_Diff_Int \\<open>H3 \\<inter> H4 = {}\\<close> \\<open>H3 \\<union> H4 = U - C\\<close> clo3 closedin_closed)\n  qed (use clo4 \\<open>C \\<subseteq> U - S\\<close> in auto)\n  have \"closedin (top_of_set S) (S \\<inter> H3)\" \"closedin (top_of_set S) (S \\<inter> H4)\"\n    using clo3 clo4 \\<open>S \\<subseteq> U\\<close> \\<open>C \\<subseteq> U - S\\<close> by (auto simp: closedin_closed)\n  moreover have \"S \\<inter> H3 \\<noteq> {}\"      \n    using components_maximal [OF C cCH3] \\<open>C \\<noteq> {}\\<close> \\<open>C \\<subseteq> U - S\\<close> \\<open>H3 \\<noteq> {}\\<close> \\<open>H3 \\<subseteq> U - C\\<close> by auto\n  moreover have \"S \\<inter> H4 \\<noteq> {}\"\n    using components_maximal [OF C cCH4] \\<open>C \\<noteq> {}\\<close> \\<open>C \\<subseteq> U - S\\<close> \\<open>H4 \\<noteq> {}\\<close> \\<open>H4 \\<subseteq> U - C\\<close> by auto\n  ultimately show False\n    using * [of \"S \\<inter> H3\" \"S \\<inter> H4\"] \\<open>H3 \\<inter> H4 = {}\\<close> \\<open>C \\<subseteq> U - S\\<close> \\<open>H3 \\<union> H4 = U - C\\<close> \\<open>S \\<subseteq> U\\<close> \n    by auto\nqed\n\n\nsubsection\\<^marker>\\<open>tag unimportant\\<close>\\<open>Constancy of a function from a connected set into a finite, disconnected or discrete set\\<close>\n\ntext\\<open>Still missing: versions for a set that is smaller than R, or countable.\\<close>\n\nlemma continuous_disconnected_range_constant:\n  assumes S: \"connected S\"\n      and conf: \"continuous_on S f\"\n      and fim: \"f ` S \\<subseteq> t\"\n      and cct: \"\\<And>y. y \\<in> t \\<Longrightarrow> connected_component_set t y = {y}\"\n    shows \"f constant_on S\"\nproof (cases \"S = {}\")\n  case True then show ?thesis\n    by (simp add: constant_on_def)\nnext\n  case False\n  { fix x assume \"x \\<in> S\"\n    then have \"f ` S \\<subseteq> {f x}\"\n    by (metis connected_continuous_image conf connected_component_maximal fim image_subset_iff rev_image_eqI S cct)\n  }\n  with False show ?thesis\n    unfolding constant_on_def by blast\nqed\n\n\ntext\\<open>This proof requires the existence of two separate values of the range type.\\<close>\nlemma finite_range_constant_imp_connected:\n  assumes \"\\<And>f::'a::topological_space \\<Rightarrow> 'b::real_normed_algebra_1.\n              \\<lbrakk>continuous_on S f; finite(f ` S)\\<rbrakk> \\<Longrightarrow> f constant_on S\"\n    shows \"connected S\"\nproof -\n  { fix t u\n    assume clt: \"closedin (top_of_set S) t\"\n       and clu: \"closedin (top_of_set S) u\"\n       and tue: \"t \\<inter> u = {}\" and tus: \"t \\<union> u = S\"\n    have conif: \"continuous_on S (\\<lambda>x. if x \\<in> t then 0 else 1)\"\n      apply (subst tus [symmetric])\n      apply (rule continuous_on_cases_local)\n      using clt clu tue\n      apply (auto simp: tus)\n      done\n    have fi: \"finite ((\\<lambda>x. if x \\<in> t then 0 else 1) ` S)\"\n      by (rule finite_subset [of _ \"{0,1}\"]) auto\n    have \"t = {} \\<or> u = {}\"\n      using assms [OF conif fi] tus [symmetric]\n      by (auto simp: Ball_def constant_on_def) (metis IntI empty_iff one_neq_zero tue)\n  }\n  then show ?thesis\n    by (simp add: connected_closedin_eq)\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/Connected.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8723473879530492, "lm_q2_score": 0.8267117962054049, "lm_q1q2_score": 0.7211798760097585}}
{"text": "theory ConcreteSemantics10_1_Fold\n  imports Main \"~~/src/HOL/IMP/Big_Step\"  \"~~/src/HOL/IMP/Vars\" \nbegin \n\nsubsection \"Simple folding of arithmetic expressions\"\n\ntype_synonym tab = \"vname \\<Rightarrow> val option\"\n\nfun afold :: \"aexp \\<Rightarrow> tab \\<Rightarrow> aexp\" where\n\"afold (N n) _ = N n\" |\n\"afold (V x) t = (case t x of None \\<Rightarrow> V x | Some k \\<Rightarrow> N k)\" |\n\"afold (Plus e1 e2) t = (case (afold e1 t, afold e2 t) of\n  (N n1, N n2) \\<Rightarrow> N(n1+n2) | (e1',e2') \\<Rightarrow> Plus e1' e2')\"\n\ndefinition  \"approx t s \\<longleftrightarrow> (\\<forall> x k. t x = Some k \\<longrightarrow> s x = k)\"\n\n(*Lemma 10.6 (Correctness of afold).*)\ntheorem aval_afold[simp]:\nassumes \"approx t s\"\nshows \"aval (afold a t) s = aval a s\"\nproof (induction a)\n  case (N x)\n  then show ?case by auto \nnext\n  case (V x)\n  then show ?case using assms by (auto simp: approx_def split: option.split )\nnext\n  case (Plus a1 a2)\n  then show ?case using assms by (auto simp: approx_def split: option.split aexp.split)\nqed\n\ntheorem aval_afold_N:\nassumes \"approx t s\"\nshows \"afold a t = N n \\<Longrightarrow> aval a s = n\"\n  by (metis assms aval.simps(1) aval_afold)\n\ndefinition\n  \"merge t1 t2 = (\\<lambda>m. if t1 m = t2 m then t1 m else None)\"\n\nprimrec \"defs\" :: \"com \\<Rightarrow> tab \\<Rightarrow> tab\" where\n\"defs SKIP t = t\" |\n\"defs (x ::= a) t =\n  (case afold a t of N k \\<Rightarrow> t(x \\<mapsto> k) | _ \\<Rightarrow> t(x:=None))\" |\n\"defs (c1;;c2) t = (defs c2 o defs c1) t\" |\n\"defs (IF b THEN c1 ELSE c2) t = merge (defs c1 t) (defs c2 t)\" |\n\"defs (WHILE b DO c) t = t |` (-lvars c)\"\n\nprimrec fold where\n\"fold SKIP _ = SKIP\" |\n\"fold (x ::= a) t = (x ::= (afold a t))\" |\n\"fold (c1;;c2) t = (fold c1 t;; fold c2 (defs c1 t))\" |\n\"fold (IF b THEN c1 ELSE c2) t = IF b THEN fold c1 t ELSE fold c2 t\" |\n\"fold (WHILE b DO c) t = WHILE b DO fold c (t |` (-lvars c))\"\n\nvalue \"fold(''x'' ::= Plus (N 42) (N (- 5))) nil\"\nvalue \"defs (fold(''x'' ::= Plus (N 42) (N (- 5))) nil ) nil\"\nvalue \"fold(''y'' ::= Plus (V ''x'') (V ''x'')) (defs (fold(''x'' ::= Plus (N 42) (N (- 5))) nil ) nil)\"\nvalue \"fold(''x'' ::= Plus (N 42) (N (- 5));;''y'' ::= Plus (V ''x'') (V ''x'')) nil\"\n\nsubsection \"Semantic Equivalence up to a Condition\"\n\ntype_synonym assn = \"state \\<Rightarrow> bool\"\n\ndefinition\n  equiv_up_to :: \"assn \\<Rightarrow> com \\<Rightarrow> com \\<Rightarrow> bool\" (\"_ \\<Turnstile> _ \\<sim> _\" [50,0,10] 50)\nwhere\n  \"(P \\<Turnstile> c \\<sim> c') = (\\<forall>s s'. P s \\<longrightarrow> (c,s) \\<Rightarrow> s' \\<longleftrightarrow> (c',s) \\<Rightarrow> s')\"\n\ndefinition\n  bequiv_up_to :: \"assn \\<Rightarrow> bexp \\<Rightarrow> bexp \\<Rightarrow> bool\" (\"_ \\<Turnstile> _ <\\<sim>> _\" [50,0,10] 50)\nwhere\n  \"(P \\<Turnstile> b <\\<sim>> b') = (\\<forall>s. P s \\<longrightarrow> bval b s = bval b' s)\"\n\n(* Lemma 10.7. *)\nlemma equiv_up_to_True:\n  \"((\\<lambda>_. True) \\<Turnstile> c \\<sim> c') = (c \\<sim> c')\"\n  by (simp add: equiv_up_to_def)\n\nlemma equiv_up_to_weaken:\n  \"P \\<Turnstile> c \\<sim> c' \\<Longrightarrow> (\\<And>s. P' s \\<Longrightarrow> P s) \\<Longrightarrow> P' \\<Turnstile> c \\<sim> c'\"\n  by (simp add: equiv_up_to_def)\n\nlemma equiv_up_toI:\n  \"(\\<And>s s'. P s \\<Longrightarrow> (c, s) \\<Rightarrow> s' = (c', s) \\<Rightarrow> s') \\<Longrightarrow> P \\<Turnstile> c \\<sim> c'\"\n  by (unfold equiv_up_to_def) blast\n\nlemma equiv_up_toD1:\n  \"P \\<Turnstile> c \\<sim> c' \\<Longrightarrow> (c, s) \\<Rightarrow> s' \\<Longrightarrow> P s \\<Longrightarrow> (c', s) \\<Rightarrow> s'\"\n  by (unfold equiv_up_to_def) blast\n\nlemma equiv_up_toD2:\n  \"P \\<Turnstile> c \\<sim> c' \\<Longrightarrow> (c', s) \\<Rightarrow> s' \\<Longrightarrow> P s \\<Longrightarrow> (c, s) \\<Rightarrow> s'\"\n  by (unfold equiv_up_to_def) blast\n\n(* Lemma 10.8 (Equivalence Relation). *)\nlemma equiv_up_to_refl [simp, intro!]:\n  \"P \\<Turnstile> c \\<sim> c\"\n  by (simp add: equiv_up_to_def)\n\nlemma equiv_up_to_sym:\n  \"(P \\<Turnstile> c \\<sim> c') = (P \\<Turnstile> c' \\<sim> c)\"\n  by (auto simp add: equiv_up_to_def)\n\nlemma equiv_up_to_trans:\n  \"P \\<Turnstile> c \\<sim> c' \\<Longrightarrow> P \\<Turnstile> c' \\<sim> c'' \\<Longrightarrow> P \\<Turnstile> c \\<sim> c''\"\n  by(auto simp add: equiv_up_to_def)\n\n\nlemma bequiv_up_to_refl [simp, intro!]:\n  \"P \\<Turnstile> b <\\<sim>> b\"\n  by (auto simp: bequiv_up_to_def)\n\nlemma bequiv_up_to_sym:\n  \"(P \\<Turnstile> b <\\<sim>> b') = (P \\<Turnstile> b' <\\<sim>> b)\"\n  by (auto simp: bequiv_up_to_def)\n\nlemma bequiv_up_to_trans:\n  \"P \\<Turnstile> b <\\<sim>> b' \\<Longrightarrow> P \\<Turnstile> b' <\\<sim>> b'' \\<Longrightarrow> P \\<Turnstile> b <\\<sim>> b''\"\n  by (auto simp: bequiv_up_to_def)\n\nlemma bequiv_up_to_subst:\n  \"P \\<Turnstile> b <\\<sim>> b' \\<Longrightarrow> P s \\<Longrightarrow> bval b s = bval b' s\"\n  by (simp add: bequiv_up_to_def)\n\n(* Congruence rules *)\nlemma equiv_up_to_seq:\n  \"P \\<Turnstile> c \\<sim> c' \\<Longrightarrow> Q \\<Turnstile> d \\<sim> d' \\<Longrightarrow>\n  (\\<And>s s'. (c,s) \\<Rightarrow> s' \\<Longrightarrow> P s \\<Longrightarrow> Q s') \\<Longrightarrow>\n  P \\<Turnstile> (c;; d) \\<sim> (c';; d')\"\n  apply(simp add: equiv_up_to_def)\n  apply blast\n  done\n\nlemma equiv_up_to_if_weak:\n  \"P \\<Turnstile> b <\\<sim>> b' \\<Longrightarrow> P \\<Turnstile> c \\<sim> c' \\<Longrightarrow> P \\<Turnstile> d \\<sim> d' \\<Longrightarrow>\n   P \\<Turnstile> IF b THEN c ELSE d \\<sim> IF b' THEN c' ELSE d'\"\n  apply(auto simp: bequiv_up_to_def equiv_up_to_def)\n  done\n\n\nlemma equiv_up_to_while_lemma_weak:\n  shows \"(d,s) \\<Rightarrow> s' \\<Longrightarrow>\n         P \\<Turnstile> b <\\<sim>> b' \\<Longrightarrow>\n         P \\<Turnstile> c \\<sim> c' \\<Longrightarrow>\n         (\\<And>s s'. (c, s) \\<Rightarrow> s' \\<Longrightarrow> P s \\<Longrightarrow> bval b s \\<Longrightarrow> P s') \\<Longrightarrow>\n         P s \\<Longrightarrow>\n         d = WHILE b DO c \\<Longrightarrow>\n         (WHILE b' DO c', s) \\<Rightarrow> s'\"\n  sorry\n\nlemma equiv_up_to_while_weak:\n  assumes b: \"P \\<Turnstile> b <\\<sim>> b'\"\n  assumes c: \"P \\<Turnstile> c \\<sim> c'\"\n  assumes I: \"\\<And>s s'. (c, s) \\<Rightarrow> s' \\<Longrightarrow> P s \\<Longrightarrow> bval b s \\<Longrightarrow> P s'\"\n  shows \"P \\<Turnstile> WHILE b DO c \\<sim> WHILE b' DO c'\"\nproof -\n  from b have b': \"P \\<Turnstile> b' <\\<sim>> b\" \n    by (simp add: bequiv_up_to_sym)\n  from c have c': \"P \\<Turnstile> c' \\<sim> c\" \n    by (simp add: equiv_up_to_sym)\n\n  from I have I' :\"\\<And>s s'. (c', s) \\<Rightarrow> s' \\<Longrightarrow> P s \\<Longrightarrow> bval b' s \\<Longrightarrow> P s'\"\n    using b' bequiv_up_to_subst c' equiv_up_to_def by auto\n\n  note equiv_up_to_while_lemma_weak [OF _ b c]\n       equiv_up_to_while_lemma_weak [OF _ b' c']\n  thus ?thesis using I I' by (auto intro!: equiv_up_toI)\nqed\n\n\nlemma approx_merge:\n  \"approx t1 s \\<or> approx t2 s \\<Longrightarrow> approx (merge t1 t2) s\"\n  by (fastforce simp: merge_def approx_def)\n\nlemma approx_map_le:\n  \"approx t2 s \\<Longrightarrow> t1 \\<subseteq>\\<^sub>m t2 \\<Longrightarrow> approx t1 s\"\n  by (clarsimp simp: approx_def map_le_def dom_def)\n\nlemma restrict_map_le [intro!, simp]: \"t |` S \\<subseteq>\\<^sub>m t\"\n  by (clarsimp simp: restrict_map_def map_le_def)\n\nlemma merge_restrict:\n  assumes \"t1 |` S = t |` S\"\n  assumes \"t2 |` S = t |` S\"\n  shows \"merge t1 t2 |` S = t |` S\"\nproof -\n  from assms\n  have \"\\<forall>x. (t1 |` S) x = (t |` S) x\"\n   and \"\\<forall>x. (t2 |` S) x = (t |` S) x\" by auto\n  thus ?thesis\n    by (auto simp: merge_def restrict_map_def\n             split: if_splits)\nqed\n\n(* Lemma 10.10. *)\nlemma defs_restrict:\n  \"defs c t |` (- lvars c) = t |` (- lvars c)\"\nproof(induction c arbitrary: t)\n  case SKIP\n  then show ?case \n    by simp\nnext\n  case (Assign x1 x2)\n  then show ?case by (auto split: aexp.split)\nnext\n  case (Seq c1 c2)\n(*\n    defs c1 ?t |` (- lvars c1) = ?t |` (- lvars c1)\n    defs c2 ?t |` (- lvars c2) = ?t |` (- lvars c2)\n\ndefs (?c1.2;; ?c2.2) ?ta2 |` (- lvars (?c1.2;; ?c2.2)) = ?ta2 |` (- lvars (?c1.2;; ?c2.2)) \n*)\n  have \"defs c2 (defs c1 t) |` (- lvars c2) |` (- lvars c1) =\n         defs c1 t |` (- lvars c2) |` (- lvars c1)\" \n    by (simp add: Seq.IH(2))\n  moreover have \"defs c1 t |` (- lvars c1) |` (-lvars c2) =\n         t |` (- lvars c1) |` (-lvars c2)\" \n    by (simp add: Seq.IH(1))\n  ultimately show ?case \n    by (simp add: Int_commute)\nnext\n  case (If x1 c1 c2)\n(*\n  (\\<And>t. defs ?c1.2 t |` (- lvars ?c1.2) = t |` (- lvars ?c1.2)) \\<Longrightarrow>\n  (\\<And>t. defs ?c2.2 t |` (- lvars ?c2.2) = t |` (- lvars ?c2.2)) \\<Longrightarrow>\n  defs (IF ?x1.2 THEN ?c1.2 ELSE ?c2.2) ?ta2 |` (- lvars (IF ?x1.2 THEN ?c1.2 ELSE ?c2.2)) =\n  ?ta2 |` (- lvars (IF ?x1.2 THEN ?c1.2 ELSE ?c2.2)) \n*)\n  have \"defs c1 t |` (- lvars c1) |` (- lvars c2) =\n         t |` (- lvars c1) |` (- lvars c2)\" \n    using If.IH(1) by auto\n  moreover have \"defs c2 t |` (- lvars c1) |` (-lvars c2) =\n         t |` (- lvars c1) |` (-lvars c2)\" \n    by (metis If.IH(2) inf_sup_aci(1) restrict_restrict)\n  ultimately  show ?case by (auto simp: Int_commute intro: merge_restrict)\nnext\n  case (While x1 c)\n  then show ?case by (auto split: aexp.split)\nqed\n\n\n(* Lemma 10.9 (defs approximates execution correctly). *)\nlemma big_step_pres_approx:\n  \"(c,s) \\<Rightarrow> s' \\<Longrightarrow> approx t s \\<Longrightarrow> approx (defs c t) s'\"\nproof(induction arbitrary: t rule: big_step_induct )\ncase (Skip s)\n  then show ?case by simp\nnext\n  case (Assign x a s)\n  then show ?case \n    (*by(simp add: approx_def split: aexp.split)*)\n    by(simp add: aval_afold_N approx_def split: aexp.split)\nnext\n  case (Seq c\\<^sub>1 s\\<^sub>1 s\\<^sub>2 c\\<^sub>2 s\\<^sub>3)\n(*\n  (\\<And>t. approx t ?s\\<^sub>12 \\<Longrightarrow> approx (defs ?c\\<^sub>12 t) ?s\\<^sub>22) \\<Longrightarrow>\n  (\\<And>t. approx t ?s\\<^sub>22 \\<Longrightarrow> approx (defs ?c\\<^sub>22 t) ?s\\<^sub>32) \\<Longrightarrow>\n*)\n  have \"approx (defs c\\<^sub>1 t) s\\<^sub>2\" \n    by (simp add: Seq.IH(1) Seq.prems)\n  have \"approx (defs c\\<^sub>2 (defs c\\<^sub>1 t)) s\\<^sub>3\" \n    by (simp add: Seq.IH(2) \\<open>approx (defs c\\<^sub>1 t) s\\<^sub>2\\<close>)\n  then show ?case \n    by simp\nnext\n  case (IfTrue b s c\\<^sub>1 t c\\<^sub>2)\n  then show ?case \n    by (simp add: approx_merge)\nnext\n  case (IfFalse b s c\\<^sub>2 t c\\<^sub>1)\n  then show ?case \n    by (simp add: approx_merge)\nnext\n  case (WhileFalse b s c)\n  then show ?case \n    by (simp add: approx_def restrict_map_def)\nnext\n  case (WhileTrue b s\\<^sub>1 c s\\<^sub>2 s\\<^sub>3)\n  hence \"approx (defs c t) s\\<^sub>2\" by simp\n  then have \"approx (defs c t |` (-lvars c)) s\\<^sub>3\" \n    using WhileTrue.IH(2) by auto\n  then show ?case \n    by (simp add: defs_restrict)\nqed\n\n(* Lemma 10.11. *)\n\nlemma big_step_pres_approx_restrict:\n  \"(c,s) \\<Rightarrow> s' \\<Longrightarrow> approx (t |` (-lvars c)) s \\<Longrightarrow> approx (t |` (-lvars c)) s'\"\nproof(induction arbitrary: t rule: big_step_induct)\ncase (Skip s)\n  then show ?case by simp\nnext\n  case (Assign x a s)\n  then show ?case by(simp add: aval_afold_N approx_def split: aexp.split)\nnext\n  case (Seq c1 s1 s2 c2 s3)\n(*\nusing this:\n    defs c2 (defs c1 t) |` (- lvars c2) |` (- lvars c1) =\n    defs c1 t |` (- lvars c2) |` (- lvars c1)\n    defs c1 t |` (- lvars c1) |` (- lvars c2) = t |` (- lvars c1) |` (- lvars c2)\n\ngoal (1 subgoal):\n 1. approx (t |` (- lvars (c1;; c2))) s3\n*)\n  then have \"approx (t |` (-lvars c2) |` (-lvars c1)) s1\" by (simp add: Int_commute)\n  hence \"approx (t |` (-lvars c2) |` (-lvars c1)) s2\"\n    by (rule Seq)\n  hence \"approx (t |` (-lvars c1) |` (-lvars c2)) s2\"\n    by (simp add: Int_commute)\n  then have \"approx (t |` (-lvars c1) |` (-lvars c2)) s3\" \n    using Seq.IH(2) by blast\n  then show ?case by simp\nnext\n  case (IfTrue b s c1 s' c2)\n(*\nusing this:\n    bval b s\n    (c\\<^sub>1, s) \\<Rightarrow> ta__\n    approx (?t |` (- lvars c\\<^sub>1)) s \\<Longrightarrow> approx (?t |` (- lvars c\\<^sub>1)) ta__\n    approx (t |` (- lvars (IF b THEN c\\<^sub>1 ELSE c\\<^sub>2))) s\n\ngoal (1 subgoal):\n 1. approx (t |` (- lvars (IF b THEN c\\<^sub>1 ELSE c\\<^sub>2))) ta__\n*)\n  then have \"approx (t |` (-lvars c2) |` (-lvars c1)) s\" by (simp add: Int_commute)\n  then have \"approx (t |` (-lvars c2) |` (-lvars c1)) s'\" \n    using IfTrue.IH by blast\n  then show ?case \n    (*by (simp add: approx_merge)*)\n    by (simp add: Int_commute)\nnext\n  case (IfFalse b s c2 s' c1)\n  then have \"approx (t |` (-lvars c1) |` (-lvars c2)) s\" by (simp add: Int_commute)\n  then have \"approx (t |` (-lvars c1) |` (-lvars c2)) s'\" \n    using IfFalse.IH by blast\n  then show ?case \n    (*by (simp add: approx_merge)*)\n    by (simp add: Int_commute)\nnext\n  case (WhileFalse b s c)\n  then show ?case \n    by (simp add: approx_def restrict_map_def)\nnext\n  case (WhileTrue b s\\<^sub>1 c s\\<^sub>2 s\\<^sub>3)\n  then show ?case \n    by (simp add: defs_restrict)\nqed\n\n(* Lemma 10.12 (Generalized correctness of constant folding). *) \ntext \\<open>\nthe declaration is needed to prove the case of Assign.\n\\<close>\n(*declare assign_simp [simp]*)\n\nlemma approx_eq:\n  \"approx t \\<Turnstile> c \\<sim> fold c t\"\n  proof(induction c arbitrary: t)\ncase SKIP\n  then show ?case by simp\nnext\n  case (Assign x1 x2)\n  then show ?case by (auto simp: assign_simp equiv_up_to_def)\nnext\n  case (Seq c1 c2)\n  then show ?case \n    by (auto intro!: equiv_up_to_seq big_step_pres_approx)\n(*    by (smt ConcreteSemantics10_1_Fold.fold.simps(3) big_step_pres_approx equiv_up_to_seq)*)\nnext\n  case (If x1 c1 c2)\n  then show ?case \n    by (simp add: equiv_up_to_if_weak)\nnext\n  case (While x1 c)\n(*\n 1. \\<And>x1 c t.\n       (\\<And>t. approx t \\<Turnstile> c \\<sim> ConcreteSemantics10_1_Fold.fold c t) \\<Longrightarrow>\n       approx t \\<Turnstile> WHILE x1 DO c \\<sim> ConcreteSemantics10_1_Fold.fold (WHILE x1 DO c) t\n*)\n  then have \"approx (t |` (- lvars c)) \\<Turnstile> WHILE x1 DO c \\<sim> WHILE x1 DO fold c (t |` (-lvars c))\" \n    by (simp add: big_step_pres_approx_restrict equiv_up_to_while_weak)\n  then show ?case \n    by (simp add: approx_map_le equiv_up_to_def)\nqed\n\n\n(*Theorem 10.13 (Correctness of constant folding).*)\nlemma approx_empty [simp]:\n  \"approx Map.empty = (\\<lambda>_. True)\"\n  by (auto simp: approx_def)\n\ntheorem constant_folding_equiv:\n  \"fold c Map.empty \\<sim> c\"\n  using approx_eq\n  by (metis approx_empty equiv_up_toD1 equiv_up_toD2)\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/ConcreteSemanticsChapter10/ConcreteSemantics10_1_Fold.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473779969194, "lm_q2_score": 0.8267118026095991, "lm_q1q2_score": 0.7211798733655905}}
{"text": "(*  Title:      HOL/Library/List_lexord.thy\n    Author:     Norbert Voelker\n*)\n\nsection \\<open>Lexicographic order on lists\\<close>\n\ntheory List_lexord\nimports Main\nbegin\n\ninstantiation list :: (ord) ord\nbegin\n\ndefinition\n  list_less_def: \"xs < ys \\<longleftrightarrow> (xs, ys) \\<in> lexord {(u, v). u < v}\"\n\ndefinition\n  list_le_def: \"(xs :: _ list) \\<le> ys \\<longleftrightarrow> xs < ys \\<or> xs = ys\"\n\ninstance ..\n\nend\n\ninstance list :: (order) order\nproof\n  fix xs :: \"'a list\"\n  show \"xs \\<le> xs\" by (simp add: list_le_def)\nnext\n  fix xs ys zs :: \"'a list\"\n  assume \"xs \\<le> ys\" and \"ys \\<le> zs\"\n  then show \"xs \\<le> zs\"\n    apply (auto simp add: list_le_def list_less_def)\n    apply (rule lexord_trans)\n    apply (auto intro: transI)\n    done\nnext\n  fix xs ys :: \"'a list\"\n  assume \"xs \\<le> ys\" and \"ys \\<le> xs\"\n  then show \"xs = ys\"\n    apply (auto simp add: list_le_def list_less_def)\n    apply (rule lexord_irreflexive [THEN notE])\n    defer\n    apply (rule lexord_trans)\n    apply (auto intro: transI)\n    done\nnext\n  fix xs ys :: \"'a list\"\n  show \"xs < ys \\<longleftrightarrow> xs \\<le> ys \\<and> \\<not> ys \\<le> xs\"\n    apply (auto simp add: list_less_def list_le_def)\n    defer\n    apply (rule lexord_irreflexive [THEN notE])\n    apply auto\n    apply (rule lexord_irreflexive [THEN notE])\n    defer\n    apply (rule lexord_trans)\n    apply (auto intro: transI)\n    done\nqed\n\ninstance list :: (linorder) linorder\nproof\n  fix xs ys :: \"'a list\"\n  have \"(xs, ys) \\<in> lexord {(u, v). u < v} \\<or> xs = ys \\<or> (ys, xs) \\<in> lexord {(u, v). u < v}\"\n    by (rule lexord_linear) auto\n  then show \"xs \\<le> ys \\<or> ys \\<le> xs\"\n    by (auto simp add: list_le_def list_less_def)\nqed\n\ninstantiation list :: (linorder) distrib_lattice\nbegin\n\ndefinition \"(inf :: 'a list \\<Rightarrow> _) = min\"\n\ndefinition \"(sup :: 'a list \\<Rightarrow> _) = max\"\n\ninstance\n  by standard (auto simp add: inf_list_def sup_list_def max_min_distrib2)\n\nend\n\nlemma not_less_Nil [simp]: \"\\<not> x < []\"\n  by (simp add: list_less_def)\n\nlemma Nil_less_Cons [simp]: \"[] < a # x\"\n  by (simp add: list_less_def)\n\nlemma Cons_less_Cons [simp]: \"a # x < b # y \\<longleftrightarrow> a < b \\<or> a = b \\<and> x < y\"\n  by (simp add: list_less_def)\n\nlemma le_Nil [simp]: \"x \\<le> [] \\<longleftrightarrow> x = []\"\n  unfolding list_le_def by (cases x) auto\n\nlemma Nil_le_Cons [simp]: \"[] \\<le> x\"\n  unfolding list_le_def by (cases x) auto\n\nlemma Cons_le_Cons [simp]: \"a # x \\<le> b # y \\<longleftrightarrow> a < b \\<or> a = b \\<and> x \\<le> y\"\n  unfolding list_le_def by auto\n\ninstantiation list :: (order) order_bot\nbegin\n\ndefinition \"bot = []\"\n\ninstance\n  by standard (simp add: bot_list_def)\n\nend\n\nlemma less_list_code [code]:\n  \"xs < ([]::'a::{equal, order} list) \\<longleftrightarrow> False\"\n  \"[] < (x::'a::{equal, order}) # xs \\<longleftrightarrow> True\"\n  \"(x::'a::{equal, order}) # xs < y # ys \\<longleftrightarrow> x < y \\<or> x = y \\<and> xs < ys\"\n  by simp_all\n\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/Library/List_lexord.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473746782093, "lm_q2_score": 0.8267117962054049, "lm_q1q2_score": 0.7211798650352917}}
{"text": "(*\n  Authors: Asta Halkj\u00e6r From & J\u00f8rgen Villadsen, DTU Compute\n*)\n\nsection \\<open>Formalization of the Bernays-Tarski Axiom System for Classical Implicational Logic\\<close>\n\n(* Uncomment for Full Classical Propositional Logic *)\n\nsubsection \\<open>Syntax, Semantics and Axiom System\\<close>\n\ntheory Implicational_Logic imports Main begin\n\ndatatype form =\n  (*Falsity (\\<open>\\<bottom>\\<close>) |*)\n  Pro nat (\\<open>\\<cdot>\\<close>) |\n  Imp form form (infixr \\<open>\\<rightarrow>\\<close> 55)\n\nprimrec semantics (infix \\<open>\\<Turnstile>\\<close> 50) where\n  (*\\<open>I \\<Turnstile> \\<bottom> = False\\<close> |*)\n  \\<open>I \\<Turnstile> \\<cdot> n = I n\\<close> |\n  \\<open>I \\<Turnstile> p \\<rightarrow> q = (I \\<Turnstile> p \\<longrightarrow> I \\<Turnstile> q)\\<close>\n\ninductive Ax (\\<open>\\<turnstile> _\\<close> 50) where\n  (*Expl: \\<open>\\<turnstile> \\<bottom> \\<rightarrow> p\\<close> |*)\n  Simp: \\<open>\\<turnstile> p \\<rightarrow> q \\<rightarrow> p\\<close> |\n  Tran: \\<open>\\<turnstile> (p \\<rightarrow> q) \\<rightarrow> (q \\<rightarrow> r) \\<rightarrow> p \\<rightarrow> r\\<close> |\n  MP: \\<open>\\<turnstile> p \\<rightarrow> q \\<Longrightarrow> \\<turnstile> p \\<Longrightarrow> \\<turnstile> q\\<close> |\n  PR: \\<open>\\<turnstile> (p \\<rightarrow> q) \\<rightarrow> p \\<Longrightarrow> \\<turnstile> p\\<close>\n\nsubsection \\<open>Soundness and Derived Formulas\\<close>\n\ntheorem soundness: \\<open>\\<turnstile> p \\<Longrightarrow> I \\<Turnstile> p\\<close>\n  by (induct p rule: Ax.induct) auto\n\nlemma Swap: \\<open>\\<turnstile> (p \\<rightarrow> q \\<rightarrow> r) \\<rightarrow> q \\<rightarrow> p \\<rightarrow> r\\<close>\nproof -\n  have \\<open>\\<turnstile> q \\<rightarrow> (q \\<rightarrow> r) \\<rightarrow> r\\<close>\n    using MP PR Simp Tran by metis\n  then show ?thesis\n    using MP Tran by meson\nqed\n\nlemma Peirce: \\<open>\\<turnstile> ((p \\<rightarrow> q) \\<rightarrow> p) \\<rightarrow> p\\<close>\n  using MP PR Simp Swap Tran by meson\n\nlemma Hilbert: \\<open>\\<turnstile> (p \\<rightarrow> p \\<rightarrow> q) \\<rightarrow> p \\<rightarrow> q\\<close>\n  using MP MP Tran Tran Peirce .\n\nlemma Id: \\<open>\\<turnstile> p \\<rightarrow> p\\<close>\n  using MP Hilbert Simp .\n\nlemma Tran': \\<open>\\<turnstile> (q \\<rightarrow> r) \\<rightarrow> (p \\<rightarrow> q) \\<rightarrow> p \\<rightarrow> r\\<close>\n  using MP Swap Tran .\n\nlemma Frege: \\<open>\\<turnstile> (p \\<rightarrow> q \\<rightarrow> r) \\<rightarrow> (p \\<rightarrow> q) \\<rightarrow> p \\<rightarrow> r\\<close>\n  using MP MP Tran MP MP Tran Swap Tran' MP Tran' Hilbert .\n\nlemma Imp1: \\<open>\\<turnstile> (q \\<rightarrow> s) \\<rightarrow> ((q \\<rightarrow> r) \\<rightarrow> s) \\<rightarrow> s\\<close>\n  using MP Peirce Tran Tran' by meson\n\nlemma Imp2: \\<open>\\<turnstile> ((r \\<rightarrow> s) \\<rightarrow> s) \\<rightarrow> ((q \\<rightarrow> r) \\<rightarrow> s) \\<rightarrow> s\\<close>\n  using MP Tran MP Tran Simp .\n\nlemma Imp3: \\<open>\\<turnstile> ((q \\<rightarrow> s) \\<rightarrow> s) \\<rightarrow> (r \\<rightarrow> s) \\<rightarrow> (q \\<rightarrow> r) \\<rightarrow> s\\<close>\n  using MP Swap Tran by meson\n\nsubsection \\<open>Completeness and Main Theorem\\<close>\n\nfun pros where\n  \\<open>pros (p \\<rightarrow> q) = remdups (pros p @ pros q)\\<close> |\n  \\<open>pros p = (case p of (\\<cdot> n) \\<Rightarrow> [n] | _ \\<Rightarrow> [])\\<close>\n\nlemma distinct_pros: \\<open>distinct (pros p)\\<close>\n  by (induct p) simp_all\n\nprimrec imply (infixr \\<open>\\<leadsto>\\<close> 56) where\n  \\<open>[] \\<leadsto> q = q\\<close> |\n  \\<open>p # ps \\<leadsto> q = p \\<rightarrow> ps \\<leadsto> q\\<close>\n\nlemma imply_append: \\<open>ps @ qs \\<leadsto> r = ps \\<leadsto> qs \\<leadsto> r\\<close>\n  by (induct ps) simp_all\n\nabbreviation Ax_assms (infix \\<open>\\<turnstile>\\<close> 50) where \\<open>ps \\<turnstile> q \\<equiv> \\<turnstile> ps \\<leadsto> q\\<close>\n\nlemma imply_Cons: \\<open>ps \\<turnstile> q \\<Longrightarrow> p # ps \\<turnstile> q\\<close>\nproof -\n  assume \\<open>ps \\<turnstile> q\\<close>\n  with MP Simp have \\<open>\\<turnstile> p \\<rightarrow> ps \\<leadsto> q\\<close> .\n  then show ?thesis\n    by simp\nqed\n\nlemma imply_head: \\<open>p # ps \\<turnstile> p\\<close>\n  by (induct ps) (use MP Frege Simp imply.simps in metis)+\n\nlemma imply_mem: \\<open>p \\<in> set ps \\<Longrightarrow> ps \\<turnstile> p\\<close>\n  by (induct ps) (use imply_Cons imply_head in auto)\n\nlemma imply_MP: \\<open>\\<turnstile> ps \\<leadsto> (p \\<rightarrow> q) \\<rightarrow> ps \\<leadsto> p \\<rightarrow> ps \\<leadsto> q\\<close>\nproof (induct ps)\n  case (Cons r ps)\n  then have \\<open>\\<turnstile> (r \\<rightarrow> ps \\<leadsto> (p \\<rightarrow> q)) \\<rightarrow> (r \\<rightarrow> ps \\<leadsto> p) \\<rightarrow> r \\<rightarrow> ps \\<leadsto> q\\<close>\n    using MP Frege Simp by meson\n  then show ?case\n    by simp\nqed (auto intro: Id)\n\nlemma MP': \\<open>ps \\<turnstile> p \\<rightarrow> q \\<Longrightarrow> ps \\<turnstile> p \\<Longrightarrow> ps \\<turnstile> q\\<close>\n  using MP imply_MP by metis\n\nlemma imply_swap_append: \\<open>ps @ qs \\<turnstile> r \\<Longrightarrow> qs @ ps \\<turnstile> r\\<close>\n  by (induct qs arbitrary: ps) (simp, metis MP' imply_append imply_Cons imply_head imply.simps(2))\n\nlemma imply_deduct: \\<open>p # ps \\<turnstile> q \\<Longrightarrow> ps \\<turnstile> p \\<rightarrow> q\\<close>\n  using imply_append imply_swap_append imply.simps by metis\n\nlemma add_imply [simp]: \\<open>\\<turnstile> p \\<Longrightarrow> ps \\<turnstile> p\\<close>\nproof -\n  note MP\n  moreover have \\<open>\\<turnstile> p \\<rightarrow> ps \\<leadsto> p\\<close>\n    using imply_head by simp\n  moreover assume \\<open>\\<turnstile> p\\<close>\n  ultimately show ?thesis .\nqed\n\nlemma imply_weaken: \\<open>ps \\<turnstile> p \\<Longrightarrow> set ps \\<subseteq> set ps' \\<Longrightarrow> ps' \\<turnstile> p\\<close>\n  by (induct ps arbitrary: p) (simp, metis MP' imply_deduct imply_mem insert_subset list.set(2))\n\nabbreviation \\<open>lift t s p \\<equiv> if t then (p \\<rightarrow> s) \\<rightarrow> s else p \\<rightarrow> s\\<close>\n\nabbreviation \\<open>lifts I s \\<equiv> map (\\<lambda>n. lift (I n) s (\\<cdot> n))\\<close>\n\nlemma lifts_weaken: \\<open>lifts I s l \\<turnstile> p \\<Longrightarrow> set l \\<subseteq> set l' \\<Longrightarrow> lifts I s l' \\<turnstile> p\\<close>\n  using imply_weaken by (metis (no_types, lifting) image_mono set_map)\n\nlemma lifts_pros_lift: \\<open>lifts I s (pros p) \\<turnstile> lift (I \\<Turnstile> p) s p\\<close>\nproof (induct p)\n  case (Imp q r)\n  consider \\<open>\\<not> I \\<Turnstile> q\\<close> | \\<open>I \\<Turnstile> r\\<close> | \\<open>I \\<Turnstile> q\\<close> \\<open>\\<not> I \\<Turnstile> r\\<close>\n    by blast\n  then show ?case\n  proof cases\n    case 1\n    then have \\<open>lifts I s (pros (q \\<rightarrow> r)) \\<turnstile> q \\<rightarrow> s\\<close>\n      using Imp(1) lifts_weaken[where l' = \\<open>pros (q \\<rightarrow> r)\\<close>] by simp\n    then have \\<open>lifts I s (pros (q \\<rightarrow> r)) \\<turnstile> ((q \\<rightarrow> r) \\<rightarrow> s) \\<rightarrow> s\\<close>\n      using Imp1 MP' add_imply by blast\n    with 1 show ?thesis\n      by simp\n  next\n    case 2\n    then have \\<open>lifts I s (pros (q \\<rightarrow> r)) \\<turnstile> (r \\<rightarrow> s) \\<rightarrow> s\\<close>\n      using Imp(2) lifts_weaken[where l' = \\<open>pros (q \\<rightarrow> r)\\<close>] by simp\n    then have \\<open>lifts I s (pros (q \\<rightarrow> r)) \\<turnstile> ((q \\<rightarrow> r) \\<rightarrow> s) \\<rightarrow> s\\<close>\n      using Imp2 MP' add_imply by blast\n    with 2 show ?thesis\n      by simp\n  next\n    case 3\n    then have \\<open>lifts I s (pros (q \\<rightarrow> r)) \\<turnstile> (q \\<rightarrow> s) \\<rightarrow> s\\<close> \\<open>lifts I s (pros (q \\<rightarrow> r)) \\<turnstile> r \\<rightarrow> s\\<close>\n      using Imp lifts_weaken[where l' = \\<open>pros (q \\<rightarrow> r)\\<close>] by simp_all\n    then have \\<open>lifts I s (pros (q \\<rightarrow> r)) \\<turnstile> (q \\<rightarrow> r) \\<rightarrow> s\\<close>\n      using Imp3 MP' add_imply by blast\n    with 3 show ?thesis\n      by simp\n  qed\nqed (auto intro: Id Ax.intros)\n\nlemma lifts_pros: \\<open>I \\<Turnstile> p \\<Longrightarrow> lifts I p (pros p) \\<turnstile> p\\<close>\nproof -\n  assume \\<open>I \\<Turnstile> p\\<close>\n  then have \\<open>lifts I p (pros p) \\<turnstile> (p \\<rightarrow> p) \\<rightarrow> p\\<close>\n    using lifts_pros_lift[of I p p] by simp\n  then show ?thesis\n    using Id MP' add_imply by blast\nqed\n\ntheorem completeness: \\<open>\\<forall>I. I \\<Turnstile> p \\<Longrightarrow> \\<turnstile> p\\<close>\nproof -\n  let ?A = \\<open>\\<lambda>l I. lifts I p l \\<turnstile> p\\<close>\n  let ?B = \\<open>\\<lambda>l. \\<forall>I. ?A l I \\<and> distinct l\\<close>\n  assume \\<open>\\<forall>I. I \\<Turnstile> p\\<close>\n  moreover have \\<open>?B l \\<Longrightarrow> (\\<And>n l. ?B (n # l) \\<Longrightarrow> ?B l) \\<Longrightarrow> ?B []\\<close> for l\n    by (induct l) blast+\n  moreover have \\<open>?B (n # l) \\<Longrightarrow> ?B l\\<close> for n l\n  proof -\n    assume *: \\<open>?B (n # l)\\<close>\n    show \\<open>?B l\\<close>\n    proof\n      fix I\n      from * have \\<open>?A (n # l) (I(n := True))\\<close> \\<open>?A (n # l) (I(n := False))\\<close>\n        by blast+\n      moreover from * have \\<open>\\<forall>m \\<in> set l. \\<forall>t. (I(n := t)) m = I m\\<close>\n        by simp\n      ultimately have \\<open>((\\<cdot> n \\<rightarrow> p) \\<rightarrow> p) # lifts I p l \\<turnstile> p\\<close> \\<open>(\\<cdot> n \\<rightarrow> p) # lifts I p l \\<turnstile> p\\<close>\n        by (simp_all cong: map_cong)\n      then have \\<open>?A l I\\<close>\n        using MP' imply_deduct by blast\n      moreover from * have \\<open>distinct (n # l)\\<close>\n        by blast\n      ultimately show \\<open>?A l I \\<and> distinct l\\<close>\n        by simp\n    qed\n  qed\n  ultimately have \\<open>?B []\\<close>\n    using lifts_pros distinct_pros by blast\n  then show ?thesis\n    by simp\nqed\n\ntheorem main: \\<open>(\\<turnstile> p) = (\\<forall>I. I \\<Turnstile> p)\\<close>\n  using soundness completeness by blast\n\nsubsection \\<open>Reference\\<close>\n\ntext \\<open>Wikipedia \\<^url>\\<open>https://en.wikipedia.org/wiki/Implicational_propositional_calculus\\<close> July 2022\\<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/Implicational_Logic/Implicational_Logic.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8723473746782093, "lm_q2_score": 0.8267117940706734, "lm_q1q2_score": 0.7211798631730644}}
{"text": "(*  Title:       Countable Ordinals\n\n    Author:      Brian Huffman, 2005\n    Maintainer:  Brian Huffman <brianh at cse.ogi.edu>\n*)\n\nsection \\<open>Ordinal Arithmetic\\<close>\n\ntheory OrdinalArith\nimports OrdinalRec\nbegin\n\nsubsection \\<open>Addition\\<close>\n\ninstantiation ordinal :: plus\nbegin\n\ndefinition\n  \"(+) = (\\<lambda>x. ordinal_rec x (\\<lambda>p. oSuc))\"\n\ninstance ..\n\nend\n\n\n\nlemma ordinal_plus_0 [simp]: \"x + 0 = (x::ordinal)\"\n  by (simp add: plus_ordinal_def)\n\nlemma ordinal_plus_oSuc [simp]: \"x + oSuc y = oSuc (x + y)\"\n  by (simp add: plus_ordinal_def)\n\nlemma ordinal_plus_oLimit [simp]: \"x + oLimit f = oLimit (\\<lambda>n. x + f n)\"\n  by (simp add: normal.oLimit normal_plus)\n\nlemma ordinal_0_plus [simp]: \"0 + x = (x::ordinal)\"\n  by (rule_tac a=x in oLimit_induct, simp_all)\n\nlemma ordinal_plus_assoc: \"(x + y) + z = x + (y + z::ordinal)\"\n  by (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)\"\n  by (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)\"\n  by (rule order_trans[OF ordinal_plus_monoL ordinal_plus_monoR])\n\nlemma ordinal_plus_strict_monoR: \"y < y' \\<Longrightarrow> x + y < x + (y'::ordinal)\"\n  by (rule normal.strict_monoD[OF normal_plus])\n\nlemma ordinal_le_plusL [simp]: \"y \\<le> x + (y::ordinal)\"\n  by (cut_tac ordinal_plus_monoL[OF ordinal_0_le], simp)\n\nlemma ordinal_le_plusR [simp]: \"x \\<le> x + (y::ordinal)\"\n  by (cut_tac ordinal_plus_monoR[OF ordinal_0_le], simp)\n\nlemma ordinal_less_plusR: \"0 < y \\<Longrightarrow> x < x + (y::ordinal)\"\n  by (drule_tac ordinal_plus_strict_monoR, simp)\n\nlemma ordinal_plus_left_cancel [simp]:\n  \"(w + x = w + y) = (x = (y::ordinal))\"\n  by (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))\"\n  by (rule normal.cancel_le[OF normal_plus])\n\nlemma ordinal_plus_left_cancel_less [simp]:\n  \"(w + x < w + y) = (x < (y::ordinal))\"\n  by (rule normal.cancel_less[OF normal_plus])\n\nlemma ordinal_plus_not_0: \"(0 < x + y) = (0 < x \\<or> 0 < (y::ordinal))\"\n  by (metis ordinal_le_0 ordinal_le_plusL ordinal_neq_0 ordinal_plus_0)\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 \\<open>Subtraction\\<close>\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 unfolding minus_ordinal_def\n  by (simp add: continuous_ordinal_rec order_less_imp_le)\n\nlemma ordinal_0_minus [simp]: \"0 - x = (0::ordinal)\"\n  by (simp add: minus_ordinal_def)\n\nlemma ordinal_oSuc_minus [simp]: \"y \\<le> x \\<Longrightarrow> oSuc x - y = oSuc (x - y)\"\n  by (simp add: minus_ordinal_def)\n\nlemma ordinal_oLimit_minus [simp]: \"oLimit f - y = oLimit (\\<lambda>n. f n - y)\"\n  by (rule continuousD[OF continuous_minus])\n\nlemma ordinal_minus_0 [simp]: \"x - 0 = (x::ordinal)\"\n  by (rule_tac a=x in oLimit_induct, simp_all)\n\nlemma ordinal_oSuc_minus2: \"x < y \\<Longrightarrow> oSuc x - y = x - y\"\n  by (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)\"\n  by simp\n\nlemma ordinal_minus_less_eq [simp]:\n  \"(y::ordinal) \\<le> x \\<Longrightarrow> (x - y < z) = (x < y + z)\"\n  by (metis ordinal_plus_left_cancel_less ordinal_plus_minus2)\n\nlemma ordinal_minus_le_eq [simp]: \"(x - y \\<le> z) = (x \\<le> y + (z::ordinal))\"\nproof (rule linorder_le_cases)\n  assume \"x \\<le> y\" then show ?thesis\n    using order_trans by force\nnext\n  assume \"y \\<le> x\" then show ?thesis\n    by (metis ordinal_plus_left_cancel_le ordinal_plus_minus2)\nqed\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  by (metis linorder_le_cases order_trans ordinal_minus_le_eq ordinal_plus_monoL)\n\n\nsubsection \\<open>Multiplication\\<close>\n\ninstantiation ordinal :: times\nbegin\n\ndefinition\n  times_ordinal_def: \"(*) = (\\<lambda>x. ordinal_rec 0 (\\<lambda>p w. w + x))\"\n\ninstance ..\n\nend\n\nlemma continuous_times: \"continuous ((*) x)\"\n  by (simp add: times_ordinal_def continuous_ordinal_rec)\n\nlemma normal_times: \"0 < x \\<Longrightarrow> normal ((*) x)\"\n  unfolding times_ordinal_def\n  by (simp add: normal_ordinal_rec ordinal_less_plusR)\n\nlemma ordinal_times_0 [simp]: \"x * 0 = (0::ordinal)\"\n  by (simp add: times_ordinal_def)\n\nlemma ordinal_times_oSuc [simp]: \"x * oSuc y = (x * y) + x\"\n  by (simp add: times_ordinal_def)\n\nlemma ordinal_times_oLimit [simp]: \"x * oLimit f = oLimit (\\<lambda>n. x * f n)\"\n  by (simp add: times_ordinal_def ordinal_rec_oLimit)\n\nlemma ordinal_0_times [simp]: \"0 * x = (0::ordinal)\"\n  by (rule_tac a=x in oLimit_induct, simp_all)\n\nlemma ordinal_1_times [simp]: \"oSuc 0 * x = (x::ordinal)\"\n  by (rule_tac a=x in oLimit_induct, simp_all)\n\nlemma ordinal_times_1 [simp]: \"x * oSuc 0 = (x::ordinal)\"\n  by simp\n\nlemma ordinal_times_distrib:\n  \"x * (y + z) = (x * y) + (x * z::ordinal)\"\n  by (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)\"\n  by (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\n  done\n\nlemma ordinal_times_monoR: \"y \\<le> y' \\<Longrightarrow> x * y \\<le> x * (y'::ordinal)\"\n  by (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)\"\n  by (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)\"\n  by (rule normal.strict_monoD[OF normal_times])\n\nlemma ordinal_le_timesL [simp]: \"0 < x \\<Longrightarrow> y \\<le> x * (y::ordinal)\"\n  by (drule ordinal_times_monoL[OF oSuc_leI], simp)\n\nlemma ordinal_le_timesR [simp]: \"0 < y \\<Longrightarrow> x \\<le> x * (y::ordinal)\"\n  by (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)\"\n  by (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))\"\n  by (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))\"\n  by (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))\"\n  by (rule normal.cancel_less[OF normal_times])\n\nlemma ordinal_times_eq_0:\n  \"((x::ordinal) * y = 0) = (x = 0 \\<or> y = 0)\"\n  by (metis ordinal_0_times ordinal_neq_0 ordinal_times_0 ordinal_times_strict_monoR)\n\nlemma ordinal_times_not_0 [simp]:\n  \"((0::ordinal) < x * y) = (0 < x \\<and> 0 < y)\"\n  by (metis ordinal_neq_0 ordinal_times_eq_0)\n\n\nsubsection \\<open>Exponentiation\\<close>\n\ndefinition\n  exp_ordinal :: \"[ordinal, ordinal] \\<Rightarrow> ordinal\" (infixr \"**\" 75) where\n  \"(**) = (\\<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 ((**) x)\"\n  by (simp add: exp_ordinal_def continuous_ordinal_rec)\n\nlemma ordinal_exp_0 [simp]: \"x ** 0 = (1::ordinal)\"\n  by (simp add: exp_ordinal_def)\n\nlemma ordinal_exp_oSuc [simp]: \"x ** oSuc y = (x ** y) * x\"\n  by (simp add: exp_ordinal_def)\n\nlemma ordinal_exp_oLimit [simp]:\n  \"0 < x \\<Longrightarrow> x ** oLimit f = oLimit (\\<lambda>n. x ** f n)\"\n  by (rule continuousD[OF continuous_exp])\n\nlemma ordinal_0_exp [simp]: \"0 ** x = (if x = 0 then 1 else 0)\"\n  by (simp add: exp_ordinal_def)\n\nlemma ordinal_1_exp [simp]: \"oSuc 0 ** x = oSuc 0\"\n  by (rule_tac a=x in oLimit_induct, simp_all)\n\nlemma ordinal_exp_1 [simp]: \"x ** oSuc 0 = x\"\n  by 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)\n  done\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)\n  done\n\nlemma ordinal_exp_eq_0 [simp]: \"(x ** y = 0) = (x = 0 \\<and> 0 < y)\"\n  by (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)\n  done\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\n  done\n\nlemma normal_exp: \"oSuc 0 < x \\<Longrightarrow> normal ((**) x)\"\n  using order_less_trans[OF less_oSuc]\n  by (simp add: normalI ordinal_less_timesR)\n\nlemma ordinal_exp_monoR:\n  \"\\<lbrakk>0 < x; y \\<le> y'\\<rbrakk> \\<Longrightarrow> x ** y \\<le> x ** (y'::ordinal)\"\n  by (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)\"\n  by (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)\"\n  by (rule normal.strict_monoD[OF normal_exp])\n\nlemma ordinal_le_expR [simp]: \"0 < y \\<Longrightarrow> x \\<le> x ** (y::ordinal)\"\n  by (metis leI nless_le oSuc_le_eq_less ordinal_exp_1 ordinal_exp_mono ordinal_le_0)\n\nlemma ordinal_exp_left_cancel [simp]:\n  \"oSuc 0 < w \\<Longrightarrow> (w ** x = w ** y) = (x = y)\"\n  by (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)\"\n  by (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)\"\n  by (rule normal.cancel_less[OF normal_exp])\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/OrdinalArith.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473614033683, "lm_q2_score": 0.8267117940706734, "lm_q1q2_score": 0.7211798521985967}}
{"text": "theory Ex03\nimports Main \"~~/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(* Exercise 3.1 *)\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> \\<Longrightarrow> is_aval (Plus a1 a2) s (v1 + v2)\"\n\n(* Step by step proof \n   We can also use apply(rule N V P)+\n   or apply(rule is_val.intros)+\n   or apply(intro is_aval.intros)\n*)\nlemma \"is_aval (Plus (N 2) (Plus (V x) (N 3))) s (2+(s x + 3))\"\n  apply(rule P)\n  apply(rule N)\n  apply(rule P)\n  apply(rule V)\n  apply(rule N)\n  done\n\ntheorem \"is_aval a s v \\<longleftrightarrow> aval a s = v\"\nproof (* this is the default rule(rule iffI) *)\n  assume \"is_aval a s v\"\n  (* then show \"aval a s = v\" by induction auto *)\n  (* thus \"aval a s = v\" by induction auto *)\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      (* thm P.IH IH *)\n      (* thm P.hyps additional hyps *)\n      (* thm P.prems additional premises, we dont have those here *)\n    have \"aval (Plus a1 a2) s = aval a1 s + aval a2 s\" by simp\n    also from P.IH have \"... = v1 + v2\" by simp (* \"...\" are bound to the RHS of the last equation *)\n    finally show ?case . (* \".\" means by assumption *)\n  qed\nnext\n  assume \"aval a s = v\" thus \"is_aval a s v\"\n  proof induction\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 foo: \"v = aval a1 s + aval a2 s\" by simp\n    thm Plus.IH\n    show ?case\n      unfolding foo\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      oops\n\n(*  by (induction a arbitrary: v) (auto intro: N V P) *)\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/Exercise3/Ex03.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473614033683, "lm_q2_score": 0.8267117898012105, "lm_q1q2_score": 0.7211798484741421}}
{"text": "(*  Title:      HOL/Multivariate_Analysis/Euclidean_Space.thy\n    Author:     Johannes H\u00f6lzl, TU M\u00fcnchen\n    Author:     Brian Huffman, Portland State University\n*)\n\nsection {* Finite-Dimensional Inner Product Spaces *}\n\ntheory Euclidean_Space\nimports\n  L2_Norm\n  \"~~/src/HOL/Library/Inner_Product\"\n  \"~~/src/HOL/Library/Product_Vector\"\nbegin\n\nsubsection {* Type class of Euclidean spaces *}\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\nabbreviation dimension :: \"('a::euclidean_space) itself \\<Rightarrow> nat\" where\n  \"dimension TYPE('a) \\<equiv> card (Basis :: 'a set)\"\n\nsyntax \"_type_dimension\" :: \"type => nat\" (\"(1DIM/(1'(_')))\")\n\ntranslations \"DIM('t)\" == \"CONST dimension (TYPE('t))\"\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_setsum_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_setsum_left inner_Basis if_distrib comm_monoid_add_class.setsum.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_setsum:\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_setsum':\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_setsum[symmetric])\n\nlemma (in euclidean_space) euclidean_representation: \"(\\<Sum>b\\<in>Basis. inner x b *\\<^sub>R b) = x\"\n  unfolding euclidean_representation_setsum 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 DIM_positive: \"0 < DIM('a::euclidean_space)\"\n  by (simp add: card_gt_0_iff)\n\nsubsection {* Subclass relationships *}\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    def y \\<equiv> \"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 `0 < e` have \"y \\<noteq> x\"\n      unfolding y_def by (auto intro!: nonzero_Basis)\n    from `0 < e` have \"dist y x < e\"\n      unfolding y_def by (simp add: dist_norm)\n    from `y \\<noteq> x` and `dist y x < e` show \"False\"\n      using e by simp\n  qed\nqed\n\nsubsection {* Class instances *}\n\nsubsubsection {* Type @{typ real} *}\n\ninstantiation real :: euclidean_space\nbegin\n\ndefinition \n  [simp]: \"Basis = {1::real}\"\n\ninstance\n  by default auto\n\nend\n\nlemma DIM_real[simp]: \"DIM(real) = 1\"\n  by simp\n\nsubsubsection {* Type @{typ complex} *}\n\ninstantiation complex :: euclidean_space\nbegin\n\ndefinition Basis_complex_def:\n  \"Basis = {1, ii}\"\n\ninstance\n  by default (auto simp add: Basis_complex_def intro: complex_eqI split: split_if_asm)\n\nend\n\nlemma DIM_complex[simp]: \"DIM(complex) = 2\"\n  unfolding Basis_complex_def by simp\n\nsubsubsection {* Type @{typ \"'a \\<times> 'b\"} *}\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 setsum_Basis_prod_eq:\n  fixes f::\"('a*'b)\\<Rightarrow>('a*'b)\"\n  shows \"setsum f Basis = setsum (\\<lambda>i. f (i, 0)) Basis + setsum (\\<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 setsum.union_disjoint) (auto simp: Basis_prod_def setsum.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: split_if_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": "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/Euclidean_Space.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117769928211, "lm_q2_score": 0.8723473697001441, "lm_q1q2_score": 0.7211798441598196}}
{"text": "theory Exe3p4\n  imports Main\nbegin\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\nlemma star_post: \"star r x y \\<Longrightarrow> r y z \\<Longrightarrow> star r x z\"\n  apply(induction rule: star.induct)\n   apply(auto simp add: 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(auto simp add: step)\n  done\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\nthm exI exE \n\nlemma \"star r x y \\<Longrightarrow> \\<exists>n. iter r n x y\"\nproof (induction rule: star.induct)\n  case (refl r x)\n  then show ?case\n  \nnext\n  case (step r x y z)\n  then show ?case sorry\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/Exe3p4.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297967961707, "lm_q2_score": 0.8006920068519376, "lm_q1q2_score": 0.7210470102266936}}
{"text": "theory \"HOLCF-Join\"\nimports \"~~/src/HOL/HOLCF/HOLCF\"\nbegin\n\nsubsubsection {* Binary Joins and compatibility *}\n\ncontext cpo\nbegin\ndefinition join :: \"'a => 'a => 'a\" (infix \"\\<squnion>\" 80) where\n  \"x \\<squnion> y = (if \\<exists> z. {x, y} <<| z then lub {x, y} else x)\"\n\ndefinition compatible :: \"'a \\<Rightarrow> 'a \\<Rightarrow> bool\"\n  where \"compatible x y = (\\<exists> z. {x, y} <<| z)\"\n\nlemma compatibleI:\n  assumes \"x \\<sqsubseteq> z\"\n  assumes \"y \\<sqsubseteq> z\"\n  assumes \"\\<And> a. \\<lbrakk> x \\<sqsubseteq> a ; y \\<sqsubseteq> a \\<rbrakk> \\<Longrightarrow> z \\<sqsubseteq> a\"\n  shows \"compatible x y\"\nproof-\n  from assms\n  have \"{x,y} <<| z\"\n    by (auto intro: is_lubI)\n  thus ?thesis unfolding compatible_def by (metis)\nqed\n\nlemma is_joinI:\n  assumes \"x \\<sqsubseteq> z\"\n  assumes \"y \\<sqsubseteq> z\"\n  assumes \"\\<And> a. \\<lbrakk> x \\<sqsubseteq> a ; y \\<sqsubseteq> a \\<rbrakk> \\<Longrightarrow> z \\<sqsubseteq> a\"\n  shows \"x \\<squnion> y = z\"\nproof-\n  from assms\n  have \"{x,y} <<| z\"\n    by (auto intro: is_lubI)\n  thus ?thesis unfolding join_def by (metis lub_eqI)\nqed\n\nlemma is_join_and_compatible:\n  assumes \"x \\<sqsubseteq> z\"\n  assumes \"y \\<sqsubseteq> z\"\n  assumes \"\\<And> a. \\<lbrakk> x \\<sqsubseteq> a ; y \\<sqsubseteq> a \\<rbrakk> \\<Longrightarrow> z \\<sqsubseteq> a\"\n  shows \"compatible x y \\<and> x \\<squnion> y = z\"\nby (metis compatibleI is_joinI assms)\n\nlemma compatible_sym: \"compatible x y \\<Longrightarrow> compatible y x\"\n  unfolding compatible_def by (metis insert_commute)\n\nlemma compatible_sym_iff: \"compatible x y \\<longleftrightarrow> compatible y x\"\n  unfolding compatible_def by (metis insert_commute)\n\nlemma join_above1: \"compatible x y \\<Longrightarrow> x \\<sqsubseteq> x \\<squnion> y\"\n  unfolding compatible_def join_def\n  apply auto\n  by (metis is_lubD1 is_ub_insert lub_eqI)  \n\nlemma join_above2: \"compatible x y \\<Longrightarrow> y \\<sqsubseteq> x \\<squnion> y\"\n  unfolding compatible_def join_def\n  apply auto\n  by (metis is_lubD1 is_ub_insert lub_eqI)  \n\nlemma larger_is_join1: \"y \\<sqsubseteq> x \\<Longrightarrow> x \\<squnion> y = x\"\n  unfolding join_def\n  by (metis doubleton_eq_iff lub_bin)\n\nlemma larger_is_join2: \"x \\<sqsubseteq> y \\<Longrightarrow> x \\<squnion> y = y\"\n  unfolding join_def\n  by (metis is_lub_bin lub_bin)\n\n\n\nlemma join_commute:  \"compatible x y \\<Longrightarrow> x \\<squnion> y = y \\<squnion> x\"\n  unfolding compatible_def unfolding join_def by (metis insert_commute)\n\nlemma lub_is_join:\n  \"{x, y} <<| z \\<Longrightarrow> x \\<squnion> y = z\"\nunfolding join_def by (metis lub_eqI)\n\nlemma compatible_refl[simp]: \"compatible x x\"\n  by (rule compatibleI[OF below_refl below_refl])\n\nlemma join_mono:\n  assumes \"compatible a b\"\n  and \"compatible c d\"\n  and \"a \\<sqsubseteq> c\"\n  and \"b \\<sqsubseteq> d\"\n  shows \"a \\<squnion> b \\<sqsubseteq> c \\<squnion> d\"\nproof-\n  from assms obtain x y where \"{a, b} <<| x\" \"{c, d} <<| y\" unfolding compatible_def by auto\n  with assms have \"a \\<sqsubseteq> y\" \"b \\<sqsubseteq> y\" by (metis below.r_trans is_lubD1 is_ub_insert)+\n  with `{a, b} <<| x` have \"x \\<sqsubseteq> y\" by (metis is_lub_below_iff is_lub_singleton is_ub_insert)\n  moreover\n  from `{a, b} <<| x` `{c, d} <<| y` have \"a \\<squnion> b = x\" \"c \\<squnion> d = y\" by (metis lub_is_join)+\n  ultimately\n  show ?thesis by simp\nqed\n\nlemma\n  assumes \"compatible x y\"\n  shows join_above1: \"x \\<sqsubseteq> x \\<squnion> y\" and join_above2: \"y \\<sqsubseteq> x \\<squnion> y\"\nproof-\n  from assms obtain z where \"{x,y} <<| z\" unfolding compatible_def by auto\n  hence  \"x \\<squnion> y = z\" and \"x \\<sqsubseteq> z\" and \"y \\<sqsubseteq> z\" apply (auto intro: lub_is_join) by (metis is_lubD1 is_ub_insert)+\n  thus \"x \\<sqsubseteq> x \\<squnion> y\" and \"y \\<sqsubseteq> x \\<squnion> y\" by simp_all\nqed\n\nlemma\n  assumes \"compatible x y\"\n  shows compatible_above1: \"compatible x (x \\<squnion> y)\" and compatible_above2: \"compatible y (x \\<squnion> y)\"\nproof-\n  from assms obtain z where \"{x,y} <<| z\" unfolding compatible_def by auto\n  hence  \"x \\<squnion> y = z\" and \"x \\<sqsubseteq> z\" and \"y \\<sqsubseteq> z\" apply (auto intro: lub_is_join) by (metis is_lubD1 is_ub_insert)+\n  thus  \"compatible x (x \\<squnion> y)\" and  \"compatible y (x \\<squnion> y)\" by (metis below.r_refl compatibleI)+\nqed\n\nlemma join_below:\n  assumes \"compatible x y\"\n  and \"x \\<sqsubseteq> a\" and \"y \\<sqsubseteq> a\"\n  shows \"x \\<squnion> y \\<sqsubseteq> a\"\nproof-\n  from assms obtain z where z: \"{x,y} <<| z\" unfolding compatible_def by auto\n  with assms have \"z \\<sqsubseteq> a\" by (metis is_lub_below_iff is_ub_empty is_ub_insert)\n  moreover\n  from z have \"x \\<squnion> y = z\" by (rule lub_is_join) \n  ultimately show ?thesis by simp\nqed\n\nlemma join_assoc:\n  assumes \"compatible x y\"\n  assumes \"compatible x (y \\<squnion> z)\"\n  assumes \"compatible y z\"\n  shows \"(x \\<squnion> y) \\<squnion> z = x \\<squnion> (y \\<squnion> z)\"\n  apply (rule is_joinI)\n  apply (rule join_mono[OF assms(1) assms(2) below_refl join_above1[OF assms(3)]])\n  apply (rule below_trans[OF join_above2[OF assms(3)] join_above2[OF assms(2)]])\n  apply (rule join_below[OF assms(2)])\n  apply (erule rev_below_trans)\n  apply (rule join_above1[OF assms(1)])\n  apply (rule join_below[OF assms(3)])\n  apply (erule rev_below_trans)\n  apply (rule join_above2[OF assms(1)])\n  apply assumption\n  done\n\nlemma join_idem[simp]: \"compatible x y \\<Longrightarrow> x \\<squnion> (x \\<squnion> y) = x \\<squnion> y\"\n  apply (subst join_assoc[symmetric])\n  apply (rule compatible_refl)\n  apply (erule compatible_above1)\n  apply assumption\n  apply (subst join_self)\n  apply rule\n  done\n\nlemma join_bottom[simp]: \"x \\<squnion> \\<bottom> = x\" \"\\<bottom> \\<squnion> x = x\"\n  by (auto intro: is_joinI)\n\nlemma compatible_adm2:\n  shows \"adm (\\<lambda> y. compatible x y)\"\nproof(rule admI)\n  fix Y\n  assume c: \"chain Y\" and \"\\<forall>i.  compatible x (Y i)\"\n  hence a: \"\\<And> i. compatible x (Y i)\" by auto\n  show \"compatible x (\\<Squnion> i. Y i)\"\n  proof(rule compatibleI)\n    have c2: \"chain (\\<lambda>i. x \\<squnion> Y i)\"\n      apply (rule chainI)\n      apply (rule join_mono[OF a a below_refl chainE[OF `chain Y`]])\n      done\n    show \"x \\<sqsubseteq> (\\<Squnion> i. x \\<squnion> Y i)\"\n      by (auto intro: admD[OF _ c2] join_above1[OF a])\n    show \"(\\<Squnion> i. Y i) \\<sqsubseteq> (\\<Squnion> i. x \\<squnion> Y i)\"\n      by (auto intro: admD[OF _ c] below_lub[OF c2 join_above2[OF a]])\n    fix a\n    assume \"x \\<sqsubseteq> a\" and \"(\\<Squnion> i. Y i) \\<sqsubseteq> a\"\n    show \"(\\<Squnion> i. x \\<squnion> Y i) \\<sqsubseteq> a\"\n      apply (rule lub_below[OF c2])\n      apply (rule join_below[OF a `x \\<sqsubseteq> a`])\n      apply (rule below_trans[OF is_ub_thelub[OF c] `(\\<Squnion> i. Y i) \\<sqsubseteq> a`])\n      done\n  qed\nqed\n\nlemma compatible_adm1: \"adm (\\<lambda> x. compatible x y)\"\n  by (subst compatible_sym_iff, rule compatible_adm2)\n\nlemma join_cont1:\n  assumes \"chain Y\"\n  assumes compat: \"\\<And> i. compatible (Y i) y\"\n  shows \"(\\<Squnion>i. Y i) \\<squnion> y = (\\<Squnion> i. Y i \\<squnion> y)\"\nproof-\n  have c: \"chain (\\<lambda>i. Y i \\<squnion> y)\"\n    apply (rule chainI)\n    apply (rule join_mono[OF compat compat chainE[OF `chain Y`] below_refl])\n    done\n\n  show ?thesis\n    apply (rule is_joinI)\n    apply (rule lub_mono[OF `chain Y` c join_above1[OF compat]])\n    apply (rule below_lub[OF c join_above2[OF compat]])\n    apply (rule lub_below[OF c])\n    apply (rule join_below[OF compat])\n    apply (metis lub_below_iff[OF `chain Y`])\n    apply assumption\n    done\nqed\n\nlemma join_cont2:\n  assumes \"chain Y\"\n  assumes compat: \"\\<And> i. compatible x (Y i)\"\n  shows \"x \\<squnion> (\\<Squnion>i. Y i) = (\\<Squnion> i. x \\<squnion> Y i)\"\nproof-\n  have c: \"chain (\\<lambda>i. x \\<squnion> Y i)\"\n    apply (rule chainI)\n    apply (rule join_mono[OF compat compat below_refl chainE[OF `chain Y`]])\n    done\n\n  show ?thesis\n    apply (rule is_joinI)\n    apply (rule below_lub[OF c join_above1[OF compat]])\n    apply (rule lub_mono[OF `chain Y` c join_above2[OF compat]])\n    apply (rule lub_below[OF c])\n    apply (rule join_below[OF compat])\n    apply assumption\n    apply (metis lub_below_iff[OF `chain Y`])\n    done\nqed\n\nlemma join_cont12:\n  assumes \"chain Y\" and \"chain Z\"\n  assumes compat: \"\\<And> i j. compatible (Y i) (Z j)\"\n  shows \"(\\<Squnion>i. Y i) \\<squnion> (\\<Squnion>i. Z i) = (\\<Squnion> i. Y i  \\<squnion> Z i)\"\nproof-\n  have \"(\\<Squnion>i. Y i) \\<squnion> (\\<Squnion>i. Z i) = (\\<Squnion>i. Y i \\<squnion> (\\<Squnion>j. Z j))\"\n    by (rule join_cont1[OF `chain Y` admD[OF compatible_adm2 `chain Z` compat]])\n  also have \"... = (\\<Squnion>i j. Y i \\<squnion> Z j)\"\n    by (subst join_cont2[OF `chain Z` compat], rule)\n  also have \"... = (\\<Squnion>i. Y i \\<squnion> Z i)\"\n    apply (rule diag_lub)\n    apply (rule chainI, rule join_mono[OF compat compat chainE[OF `chain Y`] below_refl])\n    apply (rule chainI, rule join_mono[OF compat compat below_refl chainE[OF `chain Z`]])\n    done\n  finally show ?thesis.\nqed\n\ncontext pcpo\nbegin\n  lemma bot_compatible[simp]:\n    \"compatible x \\<bottom>\" \"compatible \\<bottom> x\"\n    unfolding compatible_def by (metis insert_commute is_lub_bin minimal)+\nend\n\nsubsubsection {* Towards meets: Lower bounds *}\n\ncontext po\nbegin\ndefinition is_lb :: \"'a set => 'a => bool\" (infix \">|\" 55) where\n  \"S >| x <-> (\\<forall>y\\<in>S. x \\<sqsubseteq> y)\"\n\nlemma is_lbI: \"(!!x. x \\<in> S ==> l \\<sqsubseteq> x) ==> S >| l\"\n  by (simp add: is_lb_def)\n\nlemma is_lbD: \"[|S >| l; x \\<in> S|] ==> l \\<sqsubseteq> x\"\n  by (simp add: is_lb_def)\n\nlemma is_lb_empty [simp]: \"{} >| l\"\n  unfolding is_lb_def by fast\n\nlemma is_lb_insert [simp]: \"(insert x A) >| y = (y \\<sqsubseteq> x \\<and> A >| y)\"\n  unfolding is_lb_def by fast\n\nlemma is_lb_downward: \"[|S >| l; y \\<sqsubseteq> l|] ==> S >| y\"\n  unfolding is_lb_def by (fast intro: below_trans)\n\nsubsubsection {* Greatest lower bounds *}\n\ndefinition is_glb :: \"'a set => 'a => bool\" (infix \">>|\" 55) where\n  \"S >>| x <-> S >| x \\<and> (\\<forall>u. S >| u --> u \\<sqsubseteq> x)\"\n\ndefinition glb :: \"'a set => 'a\" (\"\\<Sqinter>_\" [60]60) where\n  \"glb S = (THE x. S >>| x)\" \n\ntext {* access to some definition as inference rule *}\n\nlemma is_glbD1: \"S >>| x ==> S >| x\"\n  unfolding is_glb_def by fast\n\nlemma is_glbD2: \"[|S >>| x; S >| u|] ==> u \\<sqsubseteq> x\"\n  unfolding is_glb_def by fast\n\nlemma (in po) is_glbI: \"[|S >| x; !!u. S >| u ==> u \\<sqsubseteq> x|] ==> S >>| x\"\n  unfolding is_glb_def by fast\n\nlemma is_glb_above_iff: \"S >>| x ==> u \\<sqsubseteq> x <-> S >| u\"\n  unfolding is_glb_def is_lb_def by (metis below_trans)\n\ntext {* glbs are unique *}\n\nlemma is_glb_unique: \"[|S >>| x; S >>| y|] ==> x = y\"\n  unfolding is_glb_def is_lb_def by (blast intro: below_antisym)\n\ntext {* technical lemmas about @{term glb} and @{term is_glb} *}\n\nlemma is_glb_glb: \"M >>| x ==> M >>| glb M\"\n  unfolding glb_def by (rule theI [OF _ is_glb_unique])\n\nlemma glb_eqI: \"M >>| l ==> glb M = l\"\n  by (rule is_glb_unique [OF is_glb_glb])\n\nlemma is_glb_singleton: \"{x} >>| x\"\n  by (simp add: is_glb_def)\n\nlemma glb_singleton [simp]: \"glb {x} = x\"\n  by (rule is_glb_singleton [THEN glb_eqI])\n\nlemma is_glb_bin: \"x \\<sqsubseteq> y ==> {x, y} >>| x\"\n  by (simp add: is_glb_def)\n\nlemma glb_bin: \"x \\<sqsubseteq> y ==> glb {x, y} = x\"\n  by (rule is_glb_bin [THEN glb_eqI])\n\nlemma is_glb_maximal: \"[|S >| x; x \\<in> S|] ==> S >>| x\"\n  by (erule is_glbI, erule (1) is_lbD)\n\nlemma glb_maximal: \"[|S >| x; x \\<in> S|] ==> glb S = x\"\n  by (rule is_glb_maximal [THEN glb_eqI])\nend\n\nlemma (in cpo) Meet_insert: \"S >>| l \\<Longrightarrow> {x, l} >>| l2 \\<Longrightarrow> insert x S >>| l2\"\n  apply (rule is_glbI)\n  apply (metis is_glb_above_iff is_glb_def is_lb_insert)\n  by (metis is_glb_above_iff is_glb_def is_glb_singleton is_lb_insert)\n\nsubsubsection {* Type classes for various kinds of meets *}\n\ntext {* Binary, hence finite meets. *}\n\nclass Finite_Meet_cpo = cpo +\n  assumes binary_meet_exists: \"\\<exists> l. l \\<sqsubseteq> x \\<and> l \\<sqsubseteq> y \\<and> (\\<forall> z. z \\<sqsubseteq> x \\<longrightarrow> z \\<sqsubseteq> y \\<longrightarrow> z \\<sqsubseteq> l)\"\nbegin\n\n  lemma binary_meet_exists': \"\\<exists>l. {x, y} >>| l\"\n    using binary_meet_exists[of x y]\n    unfolding is_glb_def is_lb_def\n    by auto\n\n  lemma finite_meet_exists:\n    assumes \"S \\<noteq> {}\"\n    and \"finite S\"\n    shows \"\\<exists>x. S >>| x\"\n  using `S \\<noteq> {}`\n  apply (induct rule: finite_induct[OF `finite S`])\n  apply (erule notE, rule refl)[1]\n  apply (case_tac \"F = {}\")\n  apply (metis is_glb_singleton)\n  apply (metis Meet_insert binary_meet_exists')\n  done\nend\n\ntext {* Meets for finite nonempty sets with a lower bound. *}\n\nclass Bounded_Nonempty_Meet_cpo = cpo +\n  assumes bounded_nonempty_meet_exists: \"S \\<noteq> {} \\<Longrightarrow> (\\<exists>z. S >| z) \\<Longrightarrow> \\<exists>x. S >>| x\"\nbegin\n  lemma nonempty_ub_implies_lub_exists:\n  assumes \"S <| u\"\n  assumes \"S \\<noteq> {}\"\n  shows \"\\<exists> z. S <<| z\"\n  proof-\n    have \"{u. S <| u} \\<noteq> {}\" using assms(1) by auto\n    hence \"\\<exists>x. {u. S <| u} >>| x\"\n      apply (rule bounded_nonempty_meet_exists)\n      by (metis CollectE assms(2) equals0I is_lbI is_ub_def)\n    then obtain lu where lb: \"{u. S <| u} >>| lu\" by auto\n    hence \"S <| lu\"\n      by (metis is_glb_above_iff is_lb_def is_ub_def mem_Collect_eq)\n    hence \"S <<| lu\"\n      by (metis (full_types) is_lubI is_glbD1 is_lb_def lb mem_Collect_eq)\n    thus ?thesis ..\n  qed\n\n  lemma ub_implies_compatible:\n    \"x \\<sqsubseteq> z \\<Longrightarrow> y \\<sqsubseteq> z \\<Longrightarrow> compatible x y\"\n    unfolding compatible_def\n    by (rule nonempty_ub_implies_lub_exists, auto)\nend\n\ntext {* Meets for finite nonempty sets. *}\n\nclass Nonempty_Meet_cpo = cpo +\n  assumes nonempty_meet_exists: \"S \\<noteq> {} \\<Longrightarrow> \\<exists>x. S >>| x\"\nbegin\n  lemma ub_implies_lub_exists:\n  assumes \"S <| u\"\n  shows \"\\<exists> z. S <<| z\"\n  proof-\n    have \"{u. S <| u} \\<noteq> {}\" using assms by auto\n    from nonempty_meet_exists[OF this]\n    obtain lu where lb: \"{u. S <| u} >>| lu\" by auto\n    hence \"S <| lu\"\n      by (metis is_glb_above_iff is_lb_def is_ub_def mem_Collect_eq)\n    hence \"S <<| lu\"\n      by (metis (full_types) is_lubI is_glbD1 is_lb_def lb mem_Collect_eq)\n    thus ?thesis ..\n  qed\nend\n\ncontext Nonempty_Meet_cpo\nbegin\n  subclass Bounded_Nonempty_Meet_cpo\n  apply default by (metis nonempty_meet_exists)\nend\n\nlemma (in Bounded_Nonempty_Meet_cpo) compatible_down_closed:\n    assumes \"compatible x y\"\n    and \"z \\<sqsubseteq> x\"\n    shows \"compatible z y\"\nproof-\n    from assms(1) obtain ub where \"{x, y} <<| ub\" by (metis compatible_def)\n    hence \"{x,y} <| ub\" by (metis is_lubD1)\n    hence \"{z,y} <| ub\" using assms(2) by (metis is_ub_insert rev_below_trans)\n    thus ?thesis unfolding compatible_def by (metis insert_not_empty nonempty_ub_implies_lub_exists)\nqed\n\nlemma (in Bounded_Nonempty_Meet_cpo) compatible_down_closed2:\n    assumes \"compatible y x\"\n    and \"z \\<sqsubseteq> x\"\n    shows \"compatible y z\"\nproof-\n    from assms(1) obtain ub where \"{y, x} <<| ub\" by (metis compatible_def)\n    hence \"{y,x} <| ub\" by (metis is_lubD1)\n    hence \"{y,z} <| ub\" using assms(2) by (metis is_ub_insert rev_below_trans)\n    thus ?thesis unfolding compatible_def by (metis insert_not_empty nonempty_ub_implies_lub_exists)\nqed\n\nlemma join_mono':\n  assumes  \"compatible (c::'a::Bounded_Nonempty_Meet_cpo) d\"\n  and \"a \\<sqsubseteq> c\"\n  and \"b \\<sqsubseteq> d\"\n  shows \"a \\<squnion> b \\<sqsubseteq> c \\<squnion> d\"\n  apply (rule join_mono[OF _ assms(1) assms(2) assms(3)])\n  by (metis assms(1) assms(2) assms(3) compatible_down_closed2 compatible_sym)\n\nsubsubsection {* Bifinite domains with finite nonempty meets have arbitrary nonempty meets. *}\n\nclass Finite_Meet_bifinite_cpo = Finite_Meet_cpo + bifinite\n\nlemma is_ub_range:\n     \"S >| u \\<Longrightarrow> Rep_cfun f ` S >| f \\<cdot> u\"\n  apply (rule is_lbI)\n  apply (erule imageE)\n  by (metis monofun_cfun_arg is_lbD)\n\nlemma (in approx_chain) lub_approx_arg: \"(\\<Squnion>i. approx i \\<cdot> u ) = u\"\n  by (metis chain_approx lub_ID_reach lub_approx)\n\ninstance Finite_Meet_bifinite_cpo \\<subseteq> Nonempty_Meet_cpo\nproof (default)\n  from bifinite obtain approx :: \"nat \\<Rightarrow> 'a \\<rightarrow> 'a\" where \"approx_chain approx\" by auto\n  fix S\n  assume \"(S :: 'a set) \\<noteq> {}\"\n  have \"\\<And>i. \\<exists> l . Rep_cfun (approx i) ` S >>|l\"\n    apply (rule finite_meet_exists)\n    using `S \\<noteq> {}` apply auto[1]\n    using  finite_deflation.finite_range[OF approx_chain.finite_deflation_approx[OF `approx_chain approx`]]\n    by (metis (full_types) image_mono rev_finite_subset top_greatest)\n  then obtain Y where Y_is_glb: \"\\<And>i. Rep_cfun (approx i) ` S >>| Y i\" by metis\n  \n  have \"chain Y\"\n    apply (rule chainI)\n    apply (subst is_glb_above_iff[OF Y_is_glb])\n    apply (rule is_lbI)\n    apply (erule imageE)\n    apply (erule ssubst)\n    apply (rule rev_below_trans[OF monofun_cfun_fun[OF chainE[OF approx_chain.chain_approx[OF `approx_chain approx`]]]])\n    apply (rule is_lbD[OF is_glbD1[OF Y_is_glb]])\n    apply (erule imageI)\n    done\n  \n  have \"S >| Lub Y\"\n  proof(rule is_lbI, rule lub_below[OF `chain Y`])\n    fix x i\n    assume \"x \\<in> S\"\n    hence \"Y i \\<sqsubseteq> approx i \\<cdot> x\"\n      by (rule imageI[THEN is_lbD[OF is_glbD1[OF Y_is_glb]]])\n    also have \"approx i \\<cdot> x \\<sqsubseteq> x\"\n      by (rule  approx_chain.approx_below[OF `approx_chain approx`])\n    finally\n    show \"Y i \\<sqsubseteq> x\".\n  qed\n\n  have \"S >>| Lub Y\"\n  proof (rule is_glbI[OF `S >| Lub Y`])\n    fix u\n    assume \"S >| u\"\n    hence \"\\<And> i. Rep_cfun (approx i) ` S >| approx i \\<cdot> u\"\n      by (rule is_ub_range)\n    hence \"\\<And> i.  approx i \\<cdot> u \\<sqsubseteq> Y i\"\n      by (rule is_glbD2[OF Y_is_glb])\n    hence \"(\\<Squnion>i. approx i \\<cdot> u ) \\<sqsubseteq> Lub Y\" \n      by (rule lub_mono[OF\n            ch2ch_Rep_cfunL[OF approx_chain.chain_approx[OF `approx_chain approx`]]\n            `chain Y`\n            ])\n    thus \"u \\<sqsubseteq> Lub Y\" \n      by (metis approx_chain.lub_approx_arg[OF `approx_chain approx`])\n  qed\n  thus \"\\<exists>x. S >>| x\"..\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/HOLCF-Join.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032941962904955, "lm_q2_score": 0.7981867729389246, "lm_q1q2_score": 0.7209974795515701}}
{"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_MSortTDIsSort\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 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 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\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  \"((msorttd 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_MSortTDIsSort.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009503523291, "lm_q2_score": 0.7879311956428947, "lm_q1q2_score": 0.7208789997059313}}
{"text": "(*\n  File: Divides.thy\n  Author: Bohua Zhan\n\n  Basics of divisibility and prime numbers.\n*)\n\ntheory Divides\n  imports Nat\nbegin\n\nsection \\<open>Divisibility\\<close>\n  \ndefinition divides :: \"i \\<Rightarrow> i \\<Rightarrow> i \\<Rightarrow> o\" where [rewrite]:\n  \"divides(R,a,b) \\<longleftrightarrow> (a \\<in>. R \\<and> b \\<in>. R \\<and> (\\<exists>k\\<in>.R. b = a *\\<^sub>R k))\"\n\nlemma dividesI [resolve]:\n  \"is_group_raw(R) \\<Longrightarrow> a \\<in>. R \\<Longrightarrow> k \\<in>. R \\<Longrightarrow> divides(R, a, a *\\<^sub>R k)\" by auto2\nlemma dividesD1 [forward]: \"divides(R,a,b) \\<Longrightarrow> a \\<in>. R \\<and> b \\<in>. R\" by auto2\nlemma dividesD2 [backward]: \"divides(R,a,b) \\<Longrightarrow> \\<exists>k\\<in>.R. b = a *\\<^sub>R k\" by auto2\nsetup {* del_prfstep_thm @{thm divides_def} *}\n\nlemma divides_id [resolve]: \"is_semiring(R) \\<Longrightarrow> a \\<in>. R \\<Longrightarrow> divides(R,a,a)\"\n@proof @have \"a = a *\\<^sub>R \\<one>\\<^sub>R\" @qed\n\nlemma divides_trans [forward]:\n  \"is_semiring(R) \\<Longrightarrow> divides(R,a,b) \\<Longrightarrow> divides(R,b,c) \\<Longrightarrow> divides(R,a,c)\"\n@proof\n  @obtain \"k\\<in>.R\" where \"b = a *\\<^sub>R k\"\n  @obtain \"l\\<in>.R\" where \"c = b *\\<^sub>R l\"\n  @have \"c = (a *\\<^sub>R k) *\\<^sub>R l\" @have \"c = a *\\<^sub>R (k *\\<^sub>R l)\"\n@qed\n\nlemma divides_one [resolve]:\n  \"is_semiring(R) \\<Longrightarrow> a \\<in>. R \\<Longrightarrow> divides(R,\\<one>\\<^sub>R,a)\"\n@proof @have \"a = \\<one>\\<^sub>R *\\<^sub>R a\" @qed\n    \nlemma divides_zero [resolve]:\n  \"is_semiring(R) \\<Longrightarrow> a \\<in>. R \\<Longrightarrow> divides(R,a,\\<zero>\\<^sub>R)\"\n@proof @have \"\\<zero>\\<^sub>R = a *\\<^sub>R \\<zero>\\<^sub>R\" @qed\n\nsection \\<open>Divides on natural numbers\\<close>\n\nlemma nat_divides_cancel [forward]:\n  \"a \\<in>. \\<nat> \\<Longrightarrow> b \\<in>. \\<nat> \\<Longrightarrow> c \\<in>. \\<nat> \\<Longrightarrow> c \\<noteq> 0 \\<Longrightarrow>\n   divides(\\<nat>, a *\\<^sub>\\<nat> c, b *\\<^sub>\\<nat> c) \\<Longrightarrow> divides(\\<nat>, a, b)\"\n@proof\n  @obtain \"k\\<in>.\\<nat>\" where \"b *\\<^sub>\\<nat> c = a *\\<^sub>\\<nat> c *\\<^sub>\\<nat> k\"\n  @have \"a *\\<^sub>\\<nat> k *\\<^sub>\\<nat> c = b *\\<^sub>\\<nat> c\"\n@qed\n\nlemma nat_le_prod [backward]:\n  \"a \\<in>. \\<nat> \\<Longrightarrow> k \\<in>. \\<nat> \\<Longrightarrow> k \\<noteq> 0 \\<Longrightarrow> a \\<le>\\<^sub>\\<nat> a *\\<^sub>\\<nat> k\"\n@proof @have \"k \\<ge>\\<^sub>\\<nat> 1\" @have \"a = a *\\<^sub>\\<nat> 1\" @qed\n      \nlemma nat_divides_le [forward]:\n  \"b \\<noteq> 0 \\<Longrightarrow> divides(\\<nat>,a,b) \\<Longrightarrow> 1 \\<le>\\<^sub>\\<nat> a \\<and> a \\<le>\\<^sub>\\<nat> b\"\n@proof @obtain \"k\\<in>.\\<nat>\" where \"b = a *\\<^sub>\\<nat> k\" @qed\n\ndefinition even :: \"i \\<Rightarrow> o\" where [rewrite]:\n  \"even(x) \\<longleftrightarrow> divides(\\<nat>,2,x)\"\n  \ndefinition odd :: \"i \\<Rightarrow> o\" where [rewrite]:\n  \"odd(x) \\<longleftrightarrow> (\\<not>divides(\\<nat>,2,x))\"\n  \nsection \\<open>Quotient and Remainder\\<close>\n\nlemma quotient_remainder_theorem:\n  \"m >\\<^sub>\\<nat> 0 \\<Longrightarrow> n \\<in> nat \\<Longrightarrow> \\<exists>q\\<in>nat. \\<exists>r\\<in>nat. n = m *\\<^sub>\\<nat> q +\\<^sub>\\<nat> r \\<and> 0 \\<le>\\<^sub>\\<nat> r \\<and> r <\\<^sub>\\<nat> m\"\n@proof\n  @strong_induct \"n \\<in> nat\"\n  @case \"n <\\<^sub>\\<nat> m\"\n  @let \"n' = n -\\<^sub>\\<nat> m\"\n  @have \"n' <\\<^sub>\\<nat> n\" @with @have \"n' +\\<^sub>\\<nat> m <\\<^sub>\\<nat> n +\\<^sub>\\<nat> m\" @end\n  @obtain \"q\\<in>nat\" \"r\\<in>nat\" where \"n' = m *\\<^sub>\\<nat> q +\\<^sub>\\<nat> r\" \"0 \\<le>\\<^sub>\\<nat> r\" \"r <\\<^sub>\\<nat> m\"\n  @have \"n = (m *\\<^sub>\\<nat> q +\\<^sub>\\<nat> r) +\\<^sub>\\<nat> m\"\n  @have \"n = (m *\\<^sub>\\<nat> (q +\\<^sub>\\<nat> \\<one>\\<^sub>\\<nat>)) +\\<^sub>\\<nat> r\"\n@qed\n\nsection \\<open>Prime\\<close>\n\ndefinition prime :: \"i \\<Rightarrow> o\" where [rewrite]:\n  \"prime(p) \\<longleftrightarrow> (p >\\<^sub>\\<nat> 1 \\<and> (\\<forall>m. divides(\\<nat>,m,p) \\<longrightarrow> m = 1 \\<or> m = p))\"\n  \nlemma primeD1 [forward]: \"prime(p) \\<Longrightarrow> p >\\<^sub>\\<nat> 1\" by auto2\nlemma primeD2 [forward]: \"prime(p) \\<Longrightarrow> divides(\\<nat>,m,p) \\<Longrightarrow> m = 1 \\<or> m = p\" by auto2\nsetup {* del_prfstep_thm_eqforward @{thm prime_def} *}\n  \nlemma prime_odd_nat: \"prime(p) \\<Longrightarrow> p >\\<^sub>\\<nat> 2 \\<Longrightarrow> odd(p)\" by auto2\n\nlemma exists_prime [resolve]: \"\\<exists>p. prime(p)\"\n@proof\n  @have \"prime(2)\" @with @have \"2 \\<noteq> 0\" @end\n@qed\n\nlemma prime_factor_nat: \"n \\<in> nat \\<Longrightarrow> n \\<noteq> 1 \\<Longrightarrow> \\<exists>p. divides(\\<nat>,p,n) \\<and> prime(p)\"\n@proof\n  @strong_induct \"n \\<in> nat\"\n  @case \"prime(n)\" @with @have \"divides(\\<nat>,n,n)\" @end\n  @case \"n = \\<zero>\\<^sub>\\<nat>\" @with\n    @obtain q where \"prime(q)\"\n    @have \"divides(\\<nat>,q,0)\"\n  @end\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/Divides.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.894789468908171, "lm_q2_score": 0.8056321889812553, "lm_q1q2_score": 0.7208711985138647}}
{"text": "theory Matching\nimports\n  Main\n  Parity\n  \"../Graph_Theory/Graph_Theory\"\nbegin\n\n\ntype_synonym label = nat\n(*\nsection {* Definitions *}\n*)\ndefinition disjoint_arcs :: \"('a, 'b) pre_digraph => 'b \\<Rightarrow> 'b \\<Rightarrow> bool\" where\n  \"disjoint_arcs G e1 e2 = (\n     tail G e1 \\<noteq> tail G e2 \\<and> tail G e1 \\<noteq> head G e2 \\<and> \n     head G e1 \\<noteq> tail G e2 \\<and> head G e1 \\<noteq> head G e2)\"\n\ndefinition matching :: \"('a, 'b) pre_digraph \\<Rightarrow> 'b set \\<Rightarrow> bool\" where\n  \"matching G M = (M \\<subseteq> arcs G \\<and> (\\<forall>e1 \\<in> M. \\<forall>e2 \\<in> M. e1 \\<noteq> e2 \\<longrightarrow> disjoint_arcs G e1 e2))\"\n\ndefinition OSC :: \"('a, 'b) pre_digraph \\<Rightarrow> ('a \\<Rightarrow> label) \\<Rightarrow> bool\" where\n  \"OSC G L = (\n     \\<forall>e \\<in> arcs G.\n       L (tail G e) = 1 \\<or> L (head G e) = 1 \\<or> \n       L (tail G e) = L (head G e) \\<and> L (tail G e) \\<ge> 2)\"\n\ndefinition weight:: \"label set \\<Rightarrow> (label \\<Rightarrow> nat) \\<Rightarrow> nat\" where\n  \"weight LV f \\<equiv> f 1 + (\\<Sum>i\\<in>LV. (f i) div 2)\"\n\ndefinition N :: \"'a set \\<Rightarrow> ('a \\<Rightarrow> label) \\<Rightarrow> label \\<Rightarrow> nat\" where\n  \"N V L i \\<equiv> card {v \\<in> V. L v = i}\"\n\nlocale matching_locale = digraph +\n  fixes maxM :: \"'b set\"\n  fixes L :: \"'a \\<Rightarrow> label\"\n  assumes matching: \"matching G maxM\" \n  assumes OSC: \"OSC G L\"\n  assumes weight: \"card maxM = weight {i \\<in> L ` verts G. i > 1} (N (verts G) L)\"\n\nsublocale matching_locale \\<subseteq> digraph ..\n\ncontext matching_locale begin\n\ndefinition degree :: \"'a \\<Rightarrow> nat\" where\n  \"degree v \\<equiv> card {e \\<in> arcs G. tail G e = v \\<or> head G e = v}\"\n\ndefinition edge_as_set :: \"'b \\<Rightarrow> 'a set\" where\n  \"edge_as_set e \\<equiv> {tail G e, head G e}\"\n\ndefinition matched :: \"'b set \\<Rightarrow> 'a \\<Rightarrow> bool\" where\n  \"matched M v \\<equiv> v \\<in> \\<Union> (edge_as_set ` M)\"\n\ndefinition free :: \"'b set \\<Rightarrow> 'a \\<Rightarrow> bool\" where\n  \"free M v \\<equiv> \\<not> matched M v\"\n\n\ndefinition matching_i :: \"nat \\<Rightarrow> 'b set \\<Rightarrow> 'b set\" where\n  \"matching_i i M \\<equiv> {e \\<in> M. i=1 \\<and> (L (tail G e) = i \\<or> L (head G e) = i) \n  \\<or> i>1 \\<and> L (tail G e) = i \\<and> L (head G e) = i}\"\n\ndefinition V_i:: \"nat \\<Rightarrow> 'b set \\<Rightarrow> 'a set\" where\n  \"V_i i M \\<equiv> \\<Union> (edge_as_set ` matching_i i M)\"\n\ndefinition endpoint_inV :: \"'a set \\<Rightarrow> 'b \\<Rightarrow> 'a\" where \n  \"endpoint_inV V e \\<equiv>  if tail G e \\<in> V then tail G e else head G e\" \n\ndefinition relevant_endpoint :: \"'b \\<Rightarrow> 'a\" where \n  \"relevant_endpoint e \\<equiv> if L (tail G e) = 1 then tail G e else head G e\"\n(*\nsection {* Lemmas *}\n*)\n\nlemma definition_of_range:\n  \"endpoint_inV V1 ` matching_i 1 M = \n  { v. \\<exists> e \\<in> matching_i 1 M. endpoint_inV V1 e = v }\" by auto\n\nlemma matching_i_arcs_as_sets:\n  \"edge_as_set ` matching_i i M = \n  { e1. \\<exists> e \\<in> matching_i i M. edge_as_set e = e1}\" by auto\n\nlemma matching_disjointness:\n  assumes \"matching G 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_arcs_def matching_def)\n\nlemma expand_set_containment:\n  assumes \"matching G M\"\n  assumes \"e \\<in> M\"\n  shows \"e \\<in> arcs G\"\n  using assms\n  by (auto simp add:matching_def)\n\ntheorem injectivity:\n  assumes is_m: \"matching G M\"\n  assumes e1_in_M1: \"e1 \\<in> matching_i 1 M\"\n      and e2_in_M1: \"e2 \\<in> matching_i 1 M\"\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 G M\"\n  shows \"card (matching_i 1 M) \\<le> N (verts G) L 1\"\nproof -\n  let ?f = \"endpoint_inV {v \\<in> verts G. L v = 1}\"\n  let ?A = \"matching_i 1 M\"\n  let ?B = \"{v \\<in> verts G. 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 M\"\n      hence \"e \\<in> arcs G\"\n        using assms by (auto simp add: matching_def matching_i_def)\n      with `e \\<in> matching_i 1 M`\n      have \"endpoint_inV {v \\<in> verts G. L v = 1} e \\<in> {v \\<in> verts G. L v = 1}\"\n        using assms\n        by (auto simp add: endpoint_inV_def matching_i_def intro: tail_in_verts head_in_verts)\n    }\n    then show ?thesis using assms definition_of_range by blast\n  qed\n  moreover have \"finite ?B\" by simp\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 G M\"\n  shows \"inj_on edge_as_set (matching_i i M)\"\n  using assms\n  unfolding inj_on_def edge_as_set_def matching_def\n    disjoint_arcs_def matching_i_def \n  by blast\n\nlemma card_edge_as_set_Mi_twice_card_partitions:\n  assumes \"matching G M \\<and> i > 1\"\n  shows \"2 * card (edge_as_set`matching_i i M) \n  = card (V_i i M)\" (is \"2 * card ?C = card ?Vi\")\nproof -\n  from assms have 1: \"finite (\\<Union> ?C)\" \n    by (auto simp add: matching_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 M\"\n      with assms have \"x \\<in> arcs G\" \n        unfolding matching_i_def matching_def by blast\n      then have \"tail G x \\<noteq> head G x\" using assms 3 by (metis no_loops)\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 M\"\n        \"x2 = edge_as_set e2\" \"e2 \\<in> matching_i i M\"\n      from assms have \"matching G 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 \"matching G M \\<and> i > 1\"\n  shows \"2 * card (matching_i i M) = card (V_i i M)\"\nproof -\n  show ?thesis  \n    by (metis assms card_edge_as_set_Mi_twice_card_partitions\n      edge_as_set_inj_on_Mi card_image)\nqed\n\nlemma card_Mi_le_floor_div_2_Vi:\n  assumes \"matching G M \\<and> i > 1\"\n  shows \"card (matching_i i M) \\<le> (card (V_i i M)) 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 G M\"\n  shows \"card (V_i i M) \\<le> N (verts G) L i\"\n  unfolding N_def\nproof (rule card_mono)\n  show \"finite {v \\<in> verts G. L v = i}\" using assms \n    by (simp add: matching_def)\nnext\n  let ?A = \"edge_as_set ` matching_i i M\"\n  let ?C = \"{v \\<in> verts G. L v = i}\" \n  show \"V_i i M \\<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 M. edge_as_set x = X\"\n      by (simp add: matching_i_arcs_as_sets)\n    with assms show \"X \\<subseteq> ?C\" \n      unfolding matching_def\n        matching_i_def edge_as_set_def by (blast intro: tail_in_verts head_in_verts)\n  qed\nqed\n\nlemma card_Mi_le_floor_div_2_NVLi:\n  assumes \"matching G M \\<and> i > 1\"\n  shows \"card (matching_i i M) \\<le> (N (verts G) L i) div 2\"\nproof -  \n  from assms have \"card (V_i i M) \\<le> (N (verts G) L i)\"\n    by (simp add: card_Vi_le_NVLi) \n  then have \"card (V_i i M) div 2 \\<le> (N (verts G) L i) div 2\"\n    by simp\n  moreover from assms have \n    \"card (matching_i i M) \\<le> card (V_i i M) div 2\"\n    by (intro card_Mi_le_floor_div_2_Vi)\n  ultimately show ?thesis by auto\nqed\n\nlemma card_M_le_sum_card_Mi: \nassumes \"matching G M\" and \"OSC G L\"\nshows \"card M \\<le> (\\<Sum> i \\<in> L`verts G. card (matching_i i M))\"\n  (is \"card _ \\<le> ?CardMi\")\nproof -\n  let ?UnMi = \"\\<Union>x \\<in> L`verts G. matching_i x M\"\n  from assms have 1: \"finite ?UnMi\"\n    by (auto simp add: matching_def matching_i_def finite_subset)\n  {\n    fix e assume e_inM: \"e \\<in> M\"\n    let ?v = \"relevant_endpoint e\"\n    have 1: \"e \\<in> matching_i (L ?v) M\" using assms e_inM\n      proof cases\n        assume \"L (tail G 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 (tail G e) \\<noteq> 1\" \n        have \"L (tail G e) = 1 \\<or> L (head G e) = 1 \n          \\<or>  (L (tail G e) = L (head G e) \\<and> L (tail G e) >1)\"\n          using assms e_inM unfolding OSC_def \n          by (auto 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> verts G\" using assms e_inM \n        by (auto simp add: matching_def relevant_endpoint_def intro: tail_in_verts head_in_verts)\n      then have \"\\<exists> v \\<in> verts G. e \\<in> matching_i (L v) M\" 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`verts G)\" by simp\n    next \n      show \"\\<forall>i\\<in>L`verts G. finite (matching_i i M)\" using assms\n        using finite_arcs\n        unfolding matching_def matching_i_def\n        by (blast intro: finite_subset finite_arcs)\n    next \n      show \"\\<forall>i \\<in> L`verts G. \\<forall>j \\<in> L`verts G. i \\<noteq> j \\<longrightarrow> \n        matching_i i M \\<inter> matching_i j M = {}\" 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 G M\" and \"OSC G L\"\n  shows \"card M \\<le> weight {i \\<in> L ` verts G. i > 1} (N (verts G) L)\" (is \"_ \\<le> ?W\")\nproof -\n  let ?M01 = \"\\<Sum>i| i \\<in> L ` verts G \\<and> (i=1 \\<or> i=0). card (matching_i i M)\"\n  let ?Mgr1 = \"\\<Sum>i| i \\<in> L ` verts G \\<and> 1 < i. card (matching_i i M)\"\n  let ?Mi = \"\\<Sum> i\\<in>L ` verts G. card (matching_i i M)\"\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 ` verts G. i = 1 \\<or> i = 0}\"\n    let ?B = \"{i \\<in> L ` verts G. 1 < i}\"\n    let ?g = \"\\<lambda> i. card (matching_i i M)\"\n    let ?set01 = \"{ i. i : L ` verts G & (i = 1 | i = 0)}\"\n    have a: \"L ` verts G = ?A \\<union> ?B\" using assms by auto\n    have b: \"setsum ?g (?A \\<union> ?B) = setsum ?g ?A + setsum ?g ?B\"\n      by (auto intro: setsum.union_disjoint)\n    have 1: \"?Mi = ?M01+ ?Mgr1\" using assms a b by simp\n    moreover\n    have 0: \"card (matching_i 0 M) = 0\" using assms\n      by (simp add: matching_i_def)\n      have 2: \"?M01 \\<le> N (verts G) L 1\"\n      proof cases\n        assume a: \"1 \\<in> L ` verts G\"\n        have \"?M01 = card (matching_i 1 M)\" \n        proof cases\n          assume b: \"0 \\<in> L ` verts G\"\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 ` verts G\"\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 ` verts G\"\n        show ?thesis\n        proof cases\n          assume b: \"0 \\<in> L ` verts G\"\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 ` verts G\"\n          with a have \"?set01 = {}\" by (auto simp del:One_nat_def)\n            then have \"?M01 = (\\<Sum>i\\<in>{}. card (matching_i i M))\" by auto\n            thus ?thesis by simp\n          qed\n        qed\n      moreover\n      have 3: \"?Mgr1 \\<le> (\\<Sum>i|i\\<in>L ` verts G \\<and> 1 < i. N (verts G) L i div 2)\" \n        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 *}\n*)\ntheorem maximum_cardinality_matching:\n  \"matching G M' \\<longrightarrow> card M' \\<le> card maxM\"\n  using card_M_le_weight_NVLi OSC matching weight\n  by simp\n\nend\n\nend\n", "meta": {"author": "crizkallah", "repo": "checker-verification", "sha": "cd5101e57ef70dcdd1680db2de2f08521605bd7c", "save_path": "github-repos/isabelle/crizkallah-checker-verification", "path": "github-repos/isabelle/crizkallah-checker-verification/checker-verification-cd5101e57ef70dcdd1680db2de2f08521605bd7c/Witness_Property/Matching.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894632969137, "lm_q2_score": 0.805632181981183, "lm_q1q2_score": 0.7208711877296642}}
{"text": "(*\nTitle: Butterfly Algorithm for Number Theoretic Transform\nAuthor: Thomas Ammer\n*)\n\ntheory Butterfly\n  imports NTT \"HOL-Library.Discrete\"\nbegin\n\ntext \\<open>\\pagebreak\\<close>\n\nsection \\<open>Butterfly Algorithms\\<close>\ntext \\<open>\\label{Butterfly}\\<close>\n\ntext \\<open>\\indent Several recursive algorithms for $FFT$ based on \nthe divide and conquer principle have been developed in order to speed up the transform.\nA method for reducing complexity is the butterfly scheme. \nIn this formalization, we consider the butterfly algorithm by Cooley \nand Tukey~\\parencite{Good1997} adapted to the setting of \\textit{NTT}.\n\\<close>\n\ntext \\<open>\\noindent We additionally assume that $n$ is power of two.\\<close>\n\nlocale butterfly = ntt +\n  fixes N\n  assumes n_two_pot: \"n = 2^N\"\nbegin\n\nsubsection \\<open>Recursive Definition\\<close>\n\ntext \\<open>Let's recall the definition of a transformed vector element:\n\\begin{equation*}\n\\mathsf{NTT}(\\vec{x})_i = \\sum _{j = 0} ^{n-1} x_j \\cdot \\omega ^{i\\cdot j} \n\\end{equation*}\n\nWe assume $n = 2^N$ and obtain:\n\n\\begin{align*}\n\\sum _{j = 0} ^{< 2^N} x_j \\cdot \\omega ^{i\\cdot j} \\\\ &= \n\\sum _{j = 0} ^{< 2^{N-1}} x_{2j} \\cdot \\omega ^{i\\cdot 2j} +\n \\sum _{j = 0} ^{< 2^{N-1}} x_{2j+1} \\cdot \\omega ^{i\\cdot (2j+1)} \\\\\n& = \\sum _{j = 0} ^{< 2^{N-1}} x_{2j} \\cdot (\\omega^2) ^{i\\cdot j} +\n \\omega^i \\cdot \\sum _{j = 0} ^{< 2^{N-1}} x_{2j+1} \\cdot (\\omega^2) ^{i\\cdot j}\\\\\n& = (\\sum _{j = 0} ^{< 2^{N-2}} x_{4j} \\cdot (\\omega^4) ^{i\\cdot j}  +\n \\omega^i \\cdot \\sum _{j = 0} ^{< 2^{N-2}} x_{4j+2} \\cdot (\\omega^4) ^{i\\cdot j}) \\\\\n& \\hspace{1cm}+ \\omega^i \\cdot (\\sum _{j = 0} ^{< 2^{N-2}} x_{4j+1} \\cdot (\\omega^4) ^{i\\cdot j}  +\n \\omega^i \\cdot \\sum _{j = 0} ^{< 2^{N-2}} x_{4j+3} \\cdot (\\omega^4) ^{i\\cdot j}) \\text{ etc.}\n\\end{align*}\n\nwhich gives us a recursive algorithm:\n\n\\begin{itemize}\n\\item Compose vectors consisting of elements at even and odd indices respectively\n\\item Compute a transformation of these vectors recursively where the dimensions are halved.\n\\item Add results after scaling the second subresult by $\\omega^i$\n\\end{itemize}\n\n\\<close>\n\ntext \\<open>Now we give a functional definition of the analogue to $FFT$ adapted to finite fields. \nA gentle introduction to $FFT$ can be found in~\\parencite{10.5555/1614191}. \nFor the fast implementation of Number Theoretic Transform in particular, have a look at~\\parencite{cryptoeprint:2016/504}.\\<close>\n\ntext \\<open>(The following lemma is needed to obtain an automated termination proof of $FNTT$.)\\<close>\nlemma FNTT_termination_aux [simp]: \"length (filter P [0..<l]) < Suc l\"\n  by (metis diff_zero le_imp_less_Suc length_filter_le length_upt)\n\ntext \\<open>Please note that we closely adhere to the textbook definition which just \ntalks about elements at even and odd indices. We model the informal definition by predefined functions, \nsince this seems to be more handy during proofs. \nAn algorithm splitting the elements smartly will be presented afterwards.\\<close>\n\nfun FNTT::\"('a mod_ring) list \\<Rightarrow> ('a mod_ring) list\" where\n\"FNTT [] = []\"|\n\"FNTT [a] = [a]\"|\n\"FNTT nums = (let nn = length nums;\n                  nums1 = [nums!i.  i \\<leftarrow> filter even [0..<nn]];\n                  nums2 = [nums!i.  i \\<leftarrow> filter odd [0..<nn]];\n                  fntt1 = FNTT nums1;\n                  fntt2 = FNTT nums2;\n                  sum1 = map2 (+) fntt1 (map2 ( \\<lambda> x k.  x*(\\<omega>^( (n div nn) * k))) fntt2 [0..<(nn div 2)]);\n                  sum2 = map2 (-) fntt1 (map2 ( \\<lambda> x k.  x*(\\<omega>^( (n div nn) * k))) fntt2 [0..<(nn div 2)])\n                   in sum1@sum2)\"\n\nlemmas [simp del] = FNTT_termination_aux\n\n\ntext \\<open>\nFinally, we want to prove correctness, i.e. $FNTT\\; xs = NTT\\;xs$. \nSince we consider a recursive algorithm, some kind of induction is appropriate:\nAssume the claim for $\\frac{2^d}{2} = 2^{d-1}$ and prove it for $2^d$, where $2^d$ is the vector length. \nThis implies that we have to talk about \\textit{NTT}s with respect to some powers of $\\omega$.\nIn particular, we decide to annotate \\textit{NTT} with a degree $degr$ \nindicating the referred vector length. There is a correspondence to the current level $l$ of recursion:\n\n\\begin{equation*}\ndegr = 2^{N-l}\n\\end{equation*}\n\n\\<close>\n\ntext \\<open>\\noindent A generalized version of \\textit{NTT} keeps track of all levels during recursion:\\<close>\n\ndefinition \"ntt_gen numbers degr i = (\\<Sum>j=0..<(length numbers). (numbers ! j) * \\<omega>^((n div degr)*i*j)) \"\n\ndefinition \"NTT_gen degr numbers = map (ntt_gen numbers (degr)) [0..< length numbers]\"\n\ntext \\<open>Whenever generalized \\textit{NTT} is applied to a list of full length,\n then its actually equal to the defined \\textit{NTT}.\\<close>\n\nlemma NTT_gen_NTT_full_length: \n  assumes \"length numbers =n\"\n  shows \"NTT_gen n numbers = NTT numbers\"\n  unfolding NTT_gen_def ntt_gen_def NTT_def ntt_def \n  using assms by simp\n\nsubsection \\<open>Arguments on Correctness\\<close>\ntext \\<open>First some general lemmas on list operations.\\<close>\n\nlemma length_even_filter: \"length [f i .  i <- (filter even [0..<l])] = l-l div 2\"\n  by(induction l) auto\n\nlemma length_odd_filter: \"length [f i .  i <- (filter odd [0..<l])] = l div 2\"\n  by(induction l) auto\n\nlemma map2_length: \"length (map2 f xs ys) =  min (length xs) (length ys)\"\n  by (induction xs arbitrary: ys) auto\n\nlemma map2_index: \"i < length xs \\<Longrightarrow> i < length ys \\<Longrightarrow> (map2 f xs ys) ! i = f (xs ! i) (ys ! i)\"\n  by (induction xs arbitrary: ys i) auto\n\nlemma filter_last_not: \"\\<not> P x \\<Longrightarrow> filter P (xs@[x]) = filter P xs\"\n  by simp\n\nlemma filter_even_map: \"filter even [0..<2*(x::nat)] = map ((*) (2::nat)) [0..<x]\"\n  by(induction x) simp+\n\nlemma filter_even_nth: \"2*j < l \\<Longrightarrow> 2*x = l \\<Longrightarrow> (filter even [0..<l] ! j) = (2*j)\"\n  using filter_even_map[of x] nth_map[of j \"filter even [0..<l]\" \"(*) 2\"] by auto\n\nlemma filter_odd_map: \"filter odd [0..<2*(x::nat)] = map (\\<lambda> y. (2::nat)*y +1) [0..<x]\"\n  by(induction x) simp+\n\nlemma filter_odd_nth: \"2*j < l \\<Longrightarrow> 2*x = l \\<Longrightarrow> (filter odd [0..<l] ! j) = (2*j+1)\"\n  using filter_odd_map[of x] nth_map[of j \"filter even [0..<l]\" \"(*) 2\"] by auto\n\ntext \\<open>\\noindent Lemmas by using the assumption $n = 2^N$.\\<close>\n\ntext \\<open>\\noindent ($-1$ denotes the additive inverse of $1$ in the finite field.)\\<close>\n\nlemma n_min1_2: \"n = 2  \\<Longrightarrow> \\<omega>  = -1\" \n  using omega_properties(1) omega_properties(2) power2_eq_1_iff by blast\n\nlemma n_min1_gr2:\n  assumes \"n > 2\"\n  shows \"\\<omega>^(n div 2) = -1\"\nproof-\n  have \"\\<omega>^(n div 2) \\<noteq> -1 \\<Longrightarrow> False\"\n  proof-\n  assume \"\\<omega>^(n div 2) \\<noteq> -1\"\n  hence False\n  proof (cases \\<open>\\<omega> ^ (n div 2) = 1\\<close>)\n    case True\n    then show ?thesis using omega_properties(3) assms\n      by auto\n  next\n    case False\n    hence \"(\\<omega>^(n div 2)) ^ (2::nat) \\<noteq> 1\" \n      by (smt (verit, ccfv_threshold) n_two_pot One_nat_def \\<open>\\<omega> ^ (n div 2) \\<noteq> - 1\\<close> diff_zero leD n_lst2 not_less_eq omega_properties(1) one_less_numeral_iff one_power2 power2_eq_square power_mult power_one_right power_strict_increasing_iff semiring_norm(76) square_eq_iff two_powr_div two_powrs_div)\n    moreover have \"(n div 2) * 2  = n\" using n_two_pot n_lst2  \n      by (metis One_nat_def Suc_lessD assms div_by_Suc_0 one_less_numeral_iff power_0 power_one_right power_strict_increasing_iff semiring_norm(76) two_powrs_div)\n    ultimately show ?thesis  using omega_properties(1)\n      by (metis power_mult)\n  qed\n    thus False by simp\n  qed\n  then show ?thesis by auto\nqed\n\nlemma div_exp_sub: \"2^l  < n \\<Longrightarrow> n div (2^l) = 2^(N-l)\"using n_two_pot\n    by (smt (z3) One_nat_def diff_is_0_eq diff_le_diff_pow div_if div_le_dividend eq_imp_le le_0_eq le_Suc_eq n_lst2 nat_less_le not_less_eq_eq numeral_2_eq_2 power_0 two_powr_div) \n\nlemma omega_div_exp_min1:\n  assumes \"2^(Suc l) \\<le> n\"\n  shows \"(\\<omega> ^(n div 2^(Suc l)))^(2^l) = -1\" \nproof-\n  have \"(\\<omega> ^(n div 2^(Suc l)))^(2^l) = \\<omega> ^((n div 2^(Suc l))*2^l)\"\n    by (simp add: power_mult)\n  moreover have \"(n div 2^(Suc l)) = 2^(N - Suc l)\" using assms div_exp_sub \n    by (metis n_two_pot eq_imp_le le_neq_implies_less one_less_numeral_iff power_diff power_inject_exp semiring_norm(76) zero_neq_numeral)\n  moreover have \"N \\<ge> Suc l\" using assms n_two_pot \n    by (metis diff_is_0_eq diff_le_diff_pow gr0I leD le_refl)\n  moreover hence \"(2::nat)^(N - Suc l)*2^l = 2^(N- 1)\" \n    by (metis Nat.add_diff_assoc diff_Suc_1 diff_diff_cancel diff_le_self le_add1 le_add_diff_inverse plus_1_eq_Suc power_add) \n  ultimately show ?thesis \n    by (metis n_two_pot One_nat_def \\<open>n div 2 ^ Suc l = 2 ^ (N - Suc l)\\<close> diff_Suc_1 div_exp_sub n_lst2 n_min1_2 n_min1_gr2 nat_less_le nat_power_eq_Suc_0_iff one_less_numeral_iff power_inject_exp power_one_right semiring_norm(76))\nqed\n\nlemma omg_n_2_min1:  \"\\<omega>^(n div 2) = -1\" \n  by (metis n_lst2 n_min1_2 n_min1_gr2 nat_less_le numeral_Bit0_div_2 numerals(1) power_one_right)\n\nlemma neg_cong: \"-(x::('a mod_ring)) = - y \\<Longrightarrow> x = y\" by simp\n\ntext \\<open>Generalized \\textit{NTT} indeed describes all recursive levels, \nand thus, it is actually equivalent to the ordinary \\textit{NTT} definition.\\<close>\n\ntheorem FNTT_NTT_gen_eq: \"length numbers = 2^l \\<Longrightarrow> 2^l \\<le> n \\<Longrightarrow> FNTT numbers = NTT_gen (length numbers) numbers\"\nproof(induction l arbitrary: numbers)\n  case 0\n  then show ?case unfolding NTT_gen_def ntt_gen_def \n    by (auto simp: length_Suc_conv)\nnext\n  case (Suc l)\n  text \\<open>We define some lists that are used during the recursive call.\\<close>\n  define numbers1 where \"numbers1 = [numbers!i .  i <- (filter even [0..<length numbers])]\" \n  define numbers2 where \"numbers2 = [numbers!i .  i <- (filter odd [0..<length numbers])]\" \n  define fntt1 where \"fntt1 = FNTT numbers1\"\n  define fntt2 where \"fntt2 = FNTT numbers2\" \n  define sum1 where \n    \"sum1 = map2 (+) fntt1 (map2 ( \\<lambda> x k.  x*(\\<omega>^( (n div (length numbers)) * k))) \n                   fntt2 [0..<((length numbers) div 2)])\" \n  define sum2 where  \n    \"sum2 = map2 (-) fntt1 (map2 ( \\<lambda> x k.  x*(\\<omega>^( (n div (length numbers)) * k))) \n                   fntt2 [0..<((length numbers) div 2)])\" \n  define l1 where \"l1 = length numbers1\"\n  define l2 where \"l2 = length numbers2\"\n  define llen where \"llen = length numbers\"\n\n  text \\<open>Properties of those lists.\\<close>\n  have numbers1_even: \"length numbers1 = 2^l\" \n     using numbers1_def length_even_filter Suc by simp\n   have numbers2_even: \"length numbers2 = 2^l\"\n     using numbers2_def length_odd_filter Suc by simp\n  have numbers1_fntt: \"fntt1 = NTT_gen (2^l) numbers1\" \n    using fntt1_def Suc.IH[of numbers1] numbers1_even Suc(3) by simp\n  hence fntt1_by_index: \"fntt1 ! i = ntt_gen numbers1 (2^l) i\" if \"i < 2^l\" for i\n    unfolding NTT_gen_def by (simp add: numbers1_even that)\n  have numbers2_fntt: \"fntt2 = NTT_gen (2^l) numbers2\" \n    using fntt2_def Suc.IH[of numbers2] numbers2_even Suc(3) by simp\n  hence fntt2_by_index: \"fntt2 ! i = ntt_gen numbers2 (2^l) i\" if \"i < 2^l\" for i\n    unfolding NTT_gen_def\n    by (simp add: numbers2_even that)\n  have fntt1_length: \"length fntt1 = 2^l\" unfolding numbers1_fntt NTT_gen_def numbers1_def\n    using numbers1_def numbers1_even by force\n   have fntt2_length: \"length fntt2 = 2^l\" unfolding numbers2_fntt NTT_gen_def numbers2_def\n     using numbers2_def numbers2_even by force\n\n   text \\<open>We show that the list resulting from $FNTT$ is equal to the $NTT$ list.\n         First, we prove $FNTT$ and $NTT$ to be equal concerning their first halves.\\<close>\n   have before_half: \"map (ntt_gen numbers llen) [0..<(llen div 2)] = sum1\"\n   proof-\n \n     text \\<open>Length is important, since we want to use list lemmas later on.\\<close>\n     have 00:\"length (map (ntt_gen numbers llen) [0..<(llen div 2)]) =  length sum1\"\n       unfolding sum1_def llen_def\n       using Suc(2) map2_length[of _ fntt2 \"[0..<length numbers div 2]\"]\n       map2_length[of \"(+)\" fntt1 \"(map2 (\\<lambda>x y. x * \\<omega> ^ (n div length numbers * y)) fntt2 [0..<length numbers div 2])\"]\n       fntt1_length fntt2_length by (simp add: mult_2)\n     have 01:\"length sum1 = 2^l\" unfolding sum1_def \n       using \"00\" Suc.prems(1) sum1_def unfolding llen_def by auto\n\n     text \\<open>We show equality by extensionality w.r.t. indices.\\<close>\n     have 02:\"(map (ntt_gen numbers llen) [0..<(llen div 2)]) ! i = sum1 ! i\" \n       if \"i < 2^l\" for i\n     proof-\n       text \\<open>First simplify this term.\\<close>\n       have 000:\"(map (ntt_gen numbers llen) [0..<(llen div 2)]) ! i =\n                   ntt_gen numbers llen i\" \n         using \"00\" \"01\" that by auto\n\n       text \\<open>Expand the definition of $sum1$ and massage the result.\\<close>\n       moreover have 001:\"sum1 ! i = (fntt1!i) + (fntt2!i) * (\\<omega>^((n div llen) * i))\"\n         unfolding sum1_def using map2_index\n         \"00\" \"01\" NTT_gen_def add.left_neutral diff_zero fntt1_length length_map length_upt map2_map_map map_nth nth_upt numbers2_even numbers2_fntt that llen_def by force\n       moreover have 002:\"(fntt1!i) = (\\<Sum>j=0..<l1. (numbers1 ! j) * \\<omega>^((n div (2^l))*i*j))\"\n         unfolding l1_def\n         using fntt1_by_index[of i] that unfolding ntt_gen_def by simp\n       have 003:\"... = (\\<Sum>j=0..<l1. (numbers ! (2*j)) * \\<omega>^((n div llen)*i*(2*j)))\"\n         apply (rule sum_rules(2))\n         subgoal for j unfolding numbers1_def \n           apply(subst llen_def[symmetric])\n         proof-\n           assume ass: \"j < l1 \"\n           hence \"map ((!) numbers) (filter even [0..<length numbers]) ! j = numbers ! (filter even [0..<length numbers] ! j)\"\n             using  nth_map[of j \"filter even [0..<length numbers]\" \"(!) numbers\" ] \n             unfolding l1_def numbers1_def\n             by (metis length_map)\n           moreover have \"filter even [0..<llen] ! j = 2 * j\" using\n            filter_even_nth[of j \"llen\" \"2^l\"] Suc(2)  ass numbers1_def numbers1_even \n             unfolding llen_def l1_def by fastforce\n           moreover have \"n div llen * (2 * j) = ((n div (2 ^ l))  * j)\"\n             using Suc(2) two_powrs_div[of l N] n_two_pot two_powr_div Suc(3) llen_def\n             by (metis One_nat_def div_if mult.assoc nat_less_le not_less_eq numeral_2_eq_2 power_eq_0_iff power_inject_exp zero_neq_numeral)\n           ultimately show \"map ((!) numbers) (filter even [0..<llen]) ! j * \\<omega> ^ (n div 2 ^ l * i * j) =\n                   numbers ! (2 * j) * \\<omega> ^ (n div llen * i * (2 * j))\" \n             unfolding llen_def l1_def l2_def by (metis (mono_tags, lifting) mult.assoc mult.left_commute)\n         qed\n         done\n       moreover have 004:\n          \"(fntt2!i) * (\\<omega>^((n div llen) * i)) = \n               (\\<Sum>j=0..<l2.(numbers2 ! j) * \\<omega>^((n div (2^l))*i*j+ (n div llen) * i))\"\n            apply(rule trans[where s = \"(\\<Sum>j = 0..<l2. numbers2 ! j * \\<omega> ^ (n div 2 ^ l * i * j) * \\<omega> ^ (n div llen * i))\"])\n         subgoal \n            unfolding l2_def llen_def\n            using fntt2_by_index[of i] that sum_in[of _ \"(\\<omega>^((n div llen) * i))\" \"l2\"] comm_semiring_1_class.semiring_normalization_rules(26)[of \\<omega>]\n            unfolding ntt_gen_def\n            using sum_rules  apply presburger\n            done\n          apply (rule sum_rules(2))\n          subgoal for j\n            using fntt2_by_index[of i] that sum_in[of _ \"(\\<omega>^((n div llen) * i))\" \"l2\"] comm_semiring_1_class.semiring_normalization_rules(26)[of \\<omega>]\n            unfolding ntt_gen_def\n            apply auto\n            done\n          done\n     have 005: \"\\<dots> = (\\<Sum>j=0..<l2. (numbers ! (2*j+1) * \\<omega>^((n div llen)*i*(2*j+1))))\"\n      apply (rule sum_rules(2))\n       subgoal for j unfolding numbers2_def \n         apply(subst llen_def[symmetric])\n           proof-\n           assume ass: \"j < l2 \"\n           hence \"map ((!) numbers) (filter odd [0..<llen]) ! j = numbers ! (filter odd [0..<llen] ! j)\"\n             using  nth_map unfolding l2_def numbers2_def llen_def by (metis length_map)\n           moreover have \"filter odd [0..<llen] ! j = 2 * j +1\" using\n            filter_odd_nth[of j \"length numbers\" \"2^l\"] Suc(2)  ass numbers2_def numbers2_even\n             unfolding l2_def numbers2_def llen_def by fastforce\n           moreover have \"n div llen * (2 * j) = ((n div (2 ^ l))  * j)\"\n             using Suc(2) two_powrs_div[of l N] n_two_pot two_powr_div Suc(3) llen_def\n             by (metis One_nat_def div_if mult.assoc nat_less_le not_less_eq numeral_2_eq_2 power_eq_0_iff power_inject_exp zero_neq_numeral)\n           ultimately show \n            \" map ((!) numbers) (filter odd [0..<llen]) ! j * \\<omega> ^ (n div 2 ^ l * i * j + n div llen * i) \n                = numbers ! (2 * j + 1) * \\<omega> ^ (n div llen * i * (2 * j + 1))\" unfolding llen_def\n             by (smt (z3) Groups.mult_ac(2) distrib_left mult.right_neutral mult_2 mult_cancel_left)\n         qed\n         done\n       then show ?thesis \n         using 000 001 002 003 004 005 \n         unfolding sum1_def llen_def l1_def l2_def\n         using sum_splice_other_way_round[of \"\\<lambda> d.  numbers ! d  * \\<omega> ^ (n div length numbers * i * d)\" \"2^l\"] Suc(2)\n         unfolding ntt_gen_def \n         by (smt (z3) Groups.mult_ac(2) numbers1_even numbers2_even power_Suc2)\n     qed\n     then show ?thesis \n       by  (metis \"00\" \"01\" nth_equalityI)\n   qed\n\n   text \\<open>We show equality for the indices in the second halves.\\<close>\n   have after_half: \"map (ntt_gen numbers llen) [(llen div 2)..<llen] = sum2\"\n   proof-\n     have 00:\"length (map (ntt_gen numbers llen) [(llen div 2)..<llen]) =  length sum2\"\n       unfolding sum2_def llen_def \n       using Suc(2) map2_length map2_length fntt1_length fntt2_length by (simp add: mult_2)\n     have 01:\"length sum2 = 2^l\" unfolding sum1_def \n       using \"00\" Suc.prems(1) sum1_def llen_def  by auto\n     text \\<open>Equality for every index.\\<close>\n     have 02:\"(map (ntt_gen numbers llen)  [(llen div 2)..<llen]) ! i = sum2 ! i\" \n       if \"i < 2^l\" for i\n     proof-\n       have 000:\"(map (ntt_gen numbers llen)  [(llen div 2)..<llen]) ! i =  ntt_gen numbers llen (2^l+i)\"\n         unfolding llen_def by (simp add: Suc.prems(1) that)\n       have 001:\" (map2 (\\<lambda>x y. x * \\<omega> ^ (n div llen * y)) fntt2 [0..<llen div 2]) ! i =\n                  fntt2 ! i * \\<omega> ^ (n div llen * i)\"\n         using  Suc(2) that by (simp add:  fntt2_length  llen_def)\n       have 003: \"- fntt2 ! i * \\<omega> ^ (n div llen * i) = \n                    fntt2 ! i * \\<omega> ^ (n div llen * (i+ llen div 2))\" \n         using Suc(2) omega_div_exp_min1[of l] unfolding llen_def\n         by (smt (z3) Suc.prems(2) mult.commute mult.left_commute mult_1s_ring_1(2) neq0_conv nonzero_mult_div_cancel_left numeral_One pos2 power_Suc power_add power_mult)\n       hence 004:\"sum2 ! i = (fntt1!i) - (fntt2!i) * (\\<omega>^((n div llen) * i))\"\n         unfolding sum2_def llen_def \n         by (simp add: Suc.prems(1) fntt1_length fntt2_length that)\n       have 005:\"(fntt1!i) = \n                     (\\<Sum>j=0..<l1. (numbers1 ! j) * \\<omega>^((n div (2^l))*i*j))\"\n        using fntt1_by_index that unfolding ntt_gen_def l1_def by simp\n      have 006:\"\\<dots> =(\\<Sum>j=0..<l1. (numbers ! (2*j)) * \\<omega>^((n div llen)*i*(2*j)))\"\n         apply (rule sum_rules(2))\n        subgoal for j unfolding numbers1_def \n          apply(subst llen_def[symmetric])\n         proof-\n           assume ass: \"j < l1 \"\n           hence \"map ((!) numbers) (filter even [0..<llen]) ! j = numbers ! (filter even [0..<llen] ! j)\"\n             using  nth_map unfolding llen_def l1_def numbers1_def by (metis length_map)\n           moreover have \"filter even [0..<llen] ! j = 2 * j\" using\n            filter_even_nth Suc(2)  ass numbers1_def numbers1_even llen_def l1_def by fastforce\n           moreover have \"n div llen * (2 * j) = ((n div (2 ^ l))  * j)\"\n             using Suc(2) two_powrs_div[of l N] n_two_pot two_powr_div Suc(3) llen_def\n             by (metis One_nat_def div_if mult.assoc nat_less_le not_less_eq numeral_2_eq_2 power_eq_0_iff power_inject_exp zero_neq_numeral)\n           ultimately show \n              \"map ((!) numbers) (filter even [0..<llen]) ! j * \\<omega> ^ (n div 2 ^ l * i * j) =\n                        numbers ! (2 * j) * \\<omega> ^ (n div llen * i * (2 * j))\" \n             by (metis (mono_tags, lifting) mult.assoc mult.left_commute)\n         qed\n         done\n        have 007:\"\\<dots> = (\\<Sum>j=0..<l1. (numbers ! (2*j)) * \\<omega>^((n div llen)*(2^l + i)*(2*j))) \"\n         apply (rule sum_rules(2))\n         subgoal for j \n           using Suc(2) Suc(3) omega_div_exp_min1[of l] llen_def l1_def numbers1_def\n           apply(smt (verit, del_insts) add.commute minus_power_mult_self mult_2 mult_minus1_right power_add power_mult)\n           done\n         done\n       moreover have 008: \"(fntt2!i) * (\\<omega>^((n div llen) * i)) =\n                      (\\<Sum>j=0..<l2. (numbers2 ! j) * \\<omega>^((n div (2^l))*i*j+ (n div llen) * i))\" \n         apply(rule trans[where s = \"(\\<Sum>j = 0..<l2. numbers2 ! j * \\<omega> ^ (n div 2 ^ l * i * j) * \\<omega> ^ (n div llen * i))\"])\n         subgoal \n           using fntt2_by_index[of i] that sum_in comm_semiring_1_class.semiring_normalization_rules(26)[of \\<omega>]\n           unfolding ntt_gen_def\n           using sum_rules l2_def apply presburger\n         done\n         apply (rule sum_rules(2))\n       subgoal for j\n         using fntt2_by_index[of i] that sum_in comm_semiring_1_class.semiring_normalization_rules(26)[of \\<omega>]\n         unfolding ntt_gen_def\n         apply auto\n         done\n       done\n     have 009: \"\\<dots> = (\\<Sum>j=0..<l2. (numbers ! (2*j+1) * \\<omega>^((n div llen)*i*(2*j+1))))\"\n      apply (rule sum_rules(2))\n       subgoal for j unfolding numbers2_def \n         apply(subst llen_def[symmetric])\n           proof-\n           assume ass: \"j < l2 \"\n           hence \"map ((!) numbers) (filter odd [0..<llen]) ! j = numbers ! (filter odd [0..<llen] ! j)\"\n             using  nth_map llen_def l2_def numbers2_def by (metis length_map)\n           moreover have \"filter odd [0..<llen] ! j = 2 * j +1\" using\n            filter_odd_nth Suc(2)  ass numbers2_def numbers2_even llen_def l2_def by fastforce\n           moreover have \"n div llen * (2 * j) = ((n div (2 ^ l))  * j)\"\n             using Suc(2) two_powrs_div[of l N] n_two_pot two_powr_div Suc(3) llen_def\n             by (metis One_nat_def div_if mult.assoc nat_less_le not_less_eq numeral_2_eq_2 power_eq_0_iff power_inject_exp zero_neq_numeral)\n           ultimately show \n             \"map ((!) numbers) (filter odd [0..<llen]) ! j * \\<omega> ^ (n div 2 ^ l * i * j + n div llen * i)\n                 = numbers ! (2 * j + 1) * \\<omega> ^ (n div llen * i * (2 * j + 1))\" \n             by (smt (z3) Groups.mult_ac(2) distrib_left mult.right_neutral mult_2 mult_cancel_left)\n         qed\n         done\n       have 010: \" (fntt2!i) * (\\<omega>^((n div llen) * i)) = (\\<Sum>j=0..<l2. (numbers ! (2*j+1) * \\<omega>^((n div llen)*i*(2*j+1)))) \"\n         using 008 009 by presburger\n       have 011: \" - (fntt2!i) * (\\<omega>^((n div llen) * i)) =\n                  (\\<Sum>j=0..<l2. - (numbers ! (2*j+1) * \\<omega>^((n div llen)*i*(2*j+1)))) \"\n         apply(rule neg_cong)\n         apply(rule trans[of _ \"fntt2 ! i * \\<omega> ^ (n div llen * i)\"])\n         subgoal by simp\n         apply(rule trans[where s=\"(\\<Sum>j=0..<l2. (numbers ! (2*j+1) * \\<omega>^((n div llen)*i*(2*j+1))))\"])\n          subgoal using 008 009 by simp \n         apply(rule sym)\n         using sum_neg_in[of _ \"l2\"] \n         apply simp\n         done\n       have 012: \"\\<dots> = (\\<Sum>j=0..<l2. (numbers ! (2*j+1) * \\<omega>^((n div llen)*(2^l+i)*(2*j+1))))\"\n         apply(rule sum_rules(2))\n         subgoal for j\n           using Suc(2) Suc(3) omega_div_exp_min1[of l] llen_def l2_def\n           apply (smt (z3) add.commute exp_rule mult.assoc mult_minus1_right plus_1_eq_Suc power_add power_minus1_odd power_mult)\n           done\n         done\n       have 013:\"fntt1 ! i = (\\<Sum>j = 0..<2 ^ l. numbers!(2*j) * \\<omega> ^ (n div llen * (2^l + i) * (2*j)))\"\n         using 005 006 007 numbers1_even llen_def  l1_def by auto\n       have 014: \"(\\<Sum>j = 0..<2 ^ l. numbers ! (2*j + 1) * \\<omega> ^ (n div llen* (2^l + i) * (2*j + 1))) =\n                    - fntt2 ! i * \\<omega> ^ (n div llen * i)\"\n      using  trans[OF l2_def numbers2_even]  sym[OF 012] sym[OF 011] by simp\n      have \"ntt_gen numbers llen (2 ^ l + i) = (fntt1!i) - (fntt2!i) * (\\<omega>^((n div llen) * i))\"\n        unfolding ntt_gen_def apply(subst Suc(2))\n        using  sum_splice[of \"\\<lambda> d.  numbers ! d  * \\<omega> ^ (n div llen * (2^l+i) * d)\" \"2^l\"] sym[OF 013]  014 Suc(2) by simp\n       thus ?thesis using 000 sym[OF 001] \"004\" sum2_def by simp\n     qed    \n     then show ?thesis \n       by (metis \"00\" \"01\" list_eq_iff_nth_eq)\n   qed\n   obtain x y xs where xyxs: \"numbers = x#y#xs\" using Suc(2) \n     by (metis FNTT.cases add.left_neutral even_Suc even_add length_Cons list.size(3) mult_2 power_Suc power_eq_0_iff zero_neq_numeral)\n   show ?case \n    apply(subst xyxs)\n    apply(subst FNTT.simps(3))\n    apply(subst xyxs[symmetric])+\n     unfolding Let_def      \n     using map_append[of \"ntt_gen numbers llen\" \" [0..<llen div 2]\" \"[llen div 2..<llen]\"] before_half after_half \n     unfolding llen_def sum1_def sum2_def fntt1_def fntt2_def NTT_gen_def\n    apply (metis (no_types, lifting) Suc.prems(1) numbers1_def length_odd_filter mult_2 numbers2_def numbers2_even power_Suc upt_add_eq_append zero_le_numeral zero_le_power)\n   done\nqed\n\ntext \\<open>\\noindent \\textbf{Major Correctness Theorem for Butterfly Algorithm}.\\\\\n \nWe have already shown:\n\\begin{itemize}\n\\item Generalized $NTT$ with degree annotation $2^N$ equals usual $NTT$.\n\\item Generalized $NTT$ tracks all levels of recursion in $FNTT$.\n\\end{itemize}\nThus, $FNTT$ equals $NTT$.\n\\<close>\n\ntheorem FNTT_correct:\n  assumes \"length numbers = n\"\n  shows \"FNTT numbers = NTT numbers\"\n  using FNTT_NTT_gen_eq NTT_gen_NTT_full_length assms n_two_pot by force\n\nsubsection \\<open>Inverse Transform in Butterfly Scheme\\<close>\n\ntext \\<open>We also formalized the inverse transform by using the butterfly scheme.\nProofs are obtained by adaption of arguments for $FNTT$.\\<close>\n\n\nlemmas [simp] = FNTT_termination_aux\n\nfun IFNTT where\n\"IFNTT [] = []\"|\n\"IFNTT [a] = [a]\"|\n\"IFNTT nums = (let nn = length nums;\n                  nums1 = [nums!i .  i <- (filter even [0..<nn])];\n                  nums2 = [nums!i .  i <- (filter odd [0..<nn])];\n                  ifntt1 = IFNTT nums1;\n                  ifntt2 = IFNTT nums2;\n                  sum1 = map2 (+) ifntt1 (map2 ( \\<lambda> x k.  x*(\\<mu>^( (n div nn) * k))) ifntt2 [0..<(nn div 2)]);\n                  sum2 = map2 (-) ifntt1 (map2 ( \\<lambda> x k.  x*(\\<mu>^( (n div nn) * k))) ifntt2 [0..<(nn div 2)])\n                   in sum1@sum2)\"\n\nlemmas [simp del] = FNTT_termination_aux\n\n\ndefinition \"intt_gen numbers degr i = (\\<Sum>j=0..<(length numbers). (numbers ! j) * \\<mu> ^((n div degr)*i*j)) \"\n\ndefinition \"INTT_gen degr numbers = map (intt_gen numbers (degr)) [0..< length numbers]\"\n\nlemma INTT_gen_INTT_full_length: \n  assumes \"length numbers =n\"\n  shows \"INTT_gen n numbers = INTT numbers\"\n  unfolding INTT_gen_def intt_gen_def INTT_def intt_def \n  using assms by simp\n\nlemma my_div_exp_min1:\n  assumes \"2^(Suc l) \\<le> n\"\n  shows \"(\\<mu> ^(n div 2^(Suc l)))^(2^l) = -1\" \n  by (metis assms divide_minus1 mult_zero_right mu_properties(1) nonzero_mult_div_cancel_right omega_div_exp_min1 power_one_over zero_neq_one)\n\nlemma my_n_2_min1:  \"\\<mu>^(n div 2) = -1\" \n  by (metis divide_minus1 mult_zero_right mu_properties(1) nonzero_mult_div_cancel_right omg_n_2_min1 power_one_over zero_neq_one)\n\ntext \\<open>Correctness proof by common induction technique. Same strategies as for $FNTT$.\\<close>\n\ntheorem IFNTT_INTT_gen_eq: \n \"length numbers = 2^l \\<Longrightarrow> 2^l \\<le> n \\<Longrightarrow> IFNTT numbers = INTT_gen (length numbers) numbers\"\nproof(induction l arbitrary: numbers)\n  case 0\n  hence \"local.IFNTT numbers = [numbers ! 0]\" \n    by (metis IFNTT.simps(2) One_nat_def Suc_length_conv length_0_conv nth_Cons_0 power_0)\n  then show ?case unfolding INTT_gen_def intt_gen_def \n    using 0 by simp\nnext\n  case (Suc l)\n  text \\<open>We define some lists that are used during the recursive call.\\<close>\n  define numbers1 where \"numbers1 = [numbers!i .  i <- (filter even [0..<length numbers])]\" \n  define numbers2 where \"numbers2 = [numbers!i .  i <- (filter odd [0..<length numbers])]\" \n  define ifntt1 where \"ifntt1 = IFNTT numbers1\"\n  define ifntt2 where \"ifntt2 = IFNTT numbers2\" \n  define sum1 where \n    \"sum1 = map2 (+) ifntt1 (map2 ( \\<lambda> x k.  x*(\\<mu>^( (n div (length numbers)) * k))) \n                   ifntt2 [0..<((length numbers) div 2)])\" \n  define sum2 where  \n    \"sum2 = map2 (-) ifntt1 (map2 ( \\<lambda> x k.  x*(\\<mu>^( (n div (length numbers)) * k))) \n                   ifntt2 [0..<((length numbers) div 2)])\" \n  define l1 where \"l1 = length numbers1\"\n  define l2 where \"l2 = length numbers2\"\n  define llen where \"llen = length numbers\"\n\n  text \\<open>Properties of those lists\\<close>\n  have numbers1_even: \"length numbers1 = 2^l\" \n     using numbers1_def length_even_filter Suc by simp\n   have numbers2_even: \"length numbers2 = 2^l\"\n     using numbers2_def length_odd_filter Suc by simp\n  have numbers1_ifntt: \"ifntt1 = INTT_gen (2^l) numbers1\" \n    using ifntt1_def Suc.IH[of numbers1] numbers1_even Suc(3) by simp\n  hence ifntt1_by_index: \"ifntt1 ! i = intt_gen numbers1 (2^l) i\" if \"i < 2^l\" for i\n    unfolding INTT_gen_def by (simp add: numbers1_even that)\n  have numbers2_ifntt: \"ifntt2 = INTT_gen (2^l) numbers2\" \n    using ifntt2_def Suc.IH[of numbers2] numbers2_even Suc(3) by simp\n  hence ifntt2_by_index: \"ifntt2 ! i = intt_gen numbers2 (2^l) i\" if \"i < 2^l\" for i\n    unfolding INTT_gen_def by (simp add: numbers2_even that)\n  have ifntt1_length: \"length ifntt1 = 2^l\" unfolding numbers1_ifntt INTT_gen_def numbers1_def\n    using numbers1_def numbers1_even by force\n   have ifntt2_length: \"length ifntt2 = 2^l\" unfolding numbers2_ifntt INTT_gen_def numbers2_def\n     using numbers2_def numbers2_even by force\n\n   text \\<open>Same proof structure as for the  \\textit{FNTT} proof.\n         $\\omega$s are just replaced by $\\mu$s.\\<close>\n   have before_half: \"map (intt_gen numbers llen) [0..<(llen div 2)] = sum1\"\n   proof-\n \n     text \\<open>Length is important, since we want to use list lemmas later on.\\<close>\n     have 00:\"length (map (intt_gen numbers llen) [0..<(llen div 2)]) =  length sum1\"\n       unfolding sum1_def llen_def\n       using Suc(2) map2_length[of _ ifntt2 \"[0..<length numbers div 2]\"]\n       map2_length[of \"(+)\" ifntt1 \"(map2 (\\<lambda>x y. x * \\<mu> ^ (n div length numbers * y)) ifntt2 [0..<length numbers div 2])\"]\n       ifntt1_length ifntt2_length by (simp add: mult_2)\n     have 01:\"length sum1 = 2^l\" unfolding sum1_def \n       using \"00\" Suc.prems(1) sum1_def unfolding llen_def by auto\n\n     text \\<open>We show equality by extensionality on indices.\\<close>\n     have 02:\"(map (intt_gen numbers llen) [0..<(llen div 2)]) ! i = sum1 ! i\" \n       if \"i < 2^l\" for i\n     proof-\n       text \\<open>First simplify this term.\\<close>\n       have 000:\"(map (intt_gen numbers llen) [0..<(llen div 2)]) ! i =  intt_gen numbers llen i\" \n         using \"00\" \"01\" that by auto\n\n       text \\<open>Expand the definition of $sum1$ and massage the result.\\<close>\n       moreover have 001:\"sum1 ! i = (ifntt1!i) + (ifntt2!i) * (\\<mu>^((n div llen) * i))\"\n         unfolding sum1_def using map2_index\n         \"00\" \"01\" INTT_gen_def add.left_neutral diff_zero ifntt1_length length_map length_upt map2_map_map map_nth nth_upt numbers2_even numbers2_ifntt that llen_def by force\n       moreover have 002:\"(ifntt1!i) = (\\<Sum>j=0..<l1. (numbers1 ! j) * \\<mu>^((n div (2^l))*i*j))\"\n         unfolding l1_def\n         using ifntt1_by_index[of i] that unfolding intt_gen_def by simp\n       have 003:\"... = (\\<Sum>j=0..<l1. (numbers ! (2*j)) * \\<mu>^((n div llen)*i*(2*j)))\"\n         apply (rule sum_rules(2))\n         subgoal for j unfolding numbers1_def \n           apply(subst llen_def[symmetric])\n         proof-\n           assume ass: \"j < l1 \"\n           hence \"map ((!) numbers) (filter even [0..<length numbers]) ! j = numbers ! (filter even [0..<length numbers] ! j)\"\n             using  nth_map[of j \"filter even [0..<length numbers]\" \"(!) numbers\" ] \n             unfolding l1_def numbers1_def\n             by (metis length_map)\n           moreover have \"filter even [0..<llen] ! j = 2 * j\" using\n            filter_even_nth[of j \"llen\" \"2^l\"] Suc(2)  ass numbers1_def numbers1_even \n             unfolding llen_def l1_def by fastforce\n           moreover have \"n div llen * (2 * j) = ((n div (2 ^ l))  * j)\"\n             using Suc(2) two_powrs_div[of l N] n_two_pot two_powr_div Suc(3) llen_def\n             by (metis One_nat_def div_if mult.assoc nat_less_le not_less_eq numeral_2_eq_2 power_eq_0_iff power_inject_exp zero_neq_numeral)\n           ultimately show \"map ((!) numbers) (filter even [0..<llen]) ! j * \\<mu> ^ (n div 2 ^ l * i * j) =\n                   numbers ! (2 * j) * \\<mu> ^ (n div llen * i * (2 * j))\" \n             unfolding llen_def l1_def l2_def by (metis (mono_tags, lifting) mult.assoc mult.left_commute)\n         qed\n         done\n       moreover have 004:\n          \"(ifntt2!i) * (\\<mu>^((n div llen) * i)) = \n               (\\<Sum>j=0..<l2.(numbers2 ! j) * \\<mu>^((n div (2^l))*i*j+ (n div llen) * i))\"\n          apply(rule trans[where s = \"(\\<Sum>j = 0..<l2. numbers2 ! j * \\<mu> ^ (n div 2 ^ l * i * j) * \\<mu> ^ (n div llen * i))\"])\n         subgoal \n            unfolding l2_def llen_def\n            using ifntt2_by_index[of i] that sum_in[of _ \"(\\<mu>^((n div llen) * i))\" \"l2\"] comm_semiring_1_class.semiring_normalization_rules(26)[of \\<mu>]\n            unfolding intt_gen_def\n            using sum_rules apply presburger\n            done\n          apply (rule sum_rules(2))\n          subgoal for j\n             using ifntt2_by_index[of i] that sum_in[of _ \"(\\<mu>^((n div llen) * i))\" \"l2\"] comm_semiring_1_class.semiring_normalization_rules(26)[of \\<mu>]\n            unfolding intt_gen_def\n            apply auto\n            done\n          done\n     have 005: \"\\<dots> = (\\<Sum>j=0..<l2. (numbers ! (2*j+1) * \\<mu>^((n div llen)*i*(2*j+1))))\"\n      apply (rule sum_rules(2))\n       subgoal for j unfolding numbers2_def \n         apply(subst llen_def[symmetric])\n           proof-\n           assume ass: \"j < l2 \"\n           hence \"map ((!) numbers) (filter odd [0..<llen]) ! j = numbers ! (filter odd [0..<llen] ! j)\"\n             using  nth_map unfolding l2_def numbers2_def llen_def by (metis length_map)\n           moreover have \"filter odd [0..<llen] ! j = 2 * j +1\" using\n            filter_odd_nth[of j \"length numbers\" \"2^l\"] Suc(2)  ass numbers2_def numbers2_even\n             unfolding l2_def numbers2_def llen_def by fastforce\n           moreover have \"n div llen * (2 * j) = ((n div (2 ^ l))  * j)\"\n             using Suc(2) two_powrs_div[of l N] n_two_pot two_powr_div Suc(3) llen_def\n             by (metis One_nat_def div_if mult.assoc nat_less_le not_less_eq numeral_2_eq_2 power_eq_0_iff power_inject_exp zero_neq_numeral)\n           ultimately show \n            \" map ((!) numbers) (filter odd [0..<llen]) ! j * \\<mu> ^ (n div 2 ^ l * i * j + n div llen * i) \n                = numbers ! (2 * j + 1) * \\<mu> ^ (n div llen * i * (2 * j + 1))\" unfolding llen_def\n             by (smt (z3) Groups.mult_ac(2) distrib_left mult.right_neutral mult_2 mult_cancel_left)\n         qed\n         done\n       then show ?thesis \n         using 000 001 002 003 004 005 \n         unfolding sum1_def llen_def l1_def l2_def\n         using sum_splice_other_way_round[of \"\\<lambda> d.  numbers ! d  * \\<mu> ^ (n div length numbers * i * d)\" \"2^l\"] Suc(2)\n         unfolding intt_gen_def \n         by (smt (z3) Groups.mult_ac(2) numbers1_even numbers2_even power_Suc2)\n     qed\n     then show ?thesis \n       by  (metis \"00\" \"01\" nth_equalityI)\n   qed\n\n   text \\<open>We show index-wise equality for the second halves\\<close>\n   have after_half: \"map (intt_gen numbers llen) [(llen div 2)..<llen] = sum2\"\n   proof-\n     have 00:\"length (map (intt_gen numbers llen) [(llen div 2)..<llen]) =  length sum2\"\n       unfolding sum2_def llen_def \n       using Suc(2) map2_length map2_length ifntt1_length ifntt2_length by (simp add: mult_2)\n     have 01:\"length sum2 = 2^l\" unfolding sum1_def \n       using \"00\" Suc.prems(1) sum1_def llen_def  by auto\n\n     text \\<open>Equality for every index\\<close>\n     have 02:\"(map (intt_gen numbers llen)  [(llen div 2)..<llen]) ! i = sum2 ! i\" \n       if \"i < 2^l\" for i\n     proof-\n       have 000:\"(map (intt_gen numbers llen)  [(llen div 2)..<llen]) ! i =  intt_gen numbers llen (2^l+i)\"\n         unfolding llen_def by (simp add: Suc.prems(1) that)\n       have 001:\" (map2 (\\<lambda>x y. x * \\<mu> ^ (n div llen * y)) ifntt2 [0..<llen div 2]) ! i =\n                  ifntt2 ! i * \\<mu> ^ (n div llen * i)\"\n         using  Suc(2) that by (simp add:  ifntt2_length  llen_def)\n       have 003: \"- ifntt2 ! i * \\<mu> ^ (n div llen * i) = ifntt2 ! i * \\<mu> ^ (n div llen * (i+ llen div 2))\" \n         using Suc(2) my_div_exp_min1[of l] unfolding llen_def\n         by (smt (z3) Suc.prems(2) mult.commute mult.left_commute mult_1s_ring_1(2) neq0_conv nonzero_mult_div_cancel_left numeral_One pos2 power_Suc power_add power_mult)\n       hence 004:\"sum2 ! i = (ifntt1!i) - (ifntt2!i) * (\\<mu>^((n div llen) * i))\"\n         unfolding sum2_def llen_def \n         by (simp add: Suc.prems(1) ifntt1_length ifntt2_length that)\n       have 005:\"(ifntt1!i) = \n                     (\\<Sum>j=0..<l1. (numbers1 ! j) * \\<mu>^((n div (2^l))*i*j))\"\n        using ifntt1_by_index that unfolding intt_gen_def l1_def by simp\n      have 006:\"\\<dots> =(\\<Sum>j=0..<l1. (numbers ! (2*j)) * \\<mu>^((n div llen)*i*(2*j)))\"\n         apply (rule sum_rules(2))\n         subgoal for j unfolding numbers1_def \n          apply(subst llen_def[symmetric])\n         proof-\n           assume ass: \"j < l1 \"\n           hence \"map ((!) numbers) (filter even [0..<llen]) ! j = numbers ! (filter even [0..<llen] ! j)\"\n             using  nth_map unfolding llen_def l1_def numbers1_def by (metis length_map)\n           moreover have \"filter even [0..<llen] ! j = 2 * j\" using\n            filter_even_nth Suc(2)  ass numbers1_def numbers1_even llen_def l1_def by fastforce\n           moreover have \"n div llen * (2 * j) = ((n div (2 ^ l))  * j)\"\n             using Suc(2) two_powrs_div[of l N] n_two_pot two_powr_div Suc(3) llen_def\n             by (metis One_nat_def div_if mult.assoc nat_less_le not_less_eq numeral_2_eq_2 power_eq_0_iff power_inject_exp zero_neq_numeral)\n           ultimately show \n              \"map ((!) numbers) (filter even [0..<llen]) ! j * \\<mu> ^ (n div 2 ^ l * i * j) =\n                        numbers ! (2 * j) * \\<mu> ^ (n div llen * i * (2 * j))\" \n             by (metis (mono_tags, lifting) mult.assoc mult.left_commute)\n         qed\n         done\n        have 007:\"\\<dots> = (\\<Sum>j=0..<l1. (numbers ! (2*j)) * \\<mu> ^((n div llen)*(2^l + i)*(2*j))) \"\n         apply (rule sum_rules(2))\n         subgoal for j \n           using Suc(2) Suc(3) my_div_exp_min1[of l] llen_def l1_def numbers1_def\n           apply(smt (verit, del_insts) add.commute minus_power_mult_self mult_2 mult_minus1_right power_add power_mult)\n           done\n         done\n       moreover have 008: \"(ifntt2!i) * (\\<mu>^((n div llen) * i)) =\n                      (\\<Sum>j=0..<l2. (numbers2 ! j) * \\<mu>^((n div (2^l))*i*j+ (n div llen) * i))\"\n         apply(rule trans[where s = \"(\\<Sum>j = 0..<l2. numbers2 ! j * \\<mu> ^ (n div 2 ^ l * i * j) * \\<mu> ^ (n div llen * i))\"])\n         subgoal \n          using ifntt2_by_index[of i] that sum_in comm_semiring_1_class.semiring_normalization_rules(26)[of \\<mu>]\n          unfolding intt_gen_def\n          using sum_rules l2_def apply presburger\n         done\n         apply (rule sum_rules(2))\n       subgoal for j\n         using ifntt2_by_index[of i] that sum_in comm_semiring_1_class.semiring_normalization_rules(26)[of \\<mu>]\n         unfolding intt_gen_def\n         apply auto \n         done\n       done\n     have 009: \"\\<dots> = (\\<Sum>j=0..<l2. (numbers ! (2*j+1) * \\<mu>^((n div llen)*i*(2*j+1))))\"\n      apply (rule sum_rules(2))\n       subgoal for j unfolding numbers2_def \n         apply(subst llen_def[symmetric])\n           proof-\n           assume ass: \"j < l2 \"\n           hence \"map ((!) numbers) (filter odd [0..<llen]) ! j = numbers ! (filter odd [0..<llen] ! j)\"\n             using  nth_map llen_def l2_def numbers2_def by (metis length_map)\n           moreover have \"filter odd [0..<llen] ! j = 2 * j +1\" using\n            filter_odd_nth Suc(2)  ass numbers2_def numbers2_even llen_def l2_def by fastforce\n           moreover have \"n div llen * (2 * j) = ((n div (2 ^ l))  * j)\"\n             using Suc(2) two_powrs_div[of l N] n_two_pot two_powr_div Suc(3) llen_def\n             by (metis One_nat_def div_if mult.assoc nat_less_le not_less_eq numeral_2_eq_2 power_eq_0_iff power_inject_exp zero_neq_numeral)\n           ultimately show \n             \"map ((!) numbers) (filter odd [0..<llen]) ! j * \\<mu> ^ (n div 2 ^ l * i * j + n div llen * i)\n                 = numbers ! (2 * j + 1) * \\<mu> ^ (n div llen * i * (2 * j + 1))\" \n             by (smt (z3) Groups.mult_ac(2) distrib_left mult.right_neutral mult_2 mult_cancel_left)\n         qed\n         done\n       have 010: \" (ifntt2!i) * (\\<mu>^((n div llen) * i)) = (\\<Sum>j=0..<l2. (numbers ! (2*j+1) * \\<mu>^((n div llen)*i*(2*j+1)))) \"\n         using 008 009 by presburger\n       have 011: \" - (ifntt2!i) * (\\<mu>^((n div llen) * i)) =\n                  (\\<Sum>j=0..<l2. - (numbers ! (2*j+1) * \\<mu>^((n div llen)*i*(2*j+1)))) \"\n         apply(rule neg_cong)\n         apply(rule trans[where s=\"(\\<Sum>j=0..<l2. (numbers ! (2*j+1) * \\<mu>^((n div llen)*i*(2*j+1))))\"])\n         subgoal using 008 009 by simp\n         apply(rule sym)\n         using sum_neg_in[of _ \"l2\"] \n         apply simp\n         done\n       have 012: \"\\<dots> = (\\<Sum>j=0..<l2. (numbers ! (2*j+1) * \\<mu>^((n div llen)*(2^l+i)*(2*j+1))))\"\n         apply(rule sum_rules(2))\n         subgoal for j\n           using Suc(2) Suc(3) my_div_exp_min1[of l] llen_def l2_def\n           apply (smt (z3) add.commute exp_rule mult.assoc mult_minus1_right plus_1_eq_Suc power_add power_minus1_odd power_mult)\n           done\n         done\n       have 013:\"ifntt1 ! i = (\\<Sum>j = 0..<2 ^ l. numbers!(2*j) * \\<mu> ^ (n div llen * (2^l + i) * (2*j)))\"\n         using 005 006 007 numbers1_even llen_def  l1_def by auto\n       have 014: \"(\\<Sum>j = 0..<2 ^ l. numbers ! (2*j + 1) * \\<mu> ^ (n div llen* (2^l + i) * (2*j + 1))) =\n                    - ifntt2 ! i * \\<mu> ^ (n div llen * i)\"\n      using  trans[OF l2_def numbers2_even]  sym[OF 012] sym[OF 011] by simp\n      have \"intt_gen numbers llen (2 ^ l + i) = (ifntt1!i) - (ifntt2!i) * (\\<mu>^((n div llen) * i))\"\n        unfolding intt_gen_def \n        apply(subst Suc(2))\n        using  sum_splice[of \"\\<lambda> d.  numbers ! d  * \\<mu> ^ (n div llen * (2^l+i) * d)\" \"2^l\"] sym[OF 013]  014 Suc(2) by simp\n       thus ?thesis using 000 sym[OF 001] \"004\" sum2_def by simp\n     qed    \n     then show ?thesis \n       by (metis \"00\" \"01\" list_eq_iff_nth_eq)\n   qed\n   obtain x y xs where xyxs: \"numbers = x#y#xs\" using Suc(2) \n     by (metis FNTT.cases add.left_neutral even_Suc even_add length_Cons list.size(3) mult_2 power_Suc power_eq_0_iff zero_neq_numeral)\n   show ?case \n    apply(subst xyxs)\n    apply(subst IFNTT.simps(3))\n    apply(subst xyxs[symmetric])+\n     unfolding Let_def      \n     using map_append[of \"intt_gen numbers llen\" \" [0..<llen div 2]\" \"[llen div 2..<llen]\"] before_half after_half \n     unfolding llen_def sum1_def sum2_def ifntt1_def ifntt2_def INTT_gen_def\n    apply (metis (no_types, lifting) Suc.prems(1) numbers1_def length_odd_filter mult_2 numbers2_def numbers2_even power_Suc upt_add_eq_append zero_le_numeral zero_le_power)\n   done\nqed\n\ntext \\<open>Correctness of the butterfly scheme for the inverse \\textit{INTT}.\\<close>\n\ntheorem IFNTT_correct:\n  assumes \"length numbers = n\"\n  shows \"IFNTT numbers = INTT numbers\"\n  using IFNTT_INTT_gen_eq INTT_gen_INTT_full_length assms n_two_pot by force\n\ntext \\<open>Also $FNTT$ and $IFNTT$ are mutually inverse\\<close>\n\ntheorem IFNTT_inv_FNTT:  \n  assumes \"length numbers = n\"\n  shows \"IFNTT (FNTT numbers) = map ((*) (of_int_mod_ring (int n))) numbers\"\n  by (simp add: FNTT_correct IFNTT_correct assms length_NTT ntt_correct)\n\ntext \\<open>The other way round:\\<close>\n\ntheorem FNTT_inv_IFNTT:  \n  assumes \"length numbers = n\"\n  shows \"FNTT (IFNTT numbers) = map ((*) (of_int_mod_ring (int n))) numbers\"\nby (simp add: FNTT_correct IFNTT_correct assms inv_ntt_correct length_INTT)\n\nsubsection \\<open>An Optimization\\<close>\ntext \\<open>Currently, we extract elements on even and odd positions respectively by a list comprehension \n     over even and odd indices. \nDue to the definition in Isabelle, an index access has linear time complexity. \nThis results in quadratic running time complexity for every level\nin the recursion tree of the \\textit{FNTT}. \nIn order to reach the $\\mathcal{O}(n \\log n)$ time bound, \nwe have find a better way of splitting the elements at even or odd indices respectively.\n\\<close>\n\ntext \\<open>A core of this optimization is the $evens\\text{-}odds$ function,\n which splits the vectors in linear time.\\<close>\n\nfun evens_odds::\"bool \\<Rightarrow>'b list \\<Rightarrow> 'b list\" where\n\"evens_odds _ [] = []\"|\n\"evens_odds True (x#xs)= (x# evens_odds False xs)\"|\n\"evens_odds False (x#xs) = evens_odds True xs\"\n\nlemma map_filter_shift: \" map f (filter even [0..<Suc g]) = \n        f 0 #  map (\\<lambda> x. f (x+1)) (filter odd [0..<g])\"\n  by (induction g) auto\n\nlemma map_filter_shift': \" map f (filter odd [0..<Suc g]) = \n          map (\\<lambda> x. f (x+1)) (filter even [0..<g])\"\n  by (induction g) auto\n\ntext \\<open>A splitting by the $evens\\text{-}odds$ function is \nequivalent to the more textbook-like list comprehension.\\<close>\n\nlemma filter_compehension_evens_odds:\n      \"[xs ! i. i <- filter even [0..<length xs]] = evens_odds True xs \\<and>\n       [xs ! i. i <- filter odd [0..<length xs]] = evens_odds False xs \"\n  apply(induction xs)\n   apply simp\n  subgoal for x xs\n    apply rule\n    subgoal \n      apply(subst evens_odds.simps)\n      apply(rule trans[of _ \"map ((!) (x # xs)) (filter even [0..<Suc (length xs)])\"])\n      subgoal by simp\n      apply(rule trans[OF  map_filter_shift[of \"(!) (x # xs)\" \"length xs\"]])\n      apply simp\n      done\n\n      apply(subst evens_odds.simps)\n      apply(rule trans[of _ \"map ((!) (x # xs)) (filter odd [0..<Suc (length xs)])\"])\n      subgoal by simp\n      apply(rule trans[OF  map_filter_shift'[of \"(!) (x # xs)\" \"length xs\"]])\n      apply simp\n    done\n  done\n\ntext \\<open>For automated termination proof.\\<close>\n\n\n\n\ntext \\<open>The $FNTT$ definition from above was suitable for matters of proof conduction.\n   However, the naive decomposition into elements at odd and even indices induces a complexity of $n^2$ in every recursive step.\nAs mentioned, the $evens\\text{-}odds$ function filters for elements on even or odd positions respectively.\nThe list has to be traversed only once which gives \\textit{linear} complexity for every recursive step. \\<close>\n\nfun FNTT' where\n\"FNTT' [] = []\"|\n\"FNTT' [a] = [a]\"|\n\"FNTT' nums = (let nn = length nums;\n                  nums1 = evens_odds  True nums;\n                  nums2 = evens_odds False nums;\n                  fntt1 = FNTT' nums1;\n                  fntt2 = FNTT' nums2;\n                  fntt2_omg =  (map2 ( \\<lambda> x k.  x*(\\<omega>^( (n div nn) * k))) fntt2 [0..<(nn div 2)]);\n                  sum1 = map2 (+) fntt1 fntt2_omg;\n                  sum2 = map2 (-) fntt1 fntt2_omg\n                   in sum1@sum2)\"\n\ntext \\<open>The optimized \\textit{FNTT} is equivalent to the naive \\textit{NTT}.\\<close>\n\nlemma FNTT'_FNTT: \"FNTT' xs = FNTT xs\"\n  apply(induction xs rule: FNTT'.induct)\n  subgoal by simp\n  subgoal by simp\n  apply(subst FNTT'.simps(3))\n  apply(subst FNTT.simps(3))\n  subgoal for a b xs\n    unfolding Let_def\n    apply (metis filter_compehension_evens_odds)\n    done\n  done\n\ntext \\<open>It is quite surprising that some inaccuracies in the interpretation of informal textbook definitions \n- even when just considering such a simple algorithm - can indeed affect time complexity.\\<close>\n\nsubsection \\<open>Arguments on Running Time\\<close>\n\ntext \\<open> $FFT$ is especially known for its $\\mathcal{O}(n \\log n)$ running time. \nUnfortunately, Isabelle does not provide a built-in time formalization. \nNonetheless we can reason about running time after defining some \"reasonable\" consumption functions by hand.\nOur approach loosely follows a general pattern by Nipkow et al.~\\parencite{funalgs}.\nFirst, we give running times and lemmas for the auxiliary functions used during FNTT.\\\\\nGeneral ideas behind the $\\mathcal{O}(n \\log n)$ are:\n\\begin{itemize}\n\\item By recursively halving the problem size, we obtain a tree of depth  $\\mathcal{O}(\\log n)$.\n\\item For every level of that tree, we have to process all elements which gives  $\\mathcal{O}(n)$ time.\n\\end{itemize}\n\n\\<close>\n\ntext \\<open>Time for splitting the list according to even and odd indices.\\<close>\n\nfun T_\\<^sub>e\\<^sub>o::\"bool \\<Rightarrow> 'c list \\<Rightarrow> nat\" where\n\" T_\\<^sub>e\\<^sub>o _ [] = 1\"|\n\" T_\\<^sub>e\\<^sub>o True (x#xs)= (1+  T_\\<^sub>e\\<^sub>o False xs)\"|\n\" T_\\<^sub>e\\<^sub>o  False (x#xs) = (1+  T_\\<^sub>e\\<^sub>o True xs)\"\n\nlemma T_eo_linear:  \"T_\\<^sub>e\\<^sub>o b xs = length xs + 1\"\n  by (induction b xs rule: T_\\<^sub>e\\<^sub>o.induct) auto\n\ntext \\<open>Time for length.\\<close>\n\nfun T\\<^sub>l\\<^sub>e\\<^sub>n\\<^sub>g\\<^sub>t\\<^sub>h where\n\"T\\<^sub>l\\<^sub>e\\<^sub>n\\<^sub>g\\<^sub>t\\<^sub>h [] = 1 \"|\n\"T\\<^sub>l\\<^sub>e\\<^sub>n\\<^sub>g\\<^sub>t\\<^sub>h (x#xs) = 1+ T\\<^sub>l\\<^sub>e\\<^sub>n\\<^sub>g\\<^sub>t\\<^sub>h xs\"\n\nlemma T_length_linear: \"T\\<^sub>l\\<^sub>e\\<^sub>n\\<^sub>g\\<^sub>t\\<^sub>h xs = length xs +1\"\n  by (induction xs) auto\n\ntext \\<open>Time for index access.\\<close>\n\nfun T\\<^sub>n\\<^sub>t\\<^sub>h where\n\"T\\<^sub>n\\<^sub>t\\<^sub>h [] i = 1 \"|\n\"T\\<^sub>n\\<^sub>t\\<^sub>h (x#xs) 0 = 1\"|\n\"T\\<^sub>n\\<^sub>t\\<^sub>h (x#xs) (Suc i) = 1 + T\\<^sub>n\\<^sub>t\\<^sub>h xs i\"\n\nlemma T_nth_linear: \"T\\<^sub>n\\<^sub>t\\<^sub>h xs i \\<le> length xs +1\"\n  by (induction xs i rule: T\\<^sub>n\\<^sub>t\\<^sub>h.induct) auto\n\ntext \\<open>Time for mapping two lists into one result.\\<close>\n\nfun  T\\<^sub>m\\<^sub>a\\<^sub>p\\<^sub>2 where\n \"T\\<^sub>m\\<^sub>a\\<^sub>p\\<^sub>2 t [] _ = 1\"|\n \"T\\<^sub>m\\<^sub>a\\<^sub>p\\<^sub>2 t  _ [] = 1\"|\n \"T\\<^sub>m\\<^sub>a\\<^sub>p\\<^sub>2 t (x#xs) (y#ys) = (t x y + 1 + T\\<^sub>m\\<^sub>a\\<^sub>p\\<^sub>2 t xs ys)\"\n\nlemma T_map_2_linear:\n\"c > 0 \\<Longrightarrow>\n       (\\<And> x y. t x y \\<le> c) \\<Longrightarrow> T\\<^sub>m\\<^sub>a\\<^sub>p\\<^sub>2 t xs ys \\<le> min (length xs) (length ys)  * (c+1) + 1\"\n  apply(induction t xs ys rule: T\\<^sub>m\\<^sub>a\\<^sub>p\\<^sub>2.induct)\n  subgoal by simp\n  subgoal by simp\n  subgoal for t x xs y ys\n    apply(subst  T\\<^sub>m\\<^sub>a\\<^sub>p\\<^sub>2.simps, subst length_Cons, subst length_Cons)\n    using min_add_distrib_right[of 1]\n    by (smt (z3) Suc_eq_plus1 add.assoc add.commute add_le_mono le_numeral_extra(4) min_def mult.commute mult_Suc_right)\n  done\n\nlemma T_map_2_linear':\n\"c > 0 \\<Longrightarrow>\n       (\\<And> x y. t x y = c) \\<Longrightarrow> T\\<^sub>m\\<^sub>a\\<^sub>p\\<^sub>2 t xs ys = min (length xs) (length ys)  * (c+1) + 1\"\n by(induction t xs ys rule: T\\<^sub>m\\<^sub>a\\<^sub>p\\<^sub>2.induct) simp+\n  \n\ntext \\<open>Time for append.\\<close>\n\nfun T\\<^sub>a\\<^sub>p\\<^sub>p where\n \" T\\<^sub>a\\<^sub>p\\<^sub>p  [] _ = 1\"|\n \" T\\<^sub>a\\<^sub>p\\<^sub>p  (x#xs) ys = 1 +  T\\<^sub>a\\<^sub>p\\<^sub>p  xs ys\"\n\nlemma T_app_linear: \" T\\<^sub>a\\<^sub>p\\<^sub>p xs ys = length xs +1\"\n  by(induction xs) auto\n\n\ntext \\<open>Running Time of (optimized) $FNTT$.\\<close>\n\nfun T\\<^sub>F\\<^sub>N\\<^sub>T\\<^sub>T::\"('a mod_ring) list \\<Rightarrow> nat\" where\n\"T\\<^sub>F\\<^sub>N\\<^sub>T\\<^sub>T [] = 1\"|\n\"T\\<^sub>F\\<^sub>N\\<^sub>T\\<^sub>T [a] = 1\"|\n\"T\\<^sub>F\\<^sub>N\\<^sub>T\\<^sub>T nums = (1 +T\\<^sub>l\\<^sub>e\\<^sub>n\\<^sub>g\\<^sub>t\\<^sub>h nums+ 3+\n                 \n                 (let nn = length nums;\n                  nums1 = evens_odds True nums;\n                  nums2 = evens_odds False nums\n                  in \n                  T_\\<^sub>e\\<^sub>o True nums + T_\\<^sub>e\\<^sub>o False nums + 2 +\n                 (let\n                  fntt1 = FNTT nums1;\n                  fntt2 = FNTT nums2\n                  in \n                  (T\\<^sub>F\\<^sub>N\\<^sub>T\\<^sub>T nums1) + (T\\<^sub>F\\<^sub>N\\<^sub>T\\<^sub>T nums2) +\n                 (let \n                  sum1 = map2 (+) fntt1 (map2 ( \\<lambda> x k.  x*(\\<omega>^( (n div nn) * k))) fntt2 [0..<(nn div 2)]);\n                  sum2 = map2 (-) fntt1 (map2 ( \\<lambda> x k.  x*(\\<omega>^( (n div nn) * k))) fntt2 [0..<(nn div 2)])\n                   in \n                    2* T\\<^sub>m\\<^sub>a\\<^sub>p\\<^sub>2 (\\<lambda> x y. 1) fntt2 [0..<(nn div 2)] +\n                      2* T\\<^sub>m\\<^sub>a\\<^sub>p\\<^sub>2 (\\<lambda> x y. 1) fntt1 (map2 ( \\<lambda> x k.  x*(\\<omega>^( (n div nn) * k))) fntt2 [0..<(nn div 2)]) +\n                    T\\<^sub>a\\<^sub>p\\<^sub>p sum1 sum2))))\"\n\nlemma mono:  \"((f x)::nat) \\<le> f y \\<Longrightarrow> f y \\<le> fz \\<Longrightarrow> f x \\<le> fz\" by simp\n\nlemma evens_odds_length:\n      \"length (evens_odds True xs) = (length xs+1) div 2 \\<and>\n       length (evens_odds False xs) = (length xs) div 2\"\n by(induction xs) simp+\n\ntext \\<open>Length preservation during $FNTT$.\\<close>\n\nlemma FNTT_length: \"length numbers = 2^l \\<Longrightarrow> length (FNTT numbers) = length numbers\" \nproof(induction l arbitrary: numbers)\n  case (Suc l)\n  define numbers1 where \"numbers1 = [numbers!i .  i <- (filter even [0..<length numbers])]\" \n  define numbers2 where \"numbers2 = [numbers!i .  i <- (filter odd [0..<length numbers])]\" \n  define fntt1 where \"fntt1 = FNTT numbers1\"\n  define fntt2 where \"fntt2 = FNTT numbers2\" \n  define presum where \n    \"presum = (map2 ( \\<lambda> x k.  x*(\\<omega>^( (n div (length numbers)) * k))) \n                   fntt2 [0..<((length numbers) div 2)])\" \n  define sum1 where \n    \"sum1 = map2 (+) fntt1 presum\" \n   define sum2 where  \n    \"sum2 = map2 (-) fntt1 presum\" \n  have \"length numbers1  = 2^l\" \n    by (metis Suc.prems numbers1_def diff_add_inverse2 length_even_filter mult_2 nonzero_mult_div_cancel_left power_Suc zero_neq_numeral)\n  hence \"length fntt1 = 2^l\" \n    by (simp add: Suc.IH fntt1_def)\n  hence \"length presum = 2^l\" unfolding presum_def \n    using map2_length Suc.IH Suc.prems fntt2_def length_odd_filter numbers2_def by force\n   hence \"length sum1 = 2^l\" \n    by (simp add: \\<open>length fntt1 = 2 ^ l\\<close> sum1_def)\n   have \"length numbers2 = 2^l\"\n    by (metis Suc.prems numbers2_def length_odd_filter nonzero_mult_div_cancel_left power_Suc zero_neq_numeral)\n  hence \"length fntt2 = 2^l\"\n    by (simp add: Suc.IH fntt2_def)\n  hence \"length sum2 = 2^l\" unfolding sum2_def  \n    using \\<open>length sum1 = 2 ^ l\\<close> sum1_def by force\n  hence final:\"length (sum1@sum2) = 2^(Suc l)\" \n    by (simp add: \\<open>length sum1 = 2 ^ l\\<close>)\n  obtain x y xs where xyxs_Def: \"numbers = x#y#xs\"\n    by (metis \\<open>length numbers2 = 2 ^ l\\<close> evens_odds.elims filter_compehension_evens_odds length_0_conv neq_Nil_conv numbers2_def power_eq_0_iff zero_neq_numeral)\n  show ?case \n    apply(subst xyxs_Def, subst FNTT.simps(3), subst xyxs_Def[symmetric])\n    unfolding Let_def\n    using final \n    unfolding sum1_def sum2_def presum_def fntt1_def fntt2_def numbers1_def numbers2_def\n    using Suc by (metis xyxs_Def)\nqed (metis FNTT.simps(2) Suc_length_conv length_0_conv nat_power_eq_Suc_0_iff)\n   \nlemma add_cong: \"(a1::nat) + a2+a3 +a4= b \\<Longrightarrow> a1 +a2+ c + a3+a4= c +b\"\n  by simp\n\nlemma add_mono:\"a \\<le> (b::nat) \\<Longrightarrow> c \\<le> d \\<Longrightarrow> a + c \\<le> b +d\" by simp\n\nlemma xyz: \" Suc (Suc (length xs)) = 2 ^ l \\<Longrightarrow> length (x # evens_odds True xs) = 2 ^ (l - 1)\"\n  by (metis (no_types, lifting) Nat.add_0_right Suc_eq_plus1 div2_Suc_Suc div_mult_self2 evens_odds_length length_Cons nat.distinct(1) numeral_2_eq_2 one_div_two_eq_zero plus_1_eq_Suc power_eq_if)\n\nlemma zyx:\" Suc (Suc (length xs)) = 2 ^ l  \\<Longrightarrow> length (y # evens_odds False xs) = 2 ^ (l - 1)\"\n  by (smt (z3) One_nat_def Suc_pred diff_Suc_1 div2_Suc_Suc evens_odds_length le_numeral_extra(4) length_Cons nat_less_le neq0_conv power_0 power_diff power_one_right zero_less_diff zero_neq_numeral)\n\ntext \\<open>When $length \\; xs = 2^l$, then $length \\; (evens\\text{-}odds \\; xs) = 2^{l-1}$.\\<close>\n\nlemma evens_odds_power_2:\n  fixes x::'b and y::'b\n  assumes \"Suc (Suc (length (xs::'b list))) = 2 ^ l\"\n  shows \" Suc(length (evens_odds b xs)) = 2 ^ (l-1)\"\nproof-\n  have \"Suc(length (evens_odds b xs)) = length (evens_odds b (x#y#xs))\" \n    by (metis (full_types)  evens_odds.simps(2) evens_odds.simps(3) length_Cons)\n  have \"length (x#y#xs) = 2^l\" using assms by simp\n  have \"length (evens_odds b (x#y#xs))  = 2^(l-1)\" \n    apply (cases b)\n    apply (smt (z3) Suc_eq_plus1 Suc_pred \\<open>length (x # y # xs) = 2 ^ l\\<close> add.commute add_diff_cancel_left' assms filter_compehension_evens_odds gr0I le_add1 le_imp_less_Suc length_even_filter mult_2 nat_less_le power_diff power_eq_if power_one_right zero_neq_numeral)\n    by (smt (z3) One_nat_def Suc_inject \\<open>length (x # y # xs) = 2 ^ l\\<close> assms evens_odds_length le_zero_eq nat.distinct(1) neq0_conv not_less_eq_eq pos2 power_Suc0_right power_diff_power_eq power_eq_if)\n   then show ?thesis \n    by (metis \\<open>Suc (length (evens_odds b xs)) = length (evens_odds b (x # y # xs))\\<close>)\nqed\n\ntext \\<open> \\noindent \\textbf{Major Lemma:} We rewrite the Running time of $FNTT$ in this proof and collect constraints for the time bound.\nUsing this, bounds are chosen in a way such that the induction goes through properly.\n\\paragraph \\noindent We define:\n\n\\begin{equation*}\nT(2^0) = 1\n\\end{equation*}\n\n\\begin{equation*}\nT(2^l) = \n(2^l - 1)\\cdot 14 apply+ 15 \\cdot l \\cdot 2^{l-1} + 2^l\n\\end{equation*}\n\n\\paragraph \\noindent We want to show:\n\n\\begin{equation*}\nT_{FNTT}(2^l) = T(2^l)\n\\end{equation*}\n\n(Note that by abuse of types, the $2^l$ denotes a list of length $2^l$.)\n\n\\paragraph \\noindent First, let's informally check that $T$ is indeed an accurate description of the running time:\n\n\\begin{align*}\nT_{FNTT}(2^l) & \\; =  14 + 15 \\cdot  2 ^ {l-1} + 2 \\cdot T_{FNTT}(2^{l-1}) \\hspace{1cm} \\text{by analyzing the running time function}\\\\\n&\\overset{I.H.}{=}  14 + 15 \\cdot  2 ^ {l-1} + 2 \\cdot  ((2^{l-1} - 1) \\cdot 14 + (l - 1) \\cdot 15 \\cdot 2^{l-2} + 2^{l-1})\\\\\n& \\;= 14 \\cdot 2^l - 14 + 15 \\cdot  2 ^ {l-1} + 15\\cdot l \\cdot 2^{l-1} -  15 \\cdot 2^{l-1} + 2^l\\\\\n&\\; = (2^l - 1)\\cdot 14 + 15 \\cdot l \\cdot 2^{l-1} + 2^l\\\\\n&\\overset{def.}{=} T(2^l)\n\\end{align*}\n\nThe base case is trivially true.\n\\<close>\n\ntheorem tight_bound: \n  assumes T_def: \"\\<And> numbers l. length numbers = 2^l \\<Longrightarrow> l > 0 \\<Longrightarrow>\n                               T numbers  = (2^l - 1) * 14 + l *15*2^(l-1) + 2^l\"\n                 \"\\<And> numbers l. l =0 \\<Longrightarrow> length numbers = 2^l \\<Longrightarrow> T numbers = 1\"\n  shows \" length numbers = 2^l \\<Longrightarrow> T\\<^sub>F\\<^sub>N\\<^sub>T\\<^sub>T numbers =  T numbers\"\nproof(induction numbers arbitrary: l rule: T\\<^sub>F\\<^sub>N\\<^sub>T\\<^sub>T.induct)\n  case (3 x y numbers)\n\n  text \\<open>Some definitions for making term rewriting simpler.\\<close>\n\n  define  nn where \"nn = length (x # y # numbers)\" \n  define  nums1 where \"nums1 = evens_odds True (x # y # numbers)\" \n  define  nums2 where \"nums2 = evens_odds False (x # y # numbers)\"\n  define fntt1  where \"fntt1 = local.FNTT nums1\"\n  define fntt2 where \"fntt2 = local.FNTT nums2\"\n  define sum1 where \"sum1 = map2 (+) fntt1 (map2 (\\<lambda>x y. x * \\<omega> ^ (n div nn * y)) fntt2 [0..<nn div 2])\"\n  define sum2 where \"sum2 = map2 (-) fntt1 (map2 (\\<lambda>x y. x * \\<omega> ^ (n div nn * y)) fntt2 [0..<nn div 2])\"\n\n  text \\<open>Unfolding the running time function and combining it with the definitions above.\\<close>\n\n  have TFNNT_simp: \" T\\<^sub>F\\<^sub>N\\<^sub>T\\<^sub>T (x # y # numbers) =\n                    1 + T\\<^sub>l\\<^sub>e\\<^sub>n\\<^sub>g\\<^sub>t\\<^sub>h (x # y # numbers) + 3 +  \n                    T_\\<^sub>e\\<^sub>o True (x # y # numbers) + T_\\<^sub>e\\<^sub>o False (x # y # numbers) + 2 +\n                    local.T\\<^sub>F\\<^sub>N\\<^sub>T\\<^sub>T nums1 + local.T\\<^sub>F\\<^sub>N\\<^sub>T\\<^sub>T nums2 +\n                    2 * T\\<^sub>m\\<^sub>a\\<^sub>p\\<^sub>2 (\\<lambda>x y. 1) fntt2 [0..<nn div 2] +\n                    2 *\n                    T\\<^sub>m\\<^sub>a\\<^sub>p\\<^sub>2 (\\<lambda>x y. 1) fntt1 (map2 (\\<lambda>x y. x * \\<omega> ^ (n div nn * y)) fntt2 [0..<nn div 2]) +\n                    T\\<^sub>a\\<^sub>p\\<^sub>p sum1 sum2\" \n    apply(subst  T\\<^sub>F\\<^sub>N\\<^sub>T\\<^sub>T.simps(3))\n    unfolding Let_def unfolding sum2_def sum1_def fntt1_def fntt2_def nums1_def nums2_def nn_def\n    apply simp\n    done\n\n  text \\<open>Application of lemmas related to running times of auxiliary functions.\\<close>\n\n  have length_nums1: \"length nums1 = (2::nat)^(l-1)\"\n    unfolding nums1_def\n    using evens_odds_length[of \"x # y # numbers\"] 3(3) xyz by fastforce\n have length_nums2: \"length nums2 = (2::nat)^(l-1)\"\n    unfolding nums2_def\n    using evens_odds_length[of \"x # y # numbers\"] 3(3) \n    by (metis One_nat_def le_0_eq length_Cons lessI list.size(4) neq0_conv not_add_less2 not_less_eq_eq pos2 power_Suc0_right power_diff_power_eq power_eq_if)\n  have length_simp: \"T\\<^sub>l\\<^sub>e\\<^sub>n\\<^sub>g\\<^sub>t\\<^sub>h (x # y # numbers) = (2::nat) ^l +1\"\n    using T_length_linear[of \"x#y#numbers\"]  3(3)  by simp\n  have even_odd_simp: \" T_\\<^sub>e\\<^sub>o b (x # y # numbers) = (2::nat)^l + 1\" for b\n    by (metis \"3.prems\" T_eo_linear)+\n  have 02: \"(length fntt2) =  (length [0..<nn div 2])\" unfolding fntt2_def \n    apply(subst FNTT_length[of _ \"l-1\"])\n    unfolding nums2_def\n    using length_nums2 nums2_def apply fastforce \n    by (simp add: evens_odds_length nn_def)\n  have 03: \"(length fntt1) =  (length [0..<nn div 2])\" unfolding fntt1_def \n    apply(subst FNTT_length[of _ \"l-1\"])\n    unfolding nums1_def\n    using length_nums1 nums1_def apply fastforce\n    by (metis \"02\" FNTT_length fntt2_def length_nums1 length_nums2 nums1_def)\n  have map21_simp: \"T\\<^sub>m\\<^sub>a\\<^sub>p\\<^sub>2 (\\<lambda>x y. 1) fntt2 [0..<nn div 2] = (2::nat)^l + 1\"\n    apply(subst T_map_2_linear'[of 1])\n    subgoal by simp subgoal by simp \n    by (smt (z3) \"02\" \"3\"(3) FNTT_length div_less evens_odds_length fntt2_def length_nums2 lessI less_numeral_extra(3) min.idem mult.commute nat_1_add_1 nums2_def plus_1_eq_Suc power_eq_if power_not_zero zero_power2)\n  have map22_simp: \"T\\<^sub>m\\<^sub>a\\<^sub>p\\<^sub>2 (\\<lambda>x y. 1) fntt1 (map2 (\\<lambda>x y. x * \\<omega> ^ (n div nn * y)) fntt2 [0..<nn div 2]) =\n        (2::nat)^l + 1\"\n    apply(subst T_map_2_linear'[of 1])\n    subgoal by simp subgoal by simp apply simp\n    unfolding fntt1_def fntt2_def unfolding nn_def\n    apply(subst FNTT_length[of _ \"l-1\"], (rule length_nums1)?, (rule length_nums2)?,\n                 (subst length_nums1)?,  (subst length_nums2)?,  (subst 3(3))?)+\n    apply (metis (no_types, lifting) \"3\"(3) div_less evens_odds_length length_nums2 lessI min_def mult_2 nat_1_add_1 nums2_def plus_1_eq_Suc power_eq_if power_not_zero zero_neq_numeral)\n    done\n  have sum1_simp: \"length sum1 = 2^(l-1)\"\n    unfolding sum1_def\n    apply(subst map2_length)+\n    apply(subst 02, subst 03) \n    unfolding nn_def using 3(3)\n    by (metis \"02\" FNTT_length fntt2_def length_nums2 min.idem nn_def)\n  have app_simp: \"T\\<^sub>a\\<^sub>p\\<^sub>p sum1 sum2 = (2::nat)^(l-1) + 1\"\n    by(subst T_app_linear, subst sum1_simp, simp)\n  let ?T1 = \"(2^(l-1) - 1) * 14 + (l-1) *15*2^(l-1 -1) + 2^(l-1)\"\n\n  text \\<open>Induction hypotheses\\<close>\n\n  have IH_pluged1: \"local.T\\<^sub>F\\<^sub>N\\<^sub>T\\<^sub>T nums1 = ?T1\"\n     apply(subst \"3.IH\"(1)[of nn nums1 nums2 fntt1 fntt2 \"l-1\", \n                            OF nn_def nums1_def nums2_def fntt1_def fntt2_def length_nums1])\n     apply(cases \"l \\<le> 1\")\n    subgoal\n      apply(subst T_def(2)[of \"l-1\"])\n      subgoal by simp\n       apply(rule length_nums1)\n      apply simp\n      done      \n     apply(subst T_def(1)[OF length_nums1])\n    subgoal by simp\n    subgoal by simp\n    done\n\n    have IH_pluged2: \"local.T\\<^sub>F\\<^sub>N\\<^sub>T\\<^sub>T nums2 = ?T1\"\n     apply(subst \"3.IH\"(2)[of nn nums1 _ fntt1 fntt2 \"l-1\", OF nn_def nums1_def nums2_def fntt1_def\n                           fntt2_def length_nums2 ])\n     apply(cases \"l \\<le> 1\")\n    subgoal\n      apply(subst T_def(2)[of \"l-1\"])\n      subgoal by simp\n       apply(rule length_nums2)\n      apply simp\n      done      \n     apply(subst T_def(1)[OF length_nums2])\n    subgoal by simp\n    subgoal by simp\n    done\n    \n  have \" T\\<^sub>F\\<^sub>N\\<^sub>T\\<^sub>T (x # y # numbers) =    \n        14 + (3 * 2 ^ l + (local.T\\<^sub>F\\<^sub>N\\<^sub>T\\<^sub>T nums1 +\n        (local.T\\<^sub>F\\<^sub>N\\<^sub>T\\<^sub>T nums2 + (5 * 2^(l-1) + 4 * (2 ^ l div 2)))))\"\n    apply(subst TFNNT_simp, subst map21_simp, subst map22_simp, subst  length_simp,\n          subst app_simp, subst even_odd_simp, subst even_odd_simp)\n    apply(auto simp add: algebra_simps power_eq_if[of 2 l])\n    done\n\n  text \\<open>Proof that the term $T\\text{-}def$ indeed fulfills the recursive properties, i.e.\n          $t(2^l) = 2 \\cdot t(2^{l-1}) + s$\\<close>\n\n  also have \"\\<dots> = 14 + (3 * 2 ^ l + (?T1 + (?T1 + (5 * 2^(l-1) + 4 * (2 ^ l div 2)))))\" \n    apply(subst IH_pluged1, subst IH_pluged2) \n    by simp\n  also have \"\\<dots> =  14 + (6 * 2 ^ (l-1) +\n          2*((2 ^ (l - 1) - 1) * 14 + (l - 1) * 15 * 2 ^ (l - 1 - 1) + 2 ^ (l - 1)) +\n       (5 * 2 ^ (l - 1) + 4 * (2 ^ l div 2)))\"\n    by (smt (verit) \"3\"(3) add.assoc div_less evens_odds_length left_add_twice length_nums2 lessI mult.assoc mult_2_right nat_1_add_1 numeral_Bit0 nums2_def plus_1_eq_Suc power_eq_if power_not_zero zero_neq_numeral)\n  also have \"\\<dots> =  14 +  15 * 2 ^ (l-1) +\n     2*((2 ^ (l - 1) - 1) * 14 + (l - 1) * 15 * 2 ^ (l - 1 - 1) + 2 ^ (l - 1))\" \n    by (smt (z3) \"3\"(3) add.assoc add.commute calculation diff_diff_left distrib_left div2_Suc_Suc evens_odds_length left_add_twice length_Cons length_nums2 mult.assoc mult.commute mult_2 mult_2_right numeral_Bit0 numeral_Bit1 numeral_plus_numeral nums2_def one_add_one)\n  also have \"... = 14 + 15 * 2 ^ (l-1) +\n                    (2 ^ l - 2) * 14 + (l - 1) * 15 * 2 ^ (l - 1) + 2 ^ l\"\n    apply(cases \"l > 1\")\n    apply (smt (verit, del_insts) add.assoc diff_is_0_eq distrib_left_numeral left_diff_distrib' less_imp_le_nat mult.assoc mult_2 mult_2_right nat_1_add_1 not_le not_one_le_zero power_eq_if)\n    by (smt (z3) \"3\"(3) add.commute add.right_neutral cancel_comm_monoid_add_class.diff_cancel diff_add_inverse2 diff_is_0_eq div_less_dividend evens_odds_length length_nums2 mult_2 mult_eq_0_iff nat_1_add_1 not_le nums2_def power_eq_if)\n  also have \"\\<dots> =  15 * 2 ^ (l - 1) + (2 ^ l - 1) * 14 + (l - 1) * 15 * 2 ^ (l - 1) + 2 ^ l\"\n    by (smt (z3) \"3\"(3) One_nat_def add.commute combine_common_factor diff_add_inverse2 diff_diff_left list.size(4) nat_1_add_1 nat_mult_1)\n  also have \"\\<dots> = (2^l - 1) * 14 + l *15*2^(l-1) + 2^l\" \n    apply(cases \"l > 0\")\n    subgoal using group_cancel.add1 group_cancel.add2 less_numeral_extra(3) mult.assoc mult_eq_if by auto[1]\n    using \"3\"(3) by fastforce\n\n  text \\<open>By the previous proposition, we can conclude that $T$ is indeed a suitable term for describing the running time\\<close>\n\n  finally have \"T\\<^sub>F\\<^sub>N\\<^sub>T\\<^sub>T (x # y # numbers) = T (x # y # numbers)\"\n    using T_def(1)[of \"x#y#numbers\" l] \n    by (metis \"3.prems\" bits_1_div_2 diff_is_0_eq' evens_odds_length length_nums2 neq0_conv nums2_def power_0 zero_le_one zero_neq_one)\n  thus ?case by simp\nqed (auto simp add: assms)\n\ntext \\<open>We can finally state that $FNTT$ has $\\mathcal{O}(n \\log n)$ time complexity.\\<close>\n\ntheorem log_lin_time:\n  assumes \"length numbers = 2^l\"\n  shows \"T\\<^sub>F\\<^sub>N\\<^sub>T\\<^sub>T  numbers \\<le> 30 * l * length numbers + 1\"\nproof-\n  have 00: \"T\\<^sub>F\\<^sub>N\\<^sub>T\\<^sub>T  numbers  = (2 ^ l - 1) * 14 + l * 15 * 2 ^ (l - 1) + 2 ^ l\"\n    using tight_bound[of \"\\<lambda> xs. (length xs - 1) * 14 + (Discrete.log (length xs)) * 15 * \n                            2 ^ ( (Discrete.log (length xs)) - 1) + length xs\" numbers l] \n          assms by simp\n  have \" l * 15 * 2 ^ (l - 1) \\<le> 15 * l * length numbers\" using assms by simp\n  moreover have \"(2 ^ l - 1) * 14  + 2^l\\<le> 15 * length numbers \" \n    using assms by linarith\n  moreover hence \"(2 ^ l - 1) * 14 + 2^l \\<le> 15 * l * length numbers +1\"  using assms \n    apply(cases l)\n    subgoal by simp \n    by (metis (no_types) add.commute le_add1 mult.assoc mult.commute\n          mult_le_mono nat_mult_1 plus_1_eq_Suc trans_le_add2)\n  ultimately have \" (2 ^ l - 1) * 14 + l * 15 * 2 ^ (l - 1) + 2 ^ l \\<le>  30 * l * length numbers +1\"\n    by linarith\n  then show  ?thesis using 00 by simp\nqed\n\ntheorem log_lin_time_explicitly:\n  assumes \"length numbers = 2^l\"\n  shows \"T\\<^sub>F\\<^sub>N\\<^sub>T\\<^sub>T  numbers \\<le> 30 * Discrete.log (length numbers) * length numbers + 1\"\n  using log_lin_time[of numbers l] assms by simp\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/Number_Theoretic_Transform/Butterfly.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8198933359135361, "lm_q2_score": 0.8791467785920306, "lm_q1q2_score": 0.7208065850574589}}
{"text": "chapter\\<open>Preliminaries\\<close>\ntext\\<open>In this chapter, we introduce the preliminaries, including a three-valued logic, variables,\narithmetic expressions and guard expressions.\\<close>\n\nsection\\<open>Three-Valued Logic\\<close>\n\ntext\\<open>Because our EFSMs are dynamically typed, we cannot rely on conventional Boolean logic when\nevaluating expressions. For example, we may end up in the situation where we need to evaluate\nthe guard $r_1 > 5$. This is fine if $r_1$ holds a numeric value, but if $r_1$ evaluates to a\nstring, this causes problems. We cannot simply evaluate to \\emph{false} because then the negation\nwould evaluate to \\emph{true.} Instead, we need a three-valued logic such that we can meaningfully\nevaluate nonsensical guards.\n\nThe \\texttt{trilean} datatype is used to implement three-valued Bochvar logic\n\\cite{bochvar1981}. Here we prove that the logic is an idempotent semiring, define a partial order,\nand prove some other useful lemmas.\\<close>\n\ntheory Trilean\nimports Main\nbegin\n\ndatatype trilean = true | false | invalid\n\ninstantiation trilean :: semiring begin\nfun times_trilean :: \"trilean \\<Rightarrow> trilean \\<Rightarrow> trilean\" where\n  \"times_trilean _ invalid = invalid\" |\n  \"times_trilean invalid _ = invalid\" |\n  \"times_trilean true true = true\" |\n  \"times_trilean _ false = false\" |\n  \"times_trilean false _ = false\"\n\nfun plus_trilean :: \"trilean \\<Rightarrow> trilean \\<Rightarrow> trilean\" where\n  \"plus_trilean invalid _ = invalid\" |\n  \"plus_trilean _ invalid = invalid\" |\n  \"plus_trilean true _ = true\" |\n  \"plus_trilean _ true = true\" |\n  \"plus_trilean false false = false\"\n\nabbreviation maybe_and :: \"trilean \\<Rightarrow> trilean \\<Rightarrow> trilean\" (infixl \"\\<and>?\" 70) where\n  \"maybe_and x y \\<equiv> x * y\"\n\nabbreviation maybe_or :: \"trilean \\<Rightarrow> trilean \\<Rightarrow> trilean\" (infixl \"\\<or>?\" 65) where\n  \"maybe_or x y \\<equiv> x + y\"\n\nlemma plus_trilean_assoc:\n  \"a \\<or>? b \\<or>? c = a \\<or>? (b \\<or>? c)\"\nproof(induct a b  arbitrary: c rule: plus_trilean.induct)\ncase (1 uu)\n  then show ?case\n    by simp\nnext\n  case \"2_1\"\n  then show ?case\n    by simp\nnext\n  case \"2_2\"\n  then show ?case\n    by simp\nnext\n  case \"3_1\"\n  then show ?case\n    by (metis plus_trilean.simps(2) plus_trilean.simps(4) trilean.exhaust)\nnext\n  case \"3_2\"\n  then show ?case\n    by (metis plus_trilean.simps(3) plus_trilean.simps(5) plus_trilean.simps(6) plus_trilean.simps(7) trilean.exhaust)\nnext\n  case 4\n  then show ?case\n    by (metis plus_trilean.simps(2) plus_trilean.simps(3) plus_trilean.simps(4) plus_trilean.simps(5) plus_trilean.simps(6) trilean.exhaust)\nnext\n  case 5\n  then show ?case\n    by (metis plus_trilean.simps(6) plus_trilean.simps(7) trilean.exhaust)\nqed\n\nlemma plus_trilean_commutative: \"a \\<or>? b = b \\<or>? a\"\nproof(induct a b rule: plus_trilean.induct)\n  case (1 uu)\n  then show ?case\n    by (metis plus_trilean.simps(1) plus_trilean.simps(2) plus_trilean.simps(3) trilean.exhaust)\nnext\n  case \"2_1\"\n  then show ?case\n    by simp\nnext\n  case \"2_2\"\n  then show ?case\n    by simp\nnext\n  case \"3_1\"\n  then show ?case\n    by simp\nnext\n  case \"3_2\"\n  then show ?case\n    by simp\nnext\n  case 4\n  then show ?case\n    by simp\nnext\n  case 5\n  then show ?case\n    by simp\nqed\n\nlemma times_trilean_commutative: \"a \\<and>? b = b \\<and>? a\"\n  by (metis (mono_tags) times_trilean.simps trilean.distinct(5) trilean.exhaust)\n\nlemma times_trilean_assoc:\n  \"a \\<and>? b \\<and>? c = a \\<and>? (b \\<and>? c)\"\nproof(induct a b  arbitrary: c rule: plus_trilean.induct)\n  case (1 uu)\n  then show ?case\n    by (metis (mono_tags, lifting) times_trilean.simps(1) times_trilean_commutative)\nnext\ncase \"2_1\"\n  then show ?case\n    by (metis (mono_tags, lifting) times_trilean.simps(1) times_trilean_commutative)\nnext\n  case \"2_2\"\n  then show ?case\n    by (metis (mono_tags, lifting) times_trilean.simps(1) times_trilean_commutative)\nnext\n  case \"3_1\"\n  then show ?case\n    by (metis times_trilean.simps(1) times_trilean.simps(4) times_trilean.simps(5) trilean.exhaust)\nnext\n  case \"3_2\"\n  then show ?case\n    by (metis times_trilean.simps(1) times_trilean.simps(5) times_trilean.simps(6) times_trilean.simps(7) trilean.exhaust)\nnext\n  case 4\n  then show ?case\n    by (metis times_trilean.simps(1) times_trilean.simps(4) times_trilean.simps(5) times_trilean.simps(7) trilean.exhaust)\nnext\ncase 5\n  then show ?case\n    by (metis (full_types) times_trilean.simps(1) times_trilean.simps(6) times_trilean.simps(7) trilean.exhaust)\nqed\n\nlemma trilean_distributivity_1:\n  \"(a \\<or>? b) \\<and>? c = a \\<and>? c \\<or>? b \\<and>? c\"\nproof(induct a b rule: times_trilean.induct)\ncase (1 uu)\n  then show ?case\n    by (metis (mono_tags, lifting) plus_trilean.simps(1) plus_trilean_commutative times_trilean.simps(1) times_trilean_commutative)\nnext\n  case \"2_1\"\n  then show ?case\n    by (metis (mono_tags, lifting) plus_trilean.simps(1) times_trilean.simps(1) times_trilean_commutative)\nnext\n  case \"2_2\"\n  then show ?case\n    by (metis (mono_tags, lifting) plus_trilean.simps(1) times_trilean.simps(1) times_trilean_commutative)\nnext\n  case 3\n  then show ?case\n    apply simp\n    by (metis (no_types, hide_lams) plus_trilean.simps(1) plus_trilean.simps(4) plus_trilean.simps(7) times_trilean.simps(1) times_trilean.simps(4) times_trilean.simps(5) trilean.exhaust)\nnext\n  case \"4_1\"\n  then show ?case\n    apply simp\n    by (metis (no_types, hide_lams) plus_trilean.simps(1) plus_trilean.simps(5) plus_trilean.simps(7) times_trilean.simps(1) times_trilean.simps(4) times_trilean.simps(5) times_trilean.simps(6) times_trilean.simps(7) trilean.exhaust)\nnext\n  case \"4_2\"\n  then show ?case\n    apply simp\n    by (metis (no_types, hide_lams) plus_trilean.simps(1) plus_trilean.simps(7) times_trilean.simps(1) times_trilean.simps(6) times_trilean.simps(7) trilean.exhaust)\nnext\n  case 5\n  then show ?case\n    apply simp\n    by (metis (no_types, hide_lams) plus_trilean.simps(1) plus_trilean.simps(6) plus_trilean.simps(7) times_trilean.simps(1) times_trilean.simps(4) times_trilean.simps(5) times_trilean.simps(6) times_trilean.simps(7) trilean.exhaust)\nqed\n\ninstance\n  apply standard\n      apply (simp add: plus_trilean_assoc)\n     apply (simp add: plus_trilean_commutative)\n    apply (simp add: times_trilean_assoc)\n   apply (simp add: trilean_distributivity_1)\n  using times_trilean_commutative trilean_distributivity_1 by auto\nend\n\nlemma maybe_or_idempotent: \"a \\<or>? a = a\"\n  apply (cases a)\n  by auto\n\nlemma maybe_and_idempotent: \"a \\<and>? a = a\"\n  apply (cases a)\n  by auto\n\ninstantiation trilean :: ord begin\ndefinition less_eq_trilean :: \"trilean \\<Rightarrow> trilean \\<Rightarrow> bool\" where\n  \"less_eq_trilean a b = (a + b = b)\"\n\ndefinition less_trilean :: \"trilean \\<Rightarrow> trilean \\<Rightarrow> bool\" where\n  \"less_trilean a b = (a \\<le> b \\<and> a \\<noteq> b)\"\n\ndeclare less_trilean_def less_eq_trilean_def [simp]\n\ninstance\n  by standard\nend\n\ninstantiation trilean :: uminus begin\n  fun maybe_not :: \"trilean \\<Rightarrow> trilean\" (\"\\<not>? _\" [60] 60) where\n    \"\\<not>? true = false\" |\n    \"\\<not>? false = true\" |\n    \"\\<not>? invalid = invalid\"\n\ninstance\n  by standard\nend\n\nlemma maybe_and_one: \"true \\<and>? x = x\"\n  by (cases x, auto)\n\nlemma maybe_or_zero: \"false \\<or>? x = x\"\n  by (cases x, auto)\n\nlemma maybe_double_negation: \"\\<not>? \\<not>? x = x\"\n  by (cases x, auto)\n\nlemma maybe_negate_true: \"(\\<not>? x = true) = (x = false)\"\n  by (cases x, auto)\n\nlemma maybe_negate_false: \"(\\<not>? x = false) = (x = true)\"\n  by (cases x, auto)\n\nlemma maybe_and_true: \"(x \\<and>? y = true) = (x = true \\<and> y = true)\"\n  using times_trilean.elims by blast\n\nlemma maybe_and_not_true:\n  \"(x \\<and>? y \\<noteq> true) = (x \\<noteq> true \\<or> y \\<noteq> true)\"\n  by (simp add: maybe_and_true)\n\nlemma negate_valid: \"(\\<not>? x \\<noteq> invalid) = (x \\<noteq> invalid)\"\n  by (metis maybe_double_negation maybe_not.simps(3))\n\nlemma maybe_and_valid:\n  \"x \\<and>? y \\<noteq> invalid \\<Longrightarrow> x \\<noteq> invalid \\<and> y \\<noteq> invalid\"\n  using times_trilean.elims by blast\n\nlemma maybe_or_valid:\n  \"x \\<or>? y \\<noteq> invalid \\<Longrightarrow> x \\<noteq> invalid \\<and> y \\<noteq> invalid\"\n  using plus_trilean.elims by blast\n\nlemma maybe_or_false:\n  \"(x \\<or>? y = false) = (x = false \\<and> y = false)\"\n  using plus_trilean.elims by blast\n\nlemma maybe_or_true:\n  \"(x \\<or>? y = true) = ((x = true \\<or> y = true) \\<and> x \\<noteq> invalid \\<and> y \\<noteq> invalid)\"\n  using plus_trilean.elims by blast\n\nlemma maybe_not_invalid: \"(\\<not>? x = invalid) = (x = invalid)\"\n  by (metis maybe_double_negation maybe_not.simps(3))\n\nlemma maybe_or_invalid:\n  \"(x \\<or>? y = invalid) = (x = invalid \\<or> y = invalid)\"\n  using plus_trilean.elims by blast\n\nlemma maybe_and_invalid:\n  \"(x \\<and>? y = invalid) = (x = invalid \\<or> y = invalid)\"\n  using times_trilean.elims by blast\n\nlemma maybe_and_false:\n  \"(x \\<and>? y = false) = ((x = false \\<or> y = false) \\<and> x \\<noteq> invalid \\<and> y \\<noteq> invalid)\"\n  using times_trilean.elims by blast\n\nlemma invalid_maybe_and: \"invalid \\<and>? x = invalid\"\n  using maybe_and_valid by blast\n\nlemma maybe_not_eq: \"(\\<not>? x = \\<not>? y) = (x = y)\"\n  by (metis maybe_double_negation)\n\nlemma de_morgans_1:\n  \"\\<not>? (a \\<or>? b) = (\\<not>?a) \\<and>? (\\<not>?b)\"\n  by (metis (no_types, hide_lams) add.commute invalid_maybe_and maybe_and_idempotent maybe_and_one maybe_not.elims maybe_not.simps(1) maybe_not.simps(3) maybe_not_invalid maybe_or_zero plus_trilean.simps(1) plus_trilean.simps(4) times_trilean.simps(1) times_trilean_commutative trilean.exhaust trilean.simps(6))\n\nlemma de_morgans_2:\n  \"\\<not>? (a \\<and>? b) = (\\<not>?a) \\<or>? (\\<not>?b)\"\n  by (metis de_morgans_1 maybe_double_negation)\n\nlemma not_true: \"(x \\<noteq> true) = (x = false \\<or> x = invalid)\"\n  by (metis (no_types, lifting) maybe_not.cases trilean.distinct(1) trilean.distinct(3))\n\nlemma pull_negation: \"(x = \\<not>? y) = (\\<not>? x = y)\"\n  using maybe_double_negation by auto\n\nlemma comp_fun_commute_maybe_or: \"comp_fun_commute maybe_or\"\n  apply standard\n  apply (simp add: comp_def)\n  apply (rule ext)\n  by (simp add: add.left_commute)\n\nlemma comp_fun_commute_maybe_and: \"comp_fun_commute maybe_and\"\n  apply standard\n  apply (simp add: comp_def)\n  apply (rule ext)\n  by (metis add.left_commute de_morgans_2 maybe_not_eq)\n\nend\n", "meta": {"author": "jmafoster1", "repo": "efsm-isabelle", "sha": "fde322562b98c9b4618c112e36a6ac5b9a056610", "save_path": "github-repos/isabelle/jmafoster1-efsm-isabelle", "path": "github-repos/isabelle/jmafoster1-efsm-isabelle/efsm-isabelle-fde322562b98c9b4618c112e36a6ac5b9a056610/Trilean.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467675095292, "lm_q2_score": 0.8198933381139645, "lm_q1q2_score": 0.7208065779054894}}
{"text": "theory Predictive imports Main begin\n  section{*Languages as predicates on lists*}\n\n  text{*In this formalization we use lists of some type variable \"'a\" to model\n    words over \"'a\"*}\n\n  text{*Syntax for the lattice operations:*}\n\n  notation\n    bot (\"\\<bottom>\") and\n    top (\"\\<top>\") and\n    inf (infixl \"\\<sqinter>\" 70) and\n    sup (infixl \"\\<squnion>\" 65)\n\n  text{*We introduce the prefix relation on lists as an instantiation of\n    a partial order relation. The fact that $x$ is a prefix of a list $y$\n    is denoted by $x \\le y$. We prove that the prefix relation is a partial\n    order, and we also prove some additional properties*}\n\n  instantiation \"list\" :: (type) order begin\n    primrec less_eq_list where\n      \"([] \\<le> x) = True\" |\n      \"((a # x) \\<le> y) = (case y of [] \\<Rightarrow> False | b # z \\<Rightarrow> a = b \\<and> (x \\<le> z))\"\n\n    definition less_list_def: \"((x::'a list) < y) = (x \\<le> y \\<and> \\<not> y \\<le> x)\"\n\n    \n\n    lemma prefix_antisym: \"\\<And>y . (x::'a list) \\<le> y \\<Longrightarrow> y \\<le> x \\<Longrightarrow> x = y\"\n      apply (induction x)\n        apply (case_tac y, simp_all)\n        by (case_tac y, simp_all)\n\n    lemma prefix_trans: \"\\<And>y z . (x::'a list) \\<le> y \\<Longrightarrow> y \\<le> z \\<Longrightarrow> x \\<le> z\"\n      apply (induction x, simp_all)\n        apply (case_tac y, simp_all)\n        by (case_tac z, simp_all, auto)\n\n    lemma [simp]: \"(y \\<le> []) = (y = [])\"\n      by (unfold less_eq_list_def, case_tac y, auto)\n\n    lemma [simp]: \"[] \\<le> ax\"\n      by (simp add: less_eq_list_def)\n\n    lemma prefix_concat: \"\\<And> x . x \\<le> y = (\\<exists> z . y = x @ z)\"\n      by (induction y, simp_all, case_tac x, auto)\n\n    lemma [simp]: \"(butlast x) \\<le> x\"\n      by (induction x, simp_all)\n\n    lemma prefix_butlast: \"\\<And> y . (x \\<le> y) = (x = y \\<or> x \\<le> (butlast y))\"\n      proof (induction x)\n        case Nil show ?case by simp\n        case (Cons x xs)\n          assume A: \"\\<And> y . (xs \\<le> y) = (xs = y \\<or> xs \\<le> (butlast y))\"\n          show ?case\n            apply simp\n            apply (case_tac y, simp_all)\n            apply safe\n            apply simp_all\n            apply (subst (asm) A, simp)\n            by (subst A, simp)\n      qed\n\n    lemma [simp]: \"(x @ y \\<le> x) = (y = [])\"\n      by (induction x, simp_all)\n\n    instance proof\n      qed (simp_all add: less_list_def prefix_antisym, rule prefix_trans)\n  end\n\n  section{*Finite deterministic automata*}\n\n  text{*A finite deterministic automaton is modeled as a record of a transition \n    function $\\delta:'s \\to 'a \\to 's$ and a set $Final : 's set$ of final states, \n    and an initial state $s_0:'s$. The states of the automaton are from the type \n    variable $'s$, and the letters of the alphabet from $'a$.*}\n\n  record ('s, 'a) automaton = \n       \\<delta> :: \"'s \\<Rightarrow> 'a \\<Rightarrow> 's\"\n       Final :: \"'s set\"\n       s\\<^sub>0 :: 's\n\n  text{*The language of an automaton $A$ is a predicate on lists of letters, and\n   it is defined by primitive recursion:*}\n\n  primrec lang:: \"('s, 'a, 'c) automaton_ext \\<Rightarrow> 'a list \\<Rightarrow> bool\" where\n    \"lang A [] = ((s\\<^sub>0 A) \\<in> (Final A))\" |\n    \"lang A (a # x) = lang (A\\<lparr>s\\<^sub>0 := \\<delta> A (s\\<^sub>0 A) a\\<rparr>) x\"\n\n  text{*We extend the transition function $\\delta$ from letters to lists of letters,\n    also by primitive induction*}\n\n  primrec \\<delta>e:: \"('s, 'a, 'b) automaton_ext \\<Rightarrow> 'a list \\<Rightarrow> 's\" where\n    \"\\<delta>e A [] = s\\<^sub>0 A\" |\n    \"\\<delta>e A (a # x) = \\<delta>e (A\\<lparr>s\\<^sub>0:=\\<delta> A (s\\<^sub>0 A) a\\<rparr>) x\"\n\n  text{*Next two lemma connect the language definition to the extended transition function.*}\n\n  lemma lang_deltae: \"\\<And> A . lang A x = ((\\<delta>e A x) \\<in> Final A)\"\n    by (induction x, simp_all)\n\n  lemma lang_deltaeb: \"\\<And> y A . lang A (x @ y) = lang (A\\<lparr>s\\<^sub>0:= (\\<delta>e A x)\\<rparr>) y\"\n    by (induction x, simp_all)\n\n  lemma delta_but_last_aux: \"\\<And> a s . \\<delta>e (A\\<lparr>s\\<^sub>0:=s\\<rparr>) (x @ [a]) = \\<delta> A (\\<delta>e (A\\<lparr>s\\<^sub>0:=s\\<rparr>) x) a\"\n    apply (induction x)\n    by simp_all\n    \n  lemma delta_but_last: \"\\<delta>e A (x @ [a]) = \\<delta> A (\\<delta>e A x) a\"\n    apply (cut_tac A = A and s = \"s\\<^sub>0 A\" and x = x and a = a in delta_but_last_aux)\n    by simp\n\n  text{*We introduce the standard product construction of two automata. Here we construct the\n    product corresponding the intersection of the languages of the two automata.*}\n\n  definition product :: \"('s, 'a, 'c) automaton_ext \\<Rightarrow> ('t, 'a, 'c) automaton_ext \n        \\<Rightarrow> ('s \\<times> 't, 'a, 'c) automaton_ext\" (infix \"**\" 60) where\n    \"A ** B = \\<lparr> \n        \\<delta> = (\\<lambda> (s, t) a . (\\<delta> A s a, \\<delta> B t a)), \n        Final = Final A \\<times> Final B, \n        s\\<^sub>0 = (s\\<^sub>0 A,  s\\<^sub>0 B),\n        \\<dots> = automaton.more A\\<rparr>\"\n\n  text{*Next five lemmas are straightforward properties of the product of two automata.*}\n\n  lemma [simp]: \"s\\<^sub>0 (A ** B) = (s\\<^sub>0 A, s\\<^sub>0 B)\"\n    by (simp add: product_def)\n\n  lemma [simp]: \"Final (A ** B) = (Final A \\<times> Final B)\"\n    by (simp add: product_def)\n\n  lemma [simp]: \"(A ** B)\\<lparr>s\\<^sub>0 := (s, t) \\<rparr> = (A\\<lparr>s\\<^sub>0 := s\\<rparr>) ** (B\\<lparr>s\\<^sub>0 := t\\<rparr> )\"\n    by (simp add: product_def)\n\n  lemma [simp]: \"\\<delta> (A ** B) (s, t) a = (\\<delta> A s a, \\<delta> B t a)\"\n    by (simp add: product_def)\n\n  lemma [simp]: \"\\<And> A B . \\<delta>e (A ** B) x = (\\<delta>e A x, \\<delta>e B x)\"\n    by (induction x, simp_all)\n\n\n  text{*Next two lemmas show that the language of the product is the intersection of the \n    languages of the automata. Second lemma is the point-free version of the first lemma.*}\n\n  lemma intersection_aux: \"\\<And> A B . lang (A ** B) x =  (lang A x \\<and> lang B x)\"\n    apply (induction x)\n    by (auto simp add:  lang_deltae)\n\n  lemma intersection: \"lang (A ** B) =  (lang A \\<sqinter> lang B)\"\n    by (simp add: fun_eq_iff intersection_aux)\n\n  text{*Next declaration introduces the complement of an automaton as a instantiation\n   of the Isabelle uminus class. We take this approach because we what to use the \n   unary symbol $-$ for the complement. Otherwise this is just a simple definition\n   similar to the product.*}\n\n  instantiation automaton_ext :: (type, type, type) uminus begin\n    definition complement_def: \"- A = A\\<lparr>Final := -Final A\\<rparr>\"\n    instance proof qed\n  end\n\n  text{*Next five lemmas give some properties of the complement.*}\n  lemma [simp]: \"\\<delta> (-A) = \\<delta> A\"\n    by (simp add: complement_def)\n\n  lemma [simp]: \"s\\<^sub>0 (-A) = s\\<^sub>0 A\"\n    by (simp add: complement_def)\n\n  lemma complement_init[simp]: \"(-A)\\<lparr> s\\<^sub>0 := s \\<rparr> = -(A\\<lparr> s\\<^sub>0 := s \\<rparr>)\"\n    by (simp add: complement_def)\n\n  lemma [simp]: \"\\<And> A . \\<delta>e (-A) x = \\<delta>e A x\"\n    by (induction x, simp_all)\n\n  lemma [simp]: \"Final (-A) = - Final A\"\n    by (simp add: complement_def)\n\n  text{*The language of the complement of $A$ is the complement of the \n    language of $A$. Next two lemmas express this property in point-wise\n    and point-free manner.*}\n\n  lemma complement_aux: \"\\<And>A . lang (- A) x = (\\<not> (lang A x))\"\n    by (simp add: lang_deltae)\n\n  lemma complement: \"lang (-A) = (- (lang A))\"\n    by (simp add: fun_eq_iff complement_aux)\n\n  text{*Next definition introduces an automaton $Extension\\ A$ based on automaton $A$.\n    A list $x$ is in the language of $Extension\\ A$ if and only if there is a prefix\n    of $x$ in the language of $A$. In the paper this automaton is denoted by \n    $B_\\varphi$, where $\\varphi = lang\\ A$.*}\n\n  definition \"Extension A = \\<lparr>\n    \\<delta> = (\\<lambda> s a . if s \\<in> Final A then s else \\<delta> A s a),\n    Final = Final A,\n    s\\<^sub>0 = s\\<^sub>0 A, \n    \\<dots> = more A\\<rparr>\"\n\n  lemma [simp]: \"s\\<^sub>0 (Extension A) = s\\<^sub>0 A\"\n    by (simp add: Extension_def)\n\n  text{*We introduce some properties of $Extension\\ A$ in the next six lemmas.*}\n\n  lemma Extension_initial[simp]: \"Extension A\\<lparr>s\\<^sub>0 := s\\<rparr> = Extension (A\\<lparr>s\\<^sub>0 := s\\<rparr>)\"\n    by (auto simp add: Extension_def fun_eq_iff)\n\n  lemma prefix_final[simp]: \"s \\<in> Final A \\<Longrightarrow> lang ((Extension A)\\<lparr>s\\<^sub>0 := s\\<rparr>) x\"\n    by (induction x, simp_all add: Extension_def)\n\n  lemma [simp]: \"s\\<^sub>0 A \\<in> Final A \\<Longrightarrow> lang (Extension A) x\"\n    by (drule prefix_final, simp)\n\n  lemma [simp]: \"s \\<in> Final A \\<Longrightarrow> \\<delta> (Extension A) s a = s\"\n    by (simp add: Extension_def)\n\n  lemma [simp]: \"s \\<notin> Final A \\<Longrightarrow> \\<delta> (Extension A) s a = \\<delta> A s a\"\n    by (simp add: Extension_def)\n\n  lemma \"lang ((Extension A)\\<lparr>s\\<^sub>0 := s\\<rparr>) = \\<top> \\<Longrightarrow> s \\<in> Final A\"\n    apply (simp add: fun_eq_iff Extension_def image_def)\n    by (drule_tac x = \"[]\" in spec, simp)\n\n  text{*The language of $Extension\\ A$ in terms of the language of $A$ is given by\n    the next lemma.*}\n\n  lemma Extension_lang: \"\\<And> (A::('s, 'a, 'c) automaton_ext) . lang (Extension A) x = (\\<exists> y . lang A y \\<and> y \\<le> x)\"\n    proof (induction x)\n    case (Nil) show ?case\n      by (simp add: Extension_def image_def)\n    next\n    case (Cons a x)\n      assume A: \"\\<And> (A::('s, 'a, 'c) automaton_ext) .  lang (Extension A) x = (\\<exists>y. lang A y \\<and> y \\<le> x)\"\n      from A have B: \"\\<And> (A::('s, 'a, 'c) automaton_ext) y . lang A y \\<Longrightarrow> y \\<le> x \\<Longrightarrow> lang (Extension A) x\"\n        by blast \n      show ?case\n        apply simp\n        apply safe\n          apply (case_tac \"s\\<^sub>0 A \\<in>  Final A\", simp_all)\n          apply (rule_tac x = \"[]\" in exI, simp)\n          apply (simp add: A, safe)\n          apply (rule_tac x = \"a # y\" in exI)\n        \n          apply simp\n          apply (case_tac y, simp_all, safe)\n          apply (case_tac \"s\\<^sub>0 A \\<in>  Final A\", simp_all)\n          by (drule B, simp_all)\n    qed\n\n  section{*Constraints of the Predictive Enforcement*}\n\n  text{*Next definition introduces $k_{\\psi,\\varphi}$ function from the paper \n    \\cite{predictive}. The automata $A_\\psi$ and $A_\\varphi$ correspond to the properties \n    $\\psi$ and $\\varphi$, respectively.*}\n\n  definition \"kfunc A\\<^sub>\\<psi> A\\<^sub>\\<phi> x = (\\<forall> y . lang A\\<^sub>\\<psi> (x @ y) \\<longrightarrow> (\\<exists> z .(lang A\\<^sub>\\<phi> (x @ z)) \\<and> z \\<le> y))\"\n\n  text{*The Urgency constraint is introduced in the next definition, and it has as hypothesis\n    the $kfunc$ function. For simplicity we introduce first $kfunc$ and then Urgency. In the\n    paper Urgency precedes the definition of $kfunc$.*}\n\n  definition \"Urgency A\\<^sub>\\<psi> A\\<^sub>\\<phi> Enf = (\\<forall> x . kfunc A\\<^sub>\\<psi> A\\<^sub>\\<phi> x \\<longrightarrow> Enf x = x)\"\n\n  definition \"Soundness A\\<^sub>\\<psi> A\\<^sub>\\<phi> Enf = (\\<forall> x . lang A\\<^sub>\\<psi> x \\<and> Enf x \\<noteq> [] \\<longrightarrow> lang A\\<^sub>\\<phi> (Enf x))\"\n\n  definition \"Transparency1 Enf = (\\<forall> x . Enf x \\<le> x)\"\n\n  definition \"Transparency2 A\\<^sub>\\<phi> Enf = (\\<forall> x . lang A\\<^sub>\\<phi> x \\<longrightarrow> Enf x = x)\"\n\n  definition [simp]: \"Monotonicity Enf = mono Enf\"\n\n  text{*Next lemma shows that Transparency2 is a consequence of Urgency*}\n\n  lemma \"Urgency A\\<^sub>\\<psi> A\\<^sub>\\<phi> Enf \\<Longrightarrow> Transparency2 A\\<^sub>\\<phi> Enf\"\n    by (metis Transparency2_def Urgency_def append_Nil2 kfunc_def less_eq_list.simps(1))\n\n  section{*Independence of Urgency, Transparency1, Monotonicity and Soundness*}\n\n  lemma Urgency_true [simp]: \"lang A\\<^sub>\\<psi> = \\<top> \\<Longrightarrow> lang  A\\<^sub>\\<phi> = \\<bottom> \\<Longrightarrow> Urgency A\\<^sub>\\<psi> A\\<^sub>\\<phi> Enf\"\n    by (simp add: Urgency_def kfunc_def)\n\n  lemma Urgency_phi[simp]: \"lang A\\<^sub>\\<psi> = \\<top> \\<Longrightarrow> lang A\\<^sub>\\<phi> = B \\<Longrightarrow> Urgency A\\<^sub>\\<psi> A\\<^sub>\\<phi> Enf = (\\<forall> x . B x \\<longrightarrow> Enf x = x)\"\n    apply (simp add: kfunc_def Urgency_def, auto)\n    apply (drule_tac x = x in spec, safe)\n    apply (rule_tac x = \"[]\" in exI, simp)\n    apply (drule_tac x = x in spec)\n    by (drule_tac x = \"[]\" in spec, simp)\n\n  lemma Urgency_id [simp]: \"lang A\\<^sub>\\<psi> = \\<top> \\<Longrightarrow> lang  A\\<^sub>\\<phi> = \\<top> \\<Longrightarrow> (Urgency A\\<^sub>\\<psi> A\\<^sub>\\<phi> Enf) = (Enf = id)\"\n    by (simp add: Urgency_def kfunc_def fun_eq_iff, auto)\n\n  lemma Indep1: \"lang A\\<^sub>\\<psi> = \\<top> \\<Longrightarrow> lang A\\<^sub>\\<phi> = \\<bottom> \\<Longrightarrow> (\\<forall> x . Enf x = x) \\<Longrightarrow> \n     Urgency A\\<^sub>\\<psi> A\\<^sub>\\<phi> Enf \\<and> Monotonicity Enf \\<and> Transparency1 Enf \\<and> \\<not> Soundness  A\\<^sub>\\<psi> A\\<^sub>\\<phi> Enf\"\n     by (simp add: Soundness_def mono_def Transparency1_def, auto)\n\n  lemma Indep1a: \"lang A\\<^sub>\\<psi> = \\<top> \\<Longrightarrow> lang A\\<^sub>\\<phi> = (\\<lambda> x . x = [()]) \\<Longrightarrow> (\\<forall> x . Enf x = x) \\<Longrightarrow> \n     Urgency A\\<^sub>\\<psi> A\\<^sub>\\<phi> Enf \\<and> Monotonicity Enf \\<and> Transparency1 Enf \\<and> \\<not> Soundness  A\\<^sub>\\<psi> A\\<^sub>\\<phi> Enf\"\n     by (simp add: Soundness_def mono_def Transparency1_def, auto)\n\n  lemma Indep2: \"lang A\\<^sub>\\<psi> = \\<top> \\<Longrightarrow> lang  A\\<^sub>\\<phi> = (\\<lambda> x . x = [()]) \\<Longrightarrow> (\\<forall> x . Enf x = [()]) \\<Longrightarrow> \n     Urgency A\\<^sub>\\<psi> A\\<^sub>\\<phi> Enf \\<and> Monotonicity Enf \\<and> \\<not> Transparency1 Enf \\<and> Soundness  A\\<^sub>\\<psi> A\\<^sub>\\<phi> Enf\"\n     apply (simp add: Soundness_def mono_def Transparency1_def)\n     by (rule_tac x = \"[]\" in exI, simp)\n\n  lemma Indep3: \"lang A\\<^sub>\\<psi> = \\<top> \\<Longrightarrow> lang  A\\<^sub>\\<phi> = (\\<lambda> x . x = [()]) \\<Longrightarrow> (\\<forall> x . Enf x = (if x = [()] then [()] else [])) \\<Longrightarrow> \n     Urgency A\\<^sub>\\<psi> A\\<^sub>\\<phi> Enf \\<and> \\<not> Monotonicity Enf \\<and> Transparency1 Enf \\<and> Soundness  A\\<^sub>\\<psi> A\\<^sub>\\<phi> Enf\"\n     apply (simp add: Soundness_def mono_def Transparency1_def)\n     by (rule_tac x = \"[(),()]\" in exI, simp)\n\n  lemma Indep4: \"lang A\\<^sub>\\<psi> = \\<top> \\<Longrightarrow> lang  A\\<^sub>\\<phi> = \\<top> \\<Longrightarrow> (\\<forall> x . Enf x = []) \\<Longrightarrow> \n     \\<not> Urgency A\\<^sub>\\<psi> A\\<^sub>\\<phi> Enf \\<and> Monotonicity Enf \\<and> Transparency1 Enf \\<and> Soundness  A\\<^sub>\\<psi> A\\<^sub>\\<phi> Enf\"\n     apply (simp add: Soundness_def mono_def Transparency1_def)\n     by (rule_tac x = \"[Eps \\<top>]\" in exI, simp)\n\n  section{*Alternative Urgency*}\n\n  text{*A weaker version of Urgency is introduced by:*}\n  definition \"Urgency' A\\<^sub>\\<psi> A\\<^sub>\\<phi> Enf = (\\<forall> x . (\\<forall> y . lang A\\<^sub>\\<psi> (x @ y) \\<longrightarrow> lang A\\<^sub>\\<phi> x) \\<longrightarrow> Enf x = x)\"\n\n  lemma Urgency_Urgency'_aux: \"(\\<forall> y . lang A\\<^sub>\\<psi> (x @ y) \\<longrightarrow> lang A\\<^sub>\\<phi> x) \\<Longrightarrow> kfunc A\\<^sub>\\<psi> A\\<^sub>\\<phi> x\"\n    by (metis kfunc_def append_Nil2 less_eq_list.simps(1))\n\n  text{*Urgency is stronger than Urgency'*}\n\n  lemma Urgency_Urgency': \"Urgency A\\<^sub>\\<psi> A\\<^sub>\\<phi> Enf \\<Longrightarrow> Urgency'  A\\<^sub>\\<psi> A\\<^sub>\\<phi> Enf\"\n    by (metis Urgency'_def Urgency_def kfunc_def append_Nil2 less_eq_list.simps(1))\n\n  section{*Implementation of $kfunc$ as the inclusion of two regular languages*}\n\n  text{*Next definition is a more abstract variant of $kfunc$ as an inclusion of regular\n    languages. Here we do not have the existential quantifier.*}\n  definition \"kfunc_lang A\\<^sub>\\<psi> A\\<^sub>\\<phi> x = (lang (A\\<^sub>\\<psi>\\<lparr>s\\<^sub>0 := (\\<delta>e A\\<^sub>\\<psi> x)\\<rparr>) \\<le> lang ((Extension A\\<^sub>\\<phi>)\\<lparr> s\\<^sub>0 := \\<delta>e A\\<^sub>\\<phi> x \\<rparr>))\"\n\n  lemma kfunc_kfunc_lang: \"kfunc A\\<^sub>\\<psi> A\\<^sub>\\<phi> x = kfunc_lang A\\<^sub>\\<psi> A\\<^sub>\\<phi> x\"\n    by (simp add: kfunc_def kfunc_lang_def lang_deltaeb Predictive.Extension_lang le_fun_def) \n\n  lemma kfunc_lang_empty: \" kfunc_lang A\\<^sub>\\<psi> A\\<^sub>\\<phi> x = (lang ((A\\<^sub>\\<psi> ** - (Extension A\\<^sub>\\<phi>))\\<lparr>s\\<^sub>0 := (\\<delta>e A\\<^sub>\\<psi> x, \\<delta>e A\\<^sub>\\<phi> x)\\<rparr>) = \\<bottom>)\"\n    by (simp add: intersection Predictive.complement kfunc_lang_def fun_eq_iff le_fun_def)\n\n\n  text{*Next theorem shows the implementation of $kfunc$ as a test of emptiness of a regular language\n    (Theorem 2 in \\cite{predictive}).*}\n\n  theorem kfunc_empty: \"kfunc A\\<^sub>\\<psi> A\\<^sub>\\<phi> x = (lang ((A\\<^sub>\\<psi> ** - (Extension A\\<^sub>\\<phi>))\\<lparr>s\\<^sub>0 := (\\<delta>e A\\<^sub>\\<psi> x, \\<delta>e A\\<^sub>\\<phi> x)\\<rparr>) = \\<bottom>)\"\n    by (unfold kfunc_kfunc_lang kfunc_lang_empty, simp)\n\n  section{*Enforcement Function*}\n\n  text{*Next definition introduces the enforcement function. In this formalization we chose\n    to define $enforce$ directly while in \\cite{predictive} we define it using another function\n    called $store$ that returns two sequences. The $enforce$ function is the first component\n    of $store$.*}\n\n  fun enforce :: \"('s, 'a, 'c) automaton_ext \\<Rightarrow> ('t, 'a, 'c) automaton_ext \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where\n    \"enforce A\\<^sub>\\<psi> A\\<^sub>\\<phi> x = \n      (if x = [] then \n        [] \n      else \n        (if kfunc A\\<^sub>\\<psi> A\\<^sub>\\<phi> x then \n          x \n        else \n          enforce A\\<^sub>\\<psi> A\\<^sub>\\<phi> (butlast x)))\"\n\n(*\n  definition  enforce_nat :: \"(nat, nat, nat) automaton_ext \\<Rightarrow> (nat, nat, nat) automaton_ext \\<Rightarrow> nat list \\<Rightarrow> nat list\" where\n    \"enforce_nat = enforce\"\n\n  export_code enforce_nat in SML\n    module_name Example file \"example.ML\"\n\n  export_code enforce_nat in Scala\n    module_name Example file \"example.scala\"\n\n  export_code enforce_nat in OCaml\n    module_name Example file \"example.ocaml\"\n*)\n\n  text{*When the property $\\psi$ is true for all sequences, then the Urgency property\n    is simplified to the non-predictive case.*}\n\n  lemma no_prediction: \"lang A\\<^sub>\\<psi> = \\<top> \\<Longrightarrow> Urgency A\\<^sub>\\<psi> A\\<^sub>\\<phi> Enf = (\\<forall>x. lang A\\<^sub>\\<phi> x \\<longrightarrow> Enf x = x)\"\n    apply (auto simp add: Urgency_def kfunc_def)\n    apply (metis append_Nil2 less_eq_list.simps(1))\n    by (metis list.simps(4) neq_Nil_conv less_eq_list.simps(2) self_append_conv)\n\n  text{*When the property $\\psi$ is included in $\\varphi$, then output of the\n    enforcer is always equal to the input.*}\n\n  lemma subset_enforce: \"lang A\\<^sub>\\<psi> \\<le> lang A\\<^sub>\\<phi> \\<Longrightarrow> enforce A\\<^sub>\\<psi> A\\<^sub>\\<phi> x = x\"\n    by (metis enforce.simps kfunc_def order_refl predicate1D)\n\n  text{*When the property $\\psi$ is true for all sequences, then the kfun\n    is simplified to:*}\n\n  lemma no_prediction_kfunc: \"lang A\\<^sub>\\<psi> = \\<top> \\<Longrightarrow> kfunc A\\<^sub>\\<psi> A\\<^sub>\\<phi> x = lang A\\<^sub>\\<phi> x\"\n    apply (auto simp add: kfunc_def)\n    using less_eq_list.simps(1) prefix_antisym apply fastforce\n    by (metis append_Nil2 less_eq_list.simps(1))\n\n  text{*Next three lemmas are used in the proofs of soundness,  transparency, and urgency.*}\n\n  lemma kfunc_enforce: \"enforce A\\<^sub>\\<psi> A\\<^sub>\\<phi> x \\<noteq> [] \\<Longrightarrow> kfunc A\\<^sub>\\<psi> A\\<^sub>\\<phi> (enforce A\\<^sub>\\<psi> A\\<^sub>\\<phi> x)\"\n    proof (induction x rule: length_induct)\n      fix xs::\"'a list\"\n      assume \"\\<forall>ys. length ys < length xs \\<longrightarrow> enforce A\\<^sub>\\<psi> A\\<^sub>\\<phi> ys \\<noteq> [] \\<longrightarrow> kfunc A\\<^sub>\\<psi> A\\<^sub>\\<phi> (enforce A\\<^sub>\\<psi> A\\<^sub>\\<phi> ys)\"\n      from this have A: \"\\<And> ys . length ys < length xs \\<Longrightarrow> enforce A\\<^sub>\\<psi> A\\<^sub>\\<phi> ys \\<noteq> [] \\<Longrightarrow> kfunc A\\<^sub>\\<psi> A\\<^sub>\\<phi> (enforce A\\<^sub>\\<psi> A\\<^sub>\\<phi> ys)\"\n        by simp\n      assume C: \"enforce A\\<^sub>\\<psi> A\\<^sub>\\<phi> xs \\<noteq> []\"\n      from this have B: \"xs \\<noteq> []\"\n        by (case_tac xs, simp_all)\n      from B and C have  D: \"\\<not> kfunc A\\<^sub>\\<psi> A\\<^sub>\\<phi> xs \\<Longrightarrow> enforce A\\<^sub>\\<psi> A\\<^sub>\\<phi> (butlast xs) \\<noteq> []\"\n        apply (subst enforce.simps)\n        apply (subst (asm) enforce.simps)\n        apply (subst (asm) enforce.simps)\n        by (simp del: enforce.simps)\n      from B and D show \"kfunc A\\<^sub>\\<psi> A\\<^sub>\\<phi> (enforce A\\<^sub>\\<psi> A\\<^sub>\\<phi> xs)\"\n        apply (subst enforce.simps)\n        apply (simp del: enforce.simps, safe)\n        by (cut_tac ys = \"butlast xs\" in A, simp_all del: enforce.simps)\n    qed\n        \n  lemma kfunc_prefix_enforce: \"kfunc A\\<^sub>\\<psi> A\\<^sub>\\<phi> y \\<Longrightarrow> y \\<le> x \\<Longrightarrow> y \\<le> (enforce A\\<^sub>\\<psi> A\\<^sub>\\<phi> x)\"\n    apply (induction x rule: length_induct)\n    apply (subst enforce.simps)\n    apply (case_tac \"xs = []\")\n    apply simp\n    apply (simp del: enforce.simps, safe)\n    apply (drule_tac x = \"butlast xs\" in spec, safe)\n    apply (simp_all del: enforce.simps)\n    by (subst (asm) prefix_butlast, simp)\n\n  lemma lang_enf_kfunc: \"lang A\\<^sub>\\<phi> x \\<Longrightarrow> kfunc A\\<^sub>\\<psi> A\\<^sub>\\<phi> x\"\n    apply (simp add: kfunc_def, safe)\n    by (rule_tac x= \"[]\" in exI, simp)\n\n  text{*Finally we prove the enforcement function satisfies \n    soundness,  transparency, monotonicity, and urgency properties.*}\n\n  theorem Transparency1: \"enforce A\\<^sub>\\<psi> A\\<^sub>\\<phi> x \\<le> x\"\n    apply (induction x rule: length_induct)\n    apply (subst enforce.simps)\n    apply (case_tac \"xs = []\")\n    apply (unfold if_P)\n    apply simp\n    apply (unfold if_not_P)\n    apply (case_tac \"kfunc A\\<^sub>\\<psi> A\\<^sub>\\<phi> xs\")\n    apply simp\n    apply (unfold if_not_P)\n    apply (drule_tac x = \"butlast xs\" in spec)\n    apply safe\n    apply simp\n    by (rule_tac y = \"butlast xs\" in prefix_trans, simp_all)\n\n  lemma Monotonicity_aux: \"\\<And> x y . x \\<le> y \\<Longrightarrow> n = length y \\<Longrightarrow> enforce A\\<^sub>\\<psi> A\\<^sub>\\<phi> x \\<le> enforce A\\<^sub>\\<psi> A\\<^sub>\\<phi> y\"\n    apply (induction n)\n    apply simp\n    apply (subst enforce.simps)\n    apply (subst (2) enforce.simps)\n    apply (simp del: enforce.simps, safe)\n    apply (case_tac x, simp_all del: enforce.simps)\n    apply (metis kfunc_prefix_enforce prefix_butlast)\n    apply (metis Transparency1 enforce.simps prefix_trans)\n    by (metis Suc_eq_plus1 add.commute add_diff_cancel_left' enforce.simps length_butlast prefix_butlast)\n    \n  theorem Monotonicity: \"Monotonicity (enforce A\\<^sub>\\<psi> A\\<^sub>\\<phi>)\"\n    apply (simp)\n    apply (unfold mono_def)\n    apply safe\n    by (rule Monotonicity_aux, simp_all)\n\n  theorem Urgency: \"kfunc A\\<^sub>\\<psi> A\\<^sub>\\<phi> x \\<Longrightarrow> enforce A\\<^sub>\\<psi> A\\<^sub>\\<phi> x = x\"\n    by simp\n\n  theorem Soundness: \"lang A\\<^sub>\\<psi> x \\<Longrightarrow> enforce A\\<^sub>\\<psi> A\\<^sub>\\<phi> x \\<noteq> [] \\<Longrightarrow> lang A\\<^sub>\\<phi> (enforce A\\<^sub>\\<psi> A\\<^sub>\\<phi> x)\"\n    proof -\n      assume A: \"lang A\\<^sub>\\<psi> x\"\n      assume B: \"enforce A\\<^sub>\\<psi> A\\<^sub>\\<phi> x \\<noteq> []\"\n      have \"enforce A\\<^sub>\\<psi> A\\<^sub>\\<phi> x \\<le> x\" by (rule Transparency1)\n      from this obtain z where D: \"x = enforce A\\<^sub>\\<psi> A\\<^sub>\\<phi> x @ z\" by (simp add: prefix_concat del: enforce.simps, safe, simp)\n      from A and this have [simp]: \"lang A\\<^sub>\\<psi> ( enforce A\\<^sub>\\<psi> A\\<^sub>\\<phi> x @ z)\" by simp\n      from B have \"kfunc A\\<^sub>\\<psi> A\\<^sub>\\<phi> (enforce A\\<^sub>\\<psi> A\\<^sub>\\<phi> x)\" by (rule kfunc_enforce)\n      from this have C: \"\\<And> y . lang A\\<^sub>\\<psi> (enforce A\\<^sub>\\<psi> A\\<^sub>\\<phi> x @ y) \\<Longrightarrow> (\\<exists>t . lang A\\<^sub>\\<phi> (enforce A\\<^sub>\\<psi> A\\<^sub>\\<phi> x @ t) \\<and> t \\<le> y)\" by (simp add: kfunc_def)\n      have \"(\\<exists>t . lang  A\\<^sub>\\<phi>  (enforce A\\<^sub>\\<psi> A\\<^sub>\\<phi> x @ t) \\<and> (t \\<le> z))\" by (rule C, simp del: enforce.simps)\n      then obtain za where F: \"lang A\\<^sub>\\<phi> (enforce A\\<^sub>\\<psi> A\\<^sub>\\<phi> x @ za)\" and E: \"za \\<le> z\" by blast\n      from this have \"kfunc A\\<^sub>\\<psi> A\\<^sub>\\<phi> (enforce A\\<^sub>\\<psi> A\\<^sub>\\<phi> x @ za)\" by (simp add: lang_enf_kfunc del: enforce.simps)\n      from this have \"enforce A\\<^sub>\\<psi> A\\<^sub>\\<phi> x @ za \\<le> enforce A\\<^sub>\\<psi> A\\<^sub>\\<phi> x\" \n        apply (rule kfunc_prefix_enforce)\n        by (cut_tac D E, simp add: prefix_concat del: enforce.simps, blast)\n      from this have [simp]: \"za = []\" by simp\n      from F show ?thesis by (simp del: enforce.simps)\n    qed\n\n  section{*Enforcement Algorithm*}\n\n  text{*Because the enforcement algorithm has a non-terminating loop we cannot represent it as function\n  in Isabelle. We introduce here the invariant of the algorithm, and we prove the initialization\n  establishes the invariant, and that each step of the algorithm preserves the invariant. The\n  invariant expresses the desired properties of the algorithm*}\n\n  text{*$x$ is the input received so far, $y$ is the concatenation of all released words, and \n  $z$ ($\\sigma_c$ in the paper) is the pending word.*}\n\n  definition \"Invariant A\\<^sub>\\<psi> A\\<^sub>\\<phi> C p q x y z = (\n    C = A\\<^sub>\\<psi> ** - (Extension A\\<^sub>\\<phi>) \n    \\<and> p = \\<delta>e A\\<^sub>\\<psi> x \n    \\<and> q =  \\<delta>e A\\<^sub>\\<phi> x \\<and> x = y @ z \n    \\<and> enforce A\\<^sub>\\<psi> A\\<^sub>\\<phi> x = y)\"\n\n  definition \"Init A\\<^sub>\\<psi> A\\<^sub>\\<phi> = (let (z, p, q, C) = ([], s\\<^sub>0 A\\<^sub>\\<psi>, s\\<^sub>0 A\\<^sub>\\<phi>, A\\<^sub>\\<psi> ** - (Extension A\\<^sub>\\<phi>)) in (z, p, q, C))\"\n  \n  definition \"Step A\\<^sub>\\<psi> A\\<^sub>\\<phi> C p q z a = (let (p',q') = (\\<delta> A\\<^sub>\\<psi> p a, \\<delta> A\\<^sub>\\<phi> q a) in (p', q', if lang (C\\<lparr>s\\<^sub>0 := (p',q')\\<rparr>) = \\<bottom> then (z @ [a], []) else ([], z @ [a])))\"\n\n  text{*The initialization establishes the invariant*}\n\n  lemma Init: \"(z, p, q, C) = Init A\\<^sub>\\<psi> A\\<^sub>\\<phi> \\<Longrightarrow> Invariant A\\<^sub>\\<psi> A\\<^sub>\\<phi> C p q [] [] z\"\n    by (simp add: Init_def Invariant_def) \n\n  text{*The step preserves the invariant*}\n\n  lemma Step: \"(p', q', yr, zo) = Step A\\<^sub>\\<psi> A\\<^sub>\\<phi> C p q z a \\<Longrightarrow> Invariant A\\<^sub>\\<psi> A\\<^sub>\\<phi> C p q x y z \\<Longrightarrow> Invariant A\\<^sub>\\<psi> A\\<^sub>\\<phi> C p' q' (x @ [a]) (y @ yr) zo\"\n    apply (simp add: Step_def)\n    apply (unfold Invariant_def)\n    apply (simp del: enforce.simps)\n    apply (cut_tac A\\<^sub>\\<psi>1 = A\\<^sub>\\<psi> and A\\<^sub>\\<phi>1 = A\\<^sub>\\<phi> and x1 = \"x @ [a]\" in  kfunc_lang_empty [THEN sym])\n    apply (simp del: enforce.simps add:  delta_but_last)\n    apply (unfold append_assoc [THEN sym])\n    apply (simp del: enforce.simps append_assoc add:  delta_but_last)\n    apply (unfold kfunc_kfunc_lang [THEN sym])\n    apply (case_tac  \"kfunc A\\<^sub>\\<psi> A\\<^sub>\\<phi> ((y @ z) @ [a])\")\n    apply (simp_all del: enforce.simps)\n    apply (rule Urgency, simp)\n    by (metis (no_types, lifting) append_assoc enforce.simps snoc_eq_iff_butlast)\n\n\n  section{*Example*}\n\n  datatype Sa = \"l0\" | \"l1\" | \"l2\"\n  datatype Sig = \"a\" | \"b\" | \"c\"\n  datatype Sb = \"k0\" | \"k1\" | \"k2\" | \"k3\"\n\n  fun\n    \\<delta>a :: \"Sa \\<Rightarrow> Sig \\<Rightarrow> Sa\"\n  where\n    \"\\<delta>a l0 a = l0\" |\n    \"\\<delta>a l0 b = l1\" |\n    \"\\<delta>a l1 c = l0\" |\n    \"\\<delta>a _  a = l2\" |\n    \"\\<delta>a _  b = l2\" |\n    \"\\<delta>a _  c = l2\" \n\n  definition \"Fa = {l0}\"\n\n  fun\n    \\<delta>b :: \"Sb \\<Rightarrow> Sig \\<Rightarrow> Sb\"\n  where\n    \"\\<delta>b k0 a = k0\" |\n    \"\\<delta>b k0 b = k1\" |\n    \"\\<delta>b k1 a = k0\" |\n    \"\\<delta>b k1 c = k2\" |\n    \"\\<delta>b k2 a = k0\" |\n    \"\\<delta>b _  a = k3\" |\n    \"\\<delta>b _  b = k3\" |\n    \"\\<delta>b _  c = k3\" \n\n  definition \"Fb = {k0, k1, k2}\"\n\n  lemma \"kfunc_lang \\<lparr>\\<delta> = \\<delta>b, Final = Fb, s\\<^sub>0 = k0\\<rparr> \\<lparr>\\<delta> = \\<delta>a, Final = Fa, s\\<^sub>0 = l0\\<rparr> [a,b] = False\"\n    apply (simp add: kfunc_lang_def le_fun_def)\n    apply (rule_tac x = \"[]\" in exI)\n    by (simp add: Fb_def Extension_def Fa_def )\n\n  lemma \"kfunc \\<lparr>\\<delta> = \\<delta>b, Final = Fb, s\\<^sub>0 = k0\\<rparr> \\<lparr>\\<delta> = \\<delta>a, Final = Fa, s\\<^sub>0 = l0\\<rparr> [a]\"\n    apply (simp add: kfunc_def Fb_def Fa_def, auto)\n    by (rule_tac x = \"[]\" in exI, simp)\nend\n", "meta": {"author": "isabelle-theory", "repo": "PredictiveRuntimeEnforcement", "sha": "0035a0ef066f865dc9b971df9e259d4ca6419f6e", "save_path": "github-repos/isabelle/isabelle-theory-PredictiveRuntimeEnforcement", "path": "github-repos/isabelle/isabelle-theory-PredictiveRuntimeEnforcement/PredictiveRuntimeEnforcement-0035a0ef066f865dc9b971df9e259d4ca6419f6e/Predictive.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467548438126, "lm_q2_score": 0.8198933381139645, "lm_q1q2_score": 0.7208065675209526}}
{"text": "(*  Title:      HOL/Map.thy\n    Author:     Tobias Nipkow, based on a theory by David von Oheimb\n    Copyright   1997-2003 TU Muenchen\n\nThe datatype of \"maps\"; strongly resembles maps in VDM.\n*)\n\nsection \\<open>Maps\\<close>\n\ntheory Map\n  imports List\n  abbrevs \"(=\" = \"\\<subseteq>\\<^sub>m\"\nbegin\n\ntype_synonym ('a, 'b) \"map\" = \"'a \\<Rightarrow> 'b option\" (infixr \"\\<rightharpoonup>\" 0)\n\nabbreviation\n  empty :: \"'a \\<rightharpoonup> 'b\" where\n  \"empty \\<equiv> \\<lambda>x. None\"\n\ndefinition\n  map_comp :: \"('b \\<rightharpoonup> 'c) \\<Rightarrow> ('a \\<rightharpoonup> 'b) \\<Rightarrow> ('a \\<rightharpoonup> 'c)\"  (infixl \"\\<circ>\\<^sub>m\" 55) where\n  \"f \\<circ>\\<^sub>m g = (\\<lambda>k. case g k of None \\<Rightarrow> None | Some v \\<Rightarrow> f v)\"\n\ndefinition\n  map_add :: \"('a \\<rightharpoonup> 'b) \\<Rightarrow> ('a \\<rightharpoonup> 'b) \\<Rightarrow> ('a \\<rightharpoonup> 'b)\"  (infixl \"++\" 100) where\n  \"m1 ++ m2 = (\\<lambda>x. case m2 x of None \\<Rightarrow> m1 x | Some y \\<Rightarrow> Some y)\"\n\ndefinition\n  restrict_map :: \"('a \\<rightharpoonup> 'b) \\<Rightarrow> 'a set \\<Rightarrow> ('a \\<rightharpoonup> 'b)\"  (infixl \"|`\"  110) where\n  \"m|`A = (\\<lambda>x. if x \\<in> A then m x else None)\"\n\nnotation (latex output)\n  restrict_map  (\"_\\<restriction>\\<^bsub>_\\<^esub>\" [111,110] 110)\n\ndefinition\n  dom :: \"('a \\<rightharpoonup> 'b) \\<Rightarrow> 'a set\" where\n  \"dom m = {a. m a \\<noteq> None}\"\n\ndefinition\n  ran :: \"('a \\<rightharpoonup> 'b) \\<Rightarrow> 'b set\" where\n  \"ran m = {b. \\<exists>a. m a = Some b}\"\n\ndefinition\n  graph :: \"('a \\<rightharpoonup> 'b) \\<Rightarrow> ('a \\<times> 'b) set\" where\n  \"graph m = {(a, b) | a b. m a = Some b}\"\n\ndefinition\n  map_le :: \"('a \\<rightharpoonup> 'b) \\<Rightarrow> ('a \\<rightharpoonup> 'b) \\<Rightarrow> bool\"  (infix \"\\<subseteq>\\<^sub>m\" 50) where\n  \"(m\\<^sub>1 \\<subseteq>\\<^sub>m m\\<^sub>2) \\<longleftrightarrow> (\\<forall>a \\<in> dom m\\<^sub>1. m\\<^sub>1 a = m\\<^sub>2 a)\"\n\nnonterminal maplets and maplet\n\nsyntax\n  \"_maplet\"  :: \"['a, 'a] \\<Rightarrow> maplet\"             (\"_ /\\<mapsto>/ _\")\n  \"_maplets\" :: \"['a, 'a] \\<Rightarrow> maplet\"             (\"_ /[\\<mapsto>]/ _\")\n  \"\"         :: \"maplet \\<Rightarrow> maplets\"             (\"_\")\n  \"_Maplets\" :: \"[maplet, maplets] \\<Rightarrow> maplets\" (\"_,/ _\")\n  \"_MapUpd\"  :: \"['a \\<rightharpoonup> 'b, maplets] \\<Rightarrow> 'a \\<rightharpoonup> 'b\" (\"_/'(_')\" [900, 0] 900)\n  \"_Map\"     :: \"maplets \\<Rightarrow> 'a \\<rightharpoonup> 'b\"            (\"(1[_])\")\n\nsyntax (ASCII)\n  \"_maplet\"  :: \"['a, 'a] \\<Rightarrow> maplet\"             (\"_ /|->/ _\")\n  \"_maplets\" :: \"['a, 'a] \\<Rightarrow> maplet\"             (\"_ /[|->]/ _\")\n\ntranslations\n  \"_MapUpd m (_Maplets xy ms)\"  \\<rightleftharpoons> \"_MapUpd (_MapUpd m xy) ms\"\n  \"_MapUpd m (_maplet  x y)\"    \\<rightleftharpoons> \"m(x := CONST Some y)\"\n  \"_Map ms\"                     \\<rightleftharpoons> \"_MapUpd (CONST empty) ms\"\n  \"_Map (_Maplets ms1 ms2)\"     \\<leftharpoondown> \"_MapUpd (_Map ms1) ms2\"\n  \"_Maplets ms1 (_Maplets ms2 ms3)\" \\<leftharpoondown> \"_Maplets (_Maplets ms1 ms2) ms3\"\n\nprimrec map_of :: \"('a \\<times> 'b) list \\<Rightarrow> 'a \\<rightharpoonup> 'b\"\nwhere\n  \"map_of [] = empty\"\n| \"map_of (p # ps) = (map_of ps)(fst p \\<mapsto> snd p)\"\n\ndefinition map_upds :: \"('a \\<rightharpoonup> 'b) \\<Rightarrow> 'a list \\<Rightarrow> 'b list \\<Rightarrow> 'a \\<rightharpoonup> 'b\"\n  where \"map_upds m xs ys = m ++ map_of (rev (zip xs ys))\"\ntranslations\n  \"_MapUpd m (_maplets x y)\" \\<rightleftharpoons> \"CONST map_upds m x y\"\n\nlemma map_of_Cons_code [code]:\n  \"map_of [] k = None\"\n  \"map_of ((l, v) # ps) k = (if l = k then Some v else map_of ps k)\"\n  by simp_all\n\n\nsubsection \\<open>@{term [source] empty}\\<close>\n\nlemma empty_upd_none [simp]: \"empty(x := None) = empty\"\n  by (rule ext) simp\n\n\nsubsection \\<open>@{term [source] map_upd}\\<close>\n\nlemma map_upd_triv: \"t k = Some x \\<Longrightarrow> t(k\\<mapsto>x) = t\"\n  by (rule ext) simp\n\nlemma map_upd_nonempty [simp]: \"t(k\\<mapsto>x) \\<noteq> empty\"\nproof\n  assume \"t(k \\<mapsto> x) = empty\"\n  then have \"(t(k \\<mapsto> x)) k = None\" by simp\n  then show False by simp\nqed\n\nlemma map_upd_eqD1:\n  assumes \"m(a\\<mapsto>x) = n(a\\<mapsto>y)\"\n  shows \"x = y\"\nproof -\n  from assms have \"(m(a\\<mapsto>x)) a = (n(a\\<mapsto>y)) a\" by simp\n  then show ?thesis by simp\nqed\n\nlemma map_upd_Some_unfold:\n  \"((m(a\\<mapsto>b)) x = Some y) = (x = a \\<and> b = y \\<or> x \\<noteq> a \\<and> m x = Some y)\"\n  by auto\n\nlemma image_map_upd [simp]: \"x \\<notin> A \\<Longrightarrow> m(x \\<mapsto> y) ` A = m ` A\"\n  by auto\n\nlemma finite_range_updI:\n  assumes \"finite (range f)\" shows \"finite (range (f(a\\<mapsto>b)))\"\nproof -\n  have \"range (f(a\\<mapsto>b)) \\<subseteq> insert (Some b) (range f)\"\n    by auto\n  then show ?thesis\n    by (rule finite_subset) (use assms in auto)\nqed\n\n\nsubsection \\<open>@{term [source] map_of}\\<close>\n\nlemma map_of_eq_empty_iff [simp]:\n  \"map_of xys = empty \\<longleftrightarrow> xys = []\"\nproof\n  show \"map_of xys = empty \\<Longrightarrow> xys = []\"\n    by (induction xys) simp_all\nqed simp\n\nlemma empty_eq_map_of_iff [simp]:\n  \"empty = map_of xys \\<longleftrightarrow> xys = []\"\nby(subst eq_commute) simp\n\nlemma map_of_eq_None_iff:\n  \"(map_of xys x = None) = (x \\<notin> fst ` (set xys))\"\nby (induct xys) simp_all\n\nlemma map_of_eq_Some_iff [simp]:\n  \"distinct(map fst xys) \\<Longrightarrow> (map_of xys x = Some y) = ((x,y) \\<in> set xys)\"\nproof (induct xys)\n  case (Cons xy xys)\n  then show ?case\n    by (cases xy) (auto simp flip: map_of_eq_None_iff)\nqed auto\n\nlemma Some_eq_map_of_iff [simp]:\n  \"distinct(map fst xys) \\<Longrightarrow> (Some y = map_of xys x) = ((x,y) \\<in> set xys)\"\nby (auto simp del: map_of_eq_Some_iff simp: map_of_eq_Some_iff [symmetric])\n\nlemma map_of_is_SomeI [simp]: \n  \"\\<lbrakk>distinct(map fst xys); (x,y) \\<in> set xys\\<rbrakk> \\<Longrightarrow> map_of xys x = Some y\"\n  by simp\n\nlemma map_of_zip_is_None [simp]:\n  \"length xs = length ys \\<Longrightarrow> (map_of (zip xs ys) x = None) = (x \\<notin> set xs)\"\nby (induct rule: list_induct2) simp_all\n\nlemma map_of_zip_is_Some:\n  assumes \"length xs = length ys\"\n  shows \"x \\<in> set xs \\<longleftrightarrow> (\\<exists>y. map_of (zip xs ys) x = Some y)\"\nusing assms by (induct rule: list_induct2) simp_all\n\nlemma map_of_zip_upd:\n  fixes x :: 'a and xs :: \"'a list\" and ys zs :: \"'b list\"\n  assumes \"length ys = length xs\"\n    and \"length zs = length xs\"\n    and \"x \\<notin> set xs\"\n    and \"map_of (zip xs ys)(x \\<mapsto> y) = map_of (zip xs zs)(x \\<mapsto> z)\"\n  shows \"map_of (zip xs ys) = map_of (zip xs zs)\"\nproof\n  fix x' :: 'a\n  show \"map_of (zip xs ys) x' = map_of (zip xs zs) x'\"\n  proof (cases \"x = x'\")\n    case True\n    from assms True map_of_zip_is_None [of xs ys x']\n      have \"map_of (zip xs ys) x' = None\" by simp\n    moreover from assms True map_of_zip_is_None [of xs zs x']\n      have \"map_of (zip xs zs) x' = None\" by simp\n    ultimately show ?thesis by simp\n  next\n    case False from assms\n      have \"(map_of (zip xs ys)(x \\<mapsto> y)) x' = (map_of (zip xs zs)(x \\<mapsto> z)) x'\" by auto\n    with False show ?thesis by simp\n  qed\nqed\n\nlemma map_of_zip_inject:\n  assumes \"length ys = length xs\"\n    and \"length zs = length xs\"\n    and dist: \"distinct xs\"\n    and map_of: \"map_of (zip xs ys) = map_of (zip xs zs)\"\n  shows \"ys = zs\"\n  using assms(1) assms(2)[symmetric]\n  using dist map_of\nproof (induct ys xs zs rule: list_induct3)\n  case Nil show ?case by simp\nnext\n  case (Cons y ys x xs z zs)\n  from \\<open>map_of (zip (x#xs) (y#ys)) = map_of (zip (x#xs) (z#zs))\\<close>\n    have map_of: \"map_of (zip xs ys)(x \\<mapsto> y) = map_of (zip xs zs)(x \\<mapsto> z)\" by simp\n  from Cons have \"length ys = length xs\" and \"length zs = length xs\"\n    and \"x \\<notin> set xs\" by simp_all\n  then have \"map_of (zip xs ys) = map_of (zip xs zs)\" using map_of by (rule map_of_zip_upd)\n  with Cons.hyps \\<open>distinct (x # xs)\\<close> have \"ys = zs\" by simp\n  moreover from map_of have \"y = z\" by (rule map_upd_eqD1)\n  ultimately show ?case by simp\nqed\n\nlemma map_of_zip_nth:\n  assumes \"length xs = length ys\"\n  assumes \"distinct xs\"\n  assumes \"i < length ys\"\n  shows \"map_of (zip xs ys) (xs ! i) = Some (ys ! i)\"\nusing assms proof (induct arbitrary: i rule: list_induct2)\n  case Nil\n  then show ?case by simp\nnext\n  case (Cons x xs y ys)\n  then show ?case\n    using less_Suc_eq_0_disj by auto\nqed\n\nlemma map_of_zip_map:\n  \"map_of (zip xs (map f xs)) = (\\<lambda>x. if x \\<in> set xs then Some (f x) else None)\"\n  by (induct xs) (simp_all add: fun_eq_iff)\n\nlemma finite_range_map_of: \"finite (range (map_of xys))\"\nproof (induct xys)\n  case (Cons a xys)\n  then show ?case\n    using finite_range_updI by fastforce\nqed auto\n\nlemma map_of_SomeD: \"map_of xs k = Some y \\<Longrightarrow> (k, y) \\<in> set xs\"\n  by (induct xs) (auto split: if_splits)\n\nlemma map_of_mapk_SomeI:\n  \"inj f \\<Longrightarrow> map_of t k = Some x \\<Longrightarrow>\n   map_of (map (case_prod (\\<lambda>k. Pair (f k))) t) (f k) = Some x\"\nby (induct t) (auto simp: inj_eq)\n\nlemma weak_map_of_SomeI: \"(k, x) \\<in> set l \\<Longrightarrow> \\<exists>x. map_of l k = Some x\"\nby (induct l) auto\n\nlemma map_of_filter_in:\n  \"map_of xs k = Some z \\<Longrightarrow> P k z \\<Longrightarrow> map_of (filter (case_prod P) xs) k = Some z\"\nby (induct xs) auto\n\nlemma map_of_map:\n  \"map_of (map (\\<lambda>(k, v). (k, f v)) xs) = map_option f \\<circ> map_of xs\"\n  by (induct xs) (auto simp: fun_eq_iff)\n\nlemma dom_map_option:\n  \"dom (\\<lambda>k. map_option (f k) (m k)) = dom m\"\n  by (simp add: dom_def)\n\nlemma dom_map_option_comp [simp]:\n  \"dom (map_option g \\<circ> m) = dom m\"\n  using dom_map_option [of \"\\<lambda>_. g\" m] by (simp add: comp_def)\n\n\nsubsection \\<open>\\<^const>\\<open>map_option\\<close> related\\<close>\n\nlemma map_option_o_empty [simp]: \"map_option f \\<circ> empty = empty\"\nby (rule ext) simp\n\nlemma map_option_o_map_upd [simp]:\n  \"map_option f \\<circ> m(a\\<mapsto>b) = (map_option f \\<circ> m)(a\\<mapsto>f b)\"\nby (rule ext) simp\n\n\nsubsection \\<open>@{term [source] map_comp} related\\<close>\n\nlemma map_comp_empty [simp]:\n  \"m \\<circ>\\<^sub>m empty = empty\"\n  \"empty \\<circ>\\<^sub>m m = empty\"\nby (auto simp: map_comp_def split: option.splits)\n\nlemma map_comp_simps [simp]:\n  \"m2 k = None \\<Longrightarrow> (m1 \\<circ>\\<^sub>m m2) k = None\"\n  \"m2 k = Some k' \\<Longrightarrow> (m1 \\<circ>\\<^sub>m m2) k = m1 k'\"\nby (auto simp: map_comp_def)\n\nlemma map_comp_Some_iff:\n  \"((m1 \\<circ>\\<^sub>m m2) k = Some v) = (\\<exists>k'. m2 k = Some k' \\<and> m1 k' = Some v)\"\nby (auto simp: map_comp_def split: option.splits)\n\nlemma map_comp_None_iff:\n  \"((m1 \\<circ>\\<^sub>m m2) k = None) = (m2 k = None \\<or> (\\<exists>k'. m2 k = Some k' \\<and> m1 k' = None)) \"\nby (auto simp: map_comp_def split: option.splits)\n\n\nsubsection \\<open>\\<open>++\\<close>\\<close>\n\nlemma map_add_empty[simp]: \"m ++ empty = m\"\nby(simp add: map_add_def)\n\nlemma empty_map_add[simp]: \"empty ++ m = m\"\nby (rule ext) (simp add: map_add_def split: option.split)\n\nlemma map_add_assoc[simp]: \"m1 ++ (m2 ++ m3) = (m1 ++ m2) ++ m3\"\nby (rule ext) (simp add: map_add_def split: option.split)\n\nlemma map_add_Some_iff:\n  \"((m ++ n) k = Some x) = (n k = Some x \\<or> n k = None \\<and> m k = Some x)\"\nby (simp add: map_add_def split: option.split)\n\nlemma map_add_SomeD [dest!]:\n  \"(m ++ n) k = Some x \\<Longrightarrow> n k = Some x \\<or> n k = None \\<and> m k = Some x\"\nby (rule map_add_Some_iff [THEN iffD1])\n\nlemma map_add_find_right [simp]: \"n k = Some xx \\<Longrightarrow> (m ++ n) k = Some xx\"\nby (subst map_add_Some_iff) fast\n\nlemma map_add_None [iff]: \"((m ++ n) k = None) = (n k = None \\<and> m k = None)\"\nby (simp add: map_add_def split: option.split)\n\nlemma map_add_upd[simp]: \"f ++ g(x\\<mapsto>y) = (f ++ g)(x\\<mapsto>y)\"\nby (rule ext) (simp add: map_add_def)\n\nlemma map_add_upds[simp]: \"m1 ++ (m2(xs[\\<mapsto>]ys)) = (m1++m2)(xs[\\<mapsto>]ys)\"\nby (simp add: map_upds_def)\n\nlemma map_add_upd_left: \"m\\<notin>dom e2 \\<Longrightarrow> e1(m \\<mapsto> u1) ++ e2 = (e1 ++ e2)(m \\<mapsto> u1)\"\nby (rule ext) (auto simp: map_add_def dom_def split: option.split)\n\nlemma map_of_append[simp]: \"map_of (xs @ ys) = map_of ys ++ map_of xs\"\n  unfolding map_add_def\nproof (induct xs)\n  case (Cons a xs)\n  then show ?case\n    by (force split: option.split)\nqed auto\n\nlemma finite_range_map_of_map_add:\n  \"finite (range f) \\<Longrightarrow> finite (range (f ++ map_of l))\"\nproof (induct l)\ncase (Cons a l)\n  then show ?case\n    by (metis finite_range_updI map_add_upd map_of.simps(2))\nqed auto\n\nlemma inj_on_map_add_dom [iff]:\n  \"inj_on (m ++ m') (dom m') = inj_on m' (dom m')\"\n  by (fastforce simp: map_add_def dom_def inj_on_def split: option.splits)\n\nlemma map_upds_fold_map_upd:\n  \"m(ks[\\<mapsto>]vs) = foldl (\\<lambda>m (k, v). m(k \\<mapsto> v)) m (zip ks vs)\"\nunfolding map_upds_def proof (rule sym, rule zip_obtain_same_length)\n  fix ks :: \"'a list\" and vs :: \"'b list\"\n  assume \"length ks = length vs\"\n  then show \"foldl (\\<lambda>m (k, v). m(k\\<mapsto>v)) m (zip ks vs) = m ++ map_of (rev (zip ks vs))\"\n    by(induct arbitrary: m rule: list_induct2) simp_all\nqed\n\nlemma map_add_map_of_foldr:\n  \"m ++ map_of ps = foldr (\\<lambda>(k, v) m. m(k \\<mapsto> v)) ps m\"\n  by (induct ps) (auto simp: fun_eq_iff map_add_def)\n\n\nsubsection \\<open>@{term [source] restrict_map}\\<close>\n\nlemma restrict_map_to_empty [simp]: \"m|`{} = empty\"\n  by (simp add: restrict_map_def)\n\nlemma restrict_map_insert: \"f |` (insert a A) = (f |` A)(a := f a)\"\n  by (auto simp: restrict_map_def)\n\nlemma restrict_map_empty [simp]: \"empty|`D = empty\"\n  by (simp add: restrict_map_def)\n\nlemma restrict_in [simp]: \"x \\<in> A \\<Longrightarrow> (m|`A) x = m x\"\n  by (simp add: restrict_map_def)\n\nlemma restrict_out [simp]: \"x \\<notin> A \\<Longrightarrow> (m|`A) x = None\"\n  by (simp add: restrict_map_def)\n\nlemma ran_restrictD: \"y \\<in> ran (m|`A) \\<Longrightarrow> \\<exists>x\\<in>A. m x = Some y\"\n  by (auto simp: restrict_map_def ran_def split: if_split_asm)\n\nlemma dom_restrict [simp]: \"dom (m|`A) = dom m \\<inter> A\"\n  by (auto simp: restrict_map_def dom_def split: if_split_asm)\n\nlemma restrict_upd_same [simp]: \"m(x\\<mapsto>y)|`(-{x}) = m|`(-{x})\"\n  by (rule ext) (auto simp: restrict_map_def)\n\nlemma restrict_restrict [simp]: \"m|`A|`B = m|`(A\\<inter>B)\"\n  by (rule ext) (auto simp: restrict_map_def)\n\nlemma restrict_fun_upd [simp]:\n  \"m(x := y)|`D = (if x \\<in> D then (m|`(D-{x}))(x := y) else m|`D)\"\n  by (simp add: restrict_map_def fun_eq_iff)\n\nlemma fun_upd_None_restrict [simp]:\n  \"(m|`D)(x := None) = (if x \\<in> D then m|`(D - {x}) else m|`D)\"\n  by (simp add: restrict_map_def fun_eq_iff)\n\nlemma fun_upd_restrict: \"(m|`D)(x := y) = (m|`(D-{x}))(x := y)\"\n  by (simp add: restrict_map_def fun_eq_iff)\n\nlemma fun_upd_restrict_conv [simp]:\n  \"x \\<in> D \\<Longrightarrow> (m|`D)(x := y) = (m|`(D-{x}))(x := y)\"\n  by (rule fun_upd_restrict)\n\nlemma map_of_map_restrict:\n  \"map_of (map (\\<lambda>k. (k, f k)) ks) = (Some \\<circ> f) |` set ks\"\n  by (induct ks) (simp_all add: fun_eq_iff restrict_map_insert)\n\nlemma restrict_complement_singleton_eq:\n  \"f |` (- {x}) = f(x := None)\"\n  by auto\n\n\nsubsection \\<open>@{term [source] map_upds}\\<close>\n\nlemma map_upds_Nil1 [simp]: \"m([] [\\<mapsto>] bs) = m\"\n  by (simp add: map_upds_def)\n\nlemma map_upds_Nil2 [simp]: \"m(as [\\<mapsto>] []) = m\"\n  by (simp add:map_upds_def)\n\nlemma map_upds_Cons [simp]: \"m(a#as [\\<mapsto>] b#bs) = (m(a\\<mapsto>b))(as[\\<mapsto>]bs)\"\n  by (simp add:map_upds_def)\n\nlemma map_upds_append1 [simp]:\n  \"size xs < size ys \\<Longrightarrow> m(xs@[x] [\\<mapsto>] ys) = m(xs [\\<mapsto>] ys)(x \\<mapsto> ys!size xs)\"\nproof (induct xs arbitrary: ys m)\n  case Nil\n  then show ?case\n    by (auto simp: neq_Nil_conv)\nnext\n  case (Cons a xs)\n  then show ?case\n    by (cases ys) auto\nqed\n\nlemma map_upds_list_update2_drop [simp]:\n  \"size xs \\<le> i \\<Longrightarrow> m(xs[\\<mapsto>]ys[i:=y]) = m(xs[\\<mapsto>]ys)\"\nproof (induct xs arbitrary: m ys i)\n  case Nil\n  then show ?case\n    by auto\nnext\n  case (Cons a xs)\n  then show ?case\n    by (cases ys) (use Cons in \\<open>auto split: nat.split\\<close>)\nqed\n\ntext \\<open>Something weirdly sensitive about this proof, which needs only four lines in apply style\\<close>\nlemma map_upd_upds_conv_if:\n  \"(f(x\\<mapsto>y))(xs [\\<mapsto>] ys) =\n   (if x \\<in> set(take (length ys) xs) then f(xs [\\<mapsto>] ys)\n                                    else (f(xs [\\<mapsto>] ys))(x\\<mapsto>y))\"\nproof (induct xs arbitrary: x y ys f)\n  case (Cons a xs)\n  show ?case\n  proof (cases ys)\n    case (Cons z zs)\n    then show ?thesis\n      using Cons.hyps\n      apply (auto split: if_split simp: fun_upd_twist)\n      using Cons.hyps apply fastforce+\n      done\n  qed auto\nqed auto\n\n\nlemma map_upds_twist [simp]:\n  \"a \\<notin> set as \\<Longrightarrow> m(a\\<mapsto>b)(as[\\<mapsto>]bs) = m(as[\\<mapsto>]bs)(a\\<mapsto>b)\"\nusing set_take_subset by (fastforce simp add: map_upd_upds_conv_if)\n\nlemma map_upds_apply_nontin [simp]:\n  \"x \\<notin> set xs \\<Longrightarrow> (f(xs[\\<mapsto>]ys)) x = f x\"\nproof (induct xs arbitrary: ys)\n  case (Cons a xs)\n  then show ?case\n    by (cases ys) (auto simp: map_upd_upds_conv_if)\nqed auto\n\nlemma fun_upds_append_drop [simp]:\n  \"size xs = size ys \\<Longrightarrow> m(xs@zs[\\<mapsto>]ys) = m(xs[\\<mapsto>]ys)\"\nproof (induct xs arbitrary: ys)\n  case (Cons a xs)\n  then show ?case\n    by (cases ys) (auto simp: map_upd_upds_conv_if)\nqed auto\n\nlemma fun_upds_append2_drop [simp]:\n  \"size xs = size ys \\<Longrightarrow> m(xs[\\<mapsto>]ys@zs) = m(xs[\\<mapsto>]ys)\"\nproof (induct xs arbitrary: ys)\n  case (Cons a xs)\n  then show ?case\n    by (cases ys) (auto simp: map_upd_upds_conv_if)\nqed auto\n\nlemma restrict_map_upds[simp]:\n  \"\\<lbrakk> length xs = length ys; set xs \\<subseteq> D \\<rbrakk>\n    \\<Longrightarrow> m(xs [\\<mapsto>] ys)|`D = (m|`(D - set xs))(xs [\\<mapsto>] ys)\"\nproof (induct xs arbitrary: m ys)\n  case (Cons a xs)\n  then show ?case\n  proof (cases ys)\n    case (Cons z zs)\n    with Cons.hyps Cons.prems show ?thesis\n      apply (simp add: insert_absorb flip: Diff_insert)\n      apply (auto simp add: map_upd_upds_conv_if)\n      done\n  qed auto\nqed auto\n\n\nsubsection \\<open>@{term [source] dom}\\<close>\n\nlemma dom_eq_empty_conv [simp]: \"dom f = {} \\<longleftrightarrow> f = empty\"\n  by (auto simp: dom_def)\n\nlemma domI: \"m a = Some b \\<Longrightarrow> a \\<in> dom m\"\n  by (simp add: dom_def)\n(* declare domI [intro]? *)\n\nlemma domD: \"a \\<in> dom m \\<Longrightarrow> \\<exists>b. m a = Some b\"\n  by (cases \"m a\") (auto simp add: dom_def)\n\nlemma domIff [iff, simp del, code_unfold]: \"a \\<in> dom m \\<longleftrightarrow> m a \\<noteq> None\"\n  by (simp add: dom_def)\n\nlemma dom_empty [simp]: \"dom empty = {}\"\n  by (simp add: dom_def)\n\nlemma dom_fun_upd [simp]:\n  \"dom(f(x := y)) = (if y = None then dom f - {x} else insert x (dom f))\"\n  by (auto simp: dom_def)\n\nlemma dom_if:\n  \"dom (\\<lambda>x. if P x then f x else g x) = dom f \\<inter> {x. P x} \\<union> dom g \\<inter> {x. \\<not> P x}\"\n  by (auto split: if_splits)\n\nlemma dom_map_of_conv_image_fst:\n  \"dom (map_of xys) = fst ` set xys\"\n  by (induct xys) (auto simp add: dom_if)\n\nlemma dom_map_of_zip [simp]: \"length xs = length ys \\<Longrightarrow> dom (map_of (zip xs ys)) = set xs\"\n  by (induct rule: list_induct2) (auto simp: dom_if)\n\nlemma finite_dom_map_of: \"finite (dom (map_of l))\"\n  by (induct l) (auto simp: dom_def insert_Collect [symmetric])\n\nlemma dom_map_upds [simp]:\n  \"dom(m(xs[\\<mapsto>]ys)) = set(take (length ys) xs) \\<union> dom m\"\nproof (induct xs arbitrary: ys)\n  case (Cons a xs)\n  then show ?case\n    by (cases ys) (auto simp: map_upd_upds_conv_if)\nqed auto\n\n\nlemma dom_map_add [simp]: \"dom (m ++ n) = dom n \\<union> dom m\"\n  by (auto simp: dom_def)\n\nlemma dom_override_on [simp]:\n  \"dom (override_on f g A) =\n    (dom f  - {a. a \\<in> A - dom g}) \\<union> {a. a \\<in> A \\<inter> dom g}\"\n  by (auto simp: dom_def override_on_def)\n\n\n\nlemma map_add_dom_app_simps:\n  \"m \\<in> dom l2 \\<Longrightarrow> (l1 ++ l2) m = l2 m\"\n  \"m \\<notin> dom l1 \\<Longrightarrow> (l1 ++ l2) m = l2 m\"\n  \"m \\<notin> dom l2 \\<Longrightarrow> (l1 ++ l2) m = l1 m\"\n  by (auto simp add: map_add_def split: option.split_asm)\n\nlemma dom_const [simp]:\n  \"dom (\\<lambda>x. Some (f x)) = UNIV\"\n  by auto\n\n(* Due to John Matthews - could be rephrased with dom *)\nlemma finite_map_freshness:\n  \"finite (dom (f :: 'a \\<rightharpoonup> 'b)) \\<Longrightarrow> \\<not> finite (UNIV :: 'a set) \\<Longrightarrow>\n   \\<exists>x. f x = None\"\n  by (bestsimp dest: ex_new_if_finite)\n\nlemma dom_minus:\n  \"f x = None \\<Longrightarrow> dom f - insert x A = dom f - A\"\n  unfolding dom_def by simp\n\nlemma insert_dom:\n  \"f x = Some y \\<Longrightarrow> insert x (dom f) = dom f\"\n  unfolding dom_def by auto\n\nlemma map_of_map_keys:\n  \"set xs = dom m \\<Longrightarrow> map_of (map (\\<lambda>k. (k, the (m k))) xs) = m\"\n  by (rule ext) (auto simp add: map_of_map_restrict restrict_map_def)\n\nlemma map_of_eqI:\n  assumes set_eq: \"set (map fst xs) = set (map fst ys)\"\n  assumes map_eq: \"\\<forall>k\\<in>set (map fst xs). map_of xs k = map_of ys k\"\n  shows \"map_of xs = map_of ys\"\nproof (rule ext)\n  fix k show \"map_of xs k = map_of ys k\"\n  proof (cases \"map_of xs k\")\n    case None\n    then have \"k \\<notin> set (map fst xs)\" by (simp add: map_of_eq_None_iff)\n    with set_eq have \"k \\<notin> set (map fst ys)\" by simp\n    then have \"map_of ys k = None\" by (simp add: map_of_eq_None_iff)\n    with None show ?thesis by simp\n  next\n    case (Some v)\n    then have \"k \\<in> set (map fst xs)\" by (auto simp add: dom_map_of_conv_image_fst [symmetric])\n    with map_eq show ?thesis by auto\n  qed\nqed\n\nlemma map_of_eq_dom:\n  assumes \"map_of xs = map_of ys\"\n  shows \"fst ` set xs = fst ` set ys\"\nproof -\n  from assms have \"dom (map_of xs) = dom (map_of ys)\" by simp\n  then show ?thesis by (simp add: dom_map_of_conv_image_fst)\nqed\n\nlemma finite_set_of_finite_maps:\n  assumes \"finite A\" \"finite B\"\n  shows \"finite {m. dom m = A \\<and> ran m \\<subseteq> B}\" (is \"finite ?S\")\nproof -\n  let ?S' = \"{m. \\<forall>x. (x \\<in> A \\<longrightarrow> m x \\<in> Some ` B) \\<and> (x \\<notin> A \\<longrightarrow> m x = None)}\"\n  have \"?S = ?S'\"\n  proof\n    show \"?S \\<subseteq> ?S'\" by (auto simp: dom_def ran_def image_def)\n    show \"?S' \\<subseteq> ?S\"\n    proof\n      fix m assume \"m \\<in> ?S'\"\n      hence 1: \"dom m = A\" by force\n      hence 2: \"ran m \\<subseteq> B\" using \\<open>m \\<in> ?S'\\<close> by (auto simp: dom_def ran_def)\n      from 1 2 show \"m \\<in> ?S\" by blast\n    qed\n  qed\n  with assms show ?thesis by(simp add: finite_set_of_finite_funs)\nqed\n\n\nsubsection \\<open>@{term [source] ran}\\<close>\n\nlemma ranI: \"m a = Some b \\<Longrightarrow> b \\<in> ran m\"\n  by (auto simp: ran_def)\n(* declare ranI [intro]? *)\n\nlemma ran_empty [simp]: \"ran empty = {}\"\n  by (auto simp: ran_def)\n\nlemma ran_map_upd [simp]:  \"m a = None \\<Longrightarrow> ran(m(a\\<mapsto>b)) = insert b (ran m)\"\n  unfolding ran_def\n  by force\n\nlemma fun_upd_None_if_notin_dom[simp]: \"k \\<notin> dom m \\<Longrightarrow> m(k := None) = m\"\n  by auto\n\nlemma ran_map_upd_Some:\n  \"\\<lbrakk> m x = Some y; inj_on m (dom m); z \\<notin> ran m \\<rbrakk> \\<Longrightarrow> ran(m(x := Some z)) = ran m - {y} \\<union> {z}\"\nby(force simp add: ran_def domI inj_onD)\n\nlemma ran_map_add:\n  assumes \"dom m1 \\<inter> dom m2 = {}\"\n  shows \"ran (m1 ++ m2) = ran m1 \\<union> ran m2\"\nproof\n  show \"ran (m1 ++ m2) \\<subseteq> ran m1 \\<union> ran m2\"\n    unfolding ran_def by auto\nnext\n  show \"ran m1 \\<union> ran m2 \\<subseteq> ran (m1 ++ m2)\"\n  proof -\n    have \"(m1 ++ m2) x = Some y\" if \"m1 x = Some y\" for x y\n      using assms map_add_comm that by fastforce\n    moreover have \"(m1 ++ m2) x = Some y\" if \"m2 x = Some y\" for x y\n      using assms that by auto\n    ultimately show ?thesis\n      unfolding ran_def by blast\n  qed\nqed\n\nlemma finite_ran:\n  assumes \"finite (dom p)\"\n  shows \"finite (ran p)\"\nproof -\n  have \"ran p = (\\<lambda>x. the (p x)) ` dom p\"\n    unfolding ran_def by force\n  from this \\<open>finite (dom p)\\<close> show ?thesis by auto\nqed\n\nlemma ran_distinct:\n  assumes dist: \"distinct (map fst al)\"\n  shows \"ran (map_of al) = snd ` set al\"\n  using assms\nproof (induct al)\n  case Nil\n  then show ?case by simp\nnext\n  case (Cons kv al)\n  then have \"ran (map_of al) = snd ` set al\" by simp\n  moreover from Cons.prems have \"map_of al (fst kv) = None\"\n    by (simp add: map_of_eq_None_iff)\n  ultimately show ?case by (simp only: map_of.simps ran_map_upd) simp\nqed\n\nlemma ran_map_of_zip:\n  assumes \"length xs = length ys\" \"distinct xs\"\n  shows \"ran (map_of (zip xs ys)) = set ys\"\nusing assms by (simp add: ran_distinct set_map[symmetric])\n\nlemma ran_map_option: \"ran (\\<lambda>x. map_option f (m x)) = f ` ran m\"\n  by (auto simp add: ran_def)\n\nsubsection \\<open>@{term [source] graph}\\<close>\n\n\n\nlemma in_graphI: \"m k = Some v \\<Longrightarrow> (k, v) \\<in> graph m\"\n  unfolding graph_def by blast\n\nlemma in_graphD: \"(k, v) \\<in> graph m \\<Longrightarrow> m k = Some v\"\n  unfolding graph_def by blast\n\nlemma graph_map_upd[simp]: \"graph (m(k \\<mapsto> v)) = insert (k, v) (graph (m(k := None)))\"\n  unfolding graph_def by (auto split: if_splits)\n\nlemma graph_fun_upd_None: \"graph (m(k := None)) = {e \\<in> graph m. fst e \\<noteq> k}\"\n  unfolding graph_def by (auto split: if_splits)\n\nlemma graph_restrictD:\n  assumes \"(k, v) \\<in> graph (m |` A)\"\n  shows \"k \\<in> A\" and \"m k = Some v\"\n  using assms unfolding graph_def\n  by (auto simp: restrict_map_def split: if_splits)\n\nlemma graph_map_comp[simp]: \"graph (m1 \\<circ>\\<^sub>m m2) = graph m2 O graph m1\"\n  unfolding graph_def by (auto simp: map_comp_Some_iff relcomp_unfold)\n\nlemma graph_map_add: \"dom m1 \\<inter> dom m2 = {} \\<Longrightarrow> graph (m1 ++ m2) = graph m1 \\<union> graph m2\"\n  unfolding graph_def using map_add_comm by force\n\nlemma graph_eq_to_snd_dom: \"graph m = (\\<lambda>x. (x, the (m x))) ` dom m\"\n  unfolding graph_def dom_def by force\n\nlemma fst_graph_eq_dom: \"fst ` graph m = dom m\"\n  unfolding graph_eq_to_snd_dom by force\n\nlemma graph_domD: \"x \\<in> graph m \\<Longrightarrow> fst x \\<in> dom m\"\n  using fst_graph_eq_dom by (metis imageI)\n\nlemma snd_graph_ran: \"snd ` graph m = ran m\"\n  unfolding graph_def ran_def by force\n\nlemma graph_ranD: \"x \\<in> graph m \\<Longrightarrow> snd x \\<in> ran m\"\n  using snd_graph_ran by (metis imageI)\n\nlemma finite_graph_map_of: \"finite (graph (map_of al))\"\n  unfolding graph_eq_to_snd_dom finite_dom_map_of\n  using finite_dom_map_of by blast\n\nlemma graph_map_of_if_distinct_dom: \"distinct (map fst al) \\<Longrightarrow> graph (map_of al) = set al\"\n  unfolding graph_def by auto\n\nlemma finite_graph_iff_finite_dom[simp]: \"finite (graph m) = finite (dom m)\"\n  by (metis graph_eq_to_snd_dom finite_imageI fst_graph_eq_dom)\n\nlemma inj_on_fst_graph: \"inj_on fst (graph m)\"\n  unfolding graph_def inj_on_def by force\n\nsubsection \\<open>\\<open>map_le\\<close>\\<close>\n\nlemma map_le_empty [simp]: \"empty \\<subseteq>\\<^sub>m g\"\n  by (simp add: map_le_def)\n\nlemma upd_None_map_le [simp]: \"f(x := None) \\<subseteq>\\<^sub>m f\"\n  by (force simp add: map_le_def)\n\nlemma map_le_upd[simp]: \"f \\<subseteq>\\<^sub>m g ==> f(a := b) \\<subseteq>\\<^sub>m g(a := b)\"\n  by (fastforce simp add: map_le_def)\n\nlemma map_le_imp_upd_le [simp]: \"m1 \\<subseteq>\\<^sub>m m2 \\<Longrightarrow> m1(x := None) \\<subseteq>\\<^sub>m m2(x \\<mapsto> y)\"\n  by (force simp add: map_le_def)\n\nlemma map_le_upds [simp]:\n  \"f \\<subseteq>\\<^sub>m g \\<Longrightarrow> f(as [\\<mapsto>] bs) \\<subseteq>\\<^sub>m g(as [\\<mapsto>] bs)\"\nproof (induct as arbitrary: f g bs)\n  case (Cons a as)\n  then show ?case\n    by (cases bs) (use Cons in auto)\nqed auto\n\nlemma map_le_implies_dom_le: \"(f \\<subseteq>\\<^sub>m g) \\<Longrightarrow> (dom f \\<subseteq> dom g)\"\n  by (fastforce simp add: map_le_def dom_def)\n\nlemma map_le_refl [simp]: \"f \\<subseteq>\\<^sub>m f\"\n  by (simp add: map_le_def)\n\nlemma map_le_trans[trans]: \"\\<lbrakk> m1 \\<subseteq>\\<^sub>m m2; m2 \\<subseteq>\\<^sub>m m3\\<rbrakk> \\<Longrightarrow> m1 \\<subseteq>\\<^sub>m m3\"\n  by (auto simp add: map_le_def dom_def)\n\nlemma map_le_antisym: \"\\<lbrakk> f \\<subseteq>\\<^sub>m g; g \\<subseteq>\\<^sub>m f \\<rbrakk> \\<Longrightarrow> f = g\"\n  unfolding map_le_def\n  by (metis ext domIff)\n\nlemma map_le_map_add [simp]: \"f \\<subseteq>\\<^sub>m g ++ f\"\n  by (fastforce simp: map_le_def)\n\nlemma map_le_iff_map_add_commute: \"f \\<subseteq>\\<^sub>m f ++ g \\<longleftrightarrow> f ++ g = g ++ f\"\n  by (fastforce simp: map_add_def map_le_def fun_eq_iff split: option.splits)\n\nlemma map_add_le_mapE: \"f ++ g \\<subseteq>\\<^sub>m h \\<Longrightarrow> g \\<subseteq>\\<^sub>m h\"\n  by (fastforce simp: map_le_def map_add_def dom_def)\n\nlemma map_add_le_mapI: \"\\<lbrakk> f \\<subseteq>\\<^sub>m h; g \\<subseteq>\\<^sub>m h \\<rbrakk> \\<Longrightarrow> f ++ g \\<subseteq>\\<^sub>m h\"\n  by (auto simp: map_le_def map_add_def dom_def split: option.splits)\n\nlemma map_add_subsumed1: \"f \\<subseteq>\\<^sub>m g \\<Longrightarrow> f++g = g\"\nby (simp add: map_add_le_mapI map_le_antisym)\n\nlemma map_add_subsumed2: \"f \\<subseteq>\\<^sub>m g \\<Longrightarrow> g++f = g\"\nby (metis map_add_subsumed1 map_le_iff_map_add_commute)\n\nlemma dom_eq_singleton_conv: \"dom f = {x} \\<longleftrightarrow> (\\<exists>v. f = [x \\<mapsto> v])\"\n  (is \"?lhs \\<longleftrightarrow> ?rhs\")\nproof\n  assume ?rhs\n  then show ?lhs by (auto split: if_split_asm)\nnext\n  assume ?lhs\n  then obtain v where v: \"f x = Some v\" by auto\n  show ?rhs\n  proof\n    show \"f = [x \\<mapsto> v]\"\n    proof (rule map_le_antisym)\n      show \"[x \\<mapsto> v] \\<subseteq>\\<^sub>m f\"\n        using v by (auto simp add: map_le_def)\n      show \"f \\<subseteq>\\<^sub>m [x \\<mapsto> v]\"\n        using \\<open>dom f = {x}\\<close> \\<open>f x = Some v\\<close> by (auto simp add: map_le_def)\n    qed\n  qed\nqed\n\nlemma map_add_eq_empty_iff[simp]:\n  \"(f++g = empty) \\<longleftrightarrow> f = empty \\<and> g = empty\"\nby (metis map_add_None)\n\nlemma empty_eq_map_add_iff[simp]:\n  \"(empty = f++g) \\<longleftrightarrow> f = empty \\<and> g = empty\"\nby(subst map_add_eq_empty_iff[symmetric])(rule eq_commute)\n\n\nsubsection \\<open>Various\\<close>\n\nlemma set_map_of_compr:\n  assumes distinct: \"distinct (map fst xs)\"\n  shows \"set xs = {(k, v). map_of xs k = Some v}\"\n  using assms\nproof (induct xs)\n  case Nil\n  then show ?case by simp\nnext\n  case (Cons x xs)\n  obtain k v where \"x = (k, v)\" by (cases x) blast\n  with Cons.prems have \"k \\<notin> dom (map_of xs)\"\n    by (simp add: dom_map_of_conv_image_fst)\n  then have *: \"insert (k, v) {(k, v). map_of xs k = Some v} =\n    {(k', v'). (map_of xs(k \\<mapsto> v)) k' = Some v'}\"\n    by (auto split: if_splits)\n  from Cons have \"set xs = {(k, v). map_of xs k = Some v}\" by simp\n  with * \\<open>x = (k, v)\\<close> show ?case by simp\nqed\n\nlemma eq_key_imp_eq_value:\n  \"v1 = v2\"\n  if \"distinct (map fst xs)\" \"(k, v1) \\<in> set xs\" \"(k, v2) \\<in> set xs\"\nproof -\n  from that have \"inj_on fst (set xs)\"\n    by (simp add: distinct_map)\n  moreover have \"fst (k, v1) = fst (k, v2)\"\n    by simp\n  ultimately have \"(k, v1) = (k, v2)\"\n    by (rule inj_onD) (fact that)+\n  then show ?thesis\n    by simp\nqed\n\nlemma map_of_inject_set:\n  assumes distinct: \"distinct (map fst xs)\" \"distinct (map fst ys)\"\n  shows \"map_of xs = map_of ys \\<longleftrightarrow> set xs = set ys\" (is \"?lhs \\<longleftrightarrow> ?rhs\")\nproof\n  assume ?lhs\n  moreover from \\<open>distinct (map fst xs)\\<close> have \"set xs = {(k, v). map_of xs k = Some v}\"\n    by (rule set_map_of_compr)\n  moreover from \\<open>distinct (map fst ys)\\<close> have \"set ys = {(k, v). map_of ys k = Some v}\"\n    by (rule set_map_of_compr)\n  ultimately show ?rhs by simp\nnext\n  assume ?rhs show ?lhs\n  proof\n    fix k\n    show \"map_of xs k = map_of ys k\"\n    proof (cases \"map_of xs k\")\n      case None\n      with \\<open>?rhs\\<close> have \"map_of ys k = None\"\n        by (simp add: map_of_eq_None_iff)\n      with None show ?thesis by simp\n    next\n      case (Some v)\n      with distinct \\<open>?rhs\\<close> have \"map_of ys k = Some v\"\n        by simp\n      with Some show ?thesis by simp\n    qed\n  qed\nqed\n\nlemma finite_Map_induct[consumes 1, case_names empty update]:\n  assumes \"finite (dom m)\"\n  assumes \"P Map.empty\"\n  assumes \"\\<And>k v m. finite (dom m) \\<Longrightarrow> k \\<notin> dom m \\<Longrightarrow> P m \\<Longrightarrow> P (m(k \\<mapsto> v))\"\n  shows \"P m\"\n  using assms(1)\nproof(induction \"dom m\" arbitrary: m rule: finite_induct)\n  case empty\n  then show ?case using assms(2) unfolding dom_def by simp\nnext\n  case (insert x F) \n  then have \"finite (dom (m(x:=None)))\" \"x \\<notin> dom (m(x:=None))\" \"P (m(x:=None))\"\n    by (metis Diff_insert_absorb dom_fun_upd)+\n  with assms(3)[OF this] show ?case\n    by (metis fun_upd_triv fun_upd_upd option.exhaust)\nqed\n\nhide_const (open) Map.empty Map.graph\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/Map.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8499711832583696, "lm_q2_score": 0.8479677526147223, "lm_q1q2_score": 0.720748154054876}}
{"text": "(*  Title:     HOL/Probability/Weak_Convergence.thy\n    Authors:   Jeremy Avigad (CMU), Johannes H\u00f6lzl (TUM)\n*)\n\nsection \\<open>Weak Convergence of Functions and Distributions\\<close>\n\ntext \\<open>Properties of weak convergence of functions and measures, including the portmanteau theorem.\\<close>\n\ntheory Weak_Convergence\n  imports Distribution_Functions\nbegin\n\nsection \\<open>Weak Convergence of Functions\\<close>\n\ndefinition\n  weak_conv :: \"(nat \\<Rightarrow> (real \\<Rightarrow> real)) \\<Rightarrow> (real \\<Rightarrow> real) \\<Rightarrow> bool\"\nwhere\n  \"weak_conv F_seq F \\<equiv> \\<forall>x. isCont F x \\<longrightarrow> (\\<lambda>n. F_seq n x) \\<longlonglongrightarrow> F x\"\n\nsection \\<open>Weak Convergence of Distributions\\<close>\n\ndefinition\n  weak_conv_m :: \"(nat \\<Rightarrow> real measure) \\<Rightarrow> real measure \\<Rightarrow> bool\"\nwhere\n  \"weak_conv_m M_seq M \\<equiv> weak_conv (\\<lambda>n. cdf (M_seq n)) (cdf M)\"\n\nsection \\<open>Skorohod's theorem\\<close>\n\nlocale right_continuous_mono =\n  fixes f :: \"real \\<Rightarrow> real\" and a b :: real\n  assumes cont: \"\\<And>x. continuous (at_right x) f\"\n  assumes mono: \"mono f\"\n  assumes bot: \"(f \\<longlongrightarrow> a) at_bot\"\n  assumes top: \"(f \\<longlongrightarrow> b) at_top\"\nbegin\n\nabbreviation I :: \"real \\<Rightarrow> real\" where\n  \"I \\<omega> \\<equiv> Inf {x. \\<omega> \\<le> f x}\"\n\nlemma pseudoinverse: assumes \"a < \\<omega>\" \"\\<omega> < b\" shows \"\\<omega> \\<le> f x \\<longleftrightarrow> I \\<omega> \\<le> x\"\nproof\n  let ?F = \"{x. \\<omega> \\<le> f x}\"\n  obtain y where \"f y < \\<omega>\"\n    by (metis eventually_happens' trivial_limit_at_bot_linorder order_tendstoD(2) bot \\<open>a < \\<omega>\\<close>)\n  with mono have bdd: \"bdd_below ?F\"\n    by (auto intro!: bdd_belowI[of _ y] elim: mono_invE[OF _ less_le_trans])\n\n  have ne: \"?F \\<noteq> {}\"\n    using order_tendstoD(1)[OF top \\<open>\\<omega> < b\\<close>]\n    by (auto dest!: eventually_happens'[OF trivial_limit_at_top_linorder] intro: less_imp_le)\n\n  show \"\\<omega> \\<le> f x \\<Longrightarrow> I \\<omega> \\<le> x\"\n    by (auto intro!: cInf_lower bdd)\n\n  { assume *: \"I \\<omega> \\<le> x\"\n    have \"\\<omega> \\<le> (INF s\\<in>{x. \\<omega> \\<le> f x}. f s)\"\n      by (rule cINF_greatest[OF ne]) auto\n    also have \"\\<dots> = f (I \\<omega>)\"\n      using continuous_at_Inf_mono[OF mono cont ne bdd] ..\n    also have \"\\<dots> \\<le> f x\"\n      using * by (rule monoD[OF \\<open>mono f\\<close>])\n    finally show \"\\<omega> \\<le> f x\" . }\nqed\n\nlemma pseudoinverse': \"\\<forall>\\<omega>\\<in>{a<..<b}. \\<forall>x. \\<omega> \\<le> f x \\<longleftrightarrow> I \\<omega> \\<le> x\"\n  by (intro ballI allI impI pseudoinverse) auto\n\nlemma mono_I: \"mono_on {a <..< b} I\"\n  unfolding mono_on_def by (metis order.trans order.refl pseudoinverse')\n\nend\n\nlocale cdf_distribution = real_distribution\nbegin\n\nabbreviation \"C \\<equiv> cdf M\"\n\nsublocale right_continuous_mono C 0 1\n  by standard\n     (auto intro: cdf_nondecreasing cdf_is_right_cont cdf_lim_at_top_prob cdf_lim_at_bot monoI)\n\nlemma measurable_C[measurable]: \"C \\<in> borel_measurable borel\"\n  by (intro borel_measurable_mono mono)\n\nlemma measurable_CI[measurable]: \"I \\<in> borel_measurable (restrict_space borel {0<..<1})\"\n  by (intro borel_measurable_mono_on_fnc mono_I)\n\nlemma emeasure_distr_I: \"emeasure (distr (restrict_space lborel {0<..<1::real}) borel I) UNIV = 1\"\n  by (simp add: emeasure_distr space_restrict_space emeasure_restrict_space )\n\nlemma distr_I_eq_M: \"distr (restrict_space lborel {0<..<1::real}) borel I = M\" (is \"?I = _\")\nproof (intro cdf_unique ext)\n  let ?\\<Omega> = \"restrict_space lborel {0<..<1}::real measure\"\n  interpret \\<Omega>: prob_space ?\\<Omega>\n    by (auto simp add: emeasure_restrict_space space_restrict_space intro!: prob_spaceI)\n  show \"real_distribution ?I\"\n    by auto\n\n  fix x\n  have \"cdf ?I x = measure lborel {\\<omega>\\<in>{0<..<1}. \\<omega> \\<le> C x}\"\n    by (subst cdf_def)\n       (auto simp: pseudoinverse[symmetric] measure_distr space_restrict_space measure_restrict_space\n             intro!: arg_cong2[where f=\"measure\"])\n  also have \"\\<dots> = measure lborel {0 <..< C x}\"\n    using cdf_bounded_prob[of x] AE_lborel_singleton[of \"C x\"]\n    by (auto intro!: arg_cong[where f=enn2real] emeasure_eq_AE simp: measure_def)\n  also have \"\\<dots> = C x\"\n    by (simp add: cdf_nonneg)\n  finally show \"cdf (distr ?\\<Omega> borel I) x = C x\" .\nqed standard\n\nend\n\ncontext\n  fixes \\<mu> :: \"nat \\<Rightarrow> real measure\"\n    and M :: \"real measure\"\n  assumes \\<mu>: \"\\<And>n. real_distribution (\\<mu> n)\"\n  assumes M: \"real_distribution M\"\n  assumes \\<mu>_to_M: \"weak_conv_m \\<mu> M\"\nbegin\n\n(* state using obtains? *)\ntheorem Skorohod:\n \"\\<exists> (\\<Omega> :: real measure) (Y_seq :: nat \\<Rightarrow> real \\<Rightarrow> real) (Y :: real \\<Rightarrow> real).\n    prob_space \\<Omega> \\<and>\n    (\\<forall>n. Y_seq n \\<in> measurable \\<Omega> borel) \\<and>\n    (\\<forall>n. distr \\<Omega> borel (Y_seq n) = \\<mu> n) \\<and>\n    Y \\<in> measurable \\<Omega> lborel \\<and>\n    distr \\<Omega> borel Y = M \\<and>\n    (\\<forall>x \\<in> space \\<Omega>. (\\<lambda>n. Y_seq n x) \\<longlonglongrightarrow> Y x)\"\nproof -\n  interpret \\<mu>: cdf_distribution \"\\<mu> n\" for n\n    unfolding cdf_distribution_def by (rule \\<mu>)\n  interpret M: cdf_distribution M\n    unfolding cdf_distribution_def by (rule M)\n\n  have conv: \"measure M {x} = 0 \\<Longrightarrow> (\\<lambda>n. \\<mu>.C n x) \\<longlonglongrightarrow> M.C x\" for x\n    using \\<mu>_to_M M.isCont_cdf by (auto simp: weak_conv_m_def weak_conv_def)\n\n  let ?\\<Omega> = \"restrict_space lborel {0<..<1} :: real measure\"\n  have \"prob_space ?\\<Omega>\"\n    by (auto simp: space_restrict_space emeasure_restrict_space intro!: prob_spaceI)\n  interpret \\<Omega>: prob_space ?\\<Omega>\n    by fact\n\n  have Y_distr: \"distr ?\\<Omega> borel M.I = M\"\n    by (rule M.distr_I_eq_M)\n\n  have Y_cts_cnv: \"(\\<lambda>n. \\<mu>.I n \\<omega>) \\<longlonglongrightarrow> M.I \\<omega>\"\n    if \\<omega>: \"\\<omega> \\<in> {0<..<1}\" \"isCont M.I \\<omega>\" for \\<omega> :: real\n  proof (intro limsup_le_liminf_real)\n    show \"liminf (\\<lambda>n. \\<mu>.I n \\<omega>) \\<ge> M.I \\<omega>\"\n      unfolding le_Liminf_iff\n    proof safe\n      fix B :: ereal assume B: \"B < M.I \\<omega>\"\n      then show \"\\<forall>\\<^sub>F n in sequentially. B < \\<mu>.I n \\<omega>\"\n      proof (cases B)\n        case (real r)\n        with B have r: \"r < M.I \\<omega>\"\n          by simp\n        then obtain x where x: \"r < x\" \"x < M.I \\<omega>\" \"measure M {x} = 0\"\n          using open_minus_countable[OF M.countable_support, of \"{r<..<M.I \\<omega>}\"] by auto\n        then have Fx_less: \"M.C x < \\<omega>\"\n          using M.pseudoinverse' \\<omega> not_less by blast\n\n        have \"\\<forall>\\<^sub>F n in sequentially. \\<mu>.C n x < \\<omega>\"\n          using order_tendstoD(2)[OF conv[OF x(3)] Fx_less] .\n        then have \"\\<forall>\\<^sub>F n in sequentially. x < \\<mu>.I n \\<omega>\"\n          by eventually_elim (insert \\<omega> \\<mu>.pseudoinverse[symmetric], simp add: not_le[symmetric])\n        then show ?thesis\n          by eventually_elim (insert x(1), simp add: real)\n      qed auto\n    qed\n\n    have *: \"limsup (\\<lambda>n. \\<mu>.I n \\<omega>) \\<le> M.I \\<omega>'\"\n      if \\<omega>': \"0 < \\<omega>'\" \"\\<omega>' < 1\" \"\\<omega> < \\<omega>'\" for \\<omega>' :: real\n    proof (rule dense_ge_bounded)\n      fix B' assume \"ereal (M.I \\<omega>') < B'\" \"B' < ereal (M.I \\<omega>' + 1)\"\n      then obtain B where \"M.I \\<omega>' < B\" and [simp]: \"B' = ereal B\"\n        by (cases B') auto\n      then obtain y where y: \"M.I \\<omega>' < y\" \"y < B\" \"measure M {y} = 0\"\n        using open_minus_countable[OF M.countable_support, of \"{M.I \\<omega>'<..<B}\"] by auto\n      then have \"\\<omega>' \\<le> M.C (M.I \\<omega>')\"\n        using M.pseudoinverse' \\<omega>' by (metis greaterThanLessThan_iff order_refl)\n      also have \"... \\<le> M.C y\"\n        using M.mono y unfolding mono_def by auto\n      finally have Fy_gt: \"\\<omega> < M.C y\"\n        using \\<omega>'(3) by simp\n\n      have \"\\<forall>\\<^sub>F n in sequentially. \\<omega> \\<le> \\<mu>.C n y\"\n        using order_tendstoD(1)[OF conv[OF y(3)] Fy_gt] by eventually_elim (rule less_imp_le)\n      then have 2: \"\\<forall>\\<^sub>F n in sequentially. \\<mu>.I n \\<omega> \\<le> ereal y\"\n        by simp (subst \\<mu>.pseudoinverse'[rule_format, OF \\<omega>(1), symmetric])\n      then show \"limsup (\\<lambda>n. \\<mu>.I n \\<omega>) \\<le> B'\"\n        using \\<open>y < B\\<close>\n        by (intro Limsup_bounded[rotated]) (auto intro: le_less_trans elim: eventually_mono)\n    qed simp\n\n    have **: \"(M.I \\<longlongrightarrow> ereal (M.I \\<omega>)) (at_right \\<omega>)\"\n      using \\<omega>(2) by (auto intro: tendsto_within_subset simp: continuous_at)\n    show \"limsup (\\<lambda>n. \\<mu>.I n \\<omega>) \\<le> M.I \\<omega>\"\n      using \\<omega>\n      by (intro tendsto_lowerbound[OF **])\n         (auto intro!: exI[of _ 1] * simp: eventually_at_right[of _ 1])\n  qed\n\n  let ?D = \"{\\<omega>\\<in>{0<..<1}. \\<not> isCont M.I \\<omega>}\"\n  have D_countable: \"countable ?D\"\n    using mono_on_ctble_discont[OF M.mono_I] by (simp add: at_within_open[of _ \"{0 <..< 1}\"] cong: conj_cong)\n  hence D: \"emeasure ?\\<Omega> ?D = 0\"\n    using emeasure_lborel_countable[OF D_countable]\n    by (subst emeasure_restrict_space) auto\n\n  define Y' where \"Y' \\<omega> = (if \\<omega> \\<in> ?D then 0 else M.I \\<omega>)\" for \\<omega>\n  have Y'_AE: \"AE \\<omega> in ?\\<Omega>. Y' \\<omega> = M.I \\<omega>\"\n    by (rule AE_I [OF _ D]) (auto simp: space_restrict_space sets_restrict_space_iff Y'_def)\n\n  define Y_seq' where \"Y_seq' n \\<omega> = (if \\<omega> \\<in> ?D then 0 else \\<mu>.I n \\<omega>)\" for n \\<omega>\n  have Y_seq'_AE: \"\\<And>n. AE \\<omega> in ?\\<Omega>. Y_seq' n \\<omega> = \\<mu>.I n \\<omega>\"\n    by (rule AE_I [OF _ D]) (auto simp: space_restrict_space sets_restrict_space_iff Y_seq'_def)\n\n  have Y'_cnv: \"\\<forall>\\<omega>\\<in>{0<..<1}. (\\<lambda>n. Y_seq' n \\<omega>) \\<longlonglongrightarrow> Y' \\<omega>\"\n    by (auto simp: Y'_def Y_seq'_def Y_cts_cnv)\n\n  have [simp]: \"Y_seq' n \\<in> borel_measurable ?\\<Omega>\" for n\n    by (rule measurable_discrete_difference[of \"\\<mu>.I n\" _ _ ?D])\n       (insert \\<mu>.measurable_CI[of n] D_countable, auto simp: sets_restrict_space Y_seq'_def)\n  moreover have \"distr ?\\<Omega> borel (Y_seq' n) = \\<mu> n\" for n\n    using \\<mu>.distr_I_eq_M [of n] Y_seq'_AE [of n]\n    by (subst distr_cong_AE[where f = \"Y_seq' n\" and g = \"\\<mu>.I n\"], auto)\n  moreover have [simp]: \"Y' \\<in> borel_measurable ?\\<Omega>\"\n    by (rule measurable_discrete_difference[of M.I _ _ ?D])\n       (insert M.measurable_CI D_countable, auto simp: sets_restrict_space Y'_def)\n  moreover have \"distr ?\\<Omega> borel Y' = M\"\n    using M.distr_I_eq_M Y'_AE\n    by (subst distr_cong_AE[where f = Y' and g = M.I], auto)\n  ultimately have \"prob_space ?\\<Omega> \\<and> (\\<forall>n. Y_seq' n \\<in> borel_measurable ?\\<Omega>) \\<and>\n    (\\<forall>n. distr ?\\<Omega> borel (Y_seq' n) = \\<mu> n) \\<and> Y' \\<in> measurable ?\\<Omega> lborel \\<and> distr ?\\<Omega> borel Y' = M \\<and>\n    (\\<forall>x\\<in>space ?\\<Omega>. (\\<lambda>n. Y_seq' n x) \\<longlonglongrightarrow> Y' x)\"\n    using Y'_cnv \\<open>prob_space ?\\<Omega>\\<close> by (auto simp: space_restrict_space)\n  thus ?thesis by metis\nqed\n\ntext \\<open>\n  The Portmanteau theorem, that is, the equivalence of various definitions of weak convergence.\n\\<close>\n\ntheorem weak_conv_imp_bdd_ae_continuous_conv:\n  fixes\n    f :: \"real \\<Rightarrow> 'a::{banach, second_countable_topology}\"\n  assumes\n    discont_null: \"M ({x. \\<not> isCont f x}) = 0\" and\n    f_bdd: \"\\<And>x. norm (f x) \\<le> B\" and\n    [measurable]: \"f \\<in> borel_measurable borel\"\n  shows\n    \"(\\<lambda> n. integral\\<^sup>L (\\<mu> n) f) \\<longlonglongrightarrow> integral\\<^sup>L M f\"\nproof -\n  have \"0 \\<le> B\"\n    using norm_ge_zero f_bdd by (rule order_trans)\n  note Skorohod\n  then obtain Omega Y_seq Y where\n    ps_Omega [simp]: \"prob_space Omega\" and\n    Y_seq_measurable [measurable]: \"\\<And>n. Y_seq n \\<in> borel_measurable Omega\" and\n    distr_Y_seq: \"\\<And>n. distr Omega borel (Y_seq n) = \\<mu> n\" and\n    Y_measurable [measurable]: \"Y \\<in> borel_measurable Omega\" and\n    distr_Y: \"distr Omega borel Y = M\" and\n    YnY: \"\\<And>x :: real. x \\<in> space Omega \\<Longrightarrow> (\\<lambda>n. Y_seq n x) \\<longlonglongrightarrow> Y x\"  by force\n  interpret prob_space Omega by fact\n  have *: \"emeasure Omega (Y -` {x. \\<not> isCont f x} \\<inter> space Omega) = 0\"\n    by (subst emeasure_distr [symmetric, where N=borel]) (auto simp: distr_Y discont_null)\n  have *: \"AE x in Omega. (\\<lambda>n. f (Y_seq n x)) \\<longlonglongrightarrow> f (Y x)\"\n    by (rule AE_I [OF _ *]) (auto intro: isCont_tendsto_compose YnY)\n  show ?thesis\n    by (auto intro!: integral_dominated_convergence[where w=\"\\<lambda>x. B\"]\n             simp: f_bdd * integral_distr distr_Y_seq [symmetric] distr_Y [symmetric])\nqed\n\ntheorem weak_conv_imp_integral_bdd_continuous_conv:\n  fixes f :: \"real \\<Rightarrow> 'a::{banach, second_countable_topology}\"\n  assumes\n    \"\\<And>x. isCont f x\" and\n    \"\\<And>x. norm (f x) \\<le> B\"\n  shows\n    \"(\\<lambda> n. integral\\<^sup>L (\\<mu> n) f) \\<longlonglongrightarrow> integral\\<^sup>L M f\"\n  using assms\n  by (intro weak_conv_imp_bdd_ae_continuous_conv)\n     (auto intro!: borel_measurable_continuous_onI continuous_at_imp_continuous_on)\n\ntheorem weak_conv_imp_continuity_set_conv:\n  fixes f :: \"real \\<Rightarrow> real\"\n  assumes [measurable]: \"A \\<in> sets borel\" and \"M (frontier A) = 0\"\n  shows \"(\\<lambda>n. measure (\\<mu> n) A) \\<longlonglongrightarrow> measure M A\"\nproof -\n  interpret M: real_distribution M by fact\n  interpret \\<mu>: real_distribution \"\\<mu> n\" for n by fact\n\n  have \"(\\<lambda>n. (\\<integral>x. indicator A x \\<partial>\\<mu> n) :: real) \\<longlonglongrightarrow> (\\<integral>x. indicator A x \\<partial>M)\"\n    by (intro weak_conv_imp_bdd_ae_continuous_conv[where B=1])\n       (auto intro: assms simp: isCont_indicator)\n  then show ?thesis\n    by simp\nqed\n\nend\n\ndefinition\n  cts_step :: \"real \\<Rightarrow> real \\<Rightarrow> real \\<Rightarrow> real\"\nwhere\n  \"cts_step a b x \\<equiv> if x \\<le> a then 1 else if x \\<ge> b then 0 else (b - x) / (b - a)\"\n\nlemma cts_step_uniformly_continuous:\n  assumes [arith]: \"a < b\"\n  shows \"uniformly_continuous_on UNIV (cts_step a b)\"\n  unfolding uniformly_continuous_on_def\nproof clarsimp\n  fix e :: real assume [arith]: \"0 < e\"\n  let ?d = \"min (e * (b - a)) (b - a)\"\n  have \"?d > 0\"\n    by (auto simp add: field_simps)\n  moreover have \"dist x' x < ?d \\<Longrightarrow> dist (cts_step a b x') (cts_step a b x) < e\" for x x'\n    by (auto simp: dist_real_def divide_simps cts_step_def)\n  ultimately show \"\\<exists>d > 0. \\<forall>x x'. dist x' x < d \\<longrightarrow> dist (cts_step a b x') (cts_step a b x) < e\"\n    by blast\nqed\n\nlemma (in real_distribution) integrable_cts_step: \"a < b \\<Longrightarrow> integrable M (cts_step a b)\"\n  by (rule integrable_const_bound [of _ 1]) (auto simp: cts_step_def[abs_def])\n\nlemma (in real_distribution) cdf_cts_step:\n  assumes [arith]: \"x < y\"\n  shows \"cdf M x \\<le> integral\\<^sup>L M (cts_step x y)\" and \"integral\\<^sup>L M (cts_step x y) \\<le> cdf M y\"\nproof -\n  have \"cdf M x = integral\\<^sup>L M (indicator {..x})\"\n    by (simp add: cdf_def)\n  also have \"\\<dots> \\<le> expectation (cts_step x y)\"\n    by (intro integral_mono integrable_cts_step)\n       (auto simp: cts_step_def less_top[symmetric] split: split_indicator)\n  finally show \"cdf M x \\<le> expectation (cts_step x y)\" .\nnext\n  have \"expectation (cts_step x y) \\<le> integral\\<^sup>L M (indicator {..y})\"\n    by (intro integral_mono integrable_cts_step)\n       (auto simp: cts_step_def less_top[symmetric] split: split_indicator)\n  also have \"\\<dots> = cdf M y\"\n    by (simp add: cdf_def)\n  finally show \"expectation (cts_step x y) \\<le> cdf M y\" .\nqed\n\ncontext\n  fixes M_seq :: \"nat \\<Rightarrow> real measure\"\n    and M :: \"real measure\"\n  assumes distr_M_seq [simp]: \"\\<And>n. real_distribution (M_seq n)\"\n  assumes distr_M [simp]: \"real_distribution M\"\nbegin\n\ntheorem continuity_set_conv_imp_weak_conv:\n  fixes f :: \"real \\<Rightarrow> real\"\n  assumes *: \"\\<And>A. A \\<in> sets borel \\<Longrightarrow> M (frontier A) = 0 \\<Longrightarrow> (\\<lambda> n. (measure (M_seq n) A)) \\<longlonglongrightarrow> measure M A\"\n  shows \"weak_conv_m M_seq M\"\nproof -\n  interpret real_distribution M by simp\n  show ?thesis\n    by (auto intro!: * simp: frontier_real_atMost isCont_cdf emeasure_eq_measure weak_conv_m_def weak_conv_def cdf_def2)\nqed\n\ntheorem integral_cts_step_conv_imp_weak_conv:\n  assumes integral_conv: \"\\<And>x y. x < y \\<Longrightarrow> (\\<lambda>n. integral\\<^sup>L (M_seq n) (cts_step x y)) \\<longlonglongrightarrow> integral\\<^sup>L M (cts_step x y)\"\n  shows \"weak_conv_m M_seq M\"\n  unfolding weak_conv_m_def weak_conv_def\nproof (clarsimp)\n  interpret real_distribution M by (rule distr_M)\n  fix x assume \"isCont (cdf M) x\"\n  hence left_cont: \"continuous (at_left x) (cdf M)\"\n    unfolding continuous_at_split ..\n  { fix y :: real assume [arith]: \"x < y\"\n    have \"limsup (\\<lambda>n. cdf (M_seq n) x) \\<le> limsup (\\<lambda>n. integral\\<^sup>L (M_seq n) (cts_step x y))\"\n      by (auto intro!: Limsup_mono always_eventually real_distribution.cdf_cts_step)\n    also have \"\\<dots> = integral\\<^sup>L M (cts_step x y)\"\n      by (intro lim_imp_Limsup) (auto intro: integral_conv)\n    also have \"\\<dots> \\<le> cdf M y\"\n      by (simp add: cdf_cts_step)\n    finally have \"limsup (\\<lambda>n. cdf (M_seq n) x) \\<le> cdf M y\" .\n  } note * = this\n  { fix y :: real assume [arith]: \"x > y\"\n    have \"cdf M y \\<le> ereal (integral\\<^sup>L M (cts_step y x))\"\n      by (simp add: cdf_cts_step)\n    also have \"\\<dots> = liminf (\\<lambda>n. integral\\<^sup>L (M_seq n) (cts_step y x))\"\n      by (intro lim_imp_Liminf[symmetric]) (auto intro: integral_conv)\n    also have \"\\<dots> \\<le> liminf (\\<lambda>n. cdf (M_seq n) x)\"\n      by (auto intro!: Liminf_mono always_eventually real_distribution.cdf_cts_step)\n    finally have \"liminf (\\<lambda>n. cdf (M_seq n) x) \\<ge> cdf M y\" .\n  } note ** = this\n\n  have \"limsup (\\<lambda>n. cdf (M_seq n) x) \\<le> cdf M x\"\n  proof (rule tendsto_lowerbound)\n    show \"\\<forall>\\<^sub>F i in at_right x. limsup (\\<lambda>xa. ereal (cdf (M_seq xa) x)) \\<le> ereal (cdf M i)\"\n      by (subst eventually_at_right[of _ \"x + 1\"]) (auto simp: * intro: exI [of _ \"x+1\"])\n  qed (insert cdf_is_right_cont, auto simp: continuous_within)\n  moreover have \"cdf M x \\<le> liminf (\\<lambda>n. cdf (M_seq n) x)\"\n  proof (rule tendsto_upperbound)\n    show \"\\<forall>\\<^sub>F i in at_left x. ereal (cdf M i) \\<le> liminf (\\<lambda>xa. ereal (cdf (M_seq xa) x))\"\n      by (subst eventually_at_left[of \"x - 1\"]) (auto simp: ** intro: exI [of _ \"x-1\"])\n  qed (insert left_cont, auto simp: continuous_within)\n  ultimately show \"(\\<lambda>n. cdf (M_seq n) x) \\<longlonglongrightarrow> cdf M x\"\n    by (elim limsup_le_liminf_real)\nqed\n\ntheorem integral_bdd_continuous_conv_imp_weak_conv:\n  assumes\n    \"\\<And>f. (\\<And>x. isCont f x) \\<Longrightarrow> (\\<And>x. abs (f x) \\<le> 1) \\<Longrightarrow> (\\<lambda>n. integral\\<^sup>L (M_seq n) f::real) \\<longlonglongrightarrow> integral\\<^sup>L M f\"\n  shows\n    \"weak_conv_m M_seq M\"\n  apply (rule integral_cts_step_conv_imp_weak_conv [OF assms])\n  apply (rule continuous_on_interior)\n  apply (rule uniformly_continuous_imp_continuous)\n  apply (rule cts_step_uniformly_continuous)\n  apply (auto simp: cts_step_def)\n  done\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/Probability/Weak_Convergence.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8840392848011833, "lm_q2_score": 0.8152324938410784, "lm_q1q2_score": 0.7206975508019521}}
{"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(* your definition/proof here *)\n\nfun ord :: \"int tree \\<Rightarrow> bool\"  where\n(* your definition/proof here *)\n\ntext\\<open> 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(* 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(* your definition/proof here *)\n\ntheorem ord_ins: \"ord t \\<Longrightarrow> ord(ins i t)\"\n(* your definition/proof here *)\n\ntext\\<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(* your definition/proof here *)\n\ntext \\<open> and prove \\<close>\n\nlemma \"palindrome xs \\<Longrightarrow> rev xs = xs\"\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' r x y \\<Longrightarrow> star r x y\"\n(* your definition/proof here *)\n\n\n\nlemma \"star r x y \\<Longrightarrow> star' r x y\"\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\n(* your definition/proof here *)\n\ntext\\<open>\nCorrect and prove the following claim:\n\\<close>\n\nlemma \"star r x y \\<Longrightarrow> iter r n x y\"\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 \\<open>\\<close>@{text \"(\"}'' and  \\<open>\\<close>@{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\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\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\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\\<open>\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\\<close>\n\ninductive ok :: \"nat \\<Rightarrow> instr list \\<Rightarrow> nat \\<Rightarrow> bool\" where\n(* your definition/proof here *)\n\ntext\\<open>\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: \\<close>\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 \\<open> Prove that @{text ok} correctly computes the final stack size: \\<close>\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 \\<open>\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\\<close>\n\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/Chapter4.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.815232489352, "lm_q2_score": 0.884039278690883, "lm_q1q2_score": 0.720697541852115}}
{"text": "theory Kleene_Fixed_Point\n  imports Complete_Relations\nbegin\n\n\nsection \\<open>Iterative Fixed Point Theorem\\<close>\n\ntext \\<open>Kleene's fixed-point theorem states that,\nfor a pointed directed complete partial order $\\tp{A,\\SLE}$\nand a Scott-continuous map $f: A \\to A$,\nthe supremum of $\\set{f^n(\\bot) \\mid n\\in\\Nat}$ exists in $A$ and is a least \nfixed point.\nMashburn \\<^cite>\\<open>\"mashburn83\"\\<close> generalized the result so that\n$\\tp{A,\\SLE}$ is a $\\omega$-complete partial order\nand $f$ is $\\omega$-continuous.\n\nIn this section we further generalize the result and show that\nfor $\\omega$-complete relation $\\tp{A,\\SLE}$\nand for every bottom element $\\bot \\in A$,\nthe set $\\set{f^n(\\bot) \\mid n\\in\\Nat}$ has suprema (not necessarily unique, of \ncourse) and, \nthey are quasi-fixed points.\nMoreover, if $(\\SLE)$ is attractive, then the suprema are precisely the least \nquasi-fixed points.\\<close>\n\nsubsection \\<open>Scott Continuity, $\\omega$-Completeness, $\\omega$-Continuity\\<close>\n\ntext \\<open>In this Section, we formalize $\\omega$-completeness, Scott continuity and $\\omega$-continuity.\nWe then prove that a Scott continuous map is $\\omega$-continuous and that an $\\omega$-continuous \nmap is ``nearly'' monotone.\\<close>\n\ncontext\n  fixes A :: \"'a set\" and less_eq :: \"'a \\<Rightarrow> 'a \\<Rightarrow> bool\" (infix \"\\<sqsubseteq>\" 50)\nbegin\n\ndefinition \"omega_continuous f \\<equiv>\n  f ` A \\<subseteq> A \\<and>\n  (\\<forall>c :: nat \\<Rightarrow> 'a. \\<forall> b \\<in> A.\n  range c \\<subseteq> A \\<longrightarrow>\n  monotone (\\<le>) (\\<sqsubseteq>) c \\<longrightarrow>\n  extreme_bound A (\\<sqsubseteq>) (range c) b \\<longrightarrow> extreme_bound A (\\<sqsubseteq>) (f ` range c) (f b))\"\n\nlemmas omega_continuousI[intro?] =\n  omega_continuous_def[unfolded atomize_eq, THEN iffD2, unfolded conj_imp_eq_imp_imp, rule_format]\n\nlemmas omega_continuousDdom =\n  omega_continuous_def[unfolded atomize_eq, THEN iffD1, unfolded conj_imp_eq_imp_imp, THEN conjunct1]\n\nlemmas omega_continuousD =\n  omega_continuous_def[unfolded atomize_eq, THEN iffD1, unfolded conj_imp_eq_imp_imp, THEN conjunct2, rule_format]\n\nlemmas omega_continuousE[elim] =\n  omega_continuous_def[unfolded atomize_eq, THEN iffD1, elim_format, unfolded conj_imp_eq_imp_imp, rule_format]\n\nlemma omega_continuous_imp_mono_refl:\n  assumes cont: \"omega_continuous f\"\n    and x: \"x \\<in> A\" and y: \"y \\<in> A\"\n    and xy: \"x \\<sqsubseteq> y\" and xx: \"x \\<sqsubseteq> x\" and yy: \"y \\<sqsubseteq> y\"\n  shows \"f x \\<sqsubseteq> f y\"\nproof-\n  define c :: \"nat \\<Rightarrow> 'a\" where \"c \\<equiv> \\<lambda>i. if i = 0 then x else y\"\n  from x y xx xy yy have c: \"range c \\<subseteq> A\" \"monotone (\\<le>) (\\<sqsubseteq>) c\"\n    by (auto simp: c_def intro!: monotoneI)\n  have \"extreme_bound A (\\<sqsubseteq>) (range c) y\" using xy yy x y by (auto simp: c_def)\n  then have fboy: \"extreme_bound A (\\<sqsubseteq>) (f ` range c) (f y)\" using c cont y by auto\n  then show \"f x \\<sqsubseteq> f y\" by (auto simp: c_def)\nqed\n\ndefinition \"scott_continuous f \\<equiv>\n  f ` A \\<subseteq> A \\<and>\n  (\\<forall>X s. X \\<subseteq> A \\<longrightarrow> directed X (\\<sqsubseteq>) \\<longrightarrow> X \\<noteq> {} \\<longrightarrow> extreme_bound A (\\<sqsubseteq>) X s \\<longrightarrow> extreme_bound A (\\<sqsubseteq>) (f ` X) (f s))\"\n\nlemmas scott_continuousI[intro?] =\n  scott_continuous_def[unfolded atomize_eq, THEN iffD2, unfolded conj_imp_eq_imp_imp, rule_format]\n\nlemmas scott_continuousE =\n  scott_continuous_def[unfolded atomize_eq, THEN iffD1, elim_format, unfolded conj_imp_eq_imp_imp, rule_format]\n\nlemma scott_continuous_imp_mono_refl:\n  assumes scott: \"scott_continuous f\"\n    and x: \"x \\<in> A\" and y: \"y \\<in> A\" and xy: \"x \\<sqsubseteq> y\" and yy: \"y \\<sqsubseteq> y\"\n  shows \"f x \\<sqsubseteq> f y\"\nproof-\n  define D where \"D \\<equiv> {x,y}\"\n  from x y xy yy have dir_D: \"D \\<subseteq> A\" \"directed D (\\<sqsubseteq>)\" \"D \\<noteq> {}\"\n    by (auto simp: D_def intro!: bexI[of _ y] directedI)\n  have \"extreme_bound A (\\<sqsubseteq>) D y\" using xy yy x y by (auto simp: D_def)\n  then have fboy: \"extreme_bound A (\\<sqsubseteq>) (f ` D) (f y)\" using dir_D scott by (auto elim!: scott_continuousE)\n  then show \"f x \\<sqsubseteq> f y\" by (auto simp: D_def)\nqed\n\nlemma scott_continuous_imp_omega_continuous:\n  assumes scott: \"scott_continuous f\" shows \"omega_continuous f\"\nproof\n  from scott show \"f ` A \\<subseteq> A\" by (auto elim!: scott_continuousE)\n  fix c :: \"nat \\<Rightarrow> 'a\"\n  assume mono: \"monotone (\\<le>) (\\<sqsubseteq>) c\" and c: \"range c \\<subseteq> A\"\n  from monotone_directed_image[OF mono[folded monotone_on_UNIV] order.directed] scott c\n  show \"extreme_bound A (\\<sqsubseteq>) (range c) b \\<Longrightarrow> extreme_bound A (\\<sqsubseteq>) (f ` range c) (f b)\" for b\n    by (auto elim!: scott_continuousE)\nqed\n\nend\n\nsubsection \\<open>Existence of Iterative Fixed Points\\<close>\n\ntext \\<open>The first part of Kleene's theorem demands to prove that the set \n$\\set{f^n(\\bot) \\mid n \\in \\Nat}$ has a supremum and \nthat all such are quasi-fixed points. We prove this claim without assuming \nanything on the relation $\\SLE$ besides $\\omega$-completeness and one bottom element.\\<close>\n\n(*\nno_notation power (infixr \"^\" 80)\n*)\nnotation compower (\"_^_\"[1000,1000]1000)\n\nlemma mono_funpow: assumes f: \"f ` A \\<subseteq> A\" and mono: \"monotone_on A r r f\"\n  shows \"monotone_on A r r (f^n)\"\nproof (induct n)\n  case 0\n  show ?case using monotone_on_id by (auto simp: id_def)\nnext\n  case (Suc n)\n  with funpow_dom[OF f] show ?case\n    by (auto intro!: monotone_onI monotone_onD[OF mono] elim!:monotone_onE)\nqed\n\nno_notation bot (\"\\<bottom>\")\n\ncontext\n  fixes A and less_eq (infix \"\\<sqsubseteq>\" 50) and bot (\"\\<bottom>\") and f\n  assumes bot: \"\\<bottom> \\<in> A\" \"\\<forall>q \\<in> A. \\<bottom> \\<sqsubseteq> q\"\n  assumes cont: \"omega_continuous A (\\<sqsubseteq>) f\"\nbegin\n\ninterpretation less_eq_notations.\n\nprivate lemma f: \"f ` A \\<subseteq> A\" using cont by auto\n\nprivate abbreviation(input) \"Fn \\<equiv> {f^n \\<bottom> |. n :: nat}\"\n\nprivate lemma fn_ref: \"f^n \\<bottom> \\<sqsubseteq> f^n \\<bottom>\" and fnA: \"f^n \\<bottom> \\<in> A\"\nproof (atomize(full), induct n)\n  case 0\n  from bot show ?case by simp\nnext\n  case (Suc n)\n  then have fn: \"f^n \\<bottom> \\<in> A\" and fnfn: \"f^n \\<bottom> \\<sqsubseteq> f^n \\<bottom>\" by auto\n  from f fn omega_continuous_imp_mono_refl[OF cont fn fn fnfn fnfn fnfn]\n  show ?case by auto\nqed\n\nprivate lemma FnA: \"Fn \\<subseteq> A\" using fnA by auto\n\nprivate lemma fn_monotone: \"monotone (\\<le>) (\\<sqsubseteq>) (\\<lambda>n. f^n \\<bottom>)\"\nproof\n  fix n m :: nat\n  assume \"n \\<le> m\"\n  from le_Suc_ex[OF this] obtain k where m: \"m = n + k\" by auto\n  from bot fn_ref fnA omega_continuous_imp_mono_refl[OF cont]\n  show \"f^n \\<bottom> \\<sqsubseteq> f^m \\<bottom>\" by (unfold m, induct n, auto)\nqed\n\nprivate lemma Fn: \"Fn = range (\\<lambda>n. f^n \\<bottom>)\" by auto\n\ntheorem kleene_qfp:\n  assumes q: \"extreme_bound A (\\<sqsubseteq>) Fn q\"\n  shows \"f q \\<sim> q\"\nproof\n  have fq: \"extreme_bound A (\\<sqsubseteq>) (f ` Fn) (f q)\"\n    apply (unfold Fn)\n    apply (rule omega_continuousD[OF cont])\n    using FnA fn_monotone q by (unfold Fn, auto)\n  with bot have nq: \"f^n \\<bottom> \\<sqsubseteq> f q\" for n\n    by(induct n, auto simp: extreme_bound_iff)\n  then show \"q \\<sqsubseteq> f q\" using f q by blast\n  have \"f (f^n \\<bottom>) \\<in> Fn\" for n by (auto intro!: exI[of _ \"Suc n\"])\n  then have \"f ` Fn \\<subseteq> Fn\" by auto\n  from extreme_bound_mono[OF this fq q]\n  show \"f q \\<sqsubseteq> q\".\nqed\n\nlemma ex_kleene_qfp:\n  assumes comp: \"omega_complete A (\\<sqsubseteq>)\"\n  shows \"\\<exists>p. extreme_bound A (\\<sqsubseteq>) Fn p\" \n  using fn_monotone\n  apply (intro comp[unfolded omega_complete_def, THEN completeD, OF FnA])\n  by fast\n\nsubsection \\<open>Iterative Fixed Points are Least.\\<close>\ntext \\<open>Kleene's theorem also states that the quasi-fixed point found this way is a least one.\nAgain, attractivity is needed to prove this statement.\\<close>\n\nlemma kleene_qfp_is_least:\n  assumes attract: \"\\<forall>q \\<in> A. \\<forall>x \\<in> A. f q \\<sim> q \\<longrightarrow> x \\<sqsubseteq> f q \\<longrightarrow> x \\<sqsubseteq> q\"\n  assumes q: \"extreme_bound A (\\<sqsubseteq>) Fn q\"\n  shows \"extreme {s \\<in> A. f s \\<sim> s} (\\<sqsupseteq>) q\"\nproof(safe intro!: extremeI kleene_qfp[OF q])\n  from q\n  show \"q \\<in> A\" by auto\n  fix c assume c: \"c \\<in> A\" and cqfp: \"f c \\<sim> c\"\n  {\n    fix n::nat\n    have \"f^n \\<bottom> \\<sqsubseteq> c\"\n    proof(induct n)\n      case 0\n      show ?case using bot c by auto\n    next\n      case IH: (Suc n)\n      have \"c \\<sqsubseteq> c\" using attract cqfp c by auto\n      with IH have \"f^(Suc n) \\<bottom> \\<sqsubseteq> f c\"\n        using omega_continuous_imp_mono_refl[OF cont] fn_ref fnA c by auto\n      then show ?case using attract cqfp c fnA by blast\n    qed\n  }\n  then show \"q \\<sqsubseteq> c\" using q c by auto\nqed\n\nlemma kleene_qfp_iff_least:\n  assumes comp: \"omega_complete A (\\<sqsubseteq>)\"\n  assumes attract: \"\\<forall>q \\<in> A. \\<forall>x \\<in> A. f q \\<sim> q \\<longrightarrow> x \\<sqsubseteq> f q \\<longrightarrow> x \\<sqsubseteq> q\"\n  assumes dual_attract: \"\\<forall>p \\<in> A. \\<forall>q \\<in> A. \\<forall>x \\<in> A. p \\<sim> q \\<longrightarrow> q \\<sqsubseteq> x \\<longrightarrow> p \\<sqsubseteq> x\"\n  shows \"extreme_bound A (\\<sqsubseteq>) Fn = extreme {s \\<in> A. f s \\<sim> s} (\\<sqsupseteq>)\"\nproof (intro ext iffI kleene_qfp_is_least[OF attract])\n  fix q\n  assume q: \"extreme {s \\<in> A. f s \\<sim> s} (\\<sqsupseteq>) q\"\n  from q have qA: \"q \\<in> A\" by auto\n  from q have qq: \"q \\<sqsubseteq> q\" by auto\n  from q have fqq: \"f q \\<sim> q\" by auto\n  from ex_kleene_qfp[OF comp]\n  obtain k where k: \"extreme_bound A (\\<sqsubseteq>) Fn k\" by auto\n  have qk: \"q \\<sim> k\"\n  proof\n    from kleene_qfp[OF k] q k\n    show \"q \\<sqsubseteq> k\" by auto\n    from kleene_qfp_is_least[OF _ k] q attract\n    show \"k \\<sqsubseteq> q\" by blast\n  qed\n  show \"extreme_bound A (\\<sqsubseteq>) Fn q\"\n  proof (intro extreme_boundI,safe)\n    fix n\n    show \"f^n \\<bottom> \\<sqsubseteq> q\"\n    proof (induct n)\n      case 0\n      from bot q show ?case by auto \n    next\n      case S:(Suc n)\n      from fnA f have fsnbA: \"f (f^n \\<bottom>) \\<in> A\" by auto\n      have fnfn: \"f^n \\<bottom> \\<sqsubseteq> f^n \\<bottom>\" using fn_ref by auto\n      have \"f (f^n \\<bottom>) \\<sqsubseteq> f q\"\n        using omega_continuous_imp_mono_refl[OF cont fnA qA S fnfn qq] by auto\n      then show ?case using fsnbA qA attract fqq by auto\n    qed\n  next\n    fix x\n    assume \"bound Fn (\\<sqsubseteq>) x\" and x: \"x \\<in> A\"\n    with k have kx: \"k \\<sqsubseteq> x\" by auto\n    with dual_attract[rule_format, OF _ _ x qk] q k\n    show \"q \\<sqsubseteq> x\" by auto\n  next\n    from q show \"q \\<in> A\" by auto\n  qed\nqed\n\nend\n\ncontext attractive begin\n\ninterpretation less_eq_notations.\n\ntheorem kleene_qfp_is_dual_extreme:\n  assumes comp: \"omega_complete A (\\<sqsubseteq>)\"\n    and cont: \"omega_continuous A (\\<sqsubseteq>) f\" and bA: \"b \\<in> A\" and bot: \"\\<forall>x \\<in> A. b \\<sqsubseteq> x\"\n  shows \"extreme_bound A (\\<sqsubseteq>) {f^n b |. n :: nat} = extreme {s \\<in> A. f s \\<sim> s} (\\<sqsupseteq>)\"\n  apply (rule kleene_qfp_iff_least[OF bA bot cont comp])\n  using cont[THEN omega_continuousDdom]\n  by (auto dest: sym_order_trans order_sym_trans)\n\nend\n\ncorollary(in antisymmetric) kleene_fp:\n  assumes cont: \"omega_continuous A (\\<sqsubseteq>) f\"\n    and b: \"b \\<in> A\" \"\\<forall>x \\<in> A. b \\<sqsubseteq> x\"\n    and p: \"extreme_bound A (\\<sqsubseteq>) {f^n b |. n :: nat} p\"\n  shows \"f p = p\"\n  using kleene_qfp[OF b cont] p cont[THEN omega_continuousDdom]\n  by (auto 2 3 intro!:antisym)\n\nno_notation compower (\"_^_\"[1000,1000]1000)\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/Complete_Non_Orders/Kleene_Fixed_Point.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8840392756357327, "lm_q2_score": 0.8152324848629215, "lm_q1q2_score": 0.7206975353929356}}
{"text": "(*  Title:      Sauer_Shelah_Lemma.thy\n    Author:     Ata Keskin, TU M\u00fcnchen\n*)\n\nsection \"Sauer-Shelah Lemma\"\n\ntheory Sauer_Shelah_Lemma\n  imports Shattering Card_Lemmas Binomial_Lemmas\nbegin                                     \n\nsubsection \\<open>Generalized Sauer-Shelah Lemma\\<close>\n\ntext \\<open>To prove the Sauer-Shelah Lemma, we will first prove a slightly stronger fact that every family\n      @{term \"F\"} shatters at least as many sets as @{term \"card F\"}. We first fix an element @{term \"x \\<in> (\\<Union> F)\"}\n      and consider the subfamily @{term F0} of sets in the family not containing it. By induction, @{term F0} \n      shatters at least as many elements of @{term F} as @{term \"card F0\"}. \n      Next, we consider the subfamily @{term F1} of sets in the family that contain @{term x}.\n      Again, by induction, @{term F1} shatters as many elements of @{term F} as its cardinality. \n      The number of elements of @{term F} shattered by @{term F0} and @{term F1} sum up to at least \n      @{term \"card F0 + card F1 = card F\"}. When a set @{term \"S \\<in> F\"} is shattered by only one of the two subfamilies, say @{term F0}, \n      it contributes one unit to the set @{term \"shattered_by F0\"} and to @{term \"shattered_by F\"}. However, when the set is shattered by \n      both subfamilies, both @{term S} and @{term \"S \\<union> {x}\"} are in @{term \"shattered_by F\"}, so @{term S} contributes two units\n      to @{term \"shattered_by F0 \\<union> shattered_by F1\"}. Therefore, the cardinality of @{term \"shattered_by F\"} \n      is at least equal to the cardinality of @{term \"shattered_by F0 \\<union> shattered_by F1\"}, which is at least @{term \"card F\"}.\\<close>\n\nlemma sauer_shelah_0:\n  fixes F :: \"'a set set\"\n  shows \"finite (\\<Union> F) \\<Longrightarrow> card F \\<le> card (shattered_by F)\"\nproof (induction F rule: measure_induct_rule[of \"card\"])\n  case (less F)\n  note finite_F = finite_UnionD[OF less(2)]\n  note finite_shF = finite_shattered_by[OF less(2)]\n  show ?case\n  proof (cases \"2 \\<le> card F\")\n    case True\n    from obtain_difference_element[OF True] \n    obtain x :: 'a where x_in_Union_F: \"x \\<in> \\<Union>F\" \n                     and x_not_in_Int_F: \"x \\<notin> \\<Inter>F\" by blast\n\n    text \\<open>Define F0 as the subfamily of F containing sets that don't contain @{term x}.\\<close>\n    let ?F0 = \"{S \\<in> F. x \\<notin> S}\"\n    from x_in_Union_F have F0_psubset_F: \"?F0 \\<subset> F\" by blast\n    from F0_psubset_F have F0_in_F: \"?F0 \\<subseteq> F\" by blast\n    from subset_shattered_by[OF F0_in_F] have shF0_subset_shF: \"shattered_by ?F0 \\<subseteq> shattered_by F\" .\n    from F0_in_F have Un_F0_in_Un_F:\"\\<Union> ?F0 \\<subseteq> \\<Union> F\" by blast\n\n    text \\<open>F0 shatters at least as many sets as @{term \"card F0\"} by the induction hypothesis.\\<close>\n    note IH_F0 = less(1)[OF psubset_card_mono[OF finite_F F0_psubset_F] rev_finite_subset[OF less(2) Un_F0_in_Un_F]]\n\n    text \\<open>Define F1 as the subfamily of F containing sets that contain @{term x}.\\<close>\n    let ?F1 = \"{S \\<in> F. x \\<in> S}\"\n    from x_not_in_Int_F have F1_psubset_F: \"?F1 \\<subset> F\" by blast\n    from F1_psubset_F have F1_in_F: \"?F1 \\<subseteq> F\" by blast\n    from subset_shattered_by[OF F1_in_F] have shF1_subset_shF: \"shattered_by ?F1 \\<subseteq> shattered_by F\" .\n    from F1_in_F have Un_F1_in_Un_F:\"\\<Union> ?F1 \\<subseteq> \\<Union> F\" by blast\n\n    text \\<open>F1 shatters at least as many sets as @{term \"card F1\"} by the induction hypothesis.\\<close>\n    note IH_F1 = less(1)[OF psubset_card_mono[OF finite_F F1_psubset_F] rev_finite_subset[OF less(2) Un_F1_in_Un_F]]\n\n    from shF0_subset_shF shF1_subset_shF \n    have shattered_subset: \"(shattered_by ?F0) \\<union> (shattered_by ?F1) \\<subseteq> shattered_by F\" by simp\n\n    text \\<open>There is a set with the same cardinality as the intersection of \n        @{term \"shattered_by F0\"} and @{term \"shattered_by F1\"} which is disjoint from their union and is also contained in @{term \"shattered_by F\"}.\\<close>\n    have f_copies_the_intersection:\n      \"\\<exists>f. inj_on f (shattered_by ?F0 \\<inter> shattered_by ?F1) \\<and>\n       (shattered_by ?F0 \\<union> shattered_by ?F1) \\<inter> (f ` (shattered_by ?F0 \\<inter> shattered_by ?F1)) = {} \\<and>\n       f ` (shattered_by ?F0 \\<inter> shattered_by ?F1) \\<subseteq> shattered_by F\"\n    proof\n      have x_not_in_shattered: \"\\<forall>S\\<in>(shattered_by ?F0) \\<union> (shattered_by ?F1). x \\<notin> S\" unfolding shattered_by_def by blast\n     \n      text \\<open>This set is precisely the image of the intersection under @{term \"insert x\"}.\\<close>\n      let ?f = \"insert x\"\n      have 0: \"inj_on ?f (shattered_by ?F0 \\<inter> shattered_by ?F1)\"\n      proof\n        fix X Y\n        assume x0: \"X \\<in> (shattered_by ?F0 \\<inter> shattered_by ?F1)\" and y0: \"Y \\<in> (shattered_by ?F0 \\<inter> shattered_by ?F1)\"\n               and 0: \"?f X = ?f Y\"\n        from x_not_in_shattered x0 have \"X = ?f X - {x}\" by blast\n        also from 0 have \"... = ?f Y - {x}\" by argo\n        also from x_not_in_shattered y0 have \"... = Y\" by blast\n        finally show \"X = Y\" .\n      qed\n\n      text \\<open>The set is disjoint from the union.\\<close>\n      have 1: \"(shattered_by ?F0 \\<union> shattered_by ?F1) \\<inter> ?f ` (shattered_by ?F0 \\<inter> shattered_by ?F1) = {}\"\n      proof (rule ccontr)\n        assume \"(shattered_by ?F0 \\<union> shattered_by ?F1) \\<inter> ?f ` (shattered_by ?F0 \\<inter> shattered_by ?F1) \\<noteq> {}\"\n        then obtain S where 10: \"S \\<in> (shattered_by ?F0 \\<union> shattered_by ?F1)\" \n                        and 11: \"S \\<in> ?f ` (shattered_by ?F0 \\<inter> shattered_by ?F1)\" by auto\n        from 10 x_not_in_shattered have \"x \\<notin> S\" by blast\n        with 11 show \"False\" by blast\n      qed\n\n      text \\<open>This set is also in @{term \"shattered_by F\"}.\\<close>\n      have 2: \"?f ` (shattered_by ?F0 \\<inter> shattered_by ?F1) \\<subseteq> shattered_by F\"\n      proof \n        fix S_x\n        assume \"S_x \\<in> ?f ` (shattered_by ?F0 \\<inter> shattered_by ?F1)\"\n        then obtain S where 20: \"S \\<in> shattered_by ?F0\" \n                        and 21: \"S \\<in> shattered_by ?F1\" \n                        and 22: \"S_x = ?f S\" by blast\n        from x_not_in_shattered 20 have x_not_in_S: \"x \\<notin> S\" by blast\n\n        from 22 Pow_insert[of x S] have \"Pow S_x = Pow S \\<union> ?f ` Pow S\" by fast\n        also from 20 have \"... = (?F0 \\<inter>* S) \\<union> (?f ` Pow S)\" unfolding shattered_by_def by blast\n        also from 21 have \"... = (?F0 \\<inter>* S) \\<union> (?f ` (?F1 \\<inter>* S))\" unfolding shattered_by_def by force\n        also from insert_IntF[of x S ?F1] have \"... = (?F0 \\<inter>* S) \\<union> (?f ` ?F1 \\<inter>* (?f S))\" by argo\n        also from 22 have \"... = (?F0 \\<inter>* S) \\<union> (?F1 \\<inter>* S_x)\" by blast\n        also from 22 have \"... = (?F0 \\<inter>* S_x) \\<union> (?F1 \\<inter>* S_x)\" by blast\n        also from subset_IntF[OF F0_in_F, of S_x] subset_IntF[OF F1_in_F, of S_x] have \"... \\<subseteq> (F \\<inter>* S_x)\" by blast\n        finally have \"Pow S_x \\<subseteq> (F \\<inter>* S_x)\" .\n        thus \"S_x \\<in> shattered_by F\" unfolding shattered_by_def by blast\n      qed\n\n      from 0 1 2 show \"inj_on ?f (shattered_by ?F0 \\<inter> shattered_by ?F1) \\<and>\n        (shattered_by ?F0 \\<union> shattered_by ?F1) \\<inter> (?f ` (shattered_by ?F0 \\<inter> shattered_by ?F1)) = {} \\<and>\n        ?f ` (shattered_by ?F0 \\<inter> shattered_by ?F1) \\<subseteq> shattered_by F\" by blast\n    qed\n\n    have F0_union_F1_is_F: \"?F0 \\<union> ?F1 = F\" by fastforce\n    from finite_F have finite_F0: \"finite ?F0\" and finite_F1: \"finite ?F1\" by fastforce+\n    have disjoint_F0_F1: \"?F0 \\<inter> ?F1 = {}\" by fastforce\n\n    text \\<open>We have the following lower bound on the cardinality of @{term \"shattered_by F\"}:\\<close>\n    from F0_union_F1_is_F card_Un_disjoint[OF finite_F0 finite_F1 disjoint_F0_F1] \n    have \"card F = card ?F0 + card ?F1\" by argo\n    also from IH_F0\n    have \"... \\<le> card (shattered_by ?F0) + card ?F1\" by linarith\n    also from IH_F1\n    have \"... \\<le> card (shattered_by ?F0) + card (shattered_by ?F1)\" by linarith\n    also from card_Int_copy[OF finite_shF shattered_subset f_copies_the_intersection]\n    have \"... \\<le> card (shattered_by F)\" by argo\n    finally show ?thesis .\n  next\n    text \\<open>If @{term F} contains less than 2 sets, the statement follows trivially.\\<close>\n    case False\n    hence \"card F = 0 \\<or> card F = 1\" by force\n    thus ?thesis\n    proof\n      assume \"card F = 0\"\n      thus ?thesis by auto\n    next\n      assume asm: \"card F = 1\"\n      hence F_not_empty: \"F \\<noteq> {}\" by fastforce\n      from shatters_empty[OF F_not_empty] have \"{{}} \\<subseteq> shattered_by F\" unfolding shattered_by_def by fastforce\n      from card_mono[OF finite_shF this] asm show ?thesis by fastforce\n    qed\n  qed\nqed\n\nsubsection \\<open>Sauer-Shelah Lemma\\<close>\n\ntext \\<open>The generalized version immediately implies the Sauer-Shelah Lemma,\n      because only @{text \"(\\<Sum>i\\<le>k. n choose i)\"} of the subsets of an @{term n}-item universe have cardinality less than @{term \"k + (1::nat)\"}.\n      Thus, when @{text \"(\\<Sum>i\\<le>k. n choose i) < card F\"}, there are not enough sets to be shattered, \n      so one of the shattered sets must have cardinality at least @{term \"k + (1::nat)\"}.\\<close>\n\ncorollary sauer_shelah:\n  fixes F :: \"'a set set\"\n  assumes \"finite (\\<Union>F)\" and \"(\\<Sum>i\\<le>k. card (\\<Union>F) choose i) < card F\"\n  shows \"\\<exists>S. (F shatters S \\<and> card S = k + 1)\"\nproof -\n  let ?K = \"{S. S \\<subseteq> \\<Union>F \\<and> card S \\<le> k}\"\n  from finite_Pow_iff[of F] assms(1) have finite_Pow_Un: \"finite (Pow (\\<Union>F))\" by fast\n\n  from sauer_shelah_0[OF assms(1)] assms(2) have \"(\\<Sum>i\\<le>k. card (\\<Union>F) choose i) < card (shattered_by F)\" by linarith\n  with choose_row_sum_set[OF assms(1), of k] have \"card ?K < card (shattered_by F)\" by presburger\n\n  from finite_diff_not_empty[OF finite_subset[OF _ finite_Pow_Un] this] \n  obtain S where \"S \\<in> shattered_by F - ?K\" by blast\n  then have F_shatters_S: \"F shatters S\" and \"S \\<subseteq> \\<Union>F\" and \"\\<not>(S \\<subseteq> \\<Union>F \\<and> card S \\<le> k)\" unfolding shattered_by_def by blast+\n  then have card_S_ge_Suc_k: \"k + 1 \\<le> card S\" by simp\n  from obtain_subset_with_card_n[OF card_S_ge_Suc_k] obtain S' where \"card S' = k + 1\" and \"S' \\<subseteq> S\" by blast\n  from this(1) supset_shatters[OF this(2) F_shatters_S] show ?thesis by blast\nqed\n\nsubsection \\<open>Sauer-Shelah Lemma for hypergraphs\\<close>\n\ntext \\<open>If we designate X to be the set of hyperedges and S the set of vertices, we can also formulate the Sauer-Shelah Lemma in terms of hypergraphs. \n      In this form, the statement provides a sufficient condition for the existence of an hyperedge of a given cardinality which is shattered by the set of edges.\\<close>\n\ncorollary sauer_shelah_2:\n  fixes X :: \"'a set set\" and S :: \"'a set\"\n  assumes \"finite S\" and \"X \\<subseteq> Pow S\" and \"(\\<Sum>i\\<le>k. card S choose i) < card X\"\n  shows \"\\<exists>Y. (X shatters Y \\<and> card Y = k + 1)\"\nproof -\n  from assms(2) have 0: \"\\<Union>X \\<subseteq> S\" by blast\n  then have \"(\\<Sum>i\\<le>k. card (\\<Union>X) choose i) \\<le> (\\<Sum>i\\<le>k. card S choose i)\"\n    by (simp add: assms(1) card_mono choose_mono sum_mono)\n  then show ?thesis\n    using \"0\" assms finite_subset sauer_shelah by fastforce\nqed\n\nsubsection \\<open>Alternative statement of the Sauer-Shelah Lemma\\<close>\n\ntext \\<open>We can also state the Sauer-Shelah Lemma in terms of the @{term VC_dim}. If the VC-dimension of @{term F} is @{term k} then @{term F}\n      can consist at most of @{text \"(\\<Sum>i\\<le>k. card (\\<Union>F) choose i)\"} sets which is in @{text \"\\<O>(card (\\<Union>F)^k)\"}.\\<close>\n\ncorollary sauer_shelah_alt:\n  assumes \"finite (\\<Union>F)\" and \"VC_dim F = k\"\n  shows \"card F \\<le> (\\<Sum>i\\<le>k. card (\\<Union>F) choose i)\"\nproof (rule ccontr)\n  assume \"\\<not> card F \\<le> (\\<Sum>i\\<le>k. card (\\<Union>F) choose i)\" hence \"(\\<Sum>i\\<le>k. card (\\<Union>F) choose i) < card F\" by linarith\n  then obtain S where \"F shatters S\" and \"card S = k + 1\"\n    by (meson assms(1) sauer_shelah)\n  then have \\<section>: \"k + 1 \\<in> {card S | S. F shatters S}\"\n    by simp metis\n  have \"finite {A. F shatters A}\"\n    by (metis \\<open>finite (\\<Union> F)\\<close> finite_shattered_by shattered_by_def)\n  then have \"bdd_above {card A |A. F shatters A}\"\n    by simp\n  then have \"k + 1 \\<le> Sup {card A |A. F shatters A}\"\n    by (smt (verit, best) \"\\<section>\" cSup_upper)\n  then have \"k + 1 \\<le> VC_dim F\"\n    by (simp add: VC_dim_def)\n  then show False\n    using assms(2) by 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/Sauer_Shelah_Lemma/Sauer_Shelah_Lemma.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8244619350028204, "lm_q2_score": 0.8740772433654401, "lm_q1q2_score": 0.7206434154070019}}
{"text": "(*<*)theory CTL imports Base begin(*>*)\n\nsubsection{*Computation Tree Logic --- CTL*}\n\ntext{*\\label{sec:CTL}\n\\index{CTL|(}%\nThe semantics of PDL only needs reflexive transitive closure.\nLet us be adventurous and introduce a more expressive temporal operator.\nWe extend the datatype\n@{text formula} by a new constructor\n*}\n(*<*)\ndatatype formula = Atom \"atom\"\n                  | Neg formula\n                  | And formula formula\n                  | AX formula\n                  | EF formula(*>*)\n                  | AF formula\n\ntext{*\\noindent\nwhich stands for ``\\emph{A}lways in the \\emph{F}uture'':\non all infinite paths, at some point the formula holds.\nFormalizing the notion of an infinite path is easy\nin HOL: it is simply a function from @{typ nat} to @{typ state}.\n*}\n\ndefinition Paths :: \"state \\<Rightarrow> (nat \\<Rightarrow> state)set\" where\n\"Paths s \\<equiv> {p. s = p 0 \\<and> (\\<forall>i. (p i, p(i+1)) \\<in> M)}\"\n\ntext{*\\noindent\nThis definition allows a succinct statement of the semantics of @{const AF}:\n\\footnote{Do not be misled: neither datatypes nor recursive functions can be\nextended by new constructors or equations. This is just a trick of the\npresentation (see \\S\\ref{sec:doc-prep-suppress}). In reality one has to define\na new datatype and a new function.}\n*}\n(*<*)\nprimrec valid :: \"state \\<Rightarrow> formula \\<Rightarrow> bool\" (\"(_ \\<Turnstile> _)\" [80,80] 80) where\n\"s \\<Turnstile> Atom a  =  (a \\<in> L s)\" |\n\"s \\<Turnstile> Neg f   = (~(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(*>*)\n\"s \\<Turnstile> AF f    = (\\<forall>p \\<in> Paths s. \\<exists>i. p i \\<Turnstile> f)\"\n\ntext{*\\noindent\nModel checking @{const AF} involves a function which\nis just complicated enough to warrant a separate definition:\n*}\n\ndefinition af :: \"state set \\<Rightarrow> state set \\<Rightarrow> state set\" where\n\"af A T \\<equiv> A \\<union> {s. \\<forall>t. (s, t) \\<in> M \\<longrightarrow> t \\<in> T}\"\n\ntext{*\\noindent\nNow we define @{term \"mc(AF f)\"} as the least set @{term T} that includes\n@{term\"mc f\"} and all states all of whose direct successors are in @{term T}:\n*}\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\"mc(AF f)    = lfp(af(mc f))\"\n\ntext{*\\noindent\nBecause @{const af} is monotone in its second argument (and also its first, but\nthat is irrelevant), @{term\"af A\"} has a least fixed point:\n*}\n\nlemma mono_af: \"mono(af A)\"\napply(simp add: mono_def af_def)\napply blast\ndone\n(*<*)\nlemma mono_ef: \"mono(\\<lambda>T. A \\<union> M\\<inverse> `` T)\"\napply(rule monoI)\nby(blast)\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}\"\napply(rule equalityI)\n apply(rule subsetI)\n apply(simp)\n apply(erule lfp_induct_set)\n  apply(rule mono_ef)\n apply(simp)\n apply(blast intro: rtrancl_trans)\napply(rule subsetI)\napply(simp, clarify)\napply(erule converse_rtrancl_induct)\n apply(subst lfp_unfold[OF mono_ef])\n apply(blast)\napply(subst lfp_unfold[OF mono_ef])\nby(blast)\n(*>*)\ntext{*\nAll we need to prove now is  @{prop\"mc(AF f) = {s. s \\<Turnstile> AF f}\"}, which states\nthat @{term mc} and @{text\"\\<Turnstile>\"} agree for @{const AF}\\@.\nThis time we prove the two inclusions separately, starting\nwith the easy one:\n*}\n\ntheorem AF_lemma1: \"lfp(af A) \\<subseteq> {s. \\<forall>p \\<in> Paths s. \\<exists>i. p i \\<in> A}\"\n\ntxt{*\\noindent\nIn contrast to the analogous proof for @{const EF}, and just\nfor a change, we do not use fixed point induction.  Park-induction,\nnamed after David Park, is weaker but sufficient for this proof:\n\\begin{center}\n@{thm lfp_lowerbound[of _ \"S\",no_vars]} \\hfill (@{thm[source]lfp_lowerbound})\n\\end{center}\nThe instance of the premise @{prop\"f S \\<subseteq> S\"} is proved pointwise,\na decision that \\isa{auto} takes for us:\n*}\napply(rule lfp_lowerbound)\napply(auto simp add: af_def Paths_def)\n\ntxt{*\n@{subgoals[display,indent=0,margin=70,goals_limit=1]}\nIn this remaining case, we set @{term t} to @{term\"p(1::nat)\"}.\nThe rest is automatic, which is surprising because it involves\nfinding the instantiation @{term\"\\<lambda>i::nat. p(i+1)\"}\nfor @{text\"\\<forall>p\"}.\n*}\n\napply(erule_tac x = \"p 1\" in allE)\napply(auto)\ndone\n\n\ntext{*\nThe opposite inclusion is proved by contradiction: if some state\n@{term s} is not in @{term\"lfp(af A)\"}, then we can construct an\ninfinite @{term A}-avoiding path starting from~@{term s}. The reason is\nthat by unfolding @{const lfp} we find that if @{term s} is not in\n@{term\"lfp(af A)\"}, then @{term s} is not in @{term A} and there is a\ndirect successor of @{term s} that is again not in \\mbox{@{term\"lfp(af\nA)\"}}. Iterating this argument yields the promised infinite\n@{term A}-avoiding path. Let us formalize this sketch.\n\nThe one-step argument in the sketch above\nis proved by a variant of contraposition:\n*}\n\nlemma not_in_lfp_afD:\n \"s \\<notin> lfp(af A) \\<Longrightarrow> s \\<notin> A \\<and> (\\<exists> t. (s,t) \\<in> M \\<and> t \\<notin> lfp(af A))\"\napply(erule contrapos_np)\napply(subst lfp_unfold[OF mono_af])\napply(simp add: af_def)\ndone\n\ntext{*\\noindent\nWe assume the negation of the conclusion and prove @{term\"s : lfp(af A)\"}.\nUnfolding @{const lfp} once and\nsimplifying with the definition of @{const af} finishes the proof.\n\nNow we iterate this process. The following construction of the desired\npath is parameterized by a predicate @{term Q} that should hold along the path:\n*}\n\nprimrec path :: \"state \\<Rightarrow> (state \\<Rightarrow> bool) \\<Rightarrow> (nat \\<Rightarrow> state)\" where\n\"path s Q 0 = s\" |\n\"path s Q (Suc n) = (SOME t. (path s Q n,t) \\<in> M \\<and> Q t)\"\n\ntext{*\\noindent\nElement @{term\"n+1::nat\"} on this path is some arbitrary successor\n@{term t} of element @{term n} such that @{term\"Q t\"} holds.  Remember that @{text\"SOME t. R t\"}\nis some arbitrary but fixed @{term t} such that @{prop\"R t\"} holds (see \\S\\ref{sec:SOME}). Of\ncourse, such a @{term t} need not exist, but that is of no\nconcern to us since we will only use @{const path} when a\nsuitable @{term t} does exist.\n\nLet us show that if each state @{term s} that satisfies @{term Q}\nhas a successor that again satisfies @{term Q}, then there exists an infinite @{term Q}-path:\n*}\n\nlemma infinity_lemma:\n  \"\\<lbrakk> Q s; \\<forall>s. Q s \\<longrightarrow> (\\<exists> t. (s,t) \\<in> M \\<and> Q t) \\<rbrakk> \\<Longrightarrow>\n   \\<exists>p\\<in>Paths s. \\<forall>i. Q(p i)\"\n\ntxt{*\\noindent\nFirst we rephrase the conclusion slightly because we need to prove simultaneously\nboth the path property and the fact that @{term Q} holds:\n*}\n\napply(subgoal_tac\n  \"\\<exists>p. s = p 0 \\<and> (\\<forall>i::nat. (p i, p(i+1)) \\<in> M \\<and> Q(p i))\")\n\ntxt{*\\noindent\nFrom this proposition the original goal follows easily:\n*}\n\n apply(simp add: Paths_def, blast)\n\ntxt{*\\noindent\nThe new subgoal is proved by providing the witness @{term \"path s Q\"} for @{term p}:\n*}\n\napply(rule_tac x = \"path s Q\" in exI)\napply(clarsimp)\n\ntxt{*\\noindent\nAfter simplification and clarification, the subgoal has the following form:\n@{subgoals[display,indent=0,margin=70,goals_limit=1]}\nIt invites a proof by induction on @{term i}:\n*}\n\napply(induct_tac i)\n apply(simp)\n\ntxt{*\\noindent\nAfter simplification, the base case boils down to\n@{subgoals[display,indent=0,margin=70,goals_limit=1]}\nThe conclusion looks exceedingly trivial: after all, @{term t} is chosen such that @{prop\"(s,t):M\"}\nholds. However, we first have to show that such a @{term t} actually exists! This reasoning\nis embodied in the theorem @{thm[source]someI2_ex}:\n@{thm[display,eta_contract=false]someI2_ex}\nWhen we apply this theorem as an introduction rule, @{text\"?P x\"} becomes\n@{prop\"(s, x) : M & Q x\"} and @{text\"?Q x\"} becomes @{prop\"(s,x) : M\"} and we have to prove\ntwo subgoals: @{prop\"EX a. (s, a) : M & Q a\"}, which follows from the assumptions, and\n@{prop\"(s, x) : M & Q x ==> (s,x) : M\"}, which is trivial. Thus it is not surprising that\n@{text fast} can prove the base case quickly:\n*}\n\n apply(fast intro: someI2_ex)\n\ntxt{*\\noindent\nWhat is worth noting here is that we have used \\methdx{fast} rather than\n@{text blast}.  The reason is that @{text blast} would fail because it cannot\ncope with @{thm[source]someI2_ex}: unifying its conclusion with the current\nsubgoal is non-trivial because of the nested schematic variables. For\nefficiency reasons @{text blast} does not even attempt such unifications.\nAlthough @{text fast} can in principle cope with complicated unification\nproblems, in practice the number of unifiers arising is often prohibitive and\nthe offending rule may need to be applied explicitly rather than\nautomatically. This is what happens in the step case.\n\nThe induction step is similar, but more involved, because now we face nested\noccurrences of @{text SOME}. As a result, @{text fast} is no longer able to\nsolve the subgoal and we apply @{thm[source]someI2_ex} by hand.  We merely\nshow the proof commands but do not describe the details:\n*}\n\napply(simp)\napply(rule someI2_ex)\n apply(blast)\napply(rule someI2_ex)\n apply(blast)\napply(blast)\ndone\n\ntext{*\nFunction @{const path} has fulfilled its purpose now and can be forgotten.\nIt was merely defined to provide the witness in the proof of the\n@{thm[source]infinity_lemma}. Aficionados of minimal proofs might like to know\nthat we could have given the witness without having to define a new function:\nthe term\n@{term[display]\"rec_nat s (\\<lambda>n t. SOME u. (t,u)\\<in>M \\<and> Q u)\"}\nis extensionally equal to @{term\"path s Q\"},\nwhere @{term rec_nat} is the predefined primitive recursor on @{typ nat}.\n*}\n(*<*)\nlemma\n\"\\<lbrakk> Q s; \\<forall> s. Q s \\<longrightarrow> (\\<exists> t. (s,t)\\<in>M \\<and> Q t) \\<rbrakk> \\<Longrightarrow>\n \\<exists> p\\<in>Paths s. \\<forall> i. Q(p i)\"\napply(subgoal_tac\n \"\\<exists> p. s = p 0 \\<and> (\\<forall> i. (p i,p(Suc i))\\<in>M \\<and> Q(p i))\")\n apply(simp add: Paths_def)\n apply(blast)\napply(rule_tac x = \"rec_nat s (\\<lambda>n t. SOME u. (t,u)\\<in>M \\<and> Q u)\" in exI)\napply(simp)\napply(intro strip)\napply(induct_tac i)\n apply(simp)\n apply(fast intro: someI2_ex)\napply(simp)\napply(rule someI2_ex)\n apply(blast)\napply(rule someI2_ex)\n apply(blast)\nby(blast)\n(*>*)\n\ntext{*\nAt last we can prove the opposite direction of @{thm[source]AF_lemma1}:\n*}\n\ntheorem AF_lemma2: \"{s. \\<forall>p \\<in> Paths s. \\<exists>i. p i \\<in> A} \\<subseteq> lfp(af A)\"\n\ntxt{*\\noindent\nThe proof is again pointwise and then by contraposition:\n*}\n\napply(rule subsetI)\napply(erule contrapos_pp)\napply simp\n\ntxt{*\n@{subgoals[display,indent=0,goals_limit=1]}\nApplying the @{thm[source]infinity_lemma} as a destruction rule leaves two subgoals, the second\npremise of @{thm[source]infinity_lemma} and the original subgoal:\n*}\n\napply(drule infinity_lemma)\n\ntxt{*\n@{subgoals[display,indent=0,margin=65]}\nBoth are solved automatically:\n*}\n\n apply(auto dest: not_in_lfp_afD)\ndone\n\ntext{*\nIf you find these proofs too complicated, we recommend that you read\n\\S\\ref{sec:CTL-revisited}, where we show how inductive definitions lead to\nsimpler arguments.\n\nThe main theorem is proved as for PDL, except that we also derive the\nnecessary equality @{text\"lfp(af A) = ...\"} by combining\n@{thm[source]AF_lemma1} and @{thm[source]AF_lemma2} on the spot:\n*}\n\ntheorem \"mc f = {s. s \\<Turnstile> f}\"\napply(induct_tac f)\napply(auto simp add: EF_lemma equalityI[OF AF_lemma1 AF_lemma2])\ndone\n\ntext{*\n\nThe language defined above is not quite CTL\\@. The latter also includes an\nuntil-operator @{term\"EU f g\"} with semantics ``there \\emph{E}xists a path\nwhere @{term f} is true \\emph{U}ntil @{term g} becomes true''.  We need\nan auxiliary function:\n*}\n\nprimrec\nuntil:: \"state set \\<Rightarrow> state set \\<Rightarrow> state \\<Rightarrow> state list \\<Rightarrow> bool\" where\n\"until A B s []    = (s \\<in> B)\" |\n\"until A B s (t#p) = (s \\<in> A \\<and> (s,t) \\<in> M \\<and> until A B t p)\"\n(*<*)definition\n eusem :: \"state set \\<Rightarrow> state set \\<Rightarrow> state set\" where\n\"eusem A B \\<equiv> {s. \\<exists>p. until A B s p}\"(*>*)\n\ntext{*\\noindent\nExpressing the semantics of @{term EU} is now straightforward:\n@{prop[display]\"s \\<Turnstile> EU f g = (\\<exists>p. until {t. t \\<Turnstile> f} {t. t \\<Turnstile> g} s p)\"}\nNote that @{term EU} is not definable in terms of the other operators!\n\nModel checking @{term EU} is again a least fixed point construction:\n@{text[display]\"mc(EU f g) = lfp(\\<lambda>T. mc g \\<union> mc f \\<inter> (M\\<inverse> `` T))\"}\n\n\\begin{exercise}\nExtend the datatype of formulae by the above until operator\nand prove the equivalence between semantics and model checking, i.e.\\ that\n@{prop[display]\"mc(EU f g) = {s. s \\<Turnstile> EU f g}\"}\n%For readability you may want to annotate {term EU} with its customary syntax\n%{text[display]\"| EU formula formula    E[_ U _]\"}\n%which enables you to read and write {text\"E[f U g]\"} instead of {term\"EU f g\"}.\n\\end{exercise}\nFor more CTL exercises see, for example, Huth and Ryan @{cite \"Huth-Ryan-book\"}.\n*}\n\n(*<*)\ndefinition eufix :: \"state set \\<Rightarrow> state set \\<Rightarrow> state set \\<Rightarrow> state set\" where\n\"eufix A B T \\<equiv> B \\<union> A \\<inter> (M\\<inverse> `` T)\"\n\nlemma \"lfp(eufix A B) \\<subseteq> eusem A B\"\napply(rule lfp_lowerbound)\napply(auto simp add: eusem_def eufix_def)\n apply(rule_tac x = \"[]\" in exI)\n apply simp\napply(rule_tac x = \"xa#xb\" in exI)\napply simp\ndone\n\nlemma mono_eufix: \"mono(eufix A B)\"\napply(simp add: mono_def eufix_def)\napply blast\ndone\n\nlemma \"eusem A B \\<subseteq> lfp(eufix A B)\"\napply(clarsimp simp add: eusem_def)\napply(erule rev_mp)\napply(rule_tac x = x in spec)\napply(induct_tac p)\n apply(subst lfp_unfold[OF mono_eufix])\n apply(simp add: eufix_def)\napply(clarsimp)\napply(subst lfp_unfold[OF mono_eufix])\napply(simp add: eufix_def)\napply blast\ndone\n\n(*\ndefinition eusem :: \"state set \\<Rightarrow> state set \\<Rightarrow> state set\" where\n\"eusem A B \\<equiv> {s. \\<exists>p\\<in>Paths s. \\<exists>j. p j \\<in> B \\<and> (\\<forall>i < j. p i \\<in> A)}\"\n\naxiomatization where\nM_total: \"\\<exists>t. (s,t) \\<in> M\"\n\nconsts apath :: \"state \\<Rightarrow> (nat \\<Rightarrow> state)\"\nprimrec\n\"apath s 0 = s\"\n\"apath s (Suc i) = (SOME t. (apath s i,t) \\<in> M)\"\n\n\n\ndefinition pcons :: \"state \\<Rightarrow> (nat \\<Rightarrow> state) \\<Rightarrow> (nat \\<Rightarrow> state)\" where\n\"pcons s p == \\<lambda>i. case i of 0 \\<Rightarrow> s | Suc j \\<Rightarrow> p j\"\n\nlemma pcons_PathI: \"[| (s,t) : M; p \\<in> Paths t |] ==> pcons s p \\<in> Paths s\";\nby(simp add: Paths_def pcons_def split: nat.split);\n\nlemma \"lfp(eufix A B) \\<subseteq> eusem A B\"\napply(rule lfp_lowerbound)\napply(clarsimp simp add: eusem_def eufix_def);\napply(erule disjE);\n apply(rule_tac x = \"apath x\" in bexI);\n  apply(rule_tac x = 0 in exI);\n  apply simp;\n apply simp;\napply(clarify);\napply(rule_tac x = \"pcons xb p\" in bexI);\n apply(rule_tac x = \"j+1\" in exI);\n apply (simp add: pcons_def split: nat.split);\napply (simp add: pcons_PathI)\ndone\n*)\n(*>*)\n\ntext{* Let us close this section with a few words about the executability of\nour model checkers.  It is clear that if all sets are finite, they can be\nrepresented as lists and the usual set operations are easily\nimplemented. Only @{const lfp} requires a little thought.  Fortunately, theory\n@{text While_Combinator} in the Library~@{cite \"HOL-Library\"} provides a\ntheorem stating that in the case of finite sets and a monotone\nfunction~@{term F}, the value of \\mbox{@{term\"lfp F\"}} can be computed by\niterated application of @{term F} to~@{term\"{}\"} until a fixed point is\nreached. It is actually possible to generate executable functional programs\nfrom HOL definitions, but that is beyond the scope of the tutorial.%\n\\index{CTL|)} *}\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/CTL/CTL.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8244619350028204, "lm_q2_score": 0.87407724336544, "lm_q1q2_score": 0.7206434154070018}}
{"text": "(* ************************************************************************** *)\n(* Title:      Generated_Rings.thy                                            *)\n(* Author:     Martin Baillon                                                 *)\n(* ************************************************************************** *)\n\ntheory Generated_Rings\n  imports Subrings\nbegin\n\nsection\\<open>Generated Rings\\<close>\n\ninductive_set\n  generate_ring :: \"('a, 'b) ring_scheme \\<Rightarrow> 'a set \\<Rightarrow> 'a set\"\n  for R and H where\n    one:   \"\\<one>\\<^bsub>R\\<^esub> \\<in> generate_ring R H\"\n  | incl:  \"h \\<in> H \\<Longrightarrow> h \\<in> generate_ring R H\"\n  | a_inv: \"h \\<in> generate_ring R H \\<Longrightarrow> \\<ominus>\\<^bsub>R\\<^esub> h \\<in> generate_ring R H\"\n  | eng_add : \"\\<lbrakk> h1 \\<in> generate_ring R H; h2 \\<in> generate_ring R H \\<rbrakk> \\<Longrightarrow> h1 \\<oplus>\\<^bsub>R\\<^esub> h2 \\<in> generate_ring R H\"\n  | eng_mult: \"\\<lbrakk> h1 \\<in> generate_ring R H; h2 \\<in> generate_ring R H \\<rbrakk> \\<Longrightarrow> h1 \\<otimes>\\<^bsub>R\\<^esub> h2 \\<in> generate_ring R H\"\n\nsubsection\\<open>Basic Properties of Generated Rings - First Part\\<close>\n\nlemma (in ring) generate_ring_in_carrier:\n  assumes \"H \\<subseteq> carrier R\"\n  shows \"h \\<in> generate_ring R H \\<Longrightarrow> h \\<in> carrier R\"\n  apply (induction rule: generate_ring.induct) using assms \n  by blast+\n\nlemma (in ring) generate_ring_incl:\n  assumes \"H \\<subseteq> carrier R\"\n  shows \"generate_ring R H \\<subseteq> carrier R\"\n  using generate_ring_in_carrier[OF assms] by auto\n\nlemma (in ring) zero_in_generate: \"\\<zero>\\<^bsub>R\\<^esub> \\<in> generate_ring R H\"\n  using one a_inv by (metis generate_ring.eng_add one_closed r_neg)\n\nlemma (in ring) generate_ring_is_subring:\n  assumes \"H \\<subseteq> carrier R\"\n  shows \"subring (generate_ring R H) R\"\n  by (auto intro!: subringI[of \"generate_ring R H\"]\n         simp add: generate_ring_in_carrier[OF assms] one a_inv eng_mult eng_add)\n\nlemma (in ring) generate_ring_is_ring:\n  assumes \"H \\<subseteq> carrier R\"\n  shows \"ring (R \\<lparr> carrier := generate_ring R H \\<rparr>)\"\n  using subring_iff[OF generate_ring_incl[OF assms]] generate_ring_is_subring[OF assms] by simp\n\nlemma (in ring) generate_ring_min_subring1:\n  assumes \"H \\<subseteq> carrier R\" and \"subring E R\" \"H \\<subseteq> E\"\n  shows \"generate_ring R H \\<subseteq> E\"\nproof\n  fix h assume h: \"h \\<in> generate_ring R H\"\n  show \"h \\<in> E\"\n    using h and assms(3)\n      by (induct rule: generate_ring.induct)\n         (auto simp add: subringE(3,5-7)[OF assms(2)])\nqed\n\nlemma (in ring) generate_ringI:\n  assumes \"H \\<subseteq> carrier R\"\n    and \"subring E R\" \"H \\<subseteq> E\"\n    and \"\\<And>K. \\<lbrakk> subring K R; H \\<subseteq> K \\<rbrakk> \\<Longrightarrow> E \\<subseteq> K\"\n  shows \"E = generate_ring R H\"\nproof\n  show \"E \\<subseteq> generate_ring R H\"\n    using assms generate_ring_is_subring generate_ring.incl by (metis subset_iff)\n  show \"generate_ring R H \\<subseteq> E\"\n    using generate_ring_min_subring1[OF assms(1-3)] by simp\nqed\n\nlemma (in ring) generate_ringE:\n  assumes \"H \\<subseteq> carrier R\" and \"E = generate_ring R H\"\n  shows \"subring E R\" and \"H \\<subseteq> E\" and \"\\<And>K. \\<lbrakk> subring K R; H \\<subseteq> K \\<rbrakk> \\<Longrightarrow> E \\<subseteq> K\"\nproof -\n  show \"subring E R\" using assms generate_ring_is_subring by simp\n  show \"H \\<subseteq> E\" using assms(2) by (simp add: generate_ring.incl subsetI)\n  show \"\\<And>K. subring K R  \\<Longrightarrow> H \\<subseteq> K \\<Longrightarrow> E \\<subseteq> K\"\n    using assms generate_ring_min_subring1 by auto\nqed\n\nlemma (in ring) generate_ring_min_subring2:\n  assumes \"H \\<subseteq> carrier R\"\n  shows \"generate_ring R H = \\<Inter>{K. subring K R \\<and> H \\<subseteq> K}\"\nproof\n  have \"subring (generate_ring R H) R \\<and> H \\<subseteq> generate_ring R H\"\n    by (simp add: assms generate_ringE(2) generate_ring_is_subring)\n  thus \"\\<Inter>{K. subring K R \\<and> H \\<subseteq> K} \\<subseteq> generate_ring R H\" by blast\nnext\n  have \"\\<And>K. subring K R \\<and> H \\<subseteq> K \\<Longrightarrow> generate_ring R H \\<subseteq> K\"\n    by (simp add: assms generate_ring_min_subring1)\n  thus \"generate_ring R H \\<subseteq> \\<Inter>{K. subring K R \\<and> H \\<subseteq> K}\" by blast\nqed\n\nlemma (in ring) mono_generate_ring:\n  assumes \"I \\<subseteq> J\" and \"J \\<subseteq> carrier R\"\n  shows \"generate_ring R I \\<subseteq> generate_ring R J\"\nproof-\n  have \"I \\<subseteq> generate_ring R J \"\n    using assms generate_ringE(2) by blast\n  thus \"generate_ring R I \\<subseteq> generate_ring R J\"\n    using generate_ring_min_subring1[of I \"generate_ring R J\"] assms generate_ring_is_subring[OF assms(2)]\n    by blast\nqed\n\nlemma (in ring) subring_gen_incl :\n  assumes \"subring H R\"\n    and  \"subring K R\"\n    and \"I \\<subseteq> H\"\n    and \"I \\<subseteq> K\"\n  shows \"generate_ring (R\\<lparr>carrier := K\\<rparr>) I \\<subseteq> generate_ring (R\\<lparr>carrier := H\\<rparr>) I\"\nproof\n  {fix J assume J_def : \"subring J R\" \"I \\<subseteq> J\"\n    have \"generate_ring (R \\<lparr> carrier := J \\<rparr>) I \\<subseteq> J\"\n      using ring.mono_generate_ring[of \"(R\\<lparr>carrier := J\\<rparr>)\" I J ] subring_is_ring[OF J_def(1)]\n          ring.generate_ring_in_carrier[of \"R\\<lparr>carrier := J\\<rparr>\"]  ring_axioms J_def(2)\n      by auto}\n  note incl_HK = this\n  {fix x have \"x \\<in> generate_ring (R\\<lparr>carrier := K\\<rparr>) I \\<Longrightarrow> x \\<in> generate_ring (R\\<lparr>carrier := H\\<rparr>) I\" \n    proof (induction  rule : generate_ring.induct)\n      case one\n        have \"\\<one>\\<^bsub>R\\<lparr>carrier := H\\<rparr>\\<^esub> \\<otimes> \\<one>\\<^bsub>R\\<lparr>carrier := K\\<rparr>\\<^esub> = \\<one>\\<^bsub>R\\<lparr>carrier := H\\<rparr>\\<^esub>\" by simp\n        moreover have \"\\<one>\\<^bsub>R\\<lparr>carrier := H\\<rparr>\\<^esub> \\<otimes> \\<one>\\<^bsub>R\\<lparr>carrier := K\\<rparr>\\<^esub> = \\<one>\\<^bsub>R\\<lparr>carrier := K\\<rparr>\\<^esub>\" by simp\n        ultimately show ?case using assms generate_ring.one by metis\n    next\n      case (incl h) thus ?case using generate_ring.incl by force\n    next\n      case (a_inv h)\n      note hyp = this\n      have \"a_inv (R\\<lparr>carrier := K\\<rparr>) h = a_inv R h\" \n        using assms group.m_inv_consistent[of \"add_monoid R\" K] a_comm_group incl_HK[of K] hyp\n        unfolding subring_def comm_group_def a_inv_def by auto\n      moreover have \"a_inv (R\\<lparr>carrier := H\\<rparr>) h = a_inv R h\"\n        using assms group.m_inv_consistent[of \"add_monoid R\" H] a_comm_group incl_HK[of H] hyp\n        unfolding subring_def comm_group_def a_inv_def by auto\n      ultimately show ?case using generate_ring.a_inv a_inv.IH by fastforce\n    next\n      case (eng_add h1 h2)\n      thus ?case using incl_HK assms generate_ring.eng_add by force\n    next\n      case (eng_mult h1 h2)\n      thus ?case using generate_ring.eng_mult by force\n    qed}\n  thus \"\\<And>x. x \\<in> generate_ring (R\\<lparr>carrier := K\\<rparr>) I \\<Longrightarrow> x \\<in> generate_ring (R\\<lparr>carrier := H\\<rparr>) I\"\n    by auto\nqed\n\nlemma (in ring) subring_gen_equality:\n  assumes \"subring H R\" \"K \\<subseteq> H\"\n  shows \"generate_ring R K = generate_ring (R \\<lparr> carrier := H \\<rparr>) K\"\n  using subring_gen_incl[OF assms(1)carrier_is_subring assms(2)] assms subringE(1)\n        subring_gen_incl[OF carrier_is_subring assms(1) _ assms(2)]\n  by force\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/Generated_Rings.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8740772351648677, "lm_q2_score": 0.8244619199068831, "lm_q1q2_score": 0.7206433954509269}}
{"text": "theory Add\nimports Main\nbegin\n\n(*funcao recursiva de somar nat*)\nprimrec add::\"nat \\<Rightarrow> nat \\<Rightarrow> nat\"\nwhere\n  add01: \"add x 0 = x\" |\n  add02: \"add x (Suc y) = Suc (add x y)\"\n\ntheorem th_add01as:\"\\<forall>x y. add (add x y) z = add x (add y z)\"\napply(induction z)\napply(simp)\napply(simp)\n  done\n\ntheorem addT0:\"add 1 x = Suc x\"\nproof(induct x)\n  show \"add 1 0 = Suc 0\"\n  proof -\n    have \"add 1 0 = 1\" by (simp only:add01)\n    also have \"... = Suc 0\" by (simp only:algebra)\n    finally show \"add 1 0 = Suc 0\" by simp\n  qed\nnext\n  fix x0::nat\n  assume HIP:\"add 1 x0 = Suc x0\"\n  show \"add 1 (Suc x0) = Suc (Suc x0)\"\n  proof -\n    have \"add 1 (Suc x0) = Suc (add 1 x0)\" by (simp only:add02)\n    also have \"... = Suc (Suc x0)\" by (simp only:HIP)\n    finally show \"add 1 (Suc x0) = Suc (Suc x0)\" by simp\n  qed\nqed\n\ntheorem addT1:\"\\<forall>x. add x y = x + y\"\nproof (induct y)\n  show \"\\<forall>x. add x 0 = x + 0\"\n  proof (rule allI)\n    fix x0::nat\n    have \"add x0 0 = x0\" by (simp only:add01)\n    also have \"... = x0 + 0\" by simp\n    finally show \"add x0 0 = x0 + 0\" by simp\n  qed\nnext\n  fix y0::nat\n  assume HIP:\"\\<forall>x. add x y0 = x + y0\"\n  show \"\\<forall>x. add x (Suc y0) = x + (Suc y0)\"\n  proof (rule allI)\n    fix x0::nat\n    have \"add x0 (Suc y0) = Suc (add x0 y0)\" by (simp only:add02)\n    also have \"... = Suc (x0 + y0)\" by (simp only:HIP)\n    also have \"... = x0 + (Suc y0)\" by simp\n    finally show \"add x0 (Suc y0) = x0 + (Suc y0)\" by simp\n  qed\nqed\n\ninductive ev::\"nat \\<Rightarrow> bool\"\nwhere\n  ev0: \"ev 0\" |\n  ev1: \"ev n \\<Longrightarrow> ev (Suc (Suc n))\"\n\nthm \"ev.induct\"\n\nlemma \"ev (Suc(Suc(Suc(Suc 0))))\"\napply(rule ev1)\napply(rule ev1)\napply(rule ev0)\ndone\n\nfun even::\"nat \\<Rightarrow> bool\"\nwhere\n  \"even 0 = True\" |\n  \"even (Suc 0) = False\" |\n  \"even (Suc(Suc n)) = even n\"\n\ntheorem \"ev n \\<Longrightarrow> even n\"\napply(induct rule: ev.induct)\napply(auto)\ndone\n\ntheorem \"even n \\<Longrightarrow> ev n\"\napply(induct rule: even.induct)\napply(simp add: ev0)\napply(simp)\napply(simp add: ev1)\ndone\n\ntheorem \"ev n \\<Longrightarrow> \\<exists>k. n = 2*k\"\napply(induct rule: ev.induct)\napply(simp)\napply(arith)\ndone\n\n(*provas isar*)\n\nthm nat.induct\nprint_statement nat.induct\n\ntheorem th_add01isar:\"\\<forall>x y. add (add x y) z = add x (add y z)\"\nproof (induction z)\nshow \"\\<forall>x y. add (add x y) 0 = add x (add y 0)\"\nby simp\nnext\nfix x0::nat\nassume HI:\"\\<forall>x y. add (add x y) x0 = add x (add y x0)\"\nshow \"\\<forall>x y. add (add x y) (Suc x0) = add x (add y (Suc x0))\"\nby (simp add:HI)\nqed\n\ntheorem th_add01isar2:\"\\<forall>x y. add (add x y) z = add x (add y z)\"\nproof (induction z)\nshow \"\\<forall>x y. add (add x y) 0 = add x (add y 0)\"\nproof(rule allI, rule allI)\nfix x0::nat and y0::nat\nhave \"add (add x0 y0) 0 = add x0 y0\"\nby (simp only:add01)\nalso have \"... = add x0 (add y0 0)\"\nby (simp only:add01)\nfinally show \"add (add x0 y0) 0 = add x0 (add y0 0)\"\nby simp\nqed\nnext\nfix z0::nat\nassume HI:\"\\<forall>x y. add (add x y) z0 = add x (add y z0)\"\nshow \"\\<forall>x y. add (add x y)(Suc z0) = add x (add y (Suc z0))\"\nproof(rule allI, rule allI)\nfix x0::nat and y0::nat\nhave \"add (add x0 y0)(Suc z0) = Suc(add (add x0 y0) z0)\" by (simp only:add02)\nalso have \"... = Suc(add x0 (add y0 z0))\" by (simp only:HI)\nalso have \"... = add x0 (Suc (add y0 z0))\" by (simp only:add02)\nalso have \"... = add x0 (add y0 (Suc z0))\" by (simp only:add02)\nfinally show \"add (add x0 y0)(Suc z0) = add x0 (add y0 (Suc z0))\" by simp\nqed\nqed\n\n\n\n\n\n\n\n\n\n\n\n\nend\n\n", "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/Add.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110569397307, "lm_q2_score": 0.8080672227971211, "lm_q1q2_score": 0.7206432840410534}}
{"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_MSortBUCount\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 map :: \"('a => 'b) => 'a list => 'b list\" where\n  \"map f (nil2) = nil2\"\n| \"map f (cons2 y xs) = cons2 (f y) (map f xs)\"\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 mergingbu :: \"(Nat list) list => Nat list\" where\n  \"mergingbu (nil2) = nil2\"\n| \"mergingbu (cons2 xs (nil2)) = xs\"\n| \"mergingbu (cons2 xs (cons2 z x2)) =\n     mergingbu (pairwise (cons2 xs (cons2 z x2)))\"\n  by pat_completeness auto\n\nfun msortbu :: \"Nat list => Nat list\" where\n  \"msortbu x = mergingbu (map (% (y :: Nat) => cons2 y (nil2)) 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 (msortbu 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_MSortBUCount.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110396870287, "lm_q2_score": 0.8080672227971211, "lm_q1q2_score": 0.7206432700997104}}
{"text": "(*  Title:       Recursion theorem\n    Author:      Georgy Dunaev <georgedunaev at gmail.com>, 2020\n    Maintainer:  Georgy Dunaev <georgedunaev at gmail.com>\n*)\nsection \"Recursion Submission\"\n\ntext \\<open>Recursion Theorem is proved in the following document.\nIt also contains the addition on natural numbers.\nThe development is done in the context of Zermelo-Fraenkel set theory.\\<close>\n\ntheory recursion\n  imports ZF\nbegin\n\nsection \\<open>Basic Set Theory\\<close>\ntext \\<open>Useful lemmas about sets, functions and natural numbers\\<close>\nlemma pisubsig : \\<open>Pi(A,P)\\<subseteq>Pow(Sigma(A,P))\\<close>\nproof\n  fix x\n  assume \\<open>x \\<in> Pi(A,P)\\<close>\n  hence \\<open>x \\<in> {f\\<in>Pow(Sigma(A,P)). A\\<subseteq>domain(f) & function(f)}\\<close>\n    by (unfold Pi_def)\n  thus \\<open>x \\<in> Pow(Sigma(A, P))\\<close>\n    by (rule CollectD1)\nqed\n\nlemma apparg:\n  fixes f A B\n  assumes T0:\\<open>f:A\\<rightarrow>B\\<close>\n  assumes T1:\\<open>f ` a = b\\<close>\n  assumes T2:\\<open>a \\<in> A\\<close>\n  shows \\<open>\\<langle>a, b\\<rangle> \\<in> f\\<close>\nproof(rule iffD2[OF func.apply_iff], rule T0)\n  show T:\\<open>a \\<in> A \\<and> f ` a = b\\<close>\n    by (rule conjI[OF T2 T1])\nqed\n\ntheorem nat_induct_bound :\n  assumes H0:\\<open>P(0)\\<close>\n  assumes H1:\\<open>!!x. x\\<in>nat \\<Longrightarrow> P(x) \\<Longrightarrow> P(succ(x))\\<close>\n  shows \\<open>\\<forall>n\\<in>nat. P(n)\\<close>\nproof(rule ballI)\n  fix n\n  assume H2:\\<open>n\\<in>nat\\<close>\n  show \\<open>P(n)\\<close>\n  proof(rule nat_induct[of n])\n    from H2 show \\<open>n\\<in>nat\\<close> by assumption\n  next\n    show \\<open>P(0)\\<close> by (rule H0)\n  next\n    fix x\n    assume H3:\\<open>x\\<in>nat\\<close>\n    assume H4:\\<open>P(x)\\<close>\n    show \\<open>P(succ(x))\\<close> by (rule H1[OF H3 H4])\n  qed\nqed\n\ntheorem nat_Tr : \\<open>\\<forall>n\\<in>nat. m\\<in>n \\<longrightarrow> m\\<in>nat\\<close>\nproof(rule nat_induct_bound)\n  show \\<open>m \\<in> 0 \\<longrightarrow> m \\<in> nat\\<close> by auto\nnext\n  fix x\n  assume H0:\\<open>x \\<in> nat\\<close>\n  assume H1:\\<open>m \\<in> x \\<longrightarrow> m \\<in> nat\\<close>\n  show \\<open>m \\<in> succ(x) \\<longrightarrow> m \\<in> nat\\<close>\n  proof(rule impI)\n    assume H2:\\<open>m\\<in>succ(x)\\<close>\n    show \\<open>m \\<in> nat\\<close>\n    proof(rule succE[OF H2])\n      assume H3:\\<open>m = x\\<close>\n      from H0 and H3 show \\<open>m \\<in> nat\\<close>\n        by auto\n    next\n      assume H4:\\<open>m \\<in> x\\<close>\n      show \\<open>m \\<in> nat\\<close>\n        by(rule mp[OF H1 H4])\n    qed\n  qed\nqed\n\n(* Natural numbers are linearly ordered. *)\ntheorem zeroleq : \\<open>\\<forall>n\\<in>nat. 0\\<in>n \\<or> 0=n\\<close>\nproof(rule ballI)\n  fix n\n  assume H1:\\<open>n\\<in>nat\\<close>\n  show \\<open>0\\<in>n\\<or>0=n\\<close>\n  proof(rule nat_induct[of n])\n    from H1 show \\<open>n \\<in> nat\\<close> by assumption\n  next\n    show \\<open>0 \\<in> 0 \\<or> 0 = 0\\<close> by (rule disjI2, rule refl)\n  next\n    fix x\n    assume H2:\\<open>x\\<in>nat\\<close>\n    assume H3:\\<open> 0 \\<in> x \\<or> 0 = x\\<close>\n    show \\<open>0 \\<in> succ(x) \\<or> 0 = succ(x)\\<close>\n    proof(rule disjE[OF H3])\n      assume H4:\\<open>0\\<in>x\\<close>\n      show \\<open>0 \\<in> succ(x) \\<or> 0 = succ(x)\\<close>\n      proof(rule disjI1)\n        show \\<open>0 \\<in> succ(x)\\<close>\n          by (rule succI2[OF H4])\n      qed\n    next\n      assume H4:\\<open>0=x\\<close>\n      show \\<open>0 \\<in> succ(x) \\<or> 0 = succ(x)\\<close>\n      proof(rule disjI1)\n        have q:\\<open>x \\<in> succ(x)\\<close> by auto\n        from q and H4 show \\<open>0 \\<in> succ(x)\\<close> by auto\n      qed\n    qed\n  qed\nqed\n\ntheorem JH2_1ii : \\<open>m\\<in>succ(n) \\<Longrightarrow> m\\<in>n\\<or>m=n\\<close>\n  by auto\n\ntheorem nat_transitive:\\<open>\\<forall>n\\<in>nat. \\<forall>k. \\<forall>m.  k \\<in> m \\<and> m \\<in> n \\<longrightarrow> k \\<in> n\\<close>\nproof(rule nat_induct_bound)\n  show \\<open>\\<forall>k. \\<forall>m. k \\<in> m \\<and> m \\<in> 0 \\<longrightarrow> k \\<in> 0\\<close>\n  proof(rule allI, rule allI, rule impI)\n    fix k m\n    assume H:\\<open>k \\<in> m \\<and> m \\<in> 0\\<close>\n    then have H:\\<open>m \\<in> 0\\<close> by auto\n    then show \\<open>k \\<in> 0\\<close> by auto\n  qed\nnext\n  fix n\n  assume H0:\\<open>n \\<in> nat\\<close>\n  assume H1:\\<open>\\<forall>k.\n            \\<forall>m.\n               k \\<in> m \\<and> m \\<in> n \\<longrightarrow>\n               k \\<in> n\\<close>\n  show \\<open>\\<forall>k. \\<forall>m.\n               k \\<in> m \\<and>\n               m \\<in> succ(n) \\<longrightarrow>\n               k \\<in> succ(n)\\<close>\n  proof(rule allI, rule allI, rule impI)\n    fix k m\n    assume H4:\\<open>k \\<in> m \\<and> m \\<in> succ(n)\\<close>\n    hence H4':\\<open>m \\<in> succ(n)\\<close> by (rule conjunct2)\n    hence H4'':\\<open>m\\<in>n \\<or> m=n\\<close> by (rule succE, auto)\n    from H4 have Q:\\<open>k \\<in> m\\<close> by (rule conjunct1)\n    have H1S:\\<open>\\<forall>m. k \\<in> m \\<and> m \\<in> n \\<longrightarrow> k \\<in> n\\<close>\n      by (rule spec[OF H1])\n    have H1S:\\<open>k \\<in> m \\<and> m \\<in> n \\<longrightarrow> k \\<in> n\\<close>\n      by (rule spec[OF H1S])\n    show \\<open>k \\<in> succ(n)\\<close>\n    proof(rule disjE[OF H4''])\n      assume L:\\<open>m\\<in>n\\<close>\n      from Q and L have QL:\\<open>k \\<in> m \\<and> m \\<in> n\\<close> by auto\n      have G:\\<open>k \\<in> n\\<close> by (rule mp [OF H1S QL])\n      show \\<open>k \\<in> succ(n)\\<close>\n        by (rule succI2[OF G])\n    next\n      assume L:\\<open>m=n\\<close>\n      from Q have F:\\<open>k \\<in> succ(m)\\<close> by auto\n      from L and Q show \\<open>k \\<in> succ(n)\\<close> by auto\n    qed\n  qed\nqed\n\ntheorem nat_xninx : \\<open>\\<forall>n\\<in>nat. \\<not>(n\\<in>n)\\<close>\nproof(rule nat_induct_bound)\n  show \\<open>0\\<notin>0\\<close>\n    by auto\nnext\n  fix x\n  assume H0:\\<open>x\\<in>nat\\<close>\n  assume H1:\\<open>x\\<notin>x\\<close>\n  show \\<open>succ(x) \\<notin> succ(x)\\<close>\n  proof(rule contrapos[OF H1])\n    assume Q:\\<open>succ(x) \\<in> succ(x)\\<close>\n    have D:\\<open>succ(x)\\<in>x \\<or> succ(x)=x\\<close>\n      by (rule JH2_1ii[OF Q])\n    show \\<open>x\\<in>x\\<close>\n    proof(rule disjE[OF D])\n      assume Y1:\\<open>succ(x)\\<in>x\\<close>\n      have U:\\<open>x\\<in>succ(x)\\<close> by (rule succI1)\n      have T:\\<open>x \\<in> succ(x) \\<and> succ(x) \\<in> x \\<longrightarrow> x \\<in> x\\<close>\n        by (rule spec[OF spec[OF bspec[OF nat_transitive H0]]])\n      have R:\\<open>x \\<in> succ(x) \\<and> succ(x) \\<in> x\\<close>\n        by (rule conjI[OF U Y1])\n      show \\<open>x\\<in>x\\<close>\n        by (rule mp[OF T R])\n    next\n      assume Y1:\\<open>succ(x)=x\\<close>\n      show \\<open>x\\<in>x\\<close>\n        by (rule subst[OF Y1], rule Q)\n    qed\n  qed\nqed\n\ntheorem nat_asym : \\<open>\\<forall>n\\<in>nat. \\<forall>m. \\<not>(n\\<in>m \\<and> m\\<in>n)\\<close>\nproof(rule ballI, rule allI)\n  fix n m\n  assume H0:\\<open>n \\<in> nat\\<close>\n  have Q:\\<open>\\<not>(n\\<in>n)\\<close>\n    by(rule bspec[OF nat_xninx H0])\n  show \\<open>\\<not> (n \\<in> m \\<and> m \\<in> n)\\<close>\n  proof(rule contrapos[OF Q])\n    assume W:\\<open>(n \\<in> m \\<and> m \\<in> n)\\<close>\n    show \\<open>n\\<in>n\\<close>\n      by (rule mp[OF spec[OF spec[OF bspec[OF nat_transitive H0]]] W])\n  qed\nqed\n\ntheorem zerolesucc :\\<open>\\<forall>n\\<in>nat. 0 \\<in> succ(n)\\<close>\nproof(rule nat_induct_bound)\n  show \\<open>0\\<in>1\\<close>\n    by auto\nnext\n  fix x\n  assume H0:\\<open>x\\<in>nat\\<close>\n  assume H1:\\<open>0\\<in>succ(x)\\<close>\n  show \\<open>0\\<in>succ(succ(x))\\<close>\n  proof\n    assume J:\\<open>0 \\<notin> succ(x)\\<close>\n    show \\<open>0 = succ(x)\\<close>\n      by(rule notE[OF J H1])\n  qed\nqed\n\ntheorem succ_le : \\<open>\\<forall>n\\<in>nat. succ(m)\\<in>succ(n) \\<longrightarrow> m\\<in>n\\<close>\nproof(rule nat_induct_bound)\n  show \\<open> succ(m) \\<in> 1 \\<longrightarrow> m \\<in> 0\\<close>\n    by blast\nnext\n  fix x\n  assume H0:\\<open>x \\<in> nat\\<close>\n  assume H1:\\<open>succ(m) \\<in> succ(x) \\<longrightarrow> m \\<in> x\\<close>\n  show \\<open> succ(m) \\<in>\n             succ(succ(x)) \\<longrightarrow>\n             m \\<in> succ(x)\\<close>\n  proof(rule impI)\n    assume J0:\\<open>succ(m) \\<in> succ(succ(x))\\<close>\n    show \\<open>m \\<in> succ(x)\\<close>\n    proof(rule succE[OF J0])\n      assume R:\\<open>succ(m) = succ(x)\\<close>\n      hence R:\\<open>m=x\\<close> by (rule upair.succ_inject)\n      from R and succI1 show \\<open>m \\<in> succ(x)\\<close> by auto\n    next\n      assume R:\\<open>succ(m) \\<in> succ(x)\\<close>\n      have R:\\<open>m\\<in>x\\<close> by (rule mp[OF H1 R])\n      then show \\<open>m \\<in> succ(x)\\<close> by auto\n    qed\n  qed\nqed\n\ntheorem succ_le2 : \\<open>\\<forall>n\\<in>nat. \\<forall>m. succ(m)\\<in>succ(n) \\<longrightarrow> m\\<in>n\\<close>\nproof\n  fix n\n  assume H:\\<open>n\\<in>nat\\<close>\n  show \\<open>\\<forall>m. succ(m) \\<in> succ(n) \\<longrightarrow> m \\<in> n\\<close>\n  proof\n    fix m\n    from succ_le and H show \\<open>succ(m) \\<in> succ(n) \\<longrightarrow> m \\<in> n\\<close> by auto\n  qed\nqed\n\ntheorem le_succ : \\<open>\\<forall>n\\<in>nat. m\\<in>n \\<longrightarrow> succ(m)\\<in>succ(n)\\<close>\nproof(rule nat_induct_bound)\n  show \\<open>m \\<in> 0 \\<longrightarrow> succ(m) \\<in> 1\\<close>\n    by auto\nnext\n  fix x\n  assume H0:\\<open>x\\<in>nat\\<close>\n  assume H1:\\<open>m \\<in> x \\<longrightarrow> succ(m) \\<in> succ(x)\\<close>\n  show \\<open>m \\<in> succ(x) \\<longrightarrow>\n            succ(m) \\<in> succ(succ(x))\\<close>\n  proof(rule impI)\n    assume HR1:\\<open>m\\<in>succ(x)\\<close>\n    show \\<open>succ(m) \\<in> succ(succ(x))\\<close>\n    proof(rule succE[OF HR1])\n      assume Q:\\<open>m = x\\<close>\n      from Q show \\<open>succ(m) \\<in> succ(succ(x))\\<close>\n        by auto\n    next\n      assume Q:\\<open>m \\<in> x\\<close>\n      have Q:\\<open>succ(m) \\<in> succ(x)\\<close>\n        by (rule mp[OF H1 Q])\n      from Q show \\<open>succ(m) \\<in> succ(succ(x))\\<close>\n        by (rule succI2)\n    qed\n  qed\nqed\n\ntheorem nat_linord:\\<open>\\<forall>n\\<in>nat. \\<forall>m\\<in>nat. m\\<in>n\\<or>m=n\\<or>n\\<in>m\\<close>\nproof(rule ballI)\n  fix n\n  assume H1:\\<open>n\\<in>nat\\<close>\n  show \\<open>\\<forall>m\\<in>nat. m \\<in> n \\<or> m = n \\<or> n \\<in> m\\<close>\n  proof(rule nat_induct[of n])\n    from H1 show \\<open>n\\<in>nat\\<close> by assumption\n  next\n    show \\<open>\\<forall>m\\<in>nat. m \\<in> 0 \\<or> m = 0 \\<or> 0 \\<in> m\\<close>\n    proof\n      fix m\n      assume J:\\<open>m\\<in>nat\\<close>\n      show \\<open> m \\<in> 0 \\<or> m = 0 \\<or> 0 \\<in> m\\<close>\n      proof(rule disjI2)\n        have Q:\\<open>0\\<in>m\\<or>0=m\\<close> by (rule bspec[OF zeroleq J])\n        show \\<open>m = 0 \\<or> 0 \\<in> m\\<close>\n          by (rule disjE[OF Q], auto)\n      qed\n    qed\n  next\n    fix x\n    assume K:\\<open>x\\<in>nat\\<close>\n    assume M:\\<open>\\<forall>m\\<in>nat. m \\<in> x \\<or> m = x \\<or> x \\<in> m\\<close>\n    show \\<open>\\<forall>m\\<in>nat.\n            m \\<in> succ(x) \\<or>\n            m = succ(x) \\<or>\n            succ(x) \\<in> m\\<close>\n    proof(rule nat_induct_bound)\n      show \\<open>0 \\<in> succ(x) \\<or>  0 = succ(x) \\<or> succ(x) \\<in> 0\\<close>\n      proof(rule disjI1)\n        show \\<open>0 \\<in> succ(x)\\<close>\n          by (rule bspec[OF zerolesucc K])\n      qed\n    next\n      fix y\n      assume H0:\\<open>y \\<in> nat\\<close>\n      assume H1:\\<open>y \\<in> succ(x) \\<or> y = succ(x) \\<or> succ(x) \\<in> y\\<close>\n      show \\<open>succ(y) \\<in> succ(x) \\<or>\n            succ(y) = succ(x) \\<or>\n            succ(x) \\<in> succ(y)\\<close>\n      proof(rule disjE[OF H1])\n        assume W:\\<open>y\\<in>succ(x)\\<close>\n        show \\<open>succ(y) \\<in> succ(x) \\<or>\n              succ(y) = succ(x) \\<or>\n              succ(x) \\<in> succ(y)\\<close>\n        proof(rule succE[OF W])\n          assume G:\\<open>y=x\\<close>\n          show \\<open>succ(y) \\<in> succ(x) \\<or>\n    succ(y) = succ(x) \\<or>\n    succ(x) \\<in> succ(y)\\<close>\n            by (rule disjI2, rule disjI1, rule subst[OF G], rule refl)\n        next\n          assume G:\\<open>y \\<in> x\\<close>\n          have R:\\<open>succ(y) \\<in> succ(x)\\<close>\n            by (rule mp[OF bspec[OF le_succ K] G])\n          show \\<open>succ(y) \\<in> succ(x) \\<or>\n           succ(y) = succ(x) \\<or>\n           succ(x) \\<in> succ(y)\\<close>\n            by(rule disjI1, rule R)\n        qed\n      next\n        assume W:\\<open>y = succ(x) \\<or> succ(x) \\<in> y\\<close>\n        show \\<open>succ(y) \\<in> succ(x) \\<or>\n              succ(y) = succ(x) \\<or>\n              succ(x) \\<in> succ(y)\\<close>\n        proof(rule disjE[OF W])\n          assume W:\\<open>y=succ(x)\\<close>\n          show \\<open>succ(y) \\<in> succ(x) \\<or>\n              succ(y) = succ(x) \\<or>\n              succ(x) \\<in> succ(y)\\<close>\n            by (rule disjI2, rule disjI2, rule subst[OF W], rule succI1)\n        next\n          assume W:\\<open>succ(x)\\<in>y\\<close>\n          show \\<open>succ(y) \\<in> succ(x) \\<or>\n              succ(y) = succ(x) \\<or>\n              succ(x) \\<in> succ(y)\\<close>\n            by (rule disjI2, rule disjI2, rule succI2[OF W])\n        qed\n      qed\n    qed\n  qed\nqed\n\nlemma tgb:\n  assumes knat: \\<open>k\\<in>nat\\<close>\n  assumes D: \\<open>t \\<in> k \\<rightarrow> A\\<close>\n  shows  \\<open>t \\<in> Pow(nat \\<times> A)\\<close>\nproof -\n  from D\n  have q:\\<open>t\\<in>{t\\<in>Pow(Sigma(k,%_.A)). k\\<subseteq>domain(t) & function(t)}\\<close>\n    by(unfold Pi_def)\n  have J:\\<open>t \\<in> Pow(k \\<times> A)\\<close>\n    by (rule CollectD1[OF q])\n  have G:\\<open>k \\<times> A \\<subseteq> nat \\<times> A\\<close>\n  proof(rule func.Sigma_mono)\n    from knat\n    show \\<open>k\\<subseteq>nat\\<close>\n      by (rule QUniv.naturals_subset_nat)\n  next\n    show \\<open>\\<And>x. x \\<in> k \\<Longrightarrow> A \\<subseteq> A\\<close>\n      by auto\n  qed\n  show \\<open>t \\<in> Pow(nat \\<times> A)\\<close>\n    by (rule subsetD, rule func.Pow_mono[OF G], rule J)\nqed\n\nsection \\<open>Compatible set\\<close>\ntext \\<open>Union of compatible set of functions is a function.\\<close>\n\ndefinition compat :: \\<open>[i,i]\\<Rightarrow>o\\<close>\n  where \"compat(f1,f2) == \\<forall>x.\\<forall>y1.\\<forall>y2.\\<langle>x,y1\\<rangle> \\<in> f1 \\<and> \\<langle>x,y2\\<rangle> \\<in> f2 \\<longrightarrow> y1=y2\"\n\nlemma compatI [intro]:\n  assumes H:\\<open>\\<And>x y1 y2.\\<lbrakk>\\<langle>x,y1\\<rangle> \\<in> f1; \\<langle>x,y2\\<rangle> \\<in> f2\\<rbrakk>\\<Longrightarrow>y1=y2\\<close>\n  shows \\<open>compat(f1,f2)\\<close>\nproof(unfold compat_def)\n  show \\<open>\\<forall>x y1 y2. \\<langle>x, y1\\<rangle> \\<in> f1 \\<and> \\<langle>x, y2\\<rangle> \\<in> f2 \\<longrightarrow> y1 = y2\\<close>\n  proof(rule allI | rule impI)+\n    fix x y1 y2\n    assume K:\\<open>\\<langle>x, y1\\<rangle> \\<in> f1 \\<and> \\<langle>x, y2\\<rangle> \\<in> f2\\<close>\n    have K1:\\<open>\\<langle>x, y1\\<rangle> \\<in> f1\\<close> by (rule conjunct1[OF K])\n    have K2:\\<open>\\<langle>x, y2\\<rangle> \\<in> f2\\<close> by (rule conjunct2[OF K])\n    show \\<open>y1 = y2\\<close> by (rule H[OF K1 K2])\n  qed\nqed\n\nlemma compatD:\n  assumes H: \\<open>compat(f1,f2)\\<close>\n  shows \\<open>\\<And>x y1 y2.\\<lbrakk>\\<langle>x,y1\\<rangle> \\<in> f1; \\<langle>x,y2\\<rangle> \\<in> f2\\<rbrakk>\\<Longrightarrow>y1=y2\\<close>\nproof -\n  fix x y1 y2\n  assume Q1:\\<open>\\<langle>x, y1\\<rangle> \\<in> f1\\<close>\n  assume Q2:\\<open>\\<langle>x, y2\\<rangle> \\<in> f2\\<close>\n  from H have H:\\<open>\\<forall>x y1 y2. \\<langle>x, y1\\<rangle> \\<in> f1 \\<and> \\<langle>x, y2\\<rangle> \\<in> f2 \\<longrightarrow> y1 = y2\\<close>\n    by (unfold compat_def)\n  show \\<open>y1=y2\\<close>\n  proof(rule mp[OF spec[OF spec[OF spec[OF H]]]])\n    show \\<open>\\<langle>x, y1\\<rangle> \\<in> f1 \\<and> \\<langle>x, y2\\<rangle> \\<in> f2\\<close>\n      by(rule conjI[OF Q1 Q2])\n  qed\nqed\n\nlemma compatE:\n  assumes H: \\<open>compat(f1,f2)\\<close>\n  and W:\\<open>(\\<And>x y1 y2.\\<lbrakk>\\<langle>x,y1\\<rangle> \\<in> f1; \\<langle>x,y2\\<rangle> \\<in> f2\\<rbrakk>\\<Longrightarrow>y1=y2) \\<Longrightarrow> E\\<close>\nshows \\<open>E\\<close>\n  by (rule W, rule compatD[OF H], assumption+)\n\n\ndefinition compatset :: \\<open>i\\<Rightarrow>o\\<close>\n  where \"compatset(S) == \\<forall>f1\\<in>S.\\<forall>f2\\<in>S. compat(f1,f2)\"\n\nlemma compatsetI [intro] :\n  assumes 1:\\<open>\\<And>f1 f2. \\<lbrakk>f1\\<in>S;f2\\<in>S\\<rbrakk> \\<Longrightarrow> compat(f1,f2)\\<close>\n  shows \\<open>compatset(S)\\<close>\n  by (unfold compatset_def, rule ballI, rule ballI, rule 1, assumption+)\n\nlemma compatsetD:\n  assumes H: \\<open>compatset(S)\\<close>\n  shows \\<open>\\<And>f1 f2.\\<lbrakk>f1\\<in>S; f2\\<in>S\\<rbrakk>\\<Longrightarrow>compat(f1,f2)\\<close>\nproof -\n  fix f1 f2\n  assume H1:\\<open>f1\\<in>S\\<close>\n  assume H2:\\<open>f2\\<in>S\\<close>\n  from H have H:\\<open>\\<forall>f1\\<in>S.\\<forall>f2\\<in>S. compat(f1,f2)\\<close>\n    by (unfold compatset_def)\n  show \\<open>compat(f1,f2)\\<close>\n    by (rule bspec[OF bspec[OF H H1] H2])\nqed\n\nlemma compatsetE:\n  assumes H: \\<open>compatset(S)\\<close>\n  and W:\\<open>(\\<And>f1 f2.\\<lbrakk>f1\\<in>S; f2\\<in>S\\<rbrakk>\\<Longrightarrow>compat(f1,f2)) \\<Longrightarrow> E\\<close>\nshows \\<open>E\\<close>\n  by (rule W, rule compatsetD[OF H], assumption+)\n\ntheorem upairI1 : \\<open>a \\<in> {a, b}\\<close>\nproof\n  assume \\<open>a \\<notin> {b}\\<close>\n  show \\<open>a = a\\<close> by (rule refl)\nqed\n\ntheorem upairI2 : \\<open>b \\<in> {a, b}\\<close>\nproof\n  assume H:\\<open>b \\<notin> {b}\\<close>\n  have Y:\\<open>b \\<in> {b}\\<close> by (rule upair.singletonI)\n  show \\<open>b = a\\<close> by (rule notE[OF H Y])\nqed\n\ntheorem sinup : \\<open>{x} \\<in> \\<langle>x, xa\\<rangle>\\<close>\nproof (unfold Pair_def)\n  show \\<open>{x} \\<in> {{x, x}, {x, xa}}\\<close>\n  proof (rule IFOL.subst)\n    show \\<open>{x} \\<in> {{x},{x,xa}}\\<close>\n      by (rule upairI1)\n  next\n    show \\<open>{{x}, {x, xa}} = {{x, x}, {x, xa}}\\<close>\n      by blast\n  qed\nqed\n\ntheorem compatsetunionfun :\n  fixes S\n  assumes H0:\\<open>compatset(S)\\<close>\n  shows \\<open>function(\\<Union>S)\\<close>\nproof(unfold function_def)\n  show \\<open> \\<forall>x y1. \\<langle>x, y1\\<rangle> \\<in> \\<Union>S \\<longrightarrow>\n          (\\<forall>y2. \\<langle>x, y2\\<rangle> \\<in> \\<Union>S \\<longrightarrow> y1 = y2)\\<close>\n  proof(rule allI, rule allI, rule impI, rule allI, rule impI)\n    fix x y1 y2\n    assume F1:\\<open>\\<langle>x, y1\\<rangle> \\<in> \\<Union>S\\<close>\n    assume F2:\\<open>\\<langle>x, y2\\<rangle> \\<in> \\<Union>S\\<close>\n    show \\<open>y1=y2\\<close>\n    proof(rule UnionE[OF F1], rule UnionE[OF F2])\n      fix f1 f2\n      assume J1:\\<open>\\<langle>x, y1\\<rangle> \\<in> f1\\<close>\n      assume J2:\\<open>\\<langle>x, y2\\<rangle> \\<in> f2\\<close>\n      assume K1:\\<open>f1 \\<in> S\\<close>\n      assume K2:\\<open>f2 \\<in> S\\<close>\n      have R:\\<open>compat(f1,f2)\\<close>\n        by (rule compatsetD[OF H0 K1 K2])\n      show \\<open>y1=y2\\<close>\n        by(rule compatD[OF R J1 J2])\n    qed\n  qed\nqed\n\ntheorem mkel :\n  assumes 1:\\<open>A\\<close>\n  assumes 2:\\<open>A\\<Longrightarrow>B\\<close>\n  shows \\<open>B\\<close>\n  by (rule 2, rule 1)\n\ntheorem valofunion :\n  fixes S\n  assumes H0:\\<open>compatset(S)\\<close>\n  assumes W:\\<open>f\\<in>S\\<close>\n  assumes Q:\\<open>f:A\\<rightarrow>B\\<close>\n  assumes T:\\<open>a\\<in>A\\<close>\n  assumes P:\\<open>f ` a = v\\<close>\n  shows N:\\<open>(\\<Union>S)`a = v\\<close>\nproof -\n  have K:\\<open>\\<langle>a, v\\<rangle> \\<in> f\\<close>\n    by (rule apparg[OF Q P T])\n  show N:\\<open>(\\<Union>S)`a = v\\<close>\n  proof(rule function_apply_equality)\n    show \\<open>function(\\<Union>S)\\<close>\n      by(rule compatsetunionfun[OF H0])\n  next\n    show \\<open>\\<langle>a, v\\<rangle> \\<in> \\<Union>S\\<close>\n      by(rule UnionI[OF W K ])\n  qed\nqed\n\nsection \"Partial computation\"\n\ndefinition satpc :: \\<open>[i,i,i] \\<Rightarrow> o \\<close>\n  where \\<open>satpc(t,\\<alpha>,g) == \\<forall>n \\<in> \\<alpha> . t`succ(n) = g ` <t`n, n>\\<close>\n\ntext \\<open>$m$-step computation based on $a$ and $g$\\<close>\ndefinition partcomp :: \\<open>[i,i,i,i,i]\\<Rightarrow>o\\<close>\n  where \\<open>partcomp(A,t,m,a,g) == (t:succ(m)\\<rightarrow>A) \\<and> (t`0=a) \\<and> satpc(t,m,g)\\<close>\n\nlemma partcompI [intro]:\n  assumes H1:\\<open>(t:succ(m)\\<rightarrow>A)\\<close>\n  assumes H2:\\<open>(t`0=a)\\<close>\n  assumes H3:\\<open>satpc(t,m,g)\\<close>\n  shows \\<open>partcomp(A,t,m,a,g)\\<close>\nproof (unfold partcomp_def, auto)\n  show \\<open>t \\<in> succ(m) \\<rightarrow> A\\<close> by (rule H1)\n  show \\<open>(t`0=a)\\<close> by (rule H2)\n  show \\<open>satpc(t,m,g)\\<close> by (rule H3)\nqed\n\nlemma partcompD1: \\<open>partcomp(A,t,m,a,g) \\<Longrightarrow> t \\<in> succ(m) \\<rightarrow> A\\<close>\n  by (unfold partcomp_def, auto)\n\nlemma partcompD2: \\<open>partcomp(A,t,m,a,g) \\<Longrightarrow> (t`0=a)\\<close>\n by (unfold partcomp_def, auto)\n\nlemma partcompD3: \\<open>partcomp(A,t,m,a,g) \\<Longrightarrow> satpc(t,m,g)\\<close>\n  by (unfold partcomp_def, auto)\n\nlemma partcompE [elim] :\n  assumes 1:\\<open>partcomp(A,t,m,a,g)\\<close>\n    and 2:\\<open>\\<lbrakk>(t:succ(m)\\<rightarrow>A) ; (t`0=a) ; satpc(t,m,g)\\<rbrakk> \\<Longrightarrow> E\\<close>\n  shows \\<open>E\\<close>\n  by (rule 2, rule partcompD1[OF 1], rule partcompD2[OF 1], rule partcompD3[OF 1])\n\ntext \\<open>If we add ordered pair in the middle of partial computation then\nit will not change.\\<close>\nlemma addmiddle:\n(*  fixes  t m a g*)\n  assumes mnat:\\<open>m\\<in>nat\\<close>\n  assumes F:\\<open>partcomp(A,t,m,a,g)\\<close>\n  assumes xinm:\\<open>x\\<in>m\\<close>\n  shows \\<open>cons(\\<langle>succ(x), g ` \\<langle>t ` x, x\\<rangle>\\<rangle>, t) = t\\<close>\nproof(rule partcompE[OF F])\n  assume F1:\\<open>t \\<in> succ(m) \\<rightarrow> A\\<close>\n  assume F2:\\<open>t ` 0 = a\\<close>\n  assume F3:\\<open>satpc(t, m, g)\\<close>\n  from F3\n  have W:\\<open>\\<forall>n\\<in>m. t ` succ(n) = g ` \\<langle>t ` n, n\\<rangle>\\<close>\n    by (unfold satpc_def)\n  have U:\\<open>t ` succ(x) = g ` \\<langle>t ` x, x\\<rangle>\\<close>\n    by (rule bspec[OF W xinm])\n  have E:\\<open>\\<langle>succ(x), (g ` \\<langle>t ` x, x\\<rangle>)\\<rangle> \\<in> t\\<close>\n  proof(rule apparg[OF F1 U])\n    show \\<open>succ(x) \\<in> succ(m)\\<close>\n      by(rule mp[OF bspec[OF le_succ mnat] xinm])\n  qed\n  show ?thesis\n    by (rule equalities.cons_absorb[OF E])\nqed\n\n\nsection \\<open>Set of functions \\<close>\ntext \\<open>It is denoted as $F$ on page 48 in \"Introduction to Set Theory\".\\<close>\ndefinition pcs :: \\<open>[i,i,i]\\<Rightarrow>i\\<close>\n  where \\<open>pcs(A,a,g) == {t\\<in>Pow(nat*A). \\<exists>m\\<in>nat. partcomp(A,t,m,a,g)}\\<close>\n\nlemma pcs_uniq :\n  assumes F1:\\<open>m1\\<in>nat\\<close>\n  assumes F2:\\<open>m2\\<in>nat\\<close>\n  assumes H1: \\<open>partcomp(A,f1,m1,a,g)\\<close>\n  assumes H2: \\<open>partcomp(A,f2,m2,a,g)\\<close>\n  shows \\<open>\\<forall>n\\<in>nat. n\\<in>succ(m1) \\<and> n\\<in>succ(m2) \\<longrightarrow> f1`n = f2`n\\<close>\nproof(rule partcompE[OF H1], rule partcompE[OF H2])\n  assume H11:\\<open>f1 \\<in> succ(m1) \\<rightarrow> A\\<close>\n  assume H12:\\<open>f1 ` 0 = a \\<close>\n  assume H13:\\<open>satpc(f1, m1, g)\\<close>\n  assume H21:\\<open>f2 \\<in> succ(m2) \\<rightarrow> A\\<close>\n  assume H22:\\<open>f2 ` 0 = a\\<close>\n  assume H23:\\<open>satpc(f2, m2, g)\\<close>\n  show \\<open>\\<forall>n\\<in>nat. n\\<in>succ(m1) \\<and> n\\<in>succ(m2) \\<longrightarrow> f1`n = f2`n\\<close>\nproof(rule nat_induct_bound)\n  from H12 and H22\n  show \\<open>0\\<in>succ(m1) \\<and> 0\\<in>succ(m2) \\<longrightarrow> f1 ` 0 = f2 ` 0\\<close>\n    by auto\nnext\n  fix x\n  assume J0:\\<open>x\\<in>nat\\<close>\n  assume J1:\\<open>x \\<in> succ(m1) \\<and> x \\<in> succ(m2) \\<longrightarrow> f1 ` x = f2 ` x\\<close>\n  from H13 have G1:\\<open>\\<forall>n \\<in> m1 . f1`succ(n) = g ` <f1`n, n>\\<close>\n    by (unfold satpc_def, auto)\n  from H23 have G2:\\<open>\\<forall>n \\<in> m2 . f2`succ(n) = g ` <f2`n, n>\\<close>\n    by (unfold satpc_def, auto)\n  show \\<open>succ(x) \\<in> succ(m1) \\<and> succ(x) \\<in> succ(m2) \\<longrightarrow>\n        f1 ` succ(x) = f2 ` succ(x)\\<close>\n  proof\n    assume K:\\<open>succ(x) \\<in> succ(m1) \\<and> succ(x) \\<in> succ(m2)\\<close>\n    from K have K1:\\<open>succ(x) \\<in> succ(m1)\\<close> by auto\n    from K have K2:\\<open>succ(x) \\<in> succ(m2)\\<close> by auto\n    have K1':\\<open>x \\<in> m1\\<close> by (rule mp[OF bspec[OF succ_le F1] K1])\n    have K2':\\<open>x \\<in> m2\\<close> by (rule mp[OF bspec[OF succ_le F2] K2])\n    have U1:\\<open>x\\<in>succ(m1)\\<close>\n      by (rule Nat.succ_in_naturalD[OF K1 Nat.nat_succI[OF F1]])\n    have U2:\\<open>x\\<in>succ(m2)\\<close>\n      by (rule Nat.succ_in_naturalD[OF K2 Nat.nat_succI[OF F2]])\n    have Y1:\\<open>f1`succ(x) = g ` <f1`x, x>\\<close>\n      by (rule bspec[OF G1 K1'])\n    have Y2:\\<open>f2`succ(x) = g ` <f2`x, x>\\<close>\n      by (rule bspec[OF G2 K2'])\n    have \\<open>f1 ` x = f2 ` x\\<close>\n      by(rule mp[OF J1 conjI[OF U1 U2]])\n    then have Y:\\<open>g ` <f1`x, x> = g ` <f2`x, x>\\<close> by auto\n    from Y1 and Y2 and Y\n    show \\<open>f1 ` succ(x) = f2 ` succ(x)\\<close>\n      by auto\n  qed\nqed\nqed\n\nlemma domainsubsetfunc :\n  assumes Q:\\<open>f1\\<subseteq>f2\\<close>\n  shows \\<open>domain(f1)\\<subseteq>domain(f2)\\<close>\nproof\n  fix x\n  assume H:\\<open>x \\<in> domain(f1)\\<close>\n  show \\<open>x \\<in> domain(f2)\\<close>\n  proof(rule domainE[OF H])\n    fix y\n    assume W:\\<open>\\<langle>x, y\\<rangle> \\<in> f1\\<close>\n    have \\<open>\\<langle>x, y\\<rangle> \\<in> f2\\<close>\n      by(rule subsetD[OF Q W])\n    then show \\<open>x \\<in> domain(f2)\\<close>\n      by(rule domainI)\n  qed\nqed\n\nlemma natdomfunc:\n  assumes 1:\\<open>q\\<in>A\\<close>\n  assumes J0:\\<open>f1 \\<in> Pow(nat \\<times> A)\\<close>\n  assumes U:\\<open>m1 \\<in> domain(f1)\\<close>\n  shows \\<open>m1\\<in>nat\\<close>\nproof -\n  from J0 have J0 : \\<open>f1 \\<subseteq> nat \\<times> A\\<close>\n    by auto\n  have J0:\\<open>domain(f1) \\<subseteq> domain(nat \\<times> A)\\<close>\n    by(rule func.domain_mono[OF J0])\n  have F:\\<open>m1 \\<in> domain(nat \\<times> A)\\<close>\n    by(rule subsetD[OF J0 U])\n  have R:\\<open>domain(nat \\<times> A) = nat\\<close>\n    by (rule equalities.domain_of_prod[OF 1])\n  show \\<open>m1 \\<in> nat\\<close>\n    by(rule subst[OF R], rule F)\nqed\n\nlemma pcs_lem :\n  assumes 1:\\<open>q\\<in>A\\<close>\n  shows \\<open>compatset(pcs(A, a, g))\\<close>\nproof (*(rule compatsetI)*)\n  fix f1 f2\n  assume H1:\\<open>f1 \\<in> pcs(A, a, g)\\<close>\n  then have H1':\\<open>f1 \\<in> {t\\<in>Pow(nat*A). \\<exists>m\\<in>nat. partcomp(A,t,m,a,g)}\\<close> by (unfold pcs_def)\n  hence H1'A:\\<open>f1 \\<in> Pow(nat*A)\\<close> by auto\n  hence H1'A:\\<open>f1 \\<subseteq> (nat*A)\\<close> by auto\n  assume H2:\\<open>f2 \\<in> pcs(A, a, g)\\<close>\n  then have H2':\\<open>f2 \\<in> {t\\<in>Pow(nat*A). \\<exists>m\\<in>nat. partcomp(A,t,m,a,g)}\\<close> by (unfold pcs_def)\n  show \\<open>compat(f1, f2)\\<close>\n  proof(rule compatI)\n    fix x y1 y2\n    assume P1:\\<open>\\<langle>x, y1\\<rangle> \\<in> f1\\<close>\n    assume P2:\\<open>\\<langle>x, y2\\<rangle> \\<in> f2\\<close>\n    show \\<open>y1 = y2\\<close>\n    proof(rule CollectE[OF H1'], rule CollectE[OF H2'])\n      assume J0:\\<open>f1 \\<in> Pow(nat \\<times> A)\\<close>\n      assume J1:\\<open>f2 \\<in> Pow(nat \\<times> A)\\<close>\n      assume J2:\\<open>\\<exists>m\\<in>nat. partcomp(A, f1, m, a, g)\\<close>\n      assume J3:\\<open>\\<exists>m\\<in>nat. partcomp(A, f2, m, a, g)\\<close>\n      show \\<open>y1 = y2\\<close>\n      proof(rule bexE[OF J2], rule bexE[OF J3])\n        fix m1 m2\n        assume K1:\\<open>partcomp(A, f1, m1, a, g)\\<close>\n        assume K2:\\<open>partcomp(A, f2, m2, a, g)\\<close>\n        hence K2':\\<open>(f2:succ(m2)\\<rightarrow>A) \\<and> (f2`0=a) \\<and> satpc(f2,m2,g)\\<close>\n          by (unfold partcomp_def)\n        from K1 have K1'A:\\<open>(f1:succ(m1)\\<rightarrow>A)\\<close> by (rule partcompD1)\n        from K2' have K2'A:\\<open>(f2:succ(m2)\\<rightarrow>A)\\<close> by auto\n        from K1'A have K1'AD:\\<open>domain(f1) = succ(m1)\\<close>\n          by(rule domain_of_fun)\n        from K2'A have K2'AD:\\<open>domain(f2) = succ(m2)\\<close>\n          by(rule domain_of_fun)\n        have L1:\\<open>f1`x=y1\\<close>\n          by (rule func.apply_equality[OF P1], rule K1'A)\n        have L2:\\<open>f2`x=y2\\<close>\n          by(rule func.apply_equality[OF P2], rule K2'A)\n        have m1nat:\\<open>m1\\<in>nat\\<close>\n        proof(rule natdomfunc[OF 1 J0])\n          show \\<open>m1 \\<in> domain(f1)\\<close>\n            by (rule ssubst[OF K1'AD], auto)\n        qed\n        have m2nat:\\<open>m2\\<in>nat\\<close>\n        proof(rule natdomfunc[OF 1 J1])\n          show \\<open>m2 \\<in> domain(f2)\\<close>\n            by (rule ssubst[OF K2'AD], auto)\n        qed\n        have G1:\\<open>\\<langle>x, y1\\<rangle> \\<in> (nat*A)\\<close>\n          by(rule subsetD[OF H1'A P1])\n        have KK:\\<open>x\\<in>nat\\<close>\n          by(rule SigmaE[OF G1], auto)\n        (*x is in the domain of f1  i.e. succ(m1)\nso we can have both  x \\<in> ?m1.2 \\<and> x \\<in> ?m2.2\nhow to prove that m1 \\<in> nat ? from J0 !  f1 is a subset of nat \\<times> A*)\n        have W:\\<open>f1`x=f2`x\\<close>\n        proof(rule mp[OF bspec[OF pcs_uniq KK] ])\n          show \\<open>m1 \\<in> nat\\<close>\n            by (rule m1nat)\n        next\n          show \\<open>m2 \\<in> nat\\<close>\n            by (rule m2nat)\n        next\n          show \\<open>partcomp(A, f1, m1, a, g)\\<close>\n            by (rule K1)\n        next\n          show \\<open>partcomp(A, f2, m2, a, g)\\<close>\n            by (rule K2)\n        next\n            (*  P1:\\<open>\\<langle>x, y1\\<rangle> \\<in> f1\\<close>\n              K1'A:\\<open>(f1:succ(m1)\\<rightarrow>A)\\<close>\n            *)\n          have U1:\\<open>x \\<in> succ(m1)\\<close>\n            by (rule func.domain_type[OF P1 K1'A])\n          have U2:\\<open>x \\<in> succ(m2)\\<close>\n            by (rule func.domain_type[OF P2 K2'A])\n          show \\<open>x \\<in> succ(m1) \\<and> x \\<in> succ(m2)\\<close>\n            by (rule conjI[OF U1 U2])\n        qed\n        from L1 and W and L2\n        show \\<open>y1 = y2\\<close> by auto\n      qed\n    qed\n  qed\nqed\n\ntheorem fuissu : \\<open>f \\<in> X -> Y \\<Longrightarrow> f \\<subseteq> X\\<times>Y\\<close>\nproof\n  fix w\n  assume H1 : \\<open>f \\<in> X -> Y\\<close>\n  then have J1:\\<open>f \\<in> {q\\<in>Pow(Sigma(X,\\<lambda>_.Y)). X\\<subseteq>domain(q) & function(q)}\\<close>\n    by (unfold Pi_def)\n  then have J2:\\<open>f \\<in> Pow(Sigma(X,\\<lambda>_.Y))\\<close>\n    by auto\n  then have J3:\\<open>f \\<subseteq> Sigma(X,\\<lambda>_.Y)\\<close>\n    by auto\n  assume H2 : \\<open>w \\<in> f\\<close>\n  from J3 and H2 have \\<open>w\\<in>Sigma(X,\\<lambda>_.Y)\\<close>\n    by auto\n  then have J4:\\<open>w \\<in> (\\<Union>x\\<in>X. (\\<Union>y\\<in>Y. {\\<langle>x,y\\<rangle>}))\\<close>\n    by auto\n  show \\<open>w \\<in> X*Y\\<close>\n  proof (rule UN_E[OF J4])\n    fix x\n    assume V1:\\<open>x \\<in> X\\<close>\n    assume V2:\\<open>w \\<in> (\\<Union>y\\<in>Y. {\\<langle>x, y\\<rangle>})\\<close>\n    show \\<open>w \\<in> X \\<times> Y\\<close>\n    proof (rule UN_E[OF V2])\n      fix y\n      assume V3:\\<open>y \\<in> Y\\<close>\n      assume V4:\\<open>w \\<in> {\\<langle>x, y\\<rangle>}\\<close>\n      then have V4:\\<open>w = \\<langle>x, y\\<rangle>\\<close>\n        by auto\n      have v5:\\<open>\\<langle>x, y\\<rangle> \\<in> Sigma(X,\\<lambda>_.Y)\\<close>\n      proof(rule SigmaI)\n        show \\<open>x \\<in> X\\<close> by (rule V1)\n      next\n        show \\<open>y \\<in> Y\\<close> by (rule V3)\n      qed\n      then have V5:\\<open>\\<langle>x, y\\<rangle> \\<in> X*Y\\<close>\n        by auto\n      from V4 and V5 show \\<open>w \\<in> X \\<times> Y\\<close> by auto\n    qed\n  qed\nqed\n\ntheorem recuniq :\n  fixes f\n  assumes H0:\\<open>f \\<in> nat -> A \\<and> f ` 0 = a \\<and> satpc(f, nat, g)\\<close>\n  fixes t\n  assumes H1:\\<open>t \\<in> nat -> A \\<and> t ` 0 = a \\<and> satpc(t, nat, g)\\<close>\n  fixes x\n  shows \\<open>f=t\\<close>\nproof -\n  from H0 have H02:\\<open>\\<forall>n \\<in> nat. f`succ(n) = g ` <(f`n), n>\\<close> by (unfold satpc_def, auto)\n  from H0 have H01:\\<open>f ` 0 = a\\<close> by auto\n  from H0 have H00:\\<open>f \\<in> nat -> A\\<close> by auto\n  from H1 have H12:\\<open>\\<forall>n \\<in> nat. t`succ(n) = g ` <(t`n), n>\\<close> by (unfold satpc_def, auto)\n  from H1 have H11:\\<open>t ` 0 = a\\<close> by auto\n  from H1 have H10:\\<open>t \\<in> nat -> A\\<close> by auto\n  show \\<open>f=t\\<close>\n  proof (rule fun_extension[OF H00 H10])\n    fix x\n    assume K: \\<open>x \\<in> nat\\<close>\n    show \\<open>(f ` x) = (t ` x)\\<close>\n    proof(rule nat_induct[of x])\n      show \\<open>x \\<in> nat\\<close> by (rule K)\n    next\n      from H01 and H11 show \\<open>f ` 0 = t ` 0\\<close>\n        by auto\n    next\n      fix x\n      assume A:\\<open>x\\<in>nat\\<close>\n      assume B:\\<open>f`x = t`x\\<close>\n      show \\<open>f ` succ(x) = t ` succ(x)\\<close>\n      proof -\n        from H02 and A have H02':\\<open>f`succ(x) = g ` <(f`x), x>\\<close>\n          by (rule bspec)\n        from H12 and A have H12':\\<open>t`succ(x) = g ` <(t`x), x>\\<close>\n          by (rule bspec)\n        from B and H12' have H12'':\\<open>t`succ(x) = g ` <(f`x), x>\\<close> by auto\n        from H12'' and H02' show \\<open>f ` succ(x) = t ` succ(x)\\<close> by auto\n      qed\n    qed\n  qed\nqed\n\nsection \\<open>Lemmas for recursion theorem\\<close>\n\nlocale recthm =\n  fixes A :: \"i\"\n    and a :: \"i\"\n    and g :: \"i\"\n  assumes hyp1 : \\<open>a \\<in> A\\<close>\n    and hyp2 : \\<open>g : ((A*nat)\\<rightarrow>A)\\<close>\nbegin\n\nlemma l3:\\<open>function(\\<Union>pcs(A, a, g))\\<close>\n  by (rule compatsetunionfun, rule pcs_lem, rule hyp1)\n\nlemma l1 : \\<open>\\<Union>pcs(A, a, g) \\<subseteq> nat \\<times> A\\<close>\nproof\n  fix x\n  assume H:\\<open>x \\<in> \\<Union>pcs(A, a, g)\\<close>\n  hence  H:\\<open>x \\<in> \\<Union>{t\\<in>Pow(nat*A). \\<exists>m\\<in>nat. partcomp(A,t,m,a,g)}\\<close>\n    by (unfold pcs_def)\n  show \\<open>x \\<in> nat \\<times> A\\<close>\n  proof(rule UnionE[OF H])\n    fix B\n    assume J1:\\<open>x\\<in>B\\<close>\n    assume J2:\\<open>B \\<in> {t \\<in> Pow(nat \\<times> A) .\n            \\<exists>m\\<in>nat. partcomp(A, t, m, a, g)}\\<close>\n    hence J2:\\<open>B \\<in> Pow(nat \\<times> A)\\<close> by auto\n    hence J2:\\<open>B \\<subseteq> nat \\<times> A\\<close> by auto\n    from J1 and J2 show \\<open>x \\<in> nat \\<times> A\\<close>\n      by auto\n  qed\nqed\n\nlemma le1:\n  assumes H:\\<open>x\\<in>1\\<close>\n  shows \\<open>x=0\\<close>\nproof\n  show \\<open>x \\<subseteq> 0\\<close>\n  proof\n    fix z\n    assume J:\\<open>z\\<in>x\\<close>\n    show \\<open>z\\<in>0\\<close>\n    proof(rule succE[OF H])\n      assume J:\\<open>x\\<in>0\\<close>\n      show \\<open>z\\<in>0\\<close>\n        by (rule notE[OF not_mem_empty J])\n    next\n      assume K:\\<open>x=0\\<close>\n      from J and K show \\<open>z\\<in>0\\<close>\n        by auto\n    qed\n  qed\nnext\n  show \\<open>0 \\<subseteq> x\\<close> by auto\nqed\n\nlemma lsinglfun : \\<open>function({\\<langle>0, a\\<rangle>})\\<close>\nproof(unfold function_def)\n  show \\<open> \\<forall>x y. \\<langle>x, y\\<rangle> \\<in> {\\<langle>0, a\\<rangle>} \\<longrightarrow>\n          (\\<forall>y'. \\<langle>x, y'\\<rangle> \\<in> {\\<langle>0, a\\<rangle>} \\<longrightarrow>\n                y = y')\\<close>\n  proof(rule allI,rule allI,rule impI,rule allI,rule impI)\n    fix x y y'\n    assume H0:\\<open>\\<langle>x, y\\<rangle> \\<in> {\\<langle>0, a\\<rangle>}\\<close>\n    assume H1:\\<open>\\<langle>x, y'\\<rangle> \\<in> {\\<langle>0, a\\<rangle>}\\<close>\n    show \\<open>y = y'\\<close>\n    proof(rule upair.singletonE[OF H0],rule upair.singletonE[OF H1])\n      assume H0:\\<open>\\<langle>x, y\\<rangle> = \\<langle>0, a\\<rangle>\\<close>\n      assume H1:\\<open>\\<langle>x, y'\\<rangle> = \\<langle>0, a\\<rangle>\\<close>\n      from H0 and H1 have H:\\<open>\\<langle>x, y\\<rangle> = \\<langle>x, y'\\<rangle>\\<close> by auto\n      then show \\<open>y = y'\\<close> by auto\n    qed\n  qed\nqed\n\nlemma singlsatpc:\\<open>satpc({\\<langle>0, a\\<rangle>}, 0, g)\\<close>\nproof(unfold satpc_def)\n  show \\<open>\\<forall>n\\<in>0. {\\<langle>0, a\\<rangle>} ` succ(n) =\n           g ` \\<langle>{\\<langle>0, a\\<rangle>} ` n, n\\<rangle>\\<close>\n    by auto\nqed\n\nlemma zerostep :\n  shows \\<open>partcomp(A, {\\<langle>0, a\\<rangle>}, 0, a, g)\\<close>\nproof(unfold partcomp_def)\n  show \\<open>{\\<langle>0, a\\<rangle>} \\<in> 1 -> A \\<and> {\\<langle>0, a\\<rangle>} ` 0 = a \\<and> satpc({\\<langle>0, a\\<rangle>}, 0, g)\\<close>\n  proof\n    show \\<open>{\\<langle>0, a\\<rangle>} \\<in> 1 -> A\\<close>\n    proof (unfold Pi_def)\n      show \\<open>{\\<langle>0, a\\<rangle>} \\<in> {f \\<in> Pow(1 \\<times> A) . 1 \\<subseteq> domain(f) \\<and> function(f)}\\<close>\n      proof\n        show \\<open>{\\<langle>0, a\\<rangle>} \\<in> Pow(1 \\<times> A)\\<close>\n        proof(rule PowI, rule equalities.singleton_subsetI)\n          show \\<open>\\<langle>0, a\\<rangle> \\<in> 1 \\<times> A\\<close>\n          proof\n            show \\<open>0 \\<in> 1\\<close> by auto\n          next\n            show \\<open>a \\<in> A\\<close> by (rule hyp1)\n          qed\n        qed\n      next\n        show \\<open>1 \\<subseteq> domain({\\<langle>0, a\\<rangle>}) \\<and> function({\\<langle>0, a\\<rangle>})\\<close>\n        proof\n          show \\<open>1 \\<subseteq> domain({\\<langle>0, a\\<rangle>})\\<close>\n          proof\n            fix x\n            assume W:\\<open>x\\<in>1\\<close>\n            from W have W:\\<open>x=0\\<close> by (rule le1)\n            have Y:\\<open>0\\<in>domain({\\<langle>0, a\\<rangle>})\\<close>\n              by auto\n            from W and Y\n            show \\<open>x\\<in>domain({\\<langle>0, a\\<rangle>})\\<close>\n              by auto\n          qed\n        next\n          show \\<open>function({\\<langle>0, a\\<rangle>})\\<close>\n            by (rule lsinglfun)\n        qed\n      qed\n    qed\n    show \\<open>{\\<langle>0, a\\<rangle>} ` 0 = a \\<and> satpc({\\<langle>0, a\\<rangle>}, 0, g)\\<close>\n    proof\n      show \\<open>{\\<langle>0, a\\<rangle>} ` 0 = a\\<close>\n        by (rule func.singleton_apply)\n    next\n      show \\<open>satpc({\\<langle>0, a\\<rangle>}, 0, g)\\<close>\n        by (rule singlsatpc)\n    qed\n  qed\nqed\n\nlemma zainupcs : \\<open>\\<langle>0, a\\<rangle> \\<in> \\<Union>pcs(A, a, g)\\<close>\nproof\n  show \\<open>\\<langle>0, a\\<rangle> \\<in> {\\<langle>0, a\\<rangle>}\\<close>\n    by auto\nnext\n  (* {\\<langle>0, a\\<rangle>} is a 0-step computation *)\n  show \\<open>{\\<langle>0, a\\<rangle>} \\<in> pcs(A, a, g)\\<close>\n  proof(unfold pcs_def)\n    show \\<open>{\\<langle>0, a\\<rangle>} \\<in> {t \\<in> Pow(nat \\<times> A) . \\<exists>m\\<in>nat. partcomp(A, t, m, a, g)}\\<close>\n    proof\n      show \\<open>{\\<langle>0, a\\<rangle>} \\<in> Pow(nat \\<times> A)\\<close>\n      proof(rule PowI, rule equalities.singleton_subsetI)\n        show \\<open>\\<langle>0, a\\<rangle> \\<in> nat \\<times> A\\<close>\n        proof\n          show \\<open>0 \\<in> nat\\<close> by auto\n        next\n          show \\<open>a \\<in> A\\<close> by (rule hyp1)\n        qed\n      qed\n    next\n      show \\<open>\\<exists>m\\<in>nat. partcomp(A, {\\<langle>0, a\\<rangle>}, m, a, g)\\<close>\n      proof\n        show \\<open>partcomp(A, {\\<langle>0, a\\<rangle>}, 0, a, g)\\<close>\n          by (rule zerostep)\n      next\n        show \\<open>0 \\<in> nat\\<close> by auto\n      qed\n    qed\n  qed\nqed\n\nlemma l2': \\<open>0 \\<in> domain(\\<Union>pcs(A, a, g))\\<close>\nproof\n  show \\<open>\\<langle>0, a\\<rangle> \\<in> \\<Union>pcs(A, a, g)\\<close>\n    by (rule zainupcs)\nqed\n\ntext \\<open>Push an ordered pair to the end of partial computation t\nand obtain another partial computation.\\<close>\nlemma shortlem :\n  assumes mnat:\\<open>m\\<in>nat\\<close>\n  assumes F:\\<open>partcomp(A,t,m,a,g)\\<close>\n  shows \\<open>partcomp(A,cons(\\<langle>succ(m), g ` <t`m, m>\\<rangle>, t),succ(m),a,g)\\<close>\nproof(rule partcompE[OF F])\n  assume F1:\\<open>t \\<in> succ(m) \\<rightarrow> A\\<close>\n  assume F2:\\<open>t ` 0 = a\\<close>\n  assume F3:\\<open>satpc(t, m, g)\\<close>\n  show ?thesis (*\\<open>partcomp(A,cons(\\<langle>succ(m), g ` <t`m, m>\\<rangle>, t),succ(m),a,g)\\<close> *)\n  proof\n    have ljk:\\<open>cons(\\<langle>succ(m), g ` \\<langle>t ` m, m\\<rangle>\\<rangle>, t) \\<in> (cons(succ(m),succ(m)) \\<rightarrow> A)\\<close>\n    proof(rule func.fun_extend3[OF F1])\n      show \\<open>succ(m) \\<notin> succ(m)\\<close>\n        by (rule  upair.mem_not_refl)\n      have tmA:\\<open>t ` m \\<in> A\\<close>\n        by (rule func.apply_funtype[OF F1], auto)\n      show \\<open>g ` \\<langle>t ` m, m\\<rangle> \\<in> A\\<close>\n        by(rule func.apply_funtype[OF hyp2], auto, rule tmA, rule mnat)\n    qed\n    have \\<open>cons(\\<langle>succ(m), g ` \\<langle>t ` m, m\\<rangle>\\<rangle>, t) \\<in> (cons(succ(m),succ(m)) \\<rightarrow> A)\\<close>\n      by (rule ljk)\n    then have \\<open>cons(\\<langle>cons(m, m), g ` \\<langle>t ` m, m\\<rangle>\\<rangle>, t) \\<in> cons(cons(m, m), cons(m, m)) \\<rightarrow> A\\<close>\n      by (unfold succ_def)\n    then show \\<open>cons(\\<langle>succ(m), g ` \\<langle>t ` m, m\\<rangle>\\<rangle>, t) \\<in> succ(succ(m)) \\<rightarrow> A\\<close>\n      by (unfold succ_def, assumption)\n    show \\<open>cons(\\<langle>succ(m), g ` \\<langle>t ` m, m\\<rangle>\\<rangle>, t) ` 0 = a\\<close>\n    proof(rule trans, rule func.fun_extend_apply[OF F1])\n      show \\<open>succ(m) \\<notin> succ(m)\\<close> by (rule  upair.mem_not_refl)\n      show \\<open>(if 0 = succ(m) then g ` \\<langle>t ` m, m\\<rangle> else t ` 0) = a\\<close>\n        by(rule trans, rule upair.if_not_P, auto, rule F2)\n    qed\n    show \\<open>satpc(cons(\\<langle>succ(m), g ` \\<langle>t ` m, m\\<rangle>\\<rangle>, t), succ(m), g)\\<close>\n    proof(unfold satpc_def, rule ballI)\n      fix n\n      assume Q:\\<open>n \\<in> succ(m)\\<close>\n      show \\<open>cons(\\<langle>succ(m), g ` \\<langle>t ` m, m\\<rangle>\\<rangle>, t) ` succ(n)\n= g ` \\<langle>cons(\\<langle>succ(m), g ` \\<langle>t ` m, m\\<rangle>\\<rangle>, t) ` n, n\\<rangle>\\<close>\n      proof(rule trans, rule func.fun_extend_apply[OF F1], rule upair.mem_not_refl)\n        show \\<open>(if succ(n) = succ(m) then g ` \\<langle>t ` m, m\\<rangle> else t ` succ(n)) =\n    g ` \\<langle>cons(\\<langle>succ(m), g ` \\<langle>t ` m, m\\<rangle>\\<rangle>, t) ` n, n\\<rangle>\\<close>\n        proof(rule upair.succE[OF Q])\n          assume Y:\\<open>n=m\\<close>\n          show \\<open>(if succ(n) = succ(m) then g ` \\<langle>t ` m, m\\<rangle> else t ` succ(n)) =\n    g ` \\<langle>cons(\\<langle>succ(m), g ` \\<langle>t ` m, m\\<rangle>\\<rangle>, t) ` n, n\\<rangle>\\<close>\n          proof(rule trans, rule upair.if_P)\n            from Y show \\<open>succ(n) = succ(m)\\<close> by auto\n          next\n            have L1:\\<open>t ` m = cons(\\<langle>succ(m), g ` \\<langle>t ` m, m\\<rangle>\\<rangle>, t) ` n\\<close>\n            proof(rule sym, rule trans, rule func.fun_extend_apply[OF F1], rule upair.mem_not_refl)\n              show \\<open> (if n = succ(m) then g ` \\<langle>t ` m, m\\<rangle> else t ` n) = t ` m\\<close>\n              proof(rule trans, rule upair.if_not_P)\n                from Y show \\<open>t ` n = t ` m\\<close> by auto\n                show \\<open>n \\<noteq> succ(m)\\<close>\n                proof(rule not_sym)\n                  show \\<open>succ(m) \\<noteq> n\\<close>\n                    by(rule subst, rule sym, rule Y, rule upair.succ_neq_self)\n                qed\n              qed\n            qed\n            from Y\n            have L2:\\<open>m = n\\<close>\n              by auto\n            have L:\\<open> \\<langle>t ` m, m\\<rangle> = \\<langle>cons(\\<langle>succ(m), g ` \\<langle>t ` m, m\\<rangle>\\<rangle>, t) ` n, n\\<rangle>\\<close>\n              by(rule subst_context2[OF L1 L2])\n            show \\<open> g ` \\<langle>t ` m, m\\<rangle> = g ` \\<langle>cons(\\<langle>succ(m), g ` \\<langle>t ` m, m\\<rangle>\\<rangle>, t) ` n, n\\<rangle>\\<close>\n              by(rule subst_context[OF L])\n          qed\n        next\n          assume Y:\\<open>n \\<in> m\\<close>\n          show \\<open>(if succ(n) = succ(m) then g ` \\<langle>t ` m, m\\<rangle> else t ` succ(n)) =\n                g ` \\<langle>cons(\\<langle>succ(m), g ` \\<langle>t ` m, m\\<rangle>\\<rangle>, t) ` n, n\\<rangle>\\<close>\n          proof(rule trans, rule upair.if_not_P)\n            show \\<open>succ(n) \\<noteq> succ(m)\\<close>\n              by(rule contrapos, rule upair.mem_imp_not_eq, rule Y, rule upair.succ_inject, assumption)\n          next\n            have X:\\<open>cons(\\<langle>succ(m), g ` \\<langle>t ` m, m\\<rangle>\\<rangle>, t) ` n = t ` n\\<close>\n            proof(rule trans, rule func.fun_extend_apply[OF F1], rule upair.mem_not_refl)\n              show \\<open>(if n = succ(m) then g ` \\<langle>t ` m, m\\<rangle> else t ` n) = t ` n\\<close>\n              proof(rule upair.if_not_P)\n                show \\<open>n \\<noteq> succ(m)\\<close>\n                proof(rule contrapos)\n                  assume q:\"n=succ(m)\"\n                  from q and Y have M:\\<open>succ(m)\\<in>m\\<close>\n                    by auto\n                  show \\<open>m\\<in>m\\<close>\n                    by(rule Nat.succ_in_naturalD[OF M mnat])\n                next\n                  show \\<open>m \\<notin> m\\<close> by (rule  upair.mem_not_refl)\n                qed\n              qed\n            qed\n            from F3\n            have W:\\<open>\\<forall>n\\<in>m. t ` succ(n) = g ` \\<langle>t ` n, n\\<rangle>\\<close>\n              by (unfold satpc_def)\n            have U:\\<open>t ` succ(n) = g ` \\<langle>t ` n, n\\<rangle>\\<close>\n              by (rule bspec[OF W Y])\n            show \\<open>t ` succ(n) = g ` \\<langle>cons(\\<langle>succ(m), g ` \\<langle>t ` m, m\\<rangle>\\<rangle>, t) ` n, n\\<rangle>\\<close>\n              by (rule trans, rule U, rule sym, rule subst_context[OF X])\n          qed\n        qed\n      qed\n    qed\n  qed\nqed\n\nlemma l2:\\<open>nat \\<subseteq> domain(\\<Union>pcs(A, a, g))\\<close>\nproof\n  fix x\n  assume G:\\<open>x\\<in>nat\\<close>\n  show \\<open>x \\<in> domain(\\<Union>pcs(A, a, g))\\<close>\n  proof(rule nat_induct[of x])\n    show \\<open>x\\<in>nat\\<close> by (rule G)\n  next\n    fix x\n    assume Q1:\\<open>x\\<in>nat\\<close>\n    assume Q2:\\<open>x\\<in>domain(\\<Union>pcs(A, a, g))\\<close>\n    show \\<open>succ(x)\\<in>domain(\\<Union>pcs(A, a, g))\\<close>\n    proof(rule domainE[OF Q2])\n      fix y\n      assume W1:\\<open>\\<langle>x, y\\<rangle> \\<in> (\\<Union>pcs(A, a, g))\\<close>\n      show \\<open>succ(x)\\<in>domain(\\<Union>pcs(A, a, g))\\<close>\n      proof(rule UnionE[OF W1])\n        fix t\n        assume E1:\\<open>\\<langle>x, y\\<rangle> \\<in> t\\<close>\n        assume E2:\\<open>t \\<in> pcs(A, a, g)\\<close>\n        hence E2:\\<open>t\\<in>{t\\<in>Pow(nat*A). \\<exists>m \\<in> nat. partcomp(A,t,m,a,g)}\\<close>\n          by(unfold pcs_def)\n        have E21:\\<open>t\\<in>Pow(nat*A)\\<close>\n          by(rule CollectD1[OF E2])\n        have E22m:\\<open>\\<exists>m\\<in>nat. partcomp(A,t,m,a,g)\\<close>\n          by(rule CollectD2[OF E2])\n        show \\<open>succ(x)\\<in>domain(\\<Union>pcs(A, a, g))\\<close>\n        proof(rule bexE[OF E22m])\n          fix m\n          assume mnat:\\<open>m\\<in>nat\\<close>\n          assume E22P:\\<open>partcomp(A,t,m,a,g)\\<close>\n          hence E22:\\<open>((t:succ(m)\\<rightarrow>A) \\<and> (t`0=a)) \\<and> satpc(t,m,g)\\<close>\n            by(unfold partcomp_def, auto)\n          hence E223:\\<open>satpc(t,m,g)\\<close> by auto\n          hence E223:\\<open>\\<forall>n \\<in> m . t`succ(n) = g ` <t`n, n>\\<close>\n            by(unfold satpc_def, auto)\n          from E22 have E221:\\<open>(t:succ(m)\\<rightarrow>A)\\<close>\n            by auto\n          from E221 have domt:\\<open>domain(t) = succ(m)\\<close>\n            by (rule func.domain_of_fun)\n          from E1 have xind:\\<open>x \\<in> domain(t)\\<close>\n            by (rule equalities.domainI)\n          from xind and domt have xinsm:\\<open>x \\<in> succ(m)\\<close>\n            by auto\n          show \\<open>succ(x)\\<in>domain(\\<Union>pcs(A, a, g))\\<close>\n          proof\n        (*proof(rule exE[OF E22])*)\n            show \\<open> \\<langle>succ(x), g ` <t`x, x>\\<rangle> \\<in> (\\<Union>pcs(A, a, g))\\<close> (*?*)\n            proof\n             (*t\\<union>{\\<langle>succ(x), g ` <t`x, x>\\<rangle>}*)\n              show \\<open>cons(\\<langle>succ(x), g ` <t`x, x>\\<rangle>, t) \\<in> pcs(A, a, g)\\<close>\n              proof(unfold pcs_def, rule CollectI)\n                from E21\n                have L1:\\<open>t \\<subseteq> nat \\<times> A\\<close>\n                  by auto\n                from Q1 have J1:\\<open>succ(x)\\<in>nat\\<close>\n                  by auto(*Nat.nat_succI*)\n                have txA: \\<open>t ` x \\<in> A\\<close>\n                  by (rule func.apply_type[OF E221 xinsm])\n                from txA and Q1 have txx:\\<open>\\<langle>t ` x, x\\<rangle> \\<in> A \\<times> nat\\<close>\n                  by auto\n                have secp: \\<open>g ` \\<langle>t ` x, x\\<rangle> \\<in> A\\<close>\n                  by(rule func.apply_type[OF hyp2 txx])\n                from J1 and secp\n                have L2:\\<open>\\<langle>succ(x),g ` \\<langle>t ` x, x\\<rangle>\\<rangle> \\<in> nat \\<times> A\\<close>\n                  by auto\n                show \\<open> cons(\\<langle>succ(x),g ` \\<langle>t ` x, x\\<rangle>\\<rangle>,t) \\<in> Pow(nat \\<times> A)\\<close>\n                proof(rule PowI)\n                  show \\<open> cons(\\<langle>succ(x), g ` \\<langle>t ` x, x\\<rangle>\\<rangle>, t) \\<subseteq> nat \\<times> A\\<close>\n                  proof\n                    show \\<open>\\<langle>succ(x), g ` \\<langle>t ` x, x\\<rangle>\\<rangle> \\<in> nat \\<times> A \\<and> t \\<subseteq> nat \\<times> A\\<close>\n                      by (rule conjI[OF L2 L1])\n                  qed\n                qed\n              next\n                show \\<open>\\<exists>m \\<in> nat. partcomp(A, cons(\\<langle>succ(x), g ` \\<langle>t ` x, x\\<rangle>\\<rangle>, t), m, a, g)\\<close>\n                proof(rule succE[OF xinsm])\n                  assume xeqm:\\<open>x=m\\<close>\n                  show \\<open>\\<exists>m \\<in> nat. partcomp(A, cons(\\<langle>succ(x), g ` \\<langle>t ` x, x\\<rangle>\\<rangle>, t), m, a, g)\\<close>\n                  proof\n                    show \\<open>partcomp(A, cons(\\<langle>succ(x), g ` \\<langle>t ` x, x\\<rangle>\\<rangle>, t), succ(x), a, g)\\<close>\n                    proof(rule shortlem[OF Q1])\n                      show \\<open>partcomp(A, t, x, a, g)\\<close>\n                      proof(rule subst[of m x], rule sym, rule xeqm)\n                        show \\<open>partcomp(A, t, m, a, g)\\<close>\n                          by (rule E22P)\n                      qed\n                    qed\n                  next\n                    from Q1 show \\<open>succ(x) \\<in> nat\\<close> by auto\n                  qed\n                next\n                  assume xinm:\\<open>x\\<in>m\\<close>\n                  have lmm:\\<open>cons(\\<langle>succ(x), g ` \\<langle>t ` x, x\\<rangle>\\<rangle>, t) = t\\<close>\n                    by (rule addmiddle[OF mnat E22P xinm])\n                  show \\<open>\\<exists>m\\<in>nat. partcomp(A, cons(\\<langle>succ(x), g ` \\<langle>t ` x, x\\<rangle>\\<rangle>, t), m, a, g)\\<close>\n                    by(rule subst[of t], rule sym, rule lmm, rule E22m)\n                qed\n              qed\n            next\n              show \\<open>\\<langle>succ(x), g ` \\<langle>t ` x, x\\<rangle>\\<rangle> \\<in> cons(\\<langle>succ(x), g ` \\<langle>t ` x, x\\<rangle>\\<rangle>, t)\\<close>\n                by auto\n            qed\n          qed\n        qed\n      qed\n    qed\n  next\n    show \\<open>0 \\<in> domain(\\<Union>pcs(A, a, g))\\<close>\n      by (rule l2')\n  qed\nqed\n\nlemma useful : \\<open>\\<forall>m\\<in>nat. \\<exists>t. partcomp(A,t,m,a,g)\\<close>\nproof(rule nat_induct_bound)\n  show \\<open>\\<exists>t. partcomp(A, t, 0, a, g)\\<close>\n  proof\n    show \\<open>partcomp(A, {\\<langle>0, a\\<rangle>}, 0, a, g)\\<close>\n      by (rule zerostep)\n  qed\nnext\n  fix m\n  assume mnat:\\<open>m\\<in>nat\\<close>\n  assume G:\\<open>\\<exists>t. partcomp(A,t,m,a,g)\\<close>\n  show \\<open>\\<exists>t. partcomp(A,t,succ(m),a,g)\\<close>\n  proof(rule exE[OF G])\n    fix t\n    assume G:\\<open>partcomp(A,t,m,a,g)\\<close>\n    show \\<open>\\<exists>t. partcomp(A,t,succ(m),a,g)\\<close>\n    proof\n      show \\<open>partcomp(A,cons(\\<langle>succ(m), g ` <t`m, m>\\<rangle>, t),succ(m),a,g)\\<close>\n        by(rule shortlem[OF mnat G])\n    qed\n  qed\nqed\n\nlemma l4 : \\<open>(\\<Union>pcs(A,a,g)) \\<in> nat -> A\\<close>\nproof(unfold Pi_def)\n  show \\<open> \\<Union>pcs(A, a, g) \\<in> {f \\<in> Pow(nat \\<times> A) . nat \\<subseteq> domain(f) \\<and> function(f)}\\<close>\n  proof\n    show \\<open>\\<Union>pcs(A, a, g) \\<in> Pow(nat \\<times> A)\\<close>\n    proof\n      show \\<open>\\<Union>pcs(A, a, g) \\<subseteq> nat \\<times> A\\<close>\n        by (rule l1)\n    qed\n  next\n    show \\<open>nat \\<subseteq> domain(\\<Union>pcs(A, a, g)) \\<and> function(\\<Union>pcs(A, a, g))\\<close>\n    proof\n      show \\<open>nat \\<subseteq> domain(\\<Union>pcs(A, a, g))\\<close>\n        by (rule l2)\n    next\n      show \\<open>function(\\<Union>pcs(A, a, g))\\<close>\n        by (rule l3)\n    qed\n  qed\nqed\n\nlemma l5: \\<open>(\\<Union>pcs(A, a, g)) ` 0 = a\\<close>\nproof(rule func.function_apply_equality)\n  show \\<open>function(\\<Union>pcs(A, a, g))\\<close>\n    by (rule l3)\nnext\n  show \\<open>\\<langle>0, a\\<rangle> \\<in> \\<Union>pcs(A, a, g)\\<close>\n    by (rule zainupcs)\nqed\n\nlemma ballE2:\n  assumes \\<open>\\<forall>x\\<in>AA. P(x)\\<close>\n  assumes \\<open>x\\<in>AA\\<close>\n  assumes \\<open>P(x) ==> Q\\<close>\n  shows Q\n  by (rule assms(3), rule bspec, rule assms(1), rule assms(2))\n\ntext \\<open> Recall that\n  \\<open>satpc(t,\\<alpha>,g) == \\<forall>n \\<in> \\<alpha> . t`succ(n) = g ` <t`n, n>\\<close>\n  \\<open>partcomp(A,t,m,a,g) == (t:succ(m)\\<rightarrow>A) \\<and> (t`0=a) \\<and> satpc(t,m,g)\\<close>\n  \\<open>pcs(A,a,g) == {t\\<in>Pow(nat*A). \\<exists>m. partcomp(A,t,m,a,g)}\\<close>\n\\<close>\n\nlemma l6new: \\<open>satpc(\\<Union>pcs(A, a, g), nat, g)\\<close>\nproof (unfold satpc_def, rule ballI)\n  fix n\n  assume nnat:\\<open>n\\<in>nat\\<close>\n  hence snnat:\\<open>succ(n)\\<in>nat\\<close> by auto\n  (* l2:\\<open>nat \\<subseteq> domain(\\<Union>pcs(A, a, g))\\<close> *)\n  show \\<open>(\\<Union>pcs(A, a, g)) ` succ(n) = g ` \\<langle>(\\<Union>pcs(A, a, g)) ` n, n\\<rangle>\\<close>\n  proof(rule ballE2[OF useful snnat], erule exE)\n    fix t\n    assume Y:\\<open>partcomp(A, t, succ(n), a, g)\\<close>\n    show \\<open>(\\<Union>pcs(A, a, g)) ` succ(n) = g ` \\<langle>(\\<Union>pcs(A, a, g)) ` n, n\\<rangle>\\<close>\n    proof(rule partcompE[OF Y])\n      assume Y1:\\<open>t \\<in> succ(succ(n)) \\<rightarrow> A\\<close>\n      assume Y2:\\<open>t ` 0 = a\\<close>\n      assume Y3:\\<open>satpc(t, succ(n), g)\\<close>\n      hence Y3:\\<open>\\<forall>x \\<in> succ(n) . t`succ(x) = g ` <t`x, x>\\<close>\n        by (unfold satpc_def)\n      hence Y3:\\<open>t`succ(n) = g ` <t`n, n>\\<close>\n        by (rule bspec, auto)\n      have e1:\\<open>(\\<Union>pcs(A, a, g)) ` succ(n) = t ` succ(n)\\<close>\n      proof(rule valofunion, rule pcs_lem, rule hyp1)\n        show \\<open>t \\<in> pcs(A, a, g)\\<close>\n        proof(unfold pcs_def, rule CollectI)\n          show \\<open>t \\<in> Pow(nat \\<times> A)\\<close>\n            proof(rule tgb)\n            show \\<open>t \\<in> succ(succ(n)) \\<rightarrow> A\\<close> by (rule Y1)\n          next\n            from snnat\n            show \\<open>succ(succ(n)) \\<in> nat\\<close> by auto\n          qed\n        next\n          show \\<open>\\<exists>m\\<in>nat. partcomp(A, t, m, a, g)\\<close>\n            by(rule bexI, rule Y, rule snnat)\n        qed\n      next\n        show \\<open>t \\<in> succ(succ(n)) \\<rightarrow> A\\<close> by (rule Y1)\n      next\n        show \\<open>succ(n) \\<in> succ(succ(n))\\<close> by auto\n      next\n        show \\<open>t ` succ(n) = t ` succ(n)\\<close> by (rule refl)\n      qed\n      have e2:\\<open>(\\<Union>pcs(A, a, g)) ` n = t ` n\\<close>\n      proof(rule valofunion, rule pcs_lem, rule hyp1)\n        show \\<open>t \\<in> pcs(A, a, g)\\<close>\n        proof(unfold pcs_def, rule CollectI)\n          show \\<open>t \\<in> Pow(nat \\<times> A)\\<close>\n          proof(rule tgb)\n            show \\<open>t \\<in> succ(succ(n)) \\<rightarrow> A\\<close> by (rule Y1)\n          next\n            from snnat\n            show \\<open>succ(succ(n)) \\<in> nat\\<close> by auto\n          qed\n        next\n          show \\<open>\\<exists>m\\<in>nat. partcomp(A, t, m, a, g)\\<close>\n            by(rule bexI, rule Y, rule snnat)\n        qed\n      next\n        show \\<open>t \\<in> succ(succ(n)) \\<rightarrow> A\\<close> by (rule Y1)\n      next\n        show \\<open>n \\<in> succ(succ(n))\\<close> by auto\n      next\n        show \\<open>t ` n = t ` n\\<close> by (rule refl)\n      qed\n      have e3:\\<open>g ` \\<langle>(\\<Union>pcs(A, a, g)) ` n, n\\<rangle> = g ` \\<langle>t ` n, n\\<rangle>\\<close>\n        by (rule subst[OF e2], rule refl)\n      show \\<open>(\\<Union>pcs(A, a, g)) ` succ(n) = g ` \\<langle>(\\<Union>pcs(A, a, g)) ` n, n\\<rangle>\\<close>\n        by (rule trans, rule e1,rule trans, rule Y3, rule sym, rule e3)\n    qed\n  qed\nqed\n\nsection \"Recursion theorem\"\n\ntheorem recursionthm:\n  shows \\<open>\\<exists>!f. ((f \\<in> (nat\\<rightarrow>A)) \\<and> ((f`0) = a) \\<and> satpc(f,nat,g))\\<close>\n(* where \\<open>satpc(t,\\<alpha>,g) == \\<forall>n \\<in> \\<alpha> . t`succ(n) = g ` <t`n, n>\\<close> *)\nproof\n  show \\<open>\\<exists>f. f \\<in> nat -> A \\<and> f ` 0 = a \\<and> satpc(f, nat, g)\\<close>\n  proof\n    show \\<open>(\\<Union>pcs(A,a,g)) \\<in> nat -> A \\<and> (\\<Union>pcs(A,a,g)) ` 0 = a \\<and> satpc(\\<Union>pcs(A,a,g), nat, g)\\<close>\n    proof\n      show \\<open>\\<Union>pcs(A, a, g) \\<in> nat -> A\\<close>\n        by (rule l4)\n    next\n      show \\<open>(\\<Union>pcs(A, a, g)) ` 0 = a \\<and> satpc(\\<Union>pcs(A, a, g), nat, g)\\<close>\n      proof\n        show \\<open>(\\<Union>pcs(A, a, g)) ` 0 = a\\<close>\n          by (rule l5)\n      next\n        show \\<open>satpc(\\<Union>pcs(A, a, g), nat, g)\\<close>\n          by (rule l6new)\n      qed\n    qed\n  qed\nnext\n  show \\<open>\\<And>f y. f \\<in> nat -> A \\<and>\n           f ` 0 = a \\<and>\n           satpc(f, nat, g) \\<Longrightarrow>\n           y \\<in> nat -> A \\<and>\n           y ` 0 = a \\<and>\n           satpc(y, nat, g) \\<Longrightarrow>\n           f = y\\<close>\n    by (rule recuniq)\nqed\n\nend\n\nsection \"Lemmas for addition\"\n\ntext \\<open>\nLet's define function t(x) = (a+x).\nFirstly we need to define a function \\<open>g:nat \\<times> nat \\<rightarrow> nat\\<close>, such that\n\\<open>g`\\<langle>t`n, n\\<rangle> = t`succ(n) = a + (n + 1) = (a + n) + 1 = (t`n) + 1\\<close>\nSo \\<open>g`\\<langle>a, b\\<rangle> = a + 1\\<close> and \\<open>g(p) = succ(pr1(p))\\<close>\nand \\<open>satpc(t,\\<alpha>,g) \\<Longleftrightarrow> \\<forall>n \\<in> \\<alpha> . t`succ(n) = succ(t`n)\\<close>.\n\\<close>\n\ndefinition addg :: \\<open>i\\<close>\n  where addg_def : \\<open>addg == \\<lambda>x\\<in>(nat*nat). succ(fst(x))\\<close>\n\nlemma addgfun: \\<open>function(addg)\\<close>\n  by (unfold addg_def, rule func.function_lam)\n\nlemma addgsubpow : \\<open>addg \\<in> Pow((nat \\<times> nat) \\<times> nat)\\<close>\nproof (unfold addg_def, rule subsetD)\n  show \\<open>(\\<lambda>x\\<in>nat \\<times> nat. succ(fst(x))) \\<in> nat \\<times> nat \\<rightarrow> nat\\<close>\n  proof(rule func.lam_type)\n    fix x\n    assume \\<open>x\\<in>nat \\<times> nat\\<close>\n    hence \\<open>fst(x)\\<in>nat\\<close> by auto\n    thus \\<open>succ(fst(x)) \\<in> nat\\<close> by auto\n  qed\nnext\n  show \\<open>nat \\<times> nat \\<rightarrow> nat \\<subseteq> Pow((nat \\<times> nat) \\<times> nat)\\<close>\n    by (rule pisubsig)\nqed\n\nlemma addgdom : \\<open>nat \\<times> nat \\<subseteq> domain(addg)\\<close>\nproof(unfold addg_def)\n  have e:\\<open>domain(\\<lambda>x\\<in>nat \\<times> nat. succ(fst(x))) = nat \\<times> nat\\<close>\n    by (rule domain_lam)  (* \"domain(Lambda(A,b)) = A\" *)\n  show \\<open>nat \\<times> nat \\<subseteq>\n    domain(\\<lambda>x\\<in>nat \\<times> nat. succ(fst(x)))\\<close>\n    by (rule subst, rule sym, rule e, auto)\nqed\n\nlemma plussucc:\n  assumes F:\\<open>f \\<in> (nat\\<rightarrow>nat)\\<close>\n  assumes H:\\<open>satpc(f,nat,addg)\\<close>\n  shows \\<open>\\<forall>n \\<in> nat . f`succ(n) = succ(f`n)\\<close>\nproof\n  fix n\n  assume J:\\<open>n\\<in>nat\\<close>\n  from H\n  have H:\\<open>\\<forall>n \\<in> nat . f`succ(n) = (\\<lambda>x\\<in>(nat*nat). succ(fst(x)))` <f`n, n>\\<close>\n    by (unfold satpc_def, unfold addg_def)\n  have H:\\<open>f`succ(n) = (\\<lambda>x\\<in>(nat*nat). succ(fst(x)))` <f`n, n>\\<close>\n    by (rule bspec[OF H J])\n  have Q:\\<open>(\\<lambda>x\\<in>(nat*nat). succ(fst(x)))` <f`n, n> = succ(fst(<f`n, n>))\\<close>\n  proof(rule func.beta)\n    show \\<open>\\<langle>f ` n, n\\<rangle> \\<in> nat \\<times> nat\\<close>\n    proof\n      show \\<open>f ` n \\<in> nat\\<close>\n        by (rule func.apply_funtype[OF F J])\n      show \\<open>n \\<in> nat\\<close>\n        by (rule J)\n    qed\n  qed\n  have HQ:\\<open>f`succ(n) = succ(fst(<f`n, n>))\\<close>\n    by (rule trans[OF H Q])\n  have K:\\<open>fst(<f`n, n>) = f`n\\<close>\n    by auto\n  hence K:\\<open>succ(fst(<f`n, n>)) = succ(f`n)\\<close>\n    by (rule subst_context)\n  show \\<open>f`succ(n) = succ(f`n)\\<close>\n    by (rule trans[OF HQ K])\nqed\n\nsection \"Definition of addition\"\n\ntext \\<open>Theorem that addition of natural numbers exists\nand unique in some sense. Due to theorem 'plussucc' the term\n \\<open>satpc(f,nat,addg)\\<close>\n  can be replaced here with\n \\<open>\\<forall>n \\<in> nat . f`succ(n) = succ(f`n)\\<close>.\\<close>\ntheorem addition:\n  assumes \\<open>a\\<in>nat\\<close>\n  shows\n \\<open>\\<exists>!f. ((f \\<in> (nat\\<rightarrow>nat)) \\<and> ((f`0) = a) \\<and> satpc(f,nat,addg))\\<close>\nproof(rule recthm.recursionthm, unfold recthm_def)\n  show \\<open>a \\<in> nat \\<and> addg \\<in> nat \\<times> nat \\<rightarrow> nat\\<close>\n  proof\n    show \\<open>a\\<in>nat\\<close> by (rule assms(1))\n  next\n    show \\<open>addg \\<in> nat \\<times> nat \\<rightarrow> nat\\<close>\n    proof(unfold Pi_def, rule CollectI)\n      show \\<open>addg \\<in> Pow((nat \\<times> nat) \\<times> nat)\\<close>\n        by (rule addgsubpow)\n    next\n      have A2: \\<open>nat \\<times> nat \\<subseteq> domain(addg)\\<close>\n        by(rule addgdom)\n      have A3: \\<open>function(addg)\\<close>\n        by (rule addgfun)\n      show \\<open>nat \\<times> nat \\<subseteq> domain(addg) \\<and> function(addg)\\<close>\n        by(rule conjI[OF A2 A3])\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/Recursion-Addition/recursion.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430436757313, "lm_q2_score": 0.867035771827307, "lm_q1q2_score": 0.7206307503722849}}
{"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 MainRLT\nbegin\n\nunbundle lattice_syntax\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": "dtraytel", "repo": "HOLRLT", "sha": "e9029da59bb3af0c835604a65308498f9696a364", "save_path": "github-repos/isabelle/dtraytel-HOLRLT", "path": "github-repos/isabelle/dtraytel-HOLRLT/HOLRLT-e9029da59bb3af0c835604a65308498f9696a364/HOLRLT/Examples/Knaster_Tarski.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8311430520409023, "lm_q2_score": 0.8670357512127872, "lm_q1q2_score": 0.7206307404915724}}
{"text": "(*  Title:      HOL/Datatype_Examples/Koenig.thy\n    Author:     Dmitriy Traytel, TU Muenchen\n    Author:     Andrei Popescu, TU Muenchen\n    Copyright   2012\n\nKoenig's lemma.\n*)\n\nsection {* Koenig's Lemma *}\n\ntheory Koenig\nimports TreeFI \"~~/src/HOL/Library/Stream\"\nbegin\n\n(* infinite trees: *)\ncoinductive infiniteTr where\n\"\\<lbrakk>tr' \\<in> set (sub tr); infiniteTr tr'\\<rbrakk> \\<Longrightarrow> infiniteTr tr\"\n\nlemma infiniteTr_strong_coind[consumes 1, case_names sub]:\nassumes *: \"phi tr\" and\n**: \"\\<And> tr. phi tr \\<Longrightarrow> \\<exists> tr' \\<in> set (sub tr). phi tr' \\<or> infiniteTr tr'\"\nshows \"infiniteTr tr\"\nusing assms by (elim infiniteTr.coinduct) blast\n\nlemma infiniteTr_coind[consumes 1, case_names sub, induct pred: infiniteTr]:\nassumes *: \"phi tr\" and\n**: \"\\<And> tr. phi tr \\<Longrightarrow> \\<exists> tr' \\<in> set (sub tr). phi tr'\"\nshows \"infiniteTr tr\"\nusing assms by (elim infiniteTr.coinduct) blast\n\nlemma infiniteTr_sub[simp]:\n\"infiniteTr tr \\<Longrightarrow> (\\<exists> tr' \\<in> set (sub tr). infiniteTr tr')\"\nby (erule infiniteTr.cases) blast\n\nprimcorec konigPath where\n  \"shd (konigPath t) = lab t\"\n| \"stl (konigPath t) = konigPath (SOME tr. tr \\<in> set (sub t) \\<and> infiniteTr tr)\"\n\n(* proper paths in trees: *)\ncoinductive properPath where\n\"\\<lbrakk>shd as = lab tr; tr' \\<in> set (sub tr); properPath (stl as) tr'\\<rbrakk> \\<Longrightarrow>\n properPath as tr\"\n\nlemma properPath_strong_coind[consumes 1, case_names shd_lab sub]:\nassumes *: \"phi as tr\" and\n**: \"\\<And> as tr. phi as tr \\<Longrightarrow> shd as = lab tr\" and\n***: \"\\<And> as tr.\n         phi as tr \\<Longrightarrow>\n         \\<exists> tr' \\<in> set (sub tr). phi (stl as) tr' \\<or> properPath (stl as) tr'\"\nshows \"properPath as tr\"\nusing assms by (elim properPath.coinduct) blast\n\nlemma properPath_coind[consumes 1, case_names shd_lab sub, induct pred: properPath]:\nassumes *: \"phi as tr\" and\n**: \"\\<And> as tr. phi as tr \\<Longrightarrow> shd as = lab tr\" and\n***: \"\\<And> as tr.\n         phi as tr \\<Longrightarrow>\n         \\<exists> tr' \\<in> set (sub tr). phi (stl as) tr'\"\nshows \"properPath as tr\"\nusing properPath_strong_coind[of phi, OF * **] *** by blast\n\nlemma properPath_shd_lab:\n\"properPath as tr \\<Longrightarrow> shd as = lab tr\"\nby (erule properPath.cases) blast\n\nlemma properPath_sub:\n\"properPath as tr \\<Longrightarrow>\n \\<exists> tr' \\<in> set (sub tr). phi (stl as) tr' \\<or> properPath (stl as) tr'\"\nby (erule properPath.cases) blast\n\n(* prove the following by coinduction *)\ntheorem Konig:\n  assumes \"infiniteTr tr\"\n  shows \"properPath (konigPath tr) tr\"\nproof-\n  {fix as\n   assume \"infiniteTr tr \\<and> as = konigPath tr\" hence \"properPath as tr\"\n   proof (coinduction arbitrary: tr as rule: properPath_coind)\n     case (sub tr as)\n     let ?t = \"SOME t'. t' \\<in> set (sub tr) \\<and> infiniteTr t'\"\n     from sub have \"\\<exists>t' \\<in> set (sub tr). infiniteTr t'\" by simp\n     then have \"\\<exists>t'. t' \\<in> set (sub tr) \\<and> infiniteTr t'\" by blast\n     then have \"?t \\<in> set (sub tr) \\<and> infiniteTr ?t\" by (rule someI_ex)\n     moreover have \"stl (konigPath tr) = konigPath ?t\" by simp\n     ultimately show ?case using sub by blast\n   qed simp\n  }\n  thus ?thesis using assms by blast\nqed\n\n(* some more stream theorems *)\n\nprimcorec plus :: \"nat stream \\<Rightarrow> nat stream \\<Rightarrow> nat stream\" (infixr \"\\<oplus>\" 66) where\n  \"shd (plus xs ys) = shd xs + shd ys\"\n| \"stl (plus xs ys) = plus (stl xs) (stl ys)\"\n\ndefinition scalar :: \"nat \\<Rightarrow> nat stream \\<Rightarrow> nat stream\" (infixr \"\\<cdot>\" 68) where\n  [simp]: \"scalar n = smap (\\<lambda>x. n * x)\"\n\nprimcorec ones :: \"nat stream\" where \"ones = 1 ## ones\"\nprimcorec twos :: \"nat stream\" where \"twos = 2 ## twos\"\ndefinition ns :: \"nat \\<Rightarrow> nat stream\" where [simp]: \"ns n = scalar n ones\"\n\nlemma \"ones \\<oplus> ones = twos\"\n  by coinduction simp\n\nlemma \"n \\<cdot> twos = ns (2 * n)\"\n  by coinduction simp\n\nlemma prod_scalar: \"(n * m) \\<cdot> xs = n \\<cdot> m \\<cdot> xs\"\n  by (coinduction arbitrary: xs) auto\n\nlemma scalar_plus: \"n \\<cdot> (xs \\<oplus> ys) = n \\<cdot> xs \\<oplus> n \\<cdot> ys\"\n  by (coinduction arbitrary: xs ys) (auto simp: add_mult_distrib2)\n\nlemma plus_comm: \"xs \\<oplus> ys = ys \\<oplus> xs\"\n  by (coinduction arbitrary: xs ys) auto\n\nlemma plus_assoc: \"(xs \\<oplus> ys) \\<oplus> zs = xs \\<oplus> ys \\<oplus> zs\"\n  by (coinduction arbitrary: xs ys zs) 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/Datatype_Examples/Koenig.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357529306639, "lm_q2_score": 0.8311430415844385, "lm_q1q2_score": 0.7206307328532457}}
{"text": "(*  Title:      ZF/Perm.thy\n    Author:     Lawrence C Paulson, Cambridge University Computer Laboratory\n    Copyright   1991  University of Cambridge\n\nThe theory underlying permutation groups\n  -- Composition of relations, the identity relation\n  -- Injections, surjections, bijections\n  -- Lemmas for the Schroeder-Bernstein Theorem\n*)\n\nsection\\<open>Injections, Surjections, Bijections, Composition\\<close>\n\ntheory Perm imports Function begin\n\ndefinition\n  (*composition of relations and functions; NOT Suppes's relative product*)\n  comp     :: \"[i,i]=>i\"      (infixr \"O\" 60)  where\n    \"r O s == {xz \\<in> domain(s)*range(r) .\n               \\<exists>x y z. xz=<x,z> & <x,y>:s & <y,z>:r}\"\n\ndefinition\n  (*the identity function for A*)\n  id    :: \"i=>i\"  where\n    \"id(A) == (\\<lambda>x\\<in>A. x)\"\n\ndefinition\n  (*one-to-one functions from A to B*)\n  inj   :: \"[i,i]=>i\"  where\n    \"inj A B == { f \\<in> A->B. \\<forall>w\\<in>A. \\<forall>x\\<in>A. f`w=f`x \\<longrightarrow> w=x}\"\n\ndefinition\n  (*onto functions from A to B*)\n  surj  :: \"[i,i]=>i\"  where\n    \"surj A B == { f \\<in> A->B . \\<forall>y\\<in>B. \\<exists>x\\<in>A. f`x=y}\"\n\ndefinition\n  (*one-to-one and onto functions*)\n  bij   :: \"[i,i]=>i\"  where\n    \"bij A B == inj A B \\<inter> surj A B\"\n\n\nsubsection\\<open>Surjective Function Space\\<close>\n\nlemma surj_is_fun: \"f \\<in> surj A B ==> f \\<in> A->B\"\napply (unfold surj_def)\napply (erule CollectD1)\ndone\n\nlemma fun_is_surj: \"f \\<in> Pi A B ==> f \\<in> surj A (range f)\"\napply (unfold surj_def)\napply (blast intro: apply_equality range_of_fun domain_type)\ndone\n\nlemma surj_range: \"f \\<in> surj A B ==> range(f)=B\"\napply (unfold surj_def)\napply (best intro: apply_Pair elim: range_type)\ndone\n\ntext\\<open>A function with a right inverse is a surjection\\<close>\n\nlemma f_imp_surjective:\n    \"[| f \\<in> A->B;  !!y. y \\<in> B ==> d(y): A;  !!y. y \\<in> B ==> f`d(y) = y |]\n     ==> f \\<in> surj A B\"\n  by (simp add: surj_def, blast)\n\nlemma lam_surjective:\n    \"[| !!x. x \\<in> A ==> c(x): B;\n        !!y. y \\<in> B ==> d(y): A;\n        !!y. y \\<in> B ==> c(d(y)) = y\n     |] ==> (\\<lambda>x\\<in>A. c(x)) \\<in> surj A B\"\napply (rule_tac d = d in f_imp_surjective)\napply (simp_all add: lam_type)\ndone\n\ntext\\<open>Cantor's theorem revisited\\<close>\nlemma cantor_surj: \"f \\<notin> surj A (Pow A)\"\napply (unfold surj_def, safe)\napply (cut_tac cantor)\napply (best del: subsetI)\ndone\n\n\nsubsection\\<open>Injective Function Space\\<close>\n\nlemma inj_is_fun: \"f \\<in> inj A B ==> f \\<in> A->B\"\napply (unfold inj_def)\napply (erule CollectD1)\ndone\n\ntext\\<open>Good for dealing with sets of pairs, but a bit ugly in use [used in AC]\\<close>\nlemma inj_equality:\n    \"[| <a,b>:f;  <c,b>:f;  f \\<in> inj A B |] ==> a=c\"\napply (unfold inj_def)\napply (blast dest: Pair_mem_PiD)\ndone\n\nlemma inj_apply_equality: \"[| f \\<in> inj A B;  f`a=f`b;  a \\<in> A;  b \\<in> A |] ==> a=b\"\nby (unfold inj_def, blast)\n\ntext\\<open>A function with a left inverse is an injection\\<close>\n\nlemma f_imp_injective: \"[| f \\<in> A->B;  \\<forall>x\\<in>A. d(f`x)=x |] ==> f \\<in> inj A B\"\napply (simp (no_asm_simp) add: inj_def)\napply (blast intro: subst_context [THEN box_equals])\ndone\n\nlemma lam_injective:\n    \"[| !!x. x \\<in> A ==> c(x): B;\n        !!x. x \\<in> A ==> d(c(x)) = x |]\n     ==> (\\<lambda>x\\<in>A. c(x)) \\<in> inj A B\"\napply (rule_tac d = d in f_imp_injective)\napply (simp_all add: lam_type)\ndone\n\nsubsection\\<open>Bijections\\<close>\n\nlemma bij_is_inj: \"f \\<in> bij A B ==> f \\<in> inj A B\"\napply (unfold bij_def)\napply (erule IntD1)\ndone\n\nlemma bij_is_surj: \"f \\<in> bij A B ==> f \\<in> surj A B\"\napply (unfold bij_def)\napply (erule IntD2)\ndone\n\nlemma bij_is_fun: \"f \\<in> bij A B ==> f \\<in> A->B\"\n  by (rule bij_is_inj [THEN inj_is_fun])\n\nlemma lam_bijective:\n    \"[| !!x. x \\<in> A ==> c(x): B;\n        !!y. y \\<in> B ==> d(y): A;\n        !!x. x \\<in> A ==> d(c(x)) = x;\n        !!y. y \\<in> B ==> c(d(y)) = y\n     |] ==> (\\<lambda>x\\<in>A. c(x)) \\<in> bij A B\"\napply (unfold bij_def)\napply (blast intro!: lam_injective lam_surjective)\ndone\n\nlemma RepFun_bijective: \"(\\<forall>y\\<in>x. \\<exists>!y'. f(y') = f(y))\n      ==> (\\<lambda>z\\<in>{f(y). y \\<in> x}. THE y. f(y) = z) \\<in> bij {f(y). y \\<in> x} x\"\napply (rule_tac d = f in lam_bijective)\napply (auto simp add: the_equality2)\ndone\n\n\nsubsection\\<open>Identity Function\\<close>\n\nlemma idI [intro!]: \"a \\<in> A ==> <a,a> \\<in> id(A)\"\napply (unfold id_def)\napply (erule lamI)\ndone\n\nlemma idE [elim!]: \"[| p \\<in> id(A);  !!x.[| x \\<in> A; p=<x,x> |] ==> P |] ==>  P\"\nby (simp add: id_def lam_def, blast)\n\nlemma id_type: \"id(A) \\<in> A->A\"\napply (unfold id_def)\napply (rule lam_type, assumption)\ndone\n\nlemma id_conv [simp]: \"x \\<in> A ==> id(A)`x = x\"\napply (unfold id_def)\napply (simp (no_asm_simp))\ndone\n\nlemma id_mono: \"A<=B ==> id(A) \\<subseteq> id(B)\"\napply (unfold id_def)\napply (erule lam_mono)\ndone\n\nlemma id_subset_inj: \"A<=B ==> id(A): inj A B\"\napply (simp add: inj_def id_def)\napply (blast intro: lam_type)\ndone\n\nlemmas id_inj = subset_refl [THEN id_subset_inj]\n\nlemma id_surj: \"id(A): surj A A\"\napply (unfold id_def surj_def)\napply (simp (no_asm_simp))\ndone\n\nlemma id_bij: \"id(A): bij A A\"\napply (unfold bij_def)\napply (blast intro: id_inj id_surj)\ndone\n\nlemma subset_iff_id: \"A \\<subseteq> B \\<longleftrightarrow> id(A) \\<in> A->B\"\napply (unfold id_def)\napply (force intro!: lam_type dest: apply_type)\ndone\n\ntext\\<open>@{term id} as the identity relation\\<close>\nlemma id_iff [simp]: \"<x,y> \\<in> id(A) \\<longleftrightarrow> x=y & y \\<in> A\"\nby auto\n\n\nsubsection\\<open>Converse of a Function\\<close>\n\nlemma inj_converse_fun: \"f \\<in> inj A B ==> converse(f) \\<in> range(f)->A\"\napply (unfold inj_def)\napply (simp (no_asm_simp) add: Pi_iff function_def)\napply (erule CollectE)\napply (simp (no_asm_simp) add: apply_iff)\napply (blast dest: fun_is_rel)\ndone\n\ntext\\<open>Equations for converse(f)\\<close>\n\ntext\\<open>The premises are equivalent to saying that f is injective...\\<close>\nlemma left_inverse_lemma:\n     \"[| f \\<in> A->B;  converse(f): C->A;  a \\<in> A |] ==> converse(f)`(f`a) = a\"\nby (blast intro: apply_Pair apply_equality)\n\nlemma left_inverse [simp]: \"[| f \\<in> inj A B;  a \\<in> A |] ==> converse(f)`(f`a) = a\"\nby (blast intro: left_inverse_lemma inj_converse_fun inj_is_fun)\n\nlemma left_inverse_eq:\n     \"[|f \\<in> inj A B; f ` x = y; x \\<in> A|] ==> converse(f) ` y = x\"\nby auto\n\nlemmas left_inverse_bij = bij_is_inj [THEN left_inverse]\n\nlemma right_inverse_lemma:\n     \"[| f \\<in> A->B;  converse(f): C->A;  b \\<in> C |] ==> f`(converse(f)`b) = b\"\nby (rule apply_Pair [THEN converseD [THEN apply_equality]], auto)\n\n(*Should the premises be f \\<in> surj A B, b \\<in> B for symmetry with left_inverse?\n  No: they would not imply that converse(f) was a function! *)\nlemma right_inverse [simp]:\n     \"[| f \\<in> inj A B;  b \\<in> range(f) |] ==> f`(converse(f)`b) = b\"\nby (blast intro: right_inverse_lemma inj_converse_fun inj_is_fun)\n\nlemma right_inverse_bij: \"[| f \\<in> bij A B;  b \\<in> B |] ==> f`(converse(f)`b) = b\"\nby (force simp add: bij_def surj_range)\n\nsubsection\\<open>Converses of Injections, Surjections, Bijections\\<close>\n\nlemma inj_converse_inj: \"f \\<in> inj A B ==> converse(f): inj (range f) A\"\napply (rule f_imp_injective)\napply (erule inj_converse_fun, clarify)\napply (rule right_inverse)\n apply assumption\napply blast\ndone\n\nlemma inj_converse_surj: \"f \\<in> inj A B ==> converse(f): surj (range f) A\"\nby (blast intro: f_imp_surjective inj_converse_fun left_inverse inj_is_fun\n                 range_of_fun [THEN apply_type])\n\ntext\\<open>Adding this as an intro! rule seems to cause looping\\<close>\nlemma bij_converse_bij [TC]: \"f \\<in> bij A B ==> converse(f): bij B A\"\napply (unfold bij_def)\napply (fast elim: surj_range [THEN subst] inj_converse_inj inj_converse_surj)\ndone\n\n\n\nsubsection\\<open>Composition of Two Relations\\<close>\n\ntext\\<open>The inductive definition package could derive these theorems for @{term\"r O s\"}\\<close>\n\nlemma compI [intro]: \"[| <a,b>:s; <b,c>:r |] ==> <a,c> \\<in> r O s\"\nby (unfold comp_def, blast)\n\nlemma compE [elim!]:\n    \"[| xz \\<in> r O s;\n        !!x y z. [| xz=<x,z>;  <x,y>:s;  <y,z>:r |] ==> P |]\n     ==> P\"\nby (unfold comp_def, blast)\n\nlemma compEpair:\n    \"[| <a,c> \\<in> r O s;\n        !!y. [| <a,y>:s;  <y,c>:r |] ==> P |]\n     ==> P\"\nby (erule compE, simp)\n\nlemma converse_comp: \"converse(R O S) = converse(S) O converse(R)\"\nby blast\n\n\nsubsection\\<open>Domain and Range -- see Suppes, Section 3.1\\<close>\n\ntext\\<open>Boyer et al., Set Theory in First-Order Logic, JAR 2 (1986), 287-327\\<close>\nlemma range_comp: \"range(r O s) \\<subseteq> range(r)\"\nby blast\n\nlemma range_comp_eq: \"domain(r) \\<subseteq> range(s) ==> range(r O s) = range(r)\"\nby (rule range_comp [THEN equalityI], blast)\n\nlemma domain_comp: \"domain(r O s) \\<subseteq> domain(s)\"\nby blast\n\nlemma domain_comp_eq: \"range(s) \\<subseteq> domain(r) ==> domain(r O s) = domain(s)\"\nby (rule domain_comp [THEN equalityI], blast)\n\nlemma image_comp: \"(r O s)``A = r``(s``A)\"\nby blast\n\nlemma inj_inj_range: \"f \\<in> inj A B ==> f \\<in> inj A (range f)\"\n  by (auto simp add: inj_def Pi_iff function_def)\n\nlemma inj_bij_range: \"f \\<in> inj A B ==> f \\<in> bij A (range f)\"\n  by (auto simp add: bij_def intro: inj_inj_range inj_is_fun fun_is_surj)\n\n\nsubsection\\<open>Other Results\\<close>\n\nlemma comp_mono: \"[| r'<=r; s'<=s |] ==> (r' O s') \\<subseteq> (r O s)\"\nby blast\n\ntext\\<open>composition preserves relations\\<close>\nlemma comp_rel: \"[| s<=A*B;  r<=B*C |] ==> (r O s) \\<subseteq> A*C\"\nby blast\n\ntext\\<open>associative law for composition\\<close>\nlemma comp_assoc: \"(r O s) O t = r O (s O t)\"\nby blast\n\n(*left identity of composition; provable inclusions are\n        id(A) O r \\<subseteq> r\n  and   [| r<=A*B; B<=C |] ==> r \\<subseteq> id(C) O r *)\nlemma left_comp_id: \"r<=A*B ==> id(B) O r = r\"\nby blast\n\n(*right identity of composition; provable inclusions are\n        r O id(A) \\<subseteq> r\n  and   [| r<=A*B; A<=C |] ==> r \\<subseteq> r O id(C) *)\nlemma right_comp_id: \"r<=A*B ==> r O id(A) = r\"\nby blast\n\n\nsubsection\\<open>Composition Preserves Functions, Injections, and Surjections\\<close>\n\nlemma comp_function: \"[| function(g);  function(f) |] ==> function(f O g)\"\nby (unfold function_def, blast)\n\ntext\\<open>Don't think the premises can be weakened much\\<close>\nlemma comp_fun: \"[| g \\<in> A->B;  f \\<in> B->C |] ==> (f O g) \\<in> A->C\"\napply (auto simp add: Pi_def comp_function comp_rel)\napply (subst range_rel_subset [THEN domain_comp_eq], auto)\ndone\n\n(*Thanks to the new definition of \"apply\", the premise f \\<in> B->C is gone!*)\nlemma comp_fun_apply [simp]:\n     \"[| g \\<in> A->B;  a \\<in> A |] ==> (f O g)`a = f`(g`a)\"\napply (frule apply_Pair, assumption)\napply (simp add: apply_def image_comp)\napply (blast dest: apply_equality)\ndone\n\ntext\\<open>Simplifies compositions of lambda-abstractions\\<close>\nlemma comp_lam:\n    \"[| !!x. x \\<in> A ==> b(x): B |]\n     ==> (\\<lambda>y\\<in>B. c(y)) O (\\<lambda>x\\<in>A. b(x)) = (\\<lambda>x\\<in>A. c(b(x)))\"\napply (subgoal_tac \"(\\<lambda>x\\<in>A. b(x)) \\<in> A -> B\")\n apply (rule fun_extension)\n   apply (blast intro: comp_fun lam_funtype)\n  apply (rule lam_funtype)\n apply simp\napply (simp add: lam_type)\ndone\n\nlemma comp_inj:\n     \"[| g \\<in> inj A B;  f \\<in> inj B C |] ==> (f O g) \\<in> inj A C\"\napply (frule inj_is_fun [of g])\napply (frule inj_is_fun [of f])\napply (rule_tac d = \"%y. converse (g) ` (converse (f) ` y)\" in f_imp_injective)\n apply (blast intro: comp_fun, simp)\ndone\n\nlemma comp_surj:\n    \"[| g \\<in> surj A B;  f \\<in> surj B C |] ==> (f O g) \\<in> surj A C\"\napply (unfold surj_def)\napply (blast intro!: comp_fun comp_fun_apply)\ndone\n\nlemma comp_bij:\n    \"[| g \\<in> bij A B;  f \\<in> bij B C |] ==> (f O g) \\<in> bij A C\"\napply (unfold bij_def)\napply (blast intro: comp_inj comp_surj)\ndone\n\n\nsubsection\\<open>Dual Properties of @{term inj} and @{term surj}\\<close>\n\ntext\\<open>Useful for proofs from\n    D Pastre.  Automatic theorem proving in set theory.\n    Artificial Intelligence, 10:1--27, 1978.\\<close>\n\nlemma comp_mem_injD1:\n    \"[| (f O g): inj A C;  g \\<in> A->B;  f \\<in> B->C |] ==> g \\<in> inj A B\"\nby (unfold inj_def, force)\n\nlemma comp_mem_injD2:\n    \"[| (f O g): inj A C;  g \\<in> surj A B;  f \\<in> B->C |] ==> f \\<in> inj B C\"\napply (unfold inj_def surj_def, safe)\napply (rule_tac x1 = x in bspec [THEN bexE])\napply (erule_tac [3] x1 = w in bspec [THEN bexE], assumption+, safe)\napply (rule_tac t = \"%x. g ` x \" in subst_context)\napply (erule asm_rl bspec [THEN bspec, THEN mp])+\napply (simp (no_asm_simp))\ndone\n\nlemma comp_mem_surjD1:\n    \"[| (f O g): surj A C;  g \\<in> A->B;  f \\<in> B->C |] ==> f \\<in> surj B C\"\napply (unfold surj_def)\napply (blast intro!: comp_fun_apply [symmetric] apply_funtype)\ndone\n\n\nlemma comp_mem_surjD2:\n    \"[| (f O g): surj A C;  g \\<in> A->B;  f \\<in> inj B C |] ==> g \\<in> surj A B\"\napply (unfold inj_def surj_def, safe)\napply (drule_tac x = \"f`y\" in bspec, auto)\napply (blast intro: apply_funtype)\ndone\n\nsubsubsection\\<open>Inverses of Composition\\<close>\n\ntext\\<open>left inverse of composition; one inclusion is\n        @{term \"f \\<in> A->B ==> id(A) \\<subseteq> converse(f) O f\"}\\<close>\nlemma left_comp_inverse: \"f \\<in> inj A B ==> converse(f) O f = id(A)\"\napply (unfold inj_def, clarify)\napply (rule equalityI)\n apply (auto simp add: apply_iff, blast)\ndone\n\ntext\\<open>right inverse of composition; one inclusion is\n                @{term \"f \\<in> A->B ==> f O converse(f) \\<subseteq> id(B)\"}\\<close>\nlemma right_comp_inverse:\n    \"f \\<in> surj A B ==> f O converse(f) = id(B)\"\napply (simp add: surj_def, clarify)\napply (rule equalityI)\napply (best elim: domain_type range_type dest: apply_equality2)\napply (blast intro: apply_Pair)\ndone\n\n\nsubsubsection\\<open>Proving that a Function is a Bijection\\<close>\n\nlemma comp_eq_id_iff:\n    \"[| f \\<in> A->B;  g \\<in> B->A |] ==> f O g = id(B) \\<longleftrightarrow> (\\<forall>y\\<in>B. f`(g`y)=y)\"\napply (unfold id_def, safe)\n apply (drule_tac t = \"%h. h`y \" in subst_context)\n apply simp\napply (rule fun_extension)\n  apply (blast intro: comp_fun lam_type)\n apply auto\ndone\n\nlemma fg_imp_bijective:\n    \"[| f \\<in> A->B;  g \\<in> B->A;  f O g = id(B);  g O f = id(A) |] ==> f \\<in> bij A B\"\napply (unfold bij_def)\napply (simp add: comp_eq_id_iff)\napply (blast intro: f_imp_injective f_imp_surjective apply_funtype)\ndone\n\nlemma nilpotent_imp_bijective: \"[| f \\<in> A->A;  f O f = id(A) |] ==> f \\<in> bij A A\"\nby (blast intro: fg_imp_bijective)\n\nlemma invertible_imp_bijective:\n     \"[| converse(f): B->A;  f \\<in> A->B |] ==> f \\<in> bij A B\"\nby (simp add: fg_imp_bijective comp_eq_id_iff\n              left_inverse_lemma right_inverse_lemma)\n\nsubsubsection\\<open>Unions of Functions\\<close>\n\ntext\\<open>See similar theorems in func.thy\\<close>\n\ntext\\<open>Theorem by KG, proof by LCP\\<close>\nlemma inj_disjoint_Un:\n     \"[| f \\<in> inj A B;  g \\<in> inj C D;  B \\<inter> D = 0 |]\n      ==> (\\<lambda>a\\<in>A \\<union> C. if a \\<in> A then f`a else g`a) \\<in> inj (A \\<union> C) (B \\<union> D)\"\napply (rule_tac d = \"%z. if z \\<in> B then converse (f) `z else converse (g) `z\"\n       in lam_injective)\napply (auto simp add: inj_is_fun [THEN apply_type])\ndone\n\nlemma surj_disjoint_Un:\n    \"[| f \\<in> surj A B;  g \\<in> surj C D;  A \\<inter> C = 0 |]\n     ==> (f \\<union> g) \\<in> surj (A \\<union> C) (B \\<union> D)\"\napply (simp add: surj_def fun_disjoint_Un)\napply (blast dest!: domain_of_fun\n             intro!: fun_disjoint_apply1 fun_disjoint_apply2)\ndone\n\ntext\\<open>A simple, high-level proof; the version for injections follows from it,\n  using  @{term \"f \\<in> inj A B \\<longleftrightarrow> f \\<in> bij A (range f)\"}\\<close>\nlemma bij_disjoint_Un:\n     \"[| f \\<in> bij A B;  g \\<in> bij C D;  A \\<inter> C = 0;  B \\<inter> D = 0 |]\n      ==> (f \\<union> g) \\<in> bij (A \\<union> C) (B \\<union> D)\"\napply (rule invertible_imp_bijective)\napply (subst converse_Un)\napply (auto intro: fun_disjoint_Un bij_is_fun bij_converse_bij)\ndone\n\n\nsubsubsection\\<open>Restrictions as Surjections and Bijections\\<close>\n\nlemma surj_image:\n    \"f \\<in> Pi A B ==> f \\<in> surj A (f``A)\"\napply (simp add: surj_def)\napply (blast intro: apply_equality apply_Pair Pi_type)\ndone\n\nlemma surj_image_eq: \"f \\<in> surj A B ==> f``A = B\"\n  by (auto simp add: surj_def image_fun) (blast dest: apply_type) \n\nlemma restrict_image [simp]: \"restrict f A `` B = f `` (A \\<inter> B)\"\nby (auto simp add: restrict_def)\n\nlemma restrict_inj:\n    \"[| f \\<in> inj A B;  C<=A |] ==> restrict f C : inj C B\"\napply (unfold inj_def)\napply (safe elim!: restrict_type2, auto)\ndone\n\nlemma restrict_surj: \"[| f \\<in> Pi A B;  C<=A |] ==> restrict f C : surj C (f``C)\"\napply (insert restrict_type2 [THEN surj_image])\napply (simp)\ndone\n\nlemma restrict_bij:\n    \"[| f \\<in> inj A B;  C<=A |] ==> restrict f C : bij C (f``C)\"\napply (simp add: inj_def bij_def)\napply (blast intro: restrict_surj surj_is_fun)\ndone\n\n\nsubsubsection\\<open>Lemmas for Ramsey's Theorem\\<close>\n\nlemma inj_weaken_type: \"[| f \\<in> inj A B;  B<=D |] ==> f \\<in> inj A D\"\napply (unfold inj_def)\napply (blast intro: fun_weaken_type)\ndone\n\nlemma inj_succ_restrict:\n     \"[| f \\<in> inj (succ m) A |] ==> restrict f m \\<in> inj m (A-{f`m})\"\napply (rule restrict_bij [THEN bij_is_inj, THEN inj_weaken_type], assumption, blast)\napply (unfold inj_def)\napply (fast elim: range_type mem_irrefl dest: apply_equality)\ndone\n\n\nlemma inj_extend:\n    \"[| f \\<in> inj A B;  a\\<notin>A;  b\\<notin>B |]\n     ==> cons <a,b> f \\<in> inj (cons a A) (cons b B)\"\napply (unfold inj_def)\napply (force intro: apply_type  simp add: fun_extend)\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/Perm.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8438951143326726, "lm_q2_score": 0.8539127529517043, "lm_q1q2_score": 0.7206128002823058}}
{"text": "chapter \"Residuated Transition Systems\"\n\ntheory ResiduatedTransitionSystem\nimports Main\nbegin\n\n  section \"Basic Definitions and Properties\"\n\n  subsection \"Partial Magmas\"\n\n  text \\<open>\n    A \\emph{partial magma} consists simply of a partial binary operation.\n    We represent the partiality by assuming the existence of a unique value \\<open>null\\<close>\n    that behaves as a zero for the operation.\n  \\<close>\n\n  (* TODO: Possibly unify with Category3.partial_magma? *)\n  locale partial_magma =\n  fixes OP :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a\"\n  assumes ex_un_null: \"\\<exists>!n. \\<forall>t. OP n t = n \\<and> OP t n = n\"\n  begin\n\n    definition null :: 'a\n    where \"null = (THE n. \\<forall>t. OP n t = n \\<and> OP t n = n)\"\n\n    lemma null_eqI:\n    assumes \"\\<And>t. OP n t = n \\<and> OP t n = n\"\n    shows \"n = null\"\n      using assms null_def ex_un_null the1_equality [of \"\\<lambda>n. \\<forall>t. OP n t = n \\<and> OP t n = n\"]\n      by auto\n    \n    lemma null_is_zero [simp]:\n    shows \"OP null t = null\" and \"OP t null = null\"\n      using null_def ex_un_null theI' [of \"\\<lambda>n. \\<forall>t. OP n t = n \\<and> OP t n = n\"]\n      by auto\n\n  end\n\n  subsection \"Residuation\"\n\n    text \\<open>\n      A \\emph{residuation} is a partial binary operation subject to three axioms.\n      The first, \\<open>con_sym_ax\\<close>, states that the domain of a residuation is symmetric.\n      The second, \\<open>con_imp_arr_resid\\<close>, constrains the results of residuation either to be \\<open>null\\<close>,\n      which indicates inconsistency, or something that is self-consistent, which we will\n      define below to be an ``arrow''.\n      The ``cube axiom'', \\<open>cube_ax\\<close>, states that if \\<open>v\\<close> can be transported by residuation\n      around one side of the ``commuting square'' formed by \\<open>t\\<close> and \\<open>u \\ t\\<close>, then it can also\n      be transported around the other side, formed by \\<open>u\\<close> and \\<open>t \\ u\\<close>, with the same result.\n    \\<close>\n\n  type_synonym 'a resid = \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a\"\n\n  locale residuation = partial_magma resid\n  for resid :: \"'a resid\" (infix \"\\\\\" 70) +\n  assumes con_sym_ax: \"t \\\\ u \\<noteq> null \\<Longrightarrow> u \\\\ t \\<noteq> null\"\n  and con_imp_arr_resid: \"t \\\\ u \\<noteq> null \\<Longrightarrow> (t \\\\ u) \\\\ (t \\\\ u) \\<noteq> null\"\n  and cube_ax: \"(v \\\\ t) \\\\ (u \\\\ t) \\<noteq> null \\<Longrightarrow> (v \\\\ t) \\\\ (u \\\\ t) = (v \\\\ u) \\\\ (t \\\\ u)\"\n  begin\n\n    text \\<open>\n      The axiom \\<open>cube_ax\\<close> is equivalent to the following unconditional form.\n      The locale assumptions use the weaker form to avoid having to treat\n      the case \\<open>(v \\ t) \\ (u \\ t) = null\\<close> specially for every interpretation.\n    \\<close>\n\n    lemma cube:\n    shows \"(v \\\\ t) \\\\ (u \\\\ t) = (v \\\\ u) \\\\ (t \\\\ u)\"\n      using cube_ax by metis\n\n    text \\<open>\n      We regard \\<open>t\\<close> and \\<open>u\\<close> as \\emph{consistent} if the residuation \\<open>t \\ u\\<close> is defined.\n      It is convenient to make this a definition, with associated notation.\n    \\<close>\n\n    definition con  (infix \"\\<frown>\" 50)\n    where \"t \\<frown> u \\<equiv> t \\\\ u \\<noteq> null\"\n\n    lemma conI [intro]:\n    assumes \"t \\\\ u \\<noteq> null\"\n    shows \"t \\<frown> u\"\n      using assms con_def by blast\n\n    lemma conE [elim]:\n    assumes \"t \\<frown> u\"\n    and \"t \\\\ u \\<noteq> null \\<Longrightarrow> T\"\n    shows T\n      using assms con_def by simp\n\n    lemma con_sym:\n    assumes \"t \\<frown> u\"\n    shows \"u \\<frown> t\"\n      using assms con_def con_sym_ax by blast\n\n    text \\<open>\n      We call \\<open>t\\<close> an \\emph{arrow} if it is self-consistent.\n    \\<close>\n\n    definition arr\n    where \"arr t \\<equiv> t \\<frown> t\"\n\n    lemma arrI [intro]:\n    assumes \"t \\<frown> t\"\n    shows \"arr t\"\n      using assms arr_def by simp\n\n    lemma arrE [elim]:\n    assumes \"arr t\"\n    and \"t \\<frown> t \\<Longrightarrow> T\"\n    shows T\n      using assms arr_def by simp\n\n    lemma not_arr_null [simp]:\n    shows \"\\<not> arr null\"\n      by (auto simp add: con_def)\n\n    lemma con_implies_arr:\n    assumes \"t \\<frown> u\"\n    shows \"arr t\" and \"arr u\"\n      using assms\n      by (metis arrI con_def con_imp_arr_resid cube null_is_zero(2))+\n \n    lemma arr_resid [simp]:\n    assumes \"t \\<frown> u\"\n    shows \"arr (t \\\\ u)\"\n      using assms con_imp_arr_resid by blast\n\n    lemma arr_resid_iff_con:\n    shows \"arr (t \\\\ u) \\<longleftrightarrow> t \\<frown> u\"\n      by auto\n\n    text \\<open>\n      The residuation of an arrow along itself is the \\emph{canonical target} of the arrow.\n    \\<close>\n\n    definition trg\n    where \"trg t \\<equiv> t \\\\ t\"\n\n    lemma resid_arr_self:\n    shows \"t \\\\ t = trg t\"\n      using trg_def by auto\n\n    text \\<open>\n      An \\emph{identity} is an arrow that is its own target.\n    \\<close>\n\n    definition ide\n    where \"ide a \\<equiv> a \\<frown> a \\<and> a \\\\ a = a\"\n\n    lemma ideI [intro]:\n    assumes \"a \\<frown> a\" and \"a \\\\ a = a\"\n    shows \"ide a\"\n      using assms ide_def by auto\n\n    lemma ideE [elim]:\n    assumes \"ide a\"\n    and \"\\<lbrakk>a \\<frown> a; a \\\\ a = a\\<rbrakk> \\<Longrightarrow> T\"\n    shows T\n      using assms ide_def by blast\n\n    lemma ide_implies_arr [simp]:\n    assumes \"ide a\"\n    shows \"arr a\"\n      using assms by blast\n\n  end\n\n  subsection \"Residuated Transition System\"\n\n  text \\<open>\n    A \\emph{residuated transition system} consists of a residuation subject to\n    additional axioms that concern the relationship between identities and residuation.\n    These axioms make it possible to sensibly associate with each arrow certain nonempty\n    sets of identities called the \\emph{sources} and \\emph{targets} of the arrow.\n    Axiom \\<open>ide_trg\\<close> states that the canonical target \\<open>trg t\\<close> of an arrow \\<open>t\\<close> is an identity.\n    Axiom \\<open>resid_arr_ide\\<close> states that identities are right units for residuation,\n    when it is defined.\n    Axiom \\<open>resid_ide_arr\\<close> states that the residuation of an identity along an arrow is\n    again an identity, assuming that the residuation is defined.\n    Axiom \\<open>con_imp_coinitial_ax\\<close> states that if arrows \\<open>t\\<close> and \\<open>u\\<close> are consistent,\n    then there is an identity that is consistent with both of them (\\emph{i.e.}~they\n    have a common source).\n    Axiom \\<open>con_target\\<close> states that an identity of the form \\<open>t \\ u\\<close>\n    (which may be regarded as a ``target'' of \\<open>u\\<close>) is consistent with any other\n    arrow \\<open>v \\ u\\<close> obtained by residuation along \\<open>u\\<close>.\n    We note that replacing the premise \\<open>ide (t \\ u)\\<close> in this axiom by either \\<open>arr (t \\ u)\\<close>\n    or \\<open>t \\<frown> u\\<close> would result in a strictly stronger statement.\n  \\<close>\n\n  locale rts = residuation +\n  assumes ide_trg [simp]: \"arr t \\<Longrightarrow> ide (trg t)\"\n  and resid_arr_ide: \"\\<lbrakk>ide a; t \\<frown> a\\<rbrakk> \\<Longrightarrow> t \\\\ a = t\"\n  and resid_ide_arr [simp]: \"\\<lbrakk>ide a; a \\<frown> t\\<rbrakk> \\<Longrightarrow> ide (a \\\\ t)\"\n  and con_imp_coinitial_ax: \"t \\<frown> u \\<Longrightarrow> \\<exists>a. ide a \\<and> a \\<frown> t \\<and> a \\<frown> u\"\n  and con_target: \"\\<lbrakk>ide (t \\\\ u); u \\<frown> v\\<rbrakk> \\<Longrightarrow> t \\\\ u \\<frown> v \\\\ u\"\n  begin\n\n    text \\<open>\n      We define the \\emph{sources} of an arrow \\<open>t\\<close> to be the identities that\n      are consistent with \\<open>t\\<close>.\n    \\<close>\n\n    definition sources\n    where \"sources t = {a. ide a \\<and> t \\<frown> a}\"\n\n    text \\<open>\n      We define the \\emph{targets} of an arrow \\<open>t\\<close> to be the identities that\n      are consistent with the canonical target \\<open>trg t\\<close>.\n    \\<close>\n\n    definition targets\n    where \"targets t = {b. ide b \\<and> trg t \\<frown> b}\"\n\n    lemma in_sourcesI [intro, simp]:\n    assumes \"ide a\" and \"t \\<frown> a\"\n    shows \"a \\<in> sources t\"\n      using assms sources_def by simp\n\n    lemma in_sourcesE [elim]:\n    assumes \"a \\<in> sources t\"\n    and \"\\<lbrakk>ide a; t \\<frown> a\\<rbrakk> \\<Longrightarrow> T\"\n    shows T\n      using assms sources_def by auto\n\n    lemma in_targetsI [intro, simp]:\n    assumes \"ide b\" and \"trg t \\<frown> b\"\n    shows \"b \\<in> targets t\"\n      using assms targets_def resid_arr_self by simp\n\n    lemma in_targetsE [elim]:\n    assumes \"b \\<in> targets t\"\n    and \"\\<lbrakk>ide b; trg t \\<frown> b\\<rbrakk> \\<Longrightarrow> T\"\n    shows T\n      using assms targets_def resid_arr_self by force\n\n    lemma trg_in_targets:\n    assumes \"arr t\"\n    shows \"trg t \\<in> targets t\"\n      using assms\n      by (meson ideE ide_trg in_targetsI)\n\n    lemma source_is_ide:\n    assumes \"a \\<in> sources t\"\n    shows \"ide a\"\n      using assms by blast\n\n    lemma target_is_ide:\n    assumes \"a \\<in> targets t\"\n    shows \"ide a\"\n      using assms by blast\n\n    text \\<open>\n      Consistent arrows have a common source.\n    \\<close>\n\n    lemma con_imp_common_source:\n    assumes \"t \\<frown> u\"\n    shows \"sources t \\<inter> sources u \\<noteq> {}\"\n      using assms\n      by (meson disjoint_iff in_sourcesI con_imp_coinitial_ax con_sym)\n\n    text \\<open>\n       Arrows are characterized by the property of having a nonempty set of sources,\n       or equivalently, by that of having a nonempty set of targets.\n    \\<close>\n\n    lemma arr_iff_has_source:\n    shows \"arr t \\<longleftrightarrow> sources t \\<noteq> {}\"\n      using con_imp_common_source con_implies_arr(1) sources_def by blast\n\n    lemma arr_iff_has_target:\n    shows \"arr t \\<longleftrightarrow> targets t \\<noteq> {}\"\n      using trg_def trg_in_targets by fastforce\n\n    text \\<open>\n      The residuation of a source of an arrow along that arrow gives a target\n      of the same arrow.\n      However, it is \\emph{not} true that every target of an arrow \\<open>t\\<close> is of the\n      form \\<open>u \\ t\\<close> for some \\<open>u\\<close> with \\<open>t \\<frown> u\\<close>.\n    \\<close>\n\n    lemma resid_source_in_targets:\n    assumes \"a \\<in> sources t\"\n    shows \"a \\\\ t \\<in> targets t\"\n      by (metis arr_resid assms con_target con_sym resid_arr_ide ide_trg\n          in_sourcesE resid_ide_arr in_targetsI resid_arr_self)\n\n    text \\<open>\n      Residuation along an identity reflects identities.\n    \\<close>\n\n    lemma ide_backward_stable:\n    assumes \"ide a\" and \"ide (t \\\\ a)\"\n    shows \"ide t\"\n      by (metis assms ideE resid_arr_ide arr_resid_iff_con)\n\n    lemma resid_reflects_con:\n    assumes \"t \\<frown> v\" and \"u \\<frown> v\" and \"t \\\\ v \\<frown> u \\\\ v\"\n    shows \"t \\<frown> u\"\n      using assms cube\n      by (elim conE) auto\n\n    lemma con_transitive_on_ide:\n    assumes \"ide a\" and \"ide b\" and \"ide c\"\n    shows \"\\<lbrakk>a \\<frown> b; b \\<frown> c\\<rbrakk> \\<Longrightarrow> a \\<frown> c\"\n      using assms\n      by (metis resid_arr_ide con_target con_sym)\n\n    lemma sources_are_con:\n    assumes \"a \\<in> sources t\" and \"a' \\<in> sources t\"\n    shows \"a \\<frown> a'\"\n      using assms\n      by (metis (no_types, lifting) CollectD con_target con_sym resid_ide_arr\n          sources_def resid_reflects_con)\n \n    lemma sources_con_closed:\n    assumes \"a \\<in> sources t\" and \"ide a'\" and \"a \\<frown> a'\"\n    shows \"a' \\<in> sources t\"\n      using assms\n      by (metis (no_types, lifting) con_target con_sym resid_arr_ide\n          mem_Collect_eq sources_def)\n\n    lemma sources_eqI:\n    assumes \"sources t \\<inter> sources t' \\<noteq> {}\"\n    shows \"sources t = sources t'\"\n      using assms sources_def sources_are_con sources_con_closed by blast\n\n    lemma targets_are_con:\n    assumes \"b \\<in> targets t\" and \"b' \\<in> targets t\"\n    shows \"b \\<frown> b'\"\n      using assms sources_are_con sources_def targets_def by blast\n\n    lemma targets_con_closed:\n    assumes \"b \\<in> targets t\" and \"ide b'\" and \"b \\<frown> b'\"\n    shows \"b' \\<in> targets t\"\n      using assms sources_con_closed sources_def targets_def by blast\n\n    lemma targets_eqI:\n    assumes \"targets t \\<inter> targets t' \\<noteq> {}\"\n    shows \"targets t = targets t'\"\n      using assms targets_def targets_are_con targets_con_closed by blast\n\n    text \\<open>\n      Arrows are \\emph{coinitial} if they have a common source, and \\emph{coterminal}\n      if they have a common target.\n    \\<close>\n\n    definition coinitial\n    where \"coinitial t u \\<equiv> sources t \\<inter> sources u \\<noteq> {}\"\n\n    definition coterminal\n    where \"coterminal t u \\<equiv> targets t \\<inter> targets u \\<noteq> {}\"\n\n    lemma coinitialI [intro]:\n    assumes \"arr t\" and \"sources t = sources u\"\n    shows \"coinitial t u\"\n      using assms coinitial_def arr_iff_has_source by simp\n\n    lemma coinitialE [elim]:\n    assumes \"coinitial t u\"\n    and \"\\<lbrakk>arr t; arr u; sources t = sources u\\<rbrakk> \\<Longrightarrow> T\"\n    shows T\n      using assms coinitial_def sources_eqI arr_iff_has_source by auto\n\n    lemma con_imp_coinitial:\n    assumes \"t \\<frown> u\"\n    shows \"coinitial t u\"\n      using assms\n      by (simp add: coinitial_def con_imp_common_source)\n\n    lemma coinitial_iff:\n    shows \"coinitial t t' \\<longleftrightarrow> arr t \\<and> arr t' \\<and> sources t = sources t'\"\n      by (metis arr_iff_has_source coinitial_def inf_idem sources_eqI)\n\n    lemma coterminal_iff:\n    shows \"coterminal t t' \\<longleftrightarrow> arr t \\<and> arr t' \\<and> targets t = targets t'\"\n      by (metis arr_iff_has_target coterminal_def inf_idem targets_eqI)\n\n    lemma coterminal_iff_con_trg:\n    shows \"coterminal t u \\<longleftrightarrow> trg t \\<frown> trg u\"\n      by (metis coinitial_iff con_imp_coinitial coterminal_iff in_targetsE trg_in_targets\n          resid_arr_self arr_resid_iff_con sources_def targets_def)\n\n    lemma coterminalI [intro]:\n    assumes \"arr t\" and \"targets t = targets u\"\n    shows \"coterminal t u\"\n      using assms coterminal_iff arr_iff_has_target by auto\n\n    lemma coterminalE [elim]:\n    assumes \"coterminal t u\"\n    and \"\\<lbrakk>arr t; arr u; targets t = targets u\\<rbrakk> \\<Longrightarrow> T\"\n    shows T\n      using assms coterminal_iff by auto\n\n    lemma sources_resid [simp]:\n    assumes \"t \\<frown> u\"\n    shows \"sources (t \\\\ u) = targets u\"\n      unfolding targets_def trg_def\n      using assms conI conE\n      by (metis con_imp_arr_resid assms coinitial_iff con_imp_coinitial\n          cube ex_un_null sources_def)\n\n    lemma targets_resid_sym:\n    assumes \"t \\<frown> u\"\n    shows \"targets (t \\\\ u) = targets (u \\\\ t)\"\n      using assms\n      apply (intro targets_eqI)\n      by (metis (no_types, opaque_lifting) assms cube inf_idem arr_iff_has_target arr_def\n          arr_resid_iff_con sources_resid)\n\n    text \\<open>\n      Arrows \\<open>t\\<close> and \\<open>u\\<close> are \\emph{sequential} if the set of targets of \\<open>t\\<close> equals\n      the set of sources of \\<open>u\\<close>.\n    \\<close>\n\n    definition seq\n    where \"seq t u \\<equiv> arr t \\<and> arr u \\<and> targets t = sources u\"\n\n    lemma seqI [intro]:\n    assumes \"arr t\" and \"arr u\" and \"targets t = sources u\"\n    shows \"seq t u\"\n      using assms seq_def by auto\n\n    lemma seqE [elim]:\n    assumes \"seq t u\"\n    and \"\\<lbrakk>arr t; arr u; targets t = sources u\\<rbrakk> \\<Longrightarrow> T\"\n    shows T\n      using assms seq_def by blast\n\n    subsubsection \"Congruence of Transitions\"\n\n    text \\<open>\n      Residuation induces a preorder \\<open>\\<lesssim>\\<close> on transitions, defined by \\<open>t \\<lesssim> u\\<close> if and only if\n      \\<open>t \\ u\\<close> is an identity.\n    \\<close>\n\n    abbreviation prfx  (infix \"\\<lesssim>\" 50)\n    where \"t \\<lesssim> u \\<equiv> ide (t \\\\ u)\"\n\n    lemma prfx_implies_con:\n    assumes \"t \\<lesssim> u\"\n    shows \"t \\<frown> u\"\n      using assms arr_resid_iff_con by blast\n\n    lemma prfx_reflexive:\n    assumes \"arr t\"\n    shows \"t \\<lesssim> t\"\n      by (simp add: assms resid_arr_self)\n\n    lemma prfx_transitive [trans]:\n    assumes \"t \\<lesssim> u\" and \"u \\<lesssim> v\"\n    shows \"t \\<lesssim> v\"\n      using assms con_target resid_ide_arr ide_backward_stable cube conI\n      by metis\n\n    text \\<open>\n      The equivalence \\<open>\\<sim>\\<close> associated with \\<open>\\<lesssim>\\<close> is substitutive with respect to residuation.\n    \\<close>\n\n    abbreviation cong  (infix \"\\<sim>\" 50)\n    where \"t \\<sim> u \\<equiv> t \\<lesssim> u \\<and> u \\<lesssim> t\"\n\n    lemma cong_reflexive:\n    assumes \"arr t\"\n    shows \"t \\<sim> t\"\n      using assms prfx_reflexive by simp\n\n    lemma cong_symmetric:\n    assumes \"t \\<sim> u\"\n    shows \"u \\<sim> t\"\n      using assms by simp\n\n    lemma cong_transitive [trans]:\n    assumes \"t \\<sim> u\" and \"u \\<sim> v\"\n    shows \"t \\<sim> v\"\n      using assms prfx_transitive by auto\n\n    lemma cong_subst_left:\n    assumes \"t \\<sim> t'\" and \"t \\<frown> u\"\n    shows \"t' \\<frown> u\" and \"t \\\\ u \\<sim> t' \\\\ u\"\n      apply (meson assms con_sym con_target prfx_implies_con resid_reflects_con)\n      by (metis assms con_sym con_target cube prfx_implies_con resid_ide_arr resid_reflects_con)\n\n    lemma cong_subst_right:\n    assumes \"u \\<sim> u'\" and \"t \\<frown> u\"\n    shows \"t \\<frown> u'\" and \"t \\\\ u \\<sim> t \\\\ u'\"\n    proof -\n      have 1: \"t \\<frown> u' \\<and> t \\\\ u' \\<frown> u \\\\ u' \\<and>\n                (t \\\\ u) \\\\ (u' \\\\ u) = (t \\\\ u') \\\\ (u \\\\ u')\"\n        using assms cube con_sym con_target cong_subst_left(1) by meson\n      show \"t \\<frown> u'\"\n        using 1 by simp\n      show \"t \\\\ u \\<sim> t \\\\ u'\"\n        by (metis 1 arr_resid_iff_con assms(1) cong_reflexive resid_arr_ide)\n    qed\n\n    lemma cong_implies_coinitial:\n    assumes \"u \\<sim> u'\"\n    shows \"coinitial u u'\"\n      using assms con_imp_coinitial prfx_implies_con by simp\n\n    lemma cong_implies_coterminal:\n    assumes \"u \\<sim> u'\"\n    shows \"coterminal u u'\"\n      using assms\n      by (metis con_implies_arr(1) coterminalI ideE prfx_implies_con sources_resid\n          targets_resid_sym)\n\n    lemma ide_imp_con_iff_cong:\n    assumes \"ide t\" and \"ide u\"\n    shows \"t \\<frown> u \\<longleftrightarrow> t \\<sim> u\"\n      using assms\n      by (metis con_sym resid_ide_arr prfx_implies_con)\n\n    lemma sources_are_cong:\n    assumes \"a \\<in> sources t\" and \"a' \\<in> sources t\"\n    shows \"a \\<sim> a'\"\n      using assms sources_are_con\n      by (metis CollectD ide_imp_con_iff_cong sources_def)\n\n    lemma sources_cong_closed:\n    assumes \"a \\<in> sources t\" and \"a \\<sim> a'\"\n    shows \"a' \\<in> sources t\"\n      using assms sources_def\n      by (meson in_sourcesE in_sourcesI cong_subst_right(1) ide_backward_stable)\n\n    lemma targets_are_cong:\n    assumes \"b \\<in> targets t\" and \"b' \\<in> targets t\"\n    shows \"b \\<sim> b'\"\n      using assms(1-2) sources_are_cong sources_def targets_def by blast\n\n    lemma targets_cong_closed:\n    assumes \"b \\<in> targets t\" and \"b \\<sim> b'\"\n    shows \"b' \\<in> targets t\"\n      using assms targets_def sources_cong_closed sources_def by blast\n\n    lemma targets_char:\n    shows \"targets t = {b. arr t \\<and> t \\\\ t \\<sim> b}\"\n      unfolding targets_def\n      by (metis (no_types, lifting) con_def con_implies_arr(2) con_sym cong_reflexive\n          ide_def resid_arr_ide trg_def)\n\n    lemma coinitial_ide_are_cong:\n    assumes \"ide a\" and \"ide a'\" and \"coinitial a a'\"\n    shows \"a \\<sim> a'\"\n      using assms coinitial_def\n      by (metis ideE in_sourcesI coinitialE sources_are_cong)\n\n    lemma cong_respects_seq:\n    assumes \"seq t u\" and \"cong t t'\" and \"cong u u'\"\n    shows \"seq t' u'\"\n      by (metis assms coterminalE rts.coinitialE rts.cong_implies_coinitial\n          rts.cong_implies_coterminal rts_axioms seqE seqI)\n\n  end\n\n  subsection \"Weakly Extensional RTS\"\n\n  text \\<open>\n    A \\emph{weakly extensional} RTS is an RTS that satisfies the additional condition that\n    identity arrows have trivial congruence classes.  This axiom has a number of useful\n    consequences, including that each arrow has a unique source and target.\n  \\<close>\n\n  locale weakly_extensional_rts = rts +\n  assumes weak_extensionality: \"\\<lbrakk>t \\<sim> u; ide t; ide u\\<rbrakk> \\<Longrightarrow> t = u\"\n  begin\n\n    lemma con_ide_are_eq:\n    assumes \"ide a\" and \"ide a'\" and \"a \\<frown> a'\"\n    shows \"a = a'\"\n      using assms ide_imp_con_iff_cong weak_extensionality by blast\n\n    lemma coinitial_ide_are_eq:\n    assumes \"ide a\" and \"ide a'\" and \"coinitial a a'\"\n    shows \"a = a'\"\n      using assms coinitial_def con_ide_are_eq by blast\n\n    lemma arr_has_un_source:\n    assumes \"arr t\"\n    shows \"\\<exists>!a. a \\<in> sources t\"\n      using assms\n      by (meson arr_iff_has_source con_ide_are_eq ex_in_conv in_sourcesE sources_are_con)\n\n    lemma arr_has_un_target:\n    assumes \"arr t\"\n    shows \"\\<exists>!b. b \\<in> targets t\"\n      using assms\n      by (metis arrE arr_has_un_source arr_resid sources_resid)\n\n    definition src\n    where \"src t \\<equiv> if arr t then THE a. a \\<in> sources t else null\"\n\n    lemma src_in_sources:\n    assumes \"arr t\"\n    shows \"src t \\<in> sources t\"\n      using assms src_def arr_has_un_source\n            the1I2 [of \"\\<lambda>a. a \\<in> sources t\" \"\\<lambda>a. a \\<in> sources t\"]\n      by simp\n\n    lemma src_eqI:\n    assumes \"ide a\" and \"a \\<frown> t\"\n    shows \"src t = a\"\n      using assms src_in_sources\n      by (metis arr_has_un_source resid_arr_ide in_sourcesI arr_resid_iff_con con_sym)\n\n    lemma sources_char:\n    shows \"sources t = {a. arr t \\<and> src t = a}\"\n      using src_in_sources arr_has_un_source arr_iff_has_source by auto\n\n    lemma targets_char\\<^sub>W\\<^sub>E:\n    shows \"targets t = {b. arr t \\<and> trg t = b}\"\n      using trg_in_targets arr_has_un_target arr_iff_has_target by auto\n\n    lemma arr_src_iff_arr [iff]:\n    shows \"arr (src t) \\<longleftrightarrow> arr t\"\n      by (metis arrI conE null_is_zero(2) sources_are_con arrE src_def src_in_sources)\n\n    lemma arr_trg_iff_arr [iff]:\n    shows \"arr (trg t) \\<longleftrightarrow> arr t\"\n      by (metis arrI arrE arr_resid_iff_con resid_arr_self)\n\n    lemma con_imp_eq_src:\n    assumes \"t \\<frown> u\"\n    shows \"src t = src u\"\n      using assms\n      by (metis con_imp_coinitial_ax src_eqI)\n\n    lemma src_resid [simp]:\n    assumes \"t \\<frown> u\"\n    shows \"src (t \\\\ u) = trg u\"\n      using assms\n      by (metis arr_resid_iff_con con_implies_arr(2) arr_has_un_source trg_in_targets\n                sources_resid src_in_sources)\n\n    lemma trg_resid_sym:\n    assumes \"t \\<frown> u\"\n    shows \"trg (t \\\\ u) = trg (u \\\\ t)\"\n      using assms\n      by (metis arr_has_un_target arr_resid con_sym targets_resid_sym trg_in_targets)\n\n    lemma apex_sym:\n    shows \"trg (t \\\\ u) = trg (u \\\\ t)\"\n      using trg_resid_sym con_def by metis\n\n    lemma seqI\\<^sub>W\\<^sub>E [intro, simp]:\n    assumes \"arr u\" and \"arr t\" and \"trg t = src u\"\n    shows \"seq t u\"\n      using assms\n      by (metis (mono_tags, lifting) arrE in_sourcesE resid_arr_ide sources_resid\n          resid_arr_self seqI sources_are_con src_in_sources)\n\n    lemma seqE\\<^sub>W\\<^sub>E [elim]:\n    assumes \"seq t u\"\n    and \"\\<lbrakk>arr u; arr t; trg t = src u\\<rbrakk> \\<Longrightarrow> T\"\n    shows T\n      using assms\n      by (metis arr_has_un_source seq_def src_in_sources trg_in_targets)\n\n    lemma coinitial_iff\\<^sub>W\\<^sub>E:\n    shows \"coinitial t u \\<longleftrightarrow> arr t \\<and> arr u \\<and> src t = src u\"\n      by (metis arr_has_un_source coinitial_def coinitial_iff disjoint_iff_not_equal\n          src_in_sources)\n\n    lemma coterminal_iff\\<^sub>W\\<^sub>E:\n    shows \"coterminal t u \\<longleftrightarrow> arr t \\<and> arr u \\<and> trg t = trg u\"\n      by (metis arr_has_un_target coterminal_iff_con_trg coterminal_iff trg_in_targets)\n\n    lemma coinitialI\\<^sub>W\\<^sub>E [intro]:\n    assumes \"arr t\" and \"src t = src u\"\n    shows \"coinitial t u\"\n      using assms coinitial_iff\\<^sub>W\\<^sub>E by (metis arr_src_iff_arr)\n\n    lemma coinitialE\\<^sub>W\\<^sub>E [elim]:\n    assumes \"coinitial t u\"\n    and \"\\<lbrakk>arr t; arr u; src t = src u\\<rbrakk> \\<Longrightarrow> T\"\n    shows T\n      using assms coinitial_iff\\<^sub>W\\<^sub>E by blast\n\n    lemma coterminalI\\<^sub>W\\<^sub>E [intro]:\n    assumes \"arr t\" and \"trg t = trg u\"\n    shows \"coterminal t u\"\n      using assms coterminal_iff\\<^sub>W\\<^sub>E by (metis arr_trg_iff_arr)\n\n    lemma coterminalE\\<^sub>W\\<^sub>E [elim]:\n    assumes \"coterminal t u\"\n    and \"\\<lbrakk>arr t; arr u; trg t = trg u\\<rbrakk> \\<Longrightarrow> T\"\n    shows T\n      using assms coterminal_iff\\<^sub>W\\<^sub>E by blast\n\n    lemma ide_src [simp]:\n    assumes \"arr t\"\n    shows \"ide (src t)\"\n      using assms\n      by (metis arrE con_imp_coinitial_ax src_eqI)\n\n    lemma src_ide [simp]:\n    assumes \"ide a\"\n    shows \"src a = a\"\n      using arrI assms src_eqI by blast\n\n    lemma trg_ide [simp]:\n    assumes \"ide a\"\n    shows \"trg a = a\"\n      using assms resid_arr_self by force\n\n    lemma ide_iff_src_self:\n    assumes \"arr a\"\n    shows \"ide a \\<longleftrightarrow> src a = a\"\n      using assms by (metis ide_src src_ide)\n\n    lemma ide_iff_trg_self:\n    assumes \"arr a\"\n    shows \"ide a \\<longleftrightarrow> trg a = a\"\n      using assms ide_def resid_arr_self by auto\n\n    lemma src_src [simp]:\n    shows \"src (src t) = src t\"\n      using ide_src src_def src_ide by auto\n\n    lemma trg_trg [simp]:\n    shows \"trg (trg t) = trg t\"\n      by (metis con_def cong_reflexive ide_def null_is_zero(2) resid_arr_self\n          residuation.con_implies_arr(1) residuation_axioms)\n\n    lemma src_trg [simp]:\n    shows \"src (trg t) = trg t\"\n      by (metis con_def not_arr_null src_def src_resid trg_def)\n\n    lemma trg_src [simp]:\n    shows \"trg (src t) = src t\"\n      by (metis ide_src null_is_zero(2) resid_arr_self src_def trg_ide)\n\n    lemma resid_ide:\n    assumes \"ide a\" and \"coinitial a t\"\n    shows (* [simp]: *) \"t \\\\ a = t\" and \"a \\\\ t = trg t\"\n      using assms resid_arr_ide apply blast\n      using assms\n      by (metis con_def con_sym_ax ideE in_sourcesE in_sourcesI resid_ide_arr\n          coinitialE src_ide src_resid)\n\n  end\n\n  subsection \"Extensional RTS\"\n\n  text \\<open>\n    An \\emph{extensional} RTS is an RTS in which all arrows have trivial congruence classes;\n    that is, congruent arrows are equal.\n  \\<close>\n\n  locale extensional_rts = rts +\n  assumes extensional: \"t \\<sim> u \\<Longrightarrow> t = u\"\n  begin\n\n    sublocale weakly_extensional_rts\n      using extensional\n      by unfold_locales auto\n\n    lemma cong_char:\n    shows \"t \\<sim> u \\<longleftrightarrow> arr t \\<and> t = u\"\n      by (metis arrI cong_reflexive prfx_implies_con extensional)\n\n  end\n\n  subsection \"Composites of Transitions\"\n\n  text \\<open>\n    Residuation can be used to define a notion of composite of transitions.\n    Composites are not unique, but they are unique up to congruence.\n  \\<close>\n\n  context rts\n  begin\n\n    definition composite_of\n    where \"composite_of u t v \\<equiv> u \\<lesssim> v \\<and> v \\\\ u \\<sim> t\"\n\n    lemma composite_ofI [intro]:\n    assumes \"u \\<lesssim> v\" and \"v \\\\ u \\<sim> t\"\n    shows \"composite_of u t v\"\n      using assms composite_of_def by blast\n\n    lemma composite_ofE [elim]:\n    assumes \"composite_of u t v\"\n    and \"\\<lbrakk>u \\<lesssim> v; v \\\\ u \\<sim> t\\<rbrakk> \\<Longrightarrow> T\"\n    shows T\n      using assms composite_of_def by auto\n\n    lemma arr_composite_of:\n    assumes \"composite_of u t v\"\n    shows \"arr v\"\n      using assms\n      by (meson composite_of_def con_implies_arr(2) prfx_implies_con)\n\n    lemma composite_of_unq_upto_cong:\n    assumes \"composite_of u t v\" and \"composite_of u t v'\"\n    shows \"v \\<sim> v'\"\n      using assms cube ide_backward_stable prfx_transitive\n      by (elim composite_ofE) metis\n\n    lemma composite_of_ide_arr:\n    assumes \"ide a\"\n    shows \"composite_of a t t \\<longleftrightarrow> t \\<frown> a\"\n      using assms\n      by (metis composite_of_def con_implies_arr(1) con_sym resid_arr_ide resid_ide_arr\n          prfx_implies_con prfx_reflexive)\n\n    lemma composite_of_arr_ide:\n    assumes \"ide b\"\n    shows \"composite_of t b t \\<longleftrightarrow> t \\\\ t \\<frown> b\"\n      using assms\n      by (metis arr_resid_iff_con composite_of_def ide_imp_con_iff_cong con_implies_arr(1)\n          prfx_implies_con prfx_reflexive)\n\n    lemma composite_of_source_arr:\n    assumes \"arr t\" and \"a \\<in> sources t\"\n    shows \"composite_of a t t\"\n      using assms composite_of_ide_arr sources_def by auto\n\n    lemma composite_of_arr_target:\n    assumes \"arr t\" and \"b \\<in> targets t\"\n    shows \"composite_of t b t\"\n      by (metis arrE assms composite_of_arr_ide in_sourcesE sources_resid)\n\n    lemma composite_of_ide_self:\n    assumes \"ide a\"\n    shows \"composite_of a a a\"\n      using assms composite_of_ide_arr by blast\n\n    lemma con_prfx_composite_of:\n    assumes \"composite_of t u w\"\n    shows \"t \\<frown> w\" and \"w \\<frown> v \\<Longrightarrow> t \\<frown> v\"\n      using assms apply force\n      using assms composite_of_def con_target prfx_implies_con\n            resid_reflects_con con_sym\n        by meson\n\n    lemma sources_composite_of:\n    assumes \"composite_of u t v\"\n    shows \"sources v = sources u\"\n      using assms\n      by (meson arr_resid_iff_con composite_of_def con_imp_coinitial cong_implies_coinitial\n          coinitial_iff)\n\n    lemma targets_composite_of:\n    assumes \"composite_of u t v\"\n    shows \"targets v = targets t\"\n    proof -\n      have \"targets t = targets (v \\\\ u)\"\n        using assms composite_of_def\n        by (meson cong_implies_coterminal coterminal_iff)\n      also have \"... = targets (u \\\\ v)\"\n        using assms targets_resid_sym con_prfx_composite_of by metis\n      also have \"... = targets v\"\n        using assms composite_of_def\n        by (metis prfx_implies_con sources_resid ideE)\n      finally show ?thesis by auto\n    qed\n\n    lemma resid_composite_of:\n    assumes \"composite_of t u w\" and \"w \\<frown> v\"\n    shows \"v \\\\ t \\<frown> w \\\\ t\"\n    and \"v \\\\ t \\<frown> u\"\n    and \"v \\\\ w \\<sim> (v \\\\ t) \\\\ u\"\n    and \"composite_of (t \\\\ v) (u \\\\ (v \\\\ t)) (w \\\\ v)\"\n    proof -\n      show 0: \"v \\\\ t \\<frown> w \\\\ t\"\n        using assms con_def\n        by (metis con_target composite_ofE conE con_sym cube)\n      show 1: \"v \\\\ w \\<sim> (v \\\\ t) \\\\ u\"\n      proof -\n        have \"v \\\\ w = (v \\\\ w) \\\\ (t \\\\ w)\"\n          using assms composite_of_def\n          by (metis (no_types, opaque_lifting) con_target con_sym resid_arr_ide)\n        also have \"... = (v \\\\ t) \\\\ (w \\\\ t)\"\n          using assms cube by metis\n        also have \"... \\<sim> (v \\\\ t) \\\\ u\"\n          using assms 0 cong_subst_right(2) [of \"w \\\\ t\" u \"v \\\\ t\"] by blast\n        finally show ?thesis by blast\n      qed\n      show 2: \"v \\\\ t \\<frown> u\"\n        using assms 1 by force\n      show \"composite_of (t \\\\ v) (u \\\\ (v \\\\ t)) (w \\\\ v)\"\n      proof (unfold composite_of_def, intro conjI)\n        show \"t \\\\ v \\<lesssim> w \\\\ v\"\n          using assms cube con_target composite_of_def resid_ide_arr by metis\n        show \"(w \\\\ v) \\\\ (t \\\\ v) \\<lesssim> u \\\\ (v \\\\ t)\"\n          by (metis assms(1) 2 composite_ofE con_sym cong_subst_left(2) cube)\n        thus \"u \\\\ (v \\\\ t) \\<lesssim> (w \\\\ v) \\\\ (t \\\\ v)\"\n          using assms\n          by (metis composite_of_def con_implies_arr(2) cong_subst_left(2)\n              prfx_implies_con arr_resid_iff_con cube)\n      qed\n    qed\n\n    lemma con_composite_of_iff:\n    assumes \"composite_of t u v\"\n    shows \"w \\<frown> v \\<longleftrightarrow> w \\\\ t \\<frown> u\"\n      by (meson arr_resid_iff_con assms composite_ofE con_def con_implies_arr(1)\n          con_sym_ax cong_subst_right(1) resid_composite_of(2) resid_reflects_con)\n\n    definition composable\n    where \"composable t u \\<equiv> \\<exists>v. composite_of t u v\"\n\n    lemma composableD [dest]:\n    assumes \"composable t u\"\n    shows \"arr t\" and \"arr u\" and \"targets t = sources u\"\n      using assms arr_composite_of arr_iff_has_source composable_def sources_composite_of\n            arr_composite_of arr_iff_has_target composable_def targets_composite_of\n        apply auto[2]\n      by (metis assms composable_def composite_ofE con_prfx_composite_of(1) con_sym\n          cong_implies_coinitial coinitial_iff sources_resid)\n\n    lemma composable_imp_seq:\n    assumes \"composable t u\"\n    shows \"seq t u\"\n      using assms by blast\n\n    lemma bounded_imp_con:\n    assumes \"composite_of t u v\" and \"composite_of t' u' v\"\n    shows \"con t t'\"\n      by (meson assms composite_of_def con_prfx_composite_of prfx_implies_con\n          arr_resid_iff_con con_implies_arr(2))\n\n    lemma composite_of_cancel_left:\n    assumes \"composite_of t u v\" and \"composite_of t u' v\"\n    shows \"u \\<sim> u'\"\n      using assms composite_of_def cong_transitive by blast\n\n  end\n\n  subsubsection \"RTS with Composites\"\n\n  locale rts_with_composites = rts +\n  assumes has_composites: \"seq t u \\<Longrightarrow> composable t u\"\n  begin\n\n    lemma composable_iff_seq:\n    shows \"composable g f \\<longleftrightarrow> seq g f\"\n      using composable_imp_seq has_composites by blast\n\n    lemma obtains_composite_of:\n    assumes \"seq g f\"\n    obtains h where \"composite_of g f h\"\n      using assms has_composites composable_def by blast\n\n    lemma diamond_commutes_upto_cong:\n    assumes \"composite_of t (u \\\\ t) v\" and \"composite_of u (t \\\\ u) v'\"\n    shows \"v \\<sim> v'\"\n      using assms cube ide_backward_stable prfx_transitive\n      by (elim composite_ofE) metis\n\n  end\n\n  subsection \"Joins of Transitions\"\n\n  context rts\n  begin\n\n    text \\<open>\n      Transition \\<open>v\\<close> is a \\emph{join} of \\<open>u\\<close> and \\<open>v\\<close> when \\<open>v\\<close> is the diagonal of the square\n      formed by \\<open>u\\<close>, \\<open>v\\<close>, and their residuals.  As was the case for composites,\n      joins in an RTS are not unique, but they are unique up to congruence.\n    \\<close>\n\n    definition join_of\n    where \"join_of t u v \\<equiv> composite_of t (u \\\\ t) v \\<and> composite_of u (t \\\\ u) v\"\n\n    lemma join_ofI [intro]:\n    assumes \"composite_of t (u \\\\ t) v\" and \"composite_of u (t \\\\ u) v\"\n    shows \"join_of t u v\"\n      using assms join_of_def by simp\n\n    lemma join_ofE [elim]:\n    assumes \"join_of t u v\"\n    and \"\\<lbrakk>composite_of t (u \\\\ t) v; composite_of u (t \\\\ u) v\\<rbrakk> \\<Longrightarrow> T\"\n    shows T\n      using assms join_of_def by simp\n\n    definition joinable\n    where \"joinable t u \\<equiv> \\<exists>v. join_of t u v\"\n\n    lemma joinable_implies_con:\n    assumes \"joinable t u\"\n    shows \"t \\<frown> u\"\n      by (meson assms bounded_imp_con join_of_def joinable_def)\n\n    lemma joinable_implies_coinitial:\n    assumes \"joinable t u\"\n    shows \"coinitial t u\"\n      using assms\n      by (simp add: con_imp_coinitial joinable_implies_con)\n\n    lemma join_of_un_upto_cong:\n    assumes \"join_of t u v\" and \"join_of t u v'\"\n    shows \"v \\<sim> v'\"\n      using assms join_of_def composite_of_unq_upto_cong by auto\n\n    lemma join_of_symmetric:\n    assumes \"join_of t u v\"\n    shows \"join_of u t v\"\n      using assms join_of_def by simp\n\n    lemma join_of_arr_self:\n    assumes \"arr t\"\n    shows \"join_of t t t\"\n      by (meson assms composite_of_arr_ide ideE join_of_def prfx_reflexive)\n\n    lemma join_of_arr_src:\n    assumes \"arr t\" and \"a \\<in> sources t\"\n    shows \"join_of a t t\" and \"join_of t a t\"\n    proof -\n      show \"join_of a t t\"\n        by (meson assms composite_of_arr_target composite_of_def composite_of_source_arr join_of_def\n                  prfx_transitive resid_source_in_targets)\n      thus \"join_of t a t\"\n        using join_of_symmetric by blast\n    qed\n\n    lemma sources_join_of:\n    assumes \"join_of t u v\"\n    shows \"sources t = sources v\" and \"sources u = sources v\"\n      using assms join_of_def sources_composite_of by blast+\n\n    lemma targets_join_of:\n    assumes \"join_of t u v\"\n    shows \"targets (t \\\\ u) = targets v\" and \"targets (u \\\\ t) = targets v\"\n      using assms join_of_def targets_composite_of by blast+\n\n    lemma join_of_resid:\n    assumes \"join_of t u w\" and \"con v w\"\n    shows \"join_of (t \\\\ v) (u \\\\ v) (w \\\\ v)\"\n      using assms con_sym cube join_of_def resid_composite_of(4) by fastforce\n    \n    lemma con_with_join_of_iff:\n    assumes \"join_of t u w\"\n    shows \"u \\<frown> v \\<and> v \\\\ u \\<frown> t \\\\ u \\<Longrightarrow> w \\<frown> v\"\n    and \"w \\<frown> v \\<Longrightarrow> t \\<frown> v \\<and> v \\\\ t \\<frown> u \\\\ t\"\n    proof -\n      have *: \"t \\<frown> v \\<and> v \\\\ t \\<frown> u \\\\ t \\<longleftrightarrow> u \\<frown> v \\<and> v \\\\ u \\<frown> t \\\\ u\"\n        by (metis arr_resid_iff_con con_implies_arr(1) con_sym cube)\n      show \"u \\<frown> v \\<and> v \\\\ u \\<frown> t \\\\ u \\<Longrightarrow> w \\<frown> v\"\n        by (meson assms con_composite_of_iff con_sym join_of_def)\n      show \"w \\<frown> v \\<Longrightarrow> t \\<frown> v \\<and> v \\\\ t \\<frown> u \\\\ t\"\n        by (meson assms con_prfx_composite_of join_of_def resid_composite_of(2))\n    qed\n\n  end\n\n  subsubsection \"RTS with Joins\"\n\n  locale rts_with_joins = rts +\n  assumes has_joins: \"t \\<frown> u \\<Longrightarrow> joinable t u\"\n\n  subsection \"Joins and Composites in a Weakly Extensional RTS\"\n\n  context weakly_extensional_rts\n  begin\n\n    lemma src_composite_of:\n    assumes \"composite_of u t v\"\n    shows \"src v = src u\"\n      using assms\n      by (metis con_imp_eq_src con_prfx_composite_of(1))\n\n    lemma trg_composite_of:\n    assumes \"composite_of u t v\"\n    shows \"trg v = trg t\"\n      by (metis arr_composite_of arr_has_un_target arr_iff_has_target assms\n          targets_composite_of trg_in_targets)\n\n    lemma src_join_of:\n    assumes \"join_of t u v\"\n    shows \"src t = src v\" and \"src u = src v\"\n      by (metis assms join_ofE src_composite_of)+\n\n    lemma trg_join_of:\n    assumes \"join_of t u v\"\n    shows \"trg (t \\\\ u) = trg v\" and \"trg (u \\\\ t) = trg v\"\n      by (metis assms join_of_def trg_composite_of)+\n\n  end\n\n  subsection \"Joins and Composites in an Extensional RTS\"\n\n  context extensional_rts\n  begin\n\n    lemma composite_of_unique:\n    assumes \"composite_of t u v\" and \"composite_of t u v'\"\n    shows \"v = v'\"\n      using assms composite_of_unq_upto_cong extensional by fastforce\n\n    text \\<open>\n      Here we define composition of transitions.  Note that we compose transitions\n      in diagram order, rather than in the order used for function composition.\n      This may eventually lead to confusion, but here (unlike in the case of a category)\n      transitions are typically not functions, so we don't have the constraint of having\n      to conform to the order of function application and composition, and diagram order\n      seems more natural.\n    \\<close>\n\n    definition comp  (infixl \"\\<cdot>\" 55)\n    where \"t \\<cdot> u \\<equiv> if composable t u then THE v. composite_of t u v else null\"\n\n    lemma comp_is_composite_of:\n    assumes \"composite_of t u v\"\n    shows \"composite_of t u (t \\<cdot> u)\" and \"t \\<cdot> u = v\"\n    proof -\n      show \"composite_of t u (t \\<cdot> u)\"\n        using assms comp_def composite_of_unique the1I2 [of \"composite_of t u\" \"composite_of t u\"]\n              composable_def\n        by metis\n      thus \"t \\<cdot> u = v\"\n        using assms composite_of_unique by simp\n    qed\n\n    lemma comp_null [simp]:\n    shows \"null \\<cdot> t = null\" and \"t \\<cdot> null = null\"\n      by (meson composableD not_arr_null comp_def)+\n\n    lemma composable_iff_arr_comp:\n    shows \"composable t u \\<longleftrightarrow> arr (t \\<cdot> u)\"\n      by (metis arr_composite_of comp_is_composite_of(2) composable_def comp_def not_arr_null)\n\n    lemma composable_iff_comp_not_null:\n    shows \"composable t u \\<longleftrightarrow> t \\<cdot> u \\<noteq> null\"\n      by (metis composable_iff_arr_comp comp_def not_arr_null)\n\n    lemma comp_src_arr [simp]:\n    assumes \"arr t\" and \"src t = a\"\n    shows \"a \\<cdot> t = t\"\n      using assms comp_is_composite_of(2) composite_of_source_arr src_in_sources by blast\n\n    lemma comp_arr_trg [simp]:\n    assumes \"arr t\" and \"trg t = b\"\n    shows \"t \\<cdot> b = t\"\n      using assms comp_is_composite_of(2) composite_of_arr_target trg_in_targets by blast\n\n    lemma comp_ide_self:\n    assumes \"ide a\"\n    shows \"a \\<cdot> a = a\"\n      using assms comp_is_composite_of(2) composite_of_ide_self by fastforce\n\n    lemma arr_comp [intro, simp]:\n    assumes \"composable t u\"\n    shows \"arr (t \\<cdot> u)\"\n      using assms composable_iff_arr_comp by blast\n\n    lemma trg_comp [simp]:\n    assumes \"composable t u\"\n    shows \"trg (t \\<cdot> u) = trg u\"\n      by (metis arr_has_un_target assms comp_is_composite_of(2) composable_def\n          composable_imp_seq arr_iff_has_target seq_def targets_composite_of trg_in_targets)\n\n    lemma src_comp [simp]:\n    assumes \"composable t u\"\n    shows \"src (t \\<cdot> u) = src t\"\n      using assms comp_is_composite_of arr_iff_has_source sources_composite_of src_def\n            composable_def\n      by auto\n\n    lemma con_comp_iff:\n    shows \"w \\<frown> t \\<cdot> u \\<longleftrightarrow> composable t u \\<and> w \\\\ t \\<frown> u\"\n      by (meson comp_is_composite_of(1) con_composite_of_iff con_sym con_implies_arr(2)\n                composable_def composable_iff_arr_comp)\n\n    lemma con_compI [intro]:\n    assumes \"composable t u\" and \"w \\\\ t \\<frown> u\"\n    shows \"w \\<frown> t \\<cdot> u\" and \"t \\<cdot> u \\<frown> w\"\n      using assms con_comp_iff con_sym by blast+\n\n    lemma resid_comp:\n    assumes \"t \\<cdot> u \\<frown> w\"\n    shows \"w \\\\ (t \\<cdot> u) = (w \\\\ t) \\\\ u\"\n    and \"(t \\<cdot> u) \\\\ w = (t \\\\ w) \\<cdot> (u \\\\ (w \\\\ t))\"\n    proof -\n      have 1: \"composable t u\"\n        using assms composable_iff_comp_not_null by force\n      show \"w \\\\ (t \\<cdot> u) = (w \\\\ t) \\\\ u\"\n        using 1\n        by (meson assms cong_char composable_def resid_composite_of(3) comp_is_composite_of(1))\n      show \"(t \\<cdot> u) \\\\ w = (t \\\\ w) \\<cdot> (u \\\\ (w \\\\ t))\"\n        using assms 1 composable_def comp_is_composite_of(2) resid_composite_of\n        by metis\n    qed\n\n    lemma prfx_decomp:\n    assumes \"t \\<lesssim> u\"\n    shows \"t \\<cdot> (u \\\\ t) = u\"\n      by (meson assms arr_resid_iff_con comp_is_composite_of(2) composite_of_def con_sym\n          cong_reflexive prfx_implies_con)\n\n    lemma prfx_comp:\n    assumes \"arr u\" and \"t \\<cdot> v = u\"\n    shows \"t \\<lesssim> u\"\n      by (metis assms comp_is_composite_of(2) composable_def composable_iff_arr_comp\n                composite_of_def)\n\n    lemma comp_eqI:\n    assumes \"t \\<lesssim> v\" and \"u = v \\\\ t\"\n    shows \"t \\<cdot> u = v\"\n      by (metis assms prfx_decomp)\n\n    lemma comp_assoc:\n    assumes \"composable (t \\<cdot> u) v\"\n    shows \"t \\<cdot> (u \\<cdot> v) = (t \\<cdot> u) \\<cdot> v\"\n    proof -\n      have 1: \"t \\<lesssim> (t \\<cdot> u) \\<cdot> v\"\n        by (meson assms composable_iff_arr_comp composableD prfx_comp\n            prfx_transitive)\n      moreover have \"((t \\<cdot> u) \\<cdot> v) \\\\ t = u \\<cdot> v\"\n      proof -\n        have \"((t \\<cdot> u) \\<cdot> v) \\\\ t = ((t \\<cdot> u) \\\\ t) \\<cdot> (v \\\\ (t \\\\ (t \\<cdot> u)))\" \n          by (meson assms calculation con_sym prfx_implies_con resid_comp(2))\n        also have \"... = u \\<cdot> v\"\n        proof -\n          have 2: \"(t \\<cdot> u) \\\\ t = u\"\n            by (metis assms comp_is_composite_of(2) composable_def composable_iff_arr_comp\n                      composable_imp_seq composite_of_def extensional seqE)\n          moreover have \"v \\\\ (t \\\\ (t \\<cdot> u)) = v\"\n            using assms\n            by (meson 1 con_comp_iff con_sym composable_imp_seq resid_arr_ide\n                prfx_implies_con prfx_comp seqE)\n          ultimately show ?thesis by simp\n        qed\n        finally show ?thesis by blast\n      qed\n      ultimately show \"t \\<cdot> (u \\<cdot> v) = (t \\<cdot> u) \\<cdot> v\"\n        by (metis comp_eqI)\n    qed\n\n    text \\<open>\n      We note the following assymmetry: \\<open>composable (t \\<cdot> u) v \\<Longrightarrow> composable u v\\<close> is true,\n      but \\<open>composable t (u \\<cdot> v) \\<Longrightarrow> composable t u\\<close> is not.\n    \\<close>\n\n    lemma comp_cancel_left:\n    assumes \"arr (t \\<cdot> u)\" and \"t \\<cdot> u = t \\<cdot> v\"\n    shows \"u = v\"\n      using assms\n      by (metis composable_def composable_iff_arr_comp composite_of_cancel_left extensional\n          comp_is_composite_of(2))\n\n    lemma comp_resid_prfx [simp]:\n    assumes \"arr (t \\<cdot> u)\"\n    shows \"(t \\<cdot> u) \\\\ t = u\"\n      using assms\n      by (metis comp_cancel_left comp_eqI prfx_comp)\n\n    lemma bounded_imp_con\\<^sub>E:\n    assumes \"t \\<cdot> u \\<sim> t' \\<cdot> u'\"\n    shows \"t \\<frown> t'\"\n      by (metis arr_resid_iff_con assms con_comp_iff con_implies_arr(2) prfx_implies_con\n                con_sym)\n\n    lemma join_of_unique:\n    assumes \"join_of t u v\" and \"join_of t u v'\"\n    shows \"v = v'\"\n      using assms join_of_def composite_of_unique by blast\n\n    definition join  (infix \"\\<squnion>\" 52)\n    where \"t \\<squnion> u \\<equiv> if joinable t u then THE v. join_of t u v else null\"\n\n    lemma join_is_join_of:\n    assumes \"joinable t u\"\n    shows \"join_of t u (t \\<squnion> u)\"\n      using assms joinable_def join_def join_of_unique the1I2 [of \"join_of t u\" \"join_of t u\"]\n      by force\n\n    lemma joinable_iff_arr_join:\n    shows \"joinable t u \\<longleftrightarrow> arr (t \\<squnion> u)\"\n      by (metis cong_char join_is_join_of join_of_un_upto_cong not_arr_null join_def)\n\n    lemma joinable_iff_join_not_null:\n    shows \"joinable t u \\<longleftrightarrow> t \\<squnion> u \\<noteq> null\"\n      by (metis join_def joinable_iff_arr_join not_arr_null)\n\n    lemma join_sym:\n    assumes \"t \\<squnion> u \\<noteq> null\"\n    shows \"t \\<squnion> u = u \\<squnion> t\"\n      using assms\n      by (meson join_def join_is_join_of join_of_symmetric join_of_unique joinable_def)\n\n    lemma src_join:\n    assumes \"joinable t u\"\n    shows \"src (t \\<squnion> u) = src t\"\n      using assms\n      by (metis con_imp_eq_src con_prfx_composite_of(1) join_is_join_of join_of_def)\n\n    lemma trg_join:\n    assumes \"joinable t u\"\n    shows \"trg (t \\<squnion> u) = trg (t \\\\ u)\"\n      using assms\n      by (metis arr_resid_iff_con join_is_join_of joinable_iff_arr_join joinable_implies_con\n          in_targetsE src_eqI targets_join_of(1) trg_in_targets)\n\n    lemma resid_join\\<^sub>E [simp]:\n    assumes \"joinable t u\" and \"v \\<frown> t \\<squnion> u\"\n    shows \"v \\\\ (t \\<squnion> u) = (v \\\\ u) \\\\ (t \\\\ u)\"\n    and \"v \\\\ (t \\<squnion> u) = (v \\\\ t) \\\\ (u \\\\ t)\"\n    and \"(t \\<squnion> u) \\\\ v = (t \\\\ v) \\<squnion> (u \\\\ v)\"\n    proof -\n      show 1: \"v \\\\ (t \\<squnion> u) = (v \\\\ u) \\\\ (t \\\\ u)\"\n        by (meson assms con_sym join_of_def resid_composite_of(3) extensional join_is_join_of)\n      show \"v \\\\ (t \\<squnion> u) = (v \\\\ t) \\\\ (u \\\\ t)\"\n        by (metis \"1\" cube)\n      show \"(t \\<squnion> u) \\\\ v = (t \\\\ v) \\<squnion> (u \\\\ v)\"\n        using assms joinable_def join_of_resid join_is_join_of extensional\n        by (meson join_of_unique)\n    qed\n\n    lemma join_eqI:\n    assumes \"t \\<lesssim> v\" and \"u \\<lesssim> v\" and \"v \\\\ u = t \\\\ u\" and \"v \\\\ t = u \\\\ t\"\n    shows \"t \\<squnion> u = v\"\n      using assms composite_of_def cube ideE join_of_def joinable_def join_of_unique\n            join_is_join_of trg_def\n      by metis\n\n    lemma comp_join:\n    assumes \"joinable (t \\<cdot> u) (t \\<cdot> u')\"\n    shows \"composable t (u \\<squnion> u')\"\n    and \"t \\<cdot> (u \\<squnion> u') = t \\<cdot> u \\<squnion> t \\<cdot> u'\"\n    proof -\n      have \"t \\<lesssim> t \\<cdot> u \\<squnion> t \\<cdot> u'\"\n        using assms\n        by (metis composable_def composite_of_def join_of_def join_is_join_of\n            joinable_implies_con prfx_transitive comp_is_composite_of(2) con_comp_iff)\n      moreover have \"(t \\<cdot> u \\<squnion> t \\<cdot> u') \\\\ t = u \\<squnion> u'\"\n        by (metis arr_resid_iff_con assms calculation comp_resid_prfx con_implies_arr(2)\n            joinable_implies_con resid_join\\<^sub>E(3) con_implies_arr(1) ide_implies_arr)\n      ultimately show \"t \\<cdot> (u \\<squnion> u') = t \\<cdot> u \\<squnion> t \\<cdot> u'\"\n        by (metis comp_eqI)\n      thus \"composable t (u \\<squnion> u')\"\n        by (metis assms joinable_iff_join_not_null comp_def)\n    qed\n\n    lemma join_src:\n    assumes \"arr t\"\n    shows \"src t \\<squnion> t = t\"\n      using assms joinable_def join_of_arr_src join_is_join_of join_of_unique src_in_sources\n      by meson\n\n    lemma join_self:\n    assumes \"arr t\"\n    shows \"t \\<squnion> t = t\"\n      using assms joinable_def join_of_arr_self join_is_join_of join_of_unique by blast\n\n    lemma arr_prfx_join_self:\n    assumes \"joinable t u\"\n    shows \"t \\<lesssim> t \\<squnion> u\"\n      using assms\n      by (meson composite_of_def join_is_join_of join_of_def)\n\n    text \\<open>\n      We note that it is not the case that the existence of either of \\<open>t \\<squnion> (u \\<squnion> v)\\<close>\n      or \\<open>(t \\<squnion> u) \\<squnion> v\\<close> implies that of the other.  For example, if \\<open>(t \\<squnion> u) \\<squnion> v \\<noteq> null\\<close>,\n      then it is not necessarily the case that \\<open>u \\<squnion> v \\<noteq> null\\<close>.\n    \\<close>\n\n  end\n\n  subsubsection \"Extensional RTS with Joins\"\n\n  locale extensional_rts_with_joins =\n    rts_with_joins +\n    extensional_rts\n  begin\n\n    lemma joinable_iff_con:\n    shows \"joinable t u \\<longleftrightarrow> t \\<frown> u\"\n      by (meson has_joins joinable_implies_con)\n\n    lemma src_join\\<^sub>E\\<^sub>J [simp]:\n    assumes \"t \\<frown> u\"\n    shows \"src (t \\<squnion> u) = src t\"\n      using assms\n      by (meson has_joins src_join)\n\n    lemma trg_join\\<^sub>E\\<^sub>J:\n    assumes \"t \\<frown> u\"\n    shows \"trg (t \\<squnion> u) = trg (t \\\\ u)\"\n      using assms\n      by (meson has_joins trg_join)\n\n    lemma resid_join\\<^sub>E\\<^sub>J [simp]:\n    assumes \"t \\<frown> u\" and \"v \\<frown> t \\<squnion> u\"\n    shows \"v \\\\ (t \\<squnion> u) = (v \\\\ t) \\\\ (u \\\\ t)\"\n    and \"(t \\<squnion> u) \\\\ v = (t \\\\ v) \\<squnion> (u \\\\ v)\"\n      using assms has_joins resid_join\\<^sub>E by blast+\n\n    lemma join_assoc:\n    shows \"t \\<squnion> (u \\<squnion> v) = (t \\<squnion> u) \\<squnion> v\"\n    proof -\n      have *: \"\\<And>t u v. con (t \\<squnion> u) v \\<Longrightarrow> t \\<squnion> (u \\<squnion> v) = (t \\<squnion> u) \\<squnion> v\"\n      proof -\n        fix t u v\n        assume 1: \"con (t \\<squnion> u) v\"\n        have vt_ut: \"v \\\\ t \\<frown> u \\\\ t\"\n          using 1\n          by (metis con_implies_arr(1) con_with_join_of_iff(2) join_is_join_of not_arr_null\n              join_def)\n        have tv_uv: \"t \\\\ v \\<frown> u \\\\ v\"\n          using vt_ut cube con_sym\n          by (metis arr_resid_iff_con)\n        have 2: \"(t \\<squnion> u) \\<squnion> v = (t \\<cdot> (u \\\\ t)) \\<cdot> (v \\\\ (t \\<cdot> (u \\\\ t)))\"\n          using 1\n          by (metis comp_is_composite_of(2) con_implies_arr(1) has_joins join_is_join_of\n                    join_of_def joinable_iff_arr_join)\n        also have \"... = t \\<cdot> ((u \\\\ t) \\<cdot> (v \\\\ (t \\<cdot> (u \\\\ t))))\"\n          using 1\n          by (metis calculation has_joins joinable_iff_join_not_null comp_assoc comp_def)\n        also have \"... = t \\<cdot> ((u \\\\ t) \\<cdot> ((v \\\\ t) \\\\ (u \\\\ t)))\"\n          using 1\n          by (metis 2 comp_null(2) con_compI(2) con_comp_iff has_joins resid_comp(1)\n              conI joinable_iff_join_not_null)\n        also have \"... = t \\<cdot> ((v \\\\ t) \\<squnion> (u \\\\ t))\"\n          by (metis vt_ut comp_is_composite_of(2) has_joins join_of_def join_is_join_of)\n        also have \"... = t \\<cdot> ((u \\\\ t) \\<squnion> (v \\\\ t))\"\n          using join_sym by metis\n        also have \"... = t \\<cdot> ((u \\<squnion> v) \\\\ t)\"\n          by (metis tv_uv vt_ut con_implies_arr(2) con_sym con_with_join_of_iff(1) has_joins\n                    join_is_join_of arr_resid_iff_con resid_join\\<^sub>E(3))\n        also have \"... = t \\<squnion> (u \\<squnion> v)\"\n          by (metis comp_is_composite_of(2) comp_null(2) conI has_joins join_is_join_of\n              join_of_def joinable_iff_join_not_null)\n        finally show \"t \\<squnion> (u \\<squnion> v) = (t \\<squnion> u) \\<squnion> v\"\n          by simp\n      qed\n      thus ?thesis\n        by (metis (full_types) has_joins joinable_iff_join_not_null joinable_implies_con con_sym)\n    qed\n\n    lemma join_is_lub:\n    assumes \"t \\<lesssim> v\" and \"u \\<lesssim> v\"\n    shows \"t \\<squnion> u \\<lesssim> v\"\n    proof -\n      have \"(t \\<squnion> u) \\\\ v = (t \\\\ v) \\<squnion> (u \\\\ v)\"\n        using assms resid_join\\<^sub>E(3) [of t u v]\n        by (metis arr_prfx_join_self con_target con_sym join_assoc joinable_iff_con\n            joinable_iff_join_not_null prfx_implies_con resid_reflects_con)\n      also have \"... = trg v \\<squnion> trg v\"\n        using assms\n        by (metis ideE prfx_implies_con src_resid trg_ide)\n      also have \"... = trg v\"\n        by (metis assms(2) ide_iff_src_self ide_implies_arr join_self prfx_implies_con\n            src_resid)\n      finally have \"(t \\<squnion> u) \\\\ v = trg v\" by blast\n      moreover have \"ide (trg v)\"\n        using assms\n        by (metis con_implies_arr(2) prfx_implies_con cong_char trg_def)\n      ultimately show ?thesis by simp\n    qed\n        \n  end\n\n  subsubsection \"Extensional RTS with Composites\"\n\n  text \\<open>\n    If an extensional RTS is assumed to have composites for all composable pairs of transitions,\n    then the ``semantic'' property of transitions being composable can be replaced by the\n    ``syntactic'' property of transitions being sequential.  This results in simpler\n    statements of a number of properties.\n  \\<close>\n\n  locale extensional_rts_with_composites =\n    rts_with_composites +\n    extensional_rts\n  begin\n\n    lemma seq_implies_arr_comp:\n    assumes \"seq t u\"\n    shows \"arr (t \\<cdot> u)\"\n      using assms\n      by (meson composable_iff_arr_comp composable_iff_seq)\n\n    lemma arr_comp\\<^sub>E\\<^sub>C [intro, simp]:\n    assumes \"arr t\" and \"arr u\" and \"trg t = src u\"\n    shows \"arr (t \\<cdot> u)\"\n      using assms\n      by (simp add: seq_implies_arr_comp)\n\n    lemma arr_compE\\<^sub>E\\<^sub>C [elim]:\n    assumes \"arr (t \\<cdot> u)\"\n    and \"\\<lbrakk>arr t; arr u; trg t = src u\\<rbrakk> \\<Longrightarrow> T\"\n    shows T\n      using assms composable_iff_arr_comp composable_iff_seq by blast\n\n    lemma trg_comp\\<^sub>E\\<^sub>C [simp]:\n    assumes \"seq t u\"\n    shows \"trg (t \\<cdot> u) = trg u\"\n      by (meson assms has_composites trg_comp)\n\n    lemma src_comp\\<^sub>E\\<^sub>C [simp]:\n    assumes \"seq t u\"\n    shows \"src (t \\<cdot> u) = src t\"\n      using assms src_comp has_composites by simp\n\n    lemma con_comp_iff\\<^sub>E\\<^sub>C [simp]:\n    shows \"w \\<frown> t \\<cdot> u \\<longleftrightarrow> seq t u \\<and> u \\<frown> w \\\\ t\"\n    and \"t \\<cdot> u \\<frown> w \\<longleftrightarrow> seq t u \\<and> u \\<frown> w \\\\ t\"\n      using composable_iff_seq con_comp_iff con_sym by meson+\n\n    lemma comp_assoc\\<^sub>E\\<^sub>C:\n    shows \"t \\<cdot> (u \\<cdot> v) = (t \\<cdot> u) \\<cdot> v\"\n      apply (cases \"seq t u\")\n       apply (metis arr_comp comp_assoc comp_def not_arr_null arr_compE\\<^sub>E\\<^sub>C arr_comp\\<^sub>E\\<^sub>C\n                    seq_implies_arr_comp trg_comp\\<^sub>E\\<^sub>C)\n      by (metis comp_def composable_iff_arr_comp seqI\\<^sub>W\\<^sub>E src_comp arr_compE\\<^sub>E\\<^sub>C)\n\n    lemma diamond_commutes:\n    shows \"t \\<cdot> (u \\\\ t) = u \\<cdot> (t \\\\ u)\"\n    proof (cases \"t \\<frown> u\")\n      show \"\\<not> t \\<frown> u \\<Longrightarrow> ?thesis\"\n        by (metis comp_null(2) conI con_sym)\n      assume con: \"t \\<frown> u\"\n      have \"(t \\<cdot> (u \\\\ t)) \\\\ u = (t \\\\ u) \\<cdot> ((u \\\\ t) \\\\ (u \\\\ t))\"\n        using con\n        by (metis (no_types, lifting) arr_resid_iff_con con_compI(2) con_implies_arr(1)\n            resid_comp(2) con_imp_arr_resid con_sym comp_def arr_comp\\<^sub>E\\<^sub>C src_resid conI)\n      moreover have \"u \\<lesssim> t \\<cdot> (u \\\\ t)\"\n        by (metis arr_resid_iff_con calculation con cong_reflexive comp_arr_trg resid_arr_self\n            resid_comp(1) trg_resid_sym)\n      ultimately show ?thesis\n        by (metis comp_eqI con comp_arr_trg resid_arr_self arr_resid trg_resid_sym)\n    qed\n\n    lemma mediating_transition:\n    assumes \"t \\<cdot> v = u \\<cdot> w\"\n    shows \"v \\\\ (u \\\\ t) = w \\\\ (t \\\\ u)\"\n    proof (cases \"seq t v\")\n      assume 1: \"seq t v\"\n      hence 2: \"arr (u \\<cdot> w)\"\n        using assms by (metis arr_comp\\<^sub>E\\<^sub>C seqE\\<^sub>W\\<^sub>E)\n      have 3: \"v \\\\ (u \\\\ t) = ((t \\<cdot> v) \\\\ t) \\\\ (u \\\\ t)\"\n        by (metis \"1\" comp_is_composite_of(1) composite_of_def obtains_composite_of extensional)\n      also have \"... = (t \\<cdot> v) \\\\ (t \\<cdot> (u \\\\ t))\"\n        by (metis (no_types, lifting) \"2\" assms con_comp_iff\\<^sub>E\\<^sub>C(2) con_imp_eq_src\n            con_implies_arr(2) con_sym comp_resid_prfx prfx_comp resid_comp(1)\n            arr_compE\\<^sub>E\\<^sub>C arr_comp\\<^sub>E\\<^sub>C prfx_implies_con)\n      also have \"... = (u \\<cdot> w) \\\\ (u \\<cdot> (t \\\\ u))\"\n        using assms diamond_commutes by presburger\n      also have \"... = ((u \\<cdot> w) \\\\ u) \\\\ (t \\\\ u)\"\n        by (metis 3 assms calculation cube)\n      also have \"... = w \\\\ (t \\\\ u)\"\n        using 2 by simp\n      finally show ?thesis by blast\n      next\n      assume 1: \"\\<not> seq t v\"\n      have \"v \\\\ (u \\\\ t) = null\"\n        using 1\n        by (metis (mono_tags, lifting) arr_resid_iff_con coinitial_iff\\<^sub>W\\<^sub>E con_imp_coinitial\n            seqI\\<^sub>W\\<^sub>E src_resid conI)\n      also have \"... = w \\\\ (t \\\\ u)\"\n        by (metis (no_types, lifting) \"1\" arr_comp\\<^sub>E\\<^sub>C assms composable_imp_seq con_imp_eq_src\n            con_implies_arr(1) con_implies_arr(2) comp_def not_arr_null conI src_resid)\n      finally show ?thesis by blast\n    qed\n\n    lemma induced_arrow:\n    assumes \"seq t u\" and \"t \\<cdot> u = t' \\<cdot> u'\"\n    shows \"(t' \\\\ t) \\<cdot> (u \\\\ (t' \\\\ t)) = u\"\n    and \"(t \\\\ t') \\<cdot> (u \\\\ (t' \\\\ t)) = u'\"\n    and \"(t' \\\\ t) \\<cdot> v = u \\<Longrightarrow> v = u \\\\ (t' \\\\ t)\"\n      apply (metis assms comp_eqI arr_compE\\<^sub>E\\<^sub>C prfx_comp resid_comp(1) arr_resid_iff_con\n                   seq_implies_arr_comp)\n       apply (metis assms comp_resid_prfx arr_compE\\<^sub>E\\<^sub>C resid_comp(2) arr_resid_iff_con\n                    seq_implies_arr_comp)\n      by (metis assms(1) comp_resid_prfx seq_def)\n\n    text \\<open>\n      If an extensional RTS has composites, then it automatically has joins.\n    \\<close>\n\n    sublocale extensional_rts_with_joins\n    proof\n      fix t u\n      assume con: \"t \\<frown> u\"\n      have 1: \"con u (t \\<cdot> (u \\\\ t))\"\n        using con_compI(1) [of t \"u \\\\ t\" u]\n        by (metis con con_implies_arr(1) con_sym diamond_commutes prfx_implies_con arr_resid\n            prfx_comp src_resid arr_comp\\<^sub>E\\<^sub>C)\n      have \"t \\<squnion> u = t \\<cdot> (u \\\\ t)\"\n      proof (intro join_eqI)\n        show \"t \\<lesssim> t \\<cdot> (u \\\\ t)\"\n          by (metis 1 composable_def comp_is_composite_of(2) composite_of_def con_comp_iff)\n        moreover show 2: \"u \\<lesssim> t \\<cdot> (u \\\\ t)\"\n          using 1 arr_resid con con_sym prfx_reflexive resid_comp(1) by metis\n        moreover show \"(t \\<cdot> (u \\\\ t)) \\\\ u = t \\\\ u\"\n          using 1 diamond_commutes induced_arrow(2) resid_comp(2) by force\n        ultimately show \"(t \\<cdot> (u \\\\ t)) \\\\ t = u \\\\ t\"\n          by (metis con_comp_iff\\<^sub>E\\<^sub>C(1) con_sym prfx_implies_con resid_comp(2) induced_arrow(1))\n      qed\n      thus \"joinable t u\"\n        by (metis \"1\" con_implies_arr(2) joinable_iff_join_not_null not_arr_null)\n    qed\n\n    lemma join_expansion:\n    assumes \"t \\<frown> u\"\n    shows \"t \\<squnion> u = t \\<cdot> (u \\\\ t)\" and \"seq t (u \\\\ t)\"\n    proof -\n      show \"t \\<squnion> u = t \\<cdot> (u \\\\ t)\"\n        by (metis assms comp_is_composite_of(2) has_joins join_is_join_of join_of_def)\n      thus \"seq t (u \\\\ t)\"\n        by (meson assms composable_def composable_iff_seq has_joins join_is_join_of join_of_def)\n    qed\n\n    lemma join3_expansion:\n    assumes \"t \\<frown> u\" and \"t \\<frown> v\" and \"u \\<frown> v\"\n    shows \"(t \\<squnion> u) \\<squnion> v = (t \\<cdot> (u \\\\ t)) \\<cdot> ((v \\\\ t) \\\\ (u \\\\ t))\"\n    proof (cases \"v \\\\ t \\<frown> u \\\\ t\")\n      show \"\\<not> v \\\\ t \\<frown> u \\\\ t \\<Longrightarrow> ?thesis\"\n        by (metis assms(1) comp_null(2) join_expansion(1) joinable_implies_con\n            resid_comp(1) join_def conI)\n      assume 1: \"v \\\\ t \\<frown> u \\\\ t \"\n      have \"(t \\<squnion> u) \\<squnion> v = (t \\<squnion> u) \\<cdot> (v \\\\ (t \\<squnion> u))\"\n        by (metis comp_null(1) diamond_commutes ex_un_null join_expansion(1)\n            joinable_implies_con null_is_zero(2) join_def conI)\n      also have \"... = (t \\<cdot> (u \\\\ t)) \\<cdot> (v \\\\ (t \\<squnion> u))\"\n        using join_expansion [of t u] assms(1) by presburger\n      also have \"... = (t \\<cdot> (u \\\\ t)) \\<cdot> ((v \\\\ u) \\\\ (t \\\\ u))\"\n        using assms 1 join_of_resid(1) [of t u v] cube [of v t u]\n        by (metis con_compI(2) con_implies_arr(2) join_expansion(1) not_arr_null resid_comp(1)\n            con_sym comp_def src_resid arr_comp\\<^sub>E\\<^sub>C)\n      also have \"... = (t \\<cdot> (u \\\\ t)) \\<cdot> ((v \\\\ t) \\\\ (u \\\\ t))\"\n        by (metis cube)\n      finally show ?thesis by blast\n    qed\n\n    lemma resid_common_prefix:\n    assumes \"t \\<cdot> u \\<frown> t \\<cdot> v\"\n    shows \"(t \\<cdot> u) \\\\ (t \\<cdot> v) = u \\\\ v\"\n      using assms\n      by (metis con_comp_iff con_sym con_comp_iff\\<^sub>E\\<^sub>C(2) con_implies_arr(2) induced_arrow(1)\n          resid_comp(1) resid_comp(2) residuation.arr_resid_iff_con residuation_axioms)\n\n  end\n\n  subsection \"Confluence\"\n\n  text \\<open>\n    An RTS is \\emph{confluent} if every coinitial pair of transitions is consistent.\n  \\<close>\n  \n  locale confluent_rts = rts +\n  assumes confluence: \"coinitial t u \\<Longrightarrow> con t u\"\n\n  section \"Simulations\"\n\n  text \\<open>\n    \\emph{Simulations} are morphisms of residuated transition systems.\n    They are assumed to preserve consistency and residuation.\n  \\<close>\n\n  locale simulation =\n    A: rts A +\n    B: rts B\n  for A :: \"'a resid\"      (infixr \"\\\\\\<^sub>A\" 70)\n  and B :: \"'b resid\"      (infixr \"\\\\\\<^sub>B\" 70)\n  and F :: \"'a \\<Rightarrow> 'b\" +\n  assumes extensional: \"\\<not> A.arr t \\<Longrightarrow> F t = B.null\"\n  and preserves_con [simp]: \"A.con t u \\<Longrightarrow> B.con (F t) (F u)\"\n  and preserves_resid [simp]: \"A.con t u \\<Longrightarrow> F (t \\\\\\<^sub>A u) = F t \\\\\\<^sub>B F u\"\n  begin\n\n    lemma preserves_reflects_arr [iff]:\n    shows \"B.arr (F t) \\<longleftrightarrow> A.arr t\"\n      by (metis A.arr_def B.con_implies_arr(2) B.not_arr_null extensional preserves_con)\n\n    lemma preserves_ide [simp]:\n    assumes \"A.ide a\"\n    shows \"B.ide (F a)\"\n      by (metis A.ideE assms preserves_con preserves_resid B.ideI)\n\n    lemma preserves_sources:\n    shows \"F ` A.sources t \\<subseteq> B.sources (F t)\"\n      using A.sources_def B.sources_def preserves_con preserves_ide by auto\n\n    lemma preserves_targets:\n    shows \"F ` A.targets t \\<subseteq> B.targets (F t)\"\n      by (metis A.arrE B.arrE A.sources_resid B.sources_resid equals0D image_subset_iff\n          A.arr_iff_has_target preserves_reflects_arr preserves_resid preserves_sources)\n\n    lemma preserves_trg:\n    assumes \"A.arr t\"\n    shows \"F (A.trg t) = B.trg (F t)\"\n      using assms A.trg_def B.trg_def by auto\n\n    lemma preserves_composites:\n    assumes \"A.composite_of t u v\"\n    shows \"B.composite_of (F t) (F u) (F v)\"\n      using assms\n      by (metis A.composite_ofE A.prfx_implies_con B.composite_of_def preserves_ide\n          preserves_resid A.con_sym)\n\n    lemma preserves_joins:\n    assumes \"A.join_of t u v\"\n    shows \"B.join_of (F t) (F u) (F v)\"\n      using assms A.join_of_def B.join_of_def A.joinable_def\n      by (metis A.joinable_implies_con preserves_composites preserves_resid)\n\n    lemma preserves_prfx:\n    assumes \"A.prfx t u\"\n    shows \"B.prfx (F t) (F u)\"\n      using assms\n      by (metis A.prfx_implies_con preserves_ide preserves_resid)\n\n    lemma preserves_cong:\n    assumes \"A.cong t u\"\n    shows \"B.cong (F t) (F u)\"\n      using assms preserves_prfx by simp\n\n  end\n\n  subsection \"Identity Simulation\"\n\n  locale identity_simulation =\n    rts\n  begin\n\n    abbreviation map\n    where \"map \\<equiv> \\<lambda>t. if arr t then t else null\"\n\n    sublocale simulation resid resid map\n      using con_implies_arr con_sym arr_resid_iff_con\n      by unfold_locales auto\n\n  end\n\n  subsection \"Composite of Simulations\"\n\n  lemma simulation_comp:\n  assumes \"simulation A B F\" and \"simulation B C G\"\n  shows \"simulation A C (G o F)\"\n  proof -\n    interpret F: simulation A B F using assms(1) by auto\n    interpret G: simulation B C G using assms(2) by auto\n    show \"simulation A C (G o F)\"\n      using F.extensional G.extensional by unfold_locales auto\n  qed\n\n  locale composite_simulation =\n    F: simulation A B F +\n    G: simulation B C G\n  for A :: \"'a resid\"\n  and B :: \"'b resid\"\n  and C :: \"'c resid\"\n  and F :: \"'a \\<Rightarrow> 'b\"\n  and G :: \"'b \\<Rightarrow> 'c\"\n  begin\n\n    abbreviation map\n    where \"map \\<equiv> G o F\"\n\n    sublocale simulation A C map\n      using simulation_comp F.simulation_axioms G.simulation_axioms by blast\n\n    lemma is_simulation:\n    shows \"simulation A C map\"\n      ..\n\n  end\n\n  subsection \"Simulations into a Weakly Extensional RTS\"\n\n  locale simulation_to_weakly_extensional_rts =\n    simulation +\n    B: weakly_extensional_rts B\n  begin\n\n    lemma preserves_src:\n    shows \"a \\<in> A.sources t \\<Longrightarrow> B.src (F t) = F a\"\n      by (metis equals0D image_subset_iff B.arr_iff_has_source\n          preserves_sources B.arr_has_un_source B.src_in_sources)\n\n    lemma preserves_trg:\n    shows \"b \\<in> A.targets t \\<Longrightarrow> B.trg (F t) = F b\"\n      by (metis equals0D image_subset_iff B.arr_iff_has_target\n          preserves_targets B.arr_has_un_target B.trg_in_targets)\n\n  end\n\n  subsection \"Simulations into an Extensional RTS\"\n\n  locale simulation_to_extensional_rts =\n    simulation +\n    B: extensional_rts B\n  begin\n\n    lemma preserves_comp:\n    assumes \"A.composite_of t u v\"\n    shows \"F v = B.comp (F t) (F u)\"\n      using assms\n      by (metis preserves_composites B.comp_is_composite_of(2))\n\n    lemma preserves_join:\n    assumes \"A.join_of t u v\"\n    shows \"F v = B.join (F t) (F u)\"\n      using assms preserves_joins\n      by (meson B.join_is_join_of B.join_of_unique B.joinable_def)\n\n  end\n\n  subsection \"Simulations between Extensional RTS's\"\n\n  locale simulation_between_extensional_rts =\n    simulation_to_extensional_rts +\n    A: extensional_rts A\n  begin\n\n    lemma preserves_src:\n    shows \"B.src (F t) = F (A.src t)\"\n      by (metis A.arr_src_iff_arr A.src_in_sources extensional image_subset_iff\n          preserves_reflects_arr preserves_sources B.arr_has_un_source B.src_def\n          B.src_in_sources)\n\n    lemma preserves_trg:\n    shows \"B.trg (F t) = F (A.trg t)\"\n      by (metis A.arr_trg_iff_arr A.residuation_axioms A.trg_def B.null_is_zero(2) B.trg_def\n          extensional preserves_resid residuation.arrE)\n\n    lemma preserves_comp:\n    assumes \"A.composable t u\"\n    shows \"F (A.comp t u) = B.comp (F t) (F u)\"\n      using assms\n      by (metis A.arr_comp A.comp_resid_prfx A.composableD(2) A.not_arr_null\n          A.prfx_comp A.residuation_axioms B.comp_eqI preserves_prfx preserves_resid\n          residuation.conI)\n\n    lemma preserves_join:\n    assumes \"A.joinable t u\"\n    shows \"F (A.join t u) = B.join (F t) (F u)\"\n      using assms\n      by (meson A.join_is_join_of B.joinable_def preserves_joins B.join_is_join_of\n          B.join_of_unique)\n\n  end\n\n  subsection \"Transformations\"\n\n  text \\<open>\n    A \\emph{transformation} is a morphism of simulations, analogously to how a natural\n    transformation is a morphism of functors, except the normal commutativity\n    condition for that ``naturality squares'' is replaced by the requirement that\n    the arrows at the apex of such a square are given by residuation of the\n    arrows at the base.  If the codomain RTS is extensional, then this\n    condition implies the commutativity of the square with respect to composition,\n    as would be the case for a natural transformation between functors.\n\n    The proper way to define a transformation when the domain and codomain are\n    general RTS's is not yet clear to me.  However, if the domain and codomain are\n    weakly extensional, then we have unique sources and targets, so there is no problem.\n    The definition below is limited to that case.  I do not make any attempt here\n    to develop facts about transformations.  My main reason for including this\n    definition here is so that in the subsequent application to the \\<open>\\<lambda>\\<close>-calculus,\n    I can exhibit \\<open>\\<beta>\\<close>-reduction as an example of a transformation.\n  \\<close>\n\n  locale transformation =\n    A: weakly_extensional_rts A +\n    B: weakly_extensional_rts B +\n    F: simulation A B F +\n    G: simulation A B G\n  for A :: \"'a resid\"      (infixr \"\\\\\\<^sub>A\" 70)\n  and B :: \"'b resid\"      (infixr \"\\\\\\<^sub>B\" 70)\n  and F :: \"'a \\<Rightarrow> 'b\"\n  and G :: \"'a \\<Rightarrow> 'b\"\n  and \\<tau> :: \"'a \\<Rightarrow> 'b\" +\n  assumes extensional: \"\\<not> A.arr f \\<Longrightarrow> \\<tau> f = B.null\"\n  and preserves_src: \"A.ide f \\<Longrightarrow> B.src (\\<tau> f) = F (A.src f)\"\n  and preserves_trg: \"A.ide f \\<Longrightarrow> B.trg (\\<tau> f) = G (A.trg f)\"\n  and naturality1: \"A.arr f \\<Longrightarrow> \\<tau> (A.src f) \\\\\\<^sub>B F f = \\<tau> (A.trg f)\"\n  and naturality2: \"A.arr f \\<Longrightarrow> F f \\\\\\<^sub>B \\<tau> (A.src f) = G f\"\n  and naturality3: \"A.arr f \\<Longrightarrow> B.join_of (\\<tau> (A.src f)) (F f) (\\<tau> f)\"\n\n  section \"Normal Sub-RTS's and Congruence\"\n\n  text \\<open>\n    We now develop a general quotient construction on an RTS.\n    We define a \\emph{normal sub-RTS} of an RTS to be a collection of transitions \\<open>\\<NN>\\<close> having\n    certain ``local'' closure properties.  A normal sub-RTS induces an equivalence\n    relation \\<open>\\<approx>\\<^sub>0\\<close>, which we call \\emph{semi-congruence}, by defining \\<open>t \\<approx>\\<^sub>0 u\\<close> to hold exactly\n    when \\<open>t \\ u\\<close> and \\<open>u \\ t\\<close> are both in \\<open>\\<NN>\\<close>.  This relation generalizes the relation \\<open>\\<sim>\\<close>\n    defined for an arbitrary RTS, in the sense that \\<open>\\<sim>\\<close> is obtained when \\<open>\\<NN>\\<close> consists of\n    all and only the identity transitions.  However, in general the relation \\<open>\\<approx>\\<^sub>0\\<close> is fully\n    substitutive only in the left argument position of residuation; for the right argument position,\n    a somewhat weaker property is satisfied.  We then coarsen \\<open>\\<approx>\\<^sub>0\\<close> to a relation \\<open>\\<approx>\\<close>, by defining\n    \\<open>t \\<approx> u\\<close> to hold exactly when \\<open>t\\<close> and \\<open>u\\<close> can be transported by residuation along transitions\n    in \\<open>\\<NN>\\<close> to a common source, in such a way that the residuals are related by \\<open>\\<approx>\\<^sub>0\\<close>.\n    To obtain full substitutivity of \\<open>\\<approx>\\<close> with respect to residuation, we need to impose an\n    additional condition on \\<open>\\<NN>\\<close>.  This condition, which we call \\emph{coherence},\n    states that transporting a transition \\<open>t\\<close> along parallel transitions \\<open>u\\<close> and \\<open>v\\<close> in \\<open>\\<NN>\\<close> always\n    yields  residuals \\<open>t \\ u\\<close> and \\<open>u \\ t\\<close> that are related by \\<open>\\<approx>\\<^sub>0\\<close>.  We show that, under the\n    assumption of coherence, the relation \\<open>\\<approx>\\<close> is fully substitutive, and the quotient of the\n    original RTS by this relation is an extensional RTS which has the \\<open>\\<NN>\\<close>-connected components of\n    the original RTS as identities.  Although the coherence property has a somewhat \\emph{ad hoc}\n    feel to it, we show that, in the context of the other conditions assumed for \\<open>\\<NN>\\<close>, coherence is\n    in fact equivalent to substitutivity for \\<open>\\<approx>\\<close>.\n  \\<close>\n\n  subsection \"Normal Sub-RTS's\"\n\n  locale normal_sub_rts =\n    R: rts +\n    fixes \\<NN> :: \"'a set\"\n    assumes elements_are_arr: \"t \\<in> \\<NN> \\<Longrightarrow> R.arr t\"\n    and ide_closed: \"R.ide a \\<Longrightarrow> a \\<in> \\<NN>\"\n    and forward_stable: \"\\<lbrakk> u \\<in> \\<NN>; R.coinitial t u \\<rbrakk> \\<Longrightarrow> u \\\\ t \\<in> \\<NN>\"\n    and backward_stable: \"\\<lbrakk> u \\<in> \\<NN>; t \\\\ u \\<in> \\<NN> \\<rbrakk> \\<Longrightarrow> t \\<in> \\<NN>\"\n    and composite_closed_left: \"\\<lbrakk> u \\<in> \\<NN>; R.seq u t \\<rbrakk> \\<Longrightarrow> \\<exists>v. R.composite_of u t v\"\n    and composite_closed_right: \"\\<lbrakk> u \\<in> \\<NN>; R.seq t u \\<rbrakk> \\<Longrightarrow> \\<exists>v. R.composite_of t u v\"\n  begin\n\n    lemma prfx_closed:\n    assumes \"u \\<in> \\<NN>\" and \"R.prfx t u\"\n    shows \"t \\<in> \\<NN>\"\n      using assms backward_stable ide_closed by blast\n\n    lemma composite_closed:\n    assumes \"t \\<in> \\<NN>\" and \"u \\<in> \\<NN>\" and \"R.composite_of t u v\"\n    shows \"v \\<in> \\<NN>\"\n      using assms backward_stable R.composite_of_def prfx_closed by blast\n\n    lemma factor_closed:\n    assumes \"R.composite_of t u v\" and \"v \\<in> \\<NN>\"\n    shows \"t \\<in> \\<NN>\" and \"u \\<in> \\<NN>\"\n       apply (metis assms R.composite_of_def prfx_closed)\n      by (meson assms R.composite_of_def R.con_imp_coinitial forward_stable prfx_closed\n                R.prfx_implies_con)\n\n    lemma resid_along_elem_preserves_con:\n    assumes \"t \\<frown> t'\" and \"R.coinitial t u\" and \"u \\<in> \\<NN>\"\n    shows \"t \\\\ u \\<frown> t' \\\\ u\"\n    proof -\n      have \"R.coinitial (t \\\\ t') (u \\\\ t')\"\n        by (metis assms R.arr_resid_iff_con R.coinitialI R.con_imp_common_source forward_stable\n            elements_are_arr R.con_implies_arr(2) R.sources_resid R.sources_eqI)\n      hence \"t \\\\ t' \\<frown> u \\\\ t'\"\n        by (metis assms(3) R.coinitial_iff R.con_imp_coinitial R.con_sym elements_are_arr\n                  forward_stable R.arr_resid_iff_con)\n      thus ?thesis\n        using assms R.cube forward_stable by fastforce\n    qed\n\n  end\n\n  subsubsection \"Normal Sub-RTS's of an Extensional RTS with Composites\"\n\n  locale normal_in_extensional_rts_with_composites =\n     R: extensional_rts +\n     R: rts_with_composites +\n     normal_sub_rts\n  begin\n\n    lemma factor_closed\\<^sub>E\\<^sub>C:\n    assumes \"t \\<cdot> u \\<in> \\<NN>\"\n    shows \"t \\<in> \\<NN>\" and \"u \\<in> \\<NN>\"\n      using assms factor_closed\n      by (metis R.arrE R.composable_def R.comp_is_composite_of(2) R.con_comp_iff\n                elements_are_arr)+\n\n    lemma comp_in_normal_iff:\n    shows \"t \\<cdot> u \\<in> \\<NN> \\<longleftrightarrow> t \\<in> \\<NN> \\<and> u \\<in> \\<NN> \\<and> R.seq t u\"\n      by (metis R.comp_is_composite_of(2) composite_closed elements_are_arr\n          factor_closed(1-2) R.composable_def R.has_composites R.rts_with_composites_axioms\n          R.extensional_rts_axioms extensional_rts_with_composites.arr_compE\\<^sub>E\\<^sub>C\n          extensional_rts_with_composites_def R.seqI\\<^sub>W\\<^sub>E)\n\n  end\n\n  subsection \"Semi-Congruence\"\n\n  context normal_sub_rts\n  begin\n\n    text \\<open>\n      We will refer to the elements of \\<open>\\<NN>\\<close> as \\emph{normal transitions}.\n      Generalizing identity transitions to normal transitions in the definition of congruence,\n      we obtain the notion of \\emph{semi-congruence} of transitions with respect to a\n      normal sub-RTS.\n    \\<close>\n\n    abbreviation Cong\\<^sub>0  (infix \"\\<approx>\\<^sub>0\" 50)\n    where \"t \\<approx>\\<^sub>0 t' \\<equiv> t \\\\ t' \\<in> \\<NN> \\<and> t' \\\\ t \\<in> \\<NN>\"\n\n    lemma Cong\\<^sub>0_reflexive:\n    assumes \"R.arr t\"\n    shows \"t \\<approx>\\<^sub>0 t\"\n      using assms R.cong_reflexive ide_closed by simp\n\n    lemma Cong\\<^sub>0_symmetric:\n    assumes \"t \\<approx>\\<^sub>0 t'\"\n    shows \"t' \\<approx>\\<^sub>0 t\"\n      using assms by simp\n\n    lemma Cong\\<^sub>0_transitive [trans]:\n    assumes \"t \\<approx>\\<^sub>0 t'\" and \"t' \\<approx>\\<^sub>0 t''\"\n    shows \"t \\<approx>\\<^sub>0 t''\"\n      by (metis (full_types) R.arr_resid_iff_con assms backward_stable forward_stable\n          elements_are_arr R.coinitialI R.cube R.sources_resid)\n\n    lemma Cong\\<^sub>0_imp_con:\n    assumes \"t \\<approx>\\<^sub>0 t'\"\n    shows \"R.con t t'\"\n      using assms R.arr_resid_iff_con elements_are_arr by blast\n\n    lemma Cong\\<^sub>0_imp_coinitial:\n    assumes \"t \\<approx>\\<^sub>0 t'\"\n    shows \"R.sources t = R.sources t'\"\n      using assms by (meson Cong\\<^sub>0_imp_con R.coinitial_iff R.con_imp_coinitial)\n\n    text \\<open>\n      Semi-congruence is preserved and reflected by residuation along normal transitions.\n    \\<close>\n\n    lemma Resid_along_normal_preserves_Cong\\<^sub>0:\n    assumes \"t \\<approx>\\<^sub>0 t'\" and \"u \\<in> \\<NN>\" and \"R.sources t = R.sources u\" \n    shows \"t \\\\ u \\<approx>\\<^sub>0 t' \\\\ u\"\n      by (metis Cong\\<^sub>0_imp_coinitial R.arr_resid_iff_con R.coinitialI R.coinitial_def\n          R.cube R.sources_resid assms elements_are_arr forward_stable)\n\n    lemma Resid_along_normal_reflects_Cong\\<^sub>0:\n    assumes \"t \\\\ u \\<approx>\\<^sub>0 t' \\\\ u\" and \"u \\<in> \\<NN>\"\n    shows \"t \\<approx>\\<^sub>0 t'\"\n      using assms\n      by (metis backward_stable R.con_imp_coinitial R.cube R.null_is_zero(2)\n                forward_stable R.conI)\n\n    text \\<open>\n      Semi-congruence is substitutive for the left-hand argument of residuation.\n    \\<close>\n\n    lemma Cong\\<^sub>0_subst_left:\n    assumes \"t \\<approx>\\<^sub>0 t'\" and \"t \\<frown> u\"\n    shows \"t' \\<frown> u\" and \"t \\\\ u \\<approx>\\<^sub>0 t' \\\\ u\"\n    proof -\n      have 1: \"t \\<frown> u \\<and> t \\<frown> t' \\<and> u \\\\ t \\<frown> t' \\\\ t\"\n        using assms\n        by (metis Resid_along_normal_preserves_Cong\\<^sub>0 Cong\\<^sub>0_imp_con Cong\\<^sub>0_reflexive R.con_sym\n                  R.null_is_zero(2) R.arr_resid_iff_con R.sources_resid R.conI)\n      hence 2: \"t' \\<frown> u \\<and> u \\\\ t \\<frown> t' \\\\ t \\<and>\n                (t \\\\ u) \\\\ (t' \\\\ u) = (t \\\\ t') \\\\ (u \\\\ t') \\<and>\n                (t' \\\\ u) \\\\ (t \\\\ u) = (t' \\\\ t) \\\\ (u \\\\ t)\"\n        by (meson R.con_sym R.cube R.resid_reflects_con)\n      show \"t' \\<frown> u\"\n        using 2 by simp\n      show \"t \\\\ u \\<approx>\\<^sub>0 t' \\\\ u\"\n        using assms 1 2\n        by (metis R.arr_resid_iff_con R.con_imp_coinitial R.cube forward_stable)\n    qed\n\n    text \\<open>\n      Semi-congruence is not exactly substitutive for residuation on the right.\n      Instead, the following weaker property is satisfied.  Obtaining exact substitutivity\n      on the right is the motivation for defining a coarser notion of congruence below.\n    \\<close>\n\n    lemma Cong\\<^sub>0_subst_right:\n    assumes \"u \\<approx>\\<^sub>0 u'\" and \"t \\<frown> u\"\n    shows \"t \\<frown> u'\" and \"(t \\\\ u) \\\\ (u' \\\\ u) \\<approx>\\<^sub>0 (t \\\\ u') \\\\ (u \\\\ u')\"\n      using assms\n       apply (meson Cong\\<^sub>0_subst_left(1) R.con_sym)\n      using assms\n      by (metis R.sources_resid Cong\\<^sub>0_imp_con Cong\\<^sub>0_reflexive Resid_along_normal_preserves_Cong\\<^sub>0\n                R.arr_resid_iff_con residuation.cube R.residuation_axioms)\n\n    lemma Cong\\<^sub>0_subst_Con:\n    assumes \"t \\<approx>\\<^sub>0 t'\" and \"u \\<approx>\\<^sub>0 u'\"\n    shows \"t \\<frown> u \\<longleftrightarrow> t' \\<frown> u'\"\n      using assms\n      by (meson Cong\\<^sub>0_subst_left(1) Cong\\<^sub>0_subst_right(1))\n\n    lemma Cong\\<^sub>0_cancel_left:\n    assumes \"R.composite_of t u v\" and \"R.composite_of t u' v'\" and \"v \\<approx>\\<^sub>0 v'\"\n    shows \"u \\<approx>\\<^sub>0 u'\"\n    proof -\n      have \"u \\<approx>\\<^sub>0 v \\\\ t\"\n        using assms(1) ide_closed by blast\n      also have \"v \\\\ t \\<approx>\\<^sub>0 v' \\\\ t\"\n        by (meson assms(1,3) Cong\\<^sub>0_subst_left(2) R.composite_of_def R.con_sym R.prfx_implies_con)\n      also have \"v' \\\\ t \\<approx>\\<^sub>0 u'\"\n        using assms(2) ide_closed by blast\n      finally show ?thesis by auto\n    qed\n\n    lemma Cong\\<^sub>0_iff:\n    shows \"t \\<approx>\\<^sub>0 t' \\<longleftrightarrow>\n           (\\<exists>u u' v v'. u \\<in> \\<NN> \\<and> u' \\<in> \\<NN> \\<and> v \\<approx>\\<^sub>0 v' \\<and>\n                        R.composite_of t u v \\<and> R.composite_of t' u' v')\"\n    proof (intro iffI)\n      show \"\\<exists>u u' v v'. u \\<in> \\<NN> \\<and> u' \\<in> \\<NN> \\<and> v \\<approx>\\<^sub>0 v' \\<and>\n                        R.composite_of t u v \\<and> R.composite_of t' u' v'\n               \\<Longrightarrow> t \\<approx>\\<^sub>0 t'\"\n        by (meson Cong\\<^sub>0_transitive R.composite_of_def ide_closed prfx_closed)\n      show \"t \\<approx>\\<^sub>0 t' \\<Longrightarrow> \\<exists>u u' v v'. u \\<in> \\<NN> \\<and> u' \\<in> \\<NN> \\<and> v \\<approx>\\<^sub>0 v' \\<and>\n                                    R.composite_of t u v \\<and> R.composite_of t' u' v'\"\n        by (metis Cong\\<^sub>0_imp_con Cong\\<^sub>0_transitive R.composite_of_def R.prfx_reflexive\n            R.arrI R.ideE)\n    qed\n\n    lemma diamond_commutes_upto_Cong\\<^sub>0:\n    assumes \"t \\<frown> u\" and \"R.composite_of t (u \\\\ t) v\" and \"R.composite_of u (t \\\\ u) v'\"\n    shows \"v \\<approx>\\<^sub>0 v'\"\n    proof -\n      have \"v \\\\ v \\<approx>\\<^sub>0 v' \\\\ v \\<and> v' \\\\ v' \\<approx>\\<^sub>0 v \\\\ v'\"\n      proof-\n        have 1: \"(v \\\\ t) \\\\ (u \\\\ t) \\<approx>\\<^sub>0 (v' \\\\ u) \\\\ (t \\\\ u)\"\n          using assms(2-3) R.cube [of v t u]\n          by (metis R.con_target R.composite_ofE R.ide_imp_con_iff_cong ide_closed\n              R.conI)\n        have 2: \"v \\\\ v \\<approx>\\<^sub>0 v' \\\\ v\"\n        proof -\n          have \"v \\\\ v \\<approx>\\<^sub>0 (v \\\\ t) \\\\ (u \\\\ t)\"\n            using assms R.composite_of_def ide_closed\n            by (meson R.composite_of_unq_upto_cong R.prfx_implies_con R.resid_composite_of(3))\n          also have \"(v \\\\ t) \\\\ (u \\\\ t) \\<approx>\\<^sub>0 (v' \\\\ u) \\\\ (t \\\\ u)\"\n            using 1 by simp\n          also have \"(v' \\\\ u) \\\\ (t \\\\ u) \\<approx>\\<^sub>0 (v' \\\\ t) \\\\ (u \\\\ t)\"\n            by (metis \"1\" Cong\\<^sub>0_transitive R.cube)\n          also have \"(v' \\\\ t) \\\\ (u \\\\ t) \\<approx>\\<^sub>0 v' \\\\ v\"\n            using assms R.composite_of_def ide_closed\n            by (metis \"1\" R.conI R.con_sym_ax R.cube R.null_is_zero(2) R.resid_composite_of(3))\n          finally show ?thesis by auto\n        qed\n        moreover have \"v' \\\\ v' \\<approx>\\<^sub>0 v \\\\ v'\"\n        proof -\n          have \"v' \\\\ v' \\<approx>\\<^sub>0 (v' \\\\ u) \\\\ (t \\\\ u)\"\n            using assms R.composite_of_def ide_closed\n            by (meson R.composite_of_unq_upto_cong R.prfx_implies_con R.resid_composite_of(3))\n          also have \"(v' \\\\ u) \\\\ (t \\\\ u) \\<approx>\\<^sub>0 (v \\\\ t) \\\\ (u \\\\ t)\"\n            using 1 by simp\n          also have \"(v \\\\ t) \\\\ (u \\\\ t) \\<approx>\\<^sub>0 (v \\\\ u) \\\\ (t \\\\ u)\"\n            using R.cube [of v t u] ide_closed\n            by (metis Cong\\<^sub>0_reflexive R.arr_resid_iff_con assms(2) R.composite_of_def\n                      R.prfx_implies_con)\n          also have \"(v \\\\ u) \\\\ (t \\\\ u) \\<approx>\\<^sub>0 v \\\\ v'\"\n            using assms R.composite_of_def ide_closed\n            by (metis 2 R.conI elements_are_arr R.not_arr_null R.null_is_zero(2)\n                R.resid_composite_of(3))\n          finally show ?thesis by auto\n        qed\n        ultimately show ?thesis by blast\n      qed\n      thus ?thesis\n        by (metis assms(2-3) R.composite_of_unq_upto_cong R.resid_arr_ide Cong\\<^sub>0_imp_con)\n    qed\n\n    subsection \"Congruence\"\n\n    text \\<open>\n      We use semi-congruence to define a coarser relation as follows.\n    \\<close>\n\n    definition Cong  (infix \"\\<approx>\" 50)\n    where \"Cong t t' \\<equiv> \\<exists>u u'. u \\<in> \\<NN> \\<and> u' \\<in> \\<NN> \\<and> t \\\\ u \\<approx>\\<^sub>0 t' \\\\ u'\"\n\n    lemma CongI [intro]:\n    assumes \"u \\<in> \\<NN>\" and \"u' \\<in> \\<NN>\" and \"t \\\\ u \\<approx>\\<^sub>0 t' \\\\ u'\"\n    shows \"Cong t t'\"\n      using assms Cong_def by auto\n\n    lemma CongE [elim]:\n    assumes \"t \\<approx> t'\"\n    obtains u u'\n    where \"u \\<in> \\<NN>\" and \"u' \\<in> \\<NN>\" and \"t \\\\ u \\<approx>\\<^sub>0 t' \\\\ u'\"\n      using assms Cong_def by auto\n\n    lemma Cong_imp_arr:\n    assumes \"t \\<approx> t'\"\n    shows \"R.arr t\" and \"R.arr t'\"\n      using assms Cong_def\n      by (meson R.arr_resid_iff_con R.con_implies_arr(2) R.con_sym elements_are_arr)+\n\n    lemma Cong_reflexive:\n    assumes \"R.arr t\"\n    shows \"t \\<approx> t\"\n      by (metis CongI Cong\\<^sub>0_reflexive assms R.con_imp_coinitial_ax ide_closed\n          R.resid_arr_ide R.arrE R.con_sym)\n\n    lemma Cong_symmetric:\n    assumes \"t \\<approx> t'\"\n    shows \"t' \\<approx> t\"\n      using assms Cong_def by auto\n\n    text \\<open>\n      The existence of composites of normal transitions is used in the following.\n    \\<close>\n\n    lemma Cong_transitive [trans]:\n    assumes \"t \\<approx> t''\" and \"t'' \\<approx> t'\"\n    shows \"t \\<approx> t'\"\n    proof -\n      obtain u u'' where uu'': \"u \\<in> \\<NN> \\<and> u'' \\<in> \\<NN> \\<and> t \\\\ u \\<approx>\\<^sub>0 t'' \\\\ u''\"\n        using assms Cong_def by blast\n      obtain v' v'' where v'v'': \"v' \\<in> \\<NN> \\<and> v'' \\<in> \\<NN> \\<and> t'' \\\\ v'' \\<approx>\\<^sub>0 t' \\\\ v'\"\n        using assms Cong_def by blast\n      let ?w = \"(t \\\\ u) \\\\ (v'' \\\\ u'')\"\n      let ?w' = \"(t' \\\\ v') \\\\ (u'' \\\\ v'')\"\n      let ?w'' = \"(t'' \\\\ v'') \\\\ (u'' \\\\ v'')\"\n      have w'': \"?w'' = (t'' \\\\ u'') \\\\ (v'' \\\\ u'')\"\n        by (metis R.cube)\n      have u''v'': \"R.coinitial u'' v''\"\n        by (metis (full_types) R.coinitial_iff elements_are_arr R.con_imp_coinitial\n            R.arr_resid_iff_con uu'' v'v'')\n      hence v''u'': \"R.coinitial v'' u''\"\n        by (meson R.con_imp_coinitial elements_are_arr forward_stable R.arr_resid_iff_con v'v'')\n      have 1: \"?w \\\\ ?w'' \\<in> \\<NN>\"\n      proof -\n        have \"(v'' \\\\ u'') \\\\ (t'' \\\\ u'') \\<in> \\<NN>\"\n          by (metis Cong\\<^sub>0_transitive R.con_imp_coinitial forward_stable Cong\\<^sub>0_imp_con\n              resid_along_elem_preserves_con R.arrI R.arr_resid_iff_con u''v'' uu'' v'v'')\n        thus ?thesis\n          by (metis Cong\\<^sub>0_subst_left(2) R.con_sym R.null_is_zero(1) uu'' w'' R.conI)\n      qed\n      have 2: \"?w'' \\\\ ?w \\<in> \\<NN>\"\n        by (metis 1 Cong\\<^sub>0_subst_left(2) uu'' w'' R.conI)\n      have 3: \"R.seq u (v'' \\\\ u'')\"\n        by (metis (full_types) 2 Cong\\<^sub>0_imp_coinitial R.sources_resid\n            Cong\\<^sub>0_imp_con R.arr_resid_iff_con R.con_implies_arr(2) R.seqI uu'' R.conI)\n      have 4: \"R.seq v' (u'' \\\\ v'')\"\n        by (metis 1 Cong\\<^sub>0_imp_coinitial Cong\\<^sub>0_imp_con R.arr_resid_iff_con\n            R.con_implies_arr(2) R.seq_def R.sources_resid v'v'' R.conI)\n      obtain x where x: \"R.composite_of u (v'' \\\\ u'') x\"\n        using 3 composite_closed_left uu'' by blast\n      obtain x' where x': \"R.composite_of v' (u'' \\\\ v'') x'\"\n        using 4 composite_closed_left v'v'' by presburger\n      have \"?w \\<approx>\\<^sub>0 ?w'\"\n      proof -\n        have \"?w \\<approx>\\<^sub>0 ?w'' \\<and> ?w' \\<approx>\\<^sub>0 ?w''\"\n          using 1 2\n          by (metis Cong\\<^sub>0_subst_left(2) R.null_is_zero(2) v'v'' R.conI)\n        thus ?thesis\n          using Cong\\<^sub>0_transitive by blast\n      qed\n      moreover have \"x \\<in> \\<NN> \\<and> ?w \\<approx>\\<^sub>0 t \\\\ x\"\n        apply (intro conjI)\n          apply (meson composite_closed forward_stable u''v'' uu'' v'v'' x)\n         apply (metis (full_types) R.arr_resid_iff_con R.con_implies_arr(2) R.con_sym\n            ide_closed forward_stable R.composite_of_def R.resid_composite_of(3)\n            Cong\\<^sub>0_subst_right(1) prfx_closed u''v'' uu'' v'v'' x R.conI)\n        by (metis (no_types, lifting) 1 R.con_composite_of_iff ide_closed \n            R.resid_composite_of(3) R.arr_resid_iff_con R.con_implies_arr(1) R.con_sym x R.conI)\n      moreover have \"x' \\<in> \\<NN> \\<and> ?w' \\<approx>\\<^sub>0 t' \\\\ x'\"\n        apply (intro conjI)\n          apply (meson composite_closed forward_stable uu'' v''u'' v'v'' x')\n         apply (metis (full_types) Cong\\<^sub>0_subst_right(1) R.composite_ofE R.con_sym\n            ide_closed forward_stable R.con_imp_coinitial prfx_closed\n            R.resid_composite_of(3) R.arr_resid_iff_con R.con_implies_arr(1) uu'' v'v'' x' R.conI)\n        by (metis (full_types) Cong\\<^sub>0_subst_left(1) R.composite_ofE R.con_sym ide_closed\n            forward_stable R.con_imp_coinitial prfx_closed R.resid_composite_of(3)\n            R.arr_resid_iff_con R.con_implies_arr(1) uu'' v'v'' x' R.conI)\n      ultimately show \"t \\<approx> t'\"\n        using Cong_def Cong\\<^sub>0_transitive by metis\n    qed\n\n    lemma Cong_closure_props:\n    shows \"t \\<approx> u \\<Longrightarrow> u \\<approx> t\"\n    and \"\\<lbrakk>t \\<approx> u; u \\<approx> v\\<rbrakk> \\<Longrightarrow> t \\<approx> v\"\n    and \"t \\<approx>\\<^sub>0 u \\<Longrightarrow> t \\<approx> u\"\n    and \"\\<lbrakk>u \\<in> \\<NN>; R.sources t = R.sources u\\<rbrakk> \\<Longrightarrow> t \\<approx> t \\\\ u\"\n    proof -\n      show \"t \\<approx> u \\<Longrightarrow> u \\<approx> t\"\n        using Cong_symmetric by blast\n      show \"\\<lbrakk>t \\<approx> u; u \\<approx> v\\<rbrakk> \\<Longrightarrow> t \\<approx> v\"\n        using Cong_transitive by blast\n      show \"t \\<approx>\\<^sub>0 u \\<Longrightarrow> t \\<approx> u\"\n        by (metis Cong\\<^sub>0_subst_left(2) Cong_def Cong_reflexive R.con_implies_arr(1)\n            R.null_is_zero(2) R.conI)\n      show \"\\<lbrakk>u \\<in> \\<NN>; R.sources t = R.sources u\\<rbrakk> \\<Longrightarrow> t \\<approx> t \\\\ u\"\n      proof -\n        assume u: \"u \\<in> \\<NN>\" and coinitial: \"R.sources t = R.sources u\"\n        obtain a where a: \"a \\<in> R.targets u\"\n          by (meson elements_are_arr empty_subsetI R.arr_iff_has_target subsetI subset_antisym u)\n        have \"t \\\\ u \\<approx>\\<^sub>0 (t \\\\ u) \\\\ a\"\n        proof -\n          have \"R.arr t\"\n            using R.arr_iff_has_source coinitial elements_are_arr u by presburger\n          thus ?thesis\n            by (meson u a R.arr_resid_iff_con coinitial ide_closed forward_stable\n                elements_are_arr R.coinitial_iff R.composite_of_arr_target R.resid_composite_of(3))\n        qed\n        thus ?thesis\n          using Cong_def\n          by (metis a R.composite_of_arr_target elements_are_arr factor_closed(2) u)\n      qed\n    qed\n\n    lemma Cong\\<^sub>0_implies_Cong:\n    assumes \"t \\<approx>\\<^sub>0 t'\"\n    shows \"t \\<approx> t'\"\n      using assms Cong_closure_props(3) by simp\n\n    lemma in_sources_respects_Cong:\n    assumes \"t \\<approx> t'\" and \"a \\<in> R.sources t\" and \"a' \\<in> R.sources t'\"\n    shows \"a \\<approx> a'\"\n    proof -\n      obtain u u' where uu': \"u \\<in> \\<NN> \\<and> u' \\<in> \\<NN> \\<and> t \\\\ u \\<approx>\\<^sub>0 t' \\\\ u'\"\n        using assms Cong_def by blast\n      show \"a \\<approx> a'\"\n      proof\n        show \"u \\<in> \\<NN>\"\n          using uu' by simp\n        show \"u' \\<in> \\<NN>\"\n          using uu' by simp\n        show \"a \\\\ u \\<approx>\\<^sub>0 a' \\\\ u'\"\n        proof -\n          have \"a \\\\ u \\<in> R.targets u\"\n            by (metis Cong\\<^sub>0_imp_con R.arr_resid_iff_con assms(2) R.con_imp_common_source\n                R.con_implies_arr(1) R.resid_source_in_targets R.sources_eqI uu')\n          moreover have \"a' \\\\ u' \\<in> R.targets u'\"\n            by (metis Cong\\<^sub>0_imp_con R.arr_resid_iff_con assms(3) R.con_imp_common_source\n                R.resid_source_in_targets R.con_implies_arr(1) R.sources_eqI uu')\n          moreover have \"R.targets u = R.targets u'\"\n            by (metis Cong\\<^sub>0_imp_coinitial Cong\\<^sub>0_imp_con R.arr_resid_iff_con\n                R.con_implies_arr(1) R.sources_resid uu')\n          ultimately show ?thesis\n            using ide_closed R.targets_are_cong by presburger\n        qed\n      qed\n    qed\n\n    lemma in_targets_respects_Cong:\n    assumes \"t \\<approx> t'\" and \"b \\<in> R.targets t\" and \"b' \\<in> R.targets t'\"\n    shows \"b \\<approx> b'\"\n    proof -\n      obtain u u' where uu': \"u \\<in> \\<NN> \\<and> u' \\<in> \\<NN> \\<and> t \\\\ u \\<approx>\\<^sub>0 t' \\\\ u'\"\n        using assms Cong_def by blast\n      have seq: \"R.seq (u \\\\ t) ((t' \\\\ u') \\\\ (t \\\\ u)) \\<and> R.seq (u' \\\\ t') ((t \\\\ u) \\\\ (t' \\\\ u'))\"\n        by (metis R.arr_iff_has_source R.arr_iff_has_target R.conI elements_are_arr R.not_arr_null\n            R.seqI R.sources_resid R.targets_resid_sym uu')\n      obtain v where v: \"R.composite_of (u \\\\ t) ((t' \\\\ u') \\\\ (t \\\\ u)) v\"\n        using seq composite_closed_right uu' by presburger\n      obtain v' where v': \"R.composite_of (u' \\\\ t') ((t \\\\ u) \\\\ (t' \\\\ u')) v'\"\n        using seq composite_closed_right uu' by presburger\n      show \"b \\<approx> b'\"\n      proof\n        show v_in_\\<NN>: \"v \\<in> \\<NN>\"\n          by (metis composite_closed R.con_imp_coinitial R.con_implies_arr(1) forward_stable\n              R.composite_of_def R.prfx_implies_con R.arr_resid_iff_con R.con_sym uu' v)\n        show v'_in_\\<NN>: \"v' \\<in> \\<NN>\"\n          by (metis backward_stable R.composite_of_def R.con_imp_coinitial forward_stable\n              R.null_is_zero(2) prfx_closed uu' v' R.conI)\n        show \"b \\\\ v \\<approx>\\<^sub>0 b' \\\\ v'\"\n          using assms uu' v v'\n          by (metis R.arr_resid_iff_con ide_closed R.seq_def R.sources_resid R.targets_resid_sym\n              R.resid_source_in_targets seq R.sources_composite_of R.targets_are_cong\n              R.targets_composite_of)\n      qed\n    qed\n\n    lemma sources_are_Cong:\n    assumes \"a \\<in> R.sources t\" and \"a' \\<in> R.sources t\"\n    shows \"a \\<approx> a'\"\n      using assms\n      by (simp add: ide_closed R.sources_are_cong Cong_closure_props(3))\n\n    lemma targets_are_Cong:\n    assumes \"b \\<in> R.targets t\" and \"b' \\<in> R.targets t\"\n    shows \"b \\<approx> b'\"\n      using assms\n      by (simp add: ide_closed R.targets_are_cong Cong_closure_props(3))\n\n    text \\<open>\n      It is \\emph{not} the case that sources and targets are \\<open>\\<approx>\\<close>-closed;\n      \\emph{i.e.} \\<open>t \\<approx> t' \\<Longrightarrow> sources t = sources t'\\<close> and \\<open>t \\<approx> t' \\<Longrightarrow> targets t = targets t'\\<close>\n      do not hold, in general.\n    \\<close>\n\n    lemma Resid_along_normal_preserves_reflects_con:\n    assumes \"u \\<in> \\<NN>\" and \"R.sources t = R.sources u\"\n    shows \"t \\\\ u \\<frown> t' \\\\ u \\<longleftrightarrow> t \\<frown> t'\"\n      by (metis R.arr_resid_iff_con assms R.con_implies_arr(1-2) elements_are_arr R.coinitial_iff\n                R.resid_reflects_con resid_along_elem_preserves_con)\n\n    text \\<open>\n      We can alternatively characterize \\<open>\\<approx>\\<close> as the least symmetric and transitive\n      relation on transitions that extends \\<open>\\<approx>\\<^sub>0\\<close> and has the property\n      of being preserved by residuation along transitions in \\<open>\\<NN>\\<close>.\n    \\<close>\n\n    inductive Cong'\n    where \"\\<And>t u. Cong' t u \\<Longrightarrow> Cong' u t\"\n        | \"\\<And>t u v. \\<lbrakk>Cong' t u; Cong' u v\\<rbrakk> \\<Longrightarrow> Cong' t v\"\n        | \"\\<And>t u. t \\<approx>\\<^sub>0 u \\<Longrightarrow> Cong' t u\"\n        | \"\\<And>t u. \\<lbrakk>R.arr t; u \\<in> \\<NN>; R.sources t = R.sources u\\<rbrakk> \\<Longrightarrow> Cong' t (t \\\\ u)\"\n\n    lemma Cong'_if:\n    shows \"\\<lbrakk>u \\<in> \\<NN>; u' \\<in> \\<NN>; t \\\\ u \\<approx>\\<^sub>0 t' \\\\ u'\\<rbrakk> \\<Longrightarrow> Cong' t t'\"\n    proof -\n      assume u: \"u \\<in> \\<NN>\" and u': \"u' \\<in> \\<NN>\" and 1: \"t \\\\ u \\<approx>\\<^sub>0 t' \\\\ u'\"\n      show \"Cong' t t'\"\n        using u u' 1\n        by (metis (no_types, lifting) Cong'.simps Cong\\<^sub>0_imp_con R.arr_resid_iff_con\n            R.coinitial_iff R.con_imp_coinitial)\n    qed\n\n    lemma Cong_char:\n    shows \"Cong t t' \\<longleftrightarrow> Cong' t t'\"\n    proof -\n      have \"Cong t t' \\<Longrightarrow> Cong' t t'\"\n        using Cong_def Cong'_if by blast\n      moreover have \"Cong' t t' \\<Longrightarrow> Cong t t'\"\n        apply (induction rule: Cong'.induct)\n        using Cong_symmetric apply simp\n        using Cong_transitive apply simp\n        using Cong_closure_props(3) apply simp\n        using Cong_closure_props(4) by simp\n      ultimately show ?thesis\n        using Cong_def by blast\n    qed\n\n    lemma normal_is_Cong_closed:\n    assumes \"t \\<in> \\<NN>\" and \"t \\<approx> t'\"\n    shows \"t' \\<in> \\<NN>\"\n      using assms\n      by (metis (full_types) CongE R.con_imp_coinitial forward_stable\n          R.null_is_zero(2) backward_stable R.conI)\n\n    subsection \"Congruence Classes\"\n\n    text \\<open>\n      Here we develop some notions relating to the congruence classes of \\<open>\\<approx>\\<close>.\n    \\<close>\n\n    definition Cong_class (\"\\<lbrace>_\\<rbrace>\")\n    where \"Cong_class t \\<equiv> {t'. t \\<approx> t'}\"\n\n    definition is_Cong_class\n    where \"is_Cong_class \\<T> \\<equiv> \\<exists>t. t \\<in> \\<T> \\<and> \\<T> = \\<lbrace>t\\<rbrace>\"\n\n    definition Cong_class_rep\n    where \"Cong_class_rep \\<T> \\<equiv> SOME t. t \\<in> \\<T>\"\n\n    lemma Cong_class_is_nonempty:\n    assumes \"is_Cong_class \\<T>\"\n    shows \"\\<T> \\<noteq> {}\"\n      using assms is_Cong_class_def Cong_class_def by auto\n\n    lemma rep_in_Cong_class:\n    assumes \"is_Cong_class \\<T>\"\n    shows \"Cong_class_rep \\<T> \\<in> \\<T>\"\n      using assms is_Cong_class_def Cong_class_rep_def someI_ex [of \"\\<lambda>t. t \\<in> \\<T>\"]\n      by metis\n\n    lemma arr_in_Cong_class:\n    assumes \"R.arr t\"\n    shows \"t \\<in> \\<lbrace>t\\<rbrace>\"\n      using assms Cong_class_def Cong_reflexive by simp\n\n    lemma is_Cong_classI:\n    assumes \"R.arr t\"\n    shows \"is_Cong_class \\<lbrace>t\\<rbrace>\"\n      using assms Cong_class_def is_Cong_class_def Cong_reflexive by blast\n\n    lemma is_Cong_classI' [intro]:\n    assumes \"\\<T> \\<noteq> {}\"\n    and \"\\<And>t t'. \\<lbrakk>t \\<in> \\<T>; t' \\<in> \\<T>\\<rbrakk> \\<Longrightarrow> t \\<approx> t'\"\n    and \"\\<And>t t'. \\<lbrakk>t \\<in> \\<T>; t' \\<approx> t\\<rbrakk> \\<Longrightarrow> t' \\<in> \\<T>\"\n    shows \"is_Cong_class \\<T>\"\n    proof -\n      obtain t where t: \"t \\<in> \\<T>\"\n        using assms by auto\n      have \"\\<T> = \\<lbrace>t\\<rbrace>\"\n        unfolding Cong_class_def\n        using assms(2-3) t by blast\n      thus ?thesis\n        using is_Cong_class_def t by blast\n    qed\n\n    lemma Cong_class_memb_is_arr:\n    assumes \"is_Cong_class \\<T>\" and \"t \\<in> \\<T>\"\n    shows \"R.arr t\"\n      using assms Cong_class_def is_Cong_class_def Cong_imp_arr(2) by force\n\n    lemma Cong_class_membs_are_Cong:\n    assumes \"is_Cong_class \\<T>\" and \"t \\<in> \\<T>\" and \"t' \\<in> \\<T>\"\n    shows \"Cong t t'\"\n      using assms Cong_class_def is_Cong_class_def\n      by (metis CollectD Cong_closure_props(2) Cong_symmetric)\n\n    lemma Cong_class_eqI:\n    assumes \"t \\<approx> t'\"\n    shows \"\\<lbrace>t\\<rbrace> = \\<lbrace>t'\\<rbrace>\"\n      using assms Cong_class_def\n      by (metis (full_types) Collect_cong Cong'.intros(1-2) Cong_char)\n\n    lemma Cong_class_eqI':\n    assumes \"is_Cong_class \\<T>\" and \"is_Cong_class \\<U>\" and \"\\<T> \\<inter> \\<U> \\<noteq> {}\"\n    shows \"\\<T> = \\<U>\"\n      using assms is_Cong_class_def Cong_class_eqI Cong_class_membs_are_Cong\n      by (metis (no_types, lifting) Int_emptyI)\n\n    lemma is_Cong_classE [elim]:\n    assumes \"is_Cong_class \\<T>\"\n    and \"\\<lbrakk>\\<T> \\<noteq> {}; \\<And>t t'. \\<lbrakk>t \\<in> \\<T>; t' \\<in> \\<T>\\<rbrakk> \\<Longrightarrow> t \\<approx> t'; \\<And>t t'. \\<lbrakk>t \\<in> \\<T>; t' \\<approx> t\\<rbrakk> \\<Longrightarrow> t' \\<in> \\<T>\\<rbrakk> \\<Longrightarrow> T\"\n    shows T\n    proof -\n      have \\<T>: \"\\<T> \\<noteq> {}\"\n        using assms Cong_class_is_nonempty by simp\n      moreover have 1: \"\\<And>t t'. \\<lbrakk>t \\<in> \\<T>; t' \\<in> \\<T>\\<rbrakk> \\<Longrightarrow> t \\<approx> t'\"\n        using assms Cong_class_membs_are_Cong by metis\n      moreover have \"\\<And>t t'. \\<lbrakk>t \\<in> \\<T>; t' \\<approx> t\\<rbrakk> \\<Longrightarrow> t' \\<in> \\<T>\"\n        using assms Cong_class_def\n        by (metis 1 Cong_class_eqI Cong_imp_arr(1) is_Cong_class_def arr_in_Cong_class)\n      ultimately show ?thesis\n        using assms by blast\n    qed\n\n    lemma Cong_class_rep [simp]:\n    assumes \"is_Cong_class \\<T>\"\n    shows \"\\<lbrace>Cong_class_rep \\<T>\\<rbrace> = \\<T>\"\n      by (metis Cong_class_membs_are_Cong Cong_class_eqI assms is_Cong_class_def rep_in_Cong_class)\n\n    lemma Cong_class_memb_Cong_rep:\n    assumes \"is_Cong_class \\<T>\" and \"t \\<in> \\<T>\"\n    shows \"Cong t (Cong_class_rep \\<T>)\"\n      using assms Cong_class_membs_are_Cong rep_in_Cong_class by simp\n\n    lemma composite_of_normal_arr:\n    shows \"\\<lbrakk> R.arr t; u \\<in> \\<NN>; R.composite_of u t t' \\<rbrakk> \\<Longrightarrow> t' \\<approx> t\"\n      by (meson Cong'.intros(3) Cong_char R.composite_of_def R.con_implies_arr(2)\n                ide_closed R.prfx_implies_con Cong_closure_props(2,4) R.sources_composite_of)\n\n    lemma composite_of_arr_normal:\n    shows \"\\<lbrakk> arr t; u \\<in> \\<NN>; R.composite_of t u t' \\<rbrakk> \\<Longrightarrow> t' \\<approx>\\<^sub>0 t\"\n      by (meson Cong_closure_props(3) R.composite_of_def ide_closed prfx_closed)\n\n  end\n\n  subsection \"Coherent Normal Sub-RTS's\"\n\n  text \\<open>\n    A \\emph{coherent} normal sub-RTS is one that satisfies a parallel moves property with respect\n    to arbitrary transitions.  The congruence \\<open>\\<approx>\\<close> induced by a coherent normal sub-RTS is\n    fully substitutive with respect to consistency and residuation,\n    and in fact coherence is equivalent to substitutivity in this context.\n  \\<close>\n\n  locale coherent_normal_sub_rts = normal_sub_rts +\n    assumes coherent: \"\\<lbrakk> R.arr t; u \\<in> \\<NN>; u' \\<in> \\<NN>; R.sources u = R.sources u';\n                         R.targets u = R.targets u'; R.sources t = R.sources u \\<rbrakk>\n                            \\<Longrightarrow> t \\\\ u \\<approx>\\<^sub>0 t \\\\ u'\"\n\n  (*\n   * TODO: Should coherence be part of normality, or is it an additional property that guarantees\n   * the existence of the quotient?\n   *\n   * e.g. see http://nlab-pages.s3.us-east-2.amazonaws.com/nlab/show/normal+subobject\n   * Maybe also http://www.tac.mta.ca/tac/volumes/36/3/36-03.pdf for recent work.\n   *)\n\n  context normal_sub_rts\n  begin\n\n    text \\<open>\n      The above ``parallel moves'' formulation of coherence is equivalent to the following\n      formulation, which involves ``opposing spans''.\n    \\<close>\n\n    lemma coherent_iff:\n    shows \"(\\<forall>t u u'. R.arr t \\<and> u \\<in> \\<NN> \\<and> u' \\<in> \\<NN> \\<and> R.sources t = R.sources u \\<and>\n                     R.sources u = R.sources u' \\<and> R.targets u = R.targets u'\n                            \\<longrightarrow> t \\\\ u \\<approx>\\<^sub>0 t \\\\ u')\n           \\<longleftrightarrow>\n           (\\<forall>t t' v v' w w'. v \\<in> \\<NN> \\<and> v' \\<in> \\<NN> \\<and> w \\<in> \\<NN> \\<and> w' \\<in> \\<NN> \\<and>\n                             R.sources v = R.sources w \\<and> R.sources v' = R.sources w' \\<and>\n                             R.targets w = R.targets w' \\<and> t \\\\ v \\<approx>\\<^sub>0 t' \\\\ v'\n                                \\<longrightarrow> t \\\\ w \\<approx>\\<^sub>0 t' \\\\ w')\"\n    proof\n      assume 1: \"\\<forall>t t' v v' w w'. v \\<in> \\<NN> \\<and> v' \\<in> \\<NN> \\<and> w \\<in> \\<NN> \\<and> w' \\<in> \\<NN> \\<and>\n                             R.sources v = R.sources w \\<and> R.sources v' = R.sources w' \\<and>\n                             R.targets w = R.targets w' \\<and> t \\\\ v \\<approx>\\<^sub>0 t' \\\\ v'\n                                \\<longrightarrow> t \\\\ w \\<approx>\\<^sub>0 t' \\\\ w'\"\n      show \"\\<forall>t u u'. R.arr t \\<and> u \\<in> \\<NN> \\<and> u' \\<in> \\<NN> \\<and> R.sources t = R.sources u \\<and>\n                     R.sources u = R.sources u' \\<and> R.targets u = R.targets u'\n                            \\<longrightarrow> t \\\\ u \\<approx>\\<^sub>0 t \\\\ u'\"\n      proof (intro allI impI, elim conjE)\n        fix t u u'\n        assume t: \"R.arr t\" and u: \"u \\<in> \\<NN>\" and u': \"u' \\<in> \\<NN>\"\n        and tu: \"R.sources t = R.sources u\" and sources: \"R.sources u = R.sources u'\"\n        and targets: \"R.targets u = R.targets u'\"\n        show \"t \\\\ u \\<approx>\\<^sub>0 t \\\\ u'\"\n          by (metis 1 Cong\\<^sub>0_reflexive Resid_along_normal_preserves_Cong\\<^sub>0 sources t targets\n              tu u u')\n      qed\n      next\n      assume 1: \"\\<forall>t u u'. R.arr t \\<and> u \\<in> \\<NN> \\<and> u' \\<in> \\<NN> \\<and> R.sources t = R.sources u \\<and>\n                     R.sources u = R.sources u' \\<and> R.targets u = R.targets u'\n                            \\<longrightarrow> t \\\\ u \\<approx>\\<^sub>0 t \\\\ u'\"\n      show \"\\<forall>t t' v v' w w'. v \\<in> \\<NN> \\<and> v' \\<in> \\<NN> \\<and> w \\<in> \\<NN> \\<and> w' \\<in> \\<NN> \\<and>\n                             R.sources v = R.sources w \\<and> R.sources v' = R.sources w' \\<and>\n                             R.targets w = R.targets w' \\<and> t \\\\ v \\<approx>\\<^sub>0 t' \\\\ v'\n                                \\<longrightarrow> t \\\\ w \\<approx>\\<^sub>0 t' \\\\ w'\"\n      proof (intro allI impI, elim conjE)\n        fix t t' v v' w w'\n        assume v: \"v \\<in> \\<NN>\" and v': \"v' \\<in> \\<NN>\" and w: \"w \\<in> \\<NN>\" and w': \"w' \\<in> \\<NN>\"\n        and vw: \"R.sources v = R.sources w\" and v'w': \"R.sources v' = R.sources w'\"\n        and ww': \"R.targets w = R.targets w'\"\n        and tvt'v': \"(t \\\\ v) \\\\ (t' \\\\ v') \\<in> \\<NN>\" and t'v'tv: \"(t' \\\\ v') \\\\ (t \\\\ v) \\<in> \\<NN>\"\n        show \"t \\\\ w \\<approx>\\<^sub>0 t' \\\\ w'\"\n        proof -\n          have 3: \"R.sources t = R.sources v \\<and> R.sources t' = R.sources v'\"\n            using R.con_imp_coinitial\n            by (meson Cong\\<^sub>0_imp_con tvt'v' t'v'tv\n                R.coinitial_iff R.arr_resid_iff_con)\n          have 2: \"t \\\\ w \\<approx> t' \\\\ w'\"\n            using Cong_closure_props\n            by (metis tvt'v' t'v'tv 3 vw v'w' v v' w w')\n          obtain z z' where zz': \"z \\<in> \\<NN> \\<and> z' \\<in> \\<NN> \\<and> (t \\\\ w) \\\\ z \\<approx>\\<^sub>0 (t' \\\\ w') \\\\ z'\"\n            using 2 by auto\n          have \"(t \\\\ w) \\\\ z \\<approx>\\<^sub>0 (t \\\\ w) \\\\ z'\"\n          proof -\n            have \"R.coinitial ((t \\\\ w) \\\\ z) ((t \\\\ w) \\\\ z')\"\n              by (metis Cong\\<^sub>0_imp_coinitial Cong_imp_arr(1)\n                  Resid_along_normal_preserves_reflects_con R.arr_def R.coinitialI\n                  R.con_imp_common_source Cong_closure_props(3) R.arr_resid_iff_con R.sources_eqI\n                  R.sources_resid ww' zz')\n            thus ?thesis\n              apply (intro conjI)\n              by (metis 1 R.coinitial_iff R.con_imp_coinitial R.arr_resid_iff_con\n                        R.sources_resid zz')+\n          qed\n          hence \"(t \\\\ w) \\\\ z' \\<approx>\\<^sub>0 (t' \\\\ w') \\\\ z'\"\n            using zz' Cong\\<^sub>0_transitive Cong\\<^sub>0_symmetric by blast\n          thus ?thesis\n            using zz' Resid_along_normal_reflects_Cong\\<^sub>0 by metis\n        qed\n      qed\n    qed\n\n  end\n\n  context coherent_normal_sub_rts\n  begin\n\n    text \\<open>\n      The proof of the substitutivity of \\<open>\\<approx>\\<close> with respect to residuation only uses\n      coherence in the ``opposing spans'' form.\n    \\<close>\n\n    lemma coherent':\n    assumes \"v \\<in> \\<NN>\" and \"v' \\<in> \\<NN>\" and \"w \\<in> \\<NN>\" and \"w' \\<in> \\<NN>\"\n    and \"R.sources v = R.sources w\" and \"R.sources v' = R.sources w'\"\n    and \"R.targets w = R.targets w'\" and \"t \\\\ v \\<approx>\\<^sub>0 t' \\\\ v'\"\n    shows \"t \\\\ w \\<approx>\\<^sub>0 t' \\\\ w'\"\n      using assms coherent coherent_iff by metis  (* 6 sec *)\n\n    text \\<open>\n      The relation \\<open>\\<approx>\\<close> is substitutive with respect to both arguments of residuation.\n    \\<close>\n\n    lemma Cong_subst:\n    assumes \"t \\<approx> t'\" and \"u \\<approx> u'\" and \"t \\<frown> u\" and \"R.sources t' = R.sources u'\"\n    shows \"t' \\<frown> u'\" and \"t \\\\ u \\<approx> t' \\\\ u'\"\n    proof -\n      obtain v v' where vv': \"v \\<in> \\<NN> \\<and> v' \\<in> \\<NN> \\<and> t \\\\ v \\<approx>\\<^sub>0 t' \\\\ v'\"\n        using assms by auto\n      obtain w w' where ww': \"w \\<in> \\<NN> \\<and> w' \\<in> \\<NN> \\<and> u \\\\ w \\<approx>\\<^sub>0 u' \\\\ w'\"\n        using assms by auto\n      let ?x = \"t \\\\ v\" and ?x' = \"t' \\\\ v'\"\n      let ?y = \"u \\\\ w\" and ?y' = \"u' \\\\ w'\"\n      have xx': \"?x \\<approx>\\<^sub>0 ?x'\"\n        using assms vv' by blast\n      have yy': \"?y \\<approx>\\<^sub>0 ?y'\"\n        using assms ww' by blast\n      have 1: \"t \\\\ w \\<approx>\\<^sub>0 t' \\\\ w'\"\n      proof -\n        have \"R.sources v = R.sources w\"\n          by (metis (no_types, lifting) Cong\\<^sub>0_imp_con R.arr_resid_iff_con assms(3)\n              R.con_imp_common_source R.con_implies_arr(2) R.sources_eqI ww' xx')\n        moreover have \"R.sources v' = R.sources w'\"\n          by (metis (no_types, lifting) assms(4) R.coinitial_iff R.con_imp_coinitial\n              Cong\\<^sub>0_imp_con R.arr_resid_iff_con ww' xx')\n        moreover have \"R.targets w = R.targets w'\"\n          by (metis Cong\\<^sub>0_implies_Cong Cong\\<^sub>0_imp_coinitial Cong_imp_arr(1)\n              R.arr_resid_iff_con R.sources_resid ww')\n        ultimately show ?thesis\n          using assms vv' ww'\n          by (intro coherent' [of v v' w w' t]) auto\n      qed\n      have 2: \"t' \\\\ w' \\<frown> u' \\\\ w'\"\n        using assms 1 ww'\n        by (metis Cong\\<^sub>0_subst_left(1) Cong\\<^sub>0_subst_right(1) Resid_along_normal_preserves_reflects_con\n            R.arr_resid_iff_con R.coinitial_iff R.con_imp_coinitial elements_are_arr)\n      thus 3: \"t' \\<frown> u'\"\n        using ww' R.cube by force\n      have \"t \\\\ u \\<approx> ((t \\\\ u) \\\\ (w \\\\ u)) \\\\ (?y' \\\\ ?y)\"\n      proof -\n        have \"t \\\\ u \\<approx> (t \\\\ u) \\\\ (w \\\\ u)\"\n          by (metis Cong_closure_props(4) assms(3) R.con_imp_coinitial\n              elements_are_arr forward_stable R.arr_resid_iff_con R.con_implies_arr(1)\n              R.sources_resid ww')\n        also have \"... \\<approx> ((t \\\\ u) \\\\ (w \\\\ u)) \\\\ (?y' \\\\ ?y)\"\n          by (metis Cong\\<^sub>0_imp_con Cong_closure_props(4) Cong_imp_arr(2)\n              R.arr_resid_iff_con calculation R.con_implies_arr(2) R.targets_resid_sym\n              R.sources_resid ww')\n        finally show ?thesis by simp\n      qed\n      also have \"... \\<approx> (((t \\\\ w) \\\\ ?y) \\\\ (?y' \\\\ ?y))\"\n        using ww'\n        by (metis Cong_imp_arr(2) Cong_reflexive calculation R.cube)\n      also have \"... \\<approx> (((t' \\\\ w') \\\\ ?y) \\\\ (?y' \\\\ ?y))\"\n        using 1 Cong\\<^sub>0_subst_left(2) [of \"t \\\\ w\" \"(t' \\\\ w')\" ?y]\n              Cong\\<^sub>0_subst_left(2) [of \"(t \\\\ w) \\\\ ?y\" \"(t' \\\\ w') \\\\ ?y\" \"?y' \\\\ ?y\"]\n        by (meson 2 Cong\\<^sub>0_implies_Cong Cong\\<^sub>0_subst_Con Cong_imp_arr(2)\n                  R.arr_resid_iff_con calculation ww')\n      also have \"... \\<approx> ((t' \\\\ w') \\\\ ?y') \\\\ (?y \\\\ ?y')\"\n        using 2 Cong\\<^sub>0_implies_Cong Cong\\<^sub>0_subst_right(2) ww' by presburger\n      also have 4: \"... \\<approx> (t' \\\\ u') \\\\ (w' \\\\ u')\"\n         using 2 ww'\n         by (metis Cong\\<^sub>0_imp_con Cong_closure_props(4) Cong_symmetric R.cube R.sources_resid)\n      also have \"... \\<approx> t' \\\\ u'\"\n         using ww' 3 4\n         by (metis Cong_closure_props(4) Cong_imp_arr(2) Cong_symmetric R.con_imp_coinitial\n                   R.con_implies_arr(2) forward_stable R.sources_resid R.arr_resid_iff_con)\n      finally show \"t \\\\ u \\<approx> t' \\\\ u'\" by simp\n    qed\n\n    lemma Cong_subst_con:\n    assumes \"R.sources t = R.sources u\" and \"R.sources t' = R.sources u'\" and \"t \\<approx> t'\" and \"u \\<approx> u'\"\n    shows \"t \\<frown> u \\<longleftrightarrow> t' \\<frown> u'\"\n      using assms by (meson Cong_subst(1) Cong_symmetric)\n\n    lemma Cong\\<^sub>0_composite_of_arr_normal:\n    assumes \"R.composite_of t u t'\" and \"u \\<in> \\<NN>\"\n    shows \"t' \\<approx>\\<^sub>0 t\"\n      using assms backward_stable R.composite_of_def ide_closed by blast\n\n    lemma Cong_composite_of_normal_arr:\n    assumes \"R.composite_of u t t'\" and \"u \\<in> \\<NN>\"\n    shows \"t' \\<approx> t\"\n      using assms\n      by (meson Cong_closure_props(2-4) R.arr_composite_of ide_closed R.composite_of_def\n                R.sources_composite_of)\n\n  end\n\n  context normal_sub_rts\n  begin\n\n    text \\<open>\n      Coherence is not an arbitrary property: here we show that substitutivity of\n      congruence in residuation is equivalent to the ``opposing spans'' form of coherence.\n    \\<close>\n\n    lemma Cong_subst_iff_coherent':\n    shows \"(\\<forall>t t' u u'. t \\<approx> t' \\<and> u \\<approx> u' \\<and> t \\<frown> u \\<and> R.sources t' = R.sources u'\n                           \\<longrightarrow> t' \\<frown> u' \\<and> t \\\\ u \\<approx> t' \\\\ u')\n           \\<longleftrightarrow>\n           (\\<forall>t t' v v' w w'. v \\<in> \\<NN> \\<and> v' \\<in> \\<NN> \\<and> w \\<in> \\<NN> \\<and> w' \\<in> \\<NN> \\<and>\n                             R.sources v = R.sources w \\<and> R.sources v' = R.sources w' \\<and>\n                             R.targets w = R.targets w' \\<and> t \\\\ v \\<approx>\\<^sub>0 t' \\\\ v'\n                                \\<longrightarrow> t \\\\ w \\<approx>\\<^sub>0 t' \\\\ w')\"\n    proof\n      assume 1: \"\\<forall>t t' u u'. t \\<approx> t' \\<and> u \\<approx> u' \\<and> t \\<frown> u \\<and> R.sources t' = R.sources u'\n                           \\<longrightarrow> t' \\<frown> u' \\<and> t \\\\ u \\<approx> t' \\\\ u'\"\n      show \"\\<forall>t t' v v' w w'. v \\<in> \\<NN> \\<and> v' \\<in> \\<NN> \\<and> w \\<in> \\<NN> \\<and> w' \\<in> \\<NN> \\<and>\n                             R.sources v = R.sources w \\<and> R.sources v' = R.sources w' \\<and>\n                             R.targets w = R.targets w' \\<and> t \\\\ v \\<approx>\\<^sub>0 t' \\\\ v'\n                                \\<longrightarrow> t \\\\ w \\<approx>\\<^sub>0 t' \\\\ w'\"\n      proof (intro allI impI, elim conjE)\n        fix t t' v v' w w'\n        assume v: \"v \\<in> \\<NN>\" and v': \"v' \\<in> \\<NN>\" and w: \"w \\<in> \\<NN>\" and w': \"w' \\<in> \\<NN>\"\n        and sources_vw: \"R.sources v = R.sources w\"\n        and sources_v'w': \"R.sources v' = R.sources w'\"\n        and targets_ww': \"R.targets w = R.targets w'\"\n        and tt': \"(t \\\\ v) \\\\ (t' \\\\ v') \\<in> \\<NN>\" and t't: \"(t' \\\\ v') \\\\ (t \\\\ v) \\<in> \\<NN>\"\n        show \"t \\\\ w \\<approx>\\<^sub>0 t' \\\\ w'\"\n        proof -\n          have 2: \"\\<And>t t' u u'. \\<lbrakk>t \\<approx> t'; u \\<approx> u'; t \\<frown> u; R.sources t' = R.sources u'\\<rbrakk>\n                                   \\<Longrightarrow> t' \\<frown> u' \\<and> t \\\\ u \\<approx> t' \\\\ u'\"\n            using 1 by blast\n          have 3: \"t \\\\ w \\<approx> t \\\\ v \\<and> t' \\\\ w' \\<approx> t' \\\\ v'\"\n            by (metis tt' t't sources_vw sources_v'w' Cong\\<^sub>0_subst_right(2) Cong_closure_props(4)\n                      Cong_def R.arr_resid_iff_con Cong_closure_props(3) Cong_imp_arr(1)\n                      normal_is_Cong_closed v w v' w')\n          have \"(t \\\\ w) \\\\ (t' \\\\ w') \\<approx> (t \\\\ v) \\\\ (t' \\\\ v')\"\n            using 2 [of \"t \\\\ w\" \"t \\\\ v\" \"t' \\\\ w'\" \"t' \\\\ v'\"] 3\n            by (metis tt' t't targets_ww' 1 Cong\\<^sub>0_imp_con Cong_imp_arr(1) Cong_symmetric\n                R.arr_resid_iff_con R.sources_resid)\n          moreover have \"(t' \\\\ w') \\\\ (t \\\\ w) \\<approx> (t' \\\\ v') \\\\ (t \\\\ v)\"\n            using 2 3\n            by (metis tt' t't targets_ww' Cong\\<^sub>0_imp_con Cong_symmetric\n                Cong_imp_arr(1) R.arr_resid_iff_con R.sources_resid)\n          ultimately show ?thesis\n            by (meson tt' t't normal_is_Cong_closed Cong_symmetric)\n        qed\n      qed\n      next\n      assume 1: \"\\<forall>t t' v v' w w'. v \\<in> \\<NN> \\<and> v' \\<in> \\<NN> \\<and> w \\<in> \\<NN> \\<and> w' \\<in> \\<NN> \\<and>\n                             R.sources v = R.sources w \\<and> R.sources v' = R.sources w' \\<and>\n                             R.targets w = R.targets w' \\<and> t \\\\ v \\<approx>\\<^sub>0 t' \\\\ v'\n                                \\<longrightarrow> t \\\\ w \\<approx>\\<^sub>0 t' \\\\ w'\"\n      show \"\\<forall>t t' u u'. t \\<approx> t' \\<and> u \\<approx> u' \\<and> t \\<frown> u \\<and> R.sources t' = R.sources u'\n                           \\<longrightarrow> t' \\<frown> u' \\<and> t \\\\ u \\<approx> t' \\\\ u'\"\n      proof (intro allI impI, elim conjE, intro conjI)\n        have *: \"\\<And>t t' v v' w w'. \\<lbrakk>v \\<in> \\<NN>; v' \\<in> \\<NN>; w \\<in> \\<NN>; w' \\<in> \\<NN>;\n                                   R.sources v = R.sources w; R.sources v' = R.sources w';\n                                   R.targets v = R.targets v'; R.targets w = R.targets w';\n                                   t \\\\ v \\<approx>\\<^sub>0 t' \\\\ v'\\<rbrakk>\n                                      \\<Longrightarrow> t \\\\ w \\<approx>\\<^sub>0 t' \\\\ w'\"\n          using 1 by metis\n        fix t t' u u'\n        assume tt': \"t \\<approx> t'\" and uu': \"u \\<approx> u'\" and con: \"t \\<frown> u\"\n        and t'u': \"R.sources t' = R.sources u'\"\n        obtain v v' where vv': \"v \\<in> \\<NN> \\<and> v' \\<in> \\<NN> \\<and> t \\\\ v \\<approx>\\<^sub>0 t' \\\\ v'\"\n          using tt' by auto\n        obtain w w' where ww': \"w \\<in> \\<NN> \\<and> w' \\<in> \\<NN> \\<and> u \\\\ w \\<approx>\\<^sub>0 u' \\\\ w'\"\n          using uu' by auto\n        let ?x = \"t \\\\ v\" and ?x' = \"t' \\\\ v'\"\n        let ?y = \"u \\\\ w\" and ?y' = \"u' \\\\ w'\"\n        have xx': \"?x \\<approx>\\<^sub>0 ?x'\"\n          using tt' vv' by blast\n        have yy': \"?y \\<approx>\\<^sub>0 ?y'\"\n          using uu' ww' by blast\n        have 1: \"t \\\\ w \\<approx>\\<^sub>0 t' \\\\ w'\"\n        proof -\n          have \"R.sources v = R.sources w \\<and> R.sources v' = R.sources w'\"\n          proof\n            show \"R.sources v' = R.sources w'\"\n              using Cong\\<^sub>0_imp_con R.arr_resid_iff_con R.coinitial_iff R.con_imp_coinitial\n                    t'u' vv' ww'\n              by metis\n            show \"R.sources v = R.sources w\"\n              by (metis con elements_are_arr R.not_arr_null R.null_is_zero(2) R.conI\n                  R.con_imp_common_source rts.sources_eqI R.rts_axioms vv' ww')\n          qed\n          moreover have \"R.targets v = R.targets v' \\<and> R.targets w = R.targets w'\"\n            by (metis Cong\\<^sub>0_imp_coinitial Cong\\<^sub>0_imp_con R.arr_resid_iff_con\n                R.con_implies_arr(2) R.sources_resid vv' ww')\n          ultimately show ?thesis\n            using vv' ww' xx'\n            by (intro * [of v v' w w' t t']) auto\n        qed\n        have 2: \"t' \\\\ w' \\<frown> u' \\\\ w'\"\n          using 1 tt' ww'\n          by (meson Cong\\<^sub>0_imp_con Cong\\<^sub>0_subst_Con R.arr_resid_iff_con con R.con_imp_coinitial\n              R.con_implies_arr(2) resid_along_elem_preserves_con)\n        thus 3: \"t' \\<frown> u'\"\n          using ww' R.cube by force\n        have \"t \\\\ u \\<approx> (t \\\\ u) \\\\ (w \\\\ u)\"\n          by (metis Cong_closure_props(4) R.arr_resid_iff_con con R.con_imp_coinitial\n              elements_are_arr forward_stable R.con_implies_arr(2) R.sources_resid ww')\n        also have \"(t \\\\ u) \\\\ (w \\\\ u) \\<approx> ((t \\\\ u) \\\\ (w \\\\ u)) \\\\ (?y' \\\\ ?y)\"\n          using yy'\n          by (metis Cong\\<^sub>0_imp_con Cong_closure_props(4) Cong_imp_arr(2)\n              R.arr_resid_iff_con calculation R.con_implies_arr(2) R.sources_resid R.targets_resid_sym)\n        also have \"... \\<approx> (((t \\\\ w) \\\\ ?y) \\\\ (?y' \\\\ ?y))\"\n          using ww'\n          by (metis Cong_imp_arr(2) Cong_reflexive calculation R.cube)\n        also have \"... \\<approx> (((t' \\\\ w') \\\\ ?y) \\\\ (?y' \\\\ ?y))\"\n        proof -\n          have \"((t \\\\ w) \\\\ ?y) \\\\ (?y' \\\\ ?y) \\<approx>\\<^sub>0 ((t' \\\\ w') \\\\ ?y) \\\\ (?y' \\\\ ?y)\"\n            using 1 2 Cong\\<^sub>0_subst_left(2)\n            by (meson Cong\\<^sub>0_subst_Con calculation Cong_imp_arr(2) R.arr_resid_iff_con ww')\n          thus ?thesis\n            using Cong\\<^sub>0_implies_Cong by presburger\n        qed\n        also have \"... \\<approx> ((t' \\\\ w') \\\\ ?y') \\\\ (?y \\\\ ?y')\"\n          by (meson \"2\" Cong\\<^sub>0_implies_Cong Cong\\<^sub>0_subst_right(2) ww')\n        also have 4: \"... \\<approx> (t' \\\\ u') \\\\ (w' \\\\ u')\"\n           using 2 ww'\n           by (metis Cong\\<^sub>0_imp_con Cong_closure_props(4) Cong_symmetric R.cube R.sources_resid)\n        also have \"... \\<approx> t' \\\\ u'\"\n           using ww' 2 3 4\n           by (metis Cong'.intros(1) Cong'.intros(4) Cong_char Cong_imp_arr(2)\n               R.arr_resid_iff_con forward_stable R.con_imp_coinitial R.sources_resid\n               R.con_implies_arr(2))\n        finally show \"t \\\\ u \\<approx> t' \\\\ u'\" by simp\n      qed\n    qed\n\n  end\n\n  subsection \"Quotient by Coherent Normal Sub-RTS\"\n\n  text \\<open>\n    We now define the quotient of an RTS by a coherent normal sub-RTS and show that it is\n    an extensional RTS.\n  \\<close>\n\n  locale quotient_by_coherent_normal =\n    R: rts +\n    N: coherent_normal_sub_rts\n  begin\n\n    definition Resid  (infix \"\\<lbrace>\\\\\\<rbrace>\" 70)\n    where \"\\<T> \\<lbrace>\\\\\\<rbrace> \\<U> \\<equiv>\n           if N.is_Cong_class \\<T> \\<and> N.is_Cong_class \\<U> \\<and> (\\<exists>t u. t \\<in> \\<T> \\<and> u \\<in> \\<U> \\<and> t \\<frown> u)\n           then N.Cong_class\n                  (fst (SOME tu. fst tu \\<in> \\<T> \\<and> snd tu \\<in> \\<U> \\<and> fst tu \\<frown> snd tu) \\\\\n                   snd (SOME tu. fst tu \\<in> \\<T> \\<and> snd tu \\<in> \\<U> \\<and> fst tu \\<frown> snd tu))\n           else {}\"\n\n    sublocale partial_magma Resid\n      using N.Cong_class_is_nonempty Resid_def\n      by unfold_locales metis\n\n    lemma is_partial_magma:\n    shows \"partial_magma Resid\"\n      ..\n\n    lemma null_char:\n    shows \"null = {}\"\n      using N.Cong_class_is_nonempty Resid_def\n      by (metis null_is_zero(2))\n\n    lemma Resid_by_members:\n    assumes \"N.is_Cong_class \\<T>\" and \"N.is_Cong_class \\<U>\" and \"t \\<in> \\<T>\" and \"u \\<in> \\<U>\" and \"t \\<frown> u\"\n    shows \"\\<T> \\<lbrace>\\\\\\<rbrace> \\<U> = \\<lbrace>t \\\\ u\\<rbrace>\"\n      using assms Resid_def someI_ex [of \"\\<lambda>tu. fst tu \\<in> \\<T> \\<and> snd tu \\<in> \\<U> \\<and> fst tu \\<frown> snd tu\"]\n      apply simp\n      by (meson N.Cong_class_membs_are_Cong N.Cong_class_eqI N.Cong_subst(2)\n          R.coinitial_iff R.con_imp_coinitial)\n\n    abbreviation Con  (infix \"\\<lbrace>\\<frown>\\<rbrace>\" 50)\n    where \"\\<T> \\<lbrace>\\<frown>\\<rbrace> \\<U> \\<equiv> \\<T> \\<lbrace>\\\\\\<rbrace> \\<U> \\<noteq> {}\"\n\n    lemma Con_char:\n    shows \"\\<T> \\<lbrace>\\<frown>\\<rbrace> \\<U> \\<longleftrightarrow>\n           N.is_Cong_class \\<T> \\<and> N.is_Cong_class \\<U> \\<and> (\\<exists>t u. t \\<in> \\<T> \\<and> u \\<in> \\<U> \\<and> t \\<frown> u)\"\n      by (metis (no_types, opaque_lifting) N.Cong_class_is_nonempty N.is_Cong_classI\n          Resid_def Resid_by_members R.arr_resid_iff_con)\n\n    lemma Con_sym:\n    assumes \"Con \\<T> \\<U>\"\n    shows \"Con \\<U> \\<T>\"\n      using assms Con_char R.con_sym by meson\n\n    lemma is_Cong_class_Resid:\n    assumes \"\\<T> \\<lbrace>\\<frown>\\<rbrace> \\<U>\"\n    shows \"N.is_Cong_class (\\<T> \\<lbrace>\\\\\\<rbrace> \\<U>)\"\n      using assms Con_char Resid_by_members R.arr_resid_iff_con N.is_Cong_classI by auto\n\n    lemma Con_witnesses:\n    assumes \"\\<T> \\<lbrace>\\<frown>\\<rbrace> \\<U>\" and \"t \\<in> \\<T>\" and \"u \\<in> \\<U>\"\n    shows \"\\<exists>v w. v \\<in> \\<NN> \\<and> w \\<in> \\<NN> \\<and> t \\\\ v \\<frown> u \\\\ w\"\n    proof -\n      have 1: \"N.is_Cong_class \\<T> \\<and> N.is_Cong_class \\<U> \\<and> (\\<exists>t u. t \\<in> \\<T> \\<and> u \\<in> \\<U> \\<and> t \\<frown> u)\"\n        using assms Con_char by simp\n      obtain t' u' where t'u': \"t' \\<in> \\<T> \\<and> u' \\<in> \\<U> \\<and> t' \\<frown> u'\"\n        using 1 by auto\n      have 2: \"t' \\<approx> t \\<and> u' \\<approx> u\"\n        using assms 1 t'u' N.Cong_class_membs_are_Cong by auto\n      obtain v v' where vv': \"v \\<in> \\<NN> \\<and> v' \\<in> \\<NN> \\<and> t' \\\\ v \\<approx>\\<^sub>0 t \\\\ v'\"\n        using 2 by auto\n      obtain w w' where ww': \"w \\<in> \\<NN> \\<and> w' \\<in> \\<NN> \\<and> u' \\\\ w \\<approx>\\<^sub>0 u \\\\ w'\"\n        using 2 by auto\n      have 3: \"w \\<frown> v\"\n        by (metis R.arr_resid_iff_con R.con_def R.con_imp_coinitial R.ex_un_null\n            N.elements_are_arr R.null_is_zero(2) N.resid_along_elem_preserves_con t'u' vv' ww')\n      have \"R.seq v (w \\\\ v)\"\n        by (simp add: N.elements_are_arr R.seq_def 3 vv')\n      obtain x where x: \"R.composite_of v (w \\\\ v) x\"\n        using N.composite_closed_left \\<open>R.seq v (w \\ v)\\<close> vv' by blast\n      obtain x' where x': \"R.composite_of v' (w \\\\ v) x'\"\n        using x vv' N.composite_closed_left\n        by (metis N.Cong\\<^sub>0_implies_Cong N.Cong\\<^sub>0_imp_coinitial N.Cong_imp_arr(1)\n            R.composable_def R.composable_imp_seq R.con_implies_arr(2)\n            R.seq_def R.sources_resid R.arr_resid_iff_con)\n      have *: \"t' \\\\ x \\<approx>\\<^sub>0 t \\\\ x'\"\n        by (metis N.coherent' N.composite_closed N.forward_stable R.con_imp_coinitial\n            R.targets_composite_of 3 R.con_sym R.sources_composite_of vv' ww' x x')\n      obtain y where y: \"R.composite_of w (v \\\\ w) y\"\n        using x vv' ww'\n        by (metis R.arr_resid_iff_con R.composable_def R.composable_imp_seq\n            R.con_imp_coinitial R.seq_def R.sources_resid N.elements_are_arr\n            N.forward_stable N.composite_closed_left)\n      obtain y' where y': \"R.composite_of w' (v \\\\ w) y'\"\n        using y ww'\n        by (metis N.Cong\\<^sub>0_imp_coinitial N.Cong_closure_props(3) N.Cong_imp_arr(1)\n            R.composable_def R.composable_imp_seq R.con_implies_arr(2) R.seq_def\n            R.sources_resid N.composite_closed_left R.arr_resid_iff_con)\n      have **: \"u' \\\\ y \\<approx>\\<^sub>0 u \\\\ y'\"\n        by (metis N.composite_closed N.forward_stable R.con_imp_coinitial R.targets_composite_of\n            \\<open>w \\<frown> v\\<close> N.coherent' R.sources_composite_of vv' ww' y y')\n      have 4: \"x \\<in> \\<NN> \\<and> y \\<in> \\<NN>\"\n        using x y vv' ww' * **\n        by (metis 3 N.composite_closed N.forward_stable R.con_imp_coinitial R.con_sym)\n      have \"t \\\\ x' \\<frown> u \\\\ y'\"\n      proof -\n        have \"t \\\\ x' \\<approx>\\<^sub>0 t' \\\\ x\"\n          using * by simp\n        moreover have \"t' \\\\ x \\<frown> u' \\\\ y\"\n        proof -\n          have \"t' \\\\ x \\<frown> u' \\\\ x\"\n            using t'u' vv' ww' 4 *\n            by (metis N.Resid_along_normal_preserves_reflects_con N.elements_are_arr\n                R.coinitial_iff R.con_imp_coinitial R.arr_resid_iff_con)\n          moreover have \"u' \\\\ x \\<approx>\\<^sub>0 u' \\\\ y\"\n            using ww' x y\n            by (metis 4 N.Cong\\<^sub>0_imp_coinitial N.Cong\\<^sub>0_imp_con N.Cong\\<^sub>0_transitive\n                N.coherent' N.factor_closed(2) R.sources_composite_of\n                R.targets_composite_of R.targets_resid_sym)\n          ultimately show ?thesis\n            using N.Cong\\<^sub>0_subst_right by blast\n        qed\n        moreover have \"u' \\\\ y \\<approx>\\<^sub>0 u \\\\ y'\"\n          using ** R.con_sym by simp\n        ultimately show ?thesis\n          using N.Cong\\<^sub>0_subst_Con by auto\n      qed\n      moreover have \"x' \\<in> \\<NN> \\<and> y' \\<in> \\<NN>\"\n        using x' y' vv' ww'\n        by (metis N.Cong_composite_of_normal_arr N.Cong_imp_arr(2) N.composite_closed\n            R.con_imp_coinitial N.forward_stable R.arr_resid_iff_con)\n      ultimately show ?thesis by auto\n    qed\n\n    abbreviation Arr\n    where \"Arr \\<T> \\<equiv> Con \\<T> \\<T>\"\n\n    lemma Arr_Resid:\n    assumes \"Con \\<T> \\<U>\"\n    shows \"Arr (\\<T> \\<lbrace>\\\\\\<rbrace> \\<U>)\"\n      by (metis Con_char N.Cong_class_memb_is_arr R.arrE N.rep_in_Cong_class\n          assms is_Cong_class_Resid)\n\n    lemma Cube:\n    assumes \"Con (\\<V> \\<lbrace>\\\\\\<rbrace> \\<T>) (\\<U> \\<lbrace>\\\\\\<rbrace> \\<T>)\"\n    shows \"(\\<V> \\<lbrace>\\\\\\<rbrace> \\<T>) \\<lbrace>\\\\\\<rbrace> (\\<U> \\<lbrace>\\\\\\<rbrace> \\<T>) = (\\<V> \\<lbrace>\\\\\\<rbrace> \\<U>) \\<lbrace>\\\\\\<rbrace> (\\<T> \\<lbrace>\\\\\\<rbrace> \\<U>)\"\n    proof -\n      obtain t u where tu: \"t \\<in> \\<T> \\<and> u \\<in> \\<U> \\<and> t \\<frown> u \\<and> \\<T> \\<lbrace>\\\\\\<rbrace> \\<U> = \\<lbrace>t \\\\ u\\<rbrace>\"\n        using assms\n        by (metis Con_char N.Cong_class_is_nonempty R.con_sym Resid_by_members)\n      obtain t' v where t'v: \"t' \\<in> \\<T> \\<and> v \\<in> \\<V> \\<and> t' \\<frown> v \\<and> \\<T> \\<lbrace>\\\\\\<rbrace> \\<V> = \\<lbrace>t' \\\\ v\\<rbrace>\"\n        using assms\n        by (metis Con_char N.Cong_class_is_nonempty Resid_by_members Con_sym)\n      have tt': \"t \\<approx> t'\"\n        using assms\n        by (metis N.Cong_class_membs_are_Cong N.Cong_class_is_nonempty Resid_def t'v tu)\n      obtain w w' where ww': \"w \\<in> \\<NN> \\<and> w' \\<in> \\<NN> \\<and> t \\\\ w \\<approx>\\<^sub>0 t' \\\\ w'\"\n        using tu t'v tt' by auto\n      have 1: \"\\<U> \\<lbrace>\\\\\\<rbrace> \\<T> = \\<lbrace>u \\\\ t\\<rbrace> \\<and> \\<V> \\<lbrace>\\\\\\<rbrace> \\<T> = \\<lbrace>v \\\\ t'\\<rbrace>\"\n        by (metis Con_char N.Cong_class_is_nonempty R.con_sym Resid_by_members assms t'v tu)\n      obtain x x' where xx': \"x \\<in> \\<NN> \\<and> x' \\<in> \\<NN> \\<and> (u \\\\ t) \\\\ x \\<frown> (v \\\\ t') \\\\ x'\"\n        using 1 Con_witnesses [of \"\\<U> \\<lbrace>\\\\\\<rbrace> \\<T>\" \"\\<V> \\<lbrace>\\\\\\<rbrace> \\<T>\" \"u \\\\ t\" \"v \\\\ t'\"]\n        by (metis N.arr_in_Cong_class R.con_sym t'v tu assms Con_sym R.arr_resid_iff_con)\n      have \"R.seq t x\"\n        by (metis R.arr_resid_iff_con R.coinitial_iff R.con_imp_coinitial R.seqI\n            R.sources_resid xx')\n      have \"R.seq t' x'\"\n        by (metis R.arr_resid_iff_con R.sources_resid R.coinitialE R.con_imp_coinitial\n            R.seqI xx')\n      obtain tx where tx: \"R.composite_of t x tx\"\n        using xx' \\<open>R.seq t x\\<close> N.composite_closed_right [of x t] R.composable_def by auto\n      obtain t'x' where t'x': \"R.composite_of t' x' t'x'\"\n        using xx' \\<open>R.seq t' x'\\<close> N.composite_closed_right [of x' t'] R.composable_def by auto\n      let ?tx_w = \"tx \\\\ w\" and ?t'x'_w' = \"t'x' \\\\ w'\"\n      let ?w_tx = \"(w \\\\ t) \\\\ x\" and ?w'_t'x' = \"(w' \\\\ t') \\\\ x'\"\n      let ?u_tx = \"(u \\\\ t) \\\\ x\" and ?v_t'x' = \"(v \\\\ t') \\\\ x'\"\n      let ?u_w = \"u \\\\ w\" and ?v_w' = \"v \\\\ w'\"\n      let ?w_u = \"w \\\\ u\" and ?w'_v = \"w' \\\\ v\"\n      have w_tx_in_\\<NN>: \"?w_tx \\<in> \\<NN>\"\n        using tx ww' xx' R.con_composite_of_iff [of t x tx w]\n        by (metis (full_types) N.Cong\\<^sub>0_composite_of_arr_normal N.Cong\\<^sub>0_subst_left(1)\n            N.forward_stable R.null_is_zero(2) R.con_imp_coinitial R.conI R.con_sym)\n      have w'_t'x'_in_\\<NN>: \"?w'_t'x' \\<in> \\<NN>\"\n        using t'x' ww' xx' R.con_composite_of_iff [of t' x' t'x' w']\n        by (metis (full_types) N.Cong\\<^sub>0_composite_of_arr_normal N.Cong\\<^sub>0_subst_left(1)\n            R.con_sym N.forward_stable R.null_is_zero(2) R.con_imp_coinitial R.conI)\n      have 2: \"?tx_w \\<approx>\\<^sub>0 ?t'x'_w'\"\n      proof -\n        have \"?tx_w \\<approx>\\<^sub>0 t \\\\ w\"\n          using t'x' tx ww' xx' N.Cong\\<^sub>0_composite_of_arr_normal [of t x tx] N.Cong\\<^sub>0_subst_left(2)\n          by (metis N.Cong\\<^sub>0_transitive R.conI)\n        also have \"t \\\\ w \\<approx>\\<^sub>0 t' \\\\ w'\"\n          using ww' by blast\n        also have \"t' \\\\ w' \\<approx>\\<^sub>0 ?t'x'_w'\"\n          using t'x' tx ww' xx' N.Cong\\<^sub>0_composite_of_arr_normal [of t' x' t'x'] N.Cong\\<^sub>0_subst_left(2)\n          by (metis N.Cong\\<^sub>0_transitive R.conI)\n        finally show ?thesis by blast\n      qed\n      obtain z where z: \"R.composite_of ?tx_w (?t'x'_w' \\\\ ?tx_w) z\"\n        by (metis \"2\" R.arr_resid_iff_con R.con_implies_arr(2) N.elements_are_arr\n            N.composite_closed_right R.seqI R.sources_resid)\n      obtain z' where z': \"R.composite_of ?t'x'_w' (?tx_w \\\\ ?t'x'_w') z'\"\n        by (metis \"2\" R.arr_resid_iff_con R.con_implies_arr(2) N.elements_are_arr\n            N.composite_closed_right R.seqI R.sources_resid)\n      have 3: \"z \\<approx>\\<^sub>0 z'\"\n        using 2 N.diamond_commutes_upto_Cong\\<^sub>0 N.Cong\\<^sub>0_imp_con z z' by blast\n      have \"R.targets z = R.targets z'\"\n        by (metis R.targets_resid_sym z z' R.targets_composite_of R.conI)\n      have Con_z_uw: \"z \\<frown> ?u_w\"\n      proof -\n        have \"?tx_w \\<frown> ?u_w\"\n          by (meson 3 N.Cong\\<^sub>0_composite_of_arr_normal N.Cong\\<^sub>0_subst_left(1)\n              R.bounded_imp_con R.con_implies_arr(1) R.con_imp_coinitial\n              N.resid_along_elem_preserves_con tu tx ww' xx' z z' R.arr_resid_iff_con)\n        thus ?thesis\n          using 2 N.Cong\\<^sub>0_composite_of_arr_normal N.Cong\\<^sub>0_subst_left(1) z by blast\n      qed\n      moreover have Con_z'_vw': \"z' \\<frown> ?v_w'\"\n      proof -\n        have \"?t'x'_w' \\<frown> ?v_w'\"\n          by (meson 3 N.Cong\\<^sub>0_composite_of_arr_normal N.Cong\\<^sub>0_subst_left(1)\n              R.bounded_imp_con t'v t'x' ww' xx' z z' R.con_imp_coinitial\n              N.resid_along_elem_preserves_con R.arr_resid_iff_con R.con_implies_arr(1))\n        thus ?thesis\n          by (meson 2 N.Cong\\<^sub>0_composite_of_arr_normal N.Cong\\<^sub>0_subst_left(1) z')\n      qed\n      moreover have Con_z_vw': \"z \\<frown> ?v_w'\"\n        using 3 Con_z'_vw' N.Cong\\<^sub>0_subst_left(1) by blast\n      moreover have *: \"?u_w \\\\ z \\<frown> ?v_w' \\\\ z\"\n      proof -\n        obtain y where y: \"R.composite_of (w \\\\ tx) (?t'x'_w' \\\\ ?tx_w) y\"\n          by (metis 2 R.arr_resid_iff_con R.composable_def R.composable_imp_seq\n              R.con_imp_coinitial N.elements_are_arr N.composite_closed_right\n              R.seq_def R.targets_resid_sym ww' z N.forward_stable)\n        obtain y' where y': \"R.composite_of (w' \\\\ t'x') (?tx_w \\\\ ?t'x'_w') y'\"\n          by (metis 2 R.arr_resid_iff_con R.composable_def R.composable_imp_seq\n              R.con_imp_coinitial N.elements_are_arr N.composite_closed_right\n              R.targets_resid_sym ww' z' R.seq_def N.forward_stable)\n        have y_comp: \"R.composite_of (w \\\\ tx) ((t'x' \\\\ w') \\\\ (tx \\\\ w)) y\"\n          using y by simp\n        have y_in_normal: \"y \\<in> \\<NN>\"\n          by (metis 2 Con_z_uw R.arr_iff_has_source R.arr_resid_iff_con N.composite_closed\n              R.con_imp_coinitial R.con_implies_arr(1) N.forward_stable\n              R.sources_composite_of ww' y_comp z)\n        have y_coinitial: \"R.coinitial y (u \\\\ tx)\"\n          using y R.coinitial_def\n          by (metis Con_z_uw R.con_def R.con_prfx_composite_of(2) R.con_sym R.cube\n              R.sources_composite_of R.con_imp_common_source z)\n        have y_con: \"y \\<frown> u \\\\ tx\"\n          using y_in_normal y_coinitial\n            by (metis R.coinitial_iff N.elements_are_arr N.forward_stable\n                R.arr_resid_iff_con)\n        have A: \"?u_w \\\\ z \\<sim> (u \\\\ tx) \\\\ y\"\n        proof -\n          have \"(u \\\\ tx) \\\\ y \\<sim> ((u \\\\ tx) \\\\ (w \\\\ tx)) \\\\ (?t'x'_w' \\\\ ?tx_w)\"\n            using y_comp y_con \n                  R.resid_composite_of(3) [of \"w \\\\ tx\" \"?t'x'_w' \\\\ ?tx_w\" y \"u \\\\ tx\"]\n            by simp\n          also have \"((u \\\\ tx) \\\\ (w \\\\ tx)) \\\\ (?t'x'_w' \\\\ ?tx_w) \\<sim> ?u_w \\\\ z\"\n            by (metis Con_z_uw R.resid_composite_of(3) z R.cube)\n          finally show ?thesis by blast\n        qed\n        have y'_comp: \"R.composite_of (w' \\\\ t'x') (?tx_w \\\\ ?t'x'_w') y'\"\n          using y' by simp\n        have y'_in_normal: \"y' \\<in> \\<NN>\"\n          by (metis 2 Con_z'_vw' R.arr_iff_has_source R.arr_resid_iff_con\n              N.composite_closed R.con_imp_coinitial R.con_implies_arr(1)\n              N.forward_stable R.sources_composite_of ww' y'_comp z')\n        have y'_coinitial: \"R.coinitial y' (v \\\\ t'x')\"\n          using y' R.coinitial_def\n          by (metis Con_z'_vw' R.arr_resid_iff_con R.composite_ofE R.con_imp_coinitial\n              R.con_implies_arr(1) R.cube R.prfx_implies_con R.resid_composite_of(1)\n              R.sources_resid z')\n        have y'_con: \"y' \\<frown> v \\\\ t'x'\"\n          using y'_in_normal y'_coinitial\n          by (metis R.coinitial_iff N.elements_are_arr N.forward_stable\n              R.arr_resid_iff_con)\n        have B: \"?v_w' \\\\ z' \\<sim> (v \\\\ t'x') \\\\ y'\"\n        proof -\n          have \"(v \\\\ t'x') \\\\ y' \\<sim> ((v \\\\ t'x') \\\\ (w' \\\\ t'x')) \\\\ (?tx_w \\\\ ?t'x'_w')\"\n            using y'_comp y'_con\n                  R.resid_composite_of(3) [of \"w' \\\\ t'x'\" \"?tx_w \\\\ ?t'x'_w'\" y' \"v \\\\ t'x'\"]\n            by blast\n          also have \"((v \\\\ t'x') \\\\ (w' \\\\ t'x')) \\\\ (?tx_w \\\\ ?t'x'_w') \\<sim> ?v_w' \\\\ z'\"\n            by (metis Con_z'_vw' R.cube R.resid_composite_of(3) z')\n          finally show ?thesis by blast\n        qed\n        have C: \"u \\\\ tx \\<frown> v \\\\ t'x'\"\n          using tx t'x' xx' R.con_sym R.cong_subst_right(1) R.resid_composite_of(3)\n          by (meson R.coinitial_iff R.arr_resid_iff_con y'_coinitial y_coinitial)\n        have D: \"y \\<approx>\\<^sub>0 y'\"\n        proof -\n          have \"y \\<approx>\\<^sub>0 w \\\\ tx\"\n            using 2 N.Cong\\<^sub>0_composite_of_arr_normal y_comp by blast\n          also have \"w \\\\ tx \\<approx>\\<^sub>0 w' \\\\ t'x'\"\n          proof -\n            have \"w \\\\ tx \\<in> \\<NN> \\<and> w' \\\\ t'x' \\<in> \\<NN>\"\n              using N.factor_closed(1) y_comp y_in_normal y'_comp y'_in_normal by blast\n            moreover have \"R.coinitial (w \\\\ tx) (w' \\\\ t'x')\"\n              by (metis C R.coinitial_def R.con_implies_arr(2) N.elements_are_arr\n                  R.sources_resid calculation R.con_imp_coinitial R.arr_resid_iff_con y_con)\n            ultimately show ?thesis\n              by (meson R.arr_resid_iff_con R.con_imp_coinitial N.forward_stable\n                  N.elements_are_arr)\n          qed\n          also have \"w' \\\\ t'x' \\<approx>\\<^sub>0 y'\"\n            using 2 N.Cong\\<^sub>0_composite_of_arr_normal y'_comp by blast\n          finally show ?thesis by blast\n        qed\n        have par_y_y': \"R.sources y = R.sources y' \\<and> R.targets y = R.targets y'\"\n          using D N.Cong\\<^sub>0_imp_coinitial R.targets_composite_of y'_comp y_comp z z'\n                \\<open>R.targets z = R.targets z'\\<close>\n          by presburger\n        have E: \"(u \\\\ tx) \\\\ y \\<frown> (v \\\\ t'x') \\\\ y'\"\n        proof -\n          have \"(u \\\\ tx) \\\\ y \\<frown> (v \\\\ t'x') \\\\ y\"\n            using C N.Resid_along_normal_preserves_reflects_con R.coinitial_iff\n                  y_coinitial y_in_normal\n            by presburger\n          moreover have \"(v \\\\ t'x') \\\\ y \\<approx>\\<^sub>0 (v \\\\ t'x') \\\\ y'\"\n            using par_y_y' N.coherent R.coinitial_iff y'_coinitial y'_in_normal y_in_normal\n            by presburger\n          ultimately show ?thesis\n            using N.Cong\\<^sub>0_subst_right(1) by blast\n        qed\n        hence \"?u_w \\\\ z \\<frown> ?v_w' \\\\ z'\"\n        proof -\n          have \"(u \\\\ tx) \\\\ y \\<sim> ?u_w \\\\ z\"\n            using A by simp\n          moreover have \"(u \\\\ tx) \\\\ y \\<frown> (v \\\\ t'x') \\\\ y'\"\n            using E by blast\n          moreover have \"(v \\\\ t'x') \\\\ y' \\<sim> ?v_w' \\\\ z'\"\n            using B R.cong_symmetric by blast\n          moreover have \"R.sources ((u \\\\ w) \\\\ z) = R.sources ((v \\\\ w') \\\\ z')\"\n            by (simp add: Con_z'_vw' Con_z_uw R.con_sym \\<open>R.targets z = R.targets z'\\<close>)\n          ultimately show ?thesis\n            by (meson N.Cong\\<^sub>0_subst_Con N.ide_closed)\n        qed\n        moreover have \"?v_w' \\\\ z' \\<approx> ?v_w' \\\\ z\"\n          by (meson 3 Con_z_vw' N.CongI N.Cong\\<^sub>0_subst_right(2) R.con_sym)\n        moreover have \"R.sources ((v \\\\ w') \\\\ z) = R.sources ((u \\\\ w) \\\\ z)\"\n          by (metis R.con_implies_arr(1) R.sources_resid calculation(1) calculation(2)\n                    N.Cong_imp_arr(2) R.arr_resid_iff_con)\n        ultimately show ?thesis\n          by (metis N.Cong_reflexive N.Cong_subst(1) R.con_implies_arr(1))\n      qed\n      ultimately have **: \"?v_w' \\\\ z \\<frown> ?u_w \\\\ z \\<and>\n                           (?v_w' \\\\ z) \\\\ (?u_w \\\\ z) = (?v_w' \\\\ ?u_w) \\\\ (z \\\\ ?u_w)\"\n        by (meson R.con_sym R.cube)\n      have Cong_t_z: \"t \\<approx> z\"\n        by (metis 2 N.Cong\\<^sub>0_composite_of_arr_normal N.Cong_closure_props(2-3)\n            N.Cong_closure_props(4) N.Cong_imp_arr(2) R.coinitial_iff R.con_imp_coinitial\n            tx ww' xx' z R.arr_resid_iff_con)\n      have Cong_u_uw: \"u \\<approx> ?u_w\"\n        by (meson Con_z_uw N.Cong_closure_props(4) R.coinitial_iff R.con_imp_coinitial\n            ww' R.arr_resid_iff_con)\n      have Cong_v_vw': \"v \\<approx> ?v_w'\"\n        by (meson Con_z_vw' N.Cong_closure_props(4) R.coinitial_iff ww' R.con_imp_coinitial\n            R.arr_resid_iff_con)\n      have \\<T>: \"N.is_Cong_class \\<T> \\<and> z \\<in> \\<T>\"\n        by (metis (no_types, lifting) Cong_t_z N.Cong_class_eqI N.Cong_class_is_nonempty\n            N.Cong_class_memb_Cong_rep N.Cong_class_rep N.Cong_imp_arr(2) N.arr_in_Cong_class\n            tu assms Con_char)\n      have \\<U>: \"N.is_Cong_class \\<U> \\<and> ?u_w \\<in> \\<U>\"\n        by (metis Con_char Con_z_uw Cong_u_uw Int_iff N.Cong_class_eqI' N.Cong_class_eqI\n            N.arr_in_Cong_class R.con_implies_arr(2) N.is_Cong_classI tu assms empty_iff)\n      have \\<V>: \"N.is_Cong_class \\<V> \\<and> ?v_w' \\<in> \\<V>\"\n        by (metis Con_char Con_z_vw' Cong_v_vw' Int_iff N.Cong_class_eqI' N.Cong_class_eqI\n            N.arr_in_Cong_class R.con_implies_arr(2) N.is_Cong_classI t'v assms empty_iff)\n      show \"(\\<V> \\<lbrace>\\\\\\<rbrace> \\<T>) \\<lbrace>\\\\\\<rbrace> (\\<U> \\<lbrace>\\\\\\<rbrace> \\<T>) = (\\<V> \\<lbrace>\\\\\\<rbrace> \\<U>) \\<lbrace>\\\\\\<rbrace> (\\<T> \\<lbrace>\\\\\\<rbrace> \\<U>)\"\n      proof -\n        have \"(\\<V> \\<lbrace>\\\\\\<rbrace> \\<T>) \\<lbrace>\\\\\\<rbrace> (\\<U> \\<lbrace>\\\\\\<rbrace> \\<T>) = \\<lbrace>(?v_w' \\\\ z) \\\\ (?u_w \\\\ z)\\<rbrace>\"\n          using \\<T> \\<U> \\<V> * Resid_by_members\n          by (metis ** Con_char N.arr_in_Cong_class R.arr_resid_iff_con assms R.con_implies_arr(2))\n        moreover have \"(\\<V> \\<lbrace>\\\\\\<rbrace> \\<U>) \\<lbrace>\\\\\\<rbrace> (\\<T> \\<lbrace>\\\\\\<rbrace> \\<U>) = \\<lbrace>(?v_w' \\\\ ?u_w) \\\\ (z \\\\ ?u_w)\\<rbrace>\"\n          using Resid_by_members [of \\<V> \\<U> ?v_w' ?u_w] Resid_by_members [of \\<T> \\<U> z ?u_w]\n                Resid_by_members [of \"\\<V> \\<lbrace>\\\\\\<rbrace> \\<U>\" \"\\<T> \\<lbrace>\\\\\\<rbrace> \\<U>\" \"?v_w' \\\\ ?u_w\" \"z \\\\ ?u_w\"]\n          by (metis \\<T> \\<U> \\<V> * ** N.arr_in_Cong_class R.con_implies_arr(2) N.is_Cong_classI\n              R.resid_reflects_con R.arr_resid_iff_con)\n        ultimately show ?thesis\n          using ** by simp\n      qed\n    qed\n\n    sublocale residuation Resid\n      using null_char Con_sym Arr_Resid Cube\n      by unfold_locales metis+\n\n    lemma is_residuation:\n    shows \"residuation Resid\"\n      ..\n\n    lemma arr_char:\n    shows \"arr \\<T> \\<longleftrightarrow> N.is_Cong_class \\<T>\"\n      by (metis N.is_Cong_class_def arrI not_arr_null null_char N.Cong_class_memb_is_arr\n          Con_char R.arrE arrE arr_resid conI)\n\n    lemma ide_char:\n    shows \"ide \\<U> \\<longleftrightarrow> arr \\<U> \\<and> \\<U> \\<inter> \\<NN> \\<noteq> {}\"\n    proof\n      show \"ide \\<U> \\<Longrightarrow> arr \\<U> \\<and> \\<U> \\<inter> \\<NN> \\<noteq> {}\"\n        apply (elim ideE)\n        by (metis Con_char N.Cong\\<^sub>0_reflexive Resid_by_members disjoint_iff null_char\n            N.arr_in_Cong_class R.arrE R.arr_resid arr_resid conE)\n      show \"arr \\<U> \\<and> \\<U> \\<inter> \\<NN> \\<noteq> {} \\<Longrightarrow> ide \\<U>\"\n      proof -\n        assume \\<U>: \"arr \\<U> \\<and> \\<U> \\<inter> \\<NN> \\<noteq> {}\"\n        obtain u where u: \"R.arr u \\<and> u \\<in> \\<U> \\<inter> \\<NN>\"\n          using \\<U> arr_char\n          by (metis IntI N.Cong_class_memb_is_arr disjoint_iff)\n        show ?thesis\n          by (metis IntD1 IntD2 N.Cong_class_eqI N.Cong_closure_props(4) N.arr_in_Cong_class\n              N.is_Cong_classI Resid_by_members \\<U> arrE arr_char disjoint_iff ideI\n              N.Cong_class_eqI' R.arrE u)\n      qed\n    qed\n\n    lemma ide_char':\n    shows \"ide \\<A> \\<longleftrightarrow> arr \\<A> \\<and> \\<A> \\<subseteq> \\<NN>\"\n      by (metis Int_absorb2 Int_emptyI N.Cong_class_memb_Cong_rep N.Cong_closure_props(1)\n          ide_char not_arr_null null_char N.normal_is_Cong_closed arr_char subsetI)\n\n    lemma con_char\\<^sub>Q\\<^sub>C\\<^sub>N:\n    shows \"con \\<T> \\<U> \\<longleftrightarrow>\n           N.is_Cong_class \\<T> \\<and> N.is_Cong_class \\<U> \\<and> (\\<exists>t u. t \\<in> \\<T> \\<and> u \\<in> \\<U> \\<and> t \\<frown> u)\"\n      by (metis Con_char conE conI null_char)\n\n    (*\n     * TODO: Does the stronger form of con_char hold in this context?\n     * I am currently only able to prove it for the more special context of paths,\n     * but it doesn't seem like that should be required.\n     *\n     * The issue is that congruent paths have the same sets of sources,\n     * but this does not necessarily hold in general.  If we know that all representatives\n     * of a congruence class have the same sets of sources, then we known that if any\n     * pair of representatives is consistent, then the arbitrarily chosen representatives\n     * of the congruence class are consistent.  This is by substitutivity of congruence,\n     * which has coinitiality as a hypothesis.\n     *\n     * In the general case, we have to reason as follows: if t and u are consistent\n     * representatives of \\<T> and \\<U>, and if t' and u' are arbitrary coinitial representatives\n     * of \\<T> and \\<U>, then we can obtain \"opposing spans\" connecting t u and t' u'.\n     * The opposing span form of coherence then implies that t' and u' are consistent.\n     * So we should be able to show that if congruence classes \\<T> and \\<U> are consistent,\n     * then all pairs of coinitial representatives are consistent.\n     *)\n\n    lemma con_imp_coinitial_members_are_con:\n    assumes \"con \\<T> \\<U>\" and \"t \\<in> \\<T>\" and \"u \\<in> \\<U>\" and \"R.sources t = R.sources u\"\n    shows \"t \\<frown> u\"\n      by (meson assms N.Cong_subst(1) N.is_Cong_classE con_char\\<^sub>Q\\<^sub>C\\<^sub>N)\n\n    sublocale rts Resid\n    proof\n      show 1: \"\\<And>\\<A> \\<T>. \\<lbrakk>ide \\<A>; con \\<T> \\<A>\\<rbrakk> \\<Longrightarrow> \\<T> \\<lbrace>\\\\\\<rbrace> \\<A> = \\<T>\"\n      proof -\n        fix \\<A> \\<T>\n        assume \\<A>: \"ide \\<A>\" and con: \"con \\<T> \\<A>\"\n        obtain t a where ta: \"t \\<in> \\<T> \\<and> a \\<in> \\<A> \\<and> R.con t a \\<and> \\<T> \\<lbrace>\\\\\\<rbrace> \\<A> = \\<lbrace>t \\\\ a\\<rbrace>\"\n          using con con_char\\<^sub>Q\\<^sub>C\\<^sub>N Resid_by_members by auto\n        have \"a \\<in> \\<NN>\"\n          using \\<A> ta ide_char' by auto\n        hence \"t \\\\ a \\<approx> t\"\n          by (meson N.Cong_closure_props(4) N.Cong_symmetric R.coinitialE R.con_imp_coinitial\n              ta)\n        thus \"\\<T> \\<lbrace>\\\\\\<rbrace> \\<A> = \\<T>\"\n          using ta\n          by (metis N.Cong_class_eqI N.Cong_class_memb_Cong_rep N.Cong_class_rep con con_char\\<^sub>Q\\<^sub>C\\<^sub>N)\n      qed\n      show \"\\<And>\\<T>. arr \\<T> \\<Longrightarrow> ide (trg \\<T>)\"\n        by (metis N.Cong\\<^sub>0_reflexive Resid_by_members disjoint_iff ide_char N.Cong_class_memb_is_arr\n            N.arr_in_Cong_class N.is_Cong_class_def arr_char R.arrE R.arr_resid resid_arr_self)\n      show \"\\<And>\\<A> \\<T>. \\<lbrakk>ide \\<A>; con \\<A> \\<T>\\<rbrakk> \\<Longrightarrow> ide (\\<A> \\<lbrace>\\\\\\<rbrace> \\<T>)\"\n        by (metis 1 arrE arr_resid con_sym ideE ideI cube)\n      show \"\\<And>\\<T> \\<U>. con \\<T> \\<U> \\<Longrightarrow> \\<exists>\\<A>. ide \\<A> \\<and> con \\<A> \\<T> \\<and> con \\<A> \\<U>\"\n      proof -\n        fix \\<T> \\<U>\n        assume \\<T>\\<U>: \"con \\<T> \\<U>\"\n        obtain t u where tu: \"\\<T> = \\<lbrace>t\\<rbrace> \\<and> \\<U> = \\<lbrace>u\\<rbrace> \\<and> t \\<frown> u\"\n          using \\<T>\\<U> con_char\\<^sub>Q\\<^sub>C\\<^sub>N arr_char\n          by (metis N.Cong_class_memb_Cong_rep N.Cong_class_eqI N.Cong_class_rep)\n        obtain a where a: \"a \\<in> R.sources t\"\n          using \\<T>\\<U> tu R.con_implies_arr(1) R.arr_iff_has_source by blast\n        have \"ide \\<lbrace>a\\<rbrace> \\<and> con \\<lbrace>a\\<rbrace> \\<T> \\<and> con \\<lbrace>a\\<rbrace> \\<U>\"\n        proof (intro conjI)\n          have 2: \"a \\<in> \\<NN>\"\n            using \\<T>\\<U> tu a arr_char N.ide_closed R.sources_def by force\n          show 3: \"ide \\<lbrace>a\\<rbrace>\"\n            using \\<T>\\<U> tu 2 a ide_char arr_char con_char\\<^sub>Q\\<^sub>C\\<^sub>N\n            by (metis IntI N.arr_in_Cong_class N.is_Cong_classI empty_iff N.elements_are_arr)\n          show \"con \\<lbrace>a\\<rbrace> \\<T>\"\n            using \\<T>\\<U> tu 2 3 a ide_char arr_char con_char\\<^sub>Q\\<^sub>C\\<^sub>N\n            by (metis N.arr_in_Cong_class R.composite_of_source_arr\n                R.composite_of_def R.prfx_implies_con R.con_implies_arr(1))\n          show \"con \\<lbrace>a\\<rbrace> \\<U>\"\n            using \\<T>\\<U> tu a ide_char arr_char con_char\\<^sub>Q\\<^sub>C\\<^sub>N\n            by (metis N.arr_in_Cong_class R.composite_of_source_arr R.con_prfx_composite_of\n                N.is_Cong_classI R.con_implies_arr(1) R.con_implies_arr(2))\n        qed\n        thus \"\\<exists>\\<A>. ide \\<A> \\<and> con \\<A> \\<T> \\<and> con \\<A> \\<U>\" by auto\n      qed\n      show \"\\<And>\\<T> \\<U> \\<V>. \\<lbrakk>ide (\\<T> \\<lbrace>\\\\\\<rbrace> \\<U>); con \\<U> \\<V>\\<rbrakk> \\<Longrightarrow> con (\\<T> \\<lbrace>\\\\\\<rbrace> \\<U>) (\\<V> \\<lbrace>\\\\\\<rbrace> \\<U>)\"\n      proof -\n        fix \\<T> \\<U> \\<V>\n        assume \\<T>\\<U>: \"ide (\\<T> \\<lbrace>\\\\\\<rbrace> \\<U>)\"\n        assume \\<U>\\<V>: \"con \\<U> \\<V>\"\n        obtain t u where tu: \"t \\<in> \\<T> \\<and> u \\<in> \\<U> \\<and> t \\<frown> u \\<and> \\<T> \\<lbrace>\\\\\\<rbrace> \\<U> = \\<lbrace>t \\\\ u\\<rbrace>\"\n          using \\<T>\\<U>\n          by (meson Resid_by_members ide_implies_arr quotient_by_coherent_normal.con_char\\<^sub>Q\\<^sub>C\\<^sub>N\n              quotient_by_coherent_normal_axioms arr_resid_iff_con)\n        obtain v u' where vu': \"v \\<in> \\<V> \\<and> u' \\<in> \\<U> \\<and> v \\<frown> u' \\<and> \\<V> \\<lbrace>\\\\\\<rbrace> \\<U> = \\<lbrace>v \\\\ u'\\<rbrace>\"\n          by (meson R.con_sym Resid_by_members \\<U>\\<V> con_char\\<^sub>Q\\<^sub>C\\<^sub>N)\n        have 1: \"u \\<approx> u'\"\n          using \\<U>\\<V> tu vu'\n          by (meson N.Cong_class_membs_are_Cong con_char\\<^sub>Q\\<^sub>C\\<^sub>N)\n        obtain w w' where ww': \"w \\<in> \\<NN> \\<and> w' \\<in> \\<NN> \\<and> u \\\\ w \\<approx>\\<^sub>0 u' \\\\ w'\"\n          using 1 by auto\n        have 2: \"((t \\\\ u) \\\\ (w \\\\ u)) \\\\ ((u' \\\\ w') \\\\ (u \\\\ w)) \\<frown>\n                 ((v \\\\ u') \\\\ (w' \\\\ u')) \\\\ ((u \\\\ w) \\\\ (u' \\\\ w'))\"\n        proof -\n          have \"((t \\\\ u) \\\\ (w \\\\ u)) \\\\ ((u' \\\\ w') \\\\ (u \\\\ w)) \\<in> \\<NN>\"\n          proof -\n            have \"t \\\\ u \\<in> \\<NN>\"\n              using tu N.arr_in_Cong_class R.arr_resid_iff_con \\<T>\\<U> ide_char' by blast\n            hence \"(t \\\\ u) \\\\ (w \\\\ u) \\<in> \\<NN>\"\n              by (metis N.Cong_closure_props(4) N.forward_stable R.null_is_zero(2)\n                  R.con_imp_coinitial R.sources_resid N.Cong_imp_arr(2) R.arr_resid_iff_con\n                  tu ww' R.conI)\n            thus ?thesis\n              by (metis N.Cong_closure_props(4) N.normal_is_Cong_closed R.sources_resid\n                  R.targets_resid_sym N.elements_are_arr R.arr_resid_iff_con ww' R.conI)\n          qed\n          moreover have \"R.sources (((t \\\\ u) \\\\ (w \\\\ u)) \\\\ ((u' \\\\ w') \\\\ (u \\\\ w))) =\n                         R.sources (((v \\\\ u') \\\\ (w' \\\\ u')) \\\\ ((u \\\\ w) \\\\ (u' \\\\ w')))\"\n          proof -\n            have \"R.sources (((t \\\\ u) \\\\ (w \\\\ u)) \\\\ ((u' \\\\ w') \\\\ (u \\\\ w))) =\n                  R.targets ((u' \\\\ w') \\\\ (u \\\\ w))\"\n              using R.arr_resid_iff_con N.elements_are_arr R.sources_resid calculation by blast\n            also have \"... = R.targets ((u \\\\ w) \\\\ (u' \\\\ w'))\"\n              by (metis R.targets_resid_sym R.conI)\n            also have \"... = R.sources (((v \\\\ u') \\\\ (w' \\\\ u')) \\\\ ((u \\\\ w) \\\\ (u' \\\\ w')))\"\n              using R.arr_resid_iff_con N.elements_are_arr R.sources_resid\n              by (metis N.Cong_closure_props(4) N.Cong_imp_arr(2) R.con_implies_arr(1)\n                  R.con_imp_coinitial N.forward_stable R.targets_resid_sym vu' ww')\n            finally show ?thesis by simp\n          qed\n          ultimately show ?thesis\n            by (metis (no_types, lifting) N.Cong\\<^sub>0_imp_con N.Cong_closure_props(4)\n                N.Cong_imp_arr(2) R.arr_resid_iff_con R.con_imp_coinitial N.forward_stable\n                R.null_is_zero(2) R.conI)\n        qed\n        moreover have \"t \\\\ u \\<approx> ((t \\\\ u) \\\\ (w \\\\ u)) \\\\ ((u' \\\\ w') \\\\ (u \\\\ w))\"\n          by (metis (no_types, opaque_lifting) N.Cong_closure_props(4) N.Cong_transitive\n              N.forward_stable R.arr_resid_iff_con R.con_imp_coinitial R.rts_axioms calculation\n              rts.coinitial_iff ww')\n        moreover have \"v \\\\ u' \\<approx> ((v \\\\ u') \\\\ (w' \\\\ u')) \\\\ ((u \\\\ w) \\\\ (u' \\\\ w'))\"\n        proof -\n          have \"w' \\\\ u' \\<in> \\<NN>\"\n            by (meson R.con_implies_arr(2) R.con_imp_coinitial N.forward_stable\n                ww' N.Cong\\<^sub>0_imp_con R.arr_resid_iff_con)\n          moreover have \"(u \\\\ w) \\\\ (u' \\\\ w') \\<in> \\<NN>\"\n            using ww' by blast\n          ultimately show ?thesis\n            by (meson 2 N.Cong_closure_props(2) N.Cong_closure_props(4) R.arr_resid_iff_con\n                R.coinitial_iff R.con_imp_coinitial)\n        qed\n        ultimately show \"con (\\<T> \\<lbrace>\\\\\\<rbrace> \\<U>) (\\<V> \\<lbrace>\\\\\\<rbrace> \\<U>)\"\n          using con_char\\<^sub>Q\\<^sub>C\\<^sub>N N.Cong_class_def N.is_Cong_classI tu vu' R.arr_resid_iff_con\n          by auto\n      qed\n    qed\n\n    lemma is_rts:\n    shows \"rts Resid\"\n      ..\n\n    sublocale extensional_rts Resid\n    proof\n      fix \\<T> \\<U>\n      assume \\<T>\\<U>: \"cong \\<T> \\<U>\"\n      show \"\\<T> = \\<U>\"\n      proof -\n        obtain t u where tu: \"\\<T> = \\<lbrace>t\\<rbrace> \\<and> \\<U> = \\<lbrace>u\\<rbrace> \\<and> t \\<frown> u\"\n          by (metis Con_char N.Cong_class_eqI N.Cong_class_memb_Cong_rep N.Cong_class_rep\n              \\<T>\\<U> ide_char not_arr_null null_char)\n        have \"t \\<approx>\\<^sub>0 u\"\n        proof\n          show \"t \\\\ u \\<in> \\<NN>\"\n            using tu \\<T>\\<U> Resid_by_members [of \\<T> \\<U> t u]\n            by (metis (full_types) N.arr_in_Cong_class R.con_implies_arr(1-2)\n                N.is_Cong_classI ide_char' R.arr_resid_iff_con subset_iff)\n          show \"u \\\\ t \\<in> \\<NN>\"\n            using tu \\<T>\\<U> Resid_by_members [of \\<U> \\<T> u t] R.con_sym\n            by (metis (full_types) N.arr_in_Cong_class R.con_implies_arr(1-2)\n                N.is_Cong_classI ide_char' R.arr_resid_iff_con subset_iff)\n        qed\n        hence \"t \\<approx> u\"\n          using N.Cong\\<^sub>0_implies_Cong by simp\n        thus \"\\<T> = \\<U>\"\n          by (simp add: N.Cong_class_eqI tu)\n      qed\n    qed\n\n    theorem is_extensional_rts:\n    shows \"extensional_rts Resid\"\n      ..\n\n    lemma sources_char\\<^sub>Q\\<^sub>C\\<^sub>N:\n    shows \"sources \\<T> = {\\<A>. arr \\<T> \\<and> \\<A> = {a. \\<exists>t a'. t \\<in> \\<T> \\<and> a' \\<in> R.sources t \\<and> a' \\<approx> a}}\"\n    proof -\n      let ?\\<A> = \"{a. \\<exists>t a'. t \\<in> \\<T> \\<and> a' \\<in> R.sources t \\<and> a' \\<approx> a}\"\n      have 1: \"arr \\<T> \\<Longrightarrow> ide ?\\<A>\"\n      proof (unfold ide_char', intro conjI)\n        assume \\<T>: \"arr \\<T>\"\n        show \"?\\<A> \\<subseteq> \\<NN>\"\n          using N.ide_closed N.normal_is_Cong_closed by blast\n        show \"arr ?\\<A>\"\n        proof -\n          have \"N.is_Cong_class ?\\<A>\"\n          proof\n            show \"?\\<A> \\<noteq> {}\"\n              by (metis (mono_tags, lifting) Collect_empty_eq N.Cong_class_def N.Cong_imp_arr(1)\n                  N.is_Cong_class_def N.sources_are_Cong R.arr_iff_has_source R.sources_def\n                  \\<T> arr_char mem_Collect_eq)\n            show \"\\<And>t t'. \\<lbrakk>t \\<in> ?\\<A>; t' \\<approx> t\\<rbrakk> \\<Longrightarrow> t' \\<in> ?\\<A>\"\n              using N.Cong_symmetric N.Cong_transitive by blast\n            show \"\\<And>a a'. \\<lbrakk>a \\<in> ?\\<A>; a' \\<in> ?\\<A>\\<rbrakk> \\<Longrightarrow> a \\<approx> a'\"\n            proof -\n              fix a a'\n              assume a: \"a \\<in> ?\\<A>\" and a': \"a' \\<in> ?\\<A>\"\n              obtain t b where b: \"t \\<in> \\<T> \\<and> b \\<in> R.sources t \\<and> b \\<approx> a\"\n                using a by blast\n              obtain t' b' where b': \"t' \\<in> \\<T> \\<and> b' \\<in> R.sources t' \\<and> b' \\<approx> a'\"\n                using a' by blast\n              have \"b \\<approx> b'\"\n                using \\<T> arr_char b b'\n                by (meson IntD1 N.Cong_class_membs_are_Cong N.in_sources_respects_Cong)\n              thus \"a \\<approx> a'\"\n                by (meson N.Cong_symmetric N.Cong_transitive b b')\n            qed\n          qed\n          thus ?thesis\n            using arr_char by auto\n        qed\n      qed\n      moreover have \"arr \\<T> \\<Longrightarrow> con \\<T> ?\\<A>\"\n      proof -\n        assume \\<T>: \"arr \\<T>\"\n        obtain t a where a: \"t \\<in> \\<T> \\<and> a \\<in> R.sources t\"\n          using \\<T> arr_char\n          by (metis N.Cong_class_is_nonempty R.arr_iff_has_source empty_subsetI\n                    N.Cong_class_memb_is_arr subsetI subset_antisym)\n        have \"t \\<in> \\<T> \\<and> a \\<in> {a. \\<exists>t a'. t \\<in> \\<T> \\<and> a' \\<in> R.sources t \\<and> a' \\<approx> a} \\<and> t \\<frown> a\"\n          using a N.Cong_reflexive R.sources_def R.con_implies_arr(2) by fast\n        thus ?thesis\n          using \\<T> 1 arr_char con_char\\<^sub>Q\\<^sub>C\\<^sub>N [of \\<T> ?\\<A>] by auto\n      qed\n      ultimately have \"arr \\<T> \\<Longrightarrow> ?\\<A> \\<in> sources \\<T>\"\n        using sources_def by blast\n      thus ?thesis\n        using \"1\" ide_char sources_char by auto\n    qed\n\n    lemma targets_char\\<^sub>Q\\<^sub>C\\<^sub>N:\n    shows \"targets \\<T> = {\\<B>. arr \\<T> \\<and> \\<B> = \\<T> \\<lbrace>\\\\\\<rbrace> \\<T>}\"\n    proof -\n      have \"targets \\<T> = {\\<B>. ide \\<B> \\<and> con (\\<T> \\<lbrace>\\\\\\<rbrace> \\<T>) \\<B>}\"\n        by (simp add: targets_def trg_def)\n      also have \"... = {\\<B>. arr \\<T> \\<and> ide \\<B> \\<and> (\\<exists>t u. t \\<in> \\<T> \\<lbrace>\\\\\\<rbrace> \\<T> \\<and> u \\<in> \\<B> \\<and> t \\<frown> u)}\"\n        using arr_resid_iff_con con_char\\<^sub>Q\\<^sub>C\\<^sub>N arr_char arr_def by auto\n      also have \"... = {\\<B>. arr \\<T> \\<and> ide \\<B> \\<and>\n                           (\\<exists>t t' b u. t \\<in> \\<T> \\<and> t' \\<in> \\<T> \\<and> t \\<frown> t' \\<and> b \\<in> \\<lbrace>t \\\\ t'\\<rbrace> \\<and> u \\<in> \\<B> \\<and> b \\<frown> u)}\"\n        using arr_char ide_char Resid_by_members [of \\<T> \\<T>] N.Cong_class_memb_is_arr\n              N.is_Cong_class_def R.arr_def\n        by auto metis+\n      also have \"... = {\\<B>. arr \\<T> \\<and> ide \\<B> \\<and>\n                           (\\<exists>t t' b. t \\<in> \\<T> \\<and> t' \\<in> \\<T> \\<and> t \\<frown> t' \\<and> b \\<in> \\<lbrace>t \\\\ t'\\<rbrace> \\<and> b \\<in> \\<B>)}\"\n      proof -\n        have \"\\<And>\\<B> t t' b. \\<lbrakk>arr \\<T>; ide \\<B>; t \\<in> \\<T>; t' \\<in> \\<T>; t \\<frown> t'; b \\<in> \\<lbrace>t \\\\ t'\\<rbrace>\\<rbrakk>\n                            \\<Longrightarrow> (\\<exists>u. u \\<in> \\<B> \\<and> b \\<frown> u) \\<longleftrightarrow> b \\<in> \\<B>\"\n        proof -\n          fix \\<B> t t' b\n          assume \\<T>: \"arr \\<T>\" and \\<B>: \"ide \\<B>\" and t: \"t \\<in> \\<T>\" and t': \"t' \\<in> \\<T>\"\n                 and tt': \"t \\<frown> t'\" and b: \"b \\<in> \\<lbrace>t \\\\ t'\\<rbrace>\"\n          have 0: \"b \\<in> \\<NN>\"\n            by (metis Resid_by_members \\<T> b ide_char' ide_trg arr_char subsetD t t' trg_def tt')\n          show \"(\\<exists>u. u \\<in> \\<B> \\<and> b \\<frown> u) \\<longleftrightarrow> b \\<in> \\<B>\"\n            using 0\n            by (meson N.Cong_closure_props(3) N.forward_stable N.elements_are_arr\n                \\<B> arr_char R.con_imp_coinitial N.is_Cong_classE ide_char' R.arrE\n                R.con_sym subsetD)\n        qed\n        thus ?thesis\n          using ide_char arr_char\n          by (metis (no_types, lifting))\n      qed\n      also have \"... = {\\<B>. arr \\<T> \\<and> ide \\<B> \\<and> (\\<exists>t t'. t \\<in> \\<T> \\<and> t' \\<in> \\<T> \\<and> t \\<frown> t' \\<and> \\<lbrace>t \\\\ t'\\<rbrace> \\<subseteq> \\<B>)}\"\n      proof -\n        have \"\\<And>\\<B> t t' b. \\<lbrakk>arr \\<T>; ide \\<B>; t \\<in> \\<T>; t' \\<in> \\<T>; t \\<frown> t'\\<rbrakk>\n                            \\<Longrightarrow> (\\<exists>b. b \\<in> \\<lbrace>t \\\\ t'\\<rbrace> \\<and> b \\<in> \\<B>) \\<longleftrightarrow> \\<lbrace>t \\\\ t'\\<rbrace> \\<subseteq> \\<B>\"\n          using ide_char arr_char\n          apply (intro iffI)\n           apply (metis IntI N.Cong_class_eqI' R.arr_resid_iff_con N.is_Cong_classI empty_iff\n                        set_eq_subset)\n          by (meson N.arr_in_Cong_class R.arr_resid_iff_con subsetD)\n        thus ?thesis\n          using ide_char arr_char\n          by (metis (no_types, lifting))\n      qed\n      also have \"... = {\\<B>. arr \\<T> \\<and> ide \\<B> \\<and> \\<T> \\<lbrace>\\\\\\<rbrace> \\<T> \\<subseteq> \\<B>}\"\n        using arr_char ide_char Resid_by_members [of \\<T> \\<T>]\n        by (metis (no_types, opaque_lifting) arrE con_char\\<^sub>Q\\<^sub>C\\<^sub>N)\n      also have \"... = {\\<B>. arr \\<T> \\<and> \\<B> = \\<T> \\<lbrace>\\\\\\<rbrace> \\<T>}\"\n        by (metis (no_types, lifting) arr_has_un_target calculation con_ide_are_eq\n            cong_reflexive mem_Collect_eq targets_def trg_def)\n      finally show ?thesis by blast\n    qed\n\n    lemma src_char\\<^sub>Q\\<^sub>C\\<^sub>N:\n    shows \"src \\<T> = {a. arr \\<T> \\<and> (\\<exists>t a'. t \\<in> \\<T> \\<and> a' \\<in> R.sources t \\<and> a' \\<approx> a)}\"\n      using sources_char\\<^sub>Q\\<^sub>C\\<^sub>N [of \\<T>]\n      by (simp add: null_char src_def)\n\n    lemma trg_char\\<^sub>Q\\<^sub>C\\<^sub>N:\n    shows \"trg \\<T> = \\<T> \\<lbrace>\\\\\\<rbrace> \\<T>\"\n      unfolding trg_def by blast\n\n    subsubsection \"Quotient Map\"\n\n    abbreviation quot\n    where \"quot t \\<equiv> \\<lbrace>t\\<rbrace>\"\n\n    sublocale quot: simulation resid Resid quot\n    proof\n      show \"\\<And>t. \\<not> R.arr t \\<Longrightarrow> \\<lbrace>t\\<rbrace> = null\"\n        using N.Cong_class_def N.Cong_imp_arr(1) null_char by force\n      show \"\\<And>t u. t \\<frown> u \\<Longrightarrow> con \\<lbrace>t\\<rbrace> \\<lbrace>u\\<rbrace>\"\n        by (meson N.arr_in_Cong_class N.is_Cong_classI R.con_implies_arr(1-2) con_char\\<^sub>Q\\<^sub>C\\<^sub>N)\n      show \"\\<And>t u. t \\<frown> u \\<Longrightarrow> \\<lbrace>t \\\\ u\\<rbrace> = \\<lbrace>t\\<rbrace> \\<lbrace>\\\\\\<rbrace> \\<lbrace>u\\<rbrace>\"\n        by (metis N.arr_in_Cong_class N.is_Cong_classI R.con_implies_arr(1-2) Resid_by_members)\n    qed\n\n    lemma quotient_is_simulation:\n    shows \"simulation resid Resid quot\"\n      ..\n\n    (*\n     * TODO: Show couniversality.\n     *)\n\n  end\n\n  subsection \"Identities form a Coherent Normal Sub-RTS\"\n\n  text \\<open>\n    We now show that the collection of identities of an RTS form a coherent normal sub-RTS,\n    and that the associated congruence \\<open>\\<approx>\\<close> coincides with \\<open>\\<sim>\\<close>.\n    Thus, every RTS can be factored by the relation \\<open>\\<sim>\\<close> to obtain an extensional RTS.\n    Although we could have shown that fact much earlier, we have delayed proving it so that\n    we could simply obtain it as a special case of our general quotient result without\n    redundant work.\n  \\<close>\n\n  context rts\n  begin\n\n    interpretation normal_sub_rts resid \\<open>Collect ide\\<close>\n    proof\n      show \"\\<And>t. t \\<in> Collect ide \\<Longrightarrow> arr t\"\n        by blast\n      show 1: \"\\<And>a. ide a \\<Longrightarrow> a \\<in> Collect ide\"\n        by blast\n      show \"\\<And>u t. \\<lbrakk>u \\<in> Collect ide; coinitial t u\\<rbrakk> \\<Longrightarrow> u \\\\ t \\<in> Collect ide\"\n        by (metis 1 CollectD arr_def coinitial_iff\n            con_sym in_sourcesE in_sourcesI resid_ide_arr)\n      show \"\\<And>u t. \\<lbrakk>u \\<in> Collect ide; t \\\\ u \\<in> Collect ide\\<rbrakk> \\<Longrightarrow> t \\<in> Collect ide\"\n        using ide_backward_stable by blast\n      show \"\\<And>u t. \\<lbrakk>u \\<in> Collect ide; seq u t\\<rbrakk> \\<Longrightarrow> \\<exists>v. composite_of u t v\"\n        by (metis composite_of_source_arr ide_def in_sourcesI mem_Collect_eq seq_def\n            resid_source_in_targets)\n      show \"\\<And>u t. \\<lbrakk>u \\<in> Collect ide; seq t u\\<rbrakk> \\<Longrightarrow> \\<exists>v. composite_of t u v\"\n        by (metis arrE composite_of_arr_target in_sourcesI seqE mem_Collect_eq)\n    qed\n\n    lemma identities_form_normal_sub_rts:\n    shows \"normal_sub_rts resid (Collect ide)\"\n      ..\n\n    interpretation coherent_normal_sub_rts resid \\<open>Collect ide\\<close>\n      apply unfold_locales\n      by (metis CollectD Cong\\<^sub>0_reflexive Cong_closure_props(4) Cong_imp_arr(2)\n                arr_resid_iff_con resid_arr_ide)\n\n    lemma identities_form_coherent_normal_sub_rts:\n    shows \"coherent_normal_sub_rts resid (Collect ide)\"\n      ..\n \n    lemma Cong_iff_cong:\n    shows \"Cong t u \\<longleftrightarrow> t \\<sim> u\"\n      by (metis CollectD Cong_def ide_closed resid_arr_ide\n          Cong_closure_props(3) Cong_imp_arr(2) arr_resid_iff_con)\n\n  end\n\n  section \"Paths\"\n\n  text \\<open>\n    A \\emph{path} in an RTS is a nonempty list of arrows such that the set\n    of targets of each arrow suitably matches the set of sources of its successor.\n    The residuation on the given RTS extends inductively to a residuation on\n    paths, so that paths also form an RTS.  The append operation on lists\n    yields a composite for each pair of compatible paths.\n  \\<close>\n\n  locale paths_in_rts =\n    R: rts\n  begin\n\n    fun Srcs\n    where \"Srcs [] = {}\"\n        | \"Srcs [t] = R.sources t\"\n        | \"Srcs (t # T) = R.sources t\"\n\n    fun Trgs\n    where \"Trgs [] = {}\"\n        | \"Trgs [t] = R.targets t\"\n        | \"Trgs (t # T) = Trgs T\"\n\n    fun Arr\n    where \"Arr [] = False\"\n        | \"Arr [t] = R.arr t\"\n        | \"Arr (t # T) = (R.arr t \\<and> Arr T \\<and> R.targets t \\<subseteq> Srcs T)\"\n\n    fun Ide\n    where \"Ide [] = False\"\n        | \"Ide [t] = R.ide t\"\n        | \"Ide (t # T) = (R.ide t \\<and> Ide T \\<and> R.targets t \\<subseteq> Srcs T)\"\n\n    lemma set_Arr_subset_arr:\n    shows \"Arr T \\<Longrightarrow> set T \\<subseteq> Collect R.arr\"\n      apply (induct T)\n       apply auto\n      using Arr.elims(2)\n       apply blast\n      by (metis Arr.simps(3) Ball_Collect list.set_cases)\n\n    lemma Arr_imp_arr_hd [simp]:\n    assumes \"Arr T\"\n    shows \"R.arr (hd T)\"\n      using assms\n      by (metis Arr.simps(1) CollectD hd_in_set set_Arr_subset_arr subset_code(1))\n\n    lemma Arr_imp_arr_last [simp]:\n    assumes \"Arr T\"\n    shows \"R.arr (last T)\"\n      using assms\n      by (metis Arr.simps(1) CollectD in_mono last_in_set set_Arr_subset_arr)\n\n    lemma Arr_imp_Arr_tl [simp]:\n    assumes \"Arr T\" and \"tl T \\<noteq> []\"\n    shows \"Arr (tl T)\"\n      using assms\n      by (metis Arr.simps(3) list.exhaust_sel list.sel(2))\n\n    lemma set_Ide_subset_ide:\n    shows \"Ide T \\<Longrightarrow> set T \\<subseteq> Collect R.ide\"\n      apply (induct T)\n       apply auto\n      using Ide.elims(2)\n       apply blast\n      by (metis Ide.simps(3) Ball_Collect list.set_cases)\n\n    lemma Ide_imp_Ide_hd [simp]:\n    assumes \"Ide T\"\n    shows \"R.ide (hd T)\"\n      using assms\n      by (metis Ide.simps(1) CollectD hd_in_set set_Ide_subset_ide subset_code(1))\n\n    lemma Ide_imp_Ide_last [simp]:\n    assumes \"Ide T\"\n    shows \"R.ide (last T)\"\n      using assms\n      by (metis Ide.simps(1) CollectD in_mono last_in_set set_Ide_subset_ide)\n\n    lemma Ide_imp_Ide_tl [simp]:\n    assumes \"Ide T\" and \"tl T \\<noteq> []\"\n    shows \"Ide (tl T)\"\n      using assms\n      by (metis Ide.simps(3) list.exhaust_sel list.sel(2))\n\n    lemma Ide_implies_Arr:\n    shows \"Ide T \\<Longrightarrow> Arr T\"\n      apply (induct T)\n       apply simp\n      using Ide.elims(2) by fastforce\n\n    lemma const_ide_is_Ide:\n    shows \"\\<lbrakk>T \\<noteq> []; R.ide (hd T); set T \\<subseteq> {hd T}\\<rbrakk> \\<Longrightarrow> Ide T\"\n      apply (induct T)\n       apply auto\n      by (metis Ide.simps(2-3) R.ideE R.sources_resid Srcs.simps(2-3) empty_iff insert_iff\n          list.exhaust_sel list.set_sel(1) order_refl subset_singletonD)\n\n    lemma Ide_char:\n    shows \"Ide T \\<longleftrightarrow> Arr T \\<and> set T \\<subseteq> Collect R.ide\"\n      apply (induct T)\n       apply auto[1]\n      by (metis Arr.simps(3) Ide.simps(2-3) Ide_implies_Arr empty_subsetI\n          insert_subset list.simps(15) mem_Collect_eq neq_Nil_conv set_empty)\n\n    lemma IdeI [intro]:\n    assumes \"Arr T\" and \"set T \\<subseteq> Collect R.ide\"\n    shows \"Ide T\"\n      using assms Ide_char by force\n\n    lemma Arr_has_Src:\n    shows \"Arr T \\<Longrightarrow> Srcs T \\<noteq> {}\"\n      apply (cases T)\n       apply simp\n      by (metis R.arr_iff_has_source Srcs.elims Arr.elims(2) list.distinct(1) list.sel(1))\n\n    lemma Arr_has_Trg:\n    shows \"Arr T \\<Longrightarrow> Trgs T \\<noteq> {}\"\n      using R.arr_iff_has_target\n      apply (induct T)\n       apply simp\n      by (metis Arr.simps(2) Arr.simps(3) Trgs.simps(2-3) list.exhaust_sel)\n\n    lemma Srcs_are_ide:\n    shows \"Srcs T \\<subseteq> Collect R.ide\"\n      apply (cases T)\n       apply simp\n      by (metis (no_types, lifting) Srcs.elims list.distinct(1) mem_Collect_eq\n          R.sources_def subsetI)\n\n    lemma Trgs_are_ide:\n    shows \"Trgs T \\<subseteq> Collect R.ide\"\n      apply (induct T)\n       apply simp\n      by (metis R.arr_iff_has_target R.sources_resid Srcs.simps(2) Trgs.simps(2-3)\n                Srcs_are_ide empty_subsetI list.exhaust R.arrE)\n\n    lemma Srcs_are_con:\n    assumes \"a \\<in> Srcs T\" and \"a' \\<in> Srcs T\"\n    shows \"a \\<frown> a'\"\n      using assms\n      by (metis Srcs.elims empty_iff R.sources_are_con)\n\n    lemma Srcs_con_closed:\n    assumes \"a \\<in> Srcs T\" and \"R.ide a'\" and \"a \\<frown> a'\"\n    shows \"a' \\<in> Srcs T\"\n      using assms R.sources_con_closed\n      apply (cases T, auto)\n      by (metis Srcs.simps(2-3) neq_Nil_conv)\n\n    lemma Srcs_eqI:\n    assumes \"Srcs T \\<inter> Srcs T' \\<noteq> {}\"\n    shows \"Srcs T = Srcs T'\"\n      using assms R.sources_eqI\n      apply (cases T; cases T')\n         apply auto\n       apply (metis IntI Srcs.simps(2-3) empty_iff neq_Nil_conv)\n      by (metis Srcs.simps(2-3) assms neq_Nil_conv)\n\n    lemma Trgs_are_con:\n    shows \"\\<lbrakk>b \\<in> Trgs T; b' \\<in> Trgs T\\<rbrakk> \\<Longrightarrow> b \\<frown> b'\"\n      apply (induct T)\n       apply auto\n      by (metis R.targets_are_con Trgs.simps(2-3) list.exhaust_sel)\n\n    lemma Trgs_con_closed:\n    shows \"\\<lbrakk>b \\<in> Trgs T; R.ide b'; b \\<frown> b'\\<rbrakk> \\<Longrightarrow> b' \\<in> Trgs T\"\n      apply (induct T)\n       apply auto\n      by (metis R.targets_con_closed Trgs.simps(2-3) neq_Nil_conv)\n\n    lemma Trgs_eqI:\n    assumes \"Trgs T \\<inter> Trgs T' \\<noteq> {}\"\n    shows \"Trgs T = Trgs T'\"\n      using assms Trgs_are_ide Trgs_are_con Trgs_con_closed by blast\n\n    lemma Srcs_simp\\<^sub>P:\n    assumes \"Arr T\"\n    shows \"Srcs T = R.sources (hd T)\"\n      using assms\n      by (metis Arr_has_Src Srcs.simps(1) Srcs.simps(2) Srcs.simps(3) list.exhaust_sel)\n\n    lemma Trgs_simp\\<^sub>P:\n    shows \"Arr T \\<Longrightarrow> Trgs T = R.targets (last T)\"\n      apply (induct T)\n       apply simp\n      by (metis Arr.simps(3) Trgs.simps(2) Trgs.simps(3) last_ConsL last_ConsR neq_Nil_conv)\n\n    subsection \"Residuation on Paths\"\n\n    text \\<open>\n      It was more difficult than I thought to get a correct formal definition for residuation\n      on paths and to prove things from it.  Straightforward attempts to write a single\n      recursive definition ran into problems with being able to prove termination,\n      as well as getting the cases correct so that the domain of definition was symmetric.\n      Eventually I found the definition below, which simplifies the termination proof\n      to some extent through the use of two auxiliary functions, and which has a\n      symmetric form that makes symmetry easier to prove.  However, there was still\n      some difficulty in proving the recursive expansions with respect to cons and\n      append that I needed.\n    \\<close>\n\n    text \\<open>\n      The following defines residuation of a single transition along a path, yielding a transition.\n    \\<close>\n\n    fun Resid1x  (infix \"\\<^sup>1\\\\\\<^sup>*\" 70)\n    where \"t \\<^sup>1\\\\\\<^sup>* [] = R.null\"\n        | \"t \\<^sup>1\\\\\\<^sup>* [u] = t \\\\ u\"\n        | \"t \\<^sup>1\\\\\\<^sup>* (u # U) = (t \\\\ u) \\<^sup>1\\\\\\<^sup>* U\"\n\n    text \\<open>\n      Next, we have residuation of a path along a single transition, yielding a path.\n    \\<close>\n\n    fun Residx1  (infix \"\\<^sup>*\\\\\\<^sup>1\" 70)\n    where \"[] \\<^sup>*\\\\\\<^sup>1 u = []\"\n        | \"[t] \\<^sup>*\\\\\\<^sup>1 u = (if t \\<frown> u then [t \\\\ u] else [])\"\n        | \"(t # T) \\<^sup>*\\\\\\<^sup>1 u =\n             (if t \\<frown> u \\<and> T \\<^sup>*\\\\\\<^sup>1 (u \\\\ t) \\<noteq> [] then (t \\\\ u) # T \\<^sup>*\\\\\\<^sup>1 (u \\\\ t) else [])\"\n\n    text \\<open>\n      Finally, residuation of a path along a path, yielding a path.\n    \\<close>\n\n    function (sequential) Resid  (infix \"\\<^sup>*\\\\\\<^sup>*\" 70)\n    where \"[] \\<^sup>*\\\\\\<^sup>* _ = []\"\n        | \"_ \\<^sup>*\\\\\\<^sup>* [] = []\"\n        | \"[t] \\<^sup>*\\\\\\<^sup>* [u] = (if t \\<frown> u then [t \\\\ u] else [])\"\n        | \"[t] \\<^sup>*\\\\\\<^sup>* (u # U) =\n             (if t \\<frown> u \\<and> (t \\\\ u) \\<^sup>1\\\\\\<^sup>* U \\<noteq> R.null then [(t \\\\ u) \\<^sup>1\\\\\\<^sup>* U] else [])\"\n        | \"(t # T) \\<^sup>*\\\\\\<^sup>* [u] =\n             (if t \\<frown> u \\<and> T \\<^sup>*\\\\\\<^sup>1 (u \\\\ t) \\<noteq> [] then (t \\\\ u) # (T \\<^sup>*\\\\\\<^sup>1 (u \\\\ t)) else [])\"\n        | \"(t # T) \\<^sup>*\\\\\\<^sup>* (u # U) =\n             (if t \\<frown> u \\<and> (t \\\\ u) \\<^sup>1\\\\\\<^sup>* U \\<noteq> R.null \\<and>\n                 (T \\<^sup>*\\\\\\<^sup>1 (u \\\\ t)) \\<^sup>*\\\\\\<^sup>* (U \\<^sup>*\\\\\\<^sup>1 (t \\\\ u)) \\<noteq> []\n              then (t \\\\ u) \\<^sup>1\\\\\\<^sup>* U # (T \\<^sup>*\\\\\\<^sup>1 (u \\\\ t)) \\<^sup>*\\\\\\<^sup>* (U \\<^sup>*\\\\\\<^sup>1 (t \\\\ u))\n              else [])\"\n      by pat_completeness auto\n\n    text \\<open>\n      Residuation of a path along a single transition is length non-increasing.\n      Actually, it is length-preserving, except in case the path and the transition\n      are not consistent.  We will show that later, but for now this is what we\n      need to establish termination for (\\<open>\\\\<close>).\n    \\<close>\n\n    lemma length_Residx1:\n    shows \"length (T \\<^sup>*\\\\\\<^sup>1 u) \\<le> length T\"\n    proof (induct T arbitrary: u)\n      show \"\\<And>u. length ([] \\<^sup>*\\\\\\<^sup>1 u) \\<le> length []\"\n        by simp\n      fix t T u\n      assume ind: \"\\<And>u. length (T \\<^sup>*\\\\\\<^sup>1 u) \\<le> length T\"\n      show \"length ((t # T) \\<^sup>*\\\\\\<^sup>1 u) \\<le> length (t # T)\"\n        using ind\n        by (cases T, cases \"t \\<frown> u\", cases \"T \\<^sup>*\\\\\\<^sup>1 (u \\\\ t)\") auto\n    qed\n\n    termination Resid\n    proof (relation \"measure (\\<lambda>(T, U). length T + length U)\")\n      show \"wf (measure (\\<lambda>(T, U). length T + length U))\"\n        by simp\n      fix t t' T u U\n      have \"length ((t' # T) \\<^sup>*\\\\\\<^sup>1 (u \\\\ t)) + length (U \\<^sup>*\\\\\\<^sup>1 (t \\\\ u))\n              < length (t # t' # T) + length (u # U)\"\n        using length_Residx1\n        by (metis add_less_le_mono impossible_Cons le_neq_implies_less list.size(4) trans_le_add1)\n      thus 1: \"(((t' # T) \\<^sup>*\\\\\\<^sup>1 (u \\\\ t), U \\<^sup>*\\\\\\<^sup>1 (t \\\\ u)), t # t' # T, u # U)\n                 \\<in> measure (\\<lambda>(T, U). length T + length U)\"\n        by simp\n      show \"(((t' # T) \\<^sup>*\\\\\\<^sup>1 (u \\\\ t), U \\<^sup>*\\\\\\<^sup>1 (t \\\\ u)), t # t' # T, u # U)\n              \\<in> measure (\\<lambda>(T, U). length T + length U)\"\n        using 1 length_Residx1 by blast\n      have \"length (T \\<^sup>*\\\\\\<^sup>1 (u \\\\ t)) + length (U \\<^sup>*\\\\\\<^sup>1 (t \\\\ u)) \\<le> length T + length U\"\n        using length_Residx1 by (simp add: add_mono)\n      thus 2: \"((T \\<^sup>*\\\\\\<^sup>1 (u \\\\ t), U \\<^sup>*\\\\\\<^sup>1 (t \\\\ u)), t # T, u # U)\n                 \\<in> measure (\\<lambda>(T, U). length T + length U)\"\n        by simp\n      show \"((T \\<^sup>*\\\\\\<^sup>1 (u \\\\ t), U \\<^sup>*\\\\\\<^sup>1 (t \\\\ u)), t # T, u # U)\n               \\<in> measure (\\<lambda>(T, U). length T + length U)\"\n        using 2 length_Residx1 by blast\n    qed\n\n    lemma Resid1x_null:\n    shows \"R.null \\<^sup>1\\\\\\<^sup>* T = R.null\"\n      apply (induct T)\n       apply auto\n      by (metis R.null_is_zero(1) Resid1x.simps(2-3) list.exhaust)\n\n    lemma Resid1x_ide:\n    shows \"\\<lbrakk>R.ide a; a \\<^sup>1\\\\\\<^sup>* T \\<noteq> R.null\\<rbrakk> \\<Longrightarrow> R.ide (a \\<^sup>1\\\\\\<^sup>* T)\"\n    proof (induct T arbitrary: a)\n      show \"\\<And>a. a \\<^sup>1\\\\\\<^sup>* [] \\<noteq> R.null \\<Longrightarrow> R.ide (a \\<^sup>1\\\\\\<^sup>* [])\"\n        by simp\n      fix a t T\n      assume a: \"R.ide a\"\n      assume ind: \"\\<And>a. \\<lbrakk>R.ide a; a \\<^sup>1\\\\\\<^sup>* T \\<noteq> R.null\\<rbrakk> \\<Longrightarrow> R.ide (a \\<^sup>1\\\\\\<^sup>* T)\"\n      assume con: \"a \\<^sup>1\\\\\\<^sup>* (t # T) \\<noteq> R.null\"\n      have 1: \"a \\<frown> t\"\n        using con\n        by (metis R.con_def Resid1x.simps(2-3) Resid1x_null list.exhaust)\n      show \"R.ide (a \\<^sup>1\\\\\\<^sup>* (t # T))\"\n        using a 1 con ind R.resid_ide_arr\n        by (metis Resid1x.simps(2-3) list.exhaust)\n    qed\n\n    (*\n     * TODO: Try to make this a definition, rather than an abbreviation.\n     *\n     * I made an attempt at this, but there are many, many places where the\n     * definition needs to be unwound.  It is not clear how valuable it might\n     * end up being to have this as a definition.\n     *)\n    abbreviation Con  (infix \"\\<^sup>*\\<frown>\\<^sup>*\" 50)\n    where \"T \\<^sup>*\\<frown>\\<^sup>* U \\<equiv> T \\<^sup>*\\\\\\<^sup>* U \\<noteq> []\"\n\n    lemma Con_sym1:\n    shows \"T \\<^sup>*\\\\\\<^sup>1 u \\<noteq> [] \\<longleftrightarrow> u \\<^sup>1\\\\\\<^sup>* T \\<noteq> R.null\"\n    proof (induct T arbitrary: u)\n      show \"\\<And>u. [] \\<^sup>*\\\\\\<^sup>1 u \\<noteq> [] \\<longleftrightarrow> u \\<^sup>1\\\\\\<^sup>* [] \\<noteq> R.null\"\n        by simp\n      show \"\\<And>t T u. (\\<And>u. T \\<^sup>*\\\\\\<^sup>1 u \\<noteq> [] \\<longleftrightarrow> u \\<^sup>1\\\\\\<^sup>* T \\<noteq> R.null)\n                        \\<Longrightarrow> (t # T) \\<^sup>*\\\\\\<^sup>1 u \\<noteq> [] \\<longleftrightarrow> u \\<^sup>1\\\\\\<^sup>* (t # T) \\<noteq> R.null\"\n      proof -\n        fix t T u\n        assume ind: \"\\<And>u. T \\<^sup>*\\\\\\<^sup>1 u \\<noteq> [] \\<longleftrightarrow> u \\<^sup>1\\\\\\<^sup>* T \\<noteq> R.null\"\n        show \"(t # T) \\<^sup>*\\\\\\<^sup>1 u \\<noteq> [] \\<longleftrightarrow> u \\<^sup>1\\\\\\<^sup>* (t # T) \\<noteq> R.null\"\n        proof\n          show \"(t # T) \\<^sup>*\\\\\\<^sup>1 u \\<noteq> [] \\<Longrightarrow> u \\<^sup>1\\\\\\<^sup>* (t # T) \\<noteq> R.null\"\n            by (metis R.con_sym Resid1x.simps(2-3) Residx1.simps(2-3)\n                ind neq_Nil_conv R.conE)\n          show \"u \\<^sup>1\\\\\\<^sup>* (t # T) \\<noteq> R.null \\<Longrightarrow> (t # T) \\<^sup>*\\\\\\<^sup>1 u \\<noteq> []\"\n            using ind R.con_sym\n            apply (cases T)\n             apply auto\n            by (metis R.conI Resid1x_null)\n        qed\n      qed\n    qed\n\n    lemma Con_sym_ind:\n    shows \"length T + length U \\<le> n \\<Longrightarrow> T \\<^sup>*\\<frown>\\<^sup>* U \\<longleftrightarrow> U \\<^sup>*\\<frown>\\<^sup>* T\"\n    proof (induct n arbitrary: T U)\n      show \"\\<And>T U. length T + length U \\<le> 0 \\<Longrightarrow> T \\<^sup>*\\<frown>\\<^sup>* U \\<longleftrightarrow> U \\<^sup>*\\<frown>\\<^sup>* T\"\n        by simp\n      fix n and T U :: \"'a list\"\n      assume ind: \"\\<And>T U. length T + length U \\<le> n \\<Longrightarrow> T \\<^sup>*\\<frown>\\<^sup>* U \\<longleftrightarrow> U \\<^sup>*\\<frown>\\<^sup>* T\"\n      assume 1: \"length T + length U \\<le> Suc n\"\n      show \"T \\<^sup>*\\<frown>\\<^sup>* U \\<longleftrightarrow> U \\<^sup>*\\<frown>\\<^sup>* T\"\n        using R.con_sym Con_sym1\n          apply (cases T; cases U)\n           apply auto[3]\n      proof -\n        fix t u T' U'\n        assume T: \"T = t # T'\" and U: \"U = u # U'\"\n        show \"T \\<^sup>*\\<frown>\\<^sup>* U \\<longleftrightarrow> U \\<^sup>*\\<frown>\\<^sup>* T\"\n        proof (cases \"T' = []\")\n          show \"T' = [] \\<Longrightarrow> T \\<^sup>*\\<frown>\\<^sup>* U \\<longleftrightarrow> U \\<^sup>*\\<frown>\\<^sup>* T\"\n            using T U Con_sym1 R.con_sym\n            by (cases U') auto\n          show \"T' \\<noteq> [] \\<Longrightarrow> T \\<^sup>*\\<frown>\\<^sup>* U \\<longleftrightarrow> U \\<^sup>*\\<frown>\\<^sup>* T\"\n          proof (cases \"U' = []\")\n            show \"\\<lbrakk>T' \\<noteq> []; U' = []\\<rbrakk> \\<Longrightarrow> T \\<^sup>*\\<frown>\\<^sup>* U \\<longleftrightarrow> U \\<^sup>*\\<frown>\\<^sup>* T\"\n              using T U R.con_sym Con_sym1\n              by (cases T') auto\n            show \"\\<lbrakk>T' \\<noteq> []; U' \\<noteq> []\\<rbrakk> \\<Longrightarrow> T \\<^sup>*\\<frown>\\<^sup>* U \\<longleftrightarrow> U \\<^sup>*\\<frown>\\<^sup>* T\"\n            proof -\n              assume T': \"T' \\<noteq> []\" and U': \"U' \\<noteq> []\"\n              have 2: \"length (U' \\<^sup>*\\\\\\<^sup>1 (t \\\\ u)) + length (T' \\<^sup>*\\\\\\<^sup>1 (u \\\\ t)) \\<le> n\"\n              proof -\n                have \"length (U' \\<^sup>*\\\\\\<^sup>1 (t \\\\ u)) + length (T' \\<^sup>*\\\\\\<^sup>1 (u \\\\ t))\n                         \\<le> length U' + length T'\"\n                  by (simp add: add_le_mono length_Residx1)\n                also have \"... \\<le> length T' + length U'\"\n                  using T' add.commute not_less_eq_eq by auto\n                also have \"... \\<le> n\"\n                  using 1 T U by simp\n                finally show ?thesis by blast\n              qed\n              show \"T \\<^sup>*\\<frown>\\<^sup>* U \\<longleftrightarrow> U \\<^sup>*\\<frown>\\<^sup>* T\"\n              proof\n                assume Con: \"T \\<^sup>*\\<frown>\\<^sup>* U\"\n                have 3: \"t \\<frown> u \\<and> T' \\<^sup>*\\\\\\<^sup>1 (u \\\\ t) \\<noteq> [] \\<and> (t \\\\ u) \\<^sup>1\\\\\\<^sup>* U' \\<noteq> R.null \\<and>\n                         (T' \\<^sup>*\\\\\\<^sup>1 (u \\\\ t)) \\<^sup>*\\\\\\<^sup>* (U' \\<^sup>*\\\\\\<^sup>1 (t \\\\ u)) \\<noteq> []\"\n                  using Con T U T' U' Con_sym1\n                  apply (cases T', cases U')\n                    apply simp_all\n                  by (metis Resid.simps(1) Resid.simps(6) neq_Nil_conv)\n                hence \"u \\<frown> t \\<and> U' \\<^sup>*\\\\\\<^sup>1 (t \\\\ u) \\<noteq> [] \\<and> (u \\\\ t) \\<^sup>1\\\\\\<^sup>* T' \\<noteq> R.null\"\n                  using T' U' R.con_sym Con_sym1 by simp\n                moreover have \"(U' \\<^sup>*\\\\\\<^sup>1 (t \\\\ u)) \\<^sup>*\\\\\\<^sup>* (T' \\<^sup>*\\\\\\<^sup>1 (u \\\\ t)) \\<noteq> []\"\n                  using 2 3 ind by simp\n                ultimately show \"U \\<^sup>*\\<frown>\\<^sup>* T\"\n                  using T U T' U'\n                  by (cases T'; cases U') auto\n                next\n                assume Con: \"U \\<^sup>*\\<frown>\\<^sup>* T\"\n                have 3: \"u \\<frown> t \\<and> U' \\<^sup>*\\\\\\<^sup>1 (t \\\\ u) \\<noteq> [] \\<and> (u \\\\ t) \\<^sup>1\\\\\\<^sup>* T' \\<noteq> R.null \\<and>\n                         (U' \\<^sup>*\\\\\\<^sup>1 (t \\\\ u)) \\<^sup>*\\\\\\<^sup>* (T' \\<^sup>*\\\\\\<^sup>1 (u \\\\ t)) \\<noteq> []\"\n                  using Con T U T' U' Con_sym1\n                  apply (cases T'; cases U')\n                     apply auto\n                   apply argo\n                  by force\n                hence \"t \\<frown> u \\<and> T' \\<^sup>*\\\\\\<^sup>1 (u \\\\ t) \\<noteq> [] \\<and> (t \\\\ u) \\<^sup>1\\\\\\<^sup>* U' \\<noteq> R.null\"\n                  using T' U' R.con_sym Con_sym1 by simp\n                moreover have \"(T' \\<^sup>*\\\\\\<^sup>1 (u \\\\ t)) \\<^sup>*\\\\\\<^sup>* (U' \\<^sup>*\\\\\\<^sup>1 (t \\\\ u)) \\<noteq> []\"\n                  using 2 3 ind by simp\n                ultimately show \"T \\<^sup>*\\<frown>\\<^sup>* U\"\n                  using T U T' U'\n                  by (cases T'; cases U') auto\n              qed\n            qed\n          qed\n        qed\n      qed\n    qed\n\n    lemma Con_sym:\n    shows \"T \\<^sup>*\\<frown>\\<^sup>* U \\<longleftrightarrow> U \\<^sup>*\\<frown>\\<^sup>* T\"\n      using Con_sym_ind by blast\n\n    lemma Residx1_as_Resid:\n    shows \"T \\<^sup>*\\\\\\<^sup>1 u = T \\<^sup>*\\\\\\<^sup>* [u]\"\n    proof (induct T)\n      show \"[] \\<^sup>*\\\\\\<^sup>1 u = [] \\<^sup>*\\\\\\<^sup>* [u]\" by simp\n      fix t T\n      assume ind: \"T \\<^sup>*\\\\\\<^sup>1 u = T \\<^sup>*\\\\\\<^sup>* [u]\"\n      show \"(t # T) \\<^sup>*\\\\\\<^sup>1 u = (t # T) \\<^sup>*\\\\\\<^sup>* [u]\"\n        by (cases T) auto\n    qed\n\n    lemma Resid1x_as_Resid':\n    shows \"t \\<^sup>1\\\\\\<^sup>* U = (if [t] \\<^sup>*\\\\\\<^sup>* U \\<noteq> [] then hd ([t] \\<^sup>*\\\\\\<^sup>* U) else R.null)\"\n    proof (induct U)\n      show \"t \\<^sup>1\\\\\\<^sup>* [] = (if [t] \\<^sup>*\\\\\\<^sup>* [] \\<noteq> [] then hd ([t] \\<^sup>*\\\\\\<^sup>* []) else R.null)\" by simp\n      fix u U\n      assume ind: \"t \\<^sup>1\\\\\\<^sup>* U = (if [t] \\<^sup>*\\\\\\<^sup>* U \\<noteq> [] then hd ([t] \\<^sup>*\\\\\\<^sup>* U) else R.null)\"\n      show \"t \\<^sup>1\\\\\\<^sup>* (u # U) = (if [t] \\<^sup>*\\\\\\<^sup>* (u # U) \\<noteq> [] then hd ([t] \\<^sup>*\\\\\\<^sup>* (u # U)) else R.null)\"\n        using Resid1x_null\n        by (cases U) auto\n    qed\n\n    text \\<open>\n      The following recursive expansion for consistency of paths is an intermediate\n      result that is not yet quite in the form we really want.\n    \\<close>\n\n    lemma Con_rec:\n    shows \"[t] \\<^sup>*\\<frown>\\<^sup>* [u] \\<longleftrightarrow> t \\<frown> u\"\n    and \"T \\<noteq> [] \\<Longrightarrow> t # T \\<^sup>*\\<frown>\\<^sup>* [u] \\<longleftrightarrow> t \\<frown> u \\<and> T \\<^sup>*\\<frown>\\<^sup>* [u \\\\ t]\"\n    and \"U \\<noteq> [] \\<Longrightarrow> [t] \\<^sup>*\\<frown>\\<^sup>* (u # U) \\<longleftrightarrow> t \\<frown> u \\<and> [t \\\\ u] \\<^sup>*\\<frown>\\<^sup>* U\"\n    and \"\\<lbrakk>T \\<noteq> []; U \\<noteq> []\\<rbrakk> \\<Longrightarrow>\n           t # T \\<^sup>*\\<frown>\\<^sup>* u # U \\<longleftrightarrow> t \\<frown> u \\<and> T \\<^sup>*\\<frown>\\<^sup>* [u \\\\ t] \\<and> [t \\\\ u] \\<^sup>*\\<frown>\\<^sup>* U \\<and>\n                               T \\<^sup>*\\\\\\<^sup>* [u \\\\ t] \\<^sup>*\\<frown>\\<^sup>* U \\<^sup>*\\\\\\<^sup>* [t \\\\ u]\"\n    proof -\n      show \"[t] \\<^sup>*\\<frown>\\<^sup>* [u] \\<longleftrightarrow> t \\<frown> u\"\n        by simp\n      show \"T \\<noteq> [] \\<Longrightarrow> t # T \\<^sup>*\\<frown>\\<^sup>* [u] \\<longleftrightarrow> t \\<frown> u \\<and> T \\<^sup>*\\<frown>\\<^sup>* [u \\\\ t]\"\n        using Residx1_as_Resid\n        by (cases T) auto\n      show \"U \\<noteq> [] \\<Longrightarrow> [t] \\<^sup>*\\<frown>\\<^sup>* (u # U) \\<longleftrightarrow> t \\<frown> u \\<and> [t \\\\ u] \\<^sup>*\\<frown>\\<^sup>* U\"\n        using Resid1x_as_Resid' Con_sym Con_sym1 Resid1x.simps(3) Residx1_as_Resid\n        by (cases U) auto\n      show \"\\<lbrakk>T \\<noteq> []; U \\<noteq> []\\<rbrakk> \\<Longrightarrow>\n            t # T \\<^sup>*\\<frown>\\<^sup>* u # U \\<longleftrightarrow> t \\<frown> u \\<and> T \\<^sup>*\\<frown>\\<^sup>* [u \\\\ t] \\<and> [t \\\\ u] \\<^sup>*\\<frown>\\<^sup>* U \\<and>\n                               T \\<^sup>*\\\\\\<^sup>* [u \\\\ t] \\<^sup>*\\<frown>\\<^sup>* U \\<^sup>*\\\\\\<^sup>* [t \\\\ u]\"\n        using Residx1_as_Resid Resid1x_as_Resid' Con_sym1 Con_sym R.con_sym\n        by (cases T; cases U) auto\n    qed\n\n    text \\<open>\n      This version is a more appealing form of the previously proved fact \\<open>Resid1x_as_Resid'\\<close>.\n    \\<close>\n\n    lemma Resid1x_as_Resid:\n    assumes \"[t] \\<^sup>*\\\\\\<^sup>* U \\<noteq> []\"\n    shows \"[t] \\<^sup>*\\\\\\<^sup>* U = [t \\<^sup>1\\\\\\<^sup>* U]\"\n      using assms Con_rec(2,4)\n      apply (cases U; cases \"tl U\")\n         apply auto\n      by argo+  (* TODO: Why can auto no longer complete this proof? *)\n\n   text \\<open>\n     The following is an intermediate version of a recursive expansion for residuation,\n     to be improved subsequently.\n   \\<close>\n\n   lemma Resid_rec:\n    shows [simp]: \"[t] \\<^sup>*\\<frown>\\<^sup>* [u] \\<Longrightarrow> [t] \\<^sup>*\\\\\\<^sup>* [u] = [t \\\\ u]\"\n    and \"\\<lbrakk>T \\<noteq> []; t # T \\<^sup>*\\<frown>\\<^sup>* [u]\\<rbrakk> \\<Longrightarrow> (t # T) \\<^sup>*\\\\\\<^sup>* [u] = (t \\\\ u) # (T \\<^sup>*\\\\\\<^sup>* [u \\\\ t])\"\n    and \"\\<lbrakk>U \\<noteq> []; Con [t] (u # U)\\<rbrakk> \\<Longrightarrow> [t] \\<^sup>*\\\\\\<^sup>* (u # U) = [t \\\\ u] \\<^sup>*\\\\\\<^sup>* U\"\n    and \"\\<lbrakk>T \\<noteq> []; U \\<noteq> []; Con (t # T) (u # U)\\<rbrakk> \\<Longrightarrow>\n         (t # T) \\<^sup>*\\\\\\<^sup>* (u # U) = ([t \\\\ u] \\<^sup>*\\\\\\<^sup>* U) @ ((T \\<^sup>*\\\\\\<^sup>* [u \\\\ t]) \\<^sup>*\\\\\\<^sup>* (U \\<^sup>*\\\\\\<^sup>* [t \\\\ u]))\"\n    proof -\n      show \"[t] \\<^sup>*\\<frown>\\<^sup>* [u] \\<Longrightarrow> Resid [t] [u] = [t \\\\ u]\"\n        by (meson Resid.simps(3))\n      show \"\\<lbrakk>T \\<noteq> []; t # T \\<^sup>*\\<frown>\\<^sup>* [u]\\<rbrakk> \\<Longrightarrow> (t # T) \\<^sup>*\\\\\\<^sup>* [u] = (t \\\\ u) # (T \\<^sup>*\\\\\\<^sup>* [u \\\\ t])\"\n        using Residx1_as_Resid\n        by (metis Residx1.simps(3) list.exhaust_sel)\n      show 1: \"\\<lbrakk>U \\<noteq> []; [t] \\<^sup>*\\<frown>\\<^sup>* u # U\\<rbrakk> \\<Longrightarrow> [t] \\<^sup>*\\\\\\<^sup>* (u # U) = [t \\\\ u] \\<^sup>*\\\\\\<^sup>* U\"\n        by (metis Con_rec(3) Resid1x.simps(3) Resid1x_as_Resid list.exhaust)\n      show \"\\<lbrakk>T \\<noteq> []; U \\<noteq> []; t # T \\<^sup>*\\<frown>\\<^sup>* u # U\\<rbrakk> \\<Longrightarrow>\n             (t # T) \\<^sup>*\\\\\\<^sup>* (u # U) = ([t \\\\ u] \\<^sup>*\\\\\\<^sup>* U) @ ((T \\<^sup>*\\\\\\<^sup>* [u \\\\ t]) \\<^sup>*\\\\\\<^sup>* (U \\<^sup>*\\\\\\<^sup>* [t \\\\ u]))\"\n      proof -\n        assume T: \"T \\<noteq> []\" and U: \"U \\<noteq> []\" and Con: \"Con (t # T) (u # U)\"\n        have tu: \"t \\<frown> u\"\n          using Con Con_rec by metis\n        have \"(t # T) \\<^sup>*\\\\\\<^sup>* (u # U) = ((t \\\\ u) \\<^sup>1\\\\\\<^sup>* U) # ((T \\<^sup>*\\\\\\<^sup>1 (u \\\\ t)) \\<^sup>*\\\\\\<^sup>* (U \\<^sup>*\\\\\\<^sup>1 (t \\\\ u)))\"\n          using T U Con tu\n          by (cases T; cases U) auto\n        also have \"... = ([t \\\\ u] \\<^sup>*\\\\\\<^sup>* U) @ ((T \\<^sup>*\\\\\\<^sup>* [u \\\\ t]) \\<^sup>*\\\\\\<^sup>* (U \\<^sup>*\\\\\\<^sup>* [t \\\\ u]))\"\n          using T U Con tu Con_rec(4) Resid1x_as_Resid Residx1_as_Resid by force\n        finally show ?thesis by simp\n      qed\n    qed\n\n    text \\<open>\n      For consistent paths, residuation is length-preserving.\n    \\<close>\n\n    lemma length_Resid_ind:\n    shows \"\\<lbrakk>length T + length U \\<le> n; T \\<^sup>*\\<frown>\\<^sup>* U\\<rbrakk> \\<Longrightarrow> length (T \\<^sup>*\\\\\\<^sup>* U) = length T\"\n      apply (induct n arbitrary: T U)\n       apply simp\n    proof -\n      fix n T U\n      assume ind: \"\\<And>T U. \\<lbrakk>length T + length U \\<le> n; T \\<^sup>*\\<frown>\\<^sup>* U\\<rbrakk>\n                            \\<Longrightarrow> length (T \\<^sup>*\\\\\\<^sup>* U) = length T\"\n      assume Con: \"T \\<^sup>*\\<frown>\\<^sup>* U\"\n      assume len: \"length T + length U \\<le> Suc n\"\n      show \"length (T \\<^sup>*\\\\\\<^sup>* U) = length T\"\n        using Con len ind Resid1x_as_Resid length_Cons Con_rec(2) Resid_rec(2)\n        apply (cases T; cases U)\n           apply auto\n        apply (cases \"tl T = []\"; cases \"tl U = []\")\n           apply auto\n          apply metis\n         apply fastforce\n      proof -\n        fix t T' u U'\n        assume T: \"T = t # T'\" and U: \"U = u # U'\"\n        assume T': \"T' \\<noteq> []\" and U': \"U' \\<noteq> []\"\n        show \"length ((t # T') \\<^sup>*\\\\\\<^sup>* (u # U')) = Suc (length T')\"\n          using Con Con_rec(4) Con_sym Resid_rec(4) T T' U U' ind len by auto\n      qed\n    qed\n\n    lemma length_Resid:\n    assumes \"T \\<^sup>*\\<frown>\\<^sup>* U\"\n    shows \"length (T \\<^sup>*\\\\\\<^sup>* U) = length T\"\n      using assms length_Resid_ind by auto\n\n    lemma Con_initial_left:\n    shows \"t # T \\<^sup>*\\<frown>\\<^sup>* U \\<Longrightarrow> [t] \\<^sup>*\\<frown>\\<^sup>* U\"\n      apply (induct U)\n       apply simp\n      by (metis Con_rec(1-4))\n\n    lemma Con_initial_right:\n    shows \"T \\<^sup>*\\<frown>\\<^sup>* u # U \\<Longrightarrow> T \\<^sup>*\\<frown>\\<^sup>* [u]\"\n      apply (induct T)\n        apply simp\n      by (metis Con_rec(1-4))\n\n    lemma Resid_cons_ind:\n    shows \"\\<lbrakk>T \\<noteq> []; U \\<noteq> []; length T + length U \\<le> n\\<rbrakk> \\<Longrightarrow>\n             (\\<forall>t. t # T \\<^sup>*\\<frown>\\<^sup>* U \\<longleftrightarrow> [t] \\<^sup>*\\<frown>\\<^sup>* U \\<and> T \\<^sup>*\\<frown>\\<^sup>* U \\<^sup>*\\\\\\<^sup>* [t]) \\<and>\n             (\\<forall>u. T \\<^sup>*\\<frown>\\<^sup>* u # U \\<longleftrightarrow> T \\<^sup>*\\<frown>\\<^sup>* [u] \\<and> T \\<^sup>*\\\\\\<^sup>* [u] \\<^sup>*\\<frown>\\<^sup>* U) \\<and>\n             (\\<forall>t. t # T \\<^sup>*\\<frown>\\<^sup>* U \\<longrightarrow> (t # T) \\<^sup>*\\\\\\<^sup>* U = [t] \\<^sup>*\\\\\\<^sup>* U @ T \\<^sup>*\\\\\\<^sup>* (U \\<^sup>*\\\\\\<^sup>* [t])) \\<and>\n             (\\<forall>u. T \\<^sup>*\\<frown>\\<^sup>* u # U \\<longrightarrow> T \\<^sup>*\\\\\\<^sup>* (u # U) = (T \\<^sup>*\\\\\\<^sup>* [u]) \\<^sup>*\\\\\\<^sup>* U)\"\n    proof (induct n arbitrary: T U)\n      show \"\\<And>T U. \\<lbrakk>T \\<noteq> []; U \\<noteq> []; length T + length U \\<le> 0\\<rbrakk> \\<Longrightarrow>\n                   (\\<forall>t. t # T \\<^sup>*\\<frown>\\<^sup>* U \\<longleftrightarrow> [t] \\<^sup>*\\<frown>\\<^sup>* U \\<and> T \\<^sup>*\\<frown>\\<^sup>* U \\<^sup>*\\\\\\<^sup>* [t]) \\<and>\n                   (\\<forall>u. T \\<^sup>*\\<frown>\\<^sup>* u # U \\<longleftrightarrow> T \\<^sup>*\\<frown>\\<^sup>* [u] \\<and> T \\<^sup>*\\\\\\<^sup>* [u] \\<^sup>*\\<frown>\\<^sup>* U) \\<and>\n                   (\\<forall>t. t # T \\<^sup>*\\<frown>\\<^sup>* U \\<longrightarrow> (t # T) \\<^sup>*\\\\\\<^sup>* U = [t] \\<^sup>*\\\\\\<^sup>* U @ T \\<^sup>*\\\\\\<^sup>* (U \\<^sup>*\\\\\\<^sup>* [t])) \\<and>\n                   (\\<forall>u. T \\<^sup>*\\<frown>\\<^sup>* u # U \\<longrightarrow> T \\<^sup>*\\\\\\<^sup>* (u # U) = (T \\<^sup>*\\\\\\<^sup>* [u]) \\<^sup>*\\\\\\<^sup>* U)\"\n        by simp\n      fix n and T U :: \"'a list\"\n      assume ind: \"\\<And>T U. \\<lbrakk>T \\<noteq> []; U \\<noteq> []; length T + length U \\<le> n\\<rbrakk> \\<Longrightarrow>\n                   (\\<forall>t. t # T \\<^sup>*\\<frown>\\<^sup>* U \\<longleftrightarrow> [t] \\<^sup>*\\<frown>\\<^sup>* U \\<and> T \\<^sup>*\\<frown>\\<^sup>* U \\<^sup>*\\\\\\<^sup>* [t]) \\<and>\n                   (\\<forall>u. T \\<^sup>*\\<frown>\\<^sup>* u # U \\<longleftrightarrow> T \\<^sup>*\\<frown>\\<^sup>* [u] \\<and> T \\<^sup>*\\\\\\<^sup>* [u] \\<^sup>*\\<frown>\\<^sup>* U) \\<and>\n                   (\\<forall>t. t # T \\<^sup>*\\<frown>\\<^sup>* U \\<longrightarrow> (t # T) \\<^sup>*\\\\\\<^sup>* U = [t] \\<^sup>*\\\\\\<^sup>* U @ T \\<^sup>*\\\\\\<^sup>* (U \\<^sup>*\\\\\\<^sup>* [t])) \\<and>\n                   (\\<forall>u. T \\<^sup>*\\<frown>\\<^sup>* u # U \\<longrightarrow> T \\<^sup>*\\\\\\<^sup>* (u # U) = (T \\<^sup>*\\\\\\<^sup>* [u]) \\<^sup>*\\\\\\<^sup>* U)\"\n      assume T: \"T \\<noteq> []\" and U: \"U \\<noteq> []\"\n      assume len: \"length T + length U \\<le> Suc n\"\n      show \"(\\<forall>t. t # T \\<^sup>*\\<frown>\\<^sup>* U \\<longleftrightarrow> [t] \\<^sup>*\\<frown>\\<^sup>* U \\<and> T \\<^sup>*\\<frown>\\<^sup>* U \\<^sup>*\\\\\\<^sup>* [t]) \\<and>\n            (\\<forall>u. T \\<^sup>*\\<frown>\\<^sup>* u # U \\<longleftrightarrow> T \\<^sup>*\\<frown>\\<^sup>* [u] \\<and> T \\<^sup>*\\\\\\<^sup>* [u] \\<^sup>*\\<frown>\\<^sup>* U) \\<and>\n            (\\<forall>t. t # T \\<^sup>*\\<frown>\\<^sup>* U \\<longrightarrow> (t # T) \\<^sup>*\\\\\\<^sup>* U = [t] \\<^sup>*\\\\\\<^sup>* U @ T \\<^sup>*\\\\\\<^sup>* (U \\<^sup>*\\\\\\<^sup>* [t])) \\<and>\n            (\\<forall>u. T \\<^sup>*\\<frown>\\<^sup>* u # U \\<longrightarrow> T \\<^sup>*\\\\\\<^sup>* (u # U) = (T \\<^sup>*\\\\\\<^sup>* [u]) \\<^sup>*\\\\\\<^sup>* U)\"\n      proof (intro allI conjI iffI impI)\n        fix t\n        show 1: \"t # T \\<^sup>*\\<frown>\\<^sup>* U \\<Longrightarrow> (t # T) \\<^sup>*\\\\\\<^sup>* U = [t] \\<^sup>*\\\\\\<^sup>* U @ T \\<^sup>*\\\\\\<^sup>* (U \\<^sup>*\\\\\\<^sup>* [t])\"\n        proof (cases U)\n          show \"U = [] \\<Longrightarrow> ?thesis\"\n            using U by simp\n          fix u U'\n          assume U: \"U = u # U'\"\n          assume Con: \"t # T \\<^sup>*\\<frown>\\<^sup>* U\"\n          show ?thesis\n          proof (cases \"U' = []\")\n            show \"U' = [] \\<Longrightarrow> ?thesis\"\n              using T U Con R.con_sym Con_rec(2) Resid_rec(2) by auto\n            assume U': \"U' \\<noteq> []\"\n            have \"(t # T) \\<^sup>*\\\\\\<^sup>* U = [t \\\\ u] \\<^sup>*\\\\\\<^sup>* U' @ (T \\<^sup>*\\\\\\<^sup>* [u \\\\ t]) \\<^sup>*\\\\\\<^sup>* (U' \\<^sup>*\\\\\\<^sup>* [t \\\\ u])\"\n              using T U U' Con Resid_rec(4) by fastforce\n            also have 1: \"... = [t] \\<^sup>*\\\\\\<^sup>* U @ (T \\<^sup>*\\\\\\<^sup>* [u \\\\ t]) \\<^sup>*\\\\\\<^sup>* (U' \\<^sup>*\\\\\\<^sup>* [t \\\\ u])\"\n              using T U U' Con Con_rec(3-4) Resid_rec(3) by auto\n            also have \"... = [t] \\<^sup>*\\\\\\<^sup>* U @ T \\<^sup>*\\\\\\<^sup>* ((u \\\\ t) # (U' \\<^sup>*\\\\\\<^sup>* [t \\\\ u]))\"\n            proof -\n              have \"T \\<^sup>*\\\\\\<^sup>* ((u \\\\ t) # (U' \\<^sup>*\\\\\\<^sup>* [t \\\\ u])) = (T \\<^sup>*\\\\\\<^sup>* [u \\\\ t]) \\<^sup>*\\\\\\<^sup>* (U' \\<^sup>*\\\\\\<^sup>* [t \\\\ u])\"\n                using T U U' ind [of T \"U' \\<^sup>*\\\\\\<^sup>* [t \\\\ u]\"] Con Con_rec(4) Con_sym len length_Resid\n                by fastforce\n              thus ?thesis by auto\n            qed\n            also have \"... = [t] \\<^sup>*\\\\\\<^sup>* U @ T \\<^sup>*\\\\\\<^sup>* (U \\<^sup>*\\\\\\<^sup>* [t])\"\n              using T U U' 1 Con Con_rec(4) Con_sym1 Residx1_as_Resid\n                    Resid1x_as_Resid Resid_rec(2) Con_sym Con_initial_left\n              by auto\n            finally show ?thesis by simp\n          qed\n        qed\n        show \"t # T \\<^sup>*\\<frown>\\<^sup>* U \\<Longrightarrow> [t] \\<^sup>*\\<frown>\\<^sup>* U\"\n          by (simp add: Con_initial_left)\n        show \"t # T \\<^sup>*\\<frown>\\<^sup>* U \\<Longrightarrow> T \\<^sup>*\\<frown>\\<^sup>* (U \\<^sup>*\\\\\\<^sup>* [t])\"\n          by (metis \"1\" Suc_inject T append_Nil2 length_0_conv length_Cons length_Resid)\n        show \"[t] \\<^sup>*\\<frown>\\<^sup>* U \\<and> T \\<^sup>*\\<frown>\\<^sup>* U \\<^sup>*\\\\\\<^sup>* [t] \\<Longrightarrow> t # T \\<^sup>*\\<frown>\\<^sup>* U\"\n        proof (cases U)\n          show \"\\<lbrakk>[t] \\<^sup>*\\<frown>\\<^sup>* U \\<and> T \\<^sup>*\\<frown>\\<^sup>* U \\<^sup>*\\\\\\<^sup>* [t]; U = []\\<rbrakk> \\<Longrightarrow> t # T \\<^sup>*\\<frown>\\<^sup>* U\"\n            using U by simp\n          fix u U'\n          assume U: \"U = u # U'\"\n          assume Con: \"[t] \\<^sup>*\\<frown>\\<^sup>* U \\<and> T \\<^sup>*\\<frown>\\<^sup>* U \\<^sup>*\\\\\\<^sup>* [t]\"\n          show \"t # T \\<^sup>*\\<frown>\\<^sup>* U\"\n          proof (cases \"U' = []\")\n            show \"U' = [] \\<Longrightarrow> ?thesis\"\n              using T U Con\n              by (metis Con_rec(2) Resid.simps(3) R.con_sym)\n            assume U': \"U' \\<noteq> []\"\n            show ?thesis\n            proof -\n              have \"t \\<frown> u\"\n                using T U U' Con Con_rec(3) by blast\n              moreover have \"T \\<^sup>*\\<frown>\\<^sup>* [u \\\\ t]\"\n                using T U U' Con Con_initial_right Con_sym1 Residx1_as_Resid\n                      Resid1x_as_Resid Resid_rec(2)\n                by (metis Con_sym)\n              moreover have \"[t \\\\ u] \\<^sup>*\\<frown>\\<^sup>* U'\"\n                using T U U' Con Resid_rec(3) by force\n              moreover have \"T \\<^sup>*\\\\\\<^sup>* [u \\\\ t] \\<^sup>*\\<frown>\\<^sup>* U' \\<^sup>*\\\\\\<^sup>* [t \\\\ u]\"\n                by (metis (no_types, opaque_lifting) Con Con_sym Resid_rec(2) Suc_le_mono\n                    T U U' add_Suc_right calculation(3) ind len length_Cons length_Resid)\n              ultimately show ?thesis\n                using T U U' Con_rec(4) by simp\n            qed\n          qed\n        qed\n        next\n        fix u\n        show 1: \"T \\<^sup>*\\<frown>\\<^sup>* u # U \\<Longrightarrow> T \\<^sup>*\\\\\\<^sup>* (u # U) = (T \\<^sup>*\\\\\\<^sup>* [u]) \\<^sup>*\\\\\\<^sup>* U\"\n        proof (cases T)\n          show 2: \"\\<lbrakk>T \\<^sup>*\\<frown>\\<^sup>* u # U; T = []\\<rbrakk> \\<Longrightarrow> T \\<^sup>*\\\\\\<^sup>* (u # U) = (T \\<^sup>*\\\\\\<^sup>* [u]) \\<^sup>*\\\\\\<^sup>* U\"\n            using T by simp\n          fix t T'\n          assume T: \"T = t # T'\"\n          assume Con: \"T \\<^sup>*\\<frown>\\<^sup>* u # U\"\n          show ?thesis\n          proof (cases \"T' = []\")\n            show \"T' = [] \\<Longrightarrow> ?thesis\"\n              using T U Con Con_rec(3) Resid1x_as_Resid Resid_rec(3) by force\n            assume T': \"T' \\<noteq> []\"\n            have \"T \\<^sup>*\\\\\\<^sup>* (u # U) = [t \\\\ u] \\<^sup>*\\\\\\<^sup>* U @ (T' \\<^sup>*\\\\\\<^sup>* [u \\\\ t]) \\<^sup>*\\\\\\<^sup>* (U \\<^sup>*\\\\\\<^sup>* [t \\\\ u])\"\n              using T U T' Con Resid_rec(4) [of T' U t u] by simp\n            also have \"... = ((t \\\\ u) # (T' \\<^sup>*\\\\\\<^sup>* [u \\\\ t])) \\<^sup>*\\\\\\<^sup>* U\"\n            proof -\n              have \"length (T' \\<^sup>*\\\\\\<^sup>* [u \\\\ t]) + length U \\<le> n\"\n                by (metis (no_types, lifting) Con Con_rec(4) One_nat_def Suc_eq_plus1 Suc_leI\n                    T T' U add_Suc le_less_trans len length_Resid lessI list.size(4)\n                    not_le)\n              thus ?thesis\n                using ind [of \"T' \\<^sup>*\\\\\\<^sup>* [u \\\\ t]\" U] Con Con_rec(4) T T' U by auto\n            qed\n            also have \"... = (T \\<^sup>*\\\\\\<^sup>* [u]) \\<^sup>*\\\\\\<^sup>* U\"\n              using T U T' Con Con_rec(2,4) Resid_rec(2) by force\n            finally show ?thesis by simp\n          qed\n        qed\n        show \"T \\<^sup>*\\<frown>\\<^sup>* u # U \\<Longrightarrow> T \\<^sup>*\\<frown>\\<^sup>* [u]\"\n          using 1 by force\n        show \"T \\<^sup>*\\<frown>\\<^sup>* u # U \\<Longrightarrow> T \\<^sup>*\\\\\\<^sup>* [u] \\<^sup>*\\<frown>\\<^sup>* U\"\n          using 1 by fastforce\n        show \"T \\<^sup>*\\<frown>\\<^sup>* [u] \\<and> T \\<^sup>*\\\\\\<^sup>* [u] \\<^sup>*\\<frown>\\<^sup>* U \\<Longrightarrow> T \\<^sup>*\\<frown>\\<^sup>* u # U\"\n        proof (cases T)\n          show \"\\<lbrakk>T \\<^sup>*\\<frown>\\<^sup>* [u] \\<and> T \\<^sup>*\\\\\\<^sup>* [u] \\<^sup>*\\<frown>\\<^sup>* U; T = []\\<rbrakk> \\<Longrightarrow> T \\<^sup>*\\<frown>\\<^sup>* u # U\"\n            using T by simp\n          fix t T'\n          assume T: \"T = t # T'\"\n          assume Con: \"T \\<^sup>*\\<frown>\\<^sup>* [u] \\<and> T \\<^sup>*\\\\\\<^sup>* [u] \\<^sup>*\\<frown>\\<^sup>* U\"\n          show \"Con T (u # U)\"\n          proof (cases \"T' = []\")\n            show \"T' = [] \\<Longrightarrow> ?thesis\"\n              using Con T U Con_rec(1,3) by auto\n            assume T': \"T' \\<noteq> []\"\n            have \"t \\<frown> u\"\n              using Con T U T' Con_rec(2) by blast\n            moreover have 2: \"T' \\<^sup>*\\<frown>\\<^sup>* [u \\\\ t]\"\n              using Con T U T' Con_rec(2) by blast\n            moreover have \"[t \\\\ u] \\<^sup>*\\<frown>\\<^sup>* U\"\n              using Con T U T'\n              by (metis Con_initial_left Resid_rec(2))\n            moreover have \"T' \\<^sup>*\\\\\\<^sup>* [u \\\\ t] \\<^sup>*\\<frown>\\<^sup>* U \\<^sup>*\\\\\\<^sup>* [t \\\\ u]\"\n            proof -\n              have 0: \"length (U \\<^sup>*\\\\\\<^sup>* [t \\\\ u]) = length U\"\n                using Con T U T' length_Resid Con_sym calculation(3) by blast\n              hence 1: \"length T' + length (U \\<^sup>*\\\\\\<^sup>* [t \\\\ u]) \\<le> n\"\n                using Con T U T' len length_Resid Con_sym by simp\n              have \"length ((T \\<^sup>*\\\\\\<^sup>* [u]) \\<^sup>*\\\\\\<^sup>* U) =\n                    length ([t \\\\ u] \\<^sup>*\\\\\\<^sup>* U) + length ((T' \\<^sup>*\\\\\\<^sup>* [u \\\\ t]) \\<^sup>*\\\\\\<^sup>* (U \\<^sup>*\\\\\\<^sup>* [t \\\\ u]))\"\n              proof -\n                have \"(T \\<^sup>*\\\\\\<^sup>* [u]) \\<^sup>*\\\\\\<^sup>* U =\n                      [t \\\\ u] \\<^sup>*\\\\\\<^sup>* U @ (T' \\<^sup>*\\\\\\<^sup>* [u \\\\ t]) \\<^sup>*\\\\\\<^sup>* (U \\<^sup>*\\\\\\<^sup>* [t \\\\ u])\"\n                  by (metis 0 1 2 Con Resid_rec(2) T T' U ind length_Resid)\n                thus ?thesis\n                  using Con T U T' length_Resid by simp\n              qed\n              moreover have \"length ((T \\<^sup>*\\\\\\<^sup>* [u]) \\<^sup>*\\\\\\<^sup>* U) = length T\"\n                using Con T U T' length_Resid by metis\n              moreover have \"length ([t \\\\ u] \\<^sup>*\\\\\\<^sup>* U) \\<le> 1\"\n                using Con T U T' Resid1x_as_Resid\n                by (metis One_nat_def length_Cons list.size(3) order_refl zero_le)\n              ultimately show ?thesis\n                using Con T U T' length_Resid by auto\n            qed\n            ultimately show \"T \\<^sup>*\\<frown>\\<^sup>* u # U\"\n              using T Con_rec(4) [of T' U t u] by fastforce\n          qed\n        qed\n      qed\n    qed\n\n    text \\<open>\n      The following are the final versions of recursive expansion for consistency\n      and residuation on paths.  These are what I really wanted the original definitions\n      to look like, but if this is tried, then \\<open>Con\\<close> and \\<open>Resid\\<close> end up having to be mutually\n      recursive, expressing the definitions so that they are single-valued becomes an issue,\n      and proving termination is more problematic.\n    \\<close>\n\n    lemma Con_cons:\n    assumes \"T \\<noteq> []\" and \"U \\<noteq> []\"\n    shows \"t # T \\<^sup>*\\<frown>\\<^sup>* U \\<longleftrightarrow> [t] \\<^sup>*\\<frown>\\<^sup>* U \\<and> T \\<^sup>*\\<frown>\\<^sup>* U \\<^sup>*\\\\\\<^sup>* [t]\"\n    and \"T \\<^sup>*\\<frown>\\<^sup>* u # U \\<longleftrightarrow> T \\<^sup>*\\<frown>\\<^sup>* [u] \\<and> T \\<^sup>*\\\\\\<^sup>* [u] \\<^sup>*\\<frown>\\<^sup>* U\"\n      using assms Resid_cons_ind [of T U] by blast+\n\n    lemma Con_consI [intro, simp]:\n    shows \"\\<lbrakk>T \\<noteq> []; U \\<noteq> []; [t] \\<^sup>*\\<frown>\\<^sup>* U; T \\<^sup>*\\<frown>\\<^sup>* U \\<^sup>*\\\\\\<^sup>* [t]\\<rbrakk> \\<Longrightarrow> t # T \\<^sup>*\\<frown>\\<^sup>* U\"\n    and \"\\<lbrakk>T \\<noteq> []; U \\<noteq> []; T \\<^sup>*\\<frown>\\<^sup>* [u]; T \\<^sup>*\\\\\\<^sup>* [u] \\<^sup>*\\<frown>\\<^sup>* U\\<rbrakk> \\<Longrightarrow> T \\<^sup>*\\<frown>\\<^sup>* u # U\"\n      using Con_cons by auto\n\n    (* TODO: Making this a simp currently seems to produce undesirable breakage. *)\n    lemma Resid_cons:\n    assumes \"U \\<noteq> []\"\n    shows \"t # T \\<^sup>*\\<frown>\\<^sup>* U \\<Longrightarrow> (t # T) \\<^sup>*\\\\\\<^sup>* U = ([t] \\<^sup>*\\\\\\<^sup>* U) @ (T \\<^sup>*\\\\\\<^sup>* (U \\<^sup>*\\\\\\<^sup>* [t]))\"\n    and \"T \\<^sup>*\\<frown>\\<^sup>* u # U \\<Longrightarrow> T \\<^sup>*\\\\\\<^sup>* (u # U) = (T \\<^sup>*\\\\\\<^sup>* [u]) \\<^sup>*\\\\\\<^sup>* U\"\n      using assms Resid_cons_ind [of T U] Resid.simps(1)\n      by blast+\n\n    text \\<open>\n      The following expansion of residuation with respect to the first argument\n      is stated in terms of the more primitive cons, rather than list append,\n      but as a result \\<open>\\<^sup>1\\\\<^sup>*\\<close> has to be used.\n    \\<close>\n\n    (* TODO: Making this a simp seems to produce similar breakage as above. *)\n    lemma Resid_cons':\n    assumes \"T \\<noteq> []\"\n    shows \"t # T \\<^sup>*\\<frown>\\<^sup>* U \\<Longrightarrow> (t # T) \\<^sup>*\\\\\\<^sup>* U = (t \\<^sup>1\\\\\\<^sup>* U) # (T \\<^sup>*\\\\\\<^sup>* (U \\<^sup>*\\\\\\<^sup>* [t]))\"\n      using assms\n      by (metis Con_sym Resid.simps(1) Resid1x_as_Resid Resid_cons(1)\n          append_Cons append_Nil)\n\n    lemma Srcs_Resid_Arr_single:\n    assumes \"T \\<^sup>*\\<frown>\\<^sup>* [u]\"\n    shows \"Srcs (T \\<^sup>*\\\\\\<^sup>* [u]) = R.targets u\"\n    proof (cases T)\n      show \"T = [] \\<Longrightarrow> Srcs (T \\<^sup>*\\\\\\<^sup>* [u]) = R.targets u\"\n        using assms by simp\n      fix t T'\n      assume T: \"T = t # T'\"\n      show \"Srcs (T \\<^sup>*\\\\\\<^sup>* [u]) = R.targets u\"\n      proof (cases \"T' = []\")\n        show \"T' = [] \\<Longrightarrow> ?thesis\"\n          using assms T R.sources_resid by auto\n        assume T': \"T' \\<noteq> []\"\n        have \"Srcs (T \\<^sup>*\\\\\\<^sup>* [u]) = Srcs ((t # T') \\<^sup>*\\\\\\<^sup>* [u])\"\n          using T by simp\n        also have \"... = Srcs ((t \\\\ u) # (T' \\<^sup>*\\\\\\<^sup>* ([u] \\<^sup>*\\\\\\<^sup>* T')))\"\n          using assms T\n          by (metis Resid_rec(2) Srcs.elims T' list.distinct(1) list.sel(1))\n        also have \"... = R.sources (t \\\\ u)\"\n          using Srcs.elims by blast\n        also have \"... = R.targets u\"\n          using assms Con_rec(2) T T' R.sources_resid by force\n        finally show ?thesis by blast\n      qed\n    qed\n\n    lemma Srcs_Resid_single_Arr:\n    shows \"[u] \\<^sup>*\\<frown>\\<^sup>* T \\<Longrightarrow> Srcs ([u] \\<^sup>*\\\\\\<^sup>* T) = Trgs T\"\n    proof (induct T arbitrary: u)\n      show \"\\<And>u. [u] \\<^sup>*\\<frown>\\<^sup>* [] \\<Longrightarrow> Srcs ([u] \\<^sup>*\\\\\\<^sup>* []) = Trgs []\"\n        by simp\n      fix t u T\n      assume ind: \"\\<And>u. [u] \\<^sup>*\\<frown>\\<^sup>* T  \\<Longrightarrow> Srcs ([u] \\<^sup>*\\\\\\<^sup>* T) = Trgs T\"\n      assume Con: \"[u] \\<^sup>*\\<frown>\\<^sup>* t # T\"\n      show \"Srcs ([u] \\<^sup>*\\\\\\<^sup>* (t # T)) = Trgs (t # T)\"\n      proof (cases \"T = []\")\n        show \"T = [] \\<Longrightarrow> ?thesis\"\n          using Con Srcs_Resid_Arr_single Trgs.simps(2) by presburger\n        assume T: \"T \\<noteq> []\"\n        have \"Srcs ([u] \\<^sup>*\\\\\\<^sup>* (t # T)) = Srcs ([u \\\\ t] \\<^sup>*\\\\\\<^sup>* T)\"\n          using Con Resid_rec(3) T by force\n        also have \"... = Trgs T\"\n          using Con ind Con_rec(3) T by auto\n        also have \"... = Trgs (t # T)\"\n          by (metis T Trgs.elims Trgs.simps(3))\n        finally show ?thesis by simp\n      qed\n    qed\n\n    lemma Trgs_Resid_sym_Arr_single:\n    shows \"T \\<^sup>*\\<frown>\\<^sup>* [u] \\<Longrightarrow> Trgs (T \\<^sup>*\\\\\\<^sup>* [u]) = Trgs ([u] \\<^sup>*\\\\\\<^sup>* T)\"\n    proof (induct T arbitrary: u)\n      show \"\\<And>u. [] \\<^sup>*\\<frown>\\<^sup>* [u] \\<Longrightarrow> Trgs ([] \\<^sup>*\\\\\\<^sup>* [u]) = Trgs ([u] \\<^sup>*\\\\\\<^sup>* [])\"\n        by simp\n      fix t u T\n      assume ind: \"\\<And>u. T \\<^sup>*\\<frown>\\<^sup>* [u] \\<Longrightarrow> Trgs (T \\<^sup>*\\\\\\<^sup>* [u]) = Trgs ([u] \\<^sup>*\\\\\\<^sup>* T)\"\n      assume Con: \"t # T \\<^sup>*\\<frown>\\<^sup>* [u]\"\n      show \"Trgs ((t # T) \\<^sup>*\\\\\\<^sup>* [u]) = Trgs ([u] \\<^sup>*\\\\\\<^sup>* (t # T))\"\n      proof (cases \"T = []\")\n        show \"T = [] \\<Longrightarrow> ?thesis\"\n          using R.targets_resid_sym\n          by (simp add: R.con_sym)\n        assume T: \"T \\<noteq> []\"\n        show ?thesis\n        proof -\n          have \"Trgs ((t # T) \\<^sup>*\\\\\\<^sup>* [u]) = Trgs ((t \\\\ u) # (T \\<^sup>*\\\\\\<^sup>* [u \\\\ t]))\"\n            using Con Resid_rec(2) T by auto\n          also have \"... = Trgs (T \\<^sup>*\\\\\\<^sup>* [u \\\\ t])\"\n            using T Con Con_rec(2) [of T t u]\n            by (metis Trgs.elims Trgs.simps(3))\n          also have \"... = Trgs ([u \\\\ t] \\<^sup>*\\\\\\<^sup>* T)\"\n            using T Con ind Con_sym by metis\n          also have \"... = Trgs ([u] \\<^sup>*\\\\\\<^sup>* (t # T))\"\n            using T Con Con_sym Resid_rec(3) by presburger\n          finally show ?thesis by blast\n        qed\n      qed\n    qed\n\n    lemma Srcs_Resid [simp]:\n    shows \"T \\<^sup>*\\<frown>\\<^sup>* U \\<Longrightarrow> Srcs (T \\<^sup>*\\\\\\<^sup>* U) = Trgs U\"\n    proof (induct U arbitrary: T)\n      show \"\\<And>T. T \\<^sup>*\\<frown>\\<^sup>* [] \\<Longrightarrow> Srcs (T \\<^sup>*\\\\\\<^sup>* []) = Trgs []\"\n        using Con_sym Resid.simps(1) by blast\n      fix u U T\n      assume ind: \"\\<And>T. T \\<^sup>*\\<frown>\\<^sup>* U \\<Longrightarrow> Srcs (T \\<^sup>*\\\\\\<^sup>* U) = Trgs U\"\n      assume Con: \"T \\<^sup>*\\<frown>\\<^sup>* u # U\"\n      show \"Srcs (T \\<^sup>*\\\\\\<^sup>* (u # U)) = Trgs (u # U)\"\n        by (metis Con Resid_cons(2) Srcs_Resid_Arr_single Trgs.simps(2-3) ind\n            list.exhaust_sel)\n    qed\n\n    lemma Trgs_Resid_sym [simp]:\n    shows \"T \\<^sup>*\\<frown>\\<^sup>* U \\<Longrightarrow> Trgs (T \\<^sup>*\\\\\\<^sup>* U) = Trgs (U \\<^sup>*\\\\\\<^sup>* T)\"\n    proof (induct U arbitrary: T)\n      show \"\\<And>T. T \\<^sup>*\\<frown>\\<^sup>* [] \\<Longrightarrow> Trgs (T \\<^sup>*\\\\\\<^sup>* []) = Trgs ([] \\<^sup>*\\\\\\<^sup>* T)\"\n        by (meson Con_sym Resid.simps(1))\n      fix u U T\n      assume ind: \"\\<And>T. T \\<^sup>*\\<frown>\\<^sup>* U \\<Longrightarrow> Trgs (T \\<^sup>*\\\\\\<^sup>* U) = Trgs (U \\<^sup>*\\\\\\<^sup>* T)\"\n      assume Con: \"T \\<^sup>*\\<frown>\\<^sup>* u # U\"\n      show \"Trgs (T \\<^sup>*\\\\\\<^sup>* (u # U)) = Trgs ((u # U) \\<^sup>*\\\\\\<^sup>* T)\"\n      proof (cases \"U = []\")\n        show \"U = [] \\<Longrightarrow> ?thesis\"\n          using Con Trgs_Resid_sym_Arr_single by blast\n        assume U: \"U \\<noteq> []\"\n        show ?thesis\n        proof -\n          have \"Trgs (T \\<^sup>*\\\\\\<^sup>* (u # U)) = Trgs ((T \\<^sup>*\\\\\\<^sup>* [u]) \\<^sup>*\\\\\\<^sup>* U)\"\n            using U by (metis Con Resid_cons(2))\n          also have \"... = Trgs (U \\<^sup>*\\\\\\<^sup>* (T \\<^sup>*\\\\\\<^sup>* [u]))\"\n            using U Con by (metis Con_sym ind)\n          also have \"... = Trgs ((u # U) \\<^sup>*\\\\\\<^sup>* T)\"\n            by (metis (no_types, opaque_lifting) Con_cons(1) Con_sym Resid.simps(1) Resid_cons'\n                Trgs.simps(3) U neq_Nil_conv)\n          finally show ?thesis by simp\n        qed\n      qed\n    qed\n\n    lemma img_Resid_Srcs:\n    shows \"Arr T \\<Longrightarrow> (\\<lambda>a. [a] \\<^sup>*\\\\\\<^sup>* T) ` Srcs T \\<subseteq> (\\<lambda>b. [b]) ` Trgs T\"\n    proof (induct T)\n      show \"Arr [] \\<Longrightarrow> (\\<lambda>a. [a] \\<^sup>*\\\\\\<^sup>* []) ` Srcs [] \\<subseteq> (\\<lambda>b. [b]) ` Trgs []\"\n        by simp\n      fix t :: 'a and T :: \"'a list\"\n      assume tT: \"Arr (t # T)\"\n      assume ind: \"Arr T \\<Longrightarrow> (\\<lambda>a. [a] \\<^sup>*\\\\\\<^sup>* T) ` Srcs T \\<subseteq> (\\<lambda>b. [b]) ` Trgs T\"\n      show \"(\\<lambda>a. [a] \\<^sup>*\\\\\\<^sup>* (t # T)) ` Srcs (t # T) \\<subseteq> (\\<lambda>b. [b]) ` Trgs (t # T)\"\n      proof\n        fix B\n        assume B: \"B \\<in> (\\<lambda>a. [a] \\<^sup>*\\\\\\<^sup>* (t # T)) ` Srcs (t # T)\"\n        show \"B \\<in> (\\<lambda>b. [b]) ` Trgs (t # T)\"\n        proof (cases \"T = []\")\n          assume T: \"T = []\"\n          obtain a where a: \"a \\<in> R.sources t \\<and> [a \\\\ t] = B\"\n            by (metis (no_types, lifting) B R.composite_of_source_arr R.con_prfx_composite_of(1)\n                Resid_rec(1) Srcs.simps(2) T Arr.simps(2) Con_rec(1) imageE tT)\n          have \"a \\\\ t \\<in> Trgs (t # T)\"\n            using tT T a\n            by (simp add: R.resid_source_in_targets)\n          thus ?thesis\n            using B a image_iff by fastforce\n          next\n          assume T: \"T \\<noteq> []\"\n          obtain a where a: \"a \\<in> R.sources t \\<and> [a] \\<^sup>*\\\\\\<^sup>* (t # T) = B\"\n            using tT T B Srcs.elims by blast\n          have \"[a \\\\ t] \\<^sup>*\\\\\\<^sup>* T = B\"\n            using tT T B a\n            by (metis Con_rec(3) R.arrI R.resid_source_in_targets R.targets_are_cong\n                Resid_rec(3) R.arr_resid_iff_con R.ide_implies_arr)\n          moreover have \"a \\\\ t \\<in> Srcs T\"\n            using a tT\n            by (metis Arr.simps(3) R.resid_source_in_targets T neq_Nil_conv subsetD)\n          ultimately show ?thesis\n            using T tT ind\n            by (metis Trgs.simps(3) Arr.simps(3) image_iff list.exhaust_sel subsetD)\n        qed\n      qed\n    qed\n\n    lemma Resid_Arr_Src:\n    shows \"\\<lbrakk>Arr T; a \\<in> Srcs T\\<rbrakk> \\<Longrightarrow> T \\<^sup>*\\\\\\<^sup>* [a] = T\"\n    proof (induct T arbitrary: a)\n      show \"\\<And>a. \\<lbrakk>Arr []; a \\<in> Srcs []\\<rbrakk> \\<Longrightarrow> [] \\<^sup>*\\\\\\<^sup>* [a] = []\"\n        by simp\n      fix a t T\n      assume ind: \"\\<And>a. \\<lbrakk>Arr T; a \\<in> Srcs T\\<rbrakk> \\<Longrightarrow> T \\<^sup>*\\\\\\<^sup>* [a] = T\"\n      assume Arr: \"Arr (t # T)\"\n      assume a: \"a \\<in> Srcs (t # T)\"\n      show \"(t # T) \\<^sup>*\\\\\\<^sup>* [a] = t # T\"\n      proof (cases \"T = []\")\n        show \"T = [] \\<Longrightarrow> ?thesis\"\n          using a R.resid_arr_ide R.sources_def by auto\n        assume T: \"T \\<noteq> []\"\n        show \"(t # T) \\<^sup>*\\\\\\<^sup>* [a] = t # T\"\n        proof -\n          have 1: \"R.arr t \\<and> Arr T \\<and> R.targets t \\<subseteq> Srcs T\"\n            using Arr T\n            by (metis Arr.elims(2) list.sel(1) list.sel(3))\n          have 2: \"t # T \\<^sup>*\\<frown>\\<^sup>* [a]\"\n            using T a Arr Con_rec(2)\n            by (metis (no_types, lifting) img_Resid_Srcs Con_sym imageE image_subset_iff\n                list.distinct(1))\n          have \"(t # T) \\<^sup>*\\\\\\<^sup>* [a] = (t \\\\ a) # (T \\<^sup>*\\\\\\<^sup>* [a \\\\ t])\"\n            using 2 T Resid_rec(2) by simp\n          moreover have \"t \\\\ a = t\"\n            using Arr a R.sources_def\n            by (metis \"2\" CollectD Con_rec(2) T Srcs_are_ide in_mono R.resid_arr_ide)\n          moreover have \"T \\<^sup>*\\\\\\<^sup>* [a \\\\ t] = T\"\n            by (metis \"1\" \"2\" R.in_sourcesI R.resid_source_in_targets Srcs_are_ide T a\n                      Con_rec(2) in_mono ind mem_Collect_eq)\n          ultimately show ?thesis by simp\n        qed\n      qed\n    qed\n\n    lemma Con_single_ide_ind:\n    shows \"R.ide a \\<Longrightarrow> [a] \\<^sup>*\\<frown>\\<^sup>* T \\<longleftrightarrow> Arr T \\<and> a \\<in> Srcs T\"\n    proof (induct T arbitrary: a)\n      show \"\\<And>a. [a] \\<^sup>*\\<frown>\\<^sup>* [] \\<longleftrightarrow> Arr [] \\<and> a \\<in> Srcs []\"\n        by simp\n      fix a t T\n      assume ind: \"\\<And>a. R.ide a \\<Longrightarrow> [a] \\<^sup>*\\<frown>\\<^sup>* T \\<longleftrightarrow> Arr T \\<and> a \\<in> Srcs T\"\n      assume a: \"R.ide a\"\n      show \"[a] \\<^sup>*\\<frown>\\<^sup>* (t # T) \\<longleftrightarrow> Arr (t # T) \\<and> a \\<in> Srcs (t # T)\"\n      proof (cases \"T = []\")\n        show \"T = [] \\<Longrightarrow> ?thesis\"\n          using a Con_sym\n          by (metis Arr.simps(2) Resid_Arr_Src Srcs.simps(2) R.arr_iff_has_source\n              Con_rec(1) empty_iff R.in_sourcesI list.distinct(1))\n        assume T: \"T \\<noteq> []\"\n        have 1: \"[a] \\<^sup>*\\<frown>\\<^sup>* (t # T) \\<longleftrightarrow> a \\<frown> t \\<and> [a \\\\ t] \\<^sup>*\\<frown>\\<^sup>* T\"\n          using a T Con_cons(2) [of \"[a]\" T t] by simp\n        also have 2: \"... \\<longleftrightarrow> a \\<frown> t \\<and> Arr T \\<and> a \\\\ t \\<in> Srcs T\"\n          using a T ind R.resid_ide_arr by blast\n        also have \"... \\<longleftrightarrow> Arr (t # T) \\<and> a \\<in> Srcs (t # T)\"\n          using a T Con_sym R.con_sym Resid_Arr_Src R.con_implies_arr Srcs_are_ide\n          apply (cases T)\n           apply simp\n          by (metis Arr.simps(3) R.resid_arr_ide R.targets_resid_sym Srcs.simps(3)\n              Srcs_Resid_Arr_single calculation dual_order.eq_iff list.distinct(1)\n              R.in_sourcesI)\n        finally show ?thesis by simp\n      qed\n    qed\n\n    lemma Con_single_ide_iff:\n    assumes \"R.ide a\"\n    shows \"[a] \\<^sup>*\\<frown>\\<^sup>* T \\<longleftrightarrow> Arr T \\<and> a \\<in> Srcs T\"\n      using assms Con_single_ide_ind by simp\n\n    lemma Con_single_ideI [intro]:\n    assumes \"R.ide a\" and \"Arr T\" and \"a \\<in> Srcs T\"\n    shows \"[a] \\<^sup>*\\<frown>\\<^sup>* T\" and \"T \\<^sup>*\\<frown>\\<^sup>* [a]\"\n      using assms Con_single_ide_iff Con_sym by auto\n\n    lemma Resid_single_ide:\n    assumes \"R.ide a\" and \"[a] \\<^sup>*\\<frown>\\<^sup>* T\"\n    shows \"[a] \\<^sup>*\\\\\\<^sup>* T \\<in> (\\<lambda>b. [b]) ` Trgs T\" and [simp]: \"T \\<^sup>*\\\\\\<^sup>* [a] = T\"\n      using assms Con_single_ide_ind img_Resid_Srcs Resid_Arr_Src Con_sym\n      by blast+\n\n    lemma Resid_Arr_Ide_ind:\n    shows \"\\<lbrakk>Ide A; T \\<^sup>*\\<frown>\\<^sup>* A\\<rbrakk> \\<Longrightarrow> T \\<^sup>*\\\\\\<^sup>* A = T\"\n    proof (induct A)\n      show \"\\<lbrakk>Ide []; T \\<^sup>*\\<frown>\\<^sup>* []\\<rbrakk> \\<Longrightarrow> T \\<^sup>*\\\\\\<^sup>* [] = T\"\n        by simp\n      fix a A\n      assume ind: \"\\<lbrakk>Ide A; T \\<^sup>*\\<frown>\\<^sup>* A\\<rbrakk> \\<Longrightarrow> T \\<^sup>*\\\\\\<^sup>* A = T\"\n      assume Ide: \"Ide (a # A)\"\n      assume Con: \"T \\<^sup>*\\<frown>\\<^sup>* a # A\"\n      show \"T \\<^sup>*\\\\\\<^sup>* (a # A) = T\"\n        by (metis (no_types, lifting) Con Con_initial_left Con_sym Ide Ide.elims(2)\n            Resid_cons(2) Resid_single_ide(2) ind list.inject)\n    qed\n\n    lemma Resid_Ide_Arr_ind:\n    shows \"\\<lbrakk>Ide A; A \\<^sup>*\\<frown>\\<^sup>* T\\<rbrakk> \\<Longrightarrow> Ide (A \\<^sup>*\\\\\\<^sup>* T)\"\n    proof (induct A)\n      show \"\\<lbrakk>Ide []; [] \\<^sup>*\\<frown>\\<^sup>* T\\<rbrakk> \\<Longrightarrow> Ide ([] \\<^sup>*\\\\\\<^sup>* T)\"\n        by simp\n      fix a A\n      assume ind: \"\\<lbrakk>Ide A; A \\<^sup>*\\<frown>\\<^sup>* T\\<rbrakk> \\<Longrightarrow> Ide (A \\<^sup>*\\\\\\<^sup>* T)\"\n      assume Ide: \"Ide (a # A)\"\n      assume Con: \"a # A \\<^sup>*\\<frown>\\<^sup>* T\"\n      have T: \"Arr T\"\n        using Con Ide Con_single_ide_ind Con_initial_left Ide.elims(2)\n        by blast\n      show \"Ide ((a # A) \\<^sup>*\\\\\\<^sup>* T)\"\n      proof (cases \"A = []\")\n        show \"A = [] \\<Longrightarrow> ?thesis\"\n          by (metis Con Con_sym1 Ide Ide.simps(2) Resid1x_as_Resid Resid1x_ide\n              Residx1_as_Resid Con_sym)\n        assume A: \"A \\<noteq> []\"\n        show ?thesis\n        proof -\n          have \"Ide ([a] \\<^sup>*\\\\\\<^sup>* T)\"\n            by (metis Con Con_initial_left Con_sym Con_sym1 Ide Ide.simps(3)\n                Resid1x_as_Resid Residx1_as_Resid Ide.simps(2) Resid1x_ide\n                list.exhaust_sel)\n          moreover have \"Trgs ([a] \\<^sup>*\\\\\\<^sup>* T) \\<subseteq> Srcs (A \\<^sup>*\\\\\\<^sup>* T)\"\n            using A T Ide Con\n            by (metis (no_types, lifting) Con_sym Ide.elims(2) Ide.simps(2) Resid_Arr_Ide_ind\n                Srcs_Resid Trgs_Resid_sym Con_cons(2) dual_order.eq_iff list.inject)\n          moreover have \"Ide (A \\<^sup>*\\\\\\<^sup>* (T \\<^sup>*\\\\\\<^sup>* [a]))\"\n            by (metis A Con Con_cons(1) Con_sym Ide Ide.simps(3) Resid_Arr_Ide_ind\n                Resid_single_ide(2) ind list.exhaust_sel)\n          moreover have \"Ide ((a # A) \\<^sup>*\\\\\\<^sup>* T) \\<longleftrightarrow> \n                         Ide ([a] \\<^sup>*\\\\\\<^sup>* T) \\<and> Ide (A \\<^sup>*\\\\\\<^sup>* (T \\<^sup>*\\\\\\<^sup>* [a])) \\<and>\n                           Trgs ([a] \\<^sup>*\\\\\\<^sup>* T) \\<subseteq> Srcs (A \\<^sup>*\\\\\\<^sup>* T)\"\n            using calculation(1-3)\n            by (metis Arr.simps(1) Con Ide Ide.simps(3) Resid1x_as_Resid Resid_cons'\n               Trgs.simps(2) Con_single_ide_iff Ide.simps(2) Ide_implies_Arr Resid_Arr_Src\n                list.exhaust_sel)\n          ultimately show ?thesis by blast\n        qed\n      qed\n    qed\n\n    lemma Resid_Ide:\n    assumes \"Ide A\" and \"A \\<^sup>*\\<frown>\\<^sup>* T\"\n    shows \"T \\<^sup>*\\\\\\<^sup>* A = T\" and \"Ide (A \\<^sup>*\\\\\\<^sup>* T)\"\n      using assms Resid_Ide_Arr_ind Resid_Arr_Ide_ind Con_sym by auto\n\n    lemma Con_Ide_iff:\n    shows \"Ide A \\<Longrightarrow> A \\<^sup>*\\<frown>\\<^sup>* T \\<longleftrightarrow> Arr T \\<and> Srcs T = Srcs A\"\n    proof (induct A)\n      show \"Ide [] \\<Longrightarrow> [] \\<^sup>*\\<frown>\\<^sup>* T \\<longleftrightarrow> Arr T \\<and> Srcs T = Srcs []\"\n        by simp\n      fix a A\n      assume ind: \"Ide A \\<Longrightarrow> A \\<^sup>*\\<frown>\\<^sup>* T \\<longleftrightarrow> Arr T \\<and> Srcs T = Srcs A\"\n      assume Ide: \"Ide (a # A)\"\n      show \"a # A \\<^sup>*\\<frown>\\<^sup>* T \\<longleftrightarrow> Arr T \\<and> Srcs T = Srcs (a # A)\"\n      proof (cases \"A = []\")\n        show \"A = [] \\<Longrightarrow> ?thesis\"\n          using Con_single_ide_ind Ide\n          by (metis Arr.simps(2) Con_sym Ide.simps(2) Ide_implies_Arr R.arrE\n                    Resid_Arr_Src Srcs.simps(2) Srcs_Resid R.in_sourcesI)\n        assume A: \"A \\<noteq> []\"\n        have \"a # A \\<^sup>*\\<frown>\\<^sup>* T \\<longleftrightarrow> [a] \\<^sup>*\\<frown>\\<^sup>* T \\<and> A \\<^sup>*\\<frown>\\<^sup>* T \\<^sup>*\\\\\\<^sup>* [a]\"\n          using A Ide Con_cons(1) [of A T a] by fastforce\n        also have 1: \"... \\<longleftrightarrow> Arr T \\<and> a \\<in> Srcs T\"\n          by (metis A Arr_has_Src Con_single_ide_ind Ide Ide.elims(2) Resid_Arr_Src\n              Srcs_Resid_Arr_single Con_sym Srcs_eqI ind inf.absorb_iff2 list.inject)\n        also have \"... \\<longleftrightarrow> Arr T \\<and> Srcs T = Srcs (a # A)\"\n          by (metis A 1 Con_sym Ide Ide.simps(3) R.ideE\n              R.sources_resid Resid_Arr_Src Srcs.simps(3) Srcs_Resid_Arr_single\n              list.exhaust_sel R.in_sourcesI)\n        finally show \"a # A \\<^sup>*\\<frown>\\<^sup>* T \\<longleftrightarrow> Arr T \\<and> Srcs T = Srcs (a # A)\"\n          by blast\n      qed\n    qed\n\n    lemma Con_IdeI:\n    assumes \"Ide A\" and \"Arr T\" and \"Srcs T = Srcs A\"\n    shows \"A \\<^sup>*\\<frown>\\<^sup>* T\" and \"T \\<^sup>*\\<frown>\\<^sup>* A\"\n      using assms Con_Ide_iff Con_sym by auto\n\n    lemma Con_Arr_self:\n    shows \"Arr T \\<Longrightarrow> T \\<^sup>*\\<frown>\\<^sup>* T\"\n    proof (induct T)\n      show \"Arr [] \\<Longrightarrow> [] \\<^sup>*\\<frown>\\<^sup>* []\"\n        by simp\n      fix t T\n      assume ind: \"Arr T \\<Longrightarrow> T \\<^sup>*\\<frown>\\<^sup>* T\"\n      assume Arr: \"Arr (t # T)\"\n      show \"t # T \\<^sup>*\\<frown>\\<^sup>* t # T\"\n      proof (cases \"T = []\")\n        show \"T = [] \\<Longrightarrow> ?thesis\"\n          using Arr R.arrE by simp\n        assume T: \"T \\<noteq> []\"\n        have \"t \\<frown> t \\<and> T \\<^sup>*\\<frown>\\<^sup>* [t \\\\ t] \\<and> [t \\\\ t] \\<^sup>*\\<frown>\\<^sup>* T \\<and> T \\<^sup>*\\\\\\<^sup>* [t \\\\ t] \\<^sup>*\\<frown>\\<^sup>* T \\<^sup>*\\\\\\<^sup>* [t \\\\ t]\"\n        proof -\n          have \"t \\<frown> t\"\n            using Arr Arr.elims(1) by auto\n          moreover have \"T \\<^sup>*\\<frown>\\<^sup>* [t \\\\ t]\"\n          proof -\n            have \"Ide [t \\\\ t]\"\n              by (simp add: R.arr_def R.prfx_reflexive calculation)\n            moreover have \"Srcs [t \\\\ t] = Srcs T\"\n              by (metis Arr Arr.simps(2) Arr_has_Trg R.arrE R.sources_resid Srcs.simps(2)\n                  Srcs_eqI T Trgs.simps(2) Arr.simps(3) inf.absorb_iff2 list.exhaust)\n            ultimately show ?thesis\n              by (metis Arr Con_sym T Arr.simps(3) Con_Ide_iff neq_Nil_conv)\n          qed\n          ultimately show ?thesis\n            by (metis Con_single_ide_ind Con_sym R.prfx_reflexive\n                Resid_single_ide(2) ind R.con_implies_arr(1))\n        qed\n        thus ?thesis\n          using Con_rec(4) [of T T t t] by force\n      qed\n    qed\n\n    lemma Resid_Arr_self:\n    shows \"Arr T \\<Longrightarrow> Ide (T \\<^sup>*\\\\\\<^sup>* T)\"\n    proof (induct T)\n      show \"Arr [] \\<Longrightarrow> Ide ([] \\<^sup>*\\\\\\<^sup>* [])\"\n        by simp\n      fix t T\n      assume ind: \"Arr T \\<Longrightarrow> Ide (T \\<^sup>*\\\\\\<^sup>* T)\"\n      assume Arr: \"Arr (t # T)\"\n      show \"Ide ((t # T) \\<^sup>*\\\\\\<^sup>* (t # T))\"\n      proof (cases \"T = []\")\n        show \"T = [] \\<Longrightarrow> ?thesis\"\n          using Arr R.prfx_reflexive by auto\n        assume T: \"T \\<noteq> []\"\n        have 1: \"(t # T) \\<^sup>*\\\\\\<^sup>* (t # T) = t \\<^sup>1\\\\\\<^sup>* (t # T) # T \\<^sup>*\\\\\\<^sup>* ((t # T) \\<^sup>*\\\\\\<^sup>* [t])\"\n          using Arr T Resid_cons' [of T t \"t # T\"] Con_Arr_self by presburger\n        also have \"... = (t \\\\ t) \\<^sup>1\\\\\\<^sup>* T # T \\<^sup>*\\\\\\<^sup>* (t \\<^sup>1\\\\\\<^sup>* [t] # T \\<^sup>*\\\\\\<^sup>* ([t] \\<^sup>*\\\\\\<^sup>* [t]))\"\n          using Arr T Resid_cons' [of T t \"[t]\"]\n          by (metis Con_initial_right Resid1x.simps(3) calculation neq_Nil_conv)\n        also have \"... = (t \\\\ t) \\<^sup>1\\\\\\<^sup>* T # (T \\<^sup>*\\\\\\<^sup>* ([t] \\<^sup>*\\\\\\<^sup>* [t])) \\<^sup>*\\\\\\<^sup>* (T \\<^sup>*\\\\\\<^sup>* ([t] \\<^sup>*\\\\\\<^sup>* [t]))\"\n          by (metis 1 Resid1x.simps(2) Residx1.simps(2) Residx1_as_Resid T calculation\n              Con_cons(1) Con_rec(4) Resid_cons(2) list.distinct(1) list.inject)\n        finally have 2: \"(t # T) \\<^sup>*\\\\\\<^sup>* (t # T) =\n                         (t \\\\ t) \\<^sup>1\\\\\\<^sup>* T # (T \\<^sup>*\\\\\\<^sup>* ([t] \\<^sup>*\\\\\\<^sup>* [t])) \\<^sup>*\\\\\\<^sup>* (T \\<^sup>*\\\\\\<^sup>* ([t] \\<^sup>*\\\\\\<^sup>* [t]))\"\n          by blast\n        moreover have \"Ide ...\"\n        proof -\n          have \"R.ide ((t \\\\ t) \\<^sup>1\\\\\\<^sup>* T)\"\n            using Arr T\n            by (metis Con_initial_right Con_rec(2) Con_sym1 R.con_implies_arr(1)\n                Resid1x_ide Con_Arr_self Residx1_as_Resid R.prfx_reflexive)\n          moreover have \"Ide ((T \\<^sup>*\\\\\\<^sup>* ([t] \\<^sup>*\\\\\\<^sup>* [t])) \\<^sup>*\\\\\\<^sup>* (T \\<^sup>*\\\\\\<^sup>* ([t] \\<^sup>*\\\\\\<^sup>* [t])))\"\n            using Arr T\n            by (metis Con_Arr_self Con_rec(4) Resid_single_ide(2) Con_single_ide_ind\n                Resid.simps(3) ind R.prfx_reflexive R.con_implies_arr(2))\n          moreover have \"R.targets ((t \\\\ t) \\<^sup>1\\\\\\<^sup>* T) \\<subseteq>\n                           Srcs ((T \\<^sup>*\\\\\\<^sup>* ([t] \\<^sup>*\\\\\\<^sup>* [t])) \\<^sup>*\\\\\\<^sup>* (T \\<^sup>*\\\\\\<^sup>* ([t] \\<^sup>*\\\\\\<^sup>* [t])))\"\n            by (metis (no_types, lifting) 1 2 Con_cons(1) Resid1x_as_Resid T Trgs.simps(2)\n                Trgs_Resid_sym Srcs_Resid dual_order.eq_iff list.discI list.inject)\n          ultimately show ?thesis\n            using Arr T\n            by (metis Ide.simps(1,3) list.exhaust_sel)\n        qed\n        ultimately show ?thesis by auto\n      qed\n    qed\n\n    lemma Con_imp_eq_Srcs:\n    assumes \"T \\<^sup>*\\<frown>\\<^sup>* U\"\n    shows \"Srcs T = Srcs U\"\n    proof (cases T)\n      show \"T = [] \\<Longrightarrow> ?thesis\"\n        using assms by simp\n      fix t T'\n      assume T: \"T = t # T'\"\n      show \"Srcs T = Srcs U\"\n      proof (cases U)\n        show \"U = [] \\<Longrightarrow> ?thesis\"\n          using assms T by simp\n        fix u U'\n        assume U: \"U = u # U'\"\n        show \"Srcs T = Srcs U\"\n          by (metis Con_initial_right Con_rec(1) Con_sym R.con_imp_common_source\n              Srcs.simps(2-3) Srcs_eqI T Trgs.cases U assms)\n      qed\n    qed\n\n    lemma Arr_iff_Con_self:\n    shows \"Arr T \\<longleftrightarrow> T \\<^sup>*\\<frown>\\<^sup>* T\"\n    proof (induct T)\n      show \"Arr [] \\<longleftrightarrow> [] \\<^sup>*\\<frown>\\<^sup>* []\"\n        by simp\n      fix t T\n      assume ind: \"Arr T \\<longleftrightarrow> T \\<^sup>*\\<frown>\\<^sup>* T\"\n      show \"Arr (t # T) \\<longleftrightarrow> t # T \\<^sup>*\\<frown>\\<^sup>* t # T\"\n      proof (cases \"T = []\")\n        show \"T = [] \\<Longrightarrow> ?thesis\"\n          by auto\n        assume T: \"T \\<noteq> []\"\n        show ?thesis\n        proof\n          show \"Arr (t # T) \\<Longrightarrow> t # T \\<^sup>*\\<frown>\\<^sup>* t # T\"\n            using Con_Arr_self by simp\n          show \"t # T \\<^sup>*\\<frown>\\<^sup>* t # T \\<Longrightarrow> Arr (t # T)\"\n          proof -\n            assume Con: \"t # T \\<^sup>*\\<frown>\\<^sup>* t # T\"\n            have \"R.arr t\"\n              using T Con Con_rec(4) [of T T t t] by blast\n            moreover have \"Arr T\"\n              using T Con Con_rec(4) [of T T t t] ind R.arrI\n              by (meson R.prfx_reflexive Con_single_ide_ind)\n            moreover have \"R.targets t \\<subseteq> Srcs T\"\n              using T Con\n              by (metis Con_cons(2) Con_imp_eq_Srcs Trgs.simps(2)\n                  Srcs_Resid list.distinct(1) subsetI)\n            ultimately show ?thesis\n              by (cases T) auto\n          qed\n        qed\n      qed\n    qed\n\n    lemma Arr_Resid_single:\n    shows \"T \\<^sup>*\\<frown>\\<^sup>* [u] \\<Longrightarrow> Arr (T \\<^sup>*\\\\\\<^sup>* [u])\"\n    proof (induct T arbitrary: u)\n      show \"\\<And>u. [] \\<^sup>*\\<frown>\\<^sup>* [u] \\<Longrightarrow> Arr ([] \\<^sup>*\\\\\\<^sup>* [u])\"\n        by simp\n      fix t u T\n      assume ind: \"\\<And>u. T \\<^sup>*\\<frown>\\<^sup>* [u] \\<Longrightarrow> Arr (T \\<^sup>*\\\\\\<^sup>* [u])\"\n      assume Con: \"t # T \\<^sup>*\\<frown>\\<^sup>* [u]\"\n      show \"Arr ((t # T) \\<^sup>*\\\\\\<^sup>* [u])\"\n      proof (cases \"T = []\")\n        show \"T = [] \\<Longrightarrow> ?thesis\"\n          using Con Arr_iff_Con_self R.con_imp_arr_resid Con_rec(1) by fastforce\n        assume T: \"T \\<noteq> []\"\n        have \"Arr ((t # T) \\<^sup>*\\\\\\<^sup>* [u]) \\<longleftrightarrow> Arr ((t \\\\ u) # (T \\<^sup>*\\\\\\<^sup>* [u \\\\ t]))\"\n          using Con T Resid_rec(2) by auto\n        also have \"... \\<longleftrightarrow> R.arr (t \\\\ u) \\<and> Arr (T \\<^sup>*\\\\\\<^sup>* [u \\\\ t]) \\<and>\n                           R.targets (t \\\\ u) \\<subseteq> Srcs (T \\<^sup>*\\\\\\<^sup>* [u \\\\ t])\"\n          using Con T\n          by (metis Arr.simps(3) Con_rec(2) neq_Nil_conv)\n        also have \"... \\<longleftrightarrow> R.con t u \\<and> Arr (T \\<^sup>*\\\\\\<^sup>* [u \\\\ t])\"\n          using Con T\n          by (metis Srcs_Resid_Arr_single Con_rec(2) R.arr_resid_iff_con subsetI\n              R.targets_resid_sym)\n        also have \"... \\<longleftrightarrow> True\"\n          using Con ind T Con_rec(2) by blast\n        finally show ?thesis by auto\n      qed\n    qed\n\n    lemma Con_imp_Arr_Resid:\n    shows \"T \\<^sup>*\\<frown>\\<^sup>* U \\<Longrightarrow> Arr (T \\<^sup>*\\\\\\<^sup>* U)\"\n    proof (induct U arbitrary: T)\n      show \"\\<And>T. T \\<^sup>*\\<frown>\\<^sup>* [] \\<Longrightarrow> Arr (T \\<^sup>*\\\\\\<^sup>* [])\"\n        by (meson Con_sym Resid.simps(1))\n      fix u U T\n      assume ind: \"\\<And>T. T \\<^sup>*\\<frown>\\<^sup>* U \\<Longrightarrow> Arr (T \\<^sup>*\\\\\\<^sup>* U)\"\n      assume Con: \"T \\<^sup>*\\<frown>\\<^sup>* u # U\"\n      show \"Arr (T \\<^sup>*\\\\\\<^sup>* (u # U))\"\n        by (metis Arr_Resid_single Con Resid_cons(2) ind)\n    qed\n\n    lemma Cube_ind:\n    shows \"\\<lbrakk>T \\<^sup>*\\<frown>\\<^sup>* U; V \\<^sup>*\\<frown>\\<^sup>* T; length T + length U + length V \\<le> n\\<rbrakk> \\<Longrightarrow>\n             (V \\<^sup>*\\\\\\<^sup>* T \\<^sup>*\\<frown>\\<^sup>* U \\<^sup>*\\\\\\<^sup>* T \\<longleftrightarrow> V \\<^sup>*\\\\\\<^sup>* U \\<^sup>*\\<frown>\\<^sup>* T \\<^sup>*\\\\\\<^sup>* U) \\<and>\n             (V \\<^sup>*\\\\\\<^sup>* T \\<^sup>*\\<frown>\\<^sup>* U \\<^sup>*\\\\\\<^sup>* T \\<longrightarrow>\n               (V \\<^sup>*\\\\\\<^sup>* T) \\<^sup>*\\\\\\<^sup>* (U \\<^sup>*\\\\\\<^sup>* T) = (V \\<^sup>*\\\\\\<^sup>* U) \\<^sup>*\\\\\\<^sup>* (T \\<^sup>*\\\\\\<^sup>* U))\"\n    proof (induct n arbitrary: T U V)\n      show \"\\<And>T U V. \\<lbrakk>T \\<^sup>*\\<frown>\\<^sup>* U; V \\<^sup>*\\<frown>\\<^sup>* T; length T + length U + length V \\<le> 0\\<rbrakk> \\<Longrightarrow>\n                       (V \\<^sup>*\\\\\\<^sup>* T \\<^sup>*\\<frown>\\<^sup>* U \\<^sup>*\\\\\\<^sup>* T \\<longleftrightarrow> V \\<^sup>*\\\\\\<^sup>* U \\<^sup>*\\<frown>\\<^sup>* T \\<^sup>*\\\\\\<^sup>* U) \\<and>\n                       (V \\<^sup>*\\\\\\<^sup>* T \\<^sup>*\\<frown>\\<^sup>* U \\<^sup>*\\\\\\<^sup>* T \\<longrightarrow>\n                         (V \\<^sup>*\\\\\\<^sup>* T) \\<^sup>*\\\\\\<^sup>* (U \\<^sup>*\\\\\\<^sup>* T) = (V \\<^sup>*\\\\\\<^sup>* U) \\<^sup>*\\\\\\<^sup>* (T \\<^sup>*\\\\\\<^sup>* U))\"\n        by simp\n      fix n and T U V :: \"'a list\"\n      assume Con_TU: \"T \\<^sup>*\\<frown>\\<^sup>* U\" and Con_VT: \"V \\<^sup>*\\<frown>\\<^sup>* T\"\n      have T: \"T \\<noteq> []\"\n        using Con_TU by auto\n      have U: \"U \\<noteq> []\"\n        using Con_TU Con_sym Resid.simps(1) by blast\n      have V: \"V \\<noteq> []\"\n        using Con_VT by auto\n      assume len: \"length T + length U + length V \\<le> Suc n\"\n      assume ind: \"\\<And>T U V. \\<lbrakk>T \\<^sup>*\\<frown>\\<^sup>* U; V \\<^sup>*\\<frown>\\<^sup>* T; length T + length U + length V \\<le> n\\<rbrakk> \\<Longrightarrow>\n                            (V \\<^sup>*\\\\\\<^sup>* T \\<^sup>*\\<frown>\\<^sup>* U \\<^sup>*\\\\\\<^sup>* T \\<longleftrightarrow> V \\<^sup>*\\\\\\<^sup>* U \\<^sup>*\\<frown>\\<^sup>* T \\<^sup>*\\\\\\<^sup>* U) \\<and>\n                            (V \\<^sup>*\\\\\\<^sup>* T \\<^sup>*\\<frown>\\<^sup>* U \\<^sup>*\\\\\\<^sup>* T \\<longrightarrow>\n                              (V \\<^sup>*\\\\\\<^sup>* T) \\<^sup>*\\\\\\<^sup>* (U \\<^sup>*\\\\\\<^sup>* T) = (V \\<^sup>*\\\\\\<^sup>* U) \\<^sup>*\\\\\\<^sup>* (T \\<^sup>*\\\\\\<^sup>* U))\"\n      show \"(V \\<^sup>*\\\\\\<^sup>* T \\<^sup>*\\<frown>\\<^sup>* U \\<^sup>*\\\\\\<^sup>* T \\<longleftrightarrow> V \\<^sup>*\\\\\\<^sup>* U \\<^sup>*\\<frown>\\<^sup>* T \\<^sup>*\\\\\\<^sup>* U) \\<and>\n            (V \\<^sup>*\\\\\\<^sup>* T \\<^sup>*\\<frown>\\<^sup>* U \\<^sup>*\\\\\\<^sup>* T \\<longrightarrow> (V \\<^sup>*\\\\\\<^sup>* T) \\<^sup>*\\\\\\<^sup>* (U \\<^sup>*\\\\\\<^sup>* T) = (V \\<^sup>*\\\\\\<^sup>* U) \\<^sup>*\\\\\\<^sup>* (T \\<^sup>*\\\\\\<^sup>* U))\"\n      proof (cases V)\n        show \"V = [] \\<Longrightarrow> ?thesis\"\n          using V by simp\n        (*\n         * TODO: I haven't found a better way to do this than just consider each combination\n         * of T U V being a singleton.\n         *)\n        fix v V'\n        assume V: \"V = v # V'\"\n        show ?thesis\n        proof (cases U)\n          show \"U = [] \\<Longrightarrow> ?thesis\"\n            using U by simp\n          fix u U'\n          assume U: \"U = u # U'\"\n          show ?thesis\n          proof (cases T)\n            show \"T = [] \\<Longrightarrow> ?thesis\"\n              using T by simp\n            fix t T'\n            assume T: \"T = t # T'\"\n            show ?thesis\n            proof (cases \"V' = []\", cases \"U' = []\", cases \"T' = []\")\n              show \"\\<lbrakk>V' = []; U' = []; T' = []\\<rbrakk> \\<Longrightarrow> ?thesis\"\n                using T U V R.cube Con_TU Resid.simps(2) Resid.simps(3) R.arr_resid_iff_con\n                      R.con_implies_arr Con_sym\n                by metis\n              assume T': \"T' \\<noteq> []\" and V': \"V' = []\" and U': \"U' = []\"\n              have 1: \"U \\<^sup>*\\<frown>\\<^sup>* [t]\"\n                using T Con_TU Con_cons(2) Con_sym Resid.simps(2) by metis\n              have 2: \"V \\<^sup>*\\<frown>\\<^sup>* [t]\"\n                using V Con_VT Con_initial_right T by blast\n              show ?thesis\n              proof (intro conjI impI)\n                have 3: \"length [t] + length U + length V \\<le> n\"\n                  using T T' le_Suc_eq len by fastforce\n                show *: \"V \\<^sup>*\\\\\\<^sup>* T \\<^sup>*\\<frown>\\<^sup>* U \\<^sup>*\\\\\\<^sup>* T \\<longleftrightarrow> V \\<^sup>*\\\\\\<^sup>* U \\<^sup>*\\<frown>\\<^sup>* T \\<^sup>*\\\\\\<^sup>* U\"\n                proof -\n                  have \"V \\<^sup>*\\\\\\<^sup>* T \\<^sup>*\\<frown>\\<^sup>* U \\<^sup>*\\\\\\<^sup>* T \\<longleftrightarrow> (V \\<^sup>*\\\\\\<^sup>* [t]) \\<^sup>*\\\\\\<^sup>* T' \\<^sup>*\\<frown>\\<^sup>* (U \\<^sup>*\\\\\\<^sup>* [t]) \\<^sup>*\\\\\\<^sup>* T'\"\n                    using Con_TU Con_VT Con_sym Resid_cons(2) T T' by force\n                  also have \"... \\<longleftrightarrow> V \\<^sup>*\\\\\\<^sup>* [t] \\<^sup>*\\<frown>\\<^sup>* U \\<^sup>*\\\\\\<^sup>* [t] \\<and>\n                                     (V \\<^sup>*\\\\\\<^sup>* [t]) \\<^sup>*\\\\\\<^sup>* (U \\<^sup>*\\\\\\<^sup>* [t]) \\<^sup>*\\<frown>\\<^sup>* T' \\<^sup>*\\\\\\<^sup>* (U \\<^sup>*\\\\\\<^sup>* [t])\"\n                  proof (intro iffI conjI)\n                    show \"(V \\<^sup>*\\\\\\<^sup>* [t]) \\<^sup>*\\\\\\<^sup>* T' \\<^sup>*\\<frown>\\<^sup>* (U \\<^sup>*\\\\\\<^sup>* [t]) \\<^sup>*\\\\\\<^sup>* T' \\<Longrightarrow> V \\<^sup>*\\\\\\<^sup>* [t] \\<^sup>*\\<frown>\\<^sup>* U \\<^sup>*\\\\\\<^sup>* [t]\"\n                      using T U V T' U' V' 1 ind len Con_TU Con_rec(2) Resid_rec(1)\n                            Resid.simps(1) length_Cons Suc_le_mono add_Suc\n                      by (metis (no_types))\n                    show \"(V \\<^sup>*\\\\\\<^sup>* [t]) \\<^sup>*\\\\\\<^sup>* T' \\<^sup>*\\<frown>\\<^sup>* (U \\<^sup>*\\\\\\<^sup>* [t]) \\<^sup>*\\\\\\<^sup>* T' \\<Longrightarrow>\n                          (V \\<^sup>*\\\\\\<^sup>* [t]) \\<^sup>*\\\\\\<^sup>* (U \\<^sup>*\\\\\\<^sup>* [t]) \\<^sup>*\\<frown>\\<^sup>* T' \\<^sup>*\\\\\\<^sup>* (U \\<^sup>*\\\\\\<^sup>* [t])\"\n                      using T U V T' U' V'\n                      by (metis Con_sym Resid.simps(1) Resid_rec(1) Suc_le_mono ind len\n                          length_Cons list.size(3-4))\n                    show \"V \\<^sup>*\\\\\\<^sup>* [t] \\<^sup>*\\<frown>\\<^sup>* U \\<^sup>*\\\\\\<^sup>* [t] \\<and>\n                          (V \\<^sup>*\\\\\\<^sup>* [t]) \\<^sup>*\\\\\\<^sup>* (U \\<^sup>*\\\\\\<^sup>* [t]) \\<^sup>*\\<frown>\\<^sup>* T' \\<^sup>*\\\\\\<^sup>* (U \\<^sup>*\\\\\\<^sup>* [t]) \\<Longrightarrow>\n                            (V \\<^sup>*\\\\\\<^sup>* [t]) \\<^sup>*\\\\\\<^sup>* T' \\<^sup>*\\<frown>\\<^sup>* (U \\<^sup>*\\\\\\<^sup>* [t]) \\<^sup>*\\\\\\<^sup>* T'\"\n                      using T U V T' U' V' 1 ind len Con_TU Con_VT Con_rec(1-3)\n                      by (metis (no_types, lifting) One_nat_def Resid_rec(1) Suc_le_mono\n                          add.commute list.size(3) list.size(4) plus_1_eq_Suc)\n                  qed\n                  also have \"... \\<longleftrightarrow> (V \\<^sup>*\\\\\\<^sup>* U) \\<^sup>*\\\\\\<^sup>* ([t] \\<^sup>*\\\\\\<^sup>* U) \\<^sup>*\\<frown>\\<^sup>* T' \\<^sup>*\\\\\\<^sup>* (U \\<^sup>*\\\\\\<^sup>* [t])\"\n                    by (metis 2 3 Con_sym ind Resid.simps(1))\n                  also have \"... \\<longleftrightarrow> V \\<^sup>*\\\\\\<^sup>* U \\<^sup>*\\<frown>\\<^sup>* T \\<^sup>*\\\\\\<^sup>* U\"\n                    using Con_rec(2) [of T' t]\n                    by (metis (no_types, lifting) \"1\" Con_TU Con_cons(2) Resid.simps(1)\n                        Resid.simps(3) Resid_rec(2) T T' U U')\n                  finally show ?thesis by simp\n                qed\n                assume Con: \"V \\<^sup>*\\\\\\<^sup>* T \\<^sup>*\\<frown>\\<^sup>* U \\<^sup>*\\\\\\<^sup>* T\"\n                show \"(V \\<^sup>*\\\\\\<^sup>* T) \\<^sup>*\\\\\\<^sup>* (U \\<^sup>*\\\\\\<^sup>* T) = (V \\<^sup>*\\\\\\<^sup>* U) \\<^sup>*\\\\\\<^sup>* (T \\<^sup>*\\\\\\<^sup>* U)\"\n                proof -\n                  have \"(V \\<^sup>*\\\\\\<^sup>* T) \\<^sup>*\\\\\\<^sup>* (U \\<^sup>*\\\\\\<^sup>* T) = ((V \\<^sup>*\\\\\\<^sup>* [t]) \\<^sup>*\\\\\\<^sup>* T') \\<^sup>*\\\\\\<^sup>* ((U \\<^sup>*\\\\\\<^sup>* [t]) \\<^sup>*\\\\\\<^sup>* T')\"\n                    using Con_TU Con_VT Con_sym Resid_cons(2) T T' by force\n                  also have \"... = ((V \\<^sup>*\\\\\\<^sup>* [t]) \\<^sup>*\\\\\\<^sup>* (U \\<^sup>*\\\\\\<^sup>* [t])) \\<^sup>*\\\\\\<^sup>* (T' \\<^sup>*\\\\\\<^sup>* (U \\<^sup>*\\\\\\<^sup>* [t]))\"\n                    using T U V T' U' V' 1 Con ind [of T' \"Resid U [t]\" \"Resid V [t]\"]\n                    by (metis One_nat_def add.commute calculation len length_0_conv length_Resid\n                        list.size(4) nat_add_left_cancel_le Con_sym plus_1_eq_Suc)\n                  also have \"... = ((V \\<^sup>*\\\\\\<^sup>* U) \\<^sup>*\\\\\\<^sup>* ([t] \\<^sup>*\\\\\\<^sup>* U)) \\<^sup>*\\\\\\<^sup>* (T' \\<^sup>*\\\\\\<^sup>* (U \\<^sup>*\\\\\\<^sup>* [t]))\"\n                    by (metis \"1\" \"2\" \"3\" Con_sym ind)\n                  also have \"... = (V \\<^sup>*\\\\\\<^sup>* U) \\<^sup>*\\\\\\<^sup>* (T \\<^sup>*\\\\\\<^sup>* U)\"\n                    using T U T' U' Con *\n                    by (metis Con_sym Resid_rec(1-2) Resid.simps(1) Resid_cons(2))\n                  finally show ?thesis by simp\n                qed\n              qed\n              next\n              assume U': \"U' \\<noteq> []\" and V': \"V' = []\"\n              show ?thesis\n              proof (intro conjI impI)\n                show *: \"V \\<^sup>*\\\\\\<^sup>* T \\<^sup>*\\<frown>\\<^sup>* U \\<^sup>*\\\\\\<^sup>* T \\<longleftrightarrow> V \\<^sup>*\\\\\\<^sup>* U \\<^sup>*\\<frown>\\<^sup>* T \\<^sup>*\\\\\\<^sup>* U\"\n                proof (cases \"T' = []\")\n                  assume T': \"T' = []\"\n                  show ?thesis\n                  proof -\n                    have \"V \\<^sup>*\\\\\\<^sup>* T \\<^sup>*\\<frown>\\<^sup>* U \\<^sup>*\\\\\\<^sup>* T \\<longleftrightarrow> V \\<^sup>*\\\\\\<^sup>* [t] \\<^sup>*\\<frown>\\<^sup>* (u \\\\ t) # (U' \\<^sup>*\\\\\\<^sup>* [t \\\\ u])\"\n                      using Con_TU Con_sym Resid_rec(2) T T' U U' by auto\n                    also have \"... \\<longleftrightarrow> (V \\<^sup>*\\\\\\<^sup>* [t]) \\<^sup>*\\\\\\<^sup>* [u \\\\ t] \\<^sup>*\\<frown>\\<^sup>* U' \\<^sup>*\\\\\\<^sup>* [t \\\\ u]\"\n                      by (metis Con_TU Con_cons(2) Con_rec(3) Con_sym Resid.simps(1) T U U')\n                    also have \"... \\<longleftrightarrow> (V \\<^sup>*\\\\\\<^sup>* [u]) \\<^sup>*\\\\\\<^sup>* [t \\\\ u] \\<^sup>*\\<frown>\\<^sup>* U' \\<^sup>*\\\\\\<^sup>* [t \\\\ u]\"\n                      using T U V V' R.cube_ax\n                      apply simp\n                      by (metis R.con_implies_arr(1) R.not_arr_null R.con_def)\n                    also have \"... \\<longleftrightarrow> (V \\<^sup>*\\\\\\<^sup>* [u]) \\<^sup>*\\\\\\<^sup>* U' \\<^sup>*\\<frown>\\<^sup>* [t \\\\ u] \\<^sup>*\\\\\\<^sup>* U'\"\n                    proof -\n                      have \"length [t \\\\ u] + length U' + length (V \\<^sup>*\\\\\\<^sup>* [u]) \\<le> n\"\n                        using T U V V' len by force\n                      thus ?thesis\n                        by (metis Con_sym Resid.simps(1) add.commute ind)\n                    qed\n                    also have \"... \\<longleftrightarrow> V \\<^sup>*\\\\\\<^sup>* U \\<^sup>*\\<frown>\\<^sup>* T \\<^sup>*\\\\\\<^sup>* U\"\n                      by (metis Con_TU Resid_cons(2) Resid_rec(3) T T' U U' Con_cons(2)\n                          length_Resid length_0_conv)\n                    finally show ?thesis by simp\n                  qed\n                  next\n                  assume T': \"T' \\<noteq> []\"\n                  show ?thesis\n                  proof -\n                    have \"V \\<^sup>*\\\\\\<^sup>* T \\<^sup>*\\<frown>\\<^sup>* U \\<^sup>*\\\\\\<^sup>* T \\<longleftrightarrow> (V \\<^sup>*\\\\\\<^sup>* [t]) \\<^sup>*\\\\\\<^sup>* T' \\<^sup>*\\<frown>\\<^sup>* ((U \\<^sup>*\\\\\\<^sup>* [t]) \\<^sup>*\\\\\\<^sup>* T')\"\n                      using Con_TU Con_VT Con_sym Resid_cons(2) T T' by force\n                    also have \"... \\<longleftrightarrow> (V \\<^sup>*\\\\\\<^sup>* [t]) \\<^sup>*\\\\\\<^sup>* (U \\<^sup>*\\\\\\<^sup>* [t]) \\<^sup>*\\<frown>\\<^sup>* T' \\<^sup>*\\\\\\<^sup>* (U \\<^sup>*\\\\\\<^sup>* [t])\"\n                    proof -\n                      have \"length T' + length (U \\<^sup>*\\\\\\<^sup>* [t]) + length (V \\<^sup>*\\\\\\<^sup>* [t]) \\<le> n\"\n                        by (metis (no_types, lifting) Con_TU Con_VT Con_initial_right Con_sym\n                            One_nat_def Suc_eq_plus1 T ab_semigroup_add_class.add_ac(1)\n                            add_le_imp_le_left len length_Resid list.size(4) plus_1_eq_Suc)\n                      thus ?thesis\n                        by (metis Con_TU Con_VT Con_cons(1) Con_cons(2) T T' U V ind list.discI)\n                    qed\n                    also have \"... \\<longleftrightarrow> (V \\<^sup>*\\\\\\<^sup>* U) \\<^sup>*\\\\\\<^sup>* ([t] \\<^sup>*\\\\\\<^sup>* U) \\<^sup>*\\<frown>\\<^sup>* T' \\<^sup>*\\\\\\<^sup>* (U \\<^sup>*\\\\\\<^sup>* [t])\"\n                    proof -\n                      have \"length [t] + length U + length V \\<le> n\"\n                        using T T' le_Suc_eq len by fastforce\n                      thus ?thesis\n                        by (metis Con_TU Con_VT Con_initial_left Con_initial_right T ind)\n                    qed\n                    also have \"... \\<longleftrightarrow> V \\<^sup>*\\\\\\<^sup>* U \\<^sup>*\\<frown>\\<^sup>* T \\<^sup>*\\\\\\<^sup>* U\"\n                      by (metis Con_cons(2) Con_sym Resid.simps(1) Resid1x_as_Resid\n                          Residx1_as_Resid Resid_cons' T T')\n                    finally show ?thesis by blast\n                  qed\n                qed\n                show \"V \\<^sup>*\\\\\\<^sup>* T \\<^sup>*\\<frown>\\<^sup>* U \\<^sup>*\\\\\\<^sup>* T \\<Longrightarrow>\n                        (V \\<^sup>*\\\\\\<^sup>* T) \\<^sup>*\\\\\\<^sup>* (U \\<^sup>*\\\\\\<^sup>* T) = (V \\<^sup>*\\\\\\<^sup>* U) \\<^sup>*\\\\\\<^sup>* (T \\<^sup>*\\\\\\<^sup>* U)\"\n                proof -\n                  assume Con: \"V \\<^sup>*\\\\\\<^sup>* T \\<^sup>*\\<frown>\\<^sup>* U \\<^sup>*\\\\\\<^sup>* T\"\n                  show ?thesis\n                  proof (cases \"T' = []\")\n                    assume T': \"T' = []\"\n                    show ?thesis\n                    proof -\n                      have 1: \"(V \\<^sup>*\\\\\\<^sup>* T) \\<^sup>*\\\\\\<^sup>* (U \\<^sup>*\\\\\\<^sup>* T) =\n                               (V \\<^sup>*\\\\\\<^sup>* T) \\<^sup>*\\\\\\<^sup>* ((u \\\\ t) # (U'\\<^sup>*\\\\\\<^sup>* [t \\\\ u]))\"\n                        using Con_TU Con_sym Resid_rec(2) T T' U U' by force\n                      also have \"... = ((V \\<^sup>*\\\\\\<^sup>* [t]) \\<^sup>*\\\\\\<^sup>* [u \\\\ t]) \\<^sup>*\\\\\\<^sup>* (U' \\<^sup>*\\\\\\<^sup>* [t \\\\ u])\"\n                        by (metis Con Con_TU Con_rec(2) Con_sym Resid_cons(2) T T' U U'\n                            calculation)\n                      also have \"... = ((V \\<^sup>*\\\\\\<^sup>* [u]) \\<^sup>*\\\\\\<^sup>* [t \\\\ u]) \\<^sup>*\\\\\\<^sup>* (U' \\<^sup>*\\\\\\<^sup>* [t \\\\ u])\"\n                        by (metis \"*\" Con Con_rec(3) R.cube Resid.simps(1,3) T T' U V V'\n                            calculation R.conI R.conE)\n                      also have \"... = ((V \\<^sup>*\\\\\\<^sup>* [u]) \\<^sup>*\\\\\\<^sup>* U') \\<^sup>*\\\\\\<^sup>* ([t \\\\ u] \\<^sup>*\\\\\\<^sup>* U')\"\n                      proof -\n                        have \"length [t \\\\ u] + length (U' \\<^sup>*\\\\\\<^sup>* [t \\\\ u]) + length (V \\<^sup>*\\\\\\<^sup>* [u]) \\<le> n\"\n                          by (metis (no_types, lifting) Nat.le_diff_conv2 One_nat_def T U V V'\n                              add.commute add_diff_cancel_left' add_leD2 len length_Cons\n                              length_Resid list.size(3) plus_1_eq_Suc)\n                        thus ?thesis\n                          by (metis Con_sym add.commute Resid.simps(1) ind length_Resid)\n                      qed\n                      also have \"... = (V \\<^sup>*\\\\\\<^sup>* U) \\<^sup>*\\\\\\<^sup>* (T \\<^sup>*\\\\\\<^sup>* U)\"\n                        by (metis Con_TU Con_cons(2) Resid_cons(2) T T' U U'\n                            Resid_rec(3) length_0_conv length_Resid)\n                      finally show ?thesis by blast\n                    qed\n                    next\n                    assume T': \"T' \\<noteq> []\"\n                    show ?thesis\n                    proof -\n                      have \"(V \\<^sup>*\\\\\\<^sup>* T) \\<^sup>*\\\\\\<^sup>* (U \\<^sup>*\\\\\\<^sup>* T) =\n                            ((V \\<^sup>*\\\\\\<^sup>* T) \\<^sup>*\\\\\\<^sup>* ([u] \\<^sup>*\\\\\\<^sup>* T)) \\<^sup>*\\\\\\<^sup>* (U' \\<^sup>*\\\\\\<^sup>* (T \\<^sup>*\\\\\\<^sup>* [u]))\"\n                        by (metis Con Con_TU Resid.simps(2) Resid1x_as_Resid U U'\n                            Con_cons(2) Con_sym Resid_cons' Resid_cons(2))\n                      also have \"... = ((V \\<^sup>*\\\\\\<^sup>* [u]) \\<^sup>*\\\\\\<^sup>* (T \\<^sup>*\\\\\\<^sup>* [u])) \\<^sup>*\\\\\\<^sup>* (U' \\<^sup>*\\\\\\<^sup>* (T \\<^sup>*\\\\\\<^sup>* [u]))\"\n                      proof -\n                        have \"length T + length [u] + length V \\<le> n\"\n                          using U U' antisym_conv len not_less_eq_eq by fastforce\n                        thus ?thesis\n                          by (metis Con_TU Con_VT Con_initial_right U ind)\n                      qed\n                      also have \"... = ((V \\<^sup>*\\\\\\<^sup>* [u]) \\<^sup>*\\\\\\<^sup>* U') \\<^sup>*\\\\\\<^sup>* ((T \\<^sup>*\\\\\\<^sup>* [u]) \\<^sup>*\\\\\\<^sup>* U')\"\n                      proof -\n                        have \"length (T \\<^sup>*\\\\\\<^sup>* [u]) + length U' + length (V \\<^sup>*\\\\\\<^sup>* [u]) \\<le> n\"\n                          using Con_TU Con_initial_right U V V' len length_Resid by force\n                        thus ?thesis\n                          by (metis Con Con_TU Con_cons(2) U U' calculation ind length_0_conv\n                              length_Resid)\n                      qed\n                      also have \"... = (V \\<^sup>*\\\\\\<^sup>* U) \\<^sup>*\\\\\\<^sup>* (T \\<^sup>*\\\\\\<^sup>* U)\"\n                        by (metis \"*\" Con Con_TU Resid_cons(2) U U' length_Resid length_0_conv)\n                      finally show ?thesis by blast\n                    qed\n                  qed\n                qed\n              qed\n              next\n              assume V': \"V' \\<noteq> []\"\n              show ?thesis\n              proof (cases \"U' = []\")\n                assume U': \"U' = []\"\n                show ?thesis\n                proof (cases \"T' = []\")\n                  assume T': \"T' = []\"\n                  show ?thesis\n                  proof (intro conjI impI)\n                    show *: \"V \\<^sup>*\\\\\\<^sup>* T \\<^sup>*\\<frown>\\<^sup>* U \\<^sup>*\\\\\\<^sup>* T \\<longleftrightarrow>  V \\<^sup>*\\\\\\<^sup>* U \\<^sup>*\\<frown>\\<^sup>* T \\<^sup>*\\\\\\<^sup>* U\"\n                    proof -\n                      have \"V \\<^sup>*\\\\\\<^sup>* T \\<^sup>*\\<frown>\\<^sup>* U \\<^sup>*\\\\\\<^sup>* T \\<longleftrightarrow> (v \\\\ t) # (V' \\<^sup>*\\\\\\<^sup>* [t \\\\ v]) \\<^sup>*\\<frown>\\<^sup>* [u \\\\ t]\"\n                        using Con_TU Con_VT Con_sym Resid_rec(1-2) T T' U U' V V'\n                        by metis\n                      also have \"... \\<longleftrightarrow> [v \\\\ t] \\<^sup>*\\<frown>\\<^sup>* [u \\\\ t] \\<and>\n                                         V' \\<^sup>*\\\\\\<^sup>* [t \\\\ v] \\<^sup>*\\<frown>\\<^sup>* [u \\\\ v] \\<^sup>*\\\\\\<^sup>* [t \\\\ v]\"\n                        by (metis T T' V V' Con_VT Con_rec(1-2) Con_sym R.con_def R.cube\n                            Resid.simps(3))\n                      also have \"... \\<longleftrightarrow> [v \\\\ t] \\<^sup>*\\<frown>\\<^sup>* [u \\\\ t] \\<and>\n                                         V' \\<^sup>*\\\\\\<^sup>* [u \\\\ v] \\<^sup>*\\<frown>\\<^sup>* [t \\\\ v] \\<^sup>*\\\\\\<^sup>* [u \\\\ v]\"\n                      proof -\n                        have \"length [t \\\\ v] + length [u \\\\ v] + length V' \\<le> n\"\n                          using T U V len by fastforce\n                        thus ?thesis\n                          by (metis Con_imp_Arr_Resid Arr_has_Src Con_VT T T' Trgs.simps(1)\n                              Trgs_Resid_sym V V' Con_rec(2) Srcs_Resid ind)\n                      qed\n                      also have \"... \\<longleftrightarrow> [v \\\\ t] \\<^sup>*\\<frown>\\<^sup>* [u \\\\ t] \\<and>\n                                         V' \\<^sup>*\\\\\\<^sup>* [u \\\\ v] \\<^sup>*\\<frown>\\<^sup>* [t \\\\ u] \\<^sup>*\\\\\\<^sup>* [v \\\\ u]\"\n                        by (simp add: R.con_def R.cube)\n                      also have \"... \\<longleftrightarrow> V \\<^sup>*\\\\\\<^sup>* U \\<^sup>*\\<frown>\\<^sup>* T \\<^sup>*\\\\\\<^sup>* U\"\n                      proof\n                        assume 1: \"V \\<^sup>*\\\\\\<^sup>* U \\<^sup>*\\<frown>\\<^sup>* T \\<^sup>*\\\\\\<^sup>* U\"\n                        have tu_vu: \"t \\\\ u \\<frown> v \\\\ u\"\n                          by (metis (no_types, lifting) 1 T T' U U' V V' Con_rec(3)\n                              Resid_rec(1-2) Con_sym length_Resid length_0_conv)\n                        have vt_ut: \"v \\\\ t \\<frown> u \\\\ t\"\n                          using 1\n                          by (metis R.con_def R.con_sym R.cube tu_vu)\n                        show \"[v \\\\ t] \\<^sup>*\\<frown>\\<^sup>* [u \\\\ t] \\<and> V' \\<^sup>*\\\\\\<^sup>* [u \\\\ v] \\<^sup>*\\<frown>\\<^sup>* [t \\\\ u] \\<^sup>*\\\\\\<^sup>* [v \\\\ u]\"\n                          by (metis (no_types, lifting) \"1\" Con_TU Con_cons(1) Con_rec(1-2)\n                              Resid_rec(1) T T' U U' V V' Resid_rec(2) length_Resid\n                              length_0_conv vt_ut)\n                        next\n                        assume 1: \"[v \\\\ t] \\<^sup>*\\<frown>\\<^sup>* [u \\\\ t] \\<and>\n                                   V' \\<^sup>*\\\\\\<^sup>* [u \\\\ v] \\<^sup>*\\<frown>\\<^sup>* [t \\\\ u] \\<^sup>*\\\\\\<^sup>* [v \\\\ u]\"\n                        have tu_vu: \"t \\\\ u \\<frown> v \\\\ u \\<and> v \\\\ t \\<frown> u \\\\ t\"\n                          by (metis 1 Con_sym Resid.simps(1) Residx1.simps(2)\n                              Residx1_as_Resid)\n                        have tu: \"t \\<frown> u\"\n                          using Con_TU Con_rec(1) T T' U U' by blast\n                        show \"V \\<^sup>*\\\\\\<^sup>* U \\<^sup>*\\<frown>\\<^sup>* T \\<^sup>*\\\\\\<^sup>* U\"\n                          by (metis (no_types, opaque_lifting) 1 Con_rec(2) Con_sym\n                              R.con_implies_arr(2) Resid.simps(1,3) T T' U U' V V'\n                              Resid_rec(2) R.arr_resid_iff_con)\n                      qed\n                      finally show ?thesis by simp\n                    qed\n                    show \"V \\<^sup>*\\\\\\<^sup>* T \\<^sup>*\\<frown>\\<^sup>* U \\<^sup>*\\\\\\<^sup>* T \\<Longrightarrow>\n                            (V \\<^sup>*\\\\\\<^sup>* T) \\<^sup>*\\\\\\<^sup>* (U \\<^sup>*\\\\\\<^sup>* T) = (V \\<^sup>*\\\\\\<^sup>* U) \\<^sup>*\\\\\\<^sup>* (T \\<^sup>*\\\\\\<^sup>* U)\"\n                    proof -\n                      assume Con: \"V \\<^sup>*\\\\\\<^sup>* T \\<^sup>*\\<frown>\\<^sup>* U \\<^sup>*\\\\\\<^sup>* T\"\n                      have \"(V \\<^sup>*\\\\\\<^sup>* T) \\<^sup>*\\\\\\<^sup>* (U \\<^sup>*\\\\\\<^sup>* T) = ((v \\\\ t) # (V' \\<^sup>*\\\\\\<^sup>* [t \\\\ v])) \\<^sup>*\\\\\\<^sup>* [u \\\\ t]\"\n                        using Con_TU Con_VT Con_sym Resid_rec(1-2) T T' U U' V V' by metis\n                      also have 1: \"... = ((v \\\\ t) \\\\ (u \\\\ t)) #\n                                            (V' \\<^sup>*\\\\\\<^sup>* [t \\\\ v]) \\<^sup>*\\\\\\<^sup>* ([u \\\\ v] \\<^sup>*\\\\\\<^sup>* [t \\\\ v])\"\n                        apply simp\n                        by (metis Con Con_VT Con_rec(2) R.conE R.conI R.con_sym R.cube\n                            Resid_rec(2) T T' V V' calculation(1))\n                      also have \"... = ((v \\\\ t) \\\\ (u \\\\ t)) #\n                                         (V' \\<^sup>*\\\\\\<^sup>* [u \\\\ v]) \\<^sup>*\\\\\\<^sup>* ([t \\\\ v] \\<^sup>*\\\\\\<^sup>* [u \\\\ v])\"\n                      proof -\n                        have \"length [t \\\\ v] + length [u \\\\ v] + length V' \\<le> n\"\n                          using T U V len by fastforce\n                        moreover have \"u \\\\ v \\<frown> t \\\\ v\"\n                          by (metis 1 Con_VT Con_rec(2) R.con_sym_ax T T' V V' list.discI\n                              R.conE R.conI R.cube)\n                        moreover have \"t \\\\ v \\<frown> u \\\\ v\"\n                          using R.con_sym calculation(2) by blast\n                        ultimately show ?thesis\n                          by (metis Con_VT Con_rec(2) T T' V V' Con_rec(1) ind)\n                      qed\n                      also have \"... = ((v \\\\ t) \\\\ (u \\\\ t)) #\n                                         ((V' \\<^sup>*\\\\\\<^sup>* [u \\\\ v]) \\<^sup>*\\\\\\<^sup>* ([t \\\\ u] \\<^sup>*\\\\\\<^sup>* [v \\\\ u]))\"\n                        using R.cube by fastforce\n                      also have \"... = ((v \\\\ u) \\\\ (t \\\\ u)) #\n                                         ((V' \\<^sup>*\\\\\\<^sup>* [u \\\\ v]) \\<^sup>*\\\\\\<^sup>* ([t \\\\ u] \\<^sup>*\\\\\\<^sup>* [v \\\\ u]))\"\n                        by (metis R.cube)\n                      also have \"... = (V \\<^sup>*\\\\\\<^sup>* U) \\<^sup>*\\\\\\<^sup>* (T \\<^sup>*\\\\\\<^sup>* U)\"\n                      proof -\n                        have \"(V \\<^sup>*\\\\\\<^sup>* U) \\<^sup>*\\\\\\<^sup>* (T \\<^sup>*\\\\\\<^sup>* U) = ((v \\\\ u) # ((V' \\<^sup>*\\\\\\<^sup>* [u \\\\ v]))) \\<^sup>*\\\\\\<^sup>* [t \\\\ u]\"\n                           using T T' U U' V Resid_cons(1) [of \"[u]\" v V']\n                           by (metis \"*\" Con Con_TU Resid.simps(1) Resid_rec(1) Resid_rec(2))\n                        also have \"... = ((v \\\\ u) \\\\ (t \\\\ u)) #\n                                           ((V' \\<^sup>*\\\\\\<^sup>* [u \\\\ v]) \\<^sup>*\\\\\\<^sup>* ([t \\\\ u] \\<^sup>*\\\\\\<^sup>* [v \\\\ u]))\"\n                          by (metis \"*\" Con Con_initial_left calculation Con_sym Resid.simps(1)\n                                    Resid_rec(1-2))\n                        finally show ?thesis by simp\n                      qed\n                      finally show ?thesis by simp\n                    qed\n                  qed\n                  next\n                  assume T': \"T' \\<noteq> []\"\n                  show ?thesis\n                  proof (intro conjI impI)\n                    show *: \"V \\<^sup>*\\\\\\<^sup>* T \\<^sup>*\\<frown>\\<^sup>* U \\<^sup>*\\\\\\<^sup>* T \\<longleftrightarrow>  V \\<^sup>*\\\\\\<^sup>* U \\<^sup>*\\<frown>\\<^sup>* T \\<^sup>*\\\\\\<^sup>* U\"\n                    proof -\n                      have \"V \\<^sup>*\\\\\\<^sup>* T \\<^sup>*\\<frown>\\<^sup>* U \\<^sup>*\\\\\\<^sup>* T \\<longleftrightarrow> (V \\<^sup>*\\\\\\<^sup>* [t]) \\<^sup>*\\\\\\<^sup>* T' \\<^sup>*\\<frown>\\<^sup>* [u \\\\ t] \\<^sup>*\\\\\\<^sup>* T'\"\n                        using Con_TU Con_VT Con_sym Resid_cons(2) Resid_rec(3) T T' U U'\n                        by force\n                      also have \"... \\<longleftrightarrow> (V \\<^sup>*\\\\\\<^sup>* [t]) \\<^sup>*\\\\\\<^sup>* [u \\\\ t] \\<^sup>*\\<frown>\\<^sup>* T' \\<^sup>*\\\\\\<^sup>* [u \\\\ t]\"\n                      proof -\n                        have \"length [u \\\\ t] + length T' + length (V \\<^sup>*\\\\\\<^sup>* [t]) \\<le> n\"\n                          using Con_VT Con_initial_right T U length_Resid len by fastforce\n                        thus ?thesis\n                          by (metis Con_TU Con_VT Con_rec(2) T T' U V add.commute Con_cons(2)\n                              ind list.discI)\n                      qed\n                      also have \"... \\<longleftrightarrow> (V \\<^sup>*\\\\\\<^sup>* [u]) \\<^sup>*\\\\\\<^sup>* [t \\\\ u] \\<^sup>*\\<frown>\\<^sup>* T' \\<^sup>*\\\\\\<^sup>* [u \\\\ t]\"\n                      proof -\n                        have \"length [t] + length [u] + length V \\<le> n\"\n                          using T T' U le_Suc_eq len by fastforce\n                        hence \"(V \\<^sup>*\\\\\\<^sup>* [t]) \\<^sup>*\\\\\\<^sup>* ([u] \\<^sup>*\\\\\\<^sup>* [t]) = (V \\<^sup>*\\\\\\<^sup>* [u]) \\<^sup>*\\\\\\<^sup>* ([t] \\<^sup>*\\\\\\<^sup>* [u])\"\n                          using ind [of \"[t]\" \"[u]\" V]\n                          by (metis Con_TU Con_VT Con_initial_left Con_initial_right T U)\n                        thus ?thesis\n                          by (metis (full_types) Con_TU Con_initial_left Con_sym Resid_rec(1) T U)\n                      qed\n                      also have \"... \\<longleftrightarrow> V \\<^sup>*\\\\\\<^sup>* U \\<^sup>*\\<frown>\\<^sup>* T \\<^sup>*\\\\\\<^sup>* U\"\n                        by (metis Con_TU Con_cons(2) Con_rec(2) Resid.simps(1) Resid_rec(2)\n                            T T' U U')\n                      finally show ?thesis by simp\n                    qed\n                    show \"V \\<^sup>*\\\\\\<^sup>* T \\<^sup>*\\<frown>\\<^sup>* U \\<^sup>*\\\\\\<^sup>* T \\<Longrightarrow>\n                           (V \\<^sup>*\\\\\\<^sup>* T) \\<^sup>*\\\\\\<^sup>* (U \\<^sup>*\\\\\\<^sup>* T) = (V \\<^sup>*\\\\\\<^sup>* U) \\<^sup>*\\\\\\<^sup>* (T \\<^sup>*\\\\\\<^sup>* U)\"\n                    proof -\n                      assume Con: \"V \\<^sup>*\\\\\\<^sup>* T \\<^sup>*\\<frown>\\<^sup>* U \\<^sup>*\\\\\\<^sup>* T\"\n                      have \"(V \\<^sup>*\\\\\\<^sup>* T) \\<^sup>*\\\\\\<^sup>* (U \\<^sup>*\\\\\\<^sup>* T) = ((V \\<^sup>*\\\\\\<^sup>* [t]) \\<^sup>*\\\\\\<^sup>* T') \\<^sup>*\\\\\\<^sup>* ([u \\\\ t] \\<^sup>*\\\\\\<^sup>* T')\"\n                        using Con_TU Con_VT Con_sym Resid_cons(2) Resid_rec(3) T T' U U'\n                        by force\n                      also have \"... = ((V \\<^sup>*\\\\\\<^sup>* [t]) \\<^sup>*\\\\\\<^sup>* [u \\\\ t]) \\<^sup>*\\\\\\<^sup>* (T' \\<^sup>*\\\\\\<^sup>* [u \\\\ t])\"\n                      proof -\n                        have \"length [u \\\\ t] + length T' + length (Resid V [t]) \\<le> n\"\n                          using Con_VT Con_initial_right T U length_Resid len by fastforce\n                        thus ?thesis\n                          by (metis Con_TU Con_VT Con_cons(2) Con_rec(2) T T' U V add.commute\n                              ind list.discI)\n                      qed\n                      also have \"... = ((V \\<^sup>*\\\\\\<^sup>* [u]) \\<^sup>*\\\\\\<^sup>* [t \\\\ u]) \\<^sup>*\\\\\\<^sup>* (T' \\<^sup>*\\\\\\<^sup>* [u \\\\ t])\"\n                      proof -\n                        have \"length [t] + length [u] + length V \\<le> n\"\n                          using T T' U le_Suc_eq len by fastforce\n                        thus ?thesis\n                          using ind [of \"[t]\" \"[u]\" V]\n                          by (metis Con_TU Con_VT Con_initial_left Con_sym Resid_rec(1) T U)\n                      qed\n                      also have \"... = (V \\<^sup>*\\\\\\<^sup>* U) \\<^sup>*\\\\\\<^sup>* (T \\<^sup>*\\\\\\<^sup>* U)\"\n                        using * Con Con_TU Con_rec(2) Resid_cons(2) Resid_rec(2) T T' U U'\n                        by auto\n                      finally show ?thesis by simp\n                    qed\n                  qed\n                qed\n                next\n                assume U': \"U' \\<noteq> []\"\n                show ?thesis\n                proof (cases \"T' = []\")\n                  assume T': \"T' = []\"\n                  show ?thesis\n                  proof (intro conjI impI)\n                    show *: \"V \\<^sup>*\\\\\\<^sup>* T \\<^sup>*\\<frown>\\<^sup>* U \\<^sup>*\\\\\\<^sup>* T \\<longleftrightarrow> V \\<^sup>*\\\\\\<^sup>* U \\<^sup>*\\<frown>\\<^sup>* T \\<^sup>*\\\\\\<^sup>* U\"\n                    proof -\n                      have \"V \\<^sup>*\\\\\\<^sup>* T \\<^sup>*\\<frown>\\<^sup>* U \\<^sup>*\\\\\\<^sup>* T \\<longleftrightarrow> V \\<^sup>*\\\\\\<^sup>* [t] \\<^sup>*\\<frown>\\<^sup>* (u \\\\ t) # (U' \\<^sup>*\\\\\\<^sup>* [t \\\\ u])\"\n                        using T U V T' U' V' Con_TU Con_VT Con_sym Resid_rec(2) by auto\n                      also have \"... \\<longleftrightarrow> V \\<^sup>*\\\\\\<^sup>* [t] \\<^sup>*\\<frown>\\<^sup>* [u \\\\ t] \\<and>\n                                         (V \\<^sup>*\\\\\\<^sup>* [t]) \\<^sup>*\\\\\\<^sup>* [u \\\\ t] \\<^sup>*\\<frown>\\<^sup>* U' \\<^sup>*\\\\\\<^sup>* [t \\\\ u]\"\n                        by (metis Con_TU Con_VT Con_cons(2) Con_initial_right\n                            Con_rec(2) Con_sym T U U')\n                      also have \"... \\<longleftrightarrow> V \\<^sup>*\\\\\\<^sup>* [t] \\<^sup>*\\<frown>\\<^sup>* [u \\\\ t] \\<and>\n                                         (V \\<^sup>*\\\\\\<^sup>* [u]) \\<^sup>*\\\\\\<^sup>* [t \\\\ u] \\<^sup>*\\<frown>\\<^sup>* U' \\<^sup>*\\\\\\<^sup>* [t \\\\ u]\"\n                      proof -\n                        have \"length [u] + length [t] + length V \\<le> n\"\n                          using T U V T' U' V' len not_less_eq_eq order_trans by fastforce\n                        thus ?thesis\n                          using ind [of \"[t]\" \"[u]\" V]\n                          by (metis Con_TU Con_VT Con_initial_right Resid_rec(1) T U\n                                    Con_sym length_Cons)\n                      qed\n                      also have \"... \\<longleftrightarrow> V \\<^sup>*\\\\\\<^sup>* [u] \\<^sup>*\\<frown>\\<^sup>* [t \\\\ u] \\<and>\n                                         (V \\<^sup>*\\\\\\<^sup>* [u]) \\<^sup>*\\\\\\<^sup>* [t \\\\ u] \\<^sup>*\\<frown>\\<^sup>* U' \\<^sup>*\\\\\\<^sup>* [t \\\\ u]\"\n                      proof -\n                        have \"length [t] + length [u] + length V \\<le> n\"\n                          using T U V T' U' V' len antisym_conv not_less_eq_eq by fastforce\n                        thus ?thesis\n                          by (metis (full_types) Con_TU Con_VT Con_initial_right Con_sym\n                              Resid_rec(1) T U ind)\n                      qed\n                      also have \"... \\<longleftrightarrow> (V \\<^sup>*\\\\\\<^sup>* [u]) \\<^sup>*\\\\\\<^sup>* U' \\<^sup>*\\<frown>\\<^sup>* [t \\\\ u] \\<^sup>*\\\\\\<^sup>* U'\"\n                      proof -\n                        have \"length [t \\\\ u] + length U' + length (V \\<^sup>*\\\\\\<^sup>* [u]) \\<le> n\"\n                          by (metis T T' U add.assoc add.right_neutral add_leD1\n                              add_le_cancel_left length_Resid len length_Cons list.size(3)\n                              plus_1_eq_Suc)\n                        thus ?thesis\n                          by (metis (no_types, opaque_lifting) Con_sym Resid.simps(1)\n                              add.commute ind)\n                      qed\n                      also have \"... \\<longleftrightarrow> V \\<^sup>*\\\\\\<^sup>* U \\<^sup>*\\<frown>\\<^sup>* T \\<^sup>*\\\\\\<^sup>* U\"\n                        by (metis Con_TU Resid_cons(2) Resid_rec(3) T T' U U'\n                            Con_cons(2) length_Resid length_0_conv)\n                      finally show ?thesis by blast\n                    qed\n                    show \"V \\<^sup>*\\\\\\<^sup>* T \\<^sup>*\\<frown>\\<^sup>* U \\<^sup>*\\\\\\<^sup>* T \\<Longrightarrow>\n                           (V \\<^sup>*\\\\\\<^sup>* T) \\<^sup>*\\\\\\<^sup>* (U \\<^sup>*\\\\\\<^sup>* T) = (V \\<^sup>*\\\\\\<^sup>* U) \\<^sup>*\\\\\\<^sup>* (T \\<^sup>*\\\\\\<^sup>* U)\"\n                    proof -\n                      assume Con: \"V \\<^sup>*\\\\\\<^sup>* T \\<^sup>*\\<frown>\\<^sup>* U \\<^sup>*\\\\\\<^sup>* T\"\n                      have \"(V \\<^sup>*\\\\\\<^sup>* T) \\<^sup>*\\\\\\<^sup>* (U \\<^sup>*\\\\\\<^sup>* T) =\n                            (V \\<^sup>*\\\\\\<^sup>* [t]) \\<^sup>*\\\\\\<^sup>* ((u \\\\ t) # (U' \\<^sup>*\\\\\\<^sup>* [t \\\\ u]))\"\n                        using Con_TU Con_sym Resid_rec(2) T T' U U' by auto\n                     also have \"... = ((V \\<^sup>*\\\\\\<^sup>* [t]) \\<^sup>*\\\\\\<^sup>* [u \\\\ t]) \\<^sup>*\\\\\\<^sup>* (U' \\<^sup>*\\\\\\<^sup>* [t \\\\ u])\"\n                        by (metis Con Con_TU Con_rec(2) Con_sym T T' U U' calculation\n                            Resid_cons(2))\n                      also have \"... = ((V \\<^sup>*\\\\\\<^sup>* [u]) \\<^sup>*\\\\\\<^sup>* [t \\\\ u]) \\<^sup>*\\\\\\<^sup>* (U' \\<^sup>*\\\\\\<^sup>* [t \\\\ u])\"\n                      proof -\n                        have \"length [t] + length [u] + length V \\<le> n\"\n                          using T U U' le_Suc_eq len by fastforce\n                        thus ?thesis\n                          using T U Con_TU Con_VT Con_sym ind [of \"[t]\" \"[u]\" V]\n                          by (metis (no_types, opaque_lifting) Con_initial_right Resid.simps(3))\n                      qed\n                      also have \"... = ((V \\<^sup>*\\\\\\<^sup>* [u]) \\<^sup>*\\\\\\<^sup>* U') \\<^sup>*\\\\\\<^sup>* ([t \\\\ u] \\<^sup>*\\\\\\<^sup>* U')\"\n                      proof -\n                        have \"length [t \\\\ u] + length U' + length (V \\<^sup>*\\\\\\<^sup>* [u]) \\<le> n\"\n                          by (metis (no_types, opaque_lifting) T T' U add.left_commute\n                              add.right_neutral add_leD2 add_le_cancel_left len length_Cons\n                              length_Resid list.size(3) plus_1_eq_Suc)\n                        thus ?thesis\n                          by (metis Con Con_TU Con_rec(3) T T' U U' calculation\n                              ind length_0_conv length_Resid)\n                      qed\n                      also have \"... = (V \\<^sup>*\\\\\\<^sup>* U) \\<^sup>*\\\\\\<^sup>* (T \\<^sup>*\\\\\\<^sup>* U)\"\n                        by (metis \"*\" Con Con_TU Resid_rec(3) T T' U U' Resid_cons(2)\n                            length_Resid length_0_conv)\n                      finally show ?thesis by blast\n                    qed\n                  qed\n                  next\n                  assume T': \"T' \\<noteq> []\"\n                  show ?thesis\n                  proof (intro conjI impI)\n                    have 1: \"U \\<^sup>*\\<frown>\\<^sup>* [t]\"\n                      using T Con_TU\n                      by (metis Con_cons(2) Con_sym Resid.simps(2))\n                    have 2: \"V \\<^sup>*\\<frown>\\<^sup>* [t]\"\n                      using V Con_VT Con_initial_right T by blast\n                    have 3: \"length T' + length (U \\<^sup>*\\\\\\<^sup>* [t]) + length (V \\<^sup>*\\\\\\<^sup>* [t]) \\<le> n\"\n                      using \"1\" \"2\" T len length_Resid by force\n                    have 4: \"length [t] + length U + length V \\<le> n\"\n                      using T T' len antisym_conv not_less_eq_eq by fastforce\n                    show *: \"V \\<^sup>*\\\\\\<^sup>* T \\<^sup>*\\<frown>\\<^sup>* U \\<^sup>*\\\\\\<^sup>* T \\<longleftrightarrow> V \\<^sup>*\\\\\\<^sup>* U \\<^sup>*\\<frown>\\<^sup>* T \\<^sup>*\\\\\\<^sup>* U\"\n                    proof -\n                      have \"V \\<^sup>*\\\\\\<^sup>* T \\<^sup>*\\<frown>\\<^sup>* U \\<^sup>*\\\\\\<^sup>* T \\<longleftrightarrow> (V \\<^sup>*\\\\\\<^sup>* [t]) \\<^sup>*\\\\\\<^sup>* T' \\<^sup>*\\<frown>\\<^sup>* (U \\<^sup>*\\\\\\<^sup>* [t]) \\<^sup>*\\\\\\<^sup>* T'\"\n                        using Con_TU Con_VT Con_sym Resid_cons(2) T T' by force\n                      also have \"... \\<longleftrightarrow> (V \\<^sup>*\\\\\\<^sup>* [t]) \\<^sup>*\\\\\\<^sup>* (U \\<^sup>*\\\\\\<^sup>* [t]) \\<^sup>*\\<frown>\\<^sup>* T' \\<^sup>*\\\\\\<^sup>* (U \\<^sup>*\\\\\\<^sup>* [t])\"\n                        by (metis 3 Con_TU Con_VT Con_cons(1) Con_cons(2) T T' U V ind\n                            list.discI)\n                      also have \"... \\<longleftrightarrow> (V \\<^sup>*\\\\\\<^sup>* U) \\<^sup>*\\\\\\<^sup>* ([t] \\<^sup>*\\\\\\<^sup>* U) \\<^sup>*\\<frown>\\<^sup>* T' \\<^sup>*\\\\\\<^sup>* (U \\<^sup>*\\\\\\<^sup>* [t])\"\n                        by (metis 1 2 4 Con_sym ind)\n                      also have \"... \\<longleftrightarrow> V \\<^sup>*\\\\\\<^sup>* U \\<^sup>*\\<frown>\\<^sup>* hd ([t] \\<^sup>*\\\\\\<^sup>* U) # T' \\<^sup>*\\\\\\<^sup>* (U \\<^sup>*\\\\\\<^sup>* [t])\"\n                        by (metis 1 Con_TU Con_cons(1) Con_cons(2) Resid.simps(1)\n                            Resid1x_as_Resid T T' list.sel(1))\n                      also have \"... \\<longleftrightarrow> V \\<^sup>*\\\\\\<^sup>* U \\<^sup>*\\<frown>\\<^sup>* T \\<^sup>*\\\\\\<^sup>* U\"\n                        using 1 Resid_cons' [of T' t U] Con_TU T T' Resid1x_as_Resid\n                              Con_sym\n                        by force\n                      finally show ?thesis by simp\n                    qed\n                    show \"(V \\<^sup>*\\\\\\<^sup>* T) \\<^sup>*\\\\\\<^sup>* (U \\<^sup>*\\\\\\<^sup>* T) = (V \\<^sup>*\\\\\\<^sup>* U) \\<^sup>*\\\\\\<^sup>* (T \\<^sup>*\\\\\\<^sup>* U)\"\n                    proof -\n                      have \"(V \\<^sup>*\\\\\\<^sup>* T) \\<^sup>*\\\\\\<^sup>* (U \\<^sup>*\\\\\\<^sup>* T) =\n                            ((V \\<^sup>*\\\\\\<^sup>* [t]) \\<^sup>*\\\\\\<^sup>* T') \\<^sup>*\\\\\\<^sup>* ((U \\<^sup>*\\\\\\<^sup>* [t]) \\<^sup>*\\\\\\<^sup>* T')\"\n                        using Con_TU Con_VT Con_sym Resid_cons(2) T T' by force\n                      also have \"... = ((V \\<^sup>*\\\\\\<^sup>* [t]) \\<^sup>*\\\\\\<^sup>* (U \\<^sup>*\\\\\\<^sup>* [t])) \\<^sup>*\\\\\\<^sup>* (T' \\<^sup>*\\\\\\<^sup>* (U \\<^sup>*\\\\\\<^sup>* [t]))\"\n                        by (metis (no_types, lifting) \"3\" Con_TU Con_VT T T' U V Con_cons(1)\n                            Con_cons(2) ind list.simps(3))\n                      also have \"... = ((V \\<^sup>*\\\\\\<^sup>* U) \\<^sup>*\\\\\\<^sup>* ([t] \\<^sup>*\\\\\\<^sup>* U)) \\<^sup>*\\\\\\<^sup>* (T' \\<^sup>*\\\\\\<^sup>* (U \\<^sup>*\\\\\\<^sup>* [t]))\"\n                        by (metis 1 2 4 Con_sym ind)\n                      also have \"... = (V \\<^sup>*\\\\\\<^sup>* U) \\<^sup>*\\\\\\<^sup>* ((t # T') \\<^sup>*\\\\\\<^sup>* U)\"\n                        by (metis \"*\" Con_TU Con_cons(1) Resid1x_as_Resid\n                            Resid_cons' T T' U calculation Resid_cons(2) list.distinct(1))\n                      also have \"... = (V \\<^sup>*\\\\\\<^sup>* U) \\<^sup>*\\\\\\<^sup>* (T \\<^sup>*\\\\\\<^sup>* U)\"\n                        using T by fastforce\n                      finally show ?thesis by simp\n                    qed\n                  qed\n                qed\n              qed\n            qed\n          qed\n        qed\n      qed\n    qed\n\n    lemma Cube:\n    shows \"T \\<^sup>*\\\\\\<^sup>* U \\<^sup>*\\<frown>\\<^sup>* V \\<^sup>*\\\\\\<^sup>* U \\<longleftrightarrow> T \\<^sup>*\\\\\\<^sup>* V \\<^sup>*\\<frown>\\<^sup>* U \\<^sup>*\\\\\\<^sup>* V\"\n    and \"T \\<^sup>*\\\\\\<^sup>* U \\<^sup>*\\<frown>\\<^sup>* V \\<^sup>*\\\\\\<^sup>* U \\<Longrightarrow> (T \\<^sup>*\\\\\\<^sup>* U) \\<^sup>*\\\\\\<^sup>* (V \\<^sup>*\\\\\\<^sup>* U) = (T \\<^sup>*\\\\\\<^sup>* V) \\<^sup>*\\\\\\<^sup>* (U \\<^sup>*\\\\\\<^sup>* V)\"\n    proof -\n      show \"T \\<^sup>*\\\\\\<^sup>* U \\<^sup>*\\<frown>\\<^sup>* V \\<^sup>*\\\\\\<^sup>* U \\<longleftrightarrow> T \\<^sup>*\\\\\\<^sup>* V \\<^sup>*\\<frown>\\<^sup>* U \\<^sup>*\\\\\\<^sup>* V\"\n        using Cube_ind by (metis Con_sym Resid.simps(1) le_add2)\n      show \"T \\<^sup>*\\\\\\<^sup>* U \\<^sup>*\\<frown>\\<^sup>* V \\<^sup>*\\\\\\<^sup>* U \\<Longrightarrow> (T \\<^sup>*\\\\\\<^sup>* U) \\<^sup>*\\\\\\<^sup>* (V \\<^sup>*\\\\\\<^sup>* U) = (T \\<^sup>*\\\\\\<^sup>* V) \\<^sup>*\\\\\\<^sup>* (U \\<^sup>*\\\\\\<^sup>* V)\"\n        using Cube_ind by (metis Con_sym Resid.simps(1) order_refl)\n    qed\n\n    lemma Con_implies_Arr:\n    assumes \"T \\<^sup>*\\<frown>\\<^sup>* U\"\n    shows \"Arr T\" and \"Arr U\"\n      using assms Con_sym\n      by (metis Con_imp_Arr_Resid Arr_iff_Con_self Cube(1) Resid.simps(1))+\n\n    sublocale partial_magma Resid\n      by (unfold_locales, metis Resid.simps(1) Con_sym)\n\n    lemma is_partial_magma:\n    shows \"partial_magma Resid\"\n      ..\n\n    lemma null_char:\n    shows \"null = []\"\n      by (metis null_is_zero(2) Resid.simps(1))\n\n    sublocale residuation Resid\n      using null_char Con_sym Arr_iff_Con_self Con_imp_Arr_Resid Cube null_is_zero(2)\n      by unfold_locales auto\n\n    lemma is_residuation:\n    shows \"residuation Resid\"\n      ..\n\n    lemma arr_char:\n    shows \"arr T \\<longleftrightarrow> Arr T\"\n      using null_char Arr_iff_Con_self by fastforce\n\n    lemma arrI\\<^sub>P [intro]:\n    assumes \"Arr T\"\n    shows \"arr T\"\n      using assms arr_char by auto\n\n    lemma ide_char:\n    shows \"ide T \\<longleftrightarrow> Ide T\"\n      by (metis Con_Arr_self Ide_implies_Arr Resid_Arr_Ide_ind Resid_Arr_self arr_char ide_def\n          arr_def)\n\n    lemma con_char:\n    shows \"con T U \\<longleftrightarrow> Con T U\"\n      using null_char by auto\n\n    lemma conI\\<^sub>P [intro]:\n    assumes \"Con T U\"\n    shows \"con T U\"\n      using assms con_char by auto\n\n    sublocale rts Resid\n    proof\n      show \"\\<And>A T. \\<lbrakk>ide A; con T A\\<rbrakk> \\<Longrightarrow> T \\<^sup>*\\\\\\<^sup>* A = T\"\n        using Resid_Arr_Ide_ind ide_char null_char by auto\n      show \"\\<And>T. arr T \\<Longrightarrow> ide (trg T)\"\n        by (metis arr_char Resid_Arr_self ide_char resid_arr_self)\n      show \"\\<And>A T. \\<lbrakk>ide A; con A T\\<rbrakk> \\<Longrightarrow> ide (A \\<^sup>*\\\\\\<^sup>* T)\"\n        by (simp add: Resid_Ide_Arr_ind con_char ide_char)\n      show \"\\<And>T U. con T U \\<Longrightarrow> \\<exists>A. ide A \\<and> con A T \\<and> con A U\"\n      proof -\n        fix T U\n        assume TU: \"con T U\"\n        have 1: \"Srcs T = Srcs U\"\n          using TU Con_imp_eq_Srcs con_char by force\n        obtain a where a: \"a \\<in> Srcs T \\<inter> Srcs U\"\n          using 1\n          by (metis Int_absorb Int_emptyI TU arr_char Arr_has_Src con_implies_arr(1))\n        show \"\\<exists>A. ide A \\<and> con A T \\<and> con A U\"\n          using a 1\n          by (metis (full_types) Ball_Collect Con_single_ide_ind Ide.simps(2) Int_absorb TU\n              Srcs_are_ide arr_char con_char con_implies_arr(1-2) ide_char)\n      qed\n      show \"\\<And>T U V. \\<lbrakk>ide (Resid T U); con U V\\<rbrakk> \\<Longrightarrow> con (T \\<^sup>*\\\\\\<^sup>* U) (V \\<^sup>*\\\\\\<^sup>* U)\"\n        using null_char ide_char\n        by (metis Con_imp_Arr_Resid Con_Ide_iff Srcs_Resid con_char con_sym arr_resid_iff_con\n            ide_implies_arr)\n    qed\n\n    theorem is_rts:\n    shows \"rts Resid\"\n      ..\n\n    notation cong  (infix \"\\<^sup>*\\<sim>\\<^sup>*\" 50)\n    notation prfx  (infix \"\\<^sup>*\\<lesssim>\\<^sup>*\" 50)\n\n    lemma sources_char\\<^sub>P:\n    shows \"sources T = {A. Ide A \\<and> Arr T \\<and> Srcs A = Srcs T}\"\n      using Con_Ide_iff Con_sym con_char ide_char sources_def by fastforce\n\n    lemma sources_cons:\n    shows \"Arr (t # T) \\<Longrightarrow> sources (t # T) = sources [t]\"\n      apply (induct T)\n       apply simp\n      using sources_char\\<^sub>P by auto\n\n    lemma targets_char\\<^sub>P:\n    shows \"targets T = {B. Ide B \\<and> Arr T \\<and> Srcs B = Trgs T}\"\n      unfolding targets_def\n      by (metis (no_types, lifting) trg_def Arr.simps(1) Ide_implies_Arr Resid_Arr_self\n          arr_char Con_Ide_iff Srcs_Resid con_char ide_char con_implies_arr(1))\n\n    lemma seq_char':\n    shows \"seq T U \\<longleftrightarrow> Arr T \\<and> Arr U \\<and> Trgs T \\<inter> Srcs U \\<noteq> {}\"\n    proof\n      show \"seq T U \\<Longrightarrow> Arr T \\<and> Arr U \\<and> Trgs T \\<inter> Srcs U \\<noteq> {}\"\n        unfolding seq_def\n        using Arr_has_Trg arr_char Con_Arr_self sources_char\\<^sub>P trg_def trg_in_targets\n        by fastforce\n      assume 1: \"Arr T \\<and> Arr U \\<and> Trgs T \\<inter> Srcs U \\<noteq> {}\"\n      have \"targets T = sources U\"\n      proof -\n        obtain a where a: \"R.ide a \\<and> a \\<in> Trgs T \\<and> a \\<in> Srcs U\"\n          using 1 Trgs_are_ide by blast\n        have \"Trgs [a] = Trgs T\"\n          using a 1\n          by (metis Con_single_ide_ind Con_sym Resid_Arr_Src Srcs_Resid Trgs_eqI)\n        moreover have \"Srcs [a] = Srcs U\"\n          using a 1 Con_single_ide_ind Con_imp_eq_Srcs by blast\n        moreover have \"Trgs [a] = Srcs [a]\"\n          using a\n          by (metis R.residuation_axioms R.sources_resid Srcs.simps(2) Trgs.simps(2)\n              residuation.ideE)\n        ultimately show ?thesis\n          using 1 sources_char\\<^sub>P targets_char\\<^sub>P by auto\n      qed\n      thus \"seq T U\"\n        using 1 by blast\n    qed\n      \n    lemma seq_char:\n    shows \"seq T U \\<longleftrightarrow> Arr T \\<and> Arr U \\<and> Trgs T = Srcs U\"\n      by (metis Int_absorb Srcs_Resid Arr_has_Src Arr_iff_Con_self Srcs_eqI seq_char')\n\n    lemma seqI\\<^sub>P [intro]:\n    assumes \"Arr T\" and \"Arr U\" and \"Trgs T \\<inter> Srcs U \\<noteq> {}\"\n    shows \"seq T U\"\n      using assms seq_char' by auto\n\n    lemma Ide_imp_sources_eq_targets:\n    assumes \"Ide T\"\n    shows \"sources T = targets T\"\n      using assms\n      by (metis Resid_Arr_Ide_ind arr_iff_has_source arr_iff_has_target con_char\n          arr_def sources_resid)\n\n    subsection \"Inclusion Map\"\n\n    text \\<open>\n      Inclusion of an RTS to the RTS of its paths.\n    \\<close>\n\n    abbreviation incl\n    where \"incl \\<equiv> \\<lambda>t. if R.arr t then [t] else null\"\n\n    lemma incl_is_simulation:\n    shows \"simulation resid Resid incl\"\n      using R.con_implies_arr(1-2) con_char R.arr_resid_iff_con null_char\n      by unfold_locales auto\n\n    lemma incl_is_injective:\n    shows \"inj_on incl (Collect R.arr)\"\n      by (intro inj_onI) simp\n\n    lemma reflects_con:\n    assumes \"incl t \\<^sup>*\\<frown>\\<^sup>* incl u\"\n    shows \"t \\<frown> u\"\n      using assms\n      by (metis (full_types) Arr.simps(1) Con_implies_Arr(1-2) Con_rec(1) null_char)\n\n  end\n\n  subsection \"Composites of Paths\"\n\n  text \\<open>\n    The RTS of paths has composites, given by the append operation on lists.\n  \\<close>\n\n  context paths_in_rts\n  begin\n\n    lemma Srcs_append [simp]:\n    assumes \"T \\<noteq> []\"\n    shows \"Srcs (T @ U) = Srcs T\"\n      by (metis Nil_is_append_conv Srcs.simps(2) Srcs.simps(3) assms hd_append list.exhaust_sel)\n\n    lemma Trgs_append [simp]:\n    shows \"U \\<noteq> [] \\<Longrightarrow> Trgs (T @ U) = Trgs U\"\n    proof (induct T)\n      show \"U \\<noteq> [] \\<Longrightarrow> Trgs ([] @ U) = Trgs U\"\n        by auto\n      show \"\\<And>t T. \\<lbrakk>U \\<noteq> [] \\<Longrightarrow> Trgs (T @ U) = Trgs U; U \\<noteq> []\\<rbrakk>\n                      \\<Longrightarrow> Trgs ((t # T) @ U) = Trgs U\"\n        by (metis Nil_is_append_conv Trgs.simps(3) append_Cons list.exhaust)\n    qed\n\n    lemma seq_implies_Trgs_eq_Srcs:\n    shows \"\\<lbrakk>Arr T; Arr U; Trgs T \\<subseteq> Srcs U\\<rbrakk> \\<Longrightarrow> Trgs T = Srcs U\"\n      by (metis inf.orderE Arr_has_Trg seqI\\<^sub>P seq_char)\n\n    lemma Arr_append_iff\\<^sub>P:\n    shows \"\\<lbrakk>T \\<noteq> []; U \\<noteq> []\\<rbrakk> \\<Longrightarrow> Arr (T @ U) \\<longleftrightarrow> Arr T \\<and> Arr U \\<and> Trgs T \\<subseteq> Srcs U\"\n    proof (induct T arbitrary: U)\n      show \"\\<And>U. \\<lbrakk>[] \\<noteq> []; U \\<noteq> []\\<rbrakk> \\<Longrightarrow> Arr ([] @ U) = (Arr [] \\<and> Arr U \\<and> Trgs [] \\<subseteq> Srcs U)\"\n        by simp\n      fix t T and U :: \"'a list\"\n      assume ind: \"\\<And>U. \\<lbrakk>T \\<noteq> []; U \\<noteq> []\\<rbrakk>\n                          \\<Longrightarrow> Arr (T @ U) = (Arr T \\<and> Arr U \\<and> Trgs T \\<subseteq> Srcs U)\"\n      assume U: \"U \\<noteq> []\"\n      show \"Arr ((t # T) @ U) \\<longleftrightarrow> Arr (t # T) \\<and> Arr U \\<and> Trgs (t # T) \\<subseteq> Srcs U\"\n      proof (cases \"T = []\")\n        show \"T = [] \\<Longrightarrow> ?thesis\"\n          using Arr.elims(1) U by auto\n        assume T: \"T \\<noteq> []\"\n        have \"Arr ((t # T) @ U) \\<longleftrightarrow> Arr (t # (T @ U))\"\n          by simp\n        also have \"... \\<longleftrightarrow> R.arr t \\<and> Arr (T @ U) \\<and> R.targets t \\<subseteq> Srcs (T @ U)\"\n          using T U\n          by (metis Arr.simps(3) Nil_is_append_conv neq_Nil_conv)\n        also have \"... \\<longleftrightarrow> R.arr t \\<and> Arr T \\<and> Arr U \\<and> Trgs T \\<subseteq> Srcs U \\<and> R.targets t \\<subseteq> Srcs T\"\n          using T U ind by auto\n        also have \"... \\<longleftrightarrow> Arr (t # T) \\<and> Arr U \\<and> Trgs (t # T) \\<subseteq> Srcs U\"\n          using T U\n          by (metis Arr.simps(3) Trgs.simps(3) neq_Nil_conv)\n        finally show ?thesis by auto\n      qed\n    qed\n\n    lemma Arr_consI\\<^sub>P [intro, simp]:\n    assumes \"R.arr t\" and \"Arr U\" and \"R.targets t \\<subseteq> Srcs U\"\n    shows \"Arr (t # U)\"\n      using assms Arr.elims(3) by blast\n\n    lemma Arr_appendI\\<^sub>P [intro, simp]:\n    assumes \"Arr T\" and \"Arr U\" and \"Trgs T \\<subseteq> Srcs U\"\n    shows \"Arr (T @ U)\"\n      using assms\n      by (metis Arr.simps(1) Arr_append_iff\\<^sub>P)\n\n    lemma Arr_appendE\\<^sub>P [elim]:\n    assumes \"Arr (T @ U)\" and \"T \\<noteq> []\" and \"U \\<noteq> []\"\n    and \"\\<lbrakk>Arr T; Arr U; Trgs T = Srcs U\\<rbrakk> \\<Longrightarrow> thesis\"\n    shows thesis\n      using assms Arr_append_iff\\<^sub>P seq_implies_Trgs_eq_Srcs by force\n\n    lemma Ide_append_iff\\<^sub>P:\n    shows \"\\<lbrakk>T \\<noteq> []; U \\<noteq> []\\<rbrakk> \\<Longrightarrow> Ide (T @ U) \\<longleftrightarrow> Ide T \\<and> Ide U \\<and> Trgs T \\<subseteq> Srcs U\"\n      using Ide_char by auto\n\n    lemma Ide_appendI\\<^sub>P [intro, simp]:\n    assumes \"Ide T\" and \"Ide U\" and \"Trgs T \\<subseteq> Srcs U\"\n    shows \"Ide (T @ U)\"\n      using assms\n      by (metis Ide.simps(1) Ide_append_iff\\<^sub>P)\n\n    lemma Resid_append_ind:\n    shows \"\\<lbrakk>T \\<noteq> []; U \\<noteq> []; V \\<noteq> []\\<rbrakk> \\<Longrightarrow>\n             (V @ T \\<^sup>*\\<frown>\\<^sup>* U \\<longleftrightarrow> V \\<^sup>*\\<frown>\\<^sup>* U \\<and> T \\<^sup>*\\<frown>\\<^sup>* U \\<^sup>*\\\\\\<^sup>* V) \\<and>\n             (T \\<^sup>*\\<frown>\\<^sup>* V @ U \\<longleftrightarrow> T \\<^sup>*\\<frown>\\<^sup>* V \\<and> T \\<^sup>*\\\\\\<^sup>* V \\<^sup>*\\<frown>\\<^sup>* U) \\<and>\n             (V @ T \\<^sup>*\\<frown>\\<^sup>* U \\<longrightarrow> (V @ T) \\<^sup>*\\\\\\<^sup>* U = V \\<^sup>*\\\\\\<^sup>* U @ T \\<^sup>*\\\\\\<^sup>* (U \\<^sup>*\\\\\\<^sup>* V)) \\<and>\n             (T \\<^sup>*\\<frown>\\<^sup>* V @ U \\<longrightarrow> T \\<^sup>*\\\\\\<^sup>* (V @ U) = (T \\<^sup>*\\\\\\<^sup>* V) \\<^sup>*\\\\\\<^sup>* U)\"\n    proof (induct V arbitrary: T U)\n      show \"\\<And>T U. \\<lbrakk>T \\<noteq> []; U \\<noteq> []; [] \\<noteq> []\\<rbrakk> \\<Longrightarrow>\n                   ([] @ T \\<^sup>*\\<frown>\\<^sup>* U \\<longleftrightarrow> [] \\<^sup>*\\<frown>\\<^sup>* U \\<and> T \\<^sup>*\\<frown>\\<^sup>* U \\<^sup>*\\\\\\<^sup>* []) \\<and>\n                   (T \\<^sup>*\\<frown>\\<^sup>* [] @ U \\<longleftrightarrow> T \\<^sup>*\\<frown>\\<^sup>* [] \\<and> T \\<^sup>*\\\\\\<^sup>* [] \\<^sup>*\\<frown>\\<^sup>* U) \\<and>\n                   ([] @ T \\<^sup>*\\<frown>\\<^sup>* U \\<longrightarrow> ([] @ T) \\<^sup>*\\\\\\<^sup>* U = [] \\<^sup>*\\\\\\<^sup>* U @ T \\<^sup>*\\\\\\<^sup>* (U \\<^sup>*\\\\\\<^sup>* [])) \\<and>\n                   (T \\<^sup>*\\<frown>\\<^sup>* [] @ U \\<longrightarrow> T \\<^sup>*\\\\\\<^sup>* ([] @ U) = (T \\<^sup>*\\\\\\<^sup>* []) \\<^sup>*\\\\\\<^sup>* U)\"\n        by simp\n      fix v :: 'a and T U V :: \"'a list\"\n      assume ind: \"\\<And>T U. \\<lbrakk>T \\<noteq> []; U \\<noteq> []; V \\<noteq> []\\<rbrakk> \\<Longrightarrow>\n                          (V @ T \\<^sup>*\\<frown>\\<^sup>* U \\<longleftrightarrow> V \\<^sup>*\\<frown>\\<^sup>* U \\<and> T \\<^sup>*\\<frown>\\<^sup>* U \\<^sup>*\\\\\\<^sup>* V) \\<and>\n                          (T \\<^sup>*\\<frown>\\<^sup>* V @ U \\<longleftrightarrow> T \\<^sup>*\\<frown>\\<^sup>* V \\<and> T \\<^sup>*\\\\\\<^sup>* V \\<^sup>*\\<frown>\\<^sup>* U) \\<and>\n                          (V @ T \\<^sup>*\\<frown>\\<^sup>* U \\<longrightarrow> (V @ T) \\<^sup>*\\\\\\<^sup>* U = V \\<^sup>*\\\\\\<^sup>* U @ T \\<^sup>*\\\\\\<^sup>* (U \\<^sup>*\\\\\\<^sup>* V)) \\<and>\n                          (T \\<^sup>*\\<frown>\\<^sup>* V @ U \\<longrightarrow> T \\<^sup>*\\\\\\<^sup>* (V @ U) = (T \\<^sup>*\\\\\\<^sup>* V) \\<^sup>*\\\\\\<^sup>* U)\"\n      assume T: \"T \\<noteq> []\" and U: \"U \\<noteq> []\"\n      show \"((v # V) @ T \\<^sup>*\\<frown>\\<^sup>* U \\<longleftrightarrow> (v # V) \\<^sup>*\\<frown>\\<^sup>* U \\<and> T \\<^sup>*\\<frown>\\<^sup>* U \\<^sup>*\\\\\\<^sup>* (v # V)) \\<and>\n            (T \\<^sup>*\\<frown>\\<^sup>* (v # V) @ U \\<longleftrightarrow> T \\<^sup>*\\<frown>\\<^sup>* (v # V) \\<and> T \\<^sup>*\\\\\\<^sup>* (v # V) \\<^sup>*\\<frown>\\<^sup>* U) \\<and>\n            ((v # V) @ T \\<^sup>*\\<frown>\\<^sup>* U \\<longrightarrow>\n              ((v # V) @ T) \\<^sup>*\\\\\\<^sup>* U = (v # V) \\<^sup>*\\\\\\<^sup>* U @ T \\<^sup>*\\\\\\<^sup>* (U \\<^sup>*\\\\\\<^sup>* (v # V))) \\<and>\n            (T \\<^sup>*\\<frown>\\<^sup>* (v # V) @ U \\<longrightarrow> T \\<^sup>*\\\\\\<^sup>* ((v # V) @ U) = (T \\<^sup>*\\\\\\<^sup>* (v # V)) \\<^sup>*\\\\\\<^sup>* U)\"\n      proof (intro conjI iffI impI)\n        show 1: \"(v # V) @ T \\<^sup>*\\<frown>\\<^sup>* U \\<Longrightarrow>\n                   ((v # V) @ T) \\<^sup>*\\\\\\<^sup>* U = (v # V) \\<^sup>*\\\\\\<^sup>* U @ T \\<^sup>*\\\\\\<^sup>* (U \\<^sup>*\\\\\\<^sup>* (v # V))\"\n        proof (cases \"V = []\")\n          show \"V = [] \\<Longrightarrow> (v # V) @ T \\<^sup>*\\<frown>\\<^sup>* U \\<Longrightarrow> ?thesis\"\n            using T U Resid_cons(1) U by auto\n          assume V: \"V \\<noteq> []\"\n          assume Con: \"(v # V) @ T \\<^sup>*\\<frown>\\<^sup>* U\"\n          have \"((v # V) @ T) \\<^sup>*\\\\\\<^sup>* U = (v # (V @ T)) \\<^sup>*\\\\\\<^sup>* U\"\n            by simp\n          also have \"... = [v] \\<^sup>*\\\\\\<^sup>* U @ (V @ T) \\<^sup>*\\\\\\<^sup>* (U \\<^sup>*\\\\\\<^sup>* [v])\"\n            using T U Con Resid_cons by simp\n          also have \"... = [v] \\<^sup>*\\\\\\<^sup>* U @ V \\<^sup>*\\\\\\<^sup>* (U \\<^sup>*\\\\\\<^sup>* [v]) @ T \\<^sup>*\\\\\\<^sup>* ((U \\<^sup>*\\\\\\<^sup>* [v]) \\<^sup>*\\\\\\<^sup>* V)\"\n            using T U V Con ind Resid_cons\n            by (metis Con_sym Cons_eq_appendI append_is_Nil_conv Con_cons(1))\n          also have \"... = (v # V) \\<^sup>*\\\\\\<^sup>* U @ T \\<^sup>*\\\\\\<^sup>* (U \\<^sup>*\\\\\\<^sup>* (v # V))\"\n            by (metis Con Con_cons(2) Cons_eq_appendI Resid_cons(1) Resid_cons(2) T U V\n                append.assoc append_is_Nil_conv Con_sym ind)\n          finally show ?thesis by simp\n        qed\n        show 2: \"T \\<^sup>*\\<frown>\\<^sup>* (v # V) @ U \\<Longrightarrow> T \\<^sup>*\\\\\\<^sup>* ((v # V) @ U) = (T \\<^sup>*\\\\\\<^sup>* (v # V)) \\<^sup>*\\\\\\<^sup>* U\"\n        proof (cases \"V = []\")\n          show \"V = [] \\<Longrightarrow> T \\<^sup>*\\<frown>\\<^sup>* (v # V) @ U \\<Longrightarrow> ?thesis\"\n            using Resid_cons(2) T U by auto\n          assume V: \"V \\<noteq> []\"\n          assume Con: \"T \\<^sup>*\\<frown>\\<^sup>* (v # V) @ U\"\n          have \"T \\<^sup>*\\\\\\<^sup>* ((v # V) @ U) = T \\<^sup>*\\\\\\<^sup>* (v # (V @ U))\"\n            by simp\n          also have 1: \"... = (T \\<^sup>*\\\\\\<^sup>* [v]) \\<^sup>*\\\\\\<^sup>* (V @ U)\"\n            using V Con Resid_cons(2) T by force\n          also have \"... = ((T \\<^sup>*\\\\\\<^sup>* [v]) \\<^sup>*\\\\\\<^sup>* V) \\<^sup>*\\\\\\<^sup>* U\"\n            using T U V 1 Con ind\n            by (metis Con_initial_right Cons_eq_appendI)\n          also have \"... = (T \\<^sup>*\\\\\\<^sup>* (v # V)) \\<^sup>*\\\\\\<^sup>* U\"\n            using T V Con\n            by (metis Con_cons(2) Con_initial_right Cons_eq_appendI Resid_cons(2))\n          finally show ?thesis by blast\n        qed\n        show \"(v # V) @ T \\<^sup>*\\<frown>\\<^sup>* U \\<Longrightarrow> v # V \\<^sup>*\\<frown>\\<^sup>* U\"\n          by (metis 1 Con_sym Resid.simps(1) append_Nil)\n        show \"(v # V) @ T \\<^sup>*\\<frown>\\<^sup>* U \\<Longrightarrow> T \\<^sup>*\\<frown>\\<^sup>* U \\<^sup>*\\\\\\<^sup>* (v # V)\"\n          using T U Con_sym\n          by (metis 1 Con_initial_right Resid_cons(1-2) append.simps(2) ind self_append_conv)\n        show \"T \\<^sup>*\\<frown>\\<^sup>* (v # V) @ U \\<Longrightarrow> T \\<^sup>*\\<frown>\\<^sup>* v # V\"\n          using 2 by fastforce\n        show \"T \\<^sup>*\\<frown>\\<^sup>* (v # V) @ U \\<Longrightarrow> T \\<^sup>*\\\\\\<^sup>* (v # V) \\<^sup>*\\<frown>\\<^sup>* U\"\n          using 2 by fastforce\n        show \"T \\<^sup>*\\<frown>\\<^sup>* v # V \\<and> T \\<^sup>*\\\\\\<^sup>* (v # V) \\<^sup>*\\<frown>\\<^sup>* U \\<Longrightarrow> T \\<^sup>*\\<frown>\\<^sup>* (v # V) @ U\"\n        proof -\n          assume Con: \"T \\<^sup>*\\<frown>\\<^sup>* v # V \\<and> T \\<^sup>*\\\\\\<^sup>* (v # V) \\<^sup>*\\<frown>\\<^sup>* U\"\n          have \"T \\<^sup>*\\<frown>\\<^sup>* (v # V) @ U \\<longleftrightarrow> T \\<^sup>*\\<frown>\\<^sup>* v # (V @ U)\"\n            by simp\n          also have \"... \\<longleftrightarrow> T \\<^sup>*\\<frown>\\<^sup>* [v] \\<and> T \\<^sup>*\\\\\\<^sup>* [v] \\<^sup>*\\<frown>\\<^sup>* V @ U\"\n            using T U Con_cons(2) by simp\n          also have \"... \\<longleftrightarrow> T \\<^sup>*\\\\\\<^sup>* [v] \\<^sup>*\\<frown>\\<^sup>* V @ U\"\n            by fastforce\n          also have \"... \\<longleftrightarrow> True\"\n            using Con ind\n            by (metis Con_cons(2) Resid_cons(2) T U self_append_conv2)\n          finally show ?thesis by blast\n        qed\n        show \"v # V \\<^sup>*\\<frown>\\<^sup>* U \\<and> T \\<^sup>*\\<frown>\\<^sup>* U \\<^sup>*\\\\\\<^sup>* (v # V) \\<Longrightarrow> (v # V) @ T \\<^sup>*\\<frown>\\<^sup>* U\"\n        proof -\n          assume Con: \"v # V \\<^sup>*\\<frown>\\<^sup>* U \\<and> T \\<^sup>*\\<frown>\\<^sup>* U \\<^sup>*\\\\\\<^sup>* (v # V)\"\n          have \"(v # V) @ T \\<^sup>*\\<frown>\\<^sup>* U \\<longleftrightarrow>v # (V @ T) \\<^sup>*\\<frown>\\<^sup>* U\"\n            by simp\n          also have \"... \\<longleftrightarrow> [v] \\<^sup>*\\<frown>\\<^sup>* U \\<and> V @ T \\<^sup>*\\<frown>\\<^sup>* U \\<^sup>*\\\\\\<^sup>* [v]\"\n            using T U Con_cons(1) by simp\n          also have \"... \\<longleftrightarrow> V @ T \\<^sup>*\\<frown>\\<^sup>* U \\<^sup>*\\\\\\<^sup>* [v]\"\n            by (metis Con Con_cons(1) U)\n          also have \"... \\<longleftrightarrow> True\"\n            using Con ind\n            by (metis Con_cons(1) Con_sym Resid_cons(2) T U append_self_conv2)\n          finally show ?thesis by blast\n        qed\n      qed\n    qed\n\n    lemma Con_append:\n    assumes \"T \\<noteq> []\" and \"U \\<noteq> []\" and \"V \\<noteq> []\"\n    shows \"T @ U \\<^sup>*\\<frown>\\<^sup>* V \\<longleftrightarrow> T \\<^sup>*\\<frown>\\<^sup>* V \\<and> U \\<^sup>*\\<frown>\\<^sup>* V \\<^sup>*\\\\\\<^sup>* T\"\n    and \"T \\<^sup>*\\<frown>\\<^sup>* U @ V \\<longleftrightarrow> T \\<^sup>*\\<frown>\\<^sup>* U \\<and> T \\<^sup>*\\\\\\<^sup>* U \\<^sup>*\\<frown>\\<^sup>* V\"\n      using assms Resid_append_ind by blast+\n\n    lemma Con_appendI [intro]:\n    shows \"\\<lbrakk>T \\<^sup>*\\<frown>\\<^sup>* V; U \\<^sup>*\\<frown>\\<^sup>* V \\<^sup>*\\\\\\<^sup>* T\\<rbrakk> \\<Longrightarrow> T @ U \\<^sup>*\\<frown>\\<^sup>* V\"\n    and \"\\<lbrakk>T \\<^sup>*\\<frown>\\<^sup>* U; T \\<^sup>*\\\\\\<^sup>* U \\<^sup>*\\<frown>\\<^sup>* V\\<rbrakk> \\<Longrightarrow> T \\<^sup>*\\<frown>\\<^sup>* U @ V\"\n      by (metis Con_append(1) Con_sym Resid.simps(1))+\n\n    lemma Resid_append [intro, simp]:\n    shows \"\\<lbrakk>T \\<noteq> []; T @ U \\<^sup>*\\<frown>\\<^sup>* V\\<rbrakk> \\<Longrightarrow> (T @ U) \\<^sup>*\\\\\\<^sup>* V = (T \\<^sup>*\\\\\\<^sup>* V) @ (U \\<^sup>*\\\\\\<^sup>* (V \\<^sup>*\\\\\\<^sup>* T))\"\n    and \"\\<lbrakk>U \\<noteq> []; V \\<noteq> []; T \\<^sup>*\\<frown>\\<^sup>* U @ V\\<rbrakk> \\<Longrightarrow> T \\<^sup>*\\\\\\<^sup>* (U @ V) = (T \\<^sup>*\\\\\\<^sup>* U) \\<^sup>*\\\\\\<^sup>* V\"\n      using Resid_append_ind\n       apply (metis Con_sym Resid.simps(1) append_self_conv)\n      using Resid_append_ind\n      by (metis Resid.simps(1))\n\n    lemma Resid_append2 [simp]:\n    assumes \"T \\<noteq> []\" and \"U \\<noteq> []\" and \"V \\<noteq> []\" and \"W \\<noteq> []\"\n    and \"T @ U \\<^sup>*\\<frown>\\<^sup>* V @ W\"\n    shows \"(T @ U) \\<^sup>*\\\\\\<^sup>* (V @ W) =\n           (T \\<^sup>*\\\\\\<^sup>* V) \\<^sup>*\\\\\\<^sup>* W @ (U \\<^sup>*\\\\\\<^sup>* (V \\<^sup>*\\\\\\<^sup>* T)) \\<^sup>*\\\\\\<^sup>* (W \\<^sup>*\\\\\\<^sup>* (T \\<^sup>*\\\\\\<^sup>* V))\"\n      using assms Resid_append\n      by (metis Con_append(1-2) append_is_Nil_conv)\n\n    lemma append_is_composite_of:\n    assumes \"seq T U\"\n    shows \"composite_of T U (T @ U)\"\n      unfolding composite_of_def\n      using assms\n      apply (intro conjI)\n        apply (metis Arr.simps(1) Resid_Arr_self Resid_Ide_Arr_ind Arr_appendI\\<^sub>P\n                     Resid_append_ind ide_char order_refl seq_char)\n       apply (metis Arr.simps(1) Arr_appendI\\<^sub>P Con_Arr_self Resid_Arr_self Resid_append_ind\n                    ide_char seq_char order_refl)\n      by (metis Arr.simps(1) Con_Arr_self Con_append(1) Resid_Arr_self Arr_appendI\\<^sub>P\n                Ide_append_iff\\<^sub>P Resid_append(1) ide_char seq_char order_refl)\n\n    sublocale rts_with_composites Resid\n      using append_is_composite_of composable_def by unfold_locales blast\n\n    theorem is_rts_with_composites:\n    shows \"rts_with_composites Resid\"\n      ..\n\n    (* TODO: This stuff might be redundant. *)\n    lemma arr_append [intro, simp]:\n    assumes \"seq T U\"\n    shows \"arr (T @ U)\"\n      using assms arrI\\<^sub>P seq_char by simp\n\n    lemma arr_append_imp_seq:\n    assumes \"T \\<noteq> []\" and \"U \\<noteq> []\" and \"arr (T @ U)\"\n    shows \"seq T U\"\n      using assms arr_char seq_char Arr_append_iff\\<^sub>P seq_implies_Trgs_eq_Srcs by simp\n\n    lemma sources_append [simp]:\n    assumes \"seq T U\"\n    shows \"sources (T @ U) = sources T\"\n      using assms\n      by (meson append_is_composite_of sources_composite_of)\n\n    lemma targets_append [simp]:\n    assumes \"seq T U\"\n    shows \"targets (T @ U) = targets U\"\n      using assms\n      by (meson append_is_composite_of targets_composite_of)\n\n    lemma cong_respects_seq\\<^sub>P:\n    assumes \"seq T U\" and \"T \\<^sup>*\\<sim>\\<^sup>* T'\" and \"U \\<^sup>*\\<sim>\\<^sup>* U'\"\n    shows \"seq T' U'\"\n      by (meson assms cong_respects_seq)\n\n    lemma cong_append [intro]:\n    assumes \"seq T U\" and \"T \\<^sup>*\\<sim>\\<^sup>* T'\" and \"U \\<^sup>*\\<sim>\\<^sup>* U'\"\n    shows \"T @ U \\<^sup>*\\<sim>\\<^sup>* T' @ U'\"\n    proof\n      have 1: \"\\<And>T U T' U'. \\<lbrakk>seq T U; T \\<^sup>*\\<sim>\\<^sup>* T'; U \\<^sup>*\\<sim>\\<^sup>* U'\\<rbrakk> \\<Longrightarrow> seq T' U'\"\n        using assms cong_respects_seq\\<^sub>P by simp\n      have 2: \"\\<And>T U T' U'. \\<lbrakk>seq T U; T \\<^sup>*\\<sim>\\<^sup>* T'; U \\<^sup>*\\<sim>\\<^sup>* U'\\<rbrakk> \\<Longrightarrow> T @ U \\<^sup>*\\<lesssim>\\<^sup>* T' @ U'\"\n      proof -\n        fix T U T' U'\n        assume TU: \"seq T U\" and TT': \"T \\<^sup>*\\<sim>\\<^sup>* T'\" and UU': \"U \\<^sup>*\\<sim>\\<^sup>* U'\"\n        have T'U': \"seq T' U'\"\n          using TU TT' UU' cong_respects_seq\\<^sub>P by simp\n        have 3: \"Ide (T \\<^sup>*\\\\\\<^sup>* T') \\<and> Ide (T' \\<^sup>*\\\\\\<^sup>* T) \\<and> Ide (U \\<^sup>*\\\\\\<^sup>* U') \\<and> Ide (U' \\<^sup>*\\\\\\<^sup>* U)\"\n          using TU TT' UU' ide_char by blast\n        have \"(T @ U) \\<^sup>*\\\\\\<^sup>* (T' @ U') =\n              ((T \\<^sup>*\\\\\\<^sup>* T') \\<^sup>*\\\\\\<^sup>* U') @ U \\<^sup>*\\\\\\<^sup>* ((T' \\<^sup>*\\\\\\<^sup>* T) @ U' \\<^sup>*\\\\\\<^sup>* (T \\<^sup>*\\\\\\<^sup>* T'))\"\n        proof -\n          have 4: \"T \\<noteq> [] \\<and> U \\<noteq> [] \\<and> T' \\<noteq> [] \\<and> U' \\<noteq> []\"\n            using TU TT' UU' Arr.simps(1) seq_char ide_char by auto\n          moreover have \"(T @ U) \\<^sup>*\\\\\\<^sup>* (T' @ U') \\<noteq> []\"\n          proof (intro Con_appendI)\n            show \"T \\<^sup>*\\\\\\<^sup>* T' \\<noteq> []\"\n              using \"3\" by force\n            show \"(T \\<^sup>*\\\\\\<^sup>* T') \\<^sup>*\\\\\\<^sup>* U' \\<noteq> []\"\n              using \"3\" T'U' \\<open>T \\<^sup>*\\\\<^sup>* T' \\<noteq> []\\<close> Con_Ide_iff seq_char by fastforce\n            show \"U \\<^sup>*\\\\\\<^sup>* ((T' @ U') \\<^sup>*\\\\\\<^sup>* T) \\<noteq> []\"\n            proof -\n              have \"U \\<^sup>*\\\\\\<^sup>* ((T' @ U') \\<^sup>*\\\\\\<^sup>* T) = U \\<^sup>*\\\\\\<^sup>* ((T' \\<^sup>*\\\\\\<^sup>* T) @ U' \\<^sup>*\\\\\\<^sup>* (T \\<^sup>*\\\\\\<^sup>* T'))\"\n                by (metis Con_appendI(1) Resid_append(1) \\<open>(T \\<^sup>*\\\\<^sup>* T') \\<^sup>*\\\\<^sup>* U' \\<noteq> []\\<close>\n                    \\<open>T \\<^sup>*\\\\<^sup>* T' \\<noteq> []\\<close> calculation Con_sym)\n              also have \"... = (U \\<^sup>*\\\\\\<^sup>* (T' \\<^sup>*\\\\\\<^sup>* T)) \\<^sup>*\\\\\\<^sup>* (U' \\<^sup>*\\\\\\<^sup>* (T \\<^sup>*\\\\\\<^sup>* T'))\"\n                by (metis Arr.simps(1) Con_append(2) Resid_append(2) \\<open>(T \\<^sup>*\\\\<^sup>* T') \\<^sup>*\\\\<^sup>* U' \\<noteq> []\\<close>\n                    Con_implies_Arr(1) Con_sym)\n              also have \"... = U \\<^sup>*\\\\\\<^sup>* U'\"\n                by (metis (mono_tags, lifting) \"3\" Ide.simps(1) Resid_Ide(1) Srcs_Resid TU\n                    \\<open>(T \\<^sup>*\\\\<^sup>* T') \\<^sup>*\\\\<^sup>* U' \\<noteq> []\\<close> Con_Ide_iff seq_char)\n              finally show ?thesis\n                using 3 UU' by force\n            qed\n          qed\n          ultimately show ?thesis\n            using Resid_append2 [of T U T' U'] seq_char\n            by (metis Con_append(2) Con_sym Resid_append(2) Resid.simps(1))\n        qed\n        moreover have \"Ide ...\"\n        proof\n          have 3: \"Ide (T \\<^sup>*\\\\\\<^sup>* T') \\<and> Ide (T' \\<^sup>*\\\\\\<^sup>* T) \\<and> Ide (U \\<^sup>*\\\\\\<^sup>* U') \\<and> Ide (U' \\<^sup>*\\\\\\<^sup>* U)\"\n            using TU TT' UU' ide_char by blast\n          show 4: \"Ide ((T \\<^sup>*\\\\\\<^sup>* T') \\<^sup>*\\\\\\<^sup>* U')\"\n            using TU T'U' TT' UU' 1 3\n            by (metis (full_types) Srcs_Resid Con_Ide_iff Resid_Ide_Arr_ind seq_char)\n          show 5: \"Ide (U \\<^sup>*\\\\\\<^sup>* ((T' \\<^sup>*\\\\\\<^sup>* T) @ U' \\<^sup>*\\\\\\<^sup>* (T \\<^sup>*\\\\\\<^sup>* T')))\"\n          proof -\n            have \"U \\<^sup>*\\\\\\<^sup>* (T' \\<^sup>*\\\\\\<^sup>* T) = U\"\n              by (metis (full_types) \"3\" TT' TU Con_Ide_iff Resid_Ide(1) Srcs_Resid\n                  con_char seq_char prfx_implies_con)\n            moreover have \"U' \\<^sup>*\\\\\\<^sup>* (T \\<^sup>*\\\\\\<^sup>* T') = U'\"\n              by (metis \"3\" \"4\" Ide.simps(1) Resid_Ide(1))\n            ultimately show ?thesis\n              by (metis \"3\" \"4\" Arr.simps(1) Con_append(2) Ide.simps(1) Resid_append(2)\n                  TU Con_sym seq_char)\n          qed\n          show \"Trgs ((T \\<^sup>*\\\\\\<^sup>* T') \\<^sup>*\\\\\\<^sup>* U') \\<subseteq> Srcs (U \\<^sup>*\\\\\\<^sup>* (T' \\<^sup>*\\\\\\<^sup>* T @ U' \\<^sup>*\\\\\\<^sup>* (T \\<^sup>*\\\\\\<^sup>* T')))\"\n            by (metis 4 5 Arr_append_iff\\<^sub>P Ide.simps(1) Nil_is_append_conv\n                calculation Con_imp_Arr_Resid)\n        qed\n        ultimately show \"T @ U \\<^sup>*\\<lesssim>\\<^sup>* T' @ U'\"\n          using ide_char by presburger\n      qed\n      show \"T @ U \\<^sup>*\\<lesssim>\\<^sup>* T' @ U'\"\n        using assms 2 by simp\n      show \"T' @ U' \\<^sup>*\\<lesssim>\\<^sup>* T @ U\"\n        using assms 1 2 cong_symmetric by blast\n    qed\n\n    lemma cong_cons [intro]:\n    assumes \"seq [t] U\" and \"t \\<sim> t'\" and \"U \\<^sup>*\\<sim>\\<^sup>* U'\"\n    shows \"t # U \\<^sup>*\\<sim>\\<^sup>* t' # U'\"\n      using assms cong_append [of \"[t]\" U \"[t']\" U']\n      by (simp add: R.prfx_implies_con ide_char)\n\n    lemma cong_append_ideI [intro]:\n    assumes \"seq T U\"\n    shows \"ide T \\<Longrightarrow> T @ U \\<^sup>*\\<sim>\\<^sup>* U\" and \"ide U \\<Longrightarrow> T @ U \\<^sup>*\\<sim>\\<^sup>* T\"\n    and \"ide T \\<Longrightarrow> U \\<^sup>*\\<sim>\\<^sup>* T @ U\" and \"ide U \\<Longrightarrow> T \\<^sup>*\\<sim>\\<^sup>* T @ U\"\n    proof -\n      show 1: \"ide T \\<Longrightarrow> T @ U \\<^sup>*\\<sim>\\<^sup>* U\"\n        using assms\n        by (metis append_is_composite_of composite_ofE resid_arr_ide prfx_implies_con\n            con_sym)\n      show 2: \"ide U \\<Longrightarrow> T @ U \\<^sup>*\\<sim>\\<^sup>* T\"\n        by (meson assms append_is_composite_of composite_ofE ide_backward_stable)\n      show \"ide T \\<Longrightarrow> U \\<^sup>*\\<sim>\\<^sup>* T @ U\"\n        using 1 cong_symmetric by auto\n      show \"ide U \\<Longrightarrow> T \\<^sup>*\\<sim>\\<^sup>* T @ U\"\n        using 2 cong_symmetric by auto\n    qed\n\n    lemma cong_cons_ideI [intro]:\n    assumes \"seq [t] U\" and \"R.ide t\"\n    shows \"t # U \\<^sup>*\\<sim>\\<^sup>* U\" and \"U \\<^sup>*\\<sim>\\<^sup>* t # U\"\n      using assms cong_append_ideI [of \"[t]\" U]\n      by (auto simp add: ide_char)\n\n    lemma prfx_decomp:\n    assumes \"[t] \\<^sup>*\\<lesssim>\\<^sup>* [u]\"\n    shows \"[t] @ [u \\\\ t] \\<^sup>*\\<sim>\\<^sup>* [u]\"\n    proof\n      (* TODO: I really want these to be doable by auto. *)\n      show 1: \"[u] \\<^sup>*\\<lesssim>\\<^sup>* [t] @ [u \\\\ t]\"\n        using assms\n        by (metis Con_imp_Arr_Resid Con_rec(3) Resid.simps(3) Resid_rec(3) R.con_sym\n            append.left_neutral append_Cons arr_char cong_reflexive list.distinct(1))\n      show \"[t] @ [u \\\\ t] \\<^sup>*\\<lesssim>\\<^sup>* [u]\"\n      proof -\n        have \"([t] @ [u \\\\ t]) \\<^sup>*\\\\\\<^sup>* [u] = ([t] \\<^sup>*\\\\\\<^sup>* [u]) @ ([u \\\\ t] \\<^sup>*\\\\\\<^sup>* [u \\\\ t])\"\n          using assms\n          by (metis Arr_Resid_single Con_Arr_self Con_appendI(1) Con_sym Resid_append(1)\n              Resid_rec(1) con_char list.discI prfx_implies_con)\n        moreover have \"Ide ...\"\n          using assms\n          by (metis 1 Con_sym append_Nil2 arr_append_imp_seq calculation cong_append_ideI(4)\n              ide_backward_stable Con_implies_Arr(2) Resid_Arr_self con_char ide_char\n              prfx_implies_con arr_resid_iff_con)\n        ultimately show ?thesis\n          using ide_char by presburger\n      qed\n    qed\n\n    lemma composite_of_single_single:\n    assumes \"R.composite_of t u v\"\n    shows \"composite_of [t] [u] ([t] @ [u])\"\n    proof\n      show \"[t] \\<^sup>*\\<lesssim>\\<^sup>* [t] @ [u]\"\n      proof -\n        have \"[t] \\<^sup>*\\\\\\<^sup>* ([t] @ [u]) = ([t] \\<^sup>*\\\\\\<^sup>* [t]) \\<^sup>*\\\\\\<^sup>* [u]\"\n          using assms by auto\n        moreover have \"Ide ...\"\n          by (metis (no_types, lifting) Con_implies_Arr(2) R.bounded_imp_con\n              R.con_composite_of_iff R.con_prfx_composite_of(1) assms resid_ide_arr\n              Con_rec(1) Resid.simps(3) Resid_Arr_self con_char ide_char)\n        ultimately show ?thesis\n          using ide_char by presburger\n      qed\n      show \"([t] @ [u]) \\<^sup>*\\\\\\<^sup>* [t] \\<^sup>*\\<sim>\\<^sup>* [u]\"\n        using assms\n        by (metis \\<open>prfx [t] ([t] @ [u])\\<close> append_is_composite_of arr_append_imp_seq\n            composite_ofE con_def not_Cons_self2 Con_implies_Arr(2) arr_char null_char\n            prfx_implies_con)\n    qed\n\n  end\n\n  subsection \"Paths in a Weakly Extensional RTS\"\n\n  locale paths_in_weakly_extensional_rts =\n    R: weakly_extensional_rts +\n    paths_in_rts\n  begin\n\n    lemma ex_un_Src:\n    assumes \"Arr T\"\n    shows \"\\<exists>!a. a \\<in> Srcs T\"\n      using assms\n      by (simp add: R.weakly_extensional_rts_axioms Srcs_simp\\<^sub>P R.arr_has_un_source)\n\n    fun Src\n    where \"Src T = R.src (hd T)\"\n\n    lemma Srcs_simp\\<^sub>P\\<^sub>W\\<^sub>E:\n    assumes \"Arr T\"\n    shows \"Srcs T = {Src T}\"\n    proof -\n      have \"[R.src (hd T)] \\<in> sources T\"\n        by (metis Arr_imp_arr_hd Con_single_ide_ind Ide.simps(2) Srcs_simp\\<^sub>P assms\n                  con_char ide_char in_sourcesI con_sym R.ide_src R.src_in_sources)\n      hence \"R.src (hd T) \\<in> Srcs T\"\n        using assms\n        by (metis Srcs.elims Arr_has_Src list.sel(1) R.arr_iff_has_source R.src_in_sources)\n      thus ?thesis\n        using assms ex_un_Src by auto\n    qed\n\n    lemma ex_un_Trg:\n    assumes \"Arr T\"\n    shows \"\\<exists>!b. b \\<in> Trgs T\"\n      using assms\n      apply (induct T)\n       apply auto[1]\n      by (metis Con_Arr_self Ide_implies_Arr Resid_Arr_self Srcs_Resid ex_un_Src)\n\n    fun Trg\n    where \"Trg [] = R.null\"\n        | \"Trg [t] = R.trg t\"\n        | \"Trg (t # T) = Trg T\"\n\n    lemma Trg_simp [simp]:\n    shows \"T \\<noteq> [] \\<Longrightarrow> Trg T = R.trg (last T)\"\n      apply (induct T)\n       apply auto\n      by (metis Trg.simps(3) list.exhaust_sel)\n\n    lemma Trgs_simp\\<^sub>P\\<^sub>W\\<^sub>E [simp]:\n    assumes \"Arr T\"\n    shows \"Trgs T = {Trg T}\"\n      using assms\n      by (metis Arr_imp_arr_last Con_Arr_self Con_imp_Arr_Resid R.trg_in_targets\n          Srcs.simps(1) Srcs_Resid Srcs_simp\\<^sub>P\\<^sub>W\\<^sub>E Trg_simp insertE insert_absorb insert_not_empty\n          Trgs_simp\\<^sub>P)\n\n    lemma Src_resid [simp]:\n    assumes \"T \\<^sup>*\\<frown>\\<^sup>* U\"\n    shows \"Src (T \\<^sup>*\\\\\\<^sup>* U) = Trg U\"\n      using assms Con_imp_Arr_Resid Con_implies_Arr(2) Srcs_Resid Srcs_simp\\<^sub>P\\<^sub>W\\<^sub>E by force\n\n    lemma Trg_resid_sym:\n    assumes \"T \\<^sup>*\\<frown>\\<^sup>* U\"\n    shows \"Trg (T \\<^sup>*\\\\\\<^sup>* U) = Trg (U \\<^sup>*\\\\\\<^sup>* T)\"\n      using assms Con_imp_Arr_Resid Con_sym Trgs_Resid_sym by auto\n\n    lemma Src_append [simp]:\n    assumes \"seq T U\"\n    shows \"Src (T @ U) = Src T\"\n      using assms\n      by (metis Arr.simps(1) Src.simps hd_append seq_char)\n\n    lemma Trg_append [simp]:\n    assumes \"seq T U\"\n    shows \"Trg (T @ U) = Trg U\"\n      using assms\n      by (metis Ide.simps(1) Resid.simps(1) Trg_simp append_is_Nil_conv ide_char ide_trg\n          last_appendR seqE trg_def)\n\n    lemma Arr_append_iff\\<^sub>P\\<^sub>W\\<^sub>E:\n    assumes \"T \\<noteq> []\" and \"U \\<noteq> []\"\n    shows \"Arr (T @ U) \\<longleftrightarrow> Arr T \\<and> Arr U \\<and> Trg T = Src U\"\n      using assms Arr_appendE\\<^sub>P Srcs_simp\\<^sub>P\\<^sub>W\\<^sub>E by auto\n\n    lemma Arr_consI\\<^sub>P\\<^sub>W\\<^sub>E [intro, simp]:\n    assumes \"R.arr t\" and \"Arr U\" and \"R.trg t = Src U\"\n    shows \"Arr (t # U)\"\n      using assms\n      by (metis Arr.simps(2) Srcs_simp\\<^sub>P\\<^sub>W\\<^sub>E Trg.simps(2) Trgs.simps(2) Trgs_simp\\<^sub>P\\<^sub>W\\<^sub>E\n          dual_order.eq_iff Arr_consI\\<^sub>P)\n\n    lemma Arr_consE [elim]:\n    assumes \"Arr (t # U)\"\n    and \"\\<lbrakk>R.arr t; U \\<noteq> [] \\<Longrightarrow> Arr U; U \\<noteq> [] \\<Longrightarrow> R.trg t = Src U\\<rbrakk> \\<Longrightarrow> thesis\"\n    shows thesis\n      using assms\n      by (metis Arr_append_iff\\<^sub>P\\<^sub>W\\<^sub>E Trg.simps(2) append_Cons append_Nil list.distinct(1)\n          Arr.simps(2))\n\n    lemma Arr_appendI\\<^sub>P\\<^sub>W\\<^sub>E [intro, simp]:\n    assumes \"Arr T\" and \"Arr U\" and \"Trg T = Src U\"\n    shows \"Arr (T @ U)\"\n      using assms\n      by (metis Arr.simps(1) Arr_append_iff\\<^sub>P\\<^sub>W\\<^sub>E)\n\n    lemma Arr_appendE\\<^sub>P\\<^sub>W\\<^sub>E [elim]:\n    assumes \"Arr (T @ U)\" and \"T \\<noteq> []\" and \"U \\<noteq> []\"\n    and \"\\<lbrakk>Arr T; Arr U; Trg T = Src U\\<rbrakk> \\<Longrightarrow> thesis\"\n    shows thesis\n      using assms Arr_append_iff\\<^sub>P\\<^sub>W\\<^sub>E seq_implies_Trgs_eq_Srcs by force\n\n    lemma Ide_append_iff\\<^sub>P\\<^sub>W\\<^sub>E:\n    assumes \"T \\<noteq> []\" and \"U \\<noteq> []\"\n    shows \"Ide (T @ U) \\<longleftrightarrow> Ide T \\<and> Ide U \\<and> Trg T = Src U\"\n      using assms Ide_char by auto\n\n    lemma Ide_appendI\\<^sub>P\\<^sub>W\\<^sub>E [intro, simp]:\n    assumes \"Ide T\" and \"Ide U\" and \"Trg T = Src U\"\n    shows \"Ide (T @ U)\"\n      using assms\n      by (metis Ide.simps(1) Ide_append_iff\\<^sub>P\\<^sub>W\\<^sub>E)\n\n    lemma Ide_appendE [elim]:\n    assumes \"Ide (T @ U)\" and \"T \\<noteq> []\" and \"U \\<noteq> []\"\n    and \"\\<lbrakk>Ide T; Ide U; Trg T = Src U\\<rbrakk> \\<Longrightarrow> thesis\"\n    shows thesis\n      using assms Ide_append_iff\\<^sub>P\\<^sub>W\\<^sub>E by metis\n\n    lemma Ide_consI [intro, simp]:\n    assumes \"R.ide t\" and \"Ide U\" and \"R.trg t = Src U\"\n    shows \"Ide (t # U)\"\n      using assms\n      by (simp add: Ide_char)\n\n    lemma Ide_consE [elim]:\n    assumes \"Ide (t # U)\"\n    and \"\\<lbrakk>R.ide t; U \\<noteq> [] \\<Longrightarrow> Ide U; U \\<noteq> [] \\<Longrightarrow> R.trg t = Src U\\<rbrakk> \\<Longrightarrow> thesis\"\n    shows thesis\n      using assms\n      by (metis Con_rec(4) Ide.simps(2) Ide_imp_Ide_hd Ide_imp_Ide_tl R.trg_def R.trg_ide\n          Resid_Arr_Ide_ind Trg.simps(2) ide_char list.sel(1) list.sel(3) list.simps(3)\n          Src_resid ide_def)\n\n    lemma Ide_imp_Src_eq_Trg:\n    assumes \"Ide T\"\n    shows \"Src T = Trg T\"\n      using assms\n      by (metis Ide.simps(1) Src_resid ide_char ide_def)\n\n  end\n\n  subsection \"Paths in a Confluent RTS\"\n\n  text \\<open>\n    Here we show that confluence of an RTS extends to  confluence of the RTS of its paths.\n  \\<close>\n\n  locale paths_in_confluent_rts =\n    paths_in_rts +\n    R: confluent_rts\n  begin\n\n    lemma confluence_single:\n    assumes \"\\<And>t u. R.coinitial t u \\<Longrightarrow> t \\<frown> u\"\n    shows \"\\<lbrakk>R.arr t; Arr U; R.sources t = Srcs U\\<rbrakk> \\<Longrightarrow> [t] \\<^sup>*\\<frown>\\<^sup>* U\"\n    proof (induct U arbitrary: t)\n      show \"\\<And>t. \\<lbrakk>R.arr t; Arr []; R.sources t = Srcs []\\<rbrakk> \\<Longrightarrow> [t] \\<^sup>*\\<frown>\\<^sup>* []\"\n        by simp\n      fix t u U\n      assume ind: \"\\<And>t. \\<lbrakk>R.arr t; Arr U; R.sources t = Srcs U\\<rbrakk> \\<Longrightarrow> [t] \\<^sup>*\\<frown>\\<^sup>* U\"\n      assume t: \"R.arr t\"\n      assume uU: \"Arr (u # U)\"\n      assume coinitial: \"R.sources t = Srcs (u # U)\"\n      hence 1: \"R.coinitial t u\"\n        using t uU\n        by (metis Arr.simps(2) Con_implies_Arr(1) Con_imp_eq_Srcs Con_initial_left\n            Srcs.simps(2) Con_Arr_self R.coinitial_iff)\n      show \"[t] \\<^sup>*\\<frown>\\<^sup>* u # U\"\n      proof (cases \"U = []\")\n        show \"U = [] \\<Longrightarrow> ?thesis\"\n          using assms t uU coinitial R.coinitial_iff by fastforce\n        assume U: \"U \\<noteq> []\"\n        show ?thesis\n        proof -\n          have 2: \"Arr [t \\\\ u] \\<and> Arr U \\<and> Srcs [t \\\\ u] = Srcs U\"\n            using assms 1 t uU U R.arr_resid_iff_con\n            apply (intro conjI)\n              apply simp\n             apply (metis Con_Arr_self Con_implies_Arr(2) Resid_cons(2))\n            by (metis (full_types) Con_cons(2) Srcs.simps(2) Srcs_Resid Trgs.simps(2)\n                Con_Arr_self Con_imp_eq_Srcs list.simps(3) R.sources_resid)\n          have \"[t] \\<^sup>*\\<frown>\\<^sup>* u # U \\<longleftrightarrow> t \\<frown> u \\<and> [t \\\\ u] \\<^sup>*\\<frown>\\<^sup>* U\"\n            using U Con_rec(3) [of U t u] by simp\n          also have \"... \\<longleftrightarrow> True\"\n            using assms t uU U 1 2 ind by force\n          finally show ?thesis by blast\n        qed\n      qed\n    qed\n\n    lemma confluence_ind:\n    shows \"\\<lbrakk>Arr T; Arr U; Srcs T = Srcs U\\<rbrakk> \\<Longrightarrow> T \\<^sup>*\\<frown>\\<^sup>* U\"\n    proof (induct T arbitrary: U)\n      show \"\\<And>U. \\<lbrakk>Arr []; Arr U; Srcs [] = Srcs U\\<rbrakk> \\<Longrightarrow> [] \\<^sup>*\\<frown>\\<^sup>* U\"\n        by simp\n      fix t T U\n      assume ind: \"\\<And>U. \\<lbrakk>Arr T; Arr U; Srcs T = Srcs U\\<rbrakk> \\<Longrightarrow> T \\<^sup>*\\<frown>\\<^sup>* U\"\n      assume tT: \"Arr (t # T)\"\n      assume U: \"Arr U\"\n      assume coinitial: \"Srcs (t # T) = Srcs U\"\n      show \"t # T \\<^sup>*\\<frown>\\<^sup>* U\"\n      proof (cases \"T = []\")\n        show \"T = [] \\<Longrightarrow> ?thesis\"\n          using U tT coinitial confluence_single [of t U] R.confluence by simp\n        assume T: \"T \\<noteq> []\"\n        show ?thesis\n        proof -\n          have 1: \"[t] \\<^sup>*\\<frown>\\<^sup>* U\"\n            using tT U coinitial R.confluence\n            by (metis R.arr_def Srcs.simps(2) T Con_Arr_self Con_imp_eq_Srcs\n                Con_initial_right Con_rec(4) confluence_single)\n          moreover have \"T \\<^sup>*\\<frown>\\<^sup>* U \\<^sup>*\\\\\\<^sup>* [t]\"\n            using 1 tT U T coinitial ind [of \"U \\<^sup>*\\\\\\<^sup>* [t]\"]\n            by (metis (full_types) Con_imp_Arr_Resid Arr_iff_Con_self Con_implies_Arr(2)\n                Con_imp_eq_Srcs Con_sym R.sources_resid Srcs.simps(2) Srcs_Resid\n                Trgs.simps(2) Con_rec(4))\n          ultimately show ?thesis\n            using Con_cons(1) [of T U t] by fastforce\n        qed\n      qed\n    qed\n\n    lemma confluence\\<^sub>P:\n    assumes \"coinitial T U\"\n    shows \"con T U\"\n      using assms confluence_ind sources_char\\<^sub>P coinitial_def con_char by auto\n\n    sublocale confluent_rts Resid\n      apply (unfold_locales)\n      using confluence\\<^sub>P by simp\n\n    lemma is_confluent_rts:\n    shows \"confluent_rts Resid\"\n      ..\n\n  end\n\n  subsection \"Simulations Lift to Paths\"\n\n  text \\<open>\n    In this section we show that a simulation from RTS \\<open>A\\<close> to RTS \\<open>B\\<close> determines a simulation\n    from the RTS of paths in \\<open>A\\<close> to the RTS of paths in \\<open>B\\<close>.  In other words, the path-RTS\n    construction is functorial with respect to simulation.\n  \\<close>\n\n  context simulation\n  begin\n\n    interpretation P\\<^sub>A: paths_in_rts A\n      ..\n    interpretation P\\<^sub>B: paths_in_rts B\n      ..\n\n    lemma map_Resid_single:\n    shows \"P\\<^sub>A.con T [u] \\<Longrightarrow> map F (P\\<^sub>A.Resid T [u]) = P\\<^sub>B.Resid (map F T) [F u]\"\n      apply (induct T arbitrary: u)\n       apply simp\n    proof -\n      fix t u T\n      assume ind: \"\\<And>u. P\\<^sub>A.con T [u] \\<Longrightarrow> map F (P\\<^sub>A.Resid T [u]) = P\\<^sub>B.Resid (map F T) [F u]\"\n      assume 1: \"P\\<^sub>A.con (t # T) [u]\"\n      show \"map F (P\\<^sub>A.Resid (t # T) [u]) = P\\<^sub>B.Resid (map F (t # T)) [F u]\"\n      proof (cases \"T = []\")\n        show \"T = [] \\<Longrightarrow> ?thesis\"\n          using \"1\" P\\<^sub>A.null_char by fastforce\n        assume T: \"T \\<noteq> []\"\n        show ?thesis\n          using T 1 ind P\\<^sub>A.con_def P\\<^sub>A.null_char P\\<^sub>A.Con_rec(2) P\\<^sub>A.Resid_rec(2) P\\<^sub>B.Con_rec(2)\n                P\\<^sub>B.Resid_rec(2)\n          apply simp\n          by (metis A.con_sym Nil_is_map_conv preserves_con preserves_resid)\n      qed\n    qed\n\n    lemma map_Resid:\n    shows \"P\\<^sub>A.con T U \\<Longrightarrow> map F (P\\<^sub>A.Resid T U) = P\\<^sub>B.Resid (map F T) (map F U)\"\n      apply (induct U arbitrary: T)\n      using P\\<^sub>A.Resid.simps(1) P\\<^sub>A.con_char P\\<^sub>A.con_sym\n       apply blast\n    proof -\n      fix u U T\n      assume ind: \"\\<And>T. P\\<^sub>A.con T U \\<Longrightarrow>\n                          map F (P\\<^sub>A.Resid T U) = P\\<^sub>B.Resid (map F T) (map F U)\"\n      assume 1: \"P\\<^sub>A.con T (u # U)\"\n      show \"map F (P\\<^sub>A.Resid T (u # U)) = P\\<^sub>B.Resid (map F T) (map F (u # U))\"\n      proof (cases \"U = []\")\n        show \"U = [] \\<Longrightarrow> ?thesis\"\n          using \"1\" map_Resid_single by force\n        assume U: \"U \\<noteq> []\"\n        have \"P\\<^sub>B.Resid (map F T) (map F (u # U)) =\n              P\\<^sub>B.Resid (P\\<^sub>B.Resid (map F T) [F u]) (map F U)\"\n          using U 1 P\\<^sub>B.Resid_cons(2)\n          apply simp\n          by (metis P\\<^sub>B.Arr.simps(1) P\\<^sub>B.Con_consI(2) P\\<^sub>B.Con_implies_Arr(1) list.map_disc_iff)\n        also have \"... = map F (P\\<^sub>A.Resid (P\\<^sub>A.Resid T [u]) U)\"\n          using U 1 ind\n          by (metis P\\<^sub>A.Con_initial_right P\\<^sub>A.Resid_cons(2) P\\<^sub>A.con_char map_Resid_single)\n        also have \"... = map F (P\\<^sub>A.Resid T (u # U))\"\n          using \"1\" P\\<^sub>A.Resid_cons(2) P\\<^sub>A.con_char U by auto\n        finally show ?thesis by simp\n      qed\n    qed\n\n    lemma preserves_paths:\n    shows \"P\\<^sub>A.Arr T \\<Longrightarrow> P\\<^sub>B.Arr (map F T)\"\n      by (metis P\\<^sub>A.Con_Arr_self P\\<^sub>A.conI\\<^sub>P P\\<^sub>B.Arr_iff_Con_self map_Resid map_is_Nil_conv)\n\n    interpretation Fx: simulation P\\<^sub>A.Resid P\\<^sub>B.Resid \\<open>\\<lambda>T. if P\\<^sub>A.Arr T then map F T else []\\<close>\n    proof\n      let ?Fx = \"\\<lambda>T. if P\\<^sub>A.Arr T then map F T else []\"\n      show \"\\<And>T. \\<not> P\\<^sub>A.arr T \\<Longrightarrow> ?Fx T = P\\<^sub>B.null\"\n        by (simp add: P\\<^sub>A.arr_char P\\<^sub>B.null_char)\n      show \"\\<And>T U. P\\<^sub>A.con T U \\<Longrightarrow> P\\<^sub>B.con (?Fx T) (?Fx U)\"\n        using P\\<^sub>A.Con_implies_Arr(1) P\\<^sub>A.Con_implies_Arr(2) P\\<^sub>A.con_char map_Resid by fastforce\n      show \"\\<And>T U. P\\<^sub>A.con T U \\<Longrightarrow> ?Fx (P\\<^sub>A.Resid T U) = P\\<^sub>B.Resid (?Fx T) (?Fx U)\"\n        by (simp add: P\\<^sub>A.Con_imp_Arr_Resid P\\<^sub>A.Con_implies_Arr(1) P\\<^sub>A.Con_implies_Arr(2)\n            P\\<^sub>A.con_char map_Resid)\n    qed\n\n    lemma lifts_to_paths:\n    shows \"simulation P\\<^sub>A.Resid P\\<^sub>B.Resid (\\<lambda>T. if P\\<^sub>A.Arr T then map F T else [])\"\n      ..\n\n  end\n\n  subsection \"Normal Sub-RTS's Lift to Paths\"\n\n  text \\<open>\n    Here we show that a normal sub-RTS \\<open>N\\<close> of an RTS \\<open>R\\<close> lifts to a normal sub-RTS\n    of the RTS of paths in \\<open>N\\<close>, and that it is coherent if \\<open>N\\<close> is.\n  \\<close>\n\n  locale paths_in_rts_with_normal =\n    R: rts +\n    N: normal_sub_rts +\n    paths_in_rts\n  begin\n\n    text \\<open>\n      We define a ``normal path'' to be a path that consists entirely of normal transitions.\n      We show that the collection of all normal paths is a normal sub-RTS of the RTS of paths.\n    \\<close>\n\n    definition NPath\n    where \"NPath T \\<equiv> (Arr T \\<and> set T \\<subseteq> \\<NN>)\"\n\n    lemma Ide_implies_NPath:\n    assumes \"Ide T\"\n    shows \"NPath T\"\n      using assms\n      by (metis Ball_Collect NPath_def Ide_implies_Arr N.ide_closed set_Ide_subset_ide\n          subsetI)\n\n    lemma NPath_implies_Arr:\n    assumes \"NPath T\"\n    shows \"Arr T\"\n      using assms NPath_def by simp\n\n    lemma NPath_append:\n    assumes \"T \\<noteq> []\" and \"U \\<noteq> []\"\n    shows \"NPath (T @ U) \\<longleftrightarrow> NPath T \\<and> NPath U \\<and> Trgs T \\<subseteq> Srcs U\"\n      using assms NPath_def by auto\n      \n    lemma NPath_appendI [intro, simp]:\n    assumes \"NPath T\" and \"NPath U\" and \"Trgs T \\<subseteq> Srcs U\"\n    shows \"NPath (T @ U)\"\n      using assms NPath_def by simp\n\n    lemma NPath_Resid_single_Arr:\n    shows \"\\<lbrakk>t \\<in> \\<NN>; Arr U; R.sources t = Srcs U\\<rbrakk> \\<Longrightarrow> NPath (Resid [t] U)\"\n    proof (induct U arbitrary: t)\n      show \"\\<And>t. \\<lbrakk>t \\<in> \\<NN>; Arr []; R.sources t = Srcs []\\<rbrakk> \\<Longrightarrow> NPath (Resid [t] [])\"\n        by simp\n      fix t u U\n      assume ind: \"\\<And>t. \\<lbrakk>t \\<in> \\<NN>; Arr U; R.sources t = Srcs U\\<rbrakk> \\<Longrightarrow> NPath (Resid [t] U)\"\n      assume t: \"t \\<in> \\<NN>\"\n      assume uU: \"Arr (u # U)\"\n      assume src: \"R.sources t = Srcs (u # U)\"\n      show \"NPath (Resid [t] (u # U))\"\n      proof (cases \"U = []\")\n        show \"U = [] \\<Longrightarrow> ?thesis\"\n          using NPath_def t src\n          apply simp\n          by (metis Arr.simps(2) R.arr_resid_iff_con R.coinitialI N.forward_stable\n              N.elements_are_arr uU)\n        assume U: \"U \\<noteq> []\"\n        show ?thesis\n        proof -\n          have \"NPath (Resid [t] (u # U)) \\<longleftrightarrow> NPath (Resid [t \\\\ u] U)\"\n            using t U uU src\n            by (metis Arr.simps(2) Con_implies_Arr(1) Resid_rec(3) Con_rec(3) R.arr_resid_iff_con)\n          also have \"... \\<longleftrightarrow> True\"\n          proof -\n            have \"t \\\\ u \\<in> \\<NN>\"\n              using t U uU src N.forward_stable [of t u]\n              by (metis Con_Arr_self Con_imp_eq_Srcs Con_initial_left\n                        Srcs.simps(2) inf.idem Arr_has_Src R.coinitial_def)\n            moreover have \"Arr U\"\n              using U uU\n              by (metis Arr.simps(3) neq_Nil_conv)\n            moreover have \"R.sources (t \\\\ u) = Srcs U\"\n              using t uU src\n              by (metis Con_Arr_self Srcs.simps(2) U calculation(1) Con_imp_eq_Srcs\n                        Con_rec(4) N.elements_are_arr R.sources_resid R.arr_resid_iff_con)\n            ultimately show ?thesis\n              using ind [of \"t \\\\ u\"] by simp\n          qed\n          finally show ?thesis by blast\n        qed\n      qed\n    qed\n\n    lemma NPath_Resid_Arr_single:\n    shows \"\\<lbrakk> NPath T; R.arr u; Srcs T = R.sources u \\<rbrakk> \\<Longrightarrow> NPath (Resid T [u])\"\n    proof (induct T arbitrary: u)\n      show \"\\<And>u. \\<lbrakk>NPath []; R.arr u; Srcs [] = R.sources u\\<rbrakk> \\<Longrightarrow> NPath (Resid [] [u])\"\n        by simp\n      fix t u T\n      assume ind: \"\\<And>u. \\<lbrakk>NPath T; R.arr u; Srcs T = R.sources u\\<rbrakk> \\<Longrightarrow> NPath (Resid T [u])\"\n      assume tT: \"NPath (t # T)\"\n      assume u: \"R.arr u\"\n      assume src: \"Srcs (t # T) = R.sources u\"\n      show \"NPath (Resid (t # T) [u])\"\n      proof (cases \"T = []\")\n        show \"T = [] \\<Longrightarrow> ?thesis\"\n          using tT u src NPath_def\n          by (metis Arr.simps(2) NPath_Resid_single_Arr Srcs.simps(2) list.set_intros(1) subsetD)\n        assume T: \"T \\<noteq> []\"\n        have \"R.coinitial u t\"\n          by (metis R.coinitialI Srcs.simps(3) T list.exhaust_sel src u)\n        hence con: \"t \\<frown> u\"\n          using tT T u src R.con_sym NPath_def\n          by (metis N.forward_stable N.elements_are_arr R.not_arr_null\n              list.set_intros(1) R.conI subsetD)\n        have 1: \"NPath (Resid (t # T) [u]) \\<longleftrightarrow> NPath ((t \\\\ u) # Resid T [u \\\\ t])\"\n        proof -\n          have \"t # T \\<^sup>*\\<frown>\\<^sup>* [u]\"\n          proof -\n            have 2: \"[t] \\<^sup>*\\<frown>\\<^sup>* [u]\"\n              by (simp add: Con_rec(1) con)\n            moreover have \"T \\<^sup>*\\<frown>\\<^sup>* Resid [u] [t]\"\n            proof -\n              have \"NPath T\"\n                using tT T NPath_def\n                by (metis NPath_append append_Cons append_Nil)\n              moreover have 3: \"R.arr (u \\\\ t)\"\n                using con by (meson R.arr_resid_iff_con R.con_sym)\n              moreover have \"Srcs T = R.sources (u \\\\ t)\"\n                using tT T u src con\n                by (metis \"3\" Arr_iff_Con_self Con_cons(2) Con_imp_eq_Srcs\n                    R.sources_resid Srcs_Resid Trgs.simps(2) NPath_implies_Arr list.discI\n                    R.arr_resid_iff_con)\n              ultimately show ?thesis\n                using 2 ind [of \"u \\\\ t\"] NPath_def by auto\n            qed\n            ultimately show ?thesis\n              using tT T u src Con_cons(1) [of T \"[u]\" t] by simp\n          qed\n          thus ?thesis\n            using tT T u src Resid_cons(1) [of T t \"[u]\"] Resid_rec(2) by presburger\n        qed\n        also have \"... \\<longleftrightarrow> True\"\n        proof -\n          have 2: \"t \\\\ u \\<in> \\<NN> \\<and> R.arr (u \\\\ t)\"\n            using tT u src con NPath_def\n            by (meson R.arr_resid_iff_con R.con_sym N.forward_stable \\<open>R.coinitial u t\\<close>\n                list.set_intros(1) subsetD)\n          moreover have 3: \"NPath (T \\<^sup>*\\\\\\<^sup>* [u \\\\ t])\"\n            using tT ind [of \"u \\\\ t\"] NPath_def\n            by (metis Con_Arr_self Con_imp_eq_Srcs Con_rec(4) R.arr_resid_iff_con\n                R.sources_resid Srcs.simps(2) T calculation insert_subset list.exhaust\n                list.simps(15) Arr.simps(3))\n          moreover have \"R.targets (t \\\\ u) \\<subseteq> Srcs (Resid T [u \\\\ t])\"\n            using tT T u src NPath_def\n            by (metis \"3\" Arr.simps(1) R.targets_resid_sym Srcs_Resid_Arr_single con subset_refl)\n          ultimately show ?thesis\n            using NPath_def\n            by (metis Arr_consI\\<^sub>P N.elements_are_arr insert_subset list.simps(15))\n        qed\n        finally show ?thesis by blast\n      qed\n    qed\n\n    lemma NPath_Resid [simp]:\n    shows \"\\<lbrakk>NPath T; Arr U; Srcs T = Srcs U\\<rbrakk> \\<Longrightarrow> NPath (T \\<^sup>*\\\\\\<^sup>* U)\"\n    proof (induct T arbitrary: U)\n      show \"\\<And>U. \\<lbrakk>NPath []; Arr U; Srcs [] = Srcs U\\<rbrakk> \\<Longrightarrow> NPath ([] \\<^sup>*\\\\\\<^sup>* U)\"\n        by simp\n      fix t T U\n      assume ind: \"\\<And>U. \\<lbrakk>NPath T; Arr U; Srcs T = Srcs U\\<rbrakk> \\<Longrightarrow> NPath (T \\<^sup>*\\\\\\<^sup>* U)\"\n      assume tT: \"NPath (t # T)\"\n      assume U: \"Arr U\"\n      assume Coinitial: \"Srcs (t # T) = Srcs U\"\n      show \"NPath ((t # T) \\<^sup>*\\\\\\<^sup>* U)\"\n      proof (cases \"T = []\")\n        show \"T = [] \\<Longrightarrow> ?thesis\"\n          using tT U Coinitial NPath_Resid_single_Arr [of t U] NPath_def by force\n        assume T: \"T \\<noteq> []\"\n        have 0: \"NPath ((t # T) \\<^sup>*\\\\\\<^sup>* U) \\<longleftrightarrow> NPath ([t] \\<^sup>*\\\\\\<^sup>* U @ T \\<^sup>*\\\\\\<^sup>* (U \\<^sup>*\\\\\\<^sup>* [t]))\"\n        proof -\n          have \"U \\<noteq> []\"\n            using U by auto\n          moreover have \"(t # T) \\<^sup>*\\<frown>\\<^sup>* U\"\n          proof -\n            have \"t \\<in> \\<NN>\"\n              using tT NPath_def by auto\n            moreover have \"R.sources t = Srcs U\"\n              using Coinitial\n              by (metis Srcs.elims U list.sel(1) Arr_has_Src)\n            ultimately have 1: \"[t] \\<^sup>*\\<frown>\\<^sup>* U\"\n              using U NPath_Resid_single_Arr [of t U] NPath_def by auto\n            moreover have \"T \\<^sup>*\\<frown>\\<^sup>* (U \\<^sup>*\\\\\\<^sup>* [t])\"\n            proof -\n              have \"Srcs T = Srcs (U \\<^sup>*\\\\\\<^sup>* [t])\"\n                using tT U Coinitial 1\n                by (metis Con_Arr_self Con_cons(2) Con_imp_eq_Srcs Con_sym Srcs_Resid_Arr_single\n                    T list.discI NPath_implies_Arr)\n              hence \"NPath (T \\<^sup>*\\\\\\<^sup>* (U \\<^sup>*\\\\\\<^sup>* [t]))\"\n                using tT U Coinitial 1 Con_sym ind [of \"Resid U [t]\"] NPath_def\n                by (metis Con_imp_Arr_Resid Srcs.elims T insert_subset list.simps(15)\n                    Arr.simps(3))\n              thus ?thesis\n                using NPath_def by auto\n            qed\n            ultimately show ?thesis\n              using Con_cons(1) [of T U t] by fastforce\n          qed\n          ultimately show ?thesis\n            using tT U T Coinitial Resid_cons(1) by auto\n        qed\n        also have \"... \\<longleftrightarrow> True\"\n        proof (intro iffI, simp_all)\n          have 1: \"NPath ([t] \\<^sup>*\\\\\\<^sup>* U)\"\n            by (metis Coinitial NPath_Resid_single_Arr Srcs_simp\\<^sub>P U insert_subset\n                list.sel(1) list.simps(15) NPath_def tT)\n          moreover have 2: \"NPath (T \\<^sup>*\\\\\\<^sup>* (U \\<^sup>*\\\\\\<^sup>* [t]))\"\n            by (metis \"0\" Arr.simps(1) Con_cons(1) Con_imp_eq_Srcs Con_implies_Arr(1-2)\n                NPath_def T append_Nil2 calculation ind insert_subset list.simps(15) tT)\n          moreover have \"Trgs ([t] \\<^sup>*\\\\\\<^sup>* U) \\<subseteq> Srcs (T \\<^sup>*\\\\\\<^sup>* (U \\<^sup>*\\\\\\<^sup>* [t]))\"\n            by (metis Arr.simps(1) NPath_def Srcs_Resid Trgs_Resid_sym calculation(2)\n                dual_order.refl)\n          ultimately show \"NPath ([t] \\<^sup>*\\\\\\<^sup>* U @ T \\<^sup>*\\\\\\<^sup>* (U \\<^sup>*\\\\\\<^sup>* [t]))\"\n            using NPath_append [of \"T \\<^sup>*\\\\\\<^sup>* (U \\<^sup>*\\\\\\<^sup>* [t])\" \"[t] \\<^sup>*\\\\\\<^sup>* U\"] by fastforce\n        qed\n        finally show ?thesis by blast\n      qed\n    qed\n\n    lemma Backward_stable_single:\n    shows \"\\<lbrakk>NPath U; NPath ([t] \\<^sup>*\\\\\\<^sup>* U)\\<rbrakk> \\<Longrightarrow> NPath [t]\"\n    proof (induct U arbitrary: t)\n      show \"\\<And>t. \\<lbrakk>NPath []; NPath ([t] \\<^sup>*\\\\\\<^sup>* [])\\<rbrakk> \\<Longrightarrow> NPath [t]\"\n        using NPath_def by simp\n      fix t u U\n      assume ind: \"\\<And>t. \\<lbrakk>NPath U; NPath ([t] \\<^sup>*\\\\\\<^sup>* U)\\<rbrakk> \\<Longrightarrow> NPath [t]\"\n      assume uU: \"NPath (u # U)\"\n      assume resid: \"NPath ([t] \\<^sup>*\\\\\\<^sup>* (u # U))\"\n      show \"NPath [t]\"\n        using uU ind NPath_def\n        by (metis Arr.simps(1) Arr.simps(2) Con_implies_Arr(2) N.backward_stable\n            N.elements_are_arr Resid_rec(1) Resid_rec(3) insert_subset list.simps(15) resid)\n    qed\n\n    lemma Backward_stable:\n    shows \"\\<lbrakk>NPath U; NPath (T \\<^sup>*\\\\\\<^sup>* U)\\<rbrakk> \\<Longrightarrow> NPath T\"\n    proof (induct T arbitrary: U)\n      show \"\\<And>U. \\<lbrakk>NPath U; NPath ([] \\<^sup>*\\\\\\<^sup>* U)\\<rbrakk> \\<Longrightarrow> NPath []\"\n        by simp\n      fix t T U\n      assume ind: \"\\<And>U. \\<lbrakk>NPath U; NPath (T \\<^sup>*\\\\\\<^sup>* U)\\<rbrakk> \\<Longrightarrow> NPath T\"\n      assume U: \"NPath U\"\n      assume resid: \"NPath ((t # T) \\<^sup>*\\\\\\<^sup>* U)\"\n      show \"NPath (t # T)\"\n      proof (cases \"T = []\")\n        show \"T = [] \\<Longrightarrow> ?thesis\"\n          using U resid Backward_stable_single by blast\n        assume T: \"T \\<noteq> []\"\n        have 1: \"NPath ([t] \\<^sup>*\\\\\\<^sup>* U) \\<and> NPath (T \\<^sup>*\\\\\\<^sup>* (U \\<^sup>*\\\\\\<^sup>* [t]))\"\n          using T U NPath_append resid NPath_def\n          by (metis Arr.simps(1) Con_cons(1) Resid_cons(1))\n        have 2: \"t \\<in> \\<NN>\"\n          using 1 U Backward_stable_single NPath_def by simp\n        moreover have \"NPath T\"\n          using 1 U resid ind\n          by (metis 2 Arr.simps(2) Con_imp_eq_Srcs NPath_Resid N.elements_are_arr)\n        moreover have \"R.targets t \\<subseteq> Srcs T\"\n          using resid 1 Con_imp_eq_Srcs Con_sym Srcs_Resid_Arr_single NPath_def\n          by (metis Arr.simps(1) dual_order.eq_iff)\n        ultimately show ?thesis\n          using NPath_def\n          by (simp add: N.elements_are_arr)\n      qed\n    qed\n\n    sublocale normal_sub_rts Resid \\<open>Collect NPath\\<close>\n      using Ide_implies_NPath NPath_implies_Arr arr_char ide_char coinitial_def\n            sources_char\\<^sub>P append_is_composite_of\n      apply unfold_locales\n           apply auto\n      using Backward_stable\n      by metis+\n\n    theorem normal_extends_to_paths:\n    shows \"normal_sub_rts Resid (Collect NPath)\"\n      ..\n\n    lemma Resid_NPath_preserves_reflects_Con:\n    assumes \"NPath U\" and \"Srcs T = Srcs U\"\n    shows \"T \\<^sup>*\\\\\\<^sup>* U \\<^sup>*\\<frown>\\<^sup>* T' \\<^sup>*\\\\\\<^sup>* U \\<longleftrightarrow> T \\<^sup>*\\<frown>\\<^sup>* T'\"\n      using assms NPath_def NPath_Resid con_char con_imp_coinitial resid_along_elem_preserves_con\n            Con_implies_Arr(2) Con_sym Cube(1)\n      by (metis Arr.simps(1) mem_Collect_eq)\n\n    notation Cong\\<^sub>0  (infix \"\\<approx>\\<^sup>*\\<^sub>0\" 50)\n    notation Cong  (infix \"\\<approx>\\<^sup>*\" 50)\n\n    (*\n     * TODO: Leave these for now -- they still seem a little difficult to prove\n     * in this context, but are probably useful.\n     *)\n    lemma Cong\\<^sub>0_cancel_left\\<^sub>C\\<^sub>S:\n    assumes \"T @ U \\<approx>\\<^sup>*\\<^sub>0 T @ U'\" and \"T \\<noteq> []\" and \"U \\<noteq> []\" and \"U' \\<noteq> []\"\n    shows \"U \\<approx>\\<^sup>*\\<^sub>0 U'\"\n      using assms Cong\\<^sub>0_cancel_left [of T U \"T @ U\" U' \"T @ U'\"] Cong\\<^sub>0_reflexive\n            append_is_composite_of\n      by (metis Cong\\<^sub>0_implies_Cong Cong_imp_arr(1) arr_append_imp_seq)\n\n    lemma Srcs_respects_Cong:\n    assumes \"T \\<approx>\\<^sup>* T'\" and \"a \\<in> Srcs T\" and \"a' \\<in> Srcs T'\"\n    shows \"[a] \\<approx>\\<^sup>* [a']\"\n    proof -\n      obtain U U' where UU': \"NPath U \\<and> NPath U' \\<and> T \\<^sup>*\\\\\\<^sup>* U \\<approx>\\<^sup>*\\<^sub>0 T' \\<^sup>*\\\\\\<^sup>* U'\"\n        using assms(1) by blast\n      show ?thesis\n      proof\n        show \"U \\<in> Collect NPath\"\n          using UU' by simp\n        show \"U' \\<in> Collect NPath\"\n          using UU' by simp\n        show \"[a] \\<^sup>*\\\\\\<^sup>* U \\<approx>\\<^sup>*\\<^sub>0 [a'] \\<^sup>*\\\\\\<^sup>* U'\"\n        proof -\n          have \"NPath ([a] \\<^sup>*\\\\\\<^sup>* U) \\<and> NPath ([a'] \\<^sup>*\\\\\\<^sup>* U')\"\n            by (metis Arr.simps(1) Con_imp_eq_Srcs Con_implies_Arr(1) Con_single_ide_ind\n                NPath_implies_Arr N.ide_closed R.in_sourcesE Srcs.simps(2) Srcs_simp\\<^sub>P\n                UU' assms(2-3) elements_are_arr not_arr_null null_char NPath_Resid_single_Arr)\n          thus ?thesis\n            using UU'\n            by (metis Con_imp_eq_Srcs Cong\\<^sub>0_imp_con NPath_Resid Srcs_Resid\n                con_char NPath_implies_Arr mem_Collect_eq arr_resid_iff_con con_implies_arr(2))\n        qed\n      qed\n    qed\n\n    lemma Trgs_respects_Cong:\n    assumes \"T \\<approx>\\<^sup>* T'\" and \"b \\<in> Trgs T\" and \"b' \\<in> Trgs T'\"\n    shows \"[b] \\<approx>\\<^sup>* [b']\"\n    proof -\n      have \"[b] \\<in> targets T \\<and> [b'] \\<in> targets T'\"\n      proof -\n        have 1: \"Ide [b] \\<and> Ide [b']\"\n          using assms\n          by (metis Ball_Collect Trgs_are_ide Ide.simps(2))\n        moreover have \"Srcs [b] = Trgs T\"\n          using assms\n          by (metis 1 Con_imp_Arr_Resid Con_imp_eq_Srcs Cong_imp_arr(1) Ide.simps(2)\n              Srcs_Resid Con_single_ide_ind con_char arrE)\n        moreover have \"Srcs [b'] = Trgs T'\"\n          using assms\n          by (metis Con_imp_Arr_Resid Con_imp_eq_Srcs Cong_imp_arr(2) Ide.simps(2)\n              Srcs_Resid 1 Con_single_ide_ind con_char arrE)\n        ultimately show ?thesis\n          unfolding targets_char\\<^sub>P\n          using assms Cong_imp_arr(2) arr_char by blast\n      qed\n      thus ?thesis\n        using assms targets_char in_targets_respects_Cong [of T T' \"[b]\" \"[b']\"] by simp\n    qed\n\n    lemma Cong\\<^sub>0_append_resid_NPath:\n    assumes \"NPath (T \\<^sup>*\\\\\\<^sup>* U)\"\n    shows \"Cong\\<^sub>0 (T @ (U \\<^sup>*\\\\\\<^sup>* T)) U\"\n    proof (intro conjI)\n      show 0: \"(T @ U \\<^sup>*\\\\\\<^sup>* T) \\<^sup>*\\\\\\<^sup>* U \\<in> Collect NPath\"\n      proof -\n        have 1: \"(T @ U \\<^sup>*\\\\\\<^sup>* T) \\<^sup>*\\\\\\<^sup>* U = T \\<^sup>*\\\\\\<^sup>* U @ (U \\<^sup>*\\\\\\<^sup>* T) \\<^sup>*\\\\\\<^sup>* (U \\<^sup>*\\\\\\<^sup>* T)\"\n          by (metis Arr.simps(1) NPath_implies_Arr assms Con_append(1) Con_implies_Arr(2)\n              Con_sym Resid_append(1) con_imp_arr_resid null_char)\n        moreover have \"NPath ...\"\n          using assms\n          by (metis 1 Arr_append_iff\\<^sub>P NPath_append NPath_implies_Arr Ide_implies_NPath\n              Nil_is_append_conv Resid_Arr_self arr_char con_char arr_resid_iff_con\n              self_append_conv)\n        ultimately show ?thesis by simp\n      qed\n      show \"U \\<^sup>*\\\\\\<^sup>* (T @ U \\<^sup>*\\\\\\<^sup>* T) \\<in> Collect NPath\"\n        using assms 0\n        by (metis Arr.simps(1) Con_implies_Arr(2) Cong\\<^sub>0_reflexive Resid_append(2)\n            append.right_neutral arr_char Con_sym)\n    qed\n\n  end\n\n  locale paths_in_rts_with_coherent_normal =\n    R: rts +\n    N: coherent_normal_sub_rts +\n    paths_in_rts\n  begin\n\n    sublocale paths_in_rts_with_normal resid \\<NN> ..\n\n    notation Cong\\<^sub>0  (infix \"\\<approx>\\<^sup>*\\<^sub>0\" 50)\n    notation Cong  (infix \"\\<approx>\\<^sup>*\" 50)\n\n    text \\<open>\n      Since composites of normal transitions are assumed to exist, normal paths can be\n      ``folded'' by composition down to single transitions.\n    \\<close>\n\n    lemma NPath_folding:\n    shows \"NPath U \\<Longrightarrow> \\<exists>u. u \\<in> \\<NN> \\<and> R.sources u = Srcs U \\<and> R.targets u = Trgs U \\<and>\n                           (\\<forall>t. con [t] U \\<longrightarrow> [t] \\<^sup>*\\\\\\<^sup>* U \\<approx>\\<^sup>*\\<^sub>0 [t \\\\ u])\"\n    proof (induct U)\n      show \"NPath [] \\<Longrightarrow> \\<exists>u. u \\<in> \\<NN> \\<and> R.sources u = Srcs [] \\<and> R.targets u = Trgs [] \\<and>\n                             (\\<forall>t. con [t] [] \\<longrightarrow> [t] \\<^sup>*\\\\\\<^sup>* [] \\<approx>\\<^sup>*\\<^sub>0 [t \\\\ u])\"\n        using NPath_def by auto\n      fix v U\n      assume ind: \"NPath U \\<Longrightarrow> \\<exists>u. u \\<in> \\<NN> \\<and> R.sources u = Srcs U \\<and> R.targets u = Trgs U \\<and>\n                                   (\\<forall>t. con [t] U \\<longrightarrow> [t] \\<^sup>*\\\\\\<^sup>* U \\<approx>\\<^sup>*\\<^sub>0 [t \\\\ u])\"\n      assume vU: \"NPath (v # U)\"\n      show \"\\<exists>vU. vU \\<in> \\<NN> \\<and> R.sources vU = Srcs (v # U) \\<and> R.targets vU = Trgs (v # U) \\<and>\n                 (\\<forall>t. con [t] (v # U) \\<longrightarrow> [t] \\<^sup>*\\\\\\<^sup>* (v # U) \\<approx>\\<^sup>*\\<^sub>0 [t \\\\ vU])\"\n      proof (cases \"U = []\")\n        show \"U = [] \\<Longrightarrow> \\<exists>vU. vU \\<in> \\<NN> \\<and> R.sources vU = Srcs (v # U) \\<and>\n                              R.targets vU = Trgs (v # U) \\<and>\n                              (\\<forall>t. con [t] (v # U) \\<longrightarrow> [t] \\<^sup>*\\\\\\<^sup>* (v # U) \\<approx>\\<^sup>*\\<^sub>0 [t \\\\ vU])\"\n          using vU Resid_rec(1) con_char\n          by (metis Cong\\<^sub>0_reflexive NPath_def Srcs.simps(2) Trgs.simps(2) arr_resid_iff_con\n              insert_subset list.simps(15))\n        assume \"U \\<noteq> []\"\n        hence U: \"NPath U\"\n          using vU by (metis NPath_append append_Cons append_Nil)\n        obtain u where u: \"u \\<in> \\<NN> \\<and> R.sources u = Srcs U \\<and> R.targets u = Trgs U \\<and>\n                           (\\<forall>t. con [t] U \\<longrightarrow> [t] \\<^sup>*\\\\\\<^sup>* U \\<approx>\\<^sup>*\\<^sub>0 [t \\\\ u])\"\n          using U ind by blast\n        have seq: \"R.seq v u\"\n        proof\n          show \"R.arr v\"\n            using vU\n            by (metis Con_Arr_self Con_rec(4) NPath_implies_Arr \\<open>U \\<noteq> []\\<close> R.arrI)\n          show \"R.arr u\"\n            by (simp add: N.elements_are_arr u)\n          show \"R.targets v = R.sources u\"\n            by (metis (full_types) NPath_implies_Arr R.sources_resid Srcs.simps(2) \\<open>U \\<noteq> []\\<close>\n                Con_Arr_self Con_imp_eq_Srcs Con_initial_right Con_rec(2) u vU)\n        qed\n        obtain vu where vu: \"R.composite_of v u vu\"\n          using N.composite_closed_right seq u by presburger\n        have \"vu \\<in> \\<NN> \\<and> R.sources vu = Srcs (v # U) \\<and> R.targets vu = Trgs (v # U) \\<and>\n              (\\<forall>t. con [t] (v # U) \\<longrightarrow> [t] \\<^sup>*\\\\\\<^sup>* (v # U) \\<approx>\\<^sup>*\\<^sub>0 [t \\\\ vu])\"\n        proof (intro conjI allI)\n          show \"vu \\<in> \\<NN>\"\n            by (meson NPath_def N.composite_closed list.set_intros(1) subsetD u vU vu)\n          show \"R.sources vu = Srcs (v # U)\"\n            by (metis Con_imp_eq_Srcs Con_initial_right NPath_implies_Arr\n                      R.sources_composite_of Srcs.simps(2) Arr_iff_Con_self vU vu)\n          show \"R.targets vu = Trgs (v # U)\"\n            by (metis R.targets_composite_of Trgs.simps(3) \\<open>U \\<noteq> []\\<close> list.exhaust_sel u vu)\n          fix t\n          show \"con [t] (v # U) \\<longrightarrow> [t] \\<^sup>*\\\\\\<^sup>* (v # U) \\<approx>\\<^sup>*\\<^sub>0 [t \\\\ vu]\"\n          proof (intro impI)\n            assume t: \"con [t] (v # U)\"\n            have 1: \"[t] \\<^sup>*\\\\\\<^sup>* (v # U) = [t \\\\ v] \\<^sup>*\\\\\\<^sup>* U\"\n              using t Resid_rec(3) \\<open>U \\<noteq> []\\<close> con_char by force\n            also have \"... \\<approx>\\<^sup>*\\<^sub>0 [(t \\\\ v) \\\\ u]\"\n              using 1 t u by force\n            also have \"[(t \\\\ v) \\\\ u] \\<approx>\\<^sup>*\\<^sub>0 [t \\\\ vu]\"\n            proof -\n              have \"(t \\\\ v) \\\\ u \\<sim> t \\\\ vu\"\n                using vu R.resid_composite_of\n                by (metis (no_types, lifting) N.Cong\\<^sub>0_composite_of_arr_normal N.Cong\\<^sub>0_subst_right(1)\n                    \\<open>U \\<noteq> []\\<close> Con_rec(3) con_char R.con_sym t u)\n              thus ?thesis\n                using Ide.simps(2) R.prfx_implies_con Resid.simps(3) ide_char ide_closed\n                by presburger\n            qed\n            finally show \"[t] \\<^sup>*\\\\\\<^sup>* (v # U) \\<approx>\\<^sup>*\\<^sub>0 [t \\\\ vu]\" by blast\n          qed\n        qed\n        thus ?thesis by blast\n      qed\n    qed\n\n    text \\<open>\n      Coherence for single transitions extends inductively to paths.\n    \\<close>\n\n    lemma Coherent_single:\n    assumes \"R.arr t\" and \"NPath U\" and \"NPath U'\"\n    and \"R.sources t = Srcs U\" and \"Srcs U = Srcs U'\" and \"Trgs U = Trgs U'\"\n    shows \"[t] \\<^sup>*\\\\\\<^sup>* U \\<approx>\\<^sup>*\\<^sub>0 [t] \\<^sup>*\\\\\\<^sup>* U'\"\n    proof -\n      have 1: \"con [t] U \\<and> con [t] U'\"\n        using assms\n        by (metis Arr.simps(1-2) Arr_iff_Con_self Resid_NPath_preserves_reflects_Con\n            Srcs.simps(2) con_char)\n      obtain u where u: \"u \\<in> \\<NN> \\<and> R.sources u = Srcs U \\<and> R.targets u = Trgs U \\<and>\n                         (\\<forall>t. con [t] U \\<longrightarrow> [t] \\<^sup>*\\\\\\<^sup>* U \\<approx>\\<^sup>*\\<^sub>0 [t \\\\ u])\"\n        using assms NPath_folding by metis\n      obtain u' where u': \"u' \\<in> \\<NN> \\<and> R.sources u' = Srcs U' \\<and> R.targets u' = Trgs U' \\<and>\n                           (\\<forall>t. con [t] U' \\<longrightarrow> [t] \\<^sup>*\\\\\\<^sup>* U' \\<approx>\\<^sup>*\\<^sub>0 [t \\\\ u'])\"\n        using assms NPath_folding by metis\n      have \"[t] \\<^sup>*\\\\\\<^sup>* U  \\<approx>\\<^sup>*\\<^sub>0 [t \\\\ u]\"\n        using u 1 by blast\n      also have \"[t \\\\ u] \\<approx>\\<^sup>*\\<^sub>0 [t \\\\ u']\"\n        using assms(1,4-6) N.Cong\\<^sub>0_imp_con N.coherent u u' NPath_def by simp\n      also have \"[t \\\\ u'] \\<approx>\\<^sup>*\\<^sub>0 [t] \\<^sup>*\\\\\\<^sup>* U'\"\n        using u' 1 by simp\n      finally show ?thesis by simp\n    qed\n\n    lemma Coherent:\n    shows \"\\<lbrakk> Arr T; NPath U; NPath U'; Srcs T = Srcs U;\n             Srcs U = Srcs U'; Trgs U = Trgs U' \\<rbrakk>\n                \\<Longrightarrow> T \\<^sup>*\\\\\\<^sup>* U \\<approx>\\<^sup>*\\<^sub>0 T \\<^sup>*\\\\\\<^sup>* U'\"\n    proof (induct T arbitrary: U U')\n      show \"\\<And>U U'. \\<lbrakk> Arr []; NPath U; NPath U'; Srcs [] = Srcs U;\n                    Srcs U = Srcs U'; Trgs U = Trgs U' \\<rbrakk>\n                      \\<Longrightarrow> [] \\<^sup>*\\\\\\<^sup>* U \\<approx>\\<^sup>*\\<^sub>0 [] \\<^sup>*\\\\\\<^sup>* U'\"\n        by (simp add: arr_char)\n      fix t T U U'\n      assume tT: \"Arr (t # T)\" and U: \"NPath U\" and U': \"NPath U'\"\n      and Srcs1: \"Srcs (t # T) = Srcs U\" and Srcs2: \"Srcs U = Srcs U'\"\n      and Trgs: \"Trgs U = Trgs U'\"\n      and ind: \"\\<And>U U'. \\<lbrakk> Arr T; NPath U; NPath U'; Srcs T = Srcs U;\n                        Srcs U = Srcs U'; Trgs U = Trgs U' \\<rbrakk>\n                            \\<Longrightarrow> T \\<^sup>*\\\\\\<^sup>* U \\<approx>\\<^sup>*\\<^sub>0 T \\<^sup>*\\\\\\<^sup>* U'\"\n      have t: \"R.arr t\"\n        using tT by (metis Arr.simps(2) Con_Arr_self Con_rec(4) R.arrI)\n      show \"(t # T) \\<^sup>*\\\\\\<^sup>* U \\<approx>\\<^sup>*\\<^sub>0 (t # T) \\<^sup>*\\\\\\<^sup>* U'\"\n      proof (cases \"T = []\")\n        show \"T = [] \\<Longrightarrow> ?thesis\"\n           by (metis Srcs.simps(2) Srcs1 Srcs2 Trgs U U' Coherent_single Arr.simps(2) tT)\n        assume T: \"T \\<noteq> []\"\n        let ?t = \"[t] \\<^sup>*\\\\\\<^sup>* U\" and ?t' = \"[t] \\<^sup>*\\\\\\<^sup>* U'\"\n        let ?T = \"T \\<^sup>*\\\\\\<^sup>* (U \\<^sup>*\\\\\\<^sup>* [t])\"\n        let ?T' = \"T \\<^sup>*\\\\\\<^sup>* (U' \\<^sup>*\\\\\\<^sup>* [t])\"\n        have 0: \"(t # T) \\<^sup>*\\\\\\<^sup>* U = ?t @ ?T \\<and> (t # T) \\<^sup>*\\\\\\<^sup>* U' = ?t' @ ?T'\"\n          using tT U U' Srcs1 Srcs2\n          by (metis Arr_has_Src Arr_iff_Con_self Resid_cons(1) Srcs.simps(1)\n              Resid_NPath_preserves_reflects_Con)\n        have 1: \"?t \\<approx>\\<^sup>*\\<^sub>0 ?t'\"\n          by (metis Srcs1 Srcs2 Srcs_simp\\<^sub>P Trgs U U' list.sel(1) Coherent_single t tT)\n        have A: \"?T \\<^sup>*\\\\\\<^sup>* (?t' \\<^sup>*\\\\\\<^sup>* ?t) = T \\<^sup>*\\\\\\<^sup>* ((U \\<^sup>*\\\\\\<^sup>* [t]) @ (?t' \\<^sup>*\\\\\\<^sup>* ?t))\"\n          using 1 Arr.simps(1) Con_append(2) Con_sym Resid_append(2) Con_implies_Arr(1)\n                NPath_def\n          by (metis arr_char elements_are_arr)\n        have B: \"?T' \\<^sup>*\\\\\\<^sup>* (?t \\<^sup>*\\\\\\<^sup>* ?t') = T \\<^sup>*\\\\\\<^sup>* ((U' \\<^sup>*\\\\\\<^sup>* [t]) @ (?t \\<^sup>*\\\\\\<^sup>* ?t'))\"\n          by (metis \"1\" Con_appendI(2) Con_sym Resid.simps(1) Resid_append(2) elements_are_arr\n              not_arr_null null_char)\n        have E: \"?T \\<^sup>*\\\\\\<^sup>* (?t' \\<^sup>*\\\\\\<^sup>* ?t) \\<approx>\\<^sup>*\\<^sub>0 ?T' \\<^sup>*\\\\\\<^sup>* (?t \\<^sup>*\\\\\\<^sup>* ?t')\"\n        proof -\n          have \"Arr T\"\n            using Arr.elims(1) T tT by blast\n          moreover have \"NPath (U \\<^sup>*\\\\\\<^sup>* [t] @ ([t] \\<^sup>*\\\\\\<^sup>* U') \\<^sup>*\\\\\\<^sup>* ([t] \\<^sup>*\\\\\\<^sup>* U))\"\n            using 1 U t tT Srcs1 Srcs_simp\\<^sub>P\n            apply (intro NPath_appendI)\n              apply auto\n            by (metis Arr.simps(1) NPath_def Srcs_Resid Trgs_Resid_sym)\n          moreover have \"NPath (U' \\<^sup>*\\\\\\<^sup>* [t] @ ([t] \\<^sup>*\\\\\\<^sup>* U) \\<^sup>*\\\\\\<^sup>* ([t] \\<^sup>*\\\\\\<^sup>* U'))\"\n            using t U' 1 Con_imp_eq_Srcs Trgs_Resid_sym\n            apply (intro NPath_appendI)\n              apply auto\n             apply (metis Arr.simps(2) NPath_Resid Resid.simps(1))\n            by (metis Arr.simps(1) NPath_def Srcs_Resid)\n          moreover have \"Srcs T = Srcs (U \\<^sup>*\\\\\\<^sup>* [t] @ ([t] \\<^sup>*\\\\\\<^sup>* U') \\<^sup>*\\\\\\<^sup>* ([t] \\<^sup>*\\\\\\<^sup>* U))\"\n            using A B\n            by (metis (full_types) \"0\" \"1\" Arr_has_Src Con_cons(1) Con_implies_Arr(1)\n                Srcs.simps(1) Srcs_append T elements_are_arr not_arr_null null_char\n                Con_imp_eq_Srcs)\n          moreover have \"Srcs (U \\<^sup>*\\\\\\<^sup>* [t] @ ([t] \\<^sup>*\\\\\\<^sup>* U') \\<^sup>*\\\\\\<^sup>* ([t] \\<^sup>*\\\\\\<^sup>* U)) =\n                         Srcs (U' \\<^sup>*\\\\\\<^sup>* [t] @ ([t] \\<^sup>*\\\\\\<^sup>* U) \\<^sup>*\\\\\\<^sup>* ([t] \\<^sup>*\\\\\\<^sup>* U'))\"\n            by (metis \"1\" Con_implies_Arr(2) Con_sym Cong\\<^sub>0_imp_con Srcs_Resid Srcs_append\n                arr_char con_char arr_resid_iff_con)\n          moreover have \"Trgs (U \\<^sup>*\\\\\\<^sup>* [t] @ ([t] \\<^sup>*\\\\\\<^sup>* U') \\<^sup>*\\\\\\<^sup>* ([t] \\<^sup>*\\\\\\<^sup>* U)) =\n                         Trgs (U' \\<^sup>*\\\\\\<^sup>* [t] @ ([t] \\<^sup>*\\\\\\<^sup>* U) \\<^sup>*\\\\\\<^sup>* ([t] \\<^sup>*\\\\\\<^sup>* U'))\"\n            using \"1\" Cong\\<^sub>0_imp_con con_char by force\n          ultimately show ?thesis\n            using A B ind [of \"(U \\<^sup>*\\\\\\<^sup>* [t]) @ (?t' \\<^sup>*\\\\\\<^sup>* ?t)\" \"(U' \\<^sup>*\\\\\\<^sup>* [t]) @ (?t \\<^sup>*\\\\\\<^sup>* ?t')\"]\n            by simp\n        qed\n        have C: \"NPath ((?T \\<^sup>*\\\\\\<^sup>* (?t' \\<^sup>*\\\\\\<^sup>* ?t)) \\<^sup>*\\\\\\<^sup>* (?T' \\<^sup>*\\\\\\<^sup>* (?t \\<^sup>*\\\\\\<^sup>* ?t')))\"\n          using E by blast\n        have D: \"NPath ((?T' \\<^sup>*\\\\\\<^sup>* (?t \\<^sup>*\\\\\\<^sup>* ?t')) \\<^sup>*\\\\\\<^sup>* (?T \\<^sup>*\\\\\\<^sup>* (?t' \\<^sup>*\\\\\\<^sup>* ?t)))\"\n          using E by blast\n        show ?thesis\n        proof\n          have 2: \"((t # T) \\<^sup>*\\\\\\<^sup>* U) \\<^sup>*\\\\\\<^sup>* ((t # T) \\<^sup>*\\\\\\<^sup>* U') =\n                   ((?t \\<^sup>*\\\\\\<^sup>* ?t') \\<^sup>*\\\\\\<^sup>* ?T') @ ((?T \\<^sup>*\\\\\\<^sup>* (?t' \\<^sup>*\\\\\\<^sup>* ?t)) \\<^sup>*\\\\\\<^sup>* (?T' \\<^sup>*\\\\\\<^sup>* (?t \\<^sup>*\\\\\\<^sup>* ?t')))\"\n          proof -\n            have \"((t # T) \\<^sup>*\\\\\\<^sup>* U) \\<^sup>*\\\\\\<^sup>* ((t # T) \\<^sup>*\\\\\\<^sup>* U') = (?t @ ?T) \\<^sup>*\\\\\\<^sup>* (?t' @ ?T')\"\n              using 0 by fastforce\n            also have \"... = ((?t @ ?T) \\<^sup>*\\\\\\<^sup>* ?t') \\<^sup>*\\\\\\<^sup>* ?T'\"\n              using tT T U U' Srcs1 Srcs2 0\n              by (metis Con_appendI(2) Con_cons(1) Con_sym Resid.simps(1) Resid_append(2))\n            also have \"... = ((?t \\<^sup>*\\\\\\<^sup>* ?t') @ (?T \\<^sup>*\\\\\\<^sup>* (?t' \\<^sup>*\\\\\\<^sup>* ?t))) \\<^sup>*\\\\\\<^sup>* ?T'\"\n              by (metis (no_types, lifting) Arr.simps(1) Con_appendI(1) Con_implies_Arr(1)\n                  D NPath_def Resid_append(1) null_is_zero(2))\n            also have \"... = ((?t \\<^sup>*\\\\\\<^sup>* ?t') \\<^sup>*\\\\\\<^sup>* ?T') @\n                               ((?T \\<^sup>*\\\\\\<^sup>* (?t' \\<^sup>*\\\\\\<^sup>* ?t)) \\<^sup>*\\\\\\<^sup>* (?T' \\<^sup>*\\\\\\<^sup>* (?t \\<^sup>*\\\\\\<^sup>* ?t')))\"\n            proof -\n              have \"?t \\<^sup>*\\\\\\<^sup>* ?t' @ ?T \\<^sup>*\\\\\\<^sup>* (?t' \\<^sup>*\\\\\\<^sup>* ?t) \\<^sup>*\\<frown>\\<^sup>* ?T'\"\n                using C D E Con_sym\n                by (metis Con_append(2) Cong\\<^sub>0_imp_con con_char arr_resid_iff_con\n                          con_implies_arr(2))\n              thus ?thesis\n                using Resid_append(1)\n                by (metis Con_sym append.right_neutral Resid.simps(1))\n            qed\n            finally show ?thesis by simp\n          qed\n          moreover have 3: \"NPath ...\"\n          proof -\n            have \"NPath ((?t \\<^sup>*\\\\\\<^sup>* ?t') \\<^sup>*\\\\\\<^sup>* ?T')\"\n              using 0 1 E\n              by (metis Con_imp_Arr_Resid Con_imp_eq_Srcs NPath_Resid Resid.simps(1)\n                  ex_un_null mem_Collect_eq)\n            moreover have \"Trgs ((?t \\<^sup>*\\\\\\<^sup>* ?t') \\<^sup>*\\\\\\<^sup>* ?T') =\n                           Srcs ((?T \\<^sup>*\\\\\\<^sup>* (?t' \\<^sup>*\\\\\\<^sup>* ?t)) \\<^sup>*\\\\\\<^sup>* (?T' \\<^sup>*\\\\\\<^sup>* (?t \\<^sup>*\\\\\\<^sup>* ?t')))\"\n              using C\n              by (metis NPath_implies_Arr Srcs.simps(1) Srcs_Resid\n                  Trgs_Resid_sym Arr_has_Src)\n            ultimately show ?thesis\n              using C by blast\n          qed\n          ultimately show \"((t # T) \\<^sup>*\\\\\\<^sup>* U) \\<^sup>*\\\\\\<^sup>* ((t # T) \\<^sup>*\\\\\\<^sup>* U') \\<in> Collect NPath\"\n            by simp\n\n          have 4: \"((t # T) \\<^sup>*\\\\\\<^sup>* U') \\<^sup>*\\\\\\<^sup>* ((t # T) \\<^sup>*\\\\\\<^sup>* U) =\n                ((?t' \\<^sup>*\\\\\\<^sup>* ?t) \\<^sup>*\\\\\\<^sup>* ?T) @ ((?T' \\<^sup>*\\\\\\<^sup>* (?t \\<^sup>*\\\\\\<^sup>* ?t')) \\<^sup>*\\\\\\<^sup>* (?T \\<^sup>*\\\\\\<^sup>* (?t' \\<^sup>*\\\\\\<^sup>* ?t)))\"\n            by (metis \"0\" \"2\" \"3\" Arr.simps(1) Con_implies_Arr(1) Con_sym D NPath_def Resid_append2)\n          moreover have \"NPath ...\"\n          proof -\n            have \"NPath ((?t' \\<^sup>*\\\\\\<^sup>* ?t) \\<^sup>*\\\\\\<^sup>* ?T)\"\n              by (metis \"1\" CollectD Cong\\<^sub>0_imp_con E con_imp_coinitial forward_stable\n                  arr_resid_iff_con con_implies_arr(2))\n            moreover have \"NPath ((?T' \\<^sup>*\\\\\\<^sup>* (?t \\<^sup>*\\\\\\<^sup>* ?t')) \\<^sup>*\\\\\\<^sup>* (?T \\<^sup>*\\\\\\<^sup>* (?t' \\<^sup>*\\\\\\<^sup>* ?t)))\"\n              using U U' 1 D ind Coherent_single [of t U' U] by blast\n            moreover have \"Trgs ((?t' \\<^sup>*\\\\\\<^sup>* ?t) \\<^sup>*\\\\\\<^sup>* ?T) =\n                           Srcs ((?T' \\<^sup>*\\\\\\<^sup>* (?t \\<^sup>*\\\\\\<^sup>* ?t')) \\<^sup>*\\\\\\<^sup>* (?T \\<^sup>*\\\\\\<^sup>* (?t' \\<^sup>*\\\\\\<^sup>* ?t)))\"\n              by (metis Arr.simps(1) NPath_def Srcs_Resid Trgs_Resid_sym calculation(2))\n            ultimately show ?thesis by blast\n          qed\n          ultimately show \"((t # T) \\<^sup>*\\\\\\<^sup>* U') \\<^sup>*\\\\\\<^sup>* ((t # T) \\<^sup>*\\\\\\<^sup>* U) \\<in> Collect NPath\"\n            by simp\n        qed\n      qed\n    qed\n\n    sublocale rts_with_composites Resid\n      using is_rts_with_composites by simp\n\n    sublocale coherent_normal_sub_rts Resid \\<open>Collect NPath\\<close>\n    proof\n      fix T U U'\n      assume T: \"arr T\" and U: \"U \\<in> Collect NPath\" and U': \"U' \\<in> Collect NPath\"\n      assume sources_UU': \"sources U = sources U'\" and targets_UU': \"targets U = targets U'\"\n      and TU: \"sources T = sources U\"\n      have \"Srcs T = Srcs U\"\n        using TU sources_char\\<^sub>P T arr_iff_has_source by auto\n      moreover have \"Srcs U = Srcs U'\"\n        by (metis Con_imp_eq_Srcs T TU con_char con_imp_coinitial_ax con_sym in_sourcesE\n            in_sourcesI arr_def sources_UU')\n      moreover have \"Trgs U = Trgs U'\"\n        using U U' targets_UU' targets_char\n        by (metis (full_types) arr_iff_has_target composable_def composable_iff_seq\n            composite_of_arr_target elements_are_arr equals0I seq_char)\n      ultimately show \"T \\<^sup>*\\\\\\<^sup>* U \\<approx>\\<^sup>*\\<^sub>0 T \\<^sup>*\\\\\\<^sup>* U'\"\n        using T U U' Coherent [of T U U'] arr_char by blast\n    qed\n\n    theorem coherent_normal_extends_to_paths:\n    shows \"coherent_normal_sub_rts Resid (Collect NPath)\"\n      ..\n\n    lemma Cong\\<^sub>0_append_Arr_NPath:\n    assumes \"T \\<noteq> []\" and \"Arr (T @ U)\" and \"NPath U\"\n    shows \"Cong\\<^sub>0 (T @ U) T\"\n      using assms\n      by (metis Arr.simps(1) Arr_appendE\\<^sub>P NPath_implies_Arr append_is_composite_of arrI\\<^sub>P\n          arr_append_imp_seq composite_of_arr_normal mem_Collect_eq)\n\n    lemma Cong_append_NPath_Arr:\n    assumes \"T \\<noteq> []\" and \"Arr (U @ T)\" and \"NPath U\"\n    shows \"U @ T \\<approx>\\<^sup>* T\"\n      using assms\n      by (metis (full_types) Arr.simps(1) Con_Arr_self Con_append(2) Con_implies_Arr(2)\n          Con_imp_eq_Srcs composite_of_normal_arr Srcs_Resid append_is_composite_of arr_char\n          NPath_implies_Arr mem_Collect_eq seq_char)\n\n    subsubsection \"Permutation Congruence\"\n\n    text \\<open>\n      Here we show that \\<open>\\<^sup>*\\<sim>\\<^sup>*\\<close> coincides with ``permutation congruence'':\n      the least congruence respecting composition that relates \\<open>[t, u \\ t]\\<close> and \\<open>[u, t \\ u]\\<close>\n      whenever \\<open>t \\<frown> u\\<close> and that relates \\<open>T @ [b]\\<close> and \\<open>T\\<close> whenever \\<open>b\\<close> is an identity\n      such that \\<open>seq T [b]\\<close>.\n    \\<close>\n\n    inductive PCong\n    where \"Arr T \\<Longrightarrow> PCong T T\"\n        | \"PCong T U \\<Longrightarrow> PCong U T\"\n        | \"\\<lbrakk>PCong T U; PCong U V\\<rbrakk> \\<Longrightarrow> PCong T V\"\n        | \"\\<lbrakk>seq T U; PCong T T'; PCong U U'\\<rbrakk> \\<Longrightarrow> PCong (T @ U) (T' @ U')\"\n        | \"\\<lbrakk>seq T [b]; R.ide b\\<rbrakk> \\<Longrightarrow> PCong (T @ [b]) T\"\n        | \"t \\<frown> u \\<Longrightarrow> PCong [t, u \\\\ t] [u, t \\\\ u]\"\n\n    lemmas PCong.intros(3) [trans]\n\n    lemma PCong_append_Ide:\n    shows \"\\<lbrakk>seq T B; Ide B\\<rbrakk> \\<Longrightarrow> PCong (T @ B) T\"\n    proof (induct B)\n      show \"\\<lbrakk>seq T []; Ide []\\<rbrakk> \\<Longrightarrow> PCong (T @ []) T\"\n        by auto\n      fix b B T\n      assume ind: \"\\<lbrakk>seq T B; Ide B\\<rbrakk> \\<Longrightarrow> PCong (T @ B) T\"\n      assume seq: \"seq T (b # B)\"\n      assume Ide: \"Ide (b # B)\"\n      have \"T @ (b # B) = (T @ [b]) @ B\"\n        by simp\n      also have \"PCong ... (T @ B)\"\n        apply (cases \"B = []\")\n        using Ide PCong.intros(5) seq apply force\n        using seq Ide PCong.intros(4) [of \"T @ [b]\" B T B]\n        by (metis Arr.simps(1) Ide_imp_Ide_hd PCong.intros(1) PCong.intros(5)\n            append_is_Nil_conv arr_append arr_append_imp_seq arr_char calculation\n            list.distinct(1) list.sel(1) seq_char)\n      also have \"PCong (T @ B) T\"\n      proof (cases \"B = []\")\n        show \"B = [] \\<Longrightarrow> ?thesis\"\n          using PCong.intros(1) seq seq_char by force\n        assume B: \"B \\<noteq> []\"\n        have \"seq T B\"\n          using B seq Ide\n          by (metis Con_imp_eq_Srcs Ide_imp_Ide_hd Trgs_append \\<open>T @ b # B = (T @ [b]) @ B\\<close>\n              append_is_Nil_conv arr_append arr_append_imp_seq arr_char cong_cons_ideI(2)\n              list.distinct(1) list.sel(1) not_arr_null null_char seq_char ide_implies_arr)\n        thus ?thesis\n          using seq Ide ind\n          by (metis Arr.simps(1) Ide.elims(3) Ide.simps(3) seq_char)\n      qed\n      finally show \"PCong (T @ (b # B)) T\" by blast\n    qed\n\n    lemma PCong_imp_Cong:\n    shows \"PCong T U \\<Longrightarrow> T \\<^sup>*\\<sim>\\<^sup>* U\"\n    proof (induct rule: PCong.induct)\n      show \"\\<And>T. Arr T \\<Longrightarrow> T \\<^sup>*\\<sim>\\<^sup>* T\"\n        using cong_reflexive by blast\n      show \"\\<And>T U. \\<lbrakk>PCong T U; T \\<^sup>*\\<sim>\\<^sup>* U\\<rbrakk> \\<Longrightarrow> U \\<^sup>*\\<sim>\\<^sup>* T\"\n        by blast\n      show \"\\<And>T U V. \\<lbrakk>PCong T U; T \\<^sup>*\\<sim>\\<^sup>* U; PCong U V; U \\<^sup>*\\<sim>\\<^sup>* V\\<rbrakk> \\<Longrightarrow> T \\<^sup>*\\<sim>\\<^sup>* V\"\n        using cong_transitive by blast\n      show \"\\<And>T U U' T'. \\<lbrakk>seq T U; PCong T T'; T \\<^sup>*\\<sim>\\<^sup>* T'; PCong U U'; U \\<^sup>*\\<sim>\\<^sup>* U'\\<rbrakk>\n                           \\<Longrightarrow> T @ U \\<^sup>*\\<sim>\\<^sup>* T' @ U'\"\n        using cong_append by simp\n      show \"\\<And>T b. \\<lbrakk>seq T [b]; R.ide b\\<rbrakk> \\<Longrightarrow> T @ [b] \\<^sup>*\\<sim>\\<^sup>* T\"\n        using cong_append_ideI(4) ide_char by force\n      show \"\\<And>t u. t \\<frown> u \\<Longrightarrow> [t, u \\\\ t] \\<^sup>*\\<sim>\\<^sup>* [u, t \\\\ u]\"\n      proof -\n        have \"\\<And>t u. t \\<frown> u \\<Longrightarrow> [t, u \\\\ t] \\<^sup>*\\<lesssim>\\<^sup>* [u, t \\\\ u]\"\n        proof -\n          fix t u\n          assume con: \"t \\<frown> u\"\n          have \"([t] @ [u \\\\ t]) \\<^sup>*\\\\\\<^sup>* ([u] @ [t \\\\ u]) =\n                [(t \\\\ u) \\\\ (t \\\\ u), ((u \\\\ t) \\\\ (u \\\\ t)) \\\\ ((t \\\\ u) \\\\ (t \\\\ u))]\"\n            using con Resid_append2 [of \"[t]\" \"[u \\\\ t]\" \"[u]\" \"[t \\\\ u]\"]\n            apply simp\n            by (metis R.arr_resid_iff_con R.con_target R.conE R.con_sym\n                R.prfx_implies_con R.prfx_reflexive R.cube)\n          moreover have \"Ide ...\"\n            using con\n            by (metis Arr.simps(2) Arr.simps(3) Ide.simps(2) Ide.simps(3) R.arr_resid_iff_con\n                R.con_sym R.resid_ide_arr R.prfx_reflexive calculation Con_imp_Arr_Resid)\n          ultimately show\"[t, u \\\\ t] \\<^sup>*\\<lesssim>\\<^sup>* [u, t \\\\ u]\"\n            using ide_char by auto\n        qed\n        thus \"\\<And>t u. t \\<frown> u \\<Longrightarrow> [t, u \\\\ t] \\<^sup>*\\<sim>\\<^sup>* [u, t \\\\ u]\"\n          using R.con_sym by blast\n      qed\n    qed\n\n    lemma PCong_permute_single:\n    shows \"[t] \\<^sup>*\\<frown>\\<^sup>* U \\<Longrightarrow> PCong ([t] @ (U \\<^sup>*\\\\\\<^sup>* [t])) (U @ ([t] \\<^sup>*\\\\\\<^sup>* U))\"\n    proof (induct U arbitrary: t)\n      show \"\\<And>t. [t] \\<^sup>*\\<frown>\\<^sup>* [] \\<Longrightarrow> PCong ([t] @ [] \\<^sup>*\\\\\\<^sup>* [t]) ([] @ [t] \\<^sup>*\\\\\\<^sup>* [])\"\n        by auto\n      fix t u U\n      assume ind: \"\\<And>t. [t] \\<^sup>*\\\\\\<^sup>* U \\<noteq> [] \\<Longrightarrow> PCong ([t] @( U \\<^sup>*\\\\\\<^sup>* [t])) (U @ ([t] \\<^sup>*\\\\\\<^sup>* U))\"\n      assume con: \"[t] \\<^sup>*\\<frown>\\<^sup>* u # U\"\n      show \"PCong ([t] @ (u # U) \\<^sup>*\\\\\\<^sup>* [t]) ((u # U) @ [t] \\<^sup>*\\\\\\<^sup>* (u # U))\"\n      proof (cases \"U = []\")\n        show \"U = [] \\<Longrightarrow> ?thesis\"\n          by (metis PCong.intros(6) Resid.simps(3) append_Cons append_eq_append_conv2\n              append_self_conv con_char con_def con con_sym_ax)\n        assume U: \"U \\<noteq> []\"\n        show \"PCong ([t] @ ((u # U) \\<^sup>*\\\\\\<^sup>* [t])) ((u # U) @ ([t] \\<^sup>*\\\\\\<^sup>* (u # U)))\"\n        proof -\n          have \"[t] @ ((u # U) \\<^sup>*\\\\\\<^sup>* [t]) = [t] @ ([u \\\\ t] @ (U \\<^sup>*\\\\\\<^sup>* [t \\\\ u]))\"\n            using Con_sym Resid_rec(2) U con by auto\n          also have \"... = ([t] @ [u \\\\ t]) @ (U \\<^sup>*\\\\\\<^sup>* [t \\\\ u])\"\n            by auto\n          also have \"PCong ... (([u] @ [t \\\\ u]) @ (U \\<^sup>*\\\\\\<^sup>* [t \\\\ u]))\"\n          proof -\n            have \"PCong ([t] @ [u \\\\ t]) ([u] @ [t \\\\ u])\"\n              using con\n              by (simp add: Con_rec(3) PCong.intros(6) U)  \n            thus ?thesis\n              by (metis Arr_Resid_single Con_implies_Arr(1) Con_rec(2) Con_sym\n                  PCong.intros(1,4) Srcs_Resid U append_is_Nil_conv append_is_composite_of\n                  arr_append_imp_seq arr_char calculation composite_of_unq_upto_cong\n                  con not_arr_null null_char ide_implies_arr seq_char)\n          qed\n          also have \"([u] @ [t \\\\ u]) @ (U \\<^sup>*\\\\\\<^sup>* [t \\\\ u]) = [u] @ ([t \\\\ u] @ (U \\<^sup>*\\\\\\<^sup>* [t \\\\ u]))\"\n            by simp\n          also have \"PCong ... ([u] @ (U @ ([t \\\\ u] \\<^sup>*\\\\\\<^sup>* U)))\"\n          proof -\n            have \"PCong ([t \\\\ u] @ (U \\<^sup>*\\\\\\<^sup>* [t \\\\ u])) (U @ ([t \\\\ u] \\<^sup>*\\\\\\<^sup>* U))\"\n              using ind\n              by (metis Resid_rec(3) U con)\n            moreover have \"seq [u] ([t \\\\ u] @ U \\<^sup>*\\\\\\<^sup>* [t \\\\ u])\"\n            proof\n              show \"Arr [u]\"\n                using Con_implies_Arr(2) Con_initial_right con by blast\n              show \"Arr ([t \\\\ u] @ U \\<^sup>*\\\\\\<^sup>* [t \\\\ u])\"\n                using Con_implies_Arr(1) U con Con_imp_Arr_Resid Con_rec(3) Con_sym\n                by fastforce\n              show \"Trgs [u] \\<inter> Srcs ([t \\\\ u] @ U \\<^sup>*\\\\\\<^sup>* [t \\\\ u]) \\<noteq> {}\"\n                by (metis Arr.simps(1) Arr.simps(2) Arr_has_Trg Con_implies_Arr(1)\n                    Int_absorb R.arr_resid_iff_con R.sources_resid Resid_rec(3)\n                    Srcs.simps(2) Srcs_append Trgs.simps(2) U \\<open>Arr [u]\\<close> con)\n            qed\n            moreover have \"PCong [u] [u]\"\n              using PCong.intros(1) calculation(2) seq_char by force\n            ultimately show ?thesis\n              using U arr_append arr_char con seq_char\n                    PCong.intros(4) [of \"[u]\" \"[t \\\\ u] @ (U \\<^sup>*\\\\\\<^sup>* [t \\\\ u])\"\n                                        \"[u]\" \"U @ ([t \\\\ u] \\<^sup>*\\\\\\<^sup>* U)\"]\n              by blast\n          qed\n          also have \"([u] @ (U @ ([t \\\\ u] \\<^sup>*\\\\\\<^sup>* U))) = ((u # U) @ [t] \\<^sup>*\\\\\\<^sup>* (u # U))\"\n            by (metis Resid_rec(3) U append_Cons append_Nil con)\n          finally show ?thesis by blast\n        qed\n      qed\n    qed\n\n    lemma PCong_permute:\n    shows \"T \\<^sup>*\\<frown>\\<^sup>* U \\<Longrightarrow> PCong (T @ (U \\<^sup>*\\\\\\<^sup>* T)) (U @ (T \\<^sup>*\\\\\\<^sup>* U))\"\n    proof (induct T arbitrary: U)\n      show \"\\<And>U. [] \\<^sup>*\\\\\\<^sup>* U \\<noteq> [] \\<Longrightarrow> PCong ([] @ U \\<^sup>*\\\\\\<^sup>* []) (U @ [] \\<^sup>*\\\\\\<^sup>* U)\"\n         by simp\n      fix t T U\n      assume ind: \"\\<And>U. T \\<^sup>*\\<frown>\\<^sup>* U \\<Longrightarrow> PCong (T @ (U \\<^sup>*\\\\\\<^sup>* T)) (U @ (T \\<^sup>*\\\\\\<^sup>* U))\"\n      assume con: \"t # T \\<^sup>*\\<frown>\\<^sup>* U\"\n      show \"PCong ((t # T) @ (U \\<^sup>*\\\\\\<^sup>* (t # T))) (U @ ((t # T) \\<^sup>*\\\\\\<^sup>* U))\"\n      proof (cases \"T = []\")\n        assume T: \"T = []\"\n        have \"(t # T) @ (U \\<^sup>*\\\\\\<^sup>* (t # T)) = [t] @ (U \\<^sup>*\\\\\\<^sup>* [t])\"\n          using con T by simp\n        also have \"PCong ... (U @ ([t] \\<^sup>*\\\\\\<^sup>* U))\"\n          using PCong_permute_single T con by blast\n        finally show ?thesis\n          using T by fastforce\n        next\n        assume T: \"T \\<noteq> []\"\n        have \"(t # T) @ (U \\<^sup>*\\\\\\<^sup>* (t # T)) = [t] @ (T @ (U \\<^sup>*\\\\\\<^sup>* (t # T)))\"\n          by simp\n        also have \"PCong ... ([t] @ (U \\<^sup>*\\\\\\<^sup>* [t]) @ (T \\<^sup>*\\\\\\<^sup>* (U \\<^sup>*\\\\\\<^sup>* [t])))\"\n          using ind [of \"U \\<^sup>*\\\\\\<^sup>* [t]\"]\n          by (metis Arr.simps(1) Con_imp_Arr_Resid Con_implies_Arr(2) Con_sym\n              PCong.intros(1,4) Resid_cons(2) Srcs_Resid T arr_append arr_append_imp_seq\n              calculation con not_arr_null null_char seq_char)\n        also have \"[t] @ (U \\<^sup>*\\\\\\<^sup>* [t]) @ (T \\<^sup>*\\\\\\<^sup>* (U \\<^sup>*\\\\\\<^sup>* [t])) =\n                   ([t] @ (U \\<^sup>*\\\\\\<^sup>* [t])) @ (T \\<^sup>*\\\\\\<^sup>* (U \\<^sup>*\\\\\\<^sup>* [t]))\"\n          by simp\n        also have \"PCong (([t] @ (U \\<^sup>*\\\\\\<^sup>* [t])) @ (T \\<^sup>*\\\\\\<^sup>* (U \\<^sup>*\\\\\\<^sup>* [t])))\n                         ((U @ ([t] \\<^sup>*\\\\\\<^sup>* U)) @ (T \\<^sup>*\\\\\\<^sup>* (U \\<^sup>*\\\\\\<^sup>* [t])))\"\n          by (metis Arr.simps(1) Con_cons(1) Con_imp_Arr_Resid Con_implies_Arr(2)\n              PCong.intros(1,4) PCong_permute_single Srcs_Resid T Trgs_append arr_append\n              arr_char con seq_char)\n        also have \"(U @ ([t] \\<^sup>*\\\\\\<^sup>* U)) @ (T \\<^sup>*\\\\\\<^sup>* (U \\<^sup>*\\\\\\<^sup>* [t])) = U @ ((t # T) \\<^sup>*\\\\\\<^sup>* U)\"\n          by (metis Resid.simps(2) Resid_cons(1) append.assoc con)\n        finally show ?thesis by blast\n      qed\n    qed\n\n    lemma Cong_imp_PCong:\n    assumes \"T \\<^sup>*\\<sim>\\<^sup>* U\"\n    shows \"PCong T U\"\n    proof -\n      have \"PCong T (T @ (U \\<^sup>*\\\\\\<^sup>* T))\"\n        using assms PCong.intros(2) PCong_append_Ide\n        by (metis Con_implies_Arr(1) Ide.simps(1) Srcs_Resid ide_char Con_imp_Arr_Resid\n            seq_char)\n      also have \"PCong (T @ (U \\<^sup>*\\\\\\<^sup>* T)) (U @ (T \\<^sup>*\\\\\\<^sup>* U))\"\n        using PCong_permute assms con_char prfx_implies_con by presburger\n      also have \"PCong (U @ (T \\<^sup>*\\\\\\<^sup>* U)) U\"\n        using assms PCong_append_Ide\n        by (metis Con_imp_Arr_Resid Con_implies_Arr(1) Srcs_Resid arr_resid_iff_con\n            ide_implies_arr con_char ide_char seq_char)\n      finally show ?thesis by blast\n    qed\n\n    lemma Cong_iff_PCong:\n    shows \"T \\<^sup>*\\<sim>\\<^sup>* U \\<longleftrightarrow> PCong T U\"\n      using PCong_imp_Cong Cong_imp_PCong by blast\n\n  end\n\n  section \"Composite Completion\"\n\n  text \\<open>\n    The RTS of paths in an RTS factors via the coherent normal sub-RTS of identity\n    paths into an extensional RTS with composites, which can be regarded as a\n    ``composite completion'' of the original RTS.\n  \\<close>\n\n  locale composite_completion =\n    R: rts\n  begin\n\n    interpretation N: coherent_normal_sub_rts resid \\<open>Collect R.ide\\<close>\n      using R.rts_axioms R.identities_form_coherent_normal_sub_rts by auto\n    sublocale P: paths_in_rts_with_coherent_normal resid \\<open>Collect R.ide\\<close> ..\n    sublocale quotient_by_coherent_normal P.Resid \\<open>Collect P.NPath\\<close> ..\n\n    notation P.Resid  (infix \"\\<^sup>*\\\\\\<^sup>*\" 70)\n    notation P.Con    (infix \"\\<^sup>*\\<frown>\\<^sup>*\" 50)\n    notation P.Cong   (infix \"\\<^sup>*\\<approx>\\<^sup>*\" 50)\n    notation P.Cong\\<^sub>0  (infix \"\\<^sup>*\\<approx>\\<^sub>0\\<^sup>*\" 50)\n    notation P.Cong_class (\"\\<lbrace>_\\<rbrace>\")\n\n    notation Resid    (infix \"\\<lbrace>\\<^sup>*\\\\\\<^sup>*\\<rbrace>\" 70)\n    notation con      (infix \"\\<lbrace>\\<^sup>*\\<frown>\\<^sup>*\\<rbrace>\" 50)\n    notation prfx     (infix \"\\<lbrace>\\<^sup>*\\<lesssim>\\<^sup>*\\<rbrace>\" 50)\n\n    lemma NPath_char:\n    shows \"P.NPath T \\<longleftrightarrow> P.Ide T\"\n      using P.NPath_def P.Ide_implies_NPath by blast\n\n    lemma Cong_eq_Cong\\<^sub>0:\n    shows \"T \\<^sup>*\\<approx>\\<^sup>* T' \\<longleftrightarrow> T \\<^sup>*\\<approx>\\<^sub>0\\<^sup>* T'\"\n      by (metis P.Cong_iff_cong P.ide_char P.ide_closed CollectD Collect_cong\n          NPath_char)\n\n    lemma Srcs_respects_Cong:\n    assumes \"T \\<^sup>*\\<approx>\\<^sup>* T'\"\n    shows \"P.Srcs T = P.Srcs T'\"\n      using assms\n      by (meson P.Con_imp_eq_Srcs P.Cong\\<^sub>0_imp_con P.con_char Cong_eq_Cong\\<^sub>0)\n\n    lemma sources_respects_Cong:\n    assumes \"T \\<^sup>*\\<approx>\\<^sup>* T'\"\n    shows \"P.sources T = P.sources T'\"\n      using assms\n      by (meson P.Cong\\<^sub>0_imp_coinitial Cong_eq_Cong\\<^sub>0)\n\n    lemma Trgs_respects_Cong:\n    assumes \"T \\<^sup>*\\<approx>\\<^sup>* T'\"\n    shows \"P.Trgs T = P.Trgs T'\"\n    proof -\n      have \"P.Trgs T = P.Trgs (T @ (T' \\<^sup>*\\\\\\<^sup>* T))\"\n        using assms NPath_char P.Arr.simps(1) P.Con_imp_Arr_Resid\n              P.Con_sym P.Cong_def P.Con_Arr_self\n              P.Con_implies_Arr(2) P.Resid_Ide(1) P.Srcs_Resid P.Trgs_append\n        by (metis P.Cong\\<^sub>0_imp_con P.con_char CollectD)\n      also have \"... = P.Trgs (T' @ (T \\<^sup>*\\\\\\<^sup>* T'))\"\n        using P.Cong\\<^sub>0_imp_con P.con_char Cong_eq_Cong\\<^sub>0 assms by force\n      also have \"... = P.Trgs T'\"\n        using assms NPath_char P.Arr.simps(1) P.Con_imp_Arr_Resid\n              P.Con_sym P.Cong_def P.Con_Arr_self\n              P.Con_implies_Arr(2) P.Resid_Ide(1) P.Srcs_Resid P.Trgs_append\n        by (metis P.Cong\\<^sub>0_imp_con P.con_char CollectD)\n      finally show ?thesis by blast\n    qed\n\n    lemma targets_respects_Cong:\n    assumes \"T \\<^sup>*\\<approx>\\<^sup>* T'\"\n    shows \"P.targets T = P.targets T'\"\n      using assms P.Cong_imp_arr(1) P.Cong_imp_arr(2) P.arr_iff_has_target\n            P.targets_char\\<^sub>P Trgs_respects_Cong\n      by force\n\n    lemma ide_char\\<^sub>C\\<^sub>C:\n    shows \"ide \\<T> \\<longleftrightarrow> arr \\<T> \\<and> (\\<forall>T. T \\<in> \\<T> \\<longrightarrow> P.Ide T)\"\n      using NPath_char ide_char' by force\n\n    lemma con_char\\<^sub>C\\<^sub>C:\n    shows \"\\<T> \\<lbrace>\\<^sup>*\\<frown>\\<^sup>*\\<rbrace> \\<U> \\<longleftrightarrow> arr \\<T> \\<and> arr \\<U> \\<and> P.Cong_class_rep \\<T> \\<^sup>*\\<frown>\\<^sup>* P.Cong_class_rep \\<U>\"\n    proof\n      show \"arr \\<T> \\<and> arr \\<U> \\<and> P.Cong_class_rep \\<T> \\<^sup>*\\<frown>\\<^sup>* P.Cong_class_rep \\<U> \\<Longrightarrow> \\<T> \\<lbrace>\\<^sup>*\\<frown>\\<^sup>*\\<rbrace> \\<U>\"\n        using arr_char P.con_char\n        by (meson P.rep_in_Cong_class con_char\\<^sub>Q\\<^sub>C\\<^sub>N)\n      show \"\\<T> \\<lbrace>\\<^sup>*\\<frown>\\<^sup>*\\<rbrace> \\<U> \\<Longrightarrow> arr \\<T> \\<and> arr \\<U> \\<and> P.Cong_class_rep \\<T> \\<^sup>*\\<frown>\\<^sup>* P.Cong_class_rep \\<U>\"\n      proof -\n        assume con: \"\\<T> \\<lbrace>\\<^sup>*\\<frown>\\<^sup>*\\<rbrace> \\<U>\"\n        have 1: \"arr \\<T> \\<and> arr \\<U>\"\n          using con coinitial_iff con_imp_coinitial by blast\n        moreover have \"P.Cong_class_rep \\<T> \\<^sup>*\\<frown>\\<^sup>* P.Cong_class_rep \\<U>\"\n        proof -\n          obtain T U where TU: \"T \\<in> \\<T> \\<and> U \\<in> \\<U> \\<and> P.Con T U\"\n            using con Resid_def\n            by (meson P.con_char con_char\\<^sub>Q\\<^sub>C\\<^sub>N)\n          have \"T \\<^sup>*\\<approx>\\<^sup>* P.Cong_class_rep \\<T> \\<and> U \\<^sup>*\\<approx>\\<^sup>* P.Cong_class_rep \\<U>\"\n            using TU 1 by (meson P.Cong_class_memb_Cong_rep arr_char)\n          thus ?thesis\n            using TU P.Cong_subst(1) [of T \"P.Cong_class_rep \\<T>\" U \"P.Cong_class_rep \\<U>\"]\n            by (metis P.coinitial_iff P.con_char P.con_imp_coinitial sources_respects_Cong)\n        qed\n        ultimately show ?thesis by simp\n      qed\n    qed\n\n    lemma con_char\\<^sub>C\\<^sub>C':\n    shows \"\\<T> \\<lbrace>\\<^sup>*\\<frown>\\<^sup>*\\<rbrace> \\<U> \\<longleftrightarrow> arr \\<T> \\<and> arr \\<U> \\<and> (\\<forall>T U. T \\<in> \\<T> \\<and> U \\<in> \\<U> \\<longrightarrow> T \\<^sup>*\\<frown>\\<^sup>* U)\"\n    proof\n      show \"arr \\<T> \\<and> arr \\<U> \\<and> (\\<forall>T U. T \\<in> \\<T> \\<and> U \\<in> \\<U> \\<longrightarrow> T \\<^sup>*\\<frown>\\<^sup>* U) \\<Longrightarrow> \\<T> \\<lbrace>\\<^sup>*\\<frown>\\<^sup>*\\<rbrace> \\<U>\"\n        using con_char\\<^sub>C\\<^sub>C\n        by (simp add: P.rep_in_Cong_class arr_char)\n      show \"\\<T> \\<lbrace>\\<^sup>*\\<frown>\\<^sup>*\\<rbrace> \\<U> \\<Longrightarrow> arr \\<T> \\<and> arr \\<U> \\<and> (\\<forall>T U. T \\<in> \\<T> \\<and> U \\<in> \\<U> \\<longrightarrow> T \\<^sup>*\\<frown>\\<^sup>* U)\"\n      proof (intro conjI allI impI)\n        assume 1: \"\\<T> \\<lbrace>\\<^sup>*\\<frown>\\<^sup>*\\<rbrace> \\<U>\"\n        show \"arr \\<T>\"\n          using 1 con_implies_arr by simp\n        show \"arr \\<U>\"\n          using 1 con_implies_arr by simp\n        fix T U\n        assume 2: \"T \\<in> \\<T> \\<and> U \\<in> \\<U>\"\n        show \"T \\<^sup>*\\<frown>\\<^sup>* U\"\n          using 1 2 P.Cong_class_memb_Cong_rep\n          by (meson P.Cong\\<^sub>0_subst_Con P.con_char Cong_eq_Cong\\<^sub>0 arr_char con_char\\<^sub>C\\<^sub>C)\n      qed\n    qed\n\n    lemma resid_char:\n    shows \"\\<T> \\<lbrace>\\<^sup>*\\\\\\<^sup>*\\<rbrace> \\<U> =\n           (if \\<T> \\<lbrace>\\<^sup>*\\<frown>\\<^sup>*\\<rbrace> \\<U> then \\<lbrace>P.Cong_class_rep \\<T> \\<^sup>*\\\\\\<^sup>* P.Cong_class_rep \\<U>\\<rbrace> else {})\"\n      by (metis P.con_char P.rep_in_Cong_class Resid_by_members arr_char arr_resid_iff_con\n          con_char\\<^sub>C\\<^sub>C is_Cong_class_Resid)\n\n    lemma src_char':\n    shows \"src \\<T> = {A. arr \\<T> \\<and> P.Ide A \\<and> P.Srcs (P.Cong_class_rep \\<T>) = P.Srcs A}\"\n    proof (cases \"arr \\<T>\")\n      show \"\\<not> arr \\<T> \\<Longrightarrow> ?thesis\"\n        by (simp add: null_char src_def)\n      assume \\<T>: \"arr \\<T>\"\n      have 1: \"\\<exists>A. P.Ide A \\<and> P.Srcs (P.Cong_class_rep \\<T>) = P.Srcs A\"\n        by (metis P.Arr.simps(1) P.Con_imp_eq_Srcs P.Cong\\<^sub>0_imp_con\n            P.Cong_class_memb_Cong_rep P.Cong_def P.con_char P.rep_in_Cong_class\n            CollectD \\<T> NPath_char P.Con_implies_Arr(1) arr_char)\n      let ?A = \"SOME A. P.Ide A \\<and> P.Srcs (P.Cong_class_rep \\<T>) = P.Srcs A\"\n      have A: \"P.Ide ?A \\<and> P.Srcs (P.Cong_class_rep \\<T>) = P.Srcs ?A\"\n        using 1 someI_ex [of \"\\<lambda>A. P.Ide A \\<and> P.Srcs (P.Cong_class_rep \\<T>) = P.Srcs A\"] by simp\n      have a: \"arr \\<lbrace>?A\\<rbrace>\"\n        using A P.ide_char P.is_Cong_classI arr_char by blast\n      have ide_a: \"ide \\<lbrace>?A\\<rbrace>\"\n        using a A P.Cong_class_def P.normal_is_Cong_closed NPath_char ide_char\\<^sub>C\\<^sub>C by auto\n      have \"sources \\<T> = {\\<lbrace>?A\\<rbrace>}\"\n      proof -\n        have \"\\<T> \\<lbrace>\\<^sup>*\\<frown>\\<^sup>*\\<rbrace> \\<lbrace>?A\\<rbrace>\"\n          by (metis (no_types, lifting) A P.Con_Ide_iff P.Cong_class_memb_Cong_rep\n              P.Cong_imp_arr(1) P.arr_char P.arr_in_Cong_class P.ide_char\n              P.ide_implies_arr P.rep_in_Cong_class Con_char a \\<T> P.con_char\n              null_char arr_char P.con_sym conI)\n        hence \"\\<lbrace>?A\\<rbrace> \\<in> sources \\<T>\"\n          using ide_a in_sourcesI by simp\n        thus ?thesis\n          using sources_char by auto\n      qed\n      moreover have \"\\<lbrace>?A\\<rbrace> = {A. P.Ide A \\<and> P.Srcs (P.Cong_class_rep \\<T>) = P.Srcs A}\"\n      proof\n        show \"{A. P.Ide A \\<and> P.Srcs (P.Cong_class_rep \\<T>) = P.Srcs A} \\<subseteq> \\<lbrace>?A\\<rbrace>\"\n          using A P.Cong_class_def P.Cong_closure_props(3) P.Ide_implies_Arr\n                P.ide_closed P.ide_char\n          by fastforce\n        show \"\\<lbrace>?A\\<rbrace> \\<subseteq> {A. P.Ide A \\<and> P.Srcs (P.Cong_class_rep \\<T>) = P.Srcs A}\"\n          using a A P.Cong_class_def Srcs_respects_Cong ide_a ide_char\\<^sub>C\\<^sub>C by blast\n      qed\n      ultimately show ?thesis\n        using \\<T> src_in_sources by force\n    qed\n\n    lemma src_char:\n    shows \"src \\<T> = {A. arr \\<T> \\<and> P.Ide A \\<and> (\\<forall>T. T \\<in> \\<T> \\<longrightarrow> P.Srcs T = P.Srcs A)}\"\n    proof (cases \"arr \\<T>\")\n      show \"\\<not> arr \\<T> \\<Longrightarrow> ?thesis\"\n        by (simp add: null_char src_def)\n      assume \\<T>: \"arr \\<T>\"\n      have \"\\<And>T. T \\<in> \\<T> \\<Longrightarrow> P.Srcs T = P.Srcs (P.Cong_class_rep \\<T>)\"\n        using \\<T> P.Cong_class_memb_Cong_rep Srcs_respects_Cong arr_char by auto\n      thus ?thesis\n        using \\<T> src_char' P.is_Cong_class_def arr_char by force\n    qed\n\n    lemma trg_char':\n    shows \"trg \\<T> = {B. arr \\<T> \\<and> P.Ide B \\<and> P.Trgs (P.Cong_class_rep \\<T>) = P.Srcs B}\"\n    proof (cases \"arr \\<T>\")\n      show \"\\<not> arr \\<T> \\<Longrightarrow> ?thesis\"\n        by (metis (no_types, lifting) Collect_empty_eq arrI resid_arr_self resid_char)\n      assume \\<T>: \"arr \\<T>\"\n      have 1: \"\\<exists>B. P.Ide B \\<and> P.Trgs (P.Cong_class_rep \\<T>) = P.Srcs B\"\n        by (metis P.Con_implies_Arr(2) P.Resid_Arr_self P.Srcs_Resid \\<T> con_char\\<^sub>C\\<^sub>C arrE)\n      define B where \"B = (SOME B. P.Ide B \\<and> P.Trgs (P.Cong_class_rep \\<T>) = P.Srcs B)\"\n      have B: \"P.Ide B \\<and> P.Trgs (P.Cong_class_rep \\<T>) = P.Srcs B\"\n        unfolding B_def\n        using 1 someI_ex [of \"\\<lambda>B. P.Ide B \\<and> P.Trgs (P.Cong_class_rep \\<T>) = P.Srcs B\"] by simp\n      hence 2: \"P.Ide B \\<and> P.Con (P.Resid (P.Cong_class_rep \\<T>) (P.Cong_class_rep \\<T>)) B\"\n        using \\<T>\n        by (metis (no_types, lifting) P.Con_Ide_iff P.Ide_implies_Arr P.Resid_Arr_self\n            P.Srcs_Resid arrE P.Con_implies_Arr(2) con_char\\<^sub>C\\<^sub>C)\n      have b: \"arr \\<lbrace>B\\<rbrace>\"\n        by (simp add: \"2\" P.ide_char P.is_Cong_classI arr_char)\n      have ide_b: \"ide \\<lbrace>B\\<rbrace>\"\n        by (meson \"2\" P.arr_in_Cong_class P.ide_char P.ide_closed\n            b disjoint_iff ide_char P.ide_implies_arr)\n      have \"targets \\<T> = {\\<lbrace>B\\<rbrace>}\"\n      proof -\n        have \"cong (\\<T> \\<lbrace>\\<^sup>*\\\\\\<^sup>*\\<rbrace> \\<T>) \\<lbrace>B\\<rbrace>\"\n        proof -\n          have \"\\<T> \\<lbrace>\\<^sup>*\\\\\\<^sup>*\\<rbrace> \\<T> = \\<lbrace>B\\<rbrace>\"\n            by (metis (no_types, lifting) \"2\" P.Cong_class_eqI P.Cong_closure_props(3)\n                P.Resid_Arr_Ide_ind P.Resid_Ide(1) NPath_char \\<T> con_char\\<^sub>C\\<^sub>C resid_char\n                P.Con_implies_Arr(2) P.Resid_Arr_self mem_Collect_eq)\n          thus ?thesis\n            using b cong_reflexive by presburger\n        qed\n        thus ?thesis\n          using \\<T> targets_char\\<^sub>Q\\<^sub>C\\<^sub>N [of \\<T>] cong_char by auto\n      qed \n      moreover have \"\\<lbrace>B\\<rbrace> = {B. P.Ide B \\<and> P.Trgs (P.Cong_class_rep \\<T>) = P.Srcs B}\"\n      proof\n        show \"{B. P.Ide B \\<and> P.Trgs (P.Cong_class_rep \\<T>) = P.Srcs B} \\<subseteq> \\<lbrace>B\\<rbrace>\"\n          using B P.Cong_class_def P.Cong_closure_props(3) P.Ide_implies_Arr\n                P.ide_closed P.ide_char\n          by force\n        show \"\\<lbrace>B\\<rbrace> \\<subseteq> {B. P.Ide B \\<and> P.Trgs (P.Cong_class_rep \\<T>) = P.Srcs B}\"\n        proof -\n          have \"\\<And>B'. P.Cong B' B \\<Longrightarrow> P.Ide B' \\<and> P.Trgs (P.Cong_class_rep \\<T>) = P.Srcs B'\"\n            using B NPath_char P.normal_is_Cong_closed Srcs_respects_Cong\n            by (metis P.Cong_closure_props(1) mem_Collect_eq)\n          thus ?thesis\n            using P.Cong_class_def by blast\n        qed\n      qed\n      ultimately show ?thesis\n        using \\<T> trg_in_targets by force\n    qed\n\n    lemma trg_char:\n    shows \"trg \\<T> = {B. arr \\<T> \\<and> P.Ide B \\<and> (\\<forall>T. T \\<in> \\<T> \\<longrightarrow> P.Trgs T = P.Srcs B)}\"\n    proof (cases \"arr \\<T>\")\n      show \"\\<not> arr \\<T> \\<Longrightarrow> ?thesis\"\n        using trg_char' by presburger\n      assume \\<T>: \"arr \\<T>\"\n      have \"\\<And>T. T \\<in> \\<T> \\<Longrightarrow> P.Trgs T = P.Trgs (P.Cong_class_rep \\<T>)\"\n        using \\<T>\n        by (metis P.Cong_class_memb_Cong_rep Trgs_respects_Cong arr_char)\n      thus ?thesis\n        using \\<T> trg_char' P.is_Cong_class_def arr_char by force\n    qed\n\n    lemma is_extensional_rts_with_composites:\n    shows \"extensional_rts_with_composites Resid\"\n    proof\n      fix \\<T> \\<U>\n      assume seq: \"seq \\<T> \\<U>\"\n      obtain T where T: \"\\<T> = \\<lbrace>T\\<rbrace>\"\n        using seq P.Cong_class_rep arr_char seq_def by blast\n      obtain U where U: \"\\<U> = \\<lbrace>U\\<rbrace>\"\n        using seq P.Cong_class_rep arr_char seq_def by blast\n      have 1: \"P.Arr T \\<and> P.Arr U\"\n        using seq T U P.Con_implies_Arr(2) P.Cong\\<^sub>0_subst_right(1) P.Cong_class_def\n              P.con_char seq_def\n        by (metis Collect_empty_eq P.Cong_imp_arr(1) P.arr_char P.rep_in_Cong_class\n            empty_iff arr_char)\n      have 2: \"P.Trgs T = P.Srcs U\"\n      proof -\n        have \"targets \\<T> = sources \\<U>\"\n          using seq seq_def sources_char targets_char\\<^sub>W\\<^sub>E by force\n        hence 3: \"trg \\<T> = src \\<U>\"\n          using seq arr_has_un_source arr_has_un_target\n          by (metis seq_def src_in_sources trg_in_targets)\n        hence \"{B. P.Ide B \\<and> P.Trgs (P.Cong_class_rep \\<T>) = P.Srcs B} =\n               {A. P.Ide A \\<and> P.Srcs (P.Cong_class_rep \\<U>) = P.Srcs A}\"\n          using seq seq_def src_char' [of \\<U>] trg_char' [of \\<T>] by force\n        hence \"P.Trgs (P.Cong_class_rep \\<T>) = P.Srcs (P.Cong_class_rep \\<U>)\"\n          using seq seq_def arr_char\n          by (metis (mono_tags, lifting) \"3\" P.Cong_class_is_nonempty Collect_empty_eq\n              arr_src_iff_arr mem_Collect_eq trg_char')\n        thus ?thesis\n          using seq seq_def arr_char T U P.Srcs_respects_Cong P.Trgs_respects_Cong\n                P.Cong_class_memb_Cong_rep P.Cong_symmetric\n          by (metis \"1\" P.arr_char P.arr_in_Cong_class Srcs_respects_Cong Trgs_respects_Cong)\n      qed\n      have \"P.Arr (T @ U)\"\n        using 1 2 by simp\n      moreover have \"P.Ide (T \\<^sup>*\\\\\\<^sup>* (T @ U))\"\n        by (metis \"1\" P.Con_append(2) P.Con_sym P.Resid_Arr_self P.Resid_Ide_Arr_ind\n            P.Resid_append(2) P.Trgs.simps(1) calculation P.Arr_has_Trg)\n      moreover have \"(T @ U) \\<^sup>*\\\\\\<^sup>* T \\<^sup>*\\<approx>\\<^sup>* U\"\n        by (metis \"1\" P.Arr.simps(1) P.Con_sym P.Cong\\<^sub>0_append_resid_NPath P.Cong\\<^sub>0_cancel_left\\<^sub>C\\<^sub>S\n            P.Ide.simps(1) calculation(2) Cong_eq_Cong\\<^sub>0 NPath_char)\n      ultimately have \"composite_of \\<T> \\<U> \\<lbrace>T @ U\\<rbrace>\"\n      proof (unfold composite_of_def, intro conjI)\n        show \"prfx \\<T> (P.Cong_class (T @ U))\"\n        proof -\n          have \"ide (\\<T> \\<lbrace>\\<^sup>*\\\\\\<^sup>*\\<rbrace> \\<lbrace>T @ U\\<rbrace>)\"\n          proof (unfold ide_char, intro conjI)\n            have 3: \"T \\<^sup>*\\\\\\<^sup>* (T @ U) \\<in> \\<T> \\<lbrace>\\<^sup>*\\\\\\<^sup>*\\<rbrace> \\<lbrace>T @ U\\<rbrace>\"\n            proof -\n              have \"\\<T> \\<lbrace>\\<^sup>*\\\\\\<^sup>*\\<rbrace> \\<lbrace>T @ U\\<rbrace> = \\<lbrace>T \\<^sup>*\\\\\\<^sup>* (T @ U)\\<rbrace>\"\n                by (metis \"1\" P.Ide.simps(1) P.arr_char P.arr_in_Cong_class P.con_char\n                    P.is_Cong_classI Resid_by_members T \\<open>P.Arr (T @ U)\\<close>\n                    \\<open>P.Ide (T \\<^sup>*\\\\<^sup>* (T @ U))\\<close>)\n              thus ?thesis\n                by (simp add: P.arr_in_Cong_class P.elements_are_arr NPath_char\n                              \\<open>P.Ide (T \\<^sup>*\\\\<^sup>* (T @ U))\\<close>)\n            qed\n            show \"arr (\\<T> \\<lbrace>\\<^sup>*\\\\\\<^sup>*\\<rbrace> \\<lbrace>T @ U\\<rbrace>)\"\n              using 3 arr_char is_Cong_class_Resid by blast\n            show \"\\<T> \\<lbrace>\\<^sup>*\\\\\\<^sup>*\\<rbrace> \\<lbrace>T @ U\\<rbrace> \\<inter> Collect P.NPath \\<noteq> {}\"\n              using 3 P.ide_closed P.ide_char \\<open>P.Ide (T \\<^sup>*\\\\<^sup>* (T @ U))\\<close> by blast\n          qed\n          thus ?thesis by blast\n        qed\n        show \"\\<lbrace>T @ U\\<rbrace> \\<lbrace>\\<^sup>*\\\\\\<^sup>*\\<rbrace> \\<T> \\<lbrace>\\<^sup>*\\<lesssim>\\<^sup>*\\<rbrace> \\<U>\"\n        proof -\n          have 3: \"((T @ U) \\<^sup>*\\\\\\<^sup>* T) \\<^sup>*\\\\\\<^sup>* U \\<in> (\\<lbrace>T @ U\\<rbrace> \\<lbrace>\\<^sup>*\\\\\\<^sup>*\\<rbrace> \\<T>) \\<lbrace>\\<^sup>*\\\\\\<^sup>*\\<rbrace> \\<U>\"\n          proof -\n            have \"(\\<lbrace>T @ U\\<rbrace> \\<lbrace>\\<^sup>*\\\\\\<^sup>*\\<rbrace> \\<T>) \\<lbrace>\\<^sup>*\\\\\\<^sup>*\\<rbrace> \\<U> = \\<lbrace>((T @ U) \\<^sup>*\\\\\\<^sup>* T) \\<^sup>*\\\\\\<^sup>* U\\<rbrace>\"\n            proof -\n              have \"\\<lbrace>T @ U\\<rbrace> \\<lbrace>\\<^sup>*\\\\\\<^sup>*\\<rbrace> \\<T> = \\<lbrace>(T @ U) \\<^sup>*\\\\\\<^sup>* T\\<rbrace>\"\n                by (metis \"1\" P.Cong_imp_arr(1) P.arr_char P.arr_in_Cong_class\n                    P.is_Cong_classI T \\<open>P.Arr (T @ U)\\<close> \\<open>(T @ U) \\<^sup>*\\\\<^sup>* T \\<^sup>*\\<approx>\\<^sup>* U\\<close>\n                    Resid_by_members P.arr_resid_iff_con)\n              moreover\n              have \"\\<lbrace>(T @ U) \\<^sup>*\\\\\\<^sup>* T\\<rbrace> \\<lbrace>\\<^sup>*\\\\\\<^sup>*\\<rbrace> \\<U> = \\<lbrace>((T @ U) \\<^sup>*\\\\\\<^sup>* T) \\<^sup>*\\\\\\<^sup>* U\\<rbrace>\"\n                by (metis \"1\" P.Cong_class_eqI P.Cong_imp_arr(1) P.arr_char\n                    P.arr_in_Cong_class P.con_char P.is_Cong_classI arr_char arrE U\n                    \\<open>(T @ U) \\<^sup>*\\\\<^sup>* T \\<^sup>*\\<approx>\\<^sup>* U\\<close> con_char\\<^sub>C\\<^sub>C' Resid_by_members)\n              ultimately show ?thesis by auto\n            qed\n            thus ?thesis\n              by (metis \"1\" P.Arr.simps(1) P.Cong\\<^sub>0_reflexive P.Resid_append(2) P.arr_char\n                        P.arr_in_Cong_class P.elements_are_arr \\<open>P.Arr (T @ U)\\<close>)\n          qed\n          have \"\\<lbrace>T @ U\\<rbrace> \\<lbrace>\\<^sup>*\\\\\\<^sup>*\\<rbrace> \\<T> \\<lbrace>\\<^sup>*\\<lesssim>\\<^sup>*\\<rbrace> \\<U>\"\n          proof (unfold ide_char, intro conjI)\n            show \"arr ((\\<lbrace>T @ U\\<rbrace> \\<lbrace>\\<^sup>*\\\\\\<^sup>*\\<rbrace> \\<T>) \\<lbrace>\\<^sup>*\\\\\\<^sup>*\\<rbrace> \\<U>)\"\n              using 3 arr_char is_Cong_class_Resid by blast\n            show \"(\\<lbrace>T @ U\\<rbrace> \\<lbrace>\\<^sup>*\\\\\\<^sup>*\\<rbrace> \\<T>) \\<lbrace>\\<^sup>*\\\\\\<^sup>*\\<rbrace> \\<U> \\<inter> Collect P.NPath \\<noteq> {}\"\n              by (metis 1 3 P.Arr.simps(1) P.Resid_append(2) P.con_char\n                  IntI \\<open>P.Arr (T @ U)\\<close> NPath_char P.Resid_Arr_self P.arr_char empty_iff\n                  mem_Collect_eq P.arrE)\n          qed\n          thus ?thesis by blast\n        qed\n        show \"\\<U> \\<lbrace>\\<^sup>*\\<lesssim>\\<^sup>*\\<rbrace> \\<lbrace>T @ U\\<rbrace> \\<lbrace>\\<^sup>*\\\\\\<^sup>*\\<rbrace> \\<T>\"\n        proof (unfold ide_char, intro conjI)\n          have 3: \"U \\<^sup>*\\\\\\<^sup>* ((T @ U) \\<^sup>*\\\\\\<^sup>* T) \\<in> \\<U> \\<lbrace>\\<^sup>*\\\\\\<^sup>*\\<rbrace> (\\<lbrace>T @ U\\<rbrace> \\<lbrace>\\<^sup>*\\\\\\<^sup>*\\<rbrace> \\<T>)\"\n          proof -\n            have \"\\<U> \\<lbrace>\\<^sup>*\\\\\\<^sup>*\\<rbrace> (\\<lbrace>T @ U\\<rbrace> \\<lbrace>\\<^sup>*\\\\\\<^sup>*\\<rbrace> \\<T>) = \\<lbrace>U \\<^sup>*\\\\\\<^sup>* ((T @ U) \\<^sup>*\\\\\\<^sup>* T)\\<rbrace>\"\n            proof -\n              have \"\\<lbrace>T @ U\\<rbrace> \\<lbrace>\\<^sup>*\\\\\\<^sup>*\\<rbrace> \\<T> = \\<lbrace>(T @ U) \\<^sup>*\\\\\\<^sup>* T\\<rbrace>\"\n                by (metis \"1\" P.Con_sym P.Ide.simps(1) P.arr_char P.arr_in_Cong_class\n                    P.con_char P.is_Cong_classI Resid_by_members T \\<open>P.Arr (T @ U)\\<close>\n                    \\<open>P.Ide (T \\<^sup>*\\\\<^sup>* (T @ U))\\<close>)\n              moreover have \"\\<U> \\<lbrace>\\<^sup>*\\\\\\<^sup>*\\<rbrace> (\\<lbrace>T @ U\\<rbrace> \\<lbrace>\\<^sup>*\\\\\\<^sup>*\\<rbrace> \\<T>) = \\<lbrace>U \\<^sup>*\\\\\\<^sup>* ((T @ U) \\<^sup>*\\\\\\<^sup>* T)\\<rbrace>\"\n                by (metis \"1\" P.Cong_class_eqI P.Cong_imp_arr(1) P.arr_char\n                    P.arr_in_Cong_class P.con_char P.is_Cong_classI prfx_implies_con\n                    U \\<open>(T @ U) \\<^sup>*\\\\<^sup>* T \\<^sup>*\\<approx>\\<^sup>* U\\<close> \\<open>\\<lbrace>T @ U\\<rbrace> \\<lbrace>\\<^sup>*\\\\<^sup>*\\<rbrace> \\<T> \\<lbrace>\\<^sup>*\\<lesssim>\\<^sup>*\\<rbrace> \\<U>\\<close>\n                    calculation con_char\\<^sub>C\\<^sub>C' Resid_by_members)\n              ultimately show ?thesis by blast\n            qed\n            thus ?thesis\n              by (metis \"1\" P.Arr.simps(1) P.Resid_append_ind P.arr_in_Cong_class\n                  P.con_char \\<open>P.Arr (T @ U)\\<close> P.Con_Arr_self P.arr_resid_iff_con)\n          qed\n          show \"arr (\\<U> \\<lbrace>\\<^sup>*\\\\\\<^sup>*\\<rbrace> (\\<lbrace>T @ U\\<rbrace> \\<lbrace>\\<^sup>*\\\\\\<^sup>*\\<rbrace> \\<T>))\"\n            by (metis \"3\" arr_resid_iff_con empty_iff resid_char)\n          show \"\\<U> \\<lbrace>\\<^sup>*\\\\\\<^sup>*\\<rbrace> (\\<lbrace>T @ U\\<rbrace> \\<lbrace>\\<^sup>*\\\\\\<^sup>*\\<rbrace> \\<T>) \\<inter> Collect P.NPath \\<noteq> {}\"\n            by (metis \"1\" \"3\" P.Arr.simps(1) P.Cong\\<^sub>0_append_resid_NPath P.Cong\\<^sub>0_cancel_left\\<^sub>C\\<^sub>S\n                P.Cong_imp_arr(1) P.arr_char NPath_char IntI \\<open>(T @ U) \\<^sup>*\\\\<^sup>* T \\<^sup>*\\<approx>\\<^sup>* U\\<close>\n                \\<open>P.Ide (T \\<^sup>*\\\\<^sup>* (T @ U))\\<close> empty_iff)\n        qed\n      qed\n      thus \"composable \\<T> \\<U>\"\n        using composable_def by auto\n    qed\n\n    sublocale extensional_rts_with_composites Resid\n      using is_extensional_rts_with_composites by simp\n\n    subsection \"Inclusion Map\"\n\n    abbreviation incl\n    where \"incl t \\<equiv> \\<lbrace>[t]\\<rbrace>\"\n\n    text \\<open>\n      The inclusion into the composite completion preserves consistency and residuation.\n    \\<close>\n\n    lemma incl_preserves_con:\n    assumes \"t \\<frown> u\"\n    shows \"\\<lbrace>[t]\\<rbrace> \\<lbrace>\\<^sup>*\\<frown>\\<^sup>*\\<rbrace> \\<lbrace>[u]\\<rbrace>\"\n      using assms\n      by (meson P.Con_rec(1) P.arr_in_Cong_class P.con_char P.is_Cong_classI\n          con_char\\<^sub>Q\\<^sub>C\\<^sub>N P.con_implies_arr(1-2))\n\n    lemma incl_preserves_resid:\n    shows \"\\<lbrace>[t \\\\ u]\\<rbrace> = \\<lbrace>[t]\\<rbrace> \\<lbrace>\\<^sup>*\\\\\\<^sup>*\\<rbrace> \\<lbrace>[u]\\<rbrace>\"\n    proof (cases \"t \\<frown> u\")\n      show \"t \\<frown> u \\<Longrightarrow> ?thesis\"\n      proof -\n        assume 1: \"t \\<frown> u\"\n        have \"P.is_Cong_class \\<lbrace>[t]\\<rbrace> \\<and> P.is_Cong_class \\<lbrace>[u]\\<rbrace>\"\n          using 1 con_char\\<^sub>Q\\<^sub>C\\<^sub>N incl_preserves_con by presburger\n        moreover have \"[t] \\<in> \\<lbrace>[t]\\<rbrace> \\<and> [u] \\<in> \\<lbrace>[u]\\<rbrace>\"\n          using 1\n          by (meson P.Con_rec(1) P.arr_in_Cong_class P.con_char\n              P.Con_implies_Arr(2) P.arr_char P.con_implies_arr(1))\n        moreover have \"P.con [t] [u]\"\n          using 1 by (simp add: P.con_char)\n        ultimately show ?thesis\n          using Resid_by_members [of \"\\<lbrace>[t]\\<rbrace>\" \"\\<lbrace>[u]\\<rbrace>\" \"[t]\" \"[u]\"]\n          by (simp add: \"1\")\n      qed\n      assume 1: \"\\<not> t \\<frown> u\"\n      have \"\\<lbrace>[t \\\\ u]\\<rbrace> = {}\"\n        using 1 R.arrI\n        by (metis Collect_empty_eq P.Con_Arr_self P.Con_rec(1)\n            P.Cong_class_def P.Cong_imp_arr(1) P.arr_char R.arr_resid_iff_con)\n      also have \"... = \\<lbrace>[t]\\<rbrace> \\<lbrace>\\<^sup>*\\\\\\<^sup>*\\<rbrace> \\<lbrace>[u]\\<rbrace>\"\n        by (metis (full_types) \"1\" Con_char CollectD P.Con_rec(1) P.Cong_class_def\n            P.Cong_imp_arr(1) P.arr_in_Cong_class con_char\\<^sub>C\\<^sub>C' null_char conI)\n      finally show ?thesis by simp\n    qed\n\n    lemma incl_reflects_con:\n    assumes \"\\<lbrace>[t]\\<rbrace> \\<lbrace>\\<^sup>*\\<frown>\\<^sup>*\\<rbrace> \\<lbrace>[u]\\<rbrace>\"\n    shows \"t \\<frown> u\"\n      by (metis P.Con_rec(1) P.Cong_class_def P.Cong_imp_arr(1) P.arr_in_Cong_class\n          CollectD assms con_char\\<^sub>C\\<^sub>C' con_char\\<^sub>Q\\<^sub>C\\<^sub>N)\n\n    text \\<open>\n      The inclusion map is a simulation.\n    \\<close>\n\n    sublocale incl: simulation resid Resid incl\n    proof\n      show \"\\<And>t. \\<not> R.arr t \\<Longrightarrow> incl t = null\"\n        by (metis Collect_empty_eq P.Cong_class_def P.Cong_imp_arr(1) P.Ide.simps(2)\n            P.Resid_rec(1) P.cong_reflexive P.elements_are_arr P.ide_char P.ide_closed\n            P.not_arr_null P.null_char R.prfx_implies_con null_char R.con_implies_arr(1))\n      show \"\\<And>t u. t \\<frown> u \\<Longrightarrow> incl t \\<lbrace>\\<^sup>*\\<frown>\\<^sup>*\\<rbrace> incl u\"\n        using incl_preserves_con by blast\n      show \"\\<And>t u. t \\<frown> u \\<Longrightarrow> incl (t \\\\ u) = incl t \\<lbrace>\\<^sup>*\\\\\\<^sup>*\\<rbrace> incl u\"\n        using incl_preserves_resid by blast\n    qed\n\n    lemma inclusion_is_simulation:\n    shows \"simulation resid Resid incl\"\n      ..\n\n    lemma incl_preserves_arr:\n    assumes \"R.arr a\"\n    shows \"arr \\<lbrace>[a]\\<rbrace>\"\n      using assms incl_preserves_con by auto\n\n    lemma incl_preserves_ide:\n    assumes \"R.ide a\"\n    shows \"ide \\<lbrace>[a]\\<rbrace>\"\n      by (metis assms incl_preserves_con incl_preserves_resid R.ide_def ide_def)\n\n    lemma cong_iff_eq_incl:\n    assumes \"R.arr t\" and \"R.arr u\"\n    shows \"\\<lbrace>[t]\\<rbrace> = \\<lbrace>[u]\\<rbrace> \\<longleftrightarrow> t \\<sim> u\"\n    proof\n      show \"\\<lbrace>[t]\\<rbrace> = \\<lbrace>[u]\\<rbrace> \\<Longrightarrow> t \\<sim> u\"\n        by (metis P.Con_rec(1) P.Ide.simps(2) P.Resid.simps(3) P.arr_in_Cong_class\n            P.con_char R.arr_def R.cong_reflexive assms(1) ide_char\\<^sub>C\\<^sub>C\n            incl_preserves_con incl_preserves_ide incl_preserves_resid incl_reflects_con\n            P.arr_resid_iff_con)\n      show \"t \\<sim> u \\<Longrightarrow> \\<lbrace>[t]\\<rbrace> = \\<lbrace>[u]\\<rbrace>\"\n        using assms\n        by (metis incl_preserves_resid extensional incl_preserves_ide)\n    qed\n\n    text \\<open>\n      The inclusion is surjective on identities.\n    \\<close>\n\n    lemma img_incl_ide:\n    shows \"incl ` (Collect R.ide) = Collect ide\"\n    proof\n      show \"incl ` Collect R.ide \\<subseteq> Collect ide\"\n        by (simp add: image_subset_iff)\n      show \"Collect ide \\<subseteq> incl ` Collect R.ide\"\n      proof\n        fix \\<A>\n        assume \\<A>: \"\\<A> \\<in> Collect ide\"\n        obtain A where A: \"A \\<in> \\<A>\"\n          using \\<A> ide_char by blast\n        have \"P.NPath A\"\n          by (metis A Ball_Collect \\<A> ide_char' mem_Collect_eq)\n        obtain a where a: \"a \\<in> P.Srcs A\"\n          using \\<open>P.NPath A\\<close>\n          by (meson P.NPath_implies_Arr equals0I P.Arr_has_Src)\n        have \"P.Cong\\<^sub>0 A [a]\"\n        proof -\n          have \"P.Ide [a]\"\n            by (metis NPath_char P.Con_Arr_self P.Ide.simps(2) P.NPath_implies_Arr\n                P.Resid_Ide(1) P.Srcs.elims R.in_sourcesE \\<open>P.NPath A\\<close> a)\n          thus ?thesis\n            using a A\n            by (metis P.Ide.simps(2) P.ide_char P.ide_closed \\<open>P.NPath A\\<close> NPath_char\n                P.Con_single_ide_iff P.Ide_implies_Arr P.Resid_Arr_Ide_ind P.Resid_Arr_Src)\n        qed\n        have \"\\<A> = \\<lbrace>[a]\\<rbrace>\"\n          by (metis A P.Cong\\<^sub>0_imp_con P.Cong\\<^sub>0_implies_Cong P.Cong\\<^sub>0_transitive P.Cong_class_eqI\n              P.ide_char P.resid_arr_ide Resid_by_members \\<A> \\<open>A \\<^sup>*\\<approx>\\<^sub>0\\<^sup>* [a]\\<close> \\<open>P.NPath A\\<close> arr_char\n              NPath_char ideE ide_implies_arr mem_Collect_eq)\n        thus \"\\<A> \\<in> incl ` Collect R.ide\"\n          using NPath_char P.Ide.simps(2) P.backward_stable \\<open>A \\<^sup>*\\<approx>\\<^sub>0\\<^sup>* [a]\\<close> \\<open>P.NPath A\\<close> by blast\n      qed\n    qed\n\n  end\n\n  subsection \"Composite Completion of an Extensional RTS\"\n\n  locale composite_completion_of_extensional_rts =\n    R: extensional_rts +\n    composite_completion\n  begin\n\n    sublocale P: paths_in_weakly_extensional_rts resid ..\n\n    notation comp (infixl \"\\<lbrace>\\<^sup>*\\<cdot>\\<^sup>*\\<rbrace>\" 55)\n\n    text \\<open>\n      When applied to an extensional RTS, the composite completion construction does not\n      identify any states that are distinct in the original RTS.\n    \\<close>\n\n    lemma incl_injective_on_ide:\n    shows \"inj_on incl (Collect R.ide)\"\n      using R.extensional cong_iff_eq_incl\n      by (intro inj_onI) auto\n\n    text \\<open>\n      When applied to an extensional RTS, the composite completion construction\n      is a bijection between the states of the original RTS and the states of its completion.\n    \\<close>\n\n    lemma incl_bijective_on_ide:\n    shows \"bij_betw incl (Collect R.ide) (Collect ide)\"\n      using incl_injective_on_ide img_incl_ide bij_betw_def by blast\n\n  end\n\n  subsection \"Freeness of Composite Completion\"\n\n  text \\<open>\n    In this section we show that the composite completion construction is free:\n    any simulation from RTS \\<open>A\\<close> to an extensional RTS with composites \\<open>B\\<close>\n    extends uniquely to a simulation on the composite completion of \\<open>A\\<close>.\n  \\<close>\n\n  locale extension_of_simulation =\n    A: paths_in_rts resid\\<^sub>A +\n    B: extensional_rts_with_composites resid\\<^sub>B +\n    F: simulation resid\\<^sub>A resid\\<^sub>B F\n  for resid\\<^sub>A :: \"'a resid\"      (infix \"\\\\\\<^sub>A\" 70)\n  and resid\\<^sub>B :: \"'b resid\"      (infix \"\\\\\\<^sub>B\" 70)\n  and F :: \"'a \\<Rightarrow> 'b\"\n  begin\n\n    notation A.Resid    (infix \"\\<^sup>*\\\\\\<^sub>A\\<^sup>*\" 70)\n    notation A.Resid1x  (infix \"\\<^sup>1\\\\\\<^sub>A\\<^sup>*\" 70)\n    notation A.Residx1  (infix \"\\<^sup>*\\\\\\<^sub>A\\<^sup>1\" 70)\n    notation A.Con      (infix \"\\<^sup>*\\<frown>\\<^sub>A\\<^sup>*\" 70)\n    notation B.comp     (infixl \"\\<cdot>\\<^sub>B\" 55)\n    notation B.con      (infix \"\\<frown>\\<^sub>B\" 50)\n\n    fun map\n    where \"map [] = B.null\"\n        | \"map [t] = F t\"\n        | \"map (t # T) = (if A.arr (t # T) then F t \\<cdot>\\<^sub>B map T else B.null)\"\n\n    lemma map_o_incl_eq:\n    shows \"map (A.incl t) = F t\"\n      by (simp add: A.null_char F.extensional)\n\n    lemma extensional:\n    shows \"\\<not> A.arr T \\<Longrightarrow> map T = B.null\"\n      using F.extensional A.arr_char\n      by (metis A.Arr.simps(2) map.elims)\n\n    lemma preserves_comp:\n    shows \"\\<lbrakk>T \\<noteq> []; U \\<noteq> []; A.Arr (T @ U)\\<rbrakk> \\<Longrightarrow> map (T @ U) = map T \\<cdot>\\<^sub>B map U\"\n    proof (induct T arbitrary: U)\n      show \"\\<And>U. [] \\<noteq> [] \\<Longrightarrow> map ([] @ U) = map [] \\<cdot>\\<^sub>B map U\"\n        by simp\n      fix t and T U :: \"'a list\"\n      assume ind: \"\\<And>U. \\<lbrakk>T \\<noteq> []; U \\<noteq> []; A.Arr (T @ U)\\<rbrakk>\n                          \\<Longrightarrow> map (T @ U) = map T \\<cdot>\\<^sub>B map U\"\n      assume U: \"U \\<noteq> []\"\n      assume Arr: \"A.Arr ((t # T) @ U)\"\n      hence 1: \"A.Arr (t # (T @ U))\"\n        by simp\n      have 2: \"A.Arr (t # T)\"\n        by (metis A.Con_Arr_self A.Con_append(1) A.Con_implies_Arr(1) Arr U append_is_Nil_conv\n            list.distinct(1))\n      show \"map ((t # T) @ U) = B.comp (map (t # T)) (map U)\"\n      proof (cases \"T = []\")\n        show \"T = [] \\<Longrightarrow> ?thesis\"\n          by (metis (full_types) \"1\" A.arr_char U append_Cons append_Nil list.exhaust\n              map.simps(2) map.simps(3))\n        assume T: \"T \\<noteq> []\"\n        have \"map ((t # T) @ U) = map (t # (T @ U))\"\n          by simp\n        also have \"... = F t \\<cdot>\\<^sub>B map (T @ U)\"\n          using T 1\n          by (metis A.arr_char Nil_is_append_conv list.exhaust map.simps(3))\n        also have \"... =  F t \\<cdot>\\<^sub>B (map T \\<cdot>\\<^sub>B map U)\"\n          using ind\n          by (metis \"1\" A.Con_Arr_self A.Con_implies_Arr(1) A.Con_rec(4) T U append_is_Nil_conv)\n        also have \"... = F t \\<cdot>\\<^sub>B map T \\<cdot>\\<^sub>B map U\"\n          using B.comp_assoc\\<^sub>E\\<^sub>C by blast\n        also have \"... = map (t # T) \\<cdot>\\<^sub>B map U\"\n          using T 2\n          by (metis A.arr_char list.exhaust map.simps(3))\n        finally show \"map ((t # T) @ U) = map (t # T) \\<cdot>\\<^sub>B map U\" by simp\n      qed\n    qed\n\n    lemma preserves_arr_ind:\n    shows \"\\<lbrakk>A.arr T; a \\<in> A.Srcs T\\<rbrakk> \\<Longrightarrow> B.arr (map T) \\<and> B.src (map T) = F a\"\n    proof (induct T arbitrary: a)\n      show \"\\<And>a. \\<lbrakk>A.arr []; a \\<in> A.Srcs []\\<rbrakk> \\<Longrightarrow> B.arr (map []) \\<and> B.src (map []) = F a\"\n        using A.arr_char by simp\n      fix a t T\n      assume a: \"a \\<in> A.Srcs (t # T)\"\n      assume tT: \"A.arr (t # T)\"\n      assume ind: \"\\<And>a. \\<lbrakk>A.arr T; a \\<in> A.Srcs T\\<rbrakk> \\<Longrightarrow> B.arr (map T) \\<and> B.src (map T) = F a\"\n      have 1: \"a \\<in> A.R.sources t\"\n        using a tT A.Con_imp_eq_Srcs A.Con_initial_right A.Srcs.simps(2) A.con_char\n        by blast\n      show \"B.arr (map (t # T)) \\<and> B.src (map (t # T)) = F a\"\n      proof (cases \"T = []\")\n        show \"T = [] \\<Longrightarrow> ?thesis\"\n          by (metis \"1\" A.Arr.simps(2) A.arr_char B.arr_has_un_source B.src_in_sources\n              F.preserves_reflects_arr F.preserves_sources image_subset_iff map.simps(2) tT)\n        assume T: \"T \\<noteq> []\"\n        obtain a' where a': \"a' \\<in> A.R.targets t\"\n          using tT \"1\" A.R.resid_source_in_targets by auto\n        have 2: \"a' \\<in> A.Srcs T\"\n          using a' tT\n          by (metis A.Con_Arr_self A.R.sources_resid A.Srcs.simps(2) A.arr_char T\n              A.Con_imp_eq_Srcs A.Con_rec(4))\n        have \"B.arr (map (t # T)) \\<longleftrightarrow> B.arr (F t \\<cdot>\\<^sub>B map T)\"\n          using tT T by (metis map.simps(3) neq_Nil_conv)\n        also have 2: \"... \\<longleftrightarrow> True\"\n          by (metis (no_types, lifting) \"2\" A.arr_char B.arr_comp\\<^sub>E\\<^sub>C B.arr_has_un_target\n              B.trg_in_targets F.preserves_reflects_arr F.preserves_targets T a'\n              A.Arr.elims(2) image_subset_iff ind list.sel(1) list.sel(3) tT)\n        finally have \"B.arr (map (t # T))\" by simp\n        moreover have \"B.src (map (t # T)) = F a\"\n        proof -\n          have \"B.src (map (t # T)) = B.src (F t \\<cdot>\\<^sub>B map T)\"\n            using tT T by (metis map.simps(3) neq_Nil_conv)\n          also have \"... = B.src (F t)\"\n            using \"2\" B.con_comp_iff by force\n          also have \"... = F a\"\n            by (meson \"1\" B.weakly_extensional_rts_axioms F.simulation_axioms\n                simulation_to_weakly_extensional_rts.preserves_src\n                simulation_to_weakly_extensional_rts_def)\n          finally show ?thesis by simp\n        qed\n        ultimately show ?thesis by simp\n      qed\n    qed\n\n    lemma preserves_arr:\n    shows \"A.arr T \\<Longrightarrow> B.arr (map T)\"\n      using preserves_arr_ind A.arr_char A.Arr_has_Src by blast\n\n    lemma preserves_src:\n    assumes \"A.arr T\" and \"a \\<in> A.Srcs T\"\n    shows \"B.src (map T) = F a\"\n      using assms preserves_arr_ind by simp\n\n    lemma preserves_trg:\n    shows \"\\<lbrakk>A.arr T; b \\<in> A.Trgs T\\<rbrakk> \\<Longrightarrow> B.trg (map T) = F b\"\n    proof (induct T)\n      show \"\\<lbrakk>A.arr []; b \\<in> A.Trgs []\\<rbrakk> \\<Longrightarrow> B.trg (map []) = F b\"\n        by simp\n      fix t T\n      assume tT: \"A.arr (t # T)\"\n      assume b: \"b \\<in> A.Trgs (t # T)\"\n      assume ind: \"\\<lbrakk>A.arr T; b \\<in> A.Trgs T\\<rbrakk> \\<Longrightarrow> B.trg (map T) = F b\"\n      show \"B.trg (map (t # T)) = F b\"\n      proof (cases \"T = []\")\n        show \"T = [] \\<Longrightarrow> ?thesis\"\n          using tT b\n          by (metis A.Trgs.simps(2) B.arr_has_un_target B.trg_in_targets F.preserves_targets\n              preserves_arr image_subset_iff map.simps(2))\n        assume T: \"T \\<noteq> []\"\n        have 1: \"B.trg (map (t # T)) = B.trg (F t \\<cdot>\\<^sub>B map T)\"\n          using tT T b\n          by (metis map.simps(3) neq_Nil_conv)\n        also have \"... = B.trg (map T)\"\n          by (metis B.arr_trg_iff_arr B.composable_iff_arr_comp B.trg_comp calculation\n              preserves_arr tT)\n        also have \"... = F b\"\n          using tT b ind\n          by (metis A.Trgs.simps(3) T A.Arr.simps(3) A.arr_char list.exhaust)\n        finally show ?thesis by simp\n      qed\n    qed\n\n    lemma preserves_Resid1x_ind:\n    shows \"t \\<^sup>1\\\\\\<^sub>A\\<^sup>* U \\<noteq> A.R.null \\<Longrightarrow> F t \\<frown>\\<^sub>B map U \\<and> F (t \\<^sup>1\\\\\\<^sub>A\\<^sup>* U) = F t \\\\\\<^sub>B map U\"\n    proof (induct U arbitrary: t)\n      show \"\\<And>t. t \\<^sup>1\\\\\\<^sub>A\\<^sup>* [] \\<noteq> A.R.null \\<Longrightarrow> F t \\<frown>\\<^sub>B map [] \\<and> F (t \\<^sup>1\\\\\\<^sub>A\\<^sup>* []) = F t \\\\\\<^sub>B map []\"\n        by simp\n      fix t u U\n      assume uU: \"t \\<^sup>1\\\\\\<^sub>A\\<^sup>* (u # U) \\<noteq> A.R.null\"\n      assume ind: \"\\<And>t. t \\<^sup>1\\\\\\<^sub>A\\<^sup>* U \\<noteq> A.R.null\n                          \\<Longrightarrow> F t \\<frown>\\<^sub>B map U \\<and> F (t \\<^sup>1\\\\\\<^sub>A\\<^sup>* U) = F t \\\\\\<^sub>B map U\"\n      show \"F t \\<frown>\\<^sub>B map (u # U) \\<and> F (t \\<^sup>1\\\\\\<^sub>A\\<^sup>* (u # U)) = F t \\\\\\<^sub>B map (u # U)\"\n      proof\n        show 1: \"F t \\<frown>\\<^sub>B map (u # U)\"\n        proof (cases \"U = []\")\n          show \"U = [] \\<Longrightarrow> ?thesis\"\n            using A.Resid1x.simps(2) map.simps(2) F.preserves_con uU by fastforce\n          assume U: \"U \\<noteq> []\"\n          have 3: \"[t] \\<^sup>*\\\\\\<^sub>A\\<^sup>* [u] \\<noteq> [] \\<and> ([t] \\<^sup>*\\\\\\<^sub>A\\<^sup>* [u]) \\<^sup>*\\\\\\<^sub>A\\<^sup>* U \\<noteq> []\"\n            using A.Con_cons(2) [of \"[t]\" U u]\n            by (meson A.Resid1x_as_Resid' U not_Cons_self2 uU)\n          hence 2: \"F t \\<frown>\\<^sub>B F u \\<and> F t \\\\\\<^sub>B F u \\<frown>\\<^sub>B map U\"\n            by (metis A.Con_rec(1) A.Con_sym A.Con_sym1 A.Residx1_as_Resid A.Resid_rec(1)\n                F.preserves_con F.preserves_resid ind)\n          moreover have \"B.seq (F u) (map U)\"\n            by (metis B.coinitial_iff\\<^sub>W\\<^sub>E B.con_imp_coinitial B.seqI\\<^sub>W\\<^sub>E B.src_resid calculation)\n          ultimately have \"F t \\<frown>\\<^sub>B map ([u] @ U)\"\n            using B.con_comp_iff\\<^sub>E\\<^sub>C(1) [of \"F t\" \"F u\" \"map U\"] B.con_sym preserves_comp\n            by (metis 3 A.Con_cons(2) A.Con_implies_Arr(2)\n                append.left_neutral append_Cons map.simps(2) not_Cons_self2)\n          thus ?thesis by simp\n        qed\n        show \"F (t \\<^sup>1\\\\\\<^sub>A\\<^sup>* (u # U)) = F t \\\\\\<^sub>B map (u # U)\"\n        proof (cases \"U = []\")\n          show \"U = [] \\<Longrightarrow> ?thesis\"\n            using A.Resid1x.simps(2) F.preserves_resid map.simps(2) uU by fastforce\n          assume U: \"U \\<noteq> []\"\n          have \"F (t \\<^sup>1\\\\\\<^sub>A\\<^sup>* (u # U)) = F ((t \\\\\\<^sub>A u) \\<^sup>1\\\\\\<^sub>A\\<^sup>* U)\"\n            using A.Resid1x_as_Resid' A.Resid_rec(3) U uU by metis\n          also have \"... = F (t \\\\\\<^sub>A u) \\\\\\<^sub>B map U\"\n            using uU U ind A.Con_rec(3) A.Resid1x_as_Resid [of \"t \\\\\\<^sub>A u\" U] \n            by (metis A.Resid1x.simps(3) list.exhaust)\n          also have \"... = (F t \\\\\\<^sub>B F u) \\\\\\<^sub>B map U\"\n            using uU U\n            by (metis A.Resid1x_as_Resid' F.preserves_resid A.Con_rec(3))\n          also have \"... = F t \\\\\\<^sub>B (F u \\<cdot>\\<^sub>B map U)\"\n            by (metis B.comp_null(2) B.composable_iff_comp_not_null B.con_compI(2) B.conI\n                B.con_sym_ax B.mediating_transition B.null_is_zero(2) B.resid_comp(1))\n          also have \"... = F t \\\\\\<^sub>B map (u # U)\"\n            by (metis A.Resid1x_as_Resid' A.con_char U map.simps(3) neq_Nil_conv\n                A.con_implies_arr(2) uU)\n          finally show ?thesis by simp\n        qed\n      qed\n    qed\n\n    lemma preserves_Residx1_ind:\n    shows \"U \\<^sup>*\\\\\\<^sub>A\\<^sup>1 t \\<noteq> [] \\<Longrightarrow> map U \\<frown>\\<^sub>B F t \\<and> map (U \\<^sup>*\\\\\\<^sub>A\\<^sup>1 t) = map U \\\\\\<^sub>B F t\"\n    proof (induct U arbitrary: t)\n      show \"\\<And>t. [] \\<^sup>*\\\\\\<^sub>A\\<^sup>1 t \\<noteq> [] \\<Longrightarrow> map [] \\<frown>\\<^sub>B F t \\<and> map ([] \\<^sup>*\\\\\\<^sub>A\\<^sup>1 t) = map [] \\\\\\<^sub>B F t\"\n        by simp\n      fix t u U\n      assume ind: \"\\<And>t. U \\<^sup>*\\\\\\<^sub>A\\<^sup>1 t \\<noteq> [] \\<Longrightarrow> map U \\<frown>\\<^sub>B F t \\<and> map (U \\<^sup>*\\\\\\<^sub>A\\<^sup>1 t) = map U \\\\\\<^sub>B F t\"\n      assume uU: \"(u # U) \\<^sup>*\\\\\\<^sub>A\\<^sup>1 t \\<noteq> []\"\n      show \"map (u # U) \\<frown>\\<^sub>B F t \\<and> map ((u # U) \\<^sup>*\\\\\\<^sub>A\\<^sup>1 t) = map (u # U) \\\\\\<^sub>B F t\"\n      proof (cases \"U = []\")\n        show \"U = [] \\<Longrightarrow> ?thesis\"\n          using A.Residx1.simps(2) F.preserves_con F.preserves_resid map.simps(2) uU\n          by presburger\n        assume U: \"U \\<noteq> []\"\n        show ?thesis\n        proof\n          show \"map (u # U) \\<frown>\\<^sub>B F t\"\n            using uU U A.Con_sym1 B.con_sym preserves_Resid1x_ind by blast\n          show \"map ((u # U) \\<^sup>*\\\\\\<^sub>A\\<^sup>1 t) = map (u # U) \\\\\\<^sub>B F t\"\n          proof -\n            have \"map ((u # U) \\<^sup>*\\\\\\<^sub>A\\<^sup>1 t) = map ((u \\\\\\<^sub>A t) # U \\<^sup>*\\\\\\<^sub>A\\<^sup>1 (t \\\\\\<^sub>A u))\"\n              using uU U A.Residx1_as_Resid A.Resid_rec(2) by fastforce\n            also have \"... = F (u \\\\\\<^sub>A t) \\<cdot>\\<^sub>B map (U \\<^sup>*\\\\\\<^sub>A\\<^sup>1 (t \\\\\\<^sub>A u))\"\n              by (metis A.Residx1_as_Resid A.arr_char U A.Con_imp_Arr_Resid\n                  A.Con_rec(2) A.Resid_rec(2) list.exhaust map.simps(3) uU)\n            also have \"... = F (u \\\\\\<^sub>A t) \\<cdot>\\<^sub>B map U \\\\\\<^sub>B F (t \\\\\\<^sub>A u)\"\n              using uU U ind A.Con_rec(2) A.Residx1_as_Resid by force\n            also have \"... = (F u \\\\\\<^sub>B F t) \\<cdot>\\<^sub>B map U \\\\\\<^sub>B (F t \\\\\\<^sub>B F u)\"\n              using uU U\n              by (metis A.Con_initial_right A.Con_rec(1) A.Con_sym1 A.Resid1x_as_Resid'\n                  A.Residx1_as_Resid F.preserves_resid)\n            also have \"... = (F u \\<cdot>\\<^sub>B map U) \\\\\\<^sub>B F t\"\n              by (metis B.comp_null(2) B.composable_iff_comp_not_null B.con_compI(2) B.con_sym\n                  B.mediating_transition B.null_is_zero(2) B.resid_comp(2) B.con_def)\n            also have \"... = map (u # U) \\\\\\<^sub>B F t\"\n              by (metis A.Con_implies_Arr(2) A.Con_sym A.Residx1_as_Resid U\n                  A.arr_char map.simps(3) neq_Nil_conv uU)\n            finally show ?thesis by simp\n          qed\n        qed\n      qed\n    qed\n\n    lemma preserves_resid_ind:\n    shows \"A.con T U \\<Longrightarrow> map T \\<frown>\\<^sub>B map U \\<and> map (T \\<^sup>*\\\\\\<^sub>A\\<^sup>* U) = map T \\\\\\<^sub>B map U\"\n    proof (induct T arbitrary: U)\n      show \"\\<And>U. A.con [] U \\<Longrightarrow> map [] \\<frown>\\<^sub>B map U \\<and> map ([] \\<^sup>*\\\\\\<^sub>A\\<^sup>* U) = map [] \\\\\\<^sub>B map U\"\n        using A.con_char A.Resid.simps(1) by blast\n      fix t T U\n      assume tT: \"A.con (t # T) U\"\n      assume ind: \"\\<And>U. A.con T U \\<Longrightarrow>\n                         map T \\<frown>\\<^sub>B map U \\<and> map (T \\<^sup>*\\\\\\<^sub>A\\<^sup>* U) = map T \\\\\\<^sub>B map U\"\n      show \"map (t # T) \\<frown>\\<^sub>B map U \\<and> map ((t # T) \\<^sup>*\\\\\\<^sub>A\\<^sup>* U) = map (t # T) \\\\\\<^sub>B map U\"\n      proof (cases \"T = []\")\n        assume T: \"T = []\"\n        show ?thesis\n          using T tT\n          apply simp\n          by (metis A.Resid1x_as_Resid A.Residx1_as_Resid A.con_char\n              A.Con_sym A.Con_sym1 map.simps(2) preserves_Resid1x_ind)\n        next\n        assume T: \"T \\<noteq> []\"\n        have 1: \"map (t # T) = F t \\<cdot>\\<^sub>B map T\"\n          using tT T\n          by (metis A.con_implies_arr(1) list.exhaust map.simps(3))\n        show ?thesis\n        proof\n          show 2: \"B.con (map (t # T)) (map U)\"\n            using T tT\n            by (metis \"1\" A.Con_cons(1) A.Residx1_as_Resid A.con_char A.not_arr_null\n                A.null_char B.composable_iff_comp_not_null B.con_compI(2) B.con_sym\n                B.not_arr_null preserves_arr ind preserves_Residx1_ind A.con_implies_arr(1-2))\n          show \"map ((t # T) \\<^sup>*\\\\\\<^sub>A\\<^sup>* U) = map (t # T) \\\\\\<^sub>B map U\"\n          proof -\n            have \"map ((t # T) \\<^sup>*\\\\\\<^sub>A\\<^sup>* U) = map (([t] \\<^sup>*\\\\\\<^sub>A\\<^sup>* U) @ (T \\<^sup>*\\\\\\<^sub>A\\<^sup>* (U \\<^sup>*\\\\\\<^sub>A\\<^sup>* [t])))\"\n              by (metis A.Resid.simps(1) A.Resid_cons(1) A.con_char A.ex_un_null tT)\n            also have \"... = map ([t] \\<^sup>*\\\\\\<^sub>A\\<^sup>* U) \\<cdot>\\<^sub>B map (T \\<^sup>*\\\\\\<^sub>A\\<^sup>* (U \\<^sup>*\\\\\\<^sub>A\\<^sup>* [t]))\"\n              by (metis A.Arr.simps(1) A.Con_imp_Arr_Resid A.Con_implies_Arr(2) A.Con_sym\n                  A.Resid_cons(1-2) A.con_char T preserves_comp tT)\n            also have \"... = (map [t] \\\\\\<^sub>B map U) \\<cdot>\\<^sub>B map (T \\<^sup>*\\\\\\<^sub>A\\<^sup>* (U \\<^sup>*\\\\\\<^sub>A\\<^sup>* [t]))\"\n              by (metis A.Con_initial_right A.Con_sym A.Resid1x_as_Resid\n                  A.Residx1_as_Resid A.con_char A.Con_sym1 map.simps(2)\n                  preserves_Resid1x_ind tT)\n            also have \"... = (map [t] \\\\\\<^sub>B map U) \\<cdot>\\<^sub>B (map T \\\\\\<^sub>B map (U \\<^sup>*\\\\\\<^sub>A\\<^sup>* [t]))\"\n              using tT T ind\n              by (metis A.Con_cons(1) A.Con_sym A.Resid.simps(1) A.con_char)\n            also have \"... = (map [t] \\\\\\<^sub>B map U) \\<cdot>\\<^sub>B (map T \\\\\\<^sub>B (map U \\\\\\<^sub>B map [t]))\"\n              using tT T\n              by (metis A.Con_cons(1) A.Con_sym A.Resid.simps(2) A.Residx1_as_Resid\n                        A.con_char map.simps(2) preserves_Residx1_ind)\n            also have \"... = (F t \\\\\\<^sub>B map U) \\<cdot>\\<^sub>B (map T \\\\\\<^sub>B (map U \\\\\\<^sub>B F t))\"\n              using tT T by simp\n            also have \"... = map (t # T) \\\\\\<^sub>B map U\"\n              using 1 2 B.resid_comp(2) by presburger\n            finally show ?thesis by simp\n          qed\n        qed\n      qed\n    qed\n\n    lemma preserves_con:\n    assumes \"A.con T U\"\n    shows \"map T \\<frown>\\<^sub>B map U\"\n      using assms preserves_resid_ind by simp\n\n    lemma preserves_resid:\n    assumes \"A.con T U\"\n    shows \"map (T \\<^sup>*\\\\\\<^sub>A\\<^sup>* U) = map T \\\\\\<^sub>B map U\"\n      using assms preserves_resid_ind by simp\n\n    sublocale simulation A.Resid resid\\<^sub>B map\n      using A.con_char preserves_con preserves_resid extensional\n      by unfold_locales auto\n\n    sublocale simulation_to_extensional_rts A.Resid resid\\<^sub>B map ..\n\n    lemma is_universal:\n    assumes \"rts_with_composites resid\\<^sub>B\" and \"simulation resid\\<^sub>A resid\\<^sub>B F\"\n    shows \"\\<exists>!F'. simulation A.Resid resid\\<^sub>B F' \\<and> F' o A.incl = F\"\n    proof\n      interpret B: rts_with_composites resid\\<^sub>B\n        using assms by auto\n      interpret F: simulation resid\\<^sub>A resid\\<^sub>B F\n        using assms by auto\n      show \"simulation A.Resid resid\\<^sub>B map \\<and> map \\<circ> A.incl = F\"\n        using map_o_incl_eq simulation_axioms by auto\n      show \"\\<And>F'. simulation A.Resid resid\\<^sub>B F' \\<and> F' o A.incl = F \\<Longrightarrow> F' = map\"\n      proof\n        fix F' T\n        assume F': \"simulation A.Resid resid\\<^sub>B F' \\<and> F' o A.incl = F\"\n        interpret F': simulation A.Resid resid\\<^sub>B F'\n          using F' by simp\n        show \"F' T = map T\"\n        proof (induct T)\n          show \"F' [] = map []\"\n            by (simp add: A.arr_char F'.extensional)\n          fix t T\n          assume ind: \"F' T = map T\"\n          show \"F' (t # T) = map (t # T)\"\n          proof (cases \"A.Arr (t # T)\")\n            show \"\\<not> A.Arr (t # T) \\<Longrightarrow> ?thesis\"\n              by (simp add: A.arr_char F'.extensional extensional)\n            assume tT: \"A.Arr (t # T)\"\n            show ?thesis\n            proof (cases \"T = []\")\n              show 2: \"T = [] \\<Longrightarrow> ?thesis\"\n                using F' tT by auto\n              assume T: \"T \\<noteq> []\"\n              have \"F' (t # T) = F' [t] \\<cdot>\\<^sub>B map T\"\n              proof -\n                have \"F' (t # T) = F' ([t] @ T)\"\n                  by simp\n                also have \"... = F' [t] \\<cdot>\\<^sub>B F' T\"\n                proof -\n                  have \"A.composite_of [t] T ([t] @ T)\"\n                    using T tT\n                    by (metis (full_types) A.Arr.simps(2) A.Con_Arr_self\n                        A.append_is_composite_of A.Con_implies_Arr(1) A.Con_imp_eq_Srcs\n                        A.Con_rec(4) A.Resid_rec(1) A.Srcs_Resid A.seq_char A.R.arrI)\n                  thus ?thesis\n                    using F'.preserves_composites [of \"[t]\" T \"[t] @ T\"] B.comp_is_composite_of\n                    by auto\n                qed\n                also have \"... = F' [t] \\<cdot>\\<^sub>B map T\"\n                  using T ind by simp\n                finally show ?thesis by simp\n              qed\n              also have \"... = (F' \\<circ> A.incl) t \\<cdot>\\<^sub>B map T\"\n                using tT\n                by (simp add: A.arr_char A.null_char F'.extensional)\n              also have \"... = F t \\<cdot>\\<^sub>B map T\"\n                using F' by simp\n              also have \"... = map (t # T)\"\n                using T tT\n                by (metis A.arr_char list.exhaust map.simps(3))\n              finally show ?thesis by simp\n            qed\n          qed\n        qed\n      qed\n    qed\n\n  end\n\n  (*\n   * TODO: Localize to context rts?\n   *)\n  lemma composite_completion_of_rts:\n  assumes \"rts A\"\n  shows \"\\<exists>(C :: 'a list resid) I. rts_with_composites C \\<and> simulation A C I \\<and>\n          (\\<forall>B (J :: 'a \\<Rightarrow> 'c). extensional_rts_with_composites B \\<and> simulation A B J\n                                 \\<longrightarrow> (\\<exists>!J'. simulation C B J' \\<and> J' o I = J))\"\n  proof (intro exI conjI)\n    interpret A: rts A\n      using assms by auto\n    interpret P\\<^sub>A: paths_in_rts A ..\n    show \"rts_with_composites P\\<^sub>A.Resid\"\n      using P\\<^sub>A.rts_with_composites_axioms by simp\n    show \"simulation A P\\<^sub>A.Resid P\\<^sub>A.incl\"\n      using P\\<^sub>A.incl_is_simulation by simp\n    show \"\\<forall>B (J :: 'a \\<Rightarrow> 'c). extensional_rts_with_composites B \\<and> simulation A B J\n                                \\<longrightarrow> (\\<exists>!J'. simulation P\\<^sub>A.Resid B J' \\<and> J' o P\\<^sub>A.incl = J)\"\n    proof (intro allI impI)\n      fix B :: \"'c resid\" and J\n      assume 1: \"extensional_rts_with_composites B \\<and> simulation A B J\"\n      interpret B: extensional_rts_with_composites B\n        using 1 by simp\n      interpret J: simulation A B J\n        using 1 by simp\n      interpret J: extension_of_simulation A B J\n        ..\n      have \"simulation P\\<^sub>A.Resid B J.map\"\n        using J.simulation_axioms by simp\n      moreover have \"J.map o P\\<^sub>A.incl = J\"\n        using J.map_o_incl_eq by auto\n      moreover have \"\\<And>J'. simulation P\\<^sub>A.Resid B J' \\<and> J' o P\\<^sub>A.incl = J \\<Longrightarrow> J' = J.map\"\n        using \"1\" B.rts_with_composites_axioms J.is_universal J.simulation_axioms\n              calculation(2)\n        by blast\n      ultimately show \"\\<exists>!J'. simulation P\\<^sub>A.Resid B J' \\<and> J' \\<circ> P\\<^sub>A.incl = J\" by auto\n    qed\n  qed\n\n  section \"Constructions on RTS's\"\n\n  subsection \"Products of RTS's\"\n\n  locale product_rts =\n    R1: rts R1 +\n    R2: rts R2\n  for R1 :: \"'a1 resid\"      (infix \"\\\\\\<^sub>1\" 70)\n  and R2 :: \"'a2 resid\"      (infix \"\\\\\\<^sub>2\" 70)\n  begin\n\n    type_synonym ('aa1, 'aa2) arr = \"'aa1 * 'aa2\"\n\n    abbreviation (input) Null :: \"('a1, 'a2) arr\"\n    where \"Null \\<equiv> (R1.null, R2.null)\"\n\n    definition resid :: \"('a1, 'a2) arr \\<Rightarrow> ('a1, 'a2) arr \\<Rightarrow> ('a1, 'a2) arr\"\n    where \"resid t u = (if R1.con (fst t) (fst u) \\<and> R2.con (snd t) (snd u)\n                        then (fst t \\\\\\<^sub>1 fst u, snd t \\\\\\<^sub>2 snd u)\n                        else Null)\"\n\n    notation resid      (infix \"\\\\\" 70)\n\n    sublocale partial_magma resid\n      by unfold_locales\n        (metis R1.con_implies_arr(1-2) R1.not_arr_null fst_conv resid_def)\n\n    lemma is_partial_magma:\n    shows \"partial_magma resid\"\n      ..\n\n    lemma null_char [simp]:\n    shows \"null = Null\"\n      by (metis R2.null_is_zero(1) R2.residuation_axioms ex_un_null null_is_zero(1)\n          resid_def residuation.conE snd_conv)\n\n    sublocale residuation resid\n    proof\n      show \"\\<And>t u. t \\\\ u \\<noteq> null \\<Longrightarrow> u \\\\ t \\<noteq> null\"\n        by (metis R1.con_def R1.con_sym null_char prod.inject resid_def R2.con_sym)\n      show \"\\<And>t u. t \\\\ u \\<noteq> null \\<Longrightarrow> (t \\\\ u) \\\\ (t \\\\ u) \\<noteq> null\"\n        by (metis (no_types, lifting) R1.arrE R2.con_def R2.con_imp_arr_resid fst_conv null_char\n            resid_def R1.arr_resid snd_conv)\n      show \"\\<And>v t u. (v \\\\ t) \\\\ (u \\\\ t) \\<noteq> null \\<Longrightarrow> (v \\\\ t) \\\\ (u \\\\ t) = (v \\\\ u) \\\\ (t \\\\ u)\"\n      proof -\n        fix t u v\n        assume 1: \"(v \\\\ t) \\\\ (u \\\\ t) \\<noteq> null\"\n        have \"(fst v \\\\\\<^sub>1 fst t) \\\\\\<^sub>1 (fst u \\\\\\<^sub>1 fst t) \\<noteq> R1.null\"\n          by (metis 1 R1.not_arr_null fst_conv null_char null_is_zero(1-2)\n              resid_def R1.arr_resid)\n        moreover have \"(snd v \\\\\\<^sub>2 snd t) \\\\\\<^sub>2 (snd u \\\\\\<^sub>2 snd t) \\<noteq> R2.null\"\n          by (metis 1 R2.not_arr_null snd_conv null_char null_is_zero(1-2)\n              resid_def R2.arr_resid)\n        ultimately show \"(v \\\\ t) \\\\ (u \\\\ t) = (v \\\\ u) \\\\ (t \\\\ u)\"\n          using resid_def null_char R1.con_def R2.con_def R1.cube R2.cube\n          apply simp\n          by (metis (no_types, lifting) R1.conI R1.con_sym_ax R1.resid_reflects_con\n              R2.con_sym_ax R2.null_is_zero(1))\n      qed\n    qed\n\n    lemma is_residuation:\n    shows \"residuation resid\"\n      ..\n\n    lemma arr_char [iff]:\n    shows \"arr t \\<longleftrightarrow> R1.arr (fst t) \\<and> R2.arr (snd t)\"\n      by (metis (no_types, lifting) R1.arr_def R2.arr_def R2.conE null_char resid_def\n          residuation.arr_def residuation.con_def residuation_axioms snd_eqD)\n\n    lemma ide_char [iff]:\n    shows \"ide t \\<longleftrightarrow> R1.ide (fst t) \\<and> R2.ide (snd t)\"\n      by (metis (no_types, lifting) R1.residuation_axioms R2.residuation_axioms\n          arr_char arr_def fst_conv null_char prod.collapse resid_def residuation.conE\n          residuation.ide_def residuation.ide_implies_arr residuation_axioms snd_conv)\n\n    lemma con_char [iff]:\n    shows \"con t u \\<longleftrightarrow> R1.con (fst t) (fst u) \\<and> R2.con (snd t) (snd u)\"\n      by (simp add: R2.residuation_axioms con_def resid_def residuation.con_def)\n\n    lemma trg_char:\n    shows \"trg t = (if arr t then (R1.trg (fst t), R2.trg (snd t)) else Null)\"\n      using R1.trg_def R2.trg_def resid_def trg_def by auto\n\n    sublocale rts resid\n    proof\n      show \"\\<And>t. arr t \\<Longrightarrow> ide (trg t)\"\n        by (simp add: trg_char)\n      show \"\\<And>a t. \\<lbrakk>ide a; con t a\\<rbrakk> \\<Longrightarrow> t \\\\ a = t\"\n        by (simp add: R1.resid_arr_ide R2.resid_arr_ide resid_def)\n      show \"\\<And>a t. \\<lbrakk>ide a; con a t\\<rbrakk> \\<Longrightarrow> ide (a \\\\ t)\"\n        by (metis \\<open>\\<And>t a. \\<lbrakk>ide a; con t a\\<rbrakk> \\<Longrightarrow> t \\ a = t\\<close> con_sym cube ideE ideI\n            residuation.con_def residuation_axioms)\n      show \"\\<And>t u. con t u \\<Longrightarrow> \\<exists>a. ide a \\<and> con a t \\<and> con a u\"\n      proof -\n        fix t u\n        assume tu: \"con t u\"\n        obtain a1 where a1: \"a1 \\<in> R1.sources (fst t) \\<inter> R1.sources (fst u)\"\n          by (meson R1.con_imp_common_source all_not_in_conv con_char tu)\n        obtain a2 where a2: \"a2 \\<in> R2.sources (snd t) \\<inter> R2.sources (snd u)\"\n          by (meson R2.con_imp_common_source all_not_in_conv con_char tu)\n        have \"ide (a1, a2) \\<and> con (a1, a2) t \\<and> con (a1, a2) u\"\n          using a1 a2 ide_char con_char\n          by (metis R1.con_imp_common_source R1.in_sourcesE R1.sources_eqI\n              R2.con_imp_common_source R2.in_sourcesE R2.sources_eqI con_sym\n              fst_conv inf_idem snd_conv tu)\n        thus \"\\<exists>a. ide a \\<and> con a t \\<and> con a u\" by blast\n      qed\n      show \"\\<And>t u v. \\<lbrakk>ide (t \\\\ u); con u v\\<rbrakk> \\<Longrightarrow> con (t \\\\ u) (v \\\\ u)\"\n      proof -\n        fix t u v\n        assume tu: \"ide (t \\\\ u)\"\n        assume uv: \"con u v\"\n        have \"R1.ide (fst t \\\\\\<^sub>1 fst u) \\<and> R2.ide (snd t \\\\\\<^sub>2 snd u)\"\n          using tu ide_char\n          by (metis conI con_char fst_eqD ide_implies_arr not_arr_null resid_def snd_conv)\n        moreover have \"R1.con (fst u) (fst v) \\<and> R2.con (snd u) (snd v)\"\n          using uv con_char by blast\n        ultimately show \"con (t \\\\ u) (v \\\\ u)\"\n          by (simp add: R1.con_target R1.con_sym R1.prfx_implies_con\n              R2.con_target R2.con_sym R2.prfx_implies_con resid_def)\n      qed\n    qed\n\n    lemma is_rts:\n    shows \"rts resid\"\n      ..\n\n    lemma sources_char:\n    shows \"sources t = R1.sources (fst t) \\<times> R2.sources (snd t)\"\n      by force\n\n    lemma targets_char:\n    shows \"targets t = R1.targets (fst t) \\<times> R2.targets (snd t)\"\n    proof\n      show \"targets t \\<subseteq> R1.targets (fst t) \\<times> R2.targets (snd t)\"\n        using targets_def ide_char con_char resid_def trg_char trg_def by auto\n      show \"R1.targets (fst t) \\<times> R2.targets (snd t) \\<subseteq> targets t\"\n      proof\n        fix a\n        assume a: \"a \\<in> R1.targets (fst t) \\<times> R2.targets (snd t)\"\n        show \"a \\<in> targets t\"\n        proof\n          show \"ide a\"\n            using a ide_char by auto\n          show \"con (trg t) a\"\n            using a trg_char con_char [of \"trg t\" a]\n            by (metis (no_types, lifting) SigmaE arr_char con_char con_implies_arr(1)\n                fst_conv R1.in_targetsE R2.in_targetsE R1.arr_resid_iff_con R2.arr_resid_iff_con\n                R1.trg_def R2.trg_def snd_conv)\n        qed\n      qed\n    qed\n\n    lemma prfx_char:\n    shows \"prfx t u \\<longleftrightarrow> R1.prfx (fst t) (fst u) \\<and> R2.prfx (snd t) (snd u)\"\n      using R1.prfx_implies_con R2.prfx_implies_con resid_def by auto\n\n    lemma cong_char:\n    shows \"cong t u \\<longleftrightarrow> R1.cong (fst t) (fst u) \\<and> R2.cong (snd t) (snd u)\"\n      using prfx_char by auto\n\n  end\n\n  locale product_of_weakly_extensional_rts =\n    R1: weakly_extensional_rts R1 +\n    R2: weakly_extensional_rts R2 +\n    product_rts\n  begin\n\n    sublocale weakly_extensional_rts resid\n    proof\n      show \"\\<And>t u. \\<lbrakk>cong t u; ide t; ide u\\<rbrakk> \\<Longrightarrow> t = u\"\n        by (metis cong_char ide_char prod.exhaust_sel R1.weak_extensionality R2.weak_extensionality)\n    qed\n\n    lemma src_char:\n    shows \"src t = (if arr t then (R1.src (fst t), R2.src (snd t)) else null)\"\n    proof (cases \"arr t\")\n      show \"\\<not> arr t \\<Longrightarrow> ?thesis\"\n        using src_def by presburger\n      assume t: \"arr t\"\n      show ?thesis\n      proof (intro src_eqI)\n        show \"ide (if arr t then (R1.src (fst t), R2.src (snd t)) else null)\"\n          using t by simp\n        show \"con (if arr t then (R1.src (fst t), R2.src (snd t)) else null) t\"\n          using t con_char arr_char\n          apply (cases t)\n          apply simp_all\n          by (metis R1.con_imp_coinitial_ax R1.residuation_axioms R1.src_eqI R2.con_sym\n              R2.in_sourcesE R2.src_in_sources residuation.arr_def)\n      qed\n    qed\n\n  end\n\n  locale product_of_extensional_rts =\n    R1: extensional_rts R1 +\n    R2: extensional_rts R2 +\n    product_of_weakly_extensional_rts\n  begin\n\n    sublocale extensional_rts resid\n    proof\n      show \"\\<And>t u. cong t u \\<Longrightarrow> t = u\"\n        by (metis R1.extensional R2.extensional cong_char prod.collapse)\n    qed\n\n  end\n\n  subsubsection \"Product Simulations\"\n\n  locale product_simulation =\n    A1: rts A1 +\n    A2: rts A2 +\n    B1: rts B1 +\n    B2: rts B2 +\n    A1xA2: product_rts A1 A2 +\n    B1xB2: product_rts B1 B2 +\n    F1: simulation A1 B1 F1 +\n    F2: simulation A2 B2 F2\n  for A1 :: \"'a1 resid\"      (infix \"\\\\\\<^sub>A\\<^sub>1\" 70)\n  and A2 :: \"'a2 resid\"      (infix \"\\\\\\<^sub>A\\<^sub>2\" 70)\n  and B1 :: \"'b1 resid\"      (infix \"\\\\\\<^sub>B\\<^sub>1\" 70)\n  and B2 :: \"'b2 resid\"      (infix \"\\\\\\<^sub>B\\<^sub>2\" 70)\n  and F1 :: \"'a1 \\<Rightarrow> 'b1\"\n  and F2 :: \"'a2 \\<Rightarrow> 'b2\"\n  begin\n\n    definition map\n    where \"map = (\\<lambda>a. if A1xA2.arr a then (F1 (fst a), F2 (snd a)) else B1xB2.null)\"\n\n    lemma map_simp [simp]:\n    assumes \"A1.arr a1\" and \"A2.arr a2\"\n    shows \"map (a1, a2) = (F1 a1, F2 a2)\"\n      using assms map_def by auto\n\n    sublocale simulation A1xA2.resid B1xB2.resid map\n    proof\n      show \"\\<And>t. \\<not> A1xA2.arr t \\<Longrightarrow> map t = B1xB2.null\"\n        using map_def by auto\n      show \"\\<And>t u. A1xA2.con t u \\<Longrightarrow> B1xB2.con (map t) (map u)\"\n        using A1xA2.con_char B1xB2.con_char A1.con_implies_arr A2.con_implies_arr by auto\n      show \"\\<And>t u. A1xA2.con t u \\<Longrightarrow> map (A1xA2.resid t u) = B1xB2.resid (map t) (map u)\"\n        using A1xA2.resid_def B1xB2.resid_def A1.con_implies_arr A2.con_implies_arr\n        by auto\n    qed\n\n    lemma is_simulation:\n    shows \"simulation A1xA2.resid B1xB2.resid map\"\n      ..\n\n  end\n\n  subsubsection \"Binary Simulations\"\n\n  locale binary_simulation =\n    A1: rts A1 +\n    A2: rts A2 +\n    A: product_rts A1 A2 +\n    B: rts B +\n    simulation A.resid B F\n  for A1 :: \"'a1 resid\"    (infixr \"\\\\\\<^sub>A\\<^sub>1\" 70)\n  and A2 :: \"'a2 resid\"    (infixr \"\\\\\\<^sub>A\\<^sub>2\" 70)\n  and B :: \"'b resid\"      (infixr \"\\\\\\<^sub>B\" 70)\n  and F :: \"'a1 * 'a2 \\<Rightarrow> 'b\"\n  begin\n\n    lemma fixing_ide_gives_simulation_1:\n    assumes \"A1.ide a1\"\n    shows \"simulation A2 B (\\<lambda>t2. F (a1, t2))\"\n    proof\n      show \"\\<And>t2. \\<not> A2.arr t2 \\<Longrightarrow> F (a1, t2) = B.null\"\n        using assms extensional A.arr_char by simp\n      show \"\\<And>t2 u2. A2.con t2 u2 \\<Longrightarrow> B.con (F (a1, t2)) (F (a1, u2))\"\n        using assms A.con_char preserves_con by auto\n      show \"\\<And>t2 u2. A2.con t2 u2 \\<Longrightarrow> F (a1, t2 \\\\\\<^sub>A\\<^sub>2 u2) = F (a1, t2) \\\\\\<^sub>B F (a1, u2)\"\n        using assms A.con_char A.resid_def preserves_resid\n        by (metis A1.ideE fst_conv snd_conv)\n    qed\n\n    lemma fixing_ide_gives_simulation_2:\n    assumes \"A2.ide a2\"\n    shows \"simulation A1 B (\\<lambda>t1. F (t1, a2))\"\n    proof\n      show \"\\<And>t1. \\<not> A1.arr t1 \\<Longrightarrow> F (t1, a2) = B.null\"\n        using assms extensional A.arr_char by simp\n      show \"\\<And>t1 u1. A1.con t1 u1 \\<Longrightarrow> B.con (F (t1, a2)) (F (u1, a2))\"\n        using assms A.con_char preserves_con by auto\n      show \"\\<And>t1 u1. A1.con t1 u1 \\<Longrightarrow> F (t1 \\\\\\<^sub>A\\<^sub>1 u1, a2) = F (t1, a2) \\\\\\<^sub>B F (u1, a2)\"\n        using assms A.con_char A.resid_def preserves_resid\n        by (metis A2.ideE fst_conv snd_conv)\n    qed\n\n  end\n\n  subsection \"Sub-RTS's\"\n\n  locale sub_rts =\n    R: rts R\n  for R :: \"'a resid\"      (infix \"\\\\\\<^sub>R\" 70)\n  and Arr :: \"'a \\<Rightarrow> bool\" +\n  assumes inclusion: \"Arr t \\<Longrightarrow> R.arr t\"\n  and sources_closed: \"Arr t \\<Longrightarrow> R.sources t \\<subseteq> Collect Arr\"\n  and resid_closed: \"\\<lbrakk>Arr t; Arr u; R.con t u\\<rbrakk> \\<Longrightarrow> Arr (t \\\\\\<^sub>R u)\"\n  begin\n\n    definition resid  (infix \"\\\\\" 70)\n    where \"t \\\\ u \\<equiv> (if Arr t \\<and> Arr u \\<and> R.con t u then t \\\\\\<^sub>R u else R.null)\"\n\n    sublocale partial_magma resid\n      by unfold_locales\n        (metis R.ex_un_null R.null_is_zero(2) resid_def)\n\n    lemma is_partial_magma:\n    shows \"partial_magma resid\"\n      ..\n\n    lemma null_char [simp]:\n    shows \"null = R.null\"\n      by (metis R.null_is_zero(1) ex_un_null null_is_zero(1) resid_def)\n\n    sublocale residuation resid\n    proof\n      show \"\\<And>t u. t \\\\ u \\<noteq> null \\<Longrightarrow> u \\\\ t \\<noteq> null\"\n        by (metis R.con_sym R.con_sym_ax null_char resid_def)\n      show \"\\<And>t u. t \\\\ u \\<noteq> null \\<Longrightarrow> (t \\\\ u) \\\\ (t \\\\ u) \\<noteq> null\"\n        by (metis R.arrE R.arr_resid R.not_arr_null null_char resid_closed resid_def)\n      show \"\\<And>v t u. (v \\\\ t) \\\\ (u \\\\ t) \\<noteq> null \\<Longrightarrow> (v \\\\ t) \\\\ (u \\\\ t) = (v \\\\ u) \\\\ (t \\\\ u)\"\n        by (metis R.cube R.ex_un_null R.null_is_zero(1) R.residuation_axioms null_is_zero(2)\n            resid_closed resid_def residuation.conE residuation.conI)\n    qed\n\n    lemma is_residuation:\n    shows \"residuation resid\"\n      ..\n\n    lemma arr_char [iff]:\n    shows \"arr t \\<longleftrightarrow> Arr t\"\n    proof\n      show \"arr t \\<Longrightarrow> Arr t\"\n        by (metis arrE conE null_char resid_def)\n      show \"Arr t \\<Longrightarrow> arr t\"\n        by (metis R.arrE R.conE conI con_implies_arr(2) inclusion null_char resid_def)\n    qed\n\n    lemma ide_char [iff]:\n    shows \"ide t \\<longleftrightarrow> Arr t \\<and> R.ide t\"\n      by (metis R.ide_def arrE arr_char conE ide_def null_char resid_def)\n\n    lemma con_char [iff]:\n    shows \"con t u \\<longleftrightarrow> Arr t \\<and> Arr u \\<and> R.con t u\"\n      using con_def resid_def by auto\n\n    lemma trg_char:\n    shows \"trg t = (if arr t then R.trg t else null)\"\n      using R.trg_def arr_def resid_def trg_def by force\n\n    sublocale rts resid\n    proof\n      show \"\\<And>t. arr t \\<Longrightarrow> ide (trg t)\"\n        by (metis R.ide_trg arrE arr_char arr_resid ide_char inclusion trg_char trg_def)\n      show \"\\<And>a t. \\<lbrakk>ide a; con t a\\<rbrakk> \\<Longrightarrow> t \\\\ a = t\"\n        by (simp add: R.resid_arr_ide resid_def)\n      show \"\\<And>a t. \\<lbrakk>ide a; con a t\\<rbrakk> \\<Longrightarrow> ide (a \\\\ t)\"\n        by (metis R.resid_ide_arr arr_resid_iff_con arr_char con_char ide_char resid_def)\n      show \"\\<And>t u. con t u \\<Longrightarrow> \\<exists>a. ide a \\<and> con a t \\<and> con a u\"\n        by (metis (full_types) R.con_imp_coinitial_ax R.con_sym R.in_sourcesI\n            con_char ide_char in_mono mem_Collect_eq sources_closed)\n      show \"\\<And>t u v. \\<lbrakk>ide (t \\\\ u); con u v\\<rbrakk> \\<Longrightarrow> con (t \\\\ u) (v \\\\ u)\"\n        by (metis R.con_target arr_resid_iff_con con_char con_sym ide_char\n            ide_implies_arr resid_closed resid_def)\n    qed\n\n    lemma is_rts:\n    shows \"rts resid\"\n      ..\n\n    lemma sources_char\\<^sub>S\\<^sub>R\\<^sub>T\\<^sub>S:\n    shows \"sources t = {a. Arr t \\<and> a \\<in> R.sources t}\"\n      using sources_closed by auto\n\n    lemma targets_char\\<^sub>S\\<^sub>R\\<^sub>T\\<^sub>S:\n    shows \"targets t = {b. Arr t \\<and> b \\<in> R.targets t}\"\n    proof\n      show \"targets t \\<subseteq> {b. Arr t \\<and> b \\<in> R.targets t}\"\n      proof\n        fix b\n        assume b: \"b \\<in> targets t\"\n        show \"b \\<in> {b. Arr t \\<and> b \\<in> R.targets t}\"\n        proof\n          have \"Arr t\"\n            using arr_iff_has_target b by force\n          moreover have \"Arr b\"\n            using b by blast\n          moreover have \"b \\<in> R.targets t\"\n            by (metis R.in_targetsI b calculation(1) con_char in_targetsE\n                arr_char ide_char trg_char)\n          ultimately show \"Arr t \\<and> b \\<in> R.targets t\" by blast\n        qed\n      qed\n      show \"{b. Arr t \\<and> b \\<in> R.targets t} \\<subseteq> targets t\"\n      proof\n        fix b\n        assume b: \"b \\<in> {b. Arr t \\<and> b \\<in> R.targets t}\"\n        show \"b \\<in> targets t\"\n        proof (intro in_targetsI)\n          show \"ide b\"\n            using b\n            by (metis R.arrE ide_char inclusion mem_Collect_eq R.sources_resid\n                R.target_is_ide resid_closed sources_closed subset_eq)\n          show \"con (trg t) b\"\n            using b\n            using \\<open>ide b\\<close> ide_trg trg_char by auto\n        qed\n      qed\n    qed\n\n    lemma prfx_char\\<^sub>S\\<^sub>R\\<^sub>T\\<^sub>S:\n    shows \"prfx t u \\<longleftrightarrow> Arr t \\<and> Arr u \\<and> R.prfx t u\"\n      by (metis R.prfx_implies_con con_char ide_char prfx_implies_con resid_closed resid_def)\n\n    lemma cong_char\\<^sub>S\\<^sub>R\\<^sub>T\\<^sub>S:\n    shows \"cong t u \\<longleftrightarrow> Arr t \\<and> Arr u \\<and> R.cong t u\"\n      using prfx_char\\<^sub>S\\<^sub>R\\<^sub>T\\<^sub>S by force\n\n    lemma inclusion_is_simulation:\n    shows \"simulation resid R (\\<lambda>t. if arr t then t else null)\"\n      using resid_closed resid_def\n      by unfold_locales auto\n\n    interpretation P\\<^sub>R: paths_in_rts R\n      ..\n    interpretation P: paths_in_rts resid\n      ..\n\n    lemma path_reflection:\n    shows \"\\<lbrakk>P\\<^sub>R.Arr T; set T \\<subseteq> Collect Arr\\<rbrakk> \\<Longrightarrow> P.Arr T\"\n      apply (induct T)\n       apply simp\n    proof -\n      fix t T\n      assume ind: \"\\<lbrakk>P\\<^sub>R.Arr T; set T \\<subseteq> Collect Arr\\<rbrakk> \\<Longrightarrow> P.Arr T\"\n      assume tT: \"P\\<^sub>R.Arr (t # T)\"\n      assume set: \"set (t # T) \\<subseteq> Collect Arr\"\n      have 1: \"R.arr t\"\n        using tT\n        by (metis P\\<^sub>R.Arr_imp_arr_hd list.sel(1))\n      show \"P.Arr (t # T)\"\n      proof (cases \"T = []\")\n        show \"T = [] \\<Longrightarrow> ?thesis\"\n          using 1 set by simp\n        assume T: \"T \\<noteq> []\"\n        show ?thesis\n        proof\n          show \"arr t\"\n            using 1 arr_char set by simp\n          show \"P.Arr T\"\n            using T tT P\\<^sub>R.Arr_imp_Arr_tl\n            by (metis ind insert_subset list.sel(3) list.simps(15) set)\n          show \"targets t \\<subseteq> P.Srcs T\"\n          proof -\n            have \"targets t \\<subseteq> R.targets t\"\n              using targets_char\\<^sub>S\\<^sub>R\\<^sub>T\\<^sub>S by blast\n            also have \"... \\<subseteq> R.sources (hd T)\"\n              using T tT\n              by (metis P\\<^sub>R.Arr.simps(3) P\\<^sub>R.Srcs_simp\\<^sub>P list.collapse)\n            also have \"... \\<subseteq> P.Srcs T\"\n              using P.Arr_imp_arr_hd P.Srcs_simp\\<^sub>P \\<open>P.Arr T\\<close> sources_char\\<^sub>S\\<^sub>R\\<^sub>T\\<^sub>S by force\n            finally show ?thesis by blast\n          qed\n        qed\n      qed\n    qed\n\n  end\n\n  locale sub_weakly_extensional_rts =\n    sub_rts +\n    R: weakly_extensional_rts R\n  begin\n\n    sublocale weakly_extensional_rts resid\n      apply unfold_locales\n      using R.weak_extensionality cong_char\\<^sub>S\\<^sub>R\\<^sub>T\\<^sub>S\n      by blast\n\n    lemma is_weakly_extensional_rts:\n    shows \"weakly_extensional_rts resid\"\n      ..\n\n    lemma src_char:\n    shows \"src t = (if arr t then R.src t else null)\"\n    proof (cases \"arr t\")\n      show \"\\<not> arr t \\<Longrightarrow> ?thesis\"\n        by (simp add: src_def)\n      assume t: \"arr t\"\n      show ?thesis\n      proof (intro src_eqI)\n        show \"ide (if arr t then R.src t else null)\"\n          using t sources_closed inclusion R.src_in_sources by auto\n        show \"con (if arr t then R.src t else null) t\"\n          using t con_char\n          by (metis (full_types) R.con_sym R.in_sourcesE R.src_in_sources\n              \\<open>ide (if arr t then R.src t else null)\\<close> arr_char ide_char inclusion)\n      qed\n    qed\n\n  end\n\n  text \\<open>\n    Here we justify the terminology ``normal sub-RTS'', which was introduced earlier,\n    by showing that a normal sub-RTS really is a sub-RTS.\n  \\<close>\n\n  lemma (in normal_sub_rts) is_sub_rts:\n  shows \"sub_rts resid (\\<lambda>t. t \\<in> \\<NN>)\"\n    using elements_are_arr ide_closed\n    apply unfold_locales\n      apply auto[2]\n    by (meson R.con_imp_coinitial R.con_sym forward_stable)\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/ResiduatedTransitionSystem/ResiduatedTransitionSystem.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.843895106480586, "lm_q2_score": 0.8539127566694178, "lm_q1q2_score": 0.720612796714669}}
{"text": "(*\n * Copyright Brian Huffman, PSU; Jeremy Dawson and Gerwin Klein, NICTA\n *\n * SPDX-License-Identifier: BSD-2-Clause\n *)\n\nsection \\<open>Bitwise Operations on integers\\<close>\n\ntheory Bits_Int\n  imports\n    \"HOL-Library.Word\"\n    Traditional_Infix_Syntax\nbegin\n\nsubsection \\<open>Implicit bit representation of \\<^typ>\\<open>int\\<close>\\<close>\n\nabbreviation (input) bin_last :: \"int \\<Rightarrow> bool\"\n  where \"bin_last \\<equiv> odd\"\n\nlemma bin_last_def:\n  \"bin_last w \\<longleftrightarrow> w mod 2 = 1\"\n  by (fact odd_iff_mod_2_eq_one)\n\nabbreviation (input) bin_rest :: \"int \\<Rightarrow> int\"\n  where \"bin_rest w \\<equiv> w div 2\"\n\nlemma bin_last_numeral_simps [simp]:\n  \"\\<not> odd (0 :: int)\"\n  \"odd (1 :: int)\"\n  \"odd (- 1 :: int)\"\n  \"odd (Numeral1 :: int)\"\n  \"\\<not> odd (numeral (Num.Bit0 w) :: int)\"\n  \"odd (numeral (Num.Bit1 w) :: int)\"\n  \"\\<not> odd (- numeral (Num.Bit0 w) :: int)\"\n  \"odd (- numeral (Num.Bit1 w) :: int)\"\n  by simp_all\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\n\nlemma bin_rl_eqI: \"\\<lbrakk>bin_rest x = bin_rest y; odd x = odd y\\<rbrakk> \\<Longrightarrow> x = y\"\n  by (auto elim: oddE)\n\n\n\nlemma bin_rest_gt_0 [simp]: \"bin_rest x > 0 \\<longleftrightarrow> x > 1\"\n  by auto\n\n\nsubsection \\<open>Bit projection\\<close>\n\nabbreviation (input) bin_nth :: \\<open>int \\<Rightarrow> nat \\<Rightarrow> bool\\<close>\n  where \\<open>bin_nth \\<equiv> bit\\<close>\n\nlemma bin_nth_eq_iff: \"bin_nth x = bin_nth y \\<longleftrightarrow> x = y\"\n  by (simp add: bit_eq_iff fun_eq_iff)\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  by (fact bit_eq_iff)\n\nlemma bin_nth_zero [simp]: \"\\<not> bin_nth 0 n\"\n  by simp\n\nlemma bin_nth_1 [simp]: \"bin_nth 1 n \\<longleftrightarrow> n = 0\"\n  by (cases n) (simp_all add: bit_Suc)\n\nlemma bin_nth_minus1 [simp]: \"bin_nth (- 1) n\"\n  by (induction n) (simp_all add: bit_Suc)\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 bit_Suc)\n\nlemmas bin_nth_numeral_simps [simp] =\n  bin_nth_numeral [OF bin_rest_numeral_simps(8)]\n\nlemmas bin_nth_simps =\n  bit_0 bit_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  by (auto simp add: bit_exp_iff)\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: bit_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))\"\n  by (cases n; simp)+\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  by (simp_all add: bin_sign_def)\n\nlemma bin_sign_rest [simp]: \"bin_sign (bin_rest w) = bin_sign w\"\n  by (simp add: bin_sign_def)\n\nabbreviation (input) bintrunc :: \\<open>nat \\<Rightarrow> int \\<Rightarrow> int\\<close>\n  where \\<open>bintrunc \\<equiv> take_bit\\<close>\n\nlemma bintrunc_mod2p: \"bintrunc n w = w mod 2 ^ n\"\n  by (fact take_bit_eq_mod)\n\nabbreviation (input) sbintrunc :: \\<open>nat \\<Rightarrow> int \\<Rightarrow> int\\<close>\n  where \\<open>sbintrunc \\<equiv> signed_take_bit\\<close>\n\nabbreviation (input) norm_sint :: \\<open>nat \\<Rightarrow> int \\<Rightarrow> int\\<close>\n  where \\<open>norm_sint n \\<equiv> signed_take_bit (n - 1)\\<close>\n\nlemma sbintrunc_mod2p: \"sbintrunc n w = (w + 2 ^ n) mod 2 ^ Suc n - 2 ^ n\"\n  by (simp add: bintrunc_mod2p signed_take_bit_eq_take_bit_shift)\n\nlemma sbintrunc_eq_take_bit:\n  \\<open>sbintrunc n k = take_bit (Suc n) (k + 2 ^ n) - 2 ^ n\\<close>\n  by (fact signed_take_bit_eq_take_bit_shift)\n\nlemma sign_bintr: \"bin_sign (bintrunc n w) = 0\"\n  by (simp add: bin_sign_def)\n\nlemma bintrunc_n_0: \"bintrunc n 0 = 0\"\n  by (fact take_bit_of_0)\n\nlemma sbintrunc_n_0: \"sbintrunc n 0 = 0\"\n  by (fact signed_take_bit_of_0)\n\nlemma sbintrunc_n_minus1: \"sbintrunc n (- 1) = -1\"\n  by (fact signed_take_bit_of_minus_1)\n\nlemma bintrunc_Suc_numeral:\n  \"bintrunc (Suc n) 1 = 1\"\n  \"bintrunc (Suc n) (- 1) = 1 + 2 * bintrunc n (- 1)\"\n  \"bintrunc (Suc n) (numeral (Num.Bit0 w)) = 2 * bintrunc n (numeral w)\"\n  \"bintrunc (Suc n) (numeral (Num.Bit1 w)) = 1 + 2 * bintrunc n (numeral w)\"\n  \"bintrunc (Suc n) (- numeral (Num.Bit0 w)) = 2 * bintrunc n (- numeral w)\"\n  \"bintrunc (Suc n) (- numeral (Num.Bit1 w)) = 1 + 2 * bintrunc n (- numeral (w + Num.One))\"\n  by (simp_all add: take_bit_Suc)\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)) = 2 * sbintrunc n (numeral w)\"\n  \"sbintrunc (Suc n) (numeral (Num.Bit1 w)) = 1 + 2 * sbintrunc n (numeral w)\"\n  \"sbintrunc (Suc n) (- numeral (Num.Bit0 w)) = 2 * sbintrunc n (- numeral w)\"\n  \"sbintrunc (Suc n) (- numeral (Num.Bit1 w)) = 1 + 2 * sbintrunc n (- numeral (w + Num.One))\"\n  by (simp_all add: signed_take_bit_Suc)\n\nlemma bin_sign_lem: \"(bin_sign (sbintrunc n bin) = -1) = bit bin n\"\n  by (simp add: bin_sign_def)\n\nlemma nth_bintr: \"bin_nth (bintrunc m w) n \\<longleftrightarrow> n < m \\<and> bin_nth w n\"\n  by (fact bit_take_bit_iff)\n\nlemma nth_sbintr: \"bin_nth (sbintrunc m w) n = (if n < m then bin_nth w n else bin_nth w m)\"\n  by (simp add: bit_signed_take_bit_iff min_def)\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 bit_double_iff [of \\<open>numeral w :: int\\<close> n]\n  by (auto intro: exI [of _ \\<open>n - 1\\<close>])\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 even_bit_succ_iff [of \\<open>2 * numeral w :: int\\<close> n]\n    bit_double_iff [of \\<open>numeral w :: int\\<close> n]\n  by auto\n\nlemma bintrunc_bintrunc_l: \"n \\<le> m \\<Longrightarrow> bintrunc m (bintrunc n w) = bintrunc n w\"\n  by simp\n\nlemma sbintrunc_sbintrunc_l: \"n \\<le> m \\<Longrightarrow> sbintrunc m (sbintrunc n w) = sbintrunc n w\"\n  by (simp add: min_def)\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 take_bit_take_bit)\n\nlemma sbintrunc_sbintrunc_min [simp]: \"sbintrunc m (sbintrunc n w) = sbintrunc (min m n) w\"\n  by (rule signed_take_bit_signed_take_bit)\n\nlemmas sbintrunc_Suc_Pls =\n  signed_take_bit_Suc [where a=\"0::int\", simplified bin_last_numeral_simps bin_rest_numeral_simps]\n\nlemmas sbintrunc_Suc_Min =\n  signed_take_bit_Suc [where a=\"-1::int\", simplified bin_last_numeral_simps bin_rest_numeral_simps]\n\nlemmas sbintrunc_Sucs = sbintrunc_Suc_Pls sbintrunc_Suc_Min\n  sbintrunc_Suc_numeral\n\nlemmas sbintrunc_Pls =\n  signed_take_bit_0 [where a=\"0::int\", simplified bin_last_numeral_simps bin_rest_numeral_simps]\n\nlemmas sbintrunc_Min =\n  signed_take_bit_0 [where a=\"-1::int\", simplified bin_last_numeral_simps bin_rest_numeral_simps]\n\nlemmas sbintrunc_0_simps =\n  sbintrunc_Pls sbintrunc_Min\n\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 sbintrunc_minus_simps =\n  sbintrunc_Sucs [THEN [2] sbintrunc_minus [symmetric, THEN trans]]\n\nlemma sbintrunc_BIT_I:\n  \\<open>0 < n \\<Longrightarrow>\n  sbintrunc (n - 1) 0 = y \\<Longrightarrow>\n  sbintrunc n 0 = 2 * y\\<close>\n  by simp\n\nlemma sbintrunc_Suc_Is:\n  \\<open>sbintrunc n (- 1) = y \\<Longrightarrow>\n  sbintrunc (Suc n) (- 1) = 1 + 2 * y\\<close>\n  by auto\n\nlemma sbintrunc_Suc_lem: \"sbintrunc (Suc n) x = y \\<Longrightarrow> m = Suc n \\<Longrightarrow> sbintrunc m x = y\"\n  by (rule ssubst)\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  by (rule take_bit_signed_take_bit)\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) simp_all\n\nlemma sbintrunc_bintrunc' [simp]: \"0 < n \\<Longrightarrow> sbintrunc (n - 1) (bintrunc n w) = sbintrunc (n - 1) w\"\n  by (cases n) simp_all\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)\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 = of_bool (odd x) + 2 * bintrunc (pred_numeral k) (x div 2)\"\n  by (simp add: numeral_eq_Suc take_bit_Suc mod_2_eq_odd)\n\nlemma sbintrunc_numeral:\n  \"sbintrunc (numeral k) x = of_bool (odd x) + 2 * sbintrunc (pred_numeral k) (x div 2)\"\n  by (simp add: numeral_eq_Suc signed_take_bit_Suc mod2_eq_if)\n\nlemma bintrunc_numeral_simps [simp]:\n  \"bintrunc (numeral k) (numeral (Num.Bit0 w)) =\n    2 * bintrunc (pred_numeral k) (numeral w)\"\n  \"bintrunc (numeral k) (numeral (Num.Bit1 w)) =\n    1 + 2 * bintrunc (pred_numeral k) (numeral w)\"\n  \"bintrunc (numeral k) (- numeral (Num.Bit0 w)) =\n    2 * bintrunc (pred_numeral k) (- numeral w)\"\n  \"bintrunc (numeral k) (- numeral (Num.Bit1 w)) =\n    1 + 2 * bintrunc (pred_numeral k) (- numeral (w + Num.One))\"\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)) =\n    2 * sbintrunc (pred_numeral k) (numeral w)\"\n  \"sbintrunc (numeral k) (numeral (Num.Bit1 w)) =\n    1 + 2 * sbintrunc (pred_numeral k) (numeral w)\"\n  \"sbintrunc (numeral k) (- numeral (Num.Bit0 w)) =\n    2 * sbintrunc (pred_numeral k) (- numeral w)\"\n  \"sbintrunc (numeral k) (- numeral (Num.Bit1 w)) =\n    1 + 2 * sbintrunc (pred_numeral k) (- numeral (w + Num.One))\"\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  by (auto simp add: take_bit_eq_mod image_iff) (metis mod_pos_pos_trivial)\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}\"\nproof -\n  have \\<open>surj (\\<lambda>k::int. k + 2 ^ n)\\<close>\n    by (rule surjI [of _ \\<open>(\\<lambda>k. k - 2 ^ n)\\<close>]) simp\n  moreover have \\<open>sbintrunc n = ((\\<lambda>k. k - 2 ^ n) \\<circ> take_bit (Suc n) \\<circ> (\\<lambda>k. k + 2 ^ n))\\<close>\n    by (simp add: sbintrunc_eq_take_bit fun_eq_iff)\n  ultimately show ?thesis\n    apply (simp only: fun.set_map range_bintrunc)\n    apply (auto simp add: image_iff)\n    apply presburger\n    done\nqed\n\nlemma sbintrunc_inc:\n  \\<open>k + 2 ^ Suc n \\<le> sbintrunc n k\\<close> if \\<open>k < - (2 ^ n)\\<close>\n  using that by (fact signed_take_bit_int_greater_eq)\n\nlemma sbintrunc_dec:\n  \\<open>sbintrunc n k \\<le> k - 2 ^ (Suc n)\\<close> if \\<open>k \\<ge> 2 ^ n\\<close>\n  using that by (fact signed_take_bit_int_less_eq)\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: stable_imp_take_bit_eq)\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 (simp add: take_bit_rec [of n bin])\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 simp add: take_bit_Suc)\n\nlemma bin_rest_strunc: \"bin_rest (sbintrunc (Suc n) bin) = sbintrunc n (bin_rest bin)\"\n  by (simp add: signed_take_bit_Suc)\n\nlemma bintrunc_rest [simp]: \"bintrunc n (bin_rest (bintrunc n bin)) = bin_rest (bintrunc n bin)\"\n  by (induct n arbitrary: bin) (simp_all add: take_bit_Suc)\n\nlemma sbintrunc_rest [simp]: \"sbintrunc n (bin_rest (sbintrunc n bin)) = bin_rest (sbintrunc n bin)\"\n  by (induct n arbitrary: bin) (simp_all add: signed_take_bit_Suc mod2_eq_if)\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\ndefinition bin_split :: \\<open>nat \\<Rightarrow> int \\<Rightarrow> int \\<times> int\\<close>\n  where [simp]: \\<open>bin_split n k = (drop_bit n k, take_bit n k)\\<close>\n\n\n\nabbreviation (input) bin_cat :: \\<open>int \\<Rightarrow> nat \\<Rightarrow> int \\<Rightarrow> int\\<close>\n  where \\<open>bin_cat k n l \\<equiv> concat_bit n l k\\<close>\n\nlemma bin_cat_eq_push_bit_add_take_bit:\n  \\<open>bin_cat k n l = push_bit n k + take_bit n l\\<close>\n  by (simp add: concat_bit_eq)\n\nlemma bin_sign_cat: \"bin_sign (bin_cat x n y) = bin_sign x\"\nproof -\n  have \\<open>0 \\<le> x\\<close> if \\<open>0 \\<le> x * 2 ^ n + y mod 2 ^ n\\<close>\n  proof -\n    have \\<open>y mod 2 ^ n < 2 ^ n\\<close>\n      using pos_mod_bound [of \\<open>2 ^ n\\<close> y] by simp\n    then have \\<open>\\<not> y mod 2 ^ n \\<ge> 2 ^ n\\<close>\n      by (simp add: less_le)\n    with that have \\<open>x \\<noteq> - 1\\<close>\n      by auto\n    have *: \\<open>- 1 \\<le> (- (y mod 2 ^ n)) div 2 ^ n\\<close>\n      by (simp add: zdiv_zminus1_eq_if)\n    from that have \\<open>- (y mod 2 ^ n) \\<le> x * 2 ^ n\\<close>\n      by simp\n    then have \\<open>(- (y mod 2 ^ n)) div 2 ^ n \\<le> (x * 2 ^ n) div 2 ^ n\\<close>\n      using zdiv_mono1 zero_less_numeral zero_less_power by blast\n    with * have \\<open>- 1 \\<le> x * 2 ^ n div 2 ^ n\\<close> by simp\n    with \\<open>x \\<noteq> - 1\\<close> show ?thesis\n      by simp\n  qed\n  then show ?thesis\n    by (simp add: bin_sign_def not_le not_less bin_cat_eq_push_bit_add_take_bit push_bit_eq_mult take_bit_eq_mod)\nqed\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 (fact concat_bit_assoc)\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  by (fact concat_bit_assoc_sym)\n\ndefinition bin_rcat :: \\<open>nat \\<Rightarrow> int list \\<Rightarrow> int\\<close>\n  where \\<open>bin_rcat n = horner_sum (take_bit n) (2 ^ n) \\<circ> rev\\<close>\n\nlemma bin_rcat_eq_foldl:\n  \\<open>bin_rcat n = foldl (\\<lambda>u v. bin_cat u n v) 0\\<close>\nproof\n  fix ks :: \\<open>int list\\<close>\n  show \\<open>bin_rcat n ks = foldl (\\<lambda>u v. bin_cat u n v) 0 ks\\<close>\n    by (induction ks rule: rev_induct)\n      (simp_all add: bin_rcat_def concat_bit_eq push_bit_eq_mult)\nqed\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\nvalue \\<open>bin_rsplit 1705 (3, 88)\\<close>\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  by (simp add: bit_concat_bit_iff)\n\nlemma bin_nth_drop_bit_iff:\n  \\<open>bin_nth (drop_bit n c) k \\<longleftrightarrow> bin_nth c (n + k)\\<close>\n  by (simp add: bit_drop_bit_eq)\n\nlemma bin_nth_take_bit_iff:\n  \\<open>bin_nth (take_bit n c) k \\<longleftrightarrow> k < n \\<and> bin_nth c k\\<close>\n  by (fact bit_take_bit_iff)\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  by (auto simp add: bin_nth_drop_bit_iff bin_nth_take_bit_iff)\n\nlemma bin_cat_zero [simp]: \"bin_cat 0 n w = bintrunc n w\"\n  by (simp add: bin_cat_eq_push_bit_add_take_bit)\n\nlemma bintr_cat1: \"bintrunc (k + n) (bin_cat a n b) = bin_cat (bintrunc k a) n b\"\n  by (metis bin_cat_assoc bin_cat_zero)\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\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 (simp add: bin_cat_eq_push_bit_add_take_bit)\n\nlemma split_bintrunc: \"bin_split n c = (a, b) \\<Longrightarrow> b = bintrunc n c\"\n  by simp\n\nlemma bin_cat_split: \"bin_split n w = (u, v) \\<Longrightarrow> w = bin_cat u n v\"\n  by (auto simp add: bin_cat_eq_push_bit_add_take_bit bits_ident)\n\nlemma drop_bit_bin_cat_eq:\n  \\<open>drop_bit n (bin_cat v n w) = v\\<close>\n  by (rule bit_eqI) (simp add: bit_drop_bit_eq bit_concat_bit_iff)\n\nlemma take_bit_bin_cat_eq:\n  \\<open>take_bit n (bin_cat v n w) = take_bit n w\\<close>\n  by (rule bit_eqI) (simp add: bit_concat_bit_iff)\n\nlemma bin_split_cat: \"bin_split n (bin_cat v n w) = (v, bintrunc n w)\"\n  by (simp add: drop_bit_bin_cat_eq take_bit_bin_cat_eq)\n\nlemma bin_split_zero [simp]: \"bin_split n 0 = (0, 0)\"\n  by simp\n\nlemma bin_split_minus1 [simp]:\n  \"bin_split n (- 1) = (- 1, bintrunc n (- 1))\"\n  by simp\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 drop_bit_Suc take_bit_Suc mod_2_eq_odd 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 drop_bit_Suc take_bit_Suc mod_2_eq_odd split: prod.split_asm)\n  done\n\nlemma bin_cat_num: \"bin_cat a n b = a * 2 ^ n + bintrunc n b\"\n  by (simp add: bin_cat_eq_push_bit_add_take_bit push_bit_eq_mult)\n\nlemma bin_split_num: \"bin_split n b = (b div 2 ^ n, b mod 2 ^ n)\"\n  by (simp add: drop_bit_eq_div take_bit_eq_mod)\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\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, of_bool (odd w) + 2 * w2))\"\n  by (simp add: take_bit_rec drop_bit_rec mod_2_eq_odd)\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 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 (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 (simp add: bit_drop_bit_eq ac_simps)\n  apply (simp add: bit_take_bit_iff 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 (simp add: ac_simps)\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 add: drop_bit_take_bit)\n  apply (case_tac \\<open>x < n\\<close>)\n  apply (simp_all add: not_less min_def)\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_eq_foldl)\n  apply (rule_tac xs = ws in rev_induct)\n   apply clarsimp\n  apply clarsimp\n  apply (subst rsplit_aux_alts)\n  apply (simp add: drop_bit_bin_cat_eq take_bit_bin_cat_eq)\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\" [of \\<open>bin_split n w\\<close> \\<open>drop_bit n w\\<close> \\<open>take_bit n w\\<close>] \\<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) (drop_bit n w) (take_bit n w # cs))\"\n      using bin_rsplit_aux_len by fastforce\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 = of_bool b + 2 * bin_rest w\"\n  | Suc: \"bin_sc (Suc n) b w = of_bool (odd w) + 2 * bin_sc n b (w div 2)\"\n\nlemma bin_nth_sc [simp]: \"bit (bin_sc n b w) n \\<longleftrightarrow> b\"\n  by (induction n arbitrary: w) (simp_all add: bit_Suc)\n\nlemma bin_sc_sc_same [simp]: \"bin_sc n c (bin_sc n b w) = bin_sc n c w\"\n  by (induction n arbitrary: w) (simp_all add: bit_Suc)\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  apply (induct n arbitrary: w m)\n   apply (case_tac m; simp add: bit_Suc)\n  apply (case_tac m; simp add: bit_Suc)\n  done\n\nlemma bin_sc_eq:\n  \\<open>bin_sc n False = unset_bit n\\<close>\n  \\<open>bin_sc n True = Bit_Operations.set_bit n\\<close>\n  by (simp_all add: fun_eq_iff bit_eq_iff)\n    (simp_all add: bin_nth_sc_gen bit_set_bit_iff bit_unset_bit_iff)\n\nlemma bin_sc_nth [simp]: \"bin_sc n (bin_nth w n) w = w\"\n  by (rule bit_eqI) (simp add: bin_nth_sc_gen)\n\nlemma bin_sign_sc [simp]: \"bin_sign (bin_sc n b w) = bin_sign w\"\nproof (induction n arbitrary: w)\n  case 0\n  then show ?case\n    by (auto simp add: bin_sign_def) (use bin_rest_ge_0 in fastforce)\nnext\n  case (Suc n)\n  from Suc [of \\<open>w div 2\\<close>]\n  show ?case by (auto simp add: bin_sign_def split: if_splits)\nqed\n\nlemma bin_sc_bintr [simp]:\n  \"bintrunc m (bin_sc n x (bintrunc m w)) = bintrunc m (bin_sc n x w)\"\n  apply (cases x)\n   apply (simp_all add: bin_sc_eq bit_eq_iff)\n   apply (auto simp add: bit_take_bit_iff bit_set_bit_iff bit_unset_bit_iff)\n  done\n\nlemma bin_clr_le: \"bin_sc n False w \\<le> w\"\n  by (simp add: bin_sc_eq unset_bit_less_eq)\n\nlemma bin_set_ge: \"bin_sc n True w \\<ge> w\"\n  by (simp add: bin_sc_eq set_bit_greater_eq)\n\nlemma bintr_bin_clr_le: \"bintrunc n (bin_sc m False w) \\<le> bintrunc n w\"\n  by (simp add: bin_sc_eq take_bit_unset_bit_eq unset_bit_less_eq)\n\nlemma bintr_bin_set_ge: \"bintrunc n (bin_sc m True w) \\<ge> bintrunc n w\"\n  by (simp add: bin_sc_eq take_bit_set_bit_eq set_bit_greater_eq)\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    of_bool (odd w) + 2 * bin_sc (pred_numeral k) b (w div 2)\"\n  by (simp add: numeral_eq_Suc)\n\nlemmas bin_sc_minus_simps =\n  bin_sc_simps (2,3,4) [THEN [2] trans, OF bin_sc_minus [THEN sym]]\n\ninstance int :: semiring_bit_syntax ..\n\nlemma test_bit_int_def [iff]:\n  \"i !! n \\<longleftrightarrow> bin_nth i n\"\n  by (simp add: test_bit_eq_bit)\n\nlemma shiftl_int_def:\n  \"shiftl x n = x * 2 ^ n\" for x :: int\n  by (simp add: push_bit_int_def shiftl_eq_push_bit)\n\nlemma shiftr_int_def:\n  \"shiftr x n = x div 2 ^ n\" for x :: int\n  by (simp add: drop_bit_int_def shiftr_eq_drop_bit)\n\n\nsubsubsection \\<open>Basic simplification rules\\<close>\n\nlemmas int_not_def = not_int_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  by (simp_all add: not_int_def)\n\nlemma int_not_not: \"NOT (NOT x) = x\"\n  for x :: int\n  by (fact bit.double_compl)\n\nlemma int_and_0 [simp]: \"0 AND x = 0\"\n  for x :: int\n  by (fact bit.conj_zero_left)\n\nlemma int_and_m1 [simp]: \"-1 AND x = x\"\n  for x :: int\n  by (fact bit.conj_one_left)\n\nlemma int_or_zero [simp]: \"0 OR x = x\"\n  for x :: int\n  by (fact bit.disj_zero_left)\n\nlemma int_or_minus1 [simp]: \"-1 OR x = -1\"\n  for x :: int\n  by (fact bit.disj_one_left)\n\nlemma int_xor_zero [simp]: \"0 XOR x = x\"\n  for x :: int\n  by (fact bit.xor_zero_left)\n\n\nsubsubsection \\<open>Binary destructors\\<close>\n\nlemma bin_rest_NOT [simp]: \"bin_rest (NOT x) = NOT (bin_rest x)\"\n  by (fact not_int_div_2)\n\nlemma bin_last_NOT [simp]: \"bin_last (NOT x) \\<longleftrightarrow> \\<not> bin_last x\"\n  by simp\n\nlemma bin_rest_AND [simp]: \"bin_rest (x AND y) = bin_rest x AND bin_rest y\"\n  by (subst and_int_rec) auto\n\nlemma bin_last_AND [simp]: \"bin_last (x AND y) \\<longleftrightarrow> bin_last x \\<and> bin_last y\"\n  by (subst and_int_rec) auto\n\nlemma bin_rest_OR [simp]: \"bin_rest (x OR y) = bin_rest x OR bin_rest y\"\n  by (subst or_int_rec) auto\n\nlemma bin_last_OR [simp]: \"bin_last (x OR y) \\<longleftrightarrow> bin_last x \\<or> bin_last y\"\n  by (subst or_int_rec) auto\n\nlemma bin_rest_XOR [simp]: \"bin_rest (x XOR y) = bin_rest x XOR bin_rest y\"\n  by (subst xor_int_rec) auto\n\nlemma bin_last_XOR [simp]: \"bin_last (x XOR y) \\<longleftrightarrow> (bin_last x \\<or> bin_last y) \\<and> \\<not> (bin_last x \\<and> bin_last y)\"\n  by (subst xor_int_rec) auto\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 (simp_all add: bit_and_iff bit_or_iff bit_xor_iff bit_not_iff)\n\n\nsubsubsection \\<open>Derived properties\\<close>\n\nlemma int_xor_minus1 [simp]: \"-1 XOR x = NOT x\"\n  for x :: int\n  by (fact bit.xor_one_left)\n\nlemma int_xor_extra_simps [simp]:\n  \"w XOR 0 = w\"\n  \"w XOR -1 = NOT w\"\n  for w :: int\n  by simp_all\n\nlemma int_or_extra_simps [simp]:\n  \"w OR 0 = w\"\n  \"w OR -1 = -1\"\n  for w :: int\n  by simp_all\n\nlemma int_and_extra_simps [simp]:\n  \"w AND 0 = 0\"\n  \"w AND -1 = w\"\n  for w :: int\n  by simp_all\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 (simp_all add: ac_simps)\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 simp_all\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\n\nlemma bin_last_neg_numeral_BitM [simp]:\n  \"bin_last (- numeral (Num.BitM w))\"\n  by simp\n\n\nsubsubsection \\<open>Interactions with arithmetic\\<close>\n\nlemma le_int_or: \"bin_sign y = 0 \\<Longrightarrow> x \\<le> x OR y\"\n  for x y :: int\n  by (simp add: bin_sign_def or_greater_eq split: if_splits)\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  by (simp add: not_int_def)\n\nlemma AND_mod: \"x AND (2 ^ n - 1) = x mod 2 ^ n\"\n  for x :: int\n  by (simp flip: take_bit_eq_mod add: take_bit_eq_mask mask_eq_exp_minus_1)\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 simp_all\n\nlemma bin_trunc_xor: \"bintrunc n (bintrunc n x XOR bintrunc n y) = bintrunc n (x XOR y)\"\n  by simp\n\nlemma bin_trunc_not: \"bintrunc n (NOT (bintrunc n x)) = bintrunc n (NOT x)\"\n  by (fact take_bit_not_take_bit)\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\"\n  by (fact bit.conj_disj_distrib)\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\"\n  by simp\n\nlemma int_nand_same_middle: fixes x :: int shows \"x AND y AND NOT x = 0\"\n  by (simp add: bit_eq_iff bit_and_iff bit_not_iff)\n\nlemma and_xor_dist: fixes x :: int shows\n  \"x AND (y XOR z) = (x AND y) XOR (x AND z)\"\n  by (fact bit.conj_xor_distrib)\n\nlemma int_and_lt0 [simp]:\n  \\<open>x AND y < 0 \\<longleftrightarrow> x < 0 \\<and> y < 0\\<close> for x y :: int\n  by (fact and_negative_int_iff)\n\nlemma int_and_ge0 [simp]:\n  \\<open>x AND y \\<ge> 0 \\<longleftrightarrow> x \\<ge> 0 \\<or> y \\<ge> 0\\<close> for x y :: int\n  by (fact and_nonnegative_int_iff)\n\nlemma int_and_1: fixes x :: int shows \"x AND 1 = x mod 2\"\n  by (fact and_one_eq)\n\nlemma int_1_and: fixes x :: int shows \"1 AND x = x mod 2\"\n  by (fact one_and_eq)\n\nlemma int_or_lt0 [simp]:\n  \\<open>x OR y < 0 \\<longleftrightarrow> x < 0 \\<or> y < 0\\<close> for x y :: int\n  by (fact or_negative_int_iff)\n\nlemma int_or_ge0 [simp]:\n  \\<open>x OR y \\<ge> 0 \\<longleftrightarrow> x \\<ge> 0 \\<and> y \\<ge> 0\\<close> for x y :: int\n  by (fact or_nonnegative_int_iff)\n\nlemma int_xor_lt0 [simp]:\n  \\<open>x XOR y < 0 \\<longleftrightarrow> (x < 0) \\<noteq> (y < 0)\\<close> for x y :: int\n  by (fact xor_negative_int_iff)\n\nlemma int_xor_ge0 [simp]:\n  \\<open>x XOR y \\<ge> 0 \\<longleftrightarrow> (x \\<ge> 0 \\<longleftrightarrow> y \\<ge> 0)\\<close> for x y :: int\n  by (fact xor_nonnegative_int_iff)\n\nlemma even_conv_AND:\n  \\<open>even i \\<longleftrightarrow> i AND 1 = 0\\<close> for i :: int\n  by (simp add: and_one_eq mod2_eq_if)\n\nlemma bin_last_conv_AND:\n  \"bin_last i \\<longleftrightarrow> i AND 1 \\<noteq> 0\"\n  by (simp add: and_one_eq mod2_eq_if)\n\nlemma bitval_bin_last:\n  \"of_bool (bin_last i) = i AND 1\"\n  by (simp add: and_one_eq mod2_eq_if)\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 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\nlemma int_shiftl_BIT: fixes x :: int\n  shows int_shiftl0 [simp]: \"x << 0 = x\"\n  and int_shiftl_Suc [simp]: \"x << Suc n = 2 * (x << n)\"\n  by (auto simp add: shiftl_int_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)\"\n  by (simp add: bit_push_bit_iff_int shiftl_eq_push_bit)\n\nlemma bin_last_shiftr: \"odd (x >> n) \\<longleftrightarrow> x !! n\" for x :: int\n  by (simp add: shiftr_eq_drop_bit bit_iff_odd_drop_bit)\n\nlemma bin_rest_shiftr [simp]: \"bin_rest (x >> n) = x >> Suc n\"\n  by (simp add: bit_eq_iff shiftr_eq_drop_bit drop_bit_Suc bit_drop_bit_eq drop_bit_half)\n\nlemma bin_nth_shiftr [simp]: \"bin_nth (x >> n) m = bin_nth x (n + m)\"\n  by (simp add: shiftr_eq_drop_bit bit_drop_bit_eq)\n\nlemma bin_nth_conv_AND:\n  fixes x :: int shows\n  \"bin_nth x n \\<longleftrightarrow> x AND (1 << n) \\<noteq> 0\"\n  by (simp add: bit_eq_iff)\n    (auto simp add: shiftl_eq_push_bit bit_and_iff bit_push_bit_iff bit_exp_iff)\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 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]:\n  \"(1 :: int) << numeral w = 2 << pred_numeral w\"\n  using int_shiftl_numeral [of Num.One w] by simp\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)\"\n  by 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\"\n  by (simp add: shiftr_eq_drop_bit)\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 add: shiftr_eq_drop_bit numeral_eq_Suc add_One drop_bit_Suc)\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)\"\n  by (simp_all add: shiftr_eq_drop_bit drop_bit_Suc add_One)\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\"\nproof -\n  from sign y x have \\<open>x \\<ge> 0\\<close> and \\<open>y = 2 ^ n\\<close> and \\<open>x < 2 ^ n\\<close>\n    by (simp_all add: bin_sign_def shiftl_eq_push_bit push_bit_eq_mult split: if_splits)\n  from \\<open>0 \\<le> x\\<close> \\<open>x < 2 ^ n\\<close> \\<open>m < n\\<close> have \\<open>bit x m \\<longleftrightarrow> bit (x - 2 ^ n) m\\<close>\n  proof (induction m arbitrary: x n)\n    case 0\n    then show ?case\n      by simp\n  next\n    case (Suc m)\n    moreover define q where \\<open>q = n - 1\\<close>\n    ultimately have n: \\<open>n = Suc q\\<close>\n      by simp\n    have \\<open>(x - 2 ^ Suc q) div 2 = x div 2 - 2 ^ q\\<close>\n      by simp\n    moreover from Suc.IH [of \\<open>x div 2\\<close> q] Suc.prems\n    have \\<open>bit (x div 2) m \\<longleftrightarrow> bit (x div 2 - 2 ^ q) m\\<close>\n      by (simp add: n)\n    ultimately show ?case\n      by (simp add: bit_Suc n)\n  qed\n  with \\<open>y = 2 ^ n\\<close> show ?thesis\n    by simp\nqed\n\nlemma bin_clr_conv_NAND:\n  \"bin_sc n False i = i AND NOT (1 << n)\"\n  by (induct n arbitrary: i) (rule bin_rl_eqI; simp)+\n\nlemma bin_set_conv_OR:\n  \"bin_sc n True i = i OR (1 << n)\"\n  by (induct n arbitrary: i) (rule bin_rl_eqI; simp)+\n\n\nsubsection \\<open>More lemmas on words\\<close>\n\nlemma word_rcat_eq:\n  \\<open>word_rcat ws = word_of_int (bin_rcat (LENGTH('a::len)) (map uint ws))\\<close>\n  for ws :: \\<open>'a::len word list\\<close>\n  apply (simp add: word_rcat_def bin_rcat_def rev_map)\n  apply transfer\n  apply (simp add: horner_sum_foldr foldr_map comp_def)\n  done\n\nlemma sign_uint_Pls [simp]: \"bin_sign (uint x) = 0\"\n  by (simp add: sign_Pls_ge_0)\n\nlemmas bin_log_bintrs = bin_trunc_not bin_trunc_xor bin_trunc_and bin_trunc_or\n\n\\<comment> \\<open>following definitions require both arithmetic and bit-wise word operations\\<close>\n\n\\<comment> \\<open>to get \\<open>word_no_log_defs\\<close> from \\<open>word_log_defs\\<close>, using \\<open>bin_log_bintrs\\<close>\\<close>\nlemmas wils1 = bin_log_bintrs [THEN word_of_int_eq_iff [THEN iffD2],\n  folded uint_word_of_int_eq, THEN eq_reflection]\n\n\\<comment> \\<open>the binary operations only\\<close>  (* BH: why is this needed? *)\nlemmas word_log_binary_defs =\n  word_and_def word_or_def word_xor_def\n\nlemma setBit_no [simp]: \"setBit (numeral bin) n = word_of_int (bin_sc n True (numeral bin))\"\n  by transfer (simp add: bin_sc_eq)\n\nlemma clearBit_no [simp]:\n  \"clearBit (numeral bin) n = word_of_int (bin_sc n False (numeral bin))\"\n  by transfer (simp add: bin_sc_eq)\n\nlemma eq_mod_iff: \"0 < n \\<Longrightarrow> b = b mod n \\<longleftrightarrow> 0 \\<le> b \\<and> b < n\"\n  for b n :: int\n  by auto (metis pos_mod_conj)+\n\nlemma split_uint_lem: \"bin_split n (uint w) = (a, b) \\<Longrightarrow>\n    a = take_bit (LENGTH('a) - n) a \\<and> b = take_bit (LENGTH('a)) b\"\n  for w :: \"'a::len word\"\n  by transfer (simp add: drop_bit_take_bit ac_simps)\n\n\\<comment> \\<open>limited hom result\\<close>\nlemma word_cat_hom:\n  \"LENGTH('a::len) \\<le> LENGTH('b::len) + LENGTH('c::len) \\<Longrightarrow>\n    (word_cat (word_of_int w :: 'b word) (b :: 'c word) :: 'a word) =\n    word_of_int (bin_cat w (size b) (uint b))\"\n  by transfer (simp add: take_bit_concat_bit_eq)\n\nlemma bintrunc_shiftl:\n  \"take_bit n (m << i) = take_bit (n - i) m << i\"\n  for m :: int\n  by (rule bit_eqI) (auto simp add: bit_take_bit_iff)\n\nlemma uint_shiftl:\n  \"uint (n << i) = take_bit (size n) (uint n << i)\"\n  by transfer (simp add: push_bit_take_bit shiftl_eq_push_bit)\n\nlemma bin_mask_conv_pow2:\n  \"mask n = 2 ^ n - (1 :: int)\"\n  by (fact mask_eq_exp_minus_1)\n\nlemma bin_mask_ge0: \"mask n \\<ge> (0 :: int)\"\n  by (fact mask_nonnegative_int)\n\nlemma and_bin_mask_conv_mod: \"x AND mask n = x mod 2 ^ n\"\n  for x :: int\n  by (simp flip: take_bit_eq_mod add: take_bit_eq_mask)\n\nlemma bin_mask_numeral:\n  \"mask (numeral n) = (1 :: int) + 2 * mask (pred_numeral n)\"\n  by (fact mask_numeral)\n\nlemma bin_nth_mask [simp]: \"bit (mask n :: int) i \\<longleftrightarrow> i < n\"\n  by (simp add: bit_mask_iff)\n\n\n\nlemma bin_mask_p1_conv_shift: \"mask n + 1 = (1 :: int) << n\"\n  by (simp add: bin_mask_conv_pow2 shiftl_int_def)\n\n\n\nlemma sbintrunc_If:\n  \"- 3 * (2 ^ n) \\<le> x \\<and> x < 3 * (2 ^ n)\n    \\<Longrightarrow> sbintrunc n x = (if x < - (2 ^ n) then x + 2 * (2 ^ n)\n        else if x \\<ge> 2 ^ n then x - 2 * (2 ^ n) else x)\"\n  apply (simp add: no_sbintr_alt2, safe)\n   apply (simp add: mod_pos_geq)\n  apply (subst mod_add_self1[symmetric], simp)\n  done\n\nlemma sint_range':\n  \\<open>- (2 ^ (LENGTH('a) - Suc 0)) \\<le> sint x \\<and> sint x < 2 ^ (LENGTH('a) - Suc 0)\\<close>\n  for x :: \\<open>'a::len word\\<close>\n  apply transfer\n  using sbintr_ge sbintr_lt apply auto\n  done\n\nlemma signed_arith_eq_checks_to_ord:\n  \"(sint a + sint b = sint (a + b ))\n    = ((a <=s a + b) = (0 <=s b))\"\n  \"(sint a - sint b = sint (a - b ))\n    = ((0 <=s a - b) = (b <=s a))\"\n  \"(- sint a = sint (- a)) = (0 <=s (- a) = (a <=s 0))\"\n  using sint_range'[where x=a] sint_range'[where x=b]\n  by (simp_all add: sint_word_ariths word_sle_eq word_sless_alt sbintrunc_If)\n\nlemma signed_mult_eq_checks_double_size:\n  assumes mult_le: \"(2 ^ (len_of TYPE ('a) - 1) + 1) ^ 2 \\<le> (2 :: int) ^ (len_of TYPE ('b) - 1)\"\n           and le: \"2 ^ (LENGTH('a) - 1) \\<le> (2 :: int) ^ (len_of TYPE ('b) - 1)\"\n  shows \"(sint (a :: 'a :: len word) * sint b = sint (a * b))\n       = (scast a * scast b = (scast (a * b) :: 'b :: len word))\"\nproof -\n  have P: \"sbintrunc (size a - 1) (sint a * sint b) \\<in> range (sbintrunc (size a - 1))\"\n    by simp\n\n  have abs: \"!! x :: 'a word. abs (sint x) < 2 ^ (size a - 1) + 1\"\n    apply (cut_tac x=x in sint_range')\n    apply (simp add: abs_le_iff word_size)\n    done\n  have abs_ab: \"abs (sint a * sint b) < 2 ^ (LENGTH('b) - 1)\"\n    using abs_mult_less[OF abs[where x=a] abs[where x=b]] mult_le\n    by (simp add: abs_mult power2_eq_square word_size)\n  define r s where \\<open>r = LENGTH('a) - 1\\<close> \\<open>s = LENGTH('b) - 1\\<close>\n  then have \\<open>LENGTH('a) = Suc r\\<close> \\<open>LENGTH('b) = Suc s\\<close>\n    \\<open>size a = Suc r\\<close> \\<open>size b = Suc r\\<close>\n    by (simp_all add: word_size)\n  then show ?thesis\n    using P[unfolded range_sbintrunc] abs_ab le\n    apply clarsimp\n    apply (transfer fixing: r s)\n    apply (auto simp add: signed_take_bit_int_eq_self simp flip: signed_take_bit_eq_iff_take_bit_eq)\n    done\nqed\n\ncode_identifier\n  code_module Bits_Int \\<rightharpoonup>\n  (SML) Bit_Operations and (OCaml) Bit_Operations and (Haskell) Bit_Operations and (Scala) Bit_Operations\n\nend\n", "meta": {"author": "ethereum", "repo": "yul-isabelle", "sha": "4d760a0dabfeab19efc772330be1059021208ad9", "save_path": "github-repos/isabelle/ethereum-yul-isabelle", "path": "github-repos/isabelle/ethereum-yul-isabelle/yul-isabelle-4d760a0dabfeab19efc772330be1059021208ad9/Word_Lib/Bits_Int.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951025545426, "lm_q2_score": 0.8539127492339909, "lm_q1q2_score": 0.7206127870874501}}
{"text": "(*  Title:       Adjunction\n    Author:      Eugene W. Stark <stark@cs.stonybrook.edu>, 2016\n    Maintainer:  Eugene W. Stark <stark@cs.stonybrook.edu>\n*)\n\nchapter Adjunction\n\ntheory Adjunction\nimports Yoneda\nbegin\n\n  text\\<open>\n    This theory defines the notions of adjoint functor and adjunction in various\n    ways and establishes their equivalence.\n    The notions ``left adjoint functor'' and ``right adjoint functor'' are defined\n    in terms of universal arrows.\n    ``Meta-adjunctions'' are defined in terms of natural bijections between hom-sets,\n    where the notion of naturality is axiomatized directly.\n    ``Hom-adjunctions'' formalize the notion of adjunction in terms of natural\n    isomorphisms of hom-functors.\n    ``Unit-counit adjunctions'' define adjunctions in terms of functors equipped\n    with unit and counit natural transformations that satisfy the usual\n    ``triangle identities.''\n    The \\<open>adjunction\\<close> locale is defined as the grand unification of all the\n    definitions, and includes formulas that connect the data from each of them.\n    It is shown that each of the definitions induces an interpretation of the\n    \\<open>adjunction\\<close> locale, so that all the definitions are essentially equivalent.\n    Finally, it is shown that right adjoint functors are unique up to natural\n    isomorphism.\n\n    The reference \\cite{Wikipedia-Adjoint-Functors} was useful in constructing this theory.\n\\<close>\n\n  section \"Left Adjoint Functor\"\n\n  text\\<open>\n    ``@{term e} is an arrow from @{term \"F x\"} to @{term y}.''\n\\<close>\n\n  locale arrow_from_functor =\n    C: category C +\n    D: category D +\n    F: \"functor\" D C F\n    for D :: \"'d comp\"     (infixr \"\\<cdot>\\<^sub>D\" 55)\n    and C :: \"'c comp\"     (infixr \"\\<cdot>\\<^sub>C\" 55)\n    and F :: \"'d \\<Rightarrow> 'c\"\n    and x :: 'd\n    and y :: 'c\n    and e :: 'c +\n    assumes arrow: \"D.ide x \\<and> C.in_hom e (F x) y\"\n  begin\n\n    notation C.in_hom      (\"\\<guillemotleft>_ : _ \\<rightarrow>\\<^sub>C _\\<guillemotright>\")\n    notation D.in_hom      (\"\\<guillemotleft>_ : _ \\<rightarrow>\\<^sub>D _\\<guillemotright>\")\n\n    text\\<open>\n      ``@{term g} is a @{term[source=true] D}-coextension of @{term f} along @{term e}.''\n\\<close>\n\n    definition is_coext :: \"'d \\<Rightarrow> 'c \\<Rightarrow> 'd \\<Rightarrow> bool\"\n    where \"is_coext x' f g \\<equiv> \\<guillemotleft>g : x' \\<rightarrow>\\<^sub>D x\\<guillemotright> \\<and> f = e \\<cdot>\\<^sub>C F g\"\n\n  end\n\n  text\\<open>\n    ``@{term e} is a terminal arrow from @{term \"F x\"} to @{term y}.''\n\\<close>\n\n  locale terminal_arrow_from_functor =\n    arrow_from_functor D C F x y e\n    for D :: \"'d comp\"     (infixr \"\\<cdot>\\<^sub>D\" 55)\n    and C :: \"'c comp\"     (infixr \"\\<cdot>\\<^sub>C\" 55)\n    and F :: \"'d \\<Rightarrow> 'c\"\n    and x :: 'd\n    and y :: 'c\n    and e :: 'c +\n    assumes is_terminal: \"arrow_from_functor D C F x' y f \\<Longrightarrow> (\\<exists>!g. is_coext x' f g)\"\n  begin\n\n    definition the_coext :: \"'d \\<Rightarrow> 'c \\<Rightarrow> 'd\"\n    where \"the_coext x' f = (THE g. is_coext x' f g)\"\n\n    lemma the_coext_prop:\n    assumes \"arrow_from_functor D C F x' y f\"\n    shows \"\\<guillemotleft>the_coext x' f : x' \\<rightarrow>\\<^sub>D x\\<guillemotright>\" and \"f = e \\<cdot>\\<^sub>C F (the_coext x' f)\"\n      using assms is_terminal the_coext_def is_coext_def theI2 [of \"\\<lambda>g. is_coext x' f g\"]\n       apply metis\n      using assms is_terminal the_coext_def is_coext_def theI2 [of \"\\<lambda>g. is_coext x' f g\"]\n      by metis\n\n    lemma the_coext_unique:\n    assumes \"arrow_from_functor D C F x' y f\" and \"is_coext x' f g\"\n    shows \"g = the_coext x' f\"\n      using assms is_terminal the_coext_def the_equality by metis\n\n  end\n\n  text\\<open>\n    A left adjoint functor is a functor \\<open>F: D \\<rightarrow> C\\<close>\n    that enjoys the following universal coextension property: for each object\n    @{term y} of @{term C} there exists an object @{term x} of @{term D} and an\n    arrow \\<open>e \\<in> C.hom (F x) y\\<close> such that for any arrow\n    \\<open>f \\<in> C.hom (F x') y\\<close> there exists a unique \\<open>g \\<in> D.hom x' x\\<close>\n    such that @{term \"f = C e (F g)\"}.\n\\<close>\n\n  locale left_adjoint_functor =\n    C: category C +\n    D: category D +\n    \"functor\" D C F\n    for D :: \"'d comp\"     (infixr \"\\<cdot>\\<^sub>D\" 55)\n    and C :: \"'c comp\"     (infixr \"\\<cdot>\\<^sub>C\" 55)\n    and F :: \"'d \\<Rightarrow> 'c\" +\n    assumes ex_terminal_arrow: \"C.ide y \\<Longrightarrow> (\\<exists>x e. terminal_arrow_from_functor D C F x y e)\"\n  begin\n\n    notation C.in_hom      (\"\\<guillemotleft>_ : _ \\<rightarrow>\\<^sub>C _\\<guillemotright>\")\n    notation D.in_hom      (\"\\<guillemotleft>_ : _ \\<rightarrow>\\<^sub>D _\\<guillemotright>\")\n\n  end\n\n  section \"Right Adjoint Functor\"\n\n  text\\<open>\n    ``@{term e} is an arrow from @{term x} to @{term \"G y\"}.''\n\\<close>\n\n  locale arrow_to_functor =\n    C: category C +\n    D: category D +\n    G: \"functor\" C D G\n    for C :: \"'c comp\"     (infixr \"\\<cdot>\\<^sub>C\" 55)\n    and D :: \"'d comp\"     (infixr \"\\<cdot>\\<^sub>D\" 55)\n    and G :: \"'c \\<Rightarrow> 'd\"\n    and x :: 'd\n    and y :: 'c\n    and e :: 'd +\n    assumes arrow: \"C.ide y \\<and> D.in_hom e x (G y)\"\n  begin\n\n    notation C.in_hom      (\"\\<guillemotleft>_ : _ \\<rightarrow>\\<^sub>C _\\<guillemotright>\")\n    notation D.in_hom      (\"\\<guillemotleft>_ : _ \\<rightarrow>\\<^sub>D _\\<guillemotright>\")\n\n    text\\<open>\n      ``@{term f} is a @{term[source=true] C}-extension of @{term g} along @{term e}.''\n\\<close>\n\n    definition is_ext :: \"'c \\<Rightarrow> 'd \\<Rightarrow> 'c \\<Rightarrow> bool\"\n    where \"is_ext y' g f \\<equiv> \\<guillemotleft>f : y \\<rightarrow>\\<^sub>C y'\\<guillemotright> \\<and> g = G f \\<cdot>\\<^sub>D e\"\n\n  end\n\n  text\\<open>\n    ``@{term e} is an initial arrow from @{term x} to @{term \"G y\"}.''\n\\<close>\n\n  locale initial_arrow_to_functor =\n    arrow_to_functor C D G x y e\n    for C :: \"'c comp\"     (infixr \"\\<cdot>\\<^sub>C\" 55)\n    and D :: \"'d comp\"     (infixr \"\\<cdot>\\<^sub>D\" 55)\n    and G :: \"'c \\<Rightarrow> 'd\"\n    and x :: 'd\n    and y :: 'c\n    and e :: 'd +\n    assumes is_initial: \"arrow_to_functor C D G x y' g \\<Longrightarrow> (\\<exists>!f. is_ext y' g f)\"\n  begin\n\n    definition the_ext :: \"'c \\<Rightarrow> 'd \\<Rightarrow> 'c\"\n    where \"the_ext y' g = (THE f. is_ext y' g f)\"\n\n    lemma the_ext_prop:\n    assumes \"arrow_to_functor C D G x y' g\"\n    shows \"\\<guillemotleft>the_ext y' g : y \\<rightarrow>\\<^sub>C y'\\<guillemotright>\" and \"g = G (the_ext y' g) \\<cdot>\\<^sub>D e\"\n      using assms is_initial the_ext_def is_ext_def theI2 [of \"\\<lambda>f. is_ext y' g f\"]\n       apply metis\n      using assms is_initial the_ext_def is_ext_def theI2 [of \"\\<lambda>f. is_ext y' g f\"]\n      by metis\n\n    lemma the_ext_unique:\n    assumes \"arrow_to_functor C D G x y' g\" and \"is_ext y' g f\"\n    shows \"f = the_ext y' g\"\n      using assms is_initial the_ext_def the_equality by metis\n\n  end\n\n  text\\<open>\n    A right adjoint functor is a functor \\<open>G: C \\<rightarrow> D\\<close>\n    that enjoys the following universal extension property:\n    for each object @{term x} of @{term D} there exists an object @{term y} of @{term C}\n    and an arrow \\<open>e \\<in> D.hom x (G y)\\<close> such that for any arrow\n    \\<open>g \\<in> D.hom x (G y')\\<close> there exists a unique \\<open>f \\<in> C.hom y y'\\<close>\n    such that @{term \"h = D e (G f)\"}.\n\\<close>\n\n  locale right_adjoint_functor =\n    C: category C +\n    D: category D +\n    \"functor\" C D G\n    for C :: \"'c comp\"     (infixr \"\\<cdot>\\<^sub>C\" 55)\n    and D :: \"'d comp\"     (infixr \"\\<cdot>\\<^sub>D\" 55)\n    and G :: \"'c \\<Rightarrow> 'd\" +\n    assumes initial_arrows_exist: \"D.ide x \\<Longrightarrow> (\\<exists>y e. initial_arrow_to_functor C D G x y e)\"\n  begin\n\n    notation C.in_hom      (\"\\<guillemotleft>_ : _ \\<rightarrow>\\<^sub>C _\\<guillemotright>\")\n    notation D.in_hom      (\"\\<guillemotleft>_ : _ \\<rightarrow>\\<^sub>D _\\<guillemotright>\")\n\n  end\n\n  section \"Various Definitions of Adjunction\"\n\n  subsection \"Meta-Adjunction\"\n\n  text\\<open>\n    A ``meta-adjunction'' consists of a functor \\<open>F: D \\<rightarrow> C\\<close>,\n    a functor \\<open>G: C \\<rightarrow> D\\<close>, and for each object @{term x}\n    of @{term C} and @{term y} of @{term D} a bijection between\n    \\<open>C.hom (F y) x\\<close> to \\<open>D.hom y (G x)\\<close> which is natural in @{term x}\n    and @{term y}.  The naturality is easy to express at the meta-level without having\n    to resort to the formal baggage of ``set category,'' ``hom-functor,''\n    and ``natural isomorphism,'' hence the name.\n\\<close>\n\n  locale meta_adjunction =\n    C: category C +\n    D: category D +\n    F: \"functor\" D C F +\n    G: \"functor\" C D G\n    for C :: \"'c comp\"     (infixr \"\\<cdot>\\<^sub>C\" 55)\n    and D :: \"'d comp\"     (infixr \"\\<cdot>\\<^sub>D\" 55)\n    and F :: \"'d \\<Rightarrow> 'c\"\n    and G :: \"'c \\<Rightarrow> 'd\"\n    and \\<phi> :: \"'d \\<Rightarrow> 'c \\<Rightarrow> 'd\"\n    and \\<psi> :: \"'c \\<Rightarrow> 'd \\<Rightarrow> 'c\" +\n    assumes \\<phi>_in_hom: \"\\<lbrakk> D.ide y; C.in_hom f (F y) x \\<rbrakk> \\<Longrightarrow> D.in_hom (\\<phi> y f) y (G x)\"\n    and \\<psi>_in_hom: \"\\<lbrakk> C.ide x; D.in_hom g y (G x) \\<rbrakk> \\<Longrightarrow> C.in_hom (\\<psi> x g) (F y) x\"\n    and \\<psi>_\\<phi>: \"\\<lbrakk> D.ide y; C.in_hom f (F y) x \\<rbrakk> \\<Longrightarrow> \\<psi> x (\\<phi> y f) = f\"\n    and \\<phi>_\\<psi>: \"\\<lbrakk> C.ide x; D.in_hom g y (G x) \\<rbrakk> \\<Longrightarrow> \\<phi> y (\\<psi> x g) = g\"\n    and \\<phi>_naturality: \"\\<lbrakk> C.in_hom f x x'; D.in_hom g y' y; C.in_hom h (F y) x \\<rbrakk> \\<Longrightarrow>\n                         \\<phi> y' (f \\<cdot>\\<^sub>C h \\<cdot>\\<^sub>C F g) = G f \\<cdot>\\<^sub>D \\<phi> y h \\<cdot>\\<^sub>D g\"\n  begin\n\n    notation C.in_hom (\"\\<guillemotleft>_ : _ \\<rightarrow>\\<^sub>C _\\<guillemotright>\")\n    notation D.in_hom (\"\\<guillemotleft>_ : _ \\<rightarrow>\\<^sub>D _\\<guillemotright>\")\n\n    text\\<open>\n      The naturality of @{term \\<psi>} is a consequence of the naturality of @{term \\<phi>}\n      and the other assumptions.\n\\<close>\n\n    lemma \\<psi>_naturality:\n    assumes f: \"\\<guillemotleft>f : x \\<rightarrow>\\<^sub>C x'\\<guillemotright>\" and g: \"\\<guillemotleft>g : y' \\<rightarrow>\\<^sub>D y\\<guillemotright>\" and h: \"\\<guillemotleft>h : y \\<rightarrow>\\<^sub>D G x\\<guillemotright>\"\n    shows \"f \\<cdot>\\<^sub>C \\<psi> x h \\<cdot>\\<^sub>C F g = \\<psi> x' (G f \\<cdot>\\<^sub>D h \\<cdot>\\<^sub>D g)\"\n    proof -\n      have \"\\<guillemotleft>f \\<cdot>\\<^sub>C \\<psi> x h \\<cdot>\\<^sub>C F g : F y' \\<rightarrow>\\<^sub>C x'\\<guillemotright>\"\n        using f g h \\<psi>_in_hom [of x h] by fastforce\n      moreover have \"\\<guillemotleft>(G f \\<cdot>\\<^sub>D h) \\<cdot>\\<^sub>D g : y' \\<rightarrow>\\<^sub>D G x'\\<guillemotright>\"\n        using f g h \\<phi>_in_hom by auto\n      moreover have \"\\<psi> x' (\\<phi> y' (f \\<cdot>\\<^sub>C \\<psi> x h \\<cdot>\\<^sub>C F g)) = \\<psi> x' (G f \\<cdot>\\<^sub>D \\<phi> y (\\<psi> x h) \\<cdot>\\<^sub>D g)\"\n      proof -\n        have \"\\<guillemotleft>\\<psi> x h : F y \\<rightarrow>\\<^sub>C x\\<guillemotright>\"\n          using f h \\<psi>_in_hom by auto\n        thus ?thesis using f g \\<phi>_naturality\n          by force\n      qed\n      ultimately show ?thesis\n        using f h \\<psi>_\\<phi> \\<phi>_\\<psi>\n        by (metis C.arrI C.ide_dom C.in_homE D.arrI D.ide_dom D.in_homE)\n    qed\n\n  end\n\n  subsection \"Hom-Adjunction\"\n\n  text\\<open>\n    The bijection between hom-sets that defines an adjunction can be represented\n    formally as a natural isomorphism of hom-functors.  However, stating the definition\n    this way is more complex than was the case for \\<open>meta_adjunction\\<close>.\n    One reason is that we need to have a ``set category'' that is suitable as\n    a target category for the hom-functors, and since the arrows of the categories\n    @{term C} and @{term D} will in general have distinct types, we need a set category\n    that simultaneously embeds both.  Another reason is that we simply have to formally\n    construct the various categories and functors required to express the definition.\n\n    This is a good place to point out that I have often included more sublocales\n    in a locale than are strictly required.  The main reason for this is the fact that\n    the locale system in Isabelle only gives one name to each entity introduced by\n    a locale: the name that it has in the first locale in which it occurs.\n    This means that entities that make their first appearance deeply nested in sublocales\n    will have to be referred to by long qualified names that can be difficult to\n    understand, or even to discover.  To counteract this, I have typically introduced\n    sublocales before the superlocales that contain them to ensure that the entities\n    in the sublocales can be referred to by short meaningful (and predictable) names.\n    In my opinion, though, it would be better if the locale system would make entities\n    that occur in multiple locales accessible by \\emph{all} possible qualified names,\n    so that the most perspicuous name could be used in any particular context.\n\\<close>\n\n  locale hom_adjunction =\n    C: category C +\n    D: category D +\n    S: set_category S +\n    Cop: dual_category C +\n    Dop: dual_category D +\n    CopxC: product_category Cop.comp C +\n    DopxD: product_category Dop.comp D +\n    DopxC: product_category Dop.comp C +\n    F: \"functor\" D C F +\n    G: \"functor\" C D G +\n    HomC: hom_functor C S \\<phi>C +\n    HomD: hom_functor D S \\<phi>D +\n    Fop: dual_functor Dop.comp Cop.comp F +\n    FopxC: product_functor Dop.comp C Cop.comp C Fop.map C.map +\n    DopxG: product_functor Dop.comp C Dop.comp D Dop.map G +\n    Hom_FopxC: composite_functor DopxC.comp CopxC.comp S FopxC.map HomC.map +\n    Hom_DopxG: composite_functor DopxC.comp DopxD.comp S DopxG.map HomD.map +\n    Hom_FopxC: set_valued_functor DopxC.comp S Hom_FopxC.map +\n    Hom_DopxG: set_valued_functor DopxC.comp S Hom_DopxG.map +\n    \\<Phi>: set_valued_transformation DopxC.comp S Hom_FopxC.map Hom_DopxG.map \\<Phi> +\n    \\<Psi>: set_valued_transformation DopxC.comp S Hom_DopxG.map Hom_FopxC.map \\<Psi> +\n    \\<Phi>\\<Psi>: inverse_transformations DopxC.comp S Hom_FopxC.map Hom_DopxG.map \\<Phi> \\<Psi>\n    for C :: \"'c comp\"     (infixr \"\\<cdot>\\<^sub>C\" 55)\n    and D :: \"'d comp\"     (infixr \"\\<cdot>\\<^sub>D\" 55)\n    and S :: \"'s comp\"     (infixr \"\\<cdot>\\<^sub>S\" 55)\n    and \\<phi>C :: \"'c * 'c \\<Rightarrow> 'c \\<Rightarrow> 's\"\n    and \\<phi>D :: \"'d * 'd \\<Rightarrow> 'd \\<Rightarrow> 's\"\n    and F :: \"'d \\<Rightarrow> 'c\"\n    and G :: \"'c \\<Rightarrow> 'd\"\n    and \\<Phi> :: \"'d * 'c \\<Rightarrow> 's\"\n    and \\<Psi> :: \"'d * 'c \\<Rightarrow> 's\"\n  begin\n\n    notation C.in_hom      (\"\\<guillemotleft>_ : _ \\<rightarrow>\\<^sub>C _\\<guillemotright>\")\n    notation D.in_hom      (\"\\<guillemotleft>_ : _ \\<rightarrow>\\<^sub>D _\\<guillemotright>\")\n\n    abbreviation \\<psi>C :: \"'c * 'c \\<Rightarrow> 's \\<Rightarrow> 'c\"\n    where \"\\<psi>C \\<equiv> HomC.\\<psi>\"\n\n    abbreviation \\<psi>D :: \"'d * 'd \\<Rightarrow> 's \\<Rightarrow> 'd\"\n    where \"\\<psi>D \\<equiv> HomD.\\<psi>\"\n\n  end\n\n  subsection \"Unit/Counit Adjunction\"\n\n  text\\<open>\n    Expressed in unit/counit terms, an adjunction consists of functors\n    \\<open>F: D \\<rightarrow> C\\<close> and \\<open>G: C \\<rightarrow> D\\<close>, equipped with natural transformations\n    \\<open>\\<eta>: 1 \\<rightarrow> GF\\<close> and \\<open>\\<epsilon>: FG \\<rightarrow> 1\\<close> satisfying certain ``triangle identities''.\n\\<close>\n\n  locale unit_counit_adjunction =\n    C: category C +\n    D: category D +\n    F: \"functor\" D C F +\n    G: \"functor\" C D G +\n    GF: composite_functor D C D F G +\n    FG: composite_functor C D C G F +\n    FGF: composite_functor D C C F \\<open>F o G\\<close> +\n    GFG: composite_functor C D D G \\<open>G o F\\<close> +\n    \\<eta>: natural_transformation D D D.map \\<open>G o F\\<close> \\<eta> +\n    \\<epsilon>: natural_transformation C C \\<open>F o G\\<close> C.map \\<epsilon> +\n    F\\<eta>: natural_transformation D C F \\<open>F o G o F\\<close> \\<open>F o \\<eta>\\<close> +\n    \\<eta>G: natural_transformation C D G \\<open>G o F o G\\<close> \\<open>\\<eta> o G\\<close> +\n    \\<epsilon>F: natural_transformation D C \\<open>F o G o F\\<close> F \\<open>\\<epsilon> o F\\<close> +\n    G\\<epsilon>: natural_transformation C D \\<open>G o F o G\\<close> G \\<open>G o \\<epsilon>\\<close> +\n    \\<epsilon>FoF\\<eta>: vertical_composite D C F \\<open>F o G o F\\<close> F \\<open>F o \\<eta>\\<close> \\<open>\\<epsilon> o F\\<close> +\n    G\\<epsilon>o\\<eta>G: vertical_composite C D G \\<open>G o F o G\\<close> G \\<open>\\<eta> o G\\<close> \\<open>G o \\<epsilon>\\<close>\n    for C :: \"'c comp\"     (infixr \"\\<cdot>\\<^sub>C\" 55)\n    and D :: \"'d comp\"     (infixr \"\\<cdot>\\<^sub>D\" 55)\n    and F :: \"'d \\<Rightarrow> 'c\"\n    and G :: \"'c \\<Rightarrow> 'd\"\n    and \\<eta> :: \"'d \\<Rightarrow> 'd\"\n    and \\<epsilon> :: \"'c \\<Rightarrow> 'c\" +\n    assumes triangle_F: \"\\<epsilon>FoF\\<eta>.map = F\"\n    and triangle_G: \"G\\<epsilon>o\\<eta>G.map = G\"\n  begin\n\n    notation C.in_hom      (\"\\<guillemotleft>_ : _ \\<rightarrow>\\<^sub>C _\\<guillemotright>\")\n    notation D.in_hom      (\"\\<guillemotleft>_ : _ \\<rightarrow>\\<^sub>D _\\<guillemotright>\")\n\n  end\n\n  lemma unit_determines_counit:\n  assumes \"unit_counit_adjunction C D F G \\<eta> \\<epsilon>\"\n  and \"unit_counit_adjunction C D F G \\<eta> \\<epsilon>'\"\n  shows \"\\<epsilon> = \\<epsilon>'\"\n  proof -\n    (* IDEA:  \\<epsilon>' = \\<epsilon>'FG o (FG\\<epsilon> o F\\<eta>G) = \\<epsilon>'\\<epsilon> o F\\<eta>G = \\<epsilon>FG o (\\<epsilon>'FG o F\\<eta>G) = \\<epsilon> *)\n    interpret Adj: unit_counit_adjunction C D F G \\<eta> \\<epsilon> using assms(1) by auto\n    interpret Adj': unit_counit_adjunction C D F G \\<eta> \\<epsilon>' using assms(2) by auto\n    interpret FGFG: composite_functor C D C G \\<open>F o G o F\\<close> ..\n    interpret FG\\<epsilon>: natural_transformation C C \\<open>(F o G) o (F o G)\\<close> \\<open>F o G\\<close> \\<open>(F o G) o \\<epsilon>\\<close>\n      using Adj.\\<epsilon>.natural_transformation_axioms Adj.FG.natural_transformation_axioms\n            horizontal_composite Adj.FG.functor_axioms\n      by fastforce\n    interpret F\\<eta>G: natural_transformation C C \\<open>F o G\\<close> \\<open>F o G o F o G\\<close> \\<open>F o \\<eta> o G\\<close>\n      using Adj.\\<eta>.natural_transformation_axioms Adj.F\\<eta>.natural_transformation_axioms\n            Adj.G.natural_transformation_axioms horizontal_composite\n      by blast\n    interpret \\<epsilon>'\\<epsilon>: natural_transformation C C \\<open>F o G o F o G\\<close> Adj.C.map \\<open>\\<epsilon>' o \\<epsilon>\\<close>\n    proof -\n      have \"natural_transformation C C ((F o G) o (F o G)) Adj.C.map (\\<epsilon>' o \\<epsilon>)\"\n        using Adj.\\<epsilon>.natural_transformation_axioms Adj'.\\<epsilon>.natural_transformation_axioms\n              horizontal_composite Adj.C.is_functor comp_functor_identity\n        by (metis (no_types, lifting))\n      thus \"natural_transformation C C (F o G o F o G) Adj.C.map (\\<epsilon>' o \\<epsilon>)\"\n        using o_assoc by metis\n    qed\n    interpret \\<epsilon>'\\<epsilon>oF\\<eta>G: vertical_composite\n                         C C \\<open>F o G\\<close> \\<open>F o G o F o G\\<close> Adj.C.map \\<open>F o \\<eta> o G\\<close> \\<open>\\<epsilon>' o \\<epsilon>\\<close> ..\n    have \"\\<epsilon>' = vertical_composite.map C C (F o Adj.G\\<epsilon>o\\<eta>G.map) \\<epsilon>'\"\n      using vcomp_ide_dom [of C C \"F o G\" Adj.C.map \\<epsilon>'] Adj.triangle_G\n      by (simp add: Adj'.\\<epsilon>.natural_transformation_axioms)\n    also have \"... = vertical_composite.map C C\n                       (vertical_composite.map C C (F o \\<eta> o G) (F o G o \\<epsilon>)) \\<epsilon>'\"\n      using whisker_left Adj.F.functor_axioms Adj.G\\<epsilon>.natural_transformation_axioms\n            Adj.\\<eta>G.natural_transformation_axioms o_assoc\n      by (metis (no_types, lifting))\n    also have \"... = vertical_composite.map C C\n                       (vertical_composite.map C C (F o \\<eta> o G) (\\<epsilon>' o F o G)) \\<epsilon>\"\n    proof -\n      have \"vertical_composite.map C C\n              (vertical_composite.map C C (F o \\<eta> o G) (F o G o \\<epsilon>)) \\<epsilon>'\n              = vertical_composite.map C C (F o \\<eta> o G)\n                  (vertical_composite.map C C (F o G o \\<epsilon>) \\<epsilon>')\"\n        using vcomp_assoc\n        by (metis (no_types, lifting) Adj'.\\<epsilon>.natural_transformation_axioms\n            FG\\<epsilon>.natural_transformation_axioms F\\<eta>G.natural_transformation_axioms o_assoc)\n      also have \"... = vertical_composite.map C C (F o \\<eta> o G)\n                         (vertical_composite.map C C (\\<epsilon>' o F o G) \\<epsilon>)\"\n      proof -\n        have \"\\<epsilon>' \\<circ> Adj.C.map = \\<epsilon>'\"\n          using Adj'.\\<epsilon>.natural_transformation_axioms hcomp_ide_dom by simp\n        moreover have \"Adj.C.map \\<circ> \\<epsilon> = \\<epsilon>\"\n          using Adj.\\<epsilon>.natural_transformation_axioms hcomp_ide_cod by simp\n        moreover have \"\\<epsilon>' \\<circ> (F o G) = \\<epsilon>' o F \\<circ> G\" by auto\n        ultimately show ?thesis\n          using Adj'.\\<epsilon>.natural_transformation_axioms Adj.\\<epsilon>.natural_transformation_axioms\n                interchange_spc [of C C \"F o G\" Adj.C.map \\<epsilon> C \"F o G\" Adj.C.map \\<epsilon>']\n          by simp\n      qed\n      also have \"... = vertical_composite.map C C\n                         (vertical_composite.map C C (F o \\<eta> o G) (\\<epsilon>' o F o G)) \\<epsilon>\"\n        using vcomp_assoc\n        by (metis Adj'.\\<epsilon>F.natural_transformation_axioms Adj.G.natural_transformation_axioms\n            Adj.\\<epsilon>.natural_transformation_axioms F\\<eta>G.natural_transformation_axioms\n            horizontal_composite)\n      finally show ?thesis by simp\n    qed\n    also have \"... = vertical_composite.map C C\n                       (vertical_composite.map D C (F o \\<eta>) (\\<epsilon>' o F) o G) \\<epsilon>\"\n      using whisker_right Adj'.\\<epsilon>F.natural_transformation_axioms\n            Adj.F\\<eta>.natural_transformation_axioms Adj.G.functor_axioms\n      by metis\n    also have \"... = vertical_composite.map C C (F o G) \\<epsilon>\"\n      using Adj'.triangle_F by simp\n    also have \"... = \\<epsilon>\"\n      using vcomp_ide_cod Adj.\\<epsilon>.natural_transformation_axioms by simp\n    finally show ?thesis by simp\n  qed\n\n  \n\n  subsection \"Adjunction\"\n\n  text\\<open>\n    The grand unification of everything to do with an adjunction.\n\\<close>\n\n  locale adjunction =\n    C: category C +\n    D: category D +\n    S: set_category S +\n    Cop: dual_category C +\n    Dop: dual_category D +\n    CopxC: product_category Cop.comp C +\n    DopxD: product_category Dop.comp D +\n    DopxC: product_category Dop.comp C +\n    idDop: identity_functor Dop.comp +\n    HomC: hom_functor C S \\<phi>C +\n    HomD: hom_functor D S \\<phi>D +\n    F: left_adjoint_functor D C F +\n    G: right_adjoint_functor C D G +\n    GF: composite_functor D C D F G +\n    FG: composite_functor C D C G F +\n    FGF: composite_functor D C C F FG.map +\n    GFG: composite_functor C D D G GF.map +\n    Fop: dual_functor Dop.comp Cop.comp F +\n    FopxC: product_functor Dop.comp C Cop.comp C Fop.map C.map +\n    DopxG: product_functor Dop.comp C Dop.comp D Dop.map G +\n    Hom_FopxC: composite_functor DopxC.comp CopxC.comp S FopxC.map HomC.map +\n    Hom_DopxG: composite_functor DopxC.comp DopxD.comp S DopxG.map HomD.map +\n    Hom_FopxC: set_valued_functor DopxC.comp S Hom_FopxC.map +\n    Hom_DopxG: set_valued_functor DopxC.comp S Hom_DopxG.map +\n    \\<eta>: natural_transformation D D D.map GF.map \\<eta> +\n    \\<epsilon>: natural_transformation C C FG.map C.map \\<epsilon> +\n    F\\<eta>: natural_transformation D C F \\<open>F o G o F\\<close> \\<open>F o \\<eta>\\<close> +\n    \\<eta>G: natural_transformation C D G \\<open>G o F o G\\<close> \\<open>\\<eta> o G\\<close> +\n    \\<epsilon>F: natural_transformation D C \\<open>F o G o F\\<close> F \\<open>\\<epsilon> o F\\<close> +\n    G\\<epsilon>: natural_transformation C D \\<open>G o F o G\\<close> G \\<open>G o \\<epsilon>\\<close> +\n    \\<epsilon>FoF\\<eta>: vertical_composite D C F FGF.map F \\<open>F o \\<eta>\\<close> \\<open>\\<epsilon> o F\\<close> +\n    G\\<epsilon>o\\<eta>G: vertical_composite C D G GFG.map G \\<open>\\<eta> o G\\<close> \\<open>G o \\<epsilon>\\<close> +\n    \\<phi>\\<psi>: meta_adjunction C D F G \\<phi> \\<psi> +\n    \\<eta>\\<epsilon>: unit_counit_adjunction C D F G \\<eta> \\<epsilon> +\n    \\<Phi>\\<Psi>: hom_adjunction C D S \\<phi>C \\<phi>D F G \\<Phi> \\<Psi>\n    for C :: \"'c comp\"     (infixr \"\\<cdot>\\<^sub>C\" 55)\n    and D :: \"'d comp\"     (infixr \"\\<cdot>\\<^sub>D\" 55)\n    and S :: \"'s comp\"     (infixr \"\\<cdot>\\<^sub>S\" 55)\n    and \\<phi>C :: \"'c * 'c \\<Rightarrow> 'c \\<Rightarrow> 's\"\n    and \\<phi>D :: \"'d * 'd \\<Rightarrow> 'd \\<Rightarrow> 's\"\n    and F :: \"'d \\<Rightarrow> 'c\"\n    and G :: \"'c \\<Rightarrow> 'd\"\n    and \\<phi> :: \"'d \\<Rightarrow> 'c \\<Rightarrow> 'd\"\n    and \\<psi> :: \"'c \\<Rightarrow> 'd \\<Rightarrow> 'c\"\n    and \\<eta> :: \"'d \\<Rightarrow> 'd\"\n    and \\<epsilon> :: \"'c \\<Rightarrow> 'c\"\n    and \\<Phi> :: \"'d * 'c \\<Rightarrow> 's\"\n    and \\<Psi> :: \"'d * 'c \\<Rightarrow> 's\" +\n    assumes \\<phi>_in_terms_of_\\<eta>: \"\\<lbrakk> D.ide y; \\<guillemotleft>f : F y \\<rightarrow>\\<^sub>C x\\<guillemotright> \\<rbrakk> \\<Longrightarrow> \\<phi> y f = G f \\<cdot>\\<^sub>D \\<eta> y\"\n    and \\<psi>_in_terms_of_\\<epsilon>: \"\\<lbrakk> C.ide x; \\<guillemotleft>g : y \\<rightarrow>\\<^sub>D G x\\<guillemotright> \\<rbrakk> \\<Longrightarrow> \\<psi> x g = \\<epsilon> x \\<cdot>\\<^sub>C F g\"\n    and \\<eta>_in_terms_of_\\<phi>: \"D.ide y \\<Longrightarrow> \\<eta> y = \\<phi> y (F y)\"\n    and \\<epsilon>_in_terms_of_\\<psi>: \"C.ide x \\<Longrightarrow> \\<epsilon> x = \\<psi> x (G x)\"\n    and \\<phi>_in_terms_of_\\<Phi>: \"\\<lbrakk> D.ide y; \\<guillemotleft>f : F y \\<rightarrow>\\<^sub>C x\\<guillemotright> \\<rbrakk> \\<Longrightarrow>\n                              \\<phi> y f = (\\<Phi>\\<Psi>.\\<psi>D (y, G x) o S.Fun (\\<Phi> (y, x)) o \\<phi>C (F y, x)) f\"\n    and \\<psi>_in_terms_of_\\<Psi>: \"\\<lbrakk> C.ide x; \\<guillemotleft>g : y \\<rightarrow>\\<^sub>D G x\\<guillemotright> \\<rbrakk> \\<Longrightarrow>\n                              \\<psi> x g = (\\<Phi>\\<Psi>.\\<psi>C (F y, x) o S.Fun (\\<Psi> (y, x)) o \\<phi>D (y, G x)) g\"\n    and \\<Phi>_in_terms_of_\\<phi>:\n           \"\\<lbrakk> C.ide x; D.ide y \\<rbrakk> \\<Longrightarrow>\n                \\<Phi> (y, x) = S.mkArr (HomC.set (F y, x)) (HomD.set (y, G x))\n                                    (\\<phi>D (y, G x) o \\<phi> y o \\<Phi>\\<Psi>.\\<psi>C (F y, x))\"\n    and \\<Psi>_in_terms_of_\\<psi>:\n           \"\\<lbrakk> C.ide x; D.ide y \\<rbrakk> \\<Longrightarrow>\n                \\<Psi> (y, x) = S.mkArr (HomD.set (y, G x)) (HomC.set (F y, x))\n                                    (\\<phi>C (F y, x) o \\<psi> x o \\<Phi>\\<Psi>.\\<psi>D (y, G x))\"\n\n  section \"Meta-Adjunctions Induce Unit/Counit Adjunctions\"\n\n  context meta_adjunction\n  begin\n\n    interpretation GF: composite_functor D C D F G ..\n    interpretation FG: composite_functor C D C G F ..\n    interpretation FGF: composite_functor D C C F FG.map ..\n    interpretation GFG: composite_functor C D D G GF.map ..\n\n    definition \\<eta>o :: \"'d \\<Rightarrow> 'd\"\n    where \"\\<eta>o y = \\<phi> y (F y)\"\n\n    lemma \\<eta>o_in_hom:\n    assumes \"D.ide y\"\n    shows \"\\<guillemotleft>\\<eta>o y : y \\<rightarrow>\\<^sub>D G (F y)\\<guillemotright>\"\n      using assms D.ide_in_hom \\<eta>o_def \\<phi>_in_hom by force\n\n    lemma \\<phi>_in_terms_of_\\<eta>o:\n    assumes \"D.ide y\" and \"\\<guillemotleft>f : F y \\<rightarrow>\\<^sub>C x\\<guillemotright>\"\n    shows \"\\<phi> y f = G f \\<cdot>\\<^sub>D \\<eta>o y\"\n    proof (unfold \\<eta>o_def)\n      have 1: \"\\<guillemotleft>F y : F y \\<rightarrow>\\<^sub>C F y\\<guillemotright>\"\n        using assms(1) D.ide_in_hom by blast\n      hence \"\\<phi> y (F y) = \\<phi> y (F y) \\<cdot>\\<^sub>D y\"\n        by (metis assms(1) D.in_homE \\<phi>_in_hom D.comp_arr_dom)\n      thus \"\\<phi> y f = G f \\<cdot>\\<^sub>D \\<phi> y (F y)\"\n        using assms 1 D.ide_in_hom by (metis C.comp_arr_dom C.in_homE \\<phi>_naturality)\n    qed\n\n    lemma \\<phi>_F_char:\n    assumes \"\\<guillemotleft>g : y' \\<rightarrow>\\<^sub>D y\\<guillemotright>\"\n    shows \"\\<phi> y' (F g) = \\<eta>o y \\<cdot>\\<^sub>D g\"\n      using assms \\<eta>o_def \\<phi>_in_hom [of y \"F y\" \"F y\"]\n            D.comp_cod_arr [of \"D (\\<phi> y (F y)) g\" \"G (F y)\"]\n            \\<phi>_naturality [of \"F y\" \"F y\" \"F y\" g y' y \"F y\"]\n      by fastforce\n\n    interpretation \\<eta>: transformation_by_components D D D.map GF.map \\<eta>o\n    proof\n      show \"\\<And>a. D.ide a \\<Longrightarrow> \\<guillemotleft>\\<eta>o a : D.map a \\<rightarrow>\\<^sub>D GF.map a\\<guillemotright>\"\n        using \\<eta>o_def \\<phi>_in_hom D.ide_in_hom by force\n      fix f\n      assume f: \"D.arr f\"\n      show \"\\<eta>o (D.cod f) \\<cdot>\\<^sub>D D.map f = GF.map f \\<cdot>\\<^sub>D \\<eta>o (D.dom f)\"\n        using f \\<phi>_F_char [of \"D.map f\" \"D.dom f\" \"D.cod f\"]\n              \\<phi>_in_terms_of_\\<eta>o [of \"D.dom f\" \"F f\" \"F (D.cod f)\"]\n        by force\n    qed\n\n    lemma \\<eta>_map_simp:\n    assumes \"D.ide y\"\n    shows \"\\<eta>.map y = \\<phi> y (F y)\"\n      using assms \\<eta>.map_simp_ide \\<eta>o_def by simp\n\n    definition \\<epsilon>o :: \"'c \\<Rightarrow> 'c\"\n    where \"\\<epsilon>o x = \\<psi> x (G x)\"\n\n    lemma \\<epsilon>o_in_hom:\n    assumes \"C.ide x\"\n    shows \"\\<guillemotleft>\\<epsilon>o x : F (G x) \\<rightarrow>\\<^sub>C x\\<guillemotright>\"\n      using assms C.ide_in_hom \\<epsilon>o_def \\<psi>_in_hom by force\n\n    lemma \\<psi>_in_terms_of_\\<epsilon>o:\n    assumes \"C.ide x\" and \"\\<guillemotleft>g : y \\<rightarrow>\\<^sub>D G x\\<guillemotright>\"\n    shows \"\\<psi> x g = \\<epsilon>o x \\<cdot>\\<^sub>C F g\"\n    proof -\n      have \"\\<epsilon>o x \\<cdot>\\<^sub>C F g = x \\<cdot>\\<^sub>C \\<psi> x (G x) \\<cdot>\\<^sub>C F g\"\n        using assms \\<epsilon>o_def \\<psi>_in_hom [of x \"G x\" \"G x\"]\n              C.comp_cod_arr [of \"\\<psi> x (G x) \\<cdot>\\<^sub>C F g\" x]\n        by fastforce\n      also have \"... = \\<psi> x (G x \\<cdot>\\<^sub>D G x \\<cdot>\\<^sub>D g)\"\n        using assms \\<psi>_naturality [of x x x g y \"G x\" \"G x\"] by force\n      also have \"... = \\<psi> x g\"\n        using assms D.comp_cod_arr by fastforce\n      finally show ?thesis by simp\n    qed\n\n    \n\n    interpretation \\<epsilon>: transformation_by_components C C FG.map C.map \\<epsilon>o\n      apply unfold_locales\n      using \\<epsilon>o_in_hom\n       apply simp\n      using \\<psi>_G_char \\<psi>_in_terms_of_\\<epsilon>o\n      by (metis C.arr_iff_in_hom C.ide_cod C.map_simp G.preserves_hom comp_apply)\n\n    lemma \\<epsilon>_map_simp:\n    assumes \"C.ide x\"\n    shows \"\\<epsilon>.map x = \\<psi> x (G x)\"\n      using assms \\<epsilon>o_def by simp\n\n    interpretation FD: composite_functor D D C D.map F ..\n    interpretation CF: composite_functor D C C F C.map ..\n    interpretation GC: composite_functor C C D C.map G ..\n    interpretation DG: composite_functor C D D G D.map ..\n\n    interpretation F\\<eta>: natural_transformation D C F \\<open>F o G o F\\<close> \\<open>F o \\<eta>.map\\<close>\n    proof -\n      have \"natural_transformation D C F (F o (G o F)) (F o \\<eta>.map)\"\n        using \\<eta>.natural_transformation_axioms F.natural_transformation_axioms\n              horizontal_composite\n        by fastforce\n      thus \"natural_transformation D C F (F o G o F) (F o \\<eta>.map)\"\n        using o_assoc by metis\n    qed\n\n    interpretation \\<epsilon>F: natural_transformation D C \\<open>F o G o F\\<close> F \\<open>\\<epsilon>.map o F\\<close>\n      using \\<epsilon>.natural_transformation_axioms F.natural_transformation_axioms\n            horizontal_composite\n      by fastforce\n\n    interpretation \\<eta>G: natural_transformation C D G \\<open>G o F o G\\<close> \\<open>\\<eta>.map o G\\<close>\n      using \\<eta>.natural_transformation_axioms G.natural_transformation_axioms\n            horizontal_composite\n      by fastforce\n\n    interpretation G\\<epsilon>: natural_transformation C D \\<open>G o F o G\\<close> G \\<open>G o \\<epsilon>.map\\<close>\n    proof - \n      have \"natural_transformation C D (G o (F o G)) G (G o \\<epsilon>.map)\"\n        using \\<epsilon>.natural_transformation_axioms G.natural_transformation_axioms\n            horizontal_composite\n        by fastforce\n      thus \"natural_transformation C D (G o F o G) G (G o \\<epsilon>.map)\"\n        using o_assoc by metis\n    qed\n\n    interpretation \\<epsilon>FoF\\<eta>: vertical_composite D C F \\<open>F o G o F\\<close> F \\<open>F o \\<eta>.map\\<close> \\<open>\\<epsilon>.map o F\\<close> ..\n    interpretation G\\<epsilon>o\\<eta>G: vertical_composite C D G \\<open>G o F o G\\<close> G \\<open>\\<eta>.map o G\\<close> \\<open>G o \\<epsilon>.map\\<close> ..\n\n    lemma unit_counit_F:\n    assumes \"D.ide y\"\n    shows \"F y = \\<epsilon>o (F y) \\<cdot>\\<^sub>C F (\\<eta>o y)\"\n      using assms \\<psi>_in_terms_of_\\<epsilon>o \\<eta>o_def \\<psi>_\\<phi> \\<eta>o_in_hom F.preserves_ide C.ide_in_hom by metis\n\n    lemma unit_counit_G:\n    assumes \"C.ide x\"\n    shows \"G x = G (\\<epsilon>o x) \\<cdot>\\<^sub>D \\<eta>o (G x)\"\n      using assms \\<phi>_in_terms_of_\\<eta>o \\<epsilon>o_def \\<phi>_\\<psi> \\<epsilon>o_in_hom G.preserves_ide D.ide_in_hom by metis\n\n    \n\n    text\\<open>\n      From the defined @{term \\<eta>} and @{term \\<epsilon>} we can recover the original @{term \\<phi>} and @{term \\<psi>}.\n\\<close>\n\n    lemma \\<phi>_in_terms_of_\\<eta>:\n    assumes \"D.ide y\" and \"\\<guillemotleft>f : F y \\<rightarrow>\\<^sub>C x\\<guillemotright>\"\n    shows \"\\<phi> y f = G f \\<cdot>\\<^sub>D \\<eta>.map y\"\n      using assms by (simp add: \\<phi>_in_terms_of_\\<eta>o)\n\n    lemma \\<psi>_in_terms_of_\\<epsilon>:\n    assumes \"C.ide x\" and \"\\<guillemotleft>g : y \\<rightarrow>\\<^sub>D G x\\<guillemotright>\"\n    shows \"\\<psi> x g = \\<epsilon>.map x \\<cdot>\\<^sub>C F g\"\n      using assms by (simp add: \\<psi>_in_terms_of_\\<epsilon>o)\n\n    definition \\<eta> :: \"'d \\<Rightarrow> 'd\" where \"\\<eta> \\<equiv> \\<eta>.map\"\n    definition \\<epsilon> :: \"'c \\<Rightarrow> 'c\" where \"\\<epsilon> \\<equiv> \\<epsilon>.map\"\n\n    lemma \\<eta>_is_natural_transformation:\n    shows \"natural_transformation D D D.map GF.map \\<eta>\"\n      unfolding \\<eta>_def ..\n\n    \n\n  end\n\n  section \"Meta-Adjunctions Induce Left and Right Adjoint Functors\"\n\n  context meta_adjunction\n  begin\n\n    interpretation unit_counit_adjunction C D F G \\<eta> \\<epsilon>\n      using induces_unit_counit_adjunction \\<eta>_def \\<epsilon>_def by auto\n\n    lemma has_terminal_arrows_from_functor:\n    assumes x: \"C.ide x\"\n    shows \"terminal_arrow_from_functor D C F (G x) x (\\<epsilon> x)\"\n    and \"\\<And>y' f. arrow_from_functor D C F y' x f\n                   \\<Longrightarrow> terminal_arrow_from_functor.the_coext D C F (G x) (\\<epsilon> x) y' f = \\<phi> y' f\"\n    proof -\n      interpret \\<epsilon>x: arrow_from_functor D C F \\<open>G x\\<close> x \\<open>\\<epsilon> x\\<close>\n        apply unfold_locales\n        using x \\<epsilon>.preserves_hom G.preserves_ide by auto\n      have 1: \"\\<And>y' f. arrow_from_functor D C F y' x f \\<Longrightarrow>\n                      \\<epsilon>x.is_coext y' f (\\<phi> y' f) \\<and> (\\<forall>g'. \\<epsilon>x.is_coext y' f g' \\<longrightarrow> g' = \\<phi> y' f)\"\n      proof\n        fix y' :: 'd and f :: 'c\n        assume f: \"arrow_from_functor D C F y' x f\"\n        show \"\\<epsilon>x.is_coext y' f (\\<phi> y' f)\"\n          using f x \\<epsilon>_def \\<phi>_in_hom \\<psi>_\\<phi> \\<psi>_in_terms_of_\\<epsilon> \\<epsilon>x.is_coext_def arrow_from_functor.arrow\n          by metis\n        show \"\\<forall>g'. \\<epsilon>x.is_coext y' f g' \\<longrightarrow> g' = \\<phi> y' f\"\n          using \\<epsilon>o_def \\<psi>_in_terms_of_\\<epsilon>o x \\<epsilon>_map_simp \\<phi>_\\<psi> \\<epsilon>x.is_coext_def \\<epsilon>_def by simp\n      qed\n      interpret \\<epsilon>x: terminal_arrow_from_functor D C F \\<open>G x\\<close> x \\<open>\\<epsilon> x\\<close>\n        apply unfold_locales using 1 by blast\n      show \"terminal_arrow_from_functor D C F (G x) x (\\<epsilon> x)\" ..\n      show \"\\<And>y' f. arrow_from_functor D C F y' x f \\<Longrightarrow> \\<epsilon>x.the_coext y' f = \\<phi> y' f\"\n        using 1 \\<epsilon>x.the_coext_def by auto\n    qed\n\n    lemma has_left_adjoint_functor:\n    shows \"left_adjoint_functor D C F\"\n      apply unfold_locales using has_terminal_arrows_from_functor by auto\n\n  end\n\n  context meta_adjunction\n  begin\n\n    interpretation unit_counit_adjunction C D F G \\<eta> \\<epsilon>\n      using induces_unit_counit_adjunction \\<eta>_def \\<epsilon>_def by auto\n\n    lemma has_initial_arrows_to_functor:\n    assumes y: \"D.ide y\"\n    shows \"initial_arrow_to_functor C D G y (F y) (\\<eta> y)\"\n    and \"\\<And>x' g. arrow_to_functor C D G y x' g \\<Longrightarrow>\n                  initial_arrow_to_functor.the_ext C D G (F y) (\\<eta> y) x' g = \\<psi> x' g\"\n    proof -\n      interpret \\<eta>y: arrow_to_functor C D G y \\<open>F y\\<close> \\<open>\\<eta> y\\<close>\n        apply unfold_locales using y by auto\n      have 1: \"\\<And>x' g. arrow_to_functor C D G y x' g \\<Longrightarrow>\n                         \\<eta>y.is_ext x' g (\\<psi> x' g) \\<and> (\\<forall>f'. \\<eta>y.is_ext x' g f' \\<longrightarrow> f' = \\<psi> x' g)\"\n      proof\n        fix x' :: 'c and g :: 'd\n        assume g: \"arrow_to_functor C D G y x' g\"\n        show \"\\<eta>y.is_ext x' g (\\<psi> x' g)\"\n          using g y \\<psi>_in_hom \\<phi>_\\<psi> \\<phi>_in_terms_of_\\<eta> \\<eta>y.is_ext_def arrow_to_functor.arrow \\<eta>_def\n          by metis\n        show \"\\<forall>f'. \\<eta>y.is_ext x' g f' \\<longrightarrow> f' = \\<psi> x' g\"\n          using y \\<eta>o_def \\<phi>_in_terms_of_\\<eta>o \\<eta>_map_simp \\<psi>_\\<phi> \\<eta>y.is_ext_def \\<eta>_def by simp\n      qed\n      interpret \\<eta>y: initial_arrow_to_functor C D G y \\<open>F y\\<close> \\<open>\\<eta> y\\<close>\n        apply unfold_locales using 1 by blast\n      show \"initial_arrow_to_functor C D G y (F y) (\\<eta> y)\" ..\n      show \"\\<And>x' g. arrow_to_functor C D G y x' g \\<Longrightarrow> \\<eta>y.the_ext x' g = \\<psi> x' g\"\n        using 1 \\<eta>y.the_ext_def by auto\n    qed\n\n    lemma has_right_adjoint_functor:\n    shows \"right_adjoint_functor C D G\"\n      apply unfold_locales using has_initial_arrows_to_functor by auto\n\n  end\n\n  section \"Unit/Counit Adjunctions Induce Meta-Adjunctions\"\n\n  context unit_counit_adjunction\n  begin\n\n    definition \\<phi> :: \"'d \\<Rightarrow> 'c \\<Rightarrow> 'd\"\n    where \"\\<phi> y h = G h \\<cdot>\\<^sub>D \\<eta> y\"\n\n    definition \\<psi> :: \"'c \\<Rightarrow> 'd \\<Rightarrow> 'c\"\n    where \"\\<psi> x h = \\<epsilon> x \\<cdot>\\<^sub>C F h\"\n\n    interpretation meta_adjunction C D F G \\<phi> \\<psi>\n    proof\n      fix x :: 'c and y :: 'd and f :: 'c\n      assume y: \"D.ide y\" and f: \"\\<guillemotleft>f : F y \\<rightarrow>\\<^sub>C x\\<guillemotright>\"\n      show 0: \"\\<guillemotleft>\\<phi> y f : y \\<rightarrow>\\<^sub>D G x\\<guillemotright>\"\n        using f y G.preserves_hom \\<eta>.preserves_hom \\<phi>_def D.ide_in_hom\n        by (metis D.comp_in_homI D.in_homE comp_apply D.map_simp)\n      show \"\\<psi> x (\\<phi> y f) = f\"\n      proof -\n        have \"\\<psi> x (\\<phi> y f) = (\\<epsilon> x \\<cdot>\\<^sub>C F (G f)) \\<cdot>\\<^sub>C F (\\<eta> y)\"\n          using y f \\<phi>_def \\<psi>_def C.comp_assoc by auto\n        also have \"... = (f \\<cdot>\\<^sub>C \\<epsilon> (F y)) \\<cdot>\\<^sub>C F (\\<eta> y)\"\n          using y f \\<epsilon>.naturality by auto\n        also have \"... = f\"\n          using y f \\<epsilon>FoF\\<eta>.map_simp_2 triangle_F C.comp_arr_dom D.ide_in_hom C.comp_assoc\n          by fastforce\n        finally show ?thesis by auto\n      qed\n      next\n      fix x :: 'c and y :: 'd and g :: 'd\n      assume x: \"C.ide x\" and g: \"\\<guillemotleft>g : y \\<rightarrow>\\<^sub>D G x\\<guillemotright>\"\n      show \"\\<guillemotleft>\\<psi> x g : F y \\<rightarrow>\\<^sub>C x\\<guillemotright>\" using g x \\<psi>_def by fastforce\n      show \"\\<phi> y (\\<psi> x g) = g\"\n      proof -\n        have \"\\<phi> y (\\<psi> x g) = (G (\\<epsilon> x) \\<cdot>\\<^sub>D \\<eta> (G x)) \\<cdot>\\<^sub>D g\"\n          using g x \\<phi>_def \\<psi>_def \\<eta>.naturality [of g] D.comp_assoc by auto\n        also have \"... = g\"\n          using x g triangle_G D.comp_ide_arr G\\<epsilon>o\\<eta>G.map_simp_ide by auto\n        finally show ?thesis by auto\n      qed\n      next\n      fix f :: 'c and g :: 'd and h :: 'c and x :: 'c and x' :: 'c and y :: 'd and y' :: 'd\n      assume f: \"\\<guillemotleft>f : x \\<rightarrow>\\<^sub>C x'\\<guillemotright>\" and g: \"\\<guillemotleft>g : y' \\<rightarrow>\\<^sub>D y\\<guillemotright>\" and h: \"\\<guillemotleft>h : F y \\<rightarrow>\\<^sub>C x\\<guillemotright>\"\n      show \"\\<phi> y' (f \\<cdot>\\<^sub>C h \\<cdot>\\<^sub>C F g) = G f \\<cdot>\\<^sub>D \\<phi> y h \\<cdot>\\<^sub>D g\"\n        using \\<phi>_def f g h \\<eta>.naturality D.comp_assoc by fastforce\n    qed\n\n    theorem induces_meta_adjunction:\n    shows \"meta_adjunction C D F G \\<phi> \\<psi>\" ..\n\n    text\\<open>\n      From the defined @{term \\<phi>} and @{term \\<psi>} we can recover the original @{term \\<eta>} and @{term \\<epsilon>}.\n\\<close>\n\n    lemma \\<eta>_in_terms_of_\\<phi>:\n    assumes \"D.ide y\"\n    shows \"\\<eta> y = \\<phi> y (F y)\"\n      using assms \\<phi>_def D.comp_cod_arr by auto\n\n    lemma \\<epsilon>_in_terms_of_\\<psi>:\n    assumes \"C.ide x\"\n    shows \"\\<epsilon> x = \\<psi> x (G x)\"\n      using assms \\<psi>_def C.comp_arr_dom by auto\n\n  end\n\n  section \"Left and Right Adjoint Functors Induce Meta-Adjunctions\"\n\n  text\\<open>\n    A left adjoint functor induces a meta-adjunction, modulo the choice of a\n    right adjoint and counit.\n\\<close>\n\n  context left_adjoint_functor\n  begin\n\n    definition Go :: \"'c \\<Rightarrow> 'd\"\n    where \"Go a = (SOME b. \\<exists>e. terminal_arrow_from_functor D C F b a e)\"\n\n    definition \\<epsilon>o :: \"'c \\<Rightarrow> 'c\"\n    where \"\\<epsilon>o a = (SOME e. terminal_arrow_from_functor D C F (Go a) a e)\"\n\n    lemma Go_\\<epsilon>o_terminal:\n    assumes \"\\<exists>b e. terminal_arrow_from_functor D C F b a e\"\n    shows \"terminal_arrow_from_functor D C F (Go a) a (\\<epsilon>o a)\"\n      using assms Go_def \\<epsilon>o_def\n            someI_ex [of \"\\<lambda>b. \\<exists>e. terminal_arrow_from_functor D C F b a e\"]\n            someI_ex [of \"\\<lambda>e. terminal_arrow_from_functor D C F (Go a) a e\"]\n      by simp\n\n    text\\<open>\n      The right adjoint @{term G} to @{term F} takes each arrow @{term f} of\n      @{term[source=true] C} to the unique @{term[source=true] D}-coextension of\n      @{term \"C f (\\<epsilon>o (C.dom f))\"} along @{term \"\\<epsilon>o (C.cod f)\"}.\n\\<close>\n\n    definition G :: \"'c \\<Rightarrow> 'd\"\n    where \"G f = (if C.arr f then\n                     terminal_arrow_from_functor.the_coext D C F (Go (C.cod f)) (\\<epsilon>o (C.cod f))\n                                  (Go (C.dom f)) (f \\<cdot>\\<^sub>C \\<epsilon>o (C.dom f))\n                  else D.null)\"\n\n    lemma G_ide:\n    assumes \"C.ide x\"\n    shows \"G x = Go x\"\n    proof -\n      interpret terminal_arrow_from_functor D C F \\<open>Go x\\<close> x \\<open>\\<epsilon>o x\\<close>\n        using assms ex_terminal_arrow Go_\\<epsilon>o_terminal by blast\n      have 1: \"arrow_from_functor D C F (Go x) x (\\<epsilon>o x)\" ..\n      have \"is_coext (Go x) (\\<epsilon>o x) (Go x)\"\n        using arrow is_coext_def C.in_homE C.comp_arr_dom by auto\n      hence \"Go x = the_coext (Go x) (\\<epsilon>o x)\" using 1 the_coext_unique by blast\n      moreover have \"\\<epsilon>o x = C x (\\<epsilon>o (C.dom x))\"\n        using assms arrow C.comp_ide_arr C.seqI' C.ide_in_hom C.in_homE by metis\n      ultimately show ?thesis using assms G_def C.cod_dom C.ide_in_hom C.in_homE by metis\n    qed\n\n    lemma G_is_functor:\n    shows \"functor C D G\"\n    proof\n      fix f :: 'c\n      assume \"\\<not>C.arr f\"\n      thus \"G f = D.null\" using G_def by auto\n      next\n      fix f :: 'c\n      assume f: \"C.arr f\"\n      let ?x = \"C.dom f\"\n      let ?x' = \"C.cod f\"\n      interpret x\\<epsilon>: terminal_arrow_from_functor D C F \\<open>Go ?x\\<close> \\<open>?x\\<close> \\<open>\\<epsilon>o ?x\\<close>\n        using f ex_terminal_arrow Go_\\<epsilon>o_terminal by simp\n      interpret x'\\<epsilon>: terminal_arrow_from_functor D C F \\<open>Go ?x'\\<close> \\<open>?x'\\<close> \\<open>\\<epsilon>o ?x'\\<close>\n        using f ex_terminal_arrow Go_\\<epsilon>o_terminal by simp\n      have 1: \"arrow_from_functor D C F (Go ?x) ?x' (C f (\\<epsilon>o ?x))\"\n        using f x\\<epsilon>.arrow by (unfold_locales, auto)\n      have \"G f = x'\\<epsilon>.the_coext (Go ?x) (C f (\\<epsilon>o ?x))\" using f G_def by simp\n      hence Gf: \"\\<guillemotleft>G f : Go ?x \\<rightarrow>\\<^sub>D Go ?x'\\<guillemotright> \\<and> f \\<cdot>\\<^sub>C \\<epsilon>o ?x = \\<epsilon>o ?x' \\<cdot>\\<^sub>C F (G f)\"\n        using 1 x'\\<epsilon>.the_coext_prop by simp\n      show \"D.arr (G f)\" using Gf by auto\n      show \"D.dom (G f) = G ?x\" using f Gf G_ide by auto\n      show \"D.cod (G f) = G ?x'\" using f Gf G_ide by auto\n      next\n      fix f f' :: 'c\n      assume ff': \"C.arr (C f' f)\"\n      have f: \"C.arr f\" using ff' by auto\n      let ?x = \"C.dom f\"\n      let ?x' = \"C.cod f\"\n      let ?x'' = \"C.cod f'\"\n      interpret x\\<epsilon>: terminal_arrow_from_functor D C F \\<open>Go ?x\\<close> \\<open>?x\\<close> \\<open>\\<epsilon>o ?x\\<close>\n        using f ex_terminal_arrow Go_\\<epsilon>o_terminal by simp\n      interpret x'\\<epsilon>: terminal_arrow_from_functor D C F \\<open>Go ?x'\\<close> \\<open>?x'\\<close> \\<open>\\<epsilon>o ?x'\\<close>\n        using f ex_terminal_arrow Go_\\<epsilon>o_terminal by simp\n      interpret x''\\<epsilon>: terminal_arrow_from_functor D C F \\<open>Go ?x''\\<close> \\<open>?x''\\<close> \\<open>\\<epsilon>o ?x''\\<close>\n        using ff' ex_terminal_arrow Go_\\<epsilon>o_terminal by auto\n      have 1: \"arrow_from_functor D C F (Go ?x) ?x' (f \\<cdot>\\<^sub>C \\<epsilon>o ?x)\"\n         using f x\\<epsilon>.arrow by (unfold_locales, auto)\n      have 2: \"arrow_from_functor D C F (Go ?x') ?x'' (f' \\<cdot>\\<^sub>C \\<epsilon>o ?x')\"\n         using ff' x'\\<epsilon>.arrow by (unfold_locales, auto)\n      have \"G f = x'\\<epsilon>.the_coext (Go ?x) (C f (\\<epsilon>o ?x))\"\n        using f G_def by simp\n      hence Gf: \"D.in_hom (G f) (Go ?x) (Go ?x') \\<and> f \\<cdot>\\<^sub>C \\<epsilon>o ?x = \\<epsilon>o ?x' \\<cdot>\\<^sub>C F (G f)\"\n        using 1 x'\\<epsilon>.the_coext_prop by simp\n      have \"G f' = x''\\<epsilon>.the_coext (Go ?x') (f' \\<cdot>\\<^sub>C \\<epsilon>o ?x')\"\n        using ff' G_def by auto\n      hence Gf': \"\\<guillemotleft>G f' : Go (C.cod f) \\<rightarrow>\\<^sub>D Go (C.cod f')\\<guillemotright> \\<and> f' \\<cdot>\\<^sub>C \\<epsilon>o ?x' = \\<epsilon>o ?x'' \\<cdot>\\<^sub>C F (G f')\"\n        using 2 x''\\<epsilon>.the_coext_prop by simp\n      show \"G (f' \\<cdot>\\<^sub>C f) = G f' \\<cdot>\\<^sub>D G f\"\n      proof -\n        have \"x''\\<epsilon>.is_coext (Go ?x) ((f' \\<cdot>\\<^sub>C f) \\<cdot>\\<^sub>C \\<epsilon>o ?x) (G f' \\<cdot>\\<^sub>D G f)\"\n        proof -\n          have \"\\<guillemotleft>G f' \\<cdot>\\<^sub>D G f : Go (C.dom f) \\<rightarrow>\\<^sub>D Go (C.cod f')\\<guillemotright>\" using 1 2 Gf Gf' by auto\n          moreover have \"(f' \\<cdot>\\<^sub>C f) \\<cdot>\\<^sub>C \\<epsilon>o ?x = \\<epsilon>o ?x'' \\<cdot>\\<^sub>C F (G f' \\<cdot>\\<^sub>D G f)\"\n          proof -\n            have \"(f' \\<cdot>\\<^sub>C f) \\<cdot>\\<^sub>C \\<epsilon>o ?x = f' \\<cdot>\\<^sub>C f \\<cdot>\\<^sub>C \\<epsilon>o ?x\"\n              using C.comp_assoc by force\n            also have \"... = (f' \\<cdot>\\<^sub>C \\<epsilon>o ?x') \\<cdot>\\<^sub>C F (G f)\"\n              using Gf C.comp_assoc by fastforce\n            also have \"... = \\<epsilon>o ?x'' \\<cdot>\\<^sub>C F (G f' \\<cdot>\\<^sub>D G f)\"\n              using Gf Gf' C.comp_assoc by fastforce\n            finally show ?thesis by auto\n          qed\n          ultimately show ?thesis using x''\\<epsilon>.is_coext_def by auto\n        qed\n        moreover have \"arrow_from_functor D C F (Go ?x) ?x'' ((f' \\<cdot>\\<^sub>C f) \\<cdot>\\<^sub>C \\<epsilon>o ?x)\"\n           using ff' x\\<epsilon>.arrow by (unfold_locales, blast)\n        ultimately show ?thesis\n          using ff' G_def x''\\<epsilon>.the_coext_unique C.seqE C.cod_comp C.dom_comp by auto\n      qed\n    qed\n\n    interpretation G: \"functor\" C D G using G_is_functor by auto\n\n    lemma G_simp:\n    assumes \"C.arr f\"\n    shows \"G f = terminal_arrow_from_functor.the_coext D C F (Go (C.cod f)) (\\<epsilon>o (C.cod f))\n                                                             (Go (C.dom f)) (f \\<cdot>\\<^sub>C \\<epsilon>o (C.dom f))\"\n      using assms G_def by simp\n\n    interpretation idC: identity_functor C ..\n    interpretation GF: composite_functor C D C G F ..\n\n    interpretation \\<epsilon>: transformation_by_components C C GF.map C.map \\<epsilon>o\n    proof\n      fix x :: 'c\n      assume x: \"C.ide x\"\n      show \"\\<guillemotleft>\\<epsilon>o x : GF.map x \\<rightarrow>\\<^sub>C C.map x\\<guillemotright>\"\n      proof -\n        interpret terminal_arrow_from_functor D C F \\<open>Go x\\<close> x \\<open>\\<epsilon>o x\\<close>\n          using x Go_\\<epsilon>o_terminal ex_terminal_arrow by simp\n        show ?thesis using x G_ide arrow by auto\n      qed\n      next\n      fix f :: 'c\n      assume f: \"C.arr f\"\n      show \"\\<epsilon>o (C.cod f) \\<cdot>\\<^sub>C GF.map f = C.map f \\<cdot>\\<^sub>C \\<epsilon>o (C.dom f)\"\n      proof -\n        let ?x = \"C.dom f\"\n        let ?x' = \"C.cod f\"\n        interpret x\\<epsilon>: terminal_arrow_from_functor D C F \\<open>Go ?x\\<close> ?x \\<open>\\<epsilon>o ?x\\<close>\n          using f Go_\\<epsilon>o_terminal ex_terminal_arrow by simp\n        interpret x'\\<epsilon>: terminal_arrow_from_functor D C F \\<open>Go ?x'\\<close> ?x' \\<open>\\<epsilon>o ?x'\\<close>\n          using f Go_\\<epsilon>o_terminal ex_terminal_arrow by simp\n        have 1: \"arrow_from_functor D C F (Go ?x) ?x' (C f (\\<epsilon>o ?x))\"\n           using f x\\<epsilon>.arrow by (unfold_locales, auto)\n        have \"G f = x'\\<epsilon>.the_coext (Go ?x) (f \\<cdot>\\<^sub>C \\<epsilon>o ?x)\"\n          using f G_simp by blast\n        hence \"x'\\<epsilon>.is_coext (Go ?x) (f \\<cdot>\\<^sub>C \\<epsilon>o ?x) (G f)\"\n          using 1 x'\\<epsilon>.the_coext_prop x'\\<epsilon>.is_coext_def by auto\n        thus ?thesis\n          using f x'\\<epsilon>.is_coext_def by simp\n      qed\n    qed\n\n    definition \\<psi>\n    where \"\\<psi> x h = C (\\<epsilon>.map x) (F h)\"\n\n    lemma \\<psi>_in_hom:\n    assumes \"C.ide x\" and \"\\<guillemotleft>g : y \\<rightarrow>\\<^sub>D G x\\<guillemotright>\"\n    shows \"\\<guillemotleft>\\<psi> x g : F y \\<rightarrow>\\<^sub>C x\\<guillemotright>\"\n      unfolding \\<psi>_def using assms \\<epsilon>.maps_ide_in_hom by auto\n\n    lemma \\<psi>_natural:\n    assumes f: \"\\<guillemotleft>f : x \\<rightarrow>\\<^sub>C x'\\<guillemotright>\" and g: \"\\<guillemotleft>g : y' \\<rightarrow>\\<^sub>D y\\<guillemotright>\" and h: \"\\<guillemotleft>h : y \\<rightarrow>\\<^sub>D G x\\<guillemotright>\"\n    shows \"f \\<cdot>\\<^sub>C \\<psi> x h \\<cdot>\\<^sub>C F g = \\<psi> x' ((G f \\<cdot>\\<^sub>D h) \\<cdot>\\<^sub>D g)\"\n    proof -\n      have \"f \\<cdot>\\<^sub>C \\<psi> x h \\<cdot>\\<^sub>C F g = f \\<cdot>\\<^sub>C (\\<epsilon>.map x \\<cdot>\\<^sub>C F h) \\<cdot>\\<^sub>C F g\"\n        unfolding \\<psi>_def by auto\n      also have \"... = (f \\<cdot>\\<^sub>C \\<epsilon>.map x) \\<cdot>\\<^sub>C F h \\<cdot>\\<^sub>C F g\"\n        using C.comp_assoc by fastforce\n      also have \"... = (f \\<cdot>\\<^sub>C \\<epsilon>.map x) \\<cdot>\\<^sub>C F (h \\<cdot>\\<^sub>D g)\"\n        using g h by fastforce\n      also have \"... = (\\<epsilon>.map x' \\<cdot>\\<^sub>C F (G f)) \\<cdot>\\<^sub>C F (h \\<cdot>\\<^sub>D g)\"\n        using f \\<epsilon>.naturality by auto\n      also have \"... = \\<epsilon>.map x' \\<cdot>\\<^sub>C F ((G f \\<cdot>\\<^sub>D h) \\<cdot>\\<^sub>D g)\"\n        using f g h C.comp_assoc by fastforce\n      also have \"... = \\<psi> x' ((G f \\<cdot>\\<^sub>D h) \\<cdot>\\<^sub>D g)\"\n        unfolding \\<psi>_def by auto\n      finally show ?thesis by auto\n    qed\n\n    lemma \\<psi>_inverts_coext:\n    assumes x: \"C.ide x\" and g: \"\\<guillemotleft>g : y \\<rightarrow>\\<^sub>D G x\\<guillemotright>\"\n    shows \"arrow_from_functor.is_coext D C F (G x) (\\<epsilon>.map x) y (\\<psi> x g) g\"\n    proof -\n      interpret x\\<epsilon>: arrow_from_functor D C F \\<open>G x\\<close> x \\<open>\\<epsilon>.map x\\<close>\n        using x \\<epsilon>.maps_ide_in_hom by (unfold_locales, auto)\n      show \"x\\<epsilon>.is_coext y (\\<psi> x g) g\"\n        using x g \\<psi>_def x\\<epsilon>.is_coext_def G_ide by blast\n    qed\n\n    lemma \\<psi>_invertible:\n    assumes y: \"D.ide y\" and f: \"\\<guillemotleft>f : F y \\<rightarrow>\\<^sub>C x\\<guillemotright>\"\n    shows \"\\<exists>!g. \\<guillemotleft>g : y \\<rightarrow>\\<^sub>D G x\\<guillemotright> \\<and> \\<psi> x g = f\"\n    proof\n      have x: \"C.ide x\" using f by auto\n      interpret x\\<epsilon>: terminal_arrow_from_functor D C F \\<open>Go x\\<close> x \\<open>\\<epsilon>o x\\<close>\n        using x ex_terminal_arrow Go_\\<epsilon>o_terminal by auto\n      have 1: \"arrow_from_functor D C F y x f\"\n        using y f by (unfold_locales, auto)\n      let ?g = \"x\\<epsilon>.the_coext y f\"\n      have \"\\<psi> x ?g = f\"\n        using 1 x y \\<psi>_def x\\<epsilon>.the_coext_prop G_ide \\<psi>_inverts_coext x\\<epsilon>.is_coext_def by simp\n      thus \"\\<guillemotleft>?g : y \\<rightarrow>\\<^sub>D G x\\<guillemotright> \\<and> \\<psi> x ?g = f\"\n        using 1 x x\\<epsilon>.the_coext_prop G_ide by simp\n      show \"\\<And>g'. \\<guillemotleft>g' : y \\<rightarrow>\\<^sub>D G x\\<guillemotright> \\<and> \\<psi> x g' = f \\<Longrightarrow> g' = ?g\"\n        using 1 x y \\<psi>_inverts_coext G_ide x\\<epsilon>.the_coext_unique by force\n    qed\n\n    definition \\<phi>\n    where \"\\<phi> y f = (THE g. \\<guillemotleft>g : y \\<rightarrow>\\<^sub>D G (C.cod f)\\<guillemotright> \\<and> \\<psi> (C.cod f) g = f)\"\n\n    lemma \\<phi>_in_hom:\n    assumes \"D.ide y\" and \"\\<guillemotleft>f : F y \\<rightarrow>\\<^sub>C x\\<guillemotright>\"\n    shows \"\\<guillemotleft>\\<phi> y f : y \\<rightarrow>\\<^sub>D G x\\<guillemotright>\"\n      using assms \\<psi>_invertible \\<phi>_def theI' [of \"\\<lambda>g. \\<guillemotleft>g : y \\<rightarrow>\\<^sub>D G x\\<guillemotright> \\<and> \\<psi> x g = f\"]\n      by auto\n\n    lemma \\<phi>_\\<psi>:\n    assumes \"C.ide x\" and \"\\<guillemotleft>g : y \\<rightarrow>\\<^sub>D G x\\<guillemotright>\"\n    shows \"\\<phi> y (\\<psi> x g) = g\"\n    proof -\n      have \"C.cod (\\<psi> x g) = x\"\n        using assms \\<psi>_in_hom by auto\n      hence \"\\<phi> y (\\<psi> x g) = (THE g'. \\<guillemotleft>g' : y \\<rightarrow>\\<^sub>D G x\\<guillemotright> \\<and> \\<psi> x g' = \\<psi> x g)\"\n        using \\<phi>_def by auto\n      moreover have \"\\<exists>!g'. \\<guillemotleft>g' : y \\<rightarrow>\\<^sub>D G x\\<guillemotright> \\<and> \\<psi> x g' = \\<psi> x g\"\n        using assms \\<psi>_in_hom \\<psi>_invertible D.ide_dom by blast\n      moreover have \"\\<guillemotleft>g : y \\<rightarrow>\\<^sub>D G x\\<guillemotright> \\<and> \\<psi> x g = \\<psi> x g\"\n        using assms(2) by auto\n      ultimately show \"\\<phi> y (\\<psi> x g) = g\" by auto\n    qed\n\n    lemma \\<psi>_\\<phi>:\n    assumes \"D.ide y\" and \"\\<guillemotleft>f : F y \\<rightarrow>\\<^sub>C x\\<guillemotright>\"\n    shows \"\\<psi> x (\\<phi> y f) = f\"\n      using assms \\<psi>_invertible \\<phi>_def theI' [of \"\\<lambda>g. \\<guillemotleft>g : y \\<rightarrow>\\<^sub>D G x\\<guillemotright> \\<and> \\<psi> x g = f\"]\n      by auto\n\n    lemma \\<phi>_natural:\n    assumes \"\\<guillemotleft>f : x \\<rightarrow>\\<^sub>C x'\\<guillemotright>\" and \"\\<guillemotleft>g : y' \\<rightarrow>\\<^sub>D y\\<guillemotright>\" and \"\\<guillemotleft>h : F y \\<rightarrow>\\<^sub>C x\\<guillemotright>\"\n    shows \"\\<phi> y' (f \\<cdot>\\<^sub>C h \\<cdot>\\<^sub>C F g) = (G f \\<cdot>\\<^sub>D \\<phi> y h) \\<cdot>\\<^sub>D g\"\n    proof -\n      have \"C.ide x' \\<and> D.ide y \\<and> D.in_hom (\\<phi> y h) y (G x)\"\n        using assms \\<phi>_in_hom by auto\n      thus ?thesis\n        using assms D.comp_in_homI G.preserves_hom \\<psi>_natural [of f x x' g y' y \"\\<phi> y h\"] \\<phi>_\\<psi> \\<psi>_\\<phi>\n        by auto\n    qed\n\n    theorem induces_meta_adjunction:\n    shows \"meta_adjunction C D F G \\<phi> \\<psi>\"\n      using \\<phi>_in_hom \\<psi>_in_hom \\<phi>_\\<psi> \\<psi>_\\<phi> \\<phi>_natural D.comp_assoc\n      by (unfold_locales, simp_all)\n\n  end\n\n  text\\<open>\n    A right adjoint functor induces a meta-adjunction, modulo the choice of a\n    left adjoint and unit.\n\\<close>\n\n  context right_adjoint_functor\n  begin\n\n    definition Fo :: \"'d \\<Rightarrow> 'c\"\n    where \"Fo y = (SOME x. \\<exists>u. initial_arrow_to_functor C D G y x u)\"\n\n    definition \\<eta>o :: \"'d \\<Rightarrow> 'd\"\n    where \"\\<eta>o y = (SOME u. initial_arrow_to_functor C D G y (Fo y) u)\"\n\n    lemma Fo_\\<eta>o_initial:\n    assumes \"\\<exists>x u. initial_arrow_to_functor C D G y x u\"\n    shows \"initial_arrow_to_functor C D G y (Fo y) (\\<eta>o y)\"\n      using assms Fo_def \\<eta>o_def\n            someI_ex [of \"\\<lambda>x. \\<exists>u. initial_arrow_to_functor C D G y x u\"]\n            someI_ex [of \"\\<lambda>u. initial_arrow_to_functor C D G y (Fo y) u\"]\n      by simp\n\n    text\\<open>\n      The left adjoint @{term F} to @{term g} takes each arrow @{term g} of\n      @{term[source=true] D} to the unique @{term[source=true] C}-extension of\n      @{term \"D (\\<eta>o (D.cod g)) g\"} along @{term \"\\<eta>o (D.dom g)\"}.\n\\<close>\n\n    definition F :: \"'d \\<Rightarrow> 'c\"\n    where \"F g = (if D.arr g then\n                     initial_arrow_to_functor.the_ext C D G (Fo (D.dom g)) (\\<eta>o (D.dom g))\n                                  (Fo (D.cod g)) (\\<eta>o (D.cod g) \\<cdot>\\<^sub>D g)\n                  else C.null)\"\n\n    lemma F_ide:\n    assumes \"D.ide y\"\n    shows \"F y = Fo y\"\n    proof -\n      interpret initial_arrow_to_functor C D G y \\<open>Fo y\\<close> \\<open>\\<eta>o y\\<close>\n        using assms initial_arrows_exist Fo_\\<eta>o_initial by blast\n      have 1: \"arrow_to_functor C D G y (Fo y) (\\<eta>o y)\" ..\n      have \"is_ext (Fo y) (\\<eta>o y) (Fo y)\"\n        unfolding is_ext_def using arrow D.comp_ide_arr [of \"G (Fo y)\" \"\\<eta>o y\"] by force\n      hence \"Fo y = the_ext (Fo y) (\\<eta>o y)\" using 1 the_ext_unique by blast\n      moreover have \"\\<eta>o y = D (\\<eta>o (D.cod y)) y\"\n        using assms arrow D.comp_arr_ide D.comp_arr_dom by auto\n      ultimately show ?thesis\n        using assms F_def D.dom_cod D.in_homE D.ide_in_hom by metis\n    qed\n\n    \n\n    interpretation F: \"functor\" D C F using F_is_functor by auto\n\n    \n\n    interpretation FG: composite_functor D C D F G ..\n\n    interpretation \\<eta>: transformation_by_components D D D.map FG.map \\<eta>o\n    proof\n      fix y :: 'd\n      assume y: \"D.ide y\"\n      show \"\\<guillemotleft>\\<eta>o y : D.map y \\<rightarrow>\\<^sub>D FG.map y\\<guillemotright>\"\n      proof -\n        interpret initial_arrow_to_functor C D G y \\<open>Fo y\\<close> \\<open>\\<eta>o y\\<close>\n          using y Fo_\\<eta>o_initial initial_arrows_exist by simp\n        show ?thesis using y F_ide arrow by auto\n      qed\n      next\n      fix g :: 'd\n      assume g: \"D.arr g\"\n      show \"\\<eta>o (D.cod g) \\<cdot>\\<^sub>D D.map g = FG.map g \\<cdot>\\<^sub>D \\<eta>o (D.dom g)\"\n      proof -\n        let ?y = \"D.dom g\"\n        let ?y' = \"D.cod g\"\n        interpret y\\<eta>: initial_arrow_to_functor C D G ?y \\<open>Fo ?y\\<close> \\<open>\\<eta>o ?y\\<close>\n          using g Fo_\\<eta>o_initial initial_arrows_exist by simp\n        interpret y'\\<eta>: initial_arrow_to_functor C D G ?y' \\<open>Fo ?y'\\<close> \\<open>\\<eta>o ?y'\\<close>\n          using g Fo_\\<eta>o_initial initial_arrows_exist by simp\n        have \"arrow_to_functor C D G ?y (Fo ?y') (\\<eta>o ?y' \\<cdot>\\<^sub>D g)\"\n          using g y'\\<eta>.arrow by (unfold_locales, auto)\n        moreover have \"F g = y\\<eta>.the_ext (Fo ?y') (\\<eta>o ?y' \\<cdot>\\<^sub>D g)\"\n          using g F_simp by blast\n        ultimately have \"y\\<eta>.is_ext (Fo ?y') (\\<eta>o ?y' \\<cdot>\\<^sub>D g) (F g)\"\n          using y\\<eta>.the_ext_prop y\\<eta>.is_ext_def by auto\n        thus ?thesis\n          using g y\\<eta>.is_ext_def by simp\n      qed\n    qed\n\n    definition \\<phi>\n    where \"\\<phi> y h = D (G h) (\\<eta>.map y)\"\n\n    lemma \\<phi>_in_hom:\n    assumes y: \"D.ide y\" and f: \"\\<guillemotleft>f : F y \\<rightarrow>\\<^sub>C x\\<guillemotright>\"\n    shows \"\\<guillemotleft>\\<phi> y f : y \\<rightarrow>\\<^sub>D G x\\<guillemotright>\"\n      unfolding \\<phi>_def using assms \\<eta>.maps_ide_in_hom by auto\n\n    lemma \\<phi>_natural:\n    assumes f: \"\\<guillemotleft>f : x \\<rightarrow>\\<^sub>C x'\\<guillemotright>\" and g: \"\\<guillemotleft>g : y' \\<rightarrow>\\<^sub>D y\\<guillemotright>\" and h: \"\\<guillemotleft>h : F y \\<rightarrow>\\<^sub>C x\\<guillemotright>\"\n    shows \"\\<phi> y' (f \\<cdot>\\<^sub>C h \\<cdot>\\<^sub>C F g) = (G f \\<cdot>\\<^sub>D \\<phi> y h) \\<cdot>\\<^sub>D g\"\n    proof -\n      have \"(G f \\<cdot>\\<^sub>D \\<phi> y h) \\<cdot>\\<^sub>D g = (G f \\<cdot>\\<^sub>D G h \\<cdot>\\<^sub>D \\<eta>.map y) \\<cdot>\\<^sub>D g\"\n        unfolding \\<phi>_def by auto\n      also have \"... = (G f \\<cdot>\\<^sub>D G h) \\<cdot>\\<^sub>D \\<eta>.map y \\<cdot>\\<^sub>D g\"\n        using D.comp_assoc by fastforce\n      also have \"... = G (f \\<cdot>\\<^sub>C h) \\<cdot>\\<^sub>D G (F g) \\<cdot>\\<^sub>D \\<eta>.map y'\"\n        using f g h \\<eta>.naturality by fastforce\n      also have \"... = (G (f \\<cdot>\\<^sub>C h) \\<cdot>\\<^sub>D G (F g)) \\<cdot>\\<^sub>D \\<eta>.map y'\"\n        using D.comp_assoc by fastforce\n      also have \"... = G (f \\<cdot>\\<^sub>C h \\<cdot>\\<^sub>C F g) \\<cdot>\\<^sub>D \\<eta>.map y'\"\n        using f g h D.comp_assoc by fastforce\n      also have \"... = \\<phi> y' (f \\<cdot>\\<^sub>C h \\<cdot>\\<^sub>C F g)\"\n        unfolding \\<phi>_def by auto\n      finally show ?thesis by auto\n    qed\n\n    lemma \\<phi>_inverts_ext:\n    assumes y: \"D.ide y\" and f: \"\\<guillemotleft>f : F y \\<rightarrow>\\<^sub>C x\\<guillemotright>\"\n    shows \"arrow_to_functor.is_ext C D G (F y) (\\<eta>.map y) x (\\<phi> y f) f\"\n    proof -\n      interpret y\\<eta>: arrow_to_functor C D G y \\<open>F y\\<close> \\<open>\\<eta>.map y\\<close>\n        using y \\<eta>.maps_ide_in_hom by (unfold_locales, auto)\n      show \"y\\<eta>.is_ext x (\\<phi> y f) f\"\n        using f y \\<phi>_def y\\<eta>.is_ext_def F_ide by (unfold_locales, auto)\n    qed\n\n    lemma \\<phi>_invertible:\n    assumes x: \"C.ide x\" and g: \"\\<guillemotleft>g : y \\<rightarrow>\\<^sub>D G x\\<guillemotright>\"\n    shows \"\\<exists>!f. \\<guillemotleft>f : F y \\<rightarrow>\\<^sub>C x\\<guillemotright> \\<and> \\<phi> y f = g\"\n    proof\n      have y: \"D.ide y\" using g by auto\n      interpret y\\<eta>: initial_arrow_to_functor C D G y \\<open>Fo y\\<close> \\<open>\\<eta>o y\\<close>\n        using y initial_arrows_exist Fo_\\<eta>o_initial by auto\n      have 1: \"arrow_to_functor C D G y x g\"\n        using x g by (unfold_locales, auto)\n      let ?f = \"y\\<eta>.the_ext x g\"\n      have \"\\<phi> y ?f = g\"\n        using \\<phi>_def y\\<eta>.the_ext_prop 1 F_ide x y \\<phi>_inverts_ext y\\<eta>.is_ext_def by fastforce\n      moreover have \"\\<guillemotleft>?f : F y \\<rightarrow>\\<^sub>C x\\<guillemotright>\"\n        using 1 y y\\<eta>.the_ext_prop F_ide by simp\n      ultimately show \"\\<guillemotleft>?f : F y \\<rightarrow>\\<^sub>C x\\<guillemotright> \\<and> \\<phi> y ?f = g\" by auto\n      show \"\\<And>f'. \\<guillemotleft>f' : F y \\<rightarrow>\\<^sub>C x\\<guillemotright> \\<and> \\<phi> y f' = g \\<Longrightarrow> f' = ?f\"\n        using 1 y \\<phi>_inverts_ext y\\<eta>.the_ext_unique F_ide by force\n    qed\n\n    definition \\<psi>\n    where \"\\<psi> x g = (THE f. \\<guillemotleft>f : F (D.dom g) \\<rightarrow>\\<^sub>C x\\<guillemotright> \\<and> \\<phi> (D.dom g) f = g)\"\n\n    lemma \\<psi>_in_hom:\n    assumes \"C.ide x\" and \"\\<guillemotleft>g : y \\<rightarrow>\\<^sub>D G x\\<guillemotright>\"\n    shows \"C.in_hom (\\<psi> x g) (F y) x\"\n      using assms \\<phi>_invertible \\<psi>_def theI' [of \"\\<lambda>f. \\<guillemotleft>f : F y \\<rightarrow>\\<^sub>C x\\<guillemotright> \\<and> \\<phi> y f = g\"]\n      by auto\n\n    lemma \\<psi>_\\<phi>:\n    assumes \"D.ide y\" and \"\\<guillemotleft>f : F y \\<rightarrow>\\<^sub>C x\\<guillemotright>\"\n    shows \"\\<psi> x (\\<phi> y f) = f\"\n    proof -\n      have \"D.dom (\\<phi> y f) = y\" using assms \\<phi>_in_hom by blast\n      hence \"\\<psi> x (\\<phi> y f) = (THE f'. \\<guillemotleft>f' : F y \\<rightarrow>\\<^sub>C x\\<guillemotright> \\<and> \\<phi> y f' = \\<phi> y f)\"\n        using \\<psi>_def by auto\n      moreover have \"\\<exists>!f'. \\<guillemotleft>f' : F y \\<rightarrow>\\<^sub>C x\\<guillemotright> \\<and> \\<phi> y f' = \\<phi> y f\"\n        using assms \\<phi>_in_hom \\<phi>_invertible C.ide_cod by blast\n      ultimately show ?thesis using assms(2) by auto\n    qed\n\n    lemma \\<phi>_\\<psi>:\n    assumes \"C.ide x\" and \"\\<guillemotleft>g : y \\<rightarrow>\\<^sub>D G x\\<guillemotright>\"\n    shows \"\\<phi> y (\\<psi> x g) = g\"\n      using assms \\<phi>_invertible \\<psi>_def theI' [of \"\\<lambda>f. \\<guillemotleft>f : F y \\<rightarrow>\\<^sub>C x\\<guillemotright> \\<and> \\<phi> y f = g\"]\n      by auto\n\n    theorem induces_meta_adjunction:\n    shows \"meta_adjunction C D F G \\<phi> \\<psi>\"\n      using \\<phi>_in_hom \\<psi>_in_hom \\<phi>_\\<psi> \\<psi>_\\<phi> \\<phi>_natural D.comp_assoc\n      by (unfold_locales, auto)\n\n  end\n\n  section \"Meta-Adjunctions Induce Hom-Adjunctions\"\n\n  text\\<open>\n    To obtain a hom-adjunction from a meta-adjunction, we need to exhibit hom-functors\n    from @{term C} and @{term D} to a common set category @{term S}, so it is necessary\n    to apply an actual concrete construction of such a category.\n    We use the category \\<open>SetCat\\<close> whose element type is the disjoint sum\n    @{typ \"('c+'d)\"} of the arrow types of @{term C} and @{term D}.\n\\<close>\n\n  context meta_adjunction\n  begin\n\n    definition inC :: \"'c \\<Rightarrow> ('c+'d) setcat.arr\"\n    where \"inC \\<equiv> SetCat.UP o Inl\"\n\n    definition inD :: \"'d \\<Rightarrow> ('c+'d) setcat.arr\"\n    where \"inD \\<equiv> SetCat.UP o Inr\"\n\n    interpretation S: set_category \\<open>SetCat.comp :: ('c+'d) setcat.arr comp\\<close>\n      using SetCat.is_set_category by auto\n    interpretation Cop: dual_category C ..\n    interpretation Dop: dual_category D ..\n    interpretation CopxC: product_category Cop.comp C ..\n    interpretation DopxD: product_category Dop.comp D ..\n    interpretation DopxC: product_category Dop.comp C ..\n    interpretation HomC: hom_functor C \\<open>SetCat.comp :: ('c+'d) setcat.arr comp\\<close> \\<open>\\<lambda>_. inC\\<close>\n      apply unfold_locales\n      unfolding inC_def using SetCat.UP_mapsto\n       apply auto[1]\n      using SetCat.inj_UP\n      by (metis injD inj_Inl inj_compose inj_on_def)\n    interpretation HomD: hom_functor D \\<open>SetCat.comp :: ('c+'d) setcat.arr comp\\<close> \\<open>\\<lambda>_. inD\\<close>\n      apply unfold_locales\n      unfolding inD_def using SetCat.UP_mapsto\n       apply auto[1]\n      using SetCat.inj_UP\n      by (metis injD inj_Inr inj_compose inj_on_def)\n    interpretation Fop: dual_functor D C F ..\n    interpretation FopxC: product_functor Dop.comp C Cop.comp C Fop.map C.map ..\n    interpretation DopxG: product_functor Dop.comp C Dop.comp D Dop.map G ..\n    interpretation Hom_FopxC: composite_functor DopxC.comp CopxC.comp SetCat.comp\n                                                FopxC.map HomC.map ..\n    interpretation Hom_DopxG: composite_functor DopxC.comp DopxD.comp SetCat.comp\n                                                DopxG.map HomD.map ..\n\n    lemma inC_\\<psi> [simp]:\n    assumes \"C.ide b\" and \"C.ide a\" and \"x \\<in> inC ` C.hom b a\"\n    shows \"inC (HomC.\\<psi> (b, a) x) = x\"\n      using assms by auto\n\n    lemma \\<psi>_inC [simp]:\n    assumes \"C.arr f\"\n    shows \"HomC.\\<psi> (C.dom f, C.cod f) (inC f) = f\"\n      using assms HomC.\\<psi>_\\<phi> by blast\n\n    lemma inD_\\<psi> [simp]:\n    assumes \"D.ide b\" and \"D.ide a\" and \"x \\<in> inD ` D.hom b a\"\n    shows \"inD (HomD.\\<psi> (b, a) x) = x\"\n      using assms by auto\n\n    lemma \\<psi>_inD [simp]:\n    assumes \"D.arr f\"\n    shows \"HomD.\\<psi> (D.dom f, D.cod f) (inD f) = f\"\n      using assms HomD.\\<psi>_\\<phi> by blast\n\n    lemma Hom_FopxC_simp:\n    assumes \"DopxC.arr gf\"\n    shows \"Hom_FopxC.map gf =\n              S.mkArr (HomC.set (F (D.cod (fst gf)), C.dom (snd gf)))\n                      (HomC.set (F (D.dom (fst gf)), C.cod (snd gf)))            \n                      (inC \\<circ> (\\<lambda>h. snd gf \\<cdot>\\<^sub>C h \\<cdot>\\<^sub>C F (fst gf))\n                           \\<circ> HomC.\\<psi> (F (D.cod (fst gf)), C.dom (snd gf)))\"\n      using assms HomC.map_def by simp\n\n    lemma Hom_DopxG_simp:\n    assumes \"DopxC.arr gf\"\n    shows \"Hom_DopxG.map gf =\n              S.mkArr (HomD.set (D.cod (fst gf), G (C.dom (snd gf))))\n                      (HomD.set (D.dom (fst gf), G (C.cod (snd gf))))           \n                      (inD \\<circ> (\\<lambda>h. G (snd gf) \\<cdot>\\<^sub>D h \\<cdot>\\<^sub>D fst gf)\n                           \\<circ> HomD.\\<psi> (D.cod (fst gf), G (C.dom (snd gf))))\"\n      using assms HomD.map_def by simp\n                      \n    definition \\<Phi>o\n    where \"\\<Phi>o yx = S.mkArr (HomC.set (F (fst yx), snd yx))\n                           (HomD.set (fst yx, G (snd yx)))\n                           (inD o \\<phi> (fst yx) o HomC.\\<psi> (F (fst yx), snd yx))\"\n\n    lemma \\<Phi>o_in_hom:\n    assumes yx: \"DopxC.ide yx\"\n    shows \"\\<guillemotleft>\\<Phi>o yx : Hom_FopxC.map yx \\<rightarrow>\\<^sub>S Hom_DopxG.map yx\\<guillemotright>\"\n    proof -\n      have \"Hom_FopxC.map yx = S.mkIde (HomC.set (F (fst yx), snd yx))\"\n        using yx HomC.map_ide by auto\n      moreover have \"Hom_DopxG.map yx = S.mkIde (HomD.set (fst yx, G (snd yx)))\"\n        using yx HomD.map_ide by auto\n      moreover have\n          \"\\<guillemotleft>S.mkArr (HomC.set (F (fst yx), snd yx)) (HomD.set (fst yx, G (snd yx)))\n                    (inD \\<circ> \\<phi> (fst yx) \\<circ> HomC.\\<psi> (F (fst yx), snd yx)) :\n              S.mkIde (HomC.set (F (fst yx), snd yx))\n                 \\<rightarrow>\\<^sub>S S.mkIde (HomD.set (fst yx, G (snd yx)))\\<guillemotright>\"\n      proof (intro S.mkArr_in_hom)\n        show \"HomC.set (F (fst yx), snd yx) \\<subseteq> S.Univ\" using yx HomC.set_subset_Univ by simp\n        show \"HomD.set (fst yx, G (snd yx)) \\<subseteq> S.Univ\" using yx HomD.set_subset_Univ by simp\n        show \"inD o \\<phi> (fst yx) o HomC.\\<psi> (F (fst yx), snd yx)\n                 \\<in> HomC.set (F (fst yx), snd yx) \\<rightarrow> HomD.set (fst yx, G (snd yx))\"\n        proof\n          fix x\n          assume x: \"x \\<in> HomC.set (F (fst yx), snd yx)\"\n          show \"(inD o \\<phi> (fst yx) o HomC.\\<psi> (F (fst yx), snd yx)) x\n                  \\<in> HomD.set (fst yx, G (snd yx))\"\n            using x yx HomC.\\<psi>_mapsto [of \"F (fst yx)\" \"snd yx\"]\n                  \\<phi>_in_hom [of \"fst yx\"] HomD.\\<phi>_mapsto [of \"fst yx\" \"G (snd yx)\"]\n            by auto\n        qed\n      qed\n      ultimately show ?thesis using \\<Phi>o_def by auto\n    qed\n\n    interpretation \\<Phi>: transformation_by_components DopxC.comp SetCat.comp\n                                                   Hom_FopxC.map Hom_DopxG.map \\<Phi>o\n    proof\n      fix yx\n      assume yx: \"DopxC.ide yx\"\n      show \"\\<guillemotleft>\\<Phi>o yx : Hom_FopxC.map yx \\<rightarrow>\\<^sub>S Hom_DopxG.map yx\\<guillemotright>\"\n        using yx \\<Phi>o_in_hom by auto\n      next\n      fix gf\n      assume gf: \"DopxC.arr gf\"\n      show \"SetCat.comp (\\<Phi>o (DopxC.cod gf)) (Hom_FopxC.map gf)\n                = SetCat.comp (Hom_DopxG.map gf) (\\<Phi>o (DopxC.dom gf))\"\n      proof -\n        let ?g = \"fst gf\"\n        let ?f = \"snd gf\"\n        let ?x = \"C.dom ?f\"\n        let ?x' = \"C.cod ?f\"\n        let ?y = \"D.cod ?g\"\n        let ?y' = \"D.dom ?g\"\n        let ?Fy = \"F ?y\"\n        let ?Fy' = \"F ?y'\"\n        let ?Fg = \"F ?g\"\n        let ?Gx = \"G ?x\"\n        let ?Gx' = \"G ?x'\"\n        let ?Gf = \"G ?f\"\n        have 1: \"S.arr (Hom_FopxC.map gf) \\<and>\n                 Hom_FopxC.map gf = S.mkArr (HomC.set (?Fy, ?x)) (HomC.set (?Fy', ?x'))\n                                            (inC o (\\<lambda>h. ?f \\<cdot>\\<^sub>C h \\<cdot>\\<^sub>C ?Fg) o HomC.\\<psi> (?Fy, ?x))\"\n          using gf Hom_FopxC.preserves_arr Hom_FopxC_simp by blast\n        have 2: \"S.arr (\\<Phi>o (DopxC.cod gf)) \\<and>\n                 \\<Phi>o (DopxC.cod gf) = S.mkArr (HomC.set (?Fy', ?x')) (HomD.set (?y', ?Gx'))\n                                             (inD o \\<phi> ?y' o HomC.\\<psi> (?Fy', ?x'))\"\n          using gf \\<Phi>o_in_hom [of \"DopxC.cod gf\"] \\<Phi>o_def [of \"DopxC.cod gf\"] \\<phi>_in_hom\n          by auto\n        have 3: \"S.arr (\\<Phi>o (DopxC.dom gf)) \\<and>\n                 \\<Phi>o (DopxC.dom gf) = S.mkArr (HomC.set (?Fy, ?x)) (HomD.set (?y, ?Gx))\n                                             (inD o \\<phi> ?y o HomC.\\<psi> (?Fy, ?x))\"\n          using gf \\<Phi>o_in_hom [of \"DopxC.dom gf\"] \\<Phi>o_def [of \"DopxC.dom gf\"] \\<phi>_in_hom\n          by auto\n        have 4: \"S.arr (Hom_DopxG.map gf) \\<and>\n                 Hom_DopxG.map gf = S.mkArr (HomD.set (?y, ?Gx)) (HomD.set (?y', ?Gx'))\n                                            (inD o (\\<lambda>h. ?Gf \\<cdot>\\<^sub>D h \\<cdot>\\<^sub>D ?g) o HomD.\\<psi> (?y, ?Gx))\"\n          using gf Hom_DopxG.preserves_arr Hom_DopxG_simp by blast\n        have 5: \"S.seq (\\<Phi>o (DopxC.cod gf)) (Hom_FopxC.map gf) \\<and>\n                 SetCat.comp (\\<Phi>o (DopxC.cod gf)) (Hom_FopxC.map gf)\n                     = S.mkArr (HomC.set (?Fy, ?x)) (HomD.set (?y', ?Gx'))\n                               ((inD o \\<phi> ?y' o HomC.\\<psi> (?Fy', ?x'))\n                                 o (inC o (\\<lambda>h. ?f \\<cdot>\\<^sub>C h \\<cdot>\\<^sub>C ?Fg) o HomC.\\<psi> (?Fy, ?x)))\"\n        proof -\n          have \"S.seq (\\<Phi>o (DopxC.cod gf)) (Hom_FopxC.map gf)\"\n            using gf 1 2 \\<Phi>o_in_hom Hom_FopxC.preserves_hom by (intro S.seqI', auto)\n          thus ?thesis\n            using S.comp_mkArr 1 2 by metis\n        qed\n        have 6: \"SetCat.comp (Hom_DopxG.map gf) (\\<Phi>o (DopxC.dom gf))\n                  = S.mkArr (HomC.set (?Fy, ?x)) (HomD.set (?y', ?Gx'))\n                            ((inD o (\\<lambda>h. ?Gf \\<cdot>\\<^sub>D h \\<cdot>\\<^sub>D ?g) o HomD.\\<psi> (?y, ?Gx))\n                              o (inD o \\<phi> ?y o HomC.\\<psi> (?Fy, ?x)))\"\n        proof -\n          have \"S.seq (Hom_DopxG.map gf) (\\<Phi>o (DopxC.dom gf))\"\n            using gf 3 4 S.arr_mkArr S.cod_mkArr S.dom_mkArr by (intro S.seqI; metis)\n          thus ?thesis\n            using 3 4 S.comp_mkArr by metis\n        qed\n        have 7:\n          \"restrict ((inD o \\<phi> ?y' o HomC.\\<psi> (?Fy', ?x'))\n                      o (inC o (\\<lambda>h. ?f \\<cdot>\\<^sub>C h \\<cdot>\\<^sub>C ?Fg) o HomC.\\<psi> (?Fy, ?x))) (HomC.set (?Fy, ?x))\n             = restrict ((inD o (\\<lambda>h. ?Gf \\<cdot>\\<^sub>D h \\<cdot>\\<^sub>D ?g) o HomD.\\<psi> (?y, ?Gx))\n                          o (inD o \\<phi> ?y o HomC.\\<psi> (?Fy, ?x))) (HomC.set (?Fy, ?x))\"\n        proof (intro restrict_ext)\n          show \"\\<And>h. h \\<in> HomC.set (?Fy, ?x) \\<Longrightarrow>\n                     ((inD o \\<phi> ?y' o HomC.\\<psi> (?Fy', ?x'))\n                       o (inC o (\\<lambda>h. ?f \\<cdot>\\<^sub>C h \\<cdot>\\<^sub>C ?Fg) o HomC.\\<psi> (?Fy, ?x))) h\n                       = ((inD o (\\<lambda>h. ?Gf \\<cdot>\\<^sub>D h \\<cdot>\\<^sub>D ?g) o HomD.\\<psi> (?y, ?Gx))\n                           o (inD o \\<phi> ?y o HomC.\\<psi> (?Fy, ?x))) h\"\n          proof -\n            fix h\n            assume h: \"h \\<in> HomC.set (?Fy, ?x)\"\n            have \\<psi>h: \"\\<guillemotleft>HomC.\\<psi> (?Fy, ?x) h : ?Fy \\<rightarrow>\\<^sub>C ?x\\<guillemotright>\"\n              using gf h HomC.\\<psi>_mapsto [of ?Fy ?x] CopxC.ide_char by auto\n            show \"((inD o \\<phi> ?y' o HomC.\\<psi> (?Fy', ?x'))\n                       o (inC o (\\<lambda>h. ?f \\<cdot>\\<^sub>C h \\<cdot>\\<^sub>C ?Fg) o HomC.\\<psi> (?Fy, ?x))) h\n                       = ((inD o (\\<lambda>h. ?Gf \\<cdot>\\<^sub>D h \\<cdot>\\<^sub>D ?g) o HomD.\\<psi> (?y, ?Gx))\n                           o (inD o \\<phi> ?y o HomC.\\<psi> (?Fy, ?x))) h\"\n            proof -\n              have\n                \"((inD o \\<phi> ?y' o HomC.\\<psi> (?Fy', ?x'))\n                   o (inC o (\\<lambda>h. ?f \\<cdot>\\<^sub>C h \\<cdot>\\<^sub>C ?Fg) o HomC.\\<psi> (?Fy, ?x))) h\n                   = inD (\\<phi> ?y' (HomC.\\<psi> (?Fy', ?x') (inC (?f \\<cdot>\\<^sub>C HomC.\\<psi> (?Fy, ?x) h \\<cdot>\\<^sub>C ?Fg))))\"\n                by simp\n              also have \"... = inD (\\<phi> ?y' (?f \\<cdot>\\<^sub>C HomC.\\<psi> (?Fy, ?x) h \\<cdot>\\<^sub>C ?Fg))\"\n                using gf \\<psi>h HomC.\\<phi>_mapsto HomC.\\<psi>_mapsto \\<phi>_in_hom\n                      \\<psi>_inC [of \"?f \\<cdot>\\<^sub>C HomC.\\<psi> (?Fy, ?x) h \\<cdot>\\<^sub>C ?Fg\"]\n                by auto\n              also have \"... = inD (D ?Gf (D (\\<phi> ?y (HomC.\\<psi> (?Fy, ?x) h)) ?g))\"\n              proof -\n                have \"\\<guillemotleft>?f : C.dom ?f \\<rightarrow> C.cod ?f\\<guillemotright>\"\n                  using gf by auto\n                moreover have \"\\<guillemotleft>?g : D.dom ?g \\<rightarrow>\\<^sub>D D.cod ?g\\<guillemotright>\"\n                  using gf by auto\n                ultimately show ?thesis\n                  using gf \\<psi>h \\<phi>_in_hom G.preserves_hom C.in_homE D.in_homE\n                        \\<phi>_naturality [of ?f ?x ?x' ?g ?y' ?y \"HomC.\\<psi> (?Fy, ?x) h\"]\n                  by simp\n              qed\n              also have \"... =\n                  inD (D ?Gf (D (HomD.\\<psi> (?y, ?Gx) (inD (\\<phi> ?y (HomC.\\<psi> (?Fy, ?x) h)))) ?g))\"\n                using gf \\<psi>h \\<phi>_in_hom by simp\n              also have \"... = ((inD o (\\<lambda>h. ?Gf \\<cdot>\\<^sub>D h \\<cdot>\\<^sub>D ?g) o HomD.\\<psi> (?y, ?Gx))\n                                o (inD o \\<phi> ?y o HomC.\\<psi> (?Fy, ?x))) h\"\n                by simp\n              finally show ?thesis by auto\n            qed\n          qed\n        qed\n        have 8: \"S.mkArr (HomC.set (?Fy, ?x)) (HomD.set (?y', ?Gx'))\n                         ((inD o \\<phi> ?y' o HomC.\\<psi> (?Fy', ?x'))\n                           o (inC o (\\<lambda>h. ?f \\<cdot>\\<^sub>C h \\<cdot>\\<^sub>C ?Fg) o HomC.\\<psi> (?Fy, ?x)))\n                    = S.mkArr (HomC.set (?Fy, ?x)) (HomD.set (?y', ?Gx'))\n                              ((inD o (\\<lambda>h. ?Gf \\<cdot>\\<^sub>D h \\<cdot>\\<^sub>D ?g) o HomD.\\<psi> (?y, ?Gx))\n                                o (inD o \\<phi> ?y o HomC.\\<psi> (?Fy, ?x)))\"\n        proof (intro S.mkArr_eqI')\n          show \"S.arr (S.mkArr (HomC.set (?Fy, ?x)) (HomD.set (?y', ?Gx'))\n                               ((inD o \\<phi> ?y' o HomC.\\<psi> (?Fy', ?x'))\n                                o (inC o (\\<lambda>h. ?f \\<cdot>\\<^sub>C h \\<cdot>\\<^sub>C ?Fg) o HomC.\\<psi> (?Fy, ?x))))\"\n            using 5 by metis\n          show \"\\<And>t. t \\<in> HomC.set (?Fy, ?x) \\<Longrightarrow>\n                      ((inD o \\<phi> ?y' o HomC.\\<psi> (?Fy', ?x'))\n                             o (inC o (\\<lambda>h. ?f \\<cdot>\\<^sub>C h \\<cdot>\\<^sub>C ?Fg) o HomC.\\<psi> (?Fy, ?x))) t\n                      = ((inD o (\\<lambda>h. ?Gf \\<cdot>\\<^sub>D h \\<cdot>\\<^sub>D ?g) o HomD.\\<psi> (?y, ?Gx))\n                              o (inD o \\<phi> ?y o HomC.\\<psi> (?Fy, ?x))) t\"\n            using 7 restrict_apply by fast\n        qed\n        show ?thesis using 5 6 8 by auto\n      qed\n    qed\n\n    lemma \\<Phi>_simp:\n    assumes YX: \"DopxC.ide yx\"\n    shows \"\\<Phi>.map yx =\n           S.mkArr (HomC.set (F (fst yx), snd yx)) (HomD.set (fst yx, G (snd yx)))\n                   (inD o \\<phi> (fst yx) o HomC.\\<psi> (F (fst yx), snd yx))\"\n      using YX \\<Phi>o_def by simp\n      \n    abbreviation \\<Psi>o\n    where \"\\<Psi>o yx \\<equiv> S.mkArr (HomD.set (fst yx, G (snd yx))) (HomC.set (F (fst yx), snd yx))\n                            (inC o \\<psi> (snd yx) o HomD.\\<psi> (fst yx, G (snd yx)))\"\n\n    lemma \\<Psi>o_in_hom:\n    assumes yx: \"DopxC.ide yx\"\n    shows \"\\<guillemotleft>\\<Psi>o yx : Hom_DopxG.map yx \\<rightarrow>\\<^sub>S Hom_FopxC.map yx\\<guillemotright>\"\n    proof -\n      have \"Hom_FopxC.map yx = S.mkIde (HomC.set (F (fst yx), snd yx))\"\n        using yx HomC.map_ide by auto\n      moreover have \"Hom_DopxG.map yx = S.mkIde (HomD.set (fst yx, G (snd yx)))\"\n        using yx HomD.map_ide by auto\n      moreover have \"\\<guillemotleft>\\<Psi>o yx : S.mkIde (HomD.set (fst yx, G (snd yx)))\n                                 \\<rightarrow>\\<^sub>S S.mkIde (HomC.set (F (fst yx), snd yx))\\<guillemotright>\"\n      proof (intro S.mkArr_in_hom)\n        show \"HomC.set (F (fst yx), snd yx) \\<subseteq> S.Univ\" using yx HomC.set_subset_Univ by simp\n        show \"HomD.set (fst yx, G (snd yx)) \\<subseteq> S.Univ\" using yx HomD.set_subset_Univ by simp\n        show \"inC o \\<psi> (snd yx) o HomD.\\<psi> (fst yx, G (snd yx))\n                 \\<in> HomD.set (fst yx, G (snd yx)) \\<rightarrow> HomC.set (F (fst yx), snd yx)\"\n        proof\n          fix x\n          assume x: \"x \\<in> HomD.set (fst yx, G (snd yx))\"\n          show \"(inC o \\<psi> (snd yx) o HomD.\\<psi> (fst yx, G (snd yx))) x\n                  \\<in> HomC.set (F (fst yx), snd yx)\"\n            using x yx HomD.\\<psi>_mapsto [of \"fst yx\" \"G (snd yx)\"] \\<psi>_in_hom [of \"snd yx\"]\n                  HomC.\\<phi>_mapsto [of \"F (fst yx)\" \"snd yx\"]\n            by auto\n        qed\n      qed\n      ultimately show ?thesis by auto\n    qed\n\n    lemma \\<Phi>_inv:\n    assumes yx: \"DopxC.ide yx\"\n    shows \"S.inverse_arrows (\\<Phi>.map yx) (\\<Psi>o yx)\"\n    proof -\n      have 1: \"\\<guillemotleft>\\<Phi>.map yx : Hom_FopxC.map yx \\<rightarrow>\\<^sub>S Hom_DopxG.map yx\\<guillemotright>\"\n        using yx \\<Phi>.preserves_hom [of yx yx yx] DopxC.ide_in_hom by blast\n      have 2: \"\\<guillemotleft>\\<Psi>o yx : Hom_DopxG.map yx \\<rightarrow>\\<^sub>S Hom_FopxC.map yx\\<guillemotright>\"\n        using yx \\<Psi>o_in_hom by simp\n      have 3: \"\\<Phi>.map yx = S.mkArr (HomC.set (F (fst yx), snd yx))\n                                   (HomD.set (fst yx, G (snd yx)))\n                                   (inD o \\<phi> (fst yx) o HomC.\\<psi> (F (fst yx), snd yx))\"\n        using yx \\<Phi>_simp by blast\n      have antipar: \"S.antipar (\\<Phi>.map yx) (\\<Psi>o yx)\"\n        using 1 2 by fastforce\n      moreover have \"S.ide (SetCat.comp (\\<Psi>o yx) (\\<Phi>.map yx))\"\n      proof -\n        have \"SetCat.comp (\\<Psi>o yx) (\\<Phi>.map yx) =\n                  S.mkArr (HomC.set (F (fst yx), snd yx)) (HomC.set (F (fst yx), snd yx))\n                          ((inC o \\<psi> (snd yx) o HomD.\\<psi> (fst yx, G (snd yx)))\n                            o (inD o \\<phi> (fst yx) o HomC.\\<psi> (F (fst yx), snd yx)))\"\n          using 1 2 3 antipar by fastforce\n        also have\n          \"... = S.mkArr (HomC.set (F (fst yx), snd yx)) (HomC.set (F (fst yx), snd yx))\n                         (\\<lambda>x. x)\"\n        proof -\n          have\n            \"S.mkArr (HomC.set (F (fst yx), snd yx)) (HomC.set (F (fst yx), snd yx)) (\\<lambda>x. x)\n               = ...\"\n          proof\n            show\n              \"S.arr (S.mkArr (HomC.set (F (fst yx), snd yx)) (HomC.set (F (fst yx), snd yx))\n                     (\\<lambda>x. x))\"\n              using yx HomC.set_subset_Univ by simp\n            show \"\\<And>x. x \\<in> HomC.set (F (fst yx), snd yx) \\<Longrightarrow>\n                        x = ((inC o \\<psi> (snd yx) o HomD.\\<psi> (fst yx, G (snd yx)))\n                             o (inD o \\<phi> (fst yx) o HomC.\\<psi> (F (fst yx), snd yx))) x\"\n            proof -\n              fix x\n              assume x: \"x \\<in> HomC.set (F (fst yx), snd yx)\"\n              have \"((inC o \\<psi> (snd yx) o HomD.\\<psi> (fst yx, G (snd yx)))\n                             o (inD o \\<phi> (fst yx) o HomC.\\<psi> (F (fst yx), snd yx))) x\n                      = inC (\\<psi> (snd yx) (HomD.\\<psi> (fst yx, G (snd yx))\n                              (inD (\\<phi> (fst yx) (HomC.\\<psi> (F (fst yx), snd yx) x)))))\"\n                by simp\n              also have \"... = inC (\\<psi> (snd yx) (\\<phi> (fst yx) (HomC.\\<psi> (F (fst yx), snd yx) x)))\"\n                using x yx HomC.\\<psi>_mapsto [of \"F (fst yx)\" \"snd yx\"] \\<phi>_in_hom by force\n              also have \"... = inC (HomC.\\<psi> (F (fst yx), snd yx) x)\"\n                using x yx HomC.\\<psi>_mapsto [of \"F (fst yx)\" \"snd yx\"] \\<psi>_\\<phi> by force\n              also have \"... = x\" using x yx inC_\\<psi> by simp\n              finally show \"x = ((inC o \\<psi> (snd yx) o HomD.\\<psi> (fst yx, G (snd yx)))\n                                   o (inD o \\<phi> (fst yx) o HomC.\\<psi> (F (fst yx), snd yx))) x\"\n                by auto\n            qed\n          qed\n          thus ?thesis by auto\n        qed\n        also have \"... = S.mkIde (HomC.set (F (fst yx), snd yx))\"\n          using yx S.mkIde_as_mkArr HomC.set_subset_Univ by force\n        finally have\n            \"SetCat.comp (\\<Psi>o yx) (\\<Phi>.map yx) = S.mkIde (HomC.set (F (fst yx), snd yx))\"\n          by auto\n        thus ?thesis using yx HomC.set_subset_Univ by simp\n      qed\n      moreover have \"S.ide (SetCat.comp (\\<Phi>.map yx) (\\<Psi>o yx))\"\n      proof -\n        have \"SetCat.comp (\\<Phi>.map yx) (\\<Psi>o yx) =\n                  S.mkArr (HomD.set (fst yx, G (snd yx))) (HomD.set (fst yx, G (snd yx)))\n                          ((inD o \\<phi> (fst yx) o HomC.\\<psi> (F (fst yx), snd yx))\n                            o (inC o \\<psi> (snd yx) o HomD.\\<psi> (fst yx, G (snd yx))))\"\n          using 1 2 3 S.comp_mkArr antipar by fastforce\n        also\n          have \"... = S.mkArr (HomD.set (fst yx, G (snd yx))) (HomD.set (fst yx, G (snd yx)))\n                              (\\<lambda>x. x)\"\n        proof -\n          have\n            \"S.mkArr (HomD.set (fst yx, G (snd yx))) (HomD.set (fst yx, G (snd yx))) (\\<lambda>x. x)\n                = ...\"\n          proof\n            show\n              \"S.arr (S.mkArr (HomD.set (fst yx, G (snd yx))) (HomD.set (fst yx, G (snd yx)))\n                     (\\<lambda>x. x))\"\n              using yx HomD.set_subset_Univ by simp\n            show \"\\<And>x. x \\<in> (HomD.set (fst yx, G (snd yx))) \\<Longrightarrow>\n                        x = ((inD o \\<phi> (fst yx) o HomC.\\<psi> (F (fst yx), snd yx))\n                            o (inC o \\<psi> (snd yx) o HomD.\\<psi> (fst yx, G (snd yx)))) x\"\n            proof -\n              fix x\n              assume x: \"x \\<in> HomD.set (fst yx, G (snd yx))\"\n              have \"((inD o \\<phi> (fst yx) o HomC.\\<psi> (F (fst yx), snd yx))\n                          o (inC o \\<psi> (snd yx) o HomD.\\<psi> (fst yx, G (snd yx)))) x\n                       = inD (\\<phi> (fst yx) (HomC.\\<psi> (F (fst yx), snd yx)\n                            (inC (\\<psi> (snd yx) (HomD.\\<psi> (fst yx, G (snd yx)) x)))))\"\n                by simp\n              also have \"... = inD (\\<phi> (fst yx) (\\<psi> (snd yx) (HomD.\\<psi> (fst yx, G (snd yx)) x)))\"\n             proof -\n                have \"\\<guillemotleft>\\<psi> (snd yx) (HomD.\\<psi> (fst yx, G (snd yx)) x) : F (fst yx) \\<rightarrow> snd yx\\<guillemotright>\"\n                  using x yx HomD.\\<psi>_mapsto [of \"fst yx\" \"G (snd yx)\"] \\<psi>_in_hom by auto\n                thus ?thesis by simp\n              qed\n              also have \"... = inD (HomD.\\<psi> (fst yx, G (snd yx)) x)\"\n                using x yx HomD.\\<psi>_mapsto [of \"fst yx\" \"G (snd yx)\"] \\<phi>_\\<psi> by force\n              also have \"... = x\" using x yx inD_\\<psi> by simp\n              finally show \"x = ((inD o \\<phi> (fst yx) o HomC.\\<psi> (F (fst yx), snd yx))\n                                   o (inC o \\<psi> (snd yx) o HomD.\\<psi> (fst yx, G (snd yx)))) x\"\n                by auto\n            qed\n          qed\n          thus ?thesis by auto\n        qed\n        also have \"... = S.mkIde (HomD.set (fst yx, G (snd yx)))\"\n          using yx S.mkIde_as_mkArr HomD.set_subset_Univ by force\n        finally have\n            \"SetCat.comp (\\<Phi>.map yx) (\\<Psi>o yx) = S.mkIde (HomD.set (fst yx, G (snd yx)))\"\n          by auto\n        thus ?thesis using yx HomD.set_subset_Univ by simp\n      qed\n      ultimately show ?thesis by auto\n    qed\n\n    interpretation \\<Phi>: natural_isomorphism DopxC.comp SetCat.comp\n                                          Hom_FopxC.map Hom_DopxG.map \\<Phi>.map\n      apply (unfold_locales) using \\<Phi>_inv by blast\n\n    interpretation \\<Psi>: inverse_transformation DopxC.comp SetCat.comp\n                           Hom_FopxC.map Hom_DopxG.map \\<Phi>.map ..\n\n    interpretation \\<Phi>\\<Psi>: inverse_transformations DopxC.comp SetCat.comp\n                           Hom_FopxC.map Hom_DopxG.map \\<Phi>.map \\<Psi>.map\n      using \\<Psi>.inverts_components by (unfold_locales, simp)\n\n    abbreviation \\<Phi> where \"\\<Phi> \\<equiv> \\<Phi>.map\"\n    abbreviation \\<Psi> where \"\\<Psi> \\<equiv> \\<Psi>.map\"\n\n    abbreviation HomC where \"HomC \\<equiv> HomC.map\"\n    abbreviation \\<phi>C where \"\\<phi>C \\<equiv> \\<lambda>_. inC\"\n    abbreviation HomD where \"HomD \\<equiv> HomD.map\"\n    abbreviation \\<phi>D where \"\\<phi>D \\<equiv> \\<lambda>_. inD\"\n\n    theorem induces_hom_adjunction: \"hom_adjunction C D SetCat.comp \\<phi>C \\<phi>D F G \\<Phi> \\<Psi>\"\n      using F.is_extensional by (unfold_locales, auto)\n\n    lemma \\<Psi>_simp:\n    assumes yx: \"DopxC.ide yx\"\n    shows \"\\<Psi> yx = S.mkArr (HomD.set (fst yx, G (snd yx))) (HomC.set (F (fst yx), snd yx))\n                          (inC o \\<psi> (snd yx) o HomD.\\<psi> (fst yx, G (snd yx)))\"\n      using assms \\<Phi>o_def \\<Phi>_inv S.inverse_unique by simp\n\n    text\\<open>\n      The original @{term \\<phi>} and @{term \\<psi>} can be recovered from @{term \\<Phi>} and @{term \\<Psi>}.\n\\<close>\n\n    interpretation \\<Phi>: set_valued_transformation DopxC.comp SetCat.comp\n                                                Hom_FopxC.map Hom_DopxG.map \\<Phi>.map ..\n     \n    interpretation \\<Psi>: set_valued_transformation DopxC.comp SetCat.comp\n                                                Hom_DopxG.map Hom_FopxC.map \\<Psi>.map ..\n\n    lemma \\<phi>_in_terms_of_\\<Phi>':\n    assumes y: \"D.ide y\" and f: \"\\<guillemotleft>f: F y \\<rightarrow>\\<^sub>C x\\<guillemotright>\"\n    shows \"\\<phi> y f = (HomD.\\<psi> (y, G x) o \\<Phi>.FUN (y, x) o inC) f\"\n    proof -\n      have x: \"C.ide x\" using f by auto\n      have 1: \"S.arr (\\<Phi> (y, x))\" using x y by fastforce\n      have 2: \"\\<Phi> (y, x) = S.mkArr (HomC.set (F y, x)) (HomD.set (y, G x))\n                                  (inD o \\<phi> y o HomC.\\<psi> (F y, x))\"\n        using x y \\<Phi>o_def by auto\n      have \"(HomD.\\<psi> (y, G x) o \\<Phi>.FUN (y, x) o inC) f =\n              HomD.\\<psi> (y, G x)\n                     (restrict (inD o \\<phi> y o HomC.\\<psi> (F y, x)) (HomC.set (F y, x)) (inC f))\"\n        using 1 2 by simp\n      also have \"... = \\<phi> y f\"\n        using x y f HomC.\\<phi>_mapsto \\<phi>_in_hom HomC.\\<psi>_mapsto C.ide_in_hom D.ide_in_hom\n        by auto\n      finally show ?thesis by auto\n    qed\n\n    lemma \\<psi>_in_terms_of_\\<Psi>':\n    assumes x: \"C.ide x\" and g: \"\\<guillemotleft>g : y \\<rightarrow>\\<^sub>D G x\\<guillemotright>\"\n    shows \"\\<psi> x g = (HomC.\\<psi> (F y, x) o \\<Psi>.FUN (y, x) o inD) g\"\n    proof -\n      have y: \"D.ide y\" using g by auto\n      have 1: \"S.arr (\\<Psi> (y, x))\"\n        using x y \\<Psi>.preserves_reflects_arr [of \"(y, x)\"] by simp\n      have 2: \"\\<Psi> (y, x) = S.mkArr (HomD.set (y, G x)) (HomC.set (F y, x))\n                                   (inC o \\<psi> x o HomD.\\<psi> (y, G x))\"\n        using x y \\<Psi>_simp by force\n      have \"(HomC.\\<psi> (F y, x) o \\<Psi>.FUN (y, x) o inD) g =\n              HomC.\\<psi> (F y, x)\n                     (restrict (inC o \\<psi> x o HomD.\\<psi> (y, G x)) (HomD.set (y, G x)) (inD g))\"\n        using 1 2 by simp\n      also have \"... = \\<psi> x g\"\n        using x y g HomD.\\<phi>_mapsto \\<psi>_in_hom HomD.\\<psi>_mapsto C.ide_in_hom D.ide_in_hom\n        by auto\n      finally show ?thesis by auto\n    qed\n\n  end\n\n  section \"Hom-Adjunctions Induce Meta-Adjunctions\"\n\n  context hom_adjunction\n  begin\n\n    definition \\<phi> :: \"'d \\<Rightarrow> 'c \\<Rightarrow> 'd\"\n    where\n      \"\\<phi> y h = (HomD.\\<psi> (y, G (C.cod h)) o \\<Phi>.FUN (y, C.cod h) o \\<phi>C (F y, C.cod h)) h\"\n    \n    definition \\<psi> :: \"'c \\<Rightarrow> 'd \\<Rightarrow> 'c\"\n    where\n      \"\\<psi> x h = (HomC.\\<psi> (F (D.dom h), x) o \\<Psi>.FUN (D.dom h, x) o \\<phi>D (D.dom h, G x)) h\"\n\n    lemma Hom_FopxC_map_simp:\n    assumes \"DopxC.arr gf\"\n    shows \"Hom_FopxC.map gf =\n              S.mkArr (HomC.set (F (D.cod (fst gf)), C.dom (snd gf)))\n                      (HomC.set (F (D.dom (fst gf)), C.cod (snd gf)))            \n                      (\\<phi>C (F (D.dom (fst gf)), C.cod (snd gf))\n                           o (\\<lambda>h. snd gf \\<cdot>\\<^sub>C h \\<cdot>\\<^sub>C F (fst gf))\n                           o HomC.\\<psi> (F (D.cod (fst gf)), C.dom (snd gf)))\"\n      using assms HomC.map_def by simp\n\n    lemma Hom_DopxG_map_simp:\n    assumes \"DopxC.arr gf\"\n    shows \"Hom_DopxG.map gf =\n              S.mkArr (HomD.set (D.cod (fst gf), G (C.dom (snd gf))))\n                      (HomD.set (D.dom (fst gf), G (C.cod (snd gf))))           \n                      (\\<phi>D (D.dom (fst gf), G (C.cod (snd gf)))\n                           o (\\<lambda>h. G (snd gf) \\<cdot>\\<^sub>D h \\<cdot>\\<^sub>D fst gf)\n                           o HomD.\\<psi> (D.cod (fst gf), G (C.dom (snd gf))))\"\n      using assms HomD.map_def by simp\n                      \n    lemma \\<Phi>_Fun_mapsto:\n    assumes \"D.ide y\" and \"\\<guillemotleft>f : F y \\<rightarrow>\\<^sub>C x\\<guillemotright>\"\n    shows \"\\<Phi>.FUN (y, x) \\<in> HomC.set (F y, x) \\<rightarrow> HomD.set (y, G x)\"\n    proof -\n      have \"S.arr (\\<Phi> (y, x)) \\<and> \\<Phi>.DOM (y, x) = HomC.set (F y, x) \\<and>\n                                \\<Phi>.COD (y, x) = HomD.set (y, G x)\"\n        using assms HomC.set_map HomD.set_map by auto\n      thus ?thesis using S.Fun_mapsto by blast\n    qed\n\n    lemma \\<phi>_mapsto:\n    assumes y: \"D.ide y\"\n    shows \"\\<phi> y \\<in> C.hom (F y) x \\<rightarrow> D.hom y (G x)\"\n    proof\n      fix h\n      assume h: \"h \\<in> C.hom (F y) x\"\n      hence 1: \" \\<guillemotleft>h : F y \\<rightarrow>\\<^sub>C x\\<guillemotright>\" by simp\n      show \"\\<phi> y h \\<in> D.hom y (G x)\"\n      proof -\n        have \"\\<phi>C (F y, x) h \\<in> HomC.set (F y, x)\"\n          using y h 1 HomC.\\<phi>_mapsto [of \"F y\" x] by fastforce\n        hence \"\\<Phi>.FUN (y, x) (\\<phi>C (F y, x) h) \\<in> HomD.set (y, G x)\"\n          using h y \\<Phi>_Fun_mapsto by auto\n        thus ?thesis\n          using y h 1 \\<phi>_def HomC.\\<phi>_mapsto HomD.\\<psi>_mapsto [of y \"G x\"] by fastforce\n      qed\n    qed\n\n    lemma \\<Phi>_simp:\n    assumes \"D.ide y\" and \"C.ide x\"\n    shows \"S.arr (\\<Phi> (y, x))\"\n    and \"\\<Phi> (y, x) = S.mkArr (HomC.set (F y, x)) (HomD.set (y, G x))\n                            (\\<phi>D (y, G x) o \\<phi> y o \\<psi>C (F y, x))\"\n    proof -\n      show 1: \"S.arr (\\<Phi> (y, x))\" using assms by auto\n      hence \"\\<Phi> (y, x) = S.mkArr (\\<Phi>.DOM (y, x)) (\\<Phi>.COD (y, x)) (\\<Phi>.FUN (y, x))\"\n        using S.mkArr_Fun by metis\n      also have \"... = S.mkArr (HomC.set (F y, x)) (HomD.set (y, G x)) (\\<Phi>.FUN (y, x))\"\n        using assms HomC.set_map HomD.set_map by fastforce\n      also have \"... = S.mkArr (HomC.set (F y, x)) (HomD.set (y, G x))\n                               (\\<phi>D (y, G x) o \\<phi> y o \\<psi>C (F y, x))\"\n      proof (intro S.mkArr_eqI')\n        show \"S.arr (S.mkArr (HomC.set (F y, x)) (HomD.set (y, G x)) (\\<Phi>.FUN (y, x)))\"\n          using 1 calculation by argo\n        show \"\\<And>h. h \\<in> HomC.set (F y, x) \\<Longrightarrow>\n                    \\<Phi>.FUN (y, x) h = (\\<phi>D (y, G x) o \\<phi> y o \\<psi>C (F y, x)) h\"\n        proof -\n          fix h\n          assume h: \"h \\<in> HomC.set (F y, x)\"\n          hence \"\\<guillemotleft>\\<psi>C (F y, x) h : F y \\<rightarrow>\\<^sub>C x\\<guillemotright>\"\n            using assms HomC.\\<psi>_mapsto [of \"F y\" x] by auto\n          hence \"(\\<phi>D (y, G x) o \\<phi> y o HomC.\\<psi> (F y, x)) h =\n                   \\<phi>D (y, G x) (\\<psi>D (y, G x) (\\<Phi>.FUN (y, x) (\\<phi>C (F y, x) (\\<psi>C (F y, x) h))))\"\n            using h \\<phi>_def by auto\n          also have \"... = \\<phi>D (y, G x) (\\<psi>D (y, G x) (\\<Phi>.FUN (y, x) h))\"\n            using assms h HomC.\\<phi>_\\<psi> \\<Phi>_Fun_mapsto by simp\n          also have \"... = \\<Phi>.FUN (y, x) h\"\n            using assms h \\<Phi>_Fun_mapsto [of y \"\\<psi>C (F y, x) h\"] HomC.\\<psi>_mapsto\n                  HomD.\\<phi>_\\<psi> [of y \"G x\"] C.ide_in_hom D.ide_in_hom\n            by blast\n          finally show \"\\<Phi>.FUN (y, x) h = (\\<phi>D (y, G x) o \\<phi> y o \\<psi>C (F y, x)) h\" by auto\n        qed\n      qed\n      finally show \"\\<Phi> (y, x) = S.mkArr (HomC.set (F y, x)) (HomD.set (y, G x))\n                                       (\\<phi>D (y, G x) o \\<phi> y o \\<psi>C (F y, x))\"\n        by force\n    qed\n\n    lemma \\<Psi>_Fun_mapsto:\n    assumes \"C.ide x\" and \"\\<guillemotleft>g : y \\<rightarrow>\\<^sub>D G x\\<guillemotright>\"\n    shows \"\\<Psi>.FUN (y, x) \\<in> HomD.set (y, G x) \\<rightarrow> HomC.set (F y, x)\"\n    proof -\n      have \"S.arr (\\<Psi> (y, x)) \\<and> \\<Psi>.COD (y, x) = HomC.set (F y, x) \\<and>\n                                \\<Psi>.DOM (y, x) = HomD.set (y, G x)\"\n        using assms HomC.set_map HomD.set_map by auto\n      thus ?thesis using S.Fun_mapsto by fast\n    qed\n\n    lemma \\<psi>_mapsto:\n    assumes x: \"C.ide x\"\n    shows \"\\<psi> x \\<in> D.hom y (G x) \\<rightarrow> C.hom (F y) x\"\n    proof\n      fix h\n      assume h: \"h \\<in> D.hom y (G x)\"\n      hence 1: \"\\<guillemotleft>h : y \\<rightarrow>\\<^sub>D G x\\<guillemotright>\" by auto\n      show \"\\<psi> x h \\<in> C.hom (F y) x\"\n      proof -\n        have \"\\<phi>D (y, G x) h \\<in> HomD.set (y, G x)\"\n          using x h 1 HomD.\\<phi>_mapsto [of y \"G x\"] by fastforce\n        hence \"\\<Psi>.FUN (y, x) (\\<phi>D (y, G x) h) \\<in> HomC.set (F y, x)\"\n          using h x \\<Psi>_Fun_mapsto by auto\n        thus ?thesis\n          using x h 1 \\<psi>_def HomD.\\<phi>_mapsto HomC.\\<psi>_mapsto [of \"F y\" x] by fastforce\n      qed\n    qed\n\n    lemma \\<Psi>_simp:\n    assumes \"D.ide y\" and \"C.ide x\"\n    shows \"S.arr (\\<Psi> (y, x))\"\n    and \"\\<Psi> (y, x) = S.mkArr (HomD.set (y, G x)) (HomC.set (F y, x))\n                            (\\<phi>C (F y, x) o \\<psi> x o \\<psi>D (y, G x))\"\n    proof -\n      show 1: \"S.arr (\\<Psi> (y, x))\" using assms by auto\n      hence \"\\<Psi> (y, x) = S.mkArr (\\<Psi>.DOM (y, x)) (\\<Psi>.COD (y, x)) (\\<Psi>.FUN (y, x))\"\n        using S.mkArr_Fun by metis\n      also have \"... = S.mkArr (HomD.set (y, G x)) (HomC.set (F y, x)) (\\<Psi>.FUN (y, x))\"\n        using assms HomC.set_map HomD.set_map by auto\n      also have \"... = S.mkArr (HomD.set (y, G x)) (HomC.set (F y, x))\n                               (\\<phi>C (F y, x) o \\<psi> x o \\<psi>D (y, G x))\"\n      proof (intro S.mkArr_eqI')\n        show \"S.arr (S.mkArr (HomD.set (y, G x)) (HomC.set (F y, x)) (\\<Psi>.FUN (y, x)))\"\n          using 1 calculation by argo\n        show \"\\<And>h. h \\<in> HomD.set (y, G x) \\<Longrightarrow>\n                    \\<Psi>.FUN (y, x) h = (\\<phi>C (F y, x) o \\<psi> x o \\<psi>D (y, G x)) h\"\n        proof -\n          fix h\n          assume h: \"h \\<in> HomD.set (y, G x)\"\n          hence \"\\<guillemotleft>\\<psi>D (y, G x) h : y \\<rightarrow>\\<^sub>D G x\\<guillemotright>\"\n            using assms HomD.\\<psi>_mapsto [of y \"G x\"] by auto\n          hence \"(\\<phi>C (F y, x) o \\<psi> x o HomD.\\<psi> (y, G x)) h =\n                   \\<phi>C (F y, x) (\\<psi>C (F y, x) (\\<Psi>.FUN (y, x) (\\<phi>D (y, G x) (\\<psi>D (y, G x) h))))\"\n            using h \\<psi>_def by auto\n          also have \"... = \\<phi>C (F y, x) (\\<psi>C (F y, x) (\\<Psi>.FUN (y, x) h))\"\n            using assms h HomD.\\<phi>_\\<psi> \\<Psi>_Fun_mapsto by simp\n          also have \"... = \\<Psi>.FUN (y, x) h\"\n            using assms h \\<Psi>_Fun_mapsto HomD.\\<psi>_mapsto [of y \"G x\"] HomC.\\<phi>_\\<psi> [of \"F y\" x]\n                  C.ide_in_hom D.ide_in_hom\n            by blast\n          finally show \"\\<Psi>.FUN (y, x) h = (\\<phi>C (F y, x) o \\<psi> x o HomD.\\<psi> (y, G x)) h\" by auto\n        qed\n      qed\n      finally show \"\\<Psi> (y, x) = S.mkArr (HomD.set (y, G x)) (HomC.set (F y, x))\n                                       (\\<phi>C (F y, x) o \\<psi> x o \\<psi>D (y, G x))\"\n        by force\n    qed\n\n    text\\<open>\n      The length of the next proof stems from having to use properties of composition\n      of arrows in @{term[source=true] S} to infer properties of the composition of the\n      corresponding functions.\n\\<close>\n\n    interpretation \\<phi>\\<psi>: meta_adjunction C D F G \\<phi> \\<psi>\n    proof\n      fix y :: 'd and x :: 'c and h :: 'c\n      assume y: \"D.ide y\" and h: \"\\<guillemotleft>h : F y \\<rightarrow>\\<^sub>C x\\<guillemotright>\"\n      have x: \"C.ide x\" using h by auto\n      show \"\\<guillemotleft>\\<phi> y h : y \\<rightarrow>\\<^sub>D G x\\<guillemotright>\"\n      proof -\n        have \"\\<Phi>.FUN (y, x) \\<in> HomC.set (F y, x) \\<rightarrow> HomD.set (y, G x)\"\n          using y h \\<Phi>_Fun_mapsto by blast\n        thus ?thesis\n          using x y h \\<phi>_def HomD.\\<psi>_mapsto [of y \"G x\"] HomC.\\<phi>_mapsto [of \"F y\" x] by auto\n      qed\n      show \"\\<psi> x (\\<phi> y h) = h\"\n      proof -\n        have 0: \"restrict (\\<lambda>h. h) (HomC.set (F y, x))\n                   = restrict (\\<phi>C (F y, x) o (\\<psi> x o \\<phi> y) o \\<psi>C (F y, x)) (HomC.set (F y, x))\"\n        proof -\n          have 1: \"S.ide (\\<Psi> (y, x) \\<cdot>\\<^sub>S \\<Phi> (y, x))\"\n            using x y \\<Phi>\\<Psi>.inv [of \"(y, x)\"] by auto\n          hence 6: \"S.seq (\\<Psi> (y, x)) (\\<Phi> (y, x))\" by auto\n          have 2: \"\\<Phi> (y, x) = S.mkArr (HomC.set (F y, x)) (HomD.set (y, G x))\n                                      (\\<phi>D (y, G x) o \\<phi> y o \\<psi>C (F y, x)) \\<and>\n                   \\<Psi> (y, x) = S.mkArr (HomD.set (y, G x)) (HomC.set (F y, x))\n                                      (\\<phi>C (F y, x) o \\<psi> x o \\<psi>D (y, G x))\"\n            using x y \\<Phi>_simp \\<Psi>_simp by force\n          have 3: \"S (\\<Psi> (y, x)) (\\<Phi> (y, x))\n                    = S.mkArr (HomC.set (F y, x)) (HomC.set (F y, x))\n                              (\\<phi>C (F y, x) o (\\<psi> x o \\<phi> y) o \\<psi>C (F y, x))\"\n          proof -\n            have 4: \"S.arr (\\<Psi> (y, x) \\<cdot>\\<^sub>S \\<Phi> (y, x))\" using 1 by auto\n            hence \"S (\\<Psi> (y, x)) (\\<Phi> (y, x))\n                     = S.mkArr (HomC.set (F y, x)) (HomC.set (F y, x))\n                               ((\\<phi>C (F y, x) o \\<psi> x o \\<psi>D (y, G x))\n                                  o (\\<phi>D (y, G x) o \\<phi> y o \\<psi>C (F y, x)))\"\n              using 1 2 S.ide_in_hom by force\n            also have \"... = S.mkArr (HomC.set (F y, x)) (HomC.set (F y, x))\n                                     (\\<phi>C (F y, x) o (\\<psi> x o \\<phi> y) o \\<psi>C (F y, x))\"\n            proof (intro S.mkArr_eqI')\n              show \"S.arr (S.mkArr (HomC.set (F y, x)) (HomC.set (F y, x))\n                                   ((\\<phi>C (F y, x) o \\<psi> x o \\<psi>D (y, G x))\n                                     o (\\<phi>D (y, G x) o \\<phi> y o \\<psi>C (F y, x))))\"\n                using 4 calculation by simp\n              show \"\\<And>h. h \\<in> HomC.set (F y, x) \\<Longrightarrow>\n                          ((\\<phi>C (F y, x) o \\<psi> x o \\<psi>D (y, G x))\n                            o (\\<phi>D (y, G x) o \\<phi> y o \\<psi>C (F y, x))) h =\n                          (\\<phi>C (F y, x) o (\\<psi> x o \\<phi> y) o \\<psi>C (F y, x)) h\"\n              proof -\n                fix h\n                assume h: \"h \\<in> HomC.set (F y, x)\"\n                hence 1: \"\\<guillemotleft>\\<phi> y (\\<psi>C (F y, x) h) : y \\<rightarrow>\\<^sub>D G x\\<guillemotright>\"\n                  using x y h HomC.\\<psi>_mapsto [of \"F y\" x] \\<phi>_mapsto by auto\n                show \"((\\<phi>C (F y, x) o \\<psi> x o \\<psi>D (y, G x))\n                            o (\\<phi>D (y, G x) o \\<phi> y o \\<psi>C (F y, x))) h =\n                      (\\<phi>C (F y, x) o (\\<psi> x o \\<phi> y) o \\<psi>C (F y, x)) h\"\n                  using x y 1 \\<phi>_mapsto HomD.\\<psi>_\\<phi> by simp\n              qed\n            qed\n            finally show ?thesis by simp\n          qed\n          moreover have \"\\<Psi> (y, x) \\<cdot>\\<^sub>S \\<Phi> (y, x)\n                             = S.mkArr (HomC.set (F y, x)) (HomC.set (F y, x)) (\\<lambda>h. h)\"\n         proof -\n            have \"\\<Psi> (y, x) \\<cdot>\\<^sub>S \\<Phi> (y, x) = S.dom (S (\\<Psi> (y, x)) (\\<Phi> (y, x)))\"\n              using 1 by auto\n            also have \"... = S.dom (\\<Phi> (y, x))\"\n              using 1 S.dom_comp by blast\n            finally show ?thesis\n              using 2 6 S.mkIde_as_mkArr by (elim S.seqE, auto)\n          qed\n          ultimately have 4: \"S.mkArr (HomC.set (F y, x)) (HomC.set (F y, x))\n                                      (\\<phi>C (F y, x) o (\\<psi> x o \\<phi> y) o \\<psi>C (F y, x))\n                                = S.mkArr (HomC.set (F y, x)) (HomC.set (F y, x)) (\\<lambda>h. h)\"\n            by auto\n          have 5: \"S.arr (S.mkArr (HomC.set (F y, x)) (HomC.set (F y, x))\n                                  (\\<phi>C (F y, x) o (\\<psi> x o \\<phi> y) o \\<psi>C (F y, x)))\"\n          proof -\n            have \"S.seq (\\<Psi> (y, x)) (\\<Phi> (y, x))\"\n              using 1 by fast\n            thus ?thesis using 3 by metis\n          qed\n          hence \"restrict (\\<phi>C (F y, x) o (\\<psi> x o \\<phi> y) o \\<psi>C (F y, x)) (HomC.set (F y, x))\n                  = S.Fun (S.mkArr (HomC.set (F y, x)) (HomC.set (F y, x))\n                         (\\<phi>C (F y, x) o (\\<psi> x o \\<phi> y) o \\<psi>C (F y, x)))\"\n            by auto\n          also have \"... = restrict (\\<lambda>h. h) (HomC.set (F y, x))\"\n            using 4 5 by auto\n          finally show ?thesis by auto\n        qed\n        moreover have \"\\<phi>C (F y, x) h \\<in> HomC.set (F y, x)\"\n          using x y h HomC.\\<phi>_mapsto [of \"F y\" x] by auto\n        ultimately have\n            \"\\<phi>C (F y, x) h = (\\<phi>C (F y, x) o (\\<psi> x o \\<phi> y) o \\<psi>C (F y, x)) (\\<phi>C (F y, x) h)\"\n          using x y h HomC.\\<phi>_mapsto [of \"F y\" x] by fast\n        hence \"\\<psi>C (F y, x) (\\<phi>C (F y, x) h) =\n                 \\<psi>C (F y, x) ((\\<phi>C (F y, x) o (\\<psi> x o \\<phi> y) o \\<psi>C (F y, x)) (\\<phi>C (F y, x) h))\"\n          by simp\n        hence \"h = \\<psi>C (F y, x) (\\<phi>C (F y, x) (\\<psi> x (\\<phi> y (\\<psi>C (F y, x) (\\<phi>C (F y, x) h)))))\"\n          using x y h HomC.\\<psi>_\\<phi> [of \"F y\" x] by simp\n        also have \"... = \\<psi> x (\\<phi> y h)\"\n          using x y h HomC.\\<psi>_\\<phi> HomC.\\<psi>_\\<phi> \\<phi>_mapsto \\<psi>_mapsto\n          by (metis PiE mem_Collect_eq)\n        finally show ?thesis by auto\n      qed\n      next\n      fix x :: 'c and h :: 'd and y :: 'd\n      assume x: \"C.ide x\" and h: \"\\<guillemotleft>h : y \\<rightarrow>\\<^sub>D G x\\<guillemotright>\"\n      have y: \"D.ide y\" using h by auto\n      show \"\\<guillemotleft>\\<psi> x h : F y \\<rightarrow>\\<^sub>C x\\<guillemotright>\" using x y h \\<psi>_mapsto [of x y] by auto\n      show \"\\<phi> y (\\<psi> x h) = h\"\n      proof -\n        have 0: \"restrict (\\<lambda>h. h) (HomD.set (y, G x))\n                   = restrict (\\<phi>D (y, G x) o (\\<phi> y o \\<psi> x) o \\<psi>D (y, G x)) (HomD.set (y, G x))\"\n        proof -\n          have 1: \"S.ide (S (\\<Phi> (y, x)) (\\<Psi> (y, x)))\"\n            using x y \\<Phi>\\<Psi>.inv by force\n          hence 6: \"S.seq (\\<Phi> (y, x)) (\\<Psi> (y, x))\" by auto\n          have 2: \"\\<Phi> (y, x) = S.mkArr (HomC.set (F y, x)) (HomD.set (y, G x))\n                                      (\\<phi>D (y, G x) o \\<phi> y o \\<psi>C (F y, x)) \\<and>\n                   \\<Psi> (y, x) = S.mkArr (HomD.set (y, G x)) (HomC.set (F y, x))\n                                       (\\<phi>C (F y, x) o \\<psi> x o \\<psi>D (y, G x))\"\n            using x h \\<Phi>_simp \\<Psi>_simp by auto\n          have 3: \"S (\\<Phi> (y, x)) (\\<Psi> (y, x))\n                     = S.mkArr (HomD.set (y, G x)) (HomD.set (y, G x))\n                               (\\<phi>D (y, G x) o (\\<phi> y o \\<psi> x) o \\<psi>D (y, G x))\"\n          proof -\n            have 4: \"S.seq (\\<Phi> (y, x)) (\\<Psi> (y, x))\" using 1 by auto\n            hence \"S (\\<Phi> (y, x)) (\\<Psi> (y, x))\n                     = S.mkArr (HomD.set (y, G x)) (HomD.set (y, G x))\n                               ((\\<phi>D (y, G x) o \\<phi> y o \\<psi>C (F y, x))\n                                 o (\\<phi>C (F y, x) o \\<psi> x o \\<psi>D (y, G x)))\"\n              using 1 2 6 S.ide_in_hom by force\n            also have \"... = S.mkArr (HomD.set (y, G x)) (HomD.set (y, G x))\n                                     (\\<phi>D (y, G x) o (\\<phi> y o \\<psi> x) o \\<psi>D (y, G x))\"\n            proof\n              show \"S.arr (S.mkArr (HomD.set (y, G x)) (HomD.set (y, G x))\n                                   ((\\<phi>D (y, G x) o \\<phi> y o \\<psi>C (F y, x))\n                                     o (\\<phi>C (F y, x) o \\<psi> x o \\<psi>D (y, G x))))\"\n                using 4 calculation by simp\n              show \"\\<And>h. h \\<in> HomD.set (y, G x) \\<Longrightarrow>\n                          ((\\<phi>D (y, G x) o \\<phi> y o \\<psi>C (F y, x))\n                            o (\\<phi>C (F y, x) o \\<psi> x o \\<psi>D (y, G x))) h =\n                          (\\<phi>D (y, G x) o (\\<phi> y o \\<psi> x) o \\<psi>D (y, G x)) h\"\n              proof -\n                fix h\n                assume h: \"h \\<in> HomD.set (y, G x)\"\n                hence \"\\<guillemotleft>\\<psi> x (\\<psi>D (y, G x) h) : F y \\<rightarrow>\\<^sub>C x\\<guillemotright>\"\n                  using x y HomD.\\<psi>_mapsto [of y \"G x\"] \\<psi>_mapsto by auto\n                thus \"((\\<phi>D (y, G x) o \\<phi> y o \\<psi>C (F y, x))\n                            o (\\<phi>C (F y, x) o \\<psi> x o \\<psi>D (y, G x))) h =\n                      (\\<phi>D (y, G x) o (\\<phi> y o \\<psi> x) o \\<psi>D (y, G x)) h\"\n                  using x y HomC.\\<psi>_\\<phi> by simp\n              qed\n            qed\n            finally show ?thesis by auto\n          qed\n          moreover have \"\\<Phi> (y, x) \\<cdot>\\<^sub>S \\<Psi> (y, x) =\n                           S.mkArr (HomD.set (y, G x)) (HomD.set (y, G x)) (\\<lambda>h. h)\"\n          proof -\n            have \"\\<Phi> (y, x) \\<cdot>\\<^sub>S \\<Psi> (y, x) = S.dom (\\<Phi> (y, x) \\<cdot>\\<^sub>S \\<Psi> (y, x))\"\n              using 1 by auto\n            also have \"... = S.dom (\\<Psi> (y, x))\"\n              using 1 S.dom_comp by blast\n            finally show ?thesis using 2 6 S.mkIde_as_mkArr by (elim S.seqE, auto)\n          qed\n          ultimately have 4: \"S.mkArr (HomD.set (y, G x)) (HomD.set (y, G x))\n                                      (\\<phi>D (y, G x) o (\\<phi> y o \\<psi> x) o \\<psi>D (y, G x))\n                                = S.mkArr (HomD.set (y, G x)) (HomD.set (y, G x)) (\\<lambda>h. h)\"\n            by auto\n          have 5: \"S.arr (S.mkArr (HomD.set (y, G x)) (HomD.set (y, G x))\n                                  (\\<phi>D (y, G x) o (\\<phi> y o \\<psi> x) o \\<psi>D (y, G x)))\"\n            using 1 3 by fastforce\n          hence \"restrict (\\<phi>D (y, G x) o (\\<phi> y o \\<psi> x) o \\<psi>D (y, G x)) (HomD.set (y, G x))\n                  = S.Fun (S.mkArr (HomD.set (y, G x)) (HomD.set (y, G x))\n                         (\\<phi>D (y, G x) o (\\<phi> y o \\<psi> x) o \\<psi>D (y, G x)))\"\n            by auto\n          also have \"... = restrict (\\<lambda>h. h) (HomD.set (y, G x))\"\n            using 4 5 by auto\n          finally show ?thesis by auto\n        qed\n        moreover have \"\\<phi>D (y, G x) h \\<in> HomD.set (y, G x)\"\n          using x y h HomD.\\<phi>_mapsto [of y \"G x\"] by auto\n        ultimately have\n            \"\\<phi>D (y, G x) h = (\\<phi>D (y, G x) o (\\<phi> y o \\<psi> x) o \\<psi>D (y, G x)) (\\<phi>D (y, G x) h)\"\n          by fast\n        hence \"\\<psi>D (y, G x) (\\<phi>D (y, G x) h) =\n                \\<psi>D (y, G x) ((\\<phi>D (y, G x) o (\\<phi> y o \\<psi> x) o \\<psi>D (y, G x)) (\\<phi>D (y, G x) h))\"\n          by simp\n        hence \"h = \\<psi>D (y, G x) (\\<phi>D (y, G x) (\\<phi> y (\\<psi> x (\\<psi>D (y, G x) (\\<phi>D (y, G x) h)))))\"\n          using x y h HomD.\\<psi>_\\<phi> by simp\n        also have \"... = \\<phi> y (\\<psi> x h)\"\n          using x y h HomD.\\<psi>_\\<phi> HomD.\\<psi>_\\<phi> [of \"\\<phi> y (\\<psi> x h)\" y \"G x\"] \\<phi>_mapsto \\<psi>_mapsto\n          by fastforce\n        finally show ?thesis by auto\n      qed\n      next\n      fix x :: 'c and x' :: 'c and y :: 'd and y' :: 'd\n      and f :: 'c and g :: 'd and h :: 'c\n      assume f: \"\\<guillemotleft>f : x \\<rightarrow>\\<^sub>C x'\\<guillemotright>\" and g: \"\\<guillemotleft>g : y' \\<rightarrow>\\<^sub>D y\\<guillemotright>\" and h: \"\\<guillemotleft>h : F y \\<rightarrow>\\<^sub>C x\\<guillemotright>\"\n      have x: \"C.ide x\" using f by auto\n      have y: \"D.ide y\" using g by auto\n      have x': \"C.ide x'\" using f by auto\n      have y': \"D.ide y'\" using g by auto\n      show \"\\<phi> y' (f \\<cdot>\\<^sub>C h \\<cdot>\\<^sub>C F g) = G f \\<cdot>\\<^sub>D \\<phi> y h \\<cdot>\\<^sub>D g\"\n      proof -\n        have 0: \"restrict ((\\<phi>D (y', G x') o (\\<lambda>h. G f \\<cdot>\\<^sub>D h \\<cdot>\\<^sub>D g) o \\<psi>D (y, G x))\n                           o (\\<phi>D (y, G x) o \\<phi> y o \\<psi>C (F y, x)))\n                       (HomC.set (F y, x))\n                = restrict ((\\<phi>D (y', G x') o \\<phi> y' o \\<psi>C (F y', x'))\n                             o (\\<phi>C (F y', x') o (\\<lambda>h. f \\<cdot>\\<^sub>C h \\<cdot>\\<^sub>C F g)) o \\<psi>C (F y, x))\n                           (HomC.set (F y, x))\"\n        proof -\n          have 1: \"S.arr (\\<Phi> (y, x)) \\<and>\n                   \\<Phi> (y, x) = S.mkArr (HomC.set (F y, x)) (HomD.set (y, G x))\n                                      (\\<phi>D (y, G x) o \\<phi> y o \\<psi>C (F y, x))\"\n                using x y \\<Phi>_simp [of y x] by auto\n          have 2: \"S.arr (\\<Phi> (y', x')) \\<and>\n                   \\<Phi> (y', x') = S.mkArr (HomC.set (F y', x')) (HomD.set (y', G x'))\n                                        (\\<phi>D (y', G x') o \\<phi> y' o \\<psi>C (F y', x'))\"\n                using x' y' \\<Phi>_simp [of y' x'] by auto\n          have 3: \"S.arr (S.mkArr (HomC.set (F y, x)) (HomD.set (y', G x'))\n                                  ((\\<phi>D (y', G x') o (\\<lambda>h. G f \\<cdot>\\<^sub>D h \\<cdot>\\<^sub>D g) o \\<psi>D (y, G x))\n                                    o (\\<phi>D (y, G x) o \\<phi> y o \\<psi>C (F y, x))))\n                   \\<and> S.mkArr (HomC.set (F y, x)) (HomD.set (y', G x'))\n                             ((\\<phi>D (y', G x') o (\\<lambda>h. G f \\<cdot>\\<^sub>D h \\<cdot>\\<^sub>D g) o \\<psi>D (y, G x))\n                               o (\\<phi>D (y, G x) o \\<phi> y o \\<psi>C (F y, x)))\n                     = S (S.mkArr (HomD.set (y, G x)) (HomD.set (y', G x'))\n                                  (\\<phi>D (y', G x') o (\\<lambda>h. G f \\<cdot>\\<^sub>D h \\<cdot>\\<^sub>D g) o \\<psi>D (y, G x)))\n                         (S.mkArr (HomC.set (F y, x)) (HomD.set (y, G x))\n                                  (\\<phi>D (y, G x) o \\<phi> y o \\<psi>C (F y, x)))\"\n          proof -\n            have 1: \"S.seq (S.mkArr (HomD.set (y, G x)) (HomD.set (y', G x'))\n                                  (\\<phi>D (y', G x') o (\\<lambda>h. G f \\<cdot>\\<^sub>D h \\<cdot>\\<^sub>D g) o \\<psi>D (y, G x)))\n                           (S.mkArr (HomC.set (F y, x)) (HomD.set (y, G x))\n                                  (\\<phi>D (y, G x) o \\<phi> y o \\<psi>C (F y, x)))\"\n            proof -\n              have \"S.arr (Hom_DopxG.map (g, f)) \\<and>\n                    Hom_DopxG.map (g, f)\n                        = S.mkArr (HomD.set (y, G x)) (HomD.set (y', G x'))\n                                  (\\<phi>D (y', G x') o (\\<lambda>h. G f \\<cdot>\\<^sub>D h \\<cdot>\\<^sub>D g) o \\<psi>D (y, G x))\"\n                using f g Hom_DopxG.preserves_arr Hom_DopxG_map_simp by fastforce\n              thus ?thesis\n                using 1 S.cod_mkArr S.dom_mkArr S.seqI by metis\n            qed\n            have \"S.seq (S.mkArr (HomD.set (y, G x)) (HomD.set (y', G x'))\n                                 (\\<phi>D (y', G x') o (\\<lambda>h. G f \\<cdot>\\<^sub>D h \\<cdot>\\<^sub>D g) o \\<psi>D (y, G x)))\n                        (S.mkArr (HomC.set (F y, x)) (HomD.set (y, G x))\n                                 (\\<phi>D (y, G x) o \\<phi> y o \\<psi>C (F y, x)))\"\n              using 1 by (intro S.seqI', auto)\n            moreover have \"S.mkArr (HomC.set (F y, x)) (HomD.set (y', G x'))\n                             ((\\<phi>D (y', G x') o (\\<lambda>h. G f \\<cdot>\\<^sub>D h \\<cdot>\\<^sub>D g) o \\<psi>D (y, G x))\n                               o (\\<phi>D (y, G x) o \\<phi> y o \\<psi>C (F y, x)))\n                             = S (S.mkArr (HomD.set (y, G x)) (HomD.set (y', G x'))\n                                          (\\<phi>D (y', G x') o (\\<lambda>h. G f \\<cdot>\\<^sub>D h \\<cdot>\\<^sub>D g) o \\<psi>D (y, G x)))\n                                 (S.mkArr (HomC.set (F y, x)) (HomD.set (y, G x))\n                                          (\\<phi>D (y, G x) o \\<phi> y o \\<psi>C (F y, x)))\"\n              using 1 by fastforce\n            ultimately show ?thesis by auto\n          qed\n          moreover have\n             4: \"S.arr (S.mkArr (HomC.set (F y, x)) (HomD.set (y', G x'))\n                                ((\\<phi>D (y', G x') o \\<phi> y' o \\<psi>C (F y', x'))\n                                  o (\\<phi>C (F y', x') o (\\<lambda>h. f \\<cdot>\\<^sub>C h \\<cdot>\\<^sub>C F g) o \\<psi>C (F y, x))))\n                 \\<and> S.mkArr (HomC.set (F y, x)) (HomD.set (y', G x'))\n                           ((\\<phi>D (y', G x') o \\<phi> y' o \\<psi>C (F y', x'))\n                             o (\\<phi>C (F y', x') o (\\<lambda>h. f \\<cdot>\\<^sub>C h \\<cdot>\\<^sub>C F g) o \\<psi>C (F y, x)))\n                     = S (S.mkArr (HomC.set (F y', x')) (HomD.set (y', G x')) \n                                  (\\<phi>D (y', G x') o \\<phi> y' o \\<psi>C (F y', x')))\n                         (S.mkArr (HomC.set (F y, x)) (HomC.set (F y', x'))\n                                  (\\<phi>C (F y', x') o (\\<lambda>h. f \\<cdot>\\<^sub>C h \\<cdot>\\<^sub>C F g) o \\<psi>C (F y, x)))\"\n          proof -\n            have 5: \"S.seq (S.mkArr (HomC.set (F y', x')) (HomD.set (y', G x'))\n                                    (\\<phi>D (y', G x') o \\<phi> y' o \\<psi>C (F y', x')))\n                           (S.mkArr (HomC.set (F y, x)) (HomC.set (F y', x'))\n                                    (\\<phi>C (F y', x') o (\\<lambda>h. f \\<cdot>\\<^sub>C h \\<cdot>\\<^sub>C F g) o \\<psi>C (F y, x)))\"\n            proof -\n              have \"S.arr (Hom_FopxC.map (g, f)) \\<and>\n                    Hom_FopxC.map (g, f)\n                          = S.mkArr (HomC.set (F y, x)) (HomC.set (F y', x'))\n                                    (\\<phi>C (F y', x') o (\\<lambda>h. f \\<cdot>\\<^sub>C h \\<cdot>\\<^sub>C F g) o \\<psi>C (F y, x))\"\n                using f g Hom_FopxC.preserves_arr Hom_FopxC_map_simp by fastforce\n              thus ?thesis using 2 S.cod_mkArr S.dom_mkArr S.seqI by metis\n            qed\n            have \"S.seq (S.mkArr (HomC.set (F y', x')) (HomD.set (y', G x'))\n                                 (\\<phi>D (y', G x') o \\<phi> y' o \\<psi>C (F y', x')))\n                        (S.mkArr (HomC.set (F y, x)) (HomC.set (F y', x'))\n                                 (\\<phi>C (F y', x') o (\\<lambda>h. f \\<cdot>\\<^sub>C h \\<cdot>\\<^sub>C F g) o \\<psi>C (F y, x)))\"\n              using 5 by (intro S.seqI', auto)\n            moreover have \"S.mkArr (HomC.set (F y, x)) (HomD.set (y', G x'))\n                                   ((\\<phi>D (y', G x') o \\<phi> y' o \\<psi>C (F y', x'))\n                                     o (\\<phi>C (F y', x') o (\\<lambda>h. f \\<cdot>\\<^sub>C h \\<cdot>\\<^sub>C F g) o \\<psi>C (F y, x)))\n                             = S (S.mkArr (HomC.set (F y', x')) (HomD.set (y', G x'))\n                                          (\\<phi>D (y', G x') o \\<phi> y' o \\<psi>C (F y', x')))\n                                 (S.mkArr (HomC.set (F y, x)) (HomC.set (F y', x'))\n                                          (\\<phi>C (F y', x') o (\\<lambda>h. f \\<cdot>\\<^sub>C h \\<cdot>\\<^sub>C F g) o \\<psi>C (F y, x)))\"\n              using 5 by fastforce\n            ultimately show ?thesis by argo\n          qed\n          moreover have 2:\n              \"S.mkArr (HomC.set (F y, x)) (HomD.set (y', G x'))\n                       ((\\<phi>D (y', G x') o (\\<lambda>h. G f \\<cdot>\\<^sub>D h \\<cdot>\\<^sub>D g) o \\<psi>D (y, G x))\n                         o (\\<phi>D (y, G x) o \\<phi> y o \\<psi>C (F y, x)))\n                  = S.mkArr (HomC.set (F y, x)) (HomD.set (y', G x'))\n                            ((\\<phi>D (y', G x') o \\<phi> y' o \\<psi>C (F y', x'))\n                              o (\\<phi>C (F y', x') o (\\<lambda>h. f \\<cdot>\\<^sub>C h \\<cdot>\\<^sub>C F g) o \\<psi>C (F y, x)))\"\n          proof -\n            have\n              \"S (Hom_DopxG.map (g, f)) (\\<Phi> (y, x)) = S (\\<Phi> (y', x')) (Hom_FopxC.map (g, f))\"\n              using f g \\<Phi>.is_natural_1 \\<Phi>.is_natural_2 by fastforce\n            moreover have \"Hom_DopxG.map (g, f)\n                             = S.mkArr (HomD.set (y, G x)) (HomD.set (y', G x'))\n                                       (\\<phi>D (y', G x') o (\\<lambda>h. G f \\<cdot>\\<^sub>D h \\<cdot>\\<^sub>D g) o \\<psi>D (y, G x))\"\n              using f g Hom_DopxG_map_simp [of \"(g, f)\"] by fastforce\n            moreover have \"Hom_FopxC.map (g, f)\n                             = S.mkArr (HomC.set (F y, x)) (HomC.set (F y', x'))\n                                       (\\<phi>C (F y', x') o (\\<lambda>h. f \\<cdot>\\<^sub>C h \\<cdot>\\<^sub>C F g) o \\<psi>C (F y, x))\"\n              using f g Hom_FopxC_map_simp [of \"(g, f)\"] by fastforce\n            ultimately show ?thesis using 1 2 3 4 by simp\n          qed\n          ultimately have 6: \"S.arr (S.mkArr (HomC.set (F y, x)) (HomD.set (y', G x'))\n                                             ((\\<phi>D (y', G x') o (\\<lambda>h. G f \\<cdot>\\<^sub>D h \\<cdot>\\<^sub>D g) o \\<psi>D (y, G x))\n                                               o (\\<phi>D (y, G x) o \\<phi> y o \\<psi>C (F y, x))))\"\n            by fast\n          hence \"restrict ((\\<phi>D (y', G x') o (\\<lambda>h. D (G f) (D h g)) o \\<psi>D (y, G x))\n                            o (\\<phi>D (y, G x) o \\<phi> y o \\<psi>C (F y, x)))\n                          (HomC.set (F y, x))\n                  = S.Fun (S.mkArr (HomC.set (F y, x)) (HomD.set (y', G x'))\n                                  ((\\<phi>D (y', G x') o (\\<lambda>h. G f \\<cdot>\\<^sub>D h \\<cdot>\\<^sub>D g) o \\<psi>D (y, G x))\n                                    o (\\<phi>D (y, G x) o \\<phi> y o \\<psi>C (F y, x))))\"\n            by simp\n          also have \"... = S.Fun (S.mkArr (HomC.set (F y, x)) (HomD.set (y', G x'))\n                                       ((\\<phi>D (y', G x') o \\<phi> y' o \\<psi>C (F y', x'))\n                                         o (\\<phi>C (F y', x') o (\\<lambda>h. f \\<cdot>\\<^sub>C h \\<cdot>\\<^sub>C F g) o \\<psi>C (F y, x))))\"\n            using 2 by argo\n          also have \"... = restrict ((\\<phi>D (y', G x') o \\<phi> y' o \\<psi>C (F y', x'))\n                                      o (\\<phi>C (F y', x') o (\\<lambda>h. f \\<cdot>\\<^sub>C h \\<cdot>\\<^sub>C F g) o \\<psi>C (F y, x)))\n                                    (HomC.set (F y, x))\"\n            using 4 S.Fun_mkArr by meson\n          finally show ?thesis by auto\n        qed\n        hence 5: \"((\\<phi>D (y', G x') \\<circ> (\\<lambda>h. G f \\<cdot>\\<^sub>D h \\<cdot>\\<^sub>D g) \\<circ> \\<psi>D (y, G x))\n                    \\<circ> (\\<phi>D (y, G x) \\<circ> \\<phi> y \\<circ> \\<psi>C (F y, x))) (\\<phi>C (F y, x) h) =\n                   (\\<phi>D (y', G x') \\<circ> \\<phi> y' \\<circ> \\<psi>C (F y', x')\n                     \\<circ> (\\<phi>C (F y', x') \\<circ> (\\<lambda>h. f \\<cdot>\\<^sub>C h \\<cdot>\\<^sub>C F g)) \\<circ> \\<psi>C (F y, x)) (\\<phi>C (F y, x) h)\"\n        proof -\n          have \"\\<phi>C (F y, x) h \\<in> HomC.set (F y, x)\"\n            using x y h HomC.\\<phi>_mapsto [of \"F y\" x] by auto\n          thus ?thesis\n            using 0 h restr_eqE [of \"(\\<phi>D (y', G x') \\<circ> (\\<lambda>h. G f \\<cdot>\\<^sub>D h \\<cdot>\\<^sub>D g) \\<circ> \\<psi>D (y, G x))\n                                      \\<circ> (\\<phi>D (y, G x) \\<circ> \\<phi> y \\<circ> \\<psi>C (F y, x))\"\n                                    \"HomC.set (F y, x)\"\n                                    \"(\\<phi>D (y', G x') \\<circ> \\<phi> y' \\<circ> \\<psi>C (F y', x'))\n                                       \\<circ> (\\<phi>C (F y', x') \\<circ> (\\<lambda>h. f \\<cdot>\\<^sub>C h \\<cdot>\\<^sub>C F g) o \\<psi>C (F y, x))\"]\n            by fast\n        qed\n        show ?thesis\n        proof -\n          have \"\\<phi> y' (C f (C h (F g))) =\n                  \\<psi>D (y', G x') (\\<phi>D (y', G x') (\\<phi> y' (\\<psi>C (F y', x') (\\<phi>C (F y', x')\n                     (C f (C (\\<psi>C (F y, x) (\\<phi>C (F y, x) h)) (F g)))))))\"\n          proof -\n            have \"\\<psi>D (y', G x') (\\<phi>D (y', G x') (\\<phi> y' (\\<psi>C (F y', x') (\\<phi>C (F y', x')\n                     (C f (C (\\<psi>C (F y, x) (\\<phi>C (F y, x) h)) (F g)))))))\n                    = \\<psi>D (y', G x') (\\<phi>D (y', G x') (\\<phi> y' (\\<psi>C (F y', x') (\\<phi>C (F y', x')\n                         (C f (C h (F g)))))))\"\n              using x y h HomC.\\<psi>_\\<phi> by simp\n            also have \"... = \\<psi>D (y', G x') (\\<phi>D (y', G x') (\\<phi> y' (C f (C h (F g)))))\"\n              using f g h HomC.\\<psi>_\\<phi> [of \"C f (C h (F g))\"] by fastforce\n            also have \"... = \\<phi> y' (C f (C h (F g)))\"\n            proof -\n              have \"\\<guillemotleft>\\<phi> y' (f \\<cdot>\\<^sub>C h \\<cdot>\\<^sub>C F g) : y' \\<rightarrow>\\<^sub>D G x'\\<guillemotright>\"\n                using f g h y' x' \\<phi>_mapsto [of y' x'] by auto\n              thus ?thesis by simp\n            qed\n            finally show ?thesis by auto\n          qed\n          also have\n             \"... = \\<psi>D (y', G x')\n                       (\\<phi>D (y', G x')\n                           (G f \\<cdot>\\<^sub>D \\<psi>D (y, G x) (\\<phi>D (y, G x) (\\<phi> y (\\<psi>C (F y, x) (\\<phi>C (F y, x) h))))\n                                \\<cdot>\\<^sub>D g))\"\n            using 5 by force\n          also have \"... = D (G f) (D (\\<phi> y h) g)\"\n          proof -\n            have \\<phi>yh: \"\\<guillemotleft>\\<phi> y h : y \\<rightarrow>\\<^sub>D G x\\<guillemotright>\"\n              using x y h \\<phi>_mapsto by auto\n            have \"\\<psi>D (y', G x')\n                     (\\<phi>D (y', G x')\n                         (G f \\<cdot>\\<^sub>D \\<psi>D (y, G x) (\\<phi>D (y, G x) (\\<phi> y (\\<psi>C (F y, x) (\\<phi>C (F y, x) h))))\n                              \\<cdot>\\<^sub>D g)) =\n                  \\<psi>D (y', G x') (\\<phi>D (y', G x') (G f \\<cdot>\\<^sub>D \\<psi>D (y, G x) (\\<phi>D (y, G x) (\\<phi> y h)) \\<cdot>\\<^sub>D g))\"\n              using x y f g h by auto\n            also have \"... = \\<psi>D (y', G x') (\\<phi>D (y', G x') (G f \\<cdot>\\<^sub>D \\<phi> y h \\<cdot>\\<^sub>D g))\"\n              using \\<phi>yh x' y' f g by simp\n            also have \"... = G f \\<cdot>\\<^sub>D \\<phi> y h \\<cdot>\\<^sub>D g\"\n            proof -\n              have \"\\<guillemotleft>G f \\<cdot>\\<^sub>D \\<phi> y h \\<cdot>\\<^sub>D g : y' \\<rightarrow>\\<^sub>D G x'\\<guillemotright>\"\n                using x x' y' f g h \\<phi>_mapsto \\<phi>yh by blast\n              thus ?thesis\n                using x y f g h \\<phi>yh HomD.\\<psi>_\\<phi> by auto\n            qed\n            finally show ?thesis by auto\n          qed\n          finally show ?thesis by auto\n        qed\n      qed\n    qed\n\n    theorem induces_meta_adjunction:\n    shows \"meta_adjunction C D F G \\<phi> \\<psi>\" ..\n\n  end\n\n  section \"Putting it All Together\"\n\n  text\\<open>\n    Combining the above results, an interpretation of any one of the locales:\n    \\<open>left_adjoint_functor\\<close>, \\<open>right_adjoint_functor\\<close>, \\<open>meta_adjunction\\<close>,\n    \\<open>hom_adjunction\\<close>, and \\<open>unit_counit_adjunction\\<close> extends to an interpretation\n    of \\<open>adjunction\\<close>.\n\\<close>\n\n  context meta_adjunction\n  begin\n\n    interpretation F: left_adjoint_functor D C F using has_left_adjoint_functor by auto\n    interpretation G: right_adjoint_functor C D G using has_right_adjoint_functor by auto\n\n    interpretation \\<eta>\\<epsilon>: unit_counit_adjunction C D F G \\<eta> \\<epsilon>\n      using induces_unit_counit_adjunction \\<eta>_def \\<epsilon>_def by auto\n\n    interpretation \\<Phi>\\<Psi>: hom_adjunction C D SetCat.comp \\<phi>C \\<phi>D F G \\<Phi> \\<Psi>\n      using induces_hom_adjunction by auto\n\n    theorem induces_adjunction:\n    shows \"adjunction C D SetCat.comp \\<phi>C \\<phi>D F G \\<phi> \\<psi> \\<eta> \\<epsilon> \\<Phi> \\<Psi>\"\n      apply (unfold_locales)\n      using \\<epsilon>_map_simp \\<eta>_map_simp \\<phi>_in_terms_of_\\<eta> \\<phi>_in_terms_of_\\<Phi>' \\<psi>_in_terms_of_\\<epsilon>\n            \\<psi>_in_terms_of_\\<Psi>' \\<Phi>_simp \\<Psi>_simp \\<eta>_def \\<epsilon>_def\n      by auto\n\n  end\n\n  sublocale meta_adjunction \\<subseteq> adjunction C D SetCat.comp \\<phi>C \\<phi>D F G \\<phi> \\<psi> \\<eta> \\<epsilon> \\<Phi> \\<Psi>\n    using induces_adjunction by auto\n\n  context unit_counit_adjunction\n  begin\n\n    interpretation \\<phi>\\<psi>: meta_adjunction C D F G \\<phi> \\<psi> using induces_meta_adjunction by auto\n\n    interpretation F: left_adjoint_functor D C F using \\<phi>\\<psi>.has_left_adjoint_functor by auto\n    interpretation G: right_adjoint_functor C D G using \\<phi>\\<psi>.has_right_adjoint_functor by auto\n\n    abbreviation HomC where \"HomC \\<equiv> \\<phi>\\<psi>.HomC\"\n    abbreviation \\<phi>C where \"\\<phi>C \\<equiv> \\<phi>\\<psi>.\\<phi>C\"\n    abbreviation HomD where \"HomD \\<equiv> \\<phi>\\<psi>.HomD\"\n    abbreviation \\<phi>D where \"\\<phi>D \\<equiv> \\<phi>\\<psi>.\\<phi>D\"\n    abbreviation \\<Phi> where \"\\<Phi> \\<equiv> \\<phi>\\<psi>.\\<Phi>\"\n    abbreviation \\<Psi> where \"\\<Psi> \\<equiv> \\<phi>\\<psi>.\\<Psi>\"\n\n    interpretation \\<Phi>\\<Psi>: hom_adjunction C D SetCat.comp \\<phi>C \\<phi>D F G \\<Phi> \\<Psi>\n      using \\<phi>\\<psi>.induces_hom_adjunction by auto\n\n    theorem induces_adjunction:\n    shows \"adjunction C D SetCat.comp \\<phi>C \\<phi>D F G \\<phi> \\<psi> \\<eta> \\<epsilon> \\<Phi> \\<Psi>\"\n      using \\<epsilon>_in_terms_of_\\<psi> \\<eta>_in_terms_of_\\<phi> \\<phi>\\<psi>.\\<phi>_in_terms_of_\\<Phi>' \\<psi>_def \\<phi>\\<psi>.\\<psi>_in_terms_of_\\<Psi>'\n            \\<phi>\\<psi>.\\<Phi>_simp \\<phi>\\<psi>.\\<Psi>_simp \\<phi>_def\n      apply (unfold_locales)\n      by auto\n\n  end\n\n  text\\<open>\n    The following fails, claiming ``roundup bound exceeded'':\\\\\n  @{theory_text\n  \"sublocale unit_counit_adjunction \\<subseteq> adjunction C D SetCat.comp \\<phi>C \\<phi>D F G \\<phi> \\<psi> \\<eta> \\<epsilon> \\<Phi> \\<Psi>\n     using induces_adjunction by auto\"}\n\\<close>\n   \n  context hom_adjunction\n  begin\n   \n    interpretation \\<phi>\\<psi>: meta_adjunction C D F G \\<phi> \\<psi>\n      using induces_meta_adjunction by auto\n\n    interpretation F: left_adjoint_functor D C F using \\<phi>\\<psi>.has_left_adjoint_functor by auto\n    interpretation G: right_adjoint_functor C D G using \\<phi>\\<psi>.has_right_adjoint_functor by auto\n\n    abbreviation \\<eta> where \"\\<eta> \\<equiv> \\<phi>\\<psi>.\\<eta>\"\n    abbreviation \\<epsilon> where \"\\<epsilon> \\<equiv> \\<phi>\\<psi>.\\<epsilon>\"\n\n    interpretation \\<eta>\\<epsilon>: unit_counit_adjunction C D F G \\<eta> \\<epsilon>\n      using \\<phi>\\<psi>.induces_unit_counit_adjunction \\<phi>\\<psi>.\\<eta>_def \\<phi>\\<psi>.\\<epsilon>_def by auto\n\n    theorem induces_adjunction:\n    shows \"adjunction C D S \\<phi>C \\<phi>D F G \\<phi> \\<psi> \\<eta> \\<epsilon> \\<Phi> \\<Psi>\"\n    proof\n      fix x\n      assume \"C.ide x\"\n      thus \"\\<epsilon> x = \\<psi> x (G x)\" using \\<phi>\\<psi>.\\<epsilon>_map_simp \\<phi>\\<psi>.\\<epsilon>_def by simp\n      next\n      fix y\n      assume \"D.ide y\"\n      thus \"\\<eta> y = \\<phi> y (F y)\" using \\<phi>\\<psi>.\\<eta>_map_simp \\<phi>\\<psi>.\\<eta>_def by simp\n      fix x y f\n      assume y: \"D.ide y\" and f: \"\\<guillemotleft>f : F y \\<rightarrow>\\<^sub>C x\\<guillemotright>\"\n      show \"\\<phi> y f = G f \\<cdot>\\<^sub>D \\<eta> y\" using y f \\<phi>\\<psi>.\\<phi>_in_terms_of_\\<eta> \\<phi>\\<psi>.\\<eta>_def by simp\n      show \"\\<phi> y f = (\\<psi>D (y, G x) \\<circ> \\<Phi>.FUN (y, x) \\<circ> \\<phi>C (F y, x)) f\" using y f \\<phi>_def by auto\n      next\n      fix x y g\n      assume x: \"C.ide x\" and g: \"\\<guillemotleft>g : y \\<rightarrow>\\<^sub>D G x\\<guillemotright>\"\n      show \"\\<psi> x g = \\<epsilon> x \\<cdot>\\<^sub>C F g\" using x g \\<phi>\\<psi>.\\<psi>_in_terms_of_\\<epsilon> \\<phi>\\<psi>.\\<epsilon>_def by simp\n      show \"\\<psi> x g = (\\<psi>C (F y, x) \\<circ> \\<Psi>.FUN (y, x) \\<circ> \\<phi>D (y, G x)) g\" using x g \\<psi>_def by fast\n      next\n      fix x y\n      assume x: \"C.ide x\" and y: \"D.ide y\"\n      show \"\\<Phi> (y, x) = S.mkArr (HomC.set (F y, x)) (HomD.set (y, G x))\n                               (\\<phi>D (y, G x) o \\<phi> y o \\<psi>C (F y, x))\"\n        using x y \\<Phi>_simp by simp\n      show \"\\<Psi> (y, x) = S.mkArr (HomD.set (y, G x)) (HomC.set (F y, x))\n                                (\\<phi>C (F y, x) o \\<psi> x o \\<psi>D (y, G x))\"\n        using x y \\<Psi>_simp by simp\n    qed\n\n  end\n\n  text\\<open>\n    The following fails for unknown reasons:\\\\\n  @{theory_text\n  \"sublocale hom_adjunction \\<subseteq> adjunction C D S \\<phi>C \\<phi>D F G \\<phi> \\<psi> \\<eta> \\<epsilon> \\<Phi> \\<Psi>\n    using induces_adjunction by auto\"}\n\\<close>\n\n  context left_adjoint_functor\n  begin\n\n    interpretation \\<phi>\\<psi>: meta_adjunction C D F G \\<phi> \\<psi>\n      using induces_meta_adjunction by auto\n\n    abbreviation HomC where \"HomC \\<equiv> \\<phi>\\<psi>.HomC\"\n    abbreviation \\<phi>C where \"\\<phi>C \\<equiv> \\<phi>\\<psi>.\\<phi>C\"\n    abbreviation HomD where \"HomD \\<equiv> \\<phi>\\<psi>.HomD\"\n    abbreviation \\<phi>D where \"\\<phi>D \\<equiv> \\<phi>\\<psi>.\\<phi>D\"\n    abbreviation \\<eta> where \"\\<eta> \\<equiv> \\<phi>\\<psi>.\\<eta>\"\n    abbreviation \\<epsilon> where \"\\<epsilon> \\<equiv> \\<phi>\\<psi>.\\<epsilon>\"\n    abbreviation \\<Phi> where \"\\<Phi> \\<equiv> \\<phi>\\<psi>.\\<Phi>\"\n    abbreviation \\<Psi> where \"\\<Psi> \\<equiv> \\<phi>\\<psi>.\\<Psi>\"\n\n    theorem induces_adjunction:\n    shows \"adjunction C D SetCat.comp \\<phi>C \\<phi>D F G \\<phi> \\<psi> \\<eta> \\<epsilon> \\<Phi> \\<Psi>\"\n      using \\<phi>\\<psi>.induces_adjunction by auto\n\n  end\n\n  sublocale left_adjoint_functor \\<subseteq> adjunction C D SetCat.comp \\<phi>C \\<phi>D F G \\<phi> \\<psi> \\<eta> \\<epsilon> \\<Phi> \\<Psi>\n    using induces_adjunction by auto\n\n  context right_adjoint_functor\n  begin\n\n    interpretation \\<phi>\\<psi>: meta_adjunction C D F G \\<phi> \\<psi>\n      using induces_meta_adjunction by auto\n\n    abbreviation HomC where \"HomC \\<equiv> \\<phi>\\<psi>.HomC\"\n    abbreviation \\<phi>C where \"\\<phi>C \\<equiv> \\<phi>\\<psi>.\\<phi>C\"\n    abbreviation HomD where \"HomD \\<equiv> \\<phi>\\<psi>.HomD\"\n    abbreviation \\<phi>D where \"\\<phi>D \\<equiv> \\<phi>\\<psi>.\\<phi>D\"\n    abbreviation \\<eta> where \"\\<eta> \\<equiv> \\<phi>\\<psi>.\\<eta>\"\n    abbreviation \\<epsilon> where \"\\<epsilon> \\<equiv> \\<phi>\\<psi>.\\<epsilon>\"\n    abbreviation \\<Phi> where \"\\<Phi> \\<equiv> \\<phi>\\<psi>.\\<Phi>\"\n    abbreviation \\<Psi> where \"\\<Psi> \\<equiv> \\<phi>\\<psi>.\\<Psi>\"\n\n    theorem induces_adjunction:\n    shows \"adjunction C D SetCat.comp \\<phi>C \\<phi>D F G \\<phi> \\<psi> \\<eta> \\<epsilon> \\<Phi> \\<Psi>\"\n      using \\<phi>\\<psi>.induces_adjunction by auto\n\n  end\n\n  text\\<open>\n    The following fails, claiming ``roundup bound exceeded'':\\\\\n  @{theory_text\n  \"sublocale right_adjoint_functor \\<subseteq> adjunction C D SetCat.comp \\<phi>C \\<phi>D F G \\<phi> \\<psi> \\<eta> \\<epsilon> \\<Phi> \\<Psi>\n    using induces_adjunction by auto\"}\n\\<close>\n\n  definition adjoint_functors\n  where \"adjoint_functors C D F G = (\\<exists>\\<phi> \\<psi>. meta_adjunction C D F G \\<phi> \\<psi>)\"\n\n  section \"Composition of Adjunctions\"\n\n  locale composite_adjunction =\n    A: category A +\n    B: category B +\n    C: category C +\n    F: \"functor\" B A F +\n    G: \"functor\" A B G +\n    F': \"functor\" C B F' +\n    G': \"functor\" B C G' +\n    FG: meta_adjunction A B F G \\<phi> \\<psi> +\n    F'G': meta_adjunction B C F' G' \\<phi>' \\<psi>'\n  for A :: \"'a comp\"     (infixr \"\\<cdot>\\<^sub>A\" 55)\n  and B :: \"'b comp\"     (infixr \"\\<cdot>\\<^sub>B\" 55)\n  and C :: \"'c comp\"     (infixr \"\\<cdot>\\<^sub>C\" 55)\n  and F :: \"'b \\<Rightarrow> 'a\"\n  and G :: \"'a \\<Rightarrow> 'b\"\n  and F' :: \"'c \\<Rightarrow> 'b\"\n  and G' :: \"'b \\<Rightarrow> 'c\"\n  and \\<phi> :: \"'b \\<Rightarrow> 'a \\<Rightarrow> 'b\"\n  and \\<psi> :: \"'a \\<Rightarrow> 'b \\<Rightarrow> 'a\"\n  and \\<phi>' :: \"'c \\<Rightarrow> 'b \\<Rightarrow> 'c\"\n  and \\<psi>' :: \"'b \\<Rightarrow> 'c \\<Rightarrow> 'b\"\n  begin\n\n    (* Notation for C.in_hom is inherited here somehow, but I don't know from where. *)\n\n    lemma is_meta_adjunction:\n    shows \"meta_adjunction A C (F o F') (G' o G) (\\<lambda>z. \\<phi>' z o \\<phi> (F' z)) (\\<lambda>x. \\<psi> x o \\<psi>' (G x))\"\n    proof -\n      interpret G'oG: composite_functor A B C G G' ..\n      interpret FoF': composite_functor C B A F' F ..\n      show ?thesis\n      proof\n        fix y f x\n        assume y: \"C.ide y\" and f: \"\\<guillemotleft>f : FoF'.map y \\<rightarrow>\\<^sub>A x\\<guillemotright>\"\n        show \"\\<guillemotleft>(\\<phi>' y \\<circ> \\<phi> (F' y)) f : y \\<rightarrow>\\<^sub>C G'oG.map x\\<guillemotright>\"\n          using y f FG.\\<phi>_in_hom F'G'.\\<phi>_in_hom by simp\n        show \"(\\<psi> x \\<circ> \\<psi>' (G x)) ((\\<phi>' y \\<circ> \\<phi> (F' y)) f) = f\"\n          using y f FG.\\<phi>_in_hom F'G'.\\<phi>_in_hom FG.\\<psi>_\\<phi> F'G'.\\<psi>_\\<phi> by simp\n        next\n        fix x g y\n        assume x: \"A.ide x\" and g: \"\\<guillemotleft>g : y \\<rightarrow>\\<^sub>C G'oG.map x\\<guillemotright>\"\n        show \"\\<guillemotleft>(\\<psi> x \\<circ> \\<psi>' (G x)) g : FoF'.map y \\<rightarrow>\\<^sub>A x\\<guillemotright>\"\n          using x g FG.\\<psi>_in_hom F'G'.\\<psi>_in_hom by auto\n        show \"(\\<phi>' y \\<circ> \\<phi> (F' y)) ((\\<psi> x \\<circ> \\<psi>' (G x)) g) = g\"\n          using x g FG.\\<psi>_in_hom F'G'.\\<psi>_in_hom FG.\\<phi>_\\<psi> F'G'.\\<phi>_\\<psi> by simp\n        next\n        fix f x x' g y' y h\n        assume f: \"\\<guillemotleft>f : x \\<rightarrow>\\<^sub>A x'\\<guillemotright>\" and g: \"\\<guillemotleft>g : y' \\<rightarrow>\\<^sub>C y\\<guillemotright>\" and h: \"\\<guillemotleft>h : FoF'.map y \\<rightarrow>\\<^sub>A x\\<guillemotright>\"\n        show \"(\\<phi>' y' \\<circ> \\<phi> (F' y')) (f \\<cdot>\\<^sub>A h \\<cdot>\\<^sub>A FoF'.map g) =\n              G'oG.map f \\<cdot>\\<^sub>C (\\<phi>' y \\<circ> \\<phi> (F' y)) h \\<cdot>\\<^sub>C g\"\n          using f g h FG.\\<phi>_naturality [of f x x' \"F' g\" \"F' y'\" \"F' y\" h]\n                F'G'.\\<phi>_naturality [of \"G f\" \"G x\" \"G x'\" g y' y \"\\<phi> (F' y) h\"]\n                FG.\\<phi>_in_hom\n          by fastforce\n      qed\n    qed\n\n    interpretation K\\<eta>H: natural_transformation C C \\<open>G' o F'\\<close> \\<open>G' o G o F o F'\\<close> \\<open>G' o FG.\\<eta> o F'\\<close>\n    proof -\n      interpret \\<eta>F': natural_transformation C B F' \\<open>(G o F) o F'\\<close> \\<open>FG.\\<eta> o F'\\<close>\n        using FG.\\<eta>_is_natural_transformation F'.natural_transformation_axioms\n              horizontal_composite\n        by fastforce\n      interpret G'\\<eta>F': natural_transformation C C \\<open>G' o F'\\<close> \\<open>G' o (G o F o F')\\<close>\n                         \\<open>G' o (FG.\\<eta> o F')\\<close>\n        using \\<eta>F'.natural_transformation_axioms G'.natural_transformation_axioms\n              horizontal_composite\n        by blast\n      show \"natural_transformation C C (G' o F') (G' o G o F o F') (G' o FG.\\<eta> o F')\"\n        using G'\\<eta>F'.natural_transformation_axioms o_assoc by metis\n    qed\n    interpretation G'\\<eta>F'o\\<eta>': vertical_composite C C C.map \\<open>G' o F'\\<close> \\<open>G' o G o F o F'\\<close>\n                             F'G'.\\<eta> \\<open>G' o FG.\\<eta> o F'\\<close> ..\n\n    interpretation F\\<epsilon>G: natural_transformation A A \\<open>F o F' o G' o G\\<close> \\<open>F o G\\<close> \\<open>F o F'G'.\\<epsilon> o G\\<close>\n    proof -\n      interpret F\\<epsilon>': natural_transformation B A \\<open>F o (F' o G')\\<close> F \\<open>F o F'G'.\\<epsilon>\\<close>\n        using F'G'.\\<epsilon>.natural_transformation_axioms F.natural_transformation_axioms\n              horizontal_composite\n        by fastforce\n      interpret F\\<epsilon>'G: natural_transformation A A \\<open>F o (F' o G') o G\\<close> \\<open>F o G\\<close> \\<open>F o F'G'.\\<epsilon> o G\\<close>\n        using F\\<epsilon>'.natural_transformation_axioms G.natural_transformation_axioms\n              horizontal_composite\n        by blast\n      show \"natural_transformation A A (F o F' o G' o G) (F o G) (F o F'G'.\\<epsilon> o G)\"\n        using F\\<epsilon>'G.natural_transformation_axioms o_assoc by metis\n    qed\n    interpretation \\<epsilon>oF\\<epsilon>'G: vertical_composite A A \\<open>F \\<circ> F' \\<circ> G' \\<circ> G\\<close> \\<open>F o G\\<close> A.map\n                             \\<open>F o F'G'.\\<epsilon> o G\\<close> FG.\\<epsilon> ..\n\n    interpretation meta_adjunction A C \\<open>F o F'\\<close> \\<open>G' o G\\<close>\n                                   \\<open>\\<lambda>z. \\<phi>' z o \\<phi> (F' z)\\<close> \\<open>\\<lambda>x. \\<psi> x o \\<psi>' (G x)\\<close>\n      using is_meta_adjunction by auto\n\n    lemma \\<eta>_char:\n    shows \"\\<eta> = G'\\<eta>F'o\\<eta>'.map\"\n    proof (intro NaturalTransformation.eqI)\n      show \"natural_transformation C C C.map (G' o G o F o F') G'\\<eta>F'o\\<eta>'.map\" ..\n      show \"natural_transformation C C C.map (G' o G o F o F') \\<eta>\"\n      proof -\n        have \"natural_transformation C C C.map ((G' \\<circ> G) \\<circ> (F \\<circ> F')) \\<eta>\" ..\n        moreover have \"(G' o G) o (F o F') = G' o G o F o F'\" by auto\n        ultimately show ?thesis by metis\n      qed\n      fix a\n      assume a: \"C.ide a\"\n      show \"\\<eta> a = G'\\<eta>F'o\\<eta>'.map a\"\n        unfolding \\<eta>_def\n        using a G'\\<eta>F'o\\<eta>'.map_def FG.\\<eta>.preserves_hom [of \"F' a\" \"F' a\" \"F' a\"]\n              F'G'.\\<phi>_in_terms_of_\\<eta> FG.\\<eta>_map_simp \\<eta>_map_simp [of a] C.ide_in_hom\n              F'G'.\\<eta>_def FG.\\<eta>_def\n        by auto\n    qed\n\n    lemma \\<epsilon>_char:\n    shows \"\\<epsilon> = \\<epsilon>oF\\<epsilon>'G.map\"\n    proof (intro NaturalTransformation.eqI)\n      show \"natural_transformation A A (F o F' o G' o G) A.map \\<epsilon>\"\n      proof -\n        have \"natural_transformation A A ((F \\<circ> F') \\<circ> (G' \\<circ> G)) A.map \\<epsilon>\" ..\n        moreover have \"(F o F') o (G' o G) = F o F' o G' o G\" by auto\n        ultimately show ?thesis by metis\n      qed\n      show \"natural_transformation A A (F \\<circ> F' \\<circ> G' \\<circ> G) A.map \\<epsilon>oF\\<epsilon>'G.map\" ..\n      fix a\n      assume a: \"A.ide a\"\n      show \"\\<epsilon> a = \\<epsilon>oF\\<epsilon>'G.map a\"\n      proof -\n        have \"\\<epsilon> a = \\<psi> a (\\<psi>' (G a) (G' (G a)))\"\n          using a \\<epsilon>_in_terms_of_\\<psi> by simp\n        also have \"... = FG.\\<epsilon> a \\<cdot>\\<^sub>A F (F'G'.\\<epsilon> (G a) \\<cdot>\\<^sub>B F' (G' (G a)))\"\n          unfolding \\<epsilon>_def\n          using a F'G'.\\<psi>_in_terms_of_\\<epsilon> [of \"G a\" \"G' (G a)\" \"G' (G a)\"]\n                F'G'.\\<epsilon>.preserves_hom [of \"G a\" \"G a\" \"G a\"]\n                FG.\\<psi>_in_terms_of_\\<epsilon> [of a \"F'G'.\\<epsilon> (G a) \\<cdot>\\<^sub>B F' (G' (G a))\" \"(F'G'.FG.map (G a))\"]\n                F'G'.\\<epsilon>_def FG.\\<epsilon>_def\n          by fastforce\n        also have \"... = \\<epsilon>oF\\<epsilon>'G.map a\"\n          using a B.comp_arr_dom \\<epsilon>oF\\<epsilon>'G.map_def by simp\n        finally show ?thesis by blast\n      qed\n    qed\n\n  end\n\n  section \"Right Adjoints are Unique up to Natural Isomorphism\"\n\n  text\\<open>\n    As an example of the use of the of the foregoing development, we show that two right adjoints\n    to the same functor are naturally isomorphic.\n\\<close>\n\n  theorem two_right_adjoints_naturally_isomorphic:\n  assumes \"adjoint_functors C D F G\" and \"adjoint_functors C D F G'\"\n  shows \"naturally_isomorphic C D G G'\"\n  proof -\n    text\\<open>\n      For any object @{term x} of @{term C}, we have that \\<open>\\<epsilon> x \\<in> C.hom (F (G x)) x\\<close>\n      is a terminal arrow from @{term F} to @{term x}, and similarly for \\<open>\\<epsilon>' x\\<close>.\n      We may therefore obtain the unique coextension \\<open>\\<tau> x \\<in> D.hom (G x) (G' x)\\<close>\n      of \\<open>\\<epsilon> x\\<close> along \\<open>\\<epsilon>' x\\<close>.\n      An explicit formula for \\<open>\\<tau> x\\<close> is \\<open>D (G' (\\<epsilon> x)) (\\<eta>' (G x))\\<close>.\n      Similarly, we obtain \\<open>\\<tau>' x = D (G (\\<epsilon>' x)) (\\<eta> (G' x)) \\<in> D.hom (G' x) (G x)\\<close>.\n      We show these are the components of inverse natural transformations between\n      @{term G} and @{term G'}.\n\\<close>\n    obtain \\<phi> \\<psi> where \\<phi>\\<psi>: \"meta_adjunction C D F G \\<phi> \\<psi>\"\n      using assms adjoint_functors_def by blast\n    obtain \\<phi>' \\<psi>' where \\<phi>'\\<psi>': \"meta_adjunction C D F G' \\<phi>' \\<psi>'\"\n      using assms adjoint_functors_def by blast\n    interpret Adj: meta_adjunction C D F G \\<phi> \\<psi> using \\<phi>\\<psi> by auto\n    interpret\n        Adj: adjunction C D SetCat.comp Adj.\\<phi>C Adj.\\<phi>D F G \\<phi> \\<psi> Adj.\\<eta> Adj.\\<epsilon> Adj.\\<Phi> Adj.\\<Psi>\n      using Adj.induces_adjunction by auto\n    interpret Adj': meta_adjunction C D F G' \\<phi>' \\<psi>' using \\<phi>'\\<psi>' by auto\n    interpret Adj': adjunction C D SetCat.comp Adj'.\\<phi>C Adj'.\\<phi>D\n                               F G' \\<phi>' \\<psi>' Adj'.\\<eta> Adj'.\\<epsilon> Adj'.\\<Phi> Adj'.\\<Psi>\n      using Adj'.induces_adjunction by auto\n    write C (infixr \"\\<cdot>\\<^sub>C\" 55)\n    write D (infixr \"\\<cdot>\\<^sub>D\" 55)\n    write Adj.C.in_hom (\"\\<guillemotleft>_ : _ \\<rightarrow>\\<^sub>C _\\<guillemotright>\")\n    write Adj.D.in_hom (\"\\<guillemotleft>_ : _ \\<rightarrow>\\<^sub>D _\\<guillemotright>\")\n    let ?\\<tau>o = \"\\<lambda>a. G' (Adj.\\<epsilon> a) \\<cdot>\\<^sub>D Adj'.\\<eta> (G a)\"\n    interpret \\<tau>: transformation_by_components C D G G' ?\\<tau>o\n    proof\n      show \"\\<And>a. Adj.C.ide a \\<Longrightarrow> \\<guillemotleft>G' (Adj.\\<epsilon> a) \\<cdot>\\<^sub>D Adj'.\\<eta> (G a) : G a \\<rightarrow>\\<^sub>D G' a\\<guillemotright>\"\n        by fastforce\n      show \"\\<And>f. Adj.C.arr f \\<Longrightarrow>\n                   (G' (Adj.\\<epsilon> (Adj.C.cod f)) \\<cdot>\\<^sub>D Adj'.\\<eta> (G (Adj.C.cod f))) \\<cdot>\\<^sub>D G f =\n                   G' f \\<cdot>\\<^sub>D G' (Adj.\\<epsilon> (Adj.C.dom f)) \\<cdot>\\<^sub>D Adj'.\\<eta> (G (Adj.C.dom f))\"\n      proof -\n        fix f\n        assume f: \"Adj.C.arr f\"\n        let ?x = \"Adj.C.dom f\"\n        let ?x' = \"Adj.C.cod f\"\n        have \"(G' (Adj.\\<epsilon> (Adj.C.cod f)) \\<cdot>\\<^sub>D Adj'.\\<eta> (G (Adj.C.cod f))) \\<cdot>\\<^sub>D G f =\n              G' (Adj.\\<epsilon> (Adj.C.cod f) \\<cdot>\\<^sub>C F (G f)) \\<cdot>\\<^sub>D Adj'.\\<eta> (G (Adj.C.dom f))\"\n          using f Adj'.\\<eta>.naturality [of \"G f\"] Adj.D.comp_assoc by simp\n        also have \"... = G' (f \\<cdot>\\<^sub>C Adj.\\<epsilon> (Adj.C.dom f)) \\<cdot>\\<^sub>D Adj'.\\<eta> (G (Adj.C.dom f))\"\n          using f Adj.\\<epsilon>.naturality by simp\n        also have \"... = G' f \\<cdot>\\<^sub>D G' (Adj.\\<epsilon> (Adj.C.dom f)) \\<cdot>\\<^sub>D Adj'.\\<eta> (G (Adj.C.dom f))\"\n          using f Adj.D.comp_assoc by simp\n        finally show \"(G' (Adj.\\<epsilon> (Adj.C.cod f)) \\<cdot>\\<^sub>D Adj'.\\<eta> (G (Adj.C.cod f))) \\<cdot>\\<^sub>D G f =\n                      G' f \\<cdot>\\<^sub>D G' (Adj.\\<epsilon> (Adj.C.dom f)) \\<cdot>\\<^sub>D Adj'.\\<eta> (G (Adj.C.dom f))\"\n          by auto\n      qed\n    qed\n    interpret natural_isomorphism C D G G' \\<tau>.map\n    proof\n      fix a\n      assume a: \"Adj.C.ide a\"\n      show \"Adj.D.iso (\\<tau>.map a)\"\n      proof\n        show \"Adj.D.inverse_arrows (\\<tau>.map a) (\\<phi> (G' a) (Adj'.\\<epsilon> a))\"\n        proof\n          text\\<open>\n            The proof that the two composites are identities is a modest diagram chase.\n            This is a good example of the inference rules for the \\<open>category\\<close>,\n            \\<open>functor\\<close>, and \\<open>natural_transformation\\<close> locales in action.\n            Isabelle is able to use the single hypothesis that \\<open>a\\<close> is an identity to\n            implicitly fill in all the details that the various quantities are in fact arrows\n            and that the indicated composites are all well-defined, as well as to apply\n            associativity of composition.  In most cases, this is done by auto or simp without\n            even mentioning any of the rules that are used.\n$$\\xymatrix{\n        {G' a} \\ar[dd]_{\\eta'(G'a)} \\ar[rr]^{\\tau' a} \\ar[dr]_{\\eta(G'a)}\n           && {G a} \\ar[rr]^{\\tau a} \\ar[dr]_{\\eta'(Ga)} && {G' a}                     \\\\\n        & {GFG'a} \\rrtwocell\\omit{\\omit(2)} \\ar[ur]_{G(\\epsilon' a)} \\ar[dr]_{\\eta'(GFG'a)}\n           && {G'FGa} \\drtwocell\\omit{\\omit(3)} \\ar[ur]_{G'(\\epsilon a)} &            \\\\\n        {G'FG'a} \\urtwocell\\omit{\\omit(1)} \\ar[rr]_{G'F\\eta(G'a)} \\ar@/_8ex/[rrrr]_{G'FG'a}\n           && {G'FGFG'a} \\dtwocell\\omit{\\omit(4)} \\ar[ru]_{G'FG(\\epsilon' a)} \\ar[rr]_{G'(\\epsilon(FG'a))}\n           && {G'FG'a} \\ar[uu]_{G'(\\epsilon' a)}                                       \\\\\n           &&&&\n}$$\n\\<close>\n          show \"Adj.D.ide (\\<tau>.map a \\<cdot>\\<^sub>D \\<phi> (G' a) (Adj'.\\<epsilon> a))\"\n          proof -\n            have \"\\<tau>.map a \\<cdot>\\<^sub>D \\<phi> (G' a) (Adj'.\\<epsilon> a) = G' a\"\n            proof -\n              have \"\\<tau>.map a \\<cdot>\\<^sub>D \\<phi> (G' a) (Adj'.\\<epsilon> a) =\n                    G' (Adj.\\<epsilon> a) \\<cdot>\\<^sub>D (Adj'.\\<eta> (G a) \\<cdot>\\<^sub>D G (Adj'.\\<epsilon> a)) \\<cdot>\\<^sub>D Adj.\\<eta> (G' a)\"\n                using a \\<tau>.map_simp_ide Adj.\\<phi>_in_terms_of_\\<eta> Adj'.\\<phi>_in_terms_of_\\<eta>\n                      Adj'.\\<epsilon>.preserves_hom [of a a a] Adj.C.ide_in_hom Adj.D.comp_assoc\n                      Adj.\\<epsilon>_def Adj.\\<eta>_def\n                by simp\n              also have \"... = G' (Adj.\\<epsilon> a) \\<cdot>\\<^sub>D (G' (F (G (Adj'.\\<epsilon> a))) \\<cdot>\\<^sub>D Adj'.\\<eta> (G (F (G' a)))) \\<cdot>\\<^sub>D\n                               Adj.\\<eta> (G' a)\"\n                using a Adj'.\\<eta>.naturality [of \"G (Adj'.\\<epsilon> a)\"] by auto\n              also have \"... = (G' (Adj.\\<epsilon> a) \\<cdot>\\<^sub>D G' (F (G (Adj'.\\<epsilon> a)))) \\<cdot>\\<^sub>D G' (F (Adj.\\<eta> (G' a))) \\<cdot>\\<^sub>D\n                               Adj'.\\<eta> (G' a)\"\n                using a Adj'.\\<eta>.naturality [of \"Adj.\\<eta> (G' a)\"] Adj.D.comp_assoc by auto\n              also have\n                  \"... = G' (Adj'.\\<epsilon> a) \\<cdot>\\<^sub>D (G' (Adj.\\<epsilon> (F (G' a))) \\<cdot>\\<^sub>D G' (F (Adj.\\<eta> (G' a)))) \\<cdot>\\<^sub>D\n                         Adj'.\\<eta> (G' a)\"\n              proof -\n                have\n                   \"G' (Adj.\\<epsilon> a) \\<cdot>\\<^sub>D G' (F (G (Adj'.\\<epsilon> a))) = G' (Adj'.\\<epsilon> a) \\<cdot>\\<^sub>D G' (Adj.\\<epsilon> (F (G' a)))\"\n                proof -\n                  have \"G' (Adj.\\<epsilon> a \\<cdot>\\<^sub>C F (G (Adj'.\\<epsilon> a))) = G' (Adj'.\\<epsilon> a \\<cdot>\\<^sub>C Adj.\\<epsilon> (F (G' a)))\"\n                    using a Adj.\\<epsilon>.naturality [of \"Adj'.\\<epsilon> a\"] by auto\n                  thus ?thesis using a by force\n                qed\n                thus ?thesis using Adj.D.comp_assoc by auto\n              qed\n              also have \"... = G' (Adj'.\\<epsilon> a) \\<cdot>\\<^sub>D Adj'.\\<eta> (G' a)\"\n              proof -\n                have \"G' (Adj.\\<epsilon> (F (G' a))) \\<cdot>\\<^sub>D G' (F (Adj.\\<eta> (G' a))) = G' (F (G' a))\"\n                proof -\n                  have\n                      \"G' (Adj.\\<epsilon> (F (G' a))) \\<cdot>\\<^sub>D G' (F (Adj.\\<eta> (G' a))) = G' (Adj.\\<epsilon>FoF\\<eta>.map (G' a))\"\n                    using a Adj.\\<epsilon>FoF\\<eta>.map_simp_1 by auto\n                  moreover have \"Adj.\\<epsilon>FoF\\<eta>.map (G' a) = F (G' a)\"\n                    using a by (simp add: Adj.\\<eta>\\<epsilon>.triangle_F)\n                  ultimately show ?thesis by auto\n                qed\n                thus ?thesis\n                  using a Adj.D.comp_cod_arr [of \"Adj'.\\<eta> (G' a)\"] by auto\n              qed\n              also have \"... = G' a\"\n                using a Adj'.\\<eta>\\<epsilon>.triangle_G Adj'.G\\<epsilon>o\\<eta>G.map_simp_1 [of a] by auto\n              finally show ?thesis by auto\n            qed\n            thus ?thesis using a by simp\n          qed\n          show \"Adj.D.ide (\\<phi> (G' a) (Adj'.\\<epsilon> a) \\<cdot>\\<^sub>D \\<tau>.map a)\"\n          proof -\n            have \"\\<phi> (G' a) (Adj'.\\<epsilon> a) \\<cdot>\\<^sub>D \\<tau>.map a = G a\"\n            proof -\n              have \"\\<phi> (G' a) (Adj'.\\<epsilon> a) \\<cdot>\\<^sub>D \\<tau>.map a =\n                    G (Adj'.\\<epsilon> a) \\<cdot>\\<^sub>D (Adj.\\<eta> (G' a) \\<cdot>\\<^sub>D G' (Adj.\\<epsilon> a)) \\<cdot>\\<^sub>D Adj'.\\<eta> (G a)\"\n                using a \\<tau>.map_simp_ide Adj.\\<phi>_in_terms_of_\\<eta> Adj'.\\<epsilon>.preserves_hom [of a a a]\n                      Adj.C.ide_in_hom Adj.D.comp_assoc Adj.\\<eta>_def\n                by auto\n              also have\n                \"... = G (Adj'.\\<epsilon> a) \\<cdot>\\<^sub>D (G (F (G' (Adj.\\<epsilon> a))) \\<cdot>\\<^sub>D Adj.\\<eta> (G' (F (G a)))) \\<cdot>\\<^sub>D\n                       Adj'.\\<eta> (G a)\"\n                using a Adj.\\<eta>.naturality [of \"G' (Adj.\\<epsilon> a)\"] by auto\n              also have\n                \"... = (G (Adj'.\\<epsilon> a) \\<cdot>\\<^sub>D G (F (G' (Adj.\\<epsilon> a)))) \\<cdot>\\<^sub>D G (F (Adj'.\\<eta> (G a))) \\<cdot>\\<^sub>D\n                       Adj.\\<eta> (G a)\"\n                using a Adj.\\<eta>.naturality [of \"Adj'.\\<eta> (G a)\"] Adj.D.comp_assoc by auto\n              also have\n                \"... = G (Adj.\\<epsilon> a) \\<cdot>\\<^sub>D (G (Adj'.\\<epsilon> (F (G a))) \\<cdot>\\<^sub>D G (F (Adj'.\\<eta> (G a)))) \\<cdot>\\<^sub>D\n                       Adj.\\<eta> (G a)\"\n              proof -\n                have \"G (Adj'.\\<epsilon> a) \\<cdot>\\<^sub>D G (F (G' (Adj.\\<epsilon> a))) = G (Adj.\\<epsilon> a) \\<cdot>\\<^sub>D G (Adj'.\\<epsilon> (F (G a)))\"\n                proof -\n                  have \"G (Adj'.\\<epsilon> a \\<cdot>\\<^sub>C F (G' (Adj.\\<epsilon> a))) = G (Adj.\\<epsilon> a \\<cdot>\\<^sub>C Adj'.\\<epsilon> (F (G a)))\"\n                    using a Adj'.\\<epsilon>.naturality [of \"Adj.\\<epsilon> a\"] by auto\n                  thus ?thesis using a by force\n                qed\n                thus ?thesis using Adj.D.comp_assoc by auto\n              qed\n              also have \"... = G (Adj.\\<epsilon> a) \\<cdot>\\<^sub>D Adj.\\<eta> (G a)\"\n              proof -\n                have \"G (Adj'.\\<epsilon> (F (G a))) \\<cdot>\\<^sub>D G (F (Adj'.\\<eta> (G a))) = G (F (G a))\"\n                proof -\n                  have\n                    \"G (Adj'.\\<epsilon> (F (G a))) \\<cdot>\\<^sub>D G (F (Adj'.\\<eta> (G a))) = G (Adj'.\\<epsilon>FoF\\<eta>.map (G a))\"\n                    using a Adj'.\\<epsilon>FoF\\<eta>.map_simp_1 [of \"G a\"] by auto\n                  moreover have \"Adj'.\\<epsilon>FoF\\<eta>.map (G a) = F (G a)\"\n                    using a by (simp add: Adj'.\\<eta>\\<epsilon>.triangle_F)\n                  ultimately show ?thesis by auto\n                qed\n                thus ?thesis\n                  using a Adj.D.comp_cod_arr by auto\n              qed\n              also have \"... = G a\"\n                using a Adj.\\<eta>\\<epsilon>.triangle_G Adj.G\\<epsilon>o\\<eta>G.map_simp_1 [of a] by auto\n              finally show ?thesis by auto\n            qed\n            thus ?thesis using a by auto\n          qed\n        qed\n      qed\n    qed\n    have \"natural_isomorphism C D G G' \\<tau>.map\" ..\n    thus \"naturally_isomorphic C D G G'\"\n      using naturally_isomorphic_def by blast\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/Category3/Adjunction.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8558511543206819, "lm_q2_score": 0.8418256551882382, "lm_q1q2_score": 0.720477458729618}}
{"text": "(*  Title:       Countable Ordinals\n\n    Author:      Brian Huffman, 2005\n    Maintainer:  Brian Huffman <brianh at cse.ogi.edu>\n*)\n\nsection \\<open>Fixed-points\\<close>\n\ntheory OrdinalFix\nimports OrdinalInverse\nbegin\n\nprimrec iter :: \"nat \\<Rightarrow> ('a \\<Rightarrow> 'a) \\<Rightarrow> ('a \\<Rightarrow> 'a)\"\nwhere\n  \"iter 0       F x = x\"\n| \"iter (Suc n) F x = F (iter n F x)\"\n\ndefinition\n  oFix :: \"(ordinal \\<Rightarrow> ordinal) \\<Rightarrow> ordinal \\<Rightarrow> ordinal\" where\n  \"oFix F a = oLimit (\\<lambda>n. iter n F a)\"\n\nlemma oFix_fixed:\n\"\\<lbrakk>continuous F; a \\<le> F a\\<rbrakk> \\<Longrightarrow> F (oFix F a) = oFix F a\"\n apply (unfold oFix_def)\n apply (simp only: continuousD)\n apply (rule order_antisym)\n  apply (rule oLimit_leI, clarify)\n  apply (rule_tac n=\"Suc n\" in le_oLimitI, simp)\n apply (rule oLimit_leI, clarify)\n apply (rule_tac n=n in le_oLimitI)\n apply (induct_tac n, simp)\n apply (simp add: continuous.monoD)\ndone\n\nlemma oFix_least:\n\"\\<lbrakk>mono F; F x = x; a \\<le> x\\<rbrakk> \\<Longrightarrow> oFix F a \\<le> x\"\n apply (unfold oFix_def)\n apply (rule oLimit_leI, clarify)\n apply (induct_tac n, simp_all)\n apply (erule subst)\n apply (erule monoD, assumption)\ndone\n\nlemma mono_oFix: \"mono F \\<Longrightarrow> mono (oFix F)\"\n apply (rule monoI, unfold oFix_def)\n apply (subgoal_tac \"\\<forall>n. iter n F x \\<le> iter n F y\")\n  apply (rule oLimit_leI, clarify)\n  apply (rule_tac n=n in le_oLimitI, erule spec)\n apply (rule allI, induct_tac n)\n  apply simp\n apply (simp add: monoD)\ndone\n\nlemma less_oFixD:\n\"\\<lbrakk>x < oFix F a; mono F; F x = x\\<rbrakk> \\<Longrightarrow> x < a\"\n apply (simp add: linorder_not_le[symmetric])\n apply (erule contrapos_nn)\nby (rule oFix_least)\n\nlemma less_oFixI: \"a < F a \\<Longrightarrow> a < oFix F a\"\n apply (unfold oFix_def)\n apply (erule order_less_le_trans)\n apply (rule_tac n=1 in le_oLimitI)\n apply simp\ndone\n\nlemma le_oFix: \"a \\<le> oFix F a\"\n apply (unfold oFix_def)\n apply (rule_tac n=0 in le_oLimitI)\n apply simp\ndone\n\nlemma le_oFix1: \"F a \\<le> oFix F a\"\n apply (unfold oFix_def)\n apply (rule_tac n=1 in le_oLimitI)\n apply simp\ndone\n\nlemma less_oFix_0D:\n\"\\<lbrakk>x < oFix F 0; mono F\\<rbrakk> \\<Longrightarrow> x < F x\"\n apply (unfold oFix_def, drule less_oLimitD, clarify)\n apply (erule_tac P=\"x < iter n F 0\" in rev_mp)\n apply (induct_tac n, auto simp add: linorder_not_less)\n apply (erule order_less_le_trans)\n apply (erule monoD, assumption)\ndone\n\nlemma zero_less_oFix_eq: \"(0 < oFix F 0) = (0 < F 0)\"\n apply (safe)\n  apply (erule contrapos_pp)\n  apply (simp only: linorder_not_less oFix_def)\n  apply (rule oLimit_leI[rule_format])\n  apply (induct_tac n, simp, simp)\n apply (erule less_oFixI)\ndone\n\nlemma oFix_eq_self: \"F a = a \\<Longrightarrow> oFix F a = a\"\n apply (unfold oFix_def)\n apply (subgoal_tac \"\\<forall>n. iter n F a = a\", simp)\n apply (rule allI, induct_tac n, simp_all)\ndone\n\n\nsubsection \\<open>Derivatives of ordinal functions\\<close>\n\ntext \"The derivative of F enumerates all the fixed-points of F\"\n\ndefinition\n  oDeriv :: \"(ordinal \\<Rightarrow> ordinal) \\<Rightarrow> ordinal \\<Rightarrow> ordinal\" where\n  \"oDeriv F = ordinal_rec (oFix F 0) (\\<lambda>p x. oFix F (oSuc x))\"\n\nlemma oDeriv_0 [simp]:\n\"oDeriv F 0 = oFix F 0\"\nby (simp add: oDeriv_def)\n\nlemma oDeriv_oSuc [simp]:\n\"oDeriv F (oSuc x) = oFix F (oSuc (oDeriv F x))\"\nby (simp add: oDeriv_def)\n\nlemma oDeriv_oLimit [simp]:\n\"oDeriv F (oLimit f) = oLimit (\\<lambda>n. oDeriv F (f n))\"\n apply (unfold oDeriv_def)\n apply (rule ordinal_rec_oLimit, clarify)\n apply (rule order_trans[OF order_less_imp_le[OF less_oSuc]])\n apply (rule le_oFix)\ndone\n\nlemma oDeriv_fixed:\n\"normal F \\<Longrightarrow> F (oDeriv F n) = oDeriv F n\"\n apply (rule_tac a=n in oLimit_induct, simp_all)\n   apply (rule oFix_fixed)\n    apply (erule normal.continuous)\n   apply simp\n  apply (rule oFix_fixed)\n   apply (erule normal.continuous)\n  apply (erule normal.increasing)\n apply (simp add: normal.oLimit)\ndone\n\nlemma oDeriv_fixedD:\n\"\\<lbrakk>oDeriv F x = x; normal F\\<rbrakk> \\<Longrightarrow> F x = x\"\nby (erule subst, erule oDeriv_fixed)\n\nlemma normal_oDeriv:\n\"normal (oDeriv F)\"\n apply (rule normalI, simp_all)\n apply (rule order_less_le_trans[OF less_oSuc])\n apply (rule le_oFix)\ndone\n\nlemma oDeriv_increasing:\n\"continuous F \\<Longrightarrow> F x \\<le> oDeriv F x\"\n apply (rule_tac a=x in oLimit_induct)\n   apply (simp add: le_oFix1)\n  apply simp\n  apply (rule order_trans[OF _ le_oFix1])\n  apply (erule continuous.monoD)\n  apply simp\n  apply (rule normal.increasing)\n  apply (rule normal_oDeriv)\n apply (simp add: continuousD)\n apply (rule oLimit_leI[rule_format])\n apply (rule_tac n=n in le_oLimitI)\n apply (erule spec)\ndone\n\nlemma oDeriv_total:\n\"\\<lbrakk>normal F; F x = x\\<rbrakk> \\<Longrightarrow> \\<exists>n. x = oDeriv F n\"\n apply (subgoal_tac \"\\<exists>n. oDeriv F n \\<le> x \\<and> x < oDeriv F (oSuc n)\")\n  apply clarsimp\n  apply (drule less_oFixD)\n    apply (erule normal.mono)\n   apply assumption\n  apply (rule_tac x=n in exI, simp add: less_oSuc_eq_le)\n apply (rule normal.oInv_ex[OF normal_oDeriv])\n apply (simp add: oFix_least normal.mono)\ndone\n\nlemma range_oDeriv:\n\"normal F \\<Longrightarrow> range (oDeriv F) = {x. F x = x}\"\nby (auto intro: oDeriv_fixed dest: oDeriv_total)\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/OrdinalFix.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8558511616741042, "lm_q2_score": 0.8418256472515683, "lm_q1q2_score": 0.7204774581273095}}
{"text": "theory Gronwall\nimports Vector_Derivative_On\nbegin\n\nsubsection \\<open>Gronwall\\<close>\n\nlemma derivative_quotient_bound:\n  assumes g_deriv_on: \"(g has_vderiv_on g') {a .. b}\"\n  assumes frac_le: \"\\<And>t. t \\<in> {a .. b} \\<Longrightarrow> g' t / g t \\<le> K\"\n  assumes g'_cont: \"continuous_on {a .. b} g'\"\n  assumes g_pos: \"\\<And>t. t \\<in> {a .. b} \\<Longrightarrow> g t > 0\"\n  assumes t_in: \"t \\<in> {a .. b}\"\n  shows \"g t \\<le> g a * exp (K * (t - a))\"\nproof -\n  have g_deriv: \"\\<And>t. t \\<in> {a .. b} \\<Longrightarrow> (g has_real_derivative g' t) (at t within {a .. b})\"\n    using g_deriv_on\n    by (auto simp: has_vderiv_on_def has_field_derivative_iff_has_vector_derivative[symmetric])\n  from assms have g_nonzero: \"\\<And>t. t \\<in> {a .. b} \\<Longrightarrow> g t \\<noteq> 0\"\n    by fastforce\n  have frac_integrable: \"\\<And>t. t \\<in> {a .. b} \\<Longrightarrow> (\\<lambda>t. g' t / g t) integrable_on {a..t}\"\n    by (force simp: g_nonzero intro: assms has_field_derivative_subset[OF g_deriv]\n      continuous_on_subset[OF g'_cont] continuous_intros integrable_continuous_real\n      continuous_on_subset[OF vderiv_on_continuous_on[OF g_deriv_on]])\n  have \"\\<And>t. t \\<in> {a..b} \\<Longrightarrow> ((\\<lambda>t. g' t / g t) has_integral ln (g t) - ln (g a)) {a .. t}\"\n    by (rule fundamental_theorem_of_calculus)\n      (auto intro!: derivative_eq_intros assms has_field_derivative_subset[OF g_deriv]\n        simp: has_field_derivative_iff_has_vector_derivative[symmetric])\n  hence *: \"\\<And>t. t \\<in> {a .. b} \\<Longrightarrow> ln (g t) - ln (g a) = integral {a .. t} (\\<lambda>t. g' t / g t)\"\n    using integrable_integral[OF frac_integrable]\n    by (rule has_integral_unique[where f = \"\\<lambda>t. g' t / g t\"])\n  from * t_in have \"ln (g t) - ln (g a) = integral {a .. t} (\\<lambda>t. g' t / g t)\" .\n  also have \"\\<dots> \\<le> integral {a .. t} (\\<lambda>_. K)\"\n    using \\<open>t \\<in> {a .. b}\\<close>\n    by (intro integral_le) (auto intro!: frac_integrable frac_le integral_le)\n  also have \"\\<dots> = K * (t - a)\" using \\<open>t \\<in> {a .. b}\\<close>\n    by simp\n  finally have \"ln (g t) \\<le> K * (t - a) + ln (g a)\" (is \"?lhs \\<le> ?rhs\")\n    by simp\n  hence \"exp ?lhs \\<le> exp ?rhs\"\n    by simp\n  thus ?thesis\n    using \\<open>t \\<in> {a .. b}\\<close> g_pos\n    by (simp add: ac_simps exp_add del: exp_le_cancel_iff)\nqed\n\nlemma derivative_quotient_bound_left:\n  assumes g_deriv_on: \"(g has_vderiv_on g') {a .. b}\"\n  assumes frac_ge: \"\\<And>t. t \\<in> {a .. b} \\<Longrightarrow> K \\<le> g' t / g t\"\n  assumes g'_cont: \"continuous_on {a .. b} g'\"\n  assumes g_pos: \"\\<And>t. t \\<in> {a .. b} \\<Longrightarrow> g t > 0\"\n  assumes t_in: \"t \\<in> {a..b}\"\n  shows \"g t \\<le> g b * exp (K * (t - b))\"\nproof -\n  have g_deriv: \"\\<And>t. t \\<in> {a .. b} \\<Longrightarrow> (g has_real_derivative g' t) (at t within {a .. b})\"\n    using g_deriv_on\n    by (auto simp: has_vderiv_on_def has_field_derivative_iff_has_vector_derivative[symmetric])\n  from assms have g_nonzero: \"\\<And>t. t \\<in> {a..b} \\<Longrightarrow> g t \\<noteq> 0\"\n    by fastforce\n  have frac_integrable: \"\\<And>t. t \\<in> {a .. b} \\<Longrightarrow> (\\<lambda>t. g' t / g t) integrable_on {t..b}\"\n    by (force simp: g_nonzero intro: assms has_field_derivative_subset[OF g_deriv]\n      continuous_on_subset[OF g'_cont] continuous_intros integrable_continuous_real\n      continuous_on_subset[OF vderiv_on_continuous_on[OF g_deriv_on]])\n  have \"\\<And>t. t \\<in> {a..b} \\<Longrightarrow> ((\\<lambda>t. g' t / g t) has_integral ln (g b) - ln (g t)) {t..b}\"\n    by (rule fundamental_theorem_of_calculus)\n      (auto intro!: derivative_eq_intros assms has_field_derivative_subset[OF g_deriv]\n        simp: has_field_derivative_iff_has_vector_derivative[symmetric])\n  hence *: \"\\<And>t. t \\<in> {a..b} \\<Longrightarrow> ln (g b) - ln (g t) = integral {t..b} (\\<lambda>t. g' t / g t)\"\n    using integrable_integral[OF frac_integrable]\n    by (rule has_integral_unique[where f = \"\\<lambda>t. g' t / g t\"])\n  have \"K * (b - t) = integral {t..b} (\\<lambda>_. K)\"\n    using \\<open>t \\<in> {a..b}\\<close>\n    by simp\n  also have \"... \\<le> integral {t..b} (\\<lambda>t. g' t / g t)\"\n    using \\<open>t \\<in> {a..b}\\<close>\n    by (intro integral_le) (auto intro!: frac_integrable frac_ge integral_le)\n  also have \"... = ln (g b) - ln (g t)\"\n    using * t_in by simp\n  finally have \"K * (b - t) + ln (g t) \\<le> ln (g b)\" (is \"?lhs \\<le> ?rhs\")\n    by simp\n  hence \"exp ?lhs \\<le> exp ?rhs\"\n    by simp\n  hence \"g t * exp (K * (b - t)) \\<le> g b\"\n    using \\<open>t \\<in> {a..b}\\<close> g_pos\n    by (simp add: ac_simps exp_add del: exp_le_cancel_iff)\n  hence \"g t / exp (K * (t - b)) \\<le> g b\"\n    by (simp add: algebra_simps exp_diff)\n  thus ?thesis\n    by (simp add: field_simps)\nqed\n\nlemma gronwall_general:\n  fixes g K C a b and t::real\n  defines \"G \\<equiv> \\<lambda>t. C + K * integral {a..t} (\\<lambda>s. g s)\"\n  assumes g_le_G: \"\\<And>t. t \\<in> {a..b} \\<Longrightarrow> g t \\<le> G t\"\n  assumes g_cont: \"continuous_on {a..b} g\"\n  assumes g_nonneg: \"\\<And>t. t \\<in> {a..b} \\<Longrightarrow> 0 \\<le> g t\"\n  assumes pos: \"0 < C\" \"K > 0\"\n  assumes \"t \\<in> {a..b}\"\n  shows \"g t \\<le> C * exp (K * (t - a))\"\nproof -\n  have G_pos: \"\\<And>t. t \\<in> {a..b} \\<Longrightarrow> 0 < G t\"\n    by (auto simp: G_def intro!: add_pos_nonneg mult_nonneg_nonneg Henstock_Kurzweil_Integration.integral_nonneg\n      integrable_continuous_real assms intro: less_imp_le continuous_on_subset)\n  have \"g t \\<le> G t\" using assms by auto\n  also\n  {\n    have \"(G has_vderiv_on (\\<lambda>t. K * g t)) {a..b}\"\n      by (auto intro!: derivative_eq_intros integral_has_vector_derivative g_cont\n        simp add: G_def has_vderiv_on_def)\n    moreover\n    {\n      fix t assume \"t \\<in> {a..b}\"\n      hence \"K * g t / G t \\<le> K * G t / G t\"\n        using pos g_le_G G_pos\n        by (intro divide_right_mono mult_left_mono) (auto intro!: less_imp_le)\n      also have \"\\<dots> = K\"\n        using G_pos[of t] \\<open>t \\<in> {a .. b}\\<close> by simp\n      finally have \"K * g t / G t \\<le> K\" .\n    }\n    ultimately have \"G t \\<le> G a * exp (K * (t - a))\"\n      apply (rule derivative_quotient_bound)\n      using \\<open>t \\<in> {a..b}\\<close>\n      by (auto intro!: continuous_intros g_cont G_pos simp: field_simps pos)\n  }\n  also have \"G a = C\"\n    by (simp add: G_def)\n  finally show ?thesis\n    by simp\nqed\n\nlemma gronwall_general_left:\n  fixes g K C a b and t::real\n  defines \"G \\<equiv> \\<lambda>t. C + K * integral {t..b} (\\<lambda>s. g s)\"\n  assumes g_le_G: \"\\<And>t. t \\<in> {a..b} \\<Longrightarrow> g t \\<le> G t\"\n  assumes g_cont: \"continuous_on {a..b} g\"\n  assumes g_nonneg: \"\\<And>t. t \\<in> {a..b} \\<Longrightarrow> 0 \\<le> g t\"\n  assumes pos: \"0 < C\" \"K > 0\"\n  assumes \"t \\<in> {a..b}\"\n  shows \"g t \\<le> C * exp (-K * (t - b))\"\nproof -\n  have G_pos: \"\\<And>t. t \\<in> {a..b} \\<Longrightarrow> 0 < G t\"\n    by (auto simp: G_def intro!: add_pos_nonneg mult_nonneg_nonneg Henstock_Kurzweil_Integration.integral_nonneg\n      integrable_continuous_real assms intro: less_imp_le continuous_on_subset)\n  have \"g t \\<le> G t\" using assms by auto\n  also\n  {\n    have \"(G has_vderiv_on (\\<lambda>t. -K * g t)) {a..b}\"\n      by (auto intro!: derivative_eq_intros g_cont integral_has_vector_derivative'\n          simp add: G_def has_vderiv_on_def)\n    moreover\n    {\n      fix t assume \"t \\<in> {a..b}\"\n      hence \"K * g t / G t \\<le> K * G t / G t\"\n        using pos g_le_G G_pos\n        by (intro divide_right_mono mult_left_mono) (auto intro!: less_imp_le)\n      also have \"\\<dots> = K\"\n        using G_pos[of t] \\<open>t \\<in> {a .. b}\\<close> by simp\n      finally have \"K * g t / G t \\<le> K\" .\n      hence \"-K \\<le> -K * g t / G t\"\n        by simp\n    }\n    ultimately\n    have \"G t \\<le> G b * exp (-K * (t - b))\"\n      apply (rule derivative_quotient_bound_left)\n      using \\<open>t \\<in> {a..b}\\<close>\n      by (auto intro!: continuous_intros g_cont G_pos simp: field_simps pos)\n  }\n  also have \"G b = C\"\n    by (simp add: G_def)\n  finally show ?thesis\n    by simp\nqed\n\nlemma gronwall_general_segment:\n  fixes a b::real\n  assumes \"\\<And>t. t \\<in> closed_segment a b \\<Longrightarrow> g t \\<le> C + K * integral (closed_segment a t) g\"\n    and \"continuous_on (closed_segment a b) g\"\n    and \"\\<And>t. t \\<in> closed_segment a b \\<Longrightarrow> 0 \\<le> g t\"\n    and \"0 < C\"\n    and \"0 < K\"\n    and \"t \\<in> closed_segment a b\"\n  shows \"g t \\<le> C * exp (K * abs (t - a))\"\nproof cases\n  assume \"a \\<le> b\"\n  then have *: \"abs (t - a) = t -a\" using assms by (auto simp: closed_segment_eq_real_ivl)\n  show ?thesis\n    unfolding *\n    using assms\n    by (intro gronwall_general[where b=b]) (auto intro!: simp: closed_segment_eq_real_ivl \\<open>a \\<le> b\\<close>)\nnext\n  assume \"\\<not>a \\<le> b\"\n  then have *: \"K * abs (t - a) = - K * (t - a)\" using assms by (auto simp: closed_segment_eq_real_ivl algebra_simps)\n  {\n    fix s :: real\n    assume a1: \"b \\<le> s\"\n    assume a2: \"s \\<le> a\"\n    assume a3: \"\\<And>t. b \\<le> t \\<and> t \\<le> a \\<Longrightarrow> g t \\<le> C + K * integral (if a \\<le> t then {a..t} else {t..a}) g\"\n    have \"s = a \\<or> s < a\"\n      using a2 by (meson less_eq_real_def)\n    then have \"g s \\<le> C + K * integral {s..a} g\"\n      using a3 a1 by fastforce\n  } then show ?thesis\n    unfolding *\n    using assms  \\<open>\\<not>a \\<le> b\\<close>\n    by (intro gronwall_general_left)\n      (auto intro!: simp: closed_segment_eq_real_ivl)\nqed\n\nlemma gronwall_more_general_segment:\n  fixes a b c::real\n  assumes \"\\<And>t. t \\<in> closed_segment a b \\<Longrightarrow> g t \\<le> C + K * integral (closed_segment c t) g\"\n    and cont: \"continuous_on (closed_segment a b) g\"\n    and \"\\<And>t. t \\<in> closed_segment a b \\<Longrightarrow> 0 \\<le> g t\"\n    and \"0 < C\"\n    and \"0 < K\"\n    and t: \"t \\<in> closed_segment a b\"\n    and c: \"c \\<in> closed_segment a b\"\n  shows \"g t \\<le> C * exp (K * abs (t - c))\"\nproof -\n  from t c have \"t \\<in> closed_segment c a \\<or> t \\<in> closed_segment c b\"\n    by (auto simp: closed_segment_eq_real_ivl split_ifs)\n  then show ?thesis\n  proof\n    assume \"t \\<in> closed_segment c a\"\n    moreover\n    have subs: \"closed_segment c a \\<subseteq> closed_segment a b\" using t c\n      by (auto simp: closed_segment_eq_real_ivl split_ifs)\n    ultimately show ?thesis\n      by (intro gronwall_general_segment[where b=a])\n        (auto intro!: assms intro: continuous_on_subset)\n  next\n    assume \"t \\<in> closed_segment c b\"\n    moreover\n    have subs: \"closed_segment c b \\<subseteq> closed_segment a b\" using t c\n      by (auto simp: closed_segment_eq_real_ivl)\n    ultimately show ?thesis\n      by (intro gronwall_general_segment[where b=b])\n        (auto intro!: assms intro: continuous_on_subset)\n  qed\nqed\n\nlemma gronwall:\n  fixes g K C and t::real\n  defines \"G \\<equiv> \\<lambda>t. C + K * integral {0..t} (\\<lambda>s. g s)\"\n  assumes g_le_G: \"\\<And>t. 0 \\<le> t \\<Longrightarrow> t \\<le> a \\<Longrightarrow> g t \\<le> G t\"\n  assumes g_cont: \"continuous_on {0..a} g\"\n  assumes g_nonneg: \"\\<And>t. 0 \\<le> t \\<Longrightarrow> t \\<le> a \\<Longrightarrow> 0 \\<le> g t\"\n  assumes pos: \"0 < C\" \"0 < K\"\n  assumes \"0 \\<le> t\" \"t \\<le> a\"\n  shows \"g t \\<le> C * exp (K * t)\"\n  apply(rule gronwall_general[where a=0, simplified, OF assms(2-6)[unfolded G_def]])\n  using assms(7,8)\n  by simp_all\n\nlemma gronwall_left:\n  fixes g K C and t::real\n  defines \"G \\<equiv> \\<lambda>t. C + K * integral {t..0} (\\<lambda>s. g s)\"\n  assumes g_le_G: \"\\<And>t. a \\<le> t \\<Longrightarrow> t \\<le> 0 \\<Longrightarrow> g t \\<le> G t\"\n  assumes g_cont: \"continuous_on {a..0} g\"\n  assumes g_nonneg: \"\\<And>t. a \\<le> t \\<Longrightarrow> t \\<le> 0 \\<Longrightarrow> 0 \\<le> g t\"\n  assumes pos: \"0 < C\" \"0 < K\"\n  assumes \"a \\<le> t\" \"t \\<le> 0\"\n  shows \"g t \\<le> C * exp (-K * t)\"\n  apply(simp, rule gronwall_general_left[where b=0, simplified, OF assms(2-6)[unfolded G_def]])\n  using assms(7,8)\n  by simp_all\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/Ordinary_Differential_Equations/Library/Gronwall.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.855851154320682, "lm_q2_score": 0.8418256492357358, "lm_q1q2_score": 0.720477453635162}}
{"text": "theory InductRules\nimports Main\nbegin\n\nlemma disjCases2[consumes 1, case_names 1 2]:\n  assumes AB: \"A \\<or> B\"\n  and AP: \"A \\<Longrightarrow> P\"\n  and BP: \"B \\<Longrightarrow> P\"\n  shows \"P\"\nproof -\n  from AB AP BP show ?thesis by blast\nqed\n\nlemma disjCases3[consumes 1, case_names 1 2 3]:\n  assumes AB: \"A \\<or> B \\<or> C\"\n  and AP: \"A \\<Longrightarrow> P\"\n  and BP: \"B \\<Longrightarrow> P\"\n  and CP: \"C \\<Longrightarrow> P\"\n  shows \"P\"\nproof -\n  from AB AP BP CP show ?thesis by blast\nqed\n\nlemma disjCases4[consumes 1, case_names 1 2 3 4]:\n  assumes AB: \"A \\<or> B \\<or> C \\<or> D\"\n  and AP: \"A \\<Longrightarrow> P\"\n  and BP: \"B \\<Longrightarrow> P\"\n  and CP: \"C \\<Longrightarrow> P\"\n  and DP: \"D \\<Longrightarrow> P\"\n  shows \"P\"\nproof -\n  from AB AP BP CP DP show ?thesis by blast\nqed\n\nlemma disjCases5[consumes 1, case_names 1 2 3 4 5]:\n  assumes AB: \"A \\<or> B \\<or> C \\<or> D \\<or> E\"\n  and AP: \"A \\<Longrightarrow> P\"\n  and BP: \"B \\<Longrightarrow> P\"\n  and CP: \"C \\<Longrightarrow> P\"\n  and DP: \"D \\<Longrightarrow> P\"\n  and EP: \"E \\<Longrightarrow> P\"\n  shows \"P\"\nproof -\n  from AB AP BP CP DP EP show ?thesis by blast\nqed\n\nlemma minimal_witness_ex:\n  assumes k: \"P (k::nat)\"\n  shows \"\\<exists> k0. k0 \\<le> k \\<and> P k0 \\<and> (\\<forall> k. k < k0 \\<longrightarrow> \\<not> (P k))\" \nproof -\n  let ?K = \"{ h. h \\<le> k \\<and> P h }\" \n  have finite_K: \"finite ?K\" by auto\n  have \"k \\<in> ?K\" by (simp add: k)\n  then have nonempty_K: \"?K \\<noteq> {}\" by auto\n  let ?k = \"Min ?K\"\n  have witness: \"?k \\<le> k \\<and> P ?k\"\n    by (metis (mono_tags, lifting) Min_in finite_K mem_Collect_eq nonempty_K)\n  have minimal: \"\\<forall> h. h < ?k \\<longrightarrow> \\<not> (P h)\" \n    by (metis Min_le witness dual_order.strict_implies_order \n        dual_order.trans finite_K leD mem_Collect_eq)\n  from witness minimal show ?thesis by metis \nqed\n\nlemma minimal_witness[consumes 1, case_names Minimal]:\n  assumes \"P (k::nat)\"\n  and \"\\<And> K. K \\<le> k \\<Longrightarrow> P K \\<Longrightarrow> (\\<And> k. k < K \\<Longrightarrow> \\<not> (P k)) \\<Longrightarrow> Q\"\n  shows \"Q\"\nproof -\n  from assms minimal_witness_ex show ?thesis by metis\nqed\n\nlemma ex_minimal_witness[consumes 1, case_names Minimal]:\n  assumes \"\\<exists> k. P (k::nat)\"\n  and \"\\<And> K. P K \\<Longrightarrow> (\\<And> k. k < K \\<Longrightarrow> \\<not> (P k)) \\<Longrightarrow> Q\"\n  shows \"Q\"\nproof -\n  from assms minimal_witness_ex show ?thesis by metis\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/LocalLexing/InductRules.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256551882382, "lm_q2_score": 0.8558511432905481, "lm_q1q2_score": 0.7204774494441684}}
{"text": "(* Author: Florian Haftmann, TU Muenchen *)\n\nsection \\<open>Lexicographic order on functions\\<close>\n\ntheory Fun_Lexorder\nimports MainRLT\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\" \"k' < k1 \\<Longrightarrow> f k' = g k'\" for k'\n    by (blast elim!: less_funE) \n  assume \"less_fun g f\" then obtain k2 where k2: \"g k2 < f k2\" \"k' < k2 \\<Longrightarrow> g k' = f k'\" for 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 \\<open>less_fun f g\\<close> obtain k1 where k1: \"f k1 < g k1\" \"k' < k1 \\<Longrightarrow> f k' = g k'\" for k'\n    by (blast elim!: less_funE)                          \n  from \\<open>less_fun g h\\<close> obtain k2 where k2: \"g k2 < h k2\" \"k' < k2 \\<Longrightarrow> g k' = h k'\" for 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  { define K where \"K = {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    define q where \"q = 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 \\<open>q \\<in> K\\<close> 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": "dtraytel", "repo": "HOLRLT", "sha": "e9029da59bb3af0c835604a65308498f9696a364", "save_path": "github-repos/isabelle/dtraytel-HOLRLT", "path": "github-repos/isabelle/dtraytel-HOLRLT/HOLRLT-e9029da59bb3af0c835604a65308498f9696a364/HOLRLT/Library/Fun_Lexorder.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511469672594, "lm_q2_score": 0.8418256432832333, "lm_q1q2_score": 0.7204774423504061}}
{"text": "(*\n  File: Connectivity.thy\n  Author: Bohua Zhan\n*)\n\nsection \\<open>Connectedness for a set of undirected edges.\\<close>\n\ntheory Connectivity\n  imports Union_Find\nbegin\n\ntext \\<open>A simple application of union-find for graph connectivity.\\<close>\n\nfun is_path :: \"nat \\<Rightarrow> (nat \\<times> nat) set \\<Rightarrow> nat list \\<Rightarrow> bool\" where\n  \"is_path n S [] = False\"\n| \"is_path n S (x # xs) =\n   (if xs = [] then x < n else ((x, hd xs) \\<in> S \\<or> (hd xs, x) \\<in> S) \\<and> is_path n S xs)\"\nsetup \\<open>fold add_rewrite_rule @{thms is_path.simps}\\<close>\n\ndefinition has_path :: \"nat \\<Rightarrow> (nat \\<times> nat) set \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> bool\" where [rewrite]:\n  \"has_path n S i j \\<longleftrightarrow> (\\<exists>p. is_path n S p \\<and> hd p = i \\<and> last p = j)\"\n\nlemma is_path_nonempty [forward]: \"is_path n S p \\<Longrightarrow> p \\<noteq> []\" by auto2\nlemma nonempty_is_not_path [resolve]: \"\\<not>is_path n S []\" by auto2\n\nlemma is_path_extend [forward]:\n  \"is_path n S p \\<Longrightarrow> S \\<subseteq> T \\<Longrightarrow> is_path n T p\"\n@proof @induct p @qed\n\nlemma has_path_extend [forward]:\n  \"has_path n S i j \\<Longrightarrow> S \\<subseteq> T \\<Longrightarrow> has_path n T i j\" by auto2\n\ndefinition joinable :: \"nat list \\<Rightarrow> nat list \\<Rightarrow> bool\" where [rewrite]:\n  \"joinable p q \\<longleftrightarrow> (last p = hd q)\"\n\ndefinition path_join :: \"nat list \\<Rightarrow> nat list \\<Rightarrow> nat list\" where [rewrite]:\n  \"path_join p q = p @ tl q\"\nsetup \\<open>register_wellform_data (\"path_join p q\", [\"joinable p q\"])\\<close>\nsetup \\<open>add_prfstep_check_req (\"path_join p q\", \"joinable p q\")\\<close>\n\nlemma path_join_hd [rewrite]: \"p \\<noteq> [] \\<Longrightarrow> hd (path_join p q) = hd p\" by auto2\n\nlemma path_join_last [rewrite]: \"joinable p q \\<Longrightarrow> q \\<noteq> [] \\<Longrightarrow> last (path_join p q) = last q\"\n@proof @have \"q = hd q # tl q\" @case \"tl q = []\" @qed\n\nlemma path_join_is_path [backward]:\n  \"joinable p q \\<Longrightarrow> is_path n S p \\<Longrightarrow> is_path n S q \\<Longrightarrow> is_path n S (path_join p q)\"\n@proof @induct p @qed\n\nlemma has_path_trans [forward]:\n  \"has_path n S i j \\<Longrightarrow> has_path n S j k \\<Longrightarrow> has_path n S i k\"\n@proof\n  @obtain p where \"is_path n S p\" \"hd p = i\" \"last p = j\"\n  @obtain q where \"is_path n S q\" \"hd q = j\" \"last q = k\"\n  @have \"is_path n S (path_join p q)\"\n@qed\n\ndefinition is_valid_graph :: \"nat \\<Rightarrow> (nat \\<times> nat) set \\<Rightarrow> bool\" where [rewrite]:\n  \"is_valid_graph n S \\<longleftrightarrow> (\\<forall>p\\<in>S. fst p < n \\<and> snd p < n)\"\n\nlemma has_path_single1 [backward1]:\n  \"is_valid_graph n S \\<Longrightarrow> (a, b) \\<in> S \\<Longrightarrow> has_path n S a b\"\n@proof @have \"is_path n S [a, b]\" @qed\n\nlemma has_path_single2 [backward1]:\n  \"is_valid_graph n S \\<Longrightarrow> (a, b) \\<in> S \\<Longrightarrow> has_path n S b a\"\n@proof @have \"is_path n S [b, a]\" @qed\n\nlemma has_path_refl [backward2]:\n  \"is_valid_graph n S \\<Longrightarrow> a < n \\<Longrightarrow> has_path n S a a\"\n@proof @have \"is_path n S [a]\" @qed\n\ndefinition connected_rel :: \"nat \\<Rightarrow> (nat \\<times> nat) set \\<Rightarrow> (nat \\<times> nat) set\" where\n  \"connected_rel n S = {(a,b). has_path n S a b}\"\n\nlemma connected_rel_iff [rewrite]:\n  \"(a, b) \\<in> connected_rel n S \\<longleftrightarrow> has_path n S a b\" using connected_rel_def by simp\n\nlemma connected_rel_trans [forward]:\n  \"trans (connected_rel n S)\" by auto2\n\nlemma connected_rel_refl [backward2]:\n  \"is_valid_graph n S \\<Longrightarrow> a < n \\<Longrightarrow> (a, a) \\<in> connected_rel n S\" by auto2\n\nlemma is_path_per_union [rewrite]:\n  \"is_valid_graph n (S \\<union> {(a, b)}) \\<Longrightarrow>\n   has_path n (S \\<union> {(a, b)}) i j \\<longleftrightarrow> (i, j) \\<in> per_union (connected_rel n S) a b\"\n@proof\n  @let \"R = connected_rel n S\"\n  @let \"S' = S \\<union> {(a, b)}\" @have \"S \\<subseteq> S'\"\n  @case \"(i, j) \\<in> per_union R a b\" @with\n    @case \"(i, a) \\<in> R \\<and> (b, j) \\<in> R\" @with\n      @have \"has_path n S' i a\" @have \"has_path n S' a b\" @have \"has_path n S' b j\"\n    @end\n    @case \"(i, b) \\<in> R \\<and> (a, j) \\<in> R\" @with\n      @have \"has_path n S' i b\" @have \"has_path n S' b a\" @have \"has_path n S' a j\"\n    @end\n  @end\n  @case \"has_path n S' i j\" @with\n    @have (@rule) \"\\<forall>p. is_path n S' p \\<longrightarrow> (hd p, last p) \\<in> per_union R a b\" @with\n      @induct p @with\n      @subgoal \"p = x # xs\" @case \"xs = []\"\n        @have \"(x, hd xs) \\<in> per_union R a b\" @with\n          @have \"is_valid_graph n S\"\n          @case \"(x, hd xs) \\<in> S'\" @with @case \"(x, hd xs) \\<in> S\" @end\n          @case \"(hd xs, x) \\<in> S'\" @with @case \"(hd xs, x) \\<in> S\" @end\n        @end\n      @endgoal @end\n    @end\n    @obtain p where \"is_path n S' p\" \"hd p = i\" \"last p = j\"\n  @end\n@qed\n\nlemma connected_rel_union [rewrite]:\n  \"is_valid_graph n (S \\<union> {(a, b)}) \\<Longrightarrow>\n   connected_rel n (S \\<union> {(a, b)}) = per_union (connected_rel n S) a b\" by auto2\n\nlemma connected_rel_init [rewrite]:\n  \"connected_rel n {} = uf_init_rel n\"\n@proof\n  @have \"is_valid_graph n {}\"\n  @have \"\\<forall>i j. has_path n {} i j \\<longleftrightarrow> (i, j) \\<in> uf_init_rel n\" @with\n    @case \"has_path n {} i j\" @with\n      @obtain p where \"is_path n {} p\" \"hd p = i\" \"last p = j\"\n      @have \"p = hd p # tl p\"\n    @end\n  @end\n@qed\n\nfun connected_rel_ind :: \"nat \\<Rightarrow> (nat \\<times> nat) list \\<Rightarrow> nat \\<Rightarrow> (nat \\<times> nat) set\" where\n  \"connected_rel_ind n es 0 = uf_init_rel n\"\n| \"connected_rel_ind n es (Suc k) =\n   (let R = connected_rel_ind n es k; p = es ! k in\n      per_union R (fst p) (snd p))\"\nsetup \\<open>fold add_rewrite_rule @{thms connected_rel_ind.simps}\\<close>\n\nlemma connected_rel_ind_rule [rewrite]:\n  \"is_valid_graph n (set es) \\<Longrightarrow> k \\<le> length es \\<Longrightarrow>\n   connected_rel_ind n es k = connected_rel n (set (take k es))\"\n@proof @induct k @with\n  @subgoal \"k = Suc m\"\n    @have \"is_valid_graph n (set (take (Suc m) es))\"\n  @endgoal @end\n@qed\n\ntext \\<open>Correctness of the functional algorithm.\\<close>\ntheorem connected_rel_ind_compute [rewrite]:\n  \"is_valid_graph n (set es) \\<Longrightarrow>\n   connected_rel_ind n es (length es) = connected_rel n (set es)\" 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/Connectivity.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8558511322604133, "lm_q2_score": 0.8418256492357358, "lm_q1q2_score": 0.720477435064262}}
{"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_SSortSorts\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 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 ssortminimum1 :: \"Nat => Nat list => Nat\" where\n  \"ssortminimum1 x (nil2) = x\"\n| \"ssortminimum1 x (cons2 y1 ys1) =\n     (if le y1 x then ssortminimum1 y1 ys1 else ssortminimum1 x ys1)\"\n\nfun deleteBy :: \"('a => ('a => bool)) => 'a => 'a list =>\n                 'a list\" where\n  \"deleteBy x y (nil2) = nil2\"\n| \"deleteBy x y (cons2 y2 ys) =\n     (if (x y) y2 then ys else cons2 y2 (deleteBy x y ys))\"\n\n(*fun did not finish the proof*)\nfunction ssort :: \"Nat list => Nat list\" where\n  \"ssort (nil2) = nil2\"\n| \"ssort (cons2 y ys) =\n     (let m :: Nat = ssortminimum1 y ys\n     in cons2\n          m\n          (ssort\n             (deleteBy\n                (% (z :: Nat) => % (x2 :: Nat) => (z = x2)) m (cons2 y ys))))\"\n  by pat_completeness auto\n\ntheorem property0 :\n  \"ordered (ssort 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_SSortSorts.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797124237605, "lm_q2_score": 0.7905303137346446, "lm_q1q2_score": 0.7203151839309986}}
{"text": "section \"Tries via Search Trees\"\n\ntheory Trie_Map\nimports\n  Tree_Map\n  Trie_Fun\nbegin\n\ntext \\<open>An implementation of tries for an arbitrary alphabet \\<open>'a\\<close> where\nthe mapping from an element of type \\<open>'a\\<close> to the sub-trie is implemented by a binary search tree.\nAlthough this implementation uses maps implemented by red-black trees it works for any\nimplementation of maps.\n\nThis is an implementation of the ``ternary search trees'' by Bentley and Sedgewick\n[SODA 1997, Dr. Dobbs 1998]. The name derives from the fact that a node in the BST can now\nbe drawn to have 3 children, where the middle child is the sub-trie that the node maps\nits key to. Hence the name \\<open>trie3\\<close>.\n\nExample from @{url \"https://en.wikipedia.org/wiki/Ternary_search_tree#Description\"}:\n\n          c\n        / | \\\n       a  u  h\n       |  |  | \\\n       t. t  e. u\n     /  / |   / |\n    s. p. e. i. s.\n\nCharacters with a dot are final.\nThus the tree represents the set of strings \"cute\",\"cup\",\"at\",\"as\",\"he\",\"us\" and \"i\".\n\\<close>\n\ndatatype 'a trie3 = Nd3 bool \"('a * 'a trie3) tree\"\n\ntext \\<open>In principle one should be able to given an implementation of tries\nonce and for all for any map implementation and not just for a specific one (unbalanced trees) as done here.\nBut because the map (@{type tree}) is used in a datatype, the HOL type system does not support this.\n\nHowever, the development below works verbatim for any map implementation, eg \\<open>RBT_Map\\<close>,\nand not just \\<open>Tree_Map\\<close>, except for the termination lemma \\<open>lookup_size\\<close>.\\<close>\n\nterm size_tree\nlemma lookup_size[termination_simp]:\n  fixes t :: \"('a::linorder * 'a trie3) tree\"\n  shows \"lookup t a = Some b \\<Longrightarrow> size b < Suc (size_tree (\\<lambda>ab. Suc (size (snd( ab)))) t)\"\napply(induction t a rule: lookup.induct)\napply(auto split: if_splits)\ndone\n\n\ndefinition empty3 :: \"'a trie3\" where\n[simp]: \"empty3 = Nd3 False Leaf\"\n\nfun isin3 :: \"('a::linorder) trie3 \\<Rightarrow> 'a list \\<Rightarrow> bool\" where\n\"isin3 (Nd3 b m) [] = b\" |\n\"isin3 (Nd3 b m) (x # xs) = (case lookup m x of None \\<Rightarrow> False | Some t \\<Rightarrow> isin3 t xs)\"\n\nfun insert3 :: \"('a::linorder) list \\<Rightarrow> 'a trie3 \\<Rightarrow> 'a trie3\" where\n\"insert3 [] (Nd3 b m) = Nd3 True m\" |\n\"insert3 (x#xs) (Nd3 b m) =\n  Nd3 b (update x (insert3 xs (case lookup m x of None \\<Rightarrow> empty3 | Some t \\<Rightarrow> t)) m)\"\n\nfun delete3 :: \"('a::linorder) list \\<Rightarrow> 'a trie3 \\<Rightarrow> 'a trie3\" where\n\"delete3 [] (Nd3 b m) = Nd3 False m\" |\n\"delete3 (x#xs) (Nd3 b m) = Nd3 b\n   (case lookup m x of\n      None \\<Rightarrow> m |\n      Some t \\<Rightarrow> update x (delete3 xs t) m)\"\n\n\nsubsection \"Correctness\"\n\ntext \\<open>Proof by stepwise refinement. First abs3tract to type @{typ \"'a trie\"}.\\<close>\n\nfun abs3 :: \"'a::linorder trie3 \\<Rightarrow> 'a trie\" where\n\"abs3 (Nd3 b t) = Nd b (\\<lambda>a. map_option abs3 (lookup t a))\"\n\nfun invar3 :: \"('a::linorder)trie3 \\<Rightarrow> bool\" where\n\"invar3 (Nd3 b m) = (M.invar m \\<and> (\\<forall>a t. lookup m a = Some t \\<longrightarrow> invar3 t))\"\n\nlemma isin_abs3: \"isin3 t xs = isin (abs3 t) xs\"\napply(induction t xs rule: isin3.induct)\napply(auto split: option.split)\ndone\n\nlemma abs3_insert3: \"invar3 t \\<Longrightarrow> abs3(insert3 xs t) = insert xs (abs3 t)\"\napply(induction xs t rule: insert3.induct)\napply(auto simp: M.map_specs Tree_Set.empty_def[symmetric] split: option.split)\ndone\n\nlemma abs3_delete3: \"invar3 t \\<Longrightarrow> abs3(delete3 xs t) = delete xs (abs3 t)\"\napply(induction xs t rule: delete3.induct)\napply(auto simp: M.map_specs split: option.split)\ndone\n\nlemma invar3_insert3: \"invar3 t \\<Longrightarrow> invar3 (insert3 xs t)\"\napply(induction xs t rule: insert3.induct)\napply(auto simp: M.map_specs Tree_Set.empty_def[symmetric] split: option.split)\ndone\n\nlemma invar3_delete3: \"invar3 t \\<Longrightarrow> invar3 (delete3 xs t)\"\napply(induction xs t rule: delete3.induct)\napply(auto simp: M.map_specs split: option.split)\ndone\n\ntext \\<open>Overall correctness w.r.t. the \\<open>Set\\<close> ADT:\\<close>\n\ninterpretation S2: Set\nwhere empty = empty3 and isin = isin3 and insert = insert3 and delete = delete3\nand set = \"set o abs3\" and invar = invar3\nproof (standard, goal_cases)\n  case 1 show ?case by (simp add: isin_case split: list.split)\nnext\n  case 2 thus ?case by (simp add: isin_abs3)\nnext\n  case 3 thus ?case by (simp add: set_insert abs3_insert3 del: set_def)\nnext\n  case 4 thus ?case by (simp add: set_delete abs3_delete3 del: set_def)\nnext\n  case 5 thus ?case by (simp add: M.map_specs Tree_Set.empty_def[symmetric])\nnext\n  case 6 thus ?case by (simp add: invar3_insert3)\nnext\n  case 7 thus ?case by (simp add: invar3_delete3)\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/Trie_Map.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8577681195338728, "lm_q2_score": 0.83973396967765, "lm_q1q2_score": 0.720297028079112}}
{"text": "theory Tutorial3\nimports Main\nbegin\n\n  (*\n    A labeled transition system (LTS) is a directed graph where the edges \n    are annotated with labels. \n\n    A word from node q to node v is a list of labels, corresponding\n    to the edges on a path from q to v.\n\n    For example, the well known concept of finite automata, is usually \n    represented as an LTS with an initial state and a set of final states.\n  *)\n  \n  type_synonym ('q,'a) lts = \"'q \\<Rightarrow> 'a \\<Rightarrow> 'q \\<Rightarrow> bool\"\n  \n    \n  inductive word :: \"('q,'a) lts \\<Rightarrow> 'q \\<Rightarrow> 'a list \\<Rightarrow> 'q \\<Rightarrow> bool\" where\n    empty: \"word L q [] q\"\n  | step: \"\\<lbrakk> L q a r; word L r as s \\<rbrakk> \\<Longrightarrow> word L q (a#as) s\"  \n  \n  lemma word_append: \"\\<lbrakk>word L p as q; word L q bs r\\<rbrakk> \\<Longrightarrow> word L p (as@bs) r\"\n    apply (induction rule: word.induct)\n     apply simp\n    apply simp\n    apply (rule step) \n     apply assumption\n      by assumption\n      \n  lemma \"\\<lbrakk>word L p as q; word L q bs r\\<rbrakk> \\<Longrightarrow> word L p (as@bs) r\"\n    apply (induction rule: word.induct)\n    apply (auto intro: word.intros)\n    done  \n\n  lemma word_split: \"word L p (as@bs) r \\<Longrightarrow> (\\<exists>q. word L p as q \\<and> word L q bs r)\"\n    (* Try to instantiate induction rule *)\n    apply (induction L p \"as@bs\" r arbitrary: as rule: word.induct)\n     apply (auto intro: word.intros simp: Cons_eq_append_conv) \n    by (fastforce intro: word.intros)  \n      \n      \n  (* Sometimes, induction over a different structure, and case analysis, may be simpler: \n\n    To add case-distinctions over an inductive predicate to the rules that auto/blast/force/...\n    try automatically, use the elim: modifier. The rule is called <name>.cases\n  *)\n  thm word.cases\n  lemma \"word L p (as@bs) r \\<Longrightarrow> (\\<exists>q. word L p as q \\<and> word L q bs r)\"\n    apply (induction as arbitrary: p)\n     apply (auto intro: empty) \n     thm word.cases \n     apply (erule word.cases)\n      apply simp\n     apply (force intro: word.intros )\n     done  \n\n       \n  (* Combining both lemmas *)    \n  lemma word_append_conv: \"word L p (as@bs) r \\<longleftrightarrow> (\\<exists>q. word L p as q \\<and> word L q bs r)\"\n    by (auto simp: word_append word_split)\n\n      \n  (* Sometimes, we can also write an inductive predicate as a function.\n    For example, the empty and append equations hint at function equations\n    that recurse over the list!\n  *)\n      \n  thm empty word_append_conv\n    \n  (* We can refine them a bit *)  \n  (* In the proofs, we only need to do a case distinction over word ... \n    no induction is required.\n\n  *)\n  lemma word_Nil_conv: \"word L p [] q \\<longleftrightarrow> p=q\"\n    by (auto intro: empty elim: word.cases)\n    \n  lemma word_Cons_conv: \"word L p (a#bs) r \\<longleftrightarrow> (\\<exists>q. L p a q \\<and> word L q bs r)\"\n    apply auto\n     apply (erule word.cases)  \n      apply simp\n     apply auto\n    apply (auto intro: intro: word.intros)\n    done  \n      \n  lemma \"word L p (a#bs) r \\<longleftrightarrow> (\\<exists>q. L p a q \\<and> word L q bs r)\"\n    by (force intro: word.intros elim: word.cases)\n    \n  (* Once we have proven the above rules, we can directly encode them as a function *)\n  fun fword :: \"('q,'a) lts \\<Rightarrow> 'q \\<Rightarrow> 'a list \\<Rightarrow> 'q \\<Rightarrow> bool\" \n    where \n    \"fword L p [] q \\<longleftrightarrow> p=q\"\n  | \"fword L p (a#bs) r \\<longleftrightarrow> (\\<exists>q. L p a q \\<and> fword L q bs r)\"\n      \n\n  (* Proving equality to the inductive predicate is then straightforward,\n    by induction on the function / structural induction *)\nlemma \"fword L p w q \\<longleftrightarrow> word L p w q\"\n  apply (induction L p w q rule: fword.induct)\n   apply (auto simp: word_Nil_conv word_Cons_conv)\n   done \n    \nlemma \"fword L p w q \\<longleftrightarrow> word L p w q\"\n  apply (induction w arbitrary: p)\n   apply (auto simp: word_Nil_conv word_Cons_conv)\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/Tutorial3.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339837155239, "lm_q2_score": 0.8577681031721325, "lm_q1q2_score": 0.7202970263808433}}
{"text": "(*<*)\ntheory T6CFinitoIngles \nimports T5CCerradaIngles \nbegin\n(*>*)\n\nsubsection \\<open> Propiedad de car\u00e1cter finito \\<close>\n\ntext \\<open>\n  \\label{caracter-finitoP}\n  La demostraci\u00f3n del teorema de existencia de models est\u00e1 basada en\n  poder extender una propiedad de consistencia a otra propiedad de\n  consistencia que sea cerrada por subconjuntos y de \\emph{car\u00e1cter\n  finito}.\n\n  \\begin{definicion}\\label{cfinito}\n  Una colecci\u00f3n de conjuntos @{text \"\\<C>\"} es de \\textbf{car\u00e1cter finito}\n  si para cada conjunto @{text \"S\"} se tiene que, @{text \"S\"}\n  pertenece a @{text \"\\<C>\"} si y s\u00f3lo si cada subconjunto finito de \n  @{text \"S\"} pertenece a @{text \"\\<C>\"}.\n  \\end{definicion}\n\n  \\noindent Su formalizaci\u00f3n es:\n\\<close>\n\ndefinition caracter_finito :: \"'a set set \\<Rightarrow> bool\" where\n  \"caracter_finito \\<C> = (\\<forall>S. S \\<in> \\<C> = (\\<forall>S'. finite S' \\<longrightarrow> S' \\<subseteq> S \\<longrightarrow> S' \\<in> \\<C>))\"\n\ntext \\<open>\n  \\begin{teorema}\\label{CaracterFinitoCerradaP}\n  Toda colecci\u00f3n de conjuntos de car\u00e1cter finito @{text \"\\<C>\"} es cerrada\n  por subconjuntos.  \n  \\end{teorema}\n\n  \\begin{demostracion}\n  Supongamos que @{text \"\\<C>\"} es de car\u00e1cter finito; \n  sea @{text \"S \\<in> \\<C>\"} y @{text \"T \\<subseteq> S\"}, por la definici\u00f3n de\n  colecci\u00f3n cerrada por subconjuntos, hay que demostrar que \n  @{text \"T \\<in> \\<C>\"}. Para esto, por hipot\u00e9sis, basta con demostrar que\n  cada subconjunto finito @{text \"U\"} de @{text \"T\"} pertenece a \n  @{text \"\\<C>\"}. Sea @{text \"U\"} un conjunto finito tal que\n  @{text \"U \\<subseteq> T\"}. Puesto que @{text \"T \\<subseteq> S\"} se tiene que \n  @{text \"U \\<subseteq> S\"}. As\u00ed, puesto que @{text \"S \\<in> \\<C>\"} y @{text \"C\"} es\n  de car\u00e1cter finito se tiene que @{text \"U \\<in> \\<C>\"}.\n  \\end{demostracion}\n\n  La siguiente es la formalizaci\u00f3n del teorema anterior.\n\\<close>\n\ntheorem caracter_finito_cerrado: \n  assumes \"caracter_finito \\<C>\"\n  shows \"subconj_cerrada \\<C>\"\nproof -  \n  { fix S T\n    assume \"S \\<in> \\<C>\" and  \"T \\<subseteq> S\"\n    have \"T \\<in> \\<C>\" using \"caracter_finito_def\"\n    proof -\n      { fix U             \n        assume \"finite U\" and \"U \\<subseteq> T\"\n        have \"U \\<in> \\<C>\"\n        proof -\n          have \"U \\<subseteq> S\" using `U \\<subseteq> T` and `T \\<subseteq> S` by simp\n          thus \"U \\<in> \\<C>\" using `S \\<in> \\<C>` and `finite U` and assms \n            by (unfold caracter_finito_def) blast\n        qed} \n      thus ?thesis using assms by( unfold caracter_finito_def) blast\n    qed }\n  thus ?thesis  by(unfold  subconj_cerrada_def) blast\nqed     \n    \n(*<*)\ntext \\<open> \n  Otra estilo de demostrar el mismo teorema: \n\\<close>\n      \ntheorem caracter_finito_cerrado1: \n  assumes \"caracter_finito \\<C>\"\n  shows \"subconj_cerrada \\<C>\"\nproof (unfold subconj_cerrada_def) \n  show \"\\<forall> S \\<in> \\<C>. \\<forall> T. T \\<subseteq> S \\<longrightarrow> T \\<in> \\<C>\"  \n  proof \n    fix S \n    assume \"S \\<in> \\<C>\"\n    show \"\\<forall>T\\<subseteq>S. T \\<in> \\<C>\"\n    proof (rule allI)\n      fix T\n      show \"T \\<subseteq> S \\<longrightarrow> T \\<in> \\<C>\"\n      proof \n        assume \"T \\<subseteq> S\"\n        show \"T \\<in> \\<C>\" \n        proof -         \n          have \"\\<forall>U. finite U \\<longrightarrow> U \\<subseteq> T \\<longrightarrow> U \\<in> \\<C>\"\n          proof (rule allI)\n            fix U\n            show \"finite U \\<longrightarrow> U \\<subseteq> T \\<longrightarrow> U \\<in> \\<C>\"\n            proof\n              assume \"finite U\"\n              show \"U \\<subseteq> T \\<longrightarrow> U \\<in> \\<C>\"\n              proof\n                assume \"U \\<subseteq> T\" \n                hence \"U \\<subseteq> S\" using `T \\<subseteq> S` by simp\n                thus \"U \\<in> \\<C>\" using `S \\<in> \\<C>` and `finite U` and assms \n                  by (unfold caracter_finito_def) blast\n              qed\n            qed\n          qed\n          thus ?thesis using assms by( unfold caracter_finito_def) blast\n        qed\n      qed\n    qed\n  qed\nqed\n\n(*>*)\nsubsection \\<open> Extensi\u00f3n a una propiedad de car\u00e1cter finito \\<close>\n\ntext \\<open> \n  \\label{altercarfinito}\n  En la secci\u00f3n \\ref{cerraduraP} se demostr\u00f3 que toda propiedad de\n  consistencia proposicional @{text \"\\<C>\"} puede extenderse a una\n  propiedad de consistencia @{text \"\\<C>\\<^sup>+\"} que es cerrada por\n  subconjuntos. En esta secci\u00f3n demostraremoss que toda propiedad de\n  consistencia proposicional @{text \"\\<C>\"} que sea cerrada por\n  subconjuntos puede extenderse a una propiedad de consistencia\n  @{text \"\\<C>\u207b\"} que es de car\u00e1cter finito. Para la demostraci\u00f3n,\n  basta con considerar @{text \"\\<C>\u207b\"} igual a la colecci\u00f3n de todos\n  los conjuntos tales que sus subconjuntos finitos est\u00e1n en\n  @{text \"\\<C>\"}: @{text \"\\<C>\u207b = {S | \\<forall>S'\\<subseteq> S (S' finito \\<longrightarrow> S' \\<in> \\<C>)}\"}.\n\n  La definici\u00f3n en Isabelle de @{text \"\\<C>\u207b\"} es,\n\\<close>\n\ndefinition clausura_cfinito :: \"'a set set \\<Rightarrow> 'a set set\" (\"_\u207b\" [1000] 999) where\n  \"\\<C>\u207b = {S. \\<forall>S'. S' \\<subseteq> S \\<longrightarrow> finite S' \\<longrightarrow> S' \\<in> \\<C>}\"\n\ntext \\<open>\n  \\begin{teorema}\\label{AlternativaCfinitoP}\n  Sea @{text \"\\<C>\"} una colecci\u00f3n de conjuntos. Se verifican las\n  siguientes propiedades: \n  \\begin{itemize}\n  \\item[(a)] Si @{text \"\\<C>\"} es cerrada por subconjuntos, entonces\n    @{text \"\\<C> \\<subseteq> \\<C>\u207b\"}. \n  \\item[(b)] @{text \"\\<C>\u207b\"} es de car\u00e1cter finito.\n  \\item[(c)] Si @{text \"\\<C>\"} es una propiedad de consistencia\n    proposicional que es cerrada por subconjuntos entonces,\n    @{text \"\\<C>\u207b\"} es una propiedad de consistencia proposicional. \n  \\end{itemize}  \n  \\end{teorema}\n\\<close>\n\ntext \\<open>\n  \\begin{demostracion}\n\n  \\textbf{Apartado (a)} Supongamos que @{text \"\\<C>\"} es cerrada por\n  subconjuntos y sea @{text \"S \\<in> \\<C>\"}. Mostra\\-mos que @{text \"S \\<in> \\<C>\u207b\"}\n  usando la definici\u00f3n de @{text \"\\<C>\u207b\"}: sea @{text \"S'\\<subseteq> S\"} y \n  @{text \"S'\"} finito. Puesto que @{text \"S \\<in> \\<C>\"} y @{text \"S'\\<subseteq> S\"},\n  entonces @{text \"S' \\<in> \\<C>\"}, ya que por hip\u00f3tesis @{text \"\\<C>\"} es cerrada\n  por subconjuntos. \n \n  \\textbf{Apartado (b)} Sea @{text \"S\"} un conjunto. Por la definici\u00f3n\n  de propiedad de car\u00e1cter finito hay que demostrar que, @{text \"S\\<in> \\<C>\u207b\"}\n  si y s\u00f3lo si cada subconjunto finito de @{text \"S\"} pertenece a @{text\n  \"\\<C>\u207b\"}: \n \n  Si @{text \"S\\<in> \\<C>\u207b\"}, por la definici\u00f3n de @{text \"\\<C>\u207b\"}, se tiene que\n  cada subconjunto finito de @{text \"S\"} pertenece a @{text \"\\<C>\u207b\"} y\n  rec\u00edprocamente si cada subconjunto finito de @{text \"S\"} pertenece a\n  @{text \"\\<C>\u207b\"} entonces, por la definici\u00f3n de @{text \"\\<C>\u207b\"}, \n  @{text \"S\\<in> \\<C>\u207b\"}.\n\n  \\textbf{Apartado (c)} Supongamos que @{text \"\\<C>\"} es una propiedad de\n  consistencia proposicional que es cerrada por subconjuntos. Sea\n  @{text \"S \\<in> \\<C>\u207b\"}. Entonces, por la definici\u00f3n de @{text \"\\<C>\u207b\"}, se\n  tiene que cada subconjunto finito de @{text \"S\"} pertenece a @{text\n  \"\\<C>\"}. A continuaci\u00f3n mostramos que se cumplen las condiciones para que\n  @{text \"\\<C>\u207b\"} sea una propiedad de consistencia.\n\n  \\textbf{Condici\u00f3n 1} Sea @{text \"P\"} una f\u00f3rmula at\u00f3mica, demostramos\n  por contradicci\u00f3n que @{text \"P \\<notin> S\"} o @{text \"\\<not>P \\<notin> S\"}. Supongamos que\n  @{text \"P \\<in> S\"} y @{text \"\\<not>P \\<in> S\"}, entonces \n  @{text \"{P,\\<not>P} \\<subseteq> S\"}. Por tanto @{text \"{P,\\<not>P}\\<in> \\<C>\"}, por ser\n  @{text \"\\<C>\"} cerrada por subconjuntos.  Luego @{text \"P \\<notin> {P,\\<not>P}\"} o\n  @{text \"\\<not>P \\<notin> {P,\\<not>P}\"}, ya que @{text \"\\<C>\"} es una propiedad de\n  consistencia. De esta forma obtenemos una contradicci\u00f3n.\n\n  \\textbf{Condici\u00f3n 2} La demostraci\u00f3n de @{text \"\\<bottom> \\<notin> S\"} es por\n  contradicci\u00f3n. Supongamos que @{text \" \\<bottom>\\<in> S\"}, entonces \n  @{text \"{\\<bottom>} \\<subseteq> S\"}. Por lo tanto @{text \"{\\<bottom>} \\<in> \\<C>\"}, por ser\n  @{text \"\\<C>\"} cerrada pos subconjuntos. Luego @{text \"\\<bottom> \\<notin> {\\<bottom>}\"}, ya que\n  @{text \"\\<C>\"} es una propiedad de consistencia. De esta forma obtenemos\n  una contradicci\u00f3n. \n\n  De la misma forma @{text \"\\<not>\\<top> \\<notin> S\"}, de lo contrario @{text \"{\\<not>\\<top>} \\<subseteq> S\"}\n  y por lo tanto @{text \"{\\<not>\\<top>} \\<in> \\<C>\"}, por ser @{text \"\\<C>\"} cerrada por\n  subconjuntos. As\u00ed, puesto que @{text \"\\<C>\"} es una propiedad de\n  consistencia, se tendr\u00eda que @{text \"\\<not>\\<top> \\<notin> {\\<not>\\<top>}\"}, lo cual es imposible.\n\n  \\textbf{Condici\u00f3n 3} Supongamos que @{text \"\\<not>\\<not>F \\<in> S\"}. Demostramos que\n  @{text \"S\\<union>{F} \\<in> \\<C>\u207b\"} usando la definici\u00f3n de @{text \"\\<C>\u207b\"}:\n  consideremos @{text \"S'\"} subconjunto finito de @{text \"S\\<union>{F}\"}, y\n  mostremos que @{text \"S' \\<in> \\<C>\"}.\n\n  Puesto que @{text \"\\<not>\\<not>F \\<in> S\"} y @{text \"S' \\<subseteq> S\\<union>{F}\"} tenemos que\n  @{text \"S'\u2212{F}\\<union> {\\<not>\\<not>F}\\<subseteq> S\"}; tambi\u00e9n tene\\-mos que @{text \"S'\u2212{F}\\<union>{\\<not>\\<not>F}\"}\n  es finito ya que @{text \"S'\"} es finito. As\u00ed, @{text \"S'\u2212{F}\\<union>{\\<not>\\<not>F} \\<in> \\<C>\"} \n  por la definici\u00f3n de @{text \"\\<C>\\<^sup>-\"}, y como \n  @{text \"{\\<not>\\<not>F} \\<in> S'\u2212{F}\\<union>{\\<not>\\<not>F}\"} entonces \n  @{text \"(S'\u2212{F}\\<union>{\\<not>\\<not>F})\\<union>{F} \\<in> \\<C>\"} por ser @{text \"\\<C>\"} una propiedad de\n  consistencia. Adem\u00e1s, puesto que \n  @{text \"S' \u2212{F}\\<union>{\\<not>\\<not>F})\\<union>{F} = S'\\<union>{\\<not>\\<not>F}\\<union>{F}\"}, se tiene que \n  @{text \"S'\\<union>{\\<not>\\<not>F})\\<union>{F} \\<in> \\<C>\"}.  De esto \u00faltimo y como \n  @{text \"S'\\<subseteq> S'\\<union> {\\<not>\\<not>F}\\<union>{F}\"} se tiene que @{text \"S' \\<in> \\<C>\"} ya que por\n  hip\u00f3tesis @{text \"\\<C>\"} es cerrada por subconjuntos.\n\n  \\textbf{Condici\u00f3n 4} Supongamos que @{text \"\\<alpha> \\<in> S\"}. Demostramos que\n  @{text \"S\\<union>{\\<alpha>\\<^sub>1,\\<alpha>\\<^sub>2} \\<in> \\<C>\u207b\"} usando la definici\u00f3n de @{text \"\\<C>\u207b\"}:\n  consideremos @{text \"S'\"} subconjunto finito de @{text \"S\\<union>{\\<alpha>\\<^sub>1, \\<alpha>\\<^sub>2}\"},\n  y mostremos que @{text \"S' \\<in> \\<C>\"}. \n\n  Puesto que @{text \"\\<alpha> \\<in> S\"} y @{text \"S'\\<subseteq> S\\<union>{\\<alpha>\\<^sub>1,\\<alpha>\\<^sub>2}\"} tenemos que\n  @{text \"S'\u2212{\\<alpha>\\<^sub>1,\\<alpha>\\<^sub>2}\\<union>{\\<alpha> } \\<subseteq> S\"}; tambi\u00e9n tenemos que \n  @{text \"S'\u2212{\\<alpha>\\<^sub>1,\\<alpha>\\<^sub>2}\\<union>{\\<alpha>}\"} es finito ya que @{text \"S'\"} es finito.\n\n  As\u00ed, @{text \"S'\u2212{\\<alpha>\\<^sub>1, \\<alpha>\\<^sub>2}\\<union>{\\<alpha> } \\<in> \\<C>\"} por la definici\u00f3n de @{text \"\\<C>\\<^sup>-\"},\n  y como @{text \"\\<alpha> \\<in> S'\u2212{\\<alpha>\\<^sub>1,\\<alpha>\\<^sub>2}\\<union>{\\<alpha>}\"} entonces \n  @{text \"S'\u2212{\\<alpha>\\<^sub>1,\\<alpha>\\<^sub>2}\\<union>{\\<alpha>})\\<union>{\\<alpha>\\<^sub>1,\\<alpha>\\<^sub>2} \\<in> \\<C>\"} por ser @{text \"\\<C>\"} una propiedad de consistencia. \n\n  Adem\u00e1s, puesto que \n     @{text \"S'\u2212{\\<alpha>\\<^sub>1,\\<alpha>\\<^sub>2} \\<union> {\\<alpha>}) \\<union> {\\<alpha>\\<^sub>1,\\<alpha>\\<^sub>2} = S' \\<union> {\\<alpha>}\\<union> {\\<alpha>\\<^sub>1,\\<alpha>\\<^sub>2}\"}\n  se tiene que \n     @{text \"S'\\<union>{\\<alpha>}\\<union>{\\<alpha>\\<^sub>1,\\<alpha>\\<^sub>2} \\<in> \\<C>\"}.  \n  De esto \u00faltimo, y como @{text \"S'\\<subseteq> S'\\<union>{\\<alpha>}\\<union>{\\<alpha>\\<^sub>1,\\<alpha>\\<^sub>2}\"}, se tiene que\n  @{text \"S' \\<in> \\<C>\"} ya que por hip\u00f3tesis @{text \"\\<C>\"} es cerrada por\n  subconjuntos. \n\n  \\textbf{Condici\u00f3n 5} Supongamos que @{text \"\\<beta> \\<in> S\"}. Demostramos que\n  @{text \"S\\<union>{\\<beta>\\<^sub>1} \\<in> \\<C>\u207b\"} o @{text \"S\\<union>{\\<beta>\\<^sub>2} \\<in> \\<C>\u207b\"} por contradicci\u00f3n.\n\n  Supongamos que @{text \"S\\<union>{\\<beta>\\<^sub>1} \\<notin> \\<C>\u207b\"} y @{text \"S\\<union>{\\<beta>\\<^sub>2} \\<notin> \\<C>\u207b\"}. \n  Entonces, existe @{text \"S\\<^sub>1\"} subconjunto finito de @{text \"S\\<union>{\\<beta>\\<^sub>1}\"}\n  tal que @{text \"S\\<^sub>1 \\<notin> \\<C>\"}, y existe @{text \"S\\<^sub>2\"} subconjunto finito de\n  @{text \"S\\<union>{\\<beta>\\<^sub>2}\"} tal que @{text \"S\\<^sub>2 \\<notin> \\<C>\"}. Puesto que @{text \"\\<beta> \\<in> S\"}, \n  @{text \"S\\<^sub>1 \\<subseteq> S\\<union>{\\<beta>\\<^sub>1}\"} y @{text \"S\\<^sub>2 \\<subseteq> S\\<union>{\\<beta>\\<^sub>2}\"} tenemos que,\n  @{text \"(S\\<^sub>1\u2212{\\<beta>\\<^sub>1})\\<union>(S\\<^sub>2\u2212{\\<beta>\\<^sub>2})\\<union>{\\<beta>} \\<subseteq> S\"}.\n\n  Tambi\u00e9n tenemos que @{text \"(S\\<^sub>1\u2212{\\<beta>\\<^sub>1})\\<union>(S\\<^sub>2\u2212{\\<beta>\\<^sub>2})\\<union>{\\<beta>}\"} es finito ya que\n  @{text \"S\\<^sub>1\"} y @{text \"S\\<^sub>2\"} son finitos. As\u00ed, \n  @{text \"(S\\<^sub>1\u2212{\\<beta>\\<^sub>1})\\<union>(S\\<^sub>2\u2212{\\<beta>\\<^sub>2})\\<union>{\\<beta>} \\<in> \\<C>\"} por la definici\u00f3n de @{text \"\\<C>\\<^sup>-\"}, \n  y como  \n     \\newline \\hspace*{1cm}\n     @{text \"\\<beta> \\<in> (S\\<^sub>1\u2212{\\<beta>\\<^sub>1})\\<union>(S\\<^sub>2\u2212{\\<beta>\\<^sub>2})\\<union>{\\<beta>}\"} \n  \\newline entonces, por ser @{text \"\\<C>\"} una propiedad de consistencia,\n  se tiene que \n     \\newline \\hspace*{1cm}\n     @{text \"((S\\<^sub>1\u2212{\\<beta>\\<^sub>1})\\<union>(S\\<^sub>2\u2212{\\<beta>\\<^sub>2})\\<union>{\\<beta>})\\<union>{\\<beta>\\<^sub>1} \\<in> \\<C>\"} \n     \\newline \\hspace*{1cm}\n     @{text \"((S\\<^sub>1\u2212{\\<beta>\\<^sub>1})\\<union>(S\\<^sub>2\u2212{\\<beta>\\<^sub>2})\\<union>{\\<beta>})\\<union> {\\<beta>\\<^sub>2} \\<in> \\<C>\"}.\n\n  De esto \u00faltimo tenemos que @{text \"S\\<^sub>1 \\<in> \\<C>\"} o @{text \"S\\<^sub>2 \\<in> \\<C>\"}:\n\n  Si @{text \"((S\\<^sub>1\u2212{\\<beta>\\<^sub>1})\\<union>(S\\<^sub>2\u2212{\\<beta>\\<^sub>2})\\<union>{\\<beta>})\\<union>{\\<beta>\\<^sub>1}\\<in> \\<C>\"} entonces, puesto que \n     \\newline \\hspace*{1cm}\n     @{text \"S\\<^sub>1 \\<subseteq> ((S\\<^sub>1\u2212{\\<beta>\\<^sub>1})\\<union>(S\\<^sub>2\u2212{\\<beta>\\<^sub>2})\\<union>{\\<beta>})\\<union>{\\<beta>\\<^sub>1}\"}, \n  \\newline tenemos que @{text \"S\\<^sub>1\\<in> \\<C>\"} por ser @{text \"\\<C>\"} cerrada por\n  subconjuntos. \n\n  De igual forma, si @{text \"((S\\<^sub>1\u2212{\\<beta>\\<^sub>1})\\<union> (S\\<^sub>2\u2212{\\<beta>\\<^sub>2})\\<union>{\\<beta>})\\<union>{\\<beta>\\<^sub>2} \\<in> \\<C>\"}\n  entonces, puesto que \n     \\newline \\hspace*{1cm}\n     @{text \"S\\<^sub>2 \\<subseteq> ((S\\<^sub>1\u2212{\\<beta>\\<^sub>1})\\<union>(S\\<^sub>2\u2212{\\<beta>\\<^sub>2})\\<union>{\\<beta>})\\<union>{\\<beta>\\<^sub>2}\"}, \n  \\newline tenemos que @{text \"S\\<^sub>2 \\<in> \\<C>\"} por ser @{text \"\\<C>\"} cerrada por\n  subconjuntos. \n\n  Esto contradice la hip\u00f3tesis inicial: @{text \"S\\<^sub>1\\<notin> \\<C>\"} y @{text \"S\\<^sub>2\\<notin> \\<C>\"}. \n  \\end{demostracion}\n\n  A continuaci\u00f3n formalizamos cada parte de la prueba del teorema anterior.\n  La formalizaci\u00f3n de la parte (a) es la siguiente: \n\\<close>\n\nlemma caracter_finito_subset:\n  assumes \"subconj_cerrada \\<C>\"\n  shows \"\\<C> \\<subseteq> \\<C>\u207b\"\nproof -\n  { fix S\n    assume \"S \\<in> \\<C>\"\n    have \"S \\<in> \\<C>\u207b\" \n    proof -\n      { fix S'\n        assume \"S' \\<subseteq> S\" and \"finite S'\"\n        hence \"S' \\<in> \\<C>\" using  `subconj_cerrada \\<C>` and `S \\<in> \\<C>`\n          by (simp add: subconj_cerrada_def)}\n      thus ?thesis by (simp add: clausura_cfinito_def) \n    qed}\n  thus ?thesis by auto\nqed\n\ntext \\<open> \n  El siguiente lema formaliza la parte (b) del teorema\n  \\ref{AlternativaCfinitoP} \n\\<close>   \n\nlemma caracter_finito: \"caracter_finito (\\<C>\u207b)\"\nproof (unfold caracter_finito_def)\n  show \"\\<forall>S. (S \\<in> \\<C>\u207b) = (\\<forall>S'. finite S' \\<longrightarrow> S' \\<subseteq> S \\<longrightarrow> S' \\<in> \\<C>\u207b)\"\n  proof\n    fix  S\n    { assume  \"S \\<in> \\<C>\u207b\"\n      hence \"\\<forall>S'. finite S' \\<longrightarrow> S' \\<subseteq> S \\<longrightarrow> S' \\<in> \\<C>\u207b\" \n        by(simp add: clausura_cfinito_def)} \n    moreover\n    { assume \"\\<forall>S'. finite S' \\<longrightarrow> S' \\<subseteq> S \\<longrightarrow> S' \\<in> \\<C>\u207b\"\n      hence  \"S \\<in> \\<C>\u207b\" by(simp add: clausura_cfinito_def)}\n    ultimately\n    show \"(S \\<in> \\<C>\u207b) = (\\<forall>S'. finite S' \\<longrightarrow> S' \\<subseteq> S \\<longrightarrow> S' \\<in> \\<C>\u207b)\"\n      by blast\n  qed\nqed\n \ntext \\<open> \n  Los siguientes lemas corresponden a la formalizaci\u00f3n de los 5 casos de\n  la parte (c) del teorema \\ref{AlternativaCfinitoP}. \n\\<close>\n\nlemma condicaracterP1:\n  assumes \"consistenceP \\<C>\" \n  and \"subconj_cerrada \\<C>\" \n  and hip: \"\\<forall>S'\\<subseteq>S. finite S' \\<longrightarrow> S' \\<in> \\<C>\"\n  shows \"(\\<forall>P. \\<not>(atom P \\<in> S \\<and> (\\<not>.atom P) \\<in> S))\"\n(*<*)\nproof (rule allI)+  \n  fix P t\n  show \"\\<not>(atom P  \\<in> S \\<and> (\\<not>.atom P) \\<in> S)\"\n  proof (rule notI)\n    assume \"atom P \\<in> S \\<and> (\\<not>.atom P) \\<in> S\"\n    hence \"{atom P , \\<not>.atom P} \\<subseteq> S\" by simp\n    hence \"{atom P, \\<not>.atom P} \\<in> \\<C>\" using hip by simp\n    moreover\n    have \"\\<forall>S. S \\<in> \\<C> \\<longrightarrow> (\\<forall>P ts. \\<not>(atom P \\<in> S \\<and> (\\<not>.atom P) \\<in> S))\"\n      using `consistenceP \\<C>`\n      by (simp add: consistenceP_def)\n    ultimately\n    have \"\\<not>(atom P \\<in> {atom P , \\<not>.atom P} \\<and> \n          (\\<not>.atom P) \\<in> {atom P, \\<not>.atom P})\"\n      by auto \n    thus False by simp\n  qed\nqed  \n(*>*)\ntext\\<open> \\<close>\nlemma condicaracterP2:\n  assumes \"consistenceP \\<C>\" \n  and \"subconj_cerrada \\<C>\" \n  and hip: \"\\<forall>S'\\<subseteq>S. finite S' \\<longrightarrow> S' \\<in> \\<C>\"\n  shows \"FF \\<notin> S \\<and> (\\<not>.TT)\\<notin> S\"\n(*<*)\nproof -\n  have \"FF \\<notin> S\"\n  proof(rule notI)\n    assume \"FF \\<in> S\"\n    hence \"{FF} \\<subseteq> S\" by simp\n    hence \"{FF}\\<in> \\<C>\" using hip by simp\n    moreover\n    have \"\\<forall>S. S \\<in> \\<C> \\<longrightarrow> FF \\<notin> S\" using `consistenceP \\<C>` \n      by (simp add: consistenceP_def)\n    ultimately \n    have \"FF \\<notin> {FF}\" by auto    \n    thus False by simp\n  qed   \n  moreover\n  have \"(\\<not>.TT)\\<notin> S\"\n  proof(rule notI)    \n    assume \"(\\<not>.TT) \\<in> S\"\n    hence \"{\\<not>.TT} \\<subseteq> S\" by simp\n    hence \"{\\<not>.TT}\\<in> \\<C>\" using hip by simp\n    moreover\n    have \"\\<forall>S. S \\<in> \\<C> \\<longrightarrow> (\\<not>.TT) \\<notin> S\" using `consistenceP \\<C>` \n      by (simp add: consistenceP_def)\n    ultimately \n    have \"(\\<not>.TT) \\<notin> {(\\<not>.TT)}\" by auto    \n    thus False by simp\n  qed\n  ultimately show ?thesis by simp   \nqed   \n(*>*)\ntext\\<open> \\<close>\nlemma condicaracterP3:\n  assumes \"consistenceP \\<C>\" \n  and \"subconj_cerrada \\<C>\" \n  and hip: \"\\<forall>S'\\<subseteq>S. finite S' \\<longrightarrow> S' \\<in> \\<C>\"\n  shows \"\\<forall>F. (\\<not>.\\<not>.F) \\<in> S \\<longrightarrow>  S \\<union> {F} \\<in> \\<C>\u207b\"\n(*<*)\nproof (rule allI)        \n  fix F\n  show \"(\\<not>.\\<not>.F) \\<in> S \\<longrightarrow>  S \\<union> {F} \\<in> \\<C>\u207b\"\n  proof (rule impI)\n    assume \"(\\<not>.\\<not>.F) \\<in> S\"\n    show \"S \\<union> {F} \\<in> \\<C>\u207b\"  \n    proof (unfold clausura_cfinito_def)\n      show \"S \\<union> {F} \\<in> {S. \\<forall>S'\\<subseteq>S. finite S' \\<longrightarrow> S' \\<in> \\<C>}\"\n      proof (rule allI impI CollectI)+\n        fix S'\n        assume \"S' \\<subseteq> S \\<union> {F}\" and \"finite S'\"  \n        show \"S' \\<in> \\<C>\"\n        proof -          \n          have \"S' - {F} \\<union> {\\<not>.\\<not>.F}  \\<subseteq> S\"  \n            using `(\\<not>.\\<not>.F) \\<in> S` and  `S'\\<subseteq> S \\<union> {F}` by auto \n          moreover\n          have \"finite (S' - {F} \\<union> {\\<not>.\\<not>.F})\" using `finite S'` by auto\n          ultimately\n          have \"(S' - {F} \\<union> {\\<not>.\\<not>.F}) \\<in> \\<C>\" using hip  by simp\n          moreover\n          have \"(\\<not>.\\<not>.F) \\<in> (S' - {F} \\<union> {\\<not>.\\<not>.F})\" by simp\n          ultimately  \n          have \"(S' - {F} \\<union> {\\<not>.\\<not>.F})\\<union> {F} \\<in> \\<C>\" \n            using `consistenceP \\<C>` by (simp add: consistenceP_def)\n          moreover\n          have \"(S' - {F} \\<union> {\\<not>.\\<not>.F})\\<union> {F} = (S' \\<union> {\\<not>.\\<not>.F})\\<union> {F}\"\n            by auto\n          ultimately \n          have \"(S' \\<union> {\\<not>.\\<not>.F})\\<union> {F} \\<in> \\<C>\" by simp\n          moreover\n          have  \"S' \\<subseteq> (S' \\<union> {\\<not>.\\<not>.F})\\<union> {F}\" by auto\n          ultimately\n          show \"S'\\<in> \\<C>\" using `subconj_cerrada \\<C>` \n            by (simp add: subconj_cerrada_def)\n        qed\n      qed\n    qed\n  qed\nqed     \n(*>*)\ntext\\<open> \\<close>\nlemma condicaracterP4:\n  assumes \"consistenceP \\<C>\" \n  and \"subconj_cerrada \\<C>\" \n  and hip: \"\\<forall>S'\\<subseteq>S. finite S' \\<longrightarrow> S' \\<in> \\<C>\"\n  shows \"(\\<forall>F. ((FormulaAlfa F) \\<and> F \\<in> S) \\<longrightarrow> (S \\<union> {Comp1 F, Comp2 F}) \\<in> \\<C>\u207b)\"\n(*<*) \nproof (rule allI) \n  fix F \n  show \"((FormulaAlfa F) \\<and> F \\<in> S) \\<longrightarrow> S \\<union> {Comp1 F, Comp2 F} \\<in> \\<C>\u207b\"\n  proof (rule impI)\n    assume \"(FormulaAlfa F) \\<and> F \\<in> S\"\n    hence \"(FormulaAlfa F)\" and \"F \\<in> S\" by auto\n    show \"S \\<union> {Comp1 F, Comp2 F} \\<in> \\<C>\u207b\"  \n    proof (unfold clausura_cfinito_def)\n      show \"S \\<union> {Comp1 F, Comp2 F} \\<in> {S. \\<forall>S'\\<subseteq>S. finite S' \\<longrightarrow> S' \\<in> \\<C>}\"\n      proof (rule allI impI CollectI)+\n        fix S'\n        assume \"S' \\<subseteq> S \\<union> {Comp1 F, Comp2 F}\"  and  \"finite S'\"  \n        show \"S' \\<in> \\<C>\"\n        proof -          \n          have \"S' - {Comp1 F, Comp2 F} \\<union> {F}  \\<subseteq> S\"  \n            using `F \\<in> S` and  `S'\\<subseteq> S \\<union> {Comp1 F, Comp2 F}` by auto \n          moreover\n          have \"finite (S' - {Comp1 F, Comp2 F} \\<union> {F})\" \n            using `finite S'` by auto\n          ultimately\n          have \"(S' - {Comp1 F, Comp2 F} \\<union> {F}) \\<in> \\<C>\" using hip  by simp\n          moreover\n          have \"F \\<in> (S' - {Comp1 F, Comp2 F} \\<union> {F})\" by simp\n          ultimately  \n          have \"(S' - {Comp1 F, Comp2 F} \\<union> {F}) \\<union> {Comp1 F, Comp2 F} \\<in> \\<C>\" \n            using `consistenceP \\<C>` `FormulaAlfa F` \n            by (simp add: consistenceP_def)\n          moreover\n          have \"(S' - {Comp1 F, Comp2 F} \\<union> {F}) \\<union> {Comp1 F, Comp2 F} = \n                (S' \\<union> {F}) \\<union> {Comp1 F, Comp2 F}\"\n            by auto\n          ultimately \n          have \"(S' \\<union> {F}) \\<union> {Comp1 F, Comp2 F} \\<in> \\<C>\" by simp\n          moreover\n          have \"S' \\<subseteq> (S' \\<union> {F}) \\<union> {Comp1 F, Comp2 F}\" by auto\n          ultimately\n          show \"S'\\<in> \\<C>\" using `subconj_cerrada \\<C>` \n            by (simp add: subconj_cerrada_def)\n        qed\n      qed\n    qed\n  qed\nqed     \n(*>*)\ntext\\<open> \\<close>\nlemma condicaracterP5:\n  assumes \"consistenceP \\<C>\" \n  and \"subconj_cerrada \\<C>\" \n  and hip: \"\\<forall>S'\\<subseteq>S. finite S' \\<longrightarrow> S' \\<in> \\<C>\"\n  shows \"\\<forall>F. FormulaBeta F \\<and> F \\<in> S \\<longrightarrow> S \\<union> {Comp1 F} \\<in> \\<C>\u207b \\<or> S \\<union> {Comp2 F} \\<in> \\<C>\u207b\"\n(*<*)\nproof (rule allI) \n  fix F \n  show \"FormulaBeta F \\<and> F \\<in> S \\<longrightarrow> S \\<union> {Comp1 F} \\<in> \\<C>\u207b \\<or> S \\<union> {Comp2 F} \\<in> \\<C>\u207b\"\n  proof (rule impI)\n    assume \"(FormulaBeta F) \\<and> F \\<in> S\" \n    hence \"FormulaBeta F\" and \"F \\<in> S\" by auto \n    show \"S \\<union> {Comp1 F} \\<in> \\<C>\u207b \\<or> S \\<union> {Comp2 F} \\<in> \\<C>\u207b\"\n    proof (rule ccontr)\n      assume \"\\<not>(S \\<union> {Comp1 F} \\<in> \\<C>\u207b \\<or> S \\<union> {Comp2 F} \\<in> \\<C>\u207b)\"\n      hence \"S \\<union> {Comp1 F} \\<notin> \\<C>\u207b \\<and> S \\<union> {Comp2 F} \\<notin> \\<C>\u207b\" by simp    \n      hence 1: \"\\<exists> S1. (S1 \\<subseteq> S \\<union> {Comp1 F} \\<and> finite S1 \\<and> S1 \\<notin> \\<C>)\" \n        and 2: \"\\<exists> S2. (S2 \\<subseteq> S \\<union> {Comp2 F} \\<and> finite S2 \\<and> S2 \\<notin> \\<C>)\"\n        by (auto simp add: clausura_cfinito_def) \n      obtain S1  where S1: \"S1 \\<subseteq> S \\<union> {Comp1 F} \\<and> finite S1 \\<and> S1 \\<notin> \\<C>\" \n        using 1 by auto\n      obtain S2 where  S2: \"S2 \\<subseteq> S \\<union> {Comp2 F} \\<and> finite S2 \\<and> S2 \\<notin> \\<C>\" \n        using 2 by auto         \n      have \"(S1-{Comp1 F}) \\<union> (S2-{Comp2 F}) \\<union> {F} \\<subseteq> S\"\n        using `F \\<in> S` S1 S2 by auto\n      moreover\n      have \"finite ((S1-{Comp1 F}) \\<union> (S2-{Comp2 F}) \\<union> {F})\" \n        using S1 and S2 by simp\n      ultimately\n      have \"(S1-{Comp1 F}) \\<union> (S2-{Comp2 F}) \\<union> {F} \\<in> \\<C>\" using hip by simp\n      moreover\n      have \"F \\<in> (S1-{Comp1 F}) \\<union> (S2-{Comp2 F}) \\<union> {F}\" by simp    \n      ultimately \n      have 3: \"((S1-{Comp1 F}) \\<union> (S2-{Comp2 F}) \\<union> {F} \\<union> {Comp1 F}) \\<in> \\<C> \\<or> \n               ((S1-{Comp1 F}) \\<union> (S2-{Comp2 F}) \\<union> {F} \\<union> {Comp2 F}) \\<in> \\<C>\"\n        using `consistenceP \\<C>` `FormulaBeta F` \n        by (simp add: consistenceP_def)  \n      hence \"S1 \\<in> \\<C> \\<or> S2 \\<in> \\<C>\"\n      proof (cases)\n        assume \"((S1-{Comp1 F}) \\<union> (S2-{Comp2 F}) \\<union> {F} \\<union> {Comp1 F}) \\<in> \\<C>\"\n        moreover\n        have \"S1 \\<subseteq> ((S1-{Comp1 F}) \\<union> (S2-{Comp2 F}) \\<union> {F} \\<union> {Comp1 F})\" \n          by auto       \n        ultimately\n        have \"S1 \\<in> \\<C>\"  using `subconj_cerrada \\<C>` \n          by (simp add: subconj_cerrada_def) \n        thus ?thesis by simp\n      next \n        assume \"\\<not>((S1-{Comp1 F}) \\<union> (S2-{Comp2 F}) \\<union> {F} \\<union> {Comp1 F}) \\<in> \\<C>\"\n        hence \"((S1-{Comp1 F}) \\<union> (S2-{Comp2 F}) \\<union> {F} \\<union> {Comp2 F}) \\<in> \\<C>\" \n          using 3 by simp\n        moreover\n        have \"S2 \\<subseteq> ((S1-{Comp1 F}) \\<union> (S2-{Comp2 F}) \\<union> {F} \\<union> {Comp2 F})\" \n          by auto       \n        ultimately\n        have \"S2 \\<in> \\<C>\"  using `subconj_cerrada \\<C>` \n          by (simp add: subconj_cerrada_def) \n        thus ?thesis by simp\n      qed\n      thus False using S1 and S2 by simp\n    qed\n  qed\nqed\n(*>*)\n\ntext \\<open> \n  Por \u00faltimo, se demuestra que si @{text \"\\<C>\"} es una propiedad de\n  consistencia proposicional que es cerrada por subconjuntos entonces\n  @{text \"\\<C>\u207b\"} es de car\u00e1cter finito.  \n\\<close> \n\ntheorem cfinito_consistenceP:\n  assumes hip1: \"consistenceP \\<C>\" and hip2: \"subconj_cerrada \\<C>\" \n  shows \"consistenceP (\\<C>\u207b)\"\nproof - \n  { fix S\n    assume \"S \\<in> \\<C>\u207b\" \n    hence hip3: \"\\<forall>S'\\<subseteq>S. finite S' \\<longrightarrow> S' \\<in> \\<C>\" \n      by (simp add: clausura_cfinito_def) \n    have \"(\\<forall>P.  \\<not>(atom P \\<in> S \\<and> (\\<not>.atom P) \\<in> S)) \\<and>\n          FF \\<notin> S \\<and> (\\<not>.TT) \\<notin> S \\<and>\n          (\\<forall>F. (\\<not>.\\<not>.F) \\<in> S \\<longrightarrow> S \\<union> {F} \\<in> \\<C>\u207b) \\<and>\n          (\\<forall>F. ((FormulaAlfa F) \\<and> F \\<in> S) \\<longrightarrow> (S \\<union> {Comp1 F, Comp2 F}) \\<in> \\<C>\u207b) \\<and>\n          (\\<forall>F. ((FormulaBeta F) \\<and> F \\<in> S) \\<longrightarrow> \n               (S \\<union> {Comp1 F} \\<in> \\<C>\u207b) \\<or> (S \\<union> {Comp2 F} \\<in> \\<C>\u207b))\"\n      using \n        condicaracterP1[OF hip1 hip2 hip3]  condicaracterP2[OF hip1 hip2 hip3] \n        condicaracterP3[OF hip1 hip2 hip3]  condicaracterP4[OF hip1 hip2 hip3] \n        condicaracterP5[OF hip1 hip2 hip3]  by auto }\n  thus ?thesis by (simp add: consistenceP_def) \nqed\n\n(*<*)\nend\n(*>*)\n", "meta": {"author": "mayalarincon", "repo": "halltheorem", "sha": "6c694d6b154df4576b648810a5ec2f1814a0c99b", "save_path": "github-repos/isabelle/mayalarincon-halltheorem", "path": "github-repos/isabelle/mayalarincon-halltheorem/halltheorem-6c694d6b154df4576b648810a5ec2f1814a0c99b/ExistenciaModelosIngles/T6CFinitoIngles.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339797047029, "lm_q2_score": 0.8577681031721324, "lm_q1q2_score": 0.7202970229404889}}
{"text": "section \\<open> List Reversal -- Different Approaches \\<close>\n\ntheory List_Reversal\n  imports \"ITree_VCG.ITree_VCG\"\nbegin \n\nzstore state =\n  xs :: \"int list\"\n  ys :: \"int list\"\n  i :: nat\n\nprocedure reverse0 \"XS :: int list\" over state =\n\"ys := []; i := 0; \n while i < length XS inv ys = rev (take i XS) var length XS - i\n do \n    ys := XS!i # ys; \n    i := i + 1 \n od\"\n\nprocedure reverse1 \"XS :: int list\" over state =\n\"ys := [];\n for x in XS inv j. ys = rev (take j XS) do ys := x # ys od\"\n\nprocedure reverse2 \"XS :: int list\" over state =\n\"xs := XS; ys := [];\n while xs \\<noteq> [] \n inv ys = rev (take (length XS - length xs) XS) \\<and> xs = drop (length XS - length xs) XS\n var length xs\n do \n    ys := hd xs # ys;\n    xs := tl xs \n od\"\n\nprocedure reverse2a \"XS :: int list\" over state =\n\"xs := XS; ys := [];\n while xs \\<noteq> [] \n inv XS = rev ys @ xs var length xs\n do \n    ys := hd xs # ys;\n    xs := tl xs \n od\"\n\nprocedure reverse2b \"XS :: int list\" over state =\n\"xs := XS; ys := [];\n while xs \\<noteq> [] \n inv length XS = length xs + length ys \\<and> (\\<forall> i < length ys. XS!i = ys ! (length ys - Suc i)) \\<and> (\\<forall> i\\<in>{length ys..<length XS}. XS!i = xs ! (i - length ys))\n var length xs\n do \n    ys := hd xs # ys;\n    xs := tl xs \n od\"\n\nexecute \"reverse0 [1,2,3,4]\"\nexecute \"reverse1 [1,2,3,4]\"\nexecute \"reverse2 [1,2,3,4]\"\n\nlemma reverse0_correct: \"H[True] reverse0 XS [ys = rev XS]\"\n  by (vcg, simp add: take_Suc_conv_app_nth)\n\nlemma reverse1_correct: \"H[True] reverse1 XS [ys = rev XS]\"\n  by (vcg, simp add: take_Suc_conv_app_nth)\n\nlemma reverse2_correct: \"H[True] reverse2 XS [ys = rev XS]\"\nproof vcg\n  fix xs :: \"\\<int> list\"\n  assume \n    \"xs = drop (length XS - length xs) XS\" and\n    \"xs \\<noteq> []\"\n  thus \"hd xs # rev (take (length XS - length xs) XS) = rev (take (length XS - (length xs - Suc 0)) XS)\"\n    by (smt (verit, del_insts) Cons_nth_drop_Suc Suc_pred diff_le_self diff_less drop_all drop_rev hd_drop_conv_nth leD length_drop length_greater_0_conv length_rev not_less_eq rev_nth)\n    \nnext\n  fix xs :: \"\\<int> list\"\n  assume \n    \"xs = drop (length XS - length xs) XS\" and\n    \"xs \\<noteq> []\"\n  thus \"tl xs = drop (length XS - (length xs - Suc 0)) XS\"\n    by (metis (no_types, lifting) Cons_nth_drop_Suc One_nat_def Suc_diff_eq_diff_pred Suc_diff_le diff_le_self diff_less drop_Nil length_drop length_greater_0_conv list.exhaust_sel list.inject)    \nqed\n\nlemma reverse2a_correct: \"H[True] reverse2a XS [ys = rev XS]\"\n  by vcg\n\nlemma reverse2b_correct: \"H[True] reverse2b XS [ys = rev XS]\"\n  apply vcg\n  apply (metis add_diff_cancel_right atLeastLessThan_iff diff_self_eq_0 hd_conv_nth le_add_diff_inverse2 length_greater_0_conv less_Suc_eq less_Suc_eq_le less_add_same_cancel2 nth_Cons_0 nth_Cons_pos plus_1_eq_Suc)\n  apply (metis Suc_diff_Suc Suc_le_lessD list.exhaust_sel nth_Cons_Suc)\n  apply (simp add: list_eq_iff_nth_eq) \n  apply (simp add: rev_nth)\n  done\n\nend", "meta": {"author": "isabelle-utp", "repo": "interaction-trees", "sha": "90510d119364f534d2ab61daf2f274060f0a040e", "save_path": "github-repos/isabelle/isabelle-utp-interaction-trees", "path": "github-repos/isabelle/isabelle-utp-interaction-trees/interaction-trees-90510d119364f534d2ab61daf2f274060f0a040e/examples/List_Reversal.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681195338729, "lm_q2_score": 0.8397339616560072, "lm_q1q2_score": 0.7202970211984027}}
{"text": "(*  Title:      HOL/Isar_Examples/Cantor.thy\n    Author:     Makarius\n*)\n\nsection \\<open>Cantor's Theorem\\<close>\n\ntheory Cantor\n  imports Main\nbegin\n\nsubsection \\<open>Mathematical statement and proof\\<close>\n\ntext \\<open>\n  Cantor's Theorem states that there is no surjection from\n  a set to its powerset.  The proof works by diagonalization.  E.g.\\ see\n  \\<^item> \\<^url>\\<open>http://mathworld.wolfram.com/CantorDiagonalMethod.html\\<close>\n  \\<^item> \\<^url>\\<open>https://en.wikipedia.org/wiki/Cantor's_diagonal_argument\\<close>\n\\<close>\n\ntheorem Cantor: \"\\<nexists>f :: 'a \\<Rightarrow> 'a set. \\<forall>A. \\<exists>x. A = f x\"\nproof\n  assume \"\\<exists>f :: 'a \\<Rightarrow> 'a set. \\<forall>A. \\<exists>x. A = f x\"\n  then obtain f :: \"'a \\<Rightarrow> 'a set\" where *: \"\\<forall>A. \\<exists>x. A = f x\" ..\n  let ?notin = \"{x. x \\<notin> f x}\"\n  from * obtain a where mem: \"?notin = f a\" by blast\n  thus False\n  proof (cases \"a \\<in> ?notin\")\n    case True\n    then show ?thesis using mem by blast\n  next\n    case False\n    then show ?thesis using mem by blast\n  qed\nqed\n\nsubsection \\<open>Automated proofs\\<close>\n\ntext \\<open>\n  These automated proofs are much shorter, but lack information why and how it\n  works.\n\\<close>\n\ntheorem \"\\<nexists>f :: 'a \\<Rightarrow> 'a set. \\<forall>A. \\<exists>x. f x = A\"\n  by best\n\ntheorem \"\\<nexists>f :: 'a \\<Rightarrow> 'a set. \\<forall>A. \\<exists>x. f x = A\"\n  by force\n\ntheorem \"\\<nexists>f :: 'a \\<Rightarrow> 'a set. \\<forall>A. \\<exists>x. f x = A\"\n  by bestsimp\n\nsubsection \\<open>Elementary version in higher-order predicate logic\\<close>\n\ntext \\<open>\n  The subsequent formulation bypasses set notation of HOL; it uses elementary\n  \\<open>\\<lambda>\\<close>-calculus and predicate logic, with standard introduction and elimination\n  rules. This also shows that the proof does not require classical reasoning.\n\\<close>\n\nlemma iff_contradiction:\n  assumes *: \"\\<not> A \\<longleftrightarrow> A\"\n  shows False\nproof (rule notE)\n  show \"\\<not>A\"\n  proof\n    assume A\n    with * have \"\\<not>A\" ..\n    thus False using \\<open>A\\<close> ..\n  qed\n  with * show A ..\nqed\n  \ntheorem Cantor': \"\\<nexists>f :: 'a \\<Rightarrow> 'a \\<Rightarrow> bool. \\<forall>A. \\<exists>x. A = f x\"\nproof\n  assume \"\\<exists>f :: 'a \\<Rightarrow> 'a \\<Rightarrow> bool. \\<forall>A. \\<exists>x. A = f x\"\n  then obtain f :: \"'a \\<Rightarrow> 'a \\<Rightarrow> bool\" where *: \"\\<forall>A. \\<exists>x. A = f x\" ..\n  let ?notin_f = \"\\<lambda>x. \\<not>f x x\"\n  from * have \"\\<exists>x. ?notin_f = f x\" ..\n  then obtain a where \"?notin_f = f a\" ..\n  then have \"\\<not> f a a \\<longleftrightarrow> f a a\" by (rule arg_cong)\n  thus False by (rule iff_contradiction)\nqed\n\nsubsection \\<open>Classic Isabelle/HOL example\\<close>\n\ntext \\<open>\n  The following treatment of Cantor's Theorem follows the classic example from\n  the early 1990s, e.g.\\ see the file @{verbatim \"92/HOL/ex/set.ML\"} in\n  Isabelle92 or @{cite \\<open>\\S18.7\\<close> \"paulson-isa-book\"}. The old tactic scripts\n  synthesize key information of the proof by refinement of schematic goal\n  states. In contrast, the Isar proof needs to say explicitly what is proven.\n\n  \\<^bigskip>\n  Cantor's Theorem states that every set has more subsets than it has\n  elements. It has become a favourite basic example in pure higher-order logic\n  since it is so easily expressed:\n\n  @{text [display]\n  \\<open>\\<forall>f::\\<alpha> \\<Rightarrow> \\<alpha> \\<Rightarrow> bool. \\<exists>S::\\<alpha> \\<Rightarrow> bool. \\<forall>x::\\<alpha>. f x \\<noteq> S\\<close>}\n\n  Viewing types as sets, \\<open>\\<alpha> \\<Rightarrow> bool\\<close> represents the powerset of \\<open>\\<alpha>\\<close>. This\n  version of the theorem states that for every function from \\<open>\\<alpha>\\<close> to its\n  powerset, some subset is outside its range. The Isabelle/Isar proofs below\n  uses HOL's set theory, with the type \\<open>\\<alpha> set\\<close> and the operator \\<open>range :: (\\<alpha> \\<Rightarrow>\n  \\<beta>) \\<Rightarrow> \\<beta> set\\<close>.\n\\<close>\n\ntheorem \"\\<exists>S. S \\<notin> range (f :: 'a \\<Rightarrow> 'a set)\"\nproof\n  let ?S = \"{x. x \\<notin> f x}\"\n  show \"?S \\<notin> range f\"\n  proof\n    assume \"?S \\<in> range f\"\n    then obtain y where \"?S = f y\" ..\n    thus False\n    proof (rule equalityCE)\n      assume c1: \"y \\<in> f y\"\n      assume \"y \\<in> ?S\"\n      hence \"y \\<notin> f y\" ..\n      with c1 show False by contradiction\n    next\n      assume c2: \"y \\<notin> ?S\"\n      assume \"y \\<notin> f y\"\n      hence \"y \\<in> ?S\" ..\n      with c2 show False by contradiction\n    qed\n  qed\nqed\n\n\ntext \\<open>\n  How much creativity is required? As it happens, Isabelle can prove this\n  theorem automatically using best-first search. Depth-first search would\n  diverge, but best-first search successfully navigates through the large\n  search space. The context of Isabelle's classical prover contains rules for\n  the relevant constructs of HOL's set theory.\n\\<close>\n\ntheorem \"\\<exists>S. S \\<notin> range (f :: 'a \\<Rightarrow> 'a set)\"\n  by best\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/Isar_Examples/Cantor.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681013541613, "lm_q2_score": 0.8397339756938818, "lm_q1q2_score": 0.7202970179735223}}
{"text": "(* Title:  Rtrancl_On.thy\n   Author: Lars Noschinski, TU M\u00fcnchen\n   Author: Ren\u00e9 Neumann, TU M\u00fcnchen\n*)\n\ntheory Rtrancl_On\nimports Main\nbegin\n\nsection {* Reflexive-Transitive Closure on a Domain *}\n\ntext {*\n  In this section we introduce a variant of the reflexive-transitive closure\n  of a relation which is useful to formalize the reachability relation on\n  digraphs.\n*}\n\ninductive_set\n  rtrancl_on :: \"'a set \\<Rightarrow> 'a rel \\<Rightarrow> 'a rel\"\n  for F :: \"'a set\" and r :: \"'a rel\"\nwhere\n    rtrancl_on_refl [intro!, Pure.intro!, simp]: \"a \\<in> F \\<Longrightarrow> (a, a) \\<in> rtrancl_on F r\"\n  | rtrancl_on_into_rtrancl_on [Pure.intro]:\n      \"(a, b) \\<in> rtrancl_on F r  \\<Longrightarrow> (b, c) \\<in> r \\<Longrightarrow> c \\<in> F\n      \\<Longrightarrow> (a, c) \\<in> rtrancl_on F r\"\n\ndefinition symcl :: \"'a rel \\<Rightarrow> 'a rel\" (\"(_\\<^sup>s)\" [1000] 999) where\n  \"symcl R = R \\<union> (\\<lambda>(a,b). (b,a)) ` R\"\n\nlemma in_rtrancl_on_in_F:\n  assumes \"(a,b) \\<in> rtrancl_on F r\" shows \"a \\<in> F\" \"b \\<in> F\"\n  using assms by induct auto\n\nlemma rtrancl_on_induct[consumes 1, case_names base step, induct set: rtrancl_on]:\n  assumes \"(a, b) \\<in> rtrancl_on F r\"\n    and \"a \\<in> F \\<Longrightarrow> P a\"\n        \"\\<And>y z. \\<lbrakk>(a, y) \\<in> rtrancl_on F r; (y,z) \\<in> r; y \\<in> F; z \\<in> F; P y\\<rbrakk> \\<Longrightarrow> P z\"\n  shows \"P b\"\n  using assms by (induct a b) (auto dest: in_rtrancl_on_in_F)\n\nlemma rtrancl_on_trans:\n  assumes \"(a,b) \\<in> rtrancl_on F r\" \"(b,c) \\<in> rtrancl_on F r\" shows \"(a,c) \\<in> rtrancl_on F r\"\n  using assms(2,1)\n  by induct (auto intro: rtrancl_on_into_rtrancl_on)\n\nlemma converse_rtrancl_on_into_rtrancl_on:\n  assumes \"(a,b) \\<in> r\" \"(b, c) \\<in> rtrancl_on F r\" \"a \\<in> F\"\n  shows \"(a, c) \\<in> rtrancl_on F r\"\nproof -\n  have \"b \\<in> F\" using \\<open>(b,c) \\<in> _\\<close> by (rule in_rtrancl_on_in_F)\n  show ?thesis\n    apply (rule rtrancl_on_trans)\n    apply (rule rtrancl_on_into_rtrancl_on)\n    apply (rule rtrancl_on_refl)\n    by fact+\nqed\n\nlemma rtrancl_on_converseI:\n  assumes \"(y, x) \\<in> rtrancl_on F r\" shows \"(x, y) \\<in> rtrancl_on F (r\\<inverse>)\"\n  using assms\nproof induct\n  case (step a b)\n  then have \"(b,b) \\<in> rtrancl_on F (r\\<inverse>)\" \"(b,a) \\<in> r\\<inverse>\" by auto\n  then show ?case using step\n    by (metis rtrancl_on_trans rtrancl_on_into_rtrancl_on)\nqed auto\n\ntheorem rtrancl_on_converseD:\n  assumes \"(y, x) \\<in> rtrancl_on F (r\\<inverse>)\" shows \"(x, y) \\<in> rtrancl_on F r\"\n  using assms by - (drule rtrancl_on_converseI, simp)\n\nlemma converse_rtrancl_on_induct[consumes 1, case_names base step, induct set: rtrancl_on]:\n  assumes major: \"(a, b) \\<in> rtrancl_on F r\"\n    and cases: \"b \\<in> F \\<Longrightarrow> P b\"\n       \"\\<And>x y. \\<lbrakk>(x,y) \\<in> r; (y,b) \\<in> rtrancl_on F r; x \\<in> F; y \\<in> F; P y\\<rbrakk> \\<Longrightarrow> P x\"\n  shows \"P a\"\n  using rtrancl_on_converseI[OF major] cases\n  by induct (auto intro: rtrancl_on_converseD)\n\nlemma converse_rtrancl_on_cases:\n  assumes \"(a, b) \\<in> rtrancl_on F r\"\n  obtains (base) \"a = b\" \"b \\<in> F\"\n    | (step) c where \"(a,c) \\<in> r\" \"(c,b) \\<in> rtrancl_on F r\"\n  using assms by induct auto\n\nlemma rtrancl_on_sym:\n  assumes \"sym r\" shows \"sym (rtrancl_on F r)\"\nusing assms by (auto simp: sym_conv_converse_eq intro: symI dest: rtrancl_on_converseI)\n\nlemma rtrancl_on_mono:\n  assumes \"s \\<subseteq> r\" \"F \\<subseteq> G\" \"(a,b) \\<in> rtrancl_on F s\" shows \"(a,b) \\<in> rtrancl_on G r\"\n  using assms(3,1,2)\nproof induct\n  case (step x y) show ?case\n    using step assms by (intro converse_rtrancl_on_into_rtrancl_on[OF _ step(5)]) auto\nqed auto\n\nlemma rtrancl_consistent_rtrancl_on:\n  assumes \"(a,b) \\<in> r\\<^sup>*\"\n  and \"a \\<in> F\" \"b \\<in> F\"\n  and consistent: \"\\<And>a b. \\<lbrakk> a \\<in> F; (a,b) \\<in> r \\<rbrakk> \\<Longrightarrow> b \\<in> F\"\n  shows \"(a,b) \\<in> rtrancl_on F r\"\n  using assms(1-3)\nproof (induction rule: converse_rtrancl_induct)\n  case (step y z) then have \"z \\<in> F\" by (rule_tac consistent) simp\n  with step have \"(z,b) \\<in> rtrancl_on F r\" by simp\n  with step.prems `(y,z) \\<in> r` `z \\<in> F` show ?case\n    using converse_rtrancl_on_into_rtrancl_on\n    by metis\nqed simp\n\nlemma rtrancl_on_rtranclI:\n  \"(a,b) \\<in> rtrancl_on F r \\<Longrightarrow> (a,b) \\<in> r\\<^sup>*\"\n  by (induct rule: rtrancl_on_induct) simp_all\n\nlemma rtrancl_on_sub_rtrancl:\n  \"rtrancl_on F r \\<subseteq> r^*\"\n  using rtrancl_on_rtranclI\n  by auto\n\n\n\nend\n", "meta": {"author": "z5146542", "repo": "TOR", "sha": "9a82d491288a6d013e0764f68e602a63e48f92cf", "save_path": "github-repos/isabelle/z5146542-TOR", "path": "github-repos/isabelle/z5146542-TOR/TOR-9a82d491288a6d013e0764f68e602a63e48f92cf/checker-verification/Graph_Theory/Rtrancl_On.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8397339676722393, "lm_q2_score": 0.8577681031721325, "lm_q1q2_score": 0.7202970126194255}}
{"text": "(* Title: Geometric.thy\n   Author: Andreas Lochbihler, ETH Zurich *)\n\nsubsection \\<open>The geometric distribution\\<close>\n\ntheory Geometric imports\n  Bernoulli\n  While_SPMF\nbegin\n\ntext \\<open>\n  We define the geometric distribution as a least fixpoint, which is more elegant than\n  as a loop. To prove probabilistic termination, we prove it equivalent to a loop and use\n  the proof rules for probabilistic termination.\n\\<close>\n\ncontext notes [[function_internals]] begin\npartial_function (spmf) geometric_spmf :: \"real \\<Rightarrow> nat spmf\" where\n  \"geometric_spmf p = do {\n     b \\<leftarrow> bernoulli p;\n     if b then return_spmf 0 else map_spmf ((+) 1) (geometric_spmf p)\n  }\"\nend\n\nlemma geometric_spmf_fixp_induct [case_names adm bottom step]:\n  assumes \"spmf.admissible P\"\n    and \"P (\\<lambda>geometric_spmf. return_pmf None)\"\n    and \"\\<And>geometric_spmf'. P geometric_spmf' \\<Longrightarrow> P (\\<lambda>p. bernoulli p \\<bind> (\\<lambda>b. if b then return_spmf 0 else map_spmf ((+) 1) (geometric_spmf' p)))\"\n  shows \"P geometric_spmf\"\n  using assms by(rule geometric_spmf.fixp_induct)\n\nlemma spmf_geometric_nonpos: \"p \\<le> 0 \\<Longrightarrow> geometric_spmf p = return_pmf None\"\n  by(induction rule: geometric_spmf_fixp_induct) simp_all\n\nlemma spmf_geometric_ge_1: \"1 \\<le> p \\<Longrightarrow> geometric_spmf p = return_spmf 0\"\n  by(simp add: geometric_spmf.simps)\n\ncontext\n  fixes p :: real \n  and body :: \"bool \\<times> nat \\<Rightarrow> (bool \\<times> nat) spmf\"\n  defines [simp]: \"body \\<equiv> \\<lambda>(b, x). map_spmf (\\<lambda>b'. (\\<not> b', x + (if b' then 0 else 1))) (bernoulli p)\"\nbegin\n\ninterpretation loop_spmf fst body \n  rewrites \"body \\<equiv> \\<lambda>(b, x). map_spmf (\\<lambda>b'. (\\<not> b', x + (if b' then 0 else 1))) (bernoulli p)\" \n  by(fact body_def)\n\nlemma geometric_spmf_conv_while:\n  shows \"geometric_spmf p = map_spmf snd (while (True, 0))\"\nproof -\n  have \"map_spmf ((+) x) (geometric_spmf p) = map_spmf snd (while (True, x))\" (is \"?lhs = ?rhs\") for x\n  proof(rule spmf.leq_antisym)\n    show \"ord_spmf (=) ?lhs ?rhs\"\n    proof(induction arbitrary: x rule: geometric_spmf_fixp_induct)\n      case adm show ?case by simp\n      case bottom show ?case by simp\n      case (step geometric')\n      show ?case using step.IH[of \"Suc x\"]\n        apply(rewrite while.simps)\n        apply(clarsimp simp add: map_spmf_bind_spmf bind_map_spmf intro!: ord_spmf_bind_reflI)\n        apply(rewrite while.simps)\n        apply(clarsimp simp add: spmf.map_comp o_def)\n        done\n    qed\n    have \"ord_spmf (=) ?rhs ?lhs\"\n      and \"ord_spmf (=) (map_spmf snd (while (False, x))) (return_spmf x)\"\n    proof(induction arbitrary: x and x rule: while_fixp_induct)\n      case adm show ?case by simp\n      case bottom case 1 show ?case by simp\n      case bottom case 2 show ?case by simp\n    next\n      case (step while')\n      case 1 show ?case using step.IH(1)[of \"Suc x\"] step.IH(2)[of x]\n        by(rewrite geometric_spmf.simps)(clarsimp simp add: map_spmf_bind_spmf bind_map_spmf spmf.map_comp o_def intro!: ord_spmf_bind_reflI)\n      case 2 show ?case by simp\n    qed\n    then show \"ord_spmf (=) ?rhs ?lhs\" by -\n  qed\n  from this[of 0] show ?thesis by(simp cong: map_spmf_cong)\nqed\n\nlemma lossless_geometric [simp]: \"lossless_spmf (geometric_spmf p) \\<longleftrightarrow> p > 0\"\nproof(cases \"0 < p \\<and> p < 1\")\n  case True\n  let ?body = \"\\<lambda>(b, x :: nat). map_spmf (\\<lambda>b'. (\\<not> b', x + (if b' then 0 else 1))) (bernoulli p)\"\n  have \"lossless_spmf (while (True, 0))\"\n  proof(rule termination_0_1_immediate)\n    have \"{x. x} = {True}\" by auto\n    then show \"p \\<le> spmf (map_spmf fst (?body s)) False\" for s :: \"bool \\<times> nat\" using True\n      by(cases s)(simp add: spmf.map_comp o_def spmf_map vimage_def spmf_conv_measure_spmf[symmetric])\n    show \"0 < p\" using True by simp\n  qed(clarsimp)\n  with True show ?thesis by(simp add: geometric_spmf_conv_while)\nqed(auto simp add: spmf_geometric_nonpos spmf_geometric_ge_1)\n\nend\n\nlemma spmf_geometric:\n  assumes p: \"0 < p\" \"p < 1\"\n  shows \"spmf (geometric_spmf p) n = (1 - p) ^ n * p\" (is \"?lhs n = ?rhs n\")\nproof(rule spmf_ub_tight)\n  fix n\n  have \"ennreal (?lhs n) \\<le> ennreal (?rhs n)\" using p\n  proof(induction arbitrary: n rule: geometric_spmf_fixp_induct)\n    case adm show ?case by(rule cont_intro)+\n    case bottom show ?case by simp\n    case (step geometric_spmf')\n    then show ?case\n      by(cases n)(simp_all add: ennreal_spmf_bind nn_integral_measure_spmf UNIV_bool nn_integral_count_space_finite ennreal_mult spmf_map vimage_def mult.assoc spmf_conv_measure_spmf[symmetric] mult_mono split: split_indicator)\n  qed\n  then show \"?lhs n \\<le> ?rhs n\" using p by(simp)\nnext\n  have \"(\\<Sum>i. ennreal (p * (1 - p) ^ i)) = ennreal (p * (1 / (1 - (1 - p))))\" using p\n    by (intro suminf_ennreal_eq sums_mult geometric_sums) auto\n  then show \"(\\<Sum>\\<^sup>+ x. ennreal ((1 - p) ^ x * p)) = weight_spmf (geometric_spmf p)\"\n    using lossless_geometric[of p] p unfolding lossless_spmf_def\n    by (simp add: nn_integral_count_space_nat field_simps)\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_While/Geometric.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339676722393, "lm_q2_score": 0.8577681013541611, "lm_q1q2_score": 0.7202970110928132}}
{"text": "theory Cartan\nimports \"HOL-Complex_Analysis.Complex_Analysis\"\n\nbegin\n\nsection\\<open>First Cartan Theorem\\<close>\n\ntext\\<open>Ported from HOL Light. See\n      Gianni Ciolli, Graziano Gentili, Marco Maggesi.\n      A Certified Proof of the Cartan Fixed Point Theorems.\n      J Automated Reasoning (2011) 47:319--336    DOI 10.1007/s10817-010-9198-6\\<close>\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    apply (rule complex_derivative_transform_within_open [where s=S])\n    apply (rule assms holomorphic_on_compose_gen holomorphic_intros)+\n    apply simp\n    done\n  also have \"... = 1\"\n    using higher_deriv_id [of 1] by simp\n  finally show ?thesis .\nqed\n\nlemma Cauchy_higher_deriv_bound:\n    assumes holf: \"f holomorphic_on (ball z r)\"\n        and contf: \"continuous_on (cball z r) f\"\n        and \"0 < r\" and \"0 < n\"\n        and fin : \"\\<And>w. w \\<in> ball z r \\<Longrightarrow> f w \\<in> ball y B0\"\n      shows \"norm ((deriv ^^ n) f z) \\<le> (fact n) * B0 / r^n\"\nproof -\n  have \"0 < B0\" using \\<open>0 < r\\<close> fin [of z]\n    by (metis ball_eq_empty ex_in_conv fin not_less)\n  have le_B0: \"\\<And>w. cmod (w - z) \\<le> r \\<Longrightarrow> cmod (f w - y) \\<le> B0\"\n    apply (rule continuous_on_closure_norm_le [of \"ball z r\" \"\\<lambda>w. f w - y\"])\n    apply (auto simp: \\<open>0 < r\\<close>  dist_norm norm_minus_commute)\n    apply (rule continuous_intros contf)+\n    using fin apply (simp add: dist_commute dist_norm less_eq_real_def)\n    done\n  have \"(deriv ^^ n) f z = (deriv ^^ n) (\\<lambda>w. f w) z - (deriv ^^ n) (\\<lambda>w. y) z\"\n    using \\<open>0 < n\\<close> by simp\n  also have \"... = (deriv ^^ n) (\\<lambda>w. f w - y) z\"\n    by (rule higher_deriv_diff [OF holf, symmetric]) (auto simp: \\<open>0 < r\\<close> holomorphic_on_const)\n  finally have \"(deriv ^^ n) f z = (deriv ^^ n) (\\<lambda>w. f w - y) z\" .\n  have contf': \"continuous_on (cball z r) (\\<lambda>u. f u - y)\"\n    by (rule contf continuous_intros)+\n  have holf': \"(\\<lambda>u. (f u - y)) holomorphic_on (ball z r)\"\n    by (simp add: holf holomorphic_on_diff holomorphic_on_const)\n  define a where \"a = (2 * pi)/(fact n)\"\n  have \"0 < a\"  by (simp add: a_def)\n  have \"B0/r^(Suc n)*2 * pi * r = a*((fact n)*B0/r^n)\"\n    using \\<open>0 < r\\<close> by (simp add: a_def divide_simps)\n  have der_dif: \"(deriv ^^ n) (\\<lambda>w. f w - y) z = (deriv ^^ n) f z\"\n    using \\<open>0 < r\\<close> \\<open>0 < n\\<close>\n    by (auto simp: higher_deriv_diff [OF holf holomorphic_on_const])\n  have \"norm ((2 * of_real pi * \\<i>)/(fact n) * (deriv ^^ n) (\\<lambda>w. f w - y) z)\n        \\<le> (B0/r^(Suc n)) * (2 * pi * r)\"\n    apply (rule has_contour_integral_bound_circlepath [of \"(\\<lambda>u. (f u - y)/(u - z)^(Suc n))\" _ z])\n    using Cauchy_has_contour_integral_higher_derivative_circlepath [OF contf' holf']\n    using \\<open>0 < B0\\<close> \\<open>0 < r\\<close>\n    apply (auto simp: norm_divide norm_mult norm_power divide_simps le_B0)\n    done\n  then show ?thesis\n    using \\<open>0 < r\\<close>\n    by (auto simp: norm_divide norm_mult norm_power field_simps der_dif le_B0)\nqed\n\nlemma higher_deriv_comp_lemma:\n    assumes s: \"open s\" and holf: \"f holomorphic_on s\"\n        and \"z \\<in> s\"\n        and t: \"open t\" and holg: \"g holomorphic_on t\"\n        and fst: \"f ` s \\<subseteq> t\"\n        and n: \"i \\<le> n\"\n        and dfz: \"deriv f z = 1\" and zero: \"\\<And>i. \\<lbrakk>1 < i; i \\<le> n\\<rbrakk> \\<Longrightarrow> (deriv ^^ i) f z = 0\"\n      shows \"(deriv ^^ i) (g o f) z = (deriv ^^ i) g (f z)\"\nusing n holg\nproof (induction i arbitrary: g)\n  case 0 then show ?case by simp\nnext\n  case (Suc i)\n  have \"g \\<circ> f holomorphic_on s\" using \"Suc.prems\" holf\n    using fst  by (simp add: holomorphic_on_compose_gen image_subset_iff)\n  then have 1: \"deriv (g \\<circ> f) holomorphic_on s\"\n    by (simp add: holomorphic_deriv s)\n  have dg: \"deriv g holomorphic_on t\"\n    using Suc.prems by (simp add: Suc.prems(2) holomorphic_deriv t)\n  then have \"deriv g holomorphic_on f ` s\"\n    using fst  by (simp add: holomorphic_on_subset image_subset_iff)\n  then have dgf: \"(deriv g o f) holomorphic_on s\"\n    by (simp add: holf holomorphic_on_compose)\n  then have 2: \"(\\<lambda>w. (deriv g o f) w * deriv f w) holomorphic_on s\"\n    by (blast intro: holomorphic_intros holomorphic_on_compose holf s)\n  have \"(deriv ^^ i) (deriv (g o f)) z = (deriv ^^ i) (\\<lambda>w. deriv g (f w) * deriv f w) z\"\n    apply (rule higher_deriv_transform_within_open [OF 1 2 [unfolded o_def] s \\<open>z \\<in> s\\<close>])\n    apply (rule deriv_chain)\n    using holf Suc.prems fst apply (auto simp: holomorphic_on_imp_differentiable_at s t)\n    done\n  also have \"... = (\\<Sum>j=0..i. of_nat(i choose j) * (deriv ^^ j) (\\<lambda>w. deriv g (f w)) z * (deriv ^^ (i - j)) (deriv f) z)\"\n    apply (rule higher_deriv_mult [OF dgf [unfolded o_def] _ s \\<open>z \\<in> s\\<close>])\n    by (simp add: holf holomorphic_deriv s)\n  also have \"... = (\\<Sum>j=i..i. of_nat(i choose j) * (deriv ^^ j) (\\<lambda>w. deriv g (f w)) z * (deriv ^^ Suc (i - j)) f z)\"\n  proof -\n    have *: \"(deriv ^^ j) (\\<lambda>w. deriv g (f w)) z = 0\"  if \"j < i\" and nz: \"(deriv ^^ (i - j)) (deriv f) z \\<noteq> 0\" for j\n    proof -\n      have \"1 < Suc (i - j)\" \"Suc (i - j) \\<le> n\"\n        using \\<open>j < i\\<close> \\<open>Suc i \\<le> n\\<close> by auto\n      then show ?thesis  by (metis comp_def funpow.simps(2) funpow_swap1 zero nz)\n    qed\n    then show ?thesis\n      apply (simp only: funpow_Suc_right o_def)\n      apply (rule comm_monoid_add_class.sum.mono_neutral_right, auto)\n      done\n  qed\n  also have \"... = (deriv ^^ i) (deriv g) (f z)\"\n    using Suc.IH [OF _ dg] Suc.prems by (simp add: dfz)\n  finally show ?case\n    by (simp only: funpow_Suc_right o_def)\nqed\n\n\nlemma higher_deriv_comp_iter_lemma:\n    assumes s: \"open s\" and holf: \"f holomorphic_on s\"\n        and fss: \"f ` s \\<subseteq> s\"\n        and \"z \\<in> s\" and [simp]: \"f z = z\"\n        and n: \"i \\<le> n\"\n        and dfz: \"deriv f z = 1\" and zero: \"\\<And>i. \\<lbrakk>1 < i; i \\<le> n\\<rbrakk> \\<Longrightarrow> (deriv ^^ i) f z = 0\"\n      shows \"(deriv ^^ i) (f^^m) z = (deriv ^^ i) f z\"\nproof -\n  have holfm: \"(f^^m) holomorphic_on s\" for m\n    apply (induction m, simp add: holomorphic_on_ident)\n    apply (simp only: funpow_Suc_right holomorphic_on_compose_gen [OF holf _ fss])\n    done\n  show ?thesis using n\n  proof (induction m)\n    case 0 with dfz show ?case\n      by (auto simp: zero)\n  next\n    case (Suc m)\n    have \"(deriv ^^ i) (f ^^ m \\<circ> f) z = (deriv ^^ i) (f ^^ m) (f z)\"\n      using Suc.prems holfm \\<open>z \\<in> s\\<close> dfz fss higher_deriv_comp_lemma holf s zero by blast\n    also have \"... = (deriv ^^ i) f z\"\n      by (simp add: Suc)\n    finally show ?case\n      by (simp only: funpow_Suc_right)\n  qed\nqed\n\nlemma higher_deriv_iter_top_lemma:\n    assumes s: \"open s\" and holf: \"f holomorphic_on s\"\n        and fss: \"f ` s \\<subseteq> s\"\n        and \"z \\<in> s\" and [simp]: \"f z = z\"\n        and dfz [simp]: \"deriv f z = 1\"\n        and n: \"1 < n\" \"\\<And>i. \\<lbrakk>1 < i; i < n\\<rbrakk> \\<Longrightarrow> (deriv ^^ i) f z = 0\"\n      shows \"(deriv ^^ n) (f ^^ m) z = m * (deriv ^^ n) f z\"\nusing n\nproof (induction n arbitrary: m)\n  case 0 then show ?case by simp\nnext\n  case (Suc n)\n  have [simp]: \"(f^^m) z = z\" for m\n    by (induction m) auto\n  have fms_sb: \"(f^^m) ` s \\<subseteq> s\" for m\n    apply (induction m)\n    using fss\n    apply force+\n    done\n  have holfm: \"(f^^m) holomorphic_on s\" for m\n    apply (induction m, simp add: holomorphic_on_ident)\n    apply (simp only: funpow_Suc_right holomorphic_on_compose_gen [OF holf _ fss])\n    done\n  then have holdfm: \"deriv (f ^^ m) holomorphic_on s\" for m\n    by (simp add: holomorphic_deriv s)\n  have holdffm: \"(\\<lambda>z. deriv f ((f ^^ m) z)) holomorphic_on s\" for m\n    apply (rule holomorphic_on_compose_gen [where g=\"deriv f\" and t=s, unfolded o_def])\n    using s \\<open>z \\<in> s\\<close> holfm holf fms_sb by (auto intro: holomorphic_intros)\n  have f_cd_w: \"\\<And>w. w \\<in> s \\<Longrightarrow> f field_differentiable at w\"\n    using holf holomorphic_on_imp_differentiable_at s by blast\n  have f_cd_mw: \"\\<And>m w. w \\<in> s \\<Longrightarrow> (f^^m) field_differentiable at w\"\n    using holfm holomorphic_on_imp_differentiable_at s by auto\n  have der_fm [simp]: \"deriv (f ^^ m) z = 1\" for m\n    apply (induction m, simp add: deriv_ident)\n    apply (subst funpow_Suc_right)\n    apply (subst deriv_chain)\n    using \\<open>z \\<in> s\\<close> holfm holomorphic_on_imp_differentiable_at s f_cd_w apply auto\n    done\n  note Suc(3) [simp]\n  note n_Suc = Suc\n  show ?case\n  proof (induction m)\n    case 0 with n_Suc show ?case\n      by (metis Zero_not_Suc funpow_simps_right(1) higher_deriv_id lambda_zero nat_neq_iff of_nat_0)\n  next\n    case (Suc m)\n    have deriv_nffm: \"(deriv ^^ n) (deriv f o (f ^^ m)) z = (deriv ^^ n) (deriv f) ((f ^^ m) z)\"\n      apply (rule higher_deriv_comp_lemma [OF s holfm \\<open>z \\<in> s\\<close> s _ fms_sb order_refl])\n      using \\<open>z \\<in> s\\<close> fss higher_deriv_comp_iter_lemma holf holf holomorphic_deriv s\n        apply auto\n      done\n    have \"deriv (f ^^ m \\<circ> f) holomorphic_on s\"\n      by (metis funpow_Suc_right holdfm)\n    moreover have \"(\\<lambda>w. deriv f ((f ^^ m) w) * deriv (f ^^ m) w) holomorphic_on s\"\n      by (rule holomorphic_on_mult [OF holdffm holdfm])\n    ultimately have \"(deriv ^^ n) (deriv (f ^^ m \\<circ> f)) z = (deriv ^^ n) (\\<lambda>w. deriv f ((f ^^ m) w) * deriv (f ^^ m) w) z\"\n      apply (rule higher_deriv_transform_within_open [OF _ _ s \\<open>z \\<in> s\\<close>])\n      by (metis comp_funpow deriv_chain f_cd_mw f_cd_w fms_sb funpow_swap1 image_subset_iff o_id)\n    also have \"... =\n          (\\<Sum>i=0..n. of_nat(n choose i) * (deriv ^^ i) (\\<lambda>w. deriv f ((f ^^ m) w)) z *\n                     (deriv ^^ (n - i)) (deriv (f ^^ m)) z)\"\n      by (rule higher_deriv_mult [OF holdffm holdfm s \\<open>z \\<in> s\\<close>])\n    also have \"... = (\\<Sum>i \\<in> {0,n}. of_nat(n choose i) * (deriv ^^ i) (\\<lambda>w. deriv f ((f ^^ m) w)) z *\n                     (deriv ^^ (n - i)) (deriv (f ^^ m)) z)\"\n    proof -\n      have *: \"(deriv ^^ i) (\\<lambda>w. deriv f ((f ^^ m) w)) z = 0\"  if \"i \\<le> n\" \"0 < i\" \"i \\<noteq> n\" and nz: \"(deriv ^^ (n - i)) (deriv (f ^^ m)) z \\<noteq> 0\" for i\n      proof -\n        have less: \"1 < Suc (n-i)\" and le: \"Suc (n-i) \\<le> n\"\n          using that by auto\n        have \"(deriv ^^ (Suc (n - i))) (f ^^ m) z = (deriv ^^(Suc (n - i))) f z\"\n          apply (rule higher_deriv_comp_iter_lemma [OF s holf fss \\<open>z \\<in> s\\<close> \\<open>f z = z\\<close> le dfz])\n          by simp\n        also have \"... = 0\"\n          using n_Suc(3) less le le_imp_less_Suc by blast\n        finally have \"(deriv ^^ (Suc (n - i))) (f ^^ m) z = 0\" .\n        then show ?thesis by (simp add: funpow_swap1 nz)\n      qed\n      show ?thesis\n        by (rule comm_monoid_add_class.sum.mono_neutral_right) (auto simp: *)\n    qed\n    also have \"... = of_nat (Suc m) * (deriv ^^ n) (deriv f) z\"\n      apply (subst Groups_Big.comm_monoid_add_class.sum.insert)\n      apply (simp_all add: deriv_nffm [unfolded o_def] of_nat_Suc [of 0] del: of_nat_Suc)\n      using n_Suc(2) Suc\n      apply (auto simp del: funpow.simps simp: algebra_simps funpow_simps_right)\n      done\n    finally have \"(deriv ^^ n) (deriv (f ^^ m \\<circ> f)) z = of_nat (Suc m) * (deriv ^^ n) (deriv f) z\" .\n    then show ?case\n      apply (simp only: funpow_Suc_right)\n      apply (simp add: o_def del: of_nat_Suc)\n      done\n  qed\nqed\n\n\ntext\\<open>Should be proved for n-dimensional vectors of complex numbers\\<close>\ntheorem first_Cartan_dim_1:\n    assumes holf: \"f holomorphic_on s\"\n        and \"open s\" \"connected s\" \"bounded s\"\n        and fss: \"f ` s \\<subseteq> s\"\n        and \"z \\<in> s\" and [simp]: \"f z = z\"\n        and dfz [simp]: \"deriv f z = 1\"\n        and \"w \\<in> s\"\n      shows \"f w = w\"\nproof -\n  obtain c where \"0 < c\" and c: \"s \\<subseteq> ball z c\"\n    using \\<open>bounded s\\<close> bounded_subset_ballD by blast\n  obtain r where \"0 < r\" and r: \"cball z r \\<subseteq> s\"\n    using \\<open>z \\<in> s\\<close> open_contains_cball \\<open>open s\\<close> by blast\n  then have bzr: \"ball z r \\<subseteq> s\" using ball_subset_cball by blast\n  have fms_sb: \"(f^^m) ` s \\<subseteq> s\" for m\n    apply (induction m)\n    using fss apply force+\n    done\n  have holfm: \"(f^^m) holomorphic_on s\" for m\n    apply (induction m, simp add: holomorphic_on_ident)\n    apply (simp only: funpow_Suc_right holomorphic_on_compose_gen [OF holf _ fss])\n    done\n  have *: \"(deriv ^^ n) f z = (deriv ^^ n) id z\" for n\n  proof -\n    consider \"n = 0\" | \"n = 1\" | \"1 < n\" by arith\n    then show ?thesis\n    proof cases\n      assume \"n = 0\" then show ?thesis by force\n    next\n      assume \"n = 1\" then show ?thesis by force\n    next\n      assume n1: \"n > 1\"\n      then have \"(deriv ^^ n) f z = 0\"\n      proof (induction n rule: less_induct)\n        case (less n)\n        have le: \"real m * cmod ((deriv ^^ n) f z) \\<le> fact n * c / r ^ n\" if \"m\\<noteq>0\" for m\n        proof -\n          have holfm': \"(f ^^ m) holomorphic_on ball z r\"\n            using holfm bzr holomorphic_on_subset by blast\n          then have contfm': \"continuous_on (cball z r) (f ^^ m)\"\n            using \\<open>cball z r \\<subseteq> s\\<close> holfm holomorphic_on_imp_continuous_on holomorphic_on_subset by blast\n          have \"real m * cmod ((deriv ^^ n) f z) = cmod (real m * (deriv ^^ n) f z)\"\n            by (simp add: norm_mult)\n          also have \"... = cmod ((deriv ^^ n) (f ^^ m) z)\"\n            apply (subst higher_deriv_iter_top_lemma [OF \\<open>open s\\<close> holf fss \\<open>z \\<in> s\\<close> \\<open>f z = z\\<close> dfz])\n            using less apply auto\n            done\n          also have \"... \\<le> fact n * c / r ^ n\"\n            apply (rule Cauchy_higher_deriv_bound [OF holfm' contfm' \\<open>0 < r\\<close>, where y=z])\n            using less.prems apply linarith\n            using fms_sb c r ball_subset_cball\n            apply blast\n            done\n          finally show ?thesis .\n        qed\n        have \"cmod ((deriv ^^ n) f z) = 0\"\n          apply (rule real_archimedian_rdiv_eq_0 [where c = \"(fact n) * c / r ^ n\"])\n          apply simp\n          using \\<open>0 < r\\<close> \\<open>0 < c\\<close>\n          apply (simp add: divide_simps)\n          apply (blast intro: le)\n          done\n        then show ?case by simp\n      qed\n      with n1 show ?thesis by simp\n    qed\n  qed\n  have \"f w = id w\"\n    by (rule holomorphic_fun_eq_on_connected\n                 [OF holf holomorphic_on_id \\<open>open s\\<close> \\<open>connected s\\<close> * \\<open>z \\<in> s\\<close> \\<open>w \\<in> s\\<close>])\n  also have \"... = w\" by simp\n  finally show ?thesis .\nqed\n\n\ntext\\<open>Second Cartan Theorem.\\<close>\n\nlemma Cartan_is_linear:\n  assumes holf: \"f holomorphic_on s\"\n      and \"open s\" and \"connected s\"\n      and \"0 \\<in> s\"\n      and ins: \"\\<And>u z. \\<lbrakk>norm u = 1; z \\<in> s\\<rbrakk> \\<Longrightarrow> u * z \\<in> s\"\n      and feq: \"\\<And>u z. \\<lbrakk>norm u = 1; z \\<in> s\\<rbrakk> \\<Longrightarrow> f (u * z) = u * f z\"\n    shows \"\\<exists>c. \\<forall>z \\<in> s. f z = c * z\"\nproof -\n  have [simp]: \"f 0 = 0\"\n    using feq [of \"-1\" 0] assms by simp\n  have uneq: \"u^n * (deriv ^^ n) f (u * z) = u * (deriv ^^ n) f z\"\n       if \"norm u = 1\" \"z \\<in> s\" for n u z\n  proof -\n    have holfuw: \"(\\<lambda>w. f (u * w)) holomorphic_on s\"\n      apply (rule holomorphic_on_compose_gen [OF _ holf, unfolded o_def])\n      using that ins by (auto simp: holomorphic_on_linear)\n    have hol_d_fuw: \"(deriv ^^ n) (\\<lambda>w. u * f w) holomorphic_on s\" for n\n      by (rule holomorphic_higher_deriv holomorphic_intros holf assms)+\n    have *: \"(deriv ^^ n) (\\<lambda>w. u * f w) z = u * (deriv ^^ n) f z\" if \"z \\<in> s\" for z\n    using that\n    proof (induction n arbitrary: z)\n      case 0 then show ?case by simp\n    next\n      case (Suc n)\n      have \"deriv ((deriv ^^ n) (\\<lambda>w. u * f w)) z = deriv (\\<lambda>w. u * (deriv ^^ n) f w) z\"\n        apply (rule complex_derivative_transform_within_open [OF hol_d_fuw])\n        apply (auto intro!: holomorphic_higher_deriv holomorphic_intros assms Suc)\n        done\n      also have \"... = u * deriv ((deriv ^^ n) f) z\"\n        apply (rule deriv_cmult)\n        using Suc \\<open>open s\\<close> holf holomorphic_higher_deriv holomorphic_on_imp_differentiable_at by blast\n      finally show ?case by simp\n    qed\n    have \"(deriv ^^ n) (\\<lambda>w. f (u * w)) z = u ^ n * (deriv ^^ n) f (u * z)\"\n      apply (rule higher_deriv_compose_linear [OF holf \\<open>open s\\<close> \\<open>open s\\<close>])\n      apply (simp add: that)\n      apply (simp add: ins that)\n      done\n    moreover have \"(deriv ^^ n) (\\<lambda>w. f (u * w)) z = u * (deriv ^^ n) f z\"\n      apply (subst higher_deriv_transform_within_open [OF holfuw, of \"\\<lambda>w. u * f w\"])\n      apply (rule holomorphic_intros holf assms that)+\n      apply blast\n      using * \\<open>z \\<in> s\\<close> apply blast\n      done\n    ultimately show ?thesis by metis\n  qed\n  have dnf0: \"(deriv ^^ n) f 0 = 0\" if len: \"2 \\<le> n\" for n\n  proof -\n    have **: \"z = 0\" if \"\\<And>u::complex. norm u = 1 \\<Longrightarrow> u ^ n * z = u * z\" for z\n    proof -\n      have \"\\<exists>u::complex. norm u = 1 \\<and> u ^ n \\<noteq> u\"\n        using complex_not_root_unity [of \"n-1\"] len\n        apply (simp add: algebra_simps le_diff_conv2, clarify)\n        apply (rule_tac x=u in exI)\n        apply (subst (asm) power_diff)\n        apply auto\n        done\n      with that show ?thesis\n        by auto\n    qed\n    show ?thesis\n      apply (rule **)\n      using uneq [OF _ \\<open>0 \\<in> s\\<close>]\n      by force\n  qed\n  show ?thesis\n    apply (rule_tac x = \"deriv f 0\" in exI, clarify)\n    apply (rule holomorphic_fun_eq_on_connected [OF holf _ \\<open>open s\\<close> \\<open>connected s\\<close> _ \\<open>0 \\<in> s\\<close>])\n    using dnf0 apply (auto simp: holomorphic_on_linear)\n    done\nqed\n\ntext\\<open>Should be proved for n-dimensional vectors of complex numbers\\<close>\ntheorem second_Cartan_dim_1:\n  assumes holf: \"f holomorphic_on ball 0 r\"\n      and holg: \"g holomorphic_on ball 0 r\"\n      and [simp]: \"f 0 = 0\" and [simp]: \"g 0 = 0\"\n      and ballf: \"\\<And>z. z \\<in> ball 0 r \\<Longrightarrow> f z \\<in> ball 0 r\"\n      and ballg: \"\\<And>z. z \\<in> ball 0 r \\<Longrightarrow> g z \\<in> ball 0 r\"\n      and fg: \"\\<And>z. z \\<in> ball 0 r \\<Longrightarrow> f (g z) = z\"\n      and gf: \"\\<And>z. z \\<in> ball 0 r \\<Longrightarrow> g (f z) = z\"\n      and \"0 < r\"\n    shows \"\\<exists>t. \\<forall>z \\<in> ball 0 r. g z = exp(\\<i> * of_real t) * z\"\nproof -\n  have c_le_1: \"c \\<le> 1\"\n    if \"0 \\<le> c\" \"\\<And>x. 0 \\<le> x \\<Longrightarrow> x < r \\<Longrightarrow> c * x < r\" for c\n  proof -\n    have rst: \"\\<And>r s t::real. 0 = r \\<or> s/r < t \\<or> r < 0 \\<or> \\<not> s < r * t\"\n      by (metis (no_types) mult_less_cancel_left_disj nonzero_mult_div_cancel_left times_divide_eq_right)\n    { assume \"\\<not> r < c \\<and> c * (c * (c * (c * r))) < 1\"\n     then have \"1 \\<le> c \\<Longrightarrow> (\\<exists>r. \\<not> 1 < r \\<and> \\<not> r < c)\"\n          using \\<open>0 \\<le> c\\<close> by (metis (full_types) less_eq_real_def mult.right_neutral mult_left_mono not_less)\n      then have \"\\<not> 1 < c \\<or> \\<not> 1 \\<le> c\"\n        by linarith }\n    moreover\n    { have \"\\<not> 0 \\<le> r / c \\<Longrightarrow> \\<not> 1 \\<le> c\"\n          using \\<open>0 < r\\<close> by force\n      then have \"1 < c \\<Longrightarrow> \\<not> 1 \\<le> c\"\n        using rst \\<open>0 < r\\<close> that\n        by (metis div_by_1 frac_less2 less_le_trans mult.commute not_le order_refl pos_divide_le_eq zero_less_one) }\n    ultimately show ?thesis\n      by (metis (no_types) linear not_less)\n  qed\n  have ugeq: \"u * g z = g (u * z)\" if nou: \"norm u = 1\" and z: \"z \\<in> ball 0 r\" for u z\n  proof -\n    have [simp]: \"u \\<noteq> 0\" using that by auto\n    have hol1: \"(\\<lambda>a. f (u * g a) / u) holomorphic_on ball 0 r\"\n      apply (rule holomorphic_intros)\n      apply (rule holomorphic_on_compose_gen [OF _ holf, unfolded o_def])\n      apply (rule holomorphic_intros holg)+\n      using nou ballg\n      apply (auto simp: dist_norm norm_mult holomorphic_on_const)\n      done\n    have cdf: \"f field_differentiable at 0\"\n      using \\<open>0 < r\\<close> holf holomorphic_on_imp_differentiable_at by auto\n    have cdg: \"g field_differentiable at 0\"\n      using \\<open>0 < r\\<close> holg holomorphic_on_imp_differentiable_at by auto\n    have cd_fug: \"(\\<lambda>a. f (u * g a)) field_differentiable at 0\"\n      apply (rule field_differentiable_compose [where g=f and f = \"\\<lambda>a. (u * g a)\", unfolded o_def])\n      apply (rule derivative_intros)+\n      using cdf cdg\n      apply auto\n      done\n    have \"deriv g 0 = deriv g (f 0)\"\n      by simp\n    then have \"deriv f 0 * deriv g 0 = 1\"\n      by (metis open_ball \\<open>0 < r\\<close> ballf centre_in_ball deriv_left_inverse gf holf holg image_subsetI)\n    then have equ: \"deriv f 0 * deriv (\\<lambda>a. u * g a) 0 = u\"\n      by (simp add: cdg deriv_cmult)\n    have der1: \"deriv (\\<lambda>a. f (u * g a) / u) 0 = 1\"\n      apply (simp add: field_class.field_divide_inverse deriv_cmult_right [OF cd_fug])\n      apply (subst deriv_chain [where g=f and f = \"\\<lambda>a. (u * g a)\", unfolded o_def])\n      apply (rule derivative_intros cdf cdg | simp add: equ)+\n      done\n    have fugeq: \"\\<And>w. w \\<in> ball 0 r \\<Longrightarrow> f (u * g w) / u = w\"\n      apply (rule first_Cartan_dim_1 [OF hol1, where z=0])\n      apply (simp_all add: \\<open>0 < r\\<close>)\n      apply (auto simp: der1)\n      using nou ballf ballg\n      apply (simp add: dist_norm norm_mult norm_divide)\n      done\n    have \"f(u * g z) = u * z\"\n      by (metis \\<open>u \\<noteq> 0\\<close> fugeq nonzero_mult_div_cancel_left z times_divide_eq_right)\n    also have \"... = f (g (u * z))\"\n      by (metis (no_types, lifting) fg mem_ball_0 mult_cancel_right2 norm_mult nou z)\n    finally have \"f(u * g z) = f (g (u * z))\" .\n    then have \"g (f (u * g z)) = g (f (g (u * z)))\"\n      by simp\n    then show ?thesis\n      apply (subst (asm) gf)\n      apply (simp add: dist_norm norm_mult nou)\n      using ballg mem_ball_0 z apply blast\n      apply (subst (asm) gf)\n      apply (simp add: dist_norm norm_mult nou)\n      apply (metis ballg mem_ball_0 mult.left_neutral norm_mult nou z, simp)\n      done\n  qed\n  obtain c where c: \"\\<And>z. z \\<in> ball 0 r \\<Longrightarrow> g z = c * z\"\n    apply (rule exE [OF Cartan_is_linear [OF holg]])\n    apply (simp_all add: \\<open>0 < r\\<close> ugeq)\n    apply (auto simp: dist_norm norm_mult)\n    done\n  have gr2: \"g (f (r/2)) = c * f(r/2)\"\n    apply (rule c) using \\<open>0 < r\\<close> ballf mem_ball_0 by force\n  then have \"norm c > 0\"\n    using \\<open>0 < r\\<close>\n    by simp (metis \\<open>f 0 = 0\\<close> c dist_commute fg mem_ball mult_zero_left perfect_choose_dist)\n  then have [simp]: \"c \\<noteq> 0\" by auto\n  have xless: \"x < r * cmod c\" if \"0 \\<le> x\" \"x < r\" for x\n  proof -\n    have \"x = norm (g (f (of_real x)))\"\n    proof -\n      have \"r > cmod (of_real x)\"\n        by (simp add: that)\n      then have \"complex_of_real x \\<in> ball 0 r\"\n        using mem_ball_0 by blast\n      then show ?thesis\n        using gf \\<open>0 \\<le> x\\<close> by force\n    qed\n    then show ?thesis\n      apply (rule ssubst)\n      apply (subst c)\n      apply (rule ballf)\n      using ballf [of x] that\n      apply (auto simp: norm_mult dist_0_norm)\n      done\n  qed\n  have 11: \"1 / norm c \\<le> 1\"\n    apply (rule c_le_1)\n    using xless apply (auto simp: divide_simps)\n    done\n  have \"\\<lbrakk>0 \\<le> x; x < r\\<rbrakk> \\<Longrightarrow> cmod c * x < r\" for x\n    using c [of x] ballg [of x] by (auto simp: norm_mult dist_0_norm)\n    then have \"norm c \\<le> 1\"\n    by (force intro: c_le_1)\n  moreover have \"1 \\<le> norm c\"\n    using 11 by simp\n  ultimately have \"norm c = 1\"  by (rule antisym)\n  with complex_norm_eq_1_exp c show ?thesis\n    by metis\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/Cartan_FP/Cartan.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8577681049901036, "lm_q2_score": 0.839733963661418, "lm_q1q2_score": 0.720297010705683}}
{"text": "theory clique\n  imports Main\nbegin\n\ntext \\<open>Formalise the polynomial-time reduction between vertex cover, \nclique and independent set\\<close>\n\nsection \\<open>definitions\\<close>\n\ntype_synonym 'a graph = \"'a set \\<times> ('a set set)\"\n\ndefinition invar :: \"'a graph => bool\" where\n\"invar g = (\n    let (V, E) = g in (\\<forall>s \\<in> E. (\\<forall>x \\<in> s. x \\<in> V) \\<and> card s = 2)\n)\"\n\nfun vertex_cover :: \"'a graph => 'a set => bool\" where\n\"vertex_cover g s = (\n    let (_, E) = g in (\\<forall>s1 \\<in> E. \\<exists>x \\<in> s1. x \\<in> s)\n)\"\n\nfun clique :: \"'a graph => 'a set => bool\" where\n\"clique g s = (\n    let (_, E) = g in (\\<forall>a \\<in> s. \\<forall> b \\<in> s. a \\<noteq> b \\<longrightarrow> {a, b} \\<in> E)\n)\"\n\nfun vc_to_clique :: \"'a graph => 'a graph\" where\n\"vc_to_clique g = (\n    let (V, E) = g in (V, {s. \\<exists>a \\<in> V. \\<exists>b \\<in> V. s = {a, b} \\<and> s \\<notin> E \\<and> a \\<noteq> b})\n)\"\n\nfun T_vc_to_clique :: \"'a graph => nat\" where\n\"T_vc_to_clique (V, E) = card {s. \\<exists>a \\<in> V. \\<exists>b \\<in> V. s = {a, b} \\<and> s \\<notin> E \\<and> a \\<noteq> b}\"\n\nsection \\<open>proofs of invariant, correctness and polynomial time\\<close>\n\ntheorem invar_vc_to_clique : \"invar (V, E) \\<Longrightarrow> invar (vc_to_clique (V, E))\"\nby (auto simp add: invar_def)\n\ntheorem vc_clique_correct: \nassumes \"invar (V, E)\"\nshows \"clique (vc_to_clique (V, E)) (V - s) = vertex_cover (V, E) s\"\nproof \n  have 1:\"\\<forall>a. {a} \\<notin> E\" using assms invar_def by force\n  from assms have prems: \"\\<forall>s \\<in> E. (\\<forall>x \\<in> s. x \\<in> V)\" \"\\<forall>s \\<in> E. \\<exists>a \\<in> V. \\<exists> b \\<in> V. s = {a, b}\" \n  apply (auto simp: invar_def) by (metis card_2_iff insert_iff)\n\n  assume \"clique (vc_to_clique (V, E)) (V - s)\"\n  hence \"\\<forall>a \\<in> V-s. \\<forall>b \\<in> V-s. a \\<noteq> b \\<longrightarrow> {a, b} \\<in> {s. \\<exists>a\\<in>V. \\<exists>b\\<in>V. s = {a, b} \\<and> s \\<notin> E \\<and> a \\<noteq> b}\" by simp\n  hence \"\\<forall>a \\<in> V-s. \\<forall>b \\<in> V-s. a \\<noteq> b \\<longrightarrow> {a, b} \\<notin> E\" by auto\n  hence \"\\<forall>a \\<in> V-s. \\<forall>b \\<in> V-s. {a, b} \\<notin> E\" using 1 by force\n  hence \"\\<forall>s1 \\<in> E. \\<exists>a b. s1 = {a, b} \\<and> (a \\<notin> V-s \\<or> b \\<notin> V-s)\" \n  using prems(2) doubleton_eq_iff by fast\n  hence \"\\<forall>s1 \\<in> E. \\<exists>a \\<in> s1. a \\<notin> V-s\"\n  by auto\n  hence \"\\<forall>s1 \\<in> E. \\<exists>a \\<in> s1. a \\<in> s\"\n  using prems(1) by simp\n  thus \"vertex_cover (V, E) s\" by simp\n\nnext \n  assume \"vertex_cover (V, E) s\"\n  hence \"\\<forall>s1 \\<in> E. \\<exists>a \\<in> s1. a \\<in> s\" by simp\n  hence \"\\<forall>s1 \\<in> E. \\<exists>a \\<in> s1. a \\<notin> V-s\" by auto\n  hence \"\\<forall>a \\<in>V-s. \\<forall>b \\<in>V-s. a \\<noteq> b \\<longrightarrow> {a, b} \\<notin> E\" by fast\n  thus \"clique (vc_to_clique (V, E)) (V - s)\" by auto\nqed\n\nlemma aux0 :\nassumes \"finite A\" \"x \\<in> A\"\nshows \"card {s. \\<exists>a\\<in>A. s={x, a} \\<and> a \\<noteq> x} = card A - 1\"\nusing assms proof (induction A rule: remove_induct)\ncase empty\n  then show ?case by simp\nnext\n  case infinite\n  then show ?case by simp\nnext\n  case (remove A)\n  \n  hence 0:\"\\<forall>y \\<in> A - {x}. card {s. \\<exists>a\\<in>A - {y}. s = {x, a} \\<and> a \\<noteq> x} = card (A - {y}) - 1\" \n  by auto\n\n  have \"\\<forall>y \\<in> A - {x}. {s. \\<exists>a\\<in>A. s = {x, a} \\<and> a \\<noteq> x} = insert {x, y} {s. \\<exists>a\\<in>A - {y}. s = {x, a} \\<and> a \\<noteq> x}\"\n  by auto\n\n  moreover have \"\\<forall>y \\<in> A - {x}. {x, y} \\<notin> {s. \\<exists>a\\<in>A - {y}. s = {x, a} \\<and> a \\<noteq> x}\"\n  by auto\n\n  ultimately have 1:\"\\<forall>y \\<in> A - {x}. card {s. \\<exists>a\\<in>A. s = {x, a} \\<and> a \\<noteq> x} = card {s. \\<exists>a\\<in>A - {y}. s = {x, a} \\<and> a \\<noteq> x} + 1\"\n    using remove by simp\n\n  from 0 1 have \"\\<forall>y \\<in> A - {x}. card {s. \\<exists>a\\<in>A. s = {x, a} \\<and> a \\<noteq> x} = card (A - {y}) - 1 + 1\" by simp\n  \n  hence 3: \"\\<forall>y \\<in> A - {x}. card {s. \\<exists>a\\<in>A. s = {x, a} \\<and> a \\<noteq> x} = card (A) - 1\"\n     by (metis (no_types, lifting) One_nat_def add.right_neutral add_Suc_right card_Diff_singleton \n     card_Suc_Diff1 finite_insert insert_Diff_single insert_iff remove.prems(1) remove.prems(2))\n  \n     \n  from 3 show ?case apply auto by (metis card_le_Suc0_iff_eq remove.prems(1))\n  \nqed\n\nlemma aux: \nassumes \"finite V\"\nshows \"card {s. \\<exists>a \\<in> V. \\<exists>b \\<in> V. s = {a, b} \\<and> a \\<noteq> b} = card V * (card V - 1) div 2\"\nusing assms proof (induction V rule: finite_remove_induct)\n  case empty\n  then show ?case by auto\nnext\n  case (remove A)\n  have \"\\<forall>x \\<in> A. {s. \\<exists>a\\<in>A - {x}. \\<exists>b\\<in>A - {x}. s = {a, b} \\<and> a \\<noteq> b} = \n  {s. \\<exists>a\\<in>A. \\<exists>b\\<in>A. s = {a, b} \\<and> a \\<noteq> b} - {s. \\<exists>a\\<in>A. s={x, a} \\<and> a \\<noteq> x}\" by auto\n\n  hence \"\\<forall>x \\<in> A. {s. \\<exists>a\\<in>A. \\<exists>b\\<in>A. s = {a, b} \\<and> a \\<noteq> b} = \n    {s. \\<exists>a\\<in>A - {x}. \\<exists>b\\<in>A - {x}. s = {a, b} \\<and> a \\<noteq> b} \\<union> {s. \\<exists>a\\<in>A. s={x, a} \\<and> a \\<noteq> x}\"\n    by auto\n\n  moreover have \"\\<forall>x \\<in> A. finite {s. \\<exists>a\\<in>A - {x}. \\<exists>b\\<in>A - {x}. s = {a, b} \\<and> a \\<noteq> b}\"\n  using remove by simp\n\n  moreover have \"\\<forall>x \\<in> A. finite {s. \\<exists>a\\<in>A. s={x, a} \\<and> a \\<noteq> x}\" using remove by simp\n\n  moreover have \"\\<forall>x \\<in> A. {s. \\<exists>a\\<in>A - {x}. \\<exists>b\\<in>A - {x}. s = {a, b} \\<and> a \\<noteq> b} \n    \\<inter> {s. \\<exists>a\\<in>A. s={x, a} \\<and> a \\<noteq> x} = {}\" by auto\n\n  ultimately have \"\\<forall>x \\<in> A. card {s. \\<exists>a\\<in>A. \\<exists>b\\<in>A. s = {a, b} \\<and> a \\<noteq> b}\n    = card {s. \\<exists>a\\<in>A - {x}. \\<exists>b\\<in>A - {x}. s = {a, b} \\<and> a \\<noteq> b} + card {s. \\<exists>a\\<in>A. s={x, a} \\<and> a \\<noteq> x}\" \n  \n  using card_Un_disjoint by fastforce\n\n  hence \"\\<forall>x \\<in> A. card {s. \\<exists>a\\<in>A. \\<exists>b\\<in>A. s = {a, b} \\<and> a \\<noteq> b}\n    = card (A - {x}) * (card (A - {x}) - 1) div 2 + (card A - 1)\" \n  using aux0 remove by fastforce\n\n  hence \"\\<forall>x \\<in> A. card {s. \\<exists>a\\<in>A. \\<exists>b\\<in>A. s = {a, b} \\<and> a \\<noteq> b}\n    = (card A - 1) * (card A - 2) div 2 + (card A - 1)\"\n by (metis (no_types, lifting) card_Diff_singleton diff_diff_left nat_1_add_1)\n\n  hence \"\\<forall>x \\<in> A. card {s. \\<exists>a\\<in>A. \\<exists>b\\<in>A. s = {a, b} \\<and> a \\<noteq> b}\n    = ((card A - 1) * (card A - 2) + (card A - 1) * 2) div 2\"\n    by simp\n\n  hence \"\\<forall>x \\<in> A. card {s. \\<exists>a\\<in>A. \\<exists>b\\<in>A. s = {a, b} \\<and> a \\<noteq> b}\n    = card A * (card A - 1) div 2\" \n    by (metis (no_types, lifting) One_nat_def cancel_comm_monoid_add_class.diff_cancel\n     card_0_eq distrib_left le_add_diff_inverse2 less_Suc0 less_Suc_eq \n     linorder_not_less mult.commute mult_zero_right one_add_one plus_1_eq_Suc remove.hyps(1) remove.hyps(2))\n\n  then show ?case by auto\nqed\n\ntheorem vc_to_clique_polynomial : \"\\<lbrakk>invar (V, E); finite E; finite V\\<rbrakk> \n\\<Longrightarrow> T_vc_to_clique (V, E) = card V * (card V -1) div 2 - card E\"\nproof-\n\nassume assms: \"invar (V, E)\" \"finite E\" \"finite V\"\nhence \"\\<forall>s \\<in> E. \\<exists>a \\<in> V. \\<exists> b \\<in> V. s = {a, b} \\<and> a \\<noteq> b\" \napply (auto simp add: invar_def) by (metis card_2_iff insert_iff)\n\nhence 1: \"E \\<subseteq> {s. \\<exists>a \\<in> V. \\<exists>b \\<in> V. s = {a, b} \\<and> a \\<noteq> b}\" by auto \n\nhave \"{s. \\<exists>a \\<in> V. \\<exists>b \\<in> V. s = {a, b} \\<and> s \\<notin> E \\<and> a \\<noteq> b} \n  = {s. \\<exists>a \\<in> V. \\<exists>b \\<in> V. s = {a, b} \\<and> a \\<noteq> b} - E\" by auto\nfrom card_Diff_subset[OF assms(2) 1] this \nhave \"card {s. \\<exists>a \\<in> V. \\<exists>b \\<in> V. s = {a, b} \\<and> s \\<notin> E \\<and> a \\<noteq> b} = \ncard {s. \\<exists>a \\<in> V. \\<exists>b \\<in> V. s = {a, b} \\<and> a \\<noteq> b} - card E\" by argo\nalso have \"... = card V * (card V - 1) div 2 - card E\" by (auto simp add: aux[OF assms(3)])\nfinally show ?thesis by simp\n\nqed\n\nsection \\<open>independent set\\<close>\n\nfun independent_set :: \"'a graph => 'a set => bool\" where\n\"independent_set g s = (\n  let (V, E) = g in \n    (\\<forall>a \\<in>s. \\<forall>b \\<in>s. a \\<noteq> b \\<longrightarrow> {a, b} \\<notin> E)\n)\"\n\n\ntext \\<open>constant reduction from independet set to vertex cover\\<close>\nfun is_to_vc :: \"'a graph => 'a graph\" where\n\"is_to_vc g = g\"\n\nfun T_is_to_vc :: \"'a graph => nat\" where\n\"T_is_to_vc _ = 1\"\n\ntheorem is_to_vc_correct:\nassumes \"invar (V, E)\"\nshows \"independent_set (V, E) s = vertex_cover (is_to_vc (V, E)) (V-s)\"\nproof\n  from assms have prems: \"\\<forall>s \\<in> E. (\\<forall>x \\<in> s. x \\<in> V)\" \"\\<forall>s \\<in> E. \\<exists>a \\<in> V. \\<exists> b \\<in> V. s = {a, b}\" \n  apply (auto simp: invar_def) by (metis card_2_iff insert_iff)\n\n  assume \"independent_set (V, E) s\"\n  hence \"\\<forall>a \\<in>s. \\<forall>b \\<in>s. a \\<noteq> b \\<longrightarrow> {a, b} \\<notin> E\" by simp\n  hence \"(\\<forall>a \\<in>s. \\<forall>b \\<in>s.  {a, b} \\<notin> E)\" using assms by (force simp add: invar_def)\n  hence \"\\<forall>s1 \\<in>E. \\<exists>a b. s1 = {a, b} \\<and> (a \\<notin> s \\<or> b \\<notin> s)\" \n  using prems(2) by metis\n  hence \"\\<forall>s1 \\<in>E. \\<exists>a \\<in>s1. a\\<notin>s\" by auto\n  hence \"\\<forall>s1 \\<in>E. \\<exists>a \\<in>s1. a \\<in> V-s\" using prems(1) by simp\n  then show \"vertex_cover (is_to_vc (V, E)) (V-s)\" by simp\n\nnext\n  assume \"vertex_cover (is_to_vc (V, E)) (V-s)\"\n  hence \"\\<forall>s1 \\<in>E. \\<exists>a \\<in>s1. a \\<in>V-s\" by simp\n  hence \"\\<forall>s1 \\<in>E. \\<exists>a \\<in>s1. a \\<in> V-s\" by auto\n  hence \"\\<forall>a \\<in>s. \\<forall>b \\<in>s. a \\<noteq> b \\<longrightarrow> {a, b} \\<notin> E\" by fastforce\n  then show \"independent_set (V, E) s\" by simp\nqed\n\ntheorem is_to_vc_polynomial: \"T_is_to_vc g = 1\" by simp\n\ntext \\<open>reduction from clique to independent set\\<close>\n\nfun clique_to_is :: \"'a graph => 'a graph\" where\n\"clique_to_is g = (\n    let (V, E) = g in (V, {s. \\<exists>a \\<in> V. \\<exists>b \\<in> V. s = {a, b} \\<and> s \\<notin> E \\<and> a \\<noteq> b})\n)\"\n\nfun T_clique_to_is :: \"'a graph => nat\" where\n\"T_clique_to_is (V, E) = card {s. \\<exists>a \\<in> V. \\<exists>b \\<in> V. s = {a, b} \\<and> s \\<notin> E \\<and> a \\<noteq> b}\"\n\ntheorem clique_to_is_correct : \nassumes \"invar (V, E)\" \"s \\<subseteq> V\"\nshows \"clique (V, E) s = independent_set (clique_to_is (V, E)) s\"\nusing assms apply (auto simp add: invar_def) apply metis by blast\n\ntheorem clique_to_is_polynomial : \"\\<lbrakk>invar (V, E); finite E; finite v\\<rbrakk> \n\\<Longrightarrow> T_clique_to_is (V, E) = card V * (card V -1) div 2 - card E\"\nusing vc_to_clique_polynomial by auto\n\ntheorem threeway_reduction_correct:\nassumes \"invar (V, E)\" \"s \\<subseteq> V\"\nshows \"clique (V, E) s = vertex_cover (is_to_vc (clique_to_is (V, E))) (V - s)\"\nproof-\n\nhave \"clique (V, E) s = independent_set (clique_to_is (V, E)) s\"\n using clique_to_is_correct assms by blast\n\nalso have \"... = vertex_cover (is_to_vc (clique_to_is (V, E))) (V - s)\"\n using is_to_vc_correct assms \nby (metis (mono_tags, lifting) clique_to_is.elims invar_vc_to_clique prod.simps(2) vc_to_clique.simps)\n\nfinally show ?thesis  by simp\nqed\n\n\nend", "meta": {"author": "AlexiosFan", "repo": "SimpleMaths", "sha": "3d2045a83a4683c695065dc78b5a816322784adf", "save_path": "github-repos/isabelle/AlexiosFan-SimpleMaths", "path": "github-repos/isabelle/AlexiosFan-SimpleMaths/SimpleMaths-3d2045a83a4683c695065dc78b5a816322784adf/Polynomial_reductions/clique.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680977182187, "lm_q2_score": 0.8397339696776499, "lm_q1q2_score": 0.7202970097597661}}
{"text": "section \"Stack Proofs\"\n\ntheory Stack_Proof\nimports Stack_Aux RTD_Util\nbegin\n\nlemma push_list [simp]: \"list (push x stack) = x # list stack\"\n  by(cases stack) auto\n\nlemma pop_list [simp]: \"list (pop stack) = tl (list stack)\"\n  by(induction stack rule: pop.induct) auto\n\nlemma first_list [simp]: \"\\<not> is_empty stack \\<Longrightarrow> first stack = hd (list stack)\"\n  by(induction stack rule: first.induct) auto\n\nlemma list_empty: \"list stack = [] \\<longleftrightarrow> is_empty stack\"\n  by(induction stack rule: is_empty_stack.induct) auto\n\nlemma list_not_empty: \"list stack  \\<noteq> [] \\<longleftrightarrow> \\<not> is_empty stack\"\n  by(induction stack rule: is_empty_stack.induct) auto \n\nlemma list_empty_2 [simp]: \"\\<lbrakk>list stack \\<noteq> []; is_empty stack\\<rbrakk> \\<Longrightarrow> False\"\n  by (simp add: list_empty)\n\nlemma list_not_empty_2 [simp]:\"\\<lbrakk>list stack = []; \\<not> is_empty stack\\<rbrakk> \\<Longrightarrow> False\"\n  by (simp add: list_empty)\n\nlemma list_empty_size: \"list stack = [] \\<longleftrightarrow> size stack = 0\"\n  by(induction stack) auto \n\nlemma list_not_empty_size:\"list stack \\<noteq> [] \\<longleftrightarrow> 0 < size stack\"\n  by(induction stack) auto\n\nlemma list_empty_size_2 [simp]: \"\\<lbrakk>list stack \\<noteq> []; size stack = 0\\<rbrakk> \\<Longrightarrow> False\"\n  by (simp add: list_empty_size) \n\nlemma list_not_empty_size_2 [simp]:\"\\<lbrakk>list stack = []; 0 < size stack\\<rbrakk> \\<Longrightarrow> False\"\n  by (simp add: list_empty_size)\n\nlemma size_push [simp]: \"size (push x stack) = Suc (size stack)\"\n  by(cases stack) auto\n\nlemma size_pop [simp]: \"size (pop stack) = size stack - Suc 0\"\n  by(induction stack rule: pop.induct) auto\n\nlemma size_empty: \"size (stack :: 'a stack) = 0 \\<longleftrightarrow> is_empty stack\"\n  by(induction stack rule: is_empty_stack.induct) auto\n\nlemma size_not_empty: \"size (stack :: 'a stack) > 0 \\<longleftrightarrow> \\<not> is_empty stack\"\n  by(induction stack rule: is_empty_stack.induct) auto\n\nlemma size_empty_2[simp]: \"\\<lbrakk>size (stack :: 'a stack) = 0; \\<not>is_empty stack\\<rbrakk> \\<Longrightarrow> False\"\n  by (simp add: size_empty)\n\nlemma size_not_empty_2[simp]: \"\\<lbrakk>0 < size (stack :: 'a stack); is_empty stack\\<rbrakk> \\<Longrightarrow> False\"\n  by (simp add: size_not_empty)\n\nlemma size_list_length [simp]: \"length (list stack) = size stack\"\n  by(cases stack) auto\n\nlemma first_pop [simp]: \"\\<not> is_empty stack \\<Longrightarrow> first stack # list (pop stack) = list stack\"\n  by(induction stack rule: pop.induct) auto\n\nlemma push_not_empty [simp]: \"\\<lbrakk>\\<not> is_empty stack; is_empty (push x stack)\\<rbrakk> \\<Longrightarrow> False\"\n  by(induction x stack rule: push.induct) auto\n\nlemma pop_list_length [simp]: \"\\<not> is_empty stack\n   \\<Longrightarrow> Suc (length (list (pop stack))) = length (list stack)\"\n  by(induction stack rule: pop.induct) auto\n\nlemma first_take: \"\\<not>is_empty stack \\<Longrightarrow> [first stack] = take 1 (list stack)\"\n  by (simp add: list_empty)\n\nlemma first_take_tl [simp]: \"0 < size big\n   \\<Longrightarrow> (first big # take count (tl (list big))) = take (Suc count) (list big)\"\n  by(induction big rule: Stack.first.induct) auto\n\nlemma first_take_pop [simp]: \"\\<lbrakk>\\<not>is_empty stack; 0 < x\\<rbrakk>\n   \\<Longrightarrow> first stack # take (x - Suc 0) (list (pop stack)) = take x (list stack)\"\n  by(induction stack rule: pop.induct) (auto simp: take_Cons')\n\n\n\nlemma first_hd: \"first stack = hd (list stack)\"\n  by(induction stack rule: first.induct)(auto simp: hd_def)\n\nlemma pop_tl [simp]: \"list (pop stack) = tl (list stack)\" \n  by(induction stack rule: pop.induct) auto\n\nlemma pop_drop: \"list (pop stack) = drop 1 (list stack)\" \n  by (simp add: drop_Suc)\n\nlemma popN_drop [simp]: \"list ((pop ^^ n) stack) = drop n (list stack)\" \n  by(induction n)(auto simp: drop_Suc tl_drop)\n\nlemma popN_size [simp]: \"size ((pop ^^ n) stack) = (size stack) - n\"\n by(induction n) auto\n\nlemma take_first: \"\\<lbrakk>0 < size s1; 0 < size s2; take (size s1) (list s2) = take (size s2) (list s1)\\<rbrakk>\n    \\<Longrightarrow> first s1 = first s2\"\n  by(induction s1 rule: first.induct; induction s2 rule: first.induct) 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/Real_Time_Deque/Stack_Proof.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267898240861, "lm_q2_score": 0.8289388040954683, "lm_q1q2_score": 0.7202042401228828}}
{"text": "(*  Title:      The Second Isomorphism Theorem for Groups\n    Author:     Jakob von Raumer, Karlsruhe Institute of Technology\n    Maintainer: Jakob von Raumer <jakob.raumer@student.kit.edu>\n*)\n\ntheory SndIsomorphismGrp\nimports\n    \"HOL-Algebra.Coset\"\n    Secondary_Sylow.SubgroupConjugation\nbegin\n\nsection \\<open>The Second Isomorphism Theorem for Groups\\<close>\n\nsubsection \\<open>Preliminaries\\<close>\n\nlemma (in group) triv_subgroup:\n  shows \"subgroup {\\<one>} G\"\nunfolding subgroup_def by auto\n\nlemma (in group) triv_normal_subgroup:\n  shows \"{\\<one>} \\<lhd> G\"\nunfolding normal_def normal_axioms_def l_coset_def r_coset_def\nusing is_group triv_subgroup by auto\n\nlemma (in group) normal_restrict_supergroup:\n  assumes SsubG:\"subgroup S G\"\n  assumes Nnormal:\"N \\<lhd> G\"\n  assumes \"N \\<subseteq> S\"\n  shows \"N \\<lhd> (G\\<lparr>carrier := S\\<rparr>)\"\nproof -\n  interpret Sgrp: group \"G\\<lparr>carrier := S\\<rparr>\" using SsubG by (rule subgroup_imp_group)\n  show ?thesis\n  proof(rule Sgrp.normalI)\n    show \"subgroup N (G\\<lparr>carrier := S\\<rparr>)\" using assms is_group by (metis subgroup.subgroup_of_subset normal_inv_iff)\n  next\n    from SsubG have \"S \\<subseteq> carrier G\" by (rule subgroup.subset)\n    thus \"\\<forall>x\\<in>carrier (G\\<lparr>carrier := S\\<rparr>). N #>\\<^bsub>G\\<lparr>carrier := S\\<rparr>\\<^esub> x = x <#\\<^bsub>G\\<lparr>carrier := S\\<rparr>\\<^esub> N\"\n      using Nnormal unfolding normal_def normal_axioms_def l_coset_def r_coset_def by fastforce\n  qed\nqed\n\ntext \\<open>As this is maybe the best place this fits in: Factorizing by the trivial subgroup\nis an isomorphism.\\<close>\n\nlemma (in group) trivial_factor_iso:\n  shows \"the_elem \\<in> iso (G Mod {\\<one>}) G\"\nproof -\n  have \"group_hom G G (\\<lambda>x. x)\" unfolding group_hom_def group_hom_axioms_def hom_def using is_group by simp\n  moreover have \"(\\<lambda>x. x) ` carrier G = carrier G\" by simp\n  moreover have \"kernel G G (\\<lambda>x. x) = {\\<one>}\" unfolding kernel_def by auto\n  ultimately show ?thesis using group_hom.FactGroup_iso_set by force\nqed\n\ntext \\<open>And the dual theorem to the previous one: Factorizing by the group itself gives the trivial group\\<close>\n\nlemma (in group) self_factor_iso:\n  shows \"(\\<lambda>X. the_elem ((\\<lambda>x. \\<one>) ` X)) \\<in> iso (G Mod (carrier G)) (G\\<lparr> carrier := {\\<one>} \\<rparr>)\"\nproof -\n  have \"group (G\\<lparr>carrier := {\\<one>}\\<rparr>)\" by (metis subgroup_imp_group triv_subgroup)\n  hence \"group_hom G (G\\<lparr>carrier := {\\<one>}\\<rparr>) (\\<lambda>x. \\<one>)\" unfolding group_hom_def group_hom_axioms_def hom_def using is_group by auto\n  moreover have \"(\\<lambda>x. \\<one>) ` carrier G = carrier (G\\<lparr>carrier := {\\<one>}\\<rparr>)\" by auto\n  moreover have \"kernel G (G\\<lparr>carrier := {\\<one>}\\<rparr>) (\\<lambda>x. \\<one>) = carrier G\" unfolding kernel_def by auto\n  ultimately show ?thesis using group_hom.FactGroup_iso_set by force\nqed\n\ntext \\<open>This theory provides a proof of the second isomorphism theorems for groups. \nThe theorems consist of several facts about normal subgroups.\\<close>\n\ntext \\<open>The first lemma states that whenever we have a subgroup @{term S} and\na normal subgroup @{term H} of a group @{term G}, their intersection is normal\nin @{term G}\\<close>\n\nlocale second_isomorphism_grp = normal +\n  fixes S::\"'a set\"\n  assumes subgrpS:\"subgroup S G\"\n\ncontext second_isomorphism_grp\nbegin\n\ninterpretation groupS: group \"G\\<lparr>carrier := S\\<rparr>\"\nusing subgrpS by (metis subgroup_imp_group)\n\nlemma normal_subgrp_intersection_normal:\n  shows \"S \\<inter> H \\<lhd> (G\\<lparr>carrier := S\\<rparr>)\"\nproof(auto simp: groupS.normal_inv_iff)\n  from subgrpS is_subgroup have \"\\<And>x. x \\<in> {S, H} \\<Longrightarrow> subgroup x G\" by auto\n  hence \"subgroup (\\<Inter> {S, H}) G\" using subgroups_Inter by blast\n  hence \"subgroup (S \\<inter> H) G\" by auto\n  moreover have \"S \\<inter> H \\<subseteq> S\" by simp\n  ultimately show \"subgroup (S \\<inter> H) (G\\<lparr>carrier := S\\<rparr>)\" using is_group subgroup.subgroup_of_subset subgrpS by metis\nnext\n  fix g h\n  assume g:\"g \\<in> S\" and hH:\"h \\<in> H\" and hS:\"h \\<in> S\" {\n    from g hH subgrpS show \"g \\<otimes> h \\<otimes> inv\\<^bsub>G\\<lparr>carrier := S\\<rparr>\\<^esub> g \\<in> H\" by (metis inv_op_closed2 subgroup.mem_carrier m_inv_consistent)\n  } {\n    from g hS subgrpS show \"g \\<otimes> h \\<otimes> inv\\<^bsub>G\\<lparr>carrier := S\\<rparr>\\<^esub> g \\<in> S\" by (metis subgroup.m_closed subgroup.m_inv_closed m_inv_consistent)\n  }\nqed\n\nlemma normal_set_mult_subgroup:\n  shows \"subgroup (H <#> S) G\"\nproof(rule subgroupI)\n  show \"H <#> S \\<subseteq> carrier G\" by (metis setmult_subset_G subgroup.subset subgrpS subset)\nnext\n  have \"\\<one> \\<in> H\" \"\\<one> \\<in> S\" using is_subgroup subgrpS subgroup.one_closed by auto\n  hence \"\\<one> \\<otimes> \\<one> \\<in> H <#> S\" unfolding set_mult_def by blast\n  thus \"H <#> S \\<noteq> {}\" by auto\nnext\n  fix g\n  assume g:\"g \\<in> H <#> S\"\n  then obtain h s where h:\"h \\<in> H\" and s:\"s \\<in> S\" and ghs:\"g = h \\<otimes> s\" unfolding set_mult_def by auto\n  hence \"s \\<in> carrier G\" by (metis subgroup.mem_carrier subgrpS)\n  with h ghs obtain h' where h':\"h' \\<in> H\" and \"g = s \\<otimes> h'\" using coset_eq unfolding r_coset_def l_coset_def by auto\n  with s have \"inv g = (inv h') \\<otimes> (inv s)\" by (metis inv_mult_group mem_carrier subgroup.mem_carrier subgrpS)\n  moreover from h' s subgrpS have \"inv h' \\<in> H\" \"inv s \\<in> S\" using subgroup.m_inv_closed m_inv_closed by auto\n  ultimately show \"inv g \\<in> H <#> S\" unfolding set_mult_def by auto\nnext\n  fix g g'\n  assume g:\"g \\<in> H <#> S\" and h:\"g' \\<in> H <#> S\"\n  then obtain h h' s s' where hh'ss':\"h \\<in> H\" \"h' \\<in> H\" \"s \\<in> S\" \"s' \\<in> S\" and \"g = h \\<otimes> s\" and \"g' = h' \\<otimes> s'\" unfolding set_mult_def by auto\n  hence \"g \\<otimes> g' = (h \\<otimes> s) \\<otimes> (h' \\<otimes> s')\" by metis\n  also from hh'ss' have inG:\"h \\<in> carrier G\" \"h' \\<in> carrier G\" \"s \\<in> carrier G\" \"s' \\<in> carrier G\" using subgrpS mem_carrier subgroup.mem_carrier by force+\n  hence \"(h \\<otimes> s) \\<otimes> (h' \\<otimes> s') = h \\<otimes> (s \\<otimes> h') \\<otimes> s'\" using m_assoc by auto\n  also from hh'ss' inG obtain h'' where h'':\"h'' \\<in> H\" and \"s \\<otimes> h' = h'' \\<otimes> s\"using coset_eq unfolding r_coset_def l_coset_def by fastforce\n  hence \"h \\<otimes> (s \\<otimes> h') \\<otimes> s' = h \\<otimes> (h'' \\<otimes> s) \\<otimes> s'\" by simp\n  also from h'' inG have \"... = (h \\<otimes> h'') \\<otimes> (s \\<otimes> s')\" using m_assoc mem_carrier by auto\n  finally have \"g \\<otimes> g' = h \\<otimes> h'' \\<otimes> (s \\<otimes> s')\".\n  moreover with h'' hh'ss' have \"... \\<in> H <#> S\" unfolding set_mult_def using subgrpS subgroup.m_closed by fastforce\n  ultimately show \"g \\<otimes> g' \\<in> H <#> S\" by simp\nqed\n\nlemma oneH:\"\\<one> \\<in> H\" by (metis is_subgroup subgroup.one_closed)\n\nlemma H_contained_in_set_mult:\n  shows \"H \\<subseteq> H <#> S\"\nproof auto\n  have \"\\<one> \\<in> S\" by (metis subgroup.one_closed subgrpS)\n  fix x\n  assume x:\"x \\<in> H\"\n  with \\<open>\\<one> \\<in> S\\<close> have \"x \\<otimes> \\<one> \\<in> H <#> S\" unfolding set_mult_def by force\n  with x show  \"x \\<in> H <#> S\" by (metis mem_carrier r_one)\nqed\n\nlemma S_contained_in_set_mult:\n  shows \"S \\<subseteq> H <#> S\"\nproof auto\n  fix s\n  assume s:\"s \\<in> S\"\n  with oneH have \"\\<one> \\<otimes> s \\<in> H <#> S\" unfolding set_mult_def by force\n  with s show \"s \\<in> H <#> S\" using subgrpS subgroup.mem_carrier l_one by force\nqed\n\nlemma normal_intersection_hom:\n  shows \"group_hom (G\\<lparr>carrier := S\\<rparr>) ((G\\<lparr>carrier := H <#> S\\<rparr>) Mod H) (\\<lambda>g. H #> g)\"\nproof (auto del: equalityI simp: group_hom_def group_hom_axioms_def hom_def groupS.is_group)\n  have  gr:\"group (G\\<lparr>carrier := H <#> S\\<rparr>)\" by (metis normal_set_mult_subgroup subgroup_imp_group)\n  moreover have \"H \\<subseteq> H <#> S\" by (rule H_contained_in_set_mult)\n  moreover have \"subgroup (H <#> S) G\" by (metis normal_set_mult_subgroup)\n  ultimately have \"H \\<lhd> (G\\<lparr>carrier := H <#> S\\<rparr>)\" using normal_restrict_supergroup by (metis inv_op_closed2 is_subgroup normal_inv_iff)\n  with gr show \"group ((G\\<lparr>carrier := H <#> S\\<rparr>) Mod H)\" by (metis normal.factorgroup_is_group)\nnext\n  fix g\n  assume g: \"g \\<in> S\"\n  with subgrpS have \"\\<one> \\<otimes> g \\<in> H <#> S\" unfolding set_mult_def by fastforce\n  with g have \"g \\<in> H <#> S\" by (metis l_one subgroup.mem_carrier subgrpS)\n  thus \"H #> g \\<in> carrier ((G\\<lparr>carrier := H <#> S\\<rparr>) Mod H)\" unfolding FactGroup_def RCOSETS_def r_coset_def by auto\nnext\n  show \"\\<And>x y. \\<lbrakk>x \\<in> S; y \\<in> S\\<rbrakk> \\<Longrightarrow> H #> x \\<otimes> y = H #> x <#> (H #> y)\"\n    using normal.rcos_sum normal_axioms subgroup.mem_carrier subgrpS by fastforce\nqed\n\nlemma normal_intersection_hom_kernel:\n  shows \"kernel (G\\<lparr>carrier := S\\<rparr>) ((G\\<lparr>carrier := H <#> S\\<rparr>) Mod H) (\\<lambda>g. H #> g) = H \\<inter> S\"\nproof -\n  have \"kernel (G\\<lparr>carrier := S\\<rparr>) ((G\\<lparr>carrier := H <#> S\\<rparr>) Mod H) (\\<lambda>g. H #> g)\n                 = {g \\<in> S. H #> g = \\<one>\\<^bsub>(G\\<lparr>carrier := H <#> S\\<rparr>) Mod H\\<^esub>}\" unfolding kernel_def by auto\n  also have \"... = {g \\<in> S. H #> g = H}\" unfolding FactGroup_def by auto\n  also have \"... = {g \\<in> S. g \\<in> H}\" by (metis coset_eq is_subgroup lcoset_join2 rcos_self subgroup.mem_carrier subgrpS)\n  also have \"... = H \\<inter> S\" by auto\n  finally show ?thesis.\nqed\n\nlemma normal_intersection_hom_surj:\n  shows \"(\\<lambda>g. H #> g) ` carrier (G\\<lparr>carrier := S\\<rparr>) = carrier ((G\\<lparr>carrier := H <#> S\\<rparr>) Mod H)\"\nproof auto\n  fix g\n  assume \"g \\<in> S\"\n  hence \"g \\<in> H <#> S\" using S_contained_in_set_mult by auto\n  thus \"H #> g \\<in> carrier ((G\\<lparr>carrier := H <#> S\\<rparr>) Mod H)\" unfolding FactGroup_def RCOSETS_def r_coset_def by auto\nnext\n  fix x\n  assume \"x \\<in> carrier (G\\<lparr>carrier := H <#> S\\<rparr> Mod H)\"\n  then obtain h s where h:\"h \\<in> H\" and s:\"s \\<in> S\" and \"x = H #> (h \\<otimes> s)\"\n    unfolding FactGroup_def RCOSETS_def r_coset_def set_mult_def by auto\n  hence \"x = (H #> h) #> s\" by (metis h s coset_mult_assoc mem_carrier subgroup.mem_carrier subgrpS subset)\n  also have \"... = H #> s\" by (metis h is_group rcos_const)\n  finally have \"x = H #> s\".\n  with s show \"x \\<in> (#>) H ` S\" by simp\nqed\n\ntext \\<open>Finally we can prove the actual isomorphism theorem:\\<close>\n\ntheorem normal_intersection_quotient_isom:\n  shows \"(\\<lambda>X. the_elem ((\\<lambda>g. H #> g) ` X)) \\<in> iso ((G\\<lparr>carrier := S\\<rparr>) Mod (H \\<inter> S)) (((G\\<lparr>carrier := H <#> S\\<rparr>)) Mod H)\"\nusing normal_intersection_hom_kernel[symmetric] normal_intersection_hom normal_intersection_hom_surj\nby (metis group_hom.FactGroup_iso_set)\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/Jordan_Hoelder/SndIsomorphismGrp.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8688267694452331, "lm_q2_score": 0.8289388167733099, "lm_q1q2_score": 0.7202042342449089}}
{"text": "theory Lecture14\nimports Main\nbegin\n\n\nprimrec myappend :: \"'a list \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where\n\"myappend Nil ys = ys\" |\n\"myappend (Cons x xs) ys = Cons x (myappend xs ys)\"\n\nlemma  \"myappend xs (myappend ys zs) = myappend (myappend xs ys) zs\"\napply (induct xs)\napply simp\napply simp\ndone\n\nlemma  myappend_assoc: \"myappend xs (myappend ys zs) = myappend (myappend xs ys) zs\"\nproof (induction xs)\n  case Nil then show ?case by simp\nnext\n  case (Cons x xs) then show ?case by simp\nqed\n\nlemma myappend_Nil: \"myappend xs Nil = xs\"\nproof (induction xs)\n  case Nil thus ?case  by simp\nnext \n  case (Cons x xs) thus ?case by simp\nqed\n\n\nprimrec myreverse :: \"'a list \\<Rightarrow> 'a list\" where\n\"myreverse Nil = Nil\" |\n\"myreverse (Cons x xs) = myappend (myreverse xs) (Cons x Nil)\"\n\nlemma myreverse_myreverse: \"myreverse(myreverse xs) = xs\"\napply (induct xs)\napply simp\napply simp\n(* stuck: need to speculate a lemma *)\noops\n\n\nlemma speculated_myreverse: \n  \"myreverse(myappend xs ys) = myappend (myreverse ys) (myreverse xs)\"\nproof (induction xs)\n  case Nil then show ?case by (simp add: myappend_Nil) \nnext\n  case (Cons x xs) then show ?case by (simp add:myappend_assoc)\nqed\n\n(* A detailed proof to match the one given in the lecture *)\n\nlemma myreverse_myreverse: \"myreverse(myreverse xs) = xs\"\nproof (induct xs)\n  case Nil thus ?case by simp\nnext\n  case (Cons x xs) \n  then have \"myreverse (myreverse (x # xs)) = myreverse(myappend (myreverse xs) (Cons x Nil))\" \n       by simp\n  moreover have \"\\<dots> = myappend (Cons x Nil) (myreverse(myreverse xs))\"\n      by (simp add: speculated_myreverse) \n  moreover have \"\\<dots> = Cons x (myappend Nil (myreverse(myreverse xs)))\"\n      by simp\n  moreover have \"\\<dots> = Cons x (myreverse(myreverse xs))\" \n      by simp\n  moreover have \"\\<dots> = Cons x xs\" using Cons.hyps by blast \n  ultimately show ?case by simp\nqed\n\n(* Simpler proof -- as one would normally do it*)\nlemma myreverse_myreverse2: \"myreverse(myreverse xs) = xs\"\nproof (induct xs)\n  case Nil thus ?case by simp\nnext\n  case (Cons x xs) thus ?case by (simp add: speculated_myreverse) \nqed\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/Lecture14.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289387998695209, "lm_q2_score": 0.8688267813328976, "lm_q1q2_score": 0.7202042294125908}}
{"text": "(*  Title:       Category theory using Isar and Locales\n    Author:      Greg O'Keefe, June, July, August 2003\n    License: LGPL\n*)\n\nheader {* Categories *}\n\ntheory Cat\nimports \"~~/src/HOL/Library/FuncSet\"\nbegin\n\nsubsection {* Definitions *}\n\nrecord ('o, 'a) category =\n  ob :: \"'o set\" (\"Ob\\<index>\"  70)\n  ar :: \"'a set\" (\"Ar\\<index>\"  70)\n  dom :: \"'a \\<Rightarrow> 'o\" (\"Dom\\<index> _\" [81] 70)\n  cod :: \"'a \\<Rightarrow> 'o\" (\"Cod\\<index> _\" [81] 70)\n  id :: \"'o \\<Rightarrow> 'a\" (\"Id\\<index> _\" [81] 80)\n  comp :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a\"  (infixl \"\\<bullet>\\<index>\" 60)\n\ndefinition\n  hom :: \"[('o,'a,'m) category_scheme, 'o, 'o] \\<Rightarrow> 'a set\"\n    (\"Hom\\<index> _ _\" [81,81] 80) where\n  \"hom CC A B = { f. f\\<in>ar CC & dom CC f = A & cod CC f = B }\"\n\nlocale category =\n  fixes CC (structure)\n  assumes dom_object [intro]:\n  \"f \\<in> Ar \\<Longrightarrow> Dom f \\<in> Ob\"\n  and cod_object [intro]:\n  \"f \\<in> Ar \\<Longrightarrow> Cod f \\<in> Ob\"\n  and id_left [simp]:\n  \"f \\<in> Ar \\<Longrightarrow> Id (Cod f) \\<bullet> f = f\"\n  and id_right [simp]:\n  \"f \\<in> Ar \\<Longrightarrow> f \\<bullet> Id (Dom f) = f\"\n  and id_hom [intro]:\n  \"A \\<in> Ob \\<Longrightarrow> Id A \\<in> Hom A A\"\n  and comp_types [intro]:\n  \"\\<And>A B C. (comp CC) : (Hom B C) \\<rightarrow> (Hom A B) \\<rightarrow> (Hom A C)\"\n  and comp_associative [simp]:\n  \"f \\<in> Ar \\<Longrightarrow> g \\<in> Ar \\<Longrightarrow> h \\<in> Ar\n  \\<Longrightarrow> Cod h = Dom g \\<Longrightarrow> Cod g = Dom f\n  \\<Longrightarrow> f \\<bullet> (g \\<bullet> h) = (f \\<bullet> g) \\<bullet> h\"\n\n\nsubsection {* Lemmas *}\n\nlemma (in category) homI:\n  assumes \"f \\<in> Ar\" and \"Dom f = A\" and \"Cod f = B\"\n  shows \"f \\<in> Hom A B\"\n  using assms by (auto simp add: hom_def)\n\n\n\nlemma (in category) id_dom_cod:\n  assumes \"A \\<in> Ob\"\n  shows \"Dom (Id A) = A\" and \"Cod (Id A) = A\"\nproof-\n  from `A \\<in> Ob` have 1: \"Id A \\<in> Hom A A\" ..\n  then show \"Dom (Id A) = A\" and \"Cod (Id A) = A\"\n    by (simp_all add: hom_def)\nqed\n\n\nlemma (in category) compI [intro]:\n  assumes f: \"f \\<in> Ar\" and g: \"g \\<in> Ar\" and \"Cod f = Dom g\"\n  shows \"g \\<bullet> f \\<in> Ar\"\n  and \"Dom (g \\<bullet> f) = Dom f\"\n  and \"Cod (g \\<bullet> f) = Cod g\"\nproof-\n  have \"f \\<in> Hom (Dom f) (Cod f)\" using f by (simp add: hom_def)\n  with `Cod f = Dom g` have f_homset: \"f \\<in> Hom (Dom f) (Dom g)\" by simp\n  have g_homset: \"g \\<in> Hom (Dom g) (Cod g)\" using g by (simp add: hom_def)\n  have \"(op \\<bullet>) : Hom (Dom g) (Cod g) \\<rightarrow> Hom (Dom f) (Dom g) \\<rightarrow> Hom (Dom f) (Cod g)\" ..\n  from this and g_homset \n  have \"(op \\<bullet>) g \\<in> Hom (Dom f) (Dom g) \\<rightarrow> Hom (Dom f) (Cod g)\" \n    by (rule funcset_mem)\n  from this and f_homset \n  have gf_homset: \"g \\<bullet> f \\<in> Hom (Dom f) (Cod g)\"\n    by (rule funcset_mem)\n  thus \"g \\<bullet> f \\<in> Ar\"\n    by (simp add: hom_def) \n  from gf_homset show \"Dom (g \\<bullet> f) = Dom f\" and \"Cod (g \\<bullet> f) = Cod g\"\n    by (simp_all add: hom_def)\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/Category/Cat.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970748488296, "lm_q2_score": 0.8175744761936437, "lm_q1q2_score": 0.7201172071024254}}
{"text": "section\\<open>Repeat finitely Until it Stabilizes\\<close>\ntheory Repeat_Stabilize\nimports Main\nbegin\n\ntext\\<open>Repeating something a number of times\\<close>\n\n\ntext\\<open>Iterating a function at most @{term n} times (first parameter) until it stabilizes.\\<close>\nfun repeat_stabilize :: \"nat \\<Rightarrow> ('a \\<Rightarrow> 'a) \\<Rightarrow> 'a \\<Rightarrow> 'a\" where\n  \"repeat_stabilize 0 _ v = v\" |\n  \"repeat_stabilize (Suc n) f v = (let v_new = f v in if v = v_new then v else repeat_stabilize n f v_new)\"\n\nlemma repeat_stabilize_funpow: \"repeat_stabilize n f v = (f^^n) v\"\n  proof(induction n arbitrary: v)\n  case (Suc n)\n    have \"f v = v \\<Longrightarrow> (f^^n) v = v\" by(induction n) simp_all\n    with Suc show ?case by(simp add: Let_def funpow_swap1)\n  qed(simp)\n\nlemma repeat_stabilize_induct: \"(P m) \\<Longrightarrow> (\\<And>m. P m \\<Longrightarrow> P (f m)) \\<Longrightarrow> P (repeat_stabilize n f m)\"\n  apply(simp add: repeat_stabilize_funpow)\n  apply(induction n)\n   by(simp)+\n\n\nend", "meta": {"author": "diekmann", "repo": "Iptables_Semantics", "sha": "e0a2516bd885708fce875023b474ae341cbdee29", "save_path": "github-repos/isabelle/diekmann-Iptables_Semantics", "path": "github-repos/isabelle/diekmann-Iptables_Semantics/Iptables_Semantics-e0a2516bd885708fce875023b474ae341cbdee29/thy/Iptables_Semantics/Common/Repeat_Stabilize.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199633332891, "lm_q2_score": 0.8596637505099168, "lm_q1q2_score": 0.7200715191810744}}
{"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_HSortIsSort\n  imports \"../../Test_Base\"\nbegin\n\ndatatype 'a list = nil2 | cons2 \"'a\" \"'a list\"\n\ndatatype Heap = Node \"Heap\" \"int\" \"Heap\" | Nil\n\nfun toHeap :: \"int list => Heap list\" where\n  \"toHeap (nil2) = nil2\"\n| \"toHeap (cons2 y z) = cons2 (Node Nil y Nil) (toHeap z)\"\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\nfun hmerge :: \"Heap => Heap => Heap\" where\n  \"hmerge (Node z x2 x3) (Node x4 x5 x6) =\n   (if 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 p (nil2)) = cons2 p (nil2)\"\n| \"hpairwise (cons2 p (cons2 q qs)) =\n     cons2 (hmerge p q) (hpairwise qs)\"\n\n(*fun did not finish the proof*)\nfunction hmerging :: \"Heap list => Heap\" where\n  \"hmerging (nil2) = Nil\"\n| \"hmerging (cons2 p (nil2)) = p\"\n| \"hmerging (cons2 p (cons2 z x2)) =\n     hmerging (hpairwise (cons2 p (cons2 z x2)))\"\n  by pat_completeness auto\n\nfun toHeap2 :: \"int list => Heap\" where\n  \"toHeap2 x = hmerging (toHeap x)\"\n\n(*fun did not finish the proof*)\nfunction toList :: \"Heap => int list\" where\n  \"toList (Node p y q) = cons2 y (toList (hmerge p q))\"\n| \"toList (Nil) = nil2\"\n  by pat_completeness auto\n\nfun hsort :: \"int list => int 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_HSortIsSort.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637505099168, "lm_q2_score": 0.8376199572530448, "lm_q1q2_score": 0.7200715139541087}}
{"text": "theory Lab3_Theory\nimports Main\nbegin\n\n(* Topic: Recursion, induction and counterexamples *)\n\n(* \n  replace :: Old \\<Rightarrow> New \\<Rightarrow> List \\<Rightarrow> List'  \n  Replaces all occurences of Old in List with New.\n*)\nprimrec replace :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a list \\<Rightarrow> 'a list\"\n  where \"replace x y [] = []\"\n  | \"replace x y (z#zs) = (if z = x then y else z)#(replace x y zs)\"\n\nvalue \"replace 1 0 [1, 1, 2] :: int list\"\n\n(*\n  del1 :: Item \\<Rightarrow> List \\<Rightarrow> List'\n  Deletes first occurence of Item in List.\n*)\nprimrec del1 :: \"'a \\<Rightarrow> 'a list \\<Rightarrow> 'a list\"\n  where \"del1 x [] = []\"\n  | \"del1 x (y#ys) = (if y = x then ys else y#(del1 x ys))\"\n\nvalue \"del1 1 [0, 0, 1, 1] :: int list\"\n\n(*\n  delall :: Item \\<Rightarrow> List \\<Rightarrow> List'\n  Deletes all occurences of Item in List.\n*)\nprimrec delall :: \"'a \\<Rightarrow> 'a list \\<Rightarrow> 'a list\"\n  where \"delall x [] = []\"\n  | \"delall x (y#ys) = (if y = x then (delall x ys) else y#(delall x ys))\"\n\nvalue \"delall 0 [1, 1, 0, 0, 1] :: int list\"\n\nexport_code replace delall del1\n  in Haskell module_name App file \"haskabelle\"\n\n\n(* \u0412\u0430\u0440\u0438\u0430\u043d\u0442 3: 3 \u0438 5\n    3: theorem \"del1 x (del1 y zs) = del1 y (del1 x zs)\"\n    5: theorem \"del1 y (replace x y xs) = del1 x xs\"\n*)\n\n(* \n  prove \n  e.g.:\n    List = [0, 0, 1, 2]\n    del1 0 (del1 1 List) = del1 1 (del1 0 List) = [2]\n*)\ntheorem [simp]: \"del1 x (del1 y zs) = del1 y (del1 x zs)\"\n  apply(induct_tac zs)\n  apply auto\ndone\n\n(* \n  fail to prove \n  e.g.:\n    List = [0, 0, 1, 1]\n    LHS: del1 1 (replace 0 1 List) = [1, 1, 1]\n    RHS: del1 0 List = [0, 1, 1]\n    [1, 1, 1] \\<noteq> [0, 1, 1]\n*)\ntheorem \"del1 y (replace x y xs) = del1 x xs\"\n  apply(induct_tac xs)\n  apply auto\n  quickcheck 1\n  quickcheck 2\n  quickcheck 3\noops\n", "meta": {"author": "NoxChimaera", "repo": "formal-verification", "sha": "b828938e74e9b15e4b03f4ac645e834c7470535f", "save_path": "github-repos/isabelle/NoxChimaera-formal-verification", "path": "github-repos/isabelle/NoxChimaera-formal-verification/formal-verification-b828938e74e9b15e4b03f4ac645e834c7470535f/Lab3. Codegen/Lab3_Theory.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869916479466, "lm_q2_score": 0.822189134878876, "lm_q1q2_score": 0.7200625490011986}}
{"text": "theory MultiAssets\nimports Semantics\nbegin\n\nsection \"Assets\"\n\ntext \"We represent Multi-token assets as a function from Token to natural numbers.\"\n(*\nTODO: I want to replace Asset definition with\ntypedef Assets = \"{assets. (\\<forall> t v. fmlookup assets t = Some v \\<longrightarrow> v > 0)} :: ((Token, nat) fmap) set\n\nbut I need to solve this issue https://isabelle.zulipchat.com/#narrow/stream/238552-Beginner-Questions/topic/Is.20it.20possible.20to.20create.20a.20typedef.20.20of.20a.20typedef.3F/near/340510660\n*)\n\ntypedef Assets = \"{assets :: Token \\<Rightarrow> nat. True}\"\n  by auto\n\nsetup_lifting type_definition_Assets\n\ntext\n\"\nThe \\<^emph>\\<open>asset\\<close> definition allows us to create a single-token asset\n\"\nlift_definition asset :: \"Token \\<Rightarrow> nat \\<Rightarrow> Assets\"\n  is \"\\<lambda>tok val. \\<lambda>t. if t = tok then val else 0\"\n  by simp\n\ntext\n\"\nThe \\<^emph>\\<open>assetValue\\<close> definition allow us to obtain how many \\<^emph>\\<open>tokens\\<close> (for a particular token)\nare in the Assets\n\"\nlift_definition assetValue :: \"Token \\<Rightarrow> Assets \\<Rightarrow> nat\" is\n  \"\\<lambda>t a. a t\" .\n\nlemma assetValueOfSingleAsset [simp] : \"assetValue tok (asset tok b) = b\"\n  by transfer simp\n\nlemma assetValueOfDifferentToken [simp] : \"tok1 \\<noteq> tok2 \\<Longrightarrow> assetValue tok1 (asset tok2 b) = 0\"\n  by transfer simp\n\nlemma assetsEqByValue: \"a = b \\<longleftrightarrow> (\\<forall> tok. assetValue tok a = assetValue tok b)\"\n  by transfer auto\n\nsubsection \"Ordering\"\ntext \"\nWe define partial order for assets instead of total order because we cannot compare values of different tokens.\n\"\n\ntext \"We need to define order because Assets can't be negative, so we can only simplify things like\n\\<^term>\\<open>a + (b - a) = b\\<close> if \\<^term>\\<open>a \\<le> b\\<close>.\n\"\ninstantiation Assets :: ord\nbegin\n  lift_definition less_eq_Assets :: \"Assets \\<Rightarrow> Assets \\<Rightarrow> bool\"\n    is \"\\<lambda>a b. \\<forall>t. a t \\<le> b t\" .\n  \n  lift_definition less_Assets :: \"Assets \\<Rightarrow> Assets \\<Rightarrow> bool\"\n    is \"\\<lambda>a b. (\\<forall>rt. a rt \\<le> b rt) \\<and> (\\<exists> st. a st < b st)\" .\n  \n  instance ..\nend\n\ninstantiation Assets :: preorder\nbegin\n  instance proof\n   fix a b c :: Assets\n   show \"a \\<le> a\"\n     by transfer simp\n   show \"a \\<le> b \\<Longrightarrow> b \\<le> c \\<Longrightarrow> a \\<le> c\"\n     using le_trans by transfer blast\n   show \"a < b = ( a \\<le> b \\<and> \\<not>  b \\<le> a)\"\n     by transfer (metis leD leI)\n  qed\nend\n\ninstantiation Assets :: order\nbegin\n  instance proof\n    fix a b :: Assets\n    show \"a \\<le> b \\<Longrightarrow>  b \\<le> a \\<Longrightarrow> a = b\"\n      using le_antisym by transfer blast\n  qed\nend\n\ntext \"If we create a single asset from a multi-asset, then the single asset is going to be lower or\nequal to the multi-asset\"\nlemma singleAsset_leq_than_asset: \"asset t (assetValue t a) \\<le> a\"\n  by transfer simp\n\nsubsection \"Arithmetic\"\n\ninstantiation Assets :: zero\nbegin\n  lift_definition zero_Assets :: Assets\n    is \"\\<lambda>_. 0\"\n    by simp\n  \n  instance ..\nend\n\ntext \"Creating a single asset with 0 tokens is the same as creating the zero_Assets\"\nlemma assetZero [simp] : \"asset tok 0 = 0\"\n  by transfer auto\n\ntext \"If we try to create a single asset from a negative integer is also the same as creating the zero_Assets\"\ncorollary assetOfNegInt [simp] : \"(i :: int) \\<le> 0 \\<Longrightarrow> asset t (nat i) = 0\"\n  by simp\n\ntext \"Trying to count the amount of tokens of the zero_Assets is 0\"\nlemma assetValueOfZero [simp] : \"assetValue t 0 = 0\"\n  by transfer simp\n\ninstantiation Assets :: plus\nbegin\n  lift_definition plus_Assets :: \"Assets \\<Rightarrow> Assets \\<Rightarrow> Assets\"\n    is \"\\<lambda>x y. \\<lambda>tok. x tok + y tok\"\n    by auto\n  \n  instance ..\nend\n\nlemma assetsDistributesPlus : \"asset tok (a + b) = asset tok a + asset tok b\"\n  by transfer auto\n\nlemma assetsJoinPlus : \"asset tok a + asset tok b = asset tok (a + b)\"\n  by (simp add: assetsDistributesPlus)\n\nlemma assetValue_distrib : \"assetValue tok (a + b) = assetValue tok a + assetValue tok b\"\n  by transfer auto\n\ninstantiation Assets :: minus\nbegin\n  lift_definition minus_Assets :: \"Assets \\<Rightarrow> Assets \\<Rightarrow> Assets\"\n    is \"\\<lambda>x y. \\<lambda>tok. x tok - y tok\"\n    by auto\n  \n  instance ..\nend\n\nlemma assetsDistributesMinus : \"asset tok (a - b) = asset tok a - asset tok b\"\n  by transfer auto\n\ninstantiation Assets :: semigroup_add\nbegin\n  instance proof\n    fix a b c :: Assets\n    show \"(a + b) + c = a + (b + c)\"\n      by transfer (simp add: Groups.ab_semigroup_add_class.add_ac(1))\n  qed\nend\n\ninstantiation Assets :: ab_semigroup_add\nbegin\n  instance proof\n    fix a b :: Assets\n    show \"a + b = b + a\"\n      by transfer (simp add: Groups.ab_semigroup_add_class.add.commute)\n  qed\nend\n\n\ninstantiation Assets :: monoid_add\nbegin\n  instance proof\n    fix a :: Assets\n    show \"0 + a = a\"\n      by transfer auto\n    show \"a + 0 = a\"\n      by transfer auto\n  qed\nend\n\n(* TODO: This should be included by monoid_add, but for some reason I cannot delete it *)\ninstantiation Assets :: comm_monoid_add\nbegin\n  instance by standard simp\nend\n\ninstantiation Assets :: cancel_ab_semigroup_add\nbegin\n  instance proof\n    fix a b c :: Assets\n    show \"a + b - a = b\"\n      by transfer force\n    show \"a - b - c = a - (b + c)\"\n      using diff_diff_left by transfer presburger\n  qed\nend\n\ninstantiation Assets :: comm_monoid_diff\nbegin\n  instance proof\n    fix a :: Assets\n    show \"0 - a = 0\"\n      by transfer simp\n  qed\nend\n\ninstantiation Assets :: ordered_ab_semigroup_add\nbegin\n  instance proof\n    fix a b c :: Assets\n    show \"a \\<le> b \\<Longrightarrow> c + a \\<le> c + b\"\n      by transfer simp\n  qed\nend\n\ninstantiation Assets :: ordered_ab_semigroup_add_imp_le\nbegin\n  instance proof\n    fix a b c :: Assets\n    show \"c + a \\<le> c + b \\<Longrightarrow> a \\<le> b\"\n      by transfer simp\n  qed\nend\n\ninstantiation Assets :: canonically_ordered_monoid_add\nbegin\n  instance proof\n    fix a b :: Assets\n    (* TODO: See how to make this proof structured *)\n    have \"a \\<le> b \\<Longrightarrow> \\<exists>c. b = a + c\"\n     apply transfer\n      subgoal for a2 b2\n        apply (subgoal_tac  \"\\<And> x. a2 x \\<le> b2 x \\<Longrightarrow> b2 x = a2 x + (b2 x - a2 x)\")\n         apply fast\n        by simp\n      done\n    also have \"\\<exists>c. b = a + c \\<Longrightarrow> a \\<le> b\"\n      by transfer auto\n    then show \"(a \\<le> b) = (\\<exists>c. b = a + c)\"\n      using calculation by blast\n  qed\nend\n\ninstantiation Assets :: ordered_cancel_comm_monoid_diff\nbegin\n  instance by standard\nend\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/Core/MultiAssets.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.901920681802153, "lm_q2_score": 0.798186787341014, "lm_q1q2_score": 0.7199011714440775}}
{"text": "theory CS_Ch3\nimports Main\nbegin\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 a1 a2) s = aval a1 s + aval a2 s\"\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) = (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\"\napply(induction a)\napply(auto split: aexp.split)\ndone\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\"\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 a1 a2) = plus (asimp a1) (asimp a2)\"\n\nlemma \"aval (asimp a) s = aval a s\"\napply(induction a)\napply(auto simp add: aval_plus)\ndone\n\n(* 3.1 *)\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 a b) = (optimal a \\<and> optimal b)\"\n\nlemma \"optimal (asimp_const a)\"\napply(induction a)\napply(auto split: aexp.split)\ndone\n\n(* 3.2 *)\n\n(* If you view this as a rewriting system that is designed to work only in conjunction\n   with full_asimp, the structure of this function makes sense. We apply full_asimp recursively,\n   so this function can look as few layers deep as it wants into the expression and full_asimp will\n   glue it together. That is, its correctness can be inductively proven. *)\nfun full_plus :: \"aexp \\<Rightarrow> aexp \\<Rightarrow> aexp\" where\n\"full_plus (N i1) (N i2) = N (i1 + i2)\" |\n\"full_plus (N i1) (Plus a (N i2)) = Plus a (N (i1 + i2))\" |\n\"full_plus (Plus a (N i1)) (N i2) = Plus a (N (i1 + i2))\" |\n\"full_plus a (Plus b (N i1)) = Plus (Plus a b) (N i1)\" |\n\"full_plus (Plus a (N i1)) b = Plus (Plus a b) (N i1)\" |\n\"full_plus (N i) a = (if i = 0 then a else Plus (N i) a)\" |\n\"full_plus a (N i) = (if i = 0 then a else Plus a (N i))\" |\n\"full_plus a1 a2 = Plus a1 a2\"\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 a b) = full_plus (full_asimp a) (full_asimp b)\"\n\nlemma aval_full_plus: \"aval (full_plus a b) s = aval a s + aval b s\"\napply(induction rule: full_plus.induct)\napply(auto)\ndone\n\nlemma \"aval (full_asimp a) s = aval a s\"\napply(induction a)\napply(auto simp add: aval_full_plus)\ndone\n\n(* 3.3 *)\n\nfun subst :: \"vname \\<Rightarrow> aexp \\<Rightarrow> aexp \\<Rightarrow> aexp\" where\n\"subst x a (N i1) = N i1\" |\n\"subst x a (V y) = (if x = y then a else (V y))\" |\n\"subst x a (Plus b1 b2) = Plus (subst x a b1) (subst x a b2)\"\n\nlemma subst_lemma: \"aval (subst x a e) s = aval e (s(x := aval a s))\"\napply(induction e)\napply(auto)\ndone\n\nlemma \"aval a1 s = aval a2 s \\<Longrightarrow> aval (subst x a1 e) s = aval (subst x a2 e) s\"\napply(induction e)\napply(auto)\ndone\n\n(* 3.4 is a separate theory, CS_Ch3_Ex4 *)\n\n(* 3.5 *)\ndatatype aexp2 = N2 int | V2 vname | Plus2 aexp2 aexp2 | PostIncr2 vname | Div2 aexp2 aexp2\nfun aval2 :: \"aexp2 \\<Rightarrow> state \\<Rightarrow> (val \\<times> state) option\" where\n\"aval2 (N2 i) s = Some (i, s)\" |\n\"aval2 (V2 x) s = Some (s x, s)\" |\n\"aval2 (Plus2 a b) s = (case (aval2 a s) of Some (a', s') \\<Rightarrow> \n  (case (aval2 b s') of Some (b', s'') \\<Rightarrow> Some (a' + b', s'') | None \\<Rightarrow> None) | None \\<Rightarrow> None)\" |\n\"aval2 (PostIncr2 x) s = Some (s x, s(x := (s x) + 1))\" |\n\"aval2 (Div2 a b) s = (case (aval2 b s) of Some (b', s') \\<Rightarrow> (if b' = 0 then None else Some (\n  case (aval2 a s') of Some (a', s'') \\<Rightarrow> (a' div b', s''))) | None \\<Rightarrow> None)\"\n\nlemma \"aval2 (Div2 (N2 3) (Plus2 (N2 1) (V2 ''x''))) (\\<lambda>x. -1) = None\"\napply(auto)\ndone\n\nlemma \"case aval2 (Div2 (N2 3) (PostIncr2 ''x'')) (\\<lambda>x. 1) of Some (a, b) \\<Rightarrow> (a = 3 \\<and> b(''x'') = 2) | None \\<Rightarrow> False\"\napply(auto)\ndone\n\n(* 3.6 *)\n\ndatatype lexp = Nl int | Vl vname | Plusl lexp lexp | LET vname lexp lexp\nfun lval :: \"lexp \\<Rightarrow> state \\<Rightarrow> int\" where\n\"lval (Nl i) s = i\" |\n\"lval (Vl x) s = s x\" |\n\"lval (Plusl a b) s = lval a s + lval b s\" |\n\"lval (LET x val body) s = lval body (s(x := lval val s))\"\n\nfun inline :: \"lexp \\<Rightarrow> aexp\" where\n\"inline (Nl i) = (N i)\" |\n\"inline (Vl x) = (V x)\" |\n\"inline (Plusl a b) = Plus (inline a) (inline b)\" |\n\"inline (LET x val body) = subst x (inline val) (inline body)\"\n\nlemma \"lval e s = aval (inline e) s\"\napply(induction e arbitrary: s)\napply(auto simp add: subst_lemma)\ndone\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 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 b\\<^sub>1 b\\<^sub>2 = And b\\<^sub>1 b\\<^sub>2\"\n\nfun less :: \"aexp \\<Rightarrow> aexp \\<Rightarrow> bexp\" where\n\"less (aexp.N n\\<^sub>1) (aexp.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\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\n(* 3.7 *)\n\nfun Eq :: \"aexp \\<Rightarrow> aexp \\<Rightarrow> bexp\" where\n\"Eq a b = And (Not (Less a b)) (Not (Less b a))\"\n\nlemma \"bval (Eq a b) s = (aval a s = aval b s)\"\napply(auto)\ndone\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 (Le a b) s = (aval a s \\<le> aval b s)\"\napply(auto)\ndone\n\n(* 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 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\nfun b2ifexp :: \"bexp \\<Rightarrow> ifexp\" where\n\"b2ifexp (Less a b) = (Less2 a 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 (Bc b) = Bc2 b\"\n\nlemma \"bval b s = ifval (b2ifexp b) s\"\napply(induction b)\napply(auto)\ndone\n\nfun if2bexp :: \"ifexp \\<Rightarrow> bexp\" where\n\"if2bexp (Bc2 b) = Bc b\" |\n\"if2bexp (If c t f) = And (Not (And (if2bexp c) (Not (if2bexp t)))) (Not (And (Not (if2bexp c)) (Not (if2bexp f))))\" |\n\"if2bexp (Less2 a b) = Less a b\"\n\nlemma \"ifval i s = bval (if2bexp i) s\"\napply(induction i)\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 b) s = (\\<not> pbval b s)\" |\n\"pbval (AND b\\<^sub>1 b\\<^sub>2) s = (pbval b\\<^sub>1 s \\<and> pbval b\\<^sub>2 s)\" |\n\"pbval (OR b\\<^sub>1 b\\<^sub>2) s = (pbval b\\<^sub>1 s \\<or> pbval b\\<^sub>2 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\nfun nnf :: \"pbexp \\<Rightarrow> pbexp\" where\n\"nnf (VAR x) = VAR x\" |\n\"nnf (NOT (VAR x)) = (NOT (VAR x))\" |\n\"nnf (NOT (AND a b)) = OR (nnf (NOT a)) (nnf (NOT b))\" |\n\"nnf (NOT (OR a b)) = AND (nnf (NOT a)) (nnf (NOT b))\" |\n\"nnf (NOT (NOT b)) = nnf b \" |\n\"nnf (AND a b) = AND (nnf a) (nnf b)\" |\n\"nnf (OR a b) = OR (nnf a) (nnf b)\"\n\nlemma \"is_nnf (nnf b)\"\napply(induction b rule: nnf.induct)\napply(auto)\ndone\n\nfun is_dnf :: \"pbexp \\<Rightarrow> bool\" where\n\"is_dnf (VAR x) = True\" |\n(* since we assume NNF, we don't need to handle NOT *)\n\"is_dnf (NOT x) = True\" |\n\"is_dnf (AND (OR _ _) _) = False\" |\n\"is_dnf (AND _ (OR _ _)) = False\" |\n\"is_dnf (AND a b) = (is_dnf a \\<and> is_dnf b)\" |\n\"is_dnf (OR a b) = (is_dnf a \\<and> is_dnf b)\"\n\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 (OR a b) = OR (dnf_of_nnf a) (dnf_of_nnf b)\" |\n\"dnf_of_nnf (AND (OR o\\<^sub>1 o\\<^sub>2) a) = OR (AND o\\<^sub>1 a) (AND o\\<^sub>2 a)\" |\n\"dnf_of_nnf (AND a (OR o\\<^sub>1 o\\<^sub>2)) = OR (AND o\\<^sub>1 a) (AND o\\<^sub>2 a)\" |\n\"dnf_of_nnf (AND a b) = AND (dnf_of_nnf a) (dnf_of_nnf b)\"\n\nlemma \"pbval (dnf_of_nnf b) s = pbval b s\"\napply(induction b rule: dnf_of_nnf.induct)\napply(auto)\ndone\n\nlemma \"is_nnf b \\<Longrightarrow> is_nnf (dnf_of_nnf b)\"\napply(induction b rule: dnf_of_nnf.induct)\napply(auto)\ndone\n\ndatatype instr = LOADI val | LOAD vname | ADD\ntype_synonym stack = \"val list\"\nabbreviation \"hd2 xs == hd(tl xs)\"\nabbreviation \"tl2 xs == 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 _ (h # h2 # rst) = Some ((h2 + h) # rst)\" |\n\"exec1 ADD _ _ = None\"\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 option\" where\n\"exec [] _ stk = Some (stk)\" |\n\"exec (i # is) s stk = (case (exec1 i s stk) of Some stk' \\<Rightarrow> exec is s stk' | 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\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 = Some 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 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 *)\ntype_synonym reg = nat\ndatatype reginstr = LDI int reg | LD vname reg | ADD reg reg\n\nfun regexec1 :: \"reginstr \\<Rightarrow> state \\<Rightarrow> (reg \\<Rightarrow> int) \\<Rightarrow> reg \\<Rightarrow> int\" where\n\"regexec1 (LDI v r) s file = file(r := v)\" |\n\"regexec1 (LD x r) s file = file(r := s x)\" |\n\"regexec1 (ADD r\\<^sub>1 r\\<^sub>2) s file = file(r\\<^sub>1 := (file r\\<^sub>1) + (file r\\<^sub>2))\"\n\nfun regexec :: \"reginstr list \\<Rightarrow> state \\<Rightarrow> (reg \\<Rightarrow> int) \\<Rightarrow> reg \\<Rightarrow> int\" where\n\"regexec [] s file = file\" |\n\"regexec (i # is) s file = regexec is s (regexec1 i s file)\"\n\nfun regcomp :: \"aexp \\<Rightarrow> reg \\<Rightarrow> reginstr list\" where\n\"regcomp (N n) r = [LDI n r]\" |\n\"regcomp (V x) r = [LD x r]\" |\n\"regcomp (Plus e\\<^sub>1 e\\<^sub>2) r = regcomp e\\<^sub>1 r @ regcomp e\\<^sub>2 (r+1) @ [ADD r (r+1)]\"\n\nlemma regexec_append: \"regexec (is\\<^sub>1 @ is\\<^sub>2) s file = regexec is\\<^sub>2 s (regexec is\\<^sub>1 s file)\"\napply(induction is\\<^sub>1 arbitrary: \"file\")\napply(auto)\ndone\n\nlemma regcomp_dont_touch_small_regs: \"q < r \\<Longrightarrow> regexec (regcomp a r) s file q = file q\"\napply(induction a arbitrary: r \"file\")\napply(auto simp add: regexec_append)\ndone\n\nlemma \"(regexec (regcomp a r) s file) r = aval a s\"\napply(induction a arbitrary: s r \"file\")\napply(auto simp add: regexec_append regcomp_dont_touch_small_regs)\ndone\n\n(* 3.12 *)\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 val) s file = file(0 := val)\" |\n\"exec10 (LD0 vname) s file = file(0 := s vname)\" |\n\"exec10 (MV0 reg) s file = file(reg := file 0)\" |\n\"exec10 (ADD0 reg) s file = file(0 := (file 0) + (file reg))\"\n\nfun exec0 :: \"instr0 list \\<Rightarrow> state \\<Rightarrow> (reg \\<Rightarrow> int) \\<Rightarrow> reg \\<Rightarrow> int\" where\n\"exec0 [] s file = file\" |\n\"exec0 (i # is) s file = exec0 is s (exec10 i s file)\"\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 e\\<^sub>1 e\\<^sub>2) r = (comp0 e\\<^sub>1 (r+1)) @ [MV0 (r+1)] @ (comp0 e\\<^sub>2 (r+2)) @ [ADD0 (r+1)]\"\n\nlemma exec0_append: \"exec0 (is\\<^sub>1 @ is\\<^sub>2) s file = exec0 is\\<^sub>2 s (exec0 is\\<^sub>1 s file)\"\napply(induction is\\<^sub>1 arbitrary: \"file\")\napply(auto)\ndone\n\nlemma comp0_register_preservation: \"0 \\<noteq> q \\<Longrightarrow> q < r \\<Longrightarrow> exec0 (comp0 a r) s file q = file q\"\napply(induction a arbitrary: r q \"file\")\napply(auto simp add: exec0_append)\ndone\n\nlemma \"exec0 (comp0 a r) s rs 0 = aval a s\"\napply(induction a arbitrary: r s rs)\napply(auto simp add: exec0_append comp0_register_preservation)\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_Ch3.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206686206199, "lm_q2_score": 0.7981867849406659, "lm_q1q2_score": 0.7199011587578283}}
{"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_MSortBUPermutes\n  imports \"../../Test_Base\"\nbegin\n\ndatatype 'a list = nil2 | cons2 \"'a\" \"'a list\"\n\ndatatype Nat = Z | S \"Nat\"\n\nfun map :: \"('a => 'b) => 'a list => 'b list\" where\n  \"map f (nil2) = nil2\"\n| \"map f (cons2 y xs) = cons2 (f y) (map f xs)\"\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 mergingbu :: \"(Nat list) list => Nat list\" where\n  \"mergingbu (nil2) = nil2\"\n| \"mergingbu (cons2 xs (nil2)) = xs\"\n| \"mergingbu (cons2 xs (cons2 z x2)) =\n     mergingbu (pairwise (cons2 xs (cons2 z x2)))\"\n  by pat_completeness auto\n\nfun msortbu :: \"Nat list => Nat list\" where\n  \"msortbu x = mergingbu (map (% (y :: Nat) => cons2 y (nil2)) x)\"\n\nfun elem :: \"'a => 'a list => bool\" where\n  \"elem x (nil2) = False\"\n| \"elem x (cons2 z xs) = ((z = x) | (elem x xs))\"\n\nfun deleteBy :: \"('a => ('a => bool)) => 'a => 'a list =>\n                 'a list\" where\n  \"deleteBy x y (nil2) = nil2\"\n| \"deleteBy x y (cons2 y2 ys) =\n     (if (x y) y2 then ys else cons2 y2 (deleteBy x y ys))\"\n\nfun isPermutation :: \"'a list => 'a list => bool\" where\n  \"isPermutation (nil2) (nil2) = True\"\n| \"isPermutation (nil2) (cons2 z x2) = False\"\n| \"isPermutation (cons2 x3 xs) y =\n     ((elem x3 y) &\n        (isPermutation\n           xs (deleteBy (% (x4 :: 'a) => % (x5 :: 'a) => (x4 = x5)) x3 y)))\"\n\ntheorem property0 :\n  \"isPermutation (msortbu 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_sort_nat_MSortBUPermutes.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206712569267, "lm_q2_score": 0.7981867777396212, "lm_q1q2_score": 0.7199011543673225}}
{"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_MainRLT\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  \"a \\<noteq> 0 \\<Longrightarrow> a * x\\<^sup>2 + b * x + c = 0 \\<longleftrightarrow> (2 * a * x + b)\\<^sup>2 = discrim a b c\"\nby (simp add: discrim_def) algebra\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\nlemma Rats_solution_QE:\n  assumes \"a \\<in> \\<rat>\" \"b \\<in> \\<rat>\" \"a \\<noteq> 0\"\n  and \"a*x^2 + b*x + c = 0\"\n  and \"sqrt (discrim a b c) \\<in> \\<rat>\"\n  shows \"x \\<in> \\<rat>\" \nusing assms(1,2,5) discriminant_iff[THEN iffD1, OF assms(3,4)] by auto\n\nlemma Rats_solution_QE_converse:\n  assumes \"a \\<in> \\<rat>\" \"b \\<in> \\<rat>\"\n  and \"a*x^2 + b*x + c = 0\"\n  and \"x \\<in> \\<rat>\"\n  shows \"sqrt (discrim a b c) \\<in> \\<rat>\"\nproof -\n  from assms(3) have \"discrim a b c = (2*a*x+b)^2\" unfolding discrim_def by algebra\n  hence \"sqrt (discrim a b c) = \\<bar>2*a*x+b\\<bar>\" by (simp)\n  thus ?thesis using \\<open>a \\<in> \\<rat>\\<close> \\<open>b \\<in> \\<rat>\\<close> \\<open>x \\<in> \\<rat>\\<close> 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/Library/Quadratic_Discriminant.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206686206199, "lm_q2_score": 0.7981867729389246, "lm_q1q2_score": 0.7199011479332098}}
{"text": "section \\<open>Conjunctive and Disjunctive Functions\\<close>\n\n(*\n    Author: Viorel Preoteasa\n*)\n\ntheory Conj_Disj\nimports Main\nbegin\n\ntext\\<open>\nThis theory introduces the definitions and some properties for \nconjunctive, disjunctive, universally conjunctive, and universally \ndisjunctive functions.\n\\<close>\n\nlocale conjunctive =\n  fixes inf_b :: \"'b \\<Rightarrow> 'b \\<Rightarrow> 'b\"\n  and inf_c :: \"'c \\<Rightarrow> 'c \\<Rightarrow> 'c\"\n  and times_abc :: \"'a \\<Rightarrow> 'b \\<Rightarrow> 'c\"\nbegin\n\ndefinition\n  \"conjunctive = {x . (\\<forall> y z . times_abc x (inf_b y z) = inf_c (times_abc x y) (times_abc x z))}\"\n\nlemma conjunctiveI:\n  assumes \"(\\<And>b c. times_abc a (inf_b b c) = inf_c (times_abc a b) (times_abc a c))\"\n  shows \"a \\<in> conjunctive\"\n  using assms by (simp add: conjunctive_def)\n\nlemma conjunctiveD: \"x \\<in> conjunctive \\<Longrightarrow> times_abc x (inf_b y z) = inf_c (times_abc x y) (times_abc x z)\"\n  by (simp add: conjunctive_def)\n\nend\n\ninterpretation Apply: conjunctive \"inf::'a::semilattice_inf \\<Rightarrow> 'a \\<Rightarrow> 'a\"\n  \"inf::'b::semilattice_inf \\<Rightarrow> 'b \\<Rightarrow> 'b\" \"\\<lambda> f . f\"\n  done\n\ninterpretation Comp: conjunctive \"inf::('a::lattice \\<Rightarrow> 'a) \\<Rightarrow> ('a \\<Rightarrow> 'a) \\<Rightarrow> ('a \\<Rightarrow> 'a)\" \n  \"inf::('a::lattice \\<Rightarrow> 'a) \\<Rightarrow> ('a \\<Rightarrow> 'a) \\<Rightarrow> ('a \\<Rightarrow> 'a)\" \"(o)\"\n  done\n\nlemma \"Apply.conjunctive = Comp.conjunctive\"\n  apply (simp add: Apply.conjunctive_def Comp.conjunctive_def)\n  apply safe\n  apply (simp_all add: fun_eq_iff inf_fun_def)\n  apply (drule_tac x = \"\\<lambda> u . y\" in spec)\n  apply (drule_tac x = \"\\<lambda> u . z\" in spec)\n  by simp\n\nlocale disjunctive =\n  fixes sup_b :: \"'b \\<Rightarrow> 'b \\<Rightarrow> 'b\"\n  and sup_c :: \"'c \\<Rightarrow> 'c \\<Rightarrow> 'c\"\n  and times_abc :: \"'a \\<Rightarrow> 'b \\<Rightarrow> 'c\"\nbegin\n\ndefinition\n  \"disjunctive = {x . (\\<forall> y z . times_abc x (sup_b y z) = sup_c (times_abc x y) (times_abc x z))}\"\n\nlemma disjunctiveI:\n  assumes \"(\\<And>b c. times_abc a (sup_b b c) = sup_c (times_abc a b) (times_abc a c))\"\n  shows \"a \\<in> disjunctive\"\n  using assms by (simp add: disjunctive_def)\n\nlemma disjunctiveD: \"x \\<in> disjunctive \\<Longrightarrow> times_abc x (sup_b y z) = sup_c (times_abc x y) (times_abc x z)\"\n  by (simp add: disjunctive_def)\n\nend\n\ninterpretation Apply: disjunctive \"sup::'a::semilattice_sup \\<Rightarrow> 'a \\<Rightarrow> 'a\"\n  \"sup::'b::semilattice_sup \\<Rightarrow> 'b \\<Rightarrow> 'b\" \"\\<lambda> f . f\"\n  done\n\ninterpretation Comp: disjunctive \"sup::('a::lattice \\<Rightarrow> 'a) \\<Rightarrow> ('a \\<Rightarrow> 'a) \\<Rightarrow> ('a \\<Rightarrow> 'a)\" \n  \"sup::('a::lattice \\<Rightarrow> 'a) \\<Rightarrow> ('a \\<Rightarrow> 'a) \\<Rightarrow> ('a \\<Rightarrow> 'a)\" \"(o)\"\n  done\n\nlemma apply_comp_disjunctive: \"Apply.disjunctive = Comp.disjunctive\"\n  apply (simp add: Apply.disjunctive_def Comp.disjunctive_def)\n  apply safe\n  apply (simp_all add: fun_eq_iff sup_fun_def)\n  apply (drule_tac x = \"\\<lambda> u . y\" in spec)\n  apply (drule_tac x = \"\\<lambda> u . z\" in spec)\n  by simp\n\nlocale Conjunctive =\n  fixes Inf_b :: \"'b set \\<Rightarrow> 'b\"\n  and Inf_c :: \"'c set \\<Rightarrow> 'c\"\n  and times_abc :: \"'a \\<Rightarrow> 'b \\<Rightarrow> 'c\"\nbegin\n\ndefinition\n  \"Conjunctive = {x . (\\<forall> X . times_abc x (Inf_b X) = Inf_c ((times_abc x) ` X) )}\"\n\nlemma ConjunctiveI:\n  assumes \"\\<And>A. times_abc a (Inf_b A) = Inf_c ((times_abc a) ` A)\"\n  shows \"a \\<in> Conjunctive\"\n  using assms by (simp add: Conjunctive_def)\n\nlemma ConjunctiveD:\n  assumes \"a \\<in> Conjunctive\"\n  shows \"times_abc a (Inf_b A) = Inf_c ((times_abc a) ` A)\"\n  using assms by (simp add: Conjunctive_def)\n\nend\n\ninterpretation Apply: Conjunctive Inf Inf \"\\<lambda> f . f\"\n  done\n\ninterpretation Comp: Conjunctive \"Inf::(('a::complete_lattice \\<Rightarrow> 'a) set) \\<Rightarrow> ('a \\<Rightarrow> 'a)\" \n  \"Inf::(('a::complete_lattice \\<Rightarrow> 'a) set) \\<Rightarrow> ('a \\<Rightarrow> 'a)\" \"(o)\"\n  done\n\nlemma \"Apply.Conjunctive = Comp.Conjunctive\"\nproof\n  show \"Apply.Conjunctive \\<subseteq> (Comp.Conjunctive :: ('a \\<Rightarrow> 'a) set)\"\n  proof\n    fix f\n    assume \"f \\<in> (Apply.Conjunctive :: ('a \\<Rightarrow> 'a) set)\"\n    then have *: \"f (Inf A) = (INF a\\<in>A. f a)\" for A\n      by (auto dest!: Apply.ConjunctiveD)\n    show \"f \\<in> (Comp.Conjunctive :: ('a \\<Rightarrow> 'a) set)\"\n    proof (rule Comp.ConjunctiveI)\n      fix G :: \"('a \\<Rightarrow> 'a) set\"\n      from * have \"f (INF f\\<in>G. f a) = Inf (f ` (\\<lambda>f. f a) ` G)\"\n        for a :: 'a .\n      then show \"f \\<circ> Inf G = Inf (comp f ` G)\"\n        by (simp add: fun_eq_iff image_comp)\n    qed\n  qed\n  show \"Comp.Conjunctive \\<subseteq> (Apply.Conjunctive :: ('a \\<Rightarrow> 'a) set)\"\n  proof\n    fix f\n    assume \"f \\<in> (Comp.Conjunctive :: ('a \\<Rightarrow> 'a) set)\"\n    then have *: \"f \\<circ> Inf G = (INF g\\<in>G. f \\<circ> g)\" for G :: \"('a \\<Rightarrow> 'a) set\"\n      by (auto dest!: Comp.ConjunctiveD)\n    show \"f \\<in> (Apply.Conjunctive :: ('a \\<Rightarrow> 'a) set)\"\n    proof (rule Apply.ConjunctiveI)\n      fix A :: \"'a set\"\n      from * have \"f \\<circ> (INF a\\<in>A. (\\<lambda>b :: 'a. a)) = Inf ((\\<circ>) f ` (\\<lambda>a b. a) ` A)\" .\n      then show \"f (Inf A) = Inf (f ` A)\"\n        by (simp add: fun_eq_iff image_comp)\n    qed\n  qed\nqed  \n        \nlocale Disjunctive =\n  fixes Sup_b :: \"'b set \\<Rightarrow> 'b\"\n  and Sup_c :: \"'c set \\<Rightarrow> 'c\"\n  and times_abc :: \"'a \\<Rightarrow> 'b \\<Rightarrow> 'c\"\nbegin\n\ndefinition\n  \"Disjunctive = {x . (\\<forall> X . times_abc x (Sup_b X) = Sup_c ((times_abc x) ` X) )}\"\n\nlemma DisjunctiveI:\n  assumes \"\\<And>A. times_abc a (Sup_b A) = Sup_c ((times_abc a) ` A)\"\n  shows \"a \\<in> Disjunctive\"\n  using assms by (simp add: Disjunctive_def)\n\nlemma DisjunctiveD: \"x \\<in> Disjunctive \\<Longrightarrow> times_abc x (Sup_b X) = Sup_c ((times_abc x) ` X)\"\n  by (simp add: Disjunctive_def)\n\nend\n\ninterpretation Apply: Disjunctive Sup Sup \"\\<lambda> f . f\"\n  done\n\ninterpretation Comp: Disjunctive \"Sup::(('a::complete_lattice \\<Rightarrow> 'a) set) \\<Rightarrow> ('a \\<Rightarrow> 'a)\" \n  \"Sup::(('a::complete_lattice \\<Rightarrow> 'a) set) \\<Rightarrow> ('a \\<Rightarrow> 'a)\" \"(o)\"\n  done\n\nlemma \"Apply.Disjunctive = Comp.Disjunctive\"\nproof\n  show \"Apply.Disjunctive \\<subseteq> (Comp.Disjunctive :: ('a \\<Rightarrow> 'a) set)\"\n  proof\n    fix f\n    assume \"f \\<in> (Apply.Disjunctive :: ('a \\<Rightarrow> 'a) set)\"\n    then have *: \"f (Sup A) = (SUP a\\<in>A. f a)\" for A\n      by (auto dest!: Apply.DisjunctiveD)\n    show \"f \\<in> (Comp.Disjunctive :: ('a \\<Rightarrow> 'a) set)\"\n    proof (rule Comp.DisjunctiveI)\n      fix G :: \"('a \\<Rightarrow> 'a) set\"\n      from * have \"f (SUP f\\<in>G. f a) = Sup (f ` (\\<lambda>f. f a) ` G)\"\n        for a :: 'a .\n      then show \"f \\<circ> Sup G = Sup (comp f ` G)\"\n        by (simp add: fun_eq_iff image_comp)\n    qed\n  qed\n  show \"Comp.Disjunctive \\<subseteq> (Apply.Disjunctive :: ('a \\<Rightarrow> 'a) set)\"\n  proof\n    fix f\n    assume \"f \\<in> (Comp.Disjunctive :: ('a \\<Rightarrow> 'a) set)\"\n    then have *: \"f \\<circ> Sup G = (SUP g\\<in>G. f \\<circ> g)\" for G :: \"('a \\<Rightarrow> 'a) set\"\n      by (auto dest!: Comp.DisjunctiveD)\n    show \"f \\<in> (Apply.Disjunctive :: ('a \\<Rightarrow> 'a) set)\"\n    proof (rule Apply.DisjunctiveI)\n      fix A :: \"'a set\"\n      from * have \"f \\<circ> (SUP a\\<in>A. (\\<lambda>b :: 'a. a)) = Sup ((\\<circ>) f ` (\\<lambda>a b. a) ` A)\" .\n      then show \"f (Sup A) = Sup (f ` A)\"\n        by (simp add: fun_eq_iff image_comp)\n    qed\n  qed\nqed  \n\n\n\nlemma [simp]: \"F \\<in> Apply.conjunctive \\<Longrightarrow> mono F\"\n  apply (simp add: Apply.conjunctive_def mono_def)\n  apply safe\n  apply (drule_tac x = \"x\" in spec)\n  apply (drule_tac x = \"y\" in spec)\n  apply (subgoal_tac \"inf x y = x\")\n  apply simp\n  apply (subgoal_tac \"inf (F x) (F y) \\<le> F y\")\n  apply simp\n  apply (rule inf_le2)\n  apply (rule antisym)\n  by simp_all\n\nlemma [simp]: \"(F::'a::complete_lattice \\<Rightarrow> 'b::complete_lattice) \\<in> Apply.Conjunctive \\<Longrightarrow> F top = top\"\n  apply (simp add: Apply.Conjunctive_def)\n  apply (drule_tac x=\"{}\" in spec)\n  by simp\n\nlemma [simp]: \"(F::'a::complete_lattice \\<Rightarrow> 'b::complete_lattice) \\<in> Apply.Disjunctive \\<Longrightarrow> F \\<in> Apply.disjunctive\"\n  apply (simp add: Apply.Disjunctive_def Apply.disjunctive_def)\n  apply safe\n  apply (drule_tac x = \"{y, z}\" in spec)\n  by simp\n\nlemma [simp]: \"F \\<in> Apply.disjunctive \\<Longrightarrow> mono F\"\n  apply (simp add: Apply.disjunctive_def mono_def)\n  apply safe\n  apply (drule_tac x = \"x\" in spec)\n  apply (drule_tac x = \"y\" in spec)\n  apply (subgoal_tac \"sup x y = y\")\n  apply simp\n  apply (subgoal_tac \"F x \\<le> sup (F x) (F y)\")\n  apply simp\n  apply (rule sup_ge1)\n  apply (rule antisym)\n  apply simp\n  by (rule sup_ge2)\n\nlemma [simp]: \"(F::'a::complete_lattice \\<Rightarrow> 'b::complete_lattice) \\<in> Apply.Disjunctive \\<Longrightarrow> F bot = bot\"\n  apply (simp add: Apply.Disjunctive_def)\n  apply (drule_tac x=\"{}\" in spec)\n  by simp\n\nlemma weak_fusion: \"h \\<in> Apply.Disjunctive \\<Longrightarrow> mono f \\<Longrightarrow> mono g \\<Longrightarrow> \n    h o f \\<le> g o h \\<Longrightarrow> h (lfp f) \\<le> lfp g\"\n  apply (rule_tac P = \"\\<lambda> x . h x \\<le> lfp g\" in lfp_ordinal_induct, simp_all)\n  apply (rule_tac y = \"g (h S)\" in order_trans)\n  apply (simp add: le_fun_def)\n  apply (rule_tac y = \"g (lfp g)\" in order_trans)\n  apply (rule_tac f = g in monoD, simp_all)\n  apply (simp add: lfp_unfold [symmetric])\n  apply (simp add: Apply.DisjunctiveD)\n  by (rule SUP_least, blast)\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/LatticeProperties/Conj_Disj.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314768368161, "lm_q2_score": 0.8128673155708975, "lm_q1q2_score": 0.7199008811614322}}
{"text": "theory mLimit\n  imports msucc\nbegin\n\ncontext Ordinal_Model \nbegin\n\nlemma mlimit_mord :\n  assumes u:  \"u : mLimit\"\n  shows \"u : mOrd\"\n  using u unfolding mLimit_def has_ty_def\n  by auto\n\nlemma mlimitI : \n  assumes u : \"u : Limit\"\n  shows \"<ord, u> : mLimit\"\n  using u mordI[OF limit_ord[OF u]] mord_snd_eq\n  unfolding mLimit_def has_ty_def by auto\n\nlemma mlimitE :\n  assumes u : \"u : mLimit\"\n  obtains u' where \"u' : Limit\" \"u = <ord, u'>\"\n  using mordE[OF mlimit_mord[OF u]] u ord_snd_eq\n  unfolding mLimit_def has_ty_def by metis\n  \nlemma mlimit_mlt_mzero : \n  assumes u:\"u : mLimit\"\n  shows \"m0 \\<lless> u\"\nproof (rule mlimitE[OF u], simp, unfold mzero_def,\n       rule mltI[OF zero_ord limit_ord], auto)\n  fix u' assume \"u' : Limit\" \n  thus \"0 < u'\" \n    using limit_lt_zero by auto\nqed\n\nlemma mlimit_mlt_msucc : \n  assumes u:\"u : mLimit\"\n      and bu:\"b \\<lless> u\"\n    shows \"msucc b \\<lless> u\"\nproof (rule mlimitE[OF u])\n  fix u' \n  assume u':\"u' : Limit\" \"u = <ord,u'>\"\n  moreover obtain b' \n    where b':\"b' : Ord\" \"b = <ord, b'>\"\n    using mordE[OF mlt_mord1[OF bu]] .\n  ultimately have \"b' < u'\"\n    using mltD bu by auto\n  hence \"succ b' < u'\"\n    using limit_lt_succ[OF u'(1) b'(1)] by auto  \n  thus \"msucc b \\<lless> u\"\n    unfolding b' u' msucc_eq[OF b'(1)]\n    using mltI[OF succ_ord[OF b'(1)] limit_ord[OF u'(1)]] \n    by auto\nqed\n\nlemma mlimit_mltI :\n  assumes zero : \"m0 \\<lless> u\"\n      and succ : \"\\<And>j. j \\<lless> u \\<Longrightarrow> msucc j \\<lless> u\"\n    shows \"u : mLimit\"\nproof (rule mordE[OF mlt_mord2[OF zero]])\n  fix u' \n  assume u' : \"u' : Ord\" \"u = <ord, u'>\"\n  have \"0 < u'\"\n    using mltD zero unfolding mzero_def u'\n    by auto\n  moreover have \"\\<And>j'. j' : Ord \\<Longrightarrow> j' < u' \\<Longrightarrow> succ j' < u'\"\n  proof -\n    fix j' assume \"j' : Ord\" \"j' < u'\"\n    hence \"<ord, j'> \\<lless> u\" \n      using mltI[OF _ u'(1)] unfolding u' by auto\n    hence \"<ord, succ j'> \\<lless> u\"\n      using succ msucc_eq[OF \\<open>j' : Ord\\<close>] by metis\n    thus \"succ j' < u'\"\n      using mltD unfolding u' by auto\n  qed\n  ultimately have \"u' : Limit\" \n    using u'(1)\n    unfolding Limit_def inter_ty_def has_ty_def tall_def\n    by auto\n  thus \"u : mLimit\"\n    unfolding u'(2)\n    by (rule mlimitI)\nqed\n\ntheorem mlimit_def_ax :\n  \"mLimit = (mOrd \\<triangle> (\\<lambda>\\<mu>. m0 \\<lless> \\<mu> \\<and> (m\\<forall>j : mOrd. j \\<lless> \\<mu> \\<longrightarrow> msucc j \\<lless> \\<mu>)))\"\n  using mlimit_mltI mlimit_mlt_mzero mlimit_mlt_msucc mlimit_mord mord_m mlt_mord1\n  unfolding mtall_def inter_ty_def has_ty_def mall_def tall_def by meson\n  \ntheorem momega_mlimit : \n  \"m\\<omega> : mLimit\"\n  unfolding momega_def\n  by (rule mlimitI[OF omega_typ])\n\nlemmas momega_m =\n  mord_m[OF mlimit_mord[OF momega_mlimit]]\n\nlemma momega_disj : \n  assumes u : \"u : mLimit\"\n  shows \"u = m\\<omega> \\<or> m\\<omega> \\<lless> u\"\nproof (rule mlimitE[OF u])\n  fix u' \n  assume u': \"u' : Limit\" \"u = <ord,u'>\"\n  hence \"u' = \\<omega> \\<or> \\<omega> < u'\"\n    using omega_ax by auto\n  thus \"u = m\\<omega> \\<or> m\\<omega> \\<lless> u\"\n    unfolding u' momega_def \n    using mltI[OF omega_ord limit_ord[OF u'(1)]] by auto\nqed\n\nlemma mlimit_ax :\n  \"m\\<forall>\\<mu> : mLimit. \\<mu> = m\\<omega> \\<or> m\\<omega> \\<lless> \\<mu>\"\n  unfolding mtall_def\n  using momega_disj by auto\n    \n  \n\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/Model/mLimit.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314738181875, "lm_q2_score": 0.8128673155708975, "lm_q1q2_score": 0.7199008787076877}}
{"text": "theory MyList\n  imports Main\nbegin\ndeclare [[names_short]]  \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\nlemma rev_app [simp]: \"rev(app xs ys) = app (rev ys) (rev xs)\"\n  apply(induction xs)\n  apply(auto)\n  done\ntheorem rev_rev [simp]: \"rev(rev xs) = xs\"\n  apply(induction xs)\n  apply(auto)\n  done\n\nend\n", "meta": {"author": "HyunggyuJang", "repo": "Isabelle", "sha": "725c866251790c808116638c28c115207938086a", "save_path": "github-repos/isabelle/HyunggyuJang-Isabelle", "path": "github-repos/isabelle/HyunggyuJang-Isabelle/Isabelle-725c866251790c808116638c28c115207938086a/MyList.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8962513731336202, "lm_q2_score": 0.8031737940012417, "lm_q1q2_score": 0.7198456157385523}}
{"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_list_perm_trans\nimports \"../../Test_Base\"\nbegin\n\ndatatype 'a list = nil2 | cons2 \"'a\" \"'a list\"\n\nfun elem :: \"'a => 'a list => bool\" where\n\"elem x (nil2) = False\"\n| \"elem x (cons2 z xs) = ((z = x) | (elem x xs))\"\n\nfun deleteBy :: \"('a => ('a => bool)) => 'a => 'a list =>\n                 'a list\" where\n\"deleteBy x y (nil2) = nil2\"\n| \"deleteBy x y (cons2 y2 ys) =\n     (if (x y) y2 then ys else cons2 y2 (deleteBy x y ys))\"\n\nfun isPermutation :: \"'a list => 'a list => bool\" where\n\"isPermutation (nil2) (nil2) = True\"\n| \"isPermutation (nil2) (cons2 z x2) = False\"\n| \"isPermutation (cons2 x3 xs) y =\n     ((elem x3 y) &\n        (isPermutation\n           xs (deleteBy (% (x4 :: 'a) => % (x5 :: 'a) => (x4 = x5)) x3 y)))\"\n\ntheorem property0 :\n  \"((isPermutation xs ys) ==>\n      ((isPermutation ys zs) ==> (isPermutation xs zs)))\"\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_list_perm_trans.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513620489618, "lm_q2_score": 0.8031737892899222, "lm_q1q2_score": 0.7198456026131187}}
{"text": "(*  Title:      HOL/Analysis/L2_Norm.thy\n    Author:     Brian Huffman, Portland State University\n*)\n\nsection \\<open>Square root of sum of squares\\<close>\n\ntheory L2_Norm\nimports NthRoot\nbegin\n\ndefinition\n  \"setL2 f A = sqrt (\\<Sum>i\\<in>A. (f i)\\<^sup>2)\"\n\nlemma setL2_cong:\n  \"\\<lbrakk>A = B; \\<And>x. x \\<in> B \\<Longrightarrow> f x = g x\\<rbrakk> \\<Longrightarrow> setL2 f A = setL2 g B\"\n  unfolding setL2_def by simp\n\nlemma strong_setL2_cong:\n  \"\\<lbrakk>A = B; \\<And>x. x \\<in> B =simp=> f x = g x\\<rbrakk> \\<Longrightarrow> setL2 f A = setL2 g B\"\n  unfolding setL2_def simp_implies_def by simp\n\nlemma setL2_infinite [simp]: \"\\<not> finite A \\<Longrightarrow> setL2 f A = 0\"\n  unfolding setL2_def by simp\n\nlemma setL2_empty [simp]: \"setL2 f {} = 0\"\n  unfolding setL2_def by simp\n\nlemma setL2_insert [simp]:\n  \"\\<lbrakk>finite F; a \\<notin> F\\<rbrakk> \\<Longrightarrow>\n    setL2 f (insert a F) = sqrt ((f a)\\<^sup>2 + (setL2 f F)\\<^sup>2)\"\n  unfolding setL2_def by (simp add: sum_nonneg)\n\nlemma setL2_nonneg [simp]: \"0 \\<le> setL2 f A\"\n  unfolding setL2_def by (simp add: sum_nonneg)\n\nlemma setL2_0': \"\\<forall>a\\<in>A. f a = 0 \\<Longrightarrow> setL2 f A = 0\"\n  unfolding setL2_def by simp\n\nlemma setL2_constant: \"setL2 (\\<lambda>x. y) A = sqrt (of_nat (card A)) * \\<bar>y\\<bar>\"\n  unfolding setL2_def by (simp add: real_sqrt_mult)\n\nlemma setL2_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 \"setL2 f K \\<le> setL2 g K\"\n  unfolding setL2_def\n  by (simp add: sum_nonneg sum_mono power_mono assms)\n\nlemma setL2_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 \"setL2 f K < setL2 g K\"\n  unfolding setL2_def\n  by (simp add: sum_strict_mono power_strict_mono assms)\n\nlemma setL2_right_distrib:\n  \"0 \\<le> r \\<Longrightarrow> r * setL2 f A = setL2 (\\<lambda>x. r * f x) A\"\n  unfolding setL2_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 setL2_left_distrib:\n  \"0 \\<le> r \\<Longrightarrow> setL2 f A * r = setL2 (\\<lambda>x. f x * r) A\"\n  unfolding setL2_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 setL2_eq_0_iff: \"finite A \\<Longrightarrow> setL2 f A = 0 \\<longleftrightarrow> (\\<forall>x\\<in>A. f x = 0)\"\n  unfolding setL2_def\n  by (simp add: sum_nonneg sum_nonneg_eq_0_iff)\n\nlemma setL2_triangle_ineq:\n  shows \"setL2 (\\<lambda>i. f i + g i) A \\<le> setL2 f A + setL2 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 + (setL2 (\\<lambda>i. f i + g i) F)\\<^sup>2) \\<le>\n           sqrt ((f x + g x)\\<^sup>2 + (setL2 f F + setL2 g F)\\<^sup>2)\"\n      by (intro real_sqrt_le_mono add_left_mono power_mono insert\n                setL2_nonneg add_increasing zero_le_power2)\n    also have\n      \"\\<dots> \\<le> sqrt ((f x)\\<^sup>2 + (setL2 f F)\\<^sup>2) + sqrt ((g x)\\<^sup>2 + (setL2 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 sqrt_sum_squares_le_sum:\n  \"\\<lbrakk>0 \\<le> x; 0 \\<le> y\\<rbrakk> \\<Longrightarrow> sqrt (x\\<^sup>2 + y\\<^sup>2) \\<le> x + y\"\n  apply (rule power2_le_imp_le)\n  apply (simp add: power2_sum)\n  apply simp\n  done\n\nlemma setL2_le_sum [rule_format]:\n  \"(\\<forall>i\\<in>A. 0 \\<le> f i) \\<longrightarrow> setL2 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 sqrt_sum_squares_le_sum_abs: \"sqrt (x\\<^sup>2 + y\\<^sup>2) \\<le> \\<bar>x\\<bar> + \\<bar>y\\<bar>\"\n  apply (rule power2_le_imp_le)\n  apply (simp add: power2_sum)\n  apply simp\n  done\n\nlemma setL2_le_sum_abs: \"setL2 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 setL2_mult_ineq_lemma:\n  fixes a b c d :: real\n  shows \"2 * (a * c) * (b * d) \\<le> a\\<^sup>2 * d\\<^sup>2 + b\\<^sup>2 * c\\<^sup>2\"\nproof -\n  have \"0 \\<le> (a * d - b * c)\\<^sup>2\" by simp\n  also have \"\\<dots> = a\\<^sup>2 * d\\<^sup>2 + b\\<^sup>2 * c\\<^sup>2 - 2 * (a * d) * (b * c)\"\n    by (simp only: power2_diff power_mult_distrib)\n  also have \"\\<dots> = a\\<^sup>2 * d\\<^sup>2 + b\\<^sup>2 * c\\<^sup>2 - 2 * (a * c) * (b * d)\"\n    by simp\n  finally show \"2 * (a * c) * (b * d) \\<le> a\\<^sup>2 * d\\<^sup>2 + b\\<^sup>2 * c\\<^sup>2\"\n    by simp\nqed\n\nlemma setL2_mult_ineq: \"(\\<Sum>i\\<in>A. \\<bar>f i\\<bar> * \\<bar>g i\\<bar>) \\<le> setL2 f A * setL2 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 setL2_mult_ineq_lemma)\n  apply simp_all\n  done\n\nlemma member_le_setL2: \"\\<lbrakk>finite A; i \\<in> A\\<rbrakk> \\<Longrightarrow> f i \\<le> setL2 f A\"\n  unfolding setL2_def\n  by (auto intro!: member_le_sum real_le_rsqrt)\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/L2_Norm.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835493924954, "lm_q2_score": 0.8615382076534742, "lm_q1q2_score": 0.7198009996675734}}
{"text": "(*  Title:       A General Method for the Proof of Theorems on Tail-recursive Functions\n    Author:      Pasquale Noce\n                 Security Certification Specialist at Arjo Systems - Gep S.p.A.\n                 pasquale dot noce dot lavoro at gmail dot com\n                 pasquale dot noce at arjowiggins-it dot com\n*)\n\nsection \"Case study 2\"\n\ntheory CaseStudy2\nimports Main \"HOL-Library.Multiset\"\nbegin\n\ntext \\<open>\n\\null\n\nIn the second case study, the problem will be examined of defining a function\n\\<open>t_ins\\<close> performing item insertion into binary search trees (admitting value\nrepetitions) of elements of a linear order, and then proving the correctness of\nthis definition, i.e. that the trees output by the function still be sorted if\nthe input ones are and contain one more occurrence of the inserted value, the\nnumber of occurrences of any other value being left unaltered.\n\nHere below is a naive tail-recursive definition of such function:\n\n\\null\n\\<close>\n\ndatatype 'a bintree = Leaf | Branch 'a \"'a bintree\" \"'a bintree\"\n\nfunction (sequential) t_ins_naive ::\n \"bool \\<Rightarrow> 'a::linorder \\<Rightarrow> 'a bintree list \\<Rightarrow> 'a bintree\"\nwhere\n\"t_ins_naive False x (Branch y yl yr # ts) = (if x \\<le> y\n  then t_ins_naive False x (yl # Branch y yl yr # ts)\n  else t_ins_naive False x (yr # Branch y yl yr # ts))\" |\n\"t_ins_naive False x (Leaf # ts) =\n  t_ins_naive True x (Branch x Leaf Leaf # ts)\" |\n\"t_ins_naive True x (xt # Branch y yl yr # ts) = (if x \\<le> y\n  then t_ins_naive True x (Branch y xt yr # ts)\n  else t_ins_naive True x (Branch y yl xt # ts))\" |\n\"t_ins_naive True x [xt] = xt\"\nby pat_completeness auto\n\ntext \\<open>\n\\null\n\nThe list appearing as the third argument, deputed to initially contain the sole\ntree into which the second argument has to be inserted, is used to unfold all the\ninvolved subtrees until a leaf is reached; then, such leaf is replaced with a branch\nwhose root value matches the second argument, and the subtree list is folded again.\nThe information on whether unfolding or folding is taking place is conveyed by the\nfirst argument, whose value will respectively be \\<open>False\\<close> or \\<open>True\\<close>.\n\nAccording to this plan, the computation is meant to terminate in correspondence\nwith pattern \\<open>True\\<close>, \\<open>_\\<close>, \\<open>[_]\\<close>. Hence, the above naive\ndefinition comprises a non-recursive equation for this pattern only, so that the\nresidual ones \\<open>True\\<close>, \\<open>_\\<close>, \\<open>_ # Leaf # _\\<close> and \\<open>_\\<close>,\n\\<open>_\\<close>, \\<open>[]\\<close> are not covered by any equation.\n\nThat which decreases in recursive calls is the size of the head of the subtree\nlist during unfolding, and the length of the list during folding. Furthermore,\nunfolding precedes folding in the recursive call pipeline, viz. there is a\nrecursive equation switching from unfolding to folding, but no one carrying out\nthe opposite transition. These considerations suggest that a measure function\nsuitable to prove the termination of function \\<open>t_ins_naive\\<close> should roughly\nmatch the sum of the length of the list and the size of the list head during\nunfolding, and the length of the list alone during folding.\n\nThis idea can be refined by observing that the length of the list increases by one\nat each recursive call during unfolding, and does not change in the recursive call\nleading from unfolding to folding, at which the size of the input list head (a\nleaf) equals zero. Therefore, in order that the measure function value be strictly\ndecreasing in each recursive call, the size of the list head has to be counted more\nthan once during unfolding -- e.g. twice --, and the length of the list has to be\ndecremented by one during folding -- no more than that, as otherwise the function\nvalue would not change in the passage from a two-item to a one-item list.\n\nAs a result, a suitable measure function and the corresponding termination proof\nare as follows:\n\n\\null\n\\<close>\n\nfun t_ins_naive_measure :: \"bool \\<times> 'a \\<times> 'a bintree list \\<Rightarrow> nat\" where\n\"t_ins_naive_measure (b, x, ts) = (if b\n  then length ts - 1\n  else length ts + 2 * size (hd ts))\"\n\ntermination t_ins_naive\nby (relation \"measure t_ins_naive_measure\", simp_all)\n\ntext \\<open>\n\\null\n\nSome further functions are needed to express the aforesaid correctness\nproperties of function \\<open>t_ins_naive\\<close>:\n\n\\null\n\\<close>\n\nprimrec t_set :: \"'a bintree \\<Rightarrow> 'a set\" where\n\"t_set Leaf = {}\" |\n\"t_set (Branch x xl xr) = {x} \\<union> t_set xl \\<union> t_set xr\"\n\nprimrec t_multiset :: \"'a bintree \\<Rightarrow> 'a multiset\" where\n\"t_multiset Leaf = {#}\" |\n\"t_multiset (Branch x xl xr) = {#x#} + t_multiset xl + t_multiset xr\"\n\nlemma t_set_multiset: \"t_set xt = set_mset (t_multiset xt)\"\nby (induction, simp_all)\n\nprimrec t_sorted :: \"'a::linorder bintree \\<Rightarrow> bool\" where\n\"t_sorted Leaf = True\" |\n\"t_sorted (Branch x xl xr) =\n  ((\\<forall>y \\<in> t_set xl. y \\<le> x) \\<and> (\\<forall>y \\<in> t_set xr. x < y) \\<and> t_sorted xl \\<and> t_sorted xr)\"\n\ndefinition t_count :: \"'a \\<Rightarrow> 'a bintree \\<Rightarrow> nat\" where\n\"t_count x xt \\<equiv> count (t_multiset xt) x\"\n\ntext \\<open>\n\\null\n\nFunctions \\<open>t_set\\<close> and \\<open>t_multiset\\<close> return the set and the multiset,\nrespectively, of the items of the input tree; the connection between them\nexpressed by lemma \\<open>t_set_multiset\\<close> will be used in step 9.\n\nThe target correctness theorems can then be enunciated as follows:\n\n\\null\n\n\\<open>t_sorted xt \\<longrightarrow> t_sorted (t_ins_naive False x [xt])\\<close>\n\n\\null\n\n\\<open>t_count y (t_ins_naive False x [xt]) =\\<close>\n\n\\<open>(if y = x then Suc else id) (t_count y xt)\\<close>\n\\<close>\n\nsubsection \"Step 1\"\n\ntext \\<open>\nThis time, the Cartesian product of the input types will be implemented as a\nrecord type. The second command instructs the system to regard such type as a\ndatatype, thus enabling record patterns:\n\n\\null\n\\<close>\n\nrecord 'a t_type =\n folding :: bool\n item :: 'a\n subtrees :: \"'a bintree list\"\n\nfunction (sequential) t_ins_aux :: \"'a::linorder t_type \\<Rightarrow> 'a t_type\" where\n\"t_ins_aux \\<lparr>folding = False, item = x, subtrees = Branch y yl yr # ts\\<rparr> =\n  (if x \\<le> y\n  then t_ins_aux \\<lparr>folding = False, item = x,\n    subtrees = yl # Branch y yl yr # ts\\<rparr>\n  else t_ins_aux \\<lparr>folding = False, item = x,\n    subtrees = yr # Branch y yl yr # ts\\<rparr>)\" |\n\"t_ins_aux \\<lparr>folding = False, item = x, subtrees = Leaf # ts\\<rparr> =\n  t_ins_aux \\<lparr>folding = True, item = x, subtrees = Branch x Leaf Leaf # ts\\<rparr>\" |\n\"t_ins_aux \\<lparr>folding = True, item = x, subtrees = xt # Branch y yl yr # ts\\<rparr> =\n  (if x \\<le> y\n  then t_ins_aux \\<lparr>folding = True, item = x, subtrees = Branch y xt yr # ts\\<rparr>\n  else t_ins_aux \\<lparr>folding = True, item = x, subtrees = Branch y yl xt # ts\\<rparr>)\" |\n\"t_ins_aux X = X\"\nby pat_completeness auto\n\ntext \\<open>\n\\null\n\nObserve that the pattern appearing in the non-recursive equation matches any\none of the residual patterns\n\\<open>\\<lparr>folding = True, item = _, subtrees = [_]\\<rparr>\\<close>,\n\\<open>\\<lparr>folding = True, item = _, subtrees = _ # Leaf # _\\<rparr>\\<close>,\n\\<open>\\<lparr>folding = _, item = _, subtrees = []\\<rparr>\\<close>, thus complying with the\nrequirement that the definition of function \\<open>t_ins_aux\\<close> be total.\n\nSince the arguments of recursive calls in the definition of function\n\\<open>t_ins_aux\\<close> are the same as those of function \\<open>t_ins_naive\\<close>,\nthe termination proof developed for the latter can be applied to the former\nas well by just turning the input product type of the previous measure\nfunction into the input record type of function \\<open>t_ins_aux\\<close>.\n\n\\null\n\\<close>\n\nfun t_ins_aux_measure :: \"'a t_type \\<Rightarrow> nat\" where\n\"t_ins_aux_measure \\<lparr>folding = b, item = x, subtrees = ts\\<rparr> = (if b\n  then length ts - 1\n  else length ts + 2 * size (hd ts))\"\n\ntermination t_ins_aux\nby (relation \"measure t_ins_aux_measure\", simp_all)\n\nsubsection \"Step 2\"\n\ndefinition t_ins_in :: \"'a \\<Rightarrow> 'a bintree \\<Rightarrow> 'a t_type\" where\n\"t_ins_in x xt \\<equiv> \\<lparr>folding = False, item = x, subtrees = [xt]\\<rparr>\"\n\ndefinition t_ins_out :: \"'a t_type \\<Rightarrow> 'a bintree\" where\n\"t_ins_out X \\<equiv> hd (subtrees X)\"\n\ndefinition t_ins :: \"'a::linorder \\<Rightarrow> 'a bintree \\<Rightarrow> 'a bintree\" where\n\"t_ins x xt \\<equiv> t_ins_out (t_ins_aux (t_ins_in x xt))\"\n\ntext \\<open>\n\\null\n\nSince the significant inputs of function \\<open>t_ins_naive\\<close> match pattern\n\\<open>False\\<close>, \\<open>_\\<close>, \\<open>[_]\\<close>, those of function \\<open>t_ins_aux\\<close>\nmatch pattern \\<open>\\<lparr>folding = False, item = _, subtrees = [_]\\<rparr>\\<close>, thus\nbeing in a one-to-one correspondence with the Cartesian product of the types\nof the second and the third component.\n\nThen, the target correctness theorems can be put into the following equivalent\nform:\n\n\\null\n\n\\<open>t_sorted xt \\<longrightarrow> t_sorted (t_ins x xt)\\<close>\n\n\\null\n\n\\<open>t_count y (t_ins x xt) =\\<close>\n\\<open>(if y = x then Suc else id) (t_count y xt)\\<close>\n\\<close>\n\nsubsection \"Step 3\"\n\ninductive_set t_ins_set :: \"'a::linorder t_type \\<Rightarrow> 'a t_type set\"\nfor X :: \"'a t_type\" where\nR0: \"X \\<in> t_ins_set X\" |\nR1: \"\\<lbrakk>\\<lparr>folding = False, item = x, subtrees = Branch y yl yr # ts\\<rparr> \\<in> t_ins_set X;\n     x \\<le> y\\<rbrakk> \\<Longrightarrow>\n     \\<lparr>folding = False, item = x, subtrees = yl # Branch y yl yr # ts\\<rparr>\n       \\<in> t_ins_set X\" |\nR2: \"\\<lbrakk>\\<lparr>folding = False, item = x, subtrees = Branch y yl yr # ts\\<rparr> \\<in> t_ins_set X;\n     \\<not> x \\<le> y\\<rbrakk> \\<Longrightarrow>\n     \\<lparr>folding = False, item = x, subtrees = yr # Branch y yl yr # ts\\<rparr>\n       \\<in> t_ins_set X\" |\nR3: \"\\<lparr>folding = False, item = x, subtrees = Leaf # ts\\<rparr> \\<in> t_ins_set X \\<Longrightarrow>\n     \\<lparr>folding = True, item = x, subtrees = Branch x Leaf Leaf # ts\\<rparr>\n       \\<in> t_ins_set X\" |\nR4: \"\\<lbrakk>\\<lparr>folding = True, item = x, subtrees = xt # Branch y yl yr # ts\\<rparr>\n       \\<in> t_ins_set X; x \\<le> y\\<rbrakk> \\<Longrightarrow>\n     \\<lparr>folding = True, item = x, subtrees = Branch y xt yr # ts\\<rparr> \\<in> t_ins_set X\" |\nR5: \"\\<lbrakk>\\<lparr>folding = True, item = x, subtrees = xt # Branch y yl yr # ts\\<rparr>\n       \\<in> t_ins_set X; \\<not> x \\<le> y\\<rbrakk> \\<Longrightarrow>\n     \\<lparr>folding = True, item = x, subtrees = Branch y yl xt # ts\\<rparr> \\<in> t_ins_set X\"\n\nsubsection \"Step 4\"\n\nlemma t_ins_subset:\n  assumes XY: \"Y \\<in> t_ins_set X\"\n  shows \"t_ins_set Y \\<subseteq> t_ins_set X\"\nproof (rule subsetI, erule t_ins_set.induct)\n  show \"Y \\<in> t_ins_set X\" using XY .\nnext\n  fix x y yl yr ts\n  assume\n   \"\\<lparr>folding = False, item = x, subtrees = Branch y yl yr # ts\\<rparr> \\<in> t_ins_set X\"\n  and \"x \\<le> y\"\n  thus \"\\<lparr>folding = False, item = x, subtrees = yl # Branch y yl yr # ts\\<rparr>\n   \\<in> t_ins_set X\" by (rule R1)\nnext\n  fix x y yl yr ts\n  assume\n   \"\\<lparr>folding = False, item = x, subtrees = Branch y yl yr # ts\\<rparr> \\<in> t_ins_set X\"\n  and \"\\<not> x \\<le> y\"\n  thus \"\\<lparr>folding = False, item = x, subtrees = yr # Branch y yl yr # ts\\<rparr>\n   \\<in> t_ins_set X\" by (rule R2)\nnext\n  fix x ts\n  assume \"\\<lparr>folding = False, item = x, subtrees = Leaf # ts\\<rparr> \\<in> t_ins_set X\"\n  thus \"\\<lparr>folding = True, item = x, subtrees = Branch x Leaf Leaf # ts\\<rparr>\n   \\<in> t_ins_set X\" by (rule R3)\nnext\n  fix x xt y yl yr ts\n  assume\n   \"\\<lparr>folding = True, item = x, subtrees = xt # Branch y yl yr # ts\\<rparr> \\<in> t_ins_set X\"\n  and \"x \\<le> y\"\n  thus \"\\<lparr>folding = True, item = x, subtrees = Branch y xt yr # ts\\<rparr> \\<in> t_ins_set X\"\n   by (rule R4)\nnext\n  fix x xt y yl yr ts\n  assume\n   \"\\<lparr>folding = True, item = x, subtrees = xt # Branch y yl yr # ts\\<rparr> \\<in> t_ins_set X\"\n  and \"\\<not> x \\<le> y\"\n  thus \"\\<lparr>folding = True, item = x, subtrees = Branch y yl xt # ts\\<rparr> \\<in> t_ins_set X\"\n   by (rule R5)\nqed\n\nlemma t_ins_aux_set: \"t_ins_aux X \\<in> t_ins_set X\"\nproof (induction rule: t_ins_aux.induct,\n simp_all add: R0 del: t_ins_aux.simps(1, 3))\n  fix x :: 'a and y yl yr ts\n  let\n   ?X = \"\\<lparr>folding = False, item = x, subtrees = Branch y yl yr # ts\\<rparr>\" and\n   ?X' = \"\\<lparr>folding = False, item = x, subtrees = yl # Branch y yl yr # ts\\<rparr>\" and\n   ?X'' = \"\\<lparr>folding = False, item = x, subtrees = yr # Branch y yl yr # ts\\<rparr>\"\n  assume\n   case1: \"x \\<le> y \\<Longrightarrow> t_ins_aux ?X' \\<in> t_ins_set ?X'\" and\n   case2: \"\\<not> x \\<le> y \\<Longrightarrow> t_ins_aux ?X'' \\<in> t_ins_set ?X''\"\n  have 0: \"?X \\<in> t_ins_set ?X\" by (rule R0)\n  show \"t_ins_aux ?X \\<in> t_ins_set ?X\"\n  proof (cases \"x \\<le> y\", simp_all)\n    assume \"x \\<le> y\"\n    with 0 have \"?X' \\<in> t_ins_set ?X\" by (rule R1)\n    hence \"t_ins_set ?X' \\<subseteq> t_ins_set ?X\" by (rule t_ins_subset)\n    moreover have \"t_ins_aux ?X' \\<in> t_ins_set ?X'\"\n     using case1 and \\<open>x \\<le> y\\<close> by simp\n    ultimately show \"t_ins_aux ?X' \\<in> t_ins_set ?X\" by (rule subsetD)\n  next\n    assume \"\\<not> x \\<le> y\"\n    with 0 have \"?X'' \\<in> t_ins_set ?X\" by (rule R2)\n    hence \"t_ins_set ?X'' \\<subseteq> t_ins_set ?X\" by (rule t_ins_subset)\n    moreover have \"t_ins_aux ?X'' \\<in> t_ins_set ?X''\"\n     using case2 and \\<open>\\<not> x \\<le> y\\<close> by simp\n    ultimately show \"t_ins_aux ?X'' \\<in> t_ins_set ?X\" by (rule subsetD)\n  qed\nnext\n  fix x :: 'a and ts\n  let\n   ?X = \"\\<lparr>folding = False, item = x, subtrees = Leaf # ts\\<rparr>\" and\n   ?X' = \"\\<lparr>folding = True, item = x, subtrees = Branch x Leaf Leaf # ts\\<rparr>\"\n  have \"?X \\<in> t_ins_set ?X\" by (rule R0)\n  hence \"?X' \\<in> t_ins_set ?X\" by (rule R3)\n  hence \"t_ins_set ?X' \\<subseteq> t_ins_set ?X\" by (rule t_ins_subset)\n  moreover assume \"t_ins_aux ?X' \\<in> t_ins_set ?X'\"\n  ultimately show \"t_ins_aux ?X' \\<in> t_ins_set ?X\" by (rule subsetD)\nnext\n  fix x :: 'a and xt y yl yr ts\n  let\n   ?X = \"\\<lparr>folding = True, item = x, subtrees = xt # Branch y yl yr # ts\\<rparr>\" and\n   ?X' = \"\\<lparr>folding = True, item = x, subtrees = Branch y xt yr # ts\\<rparr>\" and\n   ?X'' = \"\\<lparr>folding = True, item = x, subtrees = Branch y yl xt # ts\\<rparr>\"\n  assume\n   case1: \"x \\<le> y \\<Longrightarrow> t_ins_aux ?X' \\<in> t_ins_set ?X'\" and\n   case2: \"\\<not> x \\<le> y \\<Longrightarrow> t_ins_aux ?X'' \\<in> t_ins_set ?X''\"\n  have 0: \"?X \\<in> t_ins_set ?X\" by (rule R0)\n  show \"t_ins_aux ?X \\<in> t_ins_set ?X\"\n  proof (cases \"x \\<le> y\", simp_all)\n    assume \"x \\<le> y\"\n    with 0 have \"?X' \\<in> t_ins_set ?X\" by (rule R4)\n    hence \"t_ins_set ?X' \\<subseteq> t_ins_set ?X\" by (rule t_ins_subset)\n    moreover have \"t_ins_aux ?X' \\<in> t_ins_set ?X'\"\n     using case1 and \\<open>x \\<le> y\\<close> by simp\n    ultimately show \"t_ins_aux ?X' \\<in> t_ins_set ?X\" by (rule subsetD)\n  next\n    assume \"\\<not> x \\<le> y\"\n    with 0 have \"?X'' \\<in> t_ins_set ?X\" by (rule R5)\n    hence \"t_ins_set ?X'' \\<subseteq> t_ins_set ?X\" by (rule t_ins_subset)\n    moreover have \"t_ins_aux ?X'' \\<in> t_ins_set ?X''\"\n     using case2 and \\<open>\\<not> x \\<le> y\\<close> by simp\n    ultimately show \"t_ins_aux ?X'' \\<in> t_ins_set ?X\" by (rule subsetD)\n  qed\nqed\n\nsubsection \"Step 5\"\n\nprimrec t_val :: \"'a bintree \\<Rightarrow> 'a\" where\n\"t_val (Branch x xl xr) = x\"\n\nprimrec t_left :: \"'a bintree \\<Rightarrow> 'a bintree\" where\n\"t_left (Branch x xl xr) = xl\"\n\nprimrec t_right :: \"'a bintree \\<Rightarrow> 'a bintree\" where\n\"t_right (Branch x xl xr) = xr\"\n\ntext \\<open>\n\\null\n\nThe partiality of the definition of the previous functions, which merely return\nthe root value and either subtree of the input branch, does not matter as they\nwill be applied to branches only.\n\nThese functions are used to define the following invariant -- this time, a single\ninvariant for both of the target correctness theorems:\n\n\\null\n\\<close>\n\nfun t_ins_inv :: \"'a::linorder \\<Rightarrow> 'a bintree \\<Rightarrow> 'a t_type \\<Rightarrow> bool\" where\n\"t_ins_inv x xt \\<lparr>folding = b, item = y, subtrees = ts\\<rparr> =\n  (y = x \\<and>\n  (\\<forall>n \\<in> {..<length ts}.\n    (t_sorted xt \\<longrightarrow> t_sorted (ts ! n)) \\<and>\n    (0 < n \\<longrightarrow> (\\<exists>y yl yr. ts ! n = Branch y yl yr)) \\<and>\n    (let ts' = ts @ [Branch x xt Leaf] in t_multiset (ts ! n) =\n      (if b \\<and> n = 0 then {#x#} else {#}) +\n      (if x \\<le> t_val (ts' ! Suc n)\n        then t_multiset (t_left (ts' ! Suc n))\n        else t_multiset (t_right (ts' ! Suc n))))))\"\n\ntext \\<open>\n\\null\n\nMore precisely, the invariant, whose type has to match \\<open>'a t_type \\<Rightarrow> bool\\<close>\naccording to the method specification, shall be comprised of function\n\\<open>t_ins_inv x xt\\<close>, where \\<open>x\\<close>, \\<open>xt\\<close> are the free variables\nappearing in the target theorems as the arguments of function \\<open>t_ins\\<close>.\n\\<close>\n\nsubsection \"Step 6\"\n\nlemma t_ins_input: \"t_ins_inv x xt \\<lparr>folding = False, item = x, subtrees = [xt]\\<rparr>\"\nby simp\n\nsubsection \"Step 7\"\n\nfun t_ins_form :: \"'a t_type \\<Rightarrow> bool\" where\n\"t_ins_form \\<lparr>folding = True, item = _, subtrees = [_]\\<rparr> = True\" |\n\"t_ins_form \\<lparr>folding = True, item = _, subtrees = _ # Leaf # _\\<rparr> = True\" |\n\"t_ins_form _ = False\"\n\nlemma t_ins_intro_1:\n \"\\<lbrakk>t_ins_inv x xt X; t_ins_form X\\<rbrakk> \\<Longrightarrow>\n  t_sorted xt \\<longrightarrow> t_sorted (t_ins_out X)\"\nproof (rule t_ins_form.cases [of X], simp_all add: t_ins_out_def)\nqed (erule conjE, drule_tac x = \"Suc 0\" in bspec, simp_all)\n\nlemma t_ins_intro_2:\n \"\\<lbrakk>t_ins_inv x xt X; t_ins_form X\\<rbrakk> \\<Longrightarrow>\n  t_count y (t_ins_out X) = (if y = x then Suc else id) (t_count y xt)\"\nproof (rule t_ins_form.cases [of X], simp_all add: t_ins_out_def t_count_def)\nqed (erule conjE, drule_tac x = \"Suc 0\" in bspec, simp_all)\n\ntext \\<open>\n\\null\n\nDefining predicate \\<open>t_ins_form\\<close> by means of pattern matching rather than\nquantifiers permits a faster proof of the introduction rules through a case\ndistinction followed by simplification. These steps leave the subgoal\ncorresponding to pattern\n\\<open>\\<lparr>folding = True, item = _, subtrees = _ # Leaf # _\\<rparr>\\<close> to be proven, which\ncan be done \\emph{ad absurdum} as this pattern is incompatible with the invariant,\nstating that all the subtrees in the list except for its head are branches.\n\nThe reason why this pattern, unlike\n\\<open>\\<lparr>folding = _, item = _, subtrees = []\\<rparr>\\<close>, is not filtered by predicate\n\\<open>t_ins_form\\<close>, is that the lack of its occurrences in recursive calls in\ncorrespondence with significant inputs cannot be proven by rule inversion,\nbeing it compatible with the patterns introduced by rules \\<open>R3\\<close>,\n\\<open>R4\\<close>, and \\<open>R5\\<close>.\n\\<close>\n\nsubsection \"Step 8\"\n\ntext \\<open>\nThis step will be accomplished by first proving by recursion induction that\nthe outputs of function \\<open>t_ins_aux\\<close> match either of the patterns\nsatisfying predicate \\<open>t_ins_form\\<close> or else the residual one\n\\<open>\\<lparr>folding = _, item = _, subtrees = []\\<rparr>\\<close>, and then proving by rule\ninversion that the last pattern may not occur in recursive calls in\ncorrespondence with significant inputs.\n\n\\null\n\\<close>\n\ndefinition t_ins_form_all :: \"'a t_type \\<Rightarrow> bool\" where\n\"t_ins_form_all X \\<equiv> t_ins_form X \\<or> subtrees X = []\"\n\nlemma t_ins_form_aux_all: \"t_ins_form_all (t_ins_aux X)\"\nby (rule t_ins_aux.induct [of \"\\<lambda>X. t_ins_form_all (t_ins_aux X)\"],\n simp_all add: t_ins_form_all_def)\n\nlemma t_ins_form_aux:\n \"t_ins_form (t_ins_aux \\<lparr>folding = False, item = x, subtrees = [xt]\\<rparr>)\"\n (is \"_ (t_ins_aux ?X)\")\nusing t_ins_aux_set [of ?X]\nproof (rule t_ins_set.cases, insert t_ins_form_aux_all [of ?X])\nqed (simp_all add: t_ins_form_all_def)\n\nsubsection \"Step 9\"\n\nlemma t_ins_invariance:\n  assumes XY: \"Y \\<in> t_ins_set X\" and X: \"t_ins_inv x xt X\"\n  shows \"t_ins_inv x xt Y\"\nusing XY\nproof (rule t_ins_set.induct, simp_all split del: if_split)\n  show \"t_ins_inv x xt X\" using X .\nnext\n  fix z :: \"'a::linorder\" and y yl yr ts\n  assume \"z = x \\<and>\n   (\\<forall>n \\<in> {..<Suc (length ts)}.\n     (t_sorted xt \\<longrightarrow> t_sorted ((Branch y yl yr # ts) ! n)) \\<and>\n     (0 < n \\<longrightarrow> (\\<exists>y' yl' yr'. ts ! (n - Suc 0) = Branch y' yl' yr')) \\<and>\n     (let ts' = Branch y yl yr # ts @ [Branch x xt Leaf]\n       in t_multiset ((Branch y yl yr # ts) ! n) =\n         (if x \\<le> t_val ((ts @ [Branch x xt Leaf]) ! n)\n           then t_multiset (t_left (ts' ! Suc n))\n           else t_multiset (t_right (ts' ! Suc n)))))\"\n   (is \"_ \\<and> (\\<forall>n \\<in> {..<Suc (length ts)}. ?P n)\")\n  hence I: \"\\<forall>n \\<in> {..<Suc (length ts)}. ?P n\" ..\n  assume xy: \"x \\<le> y\"\n  show\n   \"\\<forall>n \\<in> {..<Suc (Suc (length ts))}.\n     (t_sorted xt \\<longrightarrow> t_sorted ((yl # Branch y yl yr # ts) ! n)) \\<and>\n     (0 < n \\<longrightarrow> (\\<exists>y' yl' yr'. (Branch y yl yr # ts) ! (n - Suc 0) =\n       Branch y' yl' yr')) \\<and>\n     (let ts' = yl # Branch y yl yr # ts @ [Branch x xt Leaf]\n       in t_multiset ((yl # Branch y yl yr # ts) ! n) =\n         (if x \\<le> t_val ((Branch y yl yr # ts @ [Branch x xt Leaf]) ! n)\n           then t_multiset (t_left (ts' ! Suc n))\n           else t_multiset (t_right (ts' ! Suc n))))\"\n   (is \"\\<forall>n \\<in> {..<Suc (Suc (length ts))}. ?Q n\")\n  proof\n    fix n\n    assume n: \"n \\<in> {..<Suc (Suc (length ts))}\"\n    show \"?Q n\"\n    proof (cases n)\n      case 0\n      have \"0 \\<in> {..<Suc (length ts)}\" by simp\n      with I have \"?P 0\" ..\n      thus ?thesis by (simp add: Let_def xy 0)\n    next\n      case (Suc m)\n      hence \"m \\<in> {..<Suc (length ts)}\" using n by simp\n      with I have \"?P m\" ..\n      thus ?thesis\n      proof (simp add: Let_def Suc)\n      qed (cases m, simp_all)\n    qed\n  qed\nnext\n  fix z :: \"'a::linorder\" and y yl yr ts\n  assume \"z = x \\<and>\n   (\\<forall>n \\<in> {..<Suc (length ts)}.\n     (t_sorted xt \\<longrightarrow> t_sorted ((Branch y yl yr # ts) ! n)) \\<and>\n     (0 < n \\<longrightarrow> (\\<exists>y' yl' yr'. ts ! (n - Suc 0) = Branch y' yl' yr')) \\<and>\n     (let ts' = Branch y yl yr # ts @ [Branch x xt Leaf]\n       in t_multiset ((Branch y yl yr # ts) ! n) =\n         (if x \\<le> t_val ((ts @ [Branch x xt Leaf]) ! n)\n           then t_multiset (t_left (ts' ! Suc n))\n           else t_multiset (t_right (ts' ! Suc n)))))\"\n   (is \"_ \\<and> (\\<forall>n \\<in> {..<Suc (length ts)}. ?P n)\")\n  hence I: \"\\<forall>n \\<in> {..<Suc (length ts)}. ?P n\" ..\n  assume xy: \"\\<not> x \\<le> y\"\n  show\n   \"\\<forall>n \\<in> {..<Suc (Suc (length ts))}.\n     (t_sorted xt \\<longrightarrow> t_sorted ((yr # Branch y yl yr # ts) ! n)) \\<and>\n     (0 < n \\<longrightarrow> (\\<exists>y' yl' yr'. (Branch y yl yr # ts) ! (n - Suc 0) =\n       Branch y' yl' yr')) \\<and>\n     (let ts' = yr # Branch y yl yr # ts @ [Branch x xt Leaf]\n       in t_multiset ((yr # Branch y yl yr # ts) ! n) =\n         (if x \\<le> t_val ((Branch y yl yr # ts @ [Branch x xt Leaf]) ! n)\n           then t_multiset (t_left (ts' ! Suc n))\n           else t_multiset (t_right (ts' ! Suc n))))\"\n   (is \"\\<forall>n \\<in> {..<Suc (Suc (length ts))}. ?Q n\")\n  proof\n    fix n\n    assume n: \"n \\<in> {..<Suc (Suc (length ts))}\"\n    show \"?Q n\"\n    proof (cases n)\n      case 0\n      have \"0 \\<in> {..<Suc (length ts)}\" by simp\n      with I have \"?P 0\" ..\n      thus ?thesis by (simp add: Let_def xy 0)\n    next\n      case (Suc m)\n      hence \"m \\<in> {..<Suc (length ts)}\" using n by simp\n      with I have \"?P m\" ..\n      thus ?thesis\n      proof (simp add: Let_def Suc)\n      qed (cases m, simp_all)\n    qed\n  qed\nnext\n  fix z :: 'a and ts\n  assume \"z = x \\<and>\n   (\\<forall>n \\<in> {..<Suc (length ts)}.\n     (t_sorted xt \\<longrightarrow> t_sorted ((Leaf # ts) ! n)) \\<and>\n     (0 < n \\<longrightarrow> (\\<exists>y yl yr. ts ! (n - Suc 0) = Branch y yl yr)) \\<and>\n     (let ts' = Leaf # ts @ [Branch x xt Leaf]\n       in t_multiset ((Leaf # ts) ! n) =\n         (if x \\<le> t_val ((ts @ [Branch x xt Leaf]) ! n)\n           then t_multiset (t_left (ts' ! Suc n))\n           else t_multiset (t_right (ts' ! Suc n)))))\"\n   (is \"_ \\<and> (\\<forall>n \\<in> {..<Suc (length ts)}. ?P n)\")\n  hence I: \"\\<forall>n \\<in> {..<Suc (length ts)}. ?P n\" ..\n  show\n   \"\\<forall>n \\<in> {..<Suc (length ts)}.\n     (t_sorted xt \\<longrightarrow> t_sorted ((Branch x Leaf Leaf # ts) ! n)) \\<and>\n     (let ts' = Branch x Leaf Leaf # ts @ [Branch x xt Leaf]\n       in t_multiset ((Branch x Leaf Leaf # ts) ! n) =\n         (if n = 0 then {#x#} else {#}) +\n         (if x \\<le> t_val ((ts @ [Branch x xt Leaf]) ! n)\n           then t_multiset (t_left (ts' ! Suc n))\n           else t_multiset (t_right (ts' ! Suc n))))\"\n   (is \"\\<forall>n \\<in> {..<Suc (length ts)}. ?Q n\")\n  proof\n    fix n\n    assume n: \"n \\<in> {..<Suc (length ts)}\"\n    show \"?Q n\"\n    proof (cases n)\n      case 0\n      have \"0 \\<in> {..<Suc (length ts)}\" by simp\n      with I have \"?P 0\" ..\n      thus ?thesis by (simp add: Let_def 0 split: if_split_asm)\n    next\n      case (Suc m)\n      have \"?P n\" using I and n ..\n      thus ?thesis by (simp add: Let_def Suc)\n    qed\n  qed\nnext\n  fix z :: 'a and zt y yl yr ts\n  assume \"z = x \\<and>\n   (\\<forall>n \\<in> {..<Suc (Suc (length ts))}.\n     (t_sorted xt \\<longrightarrow> t_sorted ((zt # Branch y yl yr # ts) ! n)) \\<and>\n     (0 < n \\<longrightarrow> (\\<exists>y' yl' yr'. (Branch y yl yr # ts) ! (n - Suc 0) =\n       Branch y' yl' yr')) \\<and>\n     (let ts' = zt # Branch y yl yr # ts @ [Branch x xt Leaf]\n       in t_multiset ((zt # Branch y yl yr # ts) ! n) =\n         (if n = 0 then {#x#} else {#}) +\n         (if x \\<le> t_val ((Branch y yl yr # ts @ [Branch x xt Leaf]) ! n)\n           then t_multiset (t_left (ts' ! Suc n))\n           else t_multiset (t_right (ts' ! Suc n)))))\"\n   (is \"_ \\<and> (\\<forall>n \\<in> {..<Suc (Suc (length ts))}. ?P n)\")\n  hence I: \"\\<forall>n \\<in> {..<Suc (Suc (length ts))}. ?P n\" ..\n  assume xy: \"x \\<le> y\"\n  show\n   \"\\<forall>n \\<in> {..<Suc (length ts)}.\n     (t_sorted xt \\<longrightarrow> t_sorted ((Branch y zt yr # ts) ! n)) \\<and>\n     (0 < n \\<longrightarrow> (\\<exists>y' yl' yr'. ts ! (n - Suc 0) = Branch y' yl' yr')) \\<and>\n     (let ts' = Branch y zt yr # ts @ [Branch x xt Leaf]\n       in t_multiset ((Branch y zt yr # ts) ! n) =\n         (if n = 0 then {#x#} else {#}) +\n         (if x \\<le> t_val ((ts @ [Branch x xt Leaf]) ! n)\n           then t_multiset (t_left (ts' ! Suc n))\n           else t_multiset (t_right (ts' ! Suc n))))\"\n   (is \"\\<forall>n \\<in> {..<Suc (length ts)}. ?Q n\")\n  proof\n    fix n\n    assume n: \"n \\<in> {..<Suc (length ts)}\"\n    show \"?Q n\"\n    proof (cases n)\n      case 0\n      have \"0 \\<in> {..<Suc (Suc (length ts))}\" by simp\n      with I have \"?P 0\" ..\n      hence I0: \"(t_sorted xt \\<longrightarrow> t_sorted zt) \\<and>\n       t_multiset zt = {#x#} + t_multiset yl\"\n       by (simp add: Let_def xy)\n      have \"Suc 0 \\<in> {..<Suc (Suc (length ts))}\" by simp\n      with I have \"?P (Suc 0)\" ..\n      hence I1: \"(t_sorted xt \\<longrightarrow> t_sorted (Branch y yl yr)) \\<and>\n       t_multiset (Branch y yl yr) =\n       (if x \\<le> t_val ((ts @ [Branch x xt Leaf]) ! 0)\n        then t_multiset (t_left ((ts @ [Branch x xt Leaf]) ! 0))\n        else t_multiset (t_right ((ts @ [Branch x xt Leaf]) ! 0)))\"\n       by (simp add: Let_def)\n      show ?thesis\n      proof (simp add: Let_def 0 del: t_sorted.simps split del: if_split,\n       rule conjI, simp_all add: Let_def 0 del: t_sorted.simps,\n       rule_tac [2] conjI, rule_tac [!] impI)\n        assume s: \"t_sorted xt\"\n        hence \"t_sorted zt\" using I0 by simp\n        moreover have \"t_sorted (Branch y yl yr)\" using I1 and s by simp\n        moreover have \"t_set zt = {x} \\<union> t_set yl\" using I0\n         by (simp add: t_set_multiset)\n        ultimately show \"t_sorted (Branch y zt yr)\" using xy by simp\n      next\n        assume \"x \\<le> t_val ((ts @ [Branch x xt Leaf]) ! 0)\"\n        hence \"t_multiset (t_left ((ts @ [Branch x xt Leaf]) ! 0)) =\n         t_multiset (Branch y yl yr)\" using I1 by simp\n        thus \"add_mset y (t_multiset zt + t_multiset yr) =\n         add_mset x (t_multiset (t_left ((ts @ [Branch x xt Leaf]) ! 0)))\" using I0\n         by simp\n      next\n        assume \"\\<not> x \\<le> t_val ((ts @ [Branch x xt Leaf]) ! 0)\"\n        hence \"t_multiset (t_right ((ts @ [Branch x xt Leaf]) ! 0)) =\n         t_multiset (Branch y yl yr)\" using I1 by simp\n        thus \"add_mset y (t_multiset zt + t_multiset yr) =\n         add_mset x (t_multiset (t_right ((ts @ [Branch x xt Leaf]) ! 0)))\" using I0\n         by simp\n      qed\n    next\n      case (Suc m)\n      have \"Suc n \\<in> {..<Suc (Suc (length ts))}\" using n by simp\n      with I have \"?P (Suc n)\" ..\n      thus ?thesis by (simp add: Let_def Suc)\n    qed\n  qed\nnext\n  fix z :: 'a and zt y yl yr ts\n  assume \"z = x \\<and>\n   (\\<forall>n \\<in> {..<Suc (Suc (length ts))}.\n     (t_sorted xt \\<longrightarrow> t_sorted ((zt # Branch y yl yr # ts) ! n)) \\<and>\n     (0 < n \\<longrightarrow> (\\<exists>y' yl' yr'. (Branch y yl yr # ts) ! (n - Suc 0) =\n       Branch y' yl' yr')) \\<and>\n     (let ts' = zt # Branch y yl yr # ts @ [Branch x xt Leaf]\n       in t_multiset ((zt # Branch y yl yr # ts) ! n) =\n         (if n = 0 then {#x#} else {#}) +\n         (if x \\<le> t_val ((Branch y yl yr # ts @ [Branch x xt Leaf]) ! n)\n           then t_multiset (t_left (ts' ! Suc n))\n           else t_multiset (t_right (ts' ! Suc n)))))\"\n   (is \"_ \\<and> (\\<forall>n \\<in> {..<Suc (Suc (length ts))}. ?P n)\")\n  hence I: \"\\<forall>n \\<in> {..<Suc (Suc (length ts))}. ?P n\" ..\n  assume xy: \"\\<not> x \\<le> y\"\n  show\n   \"\\<forall>n \\<in> {..<Suc (length ts)}.\n     (t_sorted xt \\<longrightarrow> t_sorted ((Branch y yl zt # ts) ! n)) \\<and>\n     (0 < n \\<longrightarrow> (\\<exists>y' yl' yr'. ts ! (n - Suc 0) = Branch y' yl' yr')) \\<and>\n     (let ts' = Branch y yl zt # ts @ [Branch x xt Leaf]\n       in t_multiset ((Branch y yl zt # ts) ! n) =\n         (if n = 0 then {#x#} else {#}) +\n         (if x \\<le> t_val ((ts @ [Branch x xt Leaf]) ! n)\n           then t_multiset (t_left (ts' ! Suc n))\n           else t_multiset (t_right (ts' ! Suc n))))\"\n   (is \"\\<forall>n \\<in> {..<Suc (length ts)}. ?Q n\")\n  proof\n    fix n\n    assume n: \"n \\<in> {..<Suc (length ts)}\"\n    show \"?Q n\"\n    proof (cases n)\n      case 0\n      have \"0 \\<in> {..<Suc (Suc (length ts))}\" by simp\n      with I have \"?P 0\" ..\n      hence I0: \"(t_sorted xt \\<longrightarrow> t_sorted zt) \\<and>\n       t_multiset zt = {#x#} + t_multiset yr\"\n       by (simp add: Let_def xy)\n      have \"Suc 0 \\<in> {..<Suc (Suc (length ts))}\" by simp\n      with I have \"?P (Suc 0)\" ..\n      hence I1: \"(t_sorted xt \\<longrightarrow> t_sorted (Branch y yl yr)) \\<and>\n       t_multiset (Branch y yl yr) =\n       (if x \\<le> t_val ((ts @ [Branch x xt Leaf]) ! 0)\n        then t_multiset (t_left ((ts @ [Branch x xt Leaf]) ! 0))\n        else t_multiset (t_right ((ts @ [Branch x xt Leaf]) ! 0)))\"\n       by (simp add: Let_def)\n      show ?thesis\n      proof (simp add: Let_def 0 del: t_sorted.simps split del: if_split,\n       rule conjI, simp_all add: Let_def 0 del: t_sorted.simps,\n       rule_tac [2] conjI, rule_tac [!] impI)\n        assume s: \"t_sorted xt\"\n        hence \"t_sorted zt\" using I0 by simp\n        moreover have \"t_sorted (Branch y yl yr)\" using I1 and s by simp\n        moreover have \"t_set zt = {x} \\<union> t_set yr\" using I0\n         by (simp add: t_set_multiset)\n        ultimately show \"t_sorted (Branch y yl zt)\" using xy by simp\n      next\n        assume \"x \\<le> t_val ((ts @ [Branch x xt Leaf]) ! 0)\"\n        hence \"t_multiset (t_left ((ts @ [Branch x xt Leaf]) ! 0)) =\n         t_multiset (Branch y yl yr)\" using I1 by simp\n        thus \"add_mset y (t_multiset yl + t_multiset zt) =\n         add_mset x (t_multiset (t_left ((ts @ [Branch x xt Leaf]) ! 0)))\" using I0\n         by simp\n      next\n        assume \"\\<not> x \\<le> t_val ((ts @ [Branch x xt Leaf]) ! 0)\"\n        hence \"t_multiset (t_right ((ts @ [Branch x xt Leaf]) ! 0)) =\n         t_multiset (Branch y yl yr)\" using I1 by simp\n        thus \"add_mset y (t_multiset yl + t_multiset zt) =\n         add_mset x (t_multiset (t_right ((ts @ [Branch x xt Leaf]) ! 0)))\" using I0\n         by simp\n      qed\n    next\n      case (Suc m)\n      have \"Suc n \\<in> {..<Suc (Suc (length ts))}\" using n by simp\n      with I have \"?P (Suc n)\" ..\n      thus ?thesis by (simp add: Let_def Suc)\n    qed\n  qed\nqed\n\nsubsection \"Step 10\"\n\ntheorem \"t_sorted xt \\<longrightarrow> t_sorted (t_ins x xt)\"\nproof -\n  let ?X = \"\\<lparr>folding = False, item = x, subtrees = [xt]\\<rparr>\"\n  have \"t_ins_aux ?X \\<in> t_ins_set ?X\" by (rule t_ins_aux_set)\n  moreover have \"t_ins_inv x xt ?X\" by (rule t_ins_input)\n  ultimately have \"t_ins_inv x xt (t_ins_aux ?X)\" by (rule t_ins_invariance)\n  moreover have \"t_ins_form (t_ins_aux ?X)\" by (rule t_ins_form_aux)\n  ultimately have \"t_sorted xt \\<longrightarrow> t_sorted (t_ins_out (t_ins_aux ?X))\"\n   by (rule t_ins_intro_1)\n  moreover have \"?X = t_ins_in x xt\" by (simp add: t_ins_in_def)\n  ultimately show ?thesis by (simp add: t_ins_def)\nqed\n\ntheorem \"t_count y (t_ins x xt) = (if y = x then Suc else id) (t_count y xt)\"\nproof -\n  let ?X = \"\\<lparr>folding = False, item = x, subtrees = [xt]\\<rparr>\"\n  have \"t_ins_aux ?X \\<in> t_ins_set ?X\" by (rule t_ins_aux_set)\n  moreover have \"t_ins_inv x xt ?X\" by (rule t_ins_input)\n  ultimately have \"t_ins_inv x xt (t_ins_aux ?X)\" by (rule t_ins_invariance)\n  moreover have \"t_ins_form (t_ins_aux ?X)\" by (rule t_ins_form_aux)\n  ultimately have \"t_count y (t_ins_out (t_ins_aux ?X)) =\n   (if y = x then Suc else id) (t_count y xt)\"\n   by (rule t_ins_intro_2)\n  moreover have \"?X = t_ins_in x xt\" by (simp add: t_ins_in_def)\n  ultimately show ?thesis by (simp add: t_ins_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/Tail_Recursive_Functions/CaseStudy2.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8354835452961425, "lm_q2_score": 0.8615382040983515, "lm_q1q2_score": 0.7198009931681624}}
{"text": "(*\n  File:    Going_To_Filter.thy\n  Author:  Manuel Eberl, TU M\u00fcnchen\n\n  A filter describing the points x such that f(x) tends to some other filter.\n*)\n\nsection \\<open>The \\<open>going_to\\<close> filter\\<close>\n\ntheory Going_To_Filter\n  imports Complex_MainRLT\nbegin\n\ndefinition going_to_within :: \"('a \\<Rightarrow> 'b) \\<Rightarrow> 'b filter \\<Rightarrow> 'a set \\<Rightarrow> 'a filter\"\n  (\\<open>(_)/ going'_to (_)/ within (_)\\<close> [1000,60,60] 60) where\n  \"f going_to F within A = inf (filtercomap f F) (principal A)\"\n\nabbreviation going_to :: \"('a \\<Rightarrow> 'b) \\<Rightarrow> 'b filter \\<Rightarrow> 'a filter\"\n    (infix \\<open>going'_to\\<close> 60)\n    where \"f going_to F \\<equiv> f going_to F within UNIV\"\n\ntext \\<open>\n  The \\<open>going_to\\<close> filter is, in a sense, the opposite of \\<^term>\\<open>filtermap\\<close>. \n  It corresponds to the intuition of, given a function $f: A \\to B$ and a filter $F$ on the \n  range of $B$, looking at such values of $x$ that $f(x)$ approaches $F$. This can be \n  written as \\<^term>\\<open>f going_to F\\<close>.\n  \n  A classic example is the \\<^term>\\<open>at_infinity\\<close> filter, which describes the neigbourhood\n  of infinity (i.\\,e.\\ all values sufficiently far away from the zero). This can also be written\n  as \\<^term>\\<open>norm going_to at_top\\<close>.\n\n  Additionally, the \\<open>going_to\\<close> filter can be restricted with an optional `within' parameter.\n  For instance, if one would would want to consider the filter of complex numbers near infinity\n  that do not lie on the negative real line, one could write \n  \\<^term>\\<open>norm going_to at_top within - complex_of_real ` {..0}\\<close>.\n\n  A third, less mathematical example lies in the complexity analysis of algorithms.\n  Suppose we wanted to say that an algorithm on lists takes $O(n^2)$ time where $n$ is \n  the length of the input list. We can write this using the Landau symbols from the AFP,\n  where the underlying filter is \\<^term>\\<open>length going_to at_top\\<close>. If, on the other hand,\n  we want to look the complexity of the algorithm on sorted lists, we could use the filter\n  \\<^term>\\<open>length going_to at_top within {xs. sorted xs}\\<close>.\n\\<close>\n\nlemma going_to_def: \"f going_to F = filtercomap f F\"\n  by (simp add: going_to_within_def)\n\nlemma eventually_going_toI [intro]: \n  assumes \"eventually P F\"\n  shows   \"eventually (\\<lambda>x. P (f x)) (f going_to F)\"\n  using assms by (auto simp: going_to_def)\n\nlemma filterlim_going_toI_weak [intro]: \"filterlim f F (f going_to F within A)\"\n  unfolding going_to_within_def\n  by (meson filterlim_filtercomap filterlim_iff inf_le1 le_filter_def)\n\nlemma going_to_mono: \"F \\<le> G \\<Longrightarrow> A \\<subseteq> B \\<Longrightarrow> f going_to F within A \\<le> f going_to G within B\"\n  unfolding going_to_within_def by (intro inf_mono filtercomap_mono) simp_all\n\nlemma going_to_inf: \n  \"f going_to (inf F G) within A = inf (f going_to F within A) (f going_to G within A)\"\n  by (simp add: going_to_within_def filtercomap_inf inf_assoc inf_commute inf_left_commute)\n\nlemma going_to_sup: \n  \"f going_to (sup F G) within A \\<ge> sup (f going_to F within A) (f going_to G within A)\"\n  by (auto simp: going_to_within_def intro!: inf.coboundedI1 filtercomap_sup filtercomap_mono)\n\nlemma going_to_top [simp]: \"f going_to top within A = principal A\"\n  by (simp add: going_to_within_def)\n    \nlemma going_to_bot [simp]: \"f going_to bot within A = bot\"\n  by (simp add: going_to_within_def)\n    \nlemma going_to_principal: \n  \"f going_to principal A within B = principal (f -` A \\<inter> B)\"\n  by (simp add: going_to_within_def)\n    \nlemma going_to_within_empty [simp]: \"f going_to F within {} = bot\"\n  by (simp add: going_to_within_def)\n\nlemma going_to_within_union [simp]: \n  \"f going_to F within (A \\<union> B) = sup (f going_to F within A) (f going_to F within B)\"\n  by (simp add: going_to_within_def flip: inf_sup_distrib1)\n\nlemma eventually_going_to_at_top_linorder:\n  fixes f :: \"'a \\<Rightarrow> 'b :: linorder\"\n  shows \"eventually P (f going_to at_top within A) \\<longleftrightarrow> (\\<exists>C. \\<forall>x\\<in>A. f x \\<ge> C \\<longrightarrow> P x)\"\n  unfolding going_to_within_def eventually_filtercomap \n    eventually_inf_principal eventually_at_top_linorder by fast\n\nlemma eventually_going_to_at_bot_linorder:\n  fixes f :: \"'a \\<Rightarrow> 'b :: linorder\"\n  shows \"eventually P (f going_to at_bot within A) \\<longleftrightarrow> (\\<exists>C. \\<forall>x\\<in>A. f x \\<le> C \\<longrightarrow> P x)\"\n  unfolding going_to_within_def eventually_filtercomap \n    eventually_inf_principal eventually_at_bot_linorder by fast\n\nlemma eventually_going_to_at_top_dense:\n  fixes f :: \"'a \\<Rightarrow> 'b :: {linorder,no_top}\"\n  shows \"eventually P (f going_to at_top within A) \\<longleftrightarrow> (\\<exists>C. \\<forall>x\\<in>A. f x > C \\<longrightarrow> P x)\"\n  unfolding going_to_within_def eventually_filtercomap \n    eventually_inf_principal eventually_at_top_dense by fast\n\nlemma eventually_going_to_at_bot_dense:\n  fixes f :: \"'a \\<Rightarrow> 'b :: {linorder,no_bot}\"\n  shows \"eventually P (f going_to at_bot within A) \\<longleftrightarrow> (\\<exists>C. \\<forall>x\\<in>A. f x < C \\<longrightarrow> P x)\"\n  unfolding going_to_within_def eventually_filtercomap \n    eventually_inf_principal eventually_at_bot_dense by fast\n               \nlemma eventually_going_to_nhds:\n  \"eventually P (f going_to nhds a within A) \\<longleftrightarrow> \n     (\\<exists>S. open S \\<and> a \\<in> S \\<and> (\\<forall>x\\<in>A. f x \\<in> S \\<longrightarrow> P x))\"\n  unfolding going_to_within_def eventually_filtercomap eventually_inf_principal\n    eventually_nhds by fast\n\nlemma eventually_going_to_at:\n  \"eventually P (f going_to (at a within B) within A) \\<longleftrightarrow> \n     (\\<exists>S. open S \\<and> a \\<in> S \\<and> (\\<forall>x\\<in>A. f x \\<in> B \\<inter> S - {a} \\<longrightarrow> P x))\"\n  unfolding at_within_def going_to_inf eventually_inf_principal\n            eventually_going_to_nhds going_to_principal by fast\n\nlemma norm_going_to_at_top_eq: \"norm going_to at_top = at_infinity\"\n  by (simp add: eventually_at_infinity eventually_going_to_at_top_linorder filter_eq_iff)\n\nlemmas at_infinity_altdef = norm_going_to_at_top_eq [symmetric]\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/Going_To_Filter.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.86153820232079, "lm_q2_score": 0.8354835391516133, "lm_q1q2_score": 0.7198009863892924}}
{"text": "theory Exe2p10\n  imports Main\nbegin\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\nlemma \"(nodes (explode n t)) = (nodes t + 1) * (2 ^ n) - 1\"\n  apply(induction n arbitrary: t)\n   apply(auto)\n  apply(simp add: algebra_simps)\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/Exe2p10.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9196425245706047, "lm_q2_score": 0.7826624789529375, "lm_q1q2_score": 0.7197696980309672}}
{"text": "(*<*)\ntheory Choice_Functions\nimports\n  Basis\nbegin\n(*>*)\n\nsection\\<open> Choice Functions \\label{sec:cf} \\<close>\n\ntext\\<open>\n\nWe now develop a few somewhat general results about choice functions,\nfollowing \\citet{Moulin:1985,Sen:1970,Border:2012}.\n\\citet{sep-preferences} provide some philosophical background on this\ntopic. While this material is foundational to the story we tell about\nstable matching, it is perhaps best skipped over on a first reading.\n\nThe game here is to study conditions on functions that yield\nacceptable choices from a given set of alternatives drawn from some\nuniverse (a set, often a type in HOL). We adopt the Isabelle\nconvention of attaching the suffix @{emph \\<open>on\\<close>} to\npredicates that are defined on subsets of their types.\n\n\\<close>\n\ntype_synonym 'a cfun = \"'a set \\<Rightarrow> 'a set\"\n\ntext\\<open>\n\nMost results require that the choice function yield a subset of its\nargument:\n\n\\<close>\n\ndefinition f_range_on :: \"'a set \\<Rightarrow> 'a cfun \\<Rightarrow> bool\" where\n  \"f_range_on A f \\<longleftrightarrow> (\\<forall>B\\<subseteq>A. f B \\<subseteq> B)\"\n\nabbreviation f_range :: \"'a cfun \\<Rightarrow> bool\" where\n  \"f_range \\<equiv> f_range_on UNIV\"\n(*<*)\n\nlemma f_range_onI:\n  \"(\\<And>B. B \\<subseteq> A \\<Longrightarrow> f B \\<subseteq> B) \\<Longrightarrow> f_range_on A f\"\nunfolding f_range_on_def by blast\n\nlemmas f_range_onD = iffD1[OF f_range_on_def, rule_format]\nlemmas f_range_onD' = subsetD[OF f_range_onD, rotated -1]\n\nlemma f_range_on_antimono:\n  assumes \"f_range_on B f\"\n  assumes \"A \\<subseteq> B\"\n  shows \"f_range_on A f\"\nusing assms unfolding f_range_on_def by blast\n\n(*>*)\ntext\\<open>\n\nEconomists typically assume that the universe is finite, and @{term\n\"f\"} is @{emph \\<open>decisive\\<close>}, i.e., yields non-empty sets when given\nnon-empty sets.\n\n\\<close>\n\ndefinition decisive_on :: \"'a set \\<Rightarrow> 'a cfun \\<Rightarrow> bool\" where\n  \"decisive_on A f \\<longleftrightarrow> (\\<forall>B\\<subseteq>A. B \\<noteq> {} \\<longrightarrow> f B \\<noteq> {})\"\n\nabbreviation decisive :: \"'a cfun \\<Rightarrow> bool\" where\n  \"decisive \\<equiv> decisive_on UNIV\"\n(*<*)\n\nlemmas decisive_onD = iffD1[OF decisive_on_def, rule_format]\nlemmas decisive_onI = iffD2[OF decisive_on_def, rule_format]\n\nlemma decisive_on_empty:\n  shows \"decisive_on {} f\"\nunfolding decisive_on_def by simp\n\nlemma decisive_on_mono:\n  assumes \"decisive_on A f\"\n  assumes \"B \\<subseteq> A\"\n  shows \"decisive_on B f\"\nusing assms order_trans unfolding decisive_on_def by auto\n\n(*>*)\ntext\\<open>\n\nOften we can mildly generalise existing results by not requiring that\n@{term \"f\"} be @{const \"decisive\"}, and by dropping the finiteness\nhypothesis. We make essential use of the former generalization in\n\\S\\ref{sec:contracts}.\n\nSome choice functions, such as those arising from linear orders\n(\\S\\ref{sec:cf-linear}), are @{emph \\<open>resolute\\<close>}: these always yield a\nsingle choice.\n\n\\<close>\n\ndefinition resolute_on :: \"'a set \\<Rightarrow> 'a cfun \\<Rightarrow> bool\" where\n  \"resolute_on A f \\<longleftrightarrow> (\\<forall>B\\<subseteq>A. B \\<noteq> {} \\<longrightarrow> (\\<exists>a. f B = {a}))\"\n\nabbreviation resolute :: \"'a cfun \\<Rightarrow> bool\" where\n  \"resolute \\<equiv> resolute_on UNIV\"\n\nlemma resolute_on_decisive_on:\n  assumes \"resolute_on A f\"\n  shows \"decisive_on A f\"\nusing %invisible assms unfolding resolute_on_def by - (rule decisive_onI; auto)\n\ntext\\<open>\n\nOften we talk about the choices that are rejected by \\<open>f\\<close>:\n\n\\label{sec:cf-rf}\n\n\\<close>\n\nabbreviation Rf :: \"'a cfun \\<Rightarrow> 'a cfun\" where\n  \"Rf f X \\<equiv> X - f X\"\n\ntext\\<open>\n\nTypically there are many (almost-)equivalent formulations of each\nproperty in the literature. We try to formulate our rules in terms of\nthe most general of these.\n\n\\<close>\n\n\nsubsection\\<open> The @{emph \\<open>substitutes\\<close>} condition, AKA @{emph \\<open>independence of irrelevant alternatives\\<close>} \\label{sec:cf-substitutes} AKA @{emph \\<open>Chernoff\\<close>} \\<close>\n\ntext\\<open>\n\nLoosely speaking, the @{emph \\<open>substitutes\\<close>} condition asserts that an\nalternative that is rejected from @{term \"A\"} shall remain rejected\nwhen there is ``increased competition,'' i.e., from all sets that\ncontain @{term \"A\"}.\n\n\\citet{HatfieldMilgrom:2005} define this property as simply the\nmonotonicity of @{const \"Rf\"}. \\citet{AygunSonmez:2012-WP2} instead\nuse the complicated condition shown here. Condition\n\\<open>\\<alpha>\\<close>, due to \\citet[p17, see below]{Sen:1970}, is\nthe most general and arguably the most perspicuous.\n\n\\<close>\n\ndefinition substitutes_on :: \"'a set \\<Rightarrow> 'a cfun \\<Rightarrow> bool\" where\n  \"substitutes_on A f \\<longleftrightarrow> \\<not>(\\<exists>B\\<subseteq>A. \\<exists>a b. {a, b} \\<subseteq> A - B \\<and> b \\<notin> f (B \\<union> {b}) \\<and> b \\<in> f (B \\<union> {a, b}))\"\n\nabbreviation substitutes :: \"'a cfun \\<Rightarrow> bool\" where\n  \"substitutes \\<equiv> substitutes_on UNIV\"\n\nlemma substitutes_on_def2[simplified]:\n  \"substitutes_on A f \\<longleftrightarrow> (\\<forall>B\\<subseteq>A. \\<forall>a\\<in>A. \\<forall>b\\<in>A. b \\<notin> f (B \\<union> {b}) \\<longrightarrow> b \\<notin> f (B \\<union> {a, b}))\"\n(*<*)\n(is \"?lhs \\<longleftrightarrow> ?rhs\")\nproof (rule iffI, clarsimp)\n  fix B a b\n  assume lhs: ?lhs and XXX: \"B \\<subseteq> A\" \"a \\<in> A\" \"b \\<in> A\" \"b \\<notin> f (insert b B)\" \"b \\<in> f (insert a (insert b B))\"\n  show False\n  proof(cases \"a \\<in> B\")\n    case True with XXX show ?thesis by (simp add: insert_absorb)\n  next\n    case False with lhs XXX show ?thesis\n      unfolding substitutes_on_def\n      by (cases \"b \\<in> B\") (fastforce dest: spec[where x=\"B - {a, b}\"] simp: insert_commute insert_absorb)+\n  qed\nqed (fastforce simp: substitutes_on_def)\n\nlemmas substitutes_onI = iffD2[OF substitutes_on_def2, rule_format, simplified]\nlemmas substitutes_onD = iffD1[OF substitutes_on_def2, rule_format, simplified]\n\nlemmas substitutesD = substitutes_onD[where A=UNIV, simplified]\n\n(*>*)\ntext\\<open>\\<close>\n\nlemma substitutes_on_union:\n  assumes \"a \\<notin> f (B \\<union> {a})\"\n  assumes \"substitutes_on (A \\<union> B \\<union> {a}) f\"\n  assumes \"finite A\"\n  shows \"a \\<notin> f (A \\<union> B \\<union> {a})\"\nusing %invisible assms(3,1-2) by induct (simp_all add: insert_commute substitutes_on_def2 le_iff_sup)\n\nlemma substitutes_on_antimono:\n  assumes \"substitutes_on B f\"\n  assumes \"A \\<subseteq> B\"\n  shows \"substitutes_on A f\"\nusing %invisible assms unfolding substitutes_on_def2 by auto\n\ntext\\<open>\n\nThe equivalence with the monotonicity of alternative-rejection\nrequires a finiteness constraint.\n\n\\<close>\n\nlemma substitutes_on_Rf_mono_on:\n  assumes \"substitutes_on A f\"\n  assumes \"finite A\"\n  shows \"mono_on (Pow A) (Rf f)\"\nproof %invisible (rule mono_onI, rule subsetI)\n  fix B C x assume \"B \\<in> Pow A\" \"C \\<in> Pow A\" \"B \\<subseteq> C\" \"x \\<in> Rf f B\"\n  with assms substitutes_on_union[where a=x and A=C and B=B and f=f] show \"x \\<in> Rf f C\"\n    by (clarsimp simp: insert_absorb) (metis rev_finite_subset subsetCE substitutes_on_antimono sup.orderE)\nqed\n\nlemma Rf_mono_on_substitutes:\n  assumes \"mono_on (Pow A) (Rf f)\"\n  shows \"substitutes_on A f\"\nproof %invisible (rule substitutes_onI)\n  fix B a b assume \"B \\<subseteq> A\" \"a \\<in> A\" \"b \\<in> A\" \"b \\<notin> f (insert b B)\"\n  with assms show \"b \\<notin> f (insert a (insert b B))\"\n    by (auto elim: mono_onE[where x=\"insert b B\" and y=\"insert a (insert b B)\"])\nqed\n\ntext\\<open>\n\nThe above substitutes condition is equivalent to the\n@{emph \\<open>independence of irrelevant alternatives\\<close>}, AKA condition\n\\<open>\\<alpha>\\<close> due to \\citet{Sen:1970}. Intuitively if\n\\<open>a\\<close> is chosen from a set \\<open>A\\<close>, then it must\nbe chosen from every subset of \\<open>A\\<close> that it belongs\nto. Note the lack of finiteness assumptions here.\n\n\\<close>\n\ndefinition iia_on :: \"'a set \\<Rightarrow> 'a cfun \\<Rightarrow> bool\" where\n  \"iia_on A f \\<longleftrightarrow> (\\<forall>B\\<subseteq>A. \\<forall>C\\<subseteq>B. \\<forall>a\\<in>C. a \\<in> f B \\<longrightarrow> a \\<in> f C)\"\n\nabbreviation iia :: \"'a cfun \\<Rightarrow> bool\" where\n  \"iia \\<equiv> iia_on UNIV\"\n\nlemmas %invisible iia_onI = iffD2[OF iia_on_def, rule_format, unfolded conj_imp_eq_imp_imp]\nlemmas %invisible iia_onD = iffD1[OF iia_on_def, rule_format, unfolded conj_imp_eq_imp_imp]\n\nlemma Rf_mono_on_iia_on:\n  shows \"mono_on (Pow A) (Rf f) \\<longleftrightarrow> iia_on A f\"\nunfolding %invisible iia_on_def by (rule iffI) (blast elim: mono_onE intro!: mono_onI)+\n\nlemma Rf_mono_iia:\n  shows \"mono (Rf f) \\<longleftrightarrow> iia f\"\nusing %invisible Rf_mono_on_iia_on[of UNIV f] mono_on_mono by (simp add: fun_eq_iff) blast\n\nlemma substitutes_iia:\n  assumes \"finite A\"\n  shows \"substitutes_on A f \\<longleftrightarrow> iia_on A f\"\nusing %invisible Rf_mono_on_iia_on Rf_mono_on_substitutes substitutes_on_Rf_mono_on[OF _ assms] by blast\n\ntext\\<open>\n\nOne key result is that the choice function must be idempotent if it\nsatisfies @{const \"iia\"} or any of the equivalent conditions.\n\n\\<close>\n\nlemma iia_f_idem:\n  assumes \"f_range_on A f\"\n  assumes \"iia_on A f\"\n  assumes \"B \\<subseteq> A\"\n  shows \"f (f B) = f B\"\nusing %invisible assms unfolding iia_on_def\nby (meson f_range_onD f_range_on_antimono subset_antisym subset_eq)\n\ntext\\<open>\n\n\\citet[p914, bottom right]{HatfieldMilgrom:2005} claim that the\n@{const \"substitutes\"} condition coincides with the\n@{emph \\<open>substitutable preferences\\<close>} condition for the college admissions\nproblem of \\citet[Definition~6.2]{RothSotomayor:1990}, which is\nsimilar to @{const \"iia\"}:\n\n\\<close>\n\ndefinition substitutable_preferences_on :: \"'a set \\<Rightarrow> 'a cfun \\<Rightarrow> bool\" where\n  \"substitutable_preferences_on A f \\<longleftrightarrow> (\\<forall>B\\<subseteq>A. \\<forall>a\\<in>B. \\<forall>b\\<in>B. a \\<noteq> b \\<and> a \\<in> f B \\<longrightarrow> a \\<in> f (B - {b}))\"\n\nlemmas %invisible substitutable_preferences_onI = iffD2[OF substitutable_preferences_on_def, rule_format, unfolded conj_imp_eq_imp_imp]\n\nlemma substitutable_preferences_on_substitutes_on:\n  shows \"substitutable_preferences_on A f \\<longleftrightarrow> substitutes_on A f\" (is \"?lhs \\<longleftrightarrow> ?rhs\")\nproof %invisible (rule iffI)\n  assume ?lhs then show ?rhs\n    unfolding substitutable_preferences_on_def\n    by - (rule substitutes_onI; metis Diff_insert_absorb insertCI insert_absorb insert_subset)\nnext\n  assume ?rhs show ?lhs\n  proof(rule substitutable_preferences_onI)\n    fix B a b\n    assume XXX: \"B \\<subseteq> A\" \"a \\<in> B\" \"b \\<in> B\" \"a \\<noteq> b\" \"a \\<in> f B\"\n    then have \"a \\<in> A\" \"b \\<in> A\" \"B - {b} - {a} \\<subseteq> A\" by blast+\n    with \\<open>?rhs\\<close> XXX show \"a \\<in> f (B - {b})\"\n      unfolding substitutes_on_def2 by (metis insertE insert_Diff)\n  qed\nqed\n\ntext\\<open>\n\n\\citet[p152]{Moulin:1985} defines an equivalent @{emph \\<open>Chernoff\\<close>}\ncondition. Intuitively this captures the idea that ``a best choice in\nsome issue [set of alternatives] is still best if the issue shrinks.''\n\n\\<close>\n\ndefinition Chernoff_on :: \"'a set \\<Rightarrow> 'a cfun \\<Rightarrow> bool\" where\n  \"Chernoff_on A f \\<longleftrightarrow> (\\<forall>B\\<subseteq>A. \\<forall>C\\<subseteq>B. f B \\<inter> C \\<subseteq> f C)\"\n\nabbreviation Chernoff :: \"'a cfun \\<Rightarrow> bool\" where\n  \"Chernoff \\<equiv> Chernoff_on UNIV\"\n\nlemmas Chernoff_onI = iffD2[OF Chernoff_on_def, rule_format]\nlemmas Chernoff_def = Chernoff_on_def[where A=UNIV, simplified]\n\nlemma Chernoff_on_iia_on:\n  shows \"Chernoff_on A f \\<longleftrightarrow> iia_on A f\"\nunfolding %invisible Chernoff_on_def iia_on_def by blast\n\nlemma Chernoff_on_union:\n  assumes \"Chernoff_on A f\"\n  assumes \"f_range_on A f\"\n  assumes \"B \\<subseteq> A\" \"C \\<subseteq> A\"\n  shows \"f (B \\<union> C) \\<subseteq> f B \\<union> f C\"\nusing %invisible assms unfolding Chernoff_on_def f_range_on_def\nby clarsimp (metis (mono_tags, lifting) Int_iff Un_iff Un_subset_iff contra_subsetD inf_sup_ord(3,4))\n\ntext\\<open>\n\n\\citet[p159]{Moulin:1985} states a series of equivalent formulations\nof the @{const \"Chernoff\"} condition. He also claims that these hold\nif the two sets are disjoint.\n\n\\<close>\n\nlemma Chernoff_a:\n  assumes \"f_range_on A f\"\n  shows \"Chernoff_on A f \\<longleftrightarrow> (\\<forall>B C. B \\<subseteq> A \\<and> C \\<subseteq> A \\<longrightarrow> f (B \\<union> C) \\<subseteq> f B \\<union> C)\" (is \"?lhs \\<longleftrightarrow> ?rhs\")\nproof %invisible (rule iffI)\n  assume ?lhs with \\<open>f_range_on A f\\<close> show ?rhs by (auto dest: f_range_onD' Chernoff_on_union)\nnext\n  assume ?rhs show ?lhs\n  proof(rule Chernoff_onI)\n    fix B C assume \"B \\<subseteq> A\" \"C \\<subseteq> B\"\n    with spec[OF spec[OF \\<open>?rhs\\<close>, where x=\"C\"], where x=\"B - C\"] show \"f B \\<inter> C \\<subseteq> f C\"\n      by (fastforce simp add: Un_absorb1)\n  qed\nqed\n\nlemma Chernoff_b: \\<comment> \\<open>essentially the converse of @{thm [source] Chernoff_on_union}\\<close>\n  assumes \"f_range_on A f\"\n  shows \"Chernoff_on A f \\<longleftrightarrow> (\\<forall>B C. B \\<subseteq> A \\<and> C \\<subseteq> A \\<longrightarrow> f (B \\<union> C) \\<subseteq> f B \\<union> f C)\" (is \"?lhs \\<longleftrightarrow> ?rhs\")\nproof %invisible (rule iffI)\n  assume ?lhs with \\<open>f_range_on A f\\<close> show ?rhs using Chernoff_on_union by blast\nnext\n  assume ?rhs show ?lhs\n  proof(rule Chernoff_onI)\n    fix B C assume \"B \\<subseteq> A\" \"C \\<subseteq> B\"\n    with \\<open>f_range_on A f\\<close> spec[OF spec[OF \\<open>?rhs\\<close>, where x=\"C\"], where x=\"B - C\"]\n    show \"f B \\<inter> C \\<subseteq> f C\" by (clarsimp simp: Un_absorb1) (blast dest: f_range_onD')\n  qed\nqed\n\nlemma Chernoff_c:\n  assumes \"f_range_on A f\"\n  shows \"Chernoff_on A f \\<longleftrightarrow> (\\<forall>B C. B \\<subseteq> A \\<and> C \\<subseteq> A \\<longrightarrow> f (B \\<union> C) \\<subseteq> f (f B \\<union> C))\" (is \"?lhs \\<longleftrightarrow> ?rhs\")\nproof %invisible (rule iffI)\n  assume ?lhs show ?rhs\n  proof(safe)\n    fix B C x\n    assume B: \"B \\<subseteq> A\" and C: \"C \\<subseteq> A\" and x: \"x \\<in> f (B \\<union> C)\"\n    from B C have \"f (B \\<union> C) \\<subseteq> f B \\<union> f C\" by (rule Chernoff_on_union[OF \\<open>?lhs\\<close> \\<open>f_range_on A f\\<close>])\n    with \\<open>f_range_on A f\\<close> C x have \"x \\<in> f B \\<union> C\" by (blast dest: f_range_onD)\n    moreover from \\<open>f_range_on A f\\<close> B have \"f B \\<union> C \\<subseteq> B \\<union> C\" by (blast dest: f_range_onD)\n    moreover note B C x\n    ultimately show \"x \\<in> f (f B \\<union> C)\"\n      using iia_onD[OF iffD1[OF Chernoff_on_iia_on \\<open>?lhs\\<close>]] by (metis Un_subset_iff)\n  qed\nnext\n  assume ?rhs with \\<open>f_range_on A f\\<close> show ?lhs\n    unfolding f_range_on_def\n    by (clarsimp simp: Chernoff_a[OF \\<open>f_range_on A f\\<close>])\n       (metis (no_types, lifting) Un_iff Un_subset_iff rev_subsetD subset_trans)\nqed\n\nlemma Chernoff_d:\n  assumes \"f_range_on A f\"\n  shows \"Chernoff_on A f \\<longleftrightarrow> (\\<forall>B C. B \\<subseteq> A \\<and> C \\<subseteq> A \\<longrightarrow> f (B \\<union> C) \\<subseteq> f (f B \\<union> f C))\" (is \"?lhs \\<longleftrightarrow> ?rhs\")\nproof %invisible (rule iffI)\n  assume ?lhs show ?rhs\n  proof(intro allI impI)\n    fix B C x\n    assume BC: \"B \\<subseteq> A \\<and> C \\<subseteq> A\"\n    with \\<open>f_range_on A f\\<close> \\<open>?lhs\\<close> have \"f (B \\<union> C) \\<subseteq> f (f B \\<union> C)\" by (metis Chernoff_c Un_commute)\n    with \\<open>f_range_on A f\\<close> BC show \"f (B \\<union> C) \\<subseteq> f (f B \\<union> f C)\"\n      using iffD1[OF Chernoff_c[OF \\<open>f_range_on A f\\<close>] \\<open>?lhs\\<close>]\n      unfolding f_range_on_def by (metis Un_commute inf.absorb_iff2 le_infI1)\n  qed\nnext\n  assume ?rhs with \\<open>f_range_on A f\\<close> show ?lhs\n    unfolding f_range_on_def\n    by (clarsimp simp: Chernoff_a[OF assms])\n       (metis (no_types, lifting) Un_iff Un_subset_iff rev_subsetD subset_trans)\nqed\n\n\nsubsection\\<open> The @{emph \\<open>irrelevance of rejected contracts\\<close>} condition AKA @{emph \\<open>consistency\\<close>} AKA @{emph \\<open>Aizerman\\<close>} \\label{sec:cf-irc} \\<close>\n\ntext\\<open>\n\n\\citet[\\S4]{AygunSonmez:2012-WP2} propose to repair the results of\n\\citet{HatfieldMilgrom:2005} by imposing the @{emph \\<open>irrelevance of\nrejected contracts\\<close>} (IRC) condition. Intuitively this requires the\nchoice function @{term \"f\"} to ignore unchosen alternatives.\n\n\\<close>\n\ndefinition irc_on :: \"'a set \\<Rightarrow> 'a cfun \\<Rightarrow> bool\" where\n  \"irc_on A f \\<longleftrightarrow> (\\<forall>B\\<subseteq>A. \\<forall>a\\<in>A. a \\<notin> f (B \\<union> {a}) \\<longrightarrow> f (B \\<union> {a}) = f B)\"\n\nabbreviation irc :: \"'a cfun \\<Rightarrow> bool\" where\n  \"irc \\<equiv> irc_on UNIV\"\n\nlemmas %invisible irc_onI = iffD2[OF irc_on_def, rule_format, simplified]\nlemmas %invisible irc_onD = iffD1[OF irc_on_def, rule_format, simplified]\nlemmas %invisible irc_def = irc_on_def[where A=UNIV, simplified]\nlemmas %invisible ircI = iffD2[OF irc_def, rule_format, simplified]\nlemmas %invisible ircD = iffD1[OF irc_def, rule_format, simplified]\n\nlemma irc_on_discard:\n  assumes \"irc_on A f\"\n  assumes \"finite C\"\n  assumes \"B \\<union> C \\<subseteq> A\"\n  assumes \"f (B \\<union> C) \\<inter> C = {}\"\n  shows \"f (B \\<union> C) = f B\"\nusing %invisible assms(2,3,4)\nproof induct\n  case (insert c C) with assms(1) show ?case\n    unfolding irc_on_def by simp (metis Un_subset_iff)\nqed simp\n\ntext\\<open>\n\nAn equivalent condition is called @{emph \\<open>consistency\\<close>} by some\n(\\citet[Definition~2]{ChambersYenmez:2013},\n\\citet[Equation~(14)]{Fleiner:2002}). Like @{const \"iia\"}, this\nformulation generalizes to infinite universes.\n\n\\<close>\n\ndefinition consistency_on :: \"'a set \\<Rightarrow> 'a cfun \\<Rightarrow> bool\" where\n  \"consistency_on A f \\<longleftrightarrow> (\\<forall>B\\<subseteq>A. \\<forall>C\\<subseteq>B. f B \\<subseteq> C \\<longrightarrow> f B = f C)\"\n\nabbreviation consistency :: \"'a cfun \\<Rightarrow> bool\" where\n  \"consistency \\<equiv> consistency_on UNIV\"\n\nlemmas %invisible consistency_onI = iffD2[OF consistency_on_def, rule_format, unfolded conj_imp_eq_imp_imp]\nlemmas %invisible consistency_onD = iffD1[OF consistency_on_def, rule_format, unfolded conj_imp_eq_imp_imp]\nlemmas %invisible consistency_def = consistency_on_def[where A=UNIV, simplified]\nlemmas %invisible consistencyD = iffD1[OF consistency_def, rule_format, unfolded conj_imp_eq_imp_imp]\n\nlemma irc_on_consistency_on:\n  assumes \"irc_on A f\"\n  assumes \"finite A\"\n  shows \"consistency_on A f\"\nproof %invisible (rule consistency_onI)\n  fix B C assume \"B \\<subseteq>A\" \"f B \\<subseteq> C\" \"C \\<subseteq> B\"\n  then have \"C \\<union> (B - f B) = B\" by blast\n  with \\<open>B \\<subseteq>A\\<close> \\<open>finite A\\<close> show \"f B = f C\"\n    using irc_on_discard[OF assms(1), where B=C and C=\"B - f B\"] by (simp add: finite_subset)\nqed\n\nlemma consistency_on_irc_on:\n  assumes \"f_range_on A f\"\n  assumes \"consistency_on A f\"\n  shows \"irc_on A f\"\nproof %invisible (rule irc_onI)\n  fix B b assume \"B \\<subseteq> A\" \"b \\<in> A\" \"b \\<notin> f (insert b B)\"\n  with assms show \"f (insert b B) = f B\"\n    by - (erule consistency_onD; blast dest: f_range_onD')\nqed\n\ntext\\<open>\n\nThese conditions imply that @{term \"f\"} is idempotent:\n\n\\<close>\n\nlemma consistency_on_f_idem:\n  assumes \"f_range_on A f\"\n  assumes \"consistency_on A f\"\n  assumes \"B \\<subseteq> A\"\n  shows \"f (f B) = f B\"\nusing %invisible assms by (metis consistency_onD f_range_onD order_refl)\n\ntext\\<open>\n\n\\citet[p154]{Moulin:1985} defines a similar but weaker property he\ncalls @{emph \\<open>Aizerman\\<close>}:\n\n\\<close>\n\ndefinition Aizerman_on :: \"'a set \\<Rightarrow> 'a cfun \\<Rightarrow> bool\" where\n  \"Aizerman_on A f \\<longleftrightarrow> (\\<forall>B\\<subseteq>A. \\<forall>C\\<subseteq>B. f B \\<subseteq> C \\<longrightarrow> f C \\<subseteq> f B)\"\n\nabbreviation Aizerman :: \"'a cfun \\<Rightarrow> bool\" where\n  \"Aizerman \\<equiv> Aizerman_on UNIV\"\n\nlemmas %invisible Aizerman_onI = iffD2[OF Aizerman_on_def, rule_format, unfolded conj_imp_eq_imp_imp]\nlemmas %invisible Aizerman_onD = iffD1[OF Aizerman_on_def, rule_format, unfolded conj_imp_eq_imp_imp]\nlemmas %invisible Aizerman_def = Aizerman_on_def[where A=UNIV, simplified]\n\nlemma consistency_on_Aizerman_on:\n  assumes \"consistency_on A f\"\n  shows \"Aizerman_on A f\"\nusing %invisible assms by (metis Aizerman_onI consistency_onD order_refl)\n\ntext\\<open>\n\nThe converse requires @{term \"f\"} to be idempotent\n\\citep[p157]{Moulin:1985}:\n\n\\<close>\n\nlemma Aizerman_on_idem_on_consistency_on:\n  assumes \"Aizerman_on A f\"\n  assumes \"\\<forall>B\\<subseteq>A. f (f B) = f B\"\n  shows \"consistency_on A f\"\nby %invisible (rule consistency_onI) (metis inf.coboundedI2 le_iff_inf set_eq_subset Aizerman_onD[OF assms(1)] assms(2))\n\n\nsubsection\\<open> The @{emph \\<open>law of aggregate demand\\<close>} condition aka @{emph \\<open>size monotonicity\\<close>} \\label{sec:cf-lad} \\<close>\n\ntext\\<open>\n\n\\citet[{\\S}III]{HatfieldMilgrom:2005} impose the @{emph \\<open>law of\naggregate demand\\<close>} (aka @{emph \\<open>size monotonicity\\<close>}) to obtain the rural\nhospitals theorem (\\S\\ref{sec:contracts-rh}). It captures the\nfollowing intuition:\n\\begin{quote}\n\n[...] Roughly, this law states that as the price falls, agents should\ndemand more of a good. Here, price falls correspond to more contracts\nbeing available, and more demand corresponds to taking on (weakly)\nmore contracts.\n\n\\end{quote}\n\nThe @{const \"card\"} function takes a finite set into its cardinality\n(as a natural number).\n\n\\<close>\n\ndefinition lad_on :: \"'a set \\<Rightarrow> 'a::finite cfun \\<Rightarrow> bool\" where\n  \"lad_on A f \\<longleftrightarrow> (\\<forall>B\\<subseteq>A. \\<forall>C\\<subseteq>B. card (f C) \\<le> card (f B))\"\n\nabbreviation lad :: \"'a::finite cfun \\<Rightarrow> bool\" where\n  \"lad \\<equiv> lad_on UNIV\"\n\ntext\\<open>\n\nThis definition is identical amongst\n\\citet[{\\S}III]{HatfieldMilgrom:2005}, \\citet[(20)]{Fleiner:2002}, and\n\\citet[Definition~4]{AygunSonmez:2012-WP2}.\n\n\\<close>\n(*<*)\n\nlemma lad_onD:\n  assumes \"lad_on A f\"\n  assumes \"C \\<subseteq> B\"\n  assumes \"B \\<subseteq> A\"\n  shows \"card (f C) \\<le> card (f B)\"\nusing assms unfolding lad_on_def by blast\n\nlemma ladD:\n  assumes \"lad f\"\n  assumes \"\\<And>x. x \\<in> C \\<Longrightarrow> x \\<in> B\"\n  shows \"card (f C) \\<le> card (f B)\"\nusing assms unfolding lad_on_def by (simp add: subsetI)\n\n(*>*)\ntext\\<open>\n\n\\citet[\\S5, Proposition~1]{AygunSonmez:2012-WP2} show that @{const\n\"substitutes\"} and @{const \"lad\"} imply @{const \"irc\"}, which\ntherefore rescues many results in the matching-with-contracts\nliterature.\n\n\\<close>\n\nlemma lad_on_substitutes_on_irc_on:\n  assumes \"f_range_on A f\"\n  assumes \"substitutes_on A f\"\n  assumes \"lad_on A f\"\n  shows \"irc_on A f\"\nproof %invisible (rule irc_onI, rule card_seteq)\n  fix B b assume bB: \"B \\<subseteq> A\" \"b \\<in> A\" \"b \\<notin> f (insert b B)\"\n  show \"finite (f B)\" by simp\n  show \"f (insert b B) \\<subseteq> f B\"\n  proof\n    fix x assume x: \"x \\<in> f (insert b B)\"\n    with \\<open>f_range_on A f\\<close> bB have \"insert x B = B \\<or> x = b\"\n      by clarsimp (blast dest: f_range_onD')\n    with \\<open>substitutes_on A f\\<close> bB x show \"x \\<in> f B\"\n      by (metis insert_subset substitutes_onD)\n  qed\n  from \\<open>lad_on A f\\<close> bB show \"card (f B) \\<le> card (f (insert b B))\"\n    unfolding lad_on_def by (simp add: subset_insertI)\nqed\n\ntext\\<open>\n\nThe converse does not hold.\n\n\\<close>\n\n\nsubsection\\<open> The @{emph \\<open>expansion\\<close>} condition \\<close>\n\ntext\\<open>\n\nAccording to \\citet[p152]{Moulin:1985}, a choice function satifies\n@{emph \\<open>expansion\\<close>} if an alternative chosen from two sets is also chosen\nfrom their union.\n\n\\<close>\n\ndefinition expansion_on :: \"'a set \\<Rightarrow> 'a cfun \\<Rightarrow> bool\" where\n  \"expansion_on A f \\<longleftrightarrow> (\\<forall>B\\<subseteq>A. \\<forall>C\\<subseteq>A. f B \\<inter> f C \\<subseteq> f (B \\<union> C))\"\n\nabbreviation expansion :: \"'a cfun \\<Rightarrow> bool\" where\n  \"expansion \\<equiv> expansion_on UNIV\"\n\nlemmas %invisible expansion_onI = iffD2[OF expansion_on_def, rule_format]\nlemmas %invisible expansion_onD = iffD1[OF expansion_on_def, rule_format, THEN subsetD, simplified, unfolded conj_imp_eq_imp_imp]\n\ntext\\<open>\n\nCondition \\<open>\\<gamma>\\<close> due to \\citet{Sen:1971} generalizes\n@{const \"expansion\"} to collections of sets of choices.\n\n\\<close>\n\ndefinition expansion_gamma_on :: \"'a set \\<Rightarrow> 'a set set \\<Rightarrow> 'a cfun \\<Rightarrow> bool\" where\n  \"expansion_gamma_on A As f \\<longleftrightarrow> (\\<Union>As\\<subseteq>A \\<and> As \\<noteq> {} \\<longrightarrow> (\\<Inter>A\\<in>As. f A) \\<subseteq> f (\\<Union>As))\"\n\ndefinition expansion_gamma :: \"'a set set \\<Rightarrow> 'a cfun \\<Rightarrow> bool\" where\n  \"expansion_gamma \\<equiv> expansion_gamma_on UNIV\"\n\nlemmas %invisible expansion_gamma_onI = iffD2[OF expansion_gamma_on_def, rule_format, unfolded conj_imp_eq_imp_imp]\nlemmas %invisible expansion_gamma_onE = iffD1[OF expansion_gamma_on_def, rule_format, THEN subsetD, simplified, unfolded conj_imp_eq_imp_imp]\n\nlemma expansion_gamma_expansion:\n  assumes \"\\<forall>As. expansion_gamma_on A As f\"\n  shows \"expansion_on A f\"\nproof %invisible (rule expansion_onI, rule subsetI)\n  fix B C x\n  assume \"B \\<subseteq> A\" \"C \\<subseteq> A\" \"x \\<in> f B \\<inter> f C\" then show \"x \\<in> f (B \\<union> C)\"\n    using expansion_gamma_onE[OF spec[OF assms], where As=\"{B,C}\"] by simp\nqed\n\nlemma expansion_expansion_gamma:\n  assumes \"expansion_on A f\"\n  assumes \"finite As\"\n  shows \"expansion_gamma_on A As f\"\nproof %invisible (rule expansion_gamma_onI[OF subsetI])\n  fix x assume \"\\<Union>As \\<subseteq> A\" \"As \\<noteq> {}\" \"x \\<in> (\\<Inter>A\\<in>As. f A)\"\n  from \\<open>finite As\\<close> this show \"x \\<in> f (\\<Union>As)\"\n  proof induct\n    case (insert b B) with assms show ?case by (cases \"B = {}\") (auto dest: expansion_onD)\n  qed simp\nqed\n\ntext\\<open>\n\nThe @{const \"expansion\"} condition plays a major role in the study of\nthe @{emph \\<open>rationalizability\\<close>} of choice functions, which we explore\nnext.\n\n\\<close>\n\n\nsubsection\\<open> Axioms of revealed preference \\label{sec:cf-revealed_preference} \\<close>\n\ntext\\<open>\n\nWe digress from our taxonomy of conditions on choice functions to\ndiscuss @{emph \\<open>rationalizability\\<close>}. A choice function is\n@{emph \\<open>rationalizable\\<close>} if there exists some binary relation that generates\nit, typically by taking the @{emph \\<open>greatest\\<close>} or @{emph \\<open>maximal\\<close>} elements\nof the given set of alternatives:\n\n\\<close>\n\ndefinition greatest :: \"'a rel \\<Rightarrow> 'a cfun\" where\n  \"greatest r X = {x\\<in>X. \\<forall>y\\<in>X. (y, x) \\<in> r}\"\n\ndefinition maximal :: \"'a rel \\<Rightarrow> 'a cfun\" where\n  \"maximal r X = {x\\<in>X. \\<forall>y\\<in>X. \\<not>(x, y) \\<in> r}\"\n\nlemma (in MaxR) greatest:\n  shows \"set_option (MaxR_opt X) = greatest r (X \\<inter> Field r)\"\nusing %invisible greatest_is_MaxR_opt MaxR_opt_is_greatest unfolding greatest_def by (blast dest: range_Some)\n(*<*)\n\nlemma greatest_r_mono:\n  assumes \"Above r X \\<subseteq> Above r' X\"\n  shows \"greatest r X \\<subseteq> greatest r' X\"\nusing assms unfolding greatest_def Above_def by (fast intro: FieldI1)\n\nlemmas greatest_r_mono' = subsetD[OF greatest_r_mono, rotated]\n\nlemma greatest_Above:\n  shows \"greatest r X = Above r X \\<inter> X\"\nunfolding greatest_def Above_def by (blast intro: FieldI1)\n\n(*>*)\ntext\\<open>\n\nNote that @{const \"greatest\"} requires the relation to be reflexive\nand total, and @{const \"maximal\"} requires it to be irreflexive, for\nthe choice functions to ever yield non-empty sets.\n\nThis game of uncovering the preference relations (if any) underlying a\nchoice function goes by the name of @{emph \\<open>revealed preference\\<close>}. (In\ncontrast, later we show how these conditions guarantee the existence\nof stable many-to-one matches.) See \\citet{Moulin:1985} and\n\\citet{Border:2012} for background, intuition and critique, and\n\\citet{Sen:1971} for further classical results and proofs.\n\nWe adopt the following notion here:\n\n\\<close>\n\ndefinition rationalizes_on :: \"'a set \\<Rightarrow> 'a cfun \\<Rightarrow> 'a rel \\<Rightarrow> bool\" where\n  \"rationalizes_on A f r \\<longleftrightarrow> (\\<forall>B\\<subseteq>A. f B = greatest r B)\"\n\nabbreviation rationalizes :: \"'a cfun \\<Rightarrow> 'a rel \\<Rightarrow> bool\" where\n  \"rationalizes \\<equiv> rationalizes_on UNIV\"\n\nlemma %invisible rationalizes_onI:\n  assumes \"f_range_on A f\"\n  assumes \"\\<And>B x y. \\<lbrakk>B \\<subseteq> A; x \\<in> f B; y \\<in> B\\<rbrakk> \\<Longrightarrow> (y, x) \\<in> r\"\n  assumes \"\\<And>B x. \\<lbrakk>B \\<subseteq> A; x \\<in> B; \\<forall>y\\<in>B. (y, x) \\<in> r\\<rbrakk> \\<Longrightarrow> x \\<in> f B\"\n  shows \"rationalizes_on A f r\"\nusing assms unfolding rationalizes_on_def greatest_def by (auto dest: f_range_onD)\n\ntext\\<open>\n\nIn words, relation @{term \"r\"} rationalizes the choice function @{term\n\"f\"} over universe @{term \"A\"} if @{term \"f B\"} picks out the @{term\n\"greatest\"} elements of @{term \"B \\<subseteq> A\"} with respect to\n@{term \"r\"}. At this point @{term \"r\"} can be any relation that does\nthe job, but soon enough we will ask that it satisfy some familiar\nordering properties.\n\nThe analysis begins by determining under what constraints @{term \"f\"}\ncan be rationalized, continues by establishing some properties of all\nrationalizable choice functions, and concludes by considering what it\ntakes to establish stronger properties.\n\nFollowing \\citet[\\S5, Definition~2]{Border:2012} and\n\\citet[Definition~2]{Sen:1971}, we can generate the @{emph \\<open>revealed\nweakly preferred\\<close>} relation for the choice function @{term \"f\"}:\n\n\\<close>\n\ndefinition rwp_on :: \"'a set \\<Rightarrow> 'a cfun \\<Rightarrow> 'a rel\" where\n  \"rwp_on A f = {(x, y). \\<exists>B\\<subseteq>A. x \\<in> B \\<and> y \\<in> f B}\"\n\nabbreviation rwp :: \"'a cfun \\<Rightarrow> 'a rel\" where\n  \"rwp \\<equiv> rwp_on UNIV\"\n\nlemma %invisible rwp_on_Field:\n  assumes \"f_range_on A f\"\n  shows \"Field (rwp_on A f) \\<subseteq> A\"\nusing assms unfolding f_range_on_def rwp_on_def Field_def by auto\n\nlemma rwp_on_refl_on:\n  assumes \"f_range_on A f\"\n  assumes \"decisive_on A f\"\n  shows \"refl_on A (rwp_on A f)\"\nproof %invisible (rule refl_onI)\n  from \\<open>f_range_on A f\\<close> show \"rwp_on A f \\<subseteq> A \\<times> A\"\n    unfolding rwp_on_def f_range_on_def by blast\n  fix x assume \"x \\<in> A\"\n  with assms show \"(x, x) \\<in> rwp_on A f\"\n    unfolding rwp_on_def decisive_on_def f_range_on_def\n    by (fast dest: spec[where x=\"{x}\"] intro: exI[where x=\"{x}\"])\nqed\n\ntext\\<open>\n\nIn words, if it is ever possible that @{term \"x \\<in> B\"} is available\nand @{term \"f B\"} chooses @{term \"y\"}, then @{term \"y\"} is taken to\nalways be at least as good as @{term \"x\"}.\n\nThe @{emph \\<open>V-axiom\\<close>} asserts that whatever is revealed to be at least as\ngood as anything else on offer is chosen:\n\n\\<close>\n\ndefinition V_axiom_on :: \"'a set \\<Rightarrow> 'a cfun \\<Rightarrow> bool\" where\n  \"V_axiom_on A f \\<longleftrightarrow> (\\<forall>B\\<subseteq>A. \\<forall>y\\<in>B. (\\<forall>x \\<in> B. (x, y) \\<in> rwp_on A f) \\<longrightarrow> y \\<in> f B)\"\n\nabbreviation V_axiom :: \"'a cfun \\<Rightarrow> bool\" where\n  \"V_axiom \\<equiv> V_axiom_on UNIV\"\n\ntext\\<open>\n\nThis axiom characterizes rationality; see\n\\citet[Theorem~7]{Border:2012}. \\citet[\\S3]{Sen:1971} calls a decisive\nchoice function that satisfies @{const \"V_axiom\"} @{emph \\<open>normal\\<close>}.\n\n\\<close>\n\nlemma rationalizes_on_f_range_on_V_axiom_on:\n  assumes \"rationalizes_on A f r\"\n  shows \"f_range_on A f\"\n    and \"V_axiom_on A f\"\nusing %invisible assms unfolding V_axiom_on_def rationalizes_on_def greatest_def f_range_on_def rwp_on_def by simp_all blast+\n\nlemma f_range_on_V_axiom_on_rationalizes_on:\n  assumes \"f_range_on A f\"\n  assumes \"V_axiom_on A f\"\n  shows \"rationalizes_on A f (rwp_on A f)\"\nusing %invisible assms rwp_on_Field[OF assms(1)]\nunfolding V_axiom_on_def rationalizes_on_def greatest_def f_range_on_def rwp_on_def\nby auto\n\ntheorem V_axiom_on_rationalizes_on:\n  shows \"(f_range_on A f \\<and> V_axiom_on A f) \\<longleftrightarrow> (\\<exists>r. rationalizes_on A f r)\"\nusing %invisible rationalizes_on_f_range_on_V_axiom_on f_range_on_V_axiom_on_rationalizes_on by blast\n\ntext\\<open>\n\nWe could also ask that @{term \"f\"} be determined directly by how it\nbehaves on pairs (\\citet{Sen:1971}, \\citet[p151]{Moulin:1985}), which\nturns out to be equivalent:\n\n\\<close>\n\ndefinition rationalizable_binary_on :: \"'a set \\<Rightarrow> 'a cfun \\<Rightarrow> bool\" where\n  \"rationalizable_binary_on A f \\<longleftrightarrow> (\\<forall>B\\<subseteq>A. f B = {y \\<in> B. \\<forall>x\\<in>B. y \\<in> f {x, y}})\"\n\nabbreviation rationalizable_binary :: \"'a cfun \\<Rightarrow> bool\" where\n  \"rationalizable_binary \\<equiv> rationalizable_binary_on UNIV\"\n\nlemma %invisible rationalizable_binary_onI:\n  assumes \"f_range_on A f\"\n  assumes \"\\<And>B x y. \\<lbrakk>B \\<subseteq> A; y \\<in> f B; x \\<in> B; y \\<in> B\\<rbrakk> \\<Longrightarrow> y \\<in> f {x, y}\"\n  assumes \"\\<And>B y. \\<lbrakk>B \\<subseteq> A; y \\<in> B; \\<forall>x\\<in>B. y \\<in> f {x, y}\\<rbrakk> \\<Longrightarrow> y \\<in> f B\"\n  shows \"rationalizable_binary_on A f\"\nunfolding rationalizable_binary_on_def using assms by (blast dest: f_range_onD' intro: FieldI1)\n\ntheorem V_axiom_realizable_binary:\n  assumes \"f_range_on A f\"\n  shows \"V_axiom_on A f \\<longleftrightarrow> rationalizable_binary_on A f\"\n(*<*)\n(is \"?lhs = ?rhs\")\nproof (rule iffI)\n  assume lhs: ?lhs show ?rhs\n  proof(rule rationalizable_binary_onI[OF assms])\n    fix B x y assume \"B \\<subseteq> A\" \"y \\<in> f B\" \"x \\<in> B\" \"y \\<in> B\"\n    with lhs show \"y \\<in> f {x, y}\"\n      unfolding V_axiom_on_def rwp_on_def by (auto dest: spec[where x=\"{x, y}\"])\n  next\n    fix B y assume \"B \\<subseteq> A\" \"y \\<in> B\" \"\\<forall>x\\<in>B. y \\<in> f {x, y}\"\n    with lhs show \"y \\<in> f B\"\n      unfolding V_axiom_on_def rwp_on_def\n      by clarsimp (metis Un_subset_iff insertI1 insert_is_Un mk_disjoint_insert)\n  qed\nnext\n  assume ?rhs then show ?lhs\n    unfolding V_axiom_on_def rwp_on_def rationalizable_binary_on_def by force\nqed\n\n(*>*)\ntext\\<open>\n\nAll rationalizable choice functions satisfy @{const \"iia\"} and @{const\n\"expansion\"} (\\citet{Sen:1971}, \\citet[p152]{Moulin:1985}).\n\n\\<close>\n\nlemma rationalizable_binary_on_iia_on:\n  assumes \"f_range_on A f\"\n  assumes \"rationalizable_binary_on A f\"\n  shows \"iia_on A f\"\nusing %invisible assms unfolding iia_on_def rationalizable_binary_on_def f_range_on_def\nby simp (meson contra_subsetD)\n\nlemma rationalizable_binary_on_expansion_on:\n  assumes \"f_range_on A f\"\n  assumes \"rationalizable_binary_on A f\"\n  shows \"expansion_on A f\"\nusing  %invisible assms unfolding rationalizable_binary_on_def f_range_on_def\nby - (rule expansion_onI; auto)\n\ntext\\<open>\n\nThe converse requires the set of alternatives to be finite, and\nmoreover fails if the choice function is not @{const \"decisive\"}.\n\n\\<close>\n\nlemma rationalizable_binary_on_converse:\n  fixes f :: \"'a::finite cfun\"\n  assumes \"f_range_on A f\"\n  assumes \"decisive_on A f\"\n  assumes \"iia_on A f\"\n  assumes \"expansion_on A f\"\n  shows \"rationalizable_binary_on A f\"\nproof %invisible (rule rationalizable_binary_onI[OF assms(1)])\n  fix B x y\n  assume \"B \\<subseteq> A\" \"y \\<in> f B\" \"x \\<in> B\" \"y \\<in> B\" with \\<open>iia_on A f\\<close> show \"y \\<in> f {x, y}\"\n    unfolding iia_on_def by fastforce\nnext\n  fix B y\n  assume XXX: \"y \\<in> B\" and YYY: \"\\<forall>x\\<in>B. y \\<in> f {x, y}\" \"B \\<subseteq> A\"\n  have \"y \\<in> f (insert y C)\" if \"C \\<subseteq> B\" for C\n  using finite[of C] that XXX YYY\n  proof induct\n    case empty with \\<open>decisive_on A f\\<close> show ?case\n      unfolding decisive_on_def by force\n  next\n    case (insert b C) with \\<open>expansion_on A f\\<close> show ?case\n      by (force dest!: expansion_onD[where C=\"{b, y}\" and B=\"insert y C\"] simp: insert_commute)\n  qed\n  note this[OF subset_refl]\n  with XXX show \"y \\<in> f B\" by (simp add: insert_absorb)\nqed\n\ntext\\<open>\n\nThat settles the issue of existence, but it is not clear that the\nrelation is really ``rational'' (for instance, @{term \"rwp_on A f\"}\nneed not be transitive). Therefore the analysis continues by further\nconstraining the choice function so that it is rationalized by\nfamiliar ordering relations.\n\nFor instance, the following shows that the @{emph \\<open>axioms of revealed\npreference\\<close>} are rationalized by total preorders \\citep[Definitions~8\nand~13]{Sen:1971}\\footnote{For \\citet[p9]{Sen:1970}, an ordering is\ncomplete (total), reflexive, and transitive. Alternative names are:\ncomplete pre-ordering, complete quasi-ordering, and weak\nordering.}. These are alo equivalent to some congruence axioms due to\nSamuelson \\citep{Border:2012}.\n\nWe define @{term \"x\"} to be @{emph \\<open>strictly revealed-preferred to\\<close>}\n@{term \"y\"} if there is a situation where both are on offer and only\n@{term \"y\"} is chosen:\n\n\\<close>\n\ndefinition rsp_on :: \"'a set \\<Rightarrow> 'a cfun \\<Rightarrow> 'a rel\" where \\<comment> \\<open>\\citep[Definition~8]{Sen:1971}\\<close>\n  \"rsp_on A f = {(x, y). \\<exists>B\\<subseteq>A. x \\<in> Rf f B \\<and> y \\<in> f B}\"\n\nabbreviation rsp :: \"'a cfun \\<Rightarrow> 'a rel\" where\n  \"rsp \\<equiv> rsp_on UNIV\"\n\ntext\\<open>\n\nThis relation is typically denoted by @{term \"P\"}, for strict\npreference. The not-worse-than relation @{term \"R\"} is recovered by:\n\n\\<close>\n\ndefinition rspR_on :: \"'a set \\<Rightarrow> 'a cfun \\<Rightarrow> 'a rel\" where \\<comment> \\<open>\\citep[Definition~9]{Sen:1971}\\<close>\n  \"rspR_on A f = {(x, y). {x, y} \\<subseteq> A \\<and> (y, x) \\<notin> rsp_on A f}\"\n\nabbreviation rspR :: \"'a cfun \\<Rightarrow> 'a rel\" where\n  \"rspR \\<equiv> rspR_on UNIV\"\n\nlemma %invisible rsp_on_range:\n  assumes \"f_range_on A f\"\n  shows \"rsp_on A f \\<subseteq> A \\<times> A\"\nusing assms unfolding rsp_on_def f_range_on_def by blast\n\ntext\\<open>\n\n\\citet[p309]{Sen:1971} defines the @{emph \\<open>weak axiom of revealed\npreference\\<close>} (WARP) as follows:\n\n\\<close>\n\ndefinition warp_on :: \"'a set \\<Rightarrow> 'a cfun \\<Rightarrow> bool\" where\n  \"warp_on A f \\<longleftrightarrow> (\\<forall>(x, y)\\<in>rsp_on A f. (y, x) \\<notin> rwp_on A f)\"\n\nabbreviation warp :: \"'a cfun \\<Rightarrow> bool\" where\n  \"warp \\<equiv> warp_on UNIV\"\n\ntext\\<open>\n\nThe @{emph \\<open>strong axiom of revealed preference\\<close>} (SARP) is essentially\nthe transitive closure of @{const \"warp\"} \\citep[p309]{Sen:1971}:\n\n\\<close>\n\ndefinition sarp_on :: \"'a set \\<Rightarrow> 'a cfun \\<Rightarrow> bool\" where\n  \"sarp_on A f \\<longleftrightarrow> (\\<forall>(x, y)\\<in>(rsp_on A f)\\<^sup>+. (y, x) \\<notin> rwp_on A f)\"\n\nabbreviation sarp :: \"'a cfun \\<Rightarrow> bool\" where\n  \"sarp \\<equiv> sarp_on UNIV\"\n\nlemma %invisible sarp_onI:\n  assumes \"\\<And>x y. (x, y) \\<in> (rsp_on A f)\\<^sup>+ \\<Longrightarrow> (y, x) \\<notin> rwp_on A f\"\n  shows \"sarp_on A f\"\nusing assms unfolding sarp_on_def by blast\n\nlemma sarp_on_warp_on: \\<comment> \\<open>\\citet[T.3 part]{Sen:1970}\\<close>\n  assumes \"sarp_on A f\"\n  shows \"warp_on A f\"\nusing %invisible assms unfolding sarp_on_def warp_on_def rwp_on_def rsp_on_def by blast\n\nlemma rsp_on_irrefl:\n  \"A \\<noteq> {} \\<Longrightarrow> irrefl (rsp_on A f)\"\nunfolding %invisible rsp_on_def irrefl_def by fastforce\n\ntext\\<open>\n\nFor decisive choice functions, @{const \"warp\"} implies @{const\n\"sarp\"}. We show this following \\citet{Sen:1971}, via the @{emph \\<open>weak\ncongruence axiom\\<close>} (WCA): if @{term \"f\"} chooses @{term \"x\"} from some\nset @{term \"B\"} and @{term \"y\"} is revealed to be weakly preferred,\nthen @{term \"f\"} must choose @{term \"y\"} from @{term \"B\"} as well.\n\n\\<close>\n\ndefinition wca_on :: \"'a set \\<Rightarrow> 'a cfun \\<Rightarrow> bool\" where\n  \"wca_on A f \\<longleftrightarrow> (\\<forall>(x, y)\\<in>rwp_on A f. \\<forall>B\\<subseteq>A. x \\<in> f B \\<and> y \\<in> B \\<longrightarrow> y \\<in> f B)\"\n\nabbreviation wca :: \"'a cfun \\<Rightarrow> bool\" where\n  \"wca \\<equiv> wca_on UNIV\"\n\nlemma %invisible wca_onI:\n  assumes \"\\<And>B x y. \\<lbrakk> B \\<subseteq> A; (x, y) \\<in> rwp_on A f; x \\<in> f B; y \\<in> B \\<rbrakk> \\<Longrightarrow> y \\<in> f B\"\n  shows \"wca_on A f\"\nunfolding wca_on_def using assms by blast\n\ntext\\<open>\n\nDecisive choice functions that satisfy @{const \"wca\"} are rationalized\nby total preorders, in particular @{const \"rwp\"}, and the converse\nobtains if they are normal.\n\n\\<close>\n\nlemma wca_on_V_axiom_on:\n  assumes \"wca_on A f\"\n  assumes \"f_range_on A f\"\n  assumes \"decisive_on A f\"\n  shows \"V_axiom_on A f\"\nusing %invisible assms unfolding V_axiom_on_def wca_on_def rwp_on_def\nby clarsimp (metis (mono_tags) ex_in_conv f_range_onD'[where A=A and f=f] decisive_onD[where A=A and f=f])\n\nlemma wca_on_total_on:\n  assumes \"wca_on A f\"\n  assumes \"f_range_on A f\"\n  assumes \"decisive_on A f\"\n  shows \"total_on A (rwp_on A f)\"\nproof %invisible(rule total_onI)\n fix x y\n assume \"x \\<in> A\" \"y \\<in> A\" \"x \\<noteq> y\"\n with assms show \"(x, y) \\<in> rwp_on A f \\<or> (y, x) \\<in> rwp_on A f\"\n  unfolding wca_on_def decisive_on_def rwp_on_def total_on_def f_range_on_def\n  by (fast dest: spec[where x=\"{x,y}\"] intro: exI[where x=\"{x,y}\"])\nqed\n\nlemma rwp_on_trans:\n  assumes \"wca_on A f\"\n  assumes \"f_range_on A f\"\n  assumes \"decisive_on A f\"\n  shows \"trans (rwp_on A f)\"\nproof %invisible (rule transI)\n  fix x y z assume \"(x, y) \\<in> rwp_on A f\" \"(y, z) \\<in> rwp_on A f\"\n  then obtain B C where \"B \\<union> C \\<subseteq> A\" \"x \\<in> B\" \"y \\<in> f B\" \"y \\<in> C\" \"z \\<in> f C\"\n    unfolding rwp_on_def by blast\n  from \\<open>x \\<in> B\\<close> have \"x \\<in> B \\<union> C\" by blast\n  moreover\n  have \"z \\<in> f (B \\<union> C)\"\n  proof(cases \"y \\<in> f (B \\<union> C)\")\n    case True\n    with \\<open>wca_on A f\\<close> \\<open>f_range_on A f\\<close> \\<open>y \\<in> C\\<close> \\<open>z \\<in> f C\\<close> \\<open>B \\<union> C \\<subseteq> A\\<close>\n    show ?thesis\n      unfolding wca_on_def rwp_on_def\n      by simp (meson \\<open>B \\<union> C \\<subseteq> A\\<close> f_range_onD' inf_sup_ord(4) subsetCE)\n  next\n    case False\n    with assms \\<open>B \\<union> C \\<subseteq> A\\<close> \\<open>y \\<in> f B\\<close> \\<open>z \\<in> f C\\<close>\n    obtain w where \"w \\<in> f (B \\<union> C) \\<and> w \\<in> C\"\n      unfolding wca_on_def decisive_on_def rwp_on_def\n      by (clarsimp simp: ex_in_conv[symmetric] dest!: spec[where x=\"B \\<union> C\"])\n         (metis Un_iff \\<open>B \\<union> C \\<subseteq> A\\<close> f_range_onD')\n    with \\<open>wca_on A f\\<close> \\<open>f_range_on A f\\<close> \\<open>B \\<union> C \\<subseteq> A\\<close> \\<open>z \\<in> f C\\<close> show ?thesis\n      unfolding wca_on_def rwp_on_def\n      by simp (meson \\<open>B \\<union> C \\<subseteq> A\\<close> f_range_onD' inf_sup_ord(4) subsetCE)\n  qed\n  moreover note \\<open>B \\<union> C \\<subseteq> A\\<close>\n  ultimately show \"(x, z) \\<in> rwp_on A f\" unfolding rwp_on_def by blast\nqed\n\nlemma wca_on_V_axiom_on_preorder_on: \\<comment> \\<open>\\citet[T.1, T.3 part]{Sen:1970}\\<close>\n  assumes \"f_range_on A f\"\n  assumes \"decisive_on A f\"\n  shows \"wca_on A f \\<longleftrightarrow> V_axiom_on A f \\<and> preorder_on A (rwp_on A f) \\<and> total_on A (rwp_on A f)\"\n(*<*)\n(is \"?lhs \\<longleftrightarrow> ?rhs\")\nproof(rule iffI)\n  assume ?lhs with rwp_on_refl_on rwp_on_trans wca_on_V_axiom_on wca_on_total_on assms show ?rhs\n    unfolding preorder_on_def by blast\nnext\n  assume rhs: ?rhs\n  show ?lhs\n  proof(rule wca_onI)\n    fix B x y assume \"B \\<subseteq> A\" \"(x, y) \\<in> rwp_on A f\" \"x \\<in> f B\" \"y \\<in> B\"\n    from \\<open>B \\<subseteq> A\\<close> \\<open>x \\<in> f B\\<close> have \"\\<forall>z\\<in>B. (z, x) \\<in> rwp_on A f\"\n      unfolding rwp_on_def by blast\n    with rhs \\<open>(x, y) \\<in> rwp_on A f\\<close> have \"\\<forall>z\\<in>B. (z, y) \\<in> rwp_on A f\"\n      unfolding preorder_on_def by (blast elim: transE)\n    with rhs \\<open>B \\<subseteq> A\\<close> \\<open>y \\<in> B\\<close> show \"y \\<in> f B\"\n      unfolding V_axiom_on_def by blast\n  qed\nqed\n\n(*>*)\ntext\\<open>\\<close>\n\nlemma wca_on_rwp_on_rspR_on: \\<comment> \\<open>\\citet[T.2]{Sen:1970}\\<close>\n  assumes \"wca_on A f\"\n  assumes \"f_range_on A f\"\n  assumes \"decisive_on A f\"\n  shows \"rwp_on A f = rspR_on A f\"\n(*<*)\n(is \"?lhs = ?rhs\")\nproof(rule set_elem_equalityI)\n  fix x assume \"x \\<in> ?lhs\"\n  with \\<open>wca_on A f\\<close> rwp_on_refl_on[OF assms(2,3)] show \"x \\<in> ?rhs\"\n    unfolding wca_on_def rsp_on_def rspR_on_def by (force dest: refl_onD1 refl_onD2)\nnext\n  fix x assume \"x \\<in> ?rhs\"\n  with assms show \"x \\<in> ?lhs\"\n    unfolding wca_on_def rsp_on_def rspR_on_def rwp_on_def decisive_on_def\n    by (auto 3 0 simp: split_def\n               intro!: exI[where x=\"{fst x, snd x}\"]\n                dest!: spec[where x=\"{fst x, snd x}\"]\n                 dest: f_range_onD')\nqed\n(*>*)\ntext\\<open>\\<close>\n\nlemma rwp_on_rspR_on_wca_on: \\<comment> \\<open>\\citet[T.2]{Sen:1970}\\<close>\n  assumes \"rwp_on A f = rspR_on A f\"\n  shows \"wca_on A f\"\nusing %invisible assms unfolding wca_on_def rsp_on_def rspR_on_def by blast\n\nlemma wca_on_warp_on: \\<comment> \\<open>\\citet[T.3 part]{Sen:1970}\\<close>\n  shows \"wca_on A f \\<longleftrightarrow> warp_on A f\"\nunfolding %invisible warp_on_def wca_on_def rsp_on_def rwp_on_def by blast\n\nlemma warp_on_sarp_on: \\<comment> \\<open>\\citet[T.3 part]{Sen:1970}\\<close>\n  assumes \"warp_on A f\"\n  assumes \"f_range_on A f\"\n  assumes \"decisive_on A f\"\n  shows \"sarp_on A f\"\nproof(rule sarp_onI)\n  from \\<open>warp_on A f\\<close> have \"wca_on A f\" unfolding wca_on_warp_on .\n  then have XXX: \"rwp_on A f = rspR_on A f\"\n        and YYY: \"preorder_on A (rspR_on A f)\"\n        and ZZZ: \"total_on A (rspR_on A f)\"\n    using %invisible wca_on_rwp_on_rspR_on[OF _ assms(2,3)] wca_on_V_axiom_on_preorder_on[OF assms(2,3)] wca_on_total_on[OF _ assms(2,3)] by fastforce+\n  fix a b assume \"(a, b) \\<in> (rsp_on A f)\\<^sup>+\"\n  then have \"{a, b} \\<subseteq> A\" and \"(b, a) \\<notin> rspR_on A f\"\n  proof(induct a b)\n    case (r_into_trancl a b)\n    { case 1 from r_into_trancl rsp_on_range[OF assms(2)] show ?case by blast }\n    { case 2 from r_into_trancl show ?case by (simp add: rspR_on_def) }\n  next\n    case (trancl_into_trancl a b c)\n    { case 1 from trancl_into_trancl rsp_on_range[OF assms(2)] show ?case by blast }\n    { case 2 from trancl_into_trancl rsp_on_range[OF assms(2)] YYY ZZZ show ?case\n        unfolding total_on_def preorder_on_def\n        by clarsimp (metis (no_types, lifting) case_prodD mem_Collect_eq rspR_on_def transD) }\n  qed\n  with XXX show \"(b, a) \\<notin> rwp_on A f\" by simp\nqed\n\ntext\\<open>\n\nThe @{const \"decisive\"} constraint here is necessary: consider a\nCondorcet cycle over @{term \"{x, y, z}\"}: forcing @{term \"f {x, y,\nz}\"} to be non-empty resolves this.\n\n\\citet{Sen:1971} proves that these and other conditions on choice\nfunctions are equivalent (under the @{const \"decisive\"} hypothesis).\n\n\\<close>\n\n\nsubsubsection\\<open> The @{emph \\<open>strong axiom of revealed preference\\<close>} ala \\citet{AygunSonmez:2012-WP2} \\<close>\n\ntext\\<open>\n\n\\citet[\\S6]{AygunSonmez:2012-WP2} adopt a different definition for a\n@{emph \\<open>strong axiom of revealed preference\\<close>} and show that it holds for\nall choice functions that satisfy @{const \"iia\"} and @{const\n\"consistency\"}.\n\n\\<close>\n\nabbreviation nth_mod :: \"'a list \\<Rightarrow> nat \\<Rightarrow> 'a\" (infixl \"!%\" 100) where\n  \"xs !% i \\<equiv> xs ! (i mod length xs)\"\n\ndefinition mwc_sarp :: \"'a cfun \\<Rightarrow> bool\" where\n  \"mwc_sarp f \\<longleftrightarrow>\n    \\<not>(\\<exists>Xs. length Xs > 1 \\<and> distinct (map f Xs) \\<and> (\\<forall>i. f (Xs!%i) \\<subset> Xs!%i \\<inter> Xs!%(i+1)))\"\n\nlemma %invisible mwc_sarpI:\n  assumes \"\\<And>Xs. \\<lbrakk>length Xs > 1; distinct (map f Xs); \\<forall>i. f (Xs!%i) \\<subset> Xs!%i \\<inter> Xs!%(i+1)\\<rbrakk> \\<Longrightarrow> False\"\n  shows \"mwc_sarp f\"\nunfolding mwc_sarp_def using assms by blast\n\nlemma iia_consistency_mwc_sarp:\n  assumes \"f_range f\"\n  assumes \"iia f\" \\<comment> \\<open>@{const \"substitutes\"}\\<close>\n  assumes \"consistency f\" \\<comment> \\<open>@{const \"irc\"}\\<close>\n  shows \"mwc_sarp f\"\nproof(rule mwc_sarpI)\n  fix Xs\n  assume LLL: \"length Xs > 1\"\n     and EEE: \"distinct (map f Xs)\"\n     and AAA: \"\\<forall>i. f (Xs!%i) \\<subset> Xs!%i \\<inter> Xs!%(i+1)\"\n  have 6: \"f (\\<Union>(set Xs)) \\<subseteq> (\\<Inter>X\\<in>set Xs. f X)\"\n  proof -\n    have 4: \"x \\<notin> f (\\<Union>(set Xs))\" if \"x \\<in> \\<Union>(set Xs) - (\\<Union>X\\<in>set Xs. f X)\" for x\n      using that \\<open>iia f\\<close> unfolding iia_on_def by simp blast\n    have 5: \"x \\<notin> f (\\<Union>(set Xs))\" if \"x \\<in> (\\<Union>X\\<in>set Xs. f X) - (\\<Inter>X\\<in>set Xs. f X)\" for x\n    proof -\n      from that obtain j k where \"x \\<in> f (Xs ! j)\" \"x \\<notin> f (Xs ! k)\" \"j < length Xs\" \"k < length Xs\"\n        by (clarsimp simp: in_set_conv_nth)\n      with AAA LLL ex_least_nat_le[where n=\"k + length Xs - j\" and P=\"\\<lambda>i. x \\<notin> f (Xs !% (i + j))\"]\n      obtain i where \"x \\<in> f (Xs !% i) - f (Xs !% (i+1))\"\n        by %invisible auto (metis One_nat_def add_eq_if diff_diff_cancel diff_is_0_eq' lessI mod_less nat_le_linear zero_less_diff)\n      with AAA have \"x \\<in> Rf f (Xs!%(i+1))\" by auto\n      with LLL show \"x \\<notin> f (\\<Union>(set Xs))\"\n        using \\<open>iia f\\<close> unfolding iia_on_def by clarsimp (meson Suc_lessD Sup_upper mod_less_divisor nth_mem)\n    qed\n    from 4 5 have \"x \\<notin> f (\\<Union>(set Xs))\" if \"x \\<in> (\\<Union>(set Xs)) - (\\<Inter>X\\<in>set Xs. f X)\" for x\n      using that by blast\n    with \\<open>f_range f\\<close> show ?thesis by (blast dest: f_range_onD)\n  qed\n  moreover have \"\\<forall>i. (\\<Inter>X\\<in>set Xs. f X) \\<subset> f (Xs!%i)\"\n  proof -\n    from \\<open>f_range f\\<close> LLL have \"\\<Inter>(f ` set Xs) \\<subseteq> Xs ! 1\"\n      using nth_mem f_range_onD by fastforce\n    with \\<open>consistency f\\<close> LLL 6 have f4: \"f (\\<Union>(set Xs)) = f (Xs ! 1)\"\n      by - (rule consistencyD[where f=f], force+)\n    with \\<open>f_range f\\<close> LLL 6 have \"f (Xs ! 1) \\<subseteq> Xs ! 0\"\n      using f_range_onD by (metis INT_lower One_nat_def Suc_lessD subset_trans nth_mem top.extremum)\n    with \\<open>consistency f\\<close> EEE LLL f4 show ?thesis\n      by (metis One_nat_def Suc_lessD Sup_upper consistencyD length_map nth_eq_iff_index_eq nth_map nth_mem zero_neq_one)\n  qed\n  moreover have \"\\<forall>i. f (Xs!%i) = f (\\<Union>(set Xs))\"\n  proof -\n    from AAA have \"\\<forall>i. f (Xs!%i) \\<subseteq> Xs!%i\" by auto\n    moreover from LLL have \"\\<forall>i. Xs!%i \\<subseteq> \\<Union>(set Xs)\"\n      by (metis One_nat_def Suc_lessD Sup_upper mod_less_divisor nth_mem)\n    moreover note 6 \\<open>\\<forall>i. (\\<Inter>X\\<in>set Xs. f X) \\<subset> f (Xs !% i)\\<close>\n    ultimately show \"\\<forall>i. f (Xs!%i) = f (\\<Union>(set Xs))\"\n      by - (clarsimp; rule consistencyD[OF \\<open>consistency f\\<close>, symmetric]; meson dual_order.trans psubsetE)\n  qed\n  ultimately show False by force\nqed\n\n\nsubsection\\<open> Choice functions arising from linear orders \\label{sec:cf-linear} \\<close>\n\ntext\\<open>\n\nAn obvious way to construct a choice function is to derive one from a\nlinear order, i.e., a list of strict preferences. We allow such\nrankings to omit some alternatives, which means the resulting function\nis not decisive.\n\nWe work with a finite universe here.\n\n\\<close>\n\nlocale linear_cf =\n  fixes r :: \"'a::finite rel\"\n  fixes linear_cf :: \"'a cfun\"\n  assumes r_linear: \"Linear_order r\"\n  assumes linear_cf_def: \"linear_cf X \\<equiv> set_option (MaxR.MaxR_opt r X)\"\nbegin\n\ninterpretation MaxR: MaxR r by unfold_locales (rule r_linear)\n\n(*<*)\n\nlemmas maxR_code = MaxR.maxR_def\nlemmas MaxR_f_code = MaxR.MaxR_f_def\nlemma code:\n  shows \"linear_cf (set X) = set_option (fold MaxR.MaxR_f X None)\"\nunfolding linear_cf_def using MaxR.MaxR_opt_code by simp\n\nlemma simps [nitpick_simp]:\n  shows \"linear_cf {} = {}\"\n        \"linear_cf (insert x X) = (if x \\<in> Field r then if linear_cf X = {} then {x} else {MaxR.maxR x y |y. y \\<in> linear_cf X} else linear_cf X)\"\nunfolding linear_cf_def by (simp_all add: MaxR.insert split: option.splits)\n\n(*>*)\n\nlemma range:\n  shows \"linear_cf X \\<subseteq> X \\<inter> Field r\"\nunfolding %invisible linear_cf_def using MaxR.range[of X] finite[of X] by fastforce\n\nlemmas range' = rev_subsetD[OF _ range, of x] for x\n\nlemma singleton:\n  shows \"x \\<in> linear_cf X \\<longleftrightarrow> linear_cf X = {x}\"\nunfolding %invisible linear_cf_def by fastforce\n\n\n\nlemma union:\n  shows \"linear_cf (X \\<union> Y) = (if linear_cf X = {} then linear_cf Y else if linear_cf Y = {} then linear_cf X else {MaxR.maxR x y |x y. x \\<in> linear_cf X \\<and> y \\<in> linear_cf Y})\"\nunfolding %invisible linear_cf_def by (auto simp: MaxR.union)\n\nlemma mono:\n  assumes \"x \\<in> linear_cf X\"\n  shows \"\\<exists>y \\<in> linear_cf (X \\<union> Y). (x, y) \\<in> r\"\nusing %invisible MaxR.mono assms unfolding linear_cf_def by (metis elem_set)\n\nlemmas greatest = MaxR.greatest[folded linear_cf_def]\n\nlemma preferred:\n  assumes \"(x, y) \\<in> r\"\n  assumes \"x \\<in> linear_cf X\"\n  assumes \"y \\<in> X\"\n  shows \"y = x\"\nusing %invisible assms FieldI2 MaxR.MaxR_opt_is_greatest MaxR.maxR_absorb1 maxR_code unfolding linear_cf_def by fastforce\n\nlemma card_le:\n  shows \"card (linear_cf X) \\<le> 1\"\nunfolding %invisible linear_cf_def by (cases \"MaxR.MaxR_opt X\") simp_all\n\nlemma card:\n  shows \"card (linear_cf X) = (if X \\<inter> Field r = {} then 0 else 1)\"\nunfolding %invisible linear_cf_def by (cases \"MaxR.MaxR_opt X\") (auto dest: MaxR.range_None MaxR.range_Some)\n\nlemma f_range:\n  shows \"f_range_on X linear_cf\"\nunfolding %invisible f_range_on_def using range by blast\n\nlemma domain:\n  shows \"linear_cf (X \\<inter> Field r) = linear_cf X\"\nby %invisible (metis inf.cobounded1 range subset)\n\nlemma decisive_on:\n  shows \"decisive_on (Field r) linear_cf\"\nunfolding %invisible decisive_on_def linear_cf_def\nby (metis Int_absorb2 empty_subsetI MaxR.range_None MaxR.empty MaxR.subset)\n\nlemma resolute_on:\n  shows \"resolute_on (Field r) linear_cf\"\nunfolding %invisible resolute_on_def linear_cf_def using mk_disjoint_insert by (force simp: MaxR.insert)\n\nlemma Rf_mono_on:\n  shows \"mono_on X (Rf linear_cf)\"\nby %invisible (rule mono_onI) (clarsimp; metis contra_subsetD empty_subsetI insert_subset singleton subset)\n\nlemmas iia = iffD1[OF Rf_mono_on_iia_on Rf_mono_on]\n\nlemma Chernoff:\n  shows \"Chernoff_on X linear_cf\"\nusing %invisible Rf_mono_on range Rf_mono_on_iia_on[of X linear_cf, symmetric] Chernoff_on_iia_on by blast\n\nlemma irc:\n  shows \"irc_on X linear_cf\"\nunfolding %invisible irc_on_def linear_cf_def\nby (clarsimp simp: MaxR.insert dest!: MaxR.maxR_rangeD split: option.splits)\n\nlemma consistency:\n  shows \"consistency_on X linear_cf\"\nusing %invisible irc by (rule irc_on_consistency_on) simp\n\nlemma lad:\n  shows \"lad_on X linear_cf\"\nunfolding %invisible lad_on_def by (cases \"X \\<inter> Field r = {}\") (auto simp: card)\n\nend\n\n\nsubsection\\<open> Plott's @{emph \\<open>path independence\\<close>} condition \\label{sec:cf-path-independence}\\<close>\n\ntext\\<open>\n\nAs recognised by \\citet[\\S4]{Fleiner:2002} and\n\\citet{ChambersYenmez:2013} in the context of matching with contracts,\nthe @{const \"irc\"} and @{const \"substitutes\"} conditions together are\nequivalent to @{emph \\<open>path independence\\<close>}, a condition introduced to the\nsocial choice setting by\n\\citet{Plott:1973}. \\citet[Lemma~6]{Moulin:1985} ascribes this\nequivalence result to \\citet{AizermanMalishevski:1981}.\n\n\\<close>\n\ndefinition path_independent_on :: \"'a set \\<Rightarrow> 'a cfun \\<Rightarrow> bool\" where\n  \"path_independent_on A f \\<longleftrightarrow> (\\<forall>B C. B \\<subseteq> A \\<and> C \\<subseteq> A \\<longrightarrow> f (B \\<union> C) = f (B \\<union> f C))\"\n\nabbreviation path_independent :: \"'a cfun \\<Rightarrow> bool\" where\n  \"path_independent \\<equiv> path_independent_on UNIV\"\n\n(*<*)\n\nlemmas path_independent_onI = iffD2[OF path_independent_on_def, rule_format]\nlemmas path_independent_onD = iffD1[OF path_independent_on_def, rule_format, unfolded conj_imp_eq_imp_imp]\nlemmas path_independent_def = path_independent_on_def[where A=UNIV, simplified]\n\n(*>*)\ntext\\<open>\n\nIntuitively a choice function satisfying this condition ignores the\norder in which choices are made in the following sense:\n\n\\<close>\n\nlemma path_independent_on_symmetric:\n  assumes \"f_range_on A f\"\n  shows \"path_independent_on A f \\<longleftrightarrow> (\\<forall>B C. B \\<subseteq> A \\<and> C \\<subseteq> A \\<longrightarrow> f (B \\<union> C) = f (f B \\<union> f C))\"\nusing %invisible assms unfolding path_independent_on_def f_range_on_def\nby - (rule iffI, metis subset_trans Un_commute, metis (full_types) Un_subset_iff empty_subsetI sup.orderE Un_commute)\n\nlemmas %invisible path_independent_on_symmetricI = iffD2[OF path_independent_on_symmetric, rule_format, unfolded conj_imp_eq_imp_imp]\nlemmas %invisible path_independent_on_symmetricD = iffD1[OF path_independent_on_symmetric, rule_format, unfolded conj_imp_eq_imp_imp]\n\nlemma path_independent_on_Chernoff_on:\n  assumes \"path_independent_on A f\"\n  assumes \"f_range_on A f\"\n  shows \"Chernoff_on A f\"\nproof %invisible (rule Chernoff_onI[OF subsetI])\n  fix B C x assume XXX: \"B \\<subseteq> A\" \"C \\<subseteq> B\" \"x \\<in> f B \\<inter> C\"\n  from \\<open>f_range_on A f\\<close> XXX have \"f C \\<subseteq> B\" by - (erule subset_trans[OF f_range_onD], simp_all)\n  with \\<open>f_range_on A f\\<close> XXX have YYY: \"f (B - C \\<union> f C) \\<subseteq> B - C \\<union> f C\" by (fastforce elim!: f_range_onD)\n  from XXX YYY path_independent_onD[OF \\<open>path_independent_on A f\\<close>, where B=\"B - C\" and C=\"C\"] \\<open>f_range_on A f\\<close>\n  show \"x \\<in> f C\"\n    unfolding f_range_on_def by (auto simp: Un_absorb2)\nqed\n\nlemma path_independent_on_consistency_on:\n  assumes \"path_independent_on A f\"\n  shows \"consistency_on A f\"\nusing %invisible assms unfolding path_independent_on_def\nby - (rule consistency_onI; metis Un_subset_iff le_iff_sup sup_commute)\n\nlemma Chernoff_on_consistency_on_path_independent_on:\n  assumes \"f_range_on A f\"\n  shows \"Chernoff_on A f \\<and> consistency_on A f \\<longleftrightarrow> path_independent_on A f\"\n(*<*)\n(is \"?lhs \\<longleftrightarrow> ?rhs\")\nproof %invisible (rule iffI)\n  assume LHS: ?lhs show ?rhs\n  proof(rule path_independent_on_symmetricI[OF assms])\n    fix B C assume BC: \"B \\<subseteq> A\" \"C \\<subseteq> A\"\n    with LHS assms show \"f (B \\<union> C) = f (f B \\<union> f C)\"\n      by - (rule consistency_onD[where A=A and f=f, OF _ _ _ Chernoff_on_union[OF _ assms]];\n            blast dest: f_range_onD)\n  qed\nnext\n  assume ?rhs with assms path_independent_on_Chernoff_on path_independent_on_consistency_on\n  show ?lhs by blast\nqed\n\nlemmas path_independent_onI2 =\n  iffD1[OF Chernoff_on_consistency_on_path_independent_on, unfolded conj_imp_eq_imp_imp]\n\n(*>*)\ntext\\<open>\\<close>\n\nlemma (in linear_cf) path_independent:\n  shows \"path_independent linear_cf\"\nusing %invisible f_range Chernoff consistency by (blast intro: path_independent_onI2)\n\n\nsubsubsection\\<open> Path independence and decomposition into orderings \\label{sec:cf-path-independence-orderings} \\<close>\n\ntext\\<open>\n\nWe now show that a choice function over a finite universe satisfying\n@{const \"path_independent\"} is characterized by taking the maximum\nelements of some finite set of orderings.\n\n\\citet[Definition~12]{Moulin:1985} says that a choice function is\n@{emph \\<open>pseudo-rationalized\\<close>} by the orderings @{term \"Rs\"} if @{term\n\"f\"} chooses all of the @{term \"greatest r\"} elements of @{term \"B\"}\nfor each @{term \"r \\<in> Rs\"}:\n\n\\<close>\n\ndefinition pseudo_rationalizable_on :: \"'a::finite set \\<Rightarrow> 'a rel set \\<Rightarrow> 'a cfun \\<Rightarrow> bool\" where\n  \"pseudo_rationalizable_on A Rs f\n     \\<longleftrightarrow> (\\<forall>r\\<in>Rs. Linear_order r) \\<and> (\\<forall>B\\<subseteq>A. f B = (\\<Union>r\\<in>Rs. greatest r (B \\<inter> Field r)))\"\n\nlemma pseudo_rationalizable_on_def2:\n  \"pseudo_rationalizable_on A Rs f\n     \\<longleftrightarrow> (\\<forall>r\\<in>Rs. Linear_order r) \\<and> (\\<forall>B\\<subseteq>A. f B = (\\<Union>r\\<in>Rs. set_option (MaxR.MaxR_opt r B)))\"\nunfolding %invisible pseudo_rationalizable_on_def\nby (metis (no_types, lifting) MaxR.greatest MaxR.intro SUP_cong)\n\nlemmas %invisible pseudo_rationalizable_onI = iffD2[OF pseudo_rationalizable_on_def2, unfolded conj_imp_eq_imp_imp, rule_format]\n\ntext\\<open>\n\nWe deviate from \\citeauthor{Moulin:1985} in using non-total linear\norders, where his are total, asymmetric, and transitive; in other\nwords, strict total linear orders. This allows us to treat\nnon-decisive choice functions, and we later show that the choice\nfunction is decisive iff the orders are total.\n\n\\citet[Theorem~5]{Moulin:1985} assumes @{const \"Aizerman\"} and @{const\n\"Chernoff\"}, which are equivalent to @{const \"path_independent\"}.\n\n\\<close>\n\nlemma Aizerman_on_Chernoff_on_path_independent_on:\n  assumes \"f_range_on A f\"\n  shows \"Aizerman_on A f \\<and> Chernoff_on A f \\<longleftrightarrow> path_independent_on A f\"\nusing %invisible Chernoff_on_consistency_on_path_independent_on[OF assms] consistency_on_Aizerman_on Aizerman_on_idem_on_consistency_on iia_f_idem[OF assms] Chernoff_on_iia_on\nby blast\n\ntext\\<open>\n\nIt is straightforward to show that pseudo-rationalizable choice\nfunctions satisfy @{const \"path_independent\"} using the properties of\n@{const \"MaxR.MaxR_opt\"}:\n\n\\<close>\n\nlemma pseudo_rationalizable_on_path_independent_on:\n  assumes \"pseudo_rationalizable_on A Rs f\"\n  shows \"path_independent_on A f\"\nproof %invisible (rule path_independent_onI2)\n  from assms show \"f_range_on A f\"\n    unfolding f_range_on_def pseudo_rationalizable_on_def2\n    using MaxR.range_Some[unfolded MaxR_def] by fastforce\n  from assms show \"Chernoff_on A f\"\n    unfolding pseudo_rationalizable_on_def2\n    by - (rule Chernoff_onI; clarsimp; metis MaxR.intro MaxR.subset empty_subsetI insert_subset option.simps(15))\n  from assms show \"consistency_on A f\"\n    unfolding pseudo_rationalizable_on_def2\n    by - (rule consistency_onI; simp; metis (no_types, lifting) MaxR.intro MaxR.subset SUP_cong SUP_le_iff)\nqed\n\ntext\\<open>\n\nThe converse requires that we construct a suitable set of orderings\nthat rationalize @{term \"f C\"} for each @{term \"C \\<subseteq> A\"}. We\ndo this by finding a set @{term \"B \\<subseteq> A\"} where @{term \"f B\n\\<subseteq> C\"} by successively removing elements in @{term \"f A - f\nC\"}. (As these elements are chosen by @{term \"f\"} from supersets of\n@{term \"B\"}, we rank these above all of those in @{term \"f B\"}.)  By\n@{const \"consistency\"} (\\S\\ref{sec:cf-irc}), @{term \"f C = f B\"}. We\ngenerate one order for each element of @{term \"f C\"}. Some extra care\ntakes care of @{const \"decisive\"} choice functions.\n\nTermination is guaranteed by the finiteness of @{term \"A\"} and the\n@{const \"f_range_on\"} hypothesis.\n\n\\<close>\n\ncontext\n  fixes A :: \"'a::finite set\"\n  fixes f :: \"'a cfun\"\n  notes conj_cong[fundef_cong]\nbegin\n\nfunction (domintros) mk_linear_orders :: \"'a set \\<Rightarrow> 'a set \\<Rightarrow> 'a list set\" where\n  \"mk_linear_orders C B =\n   (if f B = {} then {[]}\n    else if f B \\<subseteq> C\n         then {b # cs |b cs. b \\<in> f B \\<and> cs \\<in> mk_linear_orders {} (B - {b})}\n         else let b = SOME x. x \\<in> f B - C in {b # cs |cs. cs \\<in> mk_linear_orders C (B - {b})})\"\nby %invisible pat_completeness auto\n\ncontext\n  assumes \"f_range_on A f\"\nbegin\n\n(*<*)\n\nprivate lemma mk_linear_orders_termination:\n  assumes \"B \\<subseteq> A\"\n  shows \"mk_linear_orders_dom (C, B)\"\nusing \\<open>B \\<subseteq> A\\<close>\nproof(induct t \\<equiv> \"card B\" arbitrary: B C)\n  case (0 B) with \\<open>f_range_on A f\\<close> show ?case\n    unfolding f_range_on_def by (auto intro: mk_linear_orders.domintros)\nnext\n  case (Suc i B)\n  have \"mk_linear_orders_dom ({}, B - {b})\" if \"b \\<in> f B\" for b\n    using \\<open>f_range_on A f\\<close> Suc.hyps(2) Suc.prems Suc.hyps(1)[where B=\"B - {b}\" and C=\"{}\"] finite[of B] that\n      unfolding f_range_on_def by (metis Diff_subset card_Diff_singleton contra_subsetD diff_Suc_1 subset_trans)\n  moreover\n  have \"mk_linear_orders_dom (C, B - {SOME x. x \\<in> f B - C})\" if \"b \\<in> f B\" and \"b \\<notin> C\" for b\n    using \\<open>f_range_on A f\\<close> Suc.hyps(2) Suc.prems Suc.hyps(1)[where B=\"B - {SOME x. x \\<in> f B - C}\" and C=\"C\"] that\n    by (clarsimp simp: card_Diff_singleton_if) (metis (mono_tags, lifting) contra_subsetD diff_Suc_1 f_range_onD someI subset_insertI2 subset_insert_iff)\n  ultimately show ?case by (auto intro: mk_linear_orders.domintros) (* the simplifier has made a mess of the rule *)\nqed\n\nprivate lemma mk_linear_orders_induct[consumes 2, case_names base step1 step2]:\n  assumes \"r \\<in> mk_linear_orders C B\"\n  assumes \"B \\<subseteq> A\"\n  assumes base: \"\\<And>C B. \\<lbrakk>B \\<subseteq> A; f B = {}\\<rbrakk> \\<Longrightarrow> P C B []\"\n  assumes step1: \"\\<And>C B b cs. \\<lbrakk>B \\<subseteq> A; cs \\<in> mk_linear_orders {} (B - {b}); b \\<in> f B; f B \\<subseteq> C; P {} (B - {b}) cs\\<rbrakk>\n                          \\<Longrightarrow> P C B (b # cs)\"\n  assumes step2: \"\\<And>C B b cs. \\<lbrakk>B \\<subseteq> A; cs \\<in> mk_linear_orders C (B - {SOME x. x \\<in> f B - C}); b \\<in> f B; b \\<notin> C; P C (B - {SOME x. x \\<in> f B - C}) cs\\<rbrakk>\n                          \\<Longrightarrow> P C B ((SOME x. x \\<in> f B - C) # cs)\"\n  shows \"P C B r\"\nusing mk_linear_orders_termination[OF \\<open>B \\<subseteq> A\\<close>, where C=C] assms(1,2)\nproof(induct arbitrary: r rule: mk_linear_orders.pinduct)\n  case (1 C B r) then show ?case\n    by (fastforce simp: mk_linear_orders.psimps Let_def base split: if_splits\n                intro!: step1 step2[simplified] 1)\nqed\n\n(*>*)\n\nlemma mk_linear_orders_non_empty:\n  assumes \"B \\<subseteq> A\"\n  shows \"\\<exists>r. r \\<in> mk_linear_orders C B\"\nusing %invisible assms\nproof(induct t \\<equiv> \"card B\" arbitrary: B C rule: nat_less_induct)\n  case (1 B C)\n  { assume \"f B \\<subseteq> C\" \"f B \\<noteq> {}\"\n    with \\<open>f_range_on A f\\<close> 1 have \"\\<exists>b. b \\<in> f B \\<and> (\\<exists>cs. cs \\<in> local.mk_linear_orders {} (B - {b}))\"\n      by safe (metis Diff_subset card_Diff1_less dual_order.trans finite f_range_onD') }\n  moreover\n  { assume \"\\<not> f B \\<subseteq> C\" \"f B \\<noteq> {}\"\n    with \\<open>f_range_on A f\\<close> \"1.prems\" have \"(SOME x. x \\<in> f B - C) \\<in> B \\<and> B - {SOME a. a \\<in> f B - C} \\<subseteq> A\"\n      using someI[where P=\"\\<lambda>x. x \\<in> f B - C\"] by (auto dest: f_range_onD')\n    with \"1.hyps\"[rule_format, where x=\"B - {SOME x. x \\<in> f B - C}\" and xa=C, OF _ refl]\n    have \"\\<exists>cs. cs \\<in> local.mk_linear_orders C (B - {SOME x. x \\<in> f B \\<and> x \\<notin> C})\"\n      by clarsimp (metis card_gt_0_iff diff_Suc_less equals0D finite) }\n  ultimately show ?case\n    by (clarsimp simp: mk_linear_orders.psimps[OF mk_linear_orders_termination[OF \\<open>B \\<subseteq>A\\<close>]] Let_def)\nqed\n\nlemma mk_linear_orders_range:\n  assumes \"r \\<in> mk_linear_orders C B\"\n  assumes \"B \\<subseteq> A\"\n  shows \"set r \\<subseteq> B\"\nusing %invisible assms\nproof(induct rule: mk_linear_orders_induct)\n  case (base C B) with \\<open>f_range_on A f\\<close> show ?case by (simp add: f_range_on_def)\nnext\n  case (step1 C B b cs) with \\<open>f_range_on A f\\<close> show ?case by (auto dest: f_range_onD)\nnext\n  case (step2 C B b cs) with \\<open>f_range_on A f\\<close> show ?case\n    by clarsimp (metis (mono_tags, lifting) Diff_subset someI_ex subset_eq f_range_onD)\nqed\n\nlemma mk_linear_orders_nth:\n  assumes \"r \\<in> mk_linear_orders C B\"\n  assumes \"B \\<subseteq> A\"\n  assumes \"i < length r\"\n  shows \"r ! i \\<in> f (B - set (take i r))\"\nusing %invisible assms\nproof(induct arbitrary: i rule: mk_linear_orders_induct)\n  case (step1 C B b cs i) then show ?case\n    by (cases i) (simp_all add: Diff_insert2[symmetric])\nnext\n  case (step2 C B b cs i) then show ?case\n    by (cases i) (auto simp: Diff_insert2[symmetric] intro: someI2)\nqed simp\n\nlemma mk_linear_orders_distinct:\n  assumes \"r \\<in> mk_linear_orders C B\"\n  assumes \"B \\<subseteq> A\"\n  shows \"distinct r\"\nusing %invisible assms\nproof(induct rule: mk_linear_orders_induct)\n  case (step1 C B b cs) then show ?case\n    by simp (metis Diff_eq_empty_iff Diff_subset Diff_subset_conv le_iff_sup mk_linear_orders_range subset_Diff_insert)\nnext\n  case (step2 C B b cs) then show ?case\n    by simp (meson Diff_subset order.trans mk_linear_orders_range subset_Diff_insert)\nqed simp\n\nlemma mk_linear_orders_Linear_order:\n  assumes \"r \\<in> mk_linear_orders C A\"\n  shows \"Linear_order (linord_of_list r)\"\nusing %invisible mk_linear_orders_distinct[OF assms(1)] linord_of_list_Linear_order by fastforce\n\nlemma mk_linear_orders_decisive_on_set_r:\n  assumes \"r \\<in> mk_linear_orders C B\"\n  assumes \"decisive_on A f\"\n  assumes \"B \\<subseteq> A\"\n  shows \"set r = B\"\nusing %invisible assms(1,3)\nproof(induct rule: mk_linear_orders_induct)\n  case (base C B) with \\<open>decisive_on A f\\<close> show ?case by (auto dest: decisive_onD)\nnext\n  case (step1 C B b cs) with \\<open>f_range_on A f\\<close> show ?case by (auto dest: f_range_onD)\nnext\n  case (step2 C B b cs) with \\<open>f_range_on A f\\<close> show ?case\n    unfolding f_range_on_def\n    by clarsimp (metis (no_types, lifting) Un_iff insert_Diff insert_Diff_single someI subset_Un_eq)\nqed\n\nlemma mk_linear_orders_decisive_on_refl_on:\n  assumes \"r \\<in> mk_linear_orders C A\"\n  assumes \"decisive_on A f\"\n  shows \"refl_on A (linord_of_list r)\"\nusing %invisible linord_of_list_refl_on mk_linear_orders_decisive_on_set_r[OF assms] by blast\n\nlemma mk_linear_orders_decisive_on_total_on:\n  assumes \"r \\<in> mk_linear_orders C A\"\n  assumes \"decisive_on A f\"\n  shows \"total_on A (linord_of_list r)\"\nusing %invisible linord_of_list_total_on mk_linear_orders_decisive_on_set_r[OF assms] by blast\n\nlemma mk_linear_orders_set_r_decisive_on:\n  assumes \"r \\<in> mk_linear_orders C B\"\n  assumes \"B \\<subseteq> A\"\n  assumes \"B \\<subseteq> set r\"\n  assumes \"iia_on A f\"\n  shows \"decisive_on B f\"\nusing %invisible assms(1-3)\nproof(induct rule: mk_linear_orders_induct)\n  case (base C B) with decisive_on_empty[of f] show ?case by simp\nnext\n  case (step1 C B b cs)\n  with mk_linear_orders_range[OF step1.hyps(2)] have \"set cs \\<subseteq> B - {b}\" \"decisive_on (B - {b}) f\"\n    by fastforce+\n  with step1 \\<open>iia_on A f\\<close> show ?case\n    by - (rule decisive_onI; metis (no_types, lifting) Diff_empty Diff_insert0 insert_Diff insert_not_empty subset_insert_iff decisive_onD iia_onD)\nnext\n  case (step2 C B b cs)\n  then have XXX: \"decisive_on (B - {SOME x. x \\<in> f B - C}) f\" by force\n  show ?case\n  proof(rule decisive_onI)\n    fix D assume \"D \\<subseteq> B\" \"D \\<noteq> {}\"\n    with \\<open>iia_on A f\\<close> step2 XXX show \"f D \\<noteq> {}\"\n      by (cases \"(SOME x. x \\<in> f B - C) \\<in> D\")\n         (simp_all, metis (no_types, lifting) emptyE iia_onD someI_ex, blast dest: decisive_onD)\n  qed\nqed\n\nlemma mk_linear_orders_total_on_decisive_on:\n  assumes \"r \\<in> mk_linear_orders C A\"\n  assumes \"A \\<subseteq> set r\"\n  assumes \"iia_on A f\"\n  shows \"decisive_on A f\"\nusing %invisible mk_linear_orders_set_r_decisive_on[OF assms(1) _ _ assms(3)] linord_of_list_Field[of r] \\<open>A \\<subseteq> set r\\<close> by simp\n\nlemma mk_linear_orders_MaxR_opt_f:\n  assumes \"r \\<in> mk_linear_orders C A\"\n  assumes \"MaxR.MaxR_opt (linord_of_list r) D = Some x\"\n  assumes \"iia_on A f\"\n  assumes \"D \\<subseteq> A\"\n  shows \"x \\<in> f D\"\nproof %invisible -\n  from linord_of_list_Linear_order[OF mk_linear_orders_distinct[OF assms(1) subset_refl]]\n  have \"MaxR (linord_of_list r)\" by (rule MaxR.intro) simp\n  with assms(2)\n  have \"x \\<in> greatest (linord_of_list r) (D \\<inter> Field (linord_of_list r))\"\n    using MaxR.greatest elem_set by blast\n  then obtain i where \"x = r ! i\" and \"i < length r\" and \"\\<forall>j<i. r ! j \\<notin> D\"\n    unfolding greatest_def using mk_linear_orders_distinct[OF assms(1) subset_refl] linord_of_list_nth[where xs=r]\n    by atomize_elim (clarsimp simp: set_conv_nth; metis IntI less_trans not_le nth_mem set_conv_nth)\n  with \\<open>iia_on A f\\<close> \\<open>D \\<subseteq> A\\<close> show ?thesis\n    using mk_linear_orders_nth[OF assms(1), where i=i]\n          iia_onD[of A f, where B=\"A - set (take i r)\" and C=D and a=x]\n          MaxR.range_Some[rule_format, OF \\<open>MaxR (linord_of_list r)\\<close> assms(2)]\n    by (fastforce simp: nth_image[symmetric])\nqed\n\nlemma mk_linear_orders_f_MaxR_opt:\n  assumes \"x \\<in> f C\"\n  assumes \"consistency_on A f\"\n  assumes \"B \\<subseteq> A\"\n  assumes \"C \\<subseteq> B\"\n  shows \"\\<exists>r\\<in>mk_linear_orders C B. MaxR.MaxR_opt (linord_of_list r) C = Some x\"\nusing %invisible \\<open>B \\<subseteq> A\\<close> \\<open>C \\<subseteq> B\\<close>\nproof(induct t \\<equiv> \"card B\" arbitrary: B rule: nat_less_induct)\n  case (1 B) show ?case\n  proof(cases \"f B = {}\")\n    case True\n    with consistency_onD[OF assms(2), where B=B and C=C] \"1.prems\" \\<open>x \\<in> f C\\<close>\n    show ?thesis by simp\n  next\n    case False show ?thesis\n    proof(cases \"f B \\<subseteq> C\")\n      case True\n      from \\<open>B \\<subseteq> A\\<close> obtain r where r: \"r \\<in> mk_linear_orders {} (B - {x})\"\n        using mk_linear_orders_non_empty by (meson Diff_subset_conv le_supI2)\n      from True consistency_onD[OF assms(2), where B=B and C=C] \"1.prems\" \\<open>x \\<in> f C\\<close>\n      have x: \"x \\<in> f B\" by blast\n      from \\<open>f B \\<noteq> {}\\<close> True \\<open>B \\<subseteq> A\\<close> r x have XXX: \"x # r \\<in> mk_linear_orders C B\"\n        using mk_linear_orders_termination[of B C]\n        by (simp add: mk_linear_orders.psimps card_eq_0_iff split: if_splits)\n      show ?thesis\n      proof(rule bexI[OF _ XXX])\n        from \\<open>f_range_on A f\\<close> True r x \\<open>B \\<subseteq> A\\<close> \\<open>C \\<subseteq> B\\<close>  \\<open>x \\<in> f C\\<close>\n        show \"MaxR.MaxR_opt (linord_of_list (x # r)) C = Some x\"\n          using linord_of_list_Linear_order[OF mk_linear_orders_distinct[OF XXX \\<open>B \\<subseteq> A\\<close>]]\n          unfolding Option.elem_set[symmetric] by (auto simp: MaxR.greatest MaxR_def greatest_def linord_of_list_linord_of_listP dest: f_range_onD)\n      qed\n    next\n      case False\n      let ?b = \"SOME x. x \\<in> f B - C\"\n      let ?B' = \"B - {?b}\"\n      from False \\<open>B \\<subseteq> A\\<close> obtain a where \"a \\<in> f B - C\" by blast\n      with \\<open>f_range_on A f\\<close> \\<open>B \\<subseteq> A\\<close> have \"card ?B' < card B\"\n        unfolding f_range_on_def\n        by (clarsimp simp: card_Diff_singleton_if) (metis (no_types, lifting) One_nat_def card_Diff1_less card_Diff_singleton finite someI_ex subsetCE)\n      from \\<open>C \\<subseteq> B\\<close> \\<open>a \\<in> f B - C\\<close>\n      have \"C \\<subseteq> B - {SOME x. x \\<in> f B - C}\" by (metis Diff_empty Diff_iff someI subset_Diff_insert)\n      with 1(1)[rule_format, OF \\<open>card ?B' < card B\\<close> refl] \\<open>B \\<subseteq> A\\<close>\n      obtain r where r: \"r \\<in> mk_linear_orders C ?B'\" \"MaxR.MaxR_opt (linord_of_list r) C = Some x\" by blast\n      with \\<open>f B \\<noteq> {}\\<close> False \\<open>B \\<subseteq> A\\<close> have \"?b # r \\<in> mk_linear_orders C B\"\n        using mk_linear_orders_termination[of B C]\n        by (simp add: mk_linear_orders.psimps Let_def card_eq_0_iff split: if_splits)\n      moreover\n      have \"MaxR.MaxR_opt (linord_of_list (?b # r)) C = Some x\"\n      proof(rule MaxR.greatest_is_MaxR_opt)\n        from linord_of_list_Linear_order[OF mk_linear_orders_distinct[OF \\<open>?b # r \\<in> mk_linear_orders C B\\<close> \\<open>B \\<subseteq> A\\<close>]]\n        show \"MaxR (linord_of_list (?b # r))\" by (simp add: MaxR.intro)\n        from \\<open>f_range_on A f\\<close> r \\<open>B \\<subseteq> A\\<close>\n        show \"x \\<in> C \\<inter> Field (linord_of_list (?b # r))\"\n          by clarsimp (metis (no_types, lifting) Choice_Functions.mk_linear_orders_Linear_order Diff_subset IntD2 Int_iff MaxR.intro MaxR.range_Some f_range_on_antimono linord_of_list_Field)\n        from \\<open>f_range_on A f\\<close> r \\<open>a \\<in> f B - C\\<close> \\<open>B \\<subseteq> A\\<close>\n        show \"\\<forall>y\\<in>C \\<inter> Field (linord_of_list (?b # r)). (y, x) \\<in> linord_of_list (?b # r)\"\n          using someI[where P=\"\\<lambda>x. x \\<in> f B - C\"]\n          by (auto simp: linord_of_list_linord_of_listP intro: MaxR.intro intro: f_range_on_antimono dest!: MaxR.MaxR_opt_is_greatest[rotated] Choice_Functions.mk_linear_orders_Linear_order[rotated])\n      qed\n      ultimately show ?thesis by blast\n    qed\n  qed\nqed\n\nend\n\nend\n\nlemma path_independent_on_pseudo_rationalizable_on:\n  fixes f :: \"'a::finite cfun\"\n  assumes \"path_independent_on A f\"\n  assumes \"f_range_on A f\"\n  assumes Rs_def[simp]: \"Rs = (\\<Union>C\\<in>Pow A. linord_of_list ` mk_linear_orders f C A)\"\n  shows \"pseudo_rationalizable_on A Rs f \\<and> (\\<forall>r\\<in>Rs. refl_on A r \\<and> total_on A r \\<longleftrightarrow> decisive_on A f)\"\nproof %invisible -\n  have \"pseudo_rationalizable_on A Rs f\"\n  proof(rule pseudo_rationalizable_onI)\n    fix r assume \"r \\<in> Rs\" then show \"Linear_order r\"\n      using mk_linear_orders_Linear_order[OF \\<open>f_range_on A f\\<close>] by clarsimp\n  next\n    fix B assume \"B \\<subseteq> A\" show \"f B = (\\<Union>r\\<in>Rs. set_option (MaxR.MaxR_opt r B))\" (is \"?lhs = ?rhs\")\n    proof(rule set_elem_equalityI)\n      fix x assume \"x \\<in> ?lhs\" with \\<open>B \\<subseteq> A\\<close> show \"x \\<in> ?rhs\"\n        using path_independent_on_consistency_on[OF assms(1)]\n              mk_linear_orders_f_MaxR_opt[OF \\<open>f_range_on A f\\<close>] by fastforce\n    next\n      fix x assume \"x \\<in> ?rhs\" with \\<open>B \\<subseteq> A\\<close> show \"x \\<in> ?lhs\"\n        using path_independent_on_Chernoff_on[OF assms(1,2)] Chernoff_on_iia_on\n              mk_linear_orders_MaxR_opt_f[OF \\<open>f_range_on A f\\<close>] by simp blast\n    qed\n  qed\n  moreover\n  from path_independent_on_Chernoff_on[OF assms(1,2)] Chernoff_on_iia_on\n  have \"iia_on A f\" by blast\n  then have \"\\<forall>r\\<in>Rs. refl_on A r \\<and> total_on A r \\<longleftrightarrow> decisive_on A f\"\n    using mk_linear_orders_total_on_decisive_on[OF assms(2)]\n          mk_linear_orders_decisive_on_refl_on[OF assms(2)]\n          mk_linear_orders_decisive_on_total_on[OF assms(2)]\n    by clarsimp (meson linord_of_list_refl_on refl_onD refl_onD1 subsetI)\n  ultimately show ?thesis by blast\nqed\n\ntext\\<open>\n\nOur top-level theorem is essentially \\citet[Theorem~5]{Moulin:1985}:\n\n\\<close>\n\ntheorem pseudo_rationalizable:\n  assumes \"f_range_on A f\"\n  shows \"path_independent_on A f\n           \\<longleftrightarrow> (\\<exists>Rs. pseudo_rationalizable_on A Rs f \\<and> (\\<forall>r\\<in>Rs. refl_on A r \\<and> total_on A r \\<longleftrightarrow> decisive_on A f))\"\nusing %invisible pseudo_rationalizable_on_path_independent_on path_independent_on_pseudo_rationalizable_on[OF _ assms] by fastforce\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/Stable_Matching/Choice_Functions.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8705972583359806, "lm_q2_score": 0.8267117898012105, "lm_q1q2_score": 0.7197330176349653}}
{"text": "(*\n    File:      Dirichlet_Efficient_Code.thy\n    Author:    Manuel Eberl, TU M\u00fcnchen\n*)\nsection \\<open>Efficient code for number-theoretic functions\\<close>\ntheory Dirichlet_Efficient_Code\nimports \n  Main \n  Moebius_Mu \n  More_Totient \n  Divisor_Count\n  Liouville_Lambda\n  \"HOL-Library.Code_Target_Numeral\"\n  Polynomial_Factorization.Prime_Factorization\nbegin\n\ndefinition prime_factorization_nat' :: \"nat \\<Rightarrow> (nat \\<times> nat) list\" where\n  \"prime_factorization_nat' n = (\n     let ps = prime_factorization_nat n\n     in  map (\\<lambda>p. (p, length (filter ((=) p) ps) - 1)) (remdups_adj (sort ps)))\"\n  \nlemma set_prime_factorization_nat':\n  \"set (prime_factorization_nat' n) = (\\<lambda>p. (p, multiplicity p n - 1)) ` prime_factors n\"\nproof (intro equalityI subsetI; clarify)\n  fix p k :: nat\n  assume pk: \"(p, k) \\<in> set (prime_factorization_nat' n)\"\n  hence p: \"p \\<in> prime_factors n\"\n    by (auto simp: prime_factorization_nat'_def Let_def multiset_prime_factorization_nat_correct)\n  hence p': \"prime p\" by (simp add: prime_factors_multiplicity)\n  from pk p' have \"k = multiplicity p n - 1\"\n    by (auto simp: prime_factorization_nat'_def Let_def multiset_prime_factorization_nat_correct\n          count_prime_factorization_prime [symmetric] count_mset )\n  with p show \"(p, k) \\<in> (\\<lambda>p. (p, multiplicity p n - 1)) ` prime_factors n\" by auto\nnext\n  fix p :: nat\n  assume \"p \\<in> prime_factors n\"\n  moreover from this have \"prime p\" by (simp add: prime_factors_multiplicity)\n  ultimately show \"(p, multiplicity p n - 1) \\<in> set (prime_factorization_nat' n)\"\n    by (auto simp: prime_factorization_nat'_def Let_def multiset_prime_factorization_nat_correct \n          count_prime_factorization_prime [symmetric] count_mset)\nqed\n  \nlemma distinct_prime_factorization_nat' [simp]: \"distinct (prime_factorization_nat' n)\"\n  by (simp add: distinct_map inj_on_def prime_factorization_nat'_def Let_def)\n\nlemmas (in multiplicative_function') efficient_code' = \n   efficient_code [of \"\\<lambda>_. prime_factorization_nat' n\" n for n, \n     OF set_prime_factorization_nat' distinct_prime_factorization_nat']\n\n  \nsubsection \\<open>M\\\"{o}bius $\\mu$ function\\<close>\n\ndefinition moebius_mu_aux :: \"nat \\<Rightarrow> (unit \\<Rightarrow> nat list) \\<Rightarrow> int\" where\n  \"moebius_mu_aux n ps = \n     (if n \\<noteq> 0 \\<and> \\<not>4 dvd n \\<and> \\<not>9 dvd n then\n        (let ps = ps () in if distinct ps then if even (length ps) then 1 else -1 else 0) else 0)\"\n\nlemma moebius_mu_conv_moebius_mu_aux:\n  fixes qs :: \"unit \\<Rightarrow> nat list\"\n  defines \"ps \\<equiv> qs ()\"\n  assumes \"mset ps = prime_factorization n\"\n  shows   \"moebius_mu n = of_int (moebius_mu_aux n qs)\"\nproof (cases \"n = 0 \\<or> 4 dvd n \\<or> 9 dvd n\")\n  case False\n  hence [simp]: \"n > 0\" by auto\n  have \"set_mset (mset ps) = prime_factors n\" by (subst assms) simp\n  hence [simp]: \"set ps = prime_factors n\" by simp\n  show ?thesis\n  proof (cases \"distinct ps\")\n    case True\n    have \"multiplicity p n = 1\" if p: \"p \\<in> prime_factors n\" for p\n    proof -\n      from p and True have \"count (mset ps) p = 1\" by (auto simp: distinct_count_atmost_1)\n      also from assms and p have \"count (mset ps) p = multiplicity p n\"\n        by (simp add: prime_factors_multiplicity count_prime_factorization_prime)\n      finally show \"multiplicity p n = 1\" .\n    qed\n    moreover from True have \"card (prime_factors n) = length ps\"\n      by (simp only: assms [symmetric] set_mset_mset distinct_card)\n    ultimately show ?thesis using False and True\n      by (auto simp add: moebius_mu_def moebius_mu_aux_def ps_def \n            Let_def squarefree_factorial_semiring')\n  next\n    case False\n    then obtain p where \"count (mset ps) p \\<noteq> (if p \\<in> set ps then 1 else 0)\"\n      by (subst (asm) distinct_count_atmost_1) auto\n    moreover from this have p: \"p \\<in> prime_factors n\" \n      by (cases \"count (mset ps) p = 0\") (auto split: if_splits)\n    ultimately have \"count (mset ps) p > 1\" by (cases \"count (mset ps) p\") auto\n    with p and assms have \"multiplicity p n > 1\"\n      by (simp add: prime_factors_multiplicity count_prime_factorization_prime)\n    with False and assms and p have \"\\<not>squarefree n\"\n      by (auto simp: squarefree_factorial_semiring'')\n    with False and assms and p show ?thesis \n      by (auto simp: moebius_mu_def moebius_mu_aux_def)\n  qed\nnext\n  case True\n  with not_squarefreeI[of 2 n] and not_squarefreeI[of 3 n] show ?thesis\n    by (auto simp: moebius_mu_aux_def)\nqed\n\nlemma moebius_mu_code [code]: \n    \"moebius_mu n = of_int (moebius_mu_aux n (\\<lambda>_. prime_factorization_nat n))\"\n  by (rule moebius_mu_conv_moebius_mu_aux) (simp_all add: multiset_prime_factorization_nat_correct)\n\nvalue \"moebius_mu 12578972695257 :: int\"\n\n\nsubsection \\<open>Euler's $\\phi$ function\\<close>\n  \nprimrec totient_aux1 :: \"nat \\<Rightarrow> nat list \\<Rightarrow> nat\" where\n  \"totient_aux1 n [] = n\"\n| \"totient_aux1 n (p # ps) = totient_aux1 (n - n div p) ps\"\n  \nlemma of_nat_totient_aux1:\n  assumes \"\\<And>p. p \\<in> set ps \\<Longrightarrow> prime p\" \"\\<And>p. p \\<in> set ps \\<Longrightarrow> p dvd n\" \"distinct ps\"\n  shows   \"real (totient_aux1 n ps) = real n * (\\<Prod>p\\<in>set ps. 1 - 1 / real p)\"\nusing assms\nproof (induction ps arbitrary: n)\n  case (Cons p ps n)\n  from Cons.prems have p: \"prime p\" \"p dvd n\" by auto\n  have \"real (totient_aux1 n (p # ps)) = real (totient_aux1 (n - n div p) ps)\" by simp\n  also have \"\\<dots> = real (n - n div p) * (\\<Prod>p\\<in>set ps. 1 - 1 / real p)\"\n  proof (rule Cons.IH)\n    fix q assume q: \"q \\<in> set ps\"\n    define m where \"m = n div p\"\n    from p have m: \"n = p * m\" by (simp add: m_def)\n    from Cons.prems q have \"prime q\" \"q dvd n\" \"p \\<noteq> q\" by auto\n    hence \"q dvd m\" using primes_dvd_imp_eq[of q p]  p by (auto simp add: m prime_dvd_mult_iff)\n    thus \"q dvd n - n div p\" unfolding m_def using p \\<open>q dvd n\\<close> by simp\n  qed (insert Cons.prems, auto)\n  also have \"real (n - n div p) = real n * (1 - 1 / real p)\"\n    by (simp add: of_nat_diff real_of_nat_div p field_simps)\n  also have \"\\<dots> * (\\<Prod>p\\<in>set ps. 1 - 1 / real p) = real n * (\\<Prod>p\\<in>set (p#ps). 1 - 1 / real p)\"\n    using Cons.prems by simp\n  finally show ?case .\nqed simp_all\n  \nlemma totient_conv_totient_aux1:\n  assumes \"set ps = prime_factors n\" \"distinct ps\"\n  shows   \"totient n = totient_aux1 n ps\"\nproof -\n  from assms have \"real (totient_aux1 n ps) = real n * (\\<Prod>p\\<in>set ps. 1 - 1 / real p)\"\n    by (intro of_nat_totient_aux1) auto\n  also have \"set ps = prime_factors n\" by fact\n  also have \"real n * (\\<Prod>p\\<in>prime_factors n. 1 - 1 / real p) = real (totient n)\"\n    by (rule totient_formula2 [symmetric])\n  finally show ?thesis by (simp only: of_nat_eq_iff)\nqed\n\ndefinition prime_factors_nat :: \"nat \\<Rightarrow> nat list\" where\n  \"prime_factors_nat n = remdups_adj (sort (prime_factorization_nat n))\"\n  \nlemma set_prime_factors_nat [simp]: \"set (prime_factors_nat n) = prime_factors n\"\n  unfolding prime_factors_nat_def multiset_prime_factorization_nat_correct by simp\n\nlemma distinct_prime_factors_nat [simp]: \"distinct (prime_factors_nat n)\"\n  by (simp add: prime_factors_nat_def)\n\n\ndefinition totient_aux2 :: \"(nat \\<times> nat) list \\<Rightarrow> nat\" where\n  \"totient_aux2 xs = (\\<Prod>(p,k)\\<leftarrow>xs. p ^ k * (p - 1))\"\n  \nlemma totient_conv_totient_aux2:\n  assumes \"n \\<noteq> 0\"\n  assumes \"set xs = (\\<lambda>p. (p, multiplicity p n - 1)) ` prime_factors n\"\n  assumes \"distinct xs\"\n  shows   \"totient n = totient_aux2 xs\"\nproof -\n  have \"totient_aux2 xs = (\\<Prod>(p,k)\\<leftarrow>xs. p ^ k * (p - 1))\" by (fact totient_aux2_def)\n  also from assms have \"\\<dots> = \n    (\\<Prod>x\\<in>(\\<lambda>p. (p, multiplicity p n - 1)) ` prime_factors n. case x of (p, k) \\<Rightarrow> p ^ k * (p - Suc 0))\"\n    by (subst prod.distinct_set_conv_list [symmetric]) simp_all\n  also have \"\\<dots> = (\\<Prod>p\\<in>prime_factors n. p ^ (multiplicity p n - 1) * (p - Suc 0))\"\n    by (subst prod.reindex) (auto simp: inj_on_def)\n  also have \"\\<dots> = (\\<Prod>p\\<in>prime_factors n. p ^ multiplicity p n - p ^ (multiplicity p n - 1))\"\n    by (intro prod.cong refl) (auto simp: prime_factors_multiplicity algebra_simps\n                                 power_Suc [symmetric] simp del: power_Suc)\n  also have \"\\<dots> = totient n\" using assms(1) by (subst totient.prod_prime_factors') auto\n  finally show ?thesis ..\nqed\n\nlemma totient_code1: \"totient n = totient_aux1 n (prime_factors_nat n)\"\n  by (intro totient_conv_totient_aux1) simp_all\n    \nlemma totient_code2: \"totient n = (if n = 0 then 0 else totient_aux2 (prime_factorization_nat' n))\"\n  by (simp_all add: set_prime_factorization_nat' totient_conv_totient_aux2 split: if_splits)\n\ndeclare totient_code_naive [code del]\n\nlemmas [code] = totient_code2\n\nvalue \"totient 125789726827482323235784\"\n\n\nsubsection \\<open>Divisor Functions\\<close>\n\nlemmas [code del] = divisor_count_naive divisor_sum_naive\nlemmas [code] = divisor_count.efficient_code' divisor_sum.efficient_code'\n\nvalue \"int (divisor_count 378568418621)\"\nvalue \"int (divisor_sum 378568418621)\"\n\n\nsubsection \\<open>Liouville's $\\lambda$ function\\<close>\n\n\n\nvalue \"liouville_lambda 1264785343674 :: int\"\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/Dirichlet_Efficient_Code.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.893309411735131, "lm_q2_score": 0.805632181981183, "lm_q1q2_score": 0.7196788105605006}}
{"text": "theory Pord imports Bogus Okay\n\nbegin\n\n(*\n * Typeclass definitions for partial orders and various extensions thereof\n * TODO: these proofs could be cleaned up and ISAR-ified\n *)\n\n(* Comparison function for orderings, not currently used *)\ndefinition ord_leq :: \"('a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> ('a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> bool\"\n  where\n\"ord_leq o1 o2 = (\\<forall> x1 x2 . o1 x1 x2 \\<longrightarrow> o2 x1 x2)\"\n\nlemma ord_leq_refl : \"\\<And> ord . ord_leq ord ord\"\n  apply(simp add:ord_leq_def)\n  done\n\nlemma ord_leq_trans: \"\\<And> ox oy oz . ord_leq ox oy \\<Longrightarrow> ord_leq oy oz \\<Longrightarrow> ord_leq ox oz\"\n  apply(simp add:ord_leq_def)\n  done\n\nlemma ord_leq_antisym : \"\\<And> ox oy . ord_leq ox oy\n \\<Longrightarrow> ord_leq oy ox \\<Longrightarrow> ox = oy\"\n  apply(simp add:ord_leq_def)\n  apply(blast)\n  done\n\nlemma ord_leq' : \"\\<And> ox oy a b .\n  ord_leq ox oy \\<Longrightarrow>\n  ox a b \\<Longrightarrow>\n  oy a b\"\n  apply(simp add:ord_leq_def)\n  done\n\nlemma ord_leq_d : \"\\<And> ox oy a b .\n  ox a b \\<Longrightarrow>\n  ord_leq ox oy \\<Longrightarrow>\n  oy a b\"\n  apply(simp add:ord_leq_def)\n  done\n\n(* Pord = \"Partial ORDer\"\n   This name avoids collision with Isabelle's builtin ordering notions\n   This version of pord is \"weak\" because it lacks antisymmetry; the full pord\n   typeclass adds antisymmetry.\n*)\n\nclass Pord_Weak =\n  fixes pleq :: \"'a \\<Rightarrow> 'a \\<Rightarrow> bool\" (infixl \\<open><[\\<close> 71)\n  assumes\n    leq_refl : \"pleq a a\"\n  assumes\n    leq_trans : \"pleq a b \\<Longrightarrow> pleq b c \\<Longrightarrow> pleq a c\"\n\n\n(* Notions common to partial orders - upper bounds, lower bounds, infs and sups *)\ndefinition is_lb :: \"('a :: Pord_Weak) set \\<Rightarrow> 'a \\<Rightarrow> bool\" where\n\"is_lb A a =\n  (\\<forall> x \\<in> A . a <[ x)\"\n\ndefinition is_greatest :: \"(('a :: Pord_Weak) \\<Rightarrow> bool) \\<Rightarrow> 'a \\<Rightarrow> bool\" where\n\"is_greatest P a =\n  (P a \\<and>\n   (\\<forall> a' . P a' \\<longrightarrow> pleq a' a))\"\n\ndefinition is_inf :: \"('a :: Pord_Weak) set \\<Rightarrow> 'a \\<Rightarrow> bool\" where\n\"is_inf A a = is_greatest (is_lb A) a\"\n\ndefinition is_ub :: \"('a :: Pord_Weak) set \\<Rightarrow> 'a \\<Rightarrow> bool\" where\n\"is_ub A a =\n  (\\<forall> x \\<in> A . pleq x a)\"\n\ndefinition is_least :: \"(('a :: Pord_Weak) \\<Rightarrow> bool) \\<Rightarrow> 'a \\<Rightarrow> bool\" where\n\"is_least P a =\n  (P a \\<and>\n   (\\<forall> a' . P a' \\<longrightarrow> pleq a a'))\"\n\ndefinition is_sup :: \"('a :: Pord_Weak) set \\<Rightarrow> 'a \\<Rightarrow> bool\" where\n\"is_sup A a =\n  is_least (is_ub A) a\"\n\ndefinition has_sup :: \"('a :: Pord_Weak) set \\<Rightarrow> bool\" where\n\"has_sup A = (\\<exists> s . is_sup A s)\"\n\ndefinition has_ub :: \"('a :: Pord_Weak) set \\<Rightarrow> bool\" where\n\"has_ub A = (\\<exists> s . is_ub A s)\"\n\n\n(* A key definition: bub = \"Biased Upper Bound\". The idea is that for any two objects of type\n   a and b of type 'a, bub a b is \"the closest we can get\" to a common (least) upper bound\n   even if one does not exist. bub a b is guaranteed to be greater than a; additionally,\n   if by \"forgetting information\" from b (thinking of this as an information ordering) we arrive\n   at bd <[ b such that bd _does_ have a least upper bound, bub a b is guaranteed to be\n   greater than said upper bound.\n\n   Bub is thus \"biased\" towards being forced to be an upper bound of a, while being\n   \"as close as possible\" to b.\n\n   Bsup is the least such bub.\n\n   This definition is key to specifying the mergeable typeclass, an crucial component\n   of the overall Gazelle system. It allows us to talk about \"merging\" in a very general\n   context with minimal assumptions (is_bub only requires weak partial orders), yet bsup is provably\n   being equivalent to the \"true\" least upper bound if it exists, assuming completeness;\n   that is, where the existence of _any_ upper bound between a and bd guarantees the existence\n   of a least upper bound sd.\n*)\n\ndefinition is_bub :: \"('a :: Pord_Weak) \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> bool\" where\n\"is_bub a b s =\n  (pleq a s \\<and>\n    ((\\<forall> bd sd . pleq bd (b) \\<longrightarrow>\n                is_sup {a, bd} sd \\<longrightarrow>\n                pleq sd (s))))\"\n\ndefinition is_bsup :: \"('a :: Pord_Weak) \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> bool\" where\n\"is_bsup a b s =\n  is_least (is_bub a b) s\"\n\n(* Monotonicity for predicates *)\ndefinition is_monop1 :: \"(('a :: Pord_Weak) \\<Rightarrow> bool) \\<Rightarrow> bool\" where\n\"is_monop1 P =\n  (\\<forall> a b . pleq a b \\<longrightarrow> P a \\<longrightarrow> P b)\"\n\ndefinition is_monop2 :: \"(('a :: Pord_Weak) \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> bool\" where\n\"is_monop2 P =\n  (\\<forall> a1 b1 a2 b2 .\n    pleq a1 b1 \\<longrightarrow>\n    pleq a2 b2 \\<longrightarrow>\n    P a1 a2 \\<longrightarrow>\n    P b1 b2)\"\n\n(* \"Contravariant\" version of monotonicity *)\ndefinition is_monop2' :: \"(('a :: Pord_Weak) \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> bool\" where\n\"is_monop2' P =\n  (\\<forall> a1 b1 a2 b2 .\n    pleq a1 b1 \\<longrightarrow>\n    pleq b2 a2 \\<longrightarrow>\n    P a1 a2 \\<longrightarrow>\n    P b1 b2)\"\n\n(* Monotonicity for functions *)\ndefinition is_mono :: \"(('a :: Pord_Weak) \\<Rightarrow> 'a) \\<Rightarrow> bool\" where\n\"is_mono f =\n  (\\<forall> a b .\n     pleq a b \\<longrightarrow>\n     pleq (f a) (f b))\"\n\n(* Convenience introduction and eliminations for ub/sup/bub/bsup\n   (we do not really use inf and lb, so those lemmas are omitted) *)\nlemma is_ubI [intro] :\n  assumes H : \"\\<And> x . x \\<in> A \\<Longrightarrow> pleq x a\"\n  shows \"is_ub A a\" using H\n  by(auto simp add:is_ub_def)\n\n(* TODO: some of these elim rules could be tagged with [elim]; however, I generally choose\n   not to do this as not all of them are complete in the appropriate sense.\n*)\nlemma is_ubE :\n  assumes H1 : \"is_ub S ub\"\n  assumes H2 : \"x \\<in> S\"\n  shows \"pleq x ub\"\n  using H1 H2\n  by (auto simp add: is_ub_def)\n\nlemma is_supI :\n  assumes Hpleq : \"\\<And> x . x \\<in> A \\<Longrightarrow> pleq x ub\"\n  assumes Hleast : \"\\<And> x' . is_ub A x' \\<Longrightarrow> pleq ub x'\"\n  shows \"is_sup A ub\" using Hpleq Hleast\n  by(auto simp add:is_least_def is_ub_def is_sup_def)\n\nlemma is_supD1 :\n  assumes H1 : \"is_sup S ub\"\n  assumes H2 : \"x \\<in> S\"\n  shows \"pleq x ub\"\n  using H1 H2\n  by (auto simp add: is_ub_def is_least_def is_sup_def)\n\nlemma is_supD2 :\n  assumes H1 : \"is_sup S ub\"\n  assumes H2 : \"is_ub S ub'\"\n  shows \"pleq ub ub'\"\n  using H1 H2\n  by (auto simp add: is_ub_def is_least_def is_sup_def)\n\nlemma bsup_leq :\n  assumes H : \"is_bsup a b x\"\n  shows \"pleq a x\" using H\n  by (auto simp add:is_bsup_def is_bub_def is_least_def)\n\nlemma is_bubI :\n  assumes Hpleq : \"pleq a bub\"\n  assumes Hbub :\n    \"\\<And> bd sd . pleq bd b \\<Longrightarrow> is_sup {a, bd} sd \\<Longrightarrow> pleq sd bub\"\n  shows \"is_bub a b bub\" using Hpleq Hbub\n  by(auto simp add:is_bub_def)\n\nlemma is_bubD1 :\n  assumes H1 : \"is_bub a b ub\"\n  shows \"pleq a ub\" \n  using H1 by (auto simp add:is_bub_def)\n\nlemma is_bubD2 :\n  assumes H1 : \"is_bub a b ub\"\n  assumes H2 : \"pleq bd (b)\"\n  assumes H3 : \"is_sup {a, bd} sd\"\n  shows \"pleq sd (ub)\"\n  using H1 H2 H3 by (auto simp add:is_bub_def)\n\nlemma is_bsupI :\n  assumes Hpleq : \"pleq a bub\"\n  assumes Hbub :\n    \"\\<And> bd sd . pleq bd b \\<Longrightarrow> is_sup {a, bd} sd \\<Longrightarrow> pleq sd bub\"\n  assumes Hleast : \"\\<And> x' . is_bub a b x' \\<Longrightarrow> pleq bub x'\"\n  shows \"is_bsup a b bub\" using Hpleq Hbub Hleast\n  by(auto simp add:is_bsup_def is_least_def is_bub_def)\n\nlemma is_bsupD1 :\n  assumes H1 : \"is_bsup a b ub\"\n  shows \"pleq a ub\" \n  using H1 by (rule bsup_leq)\n\nlemma is_bsupD2 :\n  assumes H1 : \"is_bsup a b ub\"\n  assumes H2 : \"pleq bd (b)\"\n  assumes H3 : \"is_sup {a, bd} sd\"\n  shows \"pleq sd (ub)\"\n  using H1 H2 H3 by (auto simp add:is_bub_def is_bsup_def is_least_def)\n\nlemma is_bsupD3 :\n  assumes H1 : \"is_bsup a b ub\"\n  assumes H2 : \"is_bub a b ub'\"\n  shows \"pleq ub ub'\"\n  using H1 H2 by (auto simp add:is_bsup_def is_least_def)\n\nclass Pord =\n    Pord_Weak +\n    assumes leq_antisym : \"pleq a b \\<Longrightarrow> pleq b a \\<Longrightarrow> a = b\"\n\n\n(* facts about Pord *)\nlemma is_greatest_unique :\n  fixes P :: \"('a :: Pord) \\<Rightarrow> bool\"\n  fixes a b :: \"('a :: Pord)\"\n  assumes H1 : \"is_greatest P a\"\n  assumes H2 : \"is_greatest P b\"\n  shows \"a = b\"\nproof(-)\n  have 0 :  \"a <[ b\" using H2 H1\n    by(auto simp add:is_greatest_def)\n  have 1 : \"b <[ a\" using H1 H2\n    by(auto simp add:is_greatest_def)\n\n  thus \"a = b\" using 0 1 by (auto intro: leq_antisym)\nqed\n\nlemma is_least_unique :\n  fixes P :: \"('a :: Pord) \\<Rightarrow> bool\"\n  fixes a b :: \"('a :: Pord)\"\n  assumes H1 : \"is_least P a\"\n  assumes H2 : \"is_least P b\"\n  shows \"a = b\"\nproof(-)\n  have 0 :  \"a <[ b\" using H2 H1\n    by(auto simp add:is_least_def)\n  have 1 : \"b <[ a\" using H1 H2\n    by(auto simp add:is_least_def)\n\n  thus \"a = b\" using 0 1 by (auto intro: leq_antisym)\nqed\n\n(* Uniqueness for sup, bsup *)\n\nlemma is_sup_unique :\n  fixes P :: \"('a :: Pord) set\"\n  fixes x y :: \"'a\"\n  shows \"is_sup P x \\<Longrightarrow> is_sup P y \\<Longrightarrow> x = y\"\nproof(auto simp add:is_sup_def is_least_unique)\nqed\n\nlemma is_sup_comm2 :\n  \"is_sup {a, b} x \\<Longrightarrow> is_sup {b, a} x\"\nproof(auto simp add:is_sup_def is_least_def is_ub_def)\nqed\n\nlemma sup_extend :\n  assumes Hleq : \"pleq a x\"\n  assumes Hlub1 : \"is_sup {a, c} u1\"\n  assumes Hlub2 : \"is_sup {x, c} u2\"\n  shows \"pleq u1 u2\"\nproof(-)\n  have 0 :  \"pleq x u2\" using Hlub2 by (auto simp add:is_sup_def is_ub_def is_least_def)\n  have 1 :  \"pleq a u2\" using leq_trans[OF Hleq 0] by auto\n  hence \"is_ub {a, c} u2\" using Hlub2\n    by (auto simp add:is_sup_def is_ub_def is_least_def)\n\n  thus ?thesis using Hlub1\n    by (auto simp add:is_sup_def is_ub_def is_least_def)\nqed\n\nlemma bsup_unique : \n  fixes a b x :: \"'a :: Pord\"\n  assumes H1 : \"is_bsup a b x\"\n  assumes H2 : \"is_bsup a b x'\"\n  shows \"x = x'\"\n  using H1 H2\nproof(-)\n  have 0 : \"is_bub a b x'\" using H2\n    by(auto simp add:is_bsup_def is_least_def)\n\n  have 1 : \"pleq x x'\" using 0 H1\n    by(auto simp add:is_bsup_def is_least_def)\n\n  have 2 : \"is_bub a b x\" using H1\n    by(auto simp add:is_bsup_def is_least_def)\n\n  have 3 : \"pleq x' x\" using 2 H2\n    by(auto simp add:is_bsup_def is_least_def)\n\n  show ?thesis using leq_antisym 1 3 by auto\nqed\n\n(*\nPordps = \"PORD + Pairwise Sups\"\n(this could be phrased as an extension of Pord_Weak, but i don't think\nthis is that useful)\n\nHere we add the assumption that if any 3 elements have pairwise\nsups, all 3 have a sup. This ends up being useful for reasoning about\nliftings.\n\n*)\n\nclass Pordps =\n  Pord +\n  assumes pairwise_sup :\n    \"has_sup {a, b} \\<Longrightarrow> has_sup {b, c} \\<Longrightarrow> has_sup {a, c} \\<Longrightarrow>\n     has_sup {a, b, c}\"\n\nclass Pordok = Pord + Okay\n\nclass Pordpsok = Pordok + Pordps +\n  assumes pairwise_sup_ok :\n  \"\\<And> a b supr :: ('a :: {Pord, Okay}). a \\<in> ok_S \\<Longrightarrow> b \\<in> ok_S \\<Longrightarrow> is_sup {a, b} supr \\<Longrightarrow> supr \\<in> ok_S\"\n\n\n(* Pordc = \"PORD + Completness\" \n * Note that this is a rather weak notion of completeness; we only require that\n * pairs with upper bounds have sups. Later we show that this implies completeness for\n * _finite_ sets. In some domain theory contexts completeness is presented as\n * applying to arbitrary sets, including infinite ones; we do not require that here\n * (intuitively, we know we will always be merging a finite number of language components\n * to get our final result)\n*)\nclass Pordc =\n  Pord +\n  assumes complete2: \"has_ub {a, b} \\<Longrightarrow> has_sup {a, b}\"\n\n(* helper lemmas for our proof that bsup equals sup, in the event sup exists *)\n\nlemma bsup_compare1:\n  fixes a b bs_ab a' b' bs_a'b :: \"'a :: Pordc\"\n  assumes Hbsup1 : \"is_bsup a b bs_ab\"\n  assumes Hbsup2 : \"is_bsup a' b' bs_a'b'\"\n  assumes Hleqa : \"pleq a a'\"\n  assumes Hleqa' : \"pleq a' bs_ab\"\n  assumes Hdesc : \"\\<And> bd sd . pleq bd b \\<Longrightarrow> is_sup {a, bd} sd \\<Longrightarrow> \n                        (pleq bd (b'))\" (* can we get away with has_ub here? *)\n  shows \"pleq (bs_ab) (bs_a'b')\"\nproof(-)\n  have Bub : \"is_bub a b bs_a'b'\"\n  proof(-)\n\n    have Hbub : \"\\<And> bd sd . pleq bd b \\<Longrightarrow> is_sup {a, bd} sd \\<Longrightarrow> pleq sd (bs_ab)\" using Hbsup1\n      by(auto simp add:is_bsup_def is_bub_def is_least_def) \n    \n    have Hbub' : \"\\<And> bd sd . pleq bd (b') \\<Longrightarrow> is_sup {a', bd} sd \\<Longrightarrow> pleq sd (bs_a'b')\" using Hbsup2\n      by(auto simp add:is_bsup_def is_bub_def is_least_def) \n\n    have Conc1 : \"pleq a (bs_a'b')\" using Hleqa\n    proof(-)\n      have in0 : \"pleq a' (bs_a'b')\" using bsup_leq Hbsup2 by auto\n      thus ?thesis using leq_trans[OF Hleqa in0] by auto\n    qed\n\n    have Conc2 : \"\\<And> bd sd . pleq bd (b) \\<Longrightarrow> is_sup {a, bd} sd \\<Longrightarrow> pleq sd (bs_a'b')\"\n    proof(-)\n      fix bd sd\n      assume Hbd : \"pleq bd (b)\"\n      assume Hsup : \"is_sup {a, bd} sd\"\n\n      have 0 : \"pleq bd (b')\" using Hdesc[OF Hbd Hsup] by auto\n(*      have 1 : \"pleq bd (aug (bsup a' b'))\" using Hdesc[OF Hbd Hsup] *)\n\n      have 1 : \"pleq bd sd\" using Hsup \n        by(auto simp add: is_sup_def is_ub_def is_least_def)\n\n      have 2 : \"pleq sd (bs_ab)\" using Hbub[OF Hbd Hsup] by auto\n\n      have \"pleq bd (bs_ab)\" using leq_trans[OF 1 2] by auto \n\n      hence 3 : \"is_ub {(a'), bd} ((bs_ab))\" using Hleqa'\n        by(auto simp add:is_ub_def leq_refl) \n\n      hence 4 : \"has_ub {(a'), bd}\"\n        by (auto simp add:has_ub_def)\n\n      hence 5 : \"has_sup {(a'), bd}\"\n        by (auto simp add:complete2)\n\n      then obtain sd' where Hsd' : \"is_sup {a', bd} sd'\" by (auto simp add:has_sup_def)\n\n      have 6: \"pleq sd' (bs_a'b')\" using Hbub'[OF 0 Hsd'] by auto\n\n      have 8 : \"pleq sd sd'\" using sup_extend[OF Hleqa Hsup Hsd'] by auto\n      \n      show \"pleq sd (bs_a'b')\" using leq_trans[OF 8 6] by auto\n    qed\n\n    then show ?thesis using Conc1 Conc2 by(simp add:is_bub_def) \n  qed\n  thus ?thesis using Hbsup1\n    by(auto simp add:is_bsup_def is_least_def)\nqed\n\n(* TODO: can we merge this with bsup_compare1 somehow? *)\nlemma bsup_compare2:\n  fixes a b bs_ab a' b' bs_a'b :: \"'a :: Pordc\"\n  assumes Hbsup1 : \"is_bsup a' b' bs_a'b'\"\n assumes Hbsup2 : \"is_bsup a b bs_ab\"\n assumes Hleqa' : \"pleq a' a\"\n assumes Hleqa : \"pleq a (bs_a'b')\" \n  assumes Hdesc : \"\\<And> bd sd . pleq bd (b) \\<Longrightarrow> is_sup {a, bd} sd \\<Longrightarrow> \n                        (pleq bd (b'))\" (* can we get away with has_ub here? *)\n  shows \"pleq bs_ab bs_a'b'\"\nproof(-)\n  have Bub : \"is_bub a b bs_a'b'\"\n  proof(-)\n\n    have Hbub : \"\\<And> bd sd . pleq bd (b) \\<Longrightarrow> is_sup {a, bd} sd \\<Longrightarrow> pleq sd (bs_ab)\" using Hbsup2\n      by(auto simp add: is_bsup_def is_bub_def is_least_def) \n    \n    have Hbub' : \"\\<And> bd sd . pleq bd (b') \\<Longrightarrow> is_sup {a', bd} sd \\<Longrightarrow> pleq sd bs_a'b'\" using Hbsup1\n      by(auto simp add: is_bsup_def is_bub_def is_least_def) \n\n    have Conc1 : \"pleq a (bs_a'b')\" using Hleqa by auto\n\n    have Conc2 : \"\\<And> bd sd . pleq bd (b) \\<Longrightarrow> is_sup {a, bd} sd \\<Longrightarrow> pleq sd (bs_a'b')\"\n    proof(-)\n      fix bd sd\n      assume Hbd : \"pleq bd (b)\"\n      assume Hsup : \"is_sup {a, bd} sd\"\n\n      have 0 : \"pleq bd (b')\" using Hdesc[OF Hbd Hsup] by auto\n\n      have 1 : \"pleq bd sd\" using Hsup \n        by(auto simp add: is_sup_def is_ub_def is_least_def)\n\n      have 2 : \"pleq sd (bs_ab)\" using Hbub[OF Hbd Hsup] by auto\n\n      have 3 : \"pleq bd (bs_ab)\" using leq_trans[OF 1 2] by auto \n\n      have 4 : \"pleq a' (bs_ab)\" using leq_trans[OF Hleqa' bsup_leq[OF Hbsup2]]\n        by auto\n\n      hence 5 : \"is_ub {(a'), bd} (bs_ab)\" using 3\n        by(auto simp add:is_ub_def leq_refl)\n\n      hence 6 : \"has_ub {(a'), bd}\" by (auto simp add:has_ub_def)\n\n      have 7: \"has_sup {a', bd}\" using complete2[OF 6] by auto\n\n      have 8 : \"pleq bd (b')\" using Hdesc[OF Hbd Hsup] by auto\n\n      obtain sd' where Hsd' : \"is_sup {a', bd} sd'\" using 7 by (auto simp add:has_sup_def)\n\n      have 9 : \"pleq sd' (bs_a'b')\" using Hbub'[OF 8 Hsd'] by auto\n\n      have 10 : \"pleq bd sd'\" using Hsd' by (auto simp add:is_sup_def is_least_def is_ub_def)\n\n      have 11 : \"pleq bd (bs_a'b')\" using leq_trans[OF 10 9] by auto\n\n      have 12 : \"is_ub {(a), bd} (bs_a'b')\" using Hleqa 11\n        by(auto simp add:is_ub_def)\n\n      show \"pleq sd (bs_a'b')\" using 12 Hsup\n        by(auto simp add:is_ub_def is_sup_def is_least_def)\n    qed\n\n    then show ?thesis using Conc1 Conc2 by(simp add:is_bub_def) \n  qed\n  thus ?thesis using Hbsup2\n    by(auto simp add:is_bsup_def is_least_def)\nqed\n\nlemma bsup_mono2 :\n  fixes a b bs_ab a' b' bs_ab' :: \"'a :: Pordc\"\n  assumes H: \"pleq b b'\"\n  assumes Hbsup1 : \"is_bsup a b bs_ab\"\n  assumes Hbsup2 : \"is_bsup a b' bs_ab'\"\n  shows   \"pleq (bs_ab) (bs_ab')\"\n\nproof(-)\n\n  have Hbound :\n     \"(\\<And>bd sd. pleq bd b \\<Longrightarrow> is_sup {a, bd} sd \\<Longrightarrow> pleq bd b') \"\n  proof(-)\n    fix bd sd\n    assume H1 : \"pleq bd b\"\n    assume H2 : \"is_sup {a, bd} sd\"\n\n    show \"pleq bd b'\" using leq_trans[OF H1 H] by auto\n  qed\n  \n  show ?thesis using bsup_compare1[OF Hbsup1 Hbsup2 leq_refl[of a] bsup_leq[OF Hbsup1] Hbound] by auto\nqed\n\n(* One of the key results from this file.\n * A biased supremum is guaranteed to coincide with the \"true\" supremum, should one exist.\n * This proves very helpful in characterizing and reasoning about bsup, avoiding some of the\n * \"lower-level\" proofs about bsup performed up to this point.\n*)\nlemma bsup_sup :\n  fixes a b bs_ab :: \"'a :: Pordc\"\n  assumes Hsup : \"is_sup {a, b} s_ab\" \n  assumes Hbsup : \"is_bsup a b bs_ab\"\n  shows \"is_sup {a, b} bs_ab\"\nproof(-)\n\n  have Bub : \"is_bub a b s_ab\"\n  proof(-)\n    have Conc1 : \"pleq a s_ab\" using Hsup\n      by(auto simp add:is_sup_def is_least_def is_ub_def)\n\n    have Conc2 :\n      \"\\<And> bd sd . pleq bd b \\<Longrightarrow> is_sup {a, bd} sd \\<Longrightarrow> pleq sd s_ab\"\n    proof(-)\n      fix bd sd\n      assume Hi1 : \"pleq bd b\"\n      assume Hi2 : \"is_sup {a, bd} sd\"\n\n      have 0 : \"pleq bd sd\"\n        using Hi2 by (auto simp add:is_sup_def is_least_def is_ub_def)\n\n      have 1 : \"pleq b s_ab\"\n        using Hsup by (auto simp add:is_sup_def is_least_def is_ub_def)\n\n      have 2 : \"pleq bd s_ab\"\n        using leq_trans[OF Hi1 1] by auto\n\n      have \"is_ub {a, bd} s_ab\" using Conc1 2\n        by(auto simp add:is_ub_def)\n\n      thus \"pleq sd s_ab\" using Hi2\n        by(auto simp add:is_sup_def is_least_def)\n    qed\n\n    show ?thesis using Conc1 Conc2\n      by (auto simp add: is_bub_def)\n  qed\n\n  have bs_ab_Lt : \"pleq bs_ab s_ab\" using Bub Hbsup\n    by(auto simp add:is_bsup_def is_least_def)\n\n  have Ub : \"is_ub {a, b} bs_ab\"\n  proof(-)\n    have Conc1 : \"pleq a bs_ab\" using Hbsup\n      by(auto simp add:is_bsup_def is_bub_def is_least_def)\n\n    have 0 : \"pleq b s_ab\" using Hsup by (auto simp add:is_supD1)\n\n    have 1 : \"pleq s_ab bs_ab\" using is_bsupD2[OF Hbsup leq_refl Hsup] by auto\n\n    have Conc2 : \"pleq b bs_ab\" using leq_trans[OF 0 1] by auto\n\n    show ?thesis using Conc1 Conc2 by\n      (auto simp add:is_ub_def)\n  qed\n\n  have s_ab_Lt : \"pleq s_ab bs_ab\" using Ub Hsup\n    by(auto simp add: is_sup_def is_least_def)\n\n  show ?thesis using leq_antisym[OF bs_ab_Lt s_ab_Lt] Hsup by auto\nqed\n\n\nlemma leq_completion :\n  fixes a a' b x :: \"'a :: Pordc\"\n  assumes Hleq : \"pleq a a'\"\n  assumes Hsup : \"is_sup {a', b} x\"\n  shows \"has_sup {a, b}\"\nproof(-)\n  have 0 :  \"pleq a' x\" using Hsup by (simp add:is_sup_def is_least_def is_ub_def)\n  have 1 : \"pleq a x\" using leq_trans[OF Hleq 0] by auto\n  hence 2 : \"is_ub {a, b} x\" using Hsup by (simp add:is_sup_def is_least_def is_ub_def)\n  hence 3 : \"has_ub {a, b}\" by (auto simp add:has_ub_def)\n  thus ?thesis by (auto elim: complete2)\nqed\n\n\nlemma bsup_imp_sup :\n  assumes Hbs : \"is_bsup a b bs\"\n  assumes H : \"pleq b bs\"\n  shows \"is_sup {a, b} bs\"\n\nproof(rule is_supI)\n  fix x\n  assume Hx : \"x \\<in> {a, b}\"\n  show \"pleq x bs\" using H bsup_leq[OF Hbs] Hx\n    by(auto)\nnext\n  fix ub\n  assume Hi :  \"is_ub {a, b} ub\"\n\n  have 0 : \"is_bub a b ub\"\n  proof(rule is_bubI)\n    show \"pleq a ub\" using Hi by (auto simp add:is_ub_def)\n  next\n    fix bd sd\n    assume Hl : \"pleq bd b\"\n    assume Hs : \"is_sup {a, bd} sd\"\n\n    have 0 : \"is_ub {a, bd} ub\" using Hi Hl leq_trans[of bd b ub]\n      by(auto simp add:is_ub_def)\n\n    show \"pleq sd ub\" using is_supD2[OF Hs 0] by auto\n  qed\n\n  show \"pleq bs ub\" using is_bsupD3[OF Hbs 0] by auto\nqed\n\n(* A consequence of bsup_sup : if we have completeness, a bsup, and an upper bound\n * for a and b, then b must be less than the bsup (i.e. bsup finds a \"true supremum\")\n *)\nlemma bsup_imp_sup_conv :\n  fixes a b bs ub :: \"'a :: Pordc\"\n  assumes Hbs : \"is_bsup a b bs\"\n  assumes H : \"\\<not> pleq b bs\"\n  assumes Hub : \"is_ub {a, b} ub\"\n  shows False\nproof(-)\n  obtain lub where Hlub : \"is_sup {a, b} lub\" using Hub complete2 by(auto simp add:has_ub_def has_sup_def)\n  have Hbub : \"is_bub a b bs\" using Hbs by(auto simp add:is_bsup_def is_least_def)\n  have \"pleq lub bs\" using is_bubD2[OF Hbub leq_refl[of b] Hlub] by auto\n  hence \"pleq b bs\" using Hlub leq_trans[of b lub bs] by (auto simp add:is_sup_def is_least_def is_ub_def)\n  thus ?thesis using H by auto\nqed\n\n(*\n * Pordb = \"Partial ORDer with Bottom. That is, a partial order with the additional requirement\n * that there be a least (\"bottom\", \\<bottom>) element. In the literature such orders are often\n * called \"pointed\"; however, I wished to avoid confusion since \"p\" in this acronym already\n * stands for \"partial\"\n *)\n\nclass Pord_Weakb = Pord_Weak +\nfixes bot :: \"'a\" (\"\\<bottom>\")\nassumes bot_spec :\n  \"\\<And> (a :: 'a ) .  pleq bot a\"\n\nclass Pordb =  Pord + Pord_Weakb\n\nclass Pordbps = Pordb + Pordps\n\nclass Pordpsc = Pordps + Pordc\n\n(* Pordc and Pordb are basically orthogonal extensions to Pord. Often we care about\n * cases where we have both. *)\nclass Pordbc =  Pordc + Pordb\n\nclass Pordbpsc = Pordbc + Pordps\n\nclass Pordc_all = Pordc +\n  assumes ub2_all : \"\\<And> a b . has_ub {a, b}\"\n\nlemma sup2_all :\n  fixes a b :: \"'a :: Pordc_all\"\n  shows \"has_sup {a, b}\"\n  using complete2[OF ub2_all[of a b]]\n  by auto\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/Mergeable/Pord.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312213841788, "lm_q2_score": 0.7931059560743422, "lm_q1q2_score": 0.7195947208169192}}
{"text": "theory Auto_Proof_Demo\nimports Main\nbegin\n\nsection \"Logic and sets\"\n\nlemma \"ALL x. EX y. x=y\"\nby auto\n\nlemma \"A \\<subseteq> B \\<inter> C \\<Longrightarrow> A \\<subseteq> B \\<union> C\"\nby auto\n\ntext \\<open>Note the bounded quantification notation:\\<close>\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\n\ntext \\<open>Most simple proofs in FOL and set theory are automatic.\nExample: if T is total, A is antisymmetric and T is a subset of A, then A is a subset of T.\\<close>\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)^*\"\noops\n\ntext \\<open>Find a suitable P and try sledgehammer:\\<close>\n\nlemma \"a # xs = ys @ [a] \\<Longrightarrow> P\"\noops\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": "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/Auto_Proof_Demo.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067244294587, "lm_q2_score": 0.7634837689358857, "lm_q1q2_score": 0.7195885862148194}}
{"text": "section \"Sequents\"\n\ntheory Sequents\nimports Formula\nbegin \n\ntype_synonym sequent = \"formula list\"\n\ndefinition\n  evalS :: \"[model,vbl => object,formula list] => bool\" where\n  \"evalS M phi fs \\<longleftrightarrow> (? f : set fs . evalF M phi f = True)\"\n\nlemma evalS_nil[simp]: \"evalS M phi [] = False\"\n  by(simp add: evalS_def)\n\nlemma evalS_cons[simp]: \"evalS M phi (A # Gamma) = (evalF M phi A | evalS M phi Gamma)\"\n  by(simp add: evalS_def)\n\nlemma evalS_append: \"evalS M phi (Gamma @ Delta) = (evalS M phi Gamma | evalS M phi Delta)\"\n  by(force simp add: evalS_def)\n\nlemma evalS_equiv[rule_format]: \"(equalOn (freeVarsFL Gamma) f g) --> (evalS M f Gamma = evalS M g Gamma)\"\n  apply (induct Gamma, simp, rule)\n  apply(simp add: freeVarsFL_cons)\n  apply(drule_tac equalOn_UnD)\n  apply(blast dest: evalF_equiv)\n  done\n\n\ndefinition\n  modelAssigns :: \"[model] => (vbl => object) set\" where\n  \"modelAssigns M = { phi . range phi <= objects M }\"\n\nlemma modelAssignsI: \"range f <= objects M \\<Longrightarrow> f : modelAssigns M\" \n  by(simp add: modelAssigns_def)\n\nlemma modelAssignsD: \"f : modelAssigns M \\<Longrightarrow> range f <= objects M\" \n  by(simp add: modelAssigns_def)\n  \ndefinition\n  validS :: \"formula list => bool\" where\n  \"validS fs \\<longleftrightarrow> (! M . ! phi : modelAssigns M . evalS M phi fs = True)\"\n\n\nsubsection \"Rules\"\n\ntype_synonym rule = \"sequent * (sequent set)\"\n\ndefinition\n  concR :: \"rule => sequent\" where\n  \"concR = (%(conc,prems). conc)\"\n\ndefinition\n  premsR :: \"rule => sequent set\" where\n  \"premsR = (%(conc,prems). prems)\"\n\ndefinition\n  mapRule :: \"(formula => formula) => rule => rule\" where\n  \"mapRule = (%f (conc,prems) . (map f conc,(map f) ` prems))\"\n\nlemma mapRuleI: \"[| A = map f a; B = (map f) ` b |] ==> (A,B) = mapRule f (a,b)\"\n  by(simp add: mapRule_def)\n    \\<comment> \\<open>FIXME tjr would like symmetric\\<close>\n\n\nsubsection \"Deductions\"\n\n(*FIXME. I don't see why plain Pow_mono is rejected.*)\nlemmas Powp_mono [mono] = Pow_mono [to_pred pred_subset_eq]\n\ninductive_set\n  deductions  :: \"rule set => formula list set\"\n  for rules :: \"rule set\"\n  (******\n   * Given a set of rules,\n   *   1. Given a rule conc/prem(i) in rules,\n   *       and the prem(i) are deductions from rules,\n   *       then conc is a deduction from rules.\n   *   2. can derive permutation of any deducible formula list.\n   *      (supposed to be multisets not lists).\n   ******)\n  where\n    inferI: \"[| (conc,prems) : rules;\n               prems : Pow(deductions(rules))\n            |] ==> conc : deductions(rules)\"\n(*\n    perms   \"[| permutation conc' conc;\n                conc' : deductions(rules)\n             |] ==> conc : deductions(rules)\"\n*)\n \nlemma mono_deductions: \"[| A <= B |] ==> deductions(A) <= deductions(B)\"\n  apply(best intro: deductions.inferI elim: deductions.induct) done\n  \n(*lemmas deductionsMono = mono_deductions*)\n\n(*\n-- \"tjr following should be subsetD?\"\nlemmas deductionSubsetI = mono_deductions[THEN subsetD]\nthm deductionSubsetI\n*)\n\n(******\n * (f : formula -> formula) extended structurally over rules, deductions etc...\n * (((If f maps rules into themselves then can consider mapping derivation trees.)))\n * (((Is the asm necessary - think not?)))\n * The mapped deductions from the rules are same as\n * the deductions from the mapped rules.\n *\n * WHY:\n *\n * map f `` deductions rules <= deductions (mapRule f `` rules)     (this thm)\n *                           <= deductions rules                    (closed)\n *\n * If rules are closed under f then so are deductions.\n * Can take f = (subst u v) and have application to exercise #1.\n *\n * Q: maybe also make f dual mapping, (what about quantifier side conditions...?).\n ******)\n\n(*\nlemma map_deductions: \"map f ` deductions rules <= deductions (mapRule f ` rules)\"\n  apply(rule subsetI)\n  apply (erule_tac imageE, simp)\n  apply(erule deductions.induct)\n  apply(blast intro: deductions.inferI mapRuleI)\n  done\n\nlemma deductionsCloseRules: \"! (conc,prems) : S . prems <= deductions R --> conc : deductions R ==> deductions (R Un S) = deductions R\"\n  apply(rule equalityI)\n  prefer 2\n  apply(rule mono_deductions) apply blast\n  apply(rule subsetI)\n  apply (erule_tac deductions.induct, simp) apply(erule conjE) apply(thin_tac \"prems \\<subseteq> deductions (R \\<union> S)\")\n  apply(erule disjE)\n  apply(rule inferI) apply assumption apply force\n  apply blast\n  done\n*)\n\n\nsubsection \"Basic Rule sets\"\n\ndefinition\n  \"Axioms  = { z. ? p vs.              z = ([FAtom Pos p vs,FAtom Neg p vs],{}) }\"\ndefinition\n  \"Conjs   = { z. ? A0 A1 Delta Gamma. z = (FConj Pos A0 A1#Gamma @ Delta,{A0#Gamma,A1#Delta}) }\"\ndefinition\n  \"Disjs   = { z. ? A0 A1       Gamma. z = (FConj Neg A0 A1#Gamma,{A0#A1#Gamma}) }\"\ndefinition\n  \"Alls    = { z. ? A x         Gamma. z = (FAll Pos A#Gamma,{instanceF x A#Gamma}) & x ~: freeVarsFL (FAll Pos A#Gamma) }\"\ndefinition\n  \"Exs     = { z. ? A x         Gamma. z = (FAll Neg A#Gamma,{instanceF x A#Gamma})}\"\ndefinition\n  \"Weaks   = { z. ? A           Gamma. z = (A#Gamma,{Gamma})}\"\ndefinition\n  \"Contrs  = { z. ? A           Gamma. z = (A#Gamma,{A#A#Gamma})}\"\ndefinition\n  \"Cuts    = { z. ? C Delta     Gamma. z = (Gamma @ Delta,{C#Gamma,FNot C#Delta})}\"\ndefinition\n  \"Perms   = { z. ? Gamma Gamma'     . z = (Gamma,{Gamma'}) & Gamma <~~> Gamma'}\"\ndefinition\n  \"DAxioms = { z. ? p vs.              z = ([FAtom Neg p vs,FAtom Pos p vs],{}) }\"\n\n\nlemma AxiomI: \"[| Axioms <= A |] ==> [FAtom Pos p vs,FAtom Neg p vs] : deductions(A)\"\n  apply(rule deductions.inferI)\n  apply(auto simp add: Axioms_def) done\n\nlemma DAxiomsI: \"[| DAxioms <= A |] ==> [FAtom Neg p vs,FAtom Pos p vs] : deductions(A)\"\n  apply(rule deductions.inferI)\n  apply(auto simp add: DAxioms_def) done\n\nlemma DisjI: \"[| A0#A1#Gamma : deductions(A); Disjs <= A |] ==> (FConj Neg A0 A1#Gamma) : deductions(A)\"\n  apply(rule deductions.inferI)\n  apply(auto simp add: Disjs_def) done\n\nlemma ConjI: \"[| (A0#Gamma) : deductions(A); (A1#Delta) : deductions(A); Conjs <= A |] ==> FConj Pos A0 A1#Gamma @ Delta : deductions(A)\"\n  apply(rule_tac prems=\"{A0#Gamma,A1#Delta}\" in deductions.inferI)\n  apply(auto simp add: Conjs_def) apply force done\n\nlemma AllI: \"[| instanceF w A#Gamma : deductions(R); w ~: freeVarsFL (FAll Pos A#Gamma); Alls <= R |] ==> (FAll Pos A#Gamma) : deductions(R)\"\n  apply(rule_tac prems=\"{instanceF w A#Gamma}\" in deductions.inferI)\n  apply(auto simp add: Alls_def) done\n\nlemma ExI: \"[| instanceF w A#Gamma : deductions(R); Exs <= R |] ==> (FAll Neg A#Gamma) : deductions(R)\"\n  apply(rule_tac prems = \"{instanceF w A#Gamma}\" in deductions.inferI)\n  apply(auto simp add: Exs_def) done\n\nlemma WeakI: \"[| Gamma : deductions R; Weaks <= R |] ==> A#Gamma : deductions(R)\"\n  apply(rule_tac prems=\"{Gamma}\" in deductions.inferI)\n  apply(auto simp add: Weaks_def) done\n\nlemma ContrI: \"[| A#A#Gamma : deductions R; Contrs <= R |] ==> A#Gamma : deductions(R)\"\n  apply(rule_tac prems=\"{A#A#Gamma}\" in deductions.inferI)\n  apply(auto simp add: Contrs_def) done\n\nlemma PermI: \"[| Gamma' : deductions R; Gamma <~~> Gamma'; Perms <= R |] ==> Gamma : deductions(R)\"\n  apply(rule_tac prems=\"{Gamma'}\" in deductions.inferI)\n  apply(auto simp add: Perms_def) done\n\n\nsubsection \"Derived Rules\"\n\nlemma WeakI1: \"[| Gamma : deductions(A); Weaks <= A |] ==> (Delta @ Gamma) : deductions(A)\"\n  apply (induct Delta, simp)\n  apply(auto intro: WeakI) done\n\nlemma WeakI2: \"[| Gamma : deductions(A); Perms <= A; Weaks <= A |] ==> (Gamma @ Delta) : deductions(A)\"\n  apply(blast intro: PermI perm_append_swap WeakI1) done\n\nlemma SATAxiomI: \"[| Axioms <= A; Weaks <= A; Perms <= A; forms = [FAtom Pos n vs,FAtom Neg n vs] @ Gamma |] ==> forms : deductions(A)\"\n  apply(simp only:)\n  apply(blast intro: WeakI2 AxiomI)\n  done\n    \nlemma DisjI1: \"[| (A1#Gamma) : deductions(A); Disjs <= A; Weaks <= A |] ==> FConj Neg A0 A1#Gamma : deductions(A)\"\n  apply(blast intro: DisjI WeakI)\n  done\n\nlemma DisjI2: \"!!A. [| (A0#Gamma) : deductions(A); Disjs <= A; Weaks <= A; Perms <= A |] ==> FConj Neg A0 A1#Gamma : deductions(A)\"\n  apply(rule DisjI)\n  apply(rule PermI[OF _ perm.swap])\n  apply(rule WeakI)\n  .\n\n    \\<comment> \\<open>FIXME the following 4 lemmas could all be proved for the standard rule sets using monotonicity as below\\<close>\n    \\<comment> \\<open>we keep proofs as in original, but they are slightly ugly, and do not state what is intuitively happening\\<close>\nlemma perm_tmp4: \"Perms \\<subseteq> R \\<Longrightarrow> A @ (a # list) @ (a # list) : deductions R \\<Longrightarrow> (a # a # A) @ list @ list : deductions R\"\n  apply (rule PermI, auto)\n  apply(simp add: perm_count_conv count_append) done\n\nlemma weaken_append[rule_format]: \"Contrs <= R ==> Perms <= R ==> !A. A @ Gamma @ Gamma : deductions(R) -->  A @ Gamma : deductions(R)\"\n  apply (induct_tac Gamma, simp, rule) apply rule\n  apply(drule_tac x=\"a#a#A\" in spec)\n  apply(erule_tac impE)\n  apply(rule perm_tmp4) apply(assumption, assumption)\n  apply(thin_tac \"A @ (a # list) @ a # list \\<in> deductions R\")\n  apply simp\n  apply(frule_tac ContrI) apply assumption\n  apply(thin_tac \"a # a # A @ list \\<in> deductions R\")\n  apply(rule PermI) apply assumption \n  apply(simp add: perm_count_conv count_append) \n  by assumption\n  \\<comment> \\<open>FIXME horrible\\<close>\n\nlemma ListWeakI: \"Perms <= R ==> Contrs <= R ==> x # Gamma @ Gamma : deductions(R) ==> x # Gamma : deductions(R)\"\n  by(rule weaken_append[of R \"[x]\" Gamma, simplified])\n    \nlemma ConjI': \"[| (A0#Gamma) : deductions(A);  (A1#Gamma) : deductions(A); Contrs <= A; Conjs <= A; Perms <= A |] ==> FConj Pos A0 A1#Gamma : deductions(A)\"\n  apply(rule ListWeakI, assumption, assumption)\n  apply(rule ConjI) .\n\n\n\nsubsection \"Standard Rule Sets For Predicate Calculus\"\n\ndefinition\n  PC :: \"rule set\" where\n  \"PC = Union {Perms,Axioms,Conjs,Disjs,Alls,Exs,Weaks,Contrs,Cuts}\"\n\ndefinition\n  CutFreePC :: \"rule set\" where\n  \"CutFreePC = Union {Perms,Axioms,Conjs,Disjs,Alls,Exs,Weaks,Contrs}\"\n\nlemma rulesInPCs: \"Axioms <= PC\" \"Axioms <= CutFreePC\"\n  \"Conjs  <= PC\" \"Conjs  <= CutFreePC\"\n  \"Disjs  <= PC\" \"Disjs  <= CutFreePC\"\n  \"Alls   <= PC\" \"Alls   <= CutFreePC\"\n  \"Exs    <= PC\" \"Exs    <= CutFreePC\"\n  \"Weaks  <= PC\" \"Weaks  <= CutFreePC\"\n  \"Contrs <= PC\" \"Contrs <= CutFreePC\"\n  \"Perms  <= PC\" \"Perms  <= CutFreePC\"\n  \"Cuts   <= PC\"\n  \"CutFreePC <= PC\"\n  by(auto simp: PC_def CutFreePC_def)\n\n\nsubsection \"Monotonicity for CutFreePC deductions\"\n\n  \\<comment> \\<open>these lemmas can be used to replace complicated permutation reasoning above\\<close>\n  \\<comment> \\<open>essentially if x is a deduction, and set x subset set y, then y is a deduction\\<close>\n\ndefinition\n  inDed :: \"formula list => bool\" where\n  \"inDed xs \\<longleftrightarrow> xs : deductions CutFreePC\"\n\nlemma perm: \"! xs ys. xs <~~> ys --> (inDed xs = inDed ys)\"\n  apply(subgoal_tac \"! xs ys. xs <~~> ys --> inDed xs --> inDed ys\")\n  apply (blast intro: perm_sym, clarify)\n  apply(simp add: inDed_def)\n  apply (rule PermI, assumption)\n  apply(rule perm_sym) apply assumption\n  by(blast intro!: rulesInPCs)\n\nlemma contr: \"! x xs. inDed (x#x#xs) --> inDed (x#xs)\"\n  apply(simp add: inDed_def)\n  apply(blast intro!: ContrI rulesInPCs)\n  done\n\nlemma weak: \"! x xs. inDed xs --> inDed (x#xs)\"\n  apply(simp add: inDed_def)\n  apply(blast intro!: WeakI rulesInPCs)\n  done\n\n\n\nlemma inDed_mono[simplified inDed_def]: \"inDed x ==> set x <= set y ==> inDed y\"\n  using perm_weak_contr_mono[OF perm contr weak] .\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/Completeness/Sequents.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391617003942, "lm_q2_score": 0.8333245891029457, "lm_q1q2_score": 0.7194854644747378}}
{"text": "section\\<open>Group by Function\\<close>\ntheory GroupF\nimports Main\nbegin\n\ntext\\<open>Grouping elements of a list according to a function.\\<close>\n\nfun groupF ::  \"('a \\<Rightarrow> 'b) \\<Rightarrow> 'a list \\<Rightarrow> 'a list list\"  where\n  \"groupF f [] = []\" |\n  \"groupF f (x#xs) = (x#(filter (\\<lambda>y. f x = f y) xs))#(groupF f (filter (\\<lambda>y. f x \\<noteq> f y) xs))\"\n\ntext\\<open>trying a more efficient implementation of @{term groupF}\\<close>\ncontext\nbegin\n  private fun select_p_tuple :: \"('a \\<Rightarrow> bool) \\<Rightarrow> 'a \\<Rightarrow> ('a list \\<times> 'a list) \\<Rightarrow> ('a list \\<times> 'a list)\"\n  where\n    \"select_p_tuple p x (ts,fs) = (if p x then (x#ts, fs) else (ts, x#fs))\"\n  \n  private definition partition_tailrec :: \"('a \\<Rightarrow> bool) \\<Rightarrow> 'a list \\<Rightarrow> ('a list \\<times> 'a list)\"\n  where\n    \"partition_tailrec p xs = foldr (select_p_tuple p) xs ([],[])\"\n  \n  private lemma partition_tailrec: \"partition_tailrec f as =  (filter f as,  filter (\\<lambda>x. \\<not>f x) as)\"\n  proof - \n    {fix ts_accu fs_accu\n      have \"foldr (select_p_tuple f) as (ts_accu, fs_accu) =\n              (filter f as @ ts_accu,  filter (\\<lambda>x. \\<not>f x) as @ fs_accu)\"\n      by(induction as arbitrary: ts_accu fs_accu) simp_all\n    } thus ?thesis unfolding partition_tailrec_def by simp\n  qed\n  \n  private lemma\n    \"groupF f (x#xs) = (let (ts, fs) = partition_tailrec (\\<lambda>y. f x = f y) xs in (x#ts)#(groupF f fs))\"\n  by(simp add: partition_tailrec)\n  \n  (*is this more efficient?*)\n  private function groupF_code ::  \"('a \\<Rightarrow> 'b) \\<Rightarrow> 'a list \\<Rightarrow> 'a list list\"  where\n    \"groupF_code f [] = []\" |\n    \"groupF_code f (x#xs) = (let\n                               (ts, fs) = partition_tailrec (\\<lambda>y. f x = f y) xs\n                             in\n                               (x#ts)#(groupF_code f fs))\"\n  by(pat_completeness) auto\n  \n  private termination groupF_code\n    apply(relation \"measure (\\<lambda>(f,as). length (filter (\\<lambda>x. (\\<lambda>y. f x = f y) x) as))\")\n     apply(simp; fail)\n    apply(simp add: partition_tailrec)\n    using le_imp_less_Suc length_filter_le by blast\n  \n  lemma groupF_code[code]: \"groupF f as = groupF_code f as\"\n    by(induction f as rule: groupF_code.induct) (simp_all add: partition_tailrec)\n  \n  export_code groupF checking SML\nend\n\nlemma groupF_concat_set: \"set (concat (groupF f xs)) = set xs\"\n  proof(induction f xs rule: groupF.induct)\n  case 2 thus ?case by (simp) blast\n  qed(simp)\n\nlemma groupF_Union_set: \"(\\<Union>x \\<in> set (groupF f xs). set x) = set xs\"\n  proof(induction f xs rule: groupF.induct)\n  case 2 thus ?case by (simp) blast\n  qed(simp)\n\nlemma groupF_set: \"\\<forall>X \\<in> set (groupF f xs). \\<forall>x \\<in> set X. x \\<in> set xs\"\n  using groupF_concat_set by fastforce\n\nlemma groupF_equality:\n  defines \"same f A \\<equiv> \\<forall>a1 \\<in> set A. \\<forall>a2 \\<in> set A. f a1 = f a2\"\n  shows \"\\<forall>A \\<in> set (groupF f xs). same f A\"\n  proof(induction f xs rule: groupF.induct)\n    case 1 thus ?case by simp\n  next\n    case (2 f x xs)\n      have groupF_fst:\n        \"groupF f (x # xs) = (x # [y\\<leftarrow>xs . f x = f y]) # groupF f [y\\<leftarrow>xs . f x \\<noteq> f y]\" by force\n      have step: \" \\<forall>A\\<in>set [x # [y\\<leftarrow>xs . f x = f y]]. same f A\" unfolding same_def by fastforce\n      with 2 show ?case unfolding groupF_fst by fastforce\n  qed\n\nlemma groupF_nequality: \"A \\<in> set (groupF f xs) \\<Longrightarrow> B \\<in> set (groupF f xs) \\<Longrightarrow> A \\<noteq> B \\<Longrightarrow>\n     \\<forall>a \\<in> set A. \\<forall>b \\<in> set B. f a \\<noteq> f b\"\n  proof(induction f xs rule: groupF.induct)\n  case 1 thus ?case by simp\n  next\n  case 2 thus ?case\n    apply -\n    apply(subst (asm) groupF.simps)+\n    using groupF_set by fastforce (*1s*)\n  qed\n\nlemma groupF_cong: fixes xs::\"'a list\" and f1::\"'a \\<Rightarrow> 'b\" and f2::\"'a \\<Rightarrow> 'c\"\n  assumes \"\\<forall>x \\<in> set xs. \\<forall>y \\<in> set xs. (f1 x = f1 y \\<longleftrightarrow> f2 x = f2 y)\"\n  shows \"groupF f1 xs = groupF f2 xs\"\n  using assms proof(induction f1 xs rule: groupF.induct)\n    case (2 f x xs) thus ?case using filter_cong[of xs xs \"\\<lambda>y. f x = f y\" \"\\<lambda>y. f2 x = f2 y\"]\n                                     filter_cong[of xs xs \"\\<lambda>y. f x \\<noteq> f y\" \"\\<lambda>y. f2 x \\<noteq> f2 y\"] by auto\n  qed (simp)\n\nlemma groupF_empty: \"groupF f xs \\<noteq> [] \\<longleftrightarrow> xs \\<noteq> []\"\n  by(induction f xs rule: groupF.induct) auto\nlemma groupF_empty_elem: \"x \\<in> set (groupF f xs) \\<Longrightarrow> x \\<noteq> []\"\n  by(induction f xs rule: groupF.induct) auto\n\nlemma groupF_distinct: \"distinct xs \\<Longrightarrow> distinct (concat (groupF f xs))\"\n  proof(induction f xs rule: groupF.induct)\n  case (2 f x xs) thus ?case\n    apply (simp)\n    apply(intro conjI)\n     apply (meson filter_is_subset groupF_set subsetCE)\n    apply(subgoal_tac \"UNION (set (groupF f [a\\<leftarrow>xs . f x \\<noteq> f a])) set = set [a\\<leftarrow>xs . f x \\<noteq> f a]\")\n     prefer 2\n     apply (metis (no_types) groupF_concat_set set_concat)\n    by auto\n  qed(simp)\n\n\ntext\\<open>It is possible to use\n    @{term \"map (map fst) (groupF snd (map (\\<lambda>x. (x, f x)) P))\"}\n  instead of\n    @{term \"groupF f P\"}\n  for the following reasons:\n    @{const groupF} executes its compare function (first parameter) very often;\n    it always tests for @{term \"(f x = f y)\"}.\n    The function @{term f} may be really expensive.\n    At least polyML does not share the result of @{term f} but (probably) always recomputes (part of) it.\n    The optimization pre-computes @{term f} and tells @{const groupF} to use\n    a really cheap function (@{const snd}) to compare.\n    The following lemma tells that those are equal.\\<close>\n  (* is this also faster for Haskell?*)\n\nlemma groupF_tuple: \"groupF f xs = map (map fst) (groupF snd (map (\\<lambda>x. (x, f x)) xs))\"\n  proof(induction f xs rule: groupF.induct)\n  case (1 f) thus ?case by simp\n  next\n  case (2 f x xs)\n    have g1: \"[y\\<leftarrow>xs . f x = f y] = map fst [y\\<leftarrow>map (\\<lambda>x. (x, f x)) xs . f x = snd y]\"\n      proof(induction xs arbitrary: f x)\n      case Cons thus ?case by fastforce\n      qed(simp)\n    have g2: \"(map (\\<lambda>x. (x, f x)) [y\\<leftarrow>xs . f x \\<noteq> f y]) = [y\\<leftarrow>map (\\<lambda>x. (x, f x)) xs . f x \\<noteq> snd y]\"\n      proof(induction xs)\n      case Cons thus ?case by fastforce\n      qed(simp)\n    from 2 g1 g2 show ?case by simp\n  qed\nend", "meta": {"author": "diekmann", "repo": "Iptables_Semantics", "sha": "e0a2516bd885708fce875023b474ae341cbdee29", "save_path": "github-repos/isabelle/diekmann-Iptables_Semantics", "path": "github-repos/isabelle/diekmann-Iptables_Semantics/Iptables_Semantics-e0a2516bd885708fce875023b474ae341cbdee29/thy/Simple_Firewall/Common/GroupF.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933271118221, "lm_q2_score": 0.8774767922879693, "lm_q1q2_score": 0.7194373666923923}}
{"text": "(*\n  File: OrderTopology.thy\n  Author: Bohua Zhan\n\n  Basic results about order topology.\n*)\n\ntheory OrderTopology\n  imports Topology Auto2_FOL.Interval Auto2_FOL.AlgStructure\nbegin\n\nsection \\<open>Set with at least two element\\<close>\n  \ndefinition card_ge2 :: \"i \\<Rightarrow> o\" where [rewrite]:\n  \"card_ge2(X) \\<longleftrightarrow> (\\<exists>a\\<in>X. \\<exists>b\\<in>X. a \\<noteq> b)\"\n  \nlemma card_ge2I [backward2]: \"{a,b} \\<subseteq> X \\<Longrightarrow> a \\<noteq> b \\<Longrightarrow> card_ge2(X)\" by auto2\nlemma card_ge2_D1 [resolve]: \"card_ge2(X) \\<Longrightarrow> \\<exists>a\\<in>X. \\<exists>b\\<in>X. a \\<noteq> b\" by auto2\nlemma card_ge2_D2 [resolve]: \"card_ge2(X) \\<Longrightarrow> a \\<in> X \\<Longrightarrow> \\<exists>b\\<in>X. b \\<noteq> a\" by auto2\nsetup {* del_prfstep_thm @{thm card_ge2_def} *}\n  \nsection \\<open>Order topology\\<close>\n\ndefinition ord_basis :: \"i \\<Rightarrow> i\" where [rewrite]:\n  \"ord_basis(X) = ((\\<Union>a\\<in>.X. \\<Union>b\\<in>.X. {open_interval(X,a,b)}) \\<union>\n     (\\<Union>a\\<in>.X. {less_interval(X,a)}) \\<union> (\\<Union>a\\<in>.X. {greater_interval(X,a)}))\"\n  \nlemma ord_basisE [forward]:\n  \"W \\<in> ord_basis(X) \\<Longrightarrow> (\\<exists>a\\<in>.X. \\<exists>b\\<in>.X. W = open_interval(X,a,b)) \\<or>\n     (\\<exists>a\\<in>.X. W = less_interval(X,a)) \\<or> (\\<exists>a\\<in>.X. W = greater_interval(X,a))\" by auto2\n  \nlemma ord_basisI [resolve]:\n  \"a \\<in>. X \\<Longrightarrow> b \\<in>. X \\<Longrightarrow> open_interval(X,a,b) \\<in> ord_basis(X)\"\n  \"a \\<in>. X \\<Longrightarrow> less_interval(X,a) \\<in> ord_basis(X)\"\n  \"a \\<in>. X \\<Longrightarrow> greater_interval(X,a) \\<in> ord_basis(X)\" by auto2+\nsetup {* del_prfstep_thm @{thm ord_basis_def} *}\n\nlemma ord_basis_eq_str [rewrite]:\n  \"eq_str_order(X,Y) \\<Longrightarrow> ord_basis(X) = ord_basis(Y)\" by auto2\n\nlemma ord_basis_is_basis [forward]:\n  \"linorder(X) \\<Longrightarrow> collection_is_basis(ord_basis(X))\"\n@proof @let \"\\<B> = ord_basis(X)\" @have \"\\<forall>U\\<in>\\<B>. \\<forall>V\\<in>\\<B>. U \\<inter> V \\<in> \\<B>\" @qed\n\nlemma ord_basis_union [rewrite]:\n  \"linorder(X) \\<Longrightarrow> card_ge2(carrier(X)) \\<Longrightarrow> \\<Union>ord_basis(X) = carrier(X)\"\n@proof\n  @have \"\\<forall>x\\<in>.X. x \\<in> \\<Union>ord_basis(X)\" @with\n    @obtain \"y\\<in>.X\" where \"y \\<noteq> x\"\n    @case \"y <\\<^sub>X x\" @with @have \"x \\<in> greater_interval(X,y)\" @end\n    @case \"y >\\<^sub>X x\" @with @have \"x \\<in> less_interval(X,y)\" @end\n  @end\n@qed\n\ndefinition order_topology :: \"i \\<Rightarrow> o\" where [rewrite]:\n  \"order_topology(X) \\<longleftrightarrow> (linorder(X) \\<and> is_top_space_raw(X) \\<and> card_ge2(carrier(X)) \\<and>\n    open_sets(X) = top_from_basis(ord_basis(X)))\"\n\nlemma order_topology_has_basis [forward]:\n  \"order_topology(X) \\<Longrightarrow> top_has_basis(X,ord_basis(X))\" by auto2\n\nlemma order_topologyD [forward]:\n  \"order_topology(X) \\<Longrightarrow> linorder(X)\"\n  \"order_topology(X) \\<Longrightarrow> is_top_space(X)\"\n  \"order_topology(X) \\<Longrightarrow> card_ge2(carrier(X))\" by auto2+\n    \nlemma order_topologyI [backward]:\n  \"linorder(X) \\<Longrightarrow> is_top_space_raw(X) \\<Longrightarrow> card_ge2(carrier(X)) \\<Longrightarrow>\n   open_sets(X) = top_from_basis(ord_basis(X)) \\<Longrightarrow> order_topology(X)\" by auto2\n\nlemma order_topology_open_interval [resolve]:\n  \"order_topology(X) \\<Longrightarrow> a \\<in>. X \\<Longrightarrow> b \\<in>. X \\<Longrightarrow> is_open(X,open_interval(X,a,b))\" by auto2\n    \nlemma order_topology_less_interval [resolve]:\n  \"order_topology(X) \\<Longrightarrow> a \\<in>. X \\<Longrightarrow> is_open(X,less_interval(X,a))\" by auto2\n    \nlemma order_topology_greater_interval [resolve]:\n  \"order_topology(X) \\<Longrightarrow> a \\<in>. X \\<Longrightarrow> is_open(X,greater_interval(X,a))\" by auto2\n    \nlemma order_topology_le_interval [resolve]:\n  \"order_topology(X) \\<Longrightarrow> a \\<in>. X \\<Longrightarrow> is_closed(X,le_interval(X,a))\" by auto2\n      \nlemma order_topology_ge_interval [resolve]:\n  \"order_topology(X) \\<Longrightarrow> a \\<in>. X \\<Longrightarrow> is_closed(X,ge_interval(X,a))\" by auto2\n    \nlemma order_topology_closed_interval [resolve]:\n  \"order_topology(X) \\<Longrightarrow> a \\<in>. X \\<Longrightarrow> b \\<in>. X \\<Longrightarrow> is_closed(X,closed_interval(X,a,b))\"\n@proof\n  @have \"closed_interval(X,a,b) = le_interval(X,b) \\<inter> ge_interval(X,a)\"\n@qed\n\nlemma order_top_is_openI [forward]:\n  \"order_topology(X) \\<Longrightarrow> \\<forall>x\\<in>U. \\<exists>a b. x \\<in> open_interval(X,a,b) \\<and> open_interval(X,a,b) \\<subseteq> U \\<Longrightarrow> is_open(X,U)\" by auto2\n  \nlemma order_top_is_openD_gt [backward2]:\n  \"order_topology(X) \\<Longrightarrow> is_open(X,U) \\<Longrightarrow> a \\<in> U \\<Longrightarrow> \\<exists>M. M >\\<^sub>X a \\<Longrightarrow> \\<exists>c >\\<^sub>X a. closed_open_interval(X,a,c) \\<subseteq> U\"\n@proof\n  @obtain \"W\\<in>ord_basis(X)\" where \"a \\<in> W \\<and> W \\<subseteq> U\"\n  @case \"\\<exists>p\\<in>.X. \\<exists>q\\<in>.X. W = open_interval(X,p,q)\"\n@qed\n\nlemma order_top_is_openD_lt [backward2]:\n  \"order_topology(X) \\<Longrightarrow> is_open(X,U) \\<Longrightarrow> a \\<in> U \\<Longrightarrow> \\<exists>M. M <\\<^sub>X a \\<Longrightarrow> \\<exists>c <\\<^sub>X a. open_closed_interval(X,c,a) \\<subseteq> U\"\n@proof\n  @obtain \"W\\<in>ord_basis(X)\" where \"a \\<in> W \\<and> W \\<subseteq> U\"\n  @case \"\\<exists>p\\<in>.X. \\<exists>q\\<in>.X. W = open_interval(X,p,q)\"\n@qed\n\nlemma order_top_is_openD_unbounded [backward2]:\n  \"order_topology(X) \\<Longrightarrow> order_unbounded(X) \\<Longrightarrow>\n   is_open(X,U) \\<Longrightarrow> x \\<in> U \\<Longrightarrow> \\<exists>a b. x \\<in> open_interval(X,a,b) \\<and> open_interval(X,a,b) \\<subseteq> U\"\n@proof\n  @obtain b where \"b >\\<^sub>X x\" \"closed_open_interval(X,x,b) \\<subseteq> U\"\n  @obtain a where \"a <\\<^sub>X x\" \"open_closed_interval(X,a,x) \\<subseteq> U\"\n  @have \"x \\<in> open_interval(X,a,b)\"\n  @have \"open_interval(X,a,b) = open_closed_interval(X,a,x) \\<union> closed_open_interval(X,x,b)\"\n@qed\n\nsetup {* fold del_prfstep_thm [@{thm order_topology_has_basis}, @{thm order_topology_def}] *}\nsetup {* add_resolve_prfstep @{thm order_topology_has_basis} *}\n  \nsection \\<open>Data structure for order topology\\<close>\n  \ndefinition is_ord_top_raw :: \"i \\<Rightarrow> o\" where [rewrite]:\n  \"is_ord_top_raw(R) \\<longleftrightarrow> is_top_space_raw(R) \\<and> raworder(R)\"\n\nlemma is_ord_top_rawD [forward]:\n  \"is_ord_top_raw(R) \\<Longrightarrow> is_top_space_raw(R)\"\n  \"is_ord_top_raw(R) \\<Longrightarrow> raworder(R)\" by auto2+\nsetup {* del_prfstep_thm_eqforward @{thm is_ord_top_raw_def} *}\n  \ndefinition ord_top_form :: \"i \\<Rightarrow> o\" where [rewrite]:\n  \"ord_top_form(R) \\<longleftrightarrow> is_ord_top_raw(R) \\<and> is_func_graph(R,{carrier_name,open_sets_name,order_graph_name})\"\n  \nlemma ord_top_form_to_raw [forward]: \"ord_top_form(R) \\<Longrightarrow> is_ord_top_raw(R)\" by auto2\n\ndefinition OrderTop :: \"[i, i, i \\<Rightarrow> i \\<Rightarrow> o] \\<Rightarrow> i\" where [rewrite]:\n  \"OrderTop(S,T,r) = Struct({\\<langle>carrier_name,S\\<rangle>, \\<langle>open_sets_name,T\\<rangle>, \\<langle>order_graph_name, rel_graph(S,r)\\<rangle>})\"\n\nlemma OrderTop_is_ord_top_raw [backward]:\n  \"T \\<subseteq> Pow(S) \\<Longrightarrow> R = OrderTop(S,T,r) \\<Longrightarrow> ord_top_form(R)\"\n@proof @have \"raworder(R)\" @qed\n\nlemma OrderTop_eval [rewrite]:\n  \"carrier(OrderTop(S,T,r)) = S\"\n  \"open_sets(OrderTop(S,T,r)) = T\"\n  \"X = OrderTop(S,T,r) \\<Longrightarrow> x \\<in>. X \\<Longrightarrow> y \\<in>. X \\<Longrightarrow> x \\<le>\\<^sub>X y \\<longleftrightarrow> r(x,y)\" by auto2+\n\nlemma ord_top_eq [backward]:\n  \"ord_top_form(X) \\<Longrightarrow> ord_top_form(Y) \\<Longrightarrow> eq_str_order(X,Y) \\<Longrightarrow> eq_str_top(X,Y) \\<Longrightarrow> X = Y\" by auto2\n\nsetup {* fold del_prfstep_thm [@{thm ord_top_form_def}, @{thm OrderTop_def}] *}\n\ndefinition order_top_from_order :: \"i \\<Rightarrow> i\" where [rewrite]:\n  \"order_top_from_order(X) = OrderTop(carrier(X),top_from_basis(ord_basis(X)),\\<lambda>x y. x \\<le>\\<^sub>X y)\"\n  \nlemma order_top_from_order_ord_top_form [forward]:\n  \"raworder(X) \\<Longrightarrow> ord_top_form(order_top_from_order(X))\" by auto2\n\nlemma order_top_from_order_eq_str:\n  \"raworder(X) \\<Longrightarrow> eq_str_order(X,order_top_from_order(X))\" by auto2\nsetup {* add_forward_prfstep_cond @{thm order_top_from_order_eq_str} [with_term \"order_top_from_order(?X)\"] *}\n\nlemma order_top_from_order_is_ord_top [backward]:\n  \"linorder(X) \\<Longrightarrow> card_ge2(carrier(X)) \\<Longrightarrow> order_topology(order_top_from_order(X))\" by auto2\nsetup {* add_prfstep_check_req (\"order_top_from_order(X)\", \"order_topology(order_top_from_order(X))\") *}\n\nsection \\<open>Defining topology on an ordered ring\\<close>\n\ndefinition OrdRingTop :: \"[i, i, i \\<Rightarrow> i \\<Rightarrow> i, i, i \\<Rightarrow> i \\<Rightarrow> i, i \\<Rightarrow> i \\<Rightarrow> o, i] \\<Rightarrow> i\" where [rewrite]:\n  \"OrdRingTop(S,z,f,u,g,r,T) = Struct({\\<langle>carrier_name,S\\<rangle>, \\<langle>open_sets_name,T\\<rangle>,\n      \\<langle>order_graph_name, rel_graph(S,r)\\<rangle>,\n      \\<langle>zero_name, z\\<rangle>, \\<langle>plus_fun_name, binary_fun_of(S,f)\\<rangle>,\n      \\<langle>one_name, u\\<rangle>, \\<langle>times_fun_name, binary_fun_of(S,g)\\<rangle>})\"\n\nlemma OrdRingTop_is_ord_ring_raw [backward]:\n  \"z \\<in> S \\<Longrightarrow> binary_fun(S,f) \\<Longrightarrow> u \\<in> S \\<Longrightarrow> binary_fun(S,g) \\<Longrightarrow>\n   R = OrdRingTop(S,z,f,u,g,r,T) \\<Longrightarrow> is_ord_ring_raw(R)\"\n@proof\n  @have \"is_abgroup_raw(R)\"\n  @have \"is_group_raw(R)\"\n  @have \"is_ring_raw(R)\"  \n  @have \"raworder(R)\"\n@qed\n    \nlemma ord_top_ring_eval [rewrite]:\n  \"carrier(OrdRingTop(S,z,f,u,g,r,T)) = S\"\n  \"zero(OrdRingTop(S,z,f,u,g,r,T)) = z\"\n  \"one(OrdRingTop(S,z,f,u,g,r,T)) = u\"\n  \"open_sets(OrdRingTop(S,z,f,u,g,r,T)) = T\"\n  \"R = OrdRingTop(S,z,f,u,g,r,T) \\<Longrightarrow> x \\<in>. R \\<Longrightarrow> y \\<in>. R \\<Longrightarrow> is_abgroup_raw(R) \\<Longrightarrow> x +\\<^sub>R y = f(x,y)\"\n  \"R = OrdRingTop(S,z,f,u,g,r,T) \\<Longrightarrow> x \\<in>. R \\<Longrightarrow> y \\<in>. R \\<Longrightarrow> is_group_raw(R) \\<Longrightarrow> x *\\<^sub>R y = g(x,y)\"\n  \"R = OrdRingTop(S,z,f,u,g,r,T) \\<Longrightarrow> x \\<in>. R \\<Longrightarrow> y \\<in>. R \\<Longrightarrow> x \\<le>\\<^sub>R y \\<longleftrightarrow> r(x,y)\" by auto2+\nsetup {* del_prfstep_thm @{thm OrdRingTop_def} *}\n\nsection \\<open>Order topology from an ordered ring\\<close>\n  \ndefinition ord_ring_top_from_ord_ring :: \"i \\<Rightarrow> i\" where [rewrite]:\n  \"ord_ring_top_from_ord_ring(R) =\n    OrdRingTop(carrier(R), \\<zero>\\<^sub>R, \\<lambda>x y. x +\\<^sub>R y, \\<one>\\<^sub>R, \\<lambda>x y. x *\\<^sub>R y, \\<lambda>x y. x \\<le>\\<^sub>R y, top_from_basis(ord_basis(R)))\"\n\nlemma ord_ring_top_from_ord_ring_is_ord_ring [forward]:\n  \"is_ord_ring_raw(R) \\<Longrightarrow> is_ord_ring_raw(ord_ring_top_from_ord_ring(R))\" by auto2\n\nlemma ord_ring_top_from_ord_ring_eq_str:\n  \"is_ord_ring_raw(R) \\<Longrightarrow> A = ord_ring_top_from_ord_ring(R) \\<Longrightarrow> eq_str_ord_ring(R,A)\" by auto2\nsetup {* add_forward_prfstep_cond @{thm ord_ring_top_from_ord_ring_eq_str} [with_term \"?A\"] *}\n\nlemma ord_ring_top_from_ord_ring_is_top_space_raw [forward]:\n  \"is_ord_ring_raw(R) \\<Longrightarrow> linorder(R) \\<Longrightarrow> is_ord_top_raw(ord_ring_top_from_ord_ring(R))\" by auto2\n\nlemma ord_ring_top_from_ord_ring_is_ord_top [backward]:\n  \"is_ord_ring_raw(R) \\<Longrightarrow> linorder(R) \\<Longrightarrow> card_ge2(carrier(R)) \\<Longrightarrow>\n   order_topology(ord_ring_top_from_ord_ring(R))\" by auto2\n\nsection \\<open>Subspace on order topology\\<close>\n  \ndefinition order_convex :: \"i \\<Rightarrow> i \\<Rightarrow> o\" where [rewrite]:\n  \"order_convex(X,A) \\<longleftrightarrow> (A \\<subseteq> carrier(X) \\<and> (\\<forall>a\\<in>A. \\<forall>b\\<in>A. closed_interval(X,a,b) \\<subseteq> A))\"\n  \nlemma order_convexD1 [forward]: \"order_convex(X,A) \\<Longrightarrow> A \\<subseteq> carrier(X)\" by auto2\n\nlemma order_convexD2a [backward2]:\n  \"order_convex(X,A) \\<Longrightarrow> a \\<in> A \\<Longrightarrow> b \\<in> A \\<Longrightarrow> closed_interval(X,a,b) \\<subseteq> A\" by auto2\n    \nlemma order_convexD2b [backward2]:\n  \"linorder(X) \\<Longrightarrow> order_convex(X,A) \\<Longrightarrow> a \\<in> A \\<Longrightarrow> b \\<in> A \\<Longrightarrow> open_interval(X,a,b) \\<subseteq> A\"\n@proof @have \"closed_interval(X,a,b) \\<subseteq> A\" @qed\nsetup {* del_prfstep_thm_eqforward @{thm order_convex_def} *}\n  \nlemma closed_interval_convex [resolve]:\n  \"linorder(X) \\<Longrightarrow> order_convex(X,closed_interval(X,a,b))\" by auto2\n\ndefinition ord_subspace :: \"i \\<Rightarrow> i \\<Rightarrow> i\" where [rewrite]:\n  \"ord_subspace(X,A) = OrderTop(A, {A \\<inter> U. U \\<in> open_sets(X)}, \\<lambda>x y. x \\<le>\\<^sub>X y)\"\n\nlemma ord_subspace_ord_top_form [forward]: \"ord_top_form(ord_subspace(X,A))\" by auto2\nlemma ord_subspace_carrier: \"carrier(ord_subspace(X,A)) = A\" by auto2\nsetup {* add_forward_prfstep_cond @{thm ord_subspace_carrier} [with_term \"ord_subspace(?X,?A)\"] *}\n\nlemma ord_subspace_eq_str [resolve]:\n  \"is_top_space(X) \\<Longrightarrow> A \\<subseteq> carrier(X) \\<Longrightarrow> eq_str_top(subspace(X,A),ord_subspace(X,A))\"\n@proof @have \"open_sets(subspace(X,A)) = open_sets(ord_subspace(X,A))\" @qed\n  \nlemma ord_subspace_is_top_space:\n  \"is_top_space(X) \\<Longrightarrow> A \\<subseteq> carrier(X) \\<Longrightarrow> is_top_space(ord_subspace(X,A))\"\n@proof @have \"eq_str_top(subspace(X,A),ord_subspace(X,A))\" @qed\nsetup {* add_forward_prfstep_cond @{thm ord_subspace_is_top_space} [with_term \"ord_subspace(?X,?A)\"] *}\n\nlemma order_top_from_order_finer1 [resolve]:\n  \"order_topology(X) \\<Longrightarrow> card_ge2(A) \\<Longrightarrow> order_convex(X,A) \\<Longrightarrow>\n   Y = order_top_from_order(suborder(X,A)) \\<Longrightarrow> is_open(Y, A \\<inter> less_interval(X,x))\"\n@proof\n  @case \"x \\<in> A\" @with @have \"A \\<inter> less_interval(X,x) = less_interval(suborder(X,A),x)\" @end\n  @have (@rule) \"A \\<inter> less_interval(X,x) = \\<emptyset> \\<or> A \\<subseteq> less_interval(X,x)\" @with\n    @contradiction\n    @obtain \"b \\<in> A\" where \"b \\<in> less_interval(X,x)\"\n    @obtain \"c \\<in> A\" where \"c \\<notin> less_interval(X,x)\"\n    @have \"closed_interval(X,b,c) \\<subseteq> A\"\n    @have \"x \\<in> closed_interval(X,b,c)\" @end\n@qed\n\nlemma order_top_from_order_finer2 [resolve]:\n  \"order_topology(X) \\<Longrightarrow> card_ge2(A) \\<Longrightarrow> order_convex(X,A) \\<Longrightarrow>\n   Y = order_top_from_order(suborder(X,A)) \\<Longrightarrow> is_open(Y, A \\<inter> greater_interval(X,x))\"\n@proof\n  @case \"x \\<in> A\" @with @have \"A \\<inter> greater_interval(X,x) = greater_interval(suborder(X,A),x)\" @end\n  @have (@rule) \"A \\<inter> greater_interval(X,x) = \\<emptyset> \\<or> A \\<subseteq> greater_interval(X,x)\" @with\n    @contradiction\n    @obtain \"b \\<in> A\" where \"b \\<in> greater_interval(X,x)\"\n    @obtain \"c \\<in> A\" where \"c \\<notin> greater_interval(X,x)\"\n    @have \"closed_interval(X,c,b) \\<subseteq> A\"\n    @have \"x \\<in> closed_interval(X,c,b)\" @end\n@qed\n\nlemma order_top_from_order_finer3 [resolve]:\n  \"order_topology(X) \\<Longrightarrow> card_ge2(A) \\<Longrightarrow> order_convex(X,A) \\<Longrightarrow>\n   Y = order_top_from_order(suborder(X,A)) \\<Longrightarrow> is_open(Y, A \\<inter> open_interval(X,x,y))\"\n@proof\n  @have \"open_interval(X,x,y) = less_interval(X,y) \\<inter> greater_interval(X,x)\"\n  @have \"A \\<inter> open_interval(X,x,y) = (A \\<inter> less_interval(X,y)) \\<inter> (A \\<inter> greater_interval(X,x))\"\n  @have \"is_open(Y, A \\<inter> less_interval(X,y))\"\n@qed\n\nlemma order_top_from_order_eq_sub [backward]:\n  \"order_topology(X) \\<Longrightarrow> card_ge2(A) \\<Longrightarrow> order_convex(X,A) \\<Longrightarrow>\n   eq_str_top(ord_subspace(X,A),order_top_from_order(suborder(X,A)))\"\n@proof\n  @let \"Y = order_top_from_order(suborder(X,A))\"\n  @let \"Z = ord_subspace(X,A)\"\n  @have \"top_space_finer(Z,Y)\"\n  @let \"\\<B> = {A \\<inter> U. U \\<in> ord_basis(X)}\"\n  @have \"top_has_basis(Z,\\<B>)\" @with @have \"eq_str_top(subspace(X,A),Z)\" @end\n  @have \"top_space_finer(Y,Z)\" @with @have \"\\<forall>U\\<in>\\<B>. is_open(Y,U)\" @end\n@qed\n\nlemma ord_subspace_is_order_top:\n  \"order_topology(X) \\<Longrightarrow> card_ge2(A) \\<Longrightarrow> order_convex(X,A) \\<Longrightarrow> order_topology(ord_subspace(X,A))\"\n@proof @have \"ord_subspace(X,A) = order_top_from_order(suborder(X,A))\"@qed\nsetup {* add_forward_prfstep_cond @{thm ord_subspace_is_order_top} [with_term \"ord_subspace(?X,?A)\"] *}\n\nlemma closed_interval_order_topology:\n  \"order_topology(X) \\<Longrightarrow> a <\\<^sub>X b \\<Longrightarrow> I = closed_interval(X,a,b) \\<Longrightarrow> order_topology(ord_subspace(X,I))\"\n@proof\n  @have \"card_ge2(I)\" @with @have \"{a,b} \\<subseteq> I\" @end\n  @have \"order_convex(X,I)\"\n@qed\nsetup {* add_forward_prfstep_cond @{thm closed_interval_order_topology} [with_term \"ord_subspace(?X,?I)\"] *}\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/OrderTopology.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767810736693, "lm_q2_score": 0.8198933359135361, "lm_q1q2_score": 0.7194373652211623}}
{"text": "section \\<open>Monotone Formulas\\<close>\n\ntext \\<open>We define monotone formulas, i.e., without negation, \n  and show that usually the constant TRUE is not required.\\<close>\n\ntheory Monotone_Formula\n  imports Main\nbegin\n\nsubsection \\<open>Definition\\<close>\n\ndatatype 'a mformula =\n  TRUE | FALSE |            \\<comment> \\<open>True and False\\<close>\n  Var 'a |                  \\<comment> \\<open>propositional variables\\<close>\n  Conj \"'a mformula\" \"'a mformula\" |  \\<comment> \\<open>conjunction\\<close>\n  Disj \"'a mformula\" \"'a mformula\"    \\<comment> \\<open>disjunction\\<close>\n\ntext \\<open>the set of subformulas of a mformula\\<close>\n\nfun SUB :: \"'a mformula \\<Rightarrow> 'a mformula set\" where\n  \"SUB (Conj \\<phi> \\<psi>) = {Conj \\<phi> \\<psi>} \\<union> SUB \\<phi> \\<union> SUB \\<psi>\" \n| \"SUB (Disj \\<phi> \\<psi>) = {Disj \\<phi> \\<psi>} \\<union> SUB \\<phi> \\<union> SUB \\<psi>\" \n| \"SUB (Var x) = {Var x}\" \n| \"SUB FALSE = {FALSE}\" \n| \"SUB TRUE = {TRUE}\" \n\ntext \\<open>the variables of a mformula\\<close>\n\nfun vars :: \"'a mformula \\<Rightarrow> 'a set\" where\n  \"vars (Var x) = {x}\" \n| \"vars (Conj \\<phi> \\<psi>) = vars \\<phi> \\<union> vars \\<psi>\" \n| \"vars (Disj \\<phi> \\<psi>) = vars \\<phi> \\<union> vars \\<psi>\" \n| \"vars FALSE = {}\" \n| \"vars TRUE = {}\" \n\nlemma finite_SUB[simp, intro]: \"finite (SUB \\<phi>)\" \n  by (induct \\<phi>, auto)\n\ntext \\<open>The circuit-size of a mformula: number of subformulas\\<close>\n\ndefinition cs :: \"'a mformula \\<Rightarrow> nat\" where \n  \"cs \\<phi> = card (SUB \\<phi>)\" \n\ntext \\<open>variable assignments\\<close>\n\ntype_synonym 'a VAS = \"'a \\<Rightarrow> bool\" \n\ntext \\<open>evaluation of mformulas\\<close>\n\nfun eval :: \"'a VAS \\<Rightarrow> 'a mformula \\<Rightarrow> bool\" where\n  \"eval \\<theta> FALSE = False\" \n| \"eval \\<theta> TRUE = True\" \n| \"eval \\<theta> (Var x) = \\<theta> x\" \n| \"eval \\<theta> (Disj \\<phi> \\<psi>) = (eval \\<theta> \\<phi> \\<or> eval \\<theta> \\<psi>)\" \n| \"eval \\<theta> (Conj \\<phi> \\<psi>) = (eval \\<theta> \\<phi> \\<and> eval \\<theta> \\<psi>)\" \n\nlemma eval_vars: assumes \"\\<And> x. x \\<in> vars \\<phi> \\<Longrightarrow> \\<theta>1 x = \\<theta>2 x\" \n  shows \"eval \\<theta>1 \\<phi> = eval \\<theta>2 \\<phi>\" \n  using assms by (induct \\<phi>, auto)\n\nsubsection \\<open>Conversion of mformulas to true-free mformulas\\<close>\n\ninductive_set tf_mformula :: \"'a mformula set\" where\n  tf_False: \"FALSE \\<in> tf_mformula\" \n| tf_Var: \"Var x \\<in> tf_mformula\" \n| tf_Disj: \"\\<phi> \\<in> tf_mformula \\<Longrightarrow> \\<psi> \\<in> tf_mformula \\<Longrightarrow> Disj \\<phi> \\<psi> \\<in> tf_mformula\" \n| tf_Conj: \"\\<phi> \\<in> tf_mformula \\<Longrightarrow> \\<psi> \\<in> tf_mformula \\<Longrightarrow> Conj \\<phi> \\<psi> \\<in> tf_mformula\" \n\nfun to_tf_formula where\n  \"to_tf_formula (Disj phi psi) = (let phi' = to_tf_formula phi; psi' = to_tf_formula psi\n    in (if phi' = TRUE \\<or> psi' = TRUE then TRUE else Disj phi' psi'))\" \n| \"to_tf_formula (Conj phi psi) = (let phi' = to_tf_formula phi; psi' = to_tf_formula psi\n    in (if phi' = TRUE then psi' else if psi' = TRUE then phi' else Conj phi' psi'))\" \n| \"to_tf_formula phi = phi\" \n\nlemma eval_to_tf_formula: \"eval \\<theta> (to_tf_formula \\<phi>) = eval \\<theta> \\<phi>\" \n  by (induct \\<phi> rule: to_tf_formula.induct, auto simp: Let_def)\n\nlemma to_tf_formula: \"to_tf_formula \\<phi> \\<noteq> TRUE \\<Longrightarrow> to_tf_formula \\<phi> \\<in> tf_mformula\" \n  by (induct \\<phi>, auto simp: Let_def intro: tf_mformula.intros)\n\nlemma vars_to_tf_formula: \"vars (to_tf_formula \\<phi>) \\<subseteq> vars \\<phi>\" \n  by (induct \\<phi> rule: to_tf_formula.induct, auto simp: Let_def)\n\nlemma SUB_to_tf_formula: \"SUB (to_tf_formula \\<phi>) \\<subseteq> to_tf_formula ` SUB \\<phi>\" \n  by (induct \\<phi> rule: to_tf_formula.induct, auto simp: Let_def)\n\nlemma cs_to_tf_formula: \"cs (to_tf_formula \\<phi>) \\<le> cs \\<phi>\" \nproof -\n  have \"cs (to_tf_formula \\<phi>) \\<le> card (to_tf_formula ` SUB \\<phi>)\" \n    unfolding cs_def by (rule card_mono[OF finite_imageI[OF finite_SUB] SUB_to_tf_formula])\n  also have \"\\<dots> \\<le> cs \\<phi>\" unfolding cs_def\n    by (rule card_image_le[OF finite_SUB])\n  finally show \"cs (to_tf_formula \\<phi>) \\<le> cs \\<phi>\" .\nqed\n\nlemma to_tf_mformula: assumes \"\\<not> eval \\<theta> \\<phi>\"\n  shows \"\\<exists> \\<psi> \\<in> tf_mformula. (\\<forall> \\<theta>. eval \\<theta> \\<phi> = eval \\<theta> \\<psi>) \\<and> vars \\<psi> \\<subseteq> vars \\<phi> \\<and> cs \\<psi> \\<le> cs \\<phi>\" \nproof (intro bexI[of _ \"to_tf_formula \\<phi>\"] conjI allI eval_to_tf_formula[symmetric] vars_to_tf_formula to_tf_formula)\n  from assms have \"\\<not> eval \\<theta> (to_tf_formula \\<phi>)\" by (simp add: eval_to_tf_formula)\n  thus \"to_tf_formula \\<phi> \\<noteq> TRUE\" by auto\n  show \"cs (to_tf_formula \\<phi>) \\<le> cs \\<phi>\" by (rule cs_to_tf_formula)\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/Clique_and_Monotone_Circuits/Monotone_Formula.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8774767746654976, "lm_q2_score": 0.8198933337131076, "lm_q1q2_score": 0.7194373580363201}}
{"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_times\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\nfun times :: \"Bin => Bin => Bin\" where\n\"times (One) y = y\"\n| \"times (ZeroAnd xs1) y = ZeroAnd (times xs1 y)\"\n| \"times (OneAnd xs12) y = plus (ZeroAnd (times xs12 y)) y\"\n\ntheorem property0 :\n  \"((toNat (times 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_times.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942377652496, "lm_q2_score": 0.8080672066194945, "lm_q1q2_score": 0.7194175777803973}}
{"text": "theory Short_Theory\n  imports Main\nbegin\n\n(* syntax  *)\ntype_synonym vname = string\ndatatype aexp = N int | V vname | Plus aexp aexp\n\n(* semantics  *)\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\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 asimp_const_corr[simp]: \"aval (asimp_const a) s = aval a s\"\n  apply(induction a)\n  apply(auto split: aexp.split)\n  done\n\n(* local optimization *)\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[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\n(* term traversing *)\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 asimp_correctness[simp]: \"aval (asimp a) s = aval a s\"\n  apply(induction a)\n  apply(auto simp add: aval_plus)\n  done\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/Short_Theory.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942232112239, "lm_q2_score": 0.8080672135527632, "lm_q1q2_score": 0.7194175721924155}}
{"text": "\ntheory BDT_ext\n  imports\n    \"HOL-Library.Tree\"\nbegin\n\nsection\\<open>BDT\\<close>\n\ninductive_set bdt :: \"(nat set \\<times> nat tree) set\"\n  where \"({}, Leaf) \\<in> bdt\"\n  | \"({x}, (Node Leaf x Leaf)) \\<in> bdt\"\n  | \"(A, L) \\<in> bdt \\<and> (A, R) \\<in> bdt \\<Longrightarrow> (insert x A, (Node L x R)) \\<in> bdt\"\n\nlemma \"({}, Leaf) \\<in> bdt\" using bdt.intros (1) .\n\ninductive_set bdt_s :: \"(nat set \\<times> nat tree) set\"\n  where \"({}, Leaf) \\<in> bdt_s\"\n  | \"(A, L) \\<in> bdt \\<and> (A, R) \\<in> bdt \\<Longrightarrow> (insert x A, (Node L x R)) \\<in> bdt_s\"\n\nlemma \"bdt = bdt_s\"\nproof\n  show \"bdt \\<subseteq> bdt_s\"\n  proof (auto simp add:  bdt.intros)\n    fix a b\n    assume bdt: \"(a, b) \\<in> bdt\"\n    then show \"(a, b) \\<in> bdt_s\" \n    proof (cases \"a = {}\")\n      case True\n      then show ?thesis using bdt bdt.cases bdt_s.simps by auto\n    next\n      case False\n      then show ?thesis\n        by (smt (verit, best) bdt bdt.cases bdt.intros(1) bdt_s.intros(2))\n    qed\n  qed\n  show \"bdt_s \\<subseteq> bdt\"\n  proof (auto simp add:  bdt.intros)\n    fix a b\n    assume bdt: \"(a, b) \\<in> bdt_s\"\n    then show \"(a, b) \\<in> bdt\" \n    proof (cases \"a = {}\")\n      case True\n      then show ?thesis by (metis bdt bdt.simps bdt_s.simps)\n    next\n      case False\n      then show ?thesis\n        by (smt (verit, ccfv_threshold) bdt bdt.simps bdt_s.cases)\n    qed\n  qed\nqed\n\nsection\\<open>Ordered Binary Decision trees -- OBDT --\\<close>\n\ntext\\<open>We represent sorted sets of variables by means of a given list\n  that contains the same elements as the set.\\<close>\n\ninductive_set sorted_variables :: \"(nat set \\<times> nat list) set\"\n  where \"({}, []) \\<in> sorted_variables\"\n  | \"(A, l) \\<in> sorted_variables \\<Longrightarrow> x \\<notin> A \\<Longrightarrow> (insert x A, Cons x l) \\<in> sorted_variables\"\n\nlemma \"({1}, [1]) \\<in> sorted_variables\"\n  by (simp add: sorted_variables.intros(1) sorted_variables.intros(2))\n\nlemma \"({1}, [1,1]) \\<notin> sorted_variables\"\n  by (metis (no_types, lifting) insert_absorb insert_eq_iff insert_not_empty not_Cons_self2 sorted_variables.cases)\n\nlemma \"({1,2,3},[3,2,1]) \\<in> sorted_variables\"\n  using sorted_variables.intros (1)\n  using sorted_variables.intros (2) [of \"{}\" \"[]\" \"1\"]\n  using sorted_variables.intros (2) [of \"{1}\" \"[1]\" \"2\"]\n  using sorted_variables.intros (2) [of \"{1,2}\" \"[2,1]\" \"3\"]\n  by (simp add: insert_commute sorted_variables.intros(2))\n\nlemma\n  sorted_variables_length_coherent:\n  assumes al: \"(A, l) \\<in> sorted_variables\"\n  shows \"card A = length l\"\nusing al proof (induct)\n  case 1\n  then show ?case by simp\nnext\n  case (2 A l x)\n  then show ?case\n    by (metis card_Suc_eq length_0_conv length_Cons neq_Nil_conv sorted_variables.simps)\nqed\n\nlemma sorted_variables_coherent:\n  assumes al: \"(A, l) \\<in> sorted_variables\"\n  shows \"A = set l\" using al by (induct, simp_all)\n\nsection\\<open>Powerset\\<close>\n\ntext\\<open>We use the term ``powerset'' just as a synonym of @{term Pow}.\\<close>\n\ndefinition powerset :: \"nat set \\<Rightarrow> nat set set\"\n  where \"powerset A = Pow A\"\n\nlemma \"powerset {} = {{}}\" unfolding powerset_def by simp\n\nlemma powerset_singleton: \"powerset {x} = {{},{x}}\" unfolding powerset_def by auto\n\nlemma\n  powerset_singleton_cases:\n  assumes K: \"K \\<subseteq> powerset {x}\"\n  shows \"K = {} \\<or> K = {{}} \\<or> K = {{x}} \\<or> K = {{},{x}}\" \n  using K\n  by (smt (verit, del_insts) powerset_singleton insert_Diff subset_insert_iff subset_singletonD)\n\nsection\\<open>Simplicial complexes\\<close>\n\ntext\\<open>In the following we introduce a definition \n  of simplicial complexes as a set of sets that\n  satisfies the property of being closed by the \n  subset relation. It is worth noting that in the\n  rest of the development we will mainly work with\n  hypergraphs, or sets of sets without the property \n  of being closed by the subset relation, \n  and simplicial complexes will not be required.\\<close>\n\ndefinition pow_closed :: \"'a set set \\<Rightarrow> bool\"\n  where \"pow_closed S \\<equiv> (\\<forall>s\\<in>S. \\<forall>s'\\<subseteq>s. s'\\<in> S)\"\n\nvalue \"pow_closed {{True, False},{True},{False},{}}\"\n\nlemma\n  assumes \"pow_closed S\" and \"s \\<in> S\" and \"s' \\<subseteq> s\"\n  shows \"s' \\<in> S\"\n  using assms(1,2,3) pow_closed_def by blast\n\ninductive_set cc_s :: \"(nat set \\<times> nat set set) set\"\n  where \"({}, {}) \\<in> cc_s\"\n  | \"(A, {}) \\<in> cc_s\"\n  | \"A \\<noteq> {} \\<Longrightarrow> K \\<subseteq> powerset A \\<Longrightarrow> pow_closed K \\<Longrightarrow> (A, K) \\<in> cc_s\"\n\nlemma cc_s_simplices:\n  assumes cc_s: \"(V, K) \\<in> cc_s\" and x: \"x \\<in> K\"\n  shows \"x \\<in> powerset V\"\nproof (cases \"V = {}\")\n  case True hence k: \"K = {}\" using cc_s\n    by (simp add: cc_s.simps)\n  show ?thesis unfolding True powerset_def using x k\n    by simp\nnext\n  case False note V = False\n  show ?thesis\n  proof (cases \"K = {}\")\n    case True\n    then show ?thesis using V x by simp\n  next\n    case False\n    then show ?thesis \n      using V False  \n      using cc_s.simps [of V K]\n      unfolding powerset_def pow_closed_def\n      using cc_s x by blast\n  qed\nqed\n\ncorollary cc_s_subset:\n  assumes cc_s: \"(V, K) \\<in> cc_s\"\n  shows \"K \\<subseteq> powerset V\" using cc_s_simplices [OF cc_s] by auto\n\ncorollary cc_s_finite_simplices:\n  assumes cc_s: \"(V, K) \\<in> cc_s\" \n    and x: \"x \\<in> K\" and f: \"finite V\"\n  shows \"finite x\"\n  using cc_s_simplices [OF cc_s x] \n  unfolding powerset_def using f using finite_subset [of x V] by auto\n\nlemma\n  cc_s_closed:\n  assumes \"s \\<subseteq> s'\" and \"(A, K) \\<in> cc_s\" and \"s' \\<in> K\"\n  shows \"s \\<in> K\"\nproof (cases \"A = {}\")\n  case True show ?thesis\n    using True assms(2) assms(3) cc_s.simps by force\nnext\n  case False note A = False\n  show ?thesis\n  proof (cases \"K = {}\")\n    case True\n    then show ?thesis using assms by blast\n  next\n    case False\n    from cc_s.simps [of A K]\n    have \"pow_closed K\" using False A\n      using assms(2) by presburger\n    then show ?thesis using assms (1,3) unfolding pow_closed_def by auto\n  qed\nqed\n\nlemma \"({0}, {}) \\<in> cc_s\" \n  by (rule cc_s.intros(2))\n\nlemma \"({0,1,2}, {}) \\<in> cc_s\" \n  by (rule cc_s.intros(2))\n\nlemma \"({0,1,2}, {{1},{}}) \\<in> cc_s\" \n  by (rule cc_s.intros(3) [of \"{0,1,2}\" \"{{1},{}}\"], \n      simp, unfold powerset_def, auto,\n      unfold pow_closed_def, auto)\n\nlemma \"({0,1,2}, {{1},{2},{}}) \\<in> cc_s\"\n  by (rule cc_s.intros(3) [of \"{0,1,2}\" \"{{1},{2},{}}\"], \n      simp, unfold powerset_def, auto,\n      unfold pow_closed_def, auto)\n\nlemma \"({0,1,2}, {{1,2},{1},{2},{}}) \\<in> cc_s\"\n  by (rule cc_s.intros(3) [of \"{0,1,2}\" \"{{1,2},{1},{2},{}}\"], \n      simp, unfold powerset_def, auto,\n      unfold pow_closed_def, auto)\n\nsection\\<open>Link and exterior link of a vertex in a set of sets\\<close>\n\ndefinition link_ext :: \"nat \\<Rightarrow> nat set \\<Rightarrow> nat set set \\<Rightarrow> nat set set\"\n  where \"link_ext x V K = {s. s \\<in> powerset V \\<and> x \\<notin> s \\<and> insert x s \\<in> K}\"\n\nlemma link_ext_empty [simp]: \"link_ext x V {} = {}\"\n  by (simp add: link_ext_def)\n\nlemma link_ext_mono:\n  assumes \"K \\<subseteq> L\"\n  shows \"link_ext x V K \\<subseteq> link_ext x V L\"\n  using assms unfolding link_ext_def powerset_def by auto\n\nlemma link_ext_cc:\n  assumes v: \"(V, K) \\<in> cc_s\"\n  shows \"(V, {s. insert x s \\<in> K}) \\<in> cc_s\"\nproof (cases \"x \\<in> V\")\n  case False\n  have \"{s. insert x s \\<in> K} = {}\" \n  proof (rule cc_s.cases [OF v])\n    assume \"V = {}\" and \"K = {}\"\n    thus \"{s. insert x s \\<in> K} = {}\" by simp\n  next\n    fix A assume \"V = A\" and \"K = {}\"\n    thus \"{s. insert x s \\<in> K} = {}\" by simp\n  next\n    fix A L\n    assume v: \"V = A\" and k: \"K = L\" and \"A \\<noteq> {}\" and l: \"L \\<subseteq> powerset A\"\n      and \"pow_closed L\" \n    show \"{s. insert x s \\<in> K} = {}\" \n      using False v k l unfolding powerset_def by auto\n  qed\n  thus ?thesis using cc_s.intros (1,2) by simp\nnext\n  case True\n  show ?thesis\n  proof (rule cc_s.intros (3))\n    show \"V \\<noteq> {}\" using True by fast\n    show \"{s. insert x s \\<in> K} \\<subseteq> powerset V\" \n      using v True cc_s.intros (3) [of V K]\n      using cc_s_simplices powerset_def by auto\n    show \"pow_closed {s. insert x s \\<in> K}\"\n    proof -  \n      have \"pow_closed K\" \n        using v True cc_s.intros (3) [of V K]\n        by (simp add: cc_s_closed pow_closed_def)\n      thus ?thesis unfolding pow_closed_def\n        by auto (meson insert_mono)\n    qed\n  qed\nqed\n\ncorollary link_ext_cc_s:\n  assumes v: \"(V, K) \\<in> cc_s\"\n  shows \"(V, link_ext x V K) \\<in> cc_s\"\nproof (cases \"V = {}\")\n  case True\n  show ?thesis using v unfolding True link_ext_def powerset_def\n    by (simp add: cc_s.simps)\nnext\n  case False note vne = False\n  show ?thesis\n  proof (cases \"x \\<in> V\")\n    case False\n    show ?thesis \n      using False cc_s_subset [OF v] \n      unfolding link_ext_def powerset_def\n      using cc_s.simps by auto\n  next\n    case True\n    show ?thesis unfolding link_ext_def\n    proof (rule cc_s.intros (3))\n      show \"V \\<noteq> {}\" using True by fast\n      show \"{s \\<in> powerset V. x \\<notin> s \\<and> insert x s \\<in> K} \\<subseteq> powerset V\"\n        using True unfolding powerset_def by auto\n      from v have pcK: \"pow_closed K\" \n        using cc_s.simps True\n        by (meson cc_s_closed pow_closed_def)\n      show \"pow_closed {s \\<in> powerset V. x \\<notin> s \\<and> insert x s \\<in> K}\"\n        using pcK\n        unfolding pow_closed_def powerset_def\n        by auto (meson insert_mono)\n    qed\n  qed\nqed\n\nlemma link_ext_commute:\n  assumes x: \"x \\<in> V\" and y: \"y \\<in> V\" \n  shows \"link_ext y (V - {x}) (link_ext x V K) = \n        link_ext x (V - {y}) (link_ext y V K)\"\n  using x y unfolding link_ext_def powerset_def \n  by auto (simp add: insert_commute)+\n\ndefinition link :: \"nat \\<Rightarrow> nat set \\<Rightarrow> nat set set \\<Rightarrow> nat set set\"\n  where \"link x V K = {s. s \\<in> powerset (V - {x}) \\<and> s \\<in> K \\<and> insert x s \\<in> K}\"\n\nlemma link_intro [intro]: \n  \"y \\<in> powerset (V - {x}) \\<Longrightarrow> y \\<in> K \\<Longrightarrow> insert x y \\<in> K \\<Longrightarrow> y \\<in> link x V K\"\n  using link_def by simp\n\nlemma link_mono:\n  assumes \"K \\<subseteq> L\"\n  shows \"link x V K \\<subseteq> link x V L\"\n  using assms unfolding link_def powerset_def by auto\n\nlemma link_commute:\n  assumes x: \"x \\<in> V\" and y: \"y \\<in> V\" \n  shows \"link y (V - {x}) (link x V K) = link x (V - {y}) (link y V K)\"\n  using x y unfolding link_def powerset_def \n  by auto (simp add: insert_commute)+\n\nlemma link_subset_link_ext:\n  \"link x V K \\<subseteq> link_ext x V K\"\n  unfolding link_def link_ext_def powerset_def by auto\n\nlemma cc_s_link_eq_link_ext:\n  assumes cc: \"(V, K) \\<in> cc_s\" \n  shows \"link x V K = link_ext x V K\"\nproof\n  show \"link x V K \\<subseteq> link_ext x V K\" using link_subset_link_ext .\n  show \"link_ext x V K \\<subseteq> link x V K\"\n  proof\n    fix y assume y: \"y \\<in> link_ext x V K\"\n    from y have y: \"y \\<in> powerset (V - {x})\" and yu: \"insert x y \\<in> K\"\n      unfolding link_ext_def powerset_def by auto\n    show \"y \\<in> link x V K\"\n    proof (intro link_intro)\n      show \"y \\<in> powerset (V - {x})\" using y .\n      show \"insert x y \\<in> K\" using yu .\n      show \"y \\<in> K\" \n      proof (rule cc_s_closed [of _ \"insert x y\" V])\n        show \"y \\<subseteq> insert x y\" by auto\n        show \"(V, K) \\<in> cc_s\" by (rule assms (1))\n        show \"insert x y \\<in> K\" using yu .\n      qed\n    qed\n  qed\nqed\n\nlemma link_cc:\n  assumes v: \"(V,K) \\<in> cc_s\" and x: \"x \\<in> V\"\n  shows \"(V, {s. x \\<notin> s \\<and> s \\<in> K \\<and> insert x s \\<in> K}) \\<in> cc_s\"\nproof (cases \"V = {}\")\n  case True then have False using x by fast\n  thus ?thesis by fast\nnext\n  case False\n  show ?thesis\n  proof (rule cc_s.intros (3))\n    show \"V \\<noteq> {}\" using False by fast\n    have \"K \\<subseteq> powerset V\" using cc_s_subset [OF v] .\n    thus \"{s. x \\<notin> s \\<and> s \\<in> K \\<and> insert x s \\<in> K} \\<subseteq> powerset V\" by auto\n    have \"pow_closed K\" using v\n      by (simp add: cc_s_closed pow_closed_def)\n    then show \"pow_closed {s. x \\<notin> s \\<and> s \\<in> K \\<and> insert x s \\<in> K}\"\n      unfolding pow_closed_def by auto (meson insert_mono)\n  qed\nqed\n\ncorollary link_cc_s:\n  assumes v: \"(V, K) \\<in> cc_s\"\n  shows \"(V, link x V K) \\<in> cc_s\" \n  using link_ext_cc_s [OF v, of x] \n  unfolding cc_s_link_eq_link_ext [OF v, symmetric] .\n\nsection\\<open>A different characterization of simplicial complexes\\<close>\n\ndefinition closed_remove_element :: \"nat set set \\<Rightarrow> bool\"\n  where \"closed_remove_element K = (\\<forall>c\\<in>K. \\<forall>x\\<in>c. c - {x} \\<in> K)\"\n\nlemma cc_s_closed_remove_element:\n  assumes cc_s: \"(V, K) \\<in> cc_s\"\n  shows \"closed_remove_element K\"\nproof (unfold closed_remove_element_def, rule, rule)\n  fix c x\n  assume c: \"c \\<in> K\" and x: \"x \\<in> c\"\n  then have v: \"V \\<noteq> {}\" using cc_s\n    using cc_s.cases by blast\n  have \"pow_closed K\" \n    using cc_s c cc_s.cases by blast\n  then show \"c - {x} \\<in> K\" using c unfolding pow_closed_def by simp\nqed\n\nlemma closed_remove_element_cc_s:\n  assumes v: \"V \\<noteq> {}\"\n    and f: \"finite V\"\n    and k: \"K \\<subseteq> powerset V\" \n    and cre: \"closed_remove_element K\"\n  shows \"(V, K) \\<in> cc_s\"\nproof\n  show \"V \\<noteq> {}\" using v .\n  show \"K \\<subseteq> powerset V\" using k .\n  show \"pow_closed K\"\n  proof (unfold pow_closed_def, safe)\n    fix s s'\n    assume s: \"s \\<in> K\" and s's: \"s' \\<subseteq> s\"\n    have fs: \"finite s\" using s f k unfolding powerset_def\n      by (meson PowD finite_subset in_mono)\n    have fs': \"finite s'\" by (rule finite_subset [OF s's fs])\n    show \"s' \\<in> K\"\n    using s's fs' fs s proof (induct \"card (s - s')\" arbitrary: s s')\n      case 0 fix s :: \"nat set\" and s' :: \"nat set\"\n      assume eq: \"0 = card (s - s')\" and subset: \"s' \\<subseteq> s\" \n        and fs': \"finite s'\" and fs: \"finite s\" and s: \"s \\<in> K\"\n      have \"s' = s\" using eq subset fs by simp \n      thus \"s' \\<in> K\" using s by fast\n    next\n      case (Suc n)\n      fix s'\n      assume hyp: \"\\<And>s s'. n = card (s - s') \\<Longrightarrow> s' \\<subseteq> s \\<Longrightarrow> finite s' \\<Longrightarrow> finite s \\<Longrightarrow> s \\<in> K \\<Longrightarrow> s' \\<in> K\"\n        and suc: \"Suc n = card (s - s')\" and subset: \"s' \\<subseteq> s\" and fs': \"finite s'\"\n        and fs: \"finite s\" and s: \"s \\<in> K\" \n      from suc obtain x where xs: \"x \\<in> s\" and xs': \"x \\<notin> s'\"\n        by (metis Diff_eq_empty_iff card_0_eq finite_Diff fs old.nat.distinct(2) subsetI)\n      have s's: \"s - s' = insert x ((s - {x}) - s')\" using xs xs' by auto\n      have card: \"card ((s - {x}) - s') = n\"\n         using suc fs' fs xs xs'\n        by (metis Diff_insert2 card_Diff_insert diff_Suc_1)\n      show \"s' \\<in> K\"\n      proof (rule hyp [of \"s - {x}\"])\n       show \"n = card (s - {x} - s')\" using card by safe\n       show \"s' \\<subseteq> s - {x}\" using subset xs xs' by auto\n       show \"finite s'\" using fs' .\n       show \"finite (s - {x})\" using fs by simp\n       show \"s - {x} \\<in> K\" using cre s xs unfolding closed_remove_element_def by simp\n     qed\n   qed\n qed\nqed\n\ntext\\<open>The following result can be understood as the inverse \n  of @{thm cc_s_link_eq_link_ext}.\\<close>\n\nlemma link_eq_link_ext_cc_s:\n  assumes v: \"V \\<noteq> {}\"\n    and f: \"finite V\"\n    and k: \"K \\<subseteq> powerset V\"\n    and l: \"\\<forall>x\\<in>V. link x V K = link_ext x V K\"\n  shows cc: \"(V, K) \\<in> cc_s\"\nproof (rule closed_remove_element_cc_s)\n  show \"V \\<noteq> {}\" using v .\n  show \"finite V\" using f .\n  show \"K \\<subseteq> powerset V\" using k .\n  show \"closed_remove_element K\"\n  proof (unfold closed_remove_element_def, rule, rule)\n    fix c x\n    assume c: \"c \\<in> K\" and x: \"x \\<in> c\"\n    have xn: \"x \\<notin> c - {x}\" and xv: \"x \\<in> V\"\n      using c k powerset_def x by auto\n    have \"c - {x} \\<in> link_ext x V K\"\n      using c x xn k \n      unfolding link_ext_def powerset_def \n      using insert_absorb [OF x] by auto\n    hence \"c - {x} \\<in> link x V K\" using l xv by simp\n    thus \"c - {x} \\<in> K\" unfolding link_def by simp\n  qed\nqed\n\nlemma link_empty [simp]: \"link x V {} = {}\" \n  unfolding link_def powerset_def by simp\n\nlemma link_empty_singleton [simp]: \"link x {} {{}} = {}\" \n  unfolding link_def powerset_def try by auto\n\nlemma link_nempty_singleton [simp]: \n  \"V \\<noteq> {} \\<Longrightarrow> link x V {{}} = {}\" \n  unfolding link_def powerset_def by simp\n\nsection\\<open>Costar of a vertex in a set of sets\\<close>\n\ndefinition cost :: \"nat \\<Rightarrow> nat set \\<Rightarrow> nat set set \\<Rightarrow> nat set set\"\n  where \"cost x V K = {s. s \\<in> powerset (V - {x}) \\<and> s \\<in> K}\"\n\nlemma cost_empty [simp]: \"cost x V {} = {}\" \n  unfolding cost_def powerset_def by simp\n\nlemma cost_singleton [simp]: \"cost x V {{}} = {{}}\" \n  unfolding cost_def powerset_def by auto\n\nlemma cost_mono:\n  assumes \"K \\<subseteq> L\"\n  shows \"cost x V K \\<subseteq> cost x V L\"\n  using assms unfolding cost_def powerset_def by auto\n\nlemma cost_commute:\n  assumes x: \"x \\<in> V\" and y: \"y \\<in> V\" \n  shows \"cost y (V - {x}) (cost x V K) = \n        cost x (V - {y}) (cost y V K)\"\n  using x y unfolding cost_def powerset_def by auto\n\nlemma link_subset_cost:\n  shows \"link x V K \\<subseteq> cost x V K\"\n  unfolding link_def cost_def powerset_def by auto\n\ntext\\<open>The previous result does not hold for @{term link_ext}, \n  it is only true for @{term link}\\<close>\n\nlemma link_ext_cost_commute:\n  assumes x: \"x \\<in> V\" and y: \"y \\<in> V\" and xy: \"x \\<noteq> y\"\n  shows \"link_ext y (V - {x}) (cost x V K) = \n        cost x (V - {y}) (link_ext y V K)\"\n  using x y xy unfolding link_ext_def cost_def powerset_def by auto\n\nlemma link_cost_commute:\n  assumes x: \"x \\<in> V\" and y: \"y \\<in> V\" and xy: \"x \\<noteq> y\"\n  shows \"link y (V - {x}) (cost x V K) = \n        cost x (V - {y}) (link y V K)\"\n  using x y xy unfolding link_def cost_def powerset_def by auto\n\nsection\\<open>Evaluation of a list over a set of sets\\<close>\n\nfunction evaluation :: \"nat list \\<Rightarrow> nat set set \\<Rightarrow> bool list\"\n  where\n  \"evaluation [] {} = [False]\"\n  | \"A \\<noteq> {} \\<Longrightarrow> evaluation [] A = [True]\"\n  | \"evaluation (x # l) K =\n          (evaluation l (link_ext x (set (x # l)) K)) @ \n          (evaluation l (cost x (set (x # l)) K))\"\n  unfolding cost_def link_ext_def powerset_def \n  by (auto) (meson neq_Nil_conv)\ntermination proof (relation \"Wellfounded.measure (\\<lambda>(V,K). length V)\", simp_all)\nqed\n\nlemma length_evaluation_empty_list [simp]: \n  shows \"length (evaluation [] K) = 1\" \n  by (cases \"K = {}\", simp_all)\n\nlemma length_evaluation_eq:\n  shows \"length (evaluation l K) = length (evaluation l L)\"\nproof (induct l arbitrary: K L)\n  case Nil\n  then show ?case by simp\nnext\n  case (Cons a l)\n  show ?case unfolding evaluation.simps\n    using Cons.hyps [of \"(cost a (set (a # l)) K)\" \"(cost a (set (a # l)) L)\"]\n    using Cons.hyps [of \"(link_ext a (set (a # l)) K)\" \"(link_ext a (set (a # l)) L)\"] \n    by simp\nqed\n\ninstantiation list :: (ord) ord  \nbegin\n\ndefinition \"less_eq l m \\<equiv> (length l \\<le> length m) \\<and> (\\<forall>i<length l. l!i \\<le> m!i)\"\n\ndefinition \"less l m \\<equiv> (length l \\<le> length m) \\<and> (\\<forall>i<length l. l!i < m!i)\"\n\ninstance\nproof\n\nqed\n\nend\n\nlemma less_eq_list_append:\n  assumes le1: \"length l1 = length l2\" and le2: \"length l3 = length l4\"\n    and leq1: \"l1 \\<le> l2\" and leq2: \"l3 \\<le> l4\"\n  shows \"l1 @ l3 \\<le> l2 @ l4\"\nproof (unfold less_eq_list_def, rule)\n  show \"length (l1 @ l3) \\<le> length (l2 @ l4)\" using le1 le2 by simp\n  show \"\\<forall>i<length (l1 @ l3). (l1 @ l3) ! i \\<le> (l2 @ l4) ! i\" \n  proof (safe)\n    fix i assume i: \"i < length (l1 @ l3)\"\n    show \"(l1 @ l3) ! i \\<le> (l2 @ l4) ! i\"\n    proof (cases \"i < length l1\")\n      case True \n      thus ?thesis using leq1 le1\n        by (simp add: less_eq_list_def nth_append)\n    next\n      case False hence \"length l1 \\<le> i\" by simp\n      thus ?thesis \n        unfolding nth_append \n        using le1\n        using leq2 le2 i unfolding less_eq_list_def by auto\n    qed\n  qed\nqed\n\nlemma evaluation_mono:\n  assumes k: \"K \\<subseteq> powerset V\" and l: \"L \\<subseteq> powerset V\" \n    and kl: \"K \\<subseteq> L\"\n    (*and \"(V, l) \\<in> sorted_variables\"*)\n shows \"evaluation l K \\<le> evaluation l L\"\nusing kl proof (induction l arbitrary: K L)\n  case Nil\n  then show ?case \n    using kl using evaluation.simps (1,2)\n    unfolding less_eq_list_def\n    by (metis One_nat_def bot.extremum_uniqueI le_boolE length_evaluation_empty_list less_Suc0 linorder_linear nth_Cons_0)\nnext\n  case (Cons a l K L)\n  note kl = Cons.prems\n  show ?case\n  proof (unfold evaluation.simps, rule less_eq_list_append)\n  show \"length (evaluation l (link_ext a (set (a # l)) K)) = length (evaluation l (link_ext a (set (a # l)) L))\"\n    and \"length (evaluation l (cost a (set (a # l)) K)) = length (evaluation l (cost a (set (a # l)) L))\"\n    using length_evaluation_eq by simp_all\n  show \"evaluation l (cost a (set (a # l)) K) \\<le> evaluation l (cost a (set (a # l)) L)\"\n    using Cons.IH [OF cost_mono [OF kl, of a \"set (a # l)\"]] .\n  show \"evaluation l (link_ext a (set (a # l)) K) \\<le> evaluation l (link_ext a (set (a # l)) L)\"\n    using Cons.IH [OF link_ext_mono [OF kl, of a \"set (a # l)\"]] .\n  qed\nqed\n\nlemma append_eq_same_length:\n  assumes mleq: \"m1 @ m2 = l1 @ l2\" \n    and lm: \"length m1 = length m2\" and ll: \"length l1 = length l2\"\n  shows \"m1 = l1\" and \"m2 = l2\"\n  using append_eq_conv_conj [of \"m1\" \"m2\" \"l1 @ l2\"]\n  using mleq lm ll by force+\n\ntext\\<open>The following result does not hold in general for \n  @{term link_ext}, but it is true for simplicial complexes,\n  where @{thm cc_s_link_eq_link_ext} and then we can make use of \n  @{thm link_subset_cost} which holds in general.\\<close>\n\ncorollary evaluation_cost_link_ext:\n  assumes e: \"evaluation l K = l1 @ l2\"\n    and cc_s: \"(set l, K) \\<in> cc_s\"\n    and l :\"length l1 = length l2\"\n  shows \"l1 \\<le> l2\"\nusing cc_s proof (cases l)\n  case Nil\n  have False\n  proof (cases \"K = {}\")\n    case True show False\n      using e unfolding Nil True\n      unfolding evaluation.simps (1) \n      using l\n      by (metis Nil_is_append_conv append_eq_Cons_conv length_0_conv list.discI)\n  next\n    case False show False\n    using e False unfolding Nil\n    unfolding evaluation.simps (2) [OF False]\n    using l\n    by (metis Nil_is_append_conv append_eq_Cons_conv length_0_conv list.discI)\n  qed\n  thus ?thesis by fast\nnext\n  case (Cons a l') note la = Cons\n  have \"l1 = evaluation l' (link_ext a (set (a # l')) K)\"\n  proof (rule append_eq_same_length [of \"l1\" \"l2\" \"evaluation l' (link_ext a (set (a # l')) K)\" \"evaluation l' (cost a (set (a # l')) K)\"])\n    show \"l1 @ l2 = evaluation l' (link_ext a (set (a # l')) K) @ evaluation l' (cost a (set (a # l')) K)\"\n      using e [symmetric] unfolding la unfolding evaluation.simps (3) .\n    show \"length l1 = length l2\" using l .\n    show \"length (evaluation l' (link_ext a (set (a # l')) K)) = length (evaluation l' (cost a (set (a # l')) K))\"\n      using length_evaluation_eq [of \"l'\" \"link_ext a (set (a # l')) K\" \"cost a (set (a # l')) K\"] .\n  qed\n  hence l1: \"l1 = evaluation l' (link a (set (a # l')) K)\"\n    using cc_s_link_eq_link_ext [OF cc_s, of a] \n    unfolding la by simp\n  have l2: \"l2 = evaluation l' (cost a (set (a # l')) K)\"\n  proof (rule append_eq_same_length [of \"l1\" \"l2\" \"evaluation l' (link_ext a (set (a # l')) K)\" \"evaluation l' (cost a (set (a # l')) K)\"])\n    show \"l1 @ l2 = evaluation l' (link_ext a (set (a # l')) K) @ evaluation l' (cost a (set (a # l')) K)\"\n      using e [symmetric] unfolding la unfolding evaluation.simps (3) .\n    show \"length l1 = length l2\" using l .\n    show \"length (evaluation l' (link_ext a (set (a # l')) K)) = length (evaluation l' (cost a (set (a # l')) K))\"\n      using length_evaluation_eq [of \"l'\" \"(link_ext a (set (a # l')) K)\" \"(cost a (set (a # l')) K)\"] .\n  qed\n  show ?thesis\n    unfolding l1 l2\n  proof (rule evaluation_mono [of _ \"set (a # l')\"])\n    show \"cost a (set (a # l')) K \\<subseteq> powerset (set (a # l'))\" unfolding cost_def powerset_def by auto\n    show \"link a (set (a # l')) K \\<subseteq> powerset (set (a # l'))\" unfolding link_def powerset_def by auto\n    show \"link a (set (a # l')) K \\<subseteq> cost a (set (a # l')) K\" by (rule link_subset_cost)\n  qed\nqed\n\nsection\\<open>Lists of Boolean elements with no evaders.\\<close>\n\ntext\\<open>The base cases, @{term \"[False, False]\"} \n  and  @{term \"[True, True]\"} belonging to the set \n  of no evaders, can be proven from the following \n  definition.\\<close>\n\ninductive_set not_evaders :: \"(bool list) set\"\n  where \n  \"l1 = l2 \\<Longrightarrow> l1 @ l2 \\<in> not_evaders\"\n  | \"l1 \\<in> not_evaders \\<Longrightarrow> l2 \\<in> not_evaders \\<Longrightarrow> length l1 = length l2 \\<Longrightarrow> l1 @ l2 \\<in> not_evaders\"\n\nlemma \"[] \\<in> not_evaders\"\n  by (metis eq_Nil_appendI not_evaders.simps)\n\nlemma \"[False, False] \\<in> not_evaders\"\n  by (metis append_eq_Cons_conv not_evaders.simps)\n\nlemma \"[True, True] \\<in> not_evaders\"\n  by (metis append_eq_Cons_conv not_evaders.simps)\n\nlemma true_evader: \"[True] \\<notin> not_evaders\"\n  by (smt (verit, best) Cons_eq_append_conv append_is_Nil_conv length_0_conv not_Cons_self2 not_evaders.cases)\n\nlemma false_evader: \"[False] \\<notin> not_evaders\"\n  by (smt (verit, best) Cons_eq_append_conv append_is_Nil_conv length_0_conv not_Cons_self2 not_evaders.cases)\n\nlemma \"[True, False] \\<notin> not_evaders\"\nproof (rule ccontr, safe)\n  assume \"[True, False] \\<in> not_evaders\"\n  show False\n    using not_evaders.cases [of \"[True, False]\"] true_evader false_evader\n    by (smt (verit, ccfv_threshold) \\<open>[True, False] \\<in> not_evaders\\<close> append_butlast_last_id append_eq_same_length(1) butlast.simps(2) last.simps list.distinct(1) list.size(4))\nqed\n\nlemma \"[False, True] \\<notin> not_evaders\"\nproof (rule ccontr, safe)\n  assume \"[False, True] \\<in> not_evaders\"\n  show False\n    using not_evaders.cases [of \"[False, True]\"] true_evader false_evader\n    by (smt (verit, ccfv_threshold) \\<open>[False, True] \\<in> not_evaders\\<close> append_butlast_last_id append_eq_same_length(1) butlast.simps(2) last.simps list.distinct(1) list.size(4))\nqed\n\nsection\\<open>A set of sets being a cone over a given vertex\\<close>\n\ndefinition cone :: \"nat set \\<Rightarrow> nat set set \\<Rightarrow> bool\"\n  where \"cone X K = ((\\<exists>x\\<in>X. \\<exists>T. T \\<subseteq> powerset (X - {x})  \n                      \\<and> K = T \\<union> {s. \\<exists>t\\<in>T. s = insert x t}))\"\n\nlemma cone_not_empty:\n  assumes a: \"(\\<exists>x\\<in>X. \\<exists>T. T \\<subseteq> powerset (X - {x}) \\<and> K = T \\<union> {s. \\<exists>t\\<in>T. s = insert x t})\"\n  shows \"cone X K\"\n  unfolding cone_def\n  using assms by blast\n\nlemma cone_disjoint:\n  assumes \"cone X K\" and \"x \\<in> X\" and t: \"T \\<subseteq> powerset (X - {x})\"\n   and \"K = T \\<union> {s. \\<exists>t\\<in>T. s = insert x t}\"\n  shows \"T \\<inter> {s. \\<exists>t\\<in>T. s = insert x t} = {}\"\n  using t unfolding powerset_def by auto\n\nlemma cone_cost_eq_link:\n  assumes x: \"x \\<in> X\" \n    and cs: \"T \\<subseteq> powerset (X - {x})\" \n    and kt: \"K = T \\<union> {s. \\<exists>t\\<in>T. s = insert x t}\"\n  shows \"cost x V K = link x V K\"\nproof\n  show \"link x V K \\<subseteq> cost x V K\" by (rule link_subset_cost) \n  show \"cost x V K \\<subseteq> link x V K\"\n    unfolding kt\n    unfolding cost_def link_def powerset_def by auto\nqed\n\ntext\\<open>The following result does hold for @{term link_ext}, \n  but the proof is different than for @{term link} \n  because in general it does not hold that \n  @{term \"link_ext x V K \\<subseteq> cost x V K\"}\\<close>\n\nlemma cone_impl_cost_eq_link_ext:\n  assumes x: \"x \\<in> V\"\n    and cs: \"T \\<subseteq> powerset (V - {x})\" \n    and kt: \"K = T \\<union> {s. \\<exists>t\\<in>T. s = insert x t}\"\n  shows \"cost x V K = link_ext x V K\"\nproof\n  show \"link_ext x V K \\<subseteq> cost x V K\"\n    using assms unfolding link_ext_def cost_def powerset_def\n    by auto (metis Diff_insert_absorb PowD in_mono mk_disjoint_insert)\n  show \"cost x V K \\<subseteq> link_ext x V K\"\n    unfolding kt\n    unfolding cost_def link_ext_def powerset_def by auto\nqed\n\nlemma cost_eq_link_ext_impl_cone:\n  assumes c: \"cost x V K = link_ext x V K\"\n    and x: \"x \\<in> V\" and p: \"K \\<subseteq> powerset V\"\n  shows \"cone V K\"\nproof (unfold cone_def, rule bexI [OF _ x], rule exI [of _ \"cost x V K\"], rule conjI)\n  show \"cost x V K \\<subseteq> powerset (V - {x})\"\n    using p unfolding cost_def powerset_def by auto\n  show \"K = cost x V K \\<union> {s. \\<exists>t\\<in>cost x V K. s = insert x t}\"\n  proof\n    show \"cost x V K \\<union> {s. \\<exists>t\\<in>cost x V K. s = insert x t} \\<subseteq> K\"\n      using x p\n      using c\n      unfolding cost_def powerset_def link_ext_def by auto\n    show \"K \\<subseteq> cost x V K \\<union> {s. \\<exists>t\\<in>cost x V K. s = insert x t}\" \n    proof (subst c, unfold cost_def link_ext_def powerset_def, rule)\n      fix xa\n      assume xa: \"xa \\<in> K\"\n      show \"xa \\<in> {s \\<in> Pow V. x \\<notin> s \\<and> insert x s \\<in> K} \\<union>\n                {s. \\<exists>t\\<in>{s \\<in> Pow (V - {x}). s \\<in> K}. s = insert x t}\"\n      proof (cases \"x \\<in> xa\")\n        case False\n        then show ?thesis using xa c p \n          unfolding cost_def link_ext_def powerset_def by blast\n      next\n        case True\n        have \"xa - {x} \\<in> {s \\<in> Pow V. x \\<notin> s \\<and> insert x s \\<in> K}\"\n          using xa p True unfolding powerset_def\n          using mk_disjoint_insert by fastforce\n        hence \"xa - {x} \\<in> {s \\<in> Pow (V - {x}). s \\<in> K}\"\n          using c unfolding cost_def link_ext_def powerset_def by simp\n        hence \"xa \\<in> {s. \\<exists>t\\<in>{s \\<in> Pow (V - {x}). s \\<in> K}. s = insert x t}\"\n          using True by auto\n        thus ?thesis by fast\n      qed\n    qed\n  qed\nqed\n\ntext\\<open>Under the given premises, @{term cost} of a cone is a cone.\\<close>\n\nlemma cost_cone_eq:\n  assumes x: \"x \\<in> V\" (*and y: \"y \\<in> V\"*) and xy: \"x \\<noteq> y\"\n    and cs: \"T \\<subseteq> powerset (V - {x})\" \n    and kt: \"K = T \\<union> {s. \\<exists>t\\<in>T. s = insert x t}\"\n  shows \"cost y V K = (cost y (V - {x}) T) \\<union> {s. \\<exists>t\\<in>(cost y (V - {x}) T). s = insert x t}\"\nproof\n  show \"cost y V K \\<subseteq> cost y (V - {x}) T \\<union> {s. \\<exists>t\\<in>cost y (V - {x}) T. s = insert x t}\"\n  proof\n    fix xa\n    assume xa: \"xa \\<in> cost y V K\"\n    show \"xa \\<in> cost y (V - {x}) T \\<union> {s. \\<exists>t\\<in>cost y (V - {x}) T. s = insert x t}\"\n    proof (cases \"x \\<in> xa\")\n      case False\n      from xa and False have \"xa \\<in> T\" and \"xa \\<in> Pow (V - {x} - {y})\" \n        unfolding kt cost_def powerset_def by auto\n      thus ?thesis unfolding cost_def powerset_def  by simp\n    next\n      case True note xxa = True\n      show ?thesis\n      proof (cases \"xa \\<in> T\")\n        case True\n        obtain xa'\n          where \"xa' \\<in> Pow (V - {x} - {y})\" and \"xa' \\<in> T\" and \"xa = insert x xa'\"\n          using cs True xxa unfolding powerset_def by auto\n        thus ?thesis unfolding cost_def powerset_def by auto\n      next\n        case False\n        with xxa and xa and cs obtain t\n          where xapow: \"xa \\<in> Pow (V - {y})\" and xainsert: \"xa = insert x t\" \n            and tT: \"t \\<in> T\" and tpow: \"t \\<in> Pow (V - {x} - {y})\"\n          unfolding kt cost_def powerset_def by blast\n        thus ?thesis unfolding cost_def powerset_def by auto\n      qed\n    qed\n  qed\n  show \"cost y (V - {x}) T \\<union> {s. \\<exists>t\\<in>cost y (V - {x}) T. s = insert x t} \\<subseteq> cost y V K\"\n    unfolding kt cost_def powerset_def using x xy by auto\nqed\n\ntext\\<open>Under the given premises, @{term link_ext} of a cone is a cone.\\<close>\n\nlemma link_ext_cone_eq:\n  assumes x: \"x \\<in> V\" (*and y: \"y \\<in> V\"*) and xy: \"x \\<noteq> y\"\n    and cs: \"T \\<subseteq> powerset (V - {x})\" \n    and kt: \"K = T \\<union> {s. \\<exists>t\\<in>T. s = insert x t}\"\n  shows \"link_ext y V K = (link_ext y (V - {x}) T) \\<union> {s. \\<exists>t\\<in>(link_ext y (V - {x}) T). s = insert x t}\"\nproof\n  show \"link_ext y (V - {x}) T \\<union> {s. \\<exists>t\\<in>link_ext y (V - {x}) T. s = insert x t} \\<subseteq> link_ext y V K\"\n    unfolding kt link_ext_def powerset_def using x xy by auto\n  show \"link_ext y V K \\<subseteq> link_ext y (V - {x}) T \\<union> {s. \\<exists>t\\<in>link_ext y (V - {x}) T. s = insert x t}\"\n  unfolding link_ext_def [of y V K]\n  unfolding link_ext_def [of y \"V - {x}\" T]\n  proof\n    fix xa\n    assume \"xa \\<in> {s \\<in> powerset V. y \\<notin> s \\<and> insert y s \\<in> K}\"\n    hence xap: \"xa \\<in> powerset V\" and xak: \"y \\<notin> xa\" and iyxa: \"insert y xa \\<in> K\" by auto\n    show \"xa \\<in> {s \\<in> powerset (V - {x}). y \\<notin> s \\<and> insert y s \\<in> T} \\<union>\n                {s. \\<exists>t\\<in>{s \\<in> powerset (V - {x}). y \\<notin> s \\<and> insert y s \\<in> T}.\n                       s = insert x t}\"\n    proof (cases \"x \\<in> xa\")\n      case False note xnxa = False\n      hence xapxy: \"xa \\<in> powerset (V - {x})\" using xap xy unfolding powerset_def by auto\n      moreover have \"y \\<notin> xa\" using xak .\n      moreover have \"insert y xa \\<in> T\"\n      proof (cases \"insert y xa \\<in> T\")\n        case True then show ?thesis by simp\n      next\n        case False with iyxa and kt have \"insert y xa \\<in> {s. \\<exists>t\\<in>T. s = insert x t}\"\n          by simp\n        then have \"False\" using xnxa\n          using xy by blast\n        thus ?thesis by (rule ccontr)\n      qed\n      ultimately have \"xa \\<in> {s \\<in> powerset (V - {x}). y \\<notin> s \\<and> insert y s \\<in> T}\"\n        by auto\n      thus ?thesis by fast\n    next\n      case True note xxa = True\n      then obtain t where xai: \"xa = insert x t\" and xnt: \"x \\<notin> t\" \n        using Set.set_insert [OF True] by auto\n      have \"t \\<in> powerset (V - {x})\" \n        using xap xai xnt unfolding powerset_def by auto\n      moreover have t: \"y \\<notin> xa\" using xak .\n      moreover have \"insert y t \\<in> T\"\n      proof (cases \"insert y xa \\<in> T\")\n        case True then have False\n          using cs xxa unfolding powerset_def by auto\n        thus ?thesis by (rule ccontr)\n      next\n        case False\n        with xai iyxa kt have \"insert y xa \\<in> {s. \\<exists>t\\<in>T. s = insert x t}\" by simp\n        with xai xap xnt kt show ?thesis\n          unfolding powerset_def\n          by auto (metis (full_types) Diff_insert_absorb False insert_absorb insert_commute insert_iff xak)\n      qed\n      ultimately show ?thesis using xai by auto\n    qed\n  qed\nqed\n\ntext\\<open>Even if it is not used in our later proofs,\n  it also holds that @{term link} of a cone is a cone.\\<close>\n\nlemma link_cone_eq:\n  assumes x: \"x \\<in> V\" (*and y: \"y \\<in> V\"*) and xy: \"x \\<noteq> y\"\n    and cs: \"T \\<subseteq> powerset (V - {x})\" \n    and kt: \"K = T \\<union> {s. \\<exists>t\\<in>T. s = insert x t}\"\n  shows \"link y V K = (link y (V - {x}) T) \\<union> {s. \\<exists>t\\<in>(link y (V - {x}) T). s = insert x t}\"\nproof\n  show \"link y (V - {x}) T \\<union> {s. \\<exists>t\\<in>link y (V - {x}) T. s = insert x t} \\<subseteq> link y V K\"\n    unfolding kt link_def powerset_def using x xy by auto\n  show \"link y V K \\<subseteq> link y (V - {x}) T \\<union> {s. \\<exists>t\\<in>link y (V - {x}) T. s = insert x t}\"\n  unfolding link_def [of y V K]\n  unfolding link_def [of y \"V - {x}\" T]\n  proof\n    fix xa\n    assume \"xa \\<in> {s \\<in> powerset (V - {y}). s \\<in> K \\<and> insert y s \\<in> K}\"\n    hence xap: \"xa \\<in> powerset (V - {y})\" and xak: \"xa \\<in> K\" and iyxa: \"insert y xa \\<in> K\" by auto\n    show \"xa \\<in> {s \\<in> powerset (V - {x} - {y}). s \\<in> T \\<and> insert y s \\<in> T} \\<union>\n           {s. \\<exists>t\\<in>{s \\<in> powerset (V - {x} - {y}). s \\<in> T \\<and> insert y s \\<in> T}. s = insert x t}\"\n    proof (cases \"x \\<in> xa\")\n      case False note xnxa = False\n      hence xapxy: \"xa \\<in> powerset (V - {x} - {y})\" using xap xy unfolding powerset_def by auto\n      moreover have \"xa \\<in> T\" using xak kt False by auto\n      moreover have \"insert y xa \\<in> T\"\n      proof (cases \"insert y xa \\<in> T\")\n        case True then show ?thesis by simp\n      next\n        case False with iyxa and kt have \"insert y xa \\<in> {s. \\<exists>t\\<in>T. s = insert x t}\"\n          by simp\n        then have \"False\" using xnxa\n          using xy by blast\n        thus ?thesis by (rule ccontr)\n      qed\n      ultimately have \"xa \\<in> {s \\<in> powerset (V - {x} - {y}). s \\<in> T \\<and> insert y s \\<in> T}\"\n        by auto\n      thus ?thesis by fast\n    next\n      case True note xxa = True\n      then obtain t where xai: \"xa = insert x t\" and xnt: \"x \\<notin> t\" \n        using Set.set_insert [OF True] by auto\n      have \"t \\<in> powerset (V - {x} - {y})\" \n        using xap xai xnt unfolding powerset_def by auto\n      moreover have t: \"t \\<in> T\"\n      proof (cases \"xa \\<in> T\")\n        case True\n        have \"xa \\<notin> {s. \\<exists>t\\<in>T. s = insert x t}\" \n          using x cs kt True unfolding powerset_def by auto\n        then have False using xai True by auto\n        then show ?thesis by (rule ccontr)\n      next\n        case False\n        with cs kt xak have \"xa \\<in> {s. \\<exists>t\\<in>T. s = insert x t}\" by simp\n        with xai xnt False show ?thesis\n          by auto (metis insert_absorb insert_ident)\n      qed\n      moreover have \"insert y t \\<in> T\"\n      proof (cases \"insert y xa \\<in> T\")\n        case True then have False\n          using cs xxa unfolding powerset_def by auto\n        thus ?thesis by (rule ccontr)\n      next\n        case False\n        then show ?thesis\n          using xai xap xnt kt iyxa unfolding powerset_def\n          by (smt (verit, del_insts) Diff_insert_absorb PowD UnE Un_insert_right insert_absorb insert_is_Un iyxa kt mem_Collect_eq powerset_def singletonD subset_Diff_insert xai xap xnt)\n      qed\n      ultimately show ?thesis using xai by auto\n    qed\n  qed\nqed\n\nlemma evaluation_cone_not_evaders:\n  assumes k: \"K \\<subseteq> powerset X\"\n    and c: \"cone X K\" and X: \"X \\<noteq> {}\" and f: \"finite X\" and xl: \"(X, l) \\<in> sorted_variables\"\n  shows \"evaluation l K \\<in> not_evaders\"\nproof -\n  from c and X obtain x :: nat and T :: \"nat set set\"\n    where x: \"x \\<in> X\" and cs: \"T \\<subseteq> powerset (X - {x})\" and kt: \"K = T \\<union> {s. \\<exists>k\\<in>T. s = insert x k}\"\n    unfolding cone_def by auto\n  show ?thesis\n  using X f xl c proof (induct \"card X\" arbitrary: X l K)\n    case 0 with f have x: \"X = {}\" by simp\n    hence False using \"0.prems\" (1) by blast\n    thus ?case by (rule ccontr)\n  next\n    case (Suc n)\n    obtain x :: nat and T :: \"nat set set\"\n      where x: \"x \\<in> X\" and cs: \"T \\<subseteq> powerset (X - {x})\"\n        and kt: \"K = T \\<union> {s. \\<exists>k\\<in>T. s = insert x k}\"\n      using Suc.prems (1,4) unfolding cone_def by auto\n    obtain y l' where l: \"l = y # l'\" and y: \"y \\<in> X\"\n      using Suc.prems Suc.hyps (2) sorted_variables_length_coherent [OF Suc.prems (3)]\n      by (metis insert_iff sorted_variables.cases)\n    show ?case\n      unfolding l \n      unfolding evaluation.simps (3) \n      unfolding l [symmetric] \n      unfolding sorted_variables_coherent [OF Suc.prems (3), symmetric]\n    proof (cases \"x = y\")\n      case True\n      have cl_eq: \"cost x X K = link_ext x X K\"\n        by (rule cone_impl_cost_eq_link_ext [of x X T], rule x, rule cs, rule kt)\n      show \"evaluation l' (link_ext y X K) @ evaluation l' (cost y X K)\n            \\<in> not_evaders\"\n        using True using cl_eq unfolding l [symmetric]\n        using not_evaders.intros(1) by presburger\n    next\n      case False\n      have crw: \"cost y X K = cost y (X - {x}) T \\<union> {s. \\<exists>t\\<in>cost y (X - {x}) T. s = insert x t}\"\n      proof (rule cost_cone_eq)\n        show \"x \\<in> X\" using x .\n        show \"x \\<noteq> y\" using False .\n        show \"T \\<subseteq> powerset (X - {x})\" using cs .\n        show \"K = T \\<union> {s. \\<exists>t\\<in>T. s = insert x t}\" using kt .\n      qed\n      have lrw: \"link_ext y X K = link_ext y (X - {x}) T \\<union> {s. \\<exists>t\\<in>link_ext y (X - {x}) T. s = insert x t}\"\n      proof (rule link_ext_cone_eq)\n        show \"x \\<in> X\" using x .\n        show \"x \\<noteq> y\" using False .\n        show \"T \\<subseteq> powerset (X - {x})\" using cs .\n        show \"K = T \\<union> {s. \\<exists>t\\<in>T. s = insert x t}\" using kt .\n      qed\n      show \"evaluation l' (link_ext y X K) @ evaluation l' (cost y X K) \\<in> not_evaders\"\n        unfolding crw lrw\n      proof (rule not_evaders.intros(2))\n        show \"evaluation l' (link_ext y (X - {x}) T \\<union> {s. \\<exists>t\\<in>link_ext y (X - {x}) T. s = insert x t}) \\<in> not_evaders\"\n        proof (rule Suc.hyps (1) [of \"X - {y}\"])\n          show \"n = card (X - {y})\" using Suc.hyps (2) y x False by simp\n          show \"X - {y} \\<noteq> {}\" using x False by auto\n          show \"finite (X - {y})\" using Suc.prems (2) by simp\n          show \"(X - {y}, l') \\<in> sorted_variables\"\n            using Suc.prems (3) using l y Suc.prems (1)\n            by (metis Diff_insert_absorb list.inject sorted_variables.cases)\n          show \"cone (X - {y}) (link_ext y (X - {x}) T \\<union> {s. \\<exists>t\\<in>link_ext y (X - {x}) T. s = insert x t})\"\n          proof (rule cone_not_empty, intro bexI [of _ x] exI [of _ \"link_ext y (X - {x}) T\"], rule conjI)\n            show \"link_ext y (X - {x}) T \\<subseteq> powerset (X - {y} - {x})\"\n              unfolding link_ext_def powerset_def by auto\n            show \"link_ext y (X - {x}) T \\<union> {s. \\<exists>t\\<in>link_ext y (X - {x}) T. s = insert x t} =\n                  link_ext y (X - {x}) T \\<union> {s. \\<exists>t\\<in>link_ext y (X - {x}) T. s = insert x t}\" ..\n            show \"x \\<in> X - {y}\" using x False by simp\n          qed\n        qed\n        show \"evaluation l' (cost y (X - {x}) T \\<union> {s. \\<exists>t\\<in>cost y (X - {x}) T. s = insert x t}) \\<in> not_evaders\"\n        proof (rule Suc.hyps (1) [of \"X - {y}\"])\n          show \"n = card (X - {y})\" using Suc.hyps (2) y x False by simp\n          show \"X - {y} \\<noteq> {}\" using x False by auto\n          show \"finite (X - {y})\" using Suc.prems (2) by simp\n          show \"(X - {y}, l') \\<in> sorted_variables\"\n            using Suc.prems (3) using l y Suc.prems (1)\n            by (metis Diff_insert_absorb list.inject sorted_variables.cases)\n          show \"cone (X - {y}) (cost y (X - {x}) T \\<union> {s. \\<exists>t\\<in>cost y (X - {x}) T. s = insert x t})\"\n          proof (rule cone_not_empty, intro bexI [of _ x] exI [of _ \"cost y (X - {x}) T\"], rule conjI)\n            show \"cost y (X - {x}) T \\<subseteq> powerset (X - {y} - {x})\"\n              unfolding cost_def powerset_def by auto\n            show \"cost y (X - {x}) T \\<union> {s. \\<exists>t\\<in>cost y (X - {x}) T. s = insert x t} =\n                  cost y (X - {x}) T \\<union> {s. \\<exists>t\\<in>cost y (X - {x}) T. s = insert x t}\" ..\n            show \"x \\<in> X - {y}\" using x False by simp\n          qed\n        qed\n        show \"length (evaluation l' (link_ext y (X - {x}) T \\<union> {s. \\<exists>t\\<in>link_ext y (X - {x}) T. s = insert x t})) =\n              length (evaluation l' (cost y (X - {x}) T \\<union> {s. \\<exists>t\\<in>cost y (X - {x}) T. s = insert x t}))\"\n          using length_evaluation_eq .\n      qed\n    qed\n  qed\nqed\n\nlemma \"link x {x} {{}, {x}} = {{}}\"\n  unfolding link_def powerset_def by auto\n\nlemma cost_singleton2: \"cost x {x} {{}, {x}} = {{}}\" \n  unfolding cost_def powerset_def by auto\n\nlemma\n  evaluation_empty_set_not_evaders:\n  assumes a: \"A \\<noteq> []\"\n  shows \"evaluation A {} \\<in> not_evaders\"\nproof -\n  from a obtain x l where xl: \"A = x # l\"\n    by (meson neq_Nil_conv)\n  show ?thesis \n    unfolding xl unfolding evaluation.simps (3) \n    unfolding link_ext_empty cost_empty\n    by (rule not_evaders.intros(1), rule refl)\nqed\n\nlemma finite_set_sorted_variables:\n  assumes f: \"finite X\"\n  shows \"\\<exists>A. (X, A) \\<in> sorted_variables\"\nusing f proof (induct \"card X\" arbitrary: X)\n  case 0\n  then have x: \"X = {}\" by simp\n  show ?case unfolding x by (rule exI [of _ \"[]\"], rule sorted_variables.intros(1))\nnext\n  case (Suc n)\n  then obtain x X' \n    where X: \"X = insert x X'\" and cx': \"card X' = n\" \n      and f: \"finite X'\" and xx': \"x \\<notin> X'\"\n    by (metis card_Suc_eq_finite)\n  from Suc.hyps (1) [OF cx'[symmetric] f] obtain A' where x'a': \"(X', A') \\<in> sorted_variables\"\n    by auto\n  show ?case \n    by (unfold X, intro exI [of _ \"x # A'\"],\n        intro sorted_variables.intros(2), intro x'a', intro xx')\nqed\n\nsection\\<open>Zero collapsible sets, based on @{term link_ext} and @{term cost}\\<close>\n\nfunction zero_collapsible :: \"nat set \\<Rightarrow> nat set set \\<Rightarrow> bool\"\n  where\n  \"V = {} \\<Longrightarrow> K = {{}} \\<Longrightarrow> zero_collapsible V K = True\"\n  | \"V = {} \\<Longrightarrow> K \\<noteq> {{}} \\<Longrightarrow> zero_collapsible V K = False\"\n  | \"V = {x} \\<Longrightarrow> K = {} \\<Longrightarrow> zero_collapsible V K = True\"\n  | \"V = {x} \\<Longrightarrow> K = {{},{x}} \\<Longrightarrow> zero_collapsible V K = True\"\n  | \"V = {x} \\<Longrightarrow> K \\<noteq> {} \\<Longrightarrow> K \\<noteq> {{},{x}} \\<Longrightarrow> zero_collapsible V K = False\"\n  | \"2 \\<le> card V \\<Longrightarrow> K = {} \\<Longrightarrow> zero_collapsible V K = True\"\n  | \"2 \\<le> card V \\<Longrightarrow> K \\<noteq> {} \\<Longrightarrow> zero_collapsible V K =\n    (\\<exists>x\\<in>V. cone (V - {x}) (link_ext x V K) \\<and> zero_collapsible (V - {x}) (cost x V K))\"\n  | \"\\<not> finite V \\<Longrightarrow> zero_collapsible V K = False\"\n  unfolding link_ext_def cost_def\nproof -\n  fix P :: \"bool\" and x :: \"(nat set \\<times> nat set set)\"\n  assume ee: \"(\\<And>V K. V = {} \\<Longrightarrow> K = {{}} \\<Longrightarrow> x = (V, K) \\<Longrightarrow> P)\"\n      and ene: \"(\\<And>V K. V = {} \\<Longrightarrow> K \\<noteq> {{}} \\<Longrightarrow> x = (V, K) \\<Longrightarrow> P)\" \n      and se: \"(\\<And>V xa K. V = {xa} \\<Longrightarrow> K = {} \\<Longrightarrow> x = (V, K) \\<Longrightarrow> P)\"\n      and sc: \"(\\<And>V xa K. V = {xa} \\<Longrightarrow> K = {{}, {xa}} \\<Longrightarrow> x = (V, K) \\<Longrightarrow> P)\" \n      and sn: \"(\\<And>V xa K. V = {xa} \\<Longrightarrow> K \\<noteq> {} \\<Longrightarrow> K \\<noteq> {{}, {xa}} \\<Longrightarrow> x = (V, K) \\<Longrightarrow> P)\"\n      and e2: \"(\\<And>V K. 2 \\<le> card V \\<Longrightarrow> K = {} \\<Longrightarrow> x = (V, K) \\<Longrightarrow> P)\"\n      and en2: \"(\\<And>V K. 2 \\<le> card V \\<Longrightarrow> K \\<noteq> {} \\<Longrightarrow> x = (V, K) \\<Longrightarrow> P)\"\n      and inf: \"(\\<And>V K. infinite V \\<Longrightarrow> x = (V, K) \\<Longrightarrow> P)\"\n  show P\n  proof (cases \"finite (fst x)\")\n    case False\n    show P\n      by (rule inf [of \"fst x\" \"snd x\"], intro False) auto\n  next\n    case True note finitex = True\n    show P\n    proof (cases \"fst x = {}\")\n      case True note ve = True\n      show P\n      proof (cases \"snd x = {{}}\")\n        case True\n        show P\n          by (rule ee [of \"fst x\" \"snd x\"], intro ve, intro True) simp\n      next\n        case False\n        show P\n          by (rule ene [of \"fst x\" \"snd x\"], intro ve, intro False) simp\n      qed\n    next\n      case False note vne = False\n      show P\n      proof (cases \"card (fst x) = 1\")\n        case True then obtain xa where f: \"fst x = {xa}\" by (rule card_1_singletonE)\n        show P\n        proof (cases \"snd x = {}\")\n          case True\n          show P\n            by (rule se [of \"fst x\" xa \"snd x\"], intro f, intro True) simp\n          next\n          case False note kne = False\n          show P\n          proof (cases \"snd x = {{},{xa}}\")\n            case True\n            show P\n              by (rule sc [of \"fst x\" xa \"snd x\"], intro f, intro True) simp\n          next\n            case False\n            show P\n              by (rule sn [of \"fst x\" xa \"snd x\"], intro f, intro kne, intro False) simp\n          qed\n        qed\n      next\n        case False\n        have card2: \"2 \\<le> card (fst x)\" using finitex vne False\n          by (metis One_nat_def Suc_1 card_gt_0_iff le_SucE not_less not_less_eq_eq)\n        show P\n        proof (cases \"snd x = {}\")\n          case True\n          show P\n            by (rule e2 [of \"fst x\" \"snd x\"], intro card2, intro True) simp\n        next\n          case False\n          show P\n            by (rule en2 [of \"fst x\" \"snd x\"], intro card2, intro False) simp\n        qed\n      qed\n    qed\n  qed\nqed (auto)\ntermination proof (relation \"Wellfounded.measure (\\<lambda>(V,K). card V)\")\n  show \"wf (measure (\\<lambda>(V, K). card V))\" by simp\n  fix V :: \"nat set\" and K :: \"nat set set\" and x :: \"nat\"\n  assume c: \"2 \\<le> card V\" and k: \"K \\<noteq> {}\" and x: \"x \\<in> V\"\n  show \"((V - {x}, cost x V K), V, K) \\<in> measure (\\<lambda>(V, K). card V)\"\n    using c k x by simp\nqed\n\nlemma shows \"zero_collapsible {x} {}\" by simp\n\nlemma shows \"\\<not> zero_collapsible {x} {{}}\" by simp\n\nlemma \"link_ext x {x} {{}, {x}} = {{}}\"\n  unfolding link_ext_def powerset_def by auto\n\nlemma shows \"zero_collapsible {x} {{}, {x}}\" by simp\n\ntext\\<open>There is always a valuation for which zero collapsible sets\n are not evasive.\\<close>\n\ntheorem\n  zero_collapsible_implies_not_evaders:\n  assumes k: \"K \\<subseteq> powerset X\"\n    and x: \"X \\<noteq> {}\" and f: \"finite X\" and cc: \"zero_collapsible X K\"\n  shows \"\\<exists>A. (X, A) \\<in> sorted_variables \\<and> evaluation A K \\<in> not_evaders\"\nusing k x f cc proof (induct \"card X\" arbitrary: X K)\n  case 0 with f have \"X = {}\" by simp\n  with \"0.prems\" (2) have False by fast\n  thus ?case by (rule ccontr)\nnext\n  case (Suc n)\n  show ?case\n  proof (cases \"K = {}\")\n    case True\n    obtain A where xa: \"(X, A) \\<in> sorted_variables\"\n      using finite_set_sorted_variables [OF Suc.prems (3)] by auto\n    show ?thesis\n    proof (intro exI [of _ A], rule conjI)\n      show \"(X, A) \\<in> sorted_variables\" using xa .\n      show \"evaluation A K \\<in> not_evaders\"\n      unfolding True\n      using evaluation.simps (3)\n      by (metis Suc.prems(2) empty_set evaluation_empty_set_not_evaders sorted_variables_coherent xa)\n  qed\n  next\n    case False note kne = False\n    show ?thesis\n    proof (cases \"card X = 1\")\n      case False\n      hence cardx: \"2 \\<le> card X\"\n        using Suc.hyps(2) by linarith\n      from Suc.prems (4) False Suc.prems (2)\n      obtain x where x: \"x \\<in> X\" and cl: \"cone (X - {x}) (link_ext x X K)\" \n        and ccc: \"zero_collapsible (X - {x}) (cost x X K)\" and xxne: \"X - {x} \\<noteq> {}\"\n        using zero_collapsible.simps (7) [OF cardx kne]\n        by (metis One_nat_def Suc.prems(3) card.empty card_Suc_Diff1)\n    have \"\\<exists>A. (X - {x}, A) \\<in> sorted_variables \\<and> evaluation A (cost x X K) \\<in> not_evaders\"\n    proof (rule Suc.hyps (1))\n      show \"n = card (X - {x})\" using x using Suc.hyps (2) by simp\n      show \"cost x X K \\<subseteq> powerset (X - {x})\" unfolding cost_def powerset_def by auto\n      show \"X - {x} \\<noteq> {}\"\n        using False Suc.hyps (2) using cardx by (intro xxne)\n      show \"finite (X - {x})\" using Suc.prems (3) by simp\n      show \"zero_collapsible (X - {x}) (cost x X K)\" using ccc .\n    qed\n    then obtain B where xxb: \"(X - {x}, B) \\<in> sorted_variables\" \n      and ec: \"evaluation B (cost x X K) \\<in> not_evaders\" by auto\n    from cl obtain y T where y: \"y \\<in> X - {x}\" and t: \"T \\<subseteq> powerset (X - {x} - {y})\" \n      and lc: \"link_ext x X K = T \\<union> {s. \\<exists>t\\<in>T. s = insert y t}\" unfolding cone_def\n      using x xxne by auto\n    have el: \"evaluation B (link_ext x X K) \\<in> not_evaders\"\n    proof (rule evaluation_cone_not_evaders)\n      show \"link_ext x X K \\<subseteq> powerset (X - {x})\" unfolding link_ext_def powerset_def by auto\n      show \"cone (X - {x}) (link_ext x X K)\" using cl .\n      show \"X - {x} \\<noteq> {}\" using y by blast\n      show \"finite (X - {x})\" using Suc.prems(3) by blast\n      show \"(X - {x}, B) \\<in> sorted_variables\" using xxb .\n    qed\n    show ?thesis\n    proof (rule exI [of _ \"x # B\"], rule conjI)\n      show \"(X, x # B) \\<in> sorted_variables\" using xxb x\n        by (metis DiffE insert_Diff sorted_variables.intros(2) singletonI)\n      show \"evaluation (x # B) K \\<in> not_evaders\"\n        unfolding evaluation.simps (3)\n      proof (rule not_evaders.intros (2))\n        show \"evaluation B (cost x (set (x # B)) K) \\<in> not_evaders\"\n          using ec\n          using \\<open>(X, x # B) \\<in> sorted_variables\\<close> sorted_variables_coherent by blast\n        show \"length (evaluation B (link_ext x (set (x # B)) K)) =\n          length (evaluation B (cost x (set (x # B)) K))\" by (rule length_evaluation_eq)\n        show \"evaluation B (link_ext x (set (x # B)) K) \\<in> not_evaders\"\n          using el\n          unfolding sorted_variables_coherent [OF \\<open>(X, x # B) \\<in> sorted_variables\\<close>, symmetric]\n          using evaluation.simps\n          using el\n          using \\<open>(X, x # B) \\<in> sorted_variables\\<close> sorted_variables_coherent by blast\n      qed\n    qed\n  next\n    case True\n    then obtain x where X: \"X = {x}\" by (rule card_1_singletonE)\n    show \"\\<exists>A. (X, A) \\<in> sorted_variables \\<and> evaluation A K \\<in> not_evaders\"\n    proof (unfold X, intro exI [of _ \"[x]\"], rule conjI)\n      show \"({x}, [x]) \\<in> sorted_variables\"\n        by (simp add: sorted_variables.intros(1) sorted_variables.intros(2))\n      show \"evaluation [x] K \\<in> not_evaders\"\n      proof -\n        from kne and Suc.prems (1)\n        have k_cases: \"K = {{}} \\<or> K = {{}, {x}} \\<or> K = {{x}}\"\n          unfolding X powerset_def\n          by (metis Suc.prems(1) X powerset_singleton_cases)\n        show ?thesis\n        proof (cases \"K = {{}}\")\n          case True note kee = True\n          have False\n            using Suc.prems(4) unfolding True X by auto\n          thus ?thesis by (rule ccontr)\n        next\n          case False note knee = False\n          show ?thesis\n          proof (cases \"K = {{}, {x}}\")\n            case True note kex = True\n            show ?thesis\n              using Suc.prems (4)\n              unfolding True X\n              unfolding evaluation.simps link_ext_def cost_def powerset_def \n              using not_evaders.intros [of \"[True]\"] \n              by auto (metis (no_types, lifting) \\<open>\\<And>l2. [True] = l2 \\<Longrightarrow> [True] @ l2 \\<in> not_evaders\\<close> bot.extremum empty_iff evaluation.simps(2) mem_Collect_eq)\n          next\n            case False\n            have kx: \"K = {{x}}\" using False kne knee k_cases by simp\n            have False \n              using Suc.prems(4) \n              unfolding X kx using zero_collapsible.simps (5) [of \"{x}\" x K] by simp\n            thus ?thesis by simp\n            qed\n          qed\n        qed\n      qed\n    qed\n  qed\nqed\n\nlocale vertex_set = fixes V :: \"nat set\"\nbegin\n\ndefinition upper_cc_s :: \"nat set set \\<Rightarrow> nat set set\"\n  where \"upper_cc_s X = (LEAST K. (V, K) \\<in> cc_s \\<and> X \\<subseteq> K)\"\n\ndefinition upper_cc_s_ex :: \"nat set set \\<Rightarrow> nat set set\"\n  where \"upper_cc_s_ex X = \\<Union>(powerset ` {x. x \\<in> X})\"\n\nlemma subset_upper_cc_s_ex: \"X \\<subseteq> upper_cc_s_ex X\" \n  unfolding upper_cc_s_ex_def powerset_def by auto\n\nlemma\n  pow_closed_upper_cc_s_ex:\n  \"pow_closed (upper_cc_s_ex X)\"\n  unfolding pow_closed_def upper_cc_s_ex_def powerset_def by auto\n\nlemma upper_cc_s_ex_idempotent:\n  \"upper_cc_s_ex (upper_cc_s_ex X) = upper_cc_s_ex X\"\n  unfolding pow_closed_def upper_cc_s_ex_def powerset_def by auto\n\nlemma\n  upper_cc_s_ex_min:\n  assumes x: \"X \\<subseteq> Y\" and y: \"pow_closed Y\"\n  shows \"upper_cc_s_ex X \\<subseteq> Y\"\n  using x y unfolding pow_closed_def upper_cc_s_ex_def powerset_def by auto\n\nlemma\n  upper_cc_s_ex_closed:\n  assumes v: \"V \\<noteq> {}\" and x: \"X \\<subseteq> powerset V\"\n  shows \"upper_cc_s_ex X \\<subseteq> powerset V\"\n  using x unfolding pow_closed_def upper_cc_s_ex_def powerset_def by auto\n\nlemma\n  upper_cc_s_ex_cc_s:\n  assumes v: \"V \\<noteq> {}\" and x: \"X \\<subseteq> powerset V\"\n  shows \"(V, upper_cc_s_ex X) \\<in> cc_s\" \nproof (rule cc_s.intros (3) [OF v, of \"upper_cc_s_ex X\"])\n  show \"upper_cc_s_ex X \\<subseteq> powerset V\" using upper_cc_s_ex_closed [OF v x] .\n  show \"pow_closed (upper_cc_s_ex X)\" using pow_closed_upper_cc_s_ex .\nqed\n\nlemma\n  powerset_cc_s:\n  assumes v: \"V \\<noteq> {}\"\n  shows \"(V, powerset V) \\<in> cc_s\"\n  unfolding powerset_def\n  using cc_s.intros (3) [OF v, of \"Pow V\"] \n  unfolding powerset_def pow_closed_def by auto\n\nlemma \"upper_cc_s {} = {}\" unfolding upper_cc_s_def \n  apply auto\n  by (metis Least_equality bot.extremum cc_s.intros(2) empty_iff)\n\nlemma\n  upper_cc_s_id:\n  assumes v: \"V \\<noteq> {}\" and c: \"(V, X) \\<in> cc_s\"\n  shows \"upper_cc_s X = X\" \n  unfolding upper_cc_s_def\n  by (metis (no_types, lifting) Least_equality c order_refl)\n\nlemma\n  exists_upper_cc_s:\n  assumes v: \"V \\<noteq> {}\" and x: \"X \\<subseteq> powerset V\"\n  shows \"\\<exists>K. (V, K) \\<in> cc_s \\<and> X \\<subseteq> K\"\nproof (rule exI [of _ \"upper_cc_s_ex X\"], rule conjI)\n  show \"(V, upper_cc_s_ex X) \\<in> cc_s\" by (rule upper_cc_s_ex_cc_s [OF v x])\n  show \"X \\<subseteq> upper_cc_s_ex X\" by (rule subset_upper_cc_s_ex)\nqed\n\ncorollary\n  upper_cc_s_subset:\n  assumes v: \"V \\<noteq> {}\" and x: \"X \\<subseteq> powerset V\"\n  shows \"X \\<subseteq> upper_cc_s X\"\n  unfolding upper_cc_s_def\nproof (rule LeastI2_order [of _ \"upper_cc_s_ex X\"], intro conjI)\n  show \"(V, upper_cc_s_ex X) \\<in> cc_s\" using upper_cc_s_ex_cc_s [OF v x] .\n  show \"X \\<subseteq> upper_cc_s_ex X\" by (rule subset_upper_cc_s_ex)\n  fix y\n  show \"(V, y) \\<in> cc_s \\<and> X \\<subseteq> y \\<Longrightarrow> upper_cc_s_ex X \\<subseteq> y\"\n    by (metis cc_s.cases empty_iff pow_closed_def upper_cc_s_ex_min)\n  fix x\n  show \"(V, x) \\<in> cc_s \\<and> X \\<subseteq> x \\<Longrightarrow> \\<forall>y. (V, y) \\<in> cc_s \\<and> X \\<subseteq> y \\<longrightarrow> x \\<subseteq> y \\<Longrightarrow> X \\<subseteq> x\" \n    by simp\nqed\n\nlemma\n  upper_cc_s_cc_s:\n  assumes v: \"V \\<noteq> {}\" and x: \"X \\<subseteq> powerset V\"\n  shows \"(V, upper_cc_s X) \\<in> cc_s\"\n  unfolding upper_cc_s_def\nproof (rule LeastI2_order [of _ \"upper_cc_s_ex X\"], intro conjI)\n  show \"(V, upper_cc_s_ex X) \\<in> cc_s\" using upper_cc_s_ex_cc_s [OF v x] .\n  show \"X \\<subseteq> upper_cc_s_ex X\" by (rule subset_upper_cc_s_ex)\n  fix y\n  show \"(V, y) \\<in> cc_s \\<and> X \\<subseteq> y \\<Longrightarrow> upper_cc_s_ex X \\<subseteq> y\"\n    by (metis cc_s.cases empty_iff pow_closed_def upper_cc_s_ex_min)\n  fix x\n  show \"(V, x) \\<in> cc_s \\<and> X \\<subseteq> x \\<Longrightarrow> \\<forall>y. (V, y) \\<in> cc_s \\<and> X \\<subseteq> y \\<longrightarrow> x \\<subseteq> y \\<Longrightarrow> (V, x) \\<in> cc_s\" \n    by simp\nqed\n\nlemma \"upper_cc_s_ex (cost 0 {0} {{0}}) = {}\"\n  unfolding upper_cc_s_ex_def cost_def powerset_def by auto\n\nlemma \"cost 0 {0} (upper_cc_s_ex {{0}}) = {{}}\"\n    unfolding upper_cc_s_ex_def cost_def powerset_def by auto\n\nlemma\n  assumes \"V \\<noteq> {}\"\n  shows \"upper_cc_s_ex (cost x V X) \\<subseteq> cost x V (upper_cc_s_ex X)\"\n  unfolding cost_def upper_cc_s_ex_def powerset_def by auto\n\nlemma\n  assumes \"V \\<noteq> {}\"\n  shows \"upper_cc_s_ex (link x V X) \\<subseteq> link x V (upper_cc_s_ex X)\"\n  unfolding link_def upper_cc_s_ex_def powerset_def by auto\n\nlemma \"upper_cc_s_ex (link 0 {0} {{0}}) = {}\"\n  unfolding upper_cc_s_ex_def link_def powerset_def by auto\n\nlemma \"link 0 {0} (upper_cc_s_ex {{0}}) = {{}}\"\n    unfolding upper_cc_s_ex_def link_def powerset_def by auto\n\nlemma \"upper_cc_s_ex (link_ext x V X) \\<subseteq> link_ext x V (upper_cc_s_ex X)\"\n  unfolding link_ext_def upper_cc_s_ex_def powerset_def by auto\n\nlemma \"link_ext 0 {0} (upper_cc_s_ex  {{1, 0}}) = {{}}\"\n  unfolding link_ext_def upper_cc_s_ex_def powerset_def by auto\n\nlemma \"upper_cc_s_ex (link_ext 0 {0} {{1, 0}}) = {}\"\n  unfolding link_ext_def upper_cc_s_ex_def powerset_def by auto\n\ndefinition lower_cc_s :: \"nat set set \\<Rightarrow> nat set set\"\n  where \"lower_cc_s X = (GREATEST K. (V, K) \\<in> cc_s \\<and> K \\<subseteq> X)\"\n\ndefinition lower_cc_s_ex :: \"nat set set \\<Rightarrow> nat set set\"\n  where \"lower_cc_s_ex X = {x. x \\<in> X \\<and> powerset x \\<subseteq> X}\"\n\nlemma subset_lower_cc_s_ex: \"lower_cc_s_ex X \\<subseteq> X\"\n  unfolding lower_cc_s_ex_def powerset_def by auto\n\nlemma \n  pow_closed_lower_cc_s_ex:\n  \"pow_closed (lower_cc_s_ex X)\"\n  unfolding pow_closed_def lower_cc_s_ex_def powerset_def by auto\n\nlemma\n  lower_cc_s_ex_idempotent:\n  \"lower_cc_s_ex (lower_cc_s_ex X) = lower_cc_s_ex X\"\n  unfolding pow_closed_def lower_cc_s_ex_def powerset_def by auto\n\nlemma\n  lower_cc_s_ex_min:\n  assumes x: \"Y \\<subseteq> X\" and y: \"pow_closed Y\"\n  shows \"Y \\<subseteq> lower_cc_s_ex X\"\n  using x y unfolding pow_closed_def lower_cc_s_ex_def powerset_def by auto\n\nlemma\n  lower_cc_s_ex_closed:\n  assumes v: \"V \\<noteq> {}\" and x: \"X \\<subseteq> powerset V\"\n  shows \"lower_cc_s_ex X \\<subseteq> powerset V\"\n  using x unfolding pow_closed_def lower_cc_s_ex_def powerset_def by auto\n\nlemma\n  lower_cc_s_ex_cc_s:\n  assumes v: \"V \\<noteq> {}\" and x: \"X \\<subseteq> powerset V\"\n  shows \"(V, lower_cc_s_ex X) \\<in> cc_s\" \nproof (rule cc_s.intros (3) [OF v, of \"lower_cc_s_ex X\"])\n  show \"lower_cc_s_ex X \\<subseteq> powerset V\" using lower_cc_s_ex_closed [OF v x] .\n  show \"pow_closed (lower_cc_s_ex X)\" using pow_closed_lower_cc_s_ex .\nqed\n\nlemma \"lower_cc_s {} = {}\" unfolding lower_cc_s_def \n  apply auto\n  by (metis (mono_tags, lifting) Greatest_equality cc_s.intros(2) dual_order.refl empty_iff)\n\nlemma\n  lower_cc_s_id:\n  assumes v: \"V \\<noteq> {}\" and c: \"(V, X) \\<in> cc_s\"\n  shows \"lower_cc_s X = X\" \n  unfolding lower_cc_s_def\n  by (metis (no_types, lifting) Greatest_equality c order_refl)\n\nlemma\n  exists_lower_cc_s:\n  assumes v: \"V \\<noteq> {}\" and x: \"X \\<subseteq> powerset V\"\n  shows \"\\<exists>K. (V, K) \\<in> cc_s \\<and> K \\<subseteq> X\"\nproof (rule exI [of _ \"lower_cc_s_ex X\"], rule conjI)\n  show \"(V, lower_cc_s_ex X) \\<in> cc_s\" by (rule lower_cc_s_ex_cc_s [OF v x])\n  show \"lower_cc_s_ex X \\<subseteq> X\" by (rule subset_lower_cc_s_ex)\nqed\n\ncorollary\n  lower_cc_s_subset:\n  assumes v: \"V \\<noteq> {}\" and x: \"X \\<subseteq> powerset V\"\n  shows \"lower_cc_s X \\<subseteq> X\"\n  unfolding lower_cc_s_def\nproof (rule GreatestI2_order [of _ \"lower_cc_s_ex X\"], intro conjI)\n  show \"(V, lower_cc_s_ex X) \\<in> cc_s\" using lower_cc_s_ex_cc_s [OF v x] .\n  show \"lower_cc_s_ex X \\<subseteq> X\" by (rule subset_lower_cc_s_ex)\n  fix x\n  show \"(V, x) \\<in> cc_s \\<and> x \\<subseteq> X \\<Longrightarrow> \\<forall>y. (V, y) \\<in> cc_s \\<and> y \\<subseteq> X \\<longrightarrow> y \\<subseteq> x \\<Longrightarrow> x \\<subseteq> X\"\n    by simp\n  fix y\n  show \"(V, y) \\<in> cc_s \\<and> y \\<subseteq> X \\<Longrightarrow> y \\<subseteq> lower_cc_s_ex X\"\n    by (metis cc_s.cases empty_iff pow_closed_def lower_cc_s_ex_min)\nqed\n\nlemma\n  lower_cc_s_cc_s:\n  assumes v: \"V \\<noteq> {}\" and x: \"X \\<subseteq> powerset V\"\n  shows \"(V, lower_cc_s X) \\<in> cc_s\"\n  unfolding lower_cc_s_def\nproof (rule GreatestI2_order [of _ \"lower_cc_s_ex X\"], intro conjI)\n  show \"(V, lower_cc_s_ex X) \\<in> cc_s\" using lower_cc_s_ex_cc_s [OF v x] .\n  show \"lower_cc_s_ex X \\<subseteq> X\" by (rule subset_lower_cc_s_ex)\n  fix y\n  show \"(V, y) \\<in> cc_s \\<and> y \\<subseteq> X \\<Longrightarrow> y \\<subseteq> lower_cc_s_ex X\"\n    by (metis cc_s.cases empty_iff pow_closed_def lower_cc_s_ex_min)\n  fix x\n  show \"(V, x) \\<in> cc_s \\<and> x \\<subseteq> X \\<Longrightarrow> \\<forall>y. (V, y) \\<in> cc_s \\<and> y \\<subseteq> X \\<longrightarrow> y \\<subseteq> x \\<Longrightarrow> (V, x) \\<in> cc_s\" \n    by simp\nqed\n\nlemma \"lower_cc_s_ex (cost 0 {0} {{0}}) = {}\"\n  unfolding lower_cc_s_ex_def cost_def powerset_def by auto\n\nlemma \"cost 0 {0} (lower_cc_s_ex {{0}}) = {}\"\n    unfolding lower_cc_s_ex_def cost_def powerset_def by auto\n\nlemma \"cost x V (lower_cc_s_ex X) = lower_cc_s_ex (cost x V X)\"\n  unfolding cost_def lower_cc_s_ex_def powerset_def by auto\n\nlemma \"link x V (lower_cc_s_ex X) \\<subseteq> lower_cc_s_ex (link x V X)\"\n  unfolding link_def lower_cc_s_ex_def powerset_def by auto\n\nlemma \"link_ext 0 {} (lower_cc_s_ex  {{0}}) = {}\"\n  unfolding link_ext_def lower_cc_s_ex_def powerset_def by auto\n\nlemma \"lower_cc_s_ex (link_ext 0 {} {{0}}) = {{}}\"\n  unfolding link_ext_def lower_cc_s_ex_def powerset_def by auto\n\n(*lemma\n  assumes \"V \\<noteq> {}\"\n  shows \"lower_cc_s_ex (link x V X) \\<subseteq> link x V (lower_cc_s_ex X)\"\n  unfolding link_def lower_cc_s_ex_def powerset_def\nproof\n  fix xa\n  assume xa: \"xa \\<in> {xa \\<in> {s \\<in> Pow (V - {x}). s \\<in> X \\<and> insert x s \\<in> X}.\n                Pow xa \\<subseteq> {s \\<in> Pow (V - {x}). s \\<in> X \\<and> insert x s \\<in> X}}\"\n  from xa have px: \"Pow xa \\<subseteq> X\" and pp: \"Pow xa \\<subseteq> Pow (V - {x})\" and ixxa: \"insert x xa \\<in> X\" \n    by auto\n  show \"xa \\<in> {s \\<in> Pow (V - {x}). s \\<in> {x \\<in> X. Pow x \\<subseteq> X} \\<and> insert x s \\<in> {x \\<in> X. Pow x \\<subseteq> X}}\"\n  proof (rule, intro conjI)\n    show \"xa \\<in> Pow (V - {x})\"\n      using xa by simp\n    show xa_pow_closed: \"xa \\<in> {x \\<in> X. Pow x \\<subseteq> X}\" using xa by auto\n    show \"insert x xa \\<in> {x \\<in> X. Pow x \\<subseteq> X}\"\n    proof (rule, intro conjI)\n      show \"insert x xa \\<in> X\" using xa by simp\n      show \"Pow (insert x xa) \\<subseteq> X\" \n      proof\n        fix xb\n        assume xb: \"xb \\<in> Pow (insert x xa)\"\n        show \"xb \\<in> X\"\n          proof (cases \"x \\<in> xb\")\n            case False\n            thus ?thesis using xb using px by auto\n          next\n            case True\n            thus ?thesis using xb using px using ixxa try\n*)\n\nend\n\nend", "meta": {"author": "jmaransay", "repo": "morse", "sha": "99d05d63fad13f5b4827f2f656ebbad989e90e09", "save_path": "github-repos/isabelle/jmaransay-morse", "path": "github-repos/isabelle/jmaransay-morse/morse-99d05d63fad13f5b4827f2f656ebbad989e90e09/BDT_ext.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8902942144788076, "lm_q2_score": 0.8080672204860317, "lm_q1q2_score": 0.7194175713086851}}
{"text": "theory boolean_algebra_infinitary\n  imports boolean_algebra\nbegin\n\nsubsection \\<open>Encoding infinitary Boolean operations\\<close>\n\n(**Our aim is to encode complete Boolean algebras (of propositions) which we can be used to\ninterpret quantified formulas (much in the spirit of Boolean-valued models for set theory).*)\n\n(**We start by defining infinite meet (infimum) and infinite join (supremum) operations,*)\ndefinition infimum:: \"('w \\<sigma> \\<Rightarrow> bool) \\<Rightarrow> 'w \\<sigma>\" (\"\\<^bold>\\<And>_\") \n  where \"\\<^bold>\\<And>S \\<equiv> \\<lambda>w. \\<forall>X. S X \\<longrightarrow> X w\"\ndefinition supremum::\"('w \\<sigma> \\<Rightarrow> bool) \\<Rightarrow> 'w \\<sigma>\" (\"\\<^bold>\\<Or>_\") \n  where \"\\<^bold>\\<Or>S \\<equiv> \\<lambda>w. \\<exists>X. S X  \\<and>  X w\"\n\nnamed_theorems iconn (*to group together definitions involving infinitary algebraic connectives*)\ndeclare infimum_def[iconn] supremum_def[iconn]\n\n(**and show that the encoded Boolean algebra is complete (as a lattice).*)\nabbreviation \"upper_bound U S \\<equiv> \\<forall>X. (S X) \\<longrightarrow> X \\<preceq> U\"\nabbreviation \"lower_bound L S \\<equiv> \\<forall>X. (S X) \\<longrightarrow> L \\<preceq> X\"\nabbreviation \"is_supremum U S \\<equiv> upper_bound U S \\<and> (\\<forall>X. upper_bound X S \\<longrightarrow> U \\<preceq> X)\"\nabbreviation \"is_infimum  L S \\<equiv> lower_bound L S \\<and> (\\<forall>X. lower_bound X S \\<longrightarrow> X \\<preceq> L)\"\n\nlemma sup_char: \"is_supremum \\<^bold>\\<Or>S S\" unfolding order supremum_def by auto\nlemma sup_ext: \"\\<forall>S. \\<exists>X. is_supremum X S\" unfolding order by (metis supremum_def)\nlemma inf_char: \"is_infimum \\<^bold>\\<And>S S\" unfolding order infimum_def by auto\nlemma inf_ext: \"\\<forall>S. \\<exists>X. is_infimum X S\" unfolding order by (metis infimum_def)\n\nabbreviation \"isEmpty S \\<equiv> \\<forall>x. \\<not>S x\"\nabbreviation \"nonEmpty S \\<equiv> \\<exists>x. S x\"\nabbreviation containment (infix \"\\<sqsubseteq>\" 100) \n  where \"D \\<sqsubseteq> S \\<equiv>  \\<forall>X. D X \\<longrightarrow> S X\" (*read as \"all Ds are contained in S\"*)\n\nlemma \"isEmpty S \\<Longrightarrow> \\<^bold>\\<And>S \\<approx> \\<^bold>\\<top>\" by (simp add: infimum_def setequ_char top_def)\nlemma \"isEmpty S \\<Longrightarrow> \\<^bold>\\<Or>S \\<approx> \\<^bold>\\<bottom>\" by (simp add: bottom_def setequ_char supremum_def)\n\n(**The property of being closed under arbitrary (resp. nonempty) supremum/infimum.*)\ndefinition \"infimum_closed S  \\<equiv> \\<forall>D. D \\<sqsubseteq> S \\<longrightarrow> S(\\<^bold>\\<And>D)\" (*observe that D can be empty*)\ndefinition \"supremum_closed S \\<equiv> \\<forall>D. D \\<sqsubseteq> S \\<longrightarrow> S(\\<^bold>\\<Or>D)\"\ndefinition \"infimum_closed' S  \\<equiv> \\<forall>D. nonEmpty D \\<and> D \\<sqsubseteq> S \\<longrightarrow> S(\\<^bold>\\<And>D)\"\ndefinition \"supremum_closed' S \\<equiv> \\<forall>D. nonEmpty D \\<and> D \\<sqsubseteq> S \\<longrightarrow> S(\\<^bold>\\<Or>D)\"\n\ndeclare infimum_closed_def[iconn]  supremum_closed_def[iconn]\n        infimum_closed'_def[iconn] supremum_closed'_def[iconn]\n\n(**Note that arbitrary infimum- (resp. supremum-) closed sets include the top (resp. bottom) element.*)\nlemma \"infimum_closed S \\<Longrightarrow> S \\<^bold>\\<top>\" unfolding infimum_closed_def infimum_def top_def by auto\nlemma \"supremum_closed S \\<Longrightarrow> S \\<^bold>\\<bottom>\" unfolding supremum_closed_def supremum_def bottom_def by auto\n(**However, the above does not hold for non-empty infimum- (resp. supremum-) closed sets.*)\nlemma \"infimum_closed' S \\<Longrightarrow> S \\<^bold>\\<top>\" nitpick oops\nlemma \"supremum_closed' S \\<Longrightarrow> S \\<^bold>\\<bottom>\" nitpick oops\n\n(**We have in fact the following characterizations for the notions above:*)\nlemma inf_closed_char: \"infimum_closed S = (infimum_closed' S \\<and> S \\<^bold>\\<top>)\" proof -\n  have l2r: \"infimum_closed S \\<Longrightarrow> (infimum_closed' S \\<and> S \\<^bold>\\<top>)\" unfolding infimum_closed'_def infimum_closed_def by (metis L10 L13 bottom_def infimum_def setequ_equ subset_def top_def)\n  have r2l: \"(infimum_closed' S \\<and> S \\<^bold>\\<top>) \\<Longrightarrow> infimum_closed S\" unfolding infimum_closed'_def infimum_closed_def by (metis L10 L13 inf_char setequ_equ)\n  from l2r r2l show ?thesis by blast\nqed\nlemma sup_closed_char: \"supremum_closed S = (supremum_closed' S \\<and> S \\<^bold>\\<bottom>)\" proof -\n  have l2r: \"supremum_closed S \\<Longrightarrow> (supremum_closed' S \\<and> S \\<^bold>\\<bottom>)\" unfolding supremum_closed'_def supremum_closed_def by (metis L14 L9 bottom_def setequ_equ sup_char)\n  have r2l: \"(supremum_closed' S \\<and> S \\<^bold>\\<bottom>) \\<Longrightarrow> supremum_closed S\" unfolding supremum_closed'_def supremum_closed_def by (metis L14 L9 setequ_equ sup_char)\n  from l2r r2l show ?thesis by blast\nqed\n\n(**We verify that being infimum-closed' (resp. supremum-closed') entails being meet-closed (resp. join-closed).*)\nlemma inf_meet_closed: \"\\<forall>S. infimum_closed' S \\<longrightarrow> meet_closed S\" proof -\n  { fix S::\"'w \\<sigma> \\<Rightarrow> bool\"\n    { assume inf_closed: \"infimum_closed' S\"\n      hence \"meet_closed S\" proof -\n        { fix X::\"'w \\<sigma>\" and Y::\"'w \\<sigma>\"\n          let ?D=\"\\<lambda>Z. Z=X \\<or> Z=Y\"\n          { assume \"S X \\<and> S Y\"\n            hence \"?D \\<sqsubseteq> S\" by simp\n            moreover have \"nonEmpty ?D\" by auto\n            ultimately have \"S(\\<^bold>\\<And>?D)\" using inf_closed infimum_closed'_def by (smt (z3))\n            hence \"S(\\<lambda>w. \\<forall>Z. (Z=X \\<or> Z=Y) \\<longrightarrow> Z w)\" unfolding infimum_def by simp\n            moreover have \"(\\<lambda>w. \\<forall>Z. (Z=X \\<or> Z=Y) \\<longrightarrow> Z w) = (\\<lambda>w. X w \\<and> Y w)\" by auto\n            ultimately have \"S(\\<lambda>w. X w \\<and> Y w)\" by simp\n          } hence \"(S X \\<and> S Y) \\<longrightarrow> S(X \\<^bold>\\<and> Y)\" unfolding conn by (rule impI)\n        } thus ?thesis unfolding meet_closed_def by simp  qed\n    } hence \"infimum_closed' S \\<longrightarrow> meet_closed S\" by simp\n  } thus ?thesis by (rule allI)\nqed\nlemma sup_join_closed: \"\\<forall>P. supremum_closed' P \\<longrightarrow> join_closed P\" proof -\n  { fix S::\"'w \\<sigma> \\<Rightarrow> bool\"\n    { assume sup_closed: \"supremum_closed' S\"\n      hence \"join_closed S\" proof -\n        { fix X::\"'w \\<sigma>\" and Y::\"'w \\<sigma>\"\n          let ?D=\"\\<lambda>Z. Z=X \\<or> Z=Y\"\n          { assume \"S X \\<and> S Y\"\n            hence \"?D \\<sqsubseteq> S\" by simp\n            moreover have \"nonEmpty ?D\" by auto\n            ultimately have \"S(\\<^bold>\\<Or>?D)\" using sup_closed supremum_closed'_def by (smt (z3))\n            hence \"S(\\<lambda>w. \\<exists>Z. (Z=X \\<or> Z=Y) \\<and> Z w)\" unfolding supremum_def by simp\n            moreover have \"(\\<lambda>w. \\<exists>Z. (Z=X \\<or> Z=Y) \\<and> Z w) = (\\<lambda>w. X w \\<or> Y w)\" by auto\n            ultimately have \"S(\\<lambda>w. X w \\<or> Y w)\" by simp\n          } hence \"(S X \\<and> S Y) \\<longrightarrow> S(X \\<^bold>\\<or> Y)\" unfolding conn by (rule impI)\n        } thus ?thesis unfolding join_closed_def by simp qed\n    } hence \"supremum_closed' S \\<longrightarrow> join_closed S\" by simp\n  } thus ?thesis by (rule allI)\nqed\n\n\nsubsection \\<open>Domains of propositions and ranges of functions\\<close>\n\n(**This useful construct returns for a given set of propositions the set of their complements.*)\ndefinition dom_compl::\"('w \\<sigma> \\<Rightarrow> bool) \\<Rightarrow> ('w \\<sigma> \\<Rightarrow> bool)\" (\"(_\\<^sup>-)\") \n  where \"D\\<^sup>- \\<equiv> \\<lambda>X. D(\\<^bold>\\<midarrow>X)\"\n\n(*We verify that the above definition is equivalent to the intended one.*)\nlemma dom_compl_char: \"D\\<^sup>- = (\\<lambda>X. \\<exists>Y. (D Y) \\<and> (X = \\<^bold>\\<midarrow>Y))\" unfolding dom_compl_def\n  by (metis (mono_tags) BA_cp compl_def setequ_def setequ_equ subset_def)\n\n(**This construct is in fact involutive.*)\nlemma dom_compl_invol: \"(D\\<^sup>-)\\<^sup>- = D\" by (simp add: BA_dn dom_compl_def)\n\n(**We can now check an infinite variant of the De Morgan laws,*)\nlemma iDM_a: \"\\<^bold>\\<midarrow>(\\<^bold>\\<And>S) \\<approx> \\<^bold>\\<Or>(S\\<^sup>-)\" unfolding order conn dom_compl_def infimum_def supremum_def using compl_def by force\nlemma iDM_b:\" \\<^bold>\\<midarrow>(\\<^bold>\\<Or>S) \\<approx> \\<^bold>\\<And>(S\\<^sup>-)\" unfolding order conn dom_compl_def infimum_def supremum_def using compl_def by force\n\n(**and that D and their complements are in a 1-1 correspondance*)\nlemma dom_compl_1to1: \"correspond1to1 D D\\<^sup>-\" by (metis (mono_tags, lifting) BA_dn dom_compl_def injectiveRel_def mapping_def surjectiveRel_def)\n\n(**as well as some useful dualities regarding the image of propositional functions (restricted wrt. a domain).*)\nlemma Ra_compl: \"\\<lbrakk>\\<pi>\\<^sup>c D\\<rbrakk>  = \\<lbrakk>\\<pi> D\\<rbrakk>\\<^sup>-\" unfolding img_dir_def dom_compl_char by (metis op_compl_def)\nlemma Ra_dual1: \"\\<lbrakk>\\<pi>\\<^sup>d D\\<rbrakk>  = \\<lbrakk>\\<pi> D\\<^sup>-\\<rbrakk>\\<^sup>-\" unfolding img_dir_def dom_compl_char by (metis op_dual_def)\nlemma Ra_dual2: \"\\<lbrakk>\\<pi>\\<^sup>d D\\<rbrakk>  = \\<lbrakk>\\<pi>\\<^sup>c D\\<^sup>-\\<rbrakk>\" unfolding img_dir_def dom_compl_char by (metis op_compl_def op_dual_def)\nlemma Ra_dual3: \"\\<lbrakk>\\<pi>\\<^sup>d D\\<rbrakk>\\<^sup>- = \\<lbrakk>\\<pi> D\\<^sup>-\\<rbrakk>\" by (metis Ra_compl Ra_dual2 comp_invol op_equal_equ)\nlemma Ra_dual4: \"\\<lbrakk>\\<pi>\\<^sup>d D\\<^sup>-\\<rbrakk> = \\<lbrakk>\\<pi> D\\<rbrakk>\\<^sup>-\" by (metis Ra_dual3 dual_invol op_equal_equ)\n\n(**We check some further properties:*)\nlemma fp_sup_inf_closed_dual': \"supremum_closed' (fp \\<phi>) \\<Longrightarrow> infimum_closed' (fp \\<phi>\\<^sup>d)\" unfolding supremum_closed'_def infimum_closed'_def by (metis dom_compl_char fp_d iDM_a setequ_equ)\nlemma fp_sup_inf_closed_dual: \"supremum_closed (fp \\<phi>) \\<Longrightarrow> infimum_closed (fp \\<phi>\\<^sup>d)\" by (simp add: bottom_def compl_def fp_d fp_sup_inf_closed_dual' inf_closed_char sup_closed_char top_def)\nlemma fp_inf_sup_closed_dual': \"infimum_closed' (fp \\<phi>) \\<Longrightarrow> supremum_closed' (fp \\<phi>\\<^sup>d)\" unfolding supremum_closed'_def infimum_closed'_def by (metis dom_compl_char fp_d iDM_b setequ_equ)\nlemma fp_inf_sup_closed_dual: \"infimum_closed (fp \\<phi>) \\<Longrightarrow> supremum_closed (fp \\<phi>\\<^sup>d)\" by (simp add: bottom_def compl_def fp_d fp_inf_sup_closed_dual' inf_closed_char sup_closed_char top_def)\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/TBAs/boolean_algebra_infinitary.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.890294223211224, "lm_q2_score": 0.8080672089305841, "lm_q1q2_score": 0.7194175680773163}}
{"text": "(*\n  File: Equipotent.thy\n  Author: Bohua Zhan\n\n  Equipotence (existence of bijective function) between two sets.\n*)\n\ntheory Equipotent\n  imports Functions Wfrec\nbegin\n\nsection \\<open>Gluing together two functions\\<close>\n\n(* Glue together two functions *)\ndefinition glue_function2 :: \"i \\<Rightarrow> i \\<Rightarrow> i\" where [rewrite]:\n  \"glue_function2(f,g) = Fun(source(f) \\<union> source(g), target(f) \\<union> target(g),\n     \\<lambda>x. if x \\<in> source(f) then f ` x else g ` x)\"\nsetup {* register_wellform_data (\"glue_function2(f,g)\", [\"source(f) \\<inter> source(g) = \\<emptyset>\"]) *}\n\nlemma glue_function2_is_function [typing]:\n  \"is_function(f) \\<Longrightarrow> is_function(g) \\<Longrightarrow>\n   glue_function2(f,g) \\<in> source(f) \\<union> source(g) \\<rightarrow> target(f) \\<union> target(g)\" by auto2\n\nlemma glue_function2_eval [rewrite]:\n  \"is_function(f) \\<Longrightarrow> is_function(g) \\<Longrightarrow> x \\<in> source(glue_function2(f,g)) \\<Longrightarrow>\n   glue_function2(f,g)`x = (if x \\<in> source(f) then f`x else g`x)\" by auto2\nsetup {* del_prfstep_thm @{thm glue_function2_def} *}\n\nlemma glue_function2_bij [backward]:\n  \"f \\<in> A \\<cong> B \\<Longrightarrow> g \\<in> C \\<cong> D \\<Longrightarrow> A \\<inter> C = \\<emptyset> \\<Longrightarrow> B \\<inter> D = \\<emptyset> \\<Longrightarrow>\n   glue_function2(f,g) \\<in> (A \\<union> C) \\<cong> (B \\<union> D)\"\n@proof\n  @have (@rule) \"\\<forall>y\\<in>B. \\<exists>x\\<in>A. f`x = y\"\n  @have (@rule) \"\\<forall>y\\<in>D. \\<exists>x\\<in>C. g`x = y\"\n@qed\n\nlemma glue_function2_image1 [rewrite]:\n  \"surjective(f) \\<Longrightarrow> is_function(g) \\<Longrightarrow> glue_function2(f,g) `` source(f) = target(f)\"\n@proof\n  @let \"h = glue_function2(f,g)\"\n  @have \"\\<forall>x. x \\<in> h``source(f) \\<longleftrightarrow> x \\<in> target(f)\" @with\n    @case \"x \\<in> h``source(f)\" @with\n      @obtain y where \"y \\<in> source(f)\" \"h`y = x\"\n    @end\n    @case \"x \\<in> target(f)\" @with\n      @obtain y where \"y \\<in> source(f)\" \"f`y = x\"\n      @have \"h`y = x\"\n    @end\n  @end\n@qed\n\nsection \\<open>Equipotent condition\\<close>\n\ndefinition equipotent :: \"i \\<Rightarrow> i \\<Rightarrow> o\"  (infix \"\\<approx>\\<^sub>S\" 50) where [rewrite]:\n  \"S \\<approx>\\<^sub>S T \\<longleftrightarrow> (\\<exists>f. f \\<in> S \\<cong> T)\"\n  \nlemma equipotentI [resolve]: \"f \\<in> S \\<cong> T \\<Longrightarrow> S \\<approx>\\<^sub>S T\" by auto2\nlemma equipotentE [backward]: \"S \\<approx>\\<^sub>S T \\<Longrightarrow> \\<exists>f. f \\<in> S \\<cong> T\" by auto2\nsetup {* del_prfstep_thm @{thm equipotent_def} *}\n\nlemma equipotent_refl [resolve]: \"X \\<approx>\\<^sub>S X\"\n@proof @have \"id_fun(X) \\<in> X \\<cong> X\" @qed\n\nlemma equipotent_sym [forward]: \"S \\<approx>\\<^sub>S T \\<Longrightarrow> T \\<approx>\\<^sub>S S\"\n@proof @obtain \"f \\<in> S \\<cong> T\" @have \"bijective(inverse(f))\" @qed\n\nlemma equipotent_trans [backward2]: \"S \\<approx>\\<^sub>S T \\<Longrightarrow> T \\<approx>\\<^sub>S U \\<Longrightarrow> S \\<approx>\\<^sub>S U\"\n@proof @obtain \"f \\<in> S \\<cong> T\" @obtain \"g \\<in> T \\<cong> U\" @have \"g \\<circ> f \\<in> S \\<cong> U\" @qed\n\nlemma equipotent_empty [forward]: \"X \\<approx>\\<^sub>S \\<emptyset> \\<Longrightarrow> X = \\<emptyset>\"\n@proof @obtain \"f \\<in> X \\<cong> \\<emptyset>\" @have \"X \\<rightarrow> \\<emptyset> \\<noteq> \\<emptyset>\" @qed\n\nlemma equipotent_singleton [resolve]: \"{a} \\<approx>\\<^sub>S {b}\"\n@proof @have \"Fun({a}, {b}, \\<lambda>x. b) \\<in> {a} \\<cong> {b}\" @qed\n\nlemma equipotent_union [backward1]:\n  \"A \\<inter> C = \\<emptyset> \\<Longrightarrow> B \\<inter> D = \\<emptyset> \\<Longrightarrow> A \\<approx>\\<^sub>S B \\<Longrightarrow> C \\<approx>\\<^sub>S D \\<Longrightarrow> A \\<union> C \\<approx>\\<^sub>S B \\<union> D\"\n@proof\n  @obtain \"f \\<in> A \\<cong> B\" @obtain \"g \\<in> C \\<cong> D\"\n  @have \"glue_function2(f,g) \\<in> (A \\<union> C) \\<cong> (B \\<union> D)\"\n@qed\n\nlemma equipotent_cons [backward1]:\n  \"x \\<notin> A \\<Longrightarrow> y \\<notin> B \\<Longrightarrow> A \\<approx>\\<^sub>S B \\<Longrightarrow> cons(x,A) \\<approx>\\<^sub>S cons(y,B)\"\n@proof\n  @have \"cons(x,A) = {x} \\<union> A\" @have \"cons(y,B) = {y} \\<union> B\"\n@qed\n\nlemma equipotent_minus1 [backward]:\n  \"a \\<in> S \\<Longrightarrow> b \\<in> S \\<Longrightarrow> S \\<midarrow> {a} \\<approx>\\<^sub>S S \\<midarrow> {b}\"\n@proof\n  @case \"a = b\"\n  @have \"a \\<in> S \\<midarrow> {b}\" @have \"b \\<in> S \\<midarrow> {a}\"\n  @let \"T = S \\<midarrow> {a} \\<midarrow> {b}\"\n  @have \"{b} \\<approx>\\<^sub>S {a}\"\n  @have \"S \\<midarrow> {a} = T \\<union> {b}\" @have \"S \\<midarrow> {b} = T \\<union> {a}\"\n@qed\n\nlemma equipotent_minus1_gen [backward2]:\n  \"A \\<approx>\\<^sub>S B \\<Longrightarrow> x \\<in> A \\<Longrightarrow> y \\<in> B \\<Longrightarrow> A \\<midarrow> {x} \\<approx>\\<^sub>S B \\<midarrow> {y}\"\n@proof\n  @obtain \"f \\<in> A \\<cong> B\"\n  @have (@rule) \"\\<forall>y'\\<in>B. \\<exists>x\\<in>A. f`x = y'\"\n  @have \"A \\<midarrow> {x} \\<approx>\\<^sub>S B \\<midarrow> {f`x}\" @with\n    @have \"func_restrict_image(func_restrict(f,A\\<midarrow>{x})) \\<in> A \\<midarrow> {x} \\<cong> B \\<midarrow> {f`x}\"\n  @end\n@qed\n\nsection \\<open>Ordering on cardinality\\<close>\n\ndefinition le_potent :: \"i \\<Rightarrow> i \\<Rightarrow> o\"  (infix \"\\<lesssim>\\<^sub>S\" 50) where [rewrite]:\n  \"S \\<lesssim>\\<^sub>S T \\<longleftrightarrow> (\\<exists>f\\<in>S\\<rightarrow>T. injective(f))\"\n\nlemma le_potentI [resolve]: \"injective(f) \\<Longrightarrow> f \\<in> A \\<rightarrow> B \\<Longrightarrow> A \\<lesssim>\\<^sub>S B\" by auto2\nlemma le_potentE [resolve]: \"S \\<lesssim>\\<^sub>S T \\<Longrightarrow> \\<exists>f\\<in>S\\<rightarrow>T. injective(f)\" by auto2\nsetup {* del_prfstep_thm @{thm le_potent_def} *}\n\ndefinition less_potent :: \"i \\<Rightarrow> i \\<Rightarrow> o\"  (infix \"\\<prec>\\<^sub>S\" 50) where [rewrite]:\n  \"S \\<prec>\\<^sub>S T \\<longleftrightarrow> (S \\<lesssim>\\<^sub>S T \\<and> \\<not>S \\<approx>\\<^sub>S T)\"\n\nlemma le_potent_trans [forward]:\n  \"A \\<lesssim>\\<^sub>S B \\<Longrightarrow> B \\<lesssim>\\<^sub>S C \\<Longrightarrow> A \\<lesssim>\\<^sub>S C\"\n@proof\n  @obtain \"f \\<in> A \\<rightarrow> B\" where \"injective(f)\"\n  @obtain \"g \\<in> B \\<rightarrow> C\" where \"injective(g)\"\n  @let \"h = g \\<circ> f\"\n  @have \"h \\<in> A \\<rightarrow> C\" @have \"injective(h)\"\n@qed\n\nlemma le_potent_eq_trans [forward]:\n  \"A \\<approx>\\<^sub>S B \\<Longrightarrow> B \\<lesssim>\\<^sub>S C \\<Longrightarrow> A \\<lesssim>\\<^sub>S C\"\n@proof\n  @obtain \"f \\<in> A \\<cong> B\"\n  @obtain \"g \\<in> B \\<rightarrow> C\" where \"injective(g)\"\n  @let \"h = g \\<circ> f\"\n  @have \"h \\<in> A \\<rightarrow> C\" @have \"injective(h)\"\n@qed\n\nlemma le_potent_trans_eq [forward]:\n  \"A \\<lesssim>\\<^sub>S B \\<Longrightarrow> B \\<approx>\\<^sub>S C \\<Longrightarrow> A \\<lesssim>\\<^sub>S C\"\n@proof\n  @obtain \"f \\<in> A \\<rightarrow> B\" where \"injective(f)\"\n  @obtain \"g \\<in> B \\<cong> C\"\n  @let \"h = g \\<circ> f\"\n  @have \"h \\<in> A \\<rightarrow> C\" @have \"injective(h)\"\n@qed\n\nlemma subset_le_potent [resolve]:\n  \"S \\<subseteq> T \\<Longrightarrow> S \\<lesssim>\\<^sub>S T\"\n@proof\n  @let \"f = Fun(S,T,\\<lambda>x. x)\"\n  @have \"injective(f)\" @have \"f \\<in> S \\<rightarrow> T\"\n@qed\n\nlemma pow_le_potent [resolve]:\n  \"S \\<lesssim>\\<^sub>S Pow(S)\"\n@proof\n  @let \"f = Fun(S,Pow(S),\\<lambda>x. {x})\"\n  @have \"injective(f)\" @have \"f \\<in> S \\<rightarrow> Pow(S)\"\n@qed\n\nsection \\<open>Schroeder-Bernstein Theorem\\<close>\n\nlemma schroeder_bernstein [forward]:\n  \"X \\<lesssim>\\<^sub>S Y \\<Longrightarrow> Y \\<lesssim>\\<^sub>S X \\<Longrightarrow> X \\<approx>\\<^sub>S Y\"\n@proof\n  @obtain \"f\\<in>X\\<rightarrow>Y\" where \"injective(f)\"\n  @obtain \"g\\<in>Y\\<rightarrow>X\" where \"injective(g)\"\n  @let \"X_A = lfp(X, \\<lambda>W. X \\<midarrow> g``(Y \\<midarrow> f``W))\"\n  @let \"X_B = X \\<midarrow> X_A\" \"Y_A = f``X_A\" \"Y_B = Y \\<midarrow> Y_A\"\n  @have \"X \\<midarrow> g``Y_B = X_A\"\n  @have \"g``Y_B = X_B\"\n  @let \"f' = func_restrict_image(func_restrict(f,X_A))\"\n  @let \"g' = func_restrict_image(func_restrict(g,Y_B))\"\n  @have \"glue_function2(f', inverse(g')) \\<in> (X_A \\<union> X_B) \\<cong> (Y_A \\<union> Y_B)\"\n  @have \"X = X_A \\<union> X_B\" @have \"Y = Y_A \\<union> Y_B\"\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/Equipotent.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8824278602705732, "lm_q2_score": 0.8152324960856175, "lm_q1q2_score": 0.7193838671438699}}
{"text": "(*  Title       : HTranscendental.thy\n    Author      : Jacques D. Fleuriot\n    Copyright   : 2001 University of Edinburgh\n\nConverted to Isar and polished by lcp\n*)\n\nsection{*Nonstandard Extensions of Transcendental Functions*}\n\ntheory HTranscendental\nimports Transcendental HSeries HDeriv\nbegin\n\ndefinition\n  exphr :: \"real => hypreal\" where\n    --{*define exponential function using standard part *}\n  \"exphr x =  st(sumhr (0, whn, %n. inverse(real (fact n)) * (x ^ n)))\"\n\ndefinition\n  sinhr :: \"real => hypreal\" where\n  \"sinhr x = st(sumhr (0, whn, %n. sin_coeff n * x ^ n))\"\n  \ndefinition\n  coshr :: \"real => hypreal\" where\n  \"coshr x = st(sumhr (0, whn, %n. cos_coeff n * x ^ n))\"\n\n\nsubsection{*Nonstandard Extension of Square Root Function*}\n\nlemma STAR_sqrt_zero [simp]: \"( *f* sqrt) 0 = 0\"\nby (simp add: starfun star_n_zero_num)\n\nlemma STAR_sqrt_one [simp]: \"( *f* sqrt) 1 = 1\"\nby (simp add: starfun star_n_one_num)\n\nlemma hypreal_sqrt_pow2_iff: \"(( *f* sqrt)(x) ^ 2 = x) = (0 \\<le> x)\"\napply (cases x)\napply (auto simp add: star_n_le star_n_zero_num starfun hrealpow star_n_eq_iff\n            simp del: hpowr_Suc power_Suc)\ndone\n\nlemma hypreal_sqrt_gt_zero_pow2: \"!!x. 0 < x ==> ( *f* sqrt) (x) ^ 2 = x\"\nby (transfer, simp)\n\nlemma hypreal_sqrt_pow2_gt_zero: \"0 < x ==> 0 < ( *f* sqrt) (x) ^ 2\"\nby (frule hypreal_sqrt_gt_zero_pow2, auto)\n\nlemma hypreal_sqrt_not_zero: \"0 < x ==> ( *f* sqrt) (x) \\<noteq> 0\"\napply (frule hypreal_sqrt_pow2_gt_zero)\napply (auto simp add: numeral_2_eq_2)\ndone\n\nlemma hypreal_inverse_sqrt_pow2:\n     \"0 < x ==> inverse (( *f* sqrt)(x)) ^ 2 = inverse x\"\napply (cut_tac n = 2 and a = \"( *f* sqrt) x\" in power_inverse [symmetric])\napply (auto dest: hypreal_sqrt_gt_zero_pow2)\ndone\n\nlemma hypreal_sqrt_mult_distrib: \n    \"!!x y. [|0 < x; 0 <y |] ==>\n      ( *f* sqrt)(x*y) = ( *f* sqrt)(x) * ( *f* sqrt)(y)\"\napply transfer\napply (auto intro: real_sqrt_mult_distrib) \ndone\n\nlemma hypreal_sqrt_mult_distrib2:\n     \"[|0\\<le>x; 0\\<le>y |] ==>  \n     ( *f* sqrt)(x*y) =  ( *f* sqrt)(x) * ( *f* sqrt)(y)\"\nby (auto intro: hypreal_sqrt_mult_distrib simp add: order_le_less)\n\nlemma hypreal_sqrt_approx_zero [simp]:\n     \"0 < x ==> (( *f* sqrt)(x) @= 0) = (x @= 0)\"\napply (auto simp add: mem_infmal_iff [symmetric])\napply (rule hypreal_sqrt_gt_zero_pow2 [THEN subst])\napply (auto intro: Infinitesimal_mult \n            dest!: hypreal_sqrt_gt_zero_pow2 [THEN ssubst] \n            simp add: numeral_2_eq_2)\ndone\n\nlemma hypreal_sqrt_approx_zero2 [simp]:\n     \"0 \\<le> x ==> (( *f* sqrt)(x) @= 0) = (x @= 0)\"\nby (auto simp add: order_le_less)\n\nlemma hypreal_sqrt_sum_squares [simp]:\n     \"(( *f* sqrt)(x*x + y*y + z*z) @= 0) = (x*x + y*y + z*z @= 0)\"\napply (rule hypreal_sqrt_approx_zero2)\napply (rule add_nonneg_nonneg)+\napply (auto)\ndone\n\nlemma hypreal_sqrt_sum_squares2 [simp]:\n     \"(( *f* sqrt)(x*x + y*y) @= 0) = (x*x + y*y @= 0)\"\napply (rule hypreal_sqrt_approx_zero2)\napply (rule add_nonneg_nonneg)\napply (auto)\ndone\n\nlemma hypreal_sqrt_gt_zero: \"!!x. 0 < x ==> 0 < ( *f* sqrt)(x)\"\napply transfer\napply (auto intro: real_sqrt_gt_zero)\ndone\n\nlemma hypreal_sqrt_ge_zero: \"0 \\<le> x ==> 0 \\<le> ( *f* sqrt)(x)\"\nby (auto intro: hypreal_sqrt_gt_zero simp add: order_le_less)\n\nlemma hypreal_sqrt_hrabs [simp]: \"!!x. ( *f* sqrt)(x\\<^sup>2) = abs(x)\"\nby (transfer, simp)\n\nlemma hypreal_sqrt_hrabs2 [simp]: \"!!x. ( *f* sqrt)(x*x) = abs(x)\"\nby (transfer, simp)\n\nlemma hypreal_sqrt_hyperpow_hrabs [simp]:\n     \"!!x. ( *f* sqrt)(x pow (hypnat_of_nat 2)) = abs(x)\"\nby (transfer, simp)\n\nlemma star_sqrt_HFinite: \"\\<lbrakk>x \\<in> HFinite; 0 \\<le> x\\<rbrakk> \\<Longrightarrow> ( *f* sqrt) x \\<in> HFinite\"\napply (rule HFinite_square_iff [THEN iffD1])\napply (simp only: hypreal_sqrt_mult_distrib2 [symmetric], simp) \ndone\n\nlemma st_hypreal_sqrt:\n     \"[| x \\<in> HFinite; 0 \\<le> x |] ==> st(( *f* sqrt) x) = ( *f* sqrt)(st x)\"\napply (rule power_inject_base [where n=1])\napply (auto intro!: st_zero_le hypreal_sqrt_ge_zero)\napply (rule st_mult [THEN subst])\napply (rule_tac [3] hypreal_sqrt_mult_distrib2 [THEN subst])\napply (rule_tac [5] hypreal_sqrt_mult_distrib2 [THEN subst])\napply (auto simp add: st_hrabs st_zero_le star_sqrt_HFinite)\ndone\n\nlemma hypreal_sqrt_sum_squares_ge1 [simp]: \"!!x y. x \\<le> ( *f* sqrt)(x\\<^sup>2 + y\\<^sup>2)\"\nby transfer (rule real_sqrt_sum_squares_ge1)\n\nlemma HFinite_hypreal_sqrt:\n     \"[| 0 \\<le> x; x \\<in> HFinite |] ==> ( *f* sqrt) x \\<in> HFinite\"\napply (auto simp add: order_le_less)\napply (rule HFinite_square_iff [THEN iffD1])\napply (drule hypreal_sqrt_gt_zero_pow2)\napply (simp add: numeral_2_eq_2)\ndone\n\nlemma HFinite_hypreal_sqrt_imp_HFinite:\n     \"[| 0 \\<le> x; ( *f* sqrt) x \\<in> HFinite |] ==> x \\<in> HFinite\"\napply (auto simp add: order_le_less)\napply (drule HFinite_square_iff [THEN iffD2])\napply (drule hypreal_sqrt_gt_zero_pow2)\napply (simp add: numeral_2_eq_2 del: HFinite_square_iff)\ndone\n\nlemma HFinite_hypreal_sqrt_iff [simp]:\n     \"0 \\<le> x ==> (( *f* sqrt) x \\<in> HFinite) = (x \\<in> HFinite)\"\nby (blast intro: HFinite_hypreal_sqrt HFinite_hypreal_sqrt_imp_HFinite)\n\nlemma HFinite_sqrt_sum_squares [simp]:\n     \"(( *f* sqrt)(x*x + y*y) \\<in> HFinite) = (x*x + y*y \\<in> HFinite)\"\napply (rule HFinite_hypreal_sqrt_iff)\napply (rule add_nonneg_nonneg)\napply (auto)\ndone\n\nlemma Infinitesimal_hypreal_sqrt:\n     \"[| 0 \\<le> x; x \\<in> Infinitesimal |] ==> ( *f* sqrt) x \\<in> Infinitesimal\"\napply (auto simp add: order_le_less)\napply (rule Infinitesimal_square_iff [THEN iffD2])\napply (drule hypreal_sqrt_gt_zero_pow2)\napply (simp add: numeral_2_eq_2)\ndone\n\nlemma Infinitesimal_hypreal_sqrt_imp_Infinitesimal:\n     \"[| 0 \\<le> x; ( *f* sqrt) x \\<in> Infinitesimal |] ==> x \\<in> Infinitesimal\"\napply (auto simp add: order_le_less)\napply (drule Infinitesimal_square_iff [THEN iffD1])\napply (drule hypreal_sqrt_gt_zero_pow2)\napply (simp add: numeral_2_eq_2 del: Infinitesimal_square_iff [symmetric])\ndone\n\nlemma Infinitesimal_hypreal_sqrt_iff [simp]:\n     \"0 \\<le> x ==> (( *f* sqrt) x \\<in> Infinitesimal) = (x \\<in> Infinitesimal)\"\nby (blast intro: Infinitesimal_hypreal_sqrt_imp_Infinitesimal Infinitesimal_hypreal_sqrt)\n\nlemma Infinitesimal_sqrt_sum_squares [simp]:\n     \"(( *f* sqrt)(x*x + y*y) \\<in> Infinitesimal) = (x*x + y*y \\<in> Infinitesimal)\"\napply (rule Infinitesimal_hypreal_sqrt_iff)\napply (rule add_nonneg_nonneg)\napply (auto)\ndone\n\nlemma HInfinite_hypreal_sqrt:\n     \"[| 0 \\<le> x; x \\<in> HInfinite |] ==> ( *f* sqrt) x \\<in> HInfinite\"\napply (auto simp add: order_le_less)\napply (rule HInfinite_square_iff [THEN iffD1])\napply (drule hypreal_sqrt_gt_zero_pow2)\napply (simp add: numeral_2_eq_2)\ndone\n\nlemma HInfinite_hypreal_sqrt_imp_HInfinite:\n     \"[| 0 \\<le> x; ( *f* sqrt) x \\<in> HInfinite |] ==> x \\<in> HInfinite\"\napply (auto simp add: order_le_less)\napply (drule HInfinite_square_iff [THEN iffD2])\napply (drule hypreal_sqrt_gt_zero_pow2)\napply (simp add: numeral_2_eq_2 del: HInfinite_square_iff)\ndone\n\nlemma HInfinite_hypreal_sqrt_iff [simp]:\n     \"0 \\<le> x ==> (( *f* sqrt) x \\<in> HInfinite) = (x \\<in> HInfinite)\"\nby (blast intro: HInfinite_hypreal_sqrt HInfinite_hypreal_sqrt_imp_HInfinite)\n\nlemma HInfinite_sqrt_sum_squares [simp]:\n     \"(( *f* sqrt)(x*x + y*y) \\<in> HInfinite) = (x*x + y*y \\<in> HInfinite)\"\napply (rule HInfinite_hypreal_sqrt_iff)\napply (rule add_nonneg_nonneg)\napply (auto)\ndone\n\nlemma HFinite_exp [simp]:\n     \"sumhr (0, whn, %n. inverse (real (fact n)) * x ^ n) \\<in> HFinite\"\nunfolding sumhr_app\napply (simp only: star_zero_def starfun2_star_of atLeast0LessThan)\napply (rule NSBseqD2)\napply (rule NSconvergent_NSBseq)\napply (rule convergent_NSconvergent_iff [THEN iffD1])\napply (rule summable_iff_convergent [THEN iffD1])\napply (rule summable_exp)\ndone\n\nlemma exphr_zero [simp]: \"exphr 0 = 1\"\napply (simp add: exphr_def sumhr_split_add [OF hypnat_one_less_hypnat_omega, symmetric])\napply (rule st_unique, simp)\napply (rule subst [where P=\"\\<lambda>x. 1 \\<approx> x\", OF _ approx_refl])\napply (rule rev_mp [OF hypnat_one_less_hypnat_omega])\napply (rule_tac x=\"whn\" in spec)\napply (unfold sumhr_app, transfer, simp add: power_0_left)\ndone\n\nlemma coshr_zero [simp]: \"coshr 0 = 1\"\napply (simp add: coshr_def sumhr_split_add\n                   [OF hypnat_one_less_hypnat_omega, symmetric]) \napply (rule st_unique, simp)\napply (rule subst [where P=\"\\<lambda>x. 1 \\<approx> x\", OF _ approx_refl])\napply (rule rev_mp [OF hypnat_one_less_hypnat_omega])\napply (rule_tac x=\"whn\" in spec)\napply (unfold sumhr_app, transfer, simp add: cos_coeff_def power_0_left)\ndone\n\nlemma STAR_exp_zero_approx_one [simp]: \"( *f* exp) (0::hypreal) @= 1\"\napply (subgoal_tac \"( *f* exp) (0::hypreal) = 1\", simp)\napply (transfer, simp)\ndone\n\nlemma STAR_exp_Infinitesimal: \"x \\<in> Infinitesimal ==> ( *f* exp) (x::hypreal) @= 1\"\napply (case_tac \"x = 0\")\napply (cut_tac [2] x = 0 in DERIV_exp)\napply (auto simp add: NSDERIV_DERIV_iff [symmetric] nsderiv_def)\napply (drule_tac x = x in bspec, auto)\napply (drule_tac c = x in approx_mult1)\napply (auto intro: Infinitesimal_subset_HFinite [THEN subsetD] \n            simp add: mult.assoc)\napply (rule approx_add_right_cancel [where d=\"-1\"])\napply (rule approx_sym [THEN [2] approx_trans2])\napply (auto simp add: mem_infmal_iff)\ndone\n\nlemma STAR_exp_epsilon [simp]: \"( *f* exp) epsilon @= 1\"\nby (auto intro: STAR_exp_Infinitesimal)\n\nlemma STAR_exp_add:\n  \"!!(x::'a:: {banach,real_normed_field} star) y. ( *f* exp)(x + y) = ( *f* exp) x * ( *f* exp) y\"\nby transfer (rule exp_add)\n\nlemma exphr_hypreal_of_real_exp_eq: \"exphr x = hypreal_of_real (exp x)\"\napply (simp add: exphr_def)\napply (rule st_unique, simp)\napply (subst starfunNat_sumr [symmetric])\nunfolding atLeast0LessThan\napply (rule NSLIMSEQ_D [THEN approx_sym])\napply (rule LIMSEQ_NSLIMSEQ)\napply (subst sums_def [symmetric])\napply (cut_tac exp_converges [where x=x], simp)\napply (rule HNatInfinite_whn)\ndone\n\nlemma starfun_exp_ge_add_one_self [simp]: \"!!x::hypreal. 0 \\<le> x ==> (1 + x) \\<le> ( *f* exp) x\"\nby transfer (rule exp_ge_add_one_self_aux)\n\n(* exp (oo) is infinite *)\nlemma starfun_exp_HInfinite:\n     \"[| x \\<in> HInfinite; 0 \\<le> x |] ==> ( *f* exp) (x::hypreal) \\<in> HInfinite\"\napply (frule starfun_exp_ge_add_one_self)\napply (rule HInfinite_ge_HInfinite, assumption)\napply (rule order_trans [of _ \"1+x\"], auto) \ndone\n\nlemma starfun_exp_minus:\n  \"!!x::'a:: {banach,real_normed_field} star. ( *f* exp) (-x) = inverse(( *f* exp) x)\"\nby transfer (rule exp_minus)\n\n(* exp (-oo) is infinitesimal *)\nlemma starfun_exp_Infinitesimal:\n     \"[| x \\<in> HInfinite; x \\<le> 0 |] ==> ( *f* exp) (x::hypreal) \\<in> Infinitesimal\"\napply (subgoal_tac \"\\<exists>y. x = - y\")\napply (rule_tac [2] x = \"- x\" in exI)\napply (auto intro!: HInfinite_inverse_Infinitesimal starfun_exp_HInfinite\n            simp add: starfun_exp_minus HInfinite_minus_iff)\ndone\n\nlemma starfun_exp_gt_one [simp]: \"!!x::hypreal. 0 < x ==> 1 < ( *f* exp) x\"\nby transfer (rule exp_gt_one)\n\nlemma starfun_ln_exp [simp]: \"!!x. ( *f* ln) (( *f* exp) x) = x\"\nby transfer (rule ln_exp)\n\nlemma starfun_exp_ln_iff [simp]: \"!!x. (( *f* exp)(( *f* ln) x) = x) = (0 < x)\"\nby transfer (rule exp_ln_iff)\n\nlemma starfun_exp_ln_eq: \"!!u x. ( *f* exp) u = x ==> ( *f* ln) x = u\"\nby transfer (rule ln_unique)\n\nlemma starfun_ln_less_self [simp]: \"!!x. 0 < x ==> ( *f* ln) x < x\"\nby transfer (rule ln_less_self)\n\nlemma starfun_ln_ge_zero [simp]: \"!!x. 1 \\<le> x ==> 0 \\<le> ( *f* ln) x\"\nby transfer (rule ln_ge_zero)\n\nlemma starfun_ln_gt_zero [simp]: \"!!x .1 < x ==> 0 < ( *f* ln) x\"\nby transfer (rule ln_gt_zero)\n\nlemma starfun_ln_not_eq_zero [simp]: \"!!x. [| 0 < x; x \\<noteq> 1 |] ==> ( *f* ln) x \\<noteq> 0\"\nby transfer simp\n\nlemma starfun_ln_HFinite: \"[| x \\<in> HFinite; 1 \\<le> x |] ==> ( *f* ln) x \\<in> HFinite\"\napply (rule HFinite_bounded)\napply assumption \napply (simp_all add: starfun_ln_less_self order_less_imp_le)\ndone\n\nlemma starfun_ln_inverse: \"!!x. 0 < x ==> ( *f* ln) (inverse x) = -( *f* ln) x\"\nby transfer (rule ln_inverse)\n\nlemma starfun_abs_exp_cancel: \"\\<And>x. \\<bar>( *f* exp) (x::hypreal)\\<bar> = ( *f* exp) x\"\nby transfer (rule abs_exp_cancel)\n\nlemma starfun_exp_less_mono: \"\\<And>x y::hypreal. x < y \\<Longrightarrow> ( *f* exp) x < ( *f* exp) y\"\nby transfer (rule exp_less_mono)\n\nlemma starfun_exp_HFinite: \"x \\<in> HFinite ==> ( *f* exp) (x::hypreal) \\<in> HFinite\"\napply (auto simp add: HFinite_def, rename_tac u)\napply (rule_tac x=\"( *f* exp) u\" in rev_bexI)\napply (simp add: Reals_eq_Standard)\napply (simp add: starfun_abs_exp_cancel)\napply (simp add: starfun_exp_less_mono)\ndone\n\nlemma starfun_exp_add_HFinite_Infinitesimal_approx:\n     \"[|x \\<in> Infinitesimal; z \\<in> HFinite |] ==> ( *f* exp) (z + x::hypreal) @= ( *f* exp) z\"\napply (simp add: STAR_exp_add)\napply (frule STAR_exp_Infinitesimal)\napply (drule approx_mult2)\napply (auto intro: starfun_exp_HFinite)\ndone\n\n(* using previous result to get to result *)\nlemma starfun_ln_HInfinite:\n     \"[| x \\<in> HInfinite; 0 < x |] ==> ( *f* ln) x \\<in> HInfinite\"\napply (rule ccontr, drule HFinite_HInfinite_iff [THEN iffD2])\napply (drule starfun_exp_HFinite)\napply (simp add: starfun_exp_ln_iff [THEN iffD2] HFinite_HInfinite_iff)\ndone\n\nlemma starfun_exp_HInfinite_Infinitesimal_disj:\n \"x \\<in> HInfinite ==> ( *f* exp) x \\<in> HInfinite | ( *f* exp) (x::hypreal) \\<in> Infinitesimal\"\napply (insert linorder_linear [of x 0]) \napply (auto intro: starfun_exp_HInfinite starfun_exp_Infinitesimal)\ndone\n\n(* check out this proof!!! *)\nlemma starfun_ln_HFinite_not_Infinitesimal:\n     \"[| x \\<in> HFinite - Infinitesimal; 0 < x |] ==> ( *f* ln) x \\<in> HFinite\"\napply (rule ccontr, drule HInfinite_HFinite_iff [THEN iffD2])\napply (drule starfun_exp_HInfinite_Infinitesimal_disj)\napply (simp add: starfun_exp_ln_iff [symmetric] HInfinite_HFinite_iff\n            del: starfun_exp_ln_iff)\ndone\n\n(* we do proof by considering ln of 1/x *)\nlemma starfun_ln_Infinitesimal_HInfinite:\n     \"[| x \\<in> Infinitesimal; 0 < x |] ==> ( *f* ln) x \\<in> HInfinite\"\napply (drule Infinitesimal_inverse_HInfinite)\napply (frule positive_imp_inverse_positive)\napply (drule_tac [2] starfun_ln_HInfinite)\napply (auto simp add: starfun_ln_inverse HInfinite_minus_iff)\ndone\n\nlemma starfun_ln_less_zero: \"!!x. [| 0 < x; x < 1 |] ==> ( *f* ln) x < 0\"\nby transfer (rule ln_less_zero)\n\nlemma starfun_ln_Infinitesimal_less_zero:\n     \"[| x \\<in> Infinitesimal; 0 < x |] ==> ( *f* ln) x < 0\"\nby (auto intro!: starfun_ln_less_zero simp add: Infinitesimal_def)\n\nlemma starfun_ln_HInfinite_gt_zero:\n     \"[| x \\<in> HInfinite; 0 < x |] ==> 0 < ( *f* ln) x\"\nby (auto intro!: starfun_ln_gt_zero simp add: HInfinite_def)\n\n\n(*\nGoalw [NSLIM_def] \"(%h. ((x powr h) - 1) / h) -- 0 --NS> ln x\"\n*)\n\nlemma HFinite_sin [simp]: \"sumhr (0, whn, %n. sin_coeff n * x ^ n) \\<in> HFinite\"\nunfolding sumhr_app\napply (simp only: star_zero_def starfun2_star_of atLeast0LessThan)\napply (rule NSBseqD2)\napply (rule NSconvergent_NSBseq)\napply (rule convergent_NSconvergent_iff [THEN iffD1])\napply (rule summable_iff_convergent [THEN iffD1])\napply (rule summable_sin)\ndone\n\nlemma STAR_sin_zero [simp]: \"( *f* sin) 0 = 0\"\nby transfer (rule sin_zero)\n\nlemma STAR_sin_Infinitesimal [simp]: \"x \\<in> Infinitesimal ==> ( *f* sin) x @= x\"\napply (case_tac \"x = 0\")\napply (cut_tac [2] x = 0 in DERIV_sin)\napply (auto simp add: NSDERIV_DERIV_iff [symmetric] nsderiv_def)\napply (drule bspec [where x = x], auto)\napply (drule approx_mult1 [where c = x])\napply (auto intro: Infinitesimal_subset_HFinite [THEN subsetD]\n           simp add: mult.assoc)\ndone\n\nlemma HFinite_cos [simp]: \"sumhr (0, whn, %n. cos_coeff n * x ^ n) \\<in> HFinite\"\nunfolding sumhr_app\napply (simp only: star_zero_def starfun2_star_of atLeast0LessThan)\napply (rule NSBseqD2)\napply (rule NSconvergent_NSBseq)\napply (rule convergent_NSconvergent_iff [THEN iffD1])\napply (rule summable_iff_convergent [THEN iffD1])\napply (rule summable_cos)\ndone\n\nlemma STAR_cos_zero [simp]: \"( *f* cos) 0 = 1\"\nby transfer (rule cos_zero)\n\nlemma STAR_cos_Infinitesimal [simp]: \"x \\<in> Infinitesimal ==> ( *f* cos) x @= 1\"\napply (case_tac \"x = 0\")\napply (cut_tac [2] x = 0 in DERIV_cos)\napply (auto simp add: NSDERIV_DERIV_iff [symmetric] nsderiv_def)\napply (drule bspec [where x = x])\napply auto\napply (drule approx_mult1 [where c = x])\napply (auto intro: Infinitesimal_subset_HFinite [THEN subsetD]\n            simp add: mult.assoc)\napply (rule approx_add_right_cancel [where d = \"-1\"])\napply simp\ndone\n\nlemma STAR_tan_zero [simp]: \"( *f* tan) 0 = 0\"\nby transfer (rule tan_zero)\n\nlemma STAR_tan_Infinitesimal: \"x \\<in> Infinitesimal ==> ( *f* tan) x @= x\"\napply (case_tac \"x = 0\")\napply (cut_tac [2] x = 0 in DERIV_tan)\napply (auto simp add: NSDERIV_DERIV_iff [symmetric] nsderiv_def)\napply (drule bspec [where x = x], auto)\napply (drule approx_mult1 [where c = x])\napply (auto intro: Infinitesimal_subset_HFinite [THEN subsetD]\n             simp add: mult.assoc)\ndone\n\nlemma STAR_sin_cos_Infinitesimal_mult:\n     \"x \\<in> Infinitesimal ==> ( *f* sin) x * ( *f* cos) x @= x\"\napply (insert approx_mult_HFinite [of \"( *f* sin) x\" _ \"( *f* cos) x\" 1]) \napply (simp add: Infinitesimal_subset_HFinite [THEN subsetD])\ndone\n\nlemma HFinite_pi: \"hypreal_of_real pi \\<in> HFinite\"\nby simp\n\n(* lemmas *)\n\nlemma lemma_split_hypreal_of_real:\n     \"N \\<in> HNatInfinite  \n      ==> hypreal_of_real a =  \n          hypreal_of_hypnat N * (inverse(hypreal_of_hypnat N) * hypreal_of_real a)\"\nby (simp add: mult.assoc [symmetric] zero_less_HNatInfinite)\n\nlemma STAR_sin_Infinitesimal_divide:\n     \"[|x \\<in> Infinitesimal; x \\<noteq> 0 |] ==> ( *f* sin) x/x @= 1\"\napply (cut_tac x = 0 in DERIV_sin)\napply (simp add: NSDERIV_DERIV_iff [symmetric] nsderiv_def)\ndone\n\n(*------------------------------------------------------------------------*) \n(* sin* (1/n) * 1/(1/n) @= 1 for n = oo                                   *)\n(*------------------------------------------------------------------------*)\n\nlemma lemma_sin_pi:\n     \"n \\<in> HNatInfinite  \n      ==> ( *f* sin) (inverse (hypreal_of_hypnat n))/(inverse (hypreal_of_hypnat n)) @= 1\"\napply (rule STAR_sin_Infinitesimal_divide)\napply (auto simp add: zero_less_HNatInfinite)\ndone\n\nlemma STAR_sin_inverse_HNatInfinite:\n     \"n \\<in> HNatInfinite  \n      ==> ( *f* sin) (inverse (hypreal_of_hypnat n)) * hypreal_of_hypnat n @= 1\"\napply (frule lemma_sin_pi)\napply (simp add: divide_inverse)\ndone\n\nlemma Infinitesimal_pi_divide_HNatInfinite: \n     \"N \\<in> HNatInfinite  \n      ==> hypreal_of_real pi/(hypreal_of_hypnat N) \\<in> Infinitesimal\"\napply (simp add: divide_inverse)\napply (auto intro: Infinitesimal_HFinite_mult2)\ndone\n\nlemma pi_divide_HNatInfinite_not_zero [simp]:\n     \"N \\<in> HNatInfinite ==> hypreal_of_real pi/(hypreal_of_hypnat N) \\<noteq> 0\"\nby (simp add: zero_less_HNatInfinite)\n\nlemma STAR_sin_pi_divide_HNatInfinite_approx_pi:\n     \"n \\<in> HNatInfinite  \n      ==> ( *f* sin) (hypreal_of_real pi/(hypreal_of_hypnat n)) * hypreal_of_hypnat n  \n          @= hypreal_of_real pi\"\napply (frule STAR_sin_Infinitesimal_divide\n               [OF Infinitesimal_pi_divide_HNatInfinite \n                   pi_divide_HNatInfinite_not_zero])\napply (auto)\napply (rule approx_SReal_mult_cancel [of \"inverse (hypreal_of_real pi)\"])\napply (auto intro: Reals_inverse simp add: divide_inverse ac_simps)\ndone\n\nlemma STAR_sin_pi_divide_HNatInfinite_approx_pi2:\n     \"n \\<in> HNatInfinite  \n      ==> hypreal_of_hypnat n *  \n          ( *f* sin) (hypreal_of_real pi/(hypreal_of_hypnat n))  \n          @= hypreal_of_real pi\"\napply (rule mult.commute [THEN subst])\napply (erule STAR_sin_pi_divide_HNatInfinite_approx_pi)\ndone\n\nlemma starfunNat_pi_divide_n_Infinitesimal: \n     \"N \\<in> HNatInfinite ==> ( *f* (%x. pi / real x)) N \\<in> Infinitesimal\"\nby (auto intro!: Infinitesimal_HFinite_mult2 \n         simp add: starfun_mult [symmetric] divide_inverse\n                   starfun_inverse [symmetric] starfunNat_real_of_nat)\n\nlemma STAR_sin_pi_divide_n_approx:\n     \"N \\<in> HNatInfinite ==>  \n      ( *f* sin) (( *f* (%x. pi / real x)) N) @=  \n      hypreal_of_real pi/(hypreal_of_hypnat N)\"\napply (simp add: starfunNat_real_of_nat [symmetric])\napply (rule STAR_sin_Infinitesimal)\napply (simp add: divide_inverse)\napply (rule Infinitesimal_HFinite_mult2)\napply (subst starfun_inverse)\napply (erule starfunNat_inverse_real_of_nat_Infinitesimal)\napply simp\ndone\n\nlemma NSLIMSEQ_sin_pi: \"(%n. real n * sin (pi / real n)) ----NS> pi\"\napply (auto simp add: NSLIMSEQ_def starfun_mult [symmetric] starfunNat_real_of_nat)\napply (rule_tac f1 = sin in starfun_o2 [THEN subst])\napply (auto simp add: starfun_mult [symmetric] starfunNat_real_of_nat divide_inverse)\napply (rule_tac f1 = inverse in starfun_o2 [THEN subst])\napply (auto dest: STAR_sin_pi_divide_HNatInfinite_approx_pi \n            simp add: starfunNat_real_of_nat mult.commute divide_inverse)\ndone\n\nlemma NSLIMSEQ_cos_one: \"(%n. cos (pi / real n))----NS> 1\"\napply (simp add: NSLIMSEQ_def, auto)\napply (rule_tac f1 = cos in starfun_o2 [THEN subst])\napply (rule STAR_cos_Infinitesimal)\napply (auto intro!: Infinitesimal_HFinite_mult2 \n            simp add: starfun_mult [symmetric] divide_inverse\n                      starfun_inverse [symmetric] starfunNat_real_of_nat)\ndone\n\nlemma NSLIMSEQ_sin_cos_pi:\n     \"(%n. real n * sin (pi / real n) * cos (pi / real n)) ----NS> pi\"\nby (insert NSLIMSEQ_mult [OF NSLIMSEQ_sin_pi NSLIMSEQ_cos_one], simp)\n\n\ntext{*A familiar approximation to @{term \"cos x\"} when @{term x} is small*}\n\nlemma STAR_cos_Infinitesimal_approx:\n     \"x \\<in> Infinitesimal ==> ( *f* cos) x @= 1 - x\\<^sup>2\"\napply (rule STAR_cos_Infinitesimal [THEN approx_trans])\napply (auto simp add: Infinitesimal_approx_minus [symmetric] \n            add.assoc [symmetric] numeral_2_eq_2)\ndone\n\nlemma STAR_cos_Infinitesimal_approx2:\n     \"x \\<in> Infinitesimal ==> ( *f* cos) x @= 1 - (x\\<^sup>2)/2\"\napply (rule STAR_cos_Infinitesimal [THEN approx_trans])\napply (auto intro: Infinitesimal_SReal_divide \n            simp add: Infinitesimal_approx_minus [symmetric] numeral_2_eq_2)\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/NSA/HTranscendental.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278726384089, "lm_q2_score": 0.8152324826183822, "lm_q1q2_score": 0.7193838653426677}}
{"text": "section\\<open>Algebra problems\\<close>\n\nsubsection \\<open>IMO 2006 SL - A2\\<close>\n\ntheory IMO_2006_SL_A2_sol\nimports Complex_Main\nbegin\n\nlemma sum_remove_zero:\n  fixes n :: nat\n  assumes \"n > 0\"\n  shows \"(\\<Sum> k < n. f k) = f 0 + (\\<Sum> k \\<in> {1..<n}. f k)\"\n  using assms\n  by (simp add: atLeast1_lessThan_eq_remove0 sum.remove)\n\ntheorem IMO_2006_SL_A2:\n  fixes a :: \"nat \\<Rightarrow> real\"\n  assumes \"a 0 = -1\" \"\\<forall> n \\<ge> 1. (\\<Sum> k < n + 1. a (n - k) / (k + 1)) = 0\" \"n \\<ge> 1\"\n  shows \"a n > 0\"\n  using \\<open>n \\<ge> 1\\<close>\nproof (induction n rule: less_induct)\n  case (less n)\n  show ?case\n  proof cases\n    assume \"n = 1\"\n    have \"a 1 = 1/2\"\n      using assms\n      by auto\n    with \\<open>n = 1\\<close> show ?thesis \n      by simp\n  next\n    assume \"n \\<noteq> 1\"\n    with \\<open>n \\<ge> 1\\<close> have \"n > 1\"\n      by simp\n\n    have \"0 = (n + 1) * (\\<Sum> k < n + 1. a k / (n + 1 - k)) - n * (\\<Sum> k < n. a k / (n - k))\"\n    proof-\n      have \"(\\<Sum> k < n. a k / (n - k)) = 0\"\n        using assms(2)[rule_format, of \"n - 1\"] \\<open>n > 1\\<close> \n              sum.nat_diff_reindex[of \"\\<lambda> k. a k / (n - k)\" \"n\"]\n        by simp\n\n      moreover\n\n      have \"(\\<Sum> k < n + 1. a k / (n + 1 - k)) = 0\"\n        using assms(2)[rule_format, of \"n\"] \\<open>n > 1\\<close>\n              sum.nat_diff_reindex[of \"\\<lambda> k. a k / (n + 1 - k)\" \"n + 1\"]\n        by simp\n\n      ultimately\n      show ?thesis\n        by simp\n    qed\n    then have \"(n + 1) * a n = - (\\<Sum> k < n. ((n + 1) / (n + 1 - k) - n / (n - k)) * a k)\"\n      by (simp add: algebra_simps sum_distrib_left sum_subtractf)\n    then have \"(n + 1) * a n = (\\<Sum> k < n. (n / (n - k) - (n + 1) / (n + 1 - k)) * a k)\"\n      by (simp add: algebra_simps sum_negf[symmetric])\n    also have \"... = (\\<Sum> k \\<in> {1..<n}. (n / (n - k) - (n + 1) / (n + 1 - k)) * a k)\"\n      using \\<open>n > 1\\<close> \n      by (subst sum_remove_zero, auto)\n    also have \"... > 0\"\n    proof (rule sum_pos)\n      show \"finite {1..<n}\"\n        by simp\n    next\n      show \"{1..<n} \\<noteq> {}\"\n        using \\<open>n > 1\\<close>\n        by simp\n    next\n      fix i\n      assume \"i \\<in> {1..<n}\"\n      show \"(n / (n - i) - (n + 1) / (n + 1 - i)) * a i > 0\" (is \"?c * a i > 0\")\n      proof-\n        have \"a i > 0\" using less \\<open>i \\<in> {1..<n}\\<close> by simp\n\n        moreover have \"?c > 0\"\n        proof-\n          have \"?c = i / ((n - i) * (n + 1 - i))\"\n            using \\<open>i \\<in> {1..<n}\\<close>\n            by (simp add: field_simps of_nat_diff)\n          then show ?thesis\n            using \\<open>i \\<in> {1..<n}\\<close>\n            by simp\n        qed\n\n        ultimately show ?thesis by simp\n      qed\n    qed\n    finally have \"(n + 1) * a n > 0\"\n      .\n    then show ?thesis\n      by (smt mult_nonneg_nonpos of_nat_0_le_iff)\n  qed                             \nqed\n\nend", "meta": {"author": "filipmaric", "repo": "IMO", "sha": "9fb602bf4fd5bcb5890361d194a4fb423ac266e2", "save_path": "github-repos/isabelle/filipmaric-IMO", "path": "github-repos/isabelle/filipmaric-IMO/IMO-9fb602bf4fd5bcb5890361d194a4fb423ac266e2/IMO_files/solutions/IMO_2006_SL_A2_sol.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278602705731, "lm_q2_score": 0.8152324938410784, "lm_q1q2_score": 0.7193838651632259}}
{"text": "theory Chap3\nimports Main\nbegin\n\ntype_synonym vname = string\ntype_synonym val = int\ntype_synonym state = \"vname \\<Rightarrow> val\"\n\ndatatype aexp =\n  N val |\n  V vname |\n  Plus aexp aexp\n\n\n\ndefinition null_state (\"<>\") where\n  \"null_state \\<equiv> \\<lambda>x. 0\"\nsyntax\n  \"_State\" :: \"updbinds => 'a\" (\"<_>\")\ntranslations\n  \"_State ms\" == \"_Update <> ms\"\n\nvalue \"aval (Plus (V ''x'') (N 5)) <''x'' := 7>\"\n\n\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\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 )\ndone\n\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 )\ndone\n\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 \"assimp_correct\" : \"aval ( asimp a ) s = aval a s\"\n  apply ( induction a )\n  apply ( auto simp add: aval_plus )\ndone\n\n\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 \\<and>  optimal a2 )\"\n\nlemma \"optimal ( asimp_const a )\"\n  apply ( induction a )\n  apply ( auto split: aexp.split)\ndone\n\n\n\n\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 ) =\n    ( case ( full_asimp a1 , full_asimp a2 ) of\n      ( N n1              , N n2 )              \\<Rightarrow> ( N ( n1 + n2 ) ) |\n      ( N n               , V y  )              \\<Rightarrow> ( Plus ( V y ) ( N n ) ) |\n      ( N n1              , Plus a2' ( N n2 ) ) \\<Rightarrow> ( Plus a2' (N  (n1 + n2)) ) |\n      ( N n               , Plus a21 a22 )      \\<Rightarrow> ( Plus ( Plus a21 a22 ) ( N n ) ) |\n      ( V x               , N n  )              \\<Rightarrow> ( Plus ( V x ) ( N n ) ) |\n      ( V x               , V y  )              \\<Rightarrow> ( Plus ( V x ) ( V y ) ) |\n      ( V x               , Plus a2' ( N n2 ) ) \\<Rightarrow> ( Plus ( Plus ( V x ) a2' ) ( N  n2 ) ) |\n      ( V x               , Plus a21 a22 )      \\<Rightarrow> ( Plus ( V x ) ( Plus a21 a22 ) ) |\n      ( Plus a1' ( N n1 ) , N n2 )              \\<Rightarrow> ( Plus a1' ( N ( n1 + n2 ) ) ) |\n      ( Plus a1' ( N n )  , V x  )              \\<Rightarrow> ( Plus ( Plus a1' ( V x ) ) ( N n ) ) |\n      ( Plus a1' ( N n1 ) , Plus a2' ( N n2 ) ) \\<Rightarrow> ( Plus ( Plus a1' a2' ) (N  (n1 + n2)) ) |\n      ( Plus a1' ( N n )  , Plus a21 a22)       \\<Rightarrow> ( Plus ( Plus a1' ( Plus a21 a22 ) ) ( N n ) ) |\n      ( Plus a11 a12      , N n  )              \\<Rightarrow> ( Plus ( Plus a11 a12 ) ( N n ) ) |\n      ( Plus a11 a12      , V x  )              \\<Rightarrow> ( Plus ( Plus a11 a12 ) ( V x ) ) |\n      ( Plus a11 a12      , Plus a2' ( N n ) )  \\<Rightarrow> ( Plus ( Plus a11 ( Plus  a12 a2' ) ) ( N n ) ) |\n      ( Plus a11 a12      , Plus a21 a22 )      \\<Rightarrow> ( Plus ( Plus a11 a12 ) ( Plus a21 a22 ) ) )\"\n\nlemma \"aval ( full_asimp a ) s = aval a s\"\n  apply ( induction a )\n  apply ( auto split: aexp.split)\ndone\n\n\n\nfun subst :: \"vname \\<Rightarrow> aexp \\<Rightarrow> aexp \\<Rightarrow> aexp\" where\n  \"subst _ _ ( N n ) = N n\" |\n  \"subst x t ( V y ) = ( if x = y then t else V y )\" |\n  \"subst x t ( Plus a1 a2 ) = Plus ( subst x t  a1 ) ( subst x t a2 )\"\n\nlemma \"substitution_lemma\" : \"aval ( subst x t e ) s = aval e ( s ( x := aval t s ) )\"\n  apply ( induction e )\n  apply ( auto )\ndone\n\nlemma \"subst_equiv\" : \"aval a1 s = aval a2 s \\<Longrightarrow> aval ( subst x a1 e ) s = aval ( subst x a2 e ) s\"\n  apply ( simp add: substitution_lemma )\ndone\n\n\n\ndatatype aexp2 =\n  N val |\n  V vname |\n  Inc vname |\n  Plus aexp2 aexp2 |\n  Div aexp2 aexp2\n\n\nfun aval2 :: \"aexp2 \\<Rightarrow> state \\<Rightarrow> ( val \\<times> state ) option\" where\n  \"aval2 ( N i ) s = Some (  i  , s )\" |\n  \"aval2 ( V x ) s = Some ( s x , s )\" |\n  \"aval2 ( Inc x ) s = Some ( s x , s ( x := ( s x ) + 1 ) )\" |\n  \"aval2 ( Plus a1 a2 ) s =\n    ( case ( aval2 a1 s ) of\n      None \\<Rightarrow> None |\n      Some ( v1 , s1 ) \\<Rightarrow>\n        ( case ( aval2 a2 s1 ) of\n          None \\<Rightarrow> None |\n          Some ( v2 , s2 ) \\<Rightarrow> Some ( v1 + v2 , s2 ) ) )\" |\n  \"aval2 ( Div a1 a2 ) s =\n    ( case ( aval2 a2 s ) of\n      None \\<Rightarrow> None |\n      Some ( v1 , s1 ) \\<Rightarrow> ( if v1 = 0 then None else\n        ( case ( aval2 a1 s1 ) of\n          None \\<Rightarrow> None |\n          Some ( v2 , s2 ) \\<Rightarrow> Some ( v1 div v2 , s2 ) ) ) )\"\n\n\n\ndatatype lexp =\n  Nl int |\n  Vl vname |\n  Plusl lexp lexp |\n  LET vname lexp lexp\n\nfun lval :: \"lexp \\<Rightarrow> state \\<Rightarrow> int\" where\n  \"lval ( Nl n ) s = n\" |\n  \"lval ( Vl x ) s = s x\" |\n  \"lval ( Plusl a1 a2 ) s = lval a1 s + lval a2 s\" |\n  \"lval ( LET x a1 a2 ) s = lval a2 ( s ( x := lval a1 s ) )\"\n\nfun inline :: \"lexp \\<Rightarrow> aexp\" where\n  \"inline ( Nl n ) = aexp.N n\" |\n  \"inline ( Vl x ) = aexp.V x\" |\n  \"inline ( Plusl a1 a2 ) = aexp.Plus ( inline a1 ) ( inline a2 )\" |\n  \"inline ( LET x t e ) = subst x ( inline t ) ( inline e )\"\n\nlemma \"lval l s = aval ( inline l ) s\"\n  apply ( induction l  arbitrary: s )\n  apply ( auto simp add: substitution_lemma)\ndone\n\n\n\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 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\n\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 \"not_lemma\" : \"bval ( not b ) s = bval ( Not b ) s\"\n  apply ( induction b )\n  apply ( auto )\ndone\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 ) _ = Bc False\" |\n  \"and _ ( Bc False ) = Bc False\" |\n  \"and b1 b2 = And b1 b2\"\n\nlemma \"and_lemma\" : \"bval ( and b1 b2 ) s = bval ( And b1 b2 ) s\"\n  apply ( induction b1 b2 rule: and.induct )\n  apply ( auto )\ndone\n\n\n\nfun less :: \"aexp \\<Rightarrow> aexp \\<Rightarrow> bexp\" where\n  \"less ( aexp.N n1 ) ( aexp.N n2 ) = Bc ( n1 < n2 )\" |\n  \"less a1 a2 = Less a1 a2\"\n\nlemma \"less_lemma\" : \"bval ( less a1 a2 ) s = bval ( Less a1 a2 ) s\"\n  apply ( induction a1 a2 rule: less.induct )\n  apply ( auto )\ndone\n\n\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\nlemma \"bval ( bsimp b ) = bval b\"\n  apply ( induction b rule: bsimp.induct )\n  apply ( auto split: bexp.split simp: not_lemma and_lemma less_lemma assimp_correct)\ndone\n\n\n\ndefinition Le :: \"aexp \\<Rightarrow> aexp \\<Rightarrow> bexp\" where\n  \"Le a1 a2 = Not ( Less a2 a1 )\"\n\nlemma \"bval ( Le a1 a2 ) s = ( aval a1 s \\<le> aval a2 s )\"\n  apply ( auto simp add: Le_def)\ndone\n\ndefinition Eq :: \"aexp \\<Rightarrow> aexp \\<Rightarrow> bexp\" where\n  \"Eq a1 a2 = And ( Le a1 a2 ) ( Le a2 a1 )\"\n\nlemma \"bval ( Eq a1 a2 ) s = ( aval a1 s = aval a2 s)\"\n  apply ( auto simp add: Eq_def Le_def )\ndone\n\n\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 ) s = b\" |\n  \"ifval ( If i t e ) s = ( if ( ifval i s ) then ( ifval t s ) else ( ifval e 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 \"ifval ( b2ifexp b ) s = bval b s\"\n  apply ( induction b )\n  apply ( auto )\ndone\n\nfun if2bexp :: \"ifexp \\<Rightarrow> bexp\" where\n  \"if2bexp ( Bc2 b ) = Bc b\" |\n  \"if2bexp ( If i t e ) =\n    And\n      ( Not (  And ( if2bexp i )  ( Not ( if2bexp t ) )  ) )\n      ( Not (  And ( Not ( if2bexp i ) )  ( Not ( if2bexp e ) )  ) )\" |\n  \"if2bexp ( Less2 a1 a2 ) = Less a1 a2\"\n\nlemma \"bval ( if2bexp i ) s = ifval i s\"\n  apply ( induction i )\n  apply ( auto )\ndone\n\n\n\ndatatype pbexp =\n  VAR vname |\n  NOT pbexp |\n  AND pbexp pbexp |\n  OR pbexp pbexp\n\nfun pbval :: \"pbexp \\<Rightarrow> ( vname \\<Rightarrow> bool ) \\<Rightarrow> bool\" where\n  \"pbval ( VAR x ) s = s x\" |\n  \"pbval ( NOT p ) s = ( \\<not> pbval p s )\" |\n  \"pbval ( AND p1 p2 ) s = ( pbval p1 s \\<and> pbval p2 s )\" |\n  \"pbval ( OR p1 p2 ) s = ( pbval p1 s \\<or> pbval p2 s )\"\n\n\n\nfun is_nnf :: \"pbexp \\<Rightarrow> bool\" where\n  \"is_nnf ( VAR _ ) = True\" |\n  \"is_nnf ( NOT ( VAR x ) ) = True\" |\n  \"is_nnf ( NOT b ) = 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\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 p1 p2 ) ) = OR  ( nnf ( NOT p1 ) )  ( nnf ( NOT p2 ) )\" |\n  \"nnf ( NOT ( OR p1 p2 ) ) = AND  ( nnf ( NOT p1 ) )  ( nnf ( NOT p2 ) )\" |\n  \"nnf ( AND p1 p2 ) = AND ( nnf p1 ) ( nnf p2 )\" |\n  \"nnf ( OR p1 p2 ) = OR ( nnf p1 ) ( nnf p2 )\"\n\nlemma \"is_nnf ( nnf b )\"\n  apply ( induction b rule: nnf.induct )\n  apply ( auto )\ndone\n\nlemma \"pbval ( nnf b ) s = pbval b s\"\n  apply ( induction b rule: nnf.induct  )\n  apply ( auto split: pbexp.split )\ndone\n\n\n\nfun or_free :: \"pbexp \\<Rightarrow> bool\" where\n  \"or_free ( VAR _ ) = True\" |\n  \"or_free ( NOT b ) = ( or_free b )\" |\n  \"or_free ( OR _ _ ) = False\" |\n  \"or_free ( AND b1 b2 ) = ( or_free b1 \\<and> or_free b2 )\"\n\nfun is_dnf :: \"pbexp \\<Rightarrow> bool\" where\n  \"is_dnf ( VAR _ ) = True\" |\n  \"is_dnf ( NOT ( VAR x ) ) = True\" |\n  \"is_dnf ( NOT b ) = False\" |\n  \"is_dnf ( OR b1 b2 ) = ( is_dnf b1 \\<and> is_dnf b2 )\" |\n  \"is_dnf ( AND b1 b2 ) = ( or_free b1 \\<and> or_free b2 \\<and> is_nnf b1 \\<and> is_nnf b2 )\"\n\nlemma \"nnf_if_dnf\" : \"is_dnf b \\<Longrightarrow> is_nnf b\"\n  apply ( induction b rule: is_dnf.induct )\n  apply ( auto )\ndone\n\nfun dist_AND :: \"pbexp \\<Rightarrow> pbexp \\<Rightarrow> pbexp\" where\n  \"dist_AND ( VAR x1 ) ( VAR x2 ) = AND ( VAR x1 ) ( VAR x2 )\" |\n  \"dist_AND ( VAR x ) ( NOT b ) = AND ( VAR x ) ( NOT b)\" |\n  \"dist_AND ( NOT b ) ( VAR x ) = AND ( NOT b ) ( VAR x )\" |\n  \"dist_AND ( NOT b1 ) ( NOT b2 ) = AND ( NOT b1 ) ( NOT b2 )\" |\n  \"dist_AND ( OR b1 b2 ) b = OR ( dist_AND b1 b ) ( dist_AND b2 b )\" |\n  \"dist_AND b ( OR b1 b2 ) = OR ( dist_AND b b1 ) ( dist_AND b b2 )\" |\n  \"dist_AND ( AND b1 b2 ) b = AND ( AND b1 b2 ) b\" |\n  \"dist_AND b ( AND b1 b2 ) = AND b ( AND b1 b2 )\"\n\nlemma \"dist_AND_correct\" : \"pbval ( dist_AND b1 b2 ) s = pbval ( AND b1 b2 ) s\"\n  apply ( induction b1 b2 rule: dist_AND.induct )\n  apply ( auto )\ndone\n\nlemma \"or_free_if_dnf\" : \"is_dnf (NOT b) \\<Longrightarrow> or_free b\"\n  apply ( induction b )\n  apply ( auto )\ndone\n\nlemma \"dist_AND_preserves_dnf\" : \"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 simp: nnf_if_dnf or_free_if_dnf)\ndone\n\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 ( 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 \"pbval ( dnf_of_nnf b ) s = pbval b s\"\n  apply ( induction b )\n  apply ( auto simp add: dist_AND_correct )\ndone\n\nlemma \"dnf_if_nnf\" : \"is_nnf (NOT b) \\<Longrightarrow> is_dnf (NOT b)\"\n  apply ( induction b )\n  apply ( auto )\ndone\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: dnf_if_nnf dist_AND_preserves_dnf )\ndone\n\n\n\ndatatype instr =\n  LOADI val |\n  LOAD vname |\n  ADD\n\ntype_synonym stack = \"val list\"\n\nabbreviation \"hd2 xs \\<equiv> hd ( tl xs )\"\nabbreviation \"tl2 xs \\<equiv> tl ( tl xs )\"\n\n\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\n\n\nfun comp :: \"aexp \\<Rightarrow> instr list\" where\n  \"comp ( aexp.N n ) = [ LOADI n ]\" |\n  \"comp ( aexp.V x ) = [ LOAD x ]\" |\n  \"comp ( aexp.Plus e1 e2 ) = comp e1 @ comp e2 @ [ ADD ]\"\n\nlemma \"exec_concat\" : \"exec ( is1 @ is2 ) s stk = exec is2 s ( exec is1 s stk )\"\n  apply ( induction is1 arbitrary: is2 s stk )\n  apply ( auto )\ndone\n\nlemma \"exec ( comp a ) s stk = aval a s # stk\"\n  apply ( induction a arbitrary: s stk )\n  apply ( auto simp: exec_concat )\ndone\n\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/Chap3.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278602705731, "lm_q2_score": 0.8152324938410784, "lm_q1q2_score": 0.7193838651632259}}
{"text": "theory Chapter1\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\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> supremum_closed T\n                \\<and> meet_closed T\"\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> join_closed T\n                \\<and> infimum_closed T\"\n\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\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(*\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\nlemma \n  (*assumes \"closure_op Cl\"*)\n  fixes Cl\n  assumes \"closure_op Cl\"\n  shows \"closed_topo (fp Cl)\"\n  unfolding closed_topo_def\nproof \n  show \"fp Cl \\<^bold>\\<top>\"\n  proof (unfold fixpoint_pred_def setequ_def top_def, rule, rule)\n    fix w\n    show l2r: \"Cl (\\<lambda>w. True) w \\<Longrightarrow> True\" by simp\n  next\n    fix w\n    show r2l: \"True \\<Longrightarrow> (Cl (\\<lambda>w. True)) w\" \n    proof -\n      have \"\\<forall>A. A \\<^bold>\\<preceq> Cl A\" \n        using CO2_def assms closure_op_def meet_def by metis\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\nnext\n  show \"fp Cl \\<^bold>\\<bottom> \\<and> join_closed (fp Cl) \\<and> infimum_closed (fp Cl)\"\n    apply (rule conjI)\n  proof -\n\n\n    from assms \n    have \"CO2 Cl\" by (simp add: closure_op_def meet_def)\n    thus \"\\<And>w. Cl (\\<lambda>w. True) w\" \n      by (simp add: CO2_def subset_def)\n  qed\nnext\n  show \"fp Cl \\<^bold>\\<bottom> \\<and> join_closed (fp Cl) \\<and> infimum_closed (fp Cl)\"\n  proof\n    from assms \n    have 1: \"CO1 Cl\" by (simp add: closure_op_def meet_def)\n    thus \"fp Cl \\<^bold>\\<bottom>\" by (simp add: CO1_def fixpoint_pred_def)\n  next\n    show \"join_closed (fp Cl) \\<and> infimum_closed (fp Cl)\" \n      apply ( rule conjI )\n       apply ( unfold join_closed_def join_def fixpoint_pred_def setequ_def)\n       apply (rule allI, rule allI, rule impI, rule allI, rule iffI)\n      apply auto\n    proof -\n      from assms\n      have 4: \"CO4 Cl\" by (simp add: closure_op_def meet_def)\n      thus \"\\<And>X Y w. Cl (\\<lambda>w. X w \\<or> Y w) w \\<Longrightarrow> \\<forall>w. Cl X w = X w \\<Longrightarrow> \\<forall>w. Cl Y w = Y w \\<Longrightarrow> \\<not> Y w \\<Longrightarrow> X w\" \n        by (simp add: CO4_def join_def setequ_equ)\n    next\n      show \"\\<And>X Y w. \\<forall>w. Cl X w = X w \\<Longrightarrow> \\<forall>w. Cl Y w = Y w \\<Longrightarrow> X w \\<Longrightarrow> Cl (\\<lambda>w. X w \\<or> Y w) w\"\n      proof -\n        from assms\n        have 4: \"CO4 Cl\" by (simp add: closure_op_def meet_def)\n        thus \"\\<And>X Y w. \\<forall>w. Cl X w = X w \\<Longrightarrow> \\<forall>w. Cl Y w = Y w \\<Longrightarrow> X w \\<Longrightarrow> Cl (\\<lambda>w. X w \\<or> Y w) w\"\n          by (simp add: CO4_def join_def setequ_equ)\n      qed\n    next\n      show \"\\<And>X Y w. \\<forall>w. Cl X w = X w \\<Longrightarrow> \\<forall>w. Cl Y w = Y w \\<Longrightarrow> Y w \\<Longrightarrow> Cl (\\<lambda>w. X w \\<or> Y w) w\"\n      proof -\n        from assms\n        have 4: \"CO4 Cl\" by (simp add: closure_op_def meet_def)\n        thus \"\\<And>X Y w. \\<forall>w. Cl X w = X w \\<Longrightarrow> \\<forall>w. Cl Y w = Y w \\<Longrightarrow> Y w \\<Longrightarrow> Cl (\\<lambda>w. X w \\<or> Y w) w\"\n          by (simp add: CO4_def join_def setequ_equ)\n      qed\n    next\n      show \"infimum_closed (\\<lambda>X. \\<forall>w. Cl X w = X w)\"\n        apply (unfold infimum_closed_def infimum_def)\n        apply (rule allI, rule impI, rule allI, rule iffI)\n        apply (rule allI )\n      proof\n        show \"\\<And>D w X. D \\<sqsubseteq> (\\<lambda>X. \\<forall>w. Cl X w = X w) \\<Longrightarrow> Cl (\\<lambda>w. D \\<sqsubseteq> (\\<lambda>X. X w)) w \\<Longrightarrow> D X \\<Longrightarrow> X w\" sledgehammer\n\n\n\n\n\n(*\nWe can then take set-complement of each of these closed sets \nto obtain another collection (i.e., another system of sets), \nwhich properly form an (open set) topology\n*)\n\nlemma \n  assumes \"closure_op Cl\" \n  shows \"open_topo (\\<lambda>X. fp Cl (\\<^bold>\\<midarrow> X))\" sorry\n\n\n\n\nsection \"3 Interior Operator Axioms\"\n\n(*\nDual to the topological closure operator \nis the topological interior operator Int, \nwhich satisfies the following four axioms (for any sets A, B \\<subseteq> X):\n[IO1] Int(X) = X;\n[IO2] Int(A) \\<subseteq> A;\n[IO3] Int(Int(A)) = Int(A);\n[IO4] Int(A \\<inter> B) = Int(A) \\<inter> Int(B).\nThe fixed points of Int, the set system {A |Int(A) = A}, \nform a system of subsets of X that will be called \u201copen sets\u201d, \nhence defining the topological space (X, T).\n*)\n\n\n(* dual Normality (DNRM).*)\ndefinition IO1::\"'w cl \\<Rightarrow> bool\" (\"DNRM\") where \"IO1 Int' \\<equiv> (Int' \\<^bold>\\<top>) \\<^bold>\\<approx> \\<^bold>\\<top>\" \n(* Expansive dual - contractive (CNTR).*)\ndefinition IO2::\"'w cl \\<Rightarrow> bool\" (\"CNTR\") where \"IO2 Int' \\<equiv> \\<forall>A. Int' A \\<^bold>\\<preceq> A\"\n(* Idempotent (IDEM) *)\ndefinition IO3::\"'w cl \\<Rightarrow> bool\" (\"IDEM\") where \"IO3 Int' \\<equiv> \\<forall>A. (Int' A) \\<^bold>\\<approx> Int'(Int' A)\"\n(* Additivity (ADDI) *)\ndefinition IO4::\"'w cl \\<Rightarrow> bool\" (\"MULT\") where \"IO4 Int' \\<equiv> \\<forall>A B. Int' (A \\<^bold>\\<and> B) \\<^bold>\\<approx> (Int' A) \\<^bold>\\<and> (Int' B)\"\n\ndefinition interior_op :: \"'w cl \\<Rightarrow> bool\"\n  where \"interior_op  \\<equiv> IO1 \\<^bold>\\<and> IO2 \\<^bold>\\<and> IO3 \\<^bold>\\<and> IO4\"\n\nlemma assumes \"interior_op Int'\" shows \"open_topo (fp Int')\" sorry\n\n\n\n\nsection \"4 Comprehension and Outlook\"\n\n(* ...\n\nThe equivalence of the above two axiomatically defined operators on P(X) in specifying any topology T is well known. In addition to the closure or interior operators defining\na topological space, there are other four set operators widely used as primitive operators\nin topology.\n\nThey are the exterior operator, the boundary operator, the derived-set operator,\nand the dually defined co-derived-set operator. All these operators have been shown to be\nable to specify an identical topology T \u2014they are equivalent to one another, as with Cl\nand Int operators. We call these various inter-related set operators specifying the one\nand the same topology a Topological System, while still use (X, T ) to denote it. Each of\nthe six above-mentioned operators P(X) \\<rightarrow> P(X) provides equivalent characterizations\nof (X, T ). In a Topological System, the various operators, when taken together, provide\ncomprehensive topological semantics to ground first-order modal logic.\n\nIn parallel to these various axiomatizations of a Topological System, it is also long\nestablished that the topological closure operator can be relaxed to the more general setting\nof a Closure System in which the closure operator satisfies, instead of [CO1]\u2013[CO4], three\nsimilar axioms (see below), without enforcing axiom [CO1] (related to \u201cgroundedness\u201d)\nand axiom [CO4] (related to \u201cstable under union\u201d). The fixed points associated with\nthis generalized closure operator are called (generalized) closed sets. Viewed in this way, the\nclosed set system of a Topological System is just a special case of a generalized Closure\nSystem. Other applications of the Closure System include Matroid, Antimatroid/Learning\nSpace [4\u20137], or Concept Lattice [8], in which the generalized closure operator is enhanced\nwith an additional exchange axiom, anti-exchange axiom, or a Galois connection.\n\n...\n\n*)\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.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9099070109242131, "lm_q2_score": 0.7905303186696747, "lm_q1q2_score": 0.7193090793056894}}
{"text": "section \\<open> Fixed-points and Recursion \\<close>\n\ntheory utp_recursion\n  imports \n    utp_pred_laws\n    utp_rel\nbegin\n\nsubsection \\<open> Fixed-point Laws \\<close>\n  \nlemma mu_id: \"(\\<mu> X \\<bullet> X) = true\"\n  by (simp add: antisym gfp_upperbound)\n\nlemma mu_const: \"(\\<mu> X \\<bullet> P) = P\"\n  by (simp add: gfp_const)\n\nlemma nu_id: \"(\\<nu> X \\<bullet> X) = false\"                                                            \n  by (meson lfp_lowerbound utp_pred_laws.bot.extremum_unique)\n\nlemma nu_const: \"(\\<nu> X \\<bullet> P) = P\"\n  by (simp add: lfp_const)\n\nlemma mu_refine_intro:\n  assumes \"(C \\<Rightarrow> S) \\<sqsubseteq> F(C \\<Rightarrow> S)\" \"(C \\<and> \\<mu> F) = (C \\<and> \\<nu> F)\"\n  shows \"(C \\<Rightarrow> S) \\<sqsubseteq> \\<mu> F\"\nproof -\n  from assms have \"(C \\<Rightarrow> S) \\<sqsubseteq> \\<nu> F\"\n    by (simp add: lfp_lowerbound)\n  with assms show ?thesis\n    by (pred_auto)\nqed\n\nsubsection \\<open> Obtaining Unique Fixed-points \\<close>\n    \ntext \\<open> Obtaining termination proofs via approximation chains. Theorems and proofs adapted\n  from Chapter 2, page 63 of the UTP book~\\cite{Hoare&98}.  \\<close>\n\ntype_synonym 'a chain = \"nat \\<Rightarrow> 'a upred\"\n\ndefinition chain :: \"'a chain \\<Rightarrow> bool\" where\n  \"chain Y = ((Y 0 = false) \\<and> (\\<forall> i. Y (Suc i) \\<sqsubseteq> Y i))\"\n\nlemma chain0 [simp]: \"chain Y \\<Longrightarrow> Y 0 = false\"\n  by (simp add:chain_def)\n\nlemma chainI:\n  assumes \"Y 0 = false\" \"\\<And> i. Y (Suc i) \\<sqsubseteq> Y i\"\n  shows \"chain Y\"\n  using assms by (auto simp add: chain_def)\n\nlemma chainE:\n  assumes \"chain Y\" \"\\<And> i. \\<lbrakk> Y 0 = false; Y (Suc i) \\<sqsubseteq> Y i \\<rbrakk> \\<Longrightarrow> P\"\n  shows \"P\"\n  using assms by (simp add: chain_def)\n\nlemma L274:\n  assumes \"\\<forall> n. ((E n \\<and>\\<^sub>p X) = (E n \\<and> Y))\"\n  shows \"(\\<Sqinter> (range E) \\<and> X) = (\\<Sqinter> (range E) \\<and> Y)\"\n  using assms by (pred_auto)\n\ntext \\<open> Constructive chains \\<close>\n\ndefinition constr ::\n  \"('a upred \\<Rightarrow> 'a upred) \\<Rightarrow> 'a chain \\<Rightarrow> bool\" where\n\"constr F E \\<longleftrightarrow> chain E \\<and> (\\<forall> X n. ((F(X) \\<and> E(n + 1)) = (F(X \\<and> E(n)) \\<and> E (n + 1))))\"\n\nlemma constrI:\n  assumes \"chain E\" \"\\<And> X n. ((F(X) \\<and> E(n + 1)) = (F(X \\<and> E(n)) \\<and> E (n + 1)))\"\n  shows \"constr F E\"\n  using assms by (auto simp add: constr_def)\n\ntext \\<open> This lemma gives a way of showing that there is a unique fixed-point when\n        the predicate function can be built using a constructive function F\n        over an approximation chain E \\<close>\n\nlemma chain_pred_terminates:\n  assumes \"constr F E\" \"mono F\"\n  shows \"(\\<Sqinter> (range E) \\<and> \\<mu> F) = (\\<Sqinter> (range E) \\<and> \\<nu> F)\"\nproof -\n  from assms have \"\\<forall> n. (E n \\<and> \\<mu> F) = (E n \\<and> \\<nu> F)\"\n  proof (rule_tac allI)\n    fix n\n    from assms show \"(E n \\<and> \\<mu> F) = (E n \\<and> \\<nu> F)\"\n    proof (induct n)\n      case 0 thus ?case by (simp add: constr_def)\n    next\n      case (Suc n)\n      note hyp = this\n      thus ?case\n      proof -\n        have \"(E (n + 1) \\<and> \\<mu> F) = (E (n + 1) \\<and> F (\\<mu> F))\"\n          using gfp_unfold[OF hyp(3), THEN sym] by (simp add: constr_def)\n        also from hyp have \"... = (E (n + 1) \\<and> F (E n \\<and> \\<mu> F))\"\n          by (metis conj_comm constr_def)\n        also from hyp have \"... = (E (n + 1) \\<and> F (E n \\<and> \\<nu> F))\"\n          by simp\n        also from hyp have \"... = (E (n + 1) \\<and> \\<nu> F)\"\n          by (metis (no_types, lifting) conj_comm constr_def lfp_unfold)\n        ultimately show ?thesis\n          by simp\n      qed\n    qed\n  qed\n  thus ?thesis\n    by (auto intro: L274)\nqed\n\ntheorem constr_fp_uniq:\n  assumes \"constr F E\" \"mono F\" \"\\<Sqinter> (range E) = C\"\n  shows \"(C \\<and> \\<mu> F) = (C \\<and> \\<nu> F)\"\n  using assms(1) assms(2) assms(3) chain_pred_terminates by blast\n    \nsubsection \\<open> Noetherian Induction Instantiation\\<close>\n      \ntext \\<open> Contribution from Yakoub Nemouchi.The following generalization was used by Tobias Nipkow\n        and Peter Lammich  in \\emph{Refine\\_Monadic} \\<close>\n\nlemma  wf_fixp_uinduct_pure_ueq_gen:     \n  assumes fixp_unfold: \"fp B = B (fp B)\"\n  and              WF: \"wf R\"\n  and     induct_step:\n          \"\\<And>f st. \\<lbrakk>\\<And>st'. (st',st) \\<in> R  \\<Longrightarrow> (((Pre \\<and> \\<lceil>e\\<rceil>\\<^sub>< =\\<^sub>u \\<guillemotleft>st'\\<guillemotright>) \\<Rightarrow> Post) \\<sqsubseteq> f)\\<rbrakk>\n               \\<Longrightarrow> fp B = f \\<Longrightarrow>((Pre \\<and> \\<lceil>e\\<rceil>\\<^sub>< =\\<^sub>u \\<guillemotleft>st\\<guillemotright>) \\<Rightarrow> Post) \\<sqsubseteq> (B f)\"\n        shows \"((Pre \\<Rightarrow> Post) \\<sqsubseteq> fp B)\"  \nproof -  \n  { fix st\n    have \"((Pre \\<and> \\<lceil>e\\<rceil>\\<^sub>< =\\<^sub>u \\<guillemotleft>st\\<guillemotright>) \\<Rightarrow> Post) \\<sqsubseteq> (fp B)\" \n    using WF proof (induction rule: wf_induct_rule)\n      case (less x)\n      hence \"(Pre \\<and> \\<lceil>e\\<rceil>\\<^sub>< =\\<^sub>u \\<guillemotleft>x\\<guillemotright> \\<Rightarrow> Post) \\<sqsubseteq> B (fp B)\"\n        by (rule induct_step, rel_blast, simp)\n      then show ?case\n        using fixp_unfold by auto\n    qed\n  }\n  thus ?thesis \n  by pred_simp  \nqed\n  \ntext \\<open> The next lemma shows that using substitution also work. However it is not that generic\n        nor practical for proof automation ... \\<close>\n\nlemma refine_usubst_to_ueq:\n  \"vwb_lens E \\<Longrightarrow> (Pre \\<Rightarrow> Post)\\<lbrakk>\\<guillemotleft>st'\\<guillemotright>/$E\\<rbrakk> \\<sqsubseteq> f\\<lbrakk>\\<guillemotleft>st'\\<guillemotright>/$E\\<rbrakk> = (((Pre \\<and> $E =\\<^sub>u \\<guillemotleft>st'\\<guillemotright>) \\<Rightarrow> Post) \\<sqsubseteq> f)\"\n  by (rel_auto, metis vwb_lens_wb wb_lens.get_put)  \n\ntext \\<open> By instantiation of @{thm wf_fixp_uinduct_pure_ueq_gen} with @{term \\<mu>} and lifting of the \n        well-founded relation we have ... \\<close>\n  \nlemma mu_rec_total_pure_rule: \n  assumes WF: \"wf R\"\n  and     M: \"mono B\"  \n  and     induct_step:\n          \"\\<And> f st.  \\<lbrakk>(Pre \\<and> (\\<lceil>e\\<rceil>\\<^sub><,\\<guillemotleft>st\\<guillemotright>)\\<^sub>u \\<in>\\<^sub>u \\<guillemotleft>R\\<guillemotright> \\<Rightarrow> Post) \\<sqsubseteq> f\\<rbrakk>\n               \\<Longrightarrow> \\<mu> B = f \\<Longrightarrow>(Pre \\<and> \\<lceil>e\\<rceil>\\<^sub>< =\\<^sub>u \\<guillemotleft>st\\<guillemotright> \\<Rightarrow> Post) \\<sqsubseteq> (B f)\"\n        shows \"(Pre \\<Rightarrow> Post) \\<sqsubseteq> \\<mu> B\"  \nproof (rule wf_fixp_uinduct_pure_ueq_gen[where fp=\\<mu> and Pre=Pre and B=B and R=R and e=e])\n  show \"\\<mu> B = B (\\<mu> B)\"\n    by (simp add: M def_gfp_unfold)\n  show \"wf R\"\n    by (fact WF)\n  show \"\\<And>f st. (\\<And>st'. (st', st) \\<in> R \\<Longrightarrow> (Pre \\<and> \\<lceil>e\\<rceil>\\<^sub>< =\\<^sub>u \\<guillemotleft>st'\\<guillemotright> \\<Rightarrow> Post) \\<sqsubseteq> f) \\<Longrightarrow> \n                \\<mu> B = f \\<Longrightarrow> \n                (Pre \\<and> \\<lceil>e\\<rceil>\\<^sub>< =\\<^sub>u \\<guillemotleft>st\\<guillemotright> \\<Rightarrow> Post) \\<sqsubseteq> B f\"\n    by (rule induct_step, rel_simp, simp)\nqed\n\nlemma nu_rec_total_pure_rule: \n  assumes WF: \"wf R\"\n  and     M: \"mono B\"  \n  and     induct_step:\n          \"\\<And> f st.  \\<lbrakk>(Pre \\<and> (\\<lceil>e\\<rceil>\\<^sub><,\\<guillemotleft>st\\<guillemotright>)\\<^sub>u \\<in>\\<^sub>u \\<guillemotleft>R\\<guillemotright> \\<Rightarrow> Post) \\<sqsubseteq> f\\<rbrakk>\n               \\<Longrightarrow> \\<nu> B = f \\<Longrightarrow>(Pre \\<and> \\<lceil>e\\<rceil>\\<^sub>< =\\<^sub>u \\<guillemotleft>st\\<guillemotright> \\<Rightarrow> Post) \\<sqsubseteq> (B f)\"\n        shows \"(Pre \\<Rightarrow> Post) \\<sqsubseteq> \\<nu> B\"  \nproof (rule wf_fixp_uinduct_pure_ueq_gen[where fp=\\<nu> and Pre=Pre and B=B and R=R and e=e])\n  show \"\\<nu> B = B (\\<nu> B)\"\n    by (simp add: M def_lfp_unfold)\n  show \"wf R\"\n    by (fact WF)\n  show \"\\<And>f st. (\\<And>st'. (st', st) \\<in> R \\<Longrightarrow> (Pre \\<and> \\<lceil>e\\<rceil>\\<^sub>< =\\<^sub>u \\<guillemotleft>st'\\<guillemotright> \\<Rightarrow> Post) \\<sqsubseteq> f) \\<Longrightarrow> \n                \\<nu> B = f \\<Longrightarrow> \n                (Pre \\<and> \\<lceil>e\\<rceil>\\<^sub>< =\\<^sub>u \\<guillemotleft>st\\<guillemotright> \\<Rightarrow> Post) \\<sqsubseteq> B f\"\n    by (rule induct_step, rel_simp, simp)\nqed\n\ntext \\<open>Since @{term \"B ((Pre \\<and> (\\<lceil>E\\<rceil>\\<^sub><,\\<guillemotleft>st\\<guillemotright>)\\<^sub>u\\<in>\\<^sub>u\\<guillemotleft>R\\<guillemotright> \\<Rightarrow> Post)) \\<sqsubseteq> B (\\<mu> B)\"} and \n      @{term \"mono B\"}, thus,  @{thm mu_rec_total_pure_rule} can be expressed as follows\\<close>\n  \nlemma mu_rec_total_utp_rule: \n  assumes WF: \"wf R\"\n    and     M: \"mono B\"  \n    and     induct_step:\n    \"\\<And>st. (Pre \\<and> \\<lceil>e\\<rceil>\\<^sub>< =\\<^sub>u \\<guillemotleft>st\\<guillemotright> \\<Rightarrow> Post) \\<sqsubseteq> (B ((Pre \\<and> (\\<lceil>e\\<rceil>\\<^sub><,\\<guillemotleft>st\\<guillemotright>)\\<^sub>u \\<in>\\<^sub>u \\<guillemotleft>R\\<guillemotright> \\<Rightarrow> Post)))\"\n  shows \"(Pre \\<Rightarrow> Post) \\<sqsubseteq> \\<mu> B\"  \nproof (rule mu_rec_total_pure_rule[where R=R and e=e], simp_all add: assms)\n  show \"\\<And>f st. (Pre \\<and> (\\<lceil>e\\<rceil>\\<^sub><, \\<guillemotleft>st\\<guillemotright>)\\<^sub>u \\<in>\\<^sub>u \\<guillemotleft>R\\<guillemotright> \\<Rightarrow> Post) \\<sqsubseteq> f \\<Longrightarrow> \\<mu> B = f \\<Longrightarrow> (Pre \\<and> \\<lceil>e\\<rceil>\\<^sub>< =\\<^sub>u \\<guillemotleft>st\\<guillemotright> \\<Rightarrow> Post) \\<sqsubseteq> B f\"\n    by (simp add: M induct_step monoD order_subst2)\nqed\n\nlemma nu_rec_total_utp_rule: \n  assumes WF: \"wf R\"\n    and     M: \"mono B\"  \n    and     induct_step:\n    \"\\<And>st. (Pre \\<and> \\<lceil>e\\<rceil>\\<^sub>< =\\<^sub>u \\<guillemotleft>st\\<guillemotright> \\<Rightarrow> Post) \\<sqsubseteq> (B ((Pre \\<and> (\\<lceil>e\\<rceil>\\<^sub><,\\<guillemotleft>st\\<guillemotright>)\\<^sub>u \\<in>\\<^sub>u \\<guillemotleft>R\\<guillemotright> \\<Rightarrow> Post)))\"\n  shows \"(Pre \\<Rightarrow> Post) \\<sqsubseteq> \\<nu> B\"  \nproof (rule nu_rec_total_pure_rule[where R=R and e=e], simp_all add: assms)\n  show \"\\<And>f st. (Pre \\<and> (\\<lceil>e\\<rceil>\\<^sub><, \\<guillemotleft>st\\<guillemotright>)\\<^sub>u \\<in>\\<^sub>u \\<guillemotleft>R\\<guillemotright> \\<Rightarrow> Post) \\<sqsubseteq> f \\<Longrightarrow> \\<nu> B = f \\<Longrightarrow> (Pre \\<and> \\<lceil>e\\<rceil>\\<^sub>< =\\<^sub>u \\<guillemotleft>st\\<guillemotright> \\<Rightarrow> Post) \\<sqsubseteq> B f\"\n    by (simp add: M induct_step monoD order_subst2)\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/UTP/utp/utp_recursion.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8244619177503205, "lm_q2_score": 0.8723473779969194, "lm_q1q2_score": 0.7192171922078039}}
{"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_MSortBUIsSort\n  imports \"../../Test_Base\"\nbegin\n\ndatatype 'a list = nil2 | cons2 \"'a\" \"'a list\"\n\ndatatype Nat = Z | S \"Nat\"\n\nfun map :: \"('a => 'b) => 'a list => 'b list\" where\n  \"map f (nil2) = nil2\"\n| \"map f (cons2 y xs) = cons2 (f y) (map f xs)\"\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 mergingbu :: \"(Nat list) list => Nat list\" where\n  \"mergingbu (nil2) = nil2\"\n| \"mergingbu (cons2 xs (nil2)) = xs\"\n| \"mergingbu (cons2 xs (cons2 z x2)) =\n     mergingbu (pairwise (cons2 xs (cons2 z x2)))\"\n  by pat_completeness auto\n\nfun msortbu :: \"Nat list => Nat list\" where\n  \"msortbu x = mergingbu (map (% (y :: Nat) => cons2 y (nil2)) 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  \"((msortbu 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_MSortBUIsSort.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.872347368040789, "lm_q2_score": 0.8244619263765707, "lm_q1q2_score": 0.7192171915244402}}
{"text": "(*  Title:      HOL/Groups_Big.thy\n    Author:     Tobias Nipkow\n    Author:     Lawrence C Paulson\n    Author:     Markus Wenzel\n    Author:     Jeremy Avigad\n*)\n\nsection \\<open>Big sum and product over finite (non-empty) sets\\<close>\n\ntheory Groups_Big\n  imports Power\nbegin\n\nsubsection \\<open>Generic monoid operation over a set\\<close>\n\nlocale comm_monoid_set = comm_monoid\nbegin\n\nsubsubsection \\<open>Standard sum or product indexed by a finite set\\<close>\n\ninterpretation comp_fun_commute f\n  by standard (simp add: fun_eq_iff left_commute)\n\ninterpretation comp?: comp_fun_commute \"f \\<circ> g\"\n  by (fact comp_comp_fun_commute)\n\ndefinition F :: \"('b \\<Rightarrow> 'a) \\<Rightarrow> 'b set \\<Rightarrow> 'a\"\n  where eq_fold: \"F g A = Finite_Set.fold (f \\<circ> g) \\<^bold>1 A\"\n\nlemma infinite [simp]: \"\\<not> finite A \\<Longrightarrow> F g A = \\<^bold>1\"\n  by (simp add: eq_fold)\n\nlemma empty [simp]: \"F g {} = \\<^bold>1\"\n  by (simp add: eq_fold)\n\nlemma insert [simp]: \"finite A \\<Longrightarrow> x \\<notin> A \\<Longrightarrow> F g (insert x A) = g x \\<^bold>* F g A\"\n  by (simp add: eq_fold)\n\nlemma remove:\n  assumes \"finite A\" and \"x \\<in> A\"\n  shows \"F g A = g x \\<^bold>* F g (A - {x})\"\nproof -\n  from \\<open>x \\<in> A\\<close> obtain B where B: \"A = insert x B\" and \"x \\<notin> B\"\n    by (auto dest: mk_disjoint_insert)\n  moreover from \\<open>finite A\\<close> B have \"finite B\" by simp\n  ultimately show ?thesis by simp\nqed\n\nlemma insert_remove: \"finite A \\<Longrightarrow> F g (insert x A) = g x \\<^bold>* F g (A - {x})\"\n  by (cases \"x \\<in> A\") (simp_all add: remove insert_absorb)\n\nlemma insert_if: \"finite A \\<Longrightarrow> F g (insert x A) = (if x \\<in> A then F g A else g x \\<^bold>* F g A)\"\n  by (cases \"x \\<in> A\") (simp_all add: insert_absorb)\n\nlemma neutral: \"\\<forall>x\\<in>A. g x = \\<^bold>1 \\<Longrightarrow> F g A = \\<^bold>1\"\n  by (induct A rule: infinite_finite_induct) simp_all\n\nlemma neutral_const [simp]: \"F (\\<lambda>_. \\<^bold>1) A = \\<^bold>1\"\n  by (simp add: neutral)\n\nlemma union_inter:\n  assumes \"finite A\" and \"finite B\"\n  shows \"F g (A \\<union> B) \\<^bold>* F g (A \\<inter> B) = F g A \\<^bold>* F g B\"\n  \\<comment> \\<open>The reversed orientation looks more natural, but LOOPS as a simprule!\\<close>\n  using assms\nproof (induct A)\n  case empty\n  then show ?case by simp\nnext\n  case (insert x A)\n  then show ?case\n    by (auto simp: insert_absorb Int_insert_left commute [of _ \"g x\"] assoc left_commute)\nqed\n\ncorollary union_inter_neutral:\n  assumes \"finite A\" and \"finite B\"\n    and \"\\<forall>x \\<in> A \\<inter> B. g x = \\<^bold>1\"\n  shows \"F g (A \\<union> B) = F g A \\<^bold>* F g B\"\n  using assms by (simp add: union_inter [symmetric] neutral)\n\ncorollary union_disjoint:\n  assumes \"finite A\" and \"finite B\"\n  assumes \"A \\<inter> B = {}\"\n  shows \"F g (A \\<union> B) = F g A \\<^bold>* F g B\"\n  using assms by (simp add: union_inter_neutral)\n\nlemma union_diff2:\n  assumes \"finite A\" and \"finite B\"\n  shows \"F g (A \\<union> B) = F g (A - B) \\<^bold>* F g (B - A) \\<^bold>* F g (A \\<inter> B)\"\nproof -\n  have \"A \\<union> B = A - B \\<union> (B - A) \\<union> A \\<inter> B\"\n    by auto\n  with assms show ?thesis\n    by simp (subst union_disjoint, auto)+\nqed\n\nlemma subset_diff:\n  assumes \"B \\<subseteq> A\" and \"finite A\"\n  shows \"F g A = F g (A - B) \\<^bold>* F g B\"\nproof -\n  from assms have \"finite (A - B)\" by auto\n  moreover from assms have \"finite B\" by (rule finite_subset)\n  moreover from assms have \"(A - B) \\<inter> B = {}\" by auto\n  ultimately have \"F g (A - B \\<union> B) = F g (A - B) \\<^bold>* F g B\" by (rule union_disjoint)\n  moreover from assms have \"A \\<union> B = A\" by auto\n  ultimately show ?thesis by simp\nqed\n\nlemma Int_Diff:\n  assumes \"finite A\"\n  shows \"F g A = F g (A \\<inter> B) \\<^bold>* F g (A - B)\"\n  by (subst subset_diff [where B = \"A - B\"]) (auto simp:  Diff_Diff_Int assms)\n\nlemma setdiff_irrelevant:\n  assumes \"finite A\"\n  shows \"F g (A - {x. g x = z}) = F g A\"\n  using assms by (induct A) (simp_all add: insert_Diff_if)\n\nlemma not_neutral_contains_not_neutral:\n  assumes \"F g A \\<noteq> \\<^bold>1\"\n  obtains a where \"a \\<in> A\" and \"g a \\<noteq> \\<^bold>1\"\nproof -\n  from assms have \"\\<exists>a\\<in>A. g a \\<noteq> \\<^bold>1\"\n  proof (induct A 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 a A)\n    then show ?case by fastforce\n  qed\n  with that show thesis by blast\nqed\n\n\n\nlemma cong [fundef_cong]:\n  assumes \"A = B\"\n  assumes g_h: \"\\<And>x. x \\<in> B \\<Longrightarrow> g x = h x\"\n  shows \"F g A = F h B\"\n  using g_h unfolding \\<open>A = B\\<close>\n  by (induct B rule: infinite_finite_induct) auto\n\nlemma cong_simp [cong]:\n  \"\\<lbrakk> A = B;  \\<And>x. x \\<in> B =simp=> g x = h x \\<rbrakk> \\<Longrightarrow> F (\\<lambda>x. g x) A = F (\\<lambda>x. h x) B\"\nby (rule cong) (simp_all add: simp_implies_def)\n\nlemma reindex_cong:\n  assumes \"inj_on l B\"\n  assumes \"A = l ` B\"\n  assumes \"\\<And>x. x \\<in> B \\<Longrightarrow> g (l x) = h x\"\n  shows \"F g A = F h B\"\n  using assms by (simp add: reindex)\n\nlemma UNION_disjoint:\n  assumes \"finite I\" and \"\\<forall>i\\<in>I. finite (A i)\"\n    and \"\\<forall>i\\<in>I. \\<forall>j\\<in>I. i \\<noteq> j \\<longrightarrow> A i \\<inter> A j = {}\"\n  shows \"F g (\\<Union>(A ` I)) = F (\\<lambda>x. F g (A x)) I\"\n  using assms\nproof (induction rule: finite_induct)\n  case (insert i I)\n  then have \"\\<forall>j\\<in>I. j \\<noteq> i\"\n    by blast\n  with insert.prems have \"A i \\<inter> \\<Union>(A ` I) = {}\"\n    by blast\n  with insert show ?case\n    by (simp add: union_disjoint)\nqed auto\n\nlemma Union_disjoint:\n  assumes \"\\<forall>A\\<in>C. finite A\" \"\\<forall>A\\<in>C. \\<forall>B\\<in>C. A \\<noteq> B \\<longrightarrow> A \\<inter> B = {}\"\n  shows \"F g (\\<Union>C) = (F \\<circ> F) g C\"\nproof (cases \"finite C\")\n  case True\n  from UNION_disjoint [OF this assms] show ?thesis by simp\nnext\n  case False\n  then show ?thesis by (auto dest: finite_UnionD intro: infinite)\nqed\n\nlemma distrib: \"F (\\<lambda>x. g x \\<^bold>* h x) A = F g A \\<^bold>* F h A\"\n  by (induct A rule: infinite_finite_induct) (simp_all add: assoc commute left_commute)\n\nlemma Sigma:\n  assumes \"finite A\" \"\\<forall>x\\<in>A. finite (B x)\"\n  shows \"F (\\<lambda>x. F (g x) (B x)) A = F (case_prod g) (SIGMA x:A. B x)\"\n  unfolding Sigma_def\nproof (subst UNION_disjoint)\n  show \"F (\\<lambda>x. F (g x) (B x)) A = F (\\<lambda>x. F (\\<lambda>(x, y). g x y) (\\<Union>y\\<in>B x. {(x, y)})) A\"\n  proof (rule cong [OF refl])\n    show \"F (g x) (B x) = F (\\<lambda>(x, y). g x y) (\\<Union>y\\<in>B x. {(x, y)})\"\n      if \"x \\<in> A\" for x\n      using that assms by (simp add: UNION_disjoint)\n  qed\nqed (use assms in auto)\n\nlemma related:\n  assumes Re: \"R \\<^bold>1 \\<^bold>1\"\n    and Rop: \"\\<forall>x1 y1 x2 y2. R x1 x2 \\<and> R y1 y2 \\<longrightarrow> R (x1 \\<^bold>* y1) (x2 \\<^bold>* y2)\"\n    and fin: \"finite S\"\n    and R_h_g: \"\\<forall>x\\<in>S. R (h x) (g x)\"\n  shows \"R (F h S) (F g S)\"\n  using fin by (rule finite_subset_induct) (use assms in auto)\n\nlemma mono_neutral_cong_left:\n  assumes \"finite T\"\n    and \"S \\<subseteq> T\"\n    and \"\\<forall>i \\<in> T - S. h i = \\<^bold>1\"\n    and \"\\<And>x. x \\<in> S \\<Longrightarrow> g x = h x\"\n  shows \"F g S = F h T\"\nproof-\n  have eq: \"T = S \\<union> (T - S)\" using \\<open>S \\<subseteq> T\\<close> by blast\n  have d: \"S \\<inter> (T - S) = {}\" using \\<open>S \\<subseteq> T\\<close> by blast\n  from \\<open>finite T\\<close> \\<open>S \\<subseteq> T\\<close> have f: \"finite S\" \"finite (T - S)\"\n    by (auto intro: finite_subset)\n  show ?thesis using assms(4)\n    by (simp add: union_disjoint [OF f d, unfolded eq [symmetric]] neutral [OF assms(3)])\nqed\n\nlemma mono_neutral_cong_right:\n  \"finite T \\<Longrightarrow> S \\<subseteq> T \\<Longrightarrow> \\<forall>i \\<in> T - S. g i = \\<^bold>1 \\<Longrightarrow> (\\<And>x. x \\<in> S \\<Longrightarrow> g x = h x) \\<Longrightarrow>\n    F g T = F h S\"\n  by (auto intro!: mono_neutral_cong_left [symmetric])\n\nlemma mono_neutral_left: \"finite T \\<Longrightarrow> S \\<subseteq> T \\<Longrightarrow> \\<forall>i \\<in> T - S. g i = \\<^bold>1 \\<Longrightarrow> F g S = F g T\"\n  by (blast intro: mono_neutral_cong_left)\n\nlemma mono_neutral_right: \"finite T \\<Longrightarrow> S \\<subseteq> T \\<Longrightarrow> \\<forall>i \\<in> T - S. g i = \\<^bold>1 \\<Longrightarrow> F g T = F g S\"\n  by (blast intro!: mono_neutral_left [symmetric])\n\nlemma mono_neutral_cong:\n  assumes [simp]: \"finite T\" \"finite S\"\n    and *: \"\\<And>i. i \\<in> T - S \\<Longrightarrow> h i = \\<^bold>1\" \"\\<And>i. i \\<in> S - T \\<Longrightarrow> g i = \\<^bold>1\"\n    and gh: \"\\<And>x. x \\<in> S \\<inter> T \\<Longrightarrow> g x = h x\"\n shows \"F g S = F h T\"\nproof-\n  have \"F g S = F g (S \\<inter> T)\"\n    by(rule mono_neutral_right)(auto intro: *)\n  also have \"\\<dots> = F h (S \\<inter> T)\" using refl gh by(rule cong)\n  also have \"\\<dots> = F h T\"\n    by(rule mono_neutral_left)(auto intro: *)\n  finally show ?thesis .\nqed\n\nlemma reindex_bij_betw: \"bij_betw h S T \\<Longrightarrow> F (\\<lambda>x. g (h x)) S = F g T\"\n  by (auto simp: bij_betw_def reindex)\n\nlemma reindex_bij_witness:\n  assumes witness:\n    \"\\<And>a. a \\<in> S \\<Longrightarrow> i (j a) = a\"\n    \"\\<And>a. a \\<in> S \\<Longrightarrow> j a \\<in> T\"\n    \"\\<And>b. b \\<in> T \\<Longrightarrow> j (i b) = b\"\n    \"\\<And>b. b \\<in> T \\<Longrightarrow> i b \\<in> S\"\n  assumes eq:\n    \"\\<And>a. a \\<in> S \\<Longrightarrow> h (j a) = g a\"\n  shows \"F g S = F h T\"\nproof -\n  have \"bij_betw j S T\"\n    using bij_betw_byWitness[where A=S and f=j and f'=i and A'=T] witness by auto\n  moreover have \"F g S = F (\\<lambda>x. h (j x)) S\"\n    by (intro cong) (auto simp: eq)\n  ultimately show ?thesis\n    by (simp add: reindex_bij_betw)\nqed\n\nlemma reindex_bij_betw_not_neutral:\n  assumes fin: \"finite S'\" \"finite T'\"\n  assumes bij: \"bij_betw h (S - S') (T - T')\"\n  assumes nn:\n    \"\\<And>a. a \\<in> S' \\<Longrightarrow> g (h a) = z\"\n    \"\\<And>b. b \\<in> T' \\<Longrightarrow> g b = z\"\n  shows \"F (\\<lambda>x. g (h x)) S = F g T\"\nproof -\n  have [simp]: \"finite S \\<longleftrightarrow> finite T\"\n    using bij_betw_finite[OF bij] fin by auto\n  show ?thesis\n  proof (cases \"finite S\")\n    case True\n    with nn have \"F (\\<lambda>x. g (h x)) S = F (\\<lambda>x. g (h x)) (S - S')\"\n      by (intro mono_neutral_cong_right) auto\n    also have \"\\<dots> = F g (T - T')\"\n      using bij by (rule reindex_bij_betw)\n    also have \"\\<dots> = F g T\"\n      using nn \\<open>finite S\\<close> by (intro mono_neutral_cong_left) auto\n    finally show ?thesis .\n  next\n    case False\n    then show ?thesis by simp\n  qed\nqed\n\nlemma reindex_nontrivial:\n  assumes \"finite A\"\n    and nz: \"\\<And>x y. x \\<in> A \\<Longrightarrow> y \\<in> A \\<Longrightarrow> x \\<noteq> y \\<Longrightarrow> h x = h y \\<Longrightarrow> g (h x) = \\<^bold>1\"\n  shows \"F g (h ` A) = F (g \\<circ> h) A\"\nproof (subst reindex_bij_betw_not_neutral [symmetric])\n  show \"bij_betw h (A - {x \\<in> A. (g \\<circ> h) x = \\<^bold>1}) (h ` A - h ` {x \\<in> A. (g \\<circ> h) x = \\<^bold>1})\"\n    using nz by (auto intro!: inj_onI simp: bij_betw_def)\nqed (use \\<open>finite A\\<close> in auto)\n\nlemma reindex_bij_witness_not_neutral:\n  assumes fin: \"finite S'\" \"finite T'\"\n  assumes witness:\n    \"\\<And>a. a \\<in> S - S' \\<Longrightarrow> i (j a) = a\"\n    \"\\<And>a. a \\<in> S - S' \\<Longrightarrow> j a \\<in> T - T'\"\n    \"\\<And>b. b \\<in> T - T' \\<Longrightarrow> j (i b) = b\"\n    \"\\<And>b. b \\<in> T - T' \\<Longrightarrow> i b \\<in> S - S'\"\n  assumes nn:\n    \"\\<And>a. a \\<in> S' \\<Longrightarrow> g a = z\"\n    \"\\<And>b. b \\<in> T' \\<Longrightarrow> h b = z\"\n  assumes eq:\n    \"\\<And>a. a \\<in> S \\<Longrightarrow> h (j a) = g a\"\n  shows \"F g S = F h T\"\nproof -\n  have bij: \"bij_betw j (S - (S' \\<inter> S)) (T - (T' \\<inter> T))\"\n    using witness by (intro bij_betw_byWitness[where f'=i]) auto\n  have F_eq: \"F g S = F (\\<lambda>x. h (j x)) S\"\n    by (intro cong) (auto simp: eq)\n  show ?thesis\n    unfolding F_eq using fin nn eq\n    by (intro reindex_bij_betw_not_neutral[OF _ _ bij]) auto\nqed\n\nlemma delta_remove:\n  assumes fS: \"finite S\"\n  shows \"F (\\<lambda>k. if k = a then b k else c k) S = (if a \\<in> S then b a \\<^bold>* F c (S-{a}) else F c (S-{a}))\"\nproof -\n  let ?f = \"(\\<lambda>k. if k = a then b k else c k)\"\n  show ?thesis\n  proof (cases \"a \\<in> S\")\n    case False\n    then have \"\\<forall>k\\<in>S. ?f k = c k\" by simp\n    with False show ?thesis by simp\n  next\n    case True\n    let ?A = \"S - {a}\"\n    let ?B = \"{a}\"\n    from True have eq: \"S = ?A \\<union> ?B\" by blast\n    have dj: \"?A \\<inter> ?B = {}\" by simp\n    from fS have fAB: \"finite ?A\" \"finite ?B\" by auto\n    have \"F ?f S = F ?f ?A \\<^bold>* F ?f ?B\"\n      using union_disjoint [OF fAB dj, of ?f, unfolded eq [symmetric]] by simp\n    with True show ?thesis\n      using comm_monoid_set.remove comm_monoid_set_axioms fS by fastforce\n  qed\nqed\n\nlemma delta [simp]:\n  assumes fS: \"finite S\"\n  shows \"F (\\<lambda>k. if k = a then b k else \\<^bold>1) S = (if a \\<in> S then b a else \\<^bold>1)\"\n  by (simp add: delta_remove [OF assms])\n\nlemma delta' [simp]:\n  assumes fin: \"finite S\"\n  shows \"F (\\<lambda>k. if a = k then b k else \\<^bold>1) S = (if a \\<in> S then b a else \\<^bold>1)\"\n  using delta [OF fin, of a b, symmetric] by (auto intro: cong)\n\nlemma If_cases:\n  fixes P :: \"'b \\<Rightarrow> bool\" and g h :: \"'b \\<Rightarrow> 'a\"\n  assumes fin: \"finite A\"\n  shows \"F (\\<lambda>x. if P x then h x else g x) A = F h (A \\<inter> {x. P x}) \\<^bold>* F g (A \\<inter> - {x. P x})\"\nproof -\n  have a: \"A = A \\<inter> {x. P x} \\<union> A \\<inter> -{x. P x}\" \"(A \\<inter> {x. P x}) \\<inter> (A \\<inter> -{x. P x}) = {}\"\n    by blast+\n  from fin have f: \"finite (A \\<inter> {x. P x})\" \"finite (A \\<inter> -{x. P x})\" by auto\n  let ?g = \"\\<lambda>x. if P x then h x else g x\"\n  from union_disjoint [OF f a(2), of ?g] a(1) show ?thesis\n    by (subst (1 2) cong) simp_all\nqed\n\nlemma cartesian_product: \"F (\\<lambda>x. F (g x) B) A = F (case_prod g) (A \\<times> B)\"\nproof (cases \"A = {} \\<or> B = {}\")\n  case True\n  then show ?thesis\n    by auto\nnext\n  case False\n  then have \"A \\<noteq> {}\" \"B \\<noteq> {}\" by auto\n  show ?thesis\n  proof (cases \"finite A \\<and> finite B\")\n    case True\n    then show ?thesis\n      by (simp add: Sigma)\n  next\n    case False\n    then consider \"infinite A\" | \"infinite B\" by auto\n    then have \"infinite (A \\<times> B)\"\n      by cases (use \\<open>A \\<noteq> {}\\<close> \\<open>B \\<noteq> {}\\<close> in \\<open>auto dest: finite_cartesian_productD1 finite_cartesian_productD2\\<close>)\n    then show ?thesis\n      using False by auto\n  qed\nqed\n\nlemma inter_restrict:\n  assumes \"finite A\"\n  shows \"F g (A \\<inter> B) = F (\\<lambda>x. if x \\<in> B then g x else \\<^bold>1) A\"\nproof -\n  let ?g = \"\\<lambda>x. if x \\<in> A \\<inter> B then g x else \\<^bold>1\"\n  have \"\\<forall>i\\<in>A - A \\<inter> B. (if i \\<in> A \\<inter> B then g i else \\<^bold>1) = \\<^bold>1\" by simp\n  moreover have \"A \\<inter> B \\<subseteq> A\" by blast\n  ultimately have \"F ?g (A \\<inter> B) = F ?g A\"\n    using \\<open>finite A\\<close> by (intro mono_neutral_left) auto\n  then show ?thesis by simp\nqed\n\nlemma inter_filter:\n  \"finite A \\<Longrightarrow> F g {x \\<in> A. P x} = F (\\<lambda>x. if P x then g x else \\<^bold>1) A\"\n  by (simp add: inter_restrict [symmetric, of A \"{x. P x}\" g, simplified mem_Collect_eq] Int_def)\n\nlemma Union_comp:\n  assumes \"\\<forall>A \\<in> B. finite A\"\n    and \"\\<And>A1 A2 x. A1 \\<in> B \\<Longrightarrow> A2 \\<in> B \\<Longrightarrow> A1 \\<noteq> A2 \\<Longrightarrow> x \\<in> A1 \\<Longrightarrow> x \\<in> A2 \\<Longrightarrow> g x = \\<^bold>1\"\n  shows \"F g (\\<Union>B) = (F \\<circ> F) g B\"\n  using assms\nproof (induct B rule: infinite_finite_induct)\n  case (infinite A)\n  then have \"\\<not> finite (\\<Union>A)\" by (blast dest: finite_UnionD)\n  with infinite show ?case by simp\nnext\n  case empty\n  then show ?case by simp\nnext\n  case (insert A B)\n  then have \"finite A\" \"finite B\" \"finite (\\<Union>B)\" \"A \\<notin> B\"\n    and \"\\<forall>x\\<in>A \\<inter> \\<Union>B. g x = \\<^bold>1\"\n    and H: \"F g (\\<Union>B) = (F \\<circ> F) g B\" by auto\n  then have \"F g (A \\<union> \\<Union>B) = F g A \\<^bold>* F g (\\<Union>B)\"\n    by (simp add: union_inter_neutral)\n  with \\<open>finite B\\<close> \\<open>A \\<notin> B\\<close> show ?case\n    by (simp add: H)\nqed\n\nlemma swap: \"F (\\<lambda>i. F (g i) B) A = F (\\<lambda>j. F (\\<lambda>i. g i j) A) B\"\n  unfolding cartesian_product\n  by (rule reindex_bij_witness [where i = \"\\<lambda>(i, j). (j, i)\" and j = \"\\<lambda>(i, j). (j, i)\"]) auto\n\nlemma swap_restrict:\n  \"finite A \\<Longrightarrow> finite B \\<Longrightarrow>\n    F (\\<lambda>x. F (g x) {y. y \\<in> B \\<and> R x y}) A = F (\\<lambda>y. F (\\<lambda>x. g x y) {x. x \\<in> A \\<and> R x y}) B\"\n  by (simp add: inter_filter) (rule swap)\n\nlemma image_gen:\n  assumes fin: \"finite S\"\n  shows \"F h S = F (\\<lambda>y. F h {x. x \\<in> S \\<and> g x = y}) (g ` S)\"\nproof -\n  have \"{y. y\\<in> g`S \\<and> g x = y} = {g x}\" if \"x \\<in> S\" for x\n    using that by auto\n  then have \"F h S = F (\\<lambda>x. F (\\<lambda>y. h x) {y. y\\<in> g`S \\<and> g x = y}) S\"\n    by simp\n  also have \"\\<dots> = F (\\<lambda>y. F h {x. x \\<in> S \\<and> g x = y}) (g ` S)\"\n    by (rule swap_restrict [OF fin finite_imageI [OF fin]])\n  finally show ?thesis .\nqed\n\nlemma group:\n  assumes fS: \"finite S\" and fT: \"finite T\" and fST: \"g ` S \\<subseteq> T\"\n  shows \"F (\\<lambda>y. F h {x. x \\<in> S \\<and> g x = y}) T = F h S\"\n  unfolding image_gen[OF fS, of h g]\n  by (auto intro: neutral mono_neutral_right[OF fT fST])\n\nlemma Plus:\n  fixes A :: \"'b set\" and B :: \"'c set\"\n  assumes fin: \"finite A\" \"finite B\"\n  shows \"F g (A <+> B) = F (g \\<circ> Inl) A \\<^bold>* F (g \\<circ> Inr) B\"\nproof -\n  have \"A <+> B = Inl ` A \\<union> Inr ` B\" by auto\n  moreover from fin have \"finite (Inl ` A)\" \"finite (Inr ` B)\" by auto\n  moreover have \"Inl ` A \\<inter> Inr ` B = {}\" by auto\n  moreover have \"inj_on Inl A\" \"inj_on Inr B\" by (auto intro: inj_onI)\n  ultimately show ?thesis\n    using fin by (simp add: union_disjoint reindex)\nqed\n\nlemma same_carrier:\n  assumes \"finite C\"\n  assumes subset: \"A \\<subseteq> C\" \"B \\<subseteq> C\"\n  assumes trivial: \"\\<And>a. a \\<in> C - A \\<Longrightarrow> g a = \\<^bold>1\" \"\\<And>b. b \\<in> C - B \\<Longrightarrow> h b = \\<^bold>1\"\n  shows \"F g A = F h B \\<longleftrightarrow> F g C = F h C\"\nproof -\n  have \"finite A\" and \"finite B\" and \"finite (C - A)\" and \"finite (C - B)\"\n    using \\<open>finite C\\<close> subset by (auto elim: finite_subset)\n  from subset have [simp]: \"A - (C - A) = A\" by auto\n  from subset have [simp]: \"B - (C - B) = B\" by auto\n  from subset have \"C = A \\<union> (C - A)\" by auto\n  then have \"F g C = F g (A \\<union> (C - A))\" by simp\n  also have \"\\<dots> = F g (A - (C - A)) \\<^bold>* F g (C - A - A) \\<^bold>* F g (A \\<inter> (C - A))\"\n    using \\<open>finite A\\<close> \\<open>finite (C - A)\\<close> by (simp only: union_diff2)\n  finally have *: \"F g C = F g A\" using trivial by simp\n  from subset have \"C = B \\<union> (C - B)\" by auto\n  then have \"F h C = F h (B \\<union> (C - B))\" by simp\n  also have \"\\<dots> = F h (B - (C - B)) \\<^bold>* F h (C - B - B) \\<^bold>* F h (B \\<inter> (C - B))\"\n    using \\<open>finite B\\<close> \\<open>finite (C - B)\\<close> by (simp only: union_diff2)\n  finally have \"F h C = F h B\"\n    using trivial by simp\n  with * show ?thesis by simp\nqed\n\nlemma same_carrierI:\n  assumes \"finite C\"\n  assumes subset: \"A \\<subseteq> C\" \"B \\<subseteq> C\"\n  assumes trivial: \"\\<And>a. a \\<in> C - A \\<Longrightarrow> g a = \\<^bold>1\" \"\\<And>b. b \\<in> C - B \\<Longrightarrow> h b = \\<^bold>1\"\n  assumes \"F g C = F h C\"\n  shows \"F g A = F h B\"\n  using assms same_carrier [of C A B] by simp\n\nlemma eq_general:\n  assumes B: \"\\<And>y. y \\<in> B \\<Longrightarrow> \\<exists>!x. x \\<in> A \\<and> h x = y\" and A: \"\\<And>x. x \\<in> A \\<Longrightarrow> h x \\<in> B \\<and> \\<gamma>(h x) = \\<phi> x\"\n  shows \"F \\<phi> A = F \\<gamma> B\"\nproof -\n  have eq: \"B = h ` A\"\n    by (auto dest: assms)\n  have h: \"inj_on h A\"\n    using assms by (blast intro: inj_onI)\n  have \"F \\<phi> A = F (\\<gamma> \\<circ> h) A\"\n    using A by auto\n  also have \"\\<dots> = F \\<gamma> B\"\n    by (simp add: eq reindex h)\n  finally show ?thesis .\nqed\n\nlemma eq_general_inverses:\n  assumes B: \"\\<And>y. y \\<in> B \\<Longrightarrow> k y \\<in> A \\<and> h(k y) = y\" and A: \"\\<And>x. x \\<in> A \\<Longrightarrow> h x \\<in> B \\<and> k(h x) = x \\<and> \\<gamma>(h x) = \\<phi> x\"\n  shows \"F \\<phi> A = F \\<gamma> B\"\n  by (rule eq_general [where h=h]) (force intro: dest: A B)+\n\nsubsubsection \\<open>HOL Light variant: sum/product indexed by the non-neutral subset\\<close>\ntext \\<open>NB only a subset of the properties above are proved\\<close>\n\ndefinition G :: \"['b \\<Rightarrow> 'a,'b set] \\<Rightarrow> 'a\"\n  where \"G p I \\<equiv> if finite {x \\<in> I. p x \\<noteq> \\<^bold>1} then F p {x \\<in> I. p x \\<noteq> \\<^bold>1} else \\<^bold>1\"\n\nlemma finite_Collect_op:\n  shows \"\\<lbrakk>finite {i \\<in> I. x i \\<noteq> \\<^bold>1}; finite {i \\<in> I. y i \\<noteq> \\<^bold>1}\\<rbrakk> \\<Longrightarrow> finite {i \\<in> I. x i \\<^bold>* y i \\<noteq> \\<^bold>1}\"\n  apply (rule finite_subset [where B = \"{i \\<in> I. x i \\<noteq> \\<^bold>1} \\<union> {i \\<in> I. y i \\<noteq> \\<^bold>1}\"]) \n  using left_neutral by force+\n\nlemma empty' [simp]: \"G p {} = \\<^bold>1\"\n  by (auto simp: G_def)\n\nlemma eq_sum [simp]: \"finite I \\<Longrightarrow> G p I = F p I\"\n  by (auto simp: G_def intro: mono_neutral_cong_left)\n\nlemma insert' [simp]:\n  assumes \"finite {x \\<in> I. p x \\<noteq> \\<^bold>1}\"\n  shows \"G p (insert i I) = (if i \\<in> I then G p I else p i \\<^bold>* G p I)\"\nproof -\n  have \"{x. x = i \\<and> p x \\<noteq> \\<^bold>1 \\<or> x \\<in> I \\<and> p x \\<noteq> \\<^bold>1} = (if p i = \\<^bold>1 then {x \\<in> I. p x \\<noteq> \\<^bold>1} else insert i {x \\<in> I. p x \\<noteq> \\<^bold>1})\"\n    by auto\n  then show ?thesis\n    using assms by (simp add: G_def conj_disj_distribR insert_absorb)\nqed\n\nlemma distrib_triv':\n  assumes \"finite I\"\n  shows \"G (\\<lambda>i. g i \\<^bold>* h i) I = G g I \\<^bold>* G h I\"\n  by (simp add: assms local.distrib)\n\nlemma non_neutral': \"G g {x \\<in> I. g x \\<noteq> \\<^bold>1} = G g I\"\n  by (simp add: G_def)\n\nlemma distrib':\n  assumes \"finite {x \\<in> I. g x \\<noteq> \\<^bold>1}\" \"finite {x \\<in> I. h x \\<noteq> \\<^bold>1}\"\n  shows \"G (\\<lambda>i. g i \\<^bold>* h i) I = G g I \\<^bold>* G h I\"\nproof -\n  have \"a \\<^bold>* a \\<noteq> a \\<Longrightarrow> a \\<noteq> \\<^bold>1\" for a\n    by auto\n  then have \"G (\\<lambda>i. g i \\<^bold>* h i) I = G (\\<lambda>i. g i \\<^bold>* h i) ({i \\<in> I. g i \\<noteq> \\<^bold>1} \\<union> {i \\<in> I. h i \\<noteq> \\<^bold>1})\"\n    using assms  by (force simp: G_def finite_Collect_op intro!: mono_neutral_cong)\n  also have \"\\<dots> = G g I \\<^bold>* G h I\"\n  proof -\n    have \"F g ({i \\<in> I. g i \\<noteq> \\<^bold>1} \\<union> {i \\<in> I. h i \\<noteq> \\<^bold>1}) = G g I\"\n         \"F h ({i \\<in> I. g i \\<noteq> \\<^bold>1} \\<union> {i \\<in> I. h i \\<noteq> \\<^bold>1}) = G h I\"\n      by (auto simp: G_def assms intro: mono_neutral_right)\n    then show ?thesis\n      using assms by (simp add: distrib)\n  qed\n  finally show ?thesis .\nqed\n\nlemma cong':\n  assumes \"A = B\"\n  assumes g_h: \"\\<And>x. x \\<in> B \\<Longrightarrow> g x = h x\"\n  shows \"G g A = G h B\"\n  using assms by (auto simp: G_def cong: conj_cong intro: cong)\n\n\nlemma mono_neutral_cong_left':\n  assumes \"S \\<subseteq> T\"\n    and \"\\<And>i. i \\<in> T - S \\<Longrightarrow> h i = \\<^bold>1\"\n    and \"\\<And>x. x \\<in> S \\<Longrightarrow> g x = h x\"\n  shows \"G g S = G h T\"\nproof -\n  have *: \"{x \\<in> S. g x \\<noteq> \\<^bold>1} = {x \\<in> T. h x \\<noteq> \\<^bold>1}\"\n    using assms by (metis DiffI subset_eq) \n  then have \"finite {x \\<in> S. g x \\<noteq> \\<^bold>1} = finite {x \\<in> T. h x \\<noteq> \\<^bold>1}\"\n    by simp\n  then show ?thesis\n    using assms by (auto simp add: G_def * intro: cong)\nqed\n\nlemma mono_neutral_cong_right':\n  \"S \\<subseteq> T \\<Longrightarrow> \\<forall>i \\<in> T - S. g i = \\<^bold>1 \\<Longrightarrow> (\\<And>x. x \\<in> S \\<Longrightarrow> g x = h x) \\<Longrightarrow>\n    G g T = G h S\"\n  by (auto intro!: mono_neutral_cong_left' [symmetric])\n\nlemma mono_neutral_left': \"S \\<subseteq> T \\<Longrightarrow> \\<forall>i \\<in> T - S. g i = \\<^bold>1 \\<Longrightarrow> G g S = G g T\"\n  by (blast intro: mono_neutral_cong_left')\n\nlemma mono_neutral_right': \"S \\<subseteq> T \\<Longrightarrow> \\<forall>i \\<in> T - S. g i = \\<^bold>1 \\<Longrightarrow> G g T = G g S\"\n  by (blast intro!: mono_neutral_left' [symmetric])\n\nend\n\n\nsubsection \\<open>Generalized summation over a set\\<close>\n\ncontext comm_monoid_add\nbegin\n\nsublocale sum: comm_monoid_set plus 0\n  defines sum = sum.F and sum' = sum.G ..\n\nabbreviation Sum (\"\\<Sum>\")\n  where \"\\<Sum> \\<equiv> sum (\\<lambda>x. x)\"\n\nend\n\ntext \\<open>Now: lots of fancy syntax. First, \\<^term>\\<open>sum (\\<lambda>x. e) A\\<close> is written \\<open>\\<Sum>x\\<in>A. e\\<close>.\\<close>\n\nsyntax (ASCII)\n  \"_sum\" :: \"pttrn \\<Rightarrow> 'a set \\<Rightarrow> 'b \\<Rightarrow> 'b::comm_monoid_add\"  (\"(3SUM (_/:_)./ _)\" [0, 51, 10] 10)\nsyntax\n  \"_sum\" :: \"pttrn \\<Rightarrow> 'a set \\<Rightarrow> 'b \\<Rightarrow> 'b::comm_monoid_add\"  (\"(2\\<Sum>(_/\\<in>_)./ _)\" [0, 51, 10] 10)\ntranslations \\<comment> \\<open>Beware of argument permutation!\\<close>\n  \"\\<Sum>i\\<in>A. b\" \\<rightleftharpoons> \"CONST sum (\\<lambda>i. b) A\"\n\ntext \\<open>Instead of \\<^term>\\<open>\\<Sum>x\\<in>{x. P}. e\\<close> we introduce the shorter \\<open>\\<Sum>x|P. e\\<close>.\\<close>\n\nsyntax (ASCII)\n  \"_qsum\" :: \"pttrn \\<Rightarrow> bool \\<Rightarrow> 'a \\<Rightarrow> 'a\"  (\"(3SUM _ |/ _./ _)\" [0, 0, 10] 10)\nsyntax\n  \"_qsum\" :: \"pttrn \\<Rightarrow> bool \\<Rightarrow> 'a \\<Rightarrow> 'a\"  (\"(2\\<Sum>_ | (_)./ _)\" [0, 0, 10] 10)\ntranslations\n  \"\\<Sum>x|P. t\" => \"CONST sum (\\<lambda>x. t) {x. P}\"\n\nprint_translation \\<open>\nlet\n  fun sum_tr' [Abs (x, Tx, t), Const (\\<^const_syntax>\\<open>Collect\\<close>, _) $ Abs (y, Ty, P)] =\n        if x <> y then raise Match\n        else\n          let\n            val x' = Syntax_Trans.mark_bound_body (x, Tx);\n            val t' = subst_bound (x', t);\n            val P' = subst_bound (x', P);\n          in\n            Syntax.const \\<^syntax_const>\\<open>_qsum\\<close> $ Syntax_Trans.mark_bound_abs (x, Tx) $ P' $ t'\n          end\n    | sum_tr' _ = raise Match;\nin [(\\<^const_syntax>\\<open>sum\\<close>, K sum_tr')] end\n\\<close>\n\n\nsubsubsection \\<open>Properties in more restricted classes of structures\\<close>\n\nlemma sum_Un:\n  \"finite A \\<Longrightarrow> finite B \\<Longrightarrow> sum f (A \\<union> B) = sum f A + sum f B - sum f (A \\<inter> B)\"\n  for f :: \"'b \\<Rightarrow> 'a::ab_group_add\"\n  by (subst sum.union_inter [symmetric]) (auto simp add: algebra_simps)\n\nlemma sum_Un2:\n  assumes \"finite (A \\<union> B)\"\n  shows \"sum f (A \\<union> B) = sum f (A - B) + sum f (B - A) + sum f (A \\<inter> B)\"\nproof -\n  have \"A \\<union> B = A - B \\<union> (B - A) \\<union> A \\<inter> B\"\n    by auto\n  with assms show ?thesis\n    by simp (subst sum.union_disjoint, auto)+\nqed\n\nlemma sum_diff1:\n  fixes f :: \"'b \\<Rightarrow> 'a::ab_group_add\"\n  assumes \"finite A\"\n  shows \"sum f (A - {a}) = (if a \\<in> A then sum f A - f a else sum f A)\"\n  using assms by induct (auto simp: insert_Diff_if)\n\nlemma sum_diff:\n  fixes f :: \"'b \\<Rightarrow> 'a::ab_group_add\"\n  assumes \"finite A\" \"B \\<subseteq> A\"\n  shows \"sum f (A - B) = sum f A - sum f B\"\nproof -\n  from assms(2,1) have \"finite B\" by (rule finite_subset)\n  from this \\<open>B \\<subseteq> A\\<close>\n  show ?thesis\n  proof induct\n    case empty\n    thus ?case by simp\n  next\n    case (insert x F)\n    with \\<open>finite A\\<close> \\<open>finite B\\<close> show ?case\n      by (simp add: Diff_insert[where a=x and B=F] sum_diff1 insert_absorb)\n  qed\nqed\n\nlemma sum_diff1'_aux:\n  fixes f :: \"'a \\<Rightarrow> 'b::ab_group_add\"\n  assumes \"finite F\" \"{i \\<in> I. f i \\<noteq> 0} \\<subseteq> F\"\n  shows \"sum' f (I - {i}) = (if i \\<in> I then sum' f I - f i else sum' f I)\"\n  using assms\nproof induct\n  case (insert x F)\n  have 1: \"finite {x \\<in> I. f x \\<noteq> 0} \\<Longrightarrow> finite {x \\<in> I. x \\<noteq> i \\<and> f x \\<noteq> 0}\"\n    by (erule rev_finite_subset) auto\n  have 2: \"finite {x \\<in> I. x \\<noteq> i \\<and> f x \\<noteq> 0} \\<Longrightarrow> finite {x \\<in> I. f x \\<noteq> 0}\"\n    apply (drule finite_insert [THEN iffD2])\n    by (erule rev_finite_subset) auto\n  have 3: \"finite {i \\<in> I. f i \\<noteq> 0}\"\n    using finite_subset insert by blast\n  show ?case\n    using insert sum_diff1 [of \"{i \\<in> I. f i \\<noteq> 0}\" f i]\n    by (auto simp: sum.G_def 1 2 3 set_diff_eq conj_ac)\nqed (simp add: sum.G_def)\n\nlemma sum_diff1':\n  fixes f :: \"'a \\<Rightarrow> 'b::ab_group_add\"\n  assumes \"finite {i \\<in> I. f i \\<noteq> 0}\"\n  shows \"sum' f (I - {i}) = (if i \\<in> I then sum' f I - f i else sum' f I)\"\n  by (rule sum_diff1'_aux [OF assms order_refl])\n\nlemma (in ordered_comm_monoid_add) sum_mono:\n  \"(\\<And>i. i\\<in>K \\<Longrightarrow> f i \\<le> g i) \\<Longrightarrow> (\\<Sum>i\\<in>K. f i) \\<le> (\\<Sum>i\\<in>K. g i)\"\n  by (induct K rule: infinite_finite_induct) (use add_mono in auto)\n\nlemma (in strict_ordered_comm_monoid_add) sum_strict_mono:\n  assumes \"finite A\" \"A \\<noteq> {}\"\n    and \"\\<And>x. x \\<in> A \\<Longrightarrow> f x < g x\"\n  shows \"sum f A < sum g A\"\n  using assms\nproof (induct rule: finite_ne_induct)\n  case singleton\n  then show ?case by simp\nnext\n  case insert\n  then show ?case by (auto simp: add_strict_mono)\nqed\n\nlemma sum_strict_mono_ex1:\n  fixes f g :: \"'i \\<Rightarrow> 'a::ordered_cancel_comm_monoid_add\"\n  assumes \"finite A\"\n    and \"\\<forall>x\\<in>A. f x \\<le> g x\"\n    and \"\\<exists>a\\<in>A. f a < g a\"\n  shows \"sum f A < sum g A\"\nproof-\n  from assms(3) obtain a where a: \"a \\<in> A\" \"f a < 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 \"sum f (A - {a}) \\<le> sum g (A - {a})\"\n    by (rule sum_mono) (simp add: assms(2))\n  also from a have \"sum f {a} < sum g {a}\" by simp\n  also have \"sum g (A - {a}) + sum g {a} = 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 (auto simp add: add_right_mono add_strict_left_mono)\nqed\n\nlemma sum_mono_inv:\n  fixes f g :: \"'i \\<Rightarrow> 'a :: ordered_cancel_comm_monoid_add\"\n  assumes eq: \"sum f I = sum g I\"\n  assumes le: \"\\<And>i. i \\<in> I \\<Longrightarrow> f i \\<le> g i\"\n  assumes i: \"i \\<in> I\"\n  assumes I: \"finite I\"\n  shows \"f i = g i\"\nproof (rule ccontr)\n  assume \"\\<not> ?thesis\"\n  with le[OF i] have \"f i < g i\" by simp\n  with i have \"\\<exists>i\\<in>I. f i < g i\" ..\n  from sum_strict_mono_ex1[OF I _ this] le have \"sum f I < sum g I\"\n    by blast\n  with eq show False by simp\nqed\n\nlemma member_le_sum:\n  fixes f :: \"_ \\<Rightarrow> 'b::{semiring_1, ordered_comm_monoid_add}\"\n  assumes \"i \\<in> A\"\n    and le: \"\\<And>x. x \\<in> A - {i} \\<Longrightarrow> 0 \\<le> f x\"\n    and \"finite A\"\n  shows \"f i \\<le> sum f A\"\nproof -\n  have \"f i \\<le> sum f (A \\<inter> {i})\"\n    by (simp add: assms)\n  also have \"... = (\\<Sum>x\\<in>A. if x \\<in> {i} then f x else 0)\"\n    using assms sum.inter_restrict by blast\n  also have \"... \\<le> sum f A\"\n    apply (rule sum_mono)\n    apply (auto simp: le)\n    done\n  finally show ?thesis .\nqed\n\nlemma sum_negf: \"(\\<Sum>x\\<in>A. - f x) = - (\\<Sum>x\\<in>A. f x)\"\n  for f :: \"'b \\<Rightarrow> 'a::ab_group_add\"\n  by (induct A rule: infinite_finite_induct) auto\n\nlemma sum_subtractf: \"(\\<Sum>x\\<in>A. f x - g x) = (\\<Sum>x\\<in>A. f x) - (\\<Sum>x\\<in>A. g x)\"\n  for f g :: \"'b \\<Rightarrow>'a::ab_group_add\"\n  using sum.distrib [of f \"- g\" A] by (simp add: sum_negf)\n\nlemma sum_subtractf_nat:\n  \"(\\<And>x. x \\<in> A \\<Longrightarrow> g x \\<le> f x) \\<Longrightarrow> (\\<Sum>x\\<in>A. f x - g x) = (\\<Sum>x\\<in>A. f x) - (\\<Sum>x\\<in>A. g x)\"\n  for f g :: \"'a \\<Rightarrow> nat\"\n  by (induct A rule: infinite_finite_induct) (auto simp: sum_mono)\n\ncontext ordered_comm_monoid_add\nbegin\n\nlemma sum_nonneg: \"(\\<And>x. x \\<in> A \\<Longrightarrow> 0 \\<le> f x) \\<Longrightarrow> 0 \\<le> sum f A\"\nproof (induct A rule: infinite_finite_induct)\n  case infinite\n  then show ?case by simp\nnext\n  case empty\n  then show ?case by simp\nnext\n  case (insert x F)\n  then have \"0 + 0 \\<le> f x + sum f F\" by (blast intro: add_mono)\n  with insert show ?case by simp\nqed\n\nlemma sum_nonpos: \"(\\<And>x. x \\<in> A \\<Longrightarrow> f x \\<le> 0) \\<Longrightarrow> sum f A \\<le> 0\"\nproof (induct A rule: infinite_finite_induct)\n  case infinite\n  then show ?case by simp\nnext\n  case empty\n  then show ?case by simp\nnext\n  case (insert x F)\n  then have \"f x + sum f F \\<le> 0 + 0\" by (blast intro: add_mono)\n  with insert show ?case by simp\nqed\n\nlemma sum_nonneg_eq_0_iff:\n  \"finite A \\<Longrightarrow> (\\<And>x. x \\<in> A \\<Longrightarrow> 0 \\<le> f x) \\<Longrightarrow> sum f A = 0 \\<longleftrightarrow> (\\<forall>x\\<in>A. f x = 0)\"\n  by (induct set: finite) (simp_all add: add_nonneg_eq_0_iff sum_nonneg)\n\nlemma sum_nonneg_0:\n  \"finite s \\<Longrightarrow> (\\<And>i. i \\<in> s \\<Longrightarrow> f i \\<ge> 0) \\<Longrightarrow> (\\<Sum> i \\<in> s. f i) = 0 \\<Longrightarrow> i \\<in> s \\<Longrightarrow> f i = 0\"\n  by (simp add: sum_nonneg_eq_0_iff)\n\nlemma sum_nonneg_leq_bound:\n  assumes \"finite s\" \"\\<And>i. i \\<in> s \\<Longrightarrow> f i \\<ge> 0\" \"(\\<Sum>i \\<in> s. f i) = B\" \"i \\<in> s\"\n  shows \"f i \\<le> B\"\nproof -\n  from assms have \"f i \\<le> f i + (\\<Sum>i \\<in> s - {i}. f i)\"\n    by (intro add_increasing2 sum_nonneg) auto\n  also have \"\\<dots> = B\"\n    using sum.remove[of s i f] assms by simp\n  finally show ?thesis by auto\nqed\n\nlemma sum_mono2:\n  assumes fin: \"finite B\"\n    and sub: \"A \\<subseteq> B\"\n    and nn: \"\\<And>b. b \\<in> B-A \\<Longrightarrow> 0 \\<le> f b\"\n  shows \"sum f A \\<le> sum f B\"\nproof -\n  have \"sum f A \\<le> sum f A + sum f (B-A)\"\n    by (auto intro: add_increasing2 [OF sum_nonneg] nn)\n  also from fin finite_subset[OF sub fin] have \"\\<dots> = sum f (A \\<union> (B-A))\"\n    by (simp add: sum.union_disjoint del: Un_Diff_cancel)\n  also from sub have \"A \\<union> (B-A) = B\" by blast\n  finally show ?thesis .\nqed\n\nlemma sum_le_included:\n  assumes \"finite s\" \"finite t\"\n  and \"\\<forall>y\\<in>t. 0 \\<le> g y\" \"(\\<forall>x\\<in>s. \\<exists>y\\<in>t. i y = x \\<and> f x \\<le> g y)\"\n  shows \"sum f s \\<le> sum g t\"\nproof -\n  have \"sum f s \\<le> sum (\\<lambda>y. sum g {x. x\\<in>t \\<and> i x = y}) s\"\n  proof (rule sum_mono)\n    fix y\n    assume \"y \\<in> s\"\n    with assms obtain z where z: \"z \\<in> t\" \"y = i z\" \"f y \\<le> g z\" by auto\n    with assms show \"f y \\<le> sum g {x \\<in> t. i x = y}\" (is \"?A y \\<le> ?B y\")\n      using order_trans[of \"?A (i z)\" \"sum g {z}\" \"?B (i z)\", intro]\n      by (auto intro!: sum_mono2)\n  qed\n  also have \"\\<dots> \\<le> sum (\\<lambda>y. sum g {x. x\\<in>t \\<and> i x = y}) (i ` t)\"\n    using assms(2-4) by (auto intro!: sum_mono2 sum_nonneg)\n  also have \"\\<dots> \\<le> sum g t\"\n    using assms by (auto simp: sum.image_gen[symmetric])\n  finally show ?thesis .\nqed\n\nend\n\nlemma (in canonically_ordered_monoid_add) sum_eq_0_iff [simp]:\n  \"finite F \\<Longrightarrow> (sum f F = 0) = (\\<forall>a\\<in>F. f a = 0)\"\n  by (intro ballI sum_nonneg_eq_0_iff zero_le)\n\ncontext semiring_0\nbegin\n\nlemma sum_distrib_left: \"r * sum f A = (\\<Sum>n\\<in>A. r * f n)\"\n  by (induct A rule: infinite_finite_induct) (simp_all add: algebra_simps)\n\nlemma sum_distrib_right: \"sum f A * r = (\\<Sum>n\\<in>A. f n * r)\"\n  by (induct A rule: infinite_finite_induct) (simp_all add: algebra_simps)\n\nend\n\nlemma sum_divide_distrib: \"sum f A / r = (\\<Sum>n\\<in>A. f n / r)\"\n  for r :: \"'a::field\"\nproof (induct A rule: infinite_finite_induct)\n  case infinite\n  then show ?case by simp\nnext\n  case empty\n  then show ?case by simp\nnext\n  case insert\n  then show ?case by (simp add: add_divide_distrib)\nqed\n\nlemma sum_abs[iff]: \"\\<bar>sum f A\\<bar> \\<le> sum (\\<lambda>i. \\<bar>f i\\<bar>) A\"\n  for f :: \"'a \\<Rightarrow> 'b::ordered_ab_group_add_abs\"\nproof (induct A rule: infinite_finite_induct)\n  case infinite\n  then show ?case by simp\nnext\n  case empty\n  then show ?case by simp\nnext\n  case insert\n  then show ?case by (auto intro: abs_triangle_ineq order_trans)\nqed\n\nlemma sum_abs_ge_zero[iff]: \"0 \\<le> sum (\\<lambda>i. \\<bar>f i\\<bar>) A\"\n  for f :: \"'a \\<Rightarrow> 'b::ordered_ab_group_add_abs\"\n  by (simp add: sum_nonneg)\n\nlemma abs_sum_abs[simp]: \"\\<bar>\\<Sum>a\\<in>A. \\<bar>f a\\<bar>\\<bar> = (\\<Sum>a\\<in>A. \\<bar>f a\\<bar>)\"\n  for f :: \"'a \\<Rightarrow> 'b::ordered_ab_group_add_abs\"\nproof (induct A rule: infinite_finite_induct)\n  case infinite\n  then show ?case by simp\nnext\n  case empty\n  then show ?case by simp\nnext\n  case (insert a A)\n  then have \"\\<bar>\\<Sum>a\\<in>insert a A. \\<bar>f a\\<bar>\\<bar> = \\<bar>\\<bar>f a\\<bar> + (\\<Sum>a\\<in>A. \\<bar>f a\\<bar>)\\<bar>\" by simp\n  also from insert have \"\\<dots> = \\<bar>\\<bar>f a\\<bar> + \\<bar>\\<Sum>a\\<in>A. \\<bar>f a\\<bar>\\<bar>\\<bar>\" by simp\n  also have \"\\<dots> = \\<bar>f a\\<bar> + \\<bar>\\<Sum>a\\<in>A. \\<bar>f a\\<bar>\\<bar>\" by (simp del: abs_of_nonneg)\n  also from insert have \"\\<dots> = (\\<Sum>a\\<in>insert a A. \\<bar>f a\\<bar>)\" by simp\n  finally show ?case .\nqed\n\nlemma sum_product:\n  fixes f :: \"'a \\<Rightarrow> 'b::semiring_0\"\n  shows \"sum f A * sum g B = (\\<Sum>i\\<in>A. \\<Sum>j\\<in>B. f i * g j)\"\n  by (simp add: sum_distrib_left sum_distrib_right) (rule sum.swap)\n\nlemma sum_mult_sum_if_inj:\n  fixes f :: \"'a \\<Rightarrow> 'b::semiring_0\"\n  shows \"inj_on (\\<lambda>(a, b). f a * g b) (A \\<times> B) \\<Longrightarrow>\n    sum f A * sum g B = sum id {f a * g b |a b. a \\<in> A \\<and> b \\<in> B}\"\n  by(auto simp: sum_product sum.cartesian_product intro!: sum.reindex_cong[symmetric])\n\nlemma sum_SucD: \"sum f A = Suc n \\<Longrightarrow> \\<exists>a\\<in>A. 0 < f a\"\n  by (induct A rule: infinite_finite_induct) auto\n\nlemma sum_eq_Suc0_iff:\n  \"finite A \\<Longrightarrow> sum f A = Suc 0 \\<longleftrightarrow> (\\<exists>a\\<in>A. f a = Suc 0 \\<and> (\\<forall>b\\<in>A. a \\<noteq> b \\<longrightarrow> f b = 0))\"\n  by (induct A rule: finite_induct) (auto simp add: add_is_1)\n\nlemmas sum_eq_1_iff = sum_eq_Suc0_iff[simplified One_nat_def[symmetric]]\n\nlemma sum_Un_nat:\n  \"finite A \\<Longrightarrow> finite B \\<Longrightarrow> sum f (A \\<union> B) = sum f A + sum f B - sum f (A \\<inter> B)\"\n  for f :: \"'a \\<Rightarrow> nat\"\n  \\<comment> \\<open>For the natural numbers, we have subtraction.\\<close>\n  by (subst sum.union_inter [symmetric]) (auto simp: algebra_simps)\n\nlemma sum_diff1_nat: \"sum f (A - {a}) = (if a \\<in> A then sum f A - f a else sum f A)\"\n  for f :: \"'a \\<Rightarrow> nat\"\nproof (induct A rule: infinite_finite_induct)\n  case infinite\n  then show ?case by simp\nnext\n  case empty\n  then show ?case by simp\nnext\n  case insert\n  then show ?case\n    apply (auto simp: insert_Diff_if)\n    apply (drule mk_disjoint_insert)\n    apply auto\n    done\nqed\n\nlemma sum_diff_nat:\n  fixes f :: \"'a \\<Rightarrow> nat\"\n  assumes \"finite B\" and \"B \\<subseteq> A\"\n  shows \"sum f (A - B) = sum f A - sum f B\"\n  using assms\nproof induct\n  case empty\n  then show ?case by simp\nnext\n  case (insert x F)\n  note IH = \\<open>F \\<subseteq> A \\<Longrightarrow> sum f (A - F) = sum f A - sum f F\\<close>\n  from \\<open>x \\<notin> F\\<close> \\<open>insert x F \\<subseteq> A\\<close> have \"x \\<in> A - F\" by simp\n  then have A: \"sum f ((A - F) - {x}) = sum f (A - F) - f x\"\n    by (simp add: sum_diff1_nat)\n  from \\<open>insert x F \\<subseteq> A\\<close> have \"F \\<subseteq> A\" by simp\n  with IH have \"sum f (A - F) = sum f A - sum f F\" by simp\n  with A have B: \"sum f ((A - F) - {x}) = sum f A - sum f F - f x\"\n    by simp\n  from \\<open>x \\<notin> F\\<close> have \"A - insert x F = (A - F) - {x}\" by auto\n  with B have C: \"sum f (A - insert x F) = sum f A - sum f F - f x\"\n    by simp\n  from \\<open>finite F\\<close> \\<open>x \\<notin> F\\<close> have \"sum f (insert x F) = sum f F + f x\"\n    by simp\n  with C have \"sum f (A - insert x F) = sum f A - sum f (insert x F)\"\n    by simp\n  then show ?case by simp\nqed\n\nlemma sum_comp_morphism:\n  \"h 0 = 0 \\<Longrightarrow> (\\<And>x y. h (x + y) = h x + h y) \\<Longrightarrow> sum (h \\<circ> g) A = h (sum g A)\"\n  by (induct A rule: infinite_finite_induct) simp_all\n\nlemma (in comm_semiring_1) dvd_sum: \"(\\<And>a. a \\<in> A \\<Longrightarrow> d dvd f a) \\<Longrightarrow> d dvd sum f A\"\n  by (induct A rule: infinite_finite_induct) simp_all\n\nlemma (in ordered_comm_monoid_add) sum_pos:\n  \"finite I \\<Longrightarrow> I \\<noteq> {} \\<Longrightarrow> (\\<And>i. i \\<in> I \\<Longrightarrow> 0 < f i) \\<Longrightarrow> 0 < sum f I\"\n  by (induct I rule: finite_ne_induct) (auto intro: add_pos_pos)\n\nlemma (in ordered_comm_monoid_add) sum_pos2:\n  assumes I: \"finite I\" \"i \\<in> I\" \"0 < f i\" \"\\<And>i. i \\<in> I \\<Longrightarrow> 0 \\<le> f i\"\n  shows \"0 < sum f I\"\nproof -\n  have \"0 < f i + sum f (I - {i})\"\n    using assms by (intro add_pos_nonneg sum_nonneg) auto\n  also have \"\\<dots> = sum f I\"\n    using assms by (simp add: sum.remove)\n  finally show ?thesis .\nqed\n\nlemma sum_cong_Suc:\n  assumes \"0 \\<notin> A\" \"\\<And>x. Suc x \\<in> A \\<Longrightarrow> f (Suc x) = g (Suc x)\"\n  shows \"sum f A = sum g A\"\nproof (rule sum.cong)\n  fix x\n  assume \"x \\<in> A\"\n  with assms(1) show \"f x = g x\"\n    by (cases x) (auto intro!: assms(2))\nqed simp_all\n\n\nsubsubsection \\<open>Cardinality as special case of \\<^const>\\<open>sum\\<close>\\<close>\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\ncontext semiring_1\nbegin\n\nlemma sum_constant [simp]:\n  \"(\\<Sum>x \\<in> A. y) = of_nat (card A) * y\"\n  by (induct A rule: infinite_finite_induct) (simp_all add: algebra_simps)\n\nend\n\nlemma sum_Suc: \"sum (\\<lambda>x. Suc(f x)) A = sum f A + card A\"\n  using sum.distrib[of f \"\\<lambda>_. 1\" A] by simp\n\nlemma sum_bounded_above:\n  fixes K :: \"'a::{semiring_1,ordered_comm_monoid_add}\"\n  assumes le: \"\\<And>i. i\\<in>A \\<Longrightarrow> f i \\<le> K\"\n  shows \"sum f A \\<le> of_nat (card A) * K\"\nproof (cases \"finite A\")\n  case True\n  then show ?thesis\n    using le sum_mono[where K=A and g = \"\\<lambda>x. K\"] by simp\nnext\n  case False\n  then show ?thesis by simp\nqed\n\nlemma sum_bounded_above_divide:\n  fixes K :: \"'a::linordered_field\"\n  assumes le: \"\\<And>i. i\\<in>A \\<Longrightarrow> f i \\<le> K / of_nat (card A)\" and fin: \"finite A\" \"A \\<noteq> {}\"\n  shows \"sum f A \\<le> K\"\n  using sum_bounded_above [of A f \"K / of_nat (card A)\", OF le] fin by simp\n\nlemma sum_bounded_above_strict:\n  fixes K :: \"'a::{ordered_cancel_comm_monoid_add,semiring_1}\"\n  assumes \"\\<And>i. i\\<in>A \\<Longrightarrow> f i < K\" \"card A > 0\"\n  shows \"sum f A < of_nat (card A) * K\"\n  using assms sum_strict_mono[where A=A and g = \"\\<lambda>x. K\"]\n  by (simp add: card_gt_0_iff)\n\nlemma sum_bounded_below:\n  fixes K :: \"'a::{semiring_1,ordered_comm_monoid_add}\"\n  assumes le: \"\\<And>i. i\\<in>A \\<Longrightarrow> K \\<le> f i\"\n  shows \"of_nat (card A) * K \\<le> sum f A\"\nproof (cases \"finite A\")\n  case True\n  then show ?thesis\n    using le sum_mono[where K=A and f = \"\\<lambda>x. K\"] by simp\nnext\n  case False\n  then show ?thesis by simp\nqed\n\nlemma convex_sum_bound_le:\n  fixes x :: \"'a \\<Rightarrow> 'b::linordered_idom\"\n  assumes 0: \"\\<And>i. i \\<in> I \\<Longrightarrow> 0 \\<le> x i\" and 1: \"sum x I = 1\"\n      and \\<delta>: \"\\<And>i. i \\<in> I \\<Longrightarrow> \\<bar>a i - b\\<bar> \\<le> \\<delta>\"\n    shows \"\\<bar>(\\<Sum>i\\<in>I. a i * x i) - b\\<bar> \\<le> \\<delta>\"\nproof -\n  have [simp]: \"(\\<Sum>i\\<in>I. c * x i) = c\" for c\n    by (simp flip: sum_distrib_left 1)\n  then have \"\\<bar>(\\<Sum>i\\<in>I. a i * x i) - b\\<bar> = \\<bar>\\<Sum>i\\<in>I. (a i - b) * x i\\<bar>\"\n    by (simp add: sum_subtractf left_diff_distrib)\n  also have \"\\<dots> \\<le> (\\<Sum>i\\<in>I. \\<bar>(a i - b) * x i\\<bar>)\"\n    using abs_abs abs_of_nonneg by blast\n  also have \"\\<dots> \\<le> (\\<Sum>i\\<in>I. \\<bar>(a i - b)\\<bar> * x i)\"\n    by (simp add: abs_mult 0)\n  also have \"\\<dots> \\<le> (\\<Sum>i\\<in>I. \\<delta> * x i)\"\n    by (rule sum_mono) (use \\<delta> \"0\" mult_right_mono in blast)\n  also have \"\\<dots> = \\<delta>\"\n    by simp\n  finally show ?thesis .\nqed\n\nlemma card_UN_disjoint:\n  assumes \"finite I\" and \"\\<forall>i\\<in>I. finite (A i)\"\n    and \"\\<forall>i\\<in>I. \\<forall>j\\<in>I. i \\<noteq> j \\<longrightarrow> A i \\<inter> A j = {}\"\n  shows \"card (\\<Union>(A ` I)) = (\\<Sum>i\\<in>I. card(A i))\"\nproof -\n  have \"(\\<Sum>i\\<in>I. card (A i)) = (\\<Sum>i\\<in>I. \\<Sum>x\\<in>A i. 1)\"\n    by simp\n  with assms show ?thesis\n    by (simp add: card_eq_sum sum.UNION_disjoint del: sum_constant)\nqed\n\nlemma card_Union_disjoint:\n  assumes \"pairwise disjnt C\" and fin: \"\\<And>A. A \\<in> C \\<Longrightarrow> finite A\"\n  shows \"card (\\<Union>C) = sum card C\"\nproof (cases \"finite C\")\n  case True\n  then show ?thesis\n    using card_UN_disjoint [OF True, of \"\\<lambda>x. x\"] assms\n    by (simp add: disjnt_def fin pairwise_def)\nnext\n  case False\n  then show ?thesis\n    using assms card_eq_0_iff finite_UnionD by fastforce\nqed\n\nlemma card_Union_le_sum_card:\n  fixes U :: \"'a set set\"\n  assumes \"\\<forall>u \\<in> U. finite u\"\n  shows \"card (\\<Union>U) \\<le> sum card U\"\nproof (cases \"finite U\")\n  case False\n  then show \"card (\\<Union>U) \\<le> sum card U\"\n    using card_eq_0_iff finite_UnionD by auto\nnext\n  case True\n  then show \"card (\\<Union>U) \\<le> sum card U\"\n  proof (induct U rule: finite_induct)\n    case empty\n    then show ?case by auto\n  next\n    case (insert x F)\n    then have \"card(\\<Union>(insert x F)) \\<le> card(x) + card (\\<Union>F)\" using card_Un_le by auto\n    also have \"... \\<le> card(x) + sum card F\" using insert.hyps by auto\n    also have \"... = sum card (insert x F)\" using sum.insert_if and insert.hyps by auto\n    finally show ?case .\n  qed\nqed\n\nlemma card_UN_le:\n  assumes \"finite I\"\n  shows \"card(\\<Union>i\\<in>I. A i) \\<le> (\\<Sum>i\\<in>I. card(A i))\"\n  using assms\nproof induction\n  case (insert i I)\n  then show ?case\n    using card_Un_le nat_add_left_cancel_le by (force intro: order_trans) \nqed auto\n\nlemma sum_multicount_gen:\n  assumes \"finite s\" \"finite t\" \"\\<forall>j\\<in>t. (card {i\\<in>s. R i j} = k j)\"\n  shows \"sum (\\<lambda>i. (card {j\\<in>t. R i j})) s = sum k t\"\n    (is \"?l = ?r\")\nproof-\n  have \"?l = sum (\\<lambda>i. sum (\\<lambda>x.1) {j\\<in>t. R i j}) s\"\n    by auto\n  also have \"\\<dots> = ?r\"\n    unfolding sum.swap_restrict [OF assms(1-2)]\n    using assms(3) by auto\n  finally show ?thesis .\nqed\n\nlemma sum_multicount:\n  assumes \"finite S\" \"finite T\" \"\\<forall>j\\<in>T. (card {i\\<in>S. R i j} = k)\"\n  shows \"sum (\\<lambda>i. card {j\\<in>T. R i j}) S = k * card T\" (is \"?l = ?r\")\nproof-\n  have \"?l = sum (\\<lambda>i. k) T\"\n    by (rule sum_multicount_gen) (auto simp: assms)\n  also have \"\\<dots> = ?r\" by (simp add: mult.commute)\n  finally show ?thesis by auto\nqed\n\nlemma sum_card_image:\n  assumes \"finite A\"\n  assumes \"pairwise (\\<lambda>s t. disjnt (f s) (f t)) A\"\n  shows \"sum card (f ` A) = sum (\\<lambda>a. card (f a)) A\"\nusing assms\nproof (induct A)\n  case (insert a A)\n  show ?case\n  proof cases\n    assume \"f a = {}\"\n    with insert show ?case\n      by (subst sum.mono_neutral_right[where S=\"f ` A\"]) (auto simp: pairwise_insert)\n  next\n    assume \"f a \\<noteq> {}\"\n    then have \"sum card (insert (f a) (f ` A)) = card (f a) + sum card (f ` A)\"\n      using insert\n      by (subst sum.insert) (auto simp: pairwise_insert)\n    with insert show ?case by (simp add: pairwise_insert)\n  qed\nqed simp\n\n\nsubsubsection \\<open>Cardinality of products\\<close>\n\nlemma card_SigmaI [simp]:\n  \"finite A \\<Longrightarrow> \\<forall>a\\<in>A. finite (B a) \\<Longrightarrow> card (SIGMA x: A. B x) = (\\<Sum>a\\<in>A. card (B a))\"\n  by (simp add: card_eq_sum sum.Sigma del: sum_constant)\n\n(*\nlemma SigmaI_insert: \"y \\<notin> A ==>\n  (SIGMA x:(insert y A). B x) = (({y} \\<times> (B y)) \\<union> (SIGMA x: A. B x))\"\n  by auto\n*)\n\nlemma card_cartesian_product: \"card (A \\<times> B) = card A * card B\"\n  by (cases \"finite A \\<and> finite B\")\n    (auto simp add: card_eq_0_iff dest: finite_cartesian_productD1 finite_cartesian_productD2)\n\nlemma card_cartesian_product_singleton:  \"card ({x} \\<times> A) = card A\"\n  by (simp add: card_cartesian_product)\n\n\nsubsection \\<open>Generalized product over a set\\<close>\n\ncontext comm_monoid_mult\nbegin\n\nsublocale prod: comm_monoid_set times 1\n  defines prod = prod.F and prod' = prod.G ..\n\nabbreviation Prod (\"\\<Prod>_\" [1000] 999)\n  where \"\\<Prod>A \\<equiv> prod (\\<lambda>x. x) A\"\n\nend\n\nsyntax (ASCII)\n  \"_prod\" :: \"pttrn => 'a set => 'b => 'b::comm_monoid_mult\"  (\"(4PROD (_/:_)./ _)\" [0, 51, 10] 10)\nsyntax\n  \"_prod\" :: \"pttrn => 'a set => 'b => 'b::comm_monoid_mult\"  (\"(2\\<Prod>(_/\\<in>_)./ _)\" [0, 51, 10] 10)\ntranslations \\<comment> \\<open>Beware of argument permutation!\\<close>\n  \"\\<Prod>i\\<in>A. b\" == \"CONST prod (\\<lambda>i. b) A\"\n\ntext \\<open>Instead of \\<^term>\\<open>\\<Prod>x\\<in>{x. P}. e\\<close> we introduce the shorter \\<open>\\<Prod>x|P. e\\<close>.\\<close>\n\nsyntax (ASCII)\n  \"_qprod\" :: \"pttrn \\<Rightarrow> bool \\<Rightarrow> 'a \\<Rightarrow> 'a\"  (\"(4PROD _ |/ _./ _)\" [0, 0, 10] 10)\nsyntax\n  \"_qprod\" :: \"pttrn \\<Rightarrow> bool \\<Rightarrow> 'a \\<Rightarrow> 'a\"  (\"(2\\<Prod>_ | (_)./ _)\" [0, 0, 10] 10)\ntranslations\n  \"\\<Prod>x|P. t\" => \"CONST prod (\\<lambda>x. t) {x. P}\"\n\ncontext comm_monoid_mult\nbegin\n\nlemma prod_dvd_prod: \"(\\<And>a. a \\<in> A \\<Longrightarrow> f a dvd g a) \\<Longrightarrow> prod f A dvd prod g A\"\nproof (induct A rule: infinite_finite_induct)\n  case infinite\n  then show ?case by (auto intro: dvdI)\nnext\n  case empty\n  then show ?case by (auto intro: dvdI)\nnext\n  case (insert a A)\n  then have \"f a dvd g a\" and \"prod f A dvd prod g A\"\n    by simp_all\n  then obtain r s where \"g a = f a * r\" and \"prod g A = prod f A * s\"\n    by (auto elim!: dvdE)\n  then have \"g a * prod g A = f a * prod f A * (r * s)\"\n    by (simp add: ac_simps)\n  with insert.hyps show ?case\n    by (auto intro: dvdI)\nqed\n\nlemma prod_dvd_prod_subset: \"finite B \\<Longrightarrow> A \\<subseteq> B \\<Longrightarrow> prod f A dvd prod f B\"\n  by (auto simp add: prod.subset_diff ac_simps intro: dvdI)\n\nend\n\n\nsubsubsection \\<open>Properties in more restricted classes of structures\\<close>\n\ncontext linordered_nonzero_semiring\nbegin\n\nlemma prod_ge_1: \"(\\<And>x. x \\<in> A \\<Longrightarrow> 1 \\<le> f x) \\<Longrightarrow> 1 \\<le> prod f A\"\nproof (induct A rule: infinite_finite_induct)\n  case infinite\n  then show ?case by simp\nnext\n  case empty\n  then show ?case by simp\nnext\n  case (insert x F)\n  have \"1 * 1 \\<le> f x * prod f F\"\n    by (rule mult_mono') (use insert in auto)\n  with insert show ?case by simp\nqed\n\nlemma prod_le_1:\n  fixes f :: \"'b \\<Rightarrow> 'a\"\n  assumes \"\\<And>x. x \\<in> A \\<Longrightarrow> 0 \\<le> f x \\<and> f x \\<le> 1\"\n  shows \"prod f A \\<le> 1\"\n    using assms\nproof (induct A rule: infinite_finite_induct)\n  case infinite\n  then show ?case by simp\nnext\n  case empty\n  then show ?case by simp\nnext\n  case (insert x F)\n  then show ?case by (force simp: mult.commute intro: dest: mult_le_one)\nqed\n\nend\n\ncontext comm_semiring_1\nbegin\n\nlemma dvd_prod_eqI [intro]:\n  assumes \"finite A\" and \"a \\<in> A\" and \"b = f a\"\n  shows \"b dvd prod f A\"\nproof -\n  from \\<open>finite A\\<close> have \"prod f (insert a (A - {a})) = f a * prod f (A - {a})\"\n    by (intro prod.insert) auto\n  also from \\<open>a \\<in> A\\<close> have \"insert a (A - {a}) = A\"\n    by blast\n  finally have \"prod f A = f a * prod f (A - {a})\" .\n  with \\<open>b = f a\\<close> show ?thesis\n    by simp\nqed\n\nlemma dvd_prodI [intro]: \"finite A \\<Longrightarrow> a \\<in> A \\<Longrightarrow> f a dvd prod f A\"\n  by auto\n\nlemma prod_zero:\n  assumes \"finite A\" and \"\\<exists>a\\<in>A. f a = 0\"\n  shows \"prod f A = 0\"\n  using assms\nproof (induct A)\n  case empty\n  then show ?case by simp\nnext\n  case (insert a A)\n  then have \"f a = 0 \\<or> (\\<exists>a\\<in>A. f a = 0)\" by simp\n  then have \"f a * prod f A = 0\" by rule (simp_all add: insert)\n  with insert show ?case by simp\nqed\n\nlemma prod_dvd_prod_subset2:\n  assumes \"finite B\" and \"A \\<subseteq> B\" and \"\\<And>a. a \\<in> A \\<Longrightarrow> f a dvd g a\"\n  shows \"prod f A dvd prod g B\"\nproof -\n  from assms have \"prod f A dvd prod g A\"\n    by (auto intro: prod_dvd_prod)\n  moreover from assms have \"prod g A dvd prod g B\"\n    by (auto intro: prod_dvd_prod_subset)\n  ultimately show ?thesis by (rule dvd_trans)\nqed\n\nend\n\nlemma (in semidom) prod_zero_iff [simp]:\n  fixes f :: \"'b \\<Rightarrow> 'a\"\n  assumes \"finite A\"\n  shows \"prod f A = 0 \\<longleftrightarrow> (\\<exists>a\\<in>A. f a = 0)\"\n  using assms by (induct A) (auto simp: no_zero_divisors)\n\nlemma (in semidom_divide) prod_diff1:\n  assumes \"finite A\" and \"f a \\<noteq> 0\"\n  shows \"prod f (A - {a}) = (if a \\<in> A then prod f A div f a else prod f A)\"\nproof (cases \"a \\<notin> A\")\n  case True\n  then show ?thesis by simp\nnext\n  case False\n  with assms show ?thesis\n  proof induct\n    case empty\n    then show ?case by simp\n  next\n    case (insert b B)\n    then show ?case\n    proof (cases \"a = b\")\n      case True\n      with insert show ?thesis by simp\n    next\n      case False\n      with insert have \"a \\<in> B\" by simp\n      define C where \"C = B - {a}\"\n      with \\<open>finite B\\<close> \\<open>a \\<in> B\\<close> have \"B = insert a C\" \"finite C\" \"a \\<notin> C\"\n        by auto\n      with insert show ?thesis\n        by (auto simp add: insert_commute ac_simps)\n    qed\n  qed\nqed\n\nlemma sum_zero_power [simp]: \"(\\<Sum>i\\<in>A. c i * 0^i) = (if finite A \\<and> 0 \\<in> A then c 0 else 0)\"\n  for c :: \"nat \\<Rightarrow> 'a::division_ring\"\n  by (induct A rule: infinite_finite_induct) auto\n\nlemma sum_zero_power' [simp]:\n  \"(\\<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  for c :: \"nat \\<Rightarrow> 'a::field\"\n  using sum_zero_power [of \"\\<lambda>i. c i / d i\" A] by auto\n\nlemma (in field) prod_inversef: \"prod (inverse \\<circ> f) A = inverse (prod f A)\"\n proof (cases \"finite A\")\n   case True\n   then show ?thesis\n     by (induct A rule: finite_induct) simp_all\n next\n   case False\n   then show ?thesis\n     by auto\n qed\n\nlemma (in field) prod_dividef: \"(\\<Prod>x\\<in>A. f x / g x) = prod f A / prod g A\"\n  using prod_inversef [of g A] by (simp add: divide_inverse prod.distrib)\n\nlemma prod_Un:\n  fixes f :: \"'b \\<Rightarrow> 'a :: field\"\n  assumes \"finite A\" and \"finite B\"\n    and \"\\<forall>x\\<in>A \\<inter> B. f x \\<noteq> 0\"\n  shows \"prod f (A \\<union> B) = prod f A * prod f B / prod f (A \\<inter> B)\"\nproof -\n  from assms have \"prod f A * prod f B = prod f (A \\<union> B) * prod f (A \\<inter> B)\"\n    by (simp add: prod.union_inter [symmetric, of A B])\n  with assms show ?thesis\n    by simp\nqed\n\ncontext linordered_semidom\nbegin\n\nlemma prod_nonneg: \"(\\<forall>a\\<in>A. 0 \\<le> f a) \\<Longrightarrow> 0 \\<le> prod f A\"\n  by (induct A rule: infinite_finite_induct) simp_all\n\nlemma prod_pos: \"(\\<forall>a\\<in>A. 0 < f a) \\<Longrightarrow> 0 < prod f A\"\n  by (induct A rule: infinite_finite_induct) simp_all\n\nlemma prod_mono:\n  \"(\\<And>i. i \\<in> A \\<Longrightarrow> 0 \\<le> f i \\<and> f i \\<le> g i) \\<Longrightarrow> prod f A \\<le> prod g A\"\n  by (induct A rule: infinite_finite_induct) (force intro!: prod_nonneg mult_mono)+\n\nlemma prod_mono_strict:\n  assumes \"finite A\" \"\\<And>i. i \\<in> A \\<Longrightarrow> 0 \\<le> f i \\<and> f i < g i\" \"A \\<noteq> {}\"\n  shows \"prod f A < prod g A\"\n  using assms\nproof (induct A rule: finite_induct)\n  case empty\n  then show ?case by simp\nnext\n  case insert\n  then show ?case by (force intro: mult_strict_mono' prod_nonneg)\nqed\n\nend\n\nlemma prod_mono2:\n  fixes f :: \"'a \\<Rightarrow> 'b :: linordered_idom\"\n  assumes fin: \"finite B\"\n    and sub: \"A \\<subseteq> B\"\n    and nn: \"\\<And>b. b \\<in> B-A \\<Longrightarrow> 1 \\<le> f b\"\n    and A: \"\\<And>a. a \\<in> A \\<Longrightarrow> 0 \\<le> f a\"\n  shows \"prod f A \\<le> prod f B\"\nproof -\n  have \"prod f A \\<le> prod f A * prod f (B-A)\"\n    by (metis prod_ge_1 A mult_le_cancel_left1 nn not_less prod_nonneg)\n  also from fin finite_subset[OF sub fin] have \"\\<dots> = prod f (A \\<union> (B-A))\"\n    by (simp add: prod.union_disjoint del: Un_Diff_cancel)\n  also from sub have \"A \\<union> (B-A) = B\" by blast\n  finally show ?thesis .\nqed\n\nlemma less_1_prod:\n  fixes f :: \"'a \\<Rightarrow> 'b::linordered_idom\"\n  shows \"finite I \\<Longrightarrow> I \\<noteq> {} \\<Longrightarrow> (\\<And>i. i \\<in> I \\<Longrightarrow> 1 < f i) \\<Longrightarrow> 1 < prod f I\"\n  by (induct I rule: finite_ne_induct) (auto intro: less_1_mult)\n\nlemma less_1_prod2:\n  fixes f :: \"'a \\<Rightarrow> 'b::linordered_idom\"\n  assumes I: \"finite I\" \"i \\<in> I\" \"1 < f i\" \"\\<And>i. i \\<in> I \\<Longrightarrow> 1 \\<le> f i\"\n  shows \"1 < prod f I\"\nproof -\n  have \"1 < f i * prod f (I - {i})\"\n    using assms\n    by (meson DiffD1 leI less_1_mult less_le_trans mult_le_cancel_left1 prod_ge_1)\n  also have \"\\<dots> = prod f I\"\n    using assms by (simp add: prod.remove)\n  finally show ?thesis .\nqed\n\nlemma (in linordered_field) abs_prod: \"\\<bar>prod f A\\<bar> = (\\<Prod>x\\<in>A. \\<bar>f x\\<bar>)\"\n  by (induct A rule: infinite_finite_induct) (simp_all add: abs_mult)\n\nlemma prod_eq_1_iff [simp]: \"finite A \\<Longrightarrow> prod f A = 1 \\<longleftrightarrow> (\\<forall>a\\<in>A. f a = 1)\"\n  for f :: \"'a \\<Rightarrow> nat\"\n  by (induct A rule: finite_induct) simp_all\n\nlemma prod_pos_nat_iff [simp]: \"finite A \\<Longrightarrow> prod f A > 0 \\<longleftrightarrow> (\\<forall>a\\<in>A. f a > 0)\"\n  for f :: \"'a \\<Rightarrow> nat\"\n  using prod_zero_iff by (simp del: neq0_conv add: zero_less_iff_neq_zero)\n\nlemma prod_constant [simp]: \"(\\<Prod>x\\<in> A. y) = y ^ card A\"\n  for y :: \"'a::comm_monoid_mult\"\n  by (induct A rule: infinite_finite_induct) simp_all\n\nlemma prod_power_distrib: \"prod f A ^ n = prod (\\<lambda>x. (f x) ^ n) A\"\n  for f :: \"'a \\<Rightarrow> 'b::comm_semiring_1\"\n  by (induct A rule: infinite_finite_induct) (auto simp add: power_mult_distrib)\n\nlemma power_sum: \"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 prod_gen_delta:\n  fixes b :: \"'b \\<Rightarrow> 'a::comm_monoid_mult\"\n  assumes fin: \"finite S\"\n  shows \"prod (\\<lambda>k. if k = a then b k else c) S =\n    (if a \\<in> S then b a * c ^ (card S - 1) else c ^ card S)\"\nproof -\n  let ?f = \"(\\<lambda>k. if k=a then b k else c)\"\n  show ?thesis\n  proof (cases \"a \\<in> S\")\n    case False\n    then have \"\\<forall> k\\<in> S. ?f k = c\" by simp\n    with False show ?thesis by (simp add: prod_constant)\n  next\n    case True\n    let ?A = \"S - {a}\"\n    let ?B = \"{a}\"\n    from True have eq: \"S = ?A \\<union> ?B\" by blast\n    have disjoint: \"?A \\<inter> ?B = {}\" by simp\n    from fin have fin': \"finite ?A\" \"finite ?B\" by auto\n    have f_A0: \"prod ?f ?A = prod (\\<lambda>i. c) ?A\"\n      by (rule prod.cong) auto\n    from fin True have card_A: \"card ?A = card S - 1\" by auto\n    have f_A1: \"prod ?f ?A = c ^ card ?A\"\n      unfolding f_A0 by (rule prod_constant)\n    have \"prod ?f ?A * prod ?f ?B = prod ?f S\"\n      using prod.union_disjoint[OF fin' disjoint, of ?f, unfolded eq[symmetric]]\n      by simp\n    with True card_A show ?thesis\n      by (simp add: f_A1 field_simps cong add: prod.cong cong del: if_weak_cong)\n  qed\nqed\n\nlemma sum_image_le:\n  fixes g :: \"'a \\<Rightarrow> 'b::ordered_comm_monoid_add\"\n  assumes \"finite I\" \"\\<And>i. i \\<in> I \\<Longrightarrow> 0 \\<le> g(f i)\"\n    shows \"sum g (f ` I) \\<le> sum (g \\<circ> f) I\"\n  using assms\nproof induction\n  case empty\n  then show ?case by auto\nnext\n  case (insert x F)\n  from insertI1 have \"0 \\<le> g (f x)\" by (rule insert)\n  hence 1: \"sum g (f ` F) \\<le> g (f x) + sum g (f ` F)\" using add_increasing by blast\n  have 2: \"sum g (f ` F) \\<le> sum (g \\<circ> f) F\" using insert by blast\n  have \"sum g (f ` insert x F) = sum g (insert (f x) (f ` F))\" by simp\n  also have \"\\<dots> \\<le> g (f x) + sum g (f ` F)\" by (simp add: 1 insert sum.insert_if)\n  also from 2 have \"\\<dots> \\<le> g (f x) + sum (g \\<circ> f) F\" by (rule add_left_mono)\n  also from insert(1, 2) have \"\\<dots> = sum (g \\<circ> f) (insert x F)\" by (simp add: sum.insert_if)\n  finally show ?case .\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/Groups_Big.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8311430562234877, "lm_q2_score": 0.8652240947405564, "lm_q1q2_score": 0.7191249984208665}}
{"text": "(*<*) theory SV1 imports Main begin (*>*)\n\ntext {* 2001 Paper 5 Question 11 part b *}\n\nlemma \"(P\\<and>(Q\\<longrightarrow>R))\\<longrightarrow>S=(\\<not>P\\<or>\\<not>Q\\<or>S)\\<and>(\\<not>P\\<or>\\<not>R\\<or>S)\" \n  quickcheck\n  oops\n\nlemma \"((P\\<longrightarrow>Q)\\<longrightarrow>(Q\\<longrightarrow>P)) \\<longleftrightarrow> (Q\\<longrightarrow>P)\"\n  apply (rule iffI)\n   apply (rule impI)\n   apply(erule impE)\n    apply(rule impI)\n    apply assumption\n   apply(erule impE)\n    apply assumption+\n  apply (rule impI)+\n  apply(erule impE)\n   apply assumption+\n  done\n\nlemma \"(\\<forall>x y. P x\\<or> \\<not>P y) \\<longleftrightarrow> (\\<forall>x y. (P x \\<longleftrightarrow> P y))\"\n  apply (rule iffI)\n   apply(rule allI)+\n   apply(rule iffI)\n    apply(rule classical)\n    apply (erule allE)+\n    apply (erule disjE)\n     apply assumption\n    apply (erule notE)+\n    apply assumption\n   apply(rule classical)\n   apply (erule allE)+\n    apply (erule disjE)\n     apply assumption\n    apply (erule notE)+\n   apply assumption\n  apply(rule allI)+\n  apply (rule classical)\n  apply (rule disjI1)\n  apply (erule allE)+\n  apply(erule notE)\n  apply (erule iffE)\n  apply(rule classical)\n  apply(erule impE)\n   apply (erule notE)\n   apply(rule classical)\n   apply(rule disjI1)\n   apply (erule impE)\n    apply (rule classical)\n    apply(erule notE)\n  apply(rule disjI2)\n    apply assumption+\n  apply(rule disjI1)\n  apply (erule impE)\n  apply assumption+\n  done\n\n  \n\n\ntext {* 2002 Paper 5 Question 11 part a *}\n\nlemma \"\\<not>(((Q\\<longrightarrow>R)\\<longrightarrow>Q)\\<and>\\<not>Q)\"\n  apply(rule notI)\n  apply(erule conjE)\n  apply (erule impE)\n   apply (rule impI)\n  apply (erule notE)\n   apply assumption\n  apply(erule notE)\n  apply assumption\n  done\n\nlemma \"((P\\<longleftrightarrow>Q)\\<longleftrightarrow>P)\\<longleftrightarrow>Q\"\n  apply(rule iffI)\n   apply(erule iffE)\n   apply (rule classical)\n   apply (erule impE)\n    apply (rule iffI)\n     apply(erule notE)\n     apply(erule impE)\n      apply assumption\n  apply(erule iffE)\n     apply (erule impE)\n      apply assumption+\n    apply(erule notE)\n    apply assumption\n   apply(erule impE)\n    apply assumption\n  apply(erule iffE)\n   apply (erule impE)\n    apply assumption+\n  apply(rule iffI)\n  apply(erule iffE)\n   apply(erule impE)+\n     apply assumption+\n  apply(erule impE)\n    apply assumption+\n  apply(rule iffI)\n   apply assumption+\n  done\n\nlemma \"\\<exists>x y. P x y \\<longrightarrow> (\\<forall>x y. P x y)\"\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\nlemma \"(\\<forall>x. (P x \\<longrightarrow>Q x)\\<and>(\\<exists>x. P x))\\<longrightarrow>(\\<forall>x. Q x)\"\n  quickcheck\n  oops\n\nlemma \"\\<not>((\\<forall>x. (P x \\<longrightarrow>Q x)\\<and>(\\<exists>x. P x))\\<longrightarrow>(\\<forall>x. Q x))\"\n  quickcheck\n  oops\n", "meta": {"author": "hei411", "repo": "Isabelle", "sha": "9126e84b3e39af28336f25e3b7563a01f70625fa", "save_path": "github-repos/isabelle/hei411-Isabelle", "path": "github-repos/isabelle/hei411-Isabelle/Isabelle-9126e84b3e39af28336f25e3b7563a01f70625fa/Supervisionwork/SV1.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218412907381, "lm_q2_score": 0.7799929002541068, "lm_q1q2_score": 0.7190924907959692}}
{"text": "theory LexicalVals3\n  imports Lexer3 \"HOL-Library.Sublist\"\nbegin\n\nsection \\<open> Sets of Lexical Values \\<close>\n\ntext \\<open>\n  Shows that lexical values are finite for a given regex and string.\n\\<close>\n\ndefinition\n  LV :: \"'a rexp \\<Rightarrow> 'a list \\<Rightarrow> ('a 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 (Atom c) s = (if s = [c] then {Atm c} else {})\"\n  and   \"LV (Plus r1 r2) s = Left ` LV r1 s \\<union> Right ` LV r2 s\"\n  and   \"LV (NTimes r 0) s = (if s = [] then {Stars []} else {})\"\n  and   \"LV (Rec l r) s = {Recv l v | v. v \\<in> LV r s}\"\n  and   \"LV (Charset cs) s = (if length s = 1 \\<and> (hd s) \\<in> cs then {Atm (hd s)} else {})\"\nunfolding LV_def\n  apply(auto intro: Prf.intros elim: Prf.cases)\n  apply(simp add: Prf_NTimes_empty)\n  by (metis Suc_length_conv length_0_conv list.sel(1))  \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::\"'a 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::'a val, 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\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 :: \"('a val) set \\<Rightarrow> nat \\<Rightarrow> ('a 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_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 LV_NTIMES_3:\n  shows \"LV (NTimes r (Suc n)) [] = \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 finite_NTimes_empty:\n  assumes \"\\<And>s. finite (LV r s)\" \n  shows \"finite (LV (NTimes r n) [])\"\n  using assms\n  apply(induct n)\n   apply(auto simp add: LV_simps)\n  apply(subst LV_NTIMES_3)\n  apply(rule finite_imageI)\n  apply(rule finite_cartesian_product)\n  using assms apply simp \n  apply(rule finite_vimageI)\n  apply(simp)\n  apply(simp add: inj_on_def)\n  done\n\nlemma LV_From_5:\n  shows \"LV (From r n) s \\<subseteq> Stars_Append (LV (Star r) s) (\\<Union>i\\<le>n. LV (From r i) [])\"\napply(auto simp add: LV_def)\napply(auto elim!: Prf_elims)\napply(auto simp add: Stars_Append_def)\napply(rule_tac x=\"vs1\" in exI)\napply(rule_tac x=\"vs2\" in exI)  \napply(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_3:\n  shows \"LV (From r (Suc n)) [] = \n    (\\<lambda>(v,vs). Stars (v#vs)) ` (LV r [] \\<times> (Stars -` (LV (From 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_From_empty:\n \"LV (From 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 finite_From_empty:\n  assumes \"\\<forall>s. finite (LV r s)\"\n  shows \"finite (LV (From r n) s)\"\n  apply(rule finite_subset)\n   apply(rule LV_From_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 LV_From_empty)\n    \n\nlemma subseteq_Upto_Star:\n  shows \"LV (Upto r n) s \\<subseteq> LV (Star r) s\"\n  apply(auto simp add: LV_def)\n  by (metis Prf.intros(6) Prf_elims(8))\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 (Atom c s)\n  show \"finite (LV (Atom c) s)\" by (simp add: LV_simps)\nnext \n  case (Plus r1 r2 s)\n  then show \"finite (LV (Plus r1 r2) s)\" by (simp add: LV_simps)\nnext \n  case (Times r1 r2 s)\n  define f where \"f \\<equiv> \\<lambda>(v1::'a val, 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 (Times 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 (Times 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 (NTimes r n s)\n  have \"\\<And>s. finite (LV r s)\" by fact\n  then have \"finite (Stars_Append (LV (Star r) s) (\\<Union>i\\<le>n. LV (NTimes r i) []))\" \n    apply(rule_tac finite_Stars_Append)\n     apply (simp add: LV_STAR_finite)\n    using finite_NTimes_empty by blast\n  then show \"finite (LV (NTimes r n) s)\"\n    by (metis LV_NTimes_5 finite_subset)\nnext\n  case (Upto r n s)\n  then have \"finite (LV (Star r) s)\" by (simp add: LV_STAR_finite)\n  moreover\n  have \"LV (Upto r n) s \\<subseteq> LV (Star r) s\"\n    by (meson subseteq_Upto_Star) \n  ultimately show \"finite (LV (Upto r n) s)\"\n    using rev_finite_subset by blast \nnext \n  case (From r n)\n  then show \"finite (LV (From r n) s)\"\n    by (simp add: finite_From_empty)\nnext \n  case (Rec l r)\n  have \"\\<And>s. finite (LV r s)\" by fact\n  then show \"finite (LV (Rec l r) s)\"\n    by(simp add: LV_simps)\nnext\n  case (Charset cs s)\n  show \"finite (LV (Charset cs) s)\" by (simp add: LV_simps)\nqed\n\n\n\ntext \\<open>\n  Our POSIX values are lexical values.\n\\<close>\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  using Prf.intros(4) flat.simps(1) apply blast\n  apply (simp add: Prf.intros(5))\n  apply (simp add: Prf.intros(2))\n  apply (simp add: Prf.intros(3))\n  apply (simp add: Prf.intros(1))\n  apply (smt (verit, best) CollectI Posix1(2) Posix1a Posix_Star1)\n  apply (simp add: Prf.intros(6))\n  apply (smt (verit, best) Posix1(2) Posix1a Posix_NTimes1 mem_Collect_eq)\n  using Posix1a Posix_NTimes2 apply fastforce\n  apply (smt (verit, ccfv_threshold) Posix1(2) Posix1a Posix_Upto1 mem_Collect_eq)\n  using Posix1a Posix_Upto2 apply fastforce\n  using Posix1a Posix_From2 apply fastforce\n  apply (smt (verit, best) Posix1(2) Posix1a Posix_From1 mem_Collect_eq)\n  apply (smt (verit, best) Posix1a Posix_From3 flat.simps(7) mem_Collect_eq)\n  apply(simp add: Prf.intros(11))\n  by (simp add: Prf.intros(12))\n  \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 blast\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/Posix-Lexing/Extensions/LexicalVals3.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8872045966995027, "lm_q2_score": 0.8104789155369047, "lm_q1q2_score": 0.7190606193923698}}
{"text": "theory Algebra\n  imports \"$AFP/Kleene_Algebra/Kleene_Algebra\" Omega_Algebra\nbegin\n\nnotation inf (infixl \"\\<sqinter>\" 70)\n\nclass par_dioid = join_semilattice_zero + one +\n  fixes par :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a\" (infixl \"\\<parallel>\" 69)\n  assumes par_assoc [simp]: \"x \\<parallel> (y \\<parallel> z) = (x \\<parallel> y) \\<parallel> z\"\n  and par_comm: \"x \\<parallel> y = y \\<parallel> x\"\n  and par_distl [simp]: \"x \\<parallel> (y + z) = x \\<parallel> y + x \\<parallel> z\"\n  and par_unitl [simp]: \"1 \\<parallel> x = x\"\n  and par_annil [simp]: \"0 \\<parallel> x = 0\"\n\nbegin\n\n  lemma par_distr [simp]: \"(x+y) \\<parallel> z = x \\<parallel> z + y \\<parallel> z\" \n    by (metis par_comm par_distl)\n\n  lemma par_isol [intro]: \"x \\<le> y \\<Longrightarrow> x \\<parallel> z \\<le> y \\<parallel> z\"\n    by (metis order_prop par_distr)\n \n  lemma par_isor [intro]: \"x \\<le> y \\<Longrightarrow> z \\<parallel> x \\<le> z \\<parallel> y\"\n    by (metis par_comm par_isol)\n\n  lemma par_unitr [simp]: \"x \\<parallel> 1 = x\"\n    by (metis par_comm par_unitl)\n\n  lemma par_annir [simp]: \"x \\<parallel> 0 = 0\"\n    by (metis par_annil par_comm)\n\n  lemma par_subdistl: \"x \\<parallel> z \\<le> (x + y) \\<parallel> z\"\n    by (metis order_prop par_distr)\n\n  lemma par_subdistr: \"z \\<parallel> x \\<le> z \\<parallel> (x + y)\"\n    by (metis par_comm par_subdistl)\n\n  lemma par_double_iso [intro]: \"w \\<le> x \\<Longrightarrow> y \\<le> z \\<Longrightarrow> w \\<parallel> y \\<le> x \\<parallel> z\"\n    by (metis order_trans par_isol par_isor)\n\nend\n\nclass weak_trioid = par_dioid + dioid_one_zerol\n\nclass trioid = par_dioid + dioid_one_zero\n\nclass weak_star_trioid = weak_trioid + left_kleene_algebra_zerol\n\nbegin\n\nend\n\nclass weak_omega_trioid = weak_trioid + left_omega_algebra_zerol\n\nclass rely_guarantee_trioid = weak_star_trioid + semilattice_inf +\n  fixes RG :: \"'a set\"\n  and C :: \"'a\"\n  assumes rg1: \"r \\<in> RG \\<Longrightarrow> r \\<parallel> r \\<le> r\"\n  and rg2: \"r \\<in> RG \\<Longrightarrow> s \\<in> RG \\<Longrightarrow> r \\<le> r \\<parallel> s\"\n  and rg3: \"r \\<in> RG \\<Longrightarrow> r\\<parallel>(x\\<cdot>y) = (r\\<parallel>x)\\<cdot>(r\\<parallel>y)\"\n  and rg4: \"r \\<in> RG \\<Longrightarrow> r\\<parallel>(x\\<^sup>\\<star>\\<cdot>x) \\<le> (r\\<parallel>x)\\<^sup>\\<star>\\<cdot>(r\\<parallel>x)\"\n  and rg5: \"r \\<in> RG \\<Longrightarrow> r\\<parallel>(x\\<^sup>\\<star>\\<cdot>x) \\<le> (r\\<parallel>x)\\<cdot>(r\\<parallel>x)\\<^sup>\\<star>\"\n  and rg_unit: \"1 \\<in> RG\"\n  and rg_meet_closed: \"\\<lbrakk>r \\<in> RG; s \\<in> RG\\<rbrakk> \\<Longrightarrow> (r \\<sqinter> s) \\<in> RG\"\n  and rg_par_closed: \"\\<lbrakk>r \\<in> RG; s \\<in> RG\\<rbrakk> \\<Longrightarrow> (r \\<parallel> s) \\<in> RG\"\n\n  and Con_mult: \"x\\<cdot>y \\<sqinter> C \\<le> (x \\<sqinter> C)\\<cdot>(y \\<sqinter> C) \\<sqinter> C\"\n  and Con_star: \"x\\<^sup>\\<star> \\<sqinter> C \\<le> (x \\<sqinter> C)\\<^sup>\\<star> \\<sqinter> C\"\n  and Con_star_inductl: \"(z + y \\<cdot> x) \\<sqinter> C \\<le> y \\<sqinter> C \\<Longrightarrow> (z \\<cdot> x\\<^sup>\\<star>) \\<sqinter> C \\<le> y \\<sqinter> C\"\n\n\n  and plus_meet_distrib: \"x + y \\<sqinter> z = (x + y) \\<sqinter> (x + z)\"\n\nbegin\n\n  declare mult_onel [simp]\n    and mult_oner [simp]\n    and par_unitl [simp]\n    and par_unitr [simp]\n\n  definition proj :: \"'a \\<Rightarrow> 'a\" (\"\\<pi>\") where\n    \"\\<pi> x = x \\<sqinter> C\"\n\n  lemma proj_mult [simp]: \"\\<pi> (\\<pi> x \\<cdot> \\<pi> y) = \\<pi> (x\\<cdot>y)\"\n    by (auto intro!: antisym Con_mult simp add: proj_def) (metis inf_commute inf_le2 le_infI2 mult_isol_var)\n\n  lemma proj_mult2 [simp]: \"\\<pi> (\\<pi> x \\<cdot> y) = \\<pi> (x\\<cdot>y)\"\n    by (metis inf_commute inf_left_idem proj_def proj_mult)\n\n  lemma proj_mult3 [simp]: \"\\<pi> (x \\<cdot> \\<pi> y) = \\<pi> (x\\<cdot>y)\"\n    by (metis proj_mult proj_mult2)\n\n  lemma proj_coextensive [intro!]: \"\\<pi> x \\<le> x\"\n    by (metis inf_le1 proj_def)\n\n  lemma proj_iso [intro]: \"x \\<le> y \\<Longrightarrow> \\<pi> x \\<le> \\<pi> y\"\n    by (metis inf_mono order_refl proj_def)\n\n  lemma proj_idem [simp]: \"\\<pi> (\\<pi> x) = \\<pi> x\"\n    by (metis inf_commute inf_left_idem proj_def)\n\n  sublocale distrib_lattice \"op \\<sqinter>\" \"op \\<le>\" \"op <\" \"op +\"\n  proof\n    fix x y z\n    show \"x \\<le> x + y\"\n      by (metis add_ub1)\n    show \"y \\<le> x + y\"\n      by (metis add_ub2)\n    show \"x + y \\<sqinter> z = (x + y) \\<sqinter> (x + z)\"\n      by (metis plus_meet_distrib)\n    assume \"y \\<le> x\" and \"z \\<le> x\"\n    thus \"y + z \\<le> x\"\n      by (metis add_lub)\n  qed\n\n  lemma \"(x \\<sqinter> C) \\<le> (y \\<sqinter> C) \\<longleftrightarrow> ((x + y) \\<sqinter> C) = (y \\<sqinter> C)\"\n    apply default\n    defer\n    apply (metis eq_refl inf_mono sup_ge1)\n    by (metis inf_commute inf_sup_distrib1 sup_absorb2)\n\n  lemma proj_plus [simp]: \"\\<pi> (x + y) = \\<pi> x + \\<pi> y\"\n    by (simp add: proj_def) (metis inf_commute inf_sup_distrib1)\n\n  lemma proj_meet [simp]: \"\\<pi> (x \\<sqinter> y) = \\<pi> x \\<sqinter> \\<pi> y\"\n    by (metis inf_commute inf_left_commute inf_left_idem proj_def)\n\n  definition pmult :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a\" (infixl \"\\<otimes>\" 70) where\n    \"x \\<otimes> y = \\<pi> (x \\<cdot> y)\"\n\n  \n\n  lemma pmult_onel [simp]: \"1 \\<otimes> x = \\<pi> x\"\n    by (metis mult_onel pmult_def)\n\n  lemma pmult_oner [simp]: \"x \\<otimes> 1 = \\<pi> x\"\n    by (metis mult_oner pmult_def)\n\n  lemma proj_zero [simp]: \"\\<pi> 0 = 0\"\n    by (metis add_zerol inf_sup_absorb proj_def)\n\n  lemma pmult_zero: \"0 \\<otimes> x = 0\"\n    by (simp add: pmult_def)\n\n  abbreviation proj_eq :: \"'a \\<Rightarrow> 'a \\<Rightarrow> bool\" (infixl \"=\\<^sub>\\<pi>\" 55) where\n    \"x =\\<^sub>\\<pi> y \\<equiv> (\\<pi> x = \\<pi> y)\"\n\n  definition proj_leq :: \"'a \\<Rightarrow> 'a \\<Rightarrow> bool\" (infixl \"\\<le>\\<^sub>\\<pi>\" 55) where\n    \"x \\<le>\\<^sub>\\<pi> y \\<equiv> (\\<pi> x \\<le> \\<pi> y)\"\n\n  lemma proj_leq_trans [trans]: \"x \\<le>\\<^sub>\\<pi> y \\<Longrightarrow> y \\<le>\\<^sub>\\<pi> z \\<Longrightarrow> x \\<le>\\<^sub>\\<pi> z\"\n    by (auto simp add: proj_leq_def)\n\n  lemma proj_leq_trans2 [trans]: \"x \\<le> y \\<Longrightarrow> y \\<le>\\<^sub>\\<pi> z \\<Longrightarrow> x \\<le>\\<^sub>\\<pi> z\"\n    by (auto simp add: proj_leq_def) (metis dual_order.trans proj_iso)\n\n  lemma proj_leq_trans3 [trans]: \"x \\<le>\\<^sub>\\<pi> y \\<Longrightarrow> y \\<le> z \\<Longrightarrow> x \\<le>\\<^sub>\\<pi> z\"\n    by (metis proj_iso proj_leq_def proj_leq_trans)\n\n  lemma proj_leq_iso: \"x \\<le> y \\<Longrightarrow> x \\<le>\\<^sub>\\<pi> y\"\n    by (metis proj_iso proj_leq_def)\n\n  sublocale proj!: dioid \"op +\" \"op \\<otimes>\" \"op \\<le>\" \"op <\"\n  proof\n    fix x y z\n    show \"(x \\<otimes> y) \\<otimes> z = x \\<otimes> (y \\<otimes> z)\"\n      by (simp add: pmult_def mult_assoc)\n    show \"(x + y) \\<otimes> z = x \\<otimes> z + y \\<otimes> z\"\n      by (simp add: pmult_def distrib_right)\n    show \"x \\<otimes> (y + z) = x \\<otimes> y + x \\<otimes> z\"\n      by (metis distrib_left inf_commute inf_sup_distrib1 pmult_def proj_def)\n    show \"x + x = x\"\n      by (metis sup_idem)\n  qed\n\n  definition quintuple :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> bool\" (\"_,// _// \\<turnstile> \\<lbrace>_\\<rbrace> _ \\<lbrace>_\\<rbrace>\" [20,20,20,20,20] 1000) where\n    \"r, g \\<turnstile> \\<lbrace>p\\<rbrace> c \\<lbrace>q\\<rbrace> \\<equiv> p\\<cdot>(r\\<parallel>c) \\<le>\\<^sub>\\<pi> q \\<and> c \\<le> g \\<and> r \\<in> RG \\<and> g \\<in> RG\"\n\n  lemma rg_idem_mult [simp]: \"r \\<in> RG \\<Longrightarrow> r\\<cdot>r = r\"\n    using rg3[where x = 1 and y = 1 and r = r, simplified] ..\n\n  lemma rg_idem_par : \"r \\<in> RG \\<Longrightarrow> r \\<parallel> r = r\"\n    by (metis eq_iff rg1 rg2)\n\n  lemma [simp]: \"x \\<le> \\<pi> (y \\<sqinter> z) \\<longleftrightarrow> x \\<le> \\<pi> y \\<and> x \\<le> \\<pi> z\"\n    by (metis le_infE le_infI proj_def)\n\n  lemma meet_iso [intro]: \"x \\<le> z \\<Longrightarrow> y \\<le> w \\<Longrightarrow> x \\<sqinter> y \\<le> z \\<sqinter> w\"\n    by (metis le_infI1 le_infI2 le_inf_iff)\n\n  lemma proj_seq_leq: \"\\<pi> w \\<cdot> \\<pi> x \\<le> \\<pi> y \\<cdot> \\<pi> z \\<Longrightarrow> \\<pi> (w \\<cdot> x) \\<le> \\<pi> (y \\<cdot> z)\"\n    by (subst proj_mult[symmetric], subst proj_mult[symmetric], rule proj_iso, assumption)\n\n  lemma proj_mult_iso: \"w \\<le>\\<^sub>\\<pi> y \\<Longrightarrow> x \\<le>\\<^sub>\\<pi> z \\<Longrightarrow> w \\<cdot> x \\<le>\\<^sub>\\<pi> y \\<cdot> z\"\n    apply (simp add: proj_leq_def)\n    apply (rule proj_seq_leq)\n    apply (rule mult_isol_var[rule_format])\n    by auto\n\n  theorem sequential:\n    assumes \"r, g \\<turnstile> \\<lbrace>p\\<rbrace> c1 \\<lbrace>q\\<rbrace>\" and \"r, g \\<turnstile> \\<lbrace>q\\<rbrace> c2 \\<lbrace>s\\<rbrace>\"\n    shows \"r, g \\<turnstile> \\<lbrace>p\\<rbrace> c1 \\<cdot> c2 \\<lbrace>s\\<rbrace>\"\n  proof (simp add: quintuple_def, intro conjI)\n    show \"r \\<in> RG\" and \"g \\<in> RG\"\n      by (metis assms(1) quintuple_def)+\n\n    hence \"p \\<cdot> (r \\<parallel> c1 \\<cdot> c2) \\<le> p \\<cdot> ((r \\<parallel> c1) \\<cdot> (r \\<parallel> c2))\"\n      by (metis order_refl rg3 mult_isol)\n    also have \"... \\<le> p \\<cdot> (r \\<parallel> c1) \\<cdot> (r \\<parallel> c2)\"\n      by (metis mult_assoc order_refl)\n    also have \"... \\<le>\\<^sub>\\<pi> q \\<cdot> (r \\<parallel> c2)\"\n      by (subst proj_leq_def, intro proj_seq_leq mult_isor[rule_format]) (metis assms(1) proj_leq_def quintuple_def)\n    also have \"... \\<le>\\<^sub>\\<pi> s\"\n      by (metis assms(2) quintuple_def)\n    finally show \"p \\<cdot> (r \\<parallel> c1 \\<cdot> c2) \\<le>\\<^sub>\\<pi> s\" .\n\n    have \"c1 \\<cdot> c2 \\<le> g \\<cdot> g\" using assms(1) and assms(2)\n      by (auto intro!: mult_isol_var[rule_format] simp add: quintuple_def simp del: rg_idem_mult)\n    also have \"... = g\"\n      by (metis `g \\<in> RG` rg_idem_mult)\n    finally show \"c1 \\<cdot> c2 \\<le> g\" .\n  qed\n\n  lemma [simp]: \"x \\<le>\\<^sub>\\<pi> y \\<sqinter> z \\<longleftrightarrow> x \\<le>\\<^sub>\\<pi> y \\<and> x \\<le>\\<^sub>\\<pi> z\"\n    by (simp add: proj_leq_def)\n\n  lemma proj_star: \"\\<pi> ((\\<pi> x)\\<^sup>\\<star>) = \\<pi> (x\\<^sup>\\<star>)\"\n    apply (rule antisym)\n    apply (metis inf_commute inf_le2 meet_iso order_refl proj_def star_iso)\n    by (metis Con_star proj_def)\n\n  lemma proj_star_inductl_nc: \"\\<pi> z + \\<pi> x \\<cdot> \\<pi> y \\<le> \\<pi> y \\<Longrightarrow> x\\<^sup>\\<star>\\<cdot>z \\<le>\\<^sub>\\<pi> y\"\n    apply (auto simp add: proj_leq_def)\n    apply (subst proj_mult[symmetric])\n    apply (subst proj_star[symmetric])\n    apply (subst proj_idem[symmetric]) back back back\n    apply (subst proj_mult)\n    apply (subst proj_idem[symmetric]) back back back\n    apply (rule proj_iso)\n    apply (rule star_inductl[rule_format])\n    by auto\n\n  theorem parallel:\n    assumes \"r1, g1 \\<turnstile> \\<lbrace>p1\\<rbrace> c1 \\<lbrace>q1\\<rbrace>\" and \"g2 \\<le> r1\"\n    and \"r2, g2 \\<turnstile> \\<lbrace>p2\\<rbrace> c2 \\<lbrace>q2\\<rbrace>\" and \"g1 \\<le> r2\"\n    shows \"(r1 \\<sqinter> r2), (g1 \\<parallel> g2) \\<turnstile> \\<lbrace>p1 \\<sqinter> p2\\<rbrace> c1 \\<parallel> c2 \\<lbrace>q1 \\<sqinter> q2\\<rbrace>\"\n  proof (simp add: quintuple_def, intro conjI)\n    have \"r1 \\<in> RG\" and \"r2 \\<in> RG\" and \"g1 \\<in> RG\" and \"g2 \\<in> RG\"\n      by (metis assms(1) assms(3) quintuple_def)+\n\n    have \"(p1 \\<sqinter> p2) \\<cdot> (r1 \\<sqinter> r2 \\<parallel> c1 \\<parallel> c2) \\<le> p1 \\<cdot> (r1 \\<sqinter> r2 \\<parallel> c1 \\<parallel> c2)\"\n      by (metis inf_le1 mult_isor)\n    also have \"... \\<le> p1 \\<cdot> (r1 \\<sqinter> r2 \\<parallel> c1 \\<parallel> g2)\"\n      by (intro mult_isol_var[rule_format] par_double_iso[rule_format] conjI order_refl) (metis assms(3) quintuple_def)\n    also have \"... \\<le> p1 \\<cdot> (r1 \\<parallel> (c1 \\<parallel> r1))\"\n      by (intro mult_isol_var[rule_format] conjI order_refl) (metis assms(2) inf_le1 par_comm par_double_iso par_isol)\n    also have \"... \\<le> p1 \\<cdot> (r1 \\<parallel> c1)\"\n      by (intro  mult_isol[rule_format]) (metis `r1 \\<in> RG` eq_iff par_assoc par_comm rg_idem_par)\n    also have \"... \\<le>\\<^sub>\\<pi> q1\"\n      by (metis assms(1) quintuple_def)\n    finally show \"(p1 \\<sqinter> p2) \\<cdot> (r1 \\<sqinter> r2 \\<parallel> c1 \\<parallel> c2) \\<le>\\<^sub>\\<pi> q1\" .\n\n    have \"(p1 \\<sqinter> p2) \\<cdot> (r1 \\<sqinter> r2 \\<parallel> c1 \\<parallel> c2) \\<le> p2 \\<cdot> (r1 \\<sqinter> r2 \\<parallel> c1 \\<parallel> c2)\"\n     by (metis inf_le2 mult_isor)\n    also have \"... \\<le> p2 \\<cdot> (r1 \\<sqinter> r2 \\<parallel> g1 \\<parallel> c2)\"\n      by (intro mult_isol_var[rule_format] conjI order_refl par_double_iso[rule_format]) (metis assms(1) quintuple_def)\n    also have \"... \\<le> p2 \\<cdot> (r2 \\<parallel> r2 \\<parallel> c2)\"\n      by (intro mult_isol_var[rule_format] conjI order_refl) (metis assms(4) inf_le2 par_comm par_double_iso par_isor)\n    also have \"... \\<le> p2 \\<cdot> (r2 \\<parallel> c2)\"\n      by (intro mult_isol[rule_format]) (metis `r2 \\<in> RG` eq_refl rg_idem_par)\n    also have \"... \\<le>\\<^sub>\\<pi> q2\"\n      by (metis assms(3) quintuple_def)\n    finally show \"(p1 \\<sqinter> p2) \\<cdot> (r1 \\<sqinter> r2 \\<parallel> c1 \\<parallel> c2) \\<le>\\<^sub>\\<pi> q2\" .\n\n    show \"c1 \\<parallel> c2 \\<le> g1 \\<parallel> g2\" using assms(1) and assms(3)\n      by (auto simp: quintuple_def)\n\n    show \"r1 \\<sqinter> r2 \\<in> RG\"\n      by (metis `r1 \\<in> RG` `r2 \\<in> RG` rg_meet_closed)\n    show \"g1 \\<parallel> g2 \\<in> RG\"\n      by (metis `g1 \\<in> RG` `g2 \\<in> RG` rg_par_closed)\n  qed\n\n  lemma proj_add_lub [simp]: \"x + y \\<le>\\<^sub>\\<pi> z \\<longleftrightarrow> x \\<le>\\<^sub>\\<pi> z \\<and> y \\<le>\\<^sub>\\<pi> z\"\n    by (auto simp add: proj_leq_def)\n\n  lemma helper: \"r\\<parallel>x\\<^sup>\\<star> = r + r\\<parallel>x\\<cdot>x\\<^sup>\\<star>\"\n    by (metis par_distl par_unitr star_unfoldl_eq)\n\n  lemma proj_star_inductl: \"\\<pi> (z + y \\<cdot> x) \\<le> \\<pi> y \\<Longrightarrow> \\<pi> (z \\<cdot> x\\<^sup>\\<star>) \\<le> \\<pi> y\"\n    by (metis Con_star_inductl dual_order.trans eq_refl inf_commute proj_def)\n\n  lemma star_rule: \"p\\<cdot>r \\<le>\\<^sub>\\<pi> p \\<Longrightarrow> r, g \\<turnstile> \\<lbrace>p\\<rbrace> c \\<lbrace>p\\<rbrace> \\<Longrightarrow> r, g \\<turnstile> \\<lbrace>p\\<rbrace> c\\<^sup>\\<star> \\<lbrace>p\\<rbrace>\"\n    apply (auto simp add: quintuple_def proj_leq_def)\n    defer\n    apply (metis boffa par_unitl rg2 rg_idem_mult rg_unit star_rtc_least_eq sup_absorb1 sup_commute sup_id_star2 sup_left_commute)\n    apply (subst helper)\n    apply (simp add: distrib_left)\n    apply (rule order_trans[of _ \"\\<pi> (p \\<cdot> (r \\<parallel> c) \\<cdot> (r \\<parallel> c)\\<^sup>\\<star>)\"])\n    apply (metis mult_assoc pmult_def proj.mult_isol rg5 star_slide_var)\n    apply (rule order_trans[of _ \"\\<pi> (p \\<cdot> (r \\<parallel> c)\\<^sup>\\<star>)\"])\n    apply (metis mult_assoc pmult_def proj.mult_isol star_1l)\n    apply (rule proj_star_inductl)\n    by (metis eq_iff inf_commute inf_sup_distrib1 proj_def sup_absorb2 sup_commute)\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/Algebra.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045877523147, "lm_q2_score": 0.8104789086703225, "lm_q1q2_score": 0.7190606060487994}}
{"text": "theory Pred_Zorn\n  imports HOL.Zorn\n\nbegin\n\n(* ========== *)\nlemma partial_order_onE:\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(* ========== *)\n\nabbreviation rel_of :: \"('a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> 'a set \\<Rightarrow> ('a \\<times> 'a) set\"\n  where \"rel_of P A \\<equiv> { (a, b) \\<in> A \\<times> A. P a b }\"\n\nlemma Field_rel_of:\n  assumes \"refl_on A (rel_of P A)\" shows \"Field (rel_of P A) = A\"\n  using assms unfolding refl_on_def Field_def by auto\n\n(* ========== *)\nlemma Chains_rel_of:\n  assumes \"C \\<in> Chains (rel_of P A)\" shows \"C \\<subseteq> A\"\n  using assms unfolding Chains_def by auto\n(* ========== *)\n\nlemma partial_order_on_rel_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 (rel_of P A)\"\nproof -\n  from refl have \"refl_on A (rel_of P A)\"\n    unfolding refl_on_def by auto\n  moreover have \"trans (rel_of P A)\" and \"antisym (rel_of P A)\"\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_rel_ofI:\n  assumes \"partial_order_on A (rel_of P A)\" shows \"Partial_order (rel_of P A)\"\n  using assms unfolding Field_rel_of[OF partial_order_onE(1)[OF assms]] .\n\nlemma predicate_Zorn:\n  assumes \"partial_order_on A (rel_of P A)\"\n    and \"\\<forall>C \\<in> Chains (rel_of P A). \\<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 \"a \\<in> C\" and \"C \\<in> Chains (rel_of P A)\" for C a\n    using that Chains_rel_of by auto\n  moreover have \"(a, u) \\<in> rel_of P A\" if \"a \\<in> A\" and \"u \\<in> A\" and \"P a u\" for a u\n    using that by auto\n  ultimately show ?thesis\n    using Zorns_po_lemma[OF Partial_order_rel_ofI[OF assms(1)]] assms(2)\n    unfolding Field_rel_of[OF partial_order_onE(1)[OF assms(1)]] by auto\nqed\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/Pred_Zorn.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677583778258, "lm_q2_score": 0.8479677660619634, "lm_q1q2_score": 0.7190493257642158}}
{"text": "section \\<open>Prefix Tree\\<close>\n\ntext \\<open>This theory introduces a tree to efficiently store prefix-complete sets of lists.\n      Several functions to lookup or merge subtrees are provided.\\<close>\n\n\ntheory Prefix_Tree\nimports Util \"HOL-Library.Mapping\" \"HOL-Library.List_Lexorder\" \nbegin\n\ndatatype 'a prefix_tree = PT \"'a \\<rightharpoonup> 'a prefix_tree\"\n\ndefinition empty :: \"'a prefix_tree\" where\n  \"empty = PT Map.empty\"\n\nfun isin :: \"'a prefix_tree \\<Rightarrow> 'a list \\<Rightarrow> bool\" where\n  \"isin t [] = True\" |\n  \"isin (PT m) (x # xs) = (case m x of None \\<Rightarrow> False | Some t \\<Rightarrow> isin t xs)\"\n\nlemma isin_prefix :\n  assumes \"isin t (xs@xs')\"\n  shows \"isin t xs\"\nproof -\n  obtain m where \"t = PT m\"\n    by (metis prefix_tree.exhaust)\n\n  show ?thesis using assms unfolding \\<open>t = PT m\\<close>\n  proof (induction xs arbitrary: m)\n    case Nil\n    then show ?case by auto\n  next\n    case (Cons x xs)\n    then have \"isin (PT m) (x # (xs @ xs'))\"\n      by auto\n    then obtain m' where \"m x = Some (PT m')\"\n                     and \"isin (PT m') (xs@xs')\"\n      unfolding isin.simps\n      by (metis option.exhaust option.simps(4) option.simps(5) prefix_tree.exhaust) \n    then show ?case \n      using Cons.IH[of m'] by auto\n  qed\nqed\n\n\nfun set :: \"'a prefix_tree \\<Rightarrow> 'a list set\" where\n  \"set t = {xs . isin t xs}\"\n\nlemma set_empty : \"set empty = ({[]} :: 'a list set)\"\nproof \n  show \"set empty \\<subseteq> ({[]} :: 'a list set)\"\n  proof \n    fix xs :: \"'a list\"\n    assume \"xs \\<in> set empty\"\n    then have \"isin empty xs\"\n      by auto\n    \n    have \"xs = []\"\n    proof (rule ccontr)\n      assume \"xs \\<noteq> []\"\n      then obtain x xs' where \"xs = x#xs'\"\n        using list.exhaust by auto \n      then have \"Map.empty x \\<noteq> None\"\n        using \\<open>isin empty xs\\<close> unfolding empty_def\n        by simp \n      then show \"False\"\n        by auto\n    qed\n    then show \"xs \\<in> {[]}\" \n      by blast \n  qed\n  show \"({[]} :: 'a list set) \\<subseteq> set empty\"\n    unfolding set.simps empty_def\n    by simp \nqed\n\nlemma set_Nil : \"[] \\<in> set t\" \n  by auto\n\n\nfun insert :: \"'a prefix_tree \\<Rightarrow> 'a list \\<Rightarrow> 'a prefix_tree\" where\n  \"insert t [] = t\" |\n  \"insert (PT m) (x#xs) = PT (m(x \\<mapsto> insert (case m x of None \\<Rightarrow> empty | Some t' \\<Rightarrow> t') xs))\"\n\n\nlemma insert_isin_prefix : \"isin (insert t (xs@xs')) xs\"\nproof (induction xs arbitrary: t)\n  case Nil\n  then show ?case by auto\nnext\n  case (Cons x xs)\n  moreover obtain m where \"t = PT m\"\n    using prefix_tree.exhaust by auto \n  ultimately obtain t' where \"(m(x \\<mapsto> insert (case m x of None \\<Rightarrow> empty | Some t' \\<Rightarrow> t') xs)) x = Some t'\"\n    by simp\n  then have \"isin (insert t ((x#xs)@xs')) (x#xs) = isin (insert (case m x of None \\<Rightarrow> empty | Some t' \\<Rightarrow> t') (xs@xs')) xs\"\n    unfolding \\<open>t = PT m\\<close>\n    by simp \n  then show ?case \n    using Cons.IH by auto\nqed\n\n  \n\nlemma insert_isin_other : \n  assumes \"isin t xs\"\nshows \"isin (insert t xs') xs\"\nproof (cases \"xs = xs'\")\n  case True\n  then show ?thesis using insert_isin_prefix[of t xs \"[]\"] by simp\nnext\n  case False\n  \n  have *: \"\\<And> i xs xs' . take i xs = take i xs' \\<Longrightarrow> take (Suc i) xs \\<noteq> take (Suc i) xs' \\<Longrightarrow> isin t xs \\<Longrightarrow> isin (insert t xs') xs\"\n  proof -\n    fix i xs xs' assume \"take i xs = take i xs'\"\n                    and \"take (Suc i) xs \\<noteq> take (Suc i) xs'\"\n                    and \"isin t xs\"\n    then show \"isin (insert t xs') xs\"\n    proof (induction i arbitrary: xs xs' t)\n      case 0\n      then consider (a) \"xs = [] \\<and> xs' \\<noteq> []\" |\n                    (b) \"xs' = [] \\<and> xs \\<noteq> []\" |\n                    (c) \"xs \\<noteq> [] \\<and> xs' \\<noteq> [] \\<and> hd xs \\<noteq> hd xs'\"\n        by (metis take_Suc take_eq_Nil)\n      then show ?case proof cases\n        case a\n        then show ?thesis by auto \n      next\n        case b\n        then show ?thesis\n          by (simp add: \"0.prems\"(3)) \n      next\n        case c\n        then obtain b bs c cs where \"xs = b#bs\" and \"xs' = c#cs\" and \"b \\<noteq> c\"\n          using list.exhaust_sel by blast\n        obtain m where \"t = PT m\"\n          using prefix_tree.exhaust by auto \n        have \"isin (Prefix_Tree.insert t xs') xs = isin t xs\" \n          unfolding \\<open>t = PT m\\<close> \\<open>xs = b#bs\\<close> \\<open>xs' = c#cs\\<close> insert.simps isin.simps using \\<open>b \\<noteq> c\\<close>\n          by simp \n        then show ?thesis \n          using \\<open>isin t xs\\<close> by simp\n      qed\n    next\n      case (Suc i) \n\n      define hxs where hxs: \"hxs = hd xs\"\n      define txs where txs: \"txs = tl xs\"\n      define txs' where txs': \"txs' = tl xs'\"\n\n      have \"xs = hxs#txs\"\n        unfolding hxs txs\n        using \\<open>take (Suc i) xs = take (Suc i) xs'\\<close> \\<open>take (Suc (Suc i)) xs \\<noteq> take (Suc (Suc i)) xs'\\<close>\n        by (metis Zero_not_Suc hd_Cons_tl take_eq_Nil) \n      moreover have \"xs' = hxs#txs'\"\n        unfolding hxs txs txs'\n        using \\<open>take (Suc i) xs = take (Suc i) xs'\\<close> \\<open>take (Suc (Suc i)) xs \\<noteq> take (Suc (Suc i)) xs'\\<close>\n        by (metis hd_Cons_tl hd_take take_Nil take_Suc_Cons take_tl zero_less_Suc)\n      ultimately have \"take (Suc i) txs \\<noteq> take (Suc i) txs'\"\n         using \\<open>take (Suc (Suc i)) xs \\<noteq> take (Suc (Suc i)) xs'\\<close>\n         by (metis take_Suc_Cons) \n      moreover have \"take i txs = take i txs'\"\n        using \\<open>take (Suc i) xs = take (Suc i) xs'\\<close> unfolding txs txs'\n        by (simp add: take_tl) \n      ultimately have \"\\<And> t . isin t txs \\<Longrightarrow> isin (Prefix_Tree.insert t txs') txs\" \n        using Suc.IH by blast\n\n      obtain m where \"t = PT m\"\n        using prefix_tree.exhaust by auto \n      \n      obtain t' where \"m hxs = Some t'\"\n                  and \"isin t' txs\"\n        using case_optionE by (metis Suc.prems(3) \\<open>t = PT m\\<close> \\<open>xs = hxs # txs\\<close> isin.simps(2)) \n\n      have \"isin (Prefix_Tree.insert t xs') xs = isin (Prefix_Tree.insert t' txs') txs\"\n        using \\<open>m hxs = Some t'\\<close> unfolding \\<open>t = PT m\\<close> \\<open>xs = hxs#txs\\<close> \\<open>xs' = hxs#txs'\\<close> by auto\n      then show ?case\n        using \\<open>\\<And> t . isin t txs \\<Longrightarrow> isin (Prefix_Tree.insert t txs') txs\\<close> \\<open>isin t' txs\\<close> \n        by simp\n    qed\n  qed\n\n  show ?thesis \n    using different_lists_shared_prefix[OF False] *[OF _ _ assms] by blast\nqed\n\n\nlemma insert_isin_rev : \n  assumes \"isin (insert t xs') xs\"\nshows \"isin t xs \\<or> (\\<exists> xs'' . xs' = xs@xs'')\" \nproof (cases \"xs = xs'\")\n  case True\n  then show ?thesis using insert_isin_prefix[of t xs \"[]\"] by simp\nnext\n  case False\n\n  have *: \"\\<And> i xs xs' . take i xs = take i xs' \\<Longrightarrow> take (Suc i) xs \\<noteq> take (Suc i) xs' \\<Longrightarrow> isin (insert t xs') xs \\<Longrightarrow> isin t xs \\<or> (\\<exists> xs'' . xs' = xs@xs'')\"\n  proof -\n    fix i xs xs' assume \"take i xs = take i xs'\"\n                    and \"take (Suc i) xs \\<noteq> take (Suc i) xs'\"\n                    and \"isin (insert t xs') xs\"\n    then show \"isin t xs \\<or> (\\<exists> xs'' . xs' = xs@xs'')\"\n    proof (induction i arbitrary: xs xs' t)\n      case 0\n      then consider (a) \"xs = [] \\<and> xs' \\<noteq> []\" |\n                    (b) \"xs' = [] \\<and> xs \\<noteq> []\" |\n                    (c) \"xs \\<noteq> [] \\<and> xs' \\<noteq> [] \\<and> hd xs \\<noteq> hd xs'\"\n        by (metis take_Suc take_eq_Nil)\n      then show ?case proof cases\n        case a\n        then show ?thesis\n          by (metis isin.simps(1) ) \n      next\n        case b\n        then show ?thesis\n          using \"0.prems\"(3) by auto\n      next\n        case c\n        then obtain b bs c cs where \"xs = b#bs\" and \"xs' = c#cs\" and \"b \\<noteq> c\"\n          using list.exhaust_sel by blast\n        obtain m where \"t = PT m\"\n          using prefix_tree.exhaust by auto \n        have \"isin (Prefix_Tree.insert t xs') xs = isin t xs\" \n          unfolding \\<open>t = PT m\\<close> \\<open>xs = b#bs\\<close> \\<open>xs' = c#cs\\<close> insert.simps isin.simps using \\<open>b \\<noteq> c\\<close>\n          by simp \n        then show ?thesis \n          using \\<open>isin (insert t xs') xs\\<close> by simp\n      qed\n    next\n      case (Suc i) \n\n      define hxs where hxs: \"hxs = hd xs\"\n      define txs where txs: \"txs = tl xs\"\n      define txs' where txs': \"txs' = tl xs'\"\n\n      have \"xs = hxs#txs\"\n        unfolding hxs txs\n        using \\<open>take (Suc i) xs = take (Suc i) xs'\\<close> \\<open>take (Suc (Suc i)) xs \\<noteq> take (Suc (Suc i)) xs'\\<close>\n        by (metis Zero_not_Suc hd_Cons_tl take_eq_Nil) \n      moreover have \"xs' = hxs#txs'\"\n        unfolding hxs txs txs'\n        using \\<open>take (Suc i) xs = take (Suc i) xs'\\<close> \\<open>take (Suc (Suc i)) xs \\<noteq> take (Suc (Suc i)) xs'\\<close>\n        by (metis hd_Cons_tl hd_take take_Nil take_Suc_Cons take_tl zero_less_Suc)\n      ultimately have \"take (Suc i) txs \\<noteq> take (Suc i) txs'\"\n         using \\<open>take (Suc (Suc i)) xs \\<noteq> take (Suc (Suc i)) xs'\\<close>\n         by (metis take_Suc_Cons) \n      moreover have \"take i txs = take i txs'\"\n        using \\<open>take (Suc i) xs = take (Suc i) xs'\\<close> unfolding txs txs'\n        by (simp add: take_tl) \n      ultimately have \"\\<And> t . isin (Prefix_Tree.insert t txs') txs \\<Longrightarrow> isin t txs \\<or> (\\<exists>xs''. txs' = txs @ xs'')\" \n        using Suc.IH by blast\n\n      \n      obtain m where \"t = PT m\"\n        using prefix_tree.exhaust by auto \n      \n      obtain t' where \"(m(hxs \\<mapsto> insert (case m hxs of None \\<Rightarrow> empty | Some t' \\<Rightarrow> t') txs')) hxs = Some t'\"\n                  and \"isin t' txs\"\n        using case_optionE \\<open>isin (Prefix_Tree.insert t xs') xs\\<close>\n        unfolding \\<open>t = PT m\\<close> \\<open>xs = hxs#txs\\<close> \\<open>xs' = hxs#txs'\\<close> insert.simps isin.simps by blast\n      then have \"t' = insert (case m hxs of None \\<Rightarrow> empty | Some t' \\<Rightarrow> t') txs'\"\n        by auto\n      then have *: \"isin (case m hxs of None \\<Rightarrow> empty | Some t' \\<Rightarrow> t') txs \\<or> (\\<exists>xs''. txs' = txs @ xs'')\"\n        using \\<open>\\<And> t . isin (Prefix_Tree.insert t txs') txs \\<Longrightarrow> isin t txs \\<or> (\\<exists>xs''. txs' = txs @ xs'')\\<close>\n              \\<open>isin t' txs\\<close>\n        by auto\n\n      show ?case proof (cases \"m hxs\")\n        case None\n        then have \"isin empty txs \\<or> (\\<exists>xs''. txs' = txs @ xs'')\"\n          using * by auto\n        then have \"txs = [] \\<or> (\\<exists>xs''. txs' = txs @ xs'')\"\n          by (metis Prefix_Tree.empty_def case_optionE isin.elims(2) option.discI prefix_tree.inject)\n        then have \"(\\<exists>xs''. txs' = txs @ xs'')\"\n          by auto\n        then show ?thesis \n          unfolding \\<open>xs = hxs#txs\\<close> \\<open>xs' = hxs#txs'\\<close> by auto\n      next\n        case (Some t'')\n        then consider \"isin t'' txs\" | \"(\\<exists>xs''. txs' = txs @ xs'')\"\n          using * by auto\n        then show ?thesis proof cases\n          case 1\n          moreover have \"isin t xs = isin t'' txs\"\n            unfolding \\<open>t = PT m\\<close> \\<open>xs = hxs#txs\\<close> \\<open>xs' = hxs#txs'\\<close> using Some by auto\n          ultimately show ?thesis by simp\n        next\n          case 2\n          then show ?thesis \n            unfolding \\<open>xs = hxs#txs\\<close> \\<open>xs' = hxs#txs'\\<close> by auto\n        qed\n      qed\n    qed\n  qed\n\n  show ?thesis \n    using different_lists_shared_prefix[OF False] *[OF _ _ assms] by blast\nqed\n\n\n\nlemma insert_set : \"set (insert t xs) = set t \\<union> {xs' . \\<exists> xs'' . xs = xs'@xs''}\"\nproof -\n  have \"set t \\<subseteq> set (insert t xs)\"\n    using insert_isin_other by auto\n  moreover have \"{xs' . \\<exists> xs'' . xs = xs'@xs''} \\<subseteq> set (insert t xs)\"\n    using insert_isin_prefix\n    by auto\n  moreover have \"set (insert t xs) \\<subseteq> set t \\<union> {xs' . \\<exists> xs'' . xs = xs'@xs''}\"\n    using insert_isin_rev[of t xs] unfolding set.simps by blast\n  ultimately show ?thesis\n    by blast\nqed\n\nlemma insert_isin : \"xs \\<in> set (insert t xs)\"\n  unfolding insert_set by auto\n\nlemma set_prefix :  \n  assumes \"xs@ys \\<in> set T\"\n  shows \"xs \\<in> set T\"\n  using assms isin_prefix by auto\n\n\nfun after :: \"'a prefix_tree \\<Rightarrow> 'a list \\<Rightarrow> 'a prefix_tree\" where\n  \"after t [] = t\" |\n  \"after (PT m) (x # xs) = (case m x of None \\<Rightarrow> empty | Some t \\<Rightarrow> after t xs)\"\n\nlemma after_set : \"set (after t xs) = Set.insert [] {xs' . xs@xs' \\<in> set t}\"\n  (is \"?A t xs = ?B t xs\")\nproof \n  show \"?A t xs \\<subseteq> ?B t xs\"\n  proof \n    fix xs' assume \"xs' \\<in> ?A t xs\"\n    then show \"xs' \\<in> ?B t xs\"\n    proof (induction xs arbitrary: t)\n      case Nil\n      then show ?case by auto\n    next\n      case (Cons x xs)\n      obtain m where \"t = PT m\"\n        using prefix_tree.exhaust by auto \n      show ?case proof (cases \"m x\")\n        case None\n        then have \"after t (x#xs) = empty\"\n          unfolding \\<open>t = PT m\\<close> by auto\n        then have \"xs' = []\"\n          using Cons.prems set_empty by auto\n        then show ?thesis by blast\n      next\n        case (Some t')\n        then have \"after t (x#xs) = after t' xs\"\n          unfolding \\<open>t = PT m\\<close> by auto\n        then have \"xs' \\<in> set (after t' xs)\"\n          using Cons.prems by simp\n        then have \"xs' \\<in> ?B t' xs\"\n          using Cons.IH by auto\n\n        show ?thesis proof (cases \"xs' = []\")\n          case True\n          then show ?thesis by auto\n        next\n          case False\n          then have \"isin t' (xs@xs')\"\n            using \\<open>xs' \\<in> ?B t' xs\\<close> by auto\n          then have \"isin t (x#(xs@xs'))\"\n            unfolding \\<open>t = PT m\\<close> using Some by auto\n          then show ?thesis by auto\n        qed\n      qed\n    qed\n  qed\n    \n  show \"?B t xs \\<subseteq> ?A t xs\"\n  proof \n    fix xs' assume \"xs' \\<in> ?B t xs\"\n    then show \"xs' \\<in> ?A t xs\"\n    proof (induction xs arbitrary: t)\n      case Nil\n      then show ?case by (cases xs'; auto)\n    next\n      case (Cons x xs)\n      obtain m where \"t = PT m\"\n        using prefix_tree.exhaust by auto \n\n      show ?case proof (cases \"xs' = []\")\n        case True\n        then show ?thesis by (cases xs'; auto)\n      next\n        case False\n        then have \"x # (xs @ xs') \\<in> set t\"\n          using Cons.prems by auto\n        then have \"isin t (x # (xs @ xs'))\"\n          by auto\n        then obtain t' where \"m x = Some t'\"\n                         and \"isin t' (xs@xs')\"\n          unfolding \\<open>t = PT m\\<close>\n          by (metis case_optionE isin.simps(2)) \n        then have \"xs' \\<in> ?B t' xs\"\n          by auto \n        then have \"xs' \\<in> ?A t' xs\"\n          using Cons.IH by blast\n        moreover have \"after t (x#xs) = after t' xs\"\n          using \\<open>m x = Some t'\\<close> unfolding \\<open>t = PT m\\<close> by auto\n        ultimately show ?thesis\n          by simp  \n      qed\n    qed\n  qed\nqed\n\nlemma after_set_Cons :\n  assumes \"\\<gamma> \\<in> set (after T \\<alpha>)\"\n  and     \"\\<gamma> \\<noteq> []\"\nshows \"\\<alpha> \\<in> set T\"\n  using assms unfolding after_set\n  by (metis insertE isin_prefix mem_Collect_eq set.simps)\n\n\nfunction (domintros) combine :: \"'a prefix_tree \\<Rightarrow> 'a prefix_tree \\<Rightarrow> 'a prefix_tree\" where\n  \"combine (PT m1) (PT m2) = (PT (\\<lambda> x . case m1 x of\n    None \\<Rightarrow> m2 x |\n    Some t1 \\<Rightarrow> (case m2 x of\n      None \\<Rightarrow> Some t1 |\n      Some t2 \\<Rightarrow> Some (combine t1 t2))))\"\n  by pat_completeness auto\ntermination \nproof -\n  {\n    fix a b :: \"'a prefix_tree\"   \n\n    have \"combine_dom (a,b)\" \n    proof (induction a arbitrary: b)\n      case (PT m1)\n  \n      obtain m2 where \"b = PT m2\"\n        by (metis prefix_tree.exhaust)\n  \n      have \"(\\<And>x a' b'. m1 x = Some a' \\<Longrightarrow> m2 x = Some b' \\<Longrightarrow> combine_dom (a', b'))\"\n      proof -\n        fix x a' b' assume \"m1 x = Some a'\" and \"m2 x = Some b'\"\n  \n        have \"Some a' \\<in> range m1\"\n          by (metis \\<open>m1 x = Some a'\\<close> range_eqI) \n        \n        show \"combine_dom (a', b')\"\n          using PT(1)[OF \\<open>Some a' \\<in> range m1\\<close>, of a']\n          by simp \n      qed\n  \n      then show ?case\n        using combine.domintros unfolding \\<open>b = PT m2\\<close> by blast\n    qed\n  } note t = this\n\n  then show ?thesis by auto\nqed\n\nlemma combine_alt_def : \n  \"combine (PT m1) (PT m2) = PT (\\<lambda>x . combine_options combine (m1 x) (m2 x))\"  \n  unfolding combine.simps\n  by (simp add: combine_options_def)\n\n\nlemma combine_set :\n  \"set (combine t1 t2) = set t1 \\<union> set t2\"\nproof \n\n  show \"set (combine t1 t2) \\<subseteq> set t1 \\<union> set t2\"\n  proof \n    fix xs assume \"xs \\<in> set (combine t1 t2)\"\n    then show \"xs \\<in> set t1 \\<union> set t2\"\n    proof (induction xs arbitrary: t1 t2)\n      case Nil\n      show ?case \n        using set_Nil by auto \n    next\n      case (Cons x xs)\n\n      obtain m1 m2 where \"t1 = PT m1\" and \"t2 = PT m2\"\n        by (meson prefix_tree.exhaust)  \n\n      obtain t' where \"combine_options combine (m1 x) (m2 x) = Some t'\"\n                  and \"isin t' xs\"\n        using Cons.prems unfolding \\<open>t1 = PT m1\\<close> \\<open>t2 = PT m2\\<close> combine_alt_def set.simps\n        by (metis (no_types, lifting) case_optionE isin.simps(2) mem_Collect_eq) \n\n      show ?case proof (cases \"m1 x\")\n        case None\n        show ?thesis proof (cases \"m2 x\")\n          case None\n          then have False\n            using \\<open>m1 x = None\\<close> \\<open>combine_options combine (m1 x) (m2 x) = Some t'\\<close>\n            by simp  \n          then show ?thesis \n            by simp\n        next\n          case (Some t'')\n          then have \"m2 x = Some t'\"\n            using \\<open>m1 x = None\\<close> \\<open>combine_options combine (m1 x) (m2 x) = Some t'\\<close>\n            by simp \n          then have \"isin t2 (x#xs)\"\n            using \\<open>isin t' xs\\<close> unfolding \\<open>t2 = PT m2\\<close> by auto\n          then show ?thesis\n            by simp            \n        qed\n      next\n        case (Some t1')\n        show ?thesis proof (cases \"m2 x\")\n          case None\n          then have \"m1 x = Some t'\"\n            using \\<open>m1 x = Some t1'\\<close> \\<open>combine_options combine (m1 x) (m2 x) = Some t'\\<close>\n            by simp \n          then have \"isin t1 (x#xs)\"\n            using \\<open>isin t' xs\\<close> unfolding \\<open>t1 = PT m1\\<close> by auto\n          then show ?thesis\n            by simp \n        next\n          case (Some t2')\n          then have \"t' = combine t1' t2'\"\n            using \\<open>m1 x = Some t1'\\<close> \\<open>combine_options combine (m1 x) (m2 x) = Some t'\\<close>\n            by simp  \n          then have \"xs \\<in> Prefix_Tree.set (combine t1' t2')\"\n            using \\<open>isin t' xs\\<close>\n            by simp \n          then have \"xs \\<in> Prefix_Tree.set t1' \\<union> Prefix_Tree.set t2'\"\n            using Cons.IH by blast\n          then have \"isin t1' xs \\<or> isin t2' xs\"\n            by simp\n          then have \"isin t1 (x#xs) \\<or> isin t2 (x#xs)\"\n            using \\<open>m1 x = Some t1'\\<close> \\<open>m2 x = Some t2'\\<close> unfolding \\<open>t1 = PT m1\\<close> \\<open>t2 = PT m2\\<close> by auto\n          then show ?thesis \n            by simp\n        qed\n      qed\n    qed\n  qed\n  \n  show \"(set t1 \\<union> set t2) \\<subseteq> set (combine t1 t2)\"\n  proof -\n    have \"set t1 \\<subseteq> set (combine t1 t2)\"\n    proof \n      fix xs assume \"xs \\<in> set t1\"\n      then have \"isin t1 xs\"\n        by auto\n      then show \"xs \\<in> set (combine t1 t2)\"\n      proof (induction xs arbitrary: t1 t2)\n        case Nil\n        then show ?case using set_Nil by auto\n      next\n        case (Cons x xs)\n\n        obtain m1 m2 where \"t1 = PT m1\" and \"t2 = PT m2\"\n          by (meson prefix_tree.exhaust)\n        \n        obtain t1' where \"m1 x = Some t1'\"\n                     and \"isin t1' xs\"\n          using Cons.prems unfolding \\<open>t1 = PT m1\\<close> isin.simps\n          using case_optionE by blast \n\n        show ?case proof (cases \"m2 x\")\n          case None\n          then have \"combine_options combine (m1 x) (m2 x) = Some t1'\"\n            by (simp add: \\<open>m1 x = Some t1'\\<close>)\n          then have \"isin (combine t1 t2) (x#xs)\"\n            using combine_alt_def\n            by (metis (no_types, lifting) Cons.prems \\<open>m1 x = Some t1'\\<close> \\<open>t1 = PT m1\\<close> \\<open>t2 = PT m2\\<close> isin.simps(2)) \n          then show ?thesis \n            by simp\n        next\n          case (Some t2')\n          then have \"combine_options combine (m1 x) (m2 x) = Some (combine t1' t2')\"\n            by (simp add: \\<open>m1 x = Some t1'\\<close>)\n          moreover have \"isin (combine t1' t2') xs\"\n            using Cons.IH[OF \\<open>isin t1' xs\\<close>]\n            by simp\n          ultimately have \"isin (combine t1 t2) (x#xs)\"\n            unfolding \\<open>t1 = PT m1\\<close> \\<open>t2 = PT m2\\<close> using isin.simps(2)[of _ x xs]\n            by (metis (no_types, lifting) combine_alt_def option.simps(5))\n          then show ?thesis by simp\n        qed\n      qed\n    qed\n    moreover have \"set t2 \\<subseteq> set (combine t1 t2)\"\n    proof \n      fix xs assume \"xs \\<in> set t2\"\n      then have \"isin t2 xs\"\n        by auto\n      then show \"xs \\<in> set (combine t1 t2)\"\n      proof (induction xs arbitrary: t1 t2)\n        case Nil\n        then show ?case using set_Nil by auto\n      next\n        case (Cons x xs)\n\n        obtain m1 m2 where \"t1 = PT m1\" and \"t2 = PT m2\"\n          by (meson prefix_tree.exhaust)\n        \n        obtain t2' where \"m2 x = Some t2'\"\n                     and \"isin t2' xs\"\n          using Cons.prems unfolding \\<open>t2 = PT m2\\<close> isin.simps\n          using case_optionE by blast \n\n        show ?case proof (cases \"m1 x\")\n          case None\n          then have \"combine_options combine (m1 x) (m2 x) = Some t2'\"\n            by (simp add: \\<open>m2 x = Some t2'\\<close>)\n          then have \"isin (combine t1 t2) (x#xs)\"\n            using combine_alt_def\n            by (metis (no_types, lifting) Cons.prems \\<open>m2 x = Some t2'\\<close> \\<open>t1 = PT m1\\<close> \\<open>t2 = PT m2\\<close> isin.simps(2)) \n          then show ?thesis \n            by simp\n        next\n          case (Some t1')\n          then have \"combine_options combine (m1 x) (m2 x) = Some (combine t1' t2')\"\n            by (simp add: \\<open>m2 x = Some t2'\\<close>)\n          moreover have \"isin (combine t1' t2') xs\"\n            using Cons.IH[OF \\<open>isin t2' xs\\<close>]\n            by simp\n          ultimately have \"isin (combine t1 t2) (x#xs)\"\n            unfolding \\<open>t1 = PT m1\\<close> \\<open>t2 = PT m2\\<close> using isin.simps(2)[of _ x xs]\n            by (metis (no_types, lifting) combine_alt_def option.simps(5))\n          then show ?thesis by simp\n        qed\n      qed\n    qed\n    ultimately show ?thesis \n      by blast\n  qed\nqed\n\n\n\n\nfun combine_after :: \"'a prefix_tree \\<Rightarrow> 'a list \\<Rightarrow> 'a prefix_tree \\<Rightarrow> 'a prefix_tree\" where\n  \"combine_after t1 [] t2 = combine t1 t2\" |\n  \"combine_after (PT m) (x#xs) t2 = PT (m(x \\<mapsto> combine_after (case m x of None \\<Rightarrow> empty | Some t' \\<Rightarrow> t') xs t2))\"\n\nlemma combine_after_set : \"set (combine_after t1 xs t2) = set t1 \\<union> {xs' . \\<exists> xs'' . xs = xs'@xs''} \\<union> {xs@xs' | xs' . xs' \\<in> set t2}\"\nproof \n  show \"set (combine_after t1 xs t2) \\<subseteq> set t1 \\<union> {xs' . \\<exists> xs'' . xs = xs'@xs''} \\<union> {xs@xs' | xs' . xs' \\<in> set t2}\"\n  proof \n    fix ys assume \"ys \\<in> set (combine_after t1 xs t2)\"\n    then show \"ys \\<in> set t1 \\<union> {xs' . \\<exists> xs'' . xs = xs'@xs''} \\<union> {xs@xs' | xs' . xs' \\<in> set t2}\"\n    proof (induction ys arbitrary: xs t1)\n      case Nil\n      show ?case using set_Nil by auto\n    next\n      case (Cons y ys)\n\n      obtain m1 where \"t1 = PT m1\"\n        by (meson prefix_tree.exhaust)  \n      \n      show ?case proof (cases xs)\n        case Nil\n        then show ?thesis using combine_set Cons.prems by auto\n      next\n        case (Cons x xs')\n\n        show ?thesis proof (cases \"x = y\")\n          case True\n          then have \"isin (combine_after t1 (x#xs') t2) (x#ys)\"\n            using Cons Cons.prems by auto\n          then have \"isin (combine_after (case m1 x of None \\<Rightarrow> empty | Some t' \\<Rightarrow> t') xs' t2) ys\"\n            unfolding \\<open>t1 = PT m1\\<close> by auto\n          then consider \"ys \\<in> set (case m1 x of None \\<Rightarrow> empty | Some t' \\<Rightarrow> t')\" | \"ys \\<in> {xs'' . \\<exists> xs''' . xs' = xs''@xs'''}\" | \"ys \\<in> {xs' @ xs'' |xs''. xs'' \\<in> set t2}\"\n            using Cons.IH by auto\n          then show ?thesis proof cases\n            case 1\n            then show ?thesis proof (cases \"m1 x\")\n              case None\n              then have \"ys = []\"\n                using 1 set_empty by auto\n              then show ?thesis unfolding True Cons by auto\n            next\n              case (Some t')\n              then have \"isin t' ys\"\n                using 1 by auto\n              then have \"y # ys \\<in> Prefix_Tree.set (PT m1)\"\n                using Some by (simp add: True)  \n              then show ?thesis unfolding \\<open>t1 = PT m1\\<close> by auto \n            qed\n          next\n            case 2\n            then show ?thesis unfolding True \\<open>t1 = PT m1\\<close> Cons by auto\n          next\n            case 3\n            then show ?thesis unfolding True \\<open>t1 = PT m1\\<close> Cons by auto\n          qed \n        next\n          case False\n          then have \"(m1(x \\<mapsto> combine_after (case m1 x of None \\<Rightarrow> empty | Some t' \\<Rightarrow> t') xs' t2)) y = m1 y\"\n            by auto\n          then have \"isin t1 (y#ys)\"\n            using Cons Cons.prems unfolding \\<open>t1 = PT m1\\<close>\n            by simp \n          then show ?thesis by auto\n        qed\n      qed\n    qed \n  qed\n\n  show \"set t1 \\<union> {xs' . \\<exists> xs'' . xs = xs'@xs''} \\<union> {xs@xs' | xs' . xs' \\<in> set t2} \\<subseteq> set (combine_after t1 xs t2)\"\n  proof -\n    have \"set t1 \\<subseteq> set (combine_after t1 xs t2)\"\n    proof\n      fix ys assume \"ys \\<in> set t1\"\n      then show \"ys \\<in> set (combine_after t1 xs t2)\"\n      proof (induction ys arbitrary: t1 xs)\n        case Nil\n        then show ?case using set_Nil by auto\n      next\n        case (Cons y ys)\n        then have \"isin t1 (y#ys)\"\n          by auto\n        \n        show ?case proof (cases \"xs\")\n          case Nil\n          then show ?thesis using Cons.prems combine_set by auto\n        next\n          case (Cons x xs')\n\n          obtain m1 where \"t1 = PT m1\"\n            by (meson prefix_tree.exhaust) \n          obtain t' where \"m1 y = Some t'\"\n                      and \"isin t' ys\"\n            using \\<open>isin t1 (y#ys)\\<close> unfolding \\<open>t1 = PT m1\\<close> isin.simps\n            using case_optionE by blast \n          then have \"ys \\<in> set t'\"\n            by auto\n          then have \"isin (combine_after t' xs' t2) ys\"\n            using Cons.IH by auto\n\n          show ?thesis proof (cases \"x=y\")\n            case True\n            show ?thesis \n              using \\<open>isin (combine_after t' xs' t2) ys\\<close> \\<open>m1 y = Some t'\\<close>\n              unfolding Cons True \\<open>t1 = PT m1\\<close> by auto\n          next\n            case False\n            then have \"isin (combine_after (PT m1) (x # xs') t2) (y#ys) = isin (PT m1) (y#ys)\"\n              unfolding combine_after.simps by auto\n            then show ?thesis \n              using \\<open>y # ys \\<in> Prefix_Tree.set t1\\<close>\n              unfolding Cons \\<open>t1 = PT m1\\<close> \n              by auto\n          qed\n        qed\n      qed\n    qed\n    moreover have \"{xs' . \\<exists> xs'' . xs = xs'@xs''} \\<union> {xs@xs' | xs' . xs' \\<in> set t2} \\<subseteq> set (combine_after t1 xs t2)\"\n    proof -\n      have \"{xs@xs' | xs' . xs' \\<in> set t2} \\<subseteq> set (combine_after t1 xs t2) \\<Longrightarrow> {xs' . \\<exists> xs'' . xs = xs'@xs''} \\<subseteq> set (combine_after t1 xs t2)\"\n      proof \n        fix ys assume *:\"{xs@xs' | xs' . xs' \\<in> set t2} \\<subseteq> set (combine_after t1 xs t2)\"\n                  and \"ys \\<in> {xs' . \\<exists> xs'' . xs = xs'@xs''}\"   \n        then obtain xs' where \"xs = ys@xs'\"\n          by blast\n        then have **: \"isin (combine_after t1 xs t2) (ys@xs')\"\n          using * set_Nil[of t2] by force\n        show \"ys \\<in> set (combine_after t1 xs t2)\"\n          using  isin_prefix[OF **] by auto\n      qed\n      moreover have \"{xs@xs' | xs' . xs' \\<in> set t2} \\<subseteq> set (combine_after t1 xs t2)\"\n      proof \n        fix ys assume \"ys \\<in> {xs@xs' | xs' . xs' \\<in> set t2}\"\n        then obtain xs' where \"ys = xs@xs'\" and \"xs' \\<in> set t2\"\n          by auto\n\n        \n\n        show \"ys \\<in> set (combine_after t1 xs t2)\" \n          unfolding \\<open>ys = xs@xs'\\<close>\n        proof (induction xs arbitrary: t1)\n          case Nil \n          then show ?case using combine_set \\<open>xs' \\<in> set t2\\<close> by auto\n        next\n          case (Cons x xs)\n\n          obtain m1 where \"t1 = PT m1\"\n            by (meson prefix_tree.exhaust) \n\n          have \"isin (combine_after t1 (x # xs) t2) ((x # xs) @ xs') = isin (combine_after (case m1 x of None \\<Rightarrow> empty | Some t' \\<Rightarrow> t') xs t2) (xs @ xs')\"\n            unfolding \\<open>t1 = PT m1\\<close> by auto\n          then have *:\"(x # xs) @ xs' \\<in> Prefix_Tree.set (combine_after t1 (x # xs) t2) = isin (combine_after (case m1 x of None \\<Rightarrow> empty | Some t' \\<Rightarrow> t') xs t2) (xs @ xs')\"\n            by auto\n\n          show ?case \n            using \\<open>xs' \\<in> set t2\\<close> Cons \n            unfolding * \n            by (cases \"m1 x\"; simp)\n        qed\n      qed\n      ultimately show ?thesis\n        by blast\n    qed\n    ultimately show ?thesis\n      by blast\n  qed\nqed\n\n\nfun from_list :: \"'a list list \\<Rightarrow> 'a prefix_tree\" where\n  \"from_list xs = foldr (\\<lambda> x t . insert t x) xs empty\"\n\nlemma from_list_set : \"set (from_list xs) = Set.insert [] {xs'' . \\<exists> xs' xs''' . xs' \\<in> list.set xs \\<and> xs' = xs''@xs'''}\"\nproof (induction xs)\n  case Nil\n  have \"from_list [] = empty\"\n    by auto\n  then have \"set (from_list []) = {[]}\"\n    using set_empty by auto\n  moreover have \"Set.insert [] {xs'' . \\<exists> xs' xs''' . xs' \\<in> list.set [] \\<and> xs' = xs''@xs'''} = {[]}\"\n    by auto\n  ultimately show ?case \n    by blast\nnext\n  case (Cons x xs)\n\n  have \"from_list (x#xs) = insert (from_list xs) x\"\n    by auto\n  then have \"set (from_list (x#xs)) = set (from_list xs) \\<union> {xs'. \\<exists>xs''. x = xs' @ xs''}\"\n    using insert_set by auto\n  then show ?case\n    unfolding Cons by force\nqed\n\nlemma from_list_subset : \"list.set xs \\<subseteq> set (from_list xs)\"\n  unfolding from_list_set by auto\n\nlemma from_list_set_elem :\n  assumes \"x \\<in> list.set xs\"\n  shows \"x \\<in> set (from_list xs)\"\n  using assms unfolding from_list_set by force\n\nfunction (domintros) finite_tree :: \"'a prefix_tree \\<Rightarrow> bool\" where\n  \"finite_tree (PT m) = (finite (dom m) \\<and> (\\<forall> t \\<in> ran m . finite_tree t))\"\n  by pat_completeness auto\ntermination\nproof -\n  { fix a :: \"'a prefix_tree\"   \n\n    have \"finite_tree_dom a\" \n    proof (induction a)\n      case (PT m)\n  \n      have \"(\\<And>x. x \\<in> ran m \\<Longrightarrow> finite_tree_dom x)\"\n      proof -\n        fix x :: \"'a prefix_tree\"\n        assume \"x \\<in> ran m\"\n        then have \"\\<exists>a. m a = Some x\"\n          by (simp add: ran_def)\n        then show \"finite_tree_dom x\"\n          using PT.IH by blast\n      qed  \n      then show ?case\n        using finite_tree.domintros\n        by blast \n    qed\n  }\n  then show ?thesis by auto\nqed\n\nlemma combine_after_after_subset :\n  \"set T2 \\<subseteq> set (after (combine_after T1 xs T2) xs)\"\n  unfolding combine_after_set after_set\n  by auto\n\nlemma subset_after_subset :\n  \"set T2 \\<subseteq> set T1 \\<Longrightarrow> set (after T2 xs) \\<subseteq> set (after T1 xs)\"\n  unfolding after_set by auto\n\nlemma set_alt_def :\n  \"set (PT m) = Set.insert [] (\\<Union> x \\<in> dom m . (Cons x) ` (set (the (m x))))\"\n  (is \"?A m = ?B m\")\nproof \n  show \"?A m \\<subseteq> ?B m\" \n  proof\n    fix xs assume \"xs \\<in> ?A m\"\n    then have \"isin (PT m) xs\"\n      by auto\n    then show \"xs \\<in> ?B m\"\n    proof (induction xs arbitrary: m)\n      case Nil\n      then show ?case by auto\n    next\n      case (Cons x xs)\n      then obtain t where \"m x = Some t\"\n                      and \"isin t xs\"\n        by (metis (no_types, lifting) case_optionE isin.simps(2)) \n      \n      obtain m' where \"t = PT m'\"\n        using prefix_tree.exhaust by blast\n      then have \"xs \\<in> ?B m'\"\n        using \\<open>isin t xs\\<close> Cons.IH by blast\n      moreover have \"x \\<in> dom m\"\n        using \\<open>m x = Some t\\<close>\n        by auto\n      ultimately show ?case \n        using \\<open>m x = Some t\\<close>\n        using \\<open>isin t xs\\<close> \\<open>t = PT m'\\<close> \n        by fastforce  \n    qed\n  qed\n\n  show \"?B m \\<subseteq> ?A m\"\n  proof\n    fix xs assume \"xs \\<in> ?B m\"\n    then show \"xs \\<in> ?A m\"\n    proof (induction xs arbitrary: m)\n      case Nil\n      show ?case \n        by auto\n    next\n      case (Cons x xs)\n      then have \"x#xs \\<in> (\\<Union> x \\<in> dom m . (Cons x) ` (set (the (m x))))\"\n        by auto\n      then have \"x \\<in> dom m\"\n            and \"xs \\<in> (set (the (m x)))\"\n        by auto\n      then obtain t where \"m x = Some t\" and \"isin t xs\"\n        unfolding keys_is_none_rep\n        by auto\n      then show ?case\n        by auto\n    qed\n  qed\nqed\n\n\n\nlemma finite_tree_iff :\n  \"finite_tree t = finite (set t)\"\n  (is \"?P1 = ?P2\")\nproof \n  show \"?P1 \\<Longrightarrow> ?P2\"\n  proof induction\n    case (PT m)\n  \n    have \"set (PT m) = Set.insert [] (\\<Union>x\\<in>dom m. (#) x ` set (the (m x)))\"\n      unfolding set_alt_def by simp\n    moreover have \"finite (dom m)\"\n      using PT.prems by auto\n    moreover have \"\\<And> x . x \\<in> dom m \\<Longrightarrow> finite ((#) x ` set (the (m x)))\"\n    proof -\n      fix x assume \"x \\<in> dom m\"\n      then obtain y where \"m x = Some y\"\n        by auto\n      then have \"y \\<in> ran m\"\n        by (meson ranI)\n      then have \"finite_tree y\"\n        using PT.prems by auto\n      then have \"finite (set y)\"\n        using PT.IH[of \"Some y\" y] \\<open>m x = Some y\\<close>\n        by (metis option.set_intros rangeI) \n      moreover have \"(the (m x)) = y\"\n        using \\<open>m x = Some y\\<close> by auto\n      ultimately show \"finite ((#) x ` set (the (m x)))\"\n        by blast\n    qed\n    ultimately show ?case\n      by simp \n  qed\n\n  show \"?P2 \\<Longrightarrow> ?P1\"\n  proof (induction t)\n    case (PT m)\n  \n    have \"finite (dom m)\"\n    proof -\n      have \"\\<And> x . x \\<in> dom m \\<Longrightarrow> [x] \\<in> set (PT m)\"\n        using image_eqI by auto\n      then have \"(\\<lambda>x . [x]) ` dom m \\<subseteq> set (PT m)\"\n        by auto\n      have \"inj (\\<lambda>x . [x])\"\n        by (meson inj_onI list.inject)    \n      show ?thesis\n        by (meson PT.prems UNIV_I \\<open>(\\<lambda>x. [x]) ` dom m \\<subseteq> Prefix_Tree.set (PT m)\\<close> \\<open>inj (\\<lambda>x. [x])\\<close> inj_on_finite inj_on_subset subsetI)  \n    qed\n    moreover have \"\\<And> t . t \\<in> ran m \\<Longrightarrow> finite_tree t\"\n    proof -\n      fix t assume \"t \\<in> ran m\"\n      then obtain x where \"m x = Some t\"\n        unfolding ran_def by blast\n      then have \"(#) x ` set t \\<subseteq> set (PT m)\"\n        unfolding set_alt_def\n        by auto \n      then have \"finite ((#) x ` set t)\"\n        using PT.prems\n        by (simp add: finite_subset) \n      moreover have \"inj ((#) x)\"\n        by auto \n      ultimately have \"finite (set t)\"\n        by (simp add: finite_image_iff)\n      then show \"finite_tree t\"\n        using PT.IH[of \"Some t\" t] \\<open>m x = Some t\\<close>\n        by (metis option.set_intros rangeI) \n    qed\n    ultimately show ?case\n      by simp \n  qed\nqed\n  \nlemma empty_finite_tree : \n  \"finite_tree empty\"\n  unfolding finite_tree_iff set_empty by auto\n\nlemma insert_finite_tree : \n  assumes \"finite_tree t\"\n  shows \"finite_tree (insert t xs)\"\nproof -\n  have \"{xs'. \\<exists>xs''. xs = xs' @ xs''} = list.set (prefixes xs)\"\n    unfolding prefixes_set by blast\n  then have \"finite {xs'. \\<exists>xs''. xs = xs' @ xs''}\" \n    using List.finite_set by simp\n  then show ?thesis\n    using assms unfolding finite_tree_iff insert_set \n    by blast\nqed\n\nlemma from_list_finite_tree : \n  \"finite_tree (from_list xs)\"\n  using insert_finite_tree empty_finite_tree by (induction xs; auto)\n\nlemma combine_after_finite_tree :\n  assumes \"finite_tree t1\"\n  and     \"finite_tree t2\"\nshows \"finite_tree (combine_after t1 \\<alpha> t2)\"\nproof -\n  have \"finite (Prefix_Tree.set t2)\" and \"finite (Prefix_Tree.set t1)\"\n    using assms unfolding finite_tree_iff by auto\n  then have \"finite (Prefix_Tree.set (Prefix_Tree.insert t1 \\<alpha>) \\<union> {\\<alpha> @ as |as. as \\<in> Prefix_Tree.set t2})\"\n    using finite_tree_iff insert_finite_tree by fastforce\n  then show ?thesis\n    unfolding finite_tree_iff combine_after_set\n    by (metis insert_set)\nqed\n\nlemma combine_finite_tree :\n  assumes \"finite_tree t1\"\n  and     \"finite_tree t2\"\nshows \"finite_tree (combine t1 t2)\"\n  using assms unfolding finite_tree_iff combine_set\n  by blast\n\n\nfunction (domintros) sorted_list_of_maximal_sequences_in_tree :: \"('a :: linorder) prefix_tree \\<Rightarrow> 'a list list\" where\n  \"sorted_list_of_maximal_sequences_in_tree (PT m) = \n    (if dom m = {}\n      then [[]]\n      else concat (map (\\<lambda>k . map ((#) k) (sorted_list_of_maximal_sequences_in_tree (the (m k)))) (sorted_list_of_set (dom m))))\"\n  by pat_completeness auto\ntermination \nproof -\n  { fix a :: \"'a prefix_tree\"   \n\n    have \"sorted_list_of_maximal_sequences_in_tree_dom a\" \n    proof (induction a)\n      case (PT m)\n      then show ?case\n        by (metis List.set_empty domIff empty_iff option.set_sel range_eqI set_sorted_list_of_set sorted_list_of_maximal_sequences_in_tree.domintros sorted_list_of_set.fold_insort_key.infinite)\n    qed\n  }\n  then show ?thesis by auto\nqed\n\n\nlemma sorted_list_of_maximal_sequences_in_tree_Nil :\n  assumes \"[] \\<in> list.set (sorted_list_of_maximal_sequences_in_tree t)\" \nshows \"t = empty\"\nproof -\n  obtain m where \"t = PT m\"\n    using prefix_tree.exhaust by blast\n\n  show ?thesis proof (cases \"dom m = {}\")\n    case True\n    then have \"m = Map.empty\"\n      using True by blast\n    then show ?thesis\n      unfolding \\<open>t = PT m\\<close>\n      by (simp add: Prefix_Tree.empty_def)\n  next\n    case False\n    then have \"[] \\<in> list.set (concat (map (\\<lambda>k . map ((#) k) (sorted_list_of_maximal_sequences_in_tree (the (m k)))) (sorted_list_of_set (dom m))))\"\n      using assms unfolding \\<open>t = PT m\\<close> by auto\n    then show ?thesis\n      by auto \n  qed\nqed\n\nlemma sorted_list_of_maximal_sequences_in_tree_set :\n  assumes \"finite_tree t\"\n  shows \"list.set (sorted_list_of_maximal_sequences_in_tree t) = {y. y \\<in> set t \\<and> \\<not>(\\<exists> y' . y' \\<noteq> [] \\<and> y@y' \\<in> set t)}\"\n    (is \"?S1 = ?S2\")\nproof \n  show \"?S1 \\<subseteq> ?S2\"\n  proof \n    fix xs assume \"xs \\<in> ?S1\"\n    then show \"xs \\<in> ?S2\"\n    proof (induction xs arbitrary: t)\n      case Nil\n      then have \"t = empty\"\n        using sorted_list_of_maximal_sequences_in_tree_Nil by auto\n      then show ?case \n        using set_empty by auto\n    next\n      case (Cons x xs)\n\n      obtain m where \"t = PT m\"\n        using prefix_tree.exhaust by blast\n      have \"x#xs \\<in> list.set (concat (map (\\<lambda>k . map ((#) k) (sorted_list_of_maximal_sequences_in_tree (the (m k)))) (sorted_list_of_set (dom m))))\"\n        by (metis (no_types) Cons.prems(1) \\<open>t = PT m\\<close> empty_iff list.set(1) list.simps(3) set_ConsD sorted_list_of_maximal_sequences_in_tree.simps)\n      then have \"x \\<in> list.set (sorted_list_of_set (dom m))\"\n            and \"xs \\<in> list.set (sorted_list_of_maximal_sequences_in_tree (the (m x)))\"\n        by auto\n\n      have \"x \\<in> dom m\"\n        using \\<open>x \\<in> list.set (sorted_list_of_set (dom m))\\<close> unfolding \\<open>t = PT m\\<close>\n        by (metis equals0D list.set(1) sorted_list_of_set.fold_insort_key.infinite sorted_list_of_set.set_sorted_key_list_of_set)\n      then obtain t' where \"m x = Some t'\"\n        by auto\n      then have \"xs \\<in> list.set (sorted_list_of_maximal_sequences_in_tree t')\"\n        using \\<open>xs \\<in> list.set (sorted_list_of_maximal_sequences_in_tree (the (m x)))\\<close> \n        by auto\n      then have \"xs \\<in> set t'\" and \"\\<not>(\\<exists> y' . y' \\<noteq> [] \\<and> xs@y' \\<in> set t')\"\n        using Cons.IH by blast+\n\n      have \"x#xs \\<in> set t\"\n        unfolding \\<open>t = PT m\\<close> using \\<open>xs \\<in> set t'\\<close> \\<open>m x = Some t'\\<close> by auto\n      moreover have \"\\<not>(\\<exists> y' . y' \\<noteq> [] \\<and> (x#xs)@y' \\<in> set t)\"\n      proof \n        assume \"\\<exists>y'. y' \\<noteq> [] \\<and> (x # xs) @ y' \\<in> Prefix_Tree.set t\"\n        then obtain y' where \"y' \\<noteq> []\" and \"(x # xs) @ y' \\<in> Prefix_Tree.set t\"\n          by blast\n        then have \"isin (PT m) (x # (xs @ y'))\"\n          unfolding \\<open>t = PT m\\<close> by auto\n        then have \"isin t' (xs @ y')\"\n          using \\<open>m x = Some t'\\<close> by auto\n        then have \"\\<exists> y' . y' \\<noteq> [] \\<and> xs@y' \\<in> set t'\"\n          using \\<open>y' \\<noteq> []\\<close> by auto\n        then show False\n          using \\<open>\\<not>(\\<exists> y' . y' \\<noteq> [] \\<and> xs@y' \\<in> set t')\\<close> by simp\n      qed\n      ultimately show ?case by blast\n    qed\n  qed\n\n  show \"?S2 \\<subseteq> ?S1\"\n  proof \n    fix xs assume \"xs \\<in> ?S2\"\n    then show \"xs \\<in> ?S1\"\n    using assms proof (induction xs arbitrary: t)\n      case Nil\n      then have \"set t = {[]}\"\n        by auto\n      moreover obtain m where \"t = PT m\"\n        using prefix_tree.exhaust by blast\n      ultimately have \"\\<And> x . \\<not> isin (PT m) [x]\"\n        by force\n      moreover have \"\\<And> x . x \\<in> dom m \\<Longrightarrow> isin (PT m) [x]\"\n        by auto\n      ultimately have \"dom m = {}\"\n        by blast\n      then show ?case\n        unfolding \\<open>t = PT m\\<close> by auto\n    next\n      case (Cons x xs)\n\n      obtain m where \"t = PT m\"\n        using prefix_tree.exhaust by blast\n      then have \"isin (PT m) (x#xs)\"\n        using Cons.prems(1) by auto\n      then obtain t' where \"m x = Some t'\"\n                       and \"isin t' xs\"\n        by (metis case_optionE isin.simps(2))\n      then have \"x \\<in> dom m\"\n        by auto\n      then have \"dom m \\<noteq> {}\"\n        by auto\n\n      have \"finite_tree t'\"\n        using \\<open>finite_tree t\\<close> \\<open>m x = Some t'\\<close> unfolding \\<open>t = PT m\\<close>\n        by (meson finite_tree.simps ranI) \n      moreover have \"xs \\<in> {y \\<in> Prefix_Tree.set t'. \\<nexists>y'. y' \\<noteq> [] \\<and> y @ y' \\<in> Prefix_Tree.set t'}\"\n      proof -\n        have \"xs \\<in> set t'\"\n          using \\<open>isin t' xs\\<close> by auto\n        moreover have \"(\\<nexists>y'. y' \\<noteq> [] \\<and> xs @ y' \\<in> Prefix_Tree.set t')\"\n        proof \n          assume \"\\<exists>y'. y' \\<noteq> [] \\<and> xs @ y' \\<in> Prefix_Tree.set t'\"\n          then obtain y' where \"y' \\<noteq> []\" and \"xs @ y' \\<in> Prefix_Tree.set t'\"\n            by blast\n          then have \"isin t' (xs@y')\"\n            by auto\n          then have \"isin (PT m) (x#(xs@y'))\"\n            using \\<open>m x = Some t'\\<close> by auto\n          then show False\n            using Cons.prems(1) \\<open>y' \\<noteq> []\\<close> unfolding \\<open>t = PT m\\<close> by auto\n        qed\n        ultimately show ?thesis\n          by blast\n      qed\n      ultimately have \"xs \\<in> list.set (sorted_list_of_maximal_sequences_in_tree t')\"\n        using Cons.IH by blast\n      moreover have \"x \\<in> list.set (sorted_list_of_set (dom m))\"\n        using \\<open>x \\<in> dom m\\<close> \\<open>finite_tree t\\<close> unfolding \\<open>t = PT m\\<close>\n        by simp\n      ultimately show ?case\n        using \\<open>finite_tree t\\<close> \\<open>dom m \\<noteq> {}\\<close> \\<open>m x = Some t'\\<close> unfolding \\<open>t = PT m\\<close> \n        by force\n    qed\n  qed\nqed\n\n\nlemma sorted_list_of_maximal_sequences_in_tree_ob :\n  assumes \"finite_tree T\"\n  and     \"xs \\<in> set T\"\nobtains xs' where \"xs@xs' \\<in> list.set (sorted_list_of_maximal_sequences_in_tree T)\"\nproof -\n  let ?xs = \"{xs@xs' | xs' . xs@xs' \\<in> set T}\"\n\n  let ?xs' = \"arg_max_on length ?xs\"\n\n  have \"xs \\<in> ?xs\"\n    using assms(2) by auto\n  then have \"?xs \\<noteq> {}\"\n    by blast\n  moreover have \"finite ?xs\"\n    using finite_subset[of ?xs \"set T\"]\n    using assms(1) unfolding finite_tree_iff \n    by blast\n  ultimately obtain xs' where \"xs' \\<in> ?xs\" and \"\\<And> xs'' . xs'' \\<in> ?xs \\<Longrightarrow> length xs'' \\<le> length xs'\"\n    using max_length_elem[of ?xs]\n    by force\n\n  obtain xs'' where \"xs' = xs@xs''\" and \"xs@xs'' \\<in> set T\"\n    using \\<open>xs' \\<in> ?xs\\<close> by auto\n  have \"\\<And> xs''' . xs@xs''' \\<in> set T \\<Longrightarrow> length xs''' \\<le> length xs''\"\n  proof -\n    fix xs''' assume \"xs@xs''' \\<in> set T\"\n    then have \"xs@xs''' \\<in> ?xs\"\n      by auto\n    then have \"length (xs@xs''')  \\<le> length xs'\"\n      using \\<open>\\<And> xs'' . xs'' \\<in> ?xs \\<Longrightarrow> length xs'' \\<le> length xs'\\<close> \n      by blast\n    then show \"length xs''' \\<le> length xs''\"\n      unfolding \\<open>xs' = xs@xs''\\<close> by auto\n  qed\n  then have \"\\<not>(\\<exists> y' . y' \\<noteq> [] \\<and> (xs@xs'')@y' \\<in> set T)\"\n    by fastforce\n  then have \"xs@xs'' \\<in> list.set (sorted_list_of_maximal_sequences_in_tree T)\"\n    using \\<open>xs@xs'' \\<in> set T\\<close>\n    unfolding sorted_list_of_maximal_sequences_in_tree_set[OF assms(1)]\n    by blast\n  then show ?thesis using that by blast\nqed\n\n\nfunction (domintros) sorted_list_of_sequences_in_tree :: \"('a :: linorder) prefix_tree \\<Rightarrow> 'a list list\" where\n  \"sorted_list_of_sequences_in_tree (PT m) = \n    (if dom m = {}\n      then [[]]\n      else [] # concat (map (\\<lambda>k . map ((#) k) (sorted_list_of_sequences_in_tree (the (m k)))) (sorted_list_of_set (dom m))))\"\n  by pat_completeness auto\ntermination \nproof -\n  {\n    fix a :: \"'a prefix_tree\"   \n  \n    have \"sorted_list_of_sequences_in_tree_dom a\" \n    proof (induction a)\n      case (PT m)\n      then show ?case\n        by (metis List.set_empty domIff emptyE option.set_sel rangeI sorted_list_of_sequences_in_tree.domintros sorted_list_of_set.fold_insort_key.infinite sorted_list_of_set.set_sorted_key_list_of_set)\n    qed\n  }\n  then show ?thesis by auto\nqed\n\nlemma sorted_list_of_sequences_in_tree_set :\n  assumes \"finite_tree t\"\n  shows \"list.set (sorted_list_of_sequences_in_tree t) = set t\"\n    (is \"?S1 = ?S2\")\nproof \n  show \"?S1 \\<subseteq> ?S2\"\n  proof \n    fix xs assume \"xs \\<in> ?S1\"\n    then show \"xs \\<in> ?S2\"\n    proof (induction xs arbitrary: t)\n      case Nil\n      then show ?case \n        using set_empty by auto\n    next\n      case (Cons x xs)\n\n      obtain m where \"t = PT m\"\n        using prefix_tree.exhaust by blast\n      have \"x#xs \\<in> list.set (concat (map (\\<lambda>k . map ((#) k) (sorted_list_of_sequences_in_tree (the (m k)))) (sorted_list_of_set (dom m))))\"\n        by (metis (no_types) Cons.prems(1) \\<open>t = PT m\\<close> empty_iff list.set(1) list.simps(3) set_ConsD sorted_list_of_sequences_in_tree.simps)\n      then have \"x \\<in> list.set (sorted_list_of_set (dom m))\"\n            and \"xs \\<in> list.set (sorted_list_of_sequences_in_tree (the (m x)))\"\n        by auto\n\n      have \"x \\<in> dom m\"\n        using \\<open>x \\<in> list.set (sorted_list_of_set (dom m))\\<close> unfolding \\<open>t = PT m\\<close>\n        by (metis emptyE empty_set sorted_list_of_set.fold_insort_key.infinite sorted_list_of_set.set_sorted_key_list_of_set)\n      then obtain t' where \"m x = Some t'\"\n        by auto\n      then have \"xs \\<in> list.set (sorted_list_of_sequences_in_tree t')\"\n        using \\<open>xs \\<in> list.set (sorted_list_of_sequences_in_tree (the (m x)))\\<close> \n        by auto\n      then have \"xs \\<in> set t'\" \n        using Cons.IH by blast+\n\n      show \"x#xs \\<in> set t\"\n        unfolding \\<open>t = PT m\\<close> using \\<open>xs \\<in> set t'\\<close> \\<open>m x = Some t'\\<close> by auto\n    qed\n  qed\n\n  show \"?S2 \\<subseteq> ?S1\"\n  proof \n    fix xs assume \"xs \\<in> ?S2\"\n    then show \"xs \\<in> ?S1\"\n    using assms proof (induction xs arbitrary: t)\n      case Nil\n      obtain m where \"t = PT m\"\n        using prefix_tree.exhaust by blast\n      then show ?case \n        by auto\n    next\n      case (Cons x xs)\n\n      obtain m where \"t = PT m\"\n        using prefix_tree.exhaust by blast\n      then have \"isin (PT m) (x#xs)\"\n        using Cons.prems(1) by auto\n      then obtain t' where \"m x = Some t'\"\n                       and \"isin t' xs\"\n        by (metis case_optionE isin.simps(2))\n      then have \"x \\<in> dom m\"\n        by auto\n      then have \"dom m \\<noteq> {}\"\n        by auto\n\n      have \"finite_tree t'\"\n        using \\<open>finite_tree t\\<close> \\<open>m x = Some t'\\<close> unfolding \\<open>t = PT m\\<close>\n        by (meson finite_tree.simps ranI) \n      moreover have \"xs \\<in> set t'\"\n        using \\<open>isin t' xs\\<close> by auto\n      ultimately have \"xs \\<in> list.set (sorted_list_of_sequences_in_tree t')\"\n        using Cons.IH by blast\n      moreover have \"x \\<in> list.set (sorted_list_of_set (dom m))\"\n        using \\<open>x \\<in> dom m\\<close> \\<open>finite_tree t\\<close> unfolding \\<open>t = PT m\\<close>\n        by simp\n      ultimately show ?case\n        using \\<open>finite_tree t\\<close> \\<open>dom m \\<noteq> {}\\<close> \\<open>m x = Some t'\\<close> unfolding \\<open>t = PT m\\<close> \n        by force\n    qed\n  qed\nqed\n\n\n\n\n\nfun difference_list :: \"('a::linorder) prefix_tree \\<Rightarrow> 'a prefix_tree \\<Rightarrow> 'a list list\" where\n  \"difference_list t1 t2 = filter (\\<lambda> xs . \\<not> isin t2 xs) (sorted_list_of_sequences_in_tree t1)\"\n\nlemma difference_list_set :\n  assumes \"finite_tree t1\"\nshows \"List.set (difference_list t1 t2) = (set t1 - set t2)\"\n  unfolding difference_list.simps \n            filter_set[symmetric]\n            sorted_list_of_sequences_in_tree_set[OF assms]\n            set.simps\n  by fastforce\n\nfun is_leaf :: \"'a prefix_tree \\<Rightarrow> bool\" where\n  \"is_leaf t = (t = empty)\"\n\nfun is_maximal_in :: \"'a prefix_tree \\<Rightarrow> 'a list \\<Rightarrow> bool\" where\n  \"is_maximal_in T \\<alpha> = (isin T \\<alpha> \\<and> is_leaf (after T \\<alpha>))\"\n\nfunction (domintros) height :: \"'a prefix_tree \\<Rightarrow> nat\" where\n  \"height (PT m) = (if (is_leaf (PT m)) then 0 else 1 + Max (height ` ran m))\"\n  by pat_completeness auto\ntermination \nproof -\n  { fix a :: \"'a prefix_tree\"   \n\n    have \"height_dom a\" \n    proof (induction a)\n      case (PT m)\n  \n      have \"(\\<And>x. x \\<in> ran m \\<Longrightarrow> height_dom x)\"\n      proof -\n        fix x :: \"'a prefix_tree\"\n        assume \"x \\<in> ran m\"\n        then have \"\\<exists>a. m a = Some x\"\n          by (simp add: ran_def)\n        then show \"height_dom x\"\n          using PT.IH by blast\n      qed  \n      then show ?case\n        using height.domintros\n        by blast \n    qed\n  }\n  then show ?thesis by auto\nqed\n\nfunction (domintros) height_over :: \"'a list \\<Rightarrow> 'a prefix_tree \\<Rightarrow> nat\" where\n  \"height_over xs (PT m) = 1 + foldr (\\<lambda> x maxH . case m x of Some t' \\<Rightarrow> max (height_over xs t') maxH | None \\<Rightarrow> maxH) xs 0\"\n  by pat_completeness auto\ntermination \nproof -\n  {\n    fix a :: \"'a prefix_tree\"   \n    fix xs :: \"'a list\"\n  \n    have \"height_over_dom (xs, a)\" \n    proof (induction a)\n      case (PT m)\n  \n      have \"(\\<And>x. x \\<in> ran m \\<Longrightarrow> height_over_dom (xs, x))\"\n      proof -\n        fix x :: \"'a prefix_tree\"\n        assume \"x \\<in> ran m\"\n        then have \"\\<exists>a. m a = Some x\"\n          by (simp add: ran_def)\n        then show \"height_over_dom (xs, x)\"\n          using PT.IH by blast\n      qed  \n      then show ?case\n        using height_over.domintros\n        by (simp add: height_over.domintros ranI)\n    qed\n  }\n  then show ?thesis by auto\nqed\n\nlemma height_over_empty :\n  \"height_over xs empty = 1\"\nproof -\n  define xs' where \"xs' = xs\"\n  have \"foldr (\\<lambda> x maxH . case Map.empty x of Some t' \\<Rightarrow> max (height_over xs' t') maxH | None \\<Rightarrow> maxH) xs 0 = 0\"\n    by (induction xs; auto)\n  then show ?thesis\n    unfolding xs'_def empty_def \n    by auto\nqed\n\n\nlemma height_over_subtree_less :\n  assumes \"m x = Some t'\"\n  and     \"x \\<in> list.set xs\"\nshows \"height_over xs t' < height_over xs (PT m)\"\nproof -\n\n  define xs' where \"xs' = xs\"\n\n  have \"height_over xs' t' \\<le> foldr (\\<lambda> x maxH . case m x of Some t' \\<Rightarrow> max (height_over xs' t') maxH | None \\<Rightarrow> maxH) xs 0\"\n    using assms(2) proof (induction xs)\n    case Nil\n    then show ?case by auto\n  next\n    case (Cons x' xs)\n\n    define f where \"f = foldr (\\<lambda> x maxH . case m x of Some t' \\<Rightarrow> max (height_over xs' t') maxH | None \\<Rightarrow> maxH) xs 0\"\n\n    have *: \"foldr (\\<lambda> x maxH . case m x of Some t' \\<Rightarrow> max (height_over xs' t') maxH | None \\<Rightarrow> maxH) (x'#xs) 0\n              = (case m x' of Some t' \\<Rightarrow> max (height_over xs' t') f | None \\<Rightarrow> f)\"\n      unfolding f_def by auto\n\n    show ?case proof (cases \"x=x'\")\n      case True\n      show ?thesis \n        using \\<open>m x = Some t'\\<close>\n        unfolding * True by auto\n    next\n      case False\n      then have \"x \\<in> list.set xs\"\n        using Cons.prems(1) by auto\n      show ?thesis\n        using Cons.IH[OF \\<open>x \\<in> list.set xs\\<close>]\n        unfolding * f_def[symmetric] \n        by (cases \"m x'\"; auto)\n    qed\n  qed\n  then show ?thesis\n    unfolding xs'_def by auto\nqed\n\n\nfun maximum_prefix :: \"'a prefix_tree \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where\n  \"maximum_prefix t [] = []\" |\n  \"maximum_prefix (PT m) (x # xs) = (case m x of None \\<Rightarrow> [] | Some t \\<Rightarrow> x # maximum_prefix t xs)\"\n\nlemma maximum_prefix_isin :\n  \"isin t (maximum_prefix t xs)\"\nproof (induction xs arbitrary: t)\n  case Nil\n  show ?case \n    by auto\nnext\n  case (Cons x xs)\n\n  obtain m where *:\"t = PT m\"\n    using finite_tree.cases by blast\n\n  show ?case proof (cases \"m x\")\n    case None\n    then have \"maximum_prefix t (x#xs) = []\"\n      unfolding * by auto\n    then show ?thesis \n      by auto\n  next\n    case (Some t')\n    then have \"maximum_prefix t (x#xs) = x # maximum_prefix t' xs\"\n      unfolding * by auto\n    moreover have \"isin t' (maximum_prefix t' xs)\"\n      using Cons.IH by auto\n    ultimately show ?thesis\n      by (simp add: \"*\" Some)\n  qed\nqed\n\n\nlemma maximum_prefix_maximal :\n  \"maximum_prefix t xs = xs \n    \\<or> (\\<exists> x' xs' . xs = (maximum_prefix t xs)@[x']@xs' \\<and> \\<not> isin t ((maximum_prefix t xs)@[x']))\"\nproof (induction xs arbitrary: t)\n  case Nil\n  show ?case by auto\nnext\n  case (Cons x xs)\n  obtain m where *:\"t = PT m\"\n    using finite_tree.cases by blast\n\n  show ?case proof (cases \"m x\")\n    case None\n    then have \"maximum_prefix t (x#xs) = []\"\n      unfolding * by auto\n    moreover have \"\\<not> isin t ([]@[x]@xs)\"\n      using isin_prefix[of t \"[x]\" xs]\n      by (simp add: \"*\" None)\n    ultimately show ?thesis\n      by (simp add: \"*\" None)\n  next\n    case (Some t')\n    then have \"maximum_prefix t (x#xs) = x # maximum_prefix t' xs\"\n      unfolding * by auto\n    moreover note Cons.IH[of t']\n    ultimately show ?thesis\n      by (simp add: \"*\" Some) \n  qed\nqed\n\n\n\n\n\n(* collects for sequence xs all sequences ys in the tree such that ys is maximal in the tree and \n   (map fst ys) is a prefix of (map fst xs) *)\nfun maximum_fst_prefixes :: \"('a\\<times>'b) prefix_tree \\<Rightarrow> 'a list \\<Rightarrow> 'b list \\<Rightarrow> ('a\\<times>'b) list list\" where\n  \"maximum_fst_prefixes t [] ys = (if is_leaf t then [[]] else [])\" |\n  \"maximum_fst_prefixes (PT m) (x # xs) ys = (if is_leaf (PT m) then [[]] else concat (map (\\<lambda> y . map ((#) (x,y)) (maximum_fst_prefixes (the (m (x,y))) xs ys)) (filter (\\<lambda> y . (m (x,y) \\<noteq> None)) ys)))\"\n\nlemma maximum_fst_prefixes_set :\n  \"list.set (maximum_fst_prefixes t xs ys) \\<subseteq> set t\"\nproof (induction xs arbitrary: t)\n  case Nil\n  show ?case \n    by auto\nnext\n  case (Cons x xs)\n\n  obtain m where *:\"t = PT m\"\n    using finite_tree.cases by blast\n\n  show \"list.set (maximum_fst_prefixes t (x # xs) ys) \\<subseteq> set t\"\n  proof \n    fix p assume \"p \\<in> list.set (maximum_fst_prefixes t (x # xs) ys)\"\n\n    show \"p \\<in> set t\" proof (cases \"is_leaf (PT m)\")\n      case True\n      then have \"p = []\"\n        using \\<open>p \\<in> list.set (maximum_fst_prefixes t (x # xs) ys)\\<close>  unfolding * maximum_fst_prefixes.simps by force\n      then show ?thesis \n        using set_Nil[of t] \n        by blast\n    next\n      case False\n      then obtain y where \"y \\<in> list.set (filter (\\<lambda> y . (m (x,y) \\<noteq> None)) ys)\"\n                    and \"p \\<in> list.set (map ((#) (x,y)) (maximum_fst_prefixes (the (m (x,y))) xs ys))\"\n        using \\<open>p \\<in> list.set (maximum_fst_prefixes t (x # xs) ys)\\<close>\n        unfolding * by auto\n\n      then have \"m (x,y) \\<noteq> None\"\n        by auto\n      then obtain t' where \"m (x,y) = Some t'\"\n        by auto\n      moreover obtain p' where \"p = (x,y)#p'\" and \"p' \\<in> list.set (maximum_fst_prefixes (the (m (x,y))) xs ys)\"\n        using \\<open>p \\<in> list.set (map ((#) (x,y)) (maximum_fst_prefixes (the (m (x,y))) xs ys))\\<close>\n        by auto\n      ultimately have \"isin t' p'\"\n        using Cons.IH\n        by auto \n      then have \"isin t p\"\n        unfolding * \\<open>p = (x,y)#p'\\<close> using \\<open>m (x,y) = Some t'\\<close> by auto\n      then show \"p \\<in> set t\"\n        by auto\n    qed\n  qed\nqed\n\nlemma maximum_fst_prefixes_are_prefixes :\n  assumes \"xys \\<in> list.set (maximum_fst_prefixes t xs ys)\"\n  shows \"map fst xys = take (length xys) xs\"\nusing assms proof (induction xys arbitrary: t xs)\n  case Nil\n  then show ?case by auto\nnext\n  case (Cons xy xys)\n  then have \"xs \\<noteq> []\"\n    by auto\n  then obtain x xs' where \"xs = x#xs'\"\n    using list.exhaust by auto\n    \n  obtain m where *:\"t = PT m\"\n    using finite_tree.cases by blast\n  have \"is_leaf (PT m) = False\"\n    using Cons.prems unfolding * \\<open>xs = x#xs'\\<close>\n    by auto\n  have \"(xy#xys) \\<in> list.set (concat (map (\\<lambda> y . map ((#) (x,y)) (maximum_fst_prefixes (the (m (x,y))) xs' ys)) (filter (\\<lambda> y . (m (x,y) \\<noteq> None)) ys)))\"\n    using Cons.prems unfolding * \\<open>xs = x#xs'\\<close> \\<open>is_leaf (PT m) = False\\<close> maximum_fst_prefixes.simps by auto\n  then obtain y where \"y \\<in> list.set (filter (\\<lambda> y . (m (x,y) \\<noteq> None)) ys)\"\n                  and \"(xy#xys) \\<in> list.set (map ((#) (x,y)) (maximum_fst_prefixes (the (m (x,y))) xs' ys))\"\n    by auto\n  then have \"xy = (x,y)\" and \"xys \\<in> list.set (maximum_fst_prefixes (the (m (x,y))) xs' ys)\"\n    by auto\n\n  have **: \"take (length ((x, y) # xys)) (x # xs') = x # (take (length xys) xs')\"\n    by auto\n\n  show ?case\n    using Cons.IH[OF \\<open>xys \\<in> list.set (maximum_fst_prefixes (the (m (x,y))) xs' ys)\\<close>]\n    unfolding \\<open>xy = (x,y)\\<close> \\<open>xs = x#xs'\\<close> ** by auto\nqed\n\n\n\nlemma finite_tree_set_eq : \n  assumes \"set t1 = set t2\"\n  and     \"finite_tree t1\"\n  shows \"t1 = t2\"\nusing assms proof (induction \"height t1\" arbitrary: t1 t2 rule: less_induct)\n  case less\n\n  obtain m1 m2 where \"t1 = PT m1\" and \"t2 = PT m2\"\n    by (metis finite_tree.cases) \n\n  show ?case proof (cases \"height t1\")\n    case 0\n    \n    have \"t1 = empty\"\n      using 0\n      unfolding \\<open>t1 = PT m1\\<close> height.simps is_leaf.simps\n      by (metis add_is_0 zero_neq_one) \n    then have \"set t2 = {[]}\"\n      using less Prefix_Tree.set_empty by auto \n    have \"m2 = Map.empty\" \n    proof \n      show \"\\<And>x. m2 x = None\"\n      proof -\n        fix x show \"m2 x = None\"\n        proof (rule ccontr) \n          assume \"m2 x \\<noteq> None\"\n          then obtain t' where \"m2 x = Some t'\"\n            by blast \n          then have \"[x] \\<in> set t2\" \n            unfolding \\<open>t2 = PT m2\\<close> set.simps by auto\n          then show False\n            using \\<open>set t2 = {[]}\\<close> by auto\n        qed\n      qed\n    qed\n    then show ?thesis \n      unfolding \\<open>t1 = empty\\<close> \\<open>t2 = PT m2\\<close> empty_def by simp\n  next\n    case (Suc k)\n\n    \n    show ?thesis proof (rule ccontr)\n      assume \"t1 \\<noteq> t2\"\n\n      then have \"m1 \\<noteq> m2\"\n        using \\<open>t1 = PT m1\\<close> \\<open>t2 = PT m2\\<close> by auto\n      then obtain x where \"m1 x \\<noteq> m2 x\"\n        by (meson ext)\n\n      then consider \"m1 x \\<noteq> None \\<and> m2 x \\<noteq> None\" | \"m1 x = None \\<longleftrightarrow> m2 x \\<noteq> None\"\n        by fastforce\n      then show False proof cases\n        case 1\n        then obtain t1' t2' where \"m1 x = Some t1'\" and \"m2 x = Some t2'\"\n          by auto\n        then have \"t1' \\<noteq> t2'\"\n          using \\<open>m1 x \\<noteq> m2 x\\<close> by auto\n        moreover have \"set t1' = set t2'\" \n        proof -\n          have \"\\<And> io . isin t1' io = isin t1 (x#io)\"\n            unfolding \\<open>t1 = PT m1\\<close> using \\<open>m1 x = Some t1'\\<close> by auto\n          moreover have \"\\<And> io . isin t2' io = isin t2 (x#io)\"\n            unfolding \\<open>t2 = PT m2\\<close> using \\<open>m2 x = Some t2'\\<close> by auto\n          ultimately show ?thesis\n            using less.prems(1)\n            by (metis Collect_cong mem_Collect_eq set.simps) \n        qed\n        moreover have \"height t1' < height t1\"\n        proof -\n          have \"height t1 = 1 + Max (height ` ran m1)\"\n            using Suc \n            unfolding \\<open>t1 = PT m1\\<close> height.simps \n            by (meson Zero_not_Suc) \n          moreover have \"height t1' \\<in> height ` ran m1\"\n            using \\<open>m1 x = Some t1'\\<close>\n            by (meson image_eqI ranI) \n          moreover have \"finite (ran m1)\"\n            using less.prems(2) \n            unfolding \\<open>t1 = PT m1\\<close> finite_tree.simps\n            by (simp add: finite_ran) \n          ultimately have \"height t1 \\<ge> 1 + height t1'\"\n            by simp\n          then show ?thesis by auto\n        qed\n        moreover have \"finite_tree t1'\"\n          using less.prems(2) \n          unfolding \\<open>t1 = PT m1\\<close> finite_tree.simps\n          by (meson \\<open>m1 x = Some t1'\\<close> ranI)  \n        ultimately show False \n          using less.hyps[of t1' t2']\n          by blast\n      next\n        case 2\n        then have \"isin t1 [x] \\<noteq> isin t2 [x]\"\n          unfolding \\<open>t1 = PT m1\\<close> \\<open>t2 = PT m2\\<close> by auto\n        then show False using less.prems(1) by auto\n      qed   \n    qed\n  qed\nqed\n\n\n\n\n(* obtain all trees after an input trace *)\nfun after_fst :: \"('a \\<times> 'b) prefix_tree \\<Rightarrow> 'a list \\<Rightarrow> 'b list \\<Rightarrow> ('a \\<times> 'b) prefix_tree\" where\n  \"after_fst t [] ys = t\" |\n  \"after_fst (PT m) (x # xs) ys = foldr (\\<lambda> y t . case m (x,y) of None \\<Rightarrow> t | Some t' \\<Rightarrow> combine t (after_fst t' xs ys)) ys empty\"\n\n\n\nsubsection \\<open>Alternative characterization for code generation\\<close>\n\ntext \\<open>In order to generate code for the prefix trees, we represent the map inside each prefix tree\n      by Mapping.\\<close>\n\ndefinition MPT :: \"('a,'a prefix_tree) mapping \\<Rightarrow> 'a prefix_tree\" where\n  \"MPT m = PT (Mapping.lookup m)\"\n\ncode_datatype MPT\n\nlemma equals_MPT[code]: \"equal_class.equal (MPT m1) (MPT m2) = (m1 = m2)\" \nproof -\n  have \"equal_class.equal (MPT m1) (MPT m2) = equal_class.equal (PT (Mapping.lookup m1)) (PT (Mapping.lookup m2))\"\n    unfolding MPT_def by simp\n  also have \"\\<dots> = ((Mapping.lookup m1) = (Mapping.lookup m2))\"\n    using prefix_tree.eq.simps by auto\n  also have \"\\<dots> = (m1 = m2)\"\n    by (simp add: Mapping.lookup.rep_eq rep_inject)\n  finally show ?thesis .\nqed\n\nlemma empty_MPT[code] :\n  \"empty = MPT Mapping.empty\"\n  unfolding MPT_def empty_def\n  by (metis lookup_empty) \n\nlemma insert_MPT[code] :\n  \"insert (MPT m) xs = (case xs of\n    [] \\<Rightarrow> (MPT m) |\n    (x#xs) \\<Rightarrow> MPT (Mapping.update x (insert (case Mapping.lookup m x of None \\<Rightarrow> empty | Some t' \\<Rightarrow> t') xs) m))\"\n  apply (cases xs; simp)\n  by (simp add: MPT_def lookup.rep_eq update.rep_eq)  \n\nlemma isin_MPT[code] :\n  \"isin (MPT m) xs = (case xs of\n    [] \\<Rightarrow> True |\n    (x#xs) \\<Rightarrow> (case Mapping.lookup m x of None \\<Rightarrow> False | Some t \\<Rightarrow> isin t xs))\"\n  unfolding MPT_def by (cases xs; auto)\n\nlemma after_MPT[code] :\n  \"after (MPT m) xs = (case xs of\n    [] \\<Rightarrow> MPT m |\n    (x#xs) \\<Rightarrow> (case Mapping.lookup m x of None \\<Rightarrow> empty | Some t \\<Rightarrow> after t xs))\"\n  unfolding MPT_def by (cases xs; auto)\n\nlemma PT_Mapping_ob : \n  fixes t :: \"'a prefix_tree\"\n  obtains m where \"t = MPT m\"\nproof -\n  obtain m' where \"t = PT m'\"\n    using prefix_tree.exhaust by blast \n  then have \"t = MPT (Mapping m')\" \n    unfolding MPT_def\n    by (simp add: Mapping_inverse lookup.rep_eq) \n  then show ?thesis using that by blast\nqed\n\n\nlemma set_MPT[code] :\n  \"set (MPT m) = Set.insert [] (\\<Union> x \\<in> Mapping.keys m . (Cons x) ` (set (the (Mapping.lookup m x))))\"\n  unfolding MPT_def set_alt_def keys_dom_lookup by simp\n\n\nlemma combine_MPT[code] : \n  \"combine (MPT m1) (MPT m2) = MPT (Mapping.combine combine m1 m2)\"  \nproof -\n  have \"combine (MPT m1) (MPT m2) = combine (PT (Mapping.lookup m1)) (PT (Mapping.lookup m2))\"\n    unfolding MPT_def by simp\n  also have \"\\<dots> = PT (\\<lambda>x . combine_options combine ((Mapping.lookup m1) x) ((Mapping.lookup m2) x))\"\n    unfolding combine.simps\n    by (simp add: combine_options_def)\n  ultimately show ?thesis\n    by (metis MPT_def combine.abs_eq lookup.abs_eq rep_inverse) \nqed\n\n\nlemma combine_after_MPT[code] :\n  \"combine_after (MPT m) xs t = (case xs of\n    [] \\<Rightarrow> combine (MPT m) t |\n    (x#xs) \\<Rightarrow> MPT (Mapping.update x (combine_after (case Mapping.lookup m x of None \\<Rightarrow> empty | Some t' \\<Rightarrow> t') xs t) m))\"\n  apply (cases xs; simp)\n  by (simp add: MPT_def lookup.rep_eq update.rep_eq)  \n\n\nlemma finite_tree_MPT[code] :\n  \"finite_tree (MPT m) = (finite (Mapping.keys m) \\<and> (\\<forall> x \\<in> Mapping.keys m . finite_tree (the (Mapping.lookup m x))))\"\n  unfolding MPT_def finite_tree.simps keys_dom_lookup ran_dom_the_eq[symmetric] by blast\n\n\nlemma sorted_list_of_maximal_sequences_in_tree_MPT[code] :\n  \"sorted_list_of_maximal_sequences_in_tree (MPT m) = \n    (if Mapping.keys m = {}\n      then [[]]\n      else concat (map (\\<lambda>k . map ((#) k) (sorted_list_of_maximal_sequences_in_tree (the (Mapping.lookup m k)))) (sorted_list_of_set (Mapping.keys m))))\"\n  unfolding MPT_def sorted_list_of_maximal_sequences_in_tree.simps keys_dom_lookup by simp\n\nlemma is_leaf_MPT[code]:\n  \"is_leaf (MPT m) = (Mapping.is_empty m)\"\n  by (simp add: MPT_def Mapping.is_empty_def Prefix_Tree.empty_def keys_dom_lookup)\n\nlemma height_MPT[code] :\n  \"height (MPT m) = (if (is_leaf (MPT m)) then 0 else 1 + Max ((height \\<circ> the \\<circ> Mapping.lookup m) ` Mapping.keys m))\"\nproof -\n  have \"height (MPT m) = (if (is_leaf (MPT m)) then 0 else 1 + Max (height ` ((\\<lambda>k . the (Mapping.lookup m k)) ` Mapping.keys m)))\"\n    by (simp add: MPT_def keys_dom_lookup ran_dom_the_eq)\n  moreover have \"(height ` ((\\<lambda>k . the (Mapping.lookup m k)) ` Mapping.keys m)) = ((height \\<circ> the \\<circ> Mapping.lookup m) ` Mapping.keys m)\"\n    by auto\n  ultimately show ?thesis \n    by auto\nqed\n\n\nlemma maximum_prefix_MPT[code]:\n  \"maximum_prefix (MPT m) xs = (case xs of\n    [] \\<Rightarrow> [] |\n    (x#xs) \\<Rightarrow> (case Mapping.lookup m x of None \\<Rightarrow> [] | Some t \\<Rightarrow> x # maximum_prefix t xs))\"\n  apply (cases xs; simp)\n  by (simp add: MPT_def lookup.rep_eq)  \n\nlemma sorted_list_of_in_tree_MPT[code] :\n  \"sorted_list_of_sequences_in_tree (MPT m) = \n    (if Mapping.keys m = {}\n      then [[]]\n      else [] # concat (map (\\<lambda>k . map ((#) k) (sorted_list_of_sequences_in_tree (the (Mapping.lookup m k)))) (sorted_list_of_set (Mapping.keys m))))\"\n  unfolding MPT_def sorted_list_of_sequences_in_tree.simps keys_dom_lookup by simp\n\nlemma maximum_fst_prefixes_leaf: \n  fixes xs :: \"'a list\" and ys :: \"'b list\"\nshows \"maximum_fst_prefixes empty xs ys  = [[]]\"\nproof -\n  have \"is_leaf (empty :: ('a\\<times>'b)prefix_tree)\" by auto\n  \n  obtain m where \"(empty :: ('a\\<times>'b)prefix_tree) = PT m\"\n    using prefix_tree.exhaust by blast \n\n  show ?thesis proof (cases xs)\n    case Nil\n    then show ?thesis by auto\n  next\n    case (Cons x xs)\n    show ?thesis \n      using \\<open>is_leaf (empty :: ('a\\<times>'b)prefix_tree) \\<close>\n      unfolding \\<open>(empty :: ('a\\<times>'b)prefix_tree) = PT m\\<close>  Cons maximum_fst_prefixes.simps by force\n  qed\nqed\n\nlemma maximum_fst_prefixes_MPT[code]:\n  \"maximum_fst_prefixes (MPT m) xs ys = (case xs of\n    [] \\<Rightarrow> (if is_leaf (MPT m) then [[]] else []) |\n    (x # xs) \\<Rightarrow> (if is_leaf (MPT m) then [[]] else concat (map (\\<lambda> y . map ((#) (x,y)) (maximum_fst_prefixes (the (Mapping.lookup m (x,y))) xs ys)) (filter (\\<lambda> y . (Mapping.lookup m (x,y) \\<noteq> None)) ys))))\"\n  using maximum_fst_prefixes_leaf\n  apply (cases xs) \n    apply auto[1]\n  by (simp add: MPT_def lookup.rep_eq)  \n\n\n\n\n\n\n\n\n\n(* The following function computes the maximum prefix xs' of xs such that there exists\n   a sequence ys in the tree with (map fst xs' = map fst ys).\n   Requires theory Polynomials.OAlist.\n   \nfun maximum_fst_prefix :: \"('a\\<times>'b) prefix_tree \\<Rightarrow> 'a list \\<Rightarrow> 'b list \\<Rightarrow> ('a\\<times>'b) list\" where\n  \"maximum_fst_prefix t [] ys = []\" |\n  \"maximum_fst_prefix (PT m) (x # xs) ys = \n    (case (map (\\<lambda> y . (x,y) # maximum_fst_prefix (the (m (x,y))) xs ys) (filter (\\<lambda> y . (m (x,y) \\<noteq> None)) ys)) of\n      [] \\<Rightarrow> [] |\n      (p'#ps) \\<Rightarrow> min_list_param (\\<lambda> a b . length a > length b) (p'#ps))\"\n\nlemma maximum_fst_prefix_isin :\n  \"isin t (maximum_fst_prefix t xs ys)\"\nproof (induction xs arbitrary: t)\n  case Nil\n  show ?case \n    by auto\nnext\n  case (Cons x xs)\n\n  obtain m where *:\"t = PT m\"\n    using finite_tree.cases by blast\n\n  show ?case proof (cases \"(map (\\<lambda> y . (x,y) # maximum_fst_prefix (the (m (x,y))) xs ys) (filter (\\<lambda> y . (m (x,y) \\<noteq> None)) ys))\")\n    case Nil\n    then show ?thesis  unfolding * by auto\n  next\n    case (Cons p' ps)\n\n    then have \"maximum_fst_prefix t (x # xs) ys = min_list_param (\\<lambda> a b . length a > length b) (p'#ps)\"\n      unfolding * by auto\n    then have \"maximum_fst_prefix t (x # xs) ys \\<in> list.set (p'#ps)\"\n      by (metis list.simps(3) min_list_param_in)\n    then have \"maximum_fst_prefix t (x # xs) ys \\<in> list.set (map (\\<lambda> y . (x,y) # maximum_fst_prefix (the (m (x,y))) xs ys) (filter (\\<lambda> y . (m (x,y) \\<noteq> None)) ys))\"\n      unfolding Cons .\n    then obtain y where \"y \\<in> list.set (filter (\\<lambda> y . (m (x,y) \\<noteq> None)) ys)\"\n                    and \"maximum_fst_prefix t (x # xs) ys = (x,y) # maximum_fst_prefix (the (m (x,y))) xs ys\"\n      by auto\n    then have \"m (x,y) \\<noteq> None\"\n      by auto\n    then obtain t' where \"m (x,y) = Some t'\"\n      by auto\n    then have \"maximum_fst_prefix t (x # xs) ys = (x,y) # maximum_fst_prefix t' xs ys\"\n      using \\<open>maximum_fst_prefix t (x # xs) ys = (x,y) # maximum_fst_prefix (the (m (x,y))) xs ys\\<close>\n      by auto\n    \n    have \"isin t' (maximum_fst_prefix t' xs ys)\"\n      using Cons.IH by blast\n    then show ?thesis\n      using \\<open>m (x,y) = Some t'\\<close>\n      unfolding \\<open>maximum_fst_prefix t (x # xs) ys = (x,y) # maximum_fst_prefix t' xs ys\\<close>\n      unfolding *\n      by auto\n  qed\nqed\n\nlemma maximum_fst_prefix_MPT[code]:\n  \"maximum_fst_prefix (MPT m) xs ys = (case xs of\n    [] \\<Rightarrow> [] |\n    (x#xs) \\<Rightarrow> (case (map (\\<lambda> y . (x,y) # maximum_fst_prefix (the (Mapping.lookup m (x,y))) xs ys) (filter (\\<lambda> y . (Mapping.lookup m (x,y) \\<noteq> None)) ys)) of\n      [] \\<Rightarrow> [] |\n      (p'#ps) \\<Rightarrow> min_list_param (\\<lambda> a b . length a > length b) (p'#ps)))\"\n  apply (cases xs; auto)\n  by (simp add: MPT_def lookup.rep_eq)  \n*)\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/FSM_Tests/Prefix_Tree.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8499711832583696, "lm_q2_score": 0.845942439250491, "lm_q1q2_score": 0.7190266960582112}}
{"text": "header {* \\subsection{Theorems on lists} *}\n\ntheory List_Theorems\n  imports List \nbegin\n\n(* Returns the last n elements of list x *)\ndefinition lastn :: \"nat \\<Rightarrow> 'a list \\<Rightarrow> 'a list\"\nwhere \"lastn n x = drop ((length x) - n) x\"\n(* Returns true iff [a,b] is a sequence in list x. *)\ndefinition is_sub_seq :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a list \\<Rightarrow> bool\"\nwhere \"is_sub_seq a b x \\<equiv> \\<exists> n . Suc n < length x \\<and> x!n = a \\<and> x!(Suc n) = b\"\n(* Return, given a set of lists, the set with all prefixes of all the lists *)\ndefinition prefixes :: \"'a list set \\<Rightarrow> 'a list set\"\nwhere \"prefixes s \\<equiv> {x . \\<exists> n y . n > 0 \\<and> y \\<in> s \\<and> take n y = x}\"\n\nlemma drop_one[simp]:\n  shows \"drop (Suc 0) x = tl x\" by(induct x,auto)\nlemma length_ge_one:\n  shows \"x \\<noteq> [] \\<longrightarrow> length x \\<ge> 1\" by(induct x,auto)\nlemma take_but_one[simp]:\n  shows \"x \\<noteq> [] \\<longrightarrow> lastn ((length x) - 1) x = tl x\" unfolding lastn_def\n  using length_ge_one[where x=x] by auto\nlemma Suc_m_minus_n[simp]:\n  shows \"m \\<ge> n \\<longrightarrow> Suc m - n = Suc (m - n)\" by auto\nlemma lastn_one_less:\n shows \"n > 0 \\<and> n \\<le> length x \\<and> lastn n x = (a#y) \\<longrightarrow> lastn (n - 1) x = y\" unfolding lastn_def\n using drop_Suc[where n=\"length x - n\" and xs=x] drop_tl[where n=\"length x - n\" and xs=x]\n by(auto)\nlemma list_sub_implies_member:\n  shows \"\\<forall> a x . set (a#x) \\<subseteq> Z \\<longrightarrow> a \\<in> Z\" by auto\nlemma subset_smaller_list:\n  shows \"\\<forall> a x . set (a#x) \\<subseteq> Z \\<longrightarrow> set x \\<subseteq> Z\" by auto\nlemma second_elt_is_hd_tl: \n  shows \"tl x = (a # x') \\<longrightarrow> a = x ! 1\" \n  by (cases x,auto)\nlemma length_ge_2_implies_tl_not_empty:\n  shows \"length x \\<ge> 2 \\<longrightarrow> tl x \\<noteq> []\"\n  by (cases x,auto)\nlemma length_lt_2_implies_tl_empty:\n  shows \"length x < 2 \\<longrightarrow> tl x = []\"\n  by (cases x,auto)  \nlemma first_second_is_sub_seq:\n  shows \"length x \\<ge> 2 \\<Longrightarrow> is_sub_seq (hd x) (x!1) x\"\nproof-\n  assume \"length x \\<ge> 2\"\n  hence 1: \"(Suc 0) < length x\" by auto\n  hence \"x!0 = hd x\" by(cases x,auto)\n  from this 1 show \"is_sub_seq (hd x) (x!1) x\" unfolding is_sub_seq_def by auto\nqed\nlemma hd_drop_is_nth:\n  shows \"n < length x \\<Longrightarrow> hd (drop n x) = x!n\"\nproof(induct x arbitrary: n)\ncase Nil\n  thus ?case by simp\nnext\ncase (Cons a x)\n{\n  have \"hd (drop n (a # x)) = (a # x) ! n\"\n  proof(cases n)\n  case 0\n    thus ?thesis by simp\n  next\n  case (Suc m)\n    from Suc Cons show ?thesis by auto\n  qed\n}\nthus ?case by auto\nqed\n\nlemma def_of_hd:\n  shows \"y = a # x \\<longrightarrow> hd y = a\" by simp\nlemma def_of_tl:\n  shows \"y = a # x \\<longrightarrow> tl y = x\" by simp  \nlemma drop_yields_results_implies_nbound:\n  shows \"drop n x \\<noteq> [] \\<longrightarrow> n < length x\"\nby(induct x,auto)\nlemma hd_take[simp]:\n  shows \"n > 0 \\<Longrightarrow> hd (take n x) = hd x\"\nby(cases x,simp,cases n, auto)\nlemma consecutive_is_sub_seq:\n  shows \"a # (b # x) = lastn n y \\<Longrightarrow> is_sub_seq a b y\"\nproof-\n  assume 1: \"a # (b # x) = lastn n y\"\n  from 1 drop_Suc[where n=\"(length y) - n\" and xs=\"y\"]\n       drop_tl[where n=\"(length y) - n\" and xs=\"y\"] \n       def_of_tl[where y=\"lastn n y\" and a=a and x =\"b#x\"]\n       drop_yields_results_implies_nbound[where n=\"Suc (length y - n)\" and x=y]\n    have 3: \"Suc (length y - n) < length y\" unfolding lastn_def by auto\n  from 3 1 hd_drop_is_nth[where n=\"(length y) - n\" and x=y] def_of_hd[where y=\"drop (length y - n) y\" and x=\"b#x\" and a=a]\n    have 4: \"y!(length y - n) = a\"  unfolding lastn_def by auto\n  from 3 1 hd_drop_is_nth[where n=\"Suc ((length y) - n)\" and x=y] def_of_hd[where y=\"drop (Suc (length y - n)) y\" and x=\"x\" and a=b]\n       drop_Suc[where n=\"(length y) - n\" and xs=\"y\"]\n       drop_tl[where n=\"(length y) - n\" and xs=\"y\"] \n       def_of_tl[where y=\"lastn n y\" and a=a and x =\"b#x\"]\n    have 5: \"y!Suc (length y - n) = b\" unfolding lastn_def by auto\n  from 3 4 5 show ?thesis\n    unfolding is_sub_seq_def by auto\nqed\n\n\nlemma sub_seq_in_prefixes:\n  assumes \"\\<exists>y \\<in> prefixes X. is_sub_seq a a' y\"\n  shows \"\\<exists>y \\<in> X. is_sub_seq a a' y\"\nproof-\n  from assms obtain y where y: \"y \\<in> prefixes X \\<and> is_sub_seq a a' y\" by auto\n  then obtain n x where x: \"n > 0 \\<and> x \\<in> X \\<and> take n x = y\"\n    unfolding prefixes_def by auto\n  from y obtain i where sub_seq_index: \"Suc i < length y \\<and> y ! i = a \\<and> y ! Suc i = a'\"\n    unfolding is_sub_seq_def by auto\n  from sub_seq_index x have \"is_sub_seq a a' x\"\n    unfolding is_sub_seq_def using nth_take by auto \n  from this x show ?thesis by metis\nqed\n\nlemma set_tl_is_subset:\nshows \"set (tl x) \\<subseteq> set x\" by(induct x,auto)\nlemma x_is_hd_snd_tl:\nshows \"length x \\<ge> 2 \\<longrightarrow> x = (hd x) # x!1 # tl(tl x)\"\nproof(induct x)\ncase Nil\n  show ?case by auto\ncase (Cons a xs)\n  show ?case by(induct xs,auto)\nqed\n\nlemma tl_x_not_x:\nshows \"x \\<noteq> [] \\<longrightarrow> tl x \\<noteq> x\" by(induct x,auto)\nlemma tl_hd_x_not_tl_x:\nshows \"x \\<noteq> [] \\<and> hd x \\<noteq> [] \\<longrightarrow> tl (hd x) # tl x \\<noteq> x\" using tl_x_not_x by(induct x,simp,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/CISC-Kernel/trace/Rushby-with-Control/List_Theorems.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711794579723, "lm_q2_score": 0.8459424353665382, "lm_q1q2_score": 0.719026689542046}}
{"text": "header {* Auxiliary Lemmas *}\ntheory ODE_Auxiliarities\nimports\n  \"~~/src/HOL/Multivariate_Analysis/Multivariate_Analysis\"\n  \"~~/src/HOL/Library/Float\"\nbegin\n\nsubsection {* Reals *}\n\nlemma image_mult_atLeastAtMost:\n  \"(\\<lambda>x. x * c::real) ` {x..y} = (if x \\<le> y then if c > 0 then {x * c .. y * c} else {y * c .. x * c} else {})\"\n  apply (cases \"c = 0\")\n   apply force\n  apply (auto simp: field_simps not_less intro!: image_eqI[where x=\"inverse c * xa\" for xa])\n  done\n\nlemma image_add_atLeastAtMost:\n  \"op + c ` {x..y::real} = {c + x .. c + y}\"\n  by (auto intro: image_eqI[where x=\"xa - c\" for xa])\n\nlemma linear_compose: \"(\\<lambda>xa. a + xa * b) = (\\<lambda>x. a + x) o (\\<lambda>x. x * b)\"\n  by auto\n\nlemma image_linear_atLeastAtMost: \"(\\<lambda>xa. a + xa * b) ` {c..d::real} =\n  (if c \\<le> d then if b > 0 then {a + c * b .. a + d * b} else {a + d * b .. a + c * b} else {})\"\n  by (simp add: linear_compose image_comp [symmetric] image_mult_atLeastAtMost image_add_atLeastAtMost)\n\nlemma min_zero_mult_nonneg_le: \"0 \\<le> h' \\<Longrightarrow> h' \\<le> h \\<Longrightarrow> min 0 (h * k::real) \\<le> h' * k\"\n  by (metis dual_order.antisym le_cases min_le_iff_disj mult_eq_0_iff mult_le_0_iff mult_right_mono_neg)\n\nlemma max_zero_mult_nonneg_le: \"0 \\<le> h' \\<Longrightarrow> h' \\<le> h \\<Longrightarrow> h' * k \\<le> max 0 (h * k::real)\"\n  by (metis dual_order.antisym le_cases le_max_iff_disj mult_eq_0_iff mult_right_mono zero_le_mult_iff)\n\nsubsection {* Vector Spaces *}\n\nlemma scaleR_dist_distrib_left:\n  fixes b c::\"'a::real_normed_vector\"\n  shows \"abs a * dist b c = dist (scaleR a b) (scaleR a c)\"\n  unfolding dist_norm scaleR_diff_right[symmetric] norm_scaleR ..\n\nlemma ex_norm_eq_1: \"\\<exists>x. norm (x::'a::euclidean_space) = 1\"\n  by (metis vector_choose_size zero_le_one)\n\nsubsection {* Euclidean Components *}\n\nlemma sqrt_le_rsquare:\n  assumes \"\\<bar>x\\<bar> \\<le> sqrt y\"\n  shows \"x\\<^sup>2 \\<le> y\"\n  using assms real_sqrt_le_iff[of \"x\\<^sup>2\"] by simp\n\nlemma setsum_ge_element:\n  fixes f::\"'a \\<Rightarrow> ('b::ordered_comm_monoid_add)\"\n  assumes \"finite s\"\n  assumes \"i \\<in> s\"\n  assumes \"\\<And>i. i \\<in> s \\<Longrightarrow> f i \\<ge> 0\"\n  assumes \"el = f i\"\n  shows \"el \\<le> setsum f s\"\nproof -\n  have \"el = setsum f {i}\" by (simp add: assms)\n  also have \"... \\<le> setsum f s\" using assms by (intro setsum_mono2) auto\n  finally show ?thesis .\nqed\n\nlemma norm_nth_le:\n  fixes x::\"'a::euclidean_space\"\n  assumes \"i \\<in> Basis\"\n  shows \"norm (x \\<bullet> i) \\<le> norm x\"\n  unfolding norm_conv_dist euclidean_dist_l2[of x] setL2_def\n  by (auto intro!: real_le_rsqrt setsum_ge_element assms)\n\nlemma norm_Pair_le:\n  shows \"norm (x, y) \\<le> norm x + norm y\"\n  unfolding norm_Pair\n  by (metis norm_ge_zero sqrt_sum_squares_le_sum)\n\nsubsection {* Continuity *}\n\nlemma continuous_on_fst[continuous_intros]: \"continuous_on X fst\"\n  unfolding continuous_on_def\n  by (intro ballI tendsto_intros)\n\nlemma continuous_on_snd[continuous_intros]: \"continuous_on X snd\"\n  unfolding continuous_on_def\n  by (intro ballI tendsto_intros)\n\nlemma continuous_at_fst[continuous_intros]:\n  fixes x::\"'a::euclidean_space \\<times> 'b::euclidean_space\"\n  shows \"continuous (at x) fst\"\n  unfolding continuous_def netlimit_at\n  by (intro tendsto_intros)\n\nlemma continuous_at_snd[continuous_intros]:\n  fixes x::\"'a::euclidean_space \\<times> 'b::euclidean_space\"\n  shows \"continuous (at x) snd\"\n  unfolding continuous_def netlimit_at\n  by (intro tendsto_intros)\n\nlemma continuous_at_Pair[continuous_intros]:\n  fixes x::\"'a::euclidean_space \\<times> 'b::euclidean_space\"\n  assumes \"continuous (at x) f\"\n  assumes \"continuous (at x) g\"\n  shows \"continuous (at x) (\\<lambda>x. (f x, g x))\"\n  using assms unfolding continuous_def\n  by (intro tendsto_intros)\n\nlemma continuous_on_Pair[continuous_intros]:\n  assumes \"continuous_on S f\"\n  assumes \"continuous_on S g\"\n  shows \"continuous_on S (\\<lambda>x. (f x, g x))\"\n  using assms unfolding continuous_on_def\n  by (auto intro: tendsto_intros)\n\nlemma continuous_Sigma:\n  assumes defined: \"y \\<in> Pi T X\"\n  assumes f_cont: \"continuous_on (Sigma T X) f\"\n  assumes y_cont: \"continuous_on T y\"\n  shows \"continuous_on T (\\<lambda>x. f (x, y x))\"\n  using continuous_on_compose2[OF continuous_on_subset[where t=\"(\\<lambda>x. (x, y x)) ` T\", OF f_cont]\n                                  continuous_on_Pair[OF continuous_on_id y_cont]] defined\n  by auto\n\nsubsection {* Differentiability *}\n\nlemma differentiable_Pair [simp]:\n  \"f differentiable at x within s \\<Longrightarrow> g differentiable at x within s \\<Longrightarrow> (\\<lambda>x. (f x, g x)) differentiable at x within s\"\n  unfolding differentiable_def by (blast intro: has_derivative_Pair)\n\nlemma (in bounded_linear)\n  differentiable:\n  assumes \"g differentiable (at x within s)\"\n  shows \" (\\<lambda>x. f (g x)) differentiable (at x within s)\"\n  using assms[simplified frechet_derivative_works]\n  by (intro differentiableI) (rule has_derivative)\n\nlemmas\n  differentiable_mult_right[intro] = bounded_linear.differentiable[OF bounded_linear_mult_right] and\n  differentiable_mult_left[intro] = bounded_linear.differentiable[OF bounded_linear_mult_left] and\n  differentiable_inner_right[intro] = bounded_linear.differentiable[OF bounded_linear_inner_right] and\n  differentiable_inner_left[intro] = bounded_linear.differentiable[OF bounded_linear_inner_left]\n\nlemma (in bounded_bilinear)\n  differentiable:\n  assumes f: \"f differentiable at x within s\" and g: \"g differentiable at x within s\"\n  shows \"(\\<lambda>x. prod (f x) (g x)) differentiable at x within s\"\n  using assms[simplified frechet_derivative_works]\n  by (intro differentiableI) (rule FDERIV)\n\nlemmas\n  differentiable_mult[intro] = bounded_bilinear.differentiable[OF bounded_bilinear_mult] and\n  differentiable_scaleR[intro] = bounded_bilinear.differentiable[OF bounded_bilinear_scaleR]\n\nlemma differentiable_transform_within_weak:\n  assumes \"x \\<in> s\" \"\\<And>x'. x'\\<in>s \\<Longrightarrow> g x' = f x'\" \"f differentiable at x within s\"\n  shows \"g differentiable at x within s\"\n  using assms by (intro differentiable_transform_within[OF zero_less_one, where g=g]) auto\n\nlemma differentiable_compose_at:\n  \"f differentiable (at x) \\<Longrightarrow> g differentiable (at (f x)) \\<Longrightarrow> (\\<lambda>x. g (f x)) differentiable (at x)\"\n  unfolding o_def[symmetric]\n  by (rule differentiable_chain_at)\n\nlemma differentiable_compose_within:\n  \"f differentiable (at x within s) \\<Longrightarrow> g differentiable (at(f x) within (f ` s)) \\<Longrightarrow>\n  (\\<lambda>x. g (f x)) differentiable (at x within s)\"\n  unfolding o_def[symmetric]\n  by (rule differentiable_chain_within)\n\nlemma differentiable_setsum[intro, simp]:\n  assumes \"finite s\" \"\\<forall>a\\<in>s. (f a) differentiable net\"\n  shows \"(\\<lambda>x. setsum (\\<lambda>a. f a x) s) differentiable net\"\nproof-\n guess f' using bchoice[OF assms(2)[unfolded differentiable_def]] ..\n thus ?thesis unfolding differentiable_def apply-\n   apply(rule,rule has_derivative_setsum[where f'=f'])\n   by auto\nqed\n\nsubsection {* Derivatives *}\n\nlemma has_derivative_singletonI: \"bounded_linear g \\<Longrightarrow> (f has_derivative g) (at x within {x})\"\n  by (rule has_derivativeI_sandwich[where e=1]) (auto intro!: bounded_linear_scaleR_left)\n\nlemma vector_derivative_eq_rhs: \"(f has_vector_derivative f') F \\<Longrightarrow> f' = g' \\<Longrightarrow> (f has_vector_derivative g') F\"\n  by simp\n\nlemma has_derivative_transform:\n  assumes \"x \\<in> s\" \"\\<And>x. x \\<in> s \\<Longrightarrow> g x = f x\"\n  assumes \"(f has_derivative f') (at x within s)\"\n  shows \"(g has_derivative f') (at x within s)\"\n  using assms by (intro has_derivative_transform_within[OF zero_less_one, where g=g]) auto\n\nlemma has_derivative_If_in_closed:\n  assumes f':\"\\<And>x. x \\<in> s \\<Longrightarrow> (f has_derivative f' x) (at x within s)\"\n  assumes g':\"\\<And>x. x \\<in> t \\<Longrightarrow> (g has_derivative g' x) (at x within t)\"\n  assumes connect: \"\\<And>x. x \\<in> s \\<inter> t \\<Longrightarrow> f x = g x\" \"\\<And>x. x \\<in> s \\<inter> t \\<Longrightarrow> f' x = g' x\"\n  assumes \"closed t\" \"closed s\" \"x \\<in> s \\<union> t\"\n  shows \"((\\<lambda>x. if x \\<in> s then f x else g x) has_derivative (if x \\<in> s then f' x else g' x)) (at x within (s \\<union> t))\"\n  (is \"(?if has_derivative ?if') _\")\n  unfolding has_derivative_within\nproof (safe intro!: tendstoI)\n  fix e::real assume \"0 < e\"\n  let ?D = \"\\<lambda>x f f' y. (1 / norm (y - x)) *\\<^sub>R (f y - (f x + f' (y - x)))\"\n  have f': \"x \\<in> s \\<Longrightarrow> ((?D x f (f' x)) ---> 0) (at x within s)\"\n    and g': \"x \\<in> t \\<Longrightarrow> ((?D x g (g' x)) ---> 0) (at x within t)\"\n    using f' g' by (auto simp: has_vector_derivative_def has_derivative_within)\n  let ?thesis = \"eventually (\\<lambda>y. dist (?D x ?if ?if' y) 0 < e) (at x within s \\<union> t)\"\n  {\n    assume \"x \\<in> s\" \"x \\<in> t\"\n    from tendstoD[OF f'[OF `x \\<in> s`] `0 < e`] tendstoD[OF g'[OF `x \\<in> t`] `0 < e`]\n    have ?thesis unfolding eventually_at_filter\n      by eventually_elim (insert `x \\<in> s` `x \\<in> t`, auto simp: connect)\n  } moreover {\n    assume \"x \\<in> s\" \"x \\<notin> t\"\n    hence \"eventually (\\<lambda>x. x \\<in> - t) (at x within s \\<union> t)\" using `closed t`\n      by (intro topological_tendstoD) (auto intro: tendsto_ident_at)\n    with tendstoD[OF f'[OF `x \\<in> s`] `0 < e`] have ?thesis unfolding eventually_at_filter\n      by eventually_elim (insert `x \\<in> s` `x \\<notin> t`, auto simp: connect)\n  } moreover {\n    assume \"x \\<notin> s\" hence \"x \\<in> t\" using assms by auto\n    have \"eventually (\\<lambda>x. x \\<in> - s) (at x within s \\<union> t)\" using `closed s` `x \\<notin> s`\n      by (intro topological_tendstoD) (auto intro: tendsto_ident_at)\n    with tendstoD[OF g'[OF `x \\<in> t`] `0 < e`] have ?thesis unfolding eventually_at_filter \n      by eventually_elim (insert `x \\<in> t` `x \\<notin> s`, auto simp: connect)\n  } ultimately show ?thesis by blast\nqed (insert assms, auto intro!: has_derivative_bounded_linear f' g')\n\nlemma linear_continuation:\n  assumes f':\"\\<And>x. x \\<in> {a .. b} \\<Longrightarrow> (f has_vector_derivative f' x) (at x within {a .. b})\"\n  assumes g':\"\\<And>x. x \\<in> {b .. c} \\<Longrightarrow> (g has_vector_derivative g' x) (at x within {b .. c})\"\n  assumes connect: \"f b = g b\" \"f' b = g' b\"\n  assumes x: \"x \\<in> {a .. c}\"\n  assumes abc:\"a \\<le> b\" \"b \\<le> c\"\n  shows \"((\\<lambda>x. if x \\<le> b then f x else g x) has_vector_derivative\n  (\\<lambda>x. if x \\<le> b then f' x else g' x) x) (at x within {a .. c})\"\n  (is \"(?h has_vector_derivative ?h' x) _\")\nproof -\n  have un: \"{a .. b} \\<union> {b .. c} = {a .. c}\" using assms by auto\n  note has_derivative_If_in_closed[derivative_intros]\n  note f'[simplified has_vector_derivative_def, derivative_intros]\n  note g'[simplified has_vector_derivative_def, derivative_intros]\n  have if': \"((\\<lambda>x. if x \\<in> {a .. b} then f x else g x) has_vector_derivative\n    (\\<lambda>x. if x \\<le> b then f' x else g' x) x) (at x within {a .. b}\\<union>{b .. c})\"\n    unfolding has_vector_derivative_def\n    using assms\n    apply -\n    apply (rule derivative_eq_intros refl | assumption)+\n    apply auto\n    done\n  show ?thesis\n    unfolding has_vector_derivative_def\n    by (rule has_derivative_transform[OF x _ if'[simplified un has_vector_derivative_def]]) simp\nqed\n\nlemma exists_linear_continuation:\n  assumes f':\"\\<And>x. x \\<in> {a .. b} \\<Longrightarrow> (f has_vector_derivative f' x) (at x within {a .. b})\"\n  shows \"\\<exists>fc. (\\<forall>x. x \\<in> {a .. b} \\<longrightarrow> (fc has_vector_derivative f' x) (at x)) \\<and>\n    (\\<forall>x. x \\<in> {a .. b} \\<longrightarrow> fc x = f x)\"\nproof (rule, safe)\n  fix x assume \"x \\<in> {a .. b}\" hence \"a \\<le> b\" by simp\n  let ?line = \"\\<lambda>a x. f a + (x - a) *\\<^sub>R f' a\"\n  let ?fc = \"(\\<lambda>x. if x \\<in> {a .. b} then f x else if x \\<in> {..a} then ?line a x else ?line b x)\"\n  have [simp]:\n    \"\\<And>x. x \\<in> {a .. b} \\<Longrightarrow> (b \\<le> x \\<longleftrightarrow> x = b)\" \"\\<And>x. x \\<in> {a .. b} \\<Longrightarrow> (x \\<le> a \\<longleftrightarrow> x = a)\"\n    \"\\<And>x. x \\<le> a \\<Longrightarrow> (b \\<le> x \\<longleftrightarrow> x = b)\" using `a \\<le> b` by auto\n  note has_derivative_If_in_closed[derivative_intros] f'[simplified has_vector_derivative_def, derivative_intros]\n  have \"(?fc has_vector_derivative f' x) (at x within {a .. b} \\<union> ({..a} \\<union> {b..}))\"\n    using `x \\<in> {a .. b}` `a \\<le> b`\n    by (auto intro!: derivative_eq_intros simp: has_vector_derivative_def\n      simp del: atMost_iff atLeastAtMost_iff)\n  moreover have \"{a .. b} \\<union> ({..a} \\<union> {b..}) = UNIV\" by auto\n  ultimately show \"(?fc has_vector_derivative f' x) (at x)\" by simp\n  show \"?fc x = f x\" using `x \\<in> {a .. b}` by simp\nqed\n\n\nlemma Pair_has_vector_derivative:\n  assumes f: \"(f has_vector_derivative f') (at x within s)\"\n      and g: \"(g has_vector_derivative g') (at x within s)\"\n  shows \"((\\<lambda>x. (f x, g x)) has_vector_derivative (f', g')) (at x within s)\"\n  using assms by (auto simp: has_vector_derivative_def intro!: derivative_eq_intros)\n\nlemma has_vector_derivative_imp:\n  assumes \"x \\<in> s\"\n  assumes \"\\<And>x. x \\<in> s \\<Longrightarrow> f x = g x\"\n  assumes f'g':\"f' = g'\"\n  assumes \"x = y\" \"s = t\"\n  assumes f': \"(f has_vector_derivative f') (at x within s)\"\n  shows \"(g has_vector_derivative g') (at y within t)\"\n  unfolding has_vector_derivative_def has_derivative_within'\nproof (safe)\n  fix e::real\n  assume \"0 < e\"\n  with assms f' have \"\\<exists>d>0. \\<forall>x'\\<in>s.\n    0 < norm (x' - x) \\<and> norm (x' - x) < d \\<longrightarrow>\n    norm (g x' - g y - (x' - y) *\\<^sub>R g') / norm (x' - x) < e\"\n    by (auto simp add: has_vector_derivative_def has_derivative_within')\n  then guess d ..\n  with assms show \"\\<exists>d>0. \\<forall>x'\\<in>t. 0 < norm (x' - y) \\<and> norm (x' - y) < d \\<longrightarrow>\n    norm (g x' - g y - (x' - y) *\\<^sub>R g') / norm (x' - y) < e\"\n    by auto\nnext\n  show \"bounded_linear (\\<lambda>x. x *\\<^sub>R g')\"\n    using has_derivative_bounded_linear[OF f'[simplified has_vector_derivative_def], simplified f'g'] assms\n    by simp\nqed\n\nlemma has_vector_derivative_cong:\n  assumes \"x \\<in> s\"\n  assumes \"\\<And>x. x \\<in> s \\<Longrightarrow> f x = g x\"\n  assumes f'g':\"f' = g'\"\n  assumes \"x = y\" \"s = t\"\n  shows \"(g has_vector_derivative g') (at y within t) =\n  (f has_vector_derivative f') (at x within s)\"\nproof\n  assume \"(f has_vector_derivative f') (at x within s)\"\n  from has_vector_derivative_imp this assms\n  show \"(g has_vector_derivative g') (at y within t)\"\n    by blast\nnext\n  assume g': \"(g has_vector_derivative g') (at y within t)\"\n  show \"(f has_vector_derivative f') (at x within s)\"\n    using assms g'\n    by (intro has_vector_derivative_imp[where f=g and g=f and f'=g' and g'=f'])\n      auto\nqed\n\nlemma has_derivative_within_union:\n  assumes \"(f has_derivative g) (at x within s)\"\n  assumes \"(f has_derivative g) (at x within t)\"\n  shows  \"(f has_derivative g) (at x within (s \\<union> t))\"\nproof cases\n  assume \"at x within (s \\<union> t) = bot\"\n  thus ?thesis using assms by (simp_all add: has_derivative_def)\nnext\n  assume st: \"at x within (s \\<union> t) \\<noteq> bot\"\n  thus ?thesis\n    using assms\n    apply (auto simp: Lim_within_union has_derivative_def)\n    apply (cases \"at x within s = bot\", simp_all add: netlimit_within)\n    apply (cases \"at x within t = bot\", simp_all add: netlimit_within)\n    done\nqed\n\nlemma has_vector_derivative_within_union:\n  assumes \"(f has_vector_derivative g) (at x within s)\"\n  assumes \"(f has_vector_derivative g) (at x within t)\"\n  shows  \"(f has_vector_derivative g) (at x within (s \\<union> t))\"\nusing assms\nby (auto simp: has_vector_derivative_def intro: has_derivative_within_union)\n\nlemma vector_derivative_within_closed_interval:\n  fixes f::\"real \\<Rightarrow> 'a::euclidean_space\"\n  assumes \"a < b\" and \"x \\<in> {a .. b}\"\n  assumes \"(f has_vector_derivative f') (at x within {a .. b})\"\n  shows \"vector_derivative f (at x within {a .. b}) = f'\"\n  apply(rule vector_derivative_unique_within_closed_interval)\n  using vector_derivative_works[unfolded differentiable_def]\n  using assms by (auto simp add: has_vector_derivative_def)\n\ntext {* TODO: include this into the attribute DERIV-intros?! *}\n\nlemma DERIV_compose_FDERIV:\n  fixes f::\"real\\<Rightarrow>real\"\n  assumes \"DERIV f (g x) :> f'\"\n  assumes \"(g has_derivative g') (at x within s)\"\n  shows \"((\\<lambda>x. f (g x)) has_derivative (\\<lambda>x. g' x * f')) (at x within s)\"\n  using assms has_derivative_compose[of g g' x s f \"op * f'\"]\n  by (auto simp: has_field_derivative_def ac_simps)\n\nlemmas has_derivative_sin[derivative_intros] = DERIV_sin[THEN DERIV_compose_FDERIV]\n  and  has_derivative_cos[derivative_intros] = DERIV_cos[THEN DERIV_compose_FDERIV]\n  and  has_derivative_exp[derivative_intros] = DERIV_exp[THEN DERIV_compose_FDERIV]\n  and  has_derivative_ln[derivative_intros] = DERIV_ln[THEN DERIV_compose_FDERIV]\n\nlemma has_derivative_continuous_on:\n  \"(\\<And>x. x \\<in> s \\<Longrightarrow> (f has_derivative f' x) (at x within s)) \\<Longrightarrow> continuous_on s f\"\n  by (auto intro!: differentiable_imp_continuous_on differentiableI simp: differentiable_on_def)\n\nlemma taylor_up_within:\n  assumes INIT: \"n>0\" \"\\<And>t. t \\<in> {a .. b} \\<Longrightarrow> diff 0 t = f t\"\n  and DERIV: \"\\<And>m t. m < n \\<Longrightarrow> a \\<le> t \\<Longrightarrow> t \\<le> b \\<Longrightarrow>\n    ((diff m) has_vector_derivative (diff (Suc m) t)) (at t within {a .. b})\"\n  and INTERV: \"a \\<le> c\" \"c < b\"\n  shows \"\\<exists>t. c < t & t < b &\n    f b = (\\<Sum>m<n. (diff m c / real (fact m)) * (b - c)^m)+\n      (diff n t / real (fact n)) * (b - c)^n\" (is \"?taylor f diff\")\nproof -\n  from exists_linear_continuation[of a b, OF DERIV]\n  have \"\\<forall>m. \\<exists>d'. m < n \\<longrightarrow>\n    (\\<forall>x \\<in> {a .. b}. (d' has_vector_derivative diff (Suc m) x) (at x) \\<and> d' x = diff m x)\"\n    by (metis atLeastAtMost_iff)\n  then guess d' unfolding choice_iff .. note d' = this\n  let ?diff = \"\\<lambda>m. if m = n then diff m else d' m\"\n  have \"?taylor (?diff 0) ?diff\" using d'\n    by (intro taylor_up[OF _ _ _ `a \\<le> c`])\n       (auto simp: has_field_derivative_def has_vector_derivative_def INIT INTERV mult_commute_abs)\n  thus \"?taylor f diff\" using d' INTERV INIT by auto\nqed\n\nlemma taylor_up_within_vector:\n  fixes f::\"real \\<Rightarrow> 'a::euclidean_space\"\n  assumes INIT: \"n>0\" \"\\<And>t. t \\<in> {a .. b} \\<Longrightarrow> diff 0 t = f t\"\n  and DERIV: \"\\<And>m t. m < n \\<Longrightarrow> a \\<le> t \\<Longrightarrow> t \\<le> b \\<Longrightarrow>\n    ((diff m) has_vector_derivative (diff (Suc m) t)) (at t within {a .. b})\"\n  and INTERV: \"a \\<le> c\" \"c < b\"\n  shows \"\\<exists>t. (\\<forall>i\\<in>Basis::'a set. c < t i & t i < b) \\<and>\n    f b = setsum (%m. (b - c)^m *\\<^sub>R (diff m c /\\<^sub>R real (fact m))) {..<n} +\n      setsum (\\<lambda>x. (((b - c) ^ n *\\<^sub>R diff n (t x) /\\<^sub>R real (fact n)) \\<bullet> x) *\\<^sub>R x) Basis\"\nproof -\n  obtain t where t: \"\\<forall>i\\<in>Basis::'a set. t i > c \\<and> t i < b \\<and>\n    f b \\<bullet> i =\n      (\\<Sum>m<n. diff m c \\<bullet> i / real (fact m) * (b - c) ^ m) +\n      diff n (t i) \\<bullet> i / real (fact n) * (b - c) ^ n\"\n  proof (atomize_elim, rule bchoice, safe)\n    fix i::'a\n    assume \"i \\<in> Basis\"\n    have DERIV_0: \"\\<And>t. t \\<in> {a .. b} \\<Longrightarrow> (diff 0) t \\<bullet> i = f t \\<bullet> i\" using INIT by simp\n    have DERIV_Suc: \"\\<And>m t. m < n \\<Longrightarrow> a \\<le> t \\<Longrightarrow> t \\<le> b \\<Longrightarrow>\n      ((\\<lambda>t. (diff m) t \\<bullet> i) has_vector_derivative (diff (Suc m) t \\<bullet> i)) (at t within {a .. b})\"\n      using DERIV by (auto intro!: derivative_eq_intros simp: has_vector_derivative_def)\n    from taylor_up_within[OF INIT(1) DERIV_0 DERIV_Suc INTERV]\n    show \"\\<exists>t>c. t < b \\<and> f b \\<bullet> i =\n      (\\<Sum>m<n. diff m c \\<bullet> i / real (fact m) * (b - c) ^ m) +\n      diff n t \\<bullet> i / real (fact n) * (b - c) ^ n\" by simp\n  qed\n  have \"f b = (\\<Sum>i\\<in>Basis. (f b \\<bullet> i) *\\<^sub>R i)\" by (rule euclidean_representation[symmetric])\n  also have \"\\<dots> =\n      (\\<Sum>i\\<in>Basis. ((\\<Sum>m<n. (b - c) ^ m *\\<^sub>R (diff m c /\\<^sub>R real (fact m))) \\<bullet> i) *\\<^sub>R i) +\n      (\\<Sum>x\\<in>Basis. (((b - c) ^ n *\\<^sub>R diff n (t x) /\\<^sub>R real (fact n)) \\<bullet> x) *\\<^sub>R x)\"\n    using t by (simp add: setsum.distrib inner_setsum_left inverse_eq_divide algebra_simps)\n  finally show ?thesis using t by (auto simp: euclidean_representation)\nqed\n\nsubsection {* Integration *}\n\nlemmas content_real[simp]\n\nlemma integral_real_singleton[simp]:\n  \"integral {a::real} f = 0\"\n  using integral_refl[of a f] by simp\nlemmas integrable_continuous[intro, simp]\n  and integrable_continuous_real[intro, simp]\n\nlemma mvt_integral:\n  fixes f::\"'a::euclidean_space\\<Rightarrow>'b::euclidean_space\"\n  assumes f'[derivative_intros]: \"\\<And>x. x \\<in> S \\<Longrightarrow> (f has_derivative f' x) (at x within S)\"\n  assumes f'_cont: \"\\<And>i. i \\<in> Basis \\<Longrightarrow> continuous_on S (\\<lambda>t. f' t i)\"\n  assumes line_in: \"\\<And>t. t \\<in> {0..1} \\<Longrightarrow> x + t *\\<^sub>R y \\<in> S\"\n  shows \"f (x + y) - f x = integral {0..1} (\\<lambda>t. f' (x + t *\\<^sub>R y) y)\" (is ?th1)\n   and  \"f (x + y) - f x = (\\<Sum>a\\<in>Basis. (y \\<bullet> a) *\\<^sub>R integral {0..1} (\\<lambda>t. f' (x + t *\\<^sub>R y) a))\" (is ?th2)\nproof -\n  from assms have subset: \"(\\<lambda>xa. x + xa *\\<^sub>R y) ` {0..1} \\<subseteq> S\" by auto\n  note has_derivative_subset[OF _ subset, derivative_intros]\n  note has_derivative_in_compose[where f=\"(\\<lambda>xa. x + xa *\\<^sub>R y)\" and g = f, derivative_intros]\n  note continuous_on_compose2[where f=\"(\\<lambda>xa. x + xa *\\<^sub>R y)\", continuous_intros]\n  note continuous_on_subset[OF _ subset, continuous_intros]\n  have \"\\<And>t. t \\<in> {0..1} \\<Longrightarrow>\n    ((\\<lambda>t. f (x + t *\\<^sub>R y)) has_vector_derivative f' (x + t *\\<^sub>R y) y) (at t within {0..1})\"\n    using assms\n    by (auto simp: has_vector_derivative_def linear_cmul[OF has_derivative_linear[OF f'], symmetric]\n      intro!: derivative_eq_intros)\n  from fundamental_theorem_of_calculus[rule_format, OF _ this]\n  show ?th1\n    by (auto intro!: integral_unique[symmetric])\n\n  also have \"integral {0..1} (\\<lambda>t. f' (x + t *\\<^sub>R y) y) =\n    integral {0..1} (\\<lambda>t. (\\<Sum>i\\<in>Basis. (f' (x + t *\\<^sub>R y) y \\<bullet> i) *\\<^sub>R i))\"\n    by (simp add: euclidean_representation)\n  also have \"\\<dots> = integral {0..1}\n     (\\<lambda>t. \\<Sum>i\\<in>Basis. (y \\<bullet> i) *\\<^sub>R (f' (x + t *\\<^sub>R y) i))\"\n  proof (rule integral_spike[OF negligible_empty], safe)\n    fix t::real assume t: \"t \\<in> {0 .. 1}\"\n    have \"(\\<Sum>i\\<in>Basis. (y \\<bullet> i) *\\<^sub>R f' (x + t *\\<^sub>R y) i) =\n      (\\<Sum>i\\<in>Basis. \\<Sum>a\\<in>Basis. (y \\<bullet> a) *\\<^sub>R (f' (x + t *\\<^sub>R y) a \\<bullet> i) *\\<^sub>R i)\"\n      by (subst setsum.commute[symmetric])\n        (simp only: scaleR_setsum_right[symmetric] euclidean_representation)\n    also have \"\\<dots> = (\\<Sum>i\\<in>Basis. (f' (x + t *\\<^sub>R y) y \\<bullet> i) *\\<^sub>R i)\"\n      by (subst Derivative.linear_componentwise[OF has_derivative_linear[OF f'], OF line_in[OF t]])\n        (simp add: scaleR_setsum_left)\n    finally\n    show \"(\\<Sum>i\\<in>Basis. (y \\<bullet> i) *\\<^sub>R f' (x + t *\\<^sub>R y) i) = (\\<Sum>i\\<in>Basis. (f' (x + t *\\<^sub>R y) y \\<bullet> i) *\\<^sub>R i)\" .\n  qed\n  also have \"\\<dots> = (\\<Sum>a\\<in>Basis. integral {0..1} (\\<lambda>t. (y \\<bullet> a) *\\<^sub>R f' (x + t *\\<^sub>R y) a))\"\n    by (subst integral_setsum) (auto intro!: continuous_intros f'_cont)\n  also have \"\\<dots> = (\\<Sum>a\\<in>Basis. (y \\<bullet> a) *\\<^sub>R integral {0..1} (\\<lambda>t. f' (x + t *\\<^sub>R y) a))\"\n    using assms\n    by (intro setsum.cong[OF refl], subst integral_cmul)\n      (auto intro!: continuous_intros f'_cont simp: integral_cmul)\n  finally show ?th2 .\nqed\n\nsubsection {* conditionally complete lattice *}\n\nlemma bounded_imp_bdd_above: \"bounded S \\<Longrightarrow> bdd_above (S :: 'a::ordered_euclidean_space set)\"\n  by (auto intro: bdd_above_mono dest!: bounded_subset_cbox)\n\nlemma bounded_imp_bdd_below: \"bounded S \\<Longrightarrow> bdd_below (S :: 'a::ordered_euclidean_space set)\"\n  by (auto intro: bdd_below_mono dest!: bounded_subset_cbox)\n\nlemma bdd_above_cmult:\n  \"0 \\<le> (a :: 'a :: ordered_semiring) \\<Longrightarrow> bdd_above S \\<Longrightarrow> bdd_above ((\\<lambda>x. a * x) ` S)\"\n  by (metis bdd_above_def bdd_aboveI2 mult_left_mono)\n\nlemma Sup_real_mult:\n  fixes a::real\n  assumes \"0 \\<le> a\"\n  assumes \"S \\<noteq> {}\" \"bdd_above S\"\n  shows \"a * Sup S = Sup ((\\<lambda>x. a * x) ` S)\"\n  using assms\nproof cases\n  assume \"a = 0\" with `S \\<noteq> {}` show ?thesis\n    by (simp add: cSUP_const)\nnext\n  assume \"a \\<noteq> 0\"\n  with `0 \\<le> a` have \"0 < a\"\n    by simp\n  show ?thesis\n  proof (intro antisym)\n    have \"Sup S \\<le> Sup (op * a ` S) / a\" using assms\n      by (intro cSup_least mult_imp_le_div_pos cSup_upper)\n         (auto simp: bdd_above_cmult assms `0 < a` less_imp_le)\n    thus \"a * Sup S \\<le> Sup (op * a ` S)\"\n      by (simp add: ac_simps pos_le_divide_eq[OF `0<a`])\n  qed (insert assms `0 < a`, auto intro!: cSUP_least cSup_upper)\nqed\n\nsubsection {* Linorder *}\n\ncontext linordered_idom\nbegin\n\nlemma mult_right_le_one_le:\n  \"0 \\<le> x \\<Longrightarrow> y \\<le> 1 \\<Longrightarrow> x * y \\<le> x\"\n  by (auto simp add: mult_le_cancel_left2)\n\nlemma mult_left_le_one_le:\n  \"0 \\<le> x \\<Longrightarrow> y \\<le> 1 \\<Longrightarrow> y * x \\<le> x\"\n  by (auto simp add: mult_le_cancel_right2)\n\nend\n\nsubsection {* Banach on type class *}\n\nlemma banach_fix_type:\n  fixes f::\"'a::complete_space\\<Rightarrow>'a\"\n  assumes c:\"0 \\<le> c\" \"c < 1\"\n      and lipschitz:\"\\<forall>x. \\<forall>y. dist (f x) (f y) \\<le> c * dist x y\"\n  shows \"\\<exists>!x. (f x = x)\"\n  using assms banach_fix[OF complete_UNIV UNIV_not_empty assms(1,2) subset_UNIV, of f]\n  by auto\n\nsubsection {* Float *}\n\ndefinition \"trunc p s =\n  (let d = truncate_down p s in\n  let u = truncate_up p s in\n  let ed = abs (s - d) in\n  let eu = abs (u - s) in\n  if abs (s - d) < abs (u - s) then (d, truncate_up p ed) else (u, truncate_up p eu))\"\n\nlemma trunc_nonneg: \"0 \\<le> s \\<Longrightarrow> 0 \\<le> trunc p s\"\n  by (auto simp: trunc_def Let_def zero_prod_def truncate_down_def round_down_nonneg\n    intro!: truncate_up_le)\n\ndefinition \"trunc_err p f = f - (fst (trunc p f))\"\n\nlemma trunc_err_eq:\n  \"fst (trunc p f) + (trunc_err p f) = f\"\n  by (auto simp: trunc_err_def)\n\nlemma trunc_err_le:\n  \"abs (trunc_err p f) \\<le> snd (trunc p f)\"\n  apply (auto simp: trunc_err_def trunc_def Let_def)\n  apply (metis truncate_up)\n  by (metis abs_minus_commute truncate_up)\n\nlemma trunc_err_eq_zero_iff:\n  \"trunc_err p f = 0 \\<longleftrightarrow> snd (trunc p f) = 0\"\n  apply (auto simp: trunc_err_def trunc_def Let_def)\n  apply (metis abs_le_zero_iff eq_iff_diff_eq_0 truncate_up)\n  apply (metis abs_le_zero_iff eq_iff_diff_eq_0 truncate_up)\n  done\n\nlemma mantissa_Float_0[simp]: \"mantissa (Float 0 e) = 0\"\n  by (metis float_of_real float_zero mantissa_eq_zero_iff zero_float_def)\n\n\nsubsection {* Lists *}\n\nlemma listsum_nonneg:\n  assumes nn: \"(\\<And>x. x \\<in> set xs \\<Longrightarrow> f x \\<ge> (0::'a::{monoid_add, ordered_ab_semigroup_add}))\"\n  shows \"0 \\<le> listsum (map f xs)\"\nproof -\n  have \"0 = listsum (map (\\<lambda>_. 0) xs)\"\n    by (induct xs) auto\n  also have \"\\<dots> \\<le> listsum (map f xs)\"\n    by (rule listsum_mono) (rule assms)\n  finally show ?thesis .\nqed\n\n\nsubsection {* Set(sum) *}\n\nlemma setsum_eq_nonzero: \"finite A \\<Longrightarrow> (\\<Sum>a\\<in>A. f a) = (\\<Sum>a\\<in>{a\\<in>A. f a \\<noteq> 0}. f a)\"\n  by (subst setsum.mono_neutral_cong_right) auto\n\nlemma singleton_subsetI:\"i \\<in> B \\<Longrightarrow> {i} \\<subseteq> B\"\n  by auto\n\n\nsubsection {* Max *}\n\nlemma max_transfer[transfer_rule]:\n  assumes [transfer_rule]: \"(rel_fun A (rel_fun A (op =))) (op \\<le>) (op \\<le>)\"\n  shows \"(rel_fun A (rel_fun A A)) max max\"\n  unfolding max_def[abs_def]\n  by transfer_prover\n\nlemma max_power2: fixes a b::real shows \"(max (abs a) (abs b))\\<^sup>2 = max (a\\<^sup>2) (b\\<^sup>2)\"\n  by (auto simp: max_def real_abs_le_square_iff)\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/Ordinary_Differential_Equations/ODE_Auxiliarities.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8499711756575749, "lm_q2_score": 0.8459424334245618, "lm_q1q2_score": 0.7190266846765045}}
{"text": "theory Exercises\nimports Main\nbegin\n\ntext \\<open> Exercise 5.1 \\<close>\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 AA: \"A x y\"\nshows \"T x y\"\nproof(rule ccontr)\n  assume a1:\"\\<not> T x y\"\n  from this and T have a2:\"T y x\" by blast\n  from this and TA have \"A y x\" by blast\n  from this and A and AA have \"x = y\" by blast\n  from this and a1 and a2 show \"False\" by blast \nqed\n\n\n\ntext \\<open> A more direct solution...\nproof(cases)\n  assume a1:\"T y x\"\n  from this and TA have \"A y x\" by auto\n  from this and AA and A have a2:\"x = y\" by auto\n  from this and a1 show \"T x y\" by simp\nnext\n  assume a1:\"\\<not> T y x\"\n  from this and T show \"T x y\" by auto\nqed\n\\<close>\n\ntext \\<open> End of exercise 5.1 \\<close>\n\ntext \\<open> Exercise 5.2 \\<close>\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 \"2 dvd (length xs)\"\n  from this obtain k where l_xs:\"length xs = 2*k\" by(auto simp add: dvd_def)\n  from this obtain ys where tys:\"ys = take k xs\" by(auto)\n  from this obtain zs where dzs:\"zs = drop k xs\" by(auto)\n  from this have l1:\"length ys = k\" using l_xs and tys by(auto)\n  from this have f1:\"xs = ys @ zs\" using tys and dzs by(metis append_eq_conv_conj)\n  from this have f2:\"length ys = length zs\" using l_xs and l1 by(auto)\n  then show ?thesis using f1 and f2 by(auto)\nnext\n  assume \" \\<not> 2 dvd (length xs)\"\n  from this have \"\\<exists> k. (length xs) = 2*k + 1\" by(arith)\n  from this obtain k where l_xs:\"(length xs) = 2*k + 1\" by(auto)\n  from this obtain ys where tys:\"ys = take (Suc k) xs\" by(auto)\n  from this obtain zs where dzs:\"zs = drop (Suc k) xs\" by(auto)\n  from this have \"length ys = Suc k\" using l_xs and tys by(auto) \n  from this have f1:\"xs = ys @ zs\" using tys and dzs by(metis append_eq_conv_conj)\n  from this have f2:\"length ys = length zs + 1\" using l_xs and tys and dzs by(auto)\n  then show ?thesis using f1 and f2 by(auto)\nqed\n\ntext \\<open> End of Exercise 5.2 \\<close>\n\ntext \\<open> Exercise 5.3 \\<close>\n\ninductive ev :: \"nat \\<Rightarrow> bool\" where\nev0: \"ev 0\" |\nevSS: \"ev n \\<Longrightarrow> ev(Suc(Suc n))\"\n\nlemma assumes a: \"ev (Suc(Suc n))\" shows \"ev n\"\nproof -\n  show \"ev n\" using a\n  proof cases\n    case evSS thus \"ev n\"  by (simp add: ev.evSS)\n  qed\nqed\n\ntext \\<open> End of Exercise 5.3 \\<close>\n\n\n\ntext \\<open> End of Exercise 5.4 \\<close>\n\nlemma \"\\<not> ev (Suc (Suc (Suc 0)))\" (is \"\\<not> ?P\")\nproof\n assume \"?P\"\n from this have \"ev (Suc 0)\" by (cases)\n from this show  False by (cases) \nqed\n\ntext \\<open> End of Exercise 5.4 \\<close>\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/Chap5/Exercises.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8519528170040852, "lm_q2_score": 0.8438951084436076, "lm_q1q2_score": 0.7189588148944994}}
{"text": "theory Najveci_zajednicki_delilac\n  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(*\n   U daljim dokazima, gde je bilo potrebno nesto dokazati preko indukcije,\n   lakse mi je bilo da to dokazem koristeci funkciju gcd_prim,\n   zbog toga imam dve funkcije koje rade istu stvar.\n*)\n\nfun gcd_prim :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\" where\n  \"gcd_prim m 0 = m\" |\n  \"gcd_prim m n = gcd_prim n (m mod n)\"\n\n(* Euklidov algoritam *)\n\n(* gcd za n = 0 i n > 0*)\nlemma gcd_0 [simp]: \"gcd m 0 = m\"\n  using gcd.simps(1)\n  by simp\n\nlemma gcd_ne_0 [simp]: \"0 < n \\<Longrightarrow> gcd m n = gcd n (m mod n)\"\n  using gcd.simps\n  by simp\n\ndeclare gcd.simps [simp del]\n\n(* Dokaz da broj koji deli m i deli n, deli i njihov nzd  *)\nlemma deli_oba_deli_gcd: \"\\<forall> d. d dvd m \\<and> d dvd n \\<longrightarrow> d dvd (gcd_prim m n)\"\nproof (induction m n rule: gcd_prim.induct)\n  case (1 m) (* \\<forall>d. d dvd m \\<and> d dvd 0 \\<longrightarrow> d dvd gcd_prim m 0 *)\n  then show ?case\n  proof (cases \"n = 0\")\n    case True\n    then show ?thesis\n      using gcd_prim.simps(1)\n      by simp\n  next\n    case False\n    then show ?thesis\n      using gcd_prim.simps(2)\n      by simp\n  qed\nnext\n  case (2 m v)\n then show ?case (*d dvd Suc v \\<and> d dvd m mod Suc v \\<longrightarrow> d dvd gcd_prim (Suc v) (m mod Suc v) *)\n   by (simp add: dvd_mod)\nqed\n\nthm dvd_mod (* ako neki broj deli m i n, deli i njihov ostatak *)\nthm dvd_mod_imp_dvd (* ako neki broj deli ostatak od a i b i deli b, deli i a*)\n\n(* Dokaz da gcd m n deli i m i n *)\nlemma gcd_deli_oba [simp]: \"(gcd m n) dvd m \\<and> (gcd m n) dvd n\"\nproof(induction m n rule: gcd_prim.induct)\n    case (1 m)  (* (nzd m 0) dvd m \\<and> (nzd m 0) dvd 0, a imamo \"nzd m 0 = m\" iz fun nzd \\<Rightarrow> m dvd m \\<and> m dvd 0 *)\n    then show ?case by simp\n  next\n    case (2 m v)\n    then show ?case using dvd_mod_imp_dvd by auto\n  qed\n\n  thm gcd_dvd1 (* gcd a b deli a*)\n\nlemmas gcd_dvd1 [iff] = gcd_deli_oba [THEN conjunct1] (* gcd m n deli m *)\nlemmas gcd_dvd2 [iff] = gcd_deli_oba [THEN conjunct2] (* gcd m n deli n *)\n\n\n(* Maksimalnost: \"Za sve m, n, d, ako d deli m i ako d deli n onda d deli njihov nzd.\" *)\nlemma gcd_najveci_zajednicki_prim [rule_format]:  \"d dvd m \\<longrightarrow> d dvd n \\<longrightarrow> d dvd (gcd_prim m n)\"\nproof (induction m n rule: gcd_prim.induct)\n  case (1 m)\n  then show ?case\n  proof (cases \"n = 0\")\n    case True\n    then show ?thesis\n      using gcd_prim.simps(1)\n      by simp\n  next\n    case False\n    then show ?thesis\n      using gcd_prim.simps(2)\n      by simp\n  qed\nnext\n  case (2 m v)\n then show ?case (* \\<forall>d. d dvd Suc v \\<and> d dvd m mod Suc v \\<longrightarrow> d dvd gcd_prim (Suc v) (m mod Suc v) *)\n   by (simp_all add: dvd_mod)\nqed\n\n(*\nTermovi se formiraju primenom funkcija na argumente.\nKada na dva terma t1-->t2 primenimo funkciju f, dobijamo f(t1) --> f(t2).\n\nIsabelle moze da razlikuje slucajeve zasnovane na termovima pomocu: apply (case_tac <term>).\n\nTako i u dokazu naredne leme, kada kazemo apply (case_tac \"n=0\"), Isabelle deli na dva slucaja\nu zavisnosti od toga da li je n = 0 ili n \\<noteq> 0:\n1. n = 0 \\<Longrightarrow> d dvd m \\<longrightarrow> d dvd n \\<longrightarrow> d dvd gcd m n\n2. n \\<noteq> 0 \\<Longrightarrow> d dvd m \\<longrightarrow> d dvd n \\<longrightarrow> d dvd gcd m n\n\ndvd_mod - ako k deli m i k deli n, onda k deli i njihov ostatak (tj. m mod n)\n*)\n\n(*\nSledeca lema je kao prethodna, ali dokazana na drugi nacin, da bi mogla gcd_najveci_zajednicki_iff da se dok.\nIz predhodne se jasnije vidi dokaz, pa sam je zato ostavila.\n*)\n\n(* Maksimalnost: \"Za sve m, n, d, ako d deli m i ako d deli n onda d deli njihov nzd.\" *)\nlemma gcd_najveci_zajednicki [rule_format]: \"d dvd m \\<longrightarrow> d dvd n \\<longrightarrow> d dvd gcd m n\"\napply (induct_tac m n rule: gcd.induct)\napply (case_tac \"n=0\")\napply (simp_all add: dvd_mod)\n  done\n\n(* Broj koji deli gcd m n, deli m i deli n *)\ntheorem gcd_najveci_zajednicki_iff [iff]: \"(k dvd gcd m n) = (k dvd m \\<and> k dvd n)\"\n  sledgehammer\n  by (meson Najveci_zajednicki_delilac.gcd_dvd1 Najveci_zajednicki_delilac.gcd_dvd2 Najveci_zajednicki_delilac.gcd_najveci_zajednicki gcd_nat.trans)\n\ndefinition is_gcd :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> bool\" where\n    \"is_gcd p m n == (p dvd m)  \\<and>  (p dvd n)  \\<and>  (\\<forall> d. d dvd m \\<and> d dvd n \\<longrightarrow> d dvd p)\"\n\n(* Funkcija gcd daje najveci zajednicki delilac *)\nlemma euklid_nzd_is_gcd:\n  shows \"is_gcd (gcd m n) m n\"\n(* Znaci ovo treba pokazati:\n\"((gcd m n) dvd m) \\<and> ((gcd m n) dvd n) \\<and> (\\<forall>d. d dvd m \\<and> d dvd n \\<longrightarrow> d dvd (gcd m n))\" *)\nproof -\n  have \"(gcd m n) dvd m \\<and> (gcd m n) dvd n\"\n    using gcd_deli_oba by simp\n  also have \"\\<forall>d. d dvd m \\<and> d dvd n \\<longrightarrow> d dvd (gcd m n)\"\n    using gcd_deli_oba by simp\n ultimately show \"is_gcd (gcd m n) m n\"\n    by (simp add: is_gcd_def)\nqed\n\nvalue \"euklid_nzd_is_gcd 3 3 27\"\n\n(* Drugi nacin *)\nlemma is_gcd: \"is_gcd (gcd m n) m n\"\napply (simp add: is_gcd_def gcd_najveci_zajednicki)\n  done\n\n(* Jedinstvenost nzd *)\nlemma gcd_jedinstven: \"is_gcd m a b \\<Longrightarrow> is_gcd n a b \\<Longrightarrow> m = n\" (* za a i b postoji jedinstven nzd m = n *)\napply (simp add: is_gcd_def)\napply (blast intro: dvd_antisym)\n  done\n\n(* Asocijativnost nzd *)\nlemma gcd_asocijativnost: \"gcd (gcd k m) n = gcd k (gcd m n)\"\n  apply (rule gcd_jedinstven)\n  apply (rule is_gcd)\n  apply (simp add: is_gcd_def)\n  apply (blast intro: dvd_trans)\n  done\n\nthm dvd_trans\n\nlemma bezuov_stav [simp]:\n  assumes ex: \"\\<exists>(d::nat) x y. d dvd a \\<and> d dvd b \\<and> (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> (a * x = (a + b) * y + d \\<or> (a + b) * x = a * y + d)\"\n  using ex\n (*\n sledgehammer\n  by (metis add.left_neutral bezout_add_strong_nat gcd_nat.extremum gcd_nat.refl mult.right_neutral mult_0)\n*)\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\n  done\n\nlemma pomocna:\n  assumes \"is_gcd d a b\"\n  shows \"\\<exists>m n. m*a + n*b = d\"\n  sorry\n\nlemma pomocna_obrnuto:\n  assumes \"\\<exists>m n. m*a + n*b = d\"\n  shows \"is_gcd d a b\"\n  sorry\n\n\n(* Dokaz da je nzd (a/d, b/d) = 1, ako su a, b > 0 i d = nzd(a, b). *)\nlemma\n  fixes d::nat\n  assumes \"0 < a \\<and> 0 < b \\<and> is_gcd d a b\"\n  shows \"is_gcd 1 (a div d) (b div d)\"\nproof-\n  have \"(gcd a b) dvd a \\<and> (gcd a b) dvd b\"\n          unfolding gcd_deli_oba\n          by simp\n        hence \"\\<exists>m n. m*a + n*b = d\"\n          unfolding pomocna\n          using assms pomocna by auto\n        hence \"\\<exists>m n. m*(a div d) + n*(b div d) = 1\" sorry\n(*          unfolding pomocna\n          sledgehammer\n          by (metis Euclidean_Division.div_eq_0_iff Nat.add_0_right One_nat_def add.commute add.left_neutral add_Suc_right add_cancel_left_right add_less_cancel_left add_mult_distrib2 assms div_mult_self1_is_m div_mult_self_is_m dividend_less_div_times dividend_less_times_div dvd_add_times_triv_left_iff dvd_add_triv_right_iff dvd_mult_div_cancel dvd_refl gcd_nat.trans is_gcd_def less_add_same_cancel1 mult.assoc mult.commute mult.left_commute mult_0_right mult_cancel1 mult_is_0 mult_zero_right nat.simps(3) nat_0_less_mult_iff nat_add_right_cancel nat_dvd_not_less nat_mult_1 nat_mult_1_right nat_mult_eq_1_iff nat_neq_iff neq0_conv not_less0 plus_nat.add_0 plus_nat.simps(2))\n  *)     \n        hence \"is_gcd 1 (a div d) (b div d)\"\n          unfolding pomocna_obrnuto\n          using pomocna_obrnuto by simp\n  thus ?thesis\n          by simp\nqed\n\n(* definicija *)\n\nabbreviation uzajamno_prosti where\n  \"uzajamno_prosti x y \\<equiv> is_gcd 1 x y\"\n\nlemma \n  fixes n a b :: nat\n  assumes \"is_gcd 1 a b\"\n  shows \"is_gcd 1 (a*a) (b*b)\"\nproof-\n  have \"\\<exists>m n. m*a + n*b = 1\"\n    unfolding pomocna\n    using assms pomocna by simp\n  hence \"\\<exists>m n. m*a = 1 - n*b\"\n    sledgehammer\n    by (metis add_diff_cancel_right')\n  hence \"\\<exists>m n. (m*a)^2  = (1 - n*b)^2\"\n    by simp\n  hence \"\\<exists>m n. m^2 * a^2  = 1 - 2*n*b + n^2*b^2\"\n    by (metis (no_types, lifting) Suc_1 even_add even_plus_one_iff gcd_jedinstven mult_2 numeral_One one_add_one one_power2 pomocna_obrnuto power_add_numeral power_one_right semiring_norm(2))\n  hence \"\\<exists>m n. 2*n*b - n^2*b^2 = 1 - m^2 * a^2\"\n       by (metis Suc_eq_plus1 add_cancel_left_left add_cancel_right_left assms id_apply gcd_jedinstven mult_eq_0_iff nat_1_eq_mult_iff of_nat_eq_id pomocna_obrnuto semiring_1_class.of_nat_simps(2) semiring_normalization_rules(4) zero_neq_one)\n     hence \"\\<exists>m n. b^2 * (2*n - n^2*b)^2 = (1 - m^2 * a^2)^2\"\n       by (metis Suc_eq_plus1 add_cancel_left_left add_cancel_right_left assms id_apply gcd_jedinstven mult_eq_0_iff nat_1_eq_mult_iff of_nat_eq_id pomocna_obrnuto semiring_1_class.of_nat_simps(2) semiring_normalization_rules(4) zero_neq_one)\n     hence \"\\<exists>m n. b^2 * (2*n - n^2*b)^2 = 1 - a * m^2 * a^2 + m^4 * a^4\"\n       by (metis Suc_eq_plus1 add_cancel_left_left add_cancel_right_left assms id_apply gcd_jedinstven mult_eq_0_iff nat_1_eq_mult_iff of_nat_eq_id pomocna_obrnuto semiring_1_class.of_nat_simps(2) semiring_normalization_rules(4) zero_neq_one)\n     hence \"\\<exists>m n. b^2 * (2*n - n^2*b)^2 + a * m^2 * a^2 - m^4 * a^4 = 1\"\n       by (metis Suc_eq_plus1 add_cancel_left_left add_cancel_right_left assms id_apply gcd_jedinstven mult_eq_0_iff nat_1_eq_mult_iff of_nat_eq_id pomocna_obrnuto semiring_1_class.of_nat_simps(2) semiring_normalization_rules(4) zero_neq_one)\n     hence \"\\<exists>m n. b^2 * (2*n - n^2*b)^2 + a^2 * (a * m^2 - m^4 * a^2) = 1\"\n       by (metis Suc_eq_plus1 add_cancel_left_left add_cancel_right_left assms id_apply gcd_jedinstven mult_eq_0_iff nat_1_eq_mult_iff of_nat_eq_id pomocna_obrnuto semiring_1_class.of_nat_simps(2) semiring_normalization_rules(4) zero_neq_one)\n     hence \"is_gcd 1 (a^2) (b^2)\"\n       by (metis Suc_eq_plus1 add_cancel_left_left add_cancel_right_left assms id_apply gcd_jedinstven mult_eq_0_iff nat_1_eq_mult_iff of_nat_eq_id pomocna_obrnuto semiring_1_class.of_nat_simps(2) semiring_normalization_rules(4) zero_neq_one)\n     thus ?thesis\n       by (simp add: semiring_normalization_rules(29))\n   qed\n\n(* Ako je gcd(a,n) = 1 \\<and> gcd(b,n) = 1, onda je gcd(ab,n) = 1. *)\nlemma\n  assumes \"is_gcd 1 a n \\<and> is_gcd 1 b n\"\n  shows \"is_gcd 1 (a*b) n\"\nproof-\n  have *: \"\\<exists> x y. a*x + n*y = 1\"\n    unfolding pomocna\n    by (metis assms mult.commute pomocna)\n  have **: \"\\<exists> z w. b*z + n*w = 1\"\n    by (metis assms mult.commute pomocna)\n  hence \"\\<exists> x y z w. (a*x + n*y) * (b*z + n*w) = 1 * 1\"\n  using \"*\" \"**\" by auto\n  hence \"\\<exists> x y z w. a*b*x*z + a*x*n*w + b*z*n*y + (n^2)*y*w = 1 * 1\"\n  by (metis One_nat_def even_plus_one_iff is_gcd_def mult_eq_1_iff one_add_one pomocna_obrnuto)\n  hence \"\\<exists> x y z w. a*b*(x*z) + n*(a*x*w + b*z*y + n*y*w) = 1\"\n    by (metis even_plus_one_iff is_gcd_def nat_1_eq_mult_iff one_add_one pomocna_obrnuto)\n  hence \"is_gcd 1 (a*b) n\"\n    by (metis mult.commute pomocna_obrnuto)\n     thus ?thesis\n       by simp\n   qed\n\n\n\nlemma\n  fixes n a b :: nat\n  assumes \"a dvd (b*c) \\<and> is_gcd 1 a b\"\n  shows \"a dvd c\"\nproof-\n  have \"\\<exists> x y. a*x + b*y = 1\"\n    by (metis assms mult.commute pomocna)\n  have *: \"\\<exists> x y. a*x*c + b*y*c = 1*c\"\n    by (metis \\<open>\\<exists>x y. a * x + b * y = 1\\<close> add_mult_distrib nat_mult_1)\n  hence \"\\<exists> x. a dvd a*c*x \\<and> a dvd b*c\"\n    by (simp add: assms)\n  hence \"\\<exists> x y. a dvd b*c*y\"\n    by simp\n  hence \"\\<exists> x y. a dvd (a*c*x + b*c*y)\"\n    by (metis add.commute add_cancel_right_left dvdI mult.assoc mult.commute mult_0 mult_0_right)\n  hence \"a dvd c\"\n    by (metis (no_types, hide_lams) add_cancel_right_left dvd_mult2 is_gcd_def gcd_jedinstven mult.right_neutral mult_0_right nat_mult_1 pomocna_obrnuto)\n  thus ?thesis\n    by simp\nqed\n\n(* 11|6^(2n)+3^(n+2)+3^n *)\n\nlemma deljivost_sa_11:\n  fixes n :: nat\nshows \"(11::nat) dvd (6^(2*n::nat) + 3^(n+2) + 3^n)\"\nproof (induction n)\n  case 0\n  then show ?case by simp\nnext\n  case (Suc n)\n  show ?case\n  proof -\n  (* [[show_types]] *)\n  (* mora da bude oblika nesto = nesto *)\n    have \"(6::nat)^(2*(Suc n)) + 3^((Suc n) + 2) + 3^ (Suc n) = 6^(2*(n + 1)) + 3^((n + 1) + 2) + 3^ (n + 1)\"\n  (*using [[show_types]] --- pokazuje da mora da se doda nat na pocetku *)\n      by simp\n    also have \"... = 6^(2*n+2) + 3^(n+2)*3 + 3^n*3\"\n      by (simp add: algebra_simps power_add)\n    also have \"... = 6^(2*n) * 6^2 + 3^(n + 2) * 3 + 3^n * 3\"\n      by (simp add: algebra_simps)\n    also have \"... = 6^(2*n) * 36 + 3 * 3^(n + 2) + 3 * 3^n\"\n      by (simp add: algebra_simps)\n    also have \"... = 36 * 6^(2*n) + 3 * 3^(n + 2) + 3 * 3^n\"\n      by (simp add: algebra_simps)\n    also have \"... = 36 * 6^(2*n) + (36-33) * 3^(n + 2) + (36-33) * 3^n\"\n      by (simp add: algebra_simps)\n    also have \"... = 36 * 6^(2*n) + 36 * 3^(n + 2) - 33 * 3^(n + 2) + 36 * 3^n - 33 * 3^n\"\n      by (simp add: algebra_simps)\n    also have \"... = 36 * (6^(2*n) + 3^(n + 2) + 3^n) - 33 * (3^(n + 2) + 3^n)\"\n      by (simp add: algebra_simps)\n    also have \"... = 36 * (6^(2*n) + 3^(n + 2) + 3^n) - 11 * 3 * (3^(n + 2) + 3^n)\"\n      by (simp add: algebra_simps)\n    also have \"... = (36::nat) * (6^(2*n) + 3^(n + 2) + 3^n) - 11 * (3^(n + 3) + 3^(n+1))\"\n      by (simp add: algebra_simps power_add)\n    finally show ?case\n      \n  (* sledgehammer *)\n      by (smt Suc.IH dvd_diff_nat dvd_trans dvd_triv_left dvd_triv_right)\n  qed\nqed\n\nend", "meta": {"author": "jovanape", "repo": "Greatest_common_divisor", "sha": "7073ce157181251e14cf541148422040372654da", "save_path": "github-repos/isabelle/jovanape-Greatest_common_divisor", "path": "github-repos/isabelle/jovanape-Greatest_common_divisor/Greatest_common_divisor-7073ce157181251e14cf541148422040372654da/Najveci_zajednicki_delilac.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528170040853, "lm_q2_score": 0.8438950986284991, "lm_q1q2_score": 0.7189588065324902}}
{"text": "\\<^marker>\\<open>creator \"Kevin Kappelmann\"\\<close>\nsubsection \\<open>Transitive\\<close>\ntheory SBinary_Relations_Transitive\n  imports\n    Pairs\nbegin\n\ndefinition \"transitive D R \\<equiv> \\<forall>x y z \\<in> D. \\<langle>x, y\\<rangle> \\<in> R \\<and> \\<langle>y, z\\<rangle> \\<in> R \\<longrightarrow> \\<langle>x, z\\<rangle> \\<in> R\"\n\nlemma transitiveI [intro]:\n  assumes\n    \"\\<And>x y z. x \\<in> D \\<Longrightarrow> y \\<in> D \\<Longrightarrow> z \\<in> D \\<Longrightarrow> \\<langle>x, y\\<rangle> \\<in> R \\<Longrightarrow> \\<langle>y, z\\<rangle> \\<in> R \\<Longrightarrow> \\<langle>x, z\\<rangle> \\<in> R\"\n  shows \"transitive D R\"\n  using assms unfolding transitive_def by blast\n\nlemma transitiveD:\n  assumes \"transitive D R\"\n  and \"x \\<in> D\" \"y \\<in> D\" \"z \\<in> D\"\n  and \"\\<langle>x, y\\<rangle> \\<in> R\" \"\\<langle>y, z\\<rangle> \\<in> R\"\n  shows \"\\<langle>x, z\\<rangle> \\<in> R\"\n  using assms unfolding transitive_def by blast\n\n\nend", "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/HOTG/Binary_Relations/Properties/SBinary_Relations_Transitive.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951104066293, "lm_q2_score": 0.8519528019683106, "lm_q1q2_score": 0.7189588038782847}}
{"text": "theory Exercise3p12\nimports AExp\nbegin\n\n(* Exercise 3.12. \n\nThis 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 (all others).\n Define a compiler pretty much as explained above except that the compiled code leaves the \nvalue of the expression in register 0. Prove that \n\nexec (comp a r) s rs 0 = aval a s. \n\n*)\n\n\ntype_synonym reg = nat \n\ndatatype instr = LDI0 val | LD0 vname | MV0 reg | ADD0 reg\n\nfun exec1 :: \"instr \\<Rightarrow> state \\<Rightarrow> (reg \\<Rightarrow> int) \\<Rightarrow> reg \\<Rightarrow> int\" where\n  \"exec1 (LDI0 i) s rs = rs (0 := i)\"  | \n  \"exec1 (LD0 x)  s rs = rs (0 := s x)\" |\n  \"exec1 (MV0 r)  s rs = rs (r := rs 0)\" |\n  \"exec1 (ADD0 r) s rs = rs (0 := rs 0 + rs r)\"  \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 (ADD0 1) <> <0 := 1, 1 := 2> 0\"\n    \n(* r is the top of the stack. Leave registers < r alone *)\nfun comp :: \"aexp \\<Rightarrow> reg \\<Rightarrow> instr list\" where\n  \"comp (N n) r = [LDI0 n]\" |\n  \"comp (V x) r = [LD0  x]\" |\n(* We put intermediate computations in r+1, r+2 so that comp (Plus a1 a2) 0 is valid\n   If we didn't then \"comp2 a2\" overwrites the intermediate result that is sitting in 0 \n   Alternatively we could just prove a result where we have r > 0 as a precondition.\n *)\n  \"comp (Plus a1 a2) r = comp a1 (r+1) @ [MV0 (r+1)] @ comp a2 (r+2) @ [ADD0 (r+1)]\"\n\nvalue \"comp (Plus (N 1) (V ''x'')) 0\"\nvalue \"exec [LDI0 1, MV0 0, LD0 ''x''] <''x'' := 10> <> 0\"\nvalue \"exec (comp (Plus (N 1) (V ''x'')) 0) <''x'' := 10> <> 0\"\n\n\n\nlemma \"exec (comp a r) s rs 0 = aval a s\"\n  apply (induction a arbitrary: r rs)\n    apply (auto)\n    done\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/Exercise3p12.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528019683106, "lm_q2_score": 0.843895106480586, "lm_q1q2_score": 0.718958800533481}}
{"text": "theory PracticeIsar \n  imports Main\nbegin\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 simp: surj_def)\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 simp: 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\n    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\nlemma \"length (tl xs) = length xs - 1\"\nproof (cases xs)\n  case Nil\n  then show ?thesis by simp\nnext\n  case (Cons a list)\n  then show ?thesis by simp\nqed\n\nlemma \"\\<Sum>{0..n::nat} = n*(n+1) div 2\" (is \"?P n\")\nproof (induction n)\n  case 0\n  then show ?case 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 (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", "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/PracticeIsar.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528019683105, "lm_q2_score": 0.843895106480586, "lm_q1q2_score": 0.7189588005334809}}
{"text": "\\<^marker>\\<open>creator \"Kevin Kappelmann\"\\<close>\nsubsection \\<open>Preorders\\<close>\ntheory Preorders\n  imports\n    Binary_Relations_Reflexive\n    Binary_Relations_Transitive\nbegin\n\ndefinition \"preorder_on P R \\<equiv> reflexive_on P R \\<and> transitive_on P R\"\n\nlemma preorder_onI [intro]:\n  assumes \"reflexive_on P R\"\n  and \"transitive_on P R\"\n  shows \"preorder_on P R\"\n  unfolding preorder_on_def using assms by blast\n\nlemma preorder_onE [elim]:\n  assumes \"preorder_on P R\"\n  obtains \"reflexive_on P R\" \"transitive_on P R\"\n  using assms unfolding preorder_on_def by blast\n\nlemma reflexive_on_if_preorder_on:\n  assumes \"preorder_on P R\"\n  shows \"reflexive_on P R\"\n  using assms by (elim preorder_onE)\n\nlemma transitive_on_if_preorder_on:\n  assumes \"preorder_on P R\"\n  shows \"transitive_on P R\"\n  using assms by (elim preorder_onE)\n\nlemma transitive_if_preorder_on_in_field:\n  assumes \"preorder_on (in_field R) R\"\n  shows \"transitive R\"\n  using assms by (elim preorder_onE) (rule transitive_if_transitive_on_in_field)\n\ncorollary preorder_on_in_fieldE [elim]:\n  assumes \"preorder_on (in_field R) R\"\n  obtains \"reflexive_on (in_field R) R\" \"transitive R\"\n  using assms\n  by (blast dest: reflexive_on_if_preorder_on transitive_if_preorder_on_in_field)\n\nlemma preorder_on_rel_inv_if_preorder_on [iff]:\n  \"preorder_on P R\\<inverse> \\<longleftrightarrow> preorder_on (P :: 'a \\<Rightarrow> bool) (R :: 'a \\<Rightarrow> _)\"\n  by auto\n\nlemma rel_if_all_rel_if_rel_if_reflexive_on:\n  assumes \"reflexive_on P R\"\n  and \"\\<And>z. P z \\<Longrightarrow> R x z \\<Longrightarrow> R y z\"\n  and \"P x\"\n  shows \"R y x\"\n  using assms by blast\n\nlemma rel_if_all_rel_if_rel_if_reflexive_on':\n  assumes \"reflexive_on P R\"\n  and \"\\<And>z. P z \\<Longrightarrow> R z x \\<Longrightarrow> R z y\"\n  and \"P x\"\n  shows \"R x y\"\n  using assms by blast\n\ndefinition \"preorder (R :: 'a \\<Rightarrow> _) \\<equiv> preorder_on (\\<top> :: 'a \\<Rightarrow> bool) R\"\n\nlemma preorder_eq_preorder_on:\n  \"preorder (R :: 'a \\<Rightarrow> _) = preorder_on (\\<top> :: 'a \\<Rightarrow> bool) R\"\n  unfolding preorder_def ..\n\nlemma preorderI [intro]:\n  assumes \"reflexive R\"\n  and \"transitive R\"\n  shows \"preorder R\"\n  unfolding preorder_eq_preorder_on using assms\n  by (intro preorder_onI reflexive_on_if_reflexive transitive_on_if_transitive)\n\nlemma preorderE [elim]:\n  assumes \"preorder R\"\n  obtains \"reflexive R\" \"transitive R\"\n  using assms unfolding preorder_eq_preorder_on by (elim preorder_onE)\n  (simp only: reflexive_eq_reflexive_on transitive_eq_transitive_on)\n\nlemma preorder_on_if_preorder:\n  fixes P :: \"'a \\<Rightarrow> bool\" and R :: \"'a \\<Rightarrow> _\"\n  assumes \"preorder R\"\n  shows \"preorder_on P R\"\n  using assms by (elim preorderE)\n  (intro preorder_onI reflexive_on_if_reflexive transitive_on_if_transitive)\n\n\nsubsubsection \\<open>Instantiations\\<close>\n\nlemma preorder_eq: \"preorder (=)\"\n  using reflexive_eq transitive_eq by (rule preorderI)\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/Orders/Preorders.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527906914787, "lm_q2_score": 0.8438951045175643, "lm_q1q2_score": 0.718958789344616}}
{"text": "theory identity1 imports Complex_Main begin\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: \"m \\<ge> n \\<Longrightarrow> f(m) \\<ge> n\"\n  (*This key lemma is such a stroke of genius. How could anyone make this generalisation?*)\n  proof (induct n arbitrary: m)\n  case 0\n    then show ?case by simp\n  next\n    case (Suc n)\n    print_facts\n    hence \"m - 1 \\<ge> n\" by auto\n    hence \"f (m-1) \\<ge> n\" using Suc.hyps by auto\n    hence 1: \"f (f (m-1)) \\<ge> n\" using Suc.hyps by auto\n    have \"f m > f (f (m-1))\" using assms\n      by (metis One_nat_def Suc.prems Suc_diff_Suc Suc_le_D diff_zero less_Suc_eq_0_disj)\n    hence \"f m > n\" using 1 by auto\n    then show ?case by auto\n  qed }\n  hence \"\\<And>n. f n \\<ge> n\" by simp\n  hence \"\\<And>n. f (n+1) > f n\"\n    by (metis Suc_eq_plus1 \\<open>\\<And>na m. na \\<le> m \\<Longrightarrow> na \\<le> f m\\<close> discrete fff not_less_eq_eq)\n  hence \"f n < n + 1\"\n    by (metis Suc_eq_plus1 fff lift_Suc_mono_less_iff)\n  then show ?thesis\n    by (metis Suc_eq_plus1 \\<open>\\<And>n. n \\<le> f n\\<close> less_antisym not_le)\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/FunWithFunctions/identity1.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297967961707, "lm_q2_score": 0.7981867753392728, "lm_q1q2_score": 0.7187909746016662}}
{"text": "\ntheory Group_Theory imports Set_Theory begin\n\nhide_const monoid\nhide_const semigroup\nhide_const group\nhide_const inverse\n\nno_notation quotient (infixl \"'/'/\" 90)\n\nsection \\<open>Semigroups\\<close>\n\nlocale semigroup =\n  fixes M and composition (infixl \"\\<cdot>\" 70)\n  assumes composition_closed [intro, simp]: \"\\<lbrakk> a \\<in> M; b \\<in> M \\<rbrakk> \\<Longrightarrow> a \\<cdot> b \\<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\nlocale subsemigroup = semigroup M \"(\\<cdot>)\"\n  for N and M and composition (infixl \"\\<cdot>\" 70) +\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\"\nbegin\n\nlemma sub [intro, simp]:\n  \"a \\<in> N \\<Longrightarrow> a \\<in> M\"\n  using subset by blast\n\nsublocale sub: semigroup N \"(\\<cdot>)\"\n  by unfold_locales (auto simp: sub_composition_closed)\n\nend (* subsemigroup *)\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  semigroup M \"(\\<cdot>)\" for M and composition (infixl \"\\<cdot>\" 70) and unit (\"\\<one>\") +\n  assumes unit_closed [intro, simp]: \"\\<one> \\<in> M\"\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 = subsemigroup N M \"(\\<cdot>)\" + monoid M \"(\\<cdot>)\" \\<one> \n  for N and M and composition (infixl \"\\<cdot>\" 70) and unit (\"\\<one>\") +\n  assumes sub_unit_closed: \"\\<one> \\<in> N\"\nbegin\n\ntext \\<open>p 29, ll 32--33\\<close>\nsublocale sub: monoid N \"(\\<cdot>)\" \\<one>\n  by unfold_locales (auto simp: 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\nlocale monoid_morphism = (* This is like homomorphism but lacks the commutes_with_unit axiom *)\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>' \\<eta> y = \\<eta> (x \\<cdot> y)\"\nbegin\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>Def 1.6\\<close>\ntext \\<open>p 58, l 33; p 59, ll 1--2\\<close>\nlocale monoid_homomorphism = monoid_morphism \\<eta>  M \"(\\<cdot>)\" \\<one> 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_unit: \"\\<eta> \\<one> = \\<one>'\"\n\ntext \\<open>Jacobson notes that @{thm [source] monoid_homomorphism.commutes_with_unit} is not necessary for groups, but doesn't make use of that later.\\<close>\n\nlocale monoid_isomorphism = bijective_map \\<eta> M M' + monoid_morphism\nbegin                                           \ntheorem commutes_with_unit: \"\\<eta> \\<one> = \\<one>'\"\nproof -\n  {\n    fix y assume \"y \\<in> M'\"\n    then obtain x where nxy:\"\\<eta> x = y\" \"x \\<in> M\" by (metis image_iff surjective)\n    then have \"\\<eta> x \\<cdot>' \\<eta> \\<one> = \\<eta> x\" using commutes_with_composition by auto\n    then have \"y \\<cdot>' \\<eta> \\<one> = y\" using nxy by auto\n  }\n  then show \"\\<eta> \\<one> = \\<one>'\" by fastforce\nqed \n\nsublocale hom: monoid_homomorphism \\<eta>  M \"(\\<cdot>)\" \\<one> M' \"(\\<cdot>')\" \"\\<one>'\"\n  by(unfold_locales, rule commutes_with_unit)\n  \nend (* monoid_isomorphism *)\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\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\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)\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\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 \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 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[symmetric] 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[symmetric] 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[symmetric] 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_morphism.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": "aleksander-mendoza", "repo": "Isabelle", "sha": "fa147735dc3e60a5fbcf2609958b9144e8242ac4", "save_path": "github-repos/isabelle/aleksander-mendoza-Isabelle", "path": "github-repos/isabelle/aleksander-mendoza-Isabelle/Isabelle-fa147735dc3e60a5fbcf2609958b9144e8242ac4/Group_Theory.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8791467548438124, "lm_q2_score": 0.8175744695262775, "lm_q1q2_score": 0.7187679417271783}}
{"text": "section \\<open>Fresh identifier generation for natural numbers\\<close>\n\ntheory Fresh_Nat\n  imports Fresh\nbegin\n\ntext \\<open>Assuming \\<open>x \\<le> y\\<close>, \\<open>fresh2 xs x y\\<close> returns an element\noutside the interval \\<open>(x,y)\\<close> that is fresh for \\<open>xs\\<close> and closest to this interval,\nfavoring smaller elements: \\<close>\n\nfunction fresh2 :: \"nat set \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> nat\" where\n\"fresh2 xs x y =\n (if x \\<notin> xs \\<or> infinite xs then x else\n  if y \\<notin> xs then y else\n  fresh2 xs (x-1) (y+1))\"\nby auto\ntermination\n  apply(relation \"measure (\\<lambda>(xs,x,y). (Max xs) + 1 - y)\")\n  by (simp_all add: Suc_diff_le)\n\nlemma fresh2_notIn: \"finite xs \\<Longrightarrow> fresh2 xs x y \\<notin> xs\"\n  by (induct xs x y rule: fresh2.induct) auto\n\nlemma fresh2_eq: \"x \\<notin> xs \\<Longrightarrow> fresh2 xs x y = x\"\n  by auto\n\ndeclare fresh2.simps[simp del]\n\ninstantiation nat :: fresh\nbegin\n\ntext \\<open>\\<open>fresh xs x y\\<close> returns an element\nthat is fresh for \\<open>xs\\<close> and closest to \\<open>x\\<close>, favoring smaller elements: \\<close>\n\ndefinition fresh_nat :: \"nat set \\<Rightarrow> nat \\<Rightarrow> nat\" where\n\"fresh_nat xs x \\<equiv> fresh2 xs x x\"\n\ninstance by standard (use fresh2_notIn fresh2_eq in \\<open>auto simp add: fresh_nat_def\\<close>)\n\nend (* instantiation *)\n\ntext \\<open>Code generation\\<close>\n\nlemma fresh2_list[code]:\n  \"fresh2 (set xs) x y =\n     (if x \\<notin> set xs then x else\n      if y \\<notin> set xs then y else\n      fresh2 (set xs) (x-1) (y+1))\"\n  by (auto simp: fresh2.simps)\n\ntext \\<open>Some tests: \\<close>\n\nvalue \"[fresh {} (1::nat),\n        fresh {3,5,2,4} 3]\"\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/Fresh_Identifiers/Fresh_Nat.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8670357598021708, "lm_q2_score": 0.8289388104343893, "lm_q1q2_score": 0.7187195913344884}}
{"text": "(*\n    Title:      Extension of Sturm's theorem for multiple roots\n    Author:     Wenda Li <wl302@cam.ac.uk / liwenda1990@hotmail.com>\n*)\n\nsection \\<open>Extension of Sturm's theorem for multiple roots\\<close>\n\ntheory Sturm_Multiple_Roots \n  imports\n    BF_Misc\nbegin\n\ntext \\<open>The classic Sturm's theorem is used to count real roots WITHOUT multiplicity of a polynomial within \n  an interval. Surprisingly, we can also extend Sturm's theorem to count real roots WITH \n  multiplicity by modifying the signed remainder sequence, which seems to be overlooked by many\n  textbooks. \n\n  Our formal proof is inspired by Theorem 10.5.6 in \n    Rahman, Q.I., Schmeisser, G.: Analytic Theory of Polynomials. Oxford University Press (2002).\n\\<close>\n\nsubsection \\<open>More results for @{term smods}\\<close>\n\nlemma last_smods_gcd:\n  fixes p q ::\"real poly\"\n  defines \"pp \\<equiv> last (smods p q)\" \n  assumes \"p\\<noteq>0\"\n  shows \"pp = smult (lead_coeff pp) (gcd p q)\"\n  using \\<open>p\\<noteq>0\\<close> unfolding pp_def\nproof (induct \"smods p q\" arbitrary:p q rule:length_induct)\n  case 1\n  have ?case when \"q=0\"\n    using that smult_normalize_field_eq \\<open>p\\<noteq>0\\<close> by auto\n  moreover have ?case when \"q\\<noteq>0\"\n  proof -\n    define r where \"r= - (p mod q)\"\n    have smods_cons:\"smods p q = p # smods q r\"\n      unfolding r_def using \\<open>p\\<noteq>0\\<close> by simp\n    have \"last (smods q r) = smult (lead_coeff (last (smods q r))) (gcd q r)\"\n      apply (rule 1(1)[rule_format,of \"smods q r\" q r])\n      using smods_cons \\<open>q\\<noteq>0\\<close> by auto\n    moreover have \"gcd p q = gcd q r\"\n      unfolding r_def by (simp add: gcd.commute that)\n    ultimately show ?thesis unfolding smods_cons using \\<open>q\\<noteq>0\\<close>\n      by simp\n  qed\n  ultimately show ?case by argo\nqed\n\nlemma last_smods_nzero:\n  assumes \"p\\<noteq>0\"\n  shows \"last (smods p q) \\<noteq>0\"\n  by (metis assms last_in_set no_0_in_smods smods_nil_eq)\n\nsubsection \\<open>Alternative signed remainder sequences\\<close>\n\nfunction smods_ext::\"real poly \\<Rightarrow> real poly \\<Rightarrow> real poly list\" where \n  \"smods_ext p q = (if p=0 then [] else\n                      (if p mod q \\<noteq> 0  \n                        then Cons p (smods_ext q (-(p mod q))) \n                        else Cons p (smods_ext q (pderiv q)))\n                   )\"\n  by auto\ntermination\n  apply (relation \"measure (\\<lambda>(p,q).if p=0 then 0 else if q=0 then 1 else 2+degree q)\")\n  using degree_mod_less by (auto simp add:degree_pderiv pderiv_eq_0_iff)\n\nlemma smods_ext_prefix:\n  fixes p q::\"real poly\"\n  defines \"pp \\<equiv> last (smods p q)\" \n  assumes \"p\\<noteq>0\" \"q\\<noteq>0\"\n  shows \"smods_ext p q = smods p q @ tl (smods_ext pp (pderiv pp))\"\n  unfolding pp_def using assms(2,3)\nproof (induct \"smods_ext p q\" arbitrary:p q rule:length_induct)\n  case 1\n  have ?case when \"p mod q \\<noteq>0\"\n  proof -\n    define pp where \"pp=last (smods q (- (p mod q)))\"\n    have smods_cons:\"smods p q = p# smods q (- (p mod q))\"\n      using \\<open>p\\<noteq>0\\<close> by auto\n    then have pp_last:\"pp=last (smods p q)\" unfolding pp_def\n      by (simp add: \"1.prems\"(2) pp_def)\n    have smods_ext_cons:\"smods_ext p q = p # smods_ext q (- (p mod q))\"\n      using that \\<open>p\\<noteq>0\\<close> by auto\n    have \"smods_ext q (- (p mod q)) = smods q (- (p mod q)) @ tl (smods_ext pp (pderiv pp))\"\n      apply (rule 1(1)[rule_format,of \"smods_ext q (- (p mod q))\" q \"- (p mod q)\",folded pp_def])\n      using smods_ext_cons \\<open>q\\<noteq>0\\<close> that by auto\n    then show ?thesis unfolding pp_last\n      apply (subst smods_cons)\n      apply (subst smods_ext_cons)\n      by auto\n  qed\n  moreover have ?case when \"p mod q =0\" \"pderiv q = 0\"\n  proof -\n    have \"smods p q = [p,q]\"\n      using \\<open>p\\<noteq>0\\<close> \\<open>q\\<noteq>0\\<close> that by auto\n    moreover have \"smods_ext p q = [p,q]\"\n      using that \\<open>p\\<noteq>0\\<close> by auto\n    ultimately show ?case using \\<open>p\\<noteq>0\\<close> \\<open>q\\<noteq>0\\<close> that(1) by auto\n  qed\n  moreover have ?case when \"p mod q =0\" \"pderiv q \\<noteq> 0\"\n  proof -\n    have smods_cons:\"smods p q = [p,q]\"\n      using \\<open>p\\<noteq>0\\<close> \\<open>q\\<noteq>0\\<close> that by auto\n    have smods_ext_cons:\"smods_ext p q = p#smods_ext q (pderiv q)\"\n      using that \\<open>p\\<noteq>0\\<close> by auto\n    show ?case unfolding smods_cons smods_ext_cons\n      apply (simp del:smods_ext.simps)\n      by (simp add: \"1.prems\"(2))\n  qed\n  ultimately show ?case by argo\nqed\n\nlemma no_0_in_smods_ext: \"0\\<notin>set (smods_ext p q)\"\n  apply (induct \"smods_ext p q\" arbitrary:p q)\n   apply simp\n  by (metis list.distinct(1) list.inject set_ConsD smods_ext.simps)\n\nsubsection \\<open>Sign variations on the alternative signed remainder sequences\\<close>\n\ndefinition changes_itv_smods_ext:: \"real \\<Rightarrow> real \\<Rightarrow>real poly \\<Rightarrow> real poly \\<Rightarrow>  int\" where\n  \"changes_itv_smods_ext a b p q= (let ps= smods_ext p q in changes_poly_at ps a \n        - changes_poly_at ps b)\"\n\ndefinition changes_gt_smods_ext:: \"real \\<Rightarrow>real poly \\<Rightarrow> real poly \\<Rightarrow>  int\" where\n  \"changes_gt_smods_ext a p q= (let ps= smods_ext p q in changes_poly_at ps a \n        - changes_poly_pos_inf ps)\"\n\ndefinition changes_le_smods_ext:: \"real \\<Rightarrow>real poly \\<Rightarrow> real poly \\<Rightarrow>  int\" where\n  \"changes_le_smods_ext b p q= (let ps= smods_ext p q in changes_poly_neg_inf ps \n        - changes_poly_at ps b)\"\n\ndefinition changes_R_smods_ext:: \"real poly \\<Rightarrow> real poly \\<Rightarrow>  int\" where\n  \"changes_R_smods_ext p q= (let ps= smods_ext p q in changes_poly_neg_inf ps \n        - changes_poly_pos_inf ps)\"\n\nsubsection \\<open>Extension of Sturm's theorem for multiple roots\\<close>\n\ntheorem sturm_ext_interval:\n  assumes \"a<b\" \"poly p a\\<noteq>0\" \"poly p b\\<noteq>0\"\n  shows \"proots_count p {x. a<x \\<and> x<b} = changes_itv_smods_ext a b p (pderiv p)\"\n  using assms(2,3)\nproof (induct \"smods_ext p (pderiv p)\" arbitrary:p rule:length_induct)\n  case 1\n  have \"p\\<noteq>0\" using \\<open>poly p a \\<noteq> 0\\<close> by auto \n  have ?case when \"pderiv p=0\"\n  proof -\n    obtain c where \"p=[:c:]\" \"c\\<noteq>0\"\n      using \\<open>p\\<noteq>0\\<close> \\<open>pderiv p = 0\\<close> pderiv_iszero by force\n    then have \"proots_count p {x. a < x \\<and> x < b} = 0\"\n      unfolding proots_count_def by auto\n    moreover have \"changes_itv_smods_ext a b p (pderiv p) = 0\"\n      unfolding changes_itv_smods_ext_def using \\<open>p=[:c:]\\<close> \\<open>c\\<noteq>0\\<close> by auto\n    ultimately show ?thesis by auto\n  qed\n  moreover have ?case when \"pderiv p\\<noteq>0\"\n  proof -\n    define pp where \"pp = last (smods p (pderiv p))\"\n    define lp where \"lp = lead_coeff pp\"\n    define S where \"S={x. a < x \\<and> x< b}\"\n\n    have prefix:\"smods_ext p (pderiv p) = smods p (pderiv p) @ tl (smods_ext pp (pderiv pp))\"\n      using smods_ext_prefix[OF \\<open>p\\<noteq>0\\<close> \\<open>pderiv p\\<noteq>0\\<close>,folded pp_def] .\n    have pp_gcd:\"pp = smult lp (gcd p (pderiv p))\"\n      using last_smods_gcd[OF \\<open>p\\<noteq>0\\<close>,of \"pderiv p\",folded pp_def lp_def] .\n    have \"pp\\<noteq>0\" \"lp\\<noteq>0\" unfolding pp_def lp_def\n      subgoal by (rule last_smods_nzero[OF \\<open>p\\<noteq>0\\<close>])\n      subgoal using \\<open>last (smods p (pderiv p)) \\<noteq> 0\\<close> by auto\n      done\n    have \"poly pp a\\<noteq>0\" \"poly pp b \\<noteq> 0\"\n      unfolding pp_gcd using \\<open>poly p a\\<noteq>0\\<close> \\<open>poly p b\\<noteq>0\\<close> \\<open>lp\\<noteq>0\\<close> \n      by (simp_all add:poly_gcd_0_iff)\n\n    have \"proots_count pp S = changes_itv_smods_ext a b pp (pderiv pp)\" unfolding S_def\n    proof (rule 1(1)[rule_format,of \"smods_ext pp (pderiv pp)\" pp])\n      show \"length (smods_ext pp (pderiv pp)) < length (smods_ext p (pderiv p))\"\n        unfolding prefix by (simp add: \\<open>p \\<noteq> 0\\<close> that)\n    qed (use \\<open>poly pp a\\<noteq>0\\<close> \\<open>poly pp b\\<noteq>0\\<close> in simp_all)\n    moreover have \"proots_count p S = card (proots_within p S) + proots_count pp S\"\n    proof -\n      have \"(\\<Sum>r\\<in>proots_within p S. order r p) = (\\<Sum>r\\<in> proots_within p S. order r pp + 1)\"\n      proof (rule sum.cong)\n        fix x assume \"x \\<in> proots_within p S\"\n        have \"order x pp = order x (gcd p (pderiv p))\"\n          unfolding pp_gcd using \\<open>lp\\<noteq>0\\<close> by (simp add:order_smult)\n        also have \"... = min (order x p) (order x (pderiv p))\"\n          apply (subst order_gcd)\n          using \\<open>p\\<noteq>0\\<close> \\<open>pderiv p\\<noteq>0\\<close> by simp_all\n        also have \"... = order x (pderiv p)\"\n          apply (subst order_pderiv)\n          using \\<open>pderiv p\\<noteq>0\\<close> \\<open>p \\<noteq> 0\\<close> \\<open>x \\<in> proots_within p S\\<close> order_root by auto\n        finally have \"order x pp = order x (pderiv p)\" .\n        moreover have \"order x p = order x (pderiv p) + 1\"\n          apply (subst order_pderiv)\n          using \\<open>pderiv p\\<noteq>0\\<close> \\<open>p \\<noteq> 0\\<close> \\<open>x \\<in> proots_within p S\\<close> order_root by auto\n        ultimately show \"order x p = order x pp + 1\" by auto\n      qed simp\n      also have \"... = card (proots_within p S) + (\\<Sum>r\\<in> proots_within p S. order r pp)\"\n        apply (subst sum.distrib)\n        by auto\n      also have \"... = card (proots_within p S) + (\\<Sum>r\\<in> proots_within pp S. order r pp)\"\n      proof -\n        have \"(\\<Sum>r\\<in>proots_within p S. order r pp) = (\\<Sum>r\\<in>proots_within pp S. order r pp)\"\n          apply (rule sum.mono_neutral_right)\n          subgoal using \\<open>p\\<noteq>0\\<close> by auto\n          subgoal unfolding pp_gcd using \\<open>lp\\<noteq>0\\<close> by (auto simp:poly_gcd_0_iff)\n          subgoal unfolding pp_gcd using \\<open>lp\\<noteq>0\\<close> \n            apply (auto simp:poly_gcd_0_iff order_smult)\n            apply (subst order_gcd)\n            by (auto simp add: order_root)\n          done\n        then show ?thesis by simp\n      qed\n      finally show ?thesis unfolding proots_count_def .\n    qed\n    moreover have \"card (proots_within p S) = changes_itv_smods a b p (pderiv p)\" \n      using sturm_interval[OF \\<open>a<b\\<close> \\<open>poly p a\\<noteq>0\\<close> \\<open>poly p b\\<noteq>0\\<close>,symmetric] \n      unfolding S_def proots_within_def \n      by (auto intro!:arg_cong[where f=card])\n    moreover have \"changes_itv_smods_ext a b p (pderiv p) \n            = changes_itv_smods a b p (pderiv p) + changes_itv_smods_ext a b pp (pderiv pp)\"\n    proof -\n      define xs ys where \"xs=smods p (pderiv p)\" and \"ys=smods_ext pp (pderiv pp)\"\n      have xys: \"xs\\<noteq>[]\" \"ys\\<noteq>[]\" \"last xs=hd ys\" \"poly (last xs) a\\<noteq>0\" \"poly (last xs) b\\<noteq>0\"\n        subgoal unfolding xs_def using \\<open>p\\<noteq>0\\<close> by auto\n        subgoal unfolding ys_def using \\<open>pp\\<noteq>0\\<close> by auto\n        subgoal using \\<open>pp\\<noteq>0\\<close> unfolding xs_def ys_def \n          apply (fold pp_def)\n          by auto\n        subgoal using \\<open>poly pp a\\<noteq>0\\<close> unfolding pp_def xs_def .\n        subgoal using \\<open>poly pp b\\<noteq>0\\<close> unfolding pp_def xs_def .\n        done\n      have \"changes_poly_at (xs @ tl ys) a = changes_poly_at xs a + changes_poly_at ys a\"\n      proof -\n        have \"changes_poly_at (xs @ tl ys) a  = changes_poly_at (xs @ ys) a\"\n          unfolding changes_poly_at_def\n          apply (simp add:map_tl)\n          apply (subst changes_drop_dup[symmetric])\n          using that xys by (auto simp add: hd_map last_map)\n        also have \"... = changes_poly_at xs a + changes_poly_at ys a\"\n          unfolding changes_poly_at_def\n          apply (subst changes_append[symmetric])\n          using xys by (auto simp add: hd_map last_map)\n        finally show ?thesis .\n      qed\n      moreover have \"changes_poly_at (xs @ tl ys) b = changes_poly_at xs b + changes_poly_at ys b\"\n      proof -\n        have \"changes_poly_at (xs @ tl ys) b  = changes_poly_at (xs @ ys) b\"\n          unfolding changes_poly_at_def\n          apply (simp add:map_tl)\n          apply (subst changes_drop_dup[symmetric])\n          using that xys by (auto simp add: hd_map last_map)\n        also have \"... = changes_poly_at xs b + changes_poly_at ys b\"\n          unfolding changes_poly_at_def\n          apply (subst changes_append[symmetric])\n          using xys by (auto simp add: hd_map last_map)\n        finally show ?thesis .\n      qed\n      ultimately show ?thesis unfolding changes_itv_smods_ext_def changes_itv_smods_def\n        apply (fold xs_def ys_def,unfold prefix[folded xs_def ys_def] Let_def)\n        by auto\n    qed\n    ultimately show \"proots_count p S = changes_itv_smods_ext a b p (pderiv p)\"\n      by auto\n  qed\n  ultimately show ?case by argo\nqed\n\ntheorem sturm_ext_above:\n  assumes \"poly p a\\<noteq>0\" \n  shows \"proots_count p {x. a<x} = changes_gt_smods_ext a p (pderiv p)\"\nproof -\n  define ps where \"ps\\<equiv>smods_ext p (pderiv p)\"\n  have \"p\\<noteq>0\" and \"p\\<in>set ps\" using \\<open>poly p a\\<noteq>0\\<close> ps_def by auto\n  obtain ub where ub:\"\\<forall>p\\<in>set ps. \\<forall>x. poly p x=0 \\<longrightarrow> x<ub\"\n    and ub_sgn:\"\\<forall>x\\<ge>ub. \\<forall>p\\<in>set ps. sgn (poly p x) = sgn_pos_inf p\"\n    and \"ub>a\"\n    using root_list_ub[OF no_0_in_smods_ext,of p \"pderiv p\",folded ps_def]\n    by auto\n  have \"proots_count p {x. a<x} = proots_count p {x. a<x \\<and> x<ub}\"\n    unfolding proots_count_def\n    apply (rule sum.cong)\n    by (use ub \\<open>p\\<in>set ps\\<close> in auto)\n  moreover have \"changes_gt_smods_ext a p (pderiv p) = changes_itv_smods_ext a ub p (pderiv p)\"\n  proof -\n    have \"map (sgn \\<circ> (\\<lambda>p. poly p ub)) ps = map sgn_pos_inf ps\"\n      using ub_sgn[THEN spec,of ub,simplified] \n      by (metis (mono_tags, lifting) comp_def list.map_cong0)\n    hence \"changes_poly_at ps ub=changes_poly_pos_inf ps\"\n      unfolding changes_poly_pos_inf_def changes_poly_at_def\n      by (subst changes_map_sgn_eq,metis map_map)\n    thus ?thesis unfolding changes_gt_smods_ext_def changes_itv_smods_ext_def ps_def\n      by metis\n  qed\n  moreover have \"poly p ub\\<noteq>0\" using ub \\<open>p\\<in>set ps\\<close> by auto\n  ultimately show ?thesis using sturm_ext_interval[OF \\<open>ub>a\\<close> assms] by auto\nqed\n\ntheorem sturm_ext_below:\n  assumes \"poly p b\\<noteq>0\" \n  shows \"proots_count p {x. x<b} = changes_le_smods_ext b p (pderiv p)\"\nproof -\n  define ps where \"ps\\<equiv>smods_ext p (pderiv p)\"\n  have \"p\\<noteq>0\" and \"p\\<in>set ps\" using \\<open>poly p b\\<noteq>0\\<close> ps_def by auto\n  obtain lb where lb:\"\\<forall>p\\<in>set ps. \\<forall>x. poly p x=0 \\<longrightarrow> x>lb\"\n    and lb_sgn:\"\\<forall>x\\<le>lb. \\<forall>p\\<in>set ps. sgn (poly p x) = sgn_neg_inf p\"\n    and \"lb<b\"\n    using root_list_lb[OF no_0_in_smods_ext,of p \"pderiv p\",folded ps_def] \n    by auto\n  have \"proots_count p {x. x<b} = proots_count p {x. lb<x \\<and> x<b}\"\n    unfolding proots_count_def by (rule sum.cong,insert lb \\<open>p\\<in>set ps\\<close>,auto)\n  moreover have \"changes_le_smods_ext b p (pderiv p) = changes_itv_smods_ext lb b p (pderiv p)\"\n  proof -\n    have \"map (sgn \\<circ> (\\<lambda>p. poly p lb)) ps = map sgn_neg_inf ps\"\n      using lb_sgn[THEN spec,of lb,simplified] \n      by (metis (mono_tags, lifting) comp_def list.map_cong0)\n    hence \"changes_poly_at ps lb=changes_poly_neg_inf ps\"\n      unfolding changes_poly_neg_inf_def changes_poly_at_def\n      by (subst changes_map_sgn_eq,metis map_map)\n    thus ?thesis unfolding changes_le_smods_ext_def changes_itv_smods_ext_def ps_def\n      by metis\n  qed\n  moreover have \"poly p lb\\<noteq>0\" using lb \\<open>p\\<in>set ps\\<close> by auto\n  ultimately show ?thesis using sturm_ext_interval[OF \\<open>lb<b\\<close> _ assms] by auto\nqed\n\ntheorem sturm_ext_R: \n  assumes \"p\\<noteq>0\"\n  shows \"proots_count p UNIV = changes_R_smods_ext p (pderiv p)\"\nproof - \n  define ps where \"ps\\<equiv>smods_ext p (pderiv p)\"\n  have \"p\\<in>set ps\" using ps_def \\<open>p\\<noteq>0\\<close> by auto\n  obtain lb where lb:\"\\<forall>p\\<in>set ps. \\<forall>x. poly p x=0 \\<longrightarrow> x>lb\"\n    and lb_sgn:\"\\<forall>x\\<le>lb. \\<forall>p\\<in>set ps. sgn (poly p x) = sgn_neg_inf p\"\n    and \"lb<0\"\n    using root_list_lb[OF no_0_in_smods_ext,of p \"pderiv p\",folded ps_def] \n    by auto\n  obtain ub where ub:\"\\<forall>p\\<in>set ps. \\<forall>x. poly p x=0 \\<longrightarrow> x<ub\"\n    and ub_sgn:\"\\<forall>x\\<ge>ub. \\<forall>p\\<in>set ps. sgn (poly p x) = sgn_pos_inf p\"\n    and \"ub>0\"\n    using root_list_ub[OF no_0_in_smods_ext,of p \"pderiv p\",folded ps_def] \n    by auto\n  have \"proots_count p UNIV = proots_count p {x. lb<x \\<and> x<ub}\"\n    unfolding proots_count_def by (rule sum.cong,insert lb ub \\<open>p\\<in>set ps\\<close>,auto)\n  moreover have \"changes_R_smods_ext p (pderiv p) = changes_itv_smods_ext lb ub p (pderiv p)\"\n  proof -\n    have \"map (sgn \\<circ> (\\<lambda>p. poly p lb)) ps = map sgn_neg_inf ps\"\n      and \"map (sgn \\<circ> (\\<lambda>p. poly p ub)) ps = map sgn_pos_inf ps\"\n      using lb_sgn[THEN spec,of lb,simplified] ub_sgn[THEN spec,of ub,simplified] \n      by (metis (mono_tags, lifting) comp_def list.map_cong0)+\n    hence \"changes_poly_at ps lb=changes_poly_neg_inf ps\n          \\<and> changes_poly_at ps ub=changes_poly_pos_inf ps\"\n      unfolding changes_poly_neg_inf_def changes_poly_at_def changes_poly_pos_inf_def\n      by (subst (1 3)  changes_map_sgn_eq,metis map_map)\n    thus ?thesis unfolding changes_R_smods_ext_def changes_itv_smods_ext_def ps_def\n      by metis\n  qed\n  moreover have \"poly p lb\\<noteq>0\" and \"poly p ub\\<noteq>0\" using lb ub \\<open>p\\<in>set ps\\<close> by auto\n  moreover have \"lb<ub\" using \\<open>lb<0\\<close> \\<open>0<ub\\<close> by auto\n  ultimately show ?thesis using sturm_ext_interval 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/Budan_Fourier/Sturm_Multiple_Roots.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.82893881677331, "lm_q2_score": 0.8670357477770337, "lm_q1q2_score": 0.7187195868624564}}
{"text": "(*  Title:      Util_Div.thy\n    Date:       Oct 2006\n    Author:     David Trachtenherz\n*)\n\nsection \\<open>Results for division and modulo operators on integers\\<close>\n\ntheory Util_Div\nimports Util_Nat\nbegin\n\nsubsection \\<open>Additional (in-)equalities with \\<open>div\\<close> and \\<open>mod\\<close>\\<close>\n\ncorollary Suc_mod_le_divisor: \"0 < m \\<Longrightarrow> Suc (n mod m) \\<le> m\"\nby (rule Suc_leI, rule mod_less_divisor)\n\nlemma mod_less_dividend: \"\\<lbrakk> 0 < m; m \\<le> n \\<rbrakk> \\<Longrightarrow> n mod m < (n::nat)\"\nby (rule less_le_trans[OF mod_less_divisor])\n(*lemma mod_le_dividend: \"n mod m \\<le> (n::nat)\"*)\nlemmas mod_le_dividend = mod_less_eq_dividend\n\n\n\nlemma diff_mod_le: \"(t - r) mod m \\<le> (t::nat)\"\nby (rule le_trans[OF mod_le_dividend, OF diff_le_self])\n\n\n(*corollary div_mult_cancel: \"m div n * n = m - m mod (n::nat)\"*)\nlemmas div_mult_cancel = minus_mod_eq_div_mult [symmetric]\n\nlemma mod_0_div_mult_cancel: \"(n mod (m::nat) = 0) = (n div m * m = n)\"\napply (insert eq_diff_left_iff[OF mod_le_dividend le0, of n m])\napply (simp add: mult.commute minus_mod_eq_mult_div [symmetric])\ndone\n\nlemma div_mult_le: \"(n::nat) div m * m \\<le> n\"\nby (simp add: mult.commute minus_mod_eq_mult_div [symmetric])\nlemma less_div_Suc_mult: \"0 < (m::nat) \\<Longrightarrow> n < Suc (n div m) * m\"\napply (simp add: mult.commute minus_mod_eq_mult_div [symmetric])\napply (rule less_add_diff)\nby (rule mod_less_divisor)\n\nlemma nat_ge2_conv: \"((2::nat) \\<le> n) = (n \\<noteq> 0 \\<and> n \\<noteq> 1)\"\nby fastforce\n\nlemma Suc0_mod: \"m \\<noteq> Suc 0 \\<Longrightarrow> Suc 0 mod m = Suc 0\"\nby (case_tac m, simp_all)\ncorollary Suc0_mod_subst: \"\n  \\<lbrakk> m \\<noteq> Suc 0; P (Suc 0) \\<rbrakk> \\<Longrightarrow> P (Suc 0 mod m)\"\nby (blast intro: subst[OF Suc0_mod[symmetric]])\ncorollary Suc0_mod_cong: \"\n  m \\<noteq> Suc 0 \\<Longrightarrow> f (Suc 0 mod m) = f (Suc 0)\"\nby (blast intro: arg_cong[OF Suc0_mod])\n\n\nsubsection \\<open>Additional results for addition and subtraction with \\<open>mod\\<close>\\<close>\n\nlemma mod_Suc_conv: \"\n  ((Suc a) mod m = (Suc b) mod m) = (a mod m = b mod m)\"\nby (simp add: mod_Suc)\n\nlemma mod_Suc': \"\n  0 < n \\<Longrightarrow> Suc m mod n = (if m mod n < n - Suc 0 then Suc (m mod n) else 0)\"\napply (simp add: mod_Suc)\napply (intro conjI impI)\n apply simp\napply (insert le_neq_trans[OF mod_less_divisor[THEN Suc_leI, of n m]], simp)\ndone\n\nlemma mod_add:\"\n  ((a + k) mod m = (b + k) mod m) =\n  ((a::nat) mod m = b mod m)\"\nby (induct \"k\", simp_all add: mod_Suc_conv)\n\ncorollary mod_sub_add: \"\n  k \\<le> (a::nat) \\<Longrightarrow>\n  ((a - k) mod m = b mod m) = (a mod m = (b + k) mod m)\"\nby (simp add: mod_add[where m=m and a=\"a-k\" and b=b and k=k, symmetric])\n\n\nlemma mod_sub_eq_mod_0_conv: \"\n  a + b \\<le> (n::nat) \\<Longrightarrow>\n  ((n - a) mod m = b mod m) = ((n - (a + b)) mod m = 0)\"\nby (insert mod_add[of \"n-(a+b)\" b m 0], simp)\nlemma mod_sub_eq_mod_swap: \"\n  \\<lbrakk> a \\<le> (n::nat); b \\<le> n \\<rbrakk> \\<Longrightarrow>\n  ((n - a) mod m = b mod m) = ((n - b) mod m = a mod m)\"\nby (simp add: mod_sub_add add.commute)\n\nlemma le_mod_greater_imp_div_less: \"\n  \\<lbrakk> a \\<le> (b::nat); a mod m > b mod m \\<rbrakk> \\<Longrightarrow> a div m < b div m\"\napply (rule ccontr, simp add: linorder_not_less)\napply (drule mult_le_mono1[of \"b div m\" _ m])\napply (drule add_less_le_mono[of \"b mod m\" \"a mod m\" \"b div m * m\" \"a div m * m\"])\napply simp_all\ndone\n\nlemma less_mod_ge_imp_div_less: \"\\<lbrakk> a < (b::nat); a mod m \\<ge> b mod m \\<rbrakk> \\<Longrightarrow> a div m < b div m\"\napply (case_tac \"m = 0\", simp)\napply (rule mult_less_cancel1[of m, THEN iffD1, THEN conjunct2])\napply (simp add: minus_mod_eq_mult_div [symmetric])\napply (rule order_less_le_trans[of _ \"b - a mod m\"])\napply (rule diff_less_mono)\napply simp+\ndone\ncorollary less_mod_0_imp_div_less: \"\\<lbrakk> a < (b::nat); b mod m = 0 \\<rbrakk> \\<Longrightarrow> a div m < b div m\"\nby (simp add: less_mod_ge_imp_div_less)\n\nlemma mod_diff_right_eq: \"\n  (a::nat) \\<le> b \\<Longrightarrow> (b - a) mod m = (b - a mod m) mod m\"\nproof -\n  assume a_as:\"a \\<le> b\"\n  have \"(b - a) mod m = (b - a + a div m * m) mod m\" by simp\n  also have \"\\<dots> = (b + a div m * m - a) mod m\" using a_as by simp\n  also have \"\\<dots> = (b + a div m * m - (a div m * m + a mod m)) mod m\" by simp\n  also have \"\\<dots> = (b + a div m * m - a div m * m - a mod m) mod m\"\n    by (simp only: diff_diff_left[symmetric])\n  also have \"\\<dots> = (b - a mod m) mod m\" by simp\n  finally show ?thesis .\nqed\ncorollary mod_eq_imp_diff_mod_eq: \"\n  \\<lbrakk> x mod m = y mod m; x \\<le> (t::nat); y \\<le> t \\<rbrakk> \\<Longrightarrow>\n  (t - x) mod m = (t - y) mod m\"\nby (simp only: mod_diff_right_eq)\nlemma mod_eq_imp_diff_mod_eq2: \"\n  \\<lbrakk> x mod m = y mod m; (t::nat) \\<le> x; t \\<le> y \\<rbrakk> \\<Longrightarrow>\n  (x - t) mod m = (y - t) mod m\"\napply (case_tac \"m = 0\", simp+)\napply (subst mod_mult_self2[of \"x - t\" m t, symmetric])\napply (subst mod_mult_self2[of \"y - t\" m t, symmetric])\napply (simp only: add_diff_assoc2 diff_add_assoc gr0_imp_self_le_mult2)\napply (simp only: mod_add)\ndone\n\nlemma divisor_add_diff_mod_if: \"\n  (m + b mod m - a mod m) mod (m::nat)= (\n  if a mod m \\<le> b mod m\n  then (b mod m - a mod m)\n  else (m + b mod m - a mod m))\"\napply (case_tac \"m = 0\", simp)\napply clarsimp\napply (subst diff_add_assoc, assumption)\napply (simp only: mod_add_self1)\napply (rule mod_less)\napply (simp add: less_imp_diff_less)\ndone\ncorollary divisor_add_diff_mod_eq1: \"\n  a mod m \\<le> b mod m \\<Longrightarrow>\n  (m + b mod m - a mod m) mod (m::nat) = b mod m - a mod m\"\nby (simp add: divisor_add_diff_mod_if)\ncorollary divisor_add_diff_mod_eq2: \"\n  b mod m < a mod m \\<Longrightarrow>\n  (m + b mod m - a mod m) mod (m::nat) = m + b mod m - a mod m\"\nby (simp add: divisor_add_diff_mod_if)\n\nlemma mod_add_mod_if: \"\n  (a mod m + b mod m) mod (m::nat)= (\n  if a mod m + b mod m < m\n  then a mod m + b mod m\n  else a mod m + b mod m - m)\"\napply (case_tac \"m = 0\", simp_all)\napply (clarsimp simp: linorder_not_less)\napply (simp add: mod_if[of \"a mod m + b mod m\"])\napply (rule mod_less)\napply (rule diff_less_conv[THEN iffD2], assumption)\napply (simp add: add_less_mono)\ndone\ncorollary mod_add_mod_eq1: \"\n  a mod m + b mod m < m \\<Longrightarrow>\n  (a mod m + b mod m) mod (m::nat) = a mod m + b mod m\"\nby (simp add: mod_add_mod_if)\ncorollary mod_add_mod_eq2: \"\n  m \\<le> a mod m + b mod m\\<Longrightarrow>\n  (a mod m + b mod m) mod (m::nat) = a mod m + b mod m - m\"\nby (simp add: mod_add_mod_if)\n\nlemma mod_add1_eq_if: \"\n  (a + b) mod (m::nat) = (\n  if (a mod m + b mod m < m) then a mod m + b mod m\n  else a mod m + b mod m - m)\"\nby (simp add: mod_add_eq[symmetric, of a b] mod_add_mod_if)\n\nlemma mod_add_eq_mod_conv: \"0 < (m::nat) \\<Longrightarrow>\n  ((x + a) mod m = b mod m ) =\n  (x mod m = (m + b mod m - a mod m) mod m)\"\napply (simp only: mod_add_eq[symmetric, of x a])\napply (rule iffI)\n apply (drule sym)\n apply (simp add: mod_add_mod_if)\napply (simp add: mod_add_left_eq le_add_diff_inverse2[OF trans_le_add1[OF mod_le_divisor]])\ndone\n\n\n\n\nlemma mod_diff1_eq: \"\n  (a::nat) \\<le> b \\<Longrightarrow> (b - a) mod m = (m + b mod m - a mod m) mod m\"\napply (case_tac \"m = 0\", simp)\napply simp\nproof -\n  assume a_as:\"a \\<le> b\"\n    and m_as: \"0 < m\"\n  have a_mod_le_b_s: \"a mod m \\<le> b\"\n    by (rule le_trans[of _ a], simp only: mod_le_dividend, simp only: a_as)\n  have \"(b - a) mod m = (b - a mod m) mod m\"\n    using a_as by (simp only: mod_diff_right_eq)\n  also have \"\\<dots> = (b - a mod m + m) mod m\"\n    by simp\n  also have \"\\<dots> = (b + m - a mod m) mod m\"\n    using a_mod_le_b_s by simp\n  also have \"\\<dots> = (b div m * m + b mod m + m - a mod m) mod m\"\n    by simp\n  also have \"\\<dots> = (b div m * m + (b mod m + m - a mod m)) mod m\"\n    by (simp add: diff_add_assoc[OF mod_le_divisor, OF m_as])\n  also have \"\\<dots> = ((b mod m + m - a mod m) + b div m * m) mod m\"\n    by simp\n  also have \"\\<dots> = (b mod m + m - a mod m) mod m\"\n    by simp\n  also have \"\\<dots> = (m + b mod m - a mod m) mod m\"\n    by (simp only: add.commute)\n  finally show ?thesis .\nqed\ncorollary mod_diff1_eq_if: \"\n  (a::nat) \\<le> b \\<Longrightarrow> (b - a) mod m = (\n    if a mod m \\<le> b mod m then b mod m - a mod m\n    else m + b mod m - a mod m)\"\nby (simp only: mod_diff1_eq divisor_add_diff_mod_if)\ncorollary mod_diff1_eq1: \"\n  \\<lbrakk> (a::nat) \\<le> b; a mod m \\<le> b mod m \\<rbrakk>\n  \\<Longrightarrow> (b - a) mod m = b mod m - a mod m\"\nby (simp add: mod_diff1_eq_if)\ncorollary mod_diff1_eq2: \"\n  \\<lbrakk> (a::nat) \\<le> b; b mod m < a mod m\\<rbrakk>\n  \\<Longrightarrow> (b - a) mod m = m + b mod m - a mod m\"\nby (simp add: mod_diff1_eq_if)\n\n\nsubsubsection \\<open>Divisor subtraction with \\<open>div\\<close> and \\<open>mod\\<close>\\<close>\n\nlemma mod_diff_self1: \"\n  0 < (n::nat) \\<Longrightarrow> (m - n) mod m = m - n\"\nby (case_tac \"m = 0\", simp_all)\nlemma mod_diff_self2: \"\n  m \\<le> (n::nat) \\<Longrightarrow> (n - m) mod m = n mod m\"\nby (simp add: mod_diff_right_eq)\nlemma mod_diff_mult_self1: \"\n  k * m \\<le> (n::nat) \\<Longrightarrow> (n - k * m) mod m = n mod m\"\nby (simp add: mod_diff_right_eq)\nlemma mod_diff_mult_self2: \"\n  m * k \\<le> (n::nat) \\<Longrightarrow> (n - m * k) mod m = n mod m\"\nby (simp only: mult.commute[of m k] mod_diff_mult_self1)\n\nlemma div_diff_self1: \"0 < (n::nat) \\<Longrightarrow> (m - n) div m = 0\"\nby (case_tac \"m = 0\", simp_all)\nlemma div_diff_self2: \"(n - m) div m = n div m - Suc 0\"\napply (case_tac \"m = 0\", simp)\napply (case_tac \"n < m\", simp)\napply (case_tac \"n = m\", simp)\napply (simp add: div_if)\ndone\n\nlemma div_diff_mult_self1: \"\n  (n - k * m) div m = n div m - (k::nat)\"\napply (case_tac \"m = 0\", simp)\napply (case_tac \"n < k * m\")\n apply simp\n apply (drule div_le_mono[OF less_imp_le, of n _ m])\n apply simp\napply (simp add: linorder_not_less)\napply (rule iffD1[OF mult_cancel1_gr0[where k=m]], assumption)\napply (subst diff_mult_distrib2)\napply (simp only: minus_mod_eq_mult_div [symmetric])\napply (simp only: diff_commute[of _ \"k*m\"])\napply (simp only: mult.commute[of m])\napply (simp only: mod_diff_mult_self1)\ndone\nlemma div_diff_mult_self2: \"\n  (n - m * k) div m = n div m - (k::nat)\"\nby (simp only: mult.commute div_diff_mult_self1)\n\n\nsubsubsection \\<open>Modulo equality and modulo of difference\\<close>\n\nlemma mod_eq_imp_diff_mod_0:\"\n  (a::nat) mod m = b mod m \\<Longrightarrow> (b - a) mod m = 0\"\n  (is \"?P \\<Longrightarrow> ?Q\")\nproof -\n  assume as1: ?P\n  have \"b - a = b div m * m + b mod m - (a div m * m + a mod m)\"\n    by simp\n  also have \"\\<dots> = b div m * m + b mod m - (a mod m + a div m * m)\"\n    by simp\n  also have \"\\<dots> = b div m * m + b mod m - a mod m - a div m * m\"\n    by simp\n  also have \"\\<dots> = b div m * m + b mod m - b mod m - a div m * m\"\n    using as1 by simp\n  also have \"\\<dots> = b div m * m - a div m * m\"\n    by (simp only: diff_add_inverse2)\n  also have \"\\<dots> = (b div m - a div m) * m\"\n    by (simp only: diff_mult_distrib)\n  finally have \"b - a = (b div m - a div m) * m\" .\n  hence \"(b - a) mod m = (b div m - a div m) * m mod m\"\n    by (rule arg_cong)\n  thus ?thesis by (simp only: mod_mult_self2_is_0)\nqed\ncorollary mod_eq_imp_diff_dvd: \"\n  (a::nat) mod m = b mod m \\<Longrightarrow> m dvd b - a\"\nby (rule dvd_eq_mod_eq_0[THEN iffD2, OF mod_eq_imp_diff_mod_0])\n\nlemma mod_neq_imp_diff_mod_neq0:\"\n  \\<lbrakk> (a::nat) mod m \\<noteq> b mod m; a \\<le> b \\<rbrakk> \\<Longrightarrow> 0 < (b - a) mod m\"\napply (case_tac \"m = 0\", simp)\napply (drule le_imp_less_or_eq, erule disjE)\n prefer 2\n apply simp\napply (drule neq_iff[THEN iffD1], erule disjE)\n apply (simp add: mod_diff1_eq1)\napply (simp add: mod_diff1_eq2[OF less_imp_le] trans_less_add1[OF mod_less_divisor])\ndone\ncorollary mod_neq_imp_diff_not_dvd:\"\n  \\<lbrakk> (a::nat) mod m \\<noteq> b mod m; a \\<le> b \\<rbrakk> \\<Longrightarrow> \\<not> m dvd b - a\"\nby (simp add: dvd_eq_mod_eq_0 mod_neq_imp_diff_mod_neq0)\n\nlemma diff_mod_0_imp_mod_eq:\"\n  \\<lbrakk> (b - a) mod m = 0; a \\<le> b \\<rbrakk> \\<Longrightarrow> (a::nat) mod m = b mod m\"\napply (rule ccontr)\napply (drule mod_neq_imp_diff_mod_neq0)\napply simp_all\ndone\ncorollary diff_dvd_imp_mod_eq:\"\n  \\<lbrakk> m dvd b - a; a \\<le> b \\<rbrakk> \\<Longrightarrow> (a::nat) mod m = b mod m\"\nby (rule dvd_eq_mod_eq_0[THEN iffD1, THEN diff_mod_0_imp_mod_eq])\n\n\n\nlemma mod_eq_diff_mod_0_conv: \"\n  a \\<le> (b::nat) \\<Longrightarrow> (a mod m = b mod m) = ((b - a) mod m = 0)\"\napply (rule iffI)\napply (rule mod_eq_imp_diff_mod_0, assumption)\napply (rule diff_mod_0_imp_mod_eq, assumption+)\ndone\ncorollary mod_eq_diff_dvd_conv: \"\n  a \\<le> (b::nat) \\<Longrightarrow> (a mod m = b mod m) = (m dvd b - a)\"\nby (rule dvd_eq_mod_eq_0[symmetric, THEN subst], rule mod_eq_diff_mod_0_conv)\n\n\nsubsection \\<open>Some additional lemmata about integer \\<open>div\\<close> and \\<open>mod\\<close>\\<close>\n\nlemma zmod_eq_imp_diff_mod_0:\n  \"a mod m = b mod m \\<Longrightarrow> (b - a) mod m = 0\" for a b m :: int\n  by (simp add: mod_diff_cong)\n  \n(*lemma int_mod_distrib: \"int (n mod m) = int n mod int m\"*)\nlemmas int_mod_distrib = zmod_int\n\nlemma zdiff_mod_0_imp_mod_eq__pos:\"\n  \\<lbrakk> (b - a) mod m = 0; 0 < (m::int) \\<rbrakk> \\<Longrightarrow> a mod m = b mod m\"\n  (is \"\\<lbrakk> ?P; ?Pm \\<rbrakk> \\<Longrightarrow> ?Q\")\nproof -\n  assume as1: ?P\n    and as2: \"0 < m\"\n\n  obtain r1 where a_r1:\"r1 = a mod m\" by blast\n  obtain r2 where b_r2:\"r2 = b mod m\" by blast\n\n  obtain q1 where a_q1: \"q1 = a div m\" by blast\n  obtain q2 where b_q2: \"q2 = b div m\" by blast\n\n  have a_r1_q1: \"a = m * q1 + r1\"\n    using a_r1 a_q1 by simp\n  have b_r2_q2: \"b = m * q2 + r2\"\n    using b_r2 b_q2 by simp\n\n  have \"b - a = m * q2 + r2 - (m * q1 + r1)\"\n    using a_r1_q1 b_r2_q2 by simp\n  also have \"\\<dots> = m * q2 + r2 - m * q1 - r1\"\n    by simp\n  also have \"\\<dots> = m * q2 - m * q1 + r2 - r1\"\n    by simp\n  finally have \"b - a = m * (q2 - q1) + (r2 - r1)\"\n    by (simp add: right_diff_distrib)\n  hence \"(b - a) mod m = (r2 - r1) mod m\"\n    by (simp add: mod_add_eq)\n  hence r2_r1_mod_m_0:\"(r2 - r1) mod m = 0\" (is \"?R1\")\n    by (simp only: as1)\n\n  have \"r1 = r2\"\n  proof (rule notI[of \"r1 \\<noteq> r2\", simplified])\n    assume as1': \"r1 \\<noteq> r2\"\n    have diff_le_s: \"\\<And>a b (m::int). \\<lbrakk> 0 \\<le> a; b < m \\<rbrakk> \\<Longrightarrow> b - a < m\"\n      by simp\n    have s_r1:\"0 \\<le> r1 \\<and> r1 < m\" and s_r2:\"0 \\<le> r2 \\<and> r2 < m\"\n      by (simp add: as2 a_r1 b_r2 pos_mod_conj)+\n    have mr2r1:\"-m < r2 - r1\" and r2r1m:\"r2 - r1 < m\"\n      by (simp add: minus_less_iff[of m] s_r1 s_r2 diff_le_s)+\n    have \"0 \\<le> r2 - r1 \\<Longrightarrow> (r2 - r1) mod m = (r2 - r1)\"\n      using r2r1m by (blast intro: mod_pos_pos_trivial)\n    hence s1_pos: \"0 \\<le> r2 - r1 \\<Longrightarrow> r2 - r1 = 0\"\n      using r2_r1_mod_m_0 by simp\n\n    have \"(r2-r1) mod -m = 0\"\n      by (simp add: zmod_zminus2_eq_if[of \"r2-r1\" m, simplified] r2_r1_mod_m_0)\n    moreover\n    have \"r2 - r1 \\<le> 0 \\<Longrightarrow> (r2 - r1) mod -m = r2 - r1\"\n      using mr2r1\n      by (simp add: mod_neg_neg_trivial)\n    ultimately have s1_neg:\"r2 - r1 \\<le> 0 \\<Longrightarrow> r2 - r1 = 0\"\n      by simp\n\n    have \"r2 - r1 = 0\"\n      using s1_pos s1_neg linorder_linear by blast\n    hence \"r1 = r2\" by simp\n    thus False\n      using as1' by blast\n  qed\n  thus ?thesis\n    using a_r1 b_r2 by blast\nqed\n\nlemma zmod_zminus_eq_conv_pos: \"\n  0 < (m::int) \\<Longrightarrow> (a mod - m = b mod - m) = (a mod m = b mod m)\"\napply (simp only: mod_minus_right neg_equal_iff_equal)\napply (simp only: zmod_zminus1_eq_if)\napply (split if_split)+\napply (safe, simp_all)\napply (insert pos_mod_bound[of m a] pos_mod_bound[of m b], simp_all)\ndone\nlemma zmod_zminus_eq_conv: \"\n  ((a::int) mod - m = b mod - m) = (a mod m = b mod m)\"\napply (insert linorder_less_linear[of 0 m], elim disjE)\napply (blast dest: zmod_zminus_eq_conv_pos)\napply simp\napply (simp add: zmod_zminus_eq_conv_pos[of \"-m\", symmetric])\ndone\n\nlemma zdiff_mod_0_imp_mod_eq:\"\n  (b - a) mod m = 0 \\<Longrightarrow> (a::int) mod m = b mod m\"\nby (metis dvd_eq_mod_eq_0 mod_eq_dvd_iff)\n\nlemma zmod_eq_diff_mod_0_conv: \"\n  ((a::int) mod m = b mod m) = ((b - a) mod m = 0)\"\napply (rule iffI)\napply (rule zmod_eq_imp_diff_mod_0, assumption)\napply (rule zdiff_mod_0_imp_mod_eq, assumption)\ndone\n\nlemma \"\\<not>(\\<exists>(a::int) b m. (b - a) mod m = 0 \\<and> a mod m \\<noteq> b mod m)\"\nby (simp add: zmod_eq_diff_mod_0_conv)\nlemma \"\\<exists>(a::nat) b m. (b - a) mod m = 0 \\<and> a mod m \\<noteq> b mod m\"\napply (rule_tac x=1 in exI)\napply (rule_tac x=0 in exI)\napply (rule_tac x=2 in exI)\napply simp\ndone\n\n\n\nlemma zmult_div_leq_mono:\"\n  \\<lbrakk> (0::int) \\<le> x; a \\<le> b; 0 < d \\<rbrakk> \\<Longrightarrow> x * a div d \\<le> x * b div d\"\nby (metis mult_right_mono zdiv_mono1 mult.commute)\n\nlemma zmult_div_leq_mono_neg:\"\n  \\<lbrakk> x \\<le> (0::int); a \\<le> b; 0 < d \\<rbrakk> \\<Longrightarrow> x * b div d \\<le> x * a div d\"\nby (metis mult_left_mono_neg zdiv_mono1)\n\nlemma zmult_div_pos_le:\"\n  \\<lbrakk> (0::int) \\<le> a; 0 \\<le> b; b \\<le> c \\<rbrakk> \\<Longrightarrow> a * b div c \\<le> a\"\napply (case_tac \"b = 0\", simp)\napply (subgoal_tac \"b * a \\<le> c * a\")\n prefer 2\n apply (simp only: mult_right_mono)\napply (simp only: mult.commute)\napply (subgoal_tac \"a * b div c \\<le> a * c div c\")\n prefer 2\n apply (simp only: zdiv_mono1)\napply simp\ndone\n\nlemma zmult_div_neg_le:\"\n  \\<lbrakk> a \\<le> (0::int); 0 < c; c \\<le> b \\<rbrakk> \\<Longrightarrow> a * b div c \\<le> a\"\napply (subgoal_tac \"b * a \\<le> c * a\")\n prefer 2\n apply (simp only: mult_right_mono_neg)\napply (simp only: mult.commute)\napply (subgoal_tac \"a * b div c \\<le> a * c div c\")\n prefer 2\n apply (simp only: zdiv_mono1)\napply simp\ndone\n\nlemma zmult_div_ge_0:\"\\<lbrakk> (0::int) \\<le> x; 0 \\<le> a; 0 < c \\<rbrakk> \\<Longrightarrow> 0 \\<le> a * x div c\"\nby (metis pos_imp_zdiv_nonneg_iff split_mult_pos_le)\n\ncorollary zmult_div_plus_ge_0: \"\n  \\<lbrakk> (0::int) \\<le> x; 0 \\<le> a; 0 \\<le> b; 0 < c\\<rbrakk> \\<Longrightarrow> 0 \\<le> a * x div c + b\"\nby (insert zmult_div_ge_0[of x a c], simp)\n\n\nlemma zmult_div_abs_ge: \"\n  \\<lbrakk> (0::int) \\<le> b; b \\<le> b'; 0 \\<le> a; 0 < c\\<rbrakk> \\<Longrightarrow>\n  \\<bar>a * b div c\\<bar> \\<le> \\<bar>a * b' div c\\<bar>\"\napply (insert zmult_div_ge_0[of b a c] zmult_div_ge_0[of \"b'\" a c], simp)\nby (metis zmult_div_leq_mono)\n\nlemma zmult_div_plus_abs_ge: \"\n  \\<lbrakk> (0::int) \\<le> b; b \\<le> b'; 0 \\<le> a; 0 < c \\<rbrakk> \\<Longrightarrow>\n  \\<bar>a * b div c + a\\<bar> \\<le> \\<bar>a * b' div c + a\\<bar>\"\napply (insert zmult_div_plus_ge_0[of b a a c] zmult_div_plus_ge_0[of \"b'\" a a c], simp)\nby (metis zmult_div_leq_mono)\n\n\nsubsection \\<open>Some further (in-)equality results for \\<open>div\\<close> and \\<open>mod\\<close>\\<close>\n\nlemma less_mod_eq_imp_add_divisor_le: \"\n  \\<lbrakk> (x::nat) < y; x mod m = y mod m \\<rbrakk> \\<Longrightarrow> x + m \\<le> y\"\napply (case_tac \"m = 0\")\n apply simp\napply (rule contrapos_pp[of \"x mod m = y mod m\"])\n apply blast\napply (rule ccontr, simp only: not_not, clarify)\nproof -\n  assume m_greater_0: \"0 < m\"\n  assume x_less_y:\"x < y\"\n  hence y_x_greater_0:\"0 < y - x\"\n    by simp\n  assume \"x mod m = y mod m\"\n  hence y_x_mod_m: \"(y - x) mod m = 0\"\n    by (simp only: mod_eq_imp_diff_mod_0)\n  assume \"\\<not> x + m \\<le> y\"\n  hence \"y < x + m\" by simp\n  hence \"y - x < x + m - x\"\n    by (simp add: diff_add_inverse diff_less_conv m_greater_0)\n  hence y_x_less_m: \"y - x < m\"\n    by simp\n  have \"(y - x) mod m = y - x\"\n    using y_x_less_m by simp\n  hence \"y - x = 0\"\n    using y_x_mod_m by simp\n  thus False\n    using y_x_greater_0 by simp\nqed\n\n\nlemma less_div_imp_mult_add_divisor_le: \"\n  (x::nat) < n div m \\<Longrightarrow> x * m + m \\<le> n\"\napply (case_tac \"m = 0\", simp)\napply (case_tac \"n < m\", simp)\napply (simp add: linorder_not_less)\napply (subgoal_tac \"m \\<le> n - n mod m\")\n prefer 2\n apply (drule div_le_mono[of m _ m])\n apply (simp only: div_self)\n apply (drule mult_le_mono2[of 1 _ m])\n apply (simp only: mult_1_right minus_mod_eq_mult_div [symmetric])\napply (drule less_imp_le_pred[of x])\napply (drule mult_le_mono2[of x _ m])\napply (simp add: diff_mult_distrib2 minus_mod_eq_mult_div [symmetric] del: diff_diff_left)\napply (simp only: le_diff_conv2[of m])\napply (drule le_diff_imp_le[of \"m * x + m\"])\napply (simp only: mult.commute[of _ m])\ndone\n\nlemma mod_add_eq_imp_mod_0: \"\n  ((n + k) mod (m::nat) = n mod m) = (k mod m = 0)\"\nby (metis add_eq_if mod_add mod_add_self1 mod_self add.commute)\n\nlemma between_imp_mod_between: \"\n  \\<lbrakk> b < (m::nat); m * k + a \\<le> n; n \\<le> m * k + b \\<rbrakk> \\<Longrightarrow>\n  a \\<le> n mod m \\<and> n mod m \\<le> b\"\n  apply (case_tac \"m = 0\", simp_all)\n  apply (frule gr_implies_gr0)\n  apply (subgoal_tac \"k = n div m\")\n   prefer 2\n   apply (rule sym, rule div_nat_eqI) apply simp\n   apply simp\n  apply clarify\n  apply (rule conjI)\n   apply (rule add_le_imp_le_left[where c=\"m * (n div m)\"], simp)+\n  done\n\ncorollary between_imp_mod_le: \"\n  \\<lbrakk> b < (m::nat); m * k \\<le> n; n \\<le> m * k + b \\<rbrakk> \\<Longrightarrow> n mod m \\<le> b\"\nby (insert between_imp_mod_between[of b m k 0 n], simp)\ncorollary between_imp_mod_gr0: \"\n  \\<lbrakk> (m::nat) * k < n; n < m * k + m \\<rbrakk> \\<Longrightarrow> 0 < n mod m\"\napply (case_tac \"m = 0\", simp_all)\napply (rule Suc_le_lessD)\napply (rule between_imp_mod_between[THEN conjunct1, of \"m - Suc 0\" m k \"Suc 0\" n])\napply simp_all\ndone\n\ncorollary le_less_div_conv: \"\n  0 < m \\<Longrightarrow> (k * m \\<le> n \\<and> n < Suc k * m) = (n div m = k)\"\n  by (auto simp add: ac_simps intro: div_nat_eqI dividend_less_times_div)\n\nlemma le_less_imp_div: \"\n  \\<lbrakk> k * m \\<le> n; n < Suc k * m \\<rbrakk> \\<Longrightarrow> n div m = k\"\n  by (auto simp add: ac_simps intro: div_nat_eqI)  \n\nlemma div_imp_le_less: \"\n  \\<lbrakk> n div m = k; 0 < m \\<rbrakk> \\<Longrightarrow> k * m \\<le> n \\<and> n < Suc k * m\"\n  by (auto simp add: ac_simps intro: dividend_less_times_div)\n\nlemma div_le_mod_le_imp_le: \"\n  \\<lbrakk> (a::nat) div m \\<le> b div m; a mod m \\<le> b mod m \\<rbrakk> \\<Longrightarrow> a \\<le> b\"\napply (rule subst[OF mult_div_mod_eq[of m a]])\napply (rule subst[OF mult_div_mod_eq[of m b]])\napply (rule add_le_mono)\napply (rule mult_le_mono2)\napply assumption+\ndone\n\nlemma le_mod_add_eq_imp_add_mod_le: \"\n  \\<lbrakk> a \\<le> b; (a + k) mod m = (b::nat) mod m \\<rbrakk> \\<Longrightarrow> a + k mod m \\<le> b\"\nby (metis add_le_mono2 diff_add_inverse le_add1 le_add_diff_inverse mod_diff1_eq mod_less_eq_dividend)\n\ncorollary mult_divisor_le_mod_ge_imp_ge: \"\n  \\<lbrakk> (m::nat) * k \\<le> n; r \\<le> n mod m \\<rbrakk> \\<Longrightarrow> m * k + r \\<le> n\"\napply (insert le_mod_add_eq_imp_add_mod_le[of \"m * k\" n \"n mod m\" m])\napply (simp add: add.commute[of \"m * k\"])\ndone\n\n\nsubsection \\<open>Additional multiplication results for \\<open>mod\\<close> and \\<open>div\\<close>\\<close>\n\nlemma mod_0_imp_mod_mult_right_0: \"\n  n mod m = (0::nat) \\<Longrightarrow> n * k mod m = 0\"\nby fastforce\nlemma mod_0_imp_mod_mult_left_0: \"\n  n mod m = (0::nat) \\<Longrightarrow> k * n mod m = 0\"\nby fastforce\n\nlemma mod_0_imp_div_mult_left_eq: \"\n  n mod m = (0::nat) \\<Longrightarrow> k * n div m = k * (n div m)\"\nby fastforce\nlemma mod_0_imp_div_mult_right_eq: \"\n  n mod m = (0::nat) \\<Longrightarrow> n * k div m = k * (n div m)\"\nby fastforce\n\n\nlemma mod_0_imp_mod_factor_0_left: \"\n  n mod (m * m') = (0::nat) \\<Longrightarrow> n mod m = 0\"\nby fastforce\nlemma mod_0_imp_mod_factor_0_right: \"\n  n mod (m * m') = (0::nat) \\<Longrightarrow> n mod m' = 0\"\nby fastforce\n\n\nsubsection \\<open>Some factor distribution facts for \\<open>mod\\<close>\\<close>\n\nlemma mod_eq_mult_distrib: \"\n  (a::nat) mod m = b mod m \\<Longrightarrow>\n  a * k mod (m * k) = b * k mod (m * k)\"\nby simp\n\nlemma mod_mult_eq_imp_mod_eq: \"\n  (a::nat) mod (m * k) = b mod (m * k) \\<Longrightarrow> a mod m = b mod m\"\napply (simp only: mod_mult2_eq)\napply (drule_tac arg_cong[where f=\"\\<lambda>x. x mod m\"])\napply (simp add: add.commute)\ndone\ncorollary mod_eq_mod_0_imp_mod_eq: \"\n  \\<lbrakk> (a::nat) mod m' = b mod m'; m' mod m = 0 \\<rbrakk>\n  \\<Longrightarrow> a mod m = b mod m\"\n  using mod_mod_cancel [of m m' a] mod_mod_cancel [of m m' b] by auto\n\nlemma mod_factor_imp_mod_0: \"\n  \\<lbrakk>(x::nat) mod (m * k) = y * k mod (m * k)\\<rbrakk> \\<Longrightarrow> x mod k = 0\"\n  (is \"\\<lbrakk> ?P1 \\<rbrakk> \\<Longrightarrow> ?Q\")\nproof -\n  assume as1: ?P1\n  have \"y * k mod (m * k) = y mod m * k\"\n    by simp\n  hence \"x mod (m * k) = y mod m * k\"\n    using as1 by simp\n  hence \"y mod m * k = k * (x div k mod m) + x mod k\" (is \"?l1 = ?r1\")\n    by (simp only: ac_simps mod_mult2_eq)\n  hence \"(y mod m * k) mod k = ?r1 mod k\"\n    by simp\n  hence \"0 = ?r1 mod k\"\n    by simp\n  thus \"x mod k = 0\"\n    by (simp add: mod_add_eq)\nqed\ncorollary mod_factor_div: \"\n  \\<lbrakk>(x::nat) mod (m * k) = y * k mod (m * k)\\<rbrakk> \\<Longrightarrow> x div k * k = x\"\nby (blast intro: mod_factor_imp_mod_0[THEN mod_0_div_mult_cancel[THEN iffD1]])\n\nlemma mod_factor_div_mod:\"\n  \\<lbrakk> (x::nat) mod (m * k) = y * k mod (m * k); 0 < k \\<rbrakk>\n  \\<Longrightarrow> x div k mod m = y mod m\"\n  (is \"\\<lbrakk> ?P1; ?P2 \\<rbrakk> \\<Longrightarrow> ?L = ?R\")\nproof -\n  assume as1: ?P1\n  assume as2: ?P2\n  have x_mod_k_0: \"x mod k = 0\"\n    using as1 by (blast intro: mod_factor_imp_mod_0)\n  have \"?L * k + x mod k = x mod (k * m)\"\n    by (simp only: mod_mult2_eq mult.commute[of _ k])\n  hence \"?L * k = x mod (k * m)\"\n    using x_mod_k_0 by simp\n  hence \"?L * k = y * k mod (m * k)\"\n    using as1 by (simp only: ac_simps)\n  hence \"?L * k = y mod m * k\"\n    by (simp only: mult_mod_left)\n  thus ?thesis\n    using as2 by simp\nqed\n\n\nsubsection \\<open>More results about quotient \\<open>div\\<close> with addition and subtraction\\<close>\n\nlemma div_add1_eq_if: \"0 < m \\<Longrightarrow>\n  (a + b) div (m::nat) = a div m + b div m + (\n    if a mod m + b mod m < m then 0 else Suc 0)\"\napply (simp only: div_add1_eq[of a b])\napply (rule arg_cong[of \"(a mod m + b mod m) div m\"])\napply (clarsimp simp: linorder_not_less)\napply (rule le_less_imp_div[of \"Suc 0\" m \"a mod m + b mod m\"], simp)\napply simp\napply (simp only: add_less_mono[OF mod_less_divisor mod_less_divisor])\ndone\ncorollary div_add1_eq1: \"\n  a mod m + b mod m < (m::nat) \\<Longrightarrow>\n  (a + b) div (m::nat) = a div m + b div m\"\napply (case_tac \"m = 0\", simp)\napply (simp add: div_add1_eq_if)\ndone\ncorollary div_add1_eq1_mod_0_left: \"\n  a mod m = 0 \\<Longrightarrow> (a + b) div (m::nat) = a div m + b div m\"\napply (case_tac \"m = 0\", simp)\napply (simp add: div_add1_eq1)\ndone\ncorollary div_add1_eq1_mod_0_right: \"\n  b mod m = 0 \\<Longrightarrow> (a + b) div (m::nat) = a div m + b div m\"\nby (fastforce simp: div_add1_eq1_mod_0_left)\ncorollary div_add1_eq2: \"\n  \\<lbrakk> 0 < m; (m::nat) \\<le> a mod m + b mod m \\<rbrakk> \\<Longrightarrow>\n  (a + b) div (m::nat) = Suc (a div m + b div m)\"\nby (simp add: div_add1_eq_if)\n\nlemma div_Suc: \"\n  0 < n \\<Longrightarrow> Suc m div n = (if Suc (m mod n) = n then Suc (m div n) else m div n)\"\napply (drule Suc_leI, drule le_imp_less_or_eq)\napply (case_tac \"n = Suc 0\", simp)\napply (split if_split, intro conjI impI)\n apply (rule_tac t=\"Suc m\" and s=\"m + 1\" in subst, simp)\n apply (subst div_add1_eq2, simp+)\napply (insert le_neq_trans[OF mod_less_divisor[THEN Suc_leI, of n m]], simp)\napply (rule_tac t=\"Suc m\" and s=\"m + 1\" in subst, simp)\napply (subst div_add1_eq1, simp+)\ndone\nlemma div_Suc': \"\n  0 < n \\<Longrightarrow> Suc m div n = (if m mod n < n - Suc 0 then m div n else Suc (m div n))\"\napply (simp add: div_Suc)\napply (intro conjI impI)\n apply simp\napply (insert le_neq_trans[OF mod_less_divisor[THEN Suc_leI, of n m]], simp)\ndone\n\nlemma div_diff1_eq_if: \"\n  (b - a) div (m::nat) =\n  b div m - a div m - (if a mod m \\<le> b mod m then 0 else Suc 0)\"\napply (case_tac \"m = 0\", simp)\napply (case_tac \"b < a\")\n apply (frule less_imp_le[of b])\n apply (frule div_le_mono[of _ _ m])\n apply simp\napply (simp only: linorder_not_less neq0_conv)\nproof -\n  assume le_as: \"a \\<le> b\"\n    and m_as: \"0 < m\"\n  have div_le:\"a div m \\<le> b div m\"\n    using le_as by (simp only: div_le_mono)\n  have \"b - a = b div m * m + b mod m - (a div m * m + a mod m)\"\n    by simp\n  also have \"\\<dots> = b div m * m + b mod m - a div m * m - a mod m\"\n    by simp\n  also have \"\\<dots> = b div m * m - a div m * m + b mod m - a mod m\"\n    by (simp only: diff_add_assoc2[OF mult_le_mono1[OF div_le]])\n  finally have b_a_s1: \"b - a = (b div m - a div m) * m + b mod m - a mod m\"\n    (is \"?b_a = ?b_a1\")\n    by (simp only: diff_mult_distrib)\n  hence b_a_div_s: \"(b - a) div m =\n    ((b div m - a div m) * m + b mod m - a mod m) div m\"\n    by (rule arg_cong)\n\n  show ?thesis\n  proof (cases \"a mod m \\<le> b mod m\")\n    case True\n    hence as': \"a mod m \\<le> b mod m\" .\n\n    have \"(b - a) div m = ?b_a1 div m\"\n      using b_a_div_s .\n    also have \"\\<dots> = ((b div m - a div m) * m + (b mod m - a mod m)) div m\"\n      using as' by simp\n    also have \"\\<dots> = b div m - a div m + (b mod m - a mod m) div m\"\n      apply (simp only: add.commute)\n      by (simp only: div_mult_self1[OF less_imp_neq[OF m_as, THEN not_sym]])\n    finally have b_a_div_s': \"(b - a) div m = \\<dots>\" .\n    have \"(b mod m - a mod m) div m = 0\"\n      by (rule div_less, rule less_imp_diff_less,\n          rule mod_less_divisor, rule m_as)\n    thus ?thesis\n      using b_a_div_s' as'\n      by simp\n  next\n    case False\n    hence as1': \"\\<not> a mod m \\<le> b mod m\" .\n    hence as': \"b mod m < a mod m\" by simp\n\n    have a_div_less: \"a div m < b div m\"\n      using le_as as'\n      by (blast intro: le_mod_greater_imp_div_less)\n\n    have \"b div m - a div m = b div m - a div m - (Suc 0 - Suc 0)\"\n      by simp\n    also have \"\\<dots> = b div m - a div m + Suc 0 - Suc 0\"\n      by simp\n    also have \"\\<dots> = b div m - a div m - Suc 0 + Suc 0\"\n      by (simp only: diff_add_assoc2\n        a_div_less[THEN zero_less_diff[THEN iffD2], THEN Suc_le_eq[THEN iffD2]])\n    finally have b_a_div_s': \"b div m - a div m = \\<dots>\" .\n\n    have \"(b - a) div m = ?b_a1 div m\"\n      using b_a_div_s .\n    also have \"\\<dots> = ((b div m - a div m - Suc 0 + Suc 0) * m\n      + b mod m - a mod m ) div m\"\n      using b_a_div_s' by (rule arg_cong)\n    also have \"\\<dots> = ((b div m - a div m - Suc 0) * m\n      + Suc 0 * m + b mod m - a mod m ) div m\"\n      by (simp only: add_mult_distrib)\n    also have \"\\<dots> = ((b div m - a div m - Suc 0) * m\n      + m + b mod m - a mod m ) div m\"\n      by simp\n    also have \"\\<dots> = ((b div m - a div m - Suc 0) * m\n      + (m + b mod m - a mod m) ) div m\"\n      by (simp only: add.assoc m_as\n        diff_add_assoc[of \"a mod m\" \"m + b mod m\"]\n        trans_le_add1[of \"a mod m\" m, OF mod_le_divisor])\n    also have \"\\<dots> = b div m - a div m - Suc 0\n      + (m + b mod m - a mod m) div m\"\n      by (simp only: add.commute div_mult_self1[OF less_imp_neq[OF m_as, THEN not_sym]])\n    finally have b_a_div_s': \"(b - a) div m = \\<dots>\" .\n\n    have div_0_s: \"(m + b mod m - a mod m) div m = 0\"\n      by (rule div_less, simp only: add_diff_less m_as as')\n    show ?thesis\n      by (simp add: as1' b_a_div_s' div_0_s)\n  qed\nqed\n\ncorollary div_diff1_eq: \"\n  (b - a) div (m::nat) =\n  b div m - a div m - (m + a mod m - Suc (b mod m)) div m\"\napply (case_tac \"m = 0\", simp)\napply (simp only: neq0_conv)\napply (rule subst[of\n  \"if a mod m \\<le> b mod m then 0 else Suc 0\"\n  \"(m + a mod m - Suc(b mod m)) div m\"])\n prefer 2 apply (rule div_diff1_eq_if)\napply (split if_split, rule conjI)\n apply simp\napply (clarsimp simp: linorder_not_le)\napply (rule sym)\napply (drule Suc_le_eq[of \"b mod m\", THEN iffD2])\napply (simp only: diff_add_assoc)\napply (simp only: div_add_self1)\napply (simp add: less_imp_diff_less)\ndone\n\ncorollary div_diff1_eq1: \"\n  a mod m \\<le> b mod m \\<Longrightarrow>\n  (b - a) div (m::nat) = b div m - a div m\"\nby (simp add: div_diff1_eq_if)\ncorollary div_diff1_eq1_mod_0: \"\n  a mod m = 0 \\<Longrightarrow>\n  (b - a) div (m::nat) = b div m - a div m\"\nby (simp add: div_diff1_eq1)\ncorollary div_diff1_eq2: \"\n  b mod m < a mod m \\<Longrightarrow>\n  (b - a) div (m::nat) = b div m - Suc (a div m)\"\nby (simp add: div_diff1_eq_if)\n\n\nsubsection \\<open>Further results about \\<open>div\\<close> and \\<open>mod\\<close>\\<close>\n\nsubsubsection \\<open>Some auxiliary facts about \\<open>mod\\<close>\\<close>\n\nlemma diff_less_divisor_imp_sub_mod_eq: \"\n  \\<lbrakk> (x::nat) \\<le> y; y - x < m \\<rbrakk> \\<Longrightarrow> x = y - (y - x) mod m\"\nby simp\nlemma diff_ge_divisor_imp_sub_mod_less: \"\n  \\<lbrakk> (x::nat) \\<le> y; m \\<le> y - x; 0 < m \\<rbrakk> \\<Longrightarrow> x < y - (y - x) mod m\"\napply (simp only: less_diff_conv)\napply (simp only: le_diff_conv2 add.commute[of m])\napply (rule less_le_trans[of _ \"x + m\"])\napply simp_all\ndone\n\nlemma le_imp_sub_mod_le: \"\n  (x::nat) \\<le> y \\<Longrightarrow> x \\<le> y - (y - x) mod m\"\napply (case_tac \"m = 0\", simp_all)\napply (case_tac \"m \\<le> y - x\")\napply (drule diff_ge_divisor_imp_sub_mod_less[of x y m])\napply simp_all\ndone\n\nlemma mod_less_diff_mod: \"\n  \\<lbrakk> n mod m < r; r \\<le> m; r \\<le> (n::nat) \\<rbrakk> \\<Longrightarrow>\n  (n - r) mod m = m + n mod m - r\"\napply (case_tac \"r = m\")\n apply (simp add: mod_diff_self2)\napply (simp add: mod_diff1_eq[of r n m])\ndone\n\nlemma mod_0_imp_mod_pred: \"\n  \\<lbrakk> 0 < (n::nat); n mod m = 0 \\<rbrakk> \\<Longrightarrow>\n  (n - Suc 0) mod m = m - Suc 0\"\napply (case_tac \"m = 0\", simp_all)\napply (simp only: Suc_le_eq[symmetric])\napply (simp only: mod_diff1_eq)\napply (case_tac \"m = Suc 0\")\napply simp_all\ndone\n\nlemma mod_pred: \"\n  0 < n \\<Longrightarrow>\n  (n - Suc 0) mod m = (\n    if n mod m = 0 then m - Suc 0 else n mod m - Suc 0)\"\napply (split if_split, rule conjI)\n apply (simp add: mod_0_imp_mod_pred)\napply clarsimp\napply (case_tac \"m = Suc 0\", simp)\napply (frule subst[OF Suc0_mod[symmetric], where P=\"\\<lambda>x. x \\<le> n mod m\"], simp)\napply (simp only: mod_diff1_eq1)\napply (simp add: Suc0_mod)\ndone\ncorollary mod_pred_Suc_mod: \"\n  0 < n \\<Longrightarrow> Suc ((n - Suc 0) mod m) mod m = n mod m\"\napply (case_tac \"m = 0\", simp)\napply (simp add: mod_pred)\ndone\ncorollary diff_mod_pred: \"\n  a < b \\<Longrightarrow>\n  (b - Suc a) mod m = (\n    if a mod m = b mod m then m - Suc 0 else (b - a) mod m - Suc 0)\"\napply (rule_tac t=\"b - Suc a\" and s=\"b - a - Suc 0\" in subst, simp)\napply (subst mod_pred, simp)\napply (simp add: mod_eq_diff_mod_0_conv)\ndone\ncorollary diff_mod_pred_Suc_mod: \"\n  a < b \\<Longrightarrow> Suc ((b - Suc a) mod m) mod m = (b - a) mod m\"\napply (case_tac \"m = 0\", simp)\napply (simp add: diff_mod_pred mod_eq_diff_mod_0_conv)\ndone\n\nlemma mod_eq_imp_diff_mod_eq_divisor: \"\n  \\<lbrakk> a < b; 0 < m; a mod m = b mod m \\<rbrakk> \\<Longrightarrow>\n  Suc ((b - Suc a) mod m) = m\"\napply (drule mod_eq_imp_diff_mod_0[of a])\napply (frule iffD2[OF zero_less_diff])\napply (drule mod_0_imp_mod_pred[of \"b-a\" m], assumption)\napply simp\ndone\n\n\nlemma sub_diff_mod_eq: \"\n  r \\<le> t \\<Longrightarrow> (t - (t - r) mod m) mod (m::nat) = r mod m\"\nby (metis mod_diff_right_eq diff_diff_cancel diff_le_self)\n\nlemma sub_diff_mod_eq': \"\n  r \\<le> t \\<Longrightarrow> (k * m + t - (t - r) mod m) mod (m::nat) = r mod m\"\napply (simp only: diff_mod_le[of t r m, THEN add_diff_assoc, symmetric])\napply (simp add: sub_diff_mod_eq)\ndone\n\nlemma mod_eq_Suc_0_conv: \"Suc 0 < k \\<Longrightarrow> ((x + k - Suc 0) mod k = 0) = (x mod k = Suc 0)\"\napply (simp only: mod_pred)\napply (case_tac \"x mod k = Suc 0\")\napply simp_all\ndone\n\nlemma mod_eq_divisor_minus_Suc_0_conv: \"Suc 0 < k \\<Longrightarrow> (x mod k = k - Suc 0) = (Suc x mod k = 0)\"\nby (simp only: mod_Suc, split if_split, fastforce)\n\n\nsubsubsection \\<open>Some auxiliary facts about \\<open>div\\<close>\\<close>\n\nlemma sub_mod_div_eq_div: \"((n::nat) - n mod m) div m = n div m\"\napply (case_tac \"m = 0\", simp)\napply (simp add: minus_mod_eq_mult_div)\ndone\n\nlemma mod_less_imp_diff_div_conv: \"\n  \\<lbrakk> n mod m < r; r \\<le> m + n mod m\\<rbrakk> \\<Longrightarrow> (n - r) div m = n div m - Suc 0\"\n  apply (case_tac \"m = 0\", simp)\n  apply (simp only: neq0_conv)\n  apply (case_tac \"n < m\", simp)\n  apply (simp only: linorder_not_less)\n  apply (rule div_nat_eqI)\n   apply (simp_all add: algebra_simps minus_mod_eq_mult_div [symmetric])\n  done\n\ncorollary mod_0_le_imp_diff_div_conv: \"\n  \\<lbrakk> n mod m = 0; 0 < r; r \\<le> m \\<rbrakk> \\<Longrightarrow> (n - r) div m = n div m - Suc 0\"\nby (simp add: mod_less_imp_diff_div_conv)\ncorollary mod_0_less_imp_diff_Suc_div_conv: \"\n  \\<lbrakk> n mod m = 0; r < m \\<rbrakk> \\<Longrightarrow> (n - Suc r) div m = n div m - Suc 0\"\nby (drule mod_0_le_imp_diff_div_conv[where r=\"Suc r\"], simp_all)\ncorollary mod_0_imp_diff_Suc_div_conv: \"\n  (n - r) mod m = 0 \\<Longrightarrow> (n - Suc r) div m = (n - r) div m - Suc 0\"\napply (case_tac \"m = 0\", simp)\napply (rule_tac t=\"n - Suc r\" and s=\"n - r - Suc 0\" in subst, simp)\napply (rule mod_0_le_imp_diff_div_conv, simp+)\ndone\ncorollary mod_0_imp_sub_1_div_conv: \"\n  n mod m = 0 \\<Longrightarrow> (n - Suc 0) div m = n div m - Suc 0\"\napply (case_tac \"m = 0\", simp)\napply (simp add: mod_0_less_imp_diff_Suc_div_conv)\ndone\ncorollary sub_Suc_mod_div_conv: \"\n  (n - Suc (n mod m)) div m = n div m - Suc 0\"\napply (case_tac \"m = 0\", simp)\napply (simp add: mod_less_imp_diff_div_conv)\ndone\n\n\nlemma div_le_conv: \"0 < m \\<Longrightarrow> n div m \\<le> k = (n \\<le> Suc k * m - Suc 0)\"\napply (rule iffI)\n apply (drule mult_le_mono1[of _ _ m])\n apply (simp only: mult.commute[of _ m] minus_mod_eq_mult_div [symmetric])\n apply (drule le_diff_conv[THEN iffD1])\n apply (rule le_trans[of _ \"m * k + n mod m\"], assumption)\n apply (simp add: add.commute[of m])\n apply (simp only: diff_add_assoc[OF Suc_leI])\n apply (rule add_le_mono[OF le_refl])\n apply (rule less_imp_le_pred)\n apply (rule mod_less_divisor, assumption)\napply (drule div_le_mono[of _ _ m])\napply (simp add: mod_0_imp_sub_1_div_conv)\ndone\n\nlemma le_div_conv: \"0 < (m::nat) \\<Longrightarrow> (n \\<le> k div m) = (n * m \\<le> k)\"\napply (rule iffI)\n apply (drule mult_le_mono1[of _ _ m])\n apply (simp add: div_mult_cancel)\napply (drule div_le_mono[of _ _ m])\napply simp\ndone\n\nlemma less_mult_imp_div_less: \"n < k * m \\<Longrightarrow> n div m < (k::nat)\"\napply (case_tac \"k = 0\", simp)\napply (case_tac \"m = 0\", simp)\napply simp\napply (drule less_imp_le_pred[of n])\napply (drule div_le_mono[of _ _ m])\napply (simp add: mod_0_imp_sub_1_div_conv)\ndone\n\nlemma div_less_imp_less_mult: \"\\<lbrakk> 0 < (m::nat); n div m < k \\<rbrakk> \\<Longrightarrow> n < k * m\"\napply (rule ccontr, simp only: linorder_not_less)\napply (drule div_le_mono[of _ _ m])\napply simp\ndone\n\nlemma div_less_conv: \"0 < (m::nat) \\<Longrightarrow> (n div m < k) = (n < k * m)\"\napply (rule iffI)\napply (rule div_less_imp_less_mult, assumption+)\napply (rule less_mult_imp_div_less, assumption)\ndone\n\nlemma div_eq_0_conv: \"(n div (m::nat) = 0) = (m = 0 \\<or> n < m)\"\napply (rule iffI)\n apply (case_tac \"m = 0\", simp)\n apply (rule ccontr)\n apply (simp add: linorder_not_less)\n apply (drule div_le_mono[of _ _ m])\n apply simp\napply fastforce\ndone\nlemma div_eq_0_conv': \"0 < m \\<Longrightarrow> (n div (m::nat) = 0) = (n < m)\"\nby (simp add: div_eq_0_conv)\ncorollary div_gr_imp_gr_divisor: \"x < n div (m::nat) \\<Longrightarrow> m \\<le> n\"\napply (drule gr_implies_gr0, drule neq0_conv[THEN iffD2])\napply (simp add: div_eq_0_conv)\ndone\n\nlemma mod_0_less_div_conv: \"\n  n mod (m::nat) = 0 \\<Longrightarrow> (k * m < n) = (k < n div m)\"\napply (case_tac \"m = 0\", simp)\napply fastforce\ndone\n\nlemma add_le_divisor_imp_le_Suc_div: \"\n  \\<lbrakk> x div m \\<le> n; y \\<le> m \\<rbrakk> \\<Longrightarrow> (x + y) div m \\<le> Suc n\"\napply (case_tac \"m = 0\", simp)\napply (simp only: div_add1_eq_if[of _ x])\napply (drule order_le_less[of y, THEN iffD1], fastforce)\ndone\n\n\ntext \\<open>List of definitions and lemmas\\<close>\n\nthm\n  minus_mod_eq_mult_div [symmetric]\n  mod_0_div_mult_cancel\n  div_mult_le\n  less_div_Suc_mult\nthm\n  Suc0_mod\n  Suc0_mod_subst\n  Suc0_mod_cong\n\nthm\n  mod_Suc_conv\n\nthm\n  mod_add\n  mod_sub_add\n\nthm\n  mod_sub_eq_mod_0_conv\n  mod_sub_eq_mod_swap\n\nthm\n  le_mod_greater_imp_div_less\nthm\n  mod_diff_right_eq\n  mod_eq_imp_diff_mod_eq\n\nthm\n  divisor_add_diff_mod_if\n  divisor_add_diff_mod_eq1\n  divisor_add_diff_mod_eq2\n\nthm\n  mod_add_eq\n  mod_add1_eq_if\nthm\n  mod_diff1_eq_if\n  mod_diff1_eq\n  mod_diff1_eq1\n  mod_diff1_eq2\n\nthm\n  Divides.nat_mod_distrib\n  int_mod_distrib\n\nthm\n  zmod_zminus_eq_conv\n\nthm\n  mod_eq_imp_diff_mod_0\n  zmod_eq_imp_diff_mod_0\n\nthm\n  mod_neq_imp_diff_mod_neq0\n  diff_mod_0_imp_mod_eq\n  zdiff_mod_0_imp_mod_eq\n\nthm\n  zmod_eq_diff_mod_0_conv\n  mod_eq_diff_mod_0_conv\n\nthm\n  less_mod_eq_imp_add_divisor_le\nthm\n  mod_add_eq_imp_mod_0\nthm\n  mod_eq_mult_distrib\n  mod_factor_imp_mod_0\n  mod_factor_div\n  mod_factor_div_mod\n\n\nthm\n  mod_diff_self1\n  mod_diff_self2\n  mod_diff_mult_self1\n  mod_diff_mult_self2\n\nthm\n  div_diff_self1\n  div_diff_self2\n  div_diff_mult_self1\n  div_diff_mult_self2\n\nthm\n  le_less_imp_div\n  div_imp_le_less\nthm\n  le_less_div_conv\n\nthm\n  diff_less_divisor_imp_sub_mod_eq\n  diff_ge_divisor_imp_sub_mod_less\n  le_imp_sub_mod_le\n\nthm\n  sub_mod_div_eq_div\n\nthm\n  mod_less_imp_diff_div_conv\n  mod_0_le_imp_diff_div_conv\n  mod_0_less_imp_diff_Suc_div_conv\n  mod_0_imp_sub_1_div_conv\n\n\nthm\n  sub_Suc_mod_div_conv\n\nthm\n  mod_less_diff_mod\n  mod_0_imp_mod_pred\n\nthm\n  mod_pred\n  mod_pred_Suc_mod\n\nthm\n  mod_eq_imp_diff_mod_eq_divisor\n\nthm\n  diff_mod_le\n  sub_diff_mod_eq\n  sub_diff_mod_eq'\n\nthm\n  div_diff1_eq_if\n  div_diff1_eq\n  div_diff1_eq1\n  div_diff1_eq2\n\n\nthm\n  div_le_conv\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_Div.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8558511579973931, "lm_q2_score": 0.8397339656668286, "lm_q1q2_score": 0.7186872869256984}}
{"text": "(*  Title:       DiscreteCategory\n    Author:      Eugene W. Stark <stark@cs.stonybrook.edu>, 2016\n    Maintainer:  Eugene W. Stark <stark@cs.stonybrook.edu>\n*)\n\nchapter DiscreteCategory\n\ntheory DiscreteCategory\nimports Category\nbegin\n\n  text\\<open>\n    The locale defined here permits us to construct a discrete category having\n    a specified set of objects, assuming that the set does not exhaust the elements\n    of its type.  In that case, we have the convenient situation that the arrows of\n    the category can be directly identified with the elements of the given set,\n    rather than having to pass between the two via tedious coercion maps.\n    If it cannot be guaranteed that the given set is not the universal set at its type,\n    then the more general discrete category construction defined (using coercions)\n    in \\<open>FreeCategory\\<close> can be used.\n\\<close>\n\n  locale discrete_category =\n    fixes Obj :: \"'a set\"\n    and Null :: 'a\n    assumes Null_not_in_Obj: \"Null \\<notin> Obj\"\n  begin\n\n    definition comp :: \"'a comp\"      (infixr \"\\<cdot>\" 55)\n    where \"y \\<cdot> x \\<equiv> (if x \\<in> Obj \\<and> x = y then x else Null)\"\n\n    interpretation partial_magma comp\n      apply unfold_locales\n      using comp_def by metis\n\n    lemma null_char:\n    shows \"null = Null\"\n      using comp_def null_def by auto\n\n    lemma ide_char [iff]:\n    shows \"ide f \\<longleftrightarrow> f \\<in> Obj\"\n      using comp_def null_char ide_def Null_not_in_Obj by auto\n\n    lemma domains_char:\n    shows \"domains f = {x. x \\<in> Obj \\<and> x = f}\"\n      unfolding domains_def\n      using ide_char ide_def comp_def null_char by metis\n\n    theorem is_category:\n    shows \"category comp\"\n      using comp_def\n      apply unfold_locales\n      using arr_def null_char self_domain_iff_ide ide_char\n           apply fastforce\n      using null_char self_codomain_iff_ide domains_char codomains_def ide_char\n          apply fastforce\n         apply (metis not_arr_null null_char)\n        apply (metis not_arr_null null_char)\n      by auto\n\n  end\n\n  sublocale discrete_category \\<subseteq> category comp\n    using is_category by auto\n\n  context discrete_category\n  begin\n\n    lemma arr_char [iff]:\n    shows \"arr f \\<longleftrightarrow> f \\<in> Obj\"\n      using comp_def comp_cod_arr\n      by (metis empty_iff has_codomain_iff_arr not_arr_null null_char self_codomain_iff_ide ide_char)\n\n    lemma dom_char [simp]:\n    shows \"dom f = (if f \\<in> Obj then f else null)\"\n      using arr_def dom_def arr_char ideD(2) by auto\n\n    lemma cod_char [simp]:\n    shows \"cod f = (if f \\<in> Obj then f else null)\"\n      using arr_def in_homE cod_def ideD(3) by auto\n\n    lemma comp_char [simp]:\n    shows \"comp g f = (if f \\<in> Obj \\<and> f = g then f else null)\"\n      using comp_def null_char by auto\n\n    lemma is_discrete:\n    shows \"ide = arr\"\n      using arr_char ide_char by auto\n\n  end\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/Category3/DiscreteCategory.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511469672595, "lm_q2_score": 0.8397339736884712, "lm_q1q2_score": 0.7186872845286526}}
{"text": "(* \n  Author: Jeremy Dawson, NICTA\n*) \n\nsection \\<open>Integers as implict bit strings\\<close>\n\ntheory Bit_Representation\nimports Misc_Numeric\nbegin\n\nsubsection \\<open>Constructors and destructors for binary integers\\<close>\n\ndefinition Bit :: \"int \\<Rightarrow> bool \\<Rightarrow> int\" (infixl \"BIT\" 90)\nwhere\n  \"k BIT b = (if b then 1 else 0) + k + k\"\n\nlemma Bit_B0:\n  \"k BIT False = k + k\"\n   by (unfold Bit_def) simp\n\nlemma Bit_B1:\n  \"k BIT True = k + k + 1\"\n   by (unfold Bit_def) simp\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\ndefinition bin_last :: \"int \\<Rightarrow> bool\"\nwhere\n  \"bin_last w \\<longleftrightarrow> w mod 2 = 1\"\n\nlemma bin_last_odd:\n  \"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\"\nwhere\n  \"bin_rest w = w div 2\"\n\nlemma bin_rl_simp [simp]:\n  \"bin_rest w BIT bin_last w = w\"\n  unfolding bin_rest_def bin_last_def Bit_def\n  using div_mult_mod_eq [of w 2]\n  by (cases \"w mod 2 = 0\", 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  apply (auto simp add: Bit_def)\n  apply arith\n  apply arith\n  done\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  unfolding Bit_def\n  by (simp_all del: arith_simps add_numeral_special diff_numeral_special)\n\nlemma BIT_special_simps [simp]:\n  shows \"0 BIT False = 0\" and \"0 BIT True = 1\"\n  and \"1 BIT False = 2\" and \"1 BIT True = 3\"\n  and \"(- 1) BIT False = - 2\" and \"(- 1) BIT True = - 1\"\n  unfolding Bit_def by simp_all\n\nlemma Bit_eq_0_iff: \"w BIT b = 0 \\<longleftrightarrow> w = 0 \\<and> \\<not> b\"\n  apply (auto simp add: Bit_def)\n  apply arith\n  done\n\nlemma Bit_eq_m1_iff: \"w BIT b = -1 \\<longleftrightarrow> w = -1 \\<and> b\"\n  apply (auto simp add: Bit_def)\n  apply arith\n  done\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  unfolding add_One by (simp_all add: 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) (auto simp add: divmod_def)\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) (auto simp add: divmod_def)\n\nlemma less_Bits: \n  \"v BIT b < w BIT c \\<longleftrightarrow> v < w \\<or> v \\<le> w \\<and> \\<not> b \\<and> c\"\n  unfolding Bit_def by auto\n\nlemma le_Bits: \n  \"v BIT b \\<le> w BIT c \\<longleftrightarrow> v < w \\<or> v \\<le> w \\<and> (\\<not> b \\<or> c)\" \n  unfolding Bit_def by auto\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': \n  \"X = 2 ==> (w BIT True) mod X = 1 & (w BIT False) mod X = 0\"\n  apply (simp (no_asm) only: Bit_B0 Bit_B1)\n  apply simp\n  done\n\nlemma bin_ex_rl: \"EX w b. w BIT b = bin\"\n  by (metis bin_rl_simp)\n\nlemma bin_exhaust:\n  assumes Q: \"\\<And>x b. bin = x BIT b \\<Longrightarrow> Q\"\n  shows \"Q\"\n  apply (insert bin_ex_rl [of bin])  \n  apply (erule exE)+\n  apply (rule Q)\n  apply force\n  done\n\nprimrec bin_nth 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_abs_lem:\n  \"bin = (w BIT b) ==> bin ~= -1 --> bin ~= 0 -->\n    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: \"!!bin bit. P bin ==> P (bin BIT bit)\"\n  shows \"P bin\"\n  apply (rule_tac P=P and a=bin and f1=\"nat o abs\" \n                  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_nth_eq_iff:\n  \"bin_nth x = bin_nth y \\<longleftrightarrow> x = y\"\nproof -\n  have bin_nth_lem [rule_format]: \"ALL y. bin_nth x = bin_nth y --> 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, \n            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, \n           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\nlemmas bin_eqI = ext [THEN bin_nth_eq_iff [THEN iffD1]]\n\nlemma bin_eq_iff:\n  \"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 ==> bin_nth (w BIT b) n = bin_nth w (n - 1)\"\n  by (cases n) auto\n\nlemma bin_nth_numeral:\n  \"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\n\nsubsection \\<open>Truncating binary integers\\<close>\n\ndefinition bin_sign :: \"int \\<Rightarrow> int\"\nwhere\n  bin_sign_def: \"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  unfolding bin_sign_def Bit_def\n  by simp_all\n\nlemma bin_sign_rest [simp]: \n  \"bin_sign (bin_rest w) = bin_sign w\"\n  by (cases w rule: bin_exhaust) auto\n\nprimrec bintrunc :: \"nat \\<Rightarrow> int \\<Rightarrow> int\" 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 => int => int\" 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 sign_bintr: \"bin_sign (bintrunc n w) = 0\"\n  by (induct n arbitrary: w) auto\n\nlemma bintrunc_mod2p: \"bintrunc n w = (w mod 2 ^ n)\"\n  apply (induct n arbitrary: w, clarsimp)\n  apply (simp add: bin_last_def bin_rest_def Bit_def zmod_zmult2_eq)\n  done\n\nlemma sbintrunc_mod2p: \"sbintrunc n w = (w + 2 ^ n) mod 2 ^ (Suc n) - 2 ^ n\"\n  apply (induct n arbitrary: w)\n   apply simp\n   apply (subst mod_add_left_eq)\n   apply (simp add: bin_last_def)\n   apply arith\n  apply (simp add: bin_last_def bin_rest_def Bit_def)\n  apply (clarsimp simp: mod_mult_mult1 [symmetric] \n         mult_div_mod_eq [symmetric, THEN diff_eq_eq [THEN iffD2 [THEN sym]]])\n  apply (rule trans [symmetric, OF _ emep1])\n  apply auto\n  done\n\nsubsection \"Simplifications for (s)bintrunc\"\n\nlemma bintrunc_n_0 [simp]: \"bintrunc n 0 = 0\"\n  by (induct n) auto\n\nlemma sbintrunc_n_0 [simp]: \"sbintrunc n 0 = 0\"\n  by (induct n) auto\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)) =\n    bintrunc n (- numeral w) BIT False\"\n  \"bintrunc (Suc n) (- numeral (Num.Bit1 w)) =\n    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)) =\n    sbintrunc n (numeral w) BIT False\"\n  \"sbintrunc (Suc n) (numeral (Num.Bit1 w)) =\n    sbintrunc n (numeral w) BIT True\"\n  \"sbintrunc (Suc n) (- numeral (Num.Bit0 w)) =\n    sbintrunc n (- numeral w) BIT False\"\n  \"sbintrunc (Suc n) (- numeral (Num.Bit1 w)) =\n    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 = (n < m & 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:\n  \"bin_nth (sbintrunc m w) n = \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:\n  \"bin_nth (w BIT b) n = (n = 0 & b | (EX m. n = Suc m & 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  \"n <= m ==> (bintrunc m (bintrunc n w) = bintrunc n w)\"\n  by (rule bin_eqI) (auto simp add : nth_bintr)\n\nlemma sbintrunc_sbintrunc_l:\n  \"n <= m ==> (sbintrunc m (sbintrunc n w) = sbintrunc n w)\"\n  by (rule bin_eqI) (auto simp: nth_sbintr)\n\nlemma bintrunc_bintrunc_ge:\n  \"n <= m ==> (bintrunc n (bintrunc m w) = bintrunc n w)\"\n  by (rule bin_eqI) (auto simp: nth_bintr)\n\nlemma bintrunc_bintrunc_min [simp]:\n  \"bintrunc m (bintrunc n w) = bintrunc (min m n) w\"\n  apply (rule bin_eqI)\n  apply (auto simp: nth_bintr)\n  done\n\nlemma sbintrunc_sbintrunc_min [simp]:\n  \"sbintrunc m (sbintrunc n w) = sbintrunc (min m n) w\"\n  apply (rule bin_eqI)\n  apply (auto simp: nth_sbintr min.absorb1 min.absorb2)\n  done\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\", \n               simplified bin_last_numeral_simps bin_rest_numeral_simps]\n\nlemmas sbintrunc_Min = \n  sbintrunc.Z [where bin=\"-1\",\n               simplified bin_last_numeral_simps bin_rest_numeral_simps]\n\nlemmas sbintrunc_0_BIT_B0 [simp] = \n  sbintrunc.Z [where bin=\"w BIT False\", \n               simplified bin_last_numeral_simps bin_rest_numeral_simps] for w\n\nlemmas sbintrunc_0_BIT_B1 [simp] = \n  sbintrunc.Z [where bin=\"w BIT True\", \n               simplified bin_last_BIT bin_rest_numeral_simps] 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:\n  \"0 < n ==> bintrunc (Suc (n - 1)) w = bintrunc n w\"\n  by auto\n\nlemma sbintrunc_minus:\n  \"0 < n ==> 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 = \"%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:\n  \"bintrunc (Suc n) x = y ==> m = Suc n ==> 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:\n  \"sbintrunc (Suc n) x = y ==> m = Suc n ==> 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:\n  \"m > n ==> sbintrunc n (bintrunc m w) = sbintrunc n w\"\n  by (rule bin_eqI) (auto simp: nth_sbintr nth_bintr)\n\nlemma bintrunc_sbintrunc_le:\n  \"m <= Suc n ==> bintrunc m (sbintrunc n w) = bintrunc m w\"\n  apply (rule bin_eqI)\n  apply (auto simp: nth_sbintr nth_bintr)\n   apply (subgoal_tac \"x=n\", safe, arith+)[1]\n  apply (subgoal_tac \"x=n\", safe, arith+)[1]\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]:\n  \"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]:\n  \"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: \n  \"bintrunc (Suc n) x = bintrunc (Suc n) y \\<longleftrightarrow> \n   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> \n            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 =\n    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 =\n    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)) =\n    bintrunc (pred_numeral k) (numeral w) BIT False\"\n  \"bintrunc (numeral k) (numeral (Num.Bit1 w)) =\n    bintrunc (pred_numeral k) (numeral w) BIT True\"\n  \"bintrunc (numeral k) (- numeral (Num.Bit0 w)) =\n    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)) =\n    sbintrunc (pred_numeral k) (numeral w) BIT False\"\n  \"sbintrunc (numeral k) (numeral (Num.Bit1 w)) =\n    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 <= i & i < 2 ^ n}\"\n  apply (unfold no_bintr_alt1)\n  apply (auto simp add: image_iff)\n  apply (rule exI)\n  apply (auto intro: int_mod_lem [THEN iffD1, symmetric])\n  done\n\nlemma no_sbintr_alt2: \n  \"sbintrunc n = (%w. (w + 2 ^ n) mod 2 ^ Suc n - 2 ^ n :: int)\"\n  by (rule ext) (simp add : sbintrunc_mod2p)\n\nlemma range_sbintrunc: \n  \"range (sbintrunc n) = {i. - (2 ^ n) <= i & i < 2 ^ n}\"\n  apply (unfold no_sbintr_alt2)\n  apply (auto simp add: image_iff eq_diff_eq)\n  apply (rule exI)\n  apply (auto intro: int_mod_lem [THEN iffD1, symmetric])\n  done\n\nlemma sb_inc_lem:\n  \"(a::int) + 2^k < 0 \\<Longrightarrow> a + 2^k + 2^(Suc k) <= (a + 2^k) mod 2^(Suc k)\"\n  apply (erule int_mod_ge' [where n = \"2 ^ (Suc k)\" and b = \"a + 2 ^ k\", simplified zless2p])\n  apply (rule TrueI)\n  done\n\nlemma sb_inc_lem':\n  \"(a::int) < - (2^k) \\<Longrightarrow> a + 2^k + 2^(Suc k) <= (a + 2^k) mod 2^(Suc k)\"\n  by (rule sb_inc_lem) simp\n\nlemma sbintrunc_inc:\n  \"x < - (2^n) ==> x + 2^(Suc n) <= sbintrunc n x\"\n  unfolding no_sbintr_alt2 by (drule sb_inc_lem') simp\n\nlemma sb_dec_lem:\n  \"(0::int) \\<le> - (2 ^ k) + a \\<Longrightarrow> (a + 2 ^ k) mod (2 * 2 ^ k) \\<le> - (2 ^ k) + a\"\n  using int_mod_le'[where n = \"2 ^ (Suc k)\" and b = \"a + 2 ^ k\"] by simp\n\nlemma sb_dec_lem':\n  \"(2::int) ^ k \\<le> a \\<Longrightarrow> (a + 2 ^ k) mod (2 * 2 ^ k) \\<le> - (2 ^ k) + a\"\n  by (rule sb_dec_lem) simp\n\nlemma sbintrunc_dec:\n  \"x >= (2 ^ n) ==> x - 2 ^ (Suc n) >= sbintrunc n x\"\n  unfolding no_sbintr_alt2 by (drule sb_dec_lem') simp\n\nlemmas zmod_uminus' = zminus_zmod [where m=c] for c\nlemmas zpower_zmod' = power_mod [where b=c and n=k] for c k\n\nlemmas brdmod1s' [symmetric] =\n  mod_add_left_eq mod_add_right_eq\n  mod_diff_left_eq mod_diff_right_eq\n  mod_mult_left_eq mod_mult_right_eq\n\nlemmas brdmods' [symmetric] = \n  zpower_zmod' [symmetric]\n  trans [OF mod_add_left_eq mod_add_right_eq] \n  trans [OF mod_diff_left_eq mod_diff_right_eq] \n  trans [OF mod_mult_right_eq mod_mult_left_eq] \n  zmod_uminus' [symmetric]\n  mod_add_left_eq [where b = \"1::int\"]\n  mod_diff_left_eq [where b = \"1::int\"]\n\nlemmas bintr_arith1s =\n  brdmod1s' [where c=\"2^n::int\", folded bintrunc_mod2p] for n\nlemmas bintr_ariths =\n  brdmods' [where c=\"2^n::int\", folded bintrunc_mod2p] for n\n\nlemmas m2pths = pos_mod_sign pos_mod_bound [OF zless2p]\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: \n  \"(bin_sign bin = 0) = (bin >= (0 :: int))\"\n  unfolding bin_sign_def by simp\n\nlemma sign_Min_lt_0: \n  \"(bin_sign bin = -1) = (bin < (0 :: int))\"\n  unfolding bin_sign_def by simp\n\nlemma bin_rest_trunc:\n  \"(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) = \n    bintrunc (n - k) ((bin_rest ^^ k) bin)\"\n  by (induct k) (auto simp: bin_rest_trunc)\n\nlemma bin_rest_trunc_i:\n  \"bintrunc n (bin_rest bin) = bin_rest (bintrunc (Suc n) bin)\"\n  by auto\n\nlemma bin_rest_strunc:\n  \"bin_rest (sbintrunc (Suc n) bin) = sbintrunc n (bin_rest bin)\"\n  by (induct n arbitrary: bin) auto\n\nlemma bintrunc_rest [simp]: \n  \"bintrunc n (bin_rest (bintrunc n bin)) = bin_rest (bintrunc n bin)\"\n  apply (induct n arbitrary: bin, simp)\n  apply (case_tac bin rule: bin_exhaust)\n  apply (auto simp: bintrunc_bintrunc_l)\n  done\n\nlemma sbintrunc_rest [simp]:\n  \"sbintrunc n (bin_rest (sbintrunc n bin)) = bin_rest (sbintrunc n bin)\"\n  apply (induct n arbitrary: bin, 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':\n  \"bintrunc n o bin_rest o bintrunc n = bin_rest o bintrunc n\"\n  by (rule ext) auto\n\nlemma sbintrunc_rest' :\n  \"sbintrunc n o bin_rest o sbintrunc n = bin_rest o sbintrunc n\"\n  by (rule ext) auto\n\nlemma rco_lem:\n  \"f o g o f = g o f ==> f o (g o f) ^^ n = g ^^ n o 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\" where\n  Z: \"bin_split 0 w = (w, 0)\"\n  | Suc: \"bin_split (Suc n) w = (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\" 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\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/Word/Bit_Representation.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.855851143290548, "lm_q2_score": 0.8397339736884712, "lm_q1q2_score": 0.7186872814411931}}
{"text": "section \\<open>The Lexicographic Path Order as an instance of WPO\\<close>\n\ntext \\<open>We first directly define the strict- and non-strict lexicographic path orders (LPO)\n  w.r.t.\\ some precedence, and then show that it is an instance of WPO.\n  For this instance we use the trivial reduction pair in WPO ($\\emptyset$, UNIV) and\n  the status is the full one, i.e., taking parameters [0,..,n-1] for each n-ary symbol.\\<close>\n\ntheory LPO\n  imports\n    WPO\nbegin\n\ncontext\n  fixes \"pr\" :: \"('f \\<times> nat \\<Rightarrow> 'f \\<times> nat \\<Rightarrow> bool \\<times> bool)\"\n    and prl :: \"'f \\<times> nat \\<Rightarrow> bool\"\n    and n :: nat\nbegin\nfun lpo :: \"('f, 'v) term \\<Rightarrow> ('f, 'v) term \\<Rightarrow> bool \\<times> bool\" \n  where\n    \"lpo (Var x) (Var y) = (False, x = y)\" |\n    \"lpo (Var x) (Fun g ts) = (False, ts = [] \\<and> prl (g,0))\" |\n    \"lpo (Fun f ss) (Var y) = (let con = (\\<exists> s \\<in> set ss. snd (lpo s (Var y))) in (con,con))\" |\n    \"lpo (Fun f ss) (Fun g ts) = (\n      if (\\<exists> s \\<in> set ss. snd (lpo s (Fun g ts)))\n         then (True,True)\n         else (let (prs,prns) = pr (f,length ss) (g,length ts) in \n           if prns \\<and> (\\<forall> t \\<in> set ts. fst (lpo (Fun f ss) t))\n           then if prs\n              then (True,True) \n              else lex_ext lpo n ss ts\n           else (False,False)))\"\n\nend\n\n\nlocale lpo_with_assms = precedence prc prl\n  for prc :: \"'f \\<times> nat \\<Rightarrow> 'f \\<times> nat \\<Rightarrow> bool \\<times> bool\"\n    and prl :: \"'f \\<times> nat \\<Rightarrow> bool\"\n    and n :: nat\nbegin\n\nsublocale wpo_with_assms n \"{}\" UNIV prc prl full_status \"\\<lambda> _. Lex\" False \"\\<lambda> _. False\"\n  by (unfold_locales, auto simp: refl_on_def trans_def simple_arg_pos_def)\n\nabbreviation \"lpo_pr \\<equiv> lpo prc prl n\" \nabbreviation \"lpo_s \\<equiv> \\<lambda> s t. fst (lpo_pr s t)\"\nabbreviation \"lpo_ns \\<equiv> \\<lambda> s t. snd (lpo_pr s t)\"\n\nlemma lpo_eq_wpo: \"lpo_pr s t = wpo s t\"\nproof - \n  note simps = wpo.simps\n  show ?thesis \n  proof (induct s t rule: lpo.induct[of _ prc prl n])\n    case (1 x y)\n    then show ?case by (simp add: simps)\n  next\n    case (2 x g ts)\n    then show ?case by (auto simp: simps)\n  next\n    case (3 f ss y)\n    then show ?case by (auto simp: simps[of \"Fun f ss\" \"Var y\"] Let_def set_conv_nth)\n  next\n    case IH: (4 f ss g ts)\n    have id: \"\\<And> s. (s \\<in> {}) = False\" \"\\<And> s. (s \\<in> UNIV) = True\" \n      and \"(\\<exists>i\\<in>{0..<length ss}. wpo_ns (ss ! i) t) = (\\<exists>si\\<in>set ss. wpo_ns si t)\" \n      by (auto, force simp: set_conv_nth) \n    have id': \"map ((!) ss) (\\<sigma> (f, length ss)) = ss\" for f ss by (intro nth_equalityI, auto)\n    have ex: \"(\\<exists>i\\<in>set (\\<sigma> (f, length ss)). wpo_ns (ss ! i) (Fun g ts)) = (\\<exists> si \\<in> set ss. lpo_ns si (Fun g ts))\" \n      using IH(1) unfolding set_conv_nth by auto\n    obtain prs prns where prc: \"prc (f, length ss) (g, length ts) = (prs, prns)\" by force\n    have lex: \"(Lex = Lex \\<and> Lex = Lex) = True\" by simp\n    show ?case\n      unfolding lpo.simps simps[of \"Fun f ss\" \"Fun g ts\"] term.simps id id' if_False if_True lex\n        Let_def ex prc split\n    proof (rule sym, rule if_cong[OF refl refl], rule if_cong[OF conj_cong[OF refl] if_cong[OF refl refl] refl])\n      assume \"\\<not> (\\<exists>si\\<in>set ss. lpo_ns si (Fun g ts))\" \n      note IH = IH(2-)[OF this prc[symmetric] refl]\n      from IH(1) show \"(\\<forall>j\\<in>set (\\<sigma> (g, length ts)). wpo_s (Fun f ss) (ts ! j)) = (\\<forall>t\\<in>set ts. lpo_s (Fun f ss) t)\"\n        unfolding set_conv_nth by auto\n      assume \"prns \\<and> (\\<forall>t\\<in>set ts. lpo_s (Fun f ss) t)\" \"\\<not> prs\" \n      note IH = IH(2-)[OF this]\n      show \"lex_ext wpo n ss ts = lex_ext lpo_pr n ss ts\" \n        using IH by (intro lex_ext_cong, auto)\n    qed\n  qed\nqed\n\nabbreviation \"LPO_S \\<equiv> {(s,t). lpo_s s t}\"\nabbreviation \"LPO_NS \\<equiv> {(s,t). lpo_ns s t}\"\n\ntheorem LPO_SN_order_pair: \"SN_order_pair LPO_S LPO_NS\"\n  unfolding lpo_eq_wpo by (rule WPO_SN_order_pair)\n\ntheorem LPO_S_subst: \"(s,t) \\<in> LPO_S \\<Longrightarrow> (s \\<cdot> \\<sigma>, t \\<cdot> \\<sigma>) \\<in> LPO_S\" for \\<sigma> :: \"('f,'a)subst\" \n  using WPO_S_subst unfolding lpo_eq_wpo .\n\ntheorem LPO_NS_subst: \"(s,t) \\<in> LPO_NS \\<Longrightarrow> (s \\<cdot> \\<sigma>, t \\<cdot> \\<sigma>) \\<in> LPO_NS\" for \\<sigma> :: \"('f,'a)subst\"\n  using WPO_NS_subst unfolding lpo_eq_wpo .\n\ntheorem LPO_NS_ctxt: \"(s,t) \\<in> LPO_NS \\<Longrightarrow> (Fun f (bef @ s # aft), Fun f (bef @ t # aft)) \\<in> LPO_NS\" \n  using WPO_NS_ctxt unfolding lpo_eq_wpo .\n\ntheorem LPO_S_ctxt: \"(s,t) \\<in> LPO_S \\<Longrightarrow> (Fun f (bef @ s # aft), Fun f (bef @ t # aft)) \\<in> LPO_S\" \n  using WPO_S_ctxt unfolding lpo_eq_wpo by auto\n\ntheorem LPO_S_subset_LPO_NS: \"LPO_S \\<subseteq> LPO_NS\" \n  using WPO_S_subset_WPO_NS unfolding lpo_eq_wpo .\n\ntheorem supt_subset_LPO_S: \"{\\<rhd>} \\<subseteq> LPO_S\" \n  using supt_subset_WPO_S unfolding lpo_eq_wpo by auto\n\ntheorem supteq_subset_LPO_NS: \"{\\<unrhd>} \\<subseteq> LPO_NS\" \n  using supteq_subset_WPO_NS unfolding lpo_eq_wpo by auto\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/Weighted_Path_Order/LPO.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.855851154320682, "lm_q2_score": 0.8397339616560072, "lm_q1q2_score": 0.7186872804055732}}
{"text": "(*  Title:      HOL/Analysis/Derivative.thy\n    Author:     John Harrison\n    Author:     Robert Himmelmann, TU Muenchen (translation from HOL Light); tidied by LCP\n*)\n\nsection \\<open>Derivative\\<close>\n\ntheory Derivative\n  imports\n    Bounded_Linear_Function\n    Line_Segment\n    Convex_Euclidean_Space\nbegin\n\ndeclare bounded_linear_inner_left [intro]\n\ndeclare has_derivative_bounded_linear[dest]\n\nsubsection \\<open>Derivatives\\<close>\n\nlemma has_derivative_add_const:\n  \"(f has_derivative f') net \\<Longrightarrow> ((\\<lambda>x. f x + c) has_derivative f') net\"\n  by (intro derivative_eq_intros) auto\n\n\nsubsection\\<^marker>\\<open>tag unimportant\\<close> \\<open>Derivative with composed bilinear function\\<close>\n\ntext \\<open>More explicit epsilon-delta forms.\\<close>\n\nproposition has_derivative_within':\n  \"(f has_derivative f')(at x within s) \\<longleftrightarrow>\n    bounded_linear f' \\<and>\n    (\\<forall>e>0. \\<exists>d>0. \\<forall>x'\\<in>s. 0 < norm (x' - x) \\<and> norm (x' - x) < d \\<longrightarrow>\n      norm (f x' - f x - f'(x' - x)) / norm (x' - x) < e)\"\n  unfolding has_derivative_within Lim_within dist_norm\n  by (simp add: diff_diff_eq)\n\nlemma has_derivative_at':\n  \"(f has_derivative f') (at x) \n   \\<longleftrightarrow> bounded_linear f' \\<and>\n       (\\<forall>e>0. \\<exists>d>0. \\<forall>x'. 0 < norm (x' - x) \\<and> norm (x' - x) < d \\<longrightarrow>\n        norm (f x' - f x - f'(x' - x)) / norm (x' - x) < e)\"\n  using has_derivative_within' [of f f' x UNIV] by simp\n\nlemma has_derivative_componentwise_within:\n   \"(f has_derivative f') (at a within S) \\<longleftrightarrow>\n    (\\<forall>i \\<in> Basis. ((\\<lambda>x. f x \\<bullet> i) has_derivative (\\<lambda>x. f' x \\<bullet> i)) (at a within S))\"\n  apply (simp add: has_derivative_within)\n  apply (subst tendsto_componentwise_iff)\n  apply (simp add: ball_conj_distrib  inner_diff_left inner_left_distrib flip: bounded_linear_componentwise_iff)\n  done\n\nlemma has_derivative_at_withinI:\n  \"(f has_derivative f') (at x) \\<Longrightarrow> (f has_derivative f') (at x within s)\"\n  unfolding has_derivative_within' has_derivative_at'\n  by blast\n\nlemma has_derivative_right:\n  fixes f :: \"real \\<Rightarrow> real\"\n    and y :: \"real\"\n  shows \"(f has_derivative ((*) y)) (at x within ({x <..} \\<inter> I)) \\<longleftrightarrow>\n         ((\\<lambda>t. (f x - f t) / (x - t)) \\<longlongrightarrow> y) (at x within ({x <..} \\<inter> I))\"\nproof -\n  have \"((\\<lambda>t. (f t - (f x + y * (t - x))) / \\<bar>t - x\\<bar>) \\<longlongrightarrow> 0) (at x within ({x<..} \\<inter> I)) \\<longleftrightarrow>\n    ((\\<lambda>t. (f t - f x) / (t - x) - y) \\<longlongrightarrow> 0) (at x within ({x<..} \\<inter> I))\"\n    by (intro Lim_cong_within) (auto simp add: diff_divide_distrib add_divide_distrib)\n  also have \"\\<dots> \\<longleftrightarrow> ((\\<lambda>t. (f t - f x) / (t - x)) \\<longlongrightarrow> y) (at x within ({x<..} \\<inter> I))\"\n    by (simp add: Lim_null[symmetric])\n  also have \"\\<dots> \\<longleftrightarrow> ((\\<lambda>t. (f x - f t) / (x - t)) \\<longlongrightarrow> y) (at x within ({x<..} \\<inter> I))\"\n    by (intro Lim_cong_within) (simp_all add: field_simps)\n  finally show ?thesis\n    by (simp add: bounded_linear_mult_right has_derivative_within)\nqed\n\nsubsubsection \\<open>Caratheodory characterization\\<close>\n\nlemma DERIV_caratheodory_within:\n  \"(f has_field_derivative l) (at x within S) \\<longleftrightarrow>\n   (\\<exists>g. (\\<forall>z. f z - f x = g z * (z - x)) \\<and> continuous (at x within S) g \\<and> g x = l)\"\n      (is \"?lhs = ?rhs\")\nproof\n  assume ?lhs\n  show ?rhs\n  proof (intro exI conjI)\n    let ?g = \"(%z. if z = x then l else (f z - f x) / (z-x))\"\n    show \"\\<forall>z. f z - f x = ?g z * (z-x)\" by simp\n    show \"continuous (at x within S) ?g\" using \\<open>?lhs\\<close>\n      by (auto simp add: continuous_within has_field_derivative_iff cong: Lim_cong_within)\n    show \"?g x = l\" by simp\n  qed\nnext\n  assume ?rhs\n  then obtain g where\n    \"(\\<forall>z. f z - f x = g z * (z-x))\" and \"continuous (at x within S) g\" and \"g x = l\" by blast\n  thus ?lhs\n    by (auto simp add: continuous_within has_field_derivative_iff cong: Lim_cong_within)\nqed\n\nsubsection \\<open>Differentiability\\<close>\n\ndefinition\\<^marker>\\<open>tag important\\<close>\n  differentiable_on :: \"('a::real_normed_vector \\<Rightarrow> 'b::real_normed_vector) \\<Rightarrow> 'a set \\<Rightarrow> bool\"\n    (infix \"differentiable'_on\" 50)\n  where \"f differentiable_on s \\<longleftrightarrow> (\\<forall>x\\<in>s. f differentiable (at x within s))\"\n\nlemma differentiableI: \"(f has_derivative f') net \\<Longrightarrow> f differentiable net\"\n  unfolding differentiable_def\n  by auto\n\nlemma differentiable_onD: \"\\<lbrakk>f differentiable_on S; x \\<in> S\\<rbrakk> \\<Longrightarrow> f differentiable (at x within S)\"\n  using differentiable_on_def by blast\n\nlemma differentiable_at_withinI: \"f differentiable (at x) \\<Longrightarrow> f differentiable (at x within s)\"\n  unfolding differentiable_def\n  using has_derivative_at_withinI\n  by blast\n\nlemma differentiable_at_imp_differentiable_on:\n  \"(\\<And>x. x \\<in> s \\<Longrightarrow> f differentiable at x) \\<Longrightarrow> f differentiable_on s\"\n  by (metis differentiable_at_withinI differentiable_on_def)\n\ncorollary\\<^marker>\\<open>tag unimportant\\<close> differentiable_iff_scaleR:\n  fixes f :: \"real \\<Rightarrow> 'a::real_normed_vector\"\n  shows \"f differentiable F \\<longleftrightarrow> (\\<exists>d. (f has_derivative (\\<lambda>x. x *\\<^sub>R d)) F)\"\n  by (auto simp: differentiable_def dest: has_derivative_linear linear_imp_scaleR)\n\nlemma differentiable_on_eq_differentiable_at:\n  \"open s \\<Longrightarrow> f differentiable_on s \\<longleftrightarrow> (\\<forall>x\\<in>s. f differentiable at x)\"\n  unfolding differentiable_on_def\n  by (metis at_within_interior interior_open)\n\nlemma differentiable_transform_within:\n  assumes \"f differentiable (at x within s)\"\n    and \"0 < d\"\n    and \"x \\<in> s\"\n    and \"\\<And>x'. \\<lbrakk>x'\\<in>s; dist x' x < d\\<rbrakk> \\<Longrightarrow> f x' = g x'\"\n  shows \"g differentiable (at x within s)\"\n   using assms has_derivative_transform_within unfolding differentiable_def\n   by blast\n\nlemma differentiable_on_ident [simp, derivative_intros]: \"(\\<lambda>x. x) differentiable_on S\"\n  by (simp add: differentiable_at_imp_differentiable_on)\n\nlemma differentiable_on_id [simp, derivative_intros]: \"id differentiable_on S\"\n  by (simp add: id_def)\n\nlemma differentiable_on_const [simp, derivative_intros]: \"(\\<lambda>z. c) differentiable_on S\"\n  by (simp add: differentiable_on_def)\n\nlemma differentiable_on_mult [simp, derivative_intros]:\n  fixes f :: \"'M::real_normed_vector \\<Rightarrow> 'a::real_normed_algebra\"\n  shows \"\\<lbrakk>f differentiable_on S; g differentiable_on S\\<rbrakk> \\<Longrightarrow> (\\<lambda>z. f z * g z) differentiable_on S\"\n  unfolding differentiable_on_def differentiable_def\n  using differentiable_def differentiable_mult by blast\n\nlemma differentiable_on_compose:\n   \"\\<lbrakk>g differentiable_on S; f differentiable_on (g ` S)\\<rbrakk> \\<Longrightarrow> (\\<lambda>x. f (g x)) differentiable_on S\"\nby (simp add: differentiable_in_compose differentiable_on_def)\n\nlemma bounded_linear_imp_differentiable_on: \"bounded_linear f \\<Longrightarrow> f differentiable_on S\"\n  by (simp add: differentiable_on_def bounded_linear_imp_differentiable)\n\nlemma linear_imp_differentiable_on:\n  fixes f :: \"'a::euclidean_space \\<Rightarrow> 'b::real_normed_vector\"\n  shows \"linear f \\<Longrightarrow> f differentiable_on S\"\nby (simp add: differentiable_on_def linear_imp_differentiable)\n\nlemma differentiable_on_minus [simp, derivative_intros]:\n   \"f differentiable_on S \\<Longrightarrow> (\\<lambda>z. -(f z)) differentiable_on S\"\nby (simp add: differentiable_on_def)\n\nlemma differentiable_on_add [simp, derivative_intros]:\n   \"\\<lbrakk>f differentiable_on S; g differentiable_on S\\<rbrakk> \\<Longrightarrow> (\\<lambda>z. f z + g z) differentiable_on S\"\nby (simp add: differentiable_on_def)\n\nlemma differentiable_on_diff [simp, derivative_intros]:\n   \"\\<lbrakk>f differentiable_on S; g differentiable_on S\\<rbrakk> \\<Longrightarrow> (\\<lambda>z. f z - g z) differentiable_on S\"\nby (simp add: differentiable_on_def)\n\nlemma differentiable_on_inverse [simp, derivative_intros]:\n  fixes f :: \"'a :: real_normed_vector \\<Rightarrow> 'b :: real_normed_field\"\n  shows \"f differentiable_on S \\<Longrightarrow> (\\<And>x. x \\<in> S \\<Longrightarrow> f x \\<noteq> 0) \\<Longrightarrow> (\\<lambda>x. inverse (f x)) differentiable_on S\"\nby (simp add: differentiable_on_def)\n\nlemma differentiable_on_scaleR [derivative_intros, simp]:\n   \"\\<lbrakk>f differentiable_on S; g differentiable_on S\\<rbrakk> \\<Longrightarrow> (\\<lambda>x. f x *\\<^sub>R g x) differentiable_on S\"\n  unfolding differentiable_on_def\n  by (blast intro: differentiable_scaleR)\n\nlemma has_derivative_sqnorm_at [derivative_intros, simp]:\n  \"((\\<lambda>x. (norm x)\\<^sup>2) has_derivative (\\<lambda>x. 2 *\\<^sub>R (a \\<bullet> x))) (at a)\"\n  using bounded_bilinear.FDERIV  [of \"(\\<bullet>)\" id id a _ id id]\n  by (auto simp: inner_commute dot_square_norm bounded_bilinear_inner)\n\nlemma differentiable_sqnorm_at [derivative_intros, simp]:\n  fixes a :: \"'a :: {real_normed_vector,real_inner}\"\n  shows \"(\\<lambda>x. (norm x)\\<^sup>2) differentiable (at a)\"\nby (force simp add: differentiable_def intro: has_derivative_sqnorm_at)\n\nlemma differentiable_on_sqnorm [derivative_intros, simp]:\n  fixes S :: \"'a :: {real_normed_vector,real_inner} set\"\n  shows \"(\\<lambda>x. (norm x)\\<^sup>2) differentiable_on S\"\nby (simp add: differentiable_at_imp_differentiable_on)\n\nlemma differentiable_norm_at [derivative_intros, simp]:\n  fixes a :: \"'a :: {real_normed_vector,real_inner}\"\n  shows \"a \\<noteq> 0 \\<Longrightarrow> norm differentiable (at a)\"\nusing differentiableI has_derivative_norm by blast\n\nlemma differentiable_on_norm [derivative_intros, simp]:\n  fixes S :: \"'a :: {real_normed_vector,real_inner} set\"\n  shows \"0 \\<notin> S \\<Longrightarrow> norm differentiable_on S\"\nby (metis differentiable_at_imp_differentiable_on differentiable_norm_at)\n\n\nsubsection \\<open>Frechet derivative and Jacobian matrix\\<close>\n\ndefinition \"frechet_derivative f net = (SOME f'. (f has_derivative f') net)\"\n\nproposition frechet_derivative_works:\n  \"f differentiable net \\<longleftrightarrow> (f has_derivative (frechet_derivative f net)) net\"\n  unfolding frechet_derivative_def differentiable_def\n  unfolding some_eq_ex[of \"\\<lambda> f' . (f has_derivative f') net\"] ..\n\nlemma linear_frechet_derivative: \"f differentiable net \\<Longrightarrow> linear (frechet_derivative f net)\"\n  unfolding frechet_derivative_works has_derivative_def\n  by (auto intro: bounded_linear.linear)\n\nlemma frechet_derivative_const [simp]: \"frechet_derivative (\\<lambda>x. c) (at a) = (\\<lambda>x. 0)\"\n  using differentiable_const frechet_derivative_works has_derivative_const has_derivative_unique by blast\n\nlemma frechet_derivative_id [simp]: \"frechet_derivative id (at a) = id\"\n  using differentiable_def frechet_derivative_works has_derivative_id has_derivative_unique by blast\n\nlemma frechet_derivative_ident [simp]: \"frechet_derivative (\\<lambda>x. x) (at a) = (\\<lambda>x. x)\"\n  by (metis eq_id_iff frechet_derivative_id)\n\n\nsubsection \\<open>Differentiability implies continuity\\<close>\n\nproposition differentiable_imp_continuous_within:\n  \"f differentiable (at x within s) \\<Longrightarrow> continuous (at x within s) f\"\n  by (auto simp: differentiable_def intro: has_derivative_continuous)\n\nlemma differentiable_imp_continuous_on:\n  \"f differentiable_on s \\<Longrightarrow> continuous_on s f\"\n  unfolding differentiable_on_def continuous_on_eq_continuous_within\n  using differentiable_imp_continuous_within by blast\n\nlemma differentiable_on_subset:\n  \"f differentiable_on t \\<Longrightarrow> s \\<subseteq> t \\<Longrightarrow> f differentiable_on s\"\n  unfolding differentiable_on_def\n  using differentiable_within_subset\n  by blast\n\nlemma differentiable_on_empty: \"f differentiable_on {}\"\n  unfolding differentiable_on_def\n  by auto\n\nlemma has_derivative_continuous_on:\n  \"(\\<And>x. x \\<in> s \\<Longrightarrow> (f has_derivative f' x) (at x within s)) \\<Longrightarrow> continuous_on s f\"\n  by (auto intro!: differentiable_imp_continuous_on differentiableI simp: differentiable_on_def)\n\ntext \\<open>Results about neighborhoods filter.\\<close>\n\nlemma eventually_nhds_metric_le:\n  \"eventually P (nhds a) = (\\<exists>d>0. \\<forall>x. dist x a \\<le> d \\<longrightarrow> P x)\"\n  unfolding eventually_nhds_metric by (safe, rule_tac x=\"d / 2\" in exI, auto)\n\nlemma le_nhds: \"F \\<le> nhds a \\<longleftrightarrow> (\\<forall>S. open S \\<and> a \\<in> S \\<longrightarrow> eventually (\\<lambda>x. x \\<in> S) F)\"\n  unfolding le_filter_def eventually_nhds by (fast elim: eventually_mono)\n\nlemma le_nhds_metric: \"F \\<le> nhds a \\<longleftrightarrow> (\\<forall>e>0. eventually (\\<lambda>x. dist x a < e) F)\"\n  unfolding le_filter_def eventually_nhds_metric by (fast elim: eventually_mono)\n\nlemma le_nhds_metric_le: \"F \\<le> nhds a \\<longleftrightarrow> (\\<forall>e>0. eventually (\\<lambda>x. dist x a \\<le> e) F)\"\n  unfolding le_filter_def eventually_nhds_metric_le by (fast elim: eventually_mono)\n\ntext \\<open>Several results are easier using a \"multiplied-out\" variant.\n(I got this idea from Dieudonne's proof of the chain rule).\\<close>\n\nlemma has_derivative_within_alt:\n  \"(f has_derivative f') (at x within s) \\<longleftrightarrow> bounded_linear f' \\<and>\n    (\\<forall>e>0. \\<exists>d>0. \\<forall>y\\<in>s. norm(y - x) < d \\<longrightarrow> norm (f y - f x - f' (y - x)) \\<le> e * norm (y - x))\"\n  unfolding has_derivative_within filterlim_def le_nhds_metric_le eventually_filtermap\n    eventually_at dist_norm diff_diff_eq\n  by (force simp add: linear_0 bounded_linear.linear pos_divide_le_eq)\n\nlemma has_derivative_within_alt2:\n  \"(f has_derivative f') (at x within s) \\<longleftrightarrow> bounded_linear f' \\<and>\n    (\\<forall>e>0. eventually (\\<lambda>y. norm (f y - f x - f' (y - x)) \\<le> e * norm (y - x)) (at x within s))\"\n  unfolding has_derivative_within filterlim_def le_nhds_metric_le eventually_filtermap\n    eventually_at dist_norm diff_diff_eq\n  by (force simp add: linear_0 bounded_linear.linear pos_divide_le_eq)\n\nlemma has_derivative_at_alt:\n  \"(f has_derivative f') (at x) \\<longleftrightarrow>\n    bounded_linear f' \\<and>\n    (\\<forall>e>0. \\<exists>d>0. \\<forall>y. norm(y - x) < d \\<longrightarrow> norm (f y - f x - f'(y - x)) \\<le> e * norm (y - x))\"\n  using has_derivative_within_alt[where s=UNIV]\n  by simp\n\n\nsubsection \\<open>The chain rule\\<close>\n\nproposition diff_chain_within[derivative_intros]:\n  assumes \"(f has_derivative f') (at x within s)\"\n    and \"(g has_derivative g') (at (f x) within (f ` s))\"\n  shows \"((g \\<circ> f) has_derivative (g' \\<circ> f'))(at x within s)\"\n  using has_derivative_in_compose[OF assms]\n  by (simp add: comp_def)\n\nlemma diff_chain_at[derivative_intros]:\n  \"(f has_derivative f') (at x) \\<Longrightarrow>\n    (g has_derivative g') (at (f x)) \\<Longrightarrow> ((g \\<circ> f) has_derivative (g' \\<circ> f')) (at x)\"\n  by (meson diff_chain_within has_derivative_at_withinI)\n\nlemma has_vector_derivative_shift: \"(f has_vector_derivative D x) (at x)\n           \\<Longrightarrow> ((+) d \\<circ> f has_vector_derivative D x) (at x)\"\n  using diff_chain_at [OF _ shift_has_derivative_id]\n  by (simp add: has_derivative_iff_Ex has_vector_derivative_def) \n  \nlemma has_vector_derivative_within_open:\n  \"a \\<in> S \\<Longrightarrow> open S \\<Longrightarrow>\n    (f has_vector_derivative f') (at a within S) \\<longleftrightarrow> (f has_vector_derivative f') (at a)\"\n  by (simp only: at_within_interior interior_open)\n\nlemma field_vector_diff_chain_within:\n assumes Df: \"(f has_vector_derivative f') (at x within S)\"\n     and Dg: \"(g has_field_derivative g') (at (f x) within f ` S)\"\n shows \"((g \\<circ> f) has_vector_derivative (f' * g')) (at x within S)\"\nusing diff_chain_within[OF Df[unfolded has_vector_derivative_def]\n                       Dg [unfolded has_field_derivative_def]]\n by (auto simp: o_def mult.commute has_vector_derivative_def)\n\nlemma vector_derivative_diff_chain_within:\n  assumes Df: \"(f has_vector_derivative f') (at x within S)\"\n     and Dg: \"(g has_derivative g') (at (f x) within f`S)\"\n  shows \"((g \\<circ> f) has_vector_derivative (g' f')) (at x within S)\"\nusing diff_chain_within[OF Df[unfolded has_vector_derivative_def] Dg]\n  linear.scaleR[OF has_derivative_linear[OF Dg]]\n  unfolding has_vector_derivative_def o_def\n  by (auto simp: o_def mult.commute has_vector_derivative_def)\n\n\nsubsection\\<^marker>\\<open>tag unimportant\\<close> \\<open>Composition rules stated just for differentiability\\<close>\n\nlemma differentiable_chain_at:\n  \"f differentiable (at x) \\<Longrightarrow>\n    g differentiable (at (f x)) \\<Longrightarrow> (g \\<circ> f) differentiable (at x)\"\n  unfolding differentiable_def\n  by (meson diff_chain_at)\n\nlemma differentiable_chain_within:\n  \"f differentiable (at x within S) \\<Longrightarrow>\n    g differentiable (at(f x) within (f ` S)) \\<Longrightarrow> (g \\<circ> f) differentiable (at x within S)\"\n  unfolding differentiable_def\n  by (meson diff_chain_within)\n\n\nsubsection \\<open>Uniqueness of derivative\\<close>\n\n\ntext\\<^marker>\\<open>tag important\\<close> \\<open>\n The general result is a bit messy because we need approachability of the\n limit point from any direction. But OK for nontrivial intervals etc.\n\\<close>\n\nproposition frechet_derivative_unique_within:\n  fixes f :: \"'a::euclidean_space \\<Rightarrow> 'b::real_normed_vector\"\n  assumes 1: \"(f has_derivative f') (at x within S)\"\n    and 2: \"(f has_derivative f'') (at x within S)\"\n    and S: \"\\<And>i e. \\<lbrakk>i\\<in>Basis; e>0\\<rbrakk> \\<Longrightarrow> \\<exists>d. 0 < \\<bar>d\\<bar> \\<and> \\<bar>d\\<bar> < e \\<and> (x + d *\\<^sub>R i) \\<in> S\"\n  shows \"f' = f''\"\nproof -\n  note as = assms(1,2)[unfolded has_derivative_def]\n  then interpret f': bounded_linear f' by auto\n  from as interpret f'': bounded_linear f'' by auto\n  have \"x islimpt S\" unfolding islimpt_approachable\n  proof (intro allI impI)\n    fix e :: real\n    assume \"e > 0\"\n    obtain d where \"0 < \\<bar>d\\<bar>\" and \"\\<bar>d\\<bar> < e\" and \"x + d *\\<^sub>R (SOME i. i \\<in> Basis) \\<in> S\"\n      using assms(3) SOME_Basis \\<open>e>0\\<close> by blast\n    then show \"\\<exists>x'\\<in>S. x' \\<noteq> x \\<and> dist x' x < e\"\n      by (rule_tac x=\"x + d *\\<^sub>R (SOME i. i \\<in> Basis)\" in bexI) (auto simp: dist_norm SOME_Basis nonzero_Basis)  qed\n  then have *: \"netlimit (at x within S) = x\"\n    by (simp add: Lim_ident_at trivial_limit_within)\n  show ?thesis\n  proof (rule linear_eq_stdbasis)\n    show \"linear f'\" \"linear f''\"\n      unfolding linear_conv_bounded_linear using as by auto\n  next\n    fix i :: 'a\n    assume i: \"i \\<in> Basis\"\n    define e where \"e = norm (f' i - f'' i)\"\n    show \"f' i = f'' i\"\n    proof (rule ccontr)\n      assume \"f' i \\<noteq> f'' i\"\n      then have \"e > 0\"\n        unfolding e_def by auto\n      obtain d where d:\n        \"0 < d\"\n        \"(\\<And>y. y\\<in>S \\<longrightarrow> 0 < dist y x \\<and> dist y x < d \\<longrightarrow>\n          dist ((f y - f x - f' (y - x)) /\\<^sub>R norm (y - x) -\n              (f y - f x - f'' (y - x)) /\\<^sub>R norm (y - x)) (0 - 0) < e)\"\n        using tendsto_diff [OF as(1,2)[THEN conjunct2]]\n        unfolding * Lim_within\n        using \\<open>e>0\\<close> by blast\n      obtain c where c: \"0 < \\<bar>c\\<bar>\" \"\\<bar>c\\<bar> < d \\<and> x + c *\\<^sub>R i \\<in> S\"\n        using assms(3) i d(1) by blast\n      have *: \"norm (- ((1 / \\<bar>c\\<bar>) *\\<^sub>R f' (c *\\<^sub>R i)) + (1 / \\<bar>c\\<bar>) *\\<^sub>R f'' (c *\\<^sub>R i)) =\n        norm ((1 / \\<bar>c\\<bar>) *\\<^sub>R (- (f' (c *\\<^sub>R i)) + f'' (c *\\<^sub>R i)))\"\n        unfolding scaleR_right_distrib by auto\n      also have \"\\<dots> = norm ((1 / \\<bar>c\\<bar>) *\\<^sub>R (c *\\<^sub>R (- (f' i) + f'' i)))\"\n        unfolding f'.scaleR f''.scaleR\n        unfolding scaleR_right_distrib scaleR_minus_right\n        by auto\n      also have \"\\<dots> = e\"\n        unfolding e_def\n        using c(1)\n        using norm_minus_cancel[of \"f' i - f'' i\"]\n        by auto\n      finally show False\n        using c\n        using d(2)[of \"x + c *\\<^sub>R i\"]\n        unfolding dist_norm\n        unfolding f'.scaleR f''.scaleR f'.add f''.add f'.diff f''.diff\n          scaleR_scaleR scaleR_right_diff_distrib scaleR_right_distrib\n        using i\n        by (auto simp: inverse_eq_divide)\n    qed\n  qed\nqed\n\nproposition frechet_derivative_unique_within_closed_interval:\n  fixes f::\"'a::euclidean_space \\<Rightarrow> 'b::real_normed_vector\"\n  assumes ab: \"\\<And>i. i\\<in>Basis \\<Longrightarrow> a\\<bullet>i < b\\<bullet>i\"\n    and x: \"x \\<in> cbox a b\"\n    and \"(f has_derivative f' ) (at x within cbox a b)\"\n    and \"(f has_derivative f'') (at x within cbox a b)\"\n  shows \"f' = f''\"\nproof (rule frechet_derivative_unique_within)\n  fix e :: real\n  fix i :: 'a\n  assume \"e > 0\" and i: \"i \\<in> Basis\"\n  then show \"\\<exists>d. 0 < \\<bar>d\\<bar> \\<and> \\<bar>d\\<bar> < e \\<and> x + d *\\<^sub>R i \\<in> cbox a b\"\n  proof (cases \"x\\<bullet>i = a\\<bullet>i\")\n    case True\n    with ab[of i] \\<open>e>0\\<close> x i show ?thesis\n      by (rule_tac x=\"(min (b\\<bullet>i - a\\<bullet>i) e) / 2\" in exI)\n         (auto simp add: mem_box field_simps inner_simps inner_Basis)\n  next\n    case False\n    moreover have \"a \\<bullet> i < x \\<bullet> i\"\n      using False i mem_box(2) x by force\n    moreover {\n      have \"a \\<bullet> i * 2 + min (x \\<bullet> i - a \\<bullet> i) e \\<le> a\\<bullet>i *2 + x\\<bullet>i - a\\<bullet>i\"\n        by auto\n      also have \"\\<dots> = a\\<bullet>i + x\\<bullet>i\"\n        by auto\n      also have \"\\<dots> \\<le> 2 * (x\\<bullet>i)\"\n        using \\<open>a \\<bullet> i < x \\<bullet> i\\<close> by auto\n      finally have \"a \\<bullet> i * 2 + min (x \\<bullet> i - a \\<bullet> i) e \\<le> x \\<bullet> i * 2\"\n        by auto\n    }\n    moreover have \"min (x \\<bullet> i - a \\<bullet> i) e \\<ge> 0\"\n      by (simp add: \\<open>0 < e\\<close> \\<open>a \\<bullet> i < x \\<bullet> i\\<close> less_eq_real_def)\n    then have \"x \\<bullet> i * 2 \\<le> b \\<bullet> i * 2 + min (x \\<bullet> i - a \\<bullet> i) e\"\n      using i mem_box(2) x by force\n    ultimately show ?thesis\n    using ab[of i] \\<open>e>0\\<close> x i \n      by (rule_tac x=\"- (min (x\\<bullet>i - a\\<bullet>i) e) / 2\" in exI)\n         (auto simp add: mem_box field_simps inner_simps inner_Basis)\n  qed\nqed (use assms in auto)\n\nlemma frechet_derivative_unique_within_open_interval:\n  fixes f::\"'a::euclidean_space \\<Rightarrow> 'b::real_normed_vector\"\n  assumes x: \"x \\<in> box a b\"\n    and f: \"(f has_derivative f' ) (at x within box a b)\" \"(f has_derivative f'') (at x within box a b)\"\n  shows \"f' = f''\"\nproof -\n  have \"at x within box a b = at x\"\n    by (metis x at_within_interior interior_open open_box)\n  with f show \"f' = f''\"\n    by (simp add: has_derivative_unique)\nqed\n\nlemma frechet_derivative_at:\n  \"(f has_derivative f') (at x) \\<Longrightarrow> f' = frechet_derivative f (at x)\"\n  using differentiable_def frechet_derivative_works has_derivative_unique by blast\n\nlemma frechet_derivative_compose:\n  \"frechet_derivative (f o g) (at x) = frechet_derivative (f) (at (g x)) o frechet_derivative g (at x)\"\n  if \"g differentiable at x\" \"f differentiable at (g x)\"\n  by (metis diff_chain_at frechet_derivative_at frechet_derivative_works that)\n\nlemma frechet_derivative_within_cbox:\n  fixes f :: \"'a::euclidean_space \\<Rightarrow> 'b::real_normed_vector\"\n  assumes \"\\<And>i. i\\<in>Basis \\<Longrightarrow> a\\<bullet>i < b\\<bullet>i\"\n    and \"x \\<in> cbox a b\"\n    and \"(f has_derivative f') (at x within cbox a b)\"\n  shows \"frechet_derivative f (at x within cbox a b) = f'\"\n  using assms\n  by (metis Derivative.differentiableI frechet_derivative_unique_within_closed_interval frechet_derivative_works)\n\nlemma frechet_derivative_transform_within_open:\n  \"frechet_derivative f (at x) = frechet_derivative g (at x)\"\n  if \"f differentiable at x\" \"open X\" \"x \\<in> X\" \"\\<And>x. x \\<in> X \\<Longrightarrow> f x = g x\"\n  by (meson frechet_derivative_at frechet_derivative_works has_derivative_transform_within_open that)\n\n\nsubsection \\<open>Derivatives of local minima and maxima are zero\\<close>\n\nlemma has_derivative_local_min:\n  fixes f :: \"'a::real_normed_vector \\<Rightarrow> real\"\n  assumes deriv: \"(f has_derivative f') (at x)\"\n  assumes min: \"eventually (\\<lambda>y. f x \\<le> f y) (at x)\"\n  shows \"f' = (\\<lambda>h. 0)\"\nproof\n  fix h :: 'a\n  interpret f': bounded_linear f'\n    using deriv by (rule has_derivative_bounded_linear)\n  show \"f' h = 0\"\n  proof (cases \"h = 0\")\n    case False\n    from min obtain d where d1: \"0 < d\" and d2: \"\\<forall>y\\<in>ball x d. f x \\<le> f y\"\n      unfolding eventually_at by (force simp: dist_commute)\n    have \"FDERIV (\\<lambda>r. x + r *\\<^sub>R h) 0 :> (\\<lambda>r. r *\\<^sub>R h)\"\n      by (intro derivative_eq_intros) auto\n    then have \"FDERIV (\\<lambda>r. f (x + r *\\<^sub>R h)) 0 :> (\\<lambda>k. f' (k *\\<^sub>R h))\"\n      by (rule has_derivative_compose, simp add: deriv)\n    then have \"DERIV (\\<lambda>r. f (x + r *\\<^sub>R h)) 0 :> f' h\"\n      unfolding has_field_derivative_def by (simp add: f'.scaleR mult_commute_abs)\n    moreover have \"0 < d / norm h\" using d1 and \\<open>h \\<noteq> 0\\<close> by simp\n    moreover have \"\\<forall>y. \\<bar>0 - y\\<bar> < d / norm h \\<longrightarrow> f (x + 0 *\\<^sub>R h) \\<le> f (x + y *\\<^sub>R h)\"\n      using \\<open>h \\<noteq> 0\\<close> by (auto simp add: d2 dist_norm pos_less_divide_eq)\n    ultimately show \"f' h = 0\"\n      by (rule DERIV_local_min)\n  qed simp\nqed\n\nlemma has_derivative_local_max:\n  fixes f :: \"'a::real_normed_vector \\<Rightarrow> real\"\n  assumes \"(f has_derivative f') (at x)\"\n  assumes \"eventually (\\<lambda>y. f y \\<le> f x) (at x)\"\n  shows \"f' = (\\<lambda>h. 0)\"\n  using has_derivative_local_min [of \"\\<lambda>x. - f x\" \"\\<lambda>h. - f' h\" \"x\"]\n  using assms unfolding fun_eq_iff by simp\n\nlemma differential_zero_maxmin:\n  fixes f::\"'a::real_normed_vector \\<Rightarrow> real\"\n  assumes \"x \\<in> S\"\n    and \"open S\"\n    and deriv: \"(f has_derivative f') (at x)\"\n    and mono: \"(\\<forall>y\\<in>S. f y \\<le> f x) \\<or> (\\<forall>y\\<in>S. f x \\<le> f y)\"\n  shows \"f' = (\\<lambda>v. 0)\"\n  using mono\nproof\n  assume \"\\<forall>y\\<in>S. f y \\<le> f x\"\n  with \\<open>x \\<in> S\\<close> and \\<open>open S\\<close> have \"eventually (\\<lambda>y. f y \\<le> f x) (at x)\"\n    unfolding eventually_at_topological by auto\n  with deriv show ?thesis\n    by (rule has_derivative_local_max)\nnext\n  assume \"\\<forall>y\\<in>S. f x \\<le> f y\"\n  with \\<open>x \\<in> S\\<close> and \\<open>open S\\<close> have \"eventually (\\<lambda>y. f x \\<le> f y) (at x)\"\n    unfolding eventually_at_topological by auto\n  with deriv show ?thesis\n    by (rule has_derivative_local_min)\nqed\n\nlemma differential_zero_maxmin_component:\n  fixes f :: \"'a::euclidean_space \\<Rightarrow> 'b::euclidean_space\"\n  assumes k: \"k \\<in> Basis\"\n    and ball: \"0 < e\" \"(\\<forall>y \\<in> ball x e. (f y)\\<bullet>k \\<le> (f x)\\<bullet>k) \\<or> (\\<forall>y\\<in>ball x e. (f x)\\<bullet>k \\<le> (f y)\\<bullet>k)\"\n    and diff: \"f differentiable (at x)\"\n  shows \"(\\<Sum>j\\<in>Basis. (frechet_derivative f (at x) j \\<bullet> k) *\\<^sub>R j) = (0::'a)\" (is \"?D k = 0\")\nproof -\n  let ?f' = \"frechet_derivative f (at x)\"\n  have \"x \\<in> ball x e\" using \\<open>0 < e\\<close> by simp\n  moreover have \"open (ball x e)\" by simp\n  moreover have \"((\\<lambda>x. f x \\<bullet> k) has_derivative (\\<lambda>h. ?f' h \\<bullet> k)) (at x)\"\n    using bounded_linear_inner_left diff[unfolded frechet_derivative_works]\n    by (rule bounded_linear.has_derivative)\n  ultimately have \"(\\<lambda>h. frechet_derivative f (at x) h \\<bullet> k) = (\\<lambda>v. 0)\"\n    using ball(2) by (rule differential_zero_maxmin)\n  then show ?thesis\n    unfolding fun_eq_iff by simp\nqed\n\nsubsection \\<open>One-dimensional mean value theorem\\<close>\n\nlemma mvt_simple:\n  fixes f :: \"real \\<Rightarrow> real\"\n  assumes \"a < b\"\n    and derf: \"\\<And>x. \\<lbrakk>a \\<le> x; x \\<le> b\\<rbrakk> \\<Longrightarrow> (f has_derivative f' x) (at x within {a..b})\"\n  shows \"\\<exists>x\\<in>{a<..<b}. f b - f a = f' x (b - a)\"\nproof (rule mvt)\n  have \"f differentiable_on {a..b}\"\n    using derf unfolding differentiable_on_def differentiable_def by force\n  then show \"continuous_on {a..b} f\"\n    by (rule differentiable_imp_continuous_on)\n  show \"(f has_derivative f' x) (at x)\" if \"a < x\" \"x < b\" for x\n    by (metis at_within_Icc_at derf leI order.asym that)\nqed (use assms in auto)\n\nlemma mvt_very_simple:\n  fixes f :: \"real \\<Rightarrow> real\"\n  assumes \"a \\<le> b\"\n    and derf: \"\\<And>x. \\<lbrakk>a \\<le> x; x \\<le> b\\<rbrakk> \\<Longrightarrow> (f has_derivative f' x) (at x within {a..b})\"\n  shows \"\\<exists>x\\<in>{a..b}. f b - f a = f' x (b - a)\"\nproof (cases \"a = b\")\n  interpret bounded_linear \"f' b\"\n    using assms(2) assms(1) by auto\n  case True\n  then show ?thesis\n    by force\nnext\n  case False\n  then show ?thesis\n    using mvt_simple[OF _ derf]\n    by (metis \\<open>a \\<le> b\\<close> atLeastAtMost_iff dual_order.order_iff_strict greaterThanLessThan_iff)\nqed\n\ntext \\<open>A nice generalization (see Havin's proof of 5.19 from Rudin's book).\\<close>\n\nlemma mvt_general:\n  fixes f :: \"real \\<Rightarrow> 'a::real_inner\"\n  assumes \"a < b\"\n    and contf: \"continuous_on {a..b} f\"\n    and derf: \"\\<And>x. \\<lbrakk>a < x; x < b\\<rbrakk> \\<Longrightarrow> (f has_derivative f' x) (at x)\"\n  shows \"\\<exists>x\\<in>{a<..<b}. norm (f b - f a) \\<le> norm (f' x (b - a))\"\nproof -\n  have \"\\<exists>x\\<in>{a<..<b}. (f b - f a) \\<bullet> f b - (f b - f a) \\<bullet> f a = (f b - f a) \\<bullet> f' x (b - a)\"\n    apply (rule mvt [OF \\<open>a < b\\<close>, where f = \"\\<lambda>x. (f b - f a) \\<bullet> f x\"])\n    apply (intro continuous_intros contf)\n    using derf apply (auto intro: has_derivative_inner_right)\n    done\n  then obtain x where x: \"x \\<in> {a<..<b}\"\n    \"(f b - f a) \\<bullet> f b - (f b - f a) \\<bullet> f a = (f b - f a) \\<bullet> f' x (b - a)\" ..\n  show ?thesis\n  proof (cases \"f a = f b\")\n    case False\n    have \"norm (f b - f a) * norm (f b - f a) = (norm (f b - f a))\\<^sup>2\"\n      by (simp add: power2_eq_square)\n    also have \"\\<dots> = (f b - f a) \\<bullet> (f b - f a)\"\n      unfolding power2_norm_eq_inner ..\n    also have \"\\<dots> = (f b - f a) \\<bullet> f' x (b - a)\"\n      using x(2) by (simp only: inner_diff_right)\n    also have \"\\<dots> \\<le> norm (f b - f a) * norm (f' x (b - a))\"\n      by (rule norm_cauchy_schwarz)\n    finally show ?thesis\n      using False x(1)\n      by (auto simp add: mult_left_cancel)\n  next\n    case True\n    then show ?thesis\n      using \\<open>a < b\\<close> by (rule_tac x=\"(a + b) /2\" in bexI) auto\n  qed\nqed\n\n\nsubsection \\<open>More general bound theorems\\<close>\n\nproposition differentiable_bound_general:\n  fixes f :: \"real \\<Rightarrow> 'a::real_normed_vector\"\n  assumes \"a < b\"\n    and f_cont: \"continuous_on {a..b} f\"\n    and phi_cont: \"continuous_on {a..b} \\<phi>\"\n    and f': \"\\<And>x. a < x \\<Longrightarrow> x < b \\<Longrightarrow> (f has_vector_derivative f' x) (at x)\"\n    and phi': \"\\<And>x. a < x \\<Longrightarrow> x < b \\<Longrightarrow> (\\<phi> has_vector_derivative \\<phi>' x) (at x)\"\n    and bnd: \"\\<And>x. a < x \\<Longrightarrow> x < b \\<Longrightarrow> norm (f' x) \\<le> \\<phi>' x\"\n  shows \"norm (f b - f a) \\<le> \\<phi> b - \\<phi> a\"\nproof -\n  {\n    fix x assume x: \"a < x\" \"x < b\"\n    have \"0 \\<le> norm (f' x)\" by simp\n    also have \"\\<dots> \\<le> \\<phi>' x\" using x by (auto intro!: bnd)\n    finally have \"0 \\<le> \\<phi>' x\" .\n  } note phi'_nonneg = this\n  note f_tendsto = assms(2)[simplified continuous_on_def, rule_format]\n  note phi_tendsto = assms(3)[simplified continuous_on_def, rule_format]\n  {\n    fix e::real assume \"e > 0\"\n    define e2 where \"e2 = e / 2\"\n    with \\<open>e > 0\\<close> have \"e2 > 0\" by simp\n    let ?le = \"\\<lambda>x1. norm (f x1 - f a) \\<le> \\<phi> x1 - \\<phi> a + e * (x1 - a) + e\"\n    define A where \"A = {x2. a \\<le> x2 \\<and> x2 \\<le> b \\<and> (\\<forall>x1\\<in>{a ..< x2}. ?le x1)}\"\n    have A_subset: \"A \\<subseteq> {a..b}\" by (auto simp: A_def)\n    {\n      fix x2\n      assume a: \"a \\<le> x2\" \"x2 \\<le> b\" and le: \"\\<forall>x1\\<in>{a..<x2}. ?le x1\"\n      have \"?le x2\" using \\<open>e > 0\\<close>\n      proof cases\n        assume \"x2 \\<noteq> a\" with a have \"a < x2\" by simp\n        have \"at x2 within {a <..<x2}\\<noteq> bot\"\n          using \\<open>a < x2\\<close>\n          by (auto simp: trivial_limit_within islimpt_in_closure)\n        moreover\n        have \"((\\<lambda>x1. (\\<phi> x1 - \\<phi> a) + e * (x1 - a) + e) \\<longlongrightarrow> (\\<phi> x2 - \\<phi> a) + e * (x2 - a) + e) (at x2 within {a <..<x2})\"\n          \"((\\<lambda>x1. norm (f x1 - f a)) \\<longlongrightarrow> norm (f x2 - f a)) (at x2 within {a <..<x2})\"\n          using a\n          by (auto intro!: tendsto_eq_intros f_tendsto phi_tendsto\n            intro: tendsto_within_subset[where S=\"{a..b}\"])\n        moreover\n        have \"eventually (\\<lambda>x. x > a) (at x2 within {a <..<x2})\"\n          by (auto simp: eventually_at_filter)\n        hence \"eventually ?le (at x2 within {a <..<x2})\"\n          unfolding eventually_at_filter\n          by eventually_elim (insert le, auto)\n        ultimately\n        show ?thesis\n          by (rule tendsto_le)\n      qed simp\n    } note le_cont = this\n    have \"a \\<in> A\"\n      using assms by (auto simp: A_def)\n    hence [simp]: \"A \\<noteq> {}\" by auto\n    have A_ivl: \"\\<And>x1 x2. x2 \\<in> A \\<Longrightarrow> x1 \\<in> {a ..x2} \\<Longrightarrow> x1 \\<in> A\"\n      by (simp add: A_def)\n    have [simp]: \"bdd_above A\" by (auto simp: A_def)\n    define y where \"y = Sup A\"\n    have \"y \\<le> b\"\n      unfolding y_def\n      by (simp add: cSup_le_iff) (simp add: A_def)\n     have leI: \"\\<And>x x1. a \\<le> x1 \\<Longrightarrow> x \\<in> A \\<Longrightarrow> x1 < x \\<Longrightarrow> ?le x1\"\n       by (auto simp: A_def intro!: le_cont)\n    have y_all_le: \"\\<forall>x1\\<in>{a..<y}. ?le x1\"\n      by (auto simp: y_def less_cSup_iff leI)\n    have \"a \\<le> y\"\n      by (metis \\<open>a \\<in> A\\<close> \\<open>bdd_above A\\<close> cSup_upper y_def)\n    have \"y \\<in> A\"\n      using y_all_le \\<open>a \\<le> y\\<close> \\<open>y \\<le> b\\<close>\n      by (auto simp: A_def)\n    hence \"A = {a .. y}\"\n      using A_subset by (auto simp: subset_iff y_def cSup_upper intro: A_ivl)\n    from le_cont[OF \\<open>a \\<le> y\\<close> \\<open>y \\<le> b\\<close> y_all_le] have le_y: \"?le y\" .\n    have \"y = b\"\n    proof (cases \"a = y\")\n      case True\n      with \\<open>a < b\\<close> have \"y < b\" by simp\n      with \\<open>a = y\\<close> f_cont phi_cont \\<open>e2 > 0\\<close>\n      have 1: \"\\<forall>\\<^sub>F x in at y within {y..b}. dist (f x) (f y) < e2\"\n       and 2: \"\\<forall>\\<^sub>F x in at y within {y..b}. dist (\\<phi> x) (\\<phi> y) < e2\"\n        by (auto simp: continuous_on_def tendsto_iff)\n      have 3: \"eventually (\\<lambda>x. y < x) (at y within {y..b})\"\n        by (auto simp: eventually_at_filter)\n      have 4: \"eventually (\\<lambda>x::real. x < b) (at y within {y..b})\"\n        using _ \\<open>y < b\\<close>\n        by (rule order_tendstoD) (auto intro!: tendsto_eq_intros)\n      from 1 2 3 4\n      have eventually_le: \"eventually (\\<lambda>x. ?le x) (at y within {y .. b})\"\n      proof eventually_elim\n        case (elim x1)\n        have \"norm (f x1 - f a) = norm (f x1 - f y)\"\n          by (simp add: \\<open>a = y\\<close>)\n        also have \"norm (f x1 - f y) \\<le> e2\"\n          using elim \\<open>a = y\\<close> by (auto simp : dist_norm intro!:  less_imp_le)\n        also have \"\\<dots> \\<le> e2 + (\\<phi> x1 - \\<phi> a + e2 + e * (x1 - a))\"\n          using \\<open>0 < e\\<close> elim\n          by (intro add_increasing2[OF add_nonneg_nonneg order.refl])\n            (auto simp: \\<open>a = y\\<close> dist_norm intro!: mult_nonneg_nonneg)\n        also have \"\\<dots> = \\<phi> x1 - \\<phi> a + e * (x1 - a) + e\"\n          by (simp add: e2_def)\n        finally show \"?le x1\" .\n      qed\n      from this[unfolded eventually_at_topological] \\<open>?le y\\<close>\n      obtain S where S: \"open S\" \"y \\<in> S\" \"\\<And>x. x\\<in>S \\<Longrightarrow> x \\<in> {y..b} \\<Longrightarrow> ?le x\"\n        by metis\n      from \\<open>open S\\<close> obtain d where d: \"\\<And>x. dist x y < d \\<Longrightarrow> x \\<in> S\" \"d > 0\"\n        by (force simp: dist_commute open_dist ball_def dest!: bspec[OF _ \\<open>y \\<in> S\\<close>])\n      define d' where \"d' = min b (y + (d/2))\"\n      have \"d' \\<in> A\"\n        unfolding A_def\n      proof safe\n        show \"a \\<le> d'\" using \\<open>a = y\\<close> \\<open>0 < d\\<close> \\<open>y < b\\<close> by (simp add: d'_def)\n        show \"d' \\<le> b\" by (simp add: d'_def)\n        fix x1\n        assume \"x1 \\<in> {a..<d'}\"\n        hence \"x1 \\<in> S\" \"x1 \\<in> {y..b}\"\n          by (auto simp: \\<open>a = y\\<close> d'_def dist_real_def intro!: d )\n        thus \"?le x1\"\n          by (rule S)\n      qed\n      hence \"d' \\<le> y\"\n        unfolding y_def\n        by (rule cSup_upper) simp\n      then show \"y = b\" using \\<open>d > 0\\<close> \\<open>y < b\\<close>\n        by (simp add: d'_def)\n    next\n      case False\n      with \\<open>a \\<le> y\\<close> have \"a < y\" by simp\n      show \"y = b\"\n      proof (rule ccontr)\n        assume \"y \\<noteq> b\"\n        hence \"y < b\" using \\<open>y \\<le> b\\<close> by simp\n        let ?F = \"at y within {y..<b}\"\n        from f' phi'\n        have \"(f has_vector_derivative f' y) ?F\"\n          and \"(\\<phi> has_vector_derivative \\<phi>' y) ?F\"\n          using \\<open>a < y\\<close> \\<open>y < b\\<close>\n          by (auto simp add: at_within_open[of _ \"{a<..<b}\"] has_vector_derivative_def\n            intro!: has_derivative_subset[where s=\"{a<..<b}\" and t=\"{y..<b}\"])\n        hence \"\\<forall>\\<^sub>F x1 in ?F. norm (f x1 - f y - (x1 - y) *\\<^sub>R f' y) \\<le> e2 * \\<bar>x1 - y\\<bar>\"\n            \"\\<forall>\\<^sub>F x1 in ?F. norm (\\<phi> x1 - \\<phi> y - (x1 - y) *\\<^sub>R \\<phi>' y) \\<le> e2 * \\<bar>x1 - y\\<bar>\"\n          using \\<open>e2 > 0\\<close>\n          by (auto simp: has_derivative_within_alt2 has_vector_derivative_def)\n        moreover\n        have \"\\<forall>\\<^sub>F x1 in ?F. y \\<le> x1\" \"\\<forall>\\<^sub>F x1 in ?F. x1 < b\"\n          by (auto simp: eventually_at_filter)\n        ultimately\n        have \"\\<forall>\\<^sub>F x1 in ?F. norm (f x1 - f y) \\<le> (\\<phi> x1 - \\<phi> y) + e * \\<bar>x1 - y\\<bar>\"\n          (is \"\\<forall>\\<^sub>F x1 in ?F. ?le' x1\")\n        proof eventually_elim\n          case (elim x1)\n          from norm_triangle_ineq2[THEN order_trans, OF elim(1)]\n          have \"norm (f x1 - f y) \\<le> norm (f' y) * \\<bar>x1 - y\\<bar> + e2 * \\<bar>x1 - y\\<bar>\"\n            by (simp add: ac_simps)\n          also have \"norm (f' y) \\<le> \\<phi>' y\" using bnd \\<open>a < y\\<close> \\<open>y < b\\<close> by simp\n          also have \"\\<phi>' y * \\<bar>x1 - y\\<bar> \\<le> \\<phi> x1 - \\<phi> y + e2 * \\<bar>x1 - y\\<bar>\"\n            using elim by (simp add: ac_simps)\n          finally\n          have \"norm (f x1 - f y) \\<le> \\<phi> x1 - \\<phi> y + e2 * \\<bar>x1 - y\\<bar> + e2 * \\<bar>x1 - y\\<bar>\"\n            by (auto simp: mult_right_mono)\n          thus ?case by (simp add: e2_def)\n        qed\n        moreover have \"?le' y\" by simp\n        ultimately obtain S\n        where S: \"open S\" \"y \\<in> S\" \"\\<And>x. x\\<in>S \\<Longrightarrow> x \\<in> {y..<b} \\<Longrightarrow> ?le' x\"\n          unfolding eventually_at_topological\n          by metis\n        from \\<open>open S\\<close> obtain d where d: \"\\<And>x. dist x y < d \\<Longrightarrow> x \\<in> S\" \"d > 0\"\n          by (force simp: dist_commute open_dist ball_def dest!: bspec[OF _ \\<open>y \\<in> S\\<close>])\n        define d' where \"d' = min ((y + b)/2) (y + (d/2))\"\n        have \"d' \\<in> A\"\n          unfolding A_def\n        proof safe\n          show \"a \\<le> d'\" using \\<open>a < y\\<close> \\<open>0 < d\\<close> \\<open>y < b\\<close> by (simp add: d'_def)\n          show \"d' \\<le> b\" using \\<open>y < b\\<close> by (simp add: d'_def min_def)\n          fix x1\n          assume x1: \"x1 \\<in> {a..<d'}\"\n          show \"?le x1\"\n          proof (cases \"x1 < y\")\n            case True\n            then show ?thesis\n              using \\<open>y \\<in> A\\<close> local.leI x1 by auto\n          next\n            case False\n            hence x1': \"x1 \\<in> S\" \"x1 \\<in> {y..<b}\" using x1\n              by (auto simp: d'_def dist_real_def intro!: d)\n            have \"norm (f x1 - f a) \\<le> norm (f x1 - f y) + norm (f y - f a)\"\n              by (rule order_trans[OF _ norm_triangle_ineq]) simp\n            also note S(3)[OF x1']\n            also note le_y\n            finally show \"?le x1\"\n              using False by (auto simp: algebra_simps)\n          qed\n        qed\n        hence \"d' \\<le> y\"\n          unfolding y_def by (rule cSup_upper) simp\n        thus False using \\<open>d > 0\\<close> \\<open>y < b\\<close>\n          by (simp add: d'_def min_def split: if_split_asm)\n      qed\n    qed\n    with le_y have \"norm (f b - f a) \\<le> \\<phi> b - \\<phi> a + e * (b - a + 1)\"\n      by (simp add: algebra_simps)\n  } note * = this\n  show ?thesis\n  proof (rule field_le_epsilon)\n    fix e::real assume \"e > 0\"\n    then show \"norm (f b - f a) \\<le> \\<phi> b - \\<phi> a + e\"\n      using *[of \"e / (b - a + 1)\"] \\<open>a < b\\<close> by simp\n  qed\nqed\n\nlemma differentiable_bound:\n  fixes f :: \"'a::real_normed_vector \\<Rightarrow> 'b::real_normed_vector\"\n  assumes \"convex S\"\n    and derf: \"\\<And>x. x\\<in>S \\<Longrightarrow> (f has_derivative f' x) (at x within S)\"\n    and B: \"\\<And>x. x \\<in> S \\<Longrightarrow> onorm (f' x) \\<le> B\"\n    and x: \"x \\<in> S\"\n    and y: \"y \\<in> S\"\n  shows \"norm (f x - f y) \\<le> B * norm (x - y)\"\nproof -\n  let ?p = \"\\<lambda>u. x + u *\\<^sub>R (y - x)\"\n  let ?\\<phi> = \"\\<lambda>h. h * B * norm (x - y)\"\n  have *: \"x + u *\\<^sub>R (y - x) \\<in> S\" if \"u \\<in> {0..1}\" for u\n  proof -\n    have \"u *\\<^sub>R y = u *\\<^sub>R (y - x) + u *\\<^sub>R x\"\n      by (simp add: scale_right_diff_distrib)\n    then show \"x + u *\\<^sub>R (y - x) \\<in> S\"\n      using that \\<open>convex S\\<close> x y by (simp add: convex_alt)\n        (metis pth_b(2) pth_c(1) scaleR_collapse)\n  qed\n  have \"\\<And>z. z \\<in> (\\<lambda>u. x + u *\\<^sub>R (y - x)) ` {0..1} \\<Longrightarrow>\n          (f has_derivative f' z) (at z within (\\<lambda>u. x + u *\\<^sub>R (y - x)) ` {0..1})\"\n    by (auto intro: * has_derivative_subset [OF derf])\n  then have \"continuous_on (?p ` {0..1}) f\"\n    unfolding continuous_on_eq_continuous_within\n    by (meson has_derivative_continuous)\n  with * have 1: \"continuous_on {0 .. 1} (f \\<circ> ?p)\"\n    by (intro continuous_intros)+\n  {\n    fix u::real assume u: \"u \\<in>{0 <..< 1}\"\n    let ?u = \"?p u\"\n    interpret linear \"(f' ?u)\"\n      using u by (auto intro!: has_derivative_linear derf *)\n    have \"(f \\<circ> ?p has_derivative (f' ?u) \\<circ> (\\<lambda>u. 0 + u *\\<^sub>R (y - x))) (at u within box 0 1)\"\n      by (intro derivative_intros has_derivative_subset [OF derf]) (use u * in auto)\n    hence \"((f \\<circ> ?p) has_vector_derivative f' ?u (y - x)) (at u)\"\n      by (simp add: at_within_open[OF u open_greaterThanLessThan] scaleR has_vector_derivative_def o_def)\n  } note 2 = this\n  have 3: \"continuous_on {0..1} ?\\<phi>\"\n    by (rule continuous_intros)+\n  have 4: \"(?\\<phi> has_vector_derivative B * norm (x - y)) (at u)\" for u\n    by (auto simp: has_vector_derivative_def intro!: derivative_eq_intros)\n  {\n    fix u::real assume u: \"u \\<in>{0 <..< 1}\"\n    let ?u = \"?p u\"\n    interpret bounded_linear \"(f' ?u)\"\n      using u by (auto intro!: has_derivative_bounded_linear derf *)\n    have \"norm (f' ?u (y - x)) \\<le> onorm (f' ?u) * norm (y - x)\"\n      by (rule onorm) (rule bounded_linear)\n    also have \"onorm (f' ?u) \\<le> B\"\n      using u by (auto intro!: assms(3)[rule_format] *)\n    finally have \"norm ((f' ?u) (y - x)) \\<le> B * norm (x - y)\"\n      by (simp add: mult_right_mono norm_minus_commute)\n  } note 5 = this\n  have \"norm (f x - f y) = norm ((f \\<circ> (\\<lambda>u. x + u *\\<^sub>R (y - x))) 1 - (f \\<circ> (\\<lambda>u. x + u *\\<^sub>R (y - x))) 0)\"\n    by (auto simp add: norm_minus_commute)\n  also\n  from differentiable_bound_general[OF zero_less_one 1, OF 3 2 4 5]\n  have \"norm ((f \\<circ> ?p) 1 - (f \\<circ> ?p) 0) \\<le> B * norm (x - y)\"\n    by simp\n  finally show ?thesis .\nqed\n\nlemma field_differentiable_bound:\n  fixes S :: \"'a::real_normed_field 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 (erule df [unfolded has_field_derivative_def])\n  apply (rule onorm_le, simp_all add: norm_mult mult_right_mono assms)\n  done\n\nlemma\n  differentiable_bound_segment:\n  fixes f::\"'a::real_normed_vector \\<Rightarrow> 'b::real_normed_vector\"\n  assumes \"\\<And>t. t \\<in> {0..1} \\<Longrightarrow> x0 + t *\\<^sub>R a \\<in> G\"\n  assumes f': \"\\<And>x. x \\<in> G \\<Longrightarrow> (f has_derivative f' x) (at x within G)\"\n  assumes B: \"\\<And>x. x \\<in> {0..1} \\<Longrightarrow> onorm (f' (x0 + x *\\<^sub>R a)) \\<le> B\"\n  shows \"norm (f (x0 + a) - f x0) \\<le> norm a * B\"\nproof -\n  let ?G = \"(\\<lambda>x. x0 + x *\\<^sub>R a) ` {0..1}\"\n  have \"?G = (+) x0 ` (\\<lambda>x. x *\\<^sub>R a) ` {0..1}\" by auto\n  also have \"convex \\<dots>\"\n    by (intro convex_translation convex_scaled convex_real_interval)\n  finally have \"convex ?G\" .\n  moreover have \"?G \\<subseteq> G\" \"x0 \\<in> ?G\" \"x0 + a \\<in> ?G\" using assms by (auto intro: image_eqI[where x=1])\n  ultimately show ?thesis\n    using has_derivative_subset[OF f' \\<open>?G \\<subseteq> G\\<close>] B\n      differentiable_bound[of \"(\\<lambda>x. x0 + x *\\<^sub>R a) ` {0..1}\" f f' B \"x0 + a\" x0]\n    by (force simp: ac_simps)\nqed\n\nlemma differentiable_bound_linearization:\n  fixes f::\"'a::real_normed_vector \\<Rightarrow> 'b::real_normed_vector\"\n  assumes S: \"\\<And>t. t \\<in> {0..1} \\<Longrightarrow> a + t *\\<^sub>R (b - a) \\<in> S\"\n  assumes f'[derivative_intros]: \"\\<And>x. x \\<in> S \\<Longrightarrow> (f has_derivative f' x) (at x within S)\"\n  assumes B: \"\\<And>x. x \\<in> S \\<Longrightarrow> onorm (f' x - f' x0) \\<le> B\"\n  assumes \"x0 \\<in> S\"\n  shows \"norm (f b - f a - f' x0 (b - a)) \\<le> norm (b - a) * B\"\nproof -\n  define g where [abs_def]: \"g x = f x - f' x0 x\" for x\n  have g: \"\\<And>x. x \\<in> S \\<Longrightarrow> (g has_derivative (\\<lambda>i. f' x i - f' x0 i)) (at x within S)\"\n    unfolding g_def using assms\n    by (auto intro!: derivative_eq_intros\n      bounded_linear.has_derivative[OF has_derivative_bounded_linear, OF f'])\n  from B have \"\\<forall>x\\<in>{0..1}. onorm (\\<lambda>i. f' (a + x *\\<^sub>R (b - a)) i - f' x0 i) \\<le> B\"\n    using assms by (auto simp: fun_diff_def)\n  with differentiable_bound_segment[OF S g] \\<open>x0 \\<in> S\\<close>\n  show ?thesis\n    by (simp add: g_def field_simps linear_diff[OF has_derivative_linear[OF f']])\nqed\n\nlemma vector_differentiable_bound_linearization:\n  fixes f::\"real \\<Rightarrow> 'b::real_normed_vector\"\n  assumes f': \"\\<And>x. x \\<in> S \\<Longrightarrow> (f has_vector_derivative f' x) (at x within S)\"\n  assumes \"closed_segment a b \\<subseteq> S\"\n  assumes B: \"\\<And>x. x \\<in> S \\<Longrightarrow> norm (f' x - f' x0) \\<le> B\"\n  assumes \"x0 \\<in> S\"\n  shows \"norm (f b - f a - (b - a) *\\<^sub>R f' x0) \\<le> norm (b - a) * B\"\n  using assms\n  by (intro differentiable_bound_linearization[of a b S f \"\\<lambda>x h. h *\\<^sub>R f' x\" x0 B])\n    (force simp: closed_segment_real_eq has_vector_derivative_def\n      scaleR_diff_right[symmetric] mult.commute[of B]\n      intro!: onorm_le mult_left_mono)+\n\n\ntext \\<open>In particular.\\<close>\n\nlemma has_derivative_zero_constant:\n  fixes f :: \"'a::real_normed_vector \\<Rightarrow> 'b::real_normed_vector\"\n  assumes \"convex s\"\n    and \"\\<And>x. x \\<in> s \\<Longrightarrow> (f has_derivative (\\<lambda>h. 0)) (at x within s)\"\n  shows \"\\<exists>c. \\<forall>x\\<in>s. f x = c\"\nproof -\n  { fix x y assume \"x \\<in> s\" \"y \\<in> s\"\n    then have \"norm (f x - f y) \\<le> 0 * norm (x - y)\"\n      using assms by (intro differentiable_bound[of s]) (auto simp: onorm_zero)\n    then have \"f x = f y\"\n      by simp }\n  then show ?thesis\n    by metis\nqed\n\nlemma has_field_derivative_zero_constant:\n  assumes \"convex s\" \"\\<And>x. x \\<in> s \\<Longrightarrow> (f has_field_derivative 0) (at x within s)\"\n  shows   \"\\<exists>c. \\<forall>x\\<in>s. f (x) = (c :: 'a :: real_normed_field)\"\nproof (rule has_derivative_zero_constant)\n  have A: \"(*) 0 = (\\<lambda>_. 0 :: 'a)\" by (intro ext) simp\n  fix x assume \"x \\<in> s\" thus \"(f has_derivative (\\<lambda>h. 0)) (at x within s)\"\n    using assms(2)[of x] by (simp add: has_field_derivative_def A)\nqed fact\n\nlemma\n  has_vector_derivative_zero_constant:\n  assumes \"convex s\"\n  assumes \"\\<And>x. x \\<in> s \\<Longrightarrow> (f has_vector_derivative 0) (at x within s)\"\n  obtains c where \"\\<And>x. x \\<in> s \\<Longrightarrow> f x = c\"\n  using has_derivative_zero_constant[of s f] assms\n  by (auto simp: has_vector_derivative_def)\n\nlemma has_derivative_zero_unique:\n  fixes f :: \"'a::real_normed_vector \\<Rightarrow> 'b::real_normed_vector\"\n  assumes \"convex s\"\n    and \"\\<And>x. x \\<in> s \\<Longrightarrow> (f has_derivative (\\<lambda>h. 0)) (at x within s)\"\n    and \"x \\<in> s\" \"y \\<in> s\"\n  shows \"f x = f y\"\n  using has_derivative_zero_constant[OF assms(1,2)] assms(3-) by force\n\nlemma has_derivative_zero_unique_connected:\n  fixes f :: \"'a::real_normed_vector \\<Rightarrow> 'b::real_normed_vector\"\n  assumes \"open s\" \"connected s\"\n  assumes f: \"\\<And>x. x \\<in> s \\<Longrightarrow> (f has_derivative (\\<lambda>x. 0)) (at x)\"\n  assumes \"x \\<in> s\" \"y \\<in> s\"\n  shows \"f x = f y\"\nproof (rule connected_local_const[where f=f, OF \\<open>connected s\\<close> \\<open>x\\<in>s\\<close> \\<open>y\\<in>s\\<close>])\n  show \"\\<forall>a\\<in>s. eventually (\\<lambda>b. f a = f b) (at a within s)\"\n  proof\n    fix a assume \"a \\<in> s\"\n    with \\<open>open s\\<close> obtain e where \"0 < e\" \"ball a e \\<subseteq> s\"\n      by (rule openE)\n    then have \"\\<exists>c. \\<forall>x\\<in>ball a e. f x = c\"\n      by (intro has_derivative_zero_constant)\n         (auto simp: at_within_open[OF _ open_ball] f)\n    with \\<open>0<e\\<close> have \"\\<forall>x\\<in>ball a e. f a = f x\"\n      by auto\n    then show \"eventually (\\<lambda>b. f a = f b) (at a within s)\"\n      using \\<open>0<e\\<close> unfolding eventually_at_topological\n      by (intro exI[of _ \"ball a e\"]) auto\n  qed\nqed\n\nsubsection \\<open>Differentiability of inverse function (most basic form)\\<close>\n\nlemma has_derivative_inverse_basic:\n  fixes f :: \"'a::real_normed_vector \\<Rightarrow> 'b::real_normed_vector\"\n  assumes derf: \"(f has_derivative f') (at (g y))\"\n    and ling': \"bounded_linear g'\"\n    and \"g' \\<circ> f' = id\"\n    and contg: \"continuous (at y) g\"\n    and \"open T\"\n    and \"y \\<in> T\"\n    and fg: \"\\<And>z. z \\<in> T \\<Longrightarrow> f (g z) = z\"\n  shows \"(g has_derivative g') (at y)\"\nproof -\n  interpret f': bounded_linear f'\n    using assms unfolding has_derivative_def by auto\n  interpret g': bounded_linear g'\n    using assms by auto\n  obtain C where C: \"0 < C\" \"\\<And>x. norm (g' x) \\<le> norm x * C\"\n    using bounded_linear.pos_bounded[OF assms(2)] by blast\n  have lem1: \"\\<forall>e>0. \\<exists>d>0. \\<forall>z.\n    norm (z - y) < d \\<longrightarrow> norm (g z - g y - g'(z - y)) \\<le> e * norm (g z - g y)\"\n  proof (intro allI impI)\n    fix e :: real\n    assume \"e > 0\"\n    with C(1) have *: \"e / C > 0\" by auto\n    obtain d0 where  \"0 < d0\" and d0:\n        \"\\<And>u. norm (u - g y) < d0 \\<Longrightarrow> norm (f u - f (g y) - f' (u - g y)) \\<le> e / C * norm (u - g y)\"\n      using derf * unfolding has_derivative_at_alt by blast\n    obtain d1 where \"0 < d1\" and d1: \"\\<And>x. \\<lbrakk>0 < dist x y; dist x y < d1\\<rbrakk> \\<Longrightarrow> dist (g x) (g y) < d0\"\n      using contg \\<open>0 < d0\\<close> unfolding continuous_at Lim_at by blast\n    obtain d2 where \"0 < d2\" and d2: \"\\<And>u. dist u y < d2 \\<Longrightarrow> u \\<in> T\"\n      using \\<open>open T\\<close> \\<open>y \\<in> T\\<close> unfolding open_dist by blast\n    obtain d where d: \"0 < d\" \"d < d1\" \"d < d2\"\n      using field_lbound_gt_zero[OF \\<open>0 < d1\\<close> \\<open>0 < d2\\<close>] by blast\n    show \"\\<exists>d>0. \\<forall>z. norm (z - y) < d \\<longrightarrow> norm (g z - g y - g' (z - y)) \\<le> e * norm (g z - g y)\"\n    proof (intro exI allI impI conjI)\n      fix z\n      assume as: \"norm (z - y) < d\"\n      then have \"z \\<in> T\"\n        using d2 d unfolding dist_norm by auto\n      have \"norm (g z - g y - g' (z - y)) \\<le> norm (g' (f (g z) - y - f' (g z - g y)))\"\n        unfolding g'.diff f'.diff\n        unfolding assms(3)[unfolded o_def id_def, THEN fun_cong] fg[OF \\<open>z\\<in>T\\<close>]\n        by (simp add: norm_minus_commute)\n      also have \"\\<dots> \\<le> norm (f (g z) - y - f' (g z - g y)) * C\"\n        by (rule C(2))\n      also have \"\\<dots> \\<le> (e / C) * norm (g z - g y) * C\"\n      proof -\n        have \"norm (g z - g y) < d0\"\n          by (metis as cancel_comm_monoid_add_class.diff_cancel d(2) \\<open>0 < d0\\<close> d1 diff_gt_0_iff_gt diff_strict_mono dist_norm dist_self zero_less_dist_iff)\n        then show ?thesis\n          by (metis C(1) \\<open>y \\<in> T\\<close> d0 fg mult_le_cancel_iff1)\n      qed\n      also have \"\\<dots> \\<le> e * norm (g z - g y)\"\n        using C by (auto simp add: field_simps)\n      finally show \"norm (g z - g y - g' (z - y)) \\<le> e * norm (g z - g y)\"\n        by simp\n    qed (use d in auto)\n  qed\n  have *: \"(0::real) < 1 / 2\"\n    by auto\n  obtain d where \"0 < d\" and d:\n      \"\\<And>z. norm (z - y) < d \\<Longrightarrow> norm (g z - g y - g' (z - y)) \\<le> 1/2 * norm (g z - g y)\"\n    using lem1 * by blast\n  define B where \"B = C * 2\"\n  have \"B > 0\"\n    unfolding B_def using C by auto\n  have lem2: \"norm (g z - g y) \\<le> B * norm (z - y)\" if z: \"norm(z - y) < d\" for z\n  proof -\n    have \"norm (g z - g y) \\<le> norm(g' (z - y)) + norm ((g z - g y) - g'(z - y))\"\n      by (rule norm_triangle_sub)\n    also have \"\\<dots> \\<le> norm (g' (z - y)) + 1 / 2 * norm (g z - g y)\"\n      by (rule add_left_mono) (use d z in auto)\n    also have \"\\<dots> \\<le> norm (z - y) * C + 1 / 2 * norm (g z - g y)\"\n      by (rule add_right_mono) (use C in auto)\n    finally show \"norm (g z - g y) \\<le> B * norm (z - y)\"\n      unfolding B_def\n      by (auto simp add: field_simps)\n  qed\n  show ?thesis\n    unfolding has_derivative_at_alt\n  proof (intro conjI assms allI impI)\n    fix e :: real\n    assume \"e > 0\"\n    then have *: \"e / B > 0\" by (metis \\<open>B > 0\\<close> divide_pos_pos)\n    obtain d' where \"0 < d'\" and d':\n        \"\\<And>z. norm (z - y) < d' \\<Longrightarrow> norm (g z - g y - g' (z - y)) \\<le> e / B * norm (g z - g y)\"\n      using lem1 * by blast\n    obtain k where k: \"0 < k\" \"k < d\" \"k < d'\"\n      using field_lbound_gt_zero[OF \\<open>0 < d\\<close> \\<open>0 < d'\\<close>] by blast\n    show \"\\<exists>d>0. \\<forall>ya. norm (ya - y) < d \\<longrightarrow> norm (g ya - g y - g' (ya - y)) \\<le> e * norm (ya - y)\"\n    proof (intro exI allI impI conjI)\n      fix z\n      assume as: \"norm (z - y) < k\"\n      then have \"norm (g z - g y - g' (z - y)) \\<le> e / B * norm(g z - g y)\"\n        using d' k by auto\n      also have \"\\<dots> \\<le> e * norm (z - y)\"\n        unfolding times_divide_eq_left pos_divide_le_eq[OF \\<open>B>0\\<close>]\n        using lem2[of z] k as \\<open>e > 0\\<close>\n        by (auto simp add: field_simps)\n      finally show \"norm (g z - g y - g' (z - y)) \\<le> e * norm (z - y)\"\n        by simp\n    qed (use k in auto)\n  qed\nqed\n\ntext\\<^marker>\\<open>tag unimportant\\<close>\\<open>Inverse function theorem for complex derivatives\\<close>\nlemma has_field_derivative_inverse_basic:\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  by (rule has_derivative_inverse_basic) (auto simp: bounded_linear_mult_right)\n\ntext \\<open>Simply rewrite that based on the domain point x.\\<close>\n\nlemma has_derivative_inverse_basic_x:\n  fixes f :: \"'a::real_normed_vector \\<Rightarrow> 'b::real_normed_vector\"\n  assumes \"(f has_derivative f') (at x)\"\n    and \"bounded_linear g'\"\n    and \"g' \\<circ> f' = id\"\n    and \"continuous (at (f x)) g\"\n    and \"g (f x) = x\"\n    and \"open T\"\n    and \"f x \\<in> T\"\n    and \"\\<And>y. y \\<in> T \\<Longrightarrow> f (g y) = y\"\n  shows \"(g has_derivative g') (at (f x))\"\n  by (rule has_derivative_inverse_basic) (use assms in auto)\n\ntext \\<open>This is the version in Dieudonne', assuming continuity of f and g.\\<close>\n\nlemma has_derivative_inverse_dieudonne:\n  fixes f :: \"'a::real_normed_vector \\<Rightarrow> 'b::real_normed_vector\"\n  assumes \"open S\"\n    and fS: \"open (f ` S)\"\n    and A: \"continuous_on S f\" \"continuous_on (f ` S) g\" \n           \"\\<And>x. x \\<in> S \\<Longrightarrow> g (f x) = x\" \"x \\<in> S\"\n    and B: \"(f has_derivative f') (at x)\" \"bounded_linear g'\" \"g' \\<circ> f' = id\"\n  shows \"(g has_derivative g') (at (f x))\"\n  using A fS continuous_on_eq_continuous_at\n  by (intro has_derivative_inverse_basic_x[OF B _ _ fS]) force+\n\ntext \\<open>Here's the simplest way of not assuming much about g.\\<close>\n\nproposition has_derivative_inverse:\n  fixes f :: \"'a::real_normed_vector \\<Rightarrow> 'b::real_normed_vector\"\n  assumes \"compact S\"\n    and \"x \\<in> S\"\n    and fx: \"f x \\<in> interior (f ` S)\"\n    and \"continuous_on S f\"\n    and gf: \"\\<And>y. y \\<in> S \\<Longrightarrow> g (f y) = y\"\n    and B: \"(f has_derivative f') (at x)\" \"bounded_linear g'\" \"g' \\<circ> f' = id\"\n  shows \"(g has_derivative g') (at (f x))\"\nproof -\n  have *: \"\\<And>y. y \\<in> interior (f ` S) \\<Longrightarrow> f (g y) = y\"\n    by (metis gf image_iff interior_subset subsetCE)\n  show ?thesis\n    using assms * continuous_on_interior continuous_on_inv fx \n    by (intro has_derivative_inverse_basic_x[OF B, where T = \"interior (f`S)\"]) blast+\nqed\n\n\ntext \\<open>Invertible derivative continuous at a point implies local\ninjectivity. It's only for this we need continuity of the derivative,\nexcept of course if we want the fact that the inverse derivative is\nalso continuous. So if we know for some other reason that the inverse\nfunction exists, it's OK.\\<close>\n\nproposition has_derivative_locally_injective:\n  fixes f :: \"'n::euclidean_space \\<Rightarrow> 'm::euclidean_space\"\n  assumes \"a \\<in> S\"\n      and \"open S\"\n      and bling: \"bounded_linear g'\"\n      and \"g' \\<circ> f' a = id\"\n      and derf: \"\\<And>x. x \\<in> S \\<Longrightarrow> (f has_derivative f' x) (at x)\"\n      and \"\\<And>e. e > 0 \\<Longrightarrow> \\<exists>d>0. \\<forall>x. dist a x < d \\<longrightarrow> onorm (\\<lambda>v. f' x v - f' a v) < e\"\n  obtains r where \"r > 0\" \"ball a r \\<subseteq> S\" \"inj_on f (ball a r)\"\nproof -\n  interpret bounded_linear g'\n    using assms by auto\n  note f'g' = assms(4)[unfolded id_def o_def,THEN cong]\n  have \"g' (f' a (\\<Sum>Basis)) = (\\<Sum>Basis)\" \"(\\<Sum>Basis) \\<noteq> (0::'n)\"\n    using f'g' by auto\n  then have *: \"0 < onorm g'\"\n    unfolding onorm_pos_lt[OF assms(3)]\n    by fastforce\n  define k where \"k = 1 / onorm g' / 2\"\n  have *: \"k > 0\"\n    unfolding k_def using * by auto\n  obtain d1 where d1:\n      \"0 < d1\"\n      \"\\<And>x. dist a x < d1 \\<Longrightarrow> onorm (\\<lambda>v. f' x v - f' a v) < k\"\n    using assms(6) * by blast\n  from \\<open>open S\\<close> obtain d2 where \"d2 > 0\" \"ball a d2 \\<subseteq> S\"\n    using \\<open>a\\<in>S\\<close> ..\n  obtain d2 where d2: \"0 < d2\" \"ball a d2 \\<subseteq> S\"\n    using \\<open>0 < d2\\<close> \\<open>ball a d2 \\<subseteq> S\\<close> by blast\n  obtain d where d: \"0 < d\" \"d < d1\" \"d < d2\"\n    using field_lbound_gt_zero[OF d1(1) d2(1)] by blast\n  show ?thesis\n  proof\n    show \"0 < d\" by (fact d)\n    show \"ball a d \\<subseteq> S\"\n      using \\<open>d < d2\\<close> \\<open>ball a d2 \\<subseteq> S\\<close> by auto\n    show \"inj_on f (ball a d)\"\n    unfolding inj_on_def\n    proof (intro strip)\n      fix x y\n      assume as: \"x \\<in> ball a d\" \"y \\<in> ball a d\" \"f x = f y\"\n      define ph where [abs_def]: \"ph w = w - g' (f w - f x)\" for w\n      have ph':\"ph = g' \\<circ> (\\<lambda>w. f' a w - (f w - f x))\"\n        unfolding ph_def o_def  by (simp add: diff f'g')\n      have \"norm (ph x - ph y) \\<le> (1 / 2) * norm (x - y)\"\n      proof (rule differentiable_bound[OF convex_ball _ _ as(1-2)])\n        fix u\n        assume u: \"u \\<in> ball a d\"\n        then have \"u \\<in> S\"\n          using d d2 by auto\n        have *: \"(\\<lambda>v. v - g' (f' u v)) = g' \\<circ> (\\<lambda>w. f' a w - f' u w)\"\n          unfolding o_def and diff\n          using f'g' by auto\n        have blin: \"bounded_linear (f' a)\"\n          using \\<open>a \\<in> S\\<close> derf by blast\n        show \"(ph has_derivative (\\<lambda>v. v - g' (f' u v))) (at u within ball a d)\"\n          unfolding ph' * comp_def\n          by (rule \\<open>u \\<in> S\\<close> derivative_eq_intros has_derivative_at_withinI [OF derf] bounded_linear.has_derivative [OF blin]  bounded_linear.has_derivative [OF bling] |simp)+\n        have **: \"bounded_linear (\\<lambda>x. f' u x - f' a x)\" \"bounded_linear (\\<lambda>x. f' a x - f' u x)\"\n          using \\<open>u \\<in> S\\<close> blin bounded_linear_sub derf by auto\n        then have \"onorm (\\<lambda>v. v - g' (f' u v)) \\<le> onorm g' * onorm (\\<lambda>w. f' a w - f' u w)\"\n          by (simp add: \"*\" bounded_linear_axioms onorm_compose)\n        also have \"\\<dots> \\<le> onorm g' * k\"\n          apply (rule mult_left_mono)\n          using d1(2)[of u]\n          using onorm_neg[where f=\"\\<lambda>x. f' u x - f' a x\"] d u onorm_pos_le[OF bling] \n           apply (auto simp: algebra_simps)\n          done\n        also have \"\\<dots> \\<le> 1 / 2\"\n          unfolding k_def by auto\n        finally show \"onorm (\\<lambda>v. v - g' (f' u v)) \\<le> 1 / 2\" .\n      qed\n      moreover have \"norm (ph y - ph x) = norm (y - x)\"\n        by (simp add: as(3) ph_def)\n      ultimately show \"x = y\"\n        unfolding norm_minus_commute by auto\n    qed\n  qed\nqed\n\n\nsubsection \\<open>Uniformly convergent sequence of derivatives\\<close>\n\nlemma has_derivative_sequence_lipschitz_lemma:\n  fixes f :: \"nat \\<Rightarrow> 'a::real_normed_vector \\<Rightarrow> 'b::real_normed_vector\"\n  assumes \"convex S\"\n    and derf: \"\\<And>n x. x \\<in> S \\<Longrightarrow> ((f n) has_derivative (f' n x)) (at x within S)\"\n    and nle: \"\\<And>n x h. \\<lbrakk>n\\<ge>N; x \\<in> S\\<rbrakk> \\<Longrightarrow> norm (f' n x h - g' x h) \\<le> e * norm h\"\n    and \"0 \\<le> e\"\n  shows \"\\<forall>m\\<ge>N. \\<forall>n\\<ge>N. \\<forall>x\\<in>S. \\<forall>y\\<in>S. norm ((f m x - f n x) - (f m y - f n y)) \\<le> 2 * e * norm (x - y)\"\nproof clarify\n  fix m n x y\n  assume as: \"N \\<le> m\" \"N \\<le> n\" \"x \\<in> S\" \"y \\<in> S\"\n  show \"norm ((f m x - f n x) - (f m y - f n y)) \\<le> 2 * e * norm (x - y)\"\n  proof (rule differentiable_bound[where f'=\"\\<lambda>x h. f' m x h - f' n x h\", OF \\<open>convex S\\<close> _ _ as(3-4)])\n    fix x\n    assume \"x \\<in> S\"\n    show \"((\\<lambda>a. f m a - f n a) has_derivative (\\<lambda>h. f' m x h - f' n x h)) (at x within S)\"\n      by (rule derivative_intros derf \\<open>x\\<in>S\\<close>)+\n    show \"onorm (\\<lambda>h. f' m x h - f' n x h) \\<le> 2 * e\"\n    proof (rule onorm_bound)\n      fix h\n      have \"norm (f' m x h - f' n x h) \\<le> norm (f' m x h - g' x h) + norm (f' n x h - g' x h)\"\n        using norm_triangle_ineq[of \"f' m x h - g' x h\" \"- f' n x h + g' x h\"]\n        by (auto simp add: algebra_simps norm_minus_commute)\n      also have \"\\<dots> \\<le> e * norm h + e * norm h\"\n        using nle[OF \\<open>N \\<le> m\\<close> \\<open>x \\<in> S\\<close>, of h] nle[OF \\<open>N \\<le> n\\<close> \\<open>x \\<in> S\\<close>, of h]\n        by (auto simp add: field_simps)\n      finally show \"norm (f' m x h - f' n x h) \\<le> 2 * e * norm h\"\n        by auto\n    qed (simp add: \\<open>0 \\<le> e\\<close>)\n  qed\nqed\n\nlemma has_derivative_sequence_Lipschitz:\n  fixes f :: \"nat \\<Rightarrow> 'a::real_normed_vector \\<Rightarrow> 'b::real_normed_vector\"\n  assumes \"convex S\"\n    and \"\\<And>n x. x \\<in> S \\<Longrightarrow> ((f n) has_derivative (f' n x)) (at x within S)\"\n    and nle: \"\\<And>e. e > 0 \\<Longrightarrow> \\<forall>\\<^sub>F n in sequentially. \\<forall>x\\<in>S. \\<forall>h. norm (f' n x h - g' x h) \\<le> e * norm h\"\n    and \"e > 0\"\n  shows \"\\<exists>N. \\<forall>m\\<ge>N. \\<forall>n\\<ge>N. \\<forall>x\\<in>S. \\<forall>y\\<in>S.\n    norm ((f m x - f n x) - (f m y - f n y)) \\<le> e * norm (x - y)\"\nproof -\n  have *: \"2 * (e/2) = e\"\n    using \\<open>e > 0\\<close> by auto\n  obtain N where \"\\<forall>n\\<ge>N. \\<forall>x\\<in>S. \\<forall>h. norm (f' n x h - g' x h) \\<le> (e/2) * norm h\"\n    using nle \\<open>e > 0\\<close>\n    unfolding eventually_sequentially\n    by (metis less_divide_eq_numeral1(1) mult_zero_left)\n  then show \"\\<exists>N. \\<forall>m\\<ge>N. \\<forall>n\\<ge>N. \\<forall>x\\<in>S. \\<forall>y\\<in>S. norm (f m x - f n x - (f m y - f n y)) \\<le> e * norm (x - y)\"\n    apply (rule_tac x=N in exI)\n    apply (rule has_derivative_sequence_lipschitz_lemma[where e=\"e/2\", unfolded *])\n    using assms \\<open>e > 0\\<close>\n    apply auto\n    done\nqed\n\nproposition has_derivative_sequence:\n  fixes f :: \"nat \\<Rightarrow> 'a::real_normed_vector \\<Rightarrow> 'b::banach\"\n  assumes \"convex S\"\n    and derf: \"\\<And>n x. x \\<in> S \\<Longrightarrow> ((f n) has_derivative (f' n x)) (at x within S)\"\n    and nle: \"\\<And>e. e > 0 \\<Longrightarrow> \\<forall>\\<^sub>F n in sequentially. \\<forall>x\\<in>S. \\<forall>h. norm (f' n x h - g' x h) \\<le> e * norm h\"\n    and \"x0 \\<in> S\"\n    and lim: \"((\\<lambda>n. f n x0) \\<longlongrightarrow> l) sequentially\"\n  shows \"\\<exists>g. \\<forall>x\\<in>S. (\\<lambda>n. f n x) \\<longlonglongrightarrow> g x \\<and> (g has_derivative g'(x)) (at x within S)\"\nproof -\n  have lem1: \"\\<And>e. e > 0 \\<Longrightarrow> \\<exists>N. \\<forall>m\\<ge>N. \\<forall>n\\<ge>N. \\<forall>x\\<in>S. \\<forall>y\\<in>S.\n      norm ((f m x - f n x) - (f m y - f n y)) \\<le> e * norm (x - y)\"\n    using assms(1,2,3) by (rule has_derivative_sequence_Lipschitz)\n  have \"\\<exists>g. \\<forall>x\\<in>S. ((\\<lambda>n. f n x) \\<longlongrightarrow> g x) sequentially\"\n  proof (intro ballI bchoice)\n    fix x\n    assume \"x \\<in> S\"\n    show \"\\<exists>y. (\\<lambda>n. f n x) \\<longlonglongrightarrow> y\"\n    unfolding convergent_eq_Cauchy\n    proof (cases \"x = x0\")\n      case True\n      then show \"Cauchy (\\<lambda>n. f n x)\"\n        using LIMSEQ_imp_Cauchy[OF lim] by auto\n    next\n      case False\n      show \"Cauchy (\\<lambda>n. f n x)\"\n        unfolding Cauchy_def\n      proof (intro allI impI)\n        fix e :: real\n        assume \"e > 0\"\n        hence *: \"e / 2 > 0\" \"e / 2 / norm (x - x0) > 0\" using False by auto\n        obtain M where M: \"\\<forall>m\\<ge>M. \\<forall>n\\<ge>M. dist (f m x0) (f n x0) < e / 2\"\n          using LIMSEQ_imp_Cauchy[OF lim] * unfolding Cauchy_def by blast\n        obtain N where N:\n          \"\\<forall>m\\<ge>N. \\<forall>n\\<ge>N.\n            \\<forall>u\\<in>S. \\<forall>y\\<in>S. norm (f m u - f n u - (f m y - f n y)) \\<le>\n              e / 2 / norm (x - x0) * norm (u - y)\"\n        using lem1 *(2) by blast\n        show \"\\<exists>M. \\<forall>m\\<ge>M. \\<forall>n\\<ge>M. dist (f m x) (f n x) < e\"\n        proof (intro exI allI impI)\n          fix m n\n          assume as: \"max M N \\<le>m\" \"max M N\\<le>n\"\n          have \"dist (f m x) (f n x) \\<le> norm (f m x0 - f n x0) + norm (f m x - f n x - (f m x0 - f n x0))\"\n            unfolding dist_norm\n            by (rule norm_triangle_sub)\n          also have \"\\<dots> \\<le> norm (f m x0 - f n x0) + e / 2\"\n            using N \\<open>x\\<in>S\\<close> \\<open>x0\\<in>S\\<close> as False by fastforce\n          also have \"\\<dots> < e / 2 + e / 2\"\n            by (rule add_strict_right_mono) (use as M in \\<open>auto simp: dist_norm\\<close>)\n          finally show \"dist (f m x) (f n x) < e\"\n            by auto\n        qed\n      qed\n    qed\n  qed\n  then obtain g where g: \"\\<forall>x\\<in>S. (\\<lambda>n. f n x) \\<longlonglongrightarrow> g x\" ..\n  have lem2: \"\\<exists>N. \\<forall>n\\<ge>N. \\<forall>x\\<in>S. \\<forall>y\\<in>S. norm ((f n x - f n y) - (g x - g y)) \\<le> e * norm (x - y)\" if \"e > 0\" for e\n  proof -\n    obtain N where\n      N: \"\\<forall>m\\<ge>N. \\<forall>n\\<ge>N. \\<forall>x\\<in>S. \\<forall>y\\<in>S. norm (f m x - f n x - (f m y - f n y)) \\<le> e * norm (x - y)\"\n      using lem1 \\<open>e > 0\\<close> by blast\n    show \"\\<exists>N. \\<forall>n\\<ge>N. \\<forall>x\\<in>S. \\<forall>y\\<in>S. norm (f n x - f n y - (g x - g y)) \\<le> e * norm (x - y)\"\n    proof (intro exI ballI allI impI)\n      fix n x y\n      assume as: \"N \\<le> n\" \"x \\<in> S\" \"y \\<in> S\"\n      have \"((\\<lambda>m. norm (f n x - f n y - (f m x - f m y))) \\<longlongrightarrow> norm (f n x - f n y - (g x - g y))) sequentially\"\n        by (intro tendsto_intros g[rule_format] as)\n      moreover have \"eventually (\\<lambda>m. norm (f n x - f n y - (f m x - f m y)) \\<le> e * norm (x - y)) sequentially\"\n        unfolding eventually_sequentially\n      proof (intro exI allI impI)\n        fix m\n        assume \"N \\<le> m\"\n        then show \"norm (f n x - f n y - (f m x - f m y)) \\<le> e * norm (x - y)\"\n          using N as by (auto simp add: algebra_simps)\n      qed\n      ultimately show \"norm (f n x - f n y - (g x - g y)) \\<le> e * norm (x - y)\"\n        by (simp add: tendsto_upperbound)\n    qed\n  qed\n  have \"\\<forall>x\\<in>S. ((\\<lambda>n. f n x) \\<longlongrightarrow> g x) sequentially \\<and> (g has_derivative g' x) (at x within S)\"\n    unfolding has_derivative_within_alt2\n  proof (intro ballI conjI allI impI)\n    fix x\n    assume \"x \\<in> S\"\n    then show \"(\\<lambda>n. f n x) \\<longlonglongrightarrow> g x\"\n      by (simp add: g)\n    have tog': \"(\\<lambda>n. f' n x u) \\<longlonglongrightarrow> g' x u\" for u\n      unfolding filterlim_def le_nhds_metric_le eventually_filtermap dist_norm\n    proof (intro allI impI)\n      fix e :: real\n      assume \"e > 0\"\n      show \"eventually (\\<lambda>n. norm (f' n x u - g' x u) \\<le> e) sequentially\"\n      proof (cases \"u = 0\")\n        case True\n        have \"eventually (\\<lambda>n. norm (f' n x u - g' x u) \\<le> e * norm u) sequentially\"\n          using nle \\<open>0 < e\\<close> \\<open>x \\<in> S\\<close> by (fast elim: eventually_mono)\n        then show ?thesis\n          using \\<open>u = 0\\<close> \\<open>0 < e\\<close> by (auto elim: eventually_mono)\n      next\n        case False\n        with \\<open>0 < e\\<close> have \"0 < e / norm u\" by simp\n        then have \"eventually (\\<lambda>n. norm (f' n x u - g' x u) \\<le> e / norm u * norm u) sequentially\"\n          using nle \\<open>x \\<in> S\\<close> by (fast elim: eventually_mono)\n        then show ?thesis\n          using \\<open>u \\<noteq> 0\\<close> by simp\n      qed\n    qed\n    show \"bounded_linear (g' x)\"\n    proof\n      fix x' y z :: 'a\n      fix c :: real\n      note lin = assms(2)[rule_format,OF \\<open>x\\<in>S\\<close>,THEN has_derivative_bounded_linear]\n      have \"(\\<lambda>n. f' n x (c *\\<^sub>R x')) \\<longlonglongrightarrow> c *\\<^sub>R g' x x'\"\n        unfolding lin[THEN bounded_linear.linear, THEN linear_cmul]\n        by (intro tendsto_intros tog')\n      then show \"g' x (c *\\<^sub>R x') = c *\\<^sub>R g' x x'\"\n        using LIMSEQ_unique tog' by blast\n      have \"(\\<lambda>n. f' n x (y + z)) \\<longlonglongrightarrow> g' x y + g' x z\"\n        unfolding lin[THEN bounded_linear.linear, THEN linear_add]\n        by (simp add: tendsto_add tog')\n      then show \"g' x (y + z) = g' x y + g' x z\"\n        using LIMSEQ_unique tog' by blast\n      obtain N where N: \"\\<forall>h. norm (f' N x h - g' x h) \\<le> 1 * norm h\"\n        using nle \\<open>x \\<in> S\\<close> unfolding eventually_sequentially by (fast intro: zero_less_one)\n      have \"bounded_linear (f' N x)\"\n        using derf \\<open>x \\<in> S\\<close> by fast\n      from bounded_linear.bounded [OF this]\n      obtain K where K: \"\\<forall>h. norm (f' N x h) \\<le> norm h * K\" ..\n      {\n        fix h\n        have \"norm (g' x h) = norm (f' N x h - (f' N x h - g' x h))\"\n          by simp\n        also have \"\\<dots> \\<le> norm (f' N x h) + norm (f' N x h - g' x h)\"\n          by (rule norm_triangle_ineq4)\n        also have \"\\<dots> \\<le> norm h * K + 1 * norm h\"\n          using N K by (fast intro: add_mono)\n        finally have \"norm (g' x h) \\<le> norm h * (K + 1)\"\n          by (simp add: ring_distribs)\n      }\n      then show \"\\<exists>K. \\<forall>h. norm (g' x h) \\<le> norm h * K\" by fast\n    qed\n    show \"eventually (\\<lambda>y. norm (g y - g x - g' x (y - x)) \\<le> e * norm (y - x)) (at x within S)\"\n      if \"e > 0\" for e\n    proof -\n      have *: \"e / 3 > 0\"\n        using that by auto\n      obtain N1 where N1: \"\\<forall>n\\<ge>N1. \\<forall>x\\<in>S. \\<forall>h. norm (f' n x h - g' x h) \\<le> e / 3 * norm h\"\n        using nle * unfolding eventually_sequentially by blast\n      obtain N2 where\n          N2[rule_format]: \"\\<forall>n\\<ge>N2. \\<forall>x\\<in>S. \\<forall>y\\<in>S. norm (f n x - f n y - (g x - g y)) \\<le> e / 3 * norm (x - y)\"\n        using lem2 * by blast\n      let ?N = \"max N1 N2\"\n      have \"eventually (\\<lambda>y. norm (f ?N y - f ?N x - f' ?N x (y - x)) \\<le> e / 3 * norm (y - x)) (at x within S)\"\n        using derf[unfolded has_derivative_within_alt2] and \\<open>x \\<in> S\\<close> and * by fast\n      moreover have \"eventually (\\<lambda>y. y \\<in> S) (at x within S)\"\n        unfolding eventually_at by (fast intro: zero_less_one)\n      ultimately show \"\\<forall>\\<^sub>F y in at x within S. norm (g y - g x - g' x (y - x)) \\<le> e * norm (y - x)\"\n      proof (rule eventually_elim2)\n        fix y\n        assume \"y \\<in> S\"\n        assume \"norm (f ?N y - f ?N x - f' ?N x (y - x)) \\<le> e / 3 * norm (y - x)\"\n        moreover have \"norm (g y - g x - (f ?N y - f ?N x)) \\<le> e / 3 * norm (y - x)\"\n          using N2[OF _ \\<open>y \\<in> S\\<close> \\<open>x \\<in> S\\<close>]\n          by (simp add: norm_minus_commute)\n        ultimately have \"norm (g y - g x - f' ?N x (y - x)) \\<le> 2 * e / 3 * norm (y - x)\"\n          using norm_triangle_le[of \"g y - g x - (f ?N y - f ?N x)\" \"f ?N y - f ?N x - f' ?N x (y - x)\" \"2 * e / 3 * norm (y - x)\"]\n          by (auto simp add: algebra_simps)\n        moreover\n        have \" norm (f' ?N x (y - x) - g' x (y - x)) \\<le> e / 3 * norm (y - x)\"\n          using N1 \\<open>x \\<in> S\\<close> by auto\n        ultimately show \"norm (g y - g x - g' x (y - x)) \\<le> e * norm (y - x)\"\n          using norm_triangle_le[of \"g y - g x - f' (max N1 N2) x (y - x)\" \"f' (max N1 N2) x (y - x) - g' x (y - x)\"]\n          by (auto simp add: algebra_simps)\n      qed\n    qed\n  qed\n  then show ?thesis by fast\nqed\n\ntext \\<open>Can choose to line up antiderivatives if we want.\\<close>\n\nlemma has_antiderivative_sequence:\n  fixes f :: \"nat \\<Rightarrow> 'a::real_normed_vector \\<Rightarrow> 'b::banach\"\n  assumes \"convex S\"\n    and der: \"\\<And>n x. x \\<in> S \\<Longrightarrow> ((f n) has_derivative (f' n x)) (at x within S)\"\n    and no: \"\\<And>e. e > 0 \\<Longrightarrow> \\<forall>\\<^sub>F n in sequentially.\n       \\<forall>x\\<in>S. \\<forall>h. norm (f' n x h - g' x h) \\<le> e * norm h\"\n  shows \"\\<exists>g. \\<forall>x\\<in>S. (g has_derivative g' x) (at x within S)\"\nproof (cases \"S = {}\")\n  case False\n  then obtain a where \"a \\<in> S\"\n    by auto\n  have *: \"\\<And>P Q. \\<exists>g. \\<forall>x\\<in>S. P g x \\<and> Q g x \\<Longrightarrow> \\<exists>g. \\<forall>x\\<in>S. Q g x\"\n    by auto\n  show ?thesis\n    apply (rule *)\n    apply (rule has_derivative_sequence [OF \\<open>convex S\\<close> _ no, of \"\\<lambda>n x. f n x + (f 0 a - f n a)\"])\n       apply (metis assms(2) has_derivative_add_const)\n    using \\<open>a \\<in> S\\<close> \n      apply auto\n    done\nqed auto\n\nlemma has_antiderivative_limit:\n  fixes g' :: \"'a::real_normed_vector \\<Rightarrow> 'a \\<Rightarrow> 'b::banach\"\n  assumes \"convex S\"\n    and \"\\<And>e. e>0 \\<Longrightarrow> \\<exists>f f'. \\<forall>x\\<in>S.\n           (f has_derivative (f' x)) (at x within S) \\<and> (\\<forall>h. norm (f' x h - g' x h) \\<le> e * norm h)\"\n  shows \"\\<exists>g. \\<forall>x\\<in>S. (g has_derivative g' x) (at x within S)\"\nproof -\n  have *: \"\\<forall>n. \\<exists>f f'. \\<forall>x\\<in>S.\n    (f has_derivative (f' x)) (at x within S) \\<and>\n    (\\<forall>h. norm(f' x h - g' x h) \\<le> inverse (real (Suc n)) * norm h)\"\n    by (simp add: assms(2))\n  obtain f where\n    *: \"\\<And>x. \\<exists>f'. \\<forall>xa\\<in>S. (f x has_derivative f' xa) (at xa within S) \\<and>\n        (\\<forall>h. norm (f' xa h - g' xa h) \\<le> inverse (real (Suc x)) * norm h)\"\n    using * by metis\n  obtain f' where\n    f': \"\\<And>x. \\<forall>z\\<in>S. (f x has_derivative f' x z) (at z within S) \\<and>\n            (\\<forall>h. norm (f' x z h - g' z h) \\<le> inverse (real (Suc x)) * norm h)\"\n    using * by metis\n  show ?thesis\n  proof (rule has_antiderivative_sequence[OF \\<open>convex S\\<close>, of f f'])\n    fix e :: real\n    assume \"e > 0\"\n    obtain N where N: \"inverse (real (Suc N)) < e\"\n      using reals_Archimedean[OF \\<open>e>0\\<close>] ..\n    show \"\\<forall>\\<^sub>F n in sequentially. \\<forall>x\\<in>S.  \\<forall>h. norm (f' n x h - g' x h) \\<le> e * norm h\"\n        unfolding eventually_sequentially\n    proof (intro exI allI ballI impI)\n      fix n x h\n      assume n: \"N \\<le> n\" and x: \"x \\<in> S\"\n      have *: \"inverse (real (Suc n)) \\<le> e\"\n        using n N\n        by (smt (verit, best) le_imp_inverse_le of_nat_0_less_iff of_nat_Suc of_nat_le_iff zero_less_Suc)\n      show \"norm (f' n x h - g' x h) \\<le> e * norm h\"\n        by (meson \"*\" mult_right_mono norm_ge_zero order.trans x f')\n    qed\n  qed (use f' in auto)\nqed\n\n\nsubsection \\<open>Differentiation of a series\\<close>\n\nproposition has_derivative_series:\n  fixes f :: \"nat \\<Rightarrow> 'a::real_normed_vector \\<Rightarrow> 'b::banach\"\n  assumes \"convex S\"\n    and \"\\<And>n x. x \\<in> S \\<Longrightarrow> ((f n) has_derivative (f' n x)) (at x within S)\"\n    and \"\\<And>e. e>0 \\<Longrightarrow> \\<forall>\\<^sub>F n in sequentially. \\<forall>x\\<in>S. \\<forall>h. norm (sum (\\<lambda>i. f' i x h) {..<n} - g' x h) \\<le> e * norm h\"\n    and \"x \\<in> S\"\n    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_derivative g' x) (at x within S)\"\n  unfolding sums_def\n  apply (rule has_derivative_sequence[OF assms(1) _ assms(3)])\n  apply (metis assms(2) has_derivative_sum)\n  using assms(4-5)\n  unfolding sums_def\n  apply auto\n  done\n\nlemma has_field_derivative_series:\n  fixes f :: \"nat \\<Rightarrow> ('a :: {real_normed_field,banach}) \\<Rightarrow> 'a\"\n  assumes \"convex S\"\n  assumes \"\\<And>n x. x \\<in> S \\<Longrightarrow> (f n has_field_derivative f' n x) (at x within S)\"\n  assumes \"uniform_limit S (\\<lambda>n x. \\<Sum>i<n. f' i x) g' sequentially\"\n  assumes \"x0 \\<in> S\" \"summable (\\<lambda>n. f n x0)\"\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)\"\nunfolding has_field_derivative_def\nproof (rule has_derivative_series)\n  show \"\\<forall>\\<^sub>F n in sequentially.\n       \\<forall>x\\<in>S. \\<forall>h. norm ((\\<Sum>i<n. f' i x * h) - g' x * h) \\<le> e * norm h\" if \"e > 0\" for e\n    unfolding eventually_sequentially\n  proof -\n    from that assms(3) obtain N where N: \"\\<And>n x. n \\<ge> N \\<Longrightarrow> x \\<in> S \\<Longrightarrow> norm ((\\<Sum>i<n. f' i x) - g' x) < e\"\n      unfolding uniform_limit_iff eventually_at_top_linorder dist_norm by blast\n    {\n      fix n :: nat and x h :: 'a assume nx: \"n \\<ge> N\" \"x \\<in> S\"\n      have \"norm ((\\<Sum>i<n. f' i x * h) - g' x * h) = norm ((\\<Sum>i<n. f' i x) - g' x) * norm h\"\n        by (simp add: norm_mult [symmetric] ring_distribs sum_distrib_right)\n      also from N[OF nx] have \"norm ((\\<Sum>i<n. f' i x) - g' x) \\<le> e\" by simp\n      hence \"norm ((\\<Sum>i<n. f' i x) - g' x) * norm h \\<le> e * norm h\"\n        by (intro mult_right_mono) simp_all\n      finally have \"norm ((\\<Sum>i<n. f' i x * h) - g' x * h) \\<le> e * norm h\" .\n    }\n    thus \"\\<exists>N. \\<forall>n\\<ge>N. \\<forall>x\\<in>S. \\<forall>h. norm ((\\<Sum>i<n. f' i x * h) - g' x * h) \\<le> e * norm h\" by blast\n  qed\nqed (use assms in \\<open>auto simp: has_field_derivative_def\\<close>)\n\nlemma has_field_derivative_series':\n  fixes f :: \"nat \\<Rightarrow> ('a :: {real_normed_field,banach}) \\<Rightarrow> 'a\"\n  assumes \"convex S\"\n  assumes \"\\<And>n x. x \\<in> S \\<Longrightarrow> (f n has_field_derivative f' n x) (at x within S)\"\n  assumes \"uniformly_convergent_on S (\\<lambda>n x. \\<Sum>i<n. f' i x)\"\n  assumes \"x0 \\<in> S\" \"summable (\\<lambda>n. f n x0)\" \"x \\<in> interior S\"\n  shows   \"summable (\\<lambda>n. f n x)\" \"((\\<lambda>x. \\<Sum>n. f n x) has_field_derivative (\\<Sum>n. f' n x)) (at x)\"\nproof -\n  from \\<open>x \\<in> interior S\\<close> have \"x \\<in> S\" using interior_subset by blast\n  define g' where [abs_def]: \"g' x = (\\<Sum>i. f' i x)\" for x\n  from assms(3) have \"uniform_limit S (\\<lambda>n x. \\<Sum>i<n. f' i x) g' sequentially\"\n    by (simp add: uniformly_convergent_uniform_limit_iff suminf_eq_lim g'_def)\n  from has_field_derivative_series[OF assms(1,2) this assms(4,5)] obtain g where g:\n    \"\\<And>x. x \\<in> S \\<Longrightarrow> (\\<lambda>n. f n x) sums g x\"\n    \"\\<And>x. x \\<in> S \\<Longrightarrow> (g has_field_derivative g' x) (at x within S)\" by blast\n  from g(1)[OF \\<open>x \\<in> S\\<close>] show \"summable (\\<lambda>n. f n x)\" by (simp add: sums_iff)\n  from g(2)[OF \\<open>x \\<in> S\\<close>] \\<open>x \\<in> interior S\\<close> have \"(g has_field_derivative g' x) (at x)\"\n    by (simp add: at_within_interior[of x S])\n  also have \"(g has_field_derivative g' x) (at x) \\<longleftrightarrow>\n                ((\\<lambda>x. \\<Sum>n. f n x) has_field_derivative g' x) (at x)\"\n    using eventually_nhds_in_nhd[OF \\<open>x \\<in> interior S\\<close>] interior_subset[of S] g(1)\n    by (intro DERIV_cong_ev) (auto elim!: eventually_mono simp: sums_iff)\n  finally show \"((\\<lambda>x. \\<Sum>n. f n x) has_field_derivative g' x) (at x)\" .\nqed\n\nlemma differentiable_series:\n  fixes f :: \"nat \\<Rightarrow> ('a :: {real_normed_field,banach}) \\<Rightarrow> 'a\"\n  assumes \"convex S\" \"open S\"\n  assumes \"\\<And>n x. x \\<in> S \\<Longrightarrow> (f n has_field_derivative f' n x) (at x)\"\n  assumes \"uniformly_convergent_on S (\\<lambda>n x. \\<Sum>i<n. f' i x)\"\n  assumes \"x0 \\<in> S\" \"summable (\\<lambda>n. f n x0)\" and x: \"x \\<in> S\"\n  shows   \"summable (\\<lambda>n. f n x)\" and \"(\\<lambda>x. \\<Sum>n. f n x) differentiable (at x)\"\nproof -\n  from assms(4) obtain g' where A: \"uniform_limit S (\\<lambda>n x. \\<Sum>i<n. f' i x) g' sequentially\"\n    unfolding uniformly_convergent_on_def by blast\n  from x and \\<open>open S\\<close> have S: \"at x within S = at x\" by (rule at_within_open)\n  have \"\\<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)\"\n    by (intro has_field_derivative_series[of S f f' g' x0] assms A has_field_derivative_at_within)\n  then obtain g where g: \"\\<And>x. x \\<in> S \\<Longrightarrow> (\\<lambda>n. f n x) sums g x\"\n    \"\\<And>x. x \\<in> S \\<Longrightarrow> (g has_field_derivative g' x) (at x within S)\" by blast\n  from g[OF x] show \"summable (\\<lambda>n. f n x)\" by (auto simp: summable_def)\n  from g(2)[OF x] have g': \"(g has_derivative (*) (g' x)) (at x)\"\n    by (simp add: has_field_derivative_def S)\n  have \"((\\<lambda>x. \\<Sum>n. f n x) has_derivative (*) (g' x)) (at x)\"\n    by (rule has_derivative_transform_within_open[OF g' \\<open>open S\\<close> x])\n       (insert g, auto simp: sums_iff)\n  thus \"(\\<lambda>x. \\<Sum>n. f n x) differentiable (at x)\" unfolding differentiable_def\n    by (auto simp: summable_def differentiable_def has_field_derivative_def)\nqed\n\nlemma differentiable_series':\n  fixes f :: \"nat \\<Rightarrow> ('a :: {real_normed_field,banach}) \\<Rightarrow> 'a\"\n  assumes \"convex S\" \"open S\"\n  assumes \"\\<And>n x. x \\<in> S \\<Longrightarrow> (f n has_field_derivative f' n x) (at x)\"\n  assumes \"uniformly_convergent_on S (\\<lambda>n x. \\<Sum>i<n. f' i x)\"\n  assumes \"x0 \\<in> S\" \"summable (\\<lambda>n. f n x0)\"\n  shows   \"(\\<lambda>x. \\<Sum>n. f n x) differentiable (at x0)\"\n  using differentiable_series[OF assms, of x0] \\<open>x0 \\<in> S\\<close> by blast+\n\nsubsection \\<open>Derivative as a vector\\<close>\n\ntext \\<open>Considering derivative \\<^typ>\\<open>real \\<Rightarrow> 'b::real_normed_vector\\<close> as a vector.\\<close>\n\ndefinition \"vector_derivative f net = (SOME f'. (f has_vector_derivative f') net)\"\n\nlemma vector_derivative_unique_within:\n  assumes not_bot: \"at x within S \\<noteq> bot\"\n    and f': \"(f has_vector_derivative f') (at x within S)\"\n    and f'': \"(f has_vector_derivative f'') (at x within S)\"\n  shows \"f' = f''\"\nproof -\n  have \"(\\<lambda>x. x *\\<^sub>R f') = (\\<lambda>x. x *\\<^sub>R f'')\"\n  proof (rule frechet_derivative_unique_within, simp_all)\n    show \"\\<exists>d. d \\<noteq> 0 \\<and> \\<bar>d\\<bar> < e \\<and> x + d \\<in> S\" if \"0 < e\"  for e\n    proof -\n      from that\n      obtain x' where \"x' \\<in> S\" \"x' \\<noteq> x\" \"\\<bar>x' - x\\<bar> < e\"\n        using islimpt_approachable_real[of x S] not_bot\n        by (auto simp add: trivial_limit_within)\n      then show ?thesis\n        using eq_iff_diff_eq_0 by fastforce\n    qed\n  qed (use f' f'' in \\<open>auto simp: has_vector_derivative_def\\<close>)\n  then show ?thesis\n    unfolding fun_eq_iff by (metis scaleR_one)\nqed\n\nlemma vector_derivative_unique_at:\n  \"(f has_vector_derivative f') (at x) \\<Longrightarrow> (f has_vector_derivative f'') (at x) \\<Longrightarrow> f' = f''\"\n  by (rule vector_derivative_unique_within) auto\n\nlemma differentiableI_vector: \"(f has_vector_derivative y) F \\<Longrightarrow> f differentiable F\"\n  by (auto simp: differentiable_def has_vector_derivative_def)\n\nproposition vector_derivative_works:\n  \"f differentiable net \\<longleftrightarrow> (f has_vector_derivative (vector_derivative f net)) net\"\n    (is \"?l = ?r\")\nproof\n  assume ?l\n  obtain f' where f': \"(f has_derivative f') net\"\n    using \\<open>?l\\<close> unfolding differentiable_def ..\n  then interpret bounded_linear f'\n    by auto\n  show ?r\n    unfolding vector_derivative_def has_vector_derivative_def\n    by (rule someI[of _ \"f' 1\"]) (simp add: scaleR[symmetric] f')\nqed (auto simp: vector_derivative_def has_vector_derivative_def differentiable_def)\n\nlemma vector_derivative_within:\n  assumes not_bot: \"at x within S \\<noteq> bot\" and y: \"(f has_vector_derivative y) (at x within S)\"\n  shows \"vector_derivative f (at x within S) = y\"\n  using y\n  by (intro vector_derivative_unique_within[OF not_bot vector_derivative_works[THEN iffD1] y])\n     (auto simp: differentiable_def has_vector_derivative_def)\n\nlemma deriv_of_real [simp]: \n  \"at x within A \\<noteq> bot \\<Longrightarrow> vector_derivative of_real (at x within A) = 1\"\n  by (auto intro!: vector_derivative_within derivative_eq_intros)\n\nlemma frechet_derivative_eq_vector_derivative:\n  assumes \"f differentiable (at x)\"\n    shows  \"(frechet_derivative f (at x)) = (\\<lambda>r. r *\\<^sub>R vector_derivative f (at x))\"\nusing assms\nby (auto simp: differentiable_iff_scaleR vector_derivative_def has_vector_derivative_def\n         intro: someI frechet_derivative_at [symmetric])\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 has_vector_derivative_cong_ev:\n  assumes *: \"eventually (\\<lambda>x. x \\<in> S \\<longrightarrow> f x = g x) (nhds x)\" \"f x = g x\"\n  shows \"(f has_vector_derivative f') (at x within S) = (g has_vector_derivative f') (at x within S)\"\nproof (cases \"at x within S = bot\")\n  case True\n  then show ?thesis   \n    by (simp add: has_derivative_def has_vector_derivative_def)\nnext\n  case False\n  then show ?thesis\n  unfolding has_vector_derivative_def has_derivative_def\n  using *\n  apply (intro refl conj_cong filterlim_cong)\n  apply (auto simp: Lim_ident_at eventually_at_filter elim: eventually_mono)\n  done\nqed\n\nlemma vector_derivative_cong_eq:\n  assumes \"eventually (\\<lambda>x. x \\<in> A \\<longrightarrow> f x = g x) (nhds x)\" \"x = y\" \"A = B\" \"x \\<in> A\"\n  shows   \"vector_derivative f (at x within A) = vector_derivative g (at y within B)\"\nproof -\n  have \"f x = g x\"\n    using assms eventually_nhds_x_imp_x by blast\n  hence \"(\\<lambda>D. (f has_vector_derivative D) (at x within A)) = \n           (\\<lambda>D. (g has_vector_derivative D) (at x within A))\" using assms\n    by (intro ext has_vector_derivative_cong_ev refl assms) simp_all\n  thus ?thesis by (simp add: vector_derivative_def assms)\nqed\n  \nlemma islimpt_closure_open:\n  fixes s :: \"'a::perfect_space set\"\n  assumes \"open s\" and t: \"t = closure s\" \"x \\<in> t\"\n  shows \"x islimpt t\"\nproof cases\n  assume \"x \\<in> s\"\n  { fix T assume \"x \\<in> T\" \"open T\"\n    then have \"open (s \\<inter> T)\"\n      using \\<open>open s\\<close> by auto\n    then have \"s \\<inter> T \\<noteq> {x}\"\n      using not_open_singleton[of x] by auto\n    with \\<open>x \\<in> T\\<close> \\<open>x \\<in> s\\<close> have \"\\<exists>y\\<in>t. y \\<in> T \\<and> y \\<noteq> x\"\n      using closure_subset[of s] by (auto simp: t) }\n  then show ?thesis\n    by (auto intro!: islimptI)\nnext\n  assume \"x \\<notin> s\" with t show ?thesis\n    unfolding t closure_def by (auto intro: islimpt_subset)\nqed\n\nlemma vector_derivative_unique_within_closed_interval:\n  assumes ab: \"a < b\" \"x \\<in> cbox a b\"\n  assumes D: \"(f has_vector_derivative f') (at x within cbox a b)\" \"(f has_vector_derivative f'') (at x within cbox a b)\"\n  shows \"f' = f''\"\n  using ab\n  by (intro vector_derivative_unique_within[OF _ D])\n     (auto simp: trivial_limit_within intro!: islimpt_closure_open[where s=\"{a <..< b}\"])\n\nlemma vector_derivative_at:\n  \"(f has_vector_derivative f') (at x) \\<Longrightarrow> vector_derivative f (at x) = f'\"\n  by (intro vector_derivative_within at_neq_bot)\n\nlemma has_vector_derivative_id_at [simp]: \"vector_derivative (\\<lambda>x. x) (at a) = 1\"\n  by (simp add: vector_derivative_at)\n\nlemma vector_derivative_minus_at [simp]:\n  \"f differentiable at a\n   \\<Longrightarrow> vector_derivative (\\<lambda>x. - f x) (at a) = - vector_derivative f (at a)\"\n  by (simp add: vector_derivative_at has_vector_derivative_minus vector_derivative_works [symmetric])\n\nlemma vector_derivative_add_at [simp]:\n  \"\\<lbrakk>f differentiable at a; g differentiable at a\\<rbrakk>\n   \\<Longrightarrow> vector_derivative (\\<lambda>x. f x + g x) (at a) = vector_derivative f (at a) + vector_derivative g (at a)\"\n  by (simp add: vector_derivative_at has_vector_derivative_add vector_derivative_works [symmetric])\n\nlemma vector_derivative_diff_at [simp,derivative_intros]:\n  \"\\<lbrakk>f differentiable at a; g differentiable at a\\<rbrakk>\n   \\<Longrightarrow> vector_derivative (\\<lambda>x. f x - g x) (at a) = vector_derivative f (at a) - vector_derivative g (at a)\"\n  by (simp add: vector_derivative_at has_vector_derivative_diff vector_derivative_works [symmetric])\n\nlemma vector_derivative_mult_at [simp]:\n  fixes f g :: \"real \\<Rightarrow> 'a :: real_normed_algebra\"\n  shows  \"\\<lbrakk>f differentiable at a; g differentiable at a\\<rbrakk>\n   \\<Longrightarrow> vector_derivative (\\<lambda>x. f x * g x) (at a) = f a * vector_derivative g (at a) + vector_derivative f (at a) * g a\"\n  by (simp add: vector_derivative_at has_vector_derivative_mult vector_derivative_works [symmetric])\n\nlemma vector_derivative_scaleR_at [simp]:\n    \"\\<lbrakk>f differentiable at a; g differentiable at a\\<rbrakk>\n   \\<Longrightarrow> vector_derivative (\\<lambda>x. f x *\\<^sub>R g x) (at a) = f a *\\<^sub>R vector_derivative g (at a) + vector_derivative f (at a) *\\<^sub>R g a\"\n  apply (intro vector_derivative_at has_vector_derivative_scaleR)\n   apply (auto simp: vector_derivative_works has_vector_derivative_def has_field_derivative_def mult_commute_abs)\n  done\n\nlemma vector_derivative_within_cbox:\n  assumes ab: \"a < b\" \"x \\<in> cbox a b\"\n  assumes f: \"(f has_vector_derivative f') (at x within cbox a b)\"\n  shows \"vector_derivative f (at x within cbox a b) = f'\"\n  by (metis assms box_real(2) f islimpt_Icc trivial_limit_within vector_derivative_within)\n\nlemma vector_derivative_within_closed_interval:\n  fixes f::\"real \\<Rightarrow> 'a::euclidean_space\"\n  assumes \"a < b\" and \"x \\<in> {a..b}\"\n  assumes \"(f has_vector_derivative f') (at x within {a..b})\"\n  shows \"vector_derivative f (at x within {a..b}) = f'\"\n  using assms vector_derivative_within_cbox\n  by fastforce\n\nlemma has_vector_derivative_within_subset:\n  \"(f has_vector_derivative f') (at x within S) \\<Longrightarrow> T \\<subseteq> S \\<Longrightarrow> (f has_vector_derivative f') (at x within T)\"\n  by (auto simp: has_vector_derivative_def intro: has_derivative_subset)\n\nlemma has_vector_derivative_at_within:\n  \"(f has_vector_derivative f') (at x) \\<Longrightarrow> (f has_vector_derivative f') (at x within S)\"\n  unfolding has_vector_derivative_def\n  by (rule has_derivative_at_withinI)\n\nlemma has_vector_derivative_weaken:\n  fixes x D and f g S T\n  assumes f: \"(f has_vector_derivative D) (at x within T)\"\n    and \"x \\<in> S\" \"S \\<subseteq> T\"\n    and \"\\<And>x. x \\<in> S \\<Longrightarrow> f x = g x\"\n  shows \"(g has_vector_derivative D) (at x within S)\"\nproof -\n  have \"(f has_vector_derivative D) (at x within S) \\<longleftrightarrow> (g has_vector_derivative D) (at x within S)\"\n    unfolding has_vector_derivative_def has_derivative_iff_norm\n    using assms by (intro conj_cong Lim_cong_within refl) auto\n  then show ?thesis\n    using has_vector_derivative_within_subset[OF f \\<open>S \\<subseteq> T\\<close>] by simp\nqed\n\nlemma has_vector_derivative_transform_within:\n  assumes \"(f has_vector_derivative f') (at x within S)\"\n    and \"0 < d\"\n    and \"x \\<in> S\"\n    and \"\\<And>x'. \\<lbrakk>x'\\<in>S; dist x' x < d\\<rbrakk> \\<Longrightarrow> f x' = g x'\"\n    shows \"(g has_vector_derivative f') (at x within S)\"\n  using assms\n  unfolding has_vector_derivative_def\n  by (rule has_derivative_transform_within)\n\nlemma has_vector_derivative_transform_within_open:\n  assumes \"(f has_vector_derivative f') (at x)\"\n    and \"open S\"\n    and \"x \\<in> S\"\n    and \"\\<And>y. y\\<in>S \\<Longrightarrow> f y = g y\"\n  shows \"(g has_vector_derivative f') (at x)\"\n  using assms\n  unfolding has_vector_derivative_def\n  by (rule has_derivative_transform_within_open)\n\nlemma has_vector_derivative_transform:\n  assumes \"x \\<in> S\" \"\\<And>x. x \\<in> S \\<Longrightarrow> g x = f x\"\n  assumes f': \"(f has_vector_derivative f') (at x within S)\"\n  shows \"(g has_vector_derivative f') (at x within S)\"\n  using assms\n  unfolding has_vector_derivative_def\n  by (rule has_derivative_transform)\n\nlemma vector_diff_chain_at:\n  assumes \"(f has_vector_derivative f') (at x)\"\n    and \"(g has_vector_derivative g') (at (f x))\"\n  shows \"((g \\<circ> f) has_vector_derivative (f' *\\<^sub>R g')) (at x)\"\n  using assms has_vector_derivative_at_within has_vector_derivative_def vector_derivative_diff_chain_within by blast\n\nlemma vector_diff_chain_within:\n  assumes \"(f has_vector_derivative f') (at x within s)\"\n    and \"(g has_vector_derivative g') (at (f x) within f ` s)\"\n  shows \"((g \\<circ> f) has_vector_derivative (f' *\\<^sub>R g')) (at x within s)\"\n  using assms has_vector_derivative_def vector_derivative_diff_chain_within by blast\n\nlemma vector_derivative_const_at [simp]: \"vector_derivative (\\<lambda>x. c) (at a) = 0\"\n  by (simp add: vector_derivative_at)\n\nlemma vector_derivative_at_within_ivl:\n  \"(f has_vector_derivative f') (at x) \\<Longrightarrow>\n    a \\<le> x \\<Longrightarrow> x \\<le> b \\<Longrightarrow> a<b \\<Longrightarrow> vector_derivative f (at x within {a..b}) = f'\"\n  using has_vector_derivative_at_within vector_derivative_within_cbox by fastforce\n\nlemma vector_derivative_chain_at:\n  assumes \"f differentiable at x\" \"(g differentiable at (f x))\"\n  shows \"vector_derivative (g \\<circ> f) (at x) =\n         vector_derivative f (at x) *\\<^sub>R vector_derivative g (at (f x))\"\nby (metis vector_diff_chain_at vector_derivative_at vector_derivative_works assms)\n\nlemma field_vector_diff_chain_at:  (*thanks to Wenda Li*)\n assumes Df: \"(f has_vector_derivative f') (at x)\"\n     and Dg: \"(g has_field_derivative g') (at (f x))\"\n shows \"((g \\<circ> f) has_vector_derivative (f' * g')) (at x)\"\nusing diff_chain_at[OF Df[unfolded has_vector_derivative_def]\n                       Dg [unfolded has_field_derivative_def]]\n by (auto simp: o_def mult.commute has_vector_derivative_def)\n\nlemma vector_derivative_chain_within: \n  assumes \"at x within S \\<noteq> bot\" \"f differentiable (at x within S)\" \n    \"(g has_derivative g') (at (f x) within f ` S)\" \n  shows \"vector_derivative (g \\<circ> f) (at x within S) =\n        g' (vector_derivative f (at x within S)) \"\n  apply (rule vector_derivative_within [OF \\<open>at x within S \\<noteq> bot\\<close>])\n  apply (rule vector_derivative_diff_chain_within)\n  using assms(2-3) vector_derivative_works\n  by auto\n\nsubsection \\<open>Field differentiability\\<close>\n\ndefinition\\<^marker>\\<open>tag important\\<close> field_differentiable :: \"['a \\<Rightarrow> 'a::real_normed_field, 'a filter] \\<Rightarrow> bool\"\n           (infixr \"(field'_differentiable)\" 50)\n  where \"f field_differentiable F \\<equiv> \\<exists>f'. (f has_field_derivative f') F\"\n\nlemma field_differentiable_imp_differentiable:\n  \"f field_differentiable F \\<Longrightarrow> f differentiable F\"\n  unfolding field_differentiable_def differentiable_def \n  using has_field_derivative_imp_has_derivative by auto\n\nlemma field_differentiable_imp_continuous_at:\n    \"f field_differentiable (at x within S) \\<Longrightarrow> continuous (at x within S) f\"\n  by (metis DERIV_continuous field_differentiable_def)\n\nlemma field_differentiable_within_subset:\n    \"\\<lbrakk>f field_differentiable (at x within S); T \\<subseteq> S\\<rbrakk> \\<Longrightarrow> f field_differentiable (at x within T)\"\n  by (metis DERIV_subset field_differentiable_def)\n\nlemma field_differentiable_at_within:\n    \"\\<lbrakk>f field_differentiable (at x)\\<rbrakk>\n     \\<Longrightarrow> f field_differentiable (at x within S)\"\n  unfolding field_differentiable_def\n  by (metis DERIV_subset top_greatest)\n\nlemma field_differentiable_linear [simp,derivative_intros]: \"((*) c) field_differentiable F\"\n  unfolding field_differentiable_def has_field_derivative_def mult_commute_abs\n  by (force intro: has_derivative_mult_right)\n\nlemma field_differentiable_const [simp,derivative_intros]: \"(\\<lambda>z. c) field_differentiable F\"\n  unfolding field_differentiable_def has_field_derivative_def\n  using DERIV_const has_field_derivative_imp_has_derivative by blast\n\nlemma field_differentiable_ident [simp,derivative_intros]: \"(\\<lambda>z. z) field_differentiable F\"\n  unfolding field_differentiable_def has_field_derivative_def\n  using DERIV_ident has_field_derivative_def by blast\n\nlemma field_differentiable_id [simp,derivative_intros]: \"id field_differentiable F\"\n  unfolding id_def by (rule field_differentiable_ident)\n\nlemma field_differentiable_minus [derivative_intros]:\n  \"f field_differentiable F \\<Longrightarrow> (\\<lambda>z. - (f z)) field_differentiable F\"\n  unfolding field_differentiable_def by (metis field_differentiable_minus)\n\nlemma field_differentiable_diff_const [simp,derivative_intros]:\n  \"(-)c field_differentiable F\"\n  unfolding field_differentiable_def by (rule derivative_eq_intros exI | force)+\n\nlemma field_differentiable_add [derivative_intros]:\n  assumes \"f field_differentiable F\" \"g field_differentiable F\"\n    shows \"(\\<lambda>z. f z + g z) field_differentiable F\"\n  using assms unfolding field_differentiable_def\n  by (metis field_differentiable_add)\n\nlemma field_differentiable_add_const [simp,derivative_intros]:\n     \"(+) c field_differentiable F\"\n  by (simp add: field_differentiable_add)\n\nlemma field_differentiable_sum [derivative_intros]:\n  \"(\\<And>i. i \\<in> I \\<Longrightarrow> (f i) field_differentiable F) \\<Longrightarrow> (\\<lambda>z. \\<Sum>i\\<in>I. f i z) field_differentiable F\"\n  by (induct I rule: infinite_finite_induct)\n     (auto intro: field_differentiable_add field_differentiable_const)\n\nlemma field_differentiable_diff [derivative_intros]:\n  assumes \"f field_differentiable F\" \"g field_differentiable F\"\n    shows \"(\\<lambda>z. f z - g z) field_differentiable F\"\n  using assms unfolding field_differentiable_def\n  by (metis field_differentiable_diff)\n\nlemma field_differentiable_inverse [derivative_intros]:\n  assumes \"f field_differentiable (at a within S)\" \"f a \\<noteq> 0\"\n  shows \"(\\<lambda>z. inverse (f z)) field_differentiable (at a within S)\"\n  using assms unfolding field_differentiable_def\n  by (metis DERIV_inverse_fun)\n\nlemma field_differentiable_mult [derivative_intros]:\n  assumes \"f field_differentiable (at a within S)\"\n          \"g field_differentiable (at a within S)\"\n    shows \"(\\<lambda>z. f z * g z) field_differentiable (at a within S)\"\n  using assms unfolding field_differentiable_def\n  by (metis DERIV_mult [of f _ a S g])\n\nlemma field_differentiable_divide [derivative_intros]:\n  assumes \"f field_differentiable (at a within S)\"\n          \"g field_differentiable (at a within S)\"\n          \"g a \\<noteq> 0\"\n    shows \"(\\<lambda>z. f z / g z) field_differentiable (at a within S)\"\n  using assms unfolding field_differentiable_def\n  by (metis DERIV_divide [of f _ a S g])\n\nlemma field_differentiable_power [derivative_intros]:\n  assumes \"f field_differentiable (at a within S)\"\n    shows \"(\\<lambda>z. f z ^ n) field_differentiable (at a within S)\"\n  using assms unfolding field_differentiable_def\n  by (metis DERIV_power)\n\nlemma field_differentiable_cnj_cnj:\n  assumes \"f field_differentiable (at (cnj z))\"\n  shows   \"(cnj \\<circ> f \\<circ> cnj) field_differentiable (at z)\"\n  using has_field_derivative_cnj_cnj assms\n  by (auto simp: field_differentiable_def)\n \nlemma field_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 field_differentiable (at x within S)\n        \\<Longrightarrow> g field_differentiable (at x within S)\"\n  unfolding field_differentiable_def has_field_derivative_def\n  by (blast intro: has_derivative_transform_within)\n\nlemma field_differentiable_compose_within:\n  assumes \"f field_differentiable (at a within S)\"\n          \"g field_differentiable (at (f a) within f`S)\"\n    shows \"(g o f) field_differentiable (at a within S)\"\n  using assms unfolding field_differentiable_def\n  by (metis DERIV_image_chain)\n\nlemma field_differentiable_compose:\n  \"f field_differentiable at z \\<Longrightarrow> g field_differentiable at (f z)\n          \\<Longrightarrow> (g o f) field_differentiable at z\"\nby (metis field_differentiable_at_within field_differentiable_compose_within)\n\nlemma field_differentiable_within_open:\n     \"\\<lbrakk>a \\<in> S; open S\\<rbrakk> \\<Longrightarrow> f field_differentiable at a within S \\<longleftrightarrow>\n                          f field_differentiable at a\"\n  unfolding field_differentiable_def\n  by (metis at_within_open)\n\nlemma exp_scaleR_has_vector_derivative_right:\n  \"((\\<lambda>t. exp (t *\\<^sub>R A)) has_vector_derivative exp (t *\\<^sub>R A) * A) (at t within T)\"\n  unfolding has_vector_derivative_def\nproof (rule has_derivativeI)\n  let ?F = \"at t within (T \\<inter> {t - 1 <..< t + 1})\"\n  have *: \"at t within T = ?F\"\n    by (rule at_within_nhd[where S=\"{t - 1 <..< t + 1}\"]) auto\n  let ?e = \"\\<lambda>i x. (inverse (1 + real i) * inverse (fact i) * (x - t) ^ i) *\\<^sub>R (A * A ^ i)\"\n  have \"\\<forall>\\<^sub>F n in sequentially.\n      \\<forall>x\\<in>T \\<inter> {t - 1<..<t + 1}. norm (?e n x) \\<le> norm (A ^ (n + 1) /\\<^sub>R fact (n + 1))\"\n    apply (auto simp: algebra_split_simps intro!: eventuallyI)\n    apply (rule mult_left_mono)\n     apply (auto simp add: field_simps power_abs intro!: divide_right_mono power_le_one)\n    done\n  then have \"uniform_limit (T \\<inter> {t - 1<..<t + 1}) (\\<lambda>n x. \\<Sum>i<n. ?e i x) (\\<lambda>x. \\<Sum>i. ?e i x) sequentially\"\n    by (rule Weierstrass_m_test_ev) (intro summable_ignore_initial_segment summable_norm_exp)\n  moreover\n  have \"\\<forall>\\<^sub>F x in sequentially. x > 0\"\n    by (metis eventually_gt_at_top)\n  then have\n    \"\\<forall>\\<^sub>F n in sequentially. ((\\<lambda>x. \\<Sum>i<n. ?e i x) \\<longlongrightarrow> A) ?F\"\n    by eventually_elim\n      (auto intro!: tendsto_eq_intros\n        simp: power_0_left if_distrib if_distribR\n        cong: if_cong)\n  ultimately\n  have [tendsto_intros]: \"((\\<lambda>x. \\<Sum>i. ?e i x) \\<longlongrightarrow> A) ?F\"\n    by (auto intro!: swap_uniform_limit[where f=\"\\<lambda>n x. \\<Sum>i < n. ?e i x\" and F = sequentially])\n  have [tendsto_intros]: \"((\\<lambda>x. if x = t then 0 else 1) \\<longlongrightarrow> 1) ?F\"\n    by (rule tendsto_eventually) (simp add: eventually_at_filter)\n  have \"((\\<lambda>y. ((y - t) / abs (y - t)) *\\<^sub>R ((\\<Sum>n. ?e n y) - A)) \\<longlongrightarrow> 0) (at t within T)\"\n    unfolding *\n    by (rule tendsto_norm_zero_cancel) (auto intro!: tendsto_eq_intros)\n\n  moreover have \"\\<forall>\\<^sub>F x in at t within T. x \\<noteq> t\"\n    by (simp add: eventually_at_filter)\n  then have \"\\<forall>\\<^sub>F x in at t within T. ((x - t) / \\<bar>x - t\\<bar>) *\\<^sub>R ((\\<Sum>n. ?e n x) - A) =\n    (exp ((x - t) *\\<^sub>R A) - 1 - (x - t) *\\<^sub>R A) /\\<^sub>R norm (x - t)\"\n  proof eventually_elim\n    case (elim x)\n    have \"(exp ((x - t) *\\<^sub>R A) - 1 - (x - t) *\\<^sub>R A) /\\<^sub>R norm (x - t) =\n      ((\\<Sum>n. (x - t) *\\<^sub>R ?e n x) - (x - t) *\\<^sub>R A) /\\<^sub>R norm (x - t)\"\n      unfolding exp_first_term\n      by (simp add: ac_simps)\n    also\n    have \"summable (\\<lambda>n. ?e n x)\"\n    proof -\n      from elim have \"?e n x = (((x - t) *\\<^sub>R A) ^ (n + 1)) /\\<^sub>R fact (n + 1) /\\<^sub>R (x - t)\" for n\n        by simp\n      then show ?thesis\n        by (auto simp only:\n          intro!: summable_scaleR_right summable_ignore_initial_segment summable_exp_generic)\n    qed\n    then have \"(\\<Sum>n. (x - t) *\\<^sub>R ?e n x) = (x - t) *\\<^sub>R (\\<Sum>n. ?e n x)\"\n      by (rule suminf_scaleR_right[symmetric])\n    also have \"(\\<dots> - (x - t) *\\<^sub>R A) /\\<^sub>R norm (x - t) = (x - t) *\\<^sub>R ((\\<Sum>n. ?e n x) - A) /\\<^sub>R norm (x - t)\"\n      by (simp add: algebra_simps)\n    finally show ?case\n      by simp (simp add: field_simps)\n  qed\n\n  ultimately have \"((\\<lambda>y. (exp ((y - t) *\\<^sub>R A) - 1 - (y - t) *\\<^sub>R A) /\\<^sub>R norm (y - t)) \\<longlongrightarrow> 0) (at t within T)\"\n    by (rule Lim_transform_eventually)\n  from tendsto_mult_right_zero[OF this, where c=\"exp (t *\\<^sub>R A)\"]\n  show \"((\\<lambda>y. (exp (y *\\<^sub>R A) - exp (t *\\<^sub>R A) - (y - t) *\\<^sub>R (exp (t *\\<^sub>R A) * A)) /\\<^sub>R norm (y - t)) \\<longlongrightarrow> 0)\n      (at t within T)\"\n    by (rule Lim_transform_eventually)\n      (auto simp: field_split_simps exp_add_commuting[symmetric])\nqed (rule bounded_linear_scaleR_left)\n\nlemma exp_times_scaleR_commute: \"exp (t *\\<^sub>R A) * A = A * exp (t *\\<^sub>R A)\"\n  using exp_times_arg_commute[symmetric, of \"t *\\<^sub>R A\"]\n  by (auto simp: algebra_simps)\n\nlemma exp_scaleR_has_vector_derivative_left: \"((\\<lambda>t. exp (t *\\<^sub>R A)) has_vector_derivative A * exp (t *\\<^sub>R A)) (at t)\"\n  using exp_scaleR_has_vector_derivative_right[of A t]\n  by (simp add: exp_times_scaleR_commute)\n\nlemma field_differentiable_series:\n  fixes f :: \"nat \\<Rightarrow> 'a::{real_normed_field,banach} \\<Rightarrow> 'a\"\n  assumes \"convex S\" \"open S\"\n  assumes \"\\<And>n x. x \\<in> S \\<Longrightarrow> (f n has_field_derivative f' n x) (at x)\"\n  assumes \"uniformly_convergent_on S (\\<lambda>n x. \\<Sum>i<n. f' i x)\"\n  assumes \"x0 \\<in> S\" \"summable (\\<lambda>n. f n x0)\" and x: \"x \\<in> S\"\n  shows  \"(\\<lambda>x. \\<Sum>n. f n x) field_differentiable (at x)\"\nproof -\n  from assms(4) obtain g' where A: \"uniform_limit S (\\<lambda>n x. \\<Sum>i<n. f' i x) g' sequentially\"\n    unfolding uniformly_convergent_on_def by blast\n  from x and \\<open>open S\\<close> have S: \"at x within S = at x\" by (rule at_within_open)\n  have \"\\<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)\"\n    by (intro has_field_derivative_series[of S f f' g' x0] assms A has_field_derivative_at_within)\n  then obtain g where g: \"\\<And>x. x \\<in> S \\<Longrightarrow> (\\<lambda>n. f n x) sums g x\"\n    \"\\<And>x. x \\<in> S \\<Longrightarrow> (g has_field_derivative g' x) (at x within S)\" by blast\n  from g(2)[OF x] have g': \"(g has_derivative (*) (g' x)) (at x)\"\n    by (simp add: has_field_derivative_def S)\n  have \"((\\<lambda>x. \\<Sum>n. f n x) has_derivative (*) (g' x)) (at x)\"\n    by (rule has_derivative_transform_within_open[OF g' \\<open>open S\\<close> x])\n       (insert g, auto simp: sums_iff)\n  thus \"(\\<lambda>x. \\<Sum>n. f n x) field_differentiable (at x)\" unfolding differentiable_def\n    by (auto simp: summable_def field_differentiable_def has_field_derivative_def)\nqed\n\nsubsubsection\\<^marker>\\<open>tag unimportant\\<close>\\<open>Caratheodory characterization\\<close>\n\nlemma field_differentiable_caratheodory_at:\n  \"f field_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: field_differentiable_def has_field_derivative_def)\n\nlemma field_differentiable_caratheodory_within:\n  \"f field_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: field_differentiable_def has_field_derivative_def)\n\n\nsubsection \\<open>Field derivative\\<close>\n\ndefinition\\<^marker>\\<open>tag important\\<close> deriv :: \"('a \\<Rightarrow> 'a::real_normed_field) \\<Rightarrow> 'a \\<Rightarrow> 'a\" where\n  \"deriv f x \\<equiv> SOME 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 some_equality DERIV_unique)\n\nlemma DERIV_deriv_iff_has_field_derivative:\n  \"DERIV f x :> deriv f x \\<longleftrightarrow> (\\<exists>f'. (f has_field_derivative f') (at x))\"\n  by (auto simp: has_field_derivative_def DERIV_imp_deriv)\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 DERIV_deriv_iff_field_differentiable:\n  \"DERIV f x :> deriv f x \\<longleftrightarrow> f field_differentiable at x\"\n  unfolding field_differentiable_def by (metis DERIV_imp_deriv)\n\nlemma vector_derivative_of_real_left:\n  assumes \"f differentiable at x\"\n  shows   \"vector_derivative (\\<lambda>x. of_real (f x)) (at x) = of_real (deriv f x)\"\n  by (metis DERIV_deriv_iff_real_differentiable assms has_vector_derivative_of_real vector_derivative_at)\n  \nlemma vector_derivative_of_real_right:\n  assumes \"f field_differentiable at (of_real x)\"\n  shows   \"vector_derivative (\\<lambda>x. f (of_real x)) (at x) = deriv f (of_real x)\"\n  by (metis DERIV_deriv_iff_field_differentiable assms has_vector_derivative_real_field vector_derivative_at)\n  \nlemma deriv_cong_ev:\n  assumes \"eventually (\\<lambda>x. f x = g x) (nhds x)\" \"x = y\"\n  shows   \"deriv f x = deriv g y\"\nproof -\n  have \"(\\<lambda>D. (f has_field_derivative D) (at x)) = (\\<lambda>D. (g has_field_derivative D) (at y))\"\n    by (intro ext DERIV_cong_ev refl assms)\n  thus ?thesis by (simp add: deriv_def assms)\nqed\n\nlemma higher_deriv_cong_ev:\n  assumes \"eventually (\\<lambda>x. f x = g x) (nhds x)\" \"x = y\"\n  shows   \"(deriv ^^ n) f x = (deriv ^^ n) g y\"\nproof -\n  from assms(1) have \"eventually (\\<lambda>x. (deriv ^^ n) f x = (deriv ^^ n) g x) (nhds x)\"\n  proof (induction n arbitrary: f g)\n    case (Suc n)\n    from Suc.prems have \"eventually (\\<lambda>y. eventually (\\<lambda>z. f z = g z) (nhds y)) (nhds x)\"\n      by (simp add: eventually_eventually)\n    hence \"eventually (\\<lambda>x. deriv f x = deriv g x) (nhds x)\"\n      by eventually_elim (rule deriv_cong_ev, simp_all)\n    thus ?case by (auto intro!: deriv_cong_ev Suc simp: funpow_Suc_right simp del: funpow.simps)\n  qed auto\n  with \\<open>x = y\\<close> eventually_nhds_x_imp_x show ?thesis by blast \nqed\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)\nlemma field_derivative_eq_vector_derivative:\n   \"(deriv f x) = vector_derivative f (at x)\"\nby (simp add: mult.commute deriv_def vector_derivative_def has_vector_derivative_def has_field_derivative_def)\n\nproposition field_differentiable_derivI:\n    \"f field_differentiable (at x) \\<Longrightarrow> (f has_field_derivative deriv f x) (at x)\"\nby (simp add: field_differentiable_def DERIV_deriv_iff_has_field_derivative)\n\nlemma vector_derivative_chain_at_general:\n  assumes \"f differentiable at x\" \"g field_differentiable at (f x)\"\n  shows \"vector_derivative (g \\<circ> f) (at x) = vector_derivative f (at x) * deriv g (f x)\"\n  using assms field_differentiable_derivI field_vector_diff_chain_at \n      vector_derivative_at vector_derivative_works by blast\n\nlemma deriv_chain:\n  \"f field_differentiable at x \\<Longrightarrow> g field_differentiable at (f x)\n    \\<Longrightarrow> deriv (g o f) x = deriv g (f x) * deriv f x\"\n  by (metis DERIV_deriv_iff_field_differentiable DERIV_chain DERIV_imp_deriv)\n\nlemma deriv_linear [simp]: \"deriv (\\<lambda>w. c * w) = (\\<lambda>z. c)\"\n  by (metis DERIV_imp_deriv DERIV_cmult_Id)\n\nlemma deriv_uminus [simp]: \"deriv (\\<lambda>w. -w) = (\\<lambda>z. -1)\"\n  using deriv_linear[of \"-1\"] by (simp del: deriv_linear)\n\nlemma deriv_ident [simp]: \"deriv (\\<lambda>w. w) = (\\<lambda>z. 1)\"\n  by (metis DERIV_imp_deriv DERIV_ident)\n\nlemma deriv_id [simp]: \"deriv id = (\\<lambda>z. 1)\"\n  by (simp add: id_def)\n\nlemma deriv_const [simp]: \"deriv (\\<lambda>w. c) = (\\<lambda>z. 0)\"\n  by (metis DERIV_imp_deriv DERIV_const)\n\nlemma deriv_add [simp]:\n  \"\\<lbrakk>f field_differentiable at z; g field_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_field_differentiable[symmetric]\n  by (auto intro!: DERIV_imp_deriv derivative_intros)\n\nlemma deriv_minus [simp]:\n  \"f field_differentiable at z \\<Longrightarrow> deriv (\\<lambda>w. - f w) z = - deriv f z\"\n  by (simp add: DERIV_deriv_iff_field_differentiable DERIV_imp_deriv Deriv.field_differentiable_minus)\n\nlemma deriv_diff [simp]:\n  \"\\<lbrakk>f field_differentiable at z; g field_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_field_differentiable[symmetric]\n  by (auto intro!: DERIV_imp_deriv derivative_intros)\n\nlemma deriv_mult [simp]:\n  \"\\<lbrakk>f field_differentiable at z; g field_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_field_differentiable[symmetric]\n  by (auto intro!: DERIV_imp_deriv derivative_eq_intros)\n\nlemma deriv_cmult:\n  \"f field_differentiable at z \\<Longrightarrow> deriv (\\<lambda>w. c * f w) z = c * deriv f z\"\n  by simp\n\nlemma deriv_cmult_right:\n  \"f field_differentiable at z \\<Longrightarrow> deriv (\\<lambda>w. f w * c) z = deriv f z * c\"\n  by simp\n\nlemma deriv_inverse [simp]:\n  \"\\<lbrakk>f field_differentiable at z; f z \\<noteq> 0\\<rbrakk>\n   \\<Longrightarrow> deriv (\\<lambda>w. inverse (f w)) z = - deriv f z / f z ^ 2\"\n  unfolding DERIV_deriv_iff_field_differentiable[symmetric]\n  by (safe intro!: DERIV_imp_deriv derivative_eq_intros) (auto simp: field_split_simps power2_eq_square)\n\nlemma deriv_divide [simp]:\n  \"\\<lbrakk>f field_differentiable at z; g field_differentiable at z; g z \\<noteq> 0\\<rbrakk>\n   \\<Longrightarrow> deriv (\\<lambda>w. f w / g w) z = (deriv f z * g z - f z * deriv g z) / g z ^ 2\"\n  by (simp add: field_class.field_divide_inverse field_differentiable_inverse)\n     (simp add: field_split_simps power2_eq_square)\n\nlemma deriv_cdivide_right:\n  \"f field_differentiable at z \\<Longrightarrow> deriv (\\<lambda>w. f w / c) z = deriv f z / c\"\n  by (simp add: field_class.field_divide_inverse)\n\nlemma deriv_pow: \"\\<lbrakk>f field_differentiable at z\\<rbrakk>\n   \\<Longrightarrow> deriv (\\<lambda>w. f w ^ n) z = (if n=0 then 0 else n * deriv f z * f z ^ (n - Suc 0))\"\n  unfolding DERIV_deriv_iff_field_differentiable[symmetric]\n  by (auto intro!: DERIV_imp_deriv derivative_eq_intros)\n\nlemma deriv_sum [simp]:\n  \"\\<lbrakk>\\<And>i. f i field_differentiable at z\\<rbrakk>\n   \\<Longrightarrow> deriv (\\<lambda>w. sum (\\<lambda>i. f i w) S) z = sum (\\<lambda>i. deriv (f i) z) S\"\n  unfolding DERIV_deriv_iff_field_differentiable[symmetric]\n  by (auto intro!: DERIV_imp_deriv derivative_intros)\n\nlemma deriv_compose_linear:\n  assumes \"f field_differentiable at (c * z)\"\n  shows \"deriv (\\<lambda>w. f (c * w)) z = c * deriv f (c * z)\"\nproof -\n  have \"deriv (\\<lambda>a. f (c * a)) z = deriv f (c * z) * c\"\n    using assms by (simp add: DERIV_chain2 DERIV_deriv_iff_field_differentiable DERIV_imp_deriv)\n  then show ?thesis\n    by simp\nqed\n\n\nlemma nonzero_deriv_nonconstant:\n  assumes df: \"DERIV f \\<xi> :> df\" and S: \"open S\" \"\\<xi> \\<in> S\" and \"df \\<noteq> 0\"\n    shows \"\\<not> f constant_on S\"\nunfolding constant_on_def\nby (metis \\<open>df \\<noteq> 0\\<close> has_field_derivative_transform_within_open [OF df S] DERIV_const DERIV_unique)\n\n\nsubsection \\<open>Relation between convexity and derivative\\<close>\n\n(* TODO: Generalise to real vector spaces? *)\nproposition convex_on_imp_above_tangent:\n  assumes convex: \"convex_on A f\" and connected: \"connected A\"\n  assumes c: \"c \\<in> interior A\" and x : \"x \\<in> A\"\n  assumes deriv: \"(f has_field_derivative f') (at c within A)\"\n  shows   \"f x - f c \\<ge> f' * (x - c)\"\nproof (cases x c rule: linorder_cases)\n  assume xc: \"x > c\"\n  let ?A' = \"interior A \\<inter> {c<..}\"\n  from c have \"c \\<in> interior A \\<inter> closure {c<..}\" by auto\n  also have \"\\<dots> \\<subseteq> closure (interior A \\<inter> {c<..})\" by (intro open_Int_closure_subset) auto\n  finally have \"at c within ?A' \\<noteq> bot\" by (subst at_within_eq_bot_iff) auto\n  moreover from deriv have \"((\\<lambda>y. (f y - f c) / (y - c)) \\<longlongrightarrow> f') (at c within ?A')\"\n    unfolding has_field_derivative_iff using interior_subset[of A] by (blast intro: tendsto_mono at_le)\n  moreover from eventually_at_right_real[OF xc]\n    have \"eventually (\\<lambda>y. (f y - f c) / (y - c) \\<le> (f x - f c) / (x - c)) (at_right c)\"\n  proof eventually_elim\n    fix y assume y: \"y \\<in> {c<..<x}\"\n    with convex connected x c have \"f y \\<le> (f x - f c) / (x - c) * (y - c) + f c\"\n      using interior_subset[of A]\n      by (intro convex_onD_Icc' convex_on_subset[OF convex] connected_contains_Icc) auto\n    hence \"f y - f c \\<le> (f x - f c) / (x - c) * (y - c)\" by simp\n    thus \"(f y - f c) / (y - c) \\<le> (f x - f c) / (x - c)\" using y xc by (simp add: field_split_simps)\n  qed\n  hence \"eventually (\\<lambda>y. (f y - f c) / (y - c) \\<le> (f x - f c) / (x - c)) (at c within ?A')\"\n    by (blast intro: filter_leD at_le)\n  ultimately have \"f' \\<le> (f x - f c) / (x - c)\" by (simp add: tendsto_upperbound)\n  thus ?thesis using xc by (simp add: field_simps)\nnext\n  assume xc: \"x < c\"\n  let ?A' = \"interior A \\<inter> {..<c}\"\n  from c have \"c \\<in> interior A \\<inter> closure {..<c}\" by auto\n  also have \"\\<dots> \\<subseteq> closure (interior A \\<inter> {..<c})\" by (intro open_Int_closure_subset) auto\n  finally have \"at c within ?A' \\<noteq> bot\" by (subst at_within_eq_bot_iff) auto\n  moreover from deriv have \"((\\<lambda>y. (f y - f c) / (y - c)) \\<longlongrightarrow> f') (at c within ?A')\"\n    unfolding has_field_derivative_iff using interior_subset[of A] by (blast intro: tendsto_mono at_le)\n  moreover from eventually_at_left_real[OF xc]\n    have \"eventually (\\<lambda>y. (f y - f c) / (y - c) \\<ge> (f x - f c) / (x - c)) (at_left c)\"\n  proof eventually_elim\n    fix y assume y: \"y \\<in> {x<..<c}\"\n    with convex connected x c have \"f y \\<le> (f x - f c) / (c - x) * (c - y) + f c\"\n      using interior_subset[of A]\n      by (intro convex_onD_Icc'' convex_on_subset[OF convex] connected_contains_Icc) auto\n    hence \"f y - f c \\<le> (f x - f c) * ((c - y) / (c - x))\" by simp\n    also have \"(c - y) / (c - x) = (y - c) / (x - c)\" using y xc by (simp add: field_simps)\n    finally show \"(f y - f c) / (y - c) \\<ge> (f x - f c) / (x - c)\" using y xc\n      by (simp add: field_split_simps)\n  qed\n  hence \"eventually (\\<lambda>y. (f y - f c) / (y - c) \\<ge> (f x - f c) / (x - c)) (at c within ?A')\"\n    by (blast intro: filter_leD at_le)\n  ultimately have \"f' \\<ge> (f x - f c) / (x - c)\" by (simp add: tendsto_lowerbound)\n  thus ?thesis using xc by (simp add: field_simps)\nqed simp_all\n\n\nsubsection \\<open>Partial derivatives\\<close>\n\nlemma eventually_at_Pair_within_TimesI1:\n  fixes x::\"'a::metric_space\"\n  assumes \"\\<forall>\\<^sub>F x' in at x within X. P x'\"\n  assumes \"P x\"\n  shows \"\\<forall>\\<^sub>F (x', y') in at (x, y) within X \\<times> Y. P x'\"\nproof -\n  from assms[unfolded eventually_at_topological]\n  obtain S where S: \"open S\" \"x \\<in> S\" \"\\<And>x'. x' \\<in> X \\<Longrightarrow> x' \\<in> S \\<Longrightarrow> P x'\"\n    by metis\n  show \"\\<forall>\\<^sub>F (x', y') in at (x, y) within X \\<times> Y. P x'\"\n    unfolding eventually_at_topological\n    by (auto intro!: exI[where x=\"S \\<times> UNIV\"] S open_Times)\nqed\n\nlemma eventually_at_Pair_within_TimesI2:\n  fixes x::\"'a::metric_space\"\n  assumes \"\\<forall>\\<^sub>F y' in at y within Y. P y'\" \"P y\"\n  shows \"\\<forall>\\<^sub>F (x', y') in at (x, y) within X \\<times> Y. P y'\"\nproof -\n  from assms[unfolded eventually_at_topological]\n  obtain S where S: \"open S\" \"y \\<in> S\" \"\\<And>y'. y' \\<in> Y \\<Longrightarrow> y' \\<in> S \\<Longrightarrow> P y'\"\n    by metis\n  show \"\\<forall>\\<^sub>F (x', y') in at (x, y) within X \\<times> Y. P y'\"\n    unfolding eventually_at_topological\n    by (auto intro!: exI[where x=\"UNIV \\<times> S\"] S open_Times)\nqed\n\nproposition has_derivative_partialsI:\n  fixes f::\"'a::real_normed_vector \\<Rightarrow> 'b::real_normed_vector \\<Rightarrow> 'c::real_normed_vector\"\n  assumes fx: \"((\\<lambda>x. f x y) has_derivative fx) (at x within X)\"\n  assumes fy: \"\\<And>x y. x \\<in> X \\<Longrightarrow> y \\<in> Y \\<Longrightarrow> ((\\<lambda>y. f x y) has_derivative blinfun_apply (fy x y)) (at y within Y)\"\n  assumes fy_cont[unfolded continuous_within]: \"continuous (at (x, y) within X \\<times> Y) (\\<lambda>(x, y). fy x y)\"\n  assumes \"y \\<in> Y\" \"convex Y\"\n  shows \"((\\<lambda>(x, y). f x y) has_derivative (\\<lambda>(tx, ty). fx tx + fy x y ty)) (at (x, y) within X \\<times> Y)\"\nproof (safe intro!: has_derivativeI tendstoI, goal_cases)\n  case (2 e')\n  interpret fx: bounded_linear \"fx\" using fx by (rule has_derivative_bounded_linear)\n  define e where \"e = e' / 9\"\n  have \"e > 0\" using \\<open>e' > 0\\<close> by (simp add: e_def)\n\n  from fy_cont[THEN tendstoD, OF \\<open>e > 0\\<close>]\n  have \"\\<forall>\\<^sub>F (x', y') in at (x, y) within X \\<times> Y. dist (fy x' y') (fy x y) < e\"\n    by (auto simp: split_beta')\n  from this[unfolded eventually_at] obtain d' where\n    \"d' > 0\"\n    \"\\<And>x' y'. x' \\<in> X \\<Longrightarrow> y' \\<in> Y \\<Longrightarrow> (x', y') \\<noteq> (x, y) \\<Longrightarrow> dist (x', y') (x, y) < d' \\<Longrightarrow>\n      dist (fy x' y') (fy x y) < e\"\n    by auto\n  then\n  have d': \"x' \\<in> X \\<Longrightarrow> y' \\<in> Y \\<Longrightarrow> dist (x', y') (x, y) < d' \\<Longrightarrow> dist (fy x' y') (fy x y) < e\"\n    for x' y'\n    using \\<open>0 < e\\<close>\n    by (cases \"(x', y') = (x, y)\") auto\n  define d where \"d = d' / sqrt 2\"\n  have \"d > 0\" using \\<open>0 < d'\\<close> by (simp add: d_def)\n  have d: \"x' \\<in> X \\<Longrightarrow> y' \\<in> Y \\<Longrightarrow> dist x' x < d \\<Longrightarrow> dist y' y < d \\<Longrightarrow> dist (fy x' y') (fy x y) < e\"\n    for x' y'\n    by (auto simp: dist_prod_def d_def intro!: d' real_sqrt_sum_squares_less)\n\n  let ?S = \"ball y d \\<inter> Y\"\n  have \"convex ?S\"\n    by (auto intro!: convex_Int \\<open>convex Y\\<close>)\n  {\n    fix x'::'a and y'::'b\n    assume x': \"x' \\<in> X\" and y': \"y' \\<in> Y\"\n    assume dx': \"dist x' x < d\" and dy': \"dist y' y < d\"\n    have \"norm (fy x' y' - fy x' y) \\<le> dist (fy x' y') (fy x y) + dist (fy x' y) (fy x y)\"\n      by norm\n    also have \"dist (fy x' y') (fy x y) < e\"\n      by (rule d; fact)\n    also have \"dist (fy x' y) (fy x y) < e\"\n      by (auto intro!: d simp: dist_prod_def x' \\<open>d > 0\\<close> \\<open>y \\<in> Y\\<close> dx')\n    finally\n    have \"norm (fy x' y' - fy x' y) < e + e\"\n      by arith\n    then have \"onorm (blinfun_apply (fy x' y') - blinfun_apply (fy x' y)) < e + e\"\n      by (auto simp: norm_blinfun.rep_eq blinfun.diff_left[abs_def] fun_diff_def)\n  } note onorm = this\n\n  have ev_mem: \"\\<forall>\\<^sub>F (x', y') in at (x, y) within X \\<times> Y. (x', y') \\<in> X \\<times> Y\"\n    using \\<open>y \\<in> Y\\<close>\n    by (auto simp: eventually_at intro!: zero_less_one)\n  moreover\n  have ev_dist: \"\\<forall>\\<^sub>F xy in at (x, y) within X \\<times> Y. dist xy (x, y) < d\" if \"d > 0\" for d\n    using eventually_at_ball[OF that]\n    by (rule eventually_elim2) (auto simp: dist_commute intro!: eventually_True)\n  note ev_dist[OF \\<open>0 < d\\<close>]\n  ultimately\n  have \"\\<forall>\\<^sub>F (x', y') in at (x, y) within X \\<times> Y.\n    norm (f x' y' - f x' y - (fy x' y) (y' - y)) \\<le> norm (y' - y) * (e + e)\"\n  proof (eventually_elim, safe)\n    fix x' y'\n    assume \"x' \\<in> X\" and y': \"y' \\<in> Y\"\n    assume dist: \"dist (x', y') (x, y) < d\"\n    then have dx: \"dist x' x < d\" and dy: \"dist y' y < d\"\n      unfolding dist_prod_def fst_conv snd_conv atomize_conj\n      by (metis le_less_trans real_sqrt_sum_squares_ge1 real_sqrt_sum_squares_ge2)\n    {\n      fix t::real\n      assume \"t \\<in> {0 .. 1}\"\n      then have \"y + t *\\<^sub>R (y' - y) \\<in> closed_segment y y'\"\n        by (auto simp: closed_segment_def algebra_simps intro!: exI[where x=t])\n      also\n      have \"\\<dots> \\<subseteq> ball y d \\<inter> Y\"\n        using \\<open>y \\<in> Y\\<close> \\<open>0 < d\\<close> dy y'\n        by (intro \\<open>convex ?S\\<close>[unfolded convex_contains_segment, rule_format, of y y'])\n          (auto simp: dist_commute)\n      finally have \"y + t *\\<^sub>R (y' - y) \\<in> ?S\" .\n    } note seg = this\n\n    have \"\\<And>x. x \\<in> ball y d \\<inter> Y \\<Longrightarrow> onorm (blinfun_apply (fy x' x) - blinfun_apply (fy x' y)) \\<le> e + e\"\n      by (safe intro!: onorm less_imp_le \\<open>x' \\<in> X\\<close> dx) (auto simp: dist_commute \\<open>0 < d\\<close> \\<open>y \\<in> Y\\<close>)\n    with seg has_derivative_subset[OF assms(2)[OF \\<open>x' \\<in> X\\<close>]]\n    show \"norm (f x' y' - f x' y - (fy x' y) (y' - y)) \\<le> norm (y' - y) * (e + e)\"\n      by (rule differentiable_bound_linearization[where S=\"?S\"])\n        (auto intro!: \\<open>0 < d\\<close> \\<open>y \\<in> Y\\<close>)\n  qed\n  moreover\n  let ?le = \"\\<lambda>x'. norm (f x' y - f x y - (fx) (x' - x)) \\<le> norm (x' - x) * e\"\n  from fx[unfolded has_derivative_within, THEN conjunct2, THEN tendstoD, OF \\<open>0 < e\\<close>]\n  have \"\\<forall>\\<^sub>F x' in at x within X. ?le x'\"\n    by eventually_elim (simp, \n      simp add: dist_norm field_split_simps split: if_split_asm)\n  then have \"\\<forall>\\<^sub>F (x', y') in at (x, y) within X \\<times> Y. ?le x'\"\n    by (rule eventually_at_Pair_within_TimesI1)\n       (simp add: blinfun.bilinear_simps)\n  moreover have \"\\<forall>\\<^sub>F (x', y') in at (x, y) within X \\<times> Y. norm ((x', y') - (x, y)) \\<noteq> 0\"\n    unfolding norm_eq_zero right_minus_eq\n    by (auto simp: eventually_at intro!: zero_less_one)\n  moreover\n  from fy_cont[THEN tendstoD, OF \\<open>0 < e\\<close>]\n  have \"\\<forall>\\<^sub>F x' in at x within X. norm (fy x' y - fy x y) < e\"\n    unfolding eventually_at\n    using \\<open>y \\<in> Y\\<close>\n    by (auto simp: dist_prod_def dist_norm)\n  then have \"\\<forall>\\<^sub>F (x', y') in at (x, y) within X \\<times> Y. norm (fy x' y - fy x y) < e\"\n    by (rule eventually_at_Pair_within_TimesI1)\n       (simp add: blinfun.bilinear_simps \\<open>0 < e\\<close>)\n  ultimately\n  have \"\\<forall>\\<^sub>F (x', y') in at (x, y) within X \\<times> Y.\n            norm ((f x' y' - f x y - (fx (x' - x) + fy x y (y' - y))) /\\<^sub>R\n              norm ((x', y') - (x, y)))\n            < e'\"\n  proof (eventually_elim, safe)\n    fix x' y'\n    have \"norm (f x' y' - f x y - (fx (x' - x) + fy x y (y' - y))) \\<le>\n        norm (f x' y' - f x' y - fy x' y (y' - y)) +\n        norm (fy x y (y' - y) - fy x' y (y' - y)) +\n        norm (f x' y - f x y - fx (x' - x))\"\n      by norm\n    also\n    assume nz: \"norm ((x', y') - (x, y)) \\<noteq> 0\"\n      and nfy: \"norm (fy x' y - fy x y) < e\"\n    assume \"norm (f x' y' - f x' y - blinfun_apply (fy x' y) (y' - y)) \\<le> norm (y' - y) * (e + e)\"\n    also assume \"norm (f x' y - f x y - (fx) (x' - x)) \\<le> norm (x' - x) * e\"\n    also\n    have \"norm ((fy x y) (y' - y) - (fy x' y) (y' - y)) \\<le> norm ((fy x y) - (fy x' y)) * norm (y' - y)\"\n      by (auto simp: blinfun.bilinear_simps[symmetric] intro!: norm_blinfun)\n    also have \"\\<dots> \\<le> (e + e) * norm (y' - y)\"\n      using \\<open>e > 0\\<close> nfy\n      by (auto simp: norm_minus_commute intro!: mult_right_mono)\n    also have \"norm (x' - x) * e \\<le> norm (x' - x) * (e + e)\"\n      using \\<open>0 < e\\<close> by simp\n    also have \"norm (y' - y) * (e + e) + (e + e) * norm (y' - y) + norm (x' - x) * (e + e) \\<le>\n        (norm (y' - y) + norm (x' - x)) * (4 * e)\"\n      using \\<open>e > 0\\<close>\n      by (simp add: algebra_simps)\n    also have \"\\<dots> \\<le> 2 * norm ((x', y') - (x, y)) * (4 * e)\"\n      using \\<open>0 < e\\<close> real_sqrt_sum_squares_ge1[of \"norm (x' - x)\" \"norm (y' - y)\"]\n        real_sqrt_sum_squares_ge2[of \"norm (y' - y)\" \"norm (x' - x)\"]\n      by (auto intro!: mult_right_mono simp: norm_prod_def\n        simp del: real_sqrt_sum_squares_ge1 real_sqrt_sum_squares_ge2)\n    also have \"\\<dots> \\<le> norm ((x', y') - (x, y)) * (8 * e)\"\n      by simp\n    also have \"\\<dots> < norm ((x', y') - (x, y)) * e'\"\n      using \\<open>0 < e'\\<close> nz\n      by (auto simp: e_def)\n    finally show \"norm ((f x' y' - f x y - (fx (x' - x) + fy x y (y' - y))) /\\<^sub>R norm ((x', y') - (x, y))) < e'\"\n      by (simp add: dist_norm) (auto simp add: field_split_simps)\n  qed\n  then show ?case\n    by eventually_elim (auto simp: dist_norm field_simps)\nnext\n  from has_derivative_bounded_linear[OF fx]\n  obtain fxb where \"fx = blinfun_apply fxb\"\n    by (metis bounded_linear_Blinfun_apply)\n  then show \"bounded_linear (\\<lambda>(tx, ty). fx tx + blinfun_apply (fy x y) ty)\"\n    by (auto intro!: bounded_linear_intros simp: split_beta')\nqed\n\n\nsubsection\\<^marker>\\<open>tag unimportant\\<close> \\<open>Differentiable case distinction\\<close>\n\nlemma has_derivative_within_If_eq:\n  \"((\\<lambda>x. if P x then f x else g x) has_derivative f') (at x within S) =\n    (bounded_linear f' \\<and>\n     ((\\<lambda>y.(if P y then (f y - ((if P x then f x else g x) + f' (y - x)))/\\<^sub>R norm (y - x)\n           else (g y - ((if P x then f x else g x) + f' (y - x)))/\\<^sub>R norm (y - x)))\n      \\<longlongrightarrow> 0) (at x within S))\"\n  (is \"_ = (_ \\<and> (?if \\<longlongrightarrow> 0) _)\")\nproof -\n  have \"(\\<lambda>y. (1 / norm (y - x)) *\\<^sub>R\n           ((if P y then f y else g y) -\n            ((if P x then f x else g x) + f' (y - x)))) = ?if\"\n    by (auto simp: inverse_eq_divide)\n  thus ?thesis by (auto simp: has_derivative_within)\nqed\n\nlemma has_derivative_If_within_closures:\n  assumes f': \"x \\<in> S \\<union> (closure S \\<inter> closure T) \\<Longrightarrow>\n    (f has_derivative f' 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 has_derivative g' x) (at x within T \\<union> (closure S \\<inter> closure T))\"\n  assumes connect: \"x \\<in> closure S \\<Longrightarrow> x \\<in> closure T \\<Longrightarrow> f x = g x\"\n  assumes connect': \"x \\<in> closure S \\<Longrightarrow> x \\<in> closure T \\<Longrightarrow> f' x = g' x\"\n  assumes x_in: \"x \\<in> S \\<union> T\"\n  shows \"((\\<lambda>x. if x \\<in> S then f x else g x) has_derivative\n      (if x \\<in> S then f' x else g' x)) (at x within (S \\<union> T))\"\nproof -\n  from f' x_in interpret f': bounded_linear \"if x \\<in> S then f' x else (\\<lambda>x. 0)\"\n    by (auto simp add: has_derivative_within)\n  from g' interpret g': bounded_linear \"if x \\<in> T then g' x else (\\<lambda>x. 0)\"\n    by (auto simp add: has_derivative_within)\n  have bl: \"bounded_linear (if x \\<in> S then f' x else g' x)\"\n    using f'.scaleR f'.bounded f'.add g'.scaleR g'.bounded g'.add x_in\n    by (unfold_locales; force)\n  show ?thesis\n    using f' g' closure_subset[of T] closure_subset[of S]\n    unfolding has_derivative_within_If_eq\n    by (intro conjI bl tendsto_If_within_closures x_in)\n      (auto simp: has_derivative_within inverse_eq_divide connect connect' subsetD)\nqed\n\nlemma has_vector_derivative_If_within_closures:\n  assumes x_in: \"x \\<in> S \\<union> T\"\n  assumes \"u = S \\<union> T\"\n  assumes f': \"x \\<in> S \\<union> (closure S \\<inter> closure T) \\<Longrightarrow>\n    (f has_vector_derivative f' 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 has_vector_derivative g' x) (at x within T \\<union> (closure S \\<inter> closure T))\"\n  assumes connect: \"x \\<in> closure S \\<Longrightarrow> x \\<in> closure T \\<Longrightarrow> f x = g x\"\n  assumes connect': \"x \\<in> closure S \\<Longrightarrow> x \\<in> closure T \\<Longrightarrow> f' x = g' x\"\n  shows \"((\\<lambda>x. if x \\<in> S then f x else g x) has_vector_derivative\n    (if x \\<in> S then f' x else g' x)) (at x within u)\"\n  unfolding has_vector_derivative_def assms\n  using x_in f' g'\n  by (intro has_derivative_If_within_closures[where ?f' = \"\\<lambda>x a. a *\\<^sub>R f' x\" and ?g' = \"\\<lambda>x a. a *\\<^sub>R g' x\",\n        THEN has_derivative_eq_rhs]; force simp: assms has_vector_derivative_def)\n\n\nsubsection\\<^marker>\\<open>tag important\\<close>\\<open>The Inverse Function Theorem\\<close>\n\nlemma linear_injective_contraction:\n  assumes \"linear f\" \"c < 1\" and le: \"\\<And>x. norm (f x - x) \\<le> c * norm x\"\n  shows \"inj f\"\n  unfolding linear_injective_0[OF \\<open>linear f\\<close>]\nproof safe\n  fix x\n  assume \"f x = 0\"\n  with le [of x] have \"norm x \\<le> c * norm x\"\n    by simp\n  then show \"x = 0\"\n    using \\<open>c < 1\\<close> by (simp add: mult_le_cancel_right1)\nqed\n\ntext\\<open>From an online proof by J. Michael Boardman, Department of Mathematics, Johns Hopkins University\\<close>\nlemma inverse_function_theorem_scaled:\n  fixes f::\"'a::euclidean_space \\<Rightarrow> 'a\"\n    and f'::\"'a \\<Rightarrow> ('a \\<Rightarrow>\\<^sub>L 'a)\"\n  assumes \"open U\"\n    and derf: \"\\<And>x. x \\<in> U \\<Longrightarrow> (f has_derivative blinfun_apply (f' x)) (at x)\"\n    and contf: \"continuous_on U f'\"\n    and \"0 \\<in> U\" and [simp]: \"f 0 = 0\"\n    and id: \"f' 0 = id_blinfun\"\n  obtains U' V g g' where \"open U'\" \"U' \\<subseteq> U\" \"0 \\<in> U'\" \"open V\" \"0 \\<in> V\" \"homeomorphism U' V f g\"\n                \"\\<And>y. y \\<in> V \\<Longrightarrow> (g has_derivative (g' y)) (at y)\"\n                \"\\<And>y. y \\<in> V \\<Longrightarrow> g' y = inv (blinfun_apply (f'(g y)))\"\n                \"\\<And>y. y \\<in> V \\<Longrightarrow> bij (blinfun_apply (f'(g y)))\"\nproof -\n  obtain d1 where \"cball 0 d1 \\<subseteq> U\" \"d1 > 0\"\n    using \\<open>open U\\<close> \\<open>0 \\<in> U\\<close> open_contains_cball by blast\n  obtain d2 where d2: \"\\<And>x. \\<lbrakk>x \\<in> U; dist x 0 \\<le> d2\\<rbrakk> \\<Longrightarrow> dist (f' x) (f' 0) < 1/2\" \"0 < d2\"\n    using continuous_onE [OF contf, of 0 \"1/2\"] by (metis \\<open>0 \\<in> U\\<close> half_gt_zero_iff zero_less_one)\n  obtain \\<delta> where le: \"\\<And>x. norm x \\<le> \\<delta> \\<Longrightarrow> dist (f' x) id_blinfun \\<le> 1/2\" and \"0 < \\<delta>\"\n    and subU: \"cball 0 \\<delta> \\<subseteq> U\"\n  proof\n    show \"min d1 d2 > 0\"\n      by (simp add: \\<open>0 < d1\\<close> \\<open>0 < d2\\<close>)\n    show \"cball 0 (min d1 d2) \\<subseteq> U\"\n      using \\<open>cball 0 d1 \\<subseteq> U\\<close> by auto\n    show \"dist (f' x) id_blinfun \\<le> 1/2\" if \"norm x \\<le> min d1 d2\" for x\n      using \\<open>cball 0 d1 \\<subseteq> U\\<close> d2 that id by fastforce\n  qed\n  let ?D = \"cball 0 \\<delta>\"\n  define V:: \"'a set\" where \"V \\<equiv> ball 0 (\\<delta>/2)\"\n  have 4: \"norm (f (x + h) - f x - h) \\<le> 1/2 * norm h\"\n    if \"x \\<in> ?D\" \"x+h \\<in> ?D\" for x h\n  proof -\n    let ?w = \"\\<lambda>x. f x - x\"\n    have B: \"\\<And>x. x \\<in> ?D \\<Longrightarrow> onorm (blinfun_apply (f' x - id_blinfun)) \\<le> 1/2\"\n      by (metis dist_norm le mem_cball_0 norm_blinfun.rep_eq)\n    have \"\\<And>x. x \\<in> ?D \\<Longrightarrow> (?w has_derivative (blinfun_apply (f' x - id_blinfun))) (at x)\"\n      by (rule derivative_eq_intros derf subsetD [OF subU] | force simp: blinfun.diff_left)+\n    then have Dw: \"\\<And>x. x \\<in> ?D \\<Longrightarrow> (?w has_derivative (blinfun_apply (f' x - id_blinfun))) (at x within ?D)\"\n      using has_derivative_at_withinI by blast\n    have \"norm (?w (x+h) - ?w x) \\<le> (1/2) * norm h\"\n      using differentiable_bound [OF convex_cball Dw B] that by fastforce\n    then show ?thesis\n      by (auto simp: algebra_simps)\n  qed\n  have for_g: \"\\<exists>!x. norm x < \\<delta> \\<and> f x = y\" if y: \"norm y < \\<delta>/2\" for y\n  proof -\n    let ?u = \"\\<lambda>x. x + (y - f x)\"\n    have *: \"norm (?u x) < \\<delta>\" if \"x \\<in> ?D\" for x\n    proof -\n      have fxx: \"norm (f x - x) \\<le> \\<delta>/2\"\n        using 4 [of 0 x] \\<open>0 < \\<delta>\\<close> \\<open>f 0 = 0\\<close> that by auto\n      have \"norm (?u x) \\<le> norm y + norm (f x - x)\"\n        by (metis add.commute add_diff_eq norm_minus_commute norm_triangle_ineq)\n      also have \"\\<dots> < \\<delta>/2 + \\<delta>/2\"\n        using fxx y by auto\n      finally show ?thesis\n        by simp\n    qed\n    have \"\\<exists>!x \\<in> ?D. ?u x = x\"\n    proof (rule banach_fix)\n      show \"cball 0 \\<delta> \\<noteq> {}\"\n        using \\<open>0 < \\<delta>\\<close> by auto\n      show \"(\\<lambda>x. x + (y - f x)) ` cball 0 \\<delta> \\<subseteq> cball 0 \\<delta>\"\n        using * by force\n      have \"dist (x + (y - f x)) (xh + (y - f xh)) * 2 \\<le> dist x xh\"\n        if \"norm x \\<le> \\<delta>\" and \"norm xh \\<le> \\<delta>\" for x xh\n        using that 4 [of x \"xh-x\"] by (auto simp: dist_norm norm_minus_commute algebra_simps)\n      then show \"\\<forall>x\\<in>cball 0 \\<delta>. \\<forall>ya\\<in>cball 0 \\<delta>. dist (x + (y - f x)) (ya + (y - f ya)) \\<le> (1/2) * dist x ya\"\n        by auto\n    qed (auto simp: complete_eq_closed)\n    then show ?thesis\n      by (metis \"*\" add_cancel_right_right eq_iff_diff_eq_0 le_less mem_cball_0)\n  qed\n  define g where \"g \\<equiv> \\<lambda>y. THE x. norm x < \\<delta> \\<and> f x = y\"\n  have g: \"norm (g y) < \\<delta> \\<and> f (g y) = y\" if \"norm y < \\<delta>/2\" for y\n    unfolding g_def using that theI' [OF for_g] by meson\n  then have fg[simp]: \"f (g y) = y\" if \"y \\<in> V\" for y\n    using that by (auto simp: V_def)\n  have 5: \"norm (g y' - g y) \\<le> 2 * norm (y' - y)\" if \"y \\<in> V\" \"y' \\<in> V\" for y y'\n  proof -\n    have no: \"norm (g y) \\<le> \\<delta>\" \"norm (g y') \\<le> \\<delta>\" and [simp]: \"f (g y) = y\"\n      using that g unfolding V_def by force+\n    have \"norm (g y' - g y) \\<le> norm (g y' - g y - (y' - y)) + norm (y' - y)\"\n      by (simp add: add.commute norm_triangle_sub)\n    also have \"\\<dots> \\<le> (1/2) * norm (g y' - g y) + norm (y' - y)\"\n      using 4 [of \"g y\" \"g y' - g y\"] that no by (simp add: g norm_minus_commute V_def)\n    finally show ?thesis\n      by auto\n  qed\n  have contg: \"continuous_on V g\"\n  proof\n    fix y::'a and e::real\n    assume \"0 < e\" and y: \"y \\<in> V\"\n    show \"\\<exists>d>0. \\<forall>x'\\<in>V. dist x' y < d \\<longrightarrow> dist (g x') (g y) \\<le> e\"\n    proof (intro exI conjI ballI impI)\n      show \"0 < e/2\"\n        by (simp add: \\<open>0 < e\\<close>)\n    qed (use 5 y in \\<open>force simp: dist_norm\\<close>)\n  qed\n  show thesis\n  proof\n    define U' where \"U' \\<equiv> (f -` V) \\<inter> ball 0 \\<delta>\"\n    have contf: \"continuous_on U f\"\n      using derf has_derivative_at_withinI by (fast intro: has_derivative_continuous_on)\n    then have \"continuous_on (ball 0 \\<delta>) f\"\n      by (meson ball_subset_cball continuous_on_subset subU)\n    then show \"open U'\"\n      by (simp add: U'_def V_def Int_commute continuous_open_preimage)\n    show \"0 \\<in> U'\" \"U' \\<subseteq> U\" \"open V\" \"0 \\<in> V\"\n      using \\<open>0 < \\<delta>\\<close> subU by (auto simp: U'_def V_def)\n    show hom: \"homeomorphism U' V f g\"\n    proof\n      show \"continuous_on U' f\"\n        using \\<open>U' \\<subseteq> U\\<close> contf continuous_on_subset by blast\n      show \"continuous_on V g\"\n        using contg by blast\n      show \"f ` U' \\<subseteq> V\"\n        using U'_def by blast\n      show \"g ` V \\<subseteq> U'\"\n        by (simp add: U'_def V_def g image_subset_iff)\n      show \"g (f x) = x\" if \"x \\<in> U'\" for x\n        by (metis that fg Int_iff U'_def V_def for_g g mem_ball_0 vimage_eq)\n      show \"f (g y) = y\" if \"y \\<in> V\" for y\n        using that by (simp add: g V_def)\n    qed\n    show bij: \"bij (blinfun_apply (f'(g y)))\" if \"y \\<in> V\" for y\n    proof -\n      have inj: \"inj (blinfun_apply (f' (g y)))\"\n      proof (rule linear_injective_contraction)\n        show \"linear (blinfun_apply (f' (g y)))\"\n          using blinfun.bounded_linear_right bounded_linear_def by blast\n      next\n        fix x\n        have \"norm (blinfun_apply (f' (g y)) x - x) = norm (blinfun_apply (f' (g y) - id_blinfun) x)\"\n          by (simp add: blinfun.diff_left)\n        also have \"\\<dots> \\<le> norm (f' (g y) - id_blinfun) * norm x\"\n          by (rule norm_blinfun)\n        also have \"\\<dots> \\<le> (1/2) * norm x\"\n        proof (rule mult_right_mono)\n          show \"norm (f' (g y) - id_blinfun) \\<le> 1/2\"\n            using that g [of y] le by (auto simp: V_def dist_norm)\n        qed auto\n        finally show \"norm (blinfun_apply (f' (g y)) x - x) \\<le> (1/2) * norm x\" .\n      qed auto\n      moreover\n      have \"surj (blinfun_apply (f' (g y)))\"\n        using blinfun.bounded_linear_right bounded_linear_def\n        by (blast intro!: linear_inj_imp_surj [OF _ inj])\n      ultimately show ?thesis\n        using bijI by blast\n    qed\n    define g' where \"g' \\<equiv> \\<lambda>y. inv (blinfun_apply (f'(g y)))\"\n    show \"(g has_derivative g' y) (at y)\" if \"y \\<in> V\" for y\n    proof -\n      have gy: \"g y \\<in> U\"\n        using g subU that unfolding V_def by fastforce\n      obtain e where e: \"\\<And>h. f (g y + h) = y + blinfun_apply (f' (g y)) h + e h\"\n        and e0: \"(\\<lambda>h. norm (e h) / norm h) \\<midarrow>0\\<rightarrow> 0\"\n        using iffD1 [OF has_derivative_iff_Ex derf [OF gy]] \\<open>y \\<in> V\\<close> by auto\n      have [simp]: \"e 0 = 0\"\n        using e [of 0] that by simp\n      let ?INV = \"inv (blinfun_apply (f' (g y)))\"\n      have inj: \"inj (blinfun_apply (f' (g y)))\"\n        using bij bij_betw_def that by blast\n      have \"(g has_derivative g' y) (at y within V)\"\n        unfolding has_derivative_at_within_iff_Ex [OF \\<open>y \\<in> V\\<close> \\<open>open V\\<close>]\n      proof\n        show blinv: \"bounded_linear (g' y)\"\n          unfolding g'_def using derf gy inj inj_linear_imp_inv_bounded_linear by blast\n        define eg where \"eg \\<equiv> \\<lambda>k. - ?INV (e (g (y+k) - g y))\"\n        have \"g (y+k) = g y + g' y k + eg k\" if \"y + k \\<in> V\" for k\n        proof -\n          have \"?INV k = ?INV (blinfun_apply (f' (g y)) (g (y+k) - g y) + e (g (y+k) - g y))\"\n            using e [of \"g(y+k) - g y\"] that by simp\n          then have \"g (y+k) = g y + ?INV k - ?INV (e (g (y+k) - g y))\"\n            using inj blinv by (simp add: linear_simps g'_def)\n          then show ?thesis\n            by (auto simp: eg_def g'_def)\n        qed\n        moreover have \"(\\<lambda>k. norm (eg k) / norm k) \\<midarrow>0\\<rightarrow> 0\"\n        proof (rule Lim_null_comparison)\n          let ?g = \"\\<lambda>k. 2 * onorm ?INV * norm (e (g (y+k) - g y)) / norm (g (y+k) - g y)\"\n          show \"\\<forall>\\<^sub>F k in at 0. norm (norm (eg k) / norm k) \\<le> ?g k\"\n            unfolding eventually_at_topological\n          proof (intro exI conjI ballI impI)\n            show \"open ((+)(-y) ` V)\"\n              using \\<open>open V\\<close> open_translation by blast\n            show \"0 \\<in> (+)(-y) ` V\"\n              by (simp add: that)\n            show \"norm (norm (eg k) / norm k) \\<le> 2 * onorm (inv (blinfun_apply (f' (g y)))) * norm (e (g (y+k) - g y)) / norm (g (y+k) - g y)\"\n              if \"k \\<in> (+)(-y) ` V\" \"k \\<noteq> 0\" for k\n            proof -\n              have \"y+k \\<in> V\"\n                using that by auto\n              have \"norm (norm (eg k) / norm k) \\<le> onorm ?INV * norm (e (g (y+k) - g y)) / norm k\"\n                using blinv g'_def onorm by (force simp: eg_def divide_simps)\n              also have \"\\<dots> = (norm (g (y+k) - g y) / norm k) * (onorm ?INV * (norm (e (g (y+k) - g y)) / norm (g (y+k) - g y)))\"\n                by (simp add: divide_simps)\n              also have \"\\<dots> \\<le> 2 * (onorm ?INV * (norm (e (g (y+k) - g y)) / norm (g (y+k) - g y)))\"\n                apply (rule mult_right_mono)\n                using 5 [of y \"y+k\"] \\<open>y \\<in> V\\<close> \\<open>y + k \\<in> V\\<close>  onorm_pos_le [OF blinv]\n                 apply (auto simp: divide_simps zero_le_mult_iff zero_le_divide_iff g'_def)\n                done\n              finally show \"norm (norm (eg k) / norm k) \\<le> 2 * onorm ?INV * norm (e (g (y+k) - g y)) / norm (g (y+k) - g y)\"\n                by simp\n            qed\n          qed\n          have 1: \"(\\<lambda>h. norm (e h) / norm h) \\<midarrow>0\\<rightarrow> (norm (e 0) / norm 0)\"\n            using e0 by auto\n          have 2: \"(\\<lambda>k. g (y+k) - g y) \\<midarrow>0\\<rightarrow> 0\"\n            using contg \\<open>open V\\<close> \\<open>y \\<in> V\\<close> LIM_offset_zero_iff LIM_zero_iff at_within_open continuous_on_def by fastforce\n          from tendsto_compose [OF 1 2, simplified]\n          have \"(\\<lambda>k. norm (e (g (y+k) - g y)) / norm (g (y+k) - g y)) \\<midarrow>0\\<rightarrow> 0\" .\n          from tendsto_mult_left [OF this] show \"?g \\<midarrow>0\\<rightarrow> 0\" by auto\n        qed\n        ultimately show \"\\<exists>e. (\\<forall>k. y + k \\<in> V \\<longrightarrow> g (y+k) = g y + g' y k + e k) \\<and> (\\<lambda>k. norm (e k) / norm k) \\<midarrow>0\\<rightarrow> 0\"\n          by blast\n      qed\n      then show ?thesis\n        by (metis \\<open>open V\\<close> at_within_open that)\n    qed\n    show \"g' y = inv (blinfun_apply (f' (g y)))\"\n      if \"y \\<in> V\" for y\n      by (simp add: g'_def)\n  qed\nqed\n\n\ntext\\<open>We need all this to justify the scaling and translations.\\<close>\ntheorem inverse_function_theorem:\n  fixes f::\"'a::euclidean_space \\<Rightarrow> 'a\"\n    and f'::\"'a \\<Rightarrow> ('a \\<Rightarrow>\\<^sub>L 'a)\"\n  assumes \"open U\"\n    and derf: \"\\<And>x. x \\<in> U \\<Longrightarrow> (f has_derivative (blinfun_apply (f' x))) (at x)\"\n    and contf:  \"continuous_on U f'\"\n    and \"x0 \\<in> U\"\n    and invf: \"invf o\\<^sub>L f' x0 = id_blinfun\"\n  obtains U' V g g' where \"open U'\" \"U' \\<subseteq> U\" \"x0 \\<in> U'\" \"open V\" \"f x0 \\<in> V\" \"homeomorphism U' V f g\"\n    \"\\<And>y. y \\<in> V \\<Longrightarrow> (g has_derivative (g' y)) (at y)\"\n    \"\\<And>y. y \\<in> V \\<Longrightarrow> g' y = inv (blinfun_apply (f'(g y)))\"\n    \"\\<And>y. y \\<in> V \\<Longrightarrow> bij (blinfun_apply (f'(g y)))\"\nproof -\n  have apply1 [simp]: \"\\<And>i. blinfun_apply invf (blinfun_apply (f' x0) i) = i\"\n    by (metis blinfun_apply_blinfun_compose blinfun_apply_id_blinfun invf)\n  have apply2 [simp]: \"\\<And>i. blinfun_apply (f' x0) (blinfun_apply invf i) = i\"\n    by (metis apply1 bij_inv_eq_iff blinfun_bij1 invf)\n  have [simp]: \"(range (blinfun_apply invf)) = UNIV\"\n    using apply1 surjI by blast\n  let ?f = \"invf \\<circ> (\\<lambda>x. (f \\<circ> (+)x0)x - f x0)\"\n  let ?f' = \"\\<lambda>x. invf o\\<^sub>L (f' (x + x0))\"\n  obtain U' V g g' where \"open U'\" and U': \"U' \\<subseteq> (+)(-x0) ` U\" \"0 \\<in> U'\"\n    and \"open V\" \"0 \\<in> V\" and hom: \"homeomorphism U' V ?f g\"\n    and derg: \"\\<And>y. y \\<in> V \\<Longrightarrow> (g has_derivative (g' y)) (at y)\"\n    and g': \"\\<And>y. y \\<in> V \\<Longrightarrow> g' y = inv (?f'(g y))\"\n    and bij: \"\\<And>y. y \\<in> V \\<Longrightarrow> bij (?f'(g y))\"\n  proof (rule inverse_function_theorem_scaled [of \"(+)(-x0) ` U\" ?f \"?f'\"])\n    show ope: \"open ((+) (- x0) ` U)\"\n      using \\<open>open U\\<close> open_translation by blast\n    show \"(?f has_derivative blinfun_apply (?f' x)) (at x)\"\n      if \"x \\<in> (+) (- x0) ` U\" for x\n      using that\n      apply clarify\n      apply (rule derf derivative_eq_intros | simp add: blinfun_compose.rep_eq)+\n      done\n    have YY: \"(\\<lambda>x. f' (x + x0)) \\<midarrow>u-x0\\<rightarrow> f' u\"\n      if \"f' \\<midarrow>u\\<rightarrow> f' u\" \"u \\<in> U\" for u\n      using that LIM_offset [where k = x0] by (auto simp: algebra_simps)\n    then have \"continuous_on ((+) (- x0) ` U) (\\<lambda>x. f' (x + x0))\"\n      using contf \\<open>open U\\<close> Lim_at_imp_Lim_at_within\n      by (fastforce simp: continuous_on_def at_within_open_NO_MATCH ope)\n    then show \"continuous_on ((+) (- x0) ` U) ?f'\"\n      by (intro continuous_intros) simp\n  qed (auto simp: invf \\<open>x0 \\<in> U\\<close>)\n  show thesis\n  proof\n    let ?U' = \"(+)x0 ` U'\"\n    let ?V = \"((+)(f x0) \\<circ> f' x0) ` V\"\n    let ?g = \"(+)x0 \\<circ> g \\<circ> invf \\<circ> (+)(- f x0)\"\n    let ?g' = \"\\<lambda>y. inv (blinfun_apply (f' (?g y)))\"\n    show oU': \"open ?U'\"\n      by (simp add: \\<open>open U'\\<close> open_translation)\n    show subU: \"?U' \\<subseteq> U\"\n      using ComplI \\<open>U' \\<subseteq> (+) (- x0) ` U\\<close> by auto\n    show \"x0 \\<in> ?U'\"\n      by (simp add: \\<open>0 \\<in> U'\\<close>)\n    show \"open ?V\"\n      using blinfun_bij2 [OF invf]\n      by (metis \\<open>open V\\<close> bij_is_surj blinfun.bounded_linear_right bounded_linear_def image_comp open_surjective_linear_image open_translation)\n    show \"f x0 \\<in> ?V\"\n      using \\<open>0 \\<in> V\\<close> image_iff by fastforce\n    show \"homeomorphism ?U' ?V f ?g\"\n    proof\n      show \"continuous_on ?U' f\"\n        by (meson subU continuous_on_eq_continuous_at derf has_derivative_continuous oU' subsetD)\n      have \"?f ` U' \\<subseteq> V\"\n        using hom homeomorphism_image1 by blast\n      then show \"f ` ?U' \\<subseteq> ?V\"\n        unfolding image_subset_iff\n        by (clarsimp simp: image_def) (metis apply2 add.commute diff_add_cancel)\n      show \"?g ` ?V \\<subseteq> ?U'\"\n        using hom invf by (auto simp: image_def homeomorphism_def)\n      show \"?g (f x) = x\"\n        if \"x \\<in> ?U'\" for x\n        using that hom homeomorphism_apply1 by fastforce\n      have \"continuous_on V g\"\n        using hom homeomorphism_def by blast\n      then show \"continuous_on ?V ?g\"\n        by (intro continuous_intros) (auto elim!: continuous_on_subset)\n      have fg: \"?f (g x) = x\" if \"x \\<in> V\" for x\n        using hom homeomorphism_apply2 that by blast\n      show \"f (?g y) = y\"\n        if \"y \\<in> ?V\" for y\n        using that fg by (simp add: image_iff) (metis apply2 add.commute diff_add_cancel)\n    qed\n    show \"(?g has_derivative ?g' y) (at y)\" \"bij (blinfun_apply (f' (?g y)))\"\n      if \"y \\<in> ?V\" for y\n    proof -\n      have 1: \"bij (blinfun_apply invf)\"\n        using blinfun_bij1 invf by blast\n      then have 2: \"bij (blinfun_apply (f' (x0 + g x)))\" if \"x \\<in> V\" for x\n        by (metis add.commute bij bij_betw_comp_iff2 blinfun_compose.rep_eq that top_greatest)\n      then show \"bij (blinfun_apply (f' (?g y)))\"\n        using that by auto\n      have \"g' x \\<circ> blinfun_apply invf = inv (blinfun_apply (f' (x0 + g x)))\"\n        if \"x \\<in> V\" for x\n        using that\n        by (simp add: g' o_inv_distrib blinfun_compose.rep_eq 1 2 add.commute bij_is_inj flip: o_assoc)\n      then show \"(?g has_derivative ?g' y) (at y)\"\n        using that invf\n        by clarsimp (rule derg derivative_eq_intros | simp flip: id_def)+\n    qed\n  qed auto\nqed\n\n\nsubsection\\<^marker>\\<open>tag unimportant\\<close> \\<open>Piecewise differentiable functions\\<close>\n\ndefinition piecewise_differentiable_on\n           (infixr \"piecewise'_differentiable'_on\" 50)\n  where \"f piecewise_differentiable_on i  \\<equiv>\n           continuous_on i f \\<and>\n           (\\<exists>S. finite S \\<and> (\\<forall>x \\<in> i - S. f differentiable (at x within i)))\"\n\nlemma piecewise_differentiable_on_imp_continuous_on:\n    \"f piecewise_differentiable_on S \\<Longrightarrow> continuous_on S f\"\nby (simp add: piecewise_differentiable_on_def)\n\nlemma piecewise_differentiable_on_subset:\n    \"f piecewise_differentiable_on S \\<Longrightarrow> T \\<le> S \\<Longrightarrow> f piecewise_differentiable_on T\"\n  using continuous_on_subset\n  by (smt (verit) Diff_iff differentiable_within_subset in_mono piecewise_differentiable_on_def)\n\nlemma differentiable_on_imp_piecewise_differentiable:\n  fixes a:: \"'a::{linorder_topology,real_normed_vector}\"\n  shows \"f differentiable_on {a..b} \\<Longrightarrow> f piecewise_differentiable_on {a..b}\"\n  using differentiable_imp_continuous_on differentiable_onD piecewise_differentiable_on_def by fastforce\n\nlemma differentiable_imp_piecewise_differentiable:\n    \"(\\<And>x. x \\<in> S \\<Longrightarrow> f differentiable (at x within S))\n         \\<Longrightarrow> f piecewise_differentiable_on S\"\nby (auto simp: piecewise_differentiable_on_def differentiable_imp_continuous_on differentiable_on_def\n         intro: differentiable_within_subset)\n\nlemma piecewise_differentiable_const [iff]: \"(\\<lambda>x. z) piecewise_differentiable_on S\"\n  by (simp add: differentiable_imp_piecewise_differentiable)\n\nlemma piecewise_differentiable_compose:\n    \"\\<lbrakk>f piecewise_differentiable_on S; g piecewise_differentiable_on (f ` S);\n      \\<And>x. finite (S \\<inter> f-`{x})\\<rbrakk>\n      \\<Longrightarrow> (g \\<circ> f) piecewise_differentiable_on S\"\n  apply (simp add: piecewise_differentiable_on_def, safe)\n  apply (blast intro: continuous_on_compose2)\n  apply (rename_tac A B)\n  apply (rule_tac x=\"A \\<union> (\\<Union>x\\<in>B. S \\<inter> f-`{x})\" in exI)\n  apply (blast intro!: differentiable_chain_within)\n  done\n\nlemma piecewise_differentiable_affine:\n  fixes m::real\n  assumes \"f piecewise_differentiable_on ((\\<lambda>x. m *\\<^sub>R x + c) ` S)\"\n  shows \"(f \\<circ> (\\<lambda>x. m *\\<^sub>R x + c)) piecewise_differentiable_on S\"\nproof (cases \"m = 0\")\n  case True\n  then show ?thesis\n    unfolding o_def\n    by (force intro: differentiable_imp_piecewise_differentiable differentiable_const)\nnext\n  case False\n  show ?thesis\n    apply (rule piecewise_differentiable_compose [OF differentiable_imp_piecewise_differentiable])\n    apply (rule assms derivative_intros | simp add: False vimage_def real_vector_affinity_eq)+\n    done\nqed\n\nlemma piecewise_differentiable_cases:\n  fixes c::real\n  assumes \"f piecewise_differentiable_on {a..c}\"\n          \"g piecewise_differentiable_on {c..b}\"\n           \"a \\<le> c\" \"c \\<le> b\" \"f c = g c\"\n  shows \"(\\<lambda>x. if x \\<le> c then f x else g x) piecewise_differentiable_on {a..b}\"\nproof -\n  obtain S T where st: \"finite S\" \"finite T\"\n               and fd: \"\\<And>x. x \\<in> {a..c} - S \\<Longrightarrow> f differentiable at x within {a..c}\"\n               and gd: \"\\<And>x. x \\<in> {c..b} - T \\<Longrightarrow> g differentiable at x within {c..b}\"\n    using assms\n    by (auto simp: piecewise_differentiable_on_def)\n  have finabc: \"finite ({a,b,c} \\<union> (S \\<union> T))\"\n    by (metis \\<open>finite S\\<close> \\<open>finite T\\<close> finite_Un finite_insert finite.emptyI)\n  have \"continuous_on {a..c} f\" \"continuous_on {c..b} g\"\n    using assms piecewise_differentiable_on_def by auto\n  then have \"continuous_on {a..b} (\\<lambda>x. if x \\<le> c then f x else g x)\"\n    using continuous_on_cases [OF closed_real_atLeastAtMost [of a c],\n                               OF closed_real_atLeastAtMost [of c b],\n                               of f g \"\\<lambda>x. x\\<le>c\"]  assms\n    by (force simp: ivl_disj_un_two_touch)\n  moreover\n  { fix x\n    assume x: \"x \\<in> {a..b} - ({a,b,c} \\<union> (S \\<union> T))\"\n    have \"(\\<lambda>x. if x \\<le> c then f x else g x) differentiable at x within {a..b}\" (is \"?diff_fg\")\n    proof (cases x c rule: le_cases)\n      case le show ?diff_fg\n      proof (rule differentiable_transform_within [where d = \"dist x c\"])\n        have \"f differentiable at x\"\n          using x le fd [of x] at_within_interior [of x \"{a..c}\"] by simp\n        then show \"f differentiable at x within {a..b}\"\n          by (simp add: differentiable_at_withinI)\n      qed (use x le st dist_real_def in auto)\n    next\n      case ge show ?diff_fg\n      proof (rule differentiable_transform_within [where d = \"dist x c\"])\n        have \"g differentiable at x\"\n          using x ge gd [of x] at_within_interior [of x \"{c..b}\"] by simp\n        then show \"g differentiable at x within {a..b}\"\n          by (simp add: differentiable_at_withinI)\n      qed (use x ge st dist_real_def in auto)\n    qed\n  }\n  then have \"\\<exists>S. finite S \\<and>\n                 (\\<forall>x\\<in>{a..b} - S. (\\<lambda>x. if x \\<le> c then f x else g x) differentiable at x within {a..b})\"\n    by (meson finabc)\n  ultimately show ?thesis\n    by (simp add: piecewise_differentiable_on_def)\nqed\n\nlemma piecewise_differentiable_neg:\n    \"f piecewise_differentiable_on S \\<Longrightarrow> (\\<lambda>x. -(f x)) piecewise_differentiable_on S\"\n  by (auto simp: piecewise_differentiable_on_def continuous_on_minus)\n\nlemma piecewise_differentiable_add:\n  assumes \"f piecewise_differentiable_on i\"\n          \"g piecewise_differentiable_on i\"\n    shows \"(\\<lambda>x. f x + g x) piecewise_differentiable_on i\"\nproof -\n  obtain S T where st: \"finite S\" \"finite T\"\n                       \"\\<forall>x\\<in>i - S. f differentiable at x within i\"\n                       \"\\<forall>x\\<in>i - T. g differentiable at x within i\"\n    using assms by (auto simp: piecewise_differentiable_on_def)\n  then have \"finite (S \\<union> T) \\<and> (\\<forall>x\\<in>i - (S \\<union> T). (\\<lambda>x. f x + g x) differentiable at x within i)\"\n    by auto\n  moreover have \"continuous_on i f\" \"continuous_on i g\"\n    using assms piecewise_differentiable_on_def by auto\n  ultimately show ?thesis\n    by (auto simp: piecewise_differentiable_on_def continuous_on_add)\nqed\n\nlemma piecewise_differentiable_diff:\n    \"\\<lbrakk>f piecewise_differentiable_on S;  g piecewise_differentiable_on S\\<rbrakk>\n     \\<Longrightarrow> (\\<lambda>x. f x - g x) piecewise_differentiable_on S\"\n  unfolding diff_conv_add_uminus\n  by (metis piecewise_differentiable_add piecewise_differentiable_neg)\n\n\nsubsection\\<open>The concept of continuously differentiable\\<close>\n\ntext \\<open>\nJohn Harrison writes as follows:\n\n``The usual assumption in complex analysis texts is that a path \\<open>\\<gamma>\\<close> should be piecewise\ncontinuously differentiable, which ensures that the path integral exists at least for any continuous\nf, since all piecewise continuous functions are integrable. However, our notion of validity is\nweaker, just piecewise differentiability\\ldots{} [namely] continuity plus differentiability except on a\nfinite set\\ldots{} [Our] underlying theory of integration is the Kurzweil-Henstock theory. In contrast to\nthe Riemann or Lebesgue theory (but in common with a simple notion based on antiderivatives), this\ncan integrate all derivatives.''\n\n\"Formalizing basic complex analysis.\" From Insight to Proof: Festschrift in Honour of Andrzej Trybulec.\nStudies in Logic, Grammar and Rhetoric 10.23 (2007): 151-165.\n\nAnd indeed he does not assume that his derivatives are continuous, but the penalty is unreasonably\ndifficult proofs concerning winding numbers. We need a self-contained and straightforward theorem\nasserting that all derivatives can be integrated before we can adopt Harrison's choice.\\<close>\n\ndefinition\\<^marker>\\<open>tag important\\<close> C1_differentiable_on :: \"(real \\<Rightarrow> 'a::real_normed_vector) \\<Rightarrow> real set \\<Rightarrow> bool\"\n           (infix \"C1'_differentiable'_on\" 50)\n  where\n  \"f C1_differentiable_on S \\<longleftrightarrow>\n   (\\<exists>D. (\\<forall>x \\<in> S. (f has_vector_derivative (D x)) (at x)) \\<and> continuous_on S D)\"\n\nlemma C1_differentiable_on_eq:\n    \"f C1_differentiable_on S \\<longleftrightarrow>\n     (\\<forall>x \\<in> S. f differentiable at x) \\<and> continuous_on S (\\<lambda>x. vector_derivative f (at x))\"\n     (is \"?lhs = ?rhs\")\nproof\n  assume ?lhs\n  then show ?rhs\n    unfolding C1_differentiable_on_def\n    by (metis (no_types, lifting) continuous_on_eq  differentiableI_vector vector_derivative_at)\nnext\n  assume ?rhs\n  then show ?lhs\n    using C1_differentiable_on_def vector_derivative_works by fastforce\nqed\n\nlemma C1_differentiable_on_subset:\n  \"f C1_differentiable_on T \\<Longrightarrow> S \\<subseteq> T \\<Longrightarrow> f C1_differentiable_on S\"\n  unfolding C1_differentiable_on_def  continuous_on_eq_continuous_within\n  by (blast intro:  continuous_within_subset)\n\nlemma C1_differentiable_compose:\n  assumes fg: \"f C1_differentiable_on S\" \"g C1_differentiable_on (f ` S)\" and fin: \"\\<And>x. finite (S \\<inter> f-`{x})\"\n  shows \"(g \\<circ> f) C1_differentiable_on S\"\nproof -\n  have \"\\<And>x. x \\<in> S \\<Longrightarrow> g \\<circ> f differentiable at x\"\n    by (meson C1_differentiable_on_eq assms differentiable_chain_at imageI)\n  moreover have \"continuous_on S (\\<lambda>x. vector_derivative (g \\<circ> f) (at x))\"\n  proof (rule continuous_on_eq [of _ \"\\<lambda>x. vector_derivative f (at x) *\\<^sub>R vector_derivative g (at (f x))\"])\n    show \"continuous_on S (\\<lambda>x. vector_derivative f (at x) *\\<^sub>R vector_derivative g (at (f x)))\"\n      using fg\n      apply (clarsimp simp add: C1_differentiable_on_eq)\n      apply (rule Limits.continuous_on_scaleR, assumption)\n      by (metis (mono_tags, lifting) continuous_at_imp_continuous_on continuous_on_compose continuous_on_cong differentiable_imp_continuous_within o_def)\n    show \"\\<And>x. x \\<in> S \\<Longrightarrow> vector_derivative f (at x) *\\<^sub>R vector_derivative g (at (f x)) = vector_derivative (g \\<circ> f) (at x)\"\n      by (metis (mono_tags, opaque_lifting) C1_differentiable_on_eq fg imageI vector_derivative_chain_at)\n  qed\n  ultimately show ?thesis\n    by (simp add: C1_differentiable_on_eq)\nqed\n\nlemma C1_diff_imp_diff: \"f C1_differentiable_on S \\<Longrightarrow> f differentiable_on S\"\n  by (simp add: C1_differentiable_on_eq differentiable_at_imp_differentiable_on)\n\nlemma C1_differentiable_on_ident [simp, derivative_intros]: \"(\\<lambda>x. x) C1_differentiable_on S\"\n  by (auto simp: C1_differentiable_on_eq)\n\nlemma C1_differentiable_on_const [simp, derivative_intros]: \"(\\<lambda>z. a) C1_differentiable_on S\"\n  by (auto simp: C1_differentiable_on_eq)\n\nlemma C1_differentiable_on_add [simp, derivative_intros]:\n  \"f C1_differentiable_on S \\<Longrightarrow> g C1_differentiable_on S \\<Longrightarrow> (\\<lambda>x. f x + g x) C1_differentiable_on S\"\n  unfolding C1_differentiable_on_eq  by (auto intro: continuous_intros)\n\nlemma C1_differentiable_on_minus [simp, derivative_intros]:\n  \"f C1_differentiable_on S \\<Longrightarrow> (\\<lambda>x. - f x) C1_differentiable_on S\"\n  unfolding C1_differentiable_on_eq  by (auto intro: continuous_intros)\n\nlemma C1_differentiable_on_diff [simp, derivative_intros]:\n  \"f C1_differentiable_on S \\<Longrightarrow> g C1_differentiable_on S \\<Longrightarrow> (\\<lambda>x. f x - g x) C1_differentiable_on S\"\n  unfolding C1_differentiable_on_eq  by (auto intro: continuous_intros)\n\nlemma C1_differentiable_on_mult [simp, derivative_intros]:\n  fixes f g :: \"real \\<Rightarrow> 'a :: real_normed_algebra\"\n  shows \"f C1_differentiable_on S \\<Longrightarrow> g C1_differentiable_on S \\<Longrightarrow> (\\<lambda>x. f x * g x) C1_differentiable_on S\"\n  unfolding C1_differentiable_on_eq\n  by (auto simp: continuous_on_add continuous_on_mult continuous_at_imp_continuous_on differentiable_imp_continuous_within)\n\nlemma C1_differentiable_on_scaleR [simp, derivative_intros]:\n  \"f C1_differentiable_on S \\<Longrightarrow> g C1_differentiable_on S \\<Longrightarrow> (\\<lambda>x. f x *\\<^sub>R g x) C1_differentiable_on S\"\n  unfolding C1_differentiable_on_eq\n  by (rule continuous_intros | simp add: continuous_at_imp_continuous_on differentiable_imp_continuous_within)+\n\nlemma C1_differentiable_on_of_real [derivative_intros]: \"of_real C1_differentiable_on S\"\n  unfolding C1_differentiable_on_def\n  using vector_derivative_works by fastforce\n\nlemma C1_differentiable_on_translation:\n  \"f C1_differentiable_on U - S \\<Longrightarrow> (+) d \\<circ> f C1_differentiable_on U - S\"\n  by (metis C1_differentiable_on_def has_vector_derivative_shift)\n\nlemma C1_differentiable_on_translation_eq: \n  fixes d :: \"'a::real_normed_vector\"\n  shows \"(+) d \\<circ> f C1_differentiable_on i - S \\<longleftrightarrow> f C1_differentiable_on i - S\"\n  by (force simp: o_def intro: C1_differentiable_on_translation dest: C1_differentiable_on_translation [of concl: \"-d\"])\n\n\ndefinition\\<^marker>\\<open>tag important\\<close> piecewise_C1_differentiable_on\n           (infixr \"piecewise'_C1'_differentiable'_on\" 50)\n  where \"f piecewise_C1_differentiable_on i  \\<equiv>\n           continuous_on i f \\<and>\n           (\\<exists>S. finite S \\<and> (f C1_differentiable_on (i - S)))\"\n\nlemma C1_differentiable_imp_piecewise:\n    \"f C1_differentiable_on S \\<Longrightarrow> f piecewise_C1_differentiable_on S\"\n  by (auto simp: piecewise_C1_differentiable_on_def C1_differentiable_on_eq continuous_at_imp_continuous_on differentiable_imp_continuous_within)\n\nlemma piecewise_C1_imp_differentiable:\n    \"f piecewise_C1_differentiable_on i \\<Longrightarrow> f piecewise_differentiable_on i\"\n  by (auto simp: piecewise_C1_differentiable_on_def piecewise_differentiable_on_def\n           C1_differentiable_on_def differentiable_def has_vector_derivative_def\n           intro: has_derivative_at_withinI)\n\nlemma piecewise_C1_differentiable_on_translation_eq:\n  \"((+) d \\<circ> f piecewise_C1_differentiable_on i) \\<longleftrightarrow> (f piecewise_C1_differentiable_on i)\"\n  unfolding piecewise_C1_differentiable_on_def continuous_on_translation_eq\n  by (metis C1_differentiable_on_translation_eq)\n\nlemma piecewise_C1_differentiable_compose [derivative_intros]:\n  assumes fg: \"f piecewise_C1_differentiable_on S\" \"g piecewise_C1_differentiable_on (f ` S)\" and fin: \"\\<And>x. finite (S \\<inter> f-`{x})\"\n  shows \"(g \\<circ> f) piecewise_C1_differentiable_on S\"\nproof -\n  have \"continuous_on S (\\<lambda>x. g (f x))\"\n    by (metis continuous_on_compose2 fg order_refl piecewise_C1_differentiable_on_def)\n  moreover have \"\\<exists>T. finite T \\<and> g \\<circ> f C1_differentiable_on S - T\"\n  proof -\n    obtain F where \"finite F\" and F: \"f C1_differentiable_on S - F\" and f: \"f piecewise_C1_differentiable_on S\"\n      using fg by (auto simp: piecewise_C1_differentiable_on_def)\n    obtain G where \"finite G\" and G: \"g C1_differentiable_on f ` S - G\" and g: \"g piecewise_C1_differentiable_on f ` S\"\n      using fg by (auto simp: piecewise_C1_differentiable_on_def)\n    show ?thesis\n    proof (intro exI conjI)\n      show \"finite (F \\<union> (\\<Union>x\\<in>G. S \\<inter> f-`{x}))\"\n        using fin by (auto simp only: Int_Union \\<open>finite F\\<close> \\<open>finite G\\<close> finite_UN finite_imageI)\n      show \"g \\<circ> f C1_differentiable_on S - (F \\<union> (\\<Union>x\\<in>G. S \\<inter> f -` {x}))\"\n        apply (rule C1_differentiable_compose)\n          apply (blast intro: C1_differentiable_on_subset [OF F])\n          apply (blast intro: C1_differentiable_on_subset [OF G])\n        by (simp add:  C1_differentiable_on_subset G Diff_Int_distrib2 fin)\n    qed\n  qed\n  ultimately show ?thesis\n    by (simp add: piecewise_C1_differentiable_on_def)\nqed\n\nlemma piecewise_C1_differentiable_on_subset:\n    \"f piecewise_C1_differentiable_on S \\<Longrightarrow> T \\<le> S \\<Longrightarrow> f piecewise_C1_differentiable_on T\"\n  by (auto simp: piecewise_C1_differentiable_on_def elim!: continuous_on_subset C1_differentiable_on_subset)\n\nlemma C1_differentiable_imp_continuous_on:\n  \"f C1_differentiable_on S \\<Longrightarrow> continuous_on S f\"\n  unfolding C1_differentiable_on_eq continuous_on_eq_continuous_within\n  using differentiable_at_withinI differentiable_imp_continuous_within by blast\n\nlemma C1_differentiable_on_empty [iff,derivative_intros]: \"f C1_differentiable_on {}\"\n  unfolding C1_differentiable_on_def\n  by auto\n\nlemma piecewise_C1_differentiable_affine:\n  fixes m::real\n  assumes \"f piecewise_C1_differentiable_on ((\\<lambda>x. m * x + c) ` S)\"\n  shows \"(f \\<circ> (\\<lambda>x. m *\\<^sub>R x + c)) piecewise_C1_differentiable_on S\"\nproof (cases \"m = 0\")\n  case True\n  then show ?thesis\n    unfolding o_def by (auto simp: piecewise_C1_differentiable_on_def)\nnext\n  case False\n  have *: \"\\<And>x. finite (S \\<inter> {y. m * y + c = x})\"\n    using False not_finite_existsD by fastforce\n  show ?thesis\n    apply (rule piecewise_C1_differentiable_compose [OF C1_differentiable_imp_piecewise])\n    apply (rule * assms derivative_intros | simp add: False vimage_def)+\n    done\nqed\n\nlemma piecewise_C1_differentiable_cases [derivative_intros]:\n  fixes c::real\n  assumes \"f piecewise_C1_differentiable_on {a..c}\"\n          \"g piecewise_C1_differentiable_on {c..b}\"\n           \"a \\<le> c\" \"c \\<le> b\" \"f c = g c\"\n  shows \"(\\<lambda>x. if x \\<le> c then f x else g x) piecewise_C1_differentiable_on {a..b}\"\nproof -\n  obtain S T where st: \"f C1_differentiable_on ({a..c} - S)\"\n                       \"g C1_differentiable_on ({c..b} - T)\"\n                       \"finite S\" \"finite T\"\n    using assms\n    by (force simp: piecewise_C1_differentiable_on_def)\n  then have f_diff: \"f differentiable_on {a..<c} - S\"\n        and g_diff: \"g differentiable_on {c<..b} - T\"\n    by (simp_all add: C1_differentiable_on_eq differentiable_at_withinI differentiable_on_def)\n  have \"continuous_on {a..c} f\" \"continuous_on {c..b} g\"\n    using assms piecewise_C1_differentiable_on_def by auto\n  then have cab: \"continuous_on {a..b} (\\<lambda>x. if x \\<le> c then f x else g x)\"\n    using continuous_on_cases [OF closed_real_atLeastAtMost [of a c],\n                               OF closed_real_atLeastAtMost [of c b],\n                               of f g \"\\<lambda>x. x\\<le>c\"]  assms\n    by (force simp: ivl_disj_un_two_touch)\n  { fix x\n    assume x: \"x \\<in> {a..b} - insert c (S \\<union> T)\"\n    have \"(\\<lambda>x. if x \\<le> c then f x else g x) differentiable at x\" (is \"?diff_fg\")\n    proof (cases x c rule: le_cases)\n      case le show ?diff_fg\n        apply (rule differentiable_transform_within [where f=f and d = \"dist x c\"])\n        using x dist_real_def le st by (auto simp: C1_differentiable_on_eq)\n    next\n      case ge show ?diff_fg\n        apply (rule differentiable_transform_within [where f=g and d = \"dist x c\"])\n        using dist_nz x dist_real_def ge st x by (auto simp: C1_differentiable_on_eq)\n    qed\n  }\n  then have \"(\\<forall>x \\<in> {a..b} - insert c (S \\<union> T). (\\<lambda>x. if x \\<le> c then f x else g x) differentiable at x)\"\n    by auto\n  moreover\n  { assume fcon: \"continuous_on ({a<..<c} - S) (\\<lambda>x. vector_derivative f (at x))\"\n       and gcon: \"continuous_on ({c<..<b} - T) (\\<lambda>x. vector_derivative g (at x))\"\n    have \"open ({a<..<c} - S)\"  \"open ({c<..<b} - T)\"\n      using st by (simp_all add: open_Diff finite_imp_closed)\n    moreover have \"continuous_on ({a<..<c} - S) (\\<lambda>x. vector_derivative (\\<lambda>x. if x \\<le> c then f x else g x) (at x))\"\n    proof -\n      have \"((\\<lambda>x. if x \\<le> c then f x else g x) has_vector_derivative vector_derivative f (at x))            (at x)\"\n        if \"a < x\" \"x < c\" \"x \\<notin> S\" for x\n      proof -\n        have f: \"f differentiable at x\"\n          by (meson C1_differentiable_on_eq Diff_iff atLeastAtMost_iff less_eq_real_def st(1) that)\n        show ?thesis\n          using that\n          apply (rule_tac f=f and d=\"dist x c\" in has_vector_derivative_transform_within)\n             apply (auto simp: dist_norm vector_derivative_works [symmetric] f)\n          done\n      qed\n      then show ?thesis\n        by (metis (no_types, lifting) continuous_on_eq [OF fcon] DiffE greaterThanLessThan_iff vector_derivative_at)\n    qed\n    moreover have \"continuous_on ({c<..<b} - T) (\\<lambda>x. vector_derivative (\\<lambda>x. if x \\<le> c then f x else g x) (at x))\"\n    proof -\n      have \"((\\<lambda>x. if x \\<le> c then f x else g x) has_vector_derivative vector_derivative g (at x))            (at x)\"\n        if \"c < x\" \"x < b\" \"x \\<notin> T\" for x\n      proof -\n        have g: \"g differentiable at x\"\n          by (metis C1_differentiable_on_eq DiffD1 DiffI atLeastAtMost_diff_ends greaterThanLessThan_iff st(2) that)\n        show ?thesis\n          using that\n          apply (rule_tac f=g and d=\"dist x c\" in has_vector_derivative_transform_within)\n             apply (auto simp: dist_norm vector_derivative_works [symmetric] g)\n          done\n      qed\n      then show ?thesis\n        by (metis (no_types, lifting) continuous_on_eq [OF gcon] DiffE greaterThanLessThan_iff vector_derivative_at)\n    qed\n    ultimately have \"continuous_on ({a<..<b} - insert c (S \\<union> T))\n        (\\<lambda>x. vector_derivative (\\<lambda>x. if x \\<le> c then f x else g x) (at x))\"\n      by (rule continuous_on_subset [OF continuous_on_open_Un], auto)\n  } note * = this\n  have \"continuous_on ({a<..<b} - insert c (S \\<union> T)) (\\<lambda>x. vector_derivative (\\<lambda>x. if x \\<le> c then f x else g x) (at x))\"\n    using st\n    by (auto simp: C1_differentiable_on_eq elim!: continuous_on_subset intro: *)\n  ultimately have \"\\<exists>S. finite S \\<and> ((\\<lambda>x. if x \\<le> c then f x else g x) C1_differentiable_on {a..b} - S)\"\n    apply (rule_tac x=\"{a,b,c} \\<union> S \\<union> T\" in exI)\n    using st  by (auto simp: C1_differentiable_on_eq elim!: continuous_on_subset)\n  with cab show ?thesis\n    by (simp add: piecewise_C1_differentiable_on_def)\nqed\n\nlemma piecewise_C1_differentiable_const [derivative_intros]:\n  \"(\\<lambda>x. c) piecewise_C1_differentiable_on S\"\n  by (simp add: C1_differentiable_imp_piecewise)\n\nlemma piecewise_C1_differentiable_scaleR [derivative_intros]:\n    \"\\<lbrakk>f piecewise_C1_differentiable_on S\\<rbrakk>\n     \\<Longrightarrow> (\\<lambda>x. c *\\<^sub>R f x) piecewise_C1_differentiable_on S\"\n  by (force simp add: piecewise_C1_differentiable_on_def continuous_on_scaleR)\n\nlemma piecewise_C1_differentiable_neg [derivative_intros]:\n    \"f piecewise_C1_differentiable_on S \\<Longrightarrow> (\\<lambda>x. -(f x)) piecewise_C1_differentiable_on S\"\n  unfolding piecewise_C1_differentiable_on_def\n  by (auto intro!: continuous_on_minus C1_differentiable_on_minus)\n\nlemma piecewise_C1_differentiable_add [derivative_intros]:\n  assumes \"f piecewise_C1_differentiable_on i\"\n          \"g piecewise_C1_differentiable_on i\"\n    shows \"(\\<lambda>x. f x + g x) piecewise_C1_differentiable_on i\"\nproof -\n  obtain S t where st: \"finite S\" \"finite t\"\n                       \"f C1_differentiable_on (i-S)\"\n                       \"g C1_differentiable_on (i-t)\"\n    using assms by (auto simp: piecewise_C1_differentiable_on_def)\n  then have \"finite (S \\<union> t) \\<and> (\\<lambda>x. f x + g x) C1_differentiable_on i - (S \\<union> t)\"\n    by (auto intro: C1_differentiable_on_add elim!: C1_differentiable_on_subset)\n  moreover have \"continuous_on i f\" \"continuous_on i g\"\n    using assms piecewise_C1_differentiable_on_def by auto\n  ultimately show ?thesis\n    by (auto simp: piecewise_C1_differentiable_on_def continuous_on_add)\nqed\n\nlemma piecewise_C1_differentiable_diff [derivative_intros]:\n    \"\\<lbrakk>f piecewise_C1_differentiable_on S;  g piecewise_C1_differentiable_on S\\<rbrakk>\n     \\<Longrightarrow> (\\<lambda>x. f x - g x) piecewise_C1_differentiable_on S\"\n  unfolding diff_conv_add_uminus\n  by (metis piecewise_C1_differentiable_add piecewise_C1_differentiable_neg)\n\nlemma piecewise_C1_differentiable_cmult_right [derivative_intros]:\n  fixes c::complex\n  shows \"f piecewise_C1_differentiable_on S\n     \\<Longrightarrow> (\\<lambda>x. f x * c) piecewise_C1_differentiable_on S\"\n  by (force simp: piecewise_C1_differentiable_on_def continuous_on_mult_right)\n\nlemma piecewise_C1_differentiable_cmult_left [derivative_intros]:\n  fixes c::complex\n  shows \"f piecewise_C1_differentiable_on S\n     \\<Longrightarrow> (\\<lambda>x. c * f x) piecewise_C1_differentiable_on S\"\n  using piecewise_C1_differentiable_cmult_right [of f S c] by (simp add: mult.commute)\n\nlemma piecewise_C1_differentiable_on_of_real [derivative_intros]: \n  \"of_real piecewise_C1_differentiable_on S\"\n  by (simp add: C1_differentiable_imp_piecewise C1_differentiable_on_of_real)\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/Derivative.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.855851135937125, "lm_q2_score": 0.8397339676722393, "lm_q1q2_score": 0.7186872701172751}}
{"text": "(*  Title:      RSAPSS/Productdivides.thy\n    Author:     Christina Lindenberg, Kai Wirt, Technische Universit\u00e4t Darmstadt\n    Copyright:  2005 - Technische Universit\u00e4t Darmstadt \n*)\n\nheader \"Lemmata for modular arithmetic with primes\"\n\ntheory Productdivides\nimports Pdifference\nbegin\n\nlemma productdivides_lemma: \"\\<lbrakk>x mod z = (0::nat)\\<rbrakk> \\<Longrightarrow> ((y*x) mod (y*z) = 0)\"\n  apply (subst mod_eq_0_iff [of \"y*x\" \"y*z\"])\n  apply auto\n  done\n\nlemma productdivides: \"\\<lbrakk>x mod a = (0::nat); x mod b = 0; prime a; prime b; a \\<noteq> b\\<rbrakk> \\<Longrightarrow> x mod (a*b) = 0\"\n  apply (simp add: mod_eq_0_iff [of x a])\n  apply (erule exE)\n  apply (simp)\n  apply (rule disjI2)\n  apply (simp add: dvd_eq_mod_eq_0 [symmetric])\n  apply (drule prime_dvd_mult_nat [of b])\n  apply (erule disjE)\n  apply auto\n  apply (simp add: prime_nat_def)\n  apply auto\n  done\n\nlemma specializedtoprimes1: \n  fixes p::nat \n  shows \"\\<lbrakk>prime p; prime q; p \\<noteq> q; a mod p = b mod p ; a mod q = b mod q\\<rbrakk>\n         \\<Longrightarrow> a mod (p*q) = b mod (p*q)\"\nby (metis equalmodstrick1 equalmodstrick2 productdivides) \n\nlemma specializedtoprimes1a:\n fixes p::nat \n shows \"\\<lbrakk>prime p; prime q; p \\<noteq> q; a mod p = b mod p; a mod q = b mod q; b < p*q \\<rbrakk>\n    \\<Longrightarrow> a mod (p*q) = b\"\nby (metis Divides.mod_less specializedtoprimes1)\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/RSAPSS/Productdivides.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894604912848, "lm_q2_score": 0.8031737987125612, "lm_q1q2_score": 0.7186714500307485}}
{"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_times\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 times :: \"Bin => Bin => Bin\" where\n\"times (One) y = y\"\n| \"times (ZeroAnd xs1) y = ZeroAnd (times xs1 y)\"\n| \"times (OneAnd xs12) y = plus2 (ZeroAnd (times xs12 y)) y\"\n\nfun plus :: \"Nat => Nat => Nat\" where\n\"plus (Z) y = y\"\n| \"plus (S z) y = S (plus z y)\"\n\nfun times2 :: \"Nat => Nat => Nat\" where\n\"times2 (Z) y = Z\"\n| \"times2 (S z) y = plus y (times2 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 (times x y)) = (times2 (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_times.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789457685656, "lm_q2_score": 0.8031737963569014, "lm_q1q2_score": 0.7186714456695213}}
{"text": "(******************************************************************************)\n(* Project: Isabelle/UTP Toolkit                                              *)\n(* File: List_Lexord_Alt.thy                                                  *)\n(* Authors: Simon Foster and Frank Zeyda                                      *)\n(* Emails: simon.foster@york.ac.uk and frank.zeyda@york.ac.uk                 *)\n(******************************************************************************)\n\nsection \\<open>Alternative List Lexicographic Order\\<close>\n\ntheory List_Lexord_Alt\n  imports Main\nbegin\n\ntext \\<open> Since we can't instantiate the order class twice for lists, and we want prefix as\n  the default order for the UTP we here add syntax for the lexicographic order relation. \\<close>\n\ndefinition list_lex_less :: \"'a::linorder list \\<Rightarrow> 'a list \\<Rightarrow> bool\" (infix \"<\\<^sub>l\" 50)\nwhere \"xs <\\<^sub>l ys \\<longleftrightarrow> (xs, ys) \\<in> lexord {(u, v). u < v}\"\n\nlemma list_lex_less_neq [simp]: \"x <\\<^sub>l y \\<Longrightarrow> x \\<noteq> y\"\n  apply (simp add: list_lex_less_def)\n  apply (meson case_prodD less_irrefl lexord_irreflexive mem_Collect_eq)\ndone\n\nlemma not_less_Nil [simp]: \"\\<not> x <\\<^sub>l []\"\n  by (simp add: list_lex_less_def)\n\nlemma Nil_less_Cons [simp]: \"[] <\\<^sub>l a # x\"\n  by (simp add: list_lex_less_def)\n\nlemma Cons_less_Cons [simp]: \"a # x <\\<^sub>l b # y \\<longleftrightarrow> a < b \\<or> a = b \\<and> x <\\<^sub>l y\"\n  by (simp add: list_lex_less_def)\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/List_Lexord_Alt.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8740772351648676, "lm_q2_score": 0.8221891370573388, "lm_q1q2_score": 0.7186568077016671}}
{"text": "theory Generators\nimports Main  \"HOL-Library.FuncSet\" \"HOL-Algebra.Group\"\nbegin\n\n\ndatatype ('a,'b) monoidgentype = C 'a  'b (infix \"!\" 63)\n\ndatatype ('a,'b) groupgentype = P \"('a,'b) monoidgentype\"\n                               | N  \"('a,'b) monoidgentype\"\n\ntype_synonym ('a,'b) word = \"(('a,'b) groupgentype) list\"\n\n\n\nprimrec inverse::\"('a,'b) groupgentype \\<Rightarrow> ('a,'b) groupgentype\"\n  where\n\"inverse (P x) = (N x)\"\n|\"inverse (N x) = (P x)\"\n\nprimrec wordinverse::\"('a,'b) word \\<Rightarrow> ('a, 'b) word\"\n  where\n\"wordinverse [] = []\"\n|\"wordinverse (x#xs) =  (wordinverse xs)@[inverse x]\"\n\n\ninductive_set spanset::\"('a,'b) word set\\<Rightarrow> ('a,'b) word set\" (\"\\<langle>_\\<rangle>\")\n  for S::\"('a,'b) word set\"\n  where\n\"x \\<in> S \\<Longrightarrow> x \\<in> \\<langle>S\\<rangle>\"\n|\"x \\<in> inver ` S \\<Longrightarrow> x \\<in> \\<langle>S\\<rangle>\"\n|\"x \\<in> S \\<Longrightarrow> y \\<in> \\<langle>S\\<rangle> \\<Longrightarrow> x@y \\<in> \\<langle>S\\<rangle>\"\n|\"x \\<in> inver ` S \\<Longrightarrow> ys \\<in> \\<langle>S\\<rangle> \\<Longrightarrow> x@y \\<in> \\<langle>S\\<rangle>\"\n\n\n\ndefinition setlistcross::\"'a set \\<Rightarrow> 'a list \\<Rightarrow> 'a list set\"\n where\n\"setlistcross S xs = {[s]@xs | s. s \\<in> S}\"\n\nvalue \"setlistcross {(1::nat), 2, 3} [(4::nat), 5, 6]\"\n\nprimrec lengthword::\"nat \\<Rightarrow> 'a set \\<Rightarrow> 'a list set\"\n  where\n\"lengthword 0 S = {[s] | s. s \\<in> S}\"\n|\"lengthword (Suc n) S = \\<Union> {setlistcross S xs | xs. xs \\<in> (lengthword n S)}\"\n\n\nabbreviation \"ngroupword \\<equiv> \\<lambda> n (S::('a,'b) word set). lengthword n (S \\<union> (wordinverse ` S))\" \n\ndatatype char = G | H\n\nvalue \"ngroupword 1 {[P (C G (1::nat))], [N (C G (2::nat))], [P (C H (3::nat))]}\" \n\n(*reduction removes cancellations next to each other*)\nfun reduction:: \"('a,'b) word \\<Rightarrow> ('a,'b) word\"\n where\n\"reduction [] = []\"\n|\"reduction [x] = [x]\"\n|\"reduction (g1#g2#wrd) = (if (g1 = inverse g2) \n                             then reduction wrd \n                             else (g1#(reduction (g2#wrd))))\"\n\nvalue \"reduction [P (C G (3::nat)), N (C G (3::nat)), (N (C G (2::nat)))]\"\n\nfun reduced::\"('a,'b) word \\<Rightarrow> bool\"\n  where\n\"reduced [] = True\"\n|\"reduced [g] = True\"\n|\"reduced (g#h#wrd) = (if (g \\<noteq> inverse h) then reduced (h#wrd) else False)\"\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\n(*prove converse of the following too*)\nlemma assumes \"reduced wrd\"\n  shows \"reduction wrd = wrd\"\n  using assms\nproof(induction wrd rule: reduction.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 g1 g2 wrd)\n  then show ?case\n  proof(cases \"g1 = inverse g2\")\n    case True\n      then show ?thesis using 3 \n        by force\n    next\n    case False\n    have \"reduced (g2#wrd)\" using False 3 by force\n      then show ?thesis using False 3 by force\n    qed\nqed\n\nlemma length_reduction:\n \"length (reduction wrd) \\<le> length wrd\"\nproof(induction wrd rule: reduction.induct)\ncase 1\n  then show ?case by simp\nnext\ncase (2 x)\n  then show ?case by simp\nnext\n  case (3 g1 g2 wrd)\n  then show ?case \n  proof(cases \"g1 = inverse g2\")\n    case True \n    then show ?thesis using 3 by force\n  next\n    case False\n    then show ?thesis using 3 \n    by auto \n qed  \nqed\n\nlemma decreasing_length:\n  assumes \"reduction wrd \\<noteq> wrd\"\n  shows \"length (reduction wrd) < length wrd\"\n  using assms\nproof(induction wrd rule: reduction.induct)\ncase 1\n  then show ?case by simp\nnext\n  case (2 x)\n  then show ?case by simp\nnext\n  case (3 g1 g2 wrd)\n  then show ?case \n  proof(cases \"g1 = inverse g2\")\n    case True\n    then have red_inv:\"reduction (g1#g2#wrd) = reduction wrd\" by auto\n    then show ?thesis \n    proof(cases \"reduction wrd = wrd\")\n      case True\n      then have \"reduction (g1#g2#wrd) = wrd\" using red_inv by auto\n      then have \"length (reduction (g1#g2#wrd)) = length wrd\" by auto    \n      then show ?thesis \n        by simp\n    next\n      case False\n      then have \"length (reduction wrd) < length wrd\" using 3 True by argo\n      then show ?thesis using red_inv by force\n    qed\n  next\n    case False\n    have prem:\"reduction (g1#g2#wrd) \\<noteq> (g1#g2#wrd)\" using 3 by argo\n    then have \"reduction (g1#g2#wrd) = g1#reduction (g2#wrd)\" using False by auto\n    then have \"reduction (g2#wrd) \\<noteq> g2#wrd\" using prem by fastforce\n    then have \"length (g2#wrd) > length (reduction (g2#wrd))\" using 3 False by blast\n    then have \"length (g1#g2#wrd) > length (reduction (g1#g2#wrd))\" using False by force\n    then show ?thesis by fast\n  qed  \nqed\n\n\n\n\nlemma if_length_reduction_eq:\n  assumes \"length (reduction (wrd)) = length wrd\"\n  shows \"reduction wrd = wrd\"\n  using assms\nproof(induction wrd rule: reduction.induct)\ncase 1\n  then show ?case \n    by simp \nnext\n  case (2 x)\n  then show ?case by simp\nnext\ncase (3 g1 g2 wrd)\n  then show ?case\n  proof(cases \"g1 = inverse g2\")\n    case True\n    then have \"reduction (g1#g2#wrd) = reduction (wrd)\" by simp     \n    then have \"length (reduction (g1#g2#wrd)) = length (reduction (wrd))\" by auto\n    moreover have \"length (wrd) > length (reduction wrd)\" using 3 by (metis \\<open>reduction (g1 # g2 # wrd) = reduction wrd\\<close> decreasing_length impossible_Cons le_cases)\n    then show ?thesis using 3 by auto\n  next\n    case False\n    then show ?thesis using \"3.prems\" decreasing_length nat_neq_iff by blast\n  qed\nqed\n\n(*\"reduction-reduced lemma\"*)\nlemma reduction_fixpt:\n  assumes \"reduction wrd = wrd\"\n  shows \"reduced wrd\"\n  using assms\nproof(induction wrd rule:reduction.induct)\ncase 1\nthen show ?case by simp\nnext\ncase (2 x)\n  then show ?case by simp\nnext\n  case (3 g1 g2 wrd)\n  then show ?case by (metis decreasing_length impossible_Cons length_Cons less_Suc_eq less_or_eq_imp_le list.inject reduced.simps(3) reduction.simps(3))\nqed\n\n\n\n(*Show that length decreases if and only the word after reduction is not the same as the original word*)\n\n(*show that if after reduction of a word it does not change, that subsequent reductions will be ineffective*)\n\n(*use the word length argument decrement argument to show that the reduced word is finally reduced*)\n\n\nvalue \"reduced  [P (C G (1::nat)), N (C G (2::nat)), P (C G (1::nat))]\" \n\n\n\n\n\ninductive reln::\"('a,'b) word \\<Rightarrow> ('a,'b) word \\<Rightarrow> bool\" (infixr \"~\" 65)\n  where\nrefl[intro!]: \"a ~ a\" |\nsym: \"a ~ b \\<Longrightarrow> b ~ a\" |\ntrans: \"a ~ b \\<Longrightarrow> b ~ c \\<Longrightarrow> a ~ c\" |\nbase: \"[g, inverse g] ~ []\" |\nmult: \"xs ~ xs' \\<Longrightarrow> ys ~ ys' \\<Longrightarrow> (xs@ys) ~ (xs'@ys')\"\n  \n\nlemma assumes \"h = inverse g\"\n  shows \"[g, h] ~ []\"\n  using assms reln.base inverse.simps by simp\n\nlemma relation: \"(xs@ys) ~ xs@[g,inverse g]@ys\"\n  using reln.base reln.refl reln.mult\nproof-\n  have \"(xs@[g, inverse g]) ~ xs\" using reln.base reln.mult reln.refl by fastforce\n  then show ?thesis using mult[of \"xs@[g, inverse g]\" \"xs\" \"ys\" \"ys\"] reln.refl reln.sym\n    by auto\nqed\n\nlemma inverse_of_inverse:\n  assumes \"g = inverse h\"\n  shows \"h = inverse g\"\n  using assms inverse.simps \n  by (metis groupgentype.exhaust)\n\nlemma rel_to_reduction:\"xs ~ reduction xs\"\nproof(induction xs rule:reduction.induct )\n  case 1\n  then show ?case \n    using reln.refl by auto\nnext\n  case (2 x)\n  then show ?case using reln.refl by auto\nnext\n  case (3 g1 g2 wrd)\n  then show ?case\n  proof(cases \"g1 = inverse g2\")\n    case True\n    have \"[g1,  g2] ~ []\" using reln.base[of \"g1\"] inverse_of_inverse[of \"g1\" \"g2\"] True\n      by blast\n    then have 1:\"([g1,g2]@wrd) ~ wrd\" using reln.mult refl by fastforce\n    with 3(1) have 2:\"reduction ([g1,g2]@wrd) ~ wrd\" using reln.trans True \n      using append_Cons append_Nil reduction.simps(3) reln.sym by auto\n    then show ?thesis using 1 reln.sym reln.trans \n      by (metis append_Cons append_Nil)\nnext\n  case False\n  then have \"([g1]@(g2#wrd)) ~ ([g1]@(reduction (g2#wrd)))\" using 3(2) reln.mult reln.refl \n    by blast\n  then have \"([g1]@(g2#wrd)) ~ (reduction (g1#g2#wrd))\" using False by simp\n  then show ?thesis by simp\nqed\nqed\n\ndefinition wordeq::\"('a,'b) word \\<Rightarrow> ('a,'b) word set\" (\"[[_]]\")\n  where\n\"wordeq wrd = {wrds. wrd ~ wrds}\"\n\n\n(*This is approach for normal form using newsmans lemma*)\n\ndefinition cancel_at :: \"nat \\<Rightarrow> ('a,'b) word \\<Rightarrow> ('a,'b) word\"\nwhere \"cancel_at i l = take i l @ drop (2+i) l\"\n\n\ndefinition cancels_to_1_at ::  \"nat \\<Rightarrow> ('a,'b) word \\<Rightarrow> ('a,'b) word \\<Rightarrow> bool\"\nwhere  \"cancels_to_1_at i l1 l2 = (0\\<le>i \\<and> (1+i) < length l1\n                              \\<and> (inverse (l1 ! i) = (l1 ! (1+i)))\n                              \\<and> (l2 = cancel_at i l1))\"\n\ndefinition cancels_to_1 :: \"('a,'b) word \\<Rightarrow> ('a,'b) word \\<Rightarrow> bool\"\nwhere \"cancels_to_1 l1 l2 = (\\<exists>i. cancels_to_1_at i l1 l2)\"\n\ndefinition cancels_to  :: \"('a,'b) word \\<Rightarrow> ('a,'b) word \\<Rightarrow> bool\"\nwhere \"cancels_to = (cancels_to_1)^**\"\n\n\nlemma \"cancels_to wrd (reduction wrd)\"\n  sorry\n\nlemma \"cancels_to wrd (iter n reduction wrd)\"\n  sorry\n\n\nlemma cancels_to_trans [trans]:\n  \"\\<lbrakk> cancels_to a b; cancels_to b c \\<rbrakk> \\<Longrightarrow> cancels_to a c\"\n  sorry\n\nlemma \"cancels_to x y \\<Longrightarrow> x ~ y\"\n  unfolding cancels_to_def\nproof(induction rule: rtranclp.induct)\n  case (rtrancl_refl a)\n  then show ?case by blast\nnext\n  case (rtrancl_into_rtrancl a b c)\n  then have \"cancels_to_1 b c\" by simp\n  then obtain i where i:\"cancels_to_1_at i b c\" unfolding cancels_to_1_def by meson\n  then have c_def:\"(take i b)@(drop (i + 2) b) = c\" unfolding cancels_to_1_at_def cancel_at_def\n    by force\n  moreover have \"b!i = inverse (b!(i+1))\" using i  unfolding cancels_to_1_at_def cancel_at_def\n    using inverse_of_inverse \n    by (simp add: inverse_of_inverse add.commute)\n  then have \"[b!i, b!(i+1)] ~ []\" \n    by (metis base inverse_of_inverse)\n  then have \"([b!i, b!(i+1)]@(drop (i+2) b)) ~ []@(drop (i+2) b)\"\n    using reln.refl reln.mult by fast\n  then have \"((take i b)@(([b!i, b!(i+1)]@(drop (i+2) b)))) ~ (take i b)@(drop (i+2) b)\"\n    using reln.refl reln.mult \n    by (simp add: mult reln.refl)\n  then have \"b ~ c\" using c_def \n    by (metis Cons_nth_drop_Suc add.commute add_2_eq_Suc' append_Cons append_self_conv2 cancels_to_1_at_def i id_take_nth_drop linorder_not_less plus_1_eq_Suc trans_le_add2)\n  then show ?case using reln.trans rtrancl_into_rtrancl(3) by fast\nqed\n\ndefinition cancels_eq::\"('a,'b) word \\<Rightarrow> ('a,'b)  word \\<Rightarrow> bool\"\n  where\n\"cancels_eq = (\\<lambda> wrd1 wrd2. cancels_to wrd1 wrd2 \\<or> cancels_to wrd2 wrd1)^**\"\n\n(*results to prove: cancels eq a b, then (1) cancels eq c@a c@b and (2) cancels eq a@c and b@c*)\n\n(*Try proving this*)\nlemma  \"x ~ y \\<Longrightarrow> cancels_eq x y\"\nproof(induction rule:reln.induct)\ncase (refl a)\nthen show ?case unfolding cancels_eq_def cancels_to_def by simp\nnext\n  case (sym a b)\n  then show ?case unfolding cancels_eq_def \n    by (metis (no_types, lifting) sympD sympI symp_rtranclp)\nnext\n  case (trans a b c)\n  then show ?case sorry\nnext\n  case (base g)\n  then show ?case sorry\nnext\n  case (mult xs xs' ys ys')\n  then show ?case sorry\nqed\n\nlemma \"x ~ y \\<longleftrightarrow>  cancels_eq x y\"\n(*Prove the following:\n  (1) if xs and ys can be reduced to same element, they are related. \n  (2) if xs and ys are related, they have the same final reduction. \n  (3) If xs is a related to a reduced word, the reduced word is unique. \n  (4) Every element is related to its reduced form. \n*)\n\n(*\n(1) Every element is related to the reduced word obtained by applying \n   the iter algorithm. \n(2) If two elements reduce to the same word obtained by the iter algorithm, they are related. \n(3) Reduced word obtained by our (iter application) algorithm is unique in the equivalence\nclass.\n(4) If two elements have the same reduced word (obtained by applying the iter\nalgorithm), the two elements are related. \n*)\n\n\nlemma reln_of_iter:\"xs ~ iter n (reduction) xs\"\nproof(induction n)\n  case 0\n  then show ?case using reln.refl[of \"xs\"] unfolding iter.simps .\nnext\n  case (Suc n)\n  have loc:\"iter n (reduction) xs ~ iter (Suc n) reduction xs\" unfolding iter.simps(2) \n    using rel_to_reduction[of \"iter n (reduction) xs \"] .\n  show ?case using reln.trans[OF \"Suc\" loc] .\nqed\n\nlemma iter_eq_implies_reln:\n  assumes \"iter n reduction xs = iter m reduction ys\"\n  shows \"xs ~ ys\"\nproof-\n  have \"xs ~ iter n reduction xs\" using reln_of_iter[of \"xs\" \"n\"] .\n  moreover have \"ys ~ iter m reduction ys\" using reln_of_iter[of \"ys\" \"m\"] .\n  ultimately show ?thesis using assms reln.refl reln.trans \n    by (metis reln.sym)\nqed\n\n\n\n \n\nlemma   \"wrd1 ~ wrd2 \\<Longrightarrow> reduced wrd1 \\<Longrightarrow> reduced wrd2 \\<Longrightarrow> wrd1 = wrd2\"\nproof(induction rule: reln.induct)\n  case (refl a)\n  then show ?case by fast\nnext\n  case (sym a b)\n  then show ?case by simp\nnext\n  case (trans a b c)\n  then show ?case sorry\nnext\n  case (base g)\n  then show ?case using reduced.simps \n    by (metis inverse_of_inverse)\nnext\n  case (mult xs xs' ys ys')\n  then show ?case sorry\n  (*use the result that if (xs@ys) is reduced, xs and ys are reduced *)\nqed\n\nquotient_type ('a,'b) wordclass = \"('a,'b) word\"/\"reln\"\n  using reln.refl reln.sym reln.trans  equivpI reflpI sympI transpI\n  by metis\n\nlift_definition mult::\"('a,'b) wordclass \\<Rightarrow> ('a,'b) wordclass \\<Rightarrow> ('a,'b) wordclass\" (infixr \"*\" 65)\n is List.append\n  by (simp add: mult)\n\n(*Prove the following: Product of Abs of two wordclasses is the Abs of the product*)\n\n(*Look up the difference between Abs_wordclasss and abs_wordclass, by experiment or reading. \nSame for Rep_wordclass and rep_wordclass*)\n\nlemma \"abs_wordclass (wrd) * abs_wordclass (wrd') = abs_wordclass (wrd@wrd')\"\n  by (simp add: mult.abs_eq)\n\n\nlemma \"Rep_wordclass (Abs_wordclass wrdset) = wrdset\"\n\n(*Try to finish this lemma along with the lemmas above*)\nlemma \"rep_wordclass (abs_wordclass wrd) = wrd\"\n  unfolding wordeq_def sorry\nqed", "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/Generators.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772417253256, "lm_q2_score": 0.8221891305219504, "lm_q1q2_score": 0.7186568073831702}}
{"text": "section  \\<open>Undirected Graphs\\<close>\ntheory Undirected_Graph\nimports\n  Common\nbegin\nsubsection \\<open>Nodes and Edges\\<close>  \n\ntypedef 'v ugraph \n  = \"{ (V::'v set , E). E \\<subseteq> V\\<times>V \\<and> finite V \\<and> sym E \\<and> irrefl E }\"\n  unfolding sym_def irrefl_def by blast\n\nsetup_lifting type_definition_ugraph\n\nlift_definition nodes_internal :: \"'v ugraph \\<Rightarrow> 'v set\" is fst .\nlift_definition edges_internal :: \"'v ugraph \\<Rightarrow> ('v\\<times>'v) set\" is snd .\nlift_definition graph_internal :: \"'v set \\<Rightarrow> ('v\\<times>'v) set \\<Rightarrow> 'v ugraph\" \n  is \"\\<lambda>V E. if finite V \\<and> finite E then (V\\<union>fst`E\\<union>snd`E, (E\\<union>E\\<inverse>)-Id) else ({},{})\"\n  by (auto simp: sym_def irrefl_def; force)     \n\ndefinition nodes :: \"'v ugraph \\<Rightarrow> 'v set\" \n  where \"nodes = nodes_internal\" \ndefinition edges :: \"'v ugraph \\<Rightarrow> ('v\\<times>'v) set\" \n  where \"edges = edges_internal\" \ndefinition graph :: \"'v set \\<Rightarrow> ('v\\<times>'v) set \\<Rightarrow> 'v ugraph\" \n  where \"graph = graph_internal\" \n\nlemma edges_subset: \"edges g \\<subseteq> nodes g \\<times> nodes g\"\n  unfolding edges_def nodes_def by transfer auto\n\nlemma nodes_finite[simp, intro!]: \"finite (nodes g)\"\n  unfolding edges_def nodes_def by transfer auto\n  \nlemma edges_sym: \"sym (edges g)\"    \n  unfolding edges_def nodes_def by transfer auto\n\nlemma edges_irrefl: \"irrefl (edges g)\"      \n  unfolding edges_def nodes_def by transfer auto\n\nlemma nodes_graph: \"\\<lbrakk>finite V; finite E\\<rbrakk> \\<Longrightarrow> nodes (graph V E) = V\\<union>fst`E\\<union>snd`E\"    \n  unfolding edges_def nodes_def graph_def by transfer auto\n  \nlemma edges_graph: \"\\<lbrakk>finite V; finite E\\<rbrakk> \\<Longrightarrow> edges (graph V E) = (E\\<union>E\\<inverse>)-Id\"    \n  unfolding edges_def nodes_def graph_def by transfer auto\n\nlemmas graph_accs = nodes_graph edges_graph  \n  \nlemma nodes_edges_graph_presentation: \"\\<lbrakk>finite V; finite E\\<rbrakk> \n    \\<Longrightarrow> nodes (graph V E) = V \\<union> fst`E \\<union> snd`E \\<and> edges (graph V E) = E\\<union>E\\<inverse> - Id\"\n  by (simp add: graph_accs)\n      \nlemma graph_eq[simp]: \"graph (nodes g) (edges g) = g\"  \n  unfolding edges_def nodes_def graph_def\n  apply transfer\n  unfolding sym_def irrefl_def\n  apply (clarsimp split: prod.splits)\n  by (fastforce simp: finite_subset)\n\nlemma edges_finite[simp, intro!]: \"finite (edges g)\"\n  using edges_subset finite_subset by fastforce\n  \nlemma graph_cases[cases type]: obtains V E \n  where \"g = graph V E\" \"finite V\" \"finite E\" \"E\\<subseteq>V\\<times>V\" \"sym E\" \"irrefl E\"  \nproof -\n  show ?thesis\n    apply (rule that[of \"nodes g\" \"edges g\"]) \n    using edges_subset edges_sym edges_irrefl[of g]\n    by auto\nqed     \n\nlemma graph_eq_iff: \"g=g' \\<longleftrightarrow> nodes g = nodes g' \\<and> edges g = edges g'\"  \n  unfolding edges_def nodes_def graph_def by transfer auto\n\n  \n  \nlemma edges_sym': \"(u,v)\\<in>edges g \\<Longrightarrow> (v,u)\\<in>edges g\" using edges_sym \n  by (blast intro: symD)\n  \nlemma edges_irrefl'[simp,intro!]: \"(u,u)\\<notin>edges g\"\n  by (meson edges_irrefl irrefl_def)\n  \nlemma edges_irreflI[simp, intro]: \"(u,v)\\<in>edges g \\<Longrightarrow> u\\<noteq>v\" by auto \n  \nlemma edgesT_diff_sng_inv_eq[simp]: \n  \"(edges T - {(x, y), (y, x)})\\<inverse> = edges T - {(x, y), (y, x)}\"\n  using edges_sym' by fast\n  \nlemma nodesI[simp,intro]: assumes \"(u,v)\\<in>edges g\" shows \"u\\<in>nodes g\" \"v\\<in>nodes g\"\n  using assms edges_subset by auto\n  \nlemma split_edges_sym: \"\\<exists>E. E\\<inter>E\\<inverse> = {} \\<and> edges g = E \\<union> E\\<inverse>\"  \n  using split_sym_rel[OF edges_sym edges_irrefl, of g] by metis\n\n  \nsubsection \\<open>Connectedness Relation\\<close>  \n  \nlemma rtrancl_edges_sym': \"(u,v)\\<in>(edges g)\\<^sup>* \\<Longrightarrow> (v,u)\\<in>(edges g)\\<^sup>*\"  \n  by (simp add: edges_sym symD sym_rtrancl)\n  \nlemma trancl_edges_subset: \"(edges g)\\<^sup>+ \\<subseteq> nodes g \\<times> nodes g\"  \n  by (simp add: edges_subset trancl_subset_Sigma)\n      \nlemma find_crossing_edge:\n  assumes \"(u,v)\\<in>E\\<^sup>*\" \"u\\<in>V\" \"v\\<notin>V\"\n  obtains u' v' where \"(u',v')\\<in>E\\<inter>V\\<times>-V\"\n  using assms apply (induction rule: converse_rtrancl_induct)\n  by auto\n\n\n  \n\nsubsection \\<open>Constructing Graphs\\<close>\n  \ndefinition \"graph_empty \\<equiv> graph {} {}\"\ndefinition \"ins_node v g \\<equiv> graph (insert v (nodes g)) (edges g)\"\ndefinition \"ins_edge e g \\<equiv> graph (nodes g) (insert e (edges g))\"\ndefinition \"graph_join g\\<^sub>1 g\\<^sub>2 \\<equiv> graph (nodes g\\<^sub>1 \\<union> nodes g\\<^sub>2) (edges g\\<^sub>1 \\<union> edges g\\<^sub>2)\"\ndefinition \"restrict_nodes g V \\<equiv> graph (nodes g \\<inter> V) (edges g \\<inter> V\\<times>V)\"\ndefinition \"restrict_edges g E \\<equiv> graph (nodes g) (edges g \\<inter> (E\\<union>E\\<inverse>))\"\n\n\ndefinition \"nodes_edges_consistent V E \\<equiv> finite V \\<and> irrefl E \\<and> sym E \\<and> E \\<subseteq> V\\<times>V\"\n\n\n\n  show ?G1 ?G2 using assms\n    by (auto simp: nodes_edges_consistent_def nodes_graph edges_graph irrefl_def)\n    \nqed    \n\nlemma nec_empty[simp]: \"nodes_edges_consistent {} {}\" \n  by (auto simp: nodes_edges_consistent_def irrefl_def sym_def)\n\nlemma graph_empty_accs[simp]:\n  \"nodes graph_empty = {}\"\n  \"edges graph_empty = {}\"\n  unfolding graph_empty_def by (auto)  \n  \n\n\nlemma edges_ins_edge_ss: \"edges g \\<subseteq> edges (ins_edge e g)\"  \n  by (auto simp: edges_ins_edge)\n  \n  \nlemma nodes_join[simp]: \"nodes (graph_join g\\<^sub>1 g\\<^sub>2) = nodes g\\<^sub>1 \\<union> nodes g\\<^sub>2\"  \n  and edges_join[simp]: \"edges (graph_join g\\<^sub>1 g\\<^sub>2) = edges g\\<^sub>1 \\<union> edges g\\<^sub>2\"\n  unfolding graph_join_def\n  by (auto simp: graph_accs dest: edges_sym')\n\nlemma nodes_restrict_nodes[simp]: \"nodes (restrict_nodes g V) = nodes g \\<inter> V\"  \n  and edges_restrict_nodes[simp]: \"edges (restrict_nodes g V) = edges g \\<inter> V\\<times>V\"\n  unfolding restrict_nodes_def\n  by (auto simp: graph_accs dest: edges_sym')\n  \nlemma nodes_restrict_edges[simp]: \"nodes (restrict_edges g E) = nodes g\"\n  and edges_restrict_edges[simp]: \"edges (restrict_edges g E) = edges g \\<inter> (E\\<union>E\\<inverse>)\"\n  unfolding restrict_edges_def\n  by (auto simp: graph_accs dest: edges_sym')\n\nlemma unrestricte_edges: \"edges (restrict_edges g E) \\<subseteq> edges g\" by auto\nlemma unrestrictn_edges: \"edges (restrict_nodes g V) \\<subseteq> edges g\" by auto\n\nlemma unrestrict_nodes: \"nodes (restrict_edges g E) \\<subseteq> nodes g\" by auto\n\n\n\nsubsection \\<open>Paths\\<close>  \n    \nfun path where\n  \"path g u [] v \\<longleftrightarrow> u=v\"  \n| \"path g u (e#ps) w \\<longleftrightarrow> (\\<exists>v. e=(u,v) \\<and> e\\<in>edges g \\<and> path g v ps w)\"  \n\nlemma path_emptyI[intro!]: \"path g u [] u\" by auto\n    \nlemma path_append[simp]: \n  \"path g u (p1@p2) w \\<longleftrightarrow> (\\<exists>v. path g u p1 v \\<and> path g v p2 w)\" \n  by (induction p1 arbitrary: u) auto\n\nlemma path_transs1[trans]:\n  \"path g u p v \\<Longrightarrow> (v,w)\\<in>edges g \\<Longrightarrow> path g u (p@[(v,w)]) w\"  \n  \"(u,v)\\<in>edges g \\<Longrightarrow> path g v p w \\<Longrightarrow> path g u ((u,v)#p) w\"\n  \"path g u p1 v \\<Longrightarrow> path g v p2 w \\<Longrightarrow> path g u (p1@p2) w\"\n  by auto\n  \nlemma path_graph_empty[simp]: \"path graph_empty u p v \\<longleftrightarrow> v=u \\<and> p=[]\" \n  by (cases p) auto\n\nabbreviation \"revp p \\<equiv> rev (map prod.swap p)\"\nlemma revp_alt: \"revp p = rev (map (\\<lambda>(u,v). (v,u)) p)\" by auto\n  \nlemma path_rev[simp]: \"path g u (revp p) v \\<longleftrightarrow> path g v p u\"  \n  by (induction p arbitrary: v) (auto dest: edges_sym')\n\nlemma path_rev_sym[sym]: \"path g v p u \\<Longrightarrow> path g u (revp p) v\" by simp \n\nlemma path_transs2[trans]: \n  \"path g u p v \\<Longrightarrow> (w,v)\\<in>edges g \\<Longrightarrow> path g u (p@[(v,w)]) w\"  \n  \"(v,u)\\<in>edges g \\<Longrightarrow> path g v p w \\<Longrightarrow> path g u ((u,v)#p) w\"\n  \"path g u p1 v \\<Longrightarrow> path g w p2 v \\<Longrightarrow> path g u (p1@revp p2) w\"\n  by (auto dest: edges_sym')\n\n  \nlemma path_edges: \"path g u p v \\<Longrightarrow> set p \\<subseteq> edges g\"\n  by (induction p arbitrary: u) auto\n\nlemma path_graph_cong: \n  \"\\<lbrakk>path g\\<^sub>1 u p v; set p \\<subseteq> edges g\\<^sub>1 \\<Longrightarrow> set p \\<subseteq> edges g\\<^sub>2\\<rbrakk> \\<Longrightarrow> path g\\<^sub>2 u p v\"\n  apply (frule path_edges; simp)\n  apply (induction p arbitrary: u) \n  by auto    \n  \n                \nlemma path_endpoints: \n  assumes \"path g u p v\" \"p\\<noteq>[]\" shows \"u\\<in>nodes g\" \"v\\<in>nodes g\"\n  subgoal using assms by (cases p) (auto intro: nodesI)\n  subgoal using assms by (cases p rule: rev_cases) (auto intro: nodesI)\n  done\n\nlemma path_mono: \"edges g \\<subseteq> edges g' \\<Longrightarrow> path g u p v \\<Longrightarrow> path g' u p v\"  \n  by (meson path_edges path_graph_cong subset_trans)\n\n  \n  \nlemmas unrestricte_path = path_mono[OF unrestricte_edges]\nlemmas unrestrictn_path = path_mono[OF unrestrictn_edges]\n\nlemma unrestrict_path_edges: \"path (restrict_edges g E) u p v \\<Longrightarrow> path g u p v\"  \n  by (induction p arbitrary: u) auto\n  \nlemma unrestrict_path_nodes: \"path (restrict_nodes g E) u p v \\<Longrightarrow> path g u p v\"  \n  by (induction p arbitrary: u) auto\n  \n      \n  \nsubsubsection \\<open>Paths and Connectedness\\<close>  \n  \nlemma rtrancl_edges_iff_path: \"(u,v)\\<in>(edges g)\\<^sup>* \\<longleftrightarrow> (\\<exists>p. path g u p v)\"\n  apply rule\n  subgoal\n    apply (induction rule: converse_rtrancl_induct)\n    by (auto dest: path_transs1)\n  apply clarify  \n  subgoal for p by (induction p arbitrary: u; force)\n  done  \n  \nlemma rtrancl_edges_pathE: \n  assumes \"(u,v)\\<in>(edges g)\\<^sup>*\" obtains p where \"path g u p v\"\n  using assms by (auto simp: rtrancl_edges_iff_path)\n\nlemma path_rtrancl_edgesD: \"path g u p v \\<Longrightarrow> (u,v)\\<in>(edges g)\\<^sup>*\"\n  by (auto simp: rtrancl_edges_iff_path)  \n      \n  \nsubsubsection \\<open>Simple Paths\\<close>  \n  \ndefinition \"uedge \\<equiv> \\<lambda>(a,b). {a,b}\"   \n  \ndefinition \"simple p \\<equiv> distinct (map uedge p)\"  \n\n\nlemma in_uedge_conv[simp]: \"x\\<in>uedge (u,v) \\<longleftrightarrow> x=u \\<or> x=v\"\n  by (auto simp: uedge_def)\n\nlemma uedge_eq_iff: \"uedge (a,b) = uedge (c,d) \\<longleftrightarrow> a=c \\<and> b=d \\<or> a=d \\<and> b=c\"\n  by (auto simp: uedge_def doubleton_eq_iff)\n  \nlemma uedge_degen[simp]: \"uedge (a,a) = {a}\"  \n  by (auto simp: uedge_def)\n\nlemma uedge_in_set_eq: \"uedge (u, v) \\<in> uedge ` S \\<longleftrightarrow> (u,v)\\<in>S \\<or> (v,u)\\<in>S\"  \n  by (auto simp: uedge_def doubleton_eq_iff)\n  \nlemma uedge_commute: \"uedge (a,b) = uedge (b,a)\" by auto \n      \nlemma simple_empty[simp]: \"simple []\"\n  by (auto simp: simple_def)\n\nlemma simple_cons[simp]: \"simple (e#p) \\<longleftrightarrow> uedge e \\<notin> uedge ` set p \\<and> simple p\"\n  by (auto simp: simple_def)\n\n\n\n  \nlemma simplify_pathD:\n  \"path g u p v \\<Longrightarrow> \\<exists>p'. path g u p' v \\<and> simple p' \\<and> set p' \\<subseteq> set p\"\nproof (induction p arbitrary: u v rule: length_induct)\n  case A: (1 p)\n  then show ?case proof (cases \"simple p\")\n    assume \"simple p\" with A.prems show ?case by blast\n  next\n    assume \"\\<not>simple p\"  \n    then consider p\\<^sub>1 a b p\\<^sub>2 p\\<^sub>3 where \"p=p\\<^sub>1@[(a,b)]@p\\<^sub>2@[(a,b)]@p\\<^sub>3\"\n                | p\\<^sub>1 a b p\\<^sub>2 p\\<^sub>3 where \"p=p\\<^sub>1@[(a,b)]@p\\<^sub>2@[(b,a)]@p\\<^sub>3\"\n      by (auto \n        simp: simple_def map_eq_append_conv uedge_eq_iff \n        dest!: not_distinct_decomp)\n    then obtain p' where \"path g u p' v\" \"length p' < length p\" \"set p' \\<subseteq> set p\"\n    proof cases\n      case [simp]: 1\n      from A.prems have \"path g u (p\\<^sub>1@[(a,b)]@p\\<^sub>3) v\" by auto\n      from that[OF this] show ?thesis by auto\n    next\n      case [simp]: 2\n      from A.prems have \"path g u (p\\<^sub>1@p\\<^sub>3) v\" by auto\n      from that[OF this] show ?thesis by auto\n    qed\n    with A.IH show ?thesis by blast\n  qed\nqed  \n    \nlemma simplify_pathE: \n  assumes \"path g u p v\" \n  obtains p' where \"path g u p' v\" \"simple p'\" \"set p' \\<subseteq> set p\"\n  using assms by (auto dest: simplify_pathD)\n   \n\nsubsubsection \\<open>Splitting Paths\\<close>  \n\nlemma find_crossing_edge_on_path:\n  assumes \"path g u p v\" \"\\<not>P u\" \"P v\"\n  obtains u' v' where \"(u',v')\\<in>set p\" \"\\<not>P u'\" \"P v'\"\n  using assms by (induction p arbitrary: u) auto\n  \nlemma find_crossing_edges_on_path:  \n  assumes P: \"path g u p v\" and \"P u\" \"P v\"\n  obtains \"\\<forall>(u,v)\\<in>set p. P u \\<and> P v\"\n        | u\\<^sub>1 v\\<^sub>1 v\\<^sub>2 u\\<^sub>2 p\\<^sub>1 p\\<^sub>2 p\\<^sub>3 \n          where \"p=p\\<^sub>1@[(u\\<^sub>1,v\\<^sub>1)]@p\\<^sub>2@[(u\\<^sub>2,v\\<^sub>2)]@p\\<^sub>3\" \"P u\\<^sub>1\" \"\\<not>P v\\<^sub>1\" \"\\<not>P u\\<^sub>2\" \"P v\\<^sub>2\"\nproof (cases \"\\<forall>(u,v)\\<in>set p. P u \\<and> P v\")\n  case True with that show ?thesis by blast\nnext\n  case False\n  with P \\<open>P u\\<close> have \"\\<exists>(u\\<^sub>1,v\\<^sub>1)\\<in>set p. P u\\<^sub>1 \\<and> \\<not>P v\\<^sub>1\"\n    apply clarsimp apply (induction p arbitrary: u) by auto\n  then obtain u\\<^sub>1 v\\<^sub>1 where \"(u\\<^sub>1,v\\<^sub>1)\\<in>set p\" and PRED1: \"P u\\<^sub>1\" \"\\<not>P v\\<^sub>1\" by blast\n  then obtain p\\<^sub>1 p\\<^sub>2\\<^sub>3 where [simp]: \"p=p\\<^sub>1@[(u\\<^sub>1,v\\<^sub>1)]@p\\<^sub>2\\<^sub>3\" \n    by (auto simp: in_set_conv_decomp)\n  with P have \"path g v\\<^sub>1 p\\<^sub>2\\<^sub>3 v\" by auto\n  from find_crossing_edge_on_path[where P=P, OF this \\<open>\\<not>P v\\<^sub>1\\<close> \\<open>P v\\<close>] obtain u\\<^sub>2 v\\<^sub>2 \n    where \"(u\\<^sub>2,v\\<^sub>2)\\<in>set p\\<^sub>2\\<^sub>3\" \"\\<not>P u\\<^sub>2\" \"P v\\<^sub>2\" .\n  then show thesis using PRED1\n    by (auto simp: in_set_conv_decomp intro: that)\nqed      \n  \nlemma find_crossing_edge_rtrancl:\n  assumes \"(u,v)\\<in>(edges g)\\<^sup>*\" \"\\<not>P u\" \"P v\"\n  obtains u' v' where \"(u',v')\\<in>edges g\" \"\\<not>P u'\" \"P v'\"\n  using assms\n  by (metis converse_rtrancl_induct)\n  \n\nlemma path_change: \n  assumes \"u\\<in>S\" \"v\\<notin>S\" \"path g u p v\" \"simple p\"\n  obtains x y p1 p2 where \n    \"(x,y) \\<in> set p\" \"x \\<in> S\" \"y \\<notin> S\"\n    \"path (restrict_edges g (-{(x,y),(y,x)})) u p1 x\" \n    \"path (restrict_edges g (-{(x,y),(y,x)})) y p2 v\"\nproof -\n  from find_crossing_edge_on_path[where P=\"\\<lambda>x. x\\<notin>S\"] assms obtain x y where \n    1: \"(x,y)\\<in>set p\" \"x\\<in>S\" \"y\\<notin>S\" by blast\n  then obtain p1 p2 where [simp]: \"p=p1@[(x,y)]@p2\" \n    by (auto simp: in_set_conv_decomp)\n  \n  let ?g' = \"restrict_edges g (-{(x,y),(y,x)})\"\n  \n  from \\<open>path g u p v\\<close> have P1: \"path g u p1 x\" and P2: \"path g y p2 v\" by auto\n  from \\<open>simple p\\<close> \n    have \"uedge (x,y)\\<notin>set (map uedge p1)\" \"uedge (x,y)\\<notin>set (map uedge p2)\" \n  by auto\n  then have \"path ?g' u p1 x\" \"path ?g' y p2 v\"  \n    using path_graph_cong[OF P1, of ?g'] path_graph_cong[OF P2, of ?g']\n    by (auto simp: uedge_in_set_eq)\n  with 1 show ?thesis by (blast intro: that)\nqed\n      \n\n\n\n\nsubsection \\<open>Cycles\\<close>      \n  \ndefinition \"cycle_free g \\<equiv> \\<nexists>p u. p\\<noteq>[] \\<and> simple p \\<and> path g u p u\"\n\nlemma cycle_free_alt_in_nodes: \n  \"cycle_free g \\<equiv> \\<nexists>p u. p\\<noteq>[] \\<and> u\\<in>nodes g \\<and> simple p \\<and> path g u p u\"\n  by (smt cycle_free_def path_endpoints(2))\n\nlemma cycle_freeI:\n  assumes \"\\<And>p u. \\<lbrakk> path g u p u; p\\<noteq>[]; simple p \\<rbrakk> \\<Longrightarrow> False\"\n  shows \"cycle_free g\"\n  using assms unfolding cycle_free_def by auto\n\nlemma cycle_freeD:\n  assumes \"cycle_free g\" \"path g u p u\" \"p\\<noteq>[]\" \"simple p\" \n  shows False\n  using assms unfolding cycle_free_def by auto\n\n  \nlemma cycle_free_antimono: \"edges g \\<subseteq> edges g' \\<Longrightarrow> cycle_free g' \\<Longrightarrow> cycle_free g\"\n  unfolding cycle_free_def\n  by (auto dest: path_mono)\n\nlemma cycle_free_empty[simp]: \"cycle_free graph_empty\" \n  unfolding cycle_free_def by auto\n  \nlemma cycle_free_no_edges: \"edges g = {} \\<Longrightarrow> cycle_free g\"\n  by (rule cycle_freeI) (auto simp: neq_Nil_conv)\n  \n\n\n  with Cons.IH[of u' p''] Cons.prems show ?case by simp \nqed    \n  \n              \n  \nsubsubsection \\<open>Characterization by Removing Edge\\<close>      \n\n\n\nlemma cycle_free_alt: \"cycle_free g \n  \\<longleftrightarrow> (\\<forall>e\\<in>edges g. e\\<notin>(edges (restrict_edges g (-{e,prod.swap e})))\\<^sup>*)\"\n  apply (rule)\n  apply (clarsimp simp del: edges_restrict_edges)\n  subgoal premises prems for u v proof -\n    note edges_restrict_edges[simp del]\n    let ?rg = \"(restrict_edges g (- {(u,v), (v,u)}))\"\n    from \\<open>(u, v) \\<in> (edges ?rg)\\<^sup>*\\<close>\n    obtain p where P: \"path ?rg u p v\" and \"simple p\" \n      by (auto simp: rtrancl_edges_iff_path elim: simplify_pathE)\n    from P have \"path g u p v\" by (rule unrestricte_path) \n    also note \\<open>(u, v) \\<in> edges g\\<close> finally have \"path g u (p @ [(v, u)]) u\" .\n    moreover from path_edges[OF P] have \"uedge (u,v) \\<notin> set (map uedge p)\" \n      by (auto simp: uedge_eq_iff edges_restrict_edges)\n    with \\<open>simple p\\<close> have \"simple (p @ [(v, u)])\"\n      by (auto simp: uedge_eq_iff uedge_in_set_eq)\n    ultimately show ?thesis using \\<open>cycle_free g\\<close>  \n      unfolding cycle_free_def by blast\n  qed\n  apply (clarsimp simp: cycle_free_def)\n  subgoal premises prems for p u proof -\n    from \\<open>p\\<noteq>[]\\<close> \\<open>path g u p u\\<close> obtain v p' where \n      [simp]: \"p=(u,v)#p'\" and \"(u,v)\\<in>edges g\" \"path g v p' u\" \n      by (cases p) auto\n    from \\<open>simple p\\<close> have \"simple p'\" \"uedge (u,v) \\<notin> set (map uedge p')\" by auto  \n    hence \"(u,v)\\<notin>set p'\" \"(v,u)\\<notin>set p'\" by (auto simp: uedge_in_set_eq)\n    with \\<open>path g v p' u\\<close> \n      have \"path (restrict_edges g (-{(u,v),(v,u)})) v p' u\" (is \"path ?rg _ _ _\")\n      by (erule_tac path_graph_cong) auto\n      \n    hence \"(u,v)\\<in>(edges ?rg)\\<^sup>*\"\n      by (meson path_rev rtrancl_edges_iff_path)  \n    with prems(1) \\<open>(u,v)\\<in>edges g\\<close> show False by auto\n  qed    \n  done\n  \nlemma cycle_free_altI:\n  assumes \"\\<And>u v. \\<lbrakk> (u,v)\\<in>edges g; (u,v)\\<in>(edges g - {(u,v),(v,u)})\\<^sup>* \\<rbrakk> \\<Longrightarrow> False\"\n  shows \"cycle_free g\"\n  unfolding cycle_free_alt using assms by (force)\n  \nlemma cycle_free_altD:  \n  assumes \"cycle_free g\"\n  assumes \"(u,v)\\<in>edges g\" \n  shows \"(u,v)\\<notin>(edges g - {(u,v),(v,u)})\\<^sup>*\"\n  using assms unfolding cycle_free_alt by (auto)\n  \n\n\nlemma remove_redundant_edge:\n  assumes \"(u, v) \\<in> (edges g - {(u, v), (v, u)})\\<^sup>*\"  \n  shows \"(edges g - {(u, v), (v, u)})\\<^sup>* = (edges g)\\<^sup>*\" (is \"?E'\\<^sup>* = _\")\nproof  \n  show \"?E'\\<^sup>* \\<subseteq> (edges g)\\<^sup>*\"\n    by (simp add: Diff_subset rtrancl_mono)\nnext\n  show \"(edges g)\\<^sup>* \\<subseteq> ?E'\\<^sup>*\"\n  proof clarify\n    fix a b assume \"(a,b)\\<in>(edges g)\\<^sup>*\" then \n    show \"(a,b)\\<in>?E'\\<^sup>*\"\n    proof induction\n      case base\n      then show ?case by simp\n    next\n      case (step b c)\n      then show ?case \n      proof (cases \"(b,c)\\<in>{(u,v),(v,u)}\")\n        case True\n\n        have SYME: \"sym (?E'\\<^sup>*)\"\n          apply (rule sym_rtrancl)\n          using edges_sym[of g] \n          by (auto simp: sym_def)\n        with step.IH assms have \n          IH': \"(b,a) \\<in> ?E'\\<^sup>*\"\n          by (auto intro: symD)\n        \n        from True show ?thesis apply safe\n          subgoal using assms step.IH by simp\n          subgoal using assms IH' apply (rule_tac symD[OF SYME]) by simp\n          done\n        \n      next\n        case False\n        then show ?thesis\n          by (meson DiffI rtrancl.rtrancl_into_rtrancl step.IH step.hyps(2))\n      qed \n        \n    qed\n  qed\nqed\n  \n  \n  \n  \n  \nsubsection \\<open>Connected Graphs\\<close>  \n  \n  \ndefinition connected \n  where \"connected g \\<equiv> nodes g \\<times> nodes g \\<subseteq> (edges g)\\<^sup>*\"  \n\nlemma connectedI[intro?]: \n  assumes \"\\<And>u v. \\<lbrakk>u\\<in>nodes g; v\\<in>nodes g\\<rbrakk> \\<Longrightarrow> (u,v)\\<in>(edges g)\\<^sup>*\"  \n  shows \"connected g\"\n  using assms unfolding connected_def by auto\n  \n\n\nsubsection \\<open>Component Containing Node\\<close>\ndefinition \"reachable_nodes g r \\<equiv> (edges g)\\<^sup>*``{r}\"\ndefinition \"component_of g r \n  \\<equiv> ins_node r (restrict_nodes g (reachable_nodes g r))\"\n\nlemma reachable_nodes_refl[simp, intro!]: \"r \\<in> reachable_nodes g r\" \n  by (auto simp: reachable_nodes_def)\n  \nlemma reachable_nodes_step: \n  \"edges g `` reachable_nodes g r \\<subseteq> reachable_nodes g r\"\n  by (auto simp: reachable_nodes_def)\n\nlemma reachable_nodes_steps: \n  \"(edges g)\\<^sup>* `` reachable_nodes g r \\<subseteq> reachable_nodes g r\"\n  by (auto simp: reachable_nodes_def)\n\nlemma reachable_nodes_step':\n  assumes \"u \\<in> reachable_nodes g r\" \"(u, v) \\<in> edges g\" \n  shows \"v\\<in>reachable_nodes g r\" \"(u, v) \\<in> edges (component_of g r)\" \nproof -\n  show \"v \\<in> reachable_nodes g r\"\n    by (meson ImageI assms(1) assms(2) reachable_nodes_step rev_subsetD)\n  then show \"(u, v) \\<in> edges (component_of g r)\"\n    by (simp add: assms(1) assms(2) component_of_def)\nqed\n  \nlemma reachable_nodes_steps':\n  assumes \"u \\<in> reachable_nodes g r\" \"(u, v) \\<in> (edges g)\\<^sup>*\" \n  shows \"v\\<in>reachable_nodes g r\" \"(u, v) \\<in> (edges (component_of g r))\\<^sup>*\" \nproof -\n  show \"v\\<in>reachable_nodes g r\" using reachable_nodes_steps assms by fast\n  show \"(u, v) \\<in> (edges (component_of g r))\\<^sup>*\"\n    using assms(2,1)\n    apply (induction rule: converse_rtrancl_induct)\n    subgoal by auto\n    subgoal by (smt converse_rtrancl_into_rtrancl reachable_nodes_step')\n    done\nqed\n   \nlemma reachable_not_node: \"r\\<notin>nodes g \\<Longrightarrow> reachable_nodes g r = {r}\"\n  by (force elim: converse_rtranclE simp: reachable_nodes_def intro: nodesI)\n   \n  \nlemma nodes_of_component[simp]: \"nodes (component_of g r) = reachable_nodes g r\"\n  apply (rule equalityI)\n  unfolding component_of_def reachable_nodes_def\n  subgoal by auto\n  subgoal by clarsimp (metis nodesI(2) rtranclE)\n  done\n\nlemma component_connected[simp, intro!]: \"connected (component_of g r)\"\nproof (rule connectedI; simp)\n  fix u v\n  assume A: \"u \\<in> reachable_nodes g r\" \"v \\<in> reachable_nodes g r\"\n  hence \"(u,r)\\<in>(edges g)\\<^sup>*\" \"(r,v)\\<in>(edges g)\\<^sup>*\" \n    by (auto simp: reachable_nodes_def dest: rtrancl_edges_sym')\n  hence \"(u,v)\\<in>(edges g)\\<^sup>*\" by (rule rtrancl_trans)\n  with A show \"(u, v) \\<in> (edges (component_of g r))\\<^sup>*\" \n    by (rule_tac reachable_nodes_steps'(2))\nqed  \n\nlemma component_edges_subset: \"edges (component_of g r) \\<subseteq> edges g\"  \n  by (auto simp: component_of_def)\n\nlemma component_path: \"u\\<in>nodes (component_of g r) \\<Longrightarrow> \n  path (component_of g r) u p v \\<longleftrightarrow> path g u p v\"  \n  apply rule\n  subgoal by (erule path_mono[OF component_edges_subset])     \n  subgoal by (induction p arbitrary: u) (auto simp: reachable_nodes_step')\n  done  \n  \nlemma component_cycle_free: \"cycle_free g \\<Longrightarrow> cycle_free (component_of g r)\"  \n  by (meson component_edges_subset cycle_free_antimono)\n  \nlemma component_of_connected_graph: \n  \"\\<lbrakk>connected g; r\\<in>nodes g\\<rbrakk> \\<Longrightarrow> component_of g r = g\"  \n  unfolding graph_eq_iff \n  apply safe\n  subgoal by simp (metis Image_singleton_iff nodesI(2) reachable_nodes_def rtranclE)\n  subgoal by (simp add: connectedD reachable_nodes_def)\n  subgoal by (simp add: component_of_def)\n  subgoal by (simp add: connectedD reachable_nodes_def reachable_nodes_step'(2))\n  done\n\nlemma component_of_not_node: \"r\\<notin>nodes g \\<Longrightarrow> component_of g r = graph {r} {}\"\n  by (clarsimp simp: graph_eq_iff component_of_def reachable_not_node graph_accs)\n\n      \nsubsection \\<open>Trees\\<close>\n\ndefinition \"tree g \\<equiv> connected g \\<and> cycle_free g \"    \n\nlemma tree_empty[simp]: \"tree graph_empty\" by (simp add: tree_def)\n\nlemma component_of_tree: \"tree T \\<Longrightarrow> tree (component_of T r)\"\n  unfolding tree_def using component_connected component_cycle_free by auto\n\n\nsubsubsection \\<open>Joining and Splitting Trees on Single Edge\\<close>\n      \nlemma join_connected:\n  assumes CONN: \"connected g\\<^sub>1\" \"connected g\\<^sub>2\"\n  assumes IN_NODES: \"u\\<in>nodes g\\<^sub>1\" \"v\\<in>nodes g\\<^sub>2\"\n  shows \"connected (ins_edge (u,v) (graph_join g\\<^sub>1 g\\<^sub>2))\" (is \"connected ?g'\") \n  unfolding connected_def\nproof clarify\n  fix a b\n  assume A: \"a\\<in>nodes ?g'\" \"b\\<in>nodes ?g'\"\n  \n  have ESS: \"(edges g\\<^sub>1)\\<^sup>* \\<subseteq> (edges ?g')\\<^sup>*\" \"(edges g\\<^sub>2)\\<^sup>* \\<subseteq> (edges ?g')\\<^sup>*\"\n    using edges_ins_edge_ss\n    by (force intro!: rtrancl_mono)+\n  \n  have UV: \"(u,v)\\<in>(edges ?g')\\<^sup>*\"\n    by (simp add: edges_ins_edge r_into_rtrancl)\n    \n  show \"(a,b)\\<in>(edges ?g')\\<^sup>*\"\n  proof -\n    {\n      assume \"a\\<in>nodes g\\<^sub>1\" \"b\\<in>nodes g\\<^sub>1\"\n      hence ?thesis using \\<open>connected g\\<^sub>1\\<close> ESS(1) unfolding connected_def by blast\n    } moreover {\n      assume \"a\\<in>nodes g\\<^sub>2\" \"b\\<in>nodes g\\<^sub>2\"\n      hence ?thesis using \\<open>connected g\\<^sub>2\\<close> ESS(2) unfolding connected_def by blast\n    } moreover {\n      assume \"a\\<in>nodes g\\<^sub>1\" \"b\\<in>nodes g\\<^sub>2\"\n      with connectedD[OF CONN(1)] connectedD[OF CONN(2)] ESS\n      have ?thesis by (meson UV IN_NODES contra_subsetD rtrancl_trans)\n    } moreover {\n      assume \"a\\<in>nodes g\\<^sub>2\" \"b\\<in>nodes g\\<^sub>1\"\n      with connectedD[OF CONN(1)] connectedD[OF CONN(2)] ESS\n      have ?thesis\n        by (meson UV IN_NODES contra_subsetD rtrancl_edges_sym' rtrancl_trans)\n    }\n    ultimately show ?thesis using A IN_NODES by auto\n  qed    \nqed\n  \n  \nlemma join_cycle_free:  \n  assumes CYCF: \"cycle_free g\\<^sub>1\" \"cycle_free g\\<^sub>2\"\n  assumes DJ: \"nodes g\\<^sub>1 \\<inter> nodes g\\<^sub>2 = {}\"\n  assumes IN_NODES: \"u\\<in>nodes g\\<^sub>1\" \"v\\<in>nodes g\\<^sub>2\"\n  shows \"cycle_free (ins_edge (u,v) (graph_join g\\<^sub>1 g\\<^sub>2))\" (is \"cycle_free ?g'\") \nproof (rule cycle_freeI)\n  fix p a\n  assume P: \"path ?g' a p a\" \"p\\<noteq>[]\" \"simple p\"\n  from path_endpoints[OF this(1,2)] IN_NODES \n    have A_NODE: \"a\\<in>nodes g\\<^sub>1 \\<union> nodes g\\<^sub>2\" \n    by auto\n  thus False proof \n    assume N1: \"a\\<in>nodes g\\<^sub>1\"\n    have \"set p \\<subseteq> nodes g\\<^sub>1 \\<times> nodes g\\<^sub>1\"\n    proof (cases \n      rule: find_crossing_edges_on_path[where P=\"\\<lambda>x. x\\<in>nodes g\\<^sub>1\", OF P(1) N1 N1])\n      case 1\n      then show ?thesis by auto\n    next\n      case (2 u\\<^sub>1 v\\<^sub>1 v\\<^sub>2 u\\<^sub>2 p\\<^sub>1 p\\<^sub>2 p\\<^sub>3)\n      then show ?thesis using \\<open>simple p\\<close> P\n        apply clarsimp\n        apply (drule path_edges)+\n        apply (cases \"u=v\"; clarsimp simp: edges_ins_edge uedge_in_set_eq)\n        apply (metis DJ IntI IN_NODES empty_iff)\n        by (metis DJ IntI empty_iff nodesI uedge_eq_iff)\n        \n    qed\n    hence \"set p \\<subseteq> edges g\\<^sub>1\" using DJ edges_subset path_edges[OF P(1)] IN_NODES\n      by (auto simp: edges_ins_edge split: if_splits; blast)\n    hence \"path g\\<^sub>1 a p a\" by (meson P(1) path_graph_cong)\n    thus False using cycle_freeD[OF CYCF(1)] P(2,3) by blast\n  next\n    assume N2: \"a\\<in>nodes g\\<^sub>2\"\n    have \"set p \\<subseteq> nodes g\\<^sub>2 \\<times> nodes g\\<^sub>2\"\n    proof (cases \n      rule: find_crossing_edges_on_path[where P=\"\\<lambda>x. x\\<in>nodes g\\<^sub>2\", OF P(1) N2 N2])\n      case 1\n      then show ?thesis by auto\n    next\n      case (2 u\\<^sub>1 v\\<^sub>1 v\\<^sub>2 u\\<^sub>2 p\\<^sub>1 p\\<^sub>2 p\\<^sub>3)\n      then show ?thesis using \\<open>simple p\\<close> P\n        apply clarsimp\n        apply (drule path_edges)+\n        apply (cases \"u=v\"; clarsimp simp: edges_ins_edge uedge_in_set_eq)\n        apply (metis DJ IntI IN_NODES empty_iff)\n        by (metis DJ IntI empty_iff nodesI uedge_eq_iff)\n        \n    qed\n    hence \"set p \\<subseteq> edges g\\<^sub>2\" using DJ edges_subset path_edges[OF P(1)] IN_NODES\n      by (auto simp: edges_ins_edge split: if_splits; blast)\n    hence \"path g\\<^sub>2 a p a\" by (meson P(1) path_graph_cong)\n    thus False using cycle_freeD[OF CYCF(2)] P(2,3) by blast\n  qed\nqed\n      \nlemma join_trees:     \n  assumes TREE: \"tree g\\<^sub>1\" \"tree g\\<^sub>2\"\n  assumes DJ: \"nodes g\\<^sub>1 \\<inter> nodes g\\<^sub>2 = {}\"\n  assumes IN_NODES: \"u\\<in>nodes g\\<^sub>1\" \"v\\<in>nodes g\\<^sub>2\"\n  shows \"tree (ins_edge (u,v) (graph_join g\\<^sub>1 g\\<^sub>2))\"\n  using assms join_cycle_free join_connected unfolding tree_def by metis \n  \n  \nlemma split_tree:\n  assumes \"tree T\" \"(x,y)\\<in>edges T\"\n  defines \"E' \\<equiv> (edges T - {(x,y),(y,x)})\"\n  obtains T1 T2 where \n    \"tree T1\" \"tree T2\" \n    \"nodes T1 \\<inter> nodes T2 = {}\" \"nodes T = nodes T1 \\<union> nodes T2\"\n    \"edges T1 \\<union> edges T2 = E'\"\n    \"nodes T1 = { u. (x,u)\\<in>E'\\<^sup>*}\" \"nodes T2 = { u. (y,u)\\<in>E'\\<^sup>*}\"\n    \"x\\<in>nodes T1\" \"y\\<in>nodes T2\"\nproof -\n  (* TODO: Use component_of here! *)\n  define N1 where \"N1 = { u. (x,u)\\<in>E'\\<^sup>* }\"\n  define N2 where \"N2 = { u. (y,u)\\<in>E'\\<^sup>* }\"\n\n  define T1 where \"T1 = restrict_nodes T N1\"\n  define T2 where \"T2 = restrict_nodes T N2\"\n  \n  have SYME: \"sym (E'\\<^sup>*)\"\n    apply (rule sym_rtrancl) \n    using edges_sym[of T] by (auto simp: sym_def E'_def)\n  \n\n  from assms have \"connected T\" \"cycle_free T\" unfolding tree_def by auto\n  from \\<open>cycle_free T\\<close> have \"cycle_free T1\" \"cycle_free T2\"\n    unfolding T1_def T2_def\n    using cycle_free_antimono unrestrictn_edges by blast+\n\n  from \\<open>(x,y) \\<in> edges T\\<close> have XYN: \"x\\<in>nodes T\" \"y\\<in>nodes T\" \n    using edges_subset by auto\n  from XYN have [simp]: \"nodes T1 = N1\" \"nodes T2 = N2\" \n    unfolding T1_def T2_def N1_def N2_def unfolding E'_def\n    apply (safe)\n    apply (all \\<open>clarsimp\\<close>)\n    by (metis DiffD1 nodesI(2) rtrancl.simps)+\n  \n  have \"x\\<in>N1\" \"y\\<in>N2\" by (auto simp: N1_def N2_def)   \n  \n  have \"N1 \\<inter> N2 = {}\" \n  proof (safe;simp)\n    fix u\n    assume \"u\\<in>N1\" \"u\\<in>N2\"\n    hence \"(x,u)\\<in>E'\\<^sup>*\" \"(u,y)\\<in>E'\\<^sup>*\" by (auto simp: N1_def N2_def symD[OF SYME])\n    with cycle_free_altD[OF \\<open>cycle_free T\\<close> \\<open>(x,y)\\<in>edges T\\<close>] show False \n      unfolding E'_def by (meson rtrancl_trans)\n  qed\n\n  \n  have N1C: \"E'``N1 \\<subseteq> N1\"\n    unfolding N1_def\n    apply clarsimp \n    by (simp add: rtrancl.rtrancl_into_rtrancl)\n  \n  have N2C: \"E'``N2 \\<subseteq> N2\"\n    unfolding N2_def\n    apply clarsimp \n    by (simp add: rtrancl.rtrancl_into_rtrancl)\n\n  have XE1: \"(x,u) \\<in> (edges T1)\\<^sup>*\" if \"u\\<in>N1\" for u\n  proof -\n    from that have \"(x,u)\\<in>E'\\<^sup>*\" by (auto simp: N1_def)\n    then show ?thesis using \\<open>x\\<in>N1\\<close> \n      unfolding T1_def\n    proof (induction rule: converse_rtrancl_induct)\n      case (step y z)\n      with N1C have \"z\\<in>N1\" by auto\n      with step.hyps(1) step.prems have \"(y,z)\\<in>Restr (edges T) N1\" \n        unfolding E'_def by auto\n      with step.IH[OF \\<open>z\\<in>N1\\<close>] show ?case \n        by (metis converse_rtrancl_into_rtrancl edges_restrict_nodes)\n    qed auto\n  qed    \n  \n  have XE2: \"(y,u) \\<in> (edges T2)\\<^sup>*\" if \"u\\<in>N2\" for u\n  proof -\n    from that have \"(y,u)\\<in>E'\\<^sup>*\" by (auto simp: N2_def)\n    then show ?thesis using \\<open>y\\<in>N2\\<close> \n      unfolding T2_def\n    proof (induction rule: converse_rtrancl_induct)\n      case (step y z)\n      with N2C have \"z\\<in>N2\" by auto\n      with step.hyps(1) step.prems have \"(y,z)\\<in>Restr (edges T) N2\" \n        unfolding E'_def by auto\n      with step.IH[OF \\<open>z\\<in>N2\\<close>] show ?case \n        by (metis converse_rtrancl_into_rtrancl edges_restrict_nodes)\n    qed auto\n  qed    \n  \n  \n  have \"connected T1\" \n    apply rule\n    apply simp\n    apply (drule XE1)+\n    by (meson rtrancl_edges_sym' rtrancl_trans)      \n  \n  have \"connected T2\" \n    apply rule\n    apply simp\n    apply (drule XE2)+\n    by (meson rtrancl_edges_sym' rtrancl_trans)      \n   \n  have \"u\\<in>N1 \\<union> N2\" if \"u\\<in>nodes T\" for u \n  proof -\n    from connectedD[OF \\<open>connected T\\<close> \\<open>x\\<in>nodes T\\<close> that ]\n    obtain p where P: \"path T x p u\" \"simple p\" \n      by (auto simp: rtrancl_edges_iff_path elim: simplify_pathE)\n    show ?thesis proof cases\n      assume \"(x,y)\\<notin>set p \\<and> (y,x)\\<notin>set p\"\n      with P(1) have \"path (restrict_edges T E') x p u\" \n        unfolding E'_def by (erule_tac path_graph_cong) auto\n      from path_rtrancl_edgesD[OF this]\n      show ?thesis unfolding N1_def E'_def by auto\n    next\n      assume \"\\<not>((x,y)\\<notin>set p \\<and> (y,x)\\<notin>set p)\"\n      with P obtain p' where \n        \"uedge (x,y)\\<notin>set (map uedge p')\" \"path T y p' u \\<or> path T x p' u\"\n        by (auto simp: in_set_conv_decomp uedge_commute)\n      hence \"path (restrict_edges T E') y p' u \\<or> path (restrict_edges T E') x p' u\"  \n        apply (clarsimp simp: uedge_in_set_eq E'_def)\n        by (smt ComplD DiffI Int_iff UnCI edges_restrict_edges insertE \n                path_graph_cong subset_Compl_singleton subset_iff)\n      then show ?thesis unfolding N1_def N2_def E'_def \n        by (auto dest: path_rtrancl_edgesD)\n    qed\n  qed\n  then have \"nodes T = N1 \\<union> N2\" \n    unfolding N1_def N2_def using XYN\n    unfolding E'_def\n    apply (safe)\n    subgoal by auto []\n    subgoal by (metis DiffD1 nodesI(2) rtrancl.cases)\n    subgoal by (metis DiffD1 nodesI(2) rtrancl.cases)\n    done\n\n  have \"edges T1 \\<union> edges T2 \\<subseteq> E'\"\n    unfolding T1_def T2_def E'_def using \\<open>N1 \\<inter> N2 = {}\\<close> \\<open>x \\<in> N1\\<close> \\<open>y \\<in> N2\\<close> \n    by auto  \n  also have \"edges T1 \\<union> edges T2 \\<supseteq> E'\"\n  proof -\n    note ED1 = nodesI[where g=T, unfolded \\<open>nodes T = N1\\<union>N2\\<close>]  \n    have \"E' \\<subseteq> edges T\" by (auto simp: E'_def)\n    thus \"edges T1 \\<union> edges T2 \\<supseteq> E'\"\n      unfolding T1_def T2_def\n      using ED1 N1C N2C by (auto; blast)\n  qed \n  finally have \"edges T1 \\<union> edges T2 = E'\" .  \n          \n  show ?thesis\n    apply (rule that[of T1 T2, unfolded tree_def]; (intro conjI)?; fact?)\n    apply simp_all\n    apply fact+\n    done\nqed\n  \n  \n  \n  \nsubsection \\<open>Spanning Trees\\<close>    \n                                    \ndefinition \"is_spanning_tree G T \n  \\<equiv> tree T \\<and> nodes T = nodes G \\<and> edges T \\<subseteq> edges G\"    \n  \n(* TODO: Move *)\nlemma connected_singleton[simp]: \"connected (ins_node u graph_empty)\"\n  unfolding connected_def by auto\n  \nlemma path_singleton[simp]: \"path (ins_node u graph_empty) v p w \\<longleftrightarrow> v=w \\<and> p=[]\"  \n  by (cases p) auto\n\nlemma tree_singleton[simp]: \"tree (ins_node u graph_empty)\"\n  by (simp add: cycle_free_no_edges tree_def)\n\n(* TODO: Move *)\nlemma tree_add_edge_in_out:\n  assumes \"tree T\"\n  assumes \"u\\<in>nodes T\" \"v\\<notin>nodes T\"\n  shows \"tree (ins_edge (u,v) T)\"\nproof -\n  from assms have [simp]: \"u\\<noteq>v\" by auto\n  have \"ins_edge (u,v) T = ins_edge (u,v) (graph_join T (ins_node v graph_empty))\"\n    by (auto simp: graph_eq_iff)\n  also have \"tree \\<dots>\"\n    apply (rule join_trees)\n    using assms\n    by auto\n  finally show ?thesis .\nqed\n  \ntext \\<open>Remove edges on cycles until the graph is cycle free\\<close>\nlemma ex_spanning_tree: \n  \"connected g \\<Longrightarrow> \\<exists>t. is_spanning_tree g t\"\n  using edges_finite[of g]\nproof (induction \"edges g\" arbitrary: g rule: finite_psubset_induct)\n  case psubset\n  show ?case proof (cases \"cycle_free g\")\n    case True \n    with \\<open>connected g\\<close> show ?thesis by (auto simp: is_spanning_tree_def tree_def)\n  next\n    case False \n    then obtain u v where \n          EDGE: \"(u,v)\\<in>edges g\" \n      and RED: \"(u,v)\\<in>(edges g - {(u,v),(v,u)})\\<^sup>*\" \n      using cycle_free_altI by metis\n    from \\<open>connected g\\<close> \n      have \"connected (restrict_edges g (- {(u,v),(v,u)}))\" (is \"connected ?g'\")\n      unfolding connected_def\n      by (auto simp: remove_redundant_edge[OF RED])\n    moreover have \"edges ?g' \\<subset> edges g\" using EDGE by auto\n    ultimately obtain t where \"is_spanning_tree ?g' t\" \n      using psubset.hyps(2)[of ?g'] by blast\n    hence \"is_spanning_tree g t\" by (auto simp: is_spanning_tree_def)\n    thus ?thesis ..\n  qed\nqed\n  \n\nsection \\<open>Weighted Undirected Graphs\\<close>\n\ndefinition weight :: \"('v set \\<Rightarrow> nat) \\<Rightarrow> 'v ugraph \\<Rightarrow> nat\" \n  where \"weight w g \\<equiv> (\\<Sum>e\\<in>edges g. w (uedge e)) div 2\"\n\n  \nlemma weight_alt: \"weight w g = (\\<Sum>e\\<in>uedge`edges g. w e)\"  \nproof -\n  from split_edges_sym[of g] obtain E where \n    \"edges g = E \\<union> E\\<inverse>\" and \"E\\<inter>E\\<inverse>={}\" by auto\n  hence [simp, intro!]: \"finite E\" by (metis edges_finite finite_Un) \n  hence [simp, intro!]: \"finite (E\\<inverse>)\" by blast\n\n  have [simp]: \"(\\<Sum>e\\<in>E\\<inverse>. w (uedge e)) = (\\<Sum>e\\<in>E. w (uedge e))\"\n    apply (rule sum.reindex_cong[where l=prod.swap and A=\"E\\<inverse>\" and B=\"E\"])\n    by (auto simp: uedge_def insert_commute)\n\n  have [simp]: \"inj_on uedge E\" using \\<open>E\\<inter>E\\<inverse>=_\\<close>\n    by (auto simp: uedge_def inj_on_def doubleton_eq_iff)\n        \n  have \"weight w g = (\\<Sum>e\\<in>E. w (uedge e))\"\n    unfolding weight_def \\<open>edges g = _\\<close> using \\<open>E\\<inter>E\\<inverse>={}\\<close>\n    by (auto simp: sum.union_disjoint)\n  also have \"\\<dots> = (\\<Sum>e\\<in>uedge`E. w e)\" \n    using sum.reindex[of uedge E w]\n    by auto \n  also have \"uedge`E = uedge`(edges g)\"  \n    unfolding \\<open>edges g = _\\<close> uedge_def using \\<open>E\\<inter>E\\<inverse>={}\\<close>\n    by auto\n  finally show ?thesis .\nqed \n\nlemma weight_empty[simp]: \"weight w graph_empty = 0\" unfolding weight_def by auto\n  \nlemma weight_ins_edge[simp]: \"\\<lbrakk>u\\<noteq>v; (u,v)\\<notin>edges g\\<rbrakk> \n  \\<Longrightarrow> weight w (ins_edge (u,v) g) = w {u,v} + weight w g\"\n  unfolding weight_def\n  apply clarsimp\n  apply (subst sum.insert)\n  by (auto dest: edges_sym' simp: uedge_def insert_commute)\n\nlemma uedge_img_disj_iff[simp]: \n  \"uedge`edges g\\<^sub>1 \\<inter> uedge`edges g\\<^sub>2 = {} \\<longleftrightarrow> edges g\\<^sub>1 \\<inter> edges g\\<^sub>2 = {}\"\n  by (auto simp: uedge_eq_iff dest: edges_sym')+  \n  \nlemma weight_join[simp]: \"edges g\\<^sub>1 \\<inter> edges g\\<^sub>2 = {} \n  \\<Longrightarrow> weight w (graph_join g\\<^sub>1 g\\<^sub>2) = weight w g\\<^sub>1 + weight w g\\<^sub>2\"  \n  unfolding weight_alt by (auto simp: sum.union_disjoint image_Un)\n\nlemma weight_cong: \"edges g\\<^sub>1 = edges g\\<^sub>2 \\<Longrightarrow> weight w g\\<^sub>1 = weight w g\\<^sub>2\"  \n  by (auto simp: weight_def)\n\nlemma weight_mono: \"edges g \\<subseteq> edges g' \\<Longrightarrow> weight w g \\<le> weight w g'\"\n  unfolding weight_alt by (rule sum_mono2) auto\n  \nlemma weight_ge_edge:\n  assumes \"(x,y)\\<in>edges T\"\n  shows \"weight w T \\<ge> w {x,y}\"\n  using assms unfolding weight_alt\n  by (auto simp: uedge_def intro: member_le_sum)\n  \n  \n          \nlemma weight_del_edge[simp]: \n  assumes \"(x,y)\\<in>edges T\"  \n  shows \"weight w (restrict_edges T (- {(x, y), (y, x)})) = weight w T - w {x,y}\"\nproof -\n  define E where \"E = uedge ` edges T - {{x,y}}\"\n  have [simp]: \"(uedge ` (edges T - {(x, y), (y, x)})) = E\"  \n    by (safe; simp add: E_def uedge_def doubleton_eq_iff; blast)\n    \n  from assms have [simp]: \"uedge ` edges T = insert {x,y} E\"\n    unfolding E_def by force\n\n  have [simp]: \"{x,y}\\<notin>E\" unfolding E_def by blast        \n\n  then show ?thesis\n    unfolding weight_alt\n    apply simp\n    by (metis E_def \\<open>uedge ` edges T = insert {x, y} E\\<close> insertI1 sum_diff1_nat)\nqed    \n  \n        \nsubsection \\<open>Minimum Spanning Trees\\<close>\n\ndefinition \"is_MST w g t \\<equiv> is_spanning_tree g t \n  \\<and> (\\<forall>t'. is_spanning_tree g t' \\<longrightarrow> weight w t \\<le> weight w t')\"  \n\nlemma exists_MST: \"connected g \\<Longrightarrow> \\<exists>t. is_MST w g t\"\n  using ex_has_least_nat[of \"is_spanning_tree g\"] ex_spanning_tree \n  unfolding is_MST_def \n  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/Prim_Dijkstra_Simple/Undirected_Graph.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8740772318846386, "lm_q2_score": 0.8221891327004133, "lm_q1q2_score": 0.7186568011964091}}
{"text": "theory SmallListDemo\nimports \"$HIPSTER_HOME/IsaHipster\"\nbegin\n\ndatatype 'a Lst = \n  Emp\n  | Cons \"'a\" \"'a Lst\"\n\nfun app :: \"'a Lst \\<Rightarrow> 'a Lst \\<Rightarrow> 'a Lst\" \nwhere \n  \"app Emp xs = xs\"\n| \"app (Cons x xs) ys = Cons x (app xs ys)\"\n\nhipster app\nlemma lemma_a [thy_expl]: \"app y Emp = y\"\n  apply (induct y)\n  by simp_all\n    \nlemma lemma_aa [thy_expl]: \"app (app y z) x2 = app y (app z x2)\"\n  apply (induct y arbitrary: x2 z)\n  by simp_all\n\nfun len ::  \"'a Lst \\<Rightarrow> nat\"\nwhere\n  \"len Emp = 0\"\n| \"len (Cons x xs) = 1 + (len xs)\"  \n\n(* hipster app len *)\nlemma lemma_ab [thy_expl]: \"len y + len z = len (app y z)\"\n  apply (induct y arbitrary: z)\n  by simp_all\n\nfun rev :: \"'a Lst \\<Rightarrow> 'a Lst\"\nwhere \n  \"rev Emp = Emp\"\n| \"rev (Cons x xs) = app (rev xs) (Cons x Emp)\"\n\n(*hipster rev len *)\nlemma lemma_ac [thy_expl]: \"app (SmallListDemo.rev z) (SmallListDemo.rev y) =\nSmallListDemo.rev (app y z)\"\n  apply hipster_induct\n  apply (induct y arbitrary: z)\n  apply (simp_all add: lemma_a)\n  by (metis lemma_aa)\n    \nlemma lemma_ad [thy_expl]: \"len (SmallListDemo.rev y) = len y\"\n  apply (induct y)\n  apply simp_all\n  by (metis One_nat_def Suc_eq_plus1 Suc_eq_plus1_left lemma_ab len.simps(1) len.simps(2))\n    \nlemma lemma_ae [thy_expl]: \"SmallListDemo.rev (SmallListDemo.rev y) = y\"\n  apply (induct y)\n  apply simp_all\n  by (metis Lst.distinct(1) SmallListDemo.rev.simps(1) SmallListDemo.rev.simps(2) app.elims app.simps(2) lemma_ac)\n\n\nfun filt :: \"('a \\<Rightarrow> bool) \\<Rightarrow> 'a Lst \\<Rightarrow> 'a Lst\" \nwhere \n  \"filt p Emp = Emp\"\n| \"filt p (Cons x xs) = (if (p x) then (Cons x (filt p xs)) else (filt p xs))\"\n\nhipster app filt\nlemma lemma_af [thy_expl]: \"filt y (filt y z) = filt y z\"\n  apply (induct z)\n  by simp_all\n    \nlemma lemma_ag [thy_expl]: \"filt z (filt y x2) = filt y (filt z x2)\"\n  apply (induct x2)\n  by simp_all\n    \nlemma lemma_ah [thy_expl]: \"app (filt y z) (filt y x2) = filt y (app z x2)\"\n  apply (induct z arbitrary: x2)\n  by simp_all\n\n\n\nfun mem :: \"'a \\<Rightarrow> 'a Lst \\<Rightarrow> bool\"\nwhere\n  \"mem x Emp = False\"\n| \"mem x (Cons y ys) = ((x=y) \\<or> (mem x ys))\"\n\n\nhipster mem rev\nlemma lemma_ai [thy_expl]: \"mem y (app x2 (Lst.Cons z x3)) = mem y (Lst.Cons z (app x2 x3))\"\n  apply (induct x2 arbitrary: x3)\n  apply simp_all\n  by auto\n    \nlemma lemma_aj [thy_expl]: \"mem y (app z (app z x2)) = mem y (app z x2)\"\n  apply (induct z arbitrary: x2)\n  by (simp_all add: lemma_ai)\n    \nlemma lemma_ak [thy_expl]: \"mem y (app z (app x3 x2)) = mem y (app z (app x2 x3))\"\n  apply (induct x2 arbitrary: x3 z)\n  apply (simp_all add: lemma_a)\n  by (metis lemma_aa lemma_ai mem.simps(2))\n    \nlemma lemma_al [thy_expl]: \"mem y (SmallListDemo.rev z) = mem y z\"\n  apply (induct z)\n  by (simp_all add: lemma_a lemma_ai)\n    \nlemma lemma_am [thy_expl]: \"mem y (app z (SmallListDemo.rev x2)) = mem y (app z x2)\"\n  apply (induct x2 arbitrary: z)\n  apply simp_all\n  by (smt SmallListDemo.rev.simps(2) app.simps(2) lemma_ac lemma_ae lemma_ai lemma_al mem.simps(2))\n\n\n\n\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/Examples/SmallListDemo.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392848011834, "lm_q2_score": 0.8128673178375734, "lm_q1q2_score": 0.7186066422993846}}
{"text": "theory Ex20 \nimports Main \nbegin \n\n(*distributivity of \"or\" over \"and\"*)\nlemma \"A \\<or> (B \\<and> C) \\<longleftrightarrow> (A \\<or> B) \\<and> (A \\<or> C)\"\nproof - \n{\n  assume \"A \\<or> (B \\<and> C)\"\n  {\n    assume A \n    hence \"A \\<or> B\" by (rule disjI1)\n    from \\<open>A\\<close> have \"A \\<or> C\" by (rule disjI1)\n    with \\<open>A \\<or> B\\<close> have \"(A \\<or> B) \\<and> (A \\<or> C)\" by (rule conjI)\n  }\n  moreover \n  {\n    assume \"B \\<and> C\"\n    hence C by (rule conjE)\n    from \\<open>B \\<and> C\\<close> have B by (rule conjE)\n    hence \"A \\<or> B\" by (rule disjI2)\n    from \\<open>C\\<close> have \"A \\<or> C\" by (rule disjI2)\n    with \\<open>A \\<or> B\\<close> have \"(A \\<or> B) \\<and> (A \\<or> C)\" by (rule conjI)\n  }\n  from \\<open>A \\<or> (B \\<and> C)\\<close> and  calculation and this have \" (A \\<or> B) \\<and> (A \\<or> C)\" by (rule disjE)\n}\nmoreover\n{\n  assume \"(A \\<or> B) \\<and> (A \\<or> C)\"\n  hence \"(A \\<or> B)\" by (rule conjE)\n  from \\<open>(A \\<or> B) \\<and> (A \\<or> C)\\<close> have \"(A \\<or> C)\" by (rule conjE)\n  {\n    assume A \n    hence \"A \\<or> (B \\<and> C)\" by (rule disjI1)\n  }\n  moreover\n  {\n    assume C\n    {\n      assume A \n      hence \"A \\<or> (B \\<and> C)\" by (rule disjI1)\n    }\n    moreover\n    {\n      assume B\n      from this and  \\<open>C\\<close> have \"B \\<and> C\" by (rule conjI)\n      hence  \"A \\<or> (B \\<and> C)\" by (rule disjI2)\n    }\n    from \\<open>A \\<or> B\\<close> and  calculation and this  have \"A \\<or> (B \\<and> C)\" by (rule disjE)\n  }\n  from \\<open>A \\<or> C\\<close> and calculation and this  have  \"A \\<or> (B \\<and> C)\" by (rule disjE)\n}\nultimately show ?thesis by (rule iffI)\nqed\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/Ex20.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392878563336, "lm_q2_score": 0.8128673110375458, "lm_q1q2_score": 0.7186066387713248}}
{"text": "(* Title:      Subset Boolean Algebras\n   Authors:    Walter Guttmann, Bernhard M\u00f6ller\n   Maintainer: Walter Guttmann <walter.guttmann at canterbury.ac.nz>\n*)\n\ntheory Subset_Boolean_Algebras\n\nimports Stone_Algebras.P_Algebras\n\nbegin\n\nsection \\<open>Boolean Algebras\\<close>\n\ntext \\<open>\nWe show that Isabelle/HOL's \\<open>boolean_algebra\\<close> class is equivalent to Huntington's axioms \\<^cite>\\<open>\"Huntington1933\"\\<close>.\nSee \\<^cite>\\<open>\"WamplerDoty2016\"\\<close> for related results.\n\\<close>\n\nsubsection \\<open>Huntington's Axioms\\<close>\n\ntext \\<open>Definition 1\\<close>\n\nclass huntington = sup + uminus +\n  assumes associative: \"x \\<squnion> (y \\<squnion> z) = (x \\<squnion> y) \\<squnion> z\"\n  assumes commutative: \"x \\<squnion> y = y \\<squnion> x\"\n  assumes huntington: \"x = -(-x \\<squnion> y) \\<squnion> -(-x \\<squnion> -y)\"\nbegin\n\nlemma top_unique:\n  \"x \\<squnion> -x = y \\<squnion> -y\"\nproof -\n  have \"x \\<squnion> -x = y \\<squnion> -(--y \\<squnion> -x) \\<squnion> -(--y \\<squnion> --x)\"\n    by (smt associative commutative huntington)\n  thus ?thesis\n    by (metis associative huntington)\nqed\n\nend\n\nsubsection \\<open>Equivalence to \\<open>boolean_algebra\\<close> Class\\<close>\n\ntext \\<open>Definition 2\\<close>\n\nclass extended = sup + inf + minus + uminus + bot + top + ord +\n  assumes top_def: \"top = (THE x . \\<forall>y . x = y \\<squnion> -y)\" (* define without imposing uniqueness *)\n  assumes bot_def: \"bot = -(THE x . \\<forall>y . x = y \\<squnion> -y)\"\n  assumes inf_def: \"x \\<sqinter> y = -(-x \\<squnion> -y)\"\n  assumes minus_def: \"x - y = -(-x \\<squnion> y)\"\n  assumes less_eq_def: \"x \\<le> y \\<longleftrightarrow> x \\<squnion> y = y\"\n  assumes less_def: \"x < y \\<longleftrightarrow> x \\<squnion> y = y \\<and> \\<not> (y \\<squnion> x = x)\"\n\nclass huntington_extended = huntington + extended\nbegin\n\nlemma top_char:\n  \"top = x \\<squnion> -x\"\n  using top_def top_unique by auto\n\nlemma bot_char:\n  \"bot = -top\"\n  by (simp add: bot_def top_def)\n\nsubclass boolean_algebra\nproof\n  show 1: \"\\<And>x y. (x < y) = (x \\<le> y \\<and> \\<not> y \\<le> x)\"\n    by (simp add: less_def less_eq_def)\n  show 2: \"\\<And>x. x \\<le> x\"\n  proof -\n    fix x\n    have \"x \\<squnion> top = top \\<squnion> --x\"\n      by (metis (full_types) associative top_char)\n    thus \"x \\<le> x\"\n      by (metis (no_types) associative huntington less_eq_def top_char)\n  qed\n  show 3: \"\\<And>x y z. x \\<le> y \\<Longrightarrow> y \\<le> z \\<Longrightarrow> x \\<le> z\"\n    by (metis associative less_eq_def)\n  show 4: \"\\<And>x y. x \\<le> y \\<Longrightarrow> y \\<le> x \\<Longrightarrow> x = y\"\n    by (simp add: commutative less_eq_def)\n  show 5: \"\\<And>x y. x \\<sqinter> y \\<le> x\"\n    using 2 by (metis associative huntington inf_def less_eq_def)\n  show 6: \"\\<And>x y. x \\<sqinter> y \\<le> y\"\n    using 5 commutative inf_def by fastforce\n  show 8: \"\\<And>x y. x \\<le> x \\<squnion> y\"\n    using 2 associative less_eq_def by auto\n  show 9: \"\\<And>y x. y \\<le> x \\<squnion> y\"\n    using 8 commutative by fastforce\n  show 10: \"\\<And>y x z. y \\<le> x \\<Longrightarrow> z \\<le> x \\<Longrightarrow> y \\<squnion> z \\<le> x\"\n    by (metis associative less_eq_def)\n  show 11: \"\\<And>x. bot \\<le> x\"\n    using 8 by (metis bot_char huntington top_char)\n  show 12: \"\\<And>x. x \\<le> top\"\n    using 6 11 by (metis huntington bot_def inf_def less_eq_def top_def)\n  show 13: \"\\<And>x y z. x \\<squnion> y \\<sqinter> z = (x \\<squnion> y) \\<sqinter> (x \\<squnion> z)\"\n  proof -\n    have 2: \"\\<And>x y z . x \\<squnion> (y \\<squnion> z) = (x \\<squnion> y) \\<squnion> z\"\n      by (simp add: associative)\n    have 3: \"\\<And>x y z . (x \\<squnion> y) \\<squnion> z = x \\<squnion> (y \\<squnion> z)\"\n      using 2 by metis\n    have 4: \"\\<And>x y . x \\<squnion> y = y \\<squnion> x\"\n      by (simp add: commutative)\n    have 5: \"\\<And>x y . x = - (- x \\<squnion> y) \\<squnion> - (- x \\<squnion> - y)\"\n      by (simp add: huntington)\n    have 6: \"\\<And>x y . - (- x \\<squnion> y) \\<squnion> - (- x \\<squnion> - y) = x\"\n      using 5 by metis\n    have 7: \"\\<And>x y . x \\<sqinter> y = - (- x \\<squnion> - y)\"\n      by (simp add: inf_def)\n    have 10: \"\\<And>x y z . x \\<squnion> (y \\<squnion> z) = y \\<squnion> (x \\<squnion> z)\"\n      using 3 4 by metis\n    have 11: \"\\<And>x y z . - (- x \\<squnion> y) \\<squnion> (- (- x \\<squnion> - y) \\<squnion> z) = x \\<squnion> z\"\n      using 3 6 by metis\n    have 12: \"\\<And>x y . - (x \\<squnion> - y) \\<squnion> - (- y \\<squnion> - x) = y\"\n      using 4 6 by metis\n    have 13: \"\\<And>x y . - (- x \\<squnion> y) \\<squnion> - (- y \\<squnion> - x) = x\"\n      using 4 6 by metis\n    have 14: \"\\<And>x y . - x \\<squnion> - (- (- x \\<squnion> y) \\<squnion> - - (- x \\<squnion> - y)) = - x \\<squnion> y\"\n      using 6 by metis\n    have 18: \"\\<And>x y z . - (x \\<squnion> - y) \\<squnion> (- (- y \\<squnion> - x) \\<squnion> z) = y \\<squnion> z\"\n      using 3 12 by metis\n    have 20: \"\\<And>x y . - (- x \\<squnion> - y) \\<squnion> - (y \\<squnion> - x) = x\"\n      using 4 12 by metis\n    have 21: \"\\<And>x y . - (x \\<squnion> - y) \\<squnion> - (- x \\<squnion> - y) = y\"\n      using 4 12 by metis\n    have 22: \"\\<And>x y . - x \\<squnion> - (- (y \\<squnion> - x) \\<squnion> - - (- x \\<squnion> - y)) = y \\<squnion> - x\"\n      using 6 12 by metis\n    have 23: \"\\<And>x y . - x \\<squnion> - (- x \\<squnion> (- y \\<squnion> - (y \\<squnion> - x))) = y \\<squnion> - x\"\n      using 3 4 6 12 by metis\n    have 24: \"\\<And>x y . - x \\<squnion> - (- (- x \\<squnion> - y) \\<squnion> - - (- x \\<squnion> y)) = - x \\<squnion> - y\"\n      using 6 12 by metis\n    have 28: \"\\<And>x y . - (- x \\<squnion> - y) \\<squnion> - (- y \\<squnion> x) = y\"\n      using 4 13 by metis\n    have 30: \"\\<And>x y . - x \\<squnion> - (- y \\<squnion> (- x \\<squnion> - (- x \\<squnion> y))) = - x \\<squnion> y\"\n      using 3 4 6 13 by metis\n    have 32: \"\\<And>x y z . - (- x \\<squnion> y) \\<squnion> (z \\<squnion> - (- y \\<squnion> - x)) = z \\<squnion> x\"\n      using 10 13 by metis\n    have 37: \"\\<And>x y z . - (- x \\<squnion> - y) \\<squnion> (- (y \\<squnion> - x) \\<squnion> z) = x \\<squnion> z\"\n      using 3 20 by metis\n    have 39: \"\\<And>x y z . - (- x \\<squnion> - y) \\<squnion> (z \\<squnion> - (y \\<squnion> - x)) = z \\<squnion> x\"\n      using 10 20 by metis\n    have 40: \"\\<And>x y z . - (x \\<squnion> - y) \\<squnion> (- (- x \\<squnion> - y) \\<squnion> z) = y \\<squnion> z\"\n      using 3 21 by metis\n    have 43: \"\\<And>x y . - x \\<squnion> - (- y \\<squnion> (- x \\<squnion> - (y \\<squnion> - x))) = y \\<squnion> - x\"\n      using 3 4 6 21 by metis\n    have 47: \"\\<And>x y z . - (x \\<squnion> y) \\<squnion> - (- (- x \\<squnion> z) \\<squnion> - (- (- x \\<squnion> - z) \\<squnion> y)) = - x \\<squnion> z\"\n      using 6 11 by metis\n    have 55: \"\\<And>x y . x \\<squnion> - (- y \\<squnion> - - x) = y \\<squnion> - (- x \\<squnion> y)\"\n      using 4 11 12 by metis\n    have 58: \"\\<And>x y . x \\<squnion> - (- - y \\<squnion> - x) = x \\<squnion> - (- x \\<squnion> y)\"\n      using 4 11 13 by metis\n    have 63: \"\\<And>x y . x \\<squnion> - (- - x \\<squnion> - y) = y \\<squnion> - (- x \\<squnion> y)\"\n      using 4 11 21 by metis\n    have 71: \"\\<And>x y . x \\<squnion> - (- y \\<squnion> x) = y \\<squnion> - (- x \\<squnion> y)\"\n      using 4 11 28 by metis\n    have 75: \"\\<And>x y . x \\<squnion> - (- y \\<squnion> x) = y \\<squnion> - (y \\<squnion> - x)\"\n      using 4 71 by metis\n    have 78: \"\\<And>x y . - x \\<squnion> (y \\<squnion> - (- x \\<squnion> (y \\<squnion> - - (- x \\<squnion> - y)))) = - x \\<squnion> - (- x \\<squnion> - y)\"\n      using 3 4 6 71 by metis\n    have 86: \"\\<And>x y . - (- x \\<squnion> - (- y \\<squnion> x)) \\<squnion> - (y \\<squnion> - (- x \\<squnion> y)) = - y \\<squnion> x\"\n      using 4 20 71 by metis\n    have 172: \"\\<And>x y . - x \\<squnion> - (- x \\<squnion> - y) = y \\<squnion> - (- - x \\<squnion> y)\"\n      using 14 75 by metis\n    have 201: \"\\<And>x y . x \\<squnion> - (- y \\<squnion> - - x) = y \\<squnion> - (y \\<squnion> - x)\"\n      using 4 55 by metis\n    have 236: \"\\<And>x y . x \\<squnion> - (- - y \\<squnion> - x) = x \\<squnion> - (y \\<squnion> - x)\"\n      using 4 58 by metis\n    have 266: \"\\<And>x y . - x \\<squnion> - (- (- x \\<squnion> - (y \\<squnion> - - x)) \\<squnion> - - (- x \\<squnion> - - (- - x \\<squnion> y))) = - x \\<squnion> - (- - x \\<squnion> y)\"\n      using 14 58 236 by metis\n    have 678: \"\\<And>x y z . - (- x \\<squnion> - (- y \\<squnion> x)) \\<squnion> (- (y \\<squnion> - (- x \\<squnion> y)) \\<squnion> z) = - y \\<squnion> (x \\<squnion> z)\"\n      using 3 4 37 71 by smt\n    have 745: \"\\<And>x y z . - (- x \\<squnion> - (- y \\<squnion> x)) \\<squnion> (z \\<squnion> - (y \\<squnion> - (- x \\<squnion> y))) = z \\<squnion> (- y \\<squnion> x)\"\n      using 4 39 71 by metis\n    have 800: \"\\<And>x y . - - x \\<squnion> (- y \\<squnion> (- (y \\<squnion> - - x) \\<squnion> - (- x \\<squnion> (- - x \\<squnion> (- y \\<squnion> - (y \\<squnion> - - x)))))) = x \\<squnion> - (y \\<squnion> - - x)\"\n      using 3 23 63 by metis\n    have 944: \"\\<And>x y . x \\<squnion> - (x \\<squnion> - - (- (- x \\<squnion> - y) \\<squnion> - - (- x \\<squnion> y))) = - (- x \\<squnion> - y) \\<squnion> - (- (- x \\<squnion> - y) \\<squnion> - - (- x \\<squnion> y))\"\n      using 4 24 71 by metis\n    have 948: \"\\<And>x y . - x \\<squnion> - (- (y \\<squnion> - (y \\<squnion> - - x)) \\<squnion> - - (- x \\<squnion> (- y \\<squnion> - x))) = - x \\<squnion> - (- y \\<squnion> - x)\"\n      using 24 75 by metis\n    have 950: \"\\<And>x y . - x \\<squnion> - (- (y \\<squnion> - (- - x \\<squnion> y)) \\<squnion> - - (- x \\<squnion> (- x \\<squnion> - y))) = - x \\<squnion> - (- x \\<squnion> - y)\"\n      using 24 75 by metis\n    have 961: \"\\<And>x y . - x \\<squnion> - (- (y \\<squnion> - (- - x \\<squnion> y)) \\<squnion> - - (- x \\<squnion> (- - - x \\<squnion> - y))) = y \\<squnion> - (- - x \\<squnion> y)\"\n      using 24 63 by metis\n    have 966: \"\\<And>x y . - x \\<squnion> - (- (y \\<squnion> - (y \\<squnion> - - x)) \\<squnion> - - (- x \\<squnion> (- y \\<squnion> - - - x))) = y \\<squnion> - (y \\<squnion> - - x)\"\n      using 24 201 by metis\n    have 969: \"\\<And>x y . - x \\<squnion> - (- (- x \\<squnion> - (y \\<squnion> - - x)) \\<squnion> - - (- x \\<squnion> (- - y \\<squnion> - - x))) = - x \\<squnion> - (y \\<squnion> - - x)\"\n      using 24 236 by metis\n    have 1096: \"\\<And>x y z . - x \\<squnion> (- (- x \\<squnion> - y) \\<squnion> z) = y \\<squnion> (- (- - x \\<squnion> y) \\<squnion> z)\"\n      using 3 172 by metis\n    have 1098: \"\\<And>x y z . - x \\<squnion> (y \\<squnion> - (- x \\<squnion> - z)) = y \\<squnion> (z \\<squnion> - (- - x \\<squnion> z))\"\n      using 10 172 by metis\n    have 1105: \"\\<And>x y . x \\<squnion> - x = y \\<squnion> - y\"\n      using 4 10 12 32 172 by metis\n    have 1109: \"\\<And>x y z . x \\<squnion> (- x \\<squnion> y) = z \\<squnion> (- z \\<squnion> y)\"\n      using 3 1105 by metis\n    have 1110: \"\\<And>x y z . x \\<squnion> - x = y \\<squnion> (z \\<squnion> - (y \\<squnion> z))\"\n      using 3 1105 by metis\n    have 1114: \"\\<And>x y . - (- x \\<squnion> - - x) = - (y \\<squnion> - y)\"\n      using 7 1105 by metis\n    have 1115: \"\\<And>x y z . x \\<squnion> (y \\<squnion> - y) = z \\<squnion> (x \\<squnion> - z)\"\n      using 10 1105 by metis\n    have 1117: \"\\<And>x y . - (x \\<squnion> - - x) \\<squnion> - (y \\<squnion> - y) = - x\"\n      using 4 13 1105 by metis\n    have 1121: \"\\<And>x y . - (x \\<squnion> - x) \\<squnion> - (y \\<squnion> - - y) = - y\"\n      using 4 28 1105 by metis\n    have 1122: \"\\<And>x . - - x = x\"\n      using 4 28 1105 1117 by metis\n    have 1134: \"\\<And>x y z . - (x \\<squnion> - y) \\<squnion> (z \\<squnion> - z) = y \\<squnion> (- y \\<squnion> - x)\"\n      using 18 1105 1122 by metis\n    have 1140: \"\\<And>x . - x \\<squnion> - (x \\<squnion> (x \\<squnion> - x)) = - x \\<squnion> - x\"\n      using 4 22 1105 1122 1134 by metis\n    have 1143: \"\\<And>x y . x \\<squnion> (- x \\<squnion> y) = y \\<squnion> (x \\<squnion> - y)\"\n      using 37 1105 1122 1134 by metis\n    have 1155: \"\\<And>x y . - (x \\<squnion> - x) \\<squnion> - (y \\<squnion> y) = - y\"\n      using 1121 1122 by metis\n    have 1156: \"\\<And>x y . - (x \\<squnion> x) \\<squnion> - (y \\<squnion> - y) = - x\"\n      using 1117 1122 by metis\n    have 1157: \"\\<And>x y . - (x \\<squnion> - x) = - (y \\<squnion> - y)\"\n      using 4 1114 1122 by metis\n    have 1167: \"\\<And>x y z . - x \\<squnion> (y \\<squnion> - (- x \\<squnion> - z)) = y \\<squnion> (z \\<squnion> - (x \\<squnion> z))\"\n      using 1098 1122 by metis\n    have 1169: \"\\<And>x y z . - x \\<squnion> (- (- x \\<squnion> - y) \\<squnion> z) = y \\<squnion> (- (x \\<squnion> y) \\<squnion> z)\"\n      using 1096 1122 by metis\n    have 1227: \"\\<And>x y . - x \\<squnion> - (- x \\<squnion> (y \\<squnion> (x \\<squnion> - (- x \\<squnion> - (y \\<squnion> x))))) = - x \\<squnion> - (y \\<squnion> x)\"\n      using 3 4 969 1122 by smt\n    have 1230: \"\\<And>x y . - x \\<squnion> - (- x \\<squnion> (- y \\<squnion> (- x \\<squnion> - (y \\<squnion> - (y \\<squnion> x))))) = y \\<squnion> - (y \\<squnion> x)\"\n      using 3 4 966 1122 by smt\n    have 1234: \"\\<And>x y . - x \\<squnion> - (- x \\<squnion> (- x \\<squnion> (- y \\<squnion> - (y \\<squnion> - (x \\<squnion> y))))) = y \\<squnion> - (x \\<squnion> y)\"\n      using 3 4 961 1122 by metis\n    have 1239: \"\\<And>x y . - x \\<squnion> - (- x \\<squnion> - y) = y \\<squnion> - (x \\<squnion> y)\"\n      using 3 4 950 1122 1234 by metis\n    have 1240: \"\\<And>x y . - x \\<squnion> - (- y \\<squnion> - x) = y \\<squnion> - (y \\<squnion> x)\"\n      using 3 4 948 1122 1230 by metis\n    have 1244: \"\\<And>x y . x \\<squnion> - (x \\<squnion> (y \\<squnion> (y \\<squnion> - (x \\<squnion> y)))) = - (- x \\<squnion> - y) \\<squnion> - (y \\<squnion> (y \\<squnion> - (x \\<squnion> y)))\"\n      using 3 4 944 1122 1167 by metis\n    have 1275: \"\\<And>x y . x \\<squnion> (- y \\<squnion> (- (y \\<squnion> x) \\<squnion> - (x \\<squnion> (- x \\<squnion> (- y \\<squnion> - (y \\<squnion> x)))))) = x \\<squnion> - (y \\<squnion> x)\"\n      using 10 800 1122 by metis\n    have 1346: \"\\<And>x y . - x \\<squnion> - (x \\<squnion> (y \\<squnion> (y \\<squnion> (x \\<squnion> - (x \\<squnion> (y \\<squnion> x)))))) = - x \\<squnion> - (x \\<squnion> y)\"\n      using 3 4 10 266 1122 1167 by smt\n    have 1377: \"\\<And>x y . - x \\<squnion> (y \\<squnion> - (- x \\<squnion> (y \\<squnion> (- x \\<squnion> - y)))) = y \\<squnion> - (x \\<squnion> y)\"\n      using 78 1122 1239 by metis\n    have 1394: \"\\<And>x y . - (- x \\<squnion> - y) \\<squnion> - (y \\<squnion> (y \\<squnion> (- x \\<squnion> - (x \\<squnion> y)))) = x\"\n      using 3 4 10 20 30 1122 1239 by smt\n    have 1427: \"\\<And>x y . - (- x \\<squnion> - y) \\<squnion> - (y \\<squnion> - (x \\<squnion> (x \\<squnion> - (x \\<squnion> y)))) = x \\<squnion> (x \\<squnion> - (x \\<squnion> y))\"\n      using 3 4 30 40 1240 by smt\n    have 1436: \"\\<And>x . - x \\<squnion> - (x \\<squnion> (x \\<squnion> (- x \\<squnion> - x))) = - x \\<squnion> (- x \\<squnion> - (x \\<squnion> - x))\"\n      using 3 4 30 1140 1239 by smt\n    have 1437: \"\\<And>x y . - (x \\<squnion> y) \\<squnion> - (x \\<squnion> - y) = - x\"\n      using 6 1122 by metis\n    have 1438: \"\\<And>x y . - (x \\<squnion> y) \\<squnion> - (y \\<squnion> - x) = - y\"\n      using 12 1122 by metis\n    have 1439: \"\\<And>x y . - (x \\<squnion> y) \\<squnion> - (- y \\<squnion> x) = - x\"\n      using 13 1122 by metis\n    have 1440: \"\\<And>x y . - (x \\<squnion> - y) \\<squnion> - (y \\<squnion> x) = - x\"\n      using 20 1122 by metis\n    have 1441: \"\\<And>x y . - (x \\<squnion> y) \\<squnion> - (- x \\<squnion> y) = - y\"\n      using 21 1122 by metis\n    have 1568: \"\\<And>x y . x \\<squnion> (- y \\<squnion> - x) = y \\<squnion> (- y \\<squnion> x)\"\n      using 10 1122 1143 by metis\n    have 1598: \"\\<And>x . - x \\<squnion> - (x \\<squnion> (x \\<squnion> (x \\<squnion> - x))) = - x \\<squnion> (- x \\<squnion> - (x \\<squnion> - x))\"\n      using 4 1436 1568 by metis\n    have 1599: \"\\<And>x y . - x \\<squnion> (y \\<squnion> - (x \\<squnion> (- x \\<squnion> (- x \\<squnion> y)))) = y \\<squnion> - (x \\<squnion> y)\"\n      using 10 1377 1568 by smt\n    have 1617: \"\\<And>x . x \\<squnion> (- x \\<squnion> (- x \\<squnion> - (x \\<squnion> - x))) = x \\<squnion> - x\"\n      using 3 4 10 71 1122 1155 1568 1598 by metis\n    have 1632: \"\\<And>x y z . - (x \\<squnion> - x) \\<squnion> - (- y \\<squnion> (- (z \\<squnion> - z) \\<squnion> - (y \\<squnion> - (x \\<squnion> - x)))) = y \\<squnion> - (x \\<squnion> - x)\"\n      using 43 1157 by metis\n    have 1633: \"\\<And>x y z . - (x \\<squnion> - x) \\<squnion> - (- y \\<squnion> (- (x \\<squnion> - x) \\<squnion> - (y \\<squnion> - (z \\<squnion> - z)))) = y \\<squnion> - (x \\<squnion> - x)\"\n      using 43 1157 by metis\n    have 1636: \"\\<And>x y . x \\<squnion> - (y \\<squnion> (- y \\<squnion> - (x \\<squnion> x))) = x \\<squnion> x\"\n      using 43 1109 1122 by metis\n    have 1645: \"\\<And>x y . x \\<squnion> - x = y \\<squnion> (y \\<squnion> - y)\"\n      using 3 1110 1156 by metis\n    have 1648: \"\\<And>x y z . - (x \\<squnion> (y \\<squnion> (- y \\<squnion> - x))) \\<squnion> - (z \\<squnion> - z) = - (y \\<squnion> - y)\"\n      using 3 1115 1156 by metis\n    have 1657: \"\\<And>x y z . x \\<squnion> - x = y \\<squnion> (z \\<squnion> - z)\"\n      using 1105 1645 by metis\n    have 1664: \"\\<And>x y z . x \\<squnion> - x = y \\<squnion> (z \\<squnion> - y)\"\n      using 1115 1645 by metis\n    have 1672: \"\\<And>x y z . x \\<squnion> - x = y \\<squnion> (- y \\<squnion> z)\"\n      using 3 4 1657 by metis\n    have 1697: \"\\<And>x y z . - x \\<squnion> (y \\<squnion> x) = z \\<squnion> - z\"\n      using 1122 1664 by metis\n    have 1733: \"\\<And>x y z . - (x \\<squnion> y) \\<squnion> - (- (z \\<squnion> - z) \\<squnion> - (- (- x \\<squnion> - x) \\<squnion> y)) = x \\<squnion> - x\"\n      using 4 47 1105 1122 by metis\n    have 1791: \"\\<And>x y z . x \\<squnion> - (y \\<squnion> (- y \\<squnion> z)) = x \\<squnion> - (x \\<squnion> - x)\"\n      using 4 71 1122 1672 by metis\n    have 1818: \"\\<And>x y z . x \\<squnion> - (- y \\<squnion> (z \\<squnion> y)) = x \\<squnion> - (x \\<squnion> - x)\"\n      using 4 71 1122 1697 by metis\n    have 1861: \"\\<And>x y z . - (x \\<squnion> - x) \\<squnion> - (y \\<squnion> - (z \\<squnion> - z)) = - y\"\n      using 1437 1657 by metis\n    have 1867: \"\\<And>x y z . - (x \\<squnion> - x) \\<squnion> - (- y \\<squnion> - (z \\<squnion> y)) = y\"\n      using 1122 1437 1697 by metis\n    have 1868: \"\\<And>x y . x \\<squnion> - (y \\<squnion> - y) = x\"\n      using 1122 1155 1633 1861 by metis\n    have 1869: \"\\<And>x y z . - (x \\<squnion> - x) \\<squnion> - (- y \\<squnion> (- (z \\<squnion> - z) \\<squnion> - y)) = y\"\n      using 1632 1868 by metis\n    have 1870: \"\\<And>x y . - (x \\<squnion> - x) \\<squnion> - y = - y\"\n      using 1861 1868 by metis\n    have 1872: \"\\<And>x y z . x \\<squnion> - (- y \\<squnion> (z \\<squnion> y)) = x\"\n      using 1818 1868 by metis\n    have 1875: \"\\<And>x y z . x \\<squnion> - (y \\<squnion> (- y \\<squnion> z)) = x\"\n      using 1791 1868 by metis\n    have 1883: \"\\<And>x y . - (x \\<squnion> (y \\<squnion> (- y \\<squnion> - x))) = - (y \\<squnion> - y)\"\n      using 1648 1868 by metis\n    have 1885: \"\\<And>x . x \\<squnion> (x \\<squnion> - x) = x \\<squnion> - x\"\n      using 4 1568 1617 1868 by metis\n    have 1886: \"\\<And>x . - x \\<squnion> - x = - x\"\n      using 1598 1868 1885 by metis\n    have 1890: \"\\<And>x . - (x \\<squnion> x) = - x\"\n      using 1156 1868 by metis\n    have 1892: \"\\<And>x y . - (x \\<squnion> - x) \\<squnion> y = y\"\n      using 1122 1869 1870 1886 by metis\n    have 1893: \"\\<And>x y . - (- x \\<squnion> - (y \\<squnion> x)) = x\"\n      using 1867 1892 by metis\n    have 1902: \"\\<And>x y . x \\<squnion> (y \\<squnion> - (x \\<squnion> y)) = x \\<squnion> - x\"\n      using 3 4 1122 1733 1886 1892 by metis\n    have 1908: \"\\<And>x . x \\<squnion> x = x\"\n      using 1636 1875 1890 by metis\n    have 1910: \"\\<And>x y . x \\<squnion> - (y \\<squnion> x) = - y \\<squnion> x\"\n      using 1599 1875 by metis\n    have 1921: \"\\<And>x y . x \\<squnion> (- y \\<squnion> - (y \\<squnion> x)) = - y \\<squnion> x\"\n      using 1275 1875 1910 by metis\n    have 1951: \"\\<And>x y . - x \\<squnion> - (y \\<squnion> x) = - x\"\n      using 1227 1872 1893 1908 by metis\n    have 1954: \"\\<And>x y z . x \\<squnion> (y \\<squnion> - (x \\<squnion> z)) = y \\<squnion> (- z \\<squnion> x)\"\n      using 745 1122 1910 1951 by metis\n    have 1956: \"\\<And>x y z . x \\<squnion> (- (x \\<squnion> y) \\<squnion> z) = - y \\<squnion> (x \\<squnion> z)\"\n      using 678 1122 1910 1951 by metis\n    have 1959: \"\\<And>x y . x \\<squnion> - (x \\<squnion> y) = - y \\<squnion> x\"\n      using 86 1122 1910 1951 by metis\n    have 1972: \"\\<And>x y . x \\<squnion> (- x \\<squnion> y) = x \\<squnion> - x\"\n      using 1902 1910 by metis\n    have 2000: \"\\<And>x y . - (- x \\<squnion> - y) \\<squnion> - (y \\<squnion> (- x \\<squnion> y)) = x \\<squnion> - (y \\<squnion> (- x \\<squnion> y))\"\n      using 4 1244 1910 1959 by metis\n    have 2054: \"\\<And>x y . x \\<squnion> - (y \\<squnion> (- x \\<squnion> y)) = x\"\n      using 1394 1921 2000 by metis\n    have 2057: \"\\<And>x y . - (x \\<squnion> (y \\<squnion> - y)) = - (y \\<squnion> - y)\"\n      using 1883 1972 by metis\n    have 2061: \"\\<And>x y . x \\<squnion> (- y \\<squnion> x) = x \\<squnion> - y\"\n      using 4 1122 1427 1910 1959 2054 by metis\n    have 2090: \"\\<And>x y z . x \\<squnion> (- (y \\<squnion> x) \\<squnion> z) = x \\<squnion> (- y \\<squnion> z)\"\n      using 1122 1169 1956 by metis\n    have 2100: \"\\<And>x y . - x \\<squnion> - (x \\<squnion> y) = - x\"\n      using 4 1346 1868 1885 1910 1959 1972 2057 by metis\n    have 2144: \"\\<And>x y . x \\<squnion> - (y \\<squnion> - x) = x\"\n      using 1122 1440 2000 2061 by metis\n    have 2199: \"\\<And>x y . x \\<squnion> (x \\<squnion> y) = x \\<squnion> y\"\n      using 3 1908 by metis\n    have 2208: \"\\<And>x y z . x \\<squnion> (- (y \\<squnion> - x) \\<squnion> z) = x \\<squnion> z\"\n      using 3 2144 by metis\n    have 2349: \"\\<And>x y z . - (x \\<squnion> y) \\<squnion> - (x \\<squnion> (y \\<squnion> z)) = - (x \\<squnion> y)\"\n      using 3 2100 by metis\n    have 2432: \"\\<And>x y z . - (x \\<squnion> (y \\<squnion> z)) \\<squnion> - (y \\<squnion> (z \\<squnion> - x)) = - (y \\<squnion> z)\"\n      using 3 1438 by metis\n    have 2530: \"\\<And>x y z . - (- (x \\<squnion> y) \\<squnion> z) = - (y \\<squnion> (- x \\<squnion> z)) \\<squnion> - (- y \\<squnion> z)\"\n      using 4 1122 1439 2090 2208 by smt\n    have 3364: \"\\<And>x y z . - (- x \\<squnion> y) \\<squnion> (z \\<squnion> - (x \\<squnion> y)) = z \\<squnion> - y\"\n      using 3 4 1122 1441 1910 1954 2199 by metis\n    have 5763: \"\\<And>x y z . - (x \\<squnion> y) \\<squnion> - (- x \\<squnion> (y \\<squnion> z)) = - (x \\<squnion> y) \\<squnion> - (y \\<squnion> z)\"\n      using 4 2349 3364 by metis\n    have 6113: \"\\<And>x y z . - (x \\<squnion> (y \\<squnion> z)) \\<squnion> - (z \\<squnion> - x) = - (y \\<squnion> z) \\<squnion> - (z \\<squnion> - x)\"\n      using 4 2432 3364 5763 by metis\n    show \"\\<And>x y z. x \\<squnion> y \\<sqinter> z = (x \\<squnion> y) \\<sqinter> (x \\<squnion> z)\"\n    proof -\n      fix x y z\n      have \"- (y \\<sqinter> z \\<squnion> x) = - (- (- y \\<squnion> z) \\<squnion> - (- y \\<squnion> - z) \\<squnion> x) \\<squnion> - (x \\<squnion> - - z)\"\n        using 1437 2530 6113 by (smt commutative inf_def)\n      thus \"x \\<squnion> y \\<sqinter> z = (x \\<squnion> y) \\<sqinter> (x \\<squnion> z)\"\n        using 12 1122 by (metis commutative inf_def)\n    qed\n  qed\n  show 14: \"\\<And>x. x \\<sqinter> - x = bot\"\n  proof -\n    fix x\n    have \"(bot \\<squnion> x) \\<sqinter> (bot \\<squnion> -x) = bot\"\n      using huntington bot_def inf_def by auto\n    thus \"x \\<sqinter> -x = bot\"\n      using 11 less_eq_def by force\n  qed\n  show 15: \"\\<And>x. x \\<squnion> - x = top\"\n    using 5 14 by (metis (no_types, lifting) huntington bot_def less_eq_def top_def)\n  show 16: \"\\<And>x y. x - y = x \\<sqinter> - y\"\n    using 15 by (metis commutative huntington inf_def minus_def)\n  show 7: \"\\<And>x y z. x \\<le> y \\<Longrightarrow> x \\<le> z \\<Longrightarrow> x \\<le> y \\<sqinter> z\"\n    by (simp add: 13 less_eq_def)\nqed\n\nend\n\ncontext boolean_algebra\nbegin\n\nsublocale ba_he: huntington_extended\nproof\n  show \"\\<And>x y z. x \\<squnion> (y \\<squnion> z) = x \\<squnion> y \\<squnion> z\"\n    by (simp add: sup_assoc)\n  show \"\\<And>x y. x \\<squnion> y = y \\<squnion> x\"\n    by (simp add: sup_commute)\n  show \"\\<And>x y. x = - (- x \\<squnion> y) \\<squnion> - (- x \\<squnion> - y)\"\n    by simp\n  show \"top = (THE x. \\<forall>y. x = y \\<squnion> - y)\"\n    by auto\n  show \"bot = - (THE x. \\<forall>y. x = y \\<squnion> - y)\"\n    by auto\n  show \"\\<And>x y. x \\<sqinter> y = - (- x \\<squnion> - y)\"\n    by simp\n  show \"\\<And>x y. x - y = - (- x \\<squnion> y)\"\n    by (simp add: diff_eq)\n  show \"\\<And>x y. (x \\<le> y) = (x \\<squnion> y = y)\"\n    by (simp add: le_iff_sup)\n  show \"\\<And>x y. (x < y) = (x \\<squnion> y = y \\<and> y \\<squnion> x \\<noteq> x)\"\n    using sup.strict_order_iff sup_commute by auto\nqed\n\nend\n\nsubsection \\<open>Stone Algebras\\<close>\n\ntext \\<open>\nWe relate Stone algebras to Boolean algebras.\n\\<close>\n\nclass stone_algebra_extended = stone_algebra + minus +\n  assumes stone_minus_def[simp]: \"x - y = x \\<sqinter> -y\"\n\nclass regular_stone_algebra = stone_algebra_extended +\n  assumes double_complement[simp]: \"--x = x\"\nbegin\n\nsubclass boolean_algebra\nproof\n  show \"\\<And>x. x \\<sqinter> - x = bot\"\n    by simp\n  show \"\\<And>x. x \\<squnion> - x = top\"\n    using regular_dense_top by fastforce\n  show \"\\<And>x y. x - y = x \\<sqinter> - y\"\n    by simp\nqed\n\nend\n\ncontext boolean_algebra\nbegin\n\nsublocale ba_rsa: regular_stone_algebra\nproof\n  show \"\\<And>x y. x - y = x \\<sqinter> - y\"\n    by (simp add: diff_eq)\n  show \"\\<And>x. - - x = x\"\n    by simp\nqed\n\nend\n\nsection \\<open>Alternative Axiomatisations of Boolean Algebras\\<close>\n\ntext \\<open>\nWe consider four axiomatisations of Boolean algebras based only on join and complement.\nThe first three are from the literature and the fourth, a version using equational axioms, is new.\nThe motivation for Byrne's and the new axiomatisation is that the axioms are easier to understand than Huntington's third axiom.\nWe also include Meredith's axiomatisation.\n\\<close>\n\nsubsection \\<open>Lee Byrne's Formulation A\\<close>\n\ntext \\<open>\nThe following axiomatisation is from \\<^cite>\\<open>\\<open>Formulation A\\<close> in \"Byrne1946\"\\<close>; see also \\<^cite>\\<open>\"Frink1941\"\\<close>.\n\\<close>\n\ntext \\<open>Theorem 3\\<close>\n\nclass boolean_algebra_1 = sup + uminus +\n  assumes ba1_associative: \"x \\<squnion> (y \\<squnion> z) = (x \\<squnion> y) \\<squnion> z\"\n  assumes ba1_commutative: \"x \\<squnion> y = y \\<squnion> x\"\n  assumes ba1_complement: \"x \\<squnion> -y = z \\<squnion> -z \\<longleftrightarrow> x \\<squnion> y = x\"\nbegin\n\nsubclass huntington\nproof\n  show 1: \"\\<And>x y z. x \\<squnion> (y \\<squnion> z) = x \\<squnion> y \\<squnion> z\"\n    by (simp add: ba1_associative)\n  show \"\\<And>x y. x \\<squnion> y = y \\<squnion> x\"\n    by (simp add: ba1_commutative)\n  show \"\\<And>x y. x = - (- x \\<squnion> y) \\<squnion> - (- x \\<squnion> - y)\"\n  proof -\n    have 2: \"\\<forall>x y. y \\<squnion> (y \\<squnion> x) = y \\<squnion> x\"\n      using 1 by (metis ba1_complement)\n    hence \"\\<forall>x. --x = x\"\n      by (smt ba1_associative ba1_commutative ba1_complement)\n    hence \"\\<forall>x y. y \\<squnion> -(y \\<squnion> -x) = y \\<squnion> x\"\n      by (smt ba1_associative ba1_commutative ba1_complement)\n    thus \"\\<And>x y. x = -(-x \\<squnion> y) \\<squnion> -(-x \\<squnion> - y)\"\n      using 2 by (smt ba1_commutative ba1_complement)\n  qed\nqed\n\nend\n\ncontext huntington\nbegin\n\nsublocale h_ba1: boolean_algebra_1\nproof\n  show \"\\<And>x y z. x \\<squnion> (y \\<squnion> z) = x \\<squnion> y \\<squnion> z\"\n    by (simp add: associative)\n  show \"\\<And>x y. x \\<squnion> y = y \\<squnion> x\"\n    by (simp add: commutative)\n  show \"\\<And>x y z. (x \\<squnion> - y = z \\<squnion> - z) = (x \\<squnion> y = x)\"\n  proof\n    fix x y z\n    have 1: \"\\<And>x y z. -(-x \\<squnion> y) \\<squnion> (-(-x \\<squnion> -y) \\<squnion> z) = x \\<squnion> z\"\n      using associative huntington by force\n    have 2: \"\\<And>x y. -(x \\<squnion> -y) \\<squnion> -(-y \\<squnion> -x) = y\"\n      by (metis commutative huntington)\n    show \"x \\<squnion> - y = z \\<squnion> - z \\<Longrightarrow> x \\<squnion> y = x\"\n      by (metis 1 2 associative commutative top_unique)\n    show \"x \\<squnion> y = x \\<Longrightarrow> x \\<squnion> - y = z \\<squnion> - z\"\n      by (metis associative huntington commutative top_unique)\n  qed\nqed\n\nend\n\nsubsection \\<open>Lee Byrne's Formulation B\\<close>\n\ntext \\<open>\nThe following axiomatisation is from \\<^cite>\\<open>\\<open>Formulation B\\<close> in \"Byrne1946\"\\<close>.\n\\<close>\n\ntext \\<open>Theorem 4\\<close>\n\nclass boolean_algebra_2 = sup + uminus +\n  assumes ba2_associative_commutative: \"(x \\<squnion> y) \\<squnion> z = (y \\<squnion> z) \\<squnion> x\"\n  assumes ba2_complement: \"x \\<squnion> -y = z \\<squnion> -z \\<longleftrightarrow> x \\<squnion> y = x\"\nbegin\n\nsubclass boolean_algebra_1\nproof\n  show \"\\<And>x y z. x \\<squnion> (y \\<squnion> z) = x \\<squnion> y \\<squnion> z\"\n    by (smt ba2_associative_commutative ba2_complement)\n  show \"\\<And>x y. x \\<squnion> y = y \\<squnion> x\"\n    by (metis ba2_associative_commutative ba2_complement)\n  show \"\\<And>x y z. (x \\<squnion> - y = z \\<squnion> - z) = (x \\<squnion> y = x)\"\n    by (simp add: ba2_complement)\nqed\n\nend\n\ncontext boolean_algebra_1\nbegin\n\nsublocale ba1_ba2: boolean_algebra_2\nproof\n  show \"\\<And>x y z. x \\<squnion> y \\<squnion> z = y \\<squnion> z \\<squnion> x\"\n    using ba1_associative commutative by force\n  show \"\\<And>x y z. (x \\<squnion> - y = z \\<squnion> - z) = (x \\<squnion> y = x)\"\n    by (simp add: ba1_complement)\nqed\n\nend\n\nsubsection \\<open>Meredith's Equational Axioms\\<close>\n\ntext \\<open>\nThe following axiomatisation is from \\<^cite>\\<open>\\<open>page 221 (1) \\{A,N\\}\\<close> in \"MeredithPrior1968\"\\<close>.\n\\<close>\n\nclass boolean_algebra_mp = sup + uminus +\n  assumes ba_mp_1: \"-(-x \\<squnion> y) \\<squnion> x = x\"\n  assumes ba_mp_2: \"-(-x \\<squnion> y) \\<squnion> (z \\<squnion> y) = y \\<squnion> (z \\<squnion> x)\"\nbegin\n\nsubclass huntington\nproof\n  show \"\\<And>x y z. x \\<squnion> (y \\<squnion> z) = x \\<squnion> y \\<squnion> z\"\n    by (metis ba_mp_1 ba_mp_2)\n  show \"\\<And>x y. x \\<squnion> y = y \\<squnion> x\"\n    by (metis ba_mp_1 ba_mp_2)\n  show \"\\<And>x y. x = - (- x \\<squnion> y) \\<squnion> - (- x \\<squnion> - y)\"\n    by (metis ba_mp_1 ba_mp_2)\nqed\n\nend\n\ncontext huntington\nbegin\n\nsublocale mp_h: boolean_algebra_mp\nproof\n  show 1: \"\\<And>x y. - (- x \\<squnion> y) \\<squnion> x = x\"\n    by (metis h_ba1.ba1_associative h_ba1.ba1_complement huntington)\n  show \"\\<And>x y z. - (- x \\<squnion> y) \\<squnion> (z \\<squnion> y) = y \\<squnion> (z \\<squnion> x)\"\n  proof -\n    fix x y z\n    have \"y = -(-x \\<squnion> -y) \\<squnion> y\"\n      using 1 h_ba1.ba1_commutative by auto\n    thus \"-(-x \\<squnion> y) \\<squnion> (z \\<squnion> y) = y \\<squnion> (z \\<squnion> x)\"\n      by (metis h_ba1.ba1_associative h_ba1.ba1_commutative huntington)\n  qed\nqed\n\nend\n\nsubsection \\<open>An Equational Axiomatisation based on Semilattices\\<close>\n\ntext \\<open>\nThe following version is an equational axiomatisation based on semilattices.\nWe add the double complement rule and that \\<open>top\\<close> is unique.\nThe final axiom \\<open>ba3_export\\<close> encodes the logical statement $P \\vee Q = P \\vee (\\neg P \\wedge Q)$.\nIts dual appears in \\<^cite>\\<open>\"BalbesHorn1970\"\\<close>.\n\\<close>\n\ntext \\<open>Theorem 5\\<close>\n\nclass boolean_algebra_3 = sup + uminus +\n  assumes ba3_associative: \"x \\<squnion> (y \\<squnion> z) = (x \\<squnion> y) \\<squnion> z\"\n  assumes ba3_commutative: \"x \\<squnion> y = y \\<squnion> x\"\n  assumes ba3_idempotent[simp]: \"x \\<squnion> x = x\"\n  assumes ba3_double_complement[simp]: \"--x = x\"\n  assumes ba3_top_unique: \"x \\<squnion> -x = y \\<squnion> -y\"\n  assumes ba3_export: \"x \\<squnion> -(x \\<squnion> y) = x \\<squnion> -y\"\nbegin\n\nsubclass huntington\nproof\n  show \"\\<And>x y z. x \\<squnion> (y \\<squnion> z) = x \\<squnion> y \\<squnion> z\"\n    by (simp add: ba3_associative)\n  show \"\\<And>x y. x \\<squnion> y = y \\<squnion> x\"\n    by (simp add: ba3_commutative)\n  show \"\\<And>x y. x = - (- x \\<squnion> y) \\<squnion> - (- x \\<squnion> - y)\"\n    by (metis ba3_commutative ba3_double_complement ba3_export ba3_idempotent ba3_top_unique)\nqed\n\nend\n\ncontext huntington\nbegin\n\nsublocale h_ba3: boolean_algebra_3\nproof\n  show \"\\<And>x y z. x \\<squnion> (y \\<squnion> z) = x \\<squnion> y \\<squnion> z\"\n    by (simp add: h_ba1.ba1_associative)\n  show \"\\<And>x y. x \\<squnion> y = y \\<squnion> x\"\n    by (simp add: h_ba1.ba1_commutative)\n  show 3: \"\\<And>x. x \\<squnion> x = x\"\n    using h_ba1.ba1_complement by blast\n  show 4: \"\\<And>x. - - x = x\"\n    by (metis h_ba1.ba1_commutative huntington top_unique)\n  show \"\\<And>x y. x \\<squnion> - x = y \\<squnion> - y\"\n    by (simp add: top_unique)\n  show \"\\<And>x y. x \\<squnion> - (x \\<squnion> y) = x \\<squnion> - y\"\n    using 3 4 by (smt h_ba1.ba1_ba2.ba2_associative_commutative h_ba1.ba1_complement)\nqed\n\nend\n\nsection \\<open>Subset Boolean Algebras\\<close>\n\ntext \\<open>\nWe apply Huntington's axioms to the range of a unary operation, which serves as complement on the range.\nThis gives a Boolean algebra structure on the range without imposing any further constraints on the set.\nThe obtained structure is used as a reference in the subsequent development and to inherit the results proved here.\nThis is taken from \\<^cite>\\<open>\"Guttmann2012c\" and \"GuttmannStruthWeber2011b\"\\<close> and follows the development of Boolean algebras in \\<^cite>\\<open>\"Maddux1996\"\\<close>.\n\\<close>\n\ntext \\<open>Definition 6\\<close>\n\nclass subset_boolean_algebra = sup + uminus +\n  assumes sub_associative: \"-x \\<squnion> (-y \\<squnion> -z) = (-x \\<squnion> -y) \\<squnion> -z\"\n  assumes sub_commutative: \"-x \\<squnion> -y = -y \\<squnion> -x\"\n  assumes sub_complement: \"-x = -(--x \\<squnion> -y) \\<squnion> -(--x \\<squnion> --y)\"\n  assumes sub_sup_closed: \"-x \\<squnion> -y = --(-x \\<squnion> -y)\"\nbegin\n\ntext \\<open>uniqueness of \\<open>top\\<close>, resulting in the lemma \\<open>top_def\\<close> to replace the assumption \\<open>sub_top_def\\<close>\\<close>\n\nlemma top_unique:\n  \"-x \\<squnion> --x = -y \\<squnion> --y\"\n  by (metis sub_associative sub_commutative sub_complement)\n\ntext \\<open>consequences for join and complement\\<close>\n\nlemma double_negation[simp]:\n  \"---x = -x\"\n  by (metis sub_complement sub_sup_closed)\n\nlemma complement_1:\n  \"--x = -(-x \\<squnion> -y) \\<squnion> -(-x \\<squnion> --y)\"\n  by (metis double_negation sub_complement)\n\nlemma sup_right_zero_var:\n  \"-x \\<squnion> (-y \\<squnion> --y) = -z \\<squnion> --z\"\n  by (smt complement_1 sub_associative sub_sup_closed top_unique)\n\nlemma sup_right_unit_idempotent:\n  \"-x \\<squnion> -x = -x \\<squnion> -(-y \\<squnion> --y)\"\n  by (metis complement_1 double_negation sub_sup_closed sup_right_zero_var)\n\nlemma sup_idempotent[simp]:\n  \"-x \\<squnion> -x = -x\"\n  by (smt complement_1 double_negation sub_associative sup_right_unit_idempotent)\n\nlemma complement_2:\n  \"-x = -(-(-x \\<squnion> -y) \\<squnion> -(-x \\<squnion> --y))\"\n  using complement_1 by auto\n\nlemma sup_eq_cases:\n  \"-x \\<squnion> -y = -x \\<squnion> -z \\<Longrightarrow> --x \\<squnion> -y = --x \\<squnion> -z \\<Longrightarrow> -y = -z\"\n  by (metis complement_2 sub_commutative)\n\nlemma sup_eq_cases_2:\n  \"-y \\<squnion> -x = -z \\<squnion> -x \\<Longrightarrow> -y \\<squnion> --x = -z \\<squnion> --x \\<Longrightarrow> -y = -z\"\n  using sub_commutative sup_eq_cases by auto\n\nend\n\ntext \\<open>Definition 7\\<close>\n\nclass subset_extended = sup + inf + minus + uminus + bot + top + ord +\n  assumes sub_top_def: \"top = (THE x . \\<forall>y . x = -y \\<squnion> --y)\" (* define without imposing uniqueness *)\n  assumes sub_bot_def: \"bot = -(THE x . \\<forall>y . x = -y \\<squnion> --y)\"\n  assumes sub_inf_def: \"-x \\<sqinter> -y = -(--x \\<squnion> --y)\"\n  assumes sub_minus_def: \"-x - -y = -(--x \\<squnion> -y)\"\n  assumes sub_less_eq_def: \"-x \\<le> -y \\<longleftrightarrow> -x \\<squnion> -y = -y\"\n  assumes sub_less_def: \"-x < -y \\<longleftrightarrow> -x \\<squnion> -y = -y \\<and> \\<not> (-y \\<squnion> -x = -x)\"\n\nclass subset_boolean_algebra_extended = subset_boolean_algebra + subset_extended\nbegin\n\nlemma top_def:\n  \"top = -x \\<squnion> --x\"\n  using sub_top_def top_unique by blast\n\ntext \\<open>consequences for meet\\<close>\n\nlemma inf_closed:\n  \"-x \\<sqinter> -y = --(-x \\<sqinter> -y)\"\n  by (simp add: sub_inf_def)\n\nlemma inf_associative:\n  \"-x \\<sqinter> (-y \\<sqinter> -z) = (-x \\<sqinter> -y) \\<sqinter> -z\"\n  using sub_associative sub_inf_def sub_sup_closed by auto\n\nlemma inf_commutative:\n  \"-x \\<sqinter> -y = -y \\<sqinter> -x\"\n  by (simp add: sub_commutative sub_inf_def)\n\nlemma inf_idempotent[simp]:\n  \"-x \\<sqinter> -x = -x\"\n  by (simp add: sub_inf_def)\n\nlemma inf_absorb[simp]:\n  \"(-x \\<squnion> -y) \\<sqinter> -x = -x\"\n  by (metis complement_1 sup_idempotent sub_inf_def sub_associative sub_sup_closed)\n\nlemma sup_absorb[simp]:\n  \"-x \\<squnion> (-x \\<sqinter> -y) = -x\"\n  by (metis sub_associative sub_complement sub_inf_def sup_idempotent)\n\nlemma inf_demorgan:\n  \"-(-x \\<sqinter> -y) = --x \\<squnion> --y\"\n  using sub_inf_def sub_sup_closed by auto\n\nlemma sub_sup_demorgan:\n  \"-(-x \\<squnion> -y) = --x \\<sqinter> --y\"\n  by (simp add: sub_inf_def)\n\nlemma sup_cases:\n  \"-x = (-x \\<sqinter> -y) \\<squnion> (-x \\<sqinter> --y)\"\n  by (metis inf_closed inf_demorgan sub_complement)\n\nlemma inf_cases:\n  \"-x = (-x \\<squnion> -y) \\<sqinter> (-x \\<squnion> --y)\"\n  by (metis complement_2 sub_sup_closed sub_sup_demorgan)\n\nlemma inf_complement_intro:\n  \"(-x \\<squnion> -y) \\<sqinter> --x = -y \\<sqinter> --x\"\nproof -\n  have \"(-x \\<squnion> -y) \\<sqinter> --x = (-x \\<squnion> -y) \\<sqinter> (--x \\<squnion> -y) \\<sqinter> --x\"\n    by (metis inf_absorb inf_associative sub_sup_closed)\n  also have \"... = -y \\<sqinter> --x\"\n    by (metis inf_cases sub_commutative)\n  finally show ?thesis\n    .\nqed\n\nlemma sup_complement_intro:\n  \"-x \\<squnion> -y = -x \\<squnion> (--x \\<sqinter> -y)\"\n  by (metis inf_absorb inf_commutative inf_complement_intro sub_sup_closed sup_cases)\n\nlemma inf_left_dist_sup:\n  \"-x \\<sqinter> (-y \\<squnion> -z) = (-x \\<sqinter> -y) \\<squnion> (-x \\<sqinter> -z)\"\nproof -\n  have \"-x \\<sqinter> (-y \\<squnion> -z) = (-x \\<sqinter> (-y \\<squnion> -z) \\<sqinter> -y) \\<squnion> (-x \\<sqinter> (-y \\<squnion> -z) \\<sqinter> --y)\"\n    by (metis sub_inf_def sub_sup_closed sup_cases)\n  also have \"... = (-x \\<sqinter> -y) \\<squnion> (-x \\<sqinter> -z \\<sqinter> --y)\"\n    by (metis inf_absorb inf_associative inf_complement_intro sub_sup_closed)\n  also have \"... = (-x \\<sqinter> -y) \\<squnion> ((-x \\<sqinter> -y \\<sqinter> -z) \\<squnion> (-x \\<sqinter> -z \\<sqinter> --y))\"\n    using sub_associative sub_inf_def sup_absorb by auto\n  also have \"... = (-x \\<sqinter> -y) \\<squnion> ((-x \\<sqinter> -z \\<sqinter> -y) \\<squnion> (-x \\<sqinter> -z \\<sqinter> --y))\"\n    by (metis inf_associative inf_commutative)\n  also have \"... = (-x \\<sqinter> -y) \\<squnion> (-x \\<sqinter> -z)\"\n    by (metis sub_inf_def sup_cases)\n  finally show ?thesis\n    .\nqed\n\nlemma sup_left_dist_inf:\n  \"-x \\<squnion> (-y \\<sqinter> -z) = (-x \\<squnion> -y) \\<sqinter> (-x \\<squnion> -z)\"\nproof -\n  have \"-x \\<squnion> (-y \\<sqinter> -z) = -(--x \\<sqinter> (--y \\<squnion> --z))\"\n    by (metis sub_inf_def sub_sup_closed sub_sup_demorgan)\n  also have \"... = (-x \\<squnion> -y) \\<sqinter> (-x \\<squnion> -z)\"\n    by (metis inf_left_dist_sup sub_sup_closed sub_sup_demorgan)\n  finally show ?thesis\n    .\nqed\n\nlemma sup_right_dist_inf:\n  \"(-y \\<sqinter> -z) \\<squnion> -x = (-y \\<squnion> -x) \\<sqinter> (-z \\<squnion> -x)\"\n  using sub_commutative sub_inf_def sup_left_dist_inf by auto\n\nlemma inf_right_dist_sup:\n  \"(-y \\<squnion> -z) \\<sqinter> -x = (-y \\<sqinter> -x) \\<squnion> (-z \\<sqinter> -x)\"\n  by (metis inf_commutative inf_left_dist_sup sub_sup_closed)\n\nlemma case_duality:\n  \"(--x \\<sqinter> -y) \\<squnion> (-x \\<sqinter> -z) = (-x \\<squnion> -y) \\<sqinter> (--x \\<squnion> -z)\"\nproof -\n  have 1: \"-(--x \\<sqinter> --y) \\<sqinter> ----x = --x \\<sqinter> -y\"\n    using inf_commutative inf_complement_intro sub_sup_closed sub_sup_demorgan by auto\n  have 2: \"-(----x \\<squnion> -(--x \\<squnion> -z)) = -----x \\<sqinter> ---z\"\n    by (metis (no_types) double_negation sup_complement_intro sub_sup_demorgan)\n  have 3: \"-(--x \\<sqinter> --y) \\<sqinter> -x = -x\"\n    using inf_commutative inf_left_dist_sup sub_sup_closed sub_sup_demorgan by auto\n  hence \"-(--x \\<sqinter> --y) = -x \\<squnion> -y\"\n    using sub_sup_closed sub_sup_demorgan by auto\n  thus ?thesis\n    by (metis double_negation 1 2 3 inf_associative inf_left_dist_sup sup_complement_intro)\nqed\n\nlemma case_duality_2:\n  \"(-x \\<sqinter> -y) \\<squnion> (--x \\<sqinter> -z) = (-x \\<squnion> -z) \\<sqinter> (--x \\<squnion> -y)\"\n  using case_duality sub_commutative sub_inf_def by auto\n\nlemma complement_cases:\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 1: \"(--v \\<squnion> -w) = --(--v \\<squnion> -w) \\<and> (-v \\<squnion> -x) = --(-v \\<squnion> -x) \\<and> (--v \\<squnion> --y) = --(--v \\<squnion> --y) \\<and> (-v \\<squnion> --z) = --(-v \\<squnion> --z)\"\n    using sub_inf_def sub_sup_closed by auto\n  have 2: \"(-v \\<squnion> (-x \\<sqinter> --z)) = --(-v \\<squnion> (-x \\<sqinter> --z))\"\n    using sub_inf_def sub_sup_closed by auto\n  have \"((-v \\<sqinter> -w) \\<squnion> (--v \\<sqinter> -x)) \\<sqinter> -((-v \\<sqinter> -y) \\<squnion> (--v \\<sqinter> -z)) = ((-v \\<sqinter> -w) \\<squnion> (--v \\<sqinter> -x)) \\<sqinter> (-(-v \\<sqinter> -y) \\<sqinter> -(--v \\<sqinter> -z))\"\n    using sub_inf_def by auto\n  also have \"... = ((-v \\<sqinter> -w) \\<squnion> (--v \\<sqinter> -x)) \\<sqinter> ((--v \\<squnion> --y) \\<sqinter> (-v \\<squnion> --z))\"\n    using inf_demorgan by auto\n  also have \"... = (--v \\<squnion> -w) \\<sqinter> (-v \\<squnion> -x) \\<sqinter> ((--v \\<squnion> --y) \\<sqinter> (-v \\<squnion> --z))\"\n    by (metis case_duality double_negation)\n  also have \"... = (--v \\<squnion> -w) \\<sqinter> ((-v \\<squnion> -x) \\<sqinter> ((--v \\<squnion> --y) \\<sqinter> (-v \\<squnion> --z)))\"\n    by (metis 1 inf_associative sub_inf_def)\n  also have \"... = (--v \\<squnion> -w) \\<sqinter> ((-v \\<squnion> -x) \\<sqinter> (--v \\<squnion> --y) \\<sqinter> (-v \\<squnion> --z))\"\n    by (metis 1 inf_associative)\n  also have \"... = (--v \\<squnion> -w) \\<sqinter> ((--v \\<squnion> --y) \\<sqinter> (-v \\<squnion> -x) \\<sqinter> (-v \\<squnion> --z))\"\n    by (metis 1 inf_commutative)\n  also have \"... = (--v \\<squnion> -w) \\<sqinter> ((--v \\<squnion> --y) \\<sqinter> ((-v \\<squnion> -x) \\<sqinter> (-v \\<squnion> --z)))\"\n    by (metis 1 inf_associative)\n  also have \"... = (--v \\<squnion> -w) \\<sqinter> ((--v \\<squnion> --y) \\<sqinter> (-v \\<squnion> (-x \\<sqinter> --z)))\"\n    by (simp add: sup_left_dist_inf)\n  also have \"... = (--v \\<squnion> -w) \\<sqinter> (--v \\<squnion> --y) \\<sqinter> (-v \\<squnion> (-x \\<sqinter> --z))\"\n    using 1 2 by (metis inf_associative)\n  also have \"... = (--v \\<squnion> (-w \\<sqinter> --y)) \\<sqinter> (-v \\<squnion> (-x \\<sqinter> --z))\"\n    by (simp add: sup_left_dist_inf)\n  also have \"... = (-v \\<sqinter> (-w \\<sqinter> --y)) \\<squnion> (--v \\<sqinter> (-x \\<sqinter> --z))\"\n    by (metis case_duality complement_1 complement_2 sub_inf_def)\n  also have \"... = (-v \\<sqinter> -w \\<sqinter> --y) \\<squnion> (--v \\<sqinter> -x \\<sqinter> --z)\"\n    by (simp add: inf_associative)\n  finally show ?thesis\n    .\nqed\n\nlemma inf_cases_2: \"--x = -(-x \\<sqinter> -y) \\<sqinter> -(-x \\<sqinter> --y)\"\n  using sub_inf_def sup_cases by auto\n\ntext \\<open>consequences for \\<open>top\\<close> and \\<open>bot\\<close>\\<close>\n\nlemma sup_complement[simp]:\n  \"-x \\<squnion> --x = top\"\n  using top_def by auto\n\nlemma inf_complement[simp]:\n  \"-x \\<sqinter> --x = bot\"\n  by (metis sub_bot_def sub_inf_def sub_top_def top_def)\n\nlemma complement_bot[simp]:\n  \"-bot = top\"\n  using inf_complement inf_demorgan sup_complement by fastforce\n\nlemma complement_top[simp]:\n  \"-top = bot\"\n  using sub_bot_def sub_top_def by blast\n\nlemma sup_right_zero[simp]:\n  \"-x \\<squnion> top = top\"\n  using sup_right_zero_var by auto\n\nlemma sup_left_zero[simp]:\n  \"top \\<squnion> -x = top\"\n  by (metis complement_bot sub_commutative sup_right_zero)\n\nlemma inf_right_unit[simp]:\n  \"-x \\<sqinter> bot = bot\"\n  by (metis complement_bot complement_top double_negation sub_sup_demorgan sup_right_zero)\n\nlemma inf_left_unit[simp]:\n  \"bot \\<sqinter> -x = bot\"\n  by (metis complement_top inf_commutative inf_right_unit)\n\nlemma sup_right_unit[simp]:\n  \"-x \\<squnion> bot = -x\"\n  using sup_right_unit_idempotent by auto\n\nlemma sup_left_unit[simp]:\n  \"bot \\<squnion> -x = -x\"\n  by (metis complement_top sub_commutative sup_right_unit)\n\nlemma inf_right_zero[simp]:\n  \"-x \\<sqinter> top = -x\"\n  by (metis inf_left_dist_sup sup_cases top_def)\n\nlemma sub_inf_left_zero[simp]:\n  \"top \\<sqinter> -x = -x\"\n  using inf_absorb top_def by fastforce\n\nlemma bot_double_complement[simp]:\n  \"--bot = bot\"\n  by simp\n\nlemma top_double_complement[simp]:\n  \"--top = top\"\n  by simp\n\ntext \\<open>consequences for the order\\<close>\n\nlemma reflexive:\n  \"-x \\<le> -x\"\n  by (simp add: sub_less_eq_def)\n\n\n\nlemma antisymmetric:\n  \"-x \\<le> -y \\<Longrightarrow> -y \\<le> -x \\<Longrightarrow> -x = -y\"\n  by (simp add: sub_commutative sub_less_eq_def)\n\nlemma sub_bot_least:\n  \"bot \\<le> -x\"\n  using sup_left_unit complement_top sub_less_eq_def by blast\n\nlemma top_greatest:\n  \"-x \\<le> top\"\n  using complement_bot sub_less_eq_def sup_right_zero by blast\n\nlemma upper_bound_left:\n  \"-x \\<le> -x \\<squnion> -y\"\n  by (metis sub_associative sub_less_eq_def sub_sup_closed sup_idempotent)\n\nlemma upper_bound_right:\n  \"-y \\<le> -x \\<squnion> -y\"\n  using sub_commutative upper_bound_left by fastforce\n\nlemma sub_sup_left_isotone:\n  assumes \"-x \\<le> -y\"\n    shows \"-x \\<squnion> -z \\<le> -y \\<squnion> -z\"\nproof -\n  have \"-x \\<squnion> -y = -y\"\n    by (meson assms sub_less_eq_def)\n  thus ?thesis\n    by (metis (full_types) sub_associative sub_commutative sub_sup_closed upper_bound_left)\nqed\n\nlemma sub_sup_right_isotone:\n  \"-x \\<le> -y \\<Longrightarrow> -z \\<squnion> -x \\<le> -z \\<squnion> -y\"\n  by (simp add: sub_commutative sub_sup_left_isotone)\n\nlemma sup_isotone:\n  assumes \"-p \\<le> -q\"\n      and \"-r \\<le> -s\"\n    shows \"-p \\<squnion> -r \\<le> -q \\<squnion> -s\"\nproof -\n  have \"\\<And>x y. \\<not> -x \\<le> -y \\<squnion> -r \\<or> -x \\<le> -y \\<squnion> -s\"\n    by (metis (full_types) assms(2) sub_sup_closed sub_sup_right_isotone transitive)\n  thus ?thesis\n    by (metis (no_types) assms(1) sub_sup_closed sub_sup_left_isotone)\nqed\n\nlemma sub_complement_antitone:\n  \"-x \\<le> -y \\<Longrightarrow> --y \\<le> --x\"\n  by (metis inf_absorb inf_demorgan sub_less_eq_def)\n\nlemma less_eq_inf:\n  \"-x \\<le> -y \\<longleftrightarrow> -x \\<sqinter> -y = -x\"\n  by (metis inf_absorb inf_commutative sub_less_eq_def upper_bound_right sup_absorb)\n\nlemma inf_complement_left_antitone:\n  \"-x \\<le> -y \\<Longrightarrow> -(-y \\<sqinter> -z) \\<le> -(-x \\<sqinter> -z)\"\n  by (simp add: sub_complement_antitone inf_demorgan sub_sup_left_isotone)\n\nlemma sub_inf_left_isotone:\n  \"-x \\<le> -y \\<Longrightarrow> -x \\<sqinter> -z \\<le> -y \\<sqinter> -z\"\n  using sub_complement_antitone inf_closed inf_complement_left_antitone by fastforce\n\nlemma sub_inf_right_isotone:\n  \"-x \\<le> -y \\<Longrightarrow> -z \\<sqinter> -x \\<le> -z \\<sqinter> -y\"\n  by (simp add: inf_commutative sub_inf_left_isotone)\n\nlemma inf_isotone:\n  assumes \"-p \\<le> -q\"\n      and \"-r \\<le> -s\"\n    shows \"-p \\<sqinter> -r \\<le> -q \\<sqinter> -s\"\nproof -\n  have \"\\<forall>w x y z. (-w \\<le> -x \\<sqinter> -y \\<or> \\<not> -w \\<le> -x \\<sqinter> -z) \\<or> \\<not> -z \\<le> -y\"\n    by (metis (no_types) inf_closed sub_inf_right_isotone transitive)\n  thus ?thesis\n    by (metis (no_types) assms inf_closed sub_inf_left_isotone)\nqed\n\nlemma least_upper_bound:\n  \"-x \\<le> -z \\<and> -y \\<le> -z \\<longleftrightarrow> -x \\<squnion> -y \\<le> -z\"\n  by (metis sub_sup_closed transitive upper_bound_right sup_idempotent sup_isotone upper_bound_left)\n\nlemma lower_bound_left:\n  \"-x \\<sqinter> -y \\<le> -x\"\n  by (metis sub_inf_def upper_bound_right sup_absorb)\n\nlemma lower_bound_right:\n  \"-x \\<sqinter> -y \\<le> -y\"\n  using inf_commutative lower_bound_left by fastforce\n\nlemma greatest_lower_bound:\n  \"-x \\<le> -y \\<and> -x \\<le> -z \\<longleftrightarrow> -x \\<le> -y \\<sqinter> -z\"\n  by (metis inf_closed sub_inf_left_isotone less_eq_inf transitive lower_bound_left lower_bound_right)\n\nlemma less_eq_sup_top:\n  \"-x \\<le> -y \\<longleftrightarrow> --x \\<squnion> -y = top\"\n  by (metis complement_1 inf_commutative inf_complement_intro sub_inf_left_zero less_eq_inf sub_complement sup_complement_intro top_def)\n\nlemma less_eq_inf_bot:\n  \"-x \\<le> -y \\<longleftrightarrow> -x \\<sqinter> --y = bot\"\n  by (metis complement_bot complement_top double_negation inf_demorgan less_eq_sup_top sub_inf_def)\n\nlemma shunting:\n  \"-x \\<sqinter> -y \\<le> -z \\<longleftrightarrow> -y \\<le> --x \\<squnion> -z\"\nproof (cases \"--x \\<squnion> (-z \\<squnion> --y) = top\")\n  case True\n  have \"\\<forall>v w. -v \\<le> -w \\<or> -w \\<squnion> --v \\<noteq> top\"\n    using less_eq_sup_top sub_commutative by blast\n  thus ?thesis\n    by (metis True sub_associative sub_commutative sub_inf_def sub_sup_closed)\nnext\n  case False\n  hence \"--x \\<squnion> (-z \\<squnion> --y) \\<noteq> top \\<and> \\<not> -y \\<le> -z \\<squnion> --x\"\n    by (metis (no_types) less_eq_sup_top sub_associative sub_commutative sub_sup_closed)\n  thus ?thesis\n    using less_eq_sup_top sub_associative sub_commutative sub_inf_def sub_sup_closed by auto\nqed\n\nlemma shunting_right:\n  \"-x \\<sqinter> -y \\<le> -z \\<longleftrightarrow> -x \\<le> -z \\<squnion> --y\"\n  by (metis inf_commutative sub_commutative shunting)\n\nlemma sup_less_eq_cases:\n  assumes \"-z \\<le> -x \\<squnion> -y\"\n      and \"-z \\<le> --x \\<squnion> -y\"\n    shows \"-z \\<le> -y\"\nproof -\n  have \"-z \\<le> (-x \\<squnion> -y) \\<sqinter> (--x \\<squnion> -y)\"\n    by (metis assms greatest_lower_bound sub_sup_closed)\n  also have \"... = -y\"\n    by (metis inf_cases sub_commutative)\n  finally show ?thesis\n    .\nqed\n\nlemma sup_less_eq_cases_2:\n  \"-x \\<squnion> -y \\<le> -x \\<squnion> -z \\<Longrightarrow> --x \\<squnion> -y \\<le> --x \\<squnion> -z \\<Longrightarrow> -y \\<le> -z\"\n  by (metis least_upper_bound sup_less_eq_cases sub_sup_closed)\n\nlemma sup_less_eq_cases_3:\n  \"-y \\<squnion> -x \\<le> -z \\<squnion> -x \\<Longrightarrow> -y \\<squnion> --x \\<le> -z \\<squnion> --x \\<Longrightarrow> -y \\<le> -z\"\n  by (simp add: sup_less_eq_cases_2 sub_commutative)\n\nlemma inf_less_eq_cases:\n  \"-x \\<sqinter> -y \\<le> -z \\<Longrightarrow> --x \\<sqinter> -y \\<le> -z \\<Longrightarrow> -y \\<le> -z\"\n  by (simp add: shunting sup_less_eq_cases)\n\nlemma inf_less_eq_cases_2:\n  \"-x \\<sqinter> -y \\<le> -x \\<sqinter> -z \\<Longrightarrow> --x \\<sqinter> -y \\<le> --x \\<sqinter> -z \\<Longrightarrow> -y \\<le> -z\"\n  by (metis greatest_lower_bound inf_closed inf_less_eq_cases)\n\nlemma inf_less_eq_cases_3:\n  \"-y \\<sqinter> -x \\<le> -z \\<sqinter> -x \\<Longrightarrow> -y \\<sqinter> --x \\<le> -z \\<sqinter> --x \\<Longrightarrow> -y \\<le> -z\"\n  by (simp add: inf_commutative inf_less_eq_cases_2)\n\nlemma inf_eq_cases:\n  \"-x \\<sqinter> -y = -x \\<sqinter> -z \\<Longrightarrow> --x \\<sqinter> -y = --x \\<sqinter> -z \\<Longrightarrow> -y = -z\"\n  by (metis inf_commutative sup_cases)\n\nlemma inf_eq_cases_2:\n  \"-y \\<sqinter> -x = -z \\<sqinter> -x \\<Longrightarrow> -y \\<sqinter> --x = -z \\<sqinter> --x \\<Longrightarrow> -y = -z\"\n  using inf_commutative inf_eq_cases by auto\n\nlemma wnf_lemma_1:\n  \"((-x \\<squnion> -y) \\<sqinter> (--x \\<squnion> -z)) \\<squnion> -x = -x \\<squnion> -y\"\nproof -\n  have \"\\<forall>u v w. (-u \\<sqinter> (-v \\<squnion> --w)) \\<squnion> -w = -u \\<squnion> -w\"\n    by (metis inf_right_zero sub_associative sub_sup_closed sup_complement sup_idempotent sup_right_dist_inf)\n  thus ?thesis\n    by (metis (no_types) sub_associative sub_commutative sub_sup_closed sup_idempotent)\nqed\n\nlemma wnf_lemma_2:\n  \"((-x \\<squnion> -y) \\<sqinter> (-z \\<squnion> --y)) \\<squnion> -y = -x \\<squnion> -y\"\n  using sub_commutative wnf_lemma_1 by fastforce\n\nlemma wnf_lemma_3:\n  \"((-x \\<squnion> -z) \\<sqinter> (--x \\<squnion> -y)) \\<squnion> --x = --x \\<squnion> -y\"\n  by (metis case_duality case_duality_2 double_negation sub_commutative wnf_lemma_2)\n\nlemma wnf_lemma_4:\n  \"((-z \\<squnion> -y) \\<sqinter> (-x \\<squnion> --y)) \\<squnion> --y = -x \\<squnion> --y\"\n  using sub_commutative wnf_lemma_3 by auto\n\nend\n\nclass subset_boolean_algebra' = sup + uminus +\n  assumes sub_associative': \"-x \\<squnion> (-y \\<squnion> -z) = (-x \\<squnion> -y) \\<squnion> -z\"\n  assumes sub_commutative': \"-x \\<squnion> -y = -y \\<squnion> -x\"\n  assumes sub_complement': \"-x = -(--x \\<squnion> -y) \\<squnion> -(--x \\<squnion> --y)\"\n  assumes sub_sup_closed': \"\\<exists>z . -x \\<squnion> -y = -z\"\nbegin\n\nsubclass subset_boolean_algebra\nproof\n  show \"\\<And>x y z. - x \\<squnion> (- y \\<squnion> - z) = - x \\<squnion> - y \\<squnion> - z\"\n    by (simp add: sub_associative')\n  show \"\\<And>x y. - x \\<squnion> - y = - y \\<squnion> - x\"\n    by (simp add: sub_commutative')\n  show \"\\<And>x y. - x = - (- - x \\<squnion> - y) \\<squnion> - (- - x \\<squnion> - - y)\"\n    by (simp add: sub_complement')\n  show \"\\<And>x y. - x \\<squnion> - y = - - (- x \\<squnion> - y)\"\n  proof -\n    fix x y\n    have \"\\<forall>x y. -y \\<squnion> (-(--y \\<squnion> -x) \\<squnion> -(---x \\<squnion> -y)) = -y \\<squnion> --x\"\n      by (metis (no_types) sub_associative' sub_commutative' sub_complement')\n    hence \"\\<forall>x. ---x = -x\"\n      by (metis (no_types) sub_commutative' sub_complement')\n    thus \"-x \\<squnion> -y = --(-x \\<squnion> -y)\"\n      by (metis sub_sup_closed')\n  qed\nqed\n\nend\n\ntext \\<open>\nWe introduce a type for the range of complement and show that it is an instance of \\<open>boolean_algebra\\<close>.\n\\<close>\n\ntypedef (overloaded) 'a boolean_subset = \"{ x::'a::uminus . \\<exists>y . x = -y }\"\n  by auto\n\nlemma simp_boolean_subset[simp]:\n  \"\\<exists>y . Rep_boolean_subset x = -y\"\n  using Rep_boolean_subset by simp\n\nsetup_lifting type_definition_boolean_subset\n\ntext \\<open>Theorem 8.1\\<close>\n\ninstantiation boolean_subset :: (subset_boolean_algebra) huntington\nbegin\n\nlift_definition sup_boolean_subset :: \"'a boolean_subset \\<Rightarrow> 'a boolean_subset \\<Rightarrow> 'a boolean_subset\" is sup\n  using sub_sup_closed by auto\n\nlift_definition uminus_boolean_subset :: \"'a boolean_subset \\<Rightarrow> 'a boolean_subset\" is uminus\n  by auto\n\ninstance\nproof\n  show \"\\<And>x y z::'a boolean_subset. x \\<squnion> (y \\<squnion> z) = x \\<squnion> y \\<squnion> z\"\n    apply transfer\n    using sub_associative by blast\n  show \"\\<And>x y::'a boolean_subset. x \\<squnion> y = y \\<squnion> x\"\n    apply transfer\n    using sub_commutative by blast\n  show \"\\<And>x y::'a boolean_subset. x = - (- x \\<squnion> y) \\<squnion> - (- x \\<squnion> - y)\"\n    apply transfer\n    using sub_complement by blast\nqed\n\nend\n\ntext \\<open>Theorem 8.2\\<close>\n\ninstantiation boolean_subset :: (subset_boolean_algebra_extended) huntington_extended\nbegin\n\nlift_definition inf_boolean_subset :: \"'a boolean_subset \\<Rightarrow> 'a boolean_subset \\<Rightarrow> 'a boolean_subset\" is inf\n  using inf_closed by auto\n\nlift_definition minus_boolean_subset :: \"'a boolean_subset \\<Rightarrow> 'a boolean_subset \\<Rightarrow> 'a boolean_subset\" is minus\n  using sub_minus_def by auto\n\nlift_definition bot_boolean_subset :: \"'a boolean_subset\" is bot\n  by (metis complement_top)\n\nlift_definition top_boolean_subset :: \"'a boolean_subset\" is top\n  by (metis complement_bot)\n\nlift_definition less_eq_boolean_subset :: \"'a boolean_subset \\<Rightarrow> 'a boolean_subset \\<Rightarrow> bool\" is less_eq .\n\nlift_definition less_boolean_subset :: \"'a boolean_subset \\<Rightarrow> 'a boolean_subset \\<Rightarrow> bool\" is less .\n\ninstance\nproof\n  show 1: \"top = (THE x. \\<forall>y::'a boolean_subset. x = y \\<squnion> - y)\"\n  proof (rule the_equality[symmetric])\n    show \"\\<forall>y::'a boolean_subset. top = y \\<squnion> - y\"\n      apply transfer\n      by auto\n    show \"\\<And>x::'a boolean_subset. \\<forall>y. x = y \\<squnion> - y \\<Longrightarrow> x = top\"\n      apply transfer\n      by force\n  qed\n  have \"(bot::'a boolean_subset) = - top\"\n    apply transfer\n    by simp\n  thus \"bot = - (THE x. \\<forall>y::'a boolean_subset. x = y \\<squnion> - y)\"\n    using 1 by simp\n  show \"\\<And>x y::'a boolean_subset. x \\<sqinter> y = - (- x \\<squnion> - y)\"\n    apply transfer\n    using sub_inf_def by blast\n  show \"\\<And>x y::'a boolean_subset. x - y = - (- x \\<squnion> y)\"\n    apply transfer\n    using sub_minus_def by blast\n  show \"\\<And>x y::'a boolean_subset. (x \\<le> y) = (x \\<squnion> y = y)\"\n    apply transfer\n    using sub_less_eq_def by blast\n  show \"\\<And>x y::'a boolean_subset. (x < y) = (x \\<squnion> y = y \\<and> y \\<squnion> x \\<noteq> x)\"\n    apply transfer\n    using sub_less_def by blast\nqed\n\nend\n\nsection \\<open>Subset Boolean algebras with Additional Structure\\<close>\n\ntext \\<open>\nWe now discuss axioms that make the range of a unary operation a Boolean algebra, but add further properties that are common to the intended models.\nIn the intended models, the unary operation can be a complement, a pseudocomplement or the antidomain operation.\nFor simplicity, we mostly call the unary operation `complement'.\n\nWe first look at structures based only on join and complement, and then add axioms for the remaining operations of Boolean algebras.\nIn the intended models, the operation that is meet on the range of the complement can be a meet in the whole algebra or composition.\n\\<close>\n\nsubsection \\<open>Axioms Derived from the New Axiomatisation\\<close>\n\ntext \\<open>\nThe axioms of the first algebra are based on \\<open>boolean_algebra_3\\<close>.\n\\<close>\n\ntext \\<open>Definition 9\\<close>\n\nclass subset_boolean_algebra_1 = sup + uminus +\n  assumes sba1_associative: \"x \\<squnion> (y \\<squnion> z) = (x \\<squnion> y) \\<squnion> z\"\n  assumes sba1_commutative: \"x \\<squnion> y = y \\<squnion> x\"\n  assumes sba1_idempotent[simp]: \"x \\<squnion> x = x\"\n  assumes sba1_double_complement[simp]: \"---x = -x\"\n  assumes sba1_bot_unique: \"-(x \\<squnion> -x) = -(y \\<squnion> -y)\"\n  assumes sba1_export: \"-x \\<squnion> -(-x \\<squnion> y) = -x \\<squnion> -y\"\nbegin\n\ntext \\<open>Theorem 11.1\\<close>\n\nsubclass subset_boolean_algebra\nproof\n  show \"\\<And>x y z. - x \\<squnion> (- y \\<squnion> - z) = - x \\<squnion> - y \\<squnion> - z\"\n    by (simp add: sba1_associative)\n  show \"\\<And>x y. - x \\<squnion> - y = - y \\<squnion> - x\"\n    by (simp add: sba1_commutative)\n  show \"\\<And>x y. - x = - (- - x \\<squnion> - y) \\<squnion> - (- - x \\<squnion> - - y)\"\n    by (smt sba1_bot_unique sba1_commutative sba1_double_complement sba1_export sba1_idempotent)\n  thus \"\\<And>x y. - x \\<squnion> - y = - - (- x \\<squnion> - y)\"\n    by (metis sba1_double_complement sba1_export)\nqed\n\ndefinition \"sba1_bot \\<equiv> THE x . \\<forall>z . x = -(z \\<squnion> -z)\"\n\nlemma sba1_bot:\n  \"sba1_bot = -(z \\<squnion> -z)\"\n  using sba1_bot_def sba1_bot_unique by auto\n\nend\n\ntext \\<open>Boolean algebra operations based on join and complement\\<close>\n\ntext \\<open>Definition 10\\<close>\n\nclass subset_extended_1 = sup + inf + minus + uminus + bot + top + ord +\n  assumes ba_bot: \"bot = (THE x . \\<forall>z . x = -(z \\<squnion> -z))\"\n  assumes ba_top: \"top = -(THE x . \\<forall>z . x = -(z \\<squnion> -z))\"\n  assumes ba_inf: \"-x \\<sqinter> -y = -(--x \\<squnion> --y)\"\n  assumes ba_minus: \"-x - -y = -(--x \\<squnion> -y)\"\n  assumes ba_less_eq: \"x \\<le> y \\<longleftrightarrow> x \\<squnion> y = y\"\n  assumes ba_less: \"x < y \\<longleftrightarrow> x \\<squnion> y = y \\<and> \\<not> (y \\<squnion> x = x)\"\n\nclass subset_extended_2 = subset_extended_1 +\n  assumes ba_bot_unique: \"-(x \\<squnion> -x) = -(y \\<squnion> -y)\"\nbegin\n\nlemma ba_bot_def:\n  \"bot = -(z \\<squnion> -z)\"\n  using ba_bot ba_bot_unique by auto\n\nlemma ba_top_def:\n  \"top = --(z \\<squnion> -z)\"\n  using ba_bot_def ba_top by simp\n\nend\n\ntext \\<open>Subset forms Boolean Algebra, extended by Boolean algebra operations\\<close>\n\nclass subset_boolean_algebra_1_extended = subset_boolean_algebra_1 + subset_extended_1\nbegin\n\nsubclass subset_extended_2\nproof\n  show \"\\<And>x y. - (x \\<squnion> - x) = - (y \\<squnion> - y)\"\n    by (simp add: sba1_bot_unique)\nqed\n\nsubclass semilattice_sup\nproof\n  show \"\\<And>x y. (x < y) = (x \\<le> y \\<and> \\<not> y \\<le> x)\"\n    by (simp add: ba_less ba_less_eq)\n  show \"\\<And>x. x \\<le> x\"\n    by (simp add: ba_less_eq)\n  show \"\\<And>x y z. x \\<le> y \\<Longrightarrow> y \\<le> z \\<Longrightarrow> x \\<le> z\"\n    by (metis sba1_associative ba_less_eq)\n  show \"\\<And>x y. x \\<le> y \\<Longrightarrow> y \\<le> x \\<Longrightarrow> x = y\"\n    by (simp add: sba1_commutative ba_less_eq)\n  show \"\\<And>x y. x \\<le> x \\<squnion> y\"\n    by (simp add: sba1_associative ba_less_eq)\n  thus \"\\<And>y x. y \\<le> x \\<squnion> y\"\n    by (simp add: sba1_commutative)\n  show \"\\<And>y x z. y \\<le> x \\<Longrightarrow> z \\<le> x \\<Longrightarrow> y \\<squnion> z \\<le> x\"\n    by (metis sba1_associative ba_less_eq)\nqed\n\ntext \\<open>Theorem 11.2\\<close>\n\nsubclass subset_boolean_algebra_extended\nproof\n  show \"top = (THE x. \\<forall>y. x = - y \\<squnion> - - y)\"\n    by (smt ba_bot ba_bot_def ba_top sub_sup_closed the_equality)\n  thus \"bot = - (THE x. \\<forall>y. x = - y \\<squnion> - - y)\"\n    using ba_bot_def ba_top_def by force\n  show \"\\<And>x y. - x \\<sqinter> - y = - (- - x \\<squnion> - - y)\"\n    by (simp add: ba_inf)\n  show \"\\<And>x y. - x - - y = - (- - x \\<squnion> - y)\"\n    by (simp add: ba_minus)\n  show \"\\<And>x y. (- x \\<le> - y) = (- x \\<squnion> - y = - y)\"\n    using le_iff_sup by auto\n  show \"\\<And>x y. (- x < - y) = (- x \\<squnion> - y = - y \\<and> - y \\<squnion> - x \\<noteq> - x)\"\n    by (simp add: ba_less)\nqed\n\nend\n\nsubsection \\<open>Stronger Assumptions based on Join and Complement\\<close>\n\ntext \\<open>\nWe add further axioms covering properties common to the antidomain and (pseudo)complement instances.\n\\<close>\n\ntext \\<open>Definition 12\\<close>\n\nclass subset_boolean_algebra_2 = sup + uminus +\n  assumes sba2_associative: \"x \\<squnion> (y \\<squnion> z) = (x \\<squnion> y) \\<squnion> z\"\n  assumes sba2_commutative: \"x \\<squnion> y = y \\<squnion> x\"\n  assumes sba2_idempotent[simp]: \"x \\<squnion> x = x\"\n  assumes sba2_bot_unit: \"x \\<squnion> -(y \\<squnion> -y) = x\"\n  assumes sba2_sub_sup_demorgan: \"-(x \\<squnion> y) = -(--x \\<squnion> --y)\"\n  assumes sba2_export: \"-x \\<squnion> -(-x \\<squnion> y) = -x \\<squnion> -y\"\nbegin\n\ntext \\<open>Theorem 13.1\\<close>\n\nsubclass subset_boolean_algebra_1\nproof\n  show \"\\<And>x y z. x \\<squnion> (y \\<squnion> z) = x \\<squnion> y \\<squnion> z\"\n    by (simp add: sba2_associative)\n  show \"\\<And>x y. x \\<squnion> y = y \\<squnion> x\"\n    by (simp add: sba2_commutative)\n  show \"\\<And>x. x \\<squnion> x = x\"\n    by simp\n  show \"\\<And>x. - - - x = - x\"\n    by (metis sba2_idempotent sba2_sub_sup_demorgan)\n  show \"\\<And>x y. - (x \\<squnion> - x) = - (y \\<squnion> - y)\"\n    by (metis sba2_bot_unit sba2_commutative)\n  show \"\\<And>x y. - x \\<squnion> - (- x \\<squnion> y) = - x \\<squnion> - y\"\n    by (simp add: sba2_export)\nqed\n\ntext \\<open>Theorem 13.2\\<close>\n\nlemma double_complement_dist_sup:\n  \"--(x \\<squnion> y) = --x \\<squnion> --y\"\n  by (metis sba2_commutative sba2_export sba2_idempotent sba2_sub_sup_demorgan)\n\nlemma maddux_3_3[simp]:\n  \"-(x \\<squnion> y) \\<squnion> -(x \\<squnion> -y) = -x\"\n  by (metis double_complement_dist_sup sba1_double_complement sba2_commutative sub_complement)\n\nlemma huntington_3_pp[simp]:\n  \"-(-x \\<squnion> -y) \\<squnion> -(-x \\<squnion> y) = --x\"\n  using sba2_commutative maddux_3_3 by fastforce\n\nend\n\nclass subset_boolean_algebra_2_extended = subset_boolean_algebra_2 + subset_extended_1\nbegin\n\nsubclass subset_boolean_algebra_1_extended ..\n\nsubclass bounded_semilattice_sup_bot\nproof\n  show \"\\<And>x. bot \\<le> x\"\n    using sba2_bot_unit ba_bot_def sup_right_divisibility by auto\nqed\n\ntext \\<open>Theorem 13.3\\<close>\n\nlemma complement_antitone:\n  \"x \\<le> y \\<Longrightarrow> -y \\<le> -x\"\n  by (metis le_iff_sup maddux_3_3 sba2_export sup_monoid.add_commute)\n\nlemma double_complement_isotone:\n  \"x \\<le> y \\<Longrightarrow> --x \\<le> --y\"\n  by (simp add: complement_antitone)\n\nlemma sup_demorgan:\n  \"-(x \\<squnion> y) = -x \\<sqinter> -y\"\n  using sba2_sub_sup_demorgan ba_inf by auto\n\nend\n\nsubsection \\<open>Axioms for Meet\\<close>\n\ntext \\<open>\nWe add further axioms of \\<open>inf\\<close> covering properties common to the antidomain and pseudocomplement instances.\nWe omit the left distributivity rule and the right zero rule as they do not hold in some models.\nIn particular, the operation \\<open>inf\\<close> does not have to be commutative.\n\\<close>\n\ntext \\<open>Definition 14\\<close>\n\nclass subset_boolean_algebra_3_extended = subset_boolean_algebra_2_extended +\n  assumes sba3_inf_associative: \"x \\<sqinter> (y \\<sqinter> z) = (x \\<sqinter> y) \\<sqinter> z\"\n  assumes sba3_inf_right_dist_sup: \"(x \\<squnion> y) \\<sqinter> z = (x \\<sqinter> z) \\<squnion> (y \\<sqinter> z)\"\n  assumes sba3_inf_complement_bot: \"-x \\<sqinter> x = bot\"\n  assumes sba3_inf_left_unit[simp]: \"top \\<sqinter> x = x\"\n  assumes sba3_complement_inf_double_complement: \"-(x \\<sqinter> --y) = -(x \\<sqinter> y)\"\nbegin\n\ntext \\<open>Theorem 15\\<close>\n\nlemma inf_left_zero:\n  \"bot \\<sqinter> x = bot\"\n  by (metis inf_right_unit sba3_inf_associative sba3_inf_complement_bot)\n\nlemma inf_double_complement_export:\n  \"--(--x \\<sqinter> y) = --x \\<sqinter> --y\"\n  by (metis inf_closed sba3_complement_inf_double_complement)\n\nlemma inf_left_isotone:\n  \"x \\<le> y \\<Longrightarrow> x \\<sqinter> z \\<le> y \\<sqinter> z\"\n  using sba3_inf_right_dist_sup sup_right_divisibility by auto\n\nlemma inf_complement_export:\n  \"--(-x \\<sqinter> y) = -x \\<sqinter> --y\"\n  by (metis inf_double_complement_export sba1_double_complement)\n\nlemma double_complement_above:\n  \"--x \\<sqinter> x = x\"\n  by (metis sup_monoid.add_0_right complement_bot inf_demorgan sba1_double_complement sba3_inf_complement_bot sba3_inf_right_dist_sup sba3_inf_left_unit)\n\nlemma \"x \\<le> y \\<Longrightarrow> z \\<sqinter> x \\<le> z \\<sqinter> y\" nitpick [expect=genuine] oops\nlemma \"x \\<sqinter> top = x\" nitpick [expect=genuine] oops\nlemma \"x \\<sqinter> y = y \\<sqinter> x\" nitpick [expect=genuine] oops\n\nend\n\nsubsection \\<open>Stronger Assumptions for Meet\\<close>\n\ntext \\<open>\nThe following axioms also hold in both models, but follow from the axioms of \\<open>subset_boolean_algebra_5_operations\\<close>.\n\\<close>\n\ntext \\<open>Definition 16\\<close>\n\nclass subset_boolean_algebra_4_extended = subset_boolean_algebra_3_extended +\n  assumes sba4_inf_right_unit[simp]: \"x \\<sqinter> top = x\"\n  assumes inf_right_isotone: \"x \\<le> y \\<Longrightarrow> z \\<sqinter> x \\<le> z \\<sqinter> y\"\nbegin\n\nlemma \"x \\<squnion> top = top\" nitpick [expect=genuine] oops\nlemma \"x \\<sqinter> bot = bot\" nitpick [expect=genuine] oops\nlemma \"x \\<sqinter> (y \\<squnion> z) = (x \\<sqinter> y) \\<squnion> (x \\<sqinter> z)\" nitpick [expect=genuine] oops\nlemma \"(x \\<sqinter> y = bot) = (x \\<le> - y)\" nitpick [expect=genuine] oops\n\nend\n\nsection \\<open>Boolean Algebras in Stone Algebras\\<close>\n\ntext \\<open>\nWe specialise \\<open>inf\\<close> to meet and complement to pseudocomplement.\nThis puts Stone algebras into the picture; for these it is well known that regular elements form a Boolean subalgebra \\<^cite>\\<open>\"Graetzer1971\"\\<close>.\n\\<close>\n\ntext \\<open>Definition 17\\<close>\n\nclass subset_boolean_algebra_5_extended = subset_boolean_algebra_3_extended +\n  assumes sba5_inf_commutative: \"x \\<sqinter> y = y \\<sqinter> x\"\n  assumes sba5_inf_absorb: \"x \\<sqinter> (x \\<squnion> y) = x\"\nbegin\n\nsubclass distrib_lattice_bot\nproof\n  show \"\\<And>x y. x \\<sqinter> y \\<le> x\"\n    by (metis sba5_inf_commutative sba3_inf_right_dist_sup sba5_inf_absorb sup_right_divisibility)\n  show \"\\<And>x y. x \\<sqinter> y \\<le> y\"\n    by (metis inf_left_isotone sba5_inf_absorb sba5_inf_commutative sup_ge2)\n  show \"\\<And>x y z. x \\<le> y \\<Longrightarrow> x \\<le> z \\<Longrightarrow> x \\<le> y \\<sqinter> z\"\n    by (metis inf_left_isotone sba5_inf_absorb sup.orderE sup_monoid.add_commute)\n  show \"\\<And>x y z. x \\<squnion> y \\<sqinter> z = (x \\<squnion> y) \\<sqinter> (x \\<squnion> z) \"\n    by (metis sba3_inf_right_dist_sup sba5_inf_absorb sba5_inf_commutative sup_assoc)\nqed\n\nlemma inf_demorgan_2:\n  \"-(x \\<sqinter> y) = -x \\<squnion> -y\"\n  using sba3_complement_inf_double_complement sba5_inf_commutative sub_sup_closed sub_sup_demorgan by auto\n\nlemma inf_export:\n  \"x \\<sqinter> -(x \\<sqinter> y) = x \\<sqinter> -y\"\n  using inf_demorgan_2 sba3_inf_complement_bot sba3_inf_right_dist_sup sba5_inf_commutative by auto\n\nlemma complement_inf[simp]:\n  \"x \\<sqinter> -x = bot\"\n  using sba3_inf_complement_bot sba5_inf_commutative by auto\n\ntext \\<open>Theorem 18.2\\<close>\n\nsubclass stone_algebra\nproof\n  show \"\\<And>x. x \\<le> top\"\n    by (simp add: inf.absorb_iff2)\n  show \"\\<And>x y. (x \\<sqinter> y = bot) = (x \\<le> - y)\"\n    by (metis (full_types) complement_bot complement_inf inf.cobounded1 inf.order_iff inf_export sba3_complement_inf_double_complement sba3_inf_left_unit)\n  show \"\\<And>x. - x \\<squnion> - - x = top\"\n    by simp\nqed\n\ntext \\<open>Theorem 18.1\\<close>\n\nsubclass subset_boolean_algebra_4_extended\nproof\n  show \"\\<And>x. x \\<sqinter> top = x\"\n    by simp\n  show \"\\<And>x y z. x \\<le> y \\<Longrightarrow> z \\<sqinter> x \\<le> z \\<sqinter> y\"\n    using inf.sup_right_isotone by blast\nqed\n\nend\n\ncontext stone_algebra_extended\nbegin\n\ntext \\<open>Theorem 18.3\\<close>\n\nsubclass subset_boolean_algebra_5_extended\nproof\n  show \"\\<And>x y z. x \\<squnion> (y \\<squnion> z) = x \\<squnion> y \\<squnion> z\"\n    using sup_assoc by auto\n  show \"\\<And>x y. x \\<squnion> y = y \\<squnion> x\"\n    by (simp add: sup_commute)\n  show \"\\<And>x. x \\<squnion> x = x\"\n    by simp\n  show \"\\<And>x y. x \\<squnion> - (y \\<squnion> - y) = x\"\n    by simp\n  show \"\\<And>x y. - (x \\<squnion> y) = - (- - x \\<squnion> - - y)\"\n    by auto\n  show \"\\<And>x y. - x \\<squnion> - (- x \\<squnion> y) = - x \\<squnion> - y\"\n    by (metis maddux_3_21_pp p_dist_sup regular_closed_p)\n  show \"bot = (THE x. \\<forall>z. x = - (z \\<squnion> - z))\"\n    by simp\n  thus \"top = - (THE x. \\<forall>z. x = - (z \\<squnion> - z))\"\n    using p_bot by blast\n  show \"\\<And>x y. - x \\<sqinter> - y = - (- - x \\<squnion> - - y)\"\n    by simp\n  show \"\\<And>x y. - x - - y = - (- - x \\<squnion> - y)\"\n    by auto\n  show \"\\<And>x y. (x \\<le> y) = (x \\<squnion> y = y)\"\n    by (simp add: le_iff_sup)\n  thus \"\\<And>x y. (x < y) = (x \\<squnion> y = y \\<and> y \\<squnion> x \\<noteq> x)\"\n    by (simp add: less_le_not_le)\n  show \"\\<And>x y z. x \\<sqinter> (y \\<sqinter> z) = x \\<sqinter> y \\<sqinter> z\"\n    by (simp add: inf.sup_monoid.add_assoc)\n  show \"\\<And>x y z. (x \\<squnion> y) \\<sqinter> z = x \\<sqinter> z \\<squnion> y \\<sqinter> z\"\n    by (simp add: inf_sup_distrib2)\n  show \"\\<And>x. - x \\<sqinter> x = bot\"\n    by simp\n  show \"\\<And>x. top \\<sqinter> x = x\"\n    by simp\n  show \"\\<And>x y. - (x \\<sqinter> - - y) = - (x \\<sqinter> y)\"\n    by simp\n  show \"\\<And>x y. x \\<sqinter> y = y \\<sqinter> x\"\n    by (simp add: inf_commute)\n  show \"\\<And>x y. x \\<sqinter> (x \\<squnion> y) = x\"\n    by simp\nqed\n\nend\n\nsection \\<open>Domain Semirings\\<close>\n\ntext \\<open>\nThe following development of tests in IL-semirings, prepredomain semirings, predomain semirings and domain semirings is mostly based on \\<^cite>\\<open>\"MoellerDesharnais2019\"\\<close>; see also \\<^cite>\\<open>\"DesharnaisMoeller2014\"\\<close>.\nSee \\<^cite>\\<open>\"DesharnaisMoellerStruth2006b\"\\<close> for domain axioms in idempotent semirings.\nSee \\<^cite>\\<open>\"DesharnaisJipsenStruth2009\" and \"JacksonStokes2004\"\\<close> for domain axioms in semigroups and monoids.\nSome variants have been implemented in \\<^cite>\\<open>\"GomesGuttmannHoefnerStruthWeber2016\"\\<close>.\n\\<close>\n\nsubsection \\<open>Idempotent Left Semirings\\<close>\n\ntext \\<open>Definition 19\\<close>\n\nclass il_semiring = sup + inf + bot + top + ord +\n  assumes il_associative: \"x \\<squnion> (y \\<squnion> z) = (x \\<squnion> y) \\<squnion> z\"\n  assumes il_commutative: \"x \\<squnion> y = y \\<squnion> x\"\n  assumes il_idempotent[simp]: \"x \\<squnion> x = x\"\n  assumes il_bot_unit: \"x \\<squnion> bot = x\"\n  assumes il_inf_associative: \"x \\<sqinter> (y \\<sqinter> z) = (x \\<sqinter> y) \\<sqinter> z\"\n  assumes il_inf_right_dist_sup: \"(x \\<squnion> y) \\<sqinter> z = (x \\<sqinter> z) \\<squnion> (y \\<sqinter> z)\"\n  assumes il_inf_left_unit[simp]: \"top \\<sqinter> x = x\"\n  assumes il_inf_right_unit[simp]: \"x \\<sqinter> top = x\"\n  assumes il_sub_inf_left_zero[simp]: \"bot \\<sqinter> x = bot\"\n  assumes il_sub_inf_right_isotone: \"x \\<le> y \\<Longrightarrow> z \\<sqinter> x \\<le> z \\<sqinter> y\"\n  assumes il_less_eq: \"x \\<le> y \\<longleftrightarrow> x \\<squnion> y = y\"\n  assumes il_less_def: \"x < y \\<longleftrightarrow> x \\<le> y \\<and> \\<not>(y \\<le> x)\"\nbegin\n\nlemma il_unit_bot: \"bot \\<squnion> x = x\"\n  using il_bot_unit il_commutative by fastforce\n\nsubclass order\nproof\n  show \"\\<And>x y. (x < y) = (x \\<le> y \\<and> \\<not> y \\<le> x)\"\n    by (simp add: il_less_def)\n  show \"\\<And>x. x \\<le> x\"\n    by (simp add: il_less_eq)\n  show \"\\<And>x y z. x \\<le> y \\<Longrightarrow> y \\<le> z \\<Longrightarrow> x \\<le> z\"\n    by (metis il_associative il_less_eq)\n  show \"\\<And>x y. x \\<le> y \\<Longrightarrow> y \\<le> x \\<Longrightarrow> x = y\"\n    by (simp add: il_commutative il_less_eq)\nqed\n\nlemma il_sub_inf_right_isotone_var:\n  \"(x \\<sqinter> y) \\<squnion> (x \\<sqinter> z) \\<le> x \\<sqinter> (y \\<squnion> z)\"\n  by (smt il_associative il_commutative il_idempotent il_less_eq il_sub_inf_right_isotone)\n\nlemma il_sub_inf_left_isotone:\n  \"x \\<le> y \\<Longrightarrow> x \\<sqinter> z \\<le> y \\<sqinter> z\"\n  by (metis il_inf_right_dist_sup il_less_eq)\n\nlemma il_sub_inf_left_isotone_var:\n  \"(y \\<sqinter> x) \\<squnion> (z \\<sqinter> x) \\<le> (y \\<squnion> z) \\<sqinter> x\"\n  by (simp add: il_inf_right_dist_sup)\n\nlemma sup_left_isotone:\n  \"x \\<le> y \\<Longrightarrow> x \\<squnion> z \\<le> y \\<squnion> z\"\n  by (smt il_associative il_commutative il_idempotent il_less_eq)\n\nlemma sup_right_isotone:\n  \"x \\<le> y \\<Longrightarrow> z \\<squnion> x \\<le> z \\<squnion> y\"\n  by (simp add: il_commutative sup_left_isotone)\n\nlemma bot_least:\n  \"bot \\<le> x\"\n  by (simp add: il_less_eq il_unit_bot)\n\nlemma less_eq_bot:\n  \"x \\<le> bot \\<longleftrightarrow> x = bot\"\n  by (simp add: il_bot_unit il_less_eq)\n\nabbreviation are_complementary :: \"'a \\<Rightarrow> 'a \\<Rightarrow> bool\"\n  where \"are_complementary x y \\<equiv> x \\<squnion> y = top \\<and> x \\<sqinter> y = bot \\<and> y \\<sqinter> x = bot\"\n\nabbreviation test :: \"'a \\<Rightarrow> bool\"\n  where \"test x \\<equiv> \\<exists>y . are_complementary x y\"\n\ndefinition tests :: \"'a set\"\n  where \"tests = { x . test x }\"\n\nlemma bot_test:\n  \"test bot\"\n  by (simp add: il_unit_bot)\n\nlemma top_test:\n  \"test top\"\n  by (simp add: il_bot_unit)\n\nlemma test_sub_identity:\n  \"test x \\<Longrightarrow> x \\<le> top\"\n  using il_associative il_less_eq by auto\n\nlemma neg_unique:\n  \"are_complementary x y \\<Longrightarrow> are_complementary x z \\<Longrightarrow> y = z\"\n  by (metis order.antisym il_inf_left_unit il_inf_right_dist_sup il_inf_right_unit il_sub_inf_right_isotone_var)\n\ndefinition neg :: \"'a \\<Rightarrow> 'a\" (\"!\")\n  where \"!x \\<equiv> THE y . are_complementary x y\"\n\nlemma neg_char:\n  assumes \"test x\"\n    shows \"are_complementary x (!x)\"\nproof (unfold neg_def)\n  from assms obtain y where 1: \"are_complementary x y\"\n    by auto\n  show \"are_complementary x (THE y. are_complementary x y)\"\n  proof (rule theI)\n    show \"are_complementary x y\"\n      using 1 by simp\n    show \"\\<And>z. are_complementary x z \\<Longrightarrow> z = y\"\n      using 1 neg_unique by blast\n  qed\nqed\n\nlemma are_complementary_symmetric:\n  \"are_complementary x y \\<longleftrightarrow> are_complementary y x\"\n  using il_commutative by auto\n\nlemma neg_test:\n  \"test x \\<Longrightarrow> test (!x)\"\n  using are_complementary_symmetric neg_char by blast\n\nlemma are_complementary_test:\n  \"test x \\<Longrightarrow> are_complementary x y \\<Longrightarrow> test y\"\n  using il_commutative by auto\n\nlemma neg_involutive:\n  \"test x \\<Longrightarrow> !(!x) = x\"\n  using are_complementary_symmetric neg_char neg_unique by blast\n\nlemma test_inf_left_below:\n  \"test x \\<Longrightarrow> x \\<sqinter> y \\<le> y\"\n  by (metis il_associative il_idempotent il_inf_left_unit il_inf_right_dist_sup il_less_eq)\n\nlemma test_inf_right_below:\n  \"test x \\<Longrightarrow> y \\<sqinter> x \\<le> y\"\n  by (metis il_inf_right_unit il_sub_inf_right_isotone test_sub_identity)\n\nlemma neg_bot:\n  \"!bot = top\"\n  using il_unit_bot neg_char by fastforce\n\nlemma neg_top:\n  \"!top = bot\"\n  using bot_test neg_bot neg_involutive by fastforce\n\nlemma test_inf_idempotent:\n  \"test x \\<Longrightarrow> x \\<sqinter> x = x\"\n  by (metis il_bot_unit il_inf_left_unit il_inf_right_dist_sup)\n\nlemma test_inf_semicommutative:\n  assumes \"test x\"\n      and \"test y\"\n  shows \"x \\<sqinter> y \\<le> y \\<sqinter> x\"\nproof -\n  have \"x \\<sqinter> y = (y \\<sqinter> x \\<sqinter> y) \\<squnion> (!y \\<sqinter> x \\<sqinter> y)\"\n    by (metis assms(2) il_inf_left_unit il_inf_right_dist_sup neg_char)\n  also have \"... \\<le> (y \\<sqinter> x \\<sqinter> y) \\<squnion> (!y \\<sqinter> y)\"\n  proof -\n    obtain z where \"are_complementary y z\"\n      using assms(2) by blast\n    hence \"y \\<sqinter> (x \\<sqinter> y) \\<squnion> !y \\<sqinter> (x \\<sqinter> y) \\<le> y \\<sqinter> (x \\<sqinter> y)\"\n      by (metis assms(1) calculation il_sub_inf_left_isotone il_bot_unit il_idempotent il_inf_associative il_less_eq neg_char test_inf_right_below)\n    thus ?thesis\n      by (simp add: il_associative il_inf_associative il_less_eq)\n  qed\n  also have \"... \\<le> (y \\<sqinter> x) \\<squnion> (!y \\<sqinter> y)\"\n    by (metis assms(2) il_bot_unit il_inf_right_unit il_sub_inf_right_isotone neg_char test_sub_identity)\n  also have \"... = y \\<sqinter> x\"\n    by (simp add: assms(2) il_bot_unit neg_char)\n  finally show ?thesis\n    .\nqed\n\nlemma test_inf_commutative:\n  \"test x \\<Longrightarrow> test y \\<Longrightarrow> x \\<sqinter> y = y \\<sqinter> x\"\n  by (simp add: order.antisym test_inf_semicommutative)\n\nlemma test_inf_bot:\n  \"test x \\<Longrightarrow> x \\<sqinter> bot = bot\"\n  using il_inf_associative test_inf_idempotent by fastforce\n\nlemma test_absorb_1:\n  \"test x \\<Longrightarrow> test y \\<Longrightarrow> x \\<squnion> (x \\<sqinter> y) = x\"\n  using il_commutative il_less_eq test_inf_right_below by auto\n\nlemma test_absorb_2:\n  \"test x \\<Longrightarrow> test y \\<Longrightarrow> x \\<squnion> (y \\<sqinter> x) = x\"\n  by (metis test_absorb_1 test_inf_commutative)\n\nlemma test_absorb_3:\n  \"test x \\<Longrightarrow> test y \\<Longrightarrow> x \\<sqinter> (x \\<squnion> y) = x\"\n  apply (rule order.antisym)\n  apply (metis il_associative il_inf_right_unit il_less_eq il_sub_inf_right_isotone test_sub_identity)\n  by (metis il_sub_inf_right_isotone_var test_absorb_1 test_inf_idempotent)\n\nlemma test_absorb_4:\n  \"test x \\<Longrightarrow> test y \\<Longrightarrow> (x \\<squnion> y) \\<sqinter> x = x\"\n  by (smt il_inf_right_dist_sup test_inf_idempotent il_commutative il_less_eq test_inf_left_below)\n\nlemma test_import_1:\n  assumes \"test x\"\n      and \"test y\"\n    shows \"x \\<squnion> (!x \\<sqinter> y) = x \\<squnion> y\"\nproof -\n  have \"x \\<squnion> (!x \\<sqinter> y) = x \\<squnion> ((y \\<squnion> !y) \\<sqinter> x) \\<squnion> (!x \\<sqinter> y)\"\n    by (simp add: assms(2) neg_char)\n  also have \"... = x \\<squnion> (!y \\<sqinter> x) \\<squnion> (x \\<sqinter> y) \\<squnion> (!x \\<sqinter> y)\"\n    by (smt assms il_associative il_commutative il_inf_right_dist_sup test_inf_commutative)\n  also have \"... = x \\<squnion> ((x \\<squnion> !x) \\<sqinter> y)\"\n    by (smt calculation il_associative il_commutative il_idempotent il_inf_right_dist_sup)\n  also have \"... = x \\<squnion> y\"\n    by (simp add: assms(1) neg_char)\n  finally show ?thesis\n    .\nqed\n\nlemma test_import_2:\n  assumes \"test x\"\n      and \"test y\"\n    shows \"x \\<squnion> (y \\<sqinter> !x) = x \\<squnion> y\"\nproof -\n  obtain z where 1: \"are_complementary y z\"\n    using assms(2) by moura\n  obtain w where 2: \"are_complementary x w\"\n    using assms(1) by auto\n  hence \"x \\<sqinter> !x = bot\"\n    using neg_char by blast\n  hence \"!x \\<sqinter> y = y \\<sqinter> !x\"\n    using 1 2 by (metis il_commutative neg_char test_inf_commutative)\n  thus ?thesis\n    using 1 2 by (metis test_import_1)\nqed\n\nlemma test_import_3:\n  assumes \"test x\"\n    shows \"(!x \\<squnion> y) \\<sqinter> x = y \\<sqinter> x\"\n  by (simp add: assms(1) il_inf_right_dist_sup il_unit_bot neg_char)\n\nlemma test_import_4:\n  assumes \"test x\"\n      and \"test y\"\n    shows \"(!x \\<squnion> y) \\<sqinter> x = x \\<sqinter> y\"\n  by (metis assms test_import_3 test_inf_commutative)\n\nlemma test_inf:\n  \"test x \\<Longrightarrow> test y \\<Longrightarrow> test z \\<Longrightarrow> z \\<le> x \\<sqinter> y \\<longleftrightarrow> z \\<le> x \\<and> z \\<le> y\"\n  apply (rule iffI)\n  using dual_order.trans test_inf_left_below test_inf_right_below apply blast\n  by (smt il_less_eq il_sub_inf_right_isotone test_absorb_4)\n\nlemma test_shunting:\n  assumes \"test x\"\n      and \"test y\"\n    shows \"x \\<sqinter> y \\<le> z \\<longleftrightarrow> x \\<le> !y \\<squnion> z\"\nproof\n  assume 1: \"x \\<sqinter> y \\<le> z\"\n  have \"x = (!y \\<sqinter> x) \\<squnion> (y \\<sqinter> x)\"\n    by (metis assms(2) il_commutative il_inf_left_unit il_inf_right_dist_sup neg_char)\n  also have \"... \\<le> !y \\<squnion> (y \\<sqinter> x)\"\n    by (simp add: assms(1) sup_left_isotone test_inf_right_below)\n  also have \"... \\<le> !y \\<squnion> z\"\n    using 1 by (simp add: assms sup_right_isotone test_inf_commutative)\n  finally show \"x \\<le> !y \\<squnion> z\"\n    .\nnext\n  assume \"x \\<le> !y \\<squnion> z\"\n  hence \"x \\<sqinter> y \\<le> (!y \\<squnion> z) \\<sqinter> y\"\n    using il_sub_inf_left_isotone by blast\n  also have \"... = z \\<sqinter> y\"\n    by (simp add: assms(2) test_import_3)\n  also have \"... \\<le> z\"\n    by (simp add: assms(2) test_inf_right_below)\n  finally show \"x \\<sqinter> y \\<le> z\"\n    .\nqed\n\nlemma test_shunting_bot:\n  assumes \"test x\"\n      and \"test y\"\n    shows \"x \\<le> y \\<longleftrightarrow> x \\<sqinter> !y \\<le> bot\"\n  by (simp add: assms il_bot_unit neg_involutive neg_test test_shunting)\n\nlemma test_shunting_bot_eq:\n  assumes \"test x\"\n      and \"test y\"\n    shows \"x \\<le> y \\<longleftrightarrow> x \\<sqinter> !y = bot\"\n  by (simp add: assms test_shunting_bot less_eq_bot)\n\nlemma neg_antitone:\n  assumes \"test x\"\n      and \"test y\"\n      and \"x \\<le> y\"\n    shows \"!y \\<le> !x\"\nproof -\n  have 1: \"x \\<sqinter> !y = bot\"\n    using assms test_shunting_bot_eq by blast\n  have 2: \"x \\<squnion> !x = top\"\n    by (simp add: assms(1) neg_char)\n  have \"are_complementary y (!y)\"\n    by (simp add: assms(2) neg_char)\n  thus ?thesis\n    using 1 2 by (metis il_unit_bot il_commutative il_inf_left_unit il_inf_right_dist_sup il_inf_right_unit il_sub_inf_right_isotone test_sub_identity)\nqed\n\nlemma test_sup_neg_1:\n  assumes \"test x\"\n      and \"test y\"\n    shows \"(x \\<squnion> y) \\<squnion> (!x \\<sqinter> !y) = top\"\nproof -\n  have \"x \\<squnion> !x = top\"\n    by (simp add: assms(1) neg_char)\n  hence \"x \\<squnion> (y \\<squnion> !x) = top\"\n    by (metis assms(2) il_associative il_commutative il_idempotent)\n  hence \"x \\<squnion> (y \\<squnion> !x \\<sqinter> !y) = top\"\n    by (simp add: assms neg_test test_import_2)\n  thus ?thesis\n    by (simp add: il_associative)\nqed\n\nlemma test_sup_neg_2:\n  assumes \"test x\"\n      and \"test y\"\n    shows \"(x \\<squnion> y) \\<sqinter> (!x \\<sqinter> !y) = bot\"\nproof -\n  have 1: \"are_complementary y (!y)\"\n    by (simp add: assms(2) neg_char)\n  obtain z where 2: \"are_complementary x z\"\n    using assms(1) by auto\n  hence \"!x = z\"\n    using neg_char neg_unique by blast\n  thus ?thesis\n    using 1 2 by (metis are_complementary_symmetric il_inf_associative neg_involutive test_import_3 test_inf_bot test_inf_commutative)\nqed\n\nlemma de_morgan_1:\n  assumes \"test x\"\n      and \"test y\"\n      and \"test (x \\<sqinter> y)\"\n    shows \"!(x \\<sqinter> y) = !x \\<squnion> !y\"\nproof (rule order.antisym)\n  have 1: \"test (!(x \\<sqinter> y))\"\n    by (simp add: assms neg_test)\n  have \"x \\<le> (x \\<sqinter> y) \\<squnion> !y\"\n    by (metis (full_types) assms il_commutative neg_char test_shunting test_shunting_bot_eq)\n  hence \"x \\<sqinter> !(x \\<sqinter> y) \\<le> !y\"\n    using 1 by (simp add: assms(1,3) neg_involutive test_shunting)\n  hence \"!(x \\<sqinter> y) \\<sqinter> x \\<le> !y\"\n    using 1 by (metis assms(1) test_inf_commutative)\n  thus \"!(x \\<sqinter> y) \\<le> !x \\<squnion> !y\"\n    using 1 assms(1) test_shunting by blast\n  have 2: \"!x \\<le> !(x \\<sqinter> y)\"\n    by (simp add: assms neg_antitone test_inf_right_below)\n  have \"!y \\<le> !(x \\<sqinter> y)\"\n    by (simp add: assms neg_antitone test_inf_left_below)\n  thus \"!x \\<squnion> !y \\<le> !(x \\<sqinter> y)\"\n    using 2 by (metis il_associative il_less_eq)\nqed\n\nlemma de_morgan_2:\n  assumes \"test x\"\n      and \"test y\"\n      and \"test (x \\<squnion> y)\"\n    shows \"!(x \\<squnion> y) = !x \\<sqinter> !y\"\nproof (rule order.antisym)\n  have 1: \"!(x \\<squnion> y) \\<le> !x\"\n    by (metis assms il_inf_left_unit il_sub_inf_left_isotone neg_antitone test_absorb_3 test_sub_identity)\n  have \"!(x \\<squnion> y) \\<le> !y\"\n    by (metis assms il_commutative il_inf_left_unit il_sub_inf_left_isotone neg_antitone test_absorb_3 test_sub_identity)\n  thus \"!(x \\<squnion> y) \\<le> !x \\<sqinter> !y\"\n    using 1 by (simp add: assms neg_test test_inf)\n  have \"top \\<le> x \\<squnion> y \\<squnion> !(x \\<squnion> y)\"\n    by (simp add: assms(3) neg_char)\n  hence \"top \\<sqinter> !x \\<le> y \\<squnion> !(x \\<squnion> y)\"\n    by (smt assms(1) assms(3) il_commutative il_inf_right_dist_sup il_inf_right_unit il_sub_inf_right_isotone il_unit_bot neg_char test_sub_identity)\n  thus \"!x \\<sqinter> !y \\<le> !(x \\<squnion> y)\"\n    by (simp add: assms(1) assms(2) neg_involutive neg_test test_shunting)\nqed\n\nlemma test_inf_closed_sup_complement:\n  assumes \"test x\"\n      and \"test y\"\n      and \"\\<forall>u v . test u \\<and> test v \\<longrightarrow> test (u \\<sqinter> v)\"\n    shows \"!x \\<sqinter> !y \\<sqinter> (x \\<squnion> y) = bot\"\nproof -\n  have 1: \"!(!x \\<sqinter> !y) = x \\<squnion> y\"\n    by (simp add: assms de_morgan_1 neg_involutive neg_test)\n  have \"test (!(!x \\<sqinter> !y))\"\n    by (metis assms neg_test)\n  thus ?thesis\n    using 1 by (metis assms(1,2) de_morgan_2 neg_char)\nqed\n\nlemma test_sup_complement_sup_closed:\n  assumes \"test x\"\n      and \"test y\"\n      and \"\\<forall>u v . test u \\<and> test v \\<longrightarrow> !u \\<sqinter> !v \\<sqinter> (u \\<squnion> v) = bot\"\n    shows \"test (x \\<squnion> y)\"\n  by (meson assms test_sup_neg_1 test_sup_neg_2)\n\nlemma test_inf_closed_sup_closed:\n  assumes \"test x\"\n      and \"test y\"\n      and \"\\<forall>u v . test u \\<and> test v \\<longrightarrow> test (u \\<sqinter> v)\"\n    shows \"test (x \\<squnion> y)\"\n  using assms test_inf_closed_sup_complement test_sup_complement_sup_closed by simp\n\nend\n\nsubsection \\<open>Prepredomain Semirings\\<close>\n\nclass dom =\n  fixes d :: \"'a \\<Rightarrow> 'a\"\n\nclass ppd_semiring = il_semiring + dom +\n  assumes d_closed: \"test (d x)\"\n  assumes d1: \"x \\<le> d x \\<sqinter> x\"\nbegin\n\nlemma d_sub_identity:\n  \"d x \\<le> top\"\n  using d_closed test_sub_identity by blast\n\nlemma d1_eq:\n  \"x = d x \\<sqinter> x\"\nproof -\n  have \"x = (d x \\<squnion> top) \\<sqinter> x\"\n    using d_sub_identity il_less_eq by auto\n  thus ?thesis\n    using d1 il_commutative il_inf_right_dist_sup il_less_eq by force\nqed\n\nlemma d_increasing_sub_identity:\n  \"x \\<le> top \\<Longrightarrow> x \\<le> d x\"\n  by (metis d1_eq il_inf_right_unit il_sub_inf_right_isotone)\n\nlemma d_top:\n  \"d top = top\"\n  by (simp add: d_increasing_sub_identity d_sub_identity dual_order.antisym)\n\nlemma d_bot_only:\n  \"d x = bot \\<Longrightarrow> x = bot\"\n  by (metis d1_eq il_sub_inf_left_zero)\n\nlemma d_strict: \"d bot \\<le> bot\" nitpick [expect=genuine] oops\nlemma d_isotone_var: \"d x \\<le> d (x \\<squnion> y)\" nitpick [expect=genuine] oops\nlemma d_fully_strict: \"d x = bot \\<longleftrightarrow> x = bot\" nitpick [expect=genuine] oops\nlemma test_d_fixpoint: \"test x \\<Longrightarrow> d x = x\" nitpick [expect=genuine] oops\n\nend\n\nsubsection \\<open>Predomain Semirings\\<close>\n\nclass pd_semiring = ppd_semiring +\n  assumes d2: \"test p \\<Longrightarrow> d (p \\<sqinter> x) \\<le> p\"\nbegin\n\nlemma d_strict:\n  \"d bot \\<le> bot\"\n  using bot_test d2 by fastforce\n\nlemma d_strict_eq:\n  \"d bot = bot\"\n  using d_strict il_bot_unit il_less_eq by auto\n\nlemma test_d_fixpoint:\n  \"test x \\<Longrightarrow> d x = x\"\n  by (metis order.antisym d1_eq d2 test_inf_idempotent test_inf_right_below)\n\nlemma d_surjective:\n  \"test x \\<Longrightarrow> \\<exists>y . d y = x\"\n  using test_d_fixpoint by blast\n\nlemma test_d_fixpoint_iff:\n  \"test x \\<longleftrightarrow> d x = x\"\n  by (metis d_closed test_d_fixpoint)\n\nlemma d_surjective_iff:\n  \"test x \\<longleftrightarrow> (\\<exists>y . d y = x)\"\n  using d_surjective d_closed by blast\n\nlemma tests_d_range:\n  \"tests = range d\"\n  using tests_def image_def d_surjective_iff by auto\n\nlemma llp:\n  assumes \"test y\"\n    shows \"d x \\<le> y \\<longleftrightarrow> x \\<le> y \\<sqinter> x\"\n  by (metis assms d1_eq d2 order.eq_iff il_sub_inf_left_isotone test_inf_left_below)\n\nlemma gla:\n  assumes \"test y\"\n    shows \"y \\<le> !(d x) \\<longleftrightarrow> y \\<sqinter> x \\<le> bot\"\nproof -\n  obtain ad where 1: \"\\<forall>x. are_complementary (d x) (ad x)\"\n    using d_closed by moura\n  hence 2: \"\\<forall>x y. d (d y \\<sqinter> x) \\<le> d y\"\n    using d2 by blast\n  have 3: \"\\<forall>x. ad x \\<sqinter> x = bot\"\n    using 1 by (metis d1_eq il_inf_associative il_sub_inf_left_zero)\n  have 4: \"\\<forall>x y. d y \\<sqinter> x \\<squnion> ad y \\<sqinter> x = top \\<sqinter> x\"\n    using 1 by (metis il_inf_right_dist_sup)\n  have 5: \"\\<forall>x y z. z \\<sqinter> y \\<le> x \\<sqinter> y \\<or> (z \\<squnion> x) \\<sqinter> y \\<noteq> x \\<sqinter> y\"\n    by (simp add: il_inf_right_dist_sup il_less_eq)\n  have 6: \"\\<forall>x. !(d x) = ad x\"\n    using 1 neg_char neg_unique by blast\n  have 7: \"\\<forall>x. top \\<sqinter> x = x\"\n    by auto\n  hence \"\\<forall>x. y \\<sqinter> x \\<squnion> !y \\<sqinter> x = x\"\n    by (metis assms il_inf_right_dist_sup neg_char)\n  thus ?thesis\n    using 1 2 3 4 5 6 7 by (metis assms d1_eq il_commutative il_less_eq test_d_fixpoint)\nqed\n\nlemma gla_var:\n  \"test y \\<Longrightarrow> y \\<sqinter> d x \\<le> bot \\<longleftrightarrow> y \\<sqinter> x \\<le> bot\"\n  using gla d_closed il_bot_unit test_shunting by auto\n\nlemma llp_var:\n  assumes \"test y\"\n    shows \"y \\<le> !(d x) \\<longleftrightarrow> x \\<le> !y \\<sqinter> x\"\n  apply (rule iffI)\n  apply (metis (no_types, opaque_lifting) assms gla Least_equality il_inf_left_unit il_inf_right_dist_sup il_less_eq il_unit_bot order.refl neg_char)\n  by (metis assms gla gla_var llp il_commutative il_sub_inf_right_isotone neg_char)\n\nlemma d_idempotent:\n  \"d (d x) = d x\"\n  using d_closed test_d_fixpoint_iff by auto\n\nlemma d_neg:\n  \"test x \\<Longrightarrow> d (!x) = !x\"\n  using il_commutative neg_char test_d_fixpoint_iff by fastforce\n\nlemma d_fully_strict:\n  \"d x = bot \\<longleftrightarrow> x = bot\"\n  using d_strict_eq d_bot_only by blast\n\nlemma d_ad_comp:\n  \"!(d x) \\<sqinter> x = bot\"\nproof -\n  have \"\\<forall>x. !(d x) \\<sqinter> d x = bot\"\n    by (simp add: d_closed neg_char)\n  thus ?thesis\n    by (metis d1_eq il_inf_associative il_sub_inf_left_zero)\nqed\n\nlemma d_isotone:\n  assumes \"x \\<le> y\"\n    shows \"d x \\<le> d y\"\nproof -\n  obtain ad where 1: \"\\<forall>x. are_complementary (d x) (ad x)\"\n    using d_closed by moura\n  hence \"ad y \\<sqinter> x \\<le> bot\"\n    by (metis assms d1_eq il_inf_associative il_sub_inf_left_zero il_sub_inf_right_isotone)\n  thus ?thesis\n    using 1 by (metis d2 il_bot_unit il_inf_left_unit il_inf_right_dist_sup il_less_eq)\nqed\n\nlemma d_isotone_var:\n  \"d x \\<le> d (x \\<squnion> y)\"\n  using d_isotone il_associative il_less_eq by auto\n\nlemma d3_conv:\n  \"d (x \\<sqinter> y) \\<le> d (x \\<sqinter> d y)\"\n  by (metis (mono_tags, opaque_lifting) d1_eq d2 d_closed il_inf_associative)\n\nlemma d_test_inf_idempotent:\n  \"d x \\<sqinter> d x = d x\"\n  by (metis d_idempotent d1_eq)\n\nlemma d_test_inf_closed:\n  assumes \"test x\"\n      and \"test y\"\n    shows \"d (x \\<sqinter> y) = x \\<sqinter> y\"\nproof (rule order.antisym)\n  have \"d (x \\<sqinter> y) = d (x \\<sqinter> y) \\<sqinter> d (x \\<sqinter> y)\"\n    by (simp add: d_test_inf_idempotent)\n  also have \"... \\<le> x \\<sqinter> d (x \\<sqinter> y)\"\n    by (simp add: assms(1) d2 il_sub_inf_left_isotone)\n  also have \"... \\<le> x \\<sqinter> y\"\n    by (metis assms d_isotone il_sub_inf_right_isotone test_inf_left_below test_d_fixpoint)\n  finally show \"d (x \\<sqinter> y) \\<le> x \\<sqinter> y\"\n    .\n  show \"x \\<sqinter> y \\<le> d (x \\<sqinter> y)\"\n    using assms d_increasing_sub_identity dual_order.trans test_inf_left_below test_sub_identity by blast\nqed\n\nlemma test_inf_closed:\n  \"test x \\<Longrightarrow> test y \\<Longrightarrow> test (x \\<sqinter> y)\"\n  using d_test_inf_closed test_d_fixpoint_iff by simp\n\nlemma test_sup_closed:\n  \"test x \\<Longrightarrow> test y \\<Longrightarrow> test (x \\<squnion> y)\"\n  using test_inf_closed test_inf_closed_sup_closed by simp\n\nlemma d_export:\n  assumes \"test x\"\n    shows \"d (x \\<sqinter> y) = x \\<sqinter> d y\"\nproof (rule order.antisym)\n  have 1: \"d (x \\<sqinter> y) \\<le> x\"\n    by (simp add: assms d2)\n  have \"d (x \\<sqinter> y) \\<le> d y\"\n    by (metis assms d_isotone_var il_inf_left_unit il_inf_right_dist_sup)\n  thus \"d (x \\<sqinter> y) \\<le> x \\<sqinter> d y\"\n    using 1 by (metis assms d_idempotent llp dual_order.trans il_sub_inf_right_isotone)\n  have \"y = (!x \\<sqinter> y) \\<squnion> (x \\<sqinter> y)\"\n    by (metis assms il_commutative il_inf_left_unit il_inf_right_dist_sup neg_char)\n  also have \"... = (!x \\<sqinter> y) \\<squnion> (d (x \\<sqinter> y) \\<sqinter> x \\<sqinter> y)\"\n    by (metis d1_eq il_inf_associative)\n  also have \"... = (!x \\<sqinter> y) \\<squnion> (d (x \\<sqinter> y) \\<sqinter> y)\"\n    using 1 by (smt calculation d1_eq il_associative il_commutative il_inf_associative il_inf_right_dist_sup il_less_eq il_sub_inf_right_isotone_var)\n  also have \"... = (!x \\<squnion> d (x \\<sqinter> y)) \\<sqinter> y\"\n    by (simp add: il_inf_right_dist_sup)\n  finally have \"y \\<le> (!x \\<squnion> d (x \\<sqinter> y)) \\<sqinter> y\"\n    by simp\n  hence \"d y \\<le> !x \\<squnion> d (x \\<sqinter> y)\"\n    using assms llp test_sup_closed neg_test d_closed by simp\n  hence \"d y \\<sqinter> x \\<le> d (x \\<sqinter> y)\"\n    by (simp add: assms d_closed test_shunting)\n  thus \"x \\<sqinter> d y \\<le> d (x \\<sqinter> y)\"\n    by (metis assms d_closed test_inf_commutative)\nqed\n\nlemma test_inf_left_dist_sup:\n  assumes \"test x\"\n      and \"test y\"\n      and \"test z\"\n    shows \"x \\<sqinter> (y \\<squnion> z) = (x \\<sqinter> y) \\<squnion> (x \\<sqinter> z)\"\nproof -\n  have \"x \\<sqinter> (y \\<squnion> z) = (y \\<squnion> z) \\<sqinter> x\"\n    using assms test_sup_closed test_inf_commutative by smt\n  also have \"... = (y \\<sqinter> x) \\<squnion> (z \\<sqinter> x)\"\n    using il_inf_right_dist_sup by simp\n  also have \"... = (x \\<sqinter> y) \\<squnion> (x \\<sqinter> z)\"\n    using assms test_sup_closed test_inf_commutative by smt\n  finally show ?thesis\n    .\nqed\n\nlemma \"!x \\<squnion> !y = !(!(!x \\<squnion> !y))\" nitpick [expect=genuine] oops\nlemma \"d x = !(!x)\" nitpick [expect=genuine] oops\n\nsublocale subset_boolean_algebra where uminus = \"\\<lambda> x . !(d x)\"\nproof\n  show \"\\<And>x y z. !(d x) \\<squnion> (!(d y) \\<squnion> !(d z)) = !(d x) \\<squnion> !(d y) \\<squnion> !(d z)\"\n    using il_associative by blast\n  show \"\\<And>x y. !(d x) \\<squnion> !(d y) = !(d y) \\<squnion> !(d x)\"\n    by (simp add: il_commutative)\n  show \"\\<And>x y. !(d x) \\<squnion> !(d y) = !(d (!(d (!(d x) \\<squnion> !(d y)))))\"\n  proof -\n    fix x y\n    have \"test (!(d x)) \\<and> test (!(d y))\"\n      by (simp add: d_closed neg_test)\n    hence \"test (!(d x) \\<squnion> !(d y))\"\n      by (simp add: test_sup_closed)\n    thus \"!(d x) \\<squnion> !(d y) = !(d (!(d (!(d x) \\<squnion> !(d y)))))\"\n      by (simp add: d_neg neg_involutive test_d_fixpoint)\n  qed\n  show \"\\<And>x y. !(d x) = !(d (!(d (!(d x))) \\<squnion> !(d y))) \\<squnion> !(d (!(d (!(d x))) \\<squnion> !(d (!(d y)))))\"\n  proof -\n    fix x y\n    have \"!(d (!(d (!(d x))) \\<squnion> !(d y))) \\<squnion> !(d (!(d (!(d x))) \\<squnion> !(d (!(d y))))) = !(d x \\<squnion> !(d y)) \\<squnion> !(d x \\<squnion> d y)\"\n      using d_closed neg_test test_sup_closed neg_involutive test_d_fixpoint by auto\n    also have \"... = (!(d x) \\<sqinter> d y) \\<squnion> (!(d x) \\<sqinter> !(d y))\"\n      using d_closed neg_test test_sup_closed neg_involutive de_morgan_2 by auto\n    also have \"... = !(d x) \\<sqinter> (d y \\<squnion> !(d y))\"\n      using d_closed neg_test test_inf_left_dist_sup by auto\n    also have \"... = !(d x) \\<sqinter> top\"\n      by (simp add: neg_char d_closed)\n    finally show \"!(d x) = !(d (!(d (!(d x))) \\<squnion> !(d y))) \\<squnion> !(d (!(d (!(d x))) \\<squnion> !(d (!(d y)))))\"\n      by simp\n  qed\nqed\n\nlemma d_dist_sup:\n  \"d (x \\<squnion> y) = d x \\<squnion> d y\"\nproof (rule order.antisym)\n  have \"x \\<le> d x \\<sqinter> x\"\n    by (simp add: d1)\n  also have \"... \\<le> (d x \\<squnion> d y) \\<sqinter> (x \\<squnion> y)\"\n    using il_associative il_inf_right_dist_sup il_less_eq il_sub_inf_right_isotone by auto\n  finally have 1: \"x \\<le> (d x \\<squnion> d y) \\<sqinter> (x \\<squnion> y)\"\n    .\n  have \"y \\<le> d y \\<sqinter> y\"\n    by (simp add: d1)\n  also have \"... \\<le> (d y \\<squnion> d x) \\<sqinter> (y \\<squnion> x)\"\n    using il_associative il_idempotent il_inf_right_dist_sup il_less_eq il_sub_inf_right_isotone by simp\n  finally have \"y \\<le> (d x \\<squnion> d y) \\<sqinter> (x \\<squnion> y)\"\n    using il_commutative by auto\n  hence \"x \\<squnion> y \\<le> (d x \\<squnion> d y) \\<sqinter> (x \\<squnion> y)\"\n    using 1 by (metis il_associative il_less_eq)\n  thus \"d (x \\<squnion> y) \\<le> d x \\<squnion> d y\"\n    using llp test_sup_closed neg_test d_closed by simp\n  show \"d x \\<squnion> d y \\<le> d (x \\<squnion> y)\"\n    using d_isotone_var il_associative il_commutative il_less_eq by fastforce\nqed\n\nend\n\nclass pd_semiring_extended = pd_semiring + uminus +\n  assumes uminus_def: \"-x = !(d x)\"\nbegin\n\nsubclass subset_boolean_algebra\n  by (metis subset_boolean_algebra_axioms uminus_def ext)\n\nend\n\nsubsection \\<open>Domain Semirings\\<close>\n\nclass d_semiring = pd_semiring +\n  assumes d3: \"d (x \\<sqinter> d y) \\<le> d (x \\<sqinter> y)\"\nbegin\n\nlemma d3_eq: \"d (x \\<sqinter> d y) = d (x \\<sqinter> y)\"\n  by (simp add: order.antisym d3 d3_conv)\n\nend\n\ntext \\<open>\nAxioms (d1), (d2) and (d3) are independent in IL-semirings.\n\\<close>\n\ncontext il_semiring\nbegin\n\ncontext\n  fixes d :: \"'a \\<Rightarrow> 'a\"\n  assumes d_closed: \"test (d x)\"\nbegin\n\ncontext\n  assumes d1: \"x \\<le> d x \\<sqinter> x\"\n  assumes d2: \"test p \\<Longrightarrow> d (p \\<sqinter> x) \\<le> p\"\nbegin\n\nlemma d3: \"d (x \\<sqinter> d y) \\<le> d (x \\<sqinter> y)\" nitpick [expect=genuine] oops\n\nend\n\ncontext\n  assumes d1: \"x \\<le> d x \\<sqinter> x\"\n  assumes d3: \"d (x \\<sqinter> d y) \\<le> d (x \\<sqinter> y)\"\nbegin\n\nlemma d2: \"test p \\<Longrightarrow> d (p \\<sqinter> x) \\<le> p\" nitpick [expect=genuine] oops\n\nend\n\ncontext\n  assumes d2: \"test p \\<Longrightarrow> d (p \\<sqinter> x) \\<le> p\"\n  assumes d3: \"d (x \\<sqinter> d y) \\<le> d (x \\<sqinter> y)\"\nbegin\n\nlemma d1: \"x \\<le> d x \\<sqinter> x\" nitpick [expect=genuine] oops\n\nend\n\nend\n\nend\n\nclass d_semiring_var = ppd_semiring +\n  assumes d3_var: \"d (x \\<sqinter> d y) \\<le> d (x \\<sqinter> y)\"\n  assumes d_strict_eq_var: \"d bot = bot\"\nbegin\n\nlemma d2_var:\n  assumes \"test p\"\n    shows \"d (p \\<sqinter> x) \\<le> p\"\nproof -\n  have \"!p \\<sqinter> p \\<sqinter> x = bot\"\n    by (simp add: assms neg_char)\n  hence \"d (!p \\<sqinter> p \\<sqinter> x) = bot\"\n    by (simp add: d_strict_eq_var)\n  hence \"d (!p \\<sqinter> d (p \\<sqinter> x)) = bot\"\n    by (metis d3_var il_inf_associative less_eq_bot)\n  hence \"!p \\<sqinter> d (p \\<sqinter> x) = bot\"\n    using d_bot_only by blast\n  thus ?thesis\n    by (metis (no_types, opaque_lifting) assms d_sub_identity il_bot_unit il_inf_left_unit il_inf_right_dist_sup il_inf_right_unit il_sub_inf_right_isotone neg_char)\nqed\n\nsubclass d_semiring\nproof\n  show \"\\<And>p x. test p \\<Longrightarrow> d (p \\<sqinter> x) \\<le> p\"\n    by (simp add: d2_var)\n  show \"\\<And>x y. d (x \\<sqinter> d y) \\<le> d (x \\<sqinter> y)\"\n    by (simp add: d3_var)\nqed\n\nend\n\nsection \\<open>Antidomain Semirings\\<close>\n\ntext \\<open>\nWe now develop prepreantidomain semirings, preantidomain semirings and antidomain semirings.\nSee \\<^cite>\\<open>\"DesharnaisStruth2008b\" and \"DesharnaisStruth2008a\" and \"DesharnaisStruth2011\"\\<close> for related work on internal axioms for antidomain.\n\\<close>\n\nsubsection \\<open>Prepreantidomain Semirings\\<close>\n\ntext \\<open>Definition 20\\<close>\n\nclass ppa_semiring = il_semiring + uminus +\n  assumes a_inf_complement_bot: \"-x \\<sqinter> x = bot\"\n  assumes a_stone[simp]: \"-x \\<squnion> --x = top\"\nbegin\n\ntext \\<open>Theorem 21\\<close>\n\nlemma l1:\n  \"-top = bot\"\n  by (metis a_inf_complement_bot il_inf_right_unit)\n\nlemma l2:\n  \"-bot = top\"\n  by (metis l1 a_stone il_unit_bot)\n\nlemma l3:\n  \"-x \\<le> -y \\<Longrightarrow> -x \\<sqinter> y = bot\"\n  by (metis a_inf_complement_bot il_bot_unit il_inf_right_dist_sup il_less_eq)\n\nlemma l5:\n  \"--x \\<le> --y \\<Longrightarrow> -y \\<le> -x\"\n  by (metis (mono_tags, opaque_lifting) l3 a_stone bot_least il_bot_unit il_inf_left_unit il_inf_right_dist_sup il_inf_right_unit il_sub_inf_right_isotone sup_right_isotone)\n\nlemma l4:\n  \"---x = -x\"\n  by (metis l5 a_inf_complement_bot a_stone order.antisym bot_least il_inf_left_unit il_inf_right_dist_sup il_inf_right_unit il_sub_inf_right_isotone il_unit_bot)\n\nlemma l6:\n  \"-x \\<sqinter> --x = bot\"\n  by (metis l3 l5 a_inf_complement_bot a_stone il_inf_left_unit il_inf_right_dist_sup il_inf_right_unit il_less_eq il_sub_inf_right_isotone il_unit_bot)\n\nlemma l7:\n  \"-x \\<sqinter> -y = -y \\<sqinter> -x\"\n  using l6 a_inf_complement_bot a_stone test_inf_commutative by blast\n\nlemma l8:\n  \"x \\<le> --x \\<sqinter> x\"\n  by (metis a_inf_complement_bot a_stone il_idempotent il_inf_left_unit il_inf_right_dist_sup il_less_eq il_unit_bot)\n\nsublocale ppa_ppd: ppd_semiring where d = \"\\<lambda>x . --x\"\nproof\n  show \"\\<And>x. test (- - x)\"\n    using l4 l6 by force\n  show \"\\<And>x. x \\<le> - - x \\<sqinter> x\"\n    by (simp add: l8)\nqed\n\n(*\nThe following statements have counterexamples, but they take a while to find.\n\nlemma \"- x = - (- - x \\<squnion> - y) \\<squnion> - (- - x \\<squnion> - - y)\" nitpick [card=8, expect=genuine] oops\nlemma \"- x \\<squnion> - y = - - (- x \\<squnion> - y)\" nitpick [card=8, expect=genuine] oops\n*)\n\nend\n\nsubsection \\<open>Preantidomain Semirings\\<close>\n\ntext \\<open>Definition 22\\<close>\n\nclass pa_semiring = ppa_semiring +\n  assumes pad2: \"--x \\<le> -(-x \\<sqinter> y)\"\nbegin\n\ntext \\<open>Theorem 23\\<close>\n\nlemma l10:\n  \"-x \\<sqinter> y = bot \\<Longrightarrow> -x \\<le> -y\"\n  by (metis a_stone il_inf_left_unit il_inf_right_dist_sup il_unit_bot l4 pad2)\n\nlemma l10_iff:\n  \"-x \\<sqinter> y = bot \\<longleftrightarrow> -x \\<le> -y\"\n  using l10 l3 by blast\n\nlemma l13:\n  \"--(--x \\<sqinter> y) \\<le> --x\"\n  by (metis l4 l5 pad2)\n\nlemma l14:\n  \"-(x \\<sqinter> --y) \\<le> -(x \\<sqinter> y)\"\n  by (metis il_inf_associative l4 pad2 ppa_ppd.d1_eq)\n\nlemma l9:\n  \"x \\<le> y \\<Longrightarrow> -y \\<le> -x\"\n  by (metis l10 a_inf_complement_bot il_commutative il_less_eq il_sub_inf_right_isotone il_unit_bot)\n\nlemma l11:\n  \"- x \\<squnion> - y = - (- - x \\<sqinter> - - y)\"\nproof -\n  have 1: \"\\<And>x y . x \\<le> y \\<longleftrightarrow> x \\<squnion> y = y\"\n    by (simp add: il_less_eq)\n  have 4: \"\\<And>x y . \\<not>(x \\<le> y) \\<or> x \\<squnion> y = y\"\n    using 1 by metis\n  have 5: \"\\<And>x y z . (x \\<sqinter> y) \\<squnion> (x \\<sqinter> z) \\<le> x \\<sqinter> (y \\<squnion> z)\"\n    by (simp add: il_sub_inf_right_isotone_var)\n  have 6: \"\\<And>x y . - - x \\<le> - (- x \\<sqinter> y)\"\n    by (simp add: pad2)\n  have 7: \"\\<And>x y z . x \\<squnion> (y \\<squnion> z) = (x \\<squnion> y) \\<squnion> z\"\n    by (simp add: il_associative)\n  have 8: \"\\<And>x y z . (x \\<squnion> y) \\<squnion> z = x \\<squnion> (y \\<squnion> z)\"\n    using 7 by metis\n  have 9: \"\\<And>x y . x \\<squnion> y = y \\<squnion> x\"\n    by (simp add: il_commutative)\n  have 10: \"\\<And>x . x \\<squnion> bot = x\"\n    by (simp add: il_bot_unit)\n  have 11: \"\\<And>x . x \\<squnion> x = x\"\n    by simp\n  have 12: \"\\<And>x y z . x \\<sqinter> (y \\<sqinter> z) = (x \\<sqinter> y) \\<sqinter> z\"\n    by (simp add: il_inf_associative)\n  have 13: \"\\<And>x y z . (x \\<sqinter> y) \\<sqinter> z = x \\<sqinter> (y \\<sqinter> z)\"\n    using 12 by metis\n  have 14: \"\\<And>x . top \\<sqinter> x = x\"\n    by simp\n  have 15: \"\\<And>x . x \\<sqinter> top = x\"\n    by simp\n  have 16: \"\\<And>x y z . (x \\<squnion> y) \\<sqinter> z = (x \\<sqinter> z) \\<squnion> (y \\<sqinter> z)\"\n    by (simp add: il_inf_right_dist_sup)\n  have 17: \"\\<And>x y z . (x \\<sqinter> y) \\<squnion> (z \\<sqinter> y) = (x \\<squnion> z) \\<sqinter> y\"\n    using 16 by metis\n  have 18: \"\\<And>x . bot \\<sqinter> x = bot\"\n    by simp\n  have 19: \"\\<And>x . - x \\<squnion> - - x = top\"\n    by simp\n  have 20: \"\\<And>x . - x \\<sqinter> x = bot\"\n    by (simp add: a_inf_complement_bot)\n  have 23: \"\\<And>x y z . ((x \\<sqinter> y) \\<squnion> (x \\<sqinter> z)) \\<squnion> (x \\<sqinter> (y \\<squnion> z)) = x \\<sqinter> (y \\<squnion> z)\"\n    using 4 5 by metis\n  have 24: \"\\<And>x y z . (x \\<sqinter> (y \\<squnion> z)) \\<squnion> ((x \\<sqinter> y) \\<squnion> (x \\<sqinter> z)) = x \\<sqinter> (y \\<squnion> z)\"\n    using 9 23 by metis\n  have 25: \"\\<And>x y . - - x \\<squnion> - (- x \\<sqinter> y) = - (- x \\<sqinter> y)\"\n    using 4 6 by metis\n  have 26: \"\\<And>x y z . x \\<squnion> (y \\<squnion> z) = y \\<squnion> (x \\<squnion> z)\"\n    using 8 9 by metis\n  have 27: \"\\<And>x y z . (x \\<sqinter> y) \\<squnion> ((x \\<sqinter> z) \\<squnion> (x \\<sqinter> (y \\<squnion> z))) = x \\<sqinter> (y \\<squnion> z)\"\n    using 9 24 26 by metis\n  have 30: \"\\<And>x . bot \\<squnion> x = x\"\n    using 9 10 by metis\n  have 31: \"\\<And>x y . x \\<squnion> (x \\<squnion> y) = x \\<squnion> y\"\n    using 8 11 by metis\n  have 34: \"\\<And>u x y z . ((x \\<squnion> y) \\<sqinter> z) \\<squnion> u = (x \\<sqinter> z) \\<squnion> ((y \\<sqinter> z) \\<squnion> u)\"\n    using 8 17 by metis\n  have 35: \"\\<And>u x y z . (x \\<sqinter> (y \\<sqinter> z)) \\<squnion> (u \\<sqinter> z) = ((x \\<sqinter> y) \\<squnion> u) \\<sqinter> z\"\n    using 13 17 by metis\n  have 36: \"\\<And>u x y z . (x \\<sqinter> y) \\<squnion> (z \\<sqinter> (u \\<sqinter> y)) = (x \\<squnion> (z \\<sqinter> u)) \\<sqinter> y\"\n    using 13 17 by metis\n  have 39: \"\\<And>x y . - x \\<squnion> (- - x \\<squnion> y) = top \\<squnion> y\"\n    using 8 19 by metis\n  have 41: \"\\<And>x y . - x \\<sqinter> (x \\<sqinter> y) = bot\"\n    using 13 18 20 by metis\n  have 42: \"- top = bot\"\n    using 15 20 by metis\n  have 43: \"\\<And>x y . (- x \\<squnion> y) \\<sqinter> x = y \\<sqinter> x\"\n    using 17 20 30 by metis\n  have 44: \"\\<And>x y . (x \\<squnion> - y) \\<sqinter> y = x \\<sqinter> y\"\n    using 9 17 20 30 by metis\n  have 46: \"\\<And>x . - bot \\<squnion> - - x = - bot\"\n    using 9 20 25 by metis\n  have 50: \"- bot = top\"\n    using 19 30 42 by metis\n  have 51: \"\\<And>x . top \\<squnion> - - x = top\"\n    using 46 50 by metis\n  have 63: \"\\<And>x y . x \\<squnion> ((x \\<sqinter> - y) \\<squnion> (x \\<sqinter> - - y)) = x\"\n    using 9 15 19 26 27 by metis\n  have 66: \"\\<And>x y . (- (x \\<squnion> y) \\<sqinter> x) \\<squnion> (- (x \\<squnion> y) \\<sqinter> y) = bot\"\n    using 9 20 27 30 by metis\n  have 67: \"\\<And>x y z . (x \\<sqinter> - - y) \\<squnion> (x \\<sqinter> - (- y \\<sqinter> z)) = x \\<sqinter> - (- y \\<sqinter> z)\"\n    using 11 25 27 by metis\n  have 70: \"\\<And>x y . x \\<squnion> (x \\<sqinter> - - y) = x\"\n    using 9 15 27 31 51 by metis\n  have 82: \"\\<And>x . top \\<squnion> - x = top\"\n    using 9 19 31 by metis\n  have 89: \"\\<And>x y . x \\<squnion> (- y \\<sqinter> x) = x\"\n    using 14 17 82 by metis\n  have 102: \"\\<And>x y z . x \\<squnion> (y \\<squnion> (x \\<sqinter> - - z)) = y \\<squnion> x\"\n    using 26 70 by metis\n  have 104: \"\\<And>x y . x \\<squnion> (x \\<sqinter> - y) = x\"\n    using 9 63 102 by metis\n  have 112: \"\\<And>x y z . (- x \\<sqinter> y) \\<squnion> ((- - x \\<sqinter> y) \\<squnion> z) = y \\<squnion> z\"\n    using 14 19 34 by metis\n  have 117: \"\\<And>x y z . x \\<squnion> ((x \\<sqinter> - y) \\<squnion> z) = x \\<squnion> z\"\n    using 8 104 by metis\n  have 120: \"\\<And>x y z . x \\<squnion> (y \\<squnion> (x \\<sqinter> - z)) = y \\<squnion> x\"\n    using 26 104 by metis\n  have 124: \"\\<And>x . - - x \\<sqinter> x = x\"\n    using 14 19 43 by metis\n  have 128: \"\\<And>x y . - - x \\<sqinter> (x \\<sqinter> y) = x \\<sqinter> y\"\n    using 13 124 by metis\n  have 131: \"\\<And>x . - x \\<squnion> - - - x = - x\"\n    using 9 25 124 by metis\n  have 133: \"\\<And>x . - - - x = - x\"\n    using 9 104 124 131 by metis\n  have 135: \"\\<And>x y . - x \\<squnion> - (- - x \\<sqinter> y) = - (- - x \\<sqinter> y)\"\n    using 25 133 by metis\n  have 137: \"\\<And>x y . (- x \\<squnion> y) \\<sqinter> - - x = y \\<sqinter> - - x\"\n    using 43 133 by metis\n  have 145: \"\\<And>x y z . ((- (x \\<sqinter> y) \\<sqinter> x) \\<squnion> z) \\<sqinter> y = z \\<sqinter> y\"\n    using 20 30 35 by metis\n  have 183: \"\\<And>x y z . (x \\<squnion> (- - (y \\<sqinter> z) \\<sqinter> y)) \\<sqinter> z = (x \\<squnion> y) \\<sqinter> z\"\n    using 17 36 124 by metis\n  have 289: \"\\<And>x y . - x \\<squnion> - (- x \\<sqinter> y) = top\"\n    using 25 39 82 by metis\n  have 316: \"\\<And>x y . - (- x \\<sqinter> y) \\<sqinter> x = x\"\n    using 14 43 289 by metis\n  have 317: \"\\<And>x y z . - (- x \\<sqinter> y) \\<sqinter> (x \\<sqinter> z) = x \\<sqinter> z\"\n    using 13 316 by metis\n  have 320: \"\\<And>x y . - x \\<squnion> - - (- x \\<sqinter> y) = - x\"\n    using 9 25 316 by metis\n  have 321: \"\\<And>x y . - - (- x \\<sqinter> y) \\<sqinter> x = bot\"\n    using 41 316 by metis\n  have 374: \"\\<And>x y . - x \\<squnion> - (x \\<sqinter> y) = - (x \\<sqinter> y)\"\n    using 25 128 133 by metis\n  have 388: \"\\<And>x y . - (x \\<sqinter> y) \\<sqinter> - x = - x\"\n    using 128 316 by metis\n  have 389: \"\\<And>x y . - - (x \\<sqinter> y) \\<sqinter> - x = bot\"\n    using 128 321 by metis\n  have 405: \"\\<And>x y z . - (x \\<sqinter> y) \\<sqinter> (- x \\<sqinter> z) = - x \\<sqinter> z\"\n    using 13 388 by metis\n  have 406: \"\\<And>x y z . - (x \\<sqinter> (y \\<sqinter> z)) \\<sqinter> - (x \\<sqinter> y) = - (x \\<sqinter> y)\"\n    using 13 388 by metis\n  have 420: \"\\<And>x y . - x \\<sqinter> - - (- x \\<sqinter> y) = - - (- x \\<sqinter> y)\"\n    using 316 388 by metis\n  have 422: \"\\<And>x y z . - - (x \\<sqinter> y) \\<sqinter> (- x \\<sqinter> z) = bot\"\n    using 13 18 389 by metis\n  have 758: \"\\<And>x y z . x \\<squnion> (x \\<sqinter> (- y \\<sqinter> - z)) = x\"\n    using 13 104 117 by metis\n  have 1092: \"\\<And>x y . - (x \\<squnion> y) \\<sqinter> x = bot\"\n    using 9 30 31 66 by metis\n  have 1130: \"\\<And>x y z . (- (x \\<squnion> y) \\<squnion> z) \\<sqinter> x = z \\<sqinter> x\"\n    using 17 30 1092 by metis\n  have 1156: \"\\<And>x y . - - x \\<sqinter> - (- x \\<sqinter> y) = - - x\"\n    using 67 104 124 133 by metis\n  have 2098: \"\\<And>x y . - - (x \\<squnion> y) \\<sqinter> x = x\"\n    using 14 19 1130 by metis\n  have 2125: \"\\<And>x y . - - (x \\<squnion> y) \\<sqinter> y = y\"\n    using 9 2098 by metis\n  have 2138: \"\\<And>x y . - x \\<squnion> - - (x \\<squnion> y) = top\"\n    using 9 289 2098 by metis\n  have 2139: \"\\<And>x y . - x \\<sqinter> - (x \\<squnion> y) = - (x \\<squnion> y)\"\n    using 316 2098 by metis\n  have 2192: \"\\<And>x y . - - x \\<sqinter> (- y \\<sqinter> x) = - y \\<sqinter> x\"\n    using 89 2125 by metis\n  have 2202: \"\\<And>x y . - x \\<squnion> - - (y \\<squnion> x) = top\"\n    using 9 289 2125 by metis\n  have 2344: \"\\<And>x y . - (- x \\<sqinter> y) \\<squnion> - - y = top\"\n    using 89 2202 by metis\n  have 2547: \"\\<And>x y z . - x \\<squnion> ((- - x \\<sqinter> - y) \\<squnion> z) = - x \\<squnion> (- y \\<squnion> z)\"\n    using 112 117 by metis\n  have 3023: \"\\<And>x y . - x \\<squnion> - (- y \\<sqinter> - x) = top\"\n    using 9 133 2344 by metis\n  have 3134: \"\\<And>x y . - (- x \\<sqinter> - y) \\<sqinter> y = y\"\n    using 14 43 3023 by metis\n  have 3135: \"\\<And>x y . - x \\<sqinter> (- y \\<sqinter> - x) = - y \\<sqinter> - x\"\n    using 14 44 3023 by metis\n  have 3962: \"\\<And>x y . - - (x \\<squnion> y) \\<sqinter> - - x = - - x\"\n    using 14 137 2138 by metis\n  have 5496: \"\\<And>x y z . - - (x \\<sqinter> y) \\<sqinter> - (x \\<squnion> z) = bot\"\n    using 422 2139 by metis\n  have 9414: \"\\<And>x y . - - (- x \\<sqinter> y) \\<sqinter> y = - x \\<sqinter> y\"\n    using 9 104 183 320 by metis\n  have 9520: \"\\<And>x y z . - - (- x \\<sqinter> y) \\<sqinter> - - (x \\<sqinter> z) = bot\"\n    using 374 5496 by metis\n  have 11070: \"\\<And>x y z . - (- - x \\<sqinter> y) \\<squnion> (- x \\<sqinter> - z) = - (- - x \\<sqinter> y)\"\n    using 317 758 by metis\n  have 12371: \"\\<And>x y . - x \\<sqinter> - (- - x \\<sqinter> y) = - x\"\n    using 133 1156 by metis\n  have 12377: \"\\<And>x y . - x \\<sqinter> - (x \\<sqinter> y) = - x\"\n    using 128 133 1156 by metis\n  have 12384: \"\\<And>x y . - (x \\<squnion> y) \\<sqinter> - y = - (x \\<squnion> y)\"\n    using 133 1156 2125 by metis\n  have 12394: \"\\<And>x y . - - (- x \\<sqinter> - y) = - x \\<sqinter> - y\"\n    using 1156 3134 9414 by metis\n  have 12640: \"\\<And>x y . - x \\<sqinter> - (- y \\<sqinter> x) = - x\"\n    using 89 12384 by metis\n  have 24648: \"\\<And>x y . (- x \\<sqinter> - y) \\<squnion> - (- x \\<sqinter> - y) = top\"\n    using 19 12394 by metis\n  have 28270: \"\\<And>x y z . - - (x \\<sqinter> y) \\<squnion> - (- x \\<sqinter> z) = - (- x \\<sqinter> z)\"\n    using 374 405 by metis\n  have 28339: \"\\<And>x y . - (- - (x \\<sqinter> y) \\<sqinter> x) = - (x \\<sqinter> y)\"\n    using 124 406 12371 by metis\n  have 28423: \"\\<And>x y . - (- x \\<sqinter> - y) = - (- y \\<sqinter> - x)\"\n    using 13 3135 12394 28339 by metis\n  have 28487: \"\\<And>x y . - x \\<sqinter> - y = - y \\<sqinter> - x\"\n    using 2098 3962 12394 28423 by metis\n  have 52423: \"\\<And>x y . - (- x \\<sqinter> - (- x \\<sqinter> y)) \\<sqinter> y = y\"\n    using 14 145 24648 28487 by metis\n  have 52522: \"\\<And>x y . - x \\<sqinter> - (- x \\<sqinter> y) = - x \\<sqinter> - y\"\n    using 13 12377 12394 12640 28487 52423 by metis\n  have 61103: \"\\<And>x y z . - (- - x \\<sqinter> y) \\<squnion> z = - x \\<squnion> (- y \\<squnion> z)\"\n    using 112 2547 12371 52522 by metis\n  have 61158: \"\\<And>x y . - - (- x \\<sqinter> y) = - x \\<sqinter> - - y\"\n    using 420 52522 by metis\n  have 61231: \"\\<And>x y z . - x \\<sqinter> (- - y \\<sqinter> - (x \\<sqinter> z)) = - x \\<sqinter> - - y\"\n    using 13 15 50 133 9520 52522 61158 by metis\n  have 61313: \"\\<And>x y . - x \\<squnion> - y = - (- - y \\<sqinter> x)\"\n    using 120 11070 61103 by metis\n  have 61393: \"\\<And>x y . - (- x \\<sqinter> - - y) = - (- x \\<sqinter> y)\"\n    using 13 28270 61158 61231 61313 by metis\n  have 61422: \"\\<And>x y . - (- - x \\<sqinter> y) = - (- - y \\<sqinter> x)\"\n    using 13 135 2192 61158 61313 by metis\n  show ?thesis\n    using 61313 61393 61422 by metis\nqed\n\nlemma l12:\n  \"- x \\<sqinter> - y = - (x \\<squnion> y)\"\nproof -\n  have 1: \"\\<And>x y . x \\<le> y \\<longleftrightarrow> x \\<squnion> y = y\"\n    by (simp add: il_less_eq)\n  have 4: \"\\<And>x y . \\<not>(x \\<le> y) \\<or> x \\<squnion> y = y\"\n    using 1 by metis\n  have 5: \"\\<And>x y z . (x \\<sqinter> y) \\<squnion> (x \\<sqinter> z) \\<le> x \\<sqinter> (y \\<squnion> z)\"\n    by (simp add: il_sub_inf_right_isotone_var)\n  have 6: \"\\<And>x y . - - x \\<le> - (- x \\<sqinter> y)\"\n    by (simp add: pad2)\n  have 7: \"\\<And>x y z . x \\<squnion> (y \\<squnion> z) = (x \\<squnion> y) \\<squnion> z\"\n    by (simp add: il_associative)\n  have 8: \"\\<And>x y z . (x \\<squnion> y) \\<squnion> z = x \\<squnion> (y \\<squnion> z)\"\n    using 7 by metis\n  have 9: \"\\<And>x y . x \\<squnion> y = y \\<squnion> x\"\n    by (simp add: il_commutative)\n  have 10: \"\\<And>x . x \\<squnion> bot = x\"\n    by (simp add: il_bot_unit)\n  have 11: \"\\<And>x . x \\<squnion> x = x\"\n    by simp\n  have 12: \"\\<And>x y z . x \\<sqinter> (y \\<sqinter> z) = (x \\<sqinter> y) \\<sqinter> z\"\n    by (simp add: il_inf_associative)\n  have 13: \"\\<And>x y z . (x \\<sqinter> y) \\<sqinter> z = x \\<sqinter> (y \\<sqinter> z)\"\n    using 12 by metis\n  have 14: \"\\<And>x . top \\<sqinter> x = x\"\n    by simp\n  have 15: \"\\<And>x . x \\<sqinter> top = x\"\n    by simp\n  have 16: \"\\<And>x y z . (x \\<squnion> y) \\<sqinter> z = (x \\<sqinter> z) \\<squnion> (y \\<sqinter> z)\"\n    by (simp add: il_inf_right_dist_sup)\n  have 17: \"\\<And>x y z . (x \\<sqinter> y) \\<squnion> (z \\<sqinter> y) = (x \\<squnion> z) \\<sqinter> y\"\n    using 16 by metis\n  have 18: \"\\<And>x . bot \\<sqinter> x = bot\"\n    by simp\n  have 19: \"\\<And>x . - x \\<squnion> - - x = top\"\n    by simp\n  have 20: \"\\<And>x . - x \\<sqinter> x = bot\"\n    by (simp add: a_inf_complement_bot)\n  have 22: \"\\<And>x y z . ((x \\<sqinter> y) \\<squnion> (x \\<sqinter> z)) \\<squnion> (x \\<sqinter> (y \\<squnion> z)) = x \\<sqinter> (y \\<squnion> z)\"\n    using 4 5 by metis\n  have 23: \"\\<And>x y z . (x \\<sqinter> (y \\<squnion> z)) \\<squnion> ((x \\<sqinter> y) \\<squnion> (x \\<sqinter> z)) = x \\<sqinter> (y \\<squnion> z)\"\n    using 9 22 by metis\n  have 24: \"\\<And>x y . - - x \\<squnion> - (- x \\<sqinter> y) = - (- x \\<sqinter> y)\"\n    using 4 6 by metis\n  have 25: \"\\<And>x y z . x \\<squnion> (y \\<squnion> z) = y \\<squnion> (x \\<squnion> z)\"\n    using 8 9 by metis\n  have 26: \"\\<And>x y z . (x \\<sqinter> y) \\<squnion> ((x \\<sqinter> z) \\<squnion> (x \\<sqinter> (y \\<squnion> z))) = x \\<sqinter> (y \\<squnion> z)\"\n    using 9 23 25 by metis\n  have 29: \"\\<And>x . bot \\<squnion> x = x\"\n    using 9 10 by metis\n  have 30: \"\\<And>x y . x \\<squnion> (x \\<squnion> y) = x \\<squnion> y\"\n    using 8 11 by metis\n  have 32: \"\\<And>x y . x \\<squnion> (y \\<squnion> x) = y \\<squnion> x\"\n    using 8 9 11 by metis\n  have 33: \"\\<And>u x y z . ((x \\<squnion> y) \\<sqinter> z) \\<squnion> u = (x \\<sqinter> z) \\<squnion> ((y \\<sqinter> z) \\<squnion> u)\"\n    using 8 17 by metis\n  have 34: \"\\<And>u x y z . (x \\<sqinter> (y \\<sqinter> z)) \\<squnion> (u \\<sqinter> z) = ((x \\<sqinter> y) \\<squnion> u) \\<sqinter> z\"\n    using 13 17 by metis\n  have 35: \"\\<And>u x y z . (x \\<sqinter> y) \\<squnion> (z \\<sqinter> (u \\<sqinter> y)) = (x \\<squnion> (z \\<sqinter> u)) \\<sqinter> y\"\n    using 13 17 by metis\n  have 36: \"\\<And>x y . (top \\<squnion> x) \\<sqinter> y = y \\<squnion> (x \\<sqinter> y)\"\n    using 14 17 by metis\n  have 37: \"\\<And>x y . (x \\<squnion> top) \\<sqinter> y = y \\<squnion> (x \\<sqinter> y)\"\n    using 9 14 17 by metis\n  have 38: \"\\<And>x y . - x \\<squnion> (- - x \\<squnion> y) = top \\<squnion> y\"\n    using 8 19 by metis\n  have 40: \"\\<And>x y . - x \\<sqinter> (x \\<sqinter> y) = bot\"\n    using 13 18 20 by metis\n  have 41: \"- top = bot\"\n    using 15 20 by metis\n  have 42: \"\\<And>x y . (- x \\<squnion> y) \\<sqinter> x = y \\<sqinter> x\"\n    using 17 20 29 by metis\n  have 43: \"\\<And>x y . (x \\<squnion> - y) \\<sqinter> y = x \\<sqinter> y\"\n    using 9 17 20 29 by metis\n  have 45: \"\\<And>x . - bot \\<squnion> - - x = - bot\"\n    using 9 20 24 by metis\n  have 46: \"\\<And>u x y z . (x \\<sqinter> y) \\<squnion> (z \\<squnion> (u \\<sqinter> y)) = z \\<squnion> ((x \\<squnion> u) \\<sqinter> y)\"\n    using 17 25 by metis\n  have 47: \"\\<And>x y . - x \\<squnion> (y \\<squnion> - - x) = y \\<squnion> top\"\n    using 19 25 by metis\n  have 49: \"- bot = top\"\n    using 19 29 41 by metis\n  have 50: \"\\<And>x . top \\<squnion> - - x = top\"\n    using 45 49 by metis\n  have 54: \"\\<And>u x y z . (x \\<sqinter> y) \\<squnion> ((x \\<sqinter> z) \\<squnion> ((x \\<sqinter> (y \\<squnion> z)) \\<squnion> u)) = (x \\<sqinter> (y \\<squnion> z)) \\<squnion> u\"\n    using 8 26 by metis\n  have 58: \"\\<And>u x y z . (x \\<sqinter> (y \\<sqinter> z)) \\<squnion> ((x \\<sqinter> (y \\<sqinter> u)) \\<squnion> (x \\<sqinter> (y \\<sqinter> (z \\<squnion> u)))) = x \\<sqinter> (y \\<sqinter> (z \\<squnion> u))\"\n    using 13 26 by metis\n  have 60: \"\\<And>x y . x \\<squnion> ((x \\<sqinter> y) \\<squnion> (x \\<sqinter> (y \\<squnion> top))) = x \\<sqinter> (y \\<squnion> top)\"\n    using 15 25 26 by metis\n  have 62: \"\\<And>x y . x \\<squnion> ((x \\<sqinter> - y) \\<squnion> (x \\<sqinter> - - y)) = x\"\n    using 9 15 19 25 26 by metis\n  have 65: \"\\<And>x y . (- (x \\<squnion> y) \\<sqinter> x) \\<squnion> (- (x \\<squnion> y) \\<sqinter> y) = bot\"\n    using 9 20 26 29 by metis\n  have 66: \"\\<And>x y z . (x \\<sqinter> - - y) \\<squnion> (x \\<sqinter> - (- y \\<sqinter> z)) = x \\<sqinter> - (- y \\<sqinter> z)\"\n    using 11 24 26 by metis\n  have 69: \"\\<And>x y . x \\<squnion> (x \\<sqinter> - - y) = x\"\n    using 9 15 26 30 50 by metis\n  have 81: \"\\<And>x . top \\<squnion> - x = top\"\n    using 9 19 30 by metis\n  have 82: \"\\<And>x y z . (x \\<sqinter> y) \\<squnion> (x \\<sqinter> (y \\<squnion> z)) = x \\<sqinter> (y \\<squnion> z)\"\n    using 11 26 30 by metis\n  have 83: \"\\<And>x y . x \\<squnion> (x \\<sqinter> (y \\<squnion> top)) = x \\<sqinter> (y \\<squnion> top)\"\n    using 60 82 by metis\n  have 88: \"\\<And>x y . x \\<squnion> (- y \\<sqinter> x) = x\"\n    using 14 17 81 by metis\n  have 89: \"\\<And>x y . top \\<squnion> (x \\<squnion> - y) = x \\<squnion> top\"\n    using 25 81 by metis\n  have 91: \"\\<And>x y z . x \\<squnion> (y \\<squnion> (z \\<squnion> x)) = y \\<squnion> (z \\<squnion> x)\"\n    using 8 32 by metis\n  have 94: \"\\<And>x y z . x \\<squnion> (y \\<squnion> (- z \\<sqinter> x)) = y \\<squnion> x\"\n    using 25 88 by metis\n  have 101: \"\\<And>x y z . x \\<squnion> (y \\<squnion> (x \\<sqinter> - - z)) = y \\<squnion> x\"\n    using 25 69 by metis\n  have 102: \"\\<And>x . x \\<squnion> (x \\<sqinter> bot) = x\"\n    using 41 49 69 by metis\n  have 103: \"\\<And>x y . x \\<squnion> (x \\<sqinter> - y) = x\"\n    using 9 62 101 by metis\n  have 109: \"\\<And>x y . x \\<squnion> (y \\<squnion> (x \\<sqinter> bot)) = y \\<squnion> x\"\n    using 25 102 by metis\n  have 111: \"\\<And>x y z . (- x \\<sqinter> y) \\<squnion> ((- - x \\<sqinter> y) \\<squnion> z) = y \\<squnion> z\"\n    using 14 19 33 by metis\n  have 116: \"\\<And>x y z . x \\<squnion> ((x \\<sqinter> - y) \\<squnion> z) = x \\<squnion> z\"\n    using 8 103 by metis\n  have 119: \"\\<And>x y z . x \\<squnion> (y \\<squnion> (x \\<sqinter> - z)) = y \\<squnion> x\"\n    using 25 103 by metis\n  have 123: \"\\<And>x . - - x \\<sqinter> x = x\"\n    using 14 19 42 by metis\n  have 127: \"\\<And>x y . - - x \\<sqinter> (x \\<sqinter> y) = x \\<sqinter> y\"\n    using 13 123 by metis\n  have 130: \"\\<And>x . - x \\<squnion> - - - x = - x\"\n    using 9 24 123 by metis\n  have 132: \"\\<And>x . - - - x = - x\"\n    using 9 103 123 130 by metis\n  have 134: \"\\<And>x y . - x \\<squnion> - (- - x \\<sqinter> y) = - (- - x \\<sqinter> y)\"\n    using 24 132 by metis\n  have 136: \"\\<And>x y . (- x \\<squnion> y) \\<sqinter> - - x = y \\<sqinter> - - x\"\n    using 42 132 by metis\n  have 138: \"\\<And>x . - x \\<sqinter> - x = - x\"\n    using 123 132 by metis\n  have 144: \"\\<And>x y z . ((- (x \\<sqinter> y) \\<sqinter> x) \\<squnion> z) \\<sqinter> y = z \\<sqinter> y\"\n    using 20 29 34 by metis\n  have 157: \"\\<And>x y . (- x \\<squnion> y) \\<sqinter> - x = (top \\<squnion> y) \\<sqinter> - x\"\n    using 17 36 138 by metis\n  have 182: \"\\<And>x y z . (x \\<squnion> (- - (y \\<sqinter> z) \\<sqinter> y)) \\<sqinter> z = (x \\<squnion> y) \\<sqinter> z\"\n    using 17 35 123 by metis\n  have 288: \"\\<And>x y . - x \\<squnion> - (- x \\<sqinter> y) = top\"\n    using 24 38 81 by metis\n  have 315: \"\\<And>x y . - (- x \\<sqinter> y) \\<sqinter> x = x\"\n    using 14 42 288 by metis\n  have 316: \"\\<And>x y z . - (- x \\<sqinter> y) \\<sqinter> (x \\<sqinter> z) = x \\<sqinter> z\"\n    using 13 315 by metis\n  have 319: \"\\<And>x y . - x \\<squnion> - - (- x \\<sqinter> y) = - x\"\n    using 9 24 315 by metis\n  have 320: \"\\<And>x y . - - (- x \\<sqinter> y) \\<sqinter> x = bot\"\n    using 40 315 by metis\n  have 373: \"\\<And>x y . - x \\<squnion> - (x \\<sqinter> y) = - (x \\<sqinter> y)\"\n    using 24 127 132 by metis\n  have 387: \"\\<And>x y . - (x \\<sqinter> y) \\<sqinter> - x = - x\"\n    using 127 315 by metis\n  have 388: \"\\<And>x y . - - (x \\<sqinter> y) \\<sqinter> - x = bot\"\n    using 127 320 by metis\n  have 404: \"\\<And>x y z . - (x \\<sqinter> y) \\<sqinter> (- x \\<sqinter> z) = - x \\<sqinter> z\"\n    using 13 387 by metis\n  have 405: \"\\<And>x y z . - (x \\<sqinter> (y \\<sqinter> z)) \\<sqinter> - (x \\<sqinter> y) = - (x \\<sqinter> y)\"\n    using 13 387 by metis\n  have 419: \"\\<And>x y . - x \\<sqinter> - - (- x \\<sqinter> y) = - - (- x \\<sqinter> y)\"\n    using 315 387 by metis\n  have 420: \"\\<And>x y . - - x \\<sqinter> - - (x \\<sqinter> y) = - - (x \\<sqinter> y)\"\n    using 387 by metis\n  have 421: \"\\<And>x y z . - - (x \\<sqinter> y) \\<sqinter> (- x \\<sqinter> z) = bot\"\n    using 13 18 388 by metis\n  have 536: \"\\<And>x y . (x \\<squnion> - - y) \\<sqinter> y = (x \\<squnion> top) \\<sqinter> y\"\n    using 42 47 by metis\n  have 662: \"\\<And>u x y z . (x \\<sqinter> y) \\<squnion> ((x \\<sqinter> (z \\<squnion> y)) \\<squnion> u) = (x \\<sqinter> (z \\<squnion> y)) \\<squnion> u\"\n    using 9 32 54 by metis\n  have 705: \"\\<And>u x y z . (x \\<sqinter> (y \\<squnion> z)) \\<squnion> ((x \\<sqinter> (y \\<squnion> (z \\<sqinter> bot))) \\<squnion> u) = (x \\<sqinter> (y \\<squnion> z)) \\<squnion> u\"\n    using 25 54 109 662 by metis\n  have 755: \"\\<And>x y z . (x \\<sqinter> - y) \\<squnion> (z \\<squnion> x) = z \\<squnion> x\"\n    using 32 91 116 by metis\n  have 757: \"\\<And>x y z . x \\<squnion> (x \\<sqinter> (- y \\<sqinter> - z)) = x\"\n    using 13 103 116 by metis\n  have 930: \"\\<And>x y z . (- (x \\<sqinter> (y \\<squnion> z)) \\<sqinter> (x \\<sqinter> y)) \\<squnion> (- (x \\<sqinter> (y \\<squnion> z)) \\<sqinter> (x \\<sqinter> z)) = bot\"\n    using 9 20 29 58 by metis\n  have 1091: \"\\<And>x y . - (x \\<squnion> y) \\<sqinter> x = bot\"\n    using 9 29 30 65 by metis\n  have 1092: \"\\<And>x y . - (x \\<squnion> y) \\<sqinter> y = bot\"\n    using 29 30 65 1091 by metis\n  have 1113: \"\\<And>u x y z . - (x \\<squnion> ((y \\<squnion> z) \\<sqinter> u)) \\<sqinter> (x \\<squnion> (z \\<sqinter> u)) = bot\"\n    using 29 46 65 1091 by metis\n  have 1117: \"\\<And>x y z . - (x \\<squnion> y) \\<sqinter> (x \\<squnion> (- z \\<sqinter> y)) = bot\"\n    using 29 65 94 1092 by metis\n  have 1128: \"\\<And>x y z . - (x \\<squnion> (y \\<squnion> z)) \\<sqinter> (x \\<squnion> y) = bot\"\n    using 8 1091 by metis\n  have 1129: \"\\<And>x y z . (- (x \\<squnion> y) \\<squnion> z) \\<sqinter> x = z \\<sqinter> x\"\n    using 17 29 1091 by metis\n  have 1155: \"\\<And>x y . - - x \\<sqinter> - (- x \\<sqinter> y) = - - x\"\n    using 66 103 123 132 by metis\n  have 1578: \"\\<And>x y z . - (x \\<sqinter> (y \\<squnion> z)) \\<sqinter> (x \\<sqinter> y) = bot\"\n    using 82 1091 by metis\n  have 1594: \"\\<And>x y z . - (x \\<sqinter> (y \\<squnion> z)) \\<sqinter> (x \\<sqinter> z) = bot\"\n    using 29 930 1578 by metis\n  have 2094: \"\\<And>x y z . - (x \\<squnion> (y \\<sqinter> (z \\<squnion> top))) \\<sqinter> (x \\<squnion> y) = bot\"\n    using 83 1128 by metis\n  have 2097: \"\\<And>x y . - - (x \\<squnion> y) \\<sqinter> x = x\"\n    using 14 19 1129 by metis\n  have 2124: \"\\<And>x y . - - (x \\<squnion> y) \\<sqinter> y = y\"\n    using 9 2097 by metis\n  have 2135: \"\\<And>x y . - - ((top \\<squnion> x) \\<sqinter> y) \\<sqinter> y = y\"\n    using 36 2097 by metis\n  have 2136: \"\\<And>x y . - - ((x \\<squnion> top) \\<sqinter> y) \\<sqinter> y = y\"\n    using 37 2097 by metis\n  have 2137: \"\\<And>x y . - x \\<squnion> - - (x \\<squnion> y) = top\"\n    using 9 288 2097 by metis\n  have 2138: \"\\<And>x y . - x \\<sqinter> - (x \\<squnion> y) = - (x \\<squnion> y)\"\n    using 315 2097 by metis\n  have 2151: \"\\<And>x y . - x \\<squnion> - (x \\<squnion> y) = - x\"\n    using 9 132 373 2097 by metis\n  have 2191: \"\\<And>x y . - - x \\<sqinter> (- y \\<sqinter> x) = - y \\<sqinter> x\"\n    using 88 2124 by metis\n  have 2201: \"\\<And>x y . - x \\<squnion> - - (y \\<squnion> x) = top\"\n    using 9 288 2124 by metis\n  have 2202: \"\\<And>x y . - x \\<sqinter> - (y \\<squnion> x) = - (y \\<squnion> x)\"\n    using 315 2124 by metis\n  have 2320: \"\\<And>x y . - (x \\<sqinter> (y \\<squnion> top)) = - x\"\n    using 83 373 2151 by metis\n  have 2343: \"\\<And>x y . - (- x \\<sqinter> y) \\<squnion> - - y = top\"\n    using 88 2201 by metis\n  have 2546: \"\\<And>x y z . - x \\<squnion> ((- - x \\<sqinter> - y) \\<squnion> z) = - x \\<squnion> (- y \\<squnion> z)\"\n    using 111 116 by metis\n  have 2706: \"\\<And>x y z . - x \\<squnion> (y \\<squnion> - - ((top \\<squnion> z) \\<sqinter> - x)) = y \\<squnion> - - ((top \\<squnion> z) \\<sqinter> - x)\"\n    using 755 2135 by metis\n  have 2810: \"\\<And>x y . - x \\<sqinter> - ((y \\<squnion> top) \\<sqinter> x) = - ((y \\<squnion> top) \\<sqinter> x)\"\n    using 315 2136 by metis\n  have 3022: \"\\<And>x y . - x \\<squnion> - (- y \\<sqinter> - x) = top\"\n    using 9 132 2343 by metis\n  have 3133: \"\\<And>x y . - (- x \\<sqinter> - y) \\<sqinter> y = y\"\n    using 14 42 3022 by metis\n  have 3134: \"\\<And>x y . - x \\<sqinter> (- y \\<sqinter> - x) = - y \\<sqinter> - x\"\n    using 14 43 3022 by metis\n  have 3961: \"\\<And>x y . - - (x \\<squnion> y) \\<sqinter> - - x = - - x\"\n    using 14 136 2137 by metis\n  have 4644: \"\\<And>x y z . - (x \\<sqinter> - y) \\<sqinter> (x \\<sqinter> - (y \\<squnion> z)) = bot\"\n    using 1594 2151 by metis\n  have 5495: \"\\<And>x y z . - - (x \\<sqinter> y) \\<sqinter> - (x \\<squnion> z) = bot\"\n    using 421 2138 by metis\n  have 9413: \"\\<And>x y . - - (- x \\<sqinter> y) \\<sqinter> y = - x \\<sqinter> y\"\n    using 9 103 182 319 by metis\n  have 9519: \"\\<And>x y z . - - (- x \\<sqinter> y) \\<sqinter> - - (x \\<sqinter> z) = bot\"\n    using 373 5495 by metis\n  have 11069: \"\\<And>x y z . - (- - x \\<sqinter> y) \\<squnion> (- x \\<sqinter> - z) = - (- - x \\<sqinter> y)\"\n    using 316 757 by metis\n  have 12370: \"\\<And>x y . - x \\<sqinter> - (- - x \\<sqinter> y) = - x\"\n    using 132 1155 by metis\n  have 12376: \"\\<And>x y . - x \\<sqinter> - (x \\<sqinter> y) = - x\"\n    using 127 132 1155 by metis\n  have 12383: \"\\<And>x y . - (x \\<squnion> y) \\<sqinter> - y = - (x \\<squnion> y)\"\n    using 132 1155 2124 by metis\n  have 12393: \"\\<And>x y . - - (- x \\<sqinter> - y) = - x \\<sqinter> - y\"\n    using 1155 3133 9413 by metis\n  have 12407: \"\\<And>x y . - - x \\<sqinter> - - (x \\<squnion> y) = - - x\"\n    using 1155 2138 by metis\n  have 12639: \"\\<And>x y . - x \\<sqinter> - (- y \\<sqinter> x) = - x\"\n    using 88 12383 by metis\n  have 24647: \"\\<And>x y . (- x \\<sqinter> - y) \\<squnion> - (- x \\<sqinter> - y) = top\"\n    using 19 12393 by metis\n  have 28269: \"\\<And>x y z . - - (x \\<sqinter> y) \\<squnion> - (- x \\<sqinter> z) = - (- x \\<sqinter> z)\"\n    using 373 404 by metis\n  have 28338: \"\\<And>x y . - (- - (x \\<sqinter> y) \\<sqinter> x) = - (x \\<sqinter> y)\"\n    using 123 405 12370 by metis\n  have 28422: \"\\<And>x y . - (- x \\<sqinter> - y) = - (- y \\<sqinter> - x)\"\n    using 13 3134 12393 28338 by metis\n  have 28485: \"\\<And>x y . - x \\<sqinter> - y = - y \\<sqinter> - x\"\n    using 2097 3961 12393 28422 by metis\n  have 30411: \"\\<And>x y . - x \\<sqinter> (x \\<squnion> (x \\<sqinter> y)) = bot\"\n    using 9 82 2094 2320 by metis\n  have 30469: \"\\<And>x . - x \\<sqinter> (x \\<squnion> - - x) = bot\"\n    using 9 123 132 30411 by metis\n  have 37513: \"\\<And>x y . - (- x \\<sqinter> - y) \\<sqinter> - (y \\<squnion> x) = bot\"\n    using 2202 4644 by metis\n  have 52421: \"\\<And>x y . - (- x \\<sqinter> - (- x \\<sqinter> y)) \\<sqinter> y = y\"\n    using 14 144 24647 28485 by metis\n  have 52520: \"\\<And>x y . - x \\<sqinter> - (- x \\<sqinter> y) = - x \\<sqinter> - y\"\n    using 13 12376 12393 12639 28485 52421 by metis\n  have 52533: \"\\<And>x y z . - - (x \\<squnion> (y \\<sqinter> (z \\<squnion> top))) \\<sqinter> (x \\<squnion> y) = x \\<squnion> y\"\n    using 15 49 2094 52421 by metis\n  have 61101: \"\\<And>x y z . - (- - x \\<sqinter> y) \\<squnion> z = - x \\<squnion> (- y \\<squnion> z)\"\n    using 111 2546 12370 52520 by metis\n  have 61156: \"\\<And>x y . - - (- x \\<sqinter> y) = - x \\<sqinter> - - y\"\n    using 419 52520 by metis\n  have 61162: \"\\<And>x y . - (x \\<squnion> (x \\<sqinter> y)) = - x\"\n    using 15 49 2138 30411 52520 by metis\n  have 61163: \"\\<And>x . - (x \\<squnion> - - x) = - x\"\n    using 15 49 2138 30469 52520 by metis\n  have 61229: \"\\<And>x y z . - x \\<sqinter> (- - y \\<sqinter> - (x \\<sqinter> z)) = - x \\<sqinter> - - y\"\n    using 13 15 49 132 9519 52520 61156 by metis\n  have 61311: \"\\<And>x y . - x \\<squnion> - y = - (- - y \\<sqinter> x)\"\n    using 119 11069 61101 by metis\n  have 61391: \"\\<And>x y . - (- x \\<sqinter> - - y) = - (- x \\<sqinter> y)\"\n    using 13 28269 61156 61229 61311 by metis\n  have 61420: \"\\<And>x y . - (- - x \\<sqinter> y) = - (- - y \\<sqinter> x)\"\n    using 13 134 2191 61156 61311 by metis\n  have 61454: \"\\<And>x y . - (x \\<squnion> - (- y \\<sqinter> - x)) = - y \\<sqinter> - x\"\n    using 9 132 3133 61156 61162 by metis\n  have 61648: \"\\<And>x y . - x \\<sqinter> (x \\<squnion> (- y \\<sqinter> - - x)) = bot\"\n    using 1117 61163 by metis\n  have 62434: \"\\<And>x y . - (- - x \\<sqinter> y) \\<sqinter> x = - y \\<sqinter> x\"\n    using 43 61311 by metis\n  have 63947: \"\\<And>x y . - (- x \\<sqinter> y) \\<sqinter> - (- y \\<squnion> x) = bot\"\n    using 37513 61391 by metis\n  have 64227: \"\\<And>x y . - (x \\<squnion> (- y \\<sqinter> - - x)) = - x\"\n    using 15 49 2138 52520 61648 by metis\n  have 64239: \"\\<And>x y . - (x \\<squnion> (- - x \\<squnion> y)) = - (x \\<squnion> y)\"\n    using 9 25 12407 64227 by metis\n  have 64241: \"\\<And>x y . - (x \\<squnion> (- - x \\<sqinter> - y)) = - x\"\n    using 28485 64227 by metis\n  have 64260: \"\\<And>x y . - (x \\<squnion> - - (x \\<sqinter> y)) = - x\"\n    using 420 64241 by metis\n  have 64271: \"\\<And>x y . - (- x \\<squnion> (y \\<squnion> - - (y \\<sqinter> x))) = - (- x \\<squnion> y)\"\n    using 9 25 42 64260 by metis\n  have 64281: \"\\<And>x y . - (- x \\<squnion> y) = - (y \\<squnion> - - ((top \\<squnion> y) \\<sqinter> - x))\"\n    using 9 25 157 2706 64260 by metis\n  have 64282: \"\\<And>x y . - (x \\<squnion> - - ((x \\<squnion> top) \\<sqinter> y)) = - (x \\<squnion> - - y)\"\n    using 9 25 132 536 2810 28485 61311 64260 by metis\n  have 65110: \"\\<And>x y . - ((- x \\<sqinter> y) \\<squnion> (- y \\<squnion> x)) = bot\"\n    using 9 14 49 37513 63947 by metis\n  have 65231: \"\\<And>x y . - (x \\<squnion> ((- x \\<sqinter> y) \\<squnion> - y)) = bot\"\n    using 9 25 65110 by metis\n  have 65585: \"\\<And>x y . - (x \\<squnion> - y) = - - y \\<sqinter> - x\"\n    using 61311 61454 64239 by metis\n  have 65615: \"\\<And>x y . - x \\<sqinter> - ((x \\<squnion> top) \\<sqinter> y) = - y \\<sqinter> - x\"\n    using 132 28485 64282 65585 by metis\n  have 65616: \"\\<And>x y . - (- x \\<squnion> y) = - y \\<sqinter> - ((top \\<squnion> y) \\<sqinter> - x)\"\n    using 132 28485 64281 65585 by metis\n  have 65791: \"\\<And>x y . - x \\<sqinter> - ((top \\<squnion> x) \\<sqinter> - y) = - - y \\<sqinter> - x\"\n    using 89 132 12376 28485 64271 65585 65615 65616 by metis\n  have 65933: \"\\<And>x y . - (- x \\<squnion> y) = - - x \\<sqinter> - y\"\n    using 65616 65791 by metis\n  have 66082: \"\\<And>x y z . - (x \\<squnion> (y \\<squnion> - z)) = - - z \\<sqinter> - (x \\<squnion> y)\"\n    using 8 65585 by metis\n  have 66204: \"\\<And>x y . - - x \\<sqinter> - (y \\<squnion> (- y \\<sqinter> x)) = bot\"\n    using 65231 66082 by metis\n  have 66281: \"\\<And>x y z . - (x \\<squnion> (- y \\<squnion> z)) = - - y \\<sqinter> - (x \\<squnion> z)\"\n    using 25 65933 by metis\n  have 67527: \"\\<And>x y . - - (x \\<squnion> (- x \\<sqinter> y)) \\<sqinter> y = y\"\n    using 14 49 62434 66204 by metis\n  have 67762: \"\\<And>x y . - (- - x \\<sqinter> (y \\<squnion> (- y \\<sqinter> x))) = - x\"\n    using 61420 67527 by metis\n  have 68018: \"\\<And>x y z . - (x \\<squnion> y) \\<sqinter> (x \\<squnion> (y \\<sqinter> (z \\<squnion> top))) = bot\"\n    using 8 83 1113 2320 by metis\n  have 71989: \"\\<And>x y z . - (x \\<squnion> (y \\<sqinter> (z \\<squnion> top))) = - (x \\<squnion> y)\"\n    using 9 29 52533 67762 68018 by metis\n  have 71997: \"\\<And>x y z . - ((x \\<sqinter> (y \\<squnion> top)) \\<squnion> z) = - (x \\<squnion> z)\"\n    using 17 2320 71989 by metis\n  have 72090: \"\\<And>x y z . - (x \\<squnion> ((x \\<sqinter> y) \\<squnion> z)) = - (x \\<squnion> z)\"\n    using 10 14 705 71997 by metis\n  have 72139: \"\\<And>x y . - (x \\<squnion> y) = - x \\<sqinter> - y\"\n    using 25 123 132 2138 65933 66281 72090 by metis\n  show ?thesis\n    using 72139 by metis\nqed\n\nlemma l15:\n  \"--(x \\<squnion> y) = --x \\<squnion> --y\"\n  by (simp add: l11 l12 l4)\n\nlemma l13_var:\n  \"- - (- x \\<sqinter> y) = - x \\<sqinter> - - y\"\nproof -\n  have 1: \"\\<And>x y . x \\<le> y \\<longleftrightarrow> x \\<squnion> y = y\"\n    by (simp add: il_less_eq)\n  have 4: \"\\<And>x y . \\<not>(x \\<le> y) \\<or> x \\<squnion> y = y\"\n    using 1 by metis\n  have 5: \"\\<And>x y z . (x \\<sqinter> y) \\<squnion> (x \\<sqinter> z) \\<le> x \\<sqinter> (y \\<squnion> z)\"\n    by (simp add: il_sub_inf_right_isotone_var)\n  have 6: \"\\<And>x y . - - x \\<le> - (- x \\<sqinter> y)\"\n    by (simp add: pad2)\n  have 7: \"\\<And>x y z . x \\<squnion> (y \\<squnion> z) = (x \\<squnion> y) \\<squnion> z\"\n    by (simp add: il_associative)\n  have 8: \"\\<And>x y z . (x \\<squnion> y) \\<squnion> z = x \\<squnion> (y \\<squnion> z)\"\n    using 7 by metis\n  have 9: \"\\<And>x y . x \\<squnion> y = y \\<squnion> x\"\n    by (simp add: il_commutative)\n  have 10: \"\\<And>x . x \\<squnion> bot = x\"\n    by (simp add: il_bot_unit)\n  have 11: \"\\<And>x . x \\<squnion> x = x\"\n    by simp\n  have 12: \"\\<And>x y z . x \\<sqinter> (y \\<sqinter> z) = (x \\<sqinter> y) \\<sqinter> z\"\n    by (simp add: il_inf_associative)\n  have 13: \"\\<And>x y z . (x \\<sqinter> y) \\<sqinter> z = x \\<sqinter> (y \\<sqinter> z)\"\n    using 12 by metis\n  have 14: \"\\<And>x . top \\<sqinter> x = x\"\n    by simp\n  have 15: \"\\<And>x . x \\<sqinter> top = x\"\n    by simp\n  have 16: \"\\<And>x y z . (x \\<squnion> y) \\<sqinter> z = (x \\<sqinter> z) \\<squnion> (y \\<sqinter> z)\"\n    by (simp add: il_inf_right_dist_sup)\n  have 17: \"\\<And>x y z . (x \\<sqinter> y) \\<squnion> (z \\<sqinter> y) = (x \\<squnion> z) \\<sqinter> y\"\n    using 16 by metis\n  have 19: \"\\<And>x . - x \\<squnion> - - x = top\"\n    by simp\n  have 20: \"\\<And>x . - x \\<sqinter> x = bot\"\n    by (simp add: a_inf_complement_bot)\n  have 22: \"\\<And>x y z . ((x \\<sqinter> y) \\<squnion> (x \\<sqinter> z)) \\<squnion> (x \\<sqinter> (y \\<squnion> z)) = x \\<sqinter> (y \\<squnion> z)\"\n    using 4 5 by metis\n  have 23: \"\\<And>x y z . (x \\<sqinter> (y \\<squnion> z)) \\<squnion> ((x \\<sqinter> y) \\<squnion> (x \\<sqinter> z)) = x \\<sqinter> (y \\<squnion> z)\"\n    using 9 22 by metis\n  have 24: \"\\<And>x y . - - x \\<squnion> - (- x \\<sqinter> y) = - (- x \\<sqinter> y)\"\n    using 4 6 by metis\n  have 25: \"\\<And>x y z . x \\<squnion> (y \\<squnion> z) = y \\<squnion> (x \\<squnion> z)\"\n    using 8 9 by metis\n  have 26: \"\\<And>x y z . (x \\<sqinter> y) \\<squnion> ((x \\<sqinter> z) \\<squnion> (x \\<sqinter> (y \\<squnion> z))) = x \\<sqinter> (y \\<squnion> z)\"\n    using 9 23 25 by metis\n  have 29: \"\\<And>x . bot \\<squnion> x = x\"\n    using 9 10 by metis\n  have 30: \"\\<And>x y . x \\<squnion> (x \\<squnion> y) = x \\<squnion> y\"\n    using 8 11 by metis\n  have 34: \"\\<And>u x y z . (x \\<sqinter> (y \\<sqinter> z)) \\<squnion> (u \\<sqinter> z) = ((x \\<sqinter> y) \\<squnion> u) \\<sqinter> z\"\n    using 13 17 by metis\n  have 35: \"\\<And>u x y z . (x \\<sqinter> y) \\<squnion> (z \\<sqinter> (u \\<sqinter> y)) = (x \\<squnion> (z \\<sqinter> u)) \\<sqinter> y\"\n    using 13 17 by metis\n  have 38: \"\\<And>x y . - x \\<squnion> (- - x \\<squnion> y) = top \\<squnion> y\"\n    using 8 19 by metis\n  have 41: \"- top = bot\"\n    using 15 20 by metis\n  have 42: \"\\<And>x y . (- x \\<squnion> y) \\<sqinter> x = y \\<sqinter> x\"\n    using 17 20 29 by metis\n  have 43: \"\\<And>x y . (x \\<squnion> - y) \\<sqinter> y = x \\<sqinter> y\"\n    using 9 17 20 29 by metis\n  have 45: \"\\<And>x . - bot \\<squnion> - - x = - bot\"\n    using 9 20 24 by metis\n  have 49: \"- bot = top\"\n    using 19 29 41 by metis\n  have 50: \"\\<And>x . top \\<squnion> - - x = top\"\n    using 45 49 by metis\n  have 62: \"\\<And>x y . x \\<squnion> ((x \\<sqinter> - y) \\<squnion> (x \\<sqinter> - - y)) = x\"\n    using 9 15 19 25 26 by metis\n  have 65: \"\\<And>x y . (- (x \\<squnion> y) \\<sqinter> x) \\<squnion> (- (x \\<squnion> y) \\<sqinter> y) = bot\"\n    using 9 20 26 29 by metis\n  have 66: \"\\<And>x y z . (x \\<sqinter> - - y) \\<squnion> (x \\<sqinter> - (- y \\<sqinter> z)) = x \\<sqinter> - (- y \\<sqinter> z)\"\n    using 11 24 26 by metis\n  have 69: \"\\<And>x y . x \\<squnion> (x \\<sqinter> - - y) = x\"\n    using 9 15 26 30 50 by metis\n  have 81: \"\\<And>x . top \\<squnion> - x = top\"\n    using 9 19 30 by metis\n  have 88: \"\\<And>x y . x \\<squnion> (- y \\<sqinter> x) = x\"\n    using 14 17 81 by metis\n  have 101: \"\\<And>x y z . x \\<squnion> (y \\<squnion> (x \\<sqinter> - - z)) = y \\<squnion> x\"\n    using 25 69 by metis\n  have 103: \"\\<And>x y . x \\<squnion> (x \\<sqinter> - y) = x\"\n    using 9 62 101 by metis\n  have 123: \"\\<And>x . - - x \\<sqinter> x = x\"\n    using 14 19 42 by metis\n  have 127: \"\\<And>x y . - - x \\<sqinter> (x \\<sqinter> y) = x \\<sqinter> y\"\n    using 13 123 by metis\n  have 130: \"\\<And>x . - x \\<squnion> - - - x = - x\"\n    using 9 24 123 by metis\n  have 132: \"\\<And>x . - - - x = - x\"\n    using 9 103 123 130 by metis\n  have 136: \"\\<And>x y . (- x \\<squnion> y) \\<sqinter> - - x = y \\<sqinter> - - x\"\n    using 42 132 by metis\n  have 144: \"\\<And>x y z . ((- (x \\<sqinter> y) \\<sqinter> x) \\<squnion> z) \\<sqinter> y = z \\<sqinter> y\"\n    using 20 29 34 by metis\n  have 182: \"\\<And>x y z . (x \\<squnion> (- - (y \\<sqinter> z) \\<sqinter> y)) \\<sqinter> z = (x \\<squnion> y) \\<sqinter> z\"\n    using 17 35 123 by metis\n  have 288: \"\\<And>x y . - x \\<squnion> - (- x \\<sqinter> y) = top\"\n    using 24 38 81 by metis\n  have 315: \"\\<And>x y . - (- x \\<sqinter> y) \\<sqinter> x = x\"\n    using 14 42 288 by metis\n  have 319: \"\\<And>x y . - x \\<squnion> - - (- x \\<sqinter> y) = - x\"\n    using 9 24 315 by metis\n  have 387: \"\\<And>x y . - (x \\<sqinter> y) \\<sqinter> - x = - x\"\n    using 127 315 by metis\n  have 405: \"\\<And>x y z . - (x \\<sqinter> (y \\<sqinter> z)) \\<sqinter> - (x \\<sqinter> y) = - (x \\<sqinter> y)\"\n    using 13 387 by metis\n  have 419: \"\\<And>x y . - x \\<sqinter> - - (- x \\<sqinter> y) = - - (- x \\<sqinter> y)\"\n    using 315 387 by metis\n  have 1091: \"\\<And>x y . - (x \\<squnion> y) \\<sqinter> x = bot\"\n    using 9 29 30 65 by metis\n  have 1129: \"\\<And>x y z . (- (x \\<squnion> y) \\<squnion> z) \\<sqinter> x = z \\<sqinter> x\"\n    using 17 29 1091 by metis\n  have 1155: \"\\<And>x y . - - x \\<sqinter> - (- x \\<sqinter> y) = - - x\"\n    using 66 103 123 132 by metis\n  have 2097: \"\\<And>x y . - - (x \\<squnion> y) \\<sqinter> x = x\"\n    using 14 19 1129 by metis\n  have 2124: \"\\<And>x y . - - (x \\<squnion> y) \\<sqinter> y = y\"\n    using 9 2097 by metis\n  have 2137: \"\\<And>x y . - x \\<squnion> - - (x \\<squnion> y) = top\"\n    using 9 288 2097 by metis\n  have 2201: \"\\<And>x y . - x \\<squnion> - - (y \\<squnion> x) = top\"\n    using 9 288 2124 by metis\n  have 2343: \"\\<And>x y . - (- x \\<sqinter> y) \\<squnion> - - y = top\"\n    using 88 2201 by metis\n  have 3022: \"\\<And>x y . - x \\<squnion> - (- y \\<sqinter> - x) = top\"\n    using 9 132 2343 by metis\n  have 3133: \"\\<And>x y . - (- x \\<sqinter> - y) \\<sqinter> y = y\"\n    using 14 42 3022 by metis\n  have 3134: \"\\<And>x y . - x \\<sqinter> (- y \\<sqinter> - x) = - y \\<sqinter> - x\"\n    using 14 43 3022 by metis\n  have 3961: \"\\<And>x y . - - (x \\<squnion> y) \\<sqinter> - - x = - - x\"\n    using 14 136 2137 by metis\n  have 9413: \"\\<And>x y . - - (- x \\<sqinter> y) \\<sqinter> y = - x \\<sqinter> y\"\n    using 9 103 182 319 by metis\n  have 12370: \"\\<And>x y . - x \\<sqinter> - (- - x \\<sqinter> y) = - x\"\n    using 132 1155 by metis\n  have 12376: \"\\<And>x y . - x \\<sqinter> - (x \\<sqinter> y) = - x\"\n    using 127 132 1155 by metis\n  have 12383: \"\\<And>x y . - (x \\<squnion> y) \\<sqinter> - y = - (x \\<squnion> y)\"\n    using 132 1155 2124 by metis\n  have 12393: \"\\<And>x y . - - (- x \\<sqinter> - y) = - x \\<sqinter> - y\"\n    using 1155 3133 9413 by metis\n  have 12639: \"\\<And>x y . - x \\<sqinter> - (- y \\<sqinter> x) = - x\"\n    using 88 12383 by metis\n  have 24647: \"\\<And>x y . (- x \\<sqinter> - y) \\<squnion> - (- x \\<sqinter> - y) = top\"\n    using 19 12393 by metis\n  have 28338: \"\\<And>x y . - (- - (x \\<sqinter> y) \\<sqinter> x) = - (x \\<sqinter> y)\"\n    using 123 405 12370 by metis\n  have 28422: \"\\<And>x y . - (- x \\<sqinter> - y) = - (- y \\<sqinter> - x)\"\n    using 13 3134 12393 28338 by metis\n  have 28485: \"\\<And>x y . - x \\<sqinter> - y = - y \\<sqinter> - x\"\n    using 2097 3961 12393 28422 by metis\n  have 52421: \"\\<And>x y . - (- x \\<sqinter> - (- x \\<sqinter> y)) \\<sqinter> y = y\"\n    using 14 144 24647 28485 by metis\n  have 52520: \"\\<And>x y . - x \\<sqinter> - (- x \\<sqinter> y) = - x \\<sqinter> - y\"\n    using 13 12376 12393 12639 28485 52421 by metis\n  have 61156: \"\\<And>x y . - - (- x \\<sqinter> y) = - x \\<sqinter> - - y\"\n    using 419 52520 by metis\n  show ?thesis\n    using 61156 by metis\nqed\n\ntext \\<open>Theorem 25.1\\<close>\n\nsubclass subset_boolean_algebra_2\nproof\n  show \"\\<And>x y z. x \\<squnion> (y \\<squnion> z) = x \\<squnion> y \\<squnion> z\"\n    by (simp add: il_associative)\n  show \"\\<And>x y. x \\<squnion> y = y \\<squnion> x\"\n    by (simp add: il_commutative)\n  show \"\\<And>x. x \\<squnion> x = x\"\n    by simp\n  show \"\\<And>x y. x \\<squnion> - (y \\<squnion> - y) = x\"\n    using il_bot_unit l12 l6 by auto\n  show \"\\<And>x y. - (x \\<squnion> y) = - (- - x \\<squnion> - - y)\"\n    by (metis l15 l4)\n  show \"\\<And>x y. - x \\<squnion> - (- x \\<squnion> y) = - x \\<squnion> - y\"\n    by (smt l11 l15 il_inf_right_dist_sup il_unit_bot l6 l7)\nqed\n\nlemma aa_test:\n  \"p = --p \\<Longrightarrow> test p\"\n  by (metis ppa_ppd.d_closed)\n\nlemma test_aa_increasing:\n  \"test p \\<Longrightarrow> p \\<le> --p\"\n  by (simp add: ppa_ppd.d_increasing_sub_identity test_sub_identity)\n\nlemma \"test p \\<Longrightarrow> - - (p \\<sqinter> x) \\<le> p\" nitpick [expect=genuine] oops\nlemma \"test p \\<Longrightarrow> --p \\<le> p\" nitpick [expect=genuine] oops\n\nend\n\nclass pa_algebra = pa_semiring + minus +\n  assumes pa_minus_def: \"-x - -y = -(--x \\<squnion> -y)\"\nbegin\n\nsubclass subset_boolean_algebra_2_extended\nproof\n  show \"bot = (THE x. \\<forall>z. x = - (z \\<squnion> - z))\"\n    using l12 l6 by auto\n  thus \"top = - (THE x. \\<forall>z. x = - (z \\<squnion> - z))\"\n    using l2 by blast\n  show \"\\<And>x y. - x \\<sqinter> - y = - (- - x \\<squnion> - - y)\"\n    by (metis l12 l4)\n  show \"\\<And>x y. - x - - y = - (- - x \\<squnion> - y)\"\n    by (simp add: pa_minus_def)\n  show \"\\<And>x y. (x \\<le> y) = (x \\<squnion> y = y)\"\n    by (simp add: il_less_eq)\n  show \"\\<And>x y. (x < y) = (x \\<squnion> y = y \\<and> y \\<squnion> x \\<noteq> x)\"\n    by (simp add: il_less_eq less_le_not_le)\nqed\n\nlemma \"\\<And>x y. - (x \\<sqinter> - - y) = - (x \\<sqinter> y)\" nitpick [expect=genuine] oops\n\nend\n\nsubsection \\<open>Antidomain Semirings\\<close>\n\ntext \\<open>Definition 24\\<close>\n\nclass a_semiring = ppa_semiring +\n  assumes ad3: \"-(x \\<sqinter> y) \\<le> -(x \\<sqinter> --y)\"\nbegin\n\nlemma l16:\n  \"- - x \\<le> - (- x \\<sqinter> y)\"\nproof -\n  have 1: \"\\<And>x y . x \\<le> y \\<longleftrightarrow> x \\<squnion> y = y\"\n    by (simp add: il_less_eq)\n  have 3: \"\\<And>x y z . x \\<squnion> (y \\<squnion> z) = (x \\<squnion> y) \\<squnion> z\"\n    by (simp add: il_associative)\n  have 4: \"\\<And>x y z . (x \\<squnion> y) \\<squnion> z = x \\<squnion> (y \\<squnion> z)\"\n    using 3 by metis\n  have 5: \"\\<And>x y . x \\<squnion> y = y \\<squnion> x\"\n    by (simp add: il_commutative)\n  have 6: \"\\<And>x . x \\<squnion> bot = x\"\n    by (simp add: il_bot_unit)\n  have 7: \"\\<And>x . x \\<squnion> x = x\"\n    by simp\n  have 8: \"\\<And>x y . \\<not>(x \\<le> y) \\<or> x \\<squnion> y = y\"\n    using 1 by metis\n  have 9: \"\\<And>x y . x \\<le> y \\<or> x \\<squnion> y \\<noteq> y\"\n    using 1 by metis\n  have 10: \"\\<And>x y z . x \\<sqinter> (y \\<sqinter> z) = (x \\<sqinter> y) \\<sqinter> z\"\n    by (simp add: il_inf_associative)\n  have 11: \"\\<And>x y z . (x \\<sqinter> y) \\<sqinter> z = x \\<sqinter> (y \\<sqinter> z)\"\n    using 10 by metis\n  have 12: \"\\<And>x . top \\<sqinter> x = x\"\n    by simp\n  have 13: \"\\<And>x . x \\<sqinter> top = x\"\n    by simp\n  have 14: \"\\<And>x y z . (x \\<sqinter> y) \\<squnion> (x \\<sqinter> z) \\<le> x \\<sqinter> (y \\<squnion> z)\"\n    by (simp add: il_sub_inf_right_isotone_var)\n  have 15: \"\\<And>x y z . (x \\<squnion> y) \\<sqinter> z = (x \\<sqinter> z) \\<squnion> (y \\<sqinter> z)\"\n    by (simp add: il_inf_right_dist_sup)\n  have 16: \"\\<And>x y z . (x \\<sqinter> y) \\<squnion> (z \\<sqinter> y) = (x \\<squnion> z) \\<sqinter> y\"\n    using 15 by metis\n  have 17: \"\\<And>x . bot \\<sqinter> x = bot\"\n    by simp\n  have 18: \"\\<And>x . - x \\<squnion> - - x = top\"\n    by simp\n  have 19: \"\\<And>x . - x \\<sqinter> x = bot\"\n    by (simp add: a_inf_complement_bot)\n  have 20: \"\\<And>x y . - (x \\<sqinter> y) \\<le> - (x \\<sqinter> - - y)\"\n    by (simp add: ad3)\n  have 22: \"\\<And>x y z . x \\<squnion> (y \\<squnion> z) = y \\<squnion> (x \\<squnion> z)\"\n    using 4 5 by metis\n  have 25: \"\\<And>x . bot \\<squnion> x = x\"\n    using 5 6 by metis\n  have 26: \"\\<And>x y . x \\<squnion> (x \\<squnion> y) = x \\<squnion> y\"\n    using 4 7 by metis\n  have 33: \"\\<And>x y z . (x \\<sqinter> y) \\<squnion> ((x \\<sqinter> z) \\<squnion> (x \\<sqinter> (y \\<squnion> z))) = x \\<sqinter> (y \\<squnion> z)\"\n    using 5 8 14 22 by metis\n  have 47: \"\\<And>x y . - x \\<squnion> (- - x \\<squnion> y) = top \\<squnion> y\"\n    using 4 18 by metis\n  have 48: \"\\<And>x y . - - x \\<squnion> (y \\<squnion> - x) = y \\<squnion> top\"\n    using 4 5 18 by metis\n  have 51: \"\\<And>x y . - x \\<sqinter> (x \\<sqinter> y) = bot\"\n    using 11 17 19 by metis\n  have 52: \"- top = bot\"\n    using 13 19 by metis\n  have 56: \"\\<And>x y . (- x \\<squnion> y) \\<sqinter> x = y \\<sqinter> x\"\n    using 16 19 25 by metis\n  have 57: \"\\<And>x y . (x \\<squnion> - y) \\<sqinter> y = x \\<sqinter> y\"\n    using 5 16 19 25 by metis\n  have 58: \"\\<And>x y . - (x \\<sqinter> y) \\<squnion> - (x \\<sqinter> - - y) = - (x \\<sqinter> - - y)\"\n    using 8 20 by metis\n  have 60: \"\\<And>x . - x \\<le> - - - x\"\n    using 12 20 by metis\n  have 69: \"- bot = top\"\n    using 18 25 52 by metis\n  have 74: \"\\<And>x y . x \\<le> x \\<squnion> y\"\n    using 9 26 by metis\n  have 78: \"\\<And>x . top \\<squnion> - x = top\"\n    using 5 18 26 by metis\n  have 80: \"\\<And>x y . x \\<le> y \\<squnion> x\"\n    using 5 74 by metis\n  have 86: \"\\<And>x y z . x \\<squnion> y \\<le> x \\<squnion> (z \\<squnion> y)\"\n    using 22 80 by metis\n  have 95: \"\\<And>x . - x \\<squnion> - - - x = - - - x\"\n    using 8 60 by metis\n  have 143: \"\\<And>x y . x \\<squnion> (x \\<sqinter> - y) = x\"\n    using 5 13 26 33 78 by metis\n  have 370: \"\\<And>x y z . x \\<squnion> (y \\<sqinter> - z) \\<le> x \\<squnion> y\"\n    using 86 143 by metis\n  have 907: \"\\<And>x . - x \\<sqinter> - x = - x\"\n    using 12 18 57 by metis\n  have 928: \"\\<And>x y . - x \\<sqinter> (- x \\<sqinter> y) = - x \\<sqinter> y\"\n    using 11 907 by metis\n  have 966: \"\\<And>x y . - (- x \\<sqinter> - - (x \\<sqinter> y)) = top\"\n    using 51 58 69 78 by metis\n  have 1535: \"\\<And>x . - x \\<squnion> - - - - x = top\"\n    using 47 78 95 by metis\n  have 1630: \"\\<And>x y z . (x \\<squnion> y) \\<sqinter> - z \\<le> (x \\<sqinter> - z) \\<squnion> y\"\n    using 16 370 by metis\n  have 2422: \"\\<And>x . - x \\<sqinter> - - - x = - - - x\"\n    using 12 57 1535 by metis\n  have 6567: \"\\<And>x y . - x \\<sqinter> - - (x \\<sqinter> y) = bot\"\n    using 12 19 966 by metis\n  have 18123: \"\\<And>x . - - - x = - x\"\n    using 95 143 2422 by metis\n  have 26264: \"\\<And>x y . - x \\<le> (- y \\<sqinter> - x) \\<squnion> - - y\"\n    using 12 18 1630 by metis\n  have 26279: \"\\<And>x y . - - (x \\<sqinter> y) \\<le> - - x\"\n    using 25 6567 26264 by metis\n  have 26307: \"\\<And>x y . - - (- x \\<sqinter> y) \\<le> - x\"\n    using 928 18123 26279 by metis\n  have 26339: \"\\<And>x y . - x \\<squnion> - - (- x \\<sqinter> y) = - x\"\n    using 5 8 26307 by metis\n  have 26564: \"\\<And>x y . - x \\<squnion> - (- x \\<sqinter> y) = top\"\n    using 5 48 78 18123 26339 by metis\n  have 26682: \"\\<And>x y . - (- x \\<sqinter> y) \\<sqinter> x = x\"\n    using 12 56 26564 by metis\n  have 26864: \"\\<And>x y . - - x \\<le> - (- x \\<sqinter> y)\"\n    using 18123 26279 26682 by metis\n  show ?thesis\n    using 26864 by metis\nqed\n\ntext \\<open>Theorem 25.2\\<close>\n\nsubclass pa_semiring\nproof\n  show \"\\<And>x y. - - x \\<le> - (- x \\<sqinter> y)\"\n    by (rule l16)\nqed\n\nlemma l17:\n  \"-(x \\<sqinter> y) = -(x \\<sqinter> --y)\"\n  by (simp add: ad3 order.antisym l14)\n\nlemma a_complement_inf_double_complement:\n  \"-(x \\<sqinter> --y) = -(x \\<sqinter> y)\"\n  using l17 by auto\n\nsublocale a_d: d_semiring_var where d = \"\\<lambda>x . --x\"\nproof\n  show \"\\<And>x y. - - (x \\<sqinter> - - y) \\<le> - - (x \\<sqinter> y)\"\n    using l17 by auto\n  show \"- - bot = bot\"\n    by (simp add: l1 l2)\nqed\n\nlemma \"test p \\<Longrightarrow> - - (p \\<sqinter> x) \\<le> p\"\n  by (fact a_d.d2)\n\nend\n\nclass a_algebra = a_semiring + minus +\n  assumes a_minus_def: \"-x - -y = -(--x \\<squnion> -y)\"\nbegin\n\nsubclass pa_algebra\nproof\n  show \"\\<And>x y. - x - - y = - (- - x \\<squnion> - y)\"\n    by (simp add: a_minus_def)\nqed\n\ntext \\<open>Theorem 25.4\\<close>\n\nsubclass subset_boolean_algebra_4_extended\nproof\n  show \"\\<And>x y z. x \\<sqinter> (y \\<sqinter> z) = x \\<sqinter> y \\<sqinter> z\"\n    by (simp add: il_inf_associative)\n  show \"\\<And>x y z. (x \\<squnion> y) \\<sqinter> z = x \\<sqinter> z \\<squnion> y \\<sqinter> z\"\n    by (simp add: il_inf_right_dist_sup)\n  show \"\\<And>x. - x \\<sqinter> x = bot\"\n    by (simp add: a_inf_complement_bot)\n  show \"\\<And>x. top \\<sqinter> x = x\"\n    by simp\n  show \"\\<And>x y. - (x \\<sqinter> - - y) = - (x \\<sqinter> y)\"\n    using l17 by auto\n  show \"\\<And>x. x \\<sqinter> top = x\"\n    by simp\n  show \"\\<And>x y z. x \\<le> y \\<Longrightarrow> z \\<sqinter> x \\<le> z \\<sqinter> y\"\n    by (simp add: il_sub_inf_right_isotone)\nqed\n\nend\n\ncontext subset_boolean_algebra_4_extended\nbegin\n\nsubclass il_semiring\nproof\n  show \"\\<And>x y z. x \\<squnion> (y \\<squnion> z) = x \\<squnion> y \\<squnion> z\"\n    by (simp add: sup_assoc)\n  show \"\\<And>x y. x \\<squnion> y = y \\<squnion> x\"\n    by (simp add: sup_commute)\n  show \"\\<And>x. x \\<squnion> x = x\"\n    by simp\n  show \"\\<And>x. x \\<squnion> bot = x\"\n    by simp\n  show \"\\<And>x y z. x \\<sqinter> (y \\<sqinter> z) = x \\<sqinter> y \\<sqinter> z\"\n    by (simp add: sba3_inf_associative)\n  show \"\\<And>x y z. (x \\<squnion> y) \\<sqinter> z = x \\<sqinter> z \\<squnion> y \\<sqinter> z\"\n    by (simp add: sba3_inf_right_dist_sup)\n  show \"\\<And>x. top \\<sqinter> x = x\"\n    by simp\n  show \"\\<And>x. x \\<sqinter> top = x\"\n    by simp\n  show \"\\<And>x. bot \\<sqinter> x = bot\"\n    by (simp add: inf_left_zero)\n  show \"\\<And>x y z. x \\<le> y \\<Longrightarrow> z \\<sqinter> x \\<le> z \\<sqinter> y\"\n    by (simp add: inf_right_isotone)\n  show \"\\<And>x y. (x \\<le> y) = (x \\<squnion> y = y)\"\n    by (simp add: le_iff_sup)\n  show \"\\<And>x y. (x < y) = (x \\<le> y \\<and> \\<not> y \\<le> x)\"\n    by (simp add: less_le_not_le)\nqed\n\nsubclass a_semiring\nproof\n  show \"\\<And>x. - x \\<sqinter> x = bot\"\n    by (simp add: sba3_inf_complement_bot)\n  show \"\\<And>x. - x \\<squnion> - - x = top\"\n    by simp\n  show \"\\<And>x y. - (x \\<sqinter> y) \\<le> - (x \\<sqinter> - - y)\"\n    by (simp add: sba3_complement_inf_double_complement)\nqed\n\nsublocale sba4_a: a_algebra\nproof\n  show \"\\<And>x y. - x - - y = - (- - x \\<squnion> - y)\"\n    by (simp add: sub_minus_def)\nqed\n\nend\n\ncontext stone_algebra\nbegin\n\ntext \\<open>Theorem 25.3\\<close>\n\nsubclass il_semiring\nproof\n  show \"\\<And>x y z. x \\<squnion> (y \\<squnion> z) = x \\<squnion> y \\<squnion> z\"\n    by (simp add: sup_assoc)\n  show \"\\<And>x y. x \\<squnion> y = y \\<squnion> x\"\n    by (simp add: sup_commute)\n  show \"\\<And>x. x \\<squnion> x = x\"\n    by simp\n  show \"\\<And>x. x \\<squnion> bot = x\"\n    by simp\n  show \"\\<And>x y z. x \\<sqinter> (y \\<sqinter> z) = x \\<sqinter> y \\<sqinter> z\"\n    by (simp add: inf.sup_monoid.add_assoc)\n  show \"\\<And>x y z. (x \\<squnion> y) \\<sqinter> z = x \\<sqinter> z \\<squnion> y \\<sqinter> z\"\n    by (simp add: inf_sup_distrib2)\n  show \"\\<And>x. top \\<sqinter> x = x\"\n    by simp\n  show \"\\<And>x. x \\<sqinter> top = x\"\n    by simp\n  show \"\\<And>x. bot \\<sqinter> x = bot\"\n    by simp\n  show \"\\<And>x y z. x \\<le> y \\<Longrightarrow> z \\<sqinter> x \\<le> z \\<sqinter> y\"\n    using inf.sup_right_isotone by blast\n  show \"\\<And>x y. (x \\<le> y) = (x \\<squnion> y = y)\"\n    by (simp add: le_iff_sup)\n  show \"\\<And>x y. (x < y) = (x \\<le> y \\<and> \\<not> y \\<le> x)\"\n    by (simp add: less_le_not_le)\nqed\n\nsubclass a_semiring\nproof\n  show \"\\<And>x. - x \\<sqinter> x = bot\"\n    by simp\n  show \"\\<And>x. - x \\<squnion> - - x = top\"\n    by simp\n  show \"\\<And>x y. - (x \\<sqinter> y) \\<le> - (x \\<sqinter> - - y)\"\n    by simp\nqed\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/Subset_Boolean_Algebras/Subset_Boolean_Algebras.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392725805823, "lm_q2_score": 0.8128673246376008, "lm_q1q2_score": 0.7186066383771487}}
{"text": "theory RelationsAndOrders_ExtBooleanAlgebra__U2E1\nimports Main\nbegin\n\nML_file \"$HETS_ISABELLE_LIB/prelude.ML\"\n\nsetup \"Header.initialize\n       [\\\"compl_def_ExtBooleanAlgebra\\\",\n        \\\"involution_compl_ExtBooleanAlgebra\\\", \\\"ga_idem___cup__\\\",\n        \\\"ga_idem___cap__\\\", \\\"uniqueComplement_BooleanAlgebra\\\",\n        \\\"ga_assoc___cap__\\\", \\\"ga_comm___cap__\\\",\n        \\\"ga_right_unit___cap__\\\", \\\"ga_left_unit___cap__\\\",\n        \\\"ga_left_comm___cap__\\\", \\\"ga_assoc___cup__\\\",\n        \\\"ga_comm___cup__\\\", \\\"ga_right_unit___cup__\\\",\n        \\\"ga_left_unit___cup__\\\", \\\"ga_left_comm___cup__\\\",\n        \\\"absorption_def1\\\", \\\"absorption_def2\\\", \\\"zeroAndCap\\\",\n        \\\"oneAndCup\\\", \\\"distr1_BooleanAlgebra\\\",\n        \\\"distr2_BooleanAlgebra\\\", \\\"inverse_BooleanAlgebra\\\",\n        \\\"de_Morgan1\\\", \\\"de_Morgan2\\\"]\"\n\ntypedecl Elem\n\nconsts\nX0 :: \"Elem\" (\"0''\")\nX1 :: \"Elem\" (\"1''\")\nX__cap__X :: \"Elem => Elem => Elem\" (\"(_/ cap/ _)\" [57,57] 56)\nX__cup__X :: \"Elem => Elem => Elem\" (\"(_/ cup/ _)\" [55,55] 54)\ncompl__X :: \"Elem => Elem\" (\"(compl/ _)\" [62] 62)\n\naxiomatization\nwhere\ncompl_def_ExtBooleanAlgebra [rule_format] :\n\"ALL x. ALL y. compl x = y = (x cup y = 1' & x cap y = 0')\"\nand\ninvolution_compl_ExtBooleanAlgebra [rule_format] :\n\"ALL x. compl compl x = x\"\nand\nga_idem___cup__ [rule_format] : \"ALL x. x cup x = x\"\nand\nga_idem___cap__ [rule_format] : \"ALL x. x cap x = x\"\nand\nuniqueComplement_BooleanAlgebra [rule_format] :\n\"ALL x. EX! x'. x cup x' = 1' & x cap x' = 0'\"\nand\nga_assoc___cap__ :\n\"ALL x. ALL y. ALL z. (x cap y) cap z = x cap (y cap z)\"\nand\nga_comm___cap__ [rule_format] : \"ALL x. ALL y. x cap y = y cap x\"\nand\nga_right_unit___cap__ [rule_format] : \"ALL x. x cap 1' = x\"\nand\nga_left_unit___cap__ [rule_format] : \"ALL x. 1' cap x = x\"\nand\nga_left_comm___cap__ [rule_format] :\n\"ALL x. ALL y. ALL z. x cap (y cap z) = y cap (x cap z)\"\nand\nga_assoc___cup__ :\n\"ALL x. ALL y. ALL z. (x cup y) cup z = x cup (y cup z)\"\nand\nga_comm___cup__ [rule_format] : \"ALL x. ALL y. x cup y = y cup x\"\nand\nga_right_unit___cup__ [rule_format] : \"ALL x. x cup 0' = x\"\nand\nga_left_unit___cup__ [rule_format] : \"ALL x. 0' cup x = x\"\nand\nga_left_comm___cup__ [rule_format] :\n\"ALL x. ALL y. ALL z. x cup (y cup z) = y cup (x cup z)\"\nand\nabsorption_def1 [rule_format] : \"ALL x. ALL y. x cap (x cup y) = x\"\nand\nabsorption_def2 [rule_format] : \"ALL x. ALL y. x cup x cap y = x\"\nand\nzeroAndCap [rule_format] : \"ALL x. x cap 0' = 0'\"\nand\noneAndCup [rule_format] : \"ALL x. x cup 1' = 1'\"\nand\ndistr1_BooleanAlgebra [rule_format] :\n\"ALL x. ALL y. ALL z. x cap (y cup z) = x cap y cup x cap z\"\nand\ndistr2_BooleanAlgebra [rule_format] :\n\"ALL x. ALL y. ALL z. x cup y cap z = (x cup y) cap (x cup z)\"\nand\ninverse_BooleanAlgebra [rule_format] :\n\"ALL x. EX x'. x cup x' = 1' & x cap x' = 0'\"\n\ndeclare involution_compl_ExtBooleanAlgebra [simp]\ndeclare ga_idem___cup__ [simp]\ndeclare ga_idem___cap__ [simp]\ndeclare ga_right_unit___cap__ [simp]\ndeclare ga_left_unit___cap__ [simp]\ndeclare ga_right_unit___cup__ [simp]\ndeclare ga_left_unit___cup__ [simp]\ndeclare absorption_def1 [simp]\ndeclare absorption_def2 [simp]\ndeclare zeroAndCap [simp]\ndeclare oneAndCup [simp]\n\nlemma compl_cap [simp] : \"x cap (compl x) = 0'\"\nusing compl_def_ExtBooleanAlgebra apply auto\ndone\nlemma compl_cup [simp]: \"x cup (compl x) = 1'\"\nusing compl_def_ExtBooleanAlgebra apply auto\ndone\n\nlemma compl_cap1 [simp]: \"(compl x) cap x = 0'\"\nusing compl_cap ga_comm___cap__ apply auto\ndone\n\nlemma compl_cup1 [simp]: \"(compl x) cup x = 1'\"\nusing compl_cup ga_comm___cup__ apply auto\ndone\n\nlemmas ga_assoc___cap__rev =\n  ga_assoc___cap__[THEN spec, THEN spec, THEN spec, THEN sym]\n\nlemmas ga_assoc___cup__rev =\n  ga_assoc___cup__[THEN spec, THEN spec, THEN spec, THEN sym]\n\ntheorem de_Morgan1 :\n\"ALL x. ALL y. compl (x cap y) = compl x cup compl y\"\napply(simp add: compl_def_ExtBooleanAlgebra)\napply((rule allI)+)\napply(rule conjI)\napply(subst ga_comm___cup__)\napply(simp add: distr2_BooleanAlgebra ga_assoc___cup__)\napply(simp add: ga_assoc___cup__rev)\napply(subst ga_comm___cup__)\napply(simp add: ga_assoc___cup__)\n\napply(simp add: distr1_BooleanAlgebra ga_assoc___cap__)\napply(simp add: ga_assoc___cap__rev)\napply(simp add: ga_comm___cap__)\napply(simp add: ga_assoc___cap__rev)\napply(simp add: ga_comm___cap__)\ndone\n\nsetup \"Header.record \\\"de_Morgan1\\\"\"\n\ntheorem de_Morgan2 :\n\"ALL x. ALL y. compl (x cup y) = compl x cap compl y\"\napply((rule allI)+)\napply (subst de_Morgan1[THEN spec,THEN spec, THEN sym,\n  of \"compl x\", of \"compl y\", simplified])\nby auto\n\nsetup \"Header.record \\\"de_Morgan2\\\"\"\n\nend\n", "meta": {"author": "spechub", "repo": "Hets-lib", "sha": "7bed416952e7000e2fa37f0b6071b5291b299b77", "save_path": "github-repos/isabelle/spechub-Hets-lib", "path": "github-repos/isabelle/spechub-Hets-lib/Hets-lib-7bed416952e7000e2fa37f0b6071b5291b299b77/Basic/RelationsAndOrders_ExtBooleanAlgebra__U2E1.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392725805822, "lm_q2_score": 0.8128673110375457, "lm_q1q2_score": 0.7186066263541658}}
{"text": "theory ExF008\n  imports Main \nbegin \n \n\n  \nlemma \"(\\<not> (\\<exists>x. \\<forall>y. P x y)) \\<longleftrightarrow> (\\<forall>x. \\<exists>y. \\<not>P x y)\" \nproof-\n  {\n    assume a:\"\\<not> (\\<exists>x. \\<forall>y. P x y)\"\n    {\n      assume b:\"\\<not>(\\<forall>x. \\<exists>y. \\<not>P x y)\" \n      {\n        fix aa \n        {\n          assume c:\"\\<not>(\\<exists>y. \\<not>P aa y)\"\n          {\n            fix bb\n            {\n              assume \"\\<not>P aa bb\" \n              hence \"\\<exists>y. \\<not>P aa y\" by (rule exI)\n              with c have False by contradiction\n            }\n            hence \"\\<not>\\<not>P aa bb\" by (rule notI)\n            hence \"P aa bb\" by (rule notnotD)\n          }\n          hence \"\\<forall>y. P aa y\" by (rule allI)\n          hence \"\\<exists>x. \\<forall>y. P x y\" by (rule exI)\n          with a have False by contradiction\n        }\n        hence \"\\<not>\\<not>(\\<exists>y. \\<not>P aa y)\" by (rule notI)\n        hence \"\\<exists>y. \\<not>P aa y\" by (rule notnotD)\n      }\n      hence \"\\<forall>x. \\<exists>y. \\<not>P x y\" by (rule allI)\n      with b have False by contradiction\n    }\n    hence \"\\<not>\\<not>(\\<forall>x. \\<exists>y. \\<not>P x y)\" by (rule notI)\n    hence \"\\<forall>x. \\<exists>y. \\<not>P x y\" by (rule notnotD)\n  }\n  moreover\n  {\n    assume a:\"\\<forall>x. \\<exists>y. \\<not>P x y\"\n    {\n      assume b:\"\\<exists>x. \\<forall>y. P x y\" \n      {\n        fix aa\n        assume c:\"\\<forall>y. P aa y\"\n        from a have d:\"\\<exists>y. \\<not>P aa y\" by (rule allE)\n        {\n          fix bb \n          assume d:\" \\<not>P aa bb\" \n          from c have \"P aa bb\" by (rule allE)\n          with d have False by contradiction\n        }\n        with d have False by (rule exE)\n      }\n      with b have False by (rule exE)\n    }\n    hence \"\\<not>(\\<exists>x. \\<forall>y. P x y)\" by (rule notI)\n  }\n  ultimately show ?thesis by (rule iffI)\nqed\n  \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/FOL/ExF008.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.905989815306765, "lm_q2_score": 0.7931059462938815, "lm_q1q2_score": 0.7185459098014908}}
{"text": "(*\n    Author:     Wenda Li <wl302@cam.ac.uk / liwenda1990@hotmail.com>\n*)\ntheory Count_Circle imports \n  Count_Half_Plane\nbegin\n\nsubsection \\<open>Polynomial roots within a circle (open ball)\\<close>\n\n\\<comment> \\<open>Roots counted WITH multiplicity\\<close>\ndefinition proots_ball::\"complex poly \\<Rightarrow> complex \\<Rightarrow> real \\<Rightarrow> nat\" where\n  \"proots_ball p z0 r = proots_count p (ball z0 r)\" \n\n\\<comment> \\<open>Roots counted WITHOUT multiplicity\\<close>\ndefinition proots_ball_card ::\"complex poly \\<Rightarrow> complex \\<Rightarrow> real \\<Rightarrow> nat\" where\n  \"proots_ball_card p z0 r = card (proots_within p (ball z0 r))\"\n\nlemma proots_ball_code1[code]:\n  \"proots_ball p z0 r = ( if r \\<le> 0 then \n                              0\n                          else if p\\<noteq>0 then\n                              proots_upper (fcompose (p \\<circ>\\<^sub>p [:z0, of_real r:]) [:\\<i>,-1:] [:\\<i>,1:]) \n                          else \n                              Code.abort (STR ''proots_ball fails when p=0.'') \n                                (\\<lambda>_. proots_ball p z0 r)\n                        )\" \nproof (cases \"p=0 \\<or> r\\<le>0\")\n  case False\n  have \"proots_ball p z0 r = proots_count (p \\<circ>\\<^sub>p [:z0, of_real r:]) (ball 0 1)\"\n    unfolding proots_ball_def\n    apply (rule proots_uball_eq[THEN arg_cong])\n    using False by auto\n  also have \"... = proots_upper (fcompose (p \\<circ>\\<^sub>p [:z0, of_real r:]) [:\\<i>,-1:] [:\\<i>,1:])\"\n    unfolding proots_upper_def\n    apply (rule proots_ball_plane_eq[THEN arg_cong])\n    using False pcompose_eq_0[of p \"[:z0, of_real r:]\"] \n    by (simp add: pcompose_eq_0)\n  finally show ?thesis using False by auto\nqed (auto simp:proots_ball_def ball_empty)\n\nlemma proots_ball_card_code1[code]:\n  \"proots_ball_card p z0 r = \n                ( if r \\<le> 0 \\<or> p=0 then \n                      0\n                 else \n                    proots_upper_card (fcompose (p \\<circ>\\<^sub>p [:z0, of_real r:]) [:\\<i>,-1:] [:\\<i>,1:]) \n                        )\" \nproof (cases \"p=0 \\<or> r\\<le>0\")\n  case True\n  moreover have ?thesis when \"r\\<le>0\"\n  proof -\n    have \"proots_within p (ball z0 r) = {}\" \n      by (simp add: ball_empty that)\n    then show ?thesis unfolding proots_ball_card_def using that by auto\n  qed\n  moreover have ?thesis when \"r>0\" \"p=0\"\n    unfolding proots_ball_card_def using that infinite_ball[of r z0]\n    by auto\n  ultimately show ?thesis by argo\nnext\n  case False\n  then have \"p\\<noteq>0\" \"r>0\" by auto\n  \n  have \"proots_ball_card p z0 r = card (proots_within (p \\<circ>\\<^sub>p [:z0, of_real r:]) (ball 0 1))\"\n    unfolding proots_ball_card_def\n    by (rule proots_card_uball_eq[OF \\<open>r>0\\<close>, THEN arg_cong])\n  also have \"... = proots_upper_card (fcompose (p \\<circ>\\<^sub>p [:z0, of_real r:]) [:\\<i>,-1:] [:\\<i>,1:])\"\n    unfolding proots_upper_card_def\n    apply (rule proots_card_ball_plane_eq[THEN arg_cong])\n    using False pcompose_eq_0[of p \"[:z0, of_real r:]\"] by (simp add: pcompose_eq_0)\n  finally show ?thesis using False by auto\nqed\n\nsubsection \\<open>Polynomial roots on a circle (sphere)\\<close>\n\n\\<comment> \\<open>Roots counted WITH multiplicity\\<close>\ndefinition proots_sphere::\"complex poly \\<Rightarrow> complex \\<Rightarrow> real \\<Rightarrow> nat\" where\n  \"proots_sphere p z0 r = proots_count p (sphere z0 r)\" \n\n\\<comment> \\<open>Roots counted WITHOUT multiplicity\\<close>\ndefinition proots_sphere_card ::\"complex poly \\<Rightarrow> complex \\<Rightarrow> real \\<Rightarrow> nat\" where\n  \"proots_sphere_card p z0 r = card (proots_within p (sphere z0 r))\"\n\nlemma proots_sphere_card_code1[code]:\n  \"proots_sphere_card p z0 r = \n                ( if r=0 then \n                      (if poly p z0=0 then 1 else 0) \n                  else if r < 0 \\<or> p=0 then \n                      0\n                  else \n                    (if poly p (z0-r) =0 then 1 else 0) +\n                    proots_unbounded_line_card (fcompose (p \\<circ>\\<^sub>p [:z0, of_real r:]) [:\\<i>,-1:] [:\\<i>,1:])\n                      0 1 \n                )\" \nproof -\n  have ?thesis when \"r=0\"\n  proof -\n    have \"proots_within p {z0} = (if poly p z0 = 0 then {z0} else {})\"\n      by auto\n    then show ?thesis unfolding proots_sphere_card_def using that by simp\n  qed\n  moreover have ?thesis when \"r\\<noteq>0\" \"r < 0 \\<or> p=0\"\n  proof -\n    have ?thesis when \"r<0\"\n    proof -\n      have \"proots_within p (sphere z0 r) = {}\" \n        by (auto simp add: ball_empty that)\n      then show ?thesis unfolding proots_sphere_card_def using that by auto\n    qed\n    moreover have ?thesis when \"r>0\" \"p=0\"\n      unfolding proots_sphere_card_def using that infinite_sphere[of r z0]\n      by auto\n    ultimately show ?thesis using that by argo\n  qed\n  moreover have ?thesis when \"r>0\" \"p\\<noteq>0\"\n  proof -\n    define pp where \"pp = p \\<circ>\\<^sub>p [:z0, of_real r:]\" \n    define ppp where \"ppp=fcompose pp [:\\<i>, - 1:] [:\\<i>, 1:]\"\n\n    have \"pp\\<noteq>0\" unfolding pp_def using that pcompose_eq_0 \n      by force\n\n    have \"proots_sphere_card p z0 r = card (proots_within pp (sphere 0 1))\"\n      unfolding proots_sphere_card_def pp_def\n      by (rule proots_card_usphere_eq[OF \\<open>r>0\\<close>, THEN arg_cong])\n    also have \"... = card (proots_within pp {-1} \\<union> proots_within pp (sphere 0 1 - {-1}))\"\n      by (simp add: insert_absorb proots_within_union)\n    also have \"... = card (proots_within pp {-1}) + card (proots_within pp (sphere 0 1 - {-1}))\"\n      apply (rule card_Un_disjoint)\n      using \\<open>pp\\<noteq>0\\<close> by auto\n    also have \"... = card (proots_within pp {-1}) + card (proots_within ppp {x. 0 = Im x})\"\n      using proots_card_sphere_axis_eq[OF \\<open>pp\\<noteq>0\\<close>,folded ppp_def] by simp\n    also have \"... = (if poly p (z0-r) =0 then 1 else 0) + proots_unbounded_line_card ppp 0 1\"\n    proof -\n      have \"proots_within pp {-1} = (if poly p (z0-r) =0 then {-1} else {})\"\n        unfolding pp_def by (auto simp:poly_pcompose)\n      then have \"card (proots_within pp {-1}) = (if poly p (z0-r) =0 then 1 else 0)\"\n        by auto\n      moreover have \"{x. Im x = 0} = unbounded_line 0 1\" \n        unfolding unbounded_line_def \n        apply auto\n        by (metis complex_is_Real_iff of_real_Re of_real_def)\n      then have \"card (proots_within ppp {x. 0 = Im x})\n                        = proots_unbounded_line_card ppp 0 1\"\n        unfolding proots_unbounded_line_card_def by simp\n      ultimately show ?thesis by auto\n    qed\n    finally show ?thesis \n      apply (fold pp_def,fold ppp_def)\n      using that by auto\n  qed\n  ultimately show ?thesis by auto\nqed\n\nsubsection \\<open>Polynomial roots on a closed ball\\<close>\n\n\\<comment> \\<open>Roots counted WITH multiplicity\\<close>\ndefinition proots_cball::\"complex poly \\<Rightarrow> complex \\<Rightarrow> real \\<Rightarrow> nat\" where\n  \"proots_cball p z0 r = proots_count p (cball z0 r)\" \n\n\\<comment> \\<open>Roots counted WITHOUT multiplicity\\<close>\ndefinition proots_cball_card ::\"complex poly \\<Rightarrow> complex \\<Rightarrow> real \\<Rightarrow> nat\" where\n  \"proots_cball_card p z0 r = card (proots_within p (cball z0 r))\"\n\n(*FIXME: this surely can be optimised/refined.*)\nlemma proots_cball_card_code1[code]:\n  \"proots_cball_card p z0 r = \n                ( if r=0 then \n                      (if poly p z0=0 then 1 else 0) \n                  else if r < 0 \\<or> p=0 then \n                      0\n                  else \n                    ( let pp=fcompose (p \\<circ>\\<^sub>p [:z0, of_real r:]) [:\\<i>,-1:] [:\\<i>,1:] \n                      in \n                        (if poly p (z0-r) =0 then 1 else 0) \n                        + proots_unbounded_line_card pp 0 1 \n                        + proots_upper_card pp\n                    )\n                )\"\nproof -\n  have ?thesis when \"r=0\"\n  proof -\n    have \"proots_within p {z0} = (if poly p z0 = 0 then {z0} else {})\"\n      by auto\n    then show ?thesis unfolding proots_cball_card_def using that by simp\n  qed\n  moreover have ?thesis when \"r\\<noteq>0\" \"r < 0 \\<or> p=0\"\n  proof -\n    have ?thesis when \"r<0\"\n    proof -\n      have \"proots_within p (cball z0 r) = {}\" \n        by (auto simp add: ball_empty that)\n      then show ?thesis unfolding proots_cball_card_def using that by auto\n    qed\n    moreover have ?thesis when \"r>0\" \"p=0\"\n      unfolding proots_cball_card_def using that infinite_cball[of r z0]\n      by auto\n    ultimately show ?thesis using that by argo\n  qed\n  moreover have ?thesis when \"p\\<noteq>0\" \"r>0\"\n  proof -\n    define pp where \"pp=fcompose (p \\<circ>\\<^sub>p [:z0, of_real r:]) [:\\<i>,-1:] [:\\<i>,1:]\"\n\n    have \"proots_cball_card p z0 r = card (proots_within p (sphere z0 r) \n                                        \\<union> proots_within p (ball z0 r))\" \n      unfolding proots_cball_card_def \n      apply (simp add:proots_within_union)\n      by (metis Diff_partition cball_diff_sphere sphere_cball)\n    also have \"... = card (proots_within p (sphere z0 r)) + card (proots_within p (ball z0 r))\"\n      apply (rule card_Un_disjoint)\n      using \\<open>p\\<noteq>0\\<close> by auto\n    also have \"... = (if poly p (z0-r) =0 then 1 else 0) + proots_unbounded_line_card pp 0 1 \n                        + proots_upper_card pp\"\n      using proots_sphere_card_code1[of p z0 r,folded pp_def,unfolded proots_sphere_card_def] \n        proots_ball_card_code1[of p z0 r,folded pp_def,unfolded proots_ball_card_def]\n        that\n      by simp\n    finally show ?thesis \n      apply (fold pp_def)\n      using that by auto\n  qed\n  ultimately show ?thesis by 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/Count_Complex_Roots/Count_Circle.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681122619885, "lm_q2_score": 0.8376199633332891, "lm_q1q2_score": 0.7184836947413514}}
{"text": "(*<*)\ntheory Logic\nimports LaTeXsugar\nbegin\n(*>*)\ntext\\<open>\n\\vspace{-5ex}\n\\section{Formulas}\n\nThe core syntax of formulas (\\textit{form} below)\nprovides the standard logical constructs, in decreasing order of precedence:\n\\[\n\\begin{array}{rcl}\n\n\\mathit{form} & ::= &\n  \\<open>(form)\\<close> ~\\mid~\n  \\<^const>\\<open>True\\<close> ~\\mid~\n  \\<^const>\\<open>False\\<close> ~\\mid~\n  \\<^prop>\\<open>term = term\\<close>\\\\\n &\\mid& \\<^prop>\\<open>\\<not> form\\<close>\\index{$HOL4@\\isasymnot} ~\\mid~\n  \\<^prop>\\<open>form \\<and> form\\<close>\\index{$HOL0@\\isasymand} ~\\mid~\n  \\<^prop>\\<open>form \\<or> form\\<close>\\index{$HOL1@\\isasymor} ~\\mid~\n  \\<^prop>\\<open>form \\<longrightarrow> form\\<close>\\index{$HOL2@\\isasymlongrightarrow}\\\\\n &\\mid& \\<^prop>\\<open>\\<forall>x. form\\<close>\\index{$HOL6@\\isasymforall} ~\\mid~  \\<^prop>\\<open>\\<exists>x. form\\<close>\\index{$HOL7@\\isasymexists}\n\\end{array}\n\\]\nTerms are the ones we have seen all along, built from constants, variables,\nfunction application and \\<open>\\<lambda>\\<close>-abstraction, including all the syntactic\nsugar like infix symbols, \\<open>if\\<close>, \\<open>case\\<close>, etc.\n\\begin{warn}\nRemember that formulas are simply terms of type \\<open>bool\\<close>. Hence\n\\<open>=\\<close> also works for formulas. Beware that \\<open>=\\<close> has a higher\nprecedence than the other logical operators. Hence \\<^prop>\\<open>s = t \\<and> A\\<close> means\n\\<open>(s = t) \\<and> A\\<close>, and \\<^prop>\\<open>A\\<and>B = B\\<and>A\\<close> means \\<open>A \\<and> (B = B) \\<and> A\\<close>.\nLogical equivalence can also be written with\n\\<open>\\<longleftrightarrow>\\<close> instead of \\<open>=\\<close>, where \\<open>\\<longleftrightarrow>\\<close> has the same low\nprecedence as \\<open>\\<longrightarrow>\\<close>. Hence \\<open>A \\<and> B \\<longleftrightarrow> B \\<and> A\\<close> really means\n\\<open>(A \\<and> B) \\<longleftrightarrow> (B \\<and> A)\\<close>.\n\\end{warn}\n\\begin{warn}\nQuantifiers need to be enclosed in parentheses if they are nested within\nother constructs (just like \\<open>if\\<close>, \\<open>case\\<close> and \\<open>let\\<close>).\n\\end{warn}\nThe most frequent logical symbols and their ASCII representations are shown\nin Fig.~\\ref{fig:log-symbols}.\n\\begin{figure}\n\\begin{center}\n\\begin{tabular}{l@ {\\qquad}l@ {\\qquad}l}\n\\<open>\\<forall>\\<close> & \\xsymbol{forall} & \\texttt{ALL}\\\\\n\\<open>\\<exists>\\<close> & \\xsymbol{exists} & \\texttt{EX}\\\\\n\\<open>\\<lambda>\\<close> & \\xsymbol{lambda} & \\texttt{\\%}\\\\\n\\<open>\\<longrightarrow>\\<close> & \\texttt{-{\\kern0pt}->}\\\\\n\\<open>\\<longleftrightarrow>\\<close> & \\texttt{<->}\\\\\n\\<open>\\<and>\\<close> & \\texttt{/\\char`\\\\} & \\texttt{\\&}\\\\\n\\<open>\\<or>\\<close> & \\texttt{\\char`\\\\/} & \\texttt{|}\\\\\n\\<open>\\<not>\\<close> & \\xsymbol{not} & \\texttt{\\char`~}\\\\\n\\<open>\\<noteq>\\<close> & \\xsymbol{noteq} & \\texttt{\\char`~=}\n\\end{tabular}\n\\end{center}\n\\caption{Logical symbols and their ASCII forms}\n\\label{fig:log-symbols}\n\\end{figure}\nThe first column shows the symbols, the other columns ASCII representations.\nThe \\texttt{\\char`\\\\}\\texttt{<...>} form is always converted into the symbolic form\nby the Isabelle interfaces, the treatment of the other ASCII forms\ndepends on the interface. The ASCII forms \\texttt{/\\char`\\\\} and\n\\texttt{\\char`\\\\/}\nare special in that they are merely keyboard shortcuts for the interface and\nnot logical symbols by themselves.\n\\begin{warn}\nThe implication \\<open>\\<Longrightarrow>\\<close> is part of the Isabelle framework. It structures\ntheorems and proof states, separating assumptions from conclusions.\nThe implication \\<open>\\<longrightarrow>\\<close> is part of the logic HOL and can occur inside the\nformulas that make up the assumptions and conclusion.\nTheorems should be of the form \\<open>\\<lbrakk> A\\<^sub>1; \\<dots>; A\\<^sub>n \\<rbrakk> \\<Longrightarrow> A\\<close>,\nnot \\<open>A\\<^sub>1 \\<and> \\<dots> \\<and> A\\<^sub>n \\<longrightarrow> A\\<close>. Both are logically equivalent\nbut the first one works better when using the theorem in further proofs.\n\nThe ASCII representation of \\<open>\\<lbrakk>\\<close> and \\<open>\\<rbrakk>\\<close> is \\texttt{[|} and \\texttt{|]}.\n\\end{warn}\n\n\\section{Sets}\n\\label{sec:Sets}\n\nSets of elements of type \\<^typ>\\<open>'a\\<close> have type \\<^typ>\\<open>'a set\\<close>\\index{set@\\<open>set\\<close>}.\nThey can be finite or infinite. Sets come with the usual notation:\n\\begin{itemize}\n\\item \\indexed{\\<^term>\\<open>{}\\<close>}{$IMP042},\\quad \\<open>{e\\<^sub>1,\\<dots>,e\\<^sub>n}\\<close>\n\\item \\<^prop>\\<open>e \\<in> A\\<close>\\index{$HOLSet0@\\isasymin},\\quad \\<^prop>\\<open>A \\<subseteq> B\\<close>\\index{$HOLSet2@\\isasymsubseteq}\n\\item \\<^term>\\<open>A \\<union> B\\<close>\\index{$HOLSet4@\\isasymunion},\\quad \\<^term>\\<open>A \\<inter> B\\<close>\\index{$HOLSet5@\\isasyminter},\\quad \\<^term>\\<open>A - B\\<close>,\\quad \\<^term>\\<open>-A\\<close>\n\\end{itemize}\n(where \\<^term>\\<open>A-B\\<close> and \\<open>-A\\<close> are set difference and complement)\nand much more. \\<^const>\\<open>UNIV\\<close> is the set of all elements of some type.\nSet comprehension\\index{set comprehension} is written\n\\<^term>\\<open>{x. P}\\<close>\\index{$IMP042@\\<^term>\\<open>{x. P}\\<close>} rather than \\<open>{x | P}\\<close>.\n\\begin{warn}\nIn \\<^term>\\<open>{x. P}\\<close> the \\<open>x\\<close> must be a variable. Set comprehension\ninvolving a proper term \\<open>t\\<close> must be written\n\\noquotes{@{term[source] \"{t | x y. P}\"}}\\index{$IMP042@\\<open>{t |x. P}\\<close>},\nwhere \\<open>x y\\<close> are those free variables in \\<open>t\\<close>\nthat occur in \\<open>P\\<close>.\nThis is just a shorthand for \\<^term>\\<open>{v. \\<exists>x y. v = t \\<and> P}\\<close>, where\n\\<open>v\\<close> is a new variable. For example, \\<^term>\\<open>{x+y|x. x \\<in> A}\\<close>\nis short for \\noquotes{@{term[source]\"{v. \\<exists>x. v = x+y \\<and> x \\<in> A}\"}}.\n\\end{warn}\n\nHere are the ASCII representations of the mathematical symbols:\n\\begin{center}\n\\begin{tabular}{l@ {\\quad}l@ {\\quad}l}\n\\<open>\\<in>\\<close> & \\texttt{\\char`\\\\\\char`\\<in>} & \\texttt{:}\\\\\n\\<open>\\<subseteq>\\<close> & \\texttt{\\char`\\\\\\char`\\<subseteq>} & \\texttt{<=}\\\\\n\\<open>\\<union>\\<close> & \\texttt{\\char`\\\\\\char`\\<union>} & \\texttt{Un}\\\\\n\\<open>\\<inter>\\<close> & \\texttt{\\char`\\\\\\char`\\<inter>} & \\texttt{Int}\n\\end{tabular}\n\\end{center}\nSets also allow bounded quantifications \\<^prop>\\<open>\\<forall>x \\<in> A. P\\<close> and\n\\<^prop>\\<open>\\<exists>x \\<in> A. P\\<close>.\n\nFor the more ambitious, there are also \\<open>\\<Union>\\<close>\\index{$HOLSet6@\\isasymUnion}\nand \\<open>\\<Inter>\\<close>\\index{$HOLSet7@\\isasymInter}:\n\\begin{center}\n@{thm Union_eq} \\qquad @{thm Inter_eq}\n\\end{center}\nThe ASCII forms of \\<open>\\<Union>\\<close> are \\texttt{\\char`\\\\\\char`\\<Union>} and \\texttt{Union},\nthose of \\<open>\\<Inter>\\<close> are \\texttt{\\char`\\\\\\char`\\<Inter>} and \\texttt{Inter}.\nThere are also indexed unions and intersections:\n\\begin{center}\n@{thm[eta_contract=false] UNION_eq} \\\\ @{thm[eta_contract=false] INTER_eq}\n\\end{center}\nThe ASCII forms are \\ \\texttt{UN x:A.~B} \\ and \\ \\texttt{INT x:A. B} \\\nwhere \\texttt{x} may occur in \\texttt{B}.\nIf \\texttt{A} is \\texttt{UNIV} you can write \\ \\texttt{UN x.~B} \\ and \\ \\texttt{INT x. B}.\n\nSome other frequently useful functions on sets are the following:\n\\begin{center}\n\\begin{tabular}{l@ {\\quad}l}\n@{const_typ set}\\index{set@\\<^const>\\<open>set\\<close>} & converts a list to the set of its elements\\\\\n@{const_typ finite}\\index{finite@\\<^const>\\<open>finite\\<close>} & is true iff its argument is finite\\\\\n\\noquotes{@{term[source] \"card :: 'a set \\<Rightarrow> nat\"}}\\index{card@\\<^const>\\<open>card\\<close>} & is the cardinality of a finite set\\\\\n & and is \\<open>0\\<close> for all infinite sets\\\\\n@{thm image_def}\\index{$IMP042@\\<^term>\\<open>f ` A\\<close>} & is the image of a function over a set\n\\end{tabular}\n\\end{center}\nSee \\<^cite>\\<open>\"Nipkow-Main\"\\<close> for the wealth of further predefined functions in theory\n\\<^theory>\\<open>Main\\<close>.\n\n\n\\subsection*{Exercises}\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>\nDefine a function \\<open>set ::\\<close> \\<^typ>\\<open>'a tree \\<Rightarrow> 'a set\\<close>\nthat returns the elements in a tree and a function\n\\<open>ord ::\\<close> \\<^typ>\\<open>int tree \\<Rightarrow> bool\\<close>\nthat tests if an \\<^typ>\\<open>int tree\\<close> is ordered.\n\nDefine a function \\<open>ins\\<close> that inserts an element into an ordered \\<^typ>\\<open>int tree\\<close>\nwhile maintaining the order of the tree. If the element is already in the tree, the\nsame tree should be returned. Prove correctness of \\<open>ins\\<close>:\n\\<^prop>\\<open>set(ins x t) = {x} \\<union> set t\\<close> and \\<^prop>\\<open>ord t \\<Longrightarrow> ord(ins i t)\\<close>.\n\\endexercise\n\n\n\\section{Proof Automation}\n\nSo far we have only seen \\<open>simp\\<close> and \\indexed{\\<open>auto\\<close>}{auto}: Both perform\nrewriting, both can also prove linear arithmetic facts (no multiplication),\nand \\<open>auto\\<close> is also able to prove simple logical or set-theoretic goals:\n\\<close>\n\nlemma \"\\<forall>x. \\<exists>y. x = y\"\nby auto\n\nlemma \"A \\<subseteq> B \\<inter> C \\<Longrightarrow> A \\<subseteq> B \\<union> C\"\nby auto\n\ntext\\<open>where\n\\begin{quote}\n\\isacom{by} \\textit{proof-method}\n\\end{quote}\nis short for\n\\begin{quote}\n\\isacom{apply} \\textit{proof-method}\\\\\n\\isacom{done}\n\\end{quote}\nThe key characteristics of both \\<open>simp\\<close> and \\<open>auto\\<close> are\n\\begin{itemize}\n\\item They show you where they got stuck, giving you an idea how to continue.\n\\item They perform the obvious steps but are highly incomplete.\n\\end{itemize}\nA proof method is \\conceptnoidx{complete} if it can prove all true formulas.\nThere is no complete proof method for HOL, not even in theory.\nHence all our proof methods only differ in how incomplete they are.\n\nA proof method that is still incomplete but tries harder than \\<open>auto\\<close> is\n\\indexed{\\<open>fastforce\\<close>}{fastforce}.  It either succeeds or fails, it acts on the first\nsubgoal only, and it can be modified like \\<open>auto\\<close>, e.g.,\nwith \\<open>simp add\\<close>. Here is a typical example of what \\<open>fastforce\\<close>\ncan do:\n\\<close>\n\nlemma \"\\<lbrakk> \\<forall>xs \\<in> A. \\<exists>ys. xs = ys @ ys;  us \\<in> A \\<rbrakk>\n   \\<Longrightarrow> \\<exists>n. length us = n+n\"\nby fastforce\n\ntext\\<open>This lemma is out of reach for \\<open>auto\\<close> because of the\nquantifiers.  Even \\<open>fastforce\\<close> fails when the quantifier structure\nbecomes more complicated. In a few cases, its slow version \\<open>force\\<close>\nsucceeds where \\<open>fastforce\\<close> fails.\n\nThe method of choice for complex logical goals is \\indexed{\\<open>blast\\<close>}{blast}. In the\nfollowing example, \\<open>T\\<close> and \\<open>A\\<close> are two binary predicates. It\nis shown that if \\<open>T\\<close> is total, \\<open>A\\<close> is antisymmetric and \\<open>T\\<close> is\na subset of \\<open>A\\<close>, then \\<open>A\\<close> is a subset of \\<open>T\\<close>:\n\\<close>\n\nlemma\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\ntext\\<open>\nWe leave it to the reader to figure out why this lemma is true.\nMethod \\<open>blast\\<close>\n\\begin{itemize}\n\\item is (in principle) a complete proof procedure for first-order formulas,\n  a fragment of HOL. In practice there is a search bound.\n\\item does no rewriting and knows very little about equality.\n\\item covers logic, sets and relations.\n\\item either succeeds or fails.\n\\end{itemize}\nBecause of its strength in logic and sets and its weakness in equality reasoning, it complements the earlier proof methods.\n\n\n\\subsection{\\concept{Sledgehammer}}\n\nCommand \\isacom{sledgehammer} calls a number of external automatic\ntheorem provers (ATPs) that run for up to 30 seconds searching for a\nproof. Some of these ATPs are part of the Isabelle installation, others are\nqueried over the internet. If successful, a proof command is generated and can\nbe inserted into your proof.  The biggest win of \\isacom{sledgehammer} is\nthat it will take into account the whole lemma library and you do not need to\nfeed in any lemma explicitly. For example,\\<close>\n\nlemma \"\\<lbrakk> xs @ ys = ys @ xs;  length xs = length ys \\<rbrakk> \\<Longrightarrow> xs = ys\"\n\ntxt\\<open>cannot be solved by any of the standard proof methods, but\n\\isacom{sledgehammer} finds the following proof:\\<close>\n\nby (metis append_eq_conv_conj)\n\ntext\\<open>We do not explain how the proof was found but what this command\nmeans. For a start, Isabelle does not trust external tools (and in particular\nnot the translations from Isabelle's logic to those tools!)\nand insists on a proof that it can check. This is what \\indexed{\\<open>metis\\<close>}{metis} does.\nIt is given a list of lemmas and tries to find a proof using just those lemmas\n(and pure logic). In contrast to using \\<open>simp\\<close> and friends who know a lot of\nlemmas already, using \\<open>metis\\<close> manually is tedious because one has\nto find all the relevant lemmas first. But that is precisely what\n\\isacom{sledgehammer} does for us.\nIn this case lemma @{thm[source]append_eq_conv_conj} alone suffices:\n@{thm[display] append_eq_conv_conj}\nWe leave it to the reader to figure out why this lemma suffices to prove\nthe above lemma, even without any knowledge of what the functions \\<^const>\\<open>take\\<close>\nand \\<^const>\\<open>drop\\<close> do. Keep in mind that the variables in the two lemmas\nare independent of each other, despite the same names, and that you can\nsubstitute arbitrary values for the free variables in a lemma.\n\nJust as for the other proof methods we have seen, there is no guarantee that\n\\isacom{sledgehammer} will find a proof if it exists. Nor is\n\\isacom{sledgehammer} superior to the other proof methods.  They are\nincomparable. Therefore it is recommended to apply \\<open>simp\\<close> or \\<open>auto\\<close> before invoking \\isacom{sledgehammer} on what is left.\n\n\\subsection{Arithmetic}\n\nBy arithmetic formulas we mean formulas involving variables, numbers, \\<open>+\\<close>, \\<open>-\\<close>, \\<open>=\\<close>, \\<open><\\<close>, \\<open>\\<le>\\<close> and the usual logical\nconnectives \\<open>\\<not>\\<close>, \\<open>\\<and>\\<close>, \\<open>\\<or>\\<close>, \\<open>\\<longrightarrow>\\<close>,\n\\<open>\\<longleftrightarrow>\\<close>. Strictly speaking, this is known as \\concept{linear arithmetic}\nbecause it does not involve multiplication, although multiplication with\nnumbers, e.g., \\<open>2*n\\<close>, is allowed. Such formulas can be proved by\n\\indexed{\\<open>arith\\<close>}{arith}:\n\\<close>\n\nlemma \"\\<lbrakk> (a::nat) \\<le> x + b; 2*x < c \\<rbrakk> \\<Longrightarrow> 2*a + 1 \\<le> 2*b + c\"\nby arith\n\ntext\\<open>In fact, \\<open>auto\\<close> and \\<open>simp\\<close> can prove many linear\narithmetic formulas already, like the one above, by calling a weak but fast\nversion of \\<open>arith\\<close>. Hence it is usually not necessary to invoke\n\\<open>arith\\<close> explicitly.\n\nThe above example involves natural numbers, but integers (type \\<^typ>\\<open>int\\<close>)\nand real numbers (type \\<open>real\\<close>) are supported as well. As are a number\nof further operators like \\<^const>\\<open>min\\<close> and \\<^const>\\<open>max\\<close>. On \\<^typ>\\<open>nat\\<close> and\n\\<^typ>\\<open>int\\<close>, \\<open>arith\\<close> can even prove theorems with quantifiers in them,\nbut we will not enlarge on that here.\n\n\n\\subsection{Trying Them All}\n\nIf you want to try all of the above automatic proof methods you simply type\n\\begin{isabelle}\n\\isacom{try}\n\\end{isabelle}\nThere is also a lightweight variant \\isacom{try0} that does not call\nsledgehammer. If desired, specific simplification and introduction rules\ncan be added:\n\\begin{isabelle}\n\\isacom{try0} \\<open>simp: \\<dots> intro: \\<dots>\\<close>\n\\end{isabelle}\n\n\\section{Single Step Proofs}\n\nAlthough automation is nice, it often fails, at least initially, and you need\nto find out why. When \\<open>fastforce\\<close> or \\<open>blast\\<close> simply fail, you have\nno clue why. At this point, the stepwise\napplication of proof rules may be necessary. For example, if \\<open>blast\\<close>\nfails on \\<^prop>\\<open>A \\<and> B\\<close>, you want to attack the two\nconjuncts \\<open>A\\<close> and \\<open>B\\<close> separately. This can\nbe achieved by applying \\emph{conjunction introduction}\n\\[ @{thm[mode=Rule,show_question_marks]conjI}\\ \\<open>conjI\\<close>\n\\]\nto the proof state. We will now examine the details of this process.\n\n\\subsection{Instantiating Unknowns}\n\nWe had briefly mentioned earlier that after proving some theorem,\nIsabelle replaces all free variables \\<open>x\\<close> by so called \\conceptidx{unknowns}{unknown}\n\\<open>?x\\<close>. We can see this clearly in rule @{thm[source] conjI}.\nThese unknowns can later be instantiated explicitly or implicitly:\n\\begin{itemize}\n\\item By hand, using \\indexed{\\<open>of\\<close>}{of}.\nThe expression \\<open>conjI[of \"a=b\" \"False\"]\\<close>\ninstantiates the unknowns in @{thm[source] conjI} from left to right with the\ntwo formulas \\<open>a=b\\<close> and \\<open>False\\<close>, yielding the rule\n@{thm[display,mode=Rule,margin=100]conjI[of \"a=b\" False]}\n\nIn general, \\<open>th[of string\\<^sub>1 \\<dots> string\\<^sub>n]\\<close> instantiates\nthe unknowns in the theorem \\<open>th\\<close> from left to right with the terms\n\\<open>string\\<^sub>1\\<close> to \\<open>string\\<^sub>n\\<close>.\n\n\\item By unification. \\conceptidx{Unification}{unification} is the process of making two\nterms syntactically equal by suitable instantiations of unknowns. For example,\nunifying \\<open>?P \\<and> ?Q\\<close> with \\mbox{\\<^prop>\\<open>a=b \\<and> False\\<close>} instantiates\n\\<open>?P\\<close> with \\<^prop>\\<open>a=b\\<close> and \\<open>?Q\\<close> with \\<^prop>\\<open>False\\<close>.\n\\end{itemize}\nWe need not instantiate all unknowns. If we want to skip a particular one we\ncan write \\<open>_\\<close> instead, for example \\<open>conjI[of _ \"False\"]\\<close>.\nUnknowns can also be instantiated by name using \\indexed{\\<open>where\\<close>}{where}, for example\n\\<open>conjI[where ?P = \"a=b\"\\<close> \\isacom{and} \\<open>?Q = \"False\"]\\<close>.\n\n\n\\subsection{Rule Application}\n\n\\conceptidx{Rule application}{rule application} means applying a rule backwards to a proof state.\nFor example, applying rule @{thm[source]conjI} to a proof state\n\\begin{quote}\n\\<open>1.  \\<dots>  \\<Longrightarrow> A \\<and> B\\<close>\n\\end{quote}\nresults in two subgoals, one for each premise of @{thm[source]conjI}:\n\\begin{quote}\n\\<open>1.  \\<dots>  \\<Longrightarrow> A\\<close>\\\\\n\\<open>2.  \\<dots>  \\<Longrightarrow> B\\<close>\n\\end{quote}\nIn general, the application of a rule \\<open>\\<lbrakk> A\\<^sub>1; \\<dots>; A\\<^sub>n \\<rbrakk> \\<Longrightarrow> A\\<close>\nto a subgoal \\mbox{\\<open>\\<dots> \\<Longrightarrow> C\\<close>} proceeds in two steps:\n\\begin{enumerate}\n\\item\nUnify \\<open>A\\<close> and \\<open>C\\<close>, thus instantiating the unknowns in the rule.\n\\item\nReplace the subgoal \\<open>C\\<close> with \\<open>n\\<close> new subgoals \\<open>A\\<^sub>1\\<close> to \\<open>A\\<^sub>n\\<close>.\n\\end{enumerate}\nThis is the command to apply rule \\<open>xyz\\<close>:\n\\begin{quote}\n\\isacom{apply}\\<open>(rule xyz)\\<close>\\index{rule@\\<open>rule\\<close>}\n\\end{quote}\nThis is also called \\concept{backchaining} with rule \\<open>xyz\\<close>.\n\n\\subsection{Introduction Rules}\n\nConjunction introduction (@{thm[source] conjI}) is one example of a whole\nclass of rules known as \\conceptidx{introduction rules}{introduction rule}. They explain under which\npremises some logical construct can be introduced. Here are some further\nuseful introduction rules:\n\\[\n\\inferrule*[right=\\mbox{\\<open>impI\\<close>}]{\\mbox{\\<open>?P \\<Longrightarrow> ?Q\\<close>}}{\\mbox{\\<open>?P \\<longrightarrow> ?Q\\<close>}}\n\\qquad\n\\inferrule*[right=\\mbox{\\<open>allI\\<close>}]{\\mbox{\\<open>\\<And>x. ?P x\\<close>}}{\\mbox{\\<open>\\<forall>x. ?P x\\<close>}}\n\\]\n\\[\n\\inferrule*[right=\\mbox{\\<open>iffI\\<close>}]{\\mbox{\\<open>?P \\<Longrightarrow> ?Q\\<close>} \\\\ \\mbox{\\<open>?Q \\<Longrightarrow> ?P\\<close>}}\n  {\\mbox{\\<open>?P = ?Q\\<close>}}\n\\]\nThese rules are part of the logical system of \\concept{natural deduction}\n(e.g., \\<^cite>\\<open>HuthRyan\\<close>). Although we intentionally de-emphasize the basic rules\nof logic in favour of automatic proof methods that allow you to take bigger\nsteps, these rules are helpful in locating where and why automation fails.\nWhen applied backwards, these rules decompose the goal:\n\\begin{itemize}\n\\item @{thm[source] conjI} and @{thm[source]iffI} split the goal into two subgoals,\n\\item @{thm[source] impI} moves the left-hand side of a HOL implication into the list of assumptions,\n\\item and @{thm[source] allI} removes a \\<open>\\<forall>\\<close> by turning the quantified variable into a fixed local variable of the subgoal.\n\\end{itemize}\nIsabelle knows about these and a number of other introduction rules.\nThe command\n\\begin{quote}\n\\isacom{apply} \\<open>rule\\<close>\\index{rule@\\<open>rule\\<close>}\n\\end{quote}\nautomatically selects the appropriate rule for the current subgoal.\n\nYou can also turn your own theorems into introduction rules by giving them\nthe \\indexed{\\<open>intro\\<close>}{intro} attribute, analogous to the \\<open>simp\\<close> attribute.  In\nthat case \\<open>blast\\<close>, \\<open>fastforce\\<close> and (to a limited extent) \\<open>auto\\<close> will automatically backchain with those theorems. The \\<open>intro\\<close>\nattribute should be used with care because it increases the search space and\ncan lead to nontermination.  Sometimes it is better to use it only in\nspecific calls of \\<open>blast\\<close> and friends. For example,\n@{thm[source] le_trans}, transitivity of \\<open>\\<le>\\<close> on type \\<^typ>\\<open>nat\\<close>,\nis not an introduction rule by default because of the disastrous effect\non the search space, but can be useful in specific situations:\n\\<close>\n\nlemma \"\\<lbrakk> (a::nat) \\<le> b; b \\<le> c; c \\<le> d; d \\<le> e \\<rbrakk> \\<Longrightarrow> a \\<le> e\"\nby(blast intro: le_trans)\n\ntext\\<open>\nOf course this is just an example and could be proved by \\<open>arith\\<close>, too.\n\n\\subsection{Forward Proof}\n\\label{sec:forward-proof}\n\nForward proof means deriving new theorems from old theorems. We have already\nseen a very simple form of forward proof: the \\<open>of\\<close> operator for\ninstantiating unknowns in a theorem. The big brother of \\<open>of\\<close> is\n\\indexed{\\<open>OF\\<close>}{OF} for applying one theorem to others. Given a theorem \\<^prop>\\<open>A \\<Longrightarrow> B\\<close> called\n\\<open>r\\<close> and a theorem \\<open>A'\\<close> called \\<open>r'\\<close>, the theorem \\<open>r[OF r']\\<close> is the result of applying \\<open>r\\<close> to \\<open>r'\\<close>, where \\<open>r\\<close> should be viewed as a function taking a theorem \\<open>A\\<close> and returning\n\\<open>B\\<close>.  More precisely, \\<open>A\\<close> and \\<open>A'\\<close> are unified, thus\ninstantiating the unknowns in \\<open>B\\<close>, and the result is the instantiated\n\\<open>B\\<close>. Of course, unification may also fail.\n\\begin{warn}\nApplication of rules to other rules operates in the forward direction: from\nthe premises to the conclusion of the rule; application of rules to proof\nstates operates in the backward direction, from the conclusion to the\npremises.\n\\end{warn}\n\nIn general \\<open>r\\<close> can be of the form \\<open>\\<lbrakk> A\\<^sub>1; \\<dots>; A\\<^sub>n \\<rbrakk> \\<Longrightarrow> A\\<close>\nand there can be multiple argument theorems \\<open>r\\<^sub>1\\<close> to \\<open>r\\<^sub>m\\<close>\n(with \\<open>m \\<le> n\\<close>), in which case \\<open>r[OF r\\<^sub>1 \\<dots> r\\<^sub>m]\\<close> is obtained\nby unifying and thus proving \\<open>A\\<^sub>i\\<close> with \\<open>r\\<^sub>i\\<close>, \\<open>i = 1\\<dots>m\\<close>.\nHere is an example, where @{thm[source]refl} is the theorem\n@{thm[show_question_marks] refl}:\n\\<close>\n\nthm conjI[OF refl[of \"a\"] refl[of \"b\"]]\n\ntext\\<open>yields the theorem @{thm conjI[OF refl[of \"a\"] refl[of \"b\"]]}.\nThe command \\isacom{thm} merely displays the result.\n\nForward reasoning also makes sense in connection with proof states.\nTherefore \\<open>blast\\<close>, \\<open>fastforce\\<close> and \\<open>auto\\<close> support a modifier\n\\<open>dest\\<close> which instructs the proof method to use certain rules in a\nforward fashion. If \\<open>r\\<close> is of the form \\mbox{\\<open>A \\<Longrightarrow> B\\<close>}, the modifier\n\\mbox{\\<open>dest: r\\<close>}\\index{dest@\\<open>dest:\\<close>}\nallows proof search to reason forward with \\<open>r\\<close>, i.e.,\nto replace an assumption \\<open>A'\\<close>, where \\<open>A'\\<close> unifies with \\<open>A\\<close>,\nwith the correspondingly instantiated \\<open>B\\<close>. For example, @{thm[source,show_question_marks] Suc_leD} is the theorem \\mbox{@{thm Suc_leD}}, which works well for forward reasoning:\n\\<close>\n\nlemma \"Suc(Suc(Suc a)) \\<le> b \\<Longrightarrow> a \\<le> b\"\nby(blast dest: Suc_leD)\n\ntext\\<open>In this particular example we could have backchained with\n@{thm[source] Suc_leD}, too, but because the premise is more complicated than the conclusion this can easily lead to nontermination.\n\n%\\subsection{Finding Theorems}\n%\n%Command \\isacom{find{\\isacharunderscorekeyword}theorems} searches for specific theorems in the current\n%theory. Search criteria include pattern matching on terms and on names.\n%For details see the Isabelle/Isar Reference Manual~\\<^cite>\\<open>IsarRef\\<close>.\n%\\bigskip\n\n\\begin{warn}\nTo ease readability we will drop the question marks\nin front of unknowns from now on.\n\\end{warn}\n\n\n\\section{Inductive Definitions}\n\\label{sec:inductive-defs}\\index{inductive definition|(}\n\nInductive definitions are the third important definition facility, after\ndatatypes and recursive function.\n\\ifsem\nIn fact, they are the key construct in the\ndefinition of operational semantics in the second part of the book.\n\\fi\n\n\\subsection{An Example: Even Numbers}\n\\label{sec:Logic:even}\n\nHere is a simple example of an inductively defined predicate:\n\\begin{itemize}\n\\item 0 is even\n\\item If $n$ is even, so is $n+2$.\n\\end{itemize}\nThe operative word ``inductive'' means that these are the only even numbers.\nIn Isabelle we give the two rules the names \\<open>ev0\\<close> and \\<open>evSS\\<close>\nand write\n\\<close>\n\ninductive ev :: \"nat \\<Rightarrow> bool\" where\nev0:    \"ev 0\" |\nevSS:  (*<*)\"ev n \\<Longrightarrow> ev (Suc(Suc n))\"(*>*)\ntext_raw\\<open>@{prop[source]\"ev n \\<Longrightarrow> ev (n + 2)\"}\\<close>\n\ntext\\<open>To get used to inductive definitions, we will first prove a few\nproperties of \\<^const>\\<open>ev\\<close> informally before we descend to the Isabelle level.\n\nHow do we prove that some number is even, e.g., \\<^prop>\\<open>ev 4\\<close>? Simply by combining the defining rules for \\<^const>\\<open>ev\\<close>:\n\\begin{quote}\n\\<open>ev 0 \\<Longrightarrow> ev (0 + 2) \\<Longrightarrow> ev((0 + 2) + 2) = ev 4\\<close>\n\\end{quote}\n\n\\subsubsection{Rule Induction}\\index{rule induction|(}\n\nShowing that all even numbers have some property is more complicated.  For\nexample, let us prove that the inductive definition of even numbers agrees\nwith the following recursive one:\\<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>We prove \\<^prop>\\<open>ev m \\<Longrightarrow> evn m\\<close>.  That is, we\nassume \\<^prop>\\<open>ev m\\<close> and by induction on the form of its derivation\nprove \\<^prop>\\<open>evn m\\<close>. There are two cases corresponding to the two rules\nfor \\<^const>\\<open>ev\\<close>:\n\\begin{description}\n\\item[Case @{thm[source]ev0}:]\n \\<^prop>\\<open>ev m\\<close> was derived by rule \\<^prop>\\<open>ev 0\\<close>: \\\\\n \\<open>\\<Longrightarrow>\\<close> \\<^prop>\\<open>m=(0::nat)\\<close> \\<open>\\<Longrightarrow>\\<close> \\<open>evn m = evn 0 = True\\<close>\n\\item[Case @{thm[source]evSS}:]\n \\<^prop>\\<open>ev m\\<close> was derived by rule \\<^prop>\\<open>ev n \\<Longrightarrow> ev(n+2)\\<close>: \\\\\n\\<open>\\<Longrightarrow>\\<close> \\<^prop>\\<open>m=n+(2::nat)\\<close> and by induction hypothesis \\<^prop>\\<open>evn n\\<close>\\\\\n\\<open>\\<Longrightarrow>\\<close> \\<open>evn m = evn(n + 2) = evn n = True\\<close>\n\\end{description}\n\nWhat we have just seen is a special case of \\concept{rule induction}.\nRule induction applies to propositions of this form\n\\begin{quote}\n\\<^prop>\\<open>ev n \\<Longrightarrow> P n\\<close>\n\\end{quote}\nThat is, we want to prove a property \\<^prop>\\<open>P n\\<close>\nfor all even \\<open>n\\<close>. But if we assume \\<^prop>\\<open>ev n\\<close>, then there must be\nsome derivation of this assumption using the two defining rules for\n\\<^const>\\<open>ev\\<close>. That is, we must prove\n\\begin{description}\n\\item[Case @{thm[source]ev0}:] \\<^prop>\\<open>P(0::nat)\\<close>\n\\item[Case @{thm[source]evSS}:] \\<^prop>\\<open>\\<lbrakk> ev n; P n \\<rbrakk> \\<Longrightarrow> P(n + 2::nat)\\<close>\n\\end{description}\nThe corresponding rule is called @{thm[source] ev.induct} and looks like this:\n\\[\n\\inferrule{\n\\mbox{@{thm (prem 1) ev.induct[of \"n\"]}}\\\\\n\\mbox{@{thm (prem 2) ev.induct}}\\\\\n\\mbox{\\<^prop>\\<open>!!n. \\<lbrakk> ev n; P n \\<rbrakk> \\<Longrightarrow> P(n+2)\\<close>}}\n{\\mbox{@{thm (concl) ev.induct[of \"n\"]}}}\n\\]\nThe first premise \\<^prop>\\<open>ev n\\<close> enforces that this rule can only be applied\nin situations where we know that \\<open>n\\<close> is even.\n\nNote that in the induction step we may not just assume \\<^prop>\\<open>P n\\<close> but also\n\\mbox{\\<^prop>\\<open>ev n\\<close>}, which is simply the premise of rule @{thm[source]\nevSS}.  Here is an example where the local assumption \\<^prop>\\<open>ev n\\<close> comes in\nhandy: we prove \\<^prop>\\<open>ev m \\<Longrightarrow> ev(m - 2)\\<close> by induction on \\<^prop>\\<open>ev m\\<close>.\nCase @{thm[source]ev0} requires us to prove \\<^prop>\\<open>ev(0 - 2)\\<close>, which follows\nfrom \\<^prop>\\<open>ev 0\\<close> because \\<^prop>\\<open>0 - 2 = (0::nat)\\<close> on type \\<^typ>\\<open>nat\\<close>. In\ncase @{thm[source]evSS} we have \\mbox{\\<^prop>\\<open>m = n+(2::nat)\\<close>} and may assume\n\\<^prop>\\<open>ev n\\<close>, which implies \\<^prop>\\<open>ev (m - 2)\\<close> because \\<open>m - 2 = (n +\n2) - 2 = n\\<close>. We did not need the induction hypothesis at all for this proof (it\nis just a case analysis of which rule was used) but having \\<^prop>\\<open>ev n\\<close>\nat our disposal in case @{thm[source]evSS} was essential.\nThis case analysis of rules is also called ``rule inversion''\nand is discussed in more detail in \\autoref{ch:Isar}.\n\n\\subsubsection{In Isabelle}\n\nLet us now recast the above informal proofs in Isabelle. For a start,\nwe use \\<^const>\\<open>Suc\\<close> terms instead of numerals in rule @{thm[source]evSS}:\n@{thm[display] evSS}\nThis avoids the difficulty of unifying \\<open>n+2\\<close> with some numeral,\nwhich is not automatic.\n\nThe simplest way to prove \\<^prop>\\<open>ev(Suc(Suc(Suc(Suc 0))))\\<close> is in a forward\ndirection: \\<open>evSS[OF evSS[OF ev0]]\\<close> yields the theorem @{thm evSS[OF\nevSS[OF ev0]]}. Alternatively, you can also prove it as a lemma in backwards\nfashion. Although this is more verbose, it allows us to demonstrate how each\nrule application changes the proof state:\\<close>\n\nlemma \"ev(Suc(Suc(Suc(Suc 0))))\"\ntxt\\<open>\n@{subgoals[display,indent=0,goals_limit=1]}\n\\<close>\napply(rule evSS)\ntxt\\<open>\n@{subgoals[display,indent=0,goals_limit=1]}\n\\<close>\napply(rule evSS)\ntxt\\<open>\n@{subgoals[display,indent=0,goals_limit=1]}\n\\<close>\napply(rule ev0)\ndone\n\ntext\\<open>\\indent\nRule induction is applied by giving the induction rule explicitly via the\n\\<open>rule:\\<close> modifier:\\index{inductionrule@\\<open>induction ... rule:\\<close>}\\<close>\n\nlemma \"ev m \\<Longrightarrow> evn m\"\napply(induction rule: ev.induct)\nby(simp_all)\n\ntext\\<open>Both cases are automatic. Note that if there are multiple assumptions\nof the form \\<^prop>\\<open>ev t\\<close>, method \\<open>induction\\<close> will induct on the leftmost\none.\n\nAs a bonus, we also prove the remaining direction of the equivalence of\n\\<^const>\\<open>ev\\<close> and \\<^const>\\<open>evn\\<close>:\n\\<close>\n\nlemma \"evn n \\<Longrightarrow> ev n\"\napply(induction n rule: evn.induct)\n\ntxt\\<open>This is a proof by computation induction on \\<open>n\\<close> (see\n\\autoref{sec:recursive-funs}) that sets up three subgoals corresponding to\nthe three equations for \\<^const>\\<open>evn\\<close>:\n@{subgoals[display,indent=0]}\nThe first and third subgoals follow with @{thm[source]ev0} and @{thm[source]evSS}, and the second subgoal is trivially true because \\<^prop>\\<open>evn(Suc 0)\\<close> is \\<^const>\\<open>False\\<close>:\n\\<close>\n\nby (simp_all add: ev0 evSS)\n\ntext\\<open>The rules for \\<^const>\\<open>ev\\<close> make perfect simplification and introduction\nrules because their premises are always smaller than the conclusion. It\nmakes sense to turn them into simplification and introduction rules\npermanently, to enhance proof automation. They are named @{thm[source] ev.intros}\n\\index{intros@\\<open>.intros\\<close>} by Isabelle:\\<close>\n\ndeclare ev.intros[simp,intro]\n\ntext\\<open>The rules of an inductive definition are not simplification rules by\ndefault because, in contrast to recursive functions, there is no termination\nrequirement for inductive definitions.\n\n\\subsubsection{Inductive Versus Recursive}\n\nWe have seen two definitions of the notion of evenness, an inductive and a\nrecursive one. Which one is better? Much of the time, the recursive one is\nmore convenient: it allows us to do rewriting in the middle of terms, and it\nexpresses both the positive information (which numbers are even) and the\nnegative information (which numbers are not even) directly. An inductive\ndefinition only expresses the positive information directly. The negative\ninformation, for example, that \\<open>1\\<close> is not even, has to be proved from\nit (by induction or rule inversion). On the other hand, rule induction is\ntailor-made for proving \\mbox{\\<^prop>\\<open>ev n \\<Longrightarrow> P n\\<close>} because it only asks you\nto prove the positive cases. In the proof of \\<^prop>\\<open>evn n \\<Longrightarrow> P n\\<close> by\ncomputation induction via @{thm[source]evn.induct}, we are also presented\nwith the trivial negative cases. If you want the convenience of both\nrewriting and rule induction, you can make two definitions and show their\nequivalence (as above) or make one definition and prove additional properties\nfrom it, for example rule induction from computation induction.\n\nBut many concepts do not admit a recursive definition at all because there is\nno datatype for the recursion (for example, the transitive closure of a\nrelation), or the recursion would not terminate (for example,\nan interpreter for a programming language). Even if there is a recursive\ndefinition, if we are only interested in the positive information, the\ninductive definition may be much simpler.\n\n\\subsection{The Reflexive Transitive Closure}\n\\label{sec:star}\n\nEvenness is really more conveniently expressed recursively than inductively.\nAs a second and very typical example of an inductive definition we define the\nreflexive transitive closure.\n\\ifsem\nIt will also be an important building block for\nsome of the semantics considered in the second part of the book.\n\\fi\n\nThe reflexive transitive closure, called \\<open>star\\<close> below, is a function\nthat maps a binary predicate to another binary predicate: if \\<open>r\\<close> is of\ntype \\<open>\\<tau> \\<Rightarrow> \\<tau> \\<Rightarrow> bool\\<close> then \\<^term>\\<open>star r\\<close> is again of type \\<open>\\<tau> \\<Rightarrow>\n\\<tau> \\<Rightarrow> bool\\<close>, and \\<^prop>\\<open>star r x y\\<close> means that \\<open>x\\<close> and \\<open>y\\<close> are in\nthe relation \\<^term>\\<open>star r\\<close>. Think \\<^term>\\<open>r\\<^sup>*\\<close> when you see \\<^term>\\<open>star\nr\\<close>, because \\<open>star r\\<close> is meant to be the reflexive transitive closure.\nThat is, \\<^prop>\\<open>star r x y\\<close> is meant to be true if from \\<open>x\\<close> we can\nreach \\<open>y\\<close> in finitely many \\<open>r\\<close> steps. This concept is naturally\ndefined inductively:\\<close>\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>The base case @{thm[source] refl} is reflexivity: \\<^term>\\<open>x=y\\<close>. The\nstep case @{thm[source]step} combines an \\<open>r\\<close> step (from \\<open>x\\<close> to\n\\<open>y\\<close>) and a \\<^term>\\<open>star r\\<close> step (from \\<open>y\\<close> to \\<open>z\\<close>) into a\n\\<^term>\\<open>star r\\<close> step (from \\<open>x\\<close> to \\<open>z\\<close>).\nThe ``\\isacom{for}~\\<open>r\\<close>'' in the header is merely a hint to Isabelle\nthat \\<open>r\\<close> is a fixed parameter of \\<^const>\\<open>star\\<close>, in contrast to the\nfurther parameters of \\<^const>\\<open>star\\<close>, which change. As a result, Isabelle\ngenerates a simpler induction rule.\n\nBy definition \\<^term>\\<open>star r\\<close> is reflexive. It is also transitive, but we\nneed rule induction to prove that:\\<close>\n\nlemma star_trans: \"star r x y \\<Longrightarrow> star r y z \\<Longrightarrow> star r x z\"\napply(induction rule: star.induct)\n(*<*)\ndefer\napply(rename_tac u x y)\ndefer\n(*>*)\ntxt\\<open>The induction is over \\<^prop>\\<open>star r x y\\<close> (the first matching assumption)\nand we try to prove \\mbox{\\<^prop>\\<open>star r y z \\<Longrightarrow> star r x z\\<close>},\nwhich we abbreviate by \\<^prop>\\<open>P x y\\<close>. These are our two subgoals:\n@{subgoals[display,indent=0]}\nThe first one is \\<^prop>\\<open>P x x\\<close>, the result of case @{thm[source]refl},\nand it is trivial:\\index{assumption@\\<open>assumption\\<close>}\n\\<close>\napply(assumption)\ntxt\\<open>Let us examine subgoal \\<open>2\\<close>, case @{thm[source] step}.\nAssumptions \\<^prop>\\<open>r u x\\<close> and \\mbox{\\<^prop>\\<open>star r x y\\<close>}\nare the premises of rule @{thm[source]step}.\nAssumption \\<^prop>\\<open>star r y z \\<Longrightarrow> star r x z\\<close> is \\mbox{\\<^prop>\\<open>P x y\\<close>},\nthe IH coming from \\<^prop>\\<open>star r x y\\<close>. We have to prove \\<^prop>\\<open>P u y\\<close>,\nwhich we do by assuming \\<^prop>\\<open>star r y z\\<close> and proving \\<^prop>\\<open>star r u z\\<close>.\nThe proof itself is straightforward: from \\mbox{\\<^prop>\\<open>star r y z\\<close>} the IH\nleads to \\<^prop>\\<open>star r x z\\<close> which, together with \\<^prop>\\<open>r u x\\<close>,\nleads to \\mbox{\\<^prop>\\<open>star r u z\\<close>} via rule @{thm[source]step}:\n\\<close>\napply(metis step)\ndone\n\ntext\\<open>\\index{rule induction|)}\n\n\\subsection{The General Case}\n\nInductive definitions have approximately the following general form:\n\\begin{quote}\n\\isacom{inductive} \\<open>I :: \"\\<tau> \\<Rightarrow> bool\"\\<close> \\isacom{where}\n\\end{quote}\nfollowed by a sequence of (possibly named) rules of the form\n\\begin{quote}\n\\<open>\\<lbrakk> I a\\<^sub>1; \\<dots>; I a\\<^sub>n \\<rbrakk> \\<Longrightarrow> I a\\<close>\n\\end{quote}\nseparated by \\<open>|\\<close>. As usual, \\<open>n\\<close> can be 0.\nThe corresponding rule induction principle\n\\<open>I.induct\\<close> applies to propositions of the form\n\\begin{quote}\n\\<^prop>\\<open>I x \\<Longrightarrow> P x\\<close>\n\\end{quote}\nwhere \\<open>P\\<close> may itself be a chain of implications.\n\\begin{warn}\nRule induction is always on the leftmost premise of the goal.\nHence \\<open>I x\\<close> must be the first premise.\n\\end{warn}\nProving \\<^prop>\\<open>I x \\<Longrightarrow> P x\\<close> by rule induction means proving\nfor every rule of \\<open>I\\<close> that \\<open>P\\<close> is invariant:\n\\begin{quote}\n\\<open>\\<lbrakk> I a\\<^sub>1; P a\\<^sub>1; \\<dots>; I a\\<^sub>n; P a\\<^sub>n \\<rbrakk> \\<Longrightarrow> P a\\<close>\n\\end{quote}\n\nThe above format for inductive definitions is simplified in a number of\nrespects. \\<open>I\\<close> can have any number of arguments and each rule can have\nadditional premises not involving \\<open>I\\<close>, so-called \\conceptidx{side\nconditions}{side condition}. In rule inductions, these side conditions appear as additional\nassumptions. The \\isacom{for} clause seen in the definition of the reflexive\ntransitive closure simplifies the induction rule.\n\\index{inductive definition|)}\n\n\\subsection*{Exercises}\n\n\\begin{exercise}\nFormalize the following definition of palindromes\n\\begin{itemize}\n\\item The empty list and a singleton list are palindromes.\n\\item If \\<open>xs\\<close> is a palindrome, so is \\<^term>\\<open>a # xs @ [a]\\<close>.\n\\end{itemize}\nas an inductive predicate \\<open>palindrome ::\\<close> \\<^typ>\\<open>'a list \\<Rightarrow> bool\\<close>\nand prove that \\<^prop>\\<open>rev xs = xs\\<close> if \\<open>xs\\<close> is a palindrome.\n\\end{exercise}\n\n\\exercise\nWe could also have defined \\<^const>\\<open>star\\<close> 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 \\<open>r\\<close> step is performed after rather than before the \\<open>star'\\<close>\nsteps. Prove \\<^prop>\\<open>star' r x y \\<Longrightarrow> star r x y\\<close> and\n\\<^prop>\\<open>star r x y \\<Longrightarrow> star' r x y\\<close>. You may need lemmas.\nNote that rule induction fails\nif the assumption about the inductive predicate is not the first assumption.\n\\endexercise\n\n\\begin{exercise}\\label{exe:iter}\nAnalogous to \\<^const>\\<open>star\\<close>, give an inductive definition of the \\<open>n\\<close>-fold iteration\nof a relation \\<open>r\\<close>: \\<^term>\\<open>iter r n x y\\<close> should hold if there are \\<open>x\\<^sub>0\\<close>, \\dots, \\<open>x\\<^sub>n\\<close>\nsuch that \\<^prop>\\<open>x = x\\<^sub>0\\<close>, \\<^prop>\\<open>x\\<^sub>n = y\\<close> and \\<open>r x\\<^bsub>i\\<^esub> x\\<^bsub>i+1\\<^esub>\\<close> for\nall \\<^prop>\\<open>i < n\\<close>. Correct and prove the following claim:\n\\<^prop>\\<open>star r x y \\<Longrightarrow> iter r n x y\\<close>.\n\\end{exercise}\n\n\\begin{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)$ means that $w$ is in the language generated by $A$.\nFor example, the production $S \\to a S b$ can be viewed as the implication\n\\<^prop>\\<open>S w \\<Longrightarrow> S (a # w @ [b])\\<close> where \\<open>a\\<close> and \\<open>b\\<close> are terminal symbols,\ni.e., elements of some alphabet. The alphabet can be defined like this:\n\\isacom{datatype} \\<open>alpha = a | b | \\<dots>\\<close>\n\nDefine the two grammars (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\\]\nas two inductive predicates.\nIf you think of \\<open>a\\<close> and \\<open>b\\<close> as ``\\<open>(\\<close>'' and  ``\\<open>)\\<close>'',\nthe grammar defines strings of balanced parentheses.\nProve \\<^prop>\\<open>T w \\<Longrightarrow> S w\\<close> and \\mbox{\\<^prop>\\<open>S w \\<Longrightarrow> T w\\<close>} separately and conclude\n\\<^prop>\\<open>S w = T w\\<close>.\n\\end{exercise}\n\n\\ifsem\n\\begin{exercise}\nIn \\autoref{sec:AExp} we defined a recursive evaluation function\n\\<open>aval :: aexp \\<Rightarrow> state \\<Rightarrow> val\\<close>.\nDefine an inductive evaluation predicate\n\\<open>aval_rel :: aexp \\<Rightarrow> state \\<Rightarrow> val \\<Rightarrow> bool\\<close>\nand prove that it agrees with the recursive function:\n\\<^prop>\\<open>aval_rel a s v \\<Longrightarrow> aval a s = v\\<close>, \n\\<^prop>\\<open>aval a s = v \\<Longrightarrow> aval_rel a s v\\<close> and thus\n\\noquotes{@{prop [source] \"aval_rel a s v \\<longleftrightarrow> aval a s = v\"}}.\n\\end{exercise}\n\n\\begin{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\\<open>ok :: nat \\<Rightarrow> instr list \\<Rightarrow> nat \\<Rightarrow> bool\\<close>\nsuch that \\<open>ok n is n'\\<close> means that with any initial stack of length\n\\<open>n\\<close> the instructions \\<open>is\\<close> can be executed\nwithout stack underflow and that the final stack has length \\<open>n'\\<close>.\nProve that \\<open>ok\\<close> correctly computes the final stack size\n@{prop[display] \"\\<lbrakk>ok n is n'; length stk = n\\<rbrakk> \\<Longrightarrow> length (exec is s stk) = n'\"}\nand that instruction sequences generated by \\<open>comp\\<close>\ncannot cause stack underflow: \\ \\<open>ok n (comp a) ?\\<close> \\ for\nsome suitable value of \\<open>?\\<close>.\n\\end{exercise}\n\\fi\n\\<close>\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/Prog_Prove/Logic.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681158979307, "lm_q2_score": 0.837619959279793, "lm_q1q2_score": 0.7184836943099295}}
{"text": "theory RegEx     \n  imports Regular\nbegin\n\n\nsection \"Regular Expressions\"\n\ndatatype 'a::linorder regex = None  | Const \"'a word\" \n  | Union \"'a regex\" \"'a regex\" (infixr \"\\<squnion>\" 65)\n  | Concat \"'a regex\" \"'a regex\"  (infixr \"\\<odot>\" 65)\n  | Star \"'a regex\"  (\"_\\<^sup>\\<star>\")\n  | Inter \"'a regex\" \"'a regex\" (infixr \"\\<sqinter>\" 65)\n  | Any (\"?\")\n  | Comp \"'a regex\" (\"\\<inverse>\")\n  | Diff \"'a regex\" \"'a regex\" (\"\\\\\")\n  | Range \"'a\" \"'a\" (\"[__]\")\n\nprimrec lang:: \"'a::linorder regex \\<Rightarrow> 'a word set\"  where\n  \"lang None = {}\"|\n  \"lang Any = {w. (length w) = 1}\" | \n  \"lang (Const w) = {w}\" |\n  \"lang (Union r1 r2) = (lang r1) Un (lang r2)\" |\n  \"lang (Concat r1 r2) = concat (lang r1) (lang r2)\"|\n  \"lang (Star r) = star (lang r)\" |\n  \"lang (Range l u) = {(v#\\<epsilon>)|v. l \\<le> v \\<and> v \\<le> u}\"|\n  \"lang (Inter r1 r2) = (lang r1) \\<inter> (lang r2)\"|\n  \"lang (Comp r) = -(lang r)\"|\n  \"lang (Diff r1 r2) = (lang r1) - (lang r2)\"\n\nlemma star_any_is_univ: \"w \\<in> lang (Star Any)\"\n  by (metis lang.simps(2) lang.simps(6) singleton_set star_of_singletons_is_univ)\n\n\nsection \"Construction functions that perform simple normalisation\"\n\nfun re_union::\"'a::linorder regex \\<Rightarrow> 'a regex \\<Rightarrow> 'a regex\" where \n  \"re_union r None = r\"|\n  \"re_union None r = r\"|\n  \"re_union (Const a) (Const b) = (if a = b then (Const a) else (Union (Const a) (Const b)))\"|\n  \"re_union r e = Union r e\"\n\nlemma re_union_correct:\"(lang (re_union r e)) = (lang (Union r e))\"\n  by (cases \\<open>(r, e)\\<close> rule: re_union.cases) auto\n\nfun re_concat:: \"'a::linorder regex \\<Rightarrow> 'a regex \\<Rightarrow> 'a regex\" where\n  \"re_concat r (Const \\<epsilon>) = r\"|\n  \"re_concat (Const \\<epsilon>) r = r\"|\n  \"re_concat None r = None\"|\n  \"re_concat r None = None\"|\n  \"re_concat r e = Concat r e\"\n\nlemma re_concat_correct:\"(lang (re_concat r e)) = (lang (Concat r e))\"\n  by (cases \\<open>(r, e)\\<close> rule: re_concat.cases) (auto simp add: concat_def)\n\nfun re_star:: \"'a::linorder regex \\<Rightarrow> 'a regex\" where\n  \"re_star (Const \\<epsilon>) = (Const \\<epsilon>)\"|\n  \"re_star None = (Const \\<epsilon>)\"|\n  \"re_star r = Star r\"\n\nlemma re_star_correct:\"(lang (re_star r)) = (lang (Star r))\"\n  by (cases r rule: re_star.cases) (auto simp add: star_of_epsilon star_of_empty)\n\nfun re_plus::\"'a::linorder regex \\<Rightarrow> 'a regex\" where \n  \"re_plus r = re_concat r (re_star r)\"\n\nfun re_inter:: \"'a::linorder regex \\<Rightarrow> 'a::linorder regex \\<Rightarrow> 'a regex\" where\n  \"re_inter None r = None\"|\n  \"re_inter r None = None\"|\n  \"re_inter (Const a) (Const b) = (if a = b then (Const a) else None)\"|\n  \"re_inter r e = Inter r e\" \n\nlemma re_inter_correct: \"lang (re_inter r1 r2) = lang (Inter r1 r2)\"\n  by (cases \\<open>(r1, r2)\\<close> rule: re_inter.cases) auto\n\nfun re_range::  \"'a::linorder \\<Rightarrow> 'a::linorder \\<Rightarrow> 'a regex\" where\n  \"re_range l u = (if (l < u) then (Range l u) else (if l = u then (Const (l#\\<epsilon>)) else None))\"\n\nlemma re_range_correct: \"lang (re_range l u) = (lang (Range l u))\"\n  by auto\n\nfun re_comp:: \"'a::linorder regex \\<Rightarrow> 'a regex\" where\n  \"re_comp None = Star Any\"|\n  \"re_comp r = Comp r\"\n\nlemma re_comp_correct: \"lang (re_comp r) = (lang (Comp r))\"\n  using star_any_is_univ by (cases r) auto\n\nfun re_diff:: \"'a::linorder regex \\<Rightarrow> 'a regex \\<Rightarrow> 'a regex\" where\n  \"re_diff None _ = None\"|\n  \"re_diff r None = r\"|\n  \"re_diff r1 r2  = Diff r1 r2\"\n\nlemma re_diff_correct: \"lang (re_diff r1 r2) = lang (Diff r1 r2)\" \n  by (cases \\<open>(r1, r2)\\<close> rule: re_diff.cases) auto\n\nprimrec re_pow::\"'a::linorder regex \\<Rightarrow> nat \\<Rightarrow> 'a regex\" where\n  \"re_pow r 0 = (Const \\<epsilon>)\"|\n  \"re_pow r (Suc n) = re_concat r (re_pow r n)\"\n\nfun re_loop::\"'a::linorder regex \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> 'a regex\" where\n  \"re_loop r (Suc a) 0 = None\"|\n  \"re_loop r 0 0 = Const \\<epsilon>\"|\n  \"re_loop r a (Suc n) = (if a \\<le> (Suc n) then re_union (re_pow r (Suc n)) (re_loop r a n) else None)\"\n\nlemma re_loop_iff1: \n  assumes \"a \\<le> b\"\n  shows \"w \\<in> lang (re_loop r a b) \\<longleftrightarrow> (\\<exists>x. a \\<le> x \\<and> x \\<le> b \\<and> w \\<in> lang (re_pow r x))\"\n  using assms\n  apply (induct b)\n  apply (auto simp add: UnE le_SucI not0_implies_Suc not_less_eq_eq re_union_correct)\n  apply (metis empty_iff lang.simps(1) le_Suc_eq re_loop.elims)\n  using antisym not_less_eq_eq by fastforce\n\nlemma re_loop_None_if:\"a > b \\<Longrightarrow> re_loop r a b = None\"\n  by (cases \\<open>(r, a, b)\\<close> rule: re_loop.cases) auto\n\n(* A language is nullable if it accepts the empty word*)\nprimrec nullable:: \"'a::linorder regex \\<Rightarrow> bool\" \n  where\n    \"nullable None = False\" |\n    \"nullable Any = False\" |\n    \"nullable (Const w) = (w = \\<epsilon>)\" |\n    \"nullable (Union r1 r2) = ((nullable r1) \\<or> (nullable r2))\" |\n    \"nullable (Inter r1 r2) = ((nullable r1) \\<and> (nullable r2))\"|\n    \"nullable (Concat r1 r2) = ((nullable r1) \\<and> (nullable r2))\" |\n    \"nullable (Star r) = True\"|\n    \"nullable (Range _ _) = False\"|\n    \"nullable (Comp r) = (\\<not> nullable r)\"|\n    \"nullable (Diff r1 r2) = ((nullable r1) \\<and> (\\<not> nullable r2))\"\n\nlemma nullability: \"nullable r \\<longleftrightarrow> \\<epsilon> \\<in> (lang r)\"\n  by (induct r) (auto simp add: concat_def)\n\n(* abbreviation vu:: \"'a regex \\<Rightarrow> 'a regex\" where \"vu r \\<equiv> (if (nullable r) then (Const \\<epsilon>) else None)\" *)\n\nprimrec vu:: \"'a::linorder regex \\<Rightarrow> 'a regex\" where\n  \"vu (Const w) = (if w = \\<epsilon> then (Const w) else None)\" |\n  \"vu None = None\" |\n  \"vu (Union r1 r2) = re_union (vu r1) (vu r2)\" |\n  \"vu (Inter r1 r2) = re_inter (vu r1) (vu r2)\" |\n  \"vu (Concat r1 r2) = re_concat (vu r1) (vu r2)\" |\n  \"vu (Star r) = (Const \\<epsilon>)\" |\n  \"vu Any = None\"|\n  \"vu (Range _ _) = None\"|\n  \"vu (Comp r) = (if (nullable r) then None else (Const \\<epsilon>))\"|\n  \"vu (Diff r1 r2) = (if (nullable r1 \\<and> \\<not> nullable r2) then (Const \\<epsilon>) else None)\"\n\n(* Derivatives of regular languages *)\n\nfun rderiv :: \"'a::linorder \\<Rightarrow> 'a::linorder regex \\<Rightarrow> 'a::linorder regex\" where\n  \"rderiv c None = None\" |\n  \"rderiv c Any = (Const \\<epsilon>)\"|\n  \"rderiv c (Const (a#w)) = (if a = c then (Const w) else None)\" |\n  \"rderiv c (Const \\<epsilon>) = None\"|\n  \"rderiv c (Union r1 r2) = re_union (rderiv c r1) (rderiv c r2)\" |\n  \"rderiv c (Inter r1 r2) = re_inter (rderiv c r1) (rderiv c r2)\"|\n  \"rderiv c (Concat r1 r2) = (re_union (re_concat (rderiv c r1) r2)  (re_concat (vu r1) (rderiv c r2)))\" |\n  \"rderiv c (Star r) = re_concat (rderiv c r) (re_star r)\"|\n  \"rderiv c (Range l u) = (if (l\\<le>c \\<and> c \\<le> u) then (Const \\<epsilon>) else None)\"|\n  \"rderiv c (Comp r) = re_comp (rderiv c r)\"|\n  \"rderiv c (Diff r1 r2) = re_diff (rderiv c r1) (rderiv c r2)\"\n\nlemma \"c > u \\<Longrightarrow> rderiv c (Range l u) = None\"\n  by auto\n\n\n\nlemma [simp]: \"l \\<le> c \\<Longrightarrow> c \\<le> u \\<Longrightarrow> rderiv c (Range l u) = (Const \\<epsilon>)\"\n  by auto\n\nlemma vu_null_iff: \"lang (vu r) = null (lang r)\"\n  unfolding Regular.null_def \n  by (induct r) (simp_all add: re_union_correct re_concat_correct re_inter_correct re_star_correct \n      concat_def re_diff_correct  nullability)\n\nlemma rderiv_correct: \"lang (rderiv a r) = deriv a (lang r)\"\nproof(induction r arbitrary: a)\n  case None\n  then show ?case \n    by (simp add: deriv_empty)\nnext\n  case (Const x)  \n  then show ?case \n  proof(cases x)\n    case Nil\n    then show ?thesis \n      by (simp add: deriv_def)\n  next\n    case (Cons a list)\n    then show ?thesis \n      by (simp add: deriv_const)\n  qed\nnext\n  case (Union r1 r2)\n  then show ?case \n    by (simp add: deriv_union re_union_correct)\nnext\n  case (Concat r1 r2)\n  then show ?case  \n    by (simp add: deriv_concat vu_null_iff re_concat_correct re_union_correct)\nnext\n  case (Inter r1 r2)\n  then show ?case \n    by (auto simp add: deriv_inter re_inter_correct)\nnext\n  case (Star r)\n  then show ?case \n    by (simp add: deriv_star re_star_correct re_union_correct re_concat_correct)\nnext\n  case Any\n  then show ?case \n    by (auto simp add: deriv_def)\nnext\n  case (Range l u)\n  then show ?case \n    by(auto simp add: deriv_def)\nnext \n  case (Comp r)\n  then show ?case\n    by (auto simp add: deriv_def re_comp_correct)\nnext \n  case (Diff r1 r2)\n  then show ?case \n    by (auto simp add: deriv_def re_diff_correct)\nqed\n\nprimrec rderivw:: \"'a::linorder word \\<Rightarrow> 'a regex \\<Rightarrow> 'a regex\" where\n  \"rderivw \\<epsilon> r = r\" |\n  \"rderivw (a#u) r = rderivw u (rderiv a r)\"\n\nlemma derivw_nullable_contains: \n  assumes \"nullable (rderivw w r)\"\n  shows \"w \\<in> (lang r)\"\n  using assms\nproof (induct w arbitrary: r)\n  case Nil\n  then show ?case \n    by (auto simp add: nullability)\nnext\n  case (Cons a w)\n  then have \"\\<epsilon> \\<in> lang (rderivw w (rderiv a r))\"\n    by (auto simp add: nullability)\n  then have \"nullable (rderivw w (rderiv a r))\"\n    by (simp add: nullability)\n  then have \"a # w \\<in> lang r\"\n    using Cons(1) by (metis deriv_correct rderiv_correct)\n  then show ?case  \n    by auto\nqed\n\nlemma contains_derivw_nullable:\n  assumes \"w \\<in> (lang r)\"\n  shows \"nullable (rderivw w r)\"\n  using assms\nproof (induct w arbitrary: r)\n  case Nil\n  then show ?case \n    by (auto simp add: nullability)\nnext\n  case (Cons a w)\n  have \"a # w \\<in> lang r\"\n    using Cons by (auto simp add: nullability)\n  then have \"\\<epsilon> \\<in> lang (rderivw w (rderiv a r))\"\n    using Cons(1) by (auto simp add: nullability deriv_correct rderiv_correct)\n  then show ?case \n    by (auto simp add: nullability)\nqed\n\ntheorem derivative_correctness: \"w \\<in> (lang r) \\<longleftrightarrow> nullable (rderivw w r)\"\n  by (auto simp add: contains_derivw_nullable derivw_nullable_contains)\n\nend", "meta": {"author": "formalsmt", "repo": "isabelle_smt", "sha": "e3f990aa6548c67d438a5c0e2cd808760d347d83", "save_path": "github-repos/isabelle/formalsmt-isabelle_smt", "path": "github-repos/isabelle/formalsmt-isabelle_smt/isabelle_smt-e3f990aa6548c67d438a5c0e2cd808760d347d83/strings/RegEx.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8577681122619885, "lm_q2_score": 0.837619961306541, "lm_q1q2_score": 0.7184836930028715}}
{"text": "theory Exe3p1\n  imports Main\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 n r) = {n} \\<union> set l \\<union> set r\"\n\nfun ord :: \"int tree \\<Rightarrow> bool\" where\n\"ord Tip = True\" |\n\"ord (Node l n r) = (\\<not>(\\<exists>x. x \\<in> set l \\<and> x > n) \\<and> \\<not>(\\<exists>x. x \\<in> set r \\<and> x < n))\"\n\nfun ins :: \"int \\<Rightarrow> int tree \\<Rightarrow> int tree\" where\n\"ins x Tip = Node Tip x Tip\" |\n\"ins x (Node l n r) = (\n  if x = n then (Node l n r)\n           else (if x < n then (Node (ins x l) n r)\n                          else (Node l n (ins x r))))\"\n\nlemma ins_correctness_1 [simp]: \"set (ins x t) = {x} \\<union> set t\"\n  apply(induction t)\n   apply(auto)\n  done\n\nlemma ins_correctness_2: \"ord t \\<Longrightarrow> ord (ins i t)\"\n  apply(induction t)\n   apply(auto)\n  done\n\nthm conjI\n\nthm conjI[of \"a=b\" \"False\"]\n\nthm conjI[OF refl[of \"a\"] refl[of \"b\"]]\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/Exe3p1.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9241418199787566, "lm_q2_score": 0.7772998508568416, "lm_q1q2_score": 0.7183352988400576}}
{"text": "section \\<open>Basic automata\\<close>\n\ntheory Automata\nimports Main\nbegin\n\ntext \\<open>We consider automata defined by a type @{text \"'state\"} (corresponding to a non-empty set)\nof states, a type @{text \"'act\"} of actions, a type @{text \"'out\"} of outputs, a starting state\n@{text s0}, a step function @{text step}, and an output function @{text out}.\\footnote{The\nIsabelle command @{text locale} opens a new context where we can fix variables and/or define\nassumptions. We can use these variables and assumptions inside the context, and we can reuse\nand extend the context later by referring to its name (in this case @{text \"Automaton\"}).\nWe can also @{emph \\<open>instantiate\\<close>} a context (using the command @{text \\<open>interpretation\\<close>},\nor @{emph \\<open>sublocale\\<close>} if we are inside another context): We then have to prove that the\nassumptions hold, and afterwards, we are allowed to use the definitions and theorems from\ninside the context.}\\<close>\n\nlocale Automaton =\n  fixes s0 :: \"'state\"\n    and step :: \"'state \\<Rightarrow> 'act \\<Rightarrow> 'state\"\n    and out :: \"'state \\<Rightarrow> 'act \\<Rightarrow> 'out\"\nbegin\n\ntext \\<open>We define @{text \"run s \\<alpha>\"} so that it returns the state we reach when performing the\naction sequence @{text \\<alpha>}, beginning in the state @{text s}.\\<close>\n\ntext \\<open>The function @{text run} is defined recursively. In Isabelle, the empty list is denoted\nas @{text \"[]\"}, the addition of an @{emph \\<open>element\\<close>} @{text a} at the beginning of a list\n@{text \\<alpha>} is denoted as @{text \"a # \\<alpha>\"}, and the concatenation of two @{emph \\<open>lists\\<close>}\n@{text \\<alpha>} and @{text \\<beta>} is denoted as @{text \"\\<alpha> @ \\<beta>\"}.\\<close>\n\nfun run :: \"'state \\<Rightarrow> 'act list \\<Rightarrow> 'state\" where\n  \"run s [] = s\"\n| \"run s (a # \\<alpha>) = run (step s a) \\<alpha>\"\n\ntext \\<open>After writing down definitions, Isabelle allows us to prove properties of them. For example,\nwe can (almost\\footnote{We tell Isabelle to perform induction over @{text \\<alpha>}. Moreover, we\ntell Isabelle to generalize the induction hypothesis to arbitrary states @{text s}, because\nwe need to apply the induction hypothesis not for the original @{text s}, but for the successor\nstate reached after performing the first action of the trace.}) automatically prove that running\nthe concatenation of two action sequences \\<open>\\<alpha>\\<close> and \\<open>\\<beta>\\<close> corresponds to running \\<open>\\<alpha>\\<close> from the initial\nstate, and then running \\<open>\\<beta>\\<close> from the final state of \\<open>\\<alpha>\\<close>.\\<close>\n\nlemma run_append: \"run s (\\<alpha> @ \\<beta>) = run (run s \\<alpha>) \\<beta>\"\nby (induction \\<alpha> arbitrary: s) auto\n\ntext \\<open>Note that free variables in lemmas are implicitly universally quantified, i.e.\\ this lemma\nholds @{emph \\<open>for all\\<close>} \\<open>s\\<close>, \\<open>\\<alpha>\\<close>, and \\<open>\\<beta>\\<close>.\\<close>\n\nend\n\nend\n", "meta": {"author": "bauereiss", "repo": "fosad", "sha": "d782ced2ea86a4f6fa3bbe7732f2a2840fce591a", "save_path": "github-repos/isabelle/bauereiss-fosad", "path": "github-repos/isabelle/bauereiss-fosad/fosad-d782ced2ea86a4f6fa3bbe7732f2a2840fce591a/Policies/Noninterference/Automata.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8267118026095991, "lm_q2_score": 0.868826784729373, "lm_q1q2_score": 0.7182693573591221}}
{"text": "(*  Title:      HOL/Cardinals/Fun_More.thy\n    Author:     Andrei Popescu, TU Muenchen\n    Copyright   2012\n\nMore on injections, bijections and inverses.\n*)\n\nsection \\<open>More on Injections, Bijections and Inverses\\<close>\n\ntheory Fun_More\nimports Main\nbegin\n\nsubsection \\<open>Purely functional properties\\<close>\n\n(* unused *)\n(*1*)lemma notIn_Un_bij_betw2:\nassumes NIN: \"b \\<notin> A\" and NIN': \"b' \\<notin> A'\" and\n        BIJ: \"bij_betw f A A'\"\nshows \"bij_betw f (A \\<union> {b}) (A' \\<union> {b'}) = (f b = b')\"\nproof\n  assume \"f b = b'\"\n  thus \"bij_betw f (A \\<union> {b}) (A' \\<union> {b'})\"\n  using assms notIn_Un_bij_betw[of b A f A'] by auto\nnext\n  assume *: \"bij_betw f (A \\<union> {b}) (A' \\<union> {b'})\"\n  hence \"f b \\<in> A' \\<union> {b'}\"\n  unfolding bij_betw_def by auto\n  moreover\n  {assume \"f b \\<in> A'\"\n   then obtain b1 where 1: \"b1 \\<in> A\" and 2: \"f b1 = f b\" using BIJ\n   by (auto simp add: bij_betw_def)\n   hence \"b = b1\" using *\n   by (auto simp add: bij_betw_def inj_on_def)\n   with 1 NIN have False by auto\n  }\n  ultimately show \"f b = b'\" by blast\nqed\n\n(* unused *)\n(*1*)lemma bij_betw_ball:\nassumes BIJ: \"bij_betw f A B\"\nshows \"(\\<forall>b \\<in> B. phi b) = (\\<forall>a \\<in> A. phi(f a))\"\nusing assms unfolding bij_betw_def inj_on_def by blast\n\n(* unused *)\n(*1*)lemma bij_betw_diff_singl:\nassumes BIJ: \"bij_betw f A A'\" and IN: \"a \\<in> A\"\nshows \"bij_betw f (A - {a}) (A' - {f a})\"\nproof-\n  let ?B = \"A - {a}\"   let ?B' = \"A' - {f a}\"\n  have \"f a \\<in> A'\" using IN BIJ unfolding bij_betw_def by blast\n  hence \"a \\<notin> ?B \\<and> f a \\<notin> ?B' \\<and> A = ?B \\<union> {a} \\<and> A' = ?B' \\<union> {f a}\"\n  using IN by blast\n  thus ?thesis using notIn_Un_bij_betw3[of a ?B f ?B'] BIJ by simp\nqed\n\n\nsubsection \\<open>Properties involving finite and infinite sets\\<close>\n\n(* unused *)\n(*1*)lemma bij_betw_inv_into_RIGHT:\nassumes BIJ: \"bij_betw f A A'\" and SUB: \"B' \\<le> A'\"\nshows \"f `((inv_into A f)`B') = B'\"\nusing assms\nproof(auto simp add: bij_betw_inv_into_right)\n  let ?f' = \"(inv_into A f)\"\n  fix a' assume *: \"a' \\<in> B'\"\n  hence \"a' \\<in> A'\" using SUB by auto\n  hence \"a' = f (?f' a')\"\n  using BIJ by (auto simp add: bij_betw_inv_into_right)\n  thus \"a' \\<in> f ` (?f' ` B')\" using * by blast\nqed\n\n(* unused *)\n(*1*)lemma bij_betw_inv_into_RIGHT_LEFT:\nassumes BIJ: \"bij_betw f A A'\" and SUB: \"B' \\<le> A'\" and\n        IM: \"(inv_into A f) ` B' = B\"\nshows \"f ` B = B'\"\nproof-\n  have \"f`((inv_into A f)` B') = B'\"\n  using assms bij_betw_inv_into_RIGHT[of f A A' B'] by auto\n  thus ?thesis using IM by auto\nqed\n\n(* unused *)\n(*2*)lemma bij_betw_inv_into_twice:\nassumes \"bij_betw f A A'\"\nshows \"\\<forall>a \\<in> A. inv_into A' (inv_into A f) a = f a\"\nproof\n  let ?f' = \"inv_into A f\"   let ?f'' = \"inv_into A' ?f'\"\n  have 1: \"bij_betw ?f' A' A\" using assms\n  by (auto simp add: bij_betw_inv_into)\n  fix a assume *: \"a \\<in> A\"\n  then obtain a' where 2: \"a' \\<in> A'\" and 3: \"?f' a' = a\"\n  using 1 unfolding bij_betw_def by force\n  hence \"?f'' a = a'\"\n  using * 1 3 by (auto simp add: bij_betw_inv_into_left)\n  moreover have \"f a = a'\" using assms 2 3\n  by (auto simp add: bij_betw_inv_into_right)\n  ultimately show \"?f'' a = f a\" by simp\nqed\n\n\nsubsection \\<open>Properties involving Hilbert choice\\<close>\n\n(*1*)lemma bij_betw_inv_into_LEFT:\nassumes BIJ: \"bij_betw f A A'\" and SUB: \"B \\<le> A\"\nshows \"(inv_into A f)`(f ` B) = B\"\nusing assms unfolding bij_betw_def using inv_into_image_cancel by force\n\n(*1*)lemma bij_betw_inv_into_LEFT_RIGHT:\nassumes BIJ: \"bij_betw f A A'\" and SUB: \"B \\<le> A\" and\n        IM: \"f ` B = B'\"\nshows \"(inv_into A f) ` B' = B\"\nusing assms bij_betw_inv_into_LEFT[of f A A' B] by fast\n\n\nsubsection \\<open>Other facts\\<close>\n\n(*3*)lemma atLeastLessThan_injective:\nassumes \"{0 ..< m::nat} = {0 ..< n}\"\nshows \"m = n\"\nproof-\n  {assume \"m < n\"\n   hence \"m \\<in> {0 ..< n}\" by auto\n   hence \"{0 ..< m} < {0 ..< n}\" by auto\n   hence False using assms by blast\n  }\n  moreover\n  {assume \"n < m\"\n   hence \"n \\<in> {0 ..< m}\" by auto\n   hence \"{0 ..< n} < {0 ..< m}\" by auto\n   hence False using assms by blast\n  }\n  ultimately show ?thesis by force\nqed\n\n(*2*)lemma atLeastLessThan_injective2:\n\"bij_betw f {0 ..< m::nat} {0 ..< n} \\<Longrightarrow> m = n\"\nusing finite_atLeastLessThan[of m] finite_atLeastLessThan[of n]\n      card_atLeastLessThan[of m] card_atLeastLessThan[of n]\n      bij_betw_iff_card[of \"{0 ..< m}\" \"{0 ..< n}\"] by auto\n\n(*2*)lemma atLeastLessThan_less_eq:\n\"({0..<m} \\<le> {0..<n}) = ((m::nat) \\<le> n)\"\nunfolding ivl_subset by arith\n\n(*2*)lemma atLeastLessThan_less_eq2:\nassumes \"inj_on f {0..<(m::nat)} \\<and> f ` {0..<m} \\<le> {0..<n}\"\nshows \"m \\<le> n\"\nusing assms\nusing finite_atLeastLessThan[of m] finite_atLeastLessThan[of n]\n      card_atLeastLessThan[of m] card_atLeastLessThan[of n]\n      card_inj_on_le[of f \"{0 ..< m}\" \"{0 ..< n}\"] by fastforce\n\n(* unused *)\n(*2*)lemma atLeastLessThan_less_eq3:\n\"(\\<exists>f. inj_on f {0..<(m::nat)} \\<and> f ` {0..<m} \\<le> {0..<n}) = (m \\<le> n)\"\nusing atLeastLessThan_less_eq2\nproof(auto)\n  assume \"m \\<le> n\"\n  hence \"inj_on id {0..<m} \\<and> id ` {0..<m} \\<subseteq> {0..<n}\" unfolding inj_on_def by force\n  thus \"\\<exists>f. inj_on f {0..<m} \\<and> f ` {0..<m} \\<subseteq> {0..<n}\" by blast\nqed\n\n(* unused *)\n(*3*)lemma atLeastLessThan_less:\n\"({0..<m} < {0..<n}) = ((m::nat) < n)\"\nproof-\n  have \"({0..<m} < {0..<n}) = ({0..<m} \\<le> {0..<n} \\<and> {0..<m} ~= {0..<n})\"\n  using subset_iff_psubset_eq by blast\n  also have \"\\<dots> = (m \\<le> n \\<and> m ~= n)\"\n  using atLeastLessThan_less_eq atLeastLessThan_injective by blast\n  also have \"\\<dots> = (m < n)\" by auto\n  finally show ?thesis .\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/Cardinals/Fun_More.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267830311354, "lm_q2_score": 0.8267118026095992, "lm_q1q2_score": 0.718269355955169}}
{"text": "(*  Title:      HOL/Examples/Cantor.thy\n    Author:     Makarius\n*)\n\nsection \\<open>Cantor's Theorem\\<close>\n\ntheory Cantor\n  imports MainRLT\nbegin\n\nsubsection \\<open>Mathematical statement and proof\\<close>\n\ntext \\<open>\n  Cantor's Theorem states that there is no surjection from\n  a set to its powerset.  The proof works by diagonalization.  E.g.\\ see\n  \\<^item> \\<^url>\\<open>http://mathworld.wolfram.com/CantorDiagonalMethod.html\\<close>\n  \\<^item> \\<^url>\\<open>https://en.wikipedia.org/wiki/Cantor's_diagonal_argument\\<close>\n\\<close>\n\ntheorem Cantor: \"\\<nexists>f :: 'a \\<Rightarrow> 'a set. \\<forall>A. \\<exists>x. A = f x\"\nproof\n  assume \"\\<exists>f :: 'a \\<Rightarrow> 'a set. \\<forall>A. \\<exists>x. A = f x\"\n  then obtain f :: \"'a \\<Rightarrow> 'a set\" where *: \"\\<forall>A. \\<exists>x. A = f x\" ..\n  let ?D = \"{x. x \\<notin> f x}\"\n  from * obtain a where \"?D = f a\" by blast\n  moreover have \"a \\<in> ?D \\<longleftrightarrow> a \\<notin> f a\" by blast\n  ultimately show False by blast\nqed\n\n\nsubsection \\<open>Automated proofs\\<close>\n\ntext \\<open>\n  These automated proofs are much shorter, but lack information why and how it\n  works.\n\\<close>\n\ntheorem \"\\<nexists>f :: 'a \\<Rightarrow> 'a set. \\<forall>A. \\<exists>x. f x = A\"\n  by best\n\ntheorem \"\\<nexists>f :: 'a \\<Rightarrow> 'a set. \\<forall>A. \\<exists>x. f x = A\"\n  by force\n\n\nsubsection \\<open>Elementary version in higher-order predicate logic\\<close>\n\ntext \\<open>\n  The subsequent formulation bypasses set notation of HOL; it uses elementary\n  \\<open>\\<lambda>\\<close>-calculus and predicate logic, with standard introduction and elimination\n  rules. This also shows that the proof does not require classical reasoning.\n\\<close>\n\nlemma iff_contradiction:\n  assumes *: \"\\<not> A \\<longleftrightarrow> A\"\n  shows False\nproof (rule notE)\n  show \"\\<not> A\"\n  proof\n    assume A\n    with * have \"\\<not> A\" ..\n    from this and \\<open>A\\<close> show False ..\n  qed\n  with * show A ..\nqed\n\ntheorem Cantor': \"\\<nexists>f :: 'a \\<Rightarrow> 'a \\<Rightarrow> bool. \\<forall>A. \\<exists>x. A = f x\"\nproof\n  assume \"\\<exists>f :: 'a \\<Rightarrow> 'a \\<Rightarrow> bool. \\<forall>A. \\<exists>x. A = f x\"\n  then obtain f :: \"'a \\<Rightarrow> 'a \\<Rightarrow> bool\" where *: \"\\<forall>A. \\<exists>x. A = f x\" ..\n  let ?D = \"\\<lambda>x. \\<not> f x x\"\n  from * have \"\\<exists>x. ?D = f x\" ..\n  then obtain a where \"?D = f a\" ..\n  then have \"?D a \\<longleftrightarrow> f a a\" by (rule arg_cong)\n  then have \"\\<not> f a a \\<longleftrightarrow> f a a\" .\n  then show False by (rule iff_contradiction)\nqed\n\n\nsubsection \\<open>Classic Isabelle/HOL example\\<close>\n\ntext \\<open>\n  The following treatment of Cantor's Theorem follows the classic example from\n  the early 1990s, e.g.\\ see the file \\<^verbatim>\\<open>92/HOL/ex/set.ML\\<close> in\n  Isabelle92 or @{cite \\<open>\\S18.7\\<close> \"paulson-isa-book\"}. The old tactic scripts\n  synthesize key information of the proof by refinement of schematic goal\n  states. In contrast, the Isar proof needs to say explicitly what is proven.\n\n  \\<^bigskip>\n  Cantor's Theorem states that every set has more subsets than it has\n  elements. It has become a favourite basic example in pure higher-order logic\n  since it is so easily expressed:\n\n  @{text [display]\n  \\<open>\\<forall>f::\\<alpha> \\<Rightarrow> \\<alpha> \\<Rightarrow> bool. \\<exists>S::\\<alpha> \\<Rightarrow> bool. \\<forall>x::\\<alpha>. f x \\<noteq> S\\<close>}\n\n  Viewing types as sets, \\<open>\\<alpha> \\<Rightarrow> bool\\<close> represents the powerset of \\<open>\\<alpha>\\<close>. This\n  version of the theorem states that for every function from \\<open>\\<alpha>\\<close> to its\n  powerset, some subset is outside its range. The Isabelle/Isar proofs below\n  uses HOL's set theory, with the type \\<open>\\<alpha> set\\<close> and the operator \\<open>range :: (\\<alpha> \\<Rightarrow>\n  \\<beta>) \\<Rightarrow> \\<beta> set\\<close>.\n\\<close>\n\ntheorem \"\\<exists>S. S \\<notin> range (f :: 'a \\<Rightarrow> 'a set)\"\nproof\n  let ?S = \"{x. x \\<notin> f x}\"\n  show \"?S \\<notin> range f\"\n  proof\n    assume \"?S \\<in> range f\"\n    then obtain y where \"?S = f y\" ..\n    then show False\n    proof (rule equalityCE)\n      assume \"y \\<in> f y\"\n      assume \"y \\<in> ?S\"\n      then have \"y \\<notin> f y\" ..\n      with \\<open>y \\<in> f y\\<close> show ?thesis by contradiction\n    next\n      assume \"y \\<notin> ?S\"\n      assume \"y \\<notin> f y\"\n      then have \"y \\<in> ?S\" ..\n      with \\<open>y \\<notin> ?S\\<close> show ?thesis by contradiction\n    qed\n  qed\nqed\n\ntext \\<open>\n  How much creativity is required? As it happens, Isabelle can prove this\n  theorem automatically using best-first search. Depth-first search would\n  diverge, but best-first search successfully navigates through the large\n  search space. The context of Isabelle's classical prover contains rules for\n  the relevant constructs of HOL's set theory.\n\\<close>\n\ntheorem \"\\<exists>S. S \\<notin> range (f :: 'a \\<Rightarrow> 'a set)\"\n  by best\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/Cantor.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835493924953, "lm_q2_score": 0.8596637559030338, "lm_q1q2_score": 0.7182349260659503}}
{"text": "theory unique\n  imports Main   \n  \"~~/src/HOL/Library/Code_Target_Nat\"\n  (* \"~~/src/HOL/Library/Fset\" *)\n  \"~~/src/HOL/Library/Finite_Set\"\nbegin\n\nsection \\<open>define unique\\<close>\n  \n(* unique. Takes a sequence of integers, returns the unique elements of that\nlist. There is no requirement on the ordering of the returned values. \n\ninspired by https://www.hillelwayne.com/post/theorem-prover-showdown/ *)\n\nfun uniqueAccum :: \"nat list \\<Rightarrow> nat list \\<Rightarrow> nat list\" where\n  \"uniqueAccum [] accum = accum\" |\n  \"uniqueAccum (x # xs) accum = uniqueAccum xs (List.insert x accum)\"\n(* note that List.insert uses set *) \n\nfun unique :: \"nat list => nat list\" where\n  \"unique xs = uniqueAccum xs []\"\n\n(* Prove: \n\nAll elements of the original list are in the output\n\nEvery element of the output is distinct\n\nNote from webpage author:\n\nI specified that all elements of the original list are in the output, but not\nthat all elements of the output were in the original list. If the method took\nin [1, 2, 2] and returned [1, 2, 99], it would still pass the partial\nspecification. I really dropped the ball on this one. *)\n\nsection \\<open>Proofs\\<close>\n\nsubsection \\<open>All elements of the original list are elements of the output\\<close>\n\n(* lemma uniqueAccum_order_invariant:\n  shows \"a \\<in> set (uniqueAccum xs ys) \\<Longrightarrow> a \\<in> set (uniqueAccum ys xs)\"\n  apply(induction xs arbitrary: ys)\n   apply(induction ys)\n    apply auto *)   \n\n\n\n\nproof(induction xs arbitrary: ys)\n  case Nil\n(*   hence \"a \\<in> set ys\" \n    by simp *)\n  then show ?case \n  proof(induction ys)\n    case Nil\n    then show ?case \n      by simp\n  next\n    case (Cons y ys\\<^sub>p)\n    then show ?case\n      apply auto\n      sorry\n  qed\nnext\n  case (Cons a xs)\n  then show ?case\n    try\n    sorry\n(* qed *)  oops\n\nlemma uniqueAccum_keeps_elements:\n  shows \"x \\<in> set (uniqueAccum ys [])\n      \\<Longrightarrow> x \\<in> set (uniqueAccum ys [a])\"\nproof(induction ys)\n  case Nil\n  then show ?case \n    by simp\nnext\n  case (Cons y ys\\<^sub>p)\n\n(* goal (1 subgoal):\n 1. x \\<in> set (uniqueAccum (y # ys\\<^sub>p) [a]) *)\n\n  (* \"uniqueAccum (x # xs) accum = uniqueAccum xs (List.insert x accum)\" *)\n(* \"insert x xs = (if x \\<in> set xs then xs else x # xs)\" *)\n\n  then show ?case \n    apply simp\n  proof(cases \"y = a\")\n    case True\n    hence ya:\"List.insert y [a] = [y]\" \n      by simp\n    hence \"x \\<in> set (uniqueAccum ys\\<^sub>p [y])\"\n      using Cons.prems by auto\n    then show \"x \\<in> set (uniqueAccum ys\\<^sub>p (List.insert y [a]))\"\n      by (simp add: ya)\n  next\n    case False\n    hence \"List.insert y [a] = [y, a]\" \n      by simp\n    hence \"uniqueAccum ys\\<^sub>p (List.insert y [a]) = uniqueAccum ys\\<^sub>p [y, a]\"\n      by simp\n    (* have \"set (uniqueAccum ys\\<^sub>p [y, a]) = set ys\\<^sub>p \\<union> {y, a}\" *)\n    then show ?thesis sorry\n  qed \n\n(*   proof(cases \"x = y\")\n    case True\n    then show ?thesis sorry\n  next\n    case False\n    hence \"x \\<in> ys\"\n      sorry\n    then show ?thesis sorry\n  qed *)\nqed\n  oops\n\n(*     assume \"x \\<in> set ys\"\n    then show \"x \\<in> set (uniqueAccum ys [y])\" *)\n\n(* https://isabelle.in.tum.de/community/FAQ#There_are_lots_of_arrows_in_Isabelle.2FHOL._What.27s_the_difference_between_-.3E.2C_.3D.3E.2C_--.3E.2C_and_.3D.3D.3E_.3F *)\n\nlemma all_elements_present:\n  fixes xs :: \"nat list\"\n  assumes \"x \\<in> set xs\"\n  shows \"x \\<in> set xs \\<Longrightarrow> x \\<in> set (unique xs)\"\nproof(induction xs)\n  case Nil\n  then show ?case\n    by simp\nnext\n  case (Cons y ys)\n  then show ?case \n    (* apply simp_all  *)\n    apply auto\n  proof -\n    assume \"x = y\"\n    then show \"y \\<in> set (uniqueAccum ys [y])\"\n      (* try *)\n      sorry\n  next\n    assume \"x \\<in> set ys\"\n    then show \"x \\<in> set (uniqueAccum ys [y])\"\n      sorry\n  qed\n  oops\n(*   proof(cases \"x = y\")\n    case True\n\n    then have \"y \\<in> set (uniqueAccum ys [y])\"\n      try\n(*     then show ?thesis \n      apply simp_all *) \n      (* try *)\n      sorry\n  next\n    case False\n    then have \"x \\<in> set ys\" \n      using Cons.prems by auto\n    then show ?thesis \n      apply simp_all \n      (* try *)\n      sorry\n  qed\n  oops *)\n\nlemma all_elements_present1:\n  fixes xs :: \"nat list\"\n  assumes \"x \\<in> set xs\"\n  shows \"\\<forall> x. x \\<in> set xs \\<Longrightarrow> x \\<in> set (unique xs)\"\nproof(induction xs)\n  case Nil\n  then show ?case\n    by simp\nnext\n  case (Cons y ys)\n  then show ?case\n    apply simp_all\n    oops\n\n(* I think this is wrong. prog-prove.pdf says:\n\"The implication =\\<Rightarrow> is part of the Isabelle framework...\"\n*)\nlemma all_elements_present2:\n  fixes xs :: \"nat list\"\n  assumes \"x \\<in> set xs\"\n  shows \"\\<forall> x. x \\<in> set xs \\<longrightarrow> x \\<in> set (unique xs)\" \nproof(induction xs)\n  case Nil\n  then show ?case\n    by simp\nnext\n  case (Cons y ys)\n  then show ?case\n   apply simp_all\n    oops", "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/unique.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8596637577007393, "lm_q2_score": 0.8354835309589073, "lm_q1q2_score": 0.7182349117212162}}
{"text": "(*<*)\ntheory Blue_Eyes\n  imports\n    \"HOL-Combinatorics.Transposition\"\nbegin\n(*>*)\n\nsection \\<open>Introduction\\<close>\n\ntext \\<open>The original problem statement @{cite xkcd} explains the puzzle well:\n\n\\begin{quotation}\nA group of people with assorted eye colors live on an island.\nThey are all perfect logicians -- if a conclusion can be logically deduced,\nthey will do it instantly.\nNo one knows the color of their eyes.\nEvery night at midnight, a ferry stops at the island.\nAny islanders who have figured out the color of their own eyes then leave the island, and the rest stay.\nEveryone can see everyone else at all times\nand keeps a count of the number of people they see with each eye color (excluding themselves),\nbut they cannot otherwise communicate.\nEveryone on the island knows all the rules in this paragraph.\n\nOn this island there are 100 blue-eyed people,\n100 brown-eyed people,\nand the Guru (she happens to have green eyes).\nSo any given blue-eyed person can see 100 people with brown eyes and 99 people with blue eyes (and one with green),\nbut that does not tell him his own eye color;\nas far as he knows the totals could be 101 brown and 99 blue.\nOr 100 brown, 99 blue, and he could have red eyes.\n\nThe Guru is allowed to speak once (let's say at noon),\non one day in all their endless years on the island.\nStanding before the islanders, she says the following:\n\n``I can see someone who has blue eyes.''\n\nWho leaves the island, and on what night?\n\\end{quotation}\n\nIt might seem weird that the Guru's declaration gives anyone any new information.\nFor an informal discussion, see \\cite[Section~1.1]{fagin1995}.\\<close>\n\nsection \\<open>Modeling the world \\label{sec:world}\\<close>\n\ntext \\<open>We begin by fixing two type variables: @{typ \"'color\"} and @{typ \"'person\"}.\nThe puzzle doesn't specify how many eye colors are possible, but four are mentioned.\nCrucially, we must assume they are distinct. We specify the existence of colors other\nthan blue and brown, even though we don't mention them later, because when blue and brown\nare the only possible colors, the puzzle has a different solution \u2014 the brown-eyed logicians\nmay leave one day after the blue-eyed ones.\n\nWe refrain from specifying the exact population of the island, choosing to only assume\nit is finite and denote a specific person as the Guru.\n\nWe could also model the Guru as an outside entity instead of a participant. This doesn't change\nthe answer and results in a slightly simpler proof, but is less faithful to the problem statement.\\<close>\n\ncontext\n  fixes blue brown green red :: 'color\n  assumes colors_distinct: \"distinct [blue, brown, green, red]\"\n\n  fixes guru :: 'person\n  assumes \"finite (UNIV :: 'person set)\"\nbegin\n\ntext \\<open>It's slightly tricky to formalize the behavior of perfect logicians.\nThe representation we use is centered around the type of a @{emph \\<open>world\\<close>},\nwhich describes the entire state of the environment. In our case, it's a function\n@{typ \"'person => 'color\"} that assigns an eye color to everyone.@{footnote \\<open>We would introduce\na type synonym, but at the time of writing Isabelle doesn't support including type variables fixed\nby a locale in a type synonym.\\<close>}\n\nThe only condition known to everyone and not dependent on the observer is Guru's declaration:\\<close>\n\ndefinition valid :: \"('person \\<Rightarrow> 'color) \\<Rightarrow> bool\" where\n  \"valid w \\<longleftrightarrow> (\\<exists>p. p \\<noteq> guru \\<and> w p = blue)\"\n\ntext \\<open>We then define the function @{term \"possible n p w w'\"}, which returns @{term True}\nif on day \\<open>n\\<close> the potential world \\<open>w'\\<close> is plausible from the perspective of person \\<open>p\\<close>,\nbased on the observations they made in the actual world \\<open>w\\<close>.\n\nThen, @{term \"leaves n p w\"} is @{term True} if \\<open>p\\<close> is able to unambiguously deduce\nthe color of their own eyes, i.e. if it is the same in all possible worlds. Note that if \\<open>p\\<close> actually\nleft many moons ago, this function still returns @{term True}.\\<close>\n\nfun leaves :: \"nat \\<Rightarrow> 'person \\<Rightarrow> ('person \\<Rightarrow> 'color) \\<Rightarrow> bool\"\n  and possible :: \"nat \\<Rightarrow> 'person \\<Rightarrow> ('person \\<Rightarrow> 'color) \\<Rightarrow> ('person \\<Rightarrow> 'color) \\<Rightarrow> bool\"\n  where\n    \"leaves n p w = (\\<forall>w'. possible n p w w' \\<longrightarrow> w' p = w p)\" |\n    \"possible n p w w' \\<longleftrightarrow> valid w \\<and> valid w'\n    \\<and> (\\<forall>p' \\<noteq> p. w p' = w' p')\n    \\<and> (\\<forall>n' < n. \\<forall>p'. leaves n' p' w = leaves n' p' w')\"\n\ntext \\<open>Naturally, the act of someone leaving can be observed by others, thus the two definitions\nare mutually recursive. As such, we need to instruct the simplifier to not unfold these definitions endlessly.\\<close>\ndeclare possible.simps[simp del] leaves.simps[simp del]\n\ntext \\<open>A world is possible if\n  \\<^enum> The Guru's declaration holds.\n  \\<^enum> The eye color of everyone but the observer matches.\n  \\<^enum> The same people left on each of the previous days.\n\nMoreover, we require that the actual world \\<open>w\\<close> is \\<open>valid\\<close>, so that the relation is symmetric:\\<close>\n\nlemma possible_sym: \"possible n p w w' = possible n p w' w\"\n  by (auto simp: possible.simps)\n\ntext \\<open>In fact, \\<open>possible n p\\<close> is an equivalence relation:\\<close>\n\nlemma possible_refl: \"valid w \\<Longrightarrow> possible n p w w\"\n  by (auto simp: possible.simps)\n\n\n\nsection \\<open>Eye colors other than blue\\<close>\n\ntext \\<open>Since there is no way to distinguish between the colors other than blue,\nonly the blue-eyed people will ever leave. To formalize this notion, we define\na function that takes a world and replaces the eye color of a specified person.\nThe original color is specified too, so that the transformation composes nicely\nwith the recursive hypothetical worlds of @{const possible}.\\<close>\n\ndefinition try_swap :: \"'person \\<Rightarrow> 'color \\<Rightarrow> 'color \\<Rightarrow> ('person \\<Rightarrow> 'color) \\<Rightarrow> ('person \\<Rightarrow> 'color)\" where\n  \"try_swap p c\\<^sub>1 c\\<^sub>2 w x = (if c\\<^sub>1 = blue \\<or> c\\<^sub>2 = blue \\<or> x \\<noteq> p then w x else transpose c\\<^sub>1 c\\<^sub>2 (w x))\"\n\nlemma try_swap_valid[simp]: \"valid (try_swap p c\\<^sub>1 c\\<^sub>2 w) = valid w\"\n  by (cases \\<open>c\\<^sub>1 = blue\\<close>; cases \\<open>c\\<^sub>2 = blue\\<close>)\n    (auto simp add: try_swap_def valid_def transpose_eq_iff)\n\nlemma try_swap_eq[simp]: \"try_swap p c\\<^sub>1 c\\<^sub>2 w x = try_swap p c\\<^sub>1 c\\<^sub>2 w' x \\<longleftrightarrow> w x = w' x\"\n  by (auto simp add: try_swap_def transpose_eq_iff)\n\nlemma try_swap_inv[simp]: \"try_swap p c\\<^sub>1 c\\<^sub>2 (try_swap p c\\<^sub>1 c\\<^sub>2 w) = w\"\n  by (rule ext) (auto simp add: try_swap_def swap_id_eq)\n\nlemma leaves_try_swap[simp]:\n  assumes \"valid w\"\n  shows \"leaves n p (try_swap p' c\\<^sub>1 c\\<^sub>2 w) = leaves n p w\"\n  using assms\nproof (induction n arbitrary: p w rule: less_induct)\n  case (less n)\n  have \"leaves n p w\" if \"leaves n p (try_swap p' c\\<^sub>1 c\\<^sub>2 w)\" for w\n  proof (unfold leaves.simps; rule+)\n    fix w'\n    assume \"possible n p w w'\"\n    then have \"possible n p (try_swap p' c\\<^sub>1 c\\<^sub>2 w) (try_swap p' c\\<^sub>1 c\\<^sub>2 w')\"\n      by (fastforce simp: possible.simps less.IH)\n    with `leaves n p (try_swap p' c\\<^sub>1 c\\<^sub>2 w)` have \"try_swap p' c\\<^sub>1 c\\<^sub>2 w' p = try_swap p' c\\<^sub>1 c\\<^sub>2 w p\"\n      unfolding leaves.simps\n      by simp\n    thus \"w' p = w p\" by simp\n  qed\n\n  with try_swap_inv show ?case by auto\nqed\n\ntext \\<open>This lets us prove that only blue-eyed people will ever leave the island.\\<close>\n\nproposition only_blue_eyes_leave:\n  assumes \"leaves n p w\" and \"valid w\"\n  shows \"w p = blue\"\nproof (rule ccontr)\n  assume \"w p \\<noteq> blue\"\n  then obtain c where c: \"w p \\<noteq> c\"  \"c \\<noteq> blue\"\n    using colors_distinct\n    by (metis distinct_length_2_or_more) \n\n  let ?w' = \"try_swap p (w p) c w\"\n  have \"possible n p w ?w'\"\n    using `valid w` apply (simp add: possible.simps)\n    by (auto simp: try_swap_def)\n  moreover have \"?w' p \\<noteq> w p\"\n    using c `w p \\<noteq> blue` by (auto simp: try_swap_def)\n  ultimately have \"\\<not> leaves n p w\"\n    by (auto simp: leaves.simps)\n  with assms show False by simp\nqed\n\nsection \"The blue-eyed logicians\"\n\ntext \\<open>We will now consider the behavior of the logicians with blue eyes. First,\nsome simple lemmas. Reasoning about set cardinalities often requires considering infinite\nsets separately. Usefully, all sets of people are finite by assumption.\\<close>\n\nlemma people_finite[simp]: \"finite (S::'person set)\"\nproof (rule finite_subset)\n  show \"S \\<subseteq> UNIV\" by auto\n  show \"finite (UNIV::'person set)\" by fact\nqed\n\ntext \\<open>Secondly, we prove a destruction rule for @{const possible}. It is strictly weaker than\nthe definition, but thanks to the simpler form, it's easier to guide the automation with it.\\<close>\nlemma possibleD_colors:\n  assumes \"possible n p w w'\" and \"p' \\<noteq> p\"\n  shows \"w' p' = w p'\"\n  using assms unfolding possible.simps by simp\n\ntext \\<open>A central concept in the reasoning is the set of blue-eyed people someone can see.\\<close>\ndefinition blues_seen :: \"('person \\<Rightarrow> 'color) \\<Rightarrow> 'person \\<Rightarrow> 'person set\" where\n  \"blues_seen w p = {p'. w p' = blue} - {p}\"\n\nlemma blues_seen_others:\n  assumes \"w p' = blue\" and \"p \\<noteq> p'\"\n  shows \"w p = blue \\<Longrightarrow> card (blues_seen w p) = card (blues_seen w p')\"\n    and \"w p \\<noteq> blue \\<Longrightarrow> card (blues_seen w p) = Suc (card (blues_seen w p'))\"\nproof -\n  assume \"w p = blue\"\n  then have \"blues_seen w p' = blues_seen w p \\<union> {p} - {p'}\"\n    by (auto simp add: blues_seen_def)\n  moreover have \"p \\<notin> blues_seen w p\"\n    unfolding blues_seen_def by auto\n  moreover have \"p' \\<in> blues_seen w p \\<union> {p}\"\n    unfolding blues_seen_def using `p \\<noteq> p'` `w p' = blue` by auto\n  ultimately show \"card (blues_seen w p) = card (blues_seen w p')\"\n    by simp\nnext\n  assume \"w p \\<noteq> blue\"\n  then have \"blues_seen w p' = blues_seen w p - {p'}\"\n    by (auto simp add: blues_seen_def)\n  moreover have \"p' \\<in> blues_seen w p\"\n    unfolding blues_seen_def using `p \\<noteq> p'` `w p' = blue` by auto\n  ultimately show \"card (blues_seen w p) = Suc (card (blues_seen w p'))\"\n    by (simp only: card_Suc_Diff1 people_finite)\nqed\n\n\n\nlemma possible_blues_seen:\n  assumes \"possible n p w w'\"\n  assumes \"w p' = blue\" and \"p \\<noteq> p'\"\n  shows \"w' p = blue \\<Longrightarrow> card (blues_seen w p) = card (blues_seen w' p')\"\n    and \"w' p \\<noteq> blue \\<Longrightarrow> card (blues_seen w p) = Suc (card (blues_seen w' p'))\"\n  using possibleD_colors[OF `possible n p w w'`] and blues_seen_others assms\n  by (auto simp flip: blues_seen_same)\n\ntext \\<open>Finally, the crux of the solution. We proceed by strong induction.\\<close>\n\nlemma blue_leaves:\n  assumes \"w p = blue\" and \"valid w\"\n    and guru: \"w guru \\<noteq> blue\"\n  shows \"leaves n p w \\<longleftrightarrow> n \\<ge> card (blues_seen w p)\"\n  using assms\nproof (induction n arbitrary: p w rule: less_induct)\n  case (less n)\n  show ?case\n  proof\n    \\<comment> \\<open>First, we show that day \\<open>n\\<close> is sufficient to deduce that the eyes are blue.\\<close>\n    assume \"n \\<ge> card (blues_seen w p)\"\n    have \"w' p = blue\" if \"possible n p w w'\" for w'\n    proof (cases \"card (blues_seen w' p)\")\n      case 0\n      moreover from `possible n p w w'` have \"valid w'\"\n        by (simp add: possible.simps)\n      ultimately show \"w' p = blue\"\n        unfolding valid_def blues_seen_def by auto\n    next\n      case (Suc k)\n      \\<comment> \\<open>We consider the behavior of somebody else, who also has blue eyes.\\<close>\n      then have \"blues_seen w' p \\<noteq> {}\"\n        by auto\n      then obtain p' where \"w' p' = blue\" and \"p \\<noteq> p'\"\n        unfolding blues_seen_def by auto\n      then have \"w p' = blue\"\n        using possibleD_colors[OF `possible n p w w'`] by simp\n\n      have \"p \\<noteq> guru\"\n        using `w p = blue` and `w guru \\<noteq> blue` by auto\n      hence \"w' guru \\<noteq> blue\"\n        using `w guru \\<noteq> blue` and possibleD_colors[OF `possible n p w w'`] by simp\n\n      have \"valid w'\"\n        using `possible n p w w'` unfolding possible.simps by simp\n\n      show \"w' p = blue\"\n      proof (rule ccontr)\n        assume \"w' p \\<noteq> blue\"\n        \\<comment> \\<open>If our eyes weren't blue, then \\<open>p'\\<close> would see one blue-eyed person less than us.\\<close>\n        with possible_blues_seen[OF `possible n p w w'` `w p' = blue` `p \\<noteq> p'`]\n        have *: \"card (blues_seen w p) = Suc (card (blues_seen w' p'))\"\n          by simp\n        \\<comment> \\<open>By induction, they would've left on day \\<open>k = blues_seen w' p'\\<close>.\\<close>\n        let ?k = \"card (blues_seen w' p')\"\n        have \"?k < n\"\n          using `n \\<ge> card (blues_seen w p)` and * by simp\n        hence \"leaves ?k p' w'\"\n          using `valid w'` `w' p' = blue` `w' guru \\<noteq> blue`\n          by (intro less.IH[THEN iffD2]; auto)\n        \\<comment> \\<open>However, we know that actually, \\<open>p'\\<close> didn't leave that day yet.\\<close>\n        moreover have \"\\<not> leaves ?k p' w\"\n        proof\n          assume \"leaves ?k p' w\"\n          then have \"?k \\<ge> card (blues_seen w p')\"\n            using `?k < n` `w p' = blue` `valid w` `w guru \\<noteq> blue`\n            by (intro less.IH[THEN iffD1]; auto)\n\n          have \"card (blues_seen w p) = card (blues_seen w p')\"\n            by (intro blues_seen_others; fact)\n          with * have \"?k < card (blues_seen w p')\"\n            by simp\n          with `?k \\<ge> card (blues_seen w p')` show False by simp\n        qed\n        moreover have \"leaves ?k p' w' = leaves ?k p' w\"\n          using `possible n p w w'` `?k < n`\n          unfolding possible.simps by simp\n        ultimately show False by simp\n      qed\n    qed\n    thus \"leaves n p w\"\n      unfolding leaves.simps using `w p = blue` by simp\n  next\n    \\<comment> \\<open>Then, we show that it's not possible to deduce the eye color any earlier.\\<close>\n    {\n      assume \"n < card (blues_seen w p)\"\n      \\<comment> \\<open>Consider a hypothetical world where \\<open>p\\<close> has brown eyes instead. We will prove that this\n        world is \\<open>possible\\<close>.\\<close>\n      let ?w' = \"w(p := brown)\"\n      have \"?w' guru \\<noteq> blue\"\n        using `w guru \\<noteq> blue` `w p = blue`\n        by auto\n      have \"valid ?w'\"\n      proof -\n        from `n < card (blues_seen w p)` have \"card (blues_seen w p) \\<noteq> 0\" by auto\n        hence \"blues_seen w p \\<noteq> {}\"\n          by auto\n        then obtain p' where \"p' \\<in> blues_seen w p\"\n          by auto\n        hence \"p \\<noteq> p'\" and \"w p' = blue\"\n          by (auto simp: blues_seen_def)\n        hence \"?w' p' = blue\" by auto\n        with `?w' guru \\<noteq> blue` show \"valid ?w'\"\n          unfolding valid_def by auto\n      qed\n      moreover have \"leaves n' p' w = leaves n' p' ?w'\" if \"n' < n\" for n' p'\n      proof -\n        have not_leavesI: \"\\<not>leaves n' p' w'\"\n          if \"valid w'\"  \"w' guru \\<noteq> blue\" and P: \"w' p' = blue \\<Longrightarrow> n' < card (blues_seen w' p')\" for w'\n        proof (cases \"w' p' = blue\")\n          case True\n          then have \"leaves n' p' w' \\<longleftrightarrow> n' \\<ge> card (blues_seen w' p')\"\n            using less.IH `n' < n` `valid w'` `w' guru \\<noteq> blue`\n            by simp\n          with P[OF `w' p' = blue`] show \"\\<not>leaves n' p' w'\" by simp\n        next\n          case False\n          then show \"\\<not> leaves n' p' w'\"\n            using only_blue_eyes_leave `valid w'` by auto\n        qed\n\n        have \"\\<not>leaves n' p' w\"\n        proof (intro not_leavesI)\n          assume \"w p' = blue\"\n          with `w p = blue` have \"card (blues_seen w p) = card (blues_seen w p')\"\n            apply (cases \"p = p'\", simp)\n            by (intro blues_seen_others; auto)\n          with `n' < n` and `n < card (blues_seen w p)` show \"n' < card (blues_seen w p')\"\n            by simp\n        qed fact+\n\n        moreover have \"\\<not> leaves n' p' ?w'\"\n        proof (intro not_leavesI)\n          assume \"?w' p' = blue\"\n          with colors_distinct have \"p \\<noteq> p'\" and \"?w' p \\<noteq> blue\" by auto\n          hence \"card (blues_seen ?w' p) = Suc (card (blues_seen ?w' p'))\"\n            using `?w' p' = blue` \n            by (intro blues_seen_others; auto)\n          moreover have \"blues_seen w p = blues_seen ?w' p\"\n            unfolding blues_seen_def by auto\n          ultimately show \"n' < card (blues_seen ?w' p')\"\n            using `n' < n` and `n < card (blues_seen w p)`\n            by auto\n        qed fact+\n\n        ultimately show \"leaves n' p' w = leaves n' p' ?w'\" by simp\n      qed\n      ultimately have \"possible n p w ?w'\"\n        using `valid w`\n        by (auto simp: possible.simps)\n      moreover have \"?w' p \\<noteq> blue\"\n        using colors_distinct by auto\n      ultimately have \"\\<not> leaves n p w\"\n        unfolding leaves.simps\n        using `w p = blue` by blast\n    }\n    then show \"leaves n p w \\<Longrightarrow> n \\<ge> card (blues_seen w p)\"\n      by fastforce\n  qed\nqed\n\ntext \\<open>This can be combined into a theorem that describes the behavior of the logicians based\non the objective count of blue-eyed people, and not the count by a specific person. The xkcd\npuzzle is the instance where \\<open>n = 99\\<close>.\\<close>\n\ntheorem blue_eyes:\n  assumes \"card {p. w p = blue} = Suc n\" and \"valid w\" and \"w guru \\<noteq> blue\"\n  shows \"leaves k p w \\<longleftrightarrow> w p = blue \\<and> k \\<ge> n\"\nproof (cases \"w p = blue\")\n  case True\n  with assms have \"card (blues_seen w p) = n\"\n    unfolding blues_seen_def by simp\n  then show ?thesis\n    using `w p = blue` `valid w` `w guru \\<noteq> blue` blue_leaves\n    by simp\nnext\n  case False\n  then show ?thesis\n    using only_blue_eyes_leave `valid w` by auto\nqed\n\nend\n\n(*<*)\nend\n(*>*)\n\nsection \\<open>Future work\\<close>\n\ntext \\<open>After completing this formalization, I have been made aware of epistemic logic.\nThe @{emph \\<open>possible worlds\\<close>} model in \\cref{sec:world} turns out to be quite similar\nto the usual semantics of this logic. It might be interesting to solve this puzzle within\nthe axiom system of epistemic logic, without explicit reasoning about possible worlds.\\<close>", "meta": {"author": "zabihullah331", "repo": "barakzai", "sha": "793257c1d71ec75a299fc6b5843af756ead2afb0", "save_path": "github-repos/isabelle/zabihullah331-barakzai", "path": "github-repos/isabelle/zabihullah331-barakzai/barakzai-793257c1d71ec75a299fc6b5843af756ead2afb0/thys/Blue_Eyes/Blue_Eyes.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8887587905460026, "lm_q2_score": 0.8080672066194945, "lm_q1q2_score": 0.7181768332350287}}
{"text": "theory FiniteHypClasses\n  imports \"HOL-Probability.Probability\" Pi_pmf LearningTheory\nbegin\n\nsection \"auxiliary lemmas\"\n\n\n\nlemma fixes m :: nat and  h \\<delta> \\<epsilon> :: real\n  assumes \n    nn: \"h >0\"  and\n        epos: \"\\<epsilon> > 0\" and m: \"real m \\<ge> (ln ( h / \\<delta>)) / \\<epsilon>\" \n      and dd: \"\\<delta> > 0\" \"\\<delta> < 1\"\n  shows aux_estim: \"h * exp (-\\<epsilon> * m) \\<le> \\<delta>\"\nproof -  \n  from m epos have \"ln ( h / \\<delta>) \\<le> real m * \\<epsilon>\"\n    by (smt divide_cancel_right mult_imp_le_div_pos nonzero_mult_div_cancel_right)\n  then have \"( h / \\<delta>) \\<le> exp (real m * \\<epsilon>)\" using dd nn\n    by (metis (full_types) divide_pos_pos exp_le_cancel_iff exp_ln of_nat_0_less_iff)\n  then have \"h \\<le> \\<delta> * exp (real m * \\<epsilon>)\" using dd\n    by (smt divide_divide_eq_left exp_gt_zero less_divide_eq_1_pos linordered_field_class.sign_simps(44))\n  then have A: \"h / exp (real m * \\<epsilon>) \\<le> \\<delta>\"\n    by (smt dd(1) divide_divide_eq_left exp_gt_zero less_divide_eq_1_pos mult.commute mult_pos_pos) \n  have B: \"h / exp (real m * \\<epsilon>) = h * exp (-\\<epsilon> * m)\"\n  proof -\n    have \"h / exp (real m * \\<epsilon>) = h * (exp 0) / exp (real m * \\<epsilon>)\"\n      by auto\n    also have \"\\<dots> = h * exp (0 - real m * \\<epsilon>)\" apply(subst exp_diff) by auto\n    also have \"\\<dots> =  h * exp (- \\<epsilon> * real m)\" by auto\n    finally show ?thesis .\n  qed\n  from A B show ed: \"h * exp (-\\<epsilon> * m) \\<le> \\<delta>\" by auto\nqed\n\n\n\nsection \"finite Hypothesis classes are PAC learnable\"    \n\n(* now assume we have a finite class of Hypotheses *)\nlocale finiteHypothesisClass = learning_basics where X=X and Y=Y and H = H \n  for X::\"'a set\" and Y::\"'b set\" and H :: \"('a \\<Rightarrow> 'b) set\" +\n  assumes fH: \"finite H\"\nbegin\n\n\ntext \\<open>Let us now analyze the performance of the \"Empirical Risk Minimization\" rule\nw.r.t. to the finite Hypothesis Class H.\nIts learning rule ERMe chooses for a given training set S an Hypothesis h from H\nwhich minimizes the Training Error. \\<close>\n\nlemma ERM_nonempty: \"H\\<noteq>{} \\<Longrightarrow> ERM S n \\<noteq> {}\" unfolding ERM_def \n  by (simp add: ex_is_arg_min_if_finite fH)\n\n\ntext \\<open>Now we show that the ERM rule is PAC learnable,\n      if we assume a finite hypotheses class H.\\<close>\n\nlemma fixes \n      D :: \"('a\\<times>'b) pmf\"\n    and \\<epsilon> \\<delta> :: real \n    and m :: nat\n  assumes\n        epos: \"\\<epsilon> > 0\" and m: \"real m \\<ge> (ln ( real (card H) / \\<delta>)) / \\<epsilon>\" \n      and dd: \"\\<delta> > 0\" \"\\<delta> < 1\"\n      and DX: \"set_pmf D \\<subseteq> (X\\<times>Y)\"\n    and RealizabilityAssumption: \"\\<exists>h'\\<in>H. PredErr D h' = 0\"\n\n  shows corollary_2_3_aux: \"measure_pmf.prob (Samples m D) {S. PredErr D (ERMe S m) \\<le> \\<epsilon>} \n        \\<ge> 1 - \\<delta>\" (is \"?LHS \\<ge> 1 - \\<delta>\")\nproof -\n\n  text \\<open>Fixing some Distribution @{term D} we are\n    interested in upperbounding the probability to sample m-tuple of instances that \n    will lead to failure of the learner.\n  \n    Formally we would like to upperbound @{term \"measure_pmf.prob (Samples m D) {S. PredErr D (ERMe S m) \\<le> \\<epsilon>}\"}.\\<close>\n\n  text \\<open>Let ?S be the carrier set of m-times labelled sample pairs (x,f x) from D.\\<close>\n  let ?S = \"set_pmf (Samples m D)\"\n\n  text \\<open>Let ?Hb be the set of \"bad\" hypotheses, that is,\\<close>\n  let ?Hb = \"{h\\<in>H. PredErr D h > \\<epsilon>}\"\n\n  have fHb: \"finite ?Hb\" using fH by simp\n  from fH have cHb: \"card ?Hb \\<le> card H\"\n    by (simp add: card_mono) \n\n  text \\<open>In addition,\\<close>\n  let ?M = \"{S\\<in>?S. \\<exists>h\\<in>?Hb. TrainErr S {0..<m} h = 0}\"\n  text \\<open>be the set of misleading samples: Namely, for every S in M, there is a \"bad\" hypothesis\n        h in H, that looks  like a \"good\" hypothesis on S.\\<close>\n\n  text \\<open>We can upperbound the \"bad\" events (in which we are interested) by ?M:\\<close>\n  have A: \"{S\\<in>?S. PredErr D (ERMe S m) > \\<epsilon>} \\<subseteq> ?M\"\n  proof  \n    from RealizabilityAssumption  \n    obtain h' where h'H: \"h'\\<in>H\" and u: \"PredErr D h' = 0\" by blast\n\n    from u have \"measure_pmf.prob D {S \\<in> set_pmf D. snd S \\<noteq> h' (fst S)} = 0\" unfolding PredErr_alt .\n    with measure_pmf_zero_iff[of D \"{S \\<in> set_pmf D. snd S \\<noteq> h' (fst S)}\"]       \n    have correct: \"\\<And>x. x\\<in>set_pmf D \\<Longrightarrow> snd x = h' (fst x)\" by blast\n    \n    fix S\n    assume \"S \\<in> {S \\<in>?S.   \\<epsilon> < PredErr D (ERMe S m)}\" \n    then have SS: \"S\\<in>?S\" and 2: \"\\<epsilon> < PredErr D (ERMe S m)\" by auto\n\n\n    from SS set_Pi_pmf[where A=\"{0..<m}\"]\n      have tD: \"\\<And>i. i\\<in>{0..<m} \\<Longrightarrow> S i \\<in> set_pmf D\"\n        unfolding Samples_def by auto \n\n\n      have z: \"\\<And>i. i\\<in>{0..<m} \\<Longrightarrow> (case S i of (x, y) \\<Rightarrow> if h' x \\<noteq> y then 1::real else 0) = 0\"\n        using tD correct\n        by (simp add: case_prod_beta') \n\n\n    have Th'0: \"TrainErr S {0..<m} h' = 0\" \n      unfolding TrainErr_def   using z  \n      by fastforce\n    \n    with h'H ERM_0_in have h'ERM: \"h' \\<in> ERM S m\" by blast\n    then have \"TrainErr S {0..<m} (ERMe S m) = 0\" using Th'0 by(rule ERMe_minimal)\n    have \"ERMe S m \\<in> H\" unfolding ERMe_def using ERM_subset ERM_nonempty\n      using nnH some_in_eq by blast  \n \n    have \"\\<exists>h\\<in>{h \\<in> H. \\<epsilon> < PredErr D h}. TrainErr S {0..<m} h = 0\"\n      apply(rule bexI[where x=\"ERMe S m\"]) \n       apply auto by fact+ \n    with SS show \"S \\<in> ?M\" by auto\n  qed\n\n  text \\<open>Note that we can rewrite ?M as\\<close>\n  have prop_2_5: \"?M = (\\<Union>h\\<in>?Hb. {S\\<in>?S. TrainErr S {0..<m} h = 0})\"\n    by auto\n\n  text \\<open>Next, let us bound the probability of the preceding events for each of the inner sets.\\<close>\n  have prop_2_9: \"\\<And>h. h\\<in>?Hb \\<Longrightarrow> measure_pmf.prob (Samples m D) ({S\\<in>?S. TrainErr S {0..<m} h = 0}) \\<le> exp (-\\<epsilon> * m)\"\n  proof -\n    text \\<open>Fix some \"bad\" hypothesis h:?Hb.\\<close>\n    fix h\n    assume \"h\\<in>?Hb\"\n    then have z: \"PredErr D h > \\<epsilon>\" by auto  \n\n    (* magic ^^, `m>0` seems to follow from `real m \\<ge> (ln ( real (card H) / \\<delta>)) / \\<epsilon>` *)\n    from nnH fH have \"card H > 0\" by auto\n    with m have mnn: \"m>0\" using epos dd\n      using fH leD real_of_nat_ge_one_iff by fastforce \n    from mnn have  \"finite {0..<m}\" \"{0..<m} \\<noteq>{}\" by auto \n\n    from TrainErr_correct[OF this] have Tc: \"\\<And>S h i. TrainErr S {0..<m} h = 0 \\<Longrightarrow> i \\<in> {0..<m} \\<Longrightarrow> h (fst (S i)) = snd (S i)\" .\n\n    text \\<open>We first estimate the probability that the \"bad\" hypothesis makes a \"good\" prediction.\\<close>\n    have individual_estim: \"measure_pmf.prob D {x. snd x = h (fst x)} \\<le> exp (-\\<epsilon>)\"\n    proof -\n      have \"measure_pmf.prob D {x. snd x = h (fst x)} = 1 - PredErr D h\" (is \"?L = ?R\") \n      proof - \n        have \"?L = measure_pmf.prob D {S \\<in> space (measure_pmf D). \\<not> (S\\<in>{x. snd x \\<noteq> h (fst x)})}\"\n          by auto  \n        also have \"\\<dots> = 1 - measure_pmf.prob D {x \\<in> space (measure_pmf D). x \\<in> {x. snd x \\<noteq> h (fst x)}}\"\n          apply(rule measure_pmf.prob_neg) by simp\n        also have \"\\<dots> = ?R\" unfolding PredErr_def by auto\n        finally show ?thesis .\n      qed \n      also have \"\\<dots> \\<le> 1 - \\<epsilon>\" using z by force\n        (* using the inequality `1-\\<epsilon> \\<le> exp (-\\<epsilon>)` *)\n      also have \"\\<dots> \\<le> exp (-\\<epsilon>)\" using epos\n        by (metis add_uminus_conv_diff exp_ge_add_one_self) \n      finally show\"measure_pmf.prob D {x. snd x = h (fst x)} \\<le> exp (-\\<epsilon>)\" .\n    qed\n \n   \n    \\<comment> \\<open>The event @{text \"L\\<^sub>S(h)=0\"} is equivalent to the event @{text \"\\<forall>i. h(x\\<^sub>i) = f(x\\<^sub>i)\"}\\<close>\n    have \"measure_pmf.prob (Samples m D) {S\\<in>?S. TrainErr S {0..<m} h = 0}\n        \\<le> measure_pmf.prob (Samples m D) {S\\<in>?S. (\\<forall>i\\<in>{0..<m}. snd (S i) = h (fst (S i)))}\"       \n      by (auto simp add: Tc intro: measure_pmf.finite_measure_mono)         \n     \\<comment> \\<open>Since the examples in the training set are sampled i.i.d. we get that:\\<close>\n    also have \"\\<dots> \\<le> measure_pmf.prob (Samples m D)  (repeated_event m {(x,y). y = h x})\" (* equality should also be correct, but \\<le> takes less effort *)\n    proof (rule measure_pmf.finite_measure_mono, safe)\n      fix S\n      assume S: \"S \\<in> set_pmf (Samples m D)\"\n      then have 1: \"\\<And>x. x \\<notin> {0..<m} \\<Longrightarrow> S x = undefined\"\n        using set_Pi_pmf_subset[of \"{0..<m}\" undefined \"(\\<lambda>_. D)\"] unfolding Samples_def\n        by blast\n      assume A: \"\\<forall>i\\<in>{0..<m}. (snd (S i)) = h (fst (S i))\"\n      { fix i\n        assume i: \"i \\<in> {0..<m}\"\n        with  set_Pi_pmf[OF _ S[unfolded Samples_def]] have Si: \"S i \\<in> set_pmf D\" by auto\n        fix x y assume \"S i = (x,y)\"\n        with Si \n        have \"y = h x\" unfolding Sample_def using A i by force\n      } note 2=this      \n      show \"S \\<in> repeated_event m {(x, y). y = h x}\" unfolding repeated_event_def PiE_dflt_def apply safe by (fact 1 2)+\n    qed simp\n    also have \"\\<dots> = (measure_pmf.prob D {(x,y). y = h x}) ^ m\" \n      by(rule iid)\n   (* also have \"\\<dots> = (measure_pmf.prob D {x. f x = h x}) ^ m\" \n      by(simp only: reduce) *)\n    \\<comment> \\<open>by estimating each individual sampling we obtain\\<close>\n    also have \"\\<dots> \\<le>  (exp (-\\<epsilon>)) ^ m\"\n        apply(rule power_mono)\n       apply (metis (mono_tags, lifting) Collect_cong case_prod_beta individual_estim)\n      by auto\n    also have \"\\<dots> \\<le> exp (-\\<epsilon> * m)\"\n      by (metis exp_of_nat2_mult order_refl) \n    finally show \"measure_pmf.prob (Samples m D) ({S\\<in>?S. TrainErr S {0..<m} h = 0}) \\<le> exp (-\\<epsilon> * m)\" .\n  qed\n\n\n          \n  text \"now we can plug all the estimations together:\"\n\n  have \"measure_pmf.prob (Samples m D) {S. PredErr D (ERMe S m) > \\<epsilon>}\n      = measure_pmf.prob (Samples m D) {S\\<in>?S. PredErr D (ERMe S m) > \\<epsilon>}\"\n    by (auto intro: pmf_prob_cong simp add: set_pmf_iff) \n  \\<comment> \\<open>the overapproximation by ?M:\\<close>\n  also have \"\\<dots> \\<le> measure_pmf.prob (Samples m D) ?M\"\n    apply(rule measure_pmf.finite_measure_mono) apply (fact A) by auto   \n  \\<comment> \\<open>the rewrite of ?M as a big Union:\\<close>\n  also have \"\\<dots> = measure_pmf.prob (Samples m D) (\\<Union>h\\<in>?Hb. {S\\<in>?S. TrainErr S {0..<m} h = 0})\" \n    using prop_2_5 by auto \n  \\<comment> \\<open>bounding the probability of a Union of events by the sum of the probability of the events:\\<close>\n  also have \"\\<dots> \\<le> sum (\\<lambda>h. measure_pmf.prob (Samples m D) ({S\\<in>?S. TrainErr S {0..<m} h = 0})) ?Hb\"\n      apply(rule measure_pmf.finite_measure_subadditive_finite) using fHb by auto\n  \\<comment> \\<open>applying the estimation:\\<close>\n  also have \"\\<dots> \\<le> sum (\\<lambda>h. exp (-\\<epsilon> * m)) ?Hb\"\n    apply(rule sum_mono) using prop_2_9  by blast\n  \\<comment> \\<open>some final rewrites:\\<close>\n  also have \"\\<dots> \\<le> (card ?Hb) * exp (-\\<epsilon> * m)\" using fHb by auto\n  also have \"\\<dots> \\<le> (card H) * exp (-\\<epsilon> * m)\" using cHb by simp\n  finally have k: \"measure_pmf.prob (Samples m D) {S. PredErr D (ERMe S m) > \\<epsilon>} \\<le> (card H) * exp (-\\<epsilon> * m)\" .\n\n  text \\<open>solve the bound for m for \\<delta>\\<close>\n  from nnH fH have nn: \"0 < real (card H)\" by fastforce \n  note bound = \\<open>m \\<ge> (ln ( card H / \\<delta>)) / \\<epsilon>\\<close>\n  from aux_estim[OF nn epos bound dd]\n    have ed: \"(card H) * exp (-\\<epsilon> * m) \\<le> \\<delta>\" by auto\n\n  text \\<open>Put everything together to yield the final result:\\<close>\n  have \"1 - \\<delta> \\<le> 1 - (card H) * exp (-\\<epsilon> * m)\" using ed by simp\n  also have \"\\<dots> \\<le> 1 - measure_pmf.prob (Samples m D) {S. PredErr D (ERMe S m) > \\<epsilon>}\"\n    using k by linarith\n  also have \"\\<dots> = ?LHS\" (is \"?R = _\")\n  proof -\n    thm measure_pmf.prob_neg\n    have \"?LHS = measure_pmf.prob (Samples m D) {S \\<in> space (measure_pmf (Samples m D)). \\<not> (S\\<in>{S. \\<epsilon> < PredErr D (ERMe S m)})}\"\n      apply auto  by (meson not_le)\n    also have \"\\<dots> = 1 - measure_pmf.prob (Samples m D) {x \\<in> space (measure_pmf (Samples m D)). x \\<in> {S. \\<epsilon> < PredErr D (ERMe S m)}}\"\n      apply(rule measure_pmf.prob_neg) by simp\n    also have \"\\<dots> = ?R\" by auto\n    finally show ?thesis by simp\n  qed \n  finally show \"measure_pmf.prob (Samples m D) {S. PredErr D (ERMe S m) \\<le> \\<epsilon>} \\<ge> 1 - \\<delta>\" by simp\nqed\n\ndefinition \"ERMbound \\<epsilon> \\<delta> = nat \\<lceil> (ln ( real (card H) / \\<delta>)) / \\<epsilon>\\<rceil>\"\n\nlemma corollary_2_3: \"PAC_learnable ERMe\"\n  unfolding PAC_learnable_def\n  apply(rule exI[where x=\"ERMbound\"])\n  apply safe unfolding ERMbound_def\n  using corollary_2_3_aux  by fastforce\n\nend\n\nend", "meta": {"author": "Quickblink", "repo": "verML", "sha": "bb7d4d1e154efb0e5464aa0a41a89f0411a6a0f8", "save_path": "github-repos/isabelle/Quickblink-verML", "path": "github-repos/isabelle/Quickblink-verML/verML-bb7d4d1e154efb0e5464aa0a41a89f0411a6a0f8/FiniteHypClasses.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8807970873650401, "lm_q2_score": 0.815232489352, "lm_q1q2_score": 0.7180544021465927}}
{"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_MSortBUPermutes\n  imports \"../../Test_Base\"\nbegin\n\ndatatype 'a list = nil2 | cons2 \"'a\" \"'a list\"\n\nfun map :: \"('a => 'b) => 'a list => 'b list\" where\n  \"map f (nil2) = nil2\"\n| \"map f (cons2 y xs) = cons2 (f y) (map f 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 mergingbu :: \"(int list) list => int list\" where\n  \"mergingbu (nil2) = nil2\"\n| \"mergingbu (cons2 xs (nil2)) = xs\"\n| \"mergingbu (cons2 xs (cons2 z x2)) =\n     mergingbu (pairwise (cons2 xs (cons2 z x2)))\"\n  by pat_completeness auto\n\nfun msortbu :: \"int list => int list\" where\n  \"msortbu x = mergingbu (map (% (y :: int) => cons2 y (nil2)) x)\"\n\nfun elem :: \"'a => 'a list => bool\" where\n  \"elem x (nil2) = False\"\n| \"elem x (cons2 z xs) = ((z = x) | (elem x xs))\"\n\nfun deleteBy :: \"('a => ('a => bool)) => 'a => 'a list =>\n                 'a list\" where\n  \"deleteBy x y (nil2) = nil2\"\n| \"deleteBy x y (cons2 y2 ys) =\n     (if (x y) y2 then ys else cons2 y2 (deleteBy x y ys))\"\n\nfun isPermutation :: \"'a list => 'a list => bool\" where\n  \"isPermutation (nil2) (nil2) = True\"\n| \"isPermutation (nil2) (cons2 z x2) = False\"\n| \"isPermutation (cons2 x3 xs) y =\n     ((elem x3 y) &\n        (isPermutation\n           xs (deleteBy (% (x4 :: 'a) => % (x5 :: 'a) => (x4 = x5)) x3 y)))\"\n\ntheorem property0 :\n  \"isPermutation (msortbu 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_sort_MSortBUPermutes.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757870046160258, "lm_q2_score": 0.8198933315126791, "lm_q1q2_score": 0.7180519249101434}}
{"text": "theory Design_Basics imports Main Multisets_Extras \"HOL-Library.Disjoint_Sets\"\nbegin\n\nsection \\<open>Design Theory Basics\\<close>\ntext \\<open>All definitions in this section reference the handbook of combinatorial designs\n \\<^cite>\\<open>\"colbournHandbookCombinatorialDesigns2007\"\\<close>\\<close>\n\nsubsection \\<open>Initial setup\\<close>\n\ntext \\<open>Enable coercion of nats to ints to aid with reasoning on design properties\\<close>\ndeclare [[coercion_enabled]]\ndeclare [[coercion \"of_nat :: nat \\<Rightarrow> int\"]]\n\nsubsection \\<open>Incidence System\\<close>\n\ntext \\<open>An incidence system is defined to be a wellformed set system. i.e. each block is a subset\nof the base point set. Alternatively, an incidence system can be looked at as the point set\nand an incidence relation which indicates if they are in the same block\\<close>\n\nlocale incidence_system = \n  fixes point_set :: \"'a set\" (\"\\<V>\")\n  fixes block_collection :: \"'a set multiset\" (\"\\<B>\")\n  assumes wellformed: \"b \\<in># \\<B> \\<Longrightarrow> b \\<subseteq> \\<V>\"\nbegin\n\ndefinition \"\\<I> \\<equiv> { (x, b) . b \\<in># \\<B> \\<and> x \\<in> b}\" (* incidence relation *)\n\ndefinition incident :: \"'a \\<Rightarrow> 'a set \\<Rightarrow> bool\" where\n\"incident p b \\<equiv> (p, b) \\<in> \\<I>\"\n\ntext \\<open>Defines common notation used to indicate number of points ($v$) and number of blocks ($b$)\\<close>\nabbreviation \"\\<v> \\<equiv> card \\<V>\"\n\nabbreviation \"\\<b> \\<equiv> size \\<B>\"\n\ntext \\<open>Basic incidence lemmas\\<close>\n\nlemma incidence_alt_def: \n  assumes \"p \\<in> \\<V>\"\n  assumes \"b \\<in># \\<B>\"\n  shows \"incident p b \\<longleftrightarrow> p \\<in> b\"\n  by (auto simp add: incident_def \\<I>_def assms)\n\nlemma wf_invalid_point: \"x \\<notin> \\<V> \\<Longrightarrow> b \\<in># \\<B> \\<Longrightarrow> x \\<notin> b\"\n  using wellformed by auto\n\nlemma block_set_nempty_imp_block_ex: \"\\<B> \\<noteq> {#} \\<Longrightarrow> \\<exists> bl . bl \\<in># \\<B>\"\n  by auto\n\ntext \\<open>Abbreviations for all incidence systems\\<close>\nabbreviation multiplicity :: \"'a set \\<Rightarrow> nat\" where\n\"multiplicity b \\<equiv> count \\<B> b\"\n\nabbreviation incomplete_block :: \"'a set \\<Rightarrow> bool\" where\n\"incomplete_block bl \\<equiv> card bl < card \\<V> \\<and> bl \\<in># \\<B>\"\n\nlemma incomplete_alt_size: \"incomplete_block bl \\<Longrightarrow> card bl < \\<v>\" \n  by simp\n\nlemma incomplete_alt_in: \"incomplete_block bl \\<Longrightarrow> bl \\<in># \\<B>\"\n  by simp\n\nlemma incomplete_alt_imp[intro]: \"card bl < \\<v> \\<Longrightarrow> bl \\<in># \\<B> \\<Longrightarrow> incomplete_block bl\"\n  by simp\n\ndefinition design_support :: \"'a set set\" where\n\"design_support \\<equiv> set_mset \\<B>\"\n\nend\n\nsubsection \\<open>Finite Incidence Systems\\<close>\n\ntext \\<open>These simply require the point set to be finite.\nAs multisets are only defined to be finite, it is implied that the block set must be finite already\\<close>\n\nlocale finite_incidence_system = incidence_system + \n  assumes finite_sets: \"finite \\<V>\"\nbegin\n\nlemma finite_blocks: \"b \\<in># \\<B> \\<Longrightarrow> finite b\"\n  using wellformed finite_sets finite_subset by blast \n\nlemma mset_points_distinct: \"distinct_mset (mset_set \\<V>)\"\n  using finite_sets by (simp add: distinct_mset_def)\n\nlemma mset_points_distinct_diff_one: \"distinct_mset (mset_set (\\<V> - {x}))\"\n  by (meson count_mset_set_le_one distinct_mset_count_less_1)\n\nlemma finite_design_support: \"finite (design_support)\"\n  using design_support_def by auto \n\nlemma block_size_lt_order: \"bl \\<in># \\<B> \\<Longrightarrow> card bl \\<le> card \\<V>\"\n  using wellformed by (simp add: card_mono finite_sets)  \n\nend\n\nsubsection \\<open>Designs\\<close>\n\ntext \\<open>There are many varied definitions of a design in literature. However, the most\ncommonly accepted definition is a finite point set, $V$ and collection of blocks $B$, where\nno block in $B$ can be empty\\<close>\nlocale design = finite_incidence_system +\n  assumes blocks_nempty: \"bl \\<in># \\<B> \\<Longrightarrow> bl \\<noteq> {}\"\nbegin\n\nlemma wf_design: \"design \\<V> \\<B>\"  by intro_locales\n\nlemma wf_design_iff: \"bl \\<in># \\<B> \\<Longrightarrow> design \\<V> \\<B> \\<longleftrightarrow> (bl \\<subseteq> \\<V> \\<and> finite \\<V> \\<and> bl \\<noteq> {})\"\n  using blocks_nempty wellformed finite_sets\n  by (simp add: wf_design) \n\ntext \\<open>Reasoning on non empty properties and non zero parameters\\<close>\nlemma blocks_nempty_alt: \"\\<forall> bl \\<in># \\<B>. bl \\<noteq> {}\"\n  using blocks_nempty by auto\n\nlemma block_set_nempty_imp_points: \"\\<B> \\<noteq> {#} \\<Longrightarrow> \\<V> \\<noteq> {}\"\n  using wf_design wf_design_iff by auto\n\nlemma b_non_zero_imp_v_non_zero: \"\\<b> > 0 \\<Longrightarrow> \\<v> > 0\"\n  using block_set_nempty_imp_points finite_sets by fastforce\n\nlemma v_eq0_imp_b_eq_0: \"\\<v> = 0 \\<Longrightarrow> \\<b> = 0\"\n  using b_non_zero_imp_v_non_zero by auto\n\ntext \\<open>Size lemmas\\<close>\nlemma block_size_lt_v: \"bl \\<in># \\<B> \\<Longrightarrow> card bl \\<le> \\<v>\"\n  by (simp add: card_mono finite_sets wellformed)\n\nlemma block_size_gt_0: \"bl \\<in># \\<B> \\<Longrightarrow> card bl > 0\"\n  using finite_sets blocks_nempty finite_blocks by fastforce\n\nlemma design_cart_product_size: \"size ((mset_set \\<V>) \\<times># \\<B>) = \\<v> * \\<b>\"\n  by (simp add: size_cartesian_product) \n\nend\n\ntext \\<open>Intro rules for design locale\\<close>\n\nlemma wf_design_implies: \n  assumes \"(\\<And> b . b \\<in># \\<B> \\<Longrightarrow> b \\<subseteq> V)\"\n  assumes \"\\<And> b . b \\<in># \\<B> \\<Longrightarrow> b \\<noteq> {}\"\n  assumes \"finite V\"\n  assumes \"\\<B> \\<noteq> {#}\"\n  assumes \"V \\<noteq> {}\"\n  shows \"design V \\<B>\"\n  using assms by (unfold_locales) simp_all\n\nlemma (in incidence_system) finite_sysI[intro]: \"finite \\<V> \\<Longrightarrow> finite_incidence_system \\<V> \\<B>\"\n  by (unfold_locales) simp_all\n\nlemma (in finite_incidence_system) designI[intro]: \"(\\<And> b. b \\<in># \\<B> \\<Longrightarrow> b \\<noteq> {}) \\<Longrightarrow> \\<B> \\<noteq> {#}\n     \\<Longrightarrow> \\<V> \\<noteq> {} \\<Longrightarrow> design \\<V> \\<B>\"\n  by (unfold_locales) simp_all\n\nsubsection \\<open>Core Property Definitions\\<close>\n\nsubsubsection \\<open>Replication Number\\<close>\n\ntext \\<open>The replication number for a point is the number of blocks that point is incident with\\<close>\n\ndefinition point_replication_number :: \"'a set multiset \\<Rightarrow> 'a \\<Rightarrow> nat\" (infix \"rep\" 75) where\n\"B rep x \\<equiv> size {#b \\<in># B . x \\<in> b#}\"\n\nlemma max_point_rep: \"B rep x \\<le> size B\"\n  using size_filter_mset_lesseq by (simp add: point_replication_number_def)\n\nlemma rep_number_g0_exists: \n  assumes \"B rep x > 0\" \n  obtains b where \"b \\<in># B\" and \"x \\<in> b\"\nproof -\n  have \"size {#b \\<in># B . x \\<in> b#} > 0\" using assms point_replication_number_def\n    by metis\n  thus ?thesis\n    by (metis filter_mset_empty_conv nonempty_has_size that) \nqed\n\nlemma rep_number_on_set_def: \"finite B \\<Longrightarrow> (mset_set B) rep x = card {b \\<in> B . x \\<in> b}\"\n  by (simp add: point_replication_number_def)\n\nlemma point_rep_number_split[simp]: \"(A + B) rep x = A rep x + B rep x\"\n  by (simp add: point_replication_number_def)\n\nlemma point_rep_singleton_val [simp]: \"x \\<in> b \\<Longrightarrow> {#b#} rep x = 1\"\n  by (simp add: point_replication_number_def)\n\nlemma point_rep_singleton_inval [simp]: \"x \\<notin> b \\<Longrightarrow> {#b#} rep x = 0\"\n  by (simp add: point_replication_number_def)\n\ncontext incidence_system\nbegin\n\nlemma point_rep_number_alt_def: \"\\<B> rep x = size {# b \\<in># \\<B> . x \\<in> b#}\"\n  by (simp add: point_replication_number_def)\n\nlemma rep_number_non_zero_system_point: \" \\<B> rep x > 0 \\<Longrightarrow> x \\<in> \\<V>\"\n  using rep_number_g0_exists wellformed\n  by (metis wf_invalid_point) \n\nlemma point_rep_non_existance [simp]: \"x \\<notin> \\<V> \\<Longrightarrow> \\<B> rep x = 0\"\n  using wf_invalid_point by (simp add:  point_replication_number_def filter_mset_empty_conv) \n\nlemma point_rep_number_inv: \"size {# b \\<in># \\<B> . x \\<notin> b #} = \\<b> - (\\<B> rep x)\"\nproof -\n  have \"\\<b> = size {# b \\<in># \\<B> . x \\<notin> b #} + size {# b \\<in># \\<B> . x \\<in> b #}\"\n    using multiset_partition by (metis add.commute size_union)  \n  thus ?thesis by (simp add: point_replication_number_def) \nqed\n\nlemma point_rep_num_inv_non_empty: \"(\\<B> rep x) < \\<b> \\<Longrightarrow> \\<B> \\<noteq> {#} \\<Longrightarrow> {# b \\<in># \\<B> . x \\<notin> b #} \\<noteq> {#}\"\n  by (metis diff_zero point_replication_number_def size_empty size_filter_neg verit_comp_simplify1(1))\n\nend\n\nsubsubsection \\<open>Point Index\\<close>\n\ntext \\<open>The point index of a subset of points in a design, is the number of times those points \noccur together in a block of the design\\<close>\ndefinition points_index :: \"'a set multiset \\<Rightarrow> 'a set \\<Rightarrow> nat\" (infix \"index\" 75) where\n\"B index ps \\<equiv> size {#b \\<in># B . ps \\<subseteq> b#}\"\n\nlemma points_index_empty [simp]: \"{#} index ps = 0\"\n  by (simp add: points_index_def)\n\nlemma point_index_distrib: \"(B1 + B2) index ps =  B1 index ps + B2 index ps\"\n  by (simp add: points_index_def)\n\nlemma point_index_diff: \"B1 index ps = (B1 + B2) index ps - B2 index ps\"\n  by (simp add: points_index_def)\n\nlemma points_index_singleton: \"{#b#} index ps = 1 \\<longleftrightarrow> ps \\<subseteq> b\"\n  by (simp add: points_index_def)\n\nlemma points_index_singleton_zero: \"\\<not> (ps \\<subseteq> b) \\<Longrightarrow> {#b#} index ps = 0\"\n  by (simp add: points_index_def)\n\nlemma points_index_sum: \"(\\<Sum>\\<^sub># B ) index ps = (\\<Sum>b \\<in># B . (b index ps))\"\n  using points_index_empty by (induction B) (auto simp add: point_index_distrib)\n\nlemma points_index_block_image_add_eq: \n  assumes \"x \\<notin> ps\"\n  assumes \"B index ps = l\"\n  shows \"{# insert x b . b \\<in># B#} index ps = l\"\n  using points_index_def by (metis (no_types, lifting) assms filter_mset_cong \n      image_mset_filter_swap2 points_index_def size_image_mset subset_insert)\n\nlemma points_index_on_set_def [simp]: \n  assumes \"finite B\"\n  shows \"(mset_set B) index ps = card {b \\<in> B. ps \\<subseteq> b}\"\n  by (simp add: points_index_def assms)\n\nlemma points_index_single_rep_num: \"B index {x} = B rep x\"\n  by (simp add: points_index_def point_replication_number_def)\n\nlemma points_index_pair_rep_num: \n  assumes \"\\<And> b. b \\<in># B \\<Longrightarrow> x \\<in> b\"\n  shows \"B index {x, y} = B rep y\"\n  using point_replication_number_def points_index_def\n  by (metis assms empty_subsetI filter_mset_cong insert_subset)\n\nlemma points_index_0_left_imp: \n  assumes \"B index ps = 0\"\n  assumes \"b \\<in># B\"\n  shows \"\\<not> (ps \\<subseteq> b)\"\nproof (rule ccontr)\n  assume \"\\<not> \\<not> ps \\<subseteq> b\"\n  then have a: \"ps \\<subseteq> b\" by auto\n  then have \"b \\<in># {#bl \\<in># B . ps \\<subseteq> bl#}\" by (simp add: assms(2)) \n  thus False by (metis assms(1) count_greater_eq_Suc_zero_iff count_size_set_repr not_less_eq_eq \n        points_index_def size_filter_mset_lesseq) \nqed\n\nlemma points_index_0_right_imp: \n  assumes \"\\<And> b . b \\<in># B \\<Longrightarrow> (\\<not> ps \\<subseteq> b)\"\n  shows \"B index ps = 0\"\n  using assms by (simp add: filter_mset_empty_conv points_index_def)\n\nlemma points_index_0_iff: \"B index ps = 0 \\<longleftrightarrow> (\\<forall> b. b \\<in># B \\<longrightarrow> (\\<not> ps \\<subseteq> b))\"\n  using points_index_0_left_imp points_index_0_right_imp by metis\n\nlemma points_index_gt0_impl_existance: \n  assumes \"B index ps > 0\"\n  shows \"(\\<exists> bl . (bl \\<in># B \\<and> ps \\<subseteq> bl))\"\nproof -\n  have \"size {#bl \\<in># B . ps \\<subseteq> bl#} > 0\"\n    by (metis assms points_index_def)\n  then obtain bl where \"bl \\<in># B\" and \"ps \\<subseteq> bl\"\n    by (metis filter_mset_empty_conv nonempty_has_size) \n  thus ?thesis by auto\nqed\n\nlemma points_index_one_unique: \n  assumes \"B index ps = 1\"\n  assumes \"bl \\<in># B\" and \"ps \\<subseteq> bl\" and \"bl' \\<in># B\" and \"ps \\<subseteq> bl'\"\n  shows \"bl = bl'\"\nproof (rule ccontr)\n  assume assm: \"bl \\<noteq> bl'\"\n  then have bl1: \"bl \\<in># {#bl \\<in># B . ps \\<subseteq> bl#}\" using assms by simp\n  then have bl2: \"bl'\\<in># {#bl \\<in># B . ps \\<subseteq> bl#}\" using assms by simp\n  then have \"{#bl, bl'#} \\<subseteq># {#bl \\<in># B . ps \\<subseteq> bl#}\" using assms by (metis bl1 bl2 points_index_def\n        add_mset_subseteq_single_iff assm mset_subset_eq_single size_single subseteq_mset_size_eql) \n  then have \"size {#bl \\<in># B . ps \\<subseteq> bl#} \\<ge> 2\" using size_mset_mono by fastforce \n  thus False using assms by (metis numeral_le_one_iff points_index_def semiring_norm(69))\nqed\n\nlemma points_index_one_unique_block: \n  assumes \"B index ps = 1\"\n  shows \"\\<exists>! bl . (bl \\<in># B \\<and> ps \\<subseteq> bl)\"\n  using assms points_index_gt0_impl_existance points_index_one_unique\n  by (metis zero_less_one) \n\nlemma points_index_one_not_unique_block: \n  assumes \"B index ps = 1\"\n  assumes \"ps \\<subseteq> bl\"\n  assumes \"bl \\<in># B\"\n  assumes \"bl' \\<in># B - {#bl#}\"\n  shows \"\\<not> ps \\<subseteq> bl'\"\nproof - \n  have \"B = (B - {#bl#}) + {#bl#}\" by (simp add: assms(3)) \n  then have \"(B - {#bl#}) index ps = B index ps - {#bl#} index ps\"\n    by (metis point_index_diff) \n  then have \"(B - {#bl#}) index ps = 0\" using assms points_index_singleton\n    by (metis diff_self_eq_0) \n  thus ?thesis using assms(4) points_index_0_left_imp by auto\nqed\n\nlemma (in incidence_system) points_index_alt_def: \"\\<B> index ps = size {#b \\<in># \\<B> . ps \\<subseteq> b#}\"\n  by (simp add: points_index_def)\n\nlemma (in incidence_system) points_index_ps_nin: \"\\<not> (ps \\<subseteq> \\<V>) \\<Longrightarrow> \\<B> index ps = 0\"\n  using points_index_alt_def filter_mset_empty_conv in_mono size_empty subsetI wf_invalid_point\n  by metis \n\nlemma (in incidence_system) points_index_count_bl: \n    \"multiplicity bl \\<ge> n \\<Longrightarrow> ps \\<subseteq> bl \\<Longrightarrow> count {#bl \\<in># \\<B> . ps \\<subseteq> bl#} bl \\<ge> n\"\n  by simp\n\nlemma (in finite_incidence_system) points_index_zero: \n  assumes \"card ps > card \\<V>\" \n  shows \"\\<B> index ps = 0\"\nproof -\n  have \"\\<And> b. b \\<in># \\<B> \\<Longrightarrow> card ps > card b\" \n    using block_size_lt_order card_subset_not_gt_card finite_sets assms by fastforce \n  then have \"{#b \\<in># \\<B> . ps \\<subseteq> b#} = {#}\"\n    by (simp add: card_subset_not_gt_card filter_mset_empty_conv finite_blocks)\n  thus ?thesis using points_index_alt_def by simp\nqed\n\nlemma (in design) points_index_subset: \n    \"x \\<subseteq># {#bl \\<in># \\<B> . ps \\<subseteq> bl#} \\<Longrightarrow> ps \\<subseteq> \\<V> \\<Longrightarrow> (\\<B> index ps) \\<ge> (size x)\"\n  by (simp add: points_index_def size_mset_mono)\n\nlemma (in design) points_index_count_min: \"multiplicity bl \\<ge> n \\<Longrightarrow> ps \\<subseteq> bl \\<Longrightarrow> \\<B> index ps \\<ge> n\"\n  using points_index_alt_def set_count_size_min by (metis filter_mset.rep_eq) \n\nsubsubsection \\<open>Intersection Number\\<close>\n\ntext \\<open>The intersection number of two blocks is the size of the intersection of those blocks. i.e. \nthe number of points which occur in both blocks\\<close>\ndefinition intersection_number :: \"'a set \\<Rightarrow> 'a set \\<Rightarrow> nat\" (infix \"|\\<inter>|\" 70) where\n\"b1 |\\<inter>| b2 \\<equiv> card (b1 \\<inter> b2)\"\n\nlemma intersection_num_non_neg: \"b1 |\\<inter>| b2 \\<ge> 0\"\n  by (simp add: intersection_number_def)\n\nlemma intersection_number_empty_iff: \n  assumes \"finite b1\"\n  shows \"b1 \\<inter> b2 = {} \\<longleftrightarrow> b1 |\\<inter>| b2 = 0\"\n  by (simp add: intersection_number_def assms)\n\nlemma intersect_num_commute: \"b1 |\\<inter>| b2 = b2 |\\<inter>| b1\"\n  by (simp add: inf_commute intersection_number_def) \n\ndefinition n_intersect_number :: \"'a set \\<Rightarrow> nat\\<Rightarrow> 'a set \\<Rightarrow> nat\" where\n\"n_intersect_number b1 n b2 \\<equiv> card { x \\<in> Pow (b1 \\<inter> b2) . card x = n}\"\n\nnotation n_intersect_number (\"(_ |\\<inter>|\\<^sub>_ _)\" [52, 51, 52] 50)\n\nlemma n_intersect_num_subset_def: \"b1 |\\<inter>|\\<^sub>n b2 = card {x . x \\<subseteq> b1 \\<inter> b2 \\<and> card x = n}\"\n  using n_intersect_number_def by auto\n\nlemma n_inter_num_one: \"finite b1 \\<Longrightarrow> finite b2 \\<Longrightarrow> b1 |\\<inter>|\\<^sub>1 b2 = b1 |\\<inter>| b2\"\n  using n_intersect_number_def intersection_number_def card_Pow_filter_one\n  by (metis (full_types) finite_Int) \n\nlemma n_inter_num_choose: \"finite b1 \\<Longrightarrow> finite b2 \\<Longrightarrow> b1 |\\<inter>|\\<^sub>n b2 = (card (b1 \\<inter> b2) choose n)\" \n  using n_subsets n_intersect_num_subset_def\n  by (metis (full_types) finite_Int) \n\nlemma set_filter_single: \"x \\<in> A \\<Longrightarrow> {a \\<in> A . a = x} = {x}\"\n  by auto \n\nlemma (in design) n_inter_num_zero: \n  assumes \"b1 \\<in># \\<B>\" and \"b2 \\<in># \\<B>\"\n  shows \"b1 |\\<inter>|\\<^sub>0 b2 = 1\"\nproof -\n  have empty: \"\\<And>x . finite x \\<Longrightarrow> card x = 0 \\<Longrightarrow> x = {}\"\n    by simp\n  have empt_in: \"{} \\<in> Pow (b1 \\<inter> b2)\" by simp\n  have \"finite (b1 \\<inter> b2)\" using finite_blocks assms by simp\n  then have \"\\<And> x . x \\<in> Pow (b1 \\<inter> b2) \\<Longrightarrow> finite x\" by (meson PowD finite_subset) \n  then have \"{x \\<in> Pow (b1 \\<inter> b2) . card x = 0} = {x \\<in> Pow (b1 \\<inter> b2) . x = {}}\" \n    using empty by (metis card.empty)\n  then have \"{x \\<in> Pow (b1 \\<inter> b2) . card x = 0} = {{}}\" \n    by (simp add: empt_in set_filter_single Collect_conv_if)\n  thus ?thesis by (simp add: n_intersect_number_def)\nqed\n\nlemma (in design) n_inter_num_choose_design: \"b1 \\<in># \\<B> \\<Longrightarrow> b2 \\<in># \\<B> \n    \\<Longrightarrow> b1 |\\<inter>|\\<^sub>n b2 = (card (b1 \\<inter> b2) choose n) \"\n  using finite_blocks by (simp add: n_inter_num_choose)\n\nlemma (in design) n_inter_num_choose_design_inter: \"b1 \\<in># \\<B> \\<Longrightarrow> b2 \\<in># \\<B> \n    \\<Longrightarrow> b1 |\\<inter>|\\<^sub>n b2 = (nat (b1 |\\<inter>| b2) choose n) \"\n  using finite_blocks by (simp add: n_inter_num_choose intersection_number_def)\n\nsubsection \\<open>Incidence System Set Property Definitions\\<close>\ncontext incidence_system\nbegin\n\ntext \\<open>The set of replication numbers for all points of design\\<close>\ndefinition replication_numbers :: \"nat set\" where\n\"replication_numbers \\<equiv> {\\<B> rep x | x . x \\<in> \\<V>}\"\n\nlemma replication_numbers_non_empty: \n  assumes \"\\<V> \\<noteq> {}\"\n  shows \"replication_numbers \\<noteq> {}\"\n  by (simp add: assms replication_numbers_def) \n\nlemma obtain_point_with_rep: \"r \\<in> replication_numbers \\<Longrightarrow> \\<exists> x. x \\<in> \\<V> \\<and> \\<B> rep x = r\"\n  using replication_numbers_def by auto\n\nlemma point_rep_number_in_set: \"x \\<in> \\<V> \\<Longrightarrow> (\\<B> rep x) \\<in> replication_numbers\"\n  by (auto simp add: replication_numbers_def)\n\nlemma (in finite_incidence_system) replication_numbers_finite: \"finite replication_numbers\"\n  using finite_sets by (simp add: replication_numbers_def)\n\ntext \\<open>The set of all block sizes in a system\\<close>\n\ndefinition sys_block_sizes :: \"nat set\" where\n\"sys_block_sizes \\<equiv> { card bl | bl. bl \\<in># \\<B>}\"\n\nlemma block_sizes_non_empty_set: \n  assumes \"\\<B> \\<noteq> {#}\"\n  shows \"sys_block_sizes \\<noteq> {}\"\nby (simp add: sys_block_sizes_def assms)\n\nlemma finite_block_sizes: \"finite (sys_block_sizes)\"\n  by (simp add: sys_block_sizes_def)\n\nlemma block_sizes_non_empty: \n  assumes \"\\<B> \\<noteq> {#}\"\n  shows \"card (sys_block_sizes) > 0\"\n  using finite_block_sizes block_sizes_non_empty_set\n  by (simp add: assms card_gt_0_iff) \n\nlemma sys_block_sizes_in: \"bl \\<in># \\<B> \\<Longrightarrow> card bl \\<in> sys_block_sizes\"\n  unfolding sys_block_sizes_def by auto \n\nlemma sys_block_sizes_obtain_bl: \"x \\<in> sys_block_sizes  \\<Longrightarrow> (\\<exists> bl \\<in># \\<B>. card bl = x)\"\n  by (auto simp add: sys_block_sizes_def)\n\ntext \\<open>The set of all possible intersection numbers in a system.\\<close>\n\ndefinition intersection_numbers :: \"nat set\" where\n\"intersection_numbers \\<equiv> { b1 |\\<inter>| b2 | b1 b2 . b1 \\<in># \\<B> \\<and> b2 \\<in># (\\<B> - {#b1#})}\"\n\nlemma obtain_blocks_intersect_num: \"n \\<in> intersection_numbers \\<Longrightarrow> \n  \\<exists> b1 b2. b1 \\<in># \\<B> \\<and> b2 \\<in># (\\<B> - {#b1#}) \\<and>  b1 |\\<inter>| b2 = n\"\n  by (auto simp add: intersection_numbers_def)\n\nlemma intersect_num_in_set: \"b1 \\<in># \\<B> \\<Longrightarrow> b2 \\<in># (\\<B> - {#b1#}) \\<Longrightarrow> b1 |\\<inter>| b2 \\<in> intersection_numbers\"\n  by (auto simp add: intersection_numbers_def)\n\ntext \\<open>The set of all possible point indices\\<close>\ndefinition point_indices :: \"nat \\<Rightarrow> nat set\" where\n\"point_indices t \\<equiv> {\\<B> index ps | ps. card ps = t \\<and> ps \\<subseteq> \\<V>}\"\n\nlemma point_indices_elem_in: \"ps \\<subseteq> \\<V> \\<Longrightarrow> card ps = t \\<Longrightarrow> \\<B> index ps \\<in> point_indices t\"\n  by (auto simp add: point_indices_def)\n\nlemma point_indices_alt_def: \"point_indices t = { \\<B> index ps | ps. card ps = t \\<and> ps \\<subseteq> \\<V>}\"\n  by (simp add: point_indices_def)\n\nend\n\nsubsection \\<open>Basic Constructions on designs\\<close>\n\ntext \\<open>This section defines some of the most common universal constructions found in design theory\ninvolving only a single design\\<close>\n\nsubsubsection \\<open>Design Complements\\<close>\n\ncontext incidence_system\nbegin\n\ntext \\<open>The complement of a block are all the points in the design not in that block. \nThe complement of a design is therefore the original point sets, and set of all block complements\\<close>\ndefinition block_complement:: \"'a set \\<Rightarrow> 'a set\" (\"_\\<^sup>c\" [56] 55) where\n\"block_complement b \\<equiv> \\<V> - b\"\n\ndefinition complement_blocks :: \"'a set multiset\" (\"(\\<B>\\<^sup>C)\")where\n\"complement_blocks \\<equiv> {# bl\\<^sup>c . bl \\<in># \\<B> #}\" \n\nlemma block_complement_elem_iff: \n  assumes \"ps \\<subseteq> \\<V>\"\n  shows \"ps \\<subseteq> bl\\<^sup>c \\<longleftrightarrow> (\\<forall> x \\<in> ps. x \\<notin> bl)\"\n  using assms block_complement_def by (auto)\n\nlemma block_complement_inter_empty: \"bl1\\<^sup>c = bl2 \\<Longrightarrow> bl1 \\<inter> bl2 = {}\"\n  using block_complement_def by auto\n\nlemma block_complement_inv: \n  assumes \"bl \\<in># \\<B>\"\n  assumes \"bl\\<^sup>c = bl2\"\n  shows \"bl2\\<^sup>c = bl\"\n  by (metis Diff_Diff_Int assms(1) assms(2) block_complement_def inf.absorb_iff2 wellformed)\n\nlemma block_complement_subset_points: \"ps \\<subseteq> (bl\\<^sup>c) \\<Longrightarrow> ps \\<subseteq> \\<V>\"\n  using block_complement_def by blast\n\nlemma obtain_comp_block_orig: \n  assumes \"bl1 \\<in># \\<B>\\<^sup>C\"\n  obtains bl2 where \"bl2 \\<in># \\<B>\" and \"bl1 = bl2\\<^sup>c\"\n  using wellformed assms by (auto simp add: complement_blocks_def)\n\nlemma complement_same_b [simp]: \"size \\<B>\\<^sup>C = size \\<B>\"\n  by (simp add: complement_blocks_def)\n\nlemma block_comp_elem_alt_left: \"x \\<in> bl \\<Longrightarrow> ps \\<subseteq> bl\\<^sup>c \\<Longrightarrow> x \\<notin> ps\"\n  by (auto simp add: block_complement_def block_complement_elem_iff)\n\nlemma block_comp_elem_alt_right: \"ps \\<subseteq> \\<V> \\<Longrightarrow> (\\<And> x . x \\<in> ps \\<Longrightarrow> x \\<notin> bl) \\<Longrightarrow> ps \\<subseteq> bl\\<^sup>c\"\n  by (auto simp add: block_complement_elem_iff)\n\nlemma complement_index:\n  assumes \"ps \\<subseteq> \\<V>\"\n  shows \"\\<B>\\<^sup>C index ps = size {# b \\<in># \\<B> . (\\<forall> x \\<in> ps . x \\<notin> b) #}\"\nproof -\n  have \"\\<B>\\<^sup>C index ps =  size {# b \\<in># {# bl\\<^sup>c . bl \\<in># \\<B>#}. ps \\<subseteq> b #}\"\n    by (simp add: complement_blocks_def points_index_def) \n  then have \"\\<B>\\<^sup>C index ps = size {# bl\\<^sup>c | bl \\<in># \\<B> . ps \\<subseteq> bl\\<^sup>c #}\"\n    by (metis image_mset_filter_swap)\n  thus ?thesis using assms by (simp add: block_complement_elem_iff)\nqed\n\nlemma complement_index_2:\n  assumes \"{x, y} \\<subseteq> \\<V>\"\n  shows \"\\<B>\\<^sup>C index {x, y} = size {# b \\<in># \\<B> . x \\<notin> b \\<and> y \\<notin> b #}\"\nproof -\n  have a: \"\\<And> b. b \\<in># \\<B> \\<Longrightarrow> \\<forall> x' \\<in> {x, y} . x' \\<notin> b \\<Longrightarrow> x \\<notin> b \\<and> y \\<notin> b\"\n    by simp \n  have \"\\<And> b. b \\<in># \\<B> \\<Longrightarrow> x \\<notin> b \\<and> y \\<notin> b \\<Longrightarrow> \\<forall> x' \\<in> {x, y} . x' \\<notin> b \"\n    by simp \n  thus ?thesis using assms a complement_index\n    by (smt (verit) filter_mset_cong) \nqed\n\nlemma complement_rep_number: \n  assumes \"x \\<in> \\<V>\" and \"\\<B> rep x = r\" \n  shows  \"\\<B>\\<^sup>C rep x = \\<b> - r\"\nproof - \n  have r: \"size {#b \\<in># \\<B> . x \\<in> b#} = r\" using assms by (simp add: point_replication_number_def)\n  then have a: \"\\<And> b . b \\<in># \\<B> \\<Longrightarrow> x \\<in> b \\<Longrightarrow> x \\<notin> b\\<^sup>c\"\n    by (simp add: block_complement_def)\n  have \"\\<And> b . b \\<in># \\<B> \\<Longrightarrow> x \\<notin> b \\<Longrightarrow> x \\<in> b\\<^sup>c\"\n    by (simp add: assms(1) block_complement_def) \n  then have alt: \"(image_mset block_complement \\<B>) rep x = size {#b \\<in># \\<B> . x \\<notin> b#}\" \n    using a filter_mset_cong image_mset_filter_swap2 point_replication_number_def\n    by (smt (verit, ccfv_SIG) size_image_mset) \n  have \"\\<b> = size {#b \\<in># \\<B> . x \\<in> b#} + size {#b \\<in># \\<B> . x \\<notin> b#}\"\n    by (metis multiset_partition size_union) \n  thus ?thesis using alt\n    by (simp add: r complement_blocks_def)\nqed\n\nlemma complement_blocks_wf: \"bl \\<in># \\<B>\\<^sup>C \\<Longrightarrow> bl \\<subseteq> \\<V>\"\n  by (auto simp add: complement_blocks_def block_complement_def)\n\nlemma complement_wf [intro]: \"incidence_system \\<V> \\<B>\\<^sup>C\"\n  using complement_blocks_wf by (unfold_locales)\n\ninterpretation sys_complement: incidence_system \"\\<V>\" \"\\<B>\\<^sup>C\"\n  using complement_wf by simp \nend\n\ncontext finite_incidence_system\nbegin\nlemma block_complement_size: \"b \\<subseteq> \\<V> \\<Longrightarrow> card (b\\<^sup>c) = card \\<V> - card b\"\n  by (simp add: block_complement_def card_Diff_subset finite_subset card_mono of_nat_diff finite_sets)  \n\nlemma block_comp_incomplete: \"incomplete_block bl \\<Longrightarrow> card (bl\\<^sup>c) > 0\"\n  using block_complement_size by (simp add: wellformed) \n\nlemma  block_comp_incomplete_nempty: \"incomplete_block bl \\<Longrightarrow> bl\\<^sup>c \\<noteq> {}\"\n  using wellformed block_complement_def finite_blocks\n  by (auto simp add: block_complement_size block_comp_incomplete card_subset_not_gt_card)\n\nlemma incomplete_block_proper_subset: \"incomplete_block bl \\<Longrightarrow> bl \\<subset> \\<V>\"\n  using wellformed by fastforce\n\nlemma complement_finite: \"finite_incidence_system \\<V> \\<B>\\<^sup>C\"\n  using complement_wf finite_sets by (simp add: incidence_system.finite_sysI) \n\ninterpretation comp_fin: finite_incidence_system \\<V> \"\\<B>\\<^sup>C\"\n  using complement_finite by simp \n\nend\n\ncontext design\nbegin\nlemma (in design) complement_design: \n  assumes \"\\<And> bl . bl \\<in># \\<B> \\<Longrightarrow> incomplete_block bl\" \n  shows \"design \\<V> (\\<B>\\<^sup>C)\"\nproof -\n  interpret fin: finite_incidence_system \\<V> \"\\<B>\\<^sup>C\" using complement_finite by simp\n  show ?thesis using assms block_comp_incomplete_nempty wellformed \n    by (unfold_locales) (auto simp add: complement_blocks_def)\nqed\n\nend\nsubsubsection \\<open>Multiples\\<close>\ntext \\<open>An easy way to construct new set systems is to simply multiply the block collection by some \nconstant\\<close>\n\ncontext incidence_system \nbegin\n\nabbreviation multiple_blocks :: \"nat \\<Rightarrow> 'a set multiset\" where\n\"multiple_blocks n \\<equiv> repeat_mset n \\<B>\"\n\nlemma multiple_block_in_original: \"b \\<in># multiple_blocks n \\<Longrightarrow> b \\<in># \\<B>\"\n  by (simp add: elem_in_repeat_in_original) \n\nlemma multiple_block_in: \"n > 0 \\<Longrightarrow> b \\<in># \\<B> \\<Longrightarrow>  b \\<in># multiple_blocks n\"\n  by (simp add: elem_in_original_in_repeat)\n\nlemma multiple_blocks_gt: \"n > 0 \\<Longrightarrow> size (multiple_blocks n) \\<ge> size \\<B>\" \n  by (simp)\n\nlemma block_original_count_le: \"n > 0 \\<Longrightarrow> count \\<B> b \\<le> count (multiple_blocks n) b\"\n  using count_repeat_mset by simp \n\nlemma multiple_blocks_sub: \"n > 0 \\<Longrightarrow> \\<B> \\<subseteq># (multiple_blocks n)\"\n  by (simp add: mset_subset_eqI block_original_count_le) \n\nlemma multiple_1_same: \"multiple_blocks 1 = \\<B>\"\n  by simp\n\nlemma multiple_unfold_1: \"multiple_blocks (Suc n) = (multiple_blocks n) + \\<B>\"\n  by simp\n\nlemma multiple_point_rep_num: \"(multiple_blocks n) rep x = (\\<B> rep x) * n\"\nproof (induction n)\n  case 0\n  then show ?case by (simp add: point_replication_number_def)\nnext\n  case (Suc n)\n  then have \"multiple_blocks (Suc n) rep x = \\<B> rep x * n + (\\<B> rep x)\"\n    using Suc.IH Suc.prems by (simp add: union_commute point_replication_number_def)\n  then show ?case\n    by (simp)\nqed\n\nlemma multiple_point_index: \"(multiple_blocks n) index ps = (\\<B> index ps) * n\"\n  by (induction n) (auto simp add: points_index_def)\n\nlemma repeat_mset_block_point_rel: \"\\<And>b x. b \\<in># multiple_blocks  n \\<Longrightarrow> x \\<in> b \\<Longrightarrow> x \\<in> \\<V>\"\n  by (induction n) (auto, meson subset_iff wellformed)\n\nlemma multiple_is_wellformed: \"incidence_system \\<V> (multiple_blocks n)\"\n  using repeat_mset_subset_in wellformed repeat_mset_block_point_rel by (unfold_locales) (auto)\n\nlemma  multiple_blocks_num [simp]: \"size (multiple_blocks n) = n*\\<b>\"\n  by simp\n\ninterpretation mult_sys: incidence_system \\<V> \"(multiple_blocks n)\"\n  by (simp add: multiple_is_wellformed)\n\nlemma multiple_block_multiplicity [simp]: \"mult_sys.multiplicity n bl = (multiplicity bl) * n\"\n  by (simp)\n\nlemma multiple_block_sizes_same: \n  assumes \"n > 0\" \n  shows \"sys_block_sizes = mult_sys.sys_block_sizes n\"\nproof -\n  have def: \"mult_sys.sys_block_sizes n = {card bl | bl. bl \\<in># (multiple_blocks n)}\"\n    by (simp add: mult_sys.sys_block_sizes_def) \n  then have eq: \"\\<And> bl. bl \\<in># (multiple_blocks n) \\<longleftrightarrow> bl \\<in># \\<B>\"\n    using assms multiple_block_in multiple_block_in_original by blast \n  thus ?thesis using def by (simp add: sys_block_sizes_def eq)\nqed \n\nend\n\ncontext finite_incidence_system\nbegin\n\nlemma multiple_is_finite: \"finite_incidence_system \\<V> (multiple_blocks n)\"\n  using multiple_is_wellformed finite_sets by (unfold_locales) (auto simp add: incidence_system_def)\n\nend\n\ncontext design\nbegin\n\nlemma multiple_is_design: \"design \\<V> (multiple_blocks n)\"\nproof -\n  interpret fis: finite_incidence_system \\<V> \"multiple_blocks n\" using multiple_is_finite by simp\n  show ?thesis using blocks_nempty\n    by (unfold_locales) (auto simp add: elem_in_repeat_in_original repeat_mset_not_empty)\nqed\n\nend\n\nsubsection \\<open>Simple Designs\\<close>\n\ntext \\<open>Simple designs are those in which the multiplicity of each block is at most one. \nIn other words, the block collection is a set. This can significantly ease reasoning.\\<close>\n\nlocale simple_incidence_system = incidence_system + \n  assumes simple [simp]: \"bl \\<in># \\<B> \\<Longrightarrow> multiplicity bl = 1\"\n\nbegin \n\nlemma simple_alt_def_all: \"\\<forall> bl \\<in># \\<B> . multiplicity bl = 1\"\n  using simple by auto\n  \nlemma simple_blocks_eq_sup: \"mset_set (design_support) = \\<B>\"\n  using distinct_mset_def simple design_support_def by (metis distinct_mset_set_mset_ident) \n\nlemma simple_block_size_eq_card: \"\\<b> = card (design_support)\"\n  by (metis simple_blocks_eq_sup size_mset_set)\n\nlemma points_index_simple_def: \"\\<B> index ps = card {b \\<in> design_support . ps \\<subseteq> b}\"\n  using design_support_def points_index_def card_size_filter_eq simple_blocks_eq_sup\n  by (metis finite_set_mset) \n\nlemma replication_num_simple_def: \"\\<B> rep x = card {b \\<in> design_support . x \\<in> b}\"\n  using design_support_def point_replication_number_def card_size_filter_eq simple_blocks_eq_sup\n  by (metis finite_set_mset) \n\nend\n\nlocale simple_design = design + simple_incidence_system\n\ntext \\<open>Additional reasoning about when something is not simple\\<close>\ncontext incidence_system\nbegin\nlemma simple_not_multiplicity: \"b \\<in># \\<B> \\<Longrightarrow> multiplicity  b > 1 \\<Longrightarrow> \\<not> simple_incidence_system \\<V> \\<B>\"\n  using simple_incidence_system_def simple_incidence_system_axioms_def by (metis nat_neq_iff) \n\nlemma multiple_not_simple: \n  assumes \"n > 1\"\n  assumes \"\\<B> \\<noteq> {#}\"\n  shows \"\\<not> simple_incidence_system \\<V> (multiple_blocks n)\"\nproof (rule ccontr, simp)\n  assume \"simple_incidence_system \\<V> (multiple_blocks n)\"\n  then have \"\\<And> bl. bl \\<in># \\<B> \\<Longrightarrow> count (multiple_blocks n) bl = 1\"\n    using assms(1) elem_in_original_in_repeat\n    by (metis not_gr_zero not_less_zero simple_incidence_system.simple)\n  thus False using assms by auto \nqed\n\nend\n\nsubsection \\<open>Proper Designs\\<close>\ntext \\<open>Many types of designs rely on parameter conditions that only make sense for non-empty designs. \ni.e. designs with at least one block, and therefore given well-formed condition, at least one point. \nTo this end we define the notion of a \"proper\" design\\<close>\n\nlocale proper_design = design + \n  assumes b_non_zero: \"\\<b> \\<noteq> 0\"\nbegin\n\nlemma is_proper: \"proper_design \\<V> \\<B>\" by intro_locales\n\nlemma v_non_zero: \"\\<v> > 0\"\n  using b_non_zero v_eq0_imp_b_eq_0 by auto\n\nlemma b_positive: \"\\<b> > 0\" using b_non_zero\n  by (simp add: nonempty_has_size)\n\nlemma design_points_nempty: \"\\<V> \\<noteq> {}\"\n  using v_non_zero by auto \n\nlemma design_blocks_nempty: \"\\<B> \\<noteq> {#}\"\n  using b_non_zero by auto\n\nend\n\ntext \\<open>Intro rules for a proper design\\<close>\nlemma (in design) proper_designI[intro]: \"\\<b> \\<noteq> 0 \\<Longrightarrow> proper_design \\<V> \\<B>\"\n  by (unfold_locales) simp\n\nlemma proper_designII[intro]: \n  assumes \"design V B\" and \"B \\<noteq> {#}\" \n  shows \"proper_design V B\"\nproof -\n  interpret des: design V B using assms by simp\n  show ?thesis using assms by unfold_locales simp\nqed\n\ntext \\<open>Reasoning on construction closure for proper designs\\<close>\ncontext proper_design\nbegin\n\nlemma multiple_proper_design: \n  assumes \"n > 0\"\n  shows \"proper_design \\<V> (multiple_blocks n)\"\n  using multiple_is_design assms design_blocks_nempty multiple_block_in\n  by (metis block_set_nempty_imp_block_ex empty_iff proper_designII set_mset_empty) \n\nlemma complement_proper_design: \n  assumes \"\\<And> bl . bl \\<in># \\<B> \\<Longrightarrow> incomplete_block bl\"\n  shows \"proper_design \\<V> \\<B>\\<^sup>C\"\nproof -\n  interpret des: design \\<V> \"\\<B>\\<^sup>C\"\n    by (simp add: assms complement_design)  \n  show ?thesis using b_non_zero by (unfold_locales) auto\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/Design_Basics.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8757869916479466, "lm_q2_score": 0.819893335913536, "lm_q1q2_score": 0.718051918131915}}
{"text": "(* Title:      Orders\n   Author:     Insa Stucke (ist@informatik.uni-kiel.de)\n*)\n\nsection {* Relation Algebra Orders *}\n\ntheory Relation_Algebra_Orders \n    imports Main \"$AFP/Relation_Algebra/Relation_Algebra\" \nbegin \n\ncontext relation_algebra\nbegin\n  \ntext {* In this theory we define and prove some basic facts about order related relations. *}\n\n\ndefinition is_refl :: \"'a \\<Rightarrow> bool\"\n  where \"is_refl x \\<equiv> 1' \\<le> x\"\n\ndefinition is_trans :: \"'a \\<Rightarrow> bool\"\n  where \"is_trans x \\<equiv> x ; x \\<le> x\"\n\ndefinition is_preorder :: \"'a \\<Rightarrow> bool\"\n  where \"is_preorder x \\<equiv> is_refl x \\<and> is_trans x\"\n\ndefinition is_antisym :: \"'a \\<Rightarrow> bool\"\n  where \"is_antisym x \\<equiv> x \\<cdot> x\\<^sup>\\<smile> \\<le> 1'\"\n\ndefinition is_order :: \"'a \\<Rightarrow> bool\"\n  where \"is_order x \\<equiv> is_refl x \\<and> is_antisym x \\<and> is_trans x\"\n\ndefinition is_irrefl :: \"'a \\<Rightarrow> bool\"\n  where \"is_irrefl x \\<equiv> x \\<le> -1'\"\n\ndefinition is_asym :: \"'a \\<Rightarrow> bool\"\n  where \"is_asym x \\<equiv> x \\<cdot> x\\<^sup>\\<smile> \\<le> 0\"\n\ndefinition is_lin :: \"'a \\<Rightarrow> bool\"\n  where \"is_lin x \\<equiv> x + x\\<^sup>\\<smile> = 1\"\n\ndefinition is_strictorder :: \"'a \\<Rightarrow> bool\"\n  where \"is_strictorder x \\<equiv> is_asym x \\<and> is_trans x\"\n\n\n\nlemma reflone: \"is_refl 1'\"\nby (simp add: is_refl_def)\n\nlemma transone: \"is_trans 1'\"\nby (simp add: is_trans_def)\n\nlemma antisymmone: \"is_antisym 1'\"\nby (simp add: is_antisym_def)\n\nlemma preorderone: \"is_preorder 1'\"\nby (simp add: is_preorder_def reflone transone)\n\nlemma orderone: \"is_order 1'\"\nby (simp add: antisymmone is_order_def reflone transone)\n\n\n\nlemma reflcup: \"is_refl x \\<and> is_refl y \\<longrightarrow> is_refl (x + y)\"\nby (simp add: is_refl_def le_supI2)\n\nlemma reflcap: \"is_refl x \\<and> is_refl y \\<longrightarrow> is_refl (x \\<cdot> y)\"\nby (simp add: is_refl_def)\n\nlemma reflcomp: \"is_refl x \\<and> is_refl y \\<longrightarrow> is_refl (x ; y)\"\nby (metis is_refl_def mult_oner subdistl sup.boundedE sup_absorb2)\n\nlemma transcap: \"is_trans x \\<and> is_trans y \\<longrightarrow> is_trans (x \\<cdot> y)\"\nby (meson is_trans_def inf_mono meet_interchange order.trans)\n\nlemma preordercap: \"is_preorder x \\<and> is_preorder y \\<longrightarrow> is_preorder (x \\<cdot> y)\"\nby (simp add: is_preorder_def reflcap transcap)\n\nlemma antisymcap: \"is_antisym x \\<and> is_antisym y \\<longrightarrow> is_antisym (x \\<cdot> y)\"\nby (meson is_antisym_def conv_self_conjugate_var dual_order.trans g_subdist inf.boundedI inf.cobounded1 inf.cobounded2)\n\nlemma ordercap: \"is_order x \\<and> is_order y \\<longrightarrow> is_order (x \\<cdot> y)\"\nby (simp add: antisymcap is_order_def reflcap transcap)\n\nlemma irreflcup: \"is_irrefl x \\<and> is_irrefl y \\<longrightarrow> is_irrefl (x + y)\"\nby (simp add: is_irrefl_def)\n\nlemma irreflcap: \"is_irrefl x \\<and> is_irrefl y \\<longrightarrow> is_irrefl (x \\<cdot> y)\"\nby (simp add: is_irrefl_def inf.coboundedI1)\n\n\nlemma aux_refl_anti_lin: \n  assumes \"is_refl x\" \n  and \"is_antisym x\" \n  and \"is_lin x\" \n  shows \"x\\<^sup>\\<smile> = 1' + -x\"\nproof (rule antisym)\n  show \"x\\<^sup>\\<smile> \\<le> 1' + -x\"\n    using assms(2) is_antisym_def galois_2 inf_commute by auto\n  show \"1' + -x \\<le> x\\<^sup>\\<smile>\"\n    using assms(1) assms(3) is_lin_def is_refl_def conv_iso galois_aux4 by fastforce\nqed\n\nlemma aux_card_lin_ord: \"is_refl x \\<and> is_antisym x \\<longrightarrow> x \\<cdot> x\\<^sup>\\<smile> = 1'\"\n  using is_antisym_def is_refl_def antisym conv_iso by fastforce\n\nend\n\nend", "meta": {"author": "insastucke", "repo": "RAProgramVerification", "sha": "e435b2d59ddd3c1e5ba94a38a532a29dc040c015", "save_path": "github-repos/isabelle/insastucke-RAProgramVerification", "path": "github-repos/isabelle/insastucke-RAProgramVerification/RAProgramVerification-e435b2d59ddd3c1e5ba94a38a532a29dc040c015/CardinalitiesInIsabelle/Relation_Algebra_Cardinalities/Relation_Algebra_Orders.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797148356995, "lm_q2_score": 0.7879311881731379, "lm_q1q2_score": 0.7179469153497536}}
{"text": "\n(* Propiedad de los conjuntos finitos de n\u00fameros naturales *)\n\n(*<*) \ntheory ConjuntosFinitos \nimports Main \"HOL-Library.LaTeXsugar\" \"HOL-Library.OptionalSugar\" \nbegin\n(*>*) \n\nsection \\<open>Propiedad de los conjuntos finitos de n\u00famero naturales \\<close>\n\n\n\nsubsection \\<open>Demostraci\u00f3n en lenguaje natural \\<close>\n\ntext \\<open>El siguiente teorema es una propiedad que verifican todos los \n  conjuntos finitos de n\u00fameros naturales. Se ha estudiado en el \n  \\href{http://bit.ly/2XBW6n2}{tema 10} de la asignatura de LMF de \n  tercer curso del grado en Matem\u00e1ticas. Su enunciado es el siguiente:\n\n  \\begin{teorema} \n    Sea S un conjunto finito de n\u00fameros naturales. Entonces todos los\n    elementos de S son menores o iguales que la suma de los elementos de\n    S; es decir,\n    $$\\forall m \\in S \\Longrightarrow m \\leq \\sum S$$ \n    donde $\\sum S $ denota la suma de todos los elementos de S.\n  \\end{teorema} \n\nPrimero se debe notar que podemos dar una definici\u00f3n inductiva de\n conjunto finito, lo que conlleva un esquema de inducci\u00f3n asociado.\n\n\\begin{definicion}\\label{defconj}\nLa definici\u00f3n inductiva de un conjunto finito es:\n\\begin{itemize}\n\\item $\\emptyset$ es finito.\n\\item Si $A$ es un conjunto finito y $x$ un elemento entonces $A\n \\cup \\{x\\}$ es un conjunto finito.\n\\end{itemize}\n\\end{definicion}\n\nDe esta construcci\u00f3n se obtiene un esquema de inducci\u00f3n. Para ello sea\n $\\varphi$ una propiedad sobre conjuntos finitos. El esquema\nde inducci\u00f3n viene dado por: \n\n\nSi se verifica: \n\\begin{enumerate}\n\\item $\\varphi(\\emptyset).$\n\\item $\\forall A$ finito  tal que $\\varphi(A)$ y  $\\forall x$ \n entonces $\\varphi(A \\cup \\{x\\}).$ \n  \\end{enumerate}\n\nEntonces $\\forall A$ finito se verifica $\\varphi(A).$\n\n\n\n  \\begin{demostracion}\n  La demostraci\u00f3n del teorema la haremos por inducci\u00f3n sobre conjuntos\n  finitos.\n\n  (Base de la inducci\u00f3n) El caso $S = \\emptyset$ es trivial.\n\n  (Paso de la inducci\u00f3n) Supongamos que se verifica el teorema para un\n  conjunto finito de n\u00fameros naturales, que se denotar\u00e1 por $S$ y sea \n  $a$ un elemento. Vamos a demostrarlo para $S \\cup \\{a\\}.$\n \n  Sea $a \\in \\Bbb{N}$ tal que $a \\notin S,$ ya que si $a \\in S$ se \n  tendr\u00eda probado el teorema. Luego hay que probar que: \n  $$\\forall n \\in S \\cup \\{a\\} \\Longrightarrow \n    n \\leq \\sum (S \\cup \\{a\\})$$\n\n\n  Distingamos dos casos ahora:\n\n  Caso 1: $n = a$.\n\n  Si $n = a$, se tiene que:\n\n  $$n = a \\leq a + \\sum S = \\sum (S \\cup \\{a\\}).$$\n\n  Caso 2: $n \\neq a.$\n\n  Si $n \\neq a,$ tenemos que $n \\in S,$ luego usando la hip\u00f3tesis de\n  inducci\u00f3n:\n  $$n \\leq \\sum S \\leq \\sum S + a = \\sum (S \\cup \\{a\\}).$$\n  \\end{demostracion}\n\n  En la demostraci\u00f3n del teorema hemos usado un resultado, que vamos a\n  probar en Isabelle despu\u00e9s de la especificaci\u00f3n del teorema;\n  el resultado es $\\sum S + a = \\sum (S \\cup \\{ a\\})$.\\<close>\n\nsubsection \\<open>Especificaci\u00f3n en Isabelle/HOL \\<close>\n\ntext  \\<open>Para la especificaci\u00f3n del teorema en Isabelle, primero \nconsideremos la definici\u00f3n de conjunto finito ya definida en Isabelle.\n\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 \\<close>\n\ntext \\<open>\nEsta definici\u00f3n de conjunto finito es una definici\u00f3n inductiva en \nIsabelle, equivalente a la Definici\u00f3n \\ref{defconj} en lenguaje\nnatural. Esta definici\u00f3n genera autom\u00e1ticamente el siguiente esquema de\n inducci\u00f3n en Isabelle: \\<close>\n\ntext \\<open>\n \\begin{itemize}\n  \\item[] @{thm[mode=Def] finite.induct} \\hfill (@{text finite.induct})\n  \\end{itemize}   \n    \\<close>     \n\ntext \\<open> Tambi\u00e9n se debe notar que  @{text \"finite S \"} indica que un \nconjunto $S$ es finito  y definir la funci\u00f3n @{text \"sumaConj\"} tal que\n  @{text \"sumaConj n\"} es la suma de todos los elementos de S.\n\\<close>\n\n\n\ndefinition sumaConj :: \"nat set \\<Rightarrow> nat\" where\n  \"sumaConj S \\<equiv> \\<Sum>S\"\n\ntext \\<open> Donde $\\sum$ ya se encuentra definido en Isabelle, pero se \nrenombra de la siguiente forma:\n\n\nabbreviation Sum (\"$\\sum$\") \\\\\n  where \"$\\sum \\equiv$  sum $(\\lambda x. x)$\" \\<close>\n\n\n\ntext \\<open>El enunciado del teorema es el siguiente : \\<close>\n\n\nlemma \"finite S \\<Longrightarrow> \\<forall>x \\<in> S. x \\<le> sumaConj S\"\n  oops \n\ntext \\<open>Vamos a demostrar primero el lema enunciado anteriormente \\<close>\n\nlemma aux_propiedad_conjuntos_finitos:\n  assumes \"finite S\"\n    \"x \\<notin> S\" \n  shows \"x + sumaConj S = sumaConj (insert x S)\"\nproof -\n  have \"x + sumaConj S = x + \\<Sum>S\"\n    by (simp only: sumaConj_def)\n  also have \"\\<dots> = sum (\\<lambda>x. x) (insert x S)\" \n    using assms \n    by (rule sum.insert[THEN sym])\n   also have \"\\<dots> = sumaConj (insert x S)\"\n    by (simp only: sumaConj_def )\n  finally show ?thesis\n    by this\nqed\n\n\ntext \\<open>En la demostraci\u00f3n del lema anterior se ha usado \n  @{term\"sumConj_def\"}, que hace referencia a la definici\u00f3n sumaConj que\n  hemos hecho anteriormente.\n\n\nVamos a presentar diferentes formas de demostraci\u00f3n:\\<close>\n\nsubsection \\<open>Demostraci\u00f3n autom\u00e1tica\\<close>\n\ntext \\<open>La demostraci\u00f3n autom\u00e1tica es:\\<close>\n\nlemma \"finite S \\<Longrightarrow> \\<forall>x\\<in>S. x \\<le> sumaConj S\"\n  by (induct rule: finite_induct)\n     (auto simp add: sumaConj_def)\n\nsubsection \\<open>Demostraci\u00f3n detallada\\<close>\n\ntext \\<open>La demostraci\u00f3n declarativa es: \\<close>\n\nlemma sumaConj_acota: \n  \"finite S \\<Longrightarrow> \\<forall>x\\<in>S. x \\<le> sumaConj S\"\nproof (induct rule: finite_induct)\n  show \"\\<forall>x \\<in> {}. x \\<le> sumaConj {}\"  \n    by (simp only: ball_empty)\nnext\n  fix x and F\n  assume fF: \"finite F\" \n    and xF: \"x \\<notin> F\" \n    and HI: \"\\<forall> x\\<in>F. x \\<le> sumaConj F\"\n  show \"\\<forall>y \\<in> insert x F. y \\<le> sumaConj (insert x F)\"\n  proof \n    fix y \n    assume \"y \\<in> insert x F\"\n    then have \"y = x \\<or> y \\<in> F\"\n      by (simp only: insert_iff)\n    then show \"y \\<le> sumaConj (insert x F)\"\n    proof \n      assume \"y = x\"\n      then have \"y \\<le> x + (sumaConj F)\" \n        by (simp only: le_add_same_cancel1)\n      also have \"\\<dots> = sumaConj (insert x F)\"  \n        using fF xF \n        by (rule aux_propiedad_conjuntos_finitos)  \n      finally show ?thesis \n        by this\n    next\n      assume \"y \\<in> F\" \n      then have \"y \\<le> sumaConj F\" \n        using HI \n        by (simp only: HI)\n      also have \"\\<dots> \\<le> x + (sumaConj F)\"\n        by (simp only: le_add_same_cancel2)\n      also have \"\\<dots> = sumaConj (insert x F)\" \n        using fF xF\n        by (rule aux_propiedad_conjuntos_finitos)\n      finally show ?thesis \n        by this\n    qed\n  qed\nqed\n\n\n(*<*)\nend\n(*>*)\n", "meta": {"author": "Carnunfer", "repo": "TFG", "sha": "d9f0989088f76442db615c1820f19fb3fad72541", "save_path": "github-repos/isabelle/Carnunfer-TFG", "path": "github-repos/isabelle/Carnunfer-TFG/TFG-d9f0989088f76442db615c1820f19fb3fad72541/ConjuntosFinitos.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246035907933, "lm_q2_score": 0.861538211208597, "lm_q1q2_score": 0.7179409883337252}}
{"text": "section \"Arithmetic and Boolean Expressions\"\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\ntheory Chapter3AExp 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\\<open>\\snip{AExpaexpdef}{2}{1}{%\\<close>\ndatatype aexp = N int | V vname | Plus aexp aexp | Times aexp aexp\ntext_raw\\<open>}%endsnip\\<close>\n\n(* Extend aval to include Times *)\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\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 @{text \"\\<lambda>x. 0\"} 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 @{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\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 *)\n  done\n\n(* Define times to eliminate 0s and 1s appropriately *)\nfun times :: \"aexp \\<Rightarrow> aexp \\<Rightarrow> aexp\" where\n\"times (N n1) (N n2) = N (n1 * n2)\" |\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 a1 a2 = Times a1 a2\"\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\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\nvalue \"asimp (Plus (Plus (N 0) (N 0)) (Plus (V ''x'') (N 0)))\"\n\nvalue \"asimp (Times (Times (N 0) (N 0)) (Times (V ''x'') (N 0)))\"\nvalue \"asimp (Times (Times (N 1) (N 1)) (Times (V ''x'') (N 0)))\"\nvalue \"asimp (Times (Times (N 0) (N 0)) (Times (V ''x'') (N 1)))\"\nvalue \"asimp (Times (Times (N 1) (N 1)) (Times (V ''x'') (N 1)))\"\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": "rasheedja", "repo": "concrete-semantics", "sha": "65997b65adccf690f076a79291aa643e2d1a9d43", "save_path": "github-repos/isabelle/rasheedja-concrete-semantics", "path": "github-repos/isabelle/rasheedja-concrete-semantics/concrete-semantics-65997b65adccf690f076a79291aa643e2d1a9d43/Chapter3AExp.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8615382094310357, "lm_q2_score": 0.8333246015211008, "lm_q1q2_score": 0.7179409850693205}}
{"text": "(*  Title:      HOL/Fun_Def.thy\n    Author:     Alexander Krauss, TU Muenchen\n*)\n\nsection \\<open>Function Definitions and Termination Proofs\\<close>\n\ntheory Fun_Def\n  imports Basic_BNF_LFPs Partial_Function SAT\n  keywords\n    \"function\" \"termination\" :: thy_goal and\n    \"fun\" \"fun_cases\" :: thy_decl\nbegin\n\nsubsection \\<open>Definitions with default value\\<close>\n\ndefinition THE_default :: \"'a \\<Rightarrow> ('a \\<Rightarrow> bool) \\<Rightarrow> 'a\"\n  where \"THE_default d P = (if (\\<exists>!x. P x) then (THE x. P x) else d)\"\n\nlemma THE_defaultI': \"\\<exists>!x. P x \\<Longrightarrow> P (THE_default d P)\"\n  by (simp add: theI' THE_default_def)\n\nlemma THE_default1_equality: \"\\<exists>!x. P x \\<Longrightarrow> P a \\<Longrightarrow> THE_default d P = a\"\n  by (simp add: the1_equality THE_default_def)\n\nlemma THE_default_none: \"\\<not> (\\<exists>!x. P x) \\<Longrightarrow> THE_default d P = d\"\n  by (simp add: THE_default_def)\n\n\nlemma fundef_ex1_existence:\n  assumes f_def: \"f \\<equiv> (\\<lambda>x::'a. THE_default (d x) (\\<lambda>y. G x y))\"\n  assumes ex1: \"\\<exists>!y. G x y\"\n  shows \"G x (f x)\"\n  apply (simp only: f_def)\n  apply (rule THE_defaultI')\n  apply (rule ex1)\n  done\n\nlemma fundef_ex1_uniqueness:\n  assumes f_def: \"f \\<equiv> (\\<lambda>x::'a. THE_default (d x) (\\<lambda>y. G x y))\"\n  assumes ex1: \"\\<exists>!y. G x y\"\n  assumes elm: \"G x (h x)\"\n  shows \"h x = f x\"\n  apply (simp only: f_def)\n  apply (rule THE_default1_equality [symmetric])\n   apply (rule ex1)\n  apply (rule elm)\n  done\n\nlemma fundef_ex1_iff:\n  assumes f_def: \"f \\<equiv> (\\<lambda>x::'a. THE_default (d x) (\\<lambda>y. G x y))\"\n  assumes ex1: \"\\<exists>!y. G x y\"\n  shows \"(G x y) = (f x = y)\"\n  apply (auto simp:ex1 f_def THE_default1_equality)\n  apply (rule THE_defaultI')\n  apply (rule ex1)\n  done\n\nlemma fundef_default_value:\n  assumes f_def: \"f \\<equiv> (\\<lambda>x::'a. THE_default (d x) (\\<lambda>y. G x y))\"\n  assumes graph: \"\\<And>x y. G x y \\<Longrightarrow> D x\"\n  assumes \"\\<not> D x\"\n  shows \"f x = d x\"\nproof -\n  have \"\\<not>(\\<exists>y. G x y)\"\n  proof\n    assume \"\\<exists>y. G x y\"\n    then have \"D x\" using graph ..\n    with \\<open>\\<not> D x\\<close> show False ..\n  qed\n  then have \"\\<not>(\\<exists>!y. G x y)\" by blast\n  then show ?thesis\n    unfolding f_def by (rule THE_default_none)\nqed\n\ndefinition in_rel_def[simp]: \"in_rel R x y \\<equiv> (x, y) \\<in> R\"\n\nlemma wf_in_rel: \"wf R \\<Longrightarrow> wfP (in_rel R)\"\n  by (simp add: wfP_def)\n\nML_file \"Tools/Function/function_core.ML\"\nML_file \"Tools/Function/mutual.ML\"\nML_file \"Tools/Function/pattern_split.ML\"\nML_file \"Tools/Function/relation.ML\"\nML_file \"Tools/Function/function_elims.ML\"\n\nmethod_setup relation = \\<open>\n  Args.term >> (fn t => fn ctxt => SIMPLE_METHOD' (Function_Relation.relation_infer_tac ctxt t))\n\\<close> \"prove termination using a user-specified wellfounded relation\"\n\nML_file \"Tools/Function/function.ML\"\nML_file \"Tools/Function/pat_completeness.ML\"\n\nmethod_setup pat_completeness = \\<open>\n  Scan.succeed (SIMPLE_METHOD' o Pat_Completeness.pat_completeness_tac)\n\\<close> \"prove completeness of (co)datatype patterns\"\n\nML_file \"Tools/Function/fun.ML\"\nML_file \"Tools/Function/induction_schema.ML\"\n\nmethod_setup induction_schema = \\<open>\n  Scan.succeed (Method.CONTEXT_TACTIC oo Induction_Schema.induction_schema_tac)\n\\<close> \"prove an induction principle\"\n\n\nsubsection \\<open>Measure functions\\<close>\n\ninductive is_measure :: \"('a \\<Rightarrow> nat) \\<Rightarrow> bool\"\n  where is_measure_trivial: \"is_measure f\"\n\nnamed_theorems measure_function \"rules that guide the heuristic generation of measure functions\"\nML_file \"Tools/Function/measure_functions.ML\"\n\nlemma measure_size[measure_function]: \"is_measure size\"\n  by (rule is_measure_trivial)\n\nlemma measure_fst[measure_function]: \"is_measure f \\<Longrightarrow> is_measure (\\<lambda>p. f (fst p))\"\n  by (rule is_measure_trivial)\n\nlemma measure_snd[measure_function]: \"is_measure f \\<Longrightarrow> is_measure (\\<lambda>p. f (snd p))\"\n  by (rule is_measure_trivial)\n\nML_file \"Tools/Function/lexicographic_order.ML\"\n\nmethod_setup lexicographic_order = \\<open>\n  Method.sections clasimp_modifiers >>\n  (K (SIMPLE_METHOD o Lexicographic_Order.lexicographic_order_tac false))\n\\<close> \"termination prover for lexicographic orderings\"\n\n\nsubsection \\<open>Congruence rules\\<close>\n\nlemma let_cong [fundef_cong]: \"M = N \\<Longrightarrow> (\\<And>x. x = N \\<Longrightarrow> f x = g x) \\<Longrightarrow> Let M f = Let N g\"\n  unfolding Let_def by blast\n\nlemmas [fundef_cong] =\n  if_cong image_cong INF_cong SUP_cong\n  bex_cong ball_cong imp_cong map_option_cong Option.bind_cong\n\nlemma split_cong [fundef_cong]:\n  \"(\\<And>x y. (x, y) = q \\<Longrightarrow> f x y = g x y) \\<Longrightarrow> p = q \\<Longrightarrow> case_prod f p = case_prod g q\"\n  by (auto simp: split_def)\n\nlemma comp_cong [fundef_cong]: \"f (g x) = f' (g' x') \\<Longrightarrow> (f \\<circ> g) x = (f' \\<circ> g') x'\"\n  by (simp only: o_apply)\n\n\nsubsection \\<open>Simp rules for termination proofs\\<close>\n\ndeclare\n  trans_less_add1[termination_simp]\n  trans_less_add2[termination_simp]\n  trans_le_add1[termination_simp]\n  trans_le_add2[termination_simp]\n  less_imp_le_nat[termination_simp]\n  le_imp_less_Suc[termination_simp]\n\nlemma size_prod_simp[termination_simp]: \"size_prod f g p = f (fst p) + g (snd p) + Suc 0\"\n  by (induct p) auto\n\n\nsubsection \\<open>Decomposition\\<close>\n\nlemma less_by_empty: \"A = {} \\<Longrightarrow> A \\<subseteq> B\"\n  and union_comp_emptyL: \"A O C = {} \\<Longrightarrow> B O C = {} \\<Longrightarrow> (A \\<union> B) O C = {}\"\n  and union_comp_emptyR: \"A O B = {} \\<Longrightarrow> A O C = {} \\<Longrightarrow> A O (B \\<union> C) = {}\"\n  and wf_no_loop: \"R O R = {} \\<Longrightarrow> wf R\"\n  by (auto simp add: wf_comp_self [of R])\n\n\nsubsection \\<open>Reduction pairs\\<close>\n\ndefinition \"reduction_pair P \\<longleftrightarrow> wf (fst P) \\<and> fst P O snd P \\<subseteq> fst P\"\n\nlemma reduction_pairI[intro]: \"wf R \\<Longrightarrow> R O S \\<subseteq> R \\<Longrightarrow> reduction_pair (R, S)\"\n  by (auto simp: reduction_pair_def)\n\nlemma reduction_pair_lemma:\n  assumes rp: \"reduction_pair P\"\n  assumes \"R \\<subseteq> fst P\"\n  assumes \"S \\<subseteq> snd P\"\n  assumes \"wf S\"\n  shows \"wf (R \\<union> S)\"\nproof -\n  from rp \\<open>S \\<subseteq> snd P\\<close> have \"wf (fst P)\" \"fst P O S \\<subseteq> fst P\"\n    unfolding reduction_pair_def by auto\n  with \\<open>wf S\\<close> have \"wf (fst P \\<union> S)\"\n    by (auto intro: wf_union_compatible)\n  moreover from \\<open>R \\<subseteq> fst P\\<close> have \"R \\<union> S \\<subseteq> fst P \\<union> S\" by auto\n  ultimately show ?thesis by (rule wf_subset)\nqed\n\ndefinition \"rp_inv_image = (\\<lambda>(R,S) f. (inv_image R f, inv_image S f))\"\n\nlemma rp_inv_image_rp: \"reduction_pair P \\<Longrightarrow> reduction_pair (rp_inv_image P f)\"\n  unfolding reduction_pair_def rp_inv_image_def split_def by force\n\n\nsubsection \\<open>Concrete orders for SCNP termination proofs\\<close>\n\ndefinition \"pair_less = less_than <*lex*> less_than\"\ndefinition \"pair_leq = pair_less^=\"\ndefinition \"max_strict = max_ext pair_less\"\ndefinition \"max_weak = max_ext pair_leq \\<union> {({}, {})}\"\ndefinition \"min_strict = min_ext pair_less\"\ndefinition \"min_weak = min_ext pair_leq \\<union> {({}, {})}\"\n\nlemma wf_pair_less[simp]: \"wf pair_less\"\n  by (auto simp: pair_less_def)\n\ntext \\<open>Introduction rules for \\<open>pair_less\\<close>/\\<open>pair_leq\\<close>\\<close>\nlemma pair_leqI1: \"a < b \\<Longrightarrow> ((a, s), (b, t)) \\<in> pair_leq\"\n  and pair_leqI2: \"a \\<le> b \\<Longrightarrow> s \\<le> t \\<Longrightarrow> ((a, s), (b, t)) \\<in> pair_leq\"\n  and pair_lessI1: \"a < b  \\<Longrightarrow> ((a, s), (b, t)) \\<in> pair_less\"\n  and pair_lessI2: \"a \\<le> b \\<Longrightarrow> s < t \\<Longrightarrow> ((a, s), (b, t)) \\<in> pair_less\"\n  by (auto simp: pair_leq_def pair_less_def)\n\ntext \\<open>Introduction rules for max\\<close>\nlemma smax_emptyI: \"finite Y \\<Longrightarrow> Y \\<noteq> {} \\<Longrightarrow> ({}, Y) \\<in> max_strict\"\n  and smax_insertI:\n    \"y \\<in> Y \\<Longrightarrow> (x, y) \\<in> pair_less \\<Longrightarrow> (X, Y) \\<in> max_strict \\<Longrightarrow> (insert x X, Y) \\<in> max_strict\"\n  and wmax_emptyI: \"finite X \\<Longrightarrow> ({}, X) \\<in> max_weak\"\n  and wmax_insertI:\n    \"y \\<in> YS \\<Longrightarrow> (x, y) \\<in> pair_leq \\<Longrightarrow> (XS, YS) \\<in> max_weak \\<Longrightarrow> (insert x XS, YS) \\<in> max_weak\"\n  by (auto simp: max_strict_def max_weak_def elim!: max_ext.cases)\n\ntext \\<open>Introduction rules for min\\<close>\nlemma smin_emptyI: \"X \\<noteq> {} \\<Longrightarrow> (X, {}) \\<in> min_strict\"\n  and smin_insertI:\n    \"x \\<in> XS \\<Longrightarrow> (x, y) \\<in> pair_less \\<Longrightarrow> (XS, YS) \\<in> min_strict \\<Longrightarrow> (XS, insert y YS) \\<in> min_strict\"\n  and wmin_emptyI: \"(X, {}) \\<in> min_weak\"\n  and wmin_insertI:\n    \"x \\<in> XS \\<Longrightarrow> (x, y) \\<in> pair_leq \\<Longrightarrow> (XS, YS) \\<in> min_weak \\<Longrightarrow> (XS, insert y YS) \\<in> min_weak\"\n  by (auto simp: min_strict_def min_weak_def min_ext_def)\n\ntext \\<open>Reduction Pairs.\\<close>\n\nlemma max_ext_compat:\n  assumes \"R O S \\<subseteq> R\"\n  shows \"max_ext R O (max_ext S \\<union> {({}, {})}) \\<subseteq> max_ext R\"\n  using assms\n  apply auto\n  apply (elim max_ext.cases)\n  apply rule\n     apply auto[3]\n  apply (drule_tac x=xa in meta_spec)\n  apply simp\n  apply (erule bexE)\n  apply (drule_tac x=xb in meta_spec)\n  apply auto\n  done\n\nlemma max_rpair_set: \"reduction_pair (max_strict, max_weak)\"\n  unfolding max_strict_def max_weak_def\n  apply (intro reduction_pairI max_ext_wf)\n   apply simp\n  apply (rule max_ext_compat)\n  apply (auto simp: pair_less_def pair_leq_def)\n  done\n\nlemma min_ext_compat:\n  assumes \"R O S \\<subseteq> R\"\n  shows \"min_ext R O  (min_ext S \\<union> {({},{})}) \\<subseteq> min_ext R\"\n  using assms\n  apply (auto simp: min_ext_def)\n  apply (drule_tac x=ya in bspec, assumption)\n  apply (erule bexE)\n  apply (drule_tac x=xc in bspec)\n   apply assumption\n  apply auto\n  done\n\nlemma min_rpair_set: \"reduction_pair (min_strict, min_weak)\"\n  unfolding min_strict_def min_weak_def\n  apply (intro reduction_pairI min_ext_wf)\n   apply simp\n  apply (rule min_ext_compat)\n  apply (auto simp: pair_less_def pair_leq_def)\n  done\n\n\nsubsection \\<open>Tool setup\\<close>\n\nML_file \"Tools/Function/termination.ML\"\nML_file \"Tools/Function/scnp_solve.ML\"\nML_file \"Tools/Function/scnp_reconstruct.ML\"\nML_file \"Tools/Function/fun_cases.ML\"\n\nML_val \\<comment> \"setup inactive\"\n\\<open>\n  Context.theory_map (Function_Common.set_termination_prover\n    (K (ScnpReconstruct.decomp_scnp_tac [ScnpSolve.MAX, ScnpSolve.MIN, ScnpSolve.MS])))\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/Fun_Def.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8615382094310357, "lm_q2_score": 0.8333246015211008, "lm_q1q2_score": 0.7179409850693205}}
{"text": "theory 3\n  imports Main\nbegin\n  \n  (* exercise 2.3 *) \n  \n  (* this exercise can't appear in the same file as 2.2, because the nat type used in count would\n  then be different than the nat type used by the library-defined length *)\n  \nfun count :: \"'a \\<Rightarrow> 'a list \\<Rightarrow> nat\" where \n  \"count v Nil = 0\" \n| \"count v (Cons x xs) = (if v=x then Suc (count v xs) else count v xs)\"\n  \nvalue \"count (1::int) [1, 2, 1]\"\nvalue \"count (2::int) [1, 2, 1]\"\n  \nlemma count_leq_length: \"count v 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 (x # xs) e = Cons x (snoc xs e)\"\n  \nvalue \"snoc [1,2,4] 10 :: int list\"\n  \nfun reverse :: \"'a list \\<Rightarrow> 'a list\" where\n  \"reverse [] = []\"\n| \"reverse (x # xs) = snoc (reverse xs) x\"\n  \nvalue \"[1,2,3] @ [4,5] :: int list\"\n  \nlemma reverse_snoc_is_cons_reverse[simp]: \"reverse (snoc xs a) = a # (reverse xs)\"\n  apply(induction xs)\n   apply(auto)\n  done \n    \n    (* This needs lemma: reverse (snoc (reverse xs) a) = a # xs *)\nlemma reverse_reverse_is_id[simp]: \"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 \"6 div 2 :: int\"\nvalue \"5 div 2 :: int\"\nvalue \"1 div 2 :: int\"\n  \nlemma summation_formula_01[simp]: \"sum_upto n = (n * (n+1)) div 2\"\n  apply(induction n)\n   apply(auto)\n  done   \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 2/2.3.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382094310357, "lm_q2_score": 0.8333245973817158, "lm_q1q2_score": 0.7179409815030822}}
{"text": "theory ex01\n  imports Main\nbegin\n\nterm \"op+\"\n\nlemma \"a + b = b + (a :: nat)\"\n  by auto\n\nlemma \"a + (b + c) = (a + b) + (c::nat)\"\n  by auto\n\nterm \"Nil\"\nterm \"Cons a b\"\n\nfun count :: \"'a list \\<Rightarrow> 'a \\<Rightarrow> nat\" where\n  \"count [] _ = 0\"\n| \"count (x#xs) y = (if x=y then count xs y + 1 else count xs y)\"\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,3,4,2,2,2::int] 2\"\n\nfind_theorems \"length [] = _\"\nfind_theorems \"length (_ # _) =  _\"\n\nlemma \"count xs a \\<le> length xs\"\n  apply(induction xs)\n   apply(simp)\n  apply(simp)\n  done\n\nfun snoc :: \"'a list \\<Rightarrow> 'a \\<Rightarrow> 'a list\" where\n  \"snoc [] y = [y]\"\n| \"snoc (x # xs) y = x # snoc xs y\"\n\nlemma \"snoc xs x = xs@[x]\"\n  apply(induction xs) by auto\n\nfun reverse :: \"'a list \\<Rightarrow> 'a list\" where\n  \"reverse [] = []\"\n| \"reverse (x # xs) = snoc (reverse xs) x\"\n\nlemma aux: \"reverse (snoc xs x) = x # reverse xs\"\n  apply(induction xs) by auto\n\nlemma rev_rev[simp]: \"reverse (reverse xs) = xs\"\n  apply (induction xs)\n   apply (auto simp:aux)\n  done\n\nlemma \"reverse (reverse xs) = xs\"\n  apply(induction xs)\n   apply(auto simp:)\n  apply(subst aux)\n  apply auto\n  done\n\n\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/01/ex01.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382094310355, "lm_q2_score": 0.8333245891029456, "lm_q1q2_score": 0.7179409743706052}}
{"text": "theory ATC\nimports \"../FSM/FSM\"\nbegin\n\nsection \\<open> Adaptive test cases \\<close>\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 \\<open> Properties of ATC-reactions \\<close>\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 \\<open> Applicability \\<close>\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 \\<open> Application function IO \\<close>\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 \\<open> R-distinguishability \\<close>\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 \\<open> Response sets \\<close>\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 \\<open> Characterizing sets \\<close>\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 \\<open> Reduction over ATCs \\<close>\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 \\<open> Reduction over ATCs applied after input sequences \\<close>\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": "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/Adaptive_State_Counting/ATC/ATC.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8705972751232809, "lm_q2_score": 0.8244619306896955, "lm_q1q2_score": 0.7177743103013282}}
{"text": "theory Zp_Compact\nimports Padic_Int_Topology\nbegin\n\ncontext padic_integers\nbegin\n\nlemma res_ring_car: \n\"carrier (Zp_res_ring k) = {0..p ^ k - 1}\"\n  unfolding residue_ring_def by simp \n\ntext\\<open>The refinement of a sequence by a function $nat \\Rightarrow nat$\\<close>\ndefinition take_subseq :: \"(nat \\<Rightarrow> 'a) \\<Rightarrow> (nat \\<Rightarrow> nat) \\<Rightarrow> (nat \\<Rightarrow> 'a)\" where\n\"take_subseq s f = (\\<lambda>k. s (f k))\"\n\ntext\\<open>Predicate for increasing function on the natural numbers\\<close>\ndefinition is_increasing :: \"(nat \\<Rightarrow> nat) \\<Rightarrow> bool\" where\n\"is_increasing f = (\\<forall> n m::nat. n>m \\<longrightarrow> (f n) > (f m))\"\n\ntext\\<open>Elimination and introduction lemma for increasing functions\\<close>\nlemma is_increasingI:\n  assumes \"\\<And> n m::nat. n>m \\<Longrightarrow> (f n) > (f m)\"\n  shows \"is_increasing f\"\n  unfolding is_increasing_def \n  using assms \n  by blast \n\nlemma is_increasingE: \n  assumes \"is_increasing f\"\n  assumes \" n> m\"\n  shows \"f n > f m\"\n  using assms\n  unfolding is_increasing_def \n  by blast \n\ntext\\<open>The subsequence predicate\\<close>\ndefinition is_subseq_of :: \"(nat \\<Rightarrow> 'a) \\<Rightarrow> (nat \\<Rightarrow> 'a) \\<Rightarrow> bool\" where\n\"is_subseq_of s s' = (\\<exists>(f::nat \\<Rightarrow> nat). is_increasing f \\<and> s' = take_subseq s f)\"\n\ntext\\<open>Subsequence introduction lemma\\<close>\nlemma is_subseqI:\n  assumes \"is_increasing f\"\n  assumes \"s' = take_subseq s f\"\n  shows \"is_subseq_of s s'\"\n  using assms \n  unfolding is_subseq_of_def \n  by auto \n\nlemma is_subseq_ind:\n  assumes \"is_subseq_of s s'\"\n  shows \"\\<exists> l. s' k = s l\"\n  using assms\n  unfolding is_subseq_of_def  take_subseq_def by blast \n\nlemma is_subseq_closed: \n  assumes \"s \\<in> closed_seqs Zp\"\n  assumes \"is_subseq_of s s'\"\n  shows \"s' \\<in> closed_seqs Zp\"\n  apply(rule closed_seqs_memI)\n  using is_subseq_ind assms closed_seqs_memE \n  by metis\n\ntext\\<open>Given a sequence and a predicate, returns the function from nat to nat which represents\nthe increasing sequences of indices n on which P (s n) holds.\\<close>\n\nprimrec seq_filter :: \"(nat \\<Rightarrow>'a) \\<Rightarrow> ('a \\<Rightarrow> bool) \\<Rightarrow> nat \\<Rightarrow> nat\" where\n\"seq_filter s P (0::nat) = (LEAST k::nat. P (s k))\"|\n\"seq_filter s P (Suc n) = (LEAST k:: nat. (P (s k)) \\<and> k > (seq_filter s P n))\"   \n\nlemma seq_filter_pre_increasing:\n  assumes \"\\<forall>n::nat. \\<exists>m. m > n \\<and> P (s m)\"\n  shows \"seq_filter s P n < seq_filter s P (Suc n)\" \n  apply(auto)\nproof(induction n)\n  case 0\n  have \"\\<exists>k. P (s k)\" using assms(1) by blast\n  then have \"\\<exists>k::nat. (LEAST k::nat. (P (s k))) \\<ge> 0\" \n    by blast\n  obtain k where \"(LEAST k::nat. (P (s k))) = k\" by simp\n  have \"\\<exists>l. l = (LEAST l::nat. (P (s l) \\<and> l > k))\" \n    by simp\n  thus ?case\n    by (metis (no_types, lifting) LeastI assms)\nnext\n  case (Suc n)\n  then show ?case\n    by (metis (no_types, lifting) LeastI assms)\nqed\n\nlemma seq_filter_increasing:\n  assumes \"\\<forall>n::nat. \\<exists>m. m > n \\<and> P (s m)\"\n  shows \"is_increasing (seq_filter s P)\" \n  by (metis assms seq_filter_pre_increasing is_increasingI lift_Suc_mono_less) \n\ndefinition filtered_seq :: \"(nat \\<Rightarrow> 'a) \\<Rightarrow> ('a \\<Rightarrow> bool) \\<Rightarrow> (nat \\<Rightarrow> 'a)\" where\n\"filtered_seq s P = take_subseq s (seq_filter s P)\"\n\nlemma filter_exist:\n  assumes \"s \\<in> closed_seqs Zp\"\n  assumes \"\\<forall>n::nat. \\<exists>m. m > n \\<and> P (s m)\"\n  shows \"\\<And>m. n\\<le>m \\<Longrightarrow> P (s (seq_filter s P n))\"\nproof(induct n)\n  case 0\n  then show ?case \n    using LeastI assms(2) by force\nnext\n  case (Suc n)\n  then show ?case \n    by (smt LeastI assms(2) seq_filter.simps(2))\nqed\n\ntext\\<open>In a filtered sequence, every element satisfies the filtering predicate \\<close>\n\nlemma fil_seq_pred:\n  assumes \"s \\<in> closed_seqs Zp\"\n  assumes \"s' = filtered_seq s P\"\n  assumes \"\\<forall>n::nat. \\<exists>m. m > n \\<and> P (s m)\"\n  shows \"\\<And>m::nat. P (s' m)\" \nproof-\n  have \"\\<exists>k. P (s k)\" using assms(3) \n    by blast\n  fix m\n  obtain k where kdef: \"k = seq_filter s P m\" by auto \n  have \"\\<exists>k. P (s k)\" \n    using assms(3) by auto\n  then have \"P (s k)\" \n    by (metis (full_types) assms(1) assms(3) kdef le_refl less_imp_triv not_less_eq filter_exist )\n  then have \"s' m = s k\"\n    by (simp add: assms(2) filtered_seq_def kdef take_subseq_def)\n  hence \"P (s' m)\" \n    by (simp add: \\<open>P (s k)\\<close>)\n  thus \"\\<And>m. P (s' m)\" using  assms(2) assms(3) dual_order.strict_trans filter_exist filtered_seq_def\n      lessI less_Suc_eq_le take_subseq_def \n    by (metis (mono_tags, opaque_lifting) assms(1))    \nqed\n\ndefinition kth_res_equals :: \"nat \\<Rightarrow> int \\<Rightarrow> (padic_int  \\<Rightarrow> bool)\"  where\n\"kth_res_equals k n a = (a k = n)\"\n\n(*The characteristic function of the underlying set of a sequence*)\ndefinition indicator:: \"(nat \\<Rightarrow> 'a) \\<Rightarrow> ('a  \\<Rightarrow> bool)\" where\n\"indicator s a = (\\<exists>n::nat. s n = a)\"  \n\n\ntext\\<open>Choice function for a subsequence with constant kth residue. Could be made constructive by \nchoosing the LEAST n if we wanted.\\<close>\n\ndefinition const_res_subseq :: \"nat \\<Rightarrow> padic_int_seq \\<Rightarrow> padic_int_seq\"  where\n\"const_res_subseq k s = (SOME s'::(padic_int_seq). (\\<exists> n. is_subseq_of s s' \\<and> s' \n  = (filtered_seq s (kth_res_equals k n)) \\<and> (\\<forall>m. s' m k = n)))\" \n\ntext\\<open>The constant kth residue value for the sequence obtained by the previous function\\<close>\n\ndefinition const_res :: \"nat \\<Rightarrow> padic_int_seq \\<Rightarrow> int\"  where\n\"const_res k s = (THE n. (\\<forall> m. (const_res_subseq k s) m k = n))\" \n\ndefinition maps_to_n:: \"int \\<Rightarrow> (nat \\<Rightarrow> int) \\<Rightarrow> bool\" where\n\"maps_to_n n f = (\\<forall>(k::nat). f k \\<in> {0..n})\"\n\ndefinition drop_res :: \"int \\<Rightarrow> (nat \\<Rightarrow> int) \\<Rightarrow> (nat \\<Rightarrow> int)\" where\n\"drop_res k f n = (if (f n) = k then 0 else f n)\"\n \nlemma maps_to_nE:\n  assumes \"maps_to_n n f\"\n  shows \"(f k) \\<in> {0..n}\"\n  using assms\n  unfolding maps_to_n_def\n  by blast\n \nlemma maps_to_nI:\n  assumes \"\\<And>n. f n \\<in>{0 .. k}\"\n  shows \"maps_to_n k f\"\n  using assms maps_to_n_def by auto\n \n \nlemma maps_to_n_drop_res:\n  assumes \"maps_to_n (Suc n) f\"\n  shows \"maps_to_n n (drop_res (Suc n) f)\"\nproof-\n  fix k\n  have \"drop_res (Suc n) f k \\<in> {0..n}\"\n  proof(cases \"f k = Suc n\")\n    case True\n    then have \"drop_res (Suc n) f k = 0\"\n      unfolding drop_res_def by auto\n    then show ?thesis \n      using assms local.drop_res_def maps_to_n_def by auto\n  next\n    case False\n    then show ?thesis\n      using assms atLeast0_atMost_Suc maps_to_n_def drop_res_def\n      by auto\n  qed\n  then have \"\\<And>k. drop_res (Suc n) f k \\<in> {0..n}\" \n    using assms local.drop_res_def maps_to_n_def by auto\n    then show \"maps_to_n n (drop_res (Suc n) f)\" using maps_to_nI\n      using maps_to_n_def by blast\nqed\n \nlemma drop_res_eq_f:\n  assumes \"maps_to_n (Suc n) f\"\n  assumes \"\\<not> (\\<forall>m. \\<exists>n. n>m \\<and> (f n = (Suc k)))\"\n  shows \"\\<exists>N. \\<forall>n. n>N \\<longrightarrow> f n = drop_res (Suc k) f n\"\nproof-\n  have \"\\<exists>m. \\<forall>n. n \\<le> m \\<or> (f n) \\<noteq> (Suc k)\"\n    using assms\n    by (meson Suc_le_eq nat_le_linear)\n  then have \"\\<exists>m. \\<forall>n. n \\<le> m \\<or> (f n)  = drop_res (Suc k) f n\"\n    using drop_res_def by auto\n  then show ?thesis\n    by (meson less_Suc_eq_le order.asym)\nqed\n \nlemma maps_to_n_infinite_seq:\n  shows \"\\<And>f. maps_to_n (k::nat) f \\<Longrightarrow> \\<exists>l::int. \\<forall>m. \\<exists>n. n>m \\<and> (f n = l)\"\nproof(induction k)\n  case 0  \n  then have \"\\<And>n. f n \\<in> {0}\"\n    using maps_to_nE[of 0 f] by auto\n  then show \" \\<exists>l. \\<forall>m. \\<exists>n. m < n \\<and> f n = l\"\n    by blast\nnext\n  case (Suc k)\n  assume IH: \"\\<And>f. maps_to_n k f \\<Longrightarrow> \\<exists>l. \\<forall>m. \\<exists>n. m < n \\<and> f n = l\"\n  fix f\n  assume A: \"maps_to_n (Suc k) f\"\n  show \"\\<exists>l. \\<forall>m. \\<exists>n. n>m \\<and> (f n = l)\"\n  proof(cases \" \\<forall>m. \\<exists>n. n>m \\<and> (f n = (Suc k))\")\n    case True\n    then show ?thesis by blast\n  next\n    case False\n    then obtain N where N_def: \"\\<forall>n. n>N \\<longrightarrow> f n = drop_res (Suc k) f n\"\n      using drop_res_eq_f drop_res_def\n      by fastforce\n    have \" maps_to_n k (drop_res (Suc k) f) \"\n      using A maps_to_n_drop_res by blast      \n    then have \" \\<exists>l. \\<forall>m. \\<exists>n. m < n \\<and> (drop_res (Suc k) f) n = l\"\n      using IH by blast\n    then obtain l where l_def: \"\\<forall>m. \\<exists>n. m < n \\<and> (drop_res (Suc k) f) n = l\"\n      by blast\n    have \"\\<forall>m. \\<exists>n. n>m \\<and> (f n = l)\"\n      apply auto\n    proof-\n      fix m\n      show \"\\<exists>n>m. f n = l\"\n      proof-\n        obtain n where N'_def: \"(max m N) < n \\<and> (drop_res (Suc k) f) n = l\"\n          using l_def by blast\n        have \"f n =  (drop_res (Suc k) f) n\"\n          using N'_def N_def\n          by simp\n        then show ?thesis\n          using N'_def by auto\n      qed\n    qed\n    then show ?thesis\n      by blast\n  qed\nqed\n\nlemma int_nat_p_pow_minus:\n\"int (nat (p ^ k - 1)) = p ^ k - 1\"\n  by (simp add: prime prime_gt_0_int)\n\nlemma maps_to_n_infinite_seq_res_ring:\n\"\\<And>f. f \\<in> (UNIV::nat set) \\<rightarrow> carrier (Zp_res_ring k) \\<Longrightarrow> \\<exists>l. \\<forall>m. \\<exists>n. n>m \\<and> (f n = l)\"\napply(rule maps_to_n_infinite_seq[of \"nat (p^k - 1)\"])\n  unfolding maps_to_n_def res_ring_car int_nat_p_pow_minus by blast \n\ndefinition index_to_residue :: \"padic_int_seq \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> int\" where\n\"index_to_residue s k m = ((s m) k)\"\n\nlemma seq_maps_to_n:\n  assumes \"s \\<in> closed_seqs Zp\"\n  shows \"(index_to_residue s k) \\<in> UNIV \\<rightarrow> carrier (Zp_res_ring k)\"\nproof-\n  have A1: \"\\<And>m. (s m) \\<in> carrier Zp\" \n    using assms closed_seqs_memE by auto\n  have A2: \"\\<And>m. (s m k) \\<in> carrier (Zp_res_ring k)\" \n    using assms by (simp add: A1)\n  have \"\\<And>m. index_to_residue s k m = s m k\" \n    using index_to_residue_def \n    by auto    \n  thus \"index_to_residue s k \\<in> UNIV \\<rightarrow> carrier (residue_ring (p ^ k))\" \n    using A2 by simp\nqed    \n\nlemma seq_pr_inc:\n  assumes \"s \\<in> closed_seqs Zp\"\n  shows \"\\<exists>l. \\<forall>m. \\<exists>n > m. (kth_res_equals k l) (s n)\"\nproof-\n  fix k l m\n  have 0: \"(kth_res_equals k l) (s m) \\<Longrightarrow> (s m) k = l\" \n    by (simp add: kth_res_equals_def)\n  have 1: \"\\<And>k m. s m k = index_to_residue s k m\" \n    by (simp add: index_to_residue_def)\n  have 2: \"(index_to_residue s k) \\<in> UNIV \\<rightarrow> carrier (Zp_res_ring k)\" \n    using seq_maps_to_n assms by blast\n  have 3: \"\\<And>m. s m k \\<in> carrier (Zp_res_ring k)\" \n  proof- \n    fix m have 30: \"s m k = index_to_residue s k m\"\n      using 1 by blast \n    show \" s m k \\<in> carrier (Zp_res_ring k)\" \n      unfolding 30 using 2 by blast \n  qed\n  obtain j where j_def: \"j = nat (p^k - 1)\"\n    by blast \n  have j_to_int: \"int j = p^k - 1\"\n    using j_def  \n    by (simp add: prime prime_gt_0_int)   \n  have \"\\<exists>l. \\<forall>m. \\<exists>n. n > m \\<and>  (index_to_residue s k n = l)\" \n    by(rule maps_to_n_infinite_seq_res_ring[of _ k], rule seq_maps_to_n, rule assms) \n  hence \"\\<exists>l. \\<forall>m. \\<exists>n. n > m \\<and>  (s n k = l)\" \n    by (simp add: index_to_residue_def)\n  thus \"\\<exists>l. \\<forall>m. \\<exists>n > m. (kth_res_equals k l) (s n)\" \n    using kth_res_equals_def by auto\nqed\n\nlemma kth_res_equals_subseq:\n  assumes \"s \\<in> closed_seqs Zp\"\n  shows \"\\<exists>n. is_subseq_of s (filtered_seq s (kth_res_equals k n)) \\<and> (\\<forall>m. (filtered_seq s (kth_res_equals k n)) m k = n)\"\nproof-\n  obtain l where l_def: \" \\<forall> m. \\<exists>n > m. (kth_res_equals k l) (s n)\"\n    using assms seq_pr_inc by blast\n  have 0: \"is_subseq_of s (filtered_seq s (kth_res_equals k l))\"\n    unfolding filtered_seq_def\n    apply(rule is_subseqI[of \"seq_filter s (kth_res_equals k l)\"])\n     apply(rule seq_filter_increasing, rule l_def)\n    by blast \n  have 1: \" (\\<forall>m. (filtered_seq s (kth_res_equals k l)) m k = l)\"\n   using l_def \n   by (meson assms kth_res_equals_def fil_seq_pred padic_integers_axioms)\n  show ?thesis using 0 1 by blast \nqed\n\nlemma const_res_subseq_prop_0: \n  assumes \"s \\<in> closed_seqs Zp\"\n  shows \"\\<exists>l. (((const_res_subseq k s) = filtered_seq s (kth_res_equals k l)) \\<and> (is_subseq_of s (const_res_subseq k s)) \\<and> (\\<forall>m.(const_res_subseq k s) m k = l))\"\nproof-\n  have \" \\<exists>n. (is_subseq_of s (filtered_seq s (kth_res_equals k n)) \\<and> (\\<forall>m. (filtered_seq s (kth_res_equals k n)) m k = n))\"\n    by (simp add: kth_res_equals_subseq assms)\n  then have \"\\<exists>s'. (\\<exists>n. (is_subseq_of s s') \\<and> (s' = filtered_seq s (kth_res_equals k n)) \\<and> (\\<forall>m. s' m k = n))\"\n    by blast\n  then show ?thesis\n  using const_res_subseq_def[of k s] const_res_subseq_def someI_ex   \n      by (smt const_res_subseq_def someI_ex)\nqed\n\nlemma const_res_subseq_prop_1: \n  assumes \"s \\<in> closed_seqs Zp\"\n  shows \"(\\<forall>m.(const_res_subseq k s) m k = (const_res k s) )\"\n  using const_res_subseq_prop_0[of s] const_res_def[of k s]\n  by (smt assms const_res_subseq_def const_res_def the_equality)\n\nlemma const_res_subseq: \n  assumes \"s \\<in> closed_seqs Zp\"\n  shows \"is_subseq_of s (const_res_subseq k s)\"\n  using assms const_res_subseq_prop_0[of s k] by blast \n\nlemma const_res_range:\n  assumes \"s \\<in> closed_seqs Zp\"\n  assumes \"k > 0\"\n  shows \"const_res k s \\<in> carrier (Zp_res_ring k)\"\nproof-\n  have 0: \"(const_res_subseq k s) 0 \\<in> carrier Zp\"\n    using const_res_subseq[of s k] is_subseq_closed[of s \"const_res_subseq k s\"]\n          assms(1) closed_seqs_memE by blast\n  have 1: \"(const_res_subseq k s) 0 k \\<in>  carrier (Zp_res_ring k)\"\n    using 0 by simp\n  then show  ?thesis\n    using assms const_res_subseq_prop_1[of s k] \n    by (simp add: \\<open>s \\<in> closed_seqs Zp\\<close>)\nqed\n\nfun res_seq ::\"padic_int_seq \\<Rightarrow> nat \\<Rightarrow>  padic_int_seq\" where\n\"res_seq s 0 = s\"|\n\"res_seq s (Suc k) = const_res_subseq (Suc k) (res_seq s k)\"\n\nlemma res_seq_res:\n  assumes \"s \\<in> closed_seqs Zp\"\n  shows \"(res_seq s k) \\<in> closed_seqs Zp\"\n  apply(induction k)\n  apply (simp add: assms)\n  by (simp add: const_res_subseq is_subseq_closed)\n\nlemma res_seq_res':\n  assumes \"s \\<in> closed_seqs Zp\"\n  shows \"\\<And>n. res_seq s (Suc k) n (Suc k) = const_res (Suc k) (res_seq s k)\"\n  using assms res_seq_res[of s k] const_res_subseq_prop_1[of \"(res_seq s k)\" \"Suc k\" ] \n  by simp\n\nlemma res_seq_subseq: \n  assumes \"s \\<in> closed_seqs Zp\"\n  shows \"is_subseq_of (res_seq s k) (res_seq s (Suc k))\"\n  by (metis assms  const_res_subseq_prop_0 res_seq_res  \n      res_seq.simps(2))\n\nlemma is_increasing_id:\n\"is_increasing (\\<lambda> n. n)\"\n  by (simp add: is_increasingI)\n\nlemma is_increasing_comp:\n  assumes \"is_increasing f\"\n  assumes \"is_increasing g\"\n  shows \"is_increasing (f \\<circ> g)\"\n  using assms(1) assms(2) is_increasing_def \n  by auto\n\nlemma is_increasing_imp_geq_id[simp]:\n  assumes  \"is_increasing f\"\n  shows \"f n \\<ge>n\"\n  apply(induction n)\n  apply simp\n  by (metis (mono_tags, lifting) assms is_increasing_def\n      leD lessI not_less_eq_eq order_less_le_subst2)\n\nlemma is_subseq_ofE:\n  assumes \"s \\<in> closed_seqs Zp\"\n  assumes \"is_subseq_of s s'\"\n  shows \"\\<exists>k. k \\<ge> n \\<and> s' n = s k\"\nproof-\n  obtain f where \"is_increasing f \\<and> s' = take_subseq s f\"\n    using assms(2) is_subseq_of_def by blast\n  then have  \" f n \\<ge> n \\<and> s' n = s (f n)\"\n    unfolding take_subseq_def \n    by simp\n  then show ?thesis by blast \nqed\n\n\nlemma is_subseq_of_id:\n  assumes \"s \\<in> closed_seqs Zp\"\n  shows \"is_subseq_of s s\"\nproof-\n  have \"s = take_subseq s (\\<lambda>n. n)\"\n    unfolding take_subseq_def \n    by auto \n  then show ?thesis using is_increasing_id\n    using is_subseqI \n    by blast\nqed\n\nlemma is_subseq_of_trans:\n  assumes \"s \\<in> closed_seqs Zp\"\n  assumes \"is_subseq_of s s'\"\n  assumes \"is_subseq_of s' s''\"\n  shows \"is_subseq_of s s''\"\nproof-\n  obtain f where f_def: \"is_increasing f \\<and> s' = take_subseq s f\"\n    using assms(2) is_subseq_of_def \n    by blast\n  obtain g where g_def: \"is_increasing g \\<and> s'' = take_subseq s' g\"\n    using assms(3) is_subseq_of_def \n    by blast\n  have \"s'' = take_subseq s (f \\<circ> g)\"\n  proof\n    fix x\n    show \"s'' x = take_subseq s (f \\<circ> g) x\"\n      using f_def g_def unfolding take_subseq_def\n      by auto\n  qed\n  then show ?thesis \n    using f_def g_def is_increasing_comp is_subseq_of_def \n    by blast\nqed\n\nlemma res_seq_subseq':\n  assumes \"s \\<in> closed_seqs Zp\"\n  shows \"is_subseq_of s (res_seq s k)\"\nproof(induction k)\n  case 0\n  then show ?case using is_subseq_of_id \n    by (simp add: assms)\nnext\n  case (Suc k)\n  fix k\n  assume \"is_subseq_of s (res_seq s k)\"\n  then show \"is_subseq_of s (res_seq s (Suc k)) \"\n    using assms is_subseq_of_trans res_seq_subseq \n    by blast\nqed\n\nlemma res_seq_subseq'':\n  assumes \"s \\<in> closed_seqs Zp\"\n  shows \"is_subseq_of (res_seq s n) (res_seq s (n + k))\"\n  apply(induction k)\n  apply (simp add: assms is_subseq_of_id res_seq_res)\n  using add_Suc_right assms is_subseq_of_trans res_seq_res res_seq_subseq by presburger\n(**)\n\ndefinition acc_point :: \"padic_int_seq \\<Rightarrow> padic_int\" where\n\"acc_point s k = (if (k = 0) then (0::int) else ((res_seq s k) 0 k))\"\n\nlemma res_seq_res_1:\n  assumes \"s \\<in> closed_seqs Zp\"\n  shows \"res_seq s (Suc k) 0 k = res_seq s k 0 k\"\nproof-\n  obtain n where  n_def: \"res_seq s (Suc k) 0 = res_seq s k n\" \n    by (metis assms is_subseq_of_def res_seq_subseq take_subseq_def)\n  have \"res_seq s (Suc k) 0 k = res_seq s k n k\"\n    using n_def by auto\n  thus ?thesis \n    using  assms padic_integers.p_res_ring_0' \n        padic_integers_axioms res_seq.elims  residues_closed \n  proof -\n    have \"\\<forall>n. s n \\<in> carrier Zp\"\n      by (simp add: assms closed_seqs_memE)\n    then show ?thesis\n      by (metis \\<open>res_seq s (Suc k) 0 k = res_seq s k n k\\<close> assms padic_integers.p_res_ring_0' padic_integers_axioms res_seq.elims res_seq_res' residues_closed)\n  qed\nqed\n\nlemma acc_point_cres:\n  assumes \"s \\<in> closed_seqs Zp\"\n  shows \"(acc_point s (Suc k)) = (const_res (Suc k) (res_seq s k))\" \nproof-\n  have \"Suc k > 0\" by simp\n  have \"(res_seq s (Suc k)) = const_res_subseq (Suc k) (res_seq s k)\" \n    by simp\n  then have \"(const_res_subseq (Suc k) (res_seq s k)) 0 (Suc k) = const_res (Suc k)  (res_seq s k)\" \n    using assms res_seq_res' padic_integers_axioms by auto\n  have \"acc_point s (Suc k) = res_seq s (Suc k) 0 (Suc k)\" using acc_point_def by simp\n  then have \"acc_point s (Suc k) = (const_res_subseq (Suc k) (res_seq s k)) 0 (Suc k)\"\n    by simp\n  thus ?thesis \n    by (simp add: \\<open>(const_res_subseq (Suc k) (res_seq s k)) 0 (Suc k) = const_res (Suc k) (res_seq s k)\\<close>)\nqed\n\nlemma acc_point_res:\n  assumes \"s \\<in> closed_seqs Zp\"\n  shows \"residue (p ^ k) (acc_point s (Suc k)) = acc_point s k\"\nproof(cases \"k = 0\")\n  case True\n  then show ?thesis \n    by (simp add: acc_point_def residue_1_zero)    \nnext\n  case False\n  assume \"k \\<noteq> 0\"  show \"residue (p ^ k) (acc_point s (Suc k)) = acc_point s k\" \n    using False acc_point_def assms lessI less_imp_le nat.distinct(1) res_seq_res_1 res_seq_res \n          Zp_defs(3) closed_seqs_memE prime by (metis padic_set_res_coherent)\nqed\n\nlemma acc_point_closed:\n  assumes \"s \\<in> closed_seqs Zp\"\n  shows \"acc_point s \\<in>  carrier Zp\" \nproof-\n  have \"acc_point s \\<in> padic_set p\"\n  proof(rule padic_set_memI)\n    show \"\\<And>m. acc_point s m \\<in> carrier (residue_ring (p ^ m))\"\n    proof-\n      fix m\n      show \"acc_point s m \\<in> carrier (residue_ring (p ^ m))\"\n      proof(cases \"m = 0\")\n        case True\n        then show ?thesis \n          by (simp add: acc_point_def residue_ring_def)\n      next\n        case False\n        assume \"m \\<noteq> 0\" \n        then have \"acc_point s m = res_seq s m 0 m\" (*\"res_seq s (Suc k) = const_res_subseq (Suc k) (res_seq s k)\"*)\n          by (simp add: acc_point_def)\n        then show ?thesis  using const_res_range[of \"(const_res_subseq (m-1) s)\" m] acc_point_def[of s m] \n          by (metis False Suc_pred acc_point_cres assms const_res_range neq0_conv res_seq_res)                     \n      qed\n    qed\n    show \"\\<And>m n. m < n \\<Longrightarrow> residue (p ^ m) (acc_point s n) = acc_point s m\"\n    proof-\n      fix m n::nat \n      assume A: \"m < n\"\n      show \"residue (p ^ m) (acc_point s n) = acc_point s m\"\n      proof-\n        obtain l where l_def: \"l = n - m - 1\"\n          by simp\n        have \"residue (p ^ m) (acc_point s (Suc (m + l))) = acc_point s m\"\n        proof(induction l)\n          case 0\n          then show ?case \n            by (simp add: acc_point_res assms)\n        next\n          case (Suc l)\n          then show ?case \n            using Zp_defs(3) acc_point_def add_Suc_right assms  le_add1 closed_seqs_memE nat.distinct(1)\n                padic_integers.prime padic_integers_axioms res_seq_res res_seq_res_1\n            by (metis padic_set_res_coherent) \n        qed\n        then show ?thesis \n          by (metis A Suc_diff_Suc Suc_eq_plus1 add_Suc_right add_diff_inverse_nat diff_diff_left \n              l_def le_less_trans less_not_refl order_less_imp_le)\n      qed\n    qed\n  qed\n  then show ?thesis \n    by (simp add: Zp_defs(3))    \nqed\n\ntext\\<open>Choice function for a subsequence of s which converges to a, if it exists\\<close>\nfun convergent_subseq_fun :: \"padic_int_seq \\<Rightarrow> padic_int \\<Rightarrow> (nat \\<Rightarrow> nat)\" where\n\"convergent_subseq_fun s a 0 = 0\"|\n\"convergent_subseq_fun s a (Suc n) = (SOME k. k > (convergent_subseq_fun s a n)\n                                                \\<and> (s k (Suc n)) = a (Suc n))\"\n\ndefinition convergent_subseq :: \"padic_int_seq \\<Rightarrow> padic_int_seq\" where\n\"convergent_subseq s = take_subseq s (convergent_subseq_fun s (acc_point s))\"\n\nlemma increasing_conv_induction_0_pre:\n  assumes \"s \\<in> closed_seqs Zp\"\n  assumes \"a = acc_point s\"\n  shows \"\\<exists>k > convergent_subseq_fun s a n. (s k (Suc n)) = a (Suc n)\"\nproof-\n  obtain l::nat where \"l > 0 \" by blast\n  have \"is_subseq_of s (res_seq s (Suc n))\" \n    using assms(1) res_seq_subseq' by blast\n  then obtain m where \"s m = res_seq s (Suc n) l \\<and> m \\<ge> l\" \n    by (metis is_increasing_imp_geq_id is_subseq_of_def take_subseq_def )  \n  have \"a (Suc n) = res_seq s (Suc n) 0 (Suc n)\" \n    by (simp add: acc_point_def assms(2))\n  have \"s m (Suc n) = a (Suc n)\" \n    by (metis \\<open>a (Suc n) = res_seq s (Suc n) 0 (Suc n)\\<close> \\<open>s m = res_seq s (Suc n) l \\<and> l \\<le> m\\<close> assms(1) res_seq_res') \n  thus ?thesis \n    using \\<open>0 < l\\<close> \\<open>s m = res_seq s (Suc n) l \\<and> l \\<le> m\\<close> less_le_trans  \\<open>s m (Suc n) = a (Suc n)\\<close> \n    by (metis \\<open>a (Suc n) = res_seq s (Suc n) 0 (Suc n)\\<close> \\<open>is_subseq_of s (res_seq s (Suc n))\\<close>\n        assms(1) lessI is_subseq_ofE res_seq_res' )\nqed\n\nlemma increasing_conv_subseq_fun_0:\n  assumes \"s \\<in> closed_seqs Zp\"\n  assumes \"\\<exists>s'. s' = convergent_subseq s\"\n  assumes \"a = acc_point s\"\n  shows \"convergent_subseq_fun s a (Suc n) > convergent_subseq_fun s a n\"\n  apply(auto) \nproof(induction n)\n  case 0\n  have \"convergent_subseq_fun s a 0 = 0\" by simp\n  then show ?case \n    by (smt assms(1) assms(3) less_Suc_eq less_Suc_eq_0_disj increasing_conv_induction_0_pre padic_integers_axioms someI_ex)\nnext\n  case (Suc k)\n  then show ?case \n    by (metis (mono_tags, lifting) assms(1) assms(3) increasing_conv_induction_0_pre someI_ex) \nqed\n\nlemma increasing_conv_subseq_fun:\n  assumes \"s \\<in> closed_seqs Zp\"\n  assumes \"a = acc_point s\"\n  assumes \"\\<exists>s'. s' = convergent_subseq s\"\n  shows \"is_increasing (convergent_subseq_fun s a)\"\n    by (metis assms(1) assms(2) increasing_conv_subseq_fun_0 is_increasingI lift_Suc_mono_less)\n\nlemma convergent_subseq_is_subseq:\n  assumes \"s \\<in> closed_seqs Zp\"\n  shows \"is_subseq_of s (convergent_subseq s)\" \n  using assms convergent_subseq_def increasing_conv_subseq_fun is_subseqI by blast\n\nlemma is_closed_seq_conv_subseq:\n  assumes \"s \\<in> closed_seqs Zp\"\n  shows \"(convergent_subseq s) \\<in> closed_seqs Zp\"  \n  by (simp add: assms convergent_subseq_def closed_seqs_memI closed_seqs_memE take_subseq_def) \n\nlemma convergent_subseq_res:\n  assumes \"s \\<in> closed_seqs Zp\"\n  assumes \"a = acc_point s\"\n  shows \"convergent_subseq s l l = residue (p ^ l) (acc_point s l)\"\nproof-\n  have \"\\<exists>k. convergent_subseq s l =  s k \\<and> s k l = a l\" \n  proof-\n    have \"convergent_subseq s l = s (convergent_subseq_fun s a l)\" \n      by (simp add: assms(2) convergent_subseq_def take_subseq_def)\n    obtain k where kdef: \"(convergent_subseq_fun s a l) = k\" \n      by simp\n    have \"convergent_subseq s l = s k\" \n      by (simp add: \\<open>convergent_subseq s l = s (convergent_subseq_fun s a l)\\<close> kdef)\n    have \"s k l = a l\"\n    proof(cases \"l = 0\")\n      case True\n      then show ?thesis \n        using acc_point_def assms(1) assms(2) \n        by (metis closed_seqs_memE p_res_ring_0' residues_closed)\n    next\n      case False\n      have \"0 < l\"\n        using False by blast\n      then have \"k > convergent_subseq_fun s a (l-1)\" \n        by (metis One_nat_def Suc_pred assms(1) assms(2) increasing_conv_subseq_fun_0 kdef)\n      then have \"s k l = a l\" using kdef \n        assms(1) assms(2) convergent_subseq_fun.simps(2) increasing_conv_induction_0_pre \n        padic_integers_axioms someI_ex One_nat_def  \\<open>0 < l\\<close> increasing_conv_induction_0_pre \n        by (smt Suc_pred)\n      then show ?thesis\n        by simp\n    qed\n    then have \"convergent_subseq s l =  s k \\<and> s k l = a l\" \n      using \\<open>convergent_subseq s l = s k\\<close> by blast\n    thus ?thesis \n      by blast\n  qed\n  thus ?thesis \n    using acc_point_closed assms(1) assms(2) Zp_defs(3) prime padic_set_res_coherent by force \nqed\n\nlemma convergent_subseq_res':\n  assumes \"s \\<in> closed_seqs Zp\"\n  assumes \"n > l\"\n  shows \"convergent_subseq s n l = convergent_subseq s l l \"\nproof-\n  have 0: \"convergent_subseq s l l = residue (p ^ l) (acc_point s l)\"\n    using assms(1) convergent_subseq_res by auto\n  have 1: \"convergent_subseq s n n = residue (p ^ n) (acc_point s n)\"\n    by (simp add: assms(1) convergent_subseq_res)\n  have 2: \"convergent_subseq s n l = residue (p ^ l) (convergent_subseq s l l)\"\n    using 0 assms 1 Zp_defs(3) acc_point_closed is_closed_seq_conv_subseq \n        closed_seqs_memE le_refl less_imp_le_nat prime \n    by (metis padic_set_res_coherent)\n  show ?thesis using 0 1 2 Zp_defs(3) assms(1) is_closed_seq_conv_subseq closed_seqs_memE le_refl prime\n    by (metis padic_set_res_coherent)\nqed\n\nlemma convergent_subsequence_is_convergent:\n  assumes \"s \\<in> closed_seqs Zp\"\n  assumes \"a = acc_point s\"\n  shows \"Zp_converges_to (convergent_subseq s) (acc_point s)\" (*\\<And>n. \\<exists>N. \\<forall>k > N. s k n = a n\"*) \nproof(rule Zp_converges_toI)\n  show \"acc_point s \\<in> carrier Zp\"\n    using acc_point_closed assms  by blast\n  show \"convergent_subseq s \\<in> carrier (Zp\\<^bsup>\\<omega>\\<^esup>)\"\n    using is_closed_seq_conv_subseq assms by simp\n  show \"\\<And>n. \\<exists>N. \\<forall>k>N. convergent_subseq s k n = acc_point s n\" \n  proof-\n    fix n\n    show \"\\<exists>N. \\<forall>k>N. convergent_subseq s k n = acc_point s n\"\n    proof(induction n)\n      case 0\n      then show ?case  \n        using acc_point_closed[of s] assms convergent_subseq_def closed_seqs_memE of_nat_0 \n              ord_pos take_subseq_def zero_below_ord is_closed_seq_conv_subseq[of s]\n        by (metis residue_of_zero(2))\n    next\n      case (Suc n)\n      have \"acc_point s (Suc n) = res_seq s (Suc n) 0 (Suc n)\"\n        by (simp add: acc_point_def)\n      obtain k where kdef: \"convergent_subseq_fun s a (Suc n) = k\" by simp\n      have \"Suc n > 0\" by simp\n      then have \"k > (convergent_subseq_fun s a n)\" \n        using assms(1) assms(2) increasing_conv_subseq_fun_0 kdef by blast \n      then have \" k > (convergent_subseq_fun s a n) \\<and> (s k (Suc n)) = a (Suc n)\" using kdef \n        by (metis (mono_tags, lifting) assms(1) assms(2) convergent_subseq_fun.simps(2) increasing_conv_induction_0_pre someI_ex)\n      have \"s k (Suc n) = a (Suc n)\" \n        using \\<open>convergent_subseq_fun s a n < k \\<and> s k (Suc n) = a (Suc n)\\<close> by blast\n      then have \"convergent_subseq s (Suc n) (Suc n) = a (Suc n)\" \n        by (metis assms(2) convergent_subseq_def kdef take_subseq_def)\n      then have \"\\<forall>l > n.  convergent_subseq s l (Suc n) = a (Suc n)\" \n        using convergent_subseq_res' \n        by (metis Suc_lessI assms(1))        \n      then show ?case \n        using assms(2) by blast\n    qed\n  qed\nqed   \n\ntheorem Zp_is_compact:\n  assumes \"s \\<in> closed_seqs Zp\"\n  shows \"\\<exists>s'. is_subseq_of s s' \\<and> (Zp_converges_to s' (acc_point s))\" \n  using assms convergent_subseq_is_subseq convergent_subsequence_is_convergent \n  by blast\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/Padic_Ints/Zp_Compact.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8705972684083609, "lm_q2_score": 0.824461932846258, "lm_q1q2_score": 0.7177743066426298}}
{"text": "(*  Title:      HOL/Groups_Big.thy\n    Author:     Tobias Nipkow\n    Author:     Lawrence C Paulson\n    Author:     Markus Wenzel\n    Author:     Jeremy Avigad\n*)\n\nsection \\<open>Big sum and product over finite (non-empty) sets\\<close>\n\ntheory Groups_Big\n  imports Power Equiv_Relations\nbegin\n\nsubsection \\<open>Generic monoid operation over a set\\<close>\n\nlocale comm_monoid_set = comm_monoid\nbegin\n\nsubsubsection \\<open>Standard sum or product indexed by a finite set\\<close>\n\ninterpretation comp_fun_commute f\n  by standard (simp add: fun_eq_iff left_commute)\n\ninterpretation comp?: comp_fun_commute \"f \\<circ> g\"\n  by (fact comp_comp_fun_commute)\n\ndefinition F :: \"('b \\<Rightarrow> 'a) \\<Rightarrow> 'b set \\<Rightarrow> 'a\"\n  where eq_fold: \"F g A = Finite_Set.fold (f \\<circ> g) \\<^bold>1 A\"\n\nlemma infinite [simp]: \"\\<not> finite A \\<Longrightarrow> F g A = \\<^bold>1\"\n  by (simp add: eq_fold)\n\nlemma empty [simp]: \"F g {} = \\<^bold>1\"\n  by (simp add: eq_fold)\n\nlemma insert [simp]: \"finite A \\<Longrightarrow> x \\<notin> A \\<Longrightarrow> F g (insert x A) = g x \\<^bold>* F g A\"\n  by (simp add: eq_fold)\n\nlemma remove:\n  assumes \"finite A\" and \"x \\<in> A\"\n  shows \"F g A = g x \\<^bold>* F g (A - {x})\"\nproof -\n  from \\<open>x \\<in> A\\<close> obtain B where B: \"A = insert x B\" and \"x \\<notin> B\"\n    by (auto dest: mk_disjoint_insert)\n  moreover from \\<open>finite A\\<close> B have \"finite B\" by simp\n  ultimately show ?thesis by simp\nqed\n\nlemma insert_remove: \"finite A \\<Longrightarrow> F g (insert x A) = g x \\<^bold>* F g (A - {x})\"\n  by (cases \"x \\<in> A\") (simp_all add: remove insert_absorb)\n\nlemma insert_if: \"finite A \\<Longrightarrow> F g (insert x A) = (if x \\<in> A then F g A else g x \\<^bold>* F g A)\"\n  by (cases \"x \\<in> A\") (simp_all add: insert_absorb)\n\nlemma neutral: \"\\<forall>x\\<in>A. g x = \\<^bold>1 \\<Longrightarrow> F g A = \\<^bold>1\"\n  by (induct A rule: infinite_finite_induct) simp_all\n\nlemma neutral_const [simp]: \"F (\\<lambda>_. \\<^bold>1) A = \\<^bold>1\"\n  by (simp add: neutral)\n\nlemma union_inter:\n  assumes \"finite A\" and \"finite B\"\n  shows \"F g (A \\<union> B) \\<^bold>* F g (A \\<inter> B) = F g A \\<^bold>* F g B\"\n  \\<comment> \\<open>The reversed orientation looks more natural, but LOOPS as a simprule!\\<close>\n  using assms\nproof (induct A)\n  case empty\n  then show ?case by simp\nnext\n  case (insert x A)\n  then show ?case\n    by (auto simp: insert_absorb Int_insert_left commute [of _ \"g x\"] assoc left_commute)\nqed\n\ncorollary union_inter_neutral:\n  assumes \"finite A\" and \"finite B\"\n    and \"\\<forall>x \\<in> A \\<inter> B. g x = \\<^bold>1\"\n  shows \"F g (A \\<union> B) = F g A \\<^bold>* F g B\"\n  using assms by (simp add: union_inter [symmetric] neutral)\n\ncorollary union_disjoint:\n  assumes \"finite A\" and \"finite B\"\n  assumes \"A \\<inter> B = {}\"\n  shows \"F g (A \\<union> B) = F g A \\<^bold>* F g B\"\n  using assms by (simp add: union_inter_neutral)\n\nlemma union_diff2:\n  assumes \"finite A\" and \"finite B\"\n  shows \"F g (A \\<union> B) = F g (A - B) \\<^bold>* F g (B - A) \\<^bold>* F g (A \\<inter> B)\"\nproof -\n  have \"A \\<union> B = A - B \\<union> (B - A) \\<union> A \\<inter> B\"\n    by auto\n  with assms show ?thesis\n    by simp (subst union_disjoint, auto)+\nqed\n\nlemma subset_diff:\n  assumes \"B \\<subseteq> A\" and \"finite A\"\n  shows \"F g A = F g (A - B) \\<^bold>* F g B\"\nproof -\n  from assms have \"finite (A - B)\" by auto\n  moreover from assms have \"finite B\" by (rule finite_subset)\n  moreover from assms have \"(A - B) \\<inter> B = {}\" by auto\n  ultimately have \"F g (A - B \\<union> B) = F g (A - B) \\<^bold>* F g B\" by (rule union_disjoint)\n  moreover from assms have \"A \\<union> B = A\" by auto\n  ultimately show ?thesis by simp\nqed\n\nlemma Int_Diff:\n  assumes \"finite A\"\n  shows \"F g A = F g (A \\<inter> B) \\<^bold>* F g (A - B)\"\n  by (subst subset_diff [where B = \"A - B\"]) (auto simp:  Diff_Diff_Int assms)\n\nlemma setdiff_irrelevant:\n  assumes \"finite A\"\n  shows \"F g (A - {x. g x = z}) = F g A\"\n  using assms by (induct A) (simp_all add: insert_Diff_if)\n\nlemma not_neutral_contains_not_neutral:\n  assumes \"F g A \\<noteq> \\<^bold>1\"\n  obtains a where \"a \\<in> A\" and \"g a \\<noteq> \\<^bold>1\"\nproof -\n  from assms have \"\\<exists>a\\<in>A. g a \\<noteq> \\<^bold>1\"\n  proof (induct A 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 a A)\n    then show ?case by fastforce\n  qed\n  with that show thesis by blast\nqed\n\n\n\nlemma cong [fundef_cong]:\n  assumes \"A = B\"\n  assumes g_h: \"\\<And>x. x \\<in> B \\<Longrightarrow> g x = h x\"\n  shows \"F g A = F h B\"\n  using g_h unfolding \\<open>A = B\\<close>\n  by (induct B rule: infinite_finite_induct) auto\n\nlemma cong_simp [cong]:\n  \"\\<lbrakk> A = B;  \\<And>x. x \\<in> B =simp=> g x = h x \\<rbrakk> \\<Longrightarrow> F (\\<lambda>x. g x) A = F (\\<lambda>x. h x) B\"\nby (rule cong) (simp_all add: simp_implies_def)\n\nlemma reindex_cong:\n  assumes \"inj_on l B\"\n  assumes \"A = l ` B\"\n  assumes \"\\<And>x. x \\<in> B \\<Longrightarrow> g (l x) = h x\"\n  shows \"F g A = F h B\"\n  using assms by (simp add: reindex)\n\nlemma image_eq:\n  assumes \"inj_on g A\"  \n  shows \"F (\\<lambda>x. x) (g ` A) = F g A\"\n  using assms reindex_cong by fastforce\n\nlemma UNION_disjoint:\n  assumes \"finite I\" and \"\\<forall>i\\<in>I. finite (A i)\"\n    and \"\\<forall>i\\<in>I. \\<forall>j\\<in>I. i \\<noteq> j \\<longrightarrow> A i \\<inter> A j = {}\"\n  shows \"F g (\\<Union>(A ` I)) = F (\\<lambda>x. F g (A x)) I\"\n  using assms\nproof (induction rule: finite_induct)\n  case (insert i I)\n  then have \"\\<forall>j\\<in>I. j \\<noteq> i\"\n    by blast\n  with insert.prems have \"A i \\<inter> \\<Union>(A ` I) = {}\"\n    by blast\n  with insert show ?case\n    by (simp add: union_disjoint)\nqed auto\n\nlemma Union_disjoint:\n  assumes \"\\<forall>A\\<in>C. finite A\" \"\\<forall>A\\<in>C. \\<forall>B\\<in>C. A \\<noteq> B \\<longrightarrow> A \\<inter> B = {}\"\n  shows \"F g (\\<Union>C) = (F \\<circ> F) g C\"\nproof (cases \"finite C\")\n  case True\n  from UNION_disjoint [OF this assms] show ?thesis by simp\nnext\n  case False\n  then show ?thesis by (auto dest: finite_UnionD intro: infinite)\nqed\n\nlemma distrib: \"F (\\<lambda>x. g x \\<^bold>* h x) A = F g A \\<^bold>* F h A\"\n  by (induct A rule: infinite_finite_induct) (simp_all add: assoc commute left_commute)\n\nlemma Sigma:\n  assumes \"finite A\" \"\\<forall>x\\<in>A. finite (B x)\"\n  shows \"F (\\<lambda>x. F (g x) (B x)) A = F (case_prod g) (SIGMA x:A. B x)\"\n  unfolding Sigma_def\nproof (subst UNION_disjoint)\n  show \"F (\\<lambda>x. F (g x) (B x)) A = F (\\<lambda>x. F (\\<lambda>(x, y). g x y) (\\<Union>y\\<in>B x. {(x, y)})) A\"\n  proof (rule cong [OF refl])\n    show \"F (g x) (B x) = F (\\<lambda>(x, y). g x y) (\\<Union>y\\<in>B x. {(x, y)})\"\n      if \"x \\<in> A\" for x\n      using that assms by (simp add: UNION_disjoint)\n  qed\nqed (use assms in auto)\n\nlemma related:\n  assumes Re: \"R \\<^bold>1 \\<^bold>1\"\n    and Rop: \"\\<forall>x1 y1 x2 y2. R x1 x2 \\<and> R y1 y2 \\<longrightarrow> R (x1 \\<^bold>* y1) (x2 \\<^bold>* y2)\"\n    and fin: \"finite S\"\n    and R_h_g: \"\\<forall>x\\<in>S. R (h x) (g x)\"\n  shows \"R (F h S) (F g S)\"\n  using fin by (rule finite_subset_induct) (use assms in auto)\n\nlemma mono_neutral_cong_left:\n  assumes \"finite T\"\n    and \"S \\<subseteq> T\"\n    and \"\\<forall>i \\<in> T - S. h i = \\<^bold>1\"\n    and \"\\<And>x. x \\<in> S \\<Longrightarrow> g x = h x\"\n  shows \"F g S = F h T\"\nproof-\n  have eq: \"T = S \\<union> (T - S)\" using \\<open>S \\<subseteq> T\\<close> by blast\n  have d: \"S \\<inter> (T - S) = {}\" using \\<open>S \\<subseteq> T\\<close> by blast\n  from \\<open>finite T\\<close> \\<open>S \\<subseteq> T\\<close> have f: \"finite S\" \"finite (T - S)\"\n    by (auto intro: finite_subset)\n  show ?thesis using assms(4)\n    by (simp add: union_disjoint [OF f d, unfolded eq [symmetric]] neutral [OF assms(3)])\nqed\n\nlemma mono_neutral_cong_right:\n  \"finite T \\<Longrightarrow> S \\<subseteq> T \\<Longrightarrow> \\<forall>i \\<in> T - S. g i = \\<^bold>1 \\<Longrightarrow> (\\<And>x. x \\<in> S \\<Longrightarrow> g x = h x) \\<Longrightarrow>\n    F g T = F h S\"\n  by (auto intro!: mono_neutral_cong_left [symmetric])\n\nlemma mono_neutral_left: \"finite T \\<Longrightarrow> S \\<subseteq> T \\<Longrightarrow> \\<forall>i \\<in> T - S. g i = \\<^bold>1 \\<Longrightarrow> F g S = F g T\"\n  by (blast intro: mono_neutral_cong_left)\n\nlemma mono_neutral_right: \"finite T \\<Longrightarrow> S \\<subseteq> T \\<Longrightarrow> \\<forall>i \\<in> T - S. g i = \\<^bold>1 \\<Longrightarrow> F g T = F g S\"\n  by (blast intro!: mono_neutral_left [symmetric])\n\nlemma mono_neutral_cong:\n  assumes [simp]: \"finite T\" \"finite S\"\n    and *: \"\\<And>i. i \\<in> T - S \\<Longrightarrow> h i = \\<^bold>1\" \"\\<And>i. i \\<in> S - T \\<Longrightarrow> g i = \\<^bold>1\"\n    and gh: \"\\<And>x. x \\<in> S \\<inter> T \\<Longrightarrow> g x = h x\"\n shows \"F g S = F h T\"\nproof-\n  have \"F g S = F g (S \\<inter> T)\"\n    by(rule mono_neutral_right)(auto intro: *)\n  also have \"\\<dots> = F h (S \\<inter> T)\" using refl gh by(rule cong)\n  also have \"\\<dots> = F h T\"\n    by(rule mono_neutral_left)(auto intro: *)\n  finally show ?thesis .\nqed\n\nlemma reindex_bij_betw: \"bij_betw h S T \\<Longrightarrow> F (\\<lambda>x. g (h x)) S = F g T\"\n  by (auto simp: bij_betw_def reindex)\n\nlemma reindex_bij_witness:\n  assumes witness:\n    \"\\<And>a. a \\<in> S \\<Longrightarrow> i (j a) = a\"\n    \"\\<And>a. a \\<in> S \\<Longrightarrow> j a \\<in> T\"\n    \"\\<And>b. b \\<in> T \\<Longrightarrow> j (i b) = b\"\n    \"\\<And>b. b \\<in> T \\<Longrightarrow> i b \\<in> S\"\n  assumes eq:\n    \"\\<And>a. a \\<in> S \\<Longrightarrow> h (j a) = g a\"\n  shows \"F g S = F h T\"\nproof -\n  have \"bij_betw j S T\"\n    using bij_betw_byWitness[where A=S and f=j and f'=i and A'=T] witness by auto\n  moreover have \"F g S = F (\\<lambda>x. h (j x)) S\"\n    by (intro cong) (auto simp: eq)\n  ultimately show ?thesis\n    by (simp add: reindex_bij_betw)\nqed\n\nlemma reindex_bij_betw_not_neutral:\n  assumes fin: \"finite S'\" \"finite T'\"\n  assumes bij: \"bij_betw h (S - S') (T - T')\"\n  assumes nn:\n    \"\\<And>a. a \\<in> S' \\<Longrightarrow> g (h a) = z\"\n    \"\\<And>b. b \\<in> T' \\<Longrightarrow> g b = z\"\n  shows \"F (\\<lambda>x. g (h x)) S = F g T\"\nproof -\n  have [simp]: \"finite S \\<longleftrightarrow> finite T\"\n    using bij_betw_finite[OF bij] fin by auto\n  show ?thesis\n  proof (cases \"finite S\")\n    case True\n    with nn have \"F (\\<lambda>x. g (h x)) S = F (\\<lambda>x. g (h x)) (S - S')\"\n      by (intro mono_neutral_cong_right) auto\n    also have \"\\<dots> = F g (T - T')\"\n      using bij by (rule reindex_bij_betw)\n    also have \"\\<dots> = F g T\"\n      using nn \\<open>finite S\\<close> by (intro mono_neutral_cong_left) auto\n    finally show ?thesis .\n  next\n    case False\n    then show ?thesis by simp\n  qed\nqed\n\nlemma reindex_nontrivial:\n  assumes \"finite A\"\n    and nz: \"\\<And>x y. x \\<in> A \\<Longrightarrow> y \\<in> A \\<Longrightarrow> x \\<noteq> y \\<Longrightarrow> h x = h y \\<Longrightarrow> g (h x) = \\<^bold>1\"\n  shows \"F g (h ` A) = F (g \\<circ> h) A\"\nproof (subst reindex_bij_betw_not_neutral [symmetric])\n  show \"bij_betw h (A - {x \\<in> A. (g \\<circ> h) x = \\<^bold>1}) (h ` A - h ` {x \\<in> A. (g \\<circ> h) x = \\<^bold>1})\"\n    using nz by (auto intro!: inj_onI simp: bij_betw_def)\nqed (use \\<open>finite A\\<close> in auto)\n\nlemma reindex_bij_witness_not_neutral:\n  assumes fin: \"finite S'\" \"finite T'\"\n  assumes witness:\n    \"\\<And>a. a \\<in> S - S' \\<Longrightarrow> i (j a) = a\"\n    \"\\<And>a. a \\<in> S - S' \\<Longrightarrow> j a \\<in> T - T'\"\n    \"\\<And>b. b \\<in> T - T' \\<Longrightarrow> j (i b) = b\"\n    \"\\<And>b. b \\<in> T - T' \\<Longrightarrow> i b \\<in> S - S'\"\n  assumes nn:\n    \"\\<And>a. a \\<in> S' \\<Longrightarrow> g a = z\"\n    \"\\<And>b. b \\<in> T' \\<Longrightarrow> h b = z\"\n  assumes eq:\n    \"\\<And>a. a \\<in> S \\<Longrightarrow> h (j a) = g a\"\n  shows \"F g S = F h T\"\nproof -\n  have bij: \"bij_betw j (S - (S' \\<inter> S)) (T - (T' \\<inter> T))\"\n    using witness by (intro bij_betw_byWitness[where f'=i]) auto\n  have F_eq: \"F g S = F (\\<lambda>x. h (j x)) S\"\n    by (intro cong) (auto simp: eq)\n  show ?thesis\n    unfolding F_eq using fin nn eq\n    by (intro reindex_bij_betw_not_neutral[OF _ _ bij]) auto\nqed\n\nlemma delta_remove:\n  assumes fS: \"finite S\"\n  shows \"F (\\<lambda>k. if k = a then b k else c k) S = (if a \\<in> S then b a \\<^bold>* F c (S-{a}) else F c (S-{a}))\"\nproof -\n  let ?f = \"(\\<lambda>k. if k = a then b k else c k)\"\n  show ?thesis\n  proof (cases \"a \\<in> S\")\n    case False\n    then have \"\\<forall>k\\<in>S. ?f k = c k\" by simp\n    with False show ?thesis by simp\n  next\n    case True\n    let ?A = \"S - {a}\"\n    let ?B = \"{a}\"\n    from True have eq: \"S = ?A \\<union> ?B\" by blast\n    have dj: \"?A \\<inter> ?B = {}\" by simp\n    from fS have fAB: \"finite ?A\" \"finite ?B\" by auto\n    have \"F ?f S = F ?f ?A \\<^bold>* F ?f ?B\"\n      using union_disjoint [OF fAB dj, of ?f, unfolded eq [symmetric]] by simp\n    with True show ?thesis\n      using comm_monoid_set.remove comm_monoid_set_axioms fS by fastforce\n  qed\nqed\n\nlemma delta [simp]:\n  assumes fS: \"finite S\"\n  shows \"F (\\<lambda>k. if k = a then b k else \\<^bold>1) S = (if a \\<in> S then b a else \\<^bold>1)\"\n  by (simp add: delta_remove [OF assms])\n\nlemma delta' [simp]:\n  assumes fin: \"finite S\"\n  shows \"F (\\<lambda>k. if a = k then b k else \\<^bold>1) S = (if a \\<in> S then b a else \\<^bold>1)\"\n  using delta [OF fin, of a b, symmetric] by (auto intro: cong)\n\nlemma If_cases:\n  fixes P :: \"'b \\<Rightarrow> bool\" and g h :: \"'b \\<Rightarrow> 'a\"\n  assumes fin: \"finite A\"\n  shows \"F (\\<lambda>x. if P x then h x else g x) A = F h (A \\<inter> {x. P x}) \\<^bold>* F g (A \\<inter> - {x. P x})\"\nproof -\n  have a: \"A = A \\<inter> {x. P x} \\<union> A \\<inter> -{x. P x}\" \"(A \\<inter> {x. P x}) \\<inter> (A \\<inter> -{x. P x}) = {}\"\n    by blast+\n  from fin have f: \"finite (A \\<inter> {x. P x})\" \"finite (A \\<inter> -{x. P x})\" by auto\n  let ?g = \"\\<lambda>x. if P x then h x else g x\"\n  from union_disjoint [OF f a(2), of ?g] a(1) show ?thesis\n    by (subst (1 2) cong) simp_all\nqed\n\nlemma cartesian_product: \"F (\\<lambda>x. F (g x) B) A = F (case_prod g) (A \\<times> B)\"\nproof (cases \"A = {} \\<or> B = {}\")\n  case True\n  then show ?thesis\n    by auto\nnext\n  case False\n  then have \"A \\<noteq> {}\" \"B \\<noteq> {}\" by auto\n  show ?thesis\n  proof (cases \"finite A \\<and> finite B\")\n    case True\n    then show ?thesis\n      by (simp add: Sigma)\n  next\n    case False\n    then consider \"infinite A\" | \"infinite B\" by auto\n    then have \"infinite (A \\<times> B)\"\n      by cases (use \\<open>A \\<noteq> {}\\<close> \\<open>B \\<noteq> {}\\<close> in \\<open>auto dest: finite_cartesian_productD1 finite_cartesian_productD2\\<close>)\n    then show ?thesis\n      using False by auto\n  qed\nqed\n\nlemma inter_restrict:\n  assumes \"finite A\"\n  shows \"F g (A \\<inter> B) = F (\\<lambda>x. if x \\<in> B then g x else \\<^bold>1) A\"\nproof -\n  let ?g = \"\\<lambda>x. if x \\<in> A \\<inter> B then g x else \\<^bold>1\"\n  have \"\\<forall>i\\<in>A - A \\<inter> B. (if i \\<in> A \\<inter> B then g i else \\<^bold>1) = \\<^bold>1\" by simp\n  moreover have \"A \\<inter> B \\<subseteq> A\" by blast\n  ultimately have \"F ?g (A \\<inter> B) = F ?g A\"\n    using \\<open>finite A\\<close> by (intro mono_neutral_left) auto\n  then show ?thesis by simp\nqed\n\nlemma inter_filter:\n  \"finite A \\<Longrightarrow> F g {x \\<in> A. P x} = F (\\<lambda>x. if P x then g x else \\<^bold>1) A\"\n  by (simp add: inter_restrict [symmetric, of A \"{x. P x}\" g, simplified mem_Collect_eq] Int_def)\n\nlemma Union_comp:\n  assumes \"\\<forall>A \\<in> B. finite A\"\n    and \"\\<And>A1 A2 x. A1 \\<in> B \\<Longrightarrow> A2 \\<in> B \\<Longrightarrow> A1 \\<noteq> A2 \\<Longrightarrow> x \\<in> A1 \\<Longrightarrow> x \\<in> A2 \\<Longrightarrow> g x = \\<^bold>1\"\n  shows \"F g (\\<Union>B) = (F \\<circ> F) g B\"\n  using assms\nproof (induct B rule: infinite_finite_induct)\n  case (infinite A)\n  then have \"\\<not> finite (\\<Union>A)\" by (blast dest: finite_UnionD)\n  with infinite show ?case by simp\nnext\n  case empty\n  then show ?case by simp\nnext\n  case (insert A B)\n  then have \"finite A\" \"finite B\" \"finite (\\<Union>B)\" \"A \\<notin> B\"\n    and \"\\<forall>x\\<in>A \\<inter> \\<Union>B. g x = \\<^bold>1\"\n    and H: \"F g (\\<Union>B) = (F \\<circ> F) g B\" by auto\n  then have \"F g (A \\<union> \\<Union>B) = F g A \\<^bold>* F g (\\<Union>B)\"\n    by (simp add: union_inter_neutral)\n  with \\<open>finite B\\<close> \\<open>A \\<notin> B\\<close> show ?case\n    by (simp add: H)\nqed\n\nlemma swap: \"F (\\<lambda>i. F (g i) B) A = F (\\<lambda>j. F (\\<lambda>i. g i j) A) B\"\n  unfolding cartesian_product\n  by (rule reindex_bij_witness [where i = \"\\<lambda>(i, j). (j, i)\" and j = \"\\<lambda>(i, j). (j, i)\"]) auto\n\nlemma swap_restrict:\n  \"finite A \\<Longrightarrow> finite B \\<Longrightarrow>\n    F (\\<lambda>x. F (g x) {y. y \\<in> B \\<and> R x y}) A = F (\\<lambda>y. F (\\<lambda>x. g x y) {x. x \\<in> A \\<and> R x y}) B\"\n  by (simp add: inter_filter) (rule swap)\n\nlemma image_gen:\n  assumes fin: \"finite S\"\n  shows \"F h S = F (\\<lambda>y. F h {x. x \\<in> S \\<and> g x = y}) (g ` S)\"\nproof -\n  have \"{y. y\\<in> g`S \\<and> g x = y} = {g x}\" if \"x \\<in> S\" for x\n    using that by auto\n  then have \"F h S = F (\\<lambda>x. F (\\<lambda>y. h x) {y. y\\<in> g`S \\<and> g x = y}) S\"\n    by simp\n  also have \"\\<dots> = F (\\<lambda>y. F h {x. x \\<in> S \\<and> g x = y}) (g ` S)\"\n    by (rule swap_restrict [OF fin finite_imageI [OF fin]])\n  finally show ?thesis .\nqed\n\nlemma group:\n  assumes fS: \"finite S\" and fT: \"finite T\" and fST: \"g ` S \\<subseteq> T\"\n  shows \"F (\\<lambda>y. F h {x. x \\<in> S \\<and> g x = y}) T = F h S\"\n  unfolding image_gen[OF fS, of h g]\n  by (auto intro: neutral mono_neutral_right[OF fT fST])\n\nlemma Plus:\n  fixes A :: \"'b set\" and B :: \"'c set\"\n  assumes fin: \"finite A\" \"finite B\"\n  shows \"F g (A <+> B) = F (g \\<circ> Inl) A \\<^bold>* F (g \\<circ> Inr) B\"\nproof -\n  have \"A <+> B = Inl ` A \\<union> Inr ` B\" by auto\n  moreover from fin have \"finite (Inl ` A)\" \"finite (Inr ` B)\" by auto\n  moreover have \"Inl ` A \\<inter> Inr ` B = {}\" by auto\n  moreover have \"inj_on Inl A\" \"inj_on Inr B\" by (auto intro: inj_onI)\n  ultimately show ?thesis\n    using fin by (simp add: union_disjoint reindex)\nqed\n\nlemma same_carrier:\n  assumes \"finite C\"\n  assumes subset: \"A \\<subseteq> C\" \"B \\<subseteq> C\"\n  assumes trivial: \"\\<And>a. a \\<in> C - A \\<Longrightarrow> g a = \\<^bold>1\" \"\\<And>b. b \\<in> C - B \\<Longrightarrow> h b = \\<^bold>1\"\n  shows \"F g A = F h B \\<longleftrightarrow> F g C = F h C\"\nproof -\n  have \"finite A\" and \"finite B\" and \"finite (C - A)\" and \"finite (C - B)\"\n    using \\<open>finite C\\<close> subset by (auto elim: finite_subset)\n  from subset have [simp]: \"A - (C - A) = A\" by auto\n  from subset have [simp]: \"B - (C - B) = B\" by auto\n  from subset have \"C = A \\<union> (C - A)\" by auto\n  then have \"F g C = F g (A \\<union> (C - A))\" by simp\n  also have \"\\<dots> = F g (A - (C - A)) \\<^bold>* F g (C - A - A) \\<^bold>* F g (A \\<inter> (C - A))\"\n    using \\<open>finite A\\<close> \\<open>finite (C - A)\\<close> by (simp only: union_diff2)\n  finally have *: \"F g C = F g A\" using trivial by simp\n  from subset have \"C = B \\<union> (C - B)\" by auto\n  then have \"F h C = F h (B \\<union> (C - B))\" by simp\n  also have \"\\<dots> = F h (B - (C - B)) \\<^bold>* F h (C - B - B) \\<^bold>* F h (B \\<inter> (C - B))\"\n    using \\<open>finite B\\<close> \\<open>finite (C - B)\\<close> by (simp only: union_diff2)\n  finally have \"F h C = F h B\"\n    using trivial by simp\n  with * show ?thesis by simp\nqed\n\nlemma same_carrierI:\n  assumes \"finite C\"\n  assumes subset: \"A \\<subseteq> C\" \"B \\<subseteq> C\"\n  assumes trivial: \"\\<And>a. a \\<in> C - A \\<Longrightarrow> g a = \\<^bold>1\" \"\\<And>b. b \\<in> C - B \\<Longrightarrow> h b = \\<^bold>1\"\n  assumes \"F g C = F h C\"\n  shows \"F g A = F h B\"\n  using assms same_carrier [of C A B] by simp\n\nlemma eq_general:\n  assumes B: \"\\<And>y. y \\<in> B \\<Longrightarrow> \\<exists>!x. x \\<in> A \\<and> h x = y\" and A: \"\\<And>x. x \\<in> A \\<Longrightarrow> h x \\<in> B \\<and> \\<gamma>(h x) = \\<phi> x\"\n  shows \"F \\<phi> A = F \\<gamma> B\"\nproof -\n  have eq: \"B = h ` A\"\n    by (auto dest: assms)\n  have h: \"inj_on h A\"\n    using assms by (blast intro: inj_onI)\n  have \"F \\<phi> A = F (\\<gamma> \\<circ> h) A\"\n    using A by auto\n  also have \"\\<dots> = F \\<gamma> B\"\n    by (simp add: eq reindex h)\n  finally show ?thesis .\nqed\n\nlemma eq_general_inverses:\n  assumes B: \"\\<And>y. y \\<in> B \\<Longrightarrow> k y \\<in> A \\<and> h(k y) = y\" and A: \"\\<And>x. x \\<in> A \\<Longrightarrow> h x \\<in> B \\<and> k(h x) = x \\<and> \\<gamma>(h x) = \\<phi> x\"\n  shows \"F \\<phi> A = F \\<gamma> B\"\n  by (rule eq_general [where h=h]) (force intro: dest: A B)+\n\nsubsubsection \\<open>HOL Light variant: sum/product indexed by the non-neutral subset\\<close>\ntext \\<open>NB only a subset of the properties above are proved\\<close>\n\ndefinition G :: \"['b \\<Rightarrow> 'a,'b set] \\<Rightarrow> 'a\"\n  where \"G p I \\<equiv> if finite {x \\<in> I. p x \\<noteq> \\<^bold>1} then F p {x \\<in> I. p x \\<noteq> \\<^bold>1} else \\<^bold>1\"\n\nlemma finite_Collect_op:\n  shows \"\\<lbrakk>finite {i \\<in> I. x i \\<noteq> \\<^bold>1}; finite {i \\<in> I. y i \\<noteq> \\<^bold>1}\\<rbrakk> \\<Longrightarrow> finite {i \\<in> I. x i \\<^bold>* y i \\<noteq> \\<^bold>1}\"\n  apply (rule finite_subset [where B = \"{i \\<in> I. x i \\<noteq> \\<^bold>1} \\<union> {i \\<in> I. y i \\<noteq> \\<^bold>1}\"]) \n  using left_neutral by force+\n\nlemma empty' [simp]: \"G p {} = \\<^bold>1\"\n  by (auto simp: G_def)\n\nlemma eq_sum [simp]: \"finite I \\<Longrightarrow> G p I = F p I\"\n  by (auto simp: G_def intro: mono_neutral_cong_left)\n\nlemma insert' [simp]:\n  assumes \"finite {x \\<in> I. p x \\<noteq> \\<^bold>1}\"\n  shows \"G p (insert i I) = (if i \\<in> I then G p I else p i \\<^bold>* G p I)\"\nproof -\n  have \"{x. x = i \\<and> p x \\<noteq> \\<^bold>1 \\<or> x \\<in> I \\<and> p x \\<noteq> \\<^bold>1} = (if p i = \\<^bold>1 then {x \\<in> I. p x \\<noteq> \\<^bold>1} else insert i {x \\<in> I. p x \\<noteq> \\<^bold>1})\"\n    by auto\n  then show ?thesis\n    using assms by (simp add: G_def conj_disj_distribR insert_absorb)\nqed\n\nlemma distrib_triv':\n  assumes \"finite I\"\n  shows \"G (\\<lambda>i. g i \\<^bold>* h i) I = G g I \\<^bold>* G h I\"\n  by (simp add: assms local.distrib)\n\nlemma non_neutral': \"G g {x \\<in> I. g x \\<noteq> \\<^bold>1} = G g I\"\n  by (simp add: G_def)\n\nlemma distrib':\n  assumes \"finite {x \\<in> I. g x \\<noteq> \\<^bold>1}\" \"finite {x \\<in> I. h x \\<noteq> \\<^bold>1}\"\n  shows \"G (\\<lambda>i. g i \\<^bold>* h i) I = G g I \\<^bold>* G h I\"\nproof -\n  have \"a \\<^bold>* a \\<noteq> a \\<Longrightarrow> a \\<noteq> \\<^bold>1\" for a\n    by auto\n  then have \"G (\\<lambda>i. g i \\<^bold>* h i) I = G (\\<lambda>i. g i \\<^bold>* h i) ({i \\<in> I. g i \\<noteq> \\<^bold>1} \\<union> {i \\<in> I. h i \\<noteq> \\<^bold>1})\"\n    using assms  by (force simp: G_def finite_Collect_op intro!: mono_neutral_cong)\n  also have \"\\<dots> = G g I \\<^bold>* G h I\"\n  proof -\n    have \"F g ({i \\<in> I. g i \\<noteq> \\<^bold>1} \\<union> {i \\<in> I. h i \\<noteq> \\<^bold>1}) = G g I\"\n         \"F h ({i \\<in> I. g i \\<noteq> \\<^bold>1} \\<union> {i \\<in> I. h i \\<noteq> \\<^bold>1}) = G h I\"\n      by (auto simp: G_def assms intro: mono_neutral_right)\n    then show ?thesis\n      using assms by (simp add: distrib)\n  qed\n  finally show ?thesis .\nqed\n\nlemma cong':\n  assumes \"A = B\"\n  assumes g_h: \"\\<And>x. x \\<in> B \\<Longrightarrow> g x = h x\"\n  shows \"G g A = G h B\"\n  using assms by (auto simp: G_def cong: conj_cong intro: cong)\n\n\nlemma mono_neutral_cong_left':\n  assumes \"S \\<subseteq> T\"\n    and \"\\<And>i. i \\<in> T - S \\<Longrightarrow> h i = \\<^bold>1\"\n    and \"\\<And>x. x \\<in> S \\<Longrightarrow> g x = h x\"\n  shows \"G g S = G h T\"\nproof -\n  have *: \"{x \\<in> S. g x \\<noteq> \\<^bold>1} = {x \\<in> T. h x \\<noteq> \\<^bold>1}\"\n    using assms by (metis DiffI subset_eq) \n  then have \"finite {x \\<in> S. g x \\<noteq> \\<^bold>1} = finite {x \\<in> T. h x \\<noteq> \\<^bold>1}\"\n    by simp\n  then show ?thesis\n    using assms by (auto simp add: G_def * intro: cong)\nqed\n\nlemma mono_neutral_cong_right':\n  \"S \\<subseteq> T \\<Longrightarrow> \\<forall>i \\<in> T - S. g i = \\<^bold>1 \\<Longrightarrow> (\\<And>x. x \\<in> S \\<Longrightarrow> g x = h x) \\<Longrightarrow>\n    G g T = G h S\"\n  by (auto intro!: mono_neutral_cong_left' [symmetric])\n\nlemma mono_neutral_left': \"S \\<subseteq> T \\<Longrightarrow> \\<forall>i \\<in> T - S. g i = \\<^bold>1 \\<Longrightarrow> G g S = G g T\"\n  by (blast intro: mono_neutral_cong_left')\n\nlemma mono_neutral_right': \"S \\<subseteq> T \\<Longrightarrow> \\<forall>i \\<in> T - S. g i = \\<^bold>1 \\<Longrightarrow> G g T = G g S\"\n  by (blast intro!: mono_neutral_left' [symmetric])\n\nend\n\n\nsubsection \\<open>Generalized summation over a set\\<close>\n\ncontext comm_monoid_add\nbegin\n\nsublocale sum: comm_monoid_set plus 0\n  defines sum = sum.F and sum' = sum.G ..\n\nabbreviation Sum (\"\\<Sum>\")\n  where \"\\<Sum> \\<equiv> sum (\\<lambda>x. x)\"\n\nend\n\ntext \\<open>Now: lots of fancy syntax. First, \\<^term>\\<open>sum (\\<lambda>x. e) A\\<close> is written \\<open>\\<Sum>x\\<in>A. e\\<close>.\\<close>\n\nsyntax (ASCII)\n  \"_sum\" :: \"pttrn \\<Rightarrow> 'a set \\<Rightarrow> 'b \\<Rightarrow> 'b::comm_monoid_add\"  (\"(3SUM (_/:_)./ _)\" [0, 51, 10] 10)\nsyntax\n  \"_sum\" :: \"pttrn \\<Rightarrow> 'a set \\<Rightarrow> 'b \\<Rightarrow> 'b::comm_monoid_add\"  (\"(2\\<Sum>(_/\\<in>_)./ _)\" [0, 51, 10] 10)\ntranslations \\<comment> \\<open>Beware of argument permutation!\\<close>\n  \"\\<Sum>i\\<in>A. b\" \\<rightleftharpoons> \"CONST sum (\\<lambda>i. b) A\"\n\ntext \\<open>Instead of \\<^term>\\<open>\\<Sum>x\\<in>{x. P}. e\\<close> we introduce the shorter \\<open>\\<Sum>x|P. e\\<close>.\\<close>\n\nsyntax (ASCII)\n  \"_qsum\" :: \"pttrn \\<Rightarrow> bool \\<Rightarrow> 'a \\<Rightarrow> 'a\"  (\"(3SUM _ |/ _./ _)\" [0, 0, 10] 10)\nsyntax\n  \"_qsum\" :: \"pttrn \\<Rightarrow> bool \\<Rightarrow> 'a \\<Rightarrow> 'a\"  (\"(2\\<Sum>_ | (_)./ _)\" [0, 0, 10] 10)\ntranslations\n  \"\\<Sum>x|P. t\" => \"CONST sum (\\<lambda>x. t) {x. P}\"\n\nprint_translation \\<open>\nlet\n  fun sum_tr' [Abs (x, Tx, t), Const (\\<^const_syntax>\\<open>Collect\\<close>, _) $ Abs (y, Ty, P)] =\n        if x <> y then raise Match\n        else\n          let\n            val x' = Syntax_Trans.mark_bound_body (x, Tx);\n            val t' = subst_bound (x', t);\n            val P' = subst_bound (x', P);\n          in\n            Syntax.const \\<^syntax_const>\\<open>_qsum\\<close> $ Syntax_Trans.mark_bound_abs (x, Tx) $ P' $ t'\n          end\n    | sum_tr' _ = raise Match;\nin [(\\<^const_syntax>\\<open>sum\\<close>, K sum_tr')] end\n\\<close>\n\n\nsubsubsection \\<open>Properties in more restricted classes of structures\\<close>\n\nlemma sum_Un:\n  \"finite A \\<Longrightarrow> finite B \\<Longrightarrow> sum f (A \\<union> B) = sum f A + sum f B - sum f (A \\<inter> B)\"\n  for f :: \"'b \\<Rightarrow> 'a::ab_group_add\"\n  by (subst sum.union_inter [symmetric]) (auto simp add: algebra_simps)\n\nlemma sum_Un2:\n  assumes \"finite (A \\<union> B)\"\n  shows \"sum f (A \\<union> B) = sum f (A - B) + sum f (B - A) + sum f (A \\<inter> B)\"\nproof -\n  have \"A \\<union> B = A - B \\<union> (B - A) \\<union> A \\<inter> B\"\n    by auto\n  with assms show ?thesis\n    by simp (subst sum.union_disjoint, auto)+\nqed\n\n(*Like sum.subset_diff but expressed perhaps more conveniently using subtraction*)\nlemma sum_diff: \n  fixes f :: \"'b \\<Rightarrow> 'a::ab_group_add\"\n  assumes \"finite A\" \"B \\<subseteq> A\"\n  shows \"sum f (A - B) = sum f A - sum f B\"\n  using sum.subset_diff [of B A f] assms by simp\n\nlemma sum_diff1:\n  fixes f :: \"'b \\<Rightarrow> 'a::ab_group_add\"\n  assumes \"finite A\"\n  shows \"sum f (A - {a}) = (if a \\<in> A then sum f A - f a else sum f A)\"\n  using assms by (simp add: sum_diff)\n\nlemma sum_diff1'_aux:\n  fixes f :: \"'a \\<Rightarrow> 'b::ab_group_add\"\n  assumes \"finite F\" \"{i \\<in> I. f i \\<noteq> 0} \\<subseteq> F\"\n  shows \"sum' f (I - {i}) = (if i \\<in> I then sum' f I - f i else sum' f I)\"\n  using assms\nproof induct\n  case (insert x F)\n  have 1: \"finite {x \\<in> I. f x \\<noteq> 0} \\<Longrightarrow> finite {x \\<in> I. x \\<noteq> i \\<and> f x \\<noteq> 0}\"\n    by (erule rev_finite_subset) auto\n  have 2: \"finite {x \\<in> I. x \\<noteq> i \\<and> f x \\<noteq> 0} \\<Longrightarrow> finite {x \\<in> I. f x \\<noteq> 0}\"\n    apply (drule finite_insert [THEN iffD2])\n    by (erule rev_finite_subset) auto\n  have 3: \"finite {i \\<in> I. f i \\<noteq> 0}\"\n    using finite_subset insert by blast\n  show ?case\n    using insert sum_diff1 [of \"{i \\<in> I. f i \\<noteq> 0}\" f i]\n    by (auto simp: sum.G_def 1 2 3 set_diff_eq conj_ac)\nqed (simp add: sum.G_def)\n\nlemma sum_diff1':\n  fixes f :: \"'a \\<Rightarrow> 'b::ab_group_add\"\n  assumes \"finite {i \\<in> I. f i \\<noteq> 0}\"\n  shows \"sum' f (I - {i}) = (if i \\<in> I then sum' f I - f i else sum' f I)\"\n  by (rule sum_diff1'_aux [OF assms order_refl])\n\nlemma (in ordered_comm_monoid_add) sum_mono:\n  \"(\\<And>i. i\\<in>K \\<Longrightarrow> f i \\<le> g i) \\<Longrightarrow> (\\<Sum>i\\<in>K. f i) \\<le> (\\<Sum>i\\<in>K. g i)\"\n  by (induct K rule: infinite_finite_induct) (use add_mono in auto)\n\nlemma (in strict_ordered_comm_monoid_add) sum_strict_mono:\n  assumes \"finite A\" \"A \\<noteq> {}\"\n    and \"\\<And>x. x \\<in> A \\<Longrightarrow> f x < g x\"\n  shows \"sum f A < sum g A\"\n  using assms\nproof (induct rule: finite_ne_induct)\n  case singleton\n  then show ?case by simp\nnext\n  case insert\n  then show ?case by (auto simp: add_strict_mono)\nqed\n\nlemma sum_strict_mono_ex1:\n  fixes f g :: \"'i \\<Rightarrow> 'a::ordered_cancel_comm_monoid_add\"\n  assumes \"finite A\"\n    and \"\\<forall>x\\<in>A. f x \\<le> g x\"\n    and \"\\<exists>a\\<in>A. f a < g a\"\n  shows \"sum f A < sum g A\"\nproof-\n  from assms(3) obtain a where a: \"a \\<in> A\" \"f a < 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 \"sum f (A - {a}) \\<le> sum g (A - {a})\"\n    by (rule sum_mono) (simp add: assms(2))\n  also from a have \"sum f {a} < sum g {a}\" by simp\n  also have \"sum g (A - {a}) + sum g {a} = 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 (auto simp add: add_right_mono add_strict_left_mono)\nqed\n\nlemma sum_mono_inv:\n  fixes f g :: \"'i \\<Rightarrow> 'a :: ordered_cancel_comm_monoid_add\"\n  assumes eq: \"sum f I = sum g I\"\n  assumes le: \"\\<And>i. i \\<in> I \\<Longrightarrow> f i \\<le> g i\"\n  assumes i: \"i \\<in> I\"\n  assumes I: \"finite I\"\n  shows \"f i = g i\"\nproof (rule ccontr)\n  assume \"\\<not> ?thesis\"\n  with le[OF i] have \"f i < g i\" by simp\n  with i have \"\\<exists>i\\<in>I. f i < g i\" ..\n  from sum_strict_mono_ex1[OF I _ this] le have \"sum f I < sum g I\"\n    by blast\n  with eq show False by simp\nqed\n\nlemma member_le_sum:\n  fixes f :: \"_ \\<Rightarrow> 'b::{semiring_1, ordered_comm_monoid_add}\"\n  assumes \"i \\<in> A\"\n    and le: \"\\<And>x. x \\<in> A - {i} \\<Longrightarrow> 0 \\<le> f x\"\n    and \"finite A\"\n  shows \"f i \\<le> sum f A\"\nproof -\n  have \"f i \\<le> sum f (A \\<inter> {i})\"\n    by (simp add: assms)\n  also have \"... = (\\<Sum>x\\<in>A. if x \\<in> {i} then f x else 0)\"\n    using assms sum.inter_restrict by blast\n  also have \"... \\<le> sum f A\"\n    apply (rule sum_mono)\n    apply (auto simp: le)\n    done\n  finally show ?thesis .\nqed\n\nlemma sum_negf: \"(\\<Sum>x\\<in>A. - f x) = - (\\<Sum>x\\<in>A. f x)\"\n  for f :: \"'b \\<Rightarrow> 'a::ab_group_add\"\n  by (induct A rule: infinite_finite_induct) auto\n\nlemma sum_subtractf: \"(\\<Sum>x\\<in>A. f x - g x) = (\\<Sum>x\\<in>A. f x) - (\\<Sum>x\\<in>A. g x)\"\n  for f g :: \"'b \\<Rightarrow>'a::ab_group_add\"\n  using sum.distrib [of f \"- g\" A] by (simp add: sum_negf)\n\nlemma sum_subtractf_nat:\n  \"(\\<And>x. x \\<in> A \\<Longrightarrow> g x \\<le> f x) \\<Longrightarrow> (\\<Sum>x\\<in>A. f x - g x) = (\\<Sum>x\\<in>A. f x) - (\\<Sum>x\\<in>A. g x)\"\n  for f g :: \"'a \\<Rightarrow> nat\"\n  by (induct A rule: infinite_finite_induct) (auto simp: sum_mono)\n\ncontext ordered_comm_monoid_add\nbegin\n\nlemma sum_nonneg: \"(\\<And>x. x \\<in> A \\<Longrightarrow> 0 \\<le> f x) \\<Longrightarrow> 0 \\<le> sum f A\"\nproof (induct A rule: infinite_finite_induct)\n  case infinite\n  then show ?case by simp\nnext\n  case empty\n  then show ?case by simp\nnext\n  case (insert x F)\n  then have \"0 + 0 \\<le> f x + sum f F\" by (blast intro: add_mono)\n  with insert show ?case by simp\nqed\n\nlemma sum_nonpos: \"(\\<And>x. x \\<in> A \\<Longrightarrow> f x \\<le> 0) \\<Longrightarrow> sum f A \\<le> 0\"\nproof (induct A rule: infinite_finite_induct)\n  case infinite\n  then show ?case by simp\nnext\n  case empty\n  then show ?case by simp\nnext\n  case (insert x F)\n  then have \"f x + sum f F \\<le> 0 + 0\" by (blast intro: add_mono)\n  with insert show ?case by simp\nqed\n\nlemma sum_nonneg_eq_0_iff:\n  \"finite A \\<Longrightarrow> (\\<And>x. x \\<in> A \\<Longrightarrow> 0 \\<le> f x) \\<Longrightarrow> sum f A = 0 \\<longleftrightarrow> (\\<forall>x\\<in>A. f x = 0)\"\n  by (induct set: finite) (simp_all add: add_nonneg_eq_0_iff sum_nonneg)\n\nlemma sum_nonneg_0:\n  \"finite s \\<Longrightarrow> (\\<And>i. i \\<in> s \\<Longrightarrow> f i \\<ge> 0) \\<Longrightarrow> (\\<Sum> i \\<in> s. f i) = 0 \\<Longrightarrow> i \\<in> s \\<Longrightarrow> f i = 0\"\n  by (simp add: sum_nonneg_eq_0_iff)\n\nlemma sum_nonneg_leq_bound:\n  assumes \"finite s\" \"\\<And>i. i \\<in> s \\<Longrightarrow> f i \\<ge> 0\" \"(\\<Sum>i \\<in> s. f i) = B\" \"i \\<in> s\"\n  shows \"f i \\<le> B\"\nproof -\n  from assms have \"f i \\<le> f i + (\\<Sum>i \\<in> s - {i}. f i)\"\n    by (intro add_increasing2 sum_nonneg) auto\n  also have \"\\<dots> = B\"\n    using sum.remove[of s i f] assms by simp\n  finally show ?thesis by auto\nqed\n\nlemma sum_mono2:\n  assumes fin: \"finite B\"\n    and sub: \"A \\<subseteq> B\"\n    and nn: \"\\<And>b. b \\<in> B-A \\<Longrightarrow> 0 \\<le> f b\"\n  shows \"sum f A \\<le> sum f B\"\nproof -\n  have \"sum f A \\<le> sum f A + sum f (B-A)\"\n    by (auto intro: add_increasing2 [OF sum_nonneg] nn)\n  also from fin finite_subset[OF sub fin] have \"\\<dots> = sum f (A \\<union> (B-A))\"\n    by (simp add: sum.union_disjoint del: Un_Diff_cancel)\n  also from sub have \"A \\<union> (B-A) = B\" by blast\n  finally show ?thesis .\nqed\n\nlemma sum_le_included:\n  assumes \"finite s\" \"finite t\"\n  and \"\\<forall>y\\<in>t. 0 \\<le> g y\" \"(\\<forall>x\\<in>s. \\<exists>y\\<in>t. i y = x \\<and> f x \\<le> g y)\"\n  shows \"sum f s \\<le> sum g t\"\nproof -\n  have \"sum f s \\<le> sum (\\<lambda>y. sum g {x. x\\<in>t \\<and> i x = y}) s\"\n  proof (rule sum_mono)\n    fix y\n    assume \"y \\<in> s\"\n    with assms obtain z where z: \"z \\<in> t\" \"y = i z\" \"f y \\<le> g z\" by auto\n    with assms show \"f y \\<le> sum g {x \\<in> t. i x = y}\" (is \"?A y \\<le> ?B y\")\n      using order_trans[of \"?A (i z)\" \"sum g {z}\" \"?B (i z)\", intro]\n      by (auto intro!: sum_mono2)\n  qed\n  also have \"\\<dots> \\<le> sum (\\<lambda>y. sum g {x. x\\<in>t \\<and> i x = y}) (i ` t)\"\n    using assms(2-4) by (auto intro!: sum_mono2 sum_nonneg)\n  also have \"\\<dots> \\<le> sum g t\"\n    using assms by (auto simp: sum.image_gen[symmetric])\n  finally show ?thesis .\nqed\n\nend\n\nlemma (in canonically_ordered_monoid_add) sum_eq_0_iff [simp]:\n  \"finite F \\<Longrightarrow> (sum f F = 0) = (\\<forall>a\\<in>F. f a = 0)\"\n  by (intro ballI sum_nonneg_eq_0_iff zero_le)\n\ncontext semiring_0\nbegin\n\nlemma sum_distrib_left: \"r * sum f A = (\\<Sum>n\\<in>A. r * f n)\"\n  by (induct A rule: infinite_finite_induct) (simp_all add: algebra_simps)\n\nlemma sum_distrib_right: \"sum f A * r = (\\<Sum>n\\<in>A. f n * r)\"\n  by (induct A rule: infinite_finite_induct) (simp_all add: algebra_simps)\n\nend\n\nlemma sum_divide_distrib: \"sum f A / r = (\\<Sum>n\\<in>A. f n / r)\"\n  for r :: \"'a::field\"\nproof (induct A rule: infinite_finite_induct)\n  case infinite\n  then show ?case by simp\nnext\n  case empty\n  then show ?case by simp\nnext\n  case insert\n  then show ?case by (simp add: add_divide_distrib)\nqed\n\nlemma sum_abs[iff]: \"\\<bar>sum f A\\<bar> \\<le> sum (\\<lambda>i. \\<bar>f i\\<bar>) A\"\n  for f :: \"'a \\<Rightarrow> 'b::ordered_ab_group_add_abs\"\nproof (induct A rule: infinite_finite_induct)\n  case infinite\n  then show ?case by simp\nnext\n  case empty\n  then show ?case by simp\nnext\n  case insert\n  then show ?case by (auto intro: abs_triangle_ineq order_trans)\nqed\n\nlemma sum_abs_ge_zero[iff]: \"0 \\<le> sum (\\<lambda>i. \\<bar>f i\\<bar>) A\"\n  for f :: \"'a \\<Rightarrow> 'b::ordered_ab_group_add_abs\"\n  by (simp add: sum_nonneg)\n\nlemma abs_sum_abs[simp]: \"\\<bar>\\<Sum>a\\<in>A. \\<bar>f a\\<bar>\\<bar> = (\\<Sum>a\\<in>A. \\<bar>f a\\<bar>)\"\n  for f :: \"'a \\<Rightarrow> 'b::ordered_ab_group_add_abs\"\nproof (induct A rule: infinite_finite_induct)\n  case infinite\n  then show ?case by simp\nnext\n  case empty\n  then show ?case by simp\nnext\n  case (insert a A)\n  then have \"\\<bar>\\<Sum>a\\<in>insert a A. \\<bar>f a\\<bar>\\<bar> = \\<bar>\\<bar>f a\\<bar> + (\\<Sum>a\\<in>A. \\<bar>f a\\<bar>)\\<bar>\" by simp\n  also from insert have \"\\<dots> = \\<bar>\\<bar>f a\\<bar> + \\<bar>\\<Sum>a\\<in>A. \\<bar>f a\\<bar>\\<bar>\\<bar>\" by simp\n  also have \"\\<dots> = \\<bar>f a\\<bar> + \\<bar>\\<Sum>a\\<in>A. \\<bar>f a\\<bar>\\<bar>\" by (simp del: abs_of_nonneg)\n  also from insert have \"\\<dots> = (\\<Sum>a\\<in>insert a A. \\<bar>f a\\<bar>)\" by simp\n  finally show ?case .\nqed\n\nlemma sum_product:\n  fixes f :: \"'a \\<Rightarrow> 'b::semiring_0\"\n  shows \"sum f A * sum g B = (\\<Sum>i\\<in>A. \\<Sum>j\\<in>B. f i * g j)\"\n  by (simp add: sum_distrib_left sum_distrib_right) (rule sum.swap)\n\nlemma sum_mult_sum_if_inj:\n  fixes f :: \"'a \\<Rightarrow> 'b::semiring_0\"\n  shows \"inj_on (\\<lambda>(a, b). f a * g b) (A \\<times> B) \\<Longrightarrow>\n    sum f A * sum g B = sum id {f a * g b |a b. a \\<in> A \\<and> b \\<in> B}\"\n  by(auto simp: sum_product sum.cartesian_product intro!: sum.reindex_cong[symmetric])\n\nlemma sum_SucD: \"sum f A = Suc n \\<Longrightarrow> \\<exists>a\\<in>A. 0 < f a\"\n  by (induct A rule: infinite_finite_induct) auto\n\nlemma sum_eq_Suc0_iff:\n  \"finite A \\<Longrightarrow> sum f A = Suc 0 \\<longleftrightarrow> (\\<exists>a\\<in>A. f a = Suc 0 \\<and> (\\<forall>b\\<in>A. a \\<noteq> b \\<longrightarrow> f b = 0))\"\n  by (induct A rule: finite_induct) (auto simp add: add_is_1)\n\nlemmas sum_eq_1_iff = sum_eq_Suc0_iff[simplified One_nat_def[symmetric]]\n\nlemma sum_Un_nat:\n  \"finite A \\<Longrightarrow> finite B \\<Longrightarrow> sum f (A \\<union> B) = sum f A + sum f B - sum f (A \\<inter> B)\"\n  for f :: \"'a \\<Rightarrow> nat\"\n  \\<comment> \\<open>For the natural numbers, we have subtraction.\\<close>\n  by (subst sum.union_inter [symmetric]) (auto simp: algebra_simps)\n\nlemma sum_diff1_nat: \"sum f (A - {a}) = (if a \\<in> A then sum f A - f a else sum f A)\"\n  for f :: \"'a \\<Rightarrow> nat\"\nproof (induct A rule: infinite_finite_induct)\n  case infinite\n  then show ?case by simp\nnext\n  case empty\n  then show ?case by simp\nnext\n  case (insert x F)\n  then show ?case\n  proof (cases \"a \\<in> F\")\n    case True\n    then have \"\\<exists>B. F = insert a B \\<and> a \\<notin> B\"\n      by (auto simp: mk_disjoint_insert)\n    then show ?thesis  using insert\n      by (auto simp: insert_Diff_if)\n  qed (auto)\nqed\n\nlemma sum_diff_nat:\n  fixes f :: \"'a \\<Rightarrow> nat\"\n  assumes \"finite B\" and \"B \\<subseteq> A\"\n  shows \"sum f (A - B) = sum f A - sum f B\"\n  using assms\nproof induct\n  case empty\n  then show ?case by simp\nnext\n  case (insert x F)\n  note IH = \\<open>F \\<subseteq> A \\<Longrightarrow> sum f (A - F) = sum f A - sum f F\\<close>\n  from \\<open>x \\<notin> F\\<close> \\<open>insert x F \\<subseteq> A\\<close> have \"x \\<in> A - F\" by simp\n  then have A: \"sum f ((A - F) - {x}) = sum f (A - F) - f x\"\n    by (simp add: sum_diff1_nat)\n  from \\<open>insert x F \\<subseteq> A\\<close> have \"F \\<subseteq> A\" by simp\n  with IH have \"sum f (A - F) = sum f A - sum f F\" by simp\n  with A have B: \"sum f ((A - F) - {x}) = sum f A - sum f F - f x\"\n    by simp\n  from \\<open>x \\<notin> F\\<close> have \"A - insert x F = (A - F) - {x}\" by auto\n  with B have C: \"sum f (A - insert x F) = sum f A - sum f F - f x\"\n    by simp\n  from \\<open>finite F\\<close> \\<open>x \\<notin> F\\<close> have \"sum f (insert x F) = sum f F + f x\"\n    by simp\n  with C have \"sum f (A - insert x F) = sum f A - sum f (insert x F)\"\n    by simp\n  then show ?case by simp\nqed\n\nlemma sum_comp_morphism:\n  \"h 0 = 0 \\<Longrightarrow> (\\<And>x y. h (x + y) = h x + h y) \\<Longrightarrow> sum (h \\<circ> g) A = h (sum g A)\"\n  by (induct A rule: infinite_finite_induct) simp_all\n\nlemma (in comm_semiring_1) dvd_sum: \"(\\<And>a. a \\<in> A \\<Longrightarrow> d dvd f a) \\<Longrightarrow> d dvd sum f A\"\n  by (induct A rule: infinite_finite_induct) simp_all\n\nlemma (in ordered_comm_monoid_add) sum_pos:\n  \"finite I \\<Longrightarrow> I \\<noteq> {} \\<Longrightarrow> (\\<And>i. i \\<in> I \\<Longrightarrow> 0 < f i) \\<Longrightarrow> 0 < sum f I\"\n  by (induct I rule: finite_ne_induct) (auto intro: add_pos_pos)\n\nlemma (in ordered_comm_monoid_add) sum_pos2:\n  assumes I: \"finite I\" \"i \\<in> I\" \"0 < f i\" \"\\<And>i. i \\<in> I \\<Longrightarrow> 0 \\<le> f i\"\n  shows \"0 < sum f I\"\nproof -\n  have \"0 < f i + sum f (I - {i})\"\n    using assms by (intro add_pos_nonneg sum_nonneg) auto\n  also have \"\\<dots> = sum f I\"\n    using assms by (simp add: sum.remove)\n  finally show ?thesis .\nqed\n\nlemma sum_strict_mono2:\n  fixes f :: \"'a \\<Rightarrow> 'b::ordered_cancel_comm_monoid_add\"\n  assumes \"finite B\" \"A \\<subseteq> B\" \"b \\<in> B-A\" \"f b > 0\" and \"\\<And>x. x \\<in> B \\<Longrightarrow> f x \\<ge> 0\"\n  shows \"sum f A < sum f B\"\nproof -\n  have \"B - A \\<noteq> {}\"\n    using assms(3) by blast\n  have \"sum f (B-A) > 0\"\n    by (rule sum_pos2) (use assms in auto)\n  moreover have \"sum f B = sum f (B-A) + sum f A\"\n    by (rule sum.subset_diff) (use assms in auto)\n  ultimately show ?thesis\n    using add_strict_increasing by auto\nqed\n\nlemma sum_cong_Suc:\n  assumes \"0 \\<notin> A\" \"\\<And>x. Suc x \\<in> A \\<Longrightarrow> f (Suc x) = g (Suc x)\"\n  shows \"sum f A = sum g A\"\nproof (rule sum.cong)\n  fix x\n  assume \"x \\<in> A\"\n  with assms(1) show \"f x = g x\"\n    by (cases x) (auto intro!: assms(2))\nqed simp_all\n\n\nsubsubsection \\<open>Cardinality as special case of \\<^const>\\<open>sum\\<close>\\<close>\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\ncontext semiring_1\nbegin\n\nlemma sum_constant [simp]:\n  \"(\\<Sum>x \\<in> A. y) = of_nat (card A) * y\"\n  by (induct A rule: infinite_finite_induct) (simp_all add: algebra_simps)\n\ncontext\n  fixes A\n  assumes \\<open>finite A\\<close>\nbegin\n\nlemma sum_of_bool_eq [simp]:\n  \\<open>(\\<Sum>x \\<in> A. of_bool (P x)) = of_nat (card (A \\<inter> {x. P x}))\\<close> if \\<open>finite A\\<close>\n  using \\<open>finite A\\<close> by induction simp_all\n\nlemma sum_mult_of_bool_eq [simp]:\n  \\<open>(\\<Sum>x \\<in> A. f x * of_bool (P x)) = (\\<Sum>x \\<in> (A \\<inter> {x. P x}). f x)\\<close>\n  by (rule sum.mono_neutral_cong) (use \\<open>finite A\\<close> in auto)\n\nlemma sum_of_bool_mult_eq [simp]:\n  \\<open>(\\<Sum>x \\<in> A. of_bool (P x) * f x) = (\\<Sum>x \\<in> (A \\<inter> {x. P x}). f x)\\<close>\n  by (rule sum.mono_neutral_cong) (use \\<open>finite A\\<close> in auto)\n\nend\n\nend\n\nlemma sum_Suc: \"sum (\\<lambda>x. Suc(f x)) A = sum f A + card A\"\n  using sum.distrib[of f \"\\<lambda>_. 1\" A] by simp\n\nlemma sum_bounded_above:\n  fixes K :: \"'a::{semiring_1,ordered_comm_monoid_add}\"\n  assumes le: \"\\<And>i. i\\<in>A \\<Longrightarrow> f i \\<le> K\"\n  shows \"sum f A \\<le> of_nat (card A) * K\"\nproof (cases \"finite A\")\n  case True\n  then show ?thesis\n    using le sum_mono[where K=A and g = \"\\<lambda>x. K\"] by simp\nnext\n  case False\n  then show ?thesis by simp\nqed\n\nlemma sum_bounded_above_divide:\n  fixes K :: \"'a::linordered_field\"\n  assumes le: \"\\<And>i. i\\<in>A \\<Longrightarrow> f i \\<le> K / of_nat (card A)\" and fin: \"finite A\" \"A \\<noteq> {}\"\n  shows \"sum f A \\<le> K\"\n  using sum_bounded_above [of A f \"K / of_nat (card A)\", OF le] fin by simp\n\nlemma sum_bounded_above_strict:\n  fixes K :: \"'a::{ordered_cancel_comm_monoid_add,semiring_1}\"\n  assumes \"\\<And>i. i\\<in>A \\<Longrightarrow> f i < K\" \"card A > 0\"\n  shows \"sum f A < of_nat (card A) * K\"\n  using assms sum_strict_mono[where A=A and g = \"\\<lambda>x. K\"]\n  by (simp add: card_gt_0_iff)\n\nlemma sum_bounded_below:\n  fixes K :: \"'a::{semiring_1,ordered_comm_monoid_add}\"\n  assumes le: \"\\<And>i. i\\<in>A \\<Longrightarrow> K \\<le> f i\"\n  shows \"of_nat (card A) * K \\<le> sum f A\"\nproof (cases \"finite A\")\n  case True\n  then show ?thesis\n    using le sum_mono[where K=A and f = \"\\<lambda>x. K\"] by simp\nnext\n  case False\n  then show ?thesis by simp\nqed\n\nlemma convex_sum_bound_le:\n  fixes x :: \"'a \\<Rightarrow> 'b::linordered_idom\"\n  assumes 0: \"\\<And>i. i \\<in> I \\<Longrightarrow> 0 \\<le> x i\" and 1: \"sum x I = 1\"\n      and \\<delta>: \"\\<And>i. i \\<in> I \\<Longrightarrow> \\<bar>a i - b\\<bar> \\<le> \\<delta>\"\n    shows \"\\<bar>(\\<Sum>i\\<in>I. a i * x i) - b\\<bar> \\<le> \\<delta>\"\nproof -\n  have [simp]: \"(\\<Sum>i\\<in>I. c * x i) = c\" for c\n    by (simp flip: sum_distrib_left 1)\n  then have \"\\<bar>(\\<Sum>i\\<in>I. a i * x i) - b\\<bar> = \\<bar>\\<Sum>i\\<in>I. (a i - b) * x i\\<bar>\"\n    by (simp add: sum_subtractf left_diff_distrib)\n  also have \"\\<dots> \\<le> (\\<Sum>i\\<in>I. \\<bar>(a i - b) * x i\\<bar>)\"\n    using abs_abs abs_of_nonneg by blast\n  also have \"\\<dots> \\<le> (\\<Sum>i\\<in>I. \\<bar>(a i - b)\\<bar> * x i)\"\n    by (simp add: abs_mult 0)\n  also have \"\\<dots> \\<le> (\\<Sum>i\\<in>I. \\<delta> * x i)\"\n    by (rule sum_mono) (use \\<delta> \"0\" mult_right_mono in blast)\n  also have \"\\<dots> = \\<delta>\"\n    by simp\n  finally show ?thesis .\nqed\n\nlemma card_UN_disjoint:\n  assumes \"finite I\" and \"\\<forall>i\\<in>I. finite (A i)\"\n    and \"\\<forall>i\\<in>I. \\<forall>j\\<in>I. i \\<noteq> j \\<longrightarrow> A i \\<inter> A j = {}\"\n  shows \"card (\\<Union>(A ` I)) = (\\<Sum>i\\<in>I. card(A i))\"\nproof -\n  have \"(\\<Sum>i\\<in>I. card (A i)) = (\\<Sum>i\\<in>I. \\<Sum>x\\<in>A i. 1)\"\n    by simp\n  with assms show ?thesis\n    by (simp add: card_eq_sum sum.UNION_disjoint del: sum_constant)\nqed\n\nlemma card_Union_disjoint:\n  assumes \"pairwise disjnt C\" and fin: \"\\<And>A. A \\<in> C \\<Longrightarrow> finite A\"\n  shows \"card (\\<Union>C) = sum card C\"\nproof (cases \"finite C\")\n  case True\n  then show ?thesis\n    using card_UN_disjoint [OF True, of \"\\<lambda>x. x\"] assms\n    by (simp add: disjnt_def fin pairwise_def)\nnext\n  case False\n  then show ?thesis\n    using assms card_eq_0_iff finite_UnionD by fastforce\nqed\n\nlemma card_Union_le_sum_card_weak:\n  fixes U :: \"'a set set\"\n  assumes \"\\<forall>u \\<in> U. finite u\"\n  shows \"card (\\<Union>U) \\<le> sum card U\"\nproof (cases \"finite U\")\n  case False\n  then show \"card (\\<Union>U) \\<le> sum card U\"\n    using card_eq_0_iff finite_UnionD by auto\nnext\n  case True\n  then show \"card (\\<Union>U) \\<le> sum card U\"\n  proof (induct U rule: finite_induct)\n    case empty\n    then show ?case by auto\n  next\n    case (insert x F)\n    then have \"card(\\<Union>(insert x F)) \\<le> card(x) + card (\\<Union>F)\" using card_Un_le by auto\n    also have \"... \\<le> card(x) + sum card F\" using insert.hyps by auto\n    also have \"... = sum card (insert x F)\" using sum.insert_if and insert.hyps by auto\n    finally show ?case .\n  qed\nqed\n\nlemma card_Union_le_sum_card:\n  fixes U :: \"'a set set\"\n  shows \"card (\\<Union>U) \\<le> sum card U\"\n  by (metis Union_upper card.infinite card_Union_le_sum_card_weak finite_subset zero_le)\n\nlemma card_UN_le:\n  assumes \"finite I\"\n  shows \"card(\\<Union>i\\<in>I. A i) \\<le> (\\<Sum>i\\<in>I. card(A i))\"\n  using assms\nproof induction\n  case (insert i I)\n  then show ?case\n    using card_Un_le nat_add_left_cancel_le by (force intro: order_trans) \nqed auto\n\nlemma card_quotient_disjoint:\n  assumes \"finite A\" \"inj_on (\\<lambda>x. {x} // r) A\"\n  shows \"card (A//r) = card A\"\nproof -\n  have \"\\<forall>i\\<in>A. \\<forall>j\\<in>A. i \\<noteq> j \\<longrightarrow> r `` {j} \\<noteq> r `` {i}\"\n    using assms by (fastforce simp add: quotient_def inj_on_def)\n  with assms show ?thesis\n    by (simp add: quotient_def card_UN_disjoint)\nqed\n\nlemma sum_multicount_gen:\n  assumes \"finite s\" \"finite t\" \"\\<forall>j\\<in>t. (card {i\\<in>s. R i j} = k j)\"\n  shows \"sum (\\<lambda>i. (card {j\\<in>t. R i j})) s = sum k t\"\n    (is \"?l = ?r\")\nproof-\n  have \"?l = sum (\\<lambda>i. sum (\\<lambda>x.1) {j\\<in>t. R i j}) s\"\n    by auto\n  also have \"\\<dots> = ?r\"\n    unfolding sum.swap_restrict [OF assms(1-2)]\n    using assms(3) by auto\n  finally show ?thesis .\nqed\n\nlemma sum_multicount:\n  assumes \"finite S\" \"finite T\" \"\\<forall>j\\<in>T. (card {i\\<in>S. R i j} = k)\"\n  shows \"sum (\\<lambda>i. card {j\\<in>T. R i j}) S = k * card T\" (is \"?l = ?r\")\nproof-\n  have \"?l = sum (\\<lambda>i. k) T\"\n    by (rule sum_multicount_gen) (auto simp: assms)\n  also have \"\\<dots> = ?r\" by (simp add: mult.commute)\n  finally show ?thesis by auto\nqed\n\nlemma sum_card_image:\n  assumes \"finite A\"\n  assumes \"pairwise (\\<lambda>s t. disjnt (f s) (f t)) A\"\n  shows \"sum card (f ` A) = sum (\\<lambda>a. card (f a)) A\"\nusing assms\nproof (induct A)\n  case (insert a A)\n  show ?case\n  proof cases\n    assume \"f a = {}\"\n    with insert show ?case\n      by (subst sum.mono_neutral_right[where S=\"f ` A\"]) (auto simp: pairwise_insert)\n  next\n    assume \"f a \\<noteq> {}\"\n    then have \"sum card (insert (f a) (f ` A)) = card (f a) + sum card (f ` A)\"\n      using insert\n      by (subst sum.insert) (auto simp: pairwise_insert)\n    with insert show ?case by (simp add: pairwise_insert)\n  qed\nqed simp\n\ntext \\<open>By Jakub K\u0105dzio\u0142ka:\\<close>\n\nlemma sum_fun_comp:\n  assumes \"finite S\" \"finite R\" \"g ` S \\<subseteq> R\"\n  shows \"(\\<Sum>x \\<in> S. f (g x)) = (\\<Sum>y \\<in> R. of_nat (card {x \\<in> S. g x = y}) * f y)\"\nproof -\n  let ?r = \"relation_of (\\<lambda>p q. g p = g q) S\"\n  have eqv: \"equiv S ?r\"\n    unfolding relation_of_def by (auto intro: comp_equivI)\n  have finite: \"C \\<in> S//?r \\<Longrightarrow> finite C\" for C\n    by (fact finite_equiv_class[OF `finite S` equiv_type[OF `equiv S ?r`]])\n  have disjoint: \"A \\<in> S//?r \\<Longrightarrow> B \\<in> S//?r \\<Longrightarrow> A \\<noteq> B \\<Longrightarrow> A \\<inter> B = {}\" for A B\n    using eqv quotient_disj by blast\n\n  let ?cls = \"\\<lambda>y. {x \\<in> S. y = g x}\"\n  have quot_as_img: \"S//?r = ?cls ` g ` S\"\n    by (auto simp add: relation_of_def quotient_def)\n  have cls_inj: \"inj_on ?cls (g ` S)\"\n    by (auto intro: inj_onI)\n\n  have rest_0: \"(\\<Sum>y \\<in> R - g ` S. of_nat (card (?cls y)) * f y) = 0\"\n  proof -\n    have \"of_nat (card (?cls y)) * f y = 0\" if asm: \"y \\<in> R - g ` S\" for y\n    proof -\n      from asm have *: \"?cls y = {}\" by auto\n      show ?thesis unfolding * by simp\n    qed\n    thus ?thesis by simp\n  qed\n\n  have \"(\\<Sum>x \\<in> S. f (g x)) = (\\<Sum>C \\<in> S//?r. \\<Sum>x \\<in> C. f (g x))\"\n    using eqv finite disjoint\n    by (simp flip: sum.Union_disjoint[simplified] add: Union_quotient)\n  also have \"... = (\\<Sum>y \\<in> g ` S. \\<Sum>x \\<in> ?cls y. f (g x))\"\n    unfolding quot_as_img by (simp add: sum.reindex[OF cls_inj])\n  also have \"... = (\\<Sum>y \\<in> g ` S. \\<Sum>x \\<in> ?cls y. f y)\"\n    by auto\n  also have \"... = (\\<Sum>y \\<in> g ` S. of_nat (card (?cls y)) * f y)\"\n    by (simp flip: sum_constant)\n  also have \"... = (\\<Sum>y \\<in> R. of_nat (card (?cls y)) * f y)\"\n    using rest_0 by (simp add: sum.subset_diff[OF \\<open>g ` S \\<subseteq> R\\<close> \\<open>finite R\\<close>])\n  finally show ?thesis\n    by (simp add: eq_commute)\nqed\n\n\n\nsubsubsection \\<open>Cardinality of products\\<close>\n\nlemma card_SigmaI [simp]:\n  \"finite A \\<Longrightarrow> \\<forall>a\\<in>A. finite (B a) \\<Longrightarrow> card (SIGMA x: A. B x) = (\\<Sum>a\\<in>A. card (B a))\"\n  by (simp add: card_eq_sum sum.Sigma del: sum_constant)\n\n(*\nlemma SigmaI_insert: \"y \\<notin> A ==>\n  (SIGMA x:(insert y A). B x) = (({y} \\<times> (B y)) \\<union> (SIGMA x: A. B x))\"\n  by auto\n*)\n\nlemma card_cartesian_product: \"card (A \\<times> B) = card A * card B\"\n  by (cases \"finite A \\<and> finite B\")\n    (auto simp add: card_eq_0_iff dest: finite_cartesian_productD1 finite_cartesian_productD2)\n\nlemma card_cartesian_product_singleton:  \"card ({x} \\<times> A) = card A\"\n  by (simp add: card_cartesian_product)\n\n\nsubsection \\<open>Generalized product over a set\\<close>\n\ncontext comm_monoid_mult\nbegin\n\nsublocale prod: comm_monoid_set times 1\n  defines prod = prod.F and prod' = prod.G ..\n\nabbreviation Prod (\"\\<Prod>_\" [1000] 999)\n  where \"\\<Prod>A \\<equiv> prod (\\<lambda>x. x) A\"\n\nend\n\nsyntax (ASCII)\n  \"_prod\" :: \"pttrn => 'a set => 'b => 'b::comm_monoid_mult\"  (\"(4PROD (_/:_)./ _)\" [0, 51, 10] 10)\nsyntax\n  \"_prod\" :: \"pttrn => 'a set => 'b => 'b::comm_monoid_mult\"  (\"(2\\<Prod>(_/\\<in>_)./ _)\" [0, 51, 10] 10)\ntranslations \\<comment> \\<open>Beware of argument permutation!\\<close>\n  \"\\<Prod>i\\<in>A. b\" == \"CONST prod (\\<lambda>i. b) A\"\n\ntext \\<open>Instead of \\<^term>\\<open>\\<Prod>x\\<in>{x. P}. e\\<close> we introduce the shorter \\<open>\\<Prod>x|P. e\\<close>.\\<close>\n\nsyntax (ASCII)\n  \"_qprod\" :: \"pttrn \\<Rightarrow> bool \\<Rightarrow> 'a \\<Rightarrow> 'a\"  (\"(4PROD _ |/ _./ _)\" [0, 0, 10] 10)\nsyntax\n  \"_qprod\" :: \"pttrn \\<Rightarrow> bool \\<Rightarrow> 'a \\<Rightarrow> 'a\"  (\"(2\\<Prod>_ | (_)./ _)\" [0, 0, 10] 10)\ntranslations\n  \"\\<Prod>x|P. t\" => \"CONST prod (\\<lambda>x. t) {x. P}\"\n\ncontext comm_monoid_mult\nbegin\n\nlemma prod_dvd_prod: \"(\\<And>a. a \\<in> A \\<Longrightarrow> f a dvd g a) \\<Longrightarrow> prod f A dvd prod g A\"\nproof (induct A rule: infinite_finite_induct)\n  case infinite\n  then show ?case by (auto intro: dvdI)\nnext\n  case empty\n  then show ?case by (auto intro: dvdI)\nnext\n  case (insert a A)\n  then have \"f a dvd g a\" and \"prod f A dvd prod g A\"\n    by simp_all\n  then obtain r s where \"g a = f a * r\" and \"prod g A = prod f A * s\"\n    by (auto elim!: dvdE)\n  then have \"g a * prod g A = f a * prod f A * (r * s)\"\n    by (simp add: ac_simps)\n  with insert.hyps show ?case\n    by (auto intro: dvdI)\nqed\n\nlemma prod_dvd_prod_subset: \"finite B \\<Longrightarrow> A \\<subseteq> B \\<Longrightarrow> prod f A dvd prod f B\"\n  by (auto simp add: prod.subset_diff ac_simps intro: dvdI)\n\nend\n\n\nsubsubsection \\<open>Properties in more restricted classes of structures\\<close>\n\ncontext linordered_nonzero_semiring\nbegin\n\nlemma prod_ge_1: \"(\\<And>x. x \\<in> A \\<Longrightarrow> 1 \\<le> f x) \\<Longrightarrow> 1 \\<le> prod f A\"\nproof (induct A rule: infinite_finite_induct)\n  case infinite\n  then show ?case by simp\nnext\n  case empty\n  then show ?case by simp\nnext\n  case (insert x F)\n  have \"1 * 1 \\<le> f x * prod f F\"\n    by (rule mult_mono') (use insert in auto)\n  with insert show ?case by simp\nqed\n\nlemma prod_le_1:\n  fixes f :: \"'b \\<Rightarrow> 'a\"\n  assumes \"\\<And>x. x \\<in> A \\<Longrightarrow> 0 \\<le> f x \\<and> f x \\<le> 1\"\n  shows \"prod f A \\<le> 1\"\n    using assms\nproof (induct A rule: infinite_finite_induct)\n  case infinite\n  then show ?case by simp\nnext\n  case empty\n  then show ?case by simp\nnext\n  case (insert x F)\n  then show ?case by (force simp: mult.commute intro: dest: mult_le_one)\nqed\n\nend\n\ncontext comm_semiring_1\nbegin\n\nlemma dvd_prod_eqI [intro]:\n  assumes \"finite A\" and \"a \\<in> A\" and \"b = f a\"\n  shows \"b dvd prod f A\"\nproof -\n  from \\<open>finite A\\<close> have \"prod f (insert a (A - {a})) = f a * prod f (A - {a})\"\n    by (intro prod.insert) auto\n  also from \\<open>a \\<in> A\\<close> have \"insert a (A - {a}) = A\"\n    by blast\n  finally have \"prod f A = f a * prod f (A - {a})\" .\n  with \\<open>b = f a\\<close> show ?thesis\n    by simp\nqed\n\nlemma dvd_prodI [intro]: \"finite A \\<Longrightarrow> a \\<in> A \\<Longrightarrow> f a dvd prod f A\"\n  by auto\n\nlemma prod_zero:\n  assumes \"finite A\" and \"\\<exists>a\\<in>A. f a = 0\"\n  shows \"prod f A = 0\"\n  using assms\nproof (induct A)\n  case empty\n  then show ?case by simp\nnext\n  case (insert a A)\n  then have \"f a = 0 \\<or> (\\<exists>a\\<in>A. f a = 0)\" by simp\n  then have \"f a * prod f A = 0\" by (rule disjE) (simp_all add: insert)\n  with insert show ?case by simp\nqed\n\nlemma prod_dvd_prod_subset2:\n  assumes \"finite B\" and \"A \\<subseteq> B\" and \"\\<And>a. a \\<in> A \\<Longrightarrow> f a dvd g a\"\n  shows \"prod f A dvd prod g B\"\nproof -\n  from assms have \"prod f A dvd prod g A\"\n    by (auto intro: prod_dvd_prod)\n  moreover from assms have \"prod g A dvd prod g B\"\n    by (auto intro: prod_dvd_prod_subset)\n  ultimately show ?thesis by (rule dvd_trans)\nqed\n\nend\n\nlemma (in semidom) prod_zero_iff [simp]:\n  fixes f :: \"'b \\<Rightarrow> 'a\"\n  assumes \"finite A\"\n  shows \"prod f A = 0 \\<longleftrightarrow> (\\<exists>a\\<in>A. f a = 0)\"\n  using assms by (induct A) (auto simp: no_zero_divisors)\n\nlemma (in semidom_divide) prod_diff1:\n  assumes \"finite A\" and \"f a \\<noteq> 0\"\n  shows \"prod f (A - {a}) = (if a \\<in> A then prod f A div f a else prod f A)\"\nproof (cases \"a \\<notin> A\")\n  case True\n  then show ?thesis by simp\nnext\n  case False\n  with assms show ?thesis\n  proof induct\n    case empty\n    then show ?case by simp\n  next\n    case (insert b B)\n    then show ?case\n    proof (cases \"a = b\")\n      case True\n      with insert show ?thesis by simp\n    next\n      case False\n      with insert have \"a \\<in> B\" by simp\n      define C where \"C = B - {a}\"\n      with \\<open>finite B\\<close> \\<open>a \\<in> B\\<close> have \"B = insert a C\" \"finite C\" \"a \\<notin> C\"\n        by auto\n      with insert show ?thesis\n        by (auto simp add: insert_commute ac_simps)\n    qed\n  qed\nqed\n\nlemma sum_zero_power [simp]: \"(\\<Sum>i\\<in>A. c i * 0^i) = (if finite A \\<and> 0 \\<in> A then c 0 else 0)\"\n  for c :: \"nat \\<Rightarrow> 'a::division_ring\"\n  by (induct A rule: infinite_finite_induct) auto\n\nlemma sum_zero_power' [simp]:\n  \"(\\<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  for c :: \"nat \\<Rightarrow> 'a::field\"\n  using sum_zero_power [of \"\\<lambda>i. c i / d i\" A] by auto\n\nlemma (in field) prod_inversef: \"prod (inverse \\<circ> f) A = inverse (prod f A)\"\n proof (cases \"finite A\")\n   case True\n   then show ?thesis\n     by (induct A rule: finite_induct) simp_all\n next\n   case False\n   then show ?thesis\n     by auto\n qed\n\nlemma (in field) prod_dividef: \"(\\<Prod>x\\<in>A. f x / g x) = prod f A / prod g A\"\n  using prod_inversef [of g A] by (simp add: divide_inverse prod.distrib)\n\nlemma prod_Un:\n  fixes f :: \"'b \\<Rightarrow> 'a :: field\"\n  assumes \"finite A\" and \"finite B\"\n    and \"\\<forall>x\\<in>A \\<inter> B. f x \\<noteq> 0\"\n  shows \"prod f (A \\<union> B) = prod f A * prod f B / prod f (A \\<inter> B)\"\nproof -\n  from assms have \"prod f A * prod f B = prod f (A \\<union> B) * prod f (A \\<inter> B)\"\n    by (simp add: prod.union_inter [symmetric, of A B])\n  with assms show ?thesis\n    by simp\nqed\n\ncontext linordered_semidom\nbegin\n\nlemma prod_nonneg: \"(\\<forall>a\\<in>A. 0 \\<le> f a) \\<Longrightarrow> 0 \\<le> prod f A\"\n  by (induct A rule: infinite_finite_induct) simp_all\n\nlemma prod_pos: \"(\\<forall>a\\<in>A. 0 < f a) \\<Longrightarrow> 0 < prod f A\"\n  by (induct A rule: infinite_finite_induct) simp_all\n\nlemma prod_mono:\n  \"(\\<And>i. i \\<in> A \\<Longrightarrow> 0 \\<le> f i \\<and> f i \\<le> g i) \\<Longrightarrow> prod f A \\<le> prod g A\"\n  by (induct A rule: infinite_finite_induct) (force intro!: prod_nonneg mult_mono)+\n\nlemma prod_mono_strict:\n  assumes \"finite A\" \"\\<And>i. i \\<in> A \\<Longrightarrow> 0 \\<le> f i \\<and> f i < g i\" \"A \\<noteq> {}\"\n  shows \"prod f A < prod g A\"\n  using assms\nproof (induct A rule: finite_induct)\n  case empty\n  then show ?case by simp\nnext\n  case insert\n  then show ?case by (force intro: mult_strict_mono' prod_nonneg)\nqed\n\nlemma prod_le_power:\n  assumes A: \"\\<And>i. i \\<in> A \\<Longrightarrow> 0 \\<le> f i \\<and> f i \\<le> n\" \"card A \\<le> k\" and \"n \\<ge> 1\"\n  shows \"prod f A \\<le> n ^ k\"\n  using A\nproof (induction A arbitrary: k rule: infinite_finite_induct)\n  case (insert i A)\n  then obtain k' where k': \"card A \\<le> k'\" \"k = Suc k'\"\n    using Suc_le_D by force\n  have \"f i * prod f A \\<le> n * n ^ k'\"\n    using insert \\<open>n \\<ge> 1\\<close> k' by (intro prod_nonneg mult_mono; force)\n  then show ?case \n    by (auto simp: \\<open>k = Suc k'\\<close> insert.hyps)\nqed (use \\<open>n \\<ge> 1\\<close> in auto)\n\nend\n\nlemma prod_mono2:\n  fixes f :: \"'a \\<Rightarrow> 'b :: linordered_idom\"\n  assumes fin: \"finite B\"\n    and sub: \"A \\<subseteq> B\"\n    and nn: \"\\<And>b. b \\<in> B-A \\<Longrightarrow> 1 \\<le> f b\"\n    and A: \"\\<And>a. a \\<in> A \\<Longrightarrow> 0 \\<le> f a\"\n  shows \"prod f A \\<le> prod f B\"\nproof -\n  have \"prod f A \\<le> prod f A * prod f (B-A)\"\n    by (metis prod_ge_1 A mult_le_cancel_left1 nn not_less prod_nonneg)\n  also from fin finite_subset[OF sub fin] have \"\\<dots> = prod f (A \\<union> (B-A))\"\n    by (simp add: prod.union_disjoint del: Un_Diff_cancel)\n  also from sub have \"A \\<union> (B-A) = B\" by blast\n  finally show ?thesis .\nqed\n\nlemma less_1_prod:\n  fixes f :: \"'a \\<Rightarrow> 'b::linordered_idom\"\n  shows \"finite I \\<Longrightarrow> I \\<noteq> {} \\<Longrightarrow> (\\<And>i. i \\<in> I \\<Longrightarrow> 1 < f i) \\<Longrightarrow> 1 < prod f I\"\n  by (induct I rule: finite_ne_induct) (auto intro: less_1_mult)\n\nlemma less_1_prod2:\n  fixes f :: \"'a \\<Rightarrow> 'b::linordered_idom\"\n  assumes I: \"finite I\" \"i \\<in> I\" \"1 < f i\" \"\\<And>i. i \\<in> I \\<Longrightarrow> 1 \\<le> f i\"\n  shows \"1 < prod f I\"\nproof -\n  have \"1 < f i * prod f (I - {i})\"\n    using assms\n    by (meson DiffD1 leI less_1_mult less_le_trans mult_le_cancel_left1 prod_ge_1)\n  also have \"\\<dots> = prod f I\"\n    using assms by (simp add: prod.remove)\n  finally show ?thesis .\nqed\n\nlemma (in linordered_field) abs_prod: \"\\<bar>prod f A\\<bar> = (\\<Prod>x\\<in>A. \\<bar>f x\\<bar>)\"\n  by (induct A rule: infinite_finite_induct) (simp_all add: abs_mult)\n\nlemma prod_eq_1_iff [simp]: \"finite A \\<Longrightarrow> prod f A = 1 \\<longleftrightarrow> (\\<forall>a\\<in>A. f a = 1)\"\n  for f :: \"'a \\<Rightarrow> nat\"\n  by (induct A rule: finite_induct) simp_all\n\nlemma prod_pos_nat_iff [simp]: \"finite A \\<Longrightarrow> prod f A > 0 \\<longleftrightarrow> (\\<forall>a\\<in>A. f a > 0)\"\n  for f :: \"'a \\<Rightarrow> nat\"\n  using prod_zero_iff by (simp del: neq0_conv add: zero_less_iff_neq_zero)\n\nlemma prod_constant [simp]: \"(\\<Prod>x\\<in> A. y) = y ^ card A\"\n  for y :: \"'a::comm_monoid_mult\"\n  by (induct A rule: infinite_finite_induct) simp_all\n\nlemma prod_power_distrib: \"prod f A ^ n = prod (\\<lambda>x. (f x) ^ n) A\"\n  for f :: \"'a \\<Rightarrow> 'b::comm_semiring_1\"\n  by (induct A rule: infinite_finite_induct) (auto simp add: power_mult_distrib)\n\nlemma power_sum: \"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 prod_gen_delta:\n  fixes b :: \"'b \\<Rightarrow> 'a::comm_monoid_mult\"\n  assumes fin: \"finite S\"\n  shows \"prod (\\<lambda>k. if k = a then b k else c) S =\n    (if a \\<in> S then b a * c ^ (card S - 1) else c ^ card S)\"\nproof -\n  let ?f = \"(\\<lambda>k. if k=a then b k else c)\"\n  show ?thesis\n  proof (cases \"a \\<in> S\")\n    case False\n    then have \"\\<forall> k\\<in> S. ?f k = c\" by simp\n    with False show ?thesis by (simp add: prod_constant)\n  next\n    case True\n    let ?A = \"S - {a}\"\n    let ?B = \"{a}\"\n    from True have eq: \"S = ?A \\<union> ?B\" by blast\n    have disjoint: \"?A \\<inter> ?B = {}\" by simp\n    from fin have fin': \"finite ?A\" \"finite ?B\" by auto\n    have f_A0: \"prod ?f ?A = prod (\\<lambda>i. c) ?A\"\n      by (rule prod.cong) auto\n    from fin True have card_A: \"card ?A = card S - 1\" by auto\n    have f_A1: \"prod ?f ?A = c ^ card ?A\"\n      unfolding f_A0 by (rule prod_constant)\n    have \"prod ?f ?A * prod ?f ?B = prod ?f S\"\n      using prod.union_disjoint[OF fin' disjoint, of ?f, unfolded eq[symmetric]]\n      by simp\n    with True card_A show ?thesis\n      by (simp add: f_A1 field_simps cong add: prod.cong cong del: if_weak_cong)\n  qed\nqed\n\nlemma sum_image_le:\n  fixes g :: \"'a \\<Rightarrow> 'b::ordered_comm_monoid_add\"\n  assumes \"finite I\" \"\\<And>i. i \\<in> I \\<Longrightarrow> 0 \\<le> g(f i)\"\n    shows \"sum g (f ` I) \\<le> sum (g \\<circ> f) I\"\n  using assms\nproof induction\n  case empty\n  then show ?case by auto\nnext\n  case (insert x F)\n  from insertI1 have \"0 \\<le> g (f x)\" by (rule insert)\n  hence 1: \"sum g (f ` F) \\<le> g (f x) + sum g (f ` F)\" using add_increasing by blast\n  have 2: \"sum g (f ` F) \\<le> sum (g \\<circ> f) F\" using insert by blast\n  have \"sum g (f ` insert x F) = sum g (insert (f x) (f ` F))\" by simp\n  also have \"\\<dots> \\<le> g (f x) + sum g (f ` F)\" by (simp add: 1 insert sum.insert_if)\n  also from 2 have \"\\<dots> \\<le> g (f x) + sum (g \\<circ> f) F\" by (rule add_left_mono)\n  also from insert(1, 2) have \"\\<dots> = sum (g \\<circ> f) (insert x F)\" by (simp add: sum.insert_if)\n  finally show ?case .\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/Groups_Big.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8244619350028204, "lm_q2_score": 0.8705972566572504, "lm_q1q2_score": 0.7177742988317837}}
{"text": "\ntheory Lists1_2\nimports Main\nbegin\n\nprimrec replace :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a list \\<Rightarrow> 'a list\"\nwhere\n  \"replace x y [] = []\" |\n  \"replace x y (z # zs) = (if x = z then (y # (replace x y zs)) else (z # (replace x y zs)))\"\n\nlemma rev_replace_append: \"replace x y (xs @ ys) = (replace x y xs) @ (replace x y ys)\"\n  apply (induct_tac xs)\n  apply auto\ndone\n\nlemma \"rev(replace x y zs) = replace x y (rev zs)\"\n  apply (induct_tac zs)\n  apply (auto simp add:rev_replace_append)\ndone\n\nlemma \"replace x y (replace u v zs) = replace u v (replace x y zs)\"\n  quickcheck\noops\n\nlemma \"replace y z (replace x y zs) = replace x z zs\"\n  quickcheck\noops\n\nprimrec del1 :: \"'a \\<Rightarrow> 'a list \\<Rightarrow> 'a list\"\nwhere\n  \"del1 x [] = []\" |\n  \"del1 x (y # ys) = (if x = y then ys else (y # (del1 x ys)))\"\n\nprimrec delall :: \"'a \\<Rightarrow> 'a list \\<Rightarrow> 'a list\"\nwhere\n  \"delall x [] = []\" |\n  \"delall x (y # ys) = (if x = y then [] else [y]) @ (delall x ys)\"\n\ntheorem testth_1: \"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 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 simp\n  apply (simp add:testth_1)\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\ntheorem \"delall y (replace x y xs) = delall x xs\"\n  quickcheck\noops\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\ntheorem \"rev(del1 x xs) = del1 x (rev xs)\"\n  quickcheck\noops\n\nlemma delall_1: \"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 (simp add:delall_1)+\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_2.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972684083609, "lm_q2_score": 0.8244619220634456, "lm_q1q2_score": 0.7177742972551427}}
{"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_MSortBU2Permutes\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 elem :: \"'a => 'a list => bool\" where\n  \"elem x (nil2) = False\"\n| \"elem x (cons2 z xs) = ((z = x) | (elem x xs))\"\n\nfun deleteBy :: \"('a => ('a => bool)) => 'a => 'a list =>\n                 'a list\" where\n  \"deleteBy x y (nil2) = nil2\"\n| \"deleteBy x y (cons2 y2 ys) =\n     (if (x y) y2 then ys else cons2 y2 (deleteBy x y ys))\"\n\nfun isPermutation :: \"'a list => 'a list => bool\" where\n  \"isPermutation (nil2) (nil2) = True\"\n| \"isPermutation (nil2) (cons2 z x2) = False\"\n| \"isPermutation (cons2 x3 xs) y =\n     ((elem x3 y) &\n        (isPermutation\n           xs (deleteBy (% (x4 :: 'a) => % (x5 :: 'a) => (x4 = x5)) x3 y)))\"\n\ntheorem property0 :\n  \"isPermutation (msortbu2 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_sort_nat_MSortBU2Permutes.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513786759491, "lm_q2_score": 0.8006920020959544, "lm_q1q2_score": 0.717621310773305}}
{"text": "theory CTL\n  imports Main\n\nbegin\ntext\\<open>Define and verify a model checker of properties defined in CTL on FTS.\nProofs are often provided twice, a slegehammer found one, and the more-manual\n one from the tutorial\\<close>\n\ntext\\<open>state is a type parameter of the theory\\<close>\ntypedecl state\n\ntext\\<open>arbitrary but fixed transition systems defined as a\nrelation between states\\<close>\nconsts M :: \"(state \\<times> state) set\"\n\ntext\\<open>type of atomic propositions\\<close>\ntypedecl \"atom\"\n\ntext\\<open>The labelling function that defines what subset of atoms\nhold in a particular state\\<close>\nconsts L :: \"state \\<Rightarrow> atom set\"\n\ntext\\<open>Formulae of Proposition Dynamic Logic are built up from atoms, negation,\nconjunction and temporal connectives \"all branches next\" and \"some branches\neventually\\<close>\ndatatype formula = Atom \"atom\"\n  | Neg formula\n  | And formula formula\n  | AX formula\n  | EF formula\n\ntext\\<open>Validity relation, when a particular PDL formul holds\\<close>\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\\<open>Now we define our model checker\\<close>\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^-1 `` T))\"\n\ntext\\<open>Proove that mc(EF _) is monotonic, and therefore has a least fixed point\\<close>\nlemma mono_ef: \"mono(\\<lambda>T. A \\<union> (M^-1 `` T))\"\n  by (smt Image_Un Un_iff monoI subsetI sup.order_iff)\n\nlemma mono_ef': \"mono(\\<lambda>T. A \\<union> (M^-1 `` T))\"\n  apply (rule monoI)\n  by blast\n\ntext\\<open>relate model checking with the logical semantics\\<close>\nlemma EF_lemma: \"lfp(\\<lambda>T. A \\<union> (M^-1 `` T)) = {s. \\<exists>t. (s, t) \\<in> M\\<^sup>* \\<and> t \\<in> A}\"\n  by try\n\nend", "meta": {"author": "tomssem", "repo": "isabelle_cheatsheet", "sha": "bc6a58e8d67590c801641934e5a1a375309dbc5f", "save_path": "github-repos/isabelle/tomssem-isabelle_cheatsheet", "path": "github-repos/isabelle/tomssem-isabelle_cheatsheet/isabelle_cheatsheet-bc6a58e8d67590c801641934e5a1a375309dbc5f/CTL.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513786759492, "lm_q2_score": 0.8006919925839875, "lm_q1q2_score": 0.7176213022481917}}
{"text": "theory Cyclic_Group_Ext imports \n  CryptHOL.CryptHOL\n  \"HOL-Number_Theory.Cong\"\nbegin\n\ncontext cyclic_group begin\n\nlemma generator_pow_order: \"\\<^bold>g [^] order G = \\<one>\"\nproof(cases \"order G > 0\")\n  case True\n  hence fin: \"finite (carrier G)\" by(simp add: order_gt_0_iff_finite)\n  then have [symmetric]: \"(\\<lambda>x. x \\<otimes> \\<^bold>g) ` carrier G = carrier G\"\n    by(rule endo_inj_surj)(auto simp add: inj_on_multc)\n  then have \"carrier G = (\\<lambda> n. \\<^bold>g [^] Suc n) ` {..<order G}\" using fin \n    by(simp add: carrier_conv_generator image_image)\n  then obtain n where n: \"\\<one> = \\<^bold>g [^] Suc n\" \"n < order G\" by auto\n  have \"n = order G - 1\" using n inj_onD[OF inj_on_generator, of 0 \"Suc n\"] by fastforce\n  with True n show ?thesis by auto\nqed simp\n\n\n\nlemma pow_generator_mod: \"\\<^bold>g [^] (k mod order G) = \\<^bold>g [^] k\"\nproof(cases \"order G > 0\")\n  case True\n  obtain n where n: \"k = n * order G + k mod order G\" by (metis div_mult_mod_eq)\n  have \"\\<^bold>g [^] k = (\\<^bold>g [^] order G) [^] n \\<otimes> \\<^bold>g [^] (k mod order G)\" \n    by(subst n)(simp add: nat_pow_mult nat_pow_pow mult_ac)\n  then show ?thesis by(simp add: generator_pow_order)\nqed simp\n\nlemma pow_carrier_mod: \n  assumes \"g \\<in> carrier G\"\n  shows \"g [^] (k mod order G) = g [^] k\"\n  using assms pow_generator_mod \n  by (metis generatorE generator_closed mod_mult_right_eq nat_pow_pow)\n\nlemma pow_generator_mod_int: \"\\<^bold>g [^] ((k::int) mod order G) = \\<^bold>g [^] k\"\nproof(cases \"order G > 0\")\n  case True\n  obtain n :: int where n: \"k = n * order G + k mod order G\"   \n    by (metis div_mult_mod_eq)\n  have \"\\<^bold>g [^] k = (\\<^bold>g [^] order G) [^] n \\<otimes> \\<^bold>g [^] (k mod order G)\" \n    apply(subst n)apply(simp add: int_pow_mult int_pow_pow mult_ac)\n    by (metis generator_closed int_pow_int int_pow_pow mult.commute)\n  then show ?thesis by(simp add: generator_pow_order)\nqed simp\n\nlemma pow_generator_eq_iff_cong:\n  \"finite (carrier G) \\<Longrightarrow> \\<^bold>g [^] x = \\<^bold>g [^] y \\<longleftrightarrow> [x = y] (mod order G)\"\n  apply(subst (1 2) pow_generator_mod[symmetric])\n  by(auto simp add: cong_def order_gt_0_iff_finite intro: inj_onD[OF inj_on_generator])\n\nlemma power_distrib: \n  assumes \"h \\<in> carrier G\" \n  shows \"\\<^bold>g [^] (e :: nat) \\<otimes> h [^] e = (\\<^bold>g \\<otimes> h ) [^] e\"\n(is \"?lhs = ?rhs\")\nproof-\n  obtain x :: nat where x: \"h = \\<^bold>g [^] x\" \n    using assms generatorE by blast\n  hence \"?lhs = \\<^bold>g [^] (e * (1 + x))\" \n    by (simp add: nat_pow_mult mult.commute nat_pow_pow)\n  also have \"... = (\\<^bold>g [^] (1 + x)) [^] e\" \n    by (metis generator_closed mult.commute nat_pow_pow)\n  ultimately show ?thesis \n    by (metis x One_nat_def generator_closed l_one monoid.nat_pow_Suc monoid_axioms nat_pow_0 nat_pow_mult)\nqed\n\nlemma neg_power_inverse:\n  assumes \"g \\<in> carrier G\" \n    and \"x < order G\"\n  shows \"g [^] (order G - (x :: nat)) = inv (g [^] x)\"\nproof-\n  have \"inv (g [^] x) = g [^] (- int x)\"  \n    by (simp add: int_pow_int int_pow_neg assms)\n  moreover have \"g [^] (order G - (x :: nat)) = g [^] (- int x)\"\n  proof-\n    have \"g [^] ((order G - (x :: nat)) mod (order G)) = g [^] ((- int x) mod (order G))\" \n    proof-\n      have \"(order G - (x :: nat)) mod (order G) = (- int x) mod (order G)\" \n        using assms(2) zmod_zminus1_eq_if by auto\n      thus ?thesis \n        by (metis int_pow_int)\n    qed\n    thus ?thesis \n    proof -\n      have f1: \"\\<forall>a. a [^] int 0 = \\<one>\"\n        by simp\n      have f2: \"\\<forall>n na. ((na::nat) + n) mod na = n mod na\"\n        by simp\n        have f3: \"\\<forall>a aa. aa \\<otimes> a [^] int 0 = aa \\<or> aa \\<notin> carrier G\"\n          by force\n        have f4: \"\\<forall>i a aa. a [^] int 0 \\<otimes> aa [^] i = aa [^] (int 0 + i) \\<or> aa \\<notin> carrier G\"\n          by force\n        have \"\\<forall>n a. a [^] int (n * 0) = a [^] (int 0 + int 0) \\<or> a \\<notin> carrier G\"\n          by simp\n        then have f5: \"\\<forall>a aa. aa [^] int (order G) = a [^] int 0 \\<or> aa \\<notin> carrier G\"\n          using f4 f3 f2 f1 by (metis int_pow_closed int_pow_int mod_mult_self2 pow_carrier_mod)\n        have \"\\<forall>n na. int (n - na) = - int na + int n \\<or> \\<not> na \\<le> n\"\n          by auto\n        then show ?thesis\n          using f5 f3 by (metis assms(1) assms(2) int_pow_closed int_pow_int int_pow_mult less_imp_le_nat)\n      qed\n    qed\n  ultimately show ?thesis by simp\nqed\n\nlemma int_nat_pow: assumes \"a \\<ge> 0\" shows \"(\\<^bold>g [^] (int (a ::nat))) [^] (b::int)  = \\<^bold>g [^] (a*b)\"\n  using assms \nproof(cases \"a >0\")\n  case True \n  show ?thesis\n    using int_pow_pow by blast\nnext case False\n  have \"(\\<^bold>g [^] (int (a ::nat))) [^] (b::int) = \\<one>\" using False by simp\n  also have \"\\<^bold>g [^] (a*b) = \\<one>\" using False by simp\n  ultimately show ?thesis by simp\nqed\n\n\n\nlemma cyclic_group_commute: assumes \"a \\<in> carrier G\" \"b \\<in> carrier G\" shows \"a \\<otimes> b = b \\<otimes> a\"\n(is \"?lhs = ?rhs\")\nproof-\n  obtain n :: nat where n: \"a = \\<^bold>g [^] n\" using generatorE assms by auto\n  also  obtain k :: nat where k: \"b = \\<^bold>g [^] k\" using generatorE assms by auto\n  ultimately have \"?lhs =  \\<^bold>g [^] n \\<otimes> \\<^bold>g [^] k\" by simp\n  then have \"... = \\<^bold>g [^] (n + k)\" by(simp add: nat_pow_mult)\n  then have \"... = \\<^bold>g [^] (k + n)\" by(simp add: add.commute)\n  then show ?thesis by(simp add: nat_pow_mult n k)\nqed\n\nlemma cyclic_group_assoc: \n  assumes \"a \\<in> carrier G\" \"b \\<in> carrier G\" \"c \\<in> carrier G\"\n  shows \"(a \\<otimes> b) \\<otimes> c = a \\<otimes> (b \\<otimes> c)\"\n(is \"?lhs = ?rhs\")\nproof-\n  obtain n :: nat where n: \"a = \\<^bold>g [^] n\" using generatorE assms by auto\n  obtain k :: nat where k: \"b = \\<^bold>g [^] k\" using generatorE assms by auto\n  obtain j :: nat where j: \"c = \\<^bold>g [^] j\" using generatorE assms by auto \n  have \"?lhs = (\\<^bold>g [^] n \\<otimes> \\<^bold>g [^] k) \\<otimes> \\<^bold>g [^] j\" using n k j by simp\n  then have \"... = \\<^bold>g [^] (n + (k + j))\" by(simp add: nat_pow_mult add.assoc)\n  then show ?thesis by(simp add: nat_pow_mult n k j)\nqed\n \nlemma l_cancel_inv: \n  assumes \"h \\<in> carrier G\" \n  shows \"(\\<^bold>g [^] (a :: nat) \\<otimes> inv (\\<^bold>g [^] a)) \\<otimes> h = h\"\n(is \"?lhs = ?rhs\")\nproof-\n  have \"?lhs = (\\<^bold>g [^] int a \\<otimes> inv (\\<^bold>g [^] int a)) \\<otimes> h\" by simp\n  then have \"... = (\\<^bold>g [^] int a \\<otimes> (\\<^bold>g [^] (- a))) \\<otimes> h\" using int_pow_neg[symmetric] by simp\n  then have \"... = \\<^bold>g [^] (int a - a)  \\<otimes> h\" by(simp add: int_pow_mult)\n  then have \"... = \\<^bold>g [^] ((0:: int)) \\<otimes> h\" by simp\n  then show ?thesis by (simp add: assms)\nqed\n\nlemma inverse_split: \n  assumes \"a \\<in> carrier G\" and \"b \\<in> carrier G\"\n  shows \"inv (a \\<otimes> b) = inv a \\<otimes> inv b\"\n  by (simp add:  assms comm_group.inv_mult cyclic_group_commute group_comm_groupI)\n\nlemma inverse_pow_pow:\n  assumes \"a \\<in> carrier G\"\n  shows \"inv (a [^] (r::nat)) = (inv a) [^] r\"\nproof -\n  have \"a [^] r \\<in> carrier G\"\n    using assms by blast\n  then show ?thesis\n    by (simp add: assms nat_pow_inv)\nqed\n\nlemma l_neq_1_exp_neq_0:\n  assumes \"l \\<in> carrier G\" \n    and \"l \\<noteq> \\<one>\" \n    and \"l = \\<^bold>g [^] (t::nat)\" \n  shows \"t \\<noteq> 0\"\nproof(rule ccontr)\n  assume \"\\<not> (t \\<noteq> 0)\"\n  hence \"t = 0\" by simp\n  hence \"\\<^bold>g [^] t = \\<one>\" by simp\n  then show \"False\" using assms by simp\nqed\n\nlemma order_gt_1_gen_not_1:\n  assumes \"order G > 1\"\n  shows \"\\<^bold>g \\<noteq> \\<one>\"\nproof(rule ccontr)\n  assume \"\\<not> \\<^bold>g \\<noteq> \\<one>\"\n  hence \"\\<^bold>g = \\<one>\" by simp\n  hence g_pow_eq_1: \"\\<^bold>g [^] n = \\<one>\" for n :: nat by simp\n  hence \"range (\\<lambda>n :: nat. \\<^bold>g [^] n) = {\\<one>}\" by auto\n  hence \"carrier G \\<subseteq> {\\<one>}\" using generator by auto\n  hence \"order G < 1\" \n    by (metis inj_onD inj_on_generator lessThan_iff g_pow_eq_1 assms less_one neq0_conv)\n  with assms show \"False\" by simp\nqed\n\nlemma power_swap: \"((\\<^bold>g [^] (\\<alpha>0::nat)) [^] (r::nat)) = ((\\<^bold>g [^] r) [^] \\<alpha>0)\"\n(is \"?lhs = ?rhs\")\nproof-\n  have \"?lhs = \\<^bold>g [^] (\\<alpha>0 * r)\" using nat_pow_pow mult.commute by auto\n  hence \"... = \\<^bold>g [^] (r * \\<alpha>0)\" by(metis mult.commute)\n  thus ?thesis using nat_pow_pow by auto\nqed\n\nlemma gen_power_0:\n  fixes r :: nat \n  assumes \"\\<^bold>g [^] r = \\<one>\" \n    and \"r < order G\"\n  shows \"r = 0\" \n  using assms inj_onD inj_on_generator by fastforce\n\nlemma group_eq_pow_eq_mod: \n  fixes a b :: nat \n  assumes \"\\<^bold>g [^] a = \\<^bold>g [^] b\" \n    and \"order G > 0\"\n  shows \"[a = b] (mod order G)\"\nproof(cases \"a > b\")\n  case True\n  have \"\\<^bold>g [^] a \\<otimes> inv (\\<^bold>g [^] b) = \\<one>\"\n    using assms by simp\n  hence \"\\<^bold>g [^] (a - b) = \\<one>\" \n    by (smt True add_Suc_right assms diff_add_inverse generator_closed group.l_cancel_one' group_l_invI l_inv_ex less_imp_Suc_add nat_pow_closed nat_pow_mult)\n  hence \"\\<^bold>g [^] ((a - b) mod (order G)) = \\<one>\" using pow_generator_mod by auto\n  thus ?thesis using gen_power_0 \n    using assms(1) assms(2) order_gt_0_iff_finite pow_generator_eq_iff_cong by blast\nnext\n  case False\n  have \"\\<^bold>g [^] a \\<otimes> inv (\\<^bold>g [^] b) = \\<one>\"\n    using assms by simp\n  hence \"\\<^bold>g [^] (b - a) = \\<one>\" \n    by (metis (no_types, lifting) False Group.group.axioms(1) Units_eq add_diff_inverse_nat assms(1) generator_closed group_l_invI l_inv_ex l_neq_1_exp_neq_0 monoid.Units_l_cancel nat_pow_closed nat_pow_mult r_one)\n  hence \"\\<^bold>g [^] ((b - a) mod (order G)) = \\<one>\" using pow_generator_mod by simp\n  thus ?thesis using gen_power_0 \n    using assms(1) assms(2) order_gt_0_iff_finite pow_generator_eq_iff_cong by blast\nqed\n\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/Sigma_Commit_Crypto/Cyclic_Group_Ext.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.90192067652954, "lm_q2_score": 0.7956580976404297, "lm_q1q2_score": 0.7176204897100632}}
{"text": "(*  Title:       Countable Ordinals\n\n    Author:      Brian Huffman, 2005\n    Maintainer:  Brian Huffman <brianh at cse.ogi.edu>\n*)\n\nsection \\<open>Definition of Ordinals\\<close>\n\ntheory OrdinalDef\n  imports Main\nbegin\n\nsubsection \\<open>Preliminary datatype for ordinals\\<close>\n\ndatatype ord0 = ord0_Zero | ord0_Lim \"nat \\<Rightarrow> ord0\"\n\ntext \\<open>subterm ordering on ord0\\<close>\n\ndefinition\n  ord0_prec :: \"(ord0 \\<times> ord0) set\" where\n  \"ord0_prec = (\\<Union>f i. {(f i, ord0_Lim f)})\"\n\nlemma wf_ord0_prec: \"wf ord0_prec\"\nproof -\n  have \"\\<forall>x. (\\<forall>y. (y, x) \\<in> ord0_prec \\<longrightarrow> P y) \\<longrightarrow> P x \\<Longrightarrow> P a\" for P a\n    unfolding ord0_prec_def by (induction a) blast+\n  then show ?thesis\n    by (metis wfUNIVI)\nqed\n\nlemmas ord0_prec_induct = wf_induct[OF wf_trancl[OF wf_ord0_prec]]\n\ntext \\<open>less-than-or-equal ordering on ord0\\<close>\n\ninductive_set ord0_leq :: \"(ord0 \\<times> ord0) set\" where\n  \"\\<lbrakk>\\<forall>a. (a,x) \\<in> ord0_prec\\<^sup>+ \\<longrightarrow> (\\<exists>b. (b,y) \\<in> ord0_prec\\<^sup>+ \\<and> (a,b) \\<in> ord0_leq)\\<rbrakk>\n  \\<Longrightarrow> (x,y) \\<in> ord0_leq\"\n\nlemma ord0_leqI:\n  \"\\<lbrakk>\\<forall>a. (a,x) \\<in> ord0_prec\\<^sup>+ \\<longrightarrow> (a,y) \\<in> ord0_leq O ord0_prec\\<^sup>+\\<rbrakk>\n \\<Longrightarrow> (x,y) \\<in> ord0_leq\"\n  by (meson ord0_leq.intros relcomp.cases)\n\nlemma ord0_leqD:\n  \"\\<lbrakk>(x,y) \\<in> ord0_leq; (a,x) \\<in> ord0_prec\\<^sup>+\\<rbrakk> \\<Longrightarrow> (a,y) \\<in> ord0_leq O ord0_prec\\<^sup>+\"\n  by (ind_cases \"(x,y) \\<in> ord0_leq\", auto)\n\nlemma ord0_leq_refl: \"(x, x) \\<in> ord0_leq\"\n  by (rule ord0_prec_induct, rule ord0_leqI, auto)\n\nlemma ord0_leq_trans:\n  \"(x,y) \\<in> ord0_leq \\<Longrightarrow> (y,z) \\<in> ord0_leq \\<Longrightarrow> (x,z) \\<in> ord0_leq\"\nproof (induction x arbitrary: y z rule: ord0_prec_induct)\n  case (1 x)\n  then show ?case\n    by (meson ord0_leq.cases ord0_leq.intros)\nqed\n\nlemma wf_ord0_leq: \"wf (ord0_leq O ord0_prec\\<^sup>+)\"\n  unfolding wf_def\nproof clarify\n  fix P x\n  assume *: \"\\<forall>x. (\\<forall>y. (y, x) \\<in> ord0_leq O ord0_prec\\<^sup>+ \\<longrightarrow> P y) \\<longrightarrow> P x\"\n  have \"\\<forall>z. (z, x) \\<in> ord0_leq \\<longrightarrow> P z\" \n    by (rule ord0_prec_induct) (meson * ord0_leq.cases ord0_leq_trans relcomp.cases)\n  then show \"P x\"\n    by (simp add: ord0_leq_refl)\nqed\n\n\ntext \\<open>ordering on ord0\\<close>\n\ninstantiation ord0 :: ord\nbegin\n\ndefinition\n  ord0_less_def: \"x < y \\<longleftrightarrow> (x,y) \\<in> ord0_leq O ord0_prec\\<^sup>+\"\n\ndefinition\n  ord0_le_def:   \"x \\<le> y \\<longleftrightarrow> (x,y) \\<in> ord0_leq\"\n\ninstance ..\n\nend\n\nlemma ord0_order_refl[simp]: \"(x::ord0) \\<le> x\"\n  by (simp add: ord0_le_def ord0_leq_refl)\n\nlemma ord0_order_trans: \"\\<lbrakk>(x::ord0) \\<le> y; y \\<le> z\\<rbrakk> \\<Longrightarrow> x \\<le> z\"\n  using ord0_le_def ord0_leq_trans by blast\n\nlemma ord0_wf: \"wf {(x,y::ord0). x < y}\"\n  using ord0_less_def wf_ord0_leq by auto\n\nlemmas ord0_less_induct = wf_induct[OF ord0_wf]\n\nlemma ord0_leI: \"\\<lbrakk>\\<forall>a::ord0. a < x \\<longrightarrow> a < y\\<rbrakk> \\<Longrightarrow> x \\<le> y\"\n  by (meson ord0_le_def ord0_leqD ord0_leqI ord0_leq_refl ord0_less_def)\n\nlemma ord0_less_le_trans: \"\\<lbrakk>(x::ord0) < y; y \\<le> z\\<rbrakk> \\<Longrightarrow> x < z\"\n  by (meson ord0_le_def ord0_leq.cases ord0_leq_trans ord0_less_def relcomp.intros relcompEpair)\n\nlemma ord0_le_less_trans:\n  \"\\<lbrakk>(x::ord0) \\<le> y; y < z\\<rbrakk> \\<Longrightarrow> x < z\"\n  by (meson ord0_le_def ord0_leq_trans ord0_less_def relcomp.cases relcomp.intros)\n\nlemma rev_ord0_le_less_trans:\n  \"\\<lbrakk>(y::ord0) < z; x \\<le> y\\<rbrakk> \\<Longrightarrow> x < z\"\n  by (rule ord0_le_less_trans)\n\nlemma ord0_less_trans: \"\\<lbrakk>(x::ord0) < y; y < z\\<rbrakk> \\<Longrightarrow> x < z\"\n  unfolding ord0_less_def \n  by (meson ord0_leq.cases relcomp.cases relcompI[OF ord0_leq_trans trancl_trans])\n\nlemma ord0_less_imp_le: \"(x::ord0) < y \\<Longrightarrow> x \\<le> y\"\n  using ord0_leI ord0_less_trans by blast\n\nlemma ord0_linear_lemma:\n  fixes m :: ord0 and n :: ord0\n  shows \"m < n \\<or> n < m \\<or> (m \\<le> n \\<and> n \\<le> m)\"\nproof -\n  have \"m < n \\<or> n < m \\<or> m \\<le> n \\<and> n \\<le> m\" for m\n  proof (induction n arbitrary: m rule: ord0_less_induct)\n    case (1 n)\n    have \"\\<forall>y. (y, n) \\<in> {(x, y). x < y} \\<longrightarrow> (\\<forall>x. x < y \\<or> y < x \\<or> x \\<le> y \\<and> y \\<le> x) \\<Longrightarrow> \n           m < n \\<or> n < m \\<or> m \\<le> n \\<and> n \\<le> m\"\n    proof (induction m rule: ord0_less_induct)\n      case (1 x)\n      then show ?case\n        by (smt (verit, best) mem_Collect_eq old.prod.case ord0_leI ord0_le_less_trans ord0_less_imp_le)\n    qed\n    then show ?case\n      using \"1\" by blast\n  qed\n  then show ?thesis\n    by simp\nqed\n\nlemma ord0_linear: \"(x::ord0) \\<le> y \\<or> y \\<le> x\"\n  using ord0_less_imp_le ord0_linear_lemma by blast\n\nlemma ord0_order_less_le: \"(x::ord0) < y \\<longleftrightarrow> (x \\<le> y \\<and> \\<not> y \\<le> x)\" (is \"?L=?R\")\nproof\n  show \"?L \\<Longrightarrow> ?R\"\n    by (metis ord0_less_def ord0_less_imp_le ord0_less_le_trans wf_not_refl wf_ord0_leq)\n  show \"?R \\<Longrightarrow> ?L\"\n  using ord0_less_imp_le ord0_linear_lemma by blast\nqed\n\nsubsection \\<open>Ordinal type\\<close>\n\ndefinition\n  ord0rel :: \"(ord0 \\<times> ord0) set\" where\n  \"ord0rel = {(x,y). x \\<le> y \\<and> y \\<le> x}\"\n\ntypedef ordinal = \"(UNIV::ord0 set) // ord0rel\"\n  by (unfold quotient_def, auto)\n\ntheorem Abs_ordinal_cases2 [case_names Abs_ordinal, cases type: ordinal]:\n  \"(\\<And>z. x = Abs_ordinal (ord0rel `` {z}) \\<Longrightarrow> P) \\<Longrightarrow> P\"\n  by (cases x, auto simp add: quotient_def)\n\n\ninstantiation ordinal :: ord\nbegin\n\ndefinition\n  ordinal_less_def: \"x < y \\<longleftrightarrow> (\\<forall>a\\<in>Rep_ordinal x. \\<forall>b\\<in>Rep_ordinal y. a < b)\"\n\ndefinition\n  ordinal_le_def: \"x \\<le> y \\<longleftrightarrow> (\\<forall>a\\<in>Rep_ordinal x. \\<forall>b\\<in>Rep_ordinal y. a \\<le> b)\"\n\ninstance ..\n\nend\n\nlemma Rep_Abs_ord0rel [simp]:\n  \"Rep_ordinal (Abs_ordinal (ord0rel `` {x})) = (ord0rel `` {x})\"\n  by (simp add: Abs_ordinal_inverse quotientI)\n\nlemma mem_ord0rel_Image [simp, intro!]: \"x \\<in> ord0rel `` {x}\"\n  by (simp add: ord0rel_def)\n\nlemma equiv_ord0rel: \"equiv UNIV ord0rel\"\n  unfolding equiv_def refl_on_def sym_def trans_def ord0rel_def\n  by (auto elim: ord0_order_trans)\n\nlemma Abs_ordinal_eq[simp]:\n  \"(Abs_ordinal (ord0rel `` {x}) = Abs_ordinal (ord0rel `` {y})) = (x \\<le> y \\<and> y \\<le> x)\"\n  apply (simp add: Abs_ordinal_inject quotientI eq_equiv_class_iff[OF equiv_ord0rel])\n  apply (simp add: ord0rel_def)\n  done\n\nlemma Abs_ordinal_le[simp]:\n  \"Abs_ordinal (ord0rel `` {x}) \\<le> Abs_ordinal (ord0rel `` {y}) \\<longleftrightarrow> (x \\<le> y)\" (is \"?L=?R\")\nproof\n  show \"?L \\<Longrightarrow> ?R\"\n    using Rep_Abs_ord0rel ordinal_le_def by blast\nnext\n  assume ?R\n  then have \"\\<And>a b. \\<lbrakk>(x, a) \\<in> ord0rel; (y, b) \\<in> ord0rel\\<rbrakk> \\<Longrightarrow> a \\<le> b\"\n    unfolding ord0rel_def by (blast intro: ord0_order_trans)\n  then show ?L\n    by (auto simp add: ordinal_le_def)\nqed\n\nlemma Abs_ordinal_less[simp]:\n  \"Abs_ordinal (ord0rel `` {x}) < Abs_ordinal (ord0rel `` {y}) \\<longleftrightarrow> (x < y)\" (is \"?L=?R\")\nproof\n  show \"?L \\<Longrightarrow> ?R\"\n    using Rep_Abs_ord0rel ordinal_less_def by blast\nnext\n  assume ?R\n  then have \"\\<And>a b. \\<lbrakk>(x, a) \\<in> ord0rel; (y, b) \\<in> ord0rel\\<rbrakk> \\<Longrightarrow> a < b\"\n    unfolding ord0rel_def\n    by (blast intro: ord0_le_less_trans ord0_less_le_trans)\n  then show ?L\n    by (auto simp add: ordinal_less_def)\nqed\n\ninstance ordinal :: linorder\nproof\n  show \"(x::ordinal) \\<le> x\" for x\n    by (cases x, simp)\n  show \"((x::ordinal) < y) = (x \\<le> y \\<and> \\<not> y \\<le> x)\" for x y\n    by (cases x, cases y, auto simp add: ord0_order_less_le)\n  show \"(x::ordinal) \\<le> y \\<Longrightarrow> y \\<le> z \\<Longrightarrow> x \\<le> z\" for x y z\n    by (cases x, cases y, cases z, auto elim: ord0_order_trans)\n  show \"(x::ordinal) \\<le> y \\<Longrightarrow> y \\<le> x \\<Longrightarrow> x = y\" for x y\n    by (cases x, cases y, simp)\n  show \"(x::ordinal) \\<le> y \\<or> y \\<le> x\" for x y\n    by (cases x, cases y, simp add: ord0_linear)\nqed\n\ninstance ordinal :: wellorder\nproof\n  show \"P a\" if \"(\\<And>x::ordinal. (\\<And>y. y < x \\<Longrightarrow> P y) \\<Longrightarrow> P x)\" for P a\n  proof (rule Abs_ordinal_cases2)\n    fix z\n    assume a: \"a = Abs_ordinal (ord0rel `` {z})\"\n    have \"P (Abs_ordinal (ord0rel `` {z}))\"\n      using that\n      apply (rule ord0_less_induct)\n      by (metis Abs_ordinal_cases2 Abs_ordinal_less CollectI case_prodI)\n    with a show \"P a\" by simp\n  qed\nqed\n\nlemma ordinal_linear: \"(x::ordinal) \\<le> y \\<or> y \\<le> x\"\n  by auto\n\nlemma ordinal_wf: \"wf {(x,y::ordinal). x < y}\"\n  by (simp add: wf)\n\n\nsubsection \\<open>Induction over ordinals\\<close>\n\ntext \"zero and strict limits\"\n\ndefinition\n  oZero :: \"ordinal\" where\n  \"oZero = Abs_ordinal (ord0rel `` {ord0_Zero})\"\n\ndefinition\n  oStrictLimit :: \"(nat \\<Rightarrow> ordinal) \\<Rightarrow> ordinal\" where\n  \"oStrictLimit f = Abs_ordinal\n      (ord0rel `` {ord0_Lim (\\<lambda>n. SOME x. x \\<in> Rep_ordinal (f n))})\"\n\ntext \"induction over ordinals\"\n\nlemma ord0relD: \"(x,y) \\<in> ord0rel \\<Longrightarrow> x \\<le> y \\<and> y \\<le> x\"\n  by (simp add: ord0rel_def)\n\nlemma ord0_precD: \"(x,y) \\<in> ord0_prec \\<Longrightarrow> \\<exists>f n. x = f n \\<and> y = ord0_Lim f\"\n  by (simp add: ord0_prec_def)\n\nlemma less_ord0_LimI: \"f n < ord0_Lim f\"\n  using ord0_leq_refl ord0_less_def ord0_prec_def by fastforce\n\nlemma less_ord0_LimD: \n  assumes \"x < ord0_Lim f\" shows \"\\<exists>n. x \\<le> f n\"\nproof -\n  obtain y where \"x\\<le>y\" \"y < ord0_Lim f\"\n    using assms ord0_linear by auto\n  then consider \"(y, ord0_Lim f) \\<in> ord0_prec\" | z where \"y \\<le> z\" \"(z, ord0_Lim f) \\<in> ord0_prec\"\n    apply (clarsimp simp add: ord0_less_def ord0_le_def)\n    by (metis ord0_less_def ord0_less_imp_le relcomp.relcompI that(2) tranclE)\n  then show ?thesis\n    by (metis \\<open>x \\<le> y\\<close> ord0.inject ord0_order_trans ord0_precD)\nqed\n  \nlemma some_ord0rel: \"(x, SOME y. (x,y) \\<in> ord0rel) \\<in> ord0rel\"\n  by (rule_tac x=x in someI, simp add: ord0rel_def)\n\nlemma ord0_Lim_le: \"\\<forall>n. f n \\<le> g n \\<Longrightarrow> ord0_Lim f \\<le> ord0_Lim g\"\n  by (metis less_ord0_LimD less_ord0_LimI ord0_le_less_trans ord0_linear ord0_order_less_le)\n\nlemma ord0_Lim_ord0rel:\n  \"\\<forall>n. (f n, g n) \\<in> ord0rel \\<Longrightarrow> (ord0_Lim f, ord0_Lim g) \\<in> ord0rel\"\n  by (simp add: ord0rel_def ord0_Lim_le)\n\nlemma Abs_ordinal_oStrictLimit:\n  \"Abs_ordinal (ord0rel `` {ord0_Lim f})\n  = oStrictLimit (\\<lambda>n. Abs_ordinal (ord0rel `` {f n}))\"\n  apply (simp add: oStrictLimit_def)\n  using ord0_Lim_le ord0relD some_ord0rel by presburger\n\nlemma oStrictLimit_induct:\n  assumes base: \"P oZero\"\n  assumes step: \"\\<And>f. \\<forall>n. P (f n) \\<Longrightarrow> P (oStrictLimit f)\"\n  shows \"P a\"\nproof -\n  obtain z where z: \"a = Abs_ordinal (ord0rel `` {z})\"\n    using Abs_ordinal_cases2 by auto\n  have \"P (Abs_ordinal (ord0rel `` {z}))\"\n  proof (induction z)\n    case ord0_Zero\n    with base oZero_def show ?case by auto\n  next\n    case (ord0_Lim x)\n    then show ?case\n      by (simp add: Abs_ordinal_oStrictLimit local.step)\n  qed\n  then show ?thesis\n    by (simp add: z)\nqed\n\ntext \"order properties of 0 and strict limits\"\n\nlemma oZero_least: \"oZero \\<le> x\"\nproof -\n  have \"x = Abs_ordinal (ord0rel `` {z}) \\<Longrightarrow> ord0_Zero \\<le> z\" for z\n  proof (induction z arbitrary: x)\n    case (ord0_Lim u)\n    then show ?case\n      by (meson less_ord0_LimI ord0_le_less_trans ord0_less_imp_le rangeI) \n  qed auto\n  then show ?thesis\n    by (metis Abs_ordinal_cases2 Abs_ordinal_le oZero_def)\nqed\n\nlemma oStrictLimit_ub: \"f n < oStrictLimit f\"\n  apply (cases \"f n\", simp add: oStrictLimit_def)\n  apply (rule_tac y=\"SOME x. x \\<in> Rep_ordinal (f n)\" in ord0_le_less_trans)\n  apply (metis (no_types) Image_singleton_iff Rep_Abs_ord0rel empty_iff mem_ord0rel_Image ord0relD some_in_eq)\n  by (meson less_ord0_LimI)\n\nlemma oStrictLimit_lub: \n  assumes \"\\<forall>n. f n < x\" shows \"oStrictLimit f \\<le> x\"\nproof -\n  have \"\\<exists>n. x \\<le> f n\" if x: \"x < oStrictLimit f\"\n  proof -\n    obtain z where z: \"x = Abs_ordinal (ord0rel `` {z})\" \n                      \"z < ord0_Lim (\\<lambda>n. SOME x. x \\<in> Rep_ordinal (f n))\"\n      using less_ord0_LimI x unfolding oStrictLimit_def\n      by (metis Abs_ordinal_cases2 Abs_ordinal_less)\n    then obtain n where \"z \\<le> (SOME x. x \\<in> Rep_ordinal (f n))\"\n      using less_ord0_LimD by blast\n    then have \"Abs_ordinal (ord0rel `` {z}) \\<le> f n\"\n      apply (rule_tac x=\"f n\" in Abs_ordinal_cases2)\n      using ord0_order_trans ord0relD some_ord0rel by auto\n    then show ?thesis\n      using \\<open>x = Abs_ordinal (ord0rel `` {z})\\<close> by auto\n  qed\n  then show ?thesis\n    using assms linorder_not_le by blast\nqed\n\nlemma less_oStrictLimitD: \"x < oStrictLimit f \\<Longrightarrow> \\<exists>n. x \\<le> f n\"\n  by (metis leD leI oStrictLimit_lub)\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/OrdinalDef.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391617003942, "lm_q2_score": 0.8311430541321951, "lm_q1q2_score": 0.7176019454687909}}
{"text": "(* Title:      Kleene Algebra\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\nheader {* Formal Power Series *}\n\ntheory Formal_Power_Series\nimports Finite_Suprema Kleene_Algebra\nbegin\n\nsubsection {* The Type of Formal Power Series*}\n\ntext {* Formal powerseries are functions from a free monoid into a\ndioid. They have applications in formal language theory, e.g.,\nweighted automata. As usual, we represent elements of a free monoid\nby lists.\n\nThis theory generalises Amine Chaieb's development of formal power\nseries as functions from natural numbers, which may be found in {\\em\nHOL/Library/Formal\\_Power\\_Series.thy}. *}\n\ntypedef ('a, 'b) fps = \"{f::'a list \\<Rightarrow> 'b. True}\"\n  morphisms fps_nth Abs_fps\n  by simp\n\ntext {* It is often convenient to reason about functions, and transfer\nresults to formal power series. *}\n\nsetup_lifting type_definition_fps\n\ndeclare fps_nth_inverse [simp]\n\nnotation fps_nth (infixl \"$\" 75)\n\nlemma expand_fps_eq: \"p = q \\<longleftrightarrow> (\\<forall>n. p $ n = q $ n)\"\nby (simp add: fps_nth_inject [symmetric] fun_eq_iff)\n\nlemma fps_ext: \"(\\<And>n. p $ n = q $ n) \\<Longrightarrow> p = q\"\nby (simp add: expand_fps_eq)\n\nlemma fps_nth_Abs_fps [simp]: \"Abs_fps f $ n = f n\"\nby (simp add: Abs_fps_inverse)\n\n\nsubsection {* Definition of the Basic Elements~0 and~1 and the Basic\nOperations of Addition and Multiplication *}\n\ntext {* The zero formal power series maps all elements of the monoid\n(all lists) to zero. *}\n\ninstantiation fps :: (type,zero) zero\nbegin\n  definition zero_fps where\n    \"0 = Abs_fps (\\<lambda>n. 0)\"\n  instance ..\nend\n\nlemma fps_zero_nth [simp]: \"0 $ n = 0\"\nunfolding zero_fps_def by simp\n\ntext {* The unit formal power series maps the monoidal unit (the empty\nlist) to one and all other elements to zero. *}\n\ninstantiation fps :: (type,\"{one,zero}\") one\nbegin\n  definition one_fps where\n    \"1 = Abs_fps (\\<lambda>n. if n = [] then 1 else 0)\"\n  instance ..\nend\n\nlemma fps_one_nth_Nil [simp]: \"1 $ [] = 1\"\nunfolding one_fps_def by simp\n\nlemma fps_one_nth_Cons [simp]: \"1 $ (x # xs) = 0\"\nunfolding one_fps_def by simp\n\ntext {* Addition of formal power series is the usual pointwise\naddition of functions. *}\n\ninstantiation fps :: (type,plus) plus\nbegin\n  definition plus_fps where\n    \"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\"\nunfolding plus_fps_def by simp\n\ntext {* This directly shows that formal power series form a\nsemilattice with zero. *}\n\nlemma fps_add_assoc: \"((f::('a,'b::semigroup_add) fps) + g) + h = f + (g + h)\"\nunfolding plus_fps_def by (simp add: add.assoc)\n\nlemma fps_add_comm [simp]: \"(f::('a,'b::ab_semigroup_add) fps) + g = g + f\"\nunfolding plus_fps_def by (simp add: add.commute)\n\nlemma fps_add_idem [simp]: \"(f::('a,'b::join_semilattice) fps) + f = f\"\nunfolding plus_fps_def by simp\n\nlemma fps_zerol [simp]: \"(f::('a,'b::monoid_add) fps) + 0 = f\"\nunfolding plus_fps_def by simp\n\nlemma fps_zeror [simp]: \"0 + (f::('a,'b::monoid_add) fps) = f\"\nunfolding plus_fps_def by simp\n\ntext {* The product of formal power series is convolution. The product\nof two formal powerseries at a list is obtained by splitting the list\ninto all possible prefix/suffix pairs, taking the product of the first\nseries applied to the first coordinate and the second series applied\nto the second coordinate of each pair, and then adding the results. *}\n\ninstantiation fps :: (type,\"{comm_monoid_add,times}\") times\nbegin\n  definition times_fps where\n    \"f * g = Abs_fps (\\<lambda>n. \\<Sum>{f $ y * g $ z |y z. n = y @ z})\"\n  instance ..\nend\n\ntext {* We call the set of all prefix/suffix splittings of a\nlist~@{term xs} the \\emph{splitset} of~@{term xs}. *}\n\ndefinition splitset where\n  \"splitset xs \\<equiv> {(p, q). xs = p @ q}\"\n\ntext {* Altenatively, splitsets can be defined recursively, which\nyields convenient simplification rules in Isabelle. *}\n\nfun splitset_fun where\n  \"splitset_fun []       = {([], [])}\"\n| \"splitset_fun (x # xs) = insert ([], x # xs) (apfst (Cons x) ` splitset_fun xs)\"\n\nlemma splitset_consl:\n  \"splitset (x # xs) = insert ([], x # xs) (apfst (Cons x) ` splitset xs)\"\nby (auto simp add: image_def splitset_def) (metis append_eq_Cons_conv)+\n\nlemma splitset_eq_splitset_fun: \"splitset xs = splitset_fun xs\"\napply (induct xs)\n apply (simp add: splitset_def)\napply (simp add: splitset_consl)\ndone\n\ntext {* The definition of multiplication is now more precise. *}\n\nlemma fps_mult_var:\n  \"(f * g) $ n = \\<Sum>{f $ (fst p) * g $ (snd p) | p. p \\<in> splitset n}\"\nby (simp add: times_fps_def splitset_def)\n\nlemma fps_mult_image:\n  \"(f * g) $ n = \\<Sum>((\\<lambda>p. f $ (fst p) * g $ (snd p)) ` splitset n)\"\nby (simp only: Collect_mem_eq fps_mult_var fun_im)\n\ntext {* Next we show that splitsets are finite and non-empty. *}\n\nlemma splitset_fun_finite [simp]: \"finite (splitset_fun xs)\"\n  by (induct xs, simp_all)\n\nlemma splitset_finite [simp]: \"finite (splitset xs)\"\n  by (simp add: splitset_eq_splitset_fun)\n\nlemma split_append_finite [simp]: \"finite {(p, q). xs = p @ q}\"\n  by (fold splitset_def, fact splitset_finite)\n\nlemma splitset_fun_nonempty [simp]: \"splitset_fun xs \\<noteq> {}\"\n  by (cases xs, simp_all)\n\nlemma splitset_nonempty [simp]: \"splitset xs \\<noteq> {}\"\n  by (simp add: splitset_eq_splitset_fun)\n\ntext {* We now proceed with proving algebraic properties of formal\npower series. *}\n\nlemma fps_annil [simp]:\n  \"0 * (f::('a::type,'b::{comm_monoid_add,mult_zero}) fps) = 0\"\nby (rule fps_ext) (simp add: times_fps_def setsum.neutral)\n\nlemma fps_annir [simp]:\n  \"(f::('a::type,'b::{comm_monoid_add,mult_zero}) fps) * 0 = 0\"\nby (simp add: fps_ext times_fps_def setsum.neutral)\n\nlemma fps_distl:\n  \"(f::('a::type,'b::{join_semilattice_zero,semiring}) fps) * (g + h) = (f * g) + (f * h)\"\nby (simp add: fps_ext fps_mult_image distrib_left setsum_fun_sum)\n\nlemma fps_distr:\n  \"((f::('a::type,'b::{join_semilattice_zero,semiring}) fps) + g) * h = (f * h) + (g * h)\"\nby (simp add: fps_ext fps_mult_image distrib_right setsum_fun_sum)\n\ntext {* The multiplicative unit laws are surprisingly tedious. For the\nproof of the left unit law we use the recursive definition, which we\ncould as well have based on splitlists instead of splitsets.\n\nHowever, a right unit law cannot simply be obtained along the lines of\nthis proofs. The reason is that an alternative recursive definition\nthat produces a unit with coordinates flipped would be needed. But\nthis is difficult to obtain without snoc lists. We therefore prove the\nright unit law more directly by using properties of suprema. *}\n\nlemma fps_onel [simp]:\n  \"1 * (f::('a::type,'b::{join_semilattice_zero,monoid_mult,mult_zero}) fps) = f\"\nproof (rule fps_ext)\n  fix n :: \"'a list\"\n  show \"(1 * f) $ n = f $ n\"\n  proof (cases n)\n    case Nil thus ?thesis\n      by (simp add: times_fps_def)\n  next\n    case Cons thus ?thesis\n      by (simp add: fps_mult_image splitset_eq_splitset_fun image_comp one_fps_def comp_def image_constant_conv)\n  qed\nqed\n\nlemma fps_oner [simp]:\n  \"(f::('a::type,'b::{join_semilattice_zero,monoid_mult,mult_zero}) fps) * 1 = f\"\nproof (rule fps_ext)\n  fix n :: \"'a list\"\n  {\n    fix z :: 'b\n    have \"(f * 1) $ n \\<le> z \\<longleftrightarrow> (\\<forall>p \\<in> splitset n. f $ (fst p) * 1 $ (snd p) \\<le> z)\"\n      by (simp add: fps_mult_image setsum_fun_image_sup)\n    also have \"... \\<longleftrightarrow> (\\<forall>a b. n = a @ b \\<longrightarrow> f $ a * 1 $ b \\<le> z)\"\n      unfolding splitset_def by simp\n    also have \"... \\<longleftrightarrow> (f $ n * 1 $ [] \\<le> z)\"\n      by (metis append_Nil2 fps_one_nth_Cons fps_one_nth_Nil mult_zero_right neq_Nil_conv zero_least)\n    finally have \"(f * 1) $ n \\<le> z \\<longleftrightarrow> f $ n \\<le> z\"\n      by simp\n  }\n  thus \"(f * 1) $ n = f $ n\"\n    by (metis eq_iff)\nqed\n\ntext {* Finally we prove associativity of convolution. This requires\nsplitting lists into three parts and rearranging these parts in two\ndifferent ways into splitsets. This rearrangement is captured by the\nfollowing technical lemma. *}\n\nlemma splitset_rearrange:\n  fixes F :: \"'a list \\<Rightarrow> 'a list \\<Rightarrow> 'a list \\<Rightarrow> 'b::join_semilattice_zero\"\n  shows \"\\<Sum>{\\<Sum>{F (fst p) (fst q) (snd q) | q. q \\<in> splitset (snd p)} | p. p \\<in> splitset x} =\n         \\<Sum>{\\<Sum>{F (fst q) (snd q) (snd p) | q. q \\<in> splitset (fst p)} | p. p \\<in> splitset x}\"\n    (is \"?lhs = ?rhs\")\nproof -\n  {\n    fix z :: 'b\n    have \"?lhs \\<le> z \\<longleftrightarrow> (\\<forall>p q r. x = p @ q @ r \\<longrightarrow> F p q r \\<le> z)\"\n      by (simp only: fset_to_im setsum_fun_image_sup splitset_finite)\n         (auto simp add: splitset_def)\n    hence \"?lhs \\<le> z \\<longleftrightarrow> ?rhs \\<le> z\"\n      by (simp only: fset_to_im setsum_fun_image_sup splitset_finite)\n         (auto simp add: splitset_def)\n  }\n  thus ?thesis\n    by (simp add: eq_iff)\nqed\n\nlemma fps_mult_assoc: \"(f::('a::type,'b::dioid_one_zero) fps) * (g * h) = (f * g) * h\"\nproof (rule fps_ext)\n  fix n :: \"'a list\"\n  have \"(f * (g * h)) $ n = \\<Sum>{\\<Sum>{f $ (fst p) * g $ (fst q) * h $ (snd q) | q. q \\<in> splitset (snd p)} | p. p \\<in> splitset n}\"\n    by (simp add: fps_mult_image setsum_sum_distl_fun mult.assoc)\n  also have \"... = \\<Sum>{\\<Sum>{f $ (fst q) * g $ (snd q) * h $ (snd p) | q. q \\<in> splitset (fst p)} | p. p \\<in> splitset n}\"\n    by (fact splitset_rearrange)\n  finally show \"(f * (g * h)) $ n = ((f * g) * h) $ n\"\n    by (simp add: fps_mult_image setsum_sum_distr_fun mult.assoc)\nqed\n\n\nsubsection {* The Dioid Model of Formal Power Series *}\n\ntext {* We can now show that formal power series with suitably\ndefined operations form a dioid. Many of the underlying properties\nalready hold in weaker settings, where the target algebra is a\nsemilattice or semiring. We currently ignore this fact. *}\n\nsubclass (in dioid_one_zero) mult_zero\nproof\n  fix x :: 'a\n  show \"0 * x = 0\"\n    by (fact annil)\n  show \"x * 0 = 0\"\n    by (fact annir)\nqed\n\ninstantiation fps :: (type,dioid_one_zero) dioid_one_zero\nbegin\n\n  definition less_eq_fps where\n    \"(f::('a,'b) fps) \\<le> g \\<longleftrightarrow> f + g = g\"\n\n  definition less_fps where\n    \"(f::('a,'b) fps) < g \\<longleftrightarrow> f \\<le> g \\<and> f \\<noteq> g\"\n\n  instance\n  proof\n    fix f g h :: \"('a,'b) fps\"\n    show \"f + g + h = f + (g + h)\"\n      by (fact fps_add_assoc)\n    show \"f + g = g + f\"\n      by (fact fps_add_comm)\n    show \"f * g * h = f * (g * h)\"\n      by (metis fps_mult_assoc)\n    show \"(f + g) * h = f * h + g * h\"\n      by (fact fps_distr)\n    show \"1 * f = f\"\n      by (fact fps_onel)\n    show \"f * 1 = f\"\n      by (fact fps_oner)\n    show \"0 + f = f\"\n      by (fact fps_zeror)\n    show \"0 * f = 0\"\n      by (fact fps_annil)\n    show \"f * 0 = 0\"\n      by (fact fps_annir)\n    show \"f \\<le> g \\<longleftrightarrow> f + g = g\"\n      by (fact less_eq_fps_def)\n    show \"f < g \\<longleftrightarrow> f \\<le> g \\<and> f \\<noteq> g\"\n      by (fact less_fps_def)\n    show \"f + f = f\"\n      by (fact fps_add_idem)\n    show \"f * (g + h) = f \\<cdot> g + f \\<cdot> h\"\n      by (fact fps_distl)\n  qed\n\nend (* instantiation *)\n\nlemma expand_fps_less_eq: \"(f::('a,'b::dioid_one_zero) fps) \\<le> g \\<longleftrightarrow> (\\<forall>n. f $ n \\<le> g $ n)\"\nby (simp add: expand_fps_eq less_eq_def less_eq_fps_def)\n\n\nsubsection {* The Kleene Algebra Model of Formal Power Series *}\n\ntext {* There are two approaches to define the Kleene star. The first\none defines the star for a certain kind of (so-called proper) formal\npower series into a semiring or dioid. The second one, which is more\ninteresting in the context of our algebraic hierarchy, shows that\nformal power series into a Kleene algebra form a Kleene algebra. We\nhave only formalised the latter approach. *}\n\nlemma Setsum_splitlist_nonempty:\n  \"\\<Sum>{f ys zs |ys zs. xs = ys @ zs} = ((f [] xs)::'a::join_semilattice_zero) + \\<Sum>{f ys zs |ys zs. xs = ys @ zs \\<and> ys \\<noteq> []}\"\nproof -\n  have \"{f ys zs |ys zs. xs = ys @ zs} = {f ys zs |ys zs. xs = ys @ zs \\<and> ys = []} \\<union> {f ys zs |ys zs. xs = ys @ zs \\<and> ys \\<noteq> []}\"\n    by blast\n  thus ?thesis using [[simproc add: finite_Collect]]\n    by (simp add: setsum.insert)\nqed\n\nlemma (in left_kleene_algebra) add_star_eq:\n  \"x + y \\<cdot> y\\<^sup>\\<star> \\<cdot> x = y\\<^sup>\\<star> \\<cdot> x\"\nby (metis add.commute mult_onel star2 star_one troeger)\n\ninstantiation fps :: (type,kleene_algebra) kleene_algebra\nbegin\n\n  text {* We first define the star on functions, where we can use\n  Isabelle's package for recursive functions, before lifting the\n  definition to the type of formal power series.\n\n  This definition of the star is from an unpublished manuscript by\n  Esik and Kuich. *}\n\n  declare rev_conj_cong[fundef_cong]\n    -- \"required for the function package to prove termination of @{term star_fps_rep}\"\n\n  fun star_fps_rep where\n    star_fps_rep_Nil: \"star_fps_rep f [] = (f [])\\<^sup>\\<star>\"\n  | star_fps_rep_Cons: \"star_fps_rep f n = (f [])\\<^sup>\\<star> \\<cdot> \\<Sum>{f y \\<cdot> star_fps_rep f z |y z. n = y @ z \\<and> y \\<noteq> []}\"\n\n  lift_definition star_fps :: \"('a, 'b) fps \\<Rightarrow> ('a, 'b) fps\" is star_fps_rep ..\n\n  lemma star_fps_Nil [simp]: \"f\\<^sup>\\<star> $ [] = (f $ [])\\<^sup>\\<star>\"\n  by (simp add: star_fps_def)\n\n  lemma star_fps_Cons [simp]: \"f\\<^sup>\\<star> $ (x # xs) = (f $ [])\\<^sup>\\<star> \\<cdot> \\<Sum>{f $ y \\<cdot> f\\<^sup>\\<star> $ z |y z. x # xs = y @ z \\<and> y \\<noteq> []}\"\n  by (simp add: star_fps_def)\n\n  instance\n  proof\n    fix f g h :: \"('a,'b) fps\"  \n    have \"1 + f \\<cdot> f\\<^sup>\\<star> = f\\<^sup>\\<star>\"\n      apply (rule fps_ext)\n      apply (case_tac n)\n       apply (auto simp add: times_fps_def)\n      apply (simp add: add_star_eq mult.assoc[THEN sym] Setsum_splitlist_nonempty)\n    done\n    thus \"1 + f \\<cdot> f\\<^sup>\\<star> \\<le> f\\<^sup>\\<star>\"\n      by (metis order_refl)\n    have \"f \\<cdot> g \\<le> g \\<longrightarrow> f\\<^sup>\\<star> \\<cdot> g \\<le> g\"\n      proof\n        assume \"f \\<cdot> g \\<le> g\"\n        hence 1: \"\\<And>u v. f $ u \\<cdot> g $ v \\<le> g $ (u @ v)\"\n          using [[simproc add: finite_Collect]]\n          apply (simp add: expand_fps_less_eq)\n          apply (drule_tac x=\"u @ v\" in spec)\n          apply (simp add: times_fps_def)\n          apply (auto elim!: setsum_less_eqE)\n        done\n        hence 2: \"\\<And>v. (f $ []) \\<^sup>\\<star> \\<cdot> g $ v \\<le> g $ v\"\n          apply (subgoal_tac \"f $ [] \\<cdot> g $ v \\<le> g $ v\")\n           apply (metis star_inductl_var)\n          apply (metis append_Nil)\n        done\n        show \"f\\<^sup>\\<star> \\<cdot> g \\<le> g\"\n          using [[simproc add: finite_Collect]]\n          apply (auto intro!: setsum_less_eqI simp add: expand_fps_less_eq times_fps_def)\n          apply (induct_tac \"y\" rule: length_induct)\n          apply (case_tac \"xs\")\n           apply (simp add: \"2\")\n          apply (auto simp add: mult.assoc setsum_distr)\n          apply (rule_tac y=\"(f $ [])\\<^sup>\\<star> \\<cdot> g $ (a # list @ z)\" in order_trans)\n           prefer 2\n           apply (rule \"2\")\n          apply (auto intro!: mult_isol[rule_format] setsum_less_eqI)\n          apply (drule_tac x=\"za\" in spec)\n          apply (drule mp)\n           apply (metis append_eq_Cons_conv length_append less_not_refl2 add.commute not_less_eq trans_less_add1)\n          apply (drule_tac z=\"f $ y\" in mult_isol[rule_format])\n          apply (auto elim!: order_trans simp add: mult.assoc)\n          apply (metis \"1\" append_Cons append_assoc)\n        done\n      qed\n    thus \"h + f \\<cdot> g \\<le> g \\<longrightarrow> f\\<^sup>\\<star> \\<cdot> h \\<le> g\"\n      by (metis (hide_lams, no_types) add_lub mult_isol order_trans)\n    have \"g \\<cdot> f \\<le> g \\<longrightarrow> g \\<cdot> f\\<^sup>\\<star> \\<le> g\"\n      -- \"this property is dual to the previous one; the proof is slightly different\"\n      proof\n        assume \"g \\<cdot> f \\<le> g\"\n        hence 1: \"\\<And>u v. g $ u \\<cdot> f $ v \\<le> g $ (u @ v)\"\n          using [[simproc add: finite_Collect]]\n          apply (simp add: expand_fps_less_eq)\n          apply (drule_tac x=\"u @ v\" in spec)\n          apply (simp add: times_fps_def)\n          apply (auto elim!: setsum_less_eqE)\n        done\n        hence 2: \"\\<And>u. g $ u \\<cdot> (f $ [])\\<^sup>\\<star> \\<le> g $ u\"\n          apply (subgoal_tac \"g $ u \\<cdot> f $ [] \\<le> g $ u\")\n           apply (metis star_inductr_var)\n          apply (metis append_Nil2)\n        done\n        show \"g \\<cdot> f\\<^sup>\\<star> \\<le> g\"\n          using [[simproc add: finite_Collect]]\n          apply (auto intro!: setsum_less_eqI simp add: expand_fps_less_eq times_fps_def)\n          apply (rule_tac P=\"\\<lambda>y. g $ y \\<cdot> f\\<^sup>\\<star> $ z \\<le> g $ (y @ z)\" and x=\"y\" in allE)\n           prefer 2\n           apply assumption\n          apply (induct_tac \"z\" rule: length_induct)\n          apply (case_tac \"xs\")\n           apply (simp add: \"2\")\n          apply (auto intro!: setsum_less_eqI simp add: setsum_distl)\n          apply (rule_tac y=\"g $ x \\<cdot> f $ yb \\<cdot> f\\<^sup>\\<star> $ z\" in order_trans)\n           apply (simp add: \"2\" mult.assoc[THEN sym] mult_isor)\n          apply (rule_tac y=\"g $ (x @ yb) \\<cdot> f\\<^sup>\\<star> $ z\" in order_trans)\n           apply (simp add: \"1\" mult_isor)\n          apply (drule_tac x=\"z\" in spec)\n          apply (drule mp)\n           apply (metis append_eq_Cons_conv length_append less_not_refl2 add.commute not_less_eq trans_less_add1)\n          apply (metis append_assoc)\n        done\n      qed\n    thus \"h + g \\<cdot> f \\<le> g \\<longrightarrow> h \\<cdot> f\\<^sup>\\<star> \\<le> g\"\n      by (metis (hide_lams, no_types) add_lub mult_isor order_trans)\n  qed\n\nend (* instantiation *)\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/Kleene_Algebra/Formal_Power_Series.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391617003942, "lm_q2_score": 0.831143054132195, "lm_q1q2_score": 0.7176019454687907}}
{"text": "(*\n    Author:      Ren\u00e9 Thiemann\n                 Akihisa Yamada\n    License:     BSD\n*)\n(* with contributions from Alexander Bentkamp, Universit\u00e4t des Saarlandes *)\n\nsection\\<open>Vectors and Matrices\\<close>\n\ntext \\<open>We define vectors as pairs of dimension and a characteristic function from natural numbers\nto elements.\nSimilarly, matrices are defined as triples of two dimensions and one\ncharacteristic function from pairs of natural numbers to elements.\nVia a subtype we ensure that the characteristic function always behaves the same\non indices outside the intended one. Hence, every matrix has a unique representation.\n\nIn this part we define basic operations like matrix-addition, -multiplication, scalar-product,\netc. We connect these operations to HOL-Algebra with its explicit carrier sets.\\<close>\n\ntheory Matrix\nimports\n  Missing_Ring\n  \"HOL-Algebra.Module\"\n  Polynomial_Interpolation.Ring_Hom\n  Conjugate\nbegin\n\nsubsection\\<open>Vectors\\<close>\n\ntext \\<open>Here we specify which value should be returned in case\n  an index is out of bounds. The current solution has the advantage\n  that in the implementation later on, no index comparison has to be performed.\\<close>\n\ndefinition undef_vec :: \"nat \\<Rightarrow> 'a\" where\n  \"undef_vec i \\<equiv> [] ! i\"\n\ndefinition mk_vec :: \"nat \\<Rightarrow> (nat \\<Rightarrow> 'a) \\<Rightarrow> (nat \\<Rightarrow> 'a)\" where\n  \"mk_vec n f \\<equiv> \\<lambda> i. if i < n then f i else undef_vec (i - n)\"\n\ntypedef 'a vec = \"{(n, mk_vec n f) | n f :: nat \\<Rightarrow> 'a. True}\"\n  by auto\n\nsetup_lifting type_definition_vec\n\nlift_definition dim_vec :: \"'a vec \\<Rightarrow> nat\" is fst .\nlift_definition vec_index :: \"'a vec \\<Rightarrow> (nat \\<Rightarrow> 'a)\" (infixl \"$\" 100) is snd .\nlift_definition vec :: \"nat \\<Rightarrow> (nat \\<Rightarrow> 'a) \\<Rightarrow> 'a vec\"\n  is \"\\<lambda> n f. (n, mk_vec n f)\" by auto\n\nlift_definition vec_of_list :: \"'a list \\<Rightarrow> 'a vec\" is\n  \"\\<lambda> v. (length v, mk_vec (length v) (nth v))\" by auto\n\nlift_definition list_of_vec :: \"'a vec \\<Rightarrow> 'a list\" is\n  \"\\<lambda> (n,v). map v [0 ..< n]\" .\n\ndefinition carrier_vec :: \"nat \\<Rightarrow> 'a vec set\" where\n  \"carrier_vec n = { v . dim_vec v = n}\"\n\nlemma carrier_vec_dim_vec[simp]: \"v \\<in> carrier_vec (dim_vec v)\" unfolding carrier_vec_def by auto\n\nlemma dim_vec[simp]: \"dim_vec (vec n f) = n\" by transfer simp\nlemma vec_carrier[simp]: \"vec n f \\<in> carrier_vec n\" unfolding carrier_vec_def by auto\nlemma index_vec[simp]: \"i < n \\<Longrightarrow> vec n f $ i = f i\" by transfer (simp add: mk_vec_def)\nlemma eq_vecI[intro]: \"(\\<And> i. i < dim_vec w \\<Longrightarrow> v $ i = w $ i) \\<Longrightarrow> dim_vec v = dim_vec w\n  \\<Longrightarrow> v = w\"\n  by (transfer, auto simp: mk_vec_def)\n\nlemma carrier_dim_vec: \"v \\<in> carrier_vec n \\<longleftrightarrow> dim_vec v = n\"\n  unfolding carrier_vec_def by auto\n\nlemma carrier_vecD[simp]: \"v \\<in> carrier_vec n \\<Longrightarrow> dim_vec v = n\" using carrier_dim_vec by auto\n\nlemma carrier_vecI: \"dim_vec v = n \\<Longrightarrow> v \\<in> carrier_vec n\" using carrier_dim_vec by auto\n\ninstantiation vec :: (plus) plus\nbegin\ndefinition plus_vec :: \"'a vec \\<Rightarrow> 'a vec \\<Rightarrow> 'a :: plus vec\" where\n  \"v\\<^sub>1 + v\\<^sub>2 \\<equiv> vec (dim_vec v\\<^sub>2) (\\<lambda> i. v\\<^sub>1 $ i + v\\<^sub>2 $ i)\"\ninstance ..\nend\n\ninstantiation vec :: (minus) minus\nbegin\ndefinition minus_vec :: \"'a vec \\<Rightarrow> 'a vec \\<Rightarrow> 'a :: minus vec\" where\n  \"v\\<^sub>1 - v\\<^sub>2 \\<equiv> vec (dim_vec v\\<^sub>2) (\\<lambda> i. v\\<^sub>1 $ i - v\\<^sub>2 $ i)\"\ninstance ..\nend\n\ndefinition\n  zero_vec :: \"nat \\<Rightarrow> 'a :: zero vec\" (\"0\\<^sub>v\")\n  where \"0\\<^sub>v n \\<equiv> vec n (\\<lambda> i. 0)\"\n\nlemma zero_carrier_vec[simp]: \"0\\<^sub>v n \\<in> carrier_vec n\"\n  unfolding zero_vec_def carrier_vec_def by auto\n\nlemma index_zero_vec[simp]: \"i < n \\<Longrightarrow> 0\\<^sub>v n $ i = 0\" \"dim_vec (0\\<^sub>v n) = n\"\n  unfolding zero_vec_def by auto\n\nlemma vec_of_dim_0[simp]: \"dim_vec v = 0 \\<longleftrightarrow> v = 0\\<^sub>v 0\" by auto\n\ndefinition\n  unit_vec :: \"nat \\<Rightarrow> nat \\<Rightarrow> ('a :: zero_neq_one) vec\"\n  where \"unit_vec n i = vec n (\\<lambda> j. if j = i then 1 else 0)\"\n\nlemma index_unit_vec[simp]:\n  \"i < n \\<Longrightarrow> j < n \\<Longrightarrow> unit_vec n i $ j = (if j = i then 1 else 0)\"\n  \"i < n \\<Longrightarrow> unit_vec n i $ i = 1\"\n  \"dim_vec (unit_vec n i) = n\"\n  unfolding unit_vec_def by auto\n\nlemma unit_vec_eq[simp]:\n  assumes i: \"i < n\"\n  shows \"(unit_vec n i = unit_vec n j) = (i = j)\"\nproof -\n  have \"i \\<noteq> j \\<Longrightarrow> unit_vec n i $ i \\<noteq> unit_vec n j $ i\"\n    unfolding unit_vec_def using i by simp\n  then show ?thesis by metis\nqed\n\nlemma unit_vec_nonzero[simp]:\n  assumes i_n: \"i < n\" shows \"unit_vec n i \\<noteq> zero_vec n\" (is \"?l \\<noteq> ?r\")\nproof -\n  have \"?l $ i = 1\" \"?r $ i = 0\" using i_n by auto\n  thus \"?l \\<noteq> ?r\" by auto\nqed\n\nlemma unit_vec_carrier[simp]: \"unit_vec n i \\<in> carrier_vec n\"\n  unfolding unit_vec_def carrier_vec_def by auto\n\ndefinition unit_vecs:: \"nat \\<Rightarrow> 'a :: zero_neq_one vec list\"\n  where \"unit_vecs n = map (unit_vec n) [0..<n]\"\n\ntext \"List of first i units\"\n\nfun unit_vecs_first:: \"nat \\<Rightarrow> nat \\<Rightarrow> 'a::zero_neq_one vec list\"\n  where \"unit_vecs_first n 0 = []\"\n    |   \"unit_vecs_first n (Suc i) = unit_vecs_first n i @ [unit_vec n i]\"\n\nlemma unit_vecs_first: \"unit_vecs n = unit_vecs_first n n\"\n  unfolding unit_vecs_def set_map set_upt\nproof -\n  {fix m\n    have \"m \\<le> n \\<Longrightarrow> map (unit_vec n) [0..<m] = unit_vecs_first n m\"\n    proof (induct m)\n      case (Suc m) then have mn:\"m\\<le>n\" by auto\n        show ?case unfolding upt_Suc using Suc(1)[OF mn] by auto\n    qed auto\n  }\n  thus \"map (unit_vec n) [0..<n] = unit_vecs_first n n\" by auto\nqed\n\ntext \"list of last i units\"\n\nfun unit_vecs_last:: \"nat \\<Rightarrow> nat \\<Rightarrow> 'a :: zero_neq_one vec list\"\n  where \"unit_vecs_last n 0 = []\"\n    |   \"unit_vecs_last n (Suc i) = unit_vec n (n - Suc i) # unit_vecs_last n i\"\n\nlemma unit_vecs_last_carrier: \"set (unit_vecs_last n i) \\<subseteq> carrier_vec n\"\n  by (induct i;auto)\n\nlemma unit_vecs_last[code]: \"unit_vecs n = unit_vecs_last n n\"\nproof -\n  { fix m assume \"m = n\"\n    have \"m \\<le> n \\<Longrightarrow> map (unit_vec n) [n-m..<n] = unit_vecs_last n m\"\n      proof (induction m)\n      case (Suc m)\n        then have nm:\"n - Suc m < n\" by auto\n        have ins: \"[n - Suc m ..< n] = (n - Suc m) # [n - m ..< n]\"\n          unfolding upt_conv_Cons[OF nm]\n          by (auto simp: Suc.prems Suc_diff_Suc Suc_le_lessD)\n        show ?case\n          unfolding ins\n          unfolding unit_vecs_last.simps\n          unfolding list.map\n          using Suc\n          unfolding Suc by auto\n      qed simp\n  }\n  thus \"unit_vecs n = unit_vecs_last n n\"\n    unfolding unit_vecs_def by auto\nqed\n\nlemma unit_vecs_carrier: \"set (unit_vecs n) \\<subseteq> carrier_vec n\"\nproof\n  fix u :: \"'a vec\"  assume u: \"u \\<in> set (unit_vecs n)\"\n  then obtain i where \"u = unit_vec n i\" unfolding unit_vecs_def by auto\n  then show \"u \\<in> carrier_vec n\"\n    using unit_vec_carrier by auto\nqed\n\nlemma unit_vecs_last_distinct:\n  \"j \\<le> n \\<Longrightarrow> i < n - j \\<Longrightarrow> unit_vec n i \\<notin> set (unit_vecs_last n j)\"\n  by (induction j arbitrary:i, auto)\n\nlemma unit_vecs_first_distinct:\n  \"i \\<le> j \\<Longrightarrow> j < n \\<Longrightarrow> unit_vec n j \\<notin> set (unit_vecs_first n i)\"\n  by (induction i arbitrary:j, auto)\n\ndefinition map_vec where \"map_vec f v \\<equiv> vec (dim_vec v) (\\<lambda>i. f (v $ i))\"\n\ninstantiation vec :: (uminus) uminus\nbegin\ndefinition uminus_vec :: \"'a :: uminus vec \\<Rightarrow> 'a vec\" where\n  \"- v \\<equiv> vec (dim_vec v) (\\<lambda> i. - (v $ i))\"\ninstance ..\nend\n\ndefinition smult_vec :: \"'a :: times \\<Rightarrow> 'a vec \\<Rightarrow> 'a vec\" (infixl \"\\<cdot>\\<^sub>v\" 70)\n  where \"a \\<cdot>\\<^sub>v v \\<equiv> vec (dim_vec v) (\\<lambda> i. a * v $ i)\"\n\ndefinition scalar_prod :: \"'a vec \\<Rightarrow> 'a vec \\<Rightarrow> 'a :: semiring_0\" (infix \"\\<bullet>\" 70)\n  where \"v \\<bullet> w \\<equiv> \\<Sum> i \\<in> {0 ..< dim_vec w}. v $ i * w $ i\"\n\ndefinition monoid_vec :: \"'a itself \\<Rightarrow> nat \\<Rightarrow> ('a :: monoid_add vec) monoid\" where\n  \"monoid_vec ty n \\<equiv> \\<lparr>\n    carrier = carrier_vec n,\n    mult = (+),\n    one = 0\\<^sub>v n\\<rparr>\"\n\ndefinition module_vec ::\n  \"'a :: semiring_1 itself \\<Rightarrow> nat \\<Rightarrow> ('a,'a vec) module\" where\n  \"module_vec ty n \\<equiv> \\<lparr>\n    carrier = carrier_vec n,\n    mult = undefined,\n    one = undefined,\n    zero = 0\\<^sub>v n,\n    add = (+),\n    smult = (\\<cdot>\\<^sub>v)\\<rparr>\"\n\nlemma monoid_vec_simps:\n  \"mult (monoid_vec ty n) = (+)\"\n  \"carrier (monoid_vec ty n) = carrier_vec n\"\n  \"one (monoid_vec ty n) = 0\\<^sub>v n\"\n  unfolding monoid_vec_def by auto\n\nlemma module_vec_simps:\n  \"add (module_vec ty n) = (+)\"\n  \"zero (module_vec ty n) = 0\\<^sub>v n\"\n  \"carrier (module_vec ty n) = carrier_vec n\"\n  \"smult (module_vec ty n) = (\\<cdot>\\<^sub>v)\"\n  unfolding module_vec_def by auto\n\ndefinition finsum_vec :: \"'a :: monoid_add itself \\<Rightarrow> nat \\<Rightarrow> ('c \\<Rightarrow> 'a vec) \\<Rightarrow> 'c set \\<Rightarrow> 'a vec\" where\n  \"finsum_vec ty n = finprod (monoid_vec ty n)\"\n\nlemma index_add_vec[simp]:\n  \"i < dim_vec v\\<^sub>2 \\<Longrightarrow> (v\\<^sub>1 + v\\<^sub>2) $ i = v\\<^sub>1 $ i + v\\<^sub>2 $ i\" \"dim_vec (v\\<^sub>1 + v\\<^sub>2) = dim_vec v\\<^sub>2\"\n  unfolding plus_vec_def by auto\n\nlemma index_minus_vec[simp]:\n  \"i < dim_vec v\\<^sub>2 \\<Longrightarrow> (v\\<^sub>1 - v\\<^sub>2) $ i = v\\<^sub>1 $ i - v\\<^sub>2 $ i\" \"dim_vec (v\\<^sub>1 - v\\<^sub>2) = dim_vec v\\<^sub>2\"\n  unfolding minus_vec_def by auto\n\nlemma index_map_vec[simp]:\n  \"i < dim_vec v \\<Longrightarrow> map_vec f v $ i = f (v $ i)\"\n  \"dim_vec (map_vec f v) = dim_vec v\"\n  unfolding map_vec_def by auto\n\nlemma map_carrier_vec[simp]: \"map_vec h v \\<in> carrier_vec n = (v \\<in> carrier_vec n)\"\n  unfolding map_vec_def carrier_vec_def by auto\n\nlemma index_uminus_vec[simp]:\n  \"i < dim_vec v \\<Longrightarrow> (- v) $ i = - (v $ i)\"\n  \"dim_vec (- v) = dim_vec v\"\n  unfolding uminus_vec_def by auto\n\nlemma index_smult_vec[simp]:\n  \"i < dim_vec v \\<Longrightarrow> (a \\<cdot>\\<^sub>v v) $ i = a * v $ i\" \"dim_vec (a \\<cdot>\\<^sub>v v) = dim_vec v\"\n  unfolding smult_vec_def by auto\n\nlemma add_carrier_vec[simp]:\n  \"v\\<^sub>1 \\<in> carrier_vec n \\<Longrightarrow> v\\<^sub>2 \\<in> carrier_vec n \\<Longrightarrow> v\\<^sub>1 + v\\<^sub>2 \\<in> carrier_vec n\"\n  unfolding carrier_vec_def by auto\n\nlemma minus_carrier_vec[simp]:\n  \"v\\<^sub>1 \\<in> carrier_vec n \\<Longrightarrow> v\\<^sub>2 \\<in> carrier_vec n \\<Longrightarrow> v\\<^sub>1 - v\\<^sub>2 \\<in> carrier_vec n\"\n  unfolding carrier_vec_def by auto\n\nlemma comm_add_vec[ac_simps]:\n  \"(v\\<^sub>1 :: 'a :: ab_semigroup_add vec) \\<in> carrier_vec n \\<Longrightarrow> v\\<^sub>2 \\<in> carrier_vec n \\<Longrightarrow> v\\<^sub>1 + v\\<^sub>2 = v\\<^sub>2 + v\\<^sub>1\"\n  by (intro eq_vecI, auto simp: ac_simps)\n\nlemma assoc_add_vec[simp]:\n  \"(v\\<^sub>1 :: 'a :: semigroup_add vec) \\<in> carrier_vec n \\<Longrightarrow> v\\<^sub>2 \\<in> carrier_vec n \\<Longrightarrow> v\\<^sub>3 \\<in> carrier_vec n\n  \\<Longrightarrow> (v\\<^sub>1 + v\\<^sub>2) + v\\<^sub>3 = v\\<^sub>1 + (v\\<^sub>2 + v\\<^sub>3)\"\n  by (intro eq_vecI, auto simp: ac_simps)\n\nlemma zero_minus_vec[simp]: \"(v :: 'a :: group_add vec) \\<in> carrier_vec n \\<Longrightarrow> 0\\<^sub>v n - v = - v\"\n  by (intro eq_vecI, auto)\n\nlemma minus_zero_vec[simp]: \"(v :: 'a :: group_add vec) \\<in> carrier_vec n \\<Longrightarrow> v - 0\\<^sub>v n = v\"\n  by (intro eq_vecI, auto)\n\nlemma minus_cancel_vec[simp]: \"(v :: 'a :: group_add vec) \\<in> carrier_vec n \\<Longrightarrow> v - v = 0\\<^sub>v n\"\n  by (intro eq_vecI, auto)\n\nlemma minus_add_uminus_vec: \"(v :: 'a :: group_add vec) \\<in> carrier_vec n \\<Longrightarrow>\n  w \\<in> carrier_vec n \\<Longrightarrow> v - w = v + (- w)\"\n  by (intro eq_vecI, auto)\n\nlemma comm_monoid_vec: \"comm_monoid (monoid_vec TYPE ('a :: comm_monoid_add) n)\"\n  by (unfold_locales, auto simp: monoid_vec_def ac_simps)\n\nlemma left_zero_vec[simp]: \"(v :: 'a :: monoid_add vec) \\<in> carrier_vec n  \\<Longrightarrow> 0\\<^sub>v n + v = v\" by auto\n\nlemma right_zero_vec[simp]: \"(v :: 'a :: monoid_add vec) \\<in> carrier_vec n  \\<Longrightarrow> v + 0\\<^sub>v n = v\" by auto\n\n\nlemma uminus_carrier_vec[simp]:\n  \"(- v \\<in> carrier_vec n) = (v \\<in> carrier_vec n)\"\n  unfolding carrier_vec_def by auto\n\nlemma uminus_r_inv_vec[simp]:\n  \"(v :: 'a :: group_add vec) \\<in> carrier_vec n \\<Longrightarrow> (v + - v) = 0\\<^sub>v n\"\n  by (intro eq_vecI, auto)\n\nlemma uminus_l_inv_vec[simp]:\n  \"(v :: 'a :: group_add vec) \\<in> carrier_vec n \\<Longrightarrow> (- v + v) = 0\\<^sub>v n\"\n  by (intro eq_vecI, auto)\n\nlemma add_inv_exists_vec:\n  \"(v :: 'a :: group_add vec) \\<in> carrier_vec n \\<Longrightarrow> \\<exists> w \\<in> carrier_vec n. w + v = 0\\<^sub>v n \\<and> v + w = 0\\<^sub>v n\"\n  by (intro bexI[of _ \"- v\"], auto)\n\nlemma comm_group_vec: \"comm_group (monoid_vec TYPE ('a :: ab_group_add) n)\"\n  by (unfold_locales, insert add_inv_exists_vec, auto simp: monoid_vec_def ac_simps Units_def)\n\nlemmas finsum_vec_insert =\n  comm_monoid.finprod_insert[OF comm_monoid_vec, folded finsum_vec_def, unfolded monoid_vec_simps]\n\nlemmas finsum_vec_closed =\n  comm_monoid.finprod_closed[OF comm_monoid_vec, folded finsum_vec_def, unfolded monoid_vec_simps]\n\nlemmas finsum_vec_empty =\n  comm_monoid.finprod_empty[OF comm_monoid_vec, folded finsum_vec_def, unfolded monoid_vec_simps]\n\nlemma smult_carrier_vec[simp]: \"(a \\<cdot>\\<^sub>v v \\<in> carrier_vec n) = (v \\<in> carrier_vec n)\"\n  unfolding carrier_vec_def by auto\n\nlemma scalar_prod_left_zero[simp]: \"v \\<in> carrier_vec n \\<Longrightarrow> 0\\<^sub>v n \\<bullet> v = 0\"\n  unfolding scalar_prod_def\n  by (rule sum.neutral, auto)\n\nlemma scalar_prod_right_zero[simp]: \"v \\<in> carrier_vec n \\<Longrightarrow> v \\<bullet> 0\\<^sub>v n = 0\"\n  unfolding scalar_prod_def\n  by (rule sum.neutral, auto)\n\nlemma scalar_prod_left_unit[simp]: assumes v: \"(v :: 'a :: semiring_1 vec) \\<in> carrier_vec n\" and i: \"i < n\"\n  shows \"unit_vec n i \\<bullet> v = v $ i\"\nproof -\n  let ?f = \"\\<lambda> k. unit_vec n i $ k * v $ k\"\n  have id: \"(\\<Sum>k\\<in>{0..<n}. ?f k) = unit_vec n i $ i * v $ i + (\\<Sum>k\\<in>{0..<n} - {i}. ?f k)\"\n    by (rule sum.remove, insert i, auto)\n  also have \"(\\<Sum> k\\<in>{0..<n} - {i}. ?f k) = 0\"\n    by (rule sum.neutral, insert i, auto)\n  finally\n  show ?thesis unfolding scalar_prod_def using i v by simp\nqed\n\nlemma scalar_prod_right_unit[simp]: assumes i: \"i < n\"\n  shows \"(v :: 'a :: semiring_1 vec) \\<bullet> unit_vec n i = v $ i\"\nproof -\n  let ?f = \"\\<lambda> k. v $ k * unit_vec n i $ k\"\n  have id: \"(\\<Sum>k\\<in>{0..<n}. ?f k) = v $ i * unit_vec n i $ i + (\\<Sum>k\\<in>{0..<n} - {i}. ?f k)\"\n    by (rule sum.remove, insert i, auto)\n  also have \"(\\<Sum>k\\<in>{0..<n} - {i}. ?f k) = 0\"\n    by (rule sum.neutral, insert i, auto)\n  finally\n  show ?thesis unfolding scalar_prod_def using i by simp\nqed\n\nlemma add_scalar_prod_distrib: assumes v: \"v\\<^sub>1 \\<in> carrier_vec n\" \"v\\<^sub>2 \\<in> carrier_vec n\" \"v\\<^sub>3 \\<in> carrier_vec n\"\n  shows \"(v\\<^sub>1 + v\\<^sub>2) \\<bullet> v\\<^sub>3 = v\\<^sub>1 \\<bullet> v\\<^sub>3 + v\\<^sub>2 \\<bullet> v\\<^sub>3\"\nproof -\n  have \"(\\<Sum>i\\<in>{0..<dim_vec v\\<^sub>3}. (v\\<^sub>1 + v\\<^sub>2) $ i * v\\<^sub>3 $ i) = (\\<Sum>i\\<in>{0..<dim_vec v\\<^sub>3}. v\\<^sub>1 $ i * v\\<^sub>3 $ i + v\\<^sub>2 $ i * v\\<^sub>3 $ i)\"\n    by (rule sum.cong, insert v, auto simp: algebra_simps)\n  thus ?thesis unfolding scalar_prod_def using v by (auto simp: sum.distrib)\nqed\n\nlemma scalar_prod_add_distrib: assumes v: \"v\\<^sub>1 \\<in> carrier_vec n\" \"v\\<^sub>2 \\<in> carrier_vec n\" \"v\\<^sub>3 \\<in> carrier_vec n\"\n  shows \"v\\<^sub>1 \\<bullet> (v\\<^sub>2 + v\\<^sub>3) = v\\<^sub>1 \\<bullet> v\\<^sub>2 + v\\<^sub>1 \\<bullet> v\\<^sub>3\"\nproof -\n  have \"(\\<Sum>i\\<in>{0..<dim_vec v\\<^sub>3}. v\\<^sub>1 $ i * (v\\<^sub>2 + v\\<^sub>3) $ i) = (\\<Sum>i\\<in>{0..<dim_vec v\\<^sub>3}. v\\<^sub>1 $ i * v\\<^sub>2 $ i + v\\<^sub>1 $ i * v\\<^sub>3 $ i)\"\n    by (rule sum.cong, insert v, auto simp: algebra_simps)\n  thus ?thesis unfolding scalar_prod_def using v by (auto intro: sum.distrib)\nqed\n\nlemma smult_scalar_prod_distrib[simp]: assumes v: \"v\\<^sub>1 \\<in> carrier_vec n\" \"v\\<^sub>2 \\<in> carrier_vec n\"\n  shows \"(a \\<cdot>\\<^sub>v v\\<^sub>1) \\<bullet> v\\<^sub>2 = a * (v\\<^sub>1 \\<bullet> v\\<^sub>2)\"\n  unfolding scalar_prod_def sum_distrib_left\n  by (rule sum.cong, insert v, auto simp: ac_simps)\n\nlemma scalar_prod_smult_distrib[simp]: assumes v: \"v\\<^sub>1 \\<in> carrier_vec n\" \"v\\<^sub>2 \\<in> carrier_vec n\"\n  shows \"v\\<^sub>1 \\<bullet> (a \\<cdot>\\<^sub>v v\\<^sub>2) = (a :: 'a :: comm_ring) * (v\\<^sub>1 \\<bullet> v\\<^sub>2)\"\n  unfolding scalar_prod_def sum_distrib_left\n  by (rule sum.cong, insert v, auto simp: ac_simps)\n\nlemma comm_scalar_prod: assumes \"(v\\<^sub>1 :: 'a :: comm_semiring_0 vec) \\<in> carrier_vec n\" \"v\\<^sub>2 \\<in> carrier_vec n\"\n  shows \"v\\<^sub>1 \\<bullet> v\\<^sub>2 = v\\<^sub>2 \\<bullet> v\\<^sub>1\"\n  unfolding scalar_prod_def\n  by (rule sum.cong, insert assms, auto simp: ac_simps)\n\nlemma add_smult_distrib_vec:\n  \"((a::'a::ring) + b) \\<cdot>\\<^sub>v v = a \\<cdot>\\<^sub>v v + b \\<cdot>\\<^sub>v v\"\n  unfolding smult_vec_def plus_vec_def\n  by (rule eq_vecI, auto simp: distrib_right)\n\nlemma smult_add_distrib_vec:\n  assumes \"v \\<in> carrier_vec n\" \"w \\<in> carrier_vec n\"\n  shows \"(a::'a::ring) \\<cdot>\\<^sub>v (v + w) = a \\<cdot>\\<^sub>v v + a \\<cdot>\\<^sub>v w\"\n  apply (rule eq_vecI)\n  unfolding smult_vec_def plus_vec_def\n  using assms distrib_left by auto\n\n\n\nlemma one_smult_vec [simp]:\n  \"(1::'a::ring_1) \\<cdot>\\<^sub>v v = v\" unfolding smult_vec_def\n  by (rule eq_vecI,auto)\n\nlemma uminus_zero_vec[simp]: \"- (0\\<^sub>v n) = (0\\<^sub>v n :: 'a :: group_add vec)\" \n  by (intro eq_vecI, auto)\n\nlemma index_finsum_vec: assumes \"finite F\" and i: \"i < n\"\n  and vs: \"vs \\<in> F \\<rightarrow> carrier_vec n\"\n  shows \"finsum_vec TYPE('a :: comm_monoid_add) n vs F $ i = sum (\\<lambda> f. vs f $ i) F\"\n  using \\<open>finite F\\<close> vs\nproof (induct F)\n  case (insert f F)\n  hence IH: \"finsum_vec TYPE('a) n vs F $ i = (\\<Sum>f\\<in>F. vs f $ i)\"\n    and vs: \"vs \\<in> F \\<rightarrow> carrier_vec n\" \"vs f \\<in> carrier_vec n\" by auto\n  show ?case unfolding finsum_vec_insert[OF insert(1-2) vs]\n    unfolding sum.insert[OF insert(1-2)]\n    unfolding IH[symmetric]\n    by (rule index_add_vec, insert i, insert finsum_vec_closed[OF vs(1)], auto)\nqed (insert i, auto simp: finsum_vec_empty)\n\ntext \\<open>Definition of pointwise ordering on vectors for non-strict part, and\n  strict version is defined in a way such that the @{class order} constraints are satisfied.\\<close>\n\ninstantiation vec :: (ord) ord\nbegin\n\ndefinition less_eq_vec :: \"'a vec \\<Rightarrow> 'a vec \\<Rightarrow> bool\" where\n  \"less_eq_vec v w = (dim_vec v = dim_vec w \\<and> (\\<forall> i < dim_vec w. v $ i \\<le> w $ i))\" \n\ndefinition less_vec :: \"'a vec \\<Rightarrow> 'a vec \\<Rightarrow> bool\" where\n  \"less_vec v w = (v \\<le> w \\<and> \\<not> (w \\<le> v))\"\ninstance ..\nend\n\ninstantiation vec :: (preorder) preorder\nbegin\ninstance\n  by (standard, auto simp: less_vec_def less_eq_vec_def order_trans)\nend\n\ninstantiation vec :: (order) order\nbegin\ninstance\n  by (standard, intro eq_vecI, auto simp: less_eq_vec_def order.antisym)\nend\n\n\nsubsection\\<open>Matrices\\<close>\n\ntext \\<open>Similarly as for vectors, we specify which value should be returned in case\n  an index is out of bounds. It is defined in a way that only few\n  index comparisons have to be performed in the implementation.\\<close>\n\ndefinition undef_mat :: \"nat \\<Rightarrow> nat \\<Rightarrow> (nat \\<times> nat \\<Rightarrow> 'a) \\<Rightarrow> nat \\<times> nat \\<Rightarrow> 'a\" where\n  \"undef_mat nr nc f \\<equiv> \\<lambda> (i,j). [[f (i,j). j <- [0 ..< nc]] . i <- [0 ..< nr]] ! i ! j\"\n\nlemma undef_cong_mat: assumes \"\\<And> i j. i < nr \\<Longrightarrow> j < nc \\<Longrightarrow> f (i,j) = f' (i,j)\"\n  shows \"undef_mat nr nc f x = undef_mat nr nc f' x\"\nproof (cases x)\n  case (Pair i j)\n  have nth_map_ge: \"\\<And> i xs. \\<not> i < length xs \\<Longrightarrow> xs ! i = [] ! (i - length xs)\"\n    by (metis append_Nil2 nth_append)\n  note [simp] = Pair undef_mat_def nth_map_ge[of i] nth_map_ge[of j]\n  show ?thesis\n    by (cases \"i < nr\", simp, cases \"j < nc\", insert assms, auto)\nqed\n\ndefinition mk_mat :: \"nat \\<Rightarrow> nat \\<Rightarrow> (nat \\<times> nat \\<Rightarrow> 'a) \\<Rightarrow> (nat \\<times> nat \\<Rightarrow> 'a)\" where\n  \"mk_mat nr nc f \\<equiv> \\<lambda> (i,j). if i < nr \\<and> j < nc then f (i,j) else undef_mat nr nc f (i,j)\"\n\nlemma cong_mk_mat: assumes \"\\<And> i j. i < nr \\<Longrightarrow> j < nc \\<Longrightarrow> f (i,j) = f' (i,j)\"\n  shows \"mk_mat nr nc f = mk_mat nr nc f'\"\n  using undef_cong_mat[of nr nc f f', OF assms]\n  using assms unfolding mk_mat_def\n  by auto\n\ntypedef 'a mat = \"{(nr, nc, mk_mat nr nc f) | nr nc f :: nat \\<times> nat \\<Rightarrow> 'a. True}\"\n  by auto\n\nsetup_lifting type_definition_mat\n\nlift_definition dim_row :: \"'a mat \\<Rightarrow> nat\" is fst .\nlift_definition dim_col :: \"'a mat \\<Rightarrow> nat\" is \"fst o snd\" .\nlift_definition index_mat :: \"'a mat \\<Rightarrow> (nat \\<times> nat \\<Rightarrow> 'a)\" (infixl \"$$\" 100) is \"snd o snd\" .\nlift_definition mat :: \"nat \\<Rightarrow> nat \\<Rightarrow> (nat \\<times> nat \\<Rightarrow> 'a) \\<Rightarrow> 'a mat\"\n  is \"\\<lambda> nr nc f. (nr, nc, mk_mat nr nc f)\" by auto\nlift_definition mat_of_row_fun :: \"nat \\<Rightarrow> nat \\<Rightarrow> (nat \\<Rightarrow> 'a vec) \\<Rightarrow> 'a mat\" (\"mat\\<^sub>r\")\n  is \"\\<lambda> nr nc f. (nr, nc, mk_mat nr nc (\\<lambda> (i,j). f i $ j))\" by auto\n\ndefinition mat_to_list :: \"'a mat \\<Rightarrow> 'a list list\" where\n  \"mat_to_list A = [ [A $$ (i,j) . j <- [0 ..< dim_col A]] . i <- [0 ..< dim_row A]]\"\n\nfun square_mat :: \"'a mat \\<Rightarrow> bool\" where \"square_mat A = (dim_col A = dim_row A)\"\n\ndefinition upper_triangular :: \"'a::zero mat \\<Rightarrow> bool\"\n  where \"upper_triangular A \\<equiv>\n    \\<forall>i < dim_row A. \\<forall> j < i. A $$ (i,j) = 0\"\n\nlemma upper_triangularD[elim] :\n  \"upper_triangular A \\<Longrightarrow> j < i \\<Longrightarrow> i < dim_row A \\<Longrightarrow> A $$ (i,j) = 0\"\nunfolding upper_triangular_def by auto\n\nlemma upper_triangularI[intro] :\n  \"(\\<And>i j. j < i \\<Longrightarrow> i < dim_row A \\<Longrightarrow> A $$ (i,j) = 0) \\<Longrightarrow> upper_triangular A\"\nunfolding upper_triangular_def by auto\n\nlemma dim_row_mat[simp]: \"dim_row (mat nr nc f) = nr\" \"dim_row (mat\\<^sub>r nr nc g) = nr\"\n  by (transfer, simp)+\n\n\n\ndefinition carrier_mat :: \"nat \\<Rightarrow> nat \\<Rightarrow> 'a mat set\"\n  where \"carrier_mat nr nc = { m . dim_row m = nr \\<and> dim_col m = nc}\"\n\nlemma carrier_mat_triv[simp]: \"m \\<in> carrier_mat (dim_row m) (dim_col m)\"\n  unfolding carrier_mat_def by auto\n\nlemma mat_carrier[simp]: \"mat nr nc f \\<in> carrier_mat nr nc\"\n  unfolding carrier_mat_def by auto\n\ndefinition elements_mat :: \"'a mat \\<Rightarrow> 'a set\"\n  where \"elements_mat A = set [A $$ (i,j). i <- [0 ..< dim_row A], j <- [0 ..< dim_col A]]\"\n\nlemma elements_matD [dest]:\n  \"a \\<in> elements_mat A \\<Longrightarrow> \\<exists>i j. i < dim_row A \\<and> j < dim_col A \\<and> a = A $$ (i,j)\"\n  unfolding elements_mat_def by force\n\nlemma elements_matI [intro]:\n  \"A \\<in> carrier_mat nr nc \\<Longrightarrow> i < nr \\<Longrightarrow> j < nc \\<Longrightarrow> a = A $$ (i,j) \\<Longrightarrow> a \\<in> elements_mat A\"\n  unfolding elements_mat_def carrier_mat_def by force\n\nlemma index_mat[simp]:  \"i < nr \\<Longrightarrow> j < nc \\<Longrightarrow> mat nr nc f $$ (i,j) = f (i,j)\"\n  \"i < nr \\<Longrightarrow> j < nc \\<Longrightarrow> mat\\<^sub>r nr nc g $$ (i,j) = g i $ j\"\n  by (transfer', simp add: mk_mat_def)+\n\nlemma eq_matI[intro]: \"(\\<And> i j . i < dim_row B \\<Longrightarrow> j < dim_col B \\<Longrightarrow> A $$ (i,j) = B $$ (i,j))\n  \\<Longrightarrow> dim_row A = dim_row B\n  \\<Longrightarrow> dim_col A = dim_col B\n  \\<Longrightarrow> A = B\"\n  by (transfer, auto intro!: cong_mk_mat, auto simp: mk_mat_def)\n\nlemma carrier_matI[intro]:\n  assumes \"dim_row A = nr\" \"dim_col A = nc\" shows  \"A \\<in> carrier_mat nr nc\"\n  using assms unfolding carrier_mat_def by auto\n\nlemma carrier_matD[dest,simp]: assumes \"A \\<in> carrier_mat nr nc\"\n  shows \"dim_row A = nr\" \"dim_col A = nc\" using assms\n  unfolding carrier_mat_def by auto\n\nlemma cong_mat: assumes \"nr = nr'\" \"nc = nc'\" \"\\<And> i j. i < nr \\<Longrightarrow> j < nc \\<Longrightarrow>\n  f (i,j) = f' (i,j)\" shows \"mat nr nc f = mat nr' nc' f'\"\n  by (rule eq_matI, insert assms, auto)\n\ndefinition row :: \"'a mat \\<Rightarrow> nat \\<Rightarrow> 'a vec\" where\n  \"row A i = vec (dim_col A) (\\<lambda> j. A $$ (i,j))\"\n\ndefinition rows :: \"'a mat \\<Rightarrow> 'a vec list\" where\n  \"rows A = map (row A) [0..<dim_row A]\"\n\nlemma row_carrier[simp]: \"row A i \\<in> carrier_vec (dim_col A)\" unfolding row_def by auto\n\nlemma rows_carrier[simp]: \"set (rows A) \\<subseteq> carrier_vec (dim_col A)\" unfolding rows_def by auto\n\nlemma length_rows[simp]: \"length (rows A) = dim_row A\" unfolding rows_def by auto\n\nlemma nth_rows[simp]: \"i < dim_row A \\<Longrightarrow> rows A ! i = row A i\"\n  unfolding rows_def by auto\n\nlemma row_mat_of_row_fun[simp]: \"i < nr \\<Longrightarrow> dim_vec (f i) = nc \\<Longrightarrow> row (mat\\<^sub>r nr nc f) i = f i\"\n  by (rule eq_vecI, auto simp: row_def)\n\nlemma set_rows_carrier:\n  assumes \"A \\<in> carrier_mat m n\" and \"v \\<in> set (rows A)\" shows \"v \\<in> carrier_vec n\"\n  using assms by (auto simp: rows_def row_def)\n\ndefinition mat_of_rows :: \"nat \\<Rightarrow> 'a vec list \\<Rightarrow> 'a mat\"\n  where \"mat_of_rows n rs = mat (length rs) n (\\<lambda>(i,j). rs ! i $ j)\"\n\ndefinition mat_of_rows_list :: \"nat \\<Rightarrow> 'a list list \\<Rightarrow> 'a mat\" where\n  \"mat_of_rows_list nc rs = mat (length rs) nc (\\<lambda> (i,j). rs ! i ! j)\"\n\nlemma mat_of_rows_carrier[simp]:\n  \"mat_of_rows n vs \\<in> carrier_mat (length vs) n\"\n  \"dim_row (mat_of_rows n vs) = length vs\"\n  \"dim_col (mat_of_rows n vs) = n\"\n  unfolding mat_of_rows_def by auto\n\nlemma mat_of_rows_row[simp]:\n  assumes i:\"i < length vs\" and n: \"vs ! i \\<in> carrier_vec n\"\n  shows \"row (mat_of_rows n vs) i = vs ! i\"\n  unfolding mat_of_rows_def row_def using n i by auto\n\nlemma rows_mat_of_rows[simp]:\n  assumes \"set vs \\<subseteq> carrier_vec n\" shows \"rows (mat_of_rows n vs) = vs\"\n  unfolding rows_def apply (rule nth_equalityI)\n  using assms unfolding subset_code(1) by auto\n\nlemma mat_of_rows_rows[simp]:\n  \"mat_of_rows (dim_col A) (rows A) = A\"\n  unfolding mat_of_rows_def by (rule, auto simp: row_def)\n\n\ndefinition col :: \"'a mat \\<Rightarrow> nat \\<Rightarrow> 'a vec\" where\n  \"col A j = vec (dim_row A) (\\<lambda> i. A $$ (i,j))\"\n\ndefinition cols :: \"'a mat \\<Rightarrow> 'a vec list\" where\n  \"cols A = map (col A) [0..<dim_col A]\"\n\ndefinition mat_of_cols :: \"nat \\<Rightarrow> 'a vec list \\<Rightarrow> 'a mat\"\n  where \"mat_of_cols n cs = mat n (length cs) (\\<lambda>(i,j). cs ! j $ i)\"\n\ndefinition mat_of_cols_list :: \"nat \\<Rightarrow> 'a list list \\<Rightarrow> 'a mat\" where\n  \"mat_of_cols_list nr cs = mat nr (length cs) (\\<lambda> (i,j). cs ! j ! i)\"\n\nlemma col_dim[simp]: \"col A i \\<in> carrier_vec (dim_row A)\" unfolding col_def by auto\n\nlemma dim_col[simp]: \"dim_vec (col A i) = dim_row A\" by auto\n\nlemma cols_dim[simp]: \"set (cols A) \\<subseteq> carrier_vec (dim_row A)\" unfolding cols_def by auto\n\nlemma cols_length[simp]: \"length (cols A) = dim_col A\" unfolding cols_def by auto\n\nlemma cols_nth[simp]: \"i < dim_col A \\<Longrightarrow> cols A ! i = col A i\"\n  unfolding cols_def by auto\n\nlemma mat_of_cols_carrier[simp]:\n  \"mat_of_cols n vs \\<in> carrier_mat n (length vs)\"\n  \"dim_row (mat_of_cols n vs) = n\"\n  \"dim_col (mat_of_cols n vs) = length vs\"\n  unfolding mat_of_cols_def by auto\n\nlemma col_mat_of_cols[simp]:\n  assumes j:\"j < length vs\" and n: \"vs ! j \\<in> carrier_vec n\"\n  shows \"col (mat_of_cols n vs) j = vs ! j\"\n  unfolding mat_of_cols_def col_def using j n by auto\n\nlemma cols_mat_of_cols[simp]:\n  assumes \"set vs \\<subseteq> carrier_vec n\" shows \"cols (mat_of_cols n vs) = vs\"\n  unfolding cols_def apply(rule nth_equalityI)\n  using assms unfolding subset_code(1) by auto\n\nlemma mat_of_cols_cols[simp]:\n  \"mat_of_cols (dim_row A) (cols A) = A\"\n  unfolding mat_of_cols_def by (rule, auto simp: col_def)\n\n\ninstantiation mat :: (ord) ord\nbegin\n\ndefinition less_eq_mat :: \"'a mat \\<Rightarrow> 'a mat \\<Rightarrow> bool\" where\n  \"less_eq_mat A B = (dim_row A = dim_row B \\<and> dim_col A = dim_col B \\<and> \n      (\\<forall> i < dim_row B. \\<forall> j < dim_col B. A $$ (i,j) \\<le> B $$ (i,j)))\" \n\ndefinition less_mat :: \"'a mat \\<Rightarrow> 'a mat \\<Rightarrow> bool\" where\n  \"less_mat A B = (A \\<le> B \\<and> \\<not> (B \\<le> A))\"\ninstance ..\nend\n\ninstantiation mat :: (preorder) preorder\nbegin\ninstance\nproof (standard, auto simp: less_mat_def less_eq_mat_def, goal_cases)\n  case (1 A B C i j)\n  thus ?case using order_trans[of \"A $$ (i,j)\" \"B $$ (i,j)\" \"C $$ (i,j)\"] by auto\nqed\nend\n\ninstantiation mat :: (order) order\nbegin\ninstance\n  by (standard, intro eq_matI, auto simp: less_eq_mat_def order.antisym)\nend\n\ninstantiation mat :: (plus) plus\nbegin\ndefinition plus_mat :: \"('a :: plus) mat \\<Rightarrow> 'a mat \\<Rightarrow> 'a mat\" where\n  \"A + B \\<equiv> mat (dim_row B) (dim_col B) (\\<lambda> ij. A $$ ij + B $$ ij)\"\ninstance ..\nend\n\ndefinition map_mat :: \"('a \\<Rightarrow> 'b) \\<Rightarrow> 'a mat \\<Rightarrow> 'b mat\" where\n  \"map_mat f A \\<equiv> mat (dim_row A) (dim_col A) (\\<lambda> ij. f (A $$ ij))\"\n\ndefinition smult_mat :: \"'a :: times \\<Rightarrow> 'a mat \\<Rightarrow> 'a mat\" (infixl \"\\<cdot>\\<^sub>m\" 70)\n  where \"a \\<cdot>\\<^sub>m A \\<equiv> map_mat (\\<lambda> b. a * b) A\"\n\ndefinition zero_mat :: \"nat \\<Rightarrow> nat \\<Rightarrow> 'a :: zero mat\" (\"0\\<^sub>m\") where\n  \"0\\<^sub>m nr nc \\<equiv> mat nr nc (\\<lambda> ij. 0)\"\n\nlemma elements_0_mat [simp]: \"elements_mat (0\\<^sub>m nr nc) \\<subseteq> {0}\"\n  unfolding elements_mat_def zero_mat_def by auto\n\ndefinition transpose_mat :: \"'a mat \\<Rightarrow> 'a mat\" where\n  \"transpose_mat A \\<equiv> mat (dim_col A) (dim_row A) (\\<lambda> (i,j). A $$ (j,i))\"\n\ndefinition one_mat :: \"nat \\<Rightarrow> 'a :: {zero,one} mat\" (\"1\\<^sub>m\") where\n  \"1\\<^sub>m n \\<equiv> mat n n (\\<lambda> (i,j). if i = j then 1 else 0)\"\n\ninstantiation mat :: (uminus) uminus\nbegin\ndefinition uminus_mat :: \"'a :: uminus mat \\<Rightarrow> 'a mat\" where\n  \"- A \\<equiv> mat (dim_row A) (dim_col A) (\\<lambda> ij. - (A $$ ij))\"\ninstance ..\nend\n\ninstantiation mat :: (minus) minus\nbegin\ndefinition minus_mat :: \"('a :: minus) mat \\<Rightarrow> 'a mat \\<Rightarrow> 'a mat\" where\n  \"A - B \\<equiv> mat (dim_row B) (dim_col B) (\\<lambda> ij. A $$ ij - B $$ ij)\"\ninstance ..\nend\n\ninstantiation mat :: (semiring_0) times\nbegin\ndefinition times_mat :: \"'a :: semiring_0 mat \\<Rightarrow> 'a mat \\<Rightarrow> 'a mat\"\n  where \"A * B \\<equiv> mat (dim_row A) (dim_col B) (\\<lambda> (i,j). row A i \\<bullet> col B j)\"\ninstance ..\nend\n\ndefinition mult_mat_vec :: \"'a :: semiring_0 mat \\<Rightarrow> 'a vec \\<Rightarrow> 'a vec\" (infixl \"*\\<^sub>v\" 70)\n  where \"A *\\<^sub>v v \\<equiv> vec (dim_row A) (\\<lambda> i. row A i \\<bullet> v)\"\n\ndefinition inverts_mat :: \"'a :: semiring_1 mat \\<Rightarrow> 'a mat \\<Rightarrow> bool\" where\n  \"inverts_mat A B \\<equiv> A * B = 1\\<^sub>m (dim_row A)\"\n\ndefinition invertible_mat :: \"'a :: semiring_1 mat \\<Rightarrow> bool\"\n  where \"invertible_mat A \\<equiv> square_mat A \\<and> (\\<exists>B. inverts_mat A B \\<and> inverts_mat B A)\"\n\ndefinition monoid_mat :: \"'a :: monoid_add itself \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> 'a mat monoid\" where\n  \"monoid_mat ty nr nc \\<equiv> \\<lparr>\n    carrier = carrier_mat nr nc,\n    mult = (+),\n    one = 0\\<^sub>m nr nc\\<rparr>\"\n\ndefinition ring_mat :: \"'a :: semiring_1 itself \\<Rightarrow> nat \\<Rightarrow> 'b \\<Rightarrow> ('a mat,'b) ring_scheme\" where\n  \"ring_mat ty n b \\<equiv> \\<lparr>\n    carrier = carrier_mat n n,\n    mult = (*),\n    one = 1\\<^sub>m n,\n    zero = 0\\<^sub>m n n,\n    add = (+),\n    \\<dots> = b\\<rparr>\"\n\ndefinition module_mat :: \"'a :: semiring_1 itself \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> ('a,'a mat)module\" where\n  \"module_mat ty nr nc \\<equiv> \\<lparr>\n    carrier = carrier_mat nr nc,\n    mult = (*),\n    one = 1\\<^sub>m nr,\n    zero = 0\\<^sub>m nr nc,\n    add = (+),\n    smult = (\\<cdot>\\<^sub>m)\\<rparr>\"\n\nlemma ring_mat_simps:\n  \"mult (ring_mat ty n b) = (*)\"\n  \"add (ring_mat ty n b) = (+)\"\n  \"one (ring_mat ty n b) = 1\\<^sub>m n\"\n  \"zero (ring_mat ty n b) = 0\\<^sub>m n n\"\n  \"carrier (ring_mat ty n b) = carrier_mat n n\"\n  unfolding ring_mat_def by auto\n\nlemma module_mat_simps:\n  \"mult (module_mat ty nr nc) = (*)\"\n  \"add (module_mat ty nr nc) = (+)\"\n  \"one (module_mat ty nr nc) = 1\\<^sub>m nr\"\n  \"zero (module_mat ty nr nc) = 0\\<^sub>m nr nc\"\n  \"carrier (module_mat ty nr nc) = carrier_mat nr nc\"\n  \"smult (module_mat ty nr nc) = (\\<cdot>\\<^sub>m)\"\n  unfolding module_mat_def by auto\n\nlemma index_zero_mat[simp]: \"i < nr \\<Longrightarrow> j < nc \\<Longrightarrow> 0\\<^sub>m nr nc $$ (i,j) = 0\"\n  \"dim_row (0\\<^sub>m nr nc) = nr\" \"dim_col (0\\<^sub>m nr nc) = nc\"\n  unfolding zero_mat_def by auto\n\nlemma index_one_mat[simp]: \"i < n \\<Longrightarrow> j < n \\<Longrightarrow> 1\\<^sub>m n $$ (i,j) = (if i = j then 1 else 0)\"\n  \"dim_row (1\\<^sub>m n) = n\" \"dim_col (1\\<^sub>m n) = n\"\n  unfolding one_mat_def by auto\n\nlemma index_add_mat[simp]:\n  \"i < dim_row B \\<Longrightarrow> j < dim_col B \\<Longrightarrow> (A + B) $$ (i,j) = A $$ (i,j) + B $$ (i,j)\"\n  \"dim_row (A + B) = dim_row B\" \"dim_col (A + B) = dim_col B\"\n  unfolding plus_mat_def by auto\n\nlemma index_minus_mat[simp]:\n  \"i < dim_row B \\<Longrightarrow> j < dim_col B \\<Longrightarrow> (A - B) $$ (i,j) = A $$ (i,j) - B $$ (i,j)\"\n  \"dim_row (A - B) = dim_row B\" \"dim_col (A - B) = dim_col B\"\n  unfolding minus_mat_def by auto\n\nlemma index_map_mat[simp]:\n  \"i < dim_row A \\<Longrightarrow> j < dim_col A \\<Longrightarrow> map_mat f A $$ (i,j) = f (A $$ (i,j))\"\n  \"dim_row (map_mat f A) = dim_row A\" \"dim_col (map_mat f A) = dim_col A\"\n  unfolding map_mat_def by auto\n\nlemma index_smult_mat[simp]:\n  \"i < dim_row A \\<Longrightarrow> j < dim_col A \\<Longrightarrow> (a \\<cdot>\\<^sub>m A) $$ (i,j) = a * A $$ (i,j)\"\n  \"dim_row (a \\<cdot>\\<^sub>m A) = dim_row A\" \"dim_col (a \\<cdot>\\<^sub>m A) = dim_col A\"\n  unfolding smult_mat_def by auto\n\nlemma index_uminus_mat[simp]:\n  \"i < dim_row A \\<Longrightarrow> j < dim_col A \\<Longrightarrow> (- A) $$ (i,j) = - (A $$ (i,j))\"\n  \"dim_row (- A) = dim_row A\" \"dim_col (- A) = dim_col A\"\n  unfolding uminus_mat_def by auto\n\nlemma index_transpose_mat[simp]:\n  \"i < dim_col A \\<Longrightarrow> j < dim_row A \\<Longrightarrow> transpose_mat A $$ (i,j) = A $$ (j,i)\"\n  \"dim_row (transpose_mat A) = dim_col A\" \"dim_col (transpose_mat A) = dim_row A\"\n  unfolding transpose_mat_def by auto\n\nlemma index_mult_mat[simp]:\n  \"i < dim_row A \\<Longrightarrow> j < dim_col B \\<Longrightarrow> (A * B) $$ (i,j) = row A i \\<bullet> col B j\"\n  \"dim_row (A * B) = dim_row A\" \"dim_col (A * B) = dim_col B\"\n  by (auto simp: times_mat_def)\n\nlemma dim_mult_mat_vec[simp]: \"dim_vec (A *\\<^sub>v v) = dim_row A\"\n  by (auto simp: mult_mat_vec_def)\n\nlemma index_mult_mat_vec[simp]: \"i < dim_row A \\<Longrightarrow> (A *\\<^sub>v v) $ i = row A i \\<bullet> v\"\n  by (auto simp: mult_mat_vec_def)\n\nlemma index_row[simp]:\n  \"i < dim_row A \\<Longrightarrow> j < dim_col A \\<Longrightarrow> row A i $ j = A $$ (i,j)\"\n  \"dim_vec (row A i) = dim_col A\"\n  by (auto simp: row_def)\n\nlemma index_col[simp]: \"i < dim_row A \\<Longrightarrow> j < dim_col A \\<Longrightarrow> col A j $ i = A $$ (i,j)\"\n  by (auto simp: col_def)\n\nlemma upper_triangular_one[simp]: \"upper_triangular (1\\<^sub>m n)\"\n  by (rule, auto)\n\nlemma upper_triangular_zero[simp]: \"upper_triangular (0\\<^sub>m n n)\"\n  by (rule, auto)\n\nlemma mat_row_carrierI[intro,simp]: \"mat\\<^sub>r nr nc r \\<in> carrier_mat nr nc\"\n  by (unfold carrier_mat_def carrier_vec_def, auto)\n\nlemma eq_rowI: assumes rows: \"\\<And> i. i < dim_row B \\<Longrightarrow> row A i = row B i\"\n  and dims: \"dim_row A = dim_row B\" \"dim_col A = dim_col B\"\n  shows \"A = B\"\nproof (rule eq_matI[OF _ dims])\n  fix i j\n  assume i: \"i < dim_row B\" and j: \"j < dim_col B\"\n  from rows[OF i] have id: \"row A i $ j = row B i $ j\" by simp\n  show \"A $$ (i, j) = B $$ (i, j)\"\n    using index_row(1)[OF i j, folded id] index_row(1)[of i A j] i j dims\n    by auto\nqed\n\nlemma row_mat[simp]: \"i < nr \\<Longrightarrow> row (mat nr nc f) i = vec nc (\\<lambda> j. f (i,j))\"\n  by auto\n\nlemma col_mat[simp]: \"j < nc \\<Longrightarrow> col (mat nr nc f) j = vec nr (\\<lambda> i. f (i,j))\"\n  by auto\n\nlemma zero_carrier_mat[simp]: \"0\\<^sub>m nr nc \\<in> carrier_mat nr nc\"\n  unfolding carrier_mat_def by auto\n\nlemma smult_carrier_mat[simp]:\n  \"A \\<in> carrier_mat nr nc \\<Longrightarrow> k \\<cdot>\\<^sub>m A \\<in> carrier_mat nr nc\"\n  unfolding carrier_mat_def by auto\n\nlemma add_carrier_mat[simp]:\n  \"B \\<in> carrier_mat nr nc \\<Longrightarrow> A + B \\<in> carrier_mat nr nc\"\n  unfolding carrier_mat_def by force\n\nlemma one_carrier_mat[simp]: \"1\\<^sub>m n \\<in> carrier_mat n n\"\n  unfolding carrier_mat_def by auto\n\nlemma uminus_carrier_mat:\n  \"A \\<in> carrier_mat nr nc \\<Longrightarrow> (- A \\<in> carrier_mat nr nc)\"\n  unfolding carrier_mat_def by auto\n\nlemma uminus_carrier_iff_mat[simp]:\n  \"(- A \\<in> carrier_mat nr nc) = (A \\<in> carrier_mat nr nc)\"\n  unfolding carrier_mat_def by auto\n\nlemma minus_carrier_mat:\n  \"B \\<in> carrier_mat nr nc \\<Longrightarrow> (A - B \\<in> carrier_mat nr nc)\"\n  unfolding carrier_mat_def by auto\n\nlemma transpose_carrier_mat[simp]: \"(transpose_mat A \\<in> carrier_mat nc nr) = (A \\<in> carrier_mat nr nc)\"\n  unfolding carrier_mat_def by auto\n\nlemma row_carrier_vec[simp]: \"i < nr \\<Longrightarrow> A \\<in> carrier_mat nr nc \\<Longrightarrow> row A i \\<in> carrier_vec nc\"\n  unfolding carrier_vec_def by auto\n\nlemma col_carrier_vec[simp]: \"j < nc \\<Longrightarrow> A \\<in> carrier_mat nr nc \\<Longrightarrow> col A j \\<in> carrier_vec nr\"\n  unfolding carrier_vec_def by auto\n\nlemma mult_carrier_mat[simp]:\n  \"A \\<in> carrier_mat nr n \\<Longrightarrow> B \\<in> carrier_mat n nc \\<Longrightarrow> A * B \\<in> carrier_mat nr nc\"\n  unfolding carrier_mat_def by auto\n\nlemma mult_mat_vec_carrier[simp]:\n  \"A \\<in> carrier_mat nr n \\<Longrightarrow> v \\<in> carrier_vec n \\<Longrightarrow> A *\\<^sub>v v \\<in> carrier_vec nr\"\n  unfolding carrier_mat_def carrier_vec_def by auto\n\n\nlemma comm_add_mat[ac_simps]:\n  \"(A :: 'a :: comm_monoid_add mat) \\<in> carrier_mat nr nc \\<Longrightarrow> B \\<in> carrier_mat nr nc \\<Longrightarrow> A + B = B + A\"\n  by (intro eq_matI, auto simp: ac_simps)\n\n\nlemma minus_r_inv_mat[simp]:\n  \"(A :: 'a :: group_add mat) \\<in> carrier_mat nr nc \\<Longrightarrow> (A - A) = 0\\<^sub>m nr nc\"\n  by (intro eq_matI, auto)\n\nlemma uminus_l_inv_mat[simp]:\n  \"(A :: 'a :: group_add mat) \\<in> carrier_mat nr nc \\<Longrightarrow> (- A + A) = 0\\<^sub>m nr nc\"\n  by (intro eq_matI, auto)\n\nlemma add_inv_exists_mat:\n  \"(A :: 'a :: group_add mat) \\<in> carrier_mat nr nc \\<Longrightarrow> \\<exists> B \\<in> carrier_mat nr nc. B + A = 0\\<^sub>m nr nc \\<and> A + B = 0\\<^sub>m nr nc\"\n  by (intro bexI[of _ \"- A\"], auto)\n\nlemma assoc_add_mat[simp]:\n  \"(A :: 'a :: monoid_add mat) \\<in> carrier_mat nr nc \\<Longrightarrow> B \\<in> carrier_mat nr nc \\<Longrightarrow> C \\<in> carrier_mat nr nc\n  \\<Longrightarrow> (A + B) + C = A + (B + C)\"\n  by (intro eq_matI, auto simp: ac_simps)\n\nlemma uminus_add_mat: fixes A :: \"'a :: group_add mat\"\n  assumes \"A \\<in> carrier_mat nr nc\"\n  and \"B \\<in> carrier_mat nr nc\"\n  shows \"- (A + B) = - B + - A\"\n  by (intro eq_matI, insert assms, auto simp: minus_add)\n\nlemma transpose_transpose[simp]:\n  \"transpose_mat (transpose_mat A) = A\"\n  by (intro eq_matI, auto)\n\nlemma transpose_one[simp]: \"transpose_mat (1\\<^sub>m n) = (1\\<^sub>m n)\"\n  by auto\n\nlemma row_transpose[simp]:\n  \"j < dim_col A \\<Longrightarrow> row (transpose_mat A) j = col A j\"\n  unfolding row_def col_def\n  by (intro eq_vecI, auto)\n\nlemma col_transpose[simp]:\n  \"i < dim_row A \\<Longrightarrow> col (transpose_mat A) i = row A i\"\n  unfolding row_def col_def\n  by (intro eq_vecI, auto)\n\nlemma row_zero[simp]:\n  \"i < nr \\<Longrightarrow> row (0\\<^sub>m nr nc) i = 0\\<^sub>v nc\"\n   by (intro eq_vecI, auto)\n\nlemma col_zero[simp]:\n  \"j < nc \\<Longrightarrow> col (0\\<^sub>m nr nc) j = 0\\<^sub>v nr\"\n   by (intro eq_vecI, auto)\n\nlemma row_one[simp]:\n  \"i < n \\<Longrightarrow> row (1\\<^sub>m n) i = unit_vec n i\"\n  by (intro eq_vecI, auto)\n\nlemma col_one[simp]:\n  \"j < n \\<Longrightarrow> col (1\\<^sub>m n) j = unit_vec n j\"\n  by (intro eq_vecI, auto)\n\nlemma transpose_add: \"A \\<in> carrier_mat nr nc \\<Longrightarrow> B \\<in> carrier_mat nr nc\n  \\<Longrightarrow> transpose_mat (A + B) = transpose_mat A + transpose_mat B\"\n  by (intro eq_matI, auto)\n\nlemma transpose_minus: \"A \\<in> carrier_mat nr nc \\<Longrightarrow> B \\<in> carrier_mat nr nc\n  \\<Longrightarrow> transpose_mat (A - B) = transpose_mat A - transpose_mat B\"\n  by (intro eq_matI, auto)\n\nlemma transpose_uminus: \"A \\<in> carrier_mat nr nc \\<Longrightarrow> transpose_mat (- A) = - (transpose_mat A)\"\n  by (intro eq_matI, auto)\n\nlemma row_add[simp]:\n  \"A \\<in> carrier_mat nr nc \\<Longrightarrow> B \\<in> carrier_mat nr nc \\<Longrightarrow> i < nr\n  \\<Longrightarrow> row (A + B) i = row A i + row B i\"\n  \"i < dim_row A \\<Longrightarrow> dim_row B = dim_row A \\<Longrightarrow> dim_col B = dim_col A \\<Longrightarrow> row (A + B) i = row A i + row B i\"\n  by (rule eq_vecI, auto)\n\nlemma col_add[simp]:\n  \"A \\<in> carrier_mat nr nc \\<Longrightarrow> B \\<in> carrier_mat nr nc \\<Longrightarrow> j < nc\n  \\<Longrightarrow> col (A + B) j = col A j + col B j\"\n  by (rule eq_vecI, auto)\n\nlemma row_mult[simp]: assumes m: \"A \\<in> carrier_mat nr n\" \"B \\<in> carrier_mat n nc\"\n  and i: \"i < nr\"\n  shows \"row (A * B) i = vec nc (\\<lambda> j. row A i \\<bullet> col B j)\"\n  by (rule eq_vecI, insert m i, auto)\n\nlemma col_mult[simp]: assumes m: \"A \\<in> carrier_mat nr n\" \"B \\<in> carrier_mat n nc\"\n  and j: \"j < nc\"\n  shows \"col (A * B) j = vec nr (\\<lambda> i. row A i \\<bullet> col B j)\"\n  by (rule eq_vecI, insert m j, auto)\n\nlemma transpose_mult:\n  \"(A :: 'a :: comm_semiring_0 mat) \\<in> carrier_mat nr n \\<Longrightarrow> B \\<in> carrier_mat n nc\n  \\<Longrightarrow> transpose_mat (A * B) = transpose_mat B * transpose_mat A\"\n  by (intro eq_matI, auto simp: comm_scalar_prod[of _ n])\n\nlemma left_add_zero_mat[simp]:\n  \"(A :: 'a :: monoid_add mat) \\<in> carrier_mat nr nc  \\<Longrightarrow> 0\\<^sub>m nr nc + A = A\"\n  by (intro eq_matI, auto)\n\nlemma add_uminus_minus_mat: \"A \\<in> carrier_mat nr nc \\<Longrightarrow> B \\<in> carrier_mat nr nc \\<Longrightarrow> \n  A + (- B) = A - (B :: 'a :: group_add mat)\" \n  by (intro eq_matI, auto)\n\nlemma right_add_zero_mat[simp]: \"A \\<in> carrier_mat nr nc \\<Longrightarrow> \n  A + 0\\<^sub>m nr nc = (A :: 'a :: monoid_add mat)\" \n  by (intro eq_matI, auto)\n\nlemma left_mult_zero_mat:\n  \"A \\<in> carrier_mat n nc \\<Longrightarrow> 0\\<^sub>m nr n * A = 0\\<^sub>m nr nc\"\n  by (intro eq_matI, auto)\n\nlemma left_mult_zero_mat'[simp]: \"dim_row A = n \\<Longrightarrow> 0\\<^sub>m nr n * A = 0\\<^sub>m nr (dim_col A)\"\n  by (rule left_mult_zero_mat, unfold carrier_mat_def, simp)\n\nlemma right_mult_zero_mat:\n  \"A \\<in> carrier_mat nr n \\<Longrightarrow> A * 0\\<^sub>m n nc = 0\\<^sub>m nr nc\"\n  by (intro eq_matI, auto)\n\nlemma right_mult_zero_mat'[simp]: \"dim_col A = n \\<Longrightarrow> A * 0\\<^sub>m n nc = 0\\<^sub>m (dim_row A) nc\"\n  by (rule right_mult_zero_mat, unfold carrier_mat_def, simp)\n\nlemma left_mult_one_mat:\n  \"(A :: 'a :: semiring_1 mat) \\<in> carrier_mat nr nc \\<Longrightarrow> 1\\<^sub>m nr * A = A\"\n  by (intro eq_matI, auto)\n\nlemma left_mult_one_mat'[simp]: \"dim_row (A :: 'a :: semiring_1 mat) = n \\<Longrightarrow> 1\\<^sub>m n * A = A\"\n  by (rule left_mult_one_mat, unfold carrier_mat_def, simp)\n\nlemma right_mult_one_mat:\n  \"(A :: 'a :: semiring_1 mat) \\<in> carrier_mat nr nc \\<Longrightarrow> A * 1\\<^sub>m nc = A\"\n  by (intro eq_matI, auto)\n\nlemma right_mult_one_mat'[simp]: \"dim_col (A :: 'a :: semiring_1 mat) = n \\<Longrightarrow> A * 1\\<^sub>m n = A\"\n  by (rule right_mult_one_mat, unfold carrier_mat_def, simp)\n\nlemma one_mult_mat_vec[simp]:\n  \"(v :: 'a :: semiring_1 vec) \\<in> carrier_vec n \\<Longrightarrow> 1\\<^sub>m n *\\<^sub>v v = v\"\n  by (intro eq_vecI, auto)\n\nlemma minus_add_uminus_mat: fixes A :: \"'a :: group_add mat\"\n  shows \"A \\<in> carrier_mat nr nc \\<Longrightarrow> B \\<in> carrier_mat nr nc \\<Longrightarrow>\n  A - B = A + (- B)\"\n  by (intro eq_matI, auto)\n\nlemma add_mult_distrib_mat[algebra_simps]: assumes m: \"A \\<in> carrier_mat nr n\"\n  \"B \\<in> carrier_mat nr n\" \"C \\<in> carrier_mat n nc\"\n  shows \"(A + B) * C = A * C + B * C\"\n  using m by (intro eq_matI, auto simp: add_scalar_prod_distrib[of _ n])\n\nlemma mult_add_distrib_mat[algebra_simps]: assumes m: \"A \\<in> carrier_mat nr n\"\n  \"B \\<in> carrier_mat n nc\" \"C \\<in> carrier_mat n nc\"\n  shows \"A * (B + C) = A * B + A * C\"\n  using m by (intro eq_matI, auto simp: scalar_prod_add_distrib[of _ n])\n\nlemma add_mult_distrib_mat_vec[algebra_simps]: assumes m: \"A \\<in> carrier_mat nr nc\"\n  \"B \\<in> carrier_mat nr nc\" \"v \\<in> carrier_vec nc\"\n  shows \"(A + B) *\\<^sub>v v = A *\\<^sub>v v + B *\\<^sub>v v\"\n  using m by (intro eq_vecI, auto intro!: add_scalar_prod_distrib)\n\nlemma mult_add_distrib_mat_vec[algebra_simps]: assumes m: \"A \\<in> carrier_mat nr nc\"\n  \"v\\<^sub>1 \\<in> carrier_vec nc\" \"v\\<^sub>2 \\<in> carrier_vec nc\"\n  shows \"A *\\<^sub>v (v\\<^sub>1 + v\\<^sub>2) = A *\\<^sub>v v\\<^sub>1 + A *\\<^sub>v v\\<^sub>2\"\n  using m by (intro eq_vecI, auto simp: scalar_prod_add_distrib[of _ nc])\n\nlemma mult_mat_vec:\n  assumes m: \"(A::'a::field mat) \\<in> carrier_mat nr nc\" and v: \"v \\<in> carrier_vec nc\"\n  shows \"A *\\<^sub>v (k \\<cdot>\\<^sub>v v) = k \\<cdot>\\<^sub>v (A *\\<^sub>v v)\" (is \"?l = ?r\")\nproof\n  have nr: \"dim_vec ?l = nr\" using m v by auto\n  also have \"... = dim_vec ?r\" using m v by auto\n  finally show \"dim_vec ?l = dim_vec ?r\".\n\n  show \"\\<And>i. i < dim_vec ?r \\<Longrightarrow> ?l $ i = ?r $ i\"\n  proof -\n    fix i assume \"i < dim_vec ?r\"\n    hence i: \"i < dim_row A\" using nr m by auto\n    hence i2: \"i < dim_vec (A *\\<^sub>v v)\" using m by auto\n    show \"?l $ i = ?r $ i\"\n    apply (subst (1) mult_mat_vec_def)\n    apply (subst (2) smult_vec_def)\n    unfolding index_vec[OF i] index_vec[OF i2]\n    unfolding mult_mat_vec_def smult_vec_def\n    unfolding scalar_prod_def index_vec[OF i]\n    by (simp add: mult.left_commute sum_distrib_left)\n  qed\nqed\n\nlemma assoc_scalar_prod: assumes *: \"v\\<^sub>1 \\<in> carrier_vec nr\" \"A \\<in> carrier_mat nr nc\" \"v\\<^sub>2 \\<in> carrier_vec nc\"\n  shows \"vec nc (\\<lambda>j. v\\<^sub>1 \\<bullet> col A j) \\<bullet> v\\<^sub>2 = v\\<^sub>1 \\<bullet> vec nr (\\<lambda>i. row A i \\<bullet> v\\<^sub>2)\"\nproof -\n  have \"vec nc (\\<lambda>j. v\\<^sub>1 \\<bullet> col A j) \\<bullet> v\\<^sub>2 = (\\<Sum>i\\<in>{0..<nc}. vec nc (\\<lambda>j. \\<Sum>k\\<in>{0..<nr}. v\\<^sub>1 $ k * col A j $ k) $ i * v\\<^sub>2 $ i)\"\n    unfolding scalar_prod_def using * by auto\n  also have \"\\<dots> = (\\<Sum>i\\<in>{0..<nc}. (\\<Sum>k\\<in>{0..<nr}. v\\<^sub>1 $ k * col A i $ k) * v\\<^sub>2 $ i)\"\n    by (rule sum.cong, auto)\n  also have \"\\<dots> = (\\<Sum>i\\<in>{0..<nc}. (\\<Sum>k\\<in>{0..<nr}. v\\<^sub>1 $ k * col A i $ k * v\\<^sub>2 $ i))\"\n    unfolding sum_distrib_right ..\n  also have \"\\<dots> = (\\<Sum>k\\<in>{0..<nr}. (\\<Sum>i\\<in>{0..<nc}. v\\<^sub>1 $ k * col A i $ k * v\\<^sub>2 $ i))\"\n    by (rule sum.swap)\n  also have \"\\<dots> = (\\<Sum>k\\<in>{0..<nr}. (\\<Sum>i\\<in>{0..<nc}. v\\<^sub>1 $ k * (col A i $ k * v\\<^sub>2 $ i)))\"\n    by (simp add: ac_simps)\n  also have \"\\<dots> = (\\<Sum>k\\<in>{0..<nr}. v\\<^sub>1 $ k * (\\<Sum>i\\<in>{0..<nc}. col A i $ k * v\\<^sub>2 $ i))\"\n    unfolding sum_distrib_left ..\n  also have \"\\<dots> = (\\<Sum>k\\<in>{0..<nr}. v\\<^sub>1 $ k * vec nr (\\<lambda>k. \\<Sum>i\\<in>{0..<nc}. row A k $ i * v\\<^sub>2 $ i) $ k)\"\n    using * by auto\n  also have \"\\<dots> = v\\<^sub>1 \\<bullet> vec nr (\\<lambda>i. row A i \\<bullet> v\\<^sub>2)\" unfolding scalar_prod_def using * by simp\n  finally show ?thesis .\nqed\n\nlemma assoc_mult_mat[simp]:\n  \"A \\<in> carrier_mat n\\<^sub>1 n\\<^sub>2 \\<Longrightarrow> B \\<in> carrier_mat n\\<^sub>2 n\\<^sub>3 \\<Longrightarrow> C \\<in> carrier_mat n\\<^sub>3 n\\<^sub>4\n  \\<Longrightarrow> (A * B) * C = A * (B * C)\"\n  by (intro eq_matI, auto simp: assoc_scalar_prod)\n\nlemma assoc_mult_mat_vec[simp]:\n  \"A \\<in> carrier_mat n\\<^sub>1 n\\<^sub>2 \\<Longrightarrow> B \\<in> carrier_mat n\\<^sub>2 n\\<^sub>3 \\<Longrightarrow> v \\<in> carrier_vec n\\<^sub>3\n  \\<Longrightarrow> (A * B) *\\<^sub>v v = A *\\<^sub>v (B *\\<^sub>v v)\"\n  by (intro eq_vecI, auto simp add: mult_mat_vec_def assoc_scalar_prod)\n\nlemma comm_monoid_mat: \"comm_monoid (monoid_mat TYPE('a :: comm_monoid_add) nr nc)\"\n  by (unfold_locales, auto simp: monoid_mat_def ac_simps)\n\nlemma comm_group_mat: \"comm_group (monoid_mat TYPE('a :: ab_group_add) nr nc)\"\n  by (unfold_locales, insert add_inv_exists_mat, auto simp: monoid_mat_def ac_simps Units_def)\n\nlemma semiring_mat: \"semiring (ring_mat TYPE('a :: semiring_1) n b)\"\n  by (unfold_locales, auto simp: ring_mat_def algebra_simps)\n\nlemma ring_mat: \"ring (ring_mat TYPE('a :: comm_ring_1) n b)\"\n  by (unfold_locales, insert add_inv_exists_mat, auto simp: ring_mat_def algebra_simps Units_def)\n\nlemma abelian_group_mat: \"abelian_group (module_mat TYPE('a :: comm_ring_1) nr nc)\"\n  by (unfold_locales, insert add_inv_exists_mat, auto simp: module_mat_def Units_def)\n\nlemma row_smult[simp]: assumes i: \"i < dim_row A\"\n  shows \"row (k \\<cdot>\\<^sub>m A) i = k \\<cdot>\\<^sub>v (row A i)\"\n  by (rule eq_vecI, insert i, auto)\n\nlemma col_smult[simp]: assumes i: \"i < dim_col A\"\n  shows \"col (k \\<cdot>\\<^sub>m A) i = k \\<cdot>\\<^sub>v (col A i)\"\n  by (rule eq_vecI, insert i, auto)\n\nlemma row_uminus[simp]: assumes i: \"i < dim_row A\"\n  shows \"row (- A) i = - (row A i)\"\n  by (rule eq_vecI, insert i, auto)\n\nlemma scalar_prod_uminus_left[simp]: assumes dim: \"dim_vec v = dim_vec (w :: 'a :: ring vec)\"\n  shows \"- v \\<bullet> w = - (v \\<bullet> w)\"\n  unfolding scalar_prod_def dim[symmetric]\n  by (subst sum_negf[symmetric], rule sum.cong, auto)\n\nlemma col_uminus[simp]: assumes i: \"i < dim_col A\"\n  shows \"col (- A) i = - (col A i)\"\n  by (rule eq_vecI, insert i, auto)\n\nlemma scalar_prod_uminus_right[simp]: assumes dim: \"dim_vec v = dim_vec (w :: 'a :: ring vec)\"\n  shows \"v \\<bullet> - w = - (v \\<bullet> w)\"\n  unfolding scalar_prod_def dim\n  by (subst sum_negf[symmetric], rule sum.cong, auto)\n\ncontext fixes A B :: \"'a :: ring mat\"\n  assumes dim: \"dim_col A = dim_row B\"\nbegin\nlemma uminus_mult_left_mat[simp]: \"(- A * B) = - (A * B)\"\n  by (intro eq_matI, insert dim, auto)\n\nlemma uminus_mult_right_mat[simp]: \"(A * - B) = - (A * B)\"\n  by (intro eq_matI, insert dim, auto)\nend\n\nlemma minus_mult_distrib_mat[algebra_simps]: fixes A :: \"'a :: ring mat\"\n  assumes m: \"A \\<in> carrier_mat nr n\" \"B \\<in> carrier_mat nr n\" \"C \\<in> carrier_mat n nc\"\n  shows \"(A - B) * C = A * C - B * C\"\n  unfolding minus_add_uminus_mat[OF m(1,2)]\n    add_mult_distrib_mat[OF m(1) uminus_carrier_mat[OF m(2)] m(3)]\n  by (subst uminus_mult_left_mat, insert m, auto)\n\nlemma minus_mult_distrib_mat_vec[algebra_simps]: assumes A: \"(A :: 'a :: ring mat) \\<in> carrier_mat nr nc\"\n  and B: \"B \\<in> carrier_mat nr nc\"\n  and v: \"v \\<in> carrier_vec nc\"\nshows \"(A - B) *\\<^sub>v v = A *\\<^sub>v v - B *\\<^sub>v v\"\n  unfolding minus_add_uminus_mat[OF A B]\n  by (subst add_mult_distrib_mat_vec[OF A _ v], insert A B v, auto)\n\nlemma mult_minus_distrib_mat_vec[algebra_simps]: assumes A: \"(A :: 'a :: ring mat) \\<in> carrier_mat nr nc\"\n  and v: \"v \\<in> carrier_vec nc\"\n  and w: \"w \\<in> carrier_vec nc\"\nshows \"A *\\<^sub>v (v - w) = A *\\<^sub>v v - A *\\<^sub>v w\"\n  unfolding minus_add_uminus_vec[OF v w]\n  by (subst mult_add_distrib_mat_vec[OF A], insert A v w, auto)\n\nlemma mult_minus_distrib_mat[algebra_simps]: fixes A :: \"'a :: ring mat\"\n  assumes m: \"A \\<in> carrier_mat nr n\" \"B \\<in> carrier_mat n nc\" \"C \\<in> carrier_mat n nc\"\n  shows \"A * (B - C) = A * B - A * C\"\n  unfolding minus_add_uminus_mat[OF m(2,3)]\n    mult_add_distrib_mat[OF m(1) m(2) uminus_carrier_mat[OF m(3)]]\n  by (subst uminus_mult_right_mat, insert m, auto)\n\n\n\nlemma uminus_zero_vec_eq: assumes v: \"(v :: 'a :: group_add vec) \\<in> carrier_vec n\"\n  shows \"(- v = 0\\<^sub>v n) = (v = 0\\<^sub>v n)\"\nproof\n  assume z: \"- v = 0\\<^sub>v n\"\n  {\n    fix i\n    assume i: \"i < n\"\n    have \"v $ i = - (- (v $ i))\" by simp\n    also have \"- (v $ i) = 0\" using arg_cong[OF z, of \"\\<lambda> v. v $ i\"] i v by auto\n    also have \"- 0 = (0 :: 'a)\" by simp\n    finally have \"v $ i = 0\" .\n  }\n  thus \"v = 0\\<^sub>v n\" using v\n    by (intro eq_vecI, auto)\nqed auto\n\nlemma map_carrier_mat[simp]:\n  \"(map_mat f A \\<in> carrier_mat nr nc) = (A \\<in> carrier_mat nr nc)\"\n  unfolding carrier_mat_def by auto\n\nlemma col_map_mat[simp]:\n  assumes \"j < dim_col A\" shows \"col (map_mat f A) j = map_vec f (col A j)\"\n  unfolding map_mat_def map_vec_def using assms by auto\n\nlemma scalar_vec_one[simp]: \"1 \\<cdot>\\<^sub>v (v :: 'a :: semiring_1 vec) = v\"\n  by (rule eq_vecI, auto)\n\nlemma scalar_prod_smult_right[simp]:\n  \"dim_vec w = dim_vec v \\<Longrightarrow> w \\<bullet> (k \\<cdot>\\<^sub>v v) = (k :: 'a :: comm_semiring_0) * (w \\<bullet> v)\"\n  unfolding scalar_prod_def sum_distrib_left\n  by (auto intro: sum.cong simp: ac_simps)\n\n\n\nlemma mult_smult_distrib: assumes A: \"A \\<in> carrier_mat nr n\" and B: \"B \\<in> carrier_mat n nc\"\n  shows \"A * (k \\<cdot>\\<^sub>m B) = (k :: 'a :: comm_semiring_0) \\<cdot>\\<^sub>m (A * B)\"\n  by (rule eq_matI, insert A B, auto)\n\nlemma add_smult_distrib_left_mat: assumes \"A \\<in> carrier_mat nr nc\" \"B \\<in> carrier_mat nr nc\"\n  shows \"k \\<cdot>\\<^sub>m (A + B) = (k :: 'a :: semiring) \\<cdot>\\<^sub>m A + k \\<cdot>\\<^sub>m B\"\n  by (rule eq_matI, insert assms, auto simp: field_simps)\n\nlemma add_smult_distrib_right_mat: assumes \"A \\<in> carrier_mat nr nc\"\n  shows \"(k + l) \\<cdot>\\<^sub>m A = (k :: 'a :: semiring) \\<cdot>\\<^sub>m A + l \\<cdot>\\<^sub>m A\"\n  by (rule eq_matI, insert assms, auto simp: field_simps)\n\nlemma mult_smult_assoc_mat: assumes A: \"A \\<in> carrier_mat nr n\" and B: \"B \\<in> carrier_mat n nc\"\n  shows \"(k \\<cdot>\\<^sub>m A) * B = (k :: 'a :: comm_semiring_0) \\<cdot>\\<^sub>m (A * B)\"\n  by (rule eq_matI, insert A B, auto)\n\ndefinition similar_mat_wit :: \"'a :: semiring_1 mat \\<Rightarrow> 'a mat \\<Rightarrow> 'a mat \\<Rightarrow> 'a mat \\<Rightarrow> bool\" where\n  \"similar_mat_wit A B P Q = (let n = dim_row A in {A,B,P,Q} \\<subseteq> carrier_mat n n \\<and> P * Q = 1\\<^sub>m n \\<and> Q * P = 1\\<^sub>m n \\<and>\n    A = P * B * Q)\"\n\ndefinition similar_mat :: \"'a :: semiring_1 mat \\<Rightarrow> 'a mat \\<Rightarrow> bool\" where\n  \"similar_mat A B = (\\<exists> P Q. similar_mat_wit A B P Q)\"\n\nlemma similar_matD: assumes \"similar_mat A B\"\n  shows \"\\<exists> n P Q. {A,B,P,Q} \\<subseteq> carrier_mat n n \\<and> P * Q = 1\\<^sub>m n \\<and> Q * P = 1\\<^sub>m n \\<and> A = P * B * Q\"\n  using assms unfolding similar_mat_def similar_mat_wit_def[abs_def] Let_def by blast\n\nlemma similar_matI: assumes \"{A,B,P,Q} \\<subseteq> carrier_mat n n\" \"P * Q = 1\\<^sub>m n\" \"Q * P = 1\\<^sub>m n\" \"A = P * B * Q\"\n  shows \"similar_mat A B\" unfolding similar_mat_def\n  by (rule exI[of _ P], rule exI[of _ Q], unfold similar_mat_wit_def Let_def, insert assms, auto)\n\nfun pow_mat :: \"'a :: semiring_1 mat \\<Rightarrow> nat \\<Rightarrow> 'a mat\" (infixr \"^\\<^sub>m\" 75) where\n  \"A ^\\<^sub>m 0 = 1\\<^sub>m (dim_row A)\"\n| \"A ^\\<^sub>m (Suc k) = A ^\\<^sub>m k * A\"\n\nlemma pow_mat_dim[simp]:\n  \"dim_row (A ^\\<^sub>m k) = dim_row A\"\n  \"dim_col (A ^\\<^sub>m k) = (if k = 0 then dim_row A else dim_col A)\"\n  by (induct k, auto)\n\nlemma pow_mat_dim_square[simp]:\n  \"A \\<in> carrier_mat n n \\<Longrightarrow> dim_row (A ^\\<^sub>m k) = n\"\n  \"A \\<in> carrier_mat n n \\<Longrightarrow> dim_col (A ^\\<^sub>m k) = n\"\n  by auto\n\nlemma pow_carrier_mat[simp]: \"A \\<in> carrier_mat n n \\<Longrightarrow> A ^\\<^sub>m k \\<in> carrier_mat n n\"\n  unfolding carrier_mat_def by auto\n\ndefinition diag_mat :: \"'a mat \\<Rightarrow> 'a list\" where\n  \"diag_mat A = map (\\<lambda> i. A $$ (i,i)) [0 ..< dim_row A]\"\n\nlemma prod_list_diag_prod: \"prod_list (diag_mat A) = (\\<Prod> i = 0 ..< dim_row A. A $$ (i,i))\"\n  unfolding diag_mat_def\n  by (subst prod.distinct_set_conv_list[symmetric], auto)\n\nlemma diag_mat_transpose[simp]: \"dim_row A = dim_col A \\<Longrightarrow>\n  diag_mat (transpose_mat A) = diag_mat A\" unfolding diag_mat_def by auto\n\nlemma diag_mat_zero[simp]: \"diag_mat (0\\<^sub>m n n) = replicate n 0\"\n  unfolding diag_mat_def\n  by (rule nth_equalityI, auto)\n\nlemma diag_mat_one[simp]: \"diag_mat (1\\<^sub>m n) = replicate n 1\"\n  unfolding diag_mat_def\n  by (rule nth_equalityI, auto)\n\nlemma pow_mat_ring_pow: assumes A: \"(A :: ('a :: semiring_1)mat) \\<in> carrier_mat n n\"\n  shows \"A ^\\<^sub>m k = A [^]\\<^bsub>ring_mat TYPE('a) n b\\<^esub> k\"\n  (is \"_ = A [^]\\<^bsub>?C\\<^esub> k\")\nproof -\n  interpret semiring ?C by (rule semiring_mat)\n  show ?thesis\n    by (induct k, insert A, auto simp: ring_mat_def nat_pow_def)\nqed\n\ndefinition diagonal_mat :: \"'a::zero mat \\<Rightarrow> bool\" where\n  \"diagonal_mat A \\<equiv> \\<forall>i<dim_row A. \\<forall>j<dim_col A. i \\<noteq> j \\<longrightarrow> A $$ (i,j) = 0\"\n\ndefinition (in comm_monoid_add) sum_mat :: \"'a mat \\<Rightarrow> 'a\" where\n  \"sum_mat A = sum (\\<lambda> ij. A $$ ij) ({0 ..< dim_row A} \\<times> {0 ..< dim_col A})\"\n\nlemma sum_mat_0[simp]: \"sum_mat (0\\<^sub>m nr nc) = (0 :: 'a :: comm_monoid_add)\"\n  unfolding sum_mat_def\n  by (rule sum.neutral, auto)\n\nlemma sum_mat_add: assumes A: \"(A :: 'a :: comm_monoid_add mat) \\<in> carrier_mat nr nc\" and B: \"B \\<in> carrier_mat nr nc\"\n  shows \"sum_mat (A + B) = sum_mat A + sum_mat B\"\nproof -\n  from A B have id: \"dim_row A = nr\" \"dim_row B = nr\" \"dim_col A = nc\" \"dim_col B = nc\"\n    by auto\n  show ?thesis unfolding sum_mat_def id\n    by (subst sum.distrib[symmetric], rule sum.cong, insert A B, auto)\nqed\n\nsubsection \\<open>Update Operators\\<close>\n\ndefinition update_vec :: \"'a vec \\<Rightarrow> nat \\<Rightarrow> 'a \\<Rightarrow> 'a vec\" (\"_ |\\<^sub>v _ \\<mapsto> _\" [60,61,62] 60)\n  where \"v |\\<^sub>v i \\<mapsto> a = vec (dim_vec v) (\\<lambda>i'. if i' = i then a else v $ i')\"\n\ndefinition update_mat :: \"'a mat \\<Rightarrow> nat \\<times> nat \\<Rightarrow> 'a \\<Rightarrow> 'a mat\" (\"_ |\\<^sub>m _ \\<mapsto> _\" [60,61,62] 60)\n  where \"A |\\<^sub>m ij \\<mapsto> a = mat (dim_row A) (dim_col A) (\\<lambda>ij'. if ij' = ij then a else A $$ ij')\"\n\nlemma dim_update_vec[simp]:\n  \"dim_vec (v |\\<^sub>v i \\<mapsto> a) = dim_vec v\" unfolding update_vec_def by simp\n\nlemma index_update_vec1[simp]:\n  assumes \"i < dim_vec v\" shows \"(v |\\<^sub>v i \\<mapsto> a) $ i = a\"\n  unfolding update_vec_def using assms by simp\n\nlemma index_update_vec2[simp]:\n  assumes \"i' \\<noteq> i\" shows \"(v |\\<^sub>v i \\<mapsto> a) $ i' = v $ i'\"\n  unfolding update_vec_def\n  using assms apply transfer unfolding mk_vec_def by auto\n\nlemma dim_update_mat[simp]:\n  \"dim_row (A |\\<^sub>m ij \\<mapsto> a) = dim_row A\"\n  \"dim_col (A |\\<^sub>m ij \\<mapsto> a) = dim_col A\" unfolding update_mat_def by simp+\n\nlemma index_update_mat1[simp]:\n  assumes \"i < dim_row A\" \"j < dim_col A\" shows \"(A |\\<^sub>m (i,j) \\<mapsto> a) $$ (i,j) = a\"\n  unfolding update_mat_def using assms by simp\n\nlemma index_update_mat2[simp]:\n  assumes i': \"i' < dim_row A\" and j': \"j' < dim_col A\" and neq: \"(i',j') \\<noteq> ij\"\n  shows \"(A |\\<^sub>m ij \\<mapsto> a) $$ (i',j') = A $$ (i',j')\"\n  unfolding update_mat_def using assms by auto\n\nsubsection \\<open>Block Vectors and Matrices\\<close>\n\ndefinition append_vec :: \"'a vec \\<Rightarrow> 'a vec \\<Rightarrow> 'a vec\" (infixr \"@\\<^sub>v\" 65) where\n  \"v @\\<^sub>v w \\<equiv> let n = dim_vec v; m = dim_vec w in\n    vec (n + m) (\\<lambda> i. if i < n then v $ i else w $ (i - n))\"\n\nlemma index_append_vec[simp]: \"i < dim_vec v + dim_vec w\n  \\<Longrightarrow> (v @\\<^sub>v w) $ i = (if i < dim_vec v then v $ i else w $ (i - dim_vec v))\"\n  \"dim_vec (v @\\<^sub>v w) = dim_vec v + dim_vec w\"\n  unfolding append_vec_def Let_def by auto\n\nlemma append_carrier_vec[simp,intro]:\n  \"v \\<in> carrier_vec n1 \\<Longrightarrow> w \\<in> carrier_vec n2 \\<Longrightarrow> v @\\<^sub>v w \\<in> carrier_vec (n1 + n2)\"\n  unfolding carrier_vec_def by auto\n\nlemma scalar_prod_append: assumes \"v1 \\<in> carrier_vec n1\" \"v2 \\<in> carrier_vec n2\"\n  \"w1 \\<in> carrier_vec n1\" \"w2 \\<in> carrier_vec n2\"\n  shows \"(v1 @\\<^sub>v v2) \\<bullet> (w1 @\\<^sub>v w2) = v1 \\<bullet> w1 + v2 \\<bullet> w2\"\nproof -\n  from assms have dim: \"dim_vec v1 = n1\" \"dim_vec v2 = n2\" \"dim_vec w1 = n1\" \"dim_vec w2 = n2\" by auto\n  have id: \"{0 ..< n1 + n2} = {0 ..< n1} \\<union> {n1 ..< n1 + n2}\" by auto\n  have id2: \"{n1 ..< n1 + n2} = (plus n1) ` {0 ..< n2}\"\n    by (simp add: ac_simps)\n  have \"(v1 @\\<^sub>v v2) \\<bullet> (w1 @\\<^sub>v w2) = (\\<Sum>i = 0..<n1. v1 $ i * w1 $ i) +\n    (\\<Sum>i = n1..<n1 + n2. v2 $ (i - n1) * w2 $ (i - n1))\"\n  unfolding scalar_prod_def\n    by (auto simp: dim id, subst sum.union_disjoint, insert assms, force+)\n  also have \"(\\<Sum>i = n1..<n1 + n2. v2 $ (i - n1) * w2 $ (i - n1))\n    = (\\<Sum>i = 0..< n2. v2 $ i * w2 $ i)\"\n    by (rule sum.reindex_cong [OF _ id2]) simp_all\n  finally show ?thesis by (simp, insert assms, auto simp: scalar_prod_def)\nqed\n\ndefinition \"vec_first v n \\<equiv> vec n (\\<lambda>i. v $ i)\"\ndefinition \"vec_last v n \\<equiv> vec n (\\<lambda>i. v $ (dim_vec v - n + i))\"\n\nlemma dim_vec_first[simp]: \"dim_vec (vec_first v n) = n\" unfolding vec_first_def by auto\nlemma dim_vec_last[simp]: \"dim_vec (vec_last v n) = n\" unfolding vec_last_def by auto\n\nlemma vec_first_carrier[simp]: \"vec_first v n \\<in> carrier_vec n\" by (rule carrier_vecI, auto)\nlemma vec_last_carrier[simp]: \"vec_last v n \\<in> carrier_vec n\" by (rule carrier_vecI, auto)\n\nlemma vec_first_last_append[simp]:\n  assumes \"v \\<in> carrier_vec (n+m)\" shows \"vec_first v n @\\<^sub>v vec_last v m = v\"\n  apply(rule) unfolding vec_first_def vec_last_def using assms by auto\n\nlemma append_vec_le: assumes \"v \\<in> carrier_vec n\" and w: \"w \\<in> carrier_vec n\" \n  shows \"v @\\<^sub>v v' \\<le> w @\\<^sub>v w' \\<longleftrightarrow> v \\<le> w \\<and> v' \\<le> w'\" \nproof -\n  {\n    fix i\n    assume *: \"\\<forall>i. (\\<not> i < n \\<longrightarrow> i < n + dim_vec w' \\<longrightarrow> v' $ (i - n) \\<le> w' $ (i - n))\"\n      and i: \"i < dim_vec w'\" \n    have \"v' $ i \\<le> w' $ i\" using *[rule_format, of \"n + i\"] i by auto\n  }\n  thus ?thesis using assms unfolding less_eq_vec_def by auto\nqed\n\nlemma all_vec_append: \"(\\<forall> x \\<in> carrier_vec (n + m). P x) \\<longleftrightarrow> (\\<forall> x1 \\<in> carrier_vec n. \\<forall> x2 \\<in> carrier_vec m. P (x1 @\\<^sub>v x2))\" \nproof (standard, force, intro ballI, goal_cases)\n  case (1 x)\n  have \"x = vec n (\\<lambda> i. x $ i) @\\<^sub>v vec m (\\<lambda> i. x $ (n + i))\" \n    by (rule eq_vecI, insert 1(2), auto)\n  hence \"P x = P (vec n (\\<lambda> i. x $ i) @\\<^sub>v vec m (\\<lambda> i. x $ (n + i)))\" by simp\n  also have \"\\<dots>\" using 1 by auto\n  finally show ?case .\nqed\n\n\n(* A B\n   C D *)\ndefinition four_block_mat :: \"'a mat \\<Rightarrow> 'a mat \\<Rightarrow> 'a mat \\<Rightarrow> 'a mat \\<Rightarrow> 'a mat\" where\n  \"four_block_mat A B C D =\n    (let nra = dim_row A; nrd = dim_row D;\n         nca = dim_col A; ncd = dim_col D\n       in\n    mat (nra + nrd) (nca + ncd) (\\<lambda> (i,j). if i < nra then\n      if j < nca then A $$ (i,j) else B $$ (i,j - nca)\n      else if j < nca then C $$ (i - nra, j) else D $$ (i - nra, j - nca)))\"\n\nlemma index_mat_four_block[simp]:\n  \"i < dim_row A + dim_row D \\<Longrightarrow> j < dim_col A + dim_col D \\<Longrightarrow> four_block_mat A B C D $$ (i,j)\n  = (if i < dim_row A then\n      if j < dim_col A then A $$ (i,j) else B $$ (i,j - dim_col A)\n      else if j < dim_col A then C $$ (i - dim_row A, j) else D $$ (i - dim_row A, j - dim_col A))\"\n  \"dim_row (four_block_mat A B C D) = dim_row A + dim_row D\"\n  \"dim_col (four_block_mat A B C D) = dim_col A + dim_col D\"\n  unfolding four_block_mat_def Let_def by auto\n\nlemma four_block_carrier_mat[simp]:\n  \"A \\<in> carrier_mat nr1 nc1 \\<Longrightarrow> D \\<in> carrier_mat nr2 nc2 \\<Longrightarrow>\n  four_block_mat A B C D \\<in> carrier_mat (nr1 + nr2) (nc1 + nc2)\"\n  unfolding carrier_mat_def by auto\n\nlemma cong_four_block_mat: \"A1 = B1 \\<Longrightarrow> A2 = B2 \\<Longrightarrow> A3 = B3 \\<Longrightarrow> A4 = B4 \\<Longrightarrow>\n  four_block_mat A1 A2 A3 A4 = four_block_mat B1 B2 B3 B4\" by auto\n\nlemma four_block_one_mat[simp]:\n  \"four_block_mat (1\\<^sub>m n1) (0\\<^sub>m n1 n2) (0\\<^sub>m n2 n1) (1\\<^sub>m n2) = 1\\<^sub>m (n1 + n2)\"\n  by (rule eq_matI, auto)\n\nlemma four_block_zero_mat[simp]:\n  \"four_block_mat (0\\<^sub>m nr1 nc1) (0\\<^sub>m nr1 nc2) (0\\<^sub>m nr2 nc1) (0\\<^sub>m nr2 nc2) = 0\\<^sub>m (nr1 + nr2) (nc1 + nc2)\"\n  by (rule eq_matI, auto)\n\nlemma row_four_block_mat:\n  assumes c: \"A \\<in> carrier_mat nr1 nc1\" \"B \\<in> carrier_mat nr1 nc2\"\n  \"C \\<in> carrier_mat nr2 nc1\" \"D \\<in> carrier_mat nr2 nc2\"\n  shows\n  \"i < nr1 \\<Longrightarrow> row (four_block_mat A B C D) i = row A i @\\<^sub>v row B i\" (is \"_ \\<Longrightarrow> ?AB\")\n  \"\\<not> i < nr1 \\<Longrightarrow> i < nr1 + nr2 \\<Longrightarrow> row (four_block_mat A B C D) i = row C (i - nr1) @\\<^sub>v row D (i - nr1)\"\n  (is \"_ \\<Longrightarrow> _ \\<Longrightarrow> ?CD\")\nproof -\n  assume i: \"i < nr1\"\n  show ?AB by (rule eq_vecI, insert i c, auto)\nnext\n  assume i: \"\\<not> i < nr1\" \"i < nr1 + nr2\"\n  show ?CD by (rule eq_vecI, insert i c, auto)\nqed\n\nlemma col_four_block_mat:\n  assumes c: \"A \\<in> carrier_mat nr1 nc1\" \"B \\<in> carrier_mat nr1 nc2\"\n  \"C \\<in> carrier_mat nr2 nc1\" \"D \\<in> carrier_mat nr2 nc2\"\n  shows\n  \"j < nc1 \\<Longrightarrow> col (four_block_mat A B C D) j = col A j @\\<^sub>v col C j\" (is \"_ \\<Longrightarrow> ?AC\")\n  \"\\<not> j < nc1 \\<Longrightarrow> j < nc1 + nc2 \\<Longrightarrow> col (four_block_mat A B C D) j = col B (j - nc1) @\\<^sub>v col D (j - nc1)\"\n  (is \"_ \\<Longrightarrow> _ \\<Longrightarrow> ?BD\")\nproof -\n  assume j: \"j < nc1\"\n  show ?AC by (rule eq_vecI, insert j c, auto)\nnext\n  assume j: \"\\<not> j < nc1\" \"j < nc1 + nc2\"\n  show ?BD by (rule eq_vecI, insert j c, auto)\nqed\n\nlemma mult_four_block_mat: assumes\n  c1: \"A1 \\<in> carrier_mat nr1 n1\" \"B1 \\<in> carrier_mat nr1 n2\" \"C1 \\<in> carrier_mat nr2 n1\" \"D1 \\<in> carrier_mat nr2 n2\" and\n  c2: \"A2 \\<in> carrier_mat n1 nc1\" \"B2 \\<in> carrier_mat n1 nc2\" \"C2 \\<in> carrier_mat n2 nc1\" \"D2 \\<in> carrier_mat n2 nc2\"\n  shows \"four_block_mat A1 B1 C1 D1 * four_block_mat A2 B2 C2 D2\n  = four_block_mat (A1 * A2 + B1 * C2) (A1 * B2 + B1 * D2)\n    (C1 * A2 + D1 * C2) (C1 * B2 + D1 * D2)\" (is \"?M1 * ?M2 = _\")\nproof -\n  note row = row_four_block_mat[OF c1]\n  note col = col_four_block_mat[OF c2]\n  {\n    fix i j\n    assume i: \"i < nr1\" and j: \"j < nc1\"\n    have \"row ?M1 i \\<bullet> col ?M2 j = row A1 i \\<bullet> col A2 j + row B1 i \\<bullet> col C2 j\"\n      unfolding row(1)[OF i] col(1)[OF j]\n      by (rule scalar_prod_append[of _ n1 _ n2], insert c1 c2 i j, auto)\n  }\n  moreover\n  {\n    fix i j\n    assume i: \"\\<not> i < nr1\" \"i < nr1 + nr2\" and j: \"j < nc1\"\n    hence i': \"i - nr1 < nr2\" by auto\n    have \"row ?M1 i \\<bullet> col ?M2 j = row C1 (i - nr1) \\<bullet> col A2 j + row D1 (i - nr1) \\<bullet> col C2 j\"\n      unfolding row(2)[OF i] col(1)[OF j]\n      by (rule scalar_prod_append[of _ n1 _ n2], insert c1 c2 i i' j, auto)\n  }\n  moreover\n  {\n    fix i j\n    assume i: \"i < nr1\" and j: \"\\<not> j < nc1\" \"j < nc1 + nc2\"\n    hence j': \"j - nc1 < nc2\" by auto\n    have \"row ?M1 i \\<bullet> col ?M2 j = row A1 i \\<bullet> col B2 (j - nc1) + row B1 i \\<bullet> col D2 (j - nc1)\"\n      unfolding row(1)[OF i] col(2)[OF j]\n      by (rule scalar_prod_append[of _ n1 _ n2], insert c1 c2 i j' j, auto)\n  }\n  moreover\n  {\n    fix i j\n    assume i: \"\\<not> i < nr1\" \"i < nr1 + nr2\" and j: \"\\<not> j < nc1\" \"j < nc1 + nc2\"\n    hence i': \"i - nr1 < nr2\" and j': \"j - nc1 < nc2\" by auto\n    have \"row ?M1 i \\<bullet> col ?M2 j = row C1 (i - nr1) \\<bullet> col B2 (j - nc1) + row D1 (i - nr1) \\<bullet> col D2 (j - nc1)\"\n      unfolding row(2)[OF i] col(2)[OF j]\n      by (rule scalar_prod_append[of _ n1 _ n2], insert c1 c2 i i' j' j, auto)\n  }\n  ultimately show ?thesis\n    by (intro eq_matI, insert c1 c2, auto)\nqed\n\ndefinition append_rows :: \"'a :: zero mat \\<Rightarrow> 'a mat \\<Rightarrow> 'a mat\" (infixr \"@\\<^sub>r\" 65)where\n  \"A @\\<^sub>r B = four_block_mat A (0\\<^sub>m (dim_row A) 0) B (0\\<^sub>m (dim_row B) 0)\" \n\nlemma carrier_append_rows[simp,intro]: \"A \\<in> carrier_mat nr1 nc \\<Longrightarrow> B \\<in> carrier_mat nr2 nc \\<Longrightarrow>\n  A @\\<^sub>r B \\<in> carrier_mat (nr1 + nr2) nc\" \n  unfolding append_rows_def by auto\n\nlemma col_mult2[simp]:\n  assumes A: \"A : carrier_mat nr n\"\n      and B: \"B : carrier_mat n nc\"\n      and j: \"j < nc\"\n  shows \"col (A * B) j = A *\\<^sub>v col B j\"\nproof\n  have AB: \"A * B : carrier_mat nr nc\" using A B by auto\n  fix i assume i: \"i < dim_vec (A *\\<^sub>v col B j)\"\n  show \"col (A * B) j $ i = (A *\\<^sub>v col B j) $ i\"\n    using A B AB j i by simp\nqed auto\n\nlemma mat_vec_as_mat_mat_mult: assumes A: \"A \\<in> carrier_mat nr nc\" \n  and v: \"v \\<in> carrier_vec nc\" \nshows \"A *\\<^sub>v v = col (A * mat_of_cols nc [v]) 0\"  \n  by (subst col_mult2[OF A], insert v, auto)\n\nlemma mat_mult_append: assumes A: \"A \\<in> carrier_mat nr1 nc\" \n  and B: \"B \\<in> carrier_mat nr2 nc\" \n  and v: \"v \\<in> carrier_vec nc\" \nshows \"(A @\\<^sub>r B) *\\<^sub>v v = (A *\\<^sub>v v) @\\<^sub>v (B *\\<^sub>v v)\" \nproof -\n  let ?Fb1 = \"four_block_mat A (0\\<^sub>m nr1 0) B (0\\<^sub>m nr2 0)\" \n  let ?Fb2 = \"four_block_mat (mat_of_cols nc [v]) (0\\<^sub>m nc 0) (0\\<^sub>m 0 1) (0\\<^sub>m 0 0)\" \n  have id: \"?Fb2 = mat_of_cols nc [v]\" \n    using v by auto\n  have \"(A @\\<^sub>r B) *\\<^sub>v v = col (?Fb1 * ?Fb2) 0\" unfolding id\n    by (subst mat_vec_as_mat_mat_mult[OF _ v], insert A B, auto simp: append_rows_def)\n  also have \"?Fb1 * ?Fb2 = four_block_mat (A * mat_of_cols nc [v] + 0\\<^sub>m nr1 0 * 0\\<^sub>m 0 1) (A * 0\\<^sub>m nc 0 + 0\\<^sub>m nr1 0 * 0\\<^sub>m 0 0)\n     (B * mat_of_cols nc [v] + 0\\<^sub>m nr2 0 * 0\\<^sub>m 0 1) (B * 0\\<^sub>m nc 0 + 0\\<^sub>m nr2 0 * 0\\<^sub>m 0 0)\" \n    by (rule mult_four_block_mat[OF A _ B], auto)\n  also have \"(A * mat_of_cols nc [v] + 0\\<^sub>m nr1 0 * 0\\<^sub>m 0 1) = A * mat_of_cols nc [v]\" \n    using A v by auto\n  also have \"(B * mat_of_cols nc [v] + 0\\<^sub>m nr2 0 * 0\\<^sub>m 0 1) = B * mat_of_cols nc [v]\" \n    using B v by auto\n  also have \"(A * 0\\<^sub>m nc 0 + 0\\<^sub>m nr1 0 * 0\\<^sub>m 0 0) = 0\\<^sub>m nr1 0\" using A by auto \n  also have \"(B * 0\\<^sub>m nc 0 + 0\\<^sub>m nr2 0 * 0\\<^sub>m 0 0) = 0\\<^sub>m nr2 0\" using B by auto\n  finally have \"(A @\\<^sub>r B) *\\<^sub>v v = col (four_block_mat (A * mat_of_cols nc [v]) (0\\<^sub>m nr1 0) (B * mat_of_cols nc [v]) (0\\<^sub>m nr2 0)) 0\" .\n  also have \"\\<dots> = col (A * mat_of_cols nc [v]) 0 @\\<^sub>v col (B * mat_of_cols nc [v]) 0\" \n    by (rule col_four_block_mat, insert A B v, auto)\n  also have \"col (A * mat_of_cols nc [v]) 0 = A *\\<^sub>v v\" \n    by (rule mat_vec_as_mat_mat_mult[symmetric, OF A v])\n  also have \"col (B * mat_of_cols nc [v]) 0 = B *\\<^sub>v v\" \n    by (rule mat_vec_as_mat_mat_mult[symmetric, OF B v])\n  finally show ?thesis .\nqed\n \nlemma append_rows_le: assumes A: \"A \\<in> carrier_mat nr1 nc\" \n  and B: \"B \\<in> carrier_mat nr2 nc\" \n  and a: \"a \\<in> carrier_vec nr1\" \n  and v: \"v \\<in> carrier_vec nc\"\nshows \"(A @\\<^sub>r B) *\\<^sub>v v \\<le> (a @\\<^sub>v b) \\<longleftrightarrow> A *\\<^sub>v v \\<le> a \\<and> B *\\<^sub>v v \\<le> b\" \n  unfolding mat_mult_append[OF A B v]\n  by (rule append_vec_le[OF _ a], insert A v, auto)\n\n\n\n\nlemma assoc_four_block_mat: fixes FB :: \"'a mat \\<Rightarrow> 'a mat \\<Rightarrow> 'a :: zero mat\"\n  defines FB: \"FB \\<equiv> \\<lambda> Bb Cc. four_block_mat Bb (0\\<^sub>m (dim_row Bb) (dim_col Cc)) (0\\<^sub>m (dim_row Cc) (dim_col Bb)) Cc\"\n  shows \"FB A (FB B C) = FB (FB A B) C\" (is \"?L = ?R\")\nproof -\n  let ?ar = \"dim_row A\" let ?ac = \"dim_col A\"\n  let ?br = \"dim_row B\" let ?bc = \"dim_col B\"\n  let ?cr = \"dim_row C\" let ?cc = \"dim_col C\"\n  let ?r = \"?ar + ?br + ?cr\" let ?c = \"?ac + ?bc + ?cc\"\n  let ?BC = \"FB B C\" let ?AB = \"FB A B\"\n  have dL: \"dim_row ?L = ?r\" \"dim_col ?L = ?c\" unfolding FB by auto\n  have dR: \"dim_row ?R = ?ar + ?br + ?cr\" \"dim_col ?R = ?ac + ?bc + ?cc\" unfolding FB by auto\n  have dBC: \"dim_row ?BC = ?br + ?cr\" \"dim_col ?BC = ?bc + ?cc\" unfolding FB by auto\n  have dAB: \"dim_row ?AB = ?ar + ?br\" \"dim_col ?AB = ?ac + ?bc\" unfolding FB by auto\n  show ?thesis\n  proof (intro eq_matI[of ?R ?L, unfolded dL dR, OF _ refl refl])\n    fix i j\n    assume i: \"i < ?r\" and j: \"j < ?c\"\n    show \"?L $$ (i,j) = ?R $$ (i,j)\"\n    proof (cases \"i < ?ar\")\n      case True note i = this\n      thus ?thesis using j\n        by (cases \"j < ?ac\", auto simp: FB)\n    next\n      case False note ii = this\n      show ?thesis\n      proof (cases \"j < ?ac\")\n        case True\n        with i ii show ?thesis unfolding FB by auto\n      next\n        case False note jj = this\n        from j jj i ii have L: \"?L $$ (i,j) = ?BC $$ (i - ?ar, j - ?ac)\" unfolding FB by auto\n        have R: \"?R $$ (i,j) = ?BC $$ (i - ?ar, j - ?ac)\" using ii jj i j\n          by (cases \"i < ?ar + ?br\"; cases \"j < ?ac + ?bc\", auto simp: FB)\n        show ?thesis unfolding L R ..\n      qed\n    qed\n  qed\nqed\n\ndefinition split_block :: \"'a mat \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> ('a mat \\<times> 'a mat \\<times> 'a mat \\<times> 'a mat)\"\n  where \"split_block A sr sc = (let\n    nr = dim_row A; nc = dim_col A;\n    nr2 = nr - sr; nc2 = nc - sc;\n    A1 = mat sr sc (\\<lambda> ij. A $$ ij);\n    A2 = mat sr nc2 (\\<lambda> (i,j). A $$ (i,j+sc));\n    A3 = mat nr2 sc (\\<lambda> (i,j). A $$ (i+sr,j));\n    A4 = mat nr2 nc2 (\\<lambda> (i,j). A $$ (i+sr,j+sc))\n  in (A1,A2,A3,A4))\"\n\nlemma split_block: assumes res: \"split_block A sr1 sc1 = (A1,A2,A3,A4)\"\n  and dims: \"dim_row A = sr1 + sr2\" \"dim_col A = sc1 + sc2\"\n  shows \"A1 \\<in> carrier_mat sr1 sc1\" \"A2 \\<in> carrier_mat sr1 sc2\"\n    \"A3 \\<in> carrier_mat sr2 sc1\" \"A4 \\<in> carrier_mat sr2 sc2\"\n    \"A = four_block_mat A1 A2 A3 A4\"\n  using res unfolding split_block_def Let_def\n  by (auto simp: dims)\n\ntext \\<open>Using @{const four_block_mat} we define block-diagonal matrices.\\<close>\n\nfun diag_block_mat :: \"'a :: zero mat list \\<Rightarrow> 'a mat\" where\n  \"diag_block_mat [] = 0\\<^sub>m 0 0\"\n| \"diag_block_mat (A # As) = (let\n     B = diag_block_mat As\n     in four_block_mat A (0\\<^sub>m (dim_row A) (dim_col B)) (0\\<^sub>m (dim_row B) (dim_col A)) B)\"\n\nlemma dim_diag_block_mat:\n  \"dim_row (diag_block_mat As) = sum_list (map dim_row As)\" (is \"?row\")\n  \"dim_col (diag_block_mat As) = sum_list (map dim_col As)\" (is \"?col\")\nproof -\n  have \"?row \\<and> ?col\"\n    by (induct As, auto simp: Let_def)\n  thus ?row and ?col by auto\nqed\n\nlemma diag_block_mat_singleton[simp]: \"diag_block_mat [A] = A\"\n  by auto\n\nlemma diag_block_mat_append: \"diag_block_mat (As @ Bs) =\n  (let A = diag_block_mat As; B = diag_block_mat Bs\n  in four_block_mat A (0\\<^sub>m (dim_row A) (dim_col B)) (0\\<^sub>m (dim_row B) (dim_col A)) B)\"\n  unfolding Let_def\nproof (induct As)\n  case (Cons A As)\n  show ?case\n    unfolding append.simps\n    unfolding diag_block_mat.simps Let_def\n    unfolding Cons\n    by (rule assoc_four_block_mat)\nqed auto\n\nlemma diag_block_mat_last: \"diag_block_mat (As @ [B]) =\n  (let A = diag_block_mat As\n  in four_block_mat A (0\\<^sub>m (dim_row A) (dim_col B)) (0\\<^sub>m (dim_row B) (dim_col A)) B)\"\n  unfolding diag_block_mat_append diag_block_mat_singleton by auto\n\n\nlemma diag_block_mat_square:\n  \"Ball (set As) square_mat \\<Longrightarrow> square_mat (diag_block_mat As)\"\nby (induct As, auto simp:Let_def)\n\nlemma diag_block_one_mat[simp]:\n  \"diag_block_mat (map (\\<lambda>A. 1\\<^sub>m (dim_row A)) As) = (1\\<^sub>m (sum_list (map dim_row As)))\"\n  by (induct As, auto simp: Let_def)\n\nlemma elements_diag_block_mat:\n  \"elements_mat (diag_block_mat As) \\<subseteq> {0} \\<union> \\<Union> (set (map elements_mat As))\"\nproof (induct As)\n  case Nil then show ?case using dim_diag_block_mat[of Nil] by auto next\n  case (Cons A As)\n    let ?D = \"diag_block_mat As\"\n    let ?B = \"0\\<^sub>m (dim_row A) (dim_col ?D)\"\n    let ?C = \"0\\<^sub>m (dim_row ?D) (dim_col A)\"\n    have A: \"A \\<in> carrier_mat (dim_row A) (dim_col A)\" by auto\n    have B: \"?B \\<in> carrier_mat (dim_row A) (dim_col ?D)\" by auto\n    have C: \"?C \\<in> carrier_mat (dim_row ?D) (dim_col A)\" by auto\n    have D: \"?D \\<in> carrier_mat (dim_row ?D) (dim_col ?D)\" by auto\n    have\n      \"elements_mat (diag_block_mat (A#As)) \\<subseteq>\n       elements_mat A \\<union> elements_mat ?B \\<union> elements_mat ?C \\<union> elements_mat ?D\"\n      unfolding diag_block_mat.simps Let_def\n      using elements_four_block_mat[OF A B C D] elements_0_mat\n      by auto\n    also have \"... \\<subseteq> {0} \\<union> elements_mat A \\<union> elements_mat ?D\"\n      using elements_0_mat by auto\n    finally show ?case using Cons by auto\nqed\n\nlemma diag_block_pow_mat: assumes sq: \"Ball (set As) square_mat\"\n  shows \"diag_block_mat As ^\\<^sub>m n = diag_block_mat (map (\\<lambda> A. A ^\\<^sub>m n) As)\" (is \"?As ^\\<^sub>m _ = _\")\nproof (induct n)\n  case 0\n  have \"?As ^\\<^sub>m 0 = 1\\<^sub>m (dim_row ?As)\" by simp\n  also have \"dim_row ?As = sum_list (map dim_row As)\"\n    using diag_block_mat_square[OF sq] unfolding dim_diag_block_mat by auto\n  also have \"1\\<^sub>m \\<dots> = diag_block_mat (map (\\<lambda>A. 1\\<^sub>m (dim_row A)) As)\" by simp\n  also have \"\\<dots> = diag_block_mat (map (\\<lambda> A. A ^\\<^sub>m 0) As)\" by simp\n  finally show ?case .\nnext\n  case (Suc n)\n  let ?An = \"\\<lambda> As. diag_block_mat (map (\\<lambda>A. A ^\\<^sub>m n) As)\"\n  let ?Asn = \"\\<lambda> As. diag_block_mat (map (\\<lambda>A. A ^\\<^sub>m n * A) As)\"\n  from Suc have \"?case = (?An As * diag_block_mat As = ?Asn As)\" by simp\n  also have \"\\<dots>\" using sq\n  proof (induct As)\n    case (Cons A As)\n    hence IH: \"?An As * diag_block_mat As = ?Asn As\"\n      and sq: \"Ball (set As) square_mat\" and A: \"dim_col A = dim_row A\" by auto\n    have sq2: \"Ball (set (List.map (\\<lambda>A. A ^\\<^sub>m n) As)) square_mat\"\n      and sq3: \"Ball (set (List.map (\\<lambda>A. A ^\\<^sub>m n * A) As)) square_mat\"\n      using sq by auto\n    define n1 where \"n1 = dim_row A\"\n    define n2 where \"n2 = sum_list (map dim_row As)\"\n    from A have A: \"A \\<in> carrier_mat n1 n1\" unfolding n1_def carrier_mat_def by simp\n    have [simp]: \"dim_col (?An As) = n2\" \"dim_row (?An As) = n2\"\n      unfolding n2_def\n      using diag_block_mat_square[OF sq2,unfolded square_mat.simps]\n      unfolding dim_diag_block_mat map_map by (auto simp:o_def)\n    have [simp]: \"dim_col (?Asn As) = n2\" \"dim_row (?Asn As) = n2\"\n      unfolding n2_def\n      using diag_block_mat_square[OF sq3,unfolded square_mat.simps]\n      unfolding dim_diag_block_mat map_map by (auto simp:o_def)\n    have [simp]:\n      \"dim_row (diag_block_mat As) = n2\"\n      \"dim_col (diag_block_mat As) = n2\"\n      unfolding n2_def\n      using diag_block_mat_square[OF sq,unfolded square_mat.simps]\n      unfolding dim_diag_block_mat by auto\n\n    have [simp]: \"diag_block_mat As \\<in> carrier_mat n2 n2\" unfolding carrier_mat_def by simp\n    have [simp]: \"?An As \\<in> carrier_mat n2 n2\" unfolding carrier_mat_def by simp\n    show ?case unfolding diag_block_mat.simps Let_def list.simps\n      by (subst mult_four_block_mat[of _ n1 n1 _ n2 _ n2 _ _ n1 _ n2],\n      insert A, auto simp: IH)\n  qed auto\n  finally show ?case by simp\nqed\n\nlemma diag_block_upper_triangular: assumes\n    \"\\<And> A i j. A \\<in> set As \\<Longrightarrow> j < i \\<Longrightarrow> i < dim_row A \\<Longrightarrow> A $$ (i,j) = 0\"\n  and \"Ball (set As) square_mat\"\n  and \"j < i\" \"i < dim_row (diag_block_mat As)\"\n  shows \"diag_block_mat As $$ (i,j) = 0\"\n  using assms\nproof (induct As arbitrary: i j)\n  case (Cons A As i j)\n  let ?n1 = \"dim_row A\"\n  let ?n2 = \"sum_list (map dim_row As)\"\n  from Cons have [simp]: \"dim_col A = ?n1\" by simp\n  from Cons have \"Ball (set As) square_mat\" by auto\n  note [simp] = diag_block_mat_square[OF this,unfolded square_mat.simps]\n  note [simp] = dim_diag_block_mat(1)\n  from Cons(5) have i: \"i < ?n1 + ?n2\" by simp\n  show ?case\n  proof (cases \"i < ?n1\")\n    case True\n    with Cons(4) have j: \"j < ?n1\" by auto\n    with True Cons(2)[of A, OF _ Cons(4)] show ?thesis\n      by (simp add: Let_def)\n  next\n    case False note iAs = this\n    show ?thesis\n    proof (cases \"j < ?n1\")\n      case True\n      with i iAs show ?thesis by (simp add: Let_def)\n    next\n      case False note jAs = this\n      from Cons(4) i have j: \"j < ?n1 + ?n2\" by auto\n      show ?thesis using iAs jAs i j\n        by (simp add: Let_def, subst Cons(1), insert Cons(2-4), auto)\n    qed\n  qed\nqed simp\n\nlemma smult_four_block_mat: assumes c: \"A \\<in> carrier_mat nr1 nc1\" \"B \\<in> carrier_mat nr1 nc2\"\n  \"C \\<in> carrier_mat nr2 nc1\" \"D \\<in> carrier_mat nr2 nc2\"\n  shows \"a \\<cdot>\\<^sub>m four_block_mat A B C D = four_block_mat (a \\<cdot>\\<^sub>m A) (a \\<cdot>\\<^sub>m B) (a \\<cdot>\\<^sub>m C) (a \\<cdot>\\<^sub>m D)\"\n  by (rule eq_matI, insert c, auto)\n\nlemma map_four_block_mat: assumes c: \"A \\<in> carrier_mat nr1 nc1\" \"B \\<in> carrier_mat nr1 nc2\"\n  \"C \\<in> carrier_mat nr2 nc1\" \"D \\<in> carrier_mat nr2 nc2\"\n  shows \"map_mat f (four_block_mat A B C D) = four_block_mat (map_mat f A) (map_mat f B) (map_mat f C) (map_mat f D)\"\n  by (rule eq_matI, insert c, auto)\n\nlemma add_four_block_mat: assumes\n  c1: \"A1 \\<in> carrier_mat nr1 nc1\" \"B1 \\<in> carrier_mat nr1 nc2\" \"C1 \\<in> carrier_mat nr2 nc1\" \"D1 \\<in> carrier_mat nr2 nc2\" and\n  c2: \"A2 \\<in> carrier_mat nr1 nc1\" \"B2 \\<in> carrier_mat nr1 nc2\" \"C2 \\<in> carrier_mat nr2 nc1\" \"D2 \\<in> carrier_mat nr2 nc2\"\n  shows \"four_block_mat A1 B1 C1 D1 + four_block_mat A2 B2 C2 D2\n  = four_block_mat (A1 + A2) (B1 + B2) (C1 + C2) (D1 + D2)\"\n  by (rule eq_matI, insert assms, auto)\n\n\nlemma diag_four_block_mat: assumes c: \"A \\<in> carrier_mat n1 n1\"\n   \"D \\<in> carrier_mat n2 n2\"\n  shows \"diag_mat (four_block_mat A B C D) = diag_mat A @ diag_mat D\"\n  by (rule nth_equalityI, insert c, auto simp: diag_mat_def nth_append)\n\ndefinition mk_diagonal :: \"'a::zero list \\<Rightarrow> 'a mat\"\n  where \"mk_diagonal as = diag_block_mat (map (\\<lambda>a. mat (Suc 0) (Suc 0) (\\<lambda>_. a)) as)\"\n\nlemma mk_diagonal_dim:\n  \"dim_row (mk_diagonal as) = length as\" \"dim_col (mk_diagonal as) = length as\"\n  unfolding mk_diagonal_def by(induct as, auto simp: Let_def)\n\nlemma mk_diagonal_diagonal: \"diagonal_mat (mk_diagonal as)\"\n  unfolding mk_diagonal_def\nproof (induct as)\n  case Nil show ?case unfolding mk_diagonal_def diagonal_mat_def by simp next\n  case (Cons a as)\n    let ?n = \"length (a#as)\"\n    let ?A = \"mat (Suc 0) (Suc 0) (\\<lambda>_. a)\"\n    let ?f = \"map (\\<lambda>a. mat (Suc 0) (Suc 0) (\\<lambda>_. a))\"\n    let ?AS = \"diag_block_mat (?f as)\"\n    let ?AAS = \"diag_block_mat (?f (a#as))\"\n    show ?case\n      unfolding diagonal_mat_def\n    proof(intro allI impI)\n      fix i j assume ir: \"i < dim_row ?AAS\" and jc: \"j < dim_col ?AAS\" and ij: \"i \\<noteq> j\"\n      hence ir2: \"i < 1 + dim_row ?AS\" and jc2: \"j < 1 + dim_col ?AS\"\n        unfolding dim_row_mat list.map diag_block_mat.simps Let_def\n        by auto\n      show \"?AAS $$ (i,j) = 0\"\n      proof (cases \"i = 0\")\n        case True\n          then show ?thesis using jc ij by (auto simp: Let_def) next\n        case False note i0 = this\n          show ?thesis\n          proof (cases \"j = 0\")\n            case True\n              then show ?thesis using ir ij by (auto simp: Let_def) next\n            case False\n              have ir3: \"i-1 < dim_row ?AS\" and jc3: \"j-1 < dim_col ?AS\"\n                using ir2 jc2 i0 False by auto\n              have IH: \"\\<And>i j. i < dim_row ?AS \\<Longrightarrow> j < dim_col ?AS \\<Longrightarrow> i \\<noteq> j \\<Longrightarrow>\n                ?AS $$ (i,j) = 0\"\n                using Cons unfolding diagonal_mat_def by auto\n              have \"?AS $$ (i-1,j-1) = 0\"\n                using IH[OF ir3 jc3] i0 False ij by auto\n              thus ?thesis using ir jc ij by (simp add: Let_def)\n          qed\n      qed\n    qed\nqed\n\ndefinition orthogonal_mat :: \"'a::semiring_0 mat \\<Rightarrow> bool\"\n  where \"orthogonal_mat A \\<equiv>\n    let B = transpose_mat A * A in\n    diagonal_mat B \\<and> (\\<forall>i<dim_col A. B $$ (i,i) \\<noteq> 0)\"\n\nlemma orthogonal_matD[elim]:\n  \"orthogonal_mat A \\<Longrightarrow>\n   i < dim_col A \\<Longrightarrow> j < dim_col A \\<Longrightarrow> (col A i \\<bullet> col A j = 0) = (i \\<noteq> j)\"\n  unfolding orthogonal_mat_def diagonal_mat_def by auto\n\nlemma orthogonal_matI[intro]:\n  \"(\\<And>i j. i < dim_col A \\<Longrightarrow> j < dim_col A \\<Longrightarrow> (col A i \\<bullet> col A j = 0) = (i \\<noteq> j)) \\<Longrightarrow>\n   orthogonal_mat A\"\n  unfolding orthogonal_mat_def diagonal_mat_def by auto\n\ndefinition orthogonal :: \"'a::semiring_0 vec list \\<Rightarrow> bool\"\n  where \"orthogonal vs \\<equiv>\n    \\<forall>i j. i < length vs \\<longrightarrow> j < length vs \\<longrightarrow>\n      (vs ! i \\<bullet> vs ! j = 0) = (i \\<noteq> j)\"\n\nlemma orthogonalD[elim]:\n  \"orthogonal vs \\<Longrightarrow> i < length vs \\<Longrightarrow> j < length vs \\<Longrightarrow>\n  (nth vs i \\<bullet> nth vs j = 0) = (i \\<noteq> j)\"\n  unfolding orthogonal_def by auto\n\nlemma orthogonalI[intro]:\n  \"(\\<And>i j. i < length vs \\<Longrightarrow> j < length vs \\<Longrightarrow> (nth vs i \\<bullet> nth vs j = 0) = (i \\<noteq> j)) \\<Longrightarrow>\n   orthogonal vs\"\n  unfolding orthogonal_def by auto\n\n\nlemma transpose_four_block_mat: assumes *: \"A \\<in> carrier_mat nr1 nc1\" \"B \\<in> carrier_mat nr1 nc2\"\n  \"C \\<in> carrier_mat nr2 nc1\" \"D \\<in> carrier_mat nr2 nc2\"\n  shows \"transpose_mat (four_block_mat A B C D) =\n    four_block_mat (transpose_mat A) (transpose_mat C) (transpose_mat B) (transpose_mat D)\"\n  by (rule eq_matI, insert *, auto)\n\nlemma zero_transpose_mat[simp]: \"transpose_mat (0\\<^sub>m n m) = (0\\<^sub>m m n)\"\n  by (rule eq_matI, auto)\n\nlemma upper_triangular_four_block: assumes AD: \"A \\<in> carrier_mat n n\" \"D \\<in> carrier_mat m m\"\n  and ut: \"upper_triangular A\" \"upper_triangular D\"\n  shows \"upper_triangular (four_block_mat A B (0\\<^sub>m m n) D)\"\nproof -\n  let ?C = \"four_block_mat A B (0\\<^sub>m m n) D\"\n  from AD have dim: \"dim_row ?C = n + m\" \"dim_col ?C = n + m\" \"dim_row A = n\" by auto\n  show ?thesis\n  proof (rule upper_triangularI, unfold dim)\n    fix i j\n    assume *: \"j < i\" \"i < n + m\"\n    show \"?C $$ (i,j) = 0\"\n    proof (cases \"i < n\")\n      case True\n      with upper_triangularD[OF ut(1) *(1)] * AD show ?thesis by auto\n    next\n      case False note i = this\n      show ?thesis by (cases \"j < n\", insert upper_triangularD[OF ut(2)] * i AD, auto)\n    qed\n  qed\nqed\n\nlemma pow_four_block_mat: assumes A: \"A \\<in> carrier_mat n n\"\n  and B: \"B \\<in> carrier_mat m m\"\n  shows \"(four_block_mat A (0\\<^sub>m n m) (0\\<^sub>m m n) B) ^\\<^sub>m k =\n    four_block_mat (A ^\\<^sub>m k) (0\\<^sub>m n m) (0\\<^sub>m m n) (B ^\\<^sub>m k)\"\nproof (induct k)\n  case (Suc k)\n  let ?FB = \"\\<lambda> A B. four_block_mat A (0\\<^sub>m n m) (0\\<^sub>m m n) B\"\n  let ?A = \"?FB A B\"\n  let ?B = \"?FB (A ^\\<^sub>m k) (B ^\\<^sub>m k)\"\n  from A B have Ak: \"A ^\\<^sub>m k \\<in> carrier_mat n n\" and Bk: \"B ^\\<^sub>m k \\<in> carrier_mat m m\" by auto\n  have \"?A ^\\<^sub>m Suc k = ?A ^\\<^sub>m k * ?A\" by simp\n  also have \"?A ^\\<^sub>m k = ?B \" by (rule Suc)\n  also have \"?B * ?A = ?FB (A ^\\<^sub>m Suc k) (B ^\\<^sub>m Suc k)\"\n    by (subst mult_four_block_mat[OF Ak _ _ Bk A _ _ B], insert A B, auto)\n  finally show ?case .\nqed (insert A B, auto)\n\nlemma uminus_scalar_prod:\n  assumes [simp]: \"v : carrier_vec n\" \"w : carrier_vec n\"\n  shows \"- ((v::'a::field vec) \\<bullet> w) = (- v) \\<bullet> w\"\n  unfolding scalar_prod_def uminus_vec_def\n  apply (subst sum_negf[symmetric])\nproof (rule sum.cong[OF refl])\n  fix i assume i: \"i : {0 ..<dim_vec w}\"\n  have [simp]: \"dim_vec v = n\" \"dim_vec w = n\" by auto\n  show \"- (v $ i * w $ i) = vec (dim_vec v) (\\<lambda>i. - v $ i) $ i * w $ i\"\n    unfolding minus_mult_left using i by auto\nqed\n\n\nlemma append_vec_eq:\n  assumes [simp]: \"v : carrier_vec n\" \"v' : carrier_vec n\"\n  shows [simp]: \"v @\\<^sub>v w = v' @\\<^sub>v w' \\<longleftrightarrow> v = v' \\<and> w = w'\" (is \"?L \\<longleftrightarrow> ?R\")\nproof\n  have [simp]: \"dim_vec v = n\" \"dim_vec v' = n\" by auto\n  { assume L: ?L\n    have vv': \"v = v'\"\n    proof\n      fix i assume i: \"i < dim_vec v'\"\n      have \"(v @\\<^sub>v w) $ i = (v' @\\<^sub>v w') $ i\" using L by auto\n      thus \"v $ i = v' $ i\" using i by auto\n    qed auto\n    moreover have \"w = w'\"\n    proof\n      show \"dim_vec w = dim_vec w'\" using vv' L\n        by (metis add_diff_cancel_left' index_append_vec(2))\n      moreover fix i assume i: \"i < dim_vec w'\"\n      have \"(v @\\<^sub>v w) $ (n + i) = (v' @\\<^sub>v w') $ (n + i)\" using L by auto\n      ultimately show \"w $ i = w' $ i\" using i by simp\n    qed\n    ultimately show ?R by simp\n  }\nqed auto\n\nlemma append_vec_add:\n  assumes [simp]: \"v : carrier_vec n\" \"v' : carrier_vec n\"\n      and [simp]: \"w : carrier_vec m\" \"w' : carrier_vec m\"\n  shows \"(v @\\<^sub>v w) + (v' @\\<^sub>v w') = (v + v') @\\<^sub>v (w + w')\" (is \"?L = ?R\")\nproof\n  have [simp]: \"dim_vec v = n\" \"dim_vec v' = n\" by auto\n  have [simp]: \"dim_vec w = m\" \"dim_vec w' = m\" by auto\n  fix i assume i: \"i < dim_vec ?R\"\n  thus \"?L $ i = ?R $ i\" by (cases \"i < n\",auto)\nqed auto\n\n\nlemma mult_mat_vec_split:\n  assumes A: \"A : carrier_mat n n\"\n      and D: \"D : carrier_mat m m\"\n      and a: \"a : carrier_vec n\"\n      and d: \"d : carrier_vec m\"\n  shows \"four_block_mat A (0\\<^sub>m n m) (0\\<^sub>m m n) D *\\<^sub>v (a @\\<^sub>v d) = A *\\<^sub>v a @\\<^sub>v D *\\<^sub>v d\"\n    (is \"?A00D *\\<^sub>v _ = ?r\")\nproof\n  have A00D: \"?A00D : carrier_mat (n+m) (n+m)\" using four_block_carrier_mat[OF A D].\n  fix i assume i: \"i < dim_vec ?r\"\n  show \"(?A00D *\\<^sub>v (a @\\<^sub>v d)) $ i = ?r $ i\" (is \"?li = _\")\n  proof (cases \"i < n\")\n    case True\n      have \"?li = (row A i @\\<^sub>v 0\\<^sub>v m) \\<bullet> (a @\\<^sub>v d)\"\n        using A row_four_block_mat[OF A _ _ D] True by simp\n      also have \"... = row A i \\<bullet> a + 0\\<^sub>v m \\<bullet> d\"\n        apply (rule scalar_prod_append) using A D a d True by auto\n      also have \"... = row A i \\<bullet> a\" using d by simp\n      finally show ?thesis using A True by auto\n    next case False\n      let ?i = \"i - n\"\n      have \"?li = (0\\<^sub>v n @\\<^sub>v row D ?i) \\<bullet> (a @\\<^sub>v d)\"\n        using i row_four_block_mat[OF A _ _ D] False A D by simp\n      also have \"... = 0\\<^sub>v n \\<bullet> a + row D ?i \\<bullet> d\"\n        apply (rule scalar_prod_append) using A D a d False by auto\n      also have \"... = row D ?i \\<bullet> d\" using a by simp\n      finally show ?thesis using A D False i by auto\n  qed\nqed auto\n\nlemma similar_mat_witI: assumes \"P * Q = 1\\<^sub>m n\" \"Q * P = 1\\<^sub>m n\" \"A = P * B * Q\"\n  \"A \\<in> carrier_mat n n\" \"B \\<in> carrier_mat n n\" \"P \\<in> carrier_mat n n\" \"Q \\<in> carrier_mat n n\"\n  shows \"similar_mat_wit A B P Q\" using assms unfolding similar_mat_wit_def Let_def by auto\n\n\n\nlemma similar_mat_witD2: assumes \"A \\<in> carrier_mat n m\" \"similar_mat_wit A B P Q\"\n  shows \"P * Q = 1\\<^sub>m n\" \"Q * P = 1\\<^sub>m n\" \"A = P * B * Q\"\n  \"A \\<in> carrier_mat n n\" \"B \\<in> carrier_mat n n\" \"P \\<in> carrier_mat n n\" \"Q \\<in> carrier_mat n n\"\n  using similar_mat_witD[OF _ assms(2), of n] assms(1)[unfolded carrier_mat_def] by auto\n\n\n\nlemma similar_mat_wit_refl: assumes A: \"A \\<in> carrier_mat n n\"\n  shows \"similar_mat_wit A A (1\\<^sub>m n) (1\\<^sub>m n)\"\n  by (rule similar_mat_witI[OF _ _ _ A], insert A, auto)\n\nlemma similar_mat_wit_trans: assumes AB: \"similar_mat_wit A B P Q\"\n  and BC: \"similar_mat_wit B C P' Q'\"\n  shows \"similar_mat_wit A C (P * P') (Q' * Q)\"\nproof -\n  from similar_mat_witD[OF refl AB] obtain n where\n    AB: \"{A, B, P, Q} \\<subseteq> carrier_mat n n\" \"P * Q = 1\\<^sub>m n\" \"Q * P = 1\\<^sub>m n\" \"A = P * B * Q\" by blast\n  hence B: \"B \\<in> carrier_mat n n\" by auto\n  from similar_mat_witD2[OF B BC] have\n    BC: \"{C, P', Q'} \\<subseteq> carrier_mat n n\" \"P' * Q' = 1\\<^sub>m n\" \"Q' * P' = 1\\<^sub>m n\" \"B = P' * C * Q'\" by auto\n  let ?c = \"\\<lambda> A. A \\<in> carrier_mat n n\"\n  let ?P = \"P * P'\"\n  let ?Q = \"Q' * Q\"\n  from AB BC have carr: \"?c A\" \"?c B\" \"?c C\" \"?c P\" \"?c P'\" \"?c Q\" \"?c Q'\"\n    and Carr: \"{A, C, ?P, ?Q} \\<subseteq> carrier_mat n n\" by auto\n  note [simp] = assoc_mult_mat[of _ n n _ n _ n]\n  have id: \"A = ?P * C * ?Q\" unfolding AB(4)[unfolded BC(4)] using carr\n    by simp\n  have \"?P * ?Q = P * (P' * Q') * Q\" using carr by simp\n  also have \"\\<dots> = 1\\<^sub>m n\" unfolding BC using carr AB by simp\n  finally have PQ: \"?P * ?Q = 1\\<^sub>m n\" .\n  have \"?Q * ?P = Q' * (Q * P) * P'\" using carr by simp\n  also have \"\\<dots> = 1\\<^sub>m n\" unfolding AB using carr BC by simp\n  finally have QP: \"?Q * ?P = 1\\<^sub>m n\" .\n  show ?thesis\n    by (rule similar_mat_witI[OF PQ QP id], insert Carr, auto)\nqed\n\nlemma similar_mat_refl: \"A \\<in> carrier_mat n n \\<Longrightarrow> similar_mat A A\"\n  using similar_mat_wit_refl unfolding similar_mat_def by blast\n\nlemma similar_mat_trans: \"similar_mat A B \\<Longrightarrow> similar_mat B C \\<Longrightarrow> similar_mat A C\"\n  using similar_mat_wit_trans unfolding similar_mat_def by blast\n\nlemma similar_mat_sym: \"similar_mat A B \\<Longrightarrow> similar_mat B A\"\n  using similar_mat_wit_sym unfolding similar_mat_def by blast\n\nlemma similar_mat_wit_four_block: assumes\n      1: \"similar_mat_wit A1 B1 P1 Q1\"\n  and 2: \"similar_mat_wit A2 B2 P2 Q2\"\n  and URA: \"URA = (P1 * UR * Q2)\"\n  and LLA: \"LLA = (P2 * LL * Q1)\"\n  and A1: \"A1 \\<in> carrier_mat n n\"\n  and A2: \"A2 \\<in> carrier_mat m m\"\n  and LL: \"LL \\<in> carrier_mat m n\"\n  and UR: \"UR \\<in> carrier_mat n m\"\n  shows \"similar_mat_wit (four_block_mat A1 URA LLA A2) (four_block_mat B1 UR LL B2)\n    (four_block_mat P1 (0\\<^sub>m n m) (0\\<^sub>m m n) P2) (four_block_mat Q1 (0\\<^sub>m n m) (0\\<^sub>m m n) Q2)\"\n  (is \"similar_mat_wit ?A ?B ?P ?Q\")\nproof -\n  let ?n = \"n + m\"\n  let ?O1 = \"1\\<^sub>m n\"   let ?O2 = \"1\\<^sub>m m\"   let ?O = \"1\\<^sub>m ?n\"\n  from similar_mat_witD2[OF A1 1] have 11: \"P1 * Q1 = ?O1\" \"Q1 * P1 = ?O1\"\n    and P1: \"P1 \\<in> carrier_mat n n\" and Q1: \"Q1 \\<in> carrier_mat n n\"\n    and B1: \"B1 \\<in> carrier_mat n n\" and 1: \"A1 = P1 * B1 * Q1\" by auto\n  from similar_mat_witD2[OF A2 2] have 21: \"P2 * Q2 = ?O2\" \"Q2 * P2 = ?O2\"\n    and P2: \"P2 \\<in> carrier_mat m m\" and Q2: \"Q2 \\<in> carrier_mat m m\"\n    and B2: \"B2 \\<in> carrier_mat m m\" and 2: \"A2 = P2 * B2 * Q2\" by auto\n  have PQ1: \"?P * ?Q = ?O\"\n    by (subst mult_four_block_mat[OF P1 _ _ P2 Q1 _ _ Q2], unfold 11 21, insert P1 P2 Q1 Q2,\n      auto intro!: eq_matI)\n  have QP1: \"?Q * ?P = ?O\"\n    by (subst mult_four_block_mat[OF Q1 _ _ Q2 P1 _ _ P2], unfold 11 21, insert P1 P2 Q1 Q2,\n      auto intro!: eq_matI)\n  let ?PB = \"?P * ?B\"\n  have P: \"?P \\<in> carrier_mat ?n ?n\" using P1 P2 by auto\n  have Q: \"?Q \\<in> carrier_mat ?n ?n\" using Q1 Q2 by auto\n  have B: \"?B \\<in> carrier_mat ?n ?n\" using B1 UR LL B2 by auto\n  have PB: \"?PB \\<in> carrier_mat ?n ?n\" using P B by auto\n  have PB1: \"P1 * B1 \\<in> carrier_mat n n\" using P1 B1 by auto\n  have PB2: \"P2 * B2 \\<in> carrier_mat m m\" using P2 B2 by auto\n  have P1UR: \"P1 * UR \\<in> carrier_mat n m\" using P1 UR by auto\n  have P2LL: \"P2 * LL \\<in> carrier_mat m n\" using P2 LL by auto\n  have id: \"?PB = four_block_mat (P1 * B1) (P1 * UR) (P2 * LL) (P2 * B2)\"\n    by (subst mult_four_block_mat[OF P1 _ _ P2 B1 UR LL B2], insert P1 P2 B1 B2 LL UR, auto)\n  have id: \"?PB * ?Q = four_block_mat (P1 * B1 * Q1) (P1 * UR * Q2)\n    (P2 * LL * Q1) (P2 * B2 * Q2)\" unfolding id\n    by (subst mult_four_block_mat[OF PB1 P1UR P2LL PB2 Q1 _ _ Q2],\n    insert P1 P2 B1 B2 Q1 Q2 UR LL, auto)\n  have id: \"?A = ?P * ?B * ?Q\" unfolding id 1 2 URA LLA ..\n  show ?thesis\n    by (rule similar_mat_witI[OF PQ1 QP1 id], insert A1 A2 B1 B2 Q1 Q2 P1 P2, auto)\nqed\n\n\nlemma similar_mat_four_block_0_ex: assumes\n      1: \"similar_mat A1 B1\"\n  and 2: \"similar_mat A2 B2\"\n  and A0: \"A0 \\<in> carrier_mat n m\"\n  and A1: \"A1 \\<in> carrier_mat n n\"\n  and A2: \"A2 \\<in> carrier_mat m m\"\n  shows \"\\<exists> B0. B0 \\<in> carrier_mat n m \\<and> similar_mat (four_block_mat A1 A0 (0\\<^sub>m m n) A2)\n    (four_block_mat B1 B0 (0\\<^sub>m m n) B2)\"\nproof -\n  from 1[unfolded similar_mat_def] obtain P1 Q1 where 1: \"similar_mat_wit A1 B1 P1 Q1\" by auto\n  note w1 = similar_mat_witD2[OF A1 1]\n  from 2[unfolded similar_mat_def] obtain P2 Q2 where 2: \"similar_mat_wit A2 B2 P2 Q2\" by auto\n  note w2 = similar_mat_witD2[OF A2 2]\n  from w1 w2 have C: \"B1 \\<in> carrier_mat n n\" \"B2 \\<in> carrier_mat m m\" by auto\n  from w1 w2 have id: \"0\\<^sub>m m n = Q2 * 0\\<^sub>m m n * P1\" by simp\n  let ?wit = \"Q1 * A0 * P2\"\n  from w1 w2 A0 have wit: \"?wit \\<in> carrier_mat n m\" by auto\n  from similar_mat_wit_sym[OF similar_mat_wit_four_block[OF similar_mat_wit_sym[OF 1] similar_mat_wit_sym[OF 2]\n    refl id C zero_carrier_mat A0]]\n  have \"similar_mat (four_block_mat A1 A0 (0\\<^sub>m m n) A2) (four_block_mat B1 (Q1 * A0 * P2) (0\\<^sub>m m n) B2)\"\n    unfolding similar_mat_def by auto\n  thus ?thesis using wit by auto\nqed\n\nlemma similar_mat_four_block_0_0: assumes\n      1: \"similar_mat A1 B1\"\n  and 2: \"similar_mat A2 B2\"\n  and A1: \"A1 \\<in> carrier_mat n n\"\n  and A2: \"A2 \\<in> carrier_mat m m\"\n  shows \"similar_mat (four_block_mat A1 (0\\<^sub>m n m) (0\\<^sub>m m n) A2)\n    (four_block_mat B1 (0\\<^sub>m n m) (0\\<^sub>m m n) B2)\"\nproof -\n  from 1[unfolded similar_mat_def] obtain P1 Q1 where 1: \"similar_mat_wit A1 B1 P1 Q1\" by auto\n  note w1 = similar_mat_witD2[OF A1 1]\n  from 2[unfolded similar_mat_def] obtain P2 Q2 where 2: \"similar_mat_wit A2 B2 P2 Q2\" by auto\n  note w2 = similar_mat_witD2[OF A2 2]\n  from w1 w2 have C: \"B1 \\<in> carrier_mat n n\" \"B2 \\<in> carrier_mat m m\" by auto\n  from w1 w2 have id: \"0\\<^sub>m m n = Q2 * 0\\<^sub>m m n * P1\" by simp\n  from w1 w2 have id2: \"0\\<^sub>m n m = Q1 * 0\\<^sub>m n m * P2\" by simp\n  from similar_mat_wit_sym[OF similar_mat_wit_four_block[OF similar_mat_wit_sym[OF 1] similar_mat_wit_sym[OF 2]\n    id2 id C zero_carrier_mat zero_carrier_mat]]\n  show ?thesis unfolding similar_mat_def by blast\nqed\n\nlemma similar_diag_mat_block_mat: assumes \"\\<And> A B. (A,B) \\<in> set Ms \\<Longrightarrow> similar_mat A B\"\n  shows \"similar_mat (diag_block_mat (map fst Ms)) (diag_block_mat (map snd Ms))\"\n  using assms\nproof (induct Ms)\n  case Nil\n  show ?case by (auto intro!: similar_mat_refl[of _ 0])\nnext\n  case (Cons AB Ms)\n  obtain A B where AB: \"AB = (A,B)\" by force\n  from Cons(2)[of A B] have simAB: \"similar_mat A B\" unfolding AB by auto\n  from similar_matD[OF this] obtain n where A: \"A \\<in> carrier_mat n n\" and B: \"B \\<in> carrier_mat n n\" by auto\n  hence [simp]: \"dim_row A = n\" \"dim_col A = n\" \"dim_row B = n\" \"dim_col B = n\" by auto\n  let ?C = \"diag_block_mat (map fst Ms)\" let ?D = \"diag_block_mat (map snd Ms)\"\n  from Cons(1)[OF Cons(2)] have simRec: \"similar_mat ?C ?D\" by auto\n  from similar_matD[OF this] obtain m where C: \"?C \\<in> carrier_mat m m\" and D: \"?D \\<in> carrier_mat m m\" by auto\n  hence [simp]: \"dim_row ?C = m\" \"dim_col ?C = m\" \"dim_row ?D = m\" \"dim_col ?D = m\" by auto\n  have \"similar_mat (diag_block_mat (map fst (AB # Ms))) (diag_block_mat (map snd (AB # Ms)))\n    = similar_mat (four_block_mat A (0\\<^sub>m n m) (0\\<^sub>m m n) ?C) (four_block_mat B (0\\<^sub>m n m) (0\\<^sub>m m n) ?D)\"\n    unfolding AB by (simp add: Let_def)\n  also have \"\\<dots>\"\n    by (rule similar_mat_four_block_0_0[OF simAB simRec A C])\n  finally show ?case .\nqed\n\nlemma similar_mat_wit_pow: assumes wit: \"similar_mat_wit A B P Q\"\n  shows \"similar_mat_wit (A ^\\<^sub>m k) (B ^\\<^sub>m k) P Q\"\nproof -\n  define n where \"n = dim_row A\"\n  let ?C = \"carrier_mat n n\"\n  from similar_mat_witD[OF refl wit, folded n_def] have\n    A: \"A \\<in> ?C\" and B: \"B \\<in> ?C\" and P: \"P \\<in> ?C\" and Q: \"Q \\<in> ?C\"\n    and PQ: \"P * Q = 1\\<^sub>m n\" and QP: \"Q * P = 1\\<^sub>m n\"\n    and AB: \"A = P * B * Q\"\n    by auto\n  from A B have *: \"(A ^\\<^sub>m k) \\<in> carrier_mat n n\" \"B ^\\<^sub>m k \\<in> carrier_mat n n\" by auto\n  note carr = A B P Q\n  have id: \"A ^\\<^sub>m k = P * B ^\\<^sub>m k * Q\" unfolding AB\n  proof (induct k)\n    case 0\n    thus ?case using carr by (simp add: PQ)\n  next\n    case (Suc k)\n    define Bk where \"Bk = B ^\\<^sub>m k\"\n    have Bk: \"Bk \\<in> carrier_mat n n\" unfolding Bk_def using carr by simp\n    have \"(P * B * Q) ^\\<^sub>m Suc k = (P * Bk * Q) * (P * B * Q)\" by (simp add: Suc Bk_def)\n    also have \"\\<dots> = P * (Bk * (Q * P) * B) * Q\"\n      using carr Bk by (simp add: assoc_mult_mat[of _ n n _ n _ n])\n    also have \"Bk * (Q * P) = Bk\" unfolding QP using Bk by simp\n    finally show ?case unfolding Bk_def by simp\n  qed\n  show ?thesis\n    by (rule similar_mat_witI[OF PQ QP id * P Q])\nqed\n\nlemma similar_mat_wit_pow_id: \"similar_mat_wit A B P Q \\<Longrightarrow> A ^\\<^sub>m k = P * B ^\\<^sub>m k * Q\"\n  using similar_mat_wit_pow[of A B P Q k] unfolding similar_mat_wit_def Let_def by blast\n\nsubsection\\<open>Homomorphism properties\\<close>\n\ncontext semiring_hom\nbegin\nabbreviation mat_hom :: \"'a mat \\<Rightarrow> 'b mat\" (\"mat\\<^sub>h\")\n  where \"mat\\<^sub>h \\<equiv> map_mat hom\"\n\nabbreviation vec_hom :: \"'a vec \\<Rightarrow> 'b vec\" (\"vec\\<^sub>h\")\n  where \"vec\\<^sub>h \\<equiv> map_vec hom\"\n\nlemma vec_hom_zero: \"vec\\<^sub>h (0\\<^sub>v n) = 0\\<^sub>v n\"\n  by (rule eq_vecI, auto)\n\nlemma mat_hom_one: \"mat\\<^sub>h (1\\<^sub>m n) = 1\\<^sub>m n\"\n  by (rule eq_matI, auto)\n\nlemma mat_hom_mult: assumes A: \"A \\<in> carrier_mat nr n\" and B: \"B \\<in> carrier_mat n nc\"\n  shows \"mat\\<^sub>h (A * B) = mat\\<^sub>h A * mat\\<^sub>h B\"\nproof -\n  let ?L = \"mat\\<^sub>h (A * B)\"\n  let ?R = \"mat\\<^sub>h A * mat\\<^sub>h B\"\n  let ?A = \"mat\\<^sub>h A\"\n  let ?B = \"mat\\<^sub>h B\"\n  from A B have id:\n    \"dim_row ?L = nr\" \"dim_row ?R = nr\"\n    \"dim_col ?L = nc\" \"dim_col ?R = nc\"  by auto\n  show ?thesis\n  proof (rule eq_matI, unfold id)\n    fix i j\n    assume *: \"i < nr\" \"j < nc\"\n    define I where \"I = {0 ..< n}\"\n    have id: \"{0 ..< dim_vec (col ?B j)} = I\" \"{0 ..< dim_vec (col B j)} = I\"\n      unfolding I_def using * B by auto\n    have finite: \"finite I\" unfolding I_def by auto\n    have I: \"I \\<subseteq> {0 ..< n}\" unfolding I_def by auto\n    have \"?L $$ (i,j) = hom (row A i \\<bullet> col B j)\" using A B * by auto\n    also have \"\\<dots> = row ?A i \\<bullet> col ?B j\" unfolding scalar_prod_def id using finite I\n    proof (induct I)\n      case (insert k I)\n      show ?case unfolding sum.insert[OF insert(1-2)] hom_add hom_mult\n        using insert(3-) * A B by auto\n    qed simp\n    also have \"\\<dots> = ?R $$ (i,j)\" using A B * by auto\n    finally\n    show \"?L $$ (i, j) = ?R $$ (i, j)\" .\n  qed auto\nqed\n\nlemma mult_mat_vec_hom: assumes A: \"A \\<in> carrier_mat nr n\" and v: \"v \\<in> carrier_vec n\"\n  shows \"vec\\<^sub>h (A *\\<^sub>v v) = mat\\<^sub>h A *\\<^sub>v vec\\<^sub>h v\"\nproof -\n  let ?L = \"vec\\<^sub>h (A *\\<^sub>v v)\"\n  let ?R = \"mat\\<^sub>h A *\\<^sub>v vec\\<^sub>h v\"\n  let ?A = \"mat\\<^sub>h A\"\n  let ?v = \"vec\\<^sub>h v\"\n  from A v have id:\n    \"dim_vec ?L = nr\" \"dim_vec ?R = nr\"\n    by auto\n  show ?thesis\n  proof (rule eq_vecI, unfold id)\n    fix i\n    assume *: \"i < nr\"\n    define I where \"I = {0 ..< n}\"\n    have id: \"{0 ..< dim_vec v} = I\" \"{0 ..< dim_vec (vec\\<^sub>h v)} = I\"\n      unfolding I_def using * v  by auto\n    have finite: \"finite I\" unfolding I_def by auto\n    have I: \"I \\<subseteq> {0 ..< n}\" unfolding I_def by auto\n    have \"?L $ i = hom (row A i \\<bullet> v)\" using A v * by auto\n    also have \"\\<dots> = row ?A i \\<bullet> ?v\" unfolding scalar_prod_def id using finite I\n    proof (induct I)\n      case (insert k I)\n      show ?case unfolding sum.insert[OF insert(1-2)] hom_add hom_mult\n        using insert(3-) * A v by auto\n    qed simp\n    also have \"\\<dots> = ?R $ i\" using A v * by auto\n    finally\n    show \"?L $ i = ?R $ i\" .\n  qed auto\nqed\nend\n\nlemma vec_eq_iff: \"(x = y) = (dim_vec x = dim_vec y \\<and> (\\<forall> i < dim_vec y. x $ i = y $ i))\" (is \"?l = ?r\")\nproof\n  assume ?r\n  show ?l\n    by (rule eq_vecI, insert \\<open>?r\\<close>, auto)\nqed simp\n\n\n\nlemma (in inj_semiring_hom) vec_hom_zero_iff[simp]: \"(vec\\<^sub>h x = 0\\<^sub>v n) = (x = 0\\<^sub>v n)\"\nproof -\n  {\n    fix i\n    assume i: \"i < n\" \"dim_vec x = n\"\n    hence \"vec\\<^sub>h x $ i = 0 \\<longleftrightarrow> x $ i = 0\"\n      using index_map_vec(1)[of i x] by simp\n  } note main = this\n  show ?thesis unfolding vec_eq_iff by (simp, insert main, auto)\nqed\n\nlemma (in inj_semiring_hom) mat_hom_inj: \"mat\\<^sub>h A = mat\\<^sub>h B \\<Longrightarrow> A = B\"\n  unfolding mat_eq_iff by auto\n\nlemma (in inj_semiring_hom) vec_hom_inj: \"vec\\<^sub>h v = vec\\<^sub>h w \\<Longrightarrow> v = w\"\n  unfolding vec_eq_iff by auto\n\nlemma (in semiring_hom) mat_hom_pow: assumes A: \"A \\<in> carrier_mat n n\"\n  shows \"mat\\<^sub>h (A ^\\<^sub>m k) = (mat\\<^sub>h A) ^\\<^sub>m k\"\nproof (induct k)\n  case (Suc k)\n  thus ?case using mat_hom_mult[OF pow_carrier_mat[OF A, of k] A] by simp\nqed (simp add: mat_hom_one)\n\nlemma (in semiring_hom) hom_sum_mat: \"hom (sum_mat A) = sum_mat (mat\\<^sub>h A)\"\nproof -\n  obtain B where id: \"?thesis = (hom (sum (($$) A) B) = sum (($$) (mat\\<^sub>h A)) B)\"\n    and B: \"B \\<subseteq> {0..<dim_row A} \\<times> {0..<dim_col A}\"\n  unfolding sum_mat_def by auto\n  from B have \"finite B\"\n    using finite_subset by blast\n  thus ?thesis unfolding id using B\n  proof (induct B)\n    case (insert x F)\n    show ?case unfolding sum.insert[OF insert(1-2)] hom_add\n      using insert(3-) by auto\n  qed simp\nqed\n\nlemma (in semiring_hom) vec_hom_smult: \"vec\\<^sub>h (ev \\<cdot>\\<^sub>v v) = hom ev \\<cdot>\\<^sub>v vec\\<^sub>h v\"\n  by (rule eq_vecI, auto simp: hom_distribs)\n\n\n\nlemma scalar_prod_minus_distrib: fixes v\\<^sub>1 :: \"'a :: ring vec\"\n  assumes v: \"v\\<^sub>1 \\<in> carrier_vec n\" \"v\\<^sub>2 \\<in> carrier_vec n\" \"v\\<^sub>3 \\<in> carrier_vec n\"\n  shows \"v\\<^sub>1 \\<bullet> (v\\<^sub>2 - v\\<^sub>3) = v\\<^sub>1 \\<bullet> v\\<^sub>2 - v\\<^sub>1 \\<bullet> v\\<^sub>3\"\n  unfolding minus_add_uminus_vec[OF v(2-3)]\n  by (subst scalar_prod_add_distrib[OF v(1)], insert v, auto)\n\nlemma uminus_add_minus_vec:\n  assumes \"l \\<in> carrier_vec n\" \"r \\<in> carrier_vec n\"\n  shows \"- ((l::'a :: ab_group_add vec) + r) = (- l - r)\"\n  using assms by auto\n\nlemma minus_add_minus_vec: fixes u :: \"'a :: ab_group_add vec\"\n  assumes \"u \\<in> carrier_vec n\" \"v \\<in> carrier_vec n\" \"w \\<in> carrier_vec n\"\n  shows \"u - (v + w) = u - v - w\"\n  using assms by auto\n\nlemma uminus_add_minus_mat:\n  assumes \"l \\<in> carrier_mat nr nc\" \"r \\<in> carrier_mat nr nc\"\n  shows \"- ((l::'a :: ab_group_add mat) + r) = (- l - r)\"\n  using assms by auto\n\nlemma minus_add_minus_mat: fixes u :: \"'a :: ab_group_add mat\"\n  assumes \"u \\<in> carrier_mat nr nc\" \"v \\<in> carrier_mat nr nc\" \"w \\<in> carrier_mat nr nc\"\n  shows \"u - (v + w) = u - v - w\"\n  using assms by auto\n\nlemma uminus_uminus_vec[simp]: \"- (- (v::'a:: group_add vec)) = v\"\n  by auto\n\nlemma uminus_eq_vec[simp]: \"- (v::'a:: group_add vec) = - w \\<longleftrightarrow> v = w\"\n  by (metis uminus_uminus_vec)\n\nlemma uminus_uminus_mat[simp]: \"- (- (A::'a:: group_add mat)) = A\"\n  by auto\n\nlemma uminus_eq_mat[simp]: \"- (A::'a:: group_add mat) = - B \\<longleftrightarrow> A = B\"\n  by (metis uminus_uminus_mat)\n\nlemma smult_zero_mat[simp]: \"(k :: 'a :: mult_zero) \\<cdot>\\<^sub>m 0\\<^sub>m nr nc = 0\\<^sub>m nr nc\"\n  by (intro eq_matI, auto)\n\nlemma similar_mat_wit_smult: fixes A :: \"'a :: comm_ring_1 mat\"\n  assumes \"similar_mat_wit A B P Q\"\n  shows \"similar_mat_wit (k \\<cdot>\\<^sub>m A) (k \\<cdot>\\<^sub>m B) P Q\"\nproof -\n  define n where \"n = dim_row A\"\n  note main = similar_mat_witD[OF n_def assms]\n  show ?thesis\n    by (rule similar_mat_witI[OF main(1-2) _ _ _ main(6-7)], insert main(3-), auto\n      simp: mult_smult_distrib mult_smult_assoc_mat[of _ n n _ n])\nqed\n\nlemma similar_mat_smult: fixes A :: \"'a :: comm_ring_1 mat\"\n  assumes \"similar_mat A B\"\n  shows \"similar_mat (k \\<cdot>\\<^sub>m A) (k \\<cdot>\\<^sub>m B)\"\n  using similar_mat_wit_smult assms unfolding similar_mat_def by blast\n\ndefinition mat_diag :: \"nat \\<Rightarrow> (nat \\<Rightarrow> 'a :: zero) \\<Rightarrow> 'a mat\" where\n  \"mat_diag n f = Matrix.mat n n (\\<lambda> (i,j). if i = j then f j else 0)\"\n\nlemma mat_diag_dim[simp]: \"mat_diag n f \\<in> carrier_mat n n\"\n  unfolding mat_diag_def by auto\n\nlemma mat_diag_mult_left: assumes A: \"A \\<in> carrier_mat n nr\"\n  shows \"mat_diag n f * A = Matrix.mat n nr (\\<lambda> (i,j). f i * A $$ (i,j))\"\nproof (rule eq_matI, insert A, auto simp: mat_diag_def scalar_prod_def, goal_cases)\n  case (1 i j)\n  thus ?case by (subst sum.remove[of _ i], auto)\nqed\n\nlemma mat_diag_mult_right: assumes A: \"A \\<in> carrier_mat nr n\"\n  shows \"A * mat_diag n f = Matrix.mat nr n (\\<lambda> (i,j). A $$ (i,j) * f j)\"\nproof (rule eq_matI, insert A, auto simp: mat_diag_def scalar_prod_def, goal_cases)\n  case (1 i j)\n  thus ?case by (subst sum.remove[of _ j], auto)\nqed\n\nlemma mat_diag_diag[simp]: \"mat_diag n f * mat_diag n g = mat_diag n (\\<lambda> i. f i * g i)\"\n  by (subst mat_diag_mult_left[of _ n n], auto simp: mat_diag_def)\n\nlemma mat_diag_one[simp]: \"mat_diag n (\\<lambda> x. 1) = 1\\<^sub>m n\" unfolding mat_diag_def by auto\n\ntext \\<open>Interpret vector as row-matrix\\<close>\n\ndefinition \"mat_of_row y = mat 1 (dim_vec y) (\\<lambda> ij. y $ (snd ij))\" \n\nlemma mat_of_row_carrier[simp,intro]: \n  \"y \\<in> carrier_vec n \\<Longrightarrow> mat_of_row y \\<in> carrier_mat 1 n\"\n  \"y \\<in> carrier_vec n \\<Longrightarrow> mat_of_row y \\<in> carrier_mat (Suc 0) n\"\n  unfolding mat_of_row_def by auto\n\nlemma mat_of_row_dim[simp]: \"dim_row (mat_of_row y) = 1\" \n  \"dim_col (mat_of_row y) = dim_vec y\" \n  unfolding mat_of_row_def by auto\n\nlemma mat_of_row_index[simp]: \"x < dim_vec y \\<Longrightarrow> mat_of_row y $$ (0,x) = y $ x\" \n  unfolding mat_of_row_def by auto\n\nlemma row_mat_of_row[simp]: \"row (mat_of_row y) 0 = y\" \n  by auto\n\nlemma mat_of_row_mult_append_rows: assumes y1: \"y1 \\<in> carrier_vec nr1\" \n  and y2: \"y2 \\<in> carrier_vec nr2\" \n  and A1: \"A1 \\<in> carrier_mat nr1 nc\" \n  and A2: \"A2 \\<in> carrier_mat nr2 nc\" \nshows \"mat_of_row (y1 @\\<^sub>v y2) * (A1 @\\<^sub>r A2) = \n  mat_of_row y1 * A1 + mat_of_row y2 * A2\" \nproof -\n  from A1 A2 have dim: \"dim_row A1 = nr1\" \"dim_row A2 = nr2\" by auto\n  let ?M1 = \"mat_of_row y1\" \n  have M1: \"?M1 \\<in> carrier_mat 1 nr1\" using y1 by auto\n  let ?M2 = \"mat_of_row y2\" \n  have M2: \"?M2 \\<in> carrier_mat 1 nr2\" using y2 by auto\n  let ?M3 = \"0\\<^sub>m 0 nr1\" \n  let ?M4 = \"0\\<^sub>m 0 nr2\" \n  note z = zero_carrier_mat\n  have id: \"mat_of_row (y1 @\\<^sub>v y2) = four_block_mat \n    ?M1 ?M2 ?M3 ?M4\" using y1 y2 \n    by (intro eq_matI, auto simp: mat_of_rows_def)\n  show ?thesis\n    unfolding id append_rows_def dim\n    by (subst mult_four_block_mat[OF M1 M2 z z A1 z A2 z], insert A1 A2, auto)\nqed\n\n\ntext \\<open>Allowing to construct and deconstruct vectors like lists\\<close>\nabbreviation vNil where \"vNil \\<equiv> vec 0 ((!) [])\"\ndefinition vCons where \"vCons a v \\<equiv> vec (Suc (dim_vec v)) (\\<lambda>i. case i of 0 \\<Rightarrow> a | Suc i \\<Rightarrow> v $ i)\"\n\nlemma vec_index_vCons_0 [simp]: \"vCons a v $ 0 = a\"\n  by (simp add: vCons_def)\n\nlemma vec_index_vCons_Suc [simp]:\n  fixes v :: \"'a vec\"\n  shows \"vCons a v $ Suc n = v $ n\"\nproof-\n  have 1: \"vec (Suc d) f $ Suc n = vec d (f \\<circ> Suc) $ n\" for d and f :: \"nat \\<Rightarrow> 'a\"\n    by (transfer, auto simp: mk_vec_def)\n  show ?thesis\n    apply (auto simp: 1 vCons_def o_def) apply transfer apply (auto simp: mk_vec_def)\n    done\nqed\n\nlemma vec_index_vCons: \"vCons a v $ n = (if n = 0 then a else v $ (n - 1))\"\n  by (cases n, auto)\n\nlemma dim_vec_vCons [simp]: \"dim_vec (vCons a v) = Suc (dim_vec v)\"\n  by (simp add: vCons_def)\n\nlemma vCons_carrier_vec[simp]: \"vCons a v \\<in> carrier_vec (Suc n) \\<longleftrightarrow> v \\<in> carrier_vec n\"\n  by (auto dest!: carrier_vecD intro: carrier_vecI)\n\nlemma vec_Suc: \"vec (Suc n) f = vCons (f 0) (vec n (f \\<circ> Suc))\" (is \"?l = ?r\")\nproof (unfold vec_eq_iff, intro conjI allI impI)\n  fix i assume \"i < dim_vec ?r\"\n  then show \"?l $ i = ?r $ i\" by (cases i, auto)\nqed simp\n\ndeclare Abs_vec_cases[cases del]\n\nlemma vec_cases [case_names vNil vCons, cases type: vec]:\n  assumes \"v = vNil \\<Longrightarrow> thesis\" and \"\\<And>a w. v = vCons a w \\<Longrightarrow> thesis\"\n  shows \"thesis\"\nproof (cases \"dim_vec v\")\n  case 0 then show thesis by (intro assms(1), auto)\nnext\n  case (Suc n)\n  show thesis\n  proof (rule assms(2))\n    show v: \"v = vCons (v $ 0) (vec n (\\<lambda>i. v $ Suc i))\" (is \"v = ?r\")\n    proof (rule eq_vecI, unfold dim_vec_vCons dim_vec Suc)\n      fix i\n      assume \"i < Suc n\"\n      then show \"v $ i = ?r $ i\" by (cases i, auto simp: vCons_def)\n    qed simp\n  qed\nqed\n\nlemma vec_induct [case_names vNil vCons, induct type: vec]:\n  assumes \"P vNil\" and \"\\<And>a v. P v \\<Longrightarrow> P (vCons a v)\"\n  shows \"P v\"\nproof (induct \"dim_vec v\" arbitrary:v)\n  case 0 then show ?case by (cases v, auto intro: assms(1))\nnext\n  case (Suc n) then show ?case by (cases v, auto intro: assms(2))\nqed\n\nlemma carrier_vec_induct [consumes 1, case_names 0 Suc, induct set:carrier_vec]:\n  assumes v: \"v \\<in> carrier_vec n\"\n    and 1: \"P 0 vNil\" and 2: \"\\<And>n a v. v \\<in> carrier_vec n \\<Longrightarrow> P n v \\<Longrightarrow> P (Suc n) (vCons a v)\"\n  shows \"P n v\"\nproof (insert v, induct n arbitrary: v)\n  case 0 then have \"v = vec 0 ((!) [])\" by auto\n  with 1 show ?case by auto\nnext\n  case (Suc n) then show ?case by (cases v, auto dest!: carrier_vecD intro:2)\nqed\n\n\n\nlemma vec_of_list_Nil[simp]: \"vec_of_list [] = vNil\"\n  by (transfer', auto)\n\nlemma scalar_prod_vCons[simp]:\n  \"vCons a v \\<bullet> vCons b w = a * b + v \\<bullet> w\"\n  apply (unfold scalar_prod_def atLeast0_lessThan_Suc_eq_insert_0 dim_vec_vCons)\n  apply (subst sum.insert) apply (simp,simp)\n  apply (subst sum.reindex) apply force\n  apply simp\n  done\n\nlemma zero_vec_Suc: \"0\\<^sub>v (Suc n) = vCons 0 (0\\<^sub>v n)\"\n  by (auto simp: zero_vec_def vec_Suc o_def)\n\nlemma zero_vec_zero[simp]: \"0\\<^sub>v 0 = vNil\" by auto\n\nlemma vCons_eq_vCons[simp]: \"vCons a v = vCons b w \\<longleftrightarrow> a = b \\<and> v = w\" (is \"?l \\<longleftrightarrow> ?r\")\nproof\n  assume ?l\n  note arg_cong[OF this]\n  from this[of dim_vec] this[of \"\\<lambda>x. x$0\"] this[of \"\\<lambda>x. x$Suc _\"]\n  show ?r by (auto simp: vec_eq_iff)\nqed simp\n\nlemma vec_carrier_vec[simp]: \"vec n f \\<in> carrier_vec m \\<longleftrightarrow> n = m\"\n  unfolding carrier_vec_def by auto\n\nnotation transpose_mat (\"(_\\<^sup>T)\" [1000])\n\nlemma map_mat_transpose: \"(map_mat f A)\\<^sup>T = map_mat f A\\<^sup>T\" by auto\n\nlemma cols_transpose[simp]: \"cols A\\<^sup>T = rows A\" unfolding cols_def rows_def by auto\nlemma rows_transpose[simp]: \"rows A\\<^sup>T = cols A\" unfolding cols_def rows_def by auto\nlemma list_of_vec_vec [simp]: \"list_of_vec (vec n f) = map f [0..<n]\"\n  by (transfer, auto simp: mk_vec_def)\n\nlemma list_of_vec_0 [simp]: \"list_of_vec (0\\<^sub>v n) = replicate n 0\"\n  by (simp add: zero_vec_def map_replicate_trivial)\n\nlemma diag_mat_map:\n  assumes M_carrier: \"M \\<in> carrier_mat n n\"\n  shows \"diag_mat (map_mat f M) = map f (diag_mat M)\"\nproof -\n  have dim_eq: \"dim_row M = dim_col M\" using M_carrier by auto\n  have m: \"map_mat f M $$ (i, i) = f (M $$ (i, i))\" if i: \"i < dim_row M\" for i\n    using dim_eq i by auto\n  show ?thesis\n    by (rule nth_equalityI, insert m, auto simp add: diag_mat_def M_carrier)\nqed\n\nlemma mat_of_rows_map [simp]:\n  assumes x: \"set vs \\<subseteq> carrier_vec n\"\n  shows \"mat_of_rows n (map (map_vec f) vs) = map_mat f (mat_of_rows n vs)\"\nproof-\n  have \"\\<forall>x\\<in>set vs. dim_vec x = n\" using x by auto\n  then show ?thesis by (auto simp add: mat_eq_iff map_vec_def mat_of_rows_def)\nqed\n\nlemma mat_of_cols_map [simp]:\n  assumes x: \"set vs \\<subseteq> carrier_vec n\"\n  shows \"mat_of_cols n (map (map_vec f) vs) = map_mat f (mat_of_cols n vs)\"\nproof-\n  have \"\\<forall>x\\<in>set vs. dim_vec x = n\" using x by auto\n  then show ?thesis by (auto simp add: mat_eq_iff map_vec_def mat_of_cols_def)\nqed\n\nlemma vec_of_list_map [simp]: \"vec_of_list (map f xs) = map_vec f (vec_of_list xs)\"\n  unfolding map_vec_def by (transfer, auto simp add: mk_vec_def)\n\nlemma map_vec: \"map_vec f (vec n g) = vec n (f o g)\" by auto\n\nlemma mat_of_cols_Cons_index_0: \"i < n \\<Longrightarrow> mat_of_cols n (w # ws) $$ (i, 0) = w $ i\"\n  by (unfold mat_of_cols_def, transfer', auto simp: mk_mat_def)\n\nlemma nth_map_out_of_bound: \"i \\<ge> length xs \\<Longrightarrow> map f xs ! i = [] ! (i - length xs)\"\n  by (induct xs arbitrary:i, auto)\n\nlemma mat_of_cols_Cons_index_Suc:\n  \"i < n \\<Longrightarrow> mat_of_cols n (w # ws) $$ (i, Suc j) = mat_of_cols n ws $$ (i,j)\"\n  by (unfold mat_of_cols_def, transfer, auto simp: mk_mat_def undef_mat_def nth_append nth_map_out_of_bound)\n\nlemma mat_of_cols_index: \"i < n \\<Longrightarrow> j < length ws \\<Longrightarrow> mat_of_cols n ws $$ (i,j) = ws ! j $ i\"\n  by (unfold mat_of_cols_def, auto)\n\nlemma mat_of_rows_index: \"i < length rs \\<Longrightarrow> j < n \\<Longrightarrow> mat_of_rows n rs $$ (i,j) = rs ! i $ j\"\n  by (unfold mat_of_rows_def, auto)\n\nlemma transpose_mat_of_rows: \"(mat_of_rows n vs)\\<^sup>T = mat_of_cols n vs\"\n  by (auto intro!: eq_matI simp: mat_of_rows_index mat_of_cols_index)\n\nlemma transpose_mat_of_cols: \"(mat_of_cols n vs)\\<^sup>T = mat_of_rows n vs\"\n  by (auto intro!: eq_matI simp: mat_of_rows_index mat_of_cols_index)\n\nlemma nth_list_of_vec [simp]:\n  assumes \"i < dim_vec v\" shows \"list_of_vec v ! i = v $ i\"\n  using assms by (transfer, auto)\n\nlemma length_list_of_vec [simp]:\n  \"length (list_of_vec v) = dim_vec v\" by (transfer, auto)\n\nlemma vec_eq_0_iff:\n  \"v = 0\\<^sub>v n \\<longleftrightarrow> n = dim_vec v \\<and> (n = 0 \\<or> set (list_of_vec v) = {0})\" (is \"?l \\<longleftrightarrow> ?r\")\nproof\n  show \"?l \\<Longrightarrow> ?r\" by auto\n  show \"?r \\<Longrightarrow> ?l\" by (intro iffI eq_vecI, force simp: set_conv_nth, force)\nqed\n\nlemma list_of_vec_vCons[simp]: \"list_of_vec (vCons a v) = a # list_of_vec v\" (is \"?l = ?r\")\nproof (intro nth_equalityI)\n  fix i\n  assume \"i < length ?l\"\n  then show \"?l ! i = ?r ! i\" by (cases i, auto)\nqed simp\n\nlemma append_vec_vCons[simp]: \"vCons a v @\\<^sub>v w = vCons a (v @\\<^sub>v w)\" (is \"?l = ?r\")\nproof (unfold vec_eq_iff, intro conjI allI impI)\n  fix i assume \"i < dim_vec ?r\"\n  then show \"?l $ i = ?r $ i\" by (cases i; subst index_append_vec, auto)\nqed simp\n\n\n\nlemma list_of_vec_append[simp]: \"list_of_vec (v @\\<^sub>v w) = list_of_vec v @ list_of_vec w\"\n  by (induct v, auto)\n\nlemma transpose_mat_eq[simp]: \"A\\<^sup>T = B\\<^sup>T \\<longleftrightarrow> A = B\"\n  using transpose_transpose by metis\n\nlemma mat_col_eqI: assumes cols: \"\\<And> i. i < dim_col B \\<Longrightarrow> col A i = col B i\"\n  and dims: \"dim_row A = dim_row B\" \"dim_col A = dim_col B\"\nshows \"A = B\"\n  by(subst transpose_mat_eq[symmetric], rule eq_rowI,insert assms,auto)\n\nlemma upper_triangular_imp_distinct:\n  assumes A: \"A \\<in> carrier_mat n n\"\n    and tri: \"upper_triangular A\"\n    and diag: \"0 \\<notin> set (diag_mat A)\"\n  shows \"distinct (rows A)\"\nproof-\n  { fix i and j\n    assume eq: \"rows A ! i = rows A ! j\" and ij: \"i < j\" and jn: \"j < n\"\n    from tri A ij jn have \"rows A ! j $ i = 0\" by (auto dest!:upper_triangularD)\n    with eq have \"rows A ! i $ i = 0\" by auto\n    with diag ij jn A have False by (auto simp: diag_mat_def)\n  }\n  with A show ?thesis by (force simp: distinct_conv_nth nat_neq_iff)\nqed\n\nlemma dim_vec_of_list[simp] :\"dim_vec (vec_of_list as) = length as\" by transfer auto\n\nlemma list_vec: \"list_of_vec (vec_of_list xs) = xs\"\nby (transfer, metis (mono_tags, lifting) atLeastLessThan_iff map_eq_conv map_nth mk_vec_def old.prod.case set_upt)\n\nlemma vec_list: \"vec_of_list (list_of_vec v) = v\"\napply transfer unfolding mk_vec_def by auto\n\nlemma index_vec_of_list: \"i<length xs \\<Longrightarrow> (vec_of_list xs) $ i = xs ! i\"\nby (metis vec.abs_eq index_vec vec_of_list.abs_eq)\n\nlemma vec_of_list_index: \"vec_of_list xs $ j = xs ! j\"\n  apply transfer unfolding mk_vec_def unfolding undef_vec_def\n  by (simp, metis append_Nil2 nth_append)\n\nlemma list_of_vec_index: \"list_of_vec v ! j = v $ j\"\n  by (metis vec_list vec_of_list_index)\n\nlemma list_of_vec_map: \"list_of_vec xs = map (($) xs) [0..<dim_vec xs]\" by transfer auto\n\ndefinition \"component_mult v w = vec (min (dim_vec v) (dim_vec w)) (\\<lambda>i. v $ i * w $ i)\"\ndefinition vec_set::\"'a vec \\<Rightarrow> 'a set\" (\"set\\<^sub>v\")\n  where \"vec_set v = vec_index v ` {..<dim_vec v}\"\n\nlemma index_component_mult:\nassumes \"i < dim_vec v\" \"i < dim_vec w\"\nshows \"component_mult v w $ i = v $ i * w $ i\"\n  unfolding component_mult_def using assms index_vec by auto\n\nlemma dim_component_mult:\n\"dim_vec (component_mult v w) = min (dim_vec v) (dim_vec w)\"\n  unfolding component_mult_def using index_vec by auto\n\nlemma vec_setE:\nassumes \"a \\<in> set\\<^sub>v v\"\nobtains i where \"v$i = a\" \"i<dim_vec v\" using assms unfolding vec_set_def by blast\n\nlemma vec_setI:\nassumes \"v$i = a\" \"i<dim_vec v\"\nshows \"a \\<in> set\\<^sub>v v\" using assms unfolding vec_set_def using image_eqI lessThan_iff by blast\n\nlemma set_list_of_vec: \"set (list_of_vec v) = set\\<^sub>v v\" unfolding vec_set_def by transfer auto\n\n\ninstantiation vec :: (conjugate) conjugate\nbegin\n\ndefinition conjugate_vec :: \"'a :: conjugate vec \\<Rightarrow> 'a vec\"\n  where \"conjugate v = vec (dim_vec v) (\\<lambda>i. conjugate (v $ i))\"\n\nlemma conjugate_vCons [simp]:\n  \"conjugate (vCons a v) = vCons (conjugate a) (conjugate v)\"\n  by (auto simp: vec_Suc conjugate_vec_def)\n\nlemma dim_vec_conjugate[simp]: \"dim_vec (conjugate v) = dim_vec v\"\n  unfolding conjugate_vec_def by auto\n\nlemma carrier_vec_conjugate[simp]: \"v \\<in> carrier_vec n \\<Longrightarrow> conjugate v \\<in> carrier_vec n\"\n  by (auto intro!: carrier_vecI)\n\nlemma vec_index_conjugate[simp]:\n  shows \"i < dim_vec v \\<Longrightarrow> conjugate v $ i = conjugate (v $ i)\"\n  unfolding conjugate_vec_def by auto\n\ninstance\nproof\n  fix v w :: \"'a vec\"\n  show \"conjugate (conjugate v) = v\" by (induct v, auto simp: conjugate_vec_def)\n  let ?v = \"conjugate v\"\n  let ?w = \"conjugate w\"\n  show \"conjugate v = conjugate w \\<longleftrightarrow> v = w\"\n  proof(rule iffI)\n    assume cvw: \"?v = ?w\" show \"v = w\"\n    proof(rule)\n      have \"dim_vec ?v = dim_vec ?w\" using cvw by auto\n      then show dim: \"dim_vec v = dim_vec w\" by simp\n      fix i assume i: \"i < dim_vec w\"\n      then have \"conjugate v $ i = conjugate w $ i\" using cvw by auto\n      then have \"conjugate (v$i) = conjugate (w $ i)\" using i dim by auto\n      then show \"v $ i = w $ i\" by auto\n    qed\n  qed auto\nqed\n\nend\n\nlemma conjugate_add_vec:\n  fixes v w :: \"'a :: conjugatable_ring vec\"\n  assumes dim: \"v : carrier_vec n\" \"w : carrier_vec n\"\n  shows \"conjugate (v + w) = conjugate v + conjugate w\"\n  by (rule, insert dim, auto simp: conjugate_dist_add)\n\nlemma uminus_conjugate_vec:\n  fixes v w :: \"'a :: conjugatable_ring vec\"\n  shows \"- (conjugate v) = conjugate (- v)\"\n  by (rule, auto simp:conjugate_neg)\n\nlemma conjugate_zero_vec[simp]:\n  \"conjugate (0\\<^sub>v n :: 'a :: conjugatable_ring vec) = 0\\<^sub>v n\" by auto\n\nlemma conjugate_vec_0[simp]:\n  \"conjugate (vec 0 f) = vec 0 f\" by auto\n\nlemma sprod_vec_0[simp]: \"v \\<bullet> vec 0 f = 0\"\n  by(auto simp: scalar_prod_def)\n\nlemma conjugate_zero_iff_vec[simp]:\n  fixes v :: \"'a :: conjugatable_ring vec\"\n  shows \"conjugate v = 0\\<^sub>v n \\<longleftrightarrow> v = 0\\<^sub>v n\"\n  using conjugate_cancel_iff[of _ \"0\\<^sub>v n :: 'a vec\"] by auto\n\nlemma conjugate_smult_vec:\n  fixes k :: \"'a :: conjugatable_ring\"\n  shows \"conjugate (k \\<cdot>\\<^sub>v v) = conjugate k \\<cdot>\\<^sub>v conjugate v\"\n  using conjugate_dist_mul by (intro eq_vecI, auto)\n\nlemma conjugate_sprod_vec:\n  fixes v w :: \"'a :: conjugatable_ring vec\"\n  assumes v: \"v : carrier_vec n\" and w: \"w : carrier_vec n\"\n  shows \"conjugate (v \\<bullet> w) = conjugate v \\<bullet> conjugate w\"\nproof (insert w v, induct w arbitrary: v rule:carrier_vec_induct)\n  case 0 then show ?case by (cases v, auto)\nnext\n  case (Suc n b w) then show ?case\n    by (cases v, auto dest: carrier_vecD simp:conjugate_dist_add conjugate_dist_mul)\nqed \n\nabbreviation cscalar_prod :: \"'a vec \\<Rightarrow> 'a vec \\<Rightarrow> 'a :: conjugatable_ring\" (infix \"\\<bullet>c\" 70)\n  where \"(\\<bullet>c) \\<equiv> \\<lambda>v w. v \\<bullet> conjugate w\"\n\nlemma conjugate_conjugate_sprod[simp]:\n  assumes v[simp]: \"v : carrier_vec n\" and w[simp]: \"w : carrier_vec n\"\n  shows \"conjugate (conjugate v \\<bullet> w) = v \\<bullet>c w\"\n  apply (subst conjugate_sprod_vec[of _ n]) by auto\n\nlemma conjugate_vec_sprod_comm:\n  fixes v w :: \"'a :: {conjugatable_ring, comm_ring} vec\"\n  assumes \"v : carrier_vec n\" and \"w : carrier_vec n\"\n  shows \"v \\<bullet>c w = (conjugate w \\<bullet> v)\"\n  unfolding scalar_prod_def using assms by(subst sum.ivl_cong, auto simp: ac_simps)\n\nlemma conjugate_square_ge_0_vec[intro!]:\n  fixes v :: \"'a :: conjugatable_ordered_ring vec\"\n  shows \"v \\<bullet>c v \\<ge> 0\"\nproof (induct v)\n  case vNil\n  then show ?case by auto\nnext\n  case (vCons a v)\n  then show ?case using conjugate_square_positive[of a] by auto\nqed\n\nlemma conjugate_square_eq_0_vec[simp]:\n  fixes v :: \"'a :: {conjugatable_ordered_ring,semiring_no_zero_divisors} vec\"\n  assumes \"v \\<in> carrier_vec n\"\n  shows \"v \\<bullet>c v = 0 \\<longleftrightarrow> v = 0\\<^sub>v n\"\nproof (insert assms, induct rule: carrier_vec_induct)\n  case 0\n  then show ?case by auto\nnext\n  case (Suc n a v)\n  then show ?case\n    using conjugate_square_positive[of a] conjugate_square_ge_0_vec[of v]\n    by (auto simp: le_less add_nonneg_eq_0_iff zero_vec_Suc)\nqed\n\nlemma conjugate_square_greater_0_vec[simp]:\n  fixes v :: \"'a :: {conjugatable_ordered_ring,semiring_no_zero_divisors} vec\"\n  assumes \"v \\<in> carrier_vec n\"\n  shows \"v \\<bullet>c v > 0 \\<longleftrightarrow> v \\<noteq> 0\\<^sub>v n\"\n  using assms by (auto simp: less_le)\n\nlemma vec_conjugate_rat[simp]: \"(conjugate :: rat vec \\<Rightarrow> rat vec) = (\\<lambda>x. x)\" by force\nlemma vec_conjugate_real[simp]: \"(conjugate :: real vec \\<Rightarrow> real vec) = (\\<lambda>x. x)\" by force\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/Jordan_Normal_Form/Matrix.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8633916099737806, "lm_q2_score": 0.8311430415844384, "lm_q1q2_score": 0.7176019287920932}}
{"text": "(*  Title:      HOL/Quotient_Examples/Quotient_Int.thy\n    Author:     Cezary Kaliszyk\n    Author:     Christian Urban\n\nIntegers based on Quotients, based on an older version by Larry\nPaulson.\n*)\n\ntheory Quotient_Int\nimports \"~~/src/HOL/Library/Quotient_Product\" Nat\nbegin\n\nfun\n  intrel :: \"(nat \\<times> nat) \\<Rightarrow> (nat \\<times> nat) \\<Rightarrow> bool\" (infix \"\\<approx>\" 50)\nwhere\n  \"intrel (x, y) (u, v) = (x + v = u + y)\"\n\nquotient_type int = \"nat \\<times> nat\" / intrel\n  by (auto simp add: equivp_def fun_eq_iff)\n\ninstantiation int :: \"{zero, one, plus, uminus, minus, times, ord, abs, sgn}\"\nbegin\n\nquotient_definition\n  \"0 \\<Colon> int\" is \"(0\\<Colon>nat, 0\\<Colon>nat)\" done\n\nquotient_definition\n  \"1 \\<Colon> int\" is \"(1\\<Colon>nat, 0\\<Colon>nat)\" done\n\nfun\n  plus_int_raw :: \"(nat \\<times> nat) \\<Rightarrow> (nat \\<times> nat) \\<Rightarrow> (nat \\<times> nat)\"\nwhere\n  \"plus_int_raw (x, y) (u, v) = (x + u, y + v)\"\n\nquotient_definition\n  \"(op +) \\<Colon> (int \\<Rightarrow> int \\<Rightarrow> int)\" is \"plus_int_raw\" by auto\n\nfun\n  uminus_int_raw :: \"(nat \\<times> nat) \\<Rightarrow> (nat \\<times> nat)\"\nwhere\n  \"uminus_int_raw (x, y) = (y, x)\"\n\nquotient_definition\n  \"(uminus \\<Colon> (int \\<Rightarrow> int))\" is \"uminus_int_raw\" by auto\n\ndefinition\n  minus_int_def:  \"z - w = z + (-w\\<Colon>int)\"\n\nfun\n  times_int_raw :: \"(nat \\<times> nat) \\<Rightarrow> (nat \\<times> nat) \\<Rightarrow> (nat \\<times> nat)\"\nwhere\n  \"times_int_raw (x, y) (u, v) = (x*u + y*v, x*v + y*u)\"\n\nlemma times_int_raw_fst:\n  assumes a: \"x \\<approx> z\"\n  shows \"times_int_raw x y \\<approx> times_int_raw z y\"\n  using a\n  apply(cases x, cases y, cases z)\n  apply(auto simp add: times_int_raw.simps intrel.simps)\n  apply(hypsubst_thin)\n  apply(rename_tac u v w x y z)\n  apply(subgoal_tac \"u*w + z*w = y*w + v*w  &  u*x + z*x = y*x + v*x\")\n  apply(simp add: ac_simps)\n  apply(simp add: add_mult_distrib [symmetric])\ndone\n\nlemma times_int_raw_snd:\n  assumes a: \"x \\<approx> z\"\n  shows \"times_int_raw y x \\<approx> times_int_raw y z\"\n  using a\n  apply(cases x, cases y, cases z)\n  apply(auto simp add: times_int_raw.simps intrel.simps)\n  apply(hypsubst_thin)\n  apply(rename_tac u v w x y z)\n  apply(subgoal_tac \"u*w + z*w = y*w + v*w  &  u*x + z*x = y*x + v*x\")\n  apply(simp add: ac_simps)\n  apply(simp add: add_mult_distrib [symmetric])\ndone\n\nquotient_definition\n  \"(op *) :: (int \\<Rightarrow> int \\<Rightarrow> int)\" is \"times_int_raw\"\n  apply(rule equivp_transp[OF int_equivp])\n  apply(rule times_int_raw_fst)\n  apply(assumption)\n  apply(rule times_int_raw_snd)\n  apply(assumption)\ndone\n\nfun\n  le_int_raw :: \"(nat \\<times> nat) \\<Rightarrow> (nat \\<times> nat) \\<Rightarrow> bool\"\nwhere\n  \"le_int_raw (x, y) (u, v) = (x+v \\<le> u+y)\"\n\nquotient_definition\n  le_int_def: \"(op \\<le>) :: int \\<Rightarrow> int \\<Rightarrow> bool\" is \"le_int_raw\" by auto\n\ndefinition\n  less_int_def: \"(z\\<Colon>int) < w = (z \\<le> w \\<and> z \\<noteq> w)\"\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 ..\n\nend\n\n\ntext{* The integers form a @{text comm_ring_1}*}\n\ninstance int :: comm_ring_1\nproof\n  fix i j k :: int\n  show \"(i + j) + k = i + (j + k)\"\n    by (descending) (auto)\n  show \"i + j = j + i\"\n    by (descending) (auto)\n  show \"0 + i = (i::int)\"\n    by (descending) (auto)\n  show \"- i + i = 0\"\n    by (descending) (auto)\n  show \"i - j = i + - j\"\n    by (simp add: minus_int_def)\n  show \"(i * j) * k = i * (j * k)\"\n    by (descending) (auto simp add: algebra_simps)\n  show \"i * j = j * i\"\n    by (descending) (auto)\n  show \"1 * i = i\"\n    by (descending) (auto)\n  show \"(i + j) * k = i * k + j * k\"\n    by (descending) (auto simp add: algebra_simps)\n  show \"0 \\<noteq> (1::int)\"\n    by (descending) (auto)\nqed\n\nlemma plus_int_raw_rsp_aux:\n  assumes a: \"a \\<approx> b\" \"c \\<approx> d\"\n  shows \"plus_int_raw a c \\<approx> plus_int_raw b d\"\n  using a\n  by (cases a, cases b, cases c, cases d)\n     (simp)\n\nlemma add_abs_int:\n  \"(abs_int (x,y)) + (abs_int (u,v)) =\n   (abs_int (x + u, y + v))\"\n  apply(simp add: plus_int_def id_simps)\n  apply(fold plus_int_raw.simps)\n  apply(rule Quotient3_rel_abs[OF Quotient3_int])\n  apply(rule plus_int_raw_rsp_aux)\n  apply(simp_all add: rep_abs_rsp_left[OF Quotient3_int])\n  done\n\ndefinition int_of_nat_raw:\n  \"int_of_nat_raw m = (m :: nat, 0 :: nat)\"\n\nquotient_definition\n  \"int_of_nat :: nat \\<Rightarrow> int\" is \"int_of_nat_raw\" done\n\nlemma int_of_nat:\n  shows \"of_nat m = int_of_nat m\"\n  by (induct m)\n     (simp_all add: zero_int_def one_int_def int_of_nat_def int_of_nat_raw add_abs_int)\n\ninstance int :: linorder\nproof\n  fix i j k :: int\n  show antisym: \"i \\<le> j \\<Longrightarrow> j \\<le> i \\<Longrightarrow> i = j\"\n    by (descending) (auto)\n  show \"(i < j) = (i \\<le> j \\<and> \\<not> j \\<le> i)\"\n    by (auto simp add: less_int_def dest: antisym)\n  show \"i \\<le> i\"\n    by (descending) (auto)\n  show \"i \\<le> j \\<Longrightarrow> j \\<le> k \\<Longrightarrow> i \\<le> k\"\n    by (descending) (auto)\n  show \"i \\<le> j \\<or> j \\<le> i\"\n    by (descending) (auto)\nqed\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 default\n     (auto simp add: inf_int_def sup_int_def max_min_distrib2)\n\nend\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 (descending) (auto)\nqed\n\nabbreviation\n  \"less_int_raw i j \\<equiv> le_int_raw i j \\<and> \\<not>(i \\<approx> j)\"\n\nlemma zmult_zless_mono2_lemma:\n  fixes i j::int\n  and   k::nat\n  shows \"i < j \\<Longrightarrow> 0 < k \\<Longrightarrow> of_nat k * i < of_nat k * j\"\n  apply(induct \"k\")\n  apply(simp)\n  apply(case_tac \"k = 0\")\n  apply(simp_all add: distrib_right add_strict_mono)\n  done\n\nlemma zero_le_imp_eq_int_raw:\n  fixes k::\"(nat \\<times> nat)\"\n  shows \"less_int_raw (0, 0) k \\<Longrightarrow> (\\<exists>n > 0. k \\<approx> int_of_nat_raw n)\"\n  apply(cases k)\n  apply(simp add:int_of_nat_raw)\n  apply(auto)\n  apply(rule_tac i=\"b\" and j=\"a\" in less_Suc_induct)\n  apply(auto)\n  done\n\nlemma zero_le_imp_eq_int:\n  fixes k::int\n  shows \"0 < k \\<Longrightarrow> \\<exists>n > 0. k = of_nat n\"\n  unfolding less_int_def int_of_nat\n  by (descending) (rule zero_le_imp_eq_int_raw)\n\nlemma zmult_zless_mono2:\n  fixes i j k::int\n  assumes a: \"i < j\" \"0 < k\"\n  shows \"k * i < k * j\"\n  using a\n  by (drule_tac zero_le_imp_eq_int) (auto simp add: zmult_zless_mono2_lemma)\n\ntext{*The integers form an ordered integral domain*}\n\ninstance int :: linordered_idom\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\\<Colon>int) = (if i=0 then 0 else if 0<i then 1 else - 1)\"\n    by (simp only: zsgn_def)\nqed\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  minus_add_distrib[of z1 z2]\n  for z1 z2 w :: int\n\nlemma int_induct2:\n  assumes \"P 0 0\"\n  and     \"\\<And>n m. P n m \\<Longrightarrow> P (Suc n) m\"\n  and     \"\\<And>n m. P n m \\<Longrightarrow> P n (Suc m)\"\n  shows   \"P n m\"\nusing assms\nby (induction_schema) (pat_completeness, lexicographic_order)\n\n\nlemma int_induct:\n  fixes j :: int\n  assumes a: \"P 0\"\n  and     b: \"\\<And>i::int. P i \\<Longrightarrow> P (i + 1)\"\n  and     c: \"\\<And>i::int. P i \\<Longrightarrow> P (i - 1)\"\n  shows      \"P j\"\nusing a b c \nunfolding minus_int_def\nby (descending) (auto intro: int_induct2)\n  \n\ntext {* Magnitide of an Integer, as a Natural Number: @{term nat} *}\n\ndefinition\n  \"int_to_nat_raw \\<equiv> \\<lambda>(x, y).x - (y::nat)\"\n\nquotient_definition\n  \"int_to_nat::int \\<Rightarrow> nat\"\nis\n  \"int_to_nat_raw\" \nunfolding int_to_nat_raw_def by auto \n\nlemma nat_le_eq_zle:\n  fixes w z::\"int\"\n  shows \"0 < w \\<or> 0 \\<le> z \\<Longrightarrow> (int_to_nat w \\<le> int_to_nat z) = (w \\<le> z)\"\n  unfolding less_int_def\n  by (descending) (auto simp add: int_to_nat_raw_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/Quotient_Examples/Quotient_Int.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391599428538, "lm_q2_score": 0.8311430499496096, "lm_q1q2_score": 0.7176019272499068}}
{"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  theory TIP_prop_77\n  imports \"../../Test_Base\"\nbegin\n\ndatatype 'a list = nil2 | cons2 \"'a\" \"'a list\"\n\ndatatype Nat = Z | S \"Nat\"\n\nfun x :: \"bool => bool => bool\" where\n  \"x True z = z\"\n| \"x False z = False\"\n\nfun t2 :: \"Nat => Nat => bool\" where\n  \"t2 (Z) z = True\"\n| \"t2 (S z2) (Z) = False\"\n| \"t2 (S z2) (S x2) = t2 z2 x2\"\n\nfun insort :: \"Nat => Nat list => Nat list\" where\n  \"insort y (nil2) = cons2 y (nil2)\"\n| \"insort y (cons2 z2 xs) =\n     (if t2 y z2 then cons2 y (cons2 z2 xs) else cons2 z2 (insort y xs))\"\n\nfun sorted :: \"Nat list => bool\" where\n  \"sorted (nil2) = True\"\n| \"sorted (cons2 z (nil2)) = True\"\n| \"sorted (cons2 z (cons2 y2 ys)) =\n     x (t2 z y2) (sorted (cons2 y2 ys))\"\n\ntheorem property0 :\n  \"((sorted xs) ==> (sorted (insort y 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/Isaplanner/Isaplanner/TIP_prop_77.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505299595162, "lm_q2_score": 0.7931059487389968, "lm_q1q2_score": 0.7174837168407783}}
{"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_25\n  imports \"../../Test_Base\"\nbegin\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 max :: \"Nat => Nat => Nat\" where\n  \"max (Z) z = z\"\n| \"max (S z2) (Z) = S z2\"\n| \"max (S z2) (S x2) = S (max z2 x2)\"\n\nfun t2 :: \"Nat => Nat => bool\" where\n  \"t2 (Z) z = True\"\n| \"t2 (S z2) (Z) = False\"\n| \"t2 (S z2) (S x2) = t2 z2 x2\"\n\ntheorem property0 :(*This problem is very similar to TIP_prop_24.thy*)\n  \"((x (max a b) b) = (t2 a b))\"\n  apply(induct rule:x.induct)\n     apply fastforce\n    apply clarsimp\n    apply(induct_tac z2)\n     apply fastforce+\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/Isaplanner/Isaplanner/TIP_prop_25.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094174159127, "lm_q2_score": 0.8031737987125612, "lm_q1q2_score": 0.7174827182116437}}
{"text": "theory Imp_List_Sum\nimports \"Separation_Logic_Imperative_HOL.Imp_List_Spec\"\nbegin\n\ntext \"A general sum operation can be defined for list iterators\nover elements of a monoid\"\n\nlocale imp_list_iterate_sum = imp_list_iterate is_list is_it\n  for is_list :: \"('a ::{monoid_add}) list \\<Rightarrow> 'b \\<Rightarrow> assn\"\n  and is_it :: \"'a list \\<Rightarrow> 'b \\<Rightarrow> 'a list \\<Rightarrow> 'it \\<Rightarrow> assn\"\nbegin\nsubsubsection \\<open>List-Sum\\<close>\n\npartial_function (heap) it_sum' :: \"'it \\<Rightarrow> 'a \\<Rightarrow> 'a Heap\"\n  where [code]:\n  \"it_sum' it s = do {\n    b \\<leftarrow> it_has_next it;\n    if b then do {\n      (x,it') \\<leftarrow> it_next it;\n      it_sum' it' (s+x)\n    } else return s\n  }\"\n\nlemma it_sum'_rule[sep_heap_rules]: \n  \"<is_it l p l' it> \n    it_sum' it s \n  <\\<lambda>r. is_list l p * \\<up>(r = s + sum_list l')>\\<^sub>t\"\nproof (induct l' arbitrary: it s)\n  case Nil thus ?case\n    apply (subst it_sum'.simps)\n    apply (sep_auto intro: quit_iteration ent_true_drop(1))\n    done\nnext\n  case (Cons x l')\n  show ?case\n    apply (subst it_sum'.simps)\n    apply (sep_auto heap: Cons.hyps simp add: add.assoc)\n    done\nqed\n\ndefinition \"it_sum p \\<equiv> do { \n  it \\<leftarrow> it_init p;\n  it_sum' it 0}\"\n\nlemma it_sum_rule[sep_heap_rules]: \n  \"<is_list l p> it_sum p <\\<lambda>r. is_list l p * \\<up>(r=sum_list l)>\\<^sub>t\"\n  unfolding it_sum_def\n  by sep_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/BTree/Imp_List_Sum.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094060543487, "lm_q2_score": 0.8031737987125612, "lm_q1q2_score": 0.717482709086333}}
{"text": "theory Desargues_Property\n  imports Main Projective_Plane_Axioms Pappus_Property Pascal_Property\nbegin\n\n(* Author: Anthony Bordg, University of Cambridge, apdb3@cam.ac.uk .*)\n\ntext \\<open>\nContents:\n\\<^item> We formalize Desargues's property, [\\<open>desargues_prop\\<close>], that states that if two triangles are perspective \nfrom a point, then they are perspective from a line. \nNote that some planes satisfy that property and some others don't, hence Desargues's property is\nnot a theorem though it is a theorem in projective space geometry. \n\\<close>\n\nsection \\<open>Desargues's Property\\<close>\n\ndefinition distinct3 :: \"[Points, Points, Points] \\<Rightarrow> bool\" where\n\"distinct3 A B C \\<equiv> A \\<noteq> B \\<and> A \\<noteq> C \\<and> B \\<noteq> C\"\n\ndefinition triangle :: \"[Points, Points, Points] \\<Rightarrow> bool\" where\n\"triangle A B C \\<equiv> distinct3 A B C \\<and> (line A B \\<noteq> line A C)\"\n\ndefinition meet_in :: \"Lines \\<Rightarrow> Lines => Points => bool \" where\n\"meet_in l m P \\<equiv> incid P l \\<and> incid P m\"\n\nlemma meet_col_1:\n  assumes \"meet_in (line A B) (line C D) P\"\n  shows \"col A B P\"\n  using assms col_def incidA_lAB incidB_lAB meet_in_def \n  by blast\n\nlemma meet_col_2:\n  assumes \"meet_in (line A B) (line C D) P\"\n  shows \"col C D P\"\n  using assms meet_col_1 meet_in_def \n  by auto\n\ndefinition meet_3_in :: \"[Lines, Lines, Lines, Points] \\<Rightarrow> bool\" where\n\"meet_3_in l m n P \\<equiv> meet_in l m P \\<and> meet_in l n P\"\n\nlemma meet_all_3:\n  assumes \"meet_3_in l m n P\"\n  shows \"meet_in m n P\"\n  using assms meet_3_in_def meet_in_def \n  by auto\n\n\n\nlemma meet_3_col_1:\n  assumes \"meet_3_in (line A B) m n P\"\n  shows \"col A B P\"\n  using assms meet_3_in_def meet_col_2 meet_in_def \n  by auto\n\nlemma meet_3_col_2:\n  assumes \"meet_3_in l (line A B) n P\"\n  shows \"col A B P\"\n  using assms col_def incidA_lAB incidB_lAB meet_3_in_def meet_in_def \n  by blast\n\nlemma meet_3_col_3:\n  assumes \"meet_3_in l m (line A B) P\"\n  shows \"col A B P\"\n  using assms meet_3_col_2 meet_3_in_def \n  by auto\n\ndefinition distinct7 ::\n  \"[Points, Points, Points, Points, Points, Points, Points] \\<Rightarrow> bool\" where\n\"distinct7 A B C D E F G \\<equiv> (A \\<noteq> B) \\<and> (A \\<noteq> C) \\<and> (A \\<noteq> D) \\<and> (A \\<noteq> E) \\<and> (A \\<noteq> F) \\<and> (A \\<noteq> G) \\<and>\n(B \\<noteq> C) \\<and> (B \\<noteq> D) \\<and> (B \\<noteq> E) \\<and> (B \\<noteq> F) \\<and> (B \\<noteq> G) \\<and>\n(C \\<noteq> D) \\<and> (C \\<noteq> E) \\<and> (C \\<noteq> F) \\<and> (C \\<noteq> G) \\<and>\n(D \\<noteq> E) \\<and> (D \\<noteq> F) \\<and> (D \\<noteq> G) \\<and>\n(E \\<noteq> F) \\<and> (E \\<noteq> G) \\<and>\n(F \\<noteq> G)\"\n\ndefinition distinct3l :: \"[Lines, Lines, Lines] \\<Rightarrow> bool\" where\n\"distinct3l l m n \\<equiv> l \\<noteq> m \\<and> l \\<noteq> n \\<and> m \\<noteq> n\"\n\n(* From now on we give less general statements on purpose to avoid a lot of uninteresting \ndegenerate cases, since we can hardly think of any interesting application where one would need \nto instantiate a statement on such degenerate case, hence our statements and proofs will be more \ntextbook-like. For the working mathematician the only thing that probably matters is the main\ntheorem without considering all the degenerate cases for which the statement might still hold. *)\n\ndefinition desargues_config :: \n  \"[Points, Points, Points, Points, Points, Points, Points, Points, Points, Points] => bool\" where\n\"desargues_config A B C A' B' C' M N P R \\<equiv> distinct7 A B C A' B' C' R \\<and> \\<not> col A B C \n\\<and> \\<not> col A' B' C' \\<and> distinct3l (line A A') (line B B') (line C C') \\<and> \nmeet_3_in (line A A') (line B B') (line C C') R \\<and> (line A B) \\<noteq> (line A' B') \\<and> \n(line B C) \\<noteq> (line B' C') \\<and> (line A C) \\<noteq> (line A' C') \\<and> meet_in (line B C) (line B' C') M \\<and>\nmeet_in (line A C) (line A' C') N \\<and> meet_in (line A B) (line A' B') P\"\n\nlemma distinct7_rot_CW:\n  assumes \"distinct7 A B C D E F G\"\n  shows \"distinct7 C A B F D E G\"\n  using assms distinct7_def \n  by auto\n\n(* Desargues configurations are stable under any rotation (i,j,k) of {1,2,3} *)\n\n\nlemma desargues_config_rot_CCW:\n  assumes \"desargues_config A B C A' B' C' M N P R\"\n  shows \"desargues_config B C A B' C' A' N P M R\"\n  by (simp add: assms desargues_config_rot_CW)\n\n(* With the two following definitions we repackage the definition of a Desargues configuration in a \n\"high-level\", i.e. textbook-like, way. *)\n\ndefinition are_perspective_from_point :: \n  \"[Points, Points, Points, Points, Points, Points, Points] \\<Rightarrow> bool\" where\n\"are_perspective_from_point A B C A' B' C' R \\<equiv> distinct7 A B C A' B' C' R \\<and> triangle A B C \\<and>\ntriangle A' B' C' \\<and> distinct3l (line A A') (line B B') (line C C') \\<and> \nmeet_3_in (line A A') (line B B') (line C C') R\"\n\ndefinition are_perspective_from_line ::\n  \"[Points, Points, Points, Points, Points, Points] \\<Rightarrow> bool\" where\n\"are_perspective_from_line A B C A' B' C' \\<equiv> distinct6 A B C A' B' C' \\<longrightarrow> triangle A B C \\<longrightarrow>\ntriangle A' B' C' \\<longrightarrow> line A B \\<noteq> line A' B' \\<longrightarrow> line A C \\<noteq> line A' C' \\<longrightarrow> line B C \\<noteq> line B' C' \\<longrightarrow>\ncol (inter (line A B) (line A' B')) (inter (line A C) (line A' C')) (inter (line B C) (line B' C'))\"\n\nlemma meet_in_inter:\n  assumes \"l \\<noteq> m\"\n  shows \"meet_in l m (inter l m)\"\n  by (simp add: incid_inter_left incid_inter_right meet_in_def)\n\nlemma perspective_from_point_desargues_config:\n  assumes \"are_perspective_from_point A B C A' B' C' R\" and \"line A B \\<noteq> line A' B'\" and \n    \"line A C \\<noteq> line A' C'\" and \"line B C \\<noteq> line B' C'\"\n  shows \"desargues_config A B C A' B' C' (inter (line B C) (line B' C')) (inter (line A C) (line A' C')) \n    (inter (line A B) (line A' B')) R\"\n  by (smt are_perspective_from_point_def assms(1) assms(2) assms(3) assms(4) col_line_ext_1 \n      desargues_config_def distinct3_def incidB_lAB inter_line_ext_2 line_comm meet_in_inter \n      triangle_def uniq_inter)\n\n(* Now, we state Desargues's property in a textbook-like form *)\ndefinition desargues_prop :: \"bool\" where\n\"desargues_prop \\<equiv> \n\\<forall>A B C A' B' C' P. \n  are_perspective_from_point A B C A' B' C' P \\<longrightarrow> are_perspective_from_line A B C A' B' C'\"\n\nend\n\n\n\n\n\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/Projective_Geometry/Desargues_Property.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8933093975331752, "lm_q2_score": 0.8031738034238807, "lm_q1q2_score": 0.7174827064510158}}
{"text": "(*  Based on HOL/Real_Vector_Spaces.thy by Brian Huffman\n    Adapted to the complex case by Dominique Unruh *)\n\nsection \\<open>\\<open>Complex_Inner_Product0\\<close> -- Inner Product Spaces and Gradient Derivative\\<close>\n\ntheory Complex_Inner_Product0\n  imports\n    Complex_Main Complex_Vector_Spaces\n    \"HOL-Analysis.Inner_Product\"\n    \"Complex_Bounded_Operators-Extra.Extra_Ordered_Fields\"\nbegin\n\nsubsection \\<open>Complex inner product spaces\\<close>\n\ntext \\<open>\n  Temporarily relax type constraints for \\<^term>\\<open>open\\<close>, \\<^term>\\<open>uniformity\\<close>,\n  \\<^term>\\<open>dist\\<close>, and \\<^term>\\<open>norm\\<close>.\n\\<close>\n\nsetup \\<open>Sign.add_const_constraint\n  (\\<^const_name>\\<open>open\\<close>, SOME \\<^typ>\\<open>'a::open set \\<Rightarrow> bool\\<close>)\\<close>\n\nsetup \\<open>Sign.add_const_constraint\n  (\\<^const_name>\\<open>dist\\<close>, SOME \\<^typ>\\<open>'a::dist \\<Rightarrow> 'a \\<Rightarrow> real\\<close>)\\<close>\n\nsetup \\<open>Sign.add_const_constraint\n  (\\<^const_name>\\<open>uniformity\\<close>, SOME \\<^typ>\\<open>('a::uniformity \\<times> 'a) filter\\<close>)\\<close>\n\nsetup \\<open>Sign.add_const_constraint\n  (\\<^const_name>\\<open>norm\\<close>, SOME \\<^typ>\\<open>'a::norm \\<Rightarrow> real\\<close>)\\<close>\n\nclass complex_inner = complex_vector + sgn_div_norm + dist_norm + uniformity_dist + open_uniformity +\n  fixes cinner :: \"'a \\<Rightarrow> 'a \\<Rightarrow> complex\"\n  assumes cinner_commute: \"cinner x y = cnj (cinner y x)\"\n    and cinner_add_left: \"cinner (x + y) z = cinner x z + cinner y z\"\n    and cinner_scaleC_left [simp]: \"cinner (scaleC r x) y = (cnj r) * (cinner x y)\"\n    and cinner_ge_zero [simp]: \"0 \\<le> cinner x x\"\n    and cinner_eq_zero_iff [simp]: \"cinner x x = 0 \\<longleftrightarrow> x = 0\"\n    and norm_eq_sqrt_cinner: \"norm x = sqrt (cmod (cinner x x))\"\nbegin\n\nlemma cinner_zero_left [simp]: \"cinner 0 x = 0\"\n  using cinner_add_left [of 0 0 x] by simp\n\nlemma cinner_minus_left [simp]: \"cinner (- x) y = - cinner x y\"\n  using cinner_add_left [of x \"- x\" y]\n  by (simp add: group_add_class.add_eq_0_iff)\n\nlemma cinner_diff_left: \"cinner (x - y) z = cinner x z - cinner y z\"\n  using cinner_add_left [of x \"- y\" z] by simp\n\nlemma cinner_sum_left: \"cinner (\\<Sum>x\\<in>A. f x) y = (\\<Sum>x\\<in>A. cinner (f x) y)\"\n  by (cases \"finite A\", induct set: finite, simp_all add: cinner_add_left)\n\nlemma call_zero_iff [simp]: \"(\\<forall>u. cinner x u = 0) \\<longleftrightarrow> (x = 0)\"\n  by auto (use cinner_eq_zero_iff in blast)\n\ntext \\<open>Transfer distributivity rules to right argument.\\<close>\n\nlemma cinner_add_right: \"cinner x (y + z) = cinner x y + cinner x z\"\n  using cinner_add_left [of y z x]\n  by (metis complex_cnj_add local.cinner_commute)\n\nlemma cinner_scaleC_right [simp]: \"cinner x (scaleC r y) = r * (cinner x y)\"\n  using cinner_scaleC_left [of r y x]\n  by (metis complex_cnj_cnj complex_cnj_mult local.cinner_commute)\n\nlemma cinner_zero_right [simp]: \"cinner x 0 = 0\"\n  using cinner_zero_left [of x]\n  by (metis (mono_tags, opaque_lifting) complex_cnj_zero local.cinner_commute)\n\nlemma cinner_minus_right [simp]: \"cinner x (- y) = - cinner x y\"\n  using cinner_minus_left [of y x]\n  by (metis complex_cnj_minus local.cinner_commute)\n\nlemma cinner_diff_right: \"cinner x (y - z) = cinner x y - cinner x z\"\n  using cinner_diff_left [of y z x]\n  by (metis complex_cnj_diff local.cinner_commute)\n\nlemma cinner_sum_right: \"cinner x (\\<Sum>y\\<in>A. f y) = (\\<Sum>y\\<in>A. cinner x (f y))\"\nproof (subst cinner_commute)\n  have \"(\\<Sum>y\\<in>A. cinner (f y) x) = (\\<Sum>y\\<in>A. cinner (f y) x)\"\n    by blast\n  hence \"cnj (\\<Sum>y\\<in>A. cinner (f y) x) = cnj (\\<Sum>y\\<in>A. (cinner (f y) x))\"\n    by simp\n  hence \"cnj (cinner (sum f A) x) = (\\<Sum>y\\<in>A. cnj (cinner (f y) x))\"\n    by (simp add: cinner_sum_left)\n  thus \"cnj (cinner (sum f A) x) = (\\<Sum>y\\<in>A. (cinner x (f y)))\"\n    by (subst (2) cinner_commute)\nqed\n\nlemmas cinner_add [algebra_simps] = cinner_add_left cinner_add_right\nlemmas cinner_diff [algebra_simps]  = cinner_diff_left cinner_diff_right\nlemmas cinner_scaleC = cinner_scaleC_left cinner_scaleC_right\n\n(* text \\<open>Legacy theorem names\\<close>\nlemmas cinner_left_distrib = cinner_add_left\nlemmas cinner_right_distrib = cinner_add_right\nlemmas cinner_distrib = cinner_left_distrib cinner_right_distrib *)\n\nlemma cinner_gt_zero_iff [simp]: \"0 < cinner x x \\<longleftrightarrow> x \\<noteq> 0\"\n  by (smt (verit) less_irrefl local.cinner_eq_zero_iff local.cinner_ge_zero order.not_eq_order_implies_strict)\n\n(* In Inner_Product, we have\n  lemma power2_norm_eq_cinner: \"(norm x)\\<^sup>2 = cinner x x\"\nThe following are two ways of inserting the conversions between real and complex into this:\n*)\n\nlemma power2_norm_eq_cinner:\n  shows \"(complex_of_real (norm x))\\<^sup>2 = (cinner x x)\"\n  by (smt (verit, del_insts) Im_complex_of_real Re_complex_of_real cinner_gt_zero_iff cinner_zero_right cmod_def complex_eq_0 complex_eq_iff less_complex_def local.norm_eq_sqrt_cinner of_real_power real_sqrt_abs real_sqrt_pow2_iff zero_complex.sel(1))\n\nlemma power2_norm_eq_cinner':\n  shows \"(norm x)\\<^sup>2 = Re (cinner x x)\"\n  by (metis Re_complex_of_real of_real_power power2_norm_eq_cinner)\n\ntext \\<open>Identities involving real multiplication and division.\\<close>\n\nlemma cinner_mult_left: \"cinner (of_complex m * a) b = cnj m * (cinner a b)\"\n  by (simp add: of_complex_def)\n\nlemma cinner_mult_right: \"cinner a (of_complex m * b) = m * (cinner a b)\"\n  by (metis complex_inner_class.cinner_scaleC_right scaleC_conv_of_complex)\n\nlemma cinner_mult_left': \"cinner (a * of_complex m) b = cnj m * (cinner a b)\"\n  by (metis cinner_mult_left mult.right_neutral mult_scaleC_right scaleC_conv_of_complex)\n\nlemma cinner_mult_right': \"cinner a (b * of_complex m) = (cinner a b) * m\"\n  by (simp add: complex_inner_class.cinner_scaleC_right of_complex_def)\n\n(* In Inner_Product, we have\n\n\nlemma Cauchy_Schwarz_ineq:\n  \"(cinner x y) * (cinner y x) \\<le> cinner x x * cinner y y\"\nproof (cases)\n  assume \"y = 0\"\n  thus ?thesis by simp\nnext\n  assume y: \"y \\<noteq> 0\"\n  have [simp]: \"cnj (cinner y y) = cinner y y\" for y\n    by (metis cinner_commute)\n  define r where \"r = cnj (cinner x y) / cinner y y\"\n  have \"0 \\<le> cinner (x - scaleC r y) (x - scaleC r y)\"\n    by (rule cinner_ge_zero)\n  also have \"\\<dots> = cinner x x - r * cinner x y - cnj r * cinner y x + r * cnj r * cinner y y\"\n    unfolding cinner_diff_left cinner_diff_right cinner_scaleC_left cinner_scaleC_right\n    by (smt (z3) cancel_comm_monoid_add_class.diff_cancel cancel_comm_monoid_add_class.diff_zero complex_cnj_divide group_add_class.diff_add_cancel local.cinner_commute local.cinner_eq_zero_iff local.cinner_scaleC_left mult.assoc mult.commute mult_eq_0_iff nonzero_eq_divide_eq r_def y)\n  also have \"\\<dots> = cinner x x - cinner y x * cnj r\"\n    unfolding r_def by auto\n  also have \"\\<dots> = cinner x x - cinner x y * cnj (cinner x y) / cinner y y\"\n    unfolding r_def\n    by (metis complex_cnj_divide local.cinner_commute mult.commute times_divide_eq_left)\n  finally have \"0 \\<le> cinner x x - cinner x y * cnj (cinner x y) / cinner y y\" .\n  hence \"cinner x y * cnj (cinner x y) / cinner y y \\<le> cinner x x\"\n    by (simp add: le_diff_eq)\n  thus \"cinner x y * cinner y x \\<le> cinner x x * cinner y y\"\n    by (metis cinner_gt_zero_iff local.cinner_commute nice_ordered_field_class.pos_divide_le_eq y)\nqed\n\n\nlemma Cauchy_Schwarz_ineq2:\n  shows \"norm (cinner x y) \\<le> norm x * norm y\"\nproof (rule power2_le_imp_le)\n  have \"(norm (cinner x y))^2 = Re (cinner x y * cinner y x)\"\n    by (metis (full_types) Re_complex_of_real complex_norm_square local.cinner_commute)\n  also have \"\\<dots> \\<le> Re (cinner x x * cinner y y)\"\n    using Cauchy_Schwarz_ineq by (rule Re_mono)\n  also have \"\\<dots> = Re (complex_of_real ((norm x)^2) * complex_of_real ((norm y)^2))\"\n    by (simp add: power2_norm_eq_cinner)\n  also have \"\\<dots> = (norm x * norm y)\\<^sup>2\"\n    by (simp add: power_mult_distrib)\n  finally show \"(cmod (cinner x y))^2 \\<le> (norm x * norm y)\\<^sup>2\" .\n  show \"0 \\<le> norm x * norm y\"\n    by (simp add: local.norm_eq_sqrt_cinner)\nqed\n\n(* The following variant does not hold in the complex case: *)\n(* lemma norm_cauchy_schwarz: \"cinner x y \\<le> norm x * norm y\"\n  using Cauchy_Schwarz_ineq2 [of x y] by auto *)\n\nsubclass complex_normed_vector\nproof\n  fix a :: complex and r :: real and x y :: 'a\n  show \"norm x = 0 \\<longleftrightarrow> x = 0\"\n    unfolding norm_eq_sqrt_cinner by simp\n  show \"norm (x + y) \\<le> norm x + norm y\"\n  proof (rule power2_le_imp_le)\n    have \"Re (cinner x y) \\<le> cmod (cinner x y)\"\n      if \"\\<And>x. Re x \\<le> cmod x\" and\n        \"\\<And>x y. x \\<le> y \\<Longrightarrow> complex_of_real x \\<le> complex_of_real y\"\n      using that by simp\n    hence a1: \"2 * Re (cinner x y) \\<le> 2 * cmod (cinner x y)\"\n      if \"\\<And>x. Re x \\<le> cmod x\" and\n        \"\\<And>x y. x \\<le> y \\<Longrightarrow> complex_of_real x \\<le> complex_of_real y\"\n      using that by simp\n    have \"cinner x y + cinner y x = complex_of_real (2 * Re (cinner x y))\"\n      by (metis complex_add_cnj local.cinner_commute)\n    also have \"\\<dots> \\<le> complex_of_real (2 * cmod (cinner x y))\"\n      using complex_Re_le_cmod complex_of_real_mono a1\n      by blast\n    also have \"\\<dots> = 2 * abs (cinner x y)\"\n      unfolding abs_complex_def by simp\n    also have \"\\<dots> \\<le> 2 * complex_of_real (norm x) * complex_of_real (norm y)\"\n      using Cauchy_Schwarz_ineq2 unfolding abs_complex_def less_eq_complex_def by auto\n    finally have xyyx: \"cinner x y + cinner y x \\<le> complex_of_real (2 * norm x * norm y)\"\n      by auto\n    have \"complex_of_real ((norm (x + y))\\<^sup>2) = cinner (x+y) (x+y)\"\n      by (simp add: power2_norm_eq_cinner)\n    also have \"\\<dots> = cinner x x + cinner x y + cinner y x + cinner y y\"\n      by (simp add: cinner_add)\n    also have \"\\<dots> = complex_of_real ((norm x)\\<^sup>2) + complex_of_real ((norm y)\\<^sup>2) + cinner x y + cinner y x\"\n      by (simp add: power2_norm_eq_cinner)\n    also have \"\\<dots> \\<le> complex_of_real ((norm x)\\<^sup>2) + complex_of_real ((norm y)\\<^sup>2) + complex_of_real (2 * norm x * norm y)\"\n      using xyyx by auto\n    also have \"\\<dots> = complex_of_real ((norm x + norm y)\\<^sup>2)\"\n      unfolding power2_sum by auto\n    finally show \"(norm (x + y))\\<^sup>2 \\<le> (norm x + norm y)\\<^sup>2\"\n      using complex_of_real_mono_iff by blast\n    show \"0 \\<le> norm x + norm y\"\n      unfolding norm_eq_sqrt_cinner by simp\n  qed\n  show norm_scaleC: \"norm (a *\\<^sub>C x) = cmod a * norm x\" for a\n  proof (rule power2_eq_imp_eq)\n    show \"(norm (a *\\<^sub>C x))\\<^sup>2 = (cmod a * norm x)\\<^sup>2\"\n      by (simp_all add: norm_eq_sqrt_cinner norm_mult power2_eq_square)\n    show \"0 \\<le> norm (a *\\<^sub>C x)\"\n      by (simp_all add: norm_eq_sqrt_cinner)\n    show \"0 \\<le> cmod a * norm x\"\n      by (simp_all add: norm_eq_sqrt_cinner)\n  qed\n  show \"norm (r *\\<^sub>R x) = \\<bar>r\\<bar> * norm x\"\n    unfolding scaleR_scaleC norm_scaleC by auto\nqed\n\nend\n\n(* Does not hold in the complex case *)\n(* lemma csquare_bound_lemma:\n  fixes x :: complex\n  shows \"x < (1 + x) * (1 + x)\" *)\n\nlemma csquare_continuous:\n  fixes e :: real\n  shows \"e > 0 \\<Longrightarrow> \\<exists>d. 0 < d \\<and> (\\<forall>y. cmod (y - x) < d \\<longrightarrow> cmod (y * y - x * x) < e)\"\n  using isCont_power[OF continuous_ident, of x, unfolded isCont_def LIM_eq, rule_format, of e 2]\n  by (force simp add: power2_eq_square)\n\nlemma cnorm_le: \"norm x \\<le> norm y \\<longleftrightarrow> cinner x x \\<le> cinner y y\"\n  by (smt (verit) complex_of_real_mono_iff norm_eq_sqrt_cinner norm_ge_zero of_real_power power2_norm_eq_cinner real_sqrt_le_mono real_sqrt_pow2)\n\nlemma cnorm_lt: \"norm x < norm y \\<longleftrightarrow> cinner x x < cinner y y\"\n  by (meson cnorm_le less_le_not_le)\n\nlemma cnorm_eq: \"norm x = norm y \\<longleftrightarrow> cinner x x = cinner y y\"\n  by (metis norm_eq_sqrt_cinner power2_norm_eq_cinner)\n\nlemma cnorm_eq_1: \"norm x = 1 \\<longleftrightarrow> cinner x x = 1\"\n  by (metis cinner_ge_zero complex_of_real_cmod norm_eq_sqrt_cinner norm_one of_real_1 real_sqrt_eq_iff real_sqrt_one)\n\nlemma cinner_divide_left:\n  fixes a :: \"'a :: {complex_inner,complex_div_algebra}\"\n  shows \"cinner (a / of_complex m) b = (cinner a b) / cnj m\"\n  by (metis cinner_mult_left' complex_cnj_inverse divide_inverse mult.commute of_complex_inverse)\n\nlemma cinner_divide_right:\n  fixes a :: \"'a :: {complex_inner,complex_div_algebra}\"\n  shows \"cinner a (b / of_complex m) = (cinner a b) / m\"\n  by (metis cinner_mult_right' divide_inverse of_complex_inverse)\n\ntext \\<open>\n  Re-enable constraints for \\<^term>\\<open>open\\<close>, \\<^term>\\<open>uniformity\\<close>,\n  \\<^term>\\<open>dist\\<close>, and \\<^term>\\<open>norm\\<close>.\n\\<close>\n\nsetup \\<open>Sign.add_const_constraint\n  (\\<^const_name>\\<open>open\\<close>, SOME \\<^typ>\\<open>'a::topological_space set \\<Rightarrow> bool\\<close>)\\<close>\n\nsetup \\<open>Sign.add_const_constraint\n  (\\<^const_name>\\<open>uniformity\\<close>, SOME \\<^typ>\\<open>('a::uniform_space \\<times> 'a) filter\\<close>)\\<close>\n\nsetup \\<open>Sign.add_const_constraint\n  (\\<^const_name>\\<open>dist\\<close>, SOME \\<^typ>\\<open>'a::metric_space \\<Rightarrow> 'a \\<Rightarrow> real\\<close>)\\<close>\n\nsetup \\<open>Sign.add_const_constraint\n  (\\<^const_name>\\<open>norm\\<close>, SOME \\<^typ>\\<open>'a::real_normed_vector \\<Rightarrow> real\\<close>)\\<close>\n\n\nlemma bounded_sesquilinear_cinner:\n  \"bounded_sesquilinear (cinner::'a::complex_inner \\<Rightarrow> 'a \\<Rightarrow> complex)\"\nproof\n  fix x y z :: 'a and r :: complex\n  show \"cinner (x + y) z = cinner x z + cinner y z\"\n    by (rule cinner_add_left)\n  show \"cinner x (y + z) = cinner x y + cinner x z\"\n    by (rule cinner_add_right)\n  show \"cinner (scaleC r x) y = scaleC (cnj r) (cinner x y)\"\n    unfolding complex_scaleC_def by (rule cinner_scaleC_left)\n  show \"cinner x (scaleC r y) = scaleC r (cinner x y)\"\n    unfolding complex_scaleC_def by (rule cinner_scaleC_right)\n  have \"\\<forall>x y::'a. norm (cinner x y) \\<le> norm x * norm y * 1\"\n    by (simp add: complex_inner_class.Cauchy_Schwarz_ineq2)\n  thus \"\\<exists>K. \\<forall>x y::'a. norm (cinner x y) \\<le> norm x * norm y * K\"\n    by metis\nqed\n\nlemmas tendsto_cinner [tendsto_intros] =\n  bounded_bilinear.tendsto [OF bounded_sesquilinear_cinner[THEN bounded_sesquilinear.bounded_bilinear]]\n\nlemmas isCont_cinner [simp] =\n  bounded_bilinear.isCont [OF bounded_sesquilinear_cinner[THEN bounded_sesquilinear.bounded_bilinear]]\n\nlemmas has_derivative_cinner [derivative_intros] =\n  bounded_bilinear.FDERIV [OF bounded_sesquilinear_cinner[THEN bounded_sesquilinear.bounded_bilinear]]\n\nlemmas bounded_antilinear_cinner_left =\n  bounded_sesquilinear.bounded_antilinear_left [OF bounded_sesquilinear_cinner]\n\nlemmas bounded_clinear_cinner_right =\n  bounded_sesquilinear.bounded_clinear_right [OF bounded_sesquilinear_cinner]\n\nlemmas bounded_antilinear_cinner_left_comp = bounded_antilinear_cinner_left[THEN bounded_antilinear_o_bounded_clinear]\n\nlemmas bounded_clinear_cinner_right_comp = bounded_clinear_cinner_right[THEN bounded_clinear_compose]\n\nlemmas has_derivative_cinner_right [derivative_intros] =\n  bounded_linear.has_derivative [OF bounded_clinear_cinner_right[THEN bounded_clinear.bounded_linear]]\n\nlemmas has_derivative_cinner_left [derivative_intros] =\n  bounded_linear.has_derivative [OF bounded_antilinear_cinner_left[THEN bounded_antilinear.bounded_linear]]\n\nlemma differentiable_cinner [simp]:\n  \"f differentiable (at x within s) \\<Longrightarrow> g differentiable at x within s \\<Longrightarrow> (\\<lambda>x. cinner (f x) (g x)) differentiable at x within s\"\n  unfolding differentiable_def by (blast intro: has_derivative_cinner)\n\n\nsubsection \\<open>Class instances\\<close>\n\ninstantiation complex :: complex_inner\nbegin\n\ndefinition cinner_complex_def [simp]: \"cinner x y = cnj x * y\"\n\ninstance\nproof\n  fix x y z r :: complex\n  show \"cinner x y = cnj (cinner y x)\"\n    unfolding cinner_complex_def by auto\n  show \"cinner (x + y) z = cinner x z + cinner y z\"\n    unfolding cinner_complex_def\n    by (simp add: ring_class.ring_distribs(2))\n  show \"cinner (scaleC r x) y = cnj r * cinner x y\"\n    unfolding cinner_complex_def complex_scaleC_def by simp\n  show \"0 \\<le> cinner x x\"\n    by simp\n  show \"cinner x x = 0 \\<longleftrightarrow> x = 0\"\n    unfolding cinner_complex_def by simp\n  have \"cmod (Complex x1 x2) = sqrt (cmod (cinner (Complex x1 x2) (Complex x1 x2)))\"\n    for x1 x2\n    unfolding cinner_complex_def complex_cnj complex_mult complex_norm\n    by (simp add: power2_eq_square)\n  thus \"norm x = sqrt (cmod (cinner x x))\"\n    by (cases x, hypsubst_thin)\nqed\n\nend\n\nlemma\n  shows complex_inner_1_left[simp]: \"cinner 1 x = x\"\n    and complex_inner_1_right[simp]: \"cinner x 1 = cnj x\"\n  by simp_all\n\n(* No analogous to \\<open>instantiation complex :: real_inner\\<close> or to\nlemma complex_inner_1 [simp]: \"inner 1 x = Re x\"\nlemma complex_inner_1_right [simp]: \"inner x 1 = Re x\"\nlemma complex_inner_i_left [simp]: \"inner \\<i> x = Im x\"\nlemma complex_inner_i_right [simp]: \"inner x \\<i> = Im x\"\n *)\n\nlemma cdot_square_norm: \"cinner x x = complex_of_real ((norm x)\\<^sup>2)\"\n  by (metis Im_complex_of_real Re_complex_of_real cinner_ge_zero complex_eq_iff less_eq_complex_def power2_norm_eq_cinner' zero_complex.simps(2))\n\nlemma cnorm_eq_square: \"norm x = a \\<longleftrightarrow> 0 \\<le> a \\<and> cinner x x = complex_of_real (a\\<^sup>2)\"\n  by (metis cdot_square_norm norm_ge_zero of_real_eq_iff power2_eq_iff_nonneg)\n\nlemma cnorm_le_square: \"norm x \\<le> a \\<longleftrightarrow> 0 \\<le> a \\<and> cinner x x \\<le> complex_of_real (a\\<^sup>2)\"\n  by (smt (verit) cdot_square_norm complex_of_real_mono_iff norm_ge_zero power2_le_imp_le)\n\nlemma cnorm_ge_square: \"norm x \\<ge> a \\<longleftrightarrow> a \\<le> 0 \\<or> cinner x x \\<ge> complex_of_real (a\\<^sup>2)\"\n  by (smt (verit, best) antisym_conv cnorm_eq_square cnorm_le_square complex_of_real_nn_iff nn_comparable zero_le_power2)\n\nlemma norm_lt_square: \"norm x < a \\<longleftrightarrow> 0 < a \\<and> cinner x x < complex_of_real (a\\<^sup>2)\"\n  by (meson cnorm_ge_square cnorm_le_square less_le_not_le)\n\nlemma norm_gt_square: \"norm x > a \\<longleftrightarrow> a < 0 \\<or> cinner x x > complex_of_real (a\\<^sup>2)\"\n  by (smt (verit, ccfv_SIG) cdot_square_norm complex_of_real_strict_mono_iff norm_ge_zero power2_eq_imp_eq power_mono)\n\ntext\\<open>Dot product in terms of the norm rather than conversely.\\<close>\n\nlemmas cinner_simps = cinner_add_left cinner_add_right cinner_diff_right cinner_diff_left\n  cinner_scaleC_left cinner_scaleC_right\n\n(* Analogue to both dot_norm and dot_norm_neg *)\nlemma cdot_norm: \"cinner x y = ((norm (x+y))\\<^sup>2 - (norm (x-y))\\<^sup>2 - \\<i> * (norm (x + \\<i> *\\<^sub>C y))\\<^sup>2 + \\<i> * (norm (x - \\<i> *\\<^sub>C y))\\<^sup>2) / 4\"\n  unfolding power2_norm_eq_cinner\n  by (simp add: power2_norm_eq_cinner cinner_add_left cinner_add_right\n      cinner_diff_left cinner_diff_right ring_distribs)\n\nlemma of_complex_inner_1 [simp]:\n  \"cinner (of_complex x) (1 :: 'a :: {complex_inner, complex_normed_algebra_1}) = cnj x\"\n  by (metis Complex_Inner_Product0.complex_inner_1_right cinner_complex_def cinner_mult_left complex_cnj_one norm_one of_complex_def power2_norm_eq_cinner scaleC_conv_of_complex)\n\nlemma summable_of_complex_iff:\n  \"summable (\\<lambda>x. of_complex (f x) :: 'a :: {complex_normed_algebra_1,complex_inner}) \\<longleftrightarrow> summable f\"\nproof\n  assume *: \"summable (\\<lambda>x. of_complex (f x) :: 'a)\"\n  have \"bounded_clinear (cinner (1::'a))\"\n    by (rule bounded_clinear_cinner_right)\n  then interpret bounded_linear \"\\<lambda>x::'a. cinner 1 x\"\n    by (rule bounded_clinear.bounded_linear)\n  from summable [OF *] show \"summable f\"\n    apply (subst (asm) cinner_commute) by simp\nnext\n  assume sum: \"summable f\"\n  thus \"summable (\\<lambda>x. of_complex (f x) :: 'a)\"\n    by (rule summable_of_complex)\nqed\n\nsubsection \\<open>Gradient derivative\\<close>\n\ndefinition\\<^marker>\\<open>tag important\\<close>\n  cgderiv :: \"['a::complex_inner \\<Rightarrow> complex, 'a, 'a] \\<Rightarrow> bool\"\n  (\"(cGDERIV (_)/ (_)/ :> (_))\" [1000, 1000, 60] 60)\n  where\n    (* Must be \"cinner D\" not \"\\<lambda>h. cinner h D\", otherwise not even \"cGDERIV id x :> 1\" holds *)\n    \"cGDERIV f x :> D \\<longleftrightarrow> FDERIV f x :> cinner D\"\n\nlemma cgderiv_deriv [simp]: \"cGDERIV f x :> D \\<longleftrightarrow> DERIV f x :> cnj D\"\n  by (simp only: cgderiv_def has_field_derivative_def cinner_complex_def[THEN ext])\n\nlemma cGDERIV_DERIV_compose:\n  assumes \"cGDERIV f x :> df\" and \"DERIV g (f x) :> cnj dg\"\n  shows \"cGDERIV (\\<lambda>x. g (f x)) x :> scaleC dg df\"\nproof (insert assms)\n  show \"cGDERIV (\\<lambda>x. g (f x)) x :> dg *\\<^sub>C df\"\n    if \"cGDERIV f x :> df\"\n      and \"(g has_field_derivative cnj dg) (at (f x))\"\n    unfolding cgderiv_def has_field_derivative_def cinner_scaleC_left complex_cnj_cnj\n    using that\n    by (simp add: cgderiv_def has_derivative_compose has_field_derivative_imp_has_derivative)\n\nqed\n\n(* Not specific to complex/real *)\n(* lemma has_derivative_subst: \"\\<lbrakk>FDERIV f x :> df; df = d\\<rbrakk> \\<Longrightarrow> FDERIV f x :> d\" *)\n\nlemma cGDERIV_subst: \"\\<lbrakk>cGDERIV f x :> df; df = d\\<rbrakk> \\<Longrightarrow> cGDERIV f x :> d\"\n  by simp\n\nlemma cGDERIV_const: \"cGDERIV (\\<lambda>x. k) x :> 0\"\n  unfolding cgderiv_def cinner_zero_left[THEN ext] by (rule has_derivative_const)\n\nlemma cGDERIV_add:\n  \"\\<lbrakk>cGDERIV f x :> df; cGDERIV g x :> dg\\<rbrakk>\n     \\<Longrightarrow> cGDERIV (\\<lambda>x. f x + g x) x :> df + dg\"\n  unfolding cgderiv_def cinner_add_left[THEN ext] by (rule has_derivative_add)\n\nlemma cGDERIV_minus:\n  \"cGDERIV f x :> df \\<Longrightarrow> cGDERIV (\\<lambda>x. - f x) x :> - df\"\n  unfolding cgderiv_def cinner_minus_left[THEN ext] by (rule has_derivative_minus)\n\nlemma cGDERIV_diff:\n  \"\\<lbrakk>cGDERIV f x :> df; cGDERIV g x :> dg\\<rbrakk>\n     \\<Longrightarrow> cGDERIV (\\<lambda>x. f x - g x) x :> df - dg\"\n  unfolding cgderiv_def cinner_diff_left by (rule has_derivative_diff)\n\nlemma cGDERIV_scaleC:\n  \"\\<lbrakk>DERIV f x :> df; cGDERIV g x :> dg\\<rbrakk>\n     \\<Longrightarrow> cGDERIV (\\<lambda>x. scaleC (f x) (g x)) x\n      :> (scaleC (cnj (f x)) dg + scaleC (cnj df) (cnj (g x)))\"\n  unfolding cgderiv_def has_field_derivative_def cinner_add_left cinner_scaleC_left\n  apply (rule has_derivative_subst)\n   apply (erule (1) has_derivative_scaleC)\n  by (simp add: ac_simps)\n\nlemma GDERIV_mult:\n  \"\\<lbrakk>cGDERIV f x :> df; cGDERIV g x :> dg\\<rbrakk>\n     \\<Longrightarrow> cGDERIV (\\<lambda>x. f x * g x) x :> cnj (f x) *\\<^sub>C dg + cnj (g x) *\\<^sub>C df\"\n  unfolding cgderiv_def\n  apply (rule has_derivative_subst)\n   apply (erule (1) has_derivative_mult)\n  apply (rule ext)\n  by (simp add: cinner_add ac_simps)\n\nlemma cGDERIV_inverse:\n  \"\\<lbrakk>cGDERIV f x :> df; f x \\<noteq> 0\\<rbrakk>\n     \\<Longrightarrow> cGDERIV (\\<lambda>x. inverse (f x)) x :> - cnj ((inverse (f x))\\<^sup>2) *\\<^sub>C df\"\n  by (metis DERIV_inverse cGDERIV_DERIV_compose complex_cnj_cnj complex_cnj_minus numerals(2))\n\n(* Don't know if this holds: *)\n(* lemma cGDERIV_norm:\n  assumes \"x \\<noteq> 0\" shows \"cGDERIV (\\<lambda>x. norm x) x :> sgn x\"\n*)\n\n\nlemma has_derivative_norm[derivative_intros]:\n  fixes x :: \"'a::complex_inner\"\n  assumes \"x \\<noteq> 0\"\n  shows \"(norm has_derivative (\\<lambda>h. Re (cinner (sgn x) h))) (at x)\"\n  thm has_derivative_norm\nproof -\n  have Re_pos: \"0 < Re (cinner x x)\"\n    using assms\n    by (metis Re_strict_mono cinner_gt_zero_iff zero_complex.simps(1))\n  have Re_plus_Re: \"Re (cinner x y) + Re (cinner y x) = 2 * Re (cinner x y)\"\n    for x y :: 'a\n    by (metis cinner_commute cnj.simps(1) mult_2_right semiring_normalization_rules(7))\n  have norm: \"norm x = sqrt (Re (cinner x x))\" for x :: 'a\n    apply (subst norm_eq_sqrt_cinner, subst cmod_Re)\n    using cinner_ge_zero by auto\n  have v2:\"((\\<lambda>x. sqrt (Re (cinner x x))) has_derivative\n          (\\<lambda>xa. (Re (cinner x xa) + Re (cinner xa x)) * (inverse (sqrt (Re (cinner x x))) / 2))) (at x)\"\n    by (rule derivative_eq_intros | simp add: Re_pos)+\n  have v1: \"((\\<lambda>x. sqrt (Re (cinner x x))) has_derivative (\\<lambda>y. Re (cinner x y) / sqrt (Re (cinner x x)))) (at x)\"\n    if \"((\\<lambda>x. sqrt (Re (cinner x x))) has_derivative (\\<lambda>xa. Re (cinner x xa) * inverse (sqrt (Re (cinner x x))))) (at x)\"\n    using that apply (subst divide_real_def)\n    by simp\n  have \\<open>(norm has_derivative (\\<lambda>y. Re (cinner x y) / norm x)) (at x)\\<close>\n    using v2\n    apply (auto simp: Re_plus_Re norm [abs_def])\n    using v1 by blast\n  then show ?thesis\n    by (auto simp: power2_eq_square sgn_div_norm scaleR_scaleC)\nqed\n\n\nbundle cinner_syntax begin\nnotation cinner (infix \"\\<bullet>\\<^sub>C\" 70)\nend\n\nbundle no_cinner_syntax begin\nno_notation cinner (infix \"\\<bullet>\\<^sub>C\" 70)\nend\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_Inner_Product0.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.877476793890012, "lm_q2_score": 0.8175744828610095, "lm_q1q2_score": 0.7174026359871633}}
{"text": "theory HL_State\nimports \n  Main\n  \"~~/src/HOL/Library/State_Monad\"\nbegin\n\nsection\\<open>Introduction\\<close>\n\nsection\\<open>Hoare calculus\\<close>\ntext\\<open>Basic definitions that can be useful inside as a parameter to spec in a proof\\<close>\ndefinition TT:: \"'a \\<Rightarrow> bool\" where \"TT x = True\"\ndefinition TTT:: \"'b \\<Rightarrow> 'a \\<Rightarrow> bool\" where \"TTT x y = True\"\ndefinition FF:: \"'a \\<Rightarrow> bool\" where \"FF x = False\"\ndefinition GG:: \"('a \\<Rightarrow> bool) \\<Rightarrow> ('b => 'a \\<Rightarrow> bool)\" where \"GG p x = p\"\ndefinition UU:: \"('a \\<Rightarrow> bool) \\<Rightarrow> (unit => 'a \\<Rightarrow> bool)\" where \"UU p x = p\"\n\ntext\\<open>Methods to get describe the basic state changes. These are described by state-monad which encapsulates the state\\<close>\ndefinition return:: \"'a \\<Rightarrow> ('b, 'a) state\" where \"return = State_Monad.return\"\ndefinition get_state:: \"('a, 'a) state\" where \"get_state = State (\\<lambda>x. (x,x))\"\ndefinition put_state:: \"'a \\<Rightarrow> ('a, unit) state\" where \"put_state x = State (\\<lambda>_. ((),x))\"\n\ndefinition unpack_state:: \"('a, unit) state \\<Rightarrow> 'a \\<Rightarrow> 'a\" where \n  \"unpack_state S x \\<equiv> snd(run_state S x)\"\n\n\ntype_synonym 'a bexp = \"'a \\<Rightarrow> bool\"\ntype_synonym 'a assn = \"'a \\<Rightarrow> bool\"\n\nsubsubsection\\<open>Commands\\<close>\ntext\\<open>Commands describe that can be done in the langagauge.\\<close>\ntext\\<open>I have assumed that all calls eventually be reduces to basic commands which involves manipulation of the state-monad.\\<close>\ndatatype 'a com =\n  Basic \"('a, unit) state\"\n| Seq  \"'a com\" \"'a com\"                     (\"(_;/ _)\"      [61,60] 60)\n| Cond \"'a bexp\" \"'a com\" \"'a com\"           (\"(1IF _/ THEN _ / ELSE _/ FI)\"  [0,0,0] 61)\n\ntext\\<open>The skip-command is just a special command which leaves the state-monad unchanged. Put monad-identify - this should be a return\\<close>\nabbreviation annskip (\"SKIP\") where \"SKIP == (State_Monad.return)\"\n\ntype_synonym 'a sem = \"('a, unit) state  => ('a, unit) state => bool\"\n\ntext\\<open>This could potentially be useful in the while-loop. \n  It states that the predicate is not longer true in the base case, but that the final state has also been reached.\n  The other case states that be predicate is true and it is possible to reach the base-case in a finite amount of steps.\n It is taken from: \\url{http://isabelle.in.tum.de/dist/library/HOL/HOL-Isar_Examples/Hoare.html}\\<close>\n(*primrec iter :: \"nat \\<Rightarrow> 'a bexp \\<Rightarrow> 'a sem \\<Rightarrow> 'a sem\"\n  where\n    \"iter 0 b S s s' \\<longleftrightarrow> \\<not>b s \\<and> s = s'\"\n  | \"iter (Suc n) b S s s' \\<longleftrightarrow> b s \\<and> (\\<exists>s''. S s s'' \\<and> iter n b S s'' s')\"\n*)\n\ntext\\<open>The semantics describe how the program should be interpreted. It takes a command and returns two states - the pre and post state of each command.\\<close>\ninductive Sem :: \"'a com \\<Rightarrow> 'a sem\"\nwhere\n  \"Sem (Basic f) s (f)\"\n| \"Sem c1 s s'' \\<Longrightarrow> Sem c2  s'' s' \\<Longrightarrow> Sem (c1;c2) s s'\"\n| \"b s \\<Longrightarrow> Sem c1 s s' \\<Longrightarrow> Sem (IF b THEN c1 ELSE c2 FI) s s'\"\n| \"\\<not>b s \\<Longrightarrow> Sem c2 s s' \\<Longrightarrow> Sem (IF b THEN c1 ELSE c2 FI) s s'\"\n\ninductive_cases [elim!]:\n  \"Sem (Basic f) s s'\" \n  \"Sem (c1;c2) s s'\"\n  \"Sem (IF b THEN c1 ELSE c2 FI) s s'\"\n\ndefinition Valid :: \"'a bexp \\<Rightarrow> 'a com \\<Rightarrow> 'a bexp \\<Rightarrow> bool\"\n  where \"Valid p c q \\<longleftrightarrow> (\\<forall>s s'. Sem c s s' \\<longrightarrow>  p s \\<longrightarrow> q (unpack_state s' s))\"\n\nlemma SkipRule: \"p = q \\<Longrightarrow> Valid p SKIP q\"\nby (auto simp:Valid_def)\n\nlemma BasicRule: \"\\<forall>s. p s \\<longrightarrow> q (unpack_state (f s) s) \\<Longrightarrow> Valid p (Basic f) q\"\n  by (auto simp:Valid_def)\n\nlemma SeqRule: \"Valid p c1 q  \\<Longrightarrow> Valid q c2 r  \\<Longrightarrow> Valid p (c1;c2) r\"\n  apply (auto simp:Valid_def)\n  sorry\n\n\nlemma CondRule:\n \"\\<forall>s. p s \\<longrightarrow> ((b s \\<longrightarrow> w s) \\<and> (\\<not>b s \\<longrightarrow>  w' s))\n  \\<Longrightarrow> Valid w c1 q \\<Longrightarrow> Valid w' c2 q \\<Longrightarrow> Valid p (Cond b c1 c2) q\"\n  by (auto simp:Valid_def)\n\ndefinition get:: \"('a \\<Rightarrow> 'b) \\<Rightarrow> ('a, 'b) state\" where \n  \"get v = do { x \\<leftarrow> get_state; return (v x) }\"\n\ndefinition put:: \"('a \\<Rightarrow> 'b \\<Rightarrow> 'a) \\<Rightarrow> 'b \\<Rightarrow> ('a, unit) state\" where \n  \"put vu a = do { x \\<leftarrow> get_state; put_state (vu x a) }\"\n\ndefinition assign:: \"('a \\<Rightarrow> 'b \\<Rightarrow> 'a) \\<Rightarrow> ('a \\<Rightarrow> 'b) \\<Rightarrow> ('a, unit) state\" where\n  \"assign vu v =  (do { a \\<leftarrow> get v; put vu a })\"\n\ndefinition assign1 :: \"('a \\<Rightarrow> 'b \\<Rightarrow> 'a) \\<Rightarrow> ('a \\<Rightarrow> 'b) \\<Rightarrow> 'a com\" (\"(2_ :=/ _)\" [70, 65] 61) where \n  \"assign1 vu v = Basic (\\<lambda>e. do { a \\<leftarrow> get v; put vu a })\" \n\ntext\\<open>This is what enables the \\<close>\nsyntax\n  \"_hoare_vars\" :: \"[idts, 'a assn,'a com,'a assn] \\<Rightarrow> bool\" (\"(VARS _ //{_} // _ // {_})\" [0,0,55,0] 50)\n\ntext\\<open>This is what enables the \\<close>\nsyntax\n  \"_hoare\" :: \"['a assn,'a com,'a assn] => bool\" (\"({_} // _ // {_})\" [0,55,0] 50)\n\n\ndefinition spec:: \"('a \\<Rightarrow> bool) \\<Rightarrow> ('a, 'b) state \\<Rightarrow> ('b \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> bool\" where \n  \"spec p S q = (\\<forall>x. p x  \\<longrightarrow> (let (y, z) = run_state S x in q y z))\"\n\nsubsection\\<open>Hoare logic\\<close>\ntext\\<open>Rules based on section 3 in Verification of Sequential and Concurrent Programs\\<close>\ntheorem get_state_rule: \"spec (\\<lambda>x. p x x) (get_state) p\"\n  by (simp add: get_state_def spec_def)\n\n\ntext\\<open>Rule to extract a value from the Monad\\<close>\ntheorem get_rule: \"\\<forall>x. spec (\\<lambda>y. p y \\<and> v x = v y) (S (v x)) q \\<Longrightarrow> spec p (get v \\<bind> S) q\"\n  by (simp add: spec_def get_def return_def case_prod_unfold get_state_def)\n\ntheorem return_rule: \"spec (p v) (return v) p\"\n  by (simp add: return_def spec_def)\n\ntext\\<open>The sequential rule describes all intermediate states that can be both a post-condition of statement @{text S} \n  with the pre-condition @{text p} which after execution of statement @{text T} will result in a final-state of @{text r}\\<close>\ntheorem seq_rule: \"\\<lbrakk>spec p S q; \\<forall>x. spec (q x) T r\\<rbrakk> \\<Longrightarrow> spec p (do { S; T }) r\"\n  apply (simp add: spec_def)\n  by fastforce\n\ntext\\<open>Rule to capture scope of local variables\\<close>\ntheorem let_rule: \"let v = E in spec p (do { T }) r \\<Longrightarrow> spec p (do { let v = E; T }) r\"\n  by (simp add: spec_def snd_def)\n\n\ntext\\<open>Pre- and post-conditions can be conjoined\\<close>\ntheorem conj_rule: \"\\<lbrakk>spec p S q; spec r S s\\<rbrakk> \\<Longrightarrow> spec (\\<lambda>x. p x \\<and> r x) S (\\<lambda>x y. q x y \\<and> s x y)\"\n  apply (simp add: spec_def)\n  by (simp add: case_prod_unfold)\n\ntext\\<open>A conjunction of the post-condition can be split up and be proved separately\\<close>\ntheorem conj_rule_right: \"\\<lbrakk>spec p S q; spec p S s\\<rbrakk> \\<Longrightarrow> spec p S (\\<lambda>x y. q x y \\<and> s x y)\"\n  apply (simp add: spec_def)\n  by (simp add: case_prod_unfold)\n\ntext\\<open>A pre-condition be weaken if it still preserves the post-condition (Weakest pre-condition)\\<close>\ntheorem weaken_rule: \"\\<lbrakk>\\<forall>x. (p x \\<longrightarrow> p0 x); spec p0 S q\\<rbrakk> \\<Longrightarrow> spec p S q\"\n  by (simp add: spec_def)\n\ntext\\<open>A post-condition can be strengthen if it gets preserved by the pre-condition\\<close>\ntheorem strengthen_rule: \"\\<lbrakk>\\<forall>x y. (q0 x y \\<longrightarrow> q x y); spec p S q0\\<rbrakk> \\<Longrightarrow> spec p S q\"\n  apply (simp add: spec_def)\n  by (simp add: case_prod_unfold)\n\ntext\\<open>A conditional statement can be split up into multiple proofs with difference assumptions (based on the queteria)\\<close>\ntheorem cond_rule: \"\\<lbrakk>spec (\\<lambda>x. p x \\<and> b) S q; spec (\\<lambda>x. p x \\<and> \\<not>b) T q\\<rbrakk> \\<Longrightarrow> spec p (if b then S else T) q\"\n  by (simp add: spec_def)\n\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/HL_State.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.877476793890012, "lm_q2_score": 0.8175744806385542, "lm_q1q2_score": 0.7174026340370102}}
{"text": "section \"Solution to Day 1 of AoC 2020\"\n\ntheory day1\n  imports Main \"HOL.Code_Numeral\" string_utils\nbegin\n\ntext \"This is a solution to the puzzle for day 1\"\n\nsubsection \"Input parsing\"\n\ndefinition parse_input :: \"string \\<Rightarrow> natural list\"\n  where \"parse_input s = map str_to_nat (split CHR ''\\<newline>'' (trim s))\"\n\nsubsection \"Solution Algorithm\"\n\ntext \"prod\\\\_of\\\\_sum takes a target number and a list of input numbers, finds the first pair that\nsums to the target number, and returns the product of those two numbers\"\n\nfun prod_of_sum :: \"natural \\<Rightarrow> natural list \\<Rightarrow> natural\"\n  where \"prod_of_sum t (Cons h rest) = (if (List.member rest (t - h)) then (h * (t - h)) else (prod_of_sum t rest))\"\n  |\"prod_of_sum t Nil = 0\"\n\ntext \"The solution to part 1 is simply $$(@{const prod_of_sum} 2020)$$ applied to the input list\"\n\nfun part1 :: \"String.string \\<Rightarrow> natural\"\n  where \"part1 a = (prod_of_sum 2020 (parse_input a))\"\n\ntext \"For the second part we need to do a little bit more checking, we now need three different\nnumbers from the list to add to the target value of 2020\"\n\nfun prod3_of_sum :: \"natural \\<Rightarrow> natural list \\<Rightarrow> natural\"\n  where \"prod3_of_sum t (Cons h rest) =\n    (let p = (h * (prod_of_sum (t - h) rest)) in\n        (if (p = 0) then (prod3_of_sum t rest) else p)\n    ) \n   \"\n  |\"prod3_of_sum t Nil = 0\"\n\nfun part2 :: \"String.string \\<Rightarrow> natural\"\n  where \"part2 s = prod3_of_sum 2020 (parse_input s)\"\n\nsubsection \"Testing\"\n\ntext \"We expect our test case to return 514579\"\n\ndefinition example_input :: \"string\" where \"example_input = ''1721\n979\n366\n299\n675\n1456\n''\"\n\nlemma \"part1 example_input = 514579\"\n  by eval\n\ntext \"We expect our test case for part 2 to return 241861950\"\n\nlemma \"part2 example_input = 241861950\"\n  by eval\n\nexport_code \"part1\" \"part2\" in Haskell module_name Solution\n\nend\n", "meta": {"author": "lexbailey", "repo": "AOC2020_isabelle", "sha": "c08c347793814e9cc3e9d9638dd889d2ada2eb1d", "save_path": "github-repos/isabelle/lexbailey-AOC2020_isabelle", "path": "github-repos/isabelle/lexbailey-AOC2020_isabelle/AOC2020_isabelle-c08c347793814e9cc3e9d9638dd889d2ada2eb1d/day1.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.877476793890012, "lm_q2_score": 0.8175744761936438, "lm_q1q2_score": 0.7174026301367045}}
{"text": "theory Signal\n  imports Complex_Main\n\nbegin\n\nfun Cons_sort :: \"(real\\<times>'v) \\<Rightarrow> (real\\<times>'v) list \\<Rightarrow> (real\\<times>'v) list\" where\n\"Cons_sort y [] = [y]\"\n| \"Cons_sort y (x#xs) = (if fst y < fst x then (y#(x#xs)) else (x#xs))\"\n\nlemma Cons_sort_works:\n  fixes y :: \"(real\\<times>'v)\" and ys :: \"(real \\<times> 'v) list\"\n  assumes \"sorted_wrt (<) (map fst ys)\"\n  shows \"sorted_wrt (<) (map fst (Cons_sort y ys))\"\nproof (cases \"(fst y) < (fst (ys!0)) \\<and> ys \\<noteq> []\")\n  case True\n  then show ?thesis\n    using Cons_sort.elims assms in_set_conv_nth leI list.simps(9) not_less_zero nth_Cons_0 \n      sorted_nth_mono strict_sorted_iff strict_sorted_simps(2)\n    by (smt (verit, best))\nnext\n  case False\n  then show ?thesis\n    using Cons_sort.simps(1) Cons_sort.elims assms list.simps(8,9) nth_Cons_0 sorted_wrt1\n    by metis\nqed\n\ntypedef 'v signal = \"{xs::(real\\<times>'v) list. sorted_wrt (<) (map fst xs)}\"\n  morphisms to_list to_sig \n  apply (rule_tac x=Nil in exI) \n  by force\n\ndeclare to_sig_inverse [simp]\n    and to_list_inverse [simp]\n\nthm list.induct\n\nsetup_lifting type_definition_signal\n\nlift_definition sNil :: \"'v signal\" is Nil by simp\nlift_definition ssCons :: \"(real\\<times>'v) \\<Rightarrow> 'v signal \\<Rightarrow> (real\\<times>'v) list\" is Cons .\nlift_definition ssmap :: \"((real\\<times>'v) \\<Rightarrow> 'a) \\<Rightarrow> 'v signal \\<Rightarrow> 'a list\" is \"map\" .\nlift_definition srel :: \"((real\\<times>'v) \\<Rightarrow> (real\\<times>'v) \\<Rightarrow> bool) \\<Rightarrow> 'v signal \\<Rightarrow> 'v signal \\<Rightarrow> bool\" is \"list_all2\" .\nlift_definition spred :: \"((real\\<times>'v) \\<Rightarrow> bool) \\<Rightarrow> 'v signal \\<Rightarrow> bool\" is \"list_all\" .\nlift_definition snth :: \"'v signal \\<Rightarrow> nat \\<Rightarrow> (real\\<times>'v)\" (infixl \"!!\" 90) is \"(!)\" .\nlift_definition slength :: \"'v signal \\<Rightarrow> nat\" is \"length\" .\nlift_definition shd :: \"'v signal \\<Rightarrow> (real\\<times>'v)\" is \"hd\" .\nlift_definition stl :: \"'v signal \\<Rightarrow> 'v signal\" is \"tl\"\n  by (simp add: distinct_tl map_tl sorted_tl strict_sorted_iff)\nlift_definition sCons :: \"(real\\<times>'v) \\<Rightarrow> 'v signal \\<Rightarrow> 'v signal\" (infixl \"##\" 90) is Cons_sort \n  using Cons_sort_works by blast\n\nlemma sCons_works: \n  fixes t1 :: \"(real\\<times>'v)\" and t :: \"'v signal\"\n  shows \"sorted_wrt (<) (map fst (to_list (sCons t1 t)))\"\n  using Cons_sort_works to_list\n  by fastforce\n\nlemma signal_rep:\n  \"t = sNil \\<or> (\\<exists>p t'. (fst p < fst (t'!!0) \\<or> t' = sNil) \\<and> t = sCons p t')\"\nproof (cases \"t=sNil\")\n  case True\n  then show ?thesis by blast\nnext\n  case False\n  then show ?thesis\n  proof (cases \"slength t = 1\")\n    case True\n    then have \"t=sCons (shd t) sNil\"\n      using \\<open>\\<not>(t=sNil)\\<close>\n      \n\nlemma [case_names sNil sCons, cases type: signal]:\n  \\<comment> \\<open>for backward compatibility -- names of variables differ\\<close>\n  \"(y = sNil \\<Longrightarrow> P) \\<Longrightarrow> (\\<And>a signal. y = sCons a signal \\<Longrightarrow> P) \\<Longrightarrow> P\"\n  by (metis order_less_irrefl sCons_def)\n\nlemma [case_names sNil ssCons, induct type: signal]:\n  \\<comment> \\<open>for backward compatibility -- names of variables differ\\<close>\n  \"P sNil \\<Longrightarrow> (\\<And>a signal. P signal \\<Longrightarrow> P (sCons a signal)) \\<Longrightarrow> P signal\"\nproof -\n  {assume \"P sNil\"\n    assume \"\\<And>a signal. P signal \\<Longrightarrow> P (sCons a signal)\"\n    have \"P signal\"\n    proof (induct \"slength signal\")\n      case 0\n      then have \"signal = sNil\"\n        using length_greater_0_conv list.size(3) sNil.abs_eq slength.rep_eq to_list_inverse\n        by metis\n      then show ?thesis\n        using \\<open>P sNil\\<close>\n        by blast\n    next\n      case (Suc n)\n      then obtain p t' where \"signal = sCons p t'\"\n        using order_less_irrefl sCons_def\n        by metis\n      then show ?thesis\n      proof (cases \"fst p \\<le>\n      have \"slength t' = n\"\n        using Suc \n      then show ?thesis\n        using \\<open>\\<And>a signal. P signal \\<Longrightarrow> P (sCons a signal)\\<close> Suc\n        \n        \n  have \"sorted_wrt (<) (map fst (to_list signal))\"\n    using to_list\n    by blast\n  have \"P  (to_sig [])\"\n    using \\<open>P sNil\\<close> sNil_def\n    by metis\n  then have \"(P \\<circ> to_sig) []\"\n    by simp\n  have 1:\"\\<And>a signal. P signal \\<Longrightarrow> \n    P (if fst a < fst (signal!!0) then to_sig (a#(to_list signal)) else signal)\"\n    using \\<open>\\<And>a signal. P signal \\<Longrightarrow> P (sCons a signal)\\<close> sCons_def\n    by (metis (full_types))\n  {fix a :: \"(real\\<times>'a)\" and signal :: \"'a signal\"\n    {assume 2: \"P (to_sig (to_list signal))\"\n      then have \"P (sCons\n    have \"P (to_sig (to_list signal)) \\<Longrightarrow> P (to_sig (a#(to_list signal)))\"\n    proof -\n      {assume 2:\n        \n  \n    \n\nsetup \\<open>Sign.mandatory_path \"signal\"\\<close>\n\nlemmas inducts = signal.induct\nlemmas recs = signal.rec\nlemmas cases = signal.case\n\nsetup \\<open>Sign.parent_path\\<close>\n\nlemmas set_simps = list.set (* legacy *)\n\ndefinition smap :: \"('v \\<Rightarrow> 'a) \\<Rightarrow> 'v signal \\<Rightarrow> 'a signal\" where\n\"smap f t = to_sig (map (\\<lambda>x. (fst x, f (snd x))) (to_list t))\"\n\ndefinition sfind :: \"real \\<Rightarrow> 'v signal \\<Rightarrow> 'v\" where\n\"sfind x t = (snd (the (find (\\<lambda>y. fst y = x) (to_list t))))\"\n\nlemma smap_nth:\n  assumes \"n<slength t\"\n  shows \"snth (smap f t) n = (fst ((to_list t)!n), f (snd ((to_list t)!n)))\"\nproof -\n  have 1:\"distinct (map fst (to_list t)) \\<and> sorted (map fst (to_list t))\"\n    using to_list strict_sorted_iff\n    by auto\n  have \"\\<forall>n<length (to_list t). fst ((map (\\<lambda>x. (fst x, f (snd x))) (to_list t))!n) = fst ((to_list t)!n)\"\n    by force\n  then have 2:\"distinct (map fst (map (\\<lambda>x. (fst x, f (snd x))) (to_list t))) \n    \\<and> sorted (map fst (map (\\<lambda>x. (fst x, f (snd x))) (to_list t)))\"\n    using 1 length_map list_eq_iff_nth_eq nth_map\n    by (metis (mono_tags, lifting))\n  have \"\\<And>t. snth t n = (to_list t)!n\"\n    by transfer simp\n  then have \"snth (smap f t) n = (to_list (smap f t))!n\"\n    by auto\n  then have \"snth (smap f t) n = (to_list (to_sig (map (\\<lambda>x. (fst x, f (snd x))) (to_list t))))!n\"\n    using smap_def \n    by metis\n  then have \"snth (smap f t) n = (map (\\<lambda>x. (fst x, f (snd x))) (to_list t))!n\"\n    using to_sig_inverse 2 strict_sorted_iff\n    by fastforce\n  then show ?thesis\n    using assms length_map list_update_id map_update nth_list_update_eq slength.rep_eq\n    by (metis (no_types, lifting))\nqed\n\nend", "meta": {"author": "MarkChevallier", "repo": "verifiednntraining", "sha": "master", "save_path": "github-repos/isabelle/MarkChevallier-verifiednntraining", "path": "github-repos/isabelle/MarkChevallier-verifiednntraining/verifiednntraining-master/Isabelle/Signal.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8774768002981829, "lm_q2_score": 0.8175744695262777, "lm_q1q2_score": 0.7174026295254023}}
{"text": "(*  Title:      Dual_Lattice.thy\n    Author:     Peter Gammie, borrowing from Makarius's Lattice theory\n                More modifications by Brian Huffman\n*)\n\nheader {* Lattice operations on dually-ordered types *}\n\ntheory Dual_Lattice\nimports Main\nbegin\n\ntext {*\n  The \\emph{dual} of an ordered structure is an isomorphic copy of the\n  underlying type, with the @{text \\<le>} 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\nlemma dual_undual [simp]: \"dual (undual x') = x'\"\n  by (cases x') simp\n\nlemma undual_comp_dual [simp]:\n  \"undual \\<circ> dual = id\"\n  by (simp add: fun_eq_iff)\n\nlemma dual_comp_undual [simp]:\n  \"dual \\<circ> undual = id\"\n  by (simp add: fun_eq_iff)\n\nlemma dual_eq_iff: \"x = y \\<longleftrightarrow> undual x = undual y\"\n  by (induct x, induct y, simp)\n\nsubsection {* Pointwise ordering *}\n\ninstantiation dual :: (ord) ord\nbegin\n\ndefinition\n  \"x \\<le> y \\<longleftrightarrow> undual y \\<le> undual x\"\n\ndefinition\n  \"(x::'a dual) < y \\<longleftrightarrow> x \\<le> y \\<and> \\<not> y \\<le> x\"\n\ninstance ..\n\nend\n\nlemma undual_leq [iff?]: \"(undual x' \\<le> undual y') = (y' \\<le> x')\"\n  by (simp add: less_eq_dual_def)\n\nlemma dual_leq [intro?, simp]: \"(dual x \\<le> dual y) = (y \\<le> x)\"\n  by (simp add: less_eq_dual_def)\n\n(* FIXME maybe this isn't so useful. *)\n\ntext {*\n  \\medskip Functions @{term dual} and @{term undual} are inverse to\n  each other; this entails the following fundamental properties.\n*}\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\n(* BH: a generalization of dual_ball[symmetric] is already in ball_simps *)\n(* BH: This proof can be replaced with \"by simp\" *)\nlemma dual_ball [iff?]: \"(\\<forall>x \\<in> A. P (dual x)) = (\\<forall>x' \\<in> dual ` A. P x')\"\n  by simp\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\ninstance dual :: (preorder) preorder\nproof\n  fix x y z :: \"'a dual\"\n  show \"x < y \\<longleftrightarrow> x \\<le> y \\<and> \\<not> y \\<le> x\"\n    by (rule less_dual_def)\n  show \"x \\<le> x\"\n    unfolding less_eq_dual_def\n    by fast\n  assume \"x \\<le> y\" and \"y \\<le> z\" thus \"x \\<le> z\"\n    unfolding less_eq_dual_def\n    by (fast elim: order_trans)\nqed\n\ninstance dual :: (order) order\n  by default (auto simp: less_eq_dual_def undual_equality)\n\n\nsubsection {* Binary infimum and supremum *}\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\ninstantiation dual :: (semilattice_sup) semilattice_inf\nbegin\n\ndefinition\n  \"inf f g = dual (sup (undual f) (undual g))\"\n\ninstance\n  by default (auto simp: inf_dual_def less_eq_dual_def)\n\nend\n\ninstantiation dual :: (semilattice_inf) semilattice_sup\nbegin\n\ndefinition\n  \"sup f g = dual (inf (undual f) (undual g))\"\n\ninstance\n  by default (auto simp: sup_dual_def less_eq_dual_def)\n\nend\n\ninstance dual :: (lattice) lattice ..\n\ntext {*\n  Apparently, the @{text \\<sqinter>} and @{text \\<squnion>} operations are dual to each\n  other.\n*}\n\ntheorem dual_inf [intro?]: \"dual (inf x y) = sup (dual x) (dual y)\"\n  unfolding sup_dual_def by simp\n(* BH: Why the \"intro?\" attribute? Why not just \"simp\"? *)\n\ntheorem dual_sup [intro?]: \"dual (sup x y) = inf (dual x) (dual y)\"\n  unfolding inf_dual_def by simp\n\nlemma undual_inf [simp]: \"undual (inf x y) = sup (undual x) (undual y)\"\n  unfolding inf_dual_def by (rule undual_dual)\n\nlemma undual_sup [simp]: \"undual (sup x y) = inf (undual x) (undual y)\"\n  unfolding sup_dual_def by (rule undual_dual)\n\ntext {*\n  Infimum and supremum are dual to each other.\n*}\n\ntheorem dual_inf' [iff?]:\n    \"(inf (dual x) (dual y) = s) = (sup x y = undual s)\"\n  by (cases s) (simp add: inf_dual_def)\n(* BH: This rule seems very contrived. When is it ever useful? *)\n\ntheorem dual_sup' [iff?]:\n    \"(sup (dual x) (dual y) = s) = (inf x y = undual s)\"\n  by (cases s) (simp add: sup_dual_def)\n\ninstance dual :: (distrib_lattice) distrib_lattice\n  by default (simp add: inf_dual_def sup_dual_def inf_sup_distrib1)\n\n\nsubsection {* Top and bottom elements *}\n\ninstantiation dual :: (order_top) order_bot\nbegin\n\ndefinition\n  \"bot = dual top\"\n\ninstance\n  by default (simp add: bot_dual_def less_eq_dual_def)\n\nend\n\ninstantiation dual :: (order_bot) order_top\nbegin\n\ndefinition\n  \"top = dual bot\"\n\ninstance\n  by default (simp add: top_dual_def less_eq_dual_def)\n\nend\n\ninstance dual :: (bounded_lattice_top) bounded_lattice_bot ..\n\ninstance dual :: (bounded_lattice_bot) bounded_lattice_top ..\n\ninstance dual :: (bounded_lattice) bounded_lattice ..\n\ntext {*\n  Likewise are @{text \\<bottom>} and @{text \\<top>} duals of each other.\n*}\n\ntheorem dual_bot [intro?, simp]: \"dual bot = top\"\n  unfolding bot_dual_def top_dual_def by simp\n(* BH: What is the \"intro?\" attribute for? *)\n\ntheorem dual_top [intro?, simp]: \"dual top = bot\"\n  unfolding bot_dual_def top_dual_def by simp\n\ntheorem undual_bot [simp]: \"undual bot = top\"\n  unfolding bot_dual_def by (rule undual_dual)\n\ntheorem undual_top [simp]: \"undual top = bot\"\n  unfolding top_dual_def by (rule undual_dual)\n\ninstantiation dual :: (uminus) uminus\nbegin\n\ndefinition\n  \"- x = dual (- undual x)\"\n\ninstance ..\n\nend\n\nlemma undual_minus [simp]: \"undual (- x) = - undual x\"\n  unfolding uminus_dual_def by (rule undual_dual)\n\ninstantiation dual :: (boolean_algebra) boolean_algebra\nbegin\n\ndefinition\n  \"(x::'a dual) - y = inf x (- y)\"\n\ninstance\n  by default\n    (auto simp: dual_eq_iff sup_compl_top inf_compl_bot minus_dual_def)\n\nend\n\nsubsection {* Complete lattice operations *}\n\ntext {*\n  The class of complete lattices is closed under formation of dual\n  structures.\n*}\n\ninstantiation dual :: (complete_lattice) complete_lattice\nbegin\n\ndefinition\n  \"Sup A \\<equiv> dual (INFIMUM A undual)\"\n\ndefinition\n  \"Inf A \\<equiv> dual (SUPREMUM A undual)\"\n\ninstance\napply intro_classes\napply (auto simp: less_eq_dual_def less_dual_def Sup_dual_def Inf_dual_def\n                  INF_lower SUP_upper\n           intro: INF_greatest SUP_least)\ndone\n\nend\n\nlemma SUP_dual_unfold:\n  \"SUPREMUM A f = dual (INFIMUM A (undual \\<circ> f))\"\n  by (simp add: SUP_def Sup_dual_def)\n\nlemma INF_dual_unfold:\n  \"INFIMUM A f = dual (SUPREMUM A (undual \\<circ> f))\"\n  by (simp add: INF_def Inf_dual_def)\n\ntext {*\n  Apparently, the @{text \\<Sqinter>} and @{text \\<Squnion>} operations are dual to each\n  other.\n*}\n\ntheorem dual_Inf [intro?]: \"dual (Inf A) = Sup (dual ` A)\"\n  unfolding Inf_dual_def Sup_dual_def by (simp add: image_image)\n(* BH: Why not [simp]? *)\n\ntheorem dual_Sup [intro?]: \"dual (Sup A) = Inf (dual ` A)\"\n  unfolding Inf_dual_def Sup_dual_def by (simp add: image_image)\n(* BH: Why not [simp]? *)\n\nlemma undual_Inf: \"undual (Inf A) = Sup (undual ` A)\"\n  unfolding Inf_dual_def by simp\n\nlemma undual_Sup: \"undual (Sup A) = Inf (undual ` A)\"\n  unfolding Sup_dual_def by simp\n\ntheorem dual_Inf' [iff?]:\n    \"(Inf (dual ` A) = dual s) = (Sup A = s)\"\n  unfolding Inf_dual_def Sup_dual_def by (simp add: image_image)\n(* BH: When would this lemma ever be useful? *)\n\ntheorem dual_Sup' [iff?]:\n    \"(Sup (dual ` A) = dual i) = (Inf A = i)\"\n  unfolding Inf_dual_def Sup_dual_def by (simp add: image_image)\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/PCF/Dual_Lattice.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8479677660619633, "lm_q2_score": 0.8459424392504911, "lm_q1q2_score": 0.717331920428247}}
{"text": "(*  Title:      HOL/ex/ThreeDivides.thy\n    Author:     Benjamin Porter, 2005\n*)\n\nsection \\<open>Three Divides Theorem\\<close>\n\ntheory ThreeDivides\nimports Main \"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>\\<open>D i\\<close> 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>\\<open>D :: (nat\\<Rightarrow>nat)\\<close>),\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>\\<open>(\\<Sum>x<nd. D x * 10^x) - (\\<Sum>x<nd. D x)\\<close>\\<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.atLeast_Suc_lessThan 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": "seL4", "repo": "isabelle", "sha": "e1ab32a3bb41728cd19541063283e37919978a4c", "save_path": "github-repos/isabelle/seL4-isabelle", "path": "github-repos/isabelle/seL4-isabelle/isabelle-e1ab32a3bb41728cd19541063283e37919978a4c/src/HOL/ex/ThreeDivides.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.84594244507642, "lm_q2_score": 0.8479677545357568, "lm_q1q2_score": 0.7173319156179396}}
{"text": "(*  Title:      HOL/Analysis/Determinants.thy\n    Author:     Amine Chaieb, University of Cambridge; proofs reworked by LCP\n*)\n\nsection \\<open>Traces and Determinants of Square Matrices\\<close>\n\ntheory Determinants\nimports\n  Cartesian_Space\n  \"HOL-Library.Permutations\"\nbegin\n\nsubsection  \\<open>Trace\\<close>\n\ndefinition\\<^marker>\\<open>tag important\\<close>  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.swap)\n  apply (simp add: mult.commute)\n  done\n\nsubsubsection\\<^marker>\\<open>tag important\\<close>  \\<open>Definition of determinant\\<close>\n\ndefinition\\<^marker>\\<open>tag important\\<close>  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>Basic determinant properties\\<close>\n\nlemma  det_transpose [simp]: \"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      have \"((\\<lambda>i. ?di (transpose A) i (inv p i)) \\<circ> p) i = ?di A i (p i)\" if \"i \\<in> ?U\" for i\n        using that permutes_inv_o[OF pU] permutes_in_image[OF pU]\n        unfolding transpose_def by (simp add: fun_eq_iff)\n      then show \"prod ((\\<lambda>i. ?di (transpose A) i (inv p i)) \\<circ> p) ?U = 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    by (subst sum_permutations_inverse) (blast intro: sum.cong)\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  have id0: \"{id} \\<subseteq> ?PU\"\n    by (auto simp: permutes_id)\n  have p0: \"\\<forall>p \\<in> ?PU - {id}. ?pp p = 0\"\n  proof\n    fix p\n    assume \"p \\<in> ?PU - {id}\"\n    then obtain i where i: \"p i > i\"\n      by clarify (meson leI permutes_natset_le)\n    from ld[OF i] have \"\\<exists>i \\<in> ?U. A$i$p i = 0\"\n      by blast\n    with prod_zero[OF fU] show \"?pp p = 0\"\n      by force\n  qed\n  from sum.mono_neutral_cong_left[OF finite_permutations[OF fU] 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  have id0: \"{id} \\<subseteq> ?PU\"\n    by (auto simp: permutes_id)\n  have p0: \"\\<forall>p \\<in> ?PU -{id}. ?pp p = 0\"\n  proof\n    fix p\n    assume p: \"p \\<in> ?PU - {id}\"\n    then obtain i where i: \"p i < i\"\n      by clarify (meson leI permutes_natset_ge)\n    from ld[OF i] have \"\\<exists>i \\<in> ?U. A$i$p i = 0\"\n      by blast\n    with prod_zero[OF fU]  show \"?pp p = 0\"\n      by force\n  qed\n  from sum.mono_neutral_cong_left[OF finite_permutations[OF fU] id0 p0] show ?thesis\n    unfolding det_def by (simp add: sign_id)\nqed\n\nproposition  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: permutes_id)\n  have p0: \"\\<forall>p \\<in> ?PU - {id}. ?pp p = 0\"\n  proof\n    fix p\n    assume p: \"p \\<in> ?PU - {id}\"\n    then obtain i where i: \"p i \\<noteq> i\"\n      by fastforce\n    with ld have \"\\<exists>i \\<in> ?U. A$i$p i = 0\"\n      by (metis UNIV_I)\n    with prod_zero [OF fU] show \"?pp p = 0\"\n      by force\n  qed\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 [simp]: \"det (mat 1 :: 'a::comm_ring_1^'n^'n) = 1\"\n  by (simp add: det_diagonal mat_def)\n\nlemma  det_0 [simp]: \"det (mat 0 :: 'a::comm_ring_1^'n^'n) = 0\"\n  by (simp add: det_def prod_zero power_0_left)\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\"\nproof -\n  let ?U = \"UNIV :: 'n set\"\n  let ?PU = \"{p. p permutes ?U}\"\n  have *: \"(\\<Sum>q\\<in>?PU. of_int (sign (q \\<circ> p)) * (\\<Prod>i\\<in>?U. A $ p i $ (q \\<circ> p) i)) =\n           (\\<Sum>n\\<in>?PU. of_int (sign p) * of_int (sign n) * (\\<Prod>i\\<in>?U. A $ i $ n i))\"\n  proof (rule sum.cong)\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    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 permutes_inv[OF p], 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    from p q have pp: \"permutation p\" and qp: \"permutation q\"\n      by (metis fU permutation_permutes)+\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)\n  qed auto\n  show ?thesis\n    apply (simp add: det_def sum_distrib_left mult.assoc[symmetric])\n    apply (subst sum_permutations_compose_right[OF p])\n    apply (rule *)\n    done\nqed\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_columns:\n  fixes A :: \"'a::comm_ring_1^'n^'n\"\n  assumes jk: \"j \\<noteq> k\"\n    and r: \"column j A = column k A\"\n  shows \"det A = 0\"\nproof -\n  let ?U=\"UNIV::'n set\"\n  let ?t_jk=\"Fun.swap j k id\"\n  let ?PU=\"{p. p permutes ?U}\"\n  let ?S1=\"{p. p\\<in>?PU \\<and> evenperm p}\"\n  let ?S2=\"{(?t_jk \\<circ> p) |p. p \\<in>?S1}\"\n  let ?f=\"\\<lambda>p. of_int (sign p) * (\\<Prod>i\\<in>UNIV. A $ i $ p i)\"\n  let ?g=\"\\<lambda>p. ?t_jk \\<circ> p\"\n  have g_S1: \"?S2 = ?g` ?S1\" by auto\n  have inj_g: \"inj_on ?g ?S1\"\n  proof (unfold inj_on_def, auto)\n    fix x y assume x: \"x permutes ?U\" and even_x: \"evenperm x\"\n      and y: \"y permutes ?U\" and even_y: \"evenperm y\" and eq: \"?t_jk \\<circ> x = ?t_jk \\<circ> y\"\n    show \"x = y\" by (metis (hide_lams, no_types) comp_assoc eq id_comp swap_id_idempotent)\n  qed\n  have tjk_permutes: \"?t_jk permutes ?U\" unfolding permutes_def swap_id_eq by (auto,metis)\n  have tjk_eq: \"\\<forall>i l. A $ i $ ?t_jk l  =  A $ i $ l\"\n    using r jk\n    unfolding column_def vec_eq_iff swap_id_eq by fastforce\n  have sign_tjk: \"sign ?t_jk = -1\" using sign_swap_id[of j k] jk by auto\n  {fix x\n    assume x: \"x\\<in> ?S1\"\n    have \"sign (?t_jk \\<circ> x) = sign (?t_jk) * sign x\"\n      by (metis (lifting) finite_class.finite_UNIV mem_Collect_eq\n          permutation_permutes permutation_swap_id sign_compose x)\n    also have \"\\<dots> = - sign x\" using sign_tjk by simp\n    also have \"\\<dots> \\<noteq> sign x\" unfolding sign_def by simp\n    finally have \"sign (?t_jk \\<circ> x) \\<noteq> sign x\" and \"(?t_jk \\<circ> x) \\<in> ?S2\"\n      using x by force+\n  }\n  hence disjoint: \"?S1 \\<inter> ?S2 = {}\"\n    by (force simp: sign_def)\n  have PU_decomposition: \"?PU = ?S1 \\<union> ?S2\"\n  proof (auto)\n    fix x\n    assume x: \"x permutes ?U\" and \"\\<forall>p. p permutes ?U \\<longrightarrow> x = Fun.swap j k id \\<circ> p \\<longrightarrow> \\<not> evenperm p\"\n    then obtain p where p: \"p permutes UNIV\" and x_eq: \"x = Fun.swap j k id \\<circ> p\"\n      and odd_p: \"\\<not> evenperm p\"\n      by (metis (mono_tags) id_o o_assoc permutes_compose swap_id_idempotent tjk_permutes)\n    thus \"evenperm x\"\n      by (meson evenperm_comp evenperm_swap finite_class.finite_UNIV\n          jk permutation_permutes permutation_swap_id)\n  next\n    fix p assume p: \"p permutes ?U\"\n    show \"Fun.swap j k id \\<circ> p permutes UNIV\" by (metis p permutes_compose tjk_permutes)\n  qed\n  have \"sum ?f ?S2 = sum ((\\<lambda>p. of_int (sign p) * (\\<Prod>i\\<in>UNIV. A $ i $ p i))\n  \\<circ> (\\<circ>) (Fun.swap j k id)) {p \\<in> {p. p permutes UNIV}. evenperm p}\"\n    unfolding g_S1 by (rule sum.reindex[OF inj_g])\n  also have \"\\<dots> = sum (\\<lambda>p. of_int (sign (?t_jk \\<circ> p)) * (\\<Prod>i\\<in>UNIV. A $ i $ p i)) ?S1\"\n    unfolding o_def by (rule sum.cong, auto simp: tjk_eq)\n  also have \"\\<dots> = sum (\\<lambda>p. - ?f p) ?S1\"\n  proof (rule sum.cong, auto)\n    fix x assume x: \"x permutes ?U\"\n      and even_x: \"evenperm x\"\n    hence perm_x: \"permutation x\" and perm_tjk: \"permutation ?t_jk\"\n      using permutation_permutes[of x] permutation_permutes[of ?t_jk] permutation_swap_id\n      by (metis finite_code)+\n    have \"(sign (?t_jk \\<circ> x)) = - (sign x)\"\n      unfolding sign_compose[OF perm_tjk perm_x] sign_tjk by auto\n    thus \"of_int (sign (?t_jk \\<circ> x)) * (\\<Prod>i\\<in>UNIV. A $ i $ x i)\n      = - (of_int (sign x) * (\\<Prod>i\\<in>UNIV. A $ i $ x i))\"\n      by auto\n  qed\n  also have \"\\<dots>= - sum ?f ?S1\" unfolding sum_negf ..\n  finally have *: \"sum ?f ?S2 = - sum ?f ?S1\" .\n  have \"det A = (\\<Sum>p | p permutes UNIV. of_int (sign p) * (\\<Prod>i\\<in>UNIV. A $ i $ p i))\"\n    unfolding det_def ..\n  also have \"\\<dots>= sum ?f ?S1 + sum ?f ?S2\"\n    by (subst PU_decomposition, rule sum.union_disjoint[OF _ _ disjoint], auto)\n  also have \"\\<dots>= sum ?f ?S1 - sum ?f ?S1 \" unfolding * by auto\n  also have \"\\<dots>= 0\" by simp\n  finally show \"det A = 0\" by simp\nqed\n\nlemma  det_identical_rows:\n  fixes A :: \"'a::comm_ring_1^'n^'n\"\n  assumes ij: \"i \\<noteq> j\" and r: \"row i A = row j A\"\n  shows \"det A = 0\"\n  by (metis column_transpose det_identical_columns det_transpose ij r)\n\nlemma  det_zero_row:\n  fixes A :: \"'a::{idom, ring_char_0}^'n^'n\" and F :: \"'b::{field}^'m^'m\"\n  shows \"row i A = 0 \\<Longrightarrow> det A = 0\" and \"row j F = 0 \\<Longrightarrow> det F = 0\"\n  by (force simp: row_def det_def vec_eq_iff sign_nz intro!: sum.neutral)+\n\nlemma  det_zero_column:\n  fixes A :: \"'a::{idom, ring_char_0}^'n^'n\" and F :: \"'b::{field}^'m^'m\"\n  shows \"column i A = 0 \\<Longrightarrow> det A = 0\" and \"column j F = 0 \\<Longrightarrow> det F = 0\"\n  unfolding atomize_conj atomize_imp\n  by (metis det_transpose det_zero_row row_transpose)\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  have eq: \"prod (\\<lambda>i. ?f i $ p i) ?Uk = prod (\\<lambda>i. ?g i $ p i) ?Uk\"\n           \"prod (\\<lambda>i. ?f i $ p i) ?Uk = prod (\\<lambda>i. ?h i $ p i) ?Uk\"\n    by auto\n  have Uk: \"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    by (rule prod.insert) auto\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 eq)\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 Uk] 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 auto\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  have eq: \"prod (\\<lambda>i. ?f i $ p i) ?Uk = prod (\\<lambda>i. ?g i $ p i) ?Uk\"\n    by auto\n  have Uk: \"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    by (rule prod.insert) auto\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 eq 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 Uk] 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 = c * (of_int (sign p) * prod (\\<lambda>i. ?g i $ p i) ?U)\"\n    by (simp add: field_simps)\nqed auto\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::{comm_ring_1}^'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 :: \"'a::{field}^'n^'n\"\n  assumes x: \"x \\<in> vec.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\"\n  using x\nproof (induction rule: vec.span_induct_alt)\n  case base\n  have \"(if k = i then row i A + 0 else row k A) = row k A\" for k\n    by simp\n  then show ?case\n    by (simp add: row_def)\nnext\n  case (step c z y)\n  then 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  let ?d = \"\\<lambda>x. det (\\<chi> k. if k = i then x else row k A)\"\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 \"?d (row i A + (c*s z + y)) = det A\"\n    unfolding thz step.IH det_row_mul[of i] det_row_add[of i] by simp\n  then show ?case\n    unfolding scalar_mult_eq_scaleR .\nqed\n\nlemma  matrix_id [simp]: \"det (matrix id) = 1\"\n  by (simp add: matrix_id_mat_1)\n\nproposition  det_matrix_scaleR [simp]: \"det (matrix (((*\\<^sub>R) r)) :: real^'n^'n) = r ^ CARD('n::finite)\"\n  apply (subst det_diagonal)\n   apply (auto simp: matrix_def mat_def)\n  apply (simp add: cart_eq_inner_axis inner_axis_axis)\n  done\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:: \"'a::{field}^'n^'n\"\n  assumes d: \"vec.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> vec.span (rows A - {row i A})\"\n    unfolding vec.dependent_def rows_def by blast\n  show ?thesis\n  proof (cases \"\\<forall>i j. i \\<noteq> j \\<longrightarrow> row i A \\<noteq> row j A\")\n    case True\n    with i have \"vec.span (rows A - {row i A}) \\<subseteq> vec.span {row j A |j. j \\<noteq> i}\"\n      by (auto simp: rows_def intro!: vec.span_mono)\n    then have \"- row i A \\<in> vec.span {row j A|j. j \\<noteq> i}\"\n      by (meson i subsetCE vec.span_neg)\n    from det_row_span[OF this]\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 \"\\<lambda>i. 1\"]\n    show ?thesis by simp\n  next\n    case False\n    then obtain j k where jk: \"j \\<noteq> k\" \"row j A = row k A\"\n      by auto\n    from det_identical_rows[OF jk] show ?thesis .\n  qed\nqed\n\nlemma  det_dependent_columns:\n  assumes d: \"vec.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 auto\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\"\n  using fS  by (induct rule: finite_induct; simp add: det_row_0 det_row_add cong: if_cong)\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 *: \"{f. \\<forall>i. f i = i} = {id}\"\n    by auto\n  show ?case\n    by (auto simp: *)\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: image_iff)\n    apply (rename_tac f)\n    apply (rule_tac x=\"f (Suc k)\" in bexI)\n    apply (rule_tac x = \"\\<lambda>i. if i = Suc k then i else f i\" in exI, 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 \\<noteq> z\"\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    by (subst thif2) (simp add: nz cong: if_cong)\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\nlemma  det_rows_mul:\n  \"det((\\<chi> i. c i *s a i)::'a::comm_ring_1^'n^'n) =\n    prod (\\<lambda>i. c i) (UNIV:: 'n set) * det((\\<chi> i. a i)::'a^'n^'n)\"\nproof (simp add: det_def sum_distrib_left cong add: prod.cong, rule sum.cong)\n  let ?U = \"UNIV :: 'n set\"\n  let ?PU = \"{p. p permutes ?U}\"\n  fix p\n  assume pU: \"p \\<in> ?PU\"\n  let ?s = \"of_int (sign p)\"\n  from pU have p: \"p permutes ?U\"\n    by blast\n  have \"prod (\\<lambda>i. c i * a i $ p i) ?U = prod c ?U * prod (\\<lambda>i. a i $ p i) ?U\"\n    unfolding prod.distrib ..\n  then show \"?s * (\\<Prod>xa\\<in>?U. c xa * a xa $ p xa) =\n    prod c ?U * (?s* (\\<Prod>xa\\<in>?U. a xa $ p xa))\"\n    by (simp add: field_simps)\nqed rule\n\nproposition  det_mul:\n  fixes A B :: \"'a::comm_ring_1^'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 \"p \\<in> ?F\" if \"p permutes ?U\" for p\n    by simp\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      then have \"row i ?B = row j ?B\"\n        by (vector row_def)\n      with det_identical_rows[OF ij(2)]\n      have \"det (\\<chi> i. A$i$f i *s B$f i) = 0\"\n        unfolding det_rows_mul by force\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 finite finite refl fUU, symmetric]]\n      have \"\\<exists>!x. f x = y\" for y\n        using fith fs by blast\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 finite]\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 finite PUF zth, symmetric]\n    unfolding det_rows_mul by auto\n  finally show ?thesis unfolding th2 .\nqed\n\n\nsubsection \\<open>Relation to invertibility\\<close>\n\nproposition  invertible_det_nz:\n  fixes A::\"'a::{field}^'n^'n\"\n  shows \"invertible A \\<longleftrightarrow> det A \\<noteq> 0\"\nproof (cases \"invertible A\")\n  case True\n  then obtain B :: \"'a^'n^'n\" where B: \"A ** B = mat 1\"\n    unfolding invertible_right_inverse by blast\n  then have \"det (A ** B) = det (mat 1 :: 'a^'n^'n)\"\n    by simp\n  then show ?thesis\n    by (metis True det_I det_mul mult_zero_left one_neq_zero)\nnext\n  case False\n  let ?U = \"UNIV :: 'n set\"\n  have fU: \"finite ?U\"\n    by simp\n  from False obtain c i where c: \"sum (\\<lambda>i. c i *s row i A) ?U = 0\" and iU: \"i \\<in> ?U\" and ci: \"c i \\<noteq> 0\"\n    unfolding invertible_right_inverse matrix_right_invertible_independent_rows\n    by blast\n  have thr0: \"- row i A = sum (\\<lambda>j. (1/ c i) *s (c j *s row j A)) (?U - {i})\"\n    unfolding sum_cmul  using c ci\n    by (auto simp: sum.remove[OF fU iU] eq_vector_fraction_iff add_eq_0_iff)\n  have thr: \"- row i A \\<in> vec.span {row j A| j. j \\<noteq> i}\"\n    unfolding thr0 by (auto intro: vec.span_base vec.span_scale vec.span_sum)\n  let ?B = \"(\\<chi> k. if k = i then 0 else row k A) :: 'a^'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(2)[OF thrb] ..\n  then show ?thesis\n    by (simp add: False)\nqed\n\n\nlemma  det_nz_iff_inj_gen:\n  fixes f :: \"'a::field^'n \\<Rightarrow> 'a::field^'n\"\n  assumes \"Vector_Spaces.linear (*s) (*s) f\"\n  shows \"det (matrix f) \\<noteq> 0 \\<longleftrightarrow> inj f\"\nproof\n  assume \"det (matrix f) \\<noteq> 0\"\n  then show \"inj f\"\n    using assms invertible_det_nz inj_matrix_vector_mult by force\nnext\n  assume \"inj f\"\n  show \"det (matrix f) \\<noteq> 0\"\n    using vec.linear_injective_left_inverse [OF assms \\<open>inj f\\<close>]\n    by (metis assms invertible_det_nz invertible_left_inverse matrix_compose_gen matrix_id_mat_1)\nqed\n\nlemma  det_nz_iff_inj:\n  fixes f :: \"real^'n \\<Rightarrow> real^'n\"\n  assumes \"linear f\"\n  shows \"det (matrix f) \\<noteq> 0 \\<longleftrightarrow> inj f\"\n  using det_nz_iff_inj_gen[of f] assms\n  unfolding linear_matrix_vector_mul_eq .\n\nlemma  det_eq_0_rank:\n  fixes A :: \"real^'n^'n\"\n  shows \"det A = 0 \\<longleftrightarrow> rank A < CARD('n)\"\n  using invertible_det_nz [of A]\n  by (auto simp: matrix_left_invertible_injective invertible_left_inverse less_rank_noninjective)\n\nsubsubsection\\<^marker>\\<open>tag important\\<close>  \\<open>Invertibility of matrices and corresponding linear functions\\<close>\n\nlemma  matrix_left_invertible_gen:\n  fixes f :: \"'a::field^'m \\<Rightarrow> 'a::field^'n\"\n  assumes \"Vector_Spaces.linear (*s) (*s) f\"\n  shows \"((\\<exists>B. B ** matrix f = mat 1) \\<longleftrightarrow> (\\<exists>g. Vector_Spaces.linear (*s) (*s) g \\<and> g \\<circ> f = id))\"\nproof safe\n  fix B\n  assume 1: \"B ** matrix f = mat 1\"\n  show \"\\<exists>g. Vector_Spaces.linear (*s) (*s) g \\<and> g \\<circ> f = id\"\n  proof (intro exI conjI)\n    show \"Vector_Spaces.linear (*s) (*s) (\\<lambda>y. B *v y)\"\n      by simp\n    show \"((*v) B) \\<circ> f = id\"\n      unfolding o_def\n      by (metis assms 1 eq_id_iff matrix_vector_mul(1) matrix_vector_mul_assoc matrix_vector_mul_lid)\n  qed\nnext\n  fix g\n  assume \"Vector_Spaces.linear (*s) (*s) g\" \"g \\<circ> f = id\"\n  then have \"matrix g ** matrix f = mat 1\"\n    by (metis assms matrix_compose_gen matrix_id_mat_1)\n  then show \"\\<exists>B. B ** matrix f = mat 1\" ..\nqed\n\nlemma  matrix_left_invertible:\n  \"linear f \\<Longrightarrow> ((\\<exists>B. B ** matrix f = mat 1) \\<longleftrightarrow> (\\<exists>g. linear g \\<and> g \\<circ> f = id))\" for f::\"real^'m \\<Rightarrow> real^'n\"\n  using matrix_left_invertible_gen[of f]\n  by (auto simp: linear_matrix_vector_mul_eq)\n\nlemma  matrix_right_invertible_gen:\n  fixes f :: \"'a::field^'m \\<Rightarrow> 'a^'n\"\n  assumes \"Vector_Spaces.linear (*s) (*s) f\"\n  shows \"((\\<exists>B. matrix f ** B = mat 1) \\<longleftrightarrow> (\\<exists>g. Vector_Spaces.linear (*s) (*s) g \\<and> f \\<circ> g = id))\"\nproof safe\n  fix B\n  assume 1: \"matrix f ** B = mat 1\"\n  show \"\\<exists>g. Vector_Spaces.linear (*s) (*s) g \\<and> f \\<circ> g = id\"\n  proof (intro exI conjI)\n    show \"Vector_Spaces.linear (*s) (*s) ((*v) B)\"\n      by simp\n    show \"f \\<circ> (*v) B = id\"\n      using 1 assms comp_apply eq_id_iff vec.linear_id matrix_id_mat_1 matrix_vector_mul_assoc matrix_works\n      by (metis (no_types, hide_lams))\n  qed\nnext\n  fix g\n  assume \"Vector_Spaces.linear (*s) (*s) g\" and \"f \\<circ> g = id\"\n  then have \"matrix f ** matrix g = mat 1\"\n    by (metis assms matrix_compose_gen matrix_id_mat_1)\n  then show \"\\<exists>B. matrix f ** B = mat 1\" ..\nqed\n\nlemma  matrix_right_invertible:\n  \"linear f \\<Longrightarrow> ((\\<exists>B. matrix f ** B = mat 1) \\<longleftrightarrow> (\\<exists>g. linear g \\<and> f \\<circ> g = id))\" for f::\"real^'m \\<Rightarrow> real^'n\"\n  using matrix_right_invertible_gen[of f]\n  by (auto simp: linear_matrix_vector_mul_eq)\n\nlemma  matrix_invertible_gen:\n  fixes f :: \"'a::field^'m \\<Rightarrow> 'a::field^'n\"\n  assumes \"Vector_Spaces.linear (*s) (*s) f\"\n  shows  \"invertible (matrix f) \\<longleftrightarrow> (\\<exists>g. Vector_Spaces.linear (*s) (*s) g \\<and> f \\<circ> g = id \\<and> g \\<circ> f = id)\"\n    (is \"?lhs = ?rhs\")\nproof\n  assume ?lhs then show ?rhs\n    by (metis assms invertible_def left_right_inverse_eq matrix_left_invertible_gen matrix_right_invertible_gen)\nnext\n  assume ?rhs then show ?lhs\n    by (metis assms invertible_def matrix_compose_gen matrix_id_mat_1)\nqed\n\nlemma  matrix_invertible:\n  \"linear f \\<Longrightarrow> invertible (matrix f) \\<longleftrightarrow> (\\<exists>g. linear g \\<and> f \\<circ> g = id \\<and> g \\<circ> f = id)\"\n  for f::\"real^'m \\<Rightarrow> real^'n\"\n  using matrix_invertible_gen[of f]\n  by (auto simp: linear_matrix_vector_mul_eq)\n\nlemma  invertible_eq_bij:\n  fixes m :: \"'a::field^'m^'n\"\n  shows \"invertible m \\<longleftrightarrow> bij ((*v) m)\"\n  using matrix_invertible_gen[OF matrix_vector_mul_linear_gen, of m, simplified matrix_of_matrix_vector_mul]\n  by (metis bij_betw_def left_right_inverse_eq matrix_vector_mul_linear_gen o_bij\n      vec.linear_injective_left_inverse vec.linear_surjective_right_inverse)\n\n\nsubsection \\<open>Cramer's rule\\<close>\n\nlemma  cramer_lemma_transpose:\n  fixes A:: \"'a::{field}^'n^'n\"\n    and x :: \"'a::{field}^'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)::'a::{field}^'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 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    by (force intro: det_row_span vec.span_sum vec.span_scale vec.span_base)\n  show \"?lhs = x$k * det A\"\n    apply (subst U)\n    unfolding sum.insert[OF finite 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\nproposition  cramer_lemma:\n  fixes A :: \"'a::{field}^'n^'n\"\n  shows \"det((\\<chi> i j. if j = k then (A *v x)$i else A$i$j):: 'a::{field}^'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 intro: sum.cong)\n  show ?thesis\n    unfolding matrix_mult_sum\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\nproposition  cramer:\n  fixes A ::\"'a::{field}^'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)\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\nlemma  det_1: \"det (A::'a::comm_ring_1^1^1) = A$1$1\"\n  by (simp add: det_def 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\nproposition  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 \"Q ** transpose Q = mat 1\"\n    by (metis oQ 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)\n  then show ?thesis\n    by (simp add: square_eq_1_iff)\nqed\n\nproposition  orthogonal_transformation_det [simp]:\n  fixes f :: \"real^'n \\<Rightarrow> real^'n\"\n  shows \"orthogonal_transformation f \\<Longrightarrow> \\<bar>det (matrix f)\\<bar> = 1\"\n  using det_orthogonal_matrix orthogonal_transformation_matrix by fastforce\n\nsubsection  \\<open>Rotation, reflection, rotoinversion\\<close>\n\ndefinition\\<^marker>\\<open>tag important\\<close>  \"rotation_matrix Q \\<longleftrightarrow> orthogonal_matrix Q \\<and> det Q = 1\"\ndefinition\\<^marker>\\<open>tag important\\<close>  \"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> Slightly stronger results giving rotation, but only in two or more dimensions\\<close>\n\nlemma  rotation_matrix_exists_basis:\n  fixes a :: \"real^'n\"\n  assumes 2: \"2 \\<le> CARD('n)\" and \"norm a = 1\"\n  obtains A where \"rotation_matrix A\" \"A *v (axis k 1) = a\"\nproof -\n  obtain A where \"orthogonal_matrix A\" and A: \"A *v (axis k 1) = a\"\n    using orthogonal_matrix_exists_basis assms by metis\n  with orthogonal_rotation_or_rotoinversion\n  consider \"rotation_matrix A\" | \"rotoinversion_matrix A\"\n    by metis\n  then show thesis\n  proof cases\n    assume \"rotation_matrix A\"\n    then show ?thesis\n      using \\<open>A *v axis k 1 = a\\<close> that by auto\n  next\n    from ex_card[OF 2] obtain h i::'n where \"h \\<noteq> i\"\n      by (auto simp add: eval_nat_numeral card_Suc_eq)\n    then obtain j where \"j \\<noteq> k\"\n      by (metis (full_types))\n    let ?TA = \"transpose A\"\n    let ?A = \"\\<chi> i. if i = j then - 1 *\\<^sub>R (?TA $ i) else ?TA $i\"\n    assume \"rotoinversion_matrix A\"\n    then have [simp]: \"det A = -1\"\n      by (simp add: rotoinversion_matrix_def)\n    show ?thesis\n    proof\n      have [simp]: \"row i (\\<chi> i. if i = j then - 1 *\\<^sub>R ?TA $ i else ?TA $ i) = (if i = j then - row i ?TA else row i ?TA)\" for i\n        by (auto simp: row_def)\n      have \"orthogonal_matrix ?A\"\n        unfolding orthogonal_matrix_orthonormal_rows\n        using \\<open>orthogonal_matrix A\\<close> by (auto simp: orthogonal_matrix_orthonormal_columns orthogonal_clauses)\n      then show \"rotation_matrix (transpose ?A)\"\n        unfolding rotation_matrix_def\n        by (simp add: det_row_mul[of j _ \"\\<lambda>i. ?TA $ i\", unfolded scalar_mult_eq_scaleR])\n      show \"transpose ?A *v axis k 1 = a\"\n        using \\<open>j \\<noteq> k\\<close> A by (simp add: matrix_vector_column axis_def scalar_mult_eq_scaleR if_distrib [of \"\\<lambda>z. z *\\<^sub>R c\" for c] cong: if_cong)\n    qed\n  qed\nqed\n\nlemma  rotation_exists_1:\n  fixes a :: \"real^'n\"\n  assumes \"2 \\<le> CARD('n)\" \"norm a = 1\" \"norm b = 1\"\n  obtains f where \"orthogonal_transformation f\" \"det(matrix f) = 1\" \"f a = b\"\nproof -\n  obtain k::'n where True\n    by simp\n  obtain A B where AB: \"rotation_matrix A\" \"rotation_matrix B\"\n               and eq: \"A *v (axis k 1) = a\" \"B *v (axis k 1) = b\"\n    using rotation_matrix_exists_basis assms by metis\n  let ?f = \"\\<lambda>x. (B ** transpose A) *v x\"\n  show thesis\n  proof\n    show \"orthogonal_transformation ?f\"\n      using AB orthogonal_matrix_mul orthogonal_transformation_matrix rotation_matrix_def matrix_vector_mul_linear by force\n    show \"det (matrix ?f) = 1\"\n      using AB by (auto simp: det_mul rotation_matrix_def)\n    show \"?f a = b\"\n      using AB unfolding orthogonal_matrix_def rotation_matrix_def\n      by (metis eq matrix_mul_rid matrix_vector_mul_assoc)\n  qed\nqed\n\nlemma  rotation_exists:\n  fixes a :: \"real^'n\"\n  assumes 2: \"2 \\<le> CARD('n)\" and eq: \"norm a = norm b\"\n  obtains f where \"orthogonal_transformation f\" \"det(matrix f) = 1\" \"f a = b\"\nproof (cases \"a = 0 \\<or> b = 0\")\n  case True\n  with assms have \"a = 0\" \"b = 0\"\n    by auto\n  then show ?thesis\n    by (metis eq_id_iff matrix_id orthogonal_transformation_id that)\nnext\n  case False\n  then obtain f where f: \"orthogonal_transformation f\" \"det (matrix f) = 1\"\n    and f': \"f (a /\\<^sub>R norm a) = b /\\<^sub>R norm b\"\n    using rotation_exists_1 [of \"a /\\<^sub>R norm a\" \"b /\\<^sub>R norm b\", OF 2] by auto\n  then interpret linear f by (simp add: orthogonal_transformation)\n  have \"f a = b\"\n    using f' False\n    by (simp add: eq scale)\n  with f show thesis ..\nqed\n\nlemma  rotation_rightward_line:\n  fixes a :: \"real^'n\"\n  obtains f where \"orthogonal_transformation f\" \"2 \\<le> CARD('n) \\<Longrightarrow> det(matrix f) = 1\"\n                  \"f(norm a *\\<^sub>R axis k 1) = a\"\nproof (cases \"CARD('n) = 1\")\n  case True\n  obtain f where \"orthogonal_transformation f\" \"f (norm a *\\<^sub>R axis k (1::real)) = a\"\n  proof (rule orthogonal_transformation_exists)\n    show \"norm (norm a *\\<^sub>R axis k (1::real)) = norm a\"\n      by simp\n  qed auto\n  then show thesis\n    using True that by auto\nnext\n  case False\n  obtain f where \"orthogonal_transformation f\" \"det(matrix f) = 1\" \"f (norm a *\\<^sub>R axis k 1) = a\"\n  proof (rule rotation_exists)\n    show \"2 \\<le> CARD('n)\"\n      using False one_le_card_finite [where 'a='n] by linarith\n    show \"norm (norm a *\\<^sub>R axis k (1::real)) = norm a\"\n      by simp\n  qed auto\n  then show thesis\n    using that by blast\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/Analysis/Determinants.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.84594244507642, "lm_q2_score": 0.8479677506936878, "lm_q1q2_score": 0.7173319123677704}}
{"text": "theory Turan\n  imports\n    \"Girth_Chromatic.Ugraphs\"\n    \"Random_Graph_Subgraph_Threshold.Ugraph_Lemmas\"\nbegin\n\nsection \\<open>Basic facts on graphs\\<close>\n\nlemma wellformed_uverts_0 :\n  assumes \"uwellformed G\" and \"uverts G = {}\"\n  shows \"card (uedges G) = 0\" using assms\n  by (metis uwellformed_def card.empty ex_in_conv zero_neq_numeral)\n\nlemma finite_verts_edges :\n  assumes \"uwellformed G\" and \"finite (uverts G)\"\n  shows \"finite (uedges G)\"\nproof -\n  have sub_pow: \"uwellformed G \\<Longrightarrow> uedges G \\<subseteq> {S. S \\<subseteq> uverts G}\"\n    by (cases G, auto simp add: uwellformed_def)\n  then have \"finite {S. S \\<subseteq> uverts G}\" using assms\n    by auto\n  with sub_pow assms show \"finite (uedges G)\"\n    using finite_subset by blast\nqed\n\nlemma ugraph_max_edges :\n  assumes \"uwellformed G\" and \"card (uverts G) = n\" and \"finite (uverts G)\"\n  shows \"card (uedges G) \\<le> n * (n-1)/2\"\n  using assms wellformed_all_edges [OF assms(1)] card_all_edges [OF assms(3)] Binomial.choose_two [of \"card(uverts G)\"]\n  by (smt (verit, del_insts) all_edges_finite card_mono dbl_simps(3) dbl_simps(5) div_times_less_eq_dividend le_divide_eq_numeral1(1) le_square nat_mult_1_right numerals(1) of_nat_1 of_nat_diff of_nat_mono of_nat_mult of_nat_numeral right_diff_distrib')\n\nlemma subgraph_verts_finite : \"\\<lbrakk> finite (uverts G); subgraph G' G \\<rbrakk> \\<Longrightarrow> finite (uverts G')\"\n  using rev_finite_subset subgraph_def by auto\n\nsection \\<open>Cliques\\<close>\n\ntext \\<open>In this section a straightforward definition of cliques for simple, undirected graphs is introduced.\nBesides fundamental facts about cliques, also more specialized lemmata are proved in subsequent subsections.\\<close>\n\ndefinition uclique :: \"ugraph \\<Rightarrow> ugraph \\<Rightarrow> nat \\<Rightarrow> bool\" where\n  \"uclique C G p \\<equiv> p = card (uverts C) \\<and> subgraph C G \\<and> C = complete (uverts C)\"\n\nlemma clique_any_edge :\n  assumes \"uclique C G p\" and \"x \\<in> uverts C\" and \"y \\<in> uverts C\" and \"x \\<noteq> y\"\n  shows \"{x,y} \\<in> uedges G\"\n  using assms\n  apply (simp add: uclique_def complete_def all_edges_def subgraph_def)\n  by (smt (verit, best) SigmaI fst_conv image_iff mem_Collect_eq mk_uedge.simps snd_conv subset_eq)\n\nlemma clique_exists : \"\\<exists> C p. uclique C G p \\<and> p \\<le> card (uverts G)\"\n  using bex_imageD card.empty emptyE gr_implies_not0 le_neq_implies_less\n  by (auto simp add: uclique_def complete_def subgraph_def all_edges_def)\n\nlemma clique_exists1 :\n  assumes \"uverts G \\<noteq> {}\" and \"finite (uverts G)\"\n  shows \"\\<exists> C p. uclique C G p \\<and> 0 < p \\<and>  p \\<le> card (uverts G)\"\nproof -\n  obtain x where x: \"x \\<in> uverts G\"\n    using assms\n    by auto\n  show ?thesis\n    apply (rule exI [of _ \"({x},{})\"], rule exI [of _ 1])\n    using x assms(2)\n    by (simp add: uclique_def subgraph_def complete_def all_edges_def Suc_leI assms(1) card_gt_0_iff)\nqed\n\nlemma clique_max_size : \"uclique C G p \\<Longrightarrow> finite (uverts G) \\<Longrightarrow>  p \\<le> card (uverts G)\"\n  by (auto simp add: uclique_def subgraph_def Finite_Set.card_mono)\n\nlemma clique_exists_gt0 :\n  assumes \"finite (uverts G)\" \"card (uverts G) > 0\"\n  shows \"\\<exists> C p. uclique C G p \\<and> p \\<le> card (uverts G) \\<and> (\\<forall>C q. uclique C G q \\<longrightarrow> q \\<le> p)\"\nproof -\n  have 1: \"finite (uverts G) \\<Longrightarrow> finite {p. \\<exists>C. uclique C G p}\"\n    using clique_max_size\n    by (smt (verit, best) finite_nat_set_iff_bounded_le mem_Collect_eq)\n  have 2: \"\\<And>A::nat set. finite A \\<Longrightarrow> \\<exists>x. x\\<in>A \\<Longrightarrow> \\<exists>x\\<in>A.\\<forall>y\\<in>A. y \\<le> x\"\n    using Max_ge Max_in by blast\n  have \"\\<exists>C p. uclique C G p \\<and> (\\<forall>C q. uclique C G q \\<longrightarrow> q \\<le> p)\"\n    using 2 [OF 1 [OF \\<open>finite (uverts G)\\<close>]] clique_exists [of G]\n    by (smt (z3) mem_Collect_eq)\n  then show ?thesis\n    using \\<open>finite (uverts G)\\<close> clique_max_size\n    by blast\nqed\n\ntext \\<open>If there exists a $(p+1)$-clique @{term C} in a graph @{term G}\n      then we can obtain a $p$-clique in @{term G} by removing an arbitrary vertex from @{term C}\\<close>\n\nlemma clique_size_jumpfree :\n  assumes \"finite (uverts G)\" and \"uwellformed G\"\n    and \"uclique C G (p+1)\"\n  shows \"\\<exists>C'. uclique C' G p\"\nproof -\n  have \"card(uverts G) > p\"\n    using assms by (simp add: uclique_def subgraph_def card_mono less_eq_Suc_le)\n  obtain x where x: \"x \\<in> uverts C\"\n    using assms by (fastforce simp add: uclique_def)\n  have \"mk_uedge ` {uv \\<in> uverts C \\<times> uverts C. fst uv \\<noteq> snd uv} - {A \\<in> uedges C. x \\<in> A} =\n    mk_uedge ` {uv \\<in> (uverts C - {x}) \\<times> (uverts C - {x}). fst uv \\<noteq> snd uv}\"\n  proof -\n    have \"\\<And>y. y \\<in> mk_uedge ` {uv \\<in> uverts C \\<times> uverts C. fst uv \\<noteq> snd uv} - {A \\<in> uedges C. x \\<in> A} \\<Longrightarrow>\n          y \\<in> mk_uedge ` {uv \\<in> (uverts C - {x}) \\<times> (uverts C - {x}). fst uv \\<noteq> snd uv}\"\n      using assms(3)\n      apply (simp add: uclique_def complete_def all_edges_def)\n      by (smt (z3) DiffI SigmaE SigmaI image_iff insertCI mem_Collect_eq mk_uedge.simps singleton_iff snd_conv)\n    moreover have \"\\<And>y. y \\<in> mk_uedge ` {uv \\<in> (uverts C - {x}) \\<times> (uverts C - {x}). fst uv \\<noteq> snd uv}\n                  \\<Longrightarrow> y \\<in> mk_uedge ` {uv \\<in> uverts C \\<times> uverts C. fst uv \\<noteq> snd uv} - {A \\<in> uedges C. x \\<in> A}\"\n      apply (simp add: uclique_def complete_def all_edges_def)\n      by (smt (z3) DiffE SigmaE SigmaI image_iff insert_iff mem_Collect_eq mk_uedge.simps singleton_iff)\n    ultimately show ?thesis\n      by blast\n  qed\n  then have 1: \"(uverts C - {x}, uedges C - {A \\<in> uedges C. x \\<in> A}) = Ugraph_Lemmas.complete (uverts C - {x})\"\n    using assms(3)\n    apply (simp add: uclique_def complete_def all_edges_def)\n    by (metis (no_types, lifting) snd_eqD)\n  show ?thesis\n    apply (rule exI [of _ \"C -- x\"])\n    using assms x\n    apply (simp add: uclique_def remove_vertex_def subgraph_def)\n    apply (simp add: 1)\n    by (auto simp add: complete_def all_edges_def)\nqed\n\ntext \\<open>The next lemma generalises the lemma @{thm [source] clique_size_jumpfree} to a proof of\n the existence of a clique of any size smaller than the size of the original clique.\\<close>\n\nlemma clique_size_decr :\n  assumes \"finite (uverts G)\" and \"uwellformed G\"\n    and \"uclique C G p\"\n  shows \"q \\<le> p \\<Longrightarrow> \\<exists>C. uclique C G q\" using assms\nproof (induction q rule: measure_induct [of \"\\<lambda>x. p - x\"])\n  case (1 x)\n  then show ?case\n  proof (cases \"x = p\")\n    case True\n    then show ?thesis\n      using \\<open>uclique C G p\\<close>\n      by blast\n  next\n    case False\n    with 1(2) have \"x < p\"\n      by auto\n    from \\<open>x < p\\<close> have \"p - Suc x < p - x\"\n      by auto\n    then show ?thesis\n      using 1(1) assms(1,2,3) \\<open>x < p\\<close>\n      using clique_size_jumpfree [OF \\<open>finite (uverts G)\\<close> \\<open>uwellformed G\\<close> _]\n      by (metis \"1.prems\"(4) add.commute linorder_not_le not_less_eq plus_1_eq_Suc)\n  qed\nqed\n\ntext \\<open>With this lemma we can easily derive by contradiction that\n      if there is no $p$-clique then there cannot exist a clique of a size greater than @{term p}\\<close>\n\ncorollary clique_size_neg_max :\n  assumes \"finite (uverts G)\" and \"uwellformed G\"\n    and \"\\<not>(\\<exists>C. uclique C G p)\"\n  shows \"\\<forall>C q. uclique C G q \\<longrightarrow> q < p\"\nproof (rule ccontr)\n  assume 1: \"\\<not> (\\<forall>C q. uclique C G q \\<longrightarrow> q < p)\"\n  show False\n  proof -\n    obtain C q where C: \"uclique C G q\"\n      and q: \"q \\<ge> p\"\n      using 1 linorder_not_less\n      by blast\n    show ?thesis\n      using assms(3) q clique_size_decr [OF \\<open>finite (uverts G)\\<close> \\<open>uwellformed G\\<close> C ]\n      using order_less_imp_le by blast\n  qed\nqed\n\ncorollary clique_complete :\n  assumes \"finite V\" and \"x \\<le> card V\"\n  shows \"\\<exists>C. uclique C (complete V) x\"\nproof -\n  have \"uclique (complete V) (complete V) (card V)\"\n    by (simp add: uclique_def complete_def subgraph_def)\n  then show ?thesis\n    using clique_size_decr [OF _ complete_wellformed [of V] _ assms(2)] assms(1)\n    by (simp add: complete_def)\nqed\n\nlemma subgraph_clique :\n  assumes \"uwellformed G\" \"subgraph C G\" \"C = complete (uverts C)\"\n  shows \"{e \\<in> uedges G. e \\<subseteq> uverts C} = uedges C\"\nproof -\n  from assms complete_wellformed [of \"uverts C\"] have \"uedges C \\<subseteq> {e \\<in> uedges G. e \\<subseteq> uverts C}\"\n    by (auto simp add: subgraph_def uwellformed_def)\n  moreover from assms(1) complete_wellformed [of \"uverts C\"] have \"{e \\<in> uedges G. e \\<subseteq> uverts C} \\<subseteq> uedges C\"\n    apply (simp add: subgraph_def uwellformed_def complete_def card_2_iff all_edges_def)\n    using assms(3)[unfolded complete_def all_edges_def] in_mk_uedge_img \n    by (smt (verit, ccfv_threshold) SigmaI fst_conv insert_subset mem_Collect_eq snd_conv subsetI)\n  ultimately show ?thesis\n    by auto\nqed\n\ntext \\<open>Next, we prove that in a graph @{term G} with a $p$-clique @{term C} and some vertex @{term v} outside of this clique,\nthere exists a $(p+1)$-clique in @{term G} if @{term v} is connected to all nodes in @{term C}.\nThe next lemma is an abstracted version that does not explicitly mention cliques:\nIf a vertex @{term n} has as many edges to a set of nodes @{term N} as there are nodes in @{term N}\nthen @{term n} is connected to all vertices in @{term N}.\\<close>\n\nlemma card_edges_nodes_all_edges :\n  fixes G :: \"ugraph\" and  N :: \"nat set\" and E :: \"nat set set\" and n :: nat\n  assumes \"uwellformed G\"\n    and \"finite N\"\n    and \"N \\<subseteq> uverts G\" and \"E \\<subseteq> uedges G\"\n    and \"n \\<in> uverts G\" and \"n \\<notin> N\"\n    and \"\\<forall>e \\<in> E. \\<exists>x \\<in> N. {n,x} = e\"\n    and \"card E = card N\"\n  shows \"\\<forall>x \\<in> N. {n,x} \\<in> E\"\nproof (rule ccontr)\n  assume \"\\<not>(\\<forall>x \\<in> N. {n,x} \\<in> E)\"\n  show False\n  proof -\n    obtain x where x: \"x \\<in> N\" and e: \"{n,x} \\<notin> E\"\n      using \\<open>\\<not>(\\<forall>x \\<in> N. {n,x} \\<in> E)\\<close>\n      by auto\n    have \"E \\<subseteq> (\\<lambda>y. {n,y}) ` (N - {x})\"\n      using Set.image_diff_subset \\<open>\\<forall>e \\<in> E. \\<exists>x \\<in> N. {n,x} = e\\<close> x e\n      by auto\n    then show ?thesis\n      using \\<open>finite N\\<close> \\<open>card E = card N\\<close> x\n      using surj_card_le [of \"N - {x}\" E \"(\\<lambda>y. {n,y})\"]\n      by (simp, metis card_gt_0_iff diff_less emptyE lessI linorder_not_le)\n  qed\nqed\n\nsubsection \\<open>Partitioning edges along a clique\\<close>\n\ntext \\<open>Tur\\'{a}n's proof partitions the edges of a graph into three partitions for a $(p-1)$-clique @{term C}:\nAll edges within @{term C}, all edges outside of @{term C}, and all edges between a vertex in @{term C} and a\nvertex not in @{term C}.\n\nWe prove a generalized lemma that partitions the edges along some arbitrary set of vertices\nwhich does not necessarily need to induce a clique.\nFurthermore, in Tur\\'{a}n's graph theorem we only argue about the cardinality of the partitions\nso that we restrict this proof to showing that\nthe sum of the cardinalities of the partitions is equal to number of all edges.\\<close>\n\nlemma graph_partition_edges_card :\n  assumes \"finite (uverts G)\" and \"uwellformed G\" and \"A \\<subseteq> (uverts G)\"\n  shows \"card (uedges G) = card {e \\<in> uedges G. e \\<subseteq> A} + card {e \\<in> uedges G.  e \\<subseteq> uverts G - A} + card {e \\<in> uedges G. e \\<inter> A \\<noteq> {} \\<and> e \\<inter> (uverts G - A) \\<noteq> {}}\"\n  using assms\nproof -\n  have \"uedges G = {e \\<in> uedges G. e \\<subseteq> A} \\<union> {e \\<in> uedges G.  e \\<subseteq> (uverts G) - A} \\<union> {e \\<in> uedges G. e \\<inter> A \\<noteq> {} \\<and> e \\<inter> ((uverts G) - A) \\<noteq> {}}\"\n    using assms uwellformed_def\n    by blast\n  moreover have \"{e \\<in> uedges G. e \\<subseteq> A} \\<inter> {e \\<in> uedges G.  e \\<subseteq> uverts G - A} = {}\"\n    using assms uwellformed_def\n    by (smt (verit, ccfv_SIG) Diff_disjoint Int_subset_iff card.empty disjoint_iff mem_Collect_eq nat.simps(3) nat_1_add_1 plus_1_eq_Suc prod.sel(2) subset_empty)\n  moreover have \"({e \\<in> uedges G. e \\<subseteq> A} \\<union> {e \\<in> uedges G.  e \\<subseteq> uverts G - A}) \\<inter> {e \\<in> uedges G. e \\<inter> A \\<noteq> {} \\<and> e \\<inter> (uverts G - A) \\<noteq> {}} = {}\"\n    by blast\n  moreover have \"finite {e \\<in> uedges G. e \\<subseteq> A}\" using assms\n    by (simp add: finite_subset)\n  moreover have \"finite {e \\<in> uedges G.  e \\<subseteq> uverts G - A}\" using assms\n    by (simp add: finite_subset)\n  moreover have \"finite {e \\<in> uedges G. e \\<inter> A \\<noteq> {} \\<and> e \\<inter> (uverts G - A) \\<noteq> {}}\"\n    using assms finite_verts_edges\n    by auto\n  ultimately show ?thesis\n    using assms Finite_Set.card_Un_disjoint\n    by (smt (verit, best) finite_UnI)\nqed\n\ntext \\<open>Now, we turn to the problem of calculating the cardinalities of these partitions\nwhen they are induced by the biggest clique in the graph.\n\nFirst, we consider the number of edges in a $p$-clique.\\<close>\n\nlemma clique_edges_inside :\n  assumes G1: \"uwellformed G\" and G2: \"finite (uverts G)\"\n    and p: \"p \\<le> card (uverts G)\" and n: \"n = card(uverts G)\"\n    and C: \"uclique C G p\"\n  shows \"card {e \\<in> uedges G. e \\<subseteq> uverts C} = p * (p-1) / 2\"\nproof -\n  have \"2 dvd (card (uverts C) * (p - 1))\"\n    using C uclique_def\n    by auto\n  have \"2 = real 2\"\n    by simp\n  then show ?thesis\n    using C uclique_def [of C G p] complete_def [of \"uverts C\"]\n    using subgraph_clique [OF G1, of C] subgraph_verts_finite [OF assms(2), of C]\n    using Real.real_of_nat_div [OF \\<open>2 dvd (card (uverts C) * (p - 1))\\<close>] Binomial.choose_two [of \" card (uverts G)\"]\n    by (smt (verit, del_insts) One_nat_def approximation_preproc_nat(5) card_all_edges diff_self_eq_0 eq_imp_le left_diff_distrib' left_diff_distrib' linorder_not_less mult_le_mono2 n_choose_2_nat not_gr0 not_less_eq_eq of_nat_1 of_nat_diff snd_eqD)\nqed\n\ntext \\<open>Next, we turn to the number of edges that connect a node inside of the biggest clique with\na node outside of said clique. For that we start by calculating a bound for the number of\nedges from one single node outside of the clique into the clique.\\<close>\n\nlemma clique_edges_inside_to_node_outside :\n  assumes \"uwellformed G\" and \"finite (uverts G)\"\n  assumes \"0 < p\" and \"p \\<le> card (uverts G)\"\n  assumes \"uclique C G p\" and \"(\\<forall>C p'. uclique C G p' \\<longrightarrow> p' \\<le> p)\"\n  assumes y: \"y \\<in> uverts G - uverts C\"\n  shows \"card {{x,y}| x. x \\<in> uverts C \\<and> {x,y} \\<in> uedges G} \\<le> p - 1\"\nproof (rule ccontr)\n  txt \\<open>For effective proof automation we use a local function definition to compute this\n       set of edges into the clique from any node @{term y}:\\<close>\n  define S where \"S \\<equiv> \\<lambda>y. {{x,y}| x. x \\<in> uverts C \\<and> {x,y} \\<in> uedges G}\"\n  assume \"\\<not> card {{x, y} |x. x \\<in> uverts C \\<and> {x, y} \\<in> uedges G} \\<le> p - 1\"\n  then have Sy: \"card (S y) > p - 1\"\n    using S_def y by auto\n  have \"uclique ({y} \\<union> (uverts C),S y \\<union> uedges C) G (Suc p)\"\n  proof -\n    have \"card ({y} \\<union> uverts C) = Suc p\"\n      using assms(3,5,7) uclique_def\n      by (metis DiffD2 card_gt_0_iff card_insert_disjoint insert_is_Un)\n    moreover have \"subgraph ({y} \\<union> uverts C, (S y) \\<union> uedges C) G\"\n      using assms(5,7)\n      by (auto simp add: uclique_def subgraph_def S_def)\n    moreover have \"({y} \\<union> (uverts C),(S y) \\<union> uedges C) = complete ({y} \\<union> (uverts C))\"\n    proof -\n      have \"(S y) \\<union> uedges C \\<subseteq> all_edges ({y} \\<union> (uverts C))\"\n        using y assms(5) S_def all_edges_def uclique_def complete_def\n        by (simp, smt (z3) SigmaE SigmaI fst_conv image_iff in_mk_uedge_img insertCI mem_Collect_eq snd_conv subsetI)\n      moreover have \"all_edges ({y} \\<union> (uverts C)) \\<subseteq> (S y) \\<union> uedges C\"\n      proof -\n        have \"\\<forall>x\\<in>uverts C. {y, x} \\<in> S y\"\n        proof -\n          have \"card (S y) = card (uverts C)\"\n            using Sy assms(2,3,5,7) S_def uclique_def card_gt_0_iff\n            using Finite_Set.surj_card_le [of \"uverts C\" \"S y\" \"\\<lambda>x. {x, y}\"]\n            by (smt (verit, del_insts) Suc_leI Suc_pred' image_iff le_antisym mem_Collect_eq subsetI)\n          then show ?thesis\n            using card_edges_nodes_all_edges [OF assms(1), of \"uverts C\" \"S y\" y] assms(1,2,5,7) S_def uclique_def\n            by (smt (verit, ccfv_threshold) DiffE insert_commute mem_Collect_eq subgraph_def subgraph_verts_finite subsetI)\n        qed\n        then show ?thesis\n          using assms(5) all_edges_def S_def uclique_def complete_def mk_uedge.simps in_mk_uedge_img\n          by (smt (z3) insert_commute SigmaI fst_conv mem_Collect_eq snd_conv SigmaE UnCI image_iff insert_iff insert_is_Un subsetI)\n      qed\n      ultimately show ?thesis\n        by (auto simp add: complete_def)\n    qed\n    ultimately show ?thesis\n      by (simp add: uclique_def complete_def)\n  qed\n  then show False\n    using assms(6)\n    by fastforce\nqed\n\ntext \\<open>Now, that we have this upper bound for the number of edges from a single vertex into the largest clique\n      we can calculate the upper bound for all such vertices and edges:\\<close>\n\nlemma clique_edges_inside_to_outside :\n  assumes G1: \"uwellformed G\" and G2: \"finite (uverts G)\"\n    and p0: \"0 < p\" and pn: \"p \\<le> card (uverts G)\" and \"card(uverts G) = n\"\n    and C: \"uclique C G p\" and C_max: \"(\\<forall>C p'. uclique C G p' \\<longrightarrow> p' \\<le> p)\"\n  shows \"card {e \\<in> uedges G. e \\<inter> uverts C \\<noteq> {} \\<and> e \\<inter> (uverts G - uverts C) \\<noteq> {}} \\<le> (p - 1) * (n - p)\"\nproof -\n  define S where \"S \\<equiv> \\<lambda>y. {{x,y}| x. x \\<in> uverts C \\<and> {x,y} \\<in> uedges G}\"\n  have \"card (uverts G - uverts C) = n - p\"\n    using pn C \\<open>card(uverts G) = n\\<close> G2\n    apply (simp add: uclique_def)\n    by (meson card_Diff_subset subgraph_def subgraph_verts_finite)\n  moreover have \"{e \\<in> uedges G. e \\<inter> uverts C \\<noteq> {} \\<and> e \\<inter> (uverts G - uverts C) \\<noteq> {}} = {{x,y}| x y. x \\<in> uverts C \\<and> y \\<in> (uverts G - uverts C) \\<and> {x,y} \\<in> uedges G}\"\n  proof -\n    have \"e \\<in> {e \\<in> uedges G. e \\<inter> uverts C \\<noteq> {} \\<and> e \\<inter> (uverts G - uverts C) \\<noteq> {}}\n          \\<Longrightarrow> \\<exists>x y. e = {x,y} \\<and> x \\<in> uverts C \\<and> y \\<in> uverts G - uverts C\" for e\n      using G1\n      apply (simp add: uwellformed_def)\n      by (smt (z3) DiffD2 card_2_iff disjoint_iff_not_equal insert_Diff insert_Diff_if insert_iff)\n    then show ?thesis\n      by auto\n  qed\n  moreover have \"card {{x,y}| x y. x \\<in> uverts C \\<and> y \\<in> (uverts G - uverts C) \\<and> {x,y} \\<in> uedges G} \\<le> card (uverts G - uverts C) * (p-1)\"\n  proof -\n    have \"card {{x,y}| x y. x \\<in> uverts C \\<and> y \\<in> (uverts G - uverts C) \\<and> {x,y} \\<in> uedges G}\n           \\<le> (\\<Sum>y \\<in> (uverts G - uverts C). card (S y))\"\n    proof -\n      have \"finite (uverts G - uverts C)\"\n        using \\<open>finite (uverts G)\\<close> by auto\n      have \"{{x,y}| x y. x \\<in> uverts C \\<and> y \\<in> (uverts G - uverts C) \\<and> {x,y} \\<in> uedges G}\n           = (\\<Union>y \\<in> (uverts G - uverts C). {{x,y}| x. x \\<in> uverts C \\<and> {x,y} \\<in> uedges G})\"\n        by auto\n      then show ?thesis\n        using Groups_Big.card_UN_le [OF \\<open>finite (uverts G - uverts C)\\<close>,\n            of \"\\<lambda>y. {{x, y} |x. x \\<in> uverts C \\<and> {x, y} \\<in> uedges G}\"]\n        using S_def\n        by auto\n    qed\n    moreover have \"(\\<Sum>y\\<in>uverts G - uverts C. card (S y)) \\<le> card (uverts G - uverts C) * (p-1)\"\n    proof -\n      have \"card (S y) \\<le> p - 1\" if y: \"y \\<in> uverts G - uverts C\" for y\n        using clique_edges_inside_to_node_outside [OF assms(1,2,3,4) C C_max y] S_def y\n        by simp\n      then show ?thesis\n        by (metis id_apply of_nat_eq_id sum_bounded_above)\n    qed\n    ultimately show ?thesis\n      using order_trans\n      by blast\n  qed\n  ultimately show ?thesis\n    by (smt (verit, ccfv_SIG) mult.commute)\nqed\n\ntext \\<open>Lastly, we need to argue about the number of edges which are located entirely outside of\nthe greatest clique. Note that this is in the inductive step case in the overarching proof\nof  Tur\\'{a}n's graph theorem. That is why we have access to the inductive hypothesis as an\nassumption in the following lemma:\\<close>\n\nlemma clique_edges_outside :\n  assumes \"uwellformed G\" and \"finite (uverts G)\"\n    and p2: \"2 \\<le> p\" and pn: \"p \\<le> card (uverts G)\" and n: \"n = card(uverts G)\"\n    and C: \"uclique C G (p-1)\" and C_max: \"(\\<forall>C q. uclique C G q \\<longrightarrow> q \\<le> p-1)\"\n    and IH: \"\\<And>G y. y < n \\<Longrightarrow> finite (uverts G) \\<Longrightarrow> uwellformed G \\<Longrightarrow> \\<forall>C p'. uclique C G p' \\<longrightarrow> p' < p\n              \\<Longrightarrow> 2 \\<le> p \\<Longrightarrow> card (uverts G) = y \\<Longrightarrow> real (card (uedges G)) \\<le> (1 - 1 / real (p - 1)) * real (y\\<^sup>2) / 2\"\n  shows \"card {e \\<in> uedges G. e \\<subseteq> uverts G - uverts C} \\<le> (1 - 1 / (p-1)) * (n - p + 1) ^ 2 / 2\"\nproof -\n  have \"n - card (uverts C) < n\"\n    using C pn p2 n\n    by (metis Suc_pred' diff_less less_2_cases_iff linorder_not_less not_gr0 uclique_def)\n  have GC1: \"finite (uverts (uverts G - uverts C, {e \\<in> uedges G. e \\<subseteq> uverts G - uverts C}))\"\n    using assms(2)\n    by simp\n  have GC2: \"uwellformed (uverts G - uverts C, {e \\<in> uedges G. e \\<subseteq> uverts G - uverts C})\"\n    using assms(1)\n    by (auto simp add: uwellformed_def)\n  have GC3: \"\\<forall>C' p'. uclique C' (uverts G - uverts C, {e \\<in> uedges G. e \\<subseteq> uverts G - uverts C}) p' \\<longrightarrow> p' < p\"\n  proof (rule ccontr)\n    assume \"\\<not>(\\<forall>C' p'. uclique C' (uverts G - uverts C, {e \\<in> uedges G. e \\<subseteq> uverts G - uverts C}) p' \\<longrightarrow> p' < p)\"\n    then obtain C' p' where C': \"uclique C' (uverts G - uverts C, {e \\<in> uedges G. e \\<subseteq> uverts G - uverts C}) p'\" and p': \"p' \\<ge> p\"\n      by auto\n    then have \"uclique C' G p'\"\n      using uclique_def subgraph_def\n      by auto\n    then show False\n      using p' p2 C_max\n      by fastforce\n  qed\n  have GC4: \"card (uverts (uverts G - uverts C,{e \\<in> uedges G. e \\<subseteq> uverts G - uverts C})) = n - card (uverts C)\"\n    using C n assms(2) uclique_def subgraph_def\n    by (simp, meson card_Diff_subset infinite_super)\n  show ?thesis\n    using C GC3 IH [OF \\<open>n - card (uverts C) < n\\<close> GC1 GC2 GC3 \\<open>2 \\<le> p\\<close> GC4] assms(2) n uclique_def\n    by (simp, smt (verit, best) C One_nat_def Suc_1 Suc_leD clique_max_size of_nat_1 of_nat_diff p2)\nqed\n\nsubsection \\<open>Extending the size of the biggest clique\\<close> text_raw \\<open>\\label{sec:extend_clique}\\<close>\n\ntext \\<open>In this section, we want to prove that we can add edges to a graph so that we augment the biggest clique\nto some greater clique with a specific number of vertices. For that, we need the following lemma:\nWhen too many edges have been added to a graph so that there exists a $(p+1)$-clique\nthen we can remove at least one of the added edges while also retaining a p-clique\\<close>\n\nlemma clique_union_size_decr :\n  assumes \"finite (uverts G)\" and \"uwellformed (uverts G, uedges G \\<union> E)\"\n    and \"uclique C (uverts G, uedges G \\<union> E) (p+1)\"\n    and \"card E \\<ge> 1\"\n  shows \"\\<exists>C' E'. card E' < card E \\<and> uclique C' (uverts G, uedges G \\<union> E') p \\<and> uwellformed (uverts G, uedges G \\<union> E')\"\nproof (cases \"\\<exists>x \\<in> uverts C. \\<exists>e \\<in> E. x \\<in> e\")\n  case True\n  then obtain x where x1: \"x \\<in> uverts C\" and x2: \"\\<exists>e \\<in> E. x \\<in> e\"\n    by auto\n  show ?thesis\n  proof (rule exI [of _ \"C -- x\"], rule exI [of _ \"{e \\<in> E. x \\<notin> e}\"])\n    have \"card {e \\<in> E. x \\<notin> e} < card E\"\n      using x2 assms(4)\n      by (smt (verit) One_nat_def card.infinite diff_is_0_eq mem_Collect_eq minus_nat.diff_0 not_less_eq psubset_card_mono psubset_eq subset_eq)\n    moreover have \"uclique (C -- x) (uverts G, uedges G \\<union> {e \\<in> E. x \\<notin> e}) p\"\n    proof -\n      have \"p = card (uverts (C -- x))\"\n        using x1 assms(3)\n        by (auto simp add: uclique_def remove_vertex_def)\n      moreover have \"subgraph (C -- x) (uverts G, uedges G \\<union> {e \\<in> E. x \\<notin> e})\"\n        using assms(3)\n        by (auto simp add: uclique_def subgraph_def remove_vertex_def)\n      moreover have \"C -- x = Ugraph_Lemmas.complete (uverts (C -- x))\"\n      proof -\n        have 1: \"\\<And>y. y \\<in> mk_uedge ` {uv \\<in> uverts C \\<times> uverts C. fst uv \\<noteq> snd uv} - {A \\<in> uedges C. x \\<in> A} \\<Longrightarrow>\n            y \\<in> mk_uedge ` {uv \\<in> (uverts C - {x}) \\<times> (uverts C - {x}). fst uv \\<noteq> snd uv}\"\n          by (smt (z3) DiffE DiffI SigmaE SigmaI Ugraph_Lemmas.complete_def all_edges_def assms(3) empty_iff image_iff insert_iff mem_Collect_eq mk_uedge.simps snd_conv uclique_def)\n        have 2: \"\\<And>y. y \\<in> mk_uedge ` {uv \\<in> (uverts C - {x}) \\<times> (uverts C - {x}). fst uv \\<noteq> snd uv} \\<Longrightarrow>\n            y \\<in> mk_uedge ` {uv \\<in> uverts C \\<times> uverts C. fst uv \\<noteq> snd uv} - {A \\<in> uedges C. x \\<in> A}\"\n          by (smt (z3) DiffE DiffI SigmaE SigmaI image_iff insert_iff mem_Collect_eq mk_uedge.simps singleton_iff)\n        show ?thesis\n          using assms(3)\n          apply (simp add: remove_vertex_def complete_def all_edges_def uclique_def)\n          using 1 2\n          by (smt (verit, ccfv_SIG) split_pairs subset_antisym subset_eq)\n      qed\n      ultimately show ?thesis\n        by (simp add: uclique_def)\n    qed\n    moreover have \"uwellformed (uverts G, uedges G \\<union> {e \\<in> E. x \\<notin> e})\"\n      using assms(2)\n      by (auto simp add: uwellformed_def)\n    ultimately show \"card {e \\<in> E. x \\<notin> e} < card E \\<and>\n    uclique (C -- x) (uverts G, uedges G \\<union> {e \\<in> E. x \\<notin> e}) p \\<and>\n    uwellformed (uverts G, uedges G \\<union> {e \\<in> E. x \\<notin> e})\"\n      by auto\n  qed\nnext\n  case False\n  then have \"\\<And>x. x \\<in> uedges C \\<Longrightarrow> x \\<notin> E\"\n    using assms(2)\n    by (metis assms(3) card_2_iff' complete_wellformed uclique_def uwellformed_def)\n  then have \"uclique C G (p+1)\"\n    using assms(3)\n    by (auto simp add: uclique_def subgraph_def uwellformed_def)\n  show ?thesis\n    using assms(2,4) clique_size_jumpfree [OF assms(1) _ \\<open>uclique C G (p+1)\\<close>]\n    apply (simp add: uwellformed_def)\n    by (metis Suc_le_eq UnCI Un_empty_right card.empty prod.exhaust_sel)\nqed\n\ntext \\<open>We use this preceding lemma to prove the next result. In this lemma we assume that we have\nadded too many edges. The goal is then to remove some of the new edges appropriately so\nthat it is indeed guaranteed that there is no bigger clique.\n\nTwo proofs of this lemma will be described in the following.\nBoth fundamentally come down to the same core idea:\nIn essence, both proofs apply the well-ordering principle.\nIn the first proof we do so immediately by obtaining the minimum of a set:\\<close>\n\nlemma clique_union_make_greatest :\n  fixes p n :: nat\n  assumes \"finite (uverts G)\" and \"uwellformed G\"\n    and \"uwellformed (uverts G, uedges G \\<union> E)\" and \"card(uverts G) \\<ge> p\"\n    and \"uclique C (uverts G, uedges G \\<union> E) p\"\n    and \"\\<forall>C' q'. uclique C' G q' \\<longrightarrow> q' < p\" and \"1 \\<le> card E\"\n  shows \"\\<exists>C' E'. uwellformed (uverts G, uedges G \\<union> E')\n        \\<and> (uclique C' (uverts G, uedges G \\<union> E') p)\n        \\<and> (\\<forall>C'' q'. uclique C'' (uverts G, uedges G \\<union> E') q' \\<longrightarrow> q' \\<le> p)\"\n  using assms\nproof  (induction \"card E\" arbitrary: C E rule: less_induct)\n  case (less E)\n  then show ?case\n  proof (cases \"\\<exists>A. uclique A (uverts G, uedges G \\<union> E) (p+1)\")\n    case True\n    then obtain A where A: \"uclique A (uverts G, uedges G \\<union> E) (p+1)\"\n      by auto\n    obtain C' E' where E'1: \"card E' < card E\"\n      and E'2: \"uclique C' (uverts G, uedges G \\<union> E') p\"\n      and E'3: \"uwellformed (uverts G, uedges G \\<union> E')\"\n      and E'4: \"1 \\<le> card E'\"\n      using less(7)\n      using clique_union_size_decr [OF assms(1) \\<open>uwellformed (uverts G, uedges G \\<union> E)\\<close> A less(8)]\n      by (metis One_nat_def Suc_le_eq Un_empty_right card_gt_0_iff finite_Un finite_verts_edges fst_conv less.prems(1) less_not_refl prod.collapse snd_conv)\n    show ?thesis\n      using less(1) [OF E'1 assms(1,2) E'3 less(5) E'2 less(7) E'4]\n      using E'1 less(8)\n      by (meson less_or_eq_imp_le order_le_less_trans)\n  next\n    case False\n    show ?thesis\n      apply (rule exI [of _ C], rule exI [of _ E])\n      using clique_size_neg_max [OF _ less(4) False]\n      using less(2,4,6)\n      by fastforce\n  qed\nqed\n\ntext \\<open>In this second, alternative proof the well-ordering principle is used through complete induction.\\<close>\n\nlemma clique_union_make_greatest_alt :\n  fixes p n :: nat\n  assumes \"finite (uverts G)\" and \"uwellformed G\"\n    and \"uwellformed (uverts G, uedges G \\<union> E)\" and \"card(uverts G) \\<ge> p\"\n    and \"uclique C (uverts G, uedges G \\<union> E) p\"\n    and \"\\<forall>C' q'. uclique C' G q' \\<longrightarrow> q' < p\" and \"1 \\<le> card E\"\n  shows \"\\<exists>C' E'. uwellformed (uverts G, uedges G \\<union> E')\n        \\<and> (uclique C' (uverts G, uedges G \\<union> E') p)\n        \\<and> (\\<forall>C'' q'. uclique C'' (uverts G, uedges G \\<union> E') q' \\<longrightarrow> q' \\<le> p)\"\nproof -\n  define P where \"P \\<equiv> \\<lambda>E. uwellformed (uverts G, uedges G \\<union> E) \\<and> (\\<exists>C. uclique C (uverts G, uedges G \\<union> E) p)\"\n  have \"finite {y. \\<exists>E. P E \\<and> card E = y}\"\n  proof -\n    have \"\\<And>E. P E \\<Longrightarrow> E \\<subseteq> Pow (uverts G)\"\n      by (auto simp add: P_def uwellformed_def)\n    then have \"finite {E. P E}\"\n      using assms(1)\n      by (metis Collect_mono Pow_def finite_Pow_iff rev_finite_subset)\n    then show ?thesis\n      by simp\n  qed\n  obtain F where F1: \"P F\"\n    and F2: \"card F = Min {y. \\<exists>E. P E \\<and> card E = y}\"\n    and F3: \"card F > 0\"\n    using assms(1,3,4,5,6) Min_in \\<open>finite {y. \\<exists>E. P E \\<and> card E = y}\\<close> P_def CollectD Collect_empty_eq\n    by (smt (verit, ccfv_threshold) Un_empty_right card_gt_0_iff finite_Un finite_verts_edges fst_conv le_refl linorder_not_le prod.collapse snd_conv)\n  have \"p > 0\"\n    using assms(6) clique_exists bot_nat_0.not_eq_extremum\n    by blast\n  then show ?thesis\n  proof (cases \"\\<exists>C. uclique C (uverts G, uedges G \\<union> F) (p + 1)\")\n    case True\n    then obtain F' where F'1 : \"P F'\" and F'2: \"card F' < card F\"\n      using F1 F2 F3 clique_union_size_decr [OF assms(1), of F _ p] P_def\n      by (smt (verit) One_nat_def Suc_eq_plus1 Suc_leI add_2_eq_Suc' assms(1) clique_size_jumpfree fst_conv)\n    then show ?thesis\n      using F2 \\<open>finite {y. \\<exists>F. P F \\<and> card F = y}\\<close> Min_gr_iff\n      by fastforce\n  next\n    case False\n    then show ?thesis\n      using clique_size_neg_max [OF _ _ False]\n      using assms(1) F1 P_def\n      by (smt (verit, ccfv_SIG) Suc_eq_plus1 Suc_leI fst_conv linorder_not_le)\n  qed\nqed\n\ntext \\<open>Finally, with this lemma we can turn to this section\u2019s main challenge of increasing the\ngreatest clique size of a graph by adding edges.\\<close>\n\nlemma clique_add_edges_max :\n  fixes p :: nat\n  assumes \"finite (uverts G)\"\n    and \"uwellformed G\" and \"card(uverts G) > p\"\n    and \"\\<exists>C. uclique C G p\" and \"(\\<forall>C q'. uclique C G q' \\<longrightarrow> q' \\<le> p)\"\n    and \"q \\<le> card(uverts G)\" and \"p \\<le> q\"\n  shows \"\\<exists>E. uwellformed (uverts G, uedges G \\<union> E) \\<and> (\\<exists>C. uclique C (uverts G, uedges G \\<union> E) q)\n        \\<and> (\\<forall>C q'. uclique C (uverts G, uedges G \\<union> E) q' \\<longrightarrow> q' \\<le> q)\"\nproof (cases \"p < q\")\n  case True\n  then show ?thesis\n  proof -\n    have \"\\<exists>E. uwellformed (uverts G, uedges G \\<union> E) \\<and> (\\<exists>C. uclique C (uverts G, uedges G \\<union> E) q) \\<and> card E \\<ge> 1\"\n      apply (rule exI [of _ \"all_edges (uverts G)\"])\n      using Set.Un_absorb1 [OF wellformed_all_edges [OF assms(2)]]\n      using complete_wellformed [of \"uverts G\"] clique_complete [OF assms(1,6)]\n      using all_edges_def assms(1,5)\n      apply (simp add: complete_def)\n      by (metis Suc_leI True Un_empty_right all_edges_finite card_gt_0_iff linorder_not_less prod.collapse)\n    then obtain E C where E1: \"uwellformed (uverts G, uedges G \\<union> E)\"\n      and E2: \"uclique C (uverts G, uedges G \\<union> E) q\"\n      and E3: \"card E \\<ge> 1\"\n      by auto\n    show ?thesis\n      using clique_union_make_greatest [OF assms(1,2) E1 assms(6) E2 _ E3] assms(5) True\n      using order_le_less_trans\n      by blast\n  qed\nnext\n  case False\n  show ?thesis\n    apply (rule exI [of _ \"{}\"])\n    using False assms(2,4,5,7)\n    by simp\nqed\n\nsection \\<open>Properties of the upper edge bound\\<close>\n\ntext \\<open>In this section we prove results about the upper edge bound in Tur\\'{a}n's theorem.\nThe first lemma proves that upper bounds of the sizes of the partitions sum up exactly to the overall upper bound.\\<close>\n\nlemma turan_sum_eq :\n  fixes n p :: nat\n  assumes \"p \\<ge> 2\" and \"p \\<le> n\"\n  shows \"(p-1) * (p-2) / 2 + (1 - 1 / (p-1)) * (n - p + 1) ^ 2 / 2 + (p - 2) * (n - p + 1) = (1 - 1 / (p-1)) * n^2 / 2\"\nproof -\n  have \"a * (a-1) / 2 + (1 - 1 / a) * (n - a) ^ 2 / 2 + (a - 1) * (n - a)  = (1 - 1 / a) * n^2 / 2\"\n    if a1: \"a \\<ge> 1\" and a2: \"n \\<ge> a\"\n    for a :: nat\n  proof -\n    have \"a\\<^sup>2 + (n - a)\\<^sup>2 + a * (n - a) * 2 = n\\<^sup>2\"\n      using a2\n      apply (simp flip: Groups.ab_semigroup_mult_class.mult.commute [of 2 \"a * (n - a)\"])\n      apply (simp add: Semiring_Normalization.comm_semiring_1_class.semiring_normalization_rules(18) [of 2 a \"(n - a)\"])\n      by (simp flip: Power.comm_semiring_1_class.power2_sum [of a \"n-a\"])\n    then have \"((a - 1) / a) * (a ^ 2 + (n - a) ^ 2 + a * (n - a) * 2) = ((a - 1) / a) * n^2\"\n      by presburger\n    then have \"(((a - 1) / a) * a ^ 2 + ((a - 1) / a) * (n - a) ^ 2 + ((a - 1) / a) * a * (n - a) * 2) = ...\"\n      using Rings.semiring_class.distrib_left [of \"(a - 1) / a\" \"a\\<^sup>2 + (n - a)\\<^sup>2\" \"a * (n - a) * 2\"]\n      using Rings.semiring_class.distrib_left [of \"(a - 1) / a\" \"a\\<^sup>2\" \"(n - a)\\<^sup>2\"]\n      by auto\n    moreover have \"((a - 1) / a) * a ^ 2 = a * (a-1)\"\n      by (simp add: power2_eq_square)\n    ultimately have \"a * (a-1) + ((a - 1) / a) * (n - a) ^ 2 + (a - 1) * (n - a) * 2  = ((a - 1) / a) * n^2\"\n      using a1 a2\n      by auto\n    moreover have \"1 - 1 / a = (a - 1) / a\"\n      by (smt (verit, del_insts) One_nat_def Suc_pred diff_divide_distrib diff_is_0_eq of_nat_1 of_nat_diff of_nat_le_0_iff of_nat_le_iff of_nat_less_iff right_inverse_eq that)\n    ultimately have \"a * (a-1) + (1 - 1 / a) * (n - a) ^ 2 + (a - 1) * (n - a) * 2  = (1 - 1 / a) * n^2\"\n      by simp\n    then show ?thesis\n      by simp\n  qed\n  moreover have \"p - 1 \\<ge> 1\"\n    using \\<open>p \\<ge> 2\\<close> by auto\n  moreover have \"n \\<ge> p - 1\"\n    using assms(2) by auto\n  ultimately show ?thesis\n    by (smt (verit) assms Nat.add_diff_assoc2 Nat.diff_diff_right diff_diff_left le_eq_less_or_eq less_Suc_eq_le linorder_not_less nat_1_add_1 plus_1_eq_Suc)\nqed\n\ntext \\<open>The next fact proves that the upper bound of edges is monotonically increasing with the size of the biggest clique.\\<close>\n\nlemma turan_mono :\n  fixes n p q :: nat\n  assumes \"0 < q\" and \"q < p\" and \"p \\<le> n\"\n  shows \"(1 - 1 / q) * n^2 / 2 \\<le> (1 - 1 / (p-1)) * n^2 / 2\"\n  using assms\n  by (simp add: Extended_Nonnegative_Real.divide_right_mono_ennreal Real.inverse_of_nat_le)\n\nsection \\<open>Tur\\'{a}n's Graph Theorem\\<close>\n\ntext \\<open>In this section we turn to the direct adaptation of Tur\\'{a}n's original proof as presented by Aigner and Ziegler \\cite{Aigner2018}\\<close>\n\ntheorem turan :\n  fixes p n :: nat\n  assumes \"finite (uverts G)\"\n    and \"uwellformed G\" and \"\\<forall>C p'. uclique C G p' \\<longrightarrow> p' < p\" and \"p \\<ge> 2\" and \"card(uverts G) = n\"\n  shows \"card (uedges G) \\<le> (1 - 1 / (p-1)) * n^2 / 2\" using assms\nproof (induction n arbitrary: G rule: less_induct)\n  case (less n)\n  then show ?case\n  proof (cases \"n < p\")\n    case True\n    show ?thesis\n    proof (cases \"n\")\n      case 0\n      with less True show ?thesis\n        by (auto simp add: wellformed_uverts_0)\n    next\n      case (Suc n')\n      with True have \"(1 - 1 / real n) \\<le> (1 - 1 / real (p - 1))\"\n        by (metis diff_Suc_1 diff_left_mono inverse_of_nat_le less_Suc_eq_le linorder_not_less list_decode.cases not_add_less1 plus_1_eq_Suc)\n      moreover have \"real (card (uedges G)) \\<le> (1 - 1 / real n) * real (n\\<^sup>2) / 2\"\n        using ugraph_max_edges [OF less(3,6,2)]\n        by (smt (verit, ccfv_SIG) left_diff_distrib mult.right_neutral mult_of_nat_commute nonzero_mult_div_cancel_left of_nat_1 of_nat_mult power2_eq_square times_divide_eq_left)\n      ultimately show ?thesis\n        using Rings.ordered_semiring_class.mult_right_mono divide_less_eq_numeral1(1) le_less_trans linorder_not_less of_nat_0_le_iff\n        by (smt (verit, ccfv_threshold) divide_nonneg_nonneg times_divide_eq_right)\n    qed\n  next\n    case False\n    show ?thesis\n    proof -\n      obtain C q where C: \"uclique C G q\"\n        and C_max: \"(\\<forall>C q'. uclique C G q' \\<longrightarrow> q' \\<le> q)\"\n        and q: \"q < card (uverts G)\"\n        using clique_exists_gt0 [OF \\<open>finite (uverts G)\\<close>] False \\<open>p \\<ge> 2\\<close> less.prems(1,3,5)\n        by (metis card.empty card_gt_0_iff le_eq_less_or_eq order_less_le_trans pos2)\n      obtain E C' where E: \"uwellformed (uverts G, uedges G \\<union> E)\"\n        and C': \"(uclique C' (uverts G, uedges G \\<union> E) (p-1))\"\n        and C'_max: \"(\\<forall>C q'. uclique C (uverts G, uedges G \\<union> E) q' \\<longrightarrow> q' \\<le> p-1)\"\n        using clique_add_edges_max [OF \\<open>finite (uverts G)\\<close> \\<open>uwellformed G\\<close> q _ C_max, of \"p-1\"]\n        using C less(4) less(5) False \\<open>card (uverts G) = n\\<close>\n        by (smt (verit) One_nat_def Suc_leD Suc_pred less_Suc_eq_le linorder_not_less order_less_le_trans pos2)\n      have \"card {e \\<in> uedges G \\<union> E. e \\<subseteq> uverts C'} = (p-1) * (p-2) / 2\"\n        using clique_edges_inside [OF E _ _ _ C'] False less(2) less.prems(4) C'\n        by (smt (verit, del_insts) Collect_cong Suc_1 add_leD1 clique_max_size fst_conv of_nat_1 of_nat_add of_nat_diff of_nat_mult plus_1_eq_Suc snd_conv)\n      moreover have \"card {e \\<in> uedges G \\<union> E. e \\<subseteq> uverts G - uverts C'} \\<le> (1 - 1 / (p-1)) * (n - p + 1) ^ 2 / 2\"\n      proof -\n        have \"real(card{e \\<in> uedges (uverts G, uedges G \\<union> E). e \\<subseteq> uverts (uverts G, uedges G \\<union> E) - uverts C'})\n              \\<le> (1 - 1 / (real p - 1)) * (real n - real p + 1)\\<^sup>2 / 2\"\n          using clique_edges_outside [OF E _ less(5) _ _ C' C'_max, of n] linorder_class.leI [OF False] less(1,2,6)\n          by (metis (no_types, lifting) fst_conv)\n        then show ?thesis\n          by (simp, smt (verit, best) False One_nat_def Suc_1 Suc_leD add.commute leI less.prems(4) of_nat_1 of_nat_diff)\n      qed\n      moreover have \"card {e \\<in> uedges G \\<union> E. e \\<inter> uverts C' \\<noteq> {} \\<and> e \\<inter> (uverts G - uverts C') \\<noteq> {}} \\<le> (p - 2) * (n - p + 1)\"\n        using clique_edges_inside_to_outside [OF E _ _ _ _ C' C'_max, of  n] less(2,5,6)\n        by (simp, metis (no_types, lifting) C' False Nat.add_diff_assoc Nat.add_diff_assoc2 One_nat_def Suc_1 clique_max_size fst_conv leI mult_Suc_right plus_1_eq_Suc)\n      ultimately have \"real (card (uedges G \\<union> E)) \\<le> (1 - 1 / real (p - 1)) * real (n\\<^sup>2) / 2\"\n        using graph_partition_edges_card [OF _ E, of \"uverts C'\"]\n        using less(2) turan_sum_eq [OF \\<open>2 \\<le> p\\<close>, of n] False C' uclique_def subgraph_def\n        by (smt (verit) Collect_cong fst_eqD linorder_not_le of_nat_add of_nat_mono snd_eqD)\n      then show ?thesis\n        using less(2) E finite_verts_edges Finite_Set.card_mono [OF _ Set.Un_upper1 [of \"uedges G\" E]]\n        by force\n    qed\n  qed\nqed\n\nsection \\<open>A simplified proof of Tur\\'{a}n's Graph Theorem\\<close>\n\ntext \\<open>In this section we discuss a simplified proof of Tur\\'{a}n's Graph Theorem which uses an idea put forward by the author:\nInstead of increasing the size of the biggest clique it is also possible to use the fact that\nthe expression in Tur\\'{a}n's graph theorem is monotonically increasing in the size of the biggest clique (Lemma @{thm [source] turan_mono}).\nHence, it suffices to prove the upper bound for the actual biggest clique size in the graph.\nAfterwards, the monotonicity provides the desired inequality.\n\nThe simplifications in the proof are annotated accordingly.\\<close>\n\ntheorem turan' :\n  fixes p n :: nat\n  assumes \"finite (uverts G)\"\n    and \"uwellformed G\" and \"\\<forall>C p'. uclique C G p' \\<longrightarrow> p' < p\" and \"p \\<ge> 2\" and \"card(uverts G) = n\"\n  shows \"card (uedges G) \\<le> (1 - 1 / (p-1)) * n^2 / 2\" using assms\nproof (induction n arbitrary: p G rule: less_induct)\n  txt \\<open>In the simplified proof we also need to generalize over the biggest clique size @{term p}\n       so that we can leverage the induction hypothesis in the proof\n       for the already pre-existing biggest clique size which might be smaller than @{term \"p-1\"}.\\<close>\n  case (less n)\n  then show ?case\n  proof (cases \"n < p\")\n    case True\n    show ?thesis\n    proof (cases \"n\")\n      case 0\n      with less True show ?thesis\n        by (auto simp add: wellformed_uverts_0)\n    next\n      case (Suc n')\n      with True have \"(1 - 1 / real n) \\<le> (1 - 1 / real (p - 1))\"\n        by (metis diff_Suc_1 diff_left_mono inverse_of_nat_le less_Suc_eq_le linorder_not_less list_decode.cases not_add_less1 plus_1_eq_Suc)\n      moreover have \"real (card (uedges G)) \\<le> (1 - 1 / real n) * real (n\\<^sup>2) / 2\"\n        using ugraph_max_edges [OF less(3,6,2)]\n        by (smt (verit, ccfv_SIG) left_diff_distrib mult.right_neutral mult_of_nat_commute nonzero_mult_div_cancel_left of_nat_1 of_nat_mult power2_eq_square times_divide_eq_left)\n      ultimately show ?thesis\n        using Rings.ordered_semiring_class.mult_right_mono divide_less_eq_numeral1(1) le_less_trans linorder_not_less of_nat_0_le_iff\n        by (smt (verit, ccfv_threshold) divide_nonneg_nonneg times_divide_eq_right)\n    qed\n  next\n    case False\n    show ?thesis\n    proof -\n      from False \\<open>p \\<ge> 2\\<close>\n      obtain C q where C: \"uclique C G q\"\n        and C_max: \"(\\<forall>C q'. uclique C G q' \\<longrightarrow> q' \\<le> q)\"\n        and q1: \"q < card (uverts G)\" and q2: \"0 < q\"\n        and pq: \"q < p\"\n        using clique_exists_gt0 [OF \\<open>finite (uverts G)\\<close>] clique_exists1 less.prems(1,3,5)\n        by (metis card.empty card_gt_0_iff le_eq_less_or_eq order_less_le_trans pos2)\n      txt \\<open>In the unsimplified proof we extend this existing greatest clique C to a clique of size @{term \"p-1\"}.\n           This part is made superfluous in the simplified proof.\n           In particular, also Section \\ref{sec:extend_clique} is unneeded for this simplified proof.\n           From here on the proof is analogous to the unsimplified proof\n           with the potentially smaller clique of size @{term q} in place of the extended clique.\\<close>\n      have \"card {e \\<in> uedges G. e \\<subseteq> uverts C} = q * (q-1) / 2\"\n        using clique_edges_inside [OF less(3,2) _ _ C] q1 less(6)\n        by auto\n      moreover have \"card {e \\<in> uedges G. e \\<subseteq> uverts G - uverts C} \\<le> (1 - 1 / q) * (n - q) ^ 2 / 2\"\n      proof -\n        have \"real (card {e \\<in> uedges G. e \\<subseteq> uverts G - uverts C})\n              \\<le> (1 - 1 / (real (q + 1) - 1)) * (real n - real (q + 1) + 1)\\<^sup>2 / 2\"\n          using clique_edges_outside [OF less(3,2) _ _ , of \"q+1\" n C] C C_max q1 q2 linorder_class.leI [OF False] less(1,6)\n          by (smt (verit, ccfv_threshold) Suc_1 Suc_eq_plus1 Suc_leI diff_add_inverse2 zero_less_diff)\n        then show ?thesis\n          using  less.prems(5) q1\n          by (simp add: of_nat_diff)\n      qed\n      moreover have \"card {e \\<in> uedges G. e \\<inter> uverts C \\<noteq> {} \\<and> e \\<inter> (uverts G - uverts C) \\<noteq> {}} \\<le> (q - 1) * (n - q)\"\n        using clique_edges_inside_to_outside [OF less(3,2) q2 _ less(6) C C_max] q1\n        by simp\n      ultimately have \"real (card (uedges G)) \\<le> (1 - 1 / real q) * real (n\\<^sup>2) / 2\"\n        using graph_partition_edges_card [OF less(2,3), of \"uverts C\"]\n        using C uclique_def subgraph_def q1 q2 less.prems(5) turan_sum_eq [of \"Suc q\" n]\n        by (smt (verit) Nat.add_diff_assoc Suc_1 Suc_le_eq Suc_le_mono add.commute add.right_neutral diff_Suc_1 diff_Suc_Suc of_nat_add of_nat_mono plus_1_eq_Suc)\n      then show ?thesis\n        txt \\<open>The final statement can then easily be derived with the monotonicity (Lemma @{thm [source] turan_mono}).\\<close>\n        using turan_mono [OF q2 pq, of n] False\n        by linarith\n    qed\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/Turans_Graph_Theorem/Turan.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8479677506936878, "lm_q2_score": 0.8459424411924673, "lm_q1q2_score": 0.7173319090743038}}
{"text": "(* Title: Examples/SML_Relativization/Foundations/SML_Relations.thy\n   Author: Mihails Milehins\n   Copyright 2021 (C) Mihails Milehins\n*)\nsection\\<open>Relativization of the results about relations\\<close>\ntheory SML_Relations\n  imports Main\nbegin\n\n\n\nsubsection\\<open>Definitions and common properties\\<close>\n\ncontext \n  notes [[inductive_internals]]\nbegin\n\ninductive_set trancl_on :: \"['a set, ('a \\<times> 'a) set] \\<Rightarrow> ('a \\<times> 'a) set\"\n  (\\<open>on _/ (_\\<^sup>+)\\<close> [1000, 1000] 999)\n  for U :: \"'a set\" and r :: \"('a \\<times> 'a) set\" \n  where\n    r_into_trancl[intro, Pure.intro]: \n      \"\\<lbrakk> a \\<in> U; b \\<in> U; (a, b) \\<in> r \\<rbrakk> \\<Longrightarrow> (a, b) \\<in> on U r\\<^sup>+\"\n  | trancl_into_trancl[Pure.intro]: \n      \"\n      \\<lbrakk> a \\<in> U; b \\<in> U; c \\<in> U; (a, b) \\<in> on U r\\<^sup>+; (b, c) \\<in> r \\<rbrakk> \\<Longrightarrow> \n        (a, c) \\<in> on U r\\<^sup>+\n      \"\n\nabbreviation tranclp_on (\\<open>on _/ (_\\<^sup>+\\<^sup>+)\\<close> [1000, 1000] 1000) where\n  \"tranclp_on \\<equiv> trancl_onp\"\n\ndeclare trancl_on_def[nitpick_unfold del]\n\nlemmas tranclp_on_def = trancl_onp_def\n\nend\n\ndefinition transp_on :: \"['a set, ['a, 'a] \\<Rightarrow> bool] \\<Rightarrow> bool\"\n  where \"transp_on U = (\\<lambda>r. (\\<forall>x\\<in>U. \\<forall>y\\<in>U. \\<forall>z\\<in>U. r x y \\<longrightarrow> r y z \\<longrightarrow> r x z))\"\n\ndefinition acyclic_on :: \"['a set, ('a \\<times> 'a) set] \\<Rightarrow> bool\"\n  where \"acyclic_on U = (\\<lambda>r. (\\<forall>x\\<in>U. (x, x) \\<notin> on U r\\<^sup>+))\"\n\nlemma trancl_on_eq_tranclp_on:\n  \"on P (\\<lambda>x y. (x, y) \\<in> r)\\<^sup>+\\<^sup>+ x y = ((x, y) \\<in> on (Collect P) r\\<^sup>+)\" \n  unfolding trancl_on_def tranclp_on_def Set.mem_Collect_eq by simp\n\nlemma trancl_on_imp_U: \"(x, y) \\<in> on U r\\<^sup>+  \\<Longrightarrow> (x, y) \\<in> U \\<times> U\"\n  by (auto dest: trancl_on.cases)\n\nlemmas tranclp_on_imp_P = trancl_on_imp_U[to_pred, simplified]\n\nlemma trancl_on_imp_trancl: \"(x, y) \\<in> on U r\\<^sup>+ \\<Longrightarrow> (x, y) \\<in> r\\<^sup>+\"\n  by (induction rule: trancl_on.induct) auto\n\nlemmas tranclp_on_imp_tranclp = trancl_on_imp_trancl[to_pred]\n\nlemma tranclp_eq_tranclp_on: \"r\\<^sup>+\\<^sup>+ = on (\\<lambda>x. True) r\\<^sup>+\\<^sup>+\"\n  unfolding tranclp_def tranclp_on_def by simp\n\nlemma trancl_eq_trancl_on: \"r\\<^sup>+ = on UNIV r\\<^sup>+\"\n  unfolding trancl_def trancl_on_def by (simp add: tranclp_eq_tranclp_on)\n\nlemma transp_on_empty[simp]: \"transp_on {} r\" unfolding transp_on_def by simp\n\nlemma transp_eq_transp_on: \"transp = transp_on UNIV\"\n  unfolding transp_def transp_on_def by simp\n\nlemma acyclic_on_empty[simp]: \"acyclic_on {} r\" unfolding acyclic_on_def by simp\n\nlemma acyclic_eq_acyclic_on: \"acyclic = acyclic_on UNIV\"\n  unfolding acyclic_def acyclic_on_def \n  unfolding trancl_def tranclp_def trancl_on_def tranclp_on_def \n  by simp\n\n\n\nsubsection\\<open>Transfer rules I: \\<^const>\\<open>lfp\\<close> transfer\\<close>\n\n\ntext\\<open>\nThe following context contains code from \\<^cite>\\<open>\"immler_re_2019\"\\<close>.\n\\<close>\n\ncontext\n  includes lifting_syntax \nbegin\n\nlemma Inf_transfer[transfer_rule]: \n  \"(rel_set (A ===> (=)) ===> A ===> (=)) Inf Inf\"\n  unfolding Inf_fun_def by transfer_prover\n\nlemma less_eq_pred_transfer[transfer_rule]:\n  assumes [transfer_rule]: \"right_total A\" \n  shows \n    \"((A ===> (=)) ===> (A ===> (=)) ===> (=)) \n      (\\<lambda>f g. \\<forall>x\\<in>Collect(Domainp A). f x \\<le> g x) (\\<le>)\"\n  unfolding le_fun_def by transfer_prover\n\nlemma lfp_transfer[transfer_rule]:\n  assumes [transfer_rule]: \"bi_unique A\" \"right_total A\" \n  defines \"R \\<equiv> (((A ===> (=)) ===> (A ===> (=))) ===> (A ===> (=)))\"\n  shows \"R (\\<lambda>f. lfp (\\<lambda>u x. if Domainp A x then f u x else bot)) lfp\"\nproof -\n  have \"R (\\<lambda>f. Inf {u. \\<forall>x\\<in>Collect (Domainp A). f u x \\<le> u x}) lfp\"\n    unfolding R_def lfp_def by transfer_prover\n  thus ?thesis by (auto simp: le_fun_def lfp_def)\nqed\n\nlemma Inf2_transfer[transfer_rule]:\n  \"(rel_set (T ===> T ===> (=)) ===> T ===> T ===> (=)) Inf Inf\"\n  unfolding Inf_fun_def by transfer_prover\n\nlemma less_eq2_pred_transfer[transfer_rule]:\n  assumes [transfer_rule]: \"right_total T\" \n  shows \n    \"((T ===> T ===> (=)) ===> (T ===> T ===> (=)) ===> (=)) \n      (\\<lambda>f g. \\<forall>x\\<in>Collect(Domainp T). \\<forall>y\\<in>Collect(Domainp T). f x y \\<le> g x y) (\\<le>)\"\n  unfolding le_fun_def by transfer_prover\n\nlemma lfp2_transfer[transfer_rule]:\n  assumes [transfer_rule]: \"bi_unique A\" \"right_total A\" \n  defines \n    \"R \\<equiv> \n      (((A ===> A ===> (=)) ===> (A ===> A ===> (=))) ===> (A ===> A ===> (=)))\"\n  shows \n    \"R \n      (\n        \\<lambda>f. lfp \n          (\n            \\<lambda>u x y. \n              if Domainp A x \n              then if Domainp A y then (f u) x y else bot \n              else bot\n          )\n      ) \n      lfp\"\nproof -\n  have \n    \"R \n      (\n        \\<lambda>f. \n          Inf \n            {\n              u. \n                \\<forall>x\\<in>Collect (Domainp A). \\<forall>y\\<in>Collect (Domainp A). \n                  (f u) x y \\<le> u x y\n            }\n      ) \n      lfp\"\n    unfolding R_def lfp_def by transfer_prover \n  thus ?thesis by (auto simp: le_fun_def lfp_def)\nqed\n\nend\n\n\n\nsubsection\\<open>Transfer rules II: application-specific rules\\<close>\n\ncontext\n  includes lifting_syntax\nbegin\n\nlemma transp_rt_transfer[transfer_rule]:\n  assumes[transfer_rule]: \"right_total A\" \n  shows \n    \"((A ===> A ===> (=)) ===> (=)) (transp_on (Collect (Domainp A))) transp\"\n  unfolding transp_def transp_on_def by transfer_prover\n\nlemma tranclp_rt_bu_transfer[transfer_rule]:\n  assumes[transfer_rule]: \"bi_unique A\" \"right_total A\" \n  shows \n    \"((A ===> A ===> (=)) ===> (A ===> A ===> (=))) \n      (tranclp_on (Domainp A)) tranclp\"\n  unfolding tranclp_on_def tranclp_def \n  apply transfer_prover_start\n  apply transfer_step+\nproof \n  fix r\n  have \n    \"(\n      \\<lambda>p x y.\n        (\\<exists>a b. x = a \\<and> y = b \\<and> Domainp A a \\<and> Domainp A b \\<and> r a b) \\<or> \n        (\n          \\<exists>a b c. \n            x = a \\<and> y = c \\<and> \n            Domainp A a \\<and> Domainp A b \\<and> Domainp A c \\<and> \n            p a b \\<and> r b c\n        ) \n    ) = \n      (\n        \\<lambda>p x y.\n          if Domainp A x\n          then if Domainp A y\n            then \n              (\n                \\<exists>a\\<in>Collect (Domainp A). \\<exists>b\\<in>Collect (Domainp A). \n                  x = a \\<and> y = b \\<and> r a b) \\<or>\n                  (\n                    \\<exists>a\\<in>Collect (Domainp A). \n                    \\<exists>b\\<in>Collect (Domainp A). \n                    \\<exists>c\\<in>Collect (Domainp A). \n                      x = a \\<and> y = c \\<and> p a b \\<and> r b c\n                  )\n           else bot\n         else bot\n      )\"\n    (is \"?lhs = ?rhs\")\n    by (intro ext) simp\n  thus \"lfp ?lhs = lfp ?rhs\" by clarsimp\nqed\n\nlemma trancl_rt_bu_transfer[transfer_rule]:\n  assumes[transfer_rule]: \"bi_unique A\" \"right_total A\" \n  shows \n    \"(rel_set (rel_prod A A) ===> rel_set (rel_prod A A)) \n      (trancl_on (Collect (Domainp A))) trancl\"\n  unfolding trancl_on_def trancl_def\n  apply transfer_prover_start\n  apply transfer_step+\n  by (auto simp: tranclp_on_imp_P[where U=\"Domainp A\"])\n\nlemma acyclic_rt_bu_transfer[transfer_rule]:\n  assumes[transfer_rule]: \"bi_unique A\" \"right_total A\" \n  shows \n    \"((rel_set (rel_prod A A)) ===> (=)) \n      (acyclic_on (Collect (Domainp A))) acyclic\"\n  unfolding acyclic_on_def acyclic_def by transfer_prover\n\nend\n\ntext\\<open>\\newpage\\<close>\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/Types_To_Sets_Extension/Examples/SML_Relativization/Foundations/SML_Relations.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8459424295406087, "lm_q2_score": 0.8479677545357568, "lm_q1q2_score": 0.7173319024440726}}
{"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>\\<open>\\<open>Section 2.4\\<close> in \"prog-prove\"\\<close>.\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>\\<open>\"nipkow16\"\\<close>,\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": "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/Lists_Ex.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8128673178375734, "lm_q2_score": 0.8824278757303677, "lm_q1q2_score": 0.7172967805300515}}
{"text": "(*\n * Copyright 2014, NICTA\n *\n * This software may be distributed and modified according to the terms of\n * the BSD 2-Clause license. Note that NO WARRANTY is provided.\n * See \"LICENSE_BSD2.txt\" for details.\n *\n * @TAG(NICTA_BSD)\n *)\n\ntheory WordAbstract\nimports L2Defs ExecConcrete\nbegin\n\ndefinition [simplified]: \"INT_MAX \\<equiv> (2 :: int) ^ 31 - 1\"\ndefinition [simplified]: \"INT_MIN \\<equiv> - ((2 :: int) ^ 31)\"\ndefinition [simplified]: \"UINT_MAX \\<equiv> (2 :: nat) ^ 32 - 1\"\n\ndefinition [simplified]: \"SHORT_MAX \\<equiv> (2 :: int) ^ 15 - 1\"\ndefinition [simplified]: \"SHORT_MIN \\<equiv> - ((2 :: int) ^ 15)\"\ndefinition [simplified]: \"USHORT_MAX \\<equiv> (2 :: nat) ^ 16 - 1\"\n\ndefinition [simplified]: \"CHAR_MAX \\<equiv> (2 :: int) ^ 7 - 1\"\ndefinition [simplified]: \"CHAR_MIN \\<equiv> - ((2 :: int) ^ 7)\"\ndefinition [simplified]: \"UCHAR_MAX \\<equiv> (2 :: nat) ^ 8 - 1\"\n\ndefinition \"WORD_MAX x \\<equiv> ((2 ^ (len_of x - 1) - 1) :: int)\"\ndefinition \"WORD_MIN x \\<equiv> (- (2 ^ (len_of x - 1)) :: int)\"\ndefinition \"UWORD_MAX x \\<equiv> ((2 ^ (len_of x)) - 1 :: nat)\"\n\nlemma WORD_values [simplified]:\n  \"WORD_MAX (TYPE(8 signed)) = (2 ^ 7 - 1)\"\n  \"WORD_MAX (TYPE(16 signed)) = (2 ^ 15 - 1)\"\n  \"WORD_MAX (TYPE(32 signed)) = (2 ^ 31 - 1)\"\n\n  \"WORD_MIN (TYPE(8 signed)) = - (2 ^ 7)\"\n  \"WORD_MIN (TYPE(16 signed)) = - (2 ^ 15)\"\n  \"WORD_MIN (TYPE(32 signed)) = - (2 ^ 31)\"\n\n  \"UWORD_MAX (TYPE(8)) = (2 ^ 8 - 1)\"\n  \"UWORD_MAX (TYPE(16)) = (2 ^ 16 - 1)\"\n  \"UWORD_MAX (TYPE(32)) = (2 ^ 32 - 1)\"\n  by (auto simp: WORD_MAX_def WORD_MIN_def UWORD_MAX_def)\n\nlemmas WORD_values_add1 =\n   WORD_values [THEN arg_cong [where f=\"\\<lambda>x. x + 1\"],\n    simplified semiring_norm, simplified numeral_One]\n\nlemmas WORD_values_minus1 =\n   WORD_values [THEN arg_cong [where f=\"\\<lambda>x. x - 1\"],\n    simplified semiring_norm, simplified numeral_One nat_numeral]\n\nlemmas [L1unfold] =\n  WORD_values [symmetric]\n  WORD_values_add1 [symmetric]\n  WORD_values_minus1 [symmetric]\n\nlemma WORD_MAX_simps [polish]:\n   \"WORD_MAX TYPE(32) = INT_MAX\"\n   \"WORD_MAX TYPE(16) = SHORT_MAX\"\n   \"WORD_MAX TYPE(8) = CHAR_MAX\"\n  by (auto simp: INT_MAX_def SHORT_MAX_def CHAR_MAX_def WORD_MAX_def)\n\nlemma WORD_MIN_simps [polish]:\n   \"WORD_MIN TYPE(32) = INT_MIN\"\n   \"WORD_MIN TYPE(16) = SHORT_MIN\"\n   \"WORD_MIN TYPE(8) = CHAR_MIN\"\n  by (auto simp: INT_MIN_def SHORT_MIN_def CHAR_MIN_def WORD_MIN_def)\n\nlemma UWORD_MAX_simps [polish]:\n   \"UWORD_MAX TYPE(32) = UINT_MAX\"\n   \"UWORD_MAX TYPE(16) = USHORT_MAX\"\n   \"UWORD_MAX TYPE(8) = UCHAR_MAX\"\n  by (auto simp: UINT_MAX_def USHORT_MAX_def UCHAR_MAX_def UWORD_MAX_def)\n\nlemma WORD_signed_to_unsigned [polish, simp]:\n   \"WORD_MAX TYPE('a signed) = WORD_MAX TYPE('a::len)\"\n   \"WORD_MIN TYPE('a signed) = WORD_MIN TYPE('a::len)\"\n   \"UWORD_MAX TYPE('a signed) = UWORD_MAX TYPE('a::len)\"\n  by (auto simp: WORD_MAX_def WORD_MIN_def UWORD_MAX_def)\n\n\nlemma INT_MIN_MAX_lemmas [simp, polish]:\n  \"unat (u :: word32) \\<le> UINT_MAX\"\n  \"sint (s :: sword32) \\<le> INT_MAX\"\n  \"INT_MIN \\<le> sint (s :: sword32)\"\n  \"INT_MIN \\<le> INT_MAX\"\n  \"INT_MIN \\<le> sint (s :: sword32)\"\n  \"INT_MIN \\<le> INT_MAX\"\n  \"INT_MIN \\<le> 0\"\n  \"0 \\<le> INT_MAX\"\n\n  \"\\<not> (sint (s :: sword32) > INT_MAX)\"\n  \"\\<not> (INT_MIN > sint (s :: sword32))\"\n  \"\\<not> (unat (u :: word32) > UINT_MAX)\"\n\n  unfolding UINT_MAX_def INT_MAX_def INT_MIN_def\n  using sint_range_size [where w=s, simplified word_size, simplified]\n        unat_lt2p [where 'a=32, simplified]\n        zle_add1_eq_le [where z=INT_MAX, symmetric]\n        less_eq_Suc_le not_less_eq_eq\n        unat_lt2p [where x=u]\n  by auto\n\n(*\n * The following set of theorems allow us to discharge simple\n * equalities involving INT_MIN, INT_MAX and UINT_MAX without\n * the constants being unfolded in the final output.\n *\n * For example:\n *\n *    (4 < INT_MAX)  becomes  True\n *    (x < INT_MAX)  remains  (x < INT_MAX)\n *)\n\nlemma INT_MIN_comparisons [simp]:\n  \"\\<lbrakk> a \\<le> - (2 ^ (len_of TYPE('a) - 1)) \\<rbrakk> \\<Longrightarrow> a \\<le> WORD_MIN (TYPE('a::len))\"\n  \"a < - (2 ^ (len_of TYPE('a) - 1)) \\<Longrightarrow> a < WORD_MIN (TYPE('a::len))\"\n  \"a \\<ge> - (2 ^ (len_of TYPE('a) - 1)) \\<Longrightarrow> a \\<ge> WORD_MIN (TYPE('a::len))\"\n  \"a > - (2 ^ (len_of TYPE('a) - 1)) \\<Longrightarrow> a \\<ge> WORD_MIN (TYPE('a::len))\"\n  by (auto simp: WORD_MIN_def)\n\nlemma INT_MAX_comparisons [simp]:\n  \"a \\<le> (2 ^ (len_of TYPE('a) - 1)) - 1 \\<Longrightarrow> a \\<le> WORD_MAX (TYPE('a::len))\"\n  \"a < (2 ^ (len_of TYPE('a) - 1)) - 1 \\<Longrightarrow> a < WORD_MAX (TYPE('a::len))\"\n  \"a \\<ge> (2 ^ (len_of TYPE('a) - 1)) - 1 \\<Longrightarrow> a \\<ge> WORD_MAX (TYPE('a::len))\"\n  \"a > (2 ^ (len_of TYPE('a) - 1)) - 1 \\<Longrightarrow> a \\<ge> WORD_MAX (TYPE('a::len))\"\n  by (auto simp: WORD_MAX_def)\n\nlemma UINT_MAX_comparisons [simp]:\n  \"x \\<le> (2 ^ (len_of TYPE('a))) - 1 \\<Longrightarrow> x \\<le> UWORD_MAX (TYPE('a::len))\"\n  \"x < (2 ^ (len_of TYPE('a))) - 1 \\<Longrightarrow> x \\<le> UWORD_MAX (TYPE('a::len))\"\n  \"x \\<ge> (2 ^ (len_of TYPE('a))) - 1 \\<Longrightarrow> x \\<ge> UWORD_MAX (TYPE('a::len))\"\n  \"x > (2 ^ (len_of TYPE('a))) - 1 \\<Longrightarrow> x > UWORD_MAX (TYPE('a::len))\"\n  by (auto simp: UWORD_MAX_def)\n\n(*\n * This definition is used when we are trying to introduce a new type\n * in the program text: it simply states that introducing a given\n * abstraction is desired in the current context.\n *)\ndefinition \"introduce_typ_abs_fn f \\<equiv> True\"\n\ndeclare introduce_typ_abs_fn_def [simp]\n\nlemma introduce_typ_abs_fn:\n  \"introduce_typ_abs_fn f\"\n  by simp\n\n(*\n * Show that a binary operator \"X\" (of type \"'a \\<Rightarrow> 'a \\<Rightarrow> bool\") is an\n * abstraction (over function f) of \"X'\".\n *\n * For example, (a \\<le>\\<^sub>i\\<^sub>n\\<^sub>t b) could be an abstraction of (a \\<le>\\<^sub>w\\<^sub>3\\<^sub>2 b)\n * over the abstraction function \"unat\".\n *)\ndefinition\n  abstract_bool_binop :: \"('a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> ('c \\<Rightarrow> 'a)\n               \\<Rightarrow> ('a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> ('c \\<Rightarrow> 'c \\<Rightarrow> bool) \\<Rightarrow> bool\"\nwhere\n  \"abstract_bool_binop P f X X' \\<equiv> \\<forall>a b. P (f a) (f b) \\<longrightarrow> (X' a b = X (f a) (f b))\"\n\n(* Show that a binary operator \"X\" (of type \"'a \\<Rightarrow> 'a \\<Rightarrow> 'b\") abstracts \"X'\". *)\ndefinition\n  abstract_binop :: \"('a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> ('c \\<Rightarrow> 'a)\n               \\<Rightarrow> ('a \\<Rightarrow> 'a \\<Rightarrow> 'a) \\<Rightarrow> ('c \\<Rightarrow> 'c \\<Rightarrow> 'c) \\<Rightarrow> bool\"\nwhere\n   \"abstract_binop P f X X' \\<equiv> \\<forall>a b. P (f a) (f b) \\<longrightarrow> (f (X' a b) = X (f a) (f b))\"\n\n(* The value \"a\" is the abstract version of \"b\" under precondition \"P\". *)\ndefinition \"abstract_val P a f b \\<equiv> P \\<longrightarrow> (a = f b)\"\n\n(* The variable \"a\" is the abstracted version of the variable \"b\". *)\ndefinition \"abs_var a f b \\<equiv> abstract_val True a f b\"\n\ndeclare abstract_bool_binop_def [simp]\ndeclare abstract_binop_def [simp]\ndeclare abstract_val_def [simp]\ndeclare abs_var_def [simp]\n\nlemma abstract_val_trivial:\n  \"abstract_val True (f b) f b\"\n  by simp\n\nlemma abstract_binop_is_abstract_val:\n    \"abstract_binop P f X X' = (\\<forall>a b. abstract_val (P (f a) (f b)) (X (f a) (f b)) f (X' a b))\"\n  by auto\n\nlemma abstract_expr_bool_binop:\n  \"\\<lbrakk> abstract_bool_binop E f X X';\n     introduce_typ_abs_fn f;\n     abstract_val P a f a';\n     abstract_val Q b f b' \\<rbrakk> \\<Longrightarrow>\n           abstract_val (P \\<and> Q \\<and> E a b) (X a b) id (X' a' b')\"\n  by clarsimp\n\nlemma abstract_expr_binop:\n  \"\\<lbrakk> abstract_binop E f X X';\n     abstract_val P a f a';\n     abstract_val Q b f b' \\<rbrakk> \\<Longrightarrow>\n           abstract_val (P \\<and> Q \\<and> E a b) (X a b) f (X' a' b')\"\n  by clarsimp\n\nlemma unat_abstract_bool_binops:\n    \"abstract_bool_binop (\\<lambda>_ _. True) (unat :: ('a::len) word \\<Rightarrow> nat) (op <) (op <)\"\n    \"abstract_bool_binop (\\<lambda>_ _. True) (unat :: ('a::len) word \\<Rightarrow> nat) (op \\<le>) (op \\<le>)\"\n    \"abstract_bool_binop (\\<lambda>_ _. True) (unat :: ('a::len) word \\<Rightarrow> nat) (op =) (op =)\"\n  by (auto simp:  word_less_nat_alt word_le_nat_alt eq_iff)\n\nlemmas unat_mult_simple = iffD1 [OF unat_mult_lem [unfolded word_bits_len_of]]\n\nlemma le_to_less_plus_one:\n    \"((a::nat) \\<le> b) = (a < b + 1)\"\n  by arith\n\nlemma unat_abstract_binops:\n  \"abstract_binop (\\<lambda>a b. a + b \\<le> UWORD_MAX TYPE('a::len)) (unat :: 'a word \\<Rightarrow> nat) (op +) (op +)\"\n  \"abstract_binop (\\<lambda>a b. a * b \\<le> UWORD_MAX TYPE('a)) (unat :: 'a word \\<Rightarrow> nat) (op * ) (op * )\"\n  \"abstract_binop (\\<lambda>a b. a \\<ge> b) (unat :: 'a word \\<Rightarrow> nat) (op -) (op -)\"\n  \"abstract_binop (\\<lambda>a b. True) (unat :: 'a word \\<Rightarrow> nat) (op div) (op div)\"\n  \"abstract_binop (\\<lambda>a b. True) (unat :: 'a word \\<Rightarrow> nat) (op mod) (op mod)\"\n  by (auto simp: unat_plus_if' unat_div unat_mod UWORD_MAX_def le_to_less_plus_one\n              WordAbstract.unat_mult_simple word_bits_def unat_sub word_le_nat_alt)\n\nlemma snat_abstract_bool_binops:\n    \"abstract_bool_binop (\\<lambda>_ _. True) (sint :: ('a::len) signed word \\<Rightarrow> int) (op <) (word_sless)\"\n    \"abstract_bool_binop (\\<lambda>_ _. True) (sint :: 'a signed word \\<Rightarrow> int) (op \\<le>) (word_sle)\"\n    \"abstract_bool_binop (\\<lambda>_ _. True) (sint :: 'a signed word \\<Rightarrow> int) (op =) (op =)\"\n  by (auto simp: word_sless_def word_sle_def less_le)\n\nlemma snat_abstract_binops:\n  \"abstract_binop (\\<lambda>a b. WORD_MIN TYPE('a::len) \\<le> a + b \\<and> a + b \\<le> WORD_MAX TYPE('a)) (sint :: 'a signed word \\<Rightarrow> int) (op +) (op +)\"\n  \"abstract_binop (\\<lambda>a b. WORD_MIN TYPE('a) \\<le> a * b \\<and> a * b \\<le> WORD_MAX TYPE('a)) (sint :: 'a signed word \\<Rightarrow> int) (op *) (op *)\"\n  \"abstract_binop (\\<lambda>a b. WORD_MIN TYPE('a) \\<le> a - b \\<and> a - b \\<le> WORD_MAX TYPE('a)) (sint :: 'a signed word \\<Rightarrow> int) (op -) (op -)\"\n  \"abstract_binop (\\<lambda>a b. WORD_MIN TYPE('a) \\<le> a sdiv b \\<and> a sdiv b \\<le> WORD_MAX TYPE('a)) (sint :: 'a signed word \\<Rightarrow> int) (op sdiv) (op sdiv)\"\n  \"abstract_binop (\\<lambda>a b. WORD_MIN TYPE('a) \\<le> a smod b \\<and> a smod b \\<le> WORD_MAX TYPE('a)) (sint :: 'a signed word \\<Rightarrow> int) (op smod) (op smod)\"\n  by (auto simp: signed_arith_sint word_size WORD_MIN_def WORD_MAX_def)\n\nlemma abstract_val_signed_unary_minus:\n  \"\\<lbrakk> abstract_val P r sint r' \\<rbrakk> \\<Longrightarrow>\n       abstract_val (P \\<and> (- r) \\<le> WORD_MAX TYPE('a)) (- r) sint ( - (r' :: ('a :: len) signed word))\"\n  apply clarsimp\n  using sint_range_size [where w=r']\n  apply -\n  apply (subst signed_arith_sint)\n   apply (clarsimp simp: word_size WORD_MAX_def)\n  apply simp\n  done\n\nlemma abstract_val_unsigned_unary_minus:\n  \"\\<lbrakk> abstract_val P r unat r' \\<rbrakk> \\<Longrightarrow>\n       abstract_val P (if r = 0 then 0 else UWORD_MAX TYPE('a::len) + 1 - r) unat ( - (r' :: 'a word))\"\n  by (clarsimp simp: unat_minus word_size unat_eq_zero UWORD_MAX_def)\n\nlemmas abstract_val_signed_ops [simplified simp_thms] =\n  abstract_expr_bool_binop [OF snat_abstract_bool_binops(1)]\n  abstract_expr_bool_binop [OF snat_abstract_bool_binops(2)]\n  abstract_expr_bool_binop [OF snat_abstract_bool_binops(3)]\n  abstract_expr_binop [OF snat_abstract_binops(1)]\n  abstract_expr_binop [OF snat_abstract_binops(2)]\n  abstract_expr_binop [OF snat_abstract_binops(3)]\n  abstract_expr_binop [OF snat_abstract_binops(4)]\n  abstract_expr_binop [OF snat_abstract_binops(5)]\n  abstract_val_signed_unary_minus\n\nlemmas abstract_val_unsigned_ops [simplified simp_thms] =\n  abstract_expr_bool_binop [OF unat_abstract_bool_binops(1)]\n  abstract_expr_bool_binop [OF unat_abstract_bool_binops(2)]\n  abstract_expr_bool_binop [OF unat_abstract_bool_binops(3)]\n  abstract_expr_binop [OF unat_abstract_binops(1)]\n  abstract_expr_binop [OF unat_abstract_binops(2)]\n  abstract_expr_binop [OF unat_abstract_binops(3)]\n  abstract_expr_binop [OF unat_abstract_binops(4)]\n  abstract_expr_binop [OF unat_abstract_binops(5)]\n  abstract_val_unsigned_unary_minus\n\nlemma mod_less:\n  \"(a :: nat) < c \\<Longrightarrow> a mod b < c\"\n  by (metis less_trans mod_less_eq_dividend order_leE)\n\nlemma abstract_val_ucast:\n    \"\\<lbrakk> introduce_typ_abs_fn (unat :: ('a::len) word \\<Rightarrow> nat);\n       abstract_val P v unat v' \\<rbrakk>\n       \\<Longrightarrow>  abstract_val (P \\<and> v \\<le> nat (WORD_MAX TYPE('a)))\n                  (int v) sint (ucast (v' :: 'a word) :: 'a signed word)\"\n  apply (clarsimp simp: uint_nat [symmetric])\n  apply (subst sint_eq_uint)\n   apply (rule not_msb_from_less)\n   apply (clarsimp simp: word_less_nat_alt unat_ucast WORD_MAX_def le_to_less_plus_one)\n   apply (subst (asm) nat_diff_distrib)\n     apply simp\n    apply clarsimp\n   apply clarsimp\n   apply (metis int_numeral nat_numeral nat_power_eq zero_zle_int)\n  apply (clarsimp simp: uint_up_ucast is_up)\n  done\n\nlemma abstract_val_scast:\n    \"\\<lbrakk> introduce_typ_abs_fn (sint :: ('a::len) signed word \\<Rightarrow> int);\n       abstract_val P C' sint C \\<rbrakk>\n            \\<Longrightarrow>  abstract_val (P \\<and> 0 \\<le> C') (nat C') unat (scast (C :: ('a::len) signed word) :: ('a::len) word)\"\n  apply (clarsimp simp: down_cast_same [symmetric] is_down unat_ucast)\n  apply (subst sint_eq_uint)\n   apply (clarsimp simp: word_msb_sint)\n  apply (clarsimp simp: unat_def [symmetric])\n  apply (subst word_unat.norm_Rep [symmetric])\n  apply clarsimp\n  done\n\nlemma abstract_val_scast_upcast:\n    \"\\<lbrakk> len_of TYPE('a::len) \\<le> len_of TYPE('b::len);\n       abstract_val P C' sint C \\<rbrakk>\n            \\<Longrightarrow>  abstract_val P (C') sint (scast (C :: 'a signed word) :: 'b signed word)\"\n  by (clarsimp simp: down_cast_same [symmetric] sint_up_scast is_up)\n\nlemma abstract_val_scast_downcast:\n    \"\\<lbrakk> len_of TYPE('b) < len_of TYPE('a::len);\n       abstract_val P C' sint C \\<rbrakk>\n            \\<Longrightarrow>  abstract_val P (sbintrunc ((len_of TYPE('b::len) - 1)) C') sint (scast (C :: 'a signed word) :: 'b signed word)\"\n  apply (clarsimp simp: scast_def word_of_int_def sint_uint bintrunc_mod2p [symmetric])\n  apply (subst bintrunc_sbintrunc_le)\n   apply clarsimp\n  apply (subst Abs_word_inverse)\n   apply (metis len_signed uint word_ubin.eq_norm)\n  apply clarsimp\n  done\n\nlemma abstract_val_ucast_upcast:\n    \"\\<lbrakk> len_of TYPE('a::len) \\<le> len_of TYPE('b::len);\n       abstract_val P C' unat C \\<rbrakk>\n            \\<Longrightarrow>  abstract_val P (C') unat (ucast (C :: 'a word) :: 'b word)\"\n  by (clarsimp simp: is_up unat_ucast_upcast)\n\nlemma abstract_val_ucast_downcast:\n    \"\\<lbrakk> len_of TYPE('b::len) < len_of TYPE('a::len);\n       abstract_val P C' unat C \\<rbrakk>\n            \\<Longrightarrow>  abstract_val P (C' mod (UWORD_MAX TYPE('b) + 1)) unat (ucast (C :: 'a word) :: 'b word)\"\n  apply (clarsimp simp: scast_def word_of_int_def sint_uint UWORD_MAX_def)\n  unfolding ucast_def unat_def\n  apply (subst int_word_uint)\n  apply (metis (hide_lams, mono_tags) uint_mod uint_power_lower\n      unat_def unat_mod unat_power_lower)\n  done\n\n(*\n * The pair A/C are a valid abstraction/concrete-isation function pair,\n * under the precondition's P and Q.\n *)\ndefinition\n \"valid_typ_abs_fn (P :: 'a \\<Rightarrow> bool) (Q :: 'a \\<Rightarrow> bool) (A :: 'c \\<Rightarrow> 'a) (C :: 'a \\<Rightarrow> 'c) \\<equiv>\n     (\\<forall>v. P v \\<longrightarrow> A (C v) = v) \\<and> (\\<forall>v. Q (A v) \\<longrightarrow> C (A v) = v)\"\n\ndeclare valid_typ_abs_fn_def [simp]\n\nlemma valid_typ_abs_fn_id:\n  \"valid_typ_abs_fn \\<top> \\<top> id id\"\n  by clarsimp\n\nlemma valid_typ_abs_fn_unit:\n  \"valid_typ_abs_fn \\<top> \\<top> id (id :: unit \\<Rightarrow> unit)\"\n  by clarsimp\n\nlemma valid_typ_abs_fn_unat:\n  \"valid_typ_abs_fn (\\<lambda>v. v \\<le> UWORD_MAX TYPE('a::len)) \\<top> (unat :: 'a word \\<Rightarrow> nat) (of_nat :: nat \\<Rightarrow> 'a word)\"\n  by (clarsimp simp: unat_of_nat_eq UWORD_MAX_def le_to_less_plus_one)\n\nlemma valid_typ_abs_fn_sint:\n  \"valid_typ_abs_fn (\\<lambda>v. WORD_MIN TYPE('a::len) \\<le> v \\<and> v \\<le> WORD_MAX TYPE('a)) \\<top> (sint :: 'a signed word \\<Rightarrow> int) (of_int :: int \\<Rightarrow> 'a signed word)\"\n  by (clarsimp simp: sint_of_int_eq WORD_MIN_def WORD_MAX_def)\n\nlemma valid_typ_abs_fn_tuple:\n  \"\\<lbrakk> valid_typ_abs_fn P_a Q_a abs_a conc_a; valid_typ_abs_fn P_b Q_b abs_b conc_b \\<rbrakk> \\<Longrightarrow>\n          valid_typ_abs_fn (\\<lambda>(a, b). P_a a \\<and> P_b b) (\\<lambda>(a, b). Q_a a \\<and> Q_b b) (map_prod abs_a abs_b) (map_prod conc_a conc_b)\"\n  by clarsimp\n\nlemma introduce_typ_abs_fn_tuple:\n  \"\\<lbrakk> introduce_typ_abs_fn abs_a; introduce_typ_abs_fn abs_b \\<rbrakk> \\<Longrightarrow>\n         introduce_typ_abs_fn (map_prod abs_a abs_b)\"\n  by clarsimp\n\ndefinition [simp]:\n  \"corresTA P rx ex A C \\<equiv> corresXF (\\<lambda>s. s) (\\<lambda>r s. rx r) (\\<lambda>r s. ex r) P A C\"\n\nlemma corresTA_L2_gets:\n  \"\\<lbrakk> \\<And>s. abstract_val (Q s) (C s) rx (C' s) \\<rbrakk> \\<Longrightarrow>\n     corresTA Q rx ex (L2_gets (\\<lambda>s. C s) n) (L2_gets (\\<lambda>s. C' s) n)\"\n  apply (monad_eq simp: L2_defs corresXF_def)\n  done\n\nlemma corresTA_L2_modify:\n    \"\\<lbrakk> \\<And>s. abstract_val (P s) (m s) id (m' s) \\<rbrakk> \\<Longrightarrow>\n            corresTA P rx ex (L2_modify (\\<lambda>s. m s)) (L2_modify (\\<lambda>s. m' s))\"\n  by (monad_eq simp: L2_modify_def corresXF_def)\n\nlemma corresTA_L2_throw:\n  \"\\<lbrakk> abstract_val Q C ex C' \\<rbrakk> \\<Longrightarrow>\n     corresTA (\\<lambda>_. Q) rx ex (L2_throw C n) (L2_throw C' n)\"\n  apply (monad_eq simp: L2_defs corresXF_def)\n  done\n\nlemma corresTA_L2_skip:\n  \"corresTA \\<top> rx ex L2_skip L2_skip\"\n  apply (monad_eq simp: L2_defs corresXF_def)\n  done\n\nlemma corresTA_L2_fail:\n  \"corresTA \\<top> rx ex L2_fail L2_fail\"\n  by (clarsimp simp: L2_defs corresXF_def)\n\nlemma corresTA_L2_seq':\n  fixes L' :: \"('s, 'e + 'c1) nondet_monad\"\n  fixes R' :: \"'c1 \\<Rightarrow> ('s, 'e + 'c2) nondet_monad\"\n  fixes L :: \"('s, 'ea + 'a1) nondet_monad\"\n  fixes R :: \"'a1 \\<Rightarrow> ('s, 'ea + 'a2) nondet_monad\"\n  shows\n  \"\\<lbrakk> corresTA P rx1 ex L L';\n     \\<And>r. corresTA (Q (rx1 r)) rx2 ex (R (rx1 r)) (R' r) \\<rbrakk> \\<Longrightarrow>\n    corresTA P rx2 ex\n       (L2_seq L (\\<lambda>r. L2_seq (L2_guard (\\<lambda>s. Q r s)) (\\<lambda>_. R r)))\n       (L2_seq L' (\\<lambda>r. R' r))\"\n  apply atomize\n  apply (clarsimp simp: L2_seq_def L2_guard_def)\n  apply (erule corresXF_join [where P'=\"\\<lambda>x y s. rx1 y = x\"])\n    apply (monad_eq simp: corresXF_def split: sum.splits)\n   apply clarsimp\n   apply (rule hoareE_TrueI)\n  apply simp\n  done\n\nlemma corresTA_L2_seq:\n  \"\\<lbrakk> introduce_typ_abs_fn rx1;\n    corresTA P (rx1 :: 'a \\<Rightarrow> 'b) ex L L';\n     \\<And>r r'. abs_var r rx1 r' \\<Longrightarrow> corresTA (\\<lambda>s. Q r s) rx2 ex (\\<lambda>s. R r s) (\\<lambda>s. R' r' s) \\<rbrakk> \\<Longrightarrow>\n       corresTA P rx2 ex (L2_seq L (\\<lambda>r. L2_seq (L2_guard (\\<lambda>s. Q r s)) (\\<lambda>_ s. R r s))) (L2_seq L' (\\<lambda>r s. R' r s))\"\n  by (rule corresTA_L2_seq', simp+)\n\nlemma corresTA_L2_seq_unit:\n  fixes L' :: \"('s, 'e + unit) nondet_monad\"\n  fixes R' :: \"unit \\<Rightarrow> ('s, 'e + 'r) nondet_monad\"\n  fixes L :: \"('s, 'ea + unit) nondet_monad\"\n  fixes R :: \"('s, 'ea + 'ra) nondet_monad\"\n  shows\n  \"\\<lbrakk> corresTA P id ex L L';\n     corresTA Q rx ex (\\<lambda>s. R s) (\\<lambda>s. R' () s) \\<rbrakk> \\<Longrightarrow>\n    corresTA P rx ex\n       (L2_seq L (\\<lambda>r. L2_seq (L2_guard Q) (\\<lambda>r s. R s)))\n       (L2_seq L' (\\<lambda>r s. R' r s))\"\n  by (rule corresTA_L2_seq', simp+)\n\nlemma corresTA_L2_catch':\n  fixes L' :: \"('s, 'e1 + 'c) nondet_monad\"\n  fixes R' :: \"'e1 \\<Rightarrow> ('s, 'e2 + 'c) nondet_monad\"\n  fixes L :: \"('s, 'e1a + 'ca) nondet_monad\"\n  fixes R :: \"'e1a \\<Rightarrow> ('s, 'e2a + 'ca) nondet_monad\"\n  shows\n  \"\\<lbrakk> corresTA P rx ex1 L L';\n     \\<And>r. corresTA (Q (ex1 r)) rx ex2 (R (ex1 r)) (R' r) \\<rbrakk> \\<Longrightarrow>\n    corresTA P rx ex2 (L2_catch L (\\<lambda>r. L2_seq (L2_guard (\\<lambda>s. Q r s)) (\\<lambda>_. R r))) (L2_catch L' (\\<lambda>r. R' r))\"\n  apply atomize\n  apply (clarsimp simp: L2_seq_def L2_catch_def L2_guard_def)\n  apply (erule corresXF_except [where P'=\"\\<lambda>x y s. ex1 y = x\"])\n    apply (monad_eq simp: corresXF_def split: sum.splits cong: rev_conj_cong)\n   apply clarsimp\n   apply (rule hoareE_TrueI)\n  apply simp\n  done\n\nlemma corresTA_L2_catch:\n  \"\\<lbrakk> introduce_typ_abs_fn ex1;\n     corresTA P rx ex1 L L';\n     \\<And>r r'. abs_var r ex1 r' \\<Longrightarrow> corresTA (Q r) rx ex2 (R r) (R' r') \\<rbrakk> \\<Longrightarrow>\n       corresTA P rx ex2 (L2_catch L (\\<lambda>r. L2_seq (L2_guard (\\<lambda>s. Q r s)) (\\<lambda>_. R r))) (L2_catch L' (\\<lambda>r. R' r))\"\n  by (rule corresTA_L2_catch', simp+)\n\nlemma corresTA_L2_while:\n  assumes init_corres: \"abstract_val Q i rx i'\"\n  and cond_corres: \"\\<And>r r' s. abs_var r rx r'\n                           \\<Longrightarrow> abstract_val (G r s) (C r s) id (C' r' s)\"\n  and body_corres: \"\\<And>r r'. abs_var r rx r'\n                           \\<Longrightarrow> corresTA (P r) rx ex (B r) (B' r')\"\n  shows \"corresTA (\\<lambda>_. Q) rx ex\n       (L2_guarded_while (\\<lambda>r s. G r s) (\\<lambda>r s. C r s) (\\<lambda>r. L2_seq (L2_guard (\\<lambda>s. P r s)) (\\<lambda>_. B r)) i x)\n       (L2_while (\\<lambda>r s. C' r s) B' i' x)\"\nproof -\n  note body_corres' =\n       corresXF_guarded_while_body [OF body_corres [unfolded corresTA_def]]\n\n  have init_corres':\n    \"Q \\<Longrightarrow> i = rx i'\"\n    using init_corres\n    by simp\n\n  show ?thesis\n    apply (clarsimp simp: L2_defs guardE_def [symmetric] returnOk_liftE [symmetric])\n    apply (rule corresXF_assume_pre)\n    apply (rule corresXF_guarded_while [where P=\"\\<lambda>r s. G (rx r) s\"])\n        apply (cut_tac r'=x in body_corres, simp)\n        apply (monad_eq simp: guardE_def corresXF_def split: sum.splits)\n       apply (insert cond_corres)[1]\n       apply clarsimp\n      apply clarsimp\n      apply (rule hoareE_TrueI)\n     apply (clarsimp simp: init_corres)\n     apply (insert init_corres)[1]\n     apply (clarsimp)\n    apply (clarsimp simp: init_corres')\n  done\nqed\n\nlemma corresTA_L2_guard:\n  \"\\<lbrakk> \\<And>s. abstract_val (Q s) (G s) id (G' s) \\<rbrakk>\n           \\<Longrightarrow> corresTA \\<top> rx ex (L2_guard (\\<lambda>s. G s \\<and> Q s)) (L2_guard (\\<lambda>s. G' s))\"\n  apply (monad_eq simp: L2_defs corresXF_def)\n  done\n\nlemma corresTA_L2_condition:\n  \"\\<lbrakk> corresTA P rx ex L L';\n     corresTA Q rx ex R R';\n     \\<And>s. abstract_val (T s) (C s) id (C' s)  \\<rbrakk>\n   \\<Longrightarrow> corresTA T rx ex\n          (L2_condition (\\<lambda>s. C s)\n            (L2_seq (L2_guard P) (\\<lambda>_. L))\n            (L2_seq (L2_guard Q) (\\<lambda>_. R))\n           ) (L2_condition (\\<lambda>s. C' s) L' R')\"\n  apply atomize\n  apply (monad_eq simp: L2_defs corresXF_def Ball_def split: sum.splits)\n  apply force\n  done\n\n\n(* Backup rule to corresTA_L2_call. Converts the return type of the function call. *)\nlemma corresTA_L2_call':\n  \"\\<lbrakk> \\<And>s. corresTA P f1 x1 A B;\n               valid_typ_abs_fn Q1 Q1' f1 f1';\n               valid_typ_abs_fn Q2 Q2' f2 f2'\n        \\<rbrakk> \\<Longrightarrow>\n        corresTA (\\<lambda>s. P s) f2 x2\n           (L2_seq (L2_call A) (\\<lambda>ret. (L2_seq (L2_guard (\\<lambda>_. Q1' ret)) (\\<lambda>_. L2_gets (\\<lambda>_. f2 (f1' ret)) [''ret'']))))\n           (L2_call B)\"\n  apply (clarsimp simp: L2_defs L2_call_def corresXF_def)\n  apply (monad_eq split: sum.splits)\n  apply (rule conjI)\n   apply metis\n  apply clarsimp\n  apply blast\n  done\n\nlemma corresTA_L2_call:\n  \"\\<lbrakk> corresTA P rx ex A B \\<rbrakk> \\<Longrightarrow>\n        corresTA P rx ex' (L2_call A) (L2_call B)\"\n  apply (clarsimp simp: L2_defs L2_call_def corresXF_def)\n  apply (monad_eq split: sum.splits)\n  apply fastforce\n  done\n\nlemma corresTA_measure_call:\n  \"\\<lbrakk> monad_mono B; \\<And>m. corresTA P rx id (A m) (B m) \\<rbrakk> \\<Longrightarrow>\n        corresTA P rx id (measure_call A) (measure_call B)\"\n  by (simp add: corresTA_def corresXF_measure_call)\n\nlemma corresTA_L2_unknown:\n  \"corresTA \\<top> rx ex (L2_unknown x) (L2_unknown x)\"\n  apply (monad_eq simp: L2_defs corresXF_def)\n  done\n\nlemma corresTA_L2_call_exec_concrete:\n  \"\\<lbrakk> corresTA P rx id A B \\<rbrakk> \\<Longrightarrow>\n        corresTA (\\<lambda>s. \\<forall>s'. s = st s' \\<longrightarrow> P s') rx id\n               (exec_concrete st (L2_call A))\n               (exec_concrete st (L2_call B))\"\n  apply (clarsimp simp: L2_defs L2_call_def corresXF_def)\n  apply (monad_eq split: sum.splits)\n  apply fastforce\n  done\n\nlemma corresTA_L2_call_exec_abstract:\n  \"\\<lbrakk> corresTA P rx id A B \\<rbrakk> \\<Longrightarrow>\n        corresTA (\\<lambda>s. P (st s)) rx id\n               (exec_abstract st (L2_call A))\n               (exec_abstract st (L2_call B))\"\n  apply (clarsimp simp: L2_defs L2_call_def corresXF_def)\n  apply (monad_eq split: sum.splits)\n  apply fastforce\n  done\n\nlemma abstract_val_fun_app:\n   \"\\<lbrakk> abstract_val Q b id b'; abstract_val P a id a' \\<rbrakk> \\<Longrightarrow>\n           abstract_val (P \\<and> Q) (f $ (a $ b)) f (a' $ b')\"\n  by simp\n\nlemma corresTA_precond_to_guard:\n  \"corresTA (\\<lambda>s. P s) rx ex A A' \\<Longrightarrow> corresTA \\<top> rx ex (L2_seq (L2_guard (\\<lambda>s. P s)) (\\<lambda>_. A)) A'\"\n  apply (monad_eq simp: corresXF_def L2_defs split: sum.splits)\n  done\n\nlemma corresTA_precond_to_asm:\n  \"\\<lbrakk> \\<And>s. P s \\<Longrightarrow> corresTA \\<top> rx ex A A' \\<rbrakk> \\<Longrightarrow> corresTA P rx ex A A'\"\n  by (clarsimp simp: corresXF_def)\n\nlemma L2_guard_true: \"L2_seq (L2_guard \\<top>) A = A ()\"\n  by (monad_eq simp: L2_defs)\nlemma corresTA_simp_trivial_guard:\n  \"corresTA P rx ex (L2_seq (L2_guard \\<top>) A) C \\<equiv> corresTA P rx ex (A ()) C\"\n  by (simp add: L2_guard_true)\n\ndefinition \"L2_assume P \\<equiv> condition P (returnOk ()) (selectE {})\"\n\nlemma L2_assume_alt_def:\n  \"L2_assume P = (\\<lambda>s. (if P s then {(Inr (), s)} else {}, False))\"\n  by (monad_eq simp: L2_assume_def selectE_def)\n\nlemma corresTA_assume_values:\n  \"\\<lbrakk> abstract_val P a f a'; corresTA \\<top> rx ex X X' \\<rbrakk>\n              \\<Longrightarrow> corresTA \\<top> rx ex (L2_seq (L2_assume (\\<lambda>s. P \\<longrightarrow> (\\<exists>a'. a = f a'))) (\\<lambda>_. X)) X'\"\n  apply (monad_eq simp: corresXF_def L2_defs L2_assume_alt_def split: sum.splits)\n  apply force\n  done\n\nlemma corresTA_extract_preconds_of_call_init:\n  \"\\<lbrakk> corresTA (\\<lambda>s. P) rx ex A A' \\<rbrakk> \\<Longrightarrow> corresTA (\\<lambda>s. P \\<and> True) rx ex A A'\"\n  by simp\n\nlemma corresTA_extract_preconds_of_call_step:\n  \"\\<lbrakk> corresTA (\\<lambda>s. (abs_var a f a' \\<and> R) \\<and> C) rx ex A A'; abstract_val Y a f a' \\<rbrakk>\n           \\<Longrightarrow> corresTA (\\<lambda>s. R \\<and> (Y \\<and> C)) rx ex A A'\"\n  by (clarsimp simp: corresXF_def)\n\nlemma corresTA_extract_preconds_of_call_final:\n  \"\\<lbrakk> corresTA (\\<lambda>s. (abs_var a f a') \\<and> C) rx ex A A'; abstract_val Y a f a' \\<rbrakk>\n           \\<Longrightarrow> corresTA (\\<lambda>s. (Y \\<and> C)) rx ex A A'\"\n  by (clarsimp simp: corresXF_def)\n\nlemma corresTA_extract_preconds_of_call_final':\n  \"\\<lbrakk> corresTA (\\<lambda>s. True \\<and> C) rx ex A A' \\<rbrakk>\n           \\<Longrightarrow> corresTA (\\<lambda>s. C) rx ex A A'\"\n  by (clarsimp simp: corresXF_def)\n\nlemma corresTA_case_prod:\n \"\\<lbrakk> introduce_typ_abs_fn rx1;\n    introduce_typ_abs_fn rx2;\n    abstract_val (Q x) x (map_prod rx1 rx2) x';\n      \\<And>a b a' b'. \\<lbrakk> abs_var a rx1 a'; abs_var  b rx2 b' \\<rbrakk>\n                      \\<Longrightarrow>  corresTA (P a b) rx ex (M a b) (M' a' b') \\<rbrakk>  \\<Longrightarrow>\n    corresTA (\\<lambda>s. case x of (a, b) \\<Rightarrow> P a b s \\<and> Q (a, b)) rx ex (case x of (a, b) \\<Rightarrow> M a b) (case x' of (a, b) \\<Rightarrow> M' a b)\"\n  apply clarsimp\n  apply (rule corresXF_assume_pre)\n  apply (clarsimp simp: split_def map_prod_def)\n  done\n\nlemma abstract_val_case_prod:\n  \"\\<lbrakk> abstract_val True r (map_prod f g) r';\n       \\<And>a b a' b'. \\<lbrakk>  abs_var a f a'; abs_var  b g b' \\<rbrakk>\n                     \\<Longrightarrow> abstract_val (P a b) (M a b) h (M' a' b') \\<rbrakk>\n       \\<Longrightarrow> abstract_val (P (fst r) (snd r))\n            (case r of (a, b) \\<Rightarrow> M a b) h\n            (case r' of (a, b) \\<Rightarrow> M' a b)\"\n  apply (case_tac r, case_tac r')\n  apply (clarsimp simp: map_prod_def)\n  done\n\nlemma abstract_val_case_prod_fun_app:\n  \"\\<lbrakk> abstract_val True r (map_prod f g) r';\n       \\<And>a b a' b'. \\<lbrakk>  abs_var a f a'; abs_var b g b' \\<rbrakk>\n                     \\<Longrightarrow> abstract_val (P a b) (M a b s) h (M' a' b' s) \\<rbrakk>\n       \\<Longrightarrow> abstract_val (P (fst r) (snd r))\n            ((case r of (a, b) \\<Rightarrow> M a b) s) h\n            ((case r' of (a, b) \\<Rightarrow> M' a b) s)\"\n  apply (case_tac r, case_tac r')\n  apply (clarsimp simp: map_prod_def)\n  done\n\nlemma abstract_val_of_nat:\n  \"abstract_val (r \\<le> UWORD_MAX TYPE('a::len)) r unat (of_nat r :: 'a word)\"\n  by (clarsimp simp: unat_of_nat_eq UWORD_MAX_def le_to_less_plus_one)\n\nlemma abstract_val_of_int:\n  \"abstract_val (WORD_MIN TYPE('a::len) \\<le> r \\<and> r \\<le> WORD_MAX TYPE('a)) r sint (of_int r :: 'a signed word)\"\n  by (clarsimp simp: sint_of_int_eq WORD_MIN_def WORD_MAX_def)\n\nlemma abstract_val_tuple:\n  \"\\<lbrakk> abstract_val P a absL a';\n     abstract_val Q b absR b' \\<rbrakk> \\<Longrightarrow>\n         abstract_val (P \\<and> Q) (a, b) (map_prod absL absR) (a', b')\"\n  by clarsimp\n\nlemma abstract_val_func:\n   \"\\<lbrakk> abstract_val P a id a'; abstract_val Q b id b' \\<rbrakk>\n        \\<Longrightarrow>  abstract_val (P \\<and> Q) (f a b) id (f a' b')\"\n  by simp\n\nlemma abstract_val_conj:\n  \"\\<lbrakk> abstract_val P a id a';\n        abstract_val Q b id b' \\<rbrakk> \\<Longrightarrow>\n     abstract_val (P \\<and> (a \\<longrightarrow> Q)) (a \\<and> b) id (a' \\<and> b')\"\n  apply clarsimp\n  apply blast\n  done\n\nlemma abstract_val_disj:\n  \"\\<lbrakk> abstract_val P a id a';\n        abstract_val Q b id b' \\<rbrakk> \\<Longrightarrow>\n     abstract_val (P \\<and> (\\<not> a \\<longrightarrow> Q)) (a \\<or> b) id (a' \\<or> b')\"\n  apply clarsimp\n  apply blast\n  done\n\nlemma abstract_val_unwrap:\n  \"\\<lbrakk> introduce_typ_abs_fn f; abstract_val P a f b \\<rbrakk>\n        \\<Longrightarrow> abstract_val P a id (f b)\"\n  by simp\n\nlemma abstract_val_uint:\n  \"\\<lbrakk> introduce_typ_abs_fn unat; abstract_val P x unat x' \\<rbrakk>\n      \\<Longrightarrow> abstract_val P (int x) id (uint x')\"\n  by (clarsimp simp: uint_nat)\n\nlemma corresTA_L2_recguard:\n  \"corresTA (\\<lambda>s. P s) rx ex A A' \\<Longrightarrow>\n        corresTA \\<top> rx ex (L2_recguard m (L2_seq (L2_guard (\\<lambda>s. P s)) (\\<lambda>_. A))) (L2_recguard m A')\"\n  by (monad_eq simp: corresXF_def L2_defs split: sum.splits)\n\nlemma corresTA_recguard_0:\n    \"corresTA st rx ex (L2_recguard 0 A) C\"\n  by (clarsimp simp: L2_recguard_def corresXF_def)\n\nlemma abstract_val_lambda:\n   \"\\<lbrakk> \\<And>v. abstract_val (P v) (a v) id (a' v) \\<rbrakk> \\<Longrightarrow>\n           abstract_val (\\<forall>v. P v) (\\<lambda>v. a v) id (\\<lambda>v. a' v)\"\n  by auto\n\n(* Variable abstraction *)\n\nlemma abstract_val_abs_var [consumes 1]:\n  \"\\<lbrakk> abs_var a f a' \\<rbrakk> \\<Longrightarrow> abstract_val True a f a'\"\n  by (clarsimp simp: fun_upd_def split: if_splits)\n\nlemma abstract_val_abs_var_concretise  [consumes 1]:\n  \"\\<lbrakk> abs_var a A a'; introduce_typ_abs_fn A; valid_typ_abs_fn PA PC A (C :: 'a \\<Rightarrow> 'c)  \\<rbrakk>\n      \\<Longrightarrow> abstract_val (PC a) (C a) id a'\"\n  by (clarsimp simp: fun_upd_def split: if_splits)\n\nlemma abstract_val_abs_var_give_up [consumes 1]:\n  \"\\<lbrakk> abs_var a id a' \\<rbrakk> \\<Longrightarrow> abstract_val True (A a) A a'\"\n  by (clarsimp simp: fun_upd_def split: if_splits)\n\n(* Misc *)\n\nlemma len_of_word_comparisons [word_abs, L2opt]:\n  \"len_of TYPE(32) \\<le> len_of TYPE(32)\"\n  \"len_of TYPE(16) \\<le> len_of TYPE(32)\"\n  \"len_of TYPE( 8) \\<le> len_of TYPE(32)\"\n  \"len_of TYPE(16) \\<le> len_of TYPE(16)\"\n  \"len_of TYPE( 8) \\<le> len_of TYPE(16)\"\n  \"len_of TYPE( 8) \\<le> len_of TYPE( 8)\"\n  \"len_of TYPE(16) < len_of TYPE(32)\"\n  \"len_of TYPE( 8) < len_of TYPE(32)\"\n  \"len_of TYPE( 8) < len_of TYPE(16)\"\n\n  \"len_of TYPE('a::len signed) = len_of TYPE('a)\"\n  \"(len_of TYPE('a) = len_of TYPE('a)) = True\"\n  by auto\n\nlemma scast_ucast_simps [simp, L2opt]:\n  \"\\<lbrakk> len_of TYPE('b) \\<le> len_of TYPE('a); len_of TYPE('c) \\<le> len_of TYPE('b) \\<rbrakk> \\<Longrightarrow>\n         (scast (ucast (a :: 'a::len word) :: 'b::len word) :: 'c::len word) = ucast a\"\n  \"\\<lbrakk> len_of TYPE('c) \\<le> len_of TYPE('a); len_of TYPE('c) \\<le> len_of TYPE('b) \\<rbrakk> \\<Longrightarrow>\n         (scast (ucast (a :: 'a::len word) :: 'b::len word) :: 'c::len word) = ucast a\"\n  \"\\<lbrakk> len_of TYPE('a) \\<le> len_of TYPE('b); len_of TYPE('c) \\<le> len_of TYPE('b) \\<rbrakk> \\<Longrightarrow>\n         (scast (ucast (a :: 'a::len word) :: 'b::len word) :: 'c::len word) = ucast a\"\n  \"\\<lbrakk> len_of TYPE('a) \\<le> len_of TYPE('b) \\<rbrakk> \\<Longrightarrow>\n     (scast (scast (a :: 'a::len word) :: 'b::len word) :: 'c::len word) = scast a\"\n  \"\\<lbrakk> len_of TYPE('b) \\<le> len_of TYPE('a); len_of TYPE('c) \\<le> len_of TYPE('b) \\<rbrakk> \\<Longrightarrow>\n            (ucast (scast (a :: 'a::len word) :: 'b::len word) :: 'c::len word) = scast a\"\n  \"\\<lbrakk> len_of TYPE('c) \\<le> len_of TYPE('a); len_of TYPE('c) \\<le> len_of TYPE('b) \\<rbrakk> \\<Longrightarrow>\n     (ucast (scast (a :: 'a::len word) :: 'b::len word) :: 'c::len word) = scast a\"\n  \"\\<lbrakk> len_of TYPE('a) \\<le> len_of TYPE('b); len_of TYPE('c) \\<le> len_of TYPE('b) \\<rbrakk> \\<Longrightarrow>\n     (ucast (scast (a :: 'a::len word) :: 'b::len word) :: 'c::len word) = scast a\"\n  \"\\<lbrakk> len_of TYPE('c) \\<le> len_of TYPE('b) \\<rbrakk> \\<Longrightarrow>\n        (ucast (ucast (a :: 'a::len word) :: 'b::len word) :: 'c::len word) = ucast a\"\n  \"\\<lbrakk> len_of TYPE('a) \\<le> len_of TYPE('b) \\<rbrakk> \\<Longrightarrow>\n     (ucast (ucast (a :: 'a::len word) :: 'b::len word) :: 'c::len word) = ucast a\"\n  \"\\<lbrakk> len_of TYPE('a) \\<le> len_of TYPE('b) \\<rbrakk> \\<Longrightarrow>\n            (scast (scast (a :: 'a::len word) :: 'b::len word) :: 'c::len word) = scast a\"\n  by (auto simp: is_up is_down\n      scast_ucast_1 scast_ucast_3 scast_ucast_4\n      ucast_scast_1 ucast_scast_3 ucast_scast_4\n      scast_scast_a scast_scast_b\n      ucast_ucast_a ucast_ucast_b)\n\ndeclare len_signed [L2opt]\n\nlemmas [L2opt, polish] = zero_sle_ucast_up\n\nlemma zero_sle_ucast_WORD_MAX [L2opt, polish]:\n  \"(0 <=s ((ucast (b::('a::len) word)) :: ('a::len) signed word))\n                = (uint b \\<le> WORD_MAX (TYPE('a)))\"\n  by (clarsimp simp: WORD_MAX_def zero_sle_ucast)\n\nlemmas [L2opt, polish] =\n    is_up is_down unat_ucast_upcast sint_ucast_eq_uint\n\nlemmas [L2opt, polish] =\n    ucast_down_add scast_down_add\n    ucast_down_minus scast_down_minus\n    ucast_down_mult scast_down_mult\n\n(*\n * Setup word abstraction rules.\n *)\n\n(* Common word abstraction rules. *)\n\nlemmas [word_abs] =\n  corresTA_L2_gets\n  corresTA_L2_modify\n  corresTA_L2_throw\n  corresTA_L2_skip\n  corresTA_L2_fail\n  corresTA_L2_seq\n  corresTA_L2_seq_unit\n  corresTA_L2_catch\n  corresTA_L2_while\n  corresTA_L2_guard\n  corresTA_L2_condition\n  corresTA_L2_unknown\n  corresTA_L2_recguard\n  corresTA_case_prod\n  corresTA_L2_call_exec_concrete\n  corresTA_L2_call_exec_abstract\n  corresTA_L2_call'\n  corresTA_L2_call\n  corresTA_measure_call\n\nlemmas [word_abs] =\n  abstract_val_tuple\n  abstract_val_conj\n  abstract_val_disj\n  abstract_val_case_prod\n  abstract_val_trivial\n  abstract_val_of_int\n  abstract_val_of_nat\n\n  abstract_val_abs_var_give_up\n  abstract_val_abs_var_concretise\n  abstract_val_abs_var\n\nlemmas word_abs_base [word_abs] =\n  valid_typ_abs_fn_id [where 'a=\"'a::c_type\"]\n  valid_typ_abs_fn_id [where 'a=\"bool\"]\n  valid_typ_abs_fn_id [where 'a=\"c_exntype\"]\n  valid_typ_abs_fn_tuple\n  valid_typ_abs_fn_unit\n  valid_typ_abs_fn_sint\n  valid_typ_abs_fn_unat\n\n(*\n * Signed word abstraction rules: sword32 \\<rightarrow> int\n *)\n\nlemmas word_abs_sword32 =\n  abstract_val_signed_ops\n  abstract_val_scast\n  abstract_val_scast_upcast\n  abstract_val_scast_downcast\n  abstract_val_unwrap [where f=sint]\n  introduce_typ_abs_fn [where f=\"sint :: (sword32 \\<Rightarrow> int)\"]\n  introduce_typ_abs_fn [where f=\"sint :: (sword16 \\<Rightarrow> int)\"]\n  introduce_typ_abs_fn [where f=\"sint :: (sword8 \\<Rightarrow> int)\"]\n\n(*\n * Unsigned word abstraction rules: word32 \\<rightarrow> nat\n *)\n\nlemmas word_abs_word32 =\n  abstract_val_unsigned_ops\n  abstract_val_uint\n  abstract_val_ucast\n  abstract_val_ucast_upcast\n  abstract_val_ucast_downcast\n  abstract_val_unwrap [where f=unat]\n  introduce_typ_abs_fn [where f=\"unat :: (word32 \\<Rightarrow> nat)\"]\n  introduce_typ_abs_fn [where f=\"unat :: (word16 \\<Rightarrow> nat)\"]\n  introduce_typ_abs_fn [where f=\"unat :: (word8 \\<Rightarrow> nat)\"]\n\n(* 'a \\<rightarrow> 'a *)\nlemmas word_abs_default =\n  introduce_typ_abs_fn [where f=\"id :: ('a::c_type \\<Rightarrow> 'a)\"]\n  introduce_typ_abs_fn [where f=\"id :: (bool \\<Rightarrow> bool)\"]\n  introduce_typ_abs_fn [where f=\"id :: (c_exntype \\<Rightarrow> c_exntype)\"]\n  introduce_typ_abs_fn [where f=\"id :: (unit \\<Rightarrow> unit)\"]\n  introduce_typ_abs_fn_tuple\n\nend\n", "meta": {"author": "8l", "repo": "AutoCorres", "sha": "47d800912e6e0d9b1b8009660e8b20c785a2ea8b", "save_path": "github-repos/isabelle/8l-AutoCorres", "path": "github-repos/isabelle/8l-AutoCorres/AutoCorres-47d800912e6e0d9b1b8009660e8b20c785a2ea8b/autocorres/WordAbstract.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278602705731, "lm_q2_score": 0.8128673246376009, "lm_q1q2_score": 0.7172967739638234}}
{"text": "\\<^marker>\\<open>creator Bernhard P\u00f6ttinger\\<close>\n\nchapter \\<open>Flow Graph\\<close>\ntheory Flow_Graph\n  imports Main Auxiliary\nbegin\n\nparagraph \\<open>Summary\\<close>\ntext \\<open>This theory implements the basic data structure used by the Flow Framework\n@{cite krishna20}: flow graphs.\\<close>\n\nsection \\<open>Flow Graph\\<close>\n\nsubsection \\<open>Preliminary Flow Graphs\\<close>\n\ntext \\<open>We start with the definition of a preliminary type for flow graphs.\nPreliminary flow graphs (N,e,f) consist of a set of nodes N, a function e representing directed\nedges (e.g. e x y represents the edge from x to y), and a function f labeling all nodes with\ntheir so-called flow.\nAs e and f both are only defined on N this representation is not unique.\nWe will lift this type to a quotient type to obtain a unique representation.\\<close>\n\ntype_synonym ('n,'m) fg' = \"'n set \\<times> ('n \\<Rightarrow> 'n \\<Rightarrow> 'm \\<Rightarrow> 'm) \\<times> ('n \\<Rightarrow> 'm)\"\n\ntext \\<open>We define the notion of equality for preliminary flow graphs.\\<close>\n\ndefinition fg'_eq :: \"('n,'m) fg' \\<Rightarrow> ('n,'m) fg' \\<Rightarrow> bool\" where\n  \"fg'_eq \\<equiv> \\<lambda>(N1,e1,f1) (N2,e2,f2). N1 = N2 \\<and> (e1 = e2 on N1) \\<and> (f1 = f2 on N1)\"\n\nlemma fg'_eqI:\n  assumes \"N1 = N2\" \"e1 = e2 on N1\" \"f1 = f2 on N1\"\n  shows \"fg'_eq (N1,e1,f1) (N2,e2,f2)\"\n  using assms unfolding fg'_eq_def by simp\n\ntext \\<open>The central ingredient to define valid flow graphs: the flow equation\n(@{cite \\<open>p. 313\\<close> krishna20}).\nThe flow equation describes if a label function f is a solution to an equation system\ninduced by a graph (N,e). If there exists an i such that f is a solution to the flow equation\nthen (N,e,f) is a valid flow graph. Function i is called inflow.\\<close>\n\ndefinition\n  flow_eq' :: \"('n,'m) fg' \\<Rightarrow> ('n \\<Rightarrow> 'm::cancel_comm_monoid_add) \\<Rightarrow> bool\"\nwhere\n  \"flow_eq' \\<equiv> \\<lambda>(N,e,f) i. \\<forall>n \\<in> N. f n = i n + (\\<Sum>n' \\<in> N. e n' n (f n'))\"\n\nlemma flow_eq'_eq: \"fg'_eq h1 h2 \\<Longrightarrow> flow_eq' h1 i \\<longleftrightarrow> flow_eq' h2 i\"\n  unfolding fg'_eq_def flow_eq'_def\n  by auto\n\ntext \\<open>For historical reasons we also keep this notation for flow equations:\\<close>\n\ndefinition\n  flow_eq2'\n  :: \"'n set \\<Rightarrow> ('n \\<Rightarrow> 'n \\<Rightarrow> 'm \\<Rightarrow> 'm) \\<Rightarrow> ('n \\<Rightarrow> 'm) \\<Rightarrow> ('n \\<Rightarrow> 'm::cancel_comm_monoid_add) \\<Rightarrow> bool\"\nwhere\n  \"flow_eq2' N e f i = flow_eq' (N,e,f) i\"\n\ntext \\<open>A flow graph is valid iff. there is an inflow i such that f solves the flow equation.\nFurthermore, the domain of the flow graph must be finite. (@{cite \\<open>def. 3\\<close> krishna20})\\<close>\n\ndefinition def_fg' :: \"('n,'m::cancel_comm_monoid_add) fg' \\<Rightarrow> bool\" where\n  \"def_fg' \\<equiv> \\<lambda>(N,e,f). (\\<exists>i. flow_eq' (N,e,f) i) \\<and> finite N\"\n\ntext \\<open>Before we can define the final flow graph type using a quotient type,\nwe have to lift preliminary flow graphs to the option type in order to obtain a representation\nfor invalid flow graphs in the quotient type.\\<close>\n\ntext \\<open>The notion of equality for is lifted canonically:\\<close>\n\ndefinition fg'_option_eq\n  :: \"('n,'m) fg' option \\<Rightarrow> ('n,'m::cancel_comm_monoid_add) fg' option \\<Rightarrow> bool\"\nwhere\n  \"fg'_option_eq \\<equiv> \\<lambda>h1 h2. \n    case (h1,h2) of\n       (Some h1', Some h2') \\<Rightarrow> if \\<not>def_fg' h1' \\<and> \\<not>def_fg' h2' then True else\n                               if def_fg' h1' \\<and> def_fg' h2' then fg'_eq h1' h2' else\n                               False\n     | (None, None) \\<Rightarrow> True\n     | (Some h1', None) \\<Rightarrow> \\<not>def_fg' h1'\n     | (None, Some h2') \\<Rightarrow> \\<not>def_fg' h2'\"\n\nsubsection \\<open>Flow Graph\\<close>\n\ntext \\<open>Defining the actual type for flow graphs using our notion of equality.\n(@{cite \\<open>def. 3\\<close> krishna20})\\<close>\n\nquotient_type (overloaded) ('n,'m) fg =\n  \"('n,'m::cancel_comm_monoid_add) fg' option\" / fg'_option_eq\n    apply (rule equivpI)\n  subgoal by (auto intro: reflpI simp: fg'_option_eq_def fg'_eq_def split: option.splits)\n  subgoal by (auto intro: sympI simp: fg'_option_eq_def fg'_eq_def split: option.splits)\n  subgoal by (rule transpI, auto simp: fg'_option_eq_def fg'_eq_def split: option.splits if_splits)\n  done\n\ntext \\<open>A constructor function that allows us to define flow graphs without mentioning Some.\\<close>\n\nlift_definition fg\n  :: \"'n set \\<Rightarrow> ('n \\<Rightarrow> 'n \\<Rightarrow> 'm \\<Rightarrow> 'm) \\<Rightarrow> ('n \\<Rightarrow> 'm) \\<Rightarrow>\n      ('n,'m::cancel_comm_monoid_add) fg\"\n  is \"\\<lambda>N e f. Some (N,e,f)\" .\n\ntext \\<open>Accessor functions that provide us with the components of flow graphs.\nFor invalid flow graphs we obtain default values. edge function and flow function are set to\ndefault values outside the domain of their flow graph.\\<close>\n\nlift_definition dom_fg :: \"('n,'m::cancel_comm_monoid_add) fg \\<Rightarrow> 'n set\"\n  is \"\\<lambda>h. case h of Some (N,e,f) \\<Rightarrow> if def_fg' (N,e,f) then N else {} | _ \\<Rightarrow> {}\"\n  unfolding fg'_option_eq_def def_fg'_def fg'_eq_def\n  by (auto split: option.splits if_splits)\n\nlift_definition flow_fg :: \"('n,'m::cancel_comm_monoid_add) fg \\<Rightarrow> ('n \\<Rightarrow> 'm)\"\n  is \"\\<lambda>h. case h of\n    Some (N,e,f) \\<Rightarrow> if def_fg' (N,e,f) then restrict N 0 f else (\\<lambda>_. 0) |\n    None \\<Rightarrow> (\\<lambda>_. 0)\"\n  unfolding fg'_option_eq_def fg'_eq_def\n  by (auto split: option.splits)\n\nlift_definition edge_fg :: \"('n,'m::cancel_comm_monoid_add) fg \\<Rightarrow> ('n \\<Rightarrow> 'n \\<Rightarrow> 'm \\<Rightarrow> 'm)\"\n  is \"\\<lambda>h. case h of\n    Some (N,e,f) \\<Rightarrow> if def_fg' (N,e,f) then restrict N (\\<lambda>_ _. 0) e else (\\<lambda>_ _ _. 0) |\n    None \\<Rightarrow> (\\<lambda>_ _ _. 0)\"\n  unfolding fg'_option_eq_def fg'_eq_def\n  by (auto split: option.splits)\n\nlemma dom_fg_finite[simp]: \"finite (dom_fg h)\"\n  apply (transfer)\n  unfolding def_fg'_def\n  by (auto split: option.splits)\n\ntext \\<open>Lift the flow equation to the actual flow graph type. (@{cite \\<open>p. 313\\<close> krishna20})\\<close>\n\nlift_definition flow_eq :: \"('n,'m) fg \\<Rightarrow> ('n \\<Rightarrow> 'm :: cancel_comm_monoid_add) \\<Rightarrow> bool\" is\n  \"\\<lambda>h i. case h of Some h' \\<Rightarrow> if def_fg' h' then flow_eq' h' i else False | _ \\<Rightarrow> False\"\n  unfolding fg'_option_eq_def fg'_eq_def\n  apply (auto split: option.splits if_splits)\n  subgoal for e1 f1 N1 e2 f2\n    using flow_eq'_eq[OF fg'_eqI[of N1 N1 e1 e2 f1 f2]] by auto\n  done\n\nlemma flow_eq_outside_irrelevant:\n  assumes \"flow_eq h i\"\n  shows \"flow_eq h (restrict (dom_fg h) 0 i)\"\n  using assms\n  apply transfer\n  by (auto split: option.splits if_splits simp: def_fg'_def flow_eq'_def)\n\ntext \\<open>Notation for the invalid flow graph:\\<close>\n\ninstantiation fg :: (type,type) bot\nbegin\nlift_definition bot_fg :: \"('n,'m::cancel_comm_monoid_add) fg\" is None .\ninstance ..\nend\n\nlemma dom_fg_bot[simp]: \"dom_fg bot = {}\"\n  apply transfer unfolding bot_fg_def dom_fg_def by simp\n\ntext \\<open>Some simplification rules for accessor functions and constructor.\\<close>\n\nlemma dom_fg_fg[simp]:\n  \"fg N e f \\<noteq> bot \\<Longrightarrow> dom_fg (fg N e f) = N\"\n  apply transfer by (auto split: option.splits simp: fg'_option_eq_def)\n\nlemma edge_fg_fg[simp]:\n  \"fg N e f \\<noteq> bot \\<Longrightarrow> edge_fg (fg N e f) = restrict N (\\<lambda>_ _. 0) e\"\n  apply transfer by (auto split: option.splits simp: fg'_option_eq_def)\n\nlemma flow_fg_fg[simp]:\n  \"fg N e f \\<noteq> bot \\<Longrightarrow> flow_fg (fg N e f) = restrict N 0 f\"\n  apply transfer by (auto split: option.splits simp: fg'_option_eq_def)\n\nlemma fg_restrict_components[simp]:\n  assumes \"a \\<noteq> bot\"\n  shows \"fg (dom_fg a) (restrict (dom_fg a) x0 (edge_fg a)) (restrict (dom_fg a) x1 (flow_fg a)) = a\"\n  using assms\n  apply transfer\n  by (auto split: option.splits if_splits\n      simp: fg'_option_eq_def def_fg'_def fg'_eq_def flow_eq'_def)\n\nlemma fg_components[simp]:\n  \"a \\<noteq> bot \\<Longrightarrow> fg (dom_fg a) (edge_fg a) (flow_fg a) = a\"\n  apply transfer\n  by (auto split: option.splits if_splits\n      simp: fg'_option_eq_def def_fg'_def fg'_eq_def flow_eq'_def)\n\ntext \\<open>Part 1 from @{cite \\<open>lemma 1\\<close> krishna20}: There exists an inflow for valid flow graphs.\nAs we extended the notion of flow graphs with validity of flow graphs we add the additional\nassumption that h is valid.\\<close>\n\nlemma flow_eq_exists:\n  assumes \"h \\<noteq> bot\"\n  shows \"\\<exists>i. flow_eq h i\"\n  using assms\n  apply transfer by (auto simp: fg'_option_eq_def def_fg'_def split: option.splits if_splits)\n\ntext \\<open>Part 2 from @{cite \\<open>lemma 1\\<close> krishna20}: The inflow of flow graphs is unique\\<close>\n\nlemma flow_eq_unique:\n  assumes \"flow_eq h i1\" \"flow_eq h i2\"\n  shows \"i1 = i2 on (dom_fg h)\"\n  using assms\n  apply transfer by (auto split: option.splits simp: flow_eq'_def)\n\nlemma pos_flow_nbot:\n  assumes \"flow_fg h x \\<noteq> 0\"\n  shows \"h \\<noteq> bot\"\n  using assms unfolding flow_fg_def bot_fg_def apply (auto split: option.splits if_splits)\n  by (metis (no_types, lifting) assms flow_fg.abs_eq option.simps(4))\n\nlemma pos_flow_dom:\n  assumes \"flow_fg h x \\<noteq> 0\"\n  shows \"x \\<in> dom_fg h\"\n  using assms unfolding flow_fg_def bot_fg_def apply (auto split: option.splits if_splits)\n  by (metis pos_flow_nbot assms fg_components flow_fg_fg)\n\ntext \\<open>Determining the validity of constructed flow graphs:\\<close>\n\nlemma fgI:\n  assumes \"f = (\\<lambda>n. i n + (\\<Sum>n' \\<in> N. e n' n (f n'))) on N\" \"finite N\"\n  shows \"fg N e f \\<noteq> bot\"\n  using assms\n  apply transfer\n  by (auto simp: fg'_option_eq_def def_fg'_def flow_eq'_def)\n\nlemma fgI2:\n  assumes \"flow_eq (fg N e f) i\" \"finite N\"\n  shows \"fg N e f \\<noteq> bot\"\n  using assms\n  apply transfer\n  by (auto simp: fg'_option_eq_def def_fg'_def flow_eq'_def split: if_splits)\n\nlemma flow_eqI:\n  assumes \"f = (\\<lambda>n. i n + (\\<Sum>n' \\<in> N. e n' n (f n'))) on N\" \"finite N\"\n  shows \"flow_eq (fg N e f) i\"\n  using assms\n  apply transfer\n  by (auto simp add: flow_eq'_def def_fg'_def)\n\ntext \\<open>Gain access to flow equation for valid flow graphs:\\<close>\n\nlemma fgE:\n  assumes \"h \\<noteq> bot\"\n  shows \"(\\<exists>i. finite (dom_fg h) \\<and> flow_fg h =\n    (\\<lambda>n. i n + (\\<Sum>n' \\<in> dom_fg h. edge_fg h n' n (flow_fg h n'))) on dom_fg h)\"\n  using assms\n  by (transfer, auto simp: fg'_option_eq_def def_fg'_def flow_eq'_def\n      split: option.splits if_splits)\n\nlemma fgE': \n  \"flow_eq h i \\<Longrightarrow> \\<forall>n \\<in> dom_fg h.\n    flow_fg h n = i n + (\\<Sum>n' \\<in> dom_fg h. edge_fg h n' n (flow_fg h n'))\"\n  by (transfer, auto simp: fg'_option_eq_def def_fg'_def flow_eq'_def\n      split: option.splits if_splits)\n\nlemma fgE'': \n  \"flow_eq (fg N e f) i \\<Longrightarrow> N \\<noteq> {} \\<Longrightarrow> \\<forall>n \\<in> N. f n = i n + (\\<Sum>n' \\<in> N. e n' n (f n'))\"\n  by (transfer, auto split: option.splits if_splits simp: flow_eq'_def)\n\ntext \\<open>Determine equality of flow graphs:\\<close>\n\nlemma fg_eqI:\n  assumes \"h1 \\<noteq> bot\" \"h2 \\<noteq> bot\" \"dom_fg h1 = dom_fg h2\"\n    \"edge_fg h1 = edge_fg h2 on dom_fg h1\" \"flow_fg h1 = flow_fg h2 on dom_fg h2\"\n  shows \"h1 = h2\"\n  using assms\n  apply transfer\n  by (auto split: option.splits simp: fg'_option_eq_def fg'_eq_def)\n\nlemma fg_eqI2:\n  assumes \"h1 \\<noteq> bot \\<Longrightarrow> h1 = h2\" \"h2 \\<noteq> bot \\<Longrightarrow> h1 = h2\"\n  shows \"h1 = h2\"\n  using assms by auto\n\nlemma fg_cong:\n  assumes \"N1 = N2\" \"e1 = e2 on N1\" \"f1 = f2 on N1\"\n  shows \"fg N1 e1 f1 = fg N2 e2 f2\"\n  using assms\n  apply transfer\n  by (auto simp: fg'_option_eq_def fg'_eq_def def_fg'_def flow_eq'_def)\n\nlemma fg_eqD:\n  assumes \"h1 = h2\"\n  shows \"dom_fg h1 = dom_fg h2 \\<and> edge_fg h1 = edge_fg h2 on dom_fg h1 \\<and>\n    flow_fg h1 = flow_fg h2 on dom_fg h2\"\n  using assms\n  unfolding edge_fg_def dom_fg_def flow_fg_def\n  by auto\n\nsubsection \\<open>Flow Graphs are Cancellative Monoids\\<close>\n\ninstantiation fg :: (type,cancel_comm_monoid_add) comm_monoid_add\nbegin\n\ntext \\<open>The unit flow graph is the flow graph consisting of no nodes. @{cite krishna20}\\<close>\n\ndefinition zero_fg where\n  \"zero_fg \\<equiv> fg {} (\\<lambda>_ _ _. 0) (\\<lambda>_. 0)\"\n\nlemma zero_fg_nbot [simp]: \"0 \\<noteq> (bot :: ('n,'m :: cancel_comm_monoid_add) fg)\"\n  unfolding zero_fg_def bot_fg_def fg_def   apply (auto)\n  by (auto simp: fg.abs_eq_iff fg'_option_eq_def def_fg'_def flow_eq'_def)\n\nlemma dom_fg_zero_fg [simp]: \"dom_fg 0 = {}\"\n  unfolding zero_fg_def using dom_fg_fg by force\n\ntext \\<open>Addition for flow graphs @{cite \\<open>def. 4\\<close> krishna20} requires the summands to be disjoint.\nThe edge and flow functions are merely the combination of the two summand's functions.\nWe have to additionally take validity into account in our definition.\\<close>\n\ndefinition\n  plus_fg :: \"('n,'m) fg \\<Rightarrow> ('n,'m) fg \\<Rightarrow> ('n,'m :: cancel_comm_monoid_add) fg\"\nwhere\n  \"plus_fg h1 h2 \\<equiv>\n    let N = dom_fg h1 \\<union> dom_fg h2;\n        e = combine (dom_fg h1) (dom_fg h2) (\\<lambda>_ _. 0) (edge_fg h1) (edge_fg h2);\n        f = combine (dom_fg h1) (dom_fg h2)        0  (flow_fg h1) (flow_fg h2) in\n    if h1 \\<noteq> bot \\<and> h2 \\<noteq> bot \\<and> dom_fg h1 \\<inter> dom_fg h2 = {}\n      then fg N e f\n      else bot\"\n\nlemma plus_fg_fg:\n  assumes \"fg N1 e1 f1 \\<noteq> bot\" \"fg N2 e2 f2 \\<noteq> bot\" \"N1 \\<inter> N2 = {}\"\n  shows \"fg N1 e1 f1 + fg N2 e2 f2 =\n    fg (N1 \\<union> N2) (combined N1 N2 (\\<lambda>_ _. 0) e1 e2) (combined N1 N2 0 f1 f2)\"\nproof -\n  have *:\n    \"fg (N1 \\<union> N2)\n      (combined N1 (dom_fg (fg N2 e2 f2)) (\\<lambda>_ _. 0) (edge_fg (fg N1 e1 f1)) (edge_fg (fg N2 e2 f2)))\n      (combined N1 (dom_fg (fg N2 e2 f2)) 0 (flow_fg (fg N1 e1 f1)) (flow_fg (fg N2 e2 f2))) =\n     fg (N1 \\<union> N2) (combined N1 N2 (\\<lambda>_ _. 0) e1 e2) (combined N1 N2 0 f1 f2)\"\n    unfolding combined_def\n    by (rule fg_cong, auto simp: assms)\n  show ?thesis\n    using assms *\n    unfolding plus_fg_def combined_def\n    by (auto simp: Let_def)\nqed\n\nlemma plus_fg_fg':\n  assumes \"fg N1 e1 f1 \\<noteq> bot\" \"fg N2 e2 f2 \\<noteq> bot\" \"N1 \\<inter> N2 = {}\" \"N1 \\<union> N2 = N\"\n      \"e = e1 on N1\" \"e = e2 on N2\" \"f = f1 on N1\" \"f = f2 on N2\"\n    shows \"fg N1 e1 f1 + fg N2 e2 f2 = fg N e f\"\nproof -\n  have \"fg N1 e1 f1 + fg N2 e2 f2 =\n    fg (N1 \\<union> N2) (combined N1 N2 (\\<lambda>_ _. 0) e1 e2) (combined N1 N2 0 f1 f2)\"\n    using plus_fg_fg assms by simp\n  also have \"... = fg N e f\"\n    apply (rule fg_cong) unfolding combined_def using assms by auto\n  finally show ?thesis .\nqed\n\nlemma plus_fg_bot_bot[simp]: \"bot + h = bot\" \"h + bot = (bot :: ('n,'m::cancel_comm_monoid_add) fg)\"\n  unfolding bot_fg_def plus_fg_def by (auto split: option.splits)\n\nlemma def_fg_zero_fg[simp]:\n  \"0 \\<noteq> (bot :: ('a,'b) fg)\"\n  by auto\n\nlemma plus_fg_ops_exist:\n  \"h1 + h2 \\<noteq> bot \\<Longrightarrow> h1 \\<noteq> bot \\<and> h2 \\<noteq> (bot :: ('n,'m :: cancel_comm_monoid_add) fg)\"\n  unfolding plus_fg_def\n  by auto\n\nlemma plus_fg_dom_un[simp]:\n  \"h1 + h2 \\<noteq> bot \\<Longrightarrow> dom_fg (h1 + h2) = dom_fg h1 \\<union> dom_fg h2\"\n  unfolding plus_fg_def\n  by (auto simp: Let_def split: if_splits)\n\nlemma plus_fg_dom_disj[simp]:\n  \"h1 + h2 \\<noteq> bot \\<Longrightarrow> dom_fg h1 \\<inter> dom_fg h2 = {}\"\n  unfolding plus_fg_def\n  by (auto simp: Let_def split: if_splits)\n\nlemma flow_fg_plus_fg_on1:\n  \"h1 + h2 \\<noteq> bot \\<Longrightarrow> flow_fg (h1 + h2) = flow_fg h1 on (dom_fg h1)\"\n  unfolding plus_fg_def\n  by (auto simp: Let_def split: if_splits)\n\nlemma flow_fg_plus_fg_on2:\n  \"h1 + h2 \\<noteq> bot \\<Longrightarrow> flow_fg (h1 + h2) = flow_fg h2 on (dom_fg h2)\"\n  unfolding plus_fg_def\n  by (auto simp: Let_def split: if_splits)\n\nlemma flow_fg_plus_fg_on1':\n  \"h1 + h2 \\<noteq> bot \\<Longrightarrow> x \\<in> dom_fg h1 \\<Longrightarrow> flow_fg (h1 + h2) x = flow_fg h1 x\"\n  unfolding plus_fg_def\n  by (auto simp: Let_def split: if_splits)\n\nlemma flow_fg_plus_fg_on2':\n  \"h1 + h2 \\<noteq> bot \\<Longrightarrow> x \\<in> dom_fg h2 \\<Longrightarrow> flow_fg (h1 + h2) x = flow_fg h2 x\"\n  unfolding plus_fg_def\n  by (auto simp: Let_def split: if_splits)\n\nlemma edge_fg_plus_fg_on1:\n  \"h1 + h2 \\<noteq> bot \\<Longrightarrow> edge_fg (h1 + h2) = edge_fg h1 on (dom_fg h1)\"\n  unfolding plus_fg_def\n  by (auto simp: Let_def split: if_splits)\n\nlemma edge_fg_plus_fg_on2:\n  \"h1 + h2 \\<noteq> bot \\<Longrightarrow> edge_fg (h1 + h2) = edge_fg h2 on (dom_fg h2)\"\n  unfolding plus_fg_def\n  by (auto simp: Let_def split: if_splits)\n\nlemma edge_fg_plus_fg_on1':\n  \"h1 + h2 \\<noteq> bot \\<Longrightarrow> x \\<in> dom_fg h1 \\<Longrightarrow> edge_fg (h1 + h2) x = edge_fg h1 x\"\n  unfolding plus_fg_def\n  by (auto simp: Let_def split: if_splits)\n\nlemma edge_fg_plus_fg_on2':\n  \"h1 + h2 \\<noteq> bot \\<Longrightarrow> x \\<in> dom_fg h2 \\<Longrightarrow> edge_fg (h1 + h2) x = edge_fg h2 x\"\n  unfolding plus_fg_def\n  by (auto simp: Let_def split: if_splits)\n\nlemma flow_fg_zero_outside_dom:\n  \"flow_fg h = (\\<lambda>_. 0) on (-dom_fg h)\"\n  unfolding plus_fg_def flow_fg_def dom_fg_def\n  by (auto simp: Let_def split: option.splits)\n\nlemma edge_fg_0_outside_dom:\n  \"x \\<in> -dom_fg h \\<Longrightarrow> h \\<noteq> bot \\<Longrightarrow> edge_fg h x = (\\<lambda> _ _. 0)\"\n  by (transfer, auto split: option.splits)\n\nlemma flow_fg_0_outside_dom:\n  \"x \\<in> -dom_fg h \\<Longrightarrow> h \\<noteq> bot \\<Longrightarrow> flow_fg h x = 0\"\n  by (transfer, auto split: option.splits)\n\ntext \\<open>@{text split_fg} enables us to decompose a valid flow graph into a sum of valid flow graphs.\nThis lemma significantly simplifies the proof of @{text plus_fg_assoc} as we have to decompose\n(a + b) + c there, this lemma and its existential quantification saves us from stating the\nquite verbose decomposition terms manually.\\<close>\n\nlemma split_fg:\n  assumes \"h \\<noteq> bot\" \"dom_fg h = N1 \\<union> N2\" \"N1 \\<inter> N2 = {}\"\n  shows \"\\<exists>h1 h2. h = h1 + h2 \\<and> h1 \\<noteq> bot \\<and> h2 \\<noteq> bot \\<and>\n    dom_fg h1 = N1 \\<and> dom_fg h2 = N2 \\<and>\n    edge_fg h = edge_fg h1 on N1 \\<and> edge_fg h = edge_fg h2 on N2 \\<and>\n    flow_fg h = flow_fg h1 on N1 \\<and> flow_fg h = flow_fg h2 on N2\"\nproof -\n  obtain i where *: \"flow_eq h i\" using assms(1) flow_eq_exists by auto\n  have \"finite (dom_fg h)\" using assms(1) by simp\n  hence **: \"finite N1\" \"finite N2\" using assms(2) by auto\n\n  let ?i1 = \"\\<lambda>n. if n \\<in> N1 then i n + (\\<Sum>n'\\<in>N2. edge_fg h n' n (flow_fg h n')) else 0\"\n  let ?i2 = \"\\<lambda>n. if n \\<in> N2 then i n + (\\<Sum>n'\\<in>N1. edge_fg h n' n (flow_fg h n')) else 0\"\n  let ?f = \"flow_fg h\" let ?e = \"edge_fg h\"\n\n  have X1: \"fg N1 ?e ?f \\<noteq> bot\"\n  proof (rule fgI)\n    show \"?f = \\<lambda>x. ?i1 x + (\\<Sum>n'\\<in>N1. ?e n' x (?f n')) on N1\"\n    proof\n      fix n assume \"n\\<in>N1\"\n      then have \"?f n = i n + (\\<Sum>n'\\<in>dom_fg h. ?e n' n (?f n'))\"\n        using assms `n\\<in>N1` * fgE'[of h i] by simp\n      thus \"?f n = ?i1 n + (\\<Sum>n'\\<in>N1. ?e n' n (?f n'))\"\n        using assms sum.union_disjoint  * ** \\<open>n \\<in> N1\\<close>\n        by (auto simp: Un_commute algebra_simps)\n    qed\n    show \"finite N1\" using ** by simp\n  qed\n\n  have X2: \"fg N2 ?e ?f \\<noteq> bot\"\n  proof (rule fgI)\n    show \"?f = \\<lambda>x. ?i2 x + (\\<Sum>n'\\<in>N2. ?e n' x (?f n')) on N2\"\n    proof\n      fix n assume \"n\\<in>N2\"\n      show \"?f n = ?i2 n + (\\<Sum>n'\\<in>N2. ?e n' n (?f n'))\"\n      proof -\n        have \"?f n = i n + (\\<Sum>n'\\<in>dom_fg h. ?e n' n (?f n'))\"\n          using assms `n\\<in>N2` * fgE'[of h i] by simp\n        thus ?thesis\n          using assms sum.union_disjoint[of N2 N1 \"\\<lambda>n'. ?e n' n (?f n')\"] * ** \\<open>n \\<in> N2\\<close>\n          by (auto simp: Un_commute algebra_simps)\n      qed\n    qed\n\n    show \"finite N2\"\n      using ** by simp\n  qed\n\n  have *: \"fg N1 ?e ?f + fg N2 ?e ?f = h\"\n    using plus_fg_fg' X1 X2 fg_components[of h] assms by metis\n\n  show ?thesis\n    apply (rule exI[where x=\"fg N1 ?e ?f\"])\n    apply (rule exI[where x=\"fg N2 ?e ?f\"])\n    using X1 X2 * assms by simp\nqed\n\nlemma plus_fg_assoc:\n  fixes a b c :: \"('a,'b :: cancel_comm_monoid_add) fg\"\n  assumes \"a + b + c \\<noteq> bot\"\n  shows \"a + b + c = a + (b + c)\"\nproof -\n  let ?h = \"a + b + c\"\n  let ?Na = \"dom_fg a\"\n  let ?Nb = \"dom_fg b\"\n  let ?Nc = \"dom_fg c\"\n\n  (* Exploit split_fg to obtain exactly the parts required by the proof and then\n    show the equality between those parts and the actual parts. *)\n\n  have nbot: \"a + b + c \\<noteq> bot\" \"a + b \\<noteq> bot\" \"a \\<noteq> bot\" \"b \\<noteq> bot\" \"c \\<noteq> bot\"\n    using assms by auto\n\n  have dom: \"dom_fg (a + b) \\<inter> ?Nc = {}\" \"?Na \\<inter> ?Nc = {}\" \"?Na \\<inter> ?Nb = {}\" \"?Nb \\<inter> ?Nc = {}\"\n    \"dom_fg (a + b + c) = dom_fg (a + b) \\<union> ?Nc\" \"dom_fg (a + b) = ?Na \\<union> ?Nb\"\n    using nbot plus_fg_dom_disj[of \"a + b\" c] by auto\n\n  then have \"dom_fg (a + b + c) = ?Na \\<union> (?Nb \\<union> ?Nc)\" \"?Na \\<inter> (?Nb \\<union> ?Nc) = {}\"\n    using dom by blast+\n\n  then obtain h1 h2 where *: \"a + b + c = h1 + h2\" \"dom_fg h1 = ?Na\" \"dom_fg h2 = ?Nb \\<union> ?Nc\"\n     \"edge_fg ?h = edge_fg h1 on ?Na\" \"edge_fg ?h = edge_fg h2 on ?Nb \\<union> ?Nc\"\n     \"flow_fg ?h = flow_fg h1 on ?Na\" \"flow_fg ?h = flow_fg h2 on ?Nb \\<union> ?Nc\"\n     \"h1 \\<noteq> bot\" \"h2 \\<noteq> bot\"\n    using split_fg[of ?h ?Na \"?Nb \\<union> ?Nc\"] assms by blast\n\n  then obtain h21 h22 where **: \"h2 = h21 + h22\" \"dom_fg h21 = ?Nb\" \"dom_fg h22 = ?Nc\"\n    \"edge_fg h2 = edge_fg h21 on ?Nb\" \"edge_fg h2 = edge_fg h22 on ?Nc\"\n    \"flow_fg h2 = flow_fg h21 on ?Nb\" \"flow_fg h2 = flow_fg h22 on ?Nc\"\n    \"h21 \\<noteq> bot\" \"h22 \\<noteq> bot\"\n    using split_fg[of h2 ?Nb ?Nc] dom * by blast\n\n  have ***: \"edge_fg ?h = edge_fg a on ?Na\" \"flow_fg ?h = flow_fg a on ?Na\"\n      \"edge_fg ?h = edge_fg b on ?Nb\" \"flow_fg ?h = flow_fg b on ?Nb\"\n      \"edge_fg ?h = edge_fg c on ?Nc\" \"flow_fg ?h = flow_fg c on ?Nc\"\n    using edge_fg_plus_fg_on1 edge_fg_plus_fg_on2\n          flow_fg_plus_fg_on1 flow_fg_plus_fg_on2 nbot by simp_all\n\n  have \"h1 = a\"\n    apply (rule fg_eqI) using nbot * ** *** by simp_all\n  moreover have \"h21 = b\"\n    apply (rule fg_eqI) using nbot * ** *** by simp_all\n  moreover have \"h22 = c\"\n    apply (rule fg_eqI) using nbot * ** *** by simp_all\n  ultimately show ?thesis\n    using * ** by simp\nqed\n\nlemma plus_fg_comm:\n  fixes a b :: \"('a,'b :: cancel_comm_monoid_add) fg\"\n  shows \"a + b = b + a\"\n  unfolding plus_fg_def\n  by (auto simp: Let_def Un_commute split: if_splits)\n\ninstance\nproof (standard, goal_cases)\n  case (1 a b c)\n  then show ?case\n  proof (rule fg_eqI2, goal_cases)\n    case 1\n    then show ?case\n      using plus_fg_assoc by simp\n  next\n    case 2\n    \\<comment> \\<open>derive second direction from first direction of associativity and commutativity\\<close>\n    then have \"a + (b + c) = (b + c) + a\" using plus_fg_comm by simp\n    then have \"a + (b + c) = b + (c + a)\" using 2 plus_fg_assoc by simp\n    then have \"a + (b + c) = (c + a) + b\" using plus_fg_comm by simp\n    then have \"a + (b + c) = c + (a + b)\" using 2 plus_fg_assoc by simp\n    then show ?case using plus_fg_comm by simp\n  qed\nnext\n  case (2 a b)\n  then show ?case\n    using plus_fg_comm by simp\nnext\n  case (3 a)\n  then show ?case\n    unfolding plus_fg_def\n    by (cases \"a = bot\", auto simp: Let_def split: if_splits)\nqed\n\nend\n\nlemma split_sum:\n  fixes f :: \"'n \\<Rightarrow> ('n,'m::cancel_comm_monoid_add) fg\"\n  assumes \"sum f (xs \\<union> ys) \\<noteq> bot\" \"xs \\<inter> ys = {}\" \"finite xs\" \"finite ys\"\n  shows \"sum f (xs \\<union> ys) = sum f xs + sum f ys \\<and> sum f xs \\<noteq> bot \\<and> sum f ys \\<noteq> bot\"\nproof -\n  have \"sum f (xs \\<union> ys) = sum f xs + sum f ys\"\n    using assms by (smt disjoint_iff_not_equal sum.cong sum.union_disjoint)\n  thus ?thesis\n    using assms by auto\nqed\n\ntext \\<open>Cancellativity only holds for valid flow graphs,\ntherefore we can not instantiate @{text cancel_comm_monoid_add}.\\<close>\n\nlemma plus_fg_cancel_left:\n  fixes h1 h2 h3 :: \"('n,'m :: cancel_comm_monoid_add) fg\"\n  assumes \"h1 + h2 \\<noteq> bot\"\n    and \"h1 + h2 = h1 + h3\"\n  shows \"h2 = h3\"\nproof (rule fg_eqI)\n  have \"h1 \\<noteq> bot\" \"h2 \\<noteq> bot\" \"h3 \\<noteq> bot\"\n    using assms plus_fg_ops_exist by auto\n\n  thus \"h2 \\<noteq> bot\" \"h3 \\<noteq> bot\"\n    by simp_all\n\n  have \"dom_fg h1 \\<inter> dom_fg h2 = {}\"\n    \"dom_fg h1 \\<inter> dom_fg h3 = {}\"\n    \"dom_fg (h1 + h2) = dom_fg h1 \\<union> dom_fg h2\"\n    \"dom_fg (h1 + h3) = dom_fg h1 \\<union> dom_fg h3\"\n    using assms plus_fg_dom_un[of h1 h2] by auto\n  thus *: \"dom_fg h2 = dom_fg h3\"\n    using assms(2) by auto\n\n  have \"edge_fg (h1 + h2) = edge_fg h2 on (dom_fg h2)\"\n    \"edge_fg (h1 + h3) = edge_fg h3 on (dom_fg h3)\"\n    using edge_fg_plus_fg_on2[of h1 h2] edge_fg_plus_fg_on2[of h1 h3] assms by simp_all\n  thus \"edge_fg h2 = edge_fg h3 on dom_fg h2\"\n    using assms(2) * by simp\n\n  have \"flow_fg (h1 + h2) = flow_fg h2 on (dom_fg h2)\"\n    \"flow_fg (h1 + h3) = flow_fg h3 on (dom_fg h3)\"\n    using flow_fg_plus_fg_on2[of h1 h2] flow_fg_plus_fg_on2[of h1 h3] assms by simp_all\n  thus \"flow_fg h2 = flow_fg h3 on dom_fg h3\"\n    using assms(2) * by simp\nqed\n\nlemma plus_fg_cancel_right:\n  assumes \"a + c \\<noteq> (bot :: (('n,'m :: cancel_comm_monoid_add) fg))\" \"a + c = b + c\"\n  shows \"a = b\"\n  using assms plus_fg_cancel_left[of c a b] by (simp add: algebra_simps)\n\ntext \\<open>Some results about validity of special cases of flow graphs\\<close>\n\nlemma def_fg_singleton[simp]:\n  (* weird/seemingly circular, but can be used to show that fg {x} e f \\<noteq> bot *)\n  \"dom_fg h = {n} \\<Longrightarrow> edge_fg h n n = (\\<lambda>_. 0) \\<Longrightarrow> h \\<noteq> bot\"\n  by (transfer, auto split: option.splits if_splits simp: fg'_option_eq_def)\n\nlemma def_fg_singleton_id:\n  (* also weird *)\n  \"dom_fg h = {n} \\<Longrightarrow> edge_fg h n n = id \\<Longrightarrow> h \\<noteq> bot\"\n  by (transfer,\n      auto split: option.splits if_splits simp: fg'_option_eq_def def_fg'_def flow_eq'_def)\n\nlemma def_fg_singleton':\n  \"e x x = (\\<lambda>_. 0) \\<Longrightarrow> fg {x} e f \\<noteq> bot\"\n  by (transfer,\n      auto split: option.splits if_splits simp: fg'_option_eq_def def_fg'_def flow_eq'_def)\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/Flow_Graph.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8499711832583696, "lm_q2_score": 0.8438951084436076, "lm_q1q2_score": 0.7172865238697633}}
{"text": "section \\<open>Lens Algebraic Operators\\<close>\n\ntheory Lens_Algebra\nimports Lens_Laws\nbegin\n\nsubsection \\<open>Lens Composition, Plus, Unit, and Identity\\<close>\n\ntext \\<open>\n  \\begin{figure}\n  \\begin{center}\n    \\includegraphics[width=7cm]{figures/Composition}\n  \\end{center}\n  \\vspace{-5ex}\n  \\caption{Lens Composition}\n  \\label{fig:Comp}\n  \\end{figure}\n  We introduce the algebraic lens operators; for more information please see our paper~\\<^cite>\\<open>\"Foster16a\"\\<close>.\n  Lens composition, illustrated in Figure~\\ref{fig:Comp}, constructs a lens by composing the source \n  of one lens with the view of another.\\<close>\n\ndefinition lens_comp :: \"('a \\<Longrightarrow> 'b) \\<Rightarrow> ('b \\<Longrightarrow> 'c) \\<Rightarrow> ('a \\<Longrightarrow> 'c)\" (infixl \";\\<^sub>L\" 80) where\n[lens_defs]: \"lens_comp Y X = \\<lparr> lens_get = get\\<^bsub>Y\\<^esub> \\<circ> lens_get X\n                              , lens_put = (\\<lambda> \\<sigma> v. lens_put X \\<sigma> (lens_put Y (lens_get X \\<sigma>) v)) \\<rparr>\"\n\ntext \\<open>\n  \\begin{figure}\n  \\begin{center}\n    \\includegraphics[width=7cm]{figures/Sum}\n  \\end{center}\n  \\vspace{-5ex}\n  \\caption{Lens Sum}\n  \\label{fig:Sum}\n  \\end{figure}\n  Lens plus, as illustrated in Figure~\\ref{fig:Sum} parallel composes two independent lenses, \n  resulting in a lens whose view is the product of the two underlying lens views.\\<close>\n\ndefinition lens_plus :: \"('a \\<Longrightarrow> 'c) \\<Rightarrow> ('b \\<Longrightarrow> 'c) \\<Rightarrow> 'a \\<times> 'b \\<Longrightarrow> 'c\" (infixr \"+\\<^sub>L\" 75) where\n[lens_defs]: \"X +\\<^sub>L Y = \\<lparr> lens_get = (\\<lambda> \\<sigma>. (lens_get X \\<sigma>, lens_get Y \\<sigma>))\n                       , lens_put = (\\<lambda> \\<sigma> (u, v). lens_put X (lens_put Y \\<sigma> v) u) \\<rparr>\"\n\ntext \\<open>The product functor lens similarly parallel composes two lenses, but in this case the lenses\n  have different sources and so the resulting source is also a product.\\<close>\n\ndefinition lens_prod :: \"('a \\<Longrightarrow> 'c) \\<Rightarrow> ('b \\<Longrightarrow> 'd) \\<Rightarrow> ('a \\<times> 'b \\<Longrightarrow> 'c \\<times> 'd)\" (infixr \"\\<times>\\<^sub>L\" 85) where\n[lens_defs]: \"lens_prod X Y = \\<lparr> lens_get = map_prod get\\<^bsub>X\\<^esub> get\\<^bsub>Y\\<^esub>\n                              , lens_put = \\<lambda> (u, v) (x, y). (put\\<^bsub>X\\<^esub> u x, put\\<^bsub>Y\\<^esub> v y) \\<rparr>\"\n\ntext \\<open>The $\\lfst$ and $\\lsnd$ lenses project the first and second elements, respectively, of a\n  product source type.\\<close>\n\ndefinition fst_lens :: \"'a \\<Longrightarrow> 'a \\<times> 'b\" (\"fst\\<^sub>L\") where\n[lens_defs]: \"fst\\<^sub>L = \\<lparr> lens_get = fst, lens_put = (\\<lambda> (\\<sigma>, \\<rho>) u. (u, \\<rho>)) \\<rparr>\"\n\ndefinition snd_lens :: \"'b \\<Longrightarrow> 'a \\<times> 'b\" (\"snd\\<^sub>L\") where\n[lens_defs]: \"snd\\<^sub>L = \\<lparr> lens_get = snd, lens_put = (\\<lambda> (\\<sigma>, \\<rho>) u. (\\<sigma>, u)) \\<rparr>\"\n\nlemma get_fst_lens [simp]: \"get\\<^bsub>fst\\<^sub>L\\<^esub> (x, y) = x\"\n  by (simp add: fst_lens_def)\n\nlemma get_snd_lens [simp]: \"get\\<^bsub>snd\\<^sub>L\\<^esub> (x, y) = y\"\n  by (simp add: snd_lens_def)\n\ntext \\<open>The swap lens is a bijective lens which swaps over the elements of the product source type.\\<close>\n\nabbreviation swap_lens :: \"'a \\<times> 'b \\<Longrightarrow> 'b \\<times> 'a\" (\"swap\\<^sub>L\") where\n\"swap\\<^sub>L \\<equiv> snd\\<^sub>L +\\<^sub>L fst\\<^sub>L\"\n\ntext \\<open>The zero lens is an ineffectual lens whose view is a unit type. This means the zero lens\n  cannot distinguish or change the source type.\\<close>\n\ndefinition zero_lens :: \"unit \\<Longrightarrow> 'a\" (\"0\\<^sub>L\") where\n[lens_defs]: \"0\\<^sub>L = \\<lparr> lens_get = (\\<lambda> _. ()), lens_put = (\\<lambda> \\<sigma> x. \\<sigma>) \\<rparr>\"\n\ntext \\<open>The identity lens is a bijective lens where the source and view type are the same.\\<close>\n\ndefinition id_lens :: \"'a \\<Longrightarrow> 'a\" (\"1\\<^sub>L\") where\n[lens_defs]: \"1\\<^sub>L = \\<lparr> lens_get = id, lens_put = (\\<lambda> _. id) \\<rparr>\"\n\ntext \\<open>The quotient operator $X \\lquot Y$ shortens lens $X$ by cutting off $Y$ from the end. It is\n  thus the dual of the composition operator.\\<close>\n\ndefinition lens_quotient :: \"('a \\<Longrightarrow> 'c) \\<Rightarrow> ('b \\<Longrightarrow> 'c) \\<Rightarrow> 'a \\<Longrightarrow> 'b\" (infixr \"'/\\<^sub>L\" 90) where\n[lens_defs]: \"X /\\<^sub>L Y = \\<lparr> lens_get = \\<lambda> \\<sigma>. get\\<^bsub>X\\<^esub> (create\\<^bsub>Y\\<^esub> \\<sigma>)\n                       , lens_put = \\<lambda> \\<sigma> v. get\\<^bsub>Y\\<^esub> (put\\<^bsub>X\\<^esub> (create\\<^bsub>Y\\<^esub> \\<sigma>) v) \\<rparr>\"\n\ntext \\<open>Lens inverse take a bijective lens and swaps the source and view types.\\<close>\n\ndefinition lens_inv :: \"('a \\<Longrightarrow> 'b) \\<Rightarrow> ('b \\<Longrightarrow> 'a)\" (\"inv\\<^sub>L\") where\n[lens_defs]: \"lens_inv x = \\<lparr> lens_get = create\\<^bsub>x\\<^esub>, lens_put = \\<lambda> \\<sigma>. get\\<^bsub>x\\<^esub> \\<rparr>\"\n\nsubsection \\<open>Closure Poperties\\<close>\n\ntext \\<open>We show that the core lenses combinators defined above are closed under the key lens classes.\\<close>\n  \nlemma id_wb_lens: \"wb_lens 1\\<^sub>L\"\n  by (unfold_locales, simp_all add: id_lens_def)\n\nlemma source_id_lens: \"\\<S>\\<^bsub>1\\<^sub>L\\<^esub> = UNIV\"\n  by (simp add: id_lens_def lens_source_def)\n\nlemma unit_wb_lens: \"wb_lens 0\\<^sub>L\"\n  by (unfold_locales, simp_all add: zero_lens_def)\n\nlemma source_zero_lens: \"\\<S>\\<^bsub>0\\<^sub>L\\<^esub> = UNIV\"\n  by (simp_all add: zero_lens_def lens_source_def)\n\nlemma comp_weak_lens: \"\\<lbrakk> weak_lens x; weak_lens y \\<rbrakk> \\<Longrightarrow> weak_lens (x ;\\<^sub>L y)\"\n  by (unfold_locales, simp_all add: lens_comp_def)\n\nlemma comp_wb_lens: \"\\<lbrakk> wb_lens x; wb_lens y \\<rbrakk> \\<Longrightarrow> wb_lens (x ;\\<^sub>L y)\"\n  by (unfold_locales, auto simp add: lens_comp_def wb_lens_def weak_lens.put_closure)\n   \nlemma comp_mwb_lens: \"\\<lbrakk> mwb_lens x; mwb_lens y \\<rbrakk> \\<Longrightarrow> mwb_lens (x ;\\<^sub>L y)\"\n  by (unfold_locales, auto simp add: lens_comp_def mwb_lens_def weak_lens.put_closure)\n\nlemma source_lens_comp: \"\\<lbrakk> mwb_lens x; mwb_lens y \\<rbrakk> \\<Longrightarrow> \\<S>\\<^bsub>x ;\\<^sub>L y\\<^esub> = {s \\<in> \\<S>\\<^bsub>y\\<^esub>. get\\<^bsub>y\\<^esub> s \\<in> \\<S>\\<^bsub>x\\<^esub>}\"\n  by (auto simp add: lens_comp_def lens_source_def, blast, metis mwb_lens.put_put mwb_lens_def weak_lens.put_get)\n\nlemma id_vwb_lens [simp]: \"vwb_lens 1\\<^sub>L\"\n  by (unfold_locales, simp_all add: id_lens_def)\n\nlemma unit_vwb_lens [simp]: \"vwb_lens 0\\<^sub>L\"\n  by (unfold_locales, simp_all add: zero_lens_def)\n\nlemma comp_vwb_lens: \"\\<lbrakk> vwb_lens x; vwb_lens y \\<rbrakk> \\<Longrightarrow> vwb_lens (x ;\\<^sub>L y)\"\n  by (unfold_locales, simp_all add: lens_comp_def weak_lens.put_closure)\n\nlemma unit_ief_lens: \"ief_lens 0\\<^sub>L\"\n  by (unfold_locales, simp_all add: zero_lens_def)\n\ntext \\<open>Lens plus requires that the lenses be independent to show closure.\\<close>\n    \nlemma plus_mwb_lens:\n  assumes \"mwb_lens x\" \"mwb_lens y\" \"x \\<bowtie> y\"\n  shows \"mwb_lens (x +\\<^sub>L y)\"\n  using assms\n  apply (unfold_locales)\n   apply (simp_all add: lens_plus_def prod.case_eq_if lens_indep_sym)\n  apply (simp add: lens_indep_comm)\ndone\n\nlemma plus_wb_lens:\n  assumes \"wb_lens x\" \"wb_lens y\" \"x \\<bowtie> y\"\n  shows \"wb_lens (x +\\<^sub>L y)\"\n  using assms\n  apply (unfold_locales, simp_all add: lens_plus_def)\n  apply (simp add: lens_indep_sym prod.case_eq_if)\ndone\n\nlemma plus_vwb_lens [simp]:\n  assumes \"vwb_lens x\" \"vwb_lens y\" \"x \\<bowtie> y\"\n  shows \"vwb_lens (x +\\<^sub>L y)\"\n  using assms\n  apply (unfold_locales, simp_all add: lens_plus_def)\n   apply (simp add: lens_indep_sym prod.case_eq_if)\n  apply (simp add: lens_indep_comm prod.case_eq_if)\ndone\n\nlemma source_plus_lens:\n  assumes \"mwb_lens x\" \"mwb_lens y\" \"x \\<bowtie> y\"\n  shows \"\\<S>\\<^bsub>x +\\<^sub>L y\\<^esub> = \\<S>\\<^bsub>x\\<^esub> \\<inter> \\<S>\\<^bsub>y\\<^esub>\"\n  apply (auto simp add: lens_source_def lens_plus_def)\n  apply (meson assms(3) lens_indep_comm)\n  apply (metis assms(1) mwb_lens.weak_get_put mwb_lens_weak weak_lens.put_closure)\ndone\n\nlemma prod_mwb_lens:\n  \"\\<lbrakk> mwb_lens X; mwb_lens Y \\<rbrakk> \\<Longrightarrow> mwb_lens (X \\<times>\\<^sub>L Y)\"\n  by (unfold_locales, simp_all add: lens_prod_def prod.case_eq_if)\n\nlemma prod_wb_lens:\n  \"\\<lbrakk> wb_lens X; wb_lens Y \\<rbrakk> \\<Longrightarrow> wb_lens (X \\<times>\\<^sub>L Y)\"\n  by (unfold_locales, simp_all add: lens_prod_def prod.case_eq_if)\n\nlemma prod_vwb_lens:\n  \"\\<lbrakk> vwb_lens X; vwb_lens Y \\<rbrakk> \\<Longrightarrow> vwb_lens (X \\<times>\\<^sub>L Y)\"\n  by (unfold_locales, simp_all add: lens_prod_def prod.case_eq_if)\n\nlemma prod_bij_lens:\n  \"\\<lbrakk> bij_lens X; bij_lens Y \\<rbrakk> \\<Longrightarrow> bij_lens (X \\<times>\\<^sub>L Y)\"\n  by (unfold_locales, simp_all add: lens_prod_def prod.case_eq_if)\n\nlemma fst_vwb_lens: \"vwb_lens fst\\<^sub>L\"\n  by (unfold_locales, simp_all add: fst_lens_def prod.case_eq_if)\n\nlemma snd_vwb_lens: \"vwb_lens snd\\<^sub>L\"\n  by (unfold_locales, simp_all add: snd_lens_def prod.case_eq_if)\n\nlemma id_bij_lens: \"bij_lens 1\\<^sub>L\"\n  by (unfold_locales, simp_all add: id_lens_def)\n\nlemma inv_id_lens: \"inv\\<^sub>L 1\\<^sub>L = 1\\<^sub>L\"\n  by (auto simp add: lens_inv_def id_lens_def lens_create_def)\n\nlemma inv_inv_lens: \"bij_lens X \\<Longrightarrow> inv\\<^sub>L (inv\\<^sub>L X) = X\"\n  apply (cases X)\n  apply (auto simp add: lens_defs fun_eq_iff)\n  apply (metis (no_types) bij_lens.strong_get_put bij_lens_def select_convs(2) weak_lens.put_get)\n  done\n\nlemma lens_inv_bij: \"bij_lens X \\<Longrightarrow> bij_lens (inv\\<^sub>L X)\"\n  by (unfold_locales, simp_all add: lens_inv_def lens_create_def)\n\nlemma swap_bij_lens: \"bij_lens swap\\<^sub>L\"\n  by (unfold_locales, simp_all add: lens_plus_def prod.case_eq_if fst_lens_def snd_lens_def)\n\nsubsection \\<open>Composition Laws\\<close>\n\ntext \\<open>Lens composition is monoidal, with unit @{term \"1\\<^sub>L\"}, as the following theorems demonstrate. \n  It also has @{term \"0\\<^sub>L\"} as a right annihilator. \\<close>\n  \nlemma lens_comp_assoc: \"X ;\\<^sub>L (Y ;\\<^sub>L Z) = (X ;\\<^sub>L Y) ;\\<^sub>L Z\"\n  by (auto simp add: lens_comp_def)\n\nlemma lens_comp_left_id [simp]: \"1\\<^sub>L ;\\<^sub>L X = X\"\n  by (simp add: id_lens_def lens_comp_def)\n\nlemma lens_comp_right_id [simp]: \"X ;\\<^sub>L 1\\<^sub>L = X\"\n  by (simp add: id_lens_def lens_comp_def)\n\nlemma lens_comp_anhil [simp]: \"wb_lens X \\<Longrightarrow> 0\\<^sub>L ;\\<^sub>L X = 0\\<^sub>L\"\n  by (simp add: zero_lens_def lens_comp_def comp_def)\n\nlemma lens_comp_anhil_right [simp]: \"wb_lens X \\<Longrightarrow> X ;\\<^sub>L 0\\<^sub>L = 0\\<^sub>L\"\n  by (simp add: zero_lens_def lens_comp_def comp_def)\n\nsubsection \\<open>Independence Laws\\<close>\n\ntext \\<open>The zero lens @{term \"0\\<^sub>L\"} is independent of any lens. This is because nothing can be observed\n  or changed using @{term \"0\\<^sub>L\"}. \\<close>\n  \nlemma zero_lens_indep [simp]: \"0\\<^sub>L \\<bowtie> X\"\n  by (auto simp add: zero_lens_def lens_indep_def)\n\nlemma zero_lens_indep' [simp]: \"X \\<bowtie> 0\\<^sub>L\"\n  by (auto simp add: zero_lens_def lens_indep_def)\n\ntext \\<open>Lens independence is irreflexive, but only for effectual lenses as otherwise nothing can\n  be observed.\\<close>\n    \nlemma lens_indep_quasi_irrefl: \"\\<lbrakk> wb_lens x; eff_lens x \\<rbrakk> \\<Longrightarrow> \\<not> (x \\<bowtie> x)\"\n  unfolding lens_indep_def ief_lens_def ief_lens_axioms_def\n  by (simp, metis (full_types) wb_lens.get_put)\n\ntext \\<open>Lens independence is a congruence with respect to composition, as the following properties demonstrate.\\<close>\n    \nlemma lens_indep_left_comp [simp]:\n  \"\\<lbrakk> mwb_lens z; x \\<bowtie> y \\<rbrakk> \\<Longrightarrow> (x ;\\<^sub>L z) \\<bowtie> (y ;\\<^sub>L z)\"\n  apply (rule lens_indepI)\n    apply (auto simp add: lens_comp_def)\n   apply (simp add: lens_indep_comm)\n  apply (simp add: lens_indep_sym)\ndone\n\nlemma lens_indep_right_comp:\n  \"y \\<bowtie> z \\<Longrightarrow> (x ;\\<^sub>L y) \\<bowtie> (x ;\\<^sub>L z)\"\n  apply (auto intro!: lens_indepI simp add: lens_comp_def)\n    using lens_indep_comm lens_indep_sym apply fastforce\n  apply (simp add: lens_indep_sym)\ndone\n\nlemma lens_indep_left_ext [intro]:\n  \"y \\<bowtie> z \\<Longrightarrow> (x ;\\<^sub>L y) \\<bowtie> z\"\n  apply (auto intro!: lens_indepI simp add: lens_comp_def)\n   apply (simp add: lens_indep_comm)\n  apply (simp add: lens_indep_sym)\ndone\n\nlemma lens_indep_right_ext [intro]:\n  \"x \\<bowtie> z \\<Longrightarrow> x \\<bowtie> (y ;\\<^sub>L z)\"\n  by (simp add: lens_indep_left_ext lens_indep_sym)\n\nlemma lens_comp_indep_cong_left:\n  \"\\<lbrakk> mwb_lens Z; X ;\\<^sub>L Z \\<bowtie> Y ;\\<^sub>L Z \\<rbrakk> \\<Longrightarrow> X \\<bowtie> Y\"\n  apply (rule lens_indepI)\n    apply (rename_tac u v \\<sigma>)\n    apply (drule_tac u=u and v=v and \\<sigma>=\"create\\<^bsub>Z\\<^esub> \\<sigma>\" in lens_indep_comm)\n    apply (simp add: lens_comp_def)\n    apply (meson mwb_lens_weak weak_lens.view_determination)\n   apply (rename_tac v \\<sigma>)\n   apply (drule_tac v=v and \\<sigma>=\"create\\<^bsub>Z\\<^esub> \\<sigma>\" in lens_indep_get)\n   apply (simp add: lens_comp_def)\n  apply (drule lens_indep_sym)\n  apply (rename_tac u \\<sigma>)\n  apply (drule_tac v=u and \\<sigma>=\"create\\<^bsub>Z\\<^esub> \\<sigma>\" in lens_indep_get)\n  apply (simp add: lens_comp_def)\ndone\n\nlemma lens_comp_indep_cong:\n  \"mwb_lens Z \\<Longrightarrow> (X ;\\<^sub>L Z) \\<bowtie> (Y ;\\<^sub>L Z) \\<longleftrightarrow> X \\<bowtie> Y\"\n  using lens_comp_indep_cong_left lens_indep_left_comp by blast\n\ntext \\<open>The first and second lenses are independent since the view different parts of a product source.\\<close>\n    \nlemma fst_snd_lens_indep [simp]:\n  \"fst\\<^sub>L \\<bowtie> snd\\<^sub>L\"\n  by (simp add: lens_indep_def fst_lens_def snd_lens_def)\n\nlemma snd_fst_lens_indep [simp]:\n  \"snd\\<^sub>L \\<bowtie> fst\\<^sub>L\"\n  by (simp add: lens_indep_def fst_lens_def snd_lens_def)\n\nlemma split_prod_lens_indep:\n  assumes \"mwb_lens X\"\n  shows \"(fst\\<^sub>L ;\\<^sub>L X) \\<bowtie> (snd\\<^sub>L ;\\<^sub>L X)\"\n  using assms fst_snd_lens_indep lens_indep_left_comp vwb_lens_mwb by blast\n    \ntext \\<open>Lens independence is preserved by summation.\\<close>\n    \nlemma plus_pres_lens_indep [simp]: \"\\<lbrakk> X \\<bowtie> Z; Y \\<bowtie> Z \\<rbrakk> \\<Longrightarrow> (X +\\<^sub>L Y) \\<bowtie> Z\"\n  apply (rule lens_indepI)\n    apply (simp_all add: lens_plus_def prod.case_eq_if)\n   apply (simp add: lens_indep_comm)\n  apply (simp add: lens_indep_sym)\ndone\n\nlemma plus_pres_lens_indep' [simp]:\n  \"\\<lbrakk> X \\<bowtie> Y; X \\<bowtie> Z \\<rbrakk> \\<Longrightarrow> X \\<bowtie> Y +\\<^sub>L Z\"\n  by (auto intro: lens_indep_sym plus_pres_lens_indep)\n\ntext \\<open>Lens independence is preserved by product.\\<close>\n    \nlemma lens_indep_prod:\n  \"\\<lbrakk> X\\<^sub>1 \\<bowtie> X\\<^sub>2; Y\\<^sub>1 \\<bowtie> Y\\<^sub>2 \\<rbrakk> \\<Longrightarrow> X\\<^sub>1 \\<times>\\<^sub>L Y\\<^sub>1 \\<bowtie> X\\<^sub>2 \\<times>\\<^sub>L Y\\<^sub>2\"\n  apply (rule lens_indepI)\n    apply (auto simp add: lens_prod_def prod.case_eq_if lens_indep_comm map_prod_def)\n   apply (simp_all add: lens_indep_sym)\n  done\n\nsubsection \\<open> Compatibility Laws \\<close>\n\nlemma zero_lens_compat [simp]: \"0\\<^sub>L ##\\<^sub>L X\"\n  by (auto simp add: zero_lens_def lens_override_def lens_compat_def)\n\nlemma id_lens_compat [simp]: \"vwb_lens X \\<Longrightarrow> 1\\<^sub>L ##\\<^sub>L X\"\n  by (auto simp add: id_lens_def lens_override_def lens_compat_def)\n\nsubsection \\<open>Algebraic Laws\\<close>\n\ntext \\<open>Lens plus distributes to the right through composition.\\<close>\n  \nlemma plus_lens_distr: \"mwb_lens Z \\<Longrightarrow> (X +\\<^sub>L Y) ;\\<^sub>L Z = (X ;\\<^sub>L Z) +\\<^sub>L (Y ;\\<^sub>L Z)\"\n  by (auto simp add: lens_comp_def lens_plus_def comp_def)\n\ntext \\<open>The first lens projects the first part of a summation.\\<close>\n  \nlemma fst_lens_plus:\n  \"wb_lens y \\<Longrightarrow> fst\\<^sub>L ;\\<^sub>L (x +\\<^sub>L y) = x\"\n  by (simp add: fst_lens_def lens_plus_def lens_comp_def comp_def)\n\ntext \\<open>The second law requires independence as we have to apply x first, before y\\<close>\n\nlemma snd_lens_plus:\n  \"\\<lbrakk> wb_lens x; x \\<bowtie> y \\<rbrakk> \\<Longrightarrow> snd\\<^sub>L ;\\<^sub>L (x +\\<^sub>L y) = y\"\n  apply (simp add: snd_lens_def lens_plus_def lens_comp_def comp_def)\n  apply (subst lens_indep_comm)\n   apply (simp_all)\ndone\n\ntext \\<open>The swap lens switches over a summation.\\<close>\n  \nlemma lens_plus_swap:\n  \"X \\<bowtie> Y \\<Longrightarrow> swap\\<^sub>L ;\\<^sub>L (X +\\<^sub>L Y) = (Y +\\<^sub>L X)\"\n  by (auto simp add: lens_plus_def fst_lens_def snd_lens_def id_lens_def lens_comp_def lens_indep_comm)\n\ntext \\<open>The first, second, and swap lenses are all closely related.\\<close>\n    \nlemma fst_snd_id_lens: \"fst\\<^sub>L +\\<^sub>L snd\\<^sub>L = 1\\<^sub>L\"\n  by (auto simp add: lens_plus_def fst_lens_def snd_lens_def id_lens_def)\n\nlemma swap_lens_idem: \"swap\\<^sub>L ;\\<^sub>L swap\\<^sub>L = 1\\<^sub>L\"\n  by (simp add: fst_snd_id_lens lens_indep_sym lens_plus_swap)\n\nlemma swap_lens_fst: \"fst\\<^sub>L ;\\<^sub>L swap\\<^sub>L = snd\\<^sub>L\"\n  by (simp add: fst_lens_plus fst_vwb_lens)\n\nlemma swap_lens_snd: \"snd\\<^sub>L ;\\<^sub>L swap\\<^sub>L = fst\\<^sub>L\"\n  by (simp add: lens_indep_sym snd_lens_plus snd_vwb_lens)\n\ntext \\<open>The product lens can be rewritten as a sum lens.\\<close>\n    \nlemma prod_as_plus: \"X \\<times>\\<^sub>L Y = X ;\\<^sub>L fst\\<^sub>L +\\<^sub>L Y ;\\<^sub>L snd\\<^sub>L\"\n  by (auto simp add: lens_prod_def fst_lens_def snd_lens_def lens_comp_def lens_plus_def)\n\nlemma prod_lens_id_equiv:\n  \"1\\<^sub>L \\<times>\\<^sub>L 1\\<^sub>L = 1\\<^sub>L\"\n  by (auto simp add: lens_prod_def id_lens_def)\n\nlemma prod_lens_comp_plus:\n  \"X\\<^sub>2 \\<bowtie> Y\\<^sub>2 \\<Longrightarrow> ((X\\<^sub>1 \\<times>\\<^sub>L Y\\<^sub>1) ;\\<^sub>L (X\\<^sub>2 +\\<^sub>L Y\\<^sub>2)) = (X\\<^sub>1 ;\\<^sub>L X\\<^sub>2) +\\<^sub>L (Y\\<^sub>1 ;\\<^sub>L Y\\<^sub>2)\"\n  by (auto simp add: lens_comp_def lens_plus_def lens_prod_def prod.case_eq_if fun_eq_iff)\n\ntext \\<open>The following laws about quotient are similar to their arithmetic analogues. Lens quotient \n  reverse the effect of a composition.\\<close>\n\nlemma lens_comp_quotient:\n  \"weak_lens Y \\<Longrightarrow> (X ;\\<^sub>L Y) /\\<^sub>L Y = X\"\n  by (simp add: lens_quotient_def lens_comp_def)\n    \nlemma lens_quotient_id [simp]: \"weak_lens X \\<Longrightarrow> (X /\\<^sub>L X) = 1\\<^sub>L\"\n  by (force simp add: lens_quotient_def id_lens_def)\n\nlemma lens_quotient_id_denom: \"X /\\<^sub>L 1\\<^sub>L = X\"\n  by (simp add: lens_quotient_def id_lens_def lens_create_def)\n\nlemma lens_quotient_unit: \"weak_lens X \\<Longrightarrow> (0\\<^sub>L /\\<^sub>L X) = 0\\<^sub>L\"\n  by (simp add: lens_quotient_def zero_lens_def)\n\nlemma lens_obs_eq_zero: \"s\\<^sub>1 \\<simeq>\\<^bsub>0\\<^sub>L\\<^esub> s\\<^sub>2 = (s\\<^sub>1 = s\\<^sub>2)\"\n  by (simp add: lens_defs)\n\nlemma lens_obs_eq_one: \"s\\<^sub>1 \\<simeq>\\<^bsub>1\\<^sub>L\\<^esub> s\\<^sub>2\"\n  by (simp add: lens_defs)\n\nlemma lens_obs_eq_as_override: \"vwb_lens X \\<Longrightarrow> s\\<^sub>1 \\<simeq>\\<^bsub>X\\<^esub> s\\<^sub>2 \\<longleftrightarrow> (s\\<^sub>2 = s\\<^sub>1 \\<oplus>\\<^sub>L s\\<^sub>2 on X)\"\n  by (auto simp add: lens_defs; metis vwb_lens.put_eq)\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/Optics/Lens_Algebra.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8438951104066293, "lm_q2_score": 0.8499711775577736, "lm_q1q2_score": 0.7172865207275702}}
{"text": "(*\n    File:      Arithmetic_Summatory.thy\n    Author:    Manuel Eberl, TU M\u00fcnchen\n*)\nsection \\<open>Summatory arithmetic functions\\<close>\ntheory Arithmetic_Summatory\n  imports \n    More_Totient\n    Moebius_Mu\n    Liouville_Lambda\n    Divisor_Count \n    Dirichlet_Series\nbegin\n\nsubsection \\<open>Definition\\<close>\n\ndefinition sum_upto :: \"(nat \\<Rightarrow> 'a :: comm_monoid_add) \\<Rightarrow> real \\<Rightarrow> 'a\" where\n  \"sum_upto f x = (\\<Sum>i | 0 < i \\<and> real i \\<le> x. f i)\"\n\nlemma sum_upto_altdef: \"sum_upto f x = (\\<Sum>i\\<in>{0<..nat \\<lfloor>x\\<rfloor>}. f i)\"\n  unfolding sum_upto_def\n  by (cases \"x \\<ge> 0\"; intro sum.cong refl) (auto simp: le_nat_iff le_floor_iff)\n    \nlemma sum_upto_0 [simp]: \"sum_upto f 0 = 0\"\n  by (simp add: sum_upto_altdef)\n\nlemma sum_upto_cong [cong]:\n  \"(\\<And>n. n > 0 \\<Longrightarrow> f n = f' n) \\<Longrightarrow> n = n' \\<Longrightarrow> sum_upto f n = sum_upto f' n'\"\n  by (simp add: sum_upto_def)\n\nlemma finite_Nats_le_real [simp,intro]: \"finite {n. 0 < n \\<and> real n \\<le> x}\"\nproof (rule finite_subset)\n  show \"finite {n. n \\<le> nat \\<lfloor>x\\<rfloor>}\" by auto\n  show \"{n. 0 < n \\<and> real n \\<le> x} \\<subseteq> {n. n \\<le> nat \\<lfloor>x\\<rfloor>}\" by safe linarith\nqed\n\nlemma sum_upto_ind: \"sum_upto (ind P) x = of_nat (card {n. n > 0 \\<and> real n \\<le> x \\<and> P n})\"\nproof -\n  have \"sum_upto (ind P :: nat \\<Rightarrow> 'a) x = (\\<Sum>n | 0 < n \\<and> real n \\<le> x \\<and> P n. 1)\"\n    unfolding sum_upto_def by (intro sum.mono_neutral_cong_right) (auto simp: ind_def)\n  also have \"\\<dots> = of_nat (card {n. n > 0 \\<and> real n \\<le> x \\<and> P n})\" by simp\n  finally show ?thesis .\nqed\n\nlemma sum_upto_sum_divisors:\n  \"sum_upto (\\<lambda>n. \\<Sum>d | d dvd n. f n d) x = sum_upto (\\<lambda>k. sum_upto (\\<lambda>d. f (d * k) k) (x / k)) x\"\nproof -\n  let ?B = \"(SIGMA k:{k. 0 < k \\<and> real k \\<le> x}. {d. 0 < d \\<and> real d \\<le> x / real k})\"\n  let ?A = \"(SIGMA k:{k. 0 < k \\<and> real k \\<le> x}. {d. d dvd k})\"\n  have *: \"real a \\<le> x\" if \"real (a * b) \\<le> x\" \"b > 0\" for a b\n  proof -\n    have \"real a * 1 \\<le> real (a * b)\" unfolding of_nat_mult using that\n      by (intro mult_left_mono) auto\n    also have \"\\<dots> \\<le> x\" by fact\n    finally show ?thesis by simp\n  qed\n  have bij: \"bij_betw (\\<lambda>(k,d). (d * k, k)) ?B ?A\"\n    by (rule bij_betwI[where g = \"\\<lambda>(k,d). (d, k div d)\"])\n       (auto simp: * divide_simps mult.commute elim!: dvdE)\n\n  have \"sum_upto (\\<lambda>n. \\<Sum>d | d dvd n. f n d) x = (\\<Sum>(k,d)\\<in>?A. f k d)\"\n    unfolding sum_upto_def by (rule sum.Sigma) auto\n  also have \"\\<dots> = (\\<Sum>(k,d)\\<in>?B. f (d * k) k)\"\n    by (subst sum.reindex_bij_betw[OF bij, symmetric]) (auto simp: case_prod_unfold)\n  also have \"\\<dots> = sum_upto (\\<lambda>k. sum_upto (\\<lambda>d. f (d * k) k) (x / k)) x\"\n    unfolding sum_upto_def by (rule sum.Sigma [symmetric]) auto\n  finally show ?thesis .\nqed\n\nlemma sum_upto_dirichlet_prod:\n  \"sum_upto (dirichlet_prod f g) x = sum_upto (\\<lambda>d. f d * sum_upto g (x / real d)) x\"\n  unfolding dirichlet_prod_def\n  by (subst sum_upto_sum_divisors) (simp add: sum_upto_def sum_distrib_left)\n\nlemma sum_upto_real: \n  assumes \"x \\<ge> 0\"\n  shows   \"sum_upto real x = of_int (floor x) * (of_int (floor x) + 1) / 2\"\nproof -\n  have A: \"2 * \\<Sum>{1..n} = n * Suc n\" for n by (induction n) simp_all\n  have \"2 * sum_upto real x = real (2 * \\<Sum>{0<..nat \\<lfloor>x\\<rfloor>})\" by (simp add: sum_upto_altdef)\n  also have \"{0<..nat \\<lfloor>x\\<rfloor>} = {1..nat \\<lfloor>x\\<rfloor>}\" by auto\n  also note A\n  also have \"real (nat \\<lfloor>x\\<rfloor> * Suc (nat \\<lfloor>x\\<rfloor>)) = of_int (floor x) * (of_int (floor x) + 1)\" using assms\n    by (simp add: algebra_simps)\n  finally show ?thesis by simp\nqed\n\nlemma summable_imp_convergent_sum_upto:\n  assumes \"summable (f :: nat \\<Rightarrow> 'a :: real_normed_vector)\"\n  obtains c where \"(sum_upto f \\<longlongrightarrow> c) at_top\"\nproof -\n  from assms have \"summable (\\<lambda>n. f (Suc n))\"\n    by (subst summable_Suc_iff)\n  then obtain c where \"(\\<lambda>n. f (Suc n)) sums c\" by (auto simp: summable_def)\n  hence \"(\\<lambda>n. \\<Sum>k<n. f (Suc k)) \\<longlonglongrightarrow> c\" by (auto simp: sums_def)\n  also have \"(\\<lambda>n. \\<Sum>k<n. f (Suc k)) = (\\<lambda>n. \\<Sum>k\\<in>{0<..n}. f k)\"\n    by (subst sum.atLeast1_atMost_eq [symmetric]) (auto simp: atLeastSucAtMost_greaterThanAtMost)\n  finally have \"((\\<lambda>x. sum f {0<..nat \\<lfloor>x\\<rfloor>}) \\<longlongrightarrow> c) at_top\"\n    by (rule filterlim_compose)\n       (auto intro!: filterlim_compose[OF filterlim_nat_sequentially] filterlim_floor_sequentially)\n  also have \"(\\<lambda>x. sum f {0<..nat \\<lfloor>x\\<rfloor>}) = sum_upto f\"\n    by (intro ext) (simp_all add: sum_upto_altdef)\n  finally show ?thesis using that[of c] by blast\nqed\n\n\nsubsection \\<open>The Hyperbola method\\<close>\n\nlemma hyperbola_method_semiring:\n  fixes f g :: \"nat \\<Rightarrow> 'a :: comm_semiring_0\"\n  assumes \"A \\<ge> 0\" and \"B \\<ge> 0\" and \"A * B = x\"\n  shows   \"sum_upto (dirichlet_prod f g) x + sum_upto f A * sum_upto g B = \n             sum_upto (\\<lambda>n. f n * sum_upto g (x / real n)) A +\n             sum_upto (\\<lambda>n. sum_upto f (x / real n) * g n) B\"\nproof -\n  from assms have [simp]: \"x \\<ge> 0\" by auto\n  {\n    fix a b :: real assume ab: \"a > 0\" \"b > 0\" \"x \\<ge> 0\" \"a * b \\<le> x\" \"a > A\" \"b > B\"\n    hence \"a * b > A * B\" using assms by (intro mult_strict_mono) auto\n    also from assms have \"A * B = x\" by simp\n    finally have False using \\<open>a * b \\<le> x\\<close> by simp\n  } note * = this\n  have *: \"a \\<le> A \\<or> b \\<le> B\" if \"a * b \\<le> x\" \"a > 0\" \"b > 0\" \"x \\<ge> 0\" for a b\n    by (rule ccontr) (insert *[of a b] that, auto)\n  \n  have nat_mult_leD1: \"real a \\<le> x\" if \"real a * real b \\<le> x\" \"b > 0\" for a b\n  proof -\n    from that have \"real a * 1 \\<le> real a * real b\" by (intro mult_left_mono) simp_all\n    also have \"\\<dots> \\<le> x\" by fact\n    finally show ?thesis by simp\n  qed\n  have nat_mult_leD2: \"real b \\<le> x\" if \"real a * real b \\<le> x\" \"a > 0\" for a b\n    using nat_mult_leD1[of b a] that by (simp add: mult_ac)\n  \n  have le_sqrt_mult_imp_le: \"a * b \\<le> x\" \n    if \"a \\<ge> 0\" \"b \\<ge> 0\" \"a \\<le> A\" \"b \\<le> B\" for a b :: real\n  proof -\n    from that and assms have \"a * b \\<le> A * B\" by (intro mult_mono) auto\n    with assms show \"a * b \\<le> x\" by simp\n  qed\n  \n  define F G where \"F = sum_upto f\" and \"G = sum_upto g\"  \n  let ?Bound = \"{0<..nat \\<lfloor>x\\<rfloor>} \\<times> {0<..nat \\<lfloor>x\\<rfloor>}\"\n  let ?B = \"{(r,d). 0 < r \\<and> real r \\<le> A \\<and> 0 < d \\<and> real d \\<le> x / real r}\"\n  let ?C = \"{(r,d). 0 < d \\<and> real d \\<le> B \\<and> 0 < r \\<and> real r \\<le> x / real d}\"\n  let ?B' = \"SIGMA r:{r. 0 < r \\<and> real r \\<le> A}. {d. 0 < d \\<and> real d \\<le> x / real r}\"\n  let ?C' = \"SIGMA d:{d. 0 < d \\<and> real d \\<le> B}. {r. 0 < r \\<and> real r \\<le> x / real d}\"\n  have \"sum_upto (dirichlet_prod f g) x + F A * G B = \n          (\\<Sum>(i,(r,d)) \\<in> (SIGMA i:{i. 0 < i \\<and> real i \\<le> x}. {(r,d). r * d = i}). f r * g d) + \n          sum_upto f A * sum_upto g B\" (is \"_ = ?S + _\")\n    unfolding sum_upto_def dirichlet_prod_altdef2 F_def G_def\n    by (subst sum.Sigma) (auto intro: finite_divisors_nat')\n  also have \"?S = (\\<Sum>(r,d) | 0 < r \\<and> 0 < d \\<and> real (r * d) \\<le> x. f r * g d)\"\n    (is \"_ = sum _ ?A\") by (intro sum.reindex_bij_witness[of _ \"\\<lambda>(r,d). (r*d,(r,d))\" snd]) auto\n  also have \"?A = ?B \\<union> ?C\"  by (auto simp: field_simps dest: *)\n  also have \"sum_upto f A * sum_upto g B = \n               (\\<Sum>r | 0 < r \\<and> real r \\<le> A. \\<Sum>d | 0 < d \\<and> real d \\<le> B. f r * g d)\"\n    by (simp add: sum_upto_def sum_product)\n  also have \"\\<dots> = (\\<Sum>(r,d)\\<in>{r. 0 < r \\<and> real r \\<le> A} \\<times> {d. 0 < d \\<and> real d \\<le> B}. f r * g d)\"\n    (is \"_ = sum _ ?X\") by (rule sum.cartesian_product)\n  also have \"?X = ?B \\<inter> ?C\" by (auto simp: field_simps le_sqrt_mult_imp_le)\n  also have \"(\\<Sum>(r,d)\\<in>?B \\<union> ?C. f r * g d) + (\\<Sum>(r,d)\\<in>?B \\<inter> ?C. f r * g d) = \n               (\\<Sum>(r,d)\\<in>?B. f r * g d) + (\\<Sum>(r,d)\\<in>?C. f r * g d)\"\n    by (intro sum.union_inter finite_subset[of ?B ?Bound] finite_subset[of ?C ?Bound])\n       (auto simp: field_simps le_nat_iff le_floor_iff dest: nat_mult_leD1 nat_mult_leD2)\n  also have \"?B = ?B'\" by auto\n  hence \"(\\<lambda>f. sum f ?B) = (\\<lambda>f. sum f ?B')\" by simp\n  also have \"(\\<Sum>(r,d)\\<in>?B'. f r * g d) = sum_upto (\\<lambda>n. f n * G (x / real n)) A\"\n    by (subst sum.Sigma [symmetric]) (simp_all add: sum_upto_def sum_distrib_left G_def)\n  also have \"(\\<Sum>(r,d)\\<in>?C. f r * g d) = (\\<Sum>(d,r)\\<in>?C'. f r * g d)\"\n    by (intro sum.reindex_bij_witness[of _ \"\\<lambda>(x,y). (y,x)\" \"\\<lambda>(x,y). (y,x)\"]) auto\n  also have \"\\<dots> = sum_upto (\\<lambda>n. F (x / real n) * g n) B\"\n    by (subst sum.Sigma [symmetric]) (simp_all add: sum_upto_def sum_distrib_right F_def)\n  finally show ?thesis by (simp only: F_def G_def)\nqed\n\nlemma hyperbola_method_semiring_sqrt:\n  fixes f g :: \"nat \\<Rightarrow> 'a :: comm_semiring_0\"\n  assumes \"x \\<ge> 0\"\n  shows   \"sum_upto (dirichlet_prod f g) x + sum_upto f (sqrt x) * sum_upto g (sqrt x) = \n             sum_upto (\\<lambda>n. f n * sum_upto g (x / real n)) (sqrt x) +\n             sum_upto (\\<lambda>n. sum_upto f (x / real n) * g n) (sqrt x)\"\n  using assms hyperbola_method_semiring[of \"sqrt x\" \"sqrt x\" x] by simp\n\nlemma hyperbola_method:\n  fixes f g :: \"nat \\<Rightarrow> 'a :: comm_ring\"\n  assumes \"A \\<ge> 0\" \"B \\<ge> 0\" \"A * B = x\"\n  shows   \"sum_upto (dirichlet_prod f g) x = \n             sum_upto (\\<lambda>n. f n * sum_upto g (x / real n)) A +\n             sum_upto (\\<lambda>n. sum_upto f (x / real n) * g n) B -\n             sum_upto f A * sum_upto g B\"\n  using hyperbola_method_semiring[OF assms, of f g] by (simp add: algebra_simps)\n\nlemma hyperbola_method_sqrt:\n  fixes f g :: \"nat \\<Rightarrow> 'a :: comm_ring\"\n  assumes \"x \\<ge> 0\"\n  shows   \"sum_upto (dirichlet_prod f g) x = \n             sum_upto (\\<lambda>n. f n * sum_upto g (x / real n)) (sqrt x) +\n             sum_upto (\\<lambda>n. sum_upto f (x / real n) * g n) (sqrt x) -\n             sum_upto f (sqrt x) * sum_upto g (sqrt x)\"\n  using assms hyperbola_method[of \"sqrt x\" \"sqrt x\" x] by 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/Dirichlet_Series/Arithmetic_Summatory.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.843895106480586, "lm_q2_score": 0.8499711756575749, "lm_q1q2_score": 0.717286515786978}}
{"text": "theory Relations imports HOMML                          (* By Christoph Benzm\u00fcller, 2018 *)\nbegin                     \n (*Some useful properties and operations on (accessibility) relations*)\n  definition reflexive :: \"\\<alpha>\\<Rightarrow>bool\" where \"reflexive R \\<equiv> \\<forall>x. R x x\"\n  definition symmetric :: \"\\<alpha>\\<Rightarrow>bool\" where \"symmetric R \\<equiv> \\<forall>x y. R x y \\<longrightarrow> R y x\"\n  definition transitive :: \"\\<alpha>\\<Rightarrow>bool\" where \"transitive R \\<equiv> \\<forall>x y z. R x y \\<and> R y z \\<longrightarrow> R x z\"\n  definition euclidean :: \"\\<alpha>\\<Rightarrow>bool\" where \"euclidean R \\<equiv> \\<forall>x y z. R x y \\<and> R x z \\<longrightarrow> R y z\"\n  definition intersection_rel :: \"\\<alpha>\\<Rightarrow>\\<alpha>\\<Rightarrow>\\<alpha>\" where \"intersection_rel R Q \\<equiv> \\<lambda>u v. R u v \\<and> Q u v\"\n  definition union_rel :: \"\\<alpha>\\<Rightarrow>\\<alpha>\\<Rightarrow>\\<alpha>\" where \"union_rel R Q \\<equiv> \\<lambda>u v. R u v \\<or> Q u v\"\n  definition sub_rel :: \"\\<alpha>\\<Rightarrow>\\<alpha>\\<Rightarrow>bool\" where \"sub_rel R Q \\<equiv> \\<forall>u v. R u v \\<longrightarrow> Q u v\"\n  definition inverse_rel :: \"\\<alpha>\\<Rightarrow>\\<alpha>\" where \"inverse_rel R \\<equiv> \\<lambda>u v. R v u\"\n\n (*In HOL the transitive closure of a relation can be defined in a single line.*)\n  definition tc :: \"\\<alpha>\\<Rightarrow>\\<alpha>\" where \"tc R \\<equiv> \\<lambda>x y.\\<forall>Q. transitive Q \\<longrightarrow> (sub_rel R Q \\<longrightarrow> Q x y)\"\n\n (*Adding the above definitions to the set of definitions Defs.*) \n declare reflexive_def[Defs] symmetric_def[Defs] transitive_def[Defs] euclidean_def[Defs] \n   intersection_rel_def[Defs] union_rel_def[Defs] sub_rel_def[Defs] inverse_rel_def[Defs] \n\n (*Some useful lemmata.*) \n  lemma trans_tc: \"transitive (tc R)\" unfolding Defs tc_def by metis\n  lemma trans_inv_tc: \"transitive (inverse_rel (tc R))\" unfolding Defs tc_def by metis\n  lemma sub_rel_tc: \"symmetric R \\<longrightarrow> (sub_rel R (inverse_rel (tc R)))\" \n    unfolding Defs tc_def by metis\n  lemma sub_rel_tc_tc: \"symmetric R \\<longrightarrow> (sub_rel (tc R) (inverse_rel (tc R)))\" \n    using sub_rel_def sub_rel_tc tc_def trans_inv_tc by fastforce\n  lemma symm_tc: \"symmetric R \\<longrightarrow> symmetric (tc R)\"  sledgehammer [verbose]  nitpick \n    using inverse_rel_def sub_rel_def sub_rel_tc_tc symmetric_def by auto\nend", "meta": {"author": "cbenzmueller", "repo": "LogiKEy", "sha": "5c16bdeb68bf8131e24ba9c8d774d4af663cb2cf", "save_path": "github-repos/isabelle/cbenzmueller-LogiKEy", "path": "github-repos/isabelle/cbenzmueller-LogiKEy/LogiKEy-5c16bdeb68bf8131e24ba9c8d774d4af663cb2cf/CoursesAndTutorials/2020-ZhejiangUniversity/examples/WiseMenPuzzle/Relations.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122313857378, "lm_q2_score": 0.7905303112671295, "lm_q1q2_score": 0.7172578206938411}}
{"text": "(* Author: Tobias Nipkow *)\n\nsection \"Abstract Interpretation\"\n\nsubsection \"Complete Lattice\"\n\ntheory Complete_Lattice\nimports Main\nbegin\n\nlocale Complete_Lattice =\nfixes L :: \"'a::order set\" and Glb :: \"'a set \\<Rightarrow> 'a\"\nassumes Glb_lower: \"A \\<subseteq> L \\<Longrightarrow> a \\<in> A \\<Longrightarrow> Glb A \\<le> a\"\nand Glb_greatest: \"b \\<in> L \\<Longrightarrow> \\<forall>a\\<in>A. b \\<le> a \\<Longrightarrow> b \\<le> Glb A\"\nand Glb_in_L: \"A \\<subseteq> L \\<Longrightarrow> Glb A \\<in> L\"\nbegin\n\ndefinition lfp :: \"('a \\<Rightarrow> 'a) \\<Rightarrow> 'a\" where\n\"lfp f = Glb {a : L. f a \\<le> a}\"\n\nlemma index_lfp: \"lfp f \\<in> L\"\nby(auto simp: lfp_def intro: Glb_in_L)\n\nlemma lfp_lowerbound:\n  \"\\<lbrakk> a \\<in> L;  f a \\<le> a \\<rbrakk> \\<Longrightarrow> lfp f \\<le> a\"\nby (auto simp add: lfp_def intro: Glb_lower)\n\nlemma lfp_greatest:\n  \"\\<lbrakk> a \\<in> L;  \\<And>u. \\<lbrakk> u \\<in> L; f u \\<le> u\\<rbrakk> \\<Longrightarrow> a \\<le> u \\<rbrakk> \\<Longrightarrow> a \\<le> lfp f\"\nby (auto simp add: lfp_def intro: Glb_greatest)\n\n\n\nend\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/IMP/Complete_Lattice.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122113355091, "lm_q2_score": 0.7905303260722198, "lm_q1q2_score": 0.7172578182763668}}
{"text": "section \\<open>Arithmetic\\label{s:tm-arithmetic}\\<close>\n\ntheory Arithmetic\n  imports Memorizing\nbegin\n\ntext \\<open>\nIn this section we define a representation of natural numbers and some reusable\nTuring machines for elementary arithmetical operations.  All Turing machines\nimplementing the operations assume that the tape heads on the tapes containing\nthe operands and the result(s) contain one natural number each.  In programming\nlanguage terms we could say that such a tape corresponds to a variable of type\n@{typ nat}. Furthermore, initially the tape heads are on cell number~1, that is,\none to the right of the start symbol. The Turing machines will halt with the\ntape heads in that position as well. In that way operations can be concatenated\nseamlessly.\n\\<close>\n\nsubsection \\<open>Binary numbers\\label{s:tm-arithmetic-binary}\\<close>\n\ntext \\<open>\nWe represent binary numbers as sequences of the symbols \\textbf{0} and\n\\textbf{1}.  Slightly unusually the least significant bit will be on the left.\nWhile every sequence over these symbols represents a natural number, the\nrepresentation is not unique due to leading (or rather, trailing) zeros.  The\n\\emph{canonical} representation is unique and has no trailing zeros, not even for\nthe number zero, which is thus represented by the empty symbol sequence.  As a\nside effect empty tapes can be thought of as being initialized with zero.\n\nNaturally the binary digits 0 and 1 are represented by the symbols \\textbf{0}\nand \\textbf{1}, respectively. For example, the decimal number $14$,\nconventionally written $1100_2$ in binary, is represented by the symbol sequence\n\\textbf{0011}. The next two functions map between symbols and binary digits:\n\\<close>\n\nabbreviation (input) tosym :: \"nat \\<Rightarrow> symbol\" where\n  \"tosym z \\<equiv> z + 2\"\n\nabbreviation todigit :: \"symbol \\<Rightarrow> nat\" where\n  \"todigit z \\<equiv> if z = \\<one> then 1 else 0\"\n\ntext \\<open>\nThe numerical value of a symbol sequence:\n\\<close>\n\ndefinition num :: \"symbol list \\<Rightarrow> nat\" where\n  \"num xs \\<equiv> \\<Sum>i\\<leftarrow>[0..<length xs]. todigit (xs ! i) * 2 ^ i\"\n\ntext \\<open>\nThe $i$-th digit of a symbol sequence, where digits out of bounds are considered\ntrailing zeros:\n\\<close>\n\ndefinition digit :: \"symbol list \\<Rightarrow> nat \\<Rightarrow> nat\" where\n  \"digit xs i \\<equiv> if i < length xs then xs ! i else 0\"\n\ntext \\<open>\nSome properties of $num$:\n\\<close>\n\nlemma num_ge_pow:\n  assumes \"i < length xs\" and \"xs ! i = \\<one>\"\n  shows \"num xs \\<ge> 2 ^ i\"\nproof -\n  let ?ys = \"map (\\<lambda>i. todigit (xs ! i) * 2 ^ i) [0..<length xs]\"\n  have \"?ys ! i = 2 ^ i\"\n    using assms by simp\n  moreover have \"i < length ?ys\"\n    using assms(1) by simp\n  ultimately show \"num xs \\<ge> 2 ^ i\"\n    unfolding num_def using elem_le_sum_list by (metis (no_types, lifting))\nqed\n\nlemma num_trailing_zero:\n  assumes \"todigit z = 0\"\n  shows \"num xs = num (xs @ [z])\"\nproof -\n  let ?xs = \"xs @ [z]\"\n  let ?ys = \"map (\\<lambda>i. todigit (?xs ! i) * 2 ^ i) [0..<length ?xs]\"\n  have *: \"?ys = map (\\<lambda>i. todigit (xs ! i) * 2 ^ i) [0..<length xs] @ [0]\"\n    using assms by (simp add: nth_append)\n  have \"num ?xs = sum_list ?ys\"\n    using num_def by simp\n  then have \"num ?xs = sum_list (map (\\<lambda>i. todigit (xs ! i) * 2 ^ i) [0..<length xs] @ [0])\"\n    using * by metis\n  then have \"num ?xs = sum_list (map (\\<lambda>i. todigit (xs ! i) * 2 ^ i) [0..<length xs])\"\n    by simp\n  then show ?thesis\n    using num_def by simp\nqed\n\nlemma num_Cons: \"num (x # xs) = todigit x + 2 * num xs\"\nproof -\n  have \"[0..<length (x # xs)] = [0..<1] @ [1..<length (x # xs)]\"\n    by (metis length_Cons less_imp_le_nat plus_1_eq_Suc upt_add_eq_append zero_less_one)\n  then have 1: \"(map (\\<lambda>i. todigit ((x # xs) ! i) * 2 ^ i) [0..<length (x # xs)]) =\n    (map (\\<lambda>i. todigit ((x # xs) ! i) * 2 ^ i) [0..<1]) @\n    (map (\\<lambda>i. todigit ((x # xs) ! i) * 2 ^ i) [1..<length (x # xs)])\"\n    by simp\n\n  have \"map (\\<lambda>i. f i) [1..<Suc m] = map (\\<lambda>i. f (Suc i)) [0..<m]\" for f :: \"nat \\<Rightarrow> nat\" and m\n  proof (rule nth_equalityI)\n    show \"length (map f [1..<Suc m]) = length (map (\\<lambda>i. f (Suc i)) [0..<m])\"\n      by simp\n    then show \"\\<And>i. i < length (map f [1..<Suc m]) \\<Longrightarrow>\n        map f [1..<Suc m] ! i = map (\\<lambda>i. f (Suc i)) [0..<m] ! i\"\n      by (metis add.left_neutral length_map length_upt nth_map_upt plus_1_eq_Suc)\n  qed\n  then have 2: \"(\\<Sum>i\\<leftarrow>[1..<Suc m]. f i) = (\\<Sum>i\\<leftarrow>[0..<m]. f (Suc i))\"\n      for f :: \"nat \\<Rightarrow> nat\" and m\n    by simp\n\n  have \"num (x # xs) = (\\<Sum>i\\<leftarrow>[0..<length (x # xs)]. todigit ((x # xs) ! i) * 2 ^ i)\"\n    using num_def by simp\n  also have \"... = (\\<Sum>i\\<leftarrow>[0..<1]. (todigit ((x # xs) ! i) * 2 ^ i)) +\n      (\\<Sum>i\\<leftarrow>[1..<length (x # xs)]. todigit ((x # xs) ! i) * 2 ^ i)\"\n    using 1 by simp\n  also have \"... = todigit x + (\\<Sum>i\\<leftarrow>[1..<length (x # xs)]. todigit ((x # xs) ! i) * 2 ^ i)\"\n    by simp\n  also have \"... = todigit x + (\\<Sum>i\\<leftarrow>[0..<length (x # xs) - 1]. todigit ((x # xs) ! (Suc i)) * 2 ^ (Suc i))\"\n    using 2 by simp\n  also have \"... = todigit x + (\\<Sum>i\\<leftarrow>[0..<length xs]. todigit (xs ! i) * 2 ^ (Suc i))\"\n    by simp\n  also have \"... = todigit x + (\\<Sum>i\\<leftarrow>[0..<length xs]. todigit (xs ! i) * (2 * 2 ^ i))\"\n    by simp\n  also have \"... = todigit x + (\\<Sum>i\\<leftarrow>[0..<length xs]. (todigit (xs ! i) * 2 * 2 ^ i))\"\n    by (simp add: mult.assoc)\n  also have \"... = todigit x + (\\<Sum>i\\<leftarrow>[0..<length xs]. (2 * (todigit (xs ! i) * 2 ^ i)))\"\n    by (metis (mono_tags, opaque_lifting) ab_semigroup_mult_class.mult_ac(1) mult.commute)\n  also have \"... = todigit x + 2 * (\\<Sum>i\\<leftarrow>[0..<length xs]. (todigit (xs ! i) * 2 ^ i))\"\n    using sum_list_const_mult by fastforce\n  also have \"... = todigit x + 2 * num xs\"\n    using num_def by simp\n  finally show ?thesis .\nqed\n\nlemma num_append: \"num (xs @ ys) = num xs + 2 ^ length xs * num ys\"\nproof (induction \"length xs\" arbitrary: xs)\n  case 0\n  then show ?case\n    using num_def by simp\nnext\n  case (Suc n)\n  then have xs: \"xs = hd xs # tl xs\"\n    by (metis hd_Cons_tl list.size(3) nat.simps(3))\n  then have \"xs @ ys = hd xs # (tl xs @ ys)\"\n    by simp\n  then have \"num (xs @ ys) = todigit (hd xs) + 2 * num (tl xs @ ys)\"\n    using num_Cons by presburger\n  also have \"... = todigit (hd xs) + 2 * (num (tl xs) + 2 ^ length (tl xs) * num ys)\"\n    using Suc by simp\n  also have \"... = todigit (hd xs) + 2 * num (tl xs) + 2 ^ Suc (length (tl xs)) * num ys\"\n    by simp\n  also have \"... = num xs + 2 ^ Suc (length (tl xs)) * num ys\"\n    using num_Cons xs by metis\n  also have \"... = num xs + 2 ^ length xs * num ys\"\n    using xs by (metis length_Cons)\n  finally show ?case .\nqed\n\nlemma num_drop: \"num (drop t zs) = todigit (digit zs t) + 2 * num (drop (Suc t) zs)\"\nproof (cases \"t < length zs\")\n  case True\n  then have \"drop t zs = zs ! t # drop (Suc t) zs\"\n    by (simp add: Cons_nth_drop_Suc)\n  then have \"num (drop t zs) = todigit (zs ! t) + 2 * num (drop (Suc t) zs)\"\n    using num_Cons by simp\n  then show ?thesis\n    using digit_def True by simp\nnext\n  case False\n  then show ?thesis\n    using digit_def num_def by simp\nqed\n\nlemma num_take_Suc: \"num (take (Suc t) zs) = num (take t zs) + 2 ^ t * todigit (digit zs t)\"\nproof (cases \"t < length zs\")\n  case True\n  let ?zs = \"take (Suc t) zs\"\n  have 1: \"?zs ! i = zs ! i\" if \"i < Suc t\" for i\n    using that by simp\n  have 2: \"take t zs ! i = zs ! i\" if \"i < t\" for i\n    using that by simp\n  have \"num ?zs = (\\<Sum>i\\<leftarrow>[0..<length ?zs]. todigit (?zs ! i) * 2 ^ i)\"\n    using num_def by simp\n  also have \"... = (\\<Sum>i\\<leftarrow>[0..<Suc t]. todigit (?zs ! i) * 2 ^ i)\"\n    by (simp add: Suc_leI True min_absorb2)\n  also have \"... = (\\<Sum>i\\<leftarrow>[0..<Suc t]. todigit (zs ! i) * 2 ^ i)\"\n    using 1 by (smt (verit, best) atLeastLessThan_iff map_eq_conv set_upt)\n  also have \"... = (\\<Sum>i\\<leftarrow>[0..<t]. todigit (zs ! i) * 2 ^ i) + todigit (zs ! t) * 2 ^ t\"\n    by simp\n  also have \"... = (\\<Sum>i\\<leftarrow>[0..<t]. todigit (take t zs ! i) * 2 ^ i) + todigit (zs ! t) * 2 ^ t\"\n    using 2 by (metis (no_types, lifting) atLeastLessThan_iff map_eq_conv set_upt)\n  also have \"... = num (take t zs) + todigit (zs ! t) * 2 ^ t\"\n    using num_def True by simp\n  also have \"... = num (take t zs) + todigit (digit zs t) * 2 ^ t\"\n    using digit_def True by simp\n  finally show ?thesis\n    by simp\nnext\n  case False\n  then show ?thesis\n    using digit_def by simp\nqed\n\ntext \\<open>\nA symbol sequence is a canonical representation of a natural number if the\nsequence contains only the symbols \\textbf{0} and \\textbf{1} and is either empty\nor ends in \\textbf{1}.\n\\<close>\n\ndefinition canonical :: \"symbol list \\<Rightarrow> bool\" where\n  \"canonical xs \\<equiv> bit_symbols xs \\<and> (xs = [] \\<or> last xs = \\<one>)\"\n\nlemma canonical_Cons:\n  assumes \"canonical xs\" and \"xs \\<noteq> []\" and \"x = \\<zero> \\<or> x = \\<one>\"\n  shows \"canonical (x # xs)\"\n  using assms canonical_def less_Suc_eq_0_disj by auto\n\nlemma canonical_Cons_3: \"canonical xs \\<Longrightarrow> canonical (\\<one> # xs)\"\n  using canonical_def less_Suc_eq_0_disj by auto\n\nlemma canonical_tl: \"canonical (x # xs) \\<Longrightarrow> canonical xs\"\n  using canonical_def by fastforce\n\nlemma prepend_2_even: \"x = \\<zero> \\<Longrightarrow> even (num (x # xs))\"\n  using num_Cons by simp\n\nlemma prepend_3_odd: \"x = \\<one> \\<Longrightarrow> odd (num (x # xs))\"\n  using num_Cons by simp\n\ntext \\<open>\nEvery number has exactly one canonical representation.\n\\<close>\n\nlemma canonical_ex1:\n  fixes n :: nat\n  shows \"\\<exists>!xs. num xs = n \\<and> canonical xs\"\nproof (induction n rule: nat_less_induct)\n  case IH: (1 n)\n  show ?case\n  proof (cases \"n = 0\")\n    case True\n    have \"num [] = 0\"\n      using num_def by simp\n    moreover have \"canonical xs \\<Longrightarrow> num xs = 0 \\<Longrightarrow> xs = []\" for xs\n    proof (rule ccontr)\n      fix xs\n      assume \"canonical xs\" \"num xs = 0\" \"xs \\<noteq> []\"\n      then have \"length xs > 0\" \"last xs = \\<one>\"\n        using canonical_def by simp_all\n      then have \"xs ! (length xs - 1) = \\<one>\"\n        by (metis Suc_diff_1 last_length)\n      then have \"num xs \\<ge> 2 ^ (length xs - 1)\"\n        using num_ge_pow by (meson \\<open>0 < length xs\\<close> diff_less zero_less_one)\n      then have \"num xs > 0\"\n        by (meson dual_order.strict_trans1 le0 le_less_trans less_exp)\n      then show False\n        using \\<open>num xs = 0\\<close> by auto\n    qed\n    ultimately show ?thesis\n      using IH True canonical_def by (metis less_nat_zero_code list.size(3))\n  next\n    case False\n    then have gt: \"n > 0\"\n      by simp\n    define m where \"m = n div 2\"\n    define r where \"r = n mod 2\"\n    have n: \"n = 2 * m + r\"\n      using m_def r_def by simp\n    have \"m < n\"\n      using gt m_def by simp\n    then obtain xs where \"num xs = m\" \"canonical xs\"\n      using IH by auto\n    then have \"num (tosym r # xs) = n\"\n        (is \"num ?xs = n\")\n      using num_Cons n add.commute r_def by simp\n    have \"canonical ?xs\"\n    proof (cases \"r = 0\")\n      case True\n      then have \"m > 0\"\n        using gt n by simp\n      then have \"xs \\<noteq> []\"\n        using `num xs = m` num_def by auto\n      then show ?thesis\n        using canonical_Cons[of xs] `canonical xs` r_def True by simp\n    next\n      case False\n      then show ?thesis\n        using `canonical xs` canonical_Cons_3 r_def\n        by (metis One_nat_def not_mod_2_eq_1_eq_0 numeral_3_eq_3 one_add_one plus_1_eq_Suc)\n    qed\n    moreover have \"xs1 = xs2\" if \"canonical xs1\" \"num xs1 = n\" \"canonical xs2\" \"num xs2 = n\" for xs1 xs2\n    proof -\n      have \"xs1 \\<noteq> []\"\n        using gt that(2) num_def by auto\n      then obtain x1 ys1 where 1: \"xs1 = x1 # ys1\"\n        by (meson neq_Nil_conv)\n      then have x1: \"x1 = \\<zero> \\<or> x1 = \\<one>\"\n        using canonical_def that(1) by auto\n      have \"xs2 \\<noteq> []\"\n        using gt that(4) num_def by auto\n      then obtain x2 ys2 where 2: \"xs2 = x2 # ys2\"\n        by (meson neq_Nil_conv)\n      then have x2: \"x2 = \\<zero> \\<or> x2 = \\<one>\"\n        using canonical_def that(3) by auto\n      have \"x1 = x2\"\n        using prepend_2_even prepend_3_odd that 1 2 x1 x2 by metis\n      moreover have \"n = todigit x1 + 2 * num ys1\"\n        using that(2) num_Cons 1 by simp\n      moreover have \"n = todigit x2 + 2 * num ys2\"\n        using that(4) num_Cons 2 by simp\n      ultimately have \"num ys1 = num ys2\"\n        by simp\n      moreover have \"num ys1 < n\"\n        using that(2) num_Cons 1 gt by simp\n      moreover have \"num ys2 < n\"\n        using that(4) num_Cons 2 gt by simp\n      ultimately have \"ys1 = ys2\"\n        using IH 1 2 that(1,3) by (metis canonical_tl)\n      then show \"xs1 = xs2\"\n        using `x1 = x2` 1 2 by simp\n    qed\n    ultimately show ?thesis\n      using \\<open>num (tosym r # xs) = n\\<close> by auto\n  qed\nqed\n\ntext \\<open>\nThe canonical representation of a natural number as symbol sequence:\n\\<close>\n\ndefinition canrepr :: \"nat \\<Rightarrow> symbol list\" where\n  \"canrepr n \\<equiv> THE xs. num xs = n \\<and> canonical xs\"\n\nlemma canrepr_inj: \"inj canrepr\"\n  using canrepr_def canonical_ex1 by (smt (verit, del_insts) inj_def the_equality)\n\nlemma canonical_canrepr: \"canonical (canrepr n)\"\n  using theI'[OF canonical_ex1] canrepr_def by simp\n\nlemma canrepr: \"num (canrepr n) = n\"\n  using theI'[OF canonical_ex1] canrepr_def by simp\n\nlemma bit_symbols_canrepr: \"bit_symbols (canrepr n)\"\n  using canonical_canrepr canonical_def by simp\n\nlemma proper_symbols_canrepr: \"proper_symbols (canrepr n)\"\n  using bit_symbols_canrepr by fastforce\n\nlemma canreprI: \"num xs = n \\<Longrightarrow> canonical xs \\<Longrightarrow> canrepr n = xs\"\n  using canrepr canonical_canrepr canonical_ex1 by blast\n\nlemma canrepr_0: \"canrepr 0 = []\"\n  using num_def canonical_def by (intro canreprI) simp_all\n\nlemma canrepr_1: \"canrepr 1 = [\\<one>]\"\n  using num_def canonical_def by (intro canreprI) simp_all\n\ntext \\<open>\nThe length of the canonical representation of a number $n$:\n\\<close>\n\nabbreviation nlength :: \"nat \\<Rightarrow> nat\" where\n  \"nlength n \\<equiv> length (canrepr n)\"\n\nlemma nlength_0: \"nlength n = 0 \\<longleftrightarrow> n = 0\"\n  by (metis canrepr canrepr_0 length_0_conv)\n\ncorollary nlength_0_simp [simp]: \"nlength 0 = 0\"\n  using nlength_0 by simp\n\nlemma num_replicate2_eq_pow: \"num (replicate j \\<zero> @ [\\<one>]) = 2 ^ j\"\nproof (induction j)\n  case 0\n  then show ?case\n    using num_def by simp\nnext\n  case (Suc j)\n  then show ?case\n    using num_Cons by simp\nqed\n\nlemma num_replicate3_eq_pow_minus_1: \"num (replicate j \\<one>) = 2 ^ j - 1\"\nproof (induction j)\n  case 0\n  then show ?case\n    using num_def by simp\nnext\n  case (Suc j)\n  then have \"num (replicate (Suc j) \\<one>) = num (\\<one> # replicate j \\<one>)\"\n    by simp\n  also have \"... = 1 + 2 * (2 ^ j - 1)\"\n    using Suc num_Cons by simp\n  also have \"... = 1 + 2 * 2 ^ j - 2\"\n    by (metis Nat.add_diff_assoc diff_mult_distrib2 mult_2 mult_le_mono2 nat_1_add_1 one_le_numeral one_le_power)\n  also have \"... = 2 ^ Suc j - 1\"\n    by simp\n  finally show ?case .\nqed\n\nlemma nlength_pow2: \"nlength (2 ^ j) = Suc j\"\nproof -\n  define xs :: \"nat list\" where \"xs = replicate j 2 @ [3]\"\n  then have \"length xs = Suc j\"\n    by simp\n  moreover have \"num xs = 2 ^ j\"\n    using num_replicate2_eq_pow xs_def by simp\n  moreover have \"canonical xs\"\n    using xs_def bit_symbols_append canonical_def by simp\n  ultimately show ?thesis\n    using canreprI by blast\nqed\n\ncorollary nlength_1_simp [simp]: \"nlength 1 = 1\"\n  using nlength_pow2[of 0] by simp\n\ncorollary nlength_2: \"nlength 2 = 2\"\n  using nlength_pow2[of 1] by simp\n\nlemma nlength_pow_minus_1: \"nlength (2 ^ j - 1) = j\"\nproof -\n  define xs :: \"nat list\" where \"xs = replicate j \\<one>\"\n  then have \"length xs = j\"\n    by simp\n  moreover have \"num xs = 2 ^ j - 1\"\n    using num_replicate3_eq_pow_minus_1 xs_def by simp\n  moreover have \"canonical xs\"\n  proof -\n    have \"bit_symbols xs\"\n      using xs_def by simp\n    moreover have \"last xs = 3 \\<or> xs = []\"\n      by (cases \"j = 0\") (simp_all add: xs_def)\n    ultimately show ?thesis\n      using canonical_def by auto\n  qed\n  ultimately show ?thesis\n    using canreprI by metis\nqed\n\ncorollary nlength_3: \"nlength 3 = 2\"\n  using nlength_pow_minus_1[of 2] by simp\n\ntext \\<open>\nWhen handling natural numbers, Turing machines will usually have tape contents\nof the following form:\n\\<close>\n\nabbreviation ncontents :: \"nat \\<Rightarrow> (nat \\<Rightarrow> symbol)\" (\"\\<lfloor>_\\<rfloor>\\<^sub>N\") where\n  \"\\<lfloor>n\\<rfloor>\\<^sub>N \\<equiv> \\<lfloor>canrepr n\\<rfloor>\"\n\nlemma ncontents_0: \"\\<lfloor>0\\<rfloor>\\<^sub>N = \\<lfloor>[]\\<rfloor>\"\n  by (simp add: canrepr_0)\n\nlemma clean_tape_ncontents: \"clean_tape (\\<lfloor>x\\<rfloor>\\<^sub>N, i)\"\n  using bit_symbols_canrepr clean_contents_proper by fastforce\n\nlemma ncontents_1_blank_iff_zero: \"\\<lfloor>n\\<rfloor>\\<^sub>N 1 = \\<box> \\<longleftrightarrow> n = 0\"\n  using bit_symbols_canrepr contents_def nlength_0\n  by (metis contents_outofbounds diff_is_0_eq' leI length_0_conv length_greater_0_conv less_one zero_neq_numeral)\n\ntext \\<open>\nEvery bit symbol sequence can be turned into a canonical representation of some\nnumber by stripping trailing zeros. The length of the prefix without trailing\nzeros is given by the next function:\n\\<close>\n\ndefinition canlen :: \"symbol list \\<Rightarrow> nat\" where\n  \"canlen zs \\<equiv> LEAST m. \\<forall>i<length zs. i \\<ge> m \\<longrightarrow> zs ! i = \\<zero>\"\n\nlemma canlen_at_ge: \"\\<forall>i<length zs. i \\<ge> canlen zs \\<longrightarrow> zs ! i = \\<zero>\"\nproof -\n  let ?P = \"\\<lambda>m. \\<forall>i<length zs. i \\<ge> m \\<longrightarrow> zs ! i = \\<zero>\"\n  have \"?P (length zs)\"\n    by simp\n  then show ?thesis\n    unfolding canlen_def using LeastI[of ?P \"length zs\"] by fast\nqed\n\nlemma canlen_eqI:\n  assumes \"\\<forall>i<length zs. i \\<ge> m \\<longrightarrow> zs ! i = \\<zero>\"\n    and \"\\<And>y. \\<forall>i<length zs. i \\<ge> y \\<longrightarrow> zs ! i = \\<zero> \\<Longrightarrow> m \\<le> y\"\n  shows \"canlen zs = m\"\n  unfolding canlen_def using assms Least_equality[of _ m, OF _ assms(2)] by presburger\n\nlemma canlen_le_length: \"canlen zs \\<le> length zs\"\nproof -\n  let ?P = \"\\<lambda>m. \\<forall>i<length zs. i \\<ge> m \\<longrightarrow> zs ! i = \\<zero>\"\n  have \"?P (length zs)\"\n    by simp\n  then show ?thesis\n    unfolding canlen_def using Least_le[of _ \"length zs\"] by simp\nqed\n\nlemma canlen_le:\n  assumes \"\\<forall>i<length zs. i \\<ge> m \\<longrightarrow> zs ! i = \\<zero>\"\n  shows \"m \\<ge> canlen zs\"\n  unfolding canlen_def using Least_le[of _ m] assms by simp\n\nlemma canlen_one:\n  assumes \"bit_symbols zs\" and \"canlen zs > 0\"\n  shows \"zs ! (canlen zs - 1) = \\<one>\"\nproof (rule ccontr)\n  assume \"zs ! (canlen zs - 1) \\<noteq> \\<one>\"\n  then have \"zs ! (canlen zs - 1) = \\<zero>\"\n    using assms canlen_le_length\n    by (metis One_nat_def Suc_pred lessI less_le_trans)\n  then have \"\\<forall>i<length zs. i \\<ge> canlen zs - 1 \\<longrightarrow> zs ! i = 2\"\n    using canlen_at_ge assms(2) by (metis One_nat_def Suc_leI Suc_pred le_eq_less_or_eq)\n  then have \"canlen zs - 1 \\<ge> canlen zs\"\n    using canlen_le by auto\n  then show False\n    using assms(2) by simp\nqed\n\nlemma canonical_take_canlen:\n  assumes \"bit_symbols zs\"\n  shows \"canonical (take (canlen zs) zs)\"\nproof (cases \"canlen zs = 0\")\n  case True\n  then show ?thesis\n    using canonical_def by simp\nnext\n  case False\n  then show ?thesis\n    using canonical_def assms canlen_le_length canlen_one\n    by (smt (verit, ccfv_SIG) One_nat_def Suc_pred append_take_drop_id diff_less last_length\n      length_take less_le_trans min_absorb2 neq0_conv nth_append zero_less_one)\nqed\n\nlemma num_take_canlen_eq: \"num (take (canlen zs) zs) = num zs\"\nproof (induction \"length zs - canlen zs\" arbitrary: zs)\n  case 0\n  then show ?case\n    by simp\nnext\n  case (Suc x)\n  let ?m = \"canlen zs\"\n  have *: \"\\<forall>i<length zs. i \\<ge> ?m \\<longrightarrow> zs ! i = \\<zero>\"\n    using canlen_at_ge by auto\n  have \"canlen zs < length zs\"\n    using Suc by simp\n  then have \"zs ! (length zs - 1) = \\<zero>\"\n    using Suc canlen_at_ge canlen_le_length\n    by (metis One_nat_def Suc_pred diff_less le_Suc_eq less_nat_zero_code nat_neq_iff zero_less_one)\n  then have \"todigit (zs ! (length zs - 1)) = 0\"\n    by simp\n  moreover have ys: \"zs = take (length zs - 1) zs @ [zs ! (length zs - 1)]\"\n      (is \"zs = ?ys @ _\")\n    by (metis Suc_diff_1 \\<open>canlen zs < length zs\\<close> append_butlast_last_id butlast_conv_take\n      gr_implies_not0 last_length length_0_conv length_greater_0_conv)\n  ultimately have \"num ?ys = num zs\"\n    using num_trailing_zero by metis\n  have canlen_ys: \"canlen ?ys = canlen zs\"\n  proof (rule canlen_eqI)\n    show \"\\<forall>i<length ?ys. canlen zs \\<le> i \\<longrightarrow> ?ys ! i = \\<zero>\"\n      by (simp add: canlen_at_ge)\n    show \"\\<And>y. \\<forall>i<length ?ys. y \\<le> i \\<longrightarrow> ?ys ! i = \\<zero> \\<Longrightarrow> canlen zs \\<le> y\"\n      using * Suc.hyps(2) canlen_le\n      by (smt (verit, del_insts) One_nat_def Suc_pred append_take_drop_id diff_le_self length_take\n        length_upt less_Suc_eq less_nat_zero_code list.size(3) min_absorb2 nth_append upt.simps(2) zero_less_Suc)\n  qed\n  then have \"length ?ys - canlen ?ys = x\"\n    using ys Suc.hyps(2) by (metis butlast_snoc diff_Suc_1 diff_commute length_butlast)\n  then have \"num (take (canlen ?ys) ?ys) = num ?ys\"\n    using Suc by blast\n  then have \"num (take (canlen zs) ?ys) = num ?ys\"\n    using canlen_ys by simp\n  then have \"num (take (canlen zs) zs) = num ?ys\"\n    by (metis \\<open>canlen zs < length zs\\<close> butlast_snoc take_butlast ys)\n  then show ?case\n    using \\<open>num ?ys = num zs\\<close> by presburger\nqed\n\nlemma canrepr_take_canlen:\n  assumes \"num zs = n\" and \"bit_symbols zs\"\n  shows \"canrepr n = take (canlen zs) zs\"\n  using assms canrepr canonical_canrepr canonical_ex1 canonical_take_canlen num_take_canlen_eq\n  by blast\n\nlemma length_canrepr_canlen:\n  assumes \"num zs = n\" and \"bit_symbols zs\"\n  shows \"nlength n = canlen zs\"\n  using canrepr_take_canlen assms canlen_le_length by (metis length_take min_absorb2)\n\nlemma nlength_ge_pow:\n  assumes \"nlength n = Suc j\"\n  shows \"n \\<ge> 2 ^ j\"\nproof -\n  let ?xs = \"canrepr n\"\n  have \"?xs ! (length ?xs - 1) = \\<one>\"\n    using canonical_def assms canonical_canrepr\n    by (metis Suc_neq_Zero diff_Suc_1 last_length length_0_conv)\n  moreover have \"(\\<Sum>i\\<leftarrow>[0..<length ?xs]. todigit (?xs ! i) * 2 ^ i) \\<ge>\n      todigit (?xs ! (length ?xs - 1)) * 2 ^ (length ?xs - 1)\"\n    using assms by simp\n  ultimately have \"num ?xs \\<ge> 2 ^ (length ?xs - 1)\"\n    using num_def by simp\n  moreover have \"num ?xs = n\"\n    using canrepr by simp\n  ultimately show ?thesis\n    using assms by simp\nqed\n\nlemma nlength_less_pow: \"n < 2 ^ (nlength n)\"\nproof (induction \"nlength n\" arbitrary: n)\n  case 0\n  then show ?case\n    by (metis canrepr canrepr_0 length_0_conv nat_zero_less_power_iff)\nnext\n  case (Suc j)\n  let ?xs = \"canrepr n\"\n  have lenxs: \"length ?xs = Suc j\"\n    using Suc by simp\n  have hdtl: \"?xs = hd ?xs # tl ?xs\"\n    using Suc by (metis hd_Cons_tl list.size(3) nat.simps(3))\n  have len: \"length (tl ?xs) = j\"\n    using Suc by simp\n  have can: \"canonical (tl ?xs)\"\n    using hdtl canonical_canrepr canonical_tl by metis\n  define n' where \"n' = num (tl ?xs)\"\n  then have \"nlength n' = j\"\n    using len can canreprI by simp\n  then have n'_less: \"n' < 2 ^ j\"\n    using Suc by auto\n  have \"num ?xs = todigit (hd ?xs) + 2 * num (tl ?xs)\"\n    by (metis hdtl num_Cons)\n  then have \"n = todigit (hd ?xs) + 2 * num (tl ?xs)\"\n    using canrepr by simp\n  also have \"... \\<le> 1 + 2 * num (tl ?xs)\"\n    by simp\n  also have \"... = 1 + 2 * n'\"\n    using n'_def by simp\n  also have \"... \\<le> 1 + 2 * (2 ^ j - 1)\"\n    using n'_less by simp\n  also have \"... = 2 ^ (Suc j) - 1\"\n    by (metis (no_types, lifting) add_Suc_right le_add_diff_inverse mult_2 one_le_numeral\n      one_le_power plus_1_eq_Suc sum.op_ivl_Suc sum_power2 zero_order(3))\n  also have \"... < 2 ^ (Suc j)\"\n    by simp\n  also have \"... = 2 ^ (nlength n)\"\n    using lenxs by simp\n  finally show ?case .\nqed\n\nlemma pow_nlength:\n  assumes \"2 ^ j \\<le> n\" and \"n < 2 ^ (Suc j)\"\n  shows \"nlength n = Suc j\"\nproof (rule ccontr)\n  assume \"nlength n \\<noteq> Suc j\"\n  then have \"nlength n < Suc j \\<or> nlength n > Suc j\"\n    by auto\n  then show False\n  proof\n    assume \"nlength n < Suc j\"\n    then have \"nlength n \\<le> j\"\n      by simp\n    moreover have \"n < 2 ^ (nlength n)\"\n      using nlength_less_pow by simp\n    ultimately have \"n < 2 ^ j\"\n      by (metis le_less_trans nat_power_less_imp_less not_less numeral_2_eq_2 zero_less_Suc)\n    then show False\n      using assms(1) by simp\n  next\n    assume *: \"nlength n > Suc j\"\n    then have \"n \\<ge> 2 ^ (nlength n - 1)\"\n      using nlength_ge_pow by simp\n    moreover have \"nlength n - 1 \\<ge> Suc j\"\n      using * by simp\n    ultimately have \"n \\<ge> 2 ^ (Suc j)\"\n      by (metis One_nat_def le_less_trans less_2_cases_iff linorder_not_less power_less_imp_less_exp)\n    then show False\n      using assms(2) by simp\n  qed\nqed\n\nlemma nlength_le_n: \"nlength n \\<le> n\"\nproof (cases \"n = 0\")\n  case True\n  then show ?thesis\n    using canrepr_0 by simp\nnext\n  case False\n  then have \"nlength n > 0\"\n    using nlength_0 by simp\n  moreover from this have \"n \\<ge> 2 ^ (nlength n - 1)\"\n    using nlength_0 nlength_ge_pow by auto\n  ultimately show ?thesis\n    using nlength_ge_pow by (metis Suc_diff_1 Suc_leI dual_order.trans less_exp)\nqed\n\nlemma nlength_Suc_le: \"nlength n \\<le> nlength (Suc n)\"\nproof (cases \"n = 0\")\n  case True\n  then show ?thesis\n    by (simp add: canrepr_0)\nnext\n  case False\n  then obtain j where j: \"nlength n = Suc j\"\n    by (metis canrepr canrepr_0 gr0_implies_Suc length_greater_0_conv)\n  then have \"n \\<ge> 2 ^ j\"\n    using nlength_ge_pow by simp\n  show ?thesis\n  proof (cases \"Suc n \\<ge> 2 ^ (Suc j)\")\n    case True\n    have \"n < 2 ^ (Suc j)\"\n      using j nlength_less_pow by metis\n    then have \"Suc n < 2 ^ (Suc (Suc j))\"\n      by simp\n    then have \"nlength (Suc n) = Suc (Suc j)\"\n      using True pow_nlength by simp\n    then show ?thesis\n      using j by simp\n  next\n    case False\n    then have \"Suc n < 2 ^ (Suc j)\"\n      by simp\n    then have \"nlength (Suc n) = Suc j\"\n      using `n \\<ge> 2 ^ j` pow_nlength by simp\n    then show ?thesis\n      using j by simp\n  qed\nqed\n\nlemma nlength_mono:\n  assumes \"n1 \\<le> n2\"\n  shows \"nlength n1 \\<le> nlength n2\"\nproof -\n  have \"nlength n \\<le> nlength (n + d)\" for n d\n  proof (induction d)\n    case 0\n    then show ?case\n      by simp\n  next\n    case (Suc d)\n    then show ?case\n      using nlength_Suc_le by (metis nat_arith.suc1 order_trans)\n  qed\n  then show ?thesis\n    using assms by (metis le_add_diff_inverse)\nqed\n\nlemma nlength_even_le: \"n > 0 \\<Longrightarrow> nlength (2 * n) = Suc (nlength n)\"\nproof -\n  assume \"n > 0\"\n  then have \"nlength n > 0\"\n    by (metis canrepr canrepr_0 length_greater_0_conv less_numeral_extra(3))\n  then have \"n \\<ge> 2 ^ (nlength n - 1)\"\n    using Suc_diff_1 nlength_ge_pow by simp\n  then have \"2 * n \\<ge> 2 ^ (nlength n)\"\n    by (metis Suc_diff_1 \\<open>0 < nlength n\\<close> mult_le_mono2 power_Suc)\n  moreover have \"2 * n < 2 ^ (Suc (nlength n))\"\n    using nlength_less_pow by simp\n  ultimately show ?thesis\n    using pow_nlength by simp\nqed\n\nlemma nlength_prod: \"nlength (n1 * n2) \\<le> nlength n1 + nlength n2\"\nproof -\n  let ?j1 = \"nlength n1\" and ?j2 = \"nlength n2\"\n  have \"n1 < 2 ^ ?j1\" \"n2 < 2 ^ ?j2\"\n    using nlength_less_pow by simp_all\n  then have \"n1 * n2 < 2 ^ ?j1 * 2 ^ ?j2\"\n    by (simp add: mult_strict_mono)\n  then have \"n1 * n2 < 2 ^ (?j1 + ?j2)\"\n    by (simp add: power_add)\n  then have \"n1 * n2 \\<le> 2 ^ (?j1 + ?j2) - 1\"\n    by simp\n  then have \"nlength (n1 * n2) \\<le> nlength (2 ^ (?j1 + ?j2) - 1)\"\n    using nlength_mono by simp\n  then show \"nlength (n1 * n2) \\<le> ?j1 + ?j2\"\n    using nlength_pow_minus_1 by simp\nqed\n\ntext \\<open>\nIn the following lemma @{const Suc} is needed because $n^0 = 1$.\n\\<close>\n\nlemma nlength_pow: \"nlength (n ^ d) \\<le> Suc (d * nlength n)\"\nproof (induction d)\n  case 0\n  then show ?case\n    by (metis less_or_eq_imp_le mult_not_zero nat_power_eq_Suc_0_iff nlength_pow2)\nnext\n  case (Suc d)\n  have \"nlength (n ^ Suc d) = nlength (n ^ d * n)\"\n    by (simp add: mult.commute)\n  then have \"nlength (n ^ Suc d) \\<le> nlength (n ^ d) + nlength n\"\n    using nlength_prod by simp\n  then show ?case\n    using Suc by simp\nqed\n\nlemma nlength_sum: \"nlength (n1 + n2) \\<le> Suc (max (nlength n1) (nlength n2))\"\nproof -\n  let ?m = \"max n1 n2\"\n  have \"n1 + n2 \\<le> 2 * ?m\"\n    by simp\n  then have \"nlength (n1 + n2) \\<le> nlength (2 * ?m)\"\n    using nlength_mono by simp\n  moreover have \"nlength ?m = max (nlength n1) (nlength n2)\"\n    using nlength_mono by (metis max.absorb1 max.cobounded2 max_def)\n  ultimately show ?thesis\n    using nlength_even_le\n    by (metis canrepr_0 le_SucI le_zero_eq list.size(3) max_nat.neutr_eq_iff not_gr_zero zero_eq_add_iff_both_eq_0)\nqed\n\nlemma nlength_Suc: \"nlength (Suc n) \\<le> Suc (nlength n)\"\n  using nlength_sum nlength_1_simp\n  by (metis One_nat_def Suc_leI add_Suc diff_Suc_1 length_greater_0_conv max.absorb_iff2\n    max.commute max_def nlength_0 plus_1_eq_Suc)\n\nlemma nlength_less_n: \"n \\<ge> 3 \\<Longrightarrow> nlength n < n\"\nproof (induction n rule: nat_induct_at_least)\n  case base\n  then show ?case\n    by (simp add: nlength_3)\nnext\n  case (Suc n)\n  then show ?case\n    using nlength_Suc by (metis Suc_le_eq le_neq_implies_less nlength_le_n not_less_eq)\nqed\n\n\nsubsubsection \\<open>Comparing two numbers\\<close>\n\ntext \\<open>\nIn order to compare two numbers in canonical representation, we can use the\nTuring machine @{const tm_equals}, which works for arbitrary proper symbol\nsequences.\n\n\\null\n\\<close>\n\nlemma min_nlength: \"min (nlength n1) (nlength n2) = nlength (min n1 n2)\"\n  by (metis min_absorb2 min_def nat_le_linear nlength_mono)\n\nlemma max_nlength: \"max (nlength n1) (nlength n2) = nlength (max n1 n2)\"\n  using nlength_mono by (metis max.absorb1 max.cobounded2 max_def)\n\nlemma contents_blank_0: \"\\<lfloor>[\\<box>]\\<rfloor> = \\<lfloor>[]\\<rfloor>\"\n  using contents_def by auto\n\ndefinition tm_equalsn :: \"tapeidx \\<Rightarrow> tapeidx \\<Rightarrow> tapeidx \\<Rightarrow> machine\" where\n  \"tm_equalsn \\<equiv> tm_equals\"\n\nlemma tm_equalsn_tm:\n  assumes \"k \\<ge> 2\" and \"G \\<ge> 4\" and \"0 < j3\"\n  shows \"turing_machine k G (tm_equalsn j1 j2 j3)\"\n  unfolding tm_equalsn_def using assms tm_equals_tm by simp\n\nlemma transforms_tm_equalsnI [transforms_intros]:\n  fixes j1 j2 j3 :: tapeidx\n  fixes tps tps' :: \"tape list\" and k b n1 n2 :: nat\n  assumes \"length tps = k\" \"j1 \\<noteq> j2\" \"j2 \\<noteq> j3\" \"j1 \\<noteq> j3\" \"j1 < k\" \"j2 < k\" \"j3 < k\"\n    and \"b \\<le> 1\"\n  assumes\n    \"tps ! j1 = (\\<lfloor>n1\\<rfloor>\\<^sub>N, 1)\"\n    \"tps ! j2 = (\\<lfloor>n2\\<rfloor>\\<^sub>N, 1)\"\n    \"tps ! j3 = (\\<lfloor>b\\<rfloor>\\<^sub>N, 1)\"\n  assumes \"ttt = (3 * nlength (min n1 n2) + 7)\"\n  assumes \"tps' = tps\n    [j3 := (\\<lfloor>if n1 = n2 then 1 else 0\\<rfloor>\\<^sub>N, 1)]\"\n  shows \"transforms (tm_equalsn j1 j2 j3) tps ttt tps'\"\n  unfolding tm_equalsn_def\nproof (tform tps: assms)\n  show \"proper_symbols (canrepr n1)\"\n    using proper_symbols_canrepr by simp\n  show \"proper_symbols (canrepr n2)\"\n    using proper_symbols_canrepr by simp\n  show \"ttt = 3 * min (nlength n1) (nlength n2) + 7\"\n    using assms(12) min_nlength by simp\n  let ?v = \"if canrepr n1 = canrepr n2 then 3::nat else 0::nat\"\n  have \"b = 0 \\<or> b = 1\"\n    using assms(8) by auto\n  then have \"\\<lfloor>b\\<rfloor>\\<^sub>N = \\<lfloor>[]\\<rfloor> \\<or> \\<lfloor>b\\<rfloor>\\<^sub>N = \\<lfloor>[\\<one>]\\<rfloor>\"\n    using canrepr_0 canrepr_1 by auto\n  then have \"tps ! j3 = (\\<lfloor>[]\\<rfloor>, 1) \\<or> tps ! j3 = (\\<lfloor>[\\<one>]\\<rfloor>, 1)\"\n    using assms(11) by simp\n  then have v: \"tps ! j3 |:=| ?v = (\\<lfloor>[?v]\\<rfloor>, 1)\"\n    using contents_def by auto\n  show \"tps' = tps[j3 := tps ! j3 |:=| ?v]\"\n  proof (cases \"n1 = n2\")\n    case True\n    then show ?thesis\n      using canrepr_1 v assms(13) by auto\n  next\n    case False\n    then have \"?v = 0\"\n      by (metis canrepr)\n    then show ?thesis\n      using canrepr_0 v assms(13) contents_blank_0 by auto\n  qed\nqed\n\n\nsubsubsection \\<open>Copying a number between tapes\\<close>\n\ntext \\<open>\nThe next Turing machine overwrites the contents of tape $j_2$ with the contents\nof tape $j_1$ and performs a carriage return on both tapes.\n\\<close>\n\ndefinition tm_copyn :: \"tapeidx \\<Rightarrow> tapeidx \\<Rightarrow> machine\" where\n  \"tm_copyn j1 j2 \\<equiv>\n     tm_erase_cr j2 ;;\n     tm_cp_until j1 j2 {\\<box>} ;;\n     tm_cr j1 ;;\n     tm_cr j2\"\n\nlemma tm_copyn_tm:\n  assumes \"k \\<ge> 2\" and \"G \\<ge> 4\" and \"j1 < k\" \"j2 < k\" \"j1 \\<noteq> j2\" \"0 < j2\"\n  shows \"turing_machine k G (tm_copyn j1 j2)\"\n  unfolding tm_copyn_def using assms tm_cp_until_tm tm_cr_tm tm_erase_cr_tm by simp\n\nlocale turing_machine_move =\n  fixes j1 j2 :: tapeidx\nbegin\n\ndefinition \"tm1 \\<equiv> tm_erase_cr j2\"\ndefinition \"tm2 \\<equiv> tm1 ;; tm_cp_until j1 j2 {\\<box>}\"\ndefinition \"tm3 \\<equiv> tm2 ;; tm_cr j1\"\ndefinition \"tm4 \\<equiv> tm3 ;; tm_cr j2\"\n\nlemma tm4_eq_tm_copyn: \"tm4 = tm_copyn j1 j2\"\n  unfolding tm4_def tm3_def tm2_def tm1_def tm_copyn_def by simp\n\ncontext\n  fixes x y :: nat and tps0 :: \"tape list\"\n  assumes j_less [simp]: \"j1 < length tps0\" \"j2 < length tps0\"\n  assumes j [simp]: \"j1 \\<noteq> j2\"\n    and tps_j1 [simp]: \"tps0 ! j1 = (\\<lfloor>x\\<rfloor>\\<^sub>N, 1)\"\n    and tps_j2 [simp]: \"tps0 ! j2 = (\\<lfloor>y\\<rfloor>\\<^sub>N, 1)\"\nbegin\n\ndefinition \"tps1 \\<equiv> tps0\n  [j2 := (\\<lfloor>[]\\<rfloor>, 1)]\"\n\nlemma tm1 [transforms_intros]:\n  assumes \"t = 7 + 2 * nlength y\"\n  shows \"transforms tm1 tps0 t tps1\"\n  unfolding tm1_def\nproof (tform tps: tps1_def time: assms)\n  show \"proper_symbols (canrepr y)\"\n    using proper_symbols_canrepr by simp\nqed\n\ndefinition \"tps2 \\<equiv> tps0\n  [j1 := (\\<lfloor>x\\<rfloor>\\<^sub>N, Suc (nlength x)),\n   j2 := (\\<lfloor>x\\<rfloor>\\<^sub>N, Suc (nlength x))]\"\n\nlemma tm2 [transforms_intros]:\n  assumes \"t = 8 + (2 * nlength y + nlength x)\"\n  shows \"transforms tm2 tps0 t tps2\"\n  unfolding tm2_def\nproof (tform tps: tps1_def time: assms)\n  show \"rneigh (tps1 ! j1) {\\<box>} (nlength x)\"\n  proof (rule rneighI)\n    show \"(tps1 ::: j1) (tps1 :#: j1 + nlength x) \\<in> {\\<box>}\"\n      using tps1_def canrepr_0 contents_outofbounds j(1) nlength_0_simp tps_j1\n      by (metis fst_eqD lessI nth_list_update_neq plus_1_eq_Suc singleton_iff snd_eqD)\n    show \"\\<And>n'. n' < nlength x \\<Longrightarrow> (tps1 ::: j1) (tps1 :#: j1 + n') \\<notin> {\\<box>}\"\n      using tps1_def tps_j1 j j_less contents_inbounds proper_symbols_canrepr\n      by (metis Suc_leI add_diff_cancel_left' fst_eqD not_add_less2 nth_list_update_neq\n        plus_1_eq_Suc singletonD snd_eqD zero_less_Suc)\n  qed\n\n  have \"(\\<lfloor>x\\<rfloor>\\<^sub>N, Suc (nlength x)) = tps0[j2 := (\\<lfloor>[]\\<rfloor>, 1)] ! j1 |+| nlength x\"\n    using tps_j1 tps_j2 by (metis fst_eqD j(1) j_less(2) nth_list_update plus_1_eq_Suc snd_eqD)\n  moreover have \"(\\<lfloor>x\\<rfloor>\\<^sub>N, Suc (nlength x)) =\n      implant (tps0[j2 := (\\<lfloor>[]\\<rfloor>, 1)] ! j1) (tps0[j2 := (\\<lfloor>[]\\<rfloor>, 1)] ! j2) (nlength x)\"\n    using tps_j1 tps_j2 j j_less implant_contents nlength_0_simp\n    by (metis add.right_neutral append.simps(1) canrepr_0 diff_Suc_1 drop0 le_eq_less_or_eq\n     nth_list_update_eq nth_list_update_neq plus_1_eq_Suc take_all zero_less_one)\n  ultimately show \"tps2 = tps1\n    [j1 := tps1 ! j1 |+| nlength x,\n     j2 := implant (tps1 ! j1) (tps1 ! j2) (nlength x)]\"\n    unfolding tps2_def tps1_def by (simp add: list_update_swap[of j1])\nqed\n\ndefinition \"tps3 \\<equiv> tps0[j2 := (\\<lfloor>x\\<rfloor>\\<^sub>N, Suc (nlength x))]\"\n\nlemma tm3 [transforms_intros]:\n  assumes \"t = 11 + (2 * nlength y + 2 * nlength x)\"\n  shows \"transforms tm3 tps0 t tps3\"\n  unfolding tm3_def\nproof (tform tps: tps2_def)\n  have \"tps2 :#: j1 = Suc (nlength x)\"\n    using assms tps2_def by (metis j(1) j_less(1) nth_list_update_eq nth_list_update_neq snd_conv)\n  then show \"t = 8 + (2 * nlength y + nlength x) + (tps2 :#: j1 + 2)\"\n    using assms by simp\n  show \"clean_tape (tps2 ! j1)\"\n    using tps2_def by (simp add: clean_tape_ncontents nth_list_update_neq')\n  have \"tps2 ! j1 |#=| 1 = (\\<lfloor>x\\<rfloor>\\<^sub>N, 1)\"\n    using tps2_def by (simp add: nth_list_update_neq')\n  then show \"tps3 = tps2[j1 := tps2 ! j1 |#=| 1]\"\n    using tps3_def tps2_def by (metis j(1) list_update_id list_update_overwrite list_update_swap tps_j1)\nqed\n\ndefinition \"tps4 \\<equiv> tps0[j2 := (\\<lfloor>x\\<rfloor>\\<^sub>N, 1)]\"\n\nlemma tm4:\n  assumes \"t = 14 + (3 * nlength x + 2 * nlength y)\"\n  shows \"transforms tm4 tps0 t tps4\"\n  unfolding tm4_def\nproof (tform tps: tps3_def time: tps3_def assms)\n  show \"clean_tape (tps3 ! j2)\"\n    using tps3_def clean_tape_ncontents by simp\n  have \"tps3 ! j2 |#=| 1 = (\\<lfloor>x\\<rfloor>\\<^sub>N, 1)\"\n    using tps3_def by (simp add: nth_list_update_neq')\n  then show \"tps4 = tps3[j2 := tps3 ! j2 |#=| 1]\"\n    using tps4_def tps3_def by (metis list_update_overwrite tps_j1)\nqed\n\nlemma tm4':\n  assumes \"t = 14 + 3 * (nlength x + nlength y)\"\n  shows \"transforms tm4 tps0 t tps4\"\n  using tm4 transforms_monotone assms by simp\n\nend\n\nend  (* locale turing_machine_move *)\n\nlemma transforms_tm_copynI [transforms_intros]:\n  fixes j1 j2 :: tapeidx\n  fixes tps tps' :: \"tape list\" and k x y :: nat\n  assumes \"j1 \\<noteq> j2\" \"j1 < length tps\" \"j2 < length tps\"\n  assumes\n    \"tps ! j1 = (\\<lfloor>x\\<rfloor>\\<^sub>N, 1)\"\n    \"tps ! j2 = (\\<lfloor>y\\<rfloor>\\<^sub>N, 1)\"\n  assumes \"ttt = 14 + 3 * (nlength x + nlength y)\"\n  assumes \"tps' = tps\n    [j2 := (\\<lfloor>x\\<rfloor>\\<^sub>N, 1)]\"\n  shows \"transforms (tm_copyn j1 j2) tps ttt tps'\"\nproof -\n  interpret loc: turing_machine_move j1 j2 .\n  show ?thesis\n    using assms loc.tm4' loc.tps4_def loc.tm4_eq_tm_copyn by simp\nqed\n\n\nsubsubsection \\<open>Setting the tape contents to a number\\<close>\n\ntext \\<open>\nThe Turing machine in this section writes a hard-coded number to a tape.\n\\<close>\n\ndefinition tm_setn :: \"tapeidx \\<Rightarrow> nat \\<Rightarrow> machine\" where\n  \"tm_setn j n \\<equiv> tm_set j (canrepr n)\"\n\nlemma tm_setn_tm:\n  assumes \"k \\<ge> 2\" and \"G \\<ge> 4\" and \"j < k\" and \"0 < j \"\n  shows \"turing_machine k G (tm_setn j n)\"\nproof -\n  have \"symbols_lt G (canrepr n)\"\n    using assms(2) bit_symbols_canrepr by fastforce\n  then show ?thesis\n    unfolding tm_setn_def using tm_set_tm assms by simp\nqed\n\nlemma transforms_tm_setnI [transforms_intros]:\n  fixes j :: tapeidx\n  fixes tps tps' :: \"tape list\" and x k n :: nat\n  assumes \"j < length tps\"\n  assumes \"tps ! j = (\\<lfloor>x\\<rfloor>\\<^sub>N, 1)\"\n  assumes \"t = 10 + 2 * nlength x + 2 * nlength n\"\n  assumes \"tps' = tps[j := (\\<lfloor>n\\<rfloor>\\<^sub>N, 1)]\"\n  shows \"transforms (tm_setn j n) tps t tps'\"\n  unfolding tm_setn_def\n  using transforms_tm_setI[OF assms(1), of \"canrepr x\" \"canrepr n\" t tps'] assms\n    canonical_canrepr canonical_def contents_clean_tape'\n  by (simp add: eval_nat_numeral(3) numeral_Bit0 proper_symbols_canrepr)\n\n\nsubsection \\<open>Incrementing\\<close>\n\ntext \\<open>\nIn this section we devise a Turing machine that increments a number. The next\nfunction describes how the symbol sequence of the incremented number looks like.\nBasically one has to flip all @{text \\<one>} symbols starting at the least\nsignificant digit until one reaches a @{text \\<zero>}, which is then replaced by a\n@{text \\<one>}.  If there is no @{text \\<zero>}, a @{text \\<one>} is appended. Here we\nexploit that the most significant digit is to the right.\n\\<close>\n\ndefinition nincr :: \"symbol list \\<Rightarrow> symbol list\" where\n  \"nincr zs \\<equiv>\n     if \\<exists>i<length zs. zs ! i = \\<zero>\n     then replicate (LEAST i. i < length zs \\<and> zs ! i = \\<zero>) \\<zero> @ [\\<one>] @ drop (Suc (LEAST i. i < length zs \\<and> zs ! i = \\<zero>)) zs\n     else replicate (length zs) \\<zero> @ [\\<one>]\"\n\nlemma canonical_nincr:\n  assumes \"canonical zs\"\n  shows \"canonical (nincr zs)\"\nproof -\n  have 1: \"bit_symbols zs\"\n    using canonical_def assms by simp\n  let ?j = \"LEAST i. i < length zs \\<and> zs ! i = \\<zero>\"\n  have \"bit_symbols (nincr zs)\"\n  proof (cases \"\\<exists>i<length zs. zs ! i = \\<zero>\")\n    case True\n    then have \"nincr zs = replicate ?j \\<zero> @ [\\<one>] @ drop (Suc ?j) zs\"\n      using nincr_def by simp\n    moreover have \"bit_symbols (replicate ?j \\<zero>)\"\n      by simp\n    moreover have \"bit_symbols [\\<one>]\"\n      by simp\n    moreover have \"bit_symbols (drop (Suc ?j) zs)\"\n      using 1 by simp\n    ultimately show ?thesis\n      using bit_symbols_append by presburger\n  next\n    case False\n    then show ?thesis\n      using nincr_def bit_symbols_append by auto\n  qed\n  moreover have \"last (nincr zs) = \\<one>\"\n  proof (cases \"\\<exists>i<length zs. zs ! i = \\<zero>\")\n    case True\n    then show ?thesis\n      using nincr_def assms canonical_def by auto\n  next\n    case False\n    then show ?thesis\n      using nincr_def by auto\n  qed\n  ultimately show ?thesis\n    using canonical_def by simp\nqed\n\nlemma nincr:\n  assumes \"bit_symbols zs\"\n  shows \"num (nincr zs) = Suc (num zs)\"\nproof (cases \"\\<exists>i<length zs. zs ! i = \\<zero>\")\n  case True\n  define j where \"j = (LEAST i. i < length zs \\<and> zs ! i = \\<zero>)\"\n  then have 1: \"j < length zs \\<and> zs ! j = \\<zero>\"\n    using LeastI_ex[OF True] by simp\n  have 2: \"zs ! i = \\<one>\" if \"i < j\" for i\n    using that True j_def assms \"1\" less_trans not_less_Least by blast\n\n  define xs :: \"symbol list\" where \"xs = replicate j \\<one> @ [\\<zero>]\"\n  define ys :: \"symbol list\" where \"ys = drop (Suc j) zs\"\n  have \"zs = xs @ ys\"\n  proof -\n    have \"xs = take (Suc j) zs\"\n      using xs_def 1 2\n      by (smt (verit, best) le_eq_less_or_eq length_replicate length_take min_absorb2 nth_equalityI\n       nth_replicate nth_take take_Suc_conv_app_nth)\n    then show ?thesis\n      using ys_def by simp\n  qed\n\n  have \"nincr zs = replicate j \\<zero> @ [\\<one>] @ drop (Suc j) zs\"\n    using nincr_def True j_def by simp\n  then have \"num (nincr zs) = num (replicate j \\<zero> @ [\\<one>] @ ys)\"\n    using ys_def by simp\n  also have \"... = num (replicate j \\<zero> @ [\\<one>]) + 2 ^ Suc j * num ys\"\n    using num_append by (metis append_assoc length_append_singleton length_replicate)\n  also have \"... = Suc (num xs) + 2 ^ Suc j * num ys\"\n  proof -\n    have \"num (replicate j \\<zero> @ [\\<one>]) = 2 ^ j\"\n      using num_replicate2_eq_pow by simp\n    also have \"... = Suc (2 ^ j - 1)\"\n      by simp\n    also have \"... = Suc (num (replicate j \\<one>))\"\n      using num_replicate3_eq_pow_minus_1 by simp\n    also have \"... = Suc (num (replicate j \\<one> @ [\\<zero>]))\"\n      using num_trailing_zero by simp\n    finally have \"num (replicate j \\<zero> @ [\\<one>]) = Suc (num xs)\"\n      using xs_def by simp\n    then show ?thesis\n      by simp\n  qed\n  also have \"... = Suc (num xs + 2 ^ Suc j * num ys)\"\n    by simp\n  also have \"... = Suc (num zs)\"\n    using `zs = xs @ ys` num_append xs_def by (metis length_append_singleton length_replicate)\n  finally show ?thesis .\nnext\n  case False\n  then have \"\\<forall>i<length zs. zs ! i = \\<one>\"\n    using assms by simp\n  then have zs: \"zs = replicate (length zs) \\<one>\"\n    by (simp add: nth_equalityI)\n  then have num_zs: \"num zs = 2 ^ length zs - 1\"\n    by (metis num_replicate3_eq_pow_minus_1)\n  have \"nincr zs = replicate (length zs) \\<zero> @ [\\<one>]\"\n    using nincr_def False by auto\n  then have \"num (nincr zs) = 2 ^ length zs\"\n    by (simp add: num_replicate2_eq_pow)\n  then show ?thesis\n    using num_zs by simp\nqed\n\nlemma nincr_canrepr: \"nincr (canrepr n) = canrepr (Suc n)\"\n  using canrepr canonical_canrepr canreprI bit_symbols_canrepr canonical_nincr nincr\n  by metis\n\ntext \\<open>\nThe next Turing machine performs the incrementing. Starting from the left of the\nsymbol sequence on tape $j$, it writes the symbol \\textbf{0} until it reaches a\nblank or the symbol \\textbf{1}. Then it writes a \\textbf{1} and returns the tape\nhead to the beginning.\n\\<close>\n\ndefinition tm_incr :: \"tapeidx \\<Rightarrow> machine\" where\n  \"tm_incr j \\<equiv> tm_const_until j j {\\<box>, \\<zero>} \\<zero> ;; tm_write j \\<one> ;; tm_cr j\"\n\nlemma tm_incr_tm:\n  assumes \"G \\<ge> 4\" and \"k \\<ge> 2\" and \"j < k\" and \"j > 0\"\n  shows \"turing_machine k G (tm_incr j)\"\n  unfolding tm_incr_def using assms tm_const_until_tm tm_write_tm tm_cr_tm by simp\n\nlocale turing_machine_incr =\n  fixes j :: tapeidx\nbegin\n\ndefinition \"tm1 \\<equiv> tm_const_until j j {\\<box>, \\<zero>} \\<zero>\"\ndefinition \"tm2 \\<equiv> tm1 ;; tm_write j \\<one>\"\ndefinition \"tm3 \\<equiv> tm2 ;; tm_cr j\"\n\nlemma tm3_eq_tm_incr: \"tm3 = tm_incr j\"\n  unfolding tm3_def tm2_def tm1_def tm_incr_def by simp\n\ncontext\n  fixes x k :: nat and tps :: \"tape list\"\n  assumes jk [simp]: \"j < k\" \"length tps = k\"\n    and tps0 [simp]: \"tps ! j = (\\<lfloor>x\\<rfloor>\\<^sub>N, 1)\"\nbegin\n\nlemma tm1 [transforms_intros]:\n  assumes \"i0 = (LEAST i. i \\<le> nlength x \\<and> \\<lfloor>x\\<rfloor>\\<^sub>N (Suc i) \\<in> {\\<box>, \\<zero>})\"\n    and \"tps' = tps[j := constplant (tps ! j) \\<zero> i0]\"\n  shows \"transforms tm1 tps (Suc i0) tps'\"\n  unfolding tm1_def\nproof (tform tps: assms(2))\n  let ?P = \"\\<lambda>i. i \\<le> nlength x \\<and> \\<lfloor>x\\<rfloor>\\<^sub>N (Suc i) \\<in> {\\<box>, \\<zero>}\"\n  have 2: \"i0 \\<le> nlength x \\<and> \\<lfloor>x\\<rfloor>\\<^sub>N (Suc i0) \\<in> {\\<box>, \\<zero>}\"\n    using LeastI[of ?P \"nlength x\"] jk(1) assms(1) by simp\n  have 3: \"\\<not> ?P i\" if \"i < i0\" for i\n    using not_less_Least[of i ?P] jk(1) assms(1) that by simp\n  show \"rneigh (tps ! j) {\\<box>, \\<zero>} i0\"\n  proof (rule rneighI)\n    show \"(tps ::: j) (tps :#: j + i0) \\<in> {\\<box>, \\<zero>}\"\n      using tps0 2 jk(1) assms(1) by simp\n    show \"\\<And>n'. n' < i0 \\<Longrightarrow> (tps ::: j) (tps :#: j + n') \\<notin> {\\<box>, \\<zero>}\"\n      using tps0 2 3 jk(1) assms(1) by simp\n  qed\nqed\n\nlemma tm2 [transforms_intros]:\n  assumes \"i0 = (LEAST i. i \\<le> nlength x \\<and> \\<lfloor>x\\<rfloor>\\<^sub>N (Suc i) \\<in> {\\<box>, \\<zero>})\"\n    and \"ttt = Suc (Suc i0)\"\n    and \"tps' = tps[j := (\\<lfloor>Suc x\\<rfloor>\\<^sub>N, Suc i0)]\"\n  shows \"transforms tm2 tps ttt tps'\"\n  unfolding tm2_def\nproof (tform tps: assms(1,3) time: assms(1,2))\n  let ?P = \"\\<lambda>i. i \\<le> nlength x \\<and> \\<lfloor>x\\<rfloor>\\<^sub>N (Suc i) \\<in> {\\<box>, \\<zero>}\"\n  have 1: \"?P (nlength x)\"\n    by simp\n  have 2: \"i0 \\<le> nlength x \\<and> \\<lfloor>x\\<rfloor>\\<^sub>N (Suc i0) \\<in> {\\<box>, \\<zero>}\"\n    using LeastI[of ?P \"nlength x\"] assms(1) by simp\n  have 3: \"\\<not> ?P i\" if \"i < i0\" for i\n    using not_less_Least[of i ?P] assms(1) that by simp\n  let ?i = \"LEAST i. i \\<le> nlength x \\<and> \\<lfloor>x\\<rfloor>\\<^sub>N (Suc i) \\<in> {\\<box>, \\<zero>}\"\n  show \"tps' = tps\n    [j := constplant (tps ! j) 2 ?i,\n     j := tps[j := constplant (tps ! j) \\<zero> ?i] ! j |:=| \\<one>]\"\n     (is \"tps' = ?rhs\")\n  proof -\n    have \"?rhs = tps [j := constplant (\\<lfloor>x\\<rfloor>\\<^sub>N, Suc 0) \\<zero> i0 |:=| \\<one>]\"\n      using jk assms(1) by simp\n    moreover have \"(\\<lfloor>Suc x\\<rfloor>\\<^sub>N, Suc i0) = constplant (\\<lfloor>x\\<rfloor>\\<^sub>N, Suc 0) 2 i0 |:=| \\<one>\"\n      (is \"?l = ?r\")\n    proof -\n      have \"snd ?l = snd ?r\"\n        by (simp add: transplant_def)\n      moreover have \"\\<lfloor>Suc x\\<rfloor>\\<^sub>N = fst ?r\"\n      proof -\n        let ?zs = \"canrepr x\"\n        have l: \"\\<lfloor>Suc x\\<rfloor>\\<^sub>N = \\<lfloor>nincr ?zs\\<rfloor>\"\n          by (simp add: nincr_canrepr)\n        have r: \"fst ?r = (\\<lambda>i. if Suc 0 \\<le> i \\<and> i < Suc i0 then \\<zero> else \\<lfloor>x\\<rfloor>\\<^sub>N i)(Suc i0 := \\<one>)\"\n          using constplant by auto\n        show ?thesis\n        proof (cases \"\\<exists>i<length ?zs. ?zs ! i = \\<zero>\")\n          case True\n          let ?Q = \"\\<lambda>i. i < length ?zs \\<and> ?zs ! i = \\<zero>\"\n          have Q1: \"?Q (Least ?Q)\"\n            using True by (metis (mono_tags, lifting) LeastI_ex)\n          have Q2: \"\\<not> ?Q i\" if \"i < Least ?Q\" for i\n            using True not_less_Least that by blast\n          have \"Least ?P = Least ?Q\"\n          proof (rule Least_equality)\n            show \"Least ?Q \\<le> nlength x \\<and> \\<lfloor>x\\<rfloor>\\<^sub>N (Suc (Least ?Q)) \\<in> {\\<box>, \\<zero>}\"\n            proof\n              show \"Least ?Q \\<le> nlength x\"\n                using True by (metis (mono_tags, lifting) LeastI_ex less_imp_le)\n              show \"\\<lfloor>x\\<rfloor>\\<^sub>N (Suc (Least ?Q)) \\<in> {\\<box>, \\<zero>}\"\n                using True by (simp add: Q1 Suc_leI)\n            qed\n            then show \"\\<And>y. y \\<le> nlength x \\<and> \\<lfloor>x\\<rfloor>\\<^sub>N (Suc y) \\<in> {\\<box>, \\<zero>} \\<Longrightarrow> (Least ?Q) \\<le> y\"\n              using True Q1 Q2 bit_symbols_canrepr contents_def\n              by (smt (z3) Least_le Suc_leI bot_nat_0.not_eq_extremum diff_Suc_1 insert_iff le_neq_implies_less\n                nat.simps(3) nlength_0_simp nlength_le_n nlength_less_n singletonD)\n          qed\n          then have i0: \"i0 = Least ?Q\"\n            using assms(1) by simp\n          then have nincr_zs: \"nincr ?zs = replicate i0 \\<zero> @ [\\<one>] @ drop (Suc i0) ?zs\"\n            using nincr_def True by simp\n          show ?thesis\n          proof\n            fix i\n            consider\n               \"i = 0\"\n             | \"Suc 0 \\<le> i \\<and> i < Suc i0\"\n             | \"i = Suc i0\"\n             | \"i > Suc i0 \\<and> i \\<le> length ?zs\"\n             | \"i > Suc i0 \\<and> i > length ?zs\"\n              by linarith\n            then have \"\\<lfloor>replicate i0 \\<zero> @ [\\<one>] @ drop (Suc i0) ?zs\\<rfloor> i =\n                ((\\<lambda>i. if Suc 0 \\<le> i \\<and> i < Suc i0 then \\<zero> else \\<lfloor>x\\<rfloor>\\<^sub>N i)(Suc i0 := \\<one>)) i\"\n                (is \"?A i = ?B i\")\n            proof (cases)\n              case 1\n              then show ?thesis\n                by (simp add: transplant_def)\n            next\n              case 2\n              then have \"i - 1 < i0\"\n                by auto\n              then have \"(replicate i0 \\<zero> @ [\\<one>] @ drop (Suc i0) ?zs) ! (i - 1) = \\<zero>\"\n                by (metis length_replicate nth_append nth_replicate)\n              then have \"?A i = \\<zero>\"\n                using contents_def i0 \"2\" Q1 nincr_canrepr nincr_zs\n                by (metis Suc_le_lessD le_trans less_Suc_eq_le less_imp_le_nat less_numeral_extra(3) nlength_Suc_le)\n              moreover have \"?B i = \\<zero>\"\n                using i0 2 by simp\n              ultimately show ?thesis\n                by simp\n            next\n              case 3\n              then show ?thesis\n                using i0 Q1 canrepr_0 contents_inbounds nincr_canrepr nincr_zs nlength_0_simp nlength_Suc nlength_Suc_le\n                by (smt (z3) Suc_leI append_Cons diff_Suc_1 fun_upd_apply le_trans length_replicate\n                  nth_append_length zero_less_Suc)\n            next\n              case 4\n              then have \"?A i = (replicate i0 \\<zero> @ [\\<one>] @ drop (Suc i0) ?zs) ! (i - 1)\"\n                by auto\n              then have \"?A i = ((replicate i0 \\<zero> @ [\\<one>]) @ drop (Suc i0) ?zs) ! (i - 1)\"\n                by simp\n              moreover have \"length (replicate i0 \\<zero> @ [\\<one>]) = Suc i0\"\n                by simp\n              moreover have \"i - 1 < length ?zs\"\n                using 4 by auto\n              moreover have \"i - 1 >= Suc i0\"\n                using 4 by auto\n              ultimately have \"?A i = ?zs ! (i - 1)\"\n                using i0 Q1\n                by (metis (no_types, lifting) Suc_leI append_take_drop_id length_take min_absorb2 not_le nth_append)\n              moreover have \"?B i = \\<lfloor>x\\<rfloor>\\<^sub>N i\"\n                using 4 by simp\n              ultimately show ?thesis\n                using i0 4 contents_def by simp\n            next\n              case 5\n              then show ?thesis\n                by auto\n            qed\n            then show \"\\<lfloor>Suc x\\<rfloor>\\<^sub>N i = fst (constplant (\\<lfloor>x\\<rfloor>\\<^sub>N, Suc 0) \\<zero> i0 |:=| \\<one>) i\"\n              using nincr_zs l r by simp\n          qed\n        next\n          case False\n          then have nincr_zs: \"nincr ?zs = replicate (length ?zs) \\<zero> @ [\\<one>]\"\n            using nincr_def by auto\n          have \"Least ?P = length ?zs\"\n          proof (rule Least_equality)\n            show \"nlength x \\<le> nlength x \\<and> \\<lfloor>x\\<rfloor>\\<^sub>N (Suc (nlength x)) \\<in> {\\<box>, \\<zero>}\"\n              by simp\n            show \"\\<And>y. y \\<le> nlength x \\<and> \\<lfloor>x\\<rfloor>\\<^sub>N (Suc y) \\<in> {\\<box>, \\<zero>} \\<Longrightarrow> nlength x \\<le> y\"\n              using False contents_def bit_symbols_canrepr\n              by (metis diff_Suc_1 insert_iff le_neq_implies_less nat.simps(3) not_less_eq_eq numeral_3_eq_3 singletonD)\n          qed\n          then have i0: \"i0 = length ?zs\"\n            using assms(1) by simp\n          show ?thesis\n          proof\n            fix i\n            consider \"i = 0\" | \"Suc 0 \\<le> i \\<and> i < Suc (length ?zs)\" | \"i = Suc (length ?zs)\" | \"i > Suc (length ?zs)\"\n              by linarith\n            then have \"\\<lfloor>replicate (length ?zs) \\<zero> @ [\\<one>]\\<rfloor> i =\n                ((\\<lambda>i. if Suc 0 \\<le> i \\<and> i < Suc i0 then \\<zero> else \\<lfloor>x\\<rfloor>\\<^sub>N i)(Suc i0 := \\<one>)) i\"\n                (is \"?A i = ?B i\")\n            proof (cases)\n              case 1\n              then show ?thesis\n                by (simp add: transplant_def)\n            next\n              case 2\n              then have \"?A i = \\<zero>\"\n                by (metis One_nat_def Suc_le_lessD add.commute contents_def diff_Suc_1 length_Cons length_append\n                  length_replicate less_Suc_eq_0_disj less_imp_le_nat less_numeral_extra(3) list.size(3) nth_append\n                   nth_replicate plus_1_eq_Suc)\n              moreover have \"?B i = \\<zero>\"\n                using i0 2 by simp\n              ultimately show ?thesis\n                by simp\n            next\n              case 3\n              then show ?thesis\n                using i0 canrepr_0 contents_inbounds nincr_canrepr nincr_zs nlength_0_simp nlength_Suc\n                by (metis One_nat_def add.commute diff_Suc_1 fun_upd_apply length_Cons length_append\n                  length_replicate nth_append_length plus_1_eq_Suc zero_less_Suc)\n            next\n              case 4\n              then show ?thesis\n                using i0 by simp\n            qed\n            then show \"\\<lfloor>Suc x\\<rfloor>\\<^sub>N i = fst (constplant (\\<lfloor>x\\<rfloor>\\<^sub>N, Suc 0) \\<zero> i0 |:=| \\<one>) i\"\n              using nincr_zs l r by simp\n          qed\n        qed\n      qed\n      ultimately show ?thesis\n        by simp\n    qed\n    ultimately show ?thesis\n      using assms(3) by simp\n  qed\nqed\n\nlemma tm3:\n  assumes \"i0 = (LEAST i. i \\<le> nlength x \\<and> \\<lfloor>x\\<rfloor>\\<^sub>N (Suc i) \\<in> {\\<box>, \\<zero>})\"\n    and \"ttt = 5 + 2 * i0\"\n    and \"tps' = tps[j := (\\<lfloor>Suc x\\<rfloor>\\<^sub>N, Suc 0)]\"\n  shows \"transforms tm3 tps ttt tps'\"\n  unfolding tm3_def\nproof (tform tps: assms(1,3) time: assms(1,2))\n  let ?tps = \"tps[j := (\\<lfloor>Suc x\\<rfloor>\\<^sub>N, Suc (LEAST i. i \\<le> nlength x \\<and> \\<lfloor>x\\<rfloor>\\<^sub>N (Suc i) \\<in> {\\<box>, \\<zero>}))]\"\n  show \"clean_tape (?tps ! j)\"\n    using clean_tape_ncontents by (simp add: assms(1,3))\nqed\n\nlemma tm3':\n  assumes \"ttt = 5 + 2 * nlength x\"\n    and \"tps' = tps[j := (\\<lfloor>Suc x\\<rfloor>\\<^sub>N, Suc 0)]\"\n  shows \"transforms tm3 tps ttt tps'\"\nproof -\n  let ?P = \"\\<lambda>i. i \\<le> nlength x \\<and> \\<lfloor>x\\<rfloor>\\<^sub>N (Suc i) \\<in> {\\<box>, \\<zero>}\"\n  define i0 where \"i0 = Least ?P\"\n  have \"i0 \\<le> nlength x \\<and> \\<lfloor>x\\<rfloor>\\<^sub>N (Suc i0) \\<in> {\\<box>, \\<zero>}\"\n    using LeastI[of ?P \"nlength x\"] i0_def by simp\n  then have \"5 + 2 * i0 \\<le> 5 + 2 * nlength x\"\n    by simp\n  moreover have \"transforms tm3 tps (5 + 2 * i0) tps'\"\n    using assms tm3 i0_def by simp\n  ultimately show ?thesis\n    using transforms_monotone assms(1) by simp\nqed\n\nend  (* context *)\n\nend  (* locale *)\n\nlemma transforms_tm_incrI [transforms_intros]:\n  assumes \"j < k\"\n    and \"length tps = k\"\n    and \"tps ! j = (\\<lfloor>x\\<rfloor>\\<^sub>N, 1)\"\n    and \"ttt = 5 + 2 * nlength x\"\n    and \"tps' = tps[j := (\\<lfloor>Suc x\\<rfloor>\\<^sub>N, 1)]\"\n  shows \"transforms (tm_incr j) tps ttt tps'\"\nproof -\n  interpret loc: turing_machine_incr j .\n  show ?thesis\n    using assms loc.tm3' loc.tm3_eq_tm_incr by simp\nqed\n\n\nsubsubsection \\<open>Incrementing multiple times\\<close>\n\ntext \\<open>\nAdding a constant by iteratively incrementing is not exactly efficient, but it\nstill only takes constant time and thus does not endanger any time bounds.\n\\<close>\n\nfun tm_plus_const :: \"nat \\<Rightarrow> tapeidx \\<Rightarrow> machine\" where\n  \"tm_plus_const 0 j = []\" |\n  \"tm_plus_const (Suc c) j = tm_plus_const c j ;; tm_incr j\"\n\nlemma tm_plus_const_tm:\n  assumes \"k \\<ge> 2\" and \"G \\<ge> 4\" and \"0 < j\" and \"j < k\"\n  shows \"turing_machine k G (tm_plus_const c j)\"\n  using assms Nil_tm tm_incr_tm by (induction c) simp_all\n\nlemma transforms_tm_plus_constI [transforms_intros]:\n  fixes c :: nat\n  assumes \"j < k\"\n    and \"j > 0\"\n    and \"length tps = k\"\n    and \"tps ! j = (\\<lfloor>x\\<rfloor>\\<^sub>N, 1)\"\n    and \"ttt = c * (5 + 2 * nlength (x + c))\"\n    and \"tps' = tps[j := (\\<lfloor>x + c\\<rfloor>\\<^sub>N, 1)]\"\n  shows \"transforms (tm_plus_const c j) tps ttt tps'\"\n  using assms(5,6,4)\nproof (induction c arbitrary: ttt tps')\n  case 0\n  then show ?case\n    using transforms_Nil assms\n    by (metis add_cancel_left_right list_update_id mult_eq_0_iff tm_plus_const.simps(1))\nnext\n  case (Suc c)\n  define tpsA where \"tpsA = tps[j := (\\<lfloor>x + c\\<rfloor>\\<^sub>N, 1)]\"\n  let ?ttt = \"c * (5 + 2 * nlength (x + c)) + (5 + 2 * nlength (x + c))\"\n  have \"transforms (tm_plus_const c j ;; tm_incr j) tps ?ttt tps'\"\n  proof (tform tps: assms)\n    show \"transforms (tm_plus_const c j) tps (c * (5 + 2 * nlength (x + c))) tpsA\"\n      using tpsA_def assms Suc by simp\n    show \"j < length tpsA\"\n      using tpsA_def assms(1,3) by simp\n    show \"tpsA ! j = (\\<lfloor>x + c\\<rfloor>\\<^sub>N, 1)\"\n      using tpsA_def assms(1,3) by simp\n    show \"tps' = tpsA[j := (\\<lfloor>Suc (x + c)\\<rfloor>\\<^sub>N, 1)]\"\n      using tpsA_def assms Suc by (metis add_Suc_right list_update_overwrite)\n  qed\n  moreover have \"?ttt \\<le> ttt\"\n  proof -\n    have \"?ttt = Suc c * (5 + 2 * nlength (x + c))\"\n      by simp\n    also have \"... \\<le> Suc c * (5 + 2 * nlength (x + Suc c))\"\n      using nlength_mono Suc_mult_le_cancel1 by auto\n    finally show \"?ttt \\<le> ttt\"\n      using Suc by simp\n  qed\n  ultimately have \"transforms (tm_plus_const c j ;; tm_incr j) tps ttt tps'\"\n    using transforms_monotone by simp\n  then show ?case\n    by simp\nqed\n\n\nsubsection \\<open>Decrementing\\<close>\n\ntext \\<open>\nDecrementing a number is almost like incrementing but with the symbols\n\\textbf{0} and \\textbf{1} swapped. One difference is that in order to get a\ncanonical symbol sequence, a trailing zero must be removed, whereas incrementing\ncannot result in a trailing zero. Another difference is that decrementing the\nnumber zero yields zero.\n\nThe next function returns the leftmost symbol~\\textbf{1}, that is, the one\nthat needs to be flipped.\n\\<close>\n\ndefinition first1 :: \"symbol list \\<Rightarrow> nat\" where\n  \"first1 zs \\<equiv> LEAST i. i < length zs \\<and> zs ! i = \\<one>\"\n\nlemma canonical_ex_3:\n  assumes \"canonical zs\" and \"zs \\<noteq> []\"\n  shows \"\\<exists>i<length zs. zs ! i = \\<one>\"\n  using assms canonical_def by (metis One_nat_def Suc_pred last_conv_nth length_greater_0_conv lessI)\n\nlemma canonical_first1:\n  assumes \"canonical zs\" and \"zs \\<noteq> []\"\n  shows \"first1 zs < length zs \\<and> zs ! first1 zs = \\<one>\"\n  using assms canonical_ex_3 by (metis (mono_tags, lifting) LeastI first1_def)\n\nlemma canonical_first1_less:\n  assumes \"canonical zs\" and \"zs \\<noteq> []\"\n  shows \"\\<forall>i<first1 zs. zs ! i = \\<zero>\"\nproof -\n  have \"\\<forall>i<first1 zs. zs ! i \\<noteq> \\<one>\"\n    using assms first1_def canonical_first1 not_less_Least by fastforce\n  then show ?thesis\n    using assms canonical_def by (meson canonical_first1 less_trans)\nqed\n\ntext \\<open>\nThe next function describes how the canonical representation of the decremented\nsymbol sequence looks like. It has special cases for the empty sequence and for\nsequences whose only \\textbf{1} is the most significant digit.\n\\<close>\n\ndefinition ndecr :: \"symbol list \\<Rightarrow> symbol list\" where\n  \"ndecr zs \\<equiv>\n    if zs = [] then []\n    else if first1 zs = length zs - 1\n      then replicate (first1 zs) \\<one>\n      else replicate (first1 zs) \\<one> @ [\\<zero>] @ drop (Suc (first1 zs)) zs\"\n\nlemma canonical_ndecr:\n  assumes \"canonical zs\"\n  shows \"canonical (ndecr zs)\"\nproof -\n  let ?i = \"first1 zs\"\n  consider\n      \"zs = []\"\n    | \"zs \\<noteq> [] \\<and> first1 zs = length zs - 1\"\n    | \"zs \\<noteq> [] \\<and> first1 zs < length zs - 1\"\n    using canonical_first1 assms by fastforce\n  then show ?thesis\n  proof (cases)\n    case 1\n    then show ?thesis\n      using ndecr_def canonical_def by simp\n  next\n    case 2\n    then show ?thesis\n      using canonical_def ndecr_def not_less_eq by fastforce\n  next\n    case 3\n    then have \"Suc (first1 zs) < length zs\"\n      by auto\n    then have \"last (drop (Suc (first1 zs)) zs) = \\<one>\"\n      using assms canonical_def 3 by simp\n    moreover have \"bit_symbols (replicate (first1 zs) \\<one> @ [\\<zero>] @ drop (Suc (first1 zs)) zs)\"\n    proof -\n      have \"bit_symbols (replicate (first1 zs) \\<one>)\"\n        by simp\n      moreover have \"bit_symbols [\\<zero>]\"\n        by simp\n      moreover have \"bit_symbols (drop (Suc (first1 zs)) zs)\"\n        using assms canonical_def by simp\n      ultimately show ?thesis\n        using bit_symbols_append by presburger\n    qed\n    ultimately show ?thesis\n      using canonical_def ndecr_def 3 by auto\n  qed\nqed\n\nlemma ndecr:\n  assumes \"canonical zs\"\n  shows \"num (ndecr zs) = num zs - 1\"\nproof -\n  let ?i = \"first1 zs\"\n  consider \"zs = []\" | \"zs \\<noteq> [] \\<and> first1 zs = length zs - 1\" | \"zs \\<noteq> [] \\<and> first1 zs < length zs - 1\"\n    using canonical_first1 assms by fastforce\n  then show ?thesis\n  proof (cases)\n    case 1\n    then show ?thesis\n      using ndecr_def canrepr_0 canrepr by (metis zero_diff)\n  next\n    case 2\n    then have less: \"zs ! i = \\<zero>\" if \"i < first1 zs\" for i\n      using that assms canonical_first1_less by simp\n    have at: \"zs ! (first1 zs) = \\<one>\"\n      using 2 canonical_first1 assms by blast\n    have \"zs = replicate (first1 zs) \\<zero> @ [\\<one>]\" (is \"zs = ?zs\")\n    proof (rule nth_equalityI)\n      show len: \"length zs = length ?zs\"\n        using 2 by simp\n      show \"zs ! i = ?zs ! i\" if \"i < length zs\" for i\n      proof (cases \"i < first1 zs\")\n        case True\n        then show ?thesis\n          by (simp add: less nth_append)\n      next\n        case False\n        then show ?thesis\n          using len that at\n          by (metis Suc_leI leD length_append_singleton length_replicate linorder_neqE_nat nth_append_length)\n      qed\n    qed\n    moreover from this have \"ndecr zs = replicate (first1 zs) 3\"\n      using ndecr_def 2 by simp\n    ultimately show ?thesis\n      using num_replicate2_eq_pow num_replicate3_eq_pow_minus_1 by metis\n  next\n    case 3\n    then have less: \"zs ! i = \\<zero>\" if \"i < ?i\" for i\n      using that assms canonical_first1_less by simp\n    have at: \"zs ! ?i = \\<one>\"\n      using 3 canonical_first1 assms by simp\n    have zs: \"zs = replicate ?i \\<zero> @ [\\<one>] @ drop (Suc ?i) zs\" (is \"zs = ?zs\")\n    proof (rule nth_equalityI)\n      show len: \"length zs = length ?zs\"\n        using 3 by auto\n      show \"zs ! i = ?zs ! i\" if \"i < length zs\" for i\n      proof -\n        consider \"i < ?i\" | \"i = ?i\" | \"i > ?i\"\n          by linarith\n        then show ?thesis\n        proof (cases)\n          case 1\n          then show ?thesis\n            using less by (metis length_replicate nth_append nth_replicate)\n        next\n          case 2\n          then show ?thesis\n            using at by (metis append_Cons length_replicate nth_append_length)\n        next\n          case 3\n          have \"?zs = (replicate ?i \\<zero> @ [\\<one>]) @ drop (Suc ?i) zs\"\n            by simp\n          then have \"?zs ! i = drop (Suc ?i) zs ! (i - Suc ?i)\"\n            using 3 by (simp add: nth_append)\n          then have \"?zs ! i = zs ! i\"\n            using 3 that by simp\n          then show ?thesis\n            by simp\n        qed\n      qed\n    qed\n    then have \"ndecr zs = replicate ?i \\<one> @ [\\<zero>] @ drop (Suc ?i) zs\"\n      using ndecr_def 3 by simp\n    then have \"Suc (num (ndecr zs)) = Suc (num ((replicate ?i \\<one> @ [\\<zero>]) @ drop (Suc ?i) zs))\"\n        (is \"_ = Suc (num (?xs @ ?ys))\")\n      by simp\n    also have \"... = Suc (num ?xs + 2 ^ length ?xs * num ?ys)\"\n      using num_append by blast\n    also have \"... = Suc (num ?xs + 2 ^ Suc ?i * num ?ys)\"\n      by simp\n    also have \"... = Suc (2 ^ ?i - 1 + 2 ^ Suc ?i * num ?ys)\"\n      using num_replicate3_eq_pow_minus_1 num_trailing_zero[of 2 \"replicate ?i \\<one>\"] by simp\n    also have \"... = 2 ^ ?i + 2 ^ Suc ?i * num ?ys\"\n      by simp\n    also have \"... = num (replicate ?i \\<zero> @ [\\<one>]) + 2 ^ Suc ?i * num ?ys\"\n      using num_replicate2_eq_pow by simp\n    also have \"... = num ((replicate ?i \\<zero> @ [\\<one>]) @ ?ys)\"\n      using num_append by (metis length_append_singleton length_replicate)\n    also have \"... = num (replicate ?i \\<zero> @ [\\<one>] @ ?ys)\"\n      by simp\n    also have \"... = num zs\"\n      using zs by simp\n    finally have \"Suc (num (ndecr zs)) = num zs\" .\n    then show ?thesis\n      by simp\n  qed\nqed\n\ntext \\<open>\nThe next Turing machine implements the function @{const ndecr}. It does nothing\non the empty input, which represents zero. On other inputs it writes symbols\n\\textbf{1} going right until it reaches a \\textbf{1} symbol, which is guaranteed\nto happen for non-empty canonical representations. It then overwrites this\n\\textbf{1} with \\textbf{0}.  If there is a blank symbol to the right of this\n\\textbf{0}, the \\textbf{0} is removed again.\n\\<close>\n\ndefinition tm_decr :: \"tapeidx \\<Rightarrow> machine\" where\n  \"tm_decr j \\<equiv>\n    IF \\<lambda>rs. rs ! j = \\<box> THEN\n      []\n    ELSE\n      tm_const_until j j {\\<one>} \\<one> ;;\n      tm_rtrans j (\\<lambda>_. \\<zero>) ;;\n      IF \\<lambda>rs. rs ! j = \\<box> THEN\n        tm_left j ;;\n        tm_write j \\<box>\n      ELSE\n        []\n      ENDIF ;;\n      tm_cr j\n    ENDIF\"\n\nlemma tm_decr_tm:\n  assumes \"G \\<ge> 4\" and \"k \\<ge> 2\" and \"j < k\" and \"0 < j\"\n  shows \"turing_machine k G (tm_decr j)\"\n  unfolding tm_decr_def\n  using assms tm_cr_tm tm_const_until_tm tm_rtrans_tm tm_left_tm tm_write_tm\n    turing_machine_branch_turing_machine Nil_tm\n  by simp\n\nlocale turing_machine_decr =\n  fixes j :: tapeidx\nbegin\n\ndefinition \"tm1 \\<equiv> tm_const_until j j {\\<one>} \\<one>\"\ndefinition \"tm2 \\<equiv> tm1 ;; tm_rtrans j (\\<lambda>_. \\<zero>)\"\ndefinition \"tm23 \\<equiv> tm_left j\"\ndefinition \"tm24 \\<equiv> tm23 ;; tm_write j \\<box>\"\ndefinition \"tm25 \\<equiv> IF \\<lambda>rs. rs ! j = \\<box> THEN tm24 ELSE [] ENDIF\"\ndefinition \"tm5 \\<equiv> tm2 ;; tm25\"\ndefinition \"tm6 \\<equiv> tm5 ;; tm_cr j\"\ndefinition \"tm7 \\<equiv> IF \\<lambda>rs. rs ! j = \\<box> THEN [] ELSE tm6 ENDIF\"\n\nlemma tm7_eq_tm_decr: \"tm7 = tm_decr j\"\n  unfolding tm1_def tm2_def tm23_def tm24_def tm25_def tm5_def tm6_def tm7_def tm_decr_def\n  by simp\n\ncontext\n  fixes tps0 :: \"tape list\" and xs :: \"symbol list\" and k :: nat\n  assumes jk: \"length tps0 = k\" \"j < k\"\n    and can: \"canonical xs\"\n    and tps0: \"tps0 ! j = (\\<lfloor>xs\\<rfloor>, 1)\"\nbegin\n\nlemma bs: \"bit_symbols xs\"\n  using can canonical_def by simp\n\ncontext\n  assumes read_tps0: \"read tps0 ! j = \\<box>\"\nbegin\n\nlemma xs_Nil: \"xs = []\"\n  using tps0 jk tapes_at_read' read_tps0 bs contents_inbounds\n  by (metis can canreprI canrepr_0 fst_conv ncontents_1_blank_iff_zero snd_conv)\n\nlemma transforms_NilI:\n  assumes \"ttt = 0\"\n    and \"tps' = tps0[j := (\\<lfloor>ndecr xs\\<rfloor>, 1)]\"\n  shows \"transforms [] tps0 ttt tps'\"\n  using transforms_Nil xs_Nil ndecr_def tps0 assms by (metis Basics.transforms_Nil list_update_id)\n\nend  (* context read tps0 ! j = 0 *)\n\ncontext\n  assumes read_tps0': \"read tps0 ! j \\<noteq> \\<box>\"\nbegin\n\nlemma xs: \"xs \\<noteq> []\"\n  using tps0 jk tapes_at_read' read_tps0' bs contents_inbounds\n  by (metis canrepr_0 fst_conv ncontents_1_blank_iff_zero snd_conv)\n\nlemma first1: \"first1 xs < length xs\" \"xs ! first1 xs = \\<one>\" \"\\<forall>i<first1 xs. xs ! i = \\<zero>\"\n  using canonical_first1[OF can xs] canonical_first1_less[OF can xs] by simp_all\n\ndefinition \"tps1 \\<equiv> tps0\n  [j := (\\<lfloor>replicate (first1 xs) \\<one> @ [\\<one>] @ (drop (Suc (first1 xs)) xs)\\<rfloor>, Suc (first1 xs))]\"\n\nlemma tm1 [transforms_intros]:\n  assumes \"ttt = Suc (first1 xs)\"\n  shows \"transforms tm1 tps0 ttt tps1\"\n  unfolding tm1_def\nproof (tform tps: tps1_def jk time: assms)\n  show \"rneigh (tps0 ! j) {\\<one>} (first1 xs)\"\n  proof (rule rneighI)\n    show \"(tps0 ::: j) (tps0 :#: j + first1 xs) \\<in> {\\<one>}\"\n      using first1(1,2) tps0 jk by (simp add: Suc_leI)\n    show \"\\<And>n'. n' < first1 xs \\<Longrightarrow> (tps0 ::: j) (tps0 :#: j + n') \\<notin> {\\<one>}\"\n      using first1(3) tps0 jk by (simp add: contents_def)\n  qed\n  show \"tps1 = tps0\n    [j := tps0 ! j |+| first1 xs,\n     j := constplant (tps0 ! j) \\<one> (first1 xs)]\"\n  proof -\n    have \"tps1 ! j = constplant (tps0 ! j) 3 (first1 xs)\"\n      (is \"_ = ?rhs\")\n    proof -\n      have \"fst ?rhs = (\\<lambda>i. if 1 \\<le> i \\<and> i < 1 + first1 xs then \\<one> else \\<lfloor>xs\\<rfloor> i)\"\n        using tps0 jk constplant by auto\n      also have \"... = \\<lfloor>replicate (first1 xs) \\<one> @ [\\<one>] @ drop (Suc (first1 xs)) xs\\<rfloor>\"\n      proof\n        fix i\n        consider\n            \"i = 0\"\n          | \"i \\<ge> 1 \\<and> i < 1 + first1 xs\"\n          | \"i = 1 + first1 xs\"\n          | \"1 + first1 xs < i \\<and> i \\<le> length xs\"\n          | \"i > length xs\"\n          by linarith\n        then show \"(if 1 \\<le> i \\<and> i < 1 + first1 xs then \\<one> else \\<lfloor>xs\\<rfloor> i) =\n          \\<lfloor>replicate (first1 xs) \\<one> @ [\\<one>] @ drop (Suc (first1 xs)) xs\\<rfloor> i\"\n          (is \"?l = ?r\")\n        proof (cases)\n          case 1\n          then show ?thesis\n            by simp\n        next\n          case 2\n          then show ?thesis\n            by (smt (verit) One_nat_def Suc_diff_Suc add_diff_inverse_nat contents_inbounds first1(1) length_append\n              length_drop length_replicate less_imp_le_nat less_le_trans list.size(3) list.size(4) not_le not_less_eq\n              nth_append nth_replicate plus_1_eq_Suc)\n        next\n          case 3\n          then show ?thesis\n            using first1\n            by (smt (verit) One_nat_def Suc_diff_Suc Suc_leI add_diff_inverse_nat append_Cons contents_inbounds\n              diff_Suc_1 length_append length_drop length_replicate less_SucI less_Suc_eq_0_disj list.size(3)\n              list.size(4) not_less_eq nth_append_length)\n        next\n          case 4\n          then have \"?r = (replicate (first1 xs) \\<one> @ [\\<one>] @ drop (Suc (first1 xs)) xs) ! (i - 1)\"\n            by auto\n          also have \"... = ((replicate (first1 xs) \\<one> @ [\\<one>]) @ drop (Suc (first1 xs)) xs) ! (i - 1)\"\n            by simp\n          also have \"... = (drop (Suc (first1 xs)) xs) ! (i - 1 - Suc (first1 xs))\"\n            using 4\n            by (metis Suc_leI add_diff_inverse_nat gr_implies_not0 leD length_append_singleton\n              length_replicate less_one nth_append plus_1_eq_Suc)\n          also have \"... = xs ! (i - 1)\"\n            using 4 by (metis Suc_leI add_diff_inverse_nat first1(1) gr_implies_not0 leD less_one nth_drop plus_1_eq_Suc)\n          also have \"... = \\<lfloor>xs\\<rfloor> i\"\n            using 4 by simp\n          also have \"... = ?l\"\n            using 4 by simp\n          finally have \"?r = ?l\" .\n          then show ?thesis\n            by simp\n        next\n          case 5\n          then show ?thesis\n            using first1(1) by simp\n        qed\n      qed\n      also have \"... = tps1 ::: j\"\n        using tps1_def jk by simp\n      finally have \"fst ?rhs = fst (tps1 ! j)\" .\n      then show ?thesis\n        using tps1_def jk constplant tps0 by simp\n    qed\n    then show ?thesis\n      using tps1_def tps0 jk by simp\n  qed\nqed\n\ndefinition \"tps2 \\<equiv> tps0\n  [j := (\\<lfloor>replicate (first1 xs) \\<one> @ [\\<zero>] @ drop (Suc (first1 xs)) xs\\<rfloor>, Suc (Suc (first1 xs)))]\"\n\nlemma tm2 [transforms_intros]:\n  assumes \"ttt = first1 xs + 2\"\n  shows \"transforms tm2 tps0 ttt tps2\"\n  unfolding tm2_def\nproof (tform tps: tps2_def tps1_def jk time: assms)\n  show \"tps2 = tps1[j := tps1 ! j |:=| \\<zero> |+| 1]\"\n    using tps1_def tps2_def jk contents_append_update by simp\nqed\n\ndefinition \"tps5 \\<equiv> tps0\n  [j := (\\<lfloor>ndecr xs\\<rfloor>, if read tps2 ! j = \\<box> then Suc (first1 xs) else Suc (Suc (first1 xs)))]\"\n\ncontext\n  assumes read_tps2: \"read tps2 ! j = \\<box>\"\nbegin\n\nlemma proper_contents_outofbounds:\n  assumes \"proper_symbols zs\" and \"\\<lfloor>zs\\<rfloor> i = \\<box>\"\n  shows \"i > length zs\"\n  using contents_def proper_symbols_ne0 assms\n  by (metis Suc_diff_1 bot_nat_0.not_eq_extremum linorder_le_less_linear not_less_eq zero_neq_one)\n\nlemma first1_eq: \"first1 xs = length xs - 1\"\nproof -\n  have \"tps2 ! j = (\\<lfloor>replicate (first1 xs) \\<one> @ [\\<zero>] @ drop (Suc (first1 xs)) xs\\<rfloor>, Suc (Suc (first1 xs)))\"\n      (is \"_ = (\\<lfloor>?zs\\<rfloor>, ?i)\")\n    using tps2_def jk by simp\n  have \"proper_symbols xs\"\n    using can bs by fastforce\n  then have *: \"proper_symbols ?zs\"\n    using proper_symbols_append[of \"[\\<zero>]\" \"drop (Suc (first1 xs)) xs\"] proper_symbols_append\n    by simp\n  have \"read tps2 ! j = \\<lfloor>?zs\\<rfloor> ?i\"\n    using tps2_def jk tapes_at_read'[of j tps2] by simp\n  then have \"\\<lfloor>?zs\\<rfloor> ?i = \\<box>\"\n    using read_tps2 by simp\n  then have \"?i > length ?zs\"\n    using * proper_contents_outofbounds by blast\n  moreover have \"length ?zs = length xs\"\n    using first1 by simp\n  ultimately have \"Suc (first1 xs) \\<ge> length xs\"\n    by simp\n  moreover have \"length xs > 0\"\n    using xs by simp\n  ultimately have \"first1 xs \\<ge> length xs - 1\"\n    by simp\n  then show ?thesis\n    using first1(1) by simp\nqed\n\nlemma drop_xs_Nil: \"drop (Suc (first1 xs)) xs = []\"\n  using first1_eq xs by simp\n\nlemma tps2_eq: \"tps2 = tps0[j := (\\<lfloor>replicate (first1 xs) \\<one> @ [\\<zero>]\\<rfloor>, Suc (Suc (first1 xs)))]\"\n  using tps2_def drop_xs_Nil jk by simp\n\ndefinition \"tps23 \\<equiv> tps0\n  [j := (\\<lfloor>replicate (first1 xs) \\<one> @ [\\<zero>]\\<rfloor>, Suc (first1 xs))]\"\n\nlemma tm23 [transforms_intros]:\n  assumes \"ttt = 1\"\n  shows \"transforms tm23 tps2 ttt tps23\"\n  unfolding tm23_def\nproof (tform tps: tps2_def tps23_def jk time: assms)\n  show \"tps23 = tps2[j := tps2 ! j |-| 1]\"\n    using tps23_def tps2_eq jk by simp\nqed\n\ndefinition \"tps24 \\<equiv> tps0\n  [j := (\\<lfloor>replicate (first1 xs) \\<one>\\<rfloor>, Suc (first1 xs))]\"\n\nlemma tm24:\n  assumes \"ttt = 2\"\n  shows \"transforms tm24 tps2 ttt tps24\"\n  unfolding tm24_def\nproof (tform tps: tps23_def tps24_def time: assms)\n  show \"tps24 = tps23[j := tps23 ! j |:=| \\<box>]\"\n  proof -\n    have \"tps23 ! j |:=| \\<box> = (\\<lfloor>replicate (first1 xs) \\<one> @ [\\<zero>]\\<rfloor>, Suc (first1 xs)) |:=| \\<box>\"\n      using tps23_def jk by simp\n    then have \"tps23 ! j |:=| \\<box> = (\\<lfloor>replicate (first1 xs) \\<one> @ [\\<box>]\\<rfloor>, Suc (first1 xs))\"\n      using contents_append_update by auto\n    then have \"tps23 ! j |:=| \\<box> = (\\<lfloor>replicate (first1 xs) \\<one>\\<rfloor>, Suc (first1 xs))\"\n      using contents_append_blanks by (metis replicate_0 replicate_Suc)\n    moreover have \"tps24 ! j = (\\<lfloor>replicate (first1 xs) \\<one>\\<rfloor>, Suc (first1 xs))\"\n      using tps24_def jk by simp\n    ultimately show ?thesis\n      using tps23_def tps24_def by auto\n  qed\nqed\n\ncorollary tm24' [transforms_intros]:\n  assumes \"ttt = 2\" and \"tps' = tps0[j := (\\<lfloor>ndecr xs\\<rfloor>, Suc (first1 xs))]\"\n  shows \"transforms tm24 tps2 ttt tps'\"\nproof -\n  have \"tps24 = tps0[j := (\\<lfloor>ndecr xs\\<rfloor>, Suc (first1 xs))]\"\n    using tps24_def jk ndecr_def first1_eq xs by simp\n  then show ?thesis\n    using assms tm24 by simp\nqed\n\nend  (* context read tps2 ! j = 0 *)\n\ncontext\n  assumes read_tps2': \"read tps2 ! j \\<noteq> \\<box>\"\nbegin\n\nlemma first1_neq: \"first1 xs \\<noteq> length xs - 1\"\nproof (rule ccontr)\n  assume eq: \"\\<not> first1 xs \\<noteq> length xs - 1\"\n\n  have \"tps2 ! j = (\\<lfloor>replicate (first1 xs) \\<one> @ [\\<zero>] @ drop (Suc (first1 xs)) xs\\<rfloor>, Suc (Suc (first1 xs)))\"\n      (is \"_ = (\\<lfloor>?zs\\<rfloor>, ?i)\")\n    using tps2_def jk by simp\n  have \"length ?zs = length xs\"\n    using first1 by simp\n  then have \"Suc (Suc (first1 xs)) = Suc (length ?zs)\"\n    using xs eq by simp\n  then have *: \"\\<lfloor>?zs\\<rfloor> ?i = 0\"\n    using contents_outofbounds by simp\n\n  have \"read tps2 ! j = \\<lfloor>?zs\\<rfloor> ?i\"\n    using tps2_def jk tapes_at_read'[of j tps2] by simp\n  then have \"\\<lfloor>?zs\\<rfloor> ?i \\<noteq> \\<box>\"\n    using read_tps2' by simp\n  then show False\n    using * by simp\nqed\n\nlemma tps2: \"tps2 = tps0[j := (\\<lfloor>ndecr xs\\<rfloor>, Suc (Suc (first1 xs)))]\"\n  using tps2_def ndecr_def first1_neq xs by simp\n\nend  (* context read tps2 ! j \\<noteq> 0 *)\n\nlemma tm25 [transforms_intros]:\n  assumes \"ttt = (if read tps2 ! j = \\<box> then 4 else 1)\"\n  shows \"transforms tm25 tps2 ttt tps5\"\n  unfolding tm25_def by (tform tps: tps2 tps5_def time: assms)\n\nlemma tm5 [transforms_intros]:\n  assumes \"ttt = first1 xs + 2 + (if read tps2 ! j = \\<box> then 4 else 1)\"\n  shows \"transforms tm5 tps0 ttt tps5\"\n  unfolding tm5_def by (tform time: assms)\n\ndefinition \"tps6 \\<equiv> tps0\n  [j := (\\<lfloor>ndecr xs\\<rfloor>, 1)]\"\n\nlemma tm6:\n  assumes \"ttt = first1 xs + 2 + (if read tps2 ! j = \\<box> then 4 else 1) + (tps5 :#: j + 2)\"\n  shows \"transforms tm6 tps0 ttt tps6\"\n  unfolding tm6_def\nproof (tform tps: tps5_def tps6_def jk time: assms)\n  show \"clean_tape (tps5 ! j)\"\n  proof -\n    have \"tps5 ::: j = \\<lfloor>ndecr xs\\<rfloor>\"\n      using tps5_def jk by simp\n    moreover have \"bit_symbols (ndecr xs)\"\n      using canonical_ndecr can canonical_def by simp\n    ultimately show ?thesis\n      using One_nat_def Suc_1 Suc_le_lessD clean_contents_proper\n      by (metis contents_clean_tape' lessI one_less_numeral_iff semiring_norm(77))\n  qed\nqed\n\nlemma tm6' [transforms_intros]:\n  assumes \"ttt = 2 * first1 xs + 9\"\n  shows \"transforms tm6 tps0 ttt tps6\"\nproof -\n  let ?ttt = \"first1 xs + 2 + (if read tps2 ! j = \\<box> then 4 else 1) + (tps5 :#: j + 2)\"\n  have \"tps5 :#: j = (if read tps2 ! j = \\<box> then Suc (first1 xs) else Suc (Suc (first1 xs)))\"\n    using tps5_def jk by simp\n  then have \"?ttt \\<le> ttt\"\n    using assms by simp\n  then show ?thesis\n    using tm6 transforms_monotone assms by simp\nqed\n\nend  (* context read tps0 ! j \\<noteq> 0 *)\n\ndefinition \"tps7 \\<equiv> tps0[j := (\\<lfloor>ndecr xs\\<rfloor>, 1)]\"\n\nlemma tm7:\n  assumes \"ttt = 8 + 2 * length xs\"\n  shows \"transforms tm7 tps0 ttt tps7\"\n  unfolding tm7_def\nproof (tform tps: tps6_def tps7_def time: assms)\n  show \"tps7 = tps0\" if \"read tps0 ! j = \\<box>\"\n    using that ndecr_def tps0 tps7_def xs_Nil jk by (simp add: list_update_same_conv)\n  show \"2 * first1 xs + 9 + 1 \\<le> ttt\" if \"read tps0 ! j \\<noteq> \\<box>\"\n  proof -\n    have \"length xs > 0\"\n      using that xs by simp\n    then show ?thesis\n      using first1(1) that assms by simp\n  qed\nqed\n\nend  (* context *)\n\nend  (* locale *)\n\nlemma transforms_tm_decrI [transforms_intros]:\n  fixes tps tps' :: \"tape list\" and n :: nat and k ttt :: nat\n  assumes \"j < k\" \"length tps = k\"\n  assumes \"tps ! j = (\\<lfloor>n\\<rfloor>\\<^sub>N, 1)\"\n  assumes \"ttt = 8 + 2 * nlength n\"\n  assumes \"tps' = tps[j := (\\<lfloor>n - 1\\<rfloor>\\<^sub>N, 1)]\"\n  shows \"transforms (tm_decr j) tps ttt tps'\"\nproof -\n  let ?xs = \"canrepr n\"\n  have can: \"canonical ?xs\"\n    using canonical_canrepr by simp\n  have tps0: \"tps ! j = (\\<lfloor>?xs\\<rfloor>, 1)\"\n    using assms by simp\n  have tps': \"tps' = tps[j := (\\<lfloor>ndecr ?xs\\<rfloor>, 1)]\"\n    using ndecr assms(5) by (metis canrepr canreprI can canonical_ndecr)\n  interpret loc: turing_machine_decr j .\n  have \"transforms loc.tm7 tps ttt tps'\"\n    using loc.tm7 loc.tps7_def by (metis assms(1,2,4) can tps' tps0)\n  then show ?thesis\n    using loc.tm7_eq_tm_decr by simp\nqed\n\n\nsubsection \\<open>Addition\\<close>\n\ntext \\<open>\nIn this section we construct a Turing machine that adds two numbers in canonical\nrepresentation each given on a separate tape and overwrites the second number\nwith the sum. The TM implements the common algorithm with carry starting from\nthe least significant digit.\n\nGiven two symbol sequences @{term xs} and @{term ys} representing numbers, the\nnext function computes the carry bit that occurs in the $i$-th position. For the\nleast significant position, 0, there is no carry (that is, it is 0); for\nposition $i + 1$ the carry is the sum of the bits of @{term xs} and @{term ys}\nin position $i$ and the carry for position $i$. The function gives the carry as\nsymbol \\textbf{0} or \\textbf{1}, except for position 0, where it is the start\nsymbol~$\\triangleright$. The start symbol represents the same bit as the\nsymbol~\\textbf{0} as defined by @{const todigit}.  The reason for this special\ntreatment is that the TM will store the carry on a memorization tape\n(see~Section~\\ref{s:tm-memorizing}), which initially contains the start symbol.\n\\<close>\n\nfun carry :: \"symbol list \\<Rightarrow> symbol list \\<Rightarrow> nat \\<Rightarrow> symbol\" where\n  \"carry xs ys 0 = 1\" |\n  \"carry xs ys (Suc i) = tosym ((todigit (digit xs i) + todigit (digit ys i) + todigit (carry xs ys i)) div 2)\"\n\ntext \\<open>\nThe next function specifies the $i$-th digit of the sum.\n\\<close>\n\ndefinition sumdigit :: \"symbol list \\<Rightarrow> symbol list \\<Rightarrow> nat \\<Rightarrow> symbol\" where\n  \"sumdigit xs ys i \\<equiv> tosym ((todigit (digit xs i) + todigit (digit ys i) + todigit (carry xs ys i)) mod 2)\"\n\nlemma carry_sumdigit: \"todigit (sumdigit xs ys i) + 2 * (todigit (carry xs ys (Suc i))) =\n    todigit (carry xs ys i) + todigit (digit xs i) + todigit (digit ys i)\"\n  using sumdigit_def by simp\n\nlemma carry_sumdigit_eq_sum:\n  \"num xs + num ys =\n   num (map (sumdigit xs ys) [0..<t]) + 2 ^ t * todigit (carry xs ys t) + 2 ^ t * num (drop t xs) + 2 ^ t * num (drop t ys)\"\nproof (induction t)\n  case 0\n  then show ?case\n    using num_def by simp\nnext\n  case (Suc t)\n  let ?z = \"sumdigit xs ys\"\n  let ?c = \"carry xs ys\"\n  let ?zzz = \"map ?z [0..<Suc t]\"\n  have \"num (take (Suc t) ?zzz) = num (take t ?zzz) + 2 ^ t * todigit (digit ?zzz t)\"\n    using num_take_Suc by blast\n  moreover have \"take (Suc t) ?zzz = map (sumdigit xs ys) [0..<Suc t]\"\n    by simp\n  moreover have \"take t ?zzz = map (sumdigit xs ys) [0..<t]\"\n    by simp\n  ultimately have 1: \"num (map ?z [0..<Suc t]) = num (map ?z [0..<t]) + 2 ^ t * todigit (digit ?zzz t)\"\n    by simp\n\n  have 2: \"digit ?zzz t = sumdigit xs ys t\"\n    using digit_def\n    by (metis One_nat_def add_Suc diff_add_inverse length_map length_upt lessI nth_map_upt plus_1_eq_Suc)\n\n  have \"todigit (?z t) + 2 * (todigit (carry xs ys (Suc t))) =\n      todigit (carry xs ys t) + todigit (digit xs t) + todigit (digit ys t)\"\n    using carry_sumdigit .\n  then have \"2 ^ t * (todigit (?z t) + 2 * (todigit (?c (Suc t)))) =\n      2 ^ t * (todigit (?c t) + todigit (digit xs t) + todigit (digit ys t))\"\n    by simp\n  then have \"2 ^ t * todigit (?z t) + 2 ^ t * 2 * todigit (?c (Suc t)) =\n      2 ^ t * todigit (?c t) + 2 ^ t * todigit (digit xs t) + 2 ^ t * todigit (digit ys t)\"\n    using add_mult_distrib2 by simp\n  then have \"num (map ?z [0..<t]) + 2 ^ t * (todigit (?z t)) + 2 ^ Suc t * (todigit (?c (Suc t))) =\n      num (map ?z [0..<t]) + 2 ^ t * (todigit (?c t)) + 2 ^ t * (todigit (digit xs t)) + 2^t * (todigit (digit ys t))\"\n    by simp\n  then have \"num (map ?z [0..<Suc t]) + 2 ^ Suc t * (todigit (?c (Suc t))) =\n      num (map ?z [0..<t]) + 2 ^ t * todigit (?c t) + 2 ^ t * todigit (digit xs t) + 2 ^ t * todigit (digit ys t)\"\n    using 1 2 by simp\n  then have \"num (map ?z [0..<Suc t]) + 2 ^ Suc t * (todigit (?c (Suc t))) +\n        2 ^ Suc t * num (drop (Suc t) xs) + 2 ^ Suc t * num (drop (Suc t) ys) =\n      num (map ?z [0..<t]) + 2 ^ t * todigit (?c t) + 2 ^ t * todigit (digit xs t) + 2 ^ t * todigit (digit ys t) +\n        2 ^ Suc t * num (drop (Suc t) xs) + 2 ^ Suc t * num (drop (Suc t) ys)\"\n    by simp\n  also have \"... = num (map ?z [0..<t]) + 2 ^ t * (todigit (?c t)) +\n        2 ^ t * (todigit (digit xs t) + 2 * num (drop (Suc t) xs)) + 2 ^ t * (todigit (digit ys t) + 2 * num (drop (Suc t) ys))\"\n    by (simp add: add_mult_distrib2)\n  also have \"... = num (map ?z [0..<t]) + 2 ^ t * (todigit (?c t)) +\n        2 ^ t * num (drop t xs) + 2 ^ t * num (drop t ys)\"\n    using num_drop by metis\n  also have \"... = num xs + num ys\"\n    using Suc by simp\n  finally show ?case\n    by simp\nqed\n\nlemma carry_le:\n  assumes \"symbols_lt 4 xs\" and \"symbols_lt 4 ys\"\n  shows \"carry xs ys t \\<le> \\<one>\"\nproof (induction t)\n  case 0\n  then show ?case\n    by simp\nnext\n  case (Suc t)\n  then have \"todigit (carry xs ys t) \\<le> 1\"\n    by simp\n  moreover have \"todigit (digit xs t) \\<le> 1\"\n    using assms(1) digit_def by auto\n  moreover have \"todigit (digit ys t) \\<le> 1\"\n    using assms(2) digit_def by auto\n  ultimately show ?case\n    by simp\nqed\n\nlemma num_sumdigit_eq_sum:\n  assumes \"length xs \\<le> n\"\n    and \"length ys \\<le> n\"\n    and \"symbols_lt 4 xs\"\n    and \"symbols_lt 4 ys\"\n  shows \"num xs + num ys = num (map (sumdigit xs ys) [0..<Suc n])\"\nproof -\n  have \"num xs + num ys =\n      num (map (sumdigit xs ys) [0..<Suc n]) + 2 ^ Suc n * todigit (carry xs ys (Suc n)) +\n        2 ^ Suc n * num (drop (Suc n) xs) + 2 ^ Suc n * num (drop (Suc n) ys)\"\n    using carry_sumdigit_eq_sum by blast\n  also have \"... = num (map (sumdigit xs ys) [0..<Suc n]) + 2 ^ Suc n * todigit (carry xs ys (Suc n))\"\n    using assms(1,2) by (simp add: num_def)\n  also have \"... = num (map (sumdigit xs ys) [0..<Suc n])\"\n  proof -\n    have \"digit xs n = 0\"\n      using assms(1) digit_def by simp\n    moreover have \"digit ys n = 0\"\n      using assms(2) digit_def by simp\n    ultimately have \"(digit xs n + digit ys n + todigit (carry xs ys n)) div 2 = 0\"\n      using carry_le[OF assms(3,4), of n] by simp\n    then show ?thesis\n      by auto\n  qed\n  finally show ?thesis .\nqed\n\nlemma num_sumdigit_eq_sum':\n  assumes \"symbols_lt 4 xs\" and \"symbols_lt 4 ys\"\n  shows \"num xs + num ys = num (map (sumdigit xs ys) [0..<Suc (max (length xs) (length ys))])\"\n  using assms num_sumdigit_eq_sum by simp\n\nlemma num_sumdigit_eq_sum'':\n  assumes \"bit_symbols xs\" and \"bit_symbols ys\"\n  shows \"num xs + num ys = num (map (sumdigit xs ys) [0..<Suc (max (length xs) (length ys))])\"\nproof -\n  have \"symbols_lt 4 xs\"\n    using assms(1) by auto\n  moreover have \"symbols_lt 4 ys\"\n    using assms(2) by auto\n  ultimately show ?thesis\n    using num_sumdigit_eq_sum' by simp\nqed\n\nlemma sumdigit_bit_symbols: \"bit_symbols (map (sumdigit xs ys) [0..<t])\"\n  using sumdigit_def by auto\n\ntext \\<open>\nThe core of the addition Turing machine is the following command. It scans the\nsymbols on tape $j_1$ and $j_2$ in lockstep until it reaches blanks on both\ntapes. In every step it adds the symbols on both tapes and the symbol on the\nlast tape, which is a memorization tape storing the carry bit. The sum of these\nthree bits modulo~2 is written to tape $j_2$ and the new carry to the\nmemorization tape.\n\\<close>\n\ndefinition cmd_plus :: \"tapeidx \\<Rightarrow> tapeidx \\<Rightarrow> command\" where\n  \"cmd_plus j1 j2 rs \\<equiv>\n    (if rs ! j1 = \\<box> \\<and> rs ! j2 = \\<box> then 1 else 0,\n     (map (\\<lambda>j.\n       if j = j1 then (rs ! j, Right)\n       else if j = j2 then (tosym ((todigit (rs ! j1) + todigit (rs ! j2) + todigit (last rs)) mod 2), Right)\n       else if j = length rs - 1 then (tosym ((todigit (rs ! j1) + todigit (rs ! j2) + todigit (last rs)) div 2), Stay)\n       else (rs ! j, Stay)) [0..<length rs]))\"\n\nlemma sem_cmd_plus:\n  assumes \"j1 \\<noteq> j2\"\n    and \"j1 < k - 1\"\n    and \"j2 < k - 1\"\n    and \"j2 > 0\"\n    and \"length tps = k\"\n    and \"bit_symbols xs\"\n    and \"bit_symbols ys\"\n    and \"tps ! j1 = (\\<lfloor>xs\\<rfloor>, Suc t)\"\n    and \"tps ! j2 = (\\<lfloor>map (sumdigit xs ys) [0..<t] @ drop t ys\\<rfloor>, Suc t)\"\n    and \"last tps = \\<lceil>carry xs ys t\\<rceil>\"\n    and \"rs = read tps\"\n    and \"tps' = tps\n      [j1 := tps!j1 |+| 1,\n       j2 := tps!j2 |:=| sumdigit xs ys t |+| 1,\n       length tps - 1 := \\<lceil>carry xs ys (Suc t)\\<rceil>]\"\n  shows \"sem (cmd_plus j1 j2) (0, tps) = (if t < max (length xs) (length ys) then 0 else 1, tps')\"\nproof\n  have \"k \\<ge> 2\"\n    using assms(3,4) by simp\n  have rs1: \"rs ! j1 = digit xs t\"\n    using assms(2,5,8,11) digit_def read_def contents_def by simp\n  let ?zs = \"map (sumdigit xs ys) [0..<t] @ drop t ys\"\n  have rs2: \"rs ! j2 = digit ys t\"\n  proof (cases \"t < length ys\")\n    case True\n    then have \"?zs ! t = ys ! t\"\n      by (simp add: nth_append)\n    then show ?thesis\n      using assms(3,5,9,11) digit_def read_def contents_def by simp\n  next\n    case False\n    then have \"length ?zs = t\"\n      by simp\n    then have \"\\<lfloor>?zs\\<rfloor> (Suc t) = \\<box>\"\n      using False contents_def by simp\n    then show ?thesis\n      using digit_def read_def contents_def False assms(3,5,9,11) by simp\n  qed\n  have rs3: \"last rs = carry xs ys t\"\n    using `k \\<ge> 2` assms onesie_read onesie_def read_def read_length tapes_at_read'\n    by (metis (no_types, lifting) diff_less last_conv_nth length_greater_0_conv less_one list.size(3) not_numeral_le_zero)\n  have *: \"tosym ((todigit (rs ! j1) + todigit (rs ! j2) + todigit (last rs)) mod 2) = sumdigit xs ys t\"\n    using rs1 rs2 rs3 sumdigit_def by simp\n\n  have \"\\<not> (digit xs t = 0 \\<and> digit ys t = 0)\" if \"t < max (length xs) (length ys)\"\n    using assms(6,7) digit_def that by auto\n  then have 4: \"\\<not> (rs ! j1 = 0 \\<and> rs ! j2 = 0)\" if \"t < max (length xs) (length ys)\"\n    using rs1 rs2 that by simp\n  then have fst1: \"fst (sem (cmd_plus j1 j2) (0, tps)) = fst (0, tps')\" if \"t < max (length xs) (length ys)\"\n    using that cmd_plus_def assms(11) by (smt (verit, ccfv_threshold) fst_conv prod.sel(2) sem)\n\n  have \"digit xs t = 0 \\<and> digit ys t = 0\" if \"t \\<ge> max (length xs) (length ys)\"\n    using that digit_def by simp\n  then have 5: \"rs ! j1 = \\<box> \\<and> rs ! j2 = \\<box>\" if \"t \\<ge> max (length xs) (length ys)\"\n    using rs1 rs2 that by simp\n  then have \"fst (sem (cmd_plus j1 j2) (0, tps)) = fst (1, tps')\" if \"t \\<ge> max (length xs) (length ys)\"\n    using that cmd_plus_def assms(11) by (smt (verit, ccfv_threshold) fst_conv prod.sel(2) sem)\n  then show \"fst (sem (cmd_plus j1 j2) (0, tps)) = fst (if t < max (length xs) (length ys) then 0 else 1, tps')\"\n    using fst1 by (simp add: not_less)\n\n  show \"snd (sem (cmd_plus j1 j2) (0, tps)) = snd (if t < max (length xs) (length ys) then 0 else 1, tps')\"\n  proof (rule snd_semI)\n    show \"proper_command k (cmd_plus j1 j2)\"\n      using cmd_plus_def by simp\n    show \"length tps = k\"\n      using assms(5) .\n    show \"length tps' = k\"\n      using assms(5,12) by simp\n    have len: \"length (read tps) = k\"\n      by (simp add: assms read_length)\n    show \"act (cmd_plus j1 j2 (read tps) [!] j) (tps ! j) = tps' ! j\"\n      if \"j < k\" for j\n    proof -\n      have j: \"j < length tps\"\n        using len that assms(5) by simp\n      consider\n          \"j = j1\"\n        | \"j \\<noteq> j1 \\<and> j = j2\"\n        | \"j \\<noteq> j1 \\<and> j \\<noteq> j2 \\<and> j = length rs - 1\"\n        | \"j \\<noteq> j1 \\<and> j \\<noteq> j2 \\<and> j \\<noteq> length rs - 1\"\n        by auto\n      then show ?thesis\n      proof (cases)\n        case 1\n        then have \"cmd_plus j1 j2 (read tps) [!] j = (read tps ! j, Right)\"\n          using that len cmd_plus_def by simp\n        then have \"act (cmd_plus j1 j2 (read tps) [!] j) (tps ! j) = tps ! j |+| 1\"\n          using act_Right[OF j] by simp\n        moreover have \"tps' ! j = tps ! j |+| 1\"\n          using assms(1,2,5,12) that 1 by simp\n        ultimately show ?thesis\n          by simp\n      next\n        case 2\n        then have \"cmd_plus j1 j2 (read tps) [!] j =\n            (tosym ((todigit (rs ! j1) + todigit (rs ! j2) + todigit (last rs)) mod 2), Right)\"\n          using that len cmd_plus_def assms(11) by simp\n        then have \"cmd_plus j1 j2 (read tps) [!] j = (sumdigit xs ys t, Right)\"\n          using * by simp\n        moreover have \"tps' ! j2 = tps!j2 |:=| sumdigit xs ys t |+| 1\"\n          using assms(3,5,12) by simp\n        ultimately show ?thesis\n          using act_Right' 2 by simp\n      next\n        case 3\n        then have \"cmd_plus j1 j2 (read tps) [!] j =\n            (tosym ((todigit (rs ! j1) + todigit (rs ! j2) + todigit (last rs)) div 2), Stay)\"\n          using that len cmd_plus_def assms(11) by simp\n        then have \"cmd_plus j1 j2 (read tps) [!] j = (carry xs ys (Suc t), Stay)\"\n          using rs1 rs2 rs3 by simp\n        moreover have \"tps' ! (length tps - 1) = \\<lceil>carry xs ys (Suc t)\\<rceil>\"\n          using 3 assms(5,11,12) len that by simp\n        ultimately show ?thesis\n          using 3 act_onesie assms(3,5,10,11) len\n          by (metis add_diff_inverse_nat last_length less_nat_zero_code nat_diff_split_asm plus_1_eq_Suc)\n      next\n        case 4\n        then have \"cmd_plus j1 j2 (read tps) [!] j = (read tps ! j, Stay)\"\n          using that len cmd_plus_def assms(11) by simp\n        then have \"act (cmd_plus j1 j2 (read tps) [!] j) (tps ! j) = tps ! j\"\n          using act_Stay[OF j] by simp\n        moreover have \"tps' ! j = tps ! j\"\n          using that 4 len assms(5,11,12) by simp\n        ultimately show ?thesis\n          by simp\n      qed\n    qed\n  qed\nqed\n\nlemma contents_map_append_drop:\n  \"\\<lfloor>map f [0..<t] @ drop t zs\\<rfloor>(Suc t := f t) = \\<lfloor>map f [0..<Suc t] @ drop (Suc t) zs\\<rfloor>\"\nproof (cases \"t < length zs\")\n  case lt: True\n  then have t_lt: \"t < length (map f [0..<t] @ drop t zs)\"\n    by simp\n  show ?thesis\n  proof\n    fix x\n    consider\n        \"x = 0\"\n      | \"x > 0 \\<and> x < Suc t\"\n      | \"x = Suc t\"\n      | \"x > Suc t \\<and> x \\<le> length zs\"\n      | \"x > Suc t \\<and> x > length zs\"\n      by linarith\n    then show \"(\\<lfloor>map f [0..<t] @ drop t zs\\<rfloor>(Suc t := f t)) x =\n        \\<lfloor>map f [0..<Suc t] @ drop (Suc t) zs\\<rfloor> x\"\n        (is \"?lhs x = ?rhs x\")\n    proof (cases)\n      case 1\n      then show ?thesis\n        using contents_def by simp\n    next\n      case 2\n      then have \"?lhs x = (map f [0..<t] @ drop t zs) ! (x - 1)\"\n        using contents_def by simp\n      moreover have \"x - 1 < t\"\n        using 2 by auto\n      ultimately have left: \"?lhs x = f (x - 1)\"\n        by (metis add.left_neutral diff_zero length_map length_upt nth_append nth_map_upt)\n      have \"?rhs x = (map f [0..<Suc t] @ drop (Suc t) zs) ! (x - 1)\"\n        using 2 contents_def by simp\n      moreover have \"x - 1 < Suc t\"\n        using 2 by auto\n      ultimately have \"?rhs x = f (x - 1)\"\n        by (metis diff_add_inverse diff_zero length_map length_upt nth_append nth_map_upt)\n      then show ?thesis\n        using left by simp\n    next\n      case 3\n      then show ?thesis\n        using contents_def lt\n        by (smt (z3) One_nat_def Suc_leI add_Suc append_take_drop_id diff_Suc_1 diff_zero fun_upd_same\n          length_append length_map length_take length_upt lessI min_absorb2 nat.simps(3) nth_append nth_map_upt plus_1_eq_Suc)\n    next\n      case 4\n      then have \"?lhs x = \\<lfloor>map f [0..<t] @ drop t zs\\<rfloor> x\"\n        using contents_def by simp\n      then have \"?lhs x = (map f [0..<t] @ drop t zs) ! (x - 1)\"\n        using 4 contents_def by simp\n      then have left: \"?lhs x = drop t zs ! (x - 1 - t)\"\n        using 4\n        by (metis Suc_lessE diff_Suc_1 length_map length_upt less_Suc_eq_le less_or_eq_imp_le minus_nat.diff_0 not_less_eq nth_append)\n      have \"x \\<le> length (map f [0..<Suc t] @ drop (Suc t) zs)\"\n        using 4 lt by auto\n      moreover have \"x > 0\"\n        using 4 by simp\n      ultimately have \"?rhs x = (map f [0..<Suc t] @ drop (Suc t) zs) ! (x - 1)\"\n        using 4 contents_inbounds by simp\n      moreover have \"x - 1 \\<ge> Suc t\"\n        using 4 by auto\n      ultimately have \"?rhs x = drop (Suc t) zs ! (x - 1 - Suc t)\"\n        by (metis diff_zero leD length_map length_upt nth_append)\n      then show ?thesis\n        using left 4 by (metis Cons_nth_drop_Suc Suc_diff_Suc diff_Suc_eq_diff_pred lt nth_Cons_Suc)\n    next\n      case 5\n      then show ?thesis\n        using lt contents_def by auto\n    qed\n  qed\nnext\n  case False\n  moreover have \"\\<lfloor>map f [0..<t]\\<rfloor>(Suc t := f t) = \\<lfloor>map f [0..<Suc t]\\<rfloor>\"\n  proof\n    fix x\n    show \"(\\<lfloor>map f [0..<t]\\<rfloor>(Suc t := f t)) x = \\<lfloor>map f [0..<Suc t]\\<rfloor> x\"\n    proof (cases \"x < Suc t\")\n      case True\n      then show ?thesis\n        using contents_def\n        by (smt (verit, del_insts) diff_Suc_1 diff_zero fun_upd_apply length_map length_upt less_Suc_eq_0_disj\n          less_Suc_eq_le less_imp_le_nat nat_neq_iff nth_map_upt)\n    next\n      case ge: False\n      show ?thesis\n      proof (cases \"x = Suc t\")\n        case True\n        then show ?thesis\n          using contents_def\n          by (metis One_nat_def add_Suc diff_Suc_1 diff_zero fun_upd_same ge le_eq_less_or_eq length_map\n            length_upt lessI less_Suc_eq_0_disj nth_map_upt plus_1_eq_Suc)\n      next\n        case False\n        then have \"x > Suc t\"\n          using ge by simp\n        then show ?thesis\n          using contents_def by simp\n      qed\n    qed\n  qed\n  ultimately show ?thesis\n    by simp\nqed\n\ncorollary sem_cmd_plus':\n  assumes \"j1 \\<noteq> j2\"\n    and \"j1 < k - 1\"\n    and \"j2 < k - 1\"\n    and \"j2 > 0\"\n    and \"length tps = k\"\n    and \"bit_symbols xs\"\n    and \"bit_symbols ys\"\n    and \"tps ! j1 = (\\<lfloor>xs\\<rfloor>, Suc t)\"\n    and \"tps ! j2 = (\\<lfloor>map (sumdigit xs ys) [0..<t] @ drop t ys\\<rfloor>, Suc t)\"\n    and \"last tps = \\<lceil>carry xs ys t\\<rceil>\"\n    and \"tps' = tps\n      [j1 := (\\<lfloor>xs\\<rfloor>, Suc (Suc t)),\n       j2 := (\\<lfloor>map (sumdigit xs ys) [0..<Suc t] @ drop (Suc t) ys\\<rfloor>, Suc (Suc t)),\n       length tps - 1 := \\<lceil>carry xs ys (Suc t)\\<rceil>]\"\n  shows \"sem (cmd_plus j1 j2) (0, tps) = (if Suc t \\<le> max (length xs) (length ys) then 0 else 1, tps')\"\nproof -\n  have \"tps ! j1 |+| 1 = (\\<lfloor>xs\\<rfloor>, Suc (Suc t))\"\n    using assms(8) by simp\n  moreover have \"tps ! j2 |:=| sumdigit xs ys t |+| 1 =\n      (\\<lfloor>map (sumdigit xs ys) [0..<Suc t] @ drop (Suc t) ys\\<rfloor>, Suc (Suc t))\"\n    using contents_map_append_drop assms(9) by simp\n  ultimately show ?thesis\n    using sem_cmd_plus[OF assms(1-10)] assms(11) by auto\nqed\n\ntext \\<open>\nThe next Turing machine comprises just the command @{const cmd_plus}. It\noverwrites tape $j_2$ with the sum of the numbers on tape $j_1$ and $j_2$. The\ncarry bit is maintained on the last tape.\n\\<close>\n\ndefinition tm_plus :: \"tapeidx \\<Rightarrow> tapeidx \\<Rightarrow> machine\" where\n  \"tm_plus j1 j2 \\<equiv> [cmd_plus j1 j2]\"\n\nlemma tm_plus_tm:\n  assumes \"j2 > 0\" and \"k \\<ge> 2\" and \"G \\<ge> 4\"\n  shows \"turing_machine k G (tm_plus j1 j2)\"\n  unfolding tm_plus_def using assms(1-3) cmd_plus_def turing_machine_def by auto\n\nlemma tm_plus_immobile:\n  fixes k :: nat\n  assumes \"j1 < k\" and \"j2 < k\"\n  shows \"immobile (tm_plus j1 j2) k (Suc k)\"\nproof -\n  let ?M = \"tm_plus j1 j2\"\n  { fix q :: nat and rs :: \"symbol list\"\n    assume q: \"q < length ?M\"\n    assume rs: \"length rs = Suc k\"\n    then have len: \"length rs - 1 = k\"\n      by simp\n    have neq: \"k \\<noteq> j1\" \"k \\<noteq> j2\"\n      using assms by simp_all\n    have \"?M ! q = cmd_plus j1 j2\"\n      using tm_plus_def q by simp\n    moreover have \"(cmd_plus j1 j2) rs [!] k =\n        (tosym ((todigit (rs ! j1) + todigit (rs ! j2) + todigit (last rs)) div 2), Stay)\"\n      using cmd_plus_def rs len neq by fastforce\n    ultimately have \"(cmd_plus j1 j2) rs [~] k = Stay\"\n      by simp\n  }\n  then show ?thesis\n    by (simp add: immobile_def tm_plus_def)\nqed\n\nlemma execute_tm_plus:\n  assumes \"j1 \\<noteq> j2\"\n    and \"j1 < k - 1\"\n    and \"j2 < k - 1\"\n    and \"j2 > 0\"\n    and \"length tps = k\"\n    and \"bit_symbols xs\"\n    and \"bit_symbols ys\"\n    and \"t \\<le> Suc (max (length xs) (length ys))\"\n    and \"tps ! j1 = (\\<lfloor>xs\\<rfloor>, 1)\"\n    and \"tps ! j2 = (\\<lfloor>ys\\<rfloor>, 1)\"\n    and \"last tps = \\<lceil>\\<triangleright>\\<rceil>\"\n  shows \"execute (tm_plus j1 j2) (0, tps) t =\n    (if t \\<le> max (length xs) (length ys) then 0 else 1, tps\n      [j1 := (\\<lfloor>xs\\<rfloor>, Suc t),\n       j2 := (\\<lfloor>map (sumdigit xs ys) [0..<t] @ drop t ys\\<rfloor>, Suc t),\n       length tps - 1 := \\<lceil>carry xs ys t\\<rceil>])\"\n  using assms(8)\nproof (induction t)\n  case 0\n  have \"carry xs ys 0 = 1\"\n    by simp\n  moreover have \"map (sumdigit xs ys) [0..<0] @ drop 0 ys = ys\"\n    by simp\n  ultimately have \"tps = tps\n      [j1 := (\\<lfloor>xs\\<rfloor>, Suc 0),\n       j2 := (\\<lfloor>map (sumdigit xs ys) [0..<0] @ drop 0 ys\\<rfloor>, Suc 0),\n       length tps - 1 := \\<lceil>carry xs ys 0\\<rceil>]\"\n    using assms\n    by (metis One_nat_def add_diff_inverse_nat last_length less_nat_zero_code\n      list_update_id nat_diff_split_asm plus_1_eq_Suc)\n  then show ?case\n    by simp\nnext\n  case (Suc t)\n  let ?M = \"tm_plus j1 j2\"\n  have \"execute ?M (0, tps) (Suc t) = exe ?M (execute ?M (0, tps) t)\"\n      (is \"_ = exe ?M ?cfg\")\n    by simp\n  also have \"... = sem (cmd_plus j1 j2) ?cfg\"\n    using Suc tm_plus_def exe_lt_length by simp\n  also have \"... = (if Suc t \\<le> max (length xs) (length ys) then 0 else 1, tps\n      [j1 := (\\<lfloor>xs\\<rfloor>, Suc (Suc t)),\n       j2 := (\\<lfloor>map (sumdigit xs ys) [0..<Suc t] @ drop (Suc t) ys\\<rfloor>, Suc (Suc t)),\n       length tps - 1 := \\<lceil>carry xs ys (Suc t)\\<rceil>])\"\n  proof -\n    let ?tps = \"tps\n      [j1 := (\\<lfloor>xs\\<rfloor>, Suc t),\n       j2 := (\\<lfloor>map (sumdigit xs ys) [0..<t] @ drop t ys\\<rfloor>, Suc t),\n       length tps - 1 := \\<lceil>carry xs ys t\\<rceil>]\"\n    let ?tps' = \"?tps\n      [j1 := (\\<lfloor>xs\\<rfloor>, Suc (Suc t)),\n       j2 := (\\<lfloor>map (sumdigit xs ys) [0..<Suc t] @ drop (Suc t) ys\\<rfloor>, Suc (Suc t)),\n       length tps - 1 := \\<lceil>carry xs ys (Suc t)\\<rceil>]\"\n    have cfg: \"?cfg = (0, ?tps)\"\n      using Suc by simp\n    have tps_k: \"length ?tps = k\"\n      using assms(2,3,5) by simp\n    have tps_j1: \"?tps ! j1 = (\\<lfloor>xs\\<rfloor>, Suc t)\"\n      using assms(1-3,5) by simp\n    have tps_j2: \"?tps ! j2 = (\\<lfloor>map (sumdigit xs ys) [0..<t] @ drop t ys\\<rfloor>, Suc t)\"\n      using assms(1-3,5) by simp\n    have tps_last: \"last ?tps = \\<lceil>carry xs ys t\\<rceil>\"\n      using assms\n      by (metis One_nat_def carry.simps(1) diff_Suc_1 last_list_update length_list_update list_update_nonempty prod.sel(2) tps_j1)\n    then have \"sem (cmd_plus j1 j2) (0, ?tps) = (if Suc t \\<le> max (length xs) (length ys) then 0 else 1, ?tps')\"\n      using sem_cmd_plus'[OF assms(1-4) tps_k assms(6,7) tps_j1 tps_j2 tps_last] assms(1-3)\n      by (smt (verit, best) Suc.prems Suc_lessD assms(5) tps_k)\n    then have \"sem (cmd_plus j1 j2) ?cfg = (if Suc t \\<le> max (length xs) (length ys) then 0 else 1, ?tps')\"\n      using cfg by simp\n    moreover have \"?tps' = tps\n      [j1 := (\\<lfloor>xs\\<rfloor>, Suc (Suc t)),\n       j2 := (\\<lfloor>map (sumdigit xs ys) [0..<Suc t] @ drop (Suc t) ys\\<rfloor>, Suc (Suc t)),\n       length tps - 1 := \\<lceil>carry xs ys (Suc t)\\<rceil>]\"\n      using assms by (smt (z3) list_update_overwrite list_update_swap)\n    ultimately show ?thesis\n      by simp\n  qed\n  finally show ?case\n    by simp\nqed\n\nlemma tm_plus_bounded_write:\n  assumes \"j1 < k - 1\"\n  shows \"bounded_write (tm_plus j1 j2) (k - 1) 4\"\n  using assms cmd_plus_def tm_plus_def bounded_write_def by simp\n\nlemma carry_max_length:\n  assumes \"bit_symbols xs\" and \"bit_symbols ys\"\n  shows \"carry xs ys (Suc (max (length xs) (length ys))) = \\<zero>\"\nproof -\n  let ?t = \"max (length xs) (length ys)\"\n  have \"carry xs ys (Suc ?t) = tosym ((todigit (digit xs ?t) + todigit (digit ys ?t) + todigit (carry xs ys ?t)) div 2)\"\n    by simp\n  then have \"carry xs ys (Suc ?t) = tosym (todigit (carry xs ys ?t) div 2)\"\n    using digit_def by simp\n  moreover have \"carry xs ys ?t \\<le> \\<one>\"\n    using carry_le assms by fastforce\n  ultimately show ?thesis\n    by simp\nqed\n\ncorollary execute_tm_plus_halt:\n  assumes \"j1 \\<noteq> j2\"\n    and \"j1 < k - 1\"\n    and \"j2 < k - 1\"\n    and \"j2 > 0\"\n    and \"length tps = k\"\n    and \"bit_symbols xs\"\n    and \"bit_symbols ys\"\n    and \"t = Suc (max (length xs) (length ys))\"\n    and \"tps ! j1 = (\\<lfloor>xs\\<rfloor>, 1)\"\n    and \"tps ! j2 = (\\<lfloor>ys\\<rfloor>, 1)\"\n    and \"last tps = \\<lceil>\\<triangleright>\\<rceil>\"\n  shows \"execute (tm_plus j1 j2) (0, tps) t =\n    (1, tps\n      [j1 := (\\<lfloor>xs\\<rfloor>, Suc t),\n       j2 := (\\<lfloor>map (sumdigit xs ys) [0..<t]\\<rfloor>, Suc t),\n       length tps - 1 := \\<lceil>\\<zero>\\<rceil>])\"\nproof -\n  have \"execute (tm_plus j1 j2) (0, tps) t =\n    (1, tps\n      [j1 := (\\<lfloor>xs\\<rfloor>, Suc t),\n       j2 := (\\<lfloor>map (sumdigit xs ys) [0..<t] @ drop t ys\\<rfloor>, Suc t),\n       length tps - 1 := \\<lceil>carry xs ys t\\<rceil>])\"\n    using assms(8) execute_tm_plus[OF assms(1-7) _ assms(9-11)] Suc_leI Suc_n_not_le_n lessI\n    by presburger\n  then have \"execute (tm_plus j1 j2) (0, tps) t =\n    (1, tps\n      [j1 := (\\<lfloor>xs\\<rfloor>, Suc t),\n       j2 := (\\<lfloor>map (sumdigit xs ys) [0..<t]\\<rfloor>, Suc t),\n       length tps - 1 := \\<lceil>carry xs ys t\\<rceil>])\"\n    using assms(8) by simp\n  then show \"execute (tm_plus j1 j2) (0, tps) t =\n    (1, tps\n      [j1 := (\\<lfloor>xs\\<rfloor>, Suc t),\n       j2 := (\\<lfloor>map (sumdigit xs ys) [0..<t]\\<rfloor>, Suc t),\n       length tps - 1 := \\<lceil>\\<zero>\\<rceil>])\"\n    using assms(8) carry_max_length[OF assms(6,7)] by metis\nqed\n\nlemma transforms_tm_plusI:\n  assumes \"j1 \\<noteq> j2\"\n    and \"j1 < k - 1\"\n    and \"j2 < k - 1\"\n    and \"j2 > 0\"\n    and \"length tps = k\"\n    and \"bit_symbols xs\"\n    and \"bit_symbols ys\"\n    and \"t = Suc (max (length xs) (length ys))\"\n    and \"tps ! j1 = (\\<lfloor>xs\\<rfloor>, 1)\"\n    and \"tps ! j2 = (\\<lfloor>ys\\<rfloor>, 1)\"\n    and \"last tps = \\<lceil>\\<triangleright>\\<rceil>\"\n    and \"tps' = tps\n      [j1 := (\\<lfloor>xs\\<rfloor>, Suc t),\n       j2 := (\\<lfloor>map (sumdigit xs ys) [0..<t]\\<rfloor>, Suc t),\n       length tps - 1 := \\<lceil>\\<zero>\\<rceil>]\"\n  shows \"transforms (tm_plus j1 j2) tps t tps'\"\n  using assms execute_tm_plus_halt[OF assms(1-11)] tm_plus_def transforms_def transits_def\n  by auto\n\ntext \\<open>\nThe next Turing machine removes the memorization tape from @{const tm_plus}.\n\\<close>\n\ndefinition tm_plus' :: \"tapeidx \\<Rightarrow> tapeidx \\<Rightarrow> machine\" where\n  \"tm_plus' j1 j2 \\<equiv> cartesian (tm_plus j1 j2) 4\"\n\nlemma tm_plus'_tm:\n  assumes \"j2 > 0\" and \"k \\<ge> 2\" and \"G \\<ge> 4\"\n  shows \"turing_machine k G (tm_plus' j1 j2)\"\n  unfolding tm_plus'_def using assms cartesian_tm tm_plus_tm by simp\n\nlemma transforms_tm_plus'I [transforms_intros]:\n  fixes k t :: nat and j1 j2 :: tapeidx and tps tps' :: \"tape list\" and xs zs :: \"symbol list\"\n  assumes \"j1 \\<noteq> j2\"\n    and \"j1 < k\"\n    and \"j2 < k\"\n    and \"j2 > 0\"\n    and \"length tps = k\"\n    and \"bit_symbols xs\"\n    and \"bit_symbols ys\"\n    and \"t = Suc (max (length xs) (length ys))\"\n    and \"tps ! j1 = (\\<lfloor>xs\\<rfloor>, 1)\"\n    and \"tps ! j2 = (\\<lfloor>ys\\<rfloor>, 1)\"\n    and \"tps' = tps\n      [j1 := (\\<lfloor>xs\\<rfloor>, Suc t),\n       j2 := (\\<lfloor>map (sumdigit xs ys) [0..<t]\\<rfloor>, Suc t)]\"\n  shows \"transforms (tm_plus' j1 j2) tps t tps'\"\nproof -\n  let ?tps = \"tps @ [\\<lceil>\\<triangleright>\\<rceil>]\"\n  let ?tps' = \"?tps\n      [j1 := (\\<lfloor>xs\\<rfloor>, Suc t),\n       j2 := (\\<lfloor>map (sumdigit xs ys) [0..<t]\\<rfloor>, Suc t),\n       length ?tps - 1 := \\<lceil>\\<zero>\\<rceil>]\"\n  let ?M = \"tm_plus j1 j2\"\n\n  have 1: \"length ?tps = Suc k\"\n    using assms(5) by simp\n  have 2: \"?tps ! j1 = (\\<lfloor>xs\\<rfloor>, 1)\"\n    by (simp add: assms(9) assms(2) assms(5) nth_append)\n  have 3: \"?tps ! j2 = (\\<lfloor>ys\\<rfloor>, 1)\"\n    by (simp add: assms(10) assms(3) assms(5) nth_append)\n  have 4: \"last ?tps = \\<lceil>\\<triangleright>\\<rceil>\"\n    by simp\n  have 5: \"k \\<ge> 2\"\n    using assms(3,4) by simp\n  have \"transforms (tm_plus j1 j2) ?tps t ?tps'\"\n    using transforms_tm_plusI[OF assms(1) _ _ assms(4) 1 assms(6,7,8) 2 3 4, of ?tps'] assms(2,3)\n    by simp\n  moreover have \"?tps' = tps' @ [\\<lceil>\\<zero>\\<rceil>]\"\n    using assms by (simp add: list_update_append)\n  ultimately have \"transforms (tm_plus j1 j2) (tps @ [\\<lceil>\\<triangleright>\\<rceil>]) t (tps' @ [\\<lceil>\\<zero>\\<rceil>])\"\n    by simp\n  moreover have \"turing_machine (Suc k) 4 ?M\"\n    using tm_plus_tm assms by simp\n  moreover have \"immobile ?M k (Suc k)\"\n    using tm_plus_immobile assms by simp\n  moreover have \"bounded_write (tm_plus j1 j2) k 4\"\n    using tm_plus_bounded_write[of j1 \"Suc k\"] assms(2) by simp\n  ultimately have \"transforms (cartesian (tm_plus j1 j2) 4) tps t tps'\"\n    using cartesian_transforms_onesie[where ?M=\"?M\" and ?b=4] assms(5) 5\n    by simp\n  then show ?thesis\n    using tm_plus'_def by simp\nqed\n\ntext \\<open>\nThe next Turing machine is the one we actually use to add two numbers. After\ncomputing the sum by running @{const tm_plus'}, it removes trailing zeros\nand performs a carriage return on the tapes $j_1$ and $j_2$.\n\\<close>\n\ndefinition tm_add :: \"tapeidx \\<Rightarrow> tapeidx \\<Rightarrow> machine\" where\n  \"tm_add j1 j2 \\<equiv>\n    tm_plus' j1 j2 ;;\n    tm_lconst_until j2 j2 {h. h \\<noteq> \\<zero> \\<and> h \\<noteq> \\<box>} \\<box> ;;\n    tm_cr j1 ;;\n    tm_cr j2\"\n\nlemma tm_add_tm:\n  assumes \"j2 > 0\" and \"k \\<ge> 2\" and \"G \\<ge> 4\" and \"j2 < k\"\n  shows \"turing_machine k G (tm_add j1 j2)\"\n  unfolding tm_add_def using tm_plus'_tm tm_lconst_until_tm tm_cr_tm assms by simp\n\nlocale turing_machine_add =\n  fixes j1 j2 :: tapeidx\nbegin\n\ndefinition \"tm1 \\<equiv> tm_plus' j1 j2\"\ndefinition \"tm2 \\<equiv> tm1 ;; tm_lconst_until j2 j2 {h. h \\<noteq> \\<zero> \\<and> h \\<noteq> \\<box>} \\<box>\"\ndefinition \"tm3 \\<equiv> tm2 ;; tm_cr j1\"\ndefinition \"tm4 \\<equiv> tm3 ;; tm_cr j2\"\n\nlemma tm4_eq_tm_add: \"tm4 = tm_add j1 j2\"\n  using tm4_def tm3_def tm2_def tm1_def tm_add_def by simp\n\ncontext\n  fixes x y k :: nat and tps0 :: \"tape list\"\n  assumes jk: \"j1 \\<noteq> j2\" \"j1 < k\" \"j2 < k\" \"j2 > 0\" \"k = length tps0\"\n  assumes tps0:\n    \"tps0 ! j1 = (\\<lfloor>canrepr x\\<rfloor>, 1)\"\n    \"tps0 ! j2 = (\\<lfloor>canrepr y\\<rfloor>, 1)\"\nbegin\n\nabbreviation \"xs \\<equiv> canrepr x\"\n\nabbreviation \"ys \\<equiv> canrepr y\"\n\nlemma xs: \"bit_symbols xs\"\n  using bit_symbols_canrepr by simp\n\nlemma ys: \"bit_symbols ys\"\n  using bit_symbols_canrepr by simp\n\nabbreviation \"n \\<equiv> Suc (max (length xs) (length ys))\"\n\nabbreviation \"m \\<equiv> length (canrepr (num xs + num ys))\"\n\ndefinition \"tps1 \\<equiv> tps0\n  [j1 := (\\<lfloor>xs\\<rfloor>, Suc n),\n   j2 := (\\<lfloor>map (sumdigit xs ys) [0..<n]\\<rfloor>, Suc n)]\"\n\nlemma tm1 [transforms_intros]:\n  assumes \"ttt = n\"\n  shows \"transforms tm1 tps0 ttt tps1\"\n  unfolding tm1_def\nproof (tform tps: jk xs ys tps0 time: assms)\n  show \"tps1 = tps0\n    [j1 := (\\<lfloor>xs\\<rfloor>, Suc ttt),\n     j2 := (\\<lfloor>map (sumdigit xs ys) [0..<ttt]\\<rfloor>, Suc ttt)]\"\n    using tps1_def assms by simp\nqed\n\ndefinition \"tps2 \\<equiv> tps0\n  [j1 := (\\<lfloor>xs\\<rfloor>, Suc n),\n   j2 := (\\<lfloor>canrepr (num xs + num ys)\\<rfloor>, m)]\"\n\nlemma contents_canlen:\n  assumes \"bit_symbols zs\"\n  shows \"\\<lfloor>zs\\<rfloor> (canlen zs) \\<in> {h. h \\<noteq> \\<zero> \\<and> \\<box> < h}\"\n  using assms contents_def canlen_le_length canlen_one by auto\n\nlemma tm2 [transforms_intros]:\n  assumes \"ttt = n + Suc (Suc n - canlen (map (sumdigit xs ys) [0..<n]))\"\n  shows \"transforms tm2 tps0 ttt tps2\"\n  unfolding tm2_def\nproof (tform tps: tps1_def jk xs ys tps0)\n  let ?zs = \"map (sumdigit xs ys) [0..<n]\"\n  have \"bit_symbols ?zs\"\n    using sumdigit_bit_symbols by blast\n  let ?ln = \"Suc n - canlen ?zs\"\n  have \"lneigh (\\<lfloor>?zs\\<rfloor>, Suc n) {h. h \\<noteq> \\<zero> \\<and> \\<box> < h} ?ln\"\n  proof (rule lneighI)\n    have \"\\<lfloor>?zs\\<rfloor> (canlen ?zs) \\<in> {h. h \\<noteq> \\<zero> \\<and> \\<box> < h}\"\n      using contents_canlen[OF `bit_symbols ?zs`] by simp\n    moreover have \"Suc n - ?ln = canlen ?zs\"\n      by (metis One_nat_def diff_Suc_1 diff_Suc_Suc diff_diff_cancel le_imp_less_Suc\n        length_map length_upt less_imp_le_nat canlen_le_length)\n    ultimately have \"\\<lfloor>?zs\\<rfloor> (Suc n - ?ln) \\<in> {h. h \\<noteq> \\<zero> \\<and> \\<box> < h}\"\n      by simp\n    then show \"fst (\\<lfloor>?zs\\<rfloor>, Suc n) (snd (\\<lfloor>?zs\\<rfloor>, Suc n) - ?ln) \\<in> {h. h \\<noteq> \\<zero> \\<and> \\<box> < h}\"\n      by simp\n\n    have \"\\<lfloor>?zs\\<rfloor> (Suc n - n') \\<in> {\\<box>, \\<zero>}\" if \"n' < ?ln\" for n'\n    proof (cases \"Suc n - n' \\<le> n\")\n      case True\n      moreover have 1: \"Suc n - n' > 0\"\n        using that by simp\n      ultimately have \"\\<lfloor>?zs\\<rfloor> (Suc n - n') = ?zs ! (Suc n - n' - 1)\"\n        using contents_def by simp\n      moreover have \"Suc n - n' - 1 < length ?zs\"\n        using that True by simp\n      moreover have \"Suc n - n' - 1 \\<ge> canlen ?zs\"\n        using that by simp\n      ultimately show ?thesis\n        using canlen_at_ge[of ?zs] by simp\n    next\n      case False\n      then show ?thesis\n        by simp\n    qed\n    then have \"\\<lfloor>?zs\\<rfloor> (Suc n - n') \\<notin> {h. h \\<noteq> \\<zero> \\<and> \\<box> < h}\" if \"n' < ?ln\" for n'\n      using that by fastforce\n    then show \"fst (\\<lfloor>?zs\\<rfloor>, Suc n) (snd (\\<lfloor>?zs\\<rfloor>, Suc n) - n') \\<notin> {h. h \\<noteq> \\<zero> \\<and> \\<box> < h}\"\n        if \"n' < ?ln\" for n'\n      using that by simp\n  qed\n  then show \"lneigh (tps1 ! j2) {h. h \\<noteq> \\<zero> \\<and> h \\<noteq> \\<box>} ?ln\"\n    using assms tps1_def jk by simp\n  show \"Suc n - canlen (map (sumdigit xs ys) [0..<n]) \\<le> tps1 :#: j2\"\n    \"Suc n - canlen (map (sumdigit xs ys) [0..<n]) \\<le> tps1 :#: j2\"\n    using assms tps1_def jk by simp_all\n\n  have num_zs: \"num ?zs = num xs + num ys\"\n    using assms num_sumdigit_eq_sum'' xs ys by simp\n  then have canrepr: \"canrepr (num xs + num ys) = take (canlen ?zs) ?zs\"\n    using canrepr_take_canlen `bit_symbols ?zs` by blast\n  have len_canrepr: \"length (canrepr (num xs + num ys)) = canlen ?zs\"\n    using num_zs length_canrepr_canlen sumdigit_bit_symbols by blast\n\n  have \"lconstplant (\\<lfloor>?zs\\<rfloor>, Suc n) \\<box> ?ln =\n      (\\<lfloor>canrepr (num xs + num ys)\\<rfloor>, m)\"\n    (is \"lconstplant ?tp \\<box> ?ln = _\")\n  proof -\n    have \"(if Suc n - ?ln < i \\<and> i \\<le> Suc n then \\<box> else \\<lfloor>?zs\\<rfloor> i) =\n        \\<lfloor>take (canlen ?zs) ?zs\\<rfloor> i\"\n        (is \"?lhs = ?rhs\")\n      for i\n    proof -\n      consider\n          \"i = 0\"\n        | \"i > 0 \\<and> i \\<le> canlen ?zs\"\n        | \"i > canlen ?zs \\<and> i \\<le> Suc n\"\n        | \"i > canlen ?zs \\<and> i > Suc n\"\n        by linarith\n      then show ?thesis\n      proof (cases)\n        case 1\n        then show ?thesis\n          by simp\n      next\n        case 2\n        then have \"i \\<le> Suc n - ?ln\"\n          using canlen_le_length\n          by (metis diff_diff_cancel diff_zero le_imp_less_Suc length_map length_upt less_imp_le_nat)\n        then have lhs: \"?lhs = \\<lfloor>?zs\\<rfloor> i\"\n          by simp\n        have \"take (canlen ?zs) ?zs ! (i - 1) = ?zs ! (i - 1)\"\n          using 2 by (metis Suc_diff_1 Suc_less_eq le_imp_less_Suc nth_take)\n        then have \"?rhs = \\<lfloor>?zs\\<rfloor> i\"\n          using 2 contents_inbounds len_canrepr local.canrepr not_le canlen_le_length\n          by (metis add_diff_inverse_nat add_leE)\n        then show ?thesis\n          using lhs by simp\n      next\n        case 3\n        then have \"Suc n - ?ln < i \\<and> i \\<le> Suc n\"\n          by (metis diff_diff_cancel less_imp_le_nat less_le_trans)\n        then have \"?lhs = 0\"\n          by simp\n        moreover have \"?rhs = 0\"\n          using 3 contents_outofbounds len_canrepr canrepr by metis\n        ultimately show ?thesis\n          by simp\n      next\n        case 4\n        then have \"?lhs = 0\"\n          by simp\n        moreover have \"?rhs = 0\"\n          using 4 contents_outofbounds len_canrepr canrepr by metis\n        ultimately show ?thesis\n          by simp\n      qed\n    qed\n    then have \"(\\<lambda>i. if Suc n - ?ln < i \\<and> i \\<le> Suc n then \\<box> else \\<lfloor>?zs\\<rfloor> i) =\n        \\<lfloor>canrepr (num xs + num ys)\\<rfloor>\"\n      using canrepr by simp\n    moreover have \"fst ?tp = \\<lfloor>?zs\\<rfloor>\"\n      by simp\n    ultimately have \"(\\<lambda>i. if Suc n - ?ln < i \\<and> i \\<le> Suc n then 0 else fst ?tp i) =\n        \\<lfloor>canrepr (num xs + num ys)\\<rfloor>\" by metis\n    moreover have \"Suc n - ?ln = m\"\n      using len_canrepr\n      by (metis add_diff_inverse_nat diff_add_inverse2 diff_is_0_eq diff_zero le_imp_less_Suc length_map\n        length_upt less_imp_le_nat less_numeral_extra(3) canlen_le_length zero_less_diff)\n    ultimately show ?thesis\n      using lconstplant[of ?tp 0 ?ln] by simp\n  qed\n  then show \"tps2 = tps1\n    [j2 := tps1 ! j2 |-| ?ln,\n     j2 := lconstplant (tps1 ! j2) 0 ?ln]\"\n    using tps2_def tps1_def jk by simp\n\n  show \"ttt = n + Suc ?ln\"\n    using assms by simp\nqed\n\ndefinition \"tps3 \\<equiv> tps0\n  [j1 := (\\<lfloor>xs\\<rfloor>, 1),\n   j2 := (\\<lfloor>canrepr (num xs + num ys)\\<rfloor>, m)]\"\n\nlemma tm3 [transforms_intros]:\n  assumes \"ttt = n + Suc (Suc n - canlen (map (sumdigit xs ys) [0..<n])) + Suc n + 2\"\n  shows \"transforms tm3 tps0 ttt tps3\"\n  unfolding tm3_def\nproof (tform tps: tps2_def jk xs ys tps0 time: assms tps2_def jk)\n  show \"clean_tape (tps2 ! j1)\"\n    using tps2_def jk xs\n    by (metis clean_tape_ncontents nth_list_update_eq nth_list_update_neq)\n  show \"tps3 = tps2[j1 := tps2 ! j1 |#=| 1]\"\n    using tps3_def tps2_def jk by (simp add: list_update_swap)\nqed\n\ndefinition \"tps4 \\<equiv> tps0\n  [j1 := (\\<lfloor>xs\\<rfloor>, 1),\n   j2 := (\\<lfloor>canrepr (num xs + num ys)\\<rfloor>, 1)]\"\n\nlemma tm4:\n  assumes \"ttt = n + Suc (Suc n - canlen (map (sumdigit xs ys) [0..<n])) + Suc n + 2 + m + 2\"\n  shows \"transforms tm4 tps0 ttt tps4\"\n  unfolding tm4_def\nproof (tform tps: tps3_def jk xs ys tps0 time: assms tps3_def jk)\n  show \"clean_tape (tps3 ! j2)\"\n    using tps3_def tps2_def jk tps0(1) by (metis clean_tape_ncontents list_update_id nth_list_update_eq)\n  show \"tps4 = tps3[j2 := tps3 ! j2 |#=| 1]\"\n    using tps4_def tps3_def jk by simp\nqed\n\nlemma tm4':\n  assumes \"ttt = 3 * max (length xs) (length ys) + 10\"\n  shows \"transforms tm4 tps0 ttt tps4\"\nproof -\n  let ?zs = \"map (sumdigit xs ys) [0..<n]\"\n  have \"num ?zs = num xs + num ys\"\n    using num_sumdigit_eq_sum'' xs ys by simp\n  then have 1: \"length (canrepr (num xs + num ys)) = canlen ?zs\"\n    using length_canrepr_canlen sumdigit_bit_symbols by blast\n  moreover have \"length ?zs = n\"\n    by simp\n  ultimately have \"m \\<le> n\"\n    by (metis canlen_le_length)\n\n  have \"n + Suc (Suc n - canlen ?zs) + Suc n + 2 + m + 2 =\n      n + Suc (Suc n - m) + Suc n + 2 + m + 2\"\n    using 1 by simp\n  also have \"... = n + Suc (Suc n - m) + Suc n + 4 + m\"\n    by simp\n  also have \"... = n + Suc (Suc n) - m + Suc n + 4 + m\"\n    using `m \\<le> n` by simp\n  also have \"... = n + Suc (Suc n) + Suc n + 4\"\n    using `m \\<le> n` by simp\n  also have \"... = 3 * n + 7\"\n    by simp\n  also have \"... = ttt\"\n    using assms by simp\n  finally have \"n + Suc (Suc n - canlen ?zs) + Suc n + 2 + m + 2 = ttt\" .\n  then show ?thesis\n    using tm4 by simp\nqed\n\ndefinition \"tps4' \\<equiv> tps0\n  [j2 := (\\<lfloor>x + y\\<rfloor>\\<^sub>N, 1)]\"\n\nlemma tm4'':\n  assumes \"ttt = 3 * max (nlength x) (nlength y) + 10\"\n  shows \"transforms tm4 tps0 ttt tps4'\"\nproof -\n  have \"canrepr (num xs + num ys) = canrepr (x + y)\"\n    by (simp add: canrepr)\n  then show ?thesis\n    using assms tps0(1) tps4'_def tps4_def tm4' by (metis list_update_id)\nqed\n\nend  (* context *)\n\nend  (* locale *)\n\nlemma transforms_tm_addI [transforms_intros]:\n  fixes j1 j2 :: tapeidx\n  fixes x y k ttt :: nat and tps tps' :: \"tape list\"\n  assumes \"j1 \\<noteq> j2\" \"j1 < k\" \"j2 < k\" \"j2 > 0\" \"k = length tps\"\n  assumes\n    \"tps ! j1 = (\\<lfloor>canrepr x\\<rfloor>, 1)\"\n    \"tps ! j2 = (\\<lfloor>canrepr y\\<rfloor>, 1)\"\n  assumes \"ttt = 3 * max (nlength x) (nlength y) + 10\"\n  assumes \"tps' = tps\n    [j2 := (\\<lfloor>x + y\\<rfloor>\\<^sub>N, 1)]\"\n  shows \"transforms (tm_add j1 j2) tps ttt tps'\"\nproof -\n  interpret loc: turing_machine_add j1 j2 .\n  show ?thesis\n    using loc.tm4_eq_tm_add loc.tps4'_def loc.tm4'' assms by simp\nqed\n\n\nsubsection \\<open>Multiplication\\<close>\n\ntext \\<open>\nIn this section we construct a Turing machine that multiplies two numbers, each\non its own tape, and writes the result to another tape. It employs the common\nalgorithm for multiplication, which for binary numbers requires only doubling a\nnumber and adding two numbers. For the latter we already have a TM; for the\nformer we are going to construct one.\n\\<close>\n\n\nsubsubsection \\<open>The common algorithm\\<close>\n\ntext \\<open>\nFor two numbers given as symbol sequences @{term xs} and @{term ys}, the common\nalgorithm maintains an intermediate result, initialized with 0, and scans @{term\nxs} starting from the most significant digit. In each step the intermediate\nresult is multiplied by two, and if the current digit of @{term xs} is @{text\n\\<one>}, the value of @{term ys} is added to the intermediate result.\n\\<close>\n\nfun prod :: \"symbol list \\<Rightarrow> symbol list \\<Rightarrow> nat \\<Rightarrow> nat\" where\n  \"prod xs ys 0 = 0\" |\n  \"prod xs ys (Suc i) = 2 * prod xs ys i + (if xs ! (length xs - 1 - i) = 3 then num ys else 0)\"\n\ntext \\<open>\nAfter $i$ steps of the algorithm, the intermediate result is the product of @{term ys}\nand the $i$ most significant bits of @{term xs}.\n\\<close>\n\nlemma prod:\n  assumes \"i \\<le> length xs\"\n  shows \"prod xs ys i = num (drop (length xs - i) xs) * num ys\"\n  using assms\nproof (induction i)\n  case 0\n  then show ?case\n    using num_def by simp\nnext\n  case (Suc i)\n  then have \"i < length xs\"\n    by simp\n  then have \"drop (length xs - Suc i) xs = (xs ! (length xs - 1 - i)) # drop (length xs - i) xs\"\n    by (metis Cons_nth_drop_Suc Suc_diff_Suc diff_Suc_eq_diff_pred\n      diff_Suc_less gr_implies_not0 length_greater_0_conv list.size(3))\n  then show ?case\n    using num_Cons Suc by simp\nqed\n\ntext \\<open>\nAfter @{term \"length xs\"} steps, the intermediate result is the final result:\n\\<close>\n\ncorollary prod_eq_prod: \"prod xs ys (length xs) = num xs * num ys\"\n  using prod by simp\n\ndefinition prod' :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> nat\" where\n  \"prod' x y i \\<equiv> prod (canrepr x) (canrepr y) i\"\n\nlemma prod': \"prod' x y (nlength x) = x * y\"\n  using prod_eq_prod prod'_def by (simp add: canrepr)\n\n\nsubsubsection \\<open>Multiplying by two\\<close>\n\ntext \\<open>\nSince we represent numbers with the least significant bit at the left, a\nmultiplication by two is a right shift with a \\textbf{0} inserted as the least\nsignificant digit. The next command implements the right shift. It scans the\ntape $j$ and memorizes the current symbol on the last tape. It only writes the\nsymbols \\textbf{0} and \\textbf{1}.\n\\<close>\n\ndefinition cmd_double :: \"tapeidx \\<Rightarrow> command\" where\n  \"cmd_double j rs \\<equiv>\n    (if rs ! j = \\<box> then 1 else 0,\n     (map (\\<lambda>i.\n       if i = j then\n         if last rs = \\<triangleright> \\<and> rs ! j = \\<box> then (rs ! i, Right)\n         else (tosym (todigit (last rs)), Right)\n       else if i = length rs - 1 then (tosym (todigit (rs ! j)), Stay)\n       else (rs ! i, Stay)) [0..<length rs]))\"\n\nlemma turing_command_double:\n  assumes \"k \\<ge> 2\" and \"G \\<ge> 4\" and \"j > 0\" and \"j < k - 1\"\n  shows \"turing_command k 1 G (cmd_double j)\"\nproof\n  show \"\\<And>gs. length gs = k \\<Longrightarrow> length ([!!] cmd_double j gs) = length gs\"\n    using cmd_double_def by simp\n  show \"\\<And>gs. length gs = k \\<Longrightarrow> 0 < k \\<Longrightarrow> cmd_double j gs [.] 0 = gs ! 0\"\n    using assms cmd_double_def by simp\n  show \"cmd_double j gs [.] j' < G\"\n    if \"length gs = k\" \"\\<And>i. i < length gs \\<Longrightarrow> gs ! i < G\" \"j' < length gs\"\n    for j' gs\n  proof -\n    consider \"j' = j\" | \"j' = k - 1\" | \"j' \\<noteq> j \\<and> j' \\<noteq> k - 1\"\n      by auto\n    then show ?thesis\n    proof (cases)\n      case 1\n      then have \"cmd_double j gs [!] j' =\n         (if last gs = \\<triangleright> \\<and> gs ! j = \\<box> then (gs ! j, Right)\n          else (tosym (todigit (last gs)), Right))\"\n        using cmd_double_def assms(1,4) that(1) by simp\n      then have \"cmd_double j gs [.] j' =\n         (if last gs = \\<triangleright> \\<and> gs ! j = \\<box> then gs ! j else tosym (todigit (last gs)))\"\n        by simp\n      then show ?thesis\n        using that assms by simp\n    next\n      case 2\n      then have \"cmd_double j gs [!] j' = (tosym (todigit (gs ! j)), Stay)\"\n        using cmd_double_def assms(1,4) that(1) by simp\n      then show ?thesis\n        using assms by simp\n    next\n      case 3\n      then show ?thesis\n        using cmd_double_def assms that by simp\n    qed\n  qed\n  show \"\\<And>gs. length gs = k \\<Longrightarrow> [*] (cmd_double j gs) \\<le> 1\"\n    using assms cmd_double_def by simp\nqed\n\nlemma sem_cmd_double_0:\n  assumes \"j < k\"\n    and \"bit_symbols xs\"\n    and \"i \\<le> length xs\"\n    and \"i > 0\"\n    and \"length tps = Suc k\"\n    and \"tps ! j = (\\<lfloor>xs\\<rfloor>, i)\"\n    and \"tps ! k = \\<lceil>z\\<rceil>\"\n    and \"tps' = tps [j := tps ! j |:=| tosym (todigit z) |+| 1, k := \\<lceil>xs ! (i - 1)\\<rceil>]\"\n  shows \"sem (cmd_double j) (0, tps) = (0, tps')\"\nproof (rule semI)\n  show \"proper_command (Suc k) (cmd_double j)\"\n    using cmd_double_def by simp\n  show \"length tps = Suc k\"\n    using assms(5) .\n  show \"length tps' = Suc k\"\n    using assms(5,8) by simp\n  show \"fst (cmd_double j (read tps)) = 0\"\n    using assms contents_def cmd_double_def tapes_at_read'[of j tps]\n    by (smt (verit, del_insts) One_nat_def Suc_le_lessD Suc_le_mono Suc_pred fst_conv\n      less_imp_le_nat snd_conv zero_neq_numeral)\n  show \"act (cmd_double j (read tps) [!] j') (tps ! j') = tps' ! j'\"\n      if \"j' < Suc k\" for j'\n  proof -\n    define rs where \"rs = read tps\"\n    then have rsj: \"rs ! j = xs ! (i - 1)\"\n      using assms tapes_at_read' contents_inbounds\n      by (metis fst_conv le_imp_less_Suc less_imp_le_nat snd_conv)\n    then have rs23: \"rs ! j = \\<zero> \\<or> rs ! j = \\<one>\"\n      using assms by simp\n    have lenrs: \"length rs = Suc k\"\n      by (simp add: rs_def assms(5) read_length)\n    consider \"j' = j\" | \"j' = k\" | \"j' \\<noteq> j \\<and> j' \\<noteq> k\"\n      by auto\n    then show ?thesis\n    proof (cases)\n      case 1\n      then have \"j' < length rs\"\n        using lenrs that by simp\n      then have \"cmd_double j rs [!] j' =\n         (if last rs = \\<triangleright> \\<and> rs ! j = \\<box> then (rs ! j, Right)\n          else (tosym (todigit (last rs)), Right))\"\n        using cmd_double_def that 1 by simp\n      then have \"cmd_double j rs [!] j' = (tosym (todigit (last rs)), Right)\"\n        using rs23 lenrs assms by auto\n      moreover have \"last rs = z\"\n        using lenrs assms(5,7) rs_def onesie_read[of z] tapes_at_read'[of _ tps]\n        by (metis diff_Suc_1 last_conv_nth length_0_conv lessI old.nat.distinct(2))\n      ultimately show ?thesis\n        using act_Right' rs_def 1 assms(1,5,8) by simp\n    next\n      case 2\n      then have \"j' = length rs - 1\" \"j' \\<noteq> j\" \"j' < length rs\"\n        using lenrs that assms(1) by simp_all\n      then have \"(cmd_double j rs) [!] j' = (tosym (todigit (rs ! j)), Stay)\"\n        using cmd_double_def by simp\n      then have \"(cmd_double j rs) [!] j' = (xs ! (i - 1), Stay)\"\n        using rsj rs23 by auto\n      then show ?thesis\n        using act_onesie rs_def 2 assms that by simp\n    next\n      case 3\n      then have \"j' \\<noteq> length rs - 1\" \"j' \\<noteq> j\" \"j' < length rs\"\n        using lenrs that by simp_all\n      then have \"(cmd_double j rs) [!] j' = (rs ! j', Stay)\"\n        using cmd_double_def by simp\n      then show ?thesis\n        using act_Stay rs_def assms that 3 by simp\n    qed\n  qed\nqed\n\nlemma sem_cmd_double_1:\n  assumes \"j < k\"\n    and \"bit_symbols xs\"\n    and \"i > length xs\"\n    and \"length tps = Suc k\"\n    and \"tps ! j = (\\<lfloor>xs\\<rfloor>, i)\"\n    and \"tps ! k = \\<lceil>z\\<rceil>\"\n    and \"tps' = tps\n      [j := tps ! j |:=| (if z = \\<triangleright> then \\<box> else tosym (todigit z)) |+| 1,\n       k := \\<lceil>\\<zero>\\<rceil>]\"\n  shows \"sem (cmd_double j) (0, tps) = (1, tps')\"\nproof (rule semI)\n  show \"proper_command (Suc k) (cmd_double j)\"\n    using cmd_double_def by simp\n  show \"length tps = Suc k\"\n    using assms(4) .\n  show \"length tps' = Suc k\"\n    using assms(4,7) by simp\n  show \"fst (cmd_double j (read tps)) = 1\"\n    using assms contents_def cmd_double_def tapes_at_read'[of j tps] by simp\n  have \"j < length tps\"\n    using assms by simp\n  show \"act (cmd_double j (read tps) [!] j') (tps ! j') = tps' ! j'\"\n      if \"j' < Suc k\" for j'\n  proof -\n    define rs where \"rs = read tps\"\n    then have rsj: \"rs ! j = \\<box>\"\n      using tapes_at_read'[OF `j < length tps`] assms(1,3,4,5) by simp\n    have lenrs: \"length rs = Suc k\"\n      by (simp add: rs_def assms(4) read_length)\n    consider \"j' = j\" | \"j' = k\" | \"j' \\<noteq> j \\<and> j' \\<noteq> k\"\n      by auto\n    then show ?thesis\n    proof (cases)\n      case 1\n      then have \"j' < length rs\"\n        using lenrs that by simp\n      then have \"cmd_double j rs [!] j' =\n         (if last rs = \\<triangleright> \\<and> rs ! j = \\<box> then (rs ! j, Right)\n          else (tosym (todigit (last rs)), Right))\"\n        using cmd_double_def that 1 by simp\n      moreover have \"last rs = z\"\n        using assms onesie_read rs_def tapes_at_read'\n        by (metis diff_Suc_1 last_conv_nth length_0_conv lenrs lessI nat.simps(3))\n      ultimately have \"cmd_double j rs [!] j' =\n         (if z = \\<triangleright> then (\\<box>, Right) else (tosym (todigit z), Right))\"\n        using rsj 1 by simp\n      then show ?thesis\n        using act_Right' rs_def 1 assms(1,4,7) by simp\n    next\n      case 2\n      then have \"j' = length rs - 1\" \"j' \\<noteq> j\" \"j' < length rs\"\n        using lenrs that assms(1) by simp_all\n      then have \"(cmd_double j rs) [!] j' = (tosym (todigit (rs ! j)), Stay)\"\n        using cmd_double_def by simp\n      then have \"(cmd_double j rs) [!] j' = (2, Stay)\"\n        using rsj by auto\n      then show ?thesis\n        using act_onesie rs_def 2 assms that by simp\n    next\n      case 3\n      then have \"j' \\<noteq> length rs - 1\" \"j' \\<noteq> j\" \"j' < length rs\"\n        using lenrs that by simp_all\n      then have \"(cmd_double j rs) [!] j' = (rs ! j', Stay)\"\n        using cmd_double_def by simp\n      then show ?thesis\n        using act_Stay rs_def assms that 3 by simp\n    qed\n  qed\nqed\n\ntext \\<open>\nThe next Turing machine consists just of the command @{const cmd_double}.\n\\<close>\n\ndefinition tm_double :: \"tapeidx \\<Rightarrow> machine\" where\n  \"tm_double j \\<equiv> [cmd_double j]\"\n\nlemma tm_double_tm:\n  assumes \"k \\<ge> 2\" and \"G \\<ge> 4\" and \"j > 0\" and \"j < k - 1\"\n  shows \"turing_machine k G (tm_double j)\"\n  using assms tm_double_def turing_command_double by auto\n\nlemma execute_tm_double_0:\n  assumes \"j < k\"\n    and \"bit_symbols xs\"\n    and \"length xs > 0\"\n    and \"length tps = Suc k\"\n    and \"tps ! j = (\\<lfloor>xs\\<rfloor>, 1)\"\n    and \"tps ! k = \\<lceil>\\<triangleright>\\<rceil>\"\n    and \"t \\<ge> 1\"\n    and \"t \\<le> length xs\"\n  shows \"execute (tm_double j) (0, tps) t =\n    (0, tps [j := (\\<lfloor>\\<zero> # take (t - 1) xs @ drop t xs\\<rfloor>, Suc t), k := \\<lceil>xs ! (t - 1)\\<rceil>])\"\n  using assms(7,8)\nproof (induction t rule: nat_induct_at_least)\n  case base\n  have \"execute (tm_double j) (0, tps) 1 = exe (tm_double j) (execute (tm_double j) (0, tps) 0)\"\n    by simp\n  also have \"... = sem (cmd_double j) (execute (tm_double j) (0, tps) 0)\"\n    using tm_double_def exe_lt_length by simp\n  also have \"... = sem (cmd_double j) (0, tps)\"\n    by simp\n  also have \"... = (0, tps [j := tps ! j |:=| tosym (todigit 1) |+| 1, k := \\<lceil>xs ! (1 - 1)\\<rceil>])\"\n    using assms(7,8) sem_cmd_double_0[OF assms(1-2) _ _ assms(4,5,6)] by simp\n  also have \"... = (0, tps [j := (\\<lfloor>\\<zero> # take (1 - 1) xs @ drop 1 xs\\<rfloor>, Suc 1), k := \\<lceil>xs ! (1 - 1)\\<rceil>])\"\n  proof -\n    have \"tps ! j |:=| tosym (todigit 1) |+| 1 = (\\<lfloor>xs\\<rfloor>, 1) |:=| tosym (todigit 1) |+| 1\"\n      using assms(5) by simp\n    also have \"... = (\\<lfloor>xs\\<rfloor>(1 := tosym (todigit 1)), Suc 1)\"\n      by simp\n    also have \"... = (\\<lfloor>xs\\<rfloor>(1 := \\<zero>), Suc 1)\"\n      by auto\n    also have \"... = (\\<lfloor>\\<zero> # drop 1 xs\\<rfloor>, Suc 1)\"\n    proof -\n      have \"\\<lfloor>\\<zero> # drop 1 xs\\<rfloor> = \\<lfloor>xs\\<rfloor>(1 := \\<zero>)\"\n      proof\n        fix i :: nat\n        consider \"i = 0\" | \"i = 1\" | \"i > 1 \\<and> i \\<le> length xs\" | \"i > length xs\"\n          by linarith\n        then show \"\\<lfloor>\\<zero> # drop 1 xs\\<rfloor> i = (\\<lfloor>xs\\<rfloor>(1 := \\<zero>)) i\"\n        proof (cases)\n          case 1\n          then show ?thesis\n            by simp\n        next\n          case 2\n          then show ?thesis\n            by simp\n        next\n          case 3\n          then have \"\\<lfloor>\\<zero> # drop 1 xs\\<rfloor> i = (\\<zero> # drop 1 xs) ! (i - 1)\"\n            using assms(3) by simp\n          also have \"... = (drop 1 xs) ! (i - 2)\"\n            using 3 by (metis Suc_1 diff_Suc_eq_diff_pred nth_Cons_pos zero_less_diff)\n          also have \"... = xs ! (Suc (i - 2))\"\n            using 3 assms(5) by simp\n          also have \"... = xs ! (i - 1)\"\n            using 3 by (metis Suc_1 Suc_diff_Suc)\n          also have \"... = \\<lfloor>xs\\<rfloor> i\"\n            using 3 by simp\n          also have \"... = (\\<lfloor>xs\\<rfloor>(1 := \\<zero>)) i\"\n            using 3 by simp\n          finally show ?thesis .\n        next\n          case 4\n          then show ?thesis\n            by simp\n        qed\n      qed\n      then show ?thesis\n        by simp\n    qed\n    also have \"... = (\\<lfloor>\\<zero> # take (1 - 1) xs @ drop 1 xs\\<rfloor>, Suc 1)\"\n      by simp\n    finally show ?thesis\n      by auto\n  qed\n  finally show ?case .\nnext\n  case (Suc t)\n  let ?xs = \"\\<zero> # take (t - 1) xs @ drop t xs\"\n  let ?z = \"xs ! (t - 1)\"\n  let ?tps = \"tps\n     [j := (\\<lfloor>?xs\\<rfloor>, Suc t),\n      k := \\<lceil>?z\\<rceil>]\"\n  have lenxs: \"length ?xs = length xs\"\n    using Suc by simp\n  have 0: \"?xs ! t = xs ! t\"\n  proof -\n    have \"t > 0\"\n      using Suc by simp\n    then have \"length (\\<zero> # take (t - 1) xs) = t\"\n      using Suc by simp\n    moreover have \"length (drop t xs) > 0\"\n      using Suc by simp\n    moreover have \"drop t xs ! 0 = xs ! t\"\n      using Suc by simp\n    ultimately have \"((\\<zero> # take (t - 1) xs) @ drop t xs) ! t = xs ! t\"\n      by (metis diff_self_eq_0 less_not_refl3 nth_append)\n    then show ?thesis\n      by simp\n  qed\n  have 1: \"bit_symbols ?xs\"\n  proof -\n    have \"bit_symbols (take (t - 1) xs)\"\n      using assms(2) by simp\n    moreover have \"bit_symbols (drop t xs)\"\n      using assms(2) by simp\n    moreover have \"bit_symbols [\\<zero>]\"\n      by simp\n    ultimately have \"bit_symbols ([\\<zero>] @ take (t - 1) xs @ drop t xs)\"\n      using bit_symbols_append by presburger\n    then show ?thesis\n      by simp\n  qed\n  have 2: \"Suc t \\<le> length ?xs\"\n    using Suc by simp\n  have 3: \"Suc t > 0\"\n    using Suc by simp\n  have 4: \"length ?tps = Suc k\"\n    using assms by simp\n  have 5: \"?tps ! j = (\\<lfloor>?xs\\<rfloor>, Suc t)\"\n    by (simp add: Suc_lessD assms(1,4) nat_neq_iff)\n  have 6: \"?tps ! k = \\<lceil>?z\\<rceil>\"\n    by (simp add: assms(4))\n  have \"execute (tm_double j) (0, tps) (Suc t) = exe (tm_double j) (execute (tm_double j) (0, tps) t)\"\n    by simp\n  also have \"... = sem (cmd_double j) (execute (tm_double j) (0, tps) t)\"\n    using tm_double_def exe_lt_length Suc by simp\n  also have \"... = sem (cmd_double j) (0, ?tps)\"\n    using Suc by simp\n  also have \"... = (0, ?tps [j := ?tps ! j |:=| tosym (todigit ?z) |+| 1, k := \\<lceil>?xs ! (Suc t - 1)\\<rceil>])\"\n    using sem_cmd_double_0[OF assms(1) 1 2 3 4 5 6] by simp\n  also have \"... = (0, ?tps [j := ?tps ! j |:=| tosym (todigit ?z) |+| 1, k := \\<lceil>xs ! (Suc t - 1)\\<rceil>])\"\n    using 0 by simp\n  also have \"... = (0, tps [j := ?tps ! j |:=| tosym (todigit ?z) |+| 1, k := \\<lceil>xs ! (Suc t - 1)\\<rceil>])\"\n    using assms by (smt (z3) list_update_overwrite list_update_swap)\n  also have \"... = (0, tps [j := (\\<lfloor>?xs\\<rfloor>, Suc t) |:=| tosym (todigit ?z) |+| 1, k := \\<lceil>xs ! (Suc t - 1)\\<rceil>])\"\n    using 5 by simp\n  also have \"... = (0, tps\n      [j := (\\<lfloor>?xs\\<rfloor>(Suc t := tosym (todigit ?z)), Suc (Suc t)),\n       k := \\<lceil>xs ! (Suc t - 1)\\<rceil>])\"\n    by simp\n  also have \"... = (0, tps\n      [j := (\\<lfloor>2 # take (Suc t - 1) xs @ drop (Suc t) xs\\<rfloor>, Suc (Suc t)),\n       k := \\<lceil>xs ! (Suc t - 1)\\<rceil>])\"\n  proof -\n    have \"\\<lfloor>?xs\\<rfloor>(Suc t := tosym (todigit ?z)) = \\<lfloor>\\<zero> # take (Suc t - 1) xs @ drop (Suc t) xs\\<rfloor>\"\n    proof\n      fix i :: nat\n      consider \"i = 0\" | \"i > 0 \\<and> i < Suc t\" | \"i = Suc t\" | \"i > Suc t \\<and> i \\<le> length xs\" | \"i > length xs\"\n        by linarith\n      then show \"(\\<lfloor>?xs\\<rfloor>(Suc t := tosym (todigit ?z))) i = \\<lfloor>\\<zero> # take (Suc t - 1) xs @ drop (Suc t) xs\\<rfloor> i\"\n      proof (cases)\n        case 1\n        then show ?thesis\n          by simp\n      next\n        case 2\n        then have lhs: \"(\\<lfloor>?xs\\<rfloor>(Suc t := tosym (todigit ?z))) i = ?xs ! (i - 1)\"\n          using lenxs Suc by simp\n        have \"\\<lfloor>\\<zero> # take (Suc t - 1) xs @ drop (Suc t) xs\\<rfloor> i =\n            (\\<zero> # take (Suc t - 1) xs @ drop (Suc t) xs) ! (i - 1)\"\n          using Suc 2 by auto\n        then have \"\\<lfloor>\\<zero> # take (Suc t - 1) xs @ drop (Suc t) xs\\<rfloor> i =\n            ((\\<zero> # take (Suc t - 1) xs) @ drop (Suc t) xs) ! (i - 1)\"\n          by simp\n        moreover have \"length (\\<zero> # take (Suc t - 1) xs) = Suc t\"\n          using Suc.prems by simp\n        ultimately have \"\\<lfloor>\\<zero> # take (Suc t - 1) xs @ drop (Suc t) xs\\<rfloor> i =\n            (\\<zero> # take (Suc t - 1) xs) ! (i - 1)\"\n          using 2 by (metis Suc_diff_1 Suc_lessD nth_append)\n        also have \"... = (\\<zero> # take t xs) ! (i - 1)\"\n          by simp\n        also have \"... = (\\<zero> # take (t - 1) xs @ [xs ! (t - 1)]) ! (i - 1)\"\n          using Suc by (metis Suc_diff_le Suc_le_lessD Suc_lessD diff_Suc_1 take_Suc_conv_app_nth)\n        also have \"... = ((\\<zero> # take (t - 1) xs) @ [xs ! (t - 1)]) ! (i - 1)\"\n          by simp\n        also have \"... = (\\<zero> # take (t - 1) xs) ! (i - 1)\"\n          using 2 Suc\n          by (metis One_nat_def Suc_leD Suc_le_eq Suc_pred length_Cons length_take less_Suc_eq_le\n            min_absorb2 nth_append)\n        also have \"... = ((\\<zero> # take (t - 1) xs) @ drop t xs) ! (i - 1)\"\n          using 2 Suc\n          by (metis Suc_diff_1 Suc_diff_le Suc_leD Suc_lessD diff_Suc_1 length_Cons length_take\n            less_Suc_eq min_absorb2 nth_append)\n        also have \"... = ?xs ! (i - 1)\"\n          by simp\n        finally have \"\\<lfloor>\\<zero> # take (Suc t - 1) xs @ drop (Suc t) xs\\<rfloor> i = ?xs ! (i - 1)\" .\n        then show ?thesis\n          using lhs by simp\n      next\n        case 3\n        moreover have \"?z = \\<zero> \\<or> ?z = \\<one>\"\n          using `bit_symbols ?xs` Suc assms(2) by (metis Suc_diff_le Suc_leD Suc_le_lessD diff_Suc_1)\n        ultimately have lhs: \"(\\<lfloor>?xs\\<rfloor>(Suc t := tosym (todigit ?z))) i = ?z\"\n          by auto\n        have \"\\<lfloor>\\<zero> # take (Suc t - 1) xs @ drop (Suc t) xs\\<rfloor> i =\n            \\<lfloor>(\\<zero> # take t xs) @ drop (Suc t) xs\\<rfloor> (Suc t)\"\n          using 3 by simp\n        also have \"... = ((\\<zero> # take t xs) @ drop (Suc t) xs) ! t\"\n          using 3 Suc by simp\n        also have \"... = (\\<zero> # take t xs) ! t\"\n          using Suc by (metis Suc_leD length_Cons length_take lessI min_absorb2 nth_append)\n        also have \"... = xs ! (t - 1)\"\n          using Suc by simp\n        finally have \"\\<lfloor>\\<zero> # take (Suc t - 1) xs @ drop (Suc t) xs\\<rfloor> i = ?z\" .\n        then show ?thesis\n          using lhs by simp\n      next\n        case 4\n        then have \"(\\<lfloor>?xs\\<rfloor>(Suc t := tosym (todigit ?z))) i = \\<lfloor>?xs\\<rfloor> i\"\n          by simp\n        also have \"... = ?xs ! (i - 1)\"\n          using 4 by auto\n        also have \"... = ((\\<zero> # take (t - 1) xs) @ drop t xs) ! (i - 1)\"\n          by simp\n        also have \"... = drop t xs ! (i - 1 - t)\"\n          using 4 Suc\n          by (smt (verit, ccfv_threshold) Cons_eq_appendI Suc_diff_1 Suc_leD\n            add_diff_cancel_right' bot_nat_0.extremum_uniqueI diff_diff_cancel\n            length_append length_drop lenxs not_le not_less_eq nth_append)\n        also have \"... = xs ! (i - 1)\"\n          using 4 Suc by simp\n        finally have lhs: \"(\\<lfloor>?xs\\<rfloor>(Suc t := tosym (todigit ?z))) i = xs ! (i - 1)\" .\n        have \"\\<lfloor>\\<zero> # take (Suc t - 1) xs @ drop (Suc t) xs\\<rfloor> i =\n            (\\<zero> # take (Suc t - 1) xs @ drop (Suc t) xs) ! (i - 1)\"\n          using 4 by auto\n        also have \"... = ((\\<zero> # take t xs) @ drop (Suc t) xs) ! (i - 1)\"\n          by simp\n        also have \"... = (drop (Suc t) xs) ! (i - 1 - Suc t)\"\n          using Suc 4\n          by (smt (z3) Suc_diff_1 Suc_leD Suc_leI bot_nat_0.extremum_uniqueI length_Cons length_take\n            min_absorb2 not_le nth_append)\n        also have \"... = xs ! (i - 1)\"\n          using Suc 4 Suc_lessE by fastforce\n        finally have \"\\<lfloor>\\<zero> # take (Suc t - 1) xs @ drop (Suc t) xs\\<rfloor> i = xs ! (i - 1)\" .\n        then show ?thesis\n          using lhs by simp\n      next\n        case 5\n        then have \"(\\<lfloor>?xs\\<rfloor>(Suc t := tosym (todigit ?z))) i = \\<lfloor>?xs\\<rfloor> i\"\n          using Suc by simp\n        then have lhs: \"(\\<lfloor>?xs\\<rfloor>(Suc t := tosym (todigit ?z))) i = \\<box>\"\n          using 5 contents_outofbounds lenxs by simp\n        have \"length (\\<zero> # take (Suc t - 1) xs @ drop (Suc t) xs) = length xs\"\n          using Suc by simp\n        then have \"\\<lfloor>\\<zero> # take (Suc t - 1) xs @ drop (Suc t) xs\\<rfloor> i = \\<box>\"\n          using 5 contents_outofbounds by simp\n        then show ?thesis\n          using lhs by simp\n      qed\n    qed\n    then show ?thesis\n      by simp\n  qed\n  finally show ?case .\nqed\n\nlemma execute_tm_double_1:\n  assumes \"j < k\"\n    and \"bit_symbols xs\"\n    and \"length xs > 0\"\n    and \"length tps = Suc k\"\n    and \"tps ! j = (\\<lfloor>xs\\<rfloor>, 1)\"\n    and \"tps ! k = \\<lceil>\\<triangleright>\\<rceil>\"\n  shows \"execute (tm_double j) (0, tps) (Suc (length xs)) =\n    (1, tps [j := (\\<lfloor>\\<zero> # xs\\<rfloor>, length xs + 2), k := \\<lceil>\\<zero>\\<rceil>])\"\nproof -\n  let ?z = \"xs ! (length xs - 1)\"\n  let ?xs = \"\\<zero> # take (length xs - 1) xs\"\n  have \"?z \\<noteq> \\<triangleright>\"\n    using assms(2,3) by (metis One_nat_def Suc_1 diff_less less_Suc_eq not_less_eq numeral_3_eq_3)\n  have z23: \"?z = \\<zero> \\<or> ?z = \\<one>\"\n    using assms(2,3) by (meson diff_less zero_less_one)\n  have lenxs: \"length ?xs = length xs\"\n    using assms(3) by (metis Suc_diff_1 diff_le_self length_Cons length_take min_absorb2)\n  have 0: \"bit_symbols ?xs\"\n    using assms(2) bit_symbols_append[of \"[\\<zero>]\" \"take (length xs - 1) xs\"] by simp\n\n  have \"execute (tm_double j) (0, tps) (length xs) =\n    (0, tps\n      [j := (\\<lfloor>\\<zero> # take (length xs - 1) xs @ drop (length xs) xs\\<rfloor>, Suc (length xs)),\n       k := \\<lceil>?z\\<rceil>])\"\n    using execute_tm_double_0[OF assms(1-6), where ?t=\"length xs\"] assms(3) by simp\n  then have *: \"execute (tm_double j) (0, tps) (length xs) =\n    (0, tps [j := (\\<lfloor>?xs\\<rfloor>, Suc (length ?xs)), k := \\<lceil>?z\\<rceil>])\"\n    (is \"_ = (0, ?tps)\")\n    using lenxs by simp\n\n  let ?i = \"Suc (length ?xs)\"\n  have 1: \"?i > length ?xs\"\n    by simp\n  have 2: \"length ?tps = Suc k\"\n    using assms(4) by simp\n  have 3: \"?tps ! j = (\\<lfloor>?xs\\<rfloor>, ?i)\"\n    using assms(1,4) by simp\n  have 4: \"?tps ! k = \\<lceil>?z\\<rceil>\"\n    using assms(4) by simp\n\n  have \"execute (tm_double j) (0, tps) (Suc (length xs)) = exe (tm_double j) (0, ?tps)\"\n    using * by simp\n  also have \"... = sem (cmd_double j) (0, ?tps)\"\n    using tm_double_def exe_lt_length by simp\n  also have \"... = (1, ?tps\n      [j := ?tps ! j |:=| (if ?z = \\<triangleright> then \\<box> else tosym (todigit ?z)) |+| 1,\n       k := \\<lceil>\\<zero>\\<rceil>])\"\n    using sem_cmd_double_1[OF assms(1) 0 1 2 3 4] by simp\n  also have \"... = (1, ?tps\n      [j := ?tps ! j |:=| (tosym (todigit ?z)) |+| 1,\n       k := \\<lceil>\\<zero>\\<rceil>])\"\n    using `?z \\<noteq> 1` by simp\n  also have \"... = (1, ?tps\n      [j := (\\<lfloor>?xs\\<rfloor>, Suc (length ?xs)) |:=| (tosym (todigit ?z)) |+| 1,\n       k := \\<lceil>\\<zero>\\<rceil>])\"\n    using 3 by simp\n  also have \"... = (1, ?tps\n      [j := (\\<lfloor>?xs\\<rfloor>, Suc (length ?xs)) |:=| ?z |+| 1,\n       k := \\<lceil>\\<zero>\\<rceil>])\"\n    using z23 One_nat_def Suc_1 add_2_eq_Suc' numeral_3_eq_3 by presburger\n  also have \"... = (1, tps\n      [j := (\\<lfloor>?xs\\<rfloor>, Suc (length ?xs)) |:=| ?z |+| 1,\n       k := \\<lceil>\\<zero>\\<rceil>])\"\n    by (smt (z3) list_update_overwrite list_update_swap)\n  also have \"... = (1, tps\n      [j := (\\<lfloor>?xs\\<rfloor>(Suc (length ?xs) := ?z), length ?xs + 2),\n       k := \\<lceil>\\<zero>\\<rceil>])\"\n    by simp\n  also have \"... = (1, tps\n      [j := (\\<lfloor>?xs\\<rfloor>(Suc (length ?xs) := ?z), length xs + 2),\n       k := \\<lceil>\\<zero>\\<rceil>])\"\n    using lenxs by simp\n  also have \"... = (1, tps [j := (\\<lfloor>\\<zero> # xs\\<rfloor>, length xs + 2), k := \\<lceil>\\<zero>\\<rceil>])\"\n  proof -\n    have \"\\<lfloor>?xs\\<rfloor>(Suc (length ?xs) := ?z) = \\<lfloor>\\<zero> # xs\\<rfloor>\"\n    proof\n      fix i\n      consider \"i = 0\" | \"i > 0 \\<and> i \\<le> length xs\" | \"i = Suc (length xs)\" | \"i > Suc (length xs)\"\n        by linarith\n      then show \"(\\<lfloor>?xs\\<rfloor>(Suc (length ?xs) := ?z)) i = \\<lfloor>\\<zero> # xs\\<rfloor> i\"\n      proof (cases)\n        case 1\n        then show ?thesis\n          by simp\n      next\n        case 2\n        then have \"(\\<lfloor>?xs\\<rfloor>(Suc (length ?xs) := ?z)) i = \\<lfloor>?xs\\<rfloor> i\"\n          using lenxs by simp\n        also have \"... = ?xs ! (i - 1)\"\n          using 2 by auto\n        also have \"... = (\\<zero> # xs) ! (i - 1)\"\n          using lenxs 2 assms(3) by (metis Suc_diff_1 Suc_le_lessD nth_take take_Suc_Cons)\n        also have \"... = \\<lfloor>\\<zero> # xs\\<rfloor> i\"\n          using 2 by simp\n        finally show ?thesis .\n      next\n        case 3\n        then have lhs: \"(\\<lfloor>?xs\\<rfloor>(Suc (length ?xs) := ?z)) i = ?z\"\n          using lenxs by simp\n        have \"\\<lfloor>\\<zero> # xs\\<rfloor> i = (\\<zero> # xs) ! (i - 1)\"\n          using 3 lenxs by simp\n        also have \"... = xs ! (i - 2)\"\n          using 3 assms(3) by simp\n        also have \"... = ?z\"\n          using 3 by simp\n        finally have \"\\<lfloor>\\<zero> # xs\\<rfloor> i = ?z\" .\n        then show ?thesis\n          using lhs by simp\n      next\n        case 4\n        then show ?thesis\n          using 4 lenxs by simp\n      qed\n    qed\n    then show ?thesis\n      by simp\n  qed\n  finally show ?thesis .\nqed\n\nlemma execute_tm_double_Nil:\n  assumes \"j < k\"\n    and \"length tps = Suc k\"\n    and \"tps ! j = (\\<lfloor>[]\\<rfloor>, 1)\"\n    and \"tps ! k = \\<lceil>\\<triangleright>\\<rceil>\"\n  shows \"execute (tm_double j) (0, tps) (Suc 0) =\n    (1, tps [j := (\\<lfloor>[]\\<rfloor>, 2), k := \\<lceil>\\<zero>\\<rceil>])\"\nproof -\n  have \"execute (tm_double j) (0, tps) (Suc 0) = exe (tm_double j) (execute (tm_double j) (0, tps) 0)\"\n    by simp\n  also have \"... = exe (tm_double j) (0, tps)\"\n    by simp\n  also have \"... = sem (cmd_double j) (0, tps)\"\n    using tm_double_def exe_lt_length by simp\n  also have \"... = (1, tps\n      [j := tps ! j |:=| (if (1::nat) = 1 then 0 else tosym (todigit 1)) |+| 1,\n       k := \\<lceil>\\<zero>\\<rceil>])\"\n    using sem_cmd_double_1[OF assms(1) _ _ assms(2-4)] by simp\n  also have \"... = (1, tps [j := tps ! j |:=| \\<box> |+| 1, k := \\<lceil>\\<zero>\\<rceil>])\"\n    by simp\n  also have \"... = (1, tps [j := (\\<lfloor>[]\\<rfloor>, 1) |:=| \\<box> |+| 1, k := \\<lceil>\\<zero>\\<rceil>])\"\n    using assms(3) by simp\n  also have \"... = (1, tps [j := (\\<lfloor>[]\\<rfloor>(1 := \\<box>), 2), k := \\<lceil>\\<zero>\\<rceil>])\"\n    by (metis fst_eqD one_add_one snd_eqD)\n  also have \"... = (1, tps [j := (\\<lfloor>[]\\<rfloor>, 2), k := \\<lceil>\\<zero>\\<rceil>])\"\n    by (metis contents_outofbounds fun_upd_idem_iff list.size(3) zero_less_one)\n  finally show ?thesis .\nqed\n\nlemma execute_tm_double:\n  assumes \"j < k\"\n    and \"length tps = Suc k\"\n    and \"tps ! j = (\\<lfloor>canrepr n\\<rfloor>, 1)\"\n    and \"tps ! k = \\<lceil>\\<triangleright>\\<rceil>\"\n  shows \"execute (tm_double j) (0, tps) (Suc (length (canrepr n))) =\n    (1, tps [j := (\\<lfloor>canrepr (2 * n)\\<rfloor>, length (canrepr n) + 2), k := \\<lceil>\\<zero>\\<rceil>])\"\nproof (cases \"n = 0\")\n  case True\n  then have \"canrepr n = []\"\n    using canrepr_0 by simp\n  then show ?thesis\n    using execute_tm_double_Nil[OF assms(1-2) _ assms(4)] assms(3) True\n    by (metis add_2_eq_Suc' list.size(3) mult_0_right numeral_2_eq_2)\nnext\n  case False\n  let ?xs = \"canrepr n\"\n  have \"num (\\<zero> # ?xs) = 2 * num ?xs\"\n    using num_Cons by simp\n  then have \"num (\\<zero> # ?xs) = 2 * n\"\n    using canrepr by simp\n  moreover have \"canonical (\\<zero> # ?xs)\"\n  proof -\n    have \"?xs \\<noteq> []\"\n      using False canrepr canrepr_0 by metis\n    then show ?thesis\n      using canonical_Cons canonical_canrepr by simp\n  qed\n  ultimately have \"canrepr (2 * n) = \\<zero> # ?xs\"\n    using canreprI by blast\n  then show ?thesis\n    using execute_tm_double_1[OF assms(1) _ _ assms(2) _ assms(4)] assms(3) False canrepr canrepr_0 bit_symbols_canrepr\n    by (metis length_greater_0_conv)\nqed\n\nlemma execute_tm_double_app:\n  assumes \"j < k\"\n    and \"length tps = k\"\n    and \"tps ! j = (\\<lfloor>canrepr n\\<rfloor>, 1)\"\n  shows \"execute (tm_double j) (0, tps @ [\\<lceil>\\<triangleright>\\<rceil>]) (Suc (length (canrepr n))) =\n    (1, tps [j := (\\<lfloor>canrepr (2 * n)\\<rfloor>, length (canrepr n) + 2)] @ [\\<lceil>\\<zero>\\<rceil>])\"\nproof -\n  let ?tps = \"tps @ [\\<lceil>\\<triangleright>\\<rceil>]\"\n  have \"length ?tps = Suc k\"\n    using assms(2) by simp\n  moreover have \"?tps ! j = (\\<lfloor>canrepr n\\<rfloor>, 1)\"\n    using assms(1,2,3) by (simp add: nth_append)\n  moreover have \"?tps ! k = \\<lceil>\\<triangleright>\\<rceil>\"\n    using assms(2) by (simp add: nth_append)\n  moreover have \"tps [j := (\\<lfloor>canrepr (2 * n)\\<rfloor>, length (canrepr n) + 2)] @ [\\<lceil>\\<zero>\\<rceil>] =\n      ?tps [j := (\\<lfloor>canrepr (2 * n)\\<rfloor>, length (canrepr n) + 2), k := \\<lceil>\\<zero>\\<rceil>]\"\n    using assms by (metis length_list_update list_update_append1 list_update_length)\n  ultimately show ?thesis\n    using assms execute_tm_double[OF assms(1), where ?tps=\"tps @ [\\<lceil>\\<triangleright>\\<rceil>]\"]\n    by simp\nqed\n\nlemma transforms_tm_double:\n  assumes \"j < k\"\n    and \"length tps = k\"\n    and \"tps ! j = (\\<lfloor>canrepr n\\<rfloor>, 1)\"\n  shows \"transforms (tm_double j)\n    (tps @ [\\<lceil>\\<triangleright>\\<rceil>])\n    (Suc (length (canrepr n)))\n    (tps [j := (\\<lfloor>canrepr (2 * n)\\<rfloor>, length (canrepr n) + 2)] @ [\\<lceil>\\<zero>\\<rceil>])\"\n  using assms transforms_def transits_def tm_double_def execute_tm_double_app by auto\n\nlemma tm_double_immobile:\n  fixes k :: nat\n  assumes \"j > 0\" and \"j < k\"\n  shows \"immobile (tm_double j) k (Suc k)\"\nproof -\n  let ?M = \"tm_double j\"\n  { fix q :: nat and rs :: \"symbol list\"\n    assume q: \"q < length ?M\"\n    assume rs: \"length rs = Suc k\"\n    then have len: \"length rs - 1 = k\"\n      by simp\n    have neq: \"k \\<noteq> j\"\n      using assms(2) by simp\n    have \"?M ! q = cmd_double j\"\n      using tm_double_def q by simp\n    moreover have \"(cmd_double j) rs [!] k = (tosym (todigit (rs ! j)), Stay)\"\n      using cmd_double_def rs len neq by fastforce\n    ultimately have \"(cmd_double j) rs [~] k = Stay\"\n      by simp\n  }\n  then show ?thesis\n    by (simp add: immobile_def tm_double_def)\nqed\n\nlemma tm_double_bounded_write:\n  assumes \"j < k - 1\"\n  shows \"bounded_write (tm_double j) (k - 1) 4\"\n  using assms cmd_double_def tm_double_def bounded_write_def by simp\n\ntext \\<open>\nThe next Turing machine removes the memorization tape.\n\\<close>\n\ndefinition tm_double' :: \"nat \\<Rightarrow> machine\" where\n  \"tm_double' j \\<equiv> cartesian (tm_double j) 4\"\n\nlemma tm_double'_tm:\n  assumes \"j > 0\" and \"k \\<ge> 2\" and \"G \\<ge> 4\" and \"j < k\"\n  shows \"turing_machine k G (tm_double' j)\"\n  unfolding tm_double'_def using assms cartesian_tm tm_double_tm by simp\n\nlemma transforms_tm_double'I [transforms_intros]:\n  assumes \"j > 0\" and \"j < k\"\n    and \"length tps = k\"\n    and \"tps ! j = (\\<lfloor>canrepr n\\<rfloor>, 1)\"\n    and \"t = (Suc (length (canrepr n)))\"\n    and \"tps' = tps [j := (\\<lfloor>canrepr (2 * n)\\<rfloor>, length (canrepr n) + 2)]\"\n  shows \"transforms (tm_double' j) tps t tps'\"\n  unfolding tm_double'_def\nproof (rule cartesian_transforms_onesie)\n  show \"turing_machine (Suc k) 4 (tm_double j)\"\n    using assms(1,2) tm_double_tm by simp\n  show \"length tps = k\" \"2 \\<le> k\" \"(1::nat) < 4\"\n    using assms by simp_all\n  show \"bounded_write (tm_double j) k 4\"\n    by (metis assms(2) diff_Suc_1 tm_double_bounded_write)\n  show \"immobile (tm_double j) k (Suc k)\"\n    by (simp add: assms(1,2) tm_double_immobile)\n  show \"transforms (tm_double j) (tps @ [\\<lceil>\\<triangleright>\\<rceil>]) t (tps' @ [\\<lceil>\\<zero>\\<rceil>])\"\n    using assms transforms_tm_double by simp\nqed\n\ntext \\<open>\nThe next Turing machine is the one we actually use to double a number. It runs\n@{const tm_double'} and performs a carriage return.\n\\<close>\n\ndefinition tm_times2 :: \"tapeidx \\<Rightarrow> machine\" where\n  \"tm_times2 j \\<equiv> tm_double' j ;; tm_cr j\"\n\nlemma tm_times2_tm:\n  assumes \"k \\<ge> 2\" and \"j > 0\" and \"j < k\" and \"G \\<ge> 4\"\n  shows \"turing_machine k G (tm_times2 j)\"\n  using assms by (simp add: assms(1) tm_cr_tm tm_double'_tm tm_times2_def)\n\nlemma transforms_tm_times2I [transforms_intros]:\n  assumes \"j > 0\" and \"j < k\"\n    and \"length tps = k\"\n    and \"tps ! j = (\\<lfloor>n\\<rfloor>\\<^sub>N, 1)\"\n    and \"t = 5 + 2 * nlength n\"\n    and \"tps' = tps [j := (\\<lfloor>2 * n\\<rfloor>\\<^sub>N, 1)]\"\n  shows \"transforms (tm_times2 j) tps t tps'\"\n  unfolding tm_times2_def\nproof (tform tps: assms)\n  show \"clean_tape (tps[j := (\\<lfloor>2 * n\\<rfloor>\\<^sub>N, nlength n + 2)] ! j)\"\n    using clean_tape_ncontents assms by simp\n  show \"t = Suc (nlength n) + (tps[j := (\\<lfloor>2 * n\\<rfloor>\\<^sub>N, nlength n + 2)] :#: j + 2)\"\n    using assms by simp\nqed\n\n\nsubsubsection \\<open>Multiplying arbitrary numbers\\<close>\n\ntext \\<open>\nBefore we can multiply arbitrary numbers we need just a few more lemmas.\n\n\\null\n\\<close>\n\nlemma num_drop_le_nu: \"num (drop j xs) \\<le> num xs\"\nproof (cases \"j \\<le> length xs\")\n  case True\n  let ?ys = \"drop j xs\"\n  have map_shift_upt: \"map (\\<lambda>i. f (j + i)) [0..<l] = map f [j..<j + l]\"\n      for f :: \"nat \\<Rightarrow> nat\" and j l\n    by (rule nth_equalityI) simp_all\n\n  have \"num ?ys = (\\<Sum>i\\<leftarrow>[0..<length ?ys]. todigit (?ys ! i) * 2 ^ i)\"\n    using num_def by simp\n  also have \"... = (\\<Sum>i\\<leftarrow>[0..<length ?ys]. todigit (xs ! (j + i)) * 2 ^ i)\"\n    by (simp add: True)\n  also have \"... \\<le> 2 ^ j * (\\<Sum>i\\<leftarrow>[0..<length ?ys].  todigit (xs ! (j + i)) * 2 ^ i)\"\n    by simp\n  also have \"... = (\\<Sum>i\\<leftarrow>[0..<length ?ys]. 2 ^ j * todigit (xs ! (j + i)) * 2 ^ i)\"\n    by (simp add: mult.assoc sum_list_const_mult)\n  also have \"... = (\\<Sum>i\\<leftarrow>[0..<length ?ys]. todigit (xs ! (j + i)) * 2 ^ (j + i))\"\n    by (simp add: ab_semigroup_mult_class.mult_ac(1) mult.commute power_add)\n  also have \"... = (\\<Sum>i\\<leftarrow>[j..<j + length ?ys]. todigit (xs ! i) * 2 ^ i)\"\n    using map_shift_upt[of \"\\<lambda>i. todigit (xs ! i) * 2 ^ i\" j \"length ?ys\"] by simp\n  also have \"... \\<le> (\\<Sum>i\\<leftarrow>[0..<j]. todigit (xs ! i) * 2 ^ i) +\n      (\\<Sum>i\\<leftarrow>[j..<j + length ?ys]. todigit (xs ! i) * 2 ^ i)\"\n    by simp\n  also have \"... = (\\<Sum>i\\<leftarrow>[0..<j + length ?ys]. todigit (xs ! i) * 2 ^ i)\"\n    by (metis (no_types, lifting) le_add2 le_add_same_cancel2 map_append sum_list.append upt_add_eq_append)\n  also have \"... = (\\<Sum>i\\<leftarrow>[0..<length xs]. todigit (xs ! i) * 2 ^ i)\"\n    by (simp add: True)\n  also have \"... = num xs\"\n    using num_def by simp\n  finally show ?thesis .\nnext\n  case False\n  then show ?thesis\n    using canrepr canrepr_0 by (metis drop_all nat_le_linear zero_le)\nqed\n\nlemma nlength_prod_le_prod:\n  assumes \"i \\<le> length xs\"\n  shows \"nlength (prod xs ys i) \\<le> nlength (num xs * num ys)\"\n  using prod[OF assms] num_drop_le_nu mult_le_mono1 nlength_mono by simp\n\ncorollary nlength_prod'_le_prod:\n  assumes \"i \\<le> nlength x\"\n  shows \"nlength (prod' x y i) \\<le> nlength (x * y)\"\n  using assms prod'_def nlength_prod_le_prod by (metis prod' prod_eq_prod)\n\nlemma two_times_prod:\n  assumes \"i < length xs\"\n  shows \"2 * prod xs ys i \\<le> num xs * num ys\"\nproof -\n  have \"2 * prod xs ys i \\<le> prod xs ys (Suc i)\"\n    by simp\n  also have \"... = num (drop (length xs - Suc i) xs) * num ys\"\n    using prod[of \"Suc i\" xs] assms by simp\n  also have \"... \\<le> num xs * num ys\"\n    using num_drop_le_nu by simp\n  finally show ?thesis .\nqed\n\ncorollary two_times_prod':\n  assumes \"i < nlength x\"\n  shows \"2 * prod' x y i \\<le> x * y\"\n  using assms two_times_prod prod'_def by (metis prod' prod_eq_prod)\n\ntext \\<open>\nThe next Turing machine multiplies the numbers on tapes $j_1$ and $j_2$ and\nwrites the result to tape $j_3$. It iterates over the binary digits on $j_1$\nstarting from the most significant digit. In each iteration it doubles the\nintermediate result on $j_3$. If the current digit is @{text \\<one>}, the number on\n$j_2$ is added to $j_3$.\n\\<close>\n\ndefinition tm_mult :: \"tapeidx \\<Rightarrow> tapeidx \\<Rightarrow> tapeidx \\<Rightarrow> machine\" where\n  \"tm_mult j1 j2 j3 \\<equiv>\n    tm_right_until j1 {\\<box>} ;;\n    tm_left j1 ;;\n    WHILE [] ; \\<lambda>rs. rs ! j1 \\<noteq> \\<triangleright> DO\n      tm_times2 j3 ;;\n      IF \\<lambda>rs. rs ! j1 = \\<one> THEN\n        tm_add j2 j3\n      ELSE\n        []\n      ENDIF ;;\n      tm_left j1\n    DONE ;;\n    tm_right j1\"\n\nlemma tm_mult_tm:\n  assumes \"j1 \\<noteq> j2\" \"j2 \\<noteq> j3\" \"j3 \\<noteq> j1\" and \"j3 > 0\"\n  assumes \"k \\<ge> 2\"\n    and \"G \\<ge> 4\"\n    and \"j1 < k\" \"j2 < k\" \"j3 < k\"\n  shows \"turing_machine k G (tm_mult j1 j2 j3)\"\n  unfolding tm_mult_def\n  using assms tm_left_tm tm_right_tm Nil_tm tm_add_tm tm_times2_tm tm_right_until_tm\n    turing_machine_branch_turing_machine turing_machine_loop_turing_machine\n  by simp\n\nlocale turing_machine_mult =\n  fixes j1 j2 j3 :: tapeidx\nbegin\n\ndefinition \"tm1 \\<equiv> tm_right_until j1 {\\<box>}\"\ndefinition \"tm2 \\<equiv> tm1 ;; tm_left j1\"\ndefinition \"tmIf \\<equiv> IF \\<lambda>rs. rs ! j1 = \\<one> THEN tm_add j2 j3 ELSE [] ENDIF\"\ndefinition \"tmBody1 \\<equiv> tm_times2 j3 ;; tmIf\"\ndefinition \"tmBody \\<equiv> tmBody1 ;; tm_left j1\"\ndefinition \"tmWhile \\<equiv> WHILE [] ; \\<lambda>rs. rs ! j1 \\<noteq> \\<triangleright> DO tmBody DONE\"\ndefinition \"tm3 \\<equiv> tm2 ;; tmWhile\"\ndefinition \"tm4 \\<equiv> tm3 ;; tm_right j1\"\n\nlemma tm4_eq_tm_mult: \"tm4 = tm_mult j1 j2 j3\"\n  using tm1_def tm2_def tm3_def tm4_def tm_mult_def tmIf_def tmBody_def tmBody1_def tmWhile_def\n  by simp\n\ncontext\n  fixes x y k :: nat and tps0 :: \"tape list\"\n  assumes jk: \"j1 \\<noteq> j2\" \"j2 \\<noteq> j3\" \"j3 \\<noteq> j1\" \"j3 > 0\" \"j1 < k\" \"j2 < k\" \"j3 < k\" \"length tps0 = k\"\n  assumes tps0:\n    \"tps0 ! j1 = (\\<lfloor>x\\<rfloor>\\<^sub>N, 1)\"\n    \"tps0 ! j2 = (\\<lfloor>y\\<rfloor>\\<^sub>N, 1)\"\n    \"tps0 ! j3 = (\\<lfloor>0\\<rfloor>\\<^sub>N, 1)\"\nbegin\n\ndefinition \"tps1 \\<equiv> tps0 [j1 := (\\<lfloor>x\\<rfloor>\\<^sub>N, Suc (nlength x))]\"\n\nlemma tm1 [transforms_intros]:\n  assumes \"t = Suc (nlength x)\"\n  shows \"transforms tm1 tps0 t tps1\"\n  unfolding tm1_def\nproof (tform tps: assms tps0 tps1_def jk)\n  show \"rneigh (tps0 ! j1) {\\<box>} (nlength x)\"\n  proof (rule rneighI)\n    show \"(tps0 ::: j1) (tps0 :#: j1 + nlength x) \\<in> {\\<box>}\"\n      by (simp add: tps0)\n    show \"\\<And>n'. n' < nlength x \\<Longrightarrow> (tps0 ::: j1) (tps0 :#: j1 + n') \\<notin> {\\<box>}\"\n      using tps0 bit_symbols_canrepr contents_def by fastforce\n  qed\nqed\n\ndefinition \"tps2 \\<equiv> tps0 [j1 := (\\<lfloor>x\\<rfloor>\\<^sub>N, nlength x)]\"\n\nlemma tm2 [transforms_intros]:\n  assumes \"t = Suc (Suc (nlength x))\" and \"tps' = tps2\"\n  shows \"transforms tm2 tps0 t tps'\"\n  unfolding tm2_def by (tform tps: assms tps1_def tps2_def jk)\n\ndefinition \"tpsL t \\<equiv> tps0\n   [j1 := (\\<lfloor>x\\<rfloor>\\<^sub>N, nlength x - t),\n    j3 := (\\<lfloor>prod' x y t\\<rfloor>\\<^sub>N, 1)]\"\n\ndefinition \"tpsL1 t \\<equiv> tps0\n   [j1 := (\\<lfloor>x\\<rfloor>\\<^sub>N, nlength x - t),\n    j3 := (\\<lfloor>2 * prod' x y t\\<rfloor>\\<^sub>N, 1)]\"\n\ndefinition \"tpsL2 t \\<equiv> tps0\n   [j1 := (\\<lfloor>x\\<rfloor>\\<^sub>N, nlength x - t),\n    j3 := (\\<lfloor>prod' x y (Suc t)\\<rfloor>\\<^sub>N, 1)]\"\n\ndefinition \"tpsL3 t \\<equiv> tps0\n   [j1 := (\\<lfloor>x\\<rfloor>\\<^sub>N, nlength x - t - 1),\n    j3 := (\\<lfloor>prod' x y (Suc t)\\<rfloor>\\<^sub>N, 1)]\"\n\nlemma tmIf [transforms_intros]:\n  assumes \"t < nlength x\" and \"ttt = 12 + 3 * nlength (x * y)\"\n  shows \"transforms tmIf (tpsL1 t) ttt (tpsL2 t)\"\n  unfolding tmIf_def\nproof (tform tps: assms tpsL1_def tps0 jk)\n  have \"nlength y \\<le> nlength (x * y) \\<and> nlength (2 * prod' x y t) \\<le> nlength (x * y)\"\n  proof\n    have \"x > 0\"\n      using assms(1) gr_implies_not_zero nlength_0 by auto\n    then have \"y \\<le> x * y\"\n      by simp\n    then show \"nlength y \\<le> nlength (x * y)\"\n      using nlength_mono by simp\n    show \"nlength (2 * prod' x y t) \\<le> nlength (x * y)\"\n      using assms(1) by (simp add: nlength_mono two_times_prod')\n  qed\n  then show \"3 * max (nlength y) (nlength (2 * Arithmetic.prod' x y t)) + 10 + 2 \\<le> ttt\"\n    using assms(2) by simp\n  let ?xs = \"canrepr x\" and ?ys = \"canrepr y\"\n  let ?r = \"read (tpsL1 t) ! j1\"\n  have \"?r = (\\<lfloor>x\\<rfloor>\\<^sub>N) (nlength x - t)\"\n    using tpsL1_def jk tapes_at_read'\n    by (metis fst_conv length_list_update list_update_swap nth_list_update_eq snd_conv)\n  then have r: \"?r = canrepr x ! (nlength x - 1 - t)\"\n    using assms contents_def by simp\n  have \"prod' x y (Suc t) = 2 * prod' x y t + (if ?xs ! (length ?xs - 1 - t) = \\<one> then num ?ys else 0)\"\n    using prod'_def by simp\n  also have \"... = 2 * prod' x y t + (if ?r = \\<one> then num ?ys else 0)\"\n    using r by simp\n  also have \"... = 2 * prod' x y t + (if ?r = \\<one> then y else 0)\"\n    using canrepr by simp\n  finally have \"prod' x y (Suc t) = 2 * prod' x y t + (if ?r = \\<one> then y else 0)\" .\n  then show \"read (tpsL1 t) ! j1 \\<noteq> \\<one> \\<Longrightarrow> tpsL2 t = tpsL1 t\"\n       and \"read (tpsL1 t) ! j1 = \\<one> \\<Longrightarrow>\n      tpsL2 t = (tpsL1 t) [j3 := (\\<lfloor>y + 2 * Arithmetic.prod' x y t\\<rfloor>\\<^sub>N, 1)]\"\n    by (simp_all add: add.commute tpsL1_def tpsL2_def)\nqed\n\nlemma tmBody1 [transforms_intros]:\n  assumes \"t < nlength x\"\n    and \"ttt = 17 + 2 * nlength (Arithmetic.prod' x y t) + 3 * nlength (x * y)\"\n  shows \"transforms tmBody1 (tpsL t) ttt (tpsL2 t)\"\n  unfolding tmBody1_def by (tform tps: jk tpsL_def tpsL1_def assms(1) time: assms(2))\n\nlemma tmBody:\n  assumes \"t < nlength x\"\n    and \"ttt = 6 + 2 * nlength (prod' x y t) + (12 + 3 * nlength (x * y))\"\n  shows \"transforms tmBody (tpsL t) ttt (tpsL (Suc t))\"\n  unfolding tmBody_def by (tform tps: jk tpsL_def tpsL2_def assms(1) time: assms(2))\n\nlemma tmBody' [transforms_intros]:\n  assumes \"t < nlength x\" and \"ttt = 18 + 5 * nlength (x * y)\"\n  shows \"transforms tmBody (tpsL t) ttt (tpsL (Suc t))\"\nproof -\n  have \"6 + 2 * nlength (prod' x y t) + (12 + 3 * nlength (x * y)) \\<le> 18 + 5 * nlength (x * y)\"\n    using assms nlength_prod'_le_prod by simp\n  then show ?thesis\n    using tmBody assms transforms_monotone by blast\nqed\n\nlemma read_contents:\n  fixes tps :: \"tape list\" and j :: tapeidx and zs :: \"symbol list\"\n  assumes \"tps ! j = (\\<lfloor>zs\\<rfloor>, i)\" and \"i > 0\" and \"i \\<le> length zs\" and \"j < length tps\"\n  shows \"read tps ! j = zs ! (i - 1)\"\n  using assms tapes_at_read' by fastforce\n\nlemma tmWhile [transforms_intros]:\n  assumes \"ttt = 1 + 25 * (nlength x + nlength y) * (nlength x + nlength y)\"\n  shows \"transforms tmWhile (tpsL 0) ttt (tpsL (nlength x))\"\n  unfolding tmWhile_def\nproof (tform)\n  show \"read (tpsL i) ! j1 \\<noteq> \\<triangleright>\" if \"i < nlength x\" for i\n  proof -\n    have \"(tpsL i) ! j1 = (\\<lfloor>x\\<rfloor>\\<^sub>N, nlength x - i)\"\n      using tpsL_def jk by simp\n    moreover have *: \"nlength x - i > 0\" \"nlength x - i \\<le> length (canrepr x)\"\n      using that by simp_all\n    moreover have \"length (tpsL i) = k\"\n      using tpsL_def jk by simp\n    ultimately have \"read (tpsL i) ! j1 = canrepr x ! (nlength x - i - 1)\"\n      using jk read_contents by simp\n    then show ?thesis\n      using * bit_symbols_canrepr\n      by (metis One_nat_def Suc_le_lessD Suc_pred less_numeral_extra(4) proper_symbols_canrepr)\n  qed\n  show \"\\<not> read (tpsL (nlength x)) ! j1 \\<noteq> \\<triangleright>\"\n  proof -\n    have \"(tpsL (nlength x)) ! j1 = (\\<lfloor>x\\<rfloor>\\<^sub>N, nlength x - nlength x)\"\n      using tpsL_def jk by simp\n    then have \"(tpsL (nlength x)) ! j1 = (\\<lfloor>x\\<rfloor>\\<^sub>N, 0)\"\n      by simp\n    then have \"read (tpsL (nlength x)) ! j1 = \\<triangleright>\"\n      using tapes_at_read' tpsL_def contents_at_0 jk by (metis fst_conv length_list_update snd_conv)\n    then show ?thesis\n      by simp\n  qed\n  show \"nlength x * (18 + 5 * nlength (x * y) + 2) + 1 \\<le> ttt\"\n  proof (cases \"x = 0\")\n    case True\n    then show ?thesis\n      using assms by simp\n  next\n    case False\n    have \"nlength x * (18 + 5 * nlength (x * y) + 2) + 1 = nlength x * (20 + 5 * nlength (x * y)) + 1\"\n      by simp\n    also have \"... \\<le> nlength x * (20 + 5 * (nlength x + nlength y)) + 1\"\n      using nlength_prod by (meson add_mono le_refl mult_le_mono)\n    also have \"... \\<le> nlength x * (20 * (nlength x + nlength y) + 5 * (nlength x + nlength y)) + 1\"\n    proof -\n      have \"1 \\<le> nlength x + nlength y\"\n        using False nlength_0 by (simp add: Suc_leI)\n      then show ?thesis\n        by simp\n    qed\n    also have \"... \\<le> nlength x * (25 * (nlength x + nlength y)) + 1\"\n      by simp\n    also have \"... \\<le> (nlength x + nlength y) * (25 * (nlength x + nlength y)) + 1\"\n      by simp\n    finally show ?thesis\n      using assms by linarith\n  qed\nqed\n\nlemma tm3:\n  assumes \"ttt = Suc (Suc (nlength x)) +\n    Suc ((25 * nlength x + 25 * nlength y) * (nlength x + nlength y))\"\n  shows \"transforms tm3 tps0 ttt (tpsL (nlength x))\"\n  unfolding tm3_def\nproof (tform time: assms)\n  show \"tpsL 0 = tps2\"\n  proof -\n    have \"prod' x y 0 = 0\"\n      using prod'_def by simp\n    then show ?thesis\n      using tpsL_def tps2_def jk tps0 by (metis diff_zero list_update_id list_update_swap)\n  qed\nqed\n\ndefinition \"tps3 \\<equiv> tps0\n   [j1 := (\\<lfloor>x\\<rfloor>\\<^sub>N, 0),\n    j3 := (\\<lfloor>x * y\\<rfloor>\\<^sub>N, 1)]\"\n\nlemma tm3' [transforms_intros]:\n  assumes \"ttt = 3 + 26 * (nlength x + nlength y) * (nlength x + nlength y)\"\n  shows \"transforms tm3 tps0 ttt tps3\"\nproof -\n  have \"Suc (Suc (nlength x)) + Suc ((25 * nlength x + 25 * nlength y) * (nlength x + nlength y)) \\<le>\n      Suc (Suc (nlength x + nlength y)) + Suc ((25 * nlength x + 25 * nlength y) * (nlength x + nlength y))\"\n    by simp\n  also have \"... \\<le> 2 + (nlength x + nlength y) * (nlength x + nlength y) + 1 +\n      25 * (nlength x + nlength y) * (nlength x + nlength y)\"\n    by (simp add: le_square)\n  also have \"... = 3 + 26 * (nlength x + nlength y) * (nlength x + nlength y)\"\n    by linarith\n  finally have \"Suc (Suc (nlength x)) + Suc ((25 * nlength x + 25 * nlength y) * (nlength x + nlength y)) \\<le>\n      3 + 26 * (nlength x + nlength y) * (nlength x + nlength y)\" .\n  moreover have \"tps3 = tpsL (nlength x)\"\n    using tps3_def tpsL_def by (simp add: prod')\n  ultimately show ?thesis\n    using tm3 assms transforms_monotone by simp\nqed\n\ndefinition \"tps4 \\<equiv> tps0\n  [j3 := (\\<lfloor>x * y\\<rfloor>\\<^sub>N, 1)]\"\n\nlemma tm4:\n  assumes \"ttt = 4 + 26 * (nlength x + nlength y) * (nlength x + nlength y)\"\n  shows \"transforms tm4 tps0 ttt tps4\"\n  unfolding tm4_def\nproof (tform tps: tps3_def jk time: assms)\n  show \"tps4 = tps3[j1 := tps3 ! j1 |+| 1]\"\n    using tps4_def tps3_def jk tps0\n    by (metis One_nat_def add.right_neutral add_Suc_right fst_conv list_update_id list_update_overwrite\n     list_update_swap nth_list_update_eq nth_list_update_neq snd_conv)\nqed\n\nend  (* context x y k tps0 *)\n\nend  (* locale turing_machine_mult *)\n\nlemma transforms_tm_mult [transforms_intros]:\n  fixes j1 j2 j3 :: tapeidx and x y k ttt :: nat and tps tps' :: \"tape list\"\n  assumes \"j1 \\<noteq> j2\" \"j2 \\<noteq> j3\" \"j3 \\<noteq> j1\" \"j3 > 0\"\n  assumes \"length tps = k\"\n    and \"j1 < k\" \"j2 < k\" \"j3 < k\"\n    and \"tps ! j1 = (\\<lfloor>x\\<rfloor>\\<^sub>N, 1)\"\n    and \"tps ! j2 = (\\<lfloor>y\\<rfloor>\\<^sub>N, 1)\"\n    and \"tps ! j3 = (\\<lfloor>0\\<rfloor>\\<^sub>N, 1)\"\n    and \"ttt = 4 + 26 * (nlength x + nlength y) * (nlength x + nlength y)\"\n    and \"tps' = tps [j3 := (\\<lfloor>x * y\\<rfloor>\\<^sub>N, 1)]\"\n  shows \"transforms (tm_mult j1 j2 j3) tps ttt tps'\"\nproof -\n  interpret loc: turing_machine_mult j1 j2 j3 .\n  show ?thesis\n    using assms loc.tps4_def loc.tm4 loc.tm4_eq_tm_mult by metis\nqed\n\n\nsubsection \\<open>Powers\\<close>\n\ntext \\<open>\nIn this section we construct for every $d \\in \\nat$ a Turing machine that\ncomputes $n^d$. The following TMs expect a number $n$ on tape $j_1$ and output\n$n^d$ on tape $j_3$. Another tape, $j_2$, is used as scratch space to hold\nintermediate values. The TMs initialize tape $j_3$ with~1 and then multiply this\nvalue by $n$ for $d$ times using the TM @{const tm_mult}.\n\\<close>\n\nfun tm_pow :: \"nat \\<Rightarrow> tapeidx \\<Rightarrow> tapeidx \\<Rightarrow> tapeidx \\<Rightarrow> machine\" where\n  \"tm_pow 0 j1 j2 j3 = tm_setn j3 1\" |\n  \"tm_pow (Suc d) j1 j2 j3 =\n     tm_pow d j1 j2 j3 ;; (tm_copyn j3 j2 ;; tm_setn j3 0 ;; tm_mult j1 j2 j3 ;; tm_setn j2 0)\"\n\nlemma tm_pow_tm:\n  assumes \"j1 \\<noteq> j2\" \"j2 \\<noteq> j3\" \"j3 \\<noteq> j1\"\n    and \"0 < j2\" \"0 < j3\" \"0 < j1\"\n  assumes \"j1 < k\" \"j2 < k\" \"j3 < k\"\n    and \"k \\<ge> 2\"\n    and \"G \\<ge> 4\"\n  shows \"turing_machine k G (tm_pow d j1 j2 j3)\"\n  using assms tm_copyn_tm tm_setn_tm tm_mult_tm by (induction d) simp_all\n\nlocale turing_machine_pow =\n  fixes j1 j2 j3 :: tapeidx\nbegin\n\ndefinition \"tm1 \\<equiv> tm_copyn j3 j2 ;; tm_setn j3 0\"\ndefinition \"tm2 \\<equiv> tm1 ;; tm_mult j1 j2 j3\"\ndefinition \"tm3 \\<equiv> tm2 ;; tm_setn j2 0\"\n\nfun tm4 :: \"nat \\<Rightarrow> machine\" where\n  \"tm4 0 = tm_setn j3 1\" |\n  \"tm4 (Suc d) = tm4 d ;; tm3\"\n\nlemma tm4_eq_tm_pow: \"tm4 d = tm_pow d j1 j2 j3\"\n  using tm3_def tm2_def tm1_def by (induction d) simp_all\n\ncontext\n  fixes x y k :: nat and tps0 :: \"tape list\"\n  assumes jk: \"k = length tps0\" \"j1 < k\" \"j2 < k\" \"j3 < k\"\n      \"j1 \\<noteq> j2\" \"j2 \\<noteq> j3\" \"j3 \\<noteq> j1\"\n      \"0 < j2\" \"0 < j3\" \"0 < j1\"\n  assumes tps0:\n    \"tps0 ! j1 = (\\<lfloor>x\\<rfloor>\\<^sub>N, 1)\"\n    \"tps0 ! j2 = (\\<lfloor>0\\<rfloor>\\<^sub>N, 1)\"\n    \"tps0 ! j3 = (\\<lfloor>y\\<rfloor>\\<^sub>N, 1)\"\nbegin\n\ndefinition \"tps1 \\<equiv> tps0\n  [j2 := (\\<lfloor>y\\<rfloor>\\<^sub>N, 1), j3 := (\\<lfloor>0\\<rfloor>\\<^sub>N, 1)]\"\n\nlemma tm1 [transforms_intros]:\n  assumes \"ttt = 24 + 5 * nlength y\"\n  shows \"transforms tm1 tps0 ttt tps1\"\n  unfolding tm1_def\nproof (tform tps: assms jk tps0 tps1_def)\n  show \"ttt = 14 + 3 * (nlength y + nlength 0) + (10 + 2 * nlength y + 2 * nlength 0)\"\n    using assms by simp\nqed\n\ndefinition \"tps2 \\<equiv> tps0\n  [j2 := (\\<lfloor>y\\<rfloor>\\<^sub>N, 1),\n   j3 := (\\<lfloor>x * y\\<rfloor>\\<^sub>N, 1)]\"\n\nlemma tm2 [transforms_intros]:\n  assumes \"ttt = 28 + 5 * nlength y + (26 * nlength x + 26 * nlength y) * (nlength x + nlength y)\"\n  shows \"transforms tm2 tps0 ttt tps2\"\n  unfolding tm2_def\nproof (tform tps: jk tps1_def time: assms)\n  show \"tps1 ! j1 = (\\<lfloor>x\\<rfloor>\\<^sub>N, 1)\"\n    using jk tps0 tps1_def by simp\n  show \"tps2 = tps1[j3 := (\\<lfloor>x * y\\<rfloor>\\<^sub>N, 1)]\"\n    using tps2_def tps1_def by simp\nqed\n\ndefinition \"tps3 \\<equiv> tps0\n  [j3 := (\\<lfloor>x * y\\<rfloor>\\<^sub>N, 1)]\"\n\nlemma tm3:\n  assumes \"ttt = 38 + 7 * nlength y + (26 * nlength x + 26 * nlength y) * (nlength x + nlength y)\"\n  shows \"transforms tm3 tps0 ttt tps3\"\n  unfolding tm3_def\nproof (tform tps: jk tps2_def time: assms)\n  show \"tps3 = tps2[j2 := (\\<lfloor>0\\<rfloor>\\<^sub>N, 1)]\"\n    using tps3_def tps2_def jk by (metis list_update_id list_update_overwrite list_update_swap tps0(2))\nqed\n\nlemma tm3':\n  assumes \"ttt = 38 + 33 * (nlength x + nlength y) ^ 2\"\n  shows \"transforms tm3 tps0 ttt tps3\"\nproof -\n  have \"38 + 7 * nlength y + (26 * nlength x + 26 * nlength y) * (nlength x + nlength y) =\n      38 + 7 * nlength y + 26 * (nlength x + nlength y) * (nlength x + nlength y)\"\n    by simp\n  also have \"... \\<le> 38 + 33 * (nlength x + nlength y) * (nlength x + nlength y)\"\n  proof -\n    have \"nlength y \\<le> (nlength x + nlength y) * (nlength x + nlength y)\"\n      by (meson le_add2 le_square le_trans)\n    then show ?thesis\n      by linarith\n  qed\n  also have \"... = 38 + 33 * (nlength x + nlength y) ^ 2\"\n    by algebra\n  finally have \"38 + 7 * nlength y + (26 * nlength x + 26 * nlength y) * (nlength x + nlength y) \\<le> ttt\"\n    using assms(1) by simp\n  then show ?thesis\n    using tm3 transforms_monotone assms by meson\nqed\n\nend  (* context x y k tps0 *)\n\nlemma tm3'' [transforms_intros]:\n  fixes x d k :: nat and tps0 :: \"tape list\"\n  assumes \"k = length tps0\"\n    and \"j1 < k\" \"j2 < k\" \"j3 < k\"\n  assumes j_neq [simp]: \"j1 \\<noteq> j2\" \"j2 \\<noteq> j3\" \"j3 \\<noteq> j1\"\n    and j_gt [simp]: \"0 < j2\" \"0 < j3\" \"0 < j1\"\n    and \"tps0 ! j1 = (\\<lfloor>x\\<rfloor>\\<^sub>N, 1)\"\n    and \"tps0 ! j2 = (\\<lfloor>0\\<rfloor>\\<^sub>N, 1)\"\n    and \"tps0 ! j3 = (\\<lfloor>x ^ d\\<rfloor>\\<^sub>N, 1)\"\n    and \"ttt = 71 + 99 * (Suc d) ^ 2 * (nlength x) ^ 2\"\n    and \"tps' = tps0 [j3 := (\\<lfloor>x ^ Suc d\\<rfloor>\\<^sub>N, 1)]\"\n  shows \"transforms tm3 tps0 ttt tps'\"\nproof -\n  let ?l = \"nlength x\"\n  have \"transforms tm3 tps0 (38 + 33 * (nlength x + nlength (x ^ d)) ^ 2) tps'\"\n    using tm3' assms tps3_def by simp\n  moreover have \"38 + 33 * (nlength x + nlength (x ^ d)) ^ 2 \\<le> 71 + 99 * (Suc d) ^ 2 * ?l ^ 2\"\n  proof -\n    have \"38 + 33 * (nlength x + nlength (x ^ d)) ^ 2 \\<le> 38 + 33 * (Suc (Suc d * ?l)) ^ 2\"\n      using nlength_pow by simp\n    also have \"... = 38 + 33 * ((Suc d * ?l)^2 + 2 * (Suc d * ?l) * 1 + 1^2)\"\n      by (metis Suc_eq_plus1 add_Suc one_power2 power2_sum)\n    also have \"... = 38 + 33 * ((Suc d * ?l)^2 + 2 * (Suc d * ?l) + 1)\"\n      by simp\n    also have \"... \\<le> 38 + 33 * ((Suc d * ?l)^2 + 2 * (Suc d * ?l)^2 + 1)\"\n    proof -\n      have \"(Suc d * ?l) \\<le> (Suc d * ?l) ^ 2\"\n        by (simp add: le_square power2_eq_square)\n      then show ?thesis\n        by simp\n    qed\n    also have \"... \\<le> 38 + 33 * (3 * (Suc d * ?l)^2 + 1)\"\n      by simp\n    also have \"... = 38 + 33 * (3 * (Suc d) ^ 2 * ?l^2 + 1)\"\n      by algebra\n    also have \"... = 71 + 99 * (Suc d) ^ 2 * ?l ^ 2\"\n      by simp\n    finally show ?thesis .\n  qed\n  ultimately show ?thesis\n    using transforms_monotone assms(14) by blast\nqed\n\ncontext\n  fixes x k :: nat and tps0 :: \"tape list\"\n  assumes jk: \"j1 < k\" \"j2 < k\" \"j3 < k\" \"j1 \\<noteq> j2\" \"j2 \\<noteq> j3\" \"j3 \\<noteq> j1\" \"0 < j2\" \"0 < j3\" \"0 < j1\" \"k = length tps0\"\n  assumes tps0:\n    \"tps0 ! j1 = (\\<lfloor>x\\<rfloor>\\<^sub>N, 1)\"\n    \"tps0 ! j2 = (\\<lfloor>0\\<rfloor>\\<^sub>N, 1)\"\n    \"tps0 ! j3 = (\\<lfloor>0\\<rfloor>\\<^sub>N, 1)\"\nbegin\n\nlemma tm4:\n  fixes d :: nat\n  assumes \"tps' = tps0 [j3 := (\\<lfloor>x ^ d\\<rfloor>\\<^sub>N, 1)]\"\n    and \"ttt = 12 + 71 * d + 99 * d ^ 3 * (nlength x) ^ 2\"\n  shows \"transforms (tm4 d) tps0 ttt tps'\"\n  using assms\nproof (induction d arbitrary: tps' ttt)\n  case 0\n  have \"tm4 0 = tm_setn j3 1\"\n    by simp\n  let ?tps = \"tps0 [j3 := (\\<lfloor>1\\<rfloor>\\<^sub>N, 1)]\"\n  let ?t = \"10 + 2 * nlength 1\"\n  have \"transforms (tm_setn j3 1) tps0 ?t ?tps\"\n    using transforms_tm_setnI[of j3 tps0 0 ?t 1 ?tps] jk tps0 by simp\n  then have \"transforms (tm_setn j3 1) tps0 ?t tps'\"\n    using 0 by simp\n  then show ?case\n    using 0 nlength_1_simp by simp\nnext\n  case (Suc d)\n  note Suc.IH [transforms_intros]\n\n  let ?l = \"nlength x\"\n  have \"tm4 (Suc d) = tm4 d ;; tm3\"\n    by simp\n  define t where\n    \"t = 12 + 71 * d + 99 * d ^ 3 * (nlength x)\\<^sup>2 + (71 + 99 * (Suc d)\\<^sup>2 * (nlength x)\\<^sup>2)\"\n  have \"transforms (tm4 d ;; tm3) tps0 t tps'\"\n    by (tform tps: jk tps0 Suc.prems(1) time: t_def)\n  moreover have \"t \\<le> 12 + 71 * Suc d + 99 * Suc d ^ 3 * ?l\\<^sup>2\"\n  proof -\n    have \"t = 12 + d * 71 + 99 * d ^ 3 * ?l\\<^sup>2 + (71 + 99 * (Suc d)\\<^sup>2 * ?l\\<^sup>2)\"\n      using t_def by simp\n    also have \"... = 12 + Suc d * 71 + 99 * d ^ 3 * ?l\\<^sup>2 + 99 * (Suc d)\\<^sup>2 * ?l\\<^sup>2\"\n      by simp\n    also have \"... = 12 + Suc d * 71 + 99 * ?l^2 * (d ^ 3 + (Suc d)\\<^sup>2)\"\n      by algebra\n    also have \"... \\<le> 12 + Suc d * 71 + 99 * ?l^2 * Suc d ^ 3\"\n    proof -\n      have \"Suc d ^ 3 = Suc d * Suc d ^ 2\"\n        by algebra\n      also have \"... = Suc d * (d ^ 2 + 2 * d + 1)\"\n        by (metis (no_types, lifting) Suc_1 add.commute add_Suc mult_2 one_power2 plus_1_eq_Suc power2_sum)\n      also have \"... = (d + 1) * (d ^ 2 + 2 * d + 1)\"\n        by simp\n      also have \"... = d ^ 3 + 2 * d ^ 2 + d + d ^ 2 + 2 * d + 1\"\n        by algebra\n      also have \"... = d ^ 3 + (d + 1) ^ 2 + 2 * d ^ 2 + d\"\n        by algebra\n      also have \"... \\<ge> d ^ 3 + (d + 1) ^ 2\"\n        by simp\n      finally have \"Suc d ^ 3 \\<ge> d ^ 3 + Suc d ^ 2\"\n        by simp\n      then show ?thesis\n        by simp\n    qed\n    also have \"... = 12 + 71 * Suc d + 99 * Suc d ^ 3 * ?l^2\"\n      by simp\n    finally show ?thesis .\n  qed\n  ultimately show ?case\n    using transforms_monotone Suc by simp\nqed\n\nend  (* context x k tps0 *)\n\nend  (* locale turing_machine_power *)\n\nlemma transforms_tm_pow [transforms_intros]:\n  fixes d :: nat\n  assumes \"j1 \\<noteq> j2\" \"j2 \\<noteq> j3\" \"j3 \\<noteq> j1\" \"0 < j2\" \"0 < j3\" \"0 < j1\" \"j1 < k\" \"j2 < k\" \"j3 < k\" \"k = length tps\"\n  assumes\n    \"tps ! j1 = (\\<lfloor>x\\<rfloor>\\<^sub>N, 1)\"\n    \"tps ! j2 = (\\<lfloor>0\\<rfloor>\\<^sub>N, 1)\"\n    \"tps ! j3 = (\\<lfloor>0\\<rfloor>\\<^sub>N, 1)\"\n  assumes \"ttt = 12 + 71 * d + 99 * d ^ 3 * (nlength x) ^ 2\"\n  assumes \"tps' = tps [j3 := (\\<lfloor>x ^ d\\<rfloor>\\<^sub>N, 1)]\"\n  shows \"transforms (tm_pow d j1 j2 j3) tps ttt tps'\"\nproof -\n  interpret loc: turing_machine_pow j1 j2 j3 .\n  show ?thesis\n    using assms loc.tm4_eq_tm_pow loc.tm4 by metis\nqed\n\n\nsubsection \\<open>Monomials\\<close>\n\ntext \\<open>\nA monomial is a power multiplied by a constant coefficient. The following Turing\nmachines have parameters $c$ and $d$ and expect a number $x$ on tape $j$. They\noutput $c\\cdot x^d$ on tape $j + 3$. The tapes $j+1$ and $j+2$ are\nscratch space for use by @{const tm_pow} and @{const tm_mult}.\n\\<close>\n\ndefinition tm_monomial :: \"nat \\<Rightarrow> nat \\<Rightarrow> tapeidx \\<Rightarrow> machine\" where\n  \"tm_monomial c d j \\<equiv>\n    tm_pow d j (j + 1) (j + 2) ;;\n    tm_setn (j + 1) c ;;\n    tm_mult (j + 1) (j + 2) (j + 3);;\n    tm_setn (j + 1) 0 ;;\n    tm_setn (j + 2) 0\"\n\nlemma tm_monomial_tm:\n  assumes \"k \\<ge> 2\" and \"G \\<ge> 4\" and \"j + 3 < k\" and \"0 < j\"\n  shows \"turing_machine k G (tm_monomial c d j)\"\n  unfolding tm_monomial_def\n  using assms tm_setn_tm tm_mult_tm tm_pow_tm turing_machine_sequential_turing_machine\n  by simp\n\nlocale turing_machine_monomial =\n  fixes c d :: nat and j :: tapeidx\nbegin\n\ndefinition \"tm1 \\<equiv> tm_pow d j (j + 1) (j + 2)\"\ndefinition \"tm2 \\<equiv> tm1 ;; tm_setn (j + 1) c\"\ndefinition \"tm3 \\<equiv> tm2 ;; tm_mult (j + 1) (j + 2) (j + 3)\"\ndefinition \"tm4 \\<equiv> tm3 ;; tm_setn (j + 1) 0\"\ndefinition \"tm5 \\<equiv> tm4 ;; tm_setn (j + 2) 0\"\n\nlemma tm5_eq_tm_monomial: \"tm5 = tm_monomial c d j\"\n  unfolding tm1_def tm2_def tm3_def tm4_def tm5_def tm_monomial_def by simp\n\ncontext\n  fixes x k :: nat and tps0 :: \"tape list\"\n  assumes jk: \"k = length tps0\" \"j + 3 < k\" \"0 < j\"\n  assumes tps0:\n    \"tps0 ! j = (\\<lfloor>x\\<rfloor>\\<^sub>N, 1)\"\n    \"tps0 ! (j + 1) = (\\<lfloor>0\\<rfloor>\\<^sub>N, 1)\"\n    \"tps0 ! (j + 2) = (\\<lfloor>0\\<rfloor>\\<^sub>N, 1)\"\n    \"tps0 ! (j + 3) = (\\<lfloor>0\\<rfloor>\\<^sub>N, 1)\"\nbegin\n\ndefinition \"tps1 \\<equiv> tps0 [(j + 2) := (\\<lfloor>x ^ d\\<rfloor>\\<^sub>N, 1)]\"\n\nlemma tm1 [transforms_intros]:\n  assumes \"ttt = 12 + 71 * d + 99 * d ^ 3 * (nlength x) ^ 2\"\n  shows \"transforms tm1 tps0 ttt tps1\"\n  unfolding tm1_def by (tform tps: assms tps0 jk tps1_def)\n\ndefinition \"tps2 \\<equiv> tps0\n  [j + 2 := (\\<lfloor>x ^ d\\<rfloor>\\<^sub>N, 1),\n   j + 1 := (\\<lfloor>c\\<rfloor>\\<^sub>N, 1)]\"\n\nlemma tm2 [transforms_intros]:\n  assumes \"ttt = 22 + 71 * d + 99 * d ^ 3 * (nlength x)\\<^sup>2 + 2 * nlength c\"\n  shows \"transforms tm2 tps0 ttt tps2\"\n  unfolding tm2_def\nproof (tform tps: assms tps0 jk tps2_def tps1_def)\n  show \"ttt = 12 + 71 * d + 99 * d ^ 3 * (nlength x)\\<^sup>2 + (10 + 2 * nlength 0 + 2 * nlength c)\"\n    using assms(1) by simp\nqed\n\ndefinition \"tps3 \\<equiv> tps0\n  [j + 2 := (\\<lfloor>x ^ d\\<rfloor>\\<^sub>N, 1),\n   j + 1 := (\\<lfloor>c\\<rfloor>\\<^sub>N, 1),\n   j + 3 := (\\<lfloor>c * x ^ d\\<rfloor>\\<^sub>N, 1)]\"\n\nlemma tm3 [transforms_intros]:\n  assumes \"ttt = 26 + 71 * d + 99 * d ^ 3 * (nlength x)\\<^sup>2 + 2 * nlength c +\n    26 * (nlength c + nlength (x ^ d)) ^ 2\"\n  shows \"transforms tm3 tps0 ttt tps3\"\n  unfolding tm3_def\nproof (tform tps: tps2_def tps3_def tps0 jk)\n  show \"ttt = 22 + 71 * d + 99 * d ^ 3 * (nlength x)\\<^sup>2 + 2 * nlength c +\n      (4 + 26 * (nlength c + nlength (x ^ d)) * (nlength c + nlength (x ^ d)))\"\n    using assms by algebra\nqed\n\ndefinition \"tps4 \\<equiv> tps0\n  [j + 2 := (\\<lfloor>x ^ d\\<rfloor>\\<^sub>N, 1),\n   j + 3 := (\\<lfloor>c * x ^ d\\<rfloor>\\<^sub>N, 1)]\"\n\nlemma tm4 [transforms_intros]:\n  assumes \"ttt = 36 + 71 * d + 99 * d ^ 3 * (nlength x)\\<^sup>2 + 4 * nlength c +\n    26 * (nlength c + nlength (x ^ d))\\<^sup>2\"\n  shows \"transforms tm4 tps0 ttt tps4\"\n  unfolding tm4_def\nproof (tform tps: tps4_def tps3_def tps0 jk time: assms)\n  show \"tps4 = tps3[j + 1 := (\\<lfloor>0\\<rfloor>\\<^sub>N, 1)]\"\n    unfolding tps4_def tps3_def\n    using jk tps0(2) list_update_id[of tps0 \"Suc j\"] by (simp add: list_update_swap)\nqed\n\ndefinition \"tps5 \\<equiv> tps0\n  [j + 3 := (\\<lfloor>c * x ^ d\\<rfloor>\\<^sub>N, 1)]\"\n\nlemma tm5:\n  assumes \"ttt = 46 + 71 * d + 99 * d ^ 3 * (nlength x)\\<^sup>2 + 4 * nlength c +\n    26 * (nlength c + nlength (x ^ d))\\<^sup>2 +\n    (2 * nlength (x ^ d))\"\n  shows \"transforms tm5 tps0 ttt tps5\"\n  unfolding tm5_def\nproof (tform tps: tps5_def tps4_def jk time: assms)\n  show \"tps5 = tps4[j + 2 := (\\<lfloor>0\\<rfloor>\\<^sub>N, 1)]\"\n    unfolding tps5_def tps4_def\n    using jk tps0 list_update_id[of tps0 \"Suc (Suc j)\"]\n    by (simp add: list_update_swap)\nqed\n\nlemma tm5':\n  assumes \"ttt = 46 + 71 * d + 99 * d ^ 3 * (nlength x)\\<^sup>2 + 32 * (nlength c + nlength (x ^ d))\\<^sup>2\"\n  shows \"transforms tm5 tps0 ttt tps5\"\nproof -\n  let ?t = \"46 + 71 * d + 99 * d ^ 3 * (nlength x)\\<^sup>2 + 4 * nlength c +\n    26 * (nlength c + nlength (x ^ d))\\<^sup>2 + (2 * nlength (x ^ d))\"\n  have \"?t \\<le> 46 + 71 * d + 99 * d ^ 3 * (nlength x)\\<^sup>2 + 4 * nlength c +\n    28 * (nlength c + nlength (x ^ d))\\<^sup>2\"\n  proof -\n    have \"2 * nlength (x ^ d) \\<le> 2 * (nlength c + nlength (x ^ d))\\<^sup>2\"\n      by (meson add_leE eq_imp_le mult_le_mono2 power2_nat_le_imp_le)\n    then show ?thesis\n      by simp\n  qed\n  also have \"... \\<le> 46 + 71 * d + 99 * d ^ 3 * (nlength x)\\<^sup>2 + 32 * (nlength c + nlength (x ^ d))\\<^sup>2\"\n  proof -\n    have \"4 * nlength c \\<le> 4 * (nlength c + nlength (x ^ d))\\<^sup>2\"\n      by (simp add: power2_nat_le_eq_le power2_nat_le_imp_le)\n    then show ?thesis\n      by simp\n  qed\n  also have \"... = ttt\"\n    using assms(1) by simp\n  finally have \"?t \\<le> ttt\" .\n  then show ?thesis\n    using assms transforms_monotone tm5 by blast\nqed\n\nend  (* context x k *)\n\nend  (* locale *)\n\nlemma transforms_tm_monomialI [transforms_intros]:\n  fixes ttt x k :: nat and tps tps' :: \"tape list\" and j :: tapeidx\n  assumes \"j > 0\" and \"j + 3 < k\" and \"k = length tps\"\n  assumes\n    \"tps ! j = (\\<lfloor>x\\<rfloor>\\<^sub>N, 1)\"\n    \"tps ! (j + 1) = (\\<lfloor>0\\<rfloor>\\<^sub>N, 1)\"\n    \"tps ! (j + 2) = (\\<lfloor>0\\<rfloor>\\<^sub>N, 1)\"\n    \"tps ! (j + 3) = (\\<lfloor>0\\<rfloor>\\<^sub>N, 1)\"\n  assumes \"ttt = 46 + 71 * d + 99 * d ^ 3 * (nlength x)\\<^sup>2 + 32 * (nlength c + nlength (x ^ d))\\<^sup>2\"\n  assumes \"tps' = tps[j + 3 := (\\<lfloor>c * x ^ d\\<rfloor>\\<^sub>N, 1)]\"\n  shows \"transforms (tm_monomial c d j) tps ttt tps'\"\nproof -\n  interpret loc: turing_machine_monomial c d j .\n  show ?thesis\n    using loc.tm5_eq_tm_monomial loc.tm5' loc.tps5_def assms by simp\nqed\n\n\nsubsection \\<open>Polynomials\\label{s:tm-arithmetic-poly}\\<close>\n\ntext \\<open>\nA polynomial is a sum of monomials. In this section we construct for every\npolynomial function $p$ a Turing machine that on input $x\\in\\nat$ outputs\n$p(x)$.\n\nAccording to our definition of polynomials (see Section~\\ref{s:tm-basic-bigoh}),\nwe can represent each polynomial by a list of coefficients. The value of such a\npolynomial with coefficient list @{term cs} on input $x$ is given by the next\nfunction. In the following definition, the coefficients of the polynomial are in\nreverse order, which simplifies the Turing machine later.\n\\<close>\n\ndefinition polyvalue :: \"nat list \\<Rightarrow> nat \\<Rightarrow> nat\" where\n  \"polyvalue cs x \\<equiv> (\\<Sum>i\\<leftarrow>[0..<length cs]. rev cs ! i * x ^ i)\"\n\nlemma polyvalue_Nil: \"polyvalue [] x = 0\"\n  using polyvalue_def by simp\n\nlemma sum_upt_snoc: \"(\\<Sum>i\\<leftarrow>[0..<length (zs @ [z])]. (zs @ [z]) ! i * x ^ i) =\n    (\\<Sum>i\\<leftarrow>[0..<length zs]. zs ! i * x ^ i) + z * x ^ (length zs)\"\n  by (smt (z3) add.right_neutral atLeastLessThan_iff length_append_singleton list.map(1) list.map(2)\n    map_append map_eq_conv nth_append nth_append_length set_upt sum_list_append sum_list_simps(1)\n    sum_list_simps(2) upt.simps(2) zero_order(1))\n\nlemma polyvalue_Cons: \"polyvalue (c # cs) x = c * x ^ (length cs) + polyvalue cs x\"\nproof -\n  have \"polyvalue (c # cs) x = (\\<Sum>i\\<leftarrow>[0..<Suc (length cs)]. (rev cs @ [c]) ! i * x ^ i)\"\n    using polyvalue_def by simp\n  also have \"... = (\\<Sum>i\\<leftarrow>[0..<length (rev cs @ [c])]. (rev cs @ [c]) ! i * x ^ i)\"\n    by simp\n  also have \"... = (\\<Sum>i\\<leftarrow>[0..<length (rev cs)]. (rev cs) ! i * x ^ i) + c * x ^ (length (rev cs))\"\n    using sum_upt_snoc by blast\n  also have \"... = (\\<Sum>i\\<leftarrow>[0..<length cs]. (rev cs) ! i * x ^ i) + c * x ^ (length cs)\"\n    by simp\n  finally show ?thesis\n    using polyvalue_def by simp\nqed\n\nlemma polyvalue_Cons_ge: \"polyvalue (c # cs) x \\<ge> polyvalue cs x\"\n  using polyvalue_Cons by simp\n\nlemma polyvalue_Cons_ge2: \"polyvalue (c # cs) x \\<ge> c * x ^ (length cs)\"\n  using polyvalue_Cons by simp\n\nlemma sum_list_const: \"(\\<Sum>_\\<leftarrow>ns. c) = c * length ns\"\n  using sum_list_triv[of c ns] by simp\n\nlemma polyvalue_le: \"polyvalue cs x \\<le> Max (set cs) * length cs * Suc x ^ length cs\"\nproof -\n  define cmax where \"cmax = Max (set (rev cs))\"\n  have \"polyvalue cs x = (\\<Sum>i\\<leftarrow>[0..<length cs]. rev cs ! i * x ^ i)\"\n    using polyvalue_def by simp\n  also have \"... \\<le> (\\<Sum>i\\<leftarrow>[0..<length cs]. cmax * x ^ i)\"\n  proof -\n    have \"rev cs ! i \\<le> cmax\" if \"i < length cs\" for i\n      using that cmax_def by (metis List.finite_set Max_ge length_rev nth_mem)\n    then show ?thesis\n      by (metis (no_types, lifting) atLeastLessThan_iff mult_le_mono1 set_upt sum_list_mono)\n  qed\n  also have \"... = cmax * (\\<Sum>i\\<leftarrow>[0..<length cs]. x ^ i)\"\n    using sum_list_const_mult by blast\n  also have \"... \\<le> cmax * (\\<Sum>i\\<leftarrow>[0..<length cs]. Suc x ^ i)\"\n    by (simp add: power_mono sum_list_mono)\n  also have \"... \\<le> cmax * (\\<Sum>i\\<leftarrow>[0..<length cs]. Suc x ^ length cs)\"\n  proof -\n    have \"Suc x ^ i \\<le> Suc x ^ length cs\" if \"i < length cs\" for i\n      using that by (simp add: dual_order.strict_implies_order pow_mono)\n    then show ?thesis\n      by (metis atLeastLessThan_iff mult_le_mono2 set_upt sum_list_mono)\n  qed\n  also have \"... = cmax * length cs * Suc x ^ length cs\"\n    using sum_list_const[of _ \"[0..<length cs]\"] by simp\n  finally have \"polyvalue cs x \\<le> cmax * length cs * Suc x ^ length cs\" .\n  moreover have \"cmax = Max (set cs)\"\n    using cmax_def by simp\n  ultimately show ?thesis\n    by simp\nqed\n\nlemma nlength_polyvalue:\n \"nlength (polyvalue cs x) \\<le> nlength (Max (set cs)) + nlength (length cs) + Suc (length cs * nlength (Suc x))\"\nproof -\n  have \"nlength (polyvalue cs x) \\<le> nlength (Max (set cs) * length cs * Suc x ^ length cs)\"\n    using polyvalue_le nlength_mono by simp\n  also have \"... \\<le> nlength (Max (set cs) * length cs) + nlength (Suc x ^ length cs)\"\n    using nlength_prod by simp\n  also have \"... \\<le> nlength (Max (set cs)) + nlength(length cs) + Suc (length cs * nlength (Suc x))\"\n    by (meson add_mono nlength_pow nlength_prod)\n  finally show ?thesis .\nqed\n\ntext \\<open>\nThe following Turing machines compute polynomials given as lists of\ncoefficients.  If the polynomial is given by coefficients @{term cs}, the TM\n@{term \"tm_polycoef cs j\"} expect a number $n$ on tape $j$ and writes $p(n)$ to\ntape $j + 4$. The tapes $j+1$, $j+2$, and $j + 3$ are auxiliary tapes for use by\n@{const tm_monomial}.\n\\<close>\n\nfun tm_polycoef :: \"nat list \\<Rightarrow> tapeidx \\<Rightarrow> machine\" where\n  \"tm_polycoef [] j = []\" |\n  \"tm_polycoef (c # cs) j =\n     tm_polycoef cs j ;;\n     (tm_monomial c (length cs) j ;;\n      tm_add (j + 3) (j + 4) ;;\n      tm_setn (j + 3) 0)\"\n\nlemma tm_polycoef_tm:\n  assumes \"k \\<ge> 2\" and \"G \\<ge> 4\" and \"j + 4 < k\" and \"0 < j\"\n  shows \"turing_machine k G (tm_polycoef cs j)\"\nproof (induction cs)\n  case Nil\n  then show ?case\n    by (simp add: assms(1) assms(2) turing_machine_def)\nnext\n  case (Cons c cs)\n  moreover have\n    \"turing_machine k G (tm_monomial c (length cs) j ;; tm_add (j + 3) (j + 4) ;; tm_setn (j + 3) 0)\"\n    using tm_monomial_tm tm_add_tm tm_setn_tm assms\n    by simp\n  ultimately show ?case\n    by simp\nqed\n\nlocale turing_machine_polycoef =\n  fixes j :: tapeidx\nbegin\n\ndefinition \"tm1 c cs \\<equiv> tm_monomial c (length cs) j\"\ndefinition \"tm2 c cs \\<equiv> tm1 c cs ;; tm_add (j + 3) (j + 4)\"\ndefinition \"tm3 c cs \\<equiv> tm2 c cs ;; tm_setn (j + 3) 0\"\n\nfun tm4 :: \"nat list \\<Rightarrow> machine\" where\n  \"tm4 [] = []\" |\n  \"tm4 (c # cs) = tm4 cs ;; tm3 c cs\"\n\nlemma tm4_eq_tm_polycoef: \"tm4 zs = tm_polycoef zs j\"\nproof (induction zs)\n  case Nil\n  then show ?case\n    by simp\nnext\n  case (Cons z zs)\n  then show ?case\n    by (simp add: tm1_def tm2_def tm3_def)\nqed\n\ncontext\n  fixes x y k :: nat and tps0 :: \"tape list\"\n  fixes c :: nat and cs :: \"nat list\"\n  assumes jk: \"0 < j\" \"j + 4 < k\" \"k = length tps0\"\n  assumes tps0:\n    \"tps0 ! j = (\\<lfloor>x\\<rfloor>\\<^sub>N, 1)\"\n    \"tps0 ! (j + 1) = (\\<lfloor>0\\<rfloor>\\<^sub>N, 1)\"\n    \"tps0 ! (j + 2) = (\\<lfloor>0\\<rfloor>\\<^sub>N, 1)\"\n    \"tps0 ! (j + 3) = (\\<lfloor>0\\<rfloor>\\<^sub>N, 1)\"\n    \"tps0 ! (j + 4) = (\\<lfloor>y\\<rfloor>\\<^sub>N, 1)\"\nbegin\n\nabbreviation \"d \\<equiv> length cs\"\n\ndefinition \"tps1 \\<equiv> tps0\n  [j + 3 := (\\<lfloor>c * x ^ (length cs)\\<rfloor>\\<^sub>N, 1)]\"\n\nlemma tm1 [transforms_intros]:\n  assumes \"ttt = 46 + 71 * d + 99 * d ^ 3 * (nlength x)\\<^sup>2 +\n      32 * (nlength c + nlength (x ^ d))\\<^sup>2\"\n  shows \"transforms (tm1 c cs) tps0 ttt tps1\"\n  unfolding tm1_def by (tform tps: assms jk tps0 tps1_def)\n\ndefinition \"tps2 = tps0\n  [j + 3 := (\\<lfloor>c * x ^ (length cs)\\<rfloor>\\<^sub>N, 1),\n   j + 4 := (\\<lfloor>c * x ^ (length cs) + y\\<rfloor>\\<^sub>N, 1)]\"\n\nlemma tm2 [transforms_intros]:\n  assumes \"ttt = 46 + 71 * d + 99 * d ^ 3 * (nlength x)\\<^sup>2 +\n    32 * (nlength c + nlength (x ^ d))\\<^sup>2 +\n    (3 * max (nlength (c * x ^ d)) (nlength y) + 10)\"\n  shows \"transforms (tm2 c cs) tps0 ttt tps2\"\n  unfolding tm2_def by (tform tps: tps1_def tps2_def jk tps0 time: assms)\n\ndefinition \"tps3 \\<equiv> tps0\n  [j + 4 := (\\<lfloor>c * x ^ d + y\\<rfloor>\\<^sub>N, 1)]\"\n\nlemma tm3:\n  assumes \"ttt = 66 + 71 * d + 99 * d ^ 3 * (nlength x)\\<^sup>2 +\n      32 * (nlength c + nlength (x ^ d))\\<^sup>2 +\n      3 * max (nlength (c * x ^ d)) (nlength y) +\n      2 * nlength (c * x ^ d)\"\n  shows \"transforms (tm3 c cs) tps0 ttt tps3\"\n  unfolding tm3_def\nproof (tform tps: tps2_def tps3_def jk tps0 time: assms)\n  show \"tps3 = tps2[j + 3 := (\\<lfloor>0\\<rfloor>\\<^sub>N, 1)]\"\n    using tps3_def tps2_def jk tps0\n    by (smt (z3) One_nat_def add_2_eq_Suc add_left_cancel lessI less_numeral_extra(4) list_update_id\n      list_update_overwrite list_update_swap numeral_3_eq_3 numeral_Bit0 plus_1_eq_Suc)\nqed\n\ndefinition \"tps3' \\<equiv> tps0\n  [j + 4 := (\\<lfloor>c * x ^ length cs + y\\<rfloor>\\<^sub>N, 1)]\"\n\nlemma tm3':\n  assumes \"ttt = 66 + 71 * d + 99 * d ^ 3 * (nlength x)\\<^sup>2 +\n      32 * (nlength c + nlength (x ^ d))\\<^sup>2 +\n      5 * max (nlength (c * x ^ d)) (nlength y)\"\n  shows \"transforms (tm3 c cs) tps0 ttt tps3'\"\nproof -\n  have \"66 + 71 * d + 99 * d ^ 3 * (nlength x)\\<^sup>2 +\n      32 * (nlength c + nlength (x ^ d))\\<^sup>2 +\n      3 * max (nlength (c * x ^ d)) (nlength y) +\n      2 * nlength (c * x ^ d) \\<le>\n      66 + 71 * d + 99 * d ^ 3 * (nlength x)\\<^sup>2 +\n      32 * (nlength c + nlength (x ^ d))\\<^sup>2 +\n      3 * max (nlength (c * x ^ d)) (nlength y) +\n      2 * max (nlength (c * x ^ d)) (nlength y)\"\n    by simp\n  also have \"... = 66 + 71 * d + 99 * d ^ 3 * (nlength x)\\<^sup>2 +\n      32 * (nlength c + nlength (x ^ d))\\<^sup>2 +\n      5 * max (nlength (c * x ^ d)) (nlength y)\"\n    by simp\n  finally have \"66 + 71 * d + 99 * d ^ 3 * (nlength x)\\<^sup>2 +\n      32 * (nlength c + nlength (x ^ d))\\<^sup>2 +\n      3 * max (nlength (c * x ^ d)) (nlength y) +\n      2 * nlength (c * x ^ d) \\<le> ttt\"\n    using assms(1) by simp\n  moreover have \"tps3' = tps3\"\n    using tps3'_def tps3_def by simp\n  ultimately show ?thesis\n    using tm3 transforms_monotone by simp\nqed\n\nend  (* context x y k c cs tps0 *)\n\nlemma tm3'' [transforms_intros]:\n  fixes c :: nat and cs :: \"nat list\"\n  fixes x k :: nat and tps0 tps' :: \"tape list\"\n  assumes \"k = length tps0\" and \"j + 4 < k\" and \"0 < j\"\n  assumes\n    \"tps0 ! j = (\\<lfloor>x\\<rfloor>\\<^sub>N, 1)\"\n    \"tps0 ! (j + 1) = (\\<lfloor>0\\<rfloor>\\<^sub>N, 1)\"\n    \"tps0 ! (j + 2) = (\\<lfloor>0\\<rfloor>\\<^sub>N, 1)\"\n    \"tps0 ! (j + 3) = (\\<lfloor>0\\<rfloor>\\<^sub>N, 1)\"\n    \"tps0 ! (j + 4) = (\\<lfloor>polyvalue cs x\\<rfloor>\\<^sub>N, 1)\"\n  assumes \"ttt = 66 +\n      71 * (length cs) +\n      99 * (length cs) ^ 3 * (nlength x)\\<^sup>2 +\n      32 * (nlength c + nlength (x ^ (length cs)))\\<^sup>2 +\n      5 * max (nlength (c * x ^ (length cs))) (nlength (polyvalue cs x))\"\n  assumes \"tps' = tps0\n    [j + 4 := (\\<lfloor>polyvalue (c # cs) x\\<rfloor>\\<^sub>N, 1)]\"\n  shows \"transforms (tm3 c cs) tps0 ttt tps'\"\n  using assms tm3'[where ?y=\"polyvalue cs x\"] tps3'_def polyvalue_Cons by simp\n\nlemma pow_le_pow_Suc:\n  fixes a b :: nat\n  shows \"a ^ b \\<le> Suc a ^ Suc b\"\nproof -\n  have \"a ^ b \\<le> Suc a ^ b\"\n    by (simp add: power_mono)\n  then show ?thesis\n    by simp\nqed\n\nlemma tm4:\n  fixes x k :: nat and tps0 :: \"tape list\"\n  fixes cs :: \"nat list\"\n  assumes \"k = length tps0\" and \"j + 4 < k\" and \"0 < j\"\n  assumes\n    \"tps0 ! j = (\\<lfloor>x\\<rfloor>\\<^sub>N, 1)\"\n    \"tps0 ! (j + 1) = (\\<lfloor>0\\<rfloor>\\<^sub>N, 1)\"\n    \"tps0 ! (j + 2) = (\\<lfloor>0\\<rfloor>\\<^sub>N, 1)\"\n    \"tps0 ! (j + 3) = (\\<lfloor>0\\<rfloor>\\<^sub>N, 1)\"\n    \"tps0 ! (j + 4) = (\\<lfloor>0\\<rfloor>\\<^sub>N, 1)\"\n  assumes ttt: \"ttt = length cs *\n     (66 +\n      71 * (length cs) +\n      99 * (length cs) ^ 3 * (nlength x)\\<^sup>2 +\n      32 * (Max (set (map nlength cs)) + nlength (Suc x ^ length cs))\\<^sup>2 +\n      5 * nlength (polyvalue cs x))\"\n  shows \"transforms (tm4 cs) tps0 ttt (tps0[j + 4 := (\\<lfloor>polyvalue cs x\\<rfloor>\\<^sub>N, 1)])\"\n  using ttt\nproof (induction cs arbitrary: ttt)\n  case Nil\n  then show ?case\n    using polyvalue_Nil transforms_Nil assms by (metis list.size(3) list_update_id mult_is_0 tm4.simps(1))\nnext\n  case (Cons c cs)\n  note Cons.IH [transforms_intros]\n\n  have tm4def: \"tm4 (c # cs) = tm4 cs ;; tm3 c cs\"\n    by simp\n\n  let ?t1 = \"d cs *\n    (66 + 71 * d cs + 99 * d cs ^ 3 * (nlength x)\\<^sup>2 +\n     32 * (Max (nlength ` set cs) + nlength (Suc x ^ d cs))\\<^sup>2 +\n     5 * nlength (polyvalue cs x))\"\n  let ?t2 = \"66 + 71 * d cs + 99 * d cs ^ 3 * (nlength x)\\<^sup>2 +\n     32 * (nlength c + nlength (x ^ d cs))\\<^sup>2 +\n     5 * max (nlength (c * x ^ d cs)) (nlength (polyvalue cs x))\"\n  define t where \"t = ?t1 + ?t2\"\n  have tm4: \"transforms (tm4 (c # cs)) tps0 t (tps0[j + 4 := (\\<lfloor>polyvalue (c # cs) x\\<rfloor>\\<^sub>N, 1)])\"\n    unfolding tm4def by (tform tps: assms t_def)\n\n  have \"?t1 \\<le> d cs *\n    (66 + 71 * d (c#cs) + 99 * d cs ^ 3 * (nlength x)\\<^sup>2 +\n     32 * (Max (nlength ` set cs) + nlength (Suc x ^d cs))\\<^sup>2 +\n     5 * nlength (polyvalue cs x))\"\n    by simp\n  also have \"... \\<le> d cs *\n    (66 + 71 * d (c#cs) + 99 * d (c#cs) ^ 3 * (nlength x)\\<^sup>2 +\n     32 * (Max (nlength ` set cs) + nlength (Suc x ^d cs))\\<^sup>2 +\n     5 * nlength (polyvalue cs x))\"\n    by simp\n  also have \"... \\<le> d cs *\n    (66 + 71 * d (c#cs) + 99 * d (c#cs) ^ 3 * (nlength x)\\<^sup>2 +\n     32 * (Max (nlength ` set (c#cs)) + nlength (Suc x ^d cs))\\<^sup>2 +\n     5 * nlength (polyvalue cs x))\"\n    by simp\n  also have \"... \\<le> d cs *\n    (66 + 71 * d (c#cs) + 99 * d (c#cs) ^ 3 * (nlength x)\\<^sup>2 +\n     32 * (Max (nlength ` set (c#cs)) + nlength (Suc x ^d (c#cs)))\\<^sup>2 +\n     5 * nlength (polyvalue cs x))\"\n    using nlength_mono by simp\n  also have \"... \\<le> d cs *\n    (66 + 71 * d (c#cs) + 99 * d (c#cs) ^ 3 * (nlength x)\\<^sup>2 +\n     32 * (Max (nlength ` set (c#cs)) + nlength (Suc x ^d (c#cs)))\\<^sup>2 +\n     5 * nlength (polyvalue (c#cs) x))\"\n    using nlength_mono polyvalue_Cons_ge by simp\n  finally have t1: \"?t1 \\<le> d cs *\n    (66 + 71 * d (c#cs) + 99 * d (c#cs) ^ 3 * (nlength x)\\<^sup>2 +\n     32 * (Max (nlength ` set (c#cs)) + nlength (Suc x ^d (c#cs)))\\<^sup>2 +\n     5 * nlength (polyvalue (c#cs) x))\"\n    (is \"?t1 \\<le> d cs * ?t3\") .\n\n  have \"?t2 \\<le>\n    66 + 71 * d (c # cs) + 99 * d cs ^ 3 * (nlength x)\\<^sup>2 +\n      32 * (nlength c + nlength (x ^ d cs))\\<^sup>2 +\n      5 * max (nlength (c * x ^ d cs)) (nlength (polyvalue cs x))\"\n    by simp\n  also have \"... \\<le> 66 + 71 * d (c # cs) + 99 * d (c # cs) ^ 3 * (nlength x)\\<^sup>2 +\n      32 * (nlength c + nlength (x ^ d cs))\\<^sup>2 +\n      5 * max (nlength (c * x ^ d cs)) (nlength (polyvalue cs x))\"\n    by simp\n  also have \"... \\<le> 66 + 71 * d (c # cs) + 99 * d (c # cs) ^ 3 * (nlength x)\\<^sup>2 +\n      32 * (Max (set (map nlength (c # cs))) + nlength (x ^ d cs))\\<^sup>2 +\n      5 * max (nlength (c * x ^ d cs)) (nlength (polyvalue cs x))\"\n    by simp\n  also have \"... \\<le> 66 + 71 * d (c # cs) + 99 * d (c # cs) ^ 3 * (nlength x)\\<^sup>2 +\n      32 * (Max (set (map nlength (c # cs))) + nlength (Suc x ^ d (c#cs)))\\<^sup>2 +\n      5 * max (nlength (c * x ^ d cs)) (nlength (polyvalue cs x))\"\n    using nlength_mono pow_le_pow_Suc by simp\n  also have \"... \\<le> 66 + 71 * d (c # cs) + 99 * d (c # cs) ^ 3 * (nlength x)\\<^sup>2 +\n      32 * (Max (set (map nlength (c # cs))) + nlength (Suc x ^ d (c#cs)))\\<^sup>2 +\n      5 * max (nlength (c * x ^ d cs)) (nlength (polyvalue (c#cs) x))\"\n  proof -\n    have \"nlength (polyvalue cs x) \\<le> nlength (polyvalue (c#cs) x)\"\n      using polyvalue_Cons by (simp add: nlength_mono)\n    then show ?thesis\n      by simp\n  qed\n  also have \"... \\<le> 66 + 71 * d (c # cs) + 99 * d (c # cs) ^ 3 * (nlength x)\\<^sup>2 +\n      32 * (Max (set (map nlength (c # cs))) + nlength (Suc x ^ d (c#cs)))\\<^sup>2 +\n      5 * max (nlength (polyvalue (c#cs) x)) (nlength (polyvalue (c#cs) x))\"\n    using nlength_mono polyvalue_Cons_ge2 by simp\n  also have \"... \\<le> 66 + 71 * d (c # cs) + 99 * d (c # cs) ^ 3 * (nlength x)\\<^sup>2 +\n      32 * (Max (set (map nlength (c # cs))) + nlength (Suc x ^ d (c#cs)))\\<^sup>2 +\n      5 * nlength (polyvalue (c#cs) x)\"\n    by simp\n  finally have t2: \"?t2 \\<le> ?t3\"\n    by simp\n\n  have \"t \\<le> d cs * ?t3 + ?t3\"\n    using t1 t2 t_def add_le_mono by blast\n  then have \"t \\<le> d (c#cs) * ?t3\"\n    by simp\n  moreover have \"ttt = d (c#cs) * ?t3\"\n    using Cons by simp\n  ultimately have \"t \\<le> ttt\"\n    by simp\n  then show ?case\n    using tm4 transforms_monotone by simp\nqed\n\nend  (* locale turing_machine_polycoef *)\n\ntext \\<open>\nThe time bound in the previous lemma for @{const tm_polycoef} is a bit unwieldy.\nIt depends not only on the length of the input $x$ but also on the list of\ncoefficients of the polynomial $p$ and on the value $p(x)$.  Next we bound this\ntime bound by a simpler expression of the form $d + d\\cdot|x|^2$ where $d$\ndepends only on the polynomial. This is accomplished by the next three lemmas.\n\\<close>\n\nlemma tm_polycoef_time_1: \"\\<exists>d. \\<forall>x. nlength (polyvalue cs x) \\<le> d + d * nlength x\"\nproof -\n  { fix x\n    have \"nlength (polyvalue cs x) \\<le> nlength (Max (set cs)) + nlength (length cs) + Suc (length cs * nlength (Suc x))\"\n      using nlength_polyvalue by simp\n    also have \"... = nlength (Max (set cs)) + nlength (length cs) + 1 + length cs * nlength (Suc x)\"\n        (is \"_ = ?a + length cs * nlength (Suc x)\")\n      by simp\n    also have \"... \\<le> ?a + length cs * (Suc (nlength x))\"\n      using nlength_Suc by (meson add_mono_thms_linordered_semiring(2) mult_le_mono2)\n    also have \"... = ?a + length cs + length cs * nlength x\"\n        (is \"_ = ?b + length cs * nlength x\")\n      by simp\n    also have \"... \\<le> ?b + ?b * nlength x\"\n      by (meson add_left_mono le_add2 mult_le_mono1)\n    finally have \"nlength (polyvalue cs x) \\<le> ?b + ?b * nlength x\" .\n  }\n  then show ?thesis\n    by blast\nqed\n\nlemma tm_polycoef_time_2: \"\\<exists>d. \\<forall>x. (Max (set (map nlength cs)) + nlength (Suc x ^ length cs))\\<^sup>2 \\<le> d + d * nlength x ^ 2\"\nproof -\n  { fix x\n    have \"(Max (set (map nlength cs)) + nlength (Suc x ^ length cs))\\<^sup>2 \\<le>\n        (Max (set (map nlength cs)) + Suc (nlength (Suc x) * length cs))\\<^sup>2\"\n      using nlength_pow by (simp add: mult.commute)\n    also have \"... = (Suc (Max (set (map nlength cs))) + nlength (Suc x) * length cs)\\<^sup>2\"\n        (is \"_ = (?a + ?b)^2\")\n      by simp\n    also have \"... = ?a ^ 2 + 2 * ?a * ?b + ?b ^ 2\"\n      by algebra\n    also have \"... \\<le> ?a ^ 2 + 2 * ?a * ?b ^ 2 + ?b ^ 2\"\n      by (meson add_le_mono dual_order.eq_iff mult_le_mono2 power2_nat_le_imp_le)\n    also have \"... \\<le> ?a ^ 2 + (2 * ?a + 1) * ?b ^ 2\"\n      by simp\n    also have \"... = ?a ^ 2 + (2 * ?a + 1) * (length cs) ^ 2 * nlength (Suc x) ^ 2\"\n      by algebra\n    also have \"... \\<le> ?a ^ 2 + (2 * ?a + 1) * (length cs) ^ 2 * Suc (nlength x) ^ 2\"\n      using nlength_Suc by simp\n    also have \"... = ?a ^ 2 + (2 * ?a + 1) * (length cs) ^ 2 * (nlength x ^ 2 + 2 * nlength x + 1)\"\n      by (smt (z3) Suc_eq_plus1 add.assoc mult_2 nat_1_add_1 one_power2 plus_1_eq_Suc power2_sum)\n    also have \"... \\<le> ?a ^ 2 + (2 * ?a + 1) * (length cs) ^ 2 * (nlength x ^ 2 + 2 * nlength x ^ 2 + 1)\"\n    proof -\n      have \"nlength x ^ 2 + 2 * nlength x + 1 \\<le> nlength x ^ 2 + 2 * nlength x ^ 2 + 1\"\n        by (metis add_le_mono1 add_mono_thms_linordered_semiring(2) le_square mult.commute\n        mult_le_mono1 numerals(1) power_add_numeral power_one_right semiring_norm(2))\n      then show ?thesis\n        by simp\n    qed\n    also have \"... = ?a ^ 2 + (2 * ?a + 1) * (length cs) ^ 2 * (3 * nlength x ^ 2 + 1)\"\n      by simp\n    also have \"... = ?a ^ 2 + (2 * ?a + 1) * (length cs) ^ 2 + (2 * ?a + 1) * (length cs) ^ 2 * 3 * nlength x ^ 2\"\n        (is \"_ = _ + ?c * nlength x ^ 2\")\n      by simp\n    also have \"... \\<le> ?a ^ 2 + ?c + ?c * nlength x ^ 2\"\n        (is \"_ \\<le> ?d + ?c * nlength x ^ 2\")\n      by simp\n    also have \"... \\<le> ?d + ?d * nlength x ^ 2\"\n      by simp\n    finally have \"(Max (set (map nlength cs)) + nlength (Suc x ^ length cs))\\<^sup>2 \\<le> ?d + ?d * nlength x ^ 2\" .\n  }\n  then show ?thesis\n    by auto\nqed\n\nlemma tm_polycoef_time_3:\n  \"\\<exists>d. \\<forall>x. length cs *\n    (66 +\n     71 * length cs +\n     99 * length cs ^ 3 * (nlength x)\\<^sup>2 +\n     32 * (Max (set (map nlength cs)) + nlength (Suc x ^ length cs))\\<^sup>2 +\n     5 * nlength (polyvalue cs x)) \\<le> d + d * nlength x ^ 2\"\nproof -\n  obtain d1 where d1: \"\\<forall>x. nlength (polyvalue cs x) \\<le> d1 + d1 * nlength x\"\n    using tm_polycoef_time_1 by auto\n  obtain d2 where d2: \"\\<forall>x. (Max (set (map nlength cs)) + nlength (Suc x ^ length cs))\\<^sup>2 \\<le> d2 + d2 * nlength x ^ 2\"\n    using tm_polycoef_time_2 by auto\n  { fix x\n    let ?lhs = \" length cs *\n      (66 +\n      71 * length cs +\n      99 * length cs ^ 3 * (nlength x)\\<^sup>2 +\n      32 * (Max (set (map nlength cs)) + nlength (Suc x ^ length cs))\\<^sup>2 +\n      5 * nlength (polyvalue cs x))\"\n    let ?n = \"nlength x\"\n    have \"?lhs \\<le> length cs *\n        (66 + 71 * length cs + 99 * length cs ^ 3 * ?n ^ 2 +\n        32 * (d2 + d2 * ?n ^ 2) + 5 * (d1 + d1 * ?n))\"\n      using d1 d2 add_le_mono mult_le_mono2 nat_add_left_cancel_le by presburger\n    also have \"... \\<le> length cs *\n        (66 + 71 * length cs + 99 * length cs ^ 3 * ?n ^ 2 +\n        32 * (d2 + d2 * ?n ^ 2) + 5 * (d1 + d1 * ?n ^ 2))\"\n      by (simp add: le_square power2_eq_square)\n    also have \"... = length cs *\n        (66 + 71 * length cs + 99 * length cs ^ 3 * ?n ^ 2 +\n        32 * d2 + 32 * d2 * ?n ^ 2 + 5 * d1 + 5 * d1 * ?n ^ 2)\"\n      by simp\n    also have \"... = length cs *\n        (66 + 71 * length cs + 32 * d2 + 5 * d1 +\n        (99 * length cs ^ 3 + 32 * d2 + 5 * d1) * ?n ^ 2)\"\n      by algebra\n    also have \"... = length cs * (66 + 71 * length cs + 32 * d2 + 5 * d1) +\n        length cs * (99 * length cs ^ 3 + 32 * d2 + 5 * d1) * ?n ^ 2\"\n          (is \"_ = ?a + ?b * ?n ^ 2\")\n      by algebra\n    also have \"... \\<le> max ?a ?b + max ?a ?b * ?n ^ 2\"\n      by (simp add: add_mono_thms_linordered_semiring(1))\n    finally have \"?lhs \\<le> max ?a ?b + max ?a ?b * ?n ^ 2\" .\n  }\n  then show ?thesis\n    by auto\nqed\n\ntext \\<open>\nAccording to our definition of @{const polynomial} (see\nSection~\\ref{s:tm-basic-bigoh}) every polynomial has a list of coefficients.\nTherefore the next definition is well-defined for polynomials $p$.\n\\<close>\n\ndefinition coefficients :: \"(nat \\<Rightarrow> nat) \\<Rightarrow> nat list\" where\n  \"coefficients p \\<equiv> SOME cs. \\<forall>n. p n = (\\<Sum>i\\<leftarrow>[0..<length cs]. cs ! i * n ^ i)\"\n\ntext \\<open>\nThe $d$ in our upper bound of the form $d + d\\cdot|x|^2$ for the running time of\n@{const tm_polycoef} depends on the polynomial. It is given by the next\nfunction:\n\\<close>\n\ndefinition d_polynomial :: \"(nat \\<Rightarrow> nat) \\<Rightarrow> nat\" where\n  \"d_polynomial p \\<equiv>\n   (let cs = rev (coefficients p)\n    in SOME d. \\<forall>x. length cs *\n    (66 +\n     71 * length cs +\n     99 * length cs ^ 3 * (nlength x)\\<^sup>2 +\n     32 * (Max (set (map nlength cs)) + nlength (Suc x ^ length cs))\\<^sup>2 +\n     5 * nlength (polyvalue cs x)) \\<le> d + d * nlength x ^ 2)\"\n\ntext \\<open>\nThe Turing machine @{const tm_polycoef} has the coefficients of a polynomial\nas parameter. Next we devise a similar Turing machine that has the polynomial,\nas a function $\\nat \\to \\nat$, as parameter.\n\\<close>\n\ndefinition tm_polynomial :: \"(nat \\<Rightarrow> nat) \\<Rightarrow> tapeidx \\<Rightarrow> machine\" where\n  \"tm_polynomial p j \\<equiv> tm_polycoef (rev (coefficients p)) j\"\n\nlemma tm_polynomial_tm:\n  assumes \"k \\<ge> 2\" and \"G \\<ge> 4\" and \"0 < j\" and \"j + 4 < k\"\n  shows \"turing_machine k G (tm_polynomial p j)\"\n  using assms tm_polynomial_def tm_polycoef_tm by simp\n\nlemma transforms_tm_polynomialI [transforms_intros]:\n  fixes p :: \"nat \\<Rightarrow> nat\" and j :: tapeidx\n  fixes k x :: nat and tps tps' :: \"tape list\"\n  assumes \"0 < j\" and \"k = length tps\" and \"j + 4 < k\"\n    and \"polynomial p\"\n  assumes\n    \"tps ! j = (\\<lfloor>x\\<rfloor>\\<^sub>N, 1)\"\n    \"tps ! (j + 1) = (\\<lfloor>0\\<rfloor>\\<^sub>N, 1)\"\n    \"tps ! (j + 2) = (\\<lfloor>0\\<rfloor>\\<^sub>N, 1)\"\n    \"tps ! (j + 3) = (\\<lfloor>0\\<rfloor>\\<^sub>N, 1)\"\n    \"tps ! (j + 4) = (\\<lfloor>0\\<rfloor>\\<^sub>N, 1)\"\n  assumes \"ttt = d_polynomial p + d_polynomial p * nlength x ^ 2\"\n  assumes \"tps' = tps\n    [j + 4 := (\\<lfloor>p x\\<rfloor>\\<^sub>N, 1)]\"\n  shows \"transforms (tm_polynomial p j) tps ttt tps'\"\nproof -\n  let ?P = \"\\<lambda>x. \\<forall>n. p n = (\\<Sum>i\\<leftarrow>[0..<length x]. x ! i * n ^ i)\"\n  define cs where \"cs = (SOME x. ?P x)\"\n  moreover have ex: \"\\<exists>cs. ?P cs\"\n    using assms(4) polynomial_def by simp\n  ultimately have \"?P cs\"\n    using someI_ex[of ?P] by blast\n  then have 1: \"polyvalue (rev cs) x = p x\"\n    using polyvalue_def by simp\n\n  let ?cs = \"rev cs\"\n  have \"d_polynomial p = (SOME d. \\<forall>x. length ?cs *\n    (66 +\n     71 * length ?cs +\n     99 * length ?cs ^ 3 * (nlength x)\\<^sup>2 +\n     32 * (Max (set (map nlength ?cs)) + nlength (Suc x ^ length ?cs))\\<^sup>2 +\n     5 * nlength (polyvalue ?cs x)) \\<le> d + d * nlength x ^ 2)\"\n    using cs_def coefficients_def d_polynomial_def by simp\n  then have *: \"\\<forall>x. length ?cs *\n    (66 +\n     71 * length ?cs +\n     99 * length ?cs ^ 3 * (nlength x)\\<^sup>2 +\n     32 * (Max (set (map nlength ?cs)) + nlength (Suc x ^ length ?cs))\\<^sup>2 +\n     5 * nlength (polyvalue ?cs x)) \\<le> (d_polynomial p) + (d_polynomial p) * nlength x ^ 2\"\n    using tm_polycoef_time_3 someI_ex[OF tm_polycoef_time_3] by presburger\n\n  let ?ttt = \"length ?cs *\n    (66 +\n     71 * length ?cs +\n     99 * length ?cs ^ 3 * (nlength x)\\<^sup>2 +\n     32 * (Max (set (map nlength ?cs)) + nlength (Suc x ^ length ?cs))\\<^sup>2 +\n     5 * nlength (polyvalue ?cs x))\"\n\n  interpret loc: turing_machine_polycoef j .\n\n  have \"transforms (loc.tm4 ?cs) tps ?ttt (tps[j + 4 := (\\<lfloor>polyvalue ?cs x\\<rfloor>\\<^sub>N, 1)])\"\n    using loc.tm4 assms * by blast\n  then have \"transforms (loc.tm4 ?cs) tps ?ttt (tps[j + 4 := (\\<lfloor>p x\\<rfloor>\\<^sub>N, 1)])\"\n    using 1 by simp\n  then have \"transforms (loc.tm4 ?cs) tps ?ttt tps'\"\n    using assms(11) by simp\n  moreover have \"loc.tm4 ?cs = tm_polynomial p j\"\n    using tm_polynomial_def loc.tm4_eq_tm_polycoef coefficients_def cs_def by simp\n  ultimately have \"transforms (tm_polynomial p j) tps ?ttt tps'\"\n    by simp\n  then show \"transforms (tm_polynomial p j) tps ttt tps'\"\n    using * assms(10) transforms_monotone by simp\nqed\n\n\nsubsection \\<open>Division by two\\<close>\n\ntext \\<open>\nIn order to divide a number by two, a Turing machine can shift all symbols on\nthe tape containing the number to the left, of course without overwriting\nthe start symbol.\n\nThe next command implements the left shift. It scans the tape $j$ from right to\nleft and memorizes the current symbol on the last tape. It works very similar to\n@{const cmd_double} only in the opposite direction. Upon reaching the start\nsymbol, it moves the head one cell to the right.\n\\<close>\n\ndefinition cmd_halve :: \"tapeidx \\<Rightarrow> command\" where\n  \"cmd_halve j rs \\<equiv>\n    (if rs ! j = 1 then 1 else 0,\n     (map (\\<lambda>i.\n       if i = j then\n         if rs ! j = \\<triangleright> then (rs ! i, Right)\n         else if last rs = \\<triangleright> then (\\<box>, Left)\n         else (tosym (todigit (last rs)), Left)\n       else if i = length rs - 1 then (tosym (todigit (rs ! j)), Stay)\n       else (rs ! i, Stay)) [0..<length rs]))\"\n\nlemma turing_command_halve:\n  assumes \"G \\<ge> 4\" and \"0 < j\" and \"j < k\"\n  shows \"turing_command (Suc k) 1 G (cmd_halve j)\"\nproof\n  show \"\\<And>gs. length gs = Suc k \\<Longrightarrow> length ([!!] cmd_halve j gs) = length gs\"\n    using cmd_halve_def by simp\n  moreover have \"0 \\<noteq> Suc k - 1\"\n    using assms by simp\n  ultimately show \"\\<And>gs. length gs = Suc k \\<Longrightarrow> 0 < Suc k \\<Longrightarrow> cmd_halve j gs [.] 0 = gs ! 0\"\n    using assms cmd_halve_def by (smt (verit) One_nat_def ab_semigroup_add_class.add_ac(1) diff_Suc_1\n      length_map neq0_conv nth_map nth_upt plus_1_eq_Suc prod.sel(1) prod.sel(2))\n  show \"cmd_halve j gs [.] j' < G\"\n    if \"length gs = Suc k\" \"(\\<And>i. i < length gs \\<Longrightarrow> gs ! i < G)\" \"j' < length gs\"\n    for gs j'\n  proof -\n    have \"cmd_halve j gs [!] j' =\n      (if j' = j then\n         if gs ! j = \\<triangleright> then (gs ! j', Right)\n         else if last gs = \\<triangleright> then (\\<box>, Left)\n         else (tosym (todigit (last gs)), Left)\n       else if j' = length gs - 1 then (tosym (todigit (gs ! j)), Stay)\n       else (gs ! j', Stay))\"\n      using cmd_halve_def that(3) by simp\n    moreover consider \"j' = j\" | \"j' = k\" | \"j' \\<noteq> j \\<and> j' \\<noteq> k\"\n      by auto\n    ultimately show ?thesis\n      using that assms by (cases) simp_all\n  qed\n  show \"\\<And>gs. length gs = Suc k \\<Longrightarrow> [*] (cmd_halve j gs) \\<le> 1\"\n    using cmd_halve_def by simp\nqed\n\nlemma sem_cmd_halve_2:\n  assumes \"j < k\"\n    and \"bit_symbols xs\"\n    and \"length tps = Suc k\"\n    and \"i \\<le> length xs\"\n    and \"i > 0\"\n    and \"z = \\<zero> \\<or> z = \\<one>\"\n    and \"tps ! j = (\\<lfloor>xs\\<rfloor>, i)\"\n    and \"tps ! k = \\<lceil>z\\<rceil>\"\n    and \"tps' = tps[j := tps ! j |:=| z |-| 1, k := \\<lceil>xs ! (i - 1)\\<rceil>]\"\n  shows \"sem (cmd_halve j) (0, tps) = (0, tps')\"\nproof (rule semI)\n  show \"proper_command (Suc k) (cmd_halve j)\"\n    using cmd_halve_def by simp\n  show \"length tps = Suc k\" \"length tps' = Suc k\"\n    using assms(3,9) by simp_all\n  define rs where \"rs = read tps\"\n  then have lenrs: \"length rs = Suc k\"\n    using assms(3) read_length by simp\n  have rsj: \"rs ! j = xs ! (i - 1)\"\n    using rs_def assms tapes_at_read' contents_inbounds\n    by (metis fst_conv le_imp_less_Suc less_imp_le_nat snd_conv)\n  then have rsj': \"rs ! j > 1\"\n    using assms Suc_1 Suc_diff_1 Suc_le_lessD by (metis eval_nat_numeral(3) less_Suc_eq)\n  then show \"fst (cmd_halve j (read tps)) = 0\"\n    using cmd_halve_def rs_def by simp\n  have lastrs: \"last rs = z\"\n    using assms rs_def onesie_read tapes_at_read'\n    by (metis diff_Suc_1 last_conv_nth length_0_conv lenrs lessI nat.simps(3))\n  show \"act (cmd_halve j (read tps) [!] j') (tps ! j') = tps' ! j'\" if \"j' < Suc k\" for j'\n  proof -\n    have \"j' < length rs\"\n      using that lenrs by simp\n    then have *: \"cmd_halve j rs [!] j' =\n      (if j' = j then\n         if rs ! j = \\<triangleright> then (rs ! j', Right)\n         else if last rs = \\<triangleright> then (\\<box>, Left)\n         else (tosym (todigit (last rs)), Left)\n       else if j' = length rs - 1 then (tosym (todigit (rs ! j)), Stay)\n       else (rs ! j', Stay))\"\n      using cmd_halve_def by simp\n    consider \"j' = j\" | \"j' = k\" | \"j' \\<noteq> j \\<and> j' \\<noteq> k\"\n      by auto\n    then show ?thesis\n    proof (cases)\n      case 1\n      then have \"cmd_halve j (read tps) [!] j' = (tosym (todigit (last rs)), Left)\"\n        using rs_def rsj' lastrs * assms(6) by auto\n      then have \"cmd_halve j (read tps) [!] j' = (z, Left)\"\n        using lastrs assms(6) by auto\n      moreover have \"tps' ! j' = tps ! j |:=| z |-| 1\"\n        using 1 assms(1,3,9) by simp\n      ultimately show ?thesis\n        using act_Left' 1 that rs_def by metis\n    next\n      case 2\n      then have \"cmd_halve j (read tps) [!] j' = (tosym (todigit (rs ! j)), Stay)\"\n        using rs_def * lenrs assms(1) by simp\n      moreover have \"tps' ! j' = \\<lceil>xs ! (i - 1)\\<rceil>\"\n        using assms 2 by simp\n      moreover have \"tps ! j' = \\<lceil>z\\<rceil>\"\n        using assms 2 by simp\n      moreover have \"tosym (todigit (rs ! j)) = xs ! (i - 1)\"\n      proof -\n        have \"xs ! (i - 1) = \\<zero> \\<or> xs ! (i - 1) = \\<one>\"\n          using rsj rs_def assms by simp\n        then show ?thesis\n          using One_nat_def add_2_eq_Suc' numeral_3_eq_3 rsj by presburger\n      qed\n      ultimately show ?thesis\n        using act_onesie by simp\n    next\n      case 3\n      then show ?thesis\n        using * act_Stay that assms lenrs rs_def by simp\n    qed\n  qed\nqed\n\nlemma sem_cmd_halve_1:\n  assumes \"j < k\"\n    and \"bit_symbols xs\"\n    and \"length tps = Suc k\"\n    and \"0 < length xs\"\n    and \"tps ! j = (\\<lfloor>xs\\<rfloor>, length xs)\"\n    and \"tps ! k = \\<lceil>\\<triangleright>\\<rceil>\"\n    and \"tps' = tps[j := tps ! j |:=| \\<box> |-| 1, k := \\<lceil>xs ! (length xs - 1)\\<rceil>]\"\n  shows \"sem (cmd_halve j) (0, tps) = (0, tps')\"\nproof (rule semI)\n  show \"proper_command (Suc k) (cmd_halve j)\"\n    using cmd_halve_def by simp\n  show \"length tps = Suc k\" \"length tps' = Suc k\"\n    using assms(3,7) by simp_all\n  define rs where \"rs = read tps\"\n  then have lenrs: \"length rs = Suc k\"\n    using assms(3) read_length by simp\n  have rsj: \"rs ! j = xs ! (length xs - 1)\"\n    using rs_def assms tapes_at_read' contents_inbounds\n    by (metis One_nat_def fst_conv le_eq_less_or_eq le_imp_less_Suc snd_conv)\n  then have rsj': \"rs ! j > 1\"\n    using assms(2,4) by (metis One_nat_def Suc_1 diff_less lessI less_add_Suc2 numeral_3_eq_3 plus_1_eq_Suc)\n  then show \"fst (cmd_halve j (read tps)) = \\<box>\"\n    using cmd_halve_def rs_def by simp\n  have lastrs: \"last rs = \\<triangleright>\"\n    using assms rs_def onesie_read tapes_at_read'\n    by (metis diff_Suc_1 last_conv_nth length_0_conv lenrs lessI nat.simps(3))\n  show \"act (cmd_halve j (read tps) [!] j') (tps ! j') = tps' ! j'\" if \"j' < Suc k\" for j'\n  proof -\n    have \"j' < length rs\"\n      using that lenrs by simp\n    then have *: \"cmd_halve j rs [!] j' =\n      (if j' = j then\n         if rs ! j = \\<triangleright> then (rs ! j', Right)\n         else if last rs = \\<triangleright> then (\\<box>, Left)\n         else (tosym (todigit (last rs)), Left)\n       else if j' = length rs - 1 then (tosym (todigit (rs ! j)), Stay)\n       else (rs ! j', Stay))\"\n      using cmd_halve_def by simp\n    consider \"j' = j\" | \"j' = k\" | \"j' \\<noteq> j \\<and> j' \\<noteq> k\"\n      by auto\n    then show ?thesis\n    proof (cases)\n      case 1\n      then have \"cmd_halve j (read tps) [!] j' = (\\<box>, Left)\"\n        using rs_def rsj' lastrs * by simp\n      then show ?thesis\n        using act_Left' 1 that rs_def assms(1,3,7) by simp\n    next\n      case 2\n      then have \"cmd_halve j (read tps) [!] j' = (tosym (todigit (rs ! j)), Stay)\"\n        using rs_def * lenrs assms(1) by simp\n      moreover have \"tps' ! j' = \\<lceil>xs ! (length xs - 1)\\<rceil>\"\n        using assms 2 by simp\n      moreover have \"tps ! j' = \\<lceil>\\<triangleright>\\<rceil>\"\n        using assms 2 by simp\n      ultimately show ?thesis\n        using act_onesie assms 2 that rs_def rsj\n        by (smt (z3) One_nat_def Suc_1 add_2_eq_Suc' diff_less numeral_3_eq_3 zero_less_one)\n    next\n      case 3\n      then show ?thesis\n        using * act_Stay that assms lenrs rs_def by simp\n    qed\n  qed\nqed\n\nlemma sem_cmd_halve_0:\n  assumes \"j < k\"\n    and \"length tps = Suc k\"\n    and \"tps ! j = (\\<lfloor>xs\\<rfloor>, 0)\"\n    and \"tps ! k = \\<lceil>z\\<rceil>\"\n    and \"tps' = tps[j := tps ! j |+| 1, k := \\<lceil>\\<zero>\\<rceil>]\"\n  shows \"sem (cmd_halve j) (0, tps) = (1, tps')\"\nproof (rule semI)\n  show \"proper_command (Suc k) (cmd_halve j)\"\n    using cmd_halve_def by simp\n  show \"length tps = Suc k\" \"length tps' = Suc k\"\n    using assms(2,5) by simp_all\n  show \"fst (cmd_halve j (read tps)) = 1\"\n    using cmd_halve_def assms contents_at_0 tapes_at_read'\n    by (smt (verit) fst_conv le_eq_less_or_eq not_less not_less_eq snd_conv)\n  show \"act (cmd_halve j (read tps) [!] j') (tps ! j') = tps' ! j'\" if \"j' < Suc k\" for j'\n  proof -\n    define gs where \"gs = read tps\"\n    then have \"length gs = Suc k\"\n      using assms by (simp add: read_length)\n    then have \"j' < length gs\"\n      using that by simp\n    then have *: \"cmd_halve j gs [!] j' =\n      (if j' = j then\n         if gs ! j = \\<triangleright> then (gs ! j', Right)\n         else if last gs = \\<triangleright> then (\\<box>, Left)\n         else (tosym (todigit (last gs)), Left)\n       else if j' = length gs - 1 then (tosym (todigit (gs ! j)), Stay)\n       else (gs ! j', Stay))\"\n      using cmd_halve_def by simp\n    have gsj: \"gs ! j = \\<triangleright>\"\n      using gs_def assms(1,2,3) by (metis contents_at_0 fstI less_Suc_eq sndI tapes_at_read')\n    consider \"j' = j\" | \"j' = k\" | \"j' \\<noteq> j \\<and> j' \\<noteq> k\"\n      by auto\n    then show ?thesis\n    proof (cases)\n      case 1\n      then have \"cmd_halve j (read tps) [!] j' = (gs ! j', Right)\"\n        using gs_def gsj * by simp\n      then show ?thesis\n        using act_Right assms 1 that gs_def by (metis length_list_update lessI nat_neq_iff nth_list_update)\n    next\n      case 2\n      then have \"cmd_halve j (read tps) [!] j' = (tosym (todigit (gs ! j)), Stay)\"\n        using gs_def * \\<open>length gs = Suc k\\<close> assms(1) by simp\n      moreover have \"tps' ! j' = \\<lceil>\\<zero>\\<rceil>\"\n        using assms 2 by simp\n      moreover have \"tps ! j' = \\<lceil>z\\<rceil>\"\n        using assms 2 by simp\n      ultimately show ?thesis\n        using act_onesie assms 2 that gs_def gsj\n        by (smt (verit, best) One_nat_def Suc_1 add_2_eq_Suc' less_Suc_eq_0_disj less_numeral_extra(3) nat.inject numeral_3_eq_3)\n    next\n      case 3\n      then show ?thesis\n        using * act_Stay that assms(2,5) \\<open>length gs = Suc k\\<close> gs_def by simp\n    qed\n  qed\nqed\n\ndefinition tm_halve :: \"tapeidx \\<Rightarrow> machine\" where\n  \"tm_halve j \\<equiv> [cmd_halve j]\"\n\nlemma tm_halve_tm:\n  assumes \"k \\<ge> 2\" and \"G \\<ge> 4\" and \"0 < j\" and \"j < k\"\n  shows \"turing_machine (Suc k) G (tm_halve j)\"\n  using tm_halve_def turing_command_halve assms by auto\n\nlemma exe_cmd_halve_0:\n  assumes \"j < k\"\n    and \"length tps = Suc k\"\n    and \"tps ! j = (\\<lfloor>xs\\<rfloor>, 0)\"\n    and \"tps ! k = \\<lceil>z\\<rceil>\"\n    and \"tps' = tps[j := tps ! j |+| 1, k := \\<lceil>\\<zero>\\<rceil>]\"\n  shows \"exe (tm_halve j) (0, tps) = (1, tps')\"\n  using assms sem_cmd_halve_0 tm_halve_def exe_lt_length by simp\n\nlemma execute_cmd_halve_0:\n  assumes \"j < k\"\n    and \"length tps = Suc k\"\n    and \"tps ! j = (\\<lfloor>[]\\<rfloor>, 0)\"\n    and \"tps ! k = \\<lceil>\\<triangleright>\\<rceil>\"\n    and \"tps' = tps[j := tps ! j |+| 1, k := \\<lceil>\\<zero>\\<rceil>]\"\n  shows \"execute (tm_halve j) (0, tps) 1 = (1, tps')\"\n  using tm_halve_def exe_lt_length sem_cmd_halve_0 assms by simp\n\ndefinition shift :: \"tape \\<Rightarrow> nat \\<Rightarrow> tape\" where\n  \"shift tp y \\<equiv> (\\<lambda>x. if x \\<le> y then (fst tp) x else (fst tp) (Suc x), y)\"\n\nlemma shift_update: \"y > 0 \\<Longrightarrow> shift tp y |:=| (fst tp) (Suc y) |-| 1 = shift tp (y - 1)\"\n  unfolding shift_def by fastforce\n\nlemma shift_contents_0:\n  assumes \"length xs > 0\"\n  shows \"shift (\\<lfloor>xs\\<rfloor>, length xs) 0 = (\\<lfloor>tl xs\\<rfloor>, 0)\"\nproof -\n  have \"shift (\\<lfloor>xs\\<rfloor>, length xs) 0 = (\\<lfloor>drop 1 xs\\<rfloor>, 0)\"\n    using shift_def contents_def by fastforce\n  then show ?thesis\n    by (simp add: drop_Suc)\nqed\n\nlemma proper_bit_symbols: \"bit_symbols ws \\<Longrightarrow> proper_symbols ws\"\n  by auto\n\nlemma bit_symbols_shift:\n  assumes \"t < length ws\" and \"bit_symbols ws\"\n  shows \"|.| (shift (\\<lfloor>ws\\<rfloor>, length ws) (length ws - t)) \\<noteq> 1\"\n  using assms shift_def contents_def nat_neq_iff proper_bit_symbols by simp\n\nlemma exe_cmd_halve_1:\n  assumes \"j < k\"\n    and \"length tps = Suc k\"\n    and \"bit_symbols xs\"\n    and \"length xs > 0\"\n    and \"tps ! j = (\\<lfloor>xs\\<rfloor>, length xs)\"\n    and \"tps ! k = \\<lceil>\\<triangleright>\\<rceil>\"\n    and \"tps' = tps[j := tps ! j |:=| \\<box> |-| 1, k := \\<lceil>xs ! (length xs - 1)\\<rceil>]\"\n  shows \"exe (tm_halve j) (0, tps) = (0, tps')\"\n  using tm_halve_def exe_lt_length sem_cmd_halve_1 assms by simp\n\nlemma shift_contents_eq_take_drop:\n  assumes \"length xs > 0\"\n    and \"ys = take i xs @ drop (Suc i) xs\"\n    and \"i > 0\"\n    and \"i < length xs\"\n  shows \"shift (\\<lfloor>xs\\<rfloor>, length xs) i = (\\<lfloor>ys\\<rfloor>, i)\"\nproof -\n  have \"shift (\\<lfloor>xs\\<rfloor>, length xs) i = (\\<lambda>x. if x \\<le> i then \\<lfloor>xs\\<rfloor> x else \\<lfloor>xs\\<rfloor> (Suc x), i)\"\n    using shift_def by auto\n  moreover have \"(\\<lambda>x. if x \\<le> i then \\<lfloor>xs\\<rfloor> x else \\<lfloor>xs\\<rfloor> (Suc x)) = \\<lfloor>take i xs @ drop (Suc i) xs\\<rfloor>\"\n    (is \"?l = ?r\")\n  proof\n    fix x\n    consider \"x = 0\" | \"0 < x \\<and> x \\<le> i\" | \"i < x \\<and> x \\<le> length xs - 1\" | \"length xs - 1 < x\"\n      by linarith\n    then show \"?l x = ?r x\"\n    proof (cases)\n      case 1\n      then show ?thesis\n        using assms contents_def by simp\n    next\n      case 2\n      then have \"?l x = \\<lfloor>xs\\<rfloor> x\"\n        by simp\n      then have lhs: \"?l x = xs ! (x - 1)\"\n        using assms 2 by simp\n      have \"?r x = (take i xs @ drop (Suc i) xs) ! (x - 1)\"\n        using assms 2 by auto\n      then have \"?r x = xs ! (x - 1)\"\n        using assms(4) 2\n        by (metis diff_less le_eq_less_or_eq length_take less_trans min_absorb2 nth_append nth_take zero_less_one)\n      then show ?thesis\n        using lhs by simp\n    next\n      case 3\n      then have \"?l x = \\<lfloor>xs\\<rfloor> (Suc x)\"\n        by simp\n      then have lhs: \"?l x = xs ! x\"\n        using 3 assms by auto\n      have \"?r x = (take i xs @ drop (Suc i) xs) ! (x - 1)\"\n        using assms 3 by auto\n      then have \"?r x = drop (Suc i) xs ! (x - 1 - i)\"\n        using assms(3,4) 3\n        by (smt (z3) Suc_diff_1 dual_order.strict_trans length_take less_Suc_eq min_absorb2 nat_less_le nth_append)\n      then have \"?r x = xs ! x\"\n        using assms 3 by simp\n      then show ?thesis\n        using lhs by simp\n    next\n      case 4\n      then show ?thesis\n        using contents_def by auto\n    qed\n  qed\n  ultimately show ?thesis\n    using assms(2) by simp\nqed\n\nlemma exe_cmd_halve_2:\n  assumes \"j < k\"\n    and \"bit_symbols xs\"\n    and \"length tps = Suc k\"\n    and \"i \\<le> length xs\"\n    and \"i > 0\"\n    and \"z = \\<zero> \\<or> z = \\<one>\"\n    and \"tps ! j = (\\<lfloor>xs\\<rfloor>, i)\"\n    and \"tps ! k = \\<lceil>z\\<rceil>\"\n    and \"tps' = tps[j := tps ! j |:=| z |-| 1, k := \\<lceil>xs ! (i - 1)\\<rceil>]\"\n  shows \"exe (tm_halve j) (0, tps) = (0, tps')\"\n  using tm_halve_def exe_lt_length sem_cmd_halve_2 assms by simp\n\nlemma shift_contents_length_minus_1:\n  assumes \"length xs > 0\"\n  shows \"shift (\\<lfloor>xs\\<rfloor>, length xs) (length xs - 1) = (\\<lfloor>xs\\<rfloor>, length xs) |:=| \\<box> |-| 1\"\n  using contents_def shift_def assms by fastforce\n\nlemma execute_tm_halve_1_less:\n  assumes \"j < k\"\n    and \"length tps = Suc k\"\n    and \"bit_symbols xs\"\n    and \"length xs > 0\"\n    and \"tps ! j = (\\<lfloor>xs\\<rfloor>, length xs)\"\n    and \"tps ! k = \\<lceil>\\<triangleright>\\<rceil>\"\n    and \"t \\<ge> 1\"\n    and \"t \\<le> length xs\"\n  shows \"execute (tm_halve j) (0, tps) t = (0, tps\n      [j := shift (tps ! j) (length xs - t),\n       k := \\<lceil>xs ! (length xs - t)\\<rceil>])\"\n  using assms(7,8)\nproof (induction t rule: nat_induct_at_least)\n  case base\n  have \"execute (tm_halve j) (0, tps) 1 = exe (tm_halve j) (0, tps)\"\n    by simp\n  also have \"... = (0, tps[j := tps ! j |:=| \\<box> |-| 1, k := \\<lceil>xs ! (length xs - 1)\\<rceil>])\"\n    using assms exe_cmd_halve_1 by simp\n  also have \"... = (0, tps[j := shift (tps ! j) (length xs - 1), k := \\<lceil>xs ! (length xs - 1)\\<rceil>])\"\n    using shift_contents_length_minus_1 assms(4,5) by simp\n  finally show ?case .\nnext\n  case (Suc t)\n  then have \"t < length xs\"\n    by simp\n  let ?ys = \"take (length xs - t) xs @ drop (Suc (length xs - t)) xs\"\n  have \"execute (tm_halve j) (0, tps) (Suc t) = exe (tm_halve j) (execute (tm_halve j) (0, tps) t)\"\n    by simp\n  also have \"... = exe (tm_halve j) (0, tps\n      [j := shift (tps ! j) (length xs - t),\n       k := \\<lceil>xs ! (length xs - t)\\<rceil>])\"\n    using Suc by simp\n  also have \"... = exe (tm_halve j) (0, tps\n      [j := shift (\\<lfloor>xs\\<rfloor>, length xs) (length xs - t),\n       k := \\<lceil>xs ! (length xs - t)\\<rceil>])\"\n    using assms(5) by simp\n  also have \"... = exe (tm_halve j) (0, tps\n      [j := (\\<lfloor>?ys\\<rfloor>, length xs - t),\n       k := \\<lceil>xs ! (length xs - t)\\<rceil>])\"\n      (is \"_ = exe _ (0, ?tps)\")\n    using shift_contents_eq_take_drop Suc assms by simp\n  also have \"... = (0, ?tps\n      [j := ?tps ! j |:=| (xs ! (length xs - t)) |-| 1,\n       k := \\<lceil>?ys ! (length xs - t - 1)\\<rceil>])\"\n  proof -\n    let ?i = \"length xs - t\"\n    let ?z = \"xs ! ?i\"\n    have 1: \"bit_symbols ?ys\"\n      using assms(3) by (intro bit_symbols_append) simp_all\n    have 2: \"length ?tps = Suc k\"\n      using assms(2) by simp\n    have 3: \"?i \\<le> length ?ys\"\n      using Suc assms by simp\n    have 4: \"?i > 0\"\n      using Suc assms by simp\n    have 5: \"?z = 2 \\<or> ?z = 3\"\n      using assms(3,4) Suc by simp\n    have 6: \"?tps ! j = (\\<lfloor>?ys\\<rfloor>, ?i)\"\n      using assms(1,2) by simp\n    have 7: \"?tps ! k = \\<lceil>?z\\<rceil>\"\n      using assms(2) by simp\n    then show ?thesis\n      using exe_cmd_halve_2[OF assms(1) 1 2 3 4 5 6 7] by simp\n  qed\n  also have \"... = (0, tps\n      [j := ?tps ! j |:=| (xs ! (length xs - t)) |-| 1,\n       k := \\<lceil>?ys ! (length xs - t - 1)\\<rceil>])\"\n    using assms by (smt (z3) list_update_overwrite list_update_swap)\n  also have \"... = (0, tps\n      [j := (\\<lfloor>?ys\\<rfloor>, length xs - t) |:=| (xs ! (length xs - t)) |-| 1,\n       k := \\<lceil>?ys ! (length xs - t - 1)\\<rceil>])\"\n    using assms(1,2) by simp\n  also have \"... = (0, tps\n      [j := shift (\\<lfloor>xs\\<rfloor>, length xs) (length xs - Suc t),\n       k := \\<lceil>xs ! (length xs - (Suc t))\\<rceil>])\"\n  proof -\n    have \"(\\<lfloor>?ys\\<rfloor>, length xs - t) |:=| xs ! (length xs - t) |-| 1 =\n        shift (\\<lfloor>xs\\<rfloor>, length xs) (length xs - t) |:=| (xs ! (length xs - t)) |-| 1\"\n      using shift_contents_eq_take_drop One_nat_def Suc Suc_le_lessD \\<open>t < length xs\\<close> assms(4) diff_less zero_less_diff\n      by presburger\n    also have \"... = shift (\\<lfloor>xs\\<rfloor>, length xs) (length xs - Suc t)\"\n      using shift_update[of \"length xs - t\" \"(\\<lfloor>xs\\<rfloor>, length xs)\"] assms Suc by simp\n    finally have \"(\\<lfloor>?ys\\<rfloor>, length xs - t) |:=| xs ! (length xs - t) |-| 1 =\n        shift (\\<lfloor>xs\\<rfloor>, length xs) (length xs - Suc t)\" .\n    moreover have \"?ys ! (length xs - t - 1) = xs ! (length xs - Suc t)\"\n      using Suc assms \\<open>t < length xs\\<close>\n      by (metis (no_types, lifting) diff_Suc_eq_diff_pred diff_Suc_less diff_commute diff_less\n        length_take min_less_iff_conj nth_append nth_take zero_less_diff zero_less_one)\n    ultimately show ?thesis\n      by simp\n  qed\n  also have \"... = (0, tps\n      [j := shift (tps ! j) (length xs - (Suc t)),\n       k := \\<lceil>xs ! (length xs - (Suc t))\\<rceil>])\"\n    using assms(5) by simp\n  finally show ?case .\nqed\n\nlemma execute_tm_halve_1:\n  assumes \"j < k\"\n    and \"length tps = Suc k\"\n    and \"bit_symbols xs\"\n    and \"length xs > 0\"\n    and \"tps ! j = (\\<lfloor>xs\\<rfloor>, length xs)\"\n    and \"tps ! k = \\<lceil>\\<triangleright>\\<rceil>\"\n    and \"tps' = tps[j := (\\<lfloor>tl xs\\<rfloor>, 1), k := \\<lceil>\\<zero>\\<rceil>]\"\n  shows \"execute (tm_halve j) (0, tps) (Suc (length xs)) = (1, tps')\"\nproof -\n  have \"execute (tm_halve j) (0, tps) (length xs) = (0, tps[j := shift (tps ! j) 0, k := \\<lceil>xs ! 0\\<rceil>])\"\n    using execute_tm_halve_1_less[OF assms(1-6), where ?t=\"length xs\"] assms(4) by simp\n  also have \"... = (0, tps[j := shift (\\<lfloor>xs\\<rfloor>, length xs) 0, k := \\<lceil>xs ! 0\\<rceil>])\"\n    using assms(5) by simp\n  also have \"... = (0, tps[j := (\\<lfloor>tl xs\\<rfloor>, 0), k := \\<lceil>xs ! 0\\<rceil>])\"\n    using shift_contents_0 assms(4) by simp\n  finally have \"execute (tm_halve j) (0, tps) (length xs) = (0, tps[j := (\\<lfloor>tl xs\\<rfloor>, 0), k := \\<lceil>xs ! 0\\<rceil>])\" .\n  then have \"execute (tm_halve j) (0, tps) (Suc (length xs)) =\n      exe (tm_halve j) (0, tps[j := (\\<lfloor>tl xs\\<rfloor>, 0), k := \\<lceil>xs ! 0\\<rceil>])\"\n      (is \"_ = exe _ (0, ?tps)\")\n    by simp\n  also have \"... = (1, ?tps[j := (\\<lfloor>tl xs\\<rfloor>, 0) |+| 1, k := \\<lceil>\\<zero>\\<rceil>])\"\n    using assms(1,2) exe_cmd_halve_0 by simp\n  also have \"... = (1, tps[j := (\\<lfloor>tl xs\\<rfloor>, 0) |+| 1, k := \\<lceil>\\<zero>\\<rceil>])\"\n    using assms(1,2) by (metis (no_types, opaque_lifting) list_update_overwrite list_update_swap)\n  also have \"... = (1, tps[j := (\\<lfloor>tl xs\\<rfloor>, 1), k := \\<lceil>\\<zero>\\<rceil>])\"\n    by simp\n  finally show ?thesis\n    using assms(7) by simp\nqed\n\nlemma execute_tm_halve:\n  assumes \"j < k\"\n    and \"length tps = Suc k\"\n    and \"bit_symbols xs\"\n    and \"tps ! j = (\\<lfloor>xs\\<rfloor>, length xs)\"\n    and \"tps ! k = \\<lceil>\\<triangleright>\\<rceil>\"\n    and \"tps' = tps[j := (\\<lfloor>tl xs\\<rfloor>, 1), k := \\<lceil>\\<zero>\\<rceil>]\"\n  shows \"execute (tm_halve j) (0, tps) (Suc (length xs)) = (1, tps')\"\n  using execute_cmd_halve_0 execute_tm_halve_1 assms by (cases \"length xs = 0\") simp_all\n\nlemma transforms_tm_halve:\n  assumes \"j < k\"\n    and \"length tps = Suc k\"\n    and \"bit_symbols xs\"\n    and \"tps ! j = (\\<lfloor>xs\\<rfloor>, length xs)\"\n    and \"tps ! k = \\<lceil>\\<triangleright>\\<rceil>\"\n    and \"tps' = tps[j := (\\<lfloor>tl xs\\<rfloor>, 1), k := \\<lceil>\\<zero>\\<rceil>]\"\n  shows \"transforms (tm_halve j) tps (Suc (length xs)) tps'\"\n  using execute_tm_halve assms tm_halve_def transforms_def transits_def by auto\n\nlemma transforms_tm_halve2:\n  assumes \"j < k\"\n    and \"length tps = k\"\n    and \"bit_symbols xs\"\n    and \"tps ! j = (\\<lfloor>xs\\<rfloor>, length xs)\"\n    and \"tps' = tps[j := (\\<lfloor>tl xs\\<rfloor>, 1)]\"\n  shows \"transforms (tm_halve j) (tps @ [\\<lceil>\\<triangleright>\\<rceil>]) (Suc (length xs)) (tps' @ [\\<lceil>\\<zero>\\<rceil>])\"\nproof -\n  let ?tps = \"tps @ [\\<lceil>\\<triangleright>\\<rceil>]\"\n  let ?tps' = \"tps' @ [\\<lceil>\\<zero>\\<rceil>]\"\n  have \"?tps ! j = (\\<lfloor>xs\\<rfloor>, length xs)\" \"?tps ! k = \\<lceil>\\<triangleright>\\<rceil>\"\n    using assms by (simp_all add: nth_append)\n  moreover have \"?tps' ! j = (\\<lfloor>tl xs\\<rfloor>, 1)\" \"?tps' ! k = \\<lceil>\\<zero>\\<rceil>\"\n    using assms by (simp_all add: nth_append)\n  moreover have \"length ?tps = Suc k\"\n    using assms(2) by simp\n  ultimately show ?thesis\n    using assms transforms_tm_halve[OF assms(1), where ?tps=\"?tps\" and ?tps'=\"?tps'\" and ?xs=xs]\n    by (metis length_list_update list_update_append1 list_update_length)\nqed\n\ntext \\<open>\nThe next Turing machine removes the memorization tape from @{const tm_halve}.\n\\<close>\n\ndefinition tm_halve' :: \"tapeidx \\<Rightarrow> machine\" where\n  \"tm_halve' j \\<equiv> cartesian (tm_halve j) 4\"\n\nlemma bounded_write_tm_halve:\n  assumes \"j < k\"\n  shows \"bounded_write (tm_halve j) k 4\"\n  unfolding bounded_write_def\nproof standard+\n  fix q :: nat and rs :: \"symbol list\"\n  assume q: \"q < length (tm_halve j)\" and lenrs: \"length rs = Suc k\"\n  have \"k < length rs\"\n    using lenrs by simp\n  then have \"cmd_halve j rs [!] k =\n    (if k = j then\n        if rs ! j = \\<triangleright> then (rs ! k, Right)\n        else if last rs = \\<triangleright> then (\\<box>, Left)\n        else (tosym (todigit (last rs)), Left)\n      else if k = length rs - 1 then (tosym (todigit (rs ! j)), Stay)\n      else (rs ! k, Stay))\"\n    using cmd_halve_def by simp\n  then have \"cmd_halve j rs [!] k = (tosym (todigit (rs ! j)), Stay)\"\n    using assms lenrs by simp\n  then have \"cmd_halve j rs [.] k = tosym (todigit (rs ! j))\"\n    by simp\n  moreover have \"(tm_halve j ! q) rs [.] k = cmd_halve j rs [.] k\"\n    using tm_halve_def q by simp\n  ultimately show \"(tm_halve j ! q) rs [.] k < 4\"\n    by simp\nqed\n\nlemma immobile_tm_halve:\n  assumes \"j < k\"\n  shows \"immobile (tm_halve j) k (Suc k)\"\nproof standard+\n  fix q :: nat and rs :: \"symbol list\"\n  assume q: \"q < length (tm_halve j)\" and lenrs: \"length rs = Suc k\"\n  have \"k < length rs\"\n    using lenrs by simp\n  then have \"cmd_halve j rs [!] k =\n    (if k = j then\n        if rs ! j = \\<triangleright> then (rs ! k, Right)\n        else if last rs = \\<triangleright> then (\\<box>, Left)\n        else (tosym (todigit (last rs)), Left)\n      else if k = length rs - 1 then (tosym (todigit (rs ! j)), Stay)\n      else (rs ! k, Stay))\"\n    using cmd_halve_def by simp\n  then have \"cmd_halve j rs [!] k = (tosym (todigit (rs ! j)), Stay)\"\n    using assms lenrs by simp\n  then have \"cmd_halve j rs [~] k = Stay\"\n    by simp\n  moreover have \"(tm_halve j ! q) rs [~] k = cmd_halve j rs [~] k\"\n    using tm_halve_def q by simp\n  ultimately show \"(tm_halve j ! q) rs [~] k = Stay\"\n    by simp\nqed\n\nlemma tm_halve'_tm:\n  assumes \"G \\<ge> 4\" and \"0 < j\" and \"j < k\"\n  shows \"turing_machine k G (tm_halve' j)\"\n  using tm_halve'_def tm_halve_tm assms cartesian_tm by simp\n\nlemma transforms_tm_halve' [transforms_intros]:\n  assumes \"j > 0\" and \"j < k\"\n    and \"length tps = k\"\n    and \"bit_symbols xs\"\n    and \"tps ! j = (\\<lfloor>xs\\<rfloor>, length xs)\"\n    and \"tps' = tps[j := (\\<lfloor>tl xs\\<rfloor>, 1)]\"\n  shows \"transforms (tm_halve' j) tps (Suc (length xs)) tps'\"\n  unfolding tm_halve'_def\nproof (rule cartesian_transforms_onesie[OF tm_halve_tm immobile_tm_halve _ _ bounded_write_tm_halve assms(3), where ?G=4];\n    (simp add: assms)?)\n  show \"2 \\<le> k\" and \"2 \\<le> k\"\n    using assms(1,2) by simp_all\n  show \"transforms (tm_halve j) (tps @ [\\<lceil>Suc 0\\<rceil>]) (Suc (length xs))\n     (tps[j := (\\<lfloor>tl xs\\<rfloor>, Suc 0)] @ [\\<lceil>\\<zero>\\<rceil>])\"\n    using transforms_tm_halve2 assms by simp\nqed\n\nlemma num_tl_div_2: \"num (tl xs) = num xs div 2\"\nproof (cases \"xs = []\")\n  case True\n  then show ?thesis\n    by (simp add: num_def)\nnext\n  case False\n  then have *: \"xs = hd xs # tl xs\"\n    by simp\n  then have \"num xs = todigit (hd xs) + 2 * num (tl xs)\"\n    using num_Cons by metis\n  then show ?thesis\n    by simp\nqed\n\nlemma canrepr_div_2: \"canrepr (n div 2) = tl (canrepr n)\"\n  using canreprI canrepr canonical_canrepr num_tl_div_2 canonical_tl\n  by (metis hd_Cons_tl list.sel(2))\n\ncorollary nlength_times2: \"nlength (2 * n) \\<le> Suc (nlength n)\"\n  using canrepr_div_2[of \"2 * n\"] by simp\n\ncorollary nlength_times2plus1: \"nlength (2 * n + 1) \\<le> Suc (nlength n)\"\n  using canrepr_div_2[of \"2 * n + 1\"] by simp\n\ntext \\<open>\nThe next Turing machine is the one we actually use to divide a number by two.\nFirst it moves to the end of the symbol sequence representing the number, then\nit applies @{const tm_halve'}.\n\\<close>\n\ndefinition tm_div2 :: \"tapeidx \\<Rightarrow> machine\" where\n  \"tm_div2 j \\<equiv> tm_right_until j {\\<box>} ;; tm_left j ;; tm_halve' j\"\n\nlemma tm_div2_tm:\n  assumes \"G \\<ge> 4\" and \"0 < j\" and \"j < k\"\n  shows \"turing_machine k G (tm_div2 j)\"\n  unfolding tm_div2_def using tm_right_until_tm tm_left_tm tm_halve'_tm assms by simp\n\nlocale turing_machine_div2 =\n  fixes j :: tapeidx\nbegin\n\ndefinition \"tm1 \\<equiv> tm_right_until j {\\<box>}\"\ndefinition \"tm2 \\<equiv> tm1 ;; tm_left j\"\ndefinition \"tm3 \\<equiv> tm2 ;; tm_halve' j\"\n\nlemma tm3_eq_tm_div2: \"tm3 = tm_div2 j\"\n  unfolding tm3_def tm2_def tm1_def tm_div2_def by simp\n\ncontext\n  fixes tps0 :: \"tape list\" and k n :: nat\n  assumes jk: \"0 < j\" \"j < k\" \"length tps0 = k\"\n    and tps0: \"tps0 ! j = (\\<lfloor>n\\<rfloor>\\<^sub>N, 1)\"\nbegin\n\ndefinition \"tps1 \\<equiv> tps0\n  [j := (\\<lfloor>n\\<rfloor>\\<^sub>N, Suc (nlength n))]\"\n\nlemma tm1 [transforms_intros]:\n  assumes \"ttt = Suc (nlength n)\"\n  shows \"transforms tm1 tps0 ttt tps1\"\n  unfolding tm1_def\nproof (tform tps: tps1_def jk tps0 time: assms)\n  have \"rneigh (\\<lfloor>n\\<rfloor>\\<^sub>N, Suc 0) {\\<box>} (nlength n)\"\n  proof (intro rneighI)\n    show \"fst (\\<lfloor>n\\<rfloor>\\<^sub>N, Suc 0) (snd (\\<lfloor>n\\<rfloor>\\<^sub>N, Suc 0) + nlength n) \\<in> {\\<box>}\"\n      using contents_def by simp\n    show \"\\<And>n'. n' < nlength n \\<Longrightarrow> fst (\\<lfloor>n\\<rfloor>\\<^sub>N, Suc 0) (snd (\\<lfloor>n\\<rfloor>\\<^sub>N, Suc 0) + n') \\<notin> {\\<box>}\"\n      using bit_symbols_canrepr contents_def contents_outofbounds proper_symbols_canrepr\n      by (metis One_nat_def Suc_leI add_diff_cancel_left' fst_eqD less_Suc_eq_0_disj less_nat_zero_code\n        plus_1_eq_Suc singletonD snd_conv)\n  qed\n  then show \"rneigh (tps0 ! j) {\\<box>} (nlength n)\"\n    using tps0 by simp\nqed\n\ndefinition \"tps2 \\<equiv> tps0\n  [j := (\\<lfloor>n\\<rfloor>\\<^sub>N, nlength n)]\"\n\nlemma tm2 [transforms_intros]:\n  assumes \"ttt = 2 + nlength n\"\n  shows \"transforms tm2 tps0 ttt tps2\"\n  unfolding tm2_def by (tform tps: tps1_def tps2_def jk assms)\n\ndefinition \"tps3 \\<equiv> tps0\n  [j := (\\<lfloor>n div 2\\<rfloor>\\<^sub>N, 1)]\"\n\nlemma tm3:\n  assumes \"ttt = 2 * nlength n + 3\"\n  shows \"transforms tm3 tps0 ttt tps3\"\n  unfolding tm3_def\nproof (tform tps: tps3_def tps2_def tps0 jk time: assms)\n  show \"bit_symbols (canrepr n)\"\n    using bit_symbols_canrepr .\n  show \"tps3 = tps2[j := (\\<lfloor>tl (canrepr n)\\<rfloor>, 1)]\"\n    using tps3_def tps2_def jk tps0 canrepr_div_2 by simp\nqed\n\nend\n\nend  (* locale turing_machine_div2 *)\n\nlemma transforms_tm_div2I [transforms_intros]:\n  fixes tps tps' :: \"tape list\" and ttt k n :: nat and j :: tapeidx\n  assumes \"0 < j\" \"j < k\"\n    and \"length tps = k\"\n    and \"tps ! j = (\\<lfloor>n\\<rfloor>\\<^sub>N, 1)\"\n  assumes \"ttt = 2 * nlength n + 3\"\n  assumes \"tps' = tps[j := (\\<lfloor>n div 2\\<rfloor>\\<^sub>N, 1)]\"\n  shows \"transforms (tm_div2 j) tps ttt tps'\"\nproof -\n  interpret loc: turing_machine_div2 j .\n  show ?thesis\n    using loc.tm3_eq_tm_div2 loc.tm3 loc.tps3_def assms by simp\nqed\n\n\nsubsection \\<open>Modulo two\\<close>\n\ntext \\<open>\nIn this section we construct a Turing machine that writes to tape $j_2$ the\nsymbol @{text \\<one>} or @{text \\<box>} depending on whether the number on tape $j_1$ is\nodd or even. If initially tape $j_2$ contained at most one symbol, it will\ncontain the numbers~1 or~0.\n\\<close>\n\nlemma canrepr_odd: \"odd n \\<Longrightarrow> canrepr n ! 0 = \\<one>\"\nproof -\n  assume \"odd n\"\n  then have \"0 < n\"\n    by presburger\n  then have len: \"length (canrepr n) > 0\"\n    using nlength_0 by simp\n  then have \"canrepr n ! 0 = \\<zero> \\<or> canrepr n ! 0 = \\<one>\"\n    using bit_symbols_canrepr by fastforce\n  then show \"canrepr n ! 0 = \\<one>\"\n    using prepend_2_even len canrepr `odd n` `0 < n`\n    by (metis gr0_implies_Suc length_Suc_conv nth_Cons_0)\nqed\n\nlemma canrepr_even: \"even n \\<Longrightarrow> 0 < n \\<Longrightarrow> canrepr n ! 0 = \\<zero>\"\nproof -\n  assume \"even n\" \"0 < n\"\n  then have len: \"length (canrepr n) > 0\"\n    using nlength_0 by simp\n  then have \"canrepr n ! 0 = \\<zero> \\<or> canrepr n ! 0 = \\<one>\"\n    using bit_symbols_canrepr by fastforce\n  then show \"canrepr n ! 0 = \\<zero>\"\n    using prepend_3_odd len canrepr `even n` `0 < n`\n    by (metis gr0_implies_Suc length_Suc_conv nth_Cons_0)\nqed\n\ndefinition \"tm_mod2 j1 j2 \\<equiv> tm_trans2 j1 j2 (\\<lambda>z. if z = \\<one> then \\<one> else \\<box>)\"\n\nlemma tm_mod2_tm:\n  assumes \"k \\<ge> 2\" and \"G \\<ge> 4\" and \"0 < j2\" and \"j1 < k\" and \"j2 < k\"\n  shows \"turing_machine k G (tm_mod2 j1 j2)\"\n  unfolding tm_mod2_def using assms tm_trans2_tm by simp\n\nlemma transforms_tm_mod2I [transforms_intros]:\n  assumes \"j1 < length tps\" and \"0 < j2\" and \"j2 < length tps\"\n    and \"b \\<le> 1\"\n  assumes \"tps ! j1 = (\\<lfloor>n\\<rfloor>\\<^sub>N, 1)\"\n    and \"tps ! j2 = (\\<lfloor>b\\<rfloor>\\<^sub>N, 1)\"\n  assumes \"tps' = tps[j2 := (\\<lfloor>n mod 2\\<rfloor>\\<^sub>N, 1)]\"\n  shows \"transforms (tm_mod2 j1 j2) tps 1 tps'\"\nproof -\n  let ?f = \"\\<lambda>z::symbol. if z = \\<one> then \\<one> else \\<box>\"\n  let ?tps = \"tps[j2 := tps ! j2 |:=| (?f (tps :.: j1))]\"\n  have *: \"transforms (tm_mod2 j1 j2) tps 1 ?tps\"\n    using transforms_tm_trans2I assms tm_mod2_def by metis\n\n  have \"tps :.: j1 = \\<one>\" if \"odd n\"\n    using that canrepr_odd assms(5) contents_def\n    by (metis One_nat_def diff_Suc_1 fst_conv gr_implies_not0 ncontents_1_blank_iff_zero odd_pos snd_conv)\n  moreover have \"tps :.: j1 = \\<zero>\" if \"even n\" and \"n > 0\"\n    using that canrepr_even assms(5) contents_def\n    by (metis One_nat_def diff_Suc_1 fst_conv gr_implies_not0 ncontents_1_blank_iff_zero snd_conv)\n  moreover have \"tps :.: j1 = \\<box>\" if \"n = 0\"\n    using that canrepr_even assms(5) contents_def\n    by simp\n  ultimately have \"tps :.: j1 = \\<one> \\<longleftrightarrow> odd n\"\n    by linarith\n  then have f: \"?f (tps :.: j1) = \\<one> \\<longleftrightarrow> odd n\"\n    by simp\n\n  have tps_j2: \"tps ! j2 |:=| (?f (tps :.: j1)) = ((\\<lfloor>b\\<rfloor>\\<^sub>N)(1 := (?f (tps :.: j1))), 1)\"\n    using assms by simp\n\n  have \"tps ! j2 |:=| (?f (tps :.: j1)) = (\\<lfloor>n mod 2\\<rfloor>\\<^sub>N, 1)\"\n  proof (cases \"even n\")\n    case True\n    then have \"tps ! j2 |:=| (?f (tps :.: j1)) = ((\\<lfloor>b\\<rfloor>\\<^sub>N)(1 := 0), 1)\"\n      using f tps_j2 by auto\n    also have \"... = (\\<lfloor>[]\\<rfloor>, 1)\"\n    proof (cases \"b = 0\")\n      case True\n      then have \"\\<lfloor>b\\<rfloor>\\<^sub>N = \\<lfloor>[]\\<rfloor>\"\n        using canrepr_0 by simp\n      then show ?thesis\n        by auto\n    next\n      case False\n      then have \"\\<lfloor>b\\<rfloor>\\<^sub>N = \\<lfloor>[\\<one>]\\<rfloor>\"\n        using canrepr_1 assms(4) by (metis One_nat_def bot_nat_0.extremum_uniqueI le_Suc_eq)\n      then show ?thesis\n        by (metis One_nat_def append.simps(1) append_Nil2 contents_append_update contents_blank_0 list.size(3))\n    qed\n    also have \"... = (\\<lfloor>0\\<rfloor>\\<^sub>N, 1)\"\n      using canrepr_0 by simp\n    finally show ?thesis\n      using True by auto\n  next\n    case False\n    then have \"tps ! j2 |:=| (?f (tps :.: j1)) = ((\\<lfloor>b\\<rfloor>\\<^sub>N)(1 := \\<one>), 1)\"\n      using f tps_j2 by auto\n    also have \"... = (\\<lfloor>[\\<one>]\\<rfloor>, 1)\"\n    proof (cases \"b = 0\")\n      case True\n      then have \"\\<lfloor>b\\<rfloor>\\<^sub>N = \\<lfloor>[]\\<rfloor>\"\n        using canrepr_0 by simp\n      then show ?thesis\n        by (metis One_nat_def append.simps(1) contents_snoc list.size(3))\n    next\n      case False\n      then have \"\\<lfloor>b\\<rfloor>\\<^sub>N = \\<lfloor>[\\<one>]\\<rfloor>\"\n        using canrepr_1 assms(4) by (metis One_nat_def bot_nat_0.extremum_uniqueI le_Suc_eq)\n      then show ?thesis\n        by auto\n    qed\n    also have \"... = (\\<lfloor>1\\<rfloor>\\<^sub>N, 1)\"\n      using canrepr_1 by simp\n    also have \"... = (\\<lfloor>n mod 2\\<rfloor>\\<^sub>N, 1)\"\n      using False by (simp add: mod2_eq_if)\n    finally show ?thesis\n      by auto\n  qed\n  then show ?thesis\n    using * assms(7) by auto\nqed\n\n\nsubsection \\<open>Boolean operations\\<close>\n\ntext \\<open>\nIn order to support Boolean operations, we represent the value True by the\nnumber~1 and False by~0.\n\\<close>\n\nabbreviation bcontents :: \"bool \\<Rightarrow> (nat \\<Rightarrow> symbol)\" (\"\\<lfloor>_\\<rfloor>\\<^sub>B\") where\n  \"\\<lfloor>b\\<rfloor>\\<^sub>B \\<equiv> \\<lfloor>if b then 1 else 0\\<rfloor>\\<^sub>N\"\n\ntext \\<open>\nA tape containing a number contains the number~0 iff.\\ there is a blank in cell\nnumber~1.\n\\<close>\n\nlemma read_ncontents_eq_0:\n  assumes \"tps ! j = (\\<lfloor>n\\<rfloor>\\<^sub>N, 1)\" and \"j < length tps\"\n  shows \"(read tps) ! j = \\<box> \\<longleftrightarrow> n = 0\"\n  using assms tapes_at_read'[of j tps] ncontents_1_blank_iff_zero by (metis prod.sel(1) prod.sel(2))\n\n\nsubsubsection \\<open>And\\<close>\n\ntext \\<open>\nThe next Turing machine, when given two numbers $a, b \\in \\{0, 1\\}$ on tapes\n$j_1$ and $j_2$, writes to tape $j_1$ the number~1 if $a = b = 1$; otherwise it\nwrites the number~0. In other words, it overwrites tape $j_1$ with the logical\nAND of the two tapes.\n\\<close>\n\ndefinition tm_and :: \"tapeidx \\<Rightarrow> tapeidx \\<Rightarrow> machine\" where\n  \"tm_and j1 j2 \\<equiv> IF \\<lambda>rs. rs ! j1 = \\<one> \\<and> rs ! j2 = \\<box> THEN tm_write j1 \\<box> ELSE [] ENDIF\"\n\nlemma tm_and_tm:\n  assumes \"k \\<ge> 2\" and \"G \\<ge> 4\" and \"0 < j1\" and \"j1 < k\"\n  shows \"turing_machine k G (tm_and j1 j2)\"\n  using tm_and_def tm_write_tm Nil_tm assms turing_machine_branch_turing_machine by simp\n\nlocale turing_machine_and =\n  fixes j1 j2 :: tapeidx\nbegin\n\ncontext\n  fixes tps0 :: \"tape list\" and k :: nat and a b :: nat\n  assumes ab: \"a < 2\" \"b < 2\"\n  assumes jk: \"j1 < k\" \"j2 < k\" \"j1 \\<noteq> j2\" \"0 < j1\" \"length tps0 = k\"\n  assumes tps0:\n    \"tps0 ! j1 = (\\<lfloor>a\\<rfloor>\\<^sub>N, 1)\"\n    \"tps0 ! j2 = (\\<lfloor>b\\<rfloor>\\<^sub>N, 1)\"\nbegin\n\ndefinition \"tps1 \\<equiv> tps0\n  [j1 := (\\<lfloor>a = 1 \\<and> b = 1\\<rfloor>\\<^sub>B, 1)]\"\n\nlemma tm: \"transforms (tm_and j1 j2) tps0 3 tps1\"\n  unfolding tm_and_def\nproof (tform)\n  have \"read tps0 ! j1 = \\<lfloor>canrepr a\\<rfloor> 1\"\n    using jk tps0 tapes_at_read'[of j1 tps0] by simp\n  then have 1: \"read tps0 ! j1 = \\<one> \\<longleftrightarrow> a = 1\"\n    using ab canrepr_odd contents_def ncontents_1_blank_iff_zero\n    by (metis (mono_tags, lifting) One_nat_def diff_Suc_1 less_2_cases_iff odd_one)\n  have \"read tps0 ! j2 = \\<lfloor>canrepr b\\<rfloor> 1\"\n    using jk tps0 tapes_at_read'[of j2 tps0] by simp\n  then have 2: \"read tps0 ! j2 = \\<one> \\<longleftrightarrow> b = 1\"\n    using ab canrepr_odd contents_def ncontents_1_blank_iff_zero\n    by (metis (mono_tags, lifting) One_nat_def diff_Suc_1 less_2_cases_iff odd_one)\n\n  show \"tps1 = tps0\" if \"\\<not> (read tps0 ! j1 = \\<one> \\<and> read tps0 ! j2 = \\<box>)\"\n  proof -\n    have \"a = (if a = 1 \\<and> b = 1 then 1 else 0)\"\n      using that 1 2 ab jk by (metis One_nat_def less_2_cases_iff read_ncontents_eq_0 tps0(2))\n    then have \"tps0 ! j1 = (\\<lfloor>a = 1 \\<and> b = 1\\<rfloor>\\<^sub>B, 1)\"\n      using tps0 by simp\n    then show ?thesis\n      unfolding tps1_def using list_update_id[of tps0 j1] by simp\n  qed\n  show \"tps1 = tps0[j1 := tps0 ! j1 |:=| \\<box>]\" if \"read tps0 ! j1 = \\<one> \\<and> read tps0 ! j2 = \\<box>\"\n  proof -\n    have \"(if a = 1 \\<and> b = 1 then 1 else 0) = 0\"\n      using that 1 2 by simp\n    moreover have \"tps0 ! j1 |:=| \\<box> = (\\<lfloor>0\\<rfloor>\\<^sub>N, 1)\"\n    proof (cases \"a = 0\")\n      case True\n      then show ?thesis\n        using tps0 jk by auto\n    next\n      case False\n      then have \"a = 1\"\n        using ab by simp\n      then have \"\\<lfloor>a\\<rfloor>\\<^sub>N = \\<lfloor>[\\<one>]\\<rfloor>\"\n        using canrepr_1 by simp\n      moreover have \"(\\<lfloor>[\\<one>]\\<rfloor>, 1) |:=| \\<box> = (\\<lfloor>[]\\<rfloor>, 1)\"\n        using contents_def by auto\n      ultimately have \"(\\<lfloor>a\\<rfloor>\\<^sub>N, 1) |:=| \\<box> = (\\<lfloor>0\\<rfloor>\\<^sub>N, 1)\"\n        using ncontents_0 by presburger\n      then show ?thesis\n        using tps0 jk by simp\n    qed\n    ultimately have \"tps0 ! j1 |:=| \\<box> = (\\<lfloor>a = 1 \\<and> b = 1\\<rfloor>\\<^sub>B, 1)\"\n      by (smt (verit, best))\n    then show ?thesis\n      unfolding tps1_def by auto\n  qed\nqed\n\nend  (* context *)\n\nend  (* locale *)\n\nlemma transforms_tm_andI [transforms_intros]:\n  fixes j1 j2 :: tapeidx\n  fixes tps :: \"tape list\" and k :: nat and a b :: nat\n  assumes \"a < 2\" \"b < 2\"\n  assumes \"length tps = k\"\n  assumes \"j1 < k\" \"j2 < k\" \"j1 \\<noteq> j2\" \"0 < j1\"\n  assumes\n    \"tps ! j1 = (\\<lfloor>a\\<rfloor>\\<^sub>N, 1)\"\n    \"tps ! j2 = (\\<lfloor>b\\<rfloor>\\<^sub>N, 1)\"\n  assumes \"tps' = tps\n    [j1 := (\\<lfloor>a = 1 \\<and> b = 1\\<rfloor>\\<^sub>B, 1)]\"\n  shows \"transforms (tm_and j1 j2) tps 3 tps'\"\nproof -\n  interpret loc: turing_machine_and j1 j2 .\n  show ?thesis\n    using assms loc.tps1_def loc.tm by simp\nqed\n\n\nsubsubsection \\<open>Not\\<close>\n\ntext \\<open>\nThe next Turing machine turns the number~1 into~0 and vice versa.\n\\<close>\n\ndefinition tm_not :: \"tapeidx \\<Rightarrow> machine\" where\n  \"tm_not j \\<equiv> IF \\<lambda>rs. rs ! j = \\<box> THEN tm_write j \\<one> ELSE tm_write j \\<box> ENDIF\"\n\nlemma tm_not_tm:\n  assumes \"k \\<ge> 2\" and \"G \\<ge> 4\" and \"0 < j\" and \"j < k\"\n  shows \"turing_machine k G (tm_not j)\"\n  using tm_not_def tm_write_tm assms turing_machine_branch_turing_machine by simp\n\nlocale turing_machine_not =\n  fixes j :: tapeidx\nbegin\n\ncontext\n  fixes tps0 :: \"tape list\" and k :: nat and a :: nat\n  assumes a: \"a < 2\"\n  assumes jk: \"j < k\" \"length tps0 = k\"\n  assumes tps0: \"tps0 ! j = (\\<lfloor>a\\<rfloor>\\<^sub>N, 1)\"\nbegin\n\ndefinition \"tps1 \\<equiv> tps0\n  [j := (\\<lfloor>a \\<noteq> 1\\<rfloor>\\<^sub>B, 1)]\"\n\nlemma tm: \"transforms (tm_not j) tps0 3 tps1\"\n  unfolding tm_not_def\nproof (tform)\n  have *: \"read tps0 ! j = \\<box> \\<longleftrightarrow> a = 0\"\n    using read_ncontents_eq_0 jk tps0 by simp\n  show \"tps1 = tps0[j := tps0 ! j |:=| \\<one>]\" if \"read tps0 ! j = \\<box>\"\n  proof -\n    have \"a = 0\"\n      using a that * by simp\n    then have \"(\\<lfloor>if a = 1 then 0 else 1\\<rfloor>\\<^sub>N, 1) = (\\<lfloor>1\\<rfloor>\\<^sub>N, 1)\"\n      by simp\n    moreover have \"tps0 ! j |:=| \\<one> = (\\<lfloor>1\\<rfloor>\\<^sub>N, 1)\"\n      using tps0 canrepr_0 canrepr_1 `a = 0` contents_snoc\n      by (metis One_nat_def append.simps(1) fst_conv list.size(3) snd_conv)\n    ultimately have \"tps0[j := tps0 ! j |:=| \\<one>] = tps0[j := (\\<lfloor>a \\<noteq> 1\\<rfloor>\\<^sub>B, 1)]\"\n      by auto\n    then show ?thesis\n      using tps1_def by simp\n  qed\n  show \"tps1 = tps0[j := tps0 ! j |:=| \\<box>]\" if \"read tps0 ! j \\<noteq> \\<box>\"\n  proof -\n    have \"a = 1\"\n      using a that * by simp\n    then have \"(\\<lfloor>if a = 1 then 0 else 1\\<rfloor>\\<^sub>N, 1) = (\\<lfloor>0\\<rfloor>\\<^sub>N, 1)\"\n      by simp\n    moreover have \"tps0 ! j |:=| \\<box> = (\\<lfloor>0\\<rfloor>\\<^sub>N, 1)\"\n      using tps0 canrepr_0 canrepr_1 `a = 1` contents_snoc\n      by (metis Suc_1 append_self_conv2 contents_blank_0 fst_eqD fun_upd_upd nat.inject nlength_0_simp numeral_2_eq_2 snd_eqD)\n    ultimately have \"tps0[j := tps0 ! j |:=| \\<box>] = tps0[j := (\\<lfloor>a \\<noteq> 1\\<rfloor>\\<^sub>B, 1)]\"\n      by auto\n    then show ?thesis\n      using tps1_def by simp\n  qed\nqed\n\nend  (* context *)\n\nend  (* locale *)\n\nlemma transforms_tm_notI [transforms_intros]:\n  fixes j :: tapeidx\n  fixes tps tps' :: \"tape list\" and k :: nat and a :: nat\n  assumes \"j < k\" \"length tps = k\"\n    and \"a < 2\"\n  assumes \"tps ! j = (\\<lfloor>a\\<rfloor>\\<^sub>N, 1)\"\n  assumes \"tps' = tps\n    [j := (\\<lfloor>a \\<noteq> 1\\<rfloor>\\<^sub>B, 1)]\"\n  shows \"transforms (tm_not j) tps 3 tps'\"\nproof -\n  interpret loc: turing_machine_not j .\n  show ?thesis\n    using assms loc.tps1_def loc.tm by simp\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/Cook_Levin/Arithmetic.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8652240930029118, "lm_q2_score": 0.8289388104343893, "lm_q1q2_score": 0.7172178304130071}}
{"text": "(*  Title:      HOL/Computational_Algebra/Polynomial_FPS.thy\n    Author:     Manuel Eberl, TU M\u00fcnchen\n*)\n\nsection \\<open>Converting polynomials to formal power series\\<close>\n\ntheory Polynomial_FPS\n  imports Polynomial Formal_Power_Series\nbegin\n\ncontext\n  includes fps_notation\nbegin\n\ndefinition fps_of_poly where\n  \"fps_of_poly p = Abs_fps (coeff p)\"\n\nlemma fps_of_poly_eq_iff: \"fps_of_poly p = fps_of_poly q \\<longleftrightarrow> p = q\"\n  by (simp add: fps_of_poly_def poly_eq_iff fps_eq_iff)\n\nlemma fps_of_poly_nth [simp]: \"fps_of_poly p $ n = coeff p n\"\n  by (simp add: fps_of_poly_def)\n  \nlemma fps_of_poly_const: \"fps_of_poly [:c:] = fps_const c\"\nproof (subst fps_eq_iff, clarify)\n  fix n :: nat show \"fps_of_poly [:c:] $ n = fps_const c $ n\"\n    by (cases n) (auto simp: fps_of_poly_def)\nqed\n\nlemma fps_of_poly_0 [simp]: \"fps_of_poly 0 = 0\"\n  by (subst fps_const_0_eq_0 [symmetric], subst fps_of_poly_const [symmetric]) simp\n\nlemma fps_of_poly_1 [simp]: \"fps_of_poly 1 = 1\"\n  by (simp add: fps_eq_iff)\n\nlemma fps_of_poly_1' [simp]: \"fps_of_poly [:1:] = 1\"\n  by (subst fps_const_1_eq_1 [symmetric], subst fps_of_poly_const [symmetric])\n     (simp add: one_poly_def)\n\nlemma fps_of_poly_numeral [simp]: \"fps_of_poly (numeral n) = numeral n\"\n  by (simp add: numeral_fps_const fps_of_poly_const [symmetric] numeral_poly)\n\nlemma fps_of_poly_numeral' [simp]: \"fps_of_poly [:numeral n:] = numeral n\"\n  by (simp add: numeral_fps_const fps_of_poly_const [symmetric] numeral_poly)\n\nlemma fps_of_poly_fps_X [simp]: \"fps_of_poly [:0, 1:] = fps_X\"\n  by (auto simp add: fps_of_poly_def fps_eq_iff coeff_pCons split: nat.split)\n\nlemma fps_of_poly_add: \"fps_of_poly (p + q) = fps_of_poly p + fps_of_poly q\"\n  by (simp add: fps_of_poly_def plus_poly.rep_eq fps_plus_def)\n\nlemma fps_of_poly_diff: \"fps_of_poly (p - q) = fps_of_poly p - fps_of_poly q\"\n  by (simp add: fps_of_poly_def minus_poly.rep_eq fps_minus_def)\n\nlemma fps_of_poly_uminus: \"fps_of_poly (-p) = -fps_of_poly p\"\n  by (simp add: fps_of_poly_def uminus_poly.rep_eq fps_uminus_def)\n\nlemma fps_of_poly_mult: \"fps_of_poly (p * q) = fps_of_poly p * fps_of_poly q\"\n  by (simp add: fps_of_poly_def fps_times_def fps_eq_iff coeff_mult atLeast0AtMost)\n\nlemma fps_of_poly_smult: \n  \"fps_of_poly (smult c p) = fps_const c * fps_of_poly p\"\n  using fps_of_poly_mult[of \"[:c:]\" p] by (simp add: fps_of_poly_mult fps_of_poly_const)\n  \nlemma fps_of_poly_sum: \"fps_of_poly (sum f A) = sum (\\<lambda>x. fps_of_poly (f x)) A\"\n  by (cases \"finite A\", induction rule: finite_induct) (simp_all add: fps_of_poly_add)\n\nlemma fps_of_poly_sum_list: \"fps_of_poly (sum_list xs) = sum_list (map fps_of_poly xs)\"\n  by (induction xs) (simp_all add: fps_of_poly_add)\n  \nlemma fps_of_poly_prod: \"fps_of_poly (prod f A) = prod (\\<lambda>x. fps_of_poly (f x)) A\"\n  by (cases \"finite A\", induction rule: finite_induct) (simp_all add: fps_of_poly_mult)\n  \nlemma fps_of_poly_prod_list: \"fps_of_poly (prod_list xs) = prod_list (map fps_of_poly xs)\"\n  by (induction xs) (simp_all add: fps_of_poly_mult)\n\nlemma fps_of_poly_pCons: \n  \"fps_of_poly (pCons (c :: 'a :: semiring_1) p) = fps_const c + fps_of_poly p * fps_X\"\n  by (subst fps_mult_fps_X_commute [symmetric], intro fps_ext) \n     (auto simp: fps_of_poly_def coeff_pCons split: nat.split)\n  \nlemma fps_of_poly_pderiv: \"fps_of_poly (pderiv p) = fps_deriv (fps_of_poly p)\"\n  by (intro fps_ext) (simp add: fps_of_poly_nth coeff_pderiv)\n\nlemma fps_of_poly_power: \"fps_of_poly (p ^ n) = fps_of_poly p ^ n\"\n  by (induction n) (simp_all add: fps_of_poly_mult)\n  \nlemma fps_of_poly_monom: \"fps_of_poly (monom (c :: 'a :: comm_ring_1) n) = fps_const c * fps_X ^ n\"\n  by (intro fps_ext) simp_all\n\nlemma fps_of_poly_monom': \"fps_of_poly (monom (1 :: 'a :: comm_ring_1) n) = fps_X ^ n\"\n  by (simp add: fps_of_poly_monom)\n\nlemma fps_of_poly_div:\n  assumes \"(q :: 'a :: field poly) dvd p\"\n  shows   \"fps_of_poly (p div q) = fps_of_poly p / fps_of_poly q\"\nproof (cases \"q = 0\")\n  case False\n  from False fps_of_poly_eq_iff[of q 0] have nz: \"fps_of_poly q \\<noteq> 0\" by simp \n  from assms have \"p = (p div q) * q\" by simp\n  also have \"fps_of_poly \\<dots> = fps_of_poly (p div q) * fps_of_poly q\" \n    by (simp add: fps_of_poly_mult)\n  also from nz have \"\\<dots> / fps_of_poly q = fps_of_poly (p div q)\"\n    by (intro nonzero_mult_div_cancel_right) (auto simp: fps_of_poly_0)\n  finally show ?thesis ..\nqed simp\n\nlemma fps_of_poly_divide_numeral:\n  \"fps_of_poly (smult (inverse (numeral c :: 'a :: field)) p) = fps_of_poly p / numeral c\"\nproof -\n  have \"smult (inverse (numeral c)) p = [:inverse (numeral c):] * p\" by simp\n  also have \"fps_of_poly \\<dots> = fps_of_poly p / numeral c\"\n    by (subst fps_of_poly_mult) (simp add: numeral_fps_const fps_of_poly_pCons)\n  finally show ?thesis by simp\nqed\n\n\nlemma subdegree_fps_of_poly:\n  assumes \"p \\<noteq> 0\"\n  defines \"n \\<equiv> Polynomial.order 0 p\"\n  shows   \"subdegree (fps_of_poly p) = n\"\nproof (rule subdegreeI)\n  from assms have \"monom 1 n dvd p\" by (simp add: monom_1_dvd_iff)\n  thus zero: \"fps_of_poly p $ i = 0\" if \"i < n\" for i\n    using that by (simp add: monom_1_dvd_iff')\n    \n  from assms have \"\\<not>monom 1 (Suc n) dvd p\"\n    by (auto simp: monom_1_dvd_iff simp del: power_Suc)\n  then obtain k where k: \"k \\<le> n\" \"fps_of_poly p $ k \\<noteq> 0\" \n    by (auto simp: monom_1_dvd_iff' less_Suc_eq_le)\n  with zero[of k] have \"k = n\" by linarith\n  with k show \"fps_of_poly p $ n \\<noteq> 0\" by simp\nqed\n\nlemma fps_of_poly_dvd:\n  assumes \"p dvd q\"\n  shows   \"fps_of_poly (p :: 'a :: field poly) dvd fps_of_poly q\"\nproof (cases \"p = 0 \\<or> q = 0\")\n  case False\n  with assms fps_of_poly_eq_iff[of p 0] fps_of_poly_eq_iff[of q 0] show ?thesis\n    by (auto simp: fps_dvd_iff subdegree_fps_of_poly dvd_imp_order_le)\nqed (insert assms, auto)\n\n\nlemmas fps_of_poly_simps =\n  fps_of_poly_0 fps_of_poly_1 fps_of_poly_numeral fps_of_poly_const fps_of_poly_fps_X\n  fps_of_poly_add fps_of_poly_diff fps_of_poly_uminus fps_of_poly_mult fps_of_poly_smult\n  fps_of_poly_sum fps_of_poly_sum_list fps_of_poly_prod fps_of_poly_prod_list\n  fps_of_poly_pCons fps_of_poly_pderiv fps_of_poly_power fps_of_poly_monom\n  fps_of_poly_divide_numeral\n\nlemma fps_of_poly_pcompose:\n  assumes \"coeff q 0 = (0 :: 'a :: idom)\"\n  shows   \"fps_of_poly (pcompose p q) = fps_compose (fps_of_poly p) (fps_of_poly q)\"\n  using assms by (induction p rule: pCons_induct)\n                 (auto simp: pcompose_pCons fps_of_poly_simps fps_of_poly_pCons \n                             fps_compose_add_distrib fps_compose_mult_distrib)\n  \nlemmas reify_fps_atom =\n  fps_of_poly_0 fps_of_poly_1' fps_of_poly_numeral' fps_of_poly_const fps_of_poly_fps_X\n\n\ntext \\<open>\n  The following simproc can reduce the equality of two polynomial FPSs two equality of the\n  respective polynomials. A polynomial FPS is one that only has finitely many non-zero \n  coefficients and can therefore be written as \\<^term>\\<open>fps_of_poly p\\<close> for some \n  polynomial \\<open>p\\<close>.\n  \n  This may sound trivial, but it covers a number of annoying side conditions like \n  \\<^term>\\<open>1 + fps_X \\<noteq> 0\\<close> that would otherwise not be solved automatically.\n\\<close>\n\nML \\<open>\n\n(* TODO: Support for division *)\nsignature POLY_FPS = sig\n\nval reify_conv : conv\nval eq_conv : conv\nval eq_simproc : cterm -> thm option\n\nend\n\n\nstructure Poly_Fps = struct\n\nfun const_binop_conv s conv ct =\n  case Thm.term_of ct of\n    (Const (s', _) $ _ $ _) => \n      if s = s' then \n        Conv.binop_conv conv ct \n      else \n        raise CTERM (\"const_binop_conv\", [ct])\n  | _ => raise CTERM (\"const_binop_conv\", [ct])\n\nfun reify_conv ct = \n  let\n    val rewr = Conv.rewrs_conv o map (fn thm => thm RS @{thm eq_reflection})\n    val un = Conv.arg_conv reify_conv\n    val bin = Conv.binop_conv reify_conv\n  in\n    case Thm.term_of ct of\n      (Const (\\<^const_name>\\<open>fps_of_poly\\<close>, _) $ _) => ct |> Conv.all_conv\n    | (Const (\\<^const_name>\\<open>Groups.plus\\<close>, _) $ _ $ _) => ct |> (\n        bin then_conv rewr @{thms fps_of_poly_add [symmetric]})\n    | (Const (\\<^const_name>\\<open>Groups.uminus\\<close>, _) $ _) => ct |> (\n        un then_conv rewr @{thms fps_of_poly_uminus [symmetric]})\n    | (Const (\\<^const_name>\\<open>Groups.minus\\<close>, _) $ _ $ _) => ct |> (\n        bin then_conv rewr @{thms fps_of_poly_diff [symmetric]})\n    | (Const (\\<^const_name>\\<open>Groups.times\\<close>, _) $ _ $ _) => ct |> (\n        bin then_conv rewr @{thms fps_of_poly_mult [symmetric]})\n    | (Const (\\<^const_name>\\<open>Rings.divide\\<close>, _) $ _ $ (Const (\\<^const_name>\\<open>Num.numeral\\<close>, _) $ _))\n        => ct |> (Conv.fun_conv (Conv.arg_conv reify_conv)\n             then_conv rewr @{thms fps_of_poly_divide_numeral [symmetric]})\n    | (Const (\\<^const_name>\\<open>Power.power\\<close>, _) $ Const (\\<^const_name>\\<open>fps_X\\<close>,_) $ _) => ct |> (\n        rewr @{thms fps_of_poly_monom' [symmetric]}) \n    | (Const (\\<^const_name>\\<open>Power.power\\<close>, _) $ _ $ _) => ct |> (\n        Conv.fun_conv (Conv.arg_conv reify_conv) \n        then_conv rewr @{thms fps_of_poly_power [symmetric]})\n    | _ => ct |> (\n        rewr @{thms reify_fps_atom [symmetric]})\n  end\n    \n\nfun eq_conv ct =\n  case Thm.term_of ct of\n    (Const (\\<^const_name>\\<open>HOL.eq\\<close>, _) $ _ $ _) => ct |> (\n      Conv.binop_conv reify_conv\n      then_conv Conv.rewr_conv @{thm fps_of_poly_eq_iff[THEN eq_reflection]})\n  | _ => raise CTERM (\"poly_fps_eq_conv\", [ct])\n\nval eq_simproc = try eq_conv\n\nend\n\\<close> \n\nsimproc_setup poly_fps_eq (\"(f :: 'a fps) = g\") = \\<open>K (K Poly_Fps.eq_simproc)\\<close>\n\nlemma fps_of_poly_linear: \"fps_of_poly [:a,1 :: 'a :: field:] = fps_X + fps_const a\"\n  by simp\n\nlemma fps_of_poly_linear': \"fps_of_poly [:1,a :: 'a :: field:] = 1 + fps_const a * fps_X\"\n  by simp\n\nlemma fps_of_poly_cutoff [simp]: \n  \"fps_of_poly (poly_cutoff n p) = fps_cutoff n (fps_of_poly p)\"\n  by (simp add: fps_eq_iff coeff_poly_cutoff)\n\nlemma fps_of_poly_shift [simp]: \"fps_of_poly (poly_shift n p) = fps_shift n (fps_of_poly p)\"\n  by (simp add: fps_eq_iff coeff_poly_shift)\n\n\ndefinition poly_subdegree :: \"'a::zero poly \\<Rightarrow> nat\" where\n  \"poly_subdegree p = subdegree (fps_of_poly p)\"\n\nlemma coeff_less_poly_subdegree:\n  \"k < poly_subdegree p \\<Longrightarrow> coeff p k = 0\"\n  unfolding poly_subdegree_def using nth_less_subdegree_zero[of k \"fps_of_poly p\"] by simp\n\n(* TODO: Move ? *)\ndefinition prefix_length :: \"('a \\<Rightarrow> bool) \\<Rightarrow> 'a list \\<Rightarrow> nat\" where\n  \"prefix_length P xs = length (takeWhile P xs)\"\n\nprimrec prefix_length_aux :: \"('a \\<Rightarrow> bool) \\<Rightarrow> nat \\<Rightarrow> 'a list \\<Rightarrow> nat\" where\n  \"prefix_length_aux P acc [] = acc\"\n| \"prefix_length_aux P acc (x#xs) = (if P x then prefix_length_aux P (Suc acc) xs else acc)\"\n\nlemma prefix_length_aux_correct: \"prefix_length_aux P acc xs = prefix_length P xs + acc\"\n  by (induction xs arbitrary: acc) (simp_all add: prefix_length_def)\n\nlemma prefix_length_code [code]: \"prefix_length P xs = prefix_length_aux P 0 xs\"\n  by (simp add: prefix_length_aux_correct)\n\nlemma prefix_length_le_length: \"prefix_length P xs \\<le> length xs\"\n  by (induction xs) (simp_all add: prefix_length_def)\n  \nlemma prefix_length_less_length: \"(\\<exists>x\\<in>set xs. \\<not>P x) \\<Longrightarrow> prefix_length P xs < length xs\"\n  by (induction xs) (simp_all add: prefix_length_def)\n\nlemma nth_prefix_length:\n  \"(\\<exists>x\\<in>set xs. \\<not>P x) \\<Longrightarrow> \\<not>P (xs ! prefix_length P xs)\"\n  by (induction xs) (simp_all add: prefix_length_def)\n  \nlemma nth_less_prefix_length:\n  \"n < prefix_length P xs \\<Longrightarrow> P (xs ! n)\"\n  by (induction xs arbitrary: n) \n     (auto simp: prefix_length_def nth_Cons split: if_splits nat.splits)\n(* END TODO *)\n  \nlemma poly_subdegree_code [code]: \"poly_subdegree p = prefix_length ((=) 0) (coeffs p)\"\nproof (cases \"p = 0\")\n  case False\n  note [simp] = this\n  define n where \"n = prefix_length ((=) 0) (coeffs p)\"\n  from False have \"\\<exists>k. coeff p k \\<noteq> 0\" by (auto simp: poly_eq_iff)\n  hence ex: \"\\<exists>x\\<in>set (coeffs p). x \\<noteq> 0\" by (auto simp: coeffs_def)\n  hence n_less: \"n < length (coeffs p)\" and nonzero: \"coeffs p ! n \\<noteq> 0\" \n    unfolding n_def by (auto intro!: prefix_length_less_length nth_prefix_length)\n  show ?thesis unfolding poly_subdegree_def\n  proof (intro subdegreeI)\n    from n_less have \"fps_of_poly p $ n = coeffs p ! n\"\n      by (subst coeffs_nth) (simp_all add: degree_eq_length_coeffs)\n    with nonzero show \"fps_of_poly p $ prefix_length ((=) 0) (coeffs p) \\<noteq> 0\"\n      unfolding n_def by simp\n  next\n    fix k assume A: \"k < prefix_length ((=) 0) (coeffs p)\"\n    also have \"\\<dots> \\<le> length (coeffs p)\" by (rule prefix_length_le_length)\n    finally show \"fps_of_poly p $ k = 0\"\n      using nth_less_prefix_length[OF A]\n      by (simp add: coeffs_nth degree_eq_length_coeffs)\n  qed\nqed (simp_all add: poly_subdegree_def prefix_length_def)\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/Polynomial_FPS.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240930029117, "lm_q2_score": 0.828938806208442, "lm_q1q2_score": 0.7172178267566156}}
{"text": "section\\<open>Repeat finitely Until it Stabilizes\\<close>\ntheory Repeat_Stabilize\nimports Main\nbegin\n\ntext\\<open>Repeating something a number of times\\<close>\n\n\ntext\\<open>Iterating a function at most @{term n} times (first parameter) until it stabilizes.\\<close>\nfun repeat_stabilize :: \"nat \\<Rightarrow> ('a \\<Rightarrow> 'a) \\<Rightarrow> 'a \\<Rightarrow> 'a\" where\n  \"repeat_stabilize 0 _ v = v\" |\n  \"repeat_stabilize (Suc n) f v = (let v_new = f v in if v = v_new then v else repeat_stabilize n f v_new)\"\n\nlemma repeat_stabilize_funpow: \"repeat_stabilize n f v = (f^^n) v\"\n  proof(induction n arbitrary: v)\n  case (Suc n)\n    have \"f v = v \\<Longrightarrow> (f^^n) v = v\" by(induction n) simp_all\n    with Suc show ?case by(simp add: Let_def funpow_swap1)\n  qed(simp)\n\nlemma repeat_stabilize_induct: \"(P m) \\<Longrightarrow> (\\<And>m. P m \\<Longrightarrow> P (f m)) \\<Longrightarrow> P (repeat_stabilize n f m)\"\n  apply(simp add: repeat_stabilize_funpow)\n  apply(induction n)\n   by(simp)+\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/Iptables_Semantics/Common/Repeat_Stabilize.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388083214156, "lm_q2_score": 0.8652240756264638, "lm_q1q2_score": 0.7172178141807992}}
{"text": "theory pexp imports Main\nbegin\n\ndatatype aop \n  = Ad\n  | Su\n  | Mu\n  | Di\n\ndatatype aexp \n  = N int\n  | V string\n  | Op aexp aop aexp\n\ndefinition Add (infixl \\<open>\\<^bold>+\\<close> 211) where \\<open>a \\<^bold>+ b \\<equiv> Op a Ad b\\<close>\ndefinition Sub (infixl \\<open>\\<^bold>-\\<close> 210) where \\<open>a \\<^bold>- b \\<equiv> Op a Su b\\<close>\ndefinition Mul (infixl \\<open>\\<^bold>*\\<close> 216) where \\<open>a \\<^bold>* b \\<equiv> Op a Mu b\\<close>\ndefinition Div (infixl \\<open>\\<^bold>:\\<close> 215) where \\<open>a \\<^bold>: b \\<equiv> Op a Di b\\<close>\n\nnotation (input) insert (infixr \\<open>\\<^bold>\\<rightarrow>\\<close> 160)\n\nprimrec aopsem :: \\<open>int \\<Rightarrow> int \\<Rightarrow> aop \\<Rightarrow> int\\<close> where\n  \\<open>aopsem x y Ad = x + y\\<close> |\n  \\<open>aopsem x y Su = x - y\\<close> |\n  \\<open>aopsem x y Mu = x * y\\<close> |\n  \\<open>aopsem x y Di = x div y\\<close>\n\nprimrec asem (\\<open>_\\<lparr> _ \\<rparr>\\<close> [102,102] 102) where\n  \\<open>asem i (N v) = v\\<close> |\n  \\<open>asem i (V x) = i x\\<close> |\n  \\<open>asem i (Op a p b) = aopsem (asem i a) (asem i b) p\\<close>\n\nlemma addsem[simp]: \\<open>asem i (a \\<^bold>+ b) = (asem i a) + (asem i b)\\<close> unfolding Add_def by simp\nlemma supsem[simp]: \\<open>asem i (a \\<^bold>- b) = (asem i a) - (asem i b)\\<close> unfolding Sub_def by simp\nlemma mulsem[simp]: \\<open>asem i (a \\<^bold>* b) = (asem i a) * (asem i b)\\<close> unfolding Mul_def by simp\nlemma divsem[simp]: \\<open>asem i (a \\<^bold>: b) = (asem i a) div (asem i b)\\<close> unfolding Div_def by simp\n\ndatatype acomp \n  = Eq\n  | Lt\n\ndatatype pexp\n  = Neg pexp (\\<open>\\<^bold>\\<not>_\\<close> [199] 200)\n  | Con pexp pexp (infixl \\<open>\\<^bold>\\<and>\\<close> 150)\n  | Uni string pexp (\\<open>\\<^bold>\\<forall> _. _\\<close> [102,102] 102)\n  | A aexp acomp aexp\n\ndefinition Eql (infix \\<open>\\<^bold>=\\<close> 205) where \\<open>a \\<^bold>= b \\<equiv> A a Eq b\\<close>\ndefinition Ltn (infix \\<open>\\<^bold><\\<close> 205) where \\<open>a \\<^bold>< b \\<equiv> A a Lt b\\<close>\n\ndefinition Dis (infixl \\<open>\\<^bold>\\<or>\\<close> 140) where \\<open>a \\<^bold>\\<or> b \\<equiv> \\<^bold>\\<not>(\\<^bold>\\<not>a \\<^bold>\\<and> \\<^bold>\\<not>b)\\<close>\ndefinition Imp (infixr \\<open>\\<^bold>\\<longrightarrow>\\<close> 120) where \\<open>a \\<^bold>\\<longrightarrow> b \\<equiv> \\<^bold>\\<not>(a \\<^bold>\\<and> \\<^bold>\\<not>b)\\<close>\ndefinition Tru (\\<open>\\<^bold>\\<top>\\<close>) where \\<open>\\<^bold>\\<top> \\<equiv> (N 0) \\<^bold>= (N 0)\\<close>\ndefinition Fls (\\<open>\\<^bold>\\<bottom>\\<close>) where \\<open>\\<^bold>\\<bottom> \\<equiv> \\<^bold>\\<not>\\<^bold>\\<top>\\<close>\ndefinition Exi (\\<open>\\<^bold>\\<exists> _. _\\<close> [101,101] 100) where \\<open>\\<^bold>\\<exists> x. p \\<equiv> \\<^bold>\\<not>(\\<^bold>\\<forall> x. \\<^bold>\\<not>p)\\<close>\n\ndefinition Leq (infix \\<open>\\<^bold>\\<le>\\<close> 205) where \\<open>a \\<^bold>\\<le> b \\<equiv> a \\<^bold>< b \\<^bold>\\<or> a \\<^bold>= b\\<close>\ndefinition Gtn (infix \\<open>\\<^bold>>\\<close> 205) where \\<open>a \\<^bold>> b \\<equiv> \\<^bold>\\<not>a \\<^bold>< b \\<^bold>\\<and> \\<^bold>\\<not>a \\<^bold>= b\\<close>\ndefinition Geq (infix \\<open>\\<^bold>\\<ge>\\<close> 205) where \\<open>a \\<^bold>\\<ge> b \\<equiv> \\<^bold>\\<not>a \\<^bold>< b\\<close>\n\nprimrec acompsem :: \\<open>int \\<Rightarrow> int \\<Rightarrow> acomp \\<Rightarrow> bool\\<close> where\n  \\<open>acompsem x y Eq = (x = y)\\<close> |\n  \\<open>acompsem x y Lt = (x < y)\\<close>\n\nprimrec psem (infix \\<open>\\<^bold>\\<Turnstile>\\<close> 101) where\n  \\<open>psem i (Neg p) = (\\<not>psem i p)\\<close> |\n  \\<open>psem i (Con p q) = (psem i p \\<and> psem i q)\\<close> |\n  \\<open>psem i (Uni x p) = (\\<forall> v. psem (i(x := v)) p)\\<close> |\n  \\<open>psem i (A a c b) = acompsem (asem i a) (asem i b) c\\<close>\n\nterm \\<open>i \\<^bold>\\<Turnstile> N 3 \\<^bold>> V x\\<close>\n\nlemma eqlsem[simp]: \\<open>psem i (a \\<^bold>= b) = (asem i a = asem i b)\\<close> unfolding Eql_def by simp\nlemma ltnsem[simp]: \\<open>psem i (a \\<^bold>< b) = (asem i a < asem i b)\\<close> unfolding Ltn_def by simp\nlemma dissem[simp]: \\<open>psem i (a \\<^bold>\\<or> b) = (psem i a \\<or> psem i b)\\<close> unfolding Dis_def by simp\nlemma impsem[simp]: \\<open>psem i (a \\<^bold>\\<longrightarrow> b) = (psem i a \\<longrightarrow> psem i b)\\<close> unfolding Imp_def by simp\nlemma trusem[simp]: \\<open>psem i \\<^bold>\\<top>\\<close> unfolding Tru_def Eql_def by simp\nlemma flssem[simp]: \\<open>\\<not>psem i \\<^bold>\\<bottom>\\<close> unfolding Fls_def by simp\nlemma leqsem[simp]: \\<open>psem i (a \\<^bold>\\<le> b) = (asem i a \\<le> asem i b)\\<close> unfolding Leq_def by force\nlemma gtnsem[simp]: \\<open>psem i (a \\<^bold>> b) = (asem i a > asem i b)\\<close> unfolding Gtn_def by force\nlemma geqsem[simp]: \\<open>psem i (a \\<^bold>\\<ge> b) = (asem i a \\<ge> asem i b)\\<close> unfolding Geq_def by force\nlemma exisem[simp]: \\<open>psem i (\\<^bold>\\<exists> x. p) = (\\<exists> v. psem (i(x := v)) p)\\<close> unfolding Exi_def by force\n\n\nsection \\<open>free variables and substitution\\<close>\n\nprimrec aexp_fv where\n  \\<open>aexp_fv (N v) = {}\\<close> |\n  \\<open>aexp_fv (V y) = {y}\\<close> |\n  \\<open>aexp_fv (Op b p c) = aexp_fv b \\<union> aexp_fv c\\<close>\n\nlemma aexp_fv_finite: \\<open>finite (aexp_fv a)\\<close>\n  by (induct a) auto\n\nprimrec pexp_fv where\n  \\<open>pexp_fv (Neg p) = pexp_fv p\\<close> |\n  \\<open>pexp_fv (Con p q) = pexp_fv p \\<union> pexp_fv q\\<close> |\n  \\<open>pexp_fv (Uni y p) = pexp_fv p - {y}\\<close> |\n  \\<open>pexp_fv (A b p c) = aexp_fv b \\<union> aexp_fv c\\<close>\n\nlemma exi_fv[simp]: \\<open>pexp_fv (\\<^bold>\\<exists> v. p) = pexp_fv p - {v}\\<close> unfolding Exi_def by auto\nlemma dis_fv[simp]: \\<open>pexp_fv (a \\<^bold>\\<or> b) = (pexp_fv a \\<union> pexp_fv b)\\<close> unfolding Dis_def by auto\nlemma imp_fv[simp]: \\<open>pexp_fv (a \\<^bold>\\<longrightarrow> b) = (pexp_fv a \\<union> pexp_fv b)\\<close> unfolding Imp_def by auto\nlemma tru_fv[simp]: \\<open>pexp_fv \\<^bold>\\<top> = {}\\<close> unfolding Tru_def Eql_def by simp\nlemma fls_fv[simp]: \\<open>pexp_fv \\<^bold>\\<bottom> = {}\\<close> unfolding Fls_def by simp\n\nlemma pexp_fv_finite: \\<open>finite (pexp_fv b)\\<close>\n  using aexp_fv_finite by (induct b) auto\n\ndefinition \\<open>fresh ss \\<equiv> SOME s. s \\<notin> ss\\<close>\n\nlemma fresh_finite: \\<open>finite (s :: string set) \\<Longrightarrow> fresh s \\<notin> s\\<close>\n  unfolding fresh_def by (metis ex_new_if_finite infinite_UNIV_listI tfl_some)\n\nlemma fresh_fv: \\<open>fresh (aexp_fv a) \\<notin> aexp_fv a\\<close> \\<open>fresh (pexp_fv b) \\<notin> pexp_fv b\\<close>\n  using fresh_finite by (simp_all add: aexp_fv_finite pexp_fv_finite)\n\nprimrec asubst where\n  \\<open>asubst x a (N v) = N v\\<close> |\n  \\<open>asubst x a (V y) = (if x = y then a else V y)\\<close> |\n  \\<open>asubst x a (Op b p c) = Op (asubst x a b) p (asubst x a c)\\<close>\n\nlemma addsubst[simp]: \\<open>asubst x a (v \\<^bold>+ w) = (asubst x a v \\<^bold>+ asubst x a w)\\<close> unfolding Add_def by simp\nlemma supsubst[simp]: \\<open>asubst x a (v \\<^bold>- w) = (asubst x a v \\<^bold>- asubst x a w)\\<close> unfolding Sub_def by simp\nlemma mulsubst[simp]: \\<open>asubst x a (v \\<^bold>* w) = (asubst x a v \\<^bold>* asubst x a w)\\<close> unfolding Mul_def by simp\nlemma dovsubst[simp]: \\<open>asubst x a (v \\<^bold>: w) = (asubst x a v \\<^bold>: asubst x a w)\\<close> unfolding Div_def by simp\n\nlemma asubst_iff_asem: \\<open>asem i (asubst x a b) = asem (i(x := asem i a)) b\\<close>\n  by (induct b) auto\n\nprimrec pexp_size where\n  \\<open>pexp_size (Neg p) = (1 :: nat) + pexp_size p\\<close> |\n  \\<open>pexp_size (Con p q) = 1 + pexp_size p + pexp_size q\\<close> |\n  \\<open>pexp_size (Uni v p) = 1 + pexp_size p\\<close> |\n  \\<open>pexp_size (A v c w) = 1\\<close>\n\nfunction (domintros) psubst where\n  \\<open>psubst x a (Neg p) = \\<^bold>\\<not>psubst x a p\\<close> |\n  \\<open>psubst x a (Con p q) = psubst x a p \\<^bold>\\<and> psubst x a q\\<close> |\n  \\<open>psubst x a (Uni y p) = (\n    if x = y \n    then Uni y p \n    else (\n      if y \\<in> aexp_fv a \n      then (let y' = fresh (x \\<^bold>\\<rightarrow> aexp_fv a \\<union> pexp_fv p) in Uni y' (psubst x a (psubst y (V y') p)))\n      else Uni y (psubst x a p)))\\<close> |\n  \\<open>psubst x a (A v c w) = A (asubst x a v) c (asubst x a w)\\<close>\n  by pat_completeness auto\ntermination \nproof (relation \\<open>measure (\\<lambda> (_,_,p). pexp_size p)\\<close>,clarify)\n  fix x :: string \n  fix a :: aexp\n  fix y p xa\n  assume \\<open>psubst_dom (y, V xa, p)\\<close>\n  then have \\<open>pexp_size p = pexp_size (psubst y (V xa) p)\\<close> \n  proof (induction p)\n    case (3 x a y p)\n    then show ?case \n      by (metis (full_types) pexp_size.simps(3) psubst.psimps(3))\n  qed (auto simp add: psubst.psimps)\n  then show \\<open>((x, a, psubst y (V xa) p), x, a, \\<^bold>\\<forall> y. p) \\<in> measure (\\<lambda> (_,_,p). pexp_size p)\\<close> \n    using in_measure by auto\nqed auto\n\nlemma psubst_preserves_pexp_size: \\<open>pexp_size p = pexp_size (psubst x a p)\\<close>\nproof (induct p rule: psubst.induct)\n  case (3 x a y p)\n  then show ?case \n    by (metis pexp_size.simps(3) psubst.simps(3))\nqed (auto simp add: psubst.psimps)\n\nlemma pexp_size_gt_0: \\<open>pexp_size p > 0\\<close>\n  by (induct p) auto\n\nlemma ltnsubst[simp]: \\<open>psubst x a (v \\<^bold>< w) = (asubst x a v \\<^bold>< asubst x a w)\\<close> unfolding Ltn_def by simp\nlemma eqlsubst[simp]: \\<open>psubst x a (v \\<^bold>= w) = (asubst x a v \\<^bold>= asubst x a w)\\<close> unfolding Eql_def by simp\nlemma dissubst[simp]: \\<open>psubst x a (v \\<^bold>\\<or> w) = (psubst x a v \\<^bold>\\<or> psubst x a w)\\<close>\n  unfolding Dis_def by simp\nlemma impsubst[simp]: \\<open>psubst x a (v \\<^bold>\\<longrightarrow> w) = (psubst x a v \\<^bold>\\<longrightarrow> psubst x a w)\\<close>\n  unfolding Imp_def by simp\nlemma trusubst[simp]: \\<open>psubst x a \\<^bold>\\<top> = \\<^bold>\\<top>\\<close> unfolding Tru_def by simp\nlemma flssubst[simp]: \\<open>psubst x a \\<^bold>\\<bottom> = \\<^bold>\\<bottom>\\<close> unfolding Fls_def by simp\nlemma exisubst[simp]: \\<open>psubst x a (\\<^bold>\\<exists> y. p) = (\n  if x = y \n    then Exi y p \n    else (\n      if y \\<in> aexp_fv a \n      then (let y' = fresh (x \\<^bold>\\<rightarrow> aexp_fv a \\<union> pexp_fv p) in Exi y' (psubst x a (psubst y (V y') p)))\n      else Exi y (psubst x a p)))\\<close> \n  unfolding Exi_def by (metis pexp_fv.simps(1) psubst.simps(1) psubst.simps(3))\nlemma leqsubst[simp]: \\<open>psubst x a (v \\<^bold>\\<le> w) = (asubst x a v \\<^bold>\\<le> asubst x a w)\\<close> unfolding Leq_def by simp\nlemma gtnsubst[simp]: \\<open>psubst x a (v \\<^bold>> w) = (asubst x a v \\<^bold>> asubst x a w)\\<close> unfolding Gtn_def by simp\nlemma geqsubst[simp]: \\<open>psubst x a (v \\<^bold>\\<ge> w) = (asubst x a v \\<^bold>\\<ge> asubst x a w)\\<close> unfolding Geq_def by simp\n\n\nlemma agreeing_i_aexp: \\<open>y \\<notin> aexp_fv a \\<Longrightarrow> asem i a = asem (i(y := j)) a\\<close>\n  by (induct a) auto\n\nlemma agreeing_i_pexp: \\<open>y \\<notin> pexp_fv p \\<Longrightarrow> psem i p = psem (i(y := j)) p\\<close>\nproof (induct p arbitrary: i)\n  case (Uni x p)\n  then show ?case \n  proof (cases \\<open>x = y\\<close>)\n    case True\n    then show ?thesis \n      by (metis psem.simps(3) fun_upd_upd)\n  next\n    case False\n    then show ?thesis \n      using Uni by (metis pexp_fv.simps(3) psem.simps(3) fun_upd_twist member_remove remove_def)\n  qed\nnext\n  case (A x1a x2 x3)\n  then show ?case \n    using agreeing_i_aexp by (metis UnI1 UnI2 pexp_fv.simps(4) psem.simps(4))\nqed auto\n\nlemma psubst_iff_psem: \\<open>psem i (psubst x a p) = psem (i(x := asem i a)) p\\<close>\nproof (induct \\<open>pexp_size p\\<close> arbitrary: i x a p rule: less_induct)\n  case less\n  then show ?case \n  proof (cases p)\n    case (Uni y p)\n    then show ?thesis \n    proof (cases \\<open>x = y\\<close>)\n      case True\n      then have \\<open>psem i (psubst x a (\\<^bold>\\<forall> x. p)) = psem (i(x := asem i a)) (\\<^bold>\\<forall> y. p)\\<close> \n        by simp\n      then show ?thesis \n        using True Uni by blast\n    next\n      case False\n      then have *:\\<open>x \\<noteq> y\\<close> .\n      show ?thesis\n      proof (cases \\<open>y \\<in> aexp_fv a\\<close>)\n        case True\n        let ?y = \\<open>fresh (x \\<^bold>\\<rightarrow> aexp_fv a \\<union> pexp_fv p)\\<close>\n        have \\<open>x \\<noteq> ?y\\<close>\n          using fresh_finite \n          by (metis Un_upper1 aexp_fv_finite pexp_fv_finite finite.insertI finite_UnI insertI1 \n              subset_iff)\n        have \\<open>y \\<noteq> ?y\\<close>\n          using True fresh_finite \n          by (metis UnCI aexp_fv_finite pexp_fv_finite finite.simps finite_Un insertI2)\n        have \\<open>?y \\<notin> pexp_fv p\\<close>\n          using fresh_finite by (meson UnI2 aexp_fv_finite pexp_fv_finite finite.insertI finite_UnI)\n        have \\<open>?y \\<notin> aexp_fv a\\<close> \n          using fresh_finite \n          by (meson UnCI aexp_fv_finite pexp_fv_finite finite_UnI finite_insert insertCI)\n        then have 1: \\<open>\\<forall> v. asem (i(?y := v)) a = asem i a\\<close>\n          using agreeing_i_aexp by simp\n        from True * have \\<open>psubst x a (\\<^bold>\\<forall> y. p) = \\<^bold>\\<forall> ?y. psubst x a (psubst y (V ?y) p)\\<close>\n          by (meson psubst.simps(3))\n        then have \\<open>psem i (psubst x a (\\<^bold>\\<forall> y. p)) = psem i (\\<^bold>\\<forall> ?y. psubst x a (psubst y (V ?y) p))\\<close>\n          by simp\n        moreover have \\<open>... = (\\<forall> v. psem (i(?y := v)) (psubst x a (psubst y (V ?y) p)))\\<close> \n          by simp\n        moreover have \\<open>... = (\\<forall> v. psem ((i(?y := v))(x := asem i a)) (psubst y (V ?y) p))\\<close>\n          using Uni less psubst_preserves_pexp_size 1 by simp\n        moreover have \\<open>... = (\\<forall> v. psem (((i(?y := v))(x := asem i a))(y := v)) p)\\<close>\n          using \\<open>x \\<noteq> ?y\\<close> Uni * less by simp\n        moreover have \\<open>... = (\\<forall> v. psem (((i(x := asem i a))(y := v))(?y := v)) p)\\<close>\n          using \\<open>x \\<noteq> ?y\\<close> \\<open>y \\<noteq> ?y\\<close> \\<open>x \\<noteq> y\\<close> by (simp add: fun_upd_twist)\n        moreover have \\<open>... = (\\<forall> v. psem ((i(x := asem i a))(y := v)) p)\\<close>\n          using \\<open>?y \\<notin> pexp_fv p\\<close> agreeing_i_pexp by simp\n        moreover have \\<open>... = psem (i(x := asem i a)) (\\<^bold>\\<forall> y. p)\\<close>\n          by simp\n        ultimately show ?thesis \n          using Uni by presburger\n      next\n        case False\n        then have \\<open>psem i (psubst x a (\\<^bold>\\<forall> y. p)) = psem i (\\<^bold>\\<forall> y. psubst x a p)\\<close>\n          using * by simp\n        moreover have \\<open>... = (\\<forall> j. psem (i(y := j)) (psubst x a p))\\<close>\n          by simp\n        moreover have \\<open>... = (\\<forall> j. psem ((i(y := j))(x := asem (i(y := j)) a)) p)\\<close>\n          using Uni less psubst_preserves_pexp_size by simp\n        moreover have \\<open>... = (\\<forall> j. psem ((i(y := j))(x := asem i a)) p)\\<close>\n          using False agreeing_i_aexp by simp\n        moreover have \\<open>... = (\\<forall> j. psem ((i(x := asem i a))(y := j)) p)\\<close>\n          using * by (simp add: fun_upd_twist)\n        moreover have \\<open>... = psem (i(x := asem i a)) (\\<^bold>\\<forall> y. p)\\<close>\n          by simp\n        ultimately show ?thesis \n          using Uni by blast\n      qed\n    qed\n  next\n    case (A x41 x42 x43)\n    from asubst_iff_asem this show ?thesis\n      by (metis psem.simps(4) psubst.simps(4))\n  qed auto\nqed\n\nlemma no_new_fv_asubst: \\<open>aexp_fv (asubst x a' a) \\<subseteq> aexp_fv a' \\<union> aexp_fv a\\<close>\n  by (induct a) auto\nlemma no_new_fv_psubst: \\<open>pexp_fv (psubst x a p) \\<subseteq> aexp_fv a \\<union> pexp_fv p\\<close>\nproof (induct p rule: psubst.induct)\n  case (3 x a y p)\n  then show ?case \n  proof (cases \\<open>x = y\\<close>)\n    case True\n    then show ?thesis \n      using 3 by auto\n  next\n    case False\n    then have \\<open>x \\<noteq> y\\<close> .\n    show ?thesis \n    proof (cases \\<open>y \\<in> aexp_fv a\\<close>)\n      case True\n      let ?xa = \\<open>fresh (x \\<^bold>\\<rightarrow> aexp_fv a \\<union> pexp_fv p)\\<close>\n      from True have \\<open>pexp_fv (psubst x a (psubst y (V ?xa) p)) \\<subseteq> insert ?xa (aexp_fv a \\<union> pexp_fv p)\\<close>\n        using 3 \\<open>x \\<noteq> y\\<close> by auto\n      moreover have \\<open>psubst x a (\\<^bold>\\<forall> y. p) = \\<^bold>\\<forall> ?xa. psubst x a (psubst y (V ?xa) p)\\<close> \n        using \\<open>x \\<noteq> y\\<close> True by (meson psubst.simps(3))\n      ultimately show ?thesis \n        using Diff_empty True by auto\n    next\n      case False\n      then show ?thesis \n        using 3 \\<open>x \\<noteq> y\\<close> by auto\n    qed\n  qed\nnext\n  case (4 x a v c w)\n  then show ?case \n    using no_new_fv_asubst by auto\nqed auto\n\nlemma pexp_size_leq_1: \\<open>pexp_size b \\<ge> 1\\<close>\n  by (induct b) auto\n\n\nlemma elem_asubst_fv: \n  \\<open>x \\<in> aexp_fv a \\<Longrightarrow> aexp_fv (asubst x b a) = (aexp_fv a - {x}) \\<union> aexp_fv b\\<close> \n  \\<open>x \\<notin> aexp_fv a \\<Longrightarrow> aexp_fv (asubst x b a) = aexp_fv a\\<close>\n  by (induct a) auto\n\nlemma elem_psubst_fv: \n  \\<open>x \\<in> pexp_fv p \\<Longrightarrow> pexp_fv (psubst x a p) = (pexp_fv p - {x}) \\<union> aexp_fv a\\<close> \n  \\<open>x \\<notin> pexp_fv p \\<Longrightarrow> pexp_fv (psubst x a p) = pexp_fv p\\<close>\nproof (induct x a p rule: psubst.induct)\n  case (3 x a y p)\n  let ?a1 = \\<open>x \\<in> pexp_fv (\\<^bold>\\<forall> y. p)\\<close>\n  let ?a2 = \\<open>x \\<notin> pexp_fv (\\<^bold>\\<forall> y. p)\\<close>\n  let ?g1 = \\<open>pexp_fv (psubst x a (\\<^bold>\\<forall> y. p)) = pexp_fv (\\<^bold>\\<forall> y. p) - {x} \\<union> aexp_fv a\\<close>\n  let ?g2 = \\<open>pexp_fv (psubst x a (\\<^bold>\\<forall> y. p)) = pexp_fv (\\<^bold>\\<forall> y. p)\\<close>\n  consider \n    \\<open>x = y\\<close> | \n    \\<open>x \\<noteq> y \\<and> y \\<notin> aexp_fv a\\<close> | \n    \\<open>x \\<noteq> y \\<and> y \\<in> aexp_fv a \\<and> y \\<in> pexp_fv p\\<close> | \n    \\<open>x \\<noteq> y \\<and> y \\<in> aexp_fv a \\<and> y \\<notin> pexp_fv p\\<close> by auto\n  then have \\<open>(?a1 \\<longrightarrow> ?g1) \\<and> (?a2 \\<longrightarrow> ?g2)\\<close> \n  proof (cases; rule conjI; clarify)\n    assume *: \\<open>x \\<noteq> y\\<close> \\<open>y \\<in> aexp_fv a\\<close> \n    let ?f = \\<open>fresh (x \\<^bold>\\<rightarrow> aexp_fv a \\<union> pexp_fv p)\\<close>\n    have sub_p_def: \\<open>psubst x a (\\<^bold>\\<forall> y. p) = \\<^bold>\\<forall> ?f. psubst x a (psubst y (V ?f) p)\\<close>\n      using * by (meson psubst.simps(3))\n    have f1: \\<open>?f \\<notin> aexp_fv a\\<close>\n      using fresh_finite by (meson UnI1 aexp_fv_finite pexp_fv_finite finite.insertI finite_UnI insertI2)\n    have f2: \\<open>?f \\<notin> pexp_fv p\\<close>\n      using fresh_finite by (metis UnCI aexp_fv_finite pexp_fv_finite finite_Un finite_insert)\n    have f3: \\<open>x \\<noteq> ?f\\<close> \n      using fresh_finite by (metis UnCI aexp_fv_finite pexp_fv_finite finite_Un finite_insert insertCI)\n    {\n      assume \\<open>y \\<in> pexp_fv p\\<close>\n      with 3 * have **: \\<open>pexp_fv (psubst y (V ?f) p) = pexp_fv p - {y} \\<union> {?f}\\<close> by force\n      {\n        assume ?a1\n        with 3 * ** sub_p_def have \\<open>pexp_fv (psubst x a (\\<^bold>\\<forall> y. p)) = ((pexp_fv p - {y} \\<union> {?f}) - {x} \\<union> aexp_fv a) - {?f}\\<close>\n          by auto\n        with f1 f2 have \\<open>pexp_fv (psubst x a (\\<^bold>\\<forall> y. p)) = (pexp_fv p - {x} \\<union> aexp_fv a)\\<close>\n          using * by force\n        then show ?g1 \n          by fastforce\n      next\n        assume a: ?a2\n        with f3 have \\<open>pexp_fv (psubst x a (psubst y (V ?f) p)) = pexp_fv p - {y} \\<union> {?f}\\<close>\n          using 3(4) * ** by force\n        with sub_p_def f2 fresh_finite *(2) f1 show ?g2 \n          by auto\n      }\n    next\n      assume \\<open>y \\<notin> pexp_fv p\\<close>\n      with 3 * have **: \\<open>pexp_fv (psubst y (V ?f) p) = pexp_fv p\\<close> by metis\n      {\n        assume ?a1\n        with 3 * sub_p_def ** f1 f2 *(2) show ?g1 \n          by auto\n      next\n        assume ?a2\n        with f2 f3 3(4) * ** \\<open>y \\<notin> pexp_fv p\\<close> sub_p_def show ?g2 \n          by auto\n      }\n    }\n  qed (use 3 in auto)\n  then show \\<open>?a1 \\<Longrightarrow> ?g1\\<close> \\<open>?a2 \\<Longrightarrow> ?g2\\<close> \n    by auto\nnext\n  case (4 x a v c w)\n  {\n    case 1\n    then consider \n      \\<open>x \\<in> aexp_fv v \\<and> x \\<in> aexp_fv w\\<close> | \n      \\<open>x \\<in> aexp_fv v \\<and> x \\<notin> aexp_fv w\\<close> | \n      \\<open>x \\<notin> aexp_fv v \\<and> x \\<in> aexp_fv w\\<close> by auto\n    then show ?case \n      using elem_asubst_fv by cases auto\n  next\n    case 2\n    then show ?case \n      using elem_asubst_fv by simp\n  }\nqed auto\n\nlemma subset_psubst_fv: \\<open>pexp_fv p \\<subseteq> pexp_fv q \\<Longrightarrow> pexp_fv (psubst x a p) \\<subseteq> pexp_fv (psubst x a q)\\<close>\n  using elem_psubst_fv by (metis dis_fv dissubst sup.absorb_iff1)\n\n\nend", "meta": {"author": "Barrikad", "repo": "ghost-code-program-verification", "sha": "master", "save_path": "github-repos/isabelle/Barrikad-ghost-code-program-verification", "path": "github-repos/isabelle/Barrikad-ghost-code-program-verification/ghost-code-program-verification-main/pexp.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240721511739, "lm_q2_score": 0.8289388040954683, "lm_q1q2_score": 0.7172178076436052}}
{"text": "(*   Title: HOL/ex/Ballot.thy\n     Author: Lukas Bulwahn <lukas.bulwahn-at-gmail.com>\n     Author: Johannes H\u00f6lzl <hoelzl@in.tum.de>\n*)\n\nsection \\<open>Bertrand's Ballot Theorem\\<close>\n\ntheory Ballot\nimports\n  Complex_Main\n  \"HOL-Library.FuncSet\"\nbegin\n\nsubsection \\<open>Preliminaries\\<close>\n\nlemma card_bij':\n  assumes \"f \\<in> A \\<rightarrow> B\" \"\\<And>x. x \\<in> A \\<Longrightarrow> g (f x) = x\"\n    and \"g \\<in> B \\<rightarrow> A\" \"\\<And>x. x \\<in> B \\<Longrightarrow> f (g x) = x\"\n  shows \"card A = card B\"\n  apply (rule bij_betw_same_card)\n  apply (rule bij_betwI)\n  apply fact+\n  done\n\nsubsection \\<open>Formalization of Problem Statement\\<close>\n\nsubsubsection \\<open>Basic Definitions\\<close>\n\ndatatype vote = A | B\n\ndefinition\n  \"all_countings a b = card {f \\<in> {1 .. a + b} \\<rightarrow>\\<^sub>E {A, B}.\n      card {x \\<in> {1 .. a + b}. f x = A} = a \\<and> card {x \\<in> {1 .. a + b}. f x = B} = b}\"\n\ndefinition\n  \"valid_countings a b =\n    card {f\\<in>{1..a+b} \\<rightarrow>\\<^sub>E {A, B}.\n      card {x\\<in>{1..a+b}. f x = A} = a \\<and> card {x\\<in>{1..a+b}. f x = B} = b \\<and>\n      (\\<forall>m\\<in>{1..a+b}. card {x\\<in>{1..m}. f x = A} > card {x\\<in>{1..m}. f x = B})}\"\n\nsubsubsection \\<open>Equivalence with Set Cardinality\\<close>\n\nlemma Collect_on_transfer:\n  assumes \"rel_set R X Y\"\n  shows \"rel_fun (rel_fun R (=)) (rel_set R) (\\<lambda>P. {x\\<in>X. P x}) (\\<lambda>P. {y\\<in>Y. P y})\"\n  using assms unfolding rel_fun_def rel_set_def by fast\n\nlemma rel_fun_trans:\n  \"rel_fun P Q g g' \\<Longrightarrow> rel_fun R P f f' \\<Longrightarrow> rel_fun R Q (\\<lambda>x. g (f x)) (\\<lambda>y. g' (f' y))\"\n  by (auto simp: rel_fun_def)\n\nlemma rel_fun_trans2:\n  \"rel_fun P1 (rel_fun P2 Q) g g' \\<Longrightarrow> rel_fun R P1 f1 f1' \\<Longrightarrow> rel_fun R P2 f2 f2' \\<Longrightarrow>\n    rel_fun R Q (\\<lambda>x. g (f1 x) (f2 x)) (\\<lambda>y. g' (f1' y) (f2' y))\"\n  by (auto simp: rel_fun_def) \n\nlemma rel_fun_trans2':\n  \"rel_fun R (=) f1 f1' \\<Longrightarrow> rel_fun R (=) f2 f2' \\<Longrightarrow>\n    rel_fun R (=) (\\<lambda>x. g (f1 x) (f2 x)) (\\<lambda>y. g (f1' y) (f2' y))\"\n  by (auto simp: rel_fun_def)\n\nlemma rel_fun_const: \"rel_fun R (=) (\\<lambda>x. a) (\\<lambda>y. a)\"\n  by auto\n\nlemma rel_fun_conj:\n  \"rel_fun R (=) f f' \\<Longrightarrow> rel_fun R (=) g g' \\<Longrightarrow> rel_fun R (=) (\\<lambda>x. f x \\<and> g x) (\\<lambda>y. f' y \\<and> g' y)\"\n  by (auto simp: rel_fun_def)\n\nlemma rel_fun_ball:\n  \"(\\<And>i. i \\<in> I \\<Longrightarrow> rel_fun R (=) (f i) (f' i)) \\<Longrightarrow> rel_fun R (=) (\\<lambda>x. \\<forall>i\\<in>I. f i x) (\\<lambda>y. \\<forall>i\\<in>I. f' i y)\"\n  by (auto simp: rel_fun_def rel_set_def)\n\nlemma\n  shows all_countings_set: \"all_countings a b = card {V\\<in>Pow {0..<a+b}. card V = a}\"\n      (is \"_ = card ?A\")\n    and valid_countings_set: \"valid_countings a b =\n      card {V\\<in>Pow {0..<a+b}. card V = a \\<and> (\\<forall>m\\<in>{1..a+b}. card ({0..<m} \\<inter> V) > m - card ({0..<m} \\<inter> V))}\"\n      (is \"_ = card ?V\")\nproof -\n  define P where \"P j i \\<longleftrightarrow> i < a + b \\<and> j = Suc i\" for j i\n  have unique_P: \"bi_unique P\" and total_P: \"\\<And>m. m \\<le> a + b \\<Longrightarrow> rel_set P {1..m} {0..<m}\"\n    by (auto simp add: bi_unique_def rel_set_def P_def Suc_le_eq gr0_conv_Suc)\n  have rel_fun_P: \"\\<And>R f g. (\\<And>i. i < a+b \\<Longrightarrow> R (f  (Suc i)) (g i)) \\<Longrightarrow> rel_fun P R f g\"\n    by (simp add: rel_fun_def P_def)\n    \n  define R where \"R f V \\<longleftrightarrow>\n    V \\<subseteq> {0..<a+b} \\<and> f \\<in> extensional {1..a+b} \\<and> (\\<forall>i<a+b. i \\<in> V \\<longleftrightarrow> f (Suc i) = A)\" for f V\n  { fix f g :: \"nat \\<Rightarrow> vote\" assume \"f \\<in> extensional {1..a + b}\" \"g \\<in> extensional {1..a + b}\" \n    moreover assume \"\\<forall>i<a + b. (f (Suc i) = A) = (g (Suc i) = A)\"\n    then have \"\\<forall>i<a + b. f (Suc i) = g (Suc i)\"\n      by (metis vote.nchotomy)\n    ultimately have \"f i = g i\" for i\n      by (cases \"i \\<in> {1..a+b}\") (auto simp: extensional_def Suc_le_eq gr0_conv_Suc) }\n  then have unique_R: \"bi_unique R\"\n    by (auto simp: bi_unique_def R_def)\n\n  have \"f \\<in> extensional {1..a + b} \\<Longrightarrow> \\<exists>V\\<in>Pow {0..<a + b}. R f V\" for f\n    by (intro bexI[of _ \"{i. i < a+b \\<and> f (Suc i) = A}\"]) (auto simp add: R_def PiE_def)\n  moreover have \"V \\<in> Pow {0..<a + b} \\<Longrightarrow> \\<exists>f\\<in>extensional {1..a+b}. R f V\" for V\n    by (intro bexI[of _ \"\\<lambda>i\\<in>{1..a+b}. if i - 1 \\<in> V then A else B\"]) (auto simp add: R_def PiE_def)\n  ultimately have total_R: \"rel_set R (extensional {1..a+b}) (Pow {0..<a+b})\"\n    by (auto simp: rel_set_def)\n\n  have P: \"rel_fun R (rel_fun P (=)) (\\<lambda>f x. f x = A) (\\<lambda>V y. y \\<in> V)\"\n    by (auto simp: P_def R_def Suc_le_eq gr0_conv_Suc rel_fun_def)\n\n  have eq_B: \"x = B \\<longleftrightarrow> x \\<noteq> A\" for x\n    by (cases x; simp)\n\n  { fix f and m :: nat\n    have \"card {x\\<in>{1..m}. f x = B} = card ({1..m} - {x\\<in>{1..m}. f x = A})\"\n      by (simp add: eq_B set_diff_eq cong: conj_cong)\n    also have \"\\<dots> = m - card {x\\<in>{1..m}. f x = A}\"\n      by (subst card_Diff_subset) auto\n    finally have \"card {x\\<in>{1..m}. f x = B} = m - card {x\\<in>{1..m}. f x = A}\" . }\n  note card_B = this\n\n  note transfers = rel_fun_const card_transfer[THEN rel_funD, OF unique_R] rel_fun_conj rel_fun_ball\n    Collect_on_transfer[THEN rel_funD, OF total_R] Collect_on_transfer[THEN rel_funD, OF total_P]\n    rel_fun_trans[OF card_transfer, OF unique_P] rel_fun_trans[OF Collect_on_transfer[OF total_P]]\n    rel_fun_trans2'[where g=\"(=)\"] rel_fun_trans2'[where g=\"(<)\"] rel_fun_trans2'[where g=\"(-)\"]\n\n  have \"all_countings a b = card {f \\<in> extensional {1..a + b}. card {x \\<in> {1..a + b}. f x = A} = a}\"\n    using card_B by (simp add: all_countings_def PiE_iff vote.nchotomy cong: conj_cong)\n  also have \"\\<dots> = card {V\\<in>Pow {0..<a+b}. card ({x\\<in>{0 ..< a + b}. x \\<in> V}) = a}\"\n    by (intro P order_refl transfers)\n  finally show \"all_countings a b = card ?A\"\n    unfolding Int_def[symmetric] by (simp add: Int_absorb1 cong: conj_cong)\n\n  have \"valid_countings a b = card {f\\<in>extensional {1..a+b}.\n      card {x\\<in>{1..a+b}. f x = A} = a \\<and> (\\<forall>m\\<in>{1..a+b}. card {x\\<in>{1..m}. f x = A} > m - card {x\\<in>{1..m}. f x = A})}\"\n    using card_B by (simp add: valid_countings_def PiE_iff vote.nchotomy cong: conj_cong)\n  also have \"\\<dots> = card {V\\<in>Pow {0..<a+b}. card {x\\<in>{0..<a+b}. x\\<in>V} = a \\<and>\n    (\\<forall>m\\<in>{1..a+b}. card {x\\<in>{0..<m}. x\\<in>V} > m - card {x\\<in>{0..<m}. x\\<in>V})}\"\n    by (intro P order_refl transfers) auto\n  finally show \"valid_countings a b = card ?V\"\n    unfolding Int_def[symmetric] by (simp add: Int_absorb1 cong: conj_cong)\nqed\n\nlemma all_countings: \"all_countings a b = (a + b) choose a\"\n  unfolding all_countings_set by (simp add: n_subsets)\n\nsubsection \\<open>Facts About \\<^term>\\<open>valid_countings\\<close>\\<close>\n\nsubsubsection \\<open>Non-Recursive Cases\\<close>\n\nlemma card_V_eq_a: \"V \\<subseteq> {0..<a} \\<Longrightarrow> card V = a \\<longleftrightarrow> V = {0..<a}\"\n  using card_subset_eq[of \"{0..<a}\" V] by auto\n\nlemma valid_countings_a_0: \"valid_countings a 0 = 1\"\n  by (simp add: valid_countings_set card_V_eq_a cong: conj_cong)\n\nlemma valid_countings_eq_zero:\n  \"a \\<le> b \\<Longrightarrow> 0 < b \\<Longrightarrow> valid_countings a b = 0\"\n  by (auto simp add: valid_countings_set Int_absorb1 intro!: bexI[of _ \"a + b\"])\n\nlemma Ico_subset_finite: \"i \\<subseteq> {a ..< b::nat} \\<Longrightarrow> finite i\"\n  by (auto dest: finite_subset)\n\nlemma Icc_Suc2: \"a \\<le> b \\<Longrightarrow> {a..Suc b} = insert (Suc b) {a..b}\"\n  by auto\n\nlemma Ico_Suc2: \"a \\<le> b \\<Longrightarrow> {a..<Suc b} = insert b {a..<b}\"\n  by auto\n\nlemma valid_countings_Suc_Suc:\n  assumes \"b < a\"\n  shows \"valid_countings (Suc a) (Suc b) = valid_countings a (Suc b) + valid_countings (Suc a) b\"\nproof -\n  let ?l = \"Suc (a + b)\"\n  let ?Q = \"\\<lambda>V c. \\<forall>m\\<in>{1..c}. m - card ({0..<m} \\<inter> V) < card ({0..<m} \\<inter> V)\"\n  let ?V = \"\\<lambda>P. {V. (V \\<in> Pow {0..<Suc ?l} \\<and> P V) \\<and> card V = Suc a \\<and> ?Q V (Suc ?l)}\"\n  have \"valid_countings (Suc a) (Suc b) = card (?V (\\<lambda>V. ?l \\<notin> V)) + card (?V (\\<lambda>V. ?l \\<in> V))\"\n    unfolding valid_countings_set\n    by (subst card_Un_disjoint[symmetric]) (auto simp add: set_eq_iff intro!: arg_cong[where f=card])\n  also have \"card (?V (\\<lambda>V. ?l \\<in> V)) = valid_countings a (Suc b)\"\n    unfolding valid_countings_set\n  proof (rule card_bij'[where f=\"\\<lambda>V. V - {?l}\" and g=\"insert ?l\"])\n    have *: \"\\<And>m V. m \\<in> {1..a + Suc b} \\<Longrightarrow> {0..<m} \\<inter> (V - {?l}) = {0..<m} \\<inter> V\"\n      by auto\n    show \"(\\<lambda>V. V - {?l}) \\<in> ?V (\\<lambda>V. ?l \\<in> V) \\<rightarrow> {V \\<in> Pow {0..<a + Suc b}. card V = a \\<and> ?Q V (a + Suc b)}\"\n      by (auto simp: Ico_subset_finite *)\n    { fix V assume V: \"V \\<subseteq> {0..<?l}\"\n      then have \"finite V\" \"?l \\<notin> V\" \"{0..<Suc ?l} \\<inter> V = V\"\n        by (auto dest: finite_subset)\n      with V have \"card (insert ?l V) = Suc (card V)\"\n        \"card ({0..<m} \\<inter> insert ?l V) = (if m = Suc ?l then Suc (card V) else card ({0..<m} \\<inter> V))\"\n        if \"m \\<le> Suc ?l\" for m\n        using that by auto }\n    then show \"insert ?l \\<in> {V \\<in> Pow {0..<a + Suc b}. card V = a \\<and> ?Q V (a + Suc b)} \\<rightarrow> ?V (\\<lambda>V. ?l \\<in> V)\"\n      using \\<open>b < a\\<close> by auto\n  qed auto\n  also have \"card (?V (\\<lambda>V. ?l \\<notin> V)) = valid_countings (Suc a) b\"\n    unfolding valid_countings_set\n  proof (intro arg_cong[where f=\"\\<lambda>P. card {x. P x}\"] ext conj_cong)\n    fix V assume \"V \\<in> Pow {0..<Suc a + b}\" and [simp]: \"card V = Suc a\"\n    then have [simp]: \"V \\<subseteq> {0..<Suc ?l}\"\n      by auto\n    show \"?Q V (Suc ?l) = ?Q V (Suc a + b)\"\n      using \\<open>b<a\\<close> by (simp add: Int_absorb1 Icc_Suc2)\n  qed (auto simp: subset_eq less_Suc_eq)\n  finally show ?thesis\n    by simp\nqed\n\nlemma valid_countings:\n  \"(a + b) * valid_countings a b = (a - b) * ((a + b) choose a)\"\nproof (induct a arbitrary: b)\n  case 0 show ?case\n    by (cases b) (simp_all add: valid_countings_eq_zero)\nnext\n  case (Suc a) note Suc_a = this\n  show ?case\n  proof (induct b)\n    case (Suc b) note Suc_b = this\n    show ?case\n    proof cases\n      assume \"a \\<le> b\" then show ?thesis\n        by (simp add: valid_countings_eq_zero)\n    next\n      assume \"\\<not> a \\<le> b\"\n      then have \"b < a\" by simp\n\n      have \"Suc a * (a - Suc b) + (Suc a - b) * Suc b =\n        (Suc a * a - Suc a * Suc b) + (Suc a * Suc b - Suc b * b)\"\n        by (simp add: algebra_simps)\n      also have \"\\<dots> = (Suc a * a + (Suc a * Suc b - Suc b * b)) - Suc a * Suc b\"\n        using \\<open>b<a\\<close> by (intro add_diff_assoc2 mult_mono) auto\n      also have \"\\<dots> = (Suc a * a + Suc a * Suc b) - Suc b * b - Suc a * Suc b\"\n        using \\<open>b<a\\<close> by (intro arg_cong2[where f=\"(-)\"] add_diff_assoc mult_mono) auto\n      also have \"\\<dots> = (Suc a * Suc (a + b)) - (Suc b * Suc (a + b))\"\n        by (simp add: algebra_simps)\n      finally have rearrange: \"Suc a * (a - Suc b) + (Suc a - b) * Suc b = (Suc a - Suc b) * Suc (a + b)\"\n        unfolding diff_mult_distrib by simp\n\n      have \"(Suc a * Suc (a + b)) * ((Suc a + Suc b) * valid_countings (Suc a) (Suc b)) =\n        (Suc a + Suc b) * Suc a * ((a + Suc b) * valid_countings a (Suc b) + (Suc a + b) * valid_countings (Suc a) b)\"\n        unfolding valid_countings_Suc_Suc[OF \\<open>b < a\\<close>] by (simp add: field_simps)\n      also have \"... = (Suc a + Suc b) * ((a - Suc b) * (Suc a * (Suc (a + b) choose a)) +\n        (Suc a - b) * (Suc a * (Suc (a + b) choose Suc a)))\"\n        unfolding Suc_a Suc_b by (simp add: field_simps)\n      also have \"... = (Suc a * (a - Suc b) + (Suc a - b) * Suc b) * (Suc (Suc a + b) * (Suc a + b choose a))\"\n        unfolding Suc_times_binomial_add by (simp add: field_simps)\n      also have \"... = Suc a * (Suc a * (a - Suc b) + (Suc a - b) * Suc b) * (Suc a + Suc b choose Suc a)\"\n        unfolding Suc_times_binomial_eq by (simp add: field_simps)\n      also have \"... = (Suc a * Suc (a + b)) * ((Suc a - Suc b) * (Suc a + Suc b choose Suc a))\"\n        unfolding rearrange by (simp only: mult_ac)\n      finally show ?thesis\n        unfolding mult_cancel1 by simp\n    qed\n  qed (simp add: valid_countings_a_0)\nqed\n\nlemma valid_countings_eq[code]:\n  \"valid_countings a b = (if a + b = 0 then 1 else ((a - b) * ((a + b) choose a)) div (a + b))\"\n  by (simp add: valid_countings[symmetric] valid_countings_a_0)\n\nsubsection \\<open>Relation Between \\<^term>\\<open>valid_countings\\<close> and \\<^term>\\<open>all_countings\\<close>\\<close>\n\nlemma main_nat: \"(a + b) * valid_countings a b = (a - b) * all_countings a b\"\n  unfolding valid_countings all_countings ..\n\nlemma main_real:\n  assumes \"b < a\"\n  shows \"valid_countings a b = (a - b) / (a + b) * all_countings a b\"\nusing assms\nproof -\n  from main_nat[of a b] \\<open>b < a\\<close> have\n    \"(real a + real b) * real (valid_countings a b) = (real a - real b) * real (all_countings a b)\"\n    by (simp only: of_nat_add[symmetric] of_nat_mult[symmetric]) auto\n  from this \\<open>b < a\\<close> show ?thesis\n    by (subst mult_left_cancel[of \"real a + real b\", symmetric]) auto\nqed\n\nlemma\n  \"valid_countings a b = (if a \\<le> b then (if b = 0 then 1 else 0) else (a - b) / (a + b) * all_countings a b)\"\nproof (cases \"a \\<le> b\")\n  case False\n    from this show ?thesis by (simp add: main_real)\nnext\n  case True\n    from this show ?thesis\n      by (auto simp add: valid_countings_a_0 all_countings valid_countings_eq_zero)\nqed\n\nsubsubsection \\<open>Executable Definition\\<close>\n\ndeclare all_countings_def [code del]\ndeclare all_countings[code]\n\nvalue \"all_countings 1 0\"\nvalue \"all_countings 0 1\"\nvalue \"all_countings 1 1\"\nvalue \"all_countings 2 1\"\nvalue \"all_countings 1 2\"\nvalue \"all_countings 2 4\"\nvalue \"all_countings 4 2\"\n\nsubsubsection \\<open>Executable Definition\\<close>\n\ndeclare valid_countings_def [code del]\n\nvalue \"valid_countings 1 0\"\nvalue \"valid_countings 0 1\"\nvalue \"valid_countings 1 1\"\nvalue \"valid_countings 2 1\"\nvalue \"valid_countings 1 2\"\nvalue \"valid_countings 2 4\"\nvalue \"valid_countings 4 2\"\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/Ballot.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8289387998695209, "lm_q2_score": 0.8652240686758841, "lm_q1q2_score": 0.7172178011064113}}
{"text": "(*  Title:      HOL/Proofs/Extraction/Util.thy\n    Author:     Stefan Berghofer, TU Muenchen\n*)\n\nsection \\<open>Auxiliary lemmas used in program extraction examples\\<close>\n\ntheory Util\nimports MainRLT\nbegin\n\ntext \\<open>Decidability of equality on natural numbers.\\<close>\n\nlemma nat_eq_dec: \"\\<And>n::nat. m = n \\<or> m \\<noteq> n\"\n  apply (induct m)\n  apply (case_tac n)\n  apply (case_tac [3] n)\n  apply (simp only: nat.simps, iprover?)+\n  done\n\ntext \\<open>\n  Well-founded induction on natural numbers, derived using the standard\n  structural induction rule.\n\\<close>\n\nlemma nat_wf_ind:\n  assumes R: \"\\<And>x::nat. (\\<And>y. y < x \\<Longrightarrow> P y) \\<Longrightarrow> P x\"\n  shows \"P z\"\nproof (rule R)\n  show \"\\<And>y. y < z \\<Longrightarrow> P y\"\n  proof (induct z)\n    case 0\n    then show ?case by simp\n  next\n    case (Suc n y)\n    from nat_eq_dec show ?case\n    proof\n      assume ny: \"n = y\"\n      have \"P n\"\n        by (rule R) (rule Suc)\n      with ny show ?case by simp\n    next\n      assume \"n \\<noteq> y\"\n      with Suc have \"y < n\" by simp\n      then show ?case by (rule Suc)\n    qed\n  qed\nqed\n\ntext \\<open>Bounded search for a natural number satisfying a decidable predicate.\\<close>\n\nlemma search:\n  assumes dec: \"\\<And>x::nat. P x \\<or> \\<not> P x\"\n  shows \"(\\<exists>x<y. P x) \\<or> \\<not> (\\<exists>x<y. P x)\"\nproof (induct y)\n  case 0\n  show ?case by simp\nnext\n  case (Suc z)\n  then show ?case\n  proof\n    assume \"\\<exists>x<z. P x\"\n    then obtain x where le: \"x < z\" and P: \"P x\" by iprover\n    from le have \"x < Suc z\" by simp\n    with P show ?case by iprover\n  next\n    assume nex: \"\\<not> (\\<exists>x<z. P x)\"\n    from dec show ?case\n    proof\n      assume P: \"P z\"\n      have \"z < Suc z\" by simp\n      with P show ?thesis by iprover\n    next\n      assume nP: \"\\<not> P z\"\n      have \"\\<not> (\\<exists>x<Suc z. P x)\"\n      proof\n        assume \"\\<exists>x<Suc z. P x\"\n        then obtain x where le: \"x < Suc z\" and P: \"P x\" by iprover\n        have \"x < z\"\n        proof (cases \"x = z\")\n          case True\n          with nP and P show ?thesis by simp\n        next\n          case False\n          with le show ?thesis by simp\n        qed\n        with P have \"\\<exists>x<z. P x\" by iprover\n        with nex show False ..\n      qed\n      then show ?case by iprover\n    qed\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/Proofs/Extraction/Util.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256631249076, "lm_q2_score": 0.8519528038477825, "lm_q1q2_score": 0.7171957340502838}}
{"text": "section {* Predicate Calculus Laws *}\n\ntheory utp_pred_laws\n  imports utp_pred\nbegin\n  \nsubsection {* Propositional Logic *}\n  \ntext {* Showing that predicates form a Boolean Algebra (under the predicate operators as opposed to\n  the lattice operators) gives us many useful laws. *}\n\ninterpretation boolean_algebra diff_upred not_upred conj_upred \"op \\<le>\" \"op <\"\n  disj_upred false_upred true_upred\n  by (unfold_locales; pred_auto)\n\nlemma taut_true [simp]: \"`true`\"\n  by (pred_auto)\n\nlemma taut_false [simp]: \"`false` = False\"\n  by (pred_auto)\n\nlemma upred_eval_taut:\n  \"`P\\<lbrakk>\\<guillemotleft>b\\<guillemotright>/&\\<Sigma>\\<rbrakk>` = \\<lbrakk>P\\<rbrakk>\\<^sub>eb\"\n  by (pred_auto)\n    \nlemma refBy_order: \"P \\<sqsubseteq> Q = `Q \\<Rightarrow> P`\"\n  by (pred_auto)\n\nlemma conj_idem [simp]: \"((P::'\\<alpha> upred) \\<and> P) = P\"\n  by (pred_auto)\n\nlemma disj_idem [simp]: \"((P::'\\<alpha> upred) \\<or> P) = P\"\n  by (pred_auto)\n\nlemma conj_comm: \"((P::'\\<alpha> upred) \\<and> Q) = (Q \\<and> P)\"\n  by (pred_auto)\n\nlemma disj_comm: \"((P::'\\<alpha> upred) \\<or> Q) = (Q \\<or> P)\"\n  by (pred_auto)\n\nlemma conj_subst: \"P = R \\<Longrightarrow> ((P::'\\<alpha> upred) \\<and> Q) = (R \\<and> Q)\"\n  by (pred_auto)\n\n\n\nlemma conj_assoc:\"(((P::'\\<alpha> upred) \\<and> Q) \\<and> S) = (P \\<and> (Q \\<and> S))\"\n  by (pred_auto)\n\nlemma disj_assoc:\"(((P::'\\<alpha> upred) \\<or> Q) \\<or> S) = (P \\<or> (Q \\<or> S))\"\n  by (pred_auto)\n\nlemma conj_disj_abs:\"((P::'\\<alpha> upred) \\<and> (P \\<or> Q)) = P\"\n  by (pred_auto)\n\nlemma disj_conj_abs:\"((P::'\\<alpha> upred) \\<or> (P \\<and> Q)) = P\"\n  by (pred_auto)\n\nlemma conj_disj_distr:\"((P::'\\<alpha> upred) \\<and> (Q \\<or> R)) = ((P \\<and> Q) \\<or> (P \\<and> R))\"\n  by (pred_auto)\n\nlemma disj_conj_distr:\"((P::'\\<alpha> upred) \\<or> (Q \\<and> R)) = ((P \\<or> Q) \\<and> (P \\<or> R))\"\n  by (pred_auto)\n\nlemma true_disj_zero [simp]:\n  \"(P \\<or> true) = true\" \"(true \\<or> P) = true\"\n  by (pred_auto)+\n\nlemma true_conj_zero [simp]:\n  \"(P \\<and> false) = false\" \"(false \\<and> P) = false\"\n  by (pred_auto)+\n\nlemma imp_vacuous [simp]: \"(false \\<Rightarrow> u) = true\"\n  by (pred_auto)\n\nlemma imp_true [simp]: \"(p \\<Rightarrow> true) = true\"\n  by (pred_auto)\n\nlemma true_imp [simp]: \"(true \\<Rightarrow> p) = p\"\n  by (pred_auto)\n\nlemma impl_mp1 [simp]: \"(P \\<and> (P \\<Rightarrow> Q)) = (P \\<and> Q)\"\n  by (pred_auto)\n\nlemma impl_mp2 [simp]: \"((P \\<Rightarrow> Q) \\<and> P) = (Q \\<and> P)\"\n  by (pred_auto)\n\nlemma impl_adjoin: \"((P \\<Rightarrow> Q) \\<and> R) = ((P \\<and> R \\<Rightarrow> Q \\<and> R) \\<and> R)\"\n  by (pred_auto)\n\nlemma impl_refine_intro:\n  \"\\<lbrakk> Q\\<^sub>1 \\<sqsubseteq> P\\<^sub>1; P\\<^sub>2 \\<sqsubseteq> (P\\<^sub>1 \\<and> Q\\<^sub>2) \\<rbrakk> \\<Longrightarrow> (P\\<^sub>1 \\<Rightarrow> P\\<^sub>2) \\<sqsubseteq> (Q\\<^sub>1 \\<Rightarrow> Q\\<^sub>2)\"\n  by (pred_auto)\n\nlemma spec_refine:\n  \"Q \\<sqsubseteq> (P \\<and> R) \\<Longrightarrow> (P \\<Rightarrow> Q) \\<sqsubseteq> R\"\n  by (rel_auto)\n    \nlemma impl_disjI: \"\\<lbrakk> `P \\<Rightarrow> R`; `Q \\<Rightarrow> R` \\<rbrakk> \\<Longrightarrow> `(P \\<or> Q) \\<Rightarrow> R`\"\n  by (rel_auto)\n\nlemma conditional_iff:\n  \"(P \\<Rightarrow> Q) = (P \\<Rightarrow> R) \\<longleftrightarrow> `P \\<Rightarrow> (Q \\<Leftrightarrow> R)`\"\n  by (pred_auto)\n\nlemma p_and_not_p [simp]: \"(P \\<and> \\<not> P) = false\"\n  by (pred_auto)\n\nlemma p_or_not_p [simp]: \"(P \\<or> \\<not> P) = true\"\n  by (pred_auto)\n\nlemma p_imp_p [simp]: \"(P \\<Rightarrow> P) = true\"\n  by (pred_auto)\n\nlemma p_iff_p [simp]: \"(P \\<Leftrightarrow> P) = true\"\n  by (pred_auto)\n\nlemma p_imp_false [simp]: \"(P \\<Rightarrow> false) = (\\<not> P)\"\n  by (pred_auto)\n\nlemma not_conj_deMorgans [simp]: \"(\\<not> ((P::'\\<alpha> upred) \\<and> Q)) = ((\\<not> P) \\<or> (\\<not> Q))\"\n  by (pred_auto)\n\nlemma not_disj_deMorgans [simp]: \"(\\<not> ((P::'\\<alpha> upred) \\<or> Q)) = ((\\<not> P) \\<and> (\\<not> Q))\"\n  by (pred_auto)\n\nlemma conj_disj_not_abs [simp]: \"((P::'\\<alpha> upred) \\<and> ((\\<not>P) \\<or> Q)) = (P \\<and> Q)\"\n  by (pred_auto)\n\nlemma subsumption1:\n  \"`P \\<Rightarrow> Q` \\<Longrightarrow> (P \\<or> Q) = Q\"\n  by (pred_auto)\n\nlemma subsumption2:\n  \"`Q \\<Rightarrow> P` \\<Longrightarrow> (P \\<or> Q) = P\"\n  by (pred_auto)\n\nlemma neg_conj_cancel1: \"(\\<not> P \\<and> (P \\<or> Q)) = (\\<not> P \\<and> Q :: '\\<alpha> upred)\"\n  by (pred_auto)\n\nlemma neg_conj_cancel2: \"(\\<not> Q \\<and> (P \\<or> Q)) = (\\<not> Q \\<and> P :: '\\<alpha> upred)\"\n  by (pred_auto)\n\nlemma double_negation [simp]: \"(\\<not> \\<not> (P::'\\<alpha> upred)) = P\"\n  by (pred_auto)\n\nlemma true_not_false [simp]: \"true \\<noteq> false\" \"false \\<noteq> true\"\n  by (pred_auto)+\n\nlemma closure_conj_distr: \"([P]\\<^sub>u \\<and> [Q]\\<^sub>u) = [P \\<and> Q]\\<^sub>u\"\n  by (pred_auto)\n\nlemma closure_imp_distr: \"`[P \\<Rightarrow> Q]\\<^sub>u \\<Rightarrow> [P]\\<^sub>u \\<Rightarrow> [Q]\\<^sub>u`\"\n  by (pred_auto)\n\nlemma true_iff [simp]: \"(P \\<Leftrightarrow> true) = P\"\n  by (pred_auto)\n\nlemma taut_iff_eq:\n  \"`P \\<Leftrightarrow> Q` \\<longleftrightarrow> (P = Q)\"\n  by (pred_auto)\n    \nlemma impl_alt_def: \"(P \\<Rightarrow> Q) = (\\<not> P \\<or> Q)\"\n  by (pred_auto)\n    \nsubsection {* Lattice laws *}\n    \nlemma uinf_or:\n  fixes P Q :: \"'\\<alpha> upred\"\n  shows \"(P \\<sqinter> Q) = (P \\<or> Q)\"\n  by (pred_auto)\n\nlemma usup_and:\n  fixes P Q :: \"'\\<alpha> upred\"\n  shows \"(P \\<squnion> Q) = (P \\<and> Q)\"\n  by (pred_auto)\n\nlemma UINF_alt_def:\n  \"(\\<Sqinter> i | A(i) \\<bullet> P(i)) = (\\<Sqinter> i \\<bullet> A(i) \\<and> P(i))\"\n  by (rel_auto)\n    \nlemma USUP_true [simp]: \"(\\<Squnion> P | F(P) \\<bullet> true) = true\"\n  by (pred_auto)\n\nlemma UINF_mem_UNIV [simp]: \"(\\<Sqinter> x\\<in>UNIV \\<bullet> P(x)) = (\\<Sqinter> x \\<bullet> P(x))\"\n  by (pred_auto)\n\nlemma USUP_mem_UNIV [simp]: \"(\\<Squnion> x\\<in>UNIV \\<bullet> P(x)) = (\\<Squnion> x \\<bullet> P(x))\"\n  by (pred_auto)\n\nlemma USUP_false [simp]: \"(\\<Squnion> i \\<bullet> false) = false\"\n  by (pred_simp)\n\nlemma UINF_true [simp]: \"(\\<Sqinter> i \\<bullet> true) = true\"\n  by (pred_simp)\n\nlemma UINF_mem_true [simp]: \"A \\<noteq> {} \\<Longrightarrow> (\\<Sqinter> i\\<in>A \\<bullet> true) = true\"\n  by (pred_auto)\n\nlemma UINF_false [simp]: \"(\\<Sqinter> i | P(i) \\<bullet> false) = false\"\n  by (pred_auto)\n\nlemma UINF_cong_eq:\n  \"\\<lbrakk> \\<And> x. P\\<^sub>1(x) = P\\<^sub>2(x); \\<And> x. `P\\<^sub>1(x) \\<Rightarrow> Q\\<^sub>1(x) =\\<^sub>u Q\\<^sub>2(x)` \\<rbrakk> \\<Longrightarrow>\n        (\\<Sqinter> x | P\\<^sub>1(x) \\<bullet> Q\\<^sub>1(x)) = (\\<Sqinter> x | P\\<^sub>2(x) \\<bullet> Q\\<^sub>2(x))\"\n by (unfold UINF_def, pred_simp, metis)\n\nlemma UINF_as_Sup: \"(\\<Sqinter> P \\<in> \\<P> \\<bullet> P) = \\<Sqinter> \\<P>\"\n  apply (simp add: upred_defs bop.rep_eq lit.rep_eq Sup_uexpr_def)\n  apply (pred_simp)\n  apply (rule cong[of \"Sup\"])\n  apply (auto)\ndone\n\nlemma UINF_as_Sup_collect: \"(\\<Sqinter>P\\<in>A \\<bullet> f(P)) = (\\<Sqinter>P\\<in>A. f(P))\"\n  apply (simp add: upred_defs bop.rep_eq lit.rep_eq Sup_uexpr_def)\n  apply (pred_simp)\n  apply (simp add: Setcompr_eq_image)\ndone\n\nlemma UINF_as_Sup_collect': \"(\\<Sqinter>P \\<bullet> f(P)) = (\\<Sqinter>P. f(P))\"\n  apply (simp add: upred_defs bop.rep_eq lit.rep_eq Sup_uexpr_def)\n  apply (pred_simp)\n  apply (simp add: full_SetCompr_eq)\ndone\n\nlemma UINF_as_Sup_image: \"(\\<Sqinter> P | \\<guillemotleft>P\\<guillemotright> \\<in>\\<^sub>u \\<guillemotleft>A\\<guillemotright> \\<bullet> f(P)) = \\<Sqinter> (f ` A)\"\n  apply (simp add: upred_defs bop.rep_eq lit.rep_eq Sup_uexpr_def)\n  apply (pred_simp)\n  apply (rule cong[of \"Sup\"])\n  apply (auto)\ndone\n\nlemma USUP_as_Inf: \"(\\<Squnion> P \\<in> \\<P> \\<bullet> P) = \\<Squnion> \\<P>\"\n  apply (simp add: upred_defs bop.rep_eq lit.rep_eq Inf_uexpr_def)\n  apply (pred_simp)\n  apply (rule cong[of \"Inf\"])\n  apply (auto)\ndone\n\nlemma USUP_as_Inf_collect: \"(\\<Squnion>P\\<in>A \\<bullet> f(P)) = (\\<Squnion>P\\<in>A. f(P))\"\n  apply (simp add: upred_defs bop.rep_eq lit.rep_eq Sup_uexpr_def)\n  apply (pred_simp)\n  apply (simp add: Setcompr_eq_image)\ndone\n\nlemma USUP_as_Inf_collect': \"(\\<Squnion>P \\<bullet> f(P)) = (\\<Squnion>P. f(P))\"\n  apply (simp add: upred_defs bop.rep_eq lit.rep_eq Sup_uexpr_def)\n  apply (pred_simp)\n  apply (simp add: full_SetCompr_eq)\ndone\n\nlemma USUP_as_Inf_image: \"(\\<Squnion> P \\<in> \\<P> \\<bullet> f(P)) = \\<Squnion> (f ` \\<P>)\"\n  apply (simp add: upred_defs bop.rep_eq lit.rep_eq Inf_uexpr_def)\n  apply (pred_simp)\n  apply (rule cong[of \"Inf\"])\n  apply (auto)\ndone\n\nlemma USUP_image_eq [simp]: \"USUP (\\<lambda>i. \\<guillemotleft>i\\<guillemotright> \\<in>\\<^sub>u \\<guillemotleft>f ` A\\<guillemotright>) g = (\\<Squnion> i\\<in>A \\<bullet> g(f(i)))\"\n  by (pred_simp, rule_tac cong[of Inf Inf], auto)\n\nlemma UINF_image_eq [simp]: \"UINF (\\<lambda>i. \\<guillemotleft>i\\<guillemotright> \\<in>\\<^sub>u \\<guillemotleft>f ` A\\<guillemotright>) g = (\\<Sqinter> i\\<in>A \\<bullet> g(f(i)))\"\n  by (pred_simp, rule_tac cong[of Sup Sup], auto)\n\nlemma subst_continuous [usubst]: \"\\<sigma> \\<dagger> (\\<Sqinter> A) = (\\<Sqinter> {\\<sigma> \\<dagger> P | P. P \\<in> A})\"\n  by (simp add: UINF_as_Sup[THEN sym] usubst setcompr_eq_image)\n\nlemma not_UINF: \"(\\<not> (\\<Sqinter> i\\<in>A\\<bullet> P(i))) = (\\<Squnion> i\\<in>A\\<bullet> \\<not> P(i))\"\n  by (pred_auto)\n\nlemma not_USUP: \"(\\<not> (\\<Squnion> i\\<in>A\\<bullet> P(i))) = (\\<Sqinter> i\\<in>A\\<bullet> \\<not> P(i))\"\n  by (pred_auto)\n\nlemma UINF_empty [simp]: \"(\\<Sqinter> i \\<in> {} \\<bullet> P(i)) = false\"\n  by (pred_auto)\n\nlemma UINF_insert [simp]: \"(\\<Sqinter> i\\<in>insert x xs \\<bullet> P(i)) = (P(x) \\<sqinter> (\\<Sqinter> i\\<in>xs \\<bullet> P(i)))\"\n  apply (pred_simp)\n  apply (subst Sup_insert[THEN sym])\n  apply (rule_tac cong[of Sup Sup])\n  apply (auto)\ndone\n\nlemma USUP_empty [simp]: \"(\\<Squnion> i \\<in> {} \\<bullet> P(i)) = true\"\n  by (pred_auto)\n\nlemma USUP_insert [simp]: \"(\\<Squnion> i\\<in>insert x xs \\<bullet> P(i)) = (P(x) \\<squnion> (\\<Squnion> i\\<in>xs \\<bullet> P(i)))\"\n  apply (pred_simp)\n  apply (subst Inf_insert[THEN sym])\n  apply (rule_tac cong[of Inf Inf])\n  apply (auto)\ndone\n\nlemma conj_UINF_dist:\n  \"(P \\<and> (\\<Sqinter> Q\\<in>S \\<bullet> F(Q))) = (\\<Sqinter> Q\\<in>S \\<bullet> P \\<and> F(Q))\"\n  by (simp add: upred_defs bop.rep_eq lit.rep_eq, pred_auto)\n\nlemma disj_UINF_dist:\n  \"S \\<noteq> {} \\<Longrightarrow> (P \\<or> (\\<Sqinter> Q\\<in>S \\<bullet> F(Q))) = (\\<Sqinter> Q\\<in>S \\<bullet> P \\<or> F(Q))\"\n  by (simp add: upred_defs bop.rep_eq lit.rep_eq, pred_auto)\n\nlemma conj_USUP_dist:\n  \"S \\<noteq> {} \\<Longrightarrow> (P \\<and> (\\<Squnion> Q\\<in>S \\<bullet> F(Q))) = (\\<Squnion> Q\\<in>S \\<bullet> P \\<and> F(Q))\"\n  by (subst uexpr_eq_iff, auto simp add: conj_upred_def USUP.rep_eq inf_uexpr.rep_eq bop.rep_eq lit.rep_eq)\n\nlemma USUP_conj_USUP: \"((\\<Squnion> P \\<in> A \\<bullet> F(P)) \\<and> (\\<Squnion> P \\<in> A \\<bullet> G(P))) = (\\<Squnion> P \\<in> A \\<bullet> F(P) \\<and> G(P))\"\n  by (simp add: upred_defs bop.rep_eq lit.rep_eq, pred_auto)\n\nlemma UINF_all_cong:\n  assumes \"\\<And> P. F(P) = G(P)\"\n  shows \"(\\<Sqinter> P \\<bullet> F(P)) = (\\<Sqinter> P \\<bullet> G(P))\"\n  by (simp add: UINF_as_Sup_collect assms)\n\nlemma UINF_cong:\n  assumes \"\\<And> P. P \\<in> A \\<Longrightarrow> F(P) = G(P)\"\n  shows \"(\\<Sqinter> P\\<in>A \\<bullet> F(P)) = (\\<Sqinter> P\\<in>A \\<bullet> G(P))\"\n  by (simp add: UINF_as_Sup_collect assms)\n\nlemma USUP_all_cong:\n  assumes \"\\<And> P. F(P) = G(P)\"\n  shows \"(\\<Squnion> P \\<bullet> F(P)) = (\\<Squnion> P \\<bullet> G(P))\"\n  by (simp add: assms)\n    \nlemma USUP_cong:\n  assumes \"\\<And> P. P \\<in> A \\<Longrightarrow> F(P) = G(P)\"\n  shows \"(\\<Squnion> P\\<in>A \\<bullet> F(P)) = (\\<Squnion> P\\<in>A \\<bullet> G(P))\"\n  by (simp add: USUP_as_Inf_collect assms)\n\nlemma UINF_subset_mono: \"A \\<subseteq> B \\<Longrightarrow> (\\<Sqinter> P\\<in>B \\<bullet> F(P)) \\<sqsubseteq> (\\<Sqinter> P\\<in>A \\<bullet> F(P))\"\n  by (simp add: SUP_subset_mono UINF_as_Sup_collect)\n\nlemma USUP_subset_mono: \"A \\<subseteq> B \\<Longrightarrow> (\\<Squnion> P\\<in>A \\<bullet> F(P)) \\<sqsubseteq> (\\<Squnion> P\\<in>B \\<bullet> F(P))\"\n  by (simp add: INF_superset_mono USUP_as_Inf_collect)\n\nlemma UINF_impl: \"(\\<Sqinter> P\\<in>A \\<bullet> F(P) \\<Rightarrow> G(P)) = ((\\<Squnion> P\\<in>A \\<bullet> F(P)) \\<Rightarrow> (\\<Sqinter> P\\<in>A \\<bullet> G(P)))\"\n  by (pred_auto)\n\nlemma UINF_all_nats [simp]:\n  fixes P :: \"nat \\<Rightarrow> '\\<alpha> upred\"\n  shows \"(\\<Sqinter> n \\<bullet> \\<Sqinter> i\\<in>{0..n} \\<bullet> P(i)) = (\\<Sqinter> i\\<in>{0..} \\<bullet> P(i))\"\n  by (pred_auto)\n\nlemma UINF_refines':\n  assumes \"\\<And> i. P \\<sqsubseteq> Q(i)\" \n  shows \"P \\<sqsubseteq> (\\<Sqinter> i \\<bullet> Q(i))\"\n  using assms\n  apply (rel_auto) using Sup_le_iff by fastforce\n    \nsubsection {* Equality laws *}\n\nlemma eq_upred_refl [simp]: \"(x =\\<^sub>u x) = true\"\n  by (pred_auto)\n\nlemma eq_upred_sym: \"(x =\\<^sub>u y) = (y =\\<^sub>u x)\"\n  by (pred_auto)\n\nlemma eq_cong_left:\n  assumes \"vwb_lens x\" \"$x \\<sharp> Q\" \"$x\\<acute> \\<sharp> Q\" \"$x \\<sharp> R\" \"$x\\<acute> \\<sharp> R\"\n  shows \"(($x\\<acute> =\\<^sub>u $x \\<and> Q) = ($x\\<acute> =\\<^sub>u $x \\<and> R)) \\<longleftrightarrow> (Q = R)\"\n  using assms\n  by (pred_simp, (meson mwb_lens_def vwb_lens_mwb weak_lens_def)+)\n\nlemma conj_eq_in_var_subst:\n  fixes x :: \"('a \\<Longrightarrow> '\\<alpha>)\"\n  assumes \"vwb_lens x\"\n  shows \"(P \\<and> $x =\\<^sub>u v) = (P\\<lbrakk>v/$x\\<rbrakk> \\<and> $x =\\<^sub>u v)\"\n  using assms\n  by (pred_simp, (metis vwb_lens_wb wb_lens.get_put)+)\n\nlemma conj_eq_out_var_subst:\n  fixes x :: \"('a \\<Longrightarrow> '\\<alpha>)\"\n  assumes \"vwb_lens x\"\n  shows \"(P \\<and> $x\\<acute> =\\<^sub>u v) = (P\\<lbrakk>v/$x\\<acute>\\<rbrakk> \\<and> $x\\<acute> =\\<^sub>u v)\"\n  using assms\n  by (pred_simp, (metis vwb_lens_wb wb_lens.get_put)+)\n\nlemma conj_pos_var_subst:\n  assumes \"vwb_lens x\"\n  shows \"($x \\<and> Q) = ($x \\<and> Q\\<lbrakk>true/$x\\<rbrakk>)\"\n  using assms\n  by (pred_auto, metis (full_types) vwb_lens_wb wb_lens.get_put, metis (full_types) vwb_lens_wb wb_lens.get_put)\n\nlemma conj_neg_var_subst:\n  assumes \"vwb_lens x\"\n  shows \"(\\<not> $x \\<and> Q) = (\\<not> $x \\<and> Q\\<lbrakk>false/$x\\<rbrakk>)\"\n  using assms\n  by (pred_auto, metis (full_types) vwb_lens_wb wb_lens.get_put, metis (full_types) vwb_lens_wb wb_lens.get_put)\n\nlemma upred_eq_true [simp]: \"(p =\\<^sub>u true) = p\"\n  by (pred_auto)\n\nlemma upred_eq_false [simp]: \"(p =\\<^sub>u false) = (\\<not> p)\"\n  by (pred_auto)\n\nlemma upred_true_eq [simp]: \"(true =\\<^sub>u p) = p\"\n  by (pred_auto)\n\nlemma upred_false_eq [simp]: \"(false =\\<^sub>u p) = (\\<not> p)\"\n  by (pred_auto)\n\nlemma conj_var_subst:\n  assumes \"vwb_lens x\"\n  shows \"(P \\<and> var x =\\<^sub>u v) = (P\\<lbrakk>v/x\\<rbrakk> \\<and> var x =\\<^sub>u v)\"\n  using assms\n  by (pred_simp, (metis (full_types) vwb_lens_def wb_lens.get_put)+)\n\nsubsection {* HOL Variable Quantifiers *}\n    \nlemma shEx_unbound [simp]: \"(\\<^bold>\\<exists> x \\<bullet> P) = P\"\n  by (pred_auto)\n\nlemma shEx_bool [simp]: \"shEx P = (P True \\<or> P False)\"\n  by (pred_simp, metis (full_types))\n\nlemma shEx_commute: \"(\\<^bold>\\<exists> x \\<bullet> \\<^bold>\\<exists> y \\<bullet> P x y) = (\\<^bold>\\<exists> y \\<bullet> \\<^bold>\\<exists> x \\<bullet> P x y)\"\n  by (pred_auto)\n\nlemma shEx_cong: \"\\<lbrakk> \\<And> x. P x = Q x \\<rbrakk> \\<Longrightarrow> shEx P = shEx Q\"\n  by (pred_auto)\n\nlemma shAll_unbound [simp]: \"(\\<^bold>\\<forall> x \\<bullet> P) = P\"\n  by (pred_auto)\n\nlemma shAll_bool [simp]: \"shAll P = (P True \\<and> P False)\"\n  by (pred_simp, metis (full_types))\n\nlemma shAll_cong: \"\\<lbrakk> \\<And> x. P x = Q x \\<rbrakk> \\<Longrightarrow> shAll P = shAll Q\"\n  by (pred_auto)\n    \ntext {* Quantifier lifting *}\n\nnamed_theorems uquant_lift\n\nlemma shEx_lift_conj_1 [uquant_lift]:\n  \"((\\<^bold>\\<exists> x \\<bullet> P(x)) \\<and> Q) = (\\<^bold>\\<exists> x \\<bullet> P(x) \\<and> Q)\"\n  by (pred_auto)\n\nlemma shEx_lift_conj_2 [uquant_lift]:\n  \"(P \\<and> (\\<^bold>\\<exists> x \\<bullet> Q(x))) = (\\<^bold>\\<exists> x \\<bullet> P \\<and> Q(x))\"\n  by (pred_auto)\n\nsubsection {* Case Splitting *}\n  \nlemma eq_split_subst:\n  assumes \"vwb_lens x\"\n  shows \"(P = Q) \\<longleftrightarrow> (\\<forall> v. P\\<lbrakk>\\<guillemotleft>v\\<guillemotright>/x\\<rbrakk> = Q\\<lbrakk>\\<guillemotleft>v\\<guillemotright>/x\\<rbrakk>)\"\n  using assms\n  by (pred_auto, metis vwb_lens_wb wb_lens.source_stability)\n\nlemma eq_split_substI:\n  assumes \"vwb_lens x\" \"\\<And> v. P\\<lbrakk>\\<guillemotleft>v\\<guillemotright>/x\\<rbrakk> = Q\\<lbrakk>\\<guillemotleft>v\\<guillemotright>/x\\<rbrakk>\"\n  shows \"P = Q\"\n  using assms(1) assms(2) eq_split_subst by blast\n\nlemma taut_split_subst:\n  assumes \"vwb_lens x\"\n  shows \"`P` \\<longleftrightarrow> (\\<forall> v. `P\\<lbrakk>\\<guillemotleft>v\\<guillemotright>/x\\<rbrakk>`)\"\n  using assms\n  by (pred_auto, metis vwb_lens_wb wb_lens.source_stability)\n\nlemma eq_split:\n  assumes \"`P \\<Rightarrow> Q`\" \"`Q \\<Rightarrow> P`\"\n  shows \"P = Q\"\n  using assms\n  by (pred_auto)\n\n\n\nlemma subst_bool_split:\n  assumes \"vwb_lens x\"\n  shows \"`P` = `(P\\<lbrakk>false/x\\<rbrakk> \\<and> P\\<lbrakk>true/x\\<rbrakk>)`\"\nproof -\n  from assms have \"`P` = (\\<forall> v. `P\\<lbrakk>\\<guillemotleft>v\\<guillemotright>/x\\<rbrakk>`)\"\n    by (subst taut_split_subst[of x], auto)\n  also have \"... = (`P\\<lbrakk>\\<guillemotleft>True\\<guillemotright>/x\\<rbrakk>` \\<and> `P\\<lbrakk>\\<guillemotleft>False\\<guillemotright>/x\\<rbrakk>`)\"\n    by (metis (mono_tags, lifting))\n  also have \"... = `(P\\<lbrakk>false/x\\<rbrakk> \\<and> P\\<lbrakk>true/x\\<rbrakk>)`\"\n    by (pred_auto)\n  finally show ?thesis .\nqed\n\nlemma subst_eq_replace:\n  fixes x :: \"('a \\<Longrightarrow> '\\<alpha>)\"\n  shows \"(p\\<lbrakk>u/x\\<rbrakk> \\<and> u =\\<^sub>u v) = (p\\<lbrakk>v/x\\<rbrakk> \\<and> u =\\<^sub>u v)\"\n  by (pred_auto)\n\nsubsection {* UTP Quantifiers *}\n    \n\n\nlemma exists_twice: \"mwb_lens x \\<Longrightarrow> (\\<exists> x \\<bullet> \\<exists> x \\<bullet> P) = (\\<exists> x \\<bullet> P)\"\n  by (pred_auto)\n\nlemma all_twice: \"mwb_lens x \\<Longrightarrow> (\\<forall> x \\<bullet> \\<forall> x \\<bullet> P) = (\\<forall> x \\<bullet> P)\"\n  by (pred_auto)\n\nlemma exists_sub: \"\\<lbrakk> mwb_lens y; x \\<subseteq>\\<^sub>L y \\<rbrakk> \\<Longrightarrow> (\\<exists> x \\<bullet> \\<exists> y \\<bullet> P) = (\\<exists> y \\<bullet> P)\"\n  by (pred_auto)\n\nlemma all_sub: \"\\<lbrakk> mwb_lens y; x \\<subseteq>\\<^sub>L y \\<rbrakk> \\<Longrightarrow> (\\<forall> x \\<bullet> \\<forall> y \\<bullet> P) = (\\<forall> y \\<bullet> P)\"\n  by (pred_auto)\n\nlemma ex_commute:\n  assumes \"x \\<bowtie> y\"\n  shows \"(\\<exists> x \\<bullet> \\<exists> y \\<bullet> P) = (\\<exists> y \\<bullet> \\<exists> x \\<bullet> P)\"\n  using assms\n  apply (pred_auto)\n  using lens_indep_comm apply fastforce+\ndone\n\nlemma all_commute:\n  assumes \"x \\<bowtie> y\"\n  shows \"(\\<forall> x \\<bullet> \\<forall> y \\<bullet> P) = (\\<forall> y \\<bullet> \\<forall> x \\<bullet> P)\"\n  using assms\n  apply (pred_auto)\n  using lens_indep_comm apply fastforce+\ndone\n\nlemma ex_equiv:\n  assumes \"x \\<approx>\\<^sub>L y\"\n  shows \"(\\<exists> x \\<bullet> P) = (\\<exists> y \\<bullet> P)\"\n  using assms\n  by (pred_simp, metis (no_types, lifting) lens.select_convs(2))\n\nlemma all_equiv:\n  assumes \"x \\<approx>\\<^sub>L y\"\n  shows \"(\\<forall> x \\<bullet> P) = (\\<forall> y \\<bullet> P)\"\n  using assms\n  by (pred_simp, metis (no_types, lifting) lens.select_convs(2))\n\nlemma ex_zero:\n  \"(\\<exists> &\\<emptyset> \\<bullet> P) = P\"\n  by (pred_auto)\n\nlemma all_zero:\n  \"(\\<forall> &\\<emptyset> \\<bullet> P) = P\"\n  by (pred_auto)\n\nlemma ex_plus:\n  \"(\\<exists> y;x \\<bullet> P) = (\\<exists> x \\<bullet> \\<exists> y \\<bullet> P)\"\n  by (pred_auto)\n\nlemma all_plus:\n  \"(\\<forall> y;x \\<bullet> P) = (\\<forall> x \\<bullet> \\<forall> y \\<bullet> P)\"\n  by (pred_auto)\n\nlemma closure_all:\n  \"[P]\\<^sub>u = (\\<forall> &\\<Sigma> \\<bullet> P)\"\n  by (pred_auto)\n\nlemma unrest_as_exists:\n  \"vwb_lens x \\<Longrightarrow> (x \\<sharp> P) \\<longleftrightarrow> ((\\<exists> x \\<bullet> P) = P)\"\n  by (pred_simp, metis vwb_lens.put_eq)\n\nlemma ex_mono: \"P \\<sqsubseteq> Q \\<Longrightarrow> (\\<exists> x \\<bullet> P) \\<sqsubseteq> (\\<exists> x \\<bullet> Q)\"\n  by (pred_auto)\n\nlemma ex_weakens: \"wb_lens x \\<Longrightarrow> (\\<exists> x \\<bullet> P) \\<sqsubseteq> P\"\n  by (pred_simp, metis wb_lens.get_put)\n\nlemma all_mono: \"P \\<sqsubseteq> Q \\<Longrightarrow> (\\<forall> x \\<bullet> P) \\<sqsubseteq> (\\<forall> x \\<bullet> Q)\"\n  by (pred_auto)\n\nlemma all_strengthens: \"wb_lens x \\<Longrightarrow> P \\<sqsubseteq> (\\<forall> x \\<bullet> P)\"\n  by (pred_simp, metis wb_lens.get_put)\n\nlemma ex_unrest: \"x \\<sharp> P \\<Longrightarrow> (\\<exists> x \\<bullet> P) = P\"\n  by (pred_auto)\n\nlemma all_unrest: \"x \\<sharp> P \\<Longrightarrow> (\\<forall> x \\<bullet> P) = P\"\n  by (pred_auto)\n\nlemma not_ex_not: \"\\<not> (\\<exists> x \\<bullet> \\<not> P) = (\\<forall> x \\<bullet> P)\"\n  by (pred_auto)\n\n\n\nsubsection {* Variable Restriction *}    \n  \nlemma var_res_all: \n  \"P \\<restriction>\\<^sub>v &\\<Sigma> = P\"\n  by (rel_auto)\n  \nlemma var_res_twice: \n  \"mwb_lens x \\<Longrightarrow> P \\<restriction>\\<^sub>v x \\<restriction>\\<^sub>v x = P \\<restriction>\\<^sub>v x\"\n  by (pred_auto)\n    \nsubsection {* Conditional laws *}\n\nlemma cond_def:\n  \"(P \\<triangleleft> b \\<triangleright> Q) = ((b \\<and> P) \\<or> ((\\<not> b) \\<and> Q))\"\n  by (pred_auto)\n    \nlemma cond_idem:\"(P \\<triangleleft> b \\<triangleright> P) = P\" by (pred_auto)\n\nlemma cond_symm:\"(P \\<triangleleft> b \\<triangleright> Q) = (Q \\<triangleleft> \\<not> b \\<triangleright> P)\" by (pred_auto)\n\nlemma cond_assoc: \"((P \\<triangleleft> b \\<triangleright> Q) \\<triangleleft> c \\<triangleright> R) = (P \\<triangleleft> b \\<and> c \\<triangleright> (Q \\<triangleleft> c \\<triangleright> R))\" by (pred_auto)\n\n\n\nlemma cond_unit_T [simp]:\"(P \\<triangleleft> true \\<triangleright> Q) = P\" by (pred_auto)\n\nlemma cond_unit_F [simp]:\"(P \\<triangleleft> false \\<triangleright> Q) = Q\" by (pred_auto)\n\nlemma cond_conj_not: \"((P \\<triangleleft> b \\<triangleright> Q) \\<and> (\\<not> b)) = (Q \\<and> (\\<not> b))\"\n  by (rel_auto)\n    \nlemma cond_and_T_integrate:\n  \"((P \\<and> b) \\<or> (Q \\<triangleleft> b \\<triangleright> R)) = ((P \\<or> Q) \\<triangleleft> b \\<triangleright> R)\"\n  by (pred_auto)\n\nlemma cond_L6: \"(P \\<triangleleft> b \\<triangleright> (Q \\<triangleleft> b \\<triangleright> R)) = (P \\<triangleleft> b \\<triangleright> R)\" by (pred_auto)\n\nlemma cond_L7: \"(P \\<triangleleft> b \\<triangleright> (P \\<triangleleft> c \\<triangleright> Q)) = (P \\<triangleleft> b \\<or> c \\<triangleright> Q)\" by (pred_auto)\n\nlemma cond_and_distr: \"((P \\<and> Q) \\<triangleleft> b \\<triangleright> (R \\<and> S)) = ((P \\<triangleleft> b \\<triangleright> R) \\<and> (Q \\<triangleleft> b \\<triangleright> S))\" by (pred_auto)\n\n\n\nlemma cond_imp_distr:\n\"((P \\<Rightarrow> Q) \\<triangleleft> b \\<triangleright> (R \\<Rightarrow> S)) = ((P \\<triangleleft> b \\<triangleright> R) \\<Rightarrow> (Q \\<triangleleft> b \\<triangleright> S))\" by (pred_auto)\n\nlemma cond_eq_distr:\n\"((P \\<Leftrightarrow> Q) \\<triangleleft> b \\<triangleright> (R \\<Leftrightarrow> S)) = ((P \\<triangleleft> b \\<triangleright> R) \\<Leftrightarrow> (Q \\<triangleleft> b \\<triangleright> S))\" by (pred_auto)\n\nlemma cond_conj_distr:\"(P \\<and> (Q \\<triangleleft> b \\<triangleright> S)) = ((P \\<and> Q) \\<triangleleft> b \\<triangleright> (P \\<and> S))\" by (pred_auto)\n\nlemma cond_disj_distr:\"(P \\<or> (Q \\<triangleleft> b \\<triangleright> S)) = ((P \\<or> Q) \\<triangleleft> b \\<triangleright> (P \\<or> S))\" by (pred_auto)\n\nlemma cond_neg: \"\\<not> (P \\<triangleleft> b \\<triangleright> Q) = ((\\<not> P) \\<triangleleft> b \\<triangleright> (\\<not> Q))\" by (pred_auto)\n\nlemma cond_conj: \"P \\<triangleleft> b \\<and> c \\<triangleright> Q = (P \\<triangleleft> c \\<triangleright> Q) \\<triangleleft> b \\<triangleright> Q\"\n  by (pred_auto)\n\nlemma spec_cond_dist: \"(P \\<Rightarrow> (Q \\<triangleleft> b \\<triangleright> R)) = ((P \\<Rightarrow> Q) \\<triangleleft> b \\<triangleright> (P \\<Rightarrow> R))\"\n  by (pred_auto)\n\nlemma cond_USUP_dist: \"(\\<Squnion> P\\<in>S \\<bullet> F(P)) \\<triangleleft> b \\<triangleright> (\\<Squnion> P\\<in>S \\<bullet> G(P)) = (\\<Squnion> P\\<in>S \\<bullet> F(P) \\<triangleleft> b \\<triangleright> G(P))\"\n  by (pred_auto)\n\nlemma cond_UINF_dist: \"(\\<Sqinter> P\\<in>S \\<bullet> F(P)) \\<triangleleft> b \\<triangleright> (\\<Sqinter> P\\<in>S \\<bullet> G(P)) = (\\<Sqinter> P\\<in>S \\<bullet> F(P) \\<triangleleft> b \\<triangleright> G(P))\"\n  by (pred_auto)\n\nlemma cond_var_subst_left:\n  assumes \"vwb_lens x\"\n  shows \"(P\\<lbrakk>true/x\\<rbrakk> \\<triangleleft> var x \\<triangleright> Q) = (P \\<triangleleft> var x \\<triangleright> Q)\"\n  using assms by (pred_auto, metis (full_types) vwb_lens_wb wb_lens.get_put)\n\nlemma cond_var_subst_right:\n  assumes \"vwb_lens x\"\n  shows \"(P \\<triangleleft> var x \\<triangleright> Q\\<lbrakk>false/x\\<rbrakk>) = (P \\<triangleleft> var x \\<triangleright> Q)\"\n  using assms by (pred_auto, metis (full_types) vwb_lens.put_eq)\n\nlemma cond_var_split:\n  \"vwb_lens x \\<Longrightarrow> (P\\<lbrakk>true/x\\<rbrakk> \\<triangleleft> var x \\<triangleright> P\\<lbrakk>false/x\\<rbrakk>) = P\"\n  by (rel_simp, (metis (full_types) vwb_lens.put_eq)+)\n\nlemma cond_assign_subst:\n  \"vwb_lens x \\<Longrightarrow> (P \\<triangleleft> utp_expr.var x =\\<^sub>u v \\<triangleright> Q) = (P\\<lbrakk>v/x\\<rbrakk> \\<triangleleft> utp_expr.var x =\\<^sub>u v \\<triangleright> Q)\"\n  apply (rel_simp) using vwb_lens.put_eq by force\n    \nlemma conj_conds: \n  \"(P1 \\<triangleleft> b \\<triangleright> Q1 \\<and> P2 \\<triangleleft> b \\<triangleright> Q2) = (P1 \\<and> P2) \\<triangleleft> b \\<triangleright> (Q1 \\<and> Q2)\"\n  by pred_auto\n\nlemma disj_conds:\n  \"(P1 \\<triangleleft> b \\<triangleright> Q1 \\<or> P2 \\<triangleleft> b \\<triangleright> Q2) = (P1 \\<or> P2) \\<triangleleft> b \\<triangleright> (Q1 \\<or> Q2)\"\n  by pred_auto\n\nsubsection {* Additional Expression Laws *}\n\nlemma le_pred_refl [simp]:\n  fixes x :: \"('a::preorder, '\\<alpha>) uexpr\"\n  shows \"(x \\<le>\\<^sub>u x) = true\"\n  by (pred_auto)\n\nlemma uzero_le_laws [simp]:\n  \"(0 :: ('a::{linordered_semidom}, '\\<alpha>) uexpr) \\<le>\\<^sub>u numeral x = true\"\n  \"(1 :: ('a::{linordered_semidom}, '\\<alpha>) uexpr) \\<le>\\<^sub>u numeral x = true\"\n  \"(0 :: ('a::{linordered_semidom}, '\\<alpha>) uexpr) \\<le>\\<^sub>u 1 = true\"\n  by (pred_simp)+\n  \nlemma unumeral_le_1 [simp]:\n  assumes \"(numeral i :: 'a::{numeral,ord}) \\<le> numeral j\"\n  shows \"(numeral i :: ('a, '\\<alpha>) uexpr) \\<le>\\<^sub>u numeral j = true\"\n  using assms by (pred_auto)\n\nlemma unumeral_le_2 [simp]:\n  assumes \"(numeral i :: 'a::{numeral,linorder}) > numeral j\"\n  shows \"(numeral i :: ('a, '\\<alpha>) uexpr) \\<le>\\<^sub>u numeral j = false\"\n  using assms by (pred_auto)\n    \nlemma uset_laws [simp]:\n  \"x \\<in>\\<^sub>u {}\\<^sub>u = false\"\n  \"x \\<in>\\<^sub>u {m..n}\\<^sub>u = (m \\<le>\\<^sub>u x \\<and> x \\<le>\\<^sub>u n)\"\n  by (pred_auto)+\n  \nlemma pfun_entries_apply [simp]:\n  \"(entr\\<^sub>u(d,f) :: (('k, 'v) pfun, '\\<alpha>) uexpr)(i)\\<^sub>a = ((\\<guillemotleft>f\\<guillemotright>(i)\\<^sub>a) \\<triangleleft> i \\<in>\\<^sub>u d \\<triangleright> \\<bottom>\\<^sub>u)\"\n  by (pred_auto)\n    \nlemma udom_uupdate_pfun [simp]:\n  fixes m :: \"(('k, 'v) pfun, '\\<alpha>) uexpr\"\n  shows \"dom\\<^sub>u(m(k \\<mapsto> v)\\<^sub>u) = {k}\\<^sub>u \\<union>\\<^sub>u dom\\<^sub>u(m)\"\n  by (rel_auto)\n\nlemma uapply_uupdate_pfun [simp]:\n  fixes m :: \"(('k, 'v) pfun, '\\<alpha>) uexpr\"\n  shows \"(m(k \\<mapsto> v)\\<^sub>u)(i)\\<^sub>a = v \\<triangleleft> i =\\<^sub>u k \\<triangleright> m(i)\\<^sub>a\"\n  by (rel_auto)\n\nlemma ulit_eq [simp]: \"x = y \\<Longrightarrow> (\\<guillemotleft>x\\<guillemotright> =\\<^sub>u \\<guillemotleft>y\\<guillemotright>) = true\"\n  by (rel_auto)\n    \nlemma ulit_neq [simp]: \"x \\<noteq> y \\<Longrightarrow> (\\<guillemotleft>x\\<guillemotright> =\\<^sub>u \\<guillemotleft>y\\<guillemotright>) = false\"\n  by (rel_auto)\n    \nlemma uset_mems [simp]:\n  \"x \\<in>\\<^sub>u {y}\\<^sub>u = (x =\\<^sub>u y)\"\n  \"x \\<in>\\<^sub>u A \\<union>\\<^sub>u B = (x \\<in>\\<^sub>u A \\<or> x \\<in>\\<^sub>u B)\"\n  \"x \\<in>\\<^sub>u A \\<inter>\\<^sub>u B = (x \\<in>\\<^sub>u A \\<and> x \\<in>\\<^sub>u B)\"\n  by (rel_auto)+\n    \nsubsection {* Refinement By Observation *}\n    \ntext {* Function to obtain the set of observations of a predicate *}\n    \ndefinition obs_upred :: \"'\\<alpha> upred \\<Rightarrow> '\\<alpha> set\" (\"\\<lbrakk>_\\<rbrakk>\\<^sub>o\")\nwhere [upred_defs]: \"\\<lbrakk>P\\<rbrakk>\\<^sub>o = {b. \\<lbrakk>P\\<rbrakk>\\<^sub>eb}\"\n    \nlemma obs_upred_refine_iff: \n  \"P \\<sqsubseteq> Q \\<longleftrightarrow> \\<lbrakk>Q\\<rbrakk>\\<^sub>o \\<subseteq> \\<lbrakk>P\\<rbrakk>\\<^sub>o\"\n  by (pred_auto)\n    \ntext {* A refinement can be demonstrated by considering only the observations of the predicates\n  which are relevant, i.e. not unrestricted, for them. In other words, if the alphabet can\n  be split into two disjoint segments, $x$ and $y$, and neither predicate refers to $y$ then\n  only $x$ need be considered when checking for observations. *}\n    \nlemma refine_by_obs:\n  assumes \"x \\<bowtie> y\" \"bij_lens (x +\\<^sub>L y)\" \"y \\<sharp> P\" \"y \\<sharp> Q\" \"{v. `P\\<lbrakk>\\<guillemotleft>v\\<guillemotright>/x\\<rbrakk>`} \\<subseteq> {v. `Q\\<lbrakk>\\<guillemotleft>v\\<guillemotright>/x\\<rbrakk>`}\"\n  shows \"Q \\<sqsubseteq> P\"\n  using assms(3-5)\n  apply (simp add: obs_upred_refine_iff subset_eq)\n  apply (pred_simp)\n  apply (rename_tac b)\n  apply (drule_tac x=\"get\\<^bsub>x\\<^esub>b\" in spec)\n  apply (auto simp add: assms)\n  apply (metis assms(1) assms(2) bij_lens.axioms(2) bij_lens_axioms_def lens_override_def lens_override_plus)+\ndone\n    \nsubsection {* Cylindric Algebra *}\n\nlemma C1: \"(\\<exists> x \\<bullet> false) = false\"\n  by (pred_auto)\n\nlemma C2: \"wb_lens x \\<Longrightarrow> `P \\<Rightarrow> (\\<exists> x \\<bullet> P)`\"\n  by (pred_simp, metis wb_lens.get_put)\n\nlemma C3: \"mwb_lens x \\<Longrightarrow> (\\<exists> x \\<bullet> (P \\<and> (\\<exists> x \\<bullet> Q))) = ((\\<exists> x \\<bullet> P) \\<and> (\\<exists> x \\<bullet> Q))\"\n  by (pred_auto)\n\nlemma C4a: \"x \\<approx>\\<^sub>L y \\<Longrightarrow> (\\<exists> x \\<bullet> \\<exists> y \\<bullet> P) = (\\<exists> y \\<bullet> \\<exists> x \\<bullet> P)\"\n  by (pred_simp, metis (no_types, lifting) lens.select_convs(2))+\n\nlemma C4b: \"x \\<bowtie> y \\<Longrightarrow> (\\<exists> x \\<bullet> \\<exists> y \\<bullet> P) = (\\<exists> y \\<bullet> \\<exists> x \\<bullet> P)\"\n  using ex_commute by blast\n\nlemma C5:\n  fixes x :: \"('a \\<Longrightarrow> '\\<alpha>)\"\n  shows \"(&x =\\<^sub>u &x) = true\"\n  by (pred_auto)\n\nlemma C6:\n  assumes \"wb_lens x\" \"x \\<bowtie> y\" \"x \\<bowtie> z\"\n  shows \"(&y =\\<^sub>u &z) = (\\<exists> x \\<bullet> &y =\\<^sub>u &x \\<and> &x =\\<^sub>u &z)\"\n  using assms\n  by (pred_simp, (metis lens_indep_def)+)\n\nlemma C7:\n  assumes \"weak_lens x\" \"x \\<bowtie> y\"\n  shows \"((\\<exists> x \\<bullet> &x =\\<^sub>u &y \\<and> P) \\<and> (\\<exists> x \\<bullet> &x =\\<^sub>u &y \\<and> \\<not> P)) = false\"\n  using assms\n  by (pred_simp, simp add: lens_indep_sym)\nsubsection {*AUX lemmas*} \n  \nlemma uimp_refl:\"`p \\<Rightarrow> p`\"\n  by pred_simp \n    \nend", "meta": {"author": "git-vt", "repo": "orca", "sha": "92bda0f9cfe5cc680b9c405fc38f07a960087a36", "save_path": "github-repos/isabelle/git-vt-orca", "path": "github-repos/isabelle/git-vt-orca/orca-92bda0f9cfe5cc680b9c405fc38f07a960087a36/C-verifier/src/Midend-IVL/Isabelle-UTP/utp/utp_pred_laws.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528057272544, "lm_q2_score": 0.8418256492357358, "lm_q1q2_score": 0.7171957237995527}}
{"text": "(*  Title:      Logical_Relations.thy\n    Author:     Peter Gammie\n*)\n\nsection \\<open>Pitts's method for solving recursive domain predicates\\<close>\n(*<*)\n\ntheory Logical_Relations\nimports\n  Basis\nbegin\n\n(*>*)\ntext\\<open>\n\nWe adopt the general theory of \\citet{PittsAM:relpod} for solving\nrecursive domain predicates. This is based on the idea of\n\\emph{minimal invariants} that \\citet[Def 2]{DBLP:conf/mfps/Pitts93}\nascribes ``essentially to D. Scott''.\n\nIdeally we would like to do the proofs once and use Pitts's\n\\emph{relational structures}. Unfortunately it seems we need\nhigher-order polymorphism (type functions) to make this work (but see\n\\citet{Huffman:MonadTransformers:2012}). Here we develop three\nversions, one for each of our applications. The proofs are similar\n(but not quite identical) in all cases.\n\nWe begin by defining an \\emph{admissible} set (aka an \\emph{inclusive\npredicate}) to be one that contains @{term \"\\<bottom>\"} and is closed under\ncountable chains:\n\n\\<close>\n\ndefinition admS :: \"'a::pcpo set set\" where\n  \"admS \\<equiv> { R :: 'a set. \\<bottom> \\<in> R \\<and> adm (\\<lambda>x. x \\<in> R) }\"\n\ntypedef ('a::pcpo) admS = \"{ x::'a::pcpo set . x \\<in> admS }\"\n  morphisms unlr mklr unfolding admS_def by fastforce\n\ntext\\<open>\n\nThese sets form a complete lattice.\n\n\\<close>\n(*<*)\n\nlemma admSI [intro]:\n  \"\\<lbrakk> \\<bottom> \\<in> R; adm (\\<lambda>x. x \\<in> R) \\<rbrakk> \\<Longrightarrow> R \\<in> admS\"\nunfolding admS_def by simp\n\nlemma bottom_in_unlr [simp]:\n  \"\\<bottom> \\<in> unlr R\"\nusing admS.unlr [of R] by (simp add: admS_def)\n\nlemma adm_unlr [simp]:\n  \"adm (\\<lambda>x. x \\<in> unlr R)\"\nusing admS.unlr [of R] by (simp add: admS_def)\n\nlemma adm_cont_unlr [intro, simp]:\n  \"cont f \\<Longrightarrow> adm (\\<lambda>x. f x \\<in> unlr r)\"\nby (erule adm_subst) simp\n\ndeclare admS.mklr_inverse[simp add]\n\ninstantiation admS :: (pcpo) order\nbegin\n\ndefinition\n  \"x \\<le> y \\<equiv> unlr x \\<subseteq> unlr y\"\n\ndefinition\n  \"x < y \\<equiv> unlr x \\<subset> unlr y\"\n\ninstance\n  by standard (auto simp add: less_eq_admS_def less_admS_def admS.unlr_inject)\n\nend\n\nlemma mklr_leq [iff]: \"\\<lbrakk> x \\<in> admS; y \\<in> admS \\<rbrakk> \\<Longrightarrow> (mklr x \\<le> mklr y) \\<longleftrightarrow> (x \\<le> y)\"\n  unfolding less_eq_admS_def by simp\n\nlemma unlr_leq: \"(unlr x \\<le> unlr y) \\<longleftrightarrow> (x \\<le> y)\"\n  unfolding less_eq_admS_def by simp\n\ninstantiation admS :: (pcpo) lattice\nbegin\n\ndefinition\n  \"inf f g \\<equiv> mklr (unlr f \\<inter> unlr g)\"\n\ndefinition\n  \"sup f g = mklr (unlr f \\<union> unlr g)\"\n\nlemma unlr_inf: \"unlr (inf x y) = unlr x \\<inter> unlr y\"\n  unfolding inf_admS_def by (simp add: admS_def)\n\nlemma unlr_sup: \"unlr (sup x y) = unlr x \\<union> unlr y\"\n  unfolding sup_admS_def by (simp add: admS_def)\n\ninstance by intro_classes (auto simp: less_eq_admS_def unlr_inf unlr_sup)\n\nend\n\ninstantiation admS :: (pcpo) bounded_lattice\nbegin\n\ndefinition\n  \"bot_admS \\<equiv> mklr {\\<bottom>}\"\n\nlemma unlr_bot[simp]:\n  \"unlr bot = {\\<bottom>}\"\n  by (simp add: admS_def bot_admS_def)\n\ndefinition\n  \"top_admS \\<equiv> mklr UNIV\"\n\ninstance\nproof\n  fix x :: \"'a admS\"\n  show \"bot \\<le> x\" by (simp add: bot_admS_def less_eq_admS_def admS_def)\nnext\n  fix x :: \"'a admS\"\n  show \"x \\<le> top\" by (simp add: top_admS_def less_eq_admS_def admS_def)\nqed\n\nend\n\ninstantiation admS :: (pcpo) complete_lattice\nbegin\n\ndefinition\n  \"Inf A \\<equiv> mklr (Inf (unlr ` A))\"\n\ndefinition\n  \"Sup (A::'a admS set) = Inf {y. \\<forall>x\\<in>A. x \\<le> y}\"\n\nlemma mklr_Inf: \"unlr (Inf A) = Inf (unlr ` A)\"\n  unfolding Inf_admS_def by (simp add: admS_def)\n\nlemma INT_admS_bot [simp]:\n  \"(\\<Inter>R. unlr R) = {\\<bottom>}\"\nby (auto, metis singletonE unlr_bot)\n\ninstance\n  by standard\n    (auto simp add:\n      less_eq_admS_def mklr_Inf Sup_admS_def\n      Inf_admS_def bot_admS_def top_admS_def admS_def)\n\nend\n(*>*)\n\n\nsubsection\\<open>Sets of vectors\\<close>\n\ntext\\<open>\n\nThe simplest case involves the recursive definition of a set of\nvectors over a single domain. This involves taking the fixed point of\na functor where the \\emph{positive} (covariant) occurrences of the\nrecursion variable are separated from the \\emph{negative}\n(contravariant) ones. (See \\S\\ref{sec:por} etc. for examples.)\n\nBy dually ordering the negative uses of the recursion variable the\nfunctor is made monotonic with respect to the order on the domain\n@{typ \"'d\"}. Here the type constructor @{typ \"'a dual\"} yields a type\nwith the same elements as @{typ \"'a\"} but with the reverse order. The\nfunctions @{term \"dual\"} and @{term \"undual\"} mediate the isomorphism.\n\n\\<close>\n\ntype_synonym 'd lf_rep = \"'d admS dual \\<times> 'd admS \\<Rightarrow> 'd set\"\ntype_synonym 'd lf = \"'d admS dual \\<times> 'd admS \\<Rightarrow> 'd admS\"\n\ntext\\<open>\n\nThe predicate @{term \"eRSV\"} encodes our notion of relation.  (This is\nPitts's \\<open>e : R \\<subset> S\\<close>.) We model a vector as a function from\nsome index type @{typ \"'i\"} to the domain @{typ \"'d\"}. Note that the\nminimal invariant is for the domain @{typ \"'d\"} only.\n\n\\<close>\n\nabbreviation\n  eRSV :: \"('d::pcpo \\<rightarrow> 'd) \\<Rightarrow> ('i::type \\<Rightarrow> 'd) admS dual \\<Rightarrow> ('i \\<Rightarrow> 'd) admS \\<Rightarrow> bool\"\nwhere\n  \"eRSV e R S \\<equiv> \\<forall>d \\<in> unlr (undual R). (\\<lambda>x. e\\<cdot>(d x)) \\<in> unlr S\"\n\ntext\\<open>\n\nIn general we can also assume that @{term \"e\"} here is strict, but we\ndo not need to do so for our examples.\n\nOur locale captures the key ingredients in Pitts's scheme:\n\\begin{itemize}\n\n\\item that the function @{term \"\\<delta>\"} is a minimal invariant;\n\n\\item that the functor defining the relation is suitably monotonic; and\n\n\\item that the functor is closed with respect to the minimal invariant.\n\n\\end{itemize}\n\n\\<close>\n\nlocale DomSol =\n  fixes F :: \"'a::order dual \\<times> 'a::order \\<Rightarrow> 'a\"\n  assumes monoF: \"mono F\"\nbegin\n\ndefinition sym_lr :: \"'a dual \\<times> 'a \\<Rightarrow> 'a dual \\<times> 'a\"\nwhere\n  \"sym_lr = (\\<lambda>(rm, rp). (dual (F (dual rp, undual rm)), F (rm, rp)))\"\n\nlemma sym_lr_mono:\n  \"mono sym_lr\"\nproof\n  fix x y :: \"'a dual \\<times> 'a\"\n  obtain x1 x2 y1 y2 where [simp]: \"x = (x1, x2)\" \"y = (y1, y2)\"\n    by (cases x, cases y)\n  assume \"x \\<le> y\"\n  with monoF have \"F x \\<le> F y\" ..\n  from \\<open>x \\<le> y\\<close> have \"(dual y2, undual y1) \\<le> (dual x2, undual x1)\"\n    by (simp_all add: dual_less_eq_iff)\n  with monoF have \"F (dual y2, undual y1) \\<le> F (dual x2, undual x1)\" ..\n  with \\<open>F x \\<le> F y\\<close> show \"sym_lr x \\<le> sym_lr y\"\n    by (simp add: sym_lr_def)\nqed\n\nend\n\nlocale DomSolV = DomSol \"F :: ('i::type \\<Rightarrow> 'd::pcpo) lf\" for F +\n  fixes \\<delta> :: \"('d::pcpo \\<rightarrow> 'd) \\<rightarrow> 'd \\<rightarrow> 'd\"\n  assumes min_inv_ID: \"fix\\<cdot>\\<delta> = ID\"\n  assumes eRSV_deltaF:\n      \"\\<And>(e :: 'd \\<rightarrow> 'd) (R :: ('i \\<Rightarrow> 'd) admS dual) (S :: ('i \\<Rightarrow> 'd) admS).\n          eRSV e R S \\<Longrightarrow> eRSV (\\<delta>\\<cdot>e) (dual (F (dual S, undual R))) (F (R, S))\"\n(*<*)\ncontext DomSolV\nbegin\n\nabbreviation\n  f_lim :: \"('i \\<Rightarrow> 'd) admS dual \\<times> ('i \\<Rightarrow> 'd) admS\"\nwhere\n  \"f_lim \\<equiv> lfp sym_lr\"\n\ndefinition\n  delta_neg :: \"('i \\<Rightarrow> 'd) admS dual\"\nwhere\n  \"delta_neg = fst f_lim\"\n\ndefinition\n  delta_pos :: \"('i \\<Rightarrow> 'd) admS\"\nwhere\n  \"delta_pos = snd f_lim\"\n\nlemma delta:\n  \"(delta_neg, delta_pos) = f_lim\"\nby (simp add: delta_neg_def delta_pos_def)\n\nlemma delta_neg_sol:\n  \"delta_neg = dual (F (dual delta_pos, undual delta_neg))\"\nby (metis (no_types, lifting) case_prod_unfold delta_neg_def delta_pos_def fst_conv lfp_unfold sym_lr_def sym_lr_mono)\n\n\n\nlemma delta_pos_neg_least:\n  assumes rm: \"rm \\<le> F (dual rp, rm)\"\n  assumes rp: \"F (dual rm, rp) \\<le> rp\"\n  shows \"delta_neg \\<le> dual rm\"\n    and \"delta_pos \\<le> rp\"\nproof -\n  from rm rp\n  have \"(delta_neg, delta_pos) \\<le> (dual rm, rp)\"\n    by (simp add: delta lfp_lowerbound sym_lr_def)\n  then show \"delta_neg \\<le> dual rm\" and \"delta_pos \\<le> rp\"\n    by simp_all\nqed\n\nlemma delta_eq:\n  \"undual delta_neg = delta_pos\"\nproof(rule antisym)\n  show \"delta_pos \\<le> undual delta_neg\"\n    by (metis delta_neg_sol delta_pos_neg_least(2) delta_pos_sol order_refl undual_dual)\nnext\n  let ?P = \"\\<lambda>x. eRSV x (delta_neg) (delta_pos)\"\n  have \"?P (fix\\<cdot>\\<delta>)\"\n    by (rule fix_ind, simp_all add: inst_fun_pcpo[symmetric])\n       (metis delta_neg_sol delta_pos_sol eRSV_deltaF)\n  with min_inv_ID\n  show \"undual delta_neg \\<le> delta_pos\"\n    by (fastforce simp: unlr_leq[symmetric])\nqed\n(*>*)\ntext\\<open>\n\nFrom these assumptions we can show that there is a unique object that\nis a solution to the recursive equation specified by @{term \"F\"}.\n\n\\<close>\n\ndefinition \"delta \\<equiv> delta_pos\"\n\nlemma delta_sol: \"delta = F (dual delta, delta)\"\n(*<*)\nunfolding delta_def\nby (subst delta_eq[symmetric], simp, rule delta_pos_sol)\n(*>*)\n\nlemma delta_unique:\n  assumes r: \"F (dual r, r) = r\"\n  shows \"r = delta\"\n(*<*)\nunfolding delta_def\nproof(rule antisym)\n  show \"delta_pos \\<le> r\"\n    using assms delta_pos_neg_least[where rm=r and rp=r] by simp\nnext\n  have \"delta_neg \\<le> dual r\"\n    using assms delta_pos_neg_least[where rm=r and rp=r] by simp\n  then have \"r \\<le> undual delta_neg\" by (simp add: less_eq_dual_def)\n  then show \"r \\<le> delta_pos\"\n    using delta_eq by simp\nqed\n(*>*)\n\nend\n\ntext\\<open>\n\nWe use this to show certain functions are not PCF-definable in\n\\S\\ref{sec:pcfdefinability}.\n\n\\<close>\n\nsubsection\\<open>Relations between domains and syntax\\<close>\n\ntext\\<open>\n\n\\label{sec:synlr}\n\nTo show computational adequacy (\\S\\ref{sec:compad}) we need to relate\nelements of a domain to their syntactic counterparts. An advantage of\nPitts's technique is that this is straightforward to do.\n\n\\<close>\n\ndefinition synlr :: \"('d::pcpo \\<times> 'a::type) set set\" where\n  \"synlr \\<equiv> { R :: ('d \\<times> 'a) set. \\<forall>a. { d. (d, a) \\<in> R } \\<in> admS }\"\n\ntypedef ('d::pcpo, 'a::type) synlr = \"{ x::('d \\<times> 'a) set. x \\<in> synlr }\"\n  morphisms unsynlr mksynlr unfolding synlr_def by fastforce\n\ntext\\<open>\n\nAn alternative representation (suggested by Brian Huffman) is to\ndirectly use the type @{typ \"'a \\<Rightarrow> 'b admS\"} as this is automatically\na complete lattice. However we end up fighting the automatic methods a\nlot.\n\n\\<close>\n\n(*<*)\n\n\nlemma bottom_in_unsynlr [simp]:\n  \"(\\<bottom>, a) \\<in> unsynlr R\"\n  using synlr.unsynlr [of R] by (simp add: synlr_def admS_def)\n\nlemma adm_unsynlr [simp]:\n  \"adm (\\<lambda>x. (x, a) \\<in> unsynlr R)\"\n  using synlr.unsynlr[of R] by (simp add: synlr_def admS_def)\n\nlemma adm_cont_unsynlr [intro, simp]:\n  \"cont f \\<Longrightarrow> adm (\\<lambda>x. (f x, a) \\<in> unsynlr r)\"\n  by (erule adm_subst) simp\n\ndeclare synlr.mksynlr_inverse[simp add]\n\ntext\\<open>Lattice machinery.\\<close>\n\ninstantiation synlr :: (pcpo, type) order\nbegin\n\ndefinition\n  \"x \\<le> y \\<equiv> unsynlr x \\<le> unsynlr y\"\n\ndefinition\n  \"x < y \\<equiv> unsynlr x < unsynlr y\"\n\ninstance\n  by standard (auto simp add: less_eq_synlr_def less_synlr_def synlr.unsynlr_inject)\n\nend\n\nlemma mksynlr_leq [iff]: \"\\<lbrakk> x \\<in> synlr; y \\<in> synlr \\<rbrakk> \\<Longrightarrow> (mksynlr x \\<le> mksynlr y) \\<longleftrightarrow> (x \\<le> y)\"\n  unfolding less_eq_synlr_def by simp\n\nlemma unsynlr_leq: \"(unsynlr x \\<le> unsynlr y) \\<longleftrightarrow> (x \\<le> y)\"\n  unfolding less_eq_synlr_def by simp\n\ninstantiation synlr :: (pcpo, type) lattice\nbegin\n\ndefinition\n  \"inf f g \\<equiv> mksynlr (unsynlr f \\<inter> unsynlr g)\"\n\ndefinition\n  \"sup f g = mksynlr (unsynlr f \\<union> unsynlr g)\"\n\nlemma unsynlr_inf: \"unsynlr (inf x y) = unsynlr x \\<inter> unsynlr y\"\n  unfolding inf_synlr_def by (simp add: admS_def synlr_def)\n\nlemma unsynlr_sup: \"unsynlr (sup x y) = unsynlr x \\<union> unsynlr y\"\n  unfolding sup_synlr_def by (simp add: admS_def synlr_def)\n\ninstance by intro_classes (auto simp: less_eq_synlr_def unsynlr_inf unsynlr_sup)\n\nend\n\ninstantiation synlr :: (pcpo, type) bounded_lattice\nbegin\n\ndefinition\n  \"bot_synlr \\<equiv> mksynlr ({\\<bottom>} \\<times> UNIV)\"\n\nlemma unsynlr_bot[simp]:\n  \"unsynlr bot = {\\<bottom>} \\<times> UNIV\"\n  by (simp add: admS_def synlr_def bot_synlr_def)\n\ndefinition\n  \"top_synlr \\<equiv> mksynlr UNIV\"\n\ninstance\nproof\n  fix x :: \"('a, 'b) synlr\"\n  show \"bot \\<le> x\" by (auto simp: bot_synlr_def less_eq_synlr_def admS_def synlr_def)\nnext\n  fix x :: \"('a, 'b) synlr\"\n  show \"x \\<le> top\" by (auto simp: top_synlr_def less_eq_synlr_def admS_def synlr_def)\nqed\n\nend\n\ninstantiation synlr :: (pcpo, type) complete_lattice\nbegin\n\ndefinition\n  \"Inf A \\<equiv> mksynlr (Inf (unsynlr ` A))\"\n\ndefinition\n  \"Sup (A::('a,'b) synlr set) = Inf {y. \\<forall>x\\<in>A. x \\<le> y}\"\n\nlemma mksynlr_Inf: \"unsynlr (Inf A) = Inf (unsynlr ` A)\"\n  unfolding Inf_synlr_def by (simp add: admS_def synlr_def)\n\nlemma INT_synlr_bot [simp]:\n  \"(\\<Inter>R. unsynlr R) = {\\<bottom>} \\<times> UNIV\"\napply auto\napply (drule spec[of _ \"mksynlr ({\\<bottom>} \\<times> UNIV)\"])\napply (metis bot_synlr_def mem_Sigma_iff singletonE unsynlr_bot)\ndone\n\ninstance\napply standard\napply (auto simp add: less_eq_synlr_def mksynlr_Inf Sup_synlr_def)\napply (auto simp add: Inf_synlr_def bot_synlr_def top_synlr_def)\ndone\n\nend\n\n(*>*)\ntext\\<open>\n\nAgain we define functors on @{typ \"('d, 'a) synlr\"}.\n\n\\<close>\n\ntype_synonym ('d, 'a) synlf_rep = \"('d, 'a) synlr dual \\<times> ('d, 'a) synlr \\<Rightarrow> ('d \\<times> 'a) set\"\ntype_synonym ('d, 'a) synlf = \"('d, 'a) synlr dual \\<times> ('d, 'a) synlr \\<Rightarrow> ('d, 'a) synlr\"\n\ntext\\<open>\n\nWe capture our relations as before. Note we need the inclusion @{term\n\"e\"} to be strict for our example.\n\n\\<close>\n\nabbreviation\n  eRSS :: \"('d::pcpo \\<rightarrow> 'd) \\<Rightarrow> ('d, 'a::type) synlr dual \\<Rightarrow> ('d, 'a) synlr \\<Rightarrow> bool\"\nwhere\n  \"eRSS e R S \\<equiv> \\<forall>(d, a) \\<in> unsynlr (undual R). (e\\<cdot>d, a) \\<in> unsynlr S\"\n\nlocale DomSolSyn =  DomSol \"F :: ('d::pcpo, 'a::type) synlf\" for F +\n  fixes \\<delta> :: \"('d::pcpo \\<rightarrow> 'd) \\<rightarrow> 'd \\<rightarrow> 'd\"\n  assumes min_inv_ID: \"fix\\<cdot>\\<delta> = ID\"\n  assumes min_inv_strict: \"\\<And>r. \\<delta>\\<cdot>r\\<cdot>\\<bottom> = \\<bottom>\"\n  assumes eRS_deltaF:\n      \"\\<And>(e :: 'd \\<rightarrow> 'd) (R :: ('d, 'a) synlr dual) (S :: ('d, 'a) synlr).\n          \\<lbrakk> e\\<cdot>\\<bottom> = \\<bottom>; eRSS e R S \\<rbrakk> \\<Longrightarrow> eRSS (\\<delta>\\<cdot>e) (dual (F (dual S, undual R))) (F (R, S))\"\n(*<*)\n\ncontext DomSolSyn\nbegin\n\nabbreviation\n  f_lim :: \"('d, 'a) synlr dual \\<times> ('d, 'a) synlr\"\nwhere\n  \"f_lim \\<equiv> lfp sym_lr\"\n\ndefinition\n  delta_neg :: \"('d, 'a) synlr dual\"\nwhere\n  \"delta_neg = fst f_lim\"\n\ndefinition\n  delta_pos :: \"('d, 'a) synlr\"\nwhere\n  \"delta_pos = snd f_lim\"\n\nlemma delta:\n  \"(delta_neg, delta_pos) = f_lim\"\nby (simp add: delta_neg_def delta_pos_def)\n\nlemma delta_neg_sol:\n  \"delta_neg = dual (F (dual delta_pos, undual delta_neg))\"\nby (metis (no_types, lifting) case_prod_unfold delta_neg_def delta_pos_def fst_conv lfp_unfold sym_lr_def sym_lr_mono)\n\nlemma delta_pos_sol:\n  \"delta_pos = F (delta_neg, delta_pos)\"\nby (metis (no_types, lifting) case_prod_conv delta lfp_unfold snd_conv sym_lr_def sym_lr_mono)\n\nlemma delta_pos_neg_least:\n  assumes rm: \"rm \\<le> F (dual rp, rm)\"\n  assumes rp: \"F (dual rm, rp) \\<le> rp\"\n  shows \"delta_neg \\<le> dual rm\"\n    and \"delta_pos \\<le> rp\"\nproof -\n  from rm rp\n  have \"(delta_neg, delta_pos) \\<le> (dual rm, rp)\"\n    by (simp add: delta lfp_lowerbound sym_lr_def)\n  then show \"delta_neg \\<le> dual rm\" and \"delta_pos \\<le> rp\"\n    by simp_all\nqed\n\nlemma delta_eq:\n  \"undual delta_neg = delta_pos\"\nproof(rule antisym)\n  show \"delta_pos \\<le> undual delta_neg\"\n    by (metis delta_neg_sol delta_pos_neg_least(2) delta_pos_sol order_refl undual_dual)\nnext\n  let ?P = \"\\<lambda>x. x\\<cdot>\\<bottom> = \\<bottom> \\<and> eRSS x (delta_neg) (delta_pos)\"\n  have \"?P (fix\\<cdot>\\<delta>)\"\n    by (rule fix_ind, simp_all)\n       (metis delta_neg_sol delta_pos_sol eRS_deltaF min_inv_strict)\n  with min_inv_ID\n  show \"undual delta_neg \\<le> delta_pos\"\n    by (fastforce simp: unsynlr_leq[symmetric])\nqed\n\ndefinition\n  \"delta \\<equiv> delta_pos\"\n\nlemma delta_sol:\n  \"delta = F (dual delta, delta)\"\nunfolding delta_def\nby (subst delta_eq[symmetric], simp, rule delta_pos_sol)\n\nlemma delta_unique:\n  assumes r: \"F (dual r, r) = r\"\n  shows \"r = delta\"\nunfolding delta_def\nproof(rule antisym)\n  show \"delta_pos \\<le> r\"\n    using assms delta_pos_neg_least[where rm=r and rp=r] by simp\nnext\n  have \"delta_neg \\<le> dual r\"\n    using assms delta_pos_neg_least[where rm=r and rp=r] by simp\n  then have \"r \\<le> undual delta_neg\" by (simp add: less_eq_dual_def)\n  then show \"r \\<le> delta_pos\"\n    using delta_eq by simp\nqed\n\nend\n\n(*>*)\ntext\\<open>\n\nAgain, from these assumptions we can construct the unique solution to\nthe recursive equation specified by @{term \"F\"}.\n\n\\<close>\n\nsubsection\\<open>Relations between pairs of domains\\<close>\n\ntext\\<open>\n\nFollowing \\citet{DBLP:conf/icalp/Reynolds74} and\n\\citet{DBLP:journals/tcs/Filinski07}, we want to relate two pairs of\nmutually-recursive domains. Each of the pairs represents a (monadic)\ncomputation and value space.\n\n\\<close>\n\ntype_synonym ('am, 'bm, 'av, 'bv) lr_pair = \"('am \\<times> 'bm) admS \\<times> ('av \\<times> 'bv) admS\"\n\ntype_synonym ('am, 'bm, 'av, 'bv) lf_pair_rep =\n  \"('am, 'bm, 'av, 'bv) lr_pair dual \\<times> ('am, 'bm, 'av, 'bv) lr_pair \\<Rightarrow> (('am \\<times> 'bm) set \\<times> ('av \\<times> 'bv) set)\"\n\ntype_synonym ('am, 'bm, 'av, 'bv) lf_pair =\n  \"('am, 'bm, 'av, 'bv) lr_pair dual \\<times> ('am, 'bm, 'av, 'bv) lr_pair \\<Rightarrow> (('am \\<times> 'bm) admS \\<times> ('av \\<times> 'bv) admS)\"\n\ntext\\<open>\n\nThe inclusions need to be strict to get our example through.\n\n\\<close>\n\nabbreviation\n  eRSP :: \"(('am::pcpo \\<rightarrow> 'am) \\<times> ('av::pcpo \\<rightarrow> 'av))\n       \\<Rightarrow> (('bm::pcpo \\<rightarrow> 'bm) \\<times> ('bv::pcpo \\<rightarrow> 'bv))\n       \\<Rightarrow> (('am \\<times> 'bm) admS \\<times> ('av \\<times> 'bv) admS) dual\n       \\<Rightarrow> ('am \\<times> 'bm) admS \\<times> ('av \\<times> 'bv) admS\n       \\<Rightarrow> bool\"\nwhere\n  \"eRSP ea eb R S \\<equiv>\n     (\\<forall>(am, bm) \\<in> unlr (fst (undual R)). (fst ea\\<cdot>am, fst eb\\<cdot>bm) \\<in> unlr (fst S))\n   \\<and> (\\<forall>(av, bv) \\<in> unlr (snd (undual R)). (snd ea\\<cdot>av, snd eb\\<cdot>bv) \\<in> unlr (snd S))\"\n\nlocale DomSolP = DomSol \"F :: ('am::pcpo, 'bm::pcpo, 'av::pcpo, 'bv::pcpo) lf_pair\" for F +\n  fixes ad :: \"(('am \\<rightarrow> 'am) \\<times> ('av \\<rightarrow> 'av)) \\<rightarrow> (('am \\<rightarrow> 'am) \\<times> ('av \\<rightarrow> 'av))\"\n  fixes bd :: \"(('bm \\<rightarrow> 'bm) \\<times> ('bv \\<rightarrow> 'bv)) \\<rightarrow> (('bm \\<rightarrow> 'bm) \\<times> ('bv \\<rightarrow> 'bv))\"\n  assumes ad_ID: \"fix\\<cdot>ad = (ID, ID)\"\n  assumes bd_ID: \"fix\\<cdot>bd = (ID, ID)\"\n  assumes ad_strict: \"\\<And>r. fst (ad\\<cdot>r)\\<cdot>\\<bottom> = \\<bottom>\" \"\\<And>r. snd (ad\\<cdot>r)\\<cdot>\\<bottom> = \\<bottom>\"\n  assumes bd_strict: \"\\<And>r. fst (bd\\<cdot>r)\\<cdot>\\<bottom> = \\<bottom>\" \"\\<And>r. snd (bd\\<cdot>r)\\<cdot>\\<bottom> = \\<bottom>\"\n  assumes eRSP_deltaF:\n    \"\\<lbrakk> eRSP ea eb R S; fst ea\\<cdot>\\<bottom> = \\<bottom>; snd ea\\<cdot>\\<bottom> = \\<bottom>; fst eb\\<cdot>\\<bottom> = \\<bottom>; snd ea\\<cdot>\\<bottom> = \\<bottom> \\<rbrakk>\n      \\<Longrightarrow> eRSP (ad\\<cdot>ea) (bd\\<cdot>eb) (dual (F (dual S, undual R))) (F (R, S))\"\n(*<*)\n\ncontext DomSolP\nbegin\n\nabbreviation\n  f_lim :: \"('am, 'bm, 'av, 'bv) lr_pair dual \\<times> ('am, 'bm, 'av, 'bv) lr_pair\"\nwhere\n  \"f_lim \\<equiv> lfp sym_lr\"\n\ndefinition\n  delta_neg :: \"('am, 'bm, 'av, 'bv) lr_pair dual\"\nwhere\n  \"delta_neg = fst f_lim\"\n\ndefinition\n  delta_pos :: \"('am, 'bm, 'av, 'bv) lr_pair\"\nwhere\n  \"delta_pos = snd f_lim\"\n\nlemma delta:\n  \"(delta_neg, delta_pos) = f_lim\"\nby (simp add: delta_neg_def delta_pos_def)\n\nlemma delta_neg_sol:\n  \"delta_neg = dual (F (dual delta_pos, undual delta_neg))\"\nby (metis (no_types, lifting) case_prod_unfold delta_neg_def delta_pos_def fst_conv lfp_unfold sym_lr_def sym_lr_mono)\n\nlemma delta_pos_sol:\n  \"delta_pos = F (delta_neg, delta_pos)\"\nby (metis (no_types, lifting) case_prod_conv delta lfp_unfold snd_conv sym_lr_def sym_lr_mono)\n\nlemma delta_pos_neg_least:\n  assumes rm: \"rm \\<le> F (dual rp, rm)\"\n  assumes rp: \"F (dual rm, rp) \\<le> rp\"\n  shows \"delta_neg \\<le> dual rm\"\n    and \"delta_pos \\<le> rp\"\nproof -\n  from rm rp\n  have \"(delta_neg, delta_pos) \\<le> (dual rm, rp)\"\n    by (simp add: delta lfp_lowerbound sym_lr_def)\n  then show \"delta_neg \\<le> dual rm\" and \"delta_pos \\<le> rp\"\n    by simp_all\nqed\n\nlemma delta_eq:\n  \"undual delta_neg = delta_pos\"\nproof(rule antisym)\n  show \"delta_pos \\<le> undual delta_neg\"\n    by (metis delta_neg_sol delta_pos_neg_least(2) delta_pos_sol order_refl undual_dual)\nnext\n  let ?P = \"\\<lambda>(ea, eb). eRSP ea eb (delta_neg) (delta_pos) \\<and> fst ea\\<cdot>\\<bottom> = \\<bottom> \\<and> snd ea\\<cdot>\\<bottom> = \\<bottom> \\<and> fst eb\\<cdot>\\<bottom> = \\<bottom> \\<and> snd eb\\<cdot>\\<bottom> = \\<bottom>\"\n  have \"?P (fix\\<cdot>ad, fix\\<cdot>bd)\"\n    apply (rule parallel_fix_ind)\n    apply simp_all\n    using ad_strict bd_strict\n    apply clarsimp\n    apply (cut_tac ea=\"(a, b)\" and eb=\"(aa, ba)\" in eRSP_deltaF[where R=delta_neg and S=delta_pos])\n    apply (simp_all add: delta_pos_sol[symmetric])\n    apply (subst delta_neg_sol)\n    apply simp\n    apply (subst delta_neg_sol)\n    apply simp\n    done\n  then have \"?P ((ID, ID), (ID, ID))\" by (simp only: ad_ID bd_ID)\n  then show \"undual delta_neg \\<le> delta_pos\"\n    by (fastforce simp: unlr_leq[symmetric] less_eq_prod_def)\nqed\n\ndefinition\n  \"delta \\<equiv> delta_pos\"\n\nlemma delta_sol:\n  \"delta = F (dual delta, delta)\"\nunfolding delta_def\nby (subst delta_eq[symmetric], simp, rule delta_pos_sol)\n\nlemma delta_unique:\n  assumes r: \"F (dual r, r) = r\"\n  shows \"r = delta\"\nunfolding delta_def\nproof(rule antisym)\n  show \"delta_pos \\<le> r\"\n    using assms delta_pos_neg_least[where rm=r and rp=r] by simp\nnext\n  have \"delta_neg \\<le> dual r\"\n    using assms delta_pos_neg_least[where rm=r and rp=r] by simp\n  then have \"r \\<le> undual delta_neg\" by (simp add: less_eq_dual_def)\n  then show \"r \\<le> delta_pos\"\n    using delta_eq by simp\nqed\n\nend\n(*>*)\n\ntext\\<open>\n\nWe use this solution to relate the direct and continuation semantics\nfor PCF in \\S\\ref{sec:continuations}.\n\n\\<close>\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/Evaluation/PCF/Logical_Relations.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256551882382, "lm_q2_score": 0.8519527982093666, "lm_q1q2_score": 0.7171957225420529}}
{"text": "(*  Title:      HOL/Library/Countable_Complete_Lattices.thy\n    Author:     Johannes H\u00f6lzl\n*)\n\nsection \\<open>Countable Complete Lattices\\<close>\n\ntheory Countable_Complete_Lattices\n  imports Main Countable_Set\nbegin\n\nlemma UNIV_nat_eq: \"UNIV = insert 0 (range Suc)\"\n  by (metis UNIV_eq_I nat.nchotomy insertCI rangeI)\n\nclass countable_complete_lattice = lattice + Inf + Sup + bot + top +\n  assumes ccInf_lower: \"countable A \\<Longrightarrow> x \\<in> A \\<Longrightarrow> Inf A \\<le> x\"\n  assumes ccInf_greatest: \"countable A \\<Longrightarrow> (\\<And>x. x \\<in> A \\<Longrightarrow> z \\<le> x) \\<Longrightarrow> z \\<le> Inf A\"\n  assumes ccSup_upper: \"countable A \\<Longrightarrow> x \\<in> A \\<Longrightarrow> x \\<le> Sup A\"\n  assumes ccSup_least: \"countable A \\<Longrightarrow> (\\<And>x. x \\<in> A \\<Longrightarrow> x \\<le> z) \\<Longrightarrow> Sup A \\<le> z\"\n  assumes ccInf_empty [simp]: \"Inf {} = top\"\n  assumes ccSup_empty [simp]: \"Sup {} = bot\"\nbegin\n\nsubclass bounded_lattice\nproof\n  fix a\n  show \"bot \\<le> a\" by (auto intro: ccSup_least simp only: ccSup_empty [symmetric])\n  show \"a \\<le> top\" by (auto intro: ccInf_greatest simp only: ccInf_empty [symmetric])\nqed\n\nlemma ccINF_lower: \"countable A \\<Longrightarrow> i \\<in> A \\<Longrightarrow> (INF i :A. f i) \\<le> f i\"\n  using ccInf_lower [of \"f ` A\"] by simp\n\nlemma ccINF_greatest: \"countable A \\<Longrightarrow> (\\<And>i. i \\<in> A \\<Longrightarrow> u \\<le> f i) \\<Longrightarrow> u \\<le> (INF i :A. f i)\"\n  using ccInf_greatest [of \"f ` A\"] by auto\n\nlemma ccSUP_upper: \"countable A \\<Longrightarrow> i \\<in> A \\<Longrightarrow> f i \\<le> (SUP i :A. f i)\"\n  using ccSup_upper [of \"f ` A\"] by simp\n\nlemma ccSUP_least: \"countable A \\<Longrightarrow> (\\<And>i. i \\<in> A \\<Longrightarrow> f i \\<le> u) \\<Longrightarrow> (SUP i :A. f i) \\<le> u\"\n  using ccSup_least [of \"f ` A\"] by auto\n\nlemma ccInf_lower2: \"countable A \\<Longrightarrow> u \\<in> A \\<Longrightarrow> u \\<le> v \\<Longrightarrow> Inf A \\<le> v\"\n  using ccInf_lower [of A u] by auto\n\nlemma ccINF_lower2: \"countable A \\<Longrightarrow> i \\<in> A \\<Longrightarrow> f i \\<le> u \\<Longrightarrow> (INF i :A. f i) \\<le> u\"\n  using ccINF_lower [of A i f] by auto\n\nlemma ccSup_upper2: \"countable A \\<Longrightarrow> u \\<in> A \\<Longrightarrow> v \\<le> u \\<Longrightarrow> v \\<le> Sup A\"\n  using ccSup_upper [of A u] by auto\n\nlemma ccSUP_upper2: \"countable A \\<Longrightarrow> i \\<in> A \\<Longrightarrow> u \\<le> f i \\<Longrightarrow> u \\<le> (SUP i :A. f i)\"\n  using ccSUP_upper [of A i f] by auto\n\nlemma le_ccInf_iff: \"countable A \\<Longrightarrow> b \\<le> Inf A \\<longleftrightarrow> (\\<forall>a\\<in>A. b \\<le> a)\"\n  by (auto intro: ccInf_greatest dest: ccInf_lower)\n\nlemma le_ccINF_iff: \"countable A \\<Longrightarrow> u \\<le> (INF i :A. f i) \\<longleftrightarrow> (\\<forall>i\\<in>A. u \\<le> f i)\"\n  using le_ccInf_iff [of \"f ` A\"] by simp\n\nlemma ccSup_le_iff: \"countable A \\<Longrightarrow> Sup A \\<le> b \\<longleftrightarrow> (\\<forall>a\\<in>A. a \\<le> b)\"\n  by (auto intro: ccSup_least dest: ccSup_upper)\n\nlemma ccSUP_le_iff: \"countable A \\<Longrightarrow> (SUP i :A. f i) \\<le> u \\<longleftrightarrow> (\\<forall>i\\<in>A. f i \\<le> u)\"\n  using ccSup_le_iff [of \"f ` A\"] by simp\n\nlemma ccInf_insert [simp]: \"countable A \\<Longrightarrow> Inf (insert a A) = inf a (Inf A)\"\n  by (force intro: le_infI le_infI1 le_infI2 antisym ccInf_greatest ccInf_lower)\n\nlemma ccINF_insert [simp]: \"countable A \\<Longrightarrow> (INF x:insert a A. f x) = inf (f a) (INFIMUM A f)\"\n  unfolding image_insert by simp\n\nlemma ccSup_insert [simp]: \"countable A \\<Longrightarrow> Sup (insert a A) = sup a (Sup A)\"\n  by (force intro: le_supI le_supI1 le_supI2 antisym ccSup_least ccSup_upper)\n\nlemma ccSUP_insert [simp]: \"countable A \\<Longrightarrow> (SUP x:insert a A. f x) = sup (f a) (SUPREMUM A f)\"\n  unfolding image_insert by simp\n\nlemma ccINF_empty [simp]: \"(INF x:{}. f x) = top\"\n  unfolding image_empty by simp\n\nlemma ccSUP_empty [simp]: \"(SUP x:{}. f x) = bot\"\n  unfolding image_empty by simp\n\nlemma ccInf_superset_mono: \"countable A \\<Longrightarrow> B \\<subseteq> A \\<Longrightarrow> Inf A \\<le> Inf B\"\n  by (auto intro: ccInf_greatest ccInf_lower countable_subset)\n\nlemma ccSup_subset_mono: \"countable B \\<Longrightarrow> A \\<subseteq> B \\<Longrightarrow> Sup A \\<le> Sup B\"\n  by (auto intro: ccSup_least ccSup_upper countable_subset)\n\nlemma ccInf_mono:\n  assumes [intro]: \"countable B\" \"countable A\"\n  assumes \"\\<And>b. b \\<in> B \\<Longrightarrow> \\<exists>a\\<in>A. a \\<le> b\"\n  shows \"Inf A \\<le> Inf B\"\nproof (rule ccInf_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 \"Inf A \\<le> a\" by (rule ccInf_lower[rotated]) auto\n  with \\<open>a \\<le> b\\<close> show \"Inf A \\<le> b\" by auto\nqed auto\n\nlemma ccINF_mono:\n  \"countable A \\<Longrightarrow> countable B \\<Longrightarrow> (\\<And>m. m \\<in> B \\<Longrightarrow> \\<exists>n\\<in>A. f n \\<le> g m) \\<Longrightarrow> (INF n:A. f n) \\<le> (INF n:B. g n)\"\n  using ccInf_mono [of \"g ` B\" \"f ` A\"] by auto\n\nlemma ccSup_mono:\n  assumes [intro]: \"countable B\" \"countable A\"\n  assumes \"\\<And>a. a \\<in> A \\<Longrightarrow> \\<exists>b\\<in>B. a \\<le> b\"\n  shows \"Sup A \\<le> Sup B\"\nproof (rule ccSup_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> Sup B\" by (rule ccSup_upper[rotated]) auto\n  with \\<open>a \\<le> b\\<close> show \"a \\<le> Sup B\" by auto\nqed auto\n\nlemma ccSUP_mono:\n  \"countable A \\<Longrightarrow> countable B \\<Longrightarrow> (\\<And>n. n \\<in> A \\<Longrightarrow> \\<exists>m\\<in>B. f n \\<le> g m) \\<Longrightarrow> (SUP n:A. f n) \\<le> (SUP n:B. g n)\"\n  using ccSup_mono [of \"g ` B\" \"f ` A\"] by auto\n\nlemma ccINF_superset_mono:\n  \"countable A \\<Longrightarrow> B \\<subseteq> A \\<Longrightarrow> (\\<And>x. x \\<in> B \\<Longrightarrow> f x \\<le> g x) \\<Longrightarrow> (INF x:A. f x) \\<le> (INF x:B. g x)\"\n  by (blast intro: ccINF_mono countable_subset dest: subsetD)\n\nlemma ccSUP_subset_mono:\n  \"countable B \\<Longrightarrow> A \\<subseteq> B \\<Longrightarrow> (\\<And>x. x \\<in> A \\<Longrightarrow> f x \\<le> g x) \\<Longrightarrow> (SUP x:A. f x) \\<le> (SUP x:B. g x)\"\n  by (blast intro: ccSUP_mono countable_subset dest: subsetD)\n\n\nlemma less_eq_ccInf_inter: \"countable A \\<Longrightarrow> countable B \\<Longrightarrow> sup (Inf A) (Inf B) \\<le> Inf (A \\<inter> B)\"\n  by (auto intro: ccInf_greatest ccInf_lower)\n\nlemma ccSup_inter_less_eq: \"countable A \\<Longrightarrow> countable B \\<Longrightarrow> Sup (A \\<inter> B) \\<le> inf (Sup A) (Sup B)\"\n  by (auto intro: ccSup_least ccSup_upper)\n\nlemma ccInf_union_distrib: \"countable A \\<Longrightarrow> countable B \\<Longrightarrow> Inf (A \\<union> B) = inf (Inf A) (Inf B)\"\n  by (rule antisym) (auto intro: ccInf_greatest ccInf_lower le_infI1 le_infI2)\n\nlemma ccINF_union:\n  \"countable A \\<Longrightarrow> countable B \\<Longrightarrow> (INF i:A \\<union> B. M i) = inf (INF i:A. M i) (INF i:B. M i)\"\n  by (auto intro!: antisym ccINF_mono intro: le_infI1 le_infI2 ccINF_greatest ccINF_lower)\n\nlemma ccSup_union_distrib: \"countable A \\<Longrightarrow> countable B \\<Longrightarrow> Sup (A \\<union> B) = sup (Sup A) (Sup B)\"\n  by (rule antisym) (auto intro: ccSup_least ccSup_upper le_supI1 le_supI2)\n\nlemma ccSUP_union:\n  \"countable A \\<Longrightarrow> countable B \\<Longrightarrow> (SUP i:A \\<union> B. M i) = sup (SUP i:A. M i) (SUP i:B. M i)\"\n  by (auto intro!: antisym ccSUP_mono intro: le_supI1 le_supI2 ccSUP_least ccSUP_upper)\n\nlemma ccINF_inf_distrib: \"countable A \\<Longrightarrow> inf (INF a:A. f a) (INF a:A. g a) = (INF a:A. inf (f a) (g a))\"\n  by (rule antisym) (rule ccINF_greatest, auto intro: le_infI1 le_infI2 ccINF_lower ccINF_mono)\n\nlemma ccSUP_sup_distrib: \"countable A \\<Longrightarrow> sup (SUP a:A. f a) (SUP a:A. g a) = (SUP a:A. sup (f a) (g a))\"\n  by (rule antisym[rotated]) (rule ccSUP_least, auto intro: le_supI1 le_supI2 ccSUP_upper ccSUP_mono)\n\nlemma ccINF_const [simp]: \"A \\<noteq> {} \\<Longrightarrow> (INF i :A. f) = f\"\n  unfolding image_constant_conv by auto\n\nlemma ccSUP_const [simp]: \"A \\<noteq> {} \\<Longrightarrow> (SUP i :A. f) = f\"\n  unfolding image_constant_conv by auto\n\nlemma ccINF_top [simp]: \"(INF x:A. top) = top\"\n  by (cases \"A = {}\") simp_all\n\nlemma ccSUP_bot [simp]: \"(SUP x:A. bot) = bot\"\n  by (cases \"A = {}\") simp_all\n\nlemma ccINF_commute: \"countable A \\<Longrightarrow> countable B \\<Longrightarrow> (INF i:A. INF j:B. f i j) = (INF j:B. INF i:A. f i j)\"\n  by (iprover intro: ccINF_lower ccINF_greatest order_trans antisym)\n\nlemma ccSUP_commute: \"countable A \\<Longrightarrow> countable B \\<Longrightarrow> (SUP i:A. SUP j:B. f i j) = (SUP j:B. SUP i:A. f i j)\"\n  by (iprover intro: ccSUP_upper ccSUP_least order_trans antisym)\n\nend\n\ncontext\n  fixes a :: \"'a::{countable_complete_lattice, linorder}\"\nbegin\n\nlemma less_ccSup_iff: \"countable S \\<Longrightarrow> a < Sup S \\<longleftrightarrow> (\\<exists>x\\<in>S. a < x)\"\n  unfolding not_le [symmetric] by (subst ccSup_le_iff) auto\n\nlemma less_ccSUP_iff: \"countable A \\<Longrightarrow> a < (SUP i:A. f i) \\<longleftrightarrow> (\\<exists>x\\<in>A. a < f x)\"\n  using less_ccSup_iff [of \"f ` A\"] by simp\n\nlemma ccInf_less_iff: \"countable S \\<Longrightarrow> Inf S < a \\<longleftrightarrow> (\\<exists>x\\<in>S. x < a)\"\n  unfolding not_le [symmetric] by (subst le_ccInf_iff) auto\n\nlemma ccINF_less_iff: \"countable A \\<Longrightarrow> (INF i:A. f i) < a \\<longleftrightarrow> (\\<exists>x\\<in>A. f x < a)\"\n  using ccInf_less_iff [of \"f ` A\"] by simp\n\nend\n\nclass countable_complete_distrib_lattice = countable_complete_lattice +\n  assumes sup_ccInf: \"countable B \\<Longrightarrow> sup a (Inf B) = (INF b:B. sup a b)\"\n  assumes inf_ccSup: \"countable B \\<Longrightarrow> inf a (Sup B) = (SUP b:B. inf a b)\"\nbegin\n\nlemma sup_ccINF:\n  \"countable B \\<Longrightarrow> sup a (INF b:B. f b) = (INF b:B. sup a (f b))\"\n  by (simp only: sup_ccInf image_image countable_image)\n\nlemma inf_ccSUP:\n  \"countable B \\<Longrightarrow> inf a (SUP b:B. f b) = (SUP b:B. inf a (f b))\"\n  by (simp only: inf_ccSup image_image countable_image)\n\nsubclass distrib_lattice\nproof\n  fix a b c\n  from sup_ccInf[of \"{b, c}\" a] have \"sup a (Inf {b, c}) = (INF d:{b, c}. sup a d)\"\n    by simp\n  then show \"sup a (inf b c) = inf (sup a b) (sup a c)\"\n    by simp\nqed\n\nlemma ccInf_sup:\n  \"countable B \\<Longrightarrow> sup (Inf B) a = (INF b:B. sup b a)\"\n  by (simp add: sup_ccInf sup_commute)\n\nlemma ccSup_inf:\n  \"countable B \\<Longrightarrow> inf (Sup B) a = (SUP b:B. inf b a)\"\n  by (simp add: inf_ccSup inf_commute)\n\nlemma ccINF_sup:\n  \"countable B \\<Longrightarrow> sup (INF b:B. f b) a = (INF b:B. sup (f b) a)\"\n  by (simp add: sup_ccINF sup_commute)\n\nlemma ccSUP_inf:\n  \"countable B \\<Longrightarrow> inf (SUP b:B. f b) a = (SUP b:B. inf (f b) a)\"\n  by (simp add: inf_ccSUP inf_commute)\n\nlemma ccINF_sup_distrib2:\n  \"countable A \\<Longrightarrow> countable B \\<Longrightarrow> sup (INF a:A. f a) (INF b:B. g b) = (INF a:A. INF b:B. sup (f a) (g b))\"\n  by (subst ccINF_commute) (simp_all add: sup_ccINF ccINF_sup)\n\nlemma ccSUP_inf_distrib2:\n  \"countable A \\<Longrightarrow> countable B \\<Longrightarrow> inf (SUP a:A. f a) (SUP b:B. g b) = (SUP a:A. SUP b:B. inf (f a) (g b))\"\n  by (subst ccSUP_commute) (simp_all add: inf_ccSUP ccSUP_inf)\n\ncontext\n  fixes f :: \"'a \\<Rightarrow> 'b::countable_complete_lattice\"\n  assumes \"mono f\"\nbegin\n\nlemma mono_ccInf:\n  \"countable A \\<Longrightarrow> f (Inf A) \\<le> (INF x:A. f x)\"\n  using \\<open>mono f\\<close>\n  by (auto intro!: countable_complete_lattice_class.ccINF_greatest intro: ccInf_lower dest: monoD)\n\nlemma mono_ccSup:\n  \"countable A \\<Longrightarrow> (SUP x:A. f x) \\<le> f (Sup A)\"\n  using \\<open>mono f\\<close> by (auto intro: countable_complete_lattice_class.ccSUP_least ccSup_upper dest: monoD)\n\nlemma mono_ccINF:\n  \"countable I \\<Longrightarrow> f (INF i : I. A i) \\<le> (INF x : I. f (A x))\"\n  by (intro countable_complete_lattice_class.ccINF_greatest monoD[OF \\<open>mono f\\<close>] ccINF_lower)\n\nlemma mono_ccSUP:\n  \"countable I \\<Longrightarrow> (SUP x : I. f (A x)) \\<le> f (SUP i : I. A i)\"\n  by (intro countable_complete_lattice_class.ccSUP_least monoD[OF \\<open>mono f\\<close>] ccSUP_upper)\n\nend\n\nend\n\nsubsubsection \\<open>Instances of countable complete lattices\\<close>\n\ninstance \"fun\" :: (type, countable_complete_lattice) countable_complete_lattice\n  by standard\n     (auto simp: le_fun_def intro!: ccSUP_upper ccSUP_least ccINF_lower ccINF_greatest)\n\nsubclass (in complete_lattice) countable_complete_lattice\n  by standard (auto intro: Sup_upper Sup_least Inf_lower Inf_greatest)\n\nsubclass (in complete_distrib_lattice) countable_complete_distrib_lattice\n  by standard (auto intro: sup_Inf inf_Sup)\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/Countable_Complete_Lattices.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256472515683, "lm_q2_score": 0.8519528000888387, "lm_q1q2_score": 0.7171957173625726}}
{"text": "(*  \n    Author:      Ren\u00e9 Thiemann \n                 Akihisa Yamada\n                 Jose Divason\n    License:     BSD\n*)\nsection \\<open>Missing Polynomial\\<close>\n\ntext \\<open>The theory contains some basic results on polynomials which have not been detected in\n  the distribution, especially on linear factors and degrees.\\<close>\n\ntheory Missing_Polynomial\nimports \n  \"HOL-Computational_Algebra.Polynomial_Factorial\"\n  Missing_Unsorted\nbegin\n\nsubsection \\<open>Basic Properties\\<close>\n\nlemma degree_0_id: assumes \"degree p = 0\"\n  shows \"[: coeff p 0 :] = p\" \nproof -\n  have \"\\<And> x. 0 \\<noteq> Suc x\" by auto \n  thus ?thesis using assms\n  by (metis coeff_pCons_0 degree_pCons_eq_if pCons_cases)\nqed\n\nlemma degree0_coeffs: \"degree p = 0 \\<Longrightarrow>\n  \\<exists> a. p = [: a :]\"\n  by (metis degree_pCons_eq_if old.nat.distinct(2) pCons_cases)\n\nlemma degree1_coeffs: \"degree p = 1 \\<Longrightarrow>\n  \\<exists> a b. p = [: b, a :] \\<and> a \\<noteq> 0\" \n  by (metis One_nat_def degree_pCons_eq_if nat.inject old.nat.distinct(2) pCons_0_0 pCons_cases)\n\nlemma degree2_coeffs: \"degree p = 2 \\<Longrightarrow>\n  \\<exists> a b c. p = [: c, b, a :] \\<and> a \\<noteq> 0\"\n  by (metis Suc_1 Suc_neq_Zero degree1_coeffs degree_pCons_eq_if nat.inject pCons_cases)\n\nlemma poly_zero:\n  fixes p :: \"'a :: comm_ring_1 poly\"\n  assumes x: \"poly p x = 0\" shows \"p = 0 \\<longleftrightarrow> degree p = 0\"\nproof\n  assume degp: \"degree p = 0\"\n  hence \"poly p x = coeff p (degree p)\" by(subst degree_0_id[OF degp,symmetric], simp)\n  hence \"coeff p (degree p) = 0\" using x by auto\n  thus \"p = 0\" by auto\nqed auto\n\nlemma coeff_monom_Suc: \"coeff (monom a (Suc d) * p) (Suc i) = coeff (monom a d * p) i\"\n  by (simp add: monom_Suc)\n\nlemma coeff_sum_monom:\n  assumes n: \"n \\<le> d\"\n  shows \"coeff (\\<Sum>i\\<le>d. monom (f i) i) n = f n\" (is \"?l = _\")\nproof -\n  have \"?l = (\\<Sum>i\\<le>d. coeff (monom (f i) i) n)\" (is \"_ = sum ?cmf _\")\n    using coeff_sum.\n  also have \"{..d} = insert n ({..d}-{n})\" using n by auto\n    hence \"sum ?cmf {..d} = sum ?cmf ...\" by auto\n  also have \"... = sum ?cmf ({..d}-{n}) + ?cmf n\" by (subst sum.insert,auto)\n  also have \"sum ?cmf ({..d}-{n}) = 0\" by (subst sum.neutral, auto)\n  finally show ?thesis by simp\nqed\n\nlemma linear_poly_root: \"(a :: 'a :: comm_ring_1) \\<in> set as \\<Longrightarrow> poly (\\<Prod> a \\<leftarrow> as. [: - a, 1:]) a = 0\"\nproof (induct as)\n  case (Cons b as)\n  show ?case\n  proof (cases \"a = b\")\n    case False\n    with Cons have \"a \\<in> set as\" by auto\n    from Cons(1)[OF this] show ?thesis by simp\n  qed simp\nqed simp\n\nlemma degree_lcoeff_sum: assumes deg: \"degree (f q) = n\"\n  and fin: \"finite S\" and q: \"q \\<in> S\" and degle: \"\\<And> p . p \\<in> S - {q} \\<Longrightarrow> degree (f p) < n\"\n  and cong: \"coeff (f q) n = c\"\n  shows \"degree (sum f S) = n \\<and> coeff (sum f S) n = c\"\nproof (cases \"S = {q}\")\n  case True\n  thus ?thesis using deg cong by simp\nnext\n  case False\n  with q obtain p where \"p \\<in> S - {q}\" by auto\n  from degle[OF this] have n: \"n > 0\" by auto\n  have \"degree (sum f S) = degree (f q + sum f (S - {q}))\"\n    unfolding sum.remove[OF fin q] ..\n  also have \"\\<dots> = degree (f q)\"\n  proof (rule degree_add_eq_left)\n    have \"degree (sum f (S - {q})) \\<le> n - 1\"\n    proof (rule degree_sum_le)\n      fix p\n      show \"p \\<in> S - {q} \\<Longrightarrow> degree (f p) \\<le> n - 1\"\n        using degle[of p] by auto\n    qed (insert fin, auto)\n    also have \"\\<dots> < n\" using n by simp\n    finally show \"degree (sum f (S - {q})) < degree (f q)\" unfolding deg .\n  qed\n  finally show ?thesis unfolding deg[symmetric] cong[symmetric]\n  proof (rule conjI)\n    have id: \"(\\<Sum>x\\<in>S - {q}. coeff (f x) (degree (f q))) = 0\"\n      by (rule sum.neutral, rule ballI, rule coeff_eq_0[OF degle[folded deg]])\n    show \"coeff (sum f S) (degree (f q)) = coeff (f q) (degree (f q))\"\n      unfolding coeff_sum\n      by (subst sum.remove[OF _ q], unfold id, insert fin, auto)\n  qed\nqed\n\nlemma degree_sum_list_le: \"(\\<And> p . p \\<in> set ps \\<Longrightarrow> degree p \\<le> n)\n  \\<Longrightarrow> degree (sum_list ps) \\<le> n\"\nproof (induct ps)\n  case (Cons p ps)\n  hence \"degree (sum_list ps) \\<le> n\" \"degree p \\<le> n\" by auto\n  thus ?case unfolding sum_list.Cons by (metis degree_add_le)\nqed simp\n\nlemma degree_prod_list_le: \"degree (prod_list ps) \\<le> sum_list (map degree ps)\"\nproof (induct ps)\n  case (Cons p ps)\n  show ?case unfolding prod_list.Cons\n    by (rule order.trans[OF degree_mult_le], insert Cons, auto)\nqed simp\n\nlemma smult_sum: \"smult (\\<Sum>i \\<in> S. f i) p = (\\<Sum>i \\<in> S. smult (f i) p)\"\n  by (induct S rule: infinite_finite_induct, auto simp: smult_add_left)\n\n\nlemma range_coeff: \"range (coeff p) = insert 0 (set (coeffs p))\" \n  by (metis nth_default_coeffs_eq range_nth_default)\n\nlemma smult_power: \"(smult a p) ^ n = smult (a ^ n) (p ^ n)\"\n  by (induct n, auto simp: field_simps)\n\nlemma poly_sum_list: \"poly (sum_list ps) x = sum_list (map (\\<lambda> p. poly p x) ps)\"\n  by (induct ps, auto)\n\nlemma poly_prod_list: \"poly (prod_list ps) x = prod_list (map (\\<lambda> p. poly p x) ps)\"\n  by (induct ps, auto)\n\nlemma sum_list_neutral: \"(\\<And> x. x \\<in> set xs \\<Longrightarrow> x = 0) \\<Longrightarrow> sum_list xs = 0\"\n  by (induct xs, auto)\n\nlemma prod_list_neutral: \"(\\<And> x. x \\<in> set xs \\<Longrightarrow> x = 1) \\<Longrightarrow> prod_list xs = 1\"\n  by (induct xs, auto)\n\nlemma (in comm_monoid_mult) prod_list_map_remove1:\n  \"x \\<in> set xs \\<Longrightarrow> prod_list (map f xs) = f x * prod_list (map f (remove1 x xs))\"\n  by (induct xs) (auto simp add: ac_simps)\n\nlemma poly_as_sum:\n  fixes p :: \"'a::comm_semiring_1 poly\"\n  shows \"poly p x = (\\<Sum>i\\<le>degree p. x ^ i * coeff p i)\"\n  unfolding poly_altdef by (simp add: ac_simps)\n\nlemma poly_prod_0: \"finite ps \\<Longrightarrow> poly (prod f ps) x = (0 :: 'a :: field) \\<longleftrightarrow> (\\<exists> p \\<in> ps. poly (f p) x = 0)\"\n  by (induct ps rule: finite_induct, auto)\n\nlemma coeff_monom_mult:\n  shows \"coeff (monom a d * p) i =\n    (if d \\<le> i then a * coeff p (i-d) else 0)\" (is \"?l = ?r\")\nproof (cases \"d \\<le> i\")\n  case False thus ?thesis unfolding coeff_mult by simp\n  next case True\n    let ?f = \"\\<lambda>j. coeff (monom a d) j * coeff p (i - j)\"\n    have \"\\<And>j. j \\<in> {0..i} - {d} \\<Longrightarrow> ?f j = 0\" by auto\n    hence \"0 = (\\<Sum>j \\<in> {0..i} - {d}. ?f j)\" by auto\n    also have \"... + ?f d = (\\<Sum>j \\<in> insert d ({0..i} - {d}). ?f j)\"\n      by(subst sum.insert, auto)\n    also have \"... = (\\<Sum>j \\<in> {0..i}. ?f j)\" by (subst insert_Diff, insert True, auto)\n    also have \"... = (\\<Sum>j\\<le>i. ?f j)\" by (rule sum.cong, auto)\n    also have \"... = ?l\" unfolding coeff_mult ..\n    finally show ?thesis using True by auto\nqed\n\nlemma poly_eqI2:\n  assumes \"degree p = degree q\" and \"\\<And>i. i \\<le> degree p \\<Longrightarrow> coeff p i = coeff q i\"\n  shows \"p = q\"\n  apply(rule poly_eqI) by (metis assms le_degree)\n\ntext \\<open>A nice extension rule for polynomials.\\<close>\nlemma poly_ext[intro]:\n  fixes p q :: \"'a :: {ring_char_0, idom} poly\"\n  assumes \"\\<And>x. poly p x = poly q x\" shows \"p = q\"\n  unfolding poly_eq_poly_eq_iff[symmetric]\n  using assms by (rule ext)\n\ntext \\<open>Copied from non-negative variants.\\<close>\nlemma coeff_linear_power_neg[simp]:\n  fixes a :: \"'a::comm_ring_1\"\n  shows \"coeff ([:a, -1:] ^ n) n = (-1)^n\"\napply (induct n, simp_all)\napply (subst coeff_eq_0)\napply (auto intro: le_less_trans degree_power_le)\ndone\n\nlemma degree_linear_power_neg[simp]:\n  fixes a :: \"'a::{idom,comm_ring_1}\"\n  shows \"degree ([:a, -1:] ^ n) = n\"\napply (rule order_antisym)\napply (rule ord_le_eq_trans [OF degree_power_le], simp)\napply (rule le_degree)\nunfolding coeff_linear_power_neg\napply (auto)\ndone\n\n\nsubsection \\<open>Polynomial Composition\\<close>\n\nlemmas [simp] = pcompose_pCons\n\nlemma pcompose_eq_0: fixes q :: \"'a :: idom poly\"\n  assumes q: \"degree q \\<noteq> 0\"\n  shows \"p \\<circ>\\<^sub>p q = 0 \\<longleftrightarrow> p = 0\"\nproof (induct p)\n  case 0\n  show ?case by auto\nnext\n  case (pCons a p)\n  have id: \"(pCons a p) \\<circ>\\<^sub>p q = [:a:] + q * (p \\<circ>\\<^sub>p q)\" by simp\n  show ?case \n  proof (cases \"p = 0\")\n    case True\n    show ?thesis unfolding id unfolding True by simp\n  next\n    case False\n    with pCons(2) have \"p \\<circ>\\<^sub>p q \\<noteq> 0\" by auto\n    from degree_mult_eq[OF _ this, of q] q have \"degree (q * (p \\<circ>\\<^sub>p q)) \\<noteq> 0\" by force\n    hence deg: \"degree ([:a:] + q * (p \\<circ>\\<^sub>p q)) \\<noteq> 0\"\n      by (subst degree_add_eq_right, auto)\n    show ?thesis unfolding id using False deg by auto\n  qed\nqed\n\ndeclare degree_pcompose[simp]\n\nsubsection \\<open>Monic Polynomials\\<close>\n\nabbreviation monic where \"monic p \\<equiv> coeff p (degree p) = 1\"\n\nlemma unit_factor_field [simp]: \n  \"unit_factor (x :: 'a :: {field,normalization_semidom}) = x\"\n  by (cases \"is_unit x\") (auto simp: is_unit_unit_factor dvd_field_iff)\n\nlemma poly_gcd_monic: \n  fixes p :: \"'a :: {field,factorial_ring_gcd,semiring_gcd_mult_normalize} poly\"\n  assumes \"p \\<noteq> 0 \\<or> q \\<noteq> 0\"\n  shows   \"monic (gcd p q)\"\nproof -\n  from assms have \"1 = unit_factor (gcd p q)\" by (auto simp: unit_factor_gcd)\n  also have \"\\<dots> = [:lead_coeff (gcd p q):]\" unfolding unit_factor_poly_def\n    by (simp add: monom_0)\n  finally show ?thesis\n    by (metis coeff_pCons_0 degree_1 lead_coeff_1)\nqed\n\nlemma normalize_monic: \"monic p \\<Longrightarrow> normalize p = p\"\n  by (simp add: normalize_poly_eq_map_poly is_unit_unit_factor)\n\nlemma lcoeff_monic_mult: assumes monic: \"monic (p :: 'a :: comm_semiring_1 poly)\"\n  shows \"coeff (p * q) (degree p + degree q) = coeff q (degree q)\"\nproof -\n  let ?pqi = \"\\<lambda> i. coeff p i * coeff q (degree p + degree q - i)\" \n  have \"coeff (p * q) (degree p + degree q) = \n    (\\<Sum>i\\<le>degree p + degree q. ?pqi i)\"\n    unfolding coeff_mult by simp\n  also have \"\\<dots> = ?pqi (degree p) + (sum ?pqi ({.. degree p + degree q} - {degree p}))\"\n    by (subst sum.remove[of _ \"degree p\"], auto)\n  also have \"?pqi (degree p) = coeff q (degree q)\" unfolding monic by simp\n  also have \"(sum ?pqi ({.. degree p + degree q} - {degree p})) = 0\"\n  proof (rule sum.neutral, intro ballI)\n    fix d\n    assume d: \"d \\<in> {.. degree p + degree q} - {degree p}\"\n    show \"?pqi d = 0\"\n    proof (cases \"d < degree p\")\n      case True\n      hence \"degree p + degree q - d > degree q\" by auto\n      hence \"coeff q (degree p + degree q - d) = 0\" by (rule coeff_eq_0)\n      thus ?thesis by simp\n    next\n      case False\n      with d have \"d > degree p\" by auto\n      hence \"coeff p d = 0\" by (rule coeff_eq_0)\n      thus ?thesis by simp\n    qed\n  qed\n  finally show ?thesis by simp\nqed\n\nlemma degree_monic_mult: assumes monic: \"monic (p :: 'a :: comm_semiring_1 poly)\"\n  and q: \"q \\<noteq> 0\"\n  shows \"degree (p * q) = degree p + degree q\"\nproof -\n  have \"degree p + degree q \\<ge> degree (p * q)\" by (rule degree_mult_le)\n  also have \"degree p + degree q \\<le> degree (p * q)\"\n  proof -\n    from q have cq: \"coeff q (degree q) \\<noteq> 0\" by auto\n    hence \"coeff (p * q) (degree p + degree q) \\<noteq> 0\" unfolding lcoeff_monic_mult[OF monic] .\n    thus \"degree (p * q) \\<ge> degree p + degree q\" by (rule le_degree)\n  qed\n  finally show ?thesis .\nqed\n\nlemma degree_prod_sum_monic: assumes\n  S: \"finite S\"\n  and nzd: \"0 \\<notin> (degree o f) ` S\"\n  and monic: \"(\\<And> a . a \\<in> S \\<Longrightarrow> monic (f a))\"\n  shows \"degree (prod f S) = (sum (degree o f) S) \\<and> coeff (prod f S) (sum (degree o f) S) = 1\"\nproof -\n  from S nzd monic \n  have \"degree (prod f S) = sum (degree \\<circ> f) S \n  \\<and> (S \\<noteq> {} \\<longrightarrow> degree (prod f S) \\<noteq> 0 \\<and> prod f S \\<noteq> 0) \\<and> coeff (prod f S) (sum (degree o f) S) = 1\"\n  proof (induct S rule: finite_induct)\n    case (insert a S)\n    have IH1: \"degree (prod f S) = sum (degree o f) S\"\n      using insert by auto\n    have IH2: \"coeff (prod f S) (degree (prod f S)) = 1\"\n      using insert by auto\n    have id: \"degree (prod f (insert a S)) = sum (degree \\<circ> f) (insert a S)\n      \\<and> coeff (prod f (insert a S)) (sum (degree o f) (insert a S)) = 1\"\n    proof (cases \"S = {}\")\n      case False\n      with insert have nz: \"prod f S \\<noteq> 0\" by auto\n      from insert have monic: \"coeff (f a) (degree (f a)) = 1\" by auto\n      have id: \"(degree \\<circ> f) a = degree (f a)\" by simp\n      show ?thesis unfolding prod.insert[OF insert(1-2)] sum.insert[OF insert(1-2)] id\n        unfolding degree_monic_mult[OF monic nz] \n        unfolding IH1[symmetric]\n        unfolding lcoeff_monic_mult[OF monic] IH2 by simp\n    qed (insert insert, auto)\n    show ?case using id unfolding sum.insert[OF insert(1-2)] using insert by auto\n  qed simp\n  thus ?thesis by auto\nqed \n\nlemma degree_prod_monic: \n  assumes \"\\<And> i. i < n \\<Longrightarrow> degree (f i :: 'a :: comm_semiring_1 poly) = 1\"\n    and \"\\<And> i. i < n \\<Longrightarrow> coeff (f i) 1 = 1\"\n  shows \"degree (prod f {0 ..< n}) = n \\<and> coeff (prod f {0 ..< n}) n = 1\"\nproof -\n  from degree_prod_sum_monic[of \"{0 ..< n}\" f] show ?thesis using assms by force\nqed\n\nlemma degree_prod_sum_lt_n: assumes \"\\<And> i. i < n \\<Longrightarrow> degree (f i :: 'a :: comm_semiring_1 poly) \\<le> 1\"\n  and i: \"i < n\" and fi: \"degree (f i) = 0\"\n  shows \"degree (prod f {0 ..< n}) < n\"\nproof -\n  have \"degree (prod f {0 ..< n}) \\<le> sum (degree o f) {0 ..< n}\"\n    by (rule degree_prod_sum_le, auto)\n  also have \"sum (degree o f) {0 ..< n} = (degree o f) i + sum (degree o f) ({0 ..< n} - {i})\"\n    by (rule sum.remove, insert i, auto)\n  also have \"(degree o f) i = 0\" using fi by simp\n  also have \"sum (degree o f) ({0 ..< n} - {i}) \\<le> sum (\\<lambda> _. 1) ({0 ..< n} - {i})\"\n    by (rule sum_mono, insert assms, auto)\n  also have \"\\<dots> = n - 1\" using i by simp\n  also have \"\\<dots> < n\" using i by simp\n  finally show ?thesis by simp\nqed\n\nlemma degree_linear_factors: \"degree (\\<Prod> a \\<leftarrow> as. [: f a, 1:]) = length as\"\nproof (induct as)\n  case (Cons b as) note IH = this\n  have id: \"(\\<Prod>a\\<leftarrow>b # as. [:f a, 1:]) = [:f b,1 :] * (\\<Prod>a\\<leftarrow>as. [:f a, 1:])\" by simp\n  show ?case unfolding id\n    by (subst degree_monic_mult, insert IH, auto)\nqed simp\n\nlemma monic_mult:\n  fixes p q :: \"'a :: idom poly\"\n  assumes \"monic p\" \"monic q\"\n  shows \"monic (p * q)\"\nproof -\n  from assms have nz: \"p \\<noteq> 0\" \"q \\<noteq> 0\" by auto\n  show ?thesis unfolding degree_mult_eq[OF nz] coeff_mult_degree_sum\n    using assms by simp\nqed\n\nlemma monic_factor:\n  fixes p q :: \"'a :: idom poly\"\n  assumes \"monic (p * q)\" \"monic p\"\n  shows \"monic q\"\nproof -\n  from assms have nz: \"p \\<noteq> 0\" \"q \\<noteq> 0\" by auto\n  from assms[unfolded degree_mult_eq[OF nz] coeff_mult_degree_sum \\<open>monic p\\<close>]\n  show ?thesis by simp\nqed\n\nlemma monic_prod:\n  fixes f :: \"'a \\<Rightarrow> 'b :: idom poly\"\n  assumes \"\\<And> a. a \\<in> as \\<Longrightarrow> monic (f a)\"\n  shows \"monic (prod f as)\" using assms\nproof (induct as rule: infinite_finite_induct)\n  case (insert a as)\n  hence id: \"prod f (insert a as) = f a * prod f as\" \n    and *: \"monic (f a)\" \"monic (prod f as)\" by auto\n  show ?case unfolding id by (rule monic_mult[OF *])\nqed auto\n\nlemma monic_prod_list:\n  fixes as :: \"'a :: idom poly list\"\n  assumes \"\\<And> a. a \\<in> set as \\<Longrightarrow> monic a\"\n  shows \"monic (prod_list as)\" using assms\n  by (induct as, auto intro: monic_mult)\n\nlemma monic_power:\n  assumes \"monic (p :: 'a :: idom poly)\"\n  shows \"monic (p ^ n)\"\n  by (induct n, insert assms, auto intro: monic_mult)\n\nlemma monic_prod_list_pow: \"monic (\\<Prod>(x::'a::idom, i)\\<leftarrow>xis. [:- x, 1:] ^ Suc i)\"\nproof (rule monic_prod_list, goal_cases)\n  case (1 a)\n  then obtain x i where a: \"a = [:-x, 1:]^Suc i\" by force\n  show \"monic a\" unfolding a\n    by (rule monic_power, auto)\nqed\n\nlemma monic_degree_0: \"monic p \\<Longrightarrow> (degree p = 0) = (p = 1)\"\n  using le_degree poly_eq_iff by force\n\nsubsection \\<open>Roots\\<close>\n\ntext \\<open>The following proof structure is completely similar to the one\n  of @{thm poly_roots_finite}.\\<close>\n\nlemma poly_roots_degree:\n  fixes p :: \"'a::idom poly\"\n  shows \"p \\<noteq> 0 \\<Longrightarrow> card {x. poly p x = 0} \\<le> degree p\"\nproof (induct n \\<equiv> \"degree p\" arbitrary: p)\n  case (0 p)\n  then obtain a where \"a \\<noteq> 0\" and \"p = [:a:]\"\n    by (cases p, simp split: if_splits)\n  then show ?case by simp\nnext\n  case (Suc n p)\n  show ?case\n  proof (cases \"\\<exists>x. poly p x = 0\")\n    case True\n    then obtain a where a: \"poly p a = 0\" ..\n    then have \"[:-a, 1:] dvd p\" by (simp only: poly_eq_0_iff_dvd)\n    then obtain k where k: \"p = [:-a, 1:] * k\" ..\n    with \\<open>p \\<noteq> 0\\<close> have \"k \\<noteq> 0\" by auto\n    with k have \"degree p = Suc (degree k)\"\n      by (simp add: degree_mult_eq del: mult_pCons_left)\n    with \\<open>Suc n = degree p\\<close> have \"n = degree k\" by simp\n    from Suc.hyps(1)[OF this \\<open>k \\<noteq> 0\\<close>]\n    have le: \"card {x. poly k x = 0} \\<le> degree k\" .\n    have \"card {x. poly p x = 0} = card {x. poly ([:-a, 1:] * k) x = 0}\" unfolding k ..\n    also have \"{x. poly ([:-a, 1:] * k) x = 0} = insert a {x. poly k x = 0}\"\n      by auto\n    also have \"card \\<dots> \\<le> Suc (card {x. poly k x = 0})\" \n      unfolding card_insert_if[OF poly_roots_finite[OF \\<open>k \\<noteq> 0\\<close>]] by simp\n    also have \"\\<dots> \\<le> Suc (degree k)\" using le by auto\n    finally show ?thesis using \\<open>degree p = Suc (degree k)\\<close> by simp\n  qed simp\nqed\n\nlemma poly_root_factor: \"(poly ([: r, 1:] * q) (k :: 'a :: idom) = 0) = (k = -r \\<or> poly q k = 0)\" (is ?one)\n  \"(poly (q * [: r, 1:]) k = 0) = (k = -r \\<or> poly q k = 0)\" (is ?two)\n  \"(poly [: r, 1 :] k = 0) = (k = -r)\" (is ?three)\nproof -\n  have [simp]: \"r + k = 0 \\<Longrightarrow> k = - r\" by (simp add: minus_unique)\n  show ?one unfolding poly_mult by auto\n  show ?two unfolding poly_mult by auto\n  show ?three by auto\nqed\n\nlemma poly_root_constant: \"c \\<noteq> 0 \\<Longrightarrow> (poly (p * [:c:]) (k :: 'a :: idom) = 0) = (poly p k = 0)\"\n  unfolding poly_mult by auto\n\n\nlemma poly_linear_exp_linear_factors_rev: \n  \"([:b,1:])^(length (filter ((=) b) as)) dvd (\\<Prod> (a :: 'a :: comm_ring_1) \\<leftarrow> as. [: a, 1:])\"\nproof (induct as)\n  case (Cons a as)\n  let ?ls = \"length (filter ((=) b) (a # as))\"\n  let ?l = \"length (filter ((=) b) as)\"\n  have prod: \"(\\<Prod> a \\<leftarrow> Cons a as. [: a, 1:]) = [: a, 1 :] * (\\<Prod> a \\<leftarrow> as. [: a, 1:])\" by simp\n  show ?case\n  proof (cases \"a = b\")\n    case False\n    hence len: \"?ls = ?l\" by simp\n    show ?thesis unfolding prod len using Cons by (rule dvd_mult)\n  next\n    case True\n    hence len: \"[: b, 1 :] ^ ?ls = [: a, 1 :] * [: b, 1 :] ^ ?l\" by simp\n    show ?thesis unfolding prod len using Cons using dvd_refl mult_dvd_mono by blast\n  qed\nqed simp\n\nlemma order_max: assumes dvd: \"[: -a, 1 :] ^ k dvd p\" and p: \"p \\<noteq> 0\"\n  shows \"k \\<le> order a p\"\nproof (rule ccontr)\n  assume \"\\<not> ?thesis\"\n  hence \"\\<exists> j. k = Suc (order a p + j)\" by arith\n  then obtain j where k: \"k = Suc (order a p + j)\" by auto\n  have \"[: -a, 1 :] ^ Suc (order a p) dvd p\"\n    by (rule power_le_dvd[OF dvd[unfolded k]], simp)\n  with order_2[OF p, of a] show False by blast\nqed\n\n\nsubsection \\<open>Divisibility\\<close>\n\ncontext\n  assumes \"SORT_CONSTRAINT('a :: idom)\"\nbegin\nlemma poly_linear_linear_factor: assumes \n  dvd: \"[:b,1:] dvd (\\<Prod> (a :: 'a) \\<leftarrow> as. [: a, 1:])\"\n  shows \"b \\<in> set as\"\nproof -\n  let ?p = \"\\<lambda> as. (\\<Prod> a \\<leftarrow> as. [: a, 1:])\"\n  let ?b = \"[:b,1:]\"\n  from assms[unfolded dvd_def] obtain p where id: \"?p as = ?b * p\" ..\n  from arg_cong[OF id, of \"\\<lambda> p. poly p (-b)\"]\n  have \"poly (?p as) (-b) = 0\" by simp\n  thus ?thesis\n  proof (induct as)\n    case (Cons a as)\n    have \"?p (a # as) = [:a,1:] * ?p as\" by simp\n    from Cons(2)[unfolded this] have \"poly (?p as) (-b) = 0 \\<or> (a - b) = 0\" by simp\n    with Cons(1) show ?case by auto\n  qed simp\nqed\n\nlemma poly_linear_exp_linear_factors: \n  assumes dvd: \"([:b,1:])^n dvd (\\<Prod> (a :: 'a) \\<leftarrow> as. [: a, 1:])\"\n  shows \"length (filter ((=) b) as) \\<ge> n\"\nproof -\n  let ?p = \"\\<lambda> as. (\\<Prod> a \\<leftarrow> as. [: a, 1:])\"\n  let ?b = \"[:b,1:]\"\n  from dvd show ?thesis\n  proof (induct n arbitrary: as)\n    case (Suc n as)\n    have bs: \"?b ^ Suc n = ?b * ?b ^ n\" by simp\n    from poly_linear_linear_factor[OF dvd_mult_left[OF Suc(2)[unfolded bs]], \n      unfolded in_set_conv_decomp]\n    obtain as1 as2 where as: \"as = as1 @ b # as2\" by auto\n    have \"?p as = [:b,1:] * ?p (as1 @ as2)\" unfolding as\n    proof (induct as1)\n      case (Cons a as1)\n      have \"?p (a # as1 @ b # as2) = [:a,1:] * ?p (as1 @ b # as2)\" by simp\n      also have \"?p (as1 @ b # as2) = [:b,1:] * ?p (as1 @ as2)\" unfolding Cons by simp\n      also have \"[:a,1:] * \\<dots> = [:b,1:] * ([:a,1:] * ?p (as1 @ as2))\" \n        by (metis (no_types, lifting) mult.left_commute)\n      finally show ?case by simp\n    qed simp\n    from Suc(2)[unfolded bs this dvd_mult_cancel_left]\n    have \"?b ^ n dvd ?p (as1 @ as2)\" by simp\n    from Suc(1)[OF this] show ?case unfolding as by simp\n  qed simp    \nqed\nend\n\nlemma const_poly_dvd: \"([:a:] dvd [:b:]) = (a dvd b)\"\nproof\n  assume \"a dvd b\"\n  then obtain c where \"b = a * c\" unfolding dvd_def by auto\n  hence \"[:b:] = [:a:] * [: c:]\" by (auto simp: ac_simps)\n  thus \"[:a:] dvd [:b:]\" unfolding dvd_def by blast\nnext\n  assume \"[:a:] dvd [:b:]\"\n  then obtain pc where \"[:b:] =  [:a:] * pc\" unfolding dvd_def by blast\n  from arg_cong[OF this, of \"\\<lambda> p. coeff p 0\", unfolded coeff_mult]\n  have \"b = a * coeff pc 0\" by auto\n  thus \"a dvd b\" unfolding dvd_def by blast\nqed\n\nlemma const_poly_dvd_1 [simp]:\n  \"[:a:] dvd 1 \\<longleftrightarrow> a dvd 1\"\n  by (metis const_poly_dvd one_poly_eq_simps(2))\n\nlemma poly_dvd_1:\n  fixes p :: \"'a :: {comm_semiring_1,semiring_no_zero_divisors} poly\"\n  shows \"p dvd 1 \\<longleftrightarrow> degree p = 0 \\<and> coeff p 0 dvd 1\"\nproof (cases \"degree p = 0\")\n  case False\n  with divides_degree[of p 1] show ?thesis by auto\nnext\n  case True\n  from degree0_coeffs[OF this] obtain a where p: \"p = [:a:]\" by auto\n  show ?thesis unfolding p by auto\nqed\n\ntext \\<open>Degree based version of irreducibility.\\<close>\n\ndefinition irreducible\\<^sub>d :: \"'a :: comm_semiring_1 poly \\<Rightarrow> bool\" where\n  \"irreducible\\<^sub>d p = (degree p > 0 \\<and> (\\<forall> q r. degree q < degree p \\<longrightarrow> degree r < degree p \\<longrightarrow> p \\<noteq> q * r))\"\n\nlemma irreducible\\<^sub>dI [intro]:\n  assumes 1: \"degree p > 0\"\n    and 2: \"\\<And>q r. degree q > 0 \\<Longrightarrow> degree q < degree p \\<Longrightarrow> degree r > 0 \\<Longrightarrow> degree r < degree p \\<Longrightarrow> p = q * r \\<Longrightarrow> False\"\n  shows \"irreducible\\<^sub>d p\"\nproof (unfold irreducible\\<^sub>d_def, intro conjI allI impI notI 1)\n  fix q r\n  assume \"degree q < degree p\" and \"degree r < degree p\" and \"p = q * r\"\n  with degree_mult_le[of q r]\n  show False by (intro 2, auto)\nqed\n\nlemma irreducible\\<^sub>dI2:\n  fixes p :: \"'a::{comm_semiring_1,semiring_no_zero_divisors} poly\"\n  assumes deg: \"degree p > 0\" and ndvd: \"\\<And> q. degree q > 0 \\<Longrightarrow> degree q \\<le> degree p div 2 \\<Longrightarrow> \\<not> q dvd p\"\n  shows \"irreducible\\<^sub>d p\"\nproof (rule ccontr)\n  assume \"\\<not> ?thesis\"\n  from this[unfolded irreducible\\<^sub>d_def] deg obtain q r where dq: \"degree q < degree p\" and dr: \"degree r < degree p\"\n    and p: \"p = q * r\" by auto\n  from deg have p0: \"p \\<noteq> 0\" by auto\n  with p have \"q \\<noteq> 0\" \"r \\<noteq> 0\" by auto\n  from degree_mult_eq[OF this] p have dp: \"degree p = degree q + degree r\" by simp\n  show False\n  proof (cases \"degree q \\<le> degree p div 2\")\n    case True\n    from ndvd[OF _ True] dq dr dp p show False by auto\n  next\n    case False\n    with dp have dr: \"degree r \\<le> degree p div 2\" by auto\n    from p have dvd: \"r dvd p\" by auto\n    from ndvd[OF _ dr] dvd dp dq show False by auto\n  qed\nqed\n\nlemma reducible\\<^sub>dI:\n  assumes \"degree p > 0 \\<Longrightarrow> \\<exists>q r. degree q < degree p \\<and> degree r < degree p \\<and> p = q * r\"\n  shows \"\\<not> irreducible\\<^sub>d p\"\n  using assms by (auto simp: irreducible\\<^sub>d_def)\n\nlemma irreducible\\<^sub>dE [elim]:\n  assumes \"irreducible\\<^sub>d p\"\n    and \"degree p > 0 \\<Longrightarrow> (\\<And>q r. degree q < degree p \\<Longrightarrow> degree r < degree p \\<Longrightarrow> p \\<noteq> q * r) \\<Longrightarrow> thesis\"\n  shows thesis\n  using assms by (auto simp: irreducible\\<^sub>d_def)\n\nlemma reducible\\<^sub>dE [elim]:\n  assumes red: \"\\<not> irreducible\\<^sub>d p\"\n    and 1: \"degree p = 0 \\<Longrightarrow> thesis\"\n    and 2: \"\\<And>q r. degree q > 0 \\<Longrightarrow> degree q < degree p \\<Longrightarrow> degree r > 0 \\<Longrightarrow> degree r < degree p \\<Longrightarrow> p = q * r \\<Longrightarrow> thesis\"\n  shows thesis\n  using red[unfolded irreducible\\<^sub>d_def de_Morgan_conj not_not not_all not_imp]\nproof (elim disjE exE conjE)\n  show \"\\<not>degree p > 0 \\<Longrightarrow> thesis\" using 1 by auto\nnext\n  fix q r\n  assume \"degree q < degree p\" and \"degree r < degree p\" and \"p = q * r\"\n  with degree_mult_le[of q r]\n  show thesis by (intro 2, auto)\nqed\n\nlemma irreducible\\<^sub>dD:\n  assumes \"irreducible\\<^sub>d p\"\n  shows \"degree p > 0\" \"\\<And>q r. degree q < degree p \\<Longrightarrow> degree r < degree p \\<Longrightarrow> p \\<noteq> q * r\"\n  using assms unfolding irreducible\\<^sub>d_def by auto\n\n\n\nlemma irreducible\\<^sub>d_factor:\n  fixes p :: \"'a::{comm_semiring_1,semiring_no_zero_divisors} poly\"\n  assumes \"degree p > 0\"\n  shows \"\\<exists> q r. irreducible\\<^sub>d q \\<and> p = q * r \\<and> degree r < degree p\" using assms\nproof (induct \"degree p\" arbitrary: p rule: less_induct)\n  case (less p)\n  show ?case\n  proof (cases \"irreducible\\<^sub>d p\")\n    case False\n    with less(2) obtain q r\n    where q: \"degree q < degree p\" \"degree q > 0\"\n      and r: \"degree r < degree p\" \"degree r > 0\"\n      and p: \"p = q * r\"\n      by auto\n    from less(1)[OF q] obtain s t where IH: \"irreducible\\<^sub>d s\" \"q = s * t\" by auto\n    from p have p: \"p = s * (t * r)\" unfolding IH by (simp add: ac_simps)\n    from less(2) have \"p \\<noteq> 0\" by auto\n    hence \"degree p = degree s + (degree (t * r))\" unfolding p \n      by (subst degree_mult_eq, insert p, auto)\n    with irreducible\\<^sub>dD[OF IH(1)] have \"degree p > degree (t * r)\" by auto\n    with p IH show ?thesis by auto\n  next\n    case True\n    show ?thesis\n      by (rule exI[of _ p], rule exI[of _ 1], insert True less(2), auto)\n  qed\nqed\n\ncontext mult_zero begin (* least class with times and zero *)\n\ndefinition zero_divisor where \"zero_divisor a \\<equiv> \\<exists>b. b \\<noteq> 0 \\<and> a * b = 0\"\n\nlemma zero_divisorI[intro]:\n  assumes \"b \\<noteq> 0\" and \"a * b = 0\" shows \"zero_divisor a\"\n  using assms by (auto simp: zero_divisor_def)\n\nlemma zero_divisorE[elim]:\n  assumes \"zero_divisor a\"\n    and \"\\<And>b. b \\<noteq> 0 \\<Longrightarrow> a * b = 0 \\<Longrightarrow> thesis\"\n  shows thesis\n  using assms by (auto simp: zero_divisor_def)\n\nend\n\nlemma zero_divisor_0[simp]:\n  \"zero_divisor (0::'a::{mult_zero,zero_neq_one})\" (* No need for one! *)\n  by (auto intro!: zero_divisorI[of 1])\n\nlemma not_zero_divisor_1:\n  \"\\<not> zero_divisor (1 :: 'a :: {monoid_mult,mult_zero})\" (* No need for associativity! *)\n  by auto\n\nlemma zero_divisor_iff_eq_0[simp]:\n  fixes a :: \"'a :: {semiring_no_zero_divisors, zero_neq_one}\"\n  shows \"zero_divisor a \\<longleftrightarrow> a = 0\" by auto\n\nlemma mult_eq_0_not_zero_divisor_left[simp]:\n  fixes a b :: \"'a :: mult_zero\"\n  assumes \"\\<not> zero_divisor a\"\n  shows \"a * b = 0 \\<longleftrightarrow> b = 0\"\n  using assms unfolding zero_divisor_def by force\n\nlemma mult_eq_0_not_zero_divisor_right[simp]:\n  fixes a b :: \"'a :: {ab_semigroup_mult,mult_zero}\" (* No need for associativity! *)\n  assumes \"\\<not> zero_divisor b\"\n  shows \"a * b = 0 \\<longleftrightarrow> a = 0\"\n  using assms unfolding zero_divisor_def by (force simp: ac_simps)\n\nlemma degree_smult_not_zero_divisor_left[simp]:\n  assumes \"\\<not> zero_divisor c\"\n  shows \"degree (smult c p) = degree p\"\nproof(cases \"p = 0\")\n  case False\n  then have \"coeff (smult c p) (degree p) \\<noteq> 0\" using assms by auto\n  from le_degree[OF this] degree_smult_le[of c p]\n  show ?thesis by auto\nqed auto\n\nlemma degree_smult_not_zero_divisor_right[simp]:\n  assumes \"\\<not> zero_divisor (lead_coeff p)\"\n  shows \"degree (smult c p) = (if c = 0 then 0 else degree p)\"\nproof(cases \"c = 0\")\n  case False\n  then have \"coeff (smult c p) (degree p) \\<noteq> 0\" using assms by auto\n  from le_degree[OF this] degree_smult_le[of c p]\n  show ?thesis by auto\nqed auto\n\n\nlemma irreducible\\<^sub>d_smult_not_zero_divisor_left:\n  assumes c0: \"\\<not> zero_divisor c\"\n  assumes L: \"irreducible\\<^sub>d (smult c p)\"\n  shows \"irreducible\\<^sub>d p\"\nproof (intro irreducible\\<^sub>dI)\n  from L have \"degree (smult c p) > 0\" by auto\n  also note degree_smult_le\n  finally show \"degree p > 0\" by auto\n  fix q r\n  assume deg_q: \"degree q < degree p\"\n    and deg_r: \"degree r < degree p\"\n    and p_qr: \"p = q * r\"\n  then have 1: \"smult c p = smult c q * r\" by auto\n  note degree_smult_le[of c q]\n  also note deg_q\n  finally have 2: \"degree (smult c q) < degree (smult c p)\" using c0 by auto\n  from deg_r have 3: \"degree r < \\<dots>\" using c0 by auto\n  from irreducible\\<^sub>dD(2)[OF L 2 3] 1 show False by auto\nqed\n\nlemmas irreducible\\<^sub>d_smultI =\n  irreducible\\<^sub>d_smult_not_zero_divisor_left\n  [where 'a = \"'a :: {comm_semiring_1,semiring_no_zero_divisors}\", simplified]\n\nlemma irreducible\\<^sub>d_smult_not_zero_divisor_right:\n  assumes p0: \"\\<not> zero_divisor (lead_coeff p)\" and L: \"irreducible\\<^sub>d (smult c p)\"\n  shows \"irreducible\\<^sub>d p\"\nproof-\n  from L have \"c \\<noteq> 0\" by auto\n  with p0 have [simp]: \"degree (smult c p) = degree p\" by simp\n  show \"irreducible\\<^sub>d p\"\n  proof (intro iffI irreducible\\<^sub>dI conjI)\n    from L show \"degree p > 0\" by auto\n    fix q r\n    assume deg_q: \"degree q < degree p\"\n      and deg_r: \"degree r < degree p\"\n      and p_qr: \"p = q * r\"\n    then have 1: \"smult c p = smult c q * r\" by auto\n    note degree_smult_le[of c q]\n    also note deg_q\n    finally have 2: \"degree (smult c q) < degree (smult c p)\" by simp\n    from deg_r have 3: \"degree r < \\<dots>\" by simp\n    from irreducible\\<^sub>dD(2)[OF L 2 3] 1 show False by auto\n  qed\nqed\n\nlemma zero_divisor_mult_left:\n  fixes a b :: \"'a :: {ab_semigroup_mult, mult_zero}\"\n  assumes \"zero_divisor a\"\n  shows \"zero_divisor (a * b)\"\nproof-\n  from assms obtain c where c0: \"c \\<noteq> 0\" and [simp]: \"a * c = 0\" by auto\n  have \"a * b * c = a * c * b\" by (simp only: ac_simps)\n  with c0 show ?thesis by auto\nqed\n\nlemma zero_divisor_mult_right:\n  fixes a b :: \"'a :: {semigroup_mult, mult_zero}\"\n  assumes \"zero_divisor b\"\n  shows \"zero_divisor (a * b)\"\nproof-\n  from assms obtain c where c0: \"c \\<noteq> 0\" and [simp]: \"b * c = 0\" by auto\n  have \"a * b * c = a * (b * c)\" by (simp only: ac_simps)\n  with c0 show ?thesis by auto\nqed\n\nlemma not_zero_divisor_mult:\n  fixes a b :: \"'a :: {ab_semigroup_mult, mult_zero}\"\n  assumes \"\\<not> zero_divisor (a * b)\"\n  shows \"\\<not> zero_divisor a\" and \"\\<not> zero_divisor b\"\n  using assms by (auto dest: zero_divisor_mult_right zero_divisor_mult_left)\n\nlemma zero_divisor_smult_left:\n  assumes \"zero_divisor a\"\n  shows \"zero_divisor (smult a f)\"\nproof-\n  from assms obtain b where b0: \"b \\<noteq> 0\" and \"a * b = 0\" by auto\n  then have \"smult a f * [:b:] = 0\" by (simp add: ac_simps)\n  with b0 show ?thesis by (auto intro!: zero_divisorI[of \"[:b:]\"])\nqed\n\nlemma unit_not_zero_divisor:\n  fixes a :: \"'a :: {comm_monoid_mult, mult_zero}\"\n  assumes \"a dvd 1\"\n  shows \"\\<not>zero_divisor a\"\nproof\n  from assms obtain b where ab: \"1 = a * b\" by (elim dvdE)\n  assume \"zero_divisor a\"\n  then have \"zero_divisor (1::'a)\" by (unfold ab, intro zero_divisor_mult_left)\n  then show False by auto\nqed\n\n\nlemma linear_irreducible\\<^sub>d: assumes \"degree p = 1\"\n  shows \"irreducible\\<^sub>d p\"\n  by (rule irreducible\\<^sub>dI, insert assms, auto)\n\nlemma irreducible\\<^sub>d_dvd_smult:\n  fixes p :: \"'a::{comm_semiring_1,semiring_no_zero_divisors} poly\"\n  assumes \"degree p > 0\" \"irreducible\\<^sub>d q\" \"p dvd q\"\n  shows \"\\<exists> c. c \\<noteq> 0 \\<and> q = smult c p\"\nproof -\n  from assms obtain r where q: \"q = p * r\" by (elim dvdE, auto)\n  from degree_mult_eq[of p r] assms(1) q\n  have \"\\<not> degree p < degree q\" and nz: \"p \\<noteq> 0\" \"q \\<noteq> 0\"\n    apply (metis assms(2) degree_mult_eq_0 gr_implies_not_zero irreducible\\<^sub>dD(2) less_add_same_cancel2)\n    using assms by auto\n  hence deg: \"degree p \\<ge> degree q\" by auto\n  from \\<open>p dvd q\\<close> obtain k where q: \"q = k * p\" unfolding dvd_def by (auto simp: ac_simps)\n  with nz have \"k \\<noteq> 0\" by auto\n  from deg[unfolded q degree_mult_eq[OF \\<open>k \\<noteq> 0\\<close> \\<open>p \\<noteq> 0\\<close> ]] have \"degree k = 0\" \n    unfolding q by auto \n  then obtain c where k: \"k = [: c :]\" by (metis degree_0_id)\n  with \\<open>k \\<noteq> 0\\<close> have \"c \\<noteq> 0\" by auto\n  have \"q = smult c p\" unfolding q k by simp\n  with \\<open>c \\<noteq> 0\\<close> show ?thesis by auto\nqed\n\nsubsection \\<open>Map over Polynomial Coefficients\\<close>\nlemma map_poly_simps:\n  shows \"map_poly f (pCons c p) =\n    (if c = 0 \\<and> p = 0 then 0 else pCons (f c) (map_poly f p))\"\nproof (cases \"c = 0\")\n  case True note c0 = this show ?thesis\n    proof (cases \"p = 0\")\n      case True thus ?thesis using c0 unfolding map_poly_def by simp\n      next case False thus ?thesis\n        unfolding map_poly_def by auto\n    qed\n  next case False thus ?thesis\n    unfolding map_poly_def by auto\nqed\n\nlemma map_poly_pCons[simp]:\n  assumes \"c \\<noteq> 0 \\<or> p \\<noteq> 0\"\n  shows \"map_poly f (pCons c p) = pCons (f c) (map_poly f p)\"\n  unfolding map_poly_simps using assms by auto\n\nlemma map_poly_map_poly:\n  assumes f0: \"f 0 = 0\"\n  shows \"map_poly f (map_poly g p) = map_poly (f \\<circ> g) p\"\nproof (induct p)\n  case (pCons a p) show ?case\n  proof(cases \"g a \\<noteq> 0 \\<or> map_poly g p \\<noteq> 0\")\n    case True show ?thesis\n      unfolding map_poly_pCons[OF pCons(1)]\n      unfolding map_poly_pCons[OF True]\n      unfolding pCons(2)\n      by simp\n  next\n    case False then show ?thesis\n      unfolding map_poly_pCons[OF pCons(1)]\n      unfolding pCons(2)[symmetric]\n      by (simp add: f0)\n  qed\nqed simp\n\nlemma map_poly_zero:\n  assumes f: \"\\<forall>c. f c = 0 \\<longrightarrow> c = 0\"\n  shows [simp]: \"map_poly f p = 0 \\<longleftrightarrow> p = 0\"\n  by (induct p; auto simp: map_poly_simps f)\n\nlemma map_poly_add:\n  assumes h0: \"h 0 = 0\"\n      and h_add: \"\\<forall>p q. h (p + q) = h p + h q\"\n  shows \"map_poly h (p + q) = map_poly h p + map_poly h q\"\nproof (induct p arbitrary: q)\n  case (pCons a p) note pIH = this\n    show ?case\n    proof(induct \"q\")\n      case (pCons b q) note qIH = this\n        show ?case\n          unfolding map_poly_pCons[OF qIH(1)]\n          unfolding map_poly_pCons[OF pIH(1)]\n          unfolding add_pCons\n          unfolding pIH(2)[symmetric]\n          unfolding h_add[rule_format,symmetric]\n          unfolding map_poly_simps using h0 by auto\n    qed auto\nqed auto\n\nsubsection \\<open>Morphismic properties of @{term \"pCons 0\"}\\<close>\n\nlemma monom_pCons_0_monom:\n  \"monom (pCons 0 (monom a n)) d = map_poly (pCons 0) (monom (monom a n) d)\"\n  apply (induct d)\n  unfolding monom_0 unfolding map_poly_simps apply simp\n  unfolding monom_Suc map_poly_simps by auto\n\nlemma pCons_0_add: \"pCons 0 (p + q) = pCons 0 p + pCons 0 q\" by auto\n\nlemma sum_pCons_0_commute:\n  \"sum (\\<lambda>i. pCons 0 (f i)) S = pCons 0 (sum f S)\"\n  by(induct S rule: infinite_finite_induct;simp)\n\nlemma pCons_0_as_mult:\n  fixes p:: \"'a :: comm_semiring_1 poly\"\n  shows \"pCons 0 p = [:0,1:] * p\" by auto\n\n\n\nsubsection \\<open>Misc\\<close>\n\nfun expand_powers :: \"(nat \\<times> 'a)list \\<Rightarrow> 'a list\" where\n  \"expand_powers [] = []\"\n| \"expand_powers ((Suc n, a) # ps) = a # expand_powers ((n,a) # ps)\"\n| \"expand_powers ((0,a) # ps) = expand_powers ps\"\n\nlemma expand_powers: fixes f :: \"'a \\<Rightarrow> 'b :: comm_ring_1\"\n  shows \"(\\<Prod> (n,a) \\<leftarrow> n_as. f a ^ n) = (\\<Prod> a \\<leftarrow> expand_powers n_as. f a)\"\n  by (rule sym, induct n_as rule: expand_powers.induct, auto)\n\nlemma poly_smult_zero_iff: fixes x :: \"'a :: idom\" \n  shows \"(poly (smult a p) x = 0) = (a = 0 \\<or> poly p x = 0)\"\n  by simp\n\nlemma poly_prod_list_zero_iff: fixes x :: \"'a :: idom\" \n  shows \"(poly (prod_list ps) x = 0) = (\\<exists> p \\<in> set ps. poly p x = 0)\"\n  by (induct ps, auto)\n\nlemma poly_mult_zero_iff: fixes x :: \"'a :: idom\" \n  shows \"(poly (p * q) x = 0) = (poly p x = 0 \\<or> poly q x = 0)\"\n  by simp\n\nlemma poly_power_zero_iff: fixes x :: \"'a :: idom\" \n  shows \"(poly (p^n) x = 0) = (n \\<noteq> 0 \\<and> poly p x = 0)\"\n  by (cases n, auto)\n\n\nlemma sum_monom_0_iff: assumes fin: \"finite S\"\n  and g: \"\\<And> i j. g i = g j \\<Longrightarrow> i = j\"\n  shows \"sum (\\<lambda> i. monom (f i) (g i)) S = 0 \\<longleftrightarrow> (\\<forall> i \\<in> S. f i = 0)\" (is \"?l = ?r\")\nproof -\n  {\n    assume \"\\<not> ?r\"\n    then obtain i where i: \"i \\<in> S\" and fi: \"f i \\<noteq> 0\" by auto\n    let ?g = \"\\<lambda> i. monom (f i) (g i)\"\n    have \"coeff (sum ?g S) (g i) = f i + sum (\\<lambda> j. coeff (?g j) (g i)) (S - {i})\"\n      by (unfold sum.remove[OF fin i], simp add: coeff_sum)\n    also have \"sum (\\<lambda> j. coeff (?g j) (g i)) (S - {i}) = 0\"\n      by (rule sum.neutral, insert g, auto)\n    finally have \"coeff (sum ?g S) (g i) \\<noteq> 0\" using fi by auto\n    hence \"\\<not> ?l\" by auto\n  }\n  thus ?thesis by auto\nqed\n\nlemma degree_prod_list_eq: assumes \"\\<And> p. p \\<in> set ps \\<Longrightarrow> (p :: 'a :: idom poly) \\<noteq> 0\"\n  shows \"degree (prod_list ps) = sum_list (map degree ps)\" using assms\nproof (induct ps)\n  case (Cons p ps)\n  show ?case unfolding prod_list.Cons\n    by (subst degree_mult_eq, insert Cons, auto simp: prod_list_zero_iff)\nqed simp\n\nlemma degree_power_eq: assumes p: \"p \\<noteq> 0\"\n  shows \"degree (p ^ n) = degree (p :: 'a :: idom poly) * n\"\nproof (induct n)\n  case (Suc n)\n  from p have pn: \"p ^ n \\<noteq> 0\" by auto\n  show ?case using degree_mult_eq[OF p pn] Suc by auto\nqed simp\n\nlemma coeff_Poly: \"coeff (Poly xs) i = (nth_default 0 xs i)\"\n  unfolding nth_default_coeffs_eq[of \"Poly xs\", symmetric] coeffs_Poly by simp\n\nlemma rsquarefree_def': \"rsquarefree p = (p \\<noteq> 0 \\<and> (\\<forall>a. order a p \\<le> 1))\"\nproof -\n  have \"\\<And> a. order a p \\<le> 1 \\<longleftrightarrow> order a p = 0 \\<or> order a p = 1\" by linarith\n  thus ?thesis unfolding rsquarefree_def by auto\nqed\n\nlemma order_prod_list: \"(\\<And> p. p \\<in> set ps \\<Longrightarrow> p \\<noteq> 0) \\<Longrightarrow> order x (prod_list ps) = sum_list (map (order x) ps)\"\n  by (induct ps, auto, subst order_mult, auto simp: prod_list_zero_iff)\n\nlemma irreducible\\<^sub>d_dvd_eq:\n  fixes a b :: \"'a::{comm_semiring_1,semiring_no_zero_divisors} poly\"\n  assumes \"irreducible\\<^sub>d a\" and \"irreducible\\<^sub>d b\"\n    and \"a dvd b\"\n    and \"monic a\" and \"monic b\" \n  shows \"a = b\"\n  using assms\n  by (metis (no_types, lifting) coeff_smult degree_smult_eq irreducible\\<^sub>dD(1) irreducible\\<^sub>d_dvd_smult \n    mult.right_neutral smult_1_left)\n\nlemma monic_gcd_dvd:\n  assumes fg: \"f dvd g\" and mon: \"monic f\" and gcd: \"gcd g h \\<in> {1, g}\"\n  shows \"gcd f h \\<in> {1, f}\"\nproof (cases \"coprime g h\")\n  case True\n  with dvd_refl have \"coprime f h\"\n    using fg by (blast intro: coprime_divisors)\n  then show ?thesis\n    by simp\nnext\n  case False\n  with gcd have gcd: \"gcd g h = g\"\n    by (simp add: coprime_iff_gcd_eq_1)\n  with fg have \"f dvd gcd g h\"\n    by simp\n  then have \"f dvd h\"\n    by simp\n  then have \"gcd f h = normalize f\"\n    by (simp add: gcd_proj1_iff)\n  also have \"normalize f = f\"\n    using mon by (rule normalize_monic)\n  finally show ?thesis\n    by simp\nqed\n\nlemma monom_power: \"(monom a b)^n = monom (a^n) (b*n)\" \n  by (induct n, auto simp add: mult_monom)\n\nlemma poly_const_pow: \"[:a:]^b = [:a^b:]\"\n  by (metis Groups.mult_ac(2) monom_0 monom_power mult_zero_right)\n\nlemma degree_pderiv_le: \"degree (pderiv f) \\<le> degree f - 1\" \nproof (rule ccontr)\n  assume \"\\<not> ?thesis\"\n  hence ge: \"degree (pderiv f) \\<ge> Suc (degree f - 1)\" by auto\n  hence \"pderiv f \\<noteq> 0\" by auto\n  hence \"coeff (pderiv f) (degree (pderiv f)) \\<noteq> 0\" by auto\n  from this[unfolded coeff_pderiv]\n  have \"coeff f (Suc (degree (pderiv f))) \\<noteq> 0\" by auto\n  moreover have \"Suc (degree (pderiv f)) > degree f\" using ge by auto\n  ultimately show False by (simp add: coeff_eq_0)\nqed\n\nlemma map_div_is_smult_inverse: \"map_poly (\\<lambda>x. x / (a :: 'a :: field)) p = smult (inverse a) p\" \n  unfolding smult_conv_map_poly\n  by (simp add: divide_inverse_commute)\n\nlemma normalize_poly_old_def:\n  \"normalize (f :: 'a :: {normalization_semidom,field} poly) = smult (inverse (unit_factor (lead_coeff f))) f\"\n  by (simp add: normalize_poly_eq_map_poly map_div_is_smult_inverse)\n\n(* was in Euclidean_Algorithm in Number_Theory before, but has been removed *)\nlemma poly_dvd_antisym:\n  fixes p q :: \"'b::idom poly\"\n  assumes coeff: \"coeff p (degree p) = coeff q (degree q)\"\n  assumes dvd1: \"p dvd q\" and dvd2: \"q dvd p\" shows \"p = q\"\nproof (cases \"p = 0\")\n  case True with coeff show \"p = q\" by simp\nnext\n  case False with coeff have \"q \\<noteq> 0\" by auto\n  have degree: \"degree p = degree q\"\n    using \\<open>p dvd q\\<close> \\<open>q dvd p\\<close> \\<open>p \\<noteq> 0\\<close> \\<open>q \\<noteq> 0\\<close>\n    by (intro order_antisym dvd_imp_degree_le)\n\n  from \\<open>p dvd q\\<close> obtain a where a: \"q = p * a\" ..\n  with \\<open>q \\<noteq> 0\\<close> have \"a \\<noteq> 0\" by auto\n  with degree a \\<open>p \\<noteq> 0\\<close> have \"degree a = 0\"\n    by (simp add: degree_mult_eq)\n  with coeff a show \"p = q\"\n    by (cases a, auto split: if_splits)\nqed\n\nlemma coeff_f_0_code[code_unfold]: \"coeff f 0 = (case coeffs f of [] \\<Rightarrow> 0 | x # _ \\<Rightarrow> x)\" \n  by (cases f, auto simp: cCons_def)\n\nlemma poly_compare_0_code[code_unfold]: \"(f = 0) = (case coeffs f of [] \\<Rightarrow> True | _ \\<Rightarrow> False)\" \n  using coeffs_eq_Nil list.disc_eq_case(1) by blast\n\ntext \\<open>Getting more efficient code for abbreviation @{term lead_coeff}\"\\<close>\n\ndefinition leading_coeff\n  where [code_abbrev, simp]: \"leading_coeff = lead_coeff\" \n\nlemma leading_coeff_code [code]:\n  \"leading_coeff f = (let xs = coeffs f in if xs = [] then 0 else last xs)\"\n  by (simp add: last_coeffs_eq_coeff_degree)\n\nlemma nth_coeffs_coeff: \"i < length (coeffs f) \\<Longrightarrow> coeffs f ! i = coeff f i\"\n  by (metis nth_default_coeffs_eq nth_default_def)\n\nlemma degree_prod_eq_sum_degree:\nfixes A :: \"'a set\"\nand f :: \"'a \\<Rightarrow> 'b::field poly\"\nassumes f0: \"\\<forall>i\\<in>A. f i \\<noteq> 0\"\nshows \"degree (\\<Prod>i\\<in>A. (f i)) = (\\<Sum>i\\<in>A. degree (f i))\"\nusing f0\nproof (induct A rule: infinite_finite_induct)\n  case (insert x A)\n  have \"(\\<Sum>i\\<in>insert x A. degree (f i)) = degree (f x) + (\\<Sum>i\\<in>A. degree (f i))\"\n    by (simp add: insert.hyps(1) insert.hyps(2))\n  also have \"... = degree (f x) + degree (\\<Prod>i\\<in>A. (f i))\"\n    by (simp add: insert.hyps insert.prems)\n  also have \"... = degree (f x * (\\<Prod>i\\<in>A. (f i)))\"\n  proof (rule degree_mult_eq[symmetric])\n    show \"f x \\<noteq> 0\" using insert.prems by auto\n    show \"prod f A \\<noteq> 0\" by (simp add: insert.hyps(1) insert.prems)\n  qed\n  also have \"... = degree (\\<Prod>i\\<in>insert x A. (f i))\"\n    by (simp add: insert.hyps)\n  finally show ?case ..\nqed auto\n\ndefinition monom_mult :: \"nat \\<Rightarrow> 'a :: comm_semiring_1 poly \\<Rightarrow> 'a poly\"\n  where \"monom_mult n f = monom 1 n * f\" \n\nlemma monom_mult_unfold [code_unfold]:\n  \"monom 1 n * f = monom_mult n f\"\n  \"f * monom 1 n = monom_mult n f\" \n  by (auto simp: monom_mult_def ac_simps)\n\nlemma monom_mult_code [code abstract]:\n  \"coeffs (monom_mult n f) = (let xs = coeffs f in\n    if xs = [] then xs else replicate n 0 @ xs)\" \n  by (rule coeffs_eqI)\n    (auto simp add: Let_def monom_mult_def coeff_monom_mult nth_default_append nth_default_coeffs_eq)\n\nlemma coeff_pcompose_monom: fixes f :: \"'a :: comm_ring_1 poly\" \n  assumes n: \"j < n\" \n  shows \"coeff (f \\<circ>\\<^sub>p monom 1 n) (n * i + j) = (if j = 0 then coeff f i else 0)\"     \nproof (induct f arbitrary: i)\n  case (pCons a f i)\n  note d = pcompose_pCons coeff_add coeff_monom_mult coeff_pCons\n  show ?case \n  proof (cases i)\n    case 0\n    show ?thesis unfolding d 0 using n by (cases j, auto)\n  next\n    case (Suc ii)\n    have id: \"n * Suc ii + j - n = n * ii + j\" using n by (simp add: diff_mult_distrib2)\n    have id1: \"(n \\<le> n * Suc ii + j) = True\" by auto\n    have id2: \"(case n * Suc ii + j of 0 \\<Rightarrow> a | Suc x \\<Rightarrow> coeff 0 x) = 0\" using n\n      by (cases \"n * Suc ii + j\", auto)\n    show ?thesis unfolding d Suc id id1 id2 pCons(2) if_True by auto\n  qed\nqed auto\n\nlemma coeff_pcompose_x_pow_n: fixes f :: \"'a :: comm_ring_1 poly\" \n  assumes n: \"n \\<noteq> 0\" \n  shows \"coeff (f \\<circ>\\<^sub>p monom 1 n) (n * i) = coeff f i\"     \n  using coeff_pcompose_monom[of 0 n f i] n by auto\n        \nlemma dvd_dvd_smult: \"a dvd b \\<Longrightarrow> f dvd g \\<Longrightarrow> smult a f dvd smult b g\"\n  unfolding dvd_def by (metis mult_smult_left mult_smult_right smult_smult)\n\ndefinition sdiv_poly :: \"'a :: idom_divide poly \\<Rightarrow> 'a \\<Rightarrow> 'a poly\" where\n  \"sdiv_poly p a = (map_poly (\\<lambda> c. c div a) p)\"  \n\nlemma smult_map_poly: \"smult a = map_poly ((*) a)\"\n  by (rule ext, rule poly_eqI, subst coeff_map_poly, auto)\n  \nlemma smult_exact_sdiv_poly: assumes \"\\<And> c. c \\<in> set (coeffs p) \\<Longrightarrow> a dvd c\"\n  shows \"smult a (sdiv_poly p a) = p\" \n  unfolding smult_map_poly sdiv_poly_def\n  by (subst map_poly_map_poly,simp,rule map_poly_idI, insert assms, auto)\n\nlemma coeff_sdiv_poly: \"coeff (sdiv_poly f a) n = coeff f n div a\" \n  unfolding sdiv_poly_def by (rule coeff_map_poly, auto)    \n\nlemma poly_pinfty_ge:\n  fixes p :: \"real poly\"\n  assumes \"lead_coeff p > 0\" \"degree p \\<noteq> 0\" \n  shows \"\\<exists>n. \\<forall> x \\<ge> n. poly p x \\<ge> b\"\nproof -\n  let ?p = \"p - [:b - lead_coeff p :]\" \n  have id: \"lead_coeff ?p = lead_coeff p\" using assms(2)\n    by (cases p, auto)\n  with assms(1) have \"lead_coeff ?p > 0\" by auto\n  from poly_pinfty_gt_lc[OF this, unfolded id] obtain n\n    where \"\\<And> x. x \\<ge> n \\<Longrightarrow> 0 \\<le> poly p x - b\" by auto\n  thus ?thesis by auto\nqed\n\nlemma pderiv_sum: \"pderiv (sum f I) = sum (\\<lambda> i. (pderiv (f i))) I\" \n  by (induct I rule: infinite_finite_induct, auto simp: pderiv_add)\n\nlemma smult_sum2: \"smult m (\\<Sum>i \\<in> S. f i) = (\\<Sum>i \\<in> S. smult m (f i))\"\n  by (induct S rule: infinite_finite_induct, auto simp add: smult_add_right)\n\nlemma degree_mult_not_eq:\n  \"degree (f * g) \\<noteq> degree f + degree g \\<Longrightarrow> lead_coeff f * lead_coeff g = 0\"\n  by (rule ccontr, auto simp: coeff_mult_degree_sum degree_mult_le le_antisym le_degree)\n\nlemma irreducible\\<^sub>d_multD:\n  fixes a b :: \"'a :: {comm_semiring_1,semiring_no_zero_divisors} poly\"\n  assumes l: \"irreducible\\<^sub>d (a*b)\"\n  shows \"degree a = 0 \\<and> a \\<noteq> 0 \\<and> irreducible\\<^sub>d b \\<or> degree b = 0 \\<and> b \\<noteq> 0 \\<and> irreducible\\<^sub>d a\"\nproof-\n  from l have a0: \"a \\<noteq> 0\" and b0: \"b \\<noteq> 0\" by auto\n  note [simp] = degree_mult_eq[OF this]\n  from l have \"degree a = 0 \\<or> degree b = 0\" apply (unfold irreducible\\<^sub>d_def) by force\n  then show ?thesis\n  proof(elim disjE)\n    assume a: \"degree a = 0\"\n    with l a0 have \"irreducible\\<^sub>d b\"\n      by (simp add: irreducible\\<^sub>d_def)\n        (metis degree_mult_eq degree_mult_eq_0 mult.left_commute plus_nat.add_0)\n    with a a0 show ?thesis by auto\n  next\n    assume b: \"degree b = 0\"\n    with l b0 have \"irreducible\\<^sub>d a\"\n      unfolding irreducible\\<^sub>d_def\n      by (smt add_cancel_left_right degree_mult_eq degree_mult_eq_0 neq0_conv semiring_normalization_rules(16))\n    with b b0 show ?thesis by auto\n  qed\nqed\n\nlemma irreducible_connect_field[simp]:\n  fixes f :: \"'a :: field poly\"\n  shows \"irreducible\\<^sub>d f = irreducible f\" (is \"?l = ?r\")\nproof\n  show \"?r \\<Longrightarrow> ?l\"\n    apply (intro irreducible\\<^sub>dI, force simp:is_unit_iff_degree)\n    by (auto dest!: irreducible_multD simp: poly_dvd_1)\nnext\n  assume l: ?l\n  show ?r\n  proof (rule irreducibleI)\n    from l show \"f \\<noteq> 0\" \"\\<not> is_unit f\" by (auto simp: poly_dvd_1)\n    fix a b assume \"f = a * b\"\n    from l[unfolded this]\n    show \"a dvd 1 \\<or> b dvd 1\" by (auto dest!: irreducible\\<^sub>d_multD simp:is_unit_iff_degree)\n  qed\nqed\n\n\n\nlemma irreducible_smult_field[simp]:\n  fixes c :: \"'a :: field\"\n  shows \"irreducible (smult c p) \\<longleftrightarrow> c \\<noteq> 0 \\<and> irreducible p\" (is \"?L \\<longleftrightarrow> ?R\")\nproof (intro iffI conjI irreducible\\<^sub>d_smult_not_zero_divisor_left[of c p, simplified])\n  assume \"irreducible (smult c p)\"\n  then show \"c \\<noteq> 0\" by auto\nnext\n  assume ?R\n  then have c0: \"c \\<noteq> 0\" and irr: \"irreducible p\" by auto\n  show ?L\n  proof (fold irreducible_connect_field, intro irreducible\\<^sub>dI, unfold degree_smult_eq if_not_P[OF c0])\n    show \"degree p > 0\" using irr by auto\n    fix q r\n    from c0 have \"p = smult (1/c) (smult c p)\" by simp\n    also assume \"smult c p = q * r\"\n    finally have [simp]: \"p = smult (1/c) \\<dots>\".\n    assume main: \"degree q < degree p\" \"degree r < degree p\"\n    have \"\\<not>irreducible\\<^sub>d p\" by (rule reducible\\<^sub>dI, rule exI[of _ \"smult (1/c) q\"], rule exI[of _ r], insert irr c0 main, simp)\n    with irr show False by auto\n  qed\nqed auto\n\nlemma irreducible_monic_factor: fixes p :: \"'a :: field poly\" \n  assumes \"degree p > 0\" \n  shows \"\\<exists> q r. irreducible q \\<and> p = q * r \\<and> monic q\"\nproof -\n  from irreducible\\<^sub>d_factorization_exists[OF assms]\n  obtain fs where \"fs \\<noteq> []\" and \"set fs \\<subseteq> Collect irreducible\" and \"p = prod_list fs\" by auto\n  then have q: \"irreducible (hd fs)\" and p: \"p = hd fs * prod_list (tl fs)\" by (atomize(full), cases fs, auto)\n  define c where \"c = coeff (hd fs) (degree (hd fs))\"\n  from q have c: \"c \\<noteq> 0\" unfolding c_def irreducible\\<^sub>d_def by auto\n  show ?thesis\n    by (rule exI[of _ \"smult (1/c) (hd fs)\"], rule exI[of _ \"smult c (prod_list (tl fs))\"], unfold p,\n    insert q c, auto simp: c_def)\nqed\n\nlemma monic_irreducible_factorization: fixes p :: \"'a :: field poly\" \n  shows \"monic p \\<Longrightarrow> \n  \\<exists> as f. finite as \\<and> p = prod (\\<lambda> a. a ^ Suc (f a)) as \\<and> as \\<subseteq> {q. irreducible q \\<and> monic q}\"\nproof (induct \"degree p\" arbitrary: p rule: less_induct)\n  case (less p)\n  show ?case\n  proof (cases \"degree p > 0\")\n    case False\n    with less(2) have \"p = 1\" by (simp add: coeff_eq_0 poly_eq_iff)\n    thus ?thesis by (intro exI[of _ \"{}\"], auto)\n  next\n    case True\n    from irreducible\\<^sub>d_factor[OF this] obtain q r where p: \"p = q * r\"\n      and q: \"irreducible q\" and deg: \"degree r < degree p\" by auto\n    hence q0: \"q \\<noteq> 0\" by auto\n    define c where \"c = coeff q (degree q)\"\n    let ?q = \"smult (1/c) q\"\n    let ?r = \"smult c r\"\n    from q0 have c: \"c \\<noteq> 0\" \"1 / c \\<noteq> 0\" unfolding c_def by auto\n    hence p: \"p = ?q * ?r\" unfolding p by auto\n    have deg: \"degree ?r < degree p\" using c deg by auto\n    let ?Q = \"{q. irreducible q \\<and> monic (q :: 'a poly)}\"\n    have mon: \"monic ?q\" unfolding c_def using q0 by auto\n    from monic_factor[OF \\<open>monic p\\<close>[unfolded p] this] have \"monic ?r\" .\n    from less(1)[OF deg this] obtain f as\n      where as: \"finite as\" \"?r = (\\<Prod> a \\<in>as. a ^ Suc (f a))\"\n        \"as \\<subseteq> ?Q\" by blast\n    from q c have irred: \"irreducible ?q\" by simp\n    show ?thesis\n    proof (cases \"?q \\<in> as\")\n      case False\n      let ?as = \"insert ?q as\"\n      let ?f = \"\\<lambda> a. if a = ?q then 0 else f a\"\n      have \"p = ?q * (\\<Prod> a \\<in>as. a ^ Suc (f a))\" unfolding p as by simp\n      also have \"(\\<Prod> a \\<in>as. a ^ Suc (f a)) = (\\<Prod> a \\<in>as. a ^ Suc (?f a))\"\n        by (rule prod.cong, insert False, auto)\n      also have \"?q * \\<dots> = (\\<Prod> a \\<in> ?as. a ^ Suc (?f a))\"\n        by (subst prod.insert, insert as False, auto)\n      finally have p: \"p = (\\<Prod> a \\<in> ?as. a ^ Suc (?f a))\" .\n      from as(1) have fin: \"finite ?as\" by auto\n      from as mon irred have Q: \"?as \\<subseteq> ?Q\" by auto\n      from fin p Q show ?thesis \n        by(intro exI[of _ ?as] exI[of _ ?f], auto)\n    next\n      case True\n      let ?f = \"\\<lambda> a. if a = ?q then Suc (f a) else f a\"\n      have \"p = ?q * (\\<Prod> a \\<in>as. a ^ Suc (f a))\" unfolding p as by simp\n      also have \"(\\<Prod> a \\<in>as. a ^ Suc (f a)) = ?q ^ Suc (f ?q) * (\\<Prod> a \\<in>(as - {?q}). a ^ Suc (f a))\"\n        by (subst prod.remove[OF _ True], insert as, auto)\n      also have \"(\\<Prod> a \\<in>(as - {?q}). a ^ Suc (f a)) = (\\<Prod> a \\<in>(as - {?q}). a ^ Suc (?f a))\"\n        by (rule prod.cong, auto)\n      also have \"?q * (?q ^ Suc (f ?q) * \\<dots> ) = ?q ^ Suc (?f ?q) * \\<dots>\"\n        by (simp add: ac_simps)\n      also have \"\\<dots> = (\\<Prod> a \\<in> as. a ^ Suc (?f a))\"\n        by (subst prod.remove[OF _ True], insert as, auto)\n      finally have \"p = (\\<Prod> a \\<in> as. a ^ Suc (?f a))\" .\n      with as show ?thesis \n        by (intro exI[of _ as] exI[of _ ?f], auto)\n    qed\n  qed\nqed\n\nlemma monic_irreducible_gcd: \n  \"monic (f::'a::{field,euclidean_ring_gcd,semiring_gcd_mult_normalize,\n                  normalization_euclidean_semiring_multiplicative} poly) \\<Longrightarrow>\n   irreducible f \\<Longrightarrow> gcd f u \\<in> {1,f}\"\n  by (metis gcd_dvd1 irreducible_altdef insertCI is_unit_gcd_iff poly_dvd_antisym poly_gcd_monic)\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/Missing_Polynomial.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527906914787, "lm_q2_score": 0.8418256412990657, "lm_q1q2_score": 0.7171957043803827}}
{"text": "(* Title:      Matrix Kleene Algebras\n   Author:     Walter Guttmann\n   Maintainer: Walter Guttmann <walter.guttmann at canterbury.ac.nz>\n*)\n\nsection \\<open>Matrix Kleene Algebras\\<close>\n\ntext \\<open>\nThis theory gives a matrix model of Stone-Kleene relation algebras.\nThe main result is that matrices over Kleene algebras form Kleene algebras.\nThe automata-based construction is due to Conway \\<^cite>\\<open>\"Conway1971\"\\<close>.\nAn implementation of the construction in Isabelle/HOL that extends \\<^cite>\\<open>\"ArmstrongGomesStruthWeber2016\"\\<close> was given in \\<^cite>\\<open>\"Asplund2014\"\\<close> without a correctness proof.\n\nFor specifying the size of matrices, Isabelle/HOL's type system requires the use of types, not sets.\nThis creates two issues when trying to implement Conway's recursive construction directly.\nFirst, the matrix size changes for recursive calls, which requires dependent types.\nSecond, some submatrices used in the construction are not square, which requires typed Kleene algebras \\<^cite>\\<open>\"Kozen1998\"\\<close>, that is, categories of Kleene algebras.\n\nBecause these instruments are not available in Isabelle/HOL, we use square matrices with a constant size given by the argument of the Kleene star operation.\nSmaller, possibly rectangular submatrices are identified by two lists of indices: one for the rows to include and one for the columns to include.\nLists are used to make recursive calls deterministic; otherwise sets would be sufficient.\n\\<close>\n\ntheory Matrix_Kleene_Algebras\n\nimports Stone_Relation_Algebras.Matrix_Relation_Algebras Kleene_Relation_Algebras\n\nbegin\n\nsubsection \\<open>Matrix Restrictions\\<close>\n\ntext \\<open>\nIn this section we develop a calculus of matrix restrictions.\nThe restriction of a matrix to specific row and column indices is implemented by the following function, which keeps the size of the matrix and sets all unused entries to \\<open>bot\\<close>.\n\\<close>\n\ndefinition restrict_matrix :: \"'a list \\<Rightarrow> ('a,'b::bot) square \\<Rightarrow> 'a list \\<Rightarrow> ('a,'b) square\" (\"_ \\<langle>_\\<rangle> _\" [90,41,90] 91)\n  where \"restrict_matrix as f bs = (\\<lambda>(i,j) . if List.member as i \\<and> List.member bs j then f (i,j) else bot)\"\n\ntext \\<open>\nThe following function captures Conway's automata-based construction of the Kleene star of a matrix.\nAn index \\<open>k\\<close> is chosen and \\<open>s\\<close> contains all other indices.\nThe matrix is split into four submatrices \\<open>a\\<close>, \\<open>b\\<close>, \\<open>c\\<close>, \\<open>d\\<close> including/not including row/column \\<open>k\\<close>.\nFour matrices are computed containing the entries given by Conway's construction.\nThese four matrices are added to obtain the result.\nAll matrices involved in the function have the same size, but matrix restriction is used to set irrelevant entries to \\<open>bot\\<close>.\n\\<close>\n\nprimrec star_matrix' :: \"'a list \\<Rightarrow> ('a,'b::{star,times,bounded_semilattice_sup_bot}) square \\<Rightarrow> ('a,'b) square\" where\n\"star_matrix' Nil g = mbot\" |\n\"star_matrix' (k#s) g = (\n  let r = [k] in\n  let a = r\\<langle>g\\<rangle>r in\n  let b = r\\<langle>g\\<rangle>s in\n  let c = s\\<langle>g\\<rangle>r in\n  let d = s\\<langle>g\\<rangle>s in\n  let as = r\\<langle>star o a\\<rangle>r in\n  let ds = star_matrix' s d in\n  let e = a \\<oplus> b \\<odot> ds \\<odot> c in\n  let es = r\\<langle>star o e\\<rangle>r in\n  let f = d \\<oplus> c \\<odot> as \\<odot> b in\n  let fs = star_matrix' s f in\n  es \\<oplus> as \\<odot> b \\<odot> fs \\<oplus> ds \\<odot> c \\<odot> es \\<oplus> fs\n)\"\n\ntext \\<open>\nThe Kleene star of the whole matrix is obtained by taking as indices all elements of the underlying type \\<open>'a\\<close>.\nThis is conveniently supplied by the \\<open>enum\\<close> class.\n\\<close>\n\nfun star_matrix :: \"('a::enum,'b::{star,times,bounded_semilattice_sup_bot}) square \\<Rightarrow> ('a,'b) square\" (\"_\\<^sup>\\<odot>\" [100] 100) where \"star_matrix f = star_matrix' (enum_class.enum::'a list) f\"\n\ntext \\<open>\nThe following lemmas deconstruct matrices with non-empty restrictions.\n\\<close>\n\nlemma restrict_empty_left:\n  \"[]\\<langle>f\\<rangle>ls = mbot\"\n  by (unfold restrict_matrix_def List.member_def bot_matrix_def) auto\n\nlemma restrict_empty_right:\n  \"ks\\<langle>f\\<rangle>[] = mbot\"\n  by (unfold restrict_matrix_def List.member_def bot_matrix_def) auto\n\nlemma restrict_nonempty_left:\n  fixes f :: \"('a,'b::bounded_semilattice_sup_bot) square\"\n  shows \"(k#ks)\\<langle>f\\<rangle>ls = [k]\\<langle>f\\<rangle>ls \\<oplus> ks\\<langle>f\\<rangle>ls\"\n  by (unfold restrict_matrix_def List.member_def sup_matrix_def) auto\n\nlemma restrict_nonempty_right:\n  fixes f :: \"('a,'b::bounded_semilattice_sup_bot) square\"\n  shows \"ks\\<langle>f\\<rangle>(l#ls) = ks\\<langle>f\\<rangle>[l] \\<oplus> ks\\<langle>f\\<rangle>ls\"\n  by (unfold restrict_matrix_def List.member_def sup_matrix_def) auto\n\nlemma restrict_nonempty:\n  fixes f :: \"('a,'b::bounded_semilattice_sup_bot) square\"\n  shows \"(k#ks)\\<langle>f\\<rangle>(l#ls) = [k]\\<langle>f\\<rangle>[l] \\<oplus> [k]\\<langle>f\\<rangle>ls \\<oplus> ks\\<langle>f\\<rangle>[l] \\<oplus> ks\\<langle>f\\<rangle>ls\"\n  by (unfold restrict_matrix_def List.member_def sup_matrix_def) auto\n\ntext \\<open>\nThe following predicate captures that two index sets are disjoint.\nThis has consequences for composition and the unit matrix.\n\\<close>\n\nabbreviation \"disjoint ks ls \\<equiv> \\<not>(\\<exists>x . List.member ks x \\<and> List.member ls x)\"\n\nlemma times_disjoint:\n  fixes f g :: \"('a,'b::idempotent_semiring) square\"\n  assumes \"disjoint ls ms\"\n    shows \"ks\\<langle>f\\<rangle>ls \\<odot> ms\\<langle>g\\<rangle>ns = mbot\"\nproof (rule ext, rule prod_cases)\n  fix i j\n  have \"(ks\\<langle>f\\<rangle>ls \\<odot> ms\\<langle>g\\<rangle>ns) (i,j) = (\\<Squnion>\\<^sub>k (ks\\<langle>f\\<rangle>ls) (i,k) * (ms\\<langle>g\\<rangle>ns) (k,j))\"\n    by (simp add: times_matrix_def)\n  also have \"... = (\\<Squnion>\\<^sub>k (if List.member ks i \\<and> List.member ls k then f (i,k) else bot) * (if List.member ms k \\<and> List.member ns j then g (k,j) else bot))\"\n    by (simp add: restrict_matrix_def)\n  also have \"... = (\\<Squnion>\\<^sub>k if List.member ms k \\<and> List.member ns j then bot * g (k,j) else (if List.member ks i \\<and> List.member ls k then f (i,k) else bot) * bot)\"\n    using assms by (auto intro: sup_monoid.sum.cong)\n  also have \"... = (\\<Squnion>\\<^sub>(k::'a) bot)\"\n    by (simp add: sup_monoid.sum.neutral)\n  also have \"... = bot\"\n    by (simp add: eq_iff le_funI)\n  also have \"... = mbot (i,j)\"\n    by (simp add: bot_matrix_def)\n  finally show \"(ks\\<langle>f\\<rangle>ls \\<odot> ms\\<langle>g\\<rangle>ns) (i,j) = mbot (i,j)\"\n    .\nqed\n\nlemma one_disjoint:\n  assumes \"disjoint ks ls\"\n    shows \"ks\\<langle>(mone::('a,'b::idempotent_semiring) square)\\<rangle>ls = mbot\"\nproof (rule ext, rule prod_cases)\n  let ?o = \"mone::('a,'b) square\"\n  fix i j\n  have \"(ks\\<langle>?o\\<rangle>ls) (i,j) = (if List.member ks i \\<and> List.member ls j then if i = j then 1 else bot else bot)\"\n    by (simp add: restrict_matrix_def one_matrix_def)\n  also have \"... = bot\"\n    using assms by auto\n  also have \"... = mbot (i,j)\"\n    by (simp add: bot_matrix_def)\n  finally show \"(ks\\<langle>?o\\<rangle>ls) (i,j) = mbot (i,j)\"\n    .\nqed\n\ntext \\<open>\nThe following predicate captures that an index set is a subset of another index set.\nThis has consequences for repeated restrictions.\n\\<close>\n\nabbreviation \"is_sublist ks ls \\<equiv> \\<forall>x . List.member ks x \\<longrightarrow> List.member ls x\"\n\nlemma restrict_sublist:\n  assumes \"is_sublist ls ks\"\n      and \"is_sublist ms ns\"\n    shows \"ls\\<langle>ks\\<langle>f\\<rangle>ns\\<rangle>ms = ls\\<langle>f\\<rangle>ms\"\nproof (rule ext, rule prod_cases)\n  fix i j\n  show \"(ls\\<langle>ks\\<langle>f\\<rangle>ns\\<rangle>ms) (i,j) = (ls\\<langle>f\\<rangle>ms) (i,j)\"\n  proof (cases \"List.member ls i \\<and> List.member ms j\")\n    case True thus ?thesis\n      by (simp add: assms restrict_matrix_def)\n  next\n    case False thus ?thesis\n      by (unfold restrict_matrix_def) auto\n  qed\nqed\n\nlemma restrict_superlist:\n  assumes \"is_sublist ls ks\"\n      and \"is_sublist ms ns\"\n    shows \"ks\\<langle>ls\\<langle>f\\<rangle>ms\\<rangle>ns = ls\\<langle>f\\<rangle>ms\"\nproof (rule ext, rule prod_cases)\n  fix i j\n  show \"(ks\\<langle>ls\\<langle>f\\<rangle>ms\\<rangle>ns) (i,j) = (ls\\<langle>f\\<rangle>ms) (i,j)\"\n  proof (cases \"List.member ls i \\<and> List.member ms j\")\n    case True thus ?thesis\n      by (simp add: assms restrict_matrix_def)\n  next\n    case False thus ?thesis\n      by (unfold restrict_matrix_def) auto\n  qed\nqed\n\ntext \\<open>\nThe following lemmas give the sizes of the results of some matrix operations.\n\\<close>\n\nlemma restrict_sup:\n  fixes f g :: \"('a,'b::bounded_semilattice_sup_bot) square\"\n  shows \"ks\\<langle>f \\<oplus> g\\<rangle>ls = ks\\<langle>f\\<rangle>ls \\<oplus> ks\\<langle>g\\<rangle>ls\"\n  by (unfold restrict_matrix_def sup_matrix_def) auto\n\nlemma restrict_times:\n  fixes f g :: \"('a,'b::idempotent_semiring) square\"\n  shows \"ks\\<langle>ks\\<langle>f\\<rangle>ls \\<odot> ls\\<langle>g\\<rangle>ms\\<rangle>ms = ks\\<langle>f\\<rangle>ls \\<odot> ls\\<langle>g\\<rangle>ms\"\nproof (rule ext, rule prod_cases)\n  fix i j\n  have \"(ks\\<langle>(ks\\<langle>f\\<rangle>ls \\<odot> ls\\<langle>g\\<rangle>ms)\\<rangle>ms) (i,j) = (if List.member ks i \\<and> List.member ms j then (\\<Squnion>\\<^sub>k (ks\\<langle>f\\<rangle>ls) (i,k) * (ls\\<langle>g\\<rangle>ms) (k,j)) else bot)\"\n    by (simp add: times_matrix_def restrict_matrix_def)\n  also have \"... = (if List.member ks i \\<and> List.member ms j then (\\<Squnion>\\<^sub>k (if List.member ks i \\<and> List.member ls k then f (i,k) else bot) * (if List.member ls k \\<and> List.member ms j then g (k,j) else bot)) else bot)\"\n    by (simp add: restrict_matrix_def)\n  also have \"... = (if List.member ks i \\<and> List.member ms j then (\\<Squnion>\\<^sub>k if List.member ls k then f (i,k) * g (k,j) else bot) else bot)\"\n    by (auto intro: sup_monoid.sum.cong)\n  also have \"... = (\\<Squnion>\\<^sub>k if List.member ks i \\<and> List.member ms j then (if List.member ls k then f (i,k) * g (k,j) else bot) else bot)\"\n    by auto\n  also have \"... = (\\<Squnion>\\<^sub>k (if List.member ks i \\<and> List.member ls k then f (i,k) else bot) * (if List.member ls k \\<and> List.member ms j then g (k,j) else bot))\"\n    by (auto intro: sup_monoid.sum.cong)\n  also have \"... = (\\<Squnion>\\<^sub>k (ks\\<langle>f\\<rangle>ls) (i,k) * (ls\\<langle>g\\<rangle>ms) (k,j))\"\n    by (simp add: restrict_matrix_def)\n  also have \"... = (ks\\<langle>f\\<rangle>ls \\<odot> ls\\<langle>g\\<rangle>ms) (i,j)\"\n    by (simp add: times_matrix_def)\n  finally show \"(ks\\<langle>(ks\\<langle>f\\<rangle>ls \\<odot> ls\\<langle>g\\<rangle>ms)\\<rangle>ms) (i,j) = (ks\\<langle>f\\<rangle>ls \\<odot> ls\\<langle>g\\<rangle>ms) (i,j)\"\n    .\nqed\n\nlemma restrict_star:\n  fixes g :: \"('a,'b::kleene_algebra) square\"\n  shows \"t\\<langle>star_matrix' t g\\<rangle>t = star_matrix' t g\"\nproof (induct arbitrary: g rule: list.induct)\n  case Nil show ?case\n    by (simp add: restrict_empty_left)\nnext\n  case (Cons k s)\n  let ?t = \"k#s\"\n  assume \"\\<And>g::('a,'b) square . s\\<langle>star_matrix' s g\\<rangle>s = star_matrix' s g\"\n  hence 1: \"\\<And>g::('a,'b) square . ?t\\<langle>star_matrix' s g\\<rangle>?t = star_matrix' s g\"\n    by (metis member_rec(1) restrict_superlist)\n  show \"?t\\<langle>star_matrix' ?t g\\<rangle>?t = star_matrix' ?t g\"\n  proof -\n    let ?r = \"[k]\"\n    let ?a = \"?r\\<langle>g\\<rangle>?r\"\n    let ?b = \"?r\\<langle>g\\<rangle>s\"\n    let ?c = \"s\\<langle>g\\<rangle>?r\"\n    let ?d = \"s\\<langle>g\\<rangle>s\"\n    let ?as = \"?r\\<langle>star o ?a\\<rangle>?r\"\n    let ?ds = \"star_matrix' s ?d\"\n    let ?e = \"?a \\<oplus> ?b \\<odot> ?ds \\<odot> ?c\"\n    let ?es = \"?r\\<langle>star o ?e\\<rangle>?r\"\n    let ?f = \"?d \\<oplus> ?c \\<odot> ?as \\<odot> ?b\"\n    let ?fs = \"star_matrix' s ?f\"\n    have 2: \"?t\\<langle>?as\\<rangle>?t = ?as \\<and> ?t\\<langle>?b\\<rangle>?t = ?b \\<and> ?t\\<langle>?c\\<rangle>?t = ?c \\<and> ?t\\<langle>?es\\<rangle>?t = ?es\"\n      by (simp add: restrict_superlist member_def)\n    have 3: \"?t\\<langle>?ds\\<rangle>?t = ?ds \\<and> ?t\\<langle>?fs\\<rangle>?t = ?fs\"\n      using 1 by simp\n    have 4: \"?t\\<langle>?t\\<langle>?as\\<rangle>?t \\<odot> ?t\\<langle>?b\\<rangle>?t \\<odot> ?t\\<langle>?fs\\<rangle>?t\\<rangle>?t = ?t\\<langle>?as\\<rangle>?t \\<odot> ?t\\<langle>?b\\<rangle>?t \\<odot> ?t\\<langle>?fs\\<rangle>?t\"\n      by (metis (no_types) restrict_times)\n    have 5: \"?t\\<langle>?t\\<langle>?ds\\<rangle>?t \\<odot> ?t\\<langle>?c\\<rangle>?t \\<odot> ?t\\<langle>?es\\<rangle>?t\\<rangle>?t = ?t\\<langle>?ds\\<rangle>?t \\<odot> ?t\\<langle>?c\\<rangle>?t \\<odot> ?t\\<langle>?es\\<rangle>?t\"\n      by (metis (no_types) restrict_times)\n    have \"?t\\<langle>star_matrix' ?t g\\<rangle>?t = ?t\\<langle>?es \\<oplus> ?as \\<odot> ?b \\<odot> ?fs \\<oplus> ?ds \\<odot> ?c \\<odot> ?es \\<oplus> ?fs\\<rangle>?t\"\n      by (metis star_matrix'.simps(2))\n    also have \"... = ?t\\<langle>?es\\<rangle>?t \\<oplus> ?t\\<langle>?as \\<odot> ?b \\<odot> ?fs\\<rangle>?t \\<oplus> ?t\\<langle>?ds \\<odot> ?c \\<odot> ?es\\<rangle>?t \\<oplus> ?t\\<langle>?fs\\<rangle>?t\"\n      by (simp add: restrict_sup)\n    also have \"... = ?es \\<oplus> ?as \\<odot> ?b \\<odot> ?fs \\<oplus> ?ds \\<odot> ?c \\<odot> ?es \\<oplus> ?fs\"\n      using 2 3 4 5 by simp\n    also have \"... = star_matrix' ?t g\"\n      by (metis star_matrix'.simps(2))\n    finally show ?thesis\n      .\n  qed\nqed\n\nlemma restrict_one:\n  assumes \"\\<not> List.member ks k\"\n    shows \"(k#ks)\\<langle>(mone::('a,'b::idempotent_semiring) square)\\<rangle>(k#ks) = [k]\\<langle>mone\\<rangle>[k] \\<oplus> ks\\<langle>mone\\<rangle>ks\"\n  by (subst restrict_nonempty) (simp add: assms member_rec one_disjoint)\n\nlemma restrict_one_left_unit:\n  \"ks\\<langle>(mone::('a::finite,'b::idempotent_semiring) square)\\<rangle>ks \\<odot> ks\\<langle>f\\<rangle>ls = ks\\<langle>f\\<rangle>ls\"\nproof (rule ext, rule prod_cases)\n  let ?o = \"mone::('a,'b::idempotent_semiring) square\"\n  fix i j\n  have \"(ks\\<langle>?o\\<rangle>ks \\<odot> ks\\<langle>f\\<rangle>ls) (i,j) = (\\<Squnion>\\<^sub>k (ks\\<langle>?o\\<rangle>ks) (i,k) * (ks\\<langle>f\\<rangle>ls) (k,j))\"\n    by (simp add: times_matrix_def)\n  also have \"... = (\\<Squnion>\\<^sub>k (if List.member ks i \\<and> List.member ks k then ?o (i,k) else bot) * (if List.member ks k \\<and> List.member ls j then f (k,j) else bot))\"\n    by (simp add: restrict_matrix_def)\n  also have \"... = (\\<Squnion>\\<^sub>k (if List.member ks i \\<and> List.member ks k then (if i = k then 1 else bot) else bot) * (if List.member ks k \\<and> List.member ls j then f (k,j) else bot))\"\n    by (unfold one_matrix_def) auto\n  also have \"... = (\\<Squnion>\\<^sub>k (if i = k then (if List.member ks i then 1 else bot) else bot) * (if List.member ks k \\<and> List.member ls j then f (k,j) else bot))\"\n    by (auto intro: sup_monoid.sum.cong)\n  also have \"... = (\\<Squnion>\\<^sub>k if i = k then (if List.member ks i then 1 else bot) * (if List.member ks i \\<and> List.member ls j then f (i,j) else bot) else bot)\"\n    by (rule sup_monoid.sum.cong) simp_all\n  also have \"... = (if List.member ks i then 1 else bot) * (if List.member ks i \\<and> List.member ls j then f (i,j) else bot)\"\n    by simp\n  also have \"... = (if List.member ks i \\<and> List.member ls j then f (i,j) else bot)\"\n    by simp\n  also have \"... = (ks\\<langle>f\\<rangle>ls) (i,j)\"\n    by (simp add: restrict_matrix_def)\n  finally show \"(ks\\<langle>?o\\<rangle>ks \\<odot> ks\\<langle>f\\<rangle>ls) (i,j) = (ks\\<langle>f\\<rangle>ls) (i,j)\"\n    .\nqed\n\ntext \\<open>\nThe following lemmas consider restrictions to singleton index sets.\n\\<close>\n\nlemma restrict_singleton:\n  \"([k]\\<langle>f\\<rangle>[l]) (i,j) = (if i = k \\<and> j = l then f (i,j) else bot)\"\n  by (simp add: restrict_matrix_def List.member_def)\n\nlemma restrict_singleton_list:\n  \"([k]\\<langle>f\\<rangle>ls) (i,j) = (if i = k \\<and> List.member ls j then f (i,j) else bot)\"\n  by (simp add: restrict_matrix_def List.member_def)\n\nlemma restrict_list_singleton:\n  \"(ks\\<langle>f\\<rangle>[l]) (i,j) = (if List.member ks i \\<and> j = l then f (i,j) else bot)\"\n  by (simp add: restrict_matrix_def List.member_def)\n\nlemma restrict_singleton_product:\n  fixes f g :: \"('a::finite,'b::kleene_algebra) square\"\n  shows \"([k]\\<langle>f\\<rangle>[l] \\<odot> [m]\\<langle>g\\<rangle>[n]) (i,j) = (if i = k \\<and> l = m \\<and> j = n then f (i,l) * g (m,j) else bot)\"\nproof -\n  have \"([k]\\<langle>f\\<rangle>[l] \\<odot> [m]\\<langle>g\\<rangle>[n]) (i,j) = (\\<Squnion>\\<^sub>h ([k]\\<langle>f\\<rangle>[l]) (i,h) * ([m]\\<langle>g\\<rangle>[n]) (h,j))\"\n    by (simp add: times_matrix_def)\n  also have \"... = (\\<Squnion>\\<^sub>h (if i = k \\<and> h = l then f (i,h) else bot) * (if h = m \\<and> j = n then g (h,j) else bot))\"\n    by (simp add: restrict_singleton)\n  also have \"... = (\\<Squnion>\\<^sub>h if h = l then (if i = k then f (i,h) else bot) * (if h = m \\<and> j = n then g (h,j) else bot) else bot)\"\n    by (rule sup_monoid.sum.cong) auto\n  also have \"... = (if i = k then f (i,l) else bot) * (if l = m \\<and> j = n then g (l,j) else bot)\"\n    by simp\n  also have \"... = (if i = k \\<and> l = m \\<and> j = n then f (i,l) * g (m,j) else bot)\"\n    by simp\n  finally show ?thesis\n    .\nqed\n\ntext \\<open>\nThe Kleene star unfold law holds for matrices with a single entry on the diagonal.\n\\<close>\n\nlemma restrict_star_unfold:\n  \"[l]\\<langle>(mone::('a::finite,'b::kleene_algebra) square)\\<rangle>[l] \\<oplus> [l]\\<langle>f\\<rangle>[l] \\<odot> [l]\\<langle>star o f\\<rangle>[l] = [l]\\<langle>star o f\\<rangle>[l]\"\nproof (rule ext, rule prod_cases)\n  let ?o = \"mone::('a,'b::kleene_algebra) square\"\n  fix i j\n  have \"([l]\\<langle>?o\\<rangle>[l] \\<oplus> [l]\\<langle>f\\<rangle>[l] \\<odot> [l]\\<langle>star o f\\<rangle>[l]) (i,j) = ([l]\\<langle>?o\\<rangle>[l]) (i,j) \\<squnion> ([l]\\<langle>f\\<rangle>[l] \\<odot> [l]\\<langle>star o f\\<rangle>[l]) (i,j)\"\n    by (simp add: sup_matrix_def)\n  also have \"... = ([l]\\<langle>?o\\<rangle>[l]) (i,j) \\<squnion> (\\<Squnion>\\<^sub>k ([l]\\<langle>f\\<rangle>[l]) (i,k) * ([l]\\<langle>star o f\\<rangle>[l]) (k,j))\"\n    by (simp add: times_matrix_def)\n  also have \"... = ([l]\\<langle>?o\\<rangle>[l]) (i,j) \\<squnion> (\\<Squnion>\\<^sub>k (if i = l \\<and> k = l then f (i,k) else bot) * (if k = l \\<and> j = l then (f (k,j))\\<^sup>\\<star> else bot))\"\n    by (simp add: restrict_singleton o_def)\n  also have \"... = ([l]\\<langle>?o\\<rangle>[l]) (i,j) \\<squnion> (\\<Squnion>\\<^sub>k if k = l then (if i = l then f (i,k) else bot) * (if j = l then (f (k,j))\\<^sup>\\<star> else bot) else bot)\"\n    apply (rule arg_cong2[where f=sup])\n    apply simp\n    by (rule sup_monoid.sum.cong) auto\n  also have \"... = ([l]\\<langle>?o\\<rangle>[l]) (i,j) \\<squnion> (if i = l then f (i,l) else bot) * (if j = l then (f (l,j))\\<^sup>\\<star> else bot)\"\n    by simp\n  also have \"... = (if i = l \\<and> j = l then 1 \\<squnion> f (l,l) * (f (l,l))\\<^sup>\\<star> else bot)\"\n    by (simp add: restrict_singleton one_matrix_def)\n  also have \"... = (if i = l \\<and> j = l then (f (l,l))\\<^sup>\\<star> else bot)\"\n    by (simp add: star_left_unfold_equal)\n  also have \"... = ([l]\\<langle>star o f\\<rangle>[l]) (i,j)\"\n    by (simp add: restrict_singleton o_def)\n  finally show \"([l]\\<langle>?o\\<rangle>[l] \\<oplus> [l]\\<langle>f\\<rangle>[l] \\<odot> [l]\\<langle>star o f\\<rangle>[l]) (i,j) = ([l]\\<langle>star o f\\<rangle>[l]) (i,j)\"\n    .\nqed\n\nlemma restrict_all:\n  \"enum_class.enum\\<langle>f\\<rangle>enum_class.enum = f\"\n  by (simp add: restrict_matrix_def List.member_def enum_UNIV)\n\ntext \\<open>\nThe following shows the various components of a matrix product.\nIt is essentially a recursive implementation of the product.\n\\<close>\n\nlemma restrict_nonempty_product:\n  fixes f g :: \"('a::finite,'b::idempotent_semiring) square\"\n  assumes \"\\<not> List.member ls l\"\n    shows \"(k#ks)\\<langle>f\\<rangle>(l#ls) \\<odot> (l#ls)\\<langle>g\\<rangle>(m#ms) = ([k]\\<langle>f\\<rangle>[l] \\<odot> [l]\\<langle>g\\<rangle>[m] \\<oplus> [k]\\<langle>f\\<rangle>ls \\<odot> ls\\<langle>g\\<rangle>[m]) \\<oplus> ([k]\\<langle>f\\<rangle>[l] \\<odot> [l]\\<langle>g\\<rangle>ms \\<oplus> [k]\\<langle>f\\<rangle>ls \\<odot> ls\\<langle>g\\<rangle>ms) \\<oplus> (ks\\<langle>f\\<rangle>[l] \\<odot> [l]\\<langle>g\\<rangle>[m] \\<oplus> ks\\<langle>f\\<rangle>ls \\<odot> ls\\<langle>g\\<rangle>[m]) \\<oplus> (ks\\<langle>f\\<rangle>[l] \\<odot> [l]\\<langle>g\\<rangle>ms \\<oplus> ks\\<langle>f\\<rangle>ls \\<odot> ls\\<langle>g\\<rangle>ms)\"\nproof -\n  have \"(k#ks)\\<langle>f\\<rangle>(l#ls) \\<odot> (l#ls)\\<langle>g\\<rangle>(m#ms) = ([k]\\<langle>f\\<rangle>[l] \\<oplus> [k]\\<langle>f\\<rangle>ls \\<oplus> ks\\<langle>f\\<rangle>[l] \\<oplus> ks\\<langle>f\\<rangle>ls) \\<odot> ([l]\\<langle>g\\<rangle>[m] \\<oplus> [l]\\<langle>g\\<rangle>ms \\<oplus> ls\\<langle>g\\<rangle>[m] \\<oplus> ls\\<langle>g\\<rangle>ms)\"\n    by (metis restrict_nonempty)\n  also have \"... = [k]\\<langle>f\\<rangle>[l] \\<odot> ([l]\\<langle>g\\<rangle>[m] \\<oplus> [l]\\<langle>g\\<rangle>ms \\<oplus> ls\\<langle>g\\<rangle>[m] \\<oplus> ls\\<langle>g\\<rangle>ms) \\<oplus> [k]\\<langle>f\\<rangle>ls \\<odot> ([l]\\<langle>g\\<rangle>[m] \\<oplus> [l]\\<langle>g\\<rangle>ms \\<oplus> ls\\<langle>g\\<rangle>[m] \\<oplus> ls\\<langle>g\\<rangle>ms) \\<oplus> ks\\<langle>f\\<rangle>[l] \\<odot> ([l]\\<langle>g\\<rangle>[m] \\<oplus> [l]\\<langle>g\\<rangle>ms \\<oplus> ls\\<langle>g\\<rangle>[m] \\<oplus> ls\\<langle>g\\<rangle>ms) \\<oplus> ks\\<langle>f\\<rangle>ls \\<odot> ([l]\\<langle>g\\<rangle>[m] \\<oplus> [l]\\<langle>g\\<rangle>ms \\<oplus> ls\\<langle>g\\<rangle>[m] \\<oplus> ls\\<langle>g\\<rangle>ms)\"\n    by (simp add: matrix_idempotent_semiring.mult_right_dist_sup)\n  also have \"... = ([k]\\<langle>f\\<rangle>[l] \\<odot> [l]\\<langle>g\\<rangle>[m] \\<oplus> [k]\\<langle>f\\<rangle>[l] \\<odot> [l]\\<langle>g\\<rangle>ms \\<oplus> [k]\\<langle>f\\<rangle>[l] \\<odot> ls\\<langle>g\\<rangle>[m] \\<oplus> [k]\\<langle>f\\<rangle>[l] \\<odot> ls\\<langle>g\\<rangle>ms) \\<oplus> ([k]\\<langle>f\\<rangle>ls \\<odot> [l]\\<langle>g\\<rangle>[m] \\<oplus> [k]\\<langle>f\\<rangle>ls \\<odot> [l]\\<langle>g\\<rangle>ms \\<oplus> [k]\\<langle>f\\<rangle>ls \\<odot> ls\\<langle>g\\<rangle>[m] \\<oplus> [k]\\<langle>f\\<rangle>ls \\<odot> ls\\<langle>g\\<rangle>ms) \\<oplus> (ks\\<langle>f\\<rangle>[l] \\<odot> [l]\\<langle>g\\<rangle>[m] \\<oplus> ks\\<langle>f\\<rangle>[l] \\<odot> [l]\\<langle>g\\<rangle>ms \\<oplus> ks\\<langle>f\\<rangle>[l] \\<odot> ls\\<langle>g\\<rangle>[m] \\<oplus> ks\\<langle>f\\<rangle>[l] \\<odot> ls\\<langle>g\\<rangle>ms) \\<oplus> (ks\\<langle>f\\<rangle>ls \\<odot> [l]\\<langle>g\\<rangle>[m] \\<oplus> ks\\<langle>f\\<rangle>ls \\<odot> [l]\\<langle>g\\<rangle>ms \\<oplus> ks\\<langle>f\\<rangle>ls \\<odot> ls\\<langle>g\\<rangle>[m] \\<oplus> ks\\<langle>f\\<rangle>ls \\<odot> ls\\<langle>g\\<rangle>ms)\"\n    by (simp add: matrix_idempotent_semiring.mult_left_dist_sup)\n  also have \"... = ([k]\\<langle>f\\<rangle>[l] \\<odot> [l]\\<langle>g\\<rangle>[m] \\<oplus> [k]\\<langle>f\\<rangle>[l] \\<odot> [l]\\<langle>g\\<rangle>ms) \\<oplus> ([k]\\<langle>f\\<rangle>ls \\<odot> ls\\<langle>g\\<rangle>[m] \\<oplus> [k]\\<langle>f\\<rangle>ls \\<odot> ls\\<langle>g\\<rangle>ms) \\<oplus> (ks\\<langle>f\\<rangle>[l] \\<odot> [l]\\<langle>g\\<rangle>[m] \\<oplus> ks\\<langle>f\\<rangle>[l] \\<odot> [l]\\<langle>g\\<rangle>ms) \\<oplus> (ks\\<langle>f\\<rangle>ls \\<odot> ls\\<langle>g\\<rangle>[m] \\<oplus> ks\\<langle>f\\<rangle>ls \\<odot> ls\\<langle>g\\<rangle>ms)\"\n    using assms by (simp add: List.member_def times_disjoint)\n  also have \"... = ([k]\\<langle>f\\<rangle>[l] \\<odot> [l]\\<langle>g\\<rangle>[m] \\<oplus> [k]\\<langle>f\\<rangle>ls \\<odot> ls\\<langle>g\\<rangle>[m]) \\<oplus> ([k]\\<langle>f\\<rangle>[l] \\<odot> [l]\\<langle>g\\<rangle>ms \\<oplus> [k]\\<langle>f\\<rangle>ls \\<odot> ls\\<langle>g\\<rangle>ms) \\<oplus> (ks\\<langle>f\\<rangle>[l] \\<odot> [l]\\<langle>g\\<rangle>[m] \\<oplus> ks\\<langle>f\\<rangle>ls \\<odot> ls\\<langle>g\\<rangle>[m]) \\<oplus> (ks\\<langle>f\\<rangle>[l] \\<odot> [l]\\<langle>g\\<rangle>ms \\<oplus> ks\\<langle>f\\<rangle>ls \\<odot> ls\\<langle>g\\<rangle>ms)\"\n    by (simp add: matrix_bounded_semilattice_sup_bot.sup_monoid.add_assoc matrix_semilattice_sup.sup_left_commute)\n  finally show ?thesis\n    .\nqed\n\ntext \\<open>\nEquality of matrices is componentwise.\n\\<close>\n\nlemma restrict_nonempty_eq:\n  \"(k#ks)\\<langle>f\\<rangle>(l#ls) = (k#ks)\\<langle>g\\<rangle>(l#ls) \\<longleftrightarrow> [k]\\<langle>f\\<rangle>[l] = [k]\\<langle>g\\<rangle>[l] \\<and> [k]\\<langle>f\\<rangle>ls = [k]\\<langle>g\\<rangle>ls \\<and> ks\\<langle>f\\<rangle>[l] = ks\\<langle>g\\<rangle>[l] \\<and> ks\\<langle>f\\<rangle>ls = ks\\<langle>g\\<rangle>ls\"\nproof\n  assume 1: \"(k#ks)\\<langle>f\\<rangle>(l#ls) = (k#ks)\\<langle>g\\<rangle>(l#ls)\"\n  have 2: \"is_sublist [k] (k#ks) \\<and> is_sublist ks (k#ks) \\<and> is_sublist [l] (l#ls) \\<and> is_sublist ls (l#ls)\"\n    by (simp add: member_rec)\n  hence \"[k]\\<langle>f\\<rangle>[l] = [k]\\<langle>(k#ks)\\<langle>f\\<rangle>(l#ls)\\<rangle>[l] \\<and> [k]\\<langle>f\\<rangle>ls = [k]\\<langle>(k#ks)\\<langle>f\\<rangle>(l#ls)\\<rangle>ls \\<and> ks\\<langle>f\\<rangle>[l] = ks\\<langle>(k#ks)\\<langle>f\\<rangle>(l#ls)\\<rangle>[l] \\<and> ks\\<langle>f\\<rangle>ls = ks\\<langle>(k#ks)\\<langle>f\\<rangle>(l#ls)\\<rangle>ls\"\n    by (simp add: restrict_sublist)\n  thus \"[k]\\<langle>f\\<rangle>[l] = [k]\\<langle>g\\<rangle>[l] \\<and> [k]\\<langle>f\\<rangle>ls = [k]\\<langle>g\\<rangle>ls \\<and> ks\\<langle>f\\<rangle>[l] = ks\\<langle>g\\<rangle>[l] \\<and> ks\\<langle>f\\<rangle>ls = ks\\<langle>g\\<rangle>ls\"\n    using 1 2 by (simp add: restrict_sublist)\nnext\n  assume 3: \"[k]\\<langle>f\\<rangle>[l] = [k]\\<langle>g\\<rangle>[l] \\<and> [k]\\<langle>f\\<rangle>ls = [k]\\<langle>g\\<rangle>ls \\<and> ks\\<langle>f\\<rangle>[l] = ks\\<langle>g\\<rangle>[l] \\<and> ks\\<langle>f\\<rangle>ls = ks\\<langle>g\\<rangle>ls\"\n  show \"(k#ks)\\<langle>f\\<rangle>(l#ls) = (k#ks)\\<langle>g\\<rangle>(l#ls)\"\n  proof (rule ext, rule prod_cases)\n    fix i j\n    have 4: \"f (k,l) = g (k,l)\"\n      using 3 by (metis restrict_singleton)\n    have 5: \"List.member ls j \\<Longrightarrow> f (k,j) = g (k,j)\"\n      using 3 by (metis restrict_singleton_list)\n    have 6: \"List.member ks i \\<Longrightarrow> f (i,l) = g (i,l)\"\n      using 3 by (metis restrict_list_singleton)\n    have \"(ks\\<langle>f\\<rangle>ls) (i,j) = (ks\\<langle>g\\<rangle>ls) (i,j)\"\n      using 3 by simp\n    hence 7: \"List.member ks i \\<Longrightarrow> List.member ls j \\<Longrightarrow> f (i,j) = g (i,j)\"\n      by (simp add: restrict_matrix_def)\n    have \"((k#ks)\\<langle>f\\<rangle>(l#ls)) (i,j) = (if (i = k \\<or> List.member ks i) \\<and> (j = l \\<or> List.member ls j) then f (i,j) else bot)\"\n      by (simp add: restrict_matrix_def List.member_def)\n    also have \"... = (if i = k \\<and> j = l then f (i,j) else if i = k \\<and> List.member ls j then f (i,j) else if List.member ks i \\<and> j = l then f (i,j) else if List.member ks i \\<and> List.member ls j then f (i,j) else bot)\"\n      by auto\n    also have \"... = (if i = k \\<and> j = l then g (i,j) else if i = k \\<and> List.member ls j then g (i,j) else if List.member ks i \\<and> j = l then g (i,j) else if List.member ks i \\<and> List.member ls j then g (i,j) else bot)\"\n      using 4 5 6 7 by simp\n    also have \"... = (if (i = k \\<or> List.member ks i) \\<and> (j = l \\<or> List.member ls j) then g (i,j) else bot)\"\n      by auto\n    also have \"... = ((k#ks)\\<langle>g\\<rangle>(l#ls)) (i,j)\"\n      by (simp add: restrict_matrix_def List.member_def)\n    finally show \"((k#ks)\\<langle>f\\<rangle>(l#ls)) (i,j) = ((k#ks)\\<langle>g\\<rangle>(l#ls)) (i,j)\"\n      .\n  qed\nqed\n\ntext \\<open>\nInequality of matrices is componentwise.\n\\<close>\n\nlemma restrict_nonempty_less_eq:\n  fixes f g :: \"('a,'b::idempotent_semiring) square\"\n  shows \"(k#ks)\\<langle>f\\<rangle>(l#ls) \\<preceq> (k#ks)\\<langle>g\\<rangle>(l#ls) \\<longleftrightarrow> [k]\\<langle>f\\<rangle>[l] \\<preceq> [k]\\<langle>g\\<rangle>[l] \\<and> [k]\\<langle>f\\<rangle>ls \\<preceq> [k]\\<langle>g\\<rangle>ls \\<and> ks\\<langle>f\\<rangle>[l] \\<preceq> ks\\<langle>g\\<rangle>[l] \\<and> ks\\<langle>f\\<rangle>ls \\<preceq> ks\\<langle>g\\<rangle>ls\"\n  by (unfold matrix_semilattice_sup.sup.order_iff) (metis (no_types, lifting) restrict_nonempty_eq restrict_sup)\n\ntext \\<open>\nThe following lemmas treat repeated restrictions to disjoint index sets.\n\\<close>\n\nlemma restrict_disjoint_left:\n  assumes \"disjoint ks ms\"\n    shows \"ms\\<langle>ks\\<langle>f\\<rangle>ls\\<rangle>ns = mbot\"\nproof (rule ext, rule prod_cases)\n  fix i j\n  have \"(ms\\<langle>ks\\<langle>f\\<rangle>ls\\<rangle>ns) (i,j) = (if List.member ms i \\<and> List.member ns j then if List.member ks i \\<and> List.member ls j then f (i,j) else bot else bot)\"\n    by (simp add: restrict_matrix_def)\n  thus \"(ms\\<langle>ks\\<langle>f\\<rangle>ls\\<rangle>ns) (i,j) = mbot (i,j)\"\n    using assms by (simp add: bot_matrix_def)\nqed\n\nlemma restrict_disjoint_right:\n  assumes \"disjoint ls ns\"\n    shows \"ms\\<langle>ks\\<langle>f\\<rangle>ls\\<rangle>ns = mbot\"\nproof (rule ext, rule prod_cases)\n  fix i j\n  have \"(ms\\<langle>ks\\<langle>f\\<rangle>ls\\<rangle>ns) (i,j) = (if List.member ms i \\<and> List.member ns j then if List.member ks i \\<and> List.member ls j then f (i,j) else bot else bot)\"\n    by (simp add: restrict_matrix_def)\n  thus \"(ms\\<langle>ks\\<langle>f\\<rangle>ls\\<rangle>ns) (i,j) = mbot (i,j)\"\n    using assms by (simp add: bot_matrix_def)\nqed\n\ntext \\<open>\nThe following lemma expresses the equality of a matrix and a product of two matrices componentwise.\n\\<close>\n\nlemma restrict_nonempty_product_eq:\n  fixes f g h :: \"('a::finite,'b::idempotent_semiring) square\"\n  assumes \"\\<not> List.member ks k\"\n      and \"\\<not> List.member ls l\"\n      and \"\\<not> List.member ms m\"\n    shows \"(k#ks)\\<langle>f\\<rangle>(l#ls) \\<odot> (l#ls)\\<langle>g\\<rangle>(m#ms) = (k#ks)\\<langle>h\\<rangle>(m#ms) \\<longleftrightarrow> [k]\\<langle>f\\<rangle>[l] \\<odot> [l]\\<langle>g\\<rangle>[m] \\<oplus> [k]\\<langle>f\\<rangle>ls \\<odot> ls\\<langle>g\\<rangle>[m] = [k]\\<langle>h\\<rangle>[m] \\<and> [k]\\<langle>f\\<rangle>[l] \\<odot> [l]\\<langle>g\\<rangle>ms \\<oplus> [k]\\<langle>f\\<rangle>ls \\<odot> ls\\<langle>g\\<rangle>ms = [k]\\<langle>h\\<rangle>ms \\<and> ks\\<langle>f\\<rangle>[l] \\<odot> [l]\\<langle>g\\<rangle>[m] \\<oplus> ks\\<langle>f\\<rangle>ls \\<odot> ls\\<langle>g\\<rangle>[m] = ks\\<langle>h\\<rangle>[m] \\<and> ks\\<langle>f\\<rangle>[l] \\<odot> [l]\\<langle>g\\<rangle>ms \\<oplus> ks\\<langle>f\\<rangle>ls \\<odot> ls\\<langle>g\\<rangle>ms = ks\\<langle>h\\<rangle>ms\"\nproof -\n  have 1: \"disjoint [k] ks \\<and> disjoint [m] ms\"\n    by (simp add: assms(1,3) member_rec)\n  have 2: \"[k]\\<langle>(k#ks)\\<langle>f\\<rangle>(l#ls) \\<odot> (l#ls)\\<langle>g\\<rangle>(m#ms)\\<rangle>[m] = [k]\\<langle>f\\<rangle>[l] \\<odot> [l]\\<langle>g\\<rangle>[m] \\<oplus> [k]\\<langle>f\\<rangle>ls \\<odot> ls\\<langle>g\\<rangle>[m]\"\n  proof -\n    have \"[k]\\<langle>(k#ks)\\<langle>f\\<rangle>(l#ls) \\<odot> (l#ls)\\<langle>g\\<rangle>(m#ms)\\<rangle>[m] = [k]\\<langle>([k]\\<langle>f\\<rangle>[l] \\<odot> [l]\\<langle>g\\<rangle>[m] \\<oplus> [k]\\<langle>f\\<rangle>ls \\<odot> ls\\<langle>g\\<rangle>[m]) \\<oplus> ([k]\\<langle>f\\<rangle>[l] \\<odot> [l]\\<langle>g\\<rangle>ms \\<oplus> [k]\\<langle>f\\<rangle>ls \\<odot> ls\\<langle>g\\<rangle>ms) \\<oplus> (ks\\<langle>f\\<rangle>[l] \\<odot> [l]\\<langle>g\\<rangle>[m] \\<oplus> ks\\<langle>f\\<rangle>ls \\<odot> ls\\<langle>g\\<rangle>[m]) \\<oplus> (ks\\<langle>f\\<rangle>[l] \\<odot> [l]\\<langle>g\\<rangle>ms \\<oplus> ks\\<langle>f\\<rangle>ls \\<odot> ls\\<langle>g\\<rangle>ms)\\<rangle>[m]\"\n      by (simp add: assms(2) restrict_nonempty_product)\n    also have \"... = [k]\\<langle>[k]\\<langle>f\\<rangle>[l] \\<odot> [l]\\<langle>g\\<rangle>[m]\\<rangle>[m] \\<oplus> [k]\\<langle>[k]\\<langle>f\\<rangle>ls \\<odot> ls\\<langle>g\\<rangle>[m]\\<rangle>[m] \\<oplus> [k]\\<langle>[k]\\<langle>f\\<rangle>[l] \\<odot> [l]\\<langle>g\\<rangle>ms\\<rangle>[m] \\<oplus> [k]\\<langle>[k]\\<langle>f\\<rangle>ls \\<odot> ls\\<langle>g\\<rangle>ms\\<rangle>[m] \\<oplus> [k]\\<langle>ks\\<langle>f\\<rangle>[l] \\<odot> [l]\\<langle>g\\<rangle>[m]\\<rangle>[m] \\<oplus> [k]\\<langle>ks\\<langle>f\\<rangle>ls \\<odot> ls\\<langle>g\\<rangle>[m]\\<rangle>[m] \\<oplus> [k]\\<langle>ks\\<langle>f\\<rangle>[l] \\<odot> [l]\\<langle>g\\<rangle>ms\\<rangle>[m] \\<oplus> [k]\\<langle>ks\\<langle>f\\<rangle>ls \\<odot> ls\\<langle>g\\<rangle>ms\\<rangle>[m]\"\n      by (simp add: matrix_bounded_semilattice_sup_bot.sup_monoid.add_assoc restrict_sup)\n    also have \"... = [k]\\<langle>f\\<rangle>[l] \\<odot> [l]\\<langle>g\\<rangle>[m] \\<oplus> [k]\\<langle>f\\<rangle>ls \\<odot> ls\\<langle>g\\<rangle>[m] \\<oplus> [k]\\<langle>[k]\\<langle>[k]\\<langle>f\\<rangle>[l] \\<odot> [l]\\<langle>g\\<rangle>ms\\<rangle>ms\\<rangle>[m] \\<oplus> [k]\\<langle>[k]\\<langle>[k]\\<langle>f\\<rangle>ls \\<odot> ls\\<langle>g\\<rangle>ms\\<rangle>ms\\<rangle>[m] \\<oplus> [k]\\<langle>ks\\<langle>ks\\<langle>f\\<rangle>[l] \\<odot> [l]\\<langle>g\\<rangle>[m]\\<rangle>[m]\\<rangle>[m] \\<oplus> [k]\\<langle>ks\\<langle>ks\\<langle>f\\<rangle>ls \\<odot> ls\\<langle>g\\<rangle>[m]\\<rangle>[m]\\<rangle>[m] \\<oplus> [k]\\<langle>ks\\<langle>ks\\<langle>f\\<rangle>[l] \\<odot> [l]\\<langle>g\\<rangle>ms\\<rangle>ms\\<rangle>[m] \\<oplus> [k]\\<langle>ks\\<langle>ks\\<langle>f\\<rangle>ls \\<odot> ls\\<langle>g\\<rangle>ms\\<rangle>ms\\<rangle>[m]\"\n      by (simp add: restrict_times)\n    also have \"... = [k]\\<langle>f\\<rangle>[l] \\<odot> [l]\\<langle>g\\<rangle>[m] \\<oplus> [k]\\<langle>f\\<rangle>ls \\<odot> ls\\<langle>g\\<rangle>[m]\"\n      using 1 by (metis restrict_disjoint_left restrict_disjoint_right matrix_bounded_semilattice_sup_bot.sup_monoid.add_0_right)\n    finally show ?thesis\n      .\n  qed\n  have 3: \"[k]\\<langle>(k#ks)\\<langle>f\\<rangle>(l#ls) \\<odot> (l#ls)\\<langle>g\\<rangle>(m#ms)\\<rangle>ms = [k]\\<langle>f\\<rangle>[l] \\<odot> [l]\\<langle>g\\<rangle>ms \\<oplus> [k]\\<langle>f\\<rangle>ls \\<odot> ls\\<langle>g\\<rangle>ms\"\n  proof -\n    have \"[k]\\<langle>(k#ks)\\<langle>f\\<rangle>(l#ls) \\<odot> (l#ls)\\<langle>g\\<rangle>(m#ms)\\<rangle>ms = [k]\\<langle>([k]\\<langle>f\\<rangle>[l] \\<odot> [l]\\<langle>g\\<rangle>[m] \\<oplus> [k]\\<langle>f\\<rangle>ls \\<odot> ls\\<langle>g\\<rangle>[m]) \\<oplus> ([k]\\<langle>f\\<rangle>[l] \\<odot> [l]\\<langle>g\\<rangle>ms \\<oplus> [k]\\<langle>f\\<rangle>ls \\<odot> ls\\<langle>g\\<rangle>ms) \\<oplus> (ks\\<langle>f\\<rangle>[l] \\<odot> [l]\\<langle>g\\<rangle>[m] \\<oplus> ks\\<langle>f\\<rangle>ls \\<odot> ls\\<langle>g\\<rangle>[m]) \\<oplus> (ks\\<langle>f\\<rangle>[l] \\<odot> [l]\\<langle>g\\<rangle>ms \\<oplus> ks\\<langle>f\\<rangle>ls \\<odot> ls\\<langle>g\\<rangle>ms)\\<rangle>ms\"\n      by (simp add: assms(2) restrict_nonempty_product)\n    also have \"... = [k]\\<langle>[k]\\<langle>f\\<rangle>[l] \\<odot> [l]\\<langle>g\\<rangle>[m]\\<rangle>ms \\<oplus> [k]\\<langle>[k]\\<langle>f\\<rangle>ls \\<odot> ls\\<langle>g\\<rangle>[m]\\<rangle>ms \\<oplus> [k]\\<langle>[k]\\<langle>f\\<rangle>[l] \\<odot> [l]\\<langle>g\\<rangle>ms\\<rangle>ms \\<oplus> [k]\\<langle>[k]\\<langle>f\\<rangle>ls \\<odot> ls\\<langle>g\\<rangle>ms\\<rangle>ms \\<oplus> [k]\\<langle>ks\\<langle>f\\<rangle>[l] \\<odot> [l]\\<langle>g\\<rangle>[m]\\<rangle>ms \\<oplus> [k]\\<langle>ks\\<langle>f\\<rangle>ls \\<odot> ls\\<langle>g\\<rangle>[m]\\<rangle>ms \\<oplus> [k]\\<langle>ks\\<langle>f\\<rangle>[l] \\<odot> [l]\\<langle>g\\<rangle>ms\\<rangle>ms \\<oplus> [k]\\<langle>ks\\<langle>f\\<rangle>ls \\<odot> ls\\<langle>g\\<rangle>ms\\<rangle>ms\"\n      by (simp add: matrix_bounded_semilattice_sup_bot.sup_monoid.add_assoc restrict_sup)\n    also have \"... = [k]\\<langle>[k]\\<langle>[k]\\<langle>f\\<rangle>[l] \\<odot> [l]\\<langle>g\\<rangle>[m]\\<rangle>[m]\\<rangle>ms \\<oplus> [k]\\<langle>[k]\\<langle>[k]\\<langle>f\\<rangle>ls \\<odot> ls\\<langle>g\\<rangle>[m]\\<rangle>[m]\\<rangle>ms \\<oplus> [k]\\<langle>f\\<rangle>[l] \\<odot> [l]\\<langle>g\\<rangle>ms \\<oplus> [k]\\<langle>f\\<rangle>ls \\<odot> ls\\<langle>g\\<rangle>ms \\<oplus> [k]\\<langle>ks\\<langle>ks\\<langle>f\\<rangle>[l] \\<odot> [l]\\<langle>g\\<rangle>[m]\\<rangle>[m]\\<rangle>ms \\<oplus> [k]\\<langle>ks\\<langle>ks\\<langle>f\\<rangle>ls \\<odot> ls\\<langle>g\\<rangle>[m]\\<rangle>[m]\\<rangle>ms \\<oplus> [k]\\<langle>ks\\<langle>ks\\<langle>f\\<rangle>[l] \\<odot> [l]\\<langle>g\\<rangle>ms\\<rangle>ms\\<rangle>ms \\<oplus> [k]\\<langle>ks\\<langle>ks\\<langle>f\\<rangle>ls \\<odot> ls\\<langle>g\\<rangle>ms\\<rangle>ms\\<rangle>ms\"\n      by (simp add: restrict_times)\n    also have \"... = [k]\\<langle>f\\<rangle>[l] \\<odot> [l]\\<langle>g\\<rangle>ms \\<oplus> [k]\\<langle>f\\<rangle>ls \\<odot> ls\\<langle>g\\<rangle>ms\"\n      using 1 by (metis restrict_disjoint_left restrict_disjoint_right matrix_bounded_semilattice_sup_bot.sup_monoid.add_0_right matrix_bounded_semilattice_sup_bot.sup_monoid.add_0_left)\n    finally show ?thesis\n      .\n  qed\n  have 4: \"ks\\<langle>(k#ks)\\<langle>f\\<rangle>(l#ls) \\<odot> (l#ls)\\<langle>g\\<rangle>(m#ms)\\<rangle>[m] = ks\\<langle>f\\<rangle>[l] \\<odot> [l]\\<langle>g\\<rangle>[m] \\<oplus> ks\\<langle>f\\<rangle>ls \\<odot> ls\\<langle>g\\<rangle>[m]\"\n  proof -\n    have \"ks\\<langle>(k#ks)\\<langle>f\\<rangle>(l#ls) \\<odot> (l#ls)\\<langle>g\\<rangle>(m#ms)\\<rangle>[m] = ks\\<langle>([k]\\<langle>f\\<rangle>[l] \\<odot> [l]\\<langle>g\\<rangle>[m] \\<oplus> [k]\\<langle>f\\<rangle>ls \\<odot> ls\\<langle>g\\<rangle>[m]) \\<oplus> ([k]\\<langle>f\\<rangle>[l] \\<odot> [l]\\<langle>g\\<rangle>ms \\<oplus> [k]\\<langle>f\\<rangle>ls \\<odot> ls\\<langle>g\\<rangle>ms) \\<oplus> (ks\\<langle>f\\<rangle>[l] \\<odot> [l]\\<langle>g\\<rangle>[m] \\<oplus> ks\\<langle>f\\<rangle>ls \\<odot> ls\\<langle>g\\<rangle>[m]) \\<oplus> (ks\\<langle>f\\<rangle>[l] \\<odot> [l]\\<langle>g\\<rangle>ms \\<oplus> ks\\<langle>f\\<rangle>ls \\<odot> ls\\<langle>g\\<rangle>ms)\\<rangle>[m]\"\n      by (simp add: assms(2) restrict_nonempty_product)\n    also have \"... = ks\\<langle>[k]\\<langle>f\\<rangle>[l] \\<odot> [l]\\<langle>g\\<rangle>[m]\\<rangle>[m] \\<oplus> ks\\<langle>[k]\\<langle>f\\<rangle>ls \\<odot> ls\\<langle>g\\<rangle>[m]\\<rangle>[m] \\<oplus> ks\\<langle>[k]\\<langle>f\\<rangle>[l] \\<odot> [l]\\<langle>g\\<rangle>ms\\<rangle>[m] \\<oplus> ks\\<langle>[k]\\<langle>f\\<rangle>ls \\<odot> ls\\<langle>g\\<rangle>ms\\<rangle>[m] \\<oplus> ks\\<langle>ks\\<langle>f\\<rangle>[l] \\<odot> [l]\\<langle>g\\<rangle>[m]\\<rangle>[m] \\<oplus> ks\\<langle>ks\\<langle>f\\<rangle>ls \\<odot> ls\\<langle>g\\<rangle>[m]\\<rangle>[m] \\<oplus> ks\\<langle>ks\\<langle>f\\<rangle>[l] \\<odot> [l]\\<langle>g\\<rangle>ms\\<rangle>[m] \\<oplus> ks\\<langle>ks\\<langle>f\\<rangle>ls \\<odot> ls\\<langle>g\\<rangle>ms\\<rangle>[m]\"\n      by (simp add: matrix_bounded_semilattice_sup_bot.sup_monoid.add_assoc restrict_sup)\n    also have \"... = ks\\<langle>[k]\\<langle>[k]\\<langle>f\\<rangle>[l] \\<odot> [l]\\<langle>g\\<rangle>[m]\\<rangle>[m]\\<rangle>[m] \\<oplus> ks\\<langle>[k]\\<langle>[k]\\<langle>f\\<rangle>ls \\<odot> ls\\<langle>g\\<rangle>[m]\\<rangle>[m]\\<rangle>[m] \\<oplus> ks\\<langle>[k]\\<langle>[k]\\<langle>f\\<rangle>[l] \\<odot> [l]\\<langle>g\\<rangle>ms\\<rangle>ms\\<rangle>[m] \\<oplus> ks\\<langle>[k]\\<langle>[k]\\<langle>f\\<rangle>ls \\<odot> ls\\<langle>g\\<rangle>ms\\<rangle>ms\\<rangle>[m] \\<oplus> ks\\<langle>f\\<rangle>[l] \\<odot> [l]\\<langle>g\\<rangle>[m] \\<oplus> ks\\<langle>f\\<rangle>ls \\<odot> ls\\<langle>g\\<rangle>[m] \\<oplus> ks\\<langle>ks\\<langle>ks\\<langle>f\\<rangle>[l] \\<odot> [l]\\<langle>g\\<rangle>ms\\<rangle>ms\\<rangle>[m] \\<oplus> ks\\<langle>ks\\<langle>ks\\<langle>f\\<rangle>ls \\<odot> ls\\<langle>g\\<rangle>ms\\<rangle>ms\\<rangle>[m]\"\n      by (simp add: restrict_times)\n    also have \"... = ks\\<langle>f\\<rangle>[l] \\<odot> [l]\\<langle>g\\<rangle>[m] \\<oplus> ks\\<langle>f\\<rangle>ls \\<odot> ls\\<langle>g\\<rangle>[m]\"\n      using 1 by (metis restrict_disjoint_left restrict_disjoint_right matrix_bounded_semilattice_sup_bot.sup_monoid.add_0_right matrix_bounded_semilattice_sup_bot.sup_monoid.add_0_left)\n    finally show ?thesis\n      .\n  qed\n  have 5: \"ks\\<langle>(k#ks)\\<langle>f\\<rangle>(l#ls) \\<odot> (l#ls)\\<langle>g\\<rangle>(m#ms)\\<rangle>ms = ks\\<langle>f\\<rangle>[l] \\<odot> [l]\\<langle>g\\<rangle>ms \\<oplus> ks\\<langle>f\\<rangle>ls \\<odot> ls\\<langle>g\\<rangle>ms\"\n  proof -\n    have \"ks\\<langle>(k#ks)\\<langle>f\\<rangle>(l#ls) \\<odot> (l#ls)\\<langle>g\\<rangle>(m#ms)\\<rangle>ms = ks\\<langle>([k]\\<langle>f\\<rangle>[l] \\<odot> [l]\\<langle>g\\<rangle>[m] \\<oplus> [k]\\<langle>f\\<rangle>ls \\<odot> ls\\<langle>g\\<rangle>[m]) \\<oplus> ([k]\\<langle>f\\<rangle>[l] \\<odot> [l]\\<langle>g\\<rangle>ms \\<oplus> [k]\\<langle>f\\<rangle>ls \\<odot> ls\\<langle>g\\<rangle>ms) \\<oplus> (ks\\<langle>f\\<rangle>[l] \\<odot> [l]\\<langle>g\\<rangle>[m] \\<oplus> ks\\<langle>f\\<rangle>ls \\<odot> ls\\<langle>g\\<rangle>[m]) \\<oplus> (ks\\<langle>f\\<rangle>[l] \\<odot> [l]\\<langle>g\\<rangle>ms \\<oplus> ks\\<langle>f\\<rangle>ls \\<odot> ls\\<langle>g\\<rangle>ms)\\<rangle>ms\"\n      by (simp add: assms(2) restrict_nonempty_product)\n    also have \"... = ks\\<langle>[k]\\<langle>f\\<rangle>[l] \\<odot> [l]\\<langle>g\\<rangle>[m]\\<rangle>ms \\<oplus> ks\\<langle>[k]\\<langle>f\\<rangle>ls \\<odot> ls\\<langle>g\\<rangle>[m]\\<rangle>ms \\<oplus> ks\\<langle>[k]\\<langle>f\\<rangle>[l] \\<odot> [l]\\<langle>g\\<rangle>ms\\<rangle>ms \\<oplus> ks\\<langle>[k]\\<langle>f\\<rangle>ls \\<odot> ls\\<langle>g\\<rangle>ms\\<rangle>ms \\<oplus> ks\\<langle>ks\\<langle>f\\<rangle>[l] \\<odot> [l]\\<langle>g\\<rangle>[m]\\<rangle>ms \\<oplus> ks\\<langle>ks\\<langle>f\\<rangle>ls \\<odot> ls\\<langle>g\\<rangle>[m]\\<rangle>ms \\<oplus> ks\\<langle>ks\\<langle>f\\<rangle>[l] \\<odot> [l]\\<langle>g\\<rangle>ms\\<rangle>ms \\<oplus> ks\\<langle>ks\\<langle>f\\<rangle>ls \\<odot> ls\\<langle>g\\<rangle>ms\\<rangle>ms\"\n      by (simp add: matrix_bounded_semilattice_sup_bot.sup_monoid.add_assoc restrict_sup)\n    also have \"... = ks\\<langle>[k]\\<langle>[k]\\<langle>f\\<rangle>[l] \\<odot> [l]\\<langle>g\\<rangle>[m]\\<rangle>[m]\\<rangle>ms \\<oplus> ks\\<langle>[k]\\<langle>[k]\\<langle>f\\<rangle>ls \\<odot> ls\\<langle>g\\<rangle>[m]\\<rangle>[m]\\<rangle>ms \\<oplus> ks\\<langle>[k]\\<langle>[k]\\<langle>f\\<rangle>[l] \\<odot> [l]\\<langle>g\\<rangle>ms\\<rangle>ms\\<rangle>ms \\<oplus> ks\\<langle>[k]\\<langle>[k]\\<langle>f\\<rangle>ls \\<odot> ls\\<langle>g\\<rangle>ms\\<rangle>ms\\<rangle>ms \\<oplus> ks\\<langle>ks\\<langle>ks\\<langle>f\\<rangle>[l] \\<odot> [l]\\<langle>g\\<rangle>[m]\\<rangle>[m]\\<rangle>ms \\<oplus> ks\\<langle>ks\\<langle>ks\\<langle>f\\<rangle>ls \\<odot> ls\\<langle>g\\<rangle>[m]\\<rangle>[m]\\<rangle>ms \\<oplus> ks\\<langle>f\\<rangle>[l] \\<odot> [l]\\<langle>g\\<rangle>ms \\<oplus> ks\\<langle>f\\<rangle>ls \\<odot> ls\\<langle>g\\<rangle>ms\"\n      by (simp add: restrict_times)\n    also have \"... = ks\\<langle>f\\<rangle>[l] \\<odot> [l]\\<langle>g\\<rangle>ms \\<oplus> ks\\<langle>f\\<rangle>ls \\<odot> ls\\<langle>g\\<rangle>ms\"\n      using 1 by (metis restrict_disjoint_left restrict_disjoint_right matrix_bounded_semilattice_sup_bot.sup_monoid.add_0_left)\n    finally show ?thesis\n      .\n  qed\n  have \"(k#ks)\\<langle>f\\<rangle>(l#ls) \\<odot> (l#ls)\\<langle>g\\<rangle>(m#ms) = (k#ks)\\<langle>h\\<rangle>(m#ms) \\<longleftrightarrow> (k#ks)\\<langle>(k#ks)\\<langle>f\\<rangle>(l#ls) \\<odot> (l#ls)\\<langle>g\\<rangle>(m#ms)\\<rangle>(m#ms) = (k#ks)\\<langle>h\\<rangle>(m#ms)\"\n    by (simp add: restrict_times)\n  also have \"... \\<longleftrightarrow> [k]\\<langle>(k#ks)\\<langle>f\\<rangle>(l#ls) \\<odot> (l#ls)\\<langle>g\\<rangle>(m#ms)\\<rangle>[m] = [k]\\<langle>h\\<rangle>[m] \\<and> [k]\\<langle>(k#ks)\\<langle>f\\<rangle>(l#ls) \\<odot> (l#ls)\\<langle>g\\<rangle>(m#ms)\\<rangle>ms = [k]\\<langle>h\\<rangle>ms \\<and> ks\\<langle>(k#ks)\\<langle>f\\<rangle>(l#ls) \\<odot> (l#ls)\\<langle>g\\<rangle>(m#ms)\\<rangle>[m] = ks\\<langle>h\\<rangle>[m] \\<and> ks\\<langle>(k#ks)\\<langle>f\\<rangle>(l#ls) \\<odot> (l#ls)\\<langle>g\\<rangle>(m#ms)\\<rangle>ms = ks\\<langle>h\\<rangle>ms\"\n    by (meson restrict_nonempty_eq)\n  also have \"... \\<longleftrightarrow> [k]\\<langle>f\\<rangle>[l] \\<odot> [l]\\<langle>g\\<rangle>[m] \\<oplus> [k]\\<langle>f\\<rangle>ls \\<odot> ls\\<langle>g\\<rangle>[m] = [k]\\<langle>h\\<rangle>[m] \\<and> [k]\\<langle>f\\<rangle>[l] \\<odot> [l]\\<langle>g\\<rangle>ms \\<oplus> [k]\\<langle>f\\<rangle>ls \\<odot> ls\\<langle>g\\<rangle>ms = [k]\\<langle>h\\<rangle>ms \\<and> ks\\<langle>f\\<rangle>[l] \\<odot> [l]\\<langle>g\\<rangle>[m] \\<oplus> ks\\<langle>f\\<rangle>ls \\<odot> ls\\<langle>g\\<rangle>[m] = ks\\<langle>h\\<rangle>[m] \\<and> ks\\<langle>f\\<rangle>[l] \\<odot> [l]\\<langle>g\\<rangle>ms \\<oplus> ks\\<langle>f\\<rangle>ls \\<odot> ls\\<langle>g\\<rangle>ms = ks\\<langle>h\\<rangle>ms\"\n    using 2 3 4 5 by simp\n  finally show ?thesis\n    by simp\nqed\n\ntext \\<open>\nThe following lemma gives a componentwise characterisation of the inequality of a matrix and a product of two matrices.\n\\<close>\n\nlemma restrict_nonempty_product_less_eq:\n  fixes f g h :: \"('a::finite,'b::idempotent_semiring) square\"\n  assumes \"\\<not> List.member ks k\"\n      and \"\\<not> List.member ls l\"\n      and \"\\<not> List.member ms m\"\n    shows \"(k#ks)\\<langle>f\\<rangle>(l#ls) \\<odot> (l#ls)\\<langle>g\\<rangle>(m#ms) \\<preceq> (k#ks)\\<langle>h\\<rangle>(m#ms) \\<longleftrightarrow> [k]\\<langle>f\\<rangle>[l] \\<odot> [l]\\<langle>g\\<rangle>[m] \\<oplus> [k]\\<langle>f\\<rangle>ls \\<odot> ls\\<langle>g\\<rangle>[m] \\<preceq> [k]\\<langle>h\\<rangle>[m] \\<and> [k]\\<langle>f\\<rangle>[l] \\<odot> [l]\\<langle>g\\<rangle>ms \\<oplus> [k]\\<langle>f\\<rangle>ls \\<odot> ls\\<langle>g\\<rangle>ms \\<preceq> [k]\\<langle>h\\<rangle>ms \\<and> ks\\<langle>f\\<rangle>[l] \\<odot> [l]\\<langle>g\\<rangle>[m] \\<oplus> ks\\<langle>f\\<rangle>ls \\<odot> ls\\<langle>g\\<rangle>[m] \\<preceq> ks\\<langle>h\\<rangle>[m] \\<and> ks\\<langle>f\\<rangle>[l] \\<odot> [l]\\<langle>g\\<rangle>ms \\<oplus> ks\\<langle>f\\<rangle>ls \\<odot> ls\\<langle>g\\<rangle>ms \\<preceq> ks\\<langle>h\\<rangle>ms\"\nproof -\n  have 1: \"[k]\\<langle>(k#ks)\\<langle>f\\<rangle>(l#ls) \\<odot> (l#ls)\\<langle>g\\<rangle>(m#ms)\\<rangle>[m] = [k]\\<langle>f\\<rangle>[l] \\<odot> [l]\\<langle>g\\<rangle>[m] \\<oplus> [k]\\<langle>f\\<rangle>ls \\<odot> ls\\<langle>g\\<rangle>[m]\"\n    by (metis assms restrict_nonempty_product_eq restrict_times)\n  have 2: \"[k]\\<langle>(k#ks)\\<langle>f\\<rangle>(l#ls) \\<odot> (l#ls)\\<langle>g\\<rangle>(m#ms)\\<rangle>ms = [k]\\<langle>f\\<rangle>[l] \\<odot> [l]\\<langle>g\\<rangle>ms \\<oplus> [k]\\<langle>f\\<rangle>ls \\<odot> ls\\<langle>g\\<rangle>ms\"\n    by (metis assms restrict_nonempty_product_eq restrict_times)\n  have 3: \"ks\\<langle>(k#ks)\\<langle>f\\<rangle>(l#ls) \\<odot> (l#ls)\\<langle>g\\<rangle>(m#ms)\\<rangle>[m] = ks\\<langle>f\\<rangle>[l] \\<odot> [l]\\<langle>g\\<rangle>[m] \\<oplus> ks\\<langle>f\\<rangle>ls \\<odot> ls\\<langle>g\\<rangle>[m]\"\n    by (metis assms restrict_nonempty_product_eq restrict_times)\n  have 4: \"ks\\<langle>(k#ks)\\<langle>f\\<rangle>(l#ls) \\<odot> (l#ls)\\<langle>g\\<rangle>(m#ms)\\<rangle>ms = ks\\<langle>f\\<rangle>[l] \\<odot> [l]\\<langle>g\\<rangle>ms \\<oplus> ks\\<langle>f\\<rangle>ls \\<odot> ls\\<langle>g\\<rangle>ms\"\n    by (metis assms restrict_nonempty_product_eq restrict_times)\n  have \"(k#ks)\\<langle>f\\<rangle>(l#ls) \\<odot> (l#ls)\\<langle>g\\<rangle>(m#ms) \\<preceq> (k#ks)\\<langle>h\\<rangle>(m#ms) \\<longleftrightarrow> (k#ks)\\<langle>(k#ks)\\<langle>f\\<rangle>(l#ls) \\<odot> (l#ls)\\<langle>g\\<rangle>(m#ms)\\<rangle>(m#ms) \\<preceq> (k#ks)\\<langle>h\\<rangle>(m#ms)\"\n    by (simp add: restrict_times)\n  also have \"... \\<longleftrightarrow> [k]\\<langle>(k#ks)\\<langle>f\\<rangle>(l#ls) \\<odot> (l#ls)\\<langle>g\\<rangle>(m#ms)\\<rangle>[m] \\<preceq> [k]\\<langle>h\\<rangle>[m] \\<and> [k]\\<langle>(k#ks)\\<langle>f\\<rangle>(l#ls) \\<odot> (l#ls)\\<langle>g\\<rangle>(m#ms)\\<rangle>ms \\<preceq> [k]\\<langle>h\\<rangle>ms \\<and> ks\\<langle>(k#ks)\\<langle>f\\<rangle>(l#ls) \\<odot> (l#ls)\\<langle>g\\<rangle>(m#ms)\\<rangle>[m] \\<preceq> ks\\<langle>h\\<rangle>[m] \\<and> ks\\<langle>(k#ks)\\<langle>f\\<rangle>(l#ls) \\<odot> (l#ls)\\<langle>g\\<rangle>(m#ms)\\<rangle>ms \\<preceq> ks\\<langle>h\\<rangle>ms\"\n    by (meson restrict_nonempty_less_eq)\n  also have \"... \\<longleftrightarrow> [k]\\<langle>f\\<rangle>[l] \\<odot> [l]\\<langle>g\\<rangle>[m] \\<oplus> [k]\\<langle>f\\<rangle>ls \\<odot> ls\\<langle>g\\<rangle>[m] \\<preceq> [k]\\<langle>h\\<rangle>[m] \\<and> [k]\\<langle>f\\<rangle>[l] \\<odot> [l]\\<langle>g\\<rangle>ms \\<oplus> [k]\\<langle>f\\<rangle>ls \\<odot> ls\\<langle>g\\<rangle>ms \\<preceq> [k]\\<langle>h\\<rangle>ms \\<and> ks\\<langle>f\\<rangle>[l] \\<odot> [l]\\<langle>g\\<rangle>[m] \\<oplus> ks\\<langle>f\\<rangle>ls \\<odot> ls\\<langle>g\\<rangle>[m] \\<preceq> ks\\<langle>h\\<rangle>[m] \\<and> ks\\<langle>f\\<rangle>[l] \\<odot> [l]\\<langle>g\\<rangle>ms \\<oplus> ks\\<langle>f\\<rangle>ls \\<odot> ls\\<langle>g\\<rangle>ms \\<preceq> ks\\<langle>h\\<rangle>ms\"\n    using 1 2 3 4 by simp\n  finally show ?thesis\n    by simp\nqed\n\ntext \\<open>\nThe Kleene star induction laws hold for matrices with a single entry on the diagonal.\nThe matrix \\<open>g\\<close> can actually contain a whole row/colum at the appropriate index.\n\\<close>\n\nlemma restrict_star_left_induct:\n  fixes f g :: \"('a::finite,'b::kleene_algebra) square\"\n  shows \"distinct ms \\<Longrightarrow> [l]\\<langle>f\\<rangle>[l] \\<odot> [l]\\<langle>g\\<rangle>ms \\<preceq> [l]\\<langle>g\\<rangle>ms \\<Longrightarrow> [l]\\<langle>star o f\\<rangle>[l] \\<odot> [l]\\<langle>g\\<rangle>ms \\<preceq> [l]\\<langle>g\\<rangle>ms\"\nproof (induct ms)\n  case Nil thus ?case\n    by (simp add: restrict_empty_right)\nnext\n  case (Cons m ms)\n  assume 1: \"distinct ms \\<Longrightarrow> [l]\\<langle>f\\<rangle>[l] \\<odot> [l]\\<langle>g\\<rangle>ms \\<preceq> [l]\\<langle>g\\<rangle>ms \\<Longrightarrow> [l]\\<langle>star o f\\<rangle>[l] \\<odot> [l]\\<langle>g\\<rangle>ms \\<preceq> [l]\\<langle>g\\<rangle>ms\"\n  assume 2: \"distinct (m#ms)\"\n  assume 3: \"[l]\\<langle>f\\<rangle>[l] \\<odot> [l]\\<langle>g\\<rangle>(m#ms) \\<preceq> [l]\\<langle>g\\<rangle>(m#ms)\"\n  have 4: \"[l]\\<langle>f\\<rangle>[l] \\<odot> [l]\\<langle>g\\<rangle>[m] \\<preceq> [l]\\<langle>g\\<rangle>[m] \\<and> [l]\\<langle>f\\<rangle>[l] \\<odot> [l]\\<langle>g\\<rangle>ms \\<preceq> [l]\\<langle>g\\<rangle>ms\"\n    using 2 3 by (metis distinct.simps(2) matrix_semilattice_sup.sup.bounded_iff member_def member_rec(2) restrict_nonempty_product_less_eq)\n  hence 5: \"[l]\\<langle>star o f\\<rangle>[l] \\<odot> [l]\\<langle>g\\<rangle>ms \\<preceq> [l]\\<langle>g\\<rangle>ms\"\n    using 1 2 by simp\n  have \"f (l,l) * g (l,m) \\<le> g (l,m)\"\n    using 4 by (metis restrict_singleton_product restrict_singleton less_eq_matrix_def)\n  hence 6: \"(f (l,l))\\<^sup>\\<star> * g (l,m) \\<le> g (l,m)\"\n    by (simp add: star_left_induct_mult)\n  have \"[l]\\<langle>star o f\\<rangle>[l] \\<odot> [l]\\<langle>g\\<rangle>[m] \\<preceq> [l]\\<langle>g\\<rangle>[m]\"\n  proof (unfold less_eq_matrix_def, rule allI, rule prod_cases)\n    fix i j\n    have \"([l]\\<langle>star o f\\<rangle>[l] \\<odot> [l]\\<langle>g\\<rangle>[m]) (i,j) = (\\<Squnion>\\<^sub>k ([l]\\<langle>star o f\\<rangle>[l]) (i,k) * ([l]\\<langle>g\\<rangle>[m]) (k,j))\"\n      by (simp add: times_matrix_def)\n    also have \"... = (\\<Squnion>\\<^sub>k (if i = l \\<and> k = l then (f (i,k))\\<^sup>\\<star> else bot) * (if k = l \\<and> j = m then g (k,j) else bot))\"\n      by (simp add: restrict_singleton o_def)\n    also have \"... = (\\<Squnion>\\<^sub>k if k = l then (if i = l then (f (i,k))\\<^sup>\\<star> else bot) * (if j = m then g (k,j) else bot) else bot)\"\n      by (rule sup_monoid.sum.cong) auto\n    also have \"... = (if i = l then (f (i,l))\\<^sup>\\<star> else bot) * (if j = m then g (l,j) else bot)\"\n      by simp\n    also have \"... = (if i = l \\<and> j = m then (f (l,l))\\<^sup>\\<star> * g (l,m) else bot)\"\n      by simp\n    also have \"... \\<le> ([l]\\<langle>g\\<rangle>[m]) (i,j)\"\n      using 6 by (simp add: restrict_singleton)\n    finally show \"([l]\\<langle>star o f\\<rangle>[l] \\<odot> [l]\\<langle>g\\<rangle>[m]) (i,j) \\<le> ([l]\\<langle>g\\<rangle>[m]) (i,j)\"\n      .\n  qed\n  thus \"[l]\\<langle>star o f\\<rangle>[l] \\<odot> [l]\\<langle>g\\<rangle>(m#ms) \\<preceq> [l]\\<langle>g\\<rangle>(m#ms)\"\n    using 2 5 by (metis (no_types, opaque_lifting) matrix_idempotent_semiring.mult_left_dist_sup matrix_semilattice_sup.sup.mono restrict_nonempty_right)\nqed\n\nlemma restrict_star_right_induct:\n  fixes f g :: \"('a::finite,'b::kleene_algebra) square\"\n  shows \"distinct ms \\<Longrightarrow> ms\\<langle>g\\<rangle>[l] \\<odot> [l]\\<langle>f\\<rangle>[l] \\<preceq> ms\\<langle>g\\<rangle>[l] \\<Longrightarrow> ms\\<langle>g\\<rangle>[l] \\<odot> [l]\\<langle>star o f\\<rangle>[l] \\<preceq> ms\\<langle>g\\<rangle>[l]\"\nproof (induct ms)\n  case Nil thus ?case\n    by (simp add: restrict_empty_left)\nnext\n  case (Cons m ms)\n  assume 1: \"distinct ms \\<Longrightarrow> ms\\<langle>g\\<rangle>[l] \\<odot> [l]\\<langle>f\\<rangle>[l] \\<preceq> ms\\<langle>g\\<rangle>[l] \\<Longrightarrow> ms\\<langle>g\\<rangle>[l] \\<odot> [l]\\<langle>star o f\\<rangle>[l] \\<preceq> ms\\<langle>g\\<rangle>[l]\"\n  assume 2: \"distinct (m#ms)\"\n  assume 3: \"(m#ms)\\<langle>g\\<rangle>[l] \\<odot> [l]\\<langle>f\\<rangle>[l] \\<preceq> (m#ms)\\<langle>g\\<rangle>[l]\"\n  have 4: \"[m]\\<langle>g\\<rangle>[l] \\<odot> [l]\\<langle>f\\<rangle>[l] \\<preceq> [m]\\<langle>g\\<rangle>[l] \\<and> ms\\<langle>g\\<rangle>[l] \\<odot> [l]\\<langle>f\\<rangle>[l] \\<preceq> ms\\<langle>g\\<rangle>[l]\"\n    using 2 3 by (metis distinct.simps(2) matrix_semilattice_sup.sup.bounded_iff member_def member_rec(2) restrict_nonempty_product_less_eq)\n  hence 5: \"ms\\<langle>g\\<rangle>[l] \\<odot> [l]\\<langle>star o f\\<rangle>[l] \\<preceq> ms\\<langle>g\\<rangle>[l]\"\n    using 1 2  by simp\n  have \"g (m,l) * f (l,l) \\<le> g (m,l)\"\n    using 4 by (metis restrict_singleton_product restrict_singleton less_eq_matrix_def)\n  hence 6: \"g (m,l) * (f (l,l))\\<^sup>\\<star> \\<le> g (m,l)\"\n    by (simp add: star_right_induct_mult)\n  have \"[m]\\<langle>g\\<rangle>[l] \\<odot> [l]\\<langle>star o f\\<rangle>[l] \\<preceq> [m]\\<langle>g\\<rangle>[l]\"\n  proof (unfold less_eq_matrix_def, rule allI, rule prod_cases)\n    fix i j\n    have \"([m]\\<langle>g\\<rangle>[l] \\<odot> [l]\\<langle>star o f\\<rangle>[l]) (i,j) = (\\<Squnion>\\<^sub>k ([m]\\<langle>g\\<rangle>[l]) (i,k) * ([l]\\<langle>star o f\\<rangle>[l]) (k,j))\"\n      by (simp add: times_matrix_def)\n    also have \"... = (\\<Squnion>\\<^sub>k (if i = m \\<and> k = l then g (i,k) else bot) * (if k = l \\<and> j = l then (f (k,j))\\<^sup>\\<star> else bot))\"\n      by (simp add: restrict_singleton o_def)\n    also have \"... = (\\<Squnion>\\<^sub>k if k = l then (if i = m then g (i,k) else bot) * (if j = l then (f (k,j))\\<^sup>\\<star> else bot) else bot)\"\n      by (rule sup_monoid.sum.cong) auto\n    also have \"... = (if i = m then g (i,l) else bot) * (if j = l then (f (l,j))\\<^sup>\\<star> else bot)\"\n      by simp\n    also have \"... = (if i = m \\<and> j = l then g (m,l) * (f (l,l))\\<^sup>\\<star> else bot)\"\n      by simp\n    also have \"... \\<le> ([m]\\<langle>g\\<rangle>[l]) (i,j)\"\n      using 6 by (simp add: restrict_singleton)\n    finally show \"([m]\\<langle>g\\<rangle>[l] \\<odot> [l]\\<langle>star o f\\<rangle>[l]) (i,j) \\<le> ([m]\\<langle>g\\<rangle>[l]) (i,j)\"\n      .\n  qed\n  thus \"(m#ms)\\<langle>g\\<rangle>[l] \\<odot> [l]\\<langle>star o f\\<rangle>[l] \\<preceq> (m#ms)\\<langle>g\\<rangle>[l]\"\n    using 2 5 by (metis (no_types, opaque_lifting) matrix_idempotent_semiring.mult_right_dist_sup matrix_semilattice_sup.sup.mono restrict_nonempty_left)\nqed\n\nlemma restrict_pp:\n  fixes f :: \"('a,'b::p_algebra) square\"\n  shows \"ks\\<langle>\\<ominus>\\<ominus>f\\<rangle>ls = \\<ominus>\\<ominus>(ks\\<langle>f\\<rangle>ls)\"\n  by (unfold restrict_matrix_def uminus_matrix_def) auto\n\nlemma pp_star_commute:\n  fixes f :: \"('a,'b::stone_kleene_relation_algebra) square\"\n  shows \"\\<ominus>\\<ominus>(star o f) = star o \\<ominus>\\<ominus>f\"\n  by (simp add: uminus_matrix_def o_def pp_dist_star)\n\nsubsection \\<open>Matrices form a Kleene Algebra\\<close>\n\ntext \\<open>\nMatrices over Kleene algebras form a Kleene algebra using Conway's construction.\nIt remains to prove one unfold and two induction axioms of the Kleene star.\nEach proof is by induction over the size of the matrix represented by an index list.\n\\<close>\n\ninterpretation matrix_kleene_algebra: kleene_algebra_var where sup = sup_matrix and less_eq = less_eq_matrix and less = less_matrix and bot = \"bot_matrix::('a::enum,'b::kleene_algebra) square\" and one = one_matrix and times = times_matrix and star = star_matrix\nproof\n  fix y :: \"('a,'b) square\"\n  let ?e = \"enum_class.enum::'a list\"\n  let ?o = \"mone :: ('a,'b) square\"\n  have \"\\<forall>g :: ('a,'b) square . distinct ?e \\<longrightarrow> (?e\\<langle>?o\\<rangle>?e \\<oplus> ?e\\<langle>g\\<rangle>?e \\<odot> star_matrix' ?e g) = (star_matrix' ?e g)\"\n  proof (induct rule: list.induct)\n    case Nil thus ?case\n      by (simp add: restrict_empty_left)\n  next\n    case (Cons k s)\n    let ?t = \"k#s\"\n    assume 1: \"\\<forall>g :: ('a,'b) square . distinct s \\<longrightarrow> (s\\<langle>?o\\<rangle>s \\<oplus> s\\<langle>g\\<rangle>s \\<odot> star_matrix' s g) = (star_matrix' s g)\"\n    show \"\\<forall>g :: ('a,'b) square . distinct ?t \\<longrightarrow> (?t\\<langle>?o\\<rangle>?t \\<oplus> ?t\\<langle>g\\<rangle>?t \\<odot> star_matrix' ?t g) = (star_matrix' ?t g)\"\n    proof (rule allI, rule impI)\n      fix g :: \"('a,'b) square\"\n      assume 2: \"distinct ?t\"\n      let ?r = \"[k]\"\n      let ?a = \"?r\\<langle>g\\<rangle>?r\"\n      let ?b = \"?r\\<langle>g\\<rangle>s\"\n      let ?c = \"s\\<langle>g\\<rangle>?r\"\n      let ?d = \"s\\<langle>g\\<rangle>s\"\n      let ?as = \"?r\\<langle>star o ?a\\<rangle>?r\"\n      let ?ds = \"star_matrix' s ?d\"\n      let ?e = \"?a \\<oplus> ?b \\<odot> ?ds \\<odot> ?c\"\n      let ?es = \"?r\\<langle>star o ?e\\<rangle>?r\"\n      let ?f = \"?d \\<oplus> ?c \\<odot> ?as \\<odot> ?b\"\n      let ?fs = \"star_matrix' s ?f\"\n      have \"s\\<langle>?ds\\<rangle>s = ?ds \\<and> s\\<langle>?fs\\<rangle>s = ?fs\"\n        by (simp add: restrict_star)\n      hence 3: \"?r\\<langle>?e\\<rangle>?r = ?e \\<and> s\\<langle>?f\\<rangle>s = ?f\"\n        by (metis (no_types, lifting) restrict_one_left_unit restrict_sup restrict_times)\n      have 4: \"disjoint s ?r \\<and> disjoint ?r s\"\n        using 2 by (simp add: in_set_member member_rec)\n      hence 5: \"?t\\<langle>?o\\<rangle>?t = ?r\\<langle>?o\\<rangle>?r \\<oplus> s\\<langle>?o\\<rangle>s\"\n        by (meson member_rec(1) restrict_one)\n      have 6: \"?t\\<langle>g\\<rangle>?t \\<odot> ?es = ?a \\<odot> ?es \\<oplus> ?c \\<odot> ?es\"\n      proof -\n        have \"?t\\<langle>g\\<rangle>?t \\<odot> ?es = (?a \\<oplus> ?b \\<oplus> ?c \\<oplus> ?d) \\<odot> ?es\"\n          by (metis restrict_nonempty)\n        also have \"... = ?a \\<odot> ?es \\<oplus> ?b \\<odot> ?es \\<oplus> ?c \\<odot> ?es \\<oplus> ?d \\<odot> ?es\"\n          by (simp add: matrix_idempotent_semiring.mult_right_dist_sup)\n        also have \"... = ?a \\<odot> ?es \\<oplus> ?c \\<odot> ?es\"\n          using 4 by (simp add: times_disjoint)\n        finally show ?thesis\n          .\n      qed\n      have 7: \"?t\\<langle>g\\<rangle>?t \\<odot> ?as \\<odot> ?b \\<odot> ?fs = ?a \\<odot> ?as \\<odot> ?b \\<odot> ?fs \\<oplus> ?c \\<odot> ?as \\<odot> ?b \\<odot> ?fs\"\n      proof -\n        have \"?t\\<langle>g\\<rangle>?t \\<odot> ?as \\<odot> ?b \\<odot> ?fs = (?a \\<oplus> ?b \\<oplus> ?c \\<oplus> ?d) \\<odot> ?as \\<odot> ?b \\<odot> ?fs\"\n          by (metis restrict_nonempty)\n        also have \"... = ?a \\<odot> ?as \\<odot> ?b \\<odot> ?fs \\<oplus> ?b \\<odot> ?as \\<odot> ?b \\<odot> ?fs \\<oplus> ?c \\<odot> ?as \\<odot> ?b \\<odot> ?fs \\<oplus> ?d \\<odot> ?as \\<odot> ?b \\<odot> ?fs\"\n          by (simp add: matrix_idempotent_semiring.mult_right_dist_sup)\n        also have \"... = ?a \\<odot> ?as \\<odot> ?b \\<odot> ?fs \\<oplus> ?c \\<odot> ?as \\<odot> ?b \\<odot> ?fs\"\n          using 4 by (simp add: times_disjoint)\n        finally show ?thesis\n          .\n      qed\n      have 8: \"?t\\<langle>g\\<rangle>?t \\<odot> ?ds \\<odot> ?c \\<odot> ?es = ?b \\<odot> ?ds \\<odot> ?c \\<odot> ?es \\<oplus> ?d \\<odot> ?ds \\<odot> ?c \\<odot> ?es\"\n      proof -\n        have \"?t\\<langle>g\\<rangle>?t \\<odot> ?ds \\<odot> ?c \\<odot> ?es = (?a \\<oplus> ?b \\<oplus> ?c \\<oplus> ?d) \\<odot> ?ds \\<odot> ?c \\<odot> ?es\"\n          by (metis restrict_nonempty)\n        also have \"... = ?a \\<odot> ?ds \\<odot> ?c \\<odot> ?es \\<oplus> ?b \\<odot> ?ds \\<odot> ?c \\<odot> ?es \\<oplus> ?c \\<odot> ?ds \\<odot> ?c \\<odot> ?es \\<oplus> ?d \\<odot> ?ds \\<odot> ?c \\<odot> ?es\"\n          by (simp add: matrix_idempotent_semiring.mult_right_dist_sup)\n        also have \"... = ?b \\<odot> ?ds \\<odot> ?c \\<odot> ?es \\<oplus> ?d \\<odot> ?ds \\<odot> ?c \\<odot> ?es\"\n          using 4 by (metis (no_types, lifting) times_disjoint matrix_idempotent_semiring.mult_left_zero restrict_star matrix_bounded_semilattice_sup_bot.sup_monoid.add_0_right matrix_bounded_semilattice_sup_bot.sup_monoid.add_0_left)\n        finally show ?thesis\n          .\n      qed\n      have 9: \"?t\\<langle>g\\<rangle>?t \\<odot> ?fs = ?b \\<odot> ?fs \\<oplus> ?d \\<odot> ?fs\"\n      proof -\n        have \"?t\\<langle>g\\<rangle>?t \\<odot> ?fs = (?a \\<oplus> ?b \\<oplus> ?c \\<oplus> ?d) \\<odot> ?fs\"\n          by (metis restrict_nonempty)\n        also have \"... = ?a \\<odot> ?fs \\<oplus> ?b \\<odot> ?fs \\<oplus> ?c \\<odot> ?fs \\<oplus> ?d \\<odot> ?fs\"\n          by (simp add: matrix_idempotent_semiring.mult_right_dist_sup)\n        also have \"... = ?b \\<odot> ?fs \\<oplus> ?d \\<odot> ?fs\"\n          using 4 by (metis (no_types, lifting) times_disjoint restrict_star matrix_bounded_semilattice_sup_bot.sup_monoid.add_0_right matrix_bounded_semilattice_sup_bot.sup_monoid.add_0_left)\n        finally show ?thesis\n          .\n      qed\n      have \"?t\\<langle>?o\\<rangle>?t \\<oplus> ?t\\<langle>g\\<rangle>?t \\<odot> star_matrix' ?t g = ?t\\<langle>?o\\<rangle>?t \\<oplus> ?t\\<langle>g\\<rangle>?t \\<odot> (?es \\<oplus> ?as \\<odot> ?b \\<odot> ?fs \\<oplus> ?ds \\<odot> ?c \\<odot> ?es \\<oplus> ?fs)\"\n        by (metis star_matrix'.simps(2))\n      also have \"... = ?t\\<langle>?o\\<rangle>?t \\<oplus> ?t\\<langle>g\\<rangle>?t \\<odot> ?es \\<oplus> ?t\\<langle>g\\<rangle>?t \\<odot> ?as \\<odot> ?b \\<odot> ?fs \\<oplus> ?t\\<langle>g\\<rangle>?t \\<odot> ?ds \\<odot> ?c \\<odot> ?es \\<oplus> ?t\\<langle>g\\<rangle>?t \\<odot> ?fs\"\n        by (simp add: matrix_idempotent_semiring.mult_left_dist_sup matrix_monoid.mult_assoc matrix_semilattice_sup.sup_assoc)\n      also have \"... = ?r\\<langle>?o\\<rangle>?r \\<oplus> s\\<langle>?o\\<rangle>s \\<oplus> ?a \\<odot> ?es \\<oplus> ?c \\<odot> ?es \\<oplus> ?a \\<odot> ?as \\<odot> ?b \\<odot> ?fs \\<oplus> ?c \\<odot> ?as \\<odot> ?b \\<odot> ?fs \\<oplus> ?b \\<odot> ?ds \\<odot> ?c \\<odot> ?es \\<oplus> ?d \\<odot> ?ds \\<odot> ?c \\<odot> ?es \\<oplus> ?b \\<odot> ?fs \\<oplus> ?d \\<odot> ?fs\"\n        using 5 6 7 8 9 by (simp add: matrix_semilattice_sup.sup.assoc)\n      also have \"... = (?r\\<langle>?o\\<rangle>?r \\<oplus> (?a \\<odot> ?es \\<oplus> ?b \\<odot> ?ds \\<odot> ?c \\<odot> ?es)) \\<oplus> (?b \\<odot> ?fs \\<oplus> ?a \\<odot> ?as \\<odot> ?b \\<odot> ?fs) \\<oplus> (?c \\<odot> ?es \\<oplus> ?d \\<odot> ?ds \\<odot> ?c \\<odot> ?es) \\<oplus> (s\\<langle>?o\\<rangle>s \\<oplus> (?d \\<odot> ?fs \\<oplus> ?c \\<odot> ?as \\<odot> ?b \\<odot> ?fs))\"\n        by (simp only: matrix_semilattice_sup.sup_assoc matrix_semilattice_sup.sup_commute matrix_semilattice_sup.sup_left_commute)\n      also have \"... = (?r\\<langle>?o\\<rangle>?r \\<oplus> (?a \\<odot> ?es \\<oplus> ?b \\<odot> ?ds \\<odot> ?c \\<odot> ?es)) \\<oplus> (?r\\<langle>?o\\<rangle>?r \\<odot> ?b \\<odot> ?fs \\<oplus> ?a \\<odot> ?as \\<odot> ?b \\<odot> ?fs) \\<oplus> (s\\<langle>?o\\<rangle>s \\<odot> ?c \\<odot> ?es \\<oplus> ?d \\<odot> ?ds \\<odot> ?c \\<odot> ?es) \\<oplus> (s\\<langle>?o\\<rangle>s \\<oplus> (?d \\<odot> ?fs \\<oplus> ?c \\<odot> ?as \\<odot> ?b \\<odot> ?fs))\"\n        by (simp add: restrict_one_left_unit)\n      also have \"... = (?r\\<langle>?o\\<rangle>?r \\<oplus> ?e \\<odot> ?es) \\<oplus> ((?r\\<langle>?o\\<rangle>?r \\<oplus> ?a \\<odot> ?as) \\<odot> ?b \\<odot> ?fs) \\<oplus> ((s\\<langle>?o\\<rangle>s \\<oplus> ?d \\<odot> ?ds) \\<odot> ?c \\<odot> ?es) \\<oplus> (s\\<langle>?o\\<rangle>s \\<oplus> ?f \\<odot> ?fs)\"\n        by (simp add: matrix_idempotent_semiring.mult_right_dist_sup)\n      also have \"... = (?r\\<langle>?o\\<rangle>?r \\<oplus> ?e \\<odot> ?es) \\<oplus> ((?r\\<langle>?o\\<rangle>?r \\<oplus> ?a \\<odot> ?as) \\<odot> ?b \\<odot> ?fs) \\<oplus> ((s\\<langle>?o\\<rangle>s \\<oplus> ?d \\<odot> ?ds) \\<odot> ?c \\<odot> ?es) \\<oplus> ?fs\"\n        using 1 2 3 by (metis distinct.simps(2))\n      also have \"... = (?r\\<langle>?o\\<rangle>?r \\<oplus> ?e \\<odot> ?es) \\<oplus> ((?r\\<langle>?o\\<rangle>?r \\<oplus> ?a \\<odot> ?as) \\<odot> ?b \\<odot> ?fs) \\<oplus> (?ds \\<odot> ?c \\<odot> ?es) \\<oplus> ?fs\"\n        using 1 2 by (metis (no_types, lifting) distinct.simps(2) restrict_superlist)\n      also have \"... = ?es \\<oplus> ((?r\\<langle>?o\\<rangle>?r \\<oplus> ?a \\<odot> ?as) \\<odot> ?b \\<odot> ?fs) \\<oplus> (?ds \\<odot> ?c \\<odot> ?es) \\<oplus> ?fs\"\n        using 3 by (metis restrict_star_unfold)\n      also have \"... = ?es \\<oplus> ?as \\<odot> ?b \\<odot> ?fs \\<oplus> ?ds \\<odot> ?c \\<odot> ?es \\<oplus> ?fs\"\n        by (metis (no_types, lifting) restrict_one_left_unit restrict_star_unfold restrict_times)\n      also have \"... = star_matrix' ?t g\"\n        by (metis star_matrix'.simps(2))\n      finally show \"?t\\<langle>?o\\<rangle>?t \\<oplus> ?t\\<langle>g\\<rangle>?t \\<odot> star_matrix' ?t g = star_matrix' ?t g\"\n        .\n    qed\n  qed\n  thus \"?o \\<oplus> y \\<odot> y\\<^sup>\\<odot> \\<preceq> y\\<^sup>\\<odot>\"\n    by (simp add: enum_distinct restrict_all)\nnext\n  fix x y z :: \"('a,'b) square\"\n  let ?e = \"enum_class.enum::'a list\"\n  have \"\\<forall>g h :: ('a,'b) square . \\<forall>zs . distinct ?e \\<and> distinct zs \\<longrightarrow> (?e\\<langle>g\\<rangle>?e \\<odot> ?e\\<langle>h\\<rangle>zs \\<preceq> ?e\\<langle>h\\<rangle>zs \\<longrightarrow> star_matrix' ?e g \\<odot> ?e\\<langle>h\\<rangle>zs \\<preceq> ?e\\<langle>h\\<rangle>zs)\"\n  proof (induct rule: list.induct)\n    case Nil thus ?case\n      by (simp add: restrict_empty_left)\n    case (Cons k s)\n    let ?t = \"k#s\"\n    assume 1: \"\\<forall>g h :: ('a,'b) square . \\<forall>zs . distinct s \\<and> distinct zs \\<longrightarrow> (s\\<langle>g\\<rangle>s \\<odot> s\\<langle>h\\<rangle>zs \\<preceq> s\\<langle>h\\<rangle>zs \\<longrightarrow> star_matrix' s g \\<odot> s\\<langle>h\\<rangle>zs \\<preceq> s\\<langle>h\\<rangle>zs)\"\n    show \"\\<forall>g h :: ('a,'b) square . \\<forall>zs . distinct ?t \\<and> distinct zs \\<longrightarrow> (?t\\<langle>g\\<rangle>?t \\<odot> ?t\\<langle>h\\<rangle>zs \\<preceq> ?t\\<langle>h\\<rangle>zs \\<longrightarrow> star_matrix' ?t g \\<odot> ?t\\<langle>h\\<rangle>zs \\<preceq> ?t\\<langle>h\\<rangle>zs)\"\n    proof (intro allI)\n      fix g h :: \"('a,'b) square\"\n      fix zs :: \"'a list\"\n      show \"distinct ?t \\<and> distinct zs \\<longrightarrow> (?t\\<langle>g\\<rangle>?t \\<odot> ?t\\<langle>h\\<rangle>zs \\<preceq> ?t\\<langle>h\\<rangle>zs \\<longrightarrow> star_matrix' ?t g \\<odot> ?t\\<langle>h\\<rangle>zs \\<preceq> ?t\\<langle>h\\<rangle>zs)\"\n      proof (cases zs)\n        case Nil thus ?thesis\n          by (metis restrict_empty_right restrict_star restrict_times)\n      next\n        case (Cons y ys)\n        assume 2: \"zs = y#ys\"\n        show \"distinct ?t \\<and> distinct zs \\<longrightarrow> (?t\\<langle>g\\<rangle>?t \\<odot> ?t\\<langle>h\\<rangle>zs \\<preceq> ?t\\<langle>h\\<rangle>zs \\<longrightarrow> star_matrix' ?t g \\<odot> ?t\\<langle>h\\<rangle>zs \\<preceq> ?t\\<langle>h\\<rangle>zs)\"\n        proof (intro impI)\n          let ?y = \"[y]\"\n          assume 3: \"distinct ?t \\<and> distinct zs\"\n          hence 4: \"distinct s \\<and> distinct ys \\<and> \\<not> List.member s k \\<and> \\<not> List.member ys y\"\n            using 2 by (simp add: List.member_def)\n          let ?r = \"[k]\"\n          let ?a = \"?r\\<langle>g\\<rangle>?r\"\n          let ?b = \"?r\\<langle>g\\<rangle>s\"\n          let ?c = \"s\\<langle>g\\<rangle>?r\"\n          let ?d = \"s\\<langle>g\\<rangle>s\"\n          let ?as = \"?r\\<langle>star o ?a\\<rangle>?r\"\n          let ?ds = \"star_matrix' s ?d\"\n          let ?e = \"?a \\<oplus> ?b \\<odot> ?ds \\<odot> ?c\"\n          let ?es = \"?r\\<langle>star o ?e\\<rangle>?r\"\n          let ?f = \"?d \\<oplus> ?c \\<odot> ?as \\<odot> ?b\"\n          let ?fs = \"star_matrix' s ?f\"\n          let ?ha = \"?r\\<langle>h\\<rangle>?y\"\n          let ?hb = \"?r\\<langle>h\\<rangle>ys\"\n          let ?hc = \"s\\<langle>h\\<rangle>?y\"\n          let ?hd = \"s\\<langle>h\\<rangle>ys\"\n          assume \"?t\\<langle>g\\<rangle>?t \\<odot> ?t\\<langle>h\\<rangle>zs \\<preceq> ?t\\<langle>h\\<rangle>zs\"\n          hence 5: \"?a \\<odot> ?ha \\<oplus> ?b \\<odot> ?hc \\<preceq> ?ha \\<and> ?a \\<odot> ?hb \\<oplus> ?b \\<odot> ?hd \\<preceq> ?hb \\<and> ?c \\<odot> ?ha \\<oplus> ?d \\<odot> ?hc \\<preceq> ?hc \\<and> ?c \\<odot> ?hb \\<oplus> ?d \\<odot> ?hd \\<preceq> ?hd\"\n            using 2 3 4 by (simp add: restrict_nonempty_product_less_eq)\n          have 6: \"s\\<langle>?ds\\<rangle>s = ?ds \\<and> s\\<langle>?fs\\<rangle>s = ?fs\"\n            by (simp add: restrict_star)\n          hence 7: \"?r\\<langle>?e\\<rangle>?r = ?e \\<and> s\\<langle>?f\\<rangle>s = ?f\"\n            by (metis (no_types, lifting) restrict_one_left_unit restrict_sup restrict_times)\n          have 8: \"disjoint s ?r \\<and> disjoint ?r s\"\n            using 3 by (simp add: in_set_member member_rec(1) member_rec(2))\n          have 9: \"?es \\<odot> ?t\\<langle>h\\<rangle>zs = ?es \\<odot> ?ha \\<oplus> ?es \\<odot> ?hb\"\n          proof -\n            have \"?es \\<odot> ?t\\<langle>h\\<rangle>zs = ?es \\<odot> (?ha \\<oplus> ?hb \\<oplus> ?hc \\<oplus> ?hd)\"\n              using 2 by (metis restrict_nonempty)\n            also have \"... = ?es \\<odot> ?ha \\<oplus> ?es \\<odot> ?hb \\<oplus> ?es \\<odot> ?hc \\<oplus> ?es \\<odot> ?hd\"\n              by (simp add: matrix_idempotent_semiring.mult_left_dist_sup)\n            also have \"... = ?es \\<odot> ?ha \\<oplus> ?es \\<odot> ?hb\"\n              using 8 by (simp add: times_disjoint)\n            finally show ?thesis\n              .\n          qed\n          have 10: \"?as \\<odot> ?b \\<odot> ?fs \\<odot> ?t\\<langle>h\\<rangle>zs = ?as \\<odot> ?b \\<odot> ?fs \\<odot> ?hc \\<oplus> ?as \\<odot> ?b \\<odot> ?fs \\<odot> ?hd\"\n          proof -\n            have \"?as \\<odot> ?b \\<odot> ?fs \\<odot> ?t\\<langle>h\\<rangle>zs = ?as \\<odot> ?b \\<odot> ?fs \\<odot> (?ha \\<oplus> ?hb \\<oplus> ?hc \\<oplus> ?hd)\"\n              using 2 by (metis restrict_nonempty)\n            also have \"... = ?as \\<odot> ?b \\<odot> ?fs \\<odot> ?ha \\<oplus> ?as \\<odot> ?b \\<odot> ?fs \\<odot> ?hb \\<oplus> ?as \\<odot> ?b \\<odot> ?fs \\<odot> ?hc \\<oplus> ?as \\<odot> ?b \\<odot> ?fs \\<odot> ?hd\"\n              by (simp add: matrix_idempotent_semiring.mult_left_dist_sup)\n            also have \"... = ?as \\<odot> ?b \\<odot> (?fs \\<odot> ?ha) \\<oplus> ?as \\<odot> ?b \\<odot> (?fs \\<odot> ?hb) \\<oplus> ?as \\<odot> ?b \\<odot> ?fs \\<odot> ?hc \\<oplus> ?as \\<odot> ?b \\<odot> ?fs \\<odot> ?hd\"\n              by (simp add: matrix_monoid.mult_assoc)\n            also have \"... = ?as \\<odot> ?b \\<odot> mbot \\<oplus> ?as \\<odot> ?b \\<odot> mbot \\<oplus> ?as \\<odot> ?b \\<odot> ?fs \\<odot> ?hc \\<oplus> ?as \\<odot> ?b \\<odot> ?fs \\<odot> ?hd\"\n              using 6 8 by (metis (no_types) times_disjoint)\n            also have \"... = ?as \\<odot> ?b \\<odot> ?fs \\<odot> ?hc \\<oplus> ?as \\<odot> ?b \\<odot> ?fs \\<odot> ?hd\"\n              by simp\n            finally show ?thesis\n              .\n          qed\n          have 11: \"?ds \\<odot> ?c \\<odot> ?es \\<odot> ?t\\<langle>h\\<rangle>zs = ?ds \\<odot> ?c \\<odot> ?es \\<odot> ?ha \\<oplus> ?ds \\<odot> ?c \\<odot> ?es \\<odot> ?hb\"\n          proof -\n            have \"?ds \\<odot> ?c \\<odot> ?es \\<odot> ?t\\<langle>h\\<rangle>zs = ?ds \\<odot> ?c \\<odot> ?es \\<odot> (?ha \\<oplus> ?hb \\<oplus> ?hc \\<oplus> ?hd)\"\n              using 2 by (metis restrict_nonempty)\n            also have \"... = ?ds \\<odot> ?c \\<odot> ?es \\<odot> ?ha \\<oplus> ?ds \\<odot> ?c \\<odot> ?es \\<odot> ?hb \\<oplus> ?ds \\<odot> ?c \\<odot> ?es \\<odot> ?hc \\<oplus> ?ds \\<odot> ?c \\<odot> ?es \\<odot> ?hd\"\n              by (simp add: matrix_idempotent_semiring.mult_left_dist_sup)\n            also have \"... = ?ds \\<odot> ?c \\<odot> ?es \\<odot> ?ha \\<oplus> ?ds \\<odot> ?c \\<odot> ?es \\<odot> ?hb \\<oplus> ?ds \\<odot> ?c \\<odot> (?es \\<odot> ?hc) \\<oplus> ?ds \\<odot> ?c \\<odot> (?es \\<odot> ?hd)\"\n              by (simp add: matrix_monoid.mult_assoc)\n            also have \"... = ?ds \\<odot> ?c \\<odot> ?es \\<odot> ?ha \\<oplus> ?ds \\<odot> ?c \\<odot> ?es \\<odot> ?hb \\<oplus> ?ds \\<odot> ?c \\<odot> mbot \\<oplus> ?ds \\<odot> ?c \\<odot> mbot\"\n              using 8 by (metis times_disjoint)\n            also have \"... = ?ds \\<odot> ?c \\<odot> ?es \\<odot> ?ha \\<oplus> ?ds \\<odot> ?c \\<odot> ?es \\<odot> ?hb\"\n              by simp\n            finally show ?thesis\n              .\n          qed\n          have 12: \"?fs \\<odot> ?t\\<langle>h\\<rangle>zs = ?fs \\<odot> ?hc \\<oplus> ?fs \\<odot> ?hd\"\n          proof -\n            have \"?fs \\<odot> ?t\\<langle>h\\<rangle>zs = ?fs \\<odot> (?ha \\<oplus> ?hb \\<oplus> ?hc \\<oplus> ?hd)\"\n              using 2 by (metis restrict_nonempty)\n            also have \"... = ?fs \\<odot> ?ha \\<oplus> ?fs \\<odot> ?hb \\<oplus> ?fs \\<odot> ?hc \\<oplus> ?fs \\<odot> ?hd\"\n              by (simp add: matrix_idempotent_semiring.mult_left_dist_sup)\n            also have \"... = ?fs \\<odot> ?hc \\<oplus> ?fs \\<odot> ?hd\"\n              using 6 8 by (metis (no_types) times_disjoint matrix_bounded_semilattice_sup_bot.sup_monoid.add_0_left)\n            finally show ?thesis\n              .\n          qed\n          have 13: \"?es \\<odot> ?ha \\<preceq> ?ha\"\n          proof -\n            have \"?b \\<odot> ?ds \\<odot> ?c \\<odot> ?ha \\<preceq> ?b \\<odot> ?ds \\<odot> ?hc\"\n              using 5 by (simp add: matrix_idempotent_semiring.mult_right_isotone matrix_monoid.mult_assoc)\n            also have \"... \\<preceq> ?b \\<odot> ?hc\"\n              using 1 3 5 by (simp add: matrix_idempotent_semiring.mult_right_isotone matrix_monoid.mult_assoc member_rec(2) restrict_sublist)\n            also have \"... \\<preceq> ?ha\"\n              using 5 by simp\n            finally have \"?e \\<odot> ?ha \\<preceq> ?ha\"\n              using 5 by (simp add: matrix_idempotent_semiring.mult_right_dist_sup)\n            thus ?thesis\n              using 7 by (simp add: restrict_star_left_induct)\n          qed\n          have 14: \"?es \\<odot> ?hb \\<preceq> ?hb\"\n          proof -\n            have \"?b \\<odot> ?ds \\<odot> ?c \\<odot> ?hb \\<preceq> ?b \\<odot> ?ds \\<odot> ?hd\"\n              using 5 by (simp add: matrix_idempotent_semiring.mult_right_isotone matrix_monoid.mult_assoc)\n            also have \"... \\<preceq> ?b \\<odot> ?hd\"\n              using 1 4 5 by (simp add: matrix_idempotent_semiring.mult_right_isotone matrix_monoid.mult_assoc restrict_sublist)\n            also have \"... \\<preceq> ?hb\"\n              using 5 by simp\n            finally have \"?e \\<odot> ?hb \\<preceq> ?hb\"\n              using 5 by (simp add: matrix_idempotent_semiring.mult_right_dist_sup)\n            thus ?thesis\n              using 4 7 by (simp add: restrict_star_left_induct)\n          qed\n          have 15: \"?fs \\<odot> ?hc \\<preceq> ?hc\"\n          proof -\n            have \"?c \\<odot> ?as \\<odot> ?b \\<odot> ?hc \\<preceq> ?c \\<odot> ?as \\<odot> ?ha\"\n              using 5 by (simp add: matrix_idempotent_semiring.mult_right_isotone matrix_monoid.mult_assoc)\n            also have \"... \\<preceq> ?c \\<odot> ?ha\"\n              using 5 by (simp add: matrix_idempotent_semiring.mult_right_isotone matrix_monoid.mult_assoc restrict_star_left_induct restrict_sublist)\n            also have \"... \\<preceq> ?hc\"\n              using 5 by simp\n            finally have \"?f \\<odot> ?hc \\<preceq> ?hc\"\n              using 5 by (simp add: matrix_idempotent_semiring.mult_right_dist_sup)\n            thus ?thesis\n              using 1 3 7 by simp\n          qed\n          have 16: \"?fs \\<odot> ?hd \\<preceq> ?hd\"\n          proof -\n            have \"?c \\<odot> ?as \\<odot> ?b \\<odot> ?hd \\<preceq> ?c \\<odot> ?as \\<odot> ?hb\"\n              using 5 by (simp add: matrix_idempotent_semiring.mult_right_isotone matrix_monoid.mult_assoc)\n            also have \"... \\<preceq> ?c \\<odot> ?hb\"\n              using 4 5 by (simp add: matrix_idempotent_semiring.mult_right_isotone matrix_monoid.mult_assoc restrict_star_left_induct restrict_sublist)\n            also have \"... \\<preceq> ?hd\"\n              using 5 by simp\n            finally have \"?f \\<odot> ?hd \\<preceq> ?hd\"\n              using 5 by (simp add: matrix_idempotent_semiring.mult_right_dist_sup)\n            thus ?thesis\n              using 1 4 7 by simp\n          qed\n          have 17: \"?as \\<odot> ?b \\<odot> ?fs \\<odot> ?hc \\<preceq> ?ha\"\n          proof -\n            have \"?as \\<odot> ?b \\<odot> ?fs \\<odot> ?hc \\<preceq> ?as \\<odot> ?b \\<odot> ?hc\"\n              using 15 by (simp add: matrix_idempotent_semiring.mult_right_isotone matrix_monoid.mult_assoc)\n            also have \"... \\<preceq> ?as \\<odot> ?ha\"\n              using 5 by (simp add: matrix_idempotent_semiring.mult_right_isotone matrix_monoid.mult_assoc)\n            also have \"... \\<preceq> ?ha\"\n              using 5 by (simp add: restrict_star_left_induct restrict_sublist)\n            finally show ?thesis\n              .\n          qed\n          have 18: \"?as \\<odot> ?b \\<odot> ?fs \\<odot> ?hd \\<preceq> ?hb\"\n          proof -\n            have \"?as \\<odot> ?b \\<odot> ?fs \\<odot> ?hd \\<preceq> ?as \\<odot> ?b \\<odot> ?hd\"\n              using 16 by (simp add: matrix_idempotent_semiring.mult_right_isotone matrix_monoid.mult_assoc)\n            also have \"... \\<preceq> ?as \\<odot> ?hb\"\n              using 5 by (simp add: matrix_idempotent_semiring.mult_right_isotone matrix_monoid.mult_assoc)\n            also have \"... \\<preceq> ?hb\"\n              using 4 5 by (simp add: restrict_star_left_induct restrict_sublist)\n            finally show ?thesis\n              .\n          qed\n          have 19: \"?ds \\<odot> ?c \\<odot> ?es \\<odot> ?ha \\<preceq> ?hc\"\n          proof -\n            have \"?ds \\<odot> ?c \\<odot> ?es \\<odot> ?ha \\<preceq> ?ds \\<odot> ?c \\<odot> ?ha\"\n              using 13 by (simp add: matrix_idempotent_semiring.mult_right_isotone matrix_monoid.mult_assoc)\n            also have \"... \\<preceq> ?ds \\<odot> ?hc\"\n              using 5 by (simp add: matrix_idempotent_semiring.mult_right_isotone matrix_monoid.mult_assoc)\n            also have \"... \\<preceq> ?hc\"\n              using 1 3 5 by (simp add: restrict_sublist)\n            finally show ?thesis\n              .\n          qed\n          have 20: \"?ds \\<odot> ?c \\<odot> ?es \\<odot> ?hb \\<preceq> ?hd\"\n          proof -\n            have \"?ds \\<odot> ?c \\<odot> ?es \\<odot> ?hb \\<preceq> ?ds \\<odot> ?c \\<odot> ?hb\"\n              using 14 by (simp add: matrix_idempotent_semiring.mult_right_isotone matrix_monoid.mult_assoc)\n            also have \"... \\<preceq> ?ds \\<odot> ?hd\"\n              using 5 by (simp add: matrix_idempotent_semiring.mult_right_isotone matrix_monoid.mult_assoc)\n            also have \"... \\<preceq> ?hd\"\n              using 1 4 5 by (simp add: restrict_sublist)\n            finally show ?thesis\n              .\n          qed\n          have 21: \"?es \\<odot> ?ha \\<oplus> ?as \\<odot> ?b \\<odot> ?fs \\<odot> ?hc \\<preceq> ?ha\"\n            using 13 17 matrix_semilattice_sup.le_supI by blast\n          have 22: \"?es \\<odot> ?hb \\<oplus> ?as \\<odot> ?b \\<odot> ?fs \\<odot> ?hd \\<preceq> ?hb\"\n            using 14 18 matrix_semilattice_sup.le_supI by blast\n          have 23: \"?ds \\<odot> ?c \\<odot> ?es \\<odot> ?ha \\<oplus> ?fs \\<odot> ?hc \\<preceq> ?hc\"\n            using 15 19 matrix_semilattice_sup.le_supI by blast\n          have 24: \"?ds \\<odot> ?c \\<odot> ?es \\<odot> ?hb \\<oplus> ?fs \\<odot> ?hd \\<preceq> ?hd\"\n            using 16 20 matrix_semilattice_sup.le_supI by blast\n          have \"star_matrix' ?t g \\<odot> ?t\\<langle>h\\<rangle>zs = (?es \\<oplus> ?as \\<odot> ?b \\<odot> ?fs \\<oplus> ?ds \\<odot> ?c \\<odot> ?es \\<oplus> ?fs) \\<odot> ?t\\<langle>h\\<rangle>zs\"\n            by (metis star_matrix'.simps(2))\n          also have \"... = ?es \\<odot> ?t\\<langle>h\\<rangle>zs \\<oplus> ?as \\<odot> ?b \\<odot> ?fs \\<odot> ?t\\<langle>h\\<rangle>zs \\<oplus> ?ds \\<odot> ?c \\<odot> ?es \\<odot> ?t\\<langle>h\\<rangle>zs \\<oplus> ?fs \\<odot> ?t\\<langle>h\\<rangle>zs\"\n            by (simp add: matrix_idempotent_semiring.mult_right_dist_sup)\n          also have \"... = ?es \\<odot> ?ha \\<oplus> ?es \\<odot> ?hb \\<oplus> ?as \\<odot> ?b \\<odot> ?fs \\<odot> ?hc \\<oplus> ?as \\<odot> ?b \\<odot> ?fs \\<odot> ?hd \\<oplus> ?ds \\<odot> ?c \\<odot> ?es \\<odot> ?ha \\<oplus> ?ds \\<odot> ?c \\<odot> ?es \\<odot> ?hb \\<oplus> ?fs \\<odot> ?hc \\<oplus> ?fs \\<odot> ?hd\"\n            using 9 10 11 12 by (simp only: matrix_semilattice_sup.sup_assoc)\n          also have \"... = (?es \\<odot> ?ha \\<oplus> ?as \\<odot> ?b \\<odot> ?fs \\<odot> ?hc) \\<oplus> (?es \\<odot> ?hb \\<oplus> ?as \\<odot> ?b \\<odot> ?fs \\<odot> ?hd) \\<oplus> (?ds \\<odot> ?c \\<odot> ?es \\<odot> ?ha \\<oplus> ?fs \\<odot> ?hc) \\<oplus> (?ds \\<odot> ?c \\<odot> ?es \\<odot> ?hb \\<oplus> ?fs \\<odot> ?hd)\"\n            by (simp only: matrix_semilattice_sup.sup_assoc matrix_semilattice_sup.sup_commute matrix_semilattice_sup.sup_left_commute)\n          also have \"... \\<preceq> ?ha \\<oplus> ?hb \\<oplus> ?hc \\<oplus> ?hd\"\n            using 21 22 23 24 matrix_semilattice_sup.sup.mono by blast\n          also have \"... = ?t\\<langle>h\\<rangle>zs\"\n            using 2 by (metis restrict_nonempty)\n          finally show \"star_matrix' ?t g \\<odot> ?t\\<langle>h\\<rangle>zs \\<preceq> ?t\\<langle>h\\<rangle>zs\"\n            .\n        qed\n      qed\n    qed\n  qed\n  hence \"\\<forall>zs . distinct zs \\<longrightarrow> (y \\<odot> ?e\\<langle>x\\<rangle>zs \\<preceq> ?e\\<langle>x\\<rangle>zs \\<longrightarrow> y\\<^sup>\\<odot> \\<odot> ?e\\<langle>x\\<rangle>zs \\<preceq> ?e\\<langle>x\\<rangle>zs)\"\n    by (simp add: enum_distinct restrict_all)\n  thus \"y \\<odot> x \\<preceq> x \\<longrightarrow> y\\<^sup>\\<odot> \\<odot> x \\<preceq> x\"\n    by (metis restrict_all enum_distinct)\nnext\n  fix x y z :: \"('a,'b) square\"\n  let ?e = \"enum_class.enum::'a list\"\n  have \"\\<forall>g h :: ('a,'b) square . \\<forall>zs . distinct ?e \\<and> distinct zs \\<longrightarrow> (zs\\<langle>h\\<rangle>?e \\<odot> ?e\\<langle>g\\<rangle>?e \\<preceq> zs\\<langle>h\\<rangle>?e \\<longrightarrow> zs\\<langle>h\\<rangle>?e \\<odot> star_matrix' ?e g \\<preceq> zs\\<langle>h\\<rangle>?e)\"\n  proof (induct rule:list.induct)\n    case Nil thus ?case\n      by (simp add: restrict_empty_left)\n    case (Cons k s)\n    let ?t = \"k#s\"\n    assume 1: \"\\<forall>g h :: ('a,'b) square . \\<forall>zs . distinct s \\<and> distinct zs \\<longrightarrow> (zs\\<langle>h\\<rangle>s \\<odot> s\\<langle>g\\<rangle>s \\<preceq> zs\\<langle>h\\<rangle>s \\<longrightarrow> zs\\<langle>h\\<rangle>s \\<odot> star_matrix' s g \\<preceq> zs\\<langle>h\\<rangle>s)\"\n    show \"\\<forall>g h :: ('a,'b) square . \\<forall>zs . distinct ?t \\<and> distinct zs \\<longrightarrow> (zs\\<langle>h\\<rangle>?t \\<odot> ?t\\<langle>g\\<rangle>?t \\<preceq> zs\\<langle>h\\<rangle>?t \\<longrightarrow> zs\\<langle>h\\<rangle>?t \\<odot> star_matrix' ?t g \\<preceq> zs\\<langle>h\\<rangle>?t)\"\n    proof (intro allI)\n      fix g h :: \"('a,'b) square\"\n      fix zs :: \"'a list\"\n      show \"distinct ?t \\<and> distinct zs \\<longrightarrow> (zs\\<langle>h\\<rangle>?t \\<odot> ?t\\<langle>g\\<rangle>?t \\<preceq> zs\\<langle>h\\<rangle>?t \\<longrightarrow> zs\\<langle>h\\<rangle>?t \\<odot> star_matrix' ?t g \\<preceq> zs\\<langle>h\\<rangle>?t)\"\n      proof (cases zs)\n        case Nil thus ?thesis\n          by (metis restrict_empty_left restrict_star restrict_times)\n      next\n        case (Cons y ys)\n        assume 2: \"zs = y#ys\"\n        show \"distinct ?t \\<and> distinct zs \\<longrightarrow> (zs\\<langle>h\\<rangle>?t \\<odot> ?t\\<langle>g\\<rangle>?t \\<preceq> zs\\<langle>h\\<rangle>?t \\<longrightarrow> zs\\<langle>h\\<rangle>?t \\<odot> star_matrix' ?t g \\<preceq> zs\\<langle>h\\<rangle>?t)\"\n        proof (intro impI)\n          let ?y = \"[y]\"\n          assume 3: \"distinct ?t \\<and> distinct zs\"\n          hence 4: \"distinct s \\<and> distinct ys \\<and> \\<not> List.member s k \\<and> \\<not> List.member ys y\"\n            using 2 by (simp add: List.member_def)\n          let ?r = \"[k]\"\n          let ?a = \"?r\\<langle>g\\<rangle>?r\"\n          let ?b = \"?r\\<langle>g\\<rangle>s\"\n          let ?c = \"s\\<langle>g\\<rangle>?r\"\n          let ?d = \"s\\<langle>g\\<rangle>s\"\n          let ?as = \"?r\\<langle>star o ?a\\<rangle>?r\"\n          let ?ds = \"star_matrix' s ?d\"\n          let ?e = \"?a \\<oplus> ?b \\<odot> ?ds \\<odot> ?c\"\n          let ?es = \"?r\\<langle>star o ?e\\<rangle>?r\"\n          let ?f = \"?d \\<oplus> ?c \\<odot> ?as \\<odot> ?b\"\n          let ?fs = \"star_matrix' s ?f\"\n          let ?ha = \"?y\\<langle>h\\<rangle>?r\"\n          let ?hb = \"?y\\<langle>h\\<rangle>s\"\n          let ?hc = \"ys\\<langle>h\\<rangle>?r\"\n          let ?hd = \"ys\\<langle>h\\<rangle>s\"\n          assume \"zs\\<langle>h\\<rangle>?t \\<odot> ?t\\<langle>g\\<rangle>?t \\<preceq> zs\\<langle>h\\<rangle>?t\"\n          hence 5: \"?ha \\<odot> ?a \\<oplus> ?hb \\<odot> ?c \\<preceq> ?ha \\<and> ?ha \\<odot> ?b \\<oplus> ?hb \\<odot> ?d \\<preceq> ?hb \\<and> ?hc \\<odot> ?a \\<oplus> ?hd \\<odot> ?c \\<preceq> ?hc \\<and> ?hc \\<odot> ?b \\<oplus> ?hd \\<odot> ?d \\<preceq> ?hd\"\n            using 2 3 4 by (simp add: restrict_nonempty_product_less_eq)\n          have 6: \"s\\<langle>?ds\\<rangle>s = ?ds \\<and> s\\<langle>?fs\\<rangle>s = ?fs\"\n            by (simp add: restrict_star)\n          hence 7: \"?r\\<langle>?e\\<rangle>?r = ?e \\<and> s\\<langle>?f\\<rangle>s = ?f\"\n            by (metis (no_types, lifting) restrict_one_left_unit restrict_sup restrict_times)\n          have 8: \"disjoint s ?r \\<and> disjoint ?r s\"\n            using 3 by (simp add: in_set_member member_rec)\n          have 9: \"zs\\<langle>h\\<rangle>?t \\<odot> ?es = ?ha \\<odot> ?es \\<oplus> ?hc \\<odot> ?es\"\n          proof -\n            have \"zs\\<langle>h\\<rangle>?t \\<odot> ?es = (?ha \\<oplus> ?hb \\<oplus> ?hc \\<oplus> ?hd) \\<odot> ?es\"\n              using 2 by (metis restrict_nonempty)\n            also have \"... = ?ha \\<odot> ?es \\<oplus> ?hb \\<odot> ?es \\<oplus> ?hc \\<odot> ?es \\<oplus> ?hd \\<odot> ?es\"\n              by (simp add: matrix_idempotent_semiring.mult_right_dist_sup)\n            also have \"... = ?ha \\<odot> ?es \\<oplus> ?hc \\<odot> ?es\"\n              using 8 by (simp add: times_disjoint)\n            finally show ?thesis\n              .\n          qed\n          have 10: \"zs\\<langle>h\\<rangle>?t \\<odot> ?as \\<odot> ?b \\<odot> ?fs = ?ha \\<odot> ?as \\<odot> ?b \\<odot> ?fs \\<oplus> ?hc \\<odot> ?as \\<odot> ?b \\<odot> ?fs\"\n          proof -\n            have \"zs\\<langle>h\\<rangle>?t \\<odot> ?as \\<odot> ?b \\<odot> ?fs = (?ha \\<oplus> ?hb \\<oplus> ?hc \\<oplus> ?hd) \\<odot> ?as \\<odot> ?b \\<odot> ?fs\"\n              using 2 by (metis restrict_nonempty)\n            also have \"... = ?ha \\<odot> ?as \\<odot> ?b \\<odot> ?fs \\<oplus> ?hb \\<odot> ?as \\<odot> ?b \\<odot> ?fs \\<oplus> ?hc \\<odot> ?as \\<odot> ?b \\<odot> ?fs \\<oplus> ?hd \\<odot> ?as \\<odot> ?b \\<odot> ?fs\"\n              by (simp add: matrix_idempotent_semiring.mult_right_dist_sup)\n            also have \"... = ?ha \\<odot> ?as \\<odot> ?b \\<odot> ?fs \\<oplus> mbot \\<odot> ?b \\<odot> ?fs \\<oplus> ?hc \\<odot> ?as \\<odot> ?b \\<odot> ?fs \\<oplus> mbot \\<odot> ?b \\<odot> ?fs\"\n              using 8 by (metis (no_types) times_disjoint)\n            also have \"... = ?ha \\<odot> ?as \\<odot> ?b \\<odot> ?fs \\<oplus> ?hc \\<odot> ?as \\<odot> ?b \\<odot> ?fs\"\n              by simp\n            finally show ?thesis\n              .\n          qed\n          have 11: \"zs\\<langle>h\\<rangle>?t \\<odot> ?ds \\<odot> ?c \\<odot> ?es = ?hb \\<odot> ?ds \\<odot> ?c \\<odot> ?es \\<oplus> ?hd \\<odot> ?ds \\<odot> ?c \\<odot> ?es\"\n          proof -\n            have \"zs\\<langle>h\\<rangle>?t \\<odot> ?ds \\<odot> ?c \\<odot> ?es = (?ha \\<oplus> ?hb \\<oplus> ?hc \\<oplus> ?hd) \\<odot> ?ds \\<odot> ?c \\<odot> ?es\"\n              using 2 by (metis restrict_nonempty)\n            also have \"... = ?ha \\<odot> ?ds \\<odot> ?c \\<odot> ?es \\<oplus> ?hb \\<odot> ?ds \\<odot> ?c \\<odot> ?es \\<oplus> ?hc \\<odot> ?ds \\<odot> ?c \\<odot> ?es \\<oplus> ?hd \\<odot> ?ds \\<odot> ?c \\<odot> ?es\"\n              by (simp add: matrix_idempotent_semiring.mult_right_dist_sup)\n            also have \"... = mbot \\<odot> ?c \\<odot> ?es \\<oplus> ?hb \\<odot> ?ds \\<odot> ?c \\<odot> ?es \\<oplus> mbot \\<odot> ?c \\<odot> ?es \\<oplus> ?hd \\<odot> ?ds \\<odot> ?c \\<odot> ?es\"\n              using 6 8 by (metis (no_types) times_disjoint)\n            also have \"... = ?hb \\<odot> ?ds \\<odot> ?c \\<odot> ?es \\<oplus> ?hd \\<odot> ?ds \\<odot> ?c \\<odot> ?es\"\n              by simp\n            finally show ?thesis\n              .\n          qed\n          have 12: \"zs\\<langle>h\\<rangle>?t \\<odot> ?fs = ?hb \\<odot> ?fs \\<oplus> ?hd \\<odot> ?fs\"\n          proof -\n            have \"zs\\<langle>h\\<rangle>?t \\<odot> ?fs = (?ha \\<oplus> ?hb \\<oplus> ?hc \\<oplus> ?hd) \\<odot> ?fs\"\n              using 2 by (metis restrict_nonempty)\n            also have \"... = ?ha \\<odot> ?fs \\<oplus> ?hb \\<odot> ?fs \\<oplus> ?hc \\<odot> ?fs \\<oplus> ?hd \\<odot> ?fs\"\n              by (simp add: matrix_idempotent_semiring.mult_right_dist_sup)\n            also have \"... = ?hb \\<odot> ?fs \\<oplus> ?hd \\<odot> ?fs\"\n              using 6 8 by (metis (no_types) times_disjoint matrix_bounded_semilattice_sup_bot.sup_monoid.add_0_right matrix_bounded_semilattice_sup_bot.sup_monoid.add_0_left)\n            finally show ?thesis\n              .\n          qed\n          have 13: \"?ha \\<odot> ?es \\<preceq> ?ha\"\n          proof -\n            have \"?ha \\<odot> ?b \\<odot> ?ds \\<odot> ?c \\<preceq> ?hb \\<odot> ?ds \\<odot> ?c\"\n              using 5 by (simp add: matrix_idempotent_semiring.mult_left_isotone)\n            also have \"... \\<preceq> ?hb \\<odot> ?c\"\n              using 1 4 5 by (simp add: matrix_idempotent_semiring.mult_left_isotone restrict_sublist)\n            also have \"... \\<preceq> ?ha\"\n              using 5 by simp\n            finally have \"?ha \\<odot> ?e \\<preceq> ?ha\"\n              using 5 by (simp add: matrix_idempotent_semiring.mult_left_dist_sup matrix_monoid.mult_assoc)\n            thus ?thesis\n              using 7 by (simp add: restrict_star_right_induct)\n          qed\n          have 14: \"?hb \\<odot> ?fs \\<preceq> ?hb\"\n          proof -\n            have \"?hb \\<odot> ?c \\<odot> ?as \\<odot> ?b \\<preceq> ?ha \\<odot> ?as \\<odot> ?b\"\n              using 5 by (metis matrix_semilattice_sup.le_supE matrix_idempotent_semiring.mult_left_isotone)\n            also have \"... \\<preceq> ?ha \\<odot> ?b\"\n              using 5 by (simp add: matrix_idempotent_semiring.mult_left_isotone restrict_star_right_induct restrict_sublist)\n            also have \"... \\<preceq> ?hb\"\n              using 5 by simp\n            finally have \"?hb \\<odot> ?f \\<preceq> ?hb\"\n              using 5 by (simp add: matrix_idempotent_semiring.mult_left_dist_sup matrix_monoid.mult_assoc)\n            thus ?thesis\n              using 1 3 7 by simp\n          qed\n          have 15: \"?hc \\<odot> ?es \\<preceq> ?hc\"\n          proof -\n            have \"?hc \\<odot> ?b \\<odot> ?ds \\<odot> ?c \\<preceq> ?hd \\<odot> ?ds \\<odot> ?c\"\n              using 5 by (simp add: matrix_idempotent_semiring.mult_left_isotone)\n            also have \"... \\<preceq> ?hd \\<odot> ?c\"\n              using 1 4 5 by (simp add: matrix_idempotent_semiring.mult_left_isotone restrict_sublist)\n            also have \"... \\<preceq> ?hc\"\n              using 5 by simp\n            finally have \"?hc \\<odot> ?e \\<preceq> ?hc\"\n              using 5 by (simp add: matrix_idempotent_semiring.mult_left_dist_sup matrix_monoid.mult_assoc)\n            thus ?thesis\n              using 4 7 by (simp add: restrict_star_right_induct)\n          qed\n          have 16: \"?hd \\<odot> ?fs \\<preceq> ?hd\"\n          proof -\n            have \"?hd \\<odot> ?c \\<odot> ?as \\<odot> ?b \\<preceq> ?hc \\<odot> ?as \\<odot> ?b\"\n              using 5 by (simp add: matrix_idempotent_semiring.mult_left_isotone)\n            also have \"... \\<preceq> ?hc \\<odot> ?b\"\n              using 4 5 by (simp add: matrix_idempotent_semiring.mult_left_isotone restrict_star_right_induct restrict_sublist)\n            also have \"... \\<preceq> ?hd\"\n              using 5 by simp\n            finally have \"?hd \\<odot> ?f \\<preceq> ?hd\"\n              using 5 by (simp add: matrix_idempotent_semiring.mult_left_dist_sup matrix_monoid.mult_assoc)\n            thus ?thesis\n              using 1 4 7 by simp\n          qed\n          have 17: \"?hb \\<odot> ?ds \\<odot> ?c \\<odot> ?es \\<preceq> ?ha\"\n          proof -\n            have \"?hb \\<odot> ?ds \\<odot> ?c \\<odot> ?es \\<preceq> ?hb \\<odot> ?c \\<odot> ?es\"\n              using 1 4 5 by (simp add: matrix_idempotent_semiring.mult_left_isotone restrict_sublist)\n            also have \"... \\<preceq> ?ha \\<odot> ?es\"\n              using 5 by (simp add: matrix_idempotent_semiring.mult_left_isotone)\n            also have \"... \\<preceq> ?ha\"\n              using 13 by simp\n            finally show ?thesis\n              .\n          qed\n          have 18: \"?ha \\<odot> ?as \\<odot> ?b \\<odot> ?fs \\<preceq> ?hb\"\n          proof -\n            have \"?ha \\<odot> ?as \\<odot> ?b \\<odot> ?fs \\<preceq> ?ha \\<odot> ?b \\<odot> ?fs\"\n              using 5 by (simp add: matrix_idempotent_semiring.mult_left_isotone restrict_star_right_induct restrict_sublist)\n            also have \"... \\<preceq> ?hb \\<odot> ?fs\"\n              using 5 by (simp add: matrix_idempotent_semiring.mult_left_isotone)\n            also have \"... \\<preceq> ?hb\"\n              using 14 by simp\n            finally show ?thesis\n              by simp\n          qed\n          have 19: \"?hd \\<odot> ?ds \\<odot> ?c \\<odot> ?es \\<preceq> ?hc\"\n          proof -\n            have \"?hd \\<odot> ?ds \\<odot> ?c \\<odot> ?es \\<preceq> ?hd \\<odot> ?c \\<odot> ?es\"\n              using 1 4 5 by (simp add: matrix_idempotent_semiring.mult_left_isotone restrict_sublist)\n            also have \"... \\<preceq> ?hc \\<odot> ?es\"\n              using 5 by (simp add: matrix_idempotent_semiring.mult_left_isotone)\n            also have \"... \\<preceq> ?hc\"\n              using 15 by simp\n            finally show ?thesis\n              by simp\n          qed\n          have 20: \"?hc \\<odot> ?as \\<odot> ?b \\<odot> ?fs \\<preceq> ?hd\"\n          proof -\n            have \"?hc \\<odot> ?as \\<odot> ?b \\<odot> ?fs \\<preceq> ?hc \\<odot> ?b \\<odot> ?fs\"\n              using 4 5 by (simp add: matrix_idempotent_semiring.mult_left_isotone restrict_star_right_induct restrict_sublist)\n            also have \"... \\<preceq> ?hd \\<odot> ?fs\"\n              using 5 by (simp add: matrix_idempotent_semiring.mult_left_isotone)\n            also have \"... \\<preceq> ?hd\"\n              using 16 by simp\n            finally show ?thesis\n              by simp\n          qed\n          have 21: \"?ha \\<odot> ?es \\<oplus> ?hb \\<odot> ?ds \\<odot> ?c \\<odot> ?es \\<preceq> ?ha\"\n            using 13 17 matrix_semilattice_sup.le_supI by blast\n          have 22: \"?ha \\<odot> ?as \\<odot> ?b \\<odot> ?fs \\<oplus> ?hb \\<odot> ?fs \\<preceq> ?hb\"\n            using 14 18 matrix_semilattice_sup.le_supI by blast\n          have 23: \"?hc \\<odot> ?es \\<oplus> ?hd \\<odot> ?ds \\<odot> ?c \\<odot> ?es \\<preceq> ?hc\"\n            using 15 19 matrix_semilattice_sup.le_supI by blast\n          have 24: \"?hc \\<odot> ?as \\<odot> ?b \\<odot> ?fs \\<oplus> ?hd \\<odot> ?fs \\<preceq> ?hd\"\n            using 16 20 matrix_semilattice_sup.le_supI by blast\n          have \"zs\\<langle>h\\<rangle>?t \\<odot> star_matrix' ?t g = zs\\<langle>h\\<rangle>?t \\<odot> (?es \\<oplus> ?as \\<odot> ?b \\<odot> ?fs \\<oplus> ?ds \\<odot> ?c \\<odot> ?es \\<oplus> ?fs)\"\n            by (metis star_matrix'.simps(2))\n          also have \"... = zs\\<langle>h\\<rangle>?t \\<odot> ?es \\<oplus> zs\\<langle>h\\<rangle>?t \\<odot> ?as \\<odot> ?b \\<odot> ?fs \\<oplus> zs\\<langle>h\\<rangle>?t \\<odot> ?ds \\<odot> ?c \\<odot> ?es \\<oplus> zs\\<langle>h\\<rangle>?t \\<odot> ?fs\"\n            by (simp add: matrix_idempotent_semiring.mult_left_dist_sup matrix_monoid.mult_assoc)\n          also have \"... = ?ha \\<odot> ?es \\<oplus> ?hc \\<odot> ?es \\<oplus> ?ha \\<odot> ?as \\<odot> ?b \\<odot> ?fs \\<oplus> ?hc \\<odot> ?as \\<odot> ?b \\<odot> ?fs \\<oplus> ?hb \\<odot> ?ds \\<odot> ?c \\<odot> ?es \\<oplus> ?hd \\<odot> ?ds \\<odot> ?c \\<odot> ?es \\<oplus> ?hb \\<odot> ?fs \\<oplus> ?hd \\<odot> ?fs\"\n            using 9 10 11 12 by (simp add: matrix_semilattice_sup.sup_assoc)\n          also have \"... = (?ha \\<odot> ?es \\<oplus> ?hb \\<odot> ?ds \\<odot> ?c \\<odot> ?es) \\<oplus> (?ha \\<odot> ?as \\<odot> ?b \\<odot> ?fs \\<oplus> ?hb \\<odot> ?fs) \\<oplus> (?hc \\<odot> ?es \\<oplus> ?hd \\<odot> ?ds \\<odot> ?c \\<odot> ?es) \\<oplus> (?hc \\<odot> ?as \\<odot> ?b \\<odot> ?fs \\<oplus> ?hd \\<odot> ?fs)\"\n            using 9 10 11 12 by (simp only: matrix_semilattice_sup.sup_assoc matrix_semilattice_sup.sup_commute matrix_semilattice_sup.sup_left_commute)\n          also have \"... \\<preceq> ?ha \\<oplus> ?hb \\<oplus> ?hc \\<oplus> ?hd\"\n            using 21 22 23 24 matrix_semilattice_sup.sup.mono by blast\n          also have \"... = zs\\<langle>h\\<rangle>?t\"\n            using 2 by (metis restrict_nonempty)\n          finally show \"zs\\<langle>h\\<rangle>?t \\<odot> star_matrix' ?t g \\<preceq> zs\\<langle>h\\<rangle>?t\"\n            .\n        qed\n      qed\n    qed\n  qed\n  hence \"\\<forall>zs . distinct zs \\<longrightarrow> (zs\\<langle>x\\<rangle>?e \\<odot> y \\<preceq> zs\\<langle>x\\<rangle>?e \\<longrightarrow> zs\\<langle>x\\<rangle>?e \\<odot> y\\<^sup>\\<odot> \\<preceq> zs\\<langle>x\\<rangle>?e)\"\n    by (simp add: enum_distinct restrict_all)\n  thus \"x \\<odot> y \\<preceq> x \\<longrightarrow> x \\<odot> y\\<^sup>\\<odot> \\<preceq> x\"\n    by (metis restrict_all enum_distinct)\nqed\n\nsubsection \\<open>Matrices form a Stone-Kleene Relation Algebra\\<close>\n\ntext \\<open>\nMatrices over Stone-Kleene relation algebras form a Stone-Kleene relation algebra.\nIt remains to prove the axiom about the interaction of Kleene star and double complement.\n\\<close>\n\ninterpretation matrix_stone_kleene_relation_algebra: stone_kleene_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::enum,'b::stone_kleene_relation_algebra) square\" and top = top_matrix and uminus = uminus_matrix and one = one_matrix and times = times_matrix and conv = conv_matrix and star = star_matrix\nproof\n  fix x :: \"('a,'b) square\"\n  let ?e = \"enum_class.enum::'a list\"\n  let ?o = \"mone :: ('a,'b) square\"\n  show \"\\<ominus>\\<ominus>(x\\<^sup>\\<odot>) = (\\<ominus>\\<ominus>x)\\<^sup>\\<odot>\"\n  proof (rule matrix_order.order_antisym)\n    have \"\\<forall>g :: ('a,'b) square . distinct ?e \\<longrightarrow> \\<ominus>\\<ominus>(star_matrix' ?e (\\<ominus>\\<ominus>g)) = star_matrix' ?e (\\<ominus>\\<ominus>g)\"\n    proof (induct rule: list.induct)\n      case Nil thus ?case\n        by simp\n    next\n      case (Cons k s)\n      let ?t = \"k#s\"\n      assume 1: \"\\<forall>g :: ('a,'b) square . distinct s \\<longrightarrow> \\<ominus>\\<ominus>(star_matrix' s (\\<ominus>\\<ominus>g)) = star_matrix' s (\\<ominus>\\<ominus>g)\"\n      show \"\\<forall>g :: ('a,'b) square . distinct ?t \\<longrightarrow> \\<ominus>\\<ominus>(star_matrix' ?t (\\<ominus>\\<ominus>g)) = star_matrix' ?t (\\<ominus>\\<ominus>g)\"\n      proof (rule allI, rule impI)\n        fix g :: \"('a,'b) square\"\n        assume 2: \"distinct ?t\"\n        let ?r = \"[k]\"\n        let ?a = \"?r\\<langle>\\<ominus>\\<ominus>g\\<rangle>?r\"\n        let ?b = \"?r\\<langle>\\<ominus>\\<ominus>g\\<rangle>s\"\n        let ?c = \"s\\<langle>\\<ominus>\\<ominus>g\\<rangle>?r\"\n        let ?d = \"s\\<langle>\\<ominus>\\<ominus>g\\<rangle>s\"\n        let ?as = \"?r\\<langle>star o ?a\\<rangle>?r\"\n        let ?ds = \"star_matrix' s ?d\"\n        let ?e = \"?a \\<oplus> ?b \\<odot> ?ds \\<odot> ?c\"\n        let ?es = \"?r\\<langle>star o ?e\\<rangle>?r\"\n        let ?f = \"?d \\<oplus> ?c \\<odot> ?as \\<odot> ?b\"\n        let ?fs = \"star_matrix' s ?f\"\n        have \"s\\<langle>?ds\\<rangle>s = ?ds \\<and> s\\<langle>?fs\\<rangle>s = ?fs\"\n          by (simp add: restrict_star)\n        have 3: \"\\<ominus>\\<ominus>?a = ?a \\<and> \\<ominus>\\<ominus>?b = ?b \\<and> \\<ominus>\\<ominus>?c = ?c \\<and> \\<ominus>\\<ominus>?d = ?d\"\n          by (metis matrix_p_algebra.regular_closed_p restrict_pp)\n        hence 4: \"\\<ominus>\\<ominus>?as = ?as\"\n          by (metis pp_star_commute restrict_pp)\n        hence \"\\<ominus>\\<ominus>?f = ?f\"\n          using 3 by (metis matrix_stone_algebra.regular_closed_sup matrix_stone_relation_algebra.regular_mult_closed)\n        hence 5: \"\\<ominus>\\<ominus>?fs = ?fs\"\n          using 1 2 by (metis distinct.simps(2))\n        have 6: \"\\<ominus>\\<ominus>?ds = ?ds\"\n          using 1 2 by (simp add: restrict_pp)\n        hence \"\\<ominus>\\<ominus>?e = ?e\"\n          using 3 by (metis matrix_stone_algebra.regular_closed_sup matrix_stone_relation_algebra.regular_mult_closed)\n        hence 7: \"\\<ominus>\\<ominus>?es = ?es\"\n          by (metis pp_star_commute restrict_pp)\n        have \"\\<ominus>\\<ominus>(star_matrix' ?t (\\<ominus>\\<ominus>g)) = \\<ominus>\\<ominus>(?es \\<oplus> ?as \\<odot> ?b \\<odot> ?fs \\<oplus> ?ds \\<odot> ?c \\<odot> ?es \\<oplus> ?fs)\"\n          by (metis star_matrix'.simps(2))\n        also have \"... = \\<ominus>\\<ominus>?es \\<oplus> \\<ominus>\\<ominus>?as \\<odot> \\<ominus>\\<ominus>?b \\<odot> \\<ominus>\\<ominus>?fs \\<oplus> \\<ominus>\\<ominus>?ds \\<odot> \\<ominus>\\<ominus>?c \\<odot> \\<ominus>\\<ominus>?es \\<oplus> \\<ominus>\\<ominus>?fs\"\n          by (simp add: matrix_stone_relation_algebra.pp_dist_comp)\n        also have \"... = ?es \\<oplus> ?as \\<odot> ?b \\<odot> ?fs \\<oplus> ?ds \\<odot> ?c \\<odot> ?es \\<oplus> ?fs\"\n          using 3 4 5 6 7 by simp\n        finally show \"\\<ominus>\\<ominus>(star_matrix' ?t (\\<ominus>\\<ominus>g)) = star_matrix' ?t (\\<ominus>\\<ominus>g)\"\n          by (metis star_matrix'.simps(2))\n      qed\n    qed\n    hence \"(\\<ominus>\\<ominus>x)\\<^sup>\\<odot> = \\<ominus>\\<ominus>((\\<ominus>\\<ominus>x)\\<^sup>\\<odot>)\"\n      by (simp add: enum_distinct restrict_all)\n    thus \"\\<ominus>\\<ominus>(x\\<^sup>\\<odot>) \\<preceq> (\\<ominus>\\<ominus>x)\\<^sup>\\<odot>\"\n      by (metis matrix_kleene_algebra.star.circ_isotone matrix_p_algebra.pp_increasing matrix_p_algebra.pp_isotone)\n  next\n    have \"?o \\<oplus> \\<ominus>\\<ominus>x \\<odot> \\<ominus>\\<ominus>(x\\<^sup>\\<odot>) \\<preceq> \\<ominus>\\<ominus>(x\\<^sup>\\<odot>)\"\n      by (metis matrix_kleene_algebra.star_left_unfold_equal matrix_p_algebra.sup_pp_semi_commute matrix_stone_relation_algebra.pp_dist_comp)\n    thus \"(\\<ominus>\\<ominus>x)\\<^sup>\\<odot> \\<preceq> \\<ominus>\\<ominus>(x\\<^sup>\\<odot>)\"\n      using matrix_kleene_algebra.star_left_induct by fastforce\n  qed\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/Stone_Kleene_Relation_Algebras/Matrix_Kleene_Algebras.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8539127566694177, "lm_q2_score": 0.839733963661418, "lm_q1q2_score": 0.717059543779058}}
{"text": "(* \nTitle: A Light-Weight Component for Kleene Algebra\nAuthor: Georg Struth\nMaintainer: Georg Struth <g.struth at sheffield.ac.uk>\n*)\n\nsection \\<open>Kleene Algebra Light\\<close>\n\ntheory \"KA_light\"\n  imports Main\n\nbegin\n\ntext \\<open>Here is a light-weight component for Kleene algebra. It could eventually be replaced by the AFP entry.\\<close>\n\nsubsection \\<open>Semilattices\\<close>\n\nclass sup_semilattice = comm_monoid_add + ord +\n  assumes add_idem: \"x + x = x\"\n  and order_def: \"(x \\<le> y) = (x + y = y)\"\n  and strict_order_def: \"(x < y) = (x \\<le> y \\<and> x \\<noteq> y)\"\n\nbegin\n\nsubclass order \n  apply unfold_locales\n     apply ( simp_all add: local.add_idem local.order_def local.strict_order_def add_commute)\n   apply force\n  by (metis add_assoc)\n\nlemma zero_least: \"0 \\<le> x\"\n  by (simp add: local.order_def)\n\nlemma add_isor: \"x \\<le> y \\<Longrightarrow> x + z \\<le> y + z\"\n  by (smt (verit, best) add_assoc add_commute local.add_idem local.order_def)\n\nlemma add_iso: \"x \\<le> y \\<Longrightarrow> x' \\<le> y' \\<Longrightarrow> x + x' \\<le> y + y'\"\n  by (metis add_commute add_isor local.dual_order.trans)\n\nlemma add_ubl: \"x \\<le> x + y\"\n  by (metis add_assoc local.add_idem local.order_def)\n\nlemma add_ubr: \"y \\<le> x + y\"\n  using add_commute add_ubl by fastforce\n\nlemma add_least: \"x \\<le> z \\<Longrightarrow> y \\<le> z \\<Longrightarrow> x + y \\<le> z\"\n  by (simp add: add_assoc local.order_def) \n\nlemma add_lub: \"(x + y \\<le> z) = (x \\<le> z \\<and> y \\<le> z)\"\n  using add_least add_ubl add_ubr dual_order.trans by blast\n\nend\n\n\nsubsection \\<open>Dioids\\<close>\n\ntext \\<open>Dioids are multiplicatively idempotent semirings.\\<close>\n\nnotation times (infixl \"\\<cdot>\" 70)\n\nclass dioid =  monoid_mult + sup_semilattice +\n  assumes distl: \"x \\<cdot> (y + z) = x \\<cdot> y + x \\<cdot> z\"\n  and distr: \"(x + y) \\<cdot> z = x \\<cdot> z + y \\<cdot> z\"\n  and annil [simp]: \"0 \\<cdot> x = 0\"\n  and annir [simp]: \"x \\<cdot> 0 = 0\"\n\nsublocale dioid \\<subseteq> dd: dioid _ \"\\<lambda>x y. y \\<cdot> x\" _ _ _ _\n  by (unfold_locales, simp_all add: mult_assoc local.distr local.distl)\n\nclass semiring_01 = semiring_0 + one +\n  assumes onel [simp]: \"1 \\<cdot> x = x\"\n  and oner [simp]: \"x \\<cdot> 1 = x\"\n\nsubclass (in dioid) semiring_01\n  by (unfold_locales, simp_all add: local.distr local.distl)\n\ntext \\<open>We do not use Isabelle's semirings because they require that 0 is not equal to 1.\\<close>\n\nlemma (in dioid) mult_isol: \"x \\<le> y \\<Longrightarrow> z \\<cdot> x \\<le> z \\<cdot> y\"\n  by (metis local.distl local.order_def)\n\nlemma (in dioid) mult_isor: \"x \\<le> y \\<Longrightarrow> x \\<cdot> z \\<le> y \\<cdot> z\"\n  by (simp add: local.dd.mult_isol)\n\nlemma (in dioid) mult_iso: \"x \\<le> y \\<Longrightarrow> x' \\<le> y' \\<Longrightarrow> x \\<cdot> x' \\<le> y \\<cdot> y'\"\n  using order_trans mult_isol mult_isor by blast\n\nlemma (in dioid) power_inductl: \"z + x \\<cdot> y \\<le> y \\<Longrightarrow> x ^ i \\<cdot> z \\<le> y\"\n  apply (induct i)\n   apply (simp add: local.add_lub)\n  by (smt (verit, ccfv_SIG) dd.mult_assoc local.add_lub local.order_def local.power.power_Suc mult_isol)\n\nlemma (in dioid) power_inductr: \"z + y \\<cdot> x \\<le> y \\<Longrightarrow> z \\<cdot> x ^ i \\<le> y\"\n  apply (induct i)\n   apply (simp add: local.add_lub)\n  by (smt (verit, ccfv_SIG) dd.mult_assoc local.add_lub local.order_def local.power_Suc2 mult_isor)\n\n\nsubsection \\<open>Kleene Algebras\\<close>\n\nclass star_op =\n  fixes star :: \"'a \\<Rightarrow> 'a\" (\"_\\<^sup>\\<star>\" [101] 100)\n\nclass kleene_algebra = dioid + star_op +\n  assumes star_unfoldl: \"1 + x \\<cdot> x\\<^sup>\\<star> \\<le> x\\<^sup>\\<star>\"  \n  and star_unfoldr: \"1 + x\\<^sup>\\<star> \\<cdot> x \\<le> x\\<^sup>\\<star>\"\n  and star_inductl: \"z + x \\<cdot> y \\<le> y \\<Longrightarrow> x\\<^sup>\\<star> \\<cdot> z \\<le> y\"\n  and star_inductr: \"z + y \\<cdot> x \\<le> y \\<Longrightarrow> z \\<cdot> x\\<^sup>\\<star> \\<le> y\"\n\nsublocale kleene_algebra \\<subseteq> dka: kleene_algebra _ \"\\<lambda>x y. y \\<cdot> x\" _ _ _ _ _\n  by (unfold_locales, simp_all add: local.star_unfoldr local.star_unfoldl local.star_inductr local.star_inductl)\n\nlemma (in kleene_algebra) one_le_star: \"1 \\<le> x\\<^sup>\\<star>\"\n  using local.add_lub local.star_unfoldl by blast\n\nlemma (in kleene_algebra) star_unfoldlr: \"x \\<cdot> x\\<^sup>\\<star> \\<le> x\\<^sup>\\<star>\"\n  using add_lub star_unfoldl by simp\n\nlemma (in kleene_algebra) star_unfoldrr: \"x\\<^sup>\\<star> \\<cdot> x \\<le> x\\<^sup>\\<star>\"\n  by (simp add: local.dka.star_unfoldlr)\n\nlemma (in kleene_algebra) star_infl: \"x \\<le> x\\<^sup>\\<star>\"\n  by (metis add_assoc local.distl local.mult_1_right local.order_def one_le_star star_unfoldlr) \n\nlemma (in kleene_algebra) star_power: \"x ^ i \\<le> x\\<^sup>\\<star>\"\n  apply (induct i)\n  apply (simp add: one_le_star)\n  by (metis local.mult_1_left local.power_inductr local.star_unfoldr)\n\nlemma (in kleene_algebra) star_trans [simp]: \"x\\<^sup>\\<star> \\<cdot> x\\<^sup>\\<star> = x\\<^sup>\\<star>\"\n  apply (rule order.antisym)\n  apply (simp add: local.add_least local.star_inductl local.star_unfoldlr)\n  using local.mult_isol local.one_le_star by fastforce\n\nlemma (in kleene_algebra) star_idem [simp]: \"(x\\<^sup>\\<star>)\\<^sup>\\<star> = x\\<^sup>\\<star>\"\n  by (metis order.antisym local.eq_refl local.mult_1_right local.order_def local.star_inductl one_le_star star_infl star_trans) \n\nlemma (in kleene_algebra) star_unfoldl_eq [simp]: \"1 + x \\<cdot> x\\<^sup>\\<star> = x\\<^sup>\\<star>\"\n  by (metis local.add_iso order.antisym local.mult_1_right local.mult_isol local.order_refl local.star_inductl local.star_unfoldl)  \n\nlemma (in kleene_algebra) star_unfoldr_eq: \"1 + x\\<^sup>\\<star> \\<cdot> x = x\\<^sup>\\<star>\"\n  by simp\n\nlemma (in kleene_algebra) star_iso: \"x \\<le> y \\<Longrightarrow> x\\<^sup>\\<star> \\<le> y\\<^sup>\\<star>\"\n  by (smt (verit, ccfv_SIG) add_assoc local.add_ubl local.distr local.mult_1_right local.order_def local.star_inductl local.star_unfoldl_eq)\n\nlemma (in kleene_algebra) star_slide: \"(x \\<cdot> y)\\<^sup>\\<star> \\<cdot> x = x \\<cdot> (y \\<cdot> x)\\<^sup>\\<star>\" \n  apply (rule order.antisym)\n   apply (smt (verit, del_insts) local.add_lub local.mult_1_right local.mult_isol local.star_inductl mult_assoc one_le_star star_unfoldlr)\n  by (smt (z3) local.distr local.eq_refl local.mult.semigroup_axioms local.mult_1_left local.star_inductr semigroup.assoc star_unfoldr_eq)\n\nlemma (in kleene_algebra) star_denest: \"(x + y)\\<^sup>\\<star> = x\\<^sup>\\<star> \\<cdot> (y \\<cdot> x\\<^sup>\\<star>)\\<^sup>\\<star>\" \n proof (rule order.antisym)\n  have a: \"1 \\<le> x\\<^sup>\\<star> \\<cdot> (y \\<cdot> x\\<^sup>\\<star>)\\<^sup>\\<star>\"\n    by (metis mult_1_right mult_isol order_trans one_le_star)\n  have b: \"x \\<cdot> x\\<^sup>\\<star> \\<cdot> (y \\<cdot> x\\<^sup>\\<star>)\\<^sup>\\<star> \\<le> x\\<^sup>\\<star> \\<cdot> (y \\<cdot> x\\<^sup>\\<star>)\\<^sup>\\<star>\"\n    by (simp add: mult_isor star_unfoldlr)\n  have \"y \\<cdot> x\\<^sup>\\<star> \\<cdot> (y \\<cdot> x\\<^sup>\\<star>)\\<^sup>\\<star> \\<le> (y \\<cdot> x\\<^sup>\\<star>)\\<^sup>\\<star>\"\n    by (simp add: star_unfoldlr)\n  also have  \"\\<dots> = 1 \\<cdot> (y \\<cdot> x\\<^sup>\\<star>)\\<^sup>\\<star>\"\n    by simp\n  also have \"\\<dots> \\<le>  x\\<^sup>\\<star> \\<cdot> (y \\<cdot> x\\<^sup>\\<star>)\\<^sup>\\<star>\"\n    using mult_isor one_le_star by blast\n  finally have \"y \\<cdot> x\\<^sup>\\<star> \\<cdot> (y \\<cdot> x\\<^sup>\\<star>)\\<^sup>\\<star> \\<le> x\\<^sup>\\<star> \\<cdot> (y \\<cdot> x\\<^sup>\\<star>)\\<^sup>\\<star>\".\n  hence \"1 + (x + y) \\<cdot> x\\<^sup>\\<star> \\<cdot> (y \\<cdot> x\\<^sup>\\<star>)\\<^sup>\\<star> \\<le> x\\<^sup>\\<star> \\<cdot> (y \\<cdot> x\\<^sup>\\<star>)\\<^sup>\\<star>\"\n    by (simp add: a b add_lub distr)\n  thus  \"(x + y)\\<^sup>\\<star> \\<le> x\\<^sup>\\<star> \\<cdot> (y \\<cdot> x\\<^sup>\\<star>)\\<^sup>\\<star>\"\n    using mult_assoc star_inductl by fastforce\n  have a: \"x\\<^sup>\\<star> \\<le> (x + y)\\<^sup>\\<star>\"\n    by (simp add: add_ubl star_iso)\n  have \"y \\<le> (x + y)\\<^sup>\\<star>\"\n    using add_lub star_infl by blast\n  hence \"(y \\<cdot> x\\<^sup>\\<star>)\\<^sup>\\<star> \\<le> ((x + y)\\<^sup>\\<star> \\<cdot> (x + y)\\<^sup>\\<star>)\\<^sup>\\<star>\"\n    using a mult_iso star_iso by blast\n  also have \"\\<dots> = (x + y)\\<^sup>\\<star>\"\n    by simp\n  finally have \"(y \\<cdot> x\\<^sup>\\<star>)\\<^sup>\\<star> \\<le> (x + y)\\<^sup>\\<star>\".\n  hence \"x\\<^sup>\\<star> \\<cdot> (y \\<cdot> x\\<^sup>\\<star>)\\<^sup>\\<star> \\<le> (x + y)\\<^sup>\\<star> \\<cdot> (x + y)\\<^sup>\\<star>\"\n    using a mult_iso by blast\n  also have \"\\<dots> \\<le> (x + y)\\<^sup>\\<star>\"\n    by simp\n  finally show \"x\\<^sup>\\<star> \\<cdot> (y \\<cdot> x\\<^sup>\\<star>)\\<^sup>\\<star> \\<le> (x + y)\\<^sup>\\<star>\".\nqed\n\nlemma (in kleene_algebra) star_subid: \"x \\<le> 1 \\<Longrightarrow> x\\<^sup>\\<star> = 1\"\n  by (metis add_commute local.mult_1_left local.order.refl local.order_def local.star_inductr one_le_star)\n\nlemma (in kleene_algebra) zero_star [simp]: \"0\\<^sup>\\<star> = 1\" \n  by (simp add: zero_least star_subid)\n\nlemma (in kleene_algebra) one_star [simp]: \"1\\<^sup>\\<star> = 1\" \n  by (simp add: star_subid)\n\nlemma (in kleene_algebra) star_sim1: \"z \\<cdot> x \\<le> y \\<cdot> z \\<Longrightarrow> z \\<cdot> x\\<^sup>\\<star> \\<le> y\\<^sup>\\<star> \\<cdot> z\"\n  by (smt (verit) add_assoc add_commute local.dd.distl local.dd.distr local.dd.mult_assoc local.mult_1_left local.order_def local.star_inductr one_le_star star_unfoldr_eq)\n\nlemma (in kleene_algebra) star_sim2: \"x \\<cdot> z \\<le> z \\<cdot> y \\<Longrightarrow> x\\<^sup>\\<star> \\<cdot> z  \\<le> z \\<cdot> y\\<^sup>\\<star>\"\n  by (simp add: local.dka.star_sim1)\n\nlemma (in kleene_algebra) star_inductl_var: \"x \\<cdot> y \\<le> y \\<Longrightarrow> x\\<^sup>\\<star> \\<cdot> y \\<le> y\"\n  by (simp add: local.add_least local.star_inductl) \n\nlemma (in kleene_algebra) star_inductr_var: \"y \\<cdot> x \\<le> y \\<Longrightarrow> y \\<cdot> x\\<^sup>\\<star> \\<le> y\"\n  by (simp add: local.dka.star_inductl_var)\n\nlemma (in kleene_algebra) church_rosser: \"y\\<^sup>\\<star> \\<cdot> x\\<^sup>\\<star> \\<le> x\\<^sup>\\<star> \\<cdot> y\\<^sup>\\<star> \\<Longrightarrow> (x + y)\\<^sup>\\<star> = x\\<^sup>\\<star> \\<cdot> y\\<^sup>\\<star>\" \n  apply (rule order.antisym)\n  apply (smt (verit, ccfv_SIG) add_commute local.mult_isor mult_assoc star_denest star_idem star_sim1 star_trans)\n  by (metis local.add_ubl local.add_ubr local.mult_iso star_iso star_trans)\n\nlemma (in kleene_algebra) power_sup: \"((\\<Sum>i=0..n. x^i) \\<le> y) = (\\<forall>i. 0 \\<le> i \\<and> i \\<le> n \\<longrightarrow> x^i \\<le> y)\"\n  apply (induct n)\n   apply simp\n  using le_Suc_eq local.add_lub by force\n\nlemma (in kleene_algebra) power_dist: \"(\\<Sum>i=0..n. x ^ i) \\<cdot> x = (\\<Sum>i=0..n. x ^ Suc i)\"\n  apply (induct n)\n   apply simp\n  using local.distr local.power_Suc2 local.sum.atLeast0_atMost_Suc by presburger \n\nlemma (in kleene_algebra) power_sum: \"(\\<Sum>i=0..n. x ^ Suc i) = (\\<Sum>i=1..n. x ^ i) + x ^ Suc n\"\n  apply (induct n)\n  by force+\n\nlemma (in kleene_algebra) sum_star: \"x\\<^sup>\\<star> = (x ^ Suc n)\\<^sup>\\<star> \\<cdot> (\\<Sum>i=0..n. x ^ i)\"\nproof (rule order.antisym)\n  have \"1 + (x ^ Suc n)\\<^sup>\\<star> \\<cdot> (\\<Sum>i=0..n. x ^ i) \\<cdot> x = 1 + (x ^ Suc n)\\<^sup>\\<star> \\<cdot> (\\<Sum>i=0..n. x ^ Suc i)\"\n    using local.mult_assoc power_dist by presburger\n  also have \"\\<dots> =  1 + (x ^ Suc n)\\<^sup>\\<star> \\<cdot> (\\<Sum>i=1..n. x ^ i) + (x ^ Suc n)\\<^sup>\\<star> \\<cdot> x ^ Suc n\"\n    using local.add_assoc local.distl local.power_sum by presburger\n  also have \"\\<dots> = (x ^ Suc n)\\<^sup>\\<star> \\<cdot> (\\<Sum>i=1..n. x ^ i) + (x ^ Suc n)\\<^sup>\\<star>\"\n    by (metis local.add.left_commute local.add_assoc star_unfoldr_eq)\n  also have \"\\<dots> = (x ^ Suc n)\\<^sup>\\<star> \\<cdot> (1 + (\\<Sum>i=1..n. x ^ i))\"\n    using add_commute local.distl local.mult_1_right by presburger\n  also have \"\\<dots> = (x ^ Suc n)\\<^sup>\\<star> \\<cdot> (\\<Sum>i=0..n. x ^ i)\"\n    by (simp add: local.sum.atLeast_Suc_atMost)\n  finally show \"x\\<^sup>\\<star> \\<le> (x ^ Suc n)\\<^sup>\\<star> \\<cdot> sum ((^) x) {0..n}\"\n    by (metis local.mult_1_left local.order_refl local.star_inductr)\nnext\n  have a: \"(x ^ Suc n)\\<^sup>\\<star> \\<le> x\\<^sup>\\<star>\"\n    by (metis star_idem star_iso star_power)\n  have \"(\\<Sum>i=0..n. x ^ i) \\<le> x\\<^sup>\\<star>\"\n    using power_sup star_power by presburger\n  thus \"(x ^ Suc n)\\<^sup>\\<star> \\<cdot> sum ((^) x) {0..n} \\<le> x\\<^sup>\\<star>\"\n    by (metis a local.mult_iso star_trans)\nqed\n\nlemma (in kleene_algebra) newman_aux: \"x\\<^sup>\\<star> \\<cdot> y \\<cdot> z\\<^sup>\\<star> = x\\<^sup>\\<star> \\<cdot> y + x\\<^sup>\\<star> \\<cdot> x \\<cdot> y \\<cdot> z \\<cdot> z\\<^sup>\\<star> + y \\<cdot> z\\<^sup>\\<star>\"\n  by (smt (z3) add_commute local.add.left_commute local.distl local.distr local.mult.monoid_axioms local.mult.semigroup_axioms local.mult_1_right local.order_def monoid.left_neutral one_le_star semigroup.assoc star_unfoldl_eq star_unfoldr_eq)\n\nend\n", "meta": {"author": "gstruth", "repo": "catoids", "sha": "1b7c623d742bcacfecf1a60518106c31716bf2dd", "save_path": "github-repos/isabelle/gstruth-catoids", "path": "github-repos/isabelle/gstruth-catoids/catoids-1b7c623d742bcacfecf1a60518106c31716bf2dd/KA_light.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8539127417985637, "lm_q2_score": 0.8397339656668287, "lm_q1q2_score": 0.7170595330039427}}
{"text": "theory prop_53\nimports Main\n        \"$HIPSTER_HOME/IsaHipster\"\nbegin\n  datatype 'a list = Nil2 | Cons2 \"'a\" \"'a list\"\n  datatype Nat = Z | S \"Nat\"\n  fun 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  fun insort :: \"Nat => Nat list => Nat list\" where\n  \"insort x (Nil2) = Cons2 x (Nil2)\"\n  | \"insort x (Cons2 z xs) =\n       (if le x z then Cons2 x (Cons2 z xs) else Cons2 z (insort x xs))\"\n  fun sort :: \"Nat list => Nat list\" where\n  \"sort (Nil2) = Nil2\"\n  | \"sort (Cons2 y xs) = insort y (sort xs)\"\n  fun equal2 :: \"Nat => Nat => bool\" where\n  \"equal2 (Z) (Z) = True\"\n  | \"equal2 (Z) (S z) = False\"\n  | \"equal2 (S x2) (Z) = False\"\n  | \"equal2 (S x2) (S y2) = equal2 x2 y2\"\n  fun count :: \"Nat => Nat list => Nat\" where\n  \"count x (Nil2) = Z\"\n  | \"count x (Cons2 z ys) =\n       (if equal2 x z then S (count x ys) else count x ys)\"\n  (*hipster le insort sort equal2 count *)\n\nlemma lemma_a [thy_expl]: \"equal2 x4 y4 = equal2 y4 x4\"\nby (hipster_induct_schemes equal2.simps)\n\nlemma lemma_aa [thy_expl]: \"equal2 x2 x2 = True\"\nby (hipster_induct_schemes equal2.simps)\n\nlemma lemma_ab [thy_expl]: \"equal2 x2 (S x2) = False\"\nby (hipster_induct_schemes equal2.simps)\n\n(*hipster le*)\nlemma lemma_ac [thy_expl]: \"le x2 x2 = True\"\nby (hipster_induct_schemes le.simps)\n\nlemma lemma_ad [thy_expl]: \"le x2 (S x2) = True\"\nby (hipster_induct_schemes le.simps)\n\nlemma lemma_ae [thy_expl]: \"le (S x2) x2 = False\"\nby (hipster_induct_schemes le.simps)\n\nlemma lemma_af [thy_expl]: \"le x2 x2 = True\"\nby (hipster_induct_schemes insort.simps)\n\nlemma lemma_ag [thy_expl]: \"le x2 (S x2) = True\"\nby (hipster_induct_schemes insort.simps)\n\nlemma lemma_ah [thy_expl]: \"le (S x2) x2 = False\"\nby (hipster_induct_schemes insort.simps)\n\nlemma lemma_ai [thy_expl]: \"insort Z (sort x2) = sort (insort Z x2)\"\nby (hipster_induct_schemes  sort.simps)\n(*\nhipster_cond le insort\\<exclamdown>d\n\n\nhipster_cond equal2 count sort\n\nhipster insort sort count\n\n\n  theorem x0 :\n    \"(count n xs) = (count n (sort xs))\"\n    by (tactic {* Subgoal.FOCUS_PARAMS (K (Tactic_Data.hard_tac @{context})) @{context} 1 *})\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/isaplanner/prop_53.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070109242131, "lm_q2_score": 0.7879312056025699, "lm_q1q2_score": 0.716944128103746}}
{"text": "theory ex4_06 imports Main \"~~/src/HOL/IMP/AExp\" begin\n\ninductive aval_rel :: \"aexp \\<Rightarrow> state \\<Rightarrow> val \\<Rightarrow> bool\" where\nconst_rel: \"aval_rel (N n) _ n\" |\nvar_rel: \"v = s x \\<Longrightarrow> aval_rel (V x) s v\" |\npl_rel: \"\\<lbrakk> aval_rel a1 s v1; aval_rel a2 s v2; v = v1+v2 \\<rbrakk> \\<Longrightarrow> aval_rel (Plus a1 a2) s v\"\n\n\ntheorem rel2val: \"aval_rel a s v \\<Longrightarrow> aval a s = v\"\nby (induction rule: \"aval_rel.induct\", auto)\n\ntheorem val2rel: \"aval a s = v \\<Longrightarrow> aval_rel a s v\"\napply(induction arbitrary: s v rule: aexp.induct)\napply(simp add: const_rel)\napply(simp add: var_rel)\napply(rule pl_rel)\napply auto\ndone\n\ntheorem \"aval_rel a s v \\<longleftrightarrow> aval a s = v\"\nusing rel2val val2rel by blast\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_06.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9099070060380482, "lm_q2_score": 0.7879311856832191, "lm_q1q2_score": 0.7169441061290273}}
{"text": "(* Author: Florian Haftmann, TU Muenchen *)\n\nsection \\<open>Preorders with explicit equivalence relation\\<close>\n\ntheory Preorder\nimports Main\nbegin\n\nclass preorder_equiv = preorder\nbegin\n\ndefinition equiv :: \"'a \\<Rightarrow> 'a \\<Rightarrow> bool\"\n  where \"equiv x y \\<longleftrightarrow> x \\<le> y \\<and> y \\<le> x\"\n\nnotation\n  equiv (\"'(\\<approx>')\") and\n  equiv (\"(_/ \\<approx> _)\"  [51, 51] 50)\n\nlemma equivD1: \"x \\<le> y\" if \"x \\<approx> y\"\n  using that by (simp add: equiv_def)\n\nlemma equivD2: \"y \\<le> x\" if \"x \\<approx> y\"\n  using that by (simp add: equiv_def)\n\nlemma equiv_refl [iff]: \"x \\<approx> x\"\n  by (simp add: equiv_def)\n\nlemma equiv_sym: \"x \\<approx> y \\<longleftrightarrow> y \\<approx> x\"\n  by (auto simp add: equiv_def)\n\nlemma equiv_trans: \"x \\<approx> y \\<Longrightarrow> y \\<approx> z \\<Longrightarrow> x \\<approx> z\"\n  by (auto simp: equiv_def intro: order_trans)\n\nlemma equiv_antisym: \"x \\<le> y \\<Longrightarrow> y \\<le> x \\<Longrightarrow> x \\<approx> y\"\n  by (simp only: equiv_def)\n\nlemma less_le: \"x < y \\<longleftrightarrow> x \\<le> y \\<and> \\<not> x \\<approx> y\"\n  by (auto simp add: equiv_def less_le_not_le)\n\nlemma le_less: \"x \\<le> y \\<longleftrightarrow> x < y \\<or> x \\<approx> y\"\n  by (auto simp add: equiv_def less_le)\n\nlemma le_imp_less_or_equiv: \"x \\<le> y \\<Longrightarrow> x < y \\<or> x \\<approx> y\"\n  by (simp add: less_le)\n\nlemma less_imp_not_equiv: \"x < y \\<Longrightarrow> \\<not> x \\<approx> y\"\n  by (simp add: less_le)\n\nlemma not_equiv_le_trans: \"\\<not> a \\<approx> b \\<Longrightarrow> a \\<le> b \\<Longrightarrow> a < b\"\n  by (simp add: less_le)\n\nlemma le_not_equiv_trans: \"a \\<le> b \\<Longrightarrow> \\<not> a \\<approx> b \\<Longrightarrow> a < b\"\n  by (rule not_equiv_le_trans)\n\nlemma antisym_conv: \"y \\<le> x \\<Longrightarrow> x \\<le> y \\<longleftrightarrow> x \\<approx> y\"\n  by (simp add: equiv_def)\n\nend\n\nML_file \\<open>~~/src/Provers/preorder.ML\\<close>\n\nML \\<open>\nstructure Quasi = Quasi_Tac(\nstruct\n\nval le_trans = @{thm order_trans};\nval le_refl = @{thm order_refl};\nval eqD1 = @{thm equivD1};\nval eqD2 = @{thm equivD2};\nval less_reflE = @{thm less_irrefl};\nval less_imp_le = @{thm less_imp_le};\nval le_neq_trans = @{thm le_not_equiv_trans};\nval neq_le_trans = @{thm not_equiv_le_trans};\nval less_imp_neq = @{thm less_imp_not_equiv};\n\nfun decomp_quasi thy (Const (@{const_name less_eq}, _) $ t1 $ t2) = SOME (t1, \"<=\", t2)\n  | decomp_quasi thy (Const (@{const_name less}, _) $ t1 $ t2) = SOME (t1, \"<\", t2)\n  | decomp_quasi thy (Const (@{const_name equiv}, _) $ t1 $ t2) = SOME (t1, \"=\", t2)\n  | decomp_quasi thy (Const (@{const_name Not}, _) $ (Const (@{const_name equiv}, _) $ t1 $ t2)) = SOME (t1, \"~=\", t2)\n  | decomp_quasi thy _ = NONE;\n\nfun decomp_trans thy t = case decomp_quasi thy t of\n    x as SOME (t1, \"<=\", t2) => x\n  | _ => NONE;\n\nend\n);\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/Library/Preorder.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045877523147, "lm_q2_score": 0.8080672112416737, "lm_q1q2_score": 0.7169209370258317}}
{"text": "(* Title: Design_Isomorphisms\n   Author: Chelsea Edmonds \n*)\n\nsection \\<open> Design Isomorphisms \\<close>\n\ntheory Design_Isomorphisms imports Design_Basics Sub_Designs\nbegin\n\nsubsection \\<open> Images of Set Systems \\<close>\n\ntext \\<open> We loosely define the concept of taking the \"image\" of a set system, as done in isomorphisms. \nNote that this is not based off mathematical theory, but is for ease of notation \\<close>\ndefinition blocks_image :: \"'a set multiset \\<Rightarrow> ('a \\<Rightarrow> 'b) \\<Rightarrow> 'b set multiset\" where\n\"blocks_image B f \\<equiv> image_mset ((`) f) B\"\n\nlemma image_block_set_constant_size: \"size (B) = size (blocks_image B f)\"\n  by (simp add: blocks_image_def)\n\nlemma (in incidence_system) image_set_system_wellformed: \n  \"incidence_system (f ` \\<V>) (blocks_image \\<B> f)\"\n  by (unfold_locales, auto simp add: blocks_image_def) (meson image_eqI wf_invalid_point)\n\nlemma (in finite_incidence_system) image_set_system_finite: \n  \"finite_incidence_system (f ` \\<V>) (blocks_image \\<B> f)\"\n  using image_set_system_wellformed finite_sets \n  by (intro_locales) (simp_all add: blocks_image_def finite_incidence_system_axioms.intro)\n\nsubsection \\<open>Incidence System Isomorphisms \\<close>\n\ntext \\<open>Isomorphism's are defined by the Handbook of Combinatorial Designs \n\\cite{colbournHandbookCombinatorialDesigns2007} \\<close>\n\nlocale incidence_system_isomorphism = source: incidence_system \\<V> \\<B> + target: incidence_system \\<V>' \\<B>'\n  for \"\\<V>\" and \"\\<B>\" and \"\\<V>'\" and \"\\<B>'\" + fixes bij_map (\"\\<pi>\")\n  assumes bij: \"bij_betw \\<pi> \\<V> \\<V>'\"\n  assumes block_img: \"image_mset ((`) \\<pi>) \\<B> = \\<B>'\"\nbegin\n\nlemma iso_eq_order: \"card \\<V> = card \\<V>'\"\n  using bij bij_betw_same_card by auto\n\nlemma iso_eq_block_num: \"size \\<B> = size \\<B>'\"\n  using block_img by (metis size_image_mset) \n\nlemma iso_block_img_alt_rep: \"{# \\<pi> ` bl . bl \\<in># \\<B>#} = \\<B>'\"\n  using block_img by simp\n\nlemma inv_iso_block_img: \"image_mset ((`) (inv_into \\<V> \\<pi>)) \\<B>' = \\<B>\"\nproof - \n  have \"\\<And> x. x \\<in> \\<V> \\<Longrightarrow> ((inv_into \\<V> \\<pi>) \\<circ> \\<pi>) x = x\"\n    using bij bij_betw_inv_into_left comp_apply by fastforce  \n  then have \"\\<And> bl x . bl \\<in># \\<B> \\<Longrightarrow> x \\<in> bl  \\<Longrightarrow> ((inv_into \\<V> \\<pi>) \\<circ> \\<pi>) x = x\" \n    using source.wellformed by blast\n  then have img: \"\\<And> bl . bl \\<in># \\<B> \\<Longrightarrow> image ((inv_into \\<V> \\<pi>) \\<circ> \\<pi>) bl = bl\"\n    by simp \n  have \"image_mset ((`) (inv_into \\<V> \\<pi>)) \\<B>' = image_mset ((`) (inv_into \\<V> \\<pi>)) (image_mset ((`) \\<pi>) \\<B>)\" \n    using block_img by simp\n  then have \"image_mset ((`) (inv_into \\<V> \\<pi>)) \\<B>' = image_mset ((`) ((inv_into \\<V> \\<pi>) \\<circ> \\<pi>)) \\<B>\"\n    by (metis (no_types, hide_lams) comp_apply image_comp multiset.map_comp multiset.map_cong0)\n  thus ?thesis using img by simp\nqed\n\nlemma inverse_incidence_sys_iso: \"incidence_system_isomorphism \\<V>' \\<B>' \\<V> \\<B> (inv_into \\<V> \\<pi>)\"\n  using bij bij_betw_inv_into inv_iso_block_img by (unfold_locales) simp\n\nlemma iso_points_map: \"\\<pi> ` \\<V> = \\<V>'\"\n  using bij by (simp add: bij_betw_imp_surj_on)\n\nlemma iso_points_inv_map: \"(inv_into \\<V> \\<pi>) `  \\<V>' = \\<V>\"\n  using incidence_system_isomorphism.iso_points_map inverse_incidence_sys_iso by blast\n\nlemma iso_points_ss_card: \n  assumes \"ps \\<subseteq> \\<V>\"\n  shows \"card ps = card (\\<pi> ` ps)\"\n  using assms bij bij_betw_same_card bij_betw_subset by blast\n\nlemma iso_block_in: \"bl \\<in># \\<B> \\<Longrightarrow> (\\<pi> ` bl) \\<in># \\<B>'\"\n  using iso_block_img_alt_rep\n  by (metis image_eqI in_image_mset)\n\nlemma iso_inv_block_in: \"x \\<in># \\<B>' \\<Longrightarrow> x \\<in> (`) \\<pi> ` set_mset \\<B>\"\n  by (metis block_img in_image_mset)\n\nlemma iso_img_block_orig_exists: \"x \\<in># \\<B>' \\<Longrightarrow> \\<exists> bl . bl \\<in># \\<B> \\<and> x = \\<pi> ` bl\"\n  using iso_inv_block_in by blast\n\nlemma iso_blocks_map_inj: \"x \\<in># \\<B> \\<Longrightarrow> y \\<in># \\<B> \\<Longrightarrow> \\<pi> ` x = \\<pi> ` y \\<Longrightarrow> x = y\"\n  using image_inv_into_cancel incidence_system.wellformed iso_points_inv_map iso_points_map\n  by (metis (no_types, lifting) source.incidence_system_axioms subset_image_iff)\n\nlemma iso_bij_betwn_block_sets: \"bij_betw ((`) \\<pi>) (set_mset \\<B>) (set_mset \\<B>')\"\n  apply ( simp add: bij_betw_def inj_on_def)\n  using iso_block_in iso_inv_block_in iso_blocks_map_inj by auto \n\nlemma iso_bij_betwn_block_sets_inv: \"bij_betw ((`) (inv_into \\<V> \\<pi>)) (set_mset \\<B>') (set_mset \\<B>)\"\n  using incidence_system_isomorphism.iso_bij_betwn_block_sets inverse_incidence_sys_iso by blast \n\nlemma iso_bij_betw_individual_blocks: \"bl \\<in># \\<B> \\<Longrightarrow> bij_betw \\<pi> bl (\\<pi> ` bl)\"\n  using bij bij_betw_subset source.wellformed by blast \n\nlemma iso_bij_betw_individual_blocks_inv: \"bl \\<in># \\<B> \\<Longrightarrow> bij_betw (inv_into \\<V> \\<pi>) (\\<pi> ` bl) bl\"\n  using bij bij_betw_subset source.wellformed bij_betw_inv_into_subset by fastforce \n\nlemma iso_bij_betw_individual_blocks_inv_alt: \n    \"bl \\<in># \\<B>' \\<Longrightarrow> bij_betw (inv_into \\<V> \\<pi>) bl ((inv_into \\<V> \\<pi>) ` bl)\"\n  using incidence_system_isomorphism.iso_bij_betw_individual_blocks inverse_incidence_sys_iso\n  by blast \n  \nlemma iso_inv_block_in_alt:  \"(\\<pi> ` bl) \\<in># \\<B>' \\<Longrightarrow> bl \\<subseteq> \\<V> \\<Longrightarrow> bl \\<in># \\<B>\"\n  using image_eqI image_inv_into_cancel inv_iso_block_img iso_points_inv_map\n  by (metis (no_types, lifting) iso_points_map multiset.set_map subset_image_iff)\n\nlemma iso_img_block_not_in: \n  assumes \"x \\<notin># \\<B>\"\n  assumes \"x \\<subseteq> \\<V>\"\n  shows \"(\\<pi> ` x) \\<notin># \\<B>'\"\nproof (rule ccontr)\n  assume a: \"\\<not> \\<pi> ` x \\<notin># \\<B>'\"\n  then have a: \"\\<pi> ` x \\<in># \\<B>'\" by simp\n  then have \"\\<And> y . y \\<in> (\\<pi> ` x) \\<Longrightarrow> (inv_into \\<V> \\<pi>) y \\<in> \\<V>\"\n    using target.wf_invalid_point iso_points_inv_map by auto \n  then have \"((`) (inv_into \\<V> \\<pi>)) (\\<pi> ` x) \\<in># \\<B>\" \n    using iso_bij_betwn_block_sets_inv by (meson a bij_betw_apply) \n  thus False\n    using a assms(1) assms(2) iso_inv_block_in_alt by blast \nqed\n\nlemma iso_block_multiplicity:\n  assumes  \"bl \\<subseteq> \\<V>\" \n  shows \"source.multiplicity bl = target.multiplicity (\\<pi> ` bl)\"\nproof (cases \"bl \\<in># \\<B>\")\n  case True\n  have \"inj_on ((`) \\<pi>) (set_mset \\<B>)\"\n    using bij_betw_imp_inj_on iso_bij_betwn_block_sets by auto \n  then have \"count \\<B> bl = count \\<B>' (\\<pi> ` bl)\" \n    using count_image_mset_le_count_inj_on count_image_mset_ge_count True block_img inv_into_f_f \n      less_le_not_le order.not_eq_order_implies_strict by metis  \n  thus ?thesis by simp\nnext\n  case False\n  have s_mult: \"source.multiplicity bl = 0\"\n    by (simp add: False count_eq_zero_iff) \n  then have \"target.multiplicity (\\<pi> ` bl) = 0\"\n    using False count_inI iso_inv_block_in_alt\n    by (metis assms) \n  thus ?thesis\n    using s_mult by simp\nqed\n\nlemma iso_point_in_block_img_iff: \"p \\<in> \\<V> \\<Longrightarrow> bl \\<in># \\<B> \\<Longrightarrow> p \\<in> bl \\<longleftrightarrow> (\\<pi> p) \\<in> (\\<pi> ` bl)\"\n  by (metis bij bij_betw_imp_surj_on iso_bij_betw_individual_blocks_inv bij_betw_inv_into_left imageI)\n\nlemma iso_point_subset_block_iff: \"p \\<subseteq> \\<V> \\<Longrightarrow> bl \\<in># \\<B> \\<Longrightarrow> p \\<subseteq> bl \\<longleftrightarrow> (\\<pi> ` p) \\<subseteq> (\\<pi> ` bl)\"\n  apply auto\n  using image_subset_iff iso_point_in_block_img_iff subset_iff by metis\n\nlemma iso_is_image_block: \"\\<B>' = blocks_image \\<B> \\<pi>\"\n  unfolding blocks_image_def by (simp add: block_img iso_points_map)\n\nend\n\nsubsection \\<open>Design Isomorphisms \\<close>\ntext \\<open> Apply the concept of isomorphisms to designs only \\<close>\n\nlocale design_isomorphism = incidence_system_isomorphism \\<V> \\<B> \\<V>' \\<B>' \\<pi> + source: design \\<V> \\<B> + \n  target: design \\<V>' \\<B>' for \\<V> and \\<B> and \\<V>' and \\<B>' and bij_map (\"\\<pi>\")\n  \ncontext design_isomorphism\nbegin\n\nlemma inverse_design_isomorphism: \"design_isomorphism \\<V>' \\<B>' \\<V> \\<B> (inv_into \\<V> \\<pi>)\"\n  using inverse_incidence_sys_iso source.wf_design target.wf_design\n  by (simp add: design_isomorphism.intro) \n\nend\n\nsubsubsection \\<open>Isomorphism Operation \\<close>\ntext \\<open> Define the concept of isomorphic designs outside the scope of locale \\<close>\n\ndefinition isomorphic_designs (infixl \"\\<cong>\\<^sub>D\" 50) where\n\"\\<D> \\<cong>\\<^sub>D \\<D>' \\<longleftrightarrow> (\\<exists> \\<pi> . design_isomorphism (fst \\<D>) (snd \\<D>) (fst \\<D>') (snd \\<D>') \\<pi>)\"\n\nlemma isomorphic_designs_symmetric: \"(\\<V>, \\<B>) \\<cong>\\<^sub>D (\\<V>', \\<B>') \\<Longrightarrow> (\\<V>', \\<B>') \\<cong>\\<^sub>D (\\<V>, \\<B>)\"\n  using isomorphic_designs_def design_isomorphism.inverse_design_isomorphism\n  by metis\n\nlemma isomorphic_designs_implies_bij: \"(\\<V>, \\<B>) \\<cong>\\<^sub>D (\\<V>', \\<B>') \\<Longrightarrow> \\<exists> \\<pi> . bij_betw \\<pi> \\<V> \\<V>'\"\n  using incidence_system_isomorphism.bij isomorphic_designs_def\n  by (metis design_isomorphism.axioms(1) fst_conv)\n\nlemma isomorphic_designs_implies_block_map: \"(\\<V>, \\<B>) \\<cong>\\<^sub>D (\\<V>', \\<B>') \\<Longrightarrow> \\<exists> \\<pi> . image_mset ((`) \\<pi>) \\<B> = \\<B>'\"\n  using incidence_system_isomorphism.block_img isomorphic_designs_def\n  using design_isomorphism.axioms(1) by fastforce\n\ncontext design\nbegin \n\nlemma isomorphic_designsI [intro]: \"design \\<V>' \\<B>' \\<Longrightarrow> bij_betw \\<pi> \\<V> \\<V>' \\<Longrightarrow> image_mset ((`) \\<pi>) \\<B> = \\<B>' \n    \\<Longrightarrow> (\\<V>, \\<B>) \\<cong>\\<^sub>D (\\<V>', \\<B>')\"\n  using design_isomorphism.intro isomorphic_designs_def wf_design image_set_system_wellformed\n  by (metis bij_betw_imp_surj_on blocks_image_def fst_conv incidence_system_axioms \n      incidence_system_isomorphism.intro incidence_system_isomorphism_axioms_def snd_conv)\n\nlemma eq_designs_isomorphic: \n  assumes \"\\<V> = \\<V>'\"\n  assumes \"\\<B> = \\<B>'\"\n  shows \"(\\<V>, \\<B>) \\<cong>\\<^sub>D (\\<V>', \\<B>')\" \nproof -\n  interpret d1: design \\<V> \\<B> using assms\n    using wf_design by auto \n  interpret d2: design \\<V>' \\<B>' using assms\n    using wf_design by blast \n  have \"design_isomorphism \\<V> \\<B> \\<V>' \\<B>' id\" using assms by (unfold_locales) simp_all\n  thus ?thesis unfolding isomorphic_designs_def by auto\nqed\n\nend\n\ncontext design_isomorphism\nbegin\n\nsubsubsection \\<open>Design Properties/Operations under Isomorphism \\<close>\n\nlemma design_iso_point_rep_num_eq: \n  assumes \"p \\<in> \\<V>\"\n  shows \"\\<B> rep p = \\<B>' rep (\\<pi> p)\"\nproof -\n  have \"{#b \\<in># \\<B> . p \\<in> b#} = {#b \\<in># \\<B> . \\<pi> p \\<in> \\<pi> ` b#}\" \n    using assms filter_mset_cong iso_point_in_block_img_iff assms by force\n  then have \"{#b \\<in># \\<B>' . \\<pi> p \\<in> b#} = image_mset ((`) \\<pi>) {#b \\<in># \\<B> . p \\<in> b#}\"\n    by (simp add: image_mset_filter_swap block_img)\n  thus ?thesis\n    by (simp add: point_replication_number_def) \nqed\n\nlemma design_iso_rep_numbers_eq: \"source.replication_numbers = target.replication_numbers\"\n  apply (simp add: source.replication_numbers_def target.replication_numbers_def)\n  using  design_iso_point_rep_num_eq design_isomorphism.design_iso_point_rep_num_eq iso_points_map\n  by (metis (no_types, hide_lams) imageI inverse_design_isomorphism iso_points_inv_map)\n\nlemma design_iso_block_size_eq: \"bl \\<in># \\<B> \\<Longrightarrow> card bl = card (\\<pi> ` bl)\"\n  using card_image_le finite_subset_image image_inv_into_cancel\n  by (metis iso_points_inv_map iso_points_map le_antisym source.finite_blocks source.wellformed)\n  \nlemma design_iso_block_sizes_eq: \"source.sys_block_sizes = target.sys_block_sizes\"\n  apply (simp add: source.sys_block_sizes_def target.sys_block_sizes_def)\n  by (metis (no_types, hide_lams) design_iso_block_size_eq iso_block_in iso_img_block_orig_exists) \n\nlemma design_iso_points_index_eq: \n  assumes \"ps \\<subseteq> \\<V>\" \n  shows \"\\<B> index ps = \\<B>' index (\\<pi> ` ps)\"\nproof - \n  have \"\\<And> b . b \\<in># \\<B> \\<Longrightarrow> ((ps \\<subseteq> b) = ((\\<pi> ` ps) \\<subseteq> \\<pi> ` b))\" \n    using iso_point_subset_block_iff assms by blast\n  then have \"{#b \\<in># \\<B> . ps \\<subseteq> b#} = {#b \\<in># \\<B> . (\\<pi> ` ps) \\<subseteq> (\\<pi> ` b)#}\" \n    using assms filter_mset_cong by force  \n  then have \"{#b \\<in># \\<B>' . \\<pi> ` ps \\<subseteq> b#} = image_mset ((`) \\<pi>) {#b \\<in># \\<B> . ps \\<subseteq> b#}\"\n    by (simp add: image_mset_filter_swap block_img)\n  thus ?thesis\n    by (simp add: points_index_def)\nqed\n\nlemma design_iso_points_indices_imp: \n  assumes \"x \\<in> source.point_indices t\"\n  shows \"x \\<in> target.point_indices t\"\nproof - \n  obtain ps where t: \"card ps = t\" and ss: \"ps \\<subseteq> \\<V>\" and x: \"\\<B> index ps = x\" using assms\n    by (auto simp add: source.point_indices_def)\n  then have x_val: \"x = \\<B>' index (\\<pi> ` ps)\" using design_iso_points_index_eq by auto\n  have x_img: \" (\\<pi> ` ps) \\<subseteq> \\<V>'\" \n    using ss bij iso_points_map by fastforce \n  then have \"card (\\<pi> ` ps) = t\" using t ss iso_points_ss_card by auto\n  then show ?thesis using target.point_indices_elem_in x_img x_val by blast \nqed\n\nlemma design_iso_points_indices_eq: \"source.point_indices t = target.point_indices t\"\n  using inverse_design_isomorphism design_isomorphism.design_iso_points_indices_imp\n    design_iso_points_indices_imp by blast \n\nlemma design_iso_block_intersect_num_eq: \n  assumes \"b1 \\<in># \\<B>\"\n  assumes \"b2 \\<in># \\<B>\"\n  shows \"b1 |\\<inter>| b2 = (\\<pi> ` b1) |\\<inter>| (\\<pi> ` b2)\"\nproof -\n  have split: \"\\<pi> ` (b1 \\<inter> b2) = (\\<pi> ` b1) \\<inter> (\\<pi> ` b2)\" using assms bij bij_betw_inter_subsets\n    by (metis source.wellformed) \n  thus ?thesis using source.wellformed\n    by (simp add: intersection_number_def iso_points_ss_card split assms(2) inf.coboundedI2) \nqed\n\nlemma design_iso_inter_numbers_imp: \n  assumes \"x \\<in> source.intersection_numbers\" \n  shows \"x \\<in> target.intersection_numbers\"\nproof - \n  obtain b1 b2 where 1: \"b1 \\<in># \\<B>\" and 2: \"b2 \\<in># (remove1_mset b1 \\<B>)\" and xval: \"x = b1 |\\<inter>| b2\" \n    using assms by (auto simp add: source.intersection_numbers_def)\n  then have pi1: \"\\<pi> ` b1 \\<in># \\<B>'\" by (simp add: iso_block_in)\n  have pi2: \"\\<pi> ` b2 \\<in># (remove1_mset (\\<pi> ` b1) \\<B>')\" using iso_block_in 2\n    by (metis (no_types, lifting) \"1\" block_img image_mset_remove1_mset_if in_remove1_mset_neq \n        iso_blocks_map_inj more_than_one_mset_mset_diff multiset.set_map)\n  have \"x = (\\<pi> ` b1) |\\<inter>| (\\<pi> ` b2)\" using 1 2 design_iso_block_intersect_num_eq\n    by (metis in_diffD xval)\n  then have \"x \\<in> {b1 |\\<inter>| b2 | b1 b2 . b1 \\<in># \\<B>' \\<and> b2 \\<in># (\\<B>' - {#b1#})}\" \n    using pi1 pi2 by blast\n  then show ?thesis by (simp add: target.intersection_numbers_def) \nqed\n\nlemma design_iso_intersection_numbers: \"source.intersection_numbers = target.intersection_numbers\"\n  using inverse_design_isomorphism design_isomorphism.design_iso_inter_numbers_imp \n      design_iso_inter_numbers_imp by blast\n\nlemma design_iso_n_intersect_num: \n  assumes \"b1 \\<in># \\<B>\" \n  assumes \"b2 \\<in># \\<B>\" \n  shows \"b1 |\\<inter>|\\<^sub>n b2 = ((\\<pi> ` b1) |\\<inter>|\\<^sub>n (\\<pi> ` b2))\"\nproof -\n  let ?A = \"{x . x \\<subseteq> b1 \\<and> x \\<subseteq> b2 \\<and> card x = n}\"\n  let ?B = \"{y . y \\<subseteq> (\\<pi> ` b1) \\<and> y \\<subseteq> (\\<pi> ` b2) \\<and> card y = n}\"\n  have b1v: \"b1 \\<subseteq> \\<V>\"  by (simp add: assms(1) source.wellformed) \n  have b2v: \"b2 \\<subseteq> \\<V>\"  by (simp add: assms(2) source.wellformed) \n  then have \"\\<And>x y . x \\<subseteq> b1 \\<Longrightarrow> x \\<subseteq> b2 \\<Longrightarrow> y \\<subseteq> b1 \\<Longrightarrow> y \\<subseteq> b2 \\<Longrightarrow>  \\<pi> ` x = \\<pi> ` y \\<Longrightarrow> x = y\"\n    using b1v bij by (metis bij_betw_imp_surj_on bij_betw_inv_into_subset dual_order.trans)\n  then have inj: \"inj_on ((`) \\<pi>) ?A\" by (simp add: inj_on_def)\n  have eqcard: \"\\<And>xa. xa \\<subseteq> b1 \\<Longrightarrow> xa \\<subseteq> b2 \\<Longrightarrow> card (\\<pi> ` xa) = card xa\" using b1v b2v bij\n    using iso_points_ss_card by auto \n  have surj: \"\\<And>x. x \\<subseteq> \\<pi> ` b1 \\<Longrightarrow> x \\<subseteq> \\<pi> ` b2  \\<Longrightarrow> \n                x \\<in> {(\\<pi> ` xa) | xa . xa \\<subseteq> b1 \\<and> xa \\<subseteq> b2 \\<and> card xa = card x}\"\n  proof - \n    fix x\n    assume x1: \"x \\<subseteq> \\<pi> ` b1\" and x2: \"x \\<subseteq> \\<pi> ` b2\" \n    then obtain xa where eq_x: \"\\<pi> ` xa = x\" and ss: \"xa \\<subseteq> \\<V>\"\n      by (metis b1v dual_order.trans subset_imageE)\n    then have f1: \"xa \\<subseteq> b1\" by (simp add: x1 assms(1) iso_point_subset_block_iff) \n    then have f2: \"xa \\<subseteq> b2\" by (simp add: eq_x ss assms(2) iso_point_subset_block_iff x2) \n    then have f3: \"card xa = card x\" using bij by (simp add: eq_x ss iso_points_ss_card)\n    then show \"x \\<in> {(\\<pi> ` xa) | xa . xa \\<subseteq> b1 \\<and> xa \\<subseteq> b2 \\<and> card xa = card x}\" \n      using f1 f2 f3 \\<open>\\<pi> ` xa = x\\<close> by auto\n  qed\n  have \"bij_betw ( (`) \\<pi>) ?A ?B\"\n  proof (auto simp add: bij_betw_def)\n    show \"inj_on ((`) \\<pi>) {x. x \\<subseteq> b1 \\<and> x \\<subseteq> b2 \\<and> card x = n}\" using inj by simp\n    show \"\\<And>xa. xa \\<subseteq> b1 \\<Longrightarrow> xa \\<subseteq> b2 \\<Longrightarrow> n = card xa \\<Longrightarrow> card (\\<pi> ` xa) = card xa\" \n      using eqcard by simp\n    show \"\\<And>x. x \\<subseteq> \\<pi> ` b1 \\<Longrightarrow> x \\<subseteq> \\<pi> ` b2 \\<Longrightarrow> n = card x \\<Longrightarrow> \n            x \\<in> (`) \\<pi> ` {xa. xa \\<subseteq> b1 \\<and> xa \\<subseteq> b2 \\<and> card xa = card x}\" \n      using surj by (simp add: setcompr_eq_image)\n  qed\n  thus ?thesis\n    using bij_betw_same_card by (auto simp add: n_intersect_number_def)\nqed\n\nlemma subdesign_iso_implies:\n  assumes \"sub_set_system V B \\<V> \\<B>\"\n  shows \"sub_set_system (\\<pi> ` V) (blocks_image B \\<pi>) \\<V>' \\<B>'\"\nproof (unfold_locales)\n  show \"\\<pi> ` V \\<subseteq> \\<V>'\" \n    by (metis assms image_mono iso_points_map sub_set_system.points_subset) \n  show \"blocks_image B \\<pi> \\<subseteq># \\<B>'\"\n    by (metis assms block_img blocks_image_def image_mset_subseteq_mono sub_set_system.blocks_subset) \nqed\n\nlemma subdesign_image_is_design: \n  assumes \"sub_set_system V B \\<V> \\<B>\"\n  assumes \"design V B\"\n  shows \"design (\\<pi> ` V) (blocks_image B \\<pi>)\"\nproof -\n  interpret fin: finite_incidence_system \"(\\<pi> ` V)\" \"(blocks_image B \\<pi>)\" using assms(2)\n    by (simp add: design.axioms(1) finite_incidence_system.image_set_system_finite)\n  interpret des: sub_design V B \\<V> \\<B> using assms design.wf_design_iff\n    by (unfold_locales, auto simp add: sub_set_system.points_subset sub_set_system.blocks_subset)\n  have bl_img: \"blocks_image B \\<pi> \\<subseteq># \\<B>'\"\n    by (simp add: blocks_image_def des.blocks_subset image_mset_subseteq_mono iso_is_image_block)  \n  then show ?thesis \n  proof (unfold_locales, auto)\n    show \"{} \\<in># blocks_image B \\<pi> \\<Longrightarrow> False\" \n      using assms subdesign_iso_implies target.blocks_nempty bl_img by auto\n  qed\nqed\n\nlemma sub_design_isomorphism: \n  assumes \"sub_set_system V B \\<V> \\<B>\"\n  assumes \"design V B\"\n  shows \"design_isomorphism V B (\\<pi> ` V) (blocks_image B \\<pi>) \\<pi>\"\nproof -\n  interpret design \"(\\<pi> ` V)\" \"(blocks_image B \\<pi>)\"\n    by (simp add: assms(1) assms(2) subdesign_image_is_design)\n  interpret des: design V B by fact\n  show ?thesis\n  proof (unfold_locales)\n    show \"bij_betw \\<pi> V (\\<pi> ` V)\" using bij\n      by (metis assms(1) bij_betw_subset sub_set_system.points_subset) \n    show \"image_mset ((`) \\<pi>) B = blocks_image B \\<pi>\" by (simp add: blocks_image_def)\n  qed\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/Design_Isomorphisms.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8558511469672595, "lm_q2_score": 0.8376199572530448, "lm_q1q2_score": 0.7168780011376853}}
{"text": "(*  Title:      HOL/Hahn_Banach/Function_Norm.thy\n    Author:     Gertrud Bauer, TU Munich\n*)\n\nsection \\<open>The norm of a function\\<close>\n\ntheory Function_Norm\nimports Normed_Space Function_Order\nbegin\n\nsubsection \\<open>Continuous linear forms\\<close>\n\ntext \\<open>\n  A linear form @{text f} on a normed vector space @{text \"(V, \\<parallel>\\<cdot>\\<parallel>)\"}\n  is \\emph{continuous}, iff it is bounded, i.e.\n  \\begin{center}\n  @{text \"\\<exists>c \\<in> R. \\<forall>x \\<in> V. \\<bar>f x\\<bar> \\<le> c \\<cdot> \\<parallel>x\\<parallel>\"}\n  \\end{center}\n  In our application no other functions than linear forms are\n  considered, so we can define continuous linear forms as bounded\n  linear forms:\n\\<close>\n\nlocale continuous = linearform +\n  fixes norm :: \"_ \\<Rightarrow> real\"    (\"\\<parallel>_\\<parallel>\")\n  assumes bounded: \"\\<exists>c. \\<forall>x \\<in> V. \\<bar>f x\\<bar> \\<le> c * \\<parallel>x\\<parallel>\"\n\ndeclare continuous.intro [intro?] continuous_axioms.intro [intro?]\n\nlemma continuousI [intro]:\n  fixes norm :: \"_ \\<Rightarrow> real\"  (\"\\<parallel>_\\<parallel>\")\n  assumes \"linearform V f\"\n  assumes r: \"\\<And>x. x \\<in> V \\<Longrightarrow> \\<bar>f x\\<bar> \\<le> c * \\<parallel>x\\<parallel>\"\n  shows \"continuous V f norm\"\nproof\n  show \"linearform V f\" by fact\n  from r have \"\\<exists>c. \\<forall>x\\<in>V. \\<bar>f x\\<bar> \\<le> c * \\<parallel>x\\<parallel>\" by blast\n  then show \"continuous_axioms V f norm\" ..\nqed\n\n\nsubsection \\<open>The norm of a linear form\\<close>\n\ntext \\<open>\n  The least real number @{text c} for which holds\n  \\begin{center}\n  @{text \"\\<forall>x \\<in> V. \\<bar>f x\\<bar> \\<le> c \\<cdot> \\<parallel>x\\<parallel>\"}\n  \\end{center}\n  is called the \\emph{norm} of @{text f}.\n\n  For non-trivial vector spaces @{text \"V \\<noteq> {0}\"} the norm can be\n  defined as\n  \\begin{center}\n  @{text \"\\<parallel>f\\<parallel> = \\<sup>x \\<noteq> 0. \\<bar>f x\\<bar> / \\<parallel>x\\<parallel>\"}\n  \\end{center}\n\n  For the case @{text \"V = {0}\"} the supremum would be taken from an\n  empty set. Since @{text \\<real>} is unbounded, there would be no supremum.\n  To avoid this situation it must be guaranteed that there is an\n  element in this set. This element must be @{text \"{} \\<ge> 0\"} so that\n  @{text fn_norm} has the norm properties. Furthermore it does not\n  have to change the norm in all other cases, so it must be @{text 0},\n  as all other elements are @{text \"{} \\<ge> 0\"}.\n\n  Thus we define the set @{text B} where the supremum is taken from as\n  follows:\n  \\begin{center}\n  @{text \"{0} \\<union> {\\<bar>f x\\<bar> / \\<parallel>x\\<parallel>. x \\<noteq> 0 \\<and> x \\<in> F}\"}\n  \\end{center}\n\n  @{text fn_norm} is equal to the supremum of @{text B}, if the\n  supremum exists (otherwise it is undefined).\n\\<close>\n\nlocale fn_norm =\n  fixes norm :: \"_ \\<Rightarrow> real\"    (\"\\<parallel>_\\<parallel>\")\n  fixes B defines \"B V f \\<equiv> {0} \\<union> {\\<bar>f x\\<bar> / \\<parallel>x\\<parallel> | x. x \\<noteq> 0 \\<and> x \\<in> V}\"\n  fixes fn_norm (\"\\<parallel>_\\<parallel>\\<hyphen>_\" [0, 1000] 999)\n  defines \"\\<parallel>f\\<parallel>\\<hyphen>V \\<equiv> \\<Squnion>(B V f)\"\n\nlocale normed_vectorspace_with_fn_norm = normed_vectorspace + fn_norm\n\nlemma (in fn_norm) B_not_empty [intro]: \"0 \\<in> B V f\"\n  by (simp add: B_def)\n\ntext \\<open>\n  The following lemma states that every continuous linear form on a\n  normed space @{text \"(V, \\<parallel>\\<cdot>\\<parallel>)\"} has a function norm.\n\\<close>\n\nlemma (in normed_vectorspace_with_fn_norm) fn_norm_works:\n  assumes \"continuous V f norm\"\n  shows \"lub (B V f) (\\<parallel>f\\<parallel>\\<hyphen>V)\"\nproof -\n  interpret continuous V f norm by fact\n  txt \\<open>The existence of the supremum is shown using the\n    completeness of the reals. Completeness means, that every\n    non-empty bounded set of reals has a supremum.\\<close>\n  have \"\\<exists>a. lub (B V f) a\"\n  proof (rule real_complete)\n    txt \\<open>First we have to show that @{text B} is non-empty:\\<close>\n    have \"0 \\<in> B V f\" ..\n    then show \"\\<exists>x. x \\<in> B V f\" ..\n\n    txt \\<open>Then we have to show that @{text B} is bounded:\\<close>\n    show \"\\<exists>c. \\<forall>y \\<in> B V f. y \\<le> c\"\n    proof -\n      txt \\<open>We know that @{text f} is bounded by some value @{text c}.\\<close>\n      from bounded obtain c where c: \"\\<forall>x \\<in> V. \\<bar>f x\\<bar> \\<le> c * \\<parallel>x\\<parallel>\" ..\n\n      txt \\<open>To prove the thesis, we have to show that there is some\n        @{text b}, such that @{text \"y \\<le> b\"} for all @{text \"y \\<in>\n        B\"}. Due to the definition of @{text B} there are two cases.\\<close>\n\n      def b \\<equiv> \"max c 0\"\n      have \"\\<forall>y \\<in> B V f. y \\<le> b\"\n      proof\n        fix y assume y: \"y \\<in> B V f\"\n        show \"y \\<le> b\"\n        proof cases\n          assume \"y = 0\"\n          then show ?thesis unfolding b_def by arith\n        next\n          txt \\<open>The second case is @{text \"y = \\<bar>f x\\<bar> / \\<parallel>x\\<parallel>\"} for some\n            @{text \"x \\<in> V\"} with @{text \"x \\<noteq> 0\"}.\\<close>\n          assume \"y \\<noteq> 0\"\n          with y obtain x where y_rep: \"y = \\<bar>f x\\<bar> * inverse \\<parallel>x\\<parallel>\"\n              and x: \"x \\<in> V\" and neq: \"x \\<noteq> 0\"\n            by (auto simp add: B_def divide_inverse)\n          from x neq have gt: \"0 < \\<parallel>x\\<parallel>\" ..\n\n          txt \\<open>The thesis follows by a short calculation using the\n            fact that @{text f} is bounded.\\<close>\n\n          note y_rep\n          also have \"\\<bar>f x\\<bar> * inverse \\<parallel>x\\<parallel> \\<le> (c * \\<parallel>x\\<parallel>) * inverse \\<parallel>x\\<parallel>\"\n          proof (rule mult_right_mono)\n            from c x show \"\\<bar>f x\\<bar> \\<le> c * \\<parallel>x\\<parallel>\" ..\n            from gt have \"0 < inverse \\<parallel>x\\<parallel>\" \n              by (rule positive_imp_inverse_positive)\n            then show \"0 \\<le> inverse \\<parallel>x\\<parallel>\" by (rule order_less_imp_le)\n          qed\n          also have \"\\<dots> = c * (\\<parallel>x\\<parallel> * inverse \\<parallel>x\\<parallel>)\"\n            by (rule Groups.mult.assoc)\n          also\n          from gt have \"\\<parallel>x\\<parallel> \\<noteq> 0\" by simp\n          then have \"\\<parallel>x\\<parallel> * inverse \\<parallel>x\\<parallel> = 1\" by simp \n          also have \"c * 1 \\<le> b\" by (simp add: b_def)\n          finally show \"y \\<le> b\" .\n        qed\n      qed\n      then show ?thesis ..\n    qed\n  qed\n  then show ?thesis unfolding fn_norm_def by (rule the_lubI_ex)\nqed\n\nlemma (in normed_vectorspace_with_fn_norm) fn_norm_ub [iff?]:\n  assumes \"continuous V f norm\"\n  assumes b: \"b \\<in> B V f\"\n  shows \"b \\<le> \\<parallel>f\\<parallel>\\<hyphen>V\"\nproof -\n  interpret continuous V f norm by fact\n  have \"lub (B V f) (\\<parallel>f\\<parallel>\\<hyphen>V)\"\n    using \\<open>continuous V f norm\\<close> by (rule fn_norm_works)\n  from this and b show ?thesis ..\nqed\n\nlemma (in normed_vectorspace_with_fn_norm) fn_norm_leastB:\n  assumes \"continuous V f norm\"\n  assumes b: \"\\<And>b. b \\<in> B V f \\<Longrightarrow> b \\<le> y\"\n  shows \"\\<parallel>f\\<parallel>\\<hyphen>V \\<le> y\"\nproof -\n  interpret continuous V f norm by fact\n  have \"lub (B V f) (\\<parallel>f\\<parallel>\\<hyphen>V)\"\n    using \\<open>continuous V f norm\\<close> by (rule fn_norm_works)\n  from this and b show ?thesis ..\nqed\n\ntext \\<open>The norm of a continuous function is always @{text \"\\<ge> 0\"}.\\<close>\n\nlemma (in normed_vectorspace_with_fn_norm) fn_norm_ge_zero [iff]:\n  assumes \"continuous V f norm\"\n  shows \"0 \\<le> \\<parallel>f\\<parallel>\\<hyphen>V\"\nproof -\n  interpret continuous V f norm by fact\n  txt \\<open>The function norm is defined as the supremum of @{text B}.\n    So it is @{text \"\\<ge> 0\"} if all elements in @{text B} are @{text \"\\<ge>\n    0\"}, provided the supremum exists and @{text B} is not empty.\\<close>\n  have \"lub (B V f) (\\<parallel>f\\<parallel>\\<hyphen>V)\"\n    using \\<open>continuous V f norm\\<close> by (rule fn_norm_works)\n  moreover have \"0 \\<in> B V f\" ..\n  ultimately show ?thesis ..\nqed\n\ntext \\<open>\n  \\medskip The fundamental property of function norms is:\n  \\begin{center}\n  @{text \"\\<bar>f x\\<bar> \\<le> \\<parallel>f\\<parallel> \\<cdot> \\<parallel>x\\<parallel>\"}\n  \\end{center}\n\\<close>\n\nlemma (in normed_vectorspace_with_fn_norm) fn_norm_le_cong:\n  assumes \"continuous V f norm\" \"linearform V f\"\n  assumes x: \"x \\<in> V\"\n  shows \"\\<bar>f x\\<bar> \\<le> \\<parallel>f\\<parallel>\\<hyphen>V * \\<parallel>x\\<parallel>\"\nproof -\n  interpret continuous V f norm by fact\n  interpret linearform V f by fact\n  show ?thesis\n  proof cases\n    assume \"x = 0\"\n    then have \"\\<bar>f x\\<bar> = \\<bar>f 0\\<bar>\" by simp\n    also have \"f 0 = 0\" by rule unfold_locales\n    also have \"\\<bar>\\<dots>\\<bar> = 0\" by simp\n    also have a: \"0 \\<le> \\<parallel>f\\<parallel>\\<hyphen>V\"\n      using \\<open>continuous V f norm\\<close> by (rule fn_norm_ge_zero)\n    from x have \"0 \\<le> norm x\" ..\n    with a have \"0 \\<le> \\<parallel>f\\<parallel>\\<hyphen>V * \\<parallel>x\\<parallel>\" by (simp add: zero_le_mult_iff)\n    finally show \"\\<bar>f x\\<bar> \\<le> \\<parallel>f\\<parallel>\\<hyphen>V * \\<parallel>x\\<parallel>\" .\n  next\n    assume \"x \\<noteq> 0\"\n    with x have neq: \"\\<parallel>x\\<parallel> \\<noteq> 0\" by simp\n    then have \"\\<bar>f x\\<bar> = (\\<bar>f x\\<bar> * inverse \\<parallel>x\\<parallel>) * \\<parallel>x\\<parallel>\" by simp\n    also have \"\\<dots> \\<le>  \\<parallel>f\\<parallel>\\<hyphen>V * \\<parallel>x\\<parallel>\"\n    proof (rule mult_right_mono)\n      from x show \"0 \\<le> \\<parallel>x\\<parallel>\" ..\n      from x and neq have \"\\<bar>f x\\<bar> * inverse \\<parallel>x\\<parallel> \\<in> B V f\"\n        by (auto simp add: B_def divide_inverse)\n      with \\<open>continuous V f norm\\<close> show \"\\<bar>f x\\<bar> * inverse \\<parallel>x\\<parallel> \\<le> \\<parallel>f\\<parallel>\\<hyphen>V\"\n        by (rule fn_norm_ub)\n    qed\n    finally show ?thesis .\n  qed\nqed\n\ntext \\<open>\n  \\medskip The function norm is the least positive real number for\n  which the following inequation holds:\n  \\begin{center}\n    @{text \"\\<bar>f x\\<bar> \\<le> c \\<cdot> \\<parallel>x\\<parallel>\"}\n  \\end{center}\n\\<close>\n\nlemma (in normed_vectorspace_with_fn_norm) fn_norm_least [intro?]:\n  assumes \"continuous V f norm\"\n  assumes ineq: \"\\<And>x. x \\<in> V \\<Longrightarrow> \\<bar>f x\\<bar> \\<le> c * \\<parallel>x\\<parallel>\" and ge: \"0 \\<le> c\"\n  shows \"\\<parallel>f\\<parallel>\\<hyphen>V \\<le> c\"\nproof -\n  interpret continuous V f norm by fact\n  show ?thesis\n  proof (rule fn_norm_leastB [folded B_def fn_norm_def])\n    fix b assume b: \"b \\<in> B V f\"\n    show \"b \\<le> c\"\n    proof cases\n      assume \"b = 0\"\n      with ge show ?thesis by simp\n    next\n      assume \"b \\<noteq> 0\"\n      with b obtain x where b_rep: \"b = \\<bar>f x\\<bar> * inverse \\<parallel>x\\<parallel>\"\n        and x_neq: \"x \\<noteq> 0\" and x: \"x \\<in> V\"\n        by (auto simp add: B_def divide_inverse)\n      note b_rep\n      also have \"\\<bar>f x\\<bar> * inverse \\<parallel>x\\<parallel> \\<le> (c * \\<parallel>x\\<parallel>) * inverse \\<parallel>x\\<parallel>\"\n      proof (rule mult_right_mono)\n        have \"0 < \\<parallel>x\\<parallel>\" using x x_neq ..\n        then show \"0 \\<le> inverse \\<parallel>x\\<parallel>\" by simp\n        from x show \"\\<bar>f x\\<bar> \\<le> c * \\<parallel>x\\<parallel>\" by (rule ineq)\n      qed\n      also have \"\\<dots> = c\"\n      proof -\n        from x_neq and x have \"\\<parallel>x\\<parallel> \\<noteq> 0\" by simp\n        then show ?thesis by simp\n      qed\n      finally show ?thesis .\n    qed\n  qed (insert \\<open>continuous V f norm\\<close>, simp_all add: continuous_def)\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/Hahn_Banach/Function_Norm.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8791467706759583, "lm_q2_score": 0.8152324826183822, "lm_q1q2_score": 0.716709004444095}}
{"text": "theory hw02\n  imports Main\nbegin\n\nfun collect:: \"'a \\<Rightarrow> ('a \\<times> 'b) list \\<Rightarrow> 'b list\" where\n  \"collect x [] = []\"\n| \"collect x ((k,y)#xs) = (if x = k then y # collect x xs else collect x xs)\"\n\ndefinition ctest :: \" (int * int) list\" where \"ctest = [\n(2 ,3 ),(2 ,5 ),(2 ,7 ),(2 ,9 ),\n(3 ,2 ),(3 ,4 ),(3 ,5 ),(3 ,7 ),(3 ,8 ),\n(4 ,3 ),(4 ,5 ),(4 ,7 ),(4 ,9 ),\n(5 ,2 ),(5 ,3 ),(5 ,4 ),(5 ,6 ),(5 ,7 ),(5 ,8 ),(5 ,9 ),\n(6 ,5 ),(6 ,7 ),\n(7 ,2 ),(7 ,3 ),(7 ,4 ),(7 ,5 ),(7 ,6 ),(7 ,8 ),(7 ,9 ),\n(8 ,3 ),(8 ,5 ),(8 ,7 ),(8 ,9 ),\n(9 ,2 ),(9 ,4 ),(9 ,5 ),(9 ,7 ),(9 ,8 )\n]\"\nvalue \"collect 3 ctest = [2 ,4 ,5 ,7, 8 ]\"\nvalue \"collect 1 ctest = []\"\n\nlemma \"collect x ys = map snd (filter (\\<lambda>kv. fst kv = x) ys)\"\n  apply(induction ys)\n   apply(auto)\n  done\n\nfun collect_tr:: \"'b list \\<Rightarrow> 'a \\<Rightarrow> ('a * 'b) list \\<Rightarrow> 'b list\" where\n  \"collect_tr acc x [] = rev acc\"\n| \"collect_tr acc x ((k,v)#ys) = (if (x = k) then collect_tr (v # acc) x ys else collect_tr acc x ys)\"\n\nlemma collect_gen:\"collect_tr acc x ys = rev acc @ (collect x ys)\"\n  apply(induction ys arbitrary:acc)\n   apply(auto)\n  done\n\nlemma \"collect_tr [] x ys = collect x ys\"\n  apply(induction ys)\n   apply(auto simp:collect_gen)\n  done\n\n\n\n\n\n\ndatatype 'a ltree = Leaf 'a | Node \"'a ltree\" \"'a ltree\" \n\nfun lheight:: \"'a ltree \\<Rightarrow> nat\" where\n  \"lheight (Leaf x) = 0\"\n| \"lheight (Node x y) = max (lheight x) (lheight y) + 1\"\n\nvalue \"lheight (Node (Leaf (1::nat)) (Node (Leaf 2) (Leaf 4)))\"\n\nfun num_leafs:: \"'a ltree \\<Rightarrow> nat\" where\n  \"num_leafs (Leaf x) = 1\"\n| \"num_leafs (Node x y) = num_leafs x + num_leafs y\"\n\nvalue \"num_leafs (Node (Leaf (1::nat)) (Node (Leaf 2) (Leaf 4)))\"\n\nfun balanced:: \"'a ltree \\<Rightarrow> bool\" where\n  \"balanced (Leaf a) = True\"\n| \"balanced (Node x y) = (op &)((op &)(lheight x = lheight y)(balanced x))(balanced y)\"\n\nvalue \"balanced (Node (Node (Leaf a\\<^sub>1) (Node (Leaf a\\<^sub>1) (Leaf a\\<^sub>1))) (Node (Leaf a\\<^sub>1) (Node (Leaf a\\<^sub>1) (Leaf a\\<^sub>1))))\"\n\n\nlemma \"balanced t \\<Longrightarrow> num_leafs t = 2 ^ lheight t\"\n  apply(induction t)\n  apply(auto)\n  done\n\n\n\n\n\n\nfun denc :: \"int \\<Rightarrow> int list \\<Rightarrow> int list\" where\n  \"denc a [] = []\"\n| \"denc a (x#xs) = (x-a) # denc x xs\"\n\nvalue \"denc 0 [1,2,4,8]\"\nvalue \"denc 0 [3,4,5]\"\nvalue \"denc 0 [5]\"\nvalue \"denc 0 []\"\n\nfun ddec :: \"int \\<Rightarrow> int list \\<Rightarrow> int list\" where\n  \"ddec a [] = []\"\n| \"ddec (a::int) (x#xs) = (x + a) # (ddec (x + a) xs)\"\n\nvalue \"ddec 0 [1,1,2,4]\"\nvalue \"ddec 0 [3,1,1]\"\nvalue \"ddec 0 [5]\"\nvalue \"ddec 0 []\"\n\nvalue \"ddec 5 (denc 4 [1,2,3])\"\n\nlemma encdecgen: \"ddec n (denc n l) = l\"\n  apply(induction l arbitrary:n)\n  by auto\n\nlemma \"ddec 0 (denc 0 l) = l\"\n  apply(auto simp:encdecgen)\n  done\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/02/hw02.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835411997897, "lm_q2_score": 0.8577681122619883, "lm_q1q2_score": 0.7166511399609048}}
{"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\ntext \\<open>Conflicting notation from \\<^theory>\\<open>HOL-Analysis.Infinite_Sum\\<close>\\<close>\nno_notation Infinite_Sum.abs_summable_on (infixr \"abs'_summable'_on\" 46)\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": "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/Skip_Lists/Pi_pmf.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8577681049901037, "lm_q2_score": 0.8354835391516132, "lm_q1q2_score": 0.7166511321285044}}
{"text": "(* Title:  Digraph_Component.thy\n   Author: Lars Noschinski, TU M\u00fcnchen\n*)\n\ntheory Digraph_Component\nimports\n  Digraph\n  Arc_Walk\n  Pair_Digraph\nbegin\n\nsection \\<open>Components of (Symmetric) Digraphs\\<close>\n\ndefinition compatible :: \"('a,'b) pre_digraph \\<Rightarrow> ('a,'b) pre_digraph \\<Rightarrow> bool\" where\n  \"compatible G H \\<equiv> tail G = tail H \\<and> head G = head H\"\n\n(* Require @{term \"wf_digraph G\"}? *)\ndefinition subgraph :: \"('a,'b) pre_digraph \\<Rightarrow> ('a,'b) pre_digraph \\<Rightarrow> bool\" where\n  \"subgraph H G \\<equiv> verts H \\<subseteq> verts G \\<and> arcs H \\<subseteq> arcs G \\<and> wf_digraph G \\<and> wf_digraph H \\<and> compatible G H\"\n\ndefinition induced_subgraph :: \"('a,'b) pre_digraph \\<Rightarrow> ('a,'b) pre_digraph \\<Rightarrow> bool\" where\n  \"induced_subgraph H G \\<equiv> subgraph H G \\<and> arcs H = {e \\<in> arcs G. tail G e \\<in> verts H \\<and> head G e \\<in> verts H}\"\n\ndefinition spanning :: \"('a,'b) pre_digraph \\<Rightarrow> ('a,'b) pre_digraph \\<Rightarrow> bool\" where\n  \"spanning H G \\<equiv> subgraph H G \\<and> verts G = verts H\"\n\ndefinition strongly_connected :: \"('a,'b) pre_digraph \\<Rightarrow> bool\" where\n  \"strongly_connected G \\<equiv> verts G \\<noteq> {} \\<and> (\\<forall>u \\<in> verts G. \\<forall>v \\<in> verts G. u \\<rightarrow>\\<^sup>*\\<^bsub>G\\<^esub> v)\"\n\n\ntext \\<open>\n  The following function computes underlying symmetric graph of a digraph\n  and removes parallel arcs.\n\\<close>\n\ndefinition mk_symmetric :: \"('a,'b) pre_digraph \\<Rightarrow> 'a pair_pre_digraph\" where\n  \"mk_symmetric G \\<equiv> \\<lparr> pverts = verts G, parcs = \\<Union>e\\<in>arcs G. {(tail G e, head G e), (head G e, tail G e)}\\<rparr>\"\n\ndefinition connected :: \"('a,'b) pre_digraph \\<Rightarrow> bool\" where\n  \"connected G \\<equiv> strongly_connected (mk_symmetric G)\"\n\ndefinition forest :: \"('a,'b) pre_digraph \\<Rightarrow> bool\" where\n  \"forest G \\<equiv> \\<not>(\\<exists>p. pre_digraph.cycle G p)\"\n\ndefinition tree :: \"('a,'b) pre_digraph \\<Rightarrow> bool\" where\n  \"tree G \\<equiv> connected G \\<and> forest G\"\n\ndefinition spanning_tree :: \"('a,'b) pre_digraph \\<Rightarrow> ('a,'b) pre_digraph \\<Rightarrow> bool\" where\n  \"spanning_tree H G \\<equiv> tree H \\<and> spanning H G\"\n\ndefinition (in pre_digraph)\n  max_subgraph :: \"(('a,'b) pre_digraph \\<Rightarrow> bool) \\<Rightarrow> ('a,'b) pre_digraph \\<Rightarrow>  bool\"\nwhere\n  \"max_subgraph P H \\<equiv> subgraph H G \\<and> P H \\<and> (\\<forall>H'. H' \\<noteq> H \\<and> subgraph H H' \\<longrightarrow> \\<not>(subgraph H' G \\<and> P H'))\"\n\ndefinition (in pre_digraph) sccs :: \"('a,'b) pre_digraph set\" where\n  \"sccs \\<equiv> {H. induced_subgraph H G \\<and> strongly_connected H \\<and> \\<not>(\\<exists>H'. induced_subgraph H' G\n      \\<and> strongly_connected H' \\<and> verts H \\<subset> verts H')}\"\n\ndefinition (in pre_digraph) sccs_verts :: \"'a set set\" where\n  \"sccs_verts = {S. S \\<noteq> {} \\<and> (\\<forall>u \\<in> S. \\<forall>v \\<in> S. u \\<rightarrow>\\<^sup>*\\<^bsub>G\\<^esub> v) \\<and> (\\<forall>u \\<in> S. \\<forall>v. v \\<notin> S \\<longrightarrow> \\<not>u \\<rightarrow>\\<^sup>*\\<^bsub>G\\<^esub> v \\<or> \\<not>v \\<rightarrow>\\<^sup>*\\<^bsub>G\\<^esub> u)}\"\n(*XXX:  \"sccs_verts = verts ` sccs\" *)\n\ndefinition (in pre_digraph) scc_of :: \"'a \\<Rightarrow> 'a set\" where\n  \"scc_of u \\<equiv> {v. u \\<rightarrow>\\<^sup>* v \\<and> v \\<rightarrow>\\<^sup>* u}\"\n\ndefinition union :: \"('a,'b) pre_digraph \\<Rightarrow> ('a,'b) pre_digraph \\<Rightarrow> ('a,'b) pre_digraph\" where\n  \"union G H \\<equiv> \\<lparr> verts = verts G \\<union> verts H, arcs = arcs G \\<union> arcs H, tail = tail G, head = head G\\<rparr>\"\n\ndefinition (in pre_digraph) Union :: \"('a,'b) pre_digraph set \\<Rightarrow> ('a,'b) pre_digraph\" where\n  \"Union gs = \\<lparr> verts = (\\<Union>G \\<in> gs. verts G), arcs = (\\<Union>G \\<in> gs. arcs G),\n    tail = tail G , head = head G  \\<rparr>\"\n\n\n\nsubsection \\<open>Compatible Graphs\\<close>\n\nlemma compatible_tail:\n  assumes \"compatible G H\" shows \"tail G = tail H\"\n  using assms by (simp add: fun_eq_iff compatible_def)\n\nlemma compatible_head:\n  assumes \"compatible G H\" shows \"head G = head H\"\n  using assms by (simp add: fun_eq_iff compatible_def)\n\nlemma compatible_cas:\n  assumes \"compatible G H\" shows \"pre_digraph.cas G = pre_digraph.cas H\"\nproof (unfold fun_eq_iff, intro allI)\n  fix u es v show \"pre_digraph.cas G u es v = pre_digraph.cas H u es v\"\n    using assms\n    by (induct es arbitrary: u)\n       (simp_all add: pre_digraph.cas.simps compatible_head compatible_tail)\nqed\n\nlemma compatible_awalk_verts:\n  assumes \"compatible G H\" shows \"pre_digraph.awalk_verts G = pre_digraph.awalk_verts H\"\nproof (unfold fun_eq_iff, intro allI)\n  fix u es show \"pre_digraph.awalk_verts G u es = pre_digraph.awalk_verts H u es\"\n    using assms\n    by (induct es arbitrary: u)\n       (simp_all add: pre_digraph.awalk_verts.simps compatible_head compatible_tail)\nqed\n\nlemma compatibleI_with_proj[intro]:\n  shows \"compatible (with_proj G) (with_proj H)\"\n  by (auto simp: compatible_def)\n\n\n\nsubsection \\<open>Basic lemmas\\<close>\n\nlemma (in sym_digraph) graph_symmetric:\n  shows \"(u,v) \\<in> arcs_ends G \\<Longrightarrow> (v,u) \\<in> arcs_ends G\"\n  using sym_arcs by (auto simp add: symmetric_def sym_def)\n\nlemma strongly_connectedI[intro]:\n  assumes \"verts G \\<noteq> {}\" \"\\<And>u v. u \\<in> verts G \\<Longrightarrow> v \\<in> verts G \\<Longrightarrow> u \\<rightarrow>\\<^sup>*\\<^bsub>G\\<^esub> v\"\n  shows \"strongly_connected G\"\nusing assms by (simp add: strongly_connected_def)\n\nlemma strongly_connectedE[elim]:\n  assumes \"strongly_connected G\"\n  assumes \"(\\<And>u v. u \\<in> verts G \\<and> v \\<in> verts G \\<Longrightarrow> u \\<rightarrow>\\<^sup>*\\<^bsub>G\\<^esub> v) \\<Longrightarrow> P\"\n  shows \"P\"\nusing assms by (auto simp add: strongly_connected_def)\n\nlemma subgraph_imp_subverts:\n  assumes \"subgraph H G\"\n  shows \"verts H \\<subseteq> verts G\"\nusing assms by (simp add: subgraph_def)\n\nlemma induced_imp_subgraph:\n  assumes \"induced_subgraph H G\"\n  shows \"subgraph H G\"\nusing assms by (simp add: induced_subgraph_def)\n\nlemma (in pre_digraph) in_sccs_imp_induced:\n  assumes \"c \\<in> sccs\"\n  shows \"induced_subgraph c G\"\nusing assms by (auto simp: sccs_def)\n\nlemma spanning_tree_imp_tree[dest]:\n  assumes \"spanning_tree H G\"\n  shows \"tree H\"\nusing assms by (simp add: spanning_tree_def)\n\nlemma tree_imp_connected[dest]:\n  assumes \"tree G\"\n  shows \"connected G\"\nusing assms by (simp add: tree_def)\n\nlemma spanning_treeI[intro]:\n  assumes \"spanning H G\"\n  assumes \"tree H\"\n  shows \"spanning_tree H G\"\nusing assms by (simp add: spanning_tree_def)\n\nlemma spanning_treeE[elim]:\n  assumes \"spanning_tree H G\"\n  assumes \"tree H \\<and> spanning H G \\<Longrightarrow> P\"\n  shows \"P\"\nusing assms by (simp add: spanning_tree_def)\n\nlemma spanningE[elim]:\n  assumes \"spanning H G\"\n  assumes \"subgraph H G \\<and> verts G = verts H \\<Longrightarrow> P\"\n  shows \"P\"\nusing assms by (simp add: spanning_def)\n\nlemma (in pre_digraph) in_sccsI[intro]:\n  assumes \"induced_subgraph c G\"\n  assumes \"strongly_connected c\"\n  assumes \"\\<not>(\\<exists>c'. induced_subgraph c' G \\<and> strongly_connected c' \\<and>\n    verts c \\<subset> verts c')\"\n  shows \"c \\<in> sccs\"\nusing assms by (auto simp add: sccs_def)\n\nlemma (in pre_digraph) in_sccsE[elim]:\n  assumes \"c \\<in> sccs\"\n  assumes \"induced_subgraph c G \\<Longrightarrow> strongly_connected c \\<Longrightarrow> \\<not> (\\<exists>d.\n    induced_subgraph d G \\<and> strongly_connected d \\<and> verts c \\<subset> verts d) \\<Longrightarrow> P\"\n  shows \"P\"\nusing assms by (simp add: sccs_def)\n\nlemma subgraphI:\n  assumes \"verts H \\<subseteq> verts G\"\n  assumes \"arcs H \\<subseteq> arcs G\"\n  assumes \"compatible G H\"\n  assumes \"wf_digraph H\"\n  assumes \"wf_digraph G\"\n  shows \"subgraph H G\"\nusing assms by (auto simp add: subgraph_def)\n\nlemma subgraphE[elim]:\n  assumes \"subgraph H G\"\n  obtains \"verts H \\<subseteq> verts G\" \"arcs H \\<subseteq> arcs G\" \"compatible G H\" \"wf_digraph H\" \"wf_digraph G\"\nusing assms by (simp add: subgraph_def)\n\nlemma induced_subgraphI[intro]:\n  assumes \"subgraph H G\"\n  assumes \"arcs H = {e \\<in> arcs G. tail G e \\<in> verts H \\<and> head G e \\<in> verts H}\"\n  shows \"induced_subgraph H G\"\nusing assms unfolding induced_subgraph_def by safe\n\nlemma induced_subgraphE[elim]:\n  assumes \"induced_subgraph H G\"\n  assumes \"\\<lbrakk>subgraph H G; arcs H = {e \\<in> arcs G. tail G e \\<in> verts H \\<and> head G e \\<in> verts H}\\<rbrakk> \\<Longrightarrow> P\"\n  shows \"P\"\nusing assms by (auto simp add: induced_subgraph_def)\n\nlemma pverts_mk_symmetric[simp]: \"pverts (mk_symmetric G) = verts G\"\n  and parcs_mk_symmetric:\n    \"parcs (mk_symmetric G) = (\\<Union>e\\<in>arcs G. {(tail G e, head G e), (head G e, tail G e)})\"\n  by (auto simp: mk_symmetric_def arcs_ends_conv image_UN)\n\nlemma arcs_ends_mono:\n  assumes \"subgraph H G\"\n  shows \"arcs_ends H \\<subseteq> arcs_ends G\"\n  using assms by (auto simp add: subgraph_def arcs_ends_conv compatible_tail compatible_head)\n\nlemma (in wf_digraph) subgraph_refl: \"subgraph G G\"\n  by (auto simp: subgraph_def compatible_def) unfold_locales\n\nlemma (in wf_digraph) induced_subgraph_refl: \"induced_subgraph G G\"\n  by (rule induced_subgraphI) (auto simp: subgraph_refl)\n\n\n\n\nsubsection \\<open>The underlying symmetric graph of a digraph\\<close>\n\nlemma (in wf_digraph) wellformed_mk_symmetric[intro]: \"pair_wf_digraph (mk_symmetric G)\"\n  by unfold_locales (auto simp: parcs_mk_symmetric)\n\nlemma (in fin_digraph) pair_fin_digraph_mk_symmetric[intro]: \"pair_fin_digraph (mk_symmetric G)\"\nproof -\n  have \"finite ((\\<lambda>(a,b). (b,a)) ` arcs_ends G)\" (is \"finite ?X\") by (auto simp: arcs_ends_conv)\n  also have \"?X = {(a, b). (b, a) \\<in> arcs_ends G}\" by auto\n  finally have X: \"finite ...\" .\n  then show ?thesis\n    by unfold_locales (auto simp: mk_symmetric_def arcs_ends_conv)\nqed\n\nlemma (in digraph) digraph_mk_symmetric[intro]: \"pair_digraph (mk_symmetric G)\"\nproof -\n  have \"finite ((\\<lambda>(a,b). (b,a)) ` arcs_ends G)\" (is \"finite ?X\") by (auto simp: arcs_ends_conv)\n  also have \"?X = {(a, b). (b, a) \\<in> arcs_ends G}\" by auto\n  finally have \"finite ...\" .\n  then show ?thesis\n    by unfold_locales (auto simp: mk_symmetric_def arc_to_ends_def dest: no_loops)\nqed\n\nlemma (in wf_digraph) reachable_mk_symmetricI:\n  assumes \"u \\<rightarrow>\\<^sup>* v\" shows \"u \\<rightarrow>\\<^sup>*\\<^bsub>mk_symmetric G\\<^esub> v\"\nproof -\n  have \"arcs_ends G \\<subseteq> parcs (mk_symmetric G)\"\n       \"(u, v) \\<in> rtrancl_on (pverts (mk_symmetric G)) (arcs_ends G)\"\n    using assms unfolding reachable_def by (auto simp: parcs_mk_symmetric)\n  then show ?thesis unfolding reachable_def by (auto intro: rtrancl_on_mono)\nqed\n\nlemma (in wf_digraph) adj_mk_symmetric_eq:\n  \"symmetric G \\<Longrightarrow> parcs (mk_symmetric G) = arcs_ends G\"\n  by (auto simp: parcs_mk_symmetric in_arcs_imp_in_arcs_ends arcs_ends_symmetric)\n\nlemma (in wf_digraph) reachable_mk_symmetric_eq:\n  assumes \"symmetric G\" shows \"u \\<rightarrow>\\<^sup>*\\<^bsub>mk_symmetric G\\<^esub> v \\<longleftrightarrow> u \\<rightarrow>\\<^sup>* v\" (is \"?L \\<longleftrightarrow> ?R\")\n  using adj_mk_symmetric_eq[OF assms] unfolding reachable_def by auto\n\nlemma (in wf_digraph) mk_symmetric_awalk_imp_awalk:\n  assumes sym: \"symmetric G\"\n  assumes walk: \"pre_digraph.awalk (mk_symmetric G) u p v\"\n  obtains q where \"awalk u q v\"\nproof -\n  interpret S: pair_wf_digraph \"mk_symmetric G\" ..\n  from walk have \"u \\<rightarrow>\\<^sup>*\\<^bsub>mk_symmetric G\\<^esub> v\"\n    by (simp only: S.reachable_awalk) rule\n  then have \"u \\<rightarrow>\\<^sup>* v\" by (simp only: reachable_mk_symmetric_eq[OF sym])\n  then show ?thesis by (auto simp: reachable_awalk intro: that)\nqed\n\nlemma symmetric_mk_symmetric:\n  \"symmetric (mk_symmetric G)\"\n  by (auto simp: symmetric_def parcs_mk_symmetric intro: symI)\n\n\n\nsubsection \\<open>Subgraphs and Induced Subgraphs\\<close>\n\nlemma subgraph_trans:\n  assumes \"subgraph G H\" \"subgraph H I\" shows \"subgraph G I\"\n  using assms by (auto simp: subgraph_def compatible_def)\n\ntext \\<open>\n  The @{term digraph} and @{term fin_digraph} properties are preserved under\n  the (inverse) subgraph relation\n\\<close>\nlemma (in fin_digraph) fin_digraph_subgraph:\n  assumes \"subgraph H G\" shows \"fin_digraph H\"\nproof (intro_locales)\n  from assms show \"wf_digraph H\" by auto\n\n  have HG: \"arcs H \\<subseteq> arcs G\" \"verts H \\<subseteq> verts G\"\n    using assms by auto\n  then have \"finite (verts H)\" \"finite (arcs H)\"\n    using finite_verts finite_arcs by (blast intro: finite_subset)+\n  then show \"fin_digraph_axioms H\"\n    by unfold_locales\nqed\n\nlemma (in digraph) digraph_subgraph:\n  assumes \"subgraph H G\" shows \"digraph H\"\nproof\n  fix e assume e: \"e \\<in> arcs H\"\n  with assms show \"tail H e \\<in> verts H\" \"head H e \\<in> verts H\"\n    by (auto simp: subgraph_def intro: wf_digraph.wellformed)\n  from e and assms have \"e \\<in> arcs H \\<inter> arcs G\" by auto\n  with assms show \"tail H e \\<noteq> head H e\"\n    using no_loops by (auto simp: subgraph_def compatible_def arc_to_ends_def)\nnext\n  have \"arcs H \\<subseteq> arcs G\" \"verts H \\<subseteq> verts G\" using assms by auto\n  then show \"finite (arcs H)\" \"finite (verts H)\"\n    using finite_verts finite_arcs by (blast intro: finite_subset)+\nnext\n  fix e1 e2 assume \"e1 \\<in> arcs H\" \"e2 \\<in> arcs H\"\n    and eq: \"arc_to_ends H e1 = arc_to_ends H e2\"\n  with assms have \"e1 \\<in> arcs H \\<inter> arcs G\" \"e2 \\<in> arcs H \\<inter> arcs G\"\n    by auto\n  with eq show \"e1 = e2\"\n    using no_multi_arcs assms\n    by (auto simp: subgraph_def compatible_def arc_to_ends_def)\nqed\n\nlemma (in pre_digraph) adj_mono:\n  assumes \"u \\<rightarrow>\\<^bsub>H\\<^esub> v\" \"subgraph H G\"\n  shows \"u \\<rightarrow> v\"\n  using assms by (blast dest: arcs_ends_mono)\n\nlemma (in pre_digraph) reachable_mono:\n  assumes walk: \"u \\<rightarrow>\\<^sup>*\\<^bsub>H\\<^esub> v\" and sub: \"subgraph H G\"\n  shows \"u \\<rightarrow>\\<^sup>* v\"\nproof -\n  have \"verts H \\<subseteq> verts G\" using sub by auto\n  with assms show ?thesis\n    unfolding reachable_def by (metis arcs_ends_mono rtrancl_on_mono)\nqed\n\n\ntext \\<open>\n  Arc walks and paths are preserved under the subgraph relation.\n\\<close>\nlemma (in wf_digraph) subgraph_awalk_imp_awalk:\n  assumes walk: \"pre_digraph.awalk H u p v\"\n  assumes sub: \"subgraph H G\"\n  shows \"awalk u p v\"\n  using assms by (auto simp: pre_digraph.awalk_def compatible_cas)\n\nlemma (in wf_digraph) subgraph_apath_imp_apath:\n  assumes path: \"pre_digraph.apath H u p v\"\n  assumes sub: \"subgraph H G\"\n  shows \"apath u p v\"\n  using assms unfolding pre_digraph.apath_def\n  by (auto intro: subgraph_awalk_imp_awalk simp: compatible_awalk_verts)\n\nlemma subgraph_mk_symmetric:\n  assumes \"subgraph H G\"\n  shows \"subgraph (mk_symmetric H) (mk_symmetric G)\"\nproof (rule subgraphI)\n  let ?wpms = \"\\<lambda>G. mk_symmetric G\"\n  from assms have \"compatible G H\" by auto\n  with assms\n  show \"verts (?wpms H)  \\<subseteq> verts (?wpms G)\"\n    and \"arcs (?wpms H) \\<subseteq> arcs (?wpms G)\"\n    by (auto simp: parcs_mk_symmetric compatible_head compatible_tail)\n  show \"compatible (?wpms G) (?wpms H)\" by rule\n  interpret H: pair_wf_digraph \"mk_symmetric H\"\n    using assms by (auto intro: wf_digraph.wellformed_mk_symmetric)\n  interpret G: pair_wf_digraph \"mk_symmetric G\"\n    using assms by (auto intro: wf_digraph.wellformed_mk_symmetric)\n  show \"wf_digraph (?wpms H)\"\n    by unfold_locales\n  show \"wf_digraph (?wpms G)\" by unfold_locales\nqed\n\nlemma (in fin_digraph) subgraph_in_degree:\n  assumes \"subgraph H G\"\n  shows \"in_degree H v \\<le> in_degree G v\"\nproof -\n  have \"finite (in_arcs G v)\" by auto\n  moreover\n  have \"in_arcs H v \\<subseteq> in_arcs G v\"\n    using assms by (auto simp: subgraph_def in_arcs_def compatible_head compatible_tail)\n  ultimately\n  show ?thesis unfolding in_degree_def by (rule card_mono)\nqed\n\nlemma (in wf_digraph) subgraph_cycle:\n  assumes \"subgraph H G\" \"pre_digraph.cycle H p \" shows \"cycle p\"\nproof -\n  from assms have \"compatible G H\" by auto\n  with assms show ?thesis\n    by (auto simp: pre_digraph.cycle_def compatible_awalk_verts intro: subgraph_awalk_imp_awalk)\nqed\n\nlemma (in wf_digraph) subgraph_del_vert: \"subgraph (del_vert u) G\"\n  by (auto simp: subgraph_def compatible_def del_vert_simps wf_digraph_del_vert) intro_locales\n\n\n\n\n\nsubsection \\<open>Induced subgraphs\\<close>\n\nlemma wf_digraphI_induced:\n  assumes \"induced_subgraph H G\"\n  shows \"wf_digraph H\"\nproof -\n  from assms have \"compatible G H\" by auto\n  with assms show ?thesis by unfold_locales (auto simp: compatible_tail compatible_head)\nqed\n\nlemma (in digraph) digraphI_induced:\n  assumes \"induced_subgraph H G\"\n  shows \"digraph H\"\nproof -\n  interpret W: wf_digraph H using assms by (rule wf_digraphI_induced)\n  from assms have \"compatible G H\" by auto\n  from assms have arcs: \"arcs H \\<subseteq> arcs G\" by blast\n  show ?thesis\n  proof\n    from assms have \"verts H \\<subseteq> verts G\" by blast\n    then show \"finite (verts H)\" using finite_verts by (rule finite_subset)\n  next\n    from arcs show \"finite (arcs H)\" using finite_arcs by (rule finite_subset)\n  next\n    fix e assume \"e \\<in> arcs H\"\n    with arcs \\<open>compatible G H\\<close> show \"tail H e \\<noteq> head H e\"\n      by (auto dest: no_loops simp: compatible_tail[symmetric] compatible_head[symmetric])\n  next\n    fix e1 e2 assume \"e1 \\<in> arcs H\" \"e2 \\<in> arcs H\" and ate: \"arc_to_ends H e1 = arc_to_ends H e2\"\n    with arcs \\<open>compatible G H\\<close> show \"e1 = e2\" using ate\n      by (auto intro: no_multi_arcs simp: compatible_tail[symmetric] compatible_head[symmetric] arc_to_ends_def)\n  qed\nqed\n\ntext \\<open>Computes the subgraph of @{term G} induced by @{term vs}\\<close>\ndefinition induce_subgraph :: \"('a,'b) pre_digraph \\<Rightarrow> 'a set \\<Rightarrow> ('a,'b) pre_digraph\" (infix \"\\<restriction>\" 67) where\n  \"G \\<restriction> vs = \\<lparr> verts = vs, arcs = {e \\<in> arcs G. tail G e \\<in> vs \\<and> head G e \\<in> vs},\n    tail = tail G, head = head G \\<rparr>\"\n\nlemma induce_subgraph_verts[simp]:\n \"verts (G \\<restriction> vs) = vs\"\nby (auto simp add: induce_subgraph_def)\n\nlemma induce_subgraph_arcs[simp]:\n \"arcs (G \\<restriction> vs) = {e \\<in> arcs G. tail G e \\<in> vs \\<and> head G e \\<in> vs}\"\nby (auto simp add: induce_subgraph_def)\n\nlemma induce_subgraph_tail[simp]:\n  \"tail (G \\<restriction> vs) = tail G\"\nby (auto simp: induce_subgraph_def)\n\nlemma induce_subgraph_head[simp]:\n  \"head (G \\<restriction> vs) = head G\"\nby (auto simp: induce_subgraph_def)\n\nlemma compatible_induce_subgraph: \"compatible (G \\<restriction> S) G\"\n  by (auto simp: compatible_def)\n\nlemma (in wf_digraph) induced_induce[intro]:\n  assumes \"vs \\<subseteq> verts G\"\n  shows \"induced_subgraph (G \\<restriction> vs) G\"\nusing assms\nby (intro subgraphI induced_subgraphI)\n   (auto simp: arc_to_ends_def induce_subgraph_def wf_digraph_def compatible_def)\n\nlemma (in wf_digraph) wellformed_induce_subgraph[intro]:\n  \"wf_digraph (G \\<restriction> vs)\"\n  by unfold_locales auto\n\nlemma induced_graph_imp_symmetric:\n  assumes \"symmetric G\"\n  assumes \"induced_subgraph H G\"\n  shows \"symmetric H\"\nproof (unfold symmetric_conv, safe)\n  from assms have \"compatible G H\" by auto\n\n  fix e1 assume \"e1 \\<in> arcs H\"\n  then obtain e2 where \"tail G e1 = head G e2\"  \"head G e1 = tail G e2\" \"e2 \\<in> arcs G\"\n    using assms by (auto simp add: symmetric_conv)\n  moreover\n  then have \"e2 \\<in> arcs H\"\n    using assms and \\<open>e1 \\<in> arcs H\\<close> by auto\n  ultimately\n  show \"\\<exists>e2\\<in>arcs H. tail H e1 = head H e2 \\<and> head H e1 = tail H e2\"\n    using assms \\<open>e1 \\<in> arcs H\\<close> \\<open>compatible G H\\<close>\n    by (auto simp: compatible_head compatible_tail)\nqed\n\nlemma (in sym_digraph) induced_graph_imp_graph:\n  assumes \"induced_subgraph H G\"\n  shows \"sym_digraph H\"\nproof (rule wf_digraph.sym_digraphI)\n  from assms show \"wf_digraph H\" by (rule wf_digraphI_induced)\nnext\n  show \"symmetric H\"\n    using assms sym_arcs by (auto intro: induced_graph_imp_symmetric)\nqed\n\nlemma (in wf_digraph) induce_reachable_preserves_paths:\n  assumes \"u \\<rightarrow>\\<^sup>*\\<^bsub>G\\<^esub> v\"\n  shows \"u \\<rightarrow>\\<^sup>*\\<^bsub>G \\<restriction> {w. u \\<rightarrow>\\<^sup>*\\<^bsub>G\\<^esub> w}\\<^esub> v\"\n  using assms\nproof induct\n  case base then show ?case by (auto simp: reachable_def)\nnext\n  case (step u w)\n  interpret iG: wf_digraph \"G \\<restriction> {w. u \\<rightarrow>\\<^sup>*\\<^bsub>G\\<^esub> w}\"\n    by (rule wellformed_induce_subgraph)\n  from \\<open>u \\<rightarrow> w\\<close> have \"u \\<rightarrow>\\<^bsub>G \\<restriction> {wa. u \\<rightarrow>\\<^sup>*\\<^bsub>G\\<^esub> wa}\\<^esub> w\"\n    by (auto simp: arcs_ends_conv reachable_def intro: wellformed rtrancl_on_into_rtrancl_on)\n  then have \"u \\<rightarrow>\\<^sup>*\\<^bsub>G \\<restriction> {wa. u \\<rightarrow>\\<^sup>*\\<^bsub>G\\<^esub> wa}\\<^esub> w\"\n    by (rule iG.reachable_adjI)\n  moreover\n  from step have \"{x. w \\<rightarrow>\\<^sup>* x} \\<subseteq> {x. u \\<rightarrow>\\<^sup>* x}\"\n    by (auto intro: adj_reachable_trans)\n  then have \"subgraph (G \\<restriction> {wa. w \\<rightarrow>\\<^sup>* wa}) (G \\<restriction> {wa. u \\<rightarrow>\\<^sup>* wa})\"\n    by (intro subgraphI) (auto simp: arcs_ends_conv compatible_def)\n  then have \"w \\<rightarrow>\\<^sup>*\\<^bsub>G \\<restriction> {wa. u \\<rightarrow>\\<^sup>* wa}\\<^esub> v\"\n    by (rule iG.reachable_mono[rotated]) fact\n  ultimately show ?case by (rule iG.reachable_trans)\nqed\n\nlemma induce_subgraph_ends[simp]:\n  \"arc_to_ends (G \\<restriction> S) = arc_to_ends G\"\n  by (auto simp: arc_to_ends_def)\n\nlemma dominates_induce_subgraphD:\n  assumes \"u \\<rightarrow>\\<^bsub>G \\<restriction> S\\<^esub> v\" shows \"u \\<rightarrow>\\<^bsub>G\\<^esub> v\"\n  using assms by (auto simp: arcs_ends_def intro: rev_image_eqI)\n\ncontext wf_digraph begin\n\n  lemma reachable_induce_subgraphD:\n    assumes \"u \\<rightarrow>\\<^sup>*\\<^bsub>G \\<restriction> S\\<^esub> v\" \"S \\<subseteq> verts G\" shows \"u \\<rightarrow>\\<^sup>*\\<^bsub>G\\<^esub> v\"\n  proof -\n    interpret GS: wf_digraph \"G \\<restriction> S\" by auto\n    show ?thesis\n      using assms by induct (auto dest: dominates_induce_subgraphD intro: adj_reachable_trans)\n  qed\n\n  lemma dominates_induce_ss:\n    assumes \"u \\<rightarrow>\\<^bsub>G \\<restriction> S\\<^esub> v\" \"S \\<subseteq> T\" shows \"u \\<rightarrow>\\<^bsub>G \\<restriction> T\\<^esub> v\"\n    using assms by (auto simp: arcs_ends_def)\n\n  lemma reachable_induce_ss:\n    assumes \"u \\<rightarrow>\\<^sup>*\\<^bsub>G \\<restriction> S\\<^esub> v\" \"S \\<subseteq> T\" shows \"u \\<rightarrow>\\<^sup>*\\<^bsub>G \\<restriction> T\\<^esub> v\"\n    using assms unfolding reachable_def\n    by induct (auto intro: dominates_induce_ss converse_rtrancl_on_into_rtrancl_on)\n\n  lemma awalk_verts_induce:\n    \"pre_digraph.awalk_verts (G \\<restriction> S) = awalk_verts\"\n  proof (intro ext)\n    fix u p show \"pre_digraph.awalk_verts (G \\<restriction> S) u p = awalk_verts u p\"\n      by (induct p arbitrary: u) (auto simp: pre_digraph.awalk_verts.simps)\n  qed\n\n  lemma (in -) cas_subset:\n    assumes \"pre_digraph.cas G u p v\" \"subgraph G H\"\n    shows \"pre_digraph.cas H u p v\"\n    using assms\n    by (induct p arbitrary: u) (auto simp: pre_digraph.cas.simps subgraph_def compatible_def)\n\n  lemma cas_induce:\n    assumes \"cas u p v\" \"set (awalk_verts u p) \\<subseteq> S\"\n    shows \"pre_digraph.cas (G \\<restriction> S) u p v\"\n    using assms\n  proof (induct p arbitrary: u S)\n    case Nil then show ?case by (auto simp: pre_digraph.cas.simps)\n  next\n    case (Cons a as)\n    have \"pre_digraph.cas (G \\<restriction> set (awalk_verts (head G a) as)) (head G a) as v\"\n      using Cons by auto\n    then have \"pre_digraph.cas (G \\<restriction> S) (head G a) as v\"\n      using \\<open>_ \\<subseteq> S\\<close> by (rule_tac cas_subset) (auto simp: subgraph_def compatible_def)\n    then show ?case using Cons by (auto simp: pre_digraph.cas.simps)\n  qed\n\n  lemma awalk_induce:\n    assumes \"awalk u p v\" \"set (awalk_verts u p) \\<subseteq> S\"\n    shows \"pre_digraph.awalk (G \\<restriction> S) u p v\"\n  proof -\n    interpret GS: wf_digraph \"G \\<restriction> S\" by auto\n    show ?thesis\n      using assms by (auto simp: pre_digraph.awalk_def cas_induce GS.cas_induce set_awalk_verts)\n  qed\n\n  lemma subgraph_induce_subgraphI:\n    assumes \"V \\<subseteq> verts G\" shows \"subgraph (G \\<restriction> V) G\"\n    by (metis assms induced_imp_subgraph induced_induce)\n\nend\n\nlemma induced_subgraphI':\n  assumes subg:\"subgraph H G\"\n  assumes max: \"\\<And>H'. subgraph H' G \\<Longrightarrow> (verts H' \\<noteq> verts H \\<or> arcs H' \\<subseteq> arcs H)\"\n  shows \"induced_subgraph H G\"\nproof -\n  interpret H: wf_digraph H using \\<open>subgraph H G\\<close> ..\n  define H' where \"H' = G \\<restriction> verts H\"\n  then have H'_props: \"subgraph H' G\" \"verts H' = verts H\"\n    using subg by (auto intro: wf_digraph.subgraph_induce_subgraphI)\n  moreover\n  have \"arcs H' = arcs H\"\n  proof\n    show \"arcs H' \\<subseteq> arcs H\" using max H'_props by auto\n    show \"arcs H \\<subseteq> arcs H'\" using subg by (auto simp: H'_def compatible_def)\n  qed\n  then show \"induced_subgraph H G\" by (auto simp: induced_subgraph_def H'_def subg) \nqed\n\nlemma (in pre_digraph) induced_subgraph_altdef:\n  \"induced_subgraph H G \\<longleftrightarrow> subgraph H G \\<and> (\\<forall>H'. subgraph H' G \\<longrightarrow> (verts H' \\<noteq> verts H \\<or> arcs H' \\<subseteq> arcs H))\" (is \"?L \\<longleftrightarrow> ?R\")\nproof -\n  { fix H' :: \"('a,'b) pre_digraph\"\n    assume A: \"verts H' = verts H\" \"subgraph H' G\"\n    interpret H': wf_digraph H' using \\<open>subgraph H' G\\<close> ..\n    from \\<open>subgraph H' G\\<close>\n    have comp: \"tail G = tail H'\" \"head G = head H'\" by (auto simp: compatible_def)\n    then have \"\\<And>a. a \\<in> arcs H' \\<Longrightarrow> tail G a \\<in> verts H\" \"\\<And>a. a \\<in> arcs H' \\<Longrightarrow> tail G a \\<in> verts H\"\n      by (auto dest: H'.wellformed simp: A)\n    then have \"arcs H' \\<subseteq> {e \\<in> arcs G. tail G e \\<in> verts H \\<and> head G e \\<in> verts H}\"\n      using \\<open>subgraph H' G\\<close> by (auto simp: subgraph_def comp A(1)[symmetric])\n  }\n  then show ?thesis using induced_subgraphI'[of H G] by (auto simp: induced_subgraph_def)\nqed\n\n\n\nsubsection \\<open>Unions of Graphs\\<close>\n\nlemma\n  verts_union[simp]: \"verts (union G H) = verts G \\<union> verts H\" and\n  arcs_union[simp]: \"arcs (union G H) = arcs G \\<union> arcs H\" and\n  tail_union[simp]: \"tail (union G H) = tail G\" and\n  head_union[simp]: \"head (union G H) = head G\"\n  by (auto simp: union_def)\n\nlemma wellformed_union:\n  assumes \"wf_digraph G\" \"wf_digraph H\" \"compatible G H\"\n  shows \"wf_digraph (union G H)\"\n  using assms\n  by unfold_locales\n     (auto simp: union_def compatible_tail compatible_head dest: wf_digraph.wellformed)\n\nlemma subgraph_union_iff:\n  assumes \"wf_digraph H1\" \"wf_digraph H2\" \"compatible H1 H2\"\n  shows \"subgraph (union H1 H2) G \\<longleftrightarrow> subgraph H1 G \\<and> subgraph H2 G\"\n  using assms by (fastforce simp: compatible_def intro!: subgraphI wellformed_union)\n\nlemma subgraph_union[intro]:\n  assumes \"subgraph H1 G\" \"compatible H1 G\"\n  assumes \"subgraph H2 G\" \"compatible H2 G\"\n  shows \"subgraph (union H1 H2) G\"\nproof -\n  from assms have \"wf_digraph (union H1 H2)\"\n    by (auto intro: wellformed_union simp: compatible_def)\n  with assms show ?thesis\n    by (auto simp add: subgraph_def union_def arc_to_ends_def compatible_def)\nqed\n\nlemma union_fin_digraph:\n  assumes \"fin_digraph G\" \"fin_digraph H\" \"compatible G H\"\n  shows \"fin_digraph (union G H)\"\nproof intro_locales\n  interpret G: fin_digraph G by (rule assms)\n  interpret H: fin_digraph H by (rule assms)\n  show \"wf_digraph (union G H)\" using assms\n    by (intro wellformed_union) intro_locales\n  show \"fin_digraph_axioms (union G H)\"\n    using assms by unfold_locales (auto simp: union_def)\nqed\n\nlemma subgraphs_of_union:\n  assumes \"wf_digraph G\" \"wf_digraph G'\" \"compatible G G'\"\n  shows \"subgraph G (union G G')\"\n    and \"subgraph G' (union G G')\"\n  using assms by (auto intro!: subgraphI wellformed_union simp: compatible_def)\n\n\nsubsection \\<open>Maximal Subgraphs\\<close>\n\nlemma (in pre_digraph) max_subgraph_mp:\n  assumes \"max_subgraph Q x\" \"\\<And>x. P x \\<Longrightarrow> Q x\" \"P x\" shows \"max_subgraph P x\"\n  using assms by (auto simp: max_subgraph_def)\n\nlemma (in pre_digraph) max_subgraph_prop: \"max_subgraph P x \\<Longrightarrow> P x\"\n  by (simp add: max_subgraph_def)\n\nlemma (in pre_digraph) max_subgraph_subg_eq:\n  assumes \"max_subgraph P H1\" \"max_subgraph P H2\" \"subgraph H1 H2\"\n  shows \"H1 = H2\"\n  using assms by (auto simp: max_subgraph_def)\n\nlemma subgraph_induce_subgraphI2:\n  assumes \"subgraph H G\" shows \"subgraph H (G \\<restriction> verts H)\"\n  using assms by (auto simp: subgraph_def compatible_def wf_digraph.wellformed wf_digraph.wellformed_induce_subgraph)\n\ndefinition arc_mono :: \"(('a,'b) pre_digraph \\<Rightarrow> bool) \\<Rightarrow> bool\" where\n  \"arc_mono P \\<equiv> (\\<forall>H1 H2. P H1 \\<and> subgraph H1 H2 \\<and> verts H1 = verts H2 \\<longrightarrow> P H2)\"\n\nlemma (in pre_digraph) induced_subgraphI_arc_mono:\n  assumes \"max_subgraph P H\"\n  assumes \"arc_mono P\"\n  shows \"induced_subgraph H G\"\nproof -\n  interpret wf_digraph G using assms by (auto simp: max_subgraph_def)\n  have \"subgraph H (G \\<restriction> verts H)\" \"subgraph (G \\<restriction> verts H) G\" \"verts H = verts (G \\<restriction> verts H)\" \"P H\"\n    using assms by (auto simp: max_subgraph_def subgraph_induce_subgraphI2 subgraph_induce_subgraphI)\n  moreover\n  then have \"P (G \\<restriction> verts  H)\"\n    using assms by (auto simp: arc_mono_def)\n  ultimately\n  have \"max_subgraph P (G \\<restriction> verts H)\"\n    using assms by (auto simp: max_subgraph_def) metis\n  then have \"H = G \\<restriction> verts H\"\n    using \\<open>max_subgraph P H\\<close> \\<open>subgraph H _\\<close>\n    by (intro max_subgraph_subg_eq)\n  show ?thesis using assms by (subst \\<open>H = _\\<close>) (auto simp: max_subgraph_def)\nqed\n\nlemma (in pre_digraph) induced_subgraph_altdef2:\n  \"induced_subgraph H G \\<longleftrightarrow> max_subgraph (\\<lambda>H'. verts H' = verts H) H\" (is \"?L \\<longleftrightarrow> ?R\")\nproof\n  assume ?L\n  moreover\n  { fix H' assume \"induced_subgraph H G\" \"subgraph H H'\" \"H \\<noteq> H'\"\n    then have \"\\<not>(subgraph H' G \\<and> verts H' = verts H)\"\n      by (auto simp: induced_subgraph_altdef compatible_def elim!: allE[where x=H'])\n  }\n  ultimately show \"max_subgraph (\\<lambda>H'. verts H' = verts H) H\" by (auto simp: max_subgraph_def)\nnext\n  assume ?R\n  moreover have \"arc_mono (\\<lambda>H'. verts H' = verts H)\" by (auto simp: arc_mono_def)\n  ultimately show ?L by (rule induced_subgraphI_arc_mono)\nqed\n\n(*XXX*)\nlemma (in pre_digraph) max_subgraphI:\n  assumes \"P x\" \"subgraph x G\" \"\\<And>y. \\<lbrakk>x \\<noteq> y; subgraph x y; subgraph y G\\<rbrakk> \\<Longrightarrow> \\<not>P y\"\n  shows \"max_subgraph P x\"\n  using assms by (auto simp: max_subgraph_def)\n\nlemma (in pre_digraph) subgraphI_max_subgraph: \"max_subgraph P x \\<Longrightarrow> subgraph x G\"\n  by (simp add: max_subgraph_def)\n\n\nsubsection \\<open>Connected and Strongly Connected Graphs\\<close>\n\ncontext wf_digraph begin\n\n  lemma in_sccs_verts_conv_reachable:\n    \"S \\<in> sccs_verts \\<longleftrightarrow> S \\<noteq> {} \\<and> (\\<forall>u \\<in> S. \\<forall>v \\<in> S. u \\<rightarrow>\\<^sup>*\\<^bsub>G\\<^esub> v) \\<and> (\\<forall>u \\<in> S. \\<forall>v. v \\<notin> S \\<longrightarrow> \\<not>u \\<rightarrow>\\<^sup>*\\<^bsub>G\\<^esub> v \\<or> \\<not>v \\<rightarrow>\\<^sup>*\\<^bsub>G\\<^esub> u)\"\n    by (simp add: sccs_verts_def)\n\n  lemma sccs_verts_disjoint:\n    assumes \"S \\<in> sccs_verts\" \"T \\<in> sccs_verts\" \"S \\<noteq> T\" shows \"S \\<inter> T = {}\"\n    using assms unfolding in_sccs_verts_conv_reachable by safe meson+\n\n  lemma strongly_connected_spanning_imp_strongly_connected:\n    assumes \"spanning H G\"\n    assumes \"strongly_connected H\"\n    shows \"strongly_connected G\"\n  proof (unfold strongly_connected_def, intro ballI conjI)\n    from assms show \"verts G \\<noteq> {}\" unfolding strongly_connected_def spanning_def by auto\n  next\n    fix u v assume \"u \\<in> verts G\" and \"v \\<in> verts G\"\n    then have \"u \\<rightarrow>\\<^sup>*\\<^bsub>H\\<^esub> v\" \"subgraph H G\"\n      using assms by (auto simp add: strongly_connected_def)\n    then show \"u \\<rightarrow>\\<^sup>* v\" by (rule reachable_mono)\n  qed\n\n  lemma strongly_connected_imp_induce_subgraph_strongly_connected:\n    assumes subg: \"subgraph H G\"\n    assumes sc: \"strongly_connected H\"\n    shows \"strongly_connected (G \\<restriction> (verts H))\"\n  proof -\n    let ?is_H = \"G \\<restriction> (verts H)\"\n\n    interpret H: wf_digraph H\n      using subg by (rule subgraphE)\n    interpret GrH: wf_digraph \"?is_H\"\n      by (rule wellformed_induce_subgraph)\n\n    have \"verts H \\<subseteq> verts G\" using assms by auto\n\n    have \"subgraph H (G \\<restriction> verts H)\"\n      using subg by (intro subgraphI) (auto simp: compatible_def)\n    then show ?thesis\n      using induced_induce[OF \\<open>verts H \\<subseteq> verts G\\<close>]\n        and sc GrH.strongly_connected_spanning_imp_strongly_connected\n      unfolding spanning_def by auto\n  qed\n\n  lemma in_sccs_vertsI_sccs:\n    assumes \"S \\<in> verts ` sccs\" shows \"S \\<in> sccs_verts\"\n    unfolding sccs_verts_def\n  proof (intro CollectI conjI allI ballI impI)\n    show \"S \\<noteq> {}\" using assms by (auto simp: sccs_verts_def sccs_def strongly_connected_def)\n\n    from assms have sc: \"strongly_connected (G \\<restriction> S)\" \"S \\<subseteq> verts G\"\n      apply (auto simp: sccs_verts_def sccs_def)\n      by (metis induced_imp_subgraph subgraphE wf_digraph.strongly_connected_imp_induce_subgraph_strongly_connected)\n\n    {\n      fix u v assume A: \"u \\<in> S\" \"v \\<in> S\"\n      with sc have \"u \\<rightarrow>\\<^sup>*\\<^bsub>G \\<restriction> S\\<^esub> v\" by auto\n      then show \"u \\<rightarrow>\\<^sup>*\\<^bsub>G\\<^esub> v\" using \\<open>S \\<subseteq> verts G\\<close> by (rule reachable_induce_subgraphD)\n    next\n      fix u v assume A: \"u \\<in> S\" \"v \\<notin> S\"\n      { assume B: \"u \\<rightarrow>\\<^sup>*\\<^bsub>G\\<^esub> v\" \"v \\<rightarrow>\\<^sup>*\\<^bsub>G\\<^esub> u\"\n        from B obtain p_uv where p_uv: \"awalk u p_uv v\" by (metis reachable_awalk)\n        from B obtain p_vu where p_vu: \"awalk v p_vu u\" by (metis reachable_awalk)\n        define T where \"T = S \\<union> set (awalk_verts u p_uv) \\<union> set (awalk_verts v p_vu)\"\n        have \"S \\<subseteq> T\" by (auto simp: T_def)\n        have \"v \\<in> T\" using p_vu by (auto simp: T_def set_awalk_verts)\n        then have \"T \\<noteq> S\" using \\<open>v \\<notin> S\\<close> by auto\n\n        interpret T: wf_digraph \"G \\<restriction> T\" by auto\n\n        from p_uv have T_p_uv: \"T.awalk u p_uv v\"\n          by (rule awalk_induce) (auto simp: T_def)\n        from p_vu have T_p_vu: \"T.awalk v p_vu u\"\n          by (rule awalk_induce) (auto simp: T_def)\n\n        have uv_reach: \"u \\<rightarrow>\\<^sup>*\\<^bsub>G \\<restriction> T\\<^esub> v\" \"v \\<rightarrow>\\<^sup>*\\<^bsub>G \\<restriction> T\\<^esub> u\"\n          using T_p_uv T_p_vu A by (metis T.reachable_awalk)+\n\n        { fix x y assume \"x \\<in> S\" \"y \\<in> S\"\n          then have \"x \\<rightarrow>\\<^sup>*\\<^bsub>G \\<restriction> S\\<^esub> y\" \"y \\<rightarrow>\\<^sup>*\\<^bsub>G \\<restriction> S\\<^esub> x\"\n            using sc by auto\n          then have \"x \\<rightarrow>\\<^sup>*\\<^bsub>G \\<restriction> T\\<^esub> y\" \"y \\<rightarrow>\\<^sup>*\\<^bsub>G \\<restriction> T\\<^esub> x\"\n            using \\<open>S \\<subseteq> T\\<close> by (auto intro: reachable_induce_ss)\n        } note A1 = this\n\n        { fix x assume \"x \\<in> T\"\n          moreover\n          { assume \"x \\<in> S\" then have \"x \\<rightarrow>\\<^sup>*\\<^bsub>G \\<restriction> T\\<^esub> v\"\n              using uv_reach A1 A by (auto intro: T.reachable_trans[rotated])\n          } moreover\n          { assume \"x \\<in> set (awalk_verts u p_uv)\" then have \"x \\<rightarrow>\\<^sup>*\\<^bsub>G \\<restriction> T\\<^esub> v\"\n              using T_p_uv by (auto simp: awalk_verts_induce intro: T.awalk_verts_reachable_to)\n          } moreover\n          { assume \"x \\<in> set (awalk_verts v p_vu)\" then have \"x \\<rightarrow>\\<^sup>*\\<^bsub>G \\<restriction> T\\<^esub> v\"\n              using T_p_vu by (rule_tac T.reachable_trans)\n                (auto simp: uv_reach awalk_verts_induce dest: T.awalk_verts_reachable_to)\n          } ultimately\n          have \"x \\<rightarrow>\\<^sup>*\\<^bsub>G \\<restriction> T\\<^esub> v\" by (auto simp: T_def)\n        } note xv_reach = this\n\n        { fix x assume \"x \\<in> T\"\n          moreover\n          { assume \"x \\<in> S\" then have \"v \\<rightarrow>\\<^sup>*\\<^bsub>G \\<restriction> T\\<^esub> x\"\n              using uv_reach A1 A by (auto intro: T.reachable_trans)\n          } moreover\n          { assume \"x \\<in> set (awalk_verts v p_vu)\" then have \"v \\<rightarrow>\\<^sup>*\\<^bsub>G \\<restriction> T\\<^esub> x\"\n              using T_p_vu by (auto simp: awalk_verts_induce intro: T.awalk_verts_reachable_from)\n          } moreover\n          { assume \"x \\<in> set (awalk_verts u p_uv)\" then have \"v \\<rightarrow>\\<^sup>*\\<^bsub>G \\<restriction> T\\<^esub> x\"\n              using T_p_uv by (rule_tac T.reachable_trans[rotated])\n                (auto intro: T.awalk_verts_reachable_from uv_reach simp: awalk_verts_induce)\n          } ultimately\n          have \"v \\<rightarrow>\\<^sup>*\\<^bsub>G \\<restriction> T\\<^esub> x\" by (auto simp: T_def)\n        } note vx_reach = this\n\n        { fix x y assume \"x \\<in> T\" \"y \\<in> T\" then have \"x \\<rightarrow>\\<^sup>*\\<^bsub>G \\<restriction> T\\<^esub> y\"\n            using xv_reach vx_reach by (blast intro: T.reachable_trans)\n        }\n        then have \"strongly_connected (G \\<restriction> T)\"\n          using \\<open>S \\<noteq> {}\\<close> \\<open>S \\<subseteq> T\\<close> by auto\n        moreover have \"induced_subgraph (G \\<restriction> T) G\"\n          using \\<open>S \\<subseteq> verts G\\<close>\n          by (auto simp: T_def intro: awalk_verts_reachable_from p_uv p_vu reachable_in_verts(2))\n        ultimately\n        have \"\\<exists>T. induced_subgraph (G \\<restriction> T) G \\<and> strongly_connected (G \\<restriction> T) \\<and> verts (G \\<restriction> S) \\<subset> verts (G \\<restriction> T)\"\n          using \\<open>S \\<subseteq> T\\<close> \\<open>T \\<noteq> S\\<close> by auto\n        then have \"G \\<restriction> S \\<notin> sccs\" unfolding sccs_def by blast\n        then have \"S \\<notin> verts ` sccs\"\n          by (metis (erased, hide_lams) \\<open>S \\<subseteq> T\\<close> \\<open>T \\<noteq> S\\<close> \\<open>induced_subgraph (G \\<restriction> T) G\\<close> \\<open>strongly_connected (G \\<restriction> T)\\<close>\n            dual_order.order_iff_strict image_iff in_sccsE induce_subgraph_verts)\n        then have False using assms by metis\n      }\n      then show \"\\<not>u \\<rightarrow>\\<^sup>*\\<^bsub>G\\<^esub> v \\<or> \\<not>v \\<rightarrow>\\<^sup>*\\<^bsub>G\\<^esub> u\" by metis\n    }\n  qed\n\nend\n\nlemma arc_mono_strongly_connected[intro,simp]: \"arc_mono strongly_connected\"\n  by (auto simp: arc_mono_def) (metis spanning_def subgraphE wf_digraph.strongly_connected_spanning_imp_strongly_connected)\n\nlemma (in pre_digraph) sccs_altdef2:\n  \"sccs = {H. max_subgraph strongly_connected H}\" (is \"?L = ?R\")\nproof -\n  { fix H H' :: \"('a, 'b) pre_digraph\" \n    assume a1: \"strongly_connected H'\"\n    assume a2: \"induced_subgraph H' G\"\n    assume a3: \"max_subgraph strongly_connected H\"\n    assume a4: \"verts H \\<subseteq> verts H'\"\n    have sg: \"subgraph H G\" and ends_G: \"tail G = tail H \" \"head G = head H\"\n      using a3 by (auto simp: max_subgraph_def compatible_def)\n    then interpret H: wf_digraph H by blast\n    have \"arcs H \\<subseteq> arcs H'\" using a2 a4 sg by (fastforce simp: ends_G)\n    then have \"H = H'\"\n      using a1 a2 a3 a4\n      by (metis (no_types) compatible_def induced_imp_subgraph max_subgraph_def subgraph_def)\n  } note X = this\n\n  { fix H\n    assume a1: \"induced_subgraph H G\"\n    assume a2: \"strongly_connected H\"\n    assume a3: \"\\<forall>H'. strongly_connected H' \\<longrightarrow> induced_subgraph H' G \\<longrightarrow> \\<not> verts H \\<subset> verts H'\"\n    interpret G: wf_digraph G using a1 by auto\n    { fix y assume \"H \\<noteq> y\" and subg: \"subgraph H y\" \"subgraph y G\"\n      then have \"verts H \\<subset> verts y\"\n        using a1 by (auto simp: induced_subgraph_altdef2 max_subgraph_def)\n      then have \"\\<not>strongly_connected y\"\n        using subg a1 a2 a3[THEN spec, of \"G \\<restriction> verts y\"]\n        by (auto simp: G.induced_induce G.strongly_connected_imp_induce_subgraph_strongly_connected)\n    }\n    then have \"max_subgraph strongly_connected H\"\n      using a1 a2 by (auto intro: max_subgraphI)\n  } note Y = this\n\n  show ?thesis unfolding sccs_def\n    by (auto dest: max_subgraph_prop X intro: induced_subgraphI_arc_mono Y)\nqed\n\nlocale max_reachable_set = wf_digraph +\n  fixes S assumes S_in_sv: \"S \\<in> sccs_verts\"\nbegin\n\n  lemma reach_in: \"\\<And>u v. \\<lbrakk>u \\<in> S; v \\<in> S\\<rbrakk> \\<Longrightarrow> u \\<rightarrow>\\<^sup>*\\<^bsub>G\\<^esub> v\"\n    and not_reach_out: \"\\<And>u v. \\<lbrakk>u \\<in> S; v \\<notin> S\\<rbrakk> \\<Longrightarrow> \\<not>u \\<rightarrow>\\<^sup>*\\<^bsub>G\\<^esub> v \\<or> \\<not>v \\<rightarrow>\\<^sup>*\\<^bsub>G\\<^esub> u\"\n    and not_empty: \"S \\<noteq> {}\"\n    using S_in_sv by (auto simp: sccs_verts_def)\n\n  lemma reachable_induced:\n    assumes conn: \"u \\<in> S\" \"v \\<in> S\" \"u \\<rightarrow>\\<^sup>*\\<^bsub>G\\<^esub> v\"\n    shows \"u \\<rightarrow>\\<^sup>*\\<^bsub>G \\<restriction> S\\<^esub> v\"\n  proof -\n    let ?H = \"G \\<restriction> S\"\n    have \"S \\<subseteq> verts G\" using reach_in by (auto dest: reachable_in_verts)\n    then have \"induced_subgraph ?H G\"\n        by (rule induced_induce)\n    then interpret H: wf_digraph ?H by (rule wf_digraphI_induced)\n\n    from conn obtain p where p: \"awalk u p v\" by (metis reachable_awalk)\n    show ?thesis\n    proof (cases \"set p \\<subseteq> arcs (G \\<restriction> S)\")\n      case True\n      with p conn have \"H.awalk u p v\"\n        by (auto simp: pre_digraph.awalk_def compatible_cas[OF compatible_induce_subgraph])\n      then show ?thesis by (metis H.reachable_awalk)\n    next\n      case False\n      then obtain a where \"a \\<in> set p\" \"a \\<notin> arcs (G \\<restriction> S)\" by auto\n      moreover\n      then have \"tail G a \\<notin> S \\<or> head G a \\<notin> S\" using p by auto\n      ultimately\n      obtain w where \"w \\<in> set (awalk_verts u p)\" \"w \\<notin> S\" using p by (auto simp: set_awalk_verts)\n      then have \"u \\<rightarrow>\\<^sup>*\\<^bsub>G\\<^esub> w\" \"w \\<rightarrow>\\<^sup>*\\<^bsub>G\\<^esub> v\"\n        using p by (auto intro: awalk_verts_reachable_from awalk_verts_reachable_to)\n      moreover have \"v \\<rightarrow>\\<^sup>*\\<^bsub>G\\<^esub> u\" using conn reach_in by auto\n      ultimately have \"u \\<rightarrow>\\<^sup>*\\<^bsub>G\\<^esub> w\" \"w \\<rightarrow>\\<^sup>*\\<^bsub>G\\<^esub> u\" by (auto intro: reachable_trans)\n      with \\<open>w \\<notin> S\\<close> conn not_reach_out have False by blast\n      then show ?thesis ..\n    qed\n  qed\n\n  lemma strongly_connected:\n    shows \"strongly_connected (G \\<restriction> S)\"\n    using not_empty by (intro strongly_connectedI) (auto intro: reachable_induced reach_in)\n\n  lemma induced_in_sccs: \"G \\<restriction> S \\<in> sccs\"\n  proof -\n    let ?H = \"G \\<restriction> S\"\n    have \"S \\<subseteq> verts G\" using reach_in by (auto dest: reachable_in_verts)\n    then have \"induced_subgraph ?H G\"\n        by (rule induced_induce)\n    then interpret H: wf_digraph ?H by (rule wf_digraphI_induced)\n\n    { fix T assume \"S \\<subset> T\" \"T \\<subseteq> verts G\" \"strongly_connected (G \\<restriction> T)\"\n      from \\<open>S \\<subset> T\\<close> obtain v where \"v \\<in> T\" \"v \\<notin> S\" by auto\n      from not_empty obtain u where \"u \\<in> S\" by auto\n      then have \"u \\<in> T\" using \\<open>S \\<subset> T\\<close> by auto\n\n      from \\<open>u \\<in> S\\<close> \\<open>v \\<notin> S\\<close> have \"\\<not>u \\<rightarrow>\\<^sup>*\\<^bsub>G\\<^esub> v \\<or> \\<not>v \\<rightarrow>\\<^sup>*\\<^bsub>G\\<^esub> u\" by (rule not_reach_out)\n      moreover\n      from \\<open>strongly_connected _\\<close> have \"u \\<rightarrow>\\<^sup>*\\<^bsub>G \\<restriction> T\\<^esub> v\" \"v \\<rightarrow>\\<^sup>*\\<^bsub>G \\<restriction> T\\<^esub> u\"\n        using \\<open>v \\<in> T\\<close> \\<open>u \\<in> T\\<close> by (auto simp: strongly_connected_def)\n      then have \"u \\<rightarrow>\\<^sup>*\\<^bsub>G\\<^esub> v\" \"v \\<rightarrow>\\<^sup>*\\<^bsub>G\\<^esub> u\"\n        using \\<open>T \\<subseteq> verts G\\<close> by (auto dest: reachable_induce_subgraphD)\n      ultimately have False by blast\n    } note psuper_not_sc = this\n\n    have \"\\<not> (\\<exists>c'. induced_subgraph c' G \\<and> strongly_connected c' \\<and> verts (G \\<restriction> S) \\<subset> verts c')\"\n      by (metis induce_subgraph_verts induced_imp_subgraph psuper_not_sc subgraphE\n        strongly_connected_imp_induce_subgraph_strongly_connected)\n    with \\<open>S \\<subseteq> _\\<close> not_empty show \"?H \\<in> sccs\" by (intro in_sccsI induced_induce strongly_connected)\n  qed\nend\n\ncontext wf_digraph begin\n\n  lemma in_verts_sccsD_sccs:\n    assumes \"S \\<in> sccs_verts\"\n    shows \"G \\<restriction> S \\<in> sccs\"\n  proof -\n    from assms interpret max_reachable_set by unfold_locales\n    show ?thesis by (auto simp: sccs_verts_def intro: induced_in_sccs)\n  qed\n\n  lemma sccs_verts_conv: \"sccs_verts = verts ` sccs\"\n    by (auto intro: in_sccs_vertsI_sccs rev_image_eqI dest: in_verts_sccsD_sccs)\n\n  lemma induce_eq_iff_induced:\n    assumes \"induced_subgraph H G\" shows \"G \\<restriction> verts H = H\"\n    using assms by (auto simp: induced_subgraph_def induce_subgraph_def compatible_def)\n\n  lemma sccs_conv_sccs_verts: \"sccs = induce_subgraph G ` sccs_verts\"\n    by (auto intro!: rev_image_eqI in_sccs_vertsI_sccs dest: in_verts_sccsD_sccs\n      simp: sccs_def induce_eq_iff_induced)\n\nend\n\n\nlemma connected_conv:\n  shows \"connected G \\<longleftrightarrow> verts G \\<noteq> {} \\<and> (\\<forall>u \\<in> verts G. \\<forall>v \\<in> verts G. (u,v) \\<in> rtrancl_on (verts G) ((arcs_ends G)\\<^sup>s))\"\nproof -\n  have \"symcl (arcs_ends G) = parcs (mk_symmetric G)\"\n    by (auto simp: parcs_mk_symmetric symcl_def arcs_ends_conv)\n  then show ?thesis by (auto simp: connected_def strongly_connected_def reachable_def)\nqed\n\nlemma (in wf_digraph) symmetric_connected_imp_strongly_connected:\n  assumes \"symmetric G\" \"connected G\"\n  shows \"strongly_connected G\"\nproof\n  from \\<open>connected G\\<close> show \"verts G \\<noteq> {}\" unfolding connected_def strongly_connected_def by auto\nnext\n  from \\<open>connected G\\<close>\n  have sc_mks: \"strongly_connected (mk_symmetric G)\"\n    unfolding connected_def by simp\n\n  fix u v assume \"u \\<in> verts G\" \"v \\<in> verts G\"\n  with sc_mks have \"u \\<rightarrow>\\<^sup>*\\<^bsub>mk_symmetric G\\<^esub> v\"\n    unfolding strongly_connected_def by auto\n  then show \"u \\<rightarrow>\\<^sup>* v\" using assms by (simp only: reachable_mk_symmetric_eq)\nqed\n\nlemma (in wf_digraph) connected_spanning_imp_connected:\n  assumes \"spanning H G\"\n  assumes \"connected H\"\n  shows \"connected G\"\nproof (unfold connected_def strongly_connected_def, intro conjI ballI)\n  from assms show \"verts (mk_symmetric G )\\<noteq> {}\"\n    unfolding spanning_def connected_def strongly_connected_def by auto\nnext\n  fix u v\n  assume \"u \\<in> verts (mk_symmetric G)\" and \"v \\<in> verts (mk_symmetric G)\"\n  then have \"u \\<in> pverts (mk_symmetric H)\" and \"v \\<in> pverts (mk_symmetric H)\"\n    using \\<open>spanning H G\\<close> by (auto simp: mk_symmetric_def)\n  with \\<open>connected H\\<close>\n  have \"u \\<rightarrow>\\<^sup>*\\<^bsub>with_proj (mk_symmetric H)\\<^esub> v\" \"subgraph (mk_symmetric H) (mk_symmetric G)\"\n    using \\<open>spanning H G\\<close> unfolding connected_def\n    by (auto simp: spanning_def dest: subgraph_mk_symmetric)\n  then show \"u \\<rightarrow>\\<^sup>*\\<^bsub>mk_symmetric G\\<^esub> v\" by (rule pre_digraph.reachable_mono)\nqed\n\nlemma (in wf_digraph) spanning_tree_imp_connected:\n  assumes \"spanning_tree H G\"\n  shows \"connected G\"\nusing assms by (auto intro: connected_spanning_imp_connected)\n\nterm \"LEAST x. P x\"\n\nlemma (in sym_digraph) induce_reachable_is_in_sccs:\n  assumes \"u \\<in> verts G\"\n  shows \"(G \\<restriction> {v. u \\<rightarrow>\\<^sup>* v}) \\<in> sccs\"\nproof -\n  let ?c = \"(G \\<restriction> {v. u \\<rightarrow>\\<^sup>* v})\"\n  have isub_c: \"induced_subgraph ?c G\"\n    by (auto elim: reachable_in_vertsE)\n  then interpret c: wf_digraph ?c by (rule wf_digraphI_induced)\n\n  have sym_c: \"symmetric (G \\<restriction> {v. u \\<rightarrow>\\<^sup>* v})\"\n    using sym_arcs isub_c by (rule induced_graph_imp_symmetric)\n\n  note \\<open>induced_subgraph ?c G\\<close>\n  moreover\n  have \"strongly_connected ?c\"\n  proof (rule strongly_connectedI)\n    show \"verts ?c \\<noteq> {}\" using assms by auto\n  next\n    fix v w assume l_assms: \"v \\<in> verts ?c\" \"w \\<in> verts ?c\"\n    have \"u \\<rightarrow>\\<^sup>*\\<^bsub>G \\<restriction> {v. u \\<rightarrow>\\<^sup>* v}\\<^esub> v\"\n      using l_assms by (intro induce_reachable_preserves_paths) auto\n    then have \"v \\<rightarrow>\\<^sup>*\\<^bsub>G \\<restriction> {v. u \\<rightarrow>\\<^sup>* v}\\<^esub> u\" by (rule symmetric_reachable[OF sym_c])\n    also have \"u \\<rightarrow>\\<^sup>*\\<^bsub>G \\<restriction> {v. u \\<rightarrow>\\<^sup>* v}\\<^esub> w\"\n      using l_assms by (intro induce_reachable_preserves_paths) auto\n    finally show \"v \\<rightarrow>\\<^sup>*\\<^bsub>G \\<restriction> {v. u \\<rightarrow>\\<^sup>* v}\\<^esub> w\" .\n  qed\n  moreover\n  have \"\\<not>(\\<exists>d. induced_subgraph d G \\<and> strongly_connected d \\<and>\n    verts ?c \\<subset> verts d)\"\n  proof\n    assume \"\\<exists>d. induced_subgraph d G \\<and> strongly_connected d \\<and>\n      verts ?c \\<subset> verts d\"\n    then obtain d where \"induced_subgraph d G\" \"strongly_connected d\"\n      \"verts ?c \\<subset> verts d\" by auto\n    then obtain v where \"v \\<in> verts d\" and \"v \\<notin> verts ?c\"\n      by auto\n\n    have \"u \\<in> verts ?c\" using \\<open>u \\<in> verts G\\<close> by auto\n    then have \"u \\<in> verts d\" using \\<open>verts ?c \\<subset> verts d\\<close> by auto \n    then have \"u \\<rightarrow>\\<^sup>*\\<^bsub>d\\<^esub> v\"\n      using \\<open>strongly_connected d\\<close> \\<open>u \\<in> verts d\\<close> \\<open>v \\<in> verts d\\<close> by auto\n    then have \"u \\<rightarrow>\\<^sup>* v\"\n      using \\<open>induced_subgraph d G\\<close>\n      by (auto intro: pre_digraph.reachable_mono)\n    then have \"v \\<in> verts ?c\" by (auto simp: reachable_awalk)\n    then show False using \\<open>v \\<notin> verts ?c\\<close> by auto\n  qed\n  ultimately show ?thesis unfolding sccs_def by auto\nqed\n\nlemma induced_eq_verts_imp_eq:\n  assumes \"induced_subgraph G H\"\n  assumes \"induced_subgraph G' H\"\n  assumes \"verts G = verts G'\"\n  shows \"G = G'\"\n  using assms by (auto simp: induced_subgraph_def subgraph_def compatible_def)\n\nlemma (in pre_digraph) in_sccs_subset_imp_eq:\n  assumes \"c \\<in> sccs\"\n  assumes \"d \\<in> sccs\"\n  assumes \"verts c \\<subseteq> verts d\"\n  shows \"c = d\"\nusing assms by (blast intro: induced_eq_verts_imp_eq)\n\ncontext wf_digraph begin\n\n  lemma connectedI:\n    assumes \"verts G \\<noteq> {}\" \"\\<And>u v. u \\<in> verts G \\<Longrightarrow> v \\<in> verts G \\<Longrightarrow> u \\<rightarrow>\\<^sup>*\\<^bsub>mk_symmetric G\\<^esub> v\"\n    shows \"connected G\"\n    using assms by (auto simp: connected_def)\n  \n  lemma connected_awalkE:\n    assumes \"connected G\" \"u \\<in> verts G\" \"v \\<in> verts G\"\n    obtains p where \"pre_digraph.awalk (mk_symmetric G) u p v\"\n  proof -\n    interpret sG: pair_wf_digraph \"mk_symmetric G\" ..\n    from assms have \"u \\<rightarrow>\\<^sup>*\\<^bsub>mk_symmetric G\\<^esub> v\" by (auto simp: connected_def)\n    then obtain p where \"sG.awalk u p v\" by (auto simp: sG.reachable_awalk)\n    then show ?thesis ..\n  qed\n\n  lemma inj_on_verts_sccs: \"inj_on verts sccs\"\n    by (rule inj_onI) (metis in_sccs_imp_induced induced_eq_verts_imp_eq)\n\n  lemma card_sccs_verts: \"card sccs_verts = card sccs\"\n    by (auto simp: sccs_verts_conv intro: inj_on_verts_sccs card_image)\n\nend\n\n\nlemma strongly_connected_non_disj:\n  assumes wf: \"wf_digraph G\" \"wf_digraph H\" \"compatible G H\"\n  assumes sc: \"strongly_connected G\" \"strongly_connected H\"\n  assumes not_disj: \"verts G \\<inter> verts H \\<noteq> {}\"\n  shows \"strongly_connected (union G H)\"\nproof\n  from sc show \"verts (union G H) \\<noteq> {}\"\n    unfolding strongly_connected_def by simp\nnext\n  let ?x = \"union G H\"\n  fix u v w assume \"u \\<in> verts ?x\" and \"v \\<in> verts ?x\"\n  obtain w where w_in_both: \"w \\<in> verts G\" \"w \\<in> verts H\"\n    using not_disj by auto\n\n  interpret x: wf_digraph ?x\n    by (rule wellformed_union) fact+\n  have subg: \"subgraph G ?x\" \"subgraph H ?x\"\n    by (rule subgraphs_of_union[OF _ _ ], fact+)+\n  have reach_uw: \"u \\<rightarrow>\\<^sup>*\\<^bsub>?x\\<^esub> w\"\n    using \\<open>u \\<in> verts ?x\\<close> subg w_in_both sc\n    by (auto intro: pre_digraph.reachable_mono)\n  also have reach_wv: \"w \\<rightarrow>\\<^sup>*\\<^bsub>?x\\<^esub> v\"\n    using \\<open>v \\<in> verts ?x\\<close> subg w_in_both sc\n    by (auto intro: pre_digraph.reachable_mono)\n  finally (x.reachable_trans) show \"u \\<rightarrow>\\<^sup>*\\<^bsub>?x\\<^esub> v\" .\nqed\n\ncontext wf_digraph begin\n\n  lemma scc_disj:\n    assumes scc: \"c \\<in> sccs\" \"d \\<in> sccs\"\n    assumes \"c \\<noteq> d\"\n    shows \"verts c \\<inter> verts d = {}\"\n  proof (rule ccontr)\n    assume contr: \"\\<not>?thesis\"\n\n    let ?x = \"union c d\"\n\n    have comp1: \"compatible G c\" \"compatible G d\"\n      using scc by (auto simp: sccs_def)\n    then have comp: \"compatible c d\" by (auto simp: compatible_def)\n\n    have wf: \"wf_digraph c\" \"wf_digraph d\"\n      and sc: \"strongly_connected c\" \"strongly_connected d\"\n      using scc by (auto intro: in_sccs_imp_induced)\n    have \"compatible c d\"\n      using comp by (auto simp: sccs_def compatible_def)\n    from wf comp sc have union_conn: \"strongly_connected ?x\"\n      using contr by (rule strongly_connected_non_disj)\n\n    have sg: \"subgraph ?x G\"\n      using scc comp1 by (intro subgraph_union) (auto simp: compatible_def)\n    then have v_cd: \"verts c \\<subseteq> verts G\"  \"verts d \\<subseteq> verts G\" by (auto elim!: subgraphE)\n    have \"wf_digraph ?x\" by (rule wellformed_union) fact+\n    with v_cd sg union_conn\n    have induce_subgraph_conn: \"strongly_connected (G \\<restriction> verts ?x)\"\n        \"induced_subgraph (G \\<restriction> verts ?x) G\"\n      by - (intro strongly_connected_imp_induce_subgraph_strongly_connected,\n        auto simp: subgraph_union_iff)\n\n    from assms have \"\\<not>verts c \\<subseteq> verts d\" and \"\\<not> verts d \\<subseteq> verts c\"\n      by (metis in_sccs_subset_imp_eq)+\n    then have psub: \"verts c \\<subset> verts ?x\"\n      by (auto simp: union_def)\n    then show False using induce_subgraph_conn\n      by (metis \\<open>c \\<in> sccs\\<close> in_sccsE induce_subgraph_verts)\n  qed\n\n  lemma in_sccs_verts_conv:\n    \"S \\<in> sccs_verts \\<longleftrightarrow> G \\<restriction> S \\<in> sccs\"\n    by (auto simp: sccs_verts_conv intro: rev_image_eqI)\n      (metis in_sccs_imp_induced induce_subgraph_verts induced_eq_verts_imp_eq induced_imp_subgraph induced_induce subgraphE)\n\nend\n\nlemma (in wf_digraph) in_scc_of_self: \"u \\<in> verts G \\<Longrightarrow> u \\<in> scc_of u\"\n  by (auto simp: scc_of_def)\n\nlemma (in wf_digraph) scc_of_empty_conv: \"scc_of u = {} \\<longleftrightarrow> u \\<notin> verts G\"\n  using in_scc_of_self by (auto simp: scc_of_def reachable_in_verts)\n\nlemma (in wf_digraph) scc_of_in_sccs_verts:\n  assumes \"u \\<in> verts G\" shows \"scc_of u \\<in> sccs_verts\"\n  using assms by (auto simp: in_sccs_verts_conv_reachable scc_of_def intro: reachable_trans exI[where x=u])\n\nlemma (in wf_digraph) sccs_verts_subsets: \"S \\<in> sccs_verts \\<Longrightarrow> S \\<subseteq> verts G\"\n  by (auto simp: sccs_verts_conv)\n\nlemma (in fin_digraph) finite_sccs_verts: \"finite sccs_verts\"\nproof -\n  have \"finite (Pow (verts G))\" by auto\n  moreover with sccs_verts_subsets have \"sccs_verts \\<subseteq> Pow (verts G)\" by auto\n  ultimately show ?thesis by (rule rev_finite_subset)\nqed\n\nlemma (in wf_digraph) sccs_verts_conv_scc_of:\n  \"sccs_verts = scc_of ` verts G\" (is \"?L = ?R\")\nproof (intro set_eqI iffI)\n  fix S assume \"S \\<in> ?R\" then show \"S \\<in> ?L\"\n    by (auto simp: in_sccs_verts_conv_reachable scc_of_empty_conv) (auto simp: scc_of_def intro: reachable_trans)\nnext\n  fix S assume \"S \\<in> ?L\"\n  moreover\n  then obtain u where \"u \\<in> S\" by (auto simp: in_sccs_verts_conv_reachable)\n  moreover\n  then have \"u \\<in> verts G\" using \\<open>S \\<in> ?L\\<close> by (metis sccs_verts_subsets subsetCE)\n  then have \"scc_of u \\<in> sccs_verts\" \"u \\<in> scc_of u\"\n    by (auto intro: scc_of_in_sccs_verts in_scc_of_self)\n  ultimately\n  have \"scc_of u = S\" using sccs_verts_disjoint by blast\n  then show \"S \\<in> ?R\" using \\<open>scc_of u \\<in> _\\<close> \\<open>u \\<in> verts G\\<close> by auto\nqed\n\nlemma (in sym_digraph) scc_ofI_reachable:\n  assumes \"u \\<rightarrow>\\<^sup>* v\" shows \"u \\<in> scc_of v\"\n  using assms by (auto simp: scc_of_def symmetric_reachable[OF sym_arcs])\n\nlemma (in sym_digraph) scc_ofI_reachable':\n  assumes \"v \\<rightarrow>\\<^sup>* u\" shows \"u \\<in> scc_of v\"\n  using assms by (auto simp: scc_of_def symmetric_reachable[OF sym_arcs])\n\nlemma (in sym_digraph) scc_ofI_awalk:\n  assumes \"awalk u p v\" shows \"u \\<in> scc_of v\"\n  using assms by (metis reachable_awalk scc_ofI_reachable)\n\nlemma (in sym_digraph) scc_ofI_apath:\n  assumes \"apath u p v\" shows \"u \\<in> scc_of v\"\n  using assms by (metis reachable_apath scc_ofI_reachable)\n\nlemma (in wf_digraph) scc_of_eq: \"u \\<in> scc_of v \\<Longrightarrow> scc_of u = scc_of v\"\n  by (auto simp: scc_of_def intro: reachable_trans)\n\nlemma (in wf_digraph) strongly_connected_eq_iff:\n  \"strongly_connected G \\<longleftrightarrow> sccs = {G}\" (is \"?L \\<longleftrightarrow> ?R\")\nproof\n  assume ?L\n  then have \"G \\<in> sccs\" by (auto simp: sccs_def induced_subgraph_refl)\n  moreover\n  { fix H assume \"H \\<in> sccs\" \"G \\<noteq> H\"\n    with \\<open>G \\<in> sccs\\<close> have \"verts G \\<inter> verts H = {}\" by (rule scc_disj)\n    moreover\n    from \\<open>H \\<in> sccs\\<close> have \"verts H \\<subseteq> verts G\" by auto\n    ultimately\n    have \"verts H = {}\" by auto\n    with \\<open>H \\<in> sccs\\<close> have \"False\" by (auto simp: sccs_def strongly_connected_def)\n  } ultimately\n  show ?R by auto\nqed (auto simp: sccs_def)\n\n\n\n\nsubsection \\<open>Components\\<close>\n\nlemma (in sym_digraph) exists_scc:\n  assumes \"verts G \\<noteq> {}\" shows \"\\<exists>c. c \\<in> sccs\"\nproof -\n  from assms obtain u where \"u \\<in> verts G\" by auto\n  then show ?thesis by (blast dest: induce_reachable_is_in_sccs)\nqed\n\ntheorem (in sym_digraph) graph_is_union_sccs:\n  shows \"Union sccs = G\"\nproof -\n  have \"(\\<Union>c \\<in> sccs. verts c) = verts G\"\n    by (auto intro: induce_reachable_is_in_sccs)\n  moreover\n  have \"(\\<Union>c \\<in> sccs. arcs c) = arcs G\"\n  proof\n    show \"(\\<Union>c \\<in> sccs. arcs c) \\<subseteq> arcs G\"\n      by safe (metis in_sccsE induced_imp_subgraph subgraphE subsetD)\n    show \"arcs G \\<subseteq> (\\<Union>c \\<in> sccs. arcs c)\"\n    proof (safe)\n      fix e assume \"e \\<in> arcs G\"\n      define a b where [simp]: \"a = tail G e\" and [simp]: \"b = head G e\"\n\n      have \"e \\<in> (\\<Union>x \\<in> sccs. arcs x)\"\n      proof cases\n        assume \"\\<exists>x\\<in>sccs. {a,b } \\<subseteq> verts x\"\n        then obtain c where \"c \\<in> sccs\" and \"{a,b} \\<subseteq> verts c\"\n          by auto\n        then have \"e \\<in> {e \\<in> arcs G. tail G e \\<in> verts c\n          \\<and> head G e \\<in> verts c}\" using \\<open>e \\<in> arcs G\\<close> by auto\n        then have \"e \\<in> arcs c\" using \\<open>c \\<in> sccs\\<close> by blast\n        then show ?thesis using \\<open>c \\<in> sccs\\<close> by auto\n      next\n        assume l_assm: \"\\<not>(\\<exists>x\\<in>sccs. {a,b} \\<subseteq> verts x)\"\n\n        have \"a \\<rightarrow>\\<^sup>* b\" using \\<open>e \\<in> arcs G\\<close> \n          by (metis a_def b_def reachable_adjI in_arcs_imp_in_arcs_ends)\n        then have \"{a,b} \\<subseteq> verts (G \\<restriction> {v. a \\<rightarrow>\\<^sup>* v})\" \"a \\<in> verts G\"\n          by (auto elim: reachable_in_vertsE)\n        moreover\n        have \"(G \\<restriction> {v. a \\<rightarrow>\\<^sup>* v}) \\<in> sccs\"\n          using \\<open>a \\<in> verts G\\<close> by (auto intro: induce_reachable_is_in_sccs)\n        ultimately\n        have False using l_assm by blast\n        then show ?thesis by simp\n      qed\n      then show \"e \\<in> (\\<Union>c \\<in> sccs. arcs c)\" by auto\n    qed\n  qed\n  ultimately show ?thesis\n    by (auto simp add: Union_def)\nqed\n\nlemma (in sym_digraph) scc_for_vert_ex:\n  assumes \"u \\<in> verts G\"\n  shows \"\\<exists>c. c\\<in>sccs \\<and> u \\<in> verts c\"\nusing assms by (auto intro: induce_reachable_is_in_sccs)\n\n\n\nlemma (in sym_digraph) scc_decomp_unique:\n  assumes \"S \\<subseteq> sccs\" \"verts (Union S) = verts G\" shows \"S = sccs\"\nproof (rule ccontr)\n  assume \"S \\<noteq> sccs\"\n  with assms obtain c where \"c \\<in> sccs\" and \"c \\<notin> S\" by auto\n  with assms have \"\\<And>d. d \\<in> S \\<Longrightarrow> verts c \\<inter> verts d = {}\"\n    by (intro scc_disj) auto\n  then have \"verts c \\<inter> verts (Union S) = {}\"\n    by (auto simp: Union_def)\n  with assms have \"verts c \\<inter> verts G = {}\" by auto\n  moreover from \\<open>c \\<in> sccs\\<close> obtain u where \"u \\<in> verts c \\<inter> verts G\"\n    by (auto simp: sccs_def strongly_connected_def)\n  ultimately show False by blast\nqed\n\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/Digraph_Component.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8577680977182187, "lm_q2_score": 0.8354835289107307, "lm_q1q2_score": 0.7166511172686619}}
{"text": "(*  Title:      HOL/Meson.thy\n    Author:     Lawrence C. Paulson, Cambridge University Computer Laboratory\n    Author:     Tobias Nipkow, TU Muenchen\n    Author:     Jasmin Blanchette, TU Muenchen\n    Copyright   2001  University of Cambridge\n*)\n\nsection \\<open>MESON Proof Method\\<close>\n\ntheory Meson\nimports Nat\nbegin\n\nsubsection \\<open>Negation Normal Form\\<close>\n\ntext \\<open>de Morgan laws\\<close>\n\nlemma not_conjD: \"\\<not>(P\\<and>Q) \\<Longrightarrow> \\<not>P \\<or> \\<not>Q\"\n  and not_disjD: \"\\<not>(P\\<or>Q) \\<Longrightarrow> \\<not>P \\<and> \\<not>Q\"\n  and not_notD: \"\\<not>\\<not>P \\<Longrightarrow> P\"\n  and not_allD: \"\\<And>P. \\<not>(\\<forall>x. P(x)) \\<Longrightarrow> \\<exists>x. \\<not>P(x)\"\n  and not_exD: \"\\<And>P. \\<not>(\\<exists>x. P(x)) \\<Longrightarrow> \\<forall>x. \\<not>P(x)\"\n  by fast+\n\ntext \\<open>Removal of \\<open>\\<longrightarrow>\\<close> and \\<open>\\<longleftrightarrow>\\<close> (positive and negative occurrences)\\<close>\n\nlemma imp_to_disjD: \"P\\<longrightarrow>Q \\<Longrightarrow> \\<not>P \\<or> Q\"\n  and not_impD: \"\\<not>(P\\<longrightarrow>Q) \\<Longrightarrow> P \\<and> \\<not>Q\"\n  and iff_to_disjD: \"P=Q \\<Longrightarrow> (\\<not>P \\<or> Q) \\<and> (\\<not>Q \\<or> P)\"\n  and not_iffD: \"\\<not>(P=Q) \\<Longrightarrow> (P \\<or> Q) \\<and> (\\<not>P \\<or> \\<not>Q)\"\n    \\<comment> \\<open>Much more efficient than \\<^prop>\\<open>(P \\<and> \\<not>Q) \\<or> (Q \\<and> \\<not>P)\\<close> for computing CNF\\<close>\n  and not_refl_disj_D: \"x \\<noteq> x \\<or> P \\<Longrightarrow> P\"\n  by fast+\n\n\nsubsection \\<open>Pulling out the existential quantifiers\\<close>\n\ntext \\<open>Conjunction\\<close>\n\nlemma conj_exD1: \"\\<And>P Q. (\\<exists>x. P(x)) \\<and> Q \\<Longrightarrow> \\<exists>x. P(x) \\<and> Q\"\n  and conj_exD2: \"\\<And>P Q. P \\<and> (\\<exists>x. Q(x)) \\<Longrightarrow> \\<exists>x. P \\<and> Q(x)\"\n  by fast+\n\n\ntext \\<open>Disjunction\\<close>\n\nlemma disj_exD: \"\\<And>P Q. (\\<exists>x. P(x)) \\<or> (\\<exists>x. Q(x)) \\<Longrightarrow> \\<exists>x. P(x) \\<or> Q(x)\"\n  \\<comment> \\<open>DO NOT USE with forall-Skolemization: makes fewer schematic variables!!\\<close>\n  \\<comment> \\<open>With ex-Skolemization, makes fewer Skolem constants\\<close>\n  and disj_exD1: \"\\<And>P Q. (\\<exists>x. P(x)) \\<or> Q \\<Longrightarrow> \\<exists>x. P(x) \\<or> Q\"\n  and disj_exD2: \"\\<And>P Q. P \\<or> (\\<exists>x. Q(x)) \\<Longrightarrow> \\<exists>x. P \\<or> Q(x)\"\n  by fast+\n\nlemma disj_assoc: \"(P\\<or>Q)\\<or>R \\<Longrightarrow> P\\<or>(Q\\<or>R)\"\n  and disj_comm: \"P\\<or>Q \\<Longrightarrow> Q\\<or>P\"\n  and disj_FalseD1: \"False\\<or>P \\<Longrightarrow> P\"\n  and disj_FalseD2: \"P\\<or>False \\<Longrightarrow> P\"\n  by fast+\n\n\ntext\\<open>Generation of contrapositives\\<close>\n\ntext\\<open>Inserts negated disjunct after removing the negation; P is a literal.\n  Model elimination requires assuming the negation of every attempted subgoal,\n  hence the negated disjuncts.\\<close>\nlemma make_neg_rule: \"\\<not>P\\<or>Q \\<Longrightarrow> ((\\<not>P\\<Longrightarrow>P) \\<Longrightarrow> Q)\"\nby blast\n\ntext\\<open>Version for Plaisted's \"Postive refinement\" of the Meson procedure\\<close>\nlemma make_refined_neg_rule: \"\\<not>P\\<or>Q \\<Longrightarrow> (P \\<Longrightarrow> Q)\"\nby blast\n\ntext\\<open>\\<^term>\\<open>P\\<close> should be a literal\\<close>\nlemma make_pos_rule: \"P\\<or>Q \\<Longrightarrow> ((P\\<Longrightarrow>\\<not>P) \\<Longrightarrow> Q)\"\nby blast\n\ntext\\<open>Versions of \\<open>make_neg_rule\\<close> and \\<open>make_pos_rule\\<close> that don't\ninsert new assumptions, for ordinary resolution.\\<close>\n\nlemmas make_neg_rule' = make_refined_neg_rule\n\nlemma make_pos_rule': \"\\<lbrakk>P\\<or>Q; \\<not>P\\<rbrakk> \\<Longrightarrow> Q\"\nby blast\n\ntext\\<open>Generation of a goal clause -- put away the final literal\\<close>\n\nlemma make_neg_goal: \"\\<not>P \\<Longrightarrow> ((\\<not>P\\<Longrightarrow>P) \\<Longrightarrow> False)\"\nby blast\n\nlemma make_pos_goal: \"P \\<Longrightarrow> ((P\\<Longrightarrow>\\<not>P) \\<Longrightarrow> False)\"\nby blast\n\n\nsubsection \\<open>Lemmas for Forward Proof\\<close>\n\ntext\\<open>There is a similarity to congruence rules. They are also useful in ordinary proofs.\\<close>\n\n(*NOTE: could handle conjunctions (faster?) by\n    nf(th RS conjunct2) RS (nf(th RS conjunct1) RS conjI) *)\nlemma conj_forward: \"\\<lbrakk>P'\\<and>Q';  P' \\<Longrightarrow> P;  Q' \\<Longrightarrow> Q \\<rbrakk> \\<Longrightarrow> P\\<and>Q\"\nby blast\n\nlemma disj_forward: \"\\<lbrakk>P'\\<or>Q';  P' \\<Longrightarrow> P;  Q' \\<Longrightarrow> Q \\<rbrakk> \\<Longrightarrow> P\\<or>Q\"\nby blast\n\nlemma imp_forward: \"\\<lbrakk>P' \\<longrightarrow> Q';  P \\<Longrightarrow> P';  Q' \\<Longrightarrow> Q \\<rbrakk> \\<Longrightarrow> P \\<longrightarrow> Q\"\nby blast\n\nlemma imp_forward2: \"\\<lbrakk>P' \\<longrightarrow> Q';  P \\<Longrightarrow> P';  P' \\<Longrightarrow> Q' \\<Longrightarrow> Q \\<rbrakk> \\<Longrightarrow> P \\<longrightarrow> Q\"\n  by blast\n\n(*Version of @{text disj_forward} for removal of duplicate literals*)\nlemma disj_forward2: \"\\<lbrakk> P'\\<or>Q';  P' \\<Longrightarrow> P;  \\<lbrakk>Q'; P\\<Longrightarrow>False\\<rbrakk> \\<Longrightarrow> Q\\<rbrakk> \\<Longrightarrow> P\\<or>Q\"\napply blast \ndone\n\nlemma all_forward: \"[| \\<forall>x. P'(x);  !!x. P'(x) ==> P(x) |] ==> \\<forall>x. P(x)\"\nby blast\n\nlemma ex_forward: \"[| \\<exists>x. P'(x);  !!x. P'(x) ==> P(x) |] ==> \\<exists>x. P(x)\"\nby blast\n\n\nsubsection \\<open>Clausification helper\\<close>\n\nlemma TruepropI: \"P \\<equiv> Q \\<Longrightarrow> Trueprop P \\<equiv> Trueprop Q\"\nby simp\n\nlemma ext_cong_neq: \"F g \\<noteq> F h \\<Longrightarrow> F g \\<noteq> F h \\<and> (\\<exists>x. g x \\<noteq> h x)\"\napply (erule contrapos_np)\napply clarsimp\napply (rule cong[where f = F])\nby auto\n\n\ntext\\<open>Combinator translation helpers\\<close>\n\ndefinition COMBI :: \"'a \\<Rightarrow> 'a\" where\n\"COMBI P = P\"\n\ndefinition COMBK :: \"'a \\<Rightarrow> 'b \\<Rightarrow> 'a\" where\n\"COMBK P Q = P\"\n\ndefinition COMBB :: \"('b => 'c) \\<Rightarrow> ('a => 'b) \\<Rightarrow> 'a \\<Rightarrow> 'c\" where\n\"COMBB P Q R = P (Q R)\"\n\ndefinition COMBC :: \"('a \\<Rightarrow> 'b \\<Rightarrow> 'c) \\<Rightarrow> 'b \\<Rightarrow> 'a \\<Rightarrow> 'c\" where\n\"COMBC P Q R = P R Q\"\n\ndefinition COMBS :: \"('a \\<Rightarrow> 'b \\<Rightarrow> 'c) \\<Rightarrow> ('a \\<Rightarrow> 'b) \\<Rightarrow> 'a \\<Rightarrow> 'c\" where\n\"COMBS P Q R = P R (Q R)\"\n\nlemma abs_S: \"\\<lambda>x. (f x) (g x) \\<equiv> COMBS f g\"\napply (rule eq_reflection)\napply (rule ext) \napply (simp add: COMBS_def) \ndone\n\nlemma abs_I: \"\\<lambda>x. x \\<equiv> COMBI\"\napply (rule eq_reflection)\napply (rule ext) \napply (simp add: COMBI_def) \ndone\n\nlemma abs_K: \"\\<lambda>x. y \\<equiv> COMBK y\"\napply (rule eq_reflection)\napply (rule ext) \napply (simp add: COMBK_def) \ndone\n\nlemma abs_B: \"\\<lambda>x. a (g x) \\<equiv> COMBB a g\"\napply (rule eq_reflection)\napply (rule ext) \napply (simp add: COMBB_def) \ndone\n\nlemma abs_C: \"\\<lambda>x. (f x) b \\<equiv> COMBC f b\"\napply (rule eq_reflection)\napply (rule ext) \napply (simp add: COMBC_def) \ndone\n\n\nsubsection \\<open>Skolemization helpers\\<close>\n\ndefinition skolem :: \"'a \\<Rightarrow> 'a\" where\n\"skolem = (\\<lambda>x. x)\"\n\nlemma skolem_COMBK_iff: \"P \\<longleftrightarrow> skolem (COMBK P (i::nat))\"\nunfolding skolem_def COMBK_def by (rule refl)\n\nlemmas skolem_COMBK_I = iffD1 [OF skolem_COMBK_iff]\n\n\nsubsection \\<open>Meson package\\<close>\n\nML_file \\<open>Tools/Meson/meson.ML\\<close>\nML_file \\<open>Tools/Meson/meson_clausify.ML\\<close>\nML_file \\<open>Tools/Meson/meson_tactic.ML\\<close>\n\nhide_const (open) COMBI COMBK COMBB COMBC COMBS skolem\nhide_fact (open) not_conjD not_disjD not_notD not_allD not_exD imp_to_disjD\n    not_impD iff_to_disjD not_iffD not_refl_disj_D conj_exD1 conj_exD2 disj_exD\n    disj_exD1 disj_exD2 disj_assoc disj_comm disj_FalseD1 disj_FalseD2 TruepropI\n    ext_cong_neq COMBI_def COMBK_def COMBB_def COMBC_def COMBS_def abs_I abs_K\n    abs_B abs_C abs_S skolem_def skolem_COMBK_iff skolem_COMBK_I\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/Meson.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933359135361, "lm_q2_score": 0.8740772335247532, "lm_q1q2_score": 0.7166500988406848}}
{"text": "header {* Hoare Triples  *}\n\ntheory Hoare\nimports Statements\nbegin\n\ntext {*\nA hoare triple for $p,q\\in \\mathit{State}\\ \\mathit{set}$, and \n$S : \\mathit{State}\\ \\mathit{set} \\to \\mathit{State}\\ \\mathit{set}$ is valid,\ndenoted $\\models p \\{|S|\\} q$, if every execution of $S$ starting from state $s\\in p$\nalways terminates, and if it terminates in state $s'$, then $s'\\in q$. When $S$ is\nmodeled as a predicate transformer, this definition is equivalent to requiring that\n$p$ is a subset of the initial states from which the execution of $S$ is guaranteed\nto terminate in $q$, that is $p \\subseteq S\\ q$.\n\nThe formal definition of a valid hoare triple only assumes that $p$ (and also $S\\ q$) ranges\nover a complete lattice.\n*}\n\ndefinition\n  Hoare :: \"'a::complete_distrib_lattice \\<Rightarrow> ('b \\<Rightarrow> 'a) \\<Rightarrow> 'b \\<Rightarrow> bool\" (\"\\<Turnstile> (_){| _ |}(_)\" [0,0,900] 900) where\n  \"\\<Turnstile> p {|S|} q = (p \\<le> (S q))\"\n\ntheorem hoare_sequential:\n  \"mono S \\<Longrightarrow> (\\<Turnstile> p {| S o T |} r) = ( (\\<exists> q. \\<Turnstile> p {| S |} q \\<and> \\<Turnstile> q {| T |} r))\"\n  by (metis (no_types) Hoare_def monoD o_def order_refl order_trans)\n\ntheorem hoare_choice:\n  \"\\<Turnstile> p {| S \\<sqinter> T |} q = (\\<Turnstile> p {| S |} q \\<and> \\<Turnstile> p {| T |} q)\"\n  by (simp_all add: Hoare_def inf_fun_def)\n\ntheorem hoare_assume:\n  \"(\\<Turnstile> P {| [.R.] |} Q) = (P \\<sqinter> R \\<le> Q)\"\n  apply (simp add: Hoare_def assume_def)\n  apply safe\n  apply (case_tac \"(inf P R) \\<le> (inf (sup (- R) Q) R)\")\n  apply (simp add: inf_sup_distrib2)\n  apply (simp add: le_infI1)\n  apply (case_tac \"(sup (-R) (inf P R)) \\<le> sup (- R) Q\")\n  apply (simp add: sup_inf_distrib1)\n  by (simp add: le_supI2)\n\ntheorem hoare_mono:\n  \"mono S \\<Longrightarrow> Q \\<le> R \\<Longrightarrow> \\<Turnstile> P {| S |} Q \\<Longrightarrow> \\<Turnstile> P {| S |} R\"\n  apply (simp add: mono_def Hoare_def)\n  apply (rule_tac y = \"S Q\" in order_trans)\n  by auto\n\ntheorem hoare_pre:\n  \"R \\<le> P \\<Longrightarrow> \\<Turnstile> P {| S |} Q \\<Longrightarrow> \\<Turnstile> R {| S |} Q\"\n  by (simp add: Hoare_def)\n\ntheorem hoare_Sup:\n  \"(\\<forall> p \\<in> P . \\<Turnstile> p {| S |} q) = \\<Turnstile> Sup P {| S |} q\"\n  apply (simp add: Hoare_def, safe, simp add: Sup_least)\n  apply (rule_tac y = \"\\<Squnion>P\" in order_trans, simp_all)\n  by (simp add: Sup_upper)\n  \nlemma hoare_magic [simp]: \"\\<Turnstile> P {| \\<top> |} Q\" \n  by (simp add: Hoare_def top_fun_def)\n\nlemma hoare_demonic: \"\\<Turnstile> P {| [:R:] |} Q = (\\<forall> s . s \\<in> P \\<longrightarrow>  R s \\<subseteq> Q)\"\n  apply (unfold Hoare_def demonic_def)\n  by auto\n\nlemma hoare_not_guard:\n  \"mono (S :: (_::order_bot) \\<Rightarrow> _) \\<Longrightarrow> \\<Turnstile> p {| S |} q = \\<Turnstile> (p \\<squnion> (- grd S)) {| S |} q\"\n  apply (simp add: Hoare_def grd_def, safe)\n  apply (drule monoD)\n  by auto\n\nsubsection {* Hoare rule for recursive statements *}\n\ntext {*\nA statement $S$ is refined by another statement $S'$ if $\\models p \\{| S' |\\} q$ \nis true for all $p$ and $q$ such that  $\\models p \\{| S |\\} q$ is true. This\nis equivalent to $S \\le S'$. \n\nNext theorem can be used to prove refinement of a recursive program. A recursive\nprogram is modeled as the least fixpoint of a monotonic mapping from predicate\ntransformers to predicate transformers.\n*}\n\ntheorem lfp_wf_induction:\n  \"mono f \\<Longrightarrow> (\\<forall> w . (p w) \\<le> f (Sup_less p w)) \\<Longrightarrow> Sup (range p) \\<le> lfp f\"\n apply (rule fp_wf_induction, simp_all)\n by (drule lfp_unfold, simp)\n\ndefinition\n  \"post_fun (p::'a::order) q = (if p \\<le> q then \\<top> else \\<bottom>)\"\n\nlemma post_mono [simp]: \"mono (post_fun p :: (_::{order_bot,order_top}))\"\n   apply (simp add: post_fun_def  mono_def, safe)\n   apply (subgoal_tac \"p \\<le> y\", simp)\n   by (rule_tac y = x in order_trans, simp_all)\n\n\n\nlemma post_refin [simp]: \"mono S \\<Longrightarrow> ((S p)::'a::bounded_lattice) \\<sqinter> (post_fun p) x \\<le> S x\"\n  apply (simp add: le_fun_def post_fun_def, safe)\n  by (rule_tac f = S in monoD, simp_all)\n\ntext {*\nNext theorem shows the equivalence between the validity of Hoare\ntriples and refinement statements. This theorem together with the\ntheorem for refinement of recursive programs will be used to prove\na Hoare rule for recursive programs.\n*}\n\ntheorem hoare_refinement_post:\n  \"mono f \\<Longrightarrow>  (\\<Turnstile> x {| f |} y) = ({.x.} o (post_fun y) \\<le> f)\"\n  apply safe\n  apply (simp_all add: Hoare_def)\n  apply (simp_all add: le_fun_def)\n  apply (simp add: assert_def, safe)\n  apply (rule_tac y = \"f y \\<sqinter> post_fun y xa\" in order_trans, simp_all)\n  apply (rule_tac y = \"x\" in order_trans, simp_all)\n  apply (simp add: assert_def)\n  by (drule_tac x = \"y\" in spec, simp)\n\n\ntext {*\nNext theorem gives a Hoare rule for recursive programs. If we can prove correct the unfolding \nof the recursive definition applid to a program $f$, $\\models p\\ w\\ \\{| F\\  f |\\}\\  y$, assumming\nthat $f$ is correct when starting from $p\\  v$, $v<w$, $\\models SUP-L\\  p\\  w\\  \\{| f |\\}\\  y$, then\nthe recursive program is correct $\\models SUP\\ p\\ \\{| lfp\\  F |\\}\\  y$\n*}\n\nlemma assert_Sup: \"{.\\<Squnion> (X::'a::complete_distrib_lattice set).} = \\<Squnion> (assert ` X)\"\n  by (simp add: fun_eq_iff assert_def Sup_inf)\n\nlemma assert_Sup_range: \"{.\\<Squnion> (range (p::'W \\<Rightarrow> 'a::complete_distrib_lattice)).} = \\<Squnion> (range (assert o p))\"\n  by (simp add: fun_eq_iff assert_def SUP_inf)\n\nlemma Sup_range_comp: \"(\\<Squnion> range p) o S = \\<Squnion> (range (\\<lambda> w . ((p w) o S)))\"\n  by (simp add: fun_eq_iff)\n\nlemma Sup_less_comp: \"(Sup_less P) w o S = Sup_less (\\<lambda> w . ((P w) o S)) w\"\n  apply (simp add: Sup_less_def fun_eq_iff, safe)\n  apply (subgoal_tac \"((\\<lambda>f. f (S x)) ` {y. \\<exists>v<w. \\<forall>x. y x = P v x}) = ((\\<lambda>f. f x) ` {y. \\<exists>v<w. \\<forall>x. y x = P v (S x)})\")\n  by (auto simp add: SUP_def simp del: Sup_image_eq)\n\nlemma Sup_less_assert: \"Sup_less (\\<lambda>w. {. (p w)::'a::complete_distrib_lattice .}) w = {.Sup_less p w.}\"\n  apply (simp add: Sup_less_def assert_Sup image_def)\n  apply (subgoal_tac \"{y. \\<exists>v<w. y = {. p v .}} = {y. \\<exists>x. (\\<exists>v<w. x = p v) \\<and> y = {. x .}}\")\n  by auto\n\n\ndeclare mono_comp[simp]\n\ntheorem hoare_fixpoint:\n  \"mono_mono F \\<Longrightarrow>\n   (!! w f . mono f \\<and> \\<Turnstile> Sup_less p w {| f |} y \\<Longrightarrow> \\<Turnstile> p w {| F f |} y) \\<Longrightarrow> \\<Turnstile> (Sup (range p)) {| lfp F |} y\"\n  apply (simp add: mono_mono_def hoare_refinement_post assert_Sup_range Sup_range_comp del: Sup_image_eq)\n  apply (rule lfp_wf_induction)\n  apply auto\n  apply (simp add: Sup_less_comp [THEN sym])\n  apply (simp add: Sup_less_assert)\n  apply (drule_tac x = \"{. Sup_less p w .} \\<circ> post_fun y\" in spec, safe)\n  apply simp\n  by (simp add: hoare_refinement_post)\n\ntheorem \"(\\<forall> t . \\<Turnstile> ({s . t \\<in> R s}) {|S|} q) \\<Longrightarrow> \\<Turnstile> ({:R:} p) {| S |} q\"\n  apply (simp add: Hoare_def angelic_def subset_eq)\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/DataRefinementIBP/Hoare.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772286044094, "lm_q2_score": 0.8198933315126791, "lm_q1q2_score": 0.7166500909598388}}
{"text": "section \\<open>Computing the Gcd via the subresultant PRS\\<close>\n\ntext \\<open>This theory now formalizes how the subresultant PRS can be used to calculate the gcd\n  of two polynomials. Moreover, it proves the connection between resultants and gcd, namely that\n  the resultant is 0 iff the degree of the gcd is non-zero.\\<close>\n\ntheory Subresultant_Gcd\nimports\n  Subresultant\n  Polynomial_Factorization.Missing_Polynomial_Factorial\nbegin\n\nsubsection \\<open>Algorithm\\<close>\n\nlocale div_exp_sound_gcd = div_exp_sound div_exp for \n  div_exp :: \"'a :: {semiring_gcd_mult_normalize,factorial_ring_gcd} \\<Rightarrow> 'a \\<Rightarrow> nat \\<Rightarrow> 'a\" \nbegin\ndefinition gcd_impl_primitive where\n  [code del]: \"gcd_impl_primitive G1 G2 = normalize (primitive_part (fst (subresultant_prs G1 G2)))\" \n\ndefinition gcd_impl_main where\n  [code del]: \"gcd_impl_main G1 G2 = (if G1 = 0 then 0 else if G2 = 0 then normalize G1 else\n   smult (gcd (content G1) (content G2))\n     (gcd_impl_primitive (primitive_part G1) (primitive_part G2)))\"\n\ndefinition gcd_impl where\n  \"gcd_impl f g = (if length (coeffs f) \\<ge> length (coeffs g) then gcd_impl_main f g  else gcd_impl_main g f)\"\n\nsubsection \\<open>Soundness Proof for @{term \"gcd_impl = gcd\"}\\<close>\nend\n\nlocale subresultant_prs_gcd = subresultant_prs_locale2 F n \\<delta> f k \\<beta> G1 G2 for\n       F :: \"nat \\<Rightarrow> 'a ::  {factorial_ring_gcd,semiring_gcd_mult_normalize} fract poly\"\n    and n :: \"nat \\<Rightarrow> nat\"\n    and \\<delta> :: \"nat \\<Rightarrow> nat\"\n    and f :: \"nat \\<Rightarrow> 'a fract\"\n    and k :: nat\n    and \\<beta> :: \"nat \\<Rightarrow> 'a fract\"\n    and G1 G2 :: \"'a poly\"\nbegin\ntext \\<open>The subresultant PRS computes the gcd up to a scalar multiple.\\<close>\n\ncontext\n  fixes div_exp :: \"'a \\<Rightarrow> 'a \\<Rightarrow> nat \\<Rightarrow> 'a\"\n  assumes div_exp_sound: \"div_exp_sound div_exp\"\nbegin\n\ninterpretation div_exp_sound_gcd div_exp \n  using div_exp_sound by (rule div_exp_sound_gcd.intro)\n\n\nlemma subresultant_prs_gcd: assumes \"subresultant_prs G1 G2 = (Gk, hk)\"\n  shows \"\\<exists> a b. a \\<noteq> 0 \\<and> b \\<noteq> 0 \\<and> smult a (gcd G1 G2) = smult b (normalize Gk)\"\nproof -\n  from subresultant_prs[OF div_exp_sound assms]\n  have Fk: \"F k = ffp Gk\" and \"\\<forall> i. \\<exists> H. i \\<noteq> 0 \\<longrightarrow> F i = ffp H\"\n    and \"\\<forall> i. \\<exists> b. 3 \\<le> i \\<longrightarrow> i \\<le> Suc k \\<longrightarrow> \\<beta> i = ff b\" by auto\n  from choice[OF this(2)] choice[OF this(3)] obtain H beta where\n    FH: \"\\<And> i. i \\<noteq> 0 \\<Longrightarrow> F i = ffp (H i)\" and\n    beta: \"\\<And> i. 3 \\<le> i \\<Longrightarrow> i \\<le> Suc k \\<Longrightarrow> \\<beta> i = ff (beta i)\" by auto\n  from Fk FH[OF k0] FH[of 1] FH[of 2] FH[of \"Suc k\"] F0[of \"Suc k\"] F1 F2\n  have border: \"H k = Gk\" \"H 1 = G1\" \"H 2 = G2\" \"H (Suc k) = 0\" by auto\n  have \"i \\<noteq> 0 \\<Longrightarrow> i \\<le> k \\<Longrightarrow> \\<exists> a b. a \\<noteq> 0 \\<and> b \\<noteq> 0 \\<and> smult a (gcd G1 G2) = smult b (gcd (H i) (H (Suc i)))\" for i\n  proof (induct i rule: less_induct)\n    case (less i)\n    from less(3) have ik: \"i \\<le> k\" .\n    from less(2) have \"i = 1 \\<or> i \\<ge> 2\" by auto\n    thus ?case\n    proof\n      assume \"i = 1\"\n      thus ?thesis unfolding border[symmetric] by (intro exI[of _ 1], auto simp: numeral_2_eq_2)\n    next\n      assume i2: \"i \\<ge> 2\"\n      with ik have \"i - 1 < i\" \"i - 1 \\<noteq> 0\" and imk: \"i - 1 \\<le> k\" by auto\n      from less(1)[OF this] i2\n      obtain a b where a: \"a \\<noteq> 0\" and b: \"b \\<noteq> 0\" and IH: \"smult a (gcd G1 G2) = smult b (gcd (H (i - 1)) (H i))\" by auto\n      define M where \"M = pseudo_mod (H (i - 1)) (H i)\"\n      define c where \"c = \\<beta> (Suc i)\"\n      have M: \"pseudo_mod (F (i - 1)) (F i) = ffp M\" unfolding to_fract_hom.pseudo_mod_hom[symmetric] M_def\n         using i2 FH by auto\n      have c: \"c \\<noteq> 0\" using \\<beta>0 unfolding c_def .\n      from i2 ik have 3: \"Suc i \\<ge> 3\" \"Suc i \\<le> Suc k\" by auto\n      from pmod[OF 3]\n      have pm: \"smult c (F (Suc i)) = pseudo_mod (F (i - 1)) (F i)\" unfolding c_def by simp\n      from beta[OF 3, folded c_def] obtain d where cd: \"c = ff d\" by auto\n      with c have d: \"d \\<noteq> 0\" by auto\n      from pm[unfolded cd M] FH[of \"Suc i\"]\n      have \"ffp (smult d (H (Suc i))) = ffp M\" by auto\n      hence pm: \"smult d (H (Suc i)) = M\" by (rule map_poly_hom.injectivity)\n      from ik F0[of i] i2 FH[of i] have Hi0: \"H i \\<noteq> 0\" by auto\n      from pseudo_mod[OF this, of \"H (i - 1)\", folded M_def]\n      obtain c Q where c: \"c \\<noteq> 0\" and \"smult c (H (i - 1)) = H i * Q + M\" by auto\n      from this[folded pm] have \"smult c (H (i - 1)) = Q * H i + smult d (H (Suc i))\" by simp\n      from gcd_add_mult[of \"H i\" Q \"smult d (H (Suc i))\", folded this]\n      have \"gcd (H i) (smult c (H (i - 1))) = gcd (H i) (smult d (H (Suc i)))\" .\n      with gcd_smult_ex[OF c, of \"H (i - 1)\" \"H i\"] obtain e where\n        e: \"e \\<noteq> 0\" and \"gcd (H i) (smult d (H (Suc i))) = smult e (gcd (H i) (H (i - 1)))\"\n        unfolding gcd.commute[of \"H i\"] by auto\n      with gcd_smult_ex[OF d, of \"H (Suc i)\" \"H i\"] obtain c where\n        c: \"c \\<noteq> 0\" and \"smult c (gcd (H i) (H (Suc i))) = smult e (gcd (H (i - 1)) (H i))\"\n        unfolding gcd.commute[of \"H i\"] by auto\n      from arg_cong[OF this(2), of \"smult b\"] arg_cong[OF IH, of \"smult e\"]\n      have \"smult (e * a) (gcd G1 G2) = smult (b * c) (gcd (H i) (H (Suc i)))\" unfolding smult_smult\n        by (simp add: ac_simps)\n      moreover have \"e * a \\<noteq> 0\" \"b * c \\<noteq> 0\" using a b c e by auto\n      ultimately show ?thesis by blast\n    qed\n  qed\n  from this[OF k0 le_refl, unfolded border]\n  obtain a b where \"a \\<noteq> 0\" \"b \\<noteq> 0\" and \"smult a (gcd G1 G2) = smult b (normalize Gk)\" by auto\n  thus ?thesis by auto\nqed\n\n\nlemma gcd_impl_primitive: assumes \"primitive_part G1 = G1\" and \"primitive_part G2 = G2\"\nshows \"gcd_impl_primitive G1 G2 = gcd G1 G2\"\nproof -\n  let ?pp = primitive_part\n  let ?c = \"content\"\n  let ?n = normalize\n  from F2 F0[of 2] k2 have G2: \"G2 \\<noteq> 0\" by auto\n  obtain Gk hk where sub: \"subresultant_prs G1 G2 = (Gk, hk)\" by force\n  have impl: \"gcd_impl_primitive G1 G2 = ?n (?pp Gk)\" unfolding gcd_impl_primitive_def sub by auto\n  from subresultant_prs_gcd[OF sub]\n  obtain a b where a: \"a \\<noteq> 0\" and b: \"b \\<noteq> 0\" and id: \"smult a (gcd G1 G2) = smult b (?n Gk)\"\n    by auto\n  define c where \"c = unit_factor (gcd G1 G2)\"\n  define d where \"d = smult (unit_factor a) c\"\n  from G2 have c: \"is_unit c\" unfolding c_def by auto\n  from arg_cong[OF id, of ?pp, unfolded primitive_part_smult primitive_part_gcd assms\n     primitive_part_normalize c_def[symmetric]]\n  have id: \"d * gcd G1 G2 = smult (unit_factor b) (?n (?pp Gk))\" unfolding d_def by simp\n  have d: \"is_unit d\" unfolding d_def using c a\n    by (simp add: is_unit_smult_iff)\n  from is_unitE[OF d]\n  obtain e where e: \"is_unit e\" and de: \"d * e = 1\" by metis\n  define a where \"a = smult (unit_factor b) e\"\n  from arg_cong[OF id, of \"\\<lambda> x. e * x\"]\n  have \"(d * e) * gcd G1 G2 = a * (?n (?pp Gk))\" by (simp add: ac_simps a_def)\n  hence id: \"gcd G1 G2 = a * (?n (?pp Gk))\" using de by simp\n  have a: \"is_unit a\" unfolding a_def using b e\n    by (simp add: is_unit_smult_iff)\n  define b where \"b = unit_factor (?pp Gk)\"\n  have \"Gk \\<noteq> 0\" using subresultant_prs[OF div_exp_sound sub] F0[OF k0] by auto\n  hence b: \"is_unit b\" unfolding b_def by auto\n  from is_unitE[OF b]\n  obtain c where c: \"is_unit c\" and bc: \"b * c = 1\" by metis\n  obtain d where d: \"is_unit d\" and dac: \"d = a * c\" using c a by auto\n  have \"gcd G1 G2 = d * (b * ?n (?pp Gk))\"\n    unfolding id dac using bc by (simp add: ac_simps)\n  also have \"b * ?n (?pp Gk) = ?pp Gk\" unfolding b_def by simp\n  finally have \"gcd G1 G2 = d * ?pp Gk\" by simp\n  from arg_cong[OF this, of ?n]\n  have \"gcd G1 G2 = ?n (d * ?pp Gk)\" by simp\n  also have \"\\<dots> = ?n (?pp Gk)\" using d\n    unfolding normalize_mult by (simp add: is_unit_normalize)\n  finally show ?thesis unfolding impl ..\nqed\nend\nend\n\ncontext div_exp_sound_gcd\nbegin\n\nlemma gcd_impl_main: assumes len: \"length (coeffs G1) \\<ge> length (coeffs G2)\"\n  shows \"gcd_impl_main G1 G2 = gcd G1 G2\"\nproof (cases \"G1 = 0\")\n  case G1: False\n  show ?thesis\n  proof (cases \"G2 = 0\")\n    case G2: False\n    let ?pp = \"primitive_part\"\n    from G2 have G2: \"?pp G2 \\<noteq> 0\" and id: \"(G2 = 0) = False\" by auto\n    from len have len: \"length (coeffs (?pp G1)) \\<ge> length (coeffs (?pp G2))\" by simp\n    from enter_subresultant_prs[OF len G2] obtain F n d f k b\n      where \"subresultant_prs_locale2 F n d f k b (?pp G1) (?pp G2)\" by auto\n    interpret subresultant_prs_locale2 F n d f k b \"?pp G1\" \"?pp G2\" by fact\n    interpret subresultant_prs_gcd F n d f k b \"?pp G1\" \"?pp G2\" ..\n    show ?thesis unfolding gcd_impl_main_def gcd_poly_decompose[of G1] id if_False using G1\n      by (subst gcd_impl_primitive, auto intro: div_exp_sound_axioms)\n  next\n    case True\n    thus ?thesis unfolding gcd_impl_main_def by simp\n  qed\nnext\n  case True\n  with len have \"G2 = 0\" by auto\n  thus ?thesis using True unfolding gcd_impl_main_def by simp\nqed\n\n\n\n\n\ntext \\<open>The implementation also reveals an important connection between resultant and gcd.\\<close>\n\nlemma resultant_0_gcd: \"resultant (f :: 'a poly) g = 0 \\<longleftrightarrow> degree (gcd f g) \\<noteq> 0\"\nproof -\n  {\n    fix f g :: \"'a poly\"\n    assume len: \"length (coeffs f) \\<ge> length (coeffs g)\"\n    {\n      assume g: \"g \\<noteq> 0\"\n      with len have f: \"f \\<noteq> 0\" by auto\n      let ?f = \"primitive_part f\"\n      let ?g = \"primitive_part g\"\n      let ?c = \"content\"\n      from len have len: \"length (coeffs ?f) \\<ge> length (coeffs ?g)\" by simp\n      obtain Gk hk where sub: \"subresultant_prs ?f ?g = (Gk,hk)\" by force\n      have cf: \"?c f \\<noteq> 0\" and cg: \"?c g \\<noteq> 0\" using f g by auto\n      {\n        from g have \"?g \\<noteq> 0\" by auto\n        from enter_subresultant_prs[OF len this] obtain F n d f k b\n          where \"subresultant_prs_locale2 F n d f k b ?f ?g\" by auto\n        interpret subresultant_prs_locale2 F n d f k b ?f ?g by fact\n        from subresultant_prs[OF div_exp_sound_axioms sub] have \"h k = ff hk\" by auto\n        with h0[OF le_refl] have \"hk \\<noteq> 0\" by auto\n      } note hk0 = this\n      have \"resultant f g = 0 \\<longleftrightarrow> resultant (smult (?c f) ?f) (smult (?c g) ?g) = 0\" by simp\n      also have \"\\<dots> \\<longleftrightarrow> resultant ?f ?g = 0\" unfolding resultant_smult_left[OF cf] resultant_smult_right[OF cg]\n        using cf cg by auto\n      also have \"\\<dots> \\<longleftrightarrow> resultant_impl_main ?f ?g = 0\" \n        unfolding resultant_impl[symmetric] resultant_impl_def resultant_impl_main_def \n        using len by auto\n      also have \"\\<dots> \\<longleftrightarrow> (degree Gk \\<noteq> 0)\"\n        unfolding resultant_impl_main_def sub split using g hk0 by auto\n      also have \"degree Gk = degree (gcd_impl_primitive ?f ?g)\"\n        unfolding gcd_impl_primitive_def sub by simp\n      also have \"\\<dots> = degree (gcd_impl_main f g)\"\n        unfolding gcd_impl_main_def using f g by auto\n      also have \"\\<dots> = degree (gcd f g)\" unfolding gcd_impl[symmetric] gcd_impl_def using len by auto\n      finally have \"(resultant f g = 0) = (degree (gcd f g) \\<noteq> 0)\" .\n    }\n    moreover\n    {\n      assume g: \"g = 0\" and f: \"degree f \\<noteq> 0\"\n      have \"(resultant f g = 0) = (degree (gcd f g) \\<noteq> 0)\"\n        unfolding g using f by auto\n    }\n    moreover\n    {\n      assume g: \"g = 0\" and f: \"degree f = 0\"\n      have \"(resultant f g = 0) = (degree (gcd f g) \\<noteq> 0)\"\n        unfolding g using f by (auto simp: resultant_def sylvester_mat_def sylvester_mat_sub_def)\n    }\n    ultimately have \"(resultant f g = 0) = (degree (gcd f g) \\<noteq> 0)\" by blast\n  } note main = this\n  show ?thesis\n  proof (cases \"length (coeffs f) \\<ge> length (coeffs g)\")\n    case True\n    from main[OF True] show ?thesis .\n  next\n    case False\n    hence \"length (coeffs g) \\<ge> length (coeffs f)\" by auto\n    from main[OF this] show ?thesis\n      unfolding gcd.commute[of g f] resultant_swap[of g f] by (simp split: if_splits)\n  qed\nqed\n\n\nsubsection \\<open>Code Equations\\<close>\n\ndefinition \"gcd_impl_rec = subresultant_prs_main_impl fst\"\ndefinition \"gcd_impl_start = subresultant_prs_impl fst\"\n\nlemma gcd_impl_rec_code:\n  \"gcd_impl_rec Gi_1 Gi ni_1 d1_1 hi_2 = (\n    let pmod = pseudo_mod Gi_1 Gi\n     in\n     if pmod = 0 then Gi\n        else let\n           ni = degree Gi;\n           d1 = ni_1 - ni;\n           gi_1 = lead_coeff Gi_1;\n           hi_1 = (if d1_1 = 1 then gi_1 else div_exp gi_1 hi_2 d1_1);\n           divisor = if d1 = 1 then gi_1 * hi_1 else if even d1 then - gi_1 * hi_1 ^ d1 else gi_1 * hi_1 ^ d1;\n           Gi_p1 = sdiv_poly pmod divisor\n       in gcd_impl_rec Gi Gi_p1 ni d1 hi_1)\"\n  unfolding gcd_impl_rec_def subresultant_prs_main_impl.simps[of _ Gi_1] split Let_def\n  unfolding gcd_impl_rec_def[symmetric]\n  by (rule if_cong, auto)\n\nlemma gcd_impl_start_code:\n  \"gcd_impl_start G1 G2 =\n     (let pmod = pseudo_mod G1 G2\n         in if pmod = 0 then G2\n            else let\n                 n2 = degree G2;\n                 n1 = degree G1;\n                 d1 = n1 - n2;\n                 G3 = if even d1 then - pmod else pmod;\n                 pmod = pseudo_mod G2 G3\n                 in if pmod = 0\n                    then G3\n                    else let\n                           g2 = lead_coeff G2;\n                           n3 = degree G3;\n                           h2 = (if d1 = 1 then g2 else g2 ^ d1);\n                           d2 = n2 - n3;\n                           divisor = (if d2 = 1 then g2 * h2 else if even d2 then - g2 * h2 ^ d2 else g2 * h2 ^ d2);\n                           G4 = sdiv_poly pmod divisor\n                         in gcd_impl_rec G3 G4 n3 d2 h2)\"\nproof -\n  obtain d1 where d1: \"degree G1 - degree G2 = d1\" by auto\n  have id1: \"(if even d1 then - pmod else pmod) = (-1)^ (d1 + 1) * (pmod :: 'a poly)\" for pmod by simp\n  show ?thesis\n    unfolding gcd_impl_start_def subresultant_prs_impl_def gcd_impl_rec_def[symmetric] Let_def split\n    unfolding d1\n    unfolding id1\n    by (rule if_cong, auto)\nqed\n\nlemma gcd_impl_main_code:\n  \"gcd_impl_main G1 G2 = (if G1 = 0 then 0 else if G2 = 0 then normalize G1 else\n    let c1 = content G1;\n      c2 = content G2;\n      p1 = map_poly (\\<lambda> x. x div c1) G1;\n      p2 = map_poly (\\<lambda> x. x div c2) G2\n     in smult (gcd c1 c2) (normalize (primitive_part (gcd_impl_start p1 p2))))\"\n  unfolding gcd_impl_main_def Let_def primitive_part_def gcd_impl_start_def gcd_impl_primitive_def\n    subresultant_prs_impl by simp\n\nlemmas gcd_code_lemmas = \n  gcd_impl_main_code\n  gcd_impl_start_code\n  gcd_impl_rec_code\n  gcd_impl_def\n\ncorollary gcd_via_subresultant: \"gcd = gcd_impl\" by simp\nend\n\nglobal_interpretation div_exp_Lazard_gcd: div_exp_sound_gcd \"dichotomous_Lazard :: 'a :: {semiring_gcd_mult_normalize,factorial_ring_gcd} \\<Rightarrow> _\" \n  defines \n    gcd_impl_Lazard = div_exp_Lazard_gcd.gcd_impl and\n    gcd_impl_main_Lazard = div_exp_Lazard_gcd.gcd_impl_main and\n    gcd_impl_start_Lazard = div_exp_Lazard_gcd.gcd_impl_start and\n    gcd_impl_rec_Lazard = div_exp_Lazard_gcd.gcd_impl_rec\n  by (simp add: Subresultant.dichotomous_Lazard div_exp_sound_gcd_def)\n\ndeclare div_exp_Lazard_gcd.gcd_code_lemmas[code]\n\nlemmas resultant_0_gcd = div_exp_Lazard_gcd.resultant_0_gcd\n\nthm div_exp_Lazard_gcd.gcd_via_subresultant\n\ntext \\<open>Note that we did not activate @{thm div_exp_Lazard_gcd.gcd_via_subresultant} as code-equation, since according to our experiments,\n  the subresultant-gcd algorithm is not always more efficient than the currently active equation.\n  In particular, on @{typ \"int poly\"} @{const gcd_impl_Lazard} performs worse, but on multi-variate polynomials,\n  e.g., @{typ \"int poly poly poly\"}, @{const gcd_impl_Lazard} is preferable.\\<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/Subresultants/Subresultant_Gcd.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.874077222043951, "lm_q2_score": 0.8198933293122506, "lm_q1q2_score": 0.7166500836576183}}
{"text": "(*  Title:      ZF/UNITY/Monotonicity.thy\n    Author:     Sidi O Ehmety, Cambridge University Computer Laboratory\n    Copyright   2002  University of Cambridge\n\nMonotonicity of an operator (meta-function) with respect to arbitrary\nset relations.\n*)\n\nsection{*Monotonicity of an Operator WRT a Relation*}\n\ntheory Monotonicity imports GenPrefix MultisetSum\nbegin\n\ndefinition\n  mono1 :: \"[i, i, i, i, i=>i] => o\"  where\n  \"mono1(A, r, B, s, f) ==\n    (\\<forall>x \\<in> A. \\<forall>y \\<in> A. <x,y> \\<in> r \\<longrightarrow> <f(x), f(y)> \\<in> s) & (\\<forall>x \\<in> A. f(x) \\<in> B)\"\n\n  (* monotonicity of a 2-place meta-function f *)\n\ndefinition\n  mono2 :: \"[i, i, i, i, i, i, [i,i]=>i] => o\"  where\n  \"mono2(A, r, B, s, C, t, f) == \n    (\\<forall>x \\<in> A. \\<forall>y \\<in> A. \\<forall>u \\<in> B. \\<forall>v \\<in> B.\n              <x,y> \\<in> r & <u,v> \\<in> s \\<longrightarrow> <f(x,u), f(y,v)> \\<in> t) &\n    (\\<forall>x \\<in> A. \\<forall>y \\<in> B. f(x,y) \\<in> C)\"\n\n (* Internalized relations on sets and multisets *)\n\ndefinition\n  SetLe :: \"i =>i\"  where\n  \"SetLe(A) == {<x,y> \\<in> Pow(A)*Pow(A). x \\<subseteq> y}\"\n\ndefinition\n  MultLe :: \"[i,i] =>i\"  where\n  \"MultLe(A, r) == multirel(A, r - id(A)) \\<union> id(Mult(A))\"\n\n\nlemma mono1D: \n  \"[| mono1(A, r, B, s, f); <x, y> \\<in> r; x \\<in> A; y \\<in> A |] ==> <f(x), f(y)> \\<in> s\"\nby (unfold mono1_def, auto)\n\nlemma mono2D: \n     \"[| mono2(A, r, B, s, C, t, f);  \n         <x, y> \\<in> r; <u,v> \\<in> s; x \\<in> A; y \\<in> A; u \\<in> B; v \\<in> B |] \n      ==> <f(x, u), f(y,v)> \\<in> t\"\nby (unfold mono2_def, auto)\n\n\n(** Monotonicity of take **)\n\nlemma take_mono_left_lemma:\n     \"[| i \\<le> j; xs \\<in> list(A); i \\<in> nat; j \\<in> nat |] \n      ==> <take(i, xs), take(j, xs)> \\<in> prefix(A)\"\napply (case_tac \"length (xs) \\<le> i\")\n apply (subgoal_tac \"length (xs) \\<le> j\")\n  apply (simp)\n apply (blast intro: le_trans)\napply (drule not_lt_imp_le, auto)\napply (case_tac \"length (xs) \\<le> j\")\n apply (auto simp add: take_prefix)\napply (drule not_lt_imp_le, auto)\napply (drule_tac m = i in less_imp_succ_add, auto)\napply (subgoal_tac \"i #+ k \\<le> length (xs) \")\n apply (simp add: take_add prefix_iff take_type drop_type)\napply (blast intro: leI)\ndone\n\nlemma take_mono_left:\n     \"[| i \\<le> j; xs \\<in> list(A); j \\<in> nat |]\n      ==> <take(i, xs), take(j, xs)> \\<in> prefix(A)\"\nby (blast intro: le_in_nat take_mono_left_lemma) \n\nlemma take_mono_right:\n     \"[| <xs,ys> \\<in> prefix(A); i \\<in> nat |] \n      ==> <take(i, xs), take(i, ys)> \\<in> prefix(A)\"\nby (auto simp add: prefix_iff)\n\nlemma take_mono:\n     \"[| i \\<le> j; <xs, ys> \\<in> prefix(A); j \\<in> nat |]\n      ==> <take(i, xs), take(j, ys)> \\<in> prefix(A)\"\napply (rule_tac b = \"take (j, xs) \" in prefix_trans)\napply (auto dest: prefix_type [THEN subsetD] intro: take_mono_left take_mono_right)\ndone\n\nlemma mono_take [iff]:\n     \"mono2(nat, Le, list(A), prefix(A), list(A), prefix(A), take)\"\napply (unfold mono2_def Le_def, auto)\napply (blast intro: take_mono)\ndone\n\n(** Monotonicity of length **)\n\nlemmas length_mono = prefix_length_le\n\nlemma mono_length [iff]:\n     \"mono1(list(A), prefix(A), nat, Le, length)\"\napply (unfold mono1_def)\napply (auto dest: prefix_length_le simp add: Le_def)\ndone\n\n(** Monotonicity of \\<union> **)\n\nlemma mono_Un [iff]: \n     \"mono2(Pow(A), SetLe(A), Pow(A), SetLe(A), Pow(A), SetLe(A), op Un)\"\nby (unfold mono2_def SetLe_def, auto)\n\n(* Monotonicity of multiset union *)\n\nlemma mono_munion [iff]: \n     \"mono2(Mult(A), MultLe(A,r), Mult(A), MultLe(A, r), Mult(A), MultLe(A, r), munion)\"\napply (unfold mono2_def MultLe_def)\napply (auto simp add: Mult_iff_multiset)\napply (blast intro: munion_multirel_mono munion_multirel_mono1 munion_multirel_mono2 multiset_into_Mult)+\ndone\n\nlemma mono_succ [iff]: \"mono1(nat, Le, nat, Le, succ)\"\nby (unfold mono1_def Le_def, auto)\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/ZF/UNITY/Monotonicity.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361604769413, "lm_q2_score": 0.7853085758631159, "lm_q1q2_score": 0.7165439417501562}}
{"text": "theory Exercise5p2\nimports Main\nbegin\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  let ?len_ys = \"length xs div 2\"\n  assume 1: \"length xs mod 2 = 0\"\n  then obtain ys where 2: \"ys = take ?len_ys xs\" by blast\n  then obtain zs where    \"zs = drop ?len_ys xs\" by blast\n  then have \"xs = ys @ zs \\<and> length ys = length zs\" \n    using 1 2 add_diff_cancel_right' append_take_drop_id distrib_right dvd_mult_div_cancel\n          even_iff_mod_2_eq_zero length_append length_drop mult.left_neutral one_add_one by auto\n  thus ?thesis by blast\nnext\n  let ?len_ys = \"length xs div 2 + 1\"\n  assume 1: \"length xs mod 2 \\<noteq> 0\"\n  then obtain ys where 2: \"ys = take ?len_ys xs\" by blast\n  then obtain zs where    \"zs = drop ?len_ys xs\" by blast\n  then have \"xs = ys @ zs \\<and> length ys = length zs + 1\" using 1 2 \n    by (smt add.commute add_diff_cancel_left' append_take_drop_id drop_drop even_iff_mod_2_eq_zero\n        length_append length_drop mult_2 odd_two_times_div_two_succ)\n  thus ?thesis by blast\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/Exercise5p2.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8976952893703477, "lm_q2_score": 0.7981867753392728, "lm_q1q2_score": 0.7165285082597732}}
{"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_SSortSorts\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 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 ssortminimum1 :: \"Nat => Nat list => Nat\" where\n  \"ssortminimum1 x (nil2) = x\"\n| \"ssortminimum1 x (cons2 y1 ys1) =\n     (if le y1 x then ssortminimum1 y1 ys1 else ssortminimum1 x ys1)\"\n\nfun deleteBy :: \"('a => ('a => bool)) => 'a => 'a list =>\n                 'a list\" where\n  \"deleteBy x y (nil2) = nil2\"\n| \"deleteBy x y (cons2 y2 ys) =\n     (if (x y) y2 then ys else cons2 y2 (deleteBy x y ys))\"\n\n(*fun did not finish the proof*)\nfunction ssort :: \"Nat list => Nat list\" where\n  \"ssort (nil2) = nil2\"\n| \"ssort (cons2 y ys) =\n     (let m :: Nat = ssortminimum1 y ys\n     in cons2\n          m\n          (ssort\n             (deleteBy\n                (% (z :: Nat) => % (x2 :: Nat) => (z = x2)) m (cons2 y ys))))\"\n  by pat_completeness auto\n\ntheorem property0 :\n  \"ordered (ssort 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_SSortSorts.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297941266014, "lm_q2_score": 0.7956580976404296, "lm_q1q2_score": 0.7165138228632993}}
{"text": "subsection \\<open>Resultants of Multivariate Polynomials\\<close>\n\ntext \\<open>We utilize the conversion of multivariate polynomials into univariate polynomials\n  for the definition of the resultant of multivariate polynomials via\n  the resultant for univariate polynomials. In this way, we can use the algorithm\n  to efficiently compute resultants for the multivariate case.\\<close>\n\ntheory Multivariate_Resultant\n  imports \n    Poly_Connection\n    Algebraic_Numbers.Resultant\n    Subresultants.Subresultant\n    MPoly_Divide_Code\n    MPoly_Container\nbegin\n\nhide_const (open) \n  MPoly_Type.degree\n  MPoly_Type.coeff\n  Symmetric_Polynomials.lead_coeff\n\nlemma det_sylvester_matrix_higher_degree: \n  \"det (sylvester_mat_sub (degree f + n) (degree g) f g)\n  = det (sylvester_mat_sub (degree f) (degree g) f g) * (lead_coeff g * (-1)^(degree g))^n\"\nproof (induct n)\n  case (Suc n)\n  let ?A = \"sylvester_mat_sub (degree f + Suc n) (degree g) f g\" \n  let ?d = \"degree f + Suc n + degree g\" \n  define h where \"h i = ?A $$ (i,0) * cofactor ?A i 0\" for i\n  have mult_left_zero: \"x = 0 \\<Longrightarrow> x * y = 0\" for x y :: 'a by auto\n  have \"det ?A = (\\<Sum>i<?d. h i)\" \n    unfolding h_def\n    by (rule laplace_expansion_column[OF sylvester_mat_sub_carrier, of 0], force)\n  also have \"\\<dots> = sum h ({degree g} \\<union> ({..<?d} - {degree g}))\" \n    by (rule sum.cong, auto)\n  also have \"\\<dots> = sum h {degree g} + sum h ({..<?d} - {degree g})\" \n    by (rule sum.union_disjoint, auto)\n  also have \"sum h ({..<?d} - {degree g}) = 0\" \n    unfolding h_def\n    by (intro sum.neutral ballI mult_left_zero, auto simp: sylvester_mat_sub_def coeff_eq_0)\n  also have \"sum h {degree g} = h (degree g)\" by simp\n  also have \"\\<dots> = lead_coeff g * cofactor ?A (degree g) 0\" unfolding h_def\n    by (rule arg_cong[of _ _ \"\\<lambda> x. x * _\"], simp add: sylvester_mat_sub_def)\n  also have \"cofactor ?A (degree g) 0 = (-1)^(degree g) * det (sylvester_mat_sub (degree f + n) (degree g) f g)\" \n    unfolding cofactor_def\n  proof (intro arg_cong2[of _ _ _ _ \"\\<lambda> x y. (-1)^x * det y\"], force)\n    show \"mat_delete ?A (degree g) 0 = sylvester_mat_sub (degree f + n) (degree g) f g\" \n      unfolding sylvester_mat_sub_def\n      by (intro eq_matI, auto simp: mat_delete_def coeff_eq_0)\n  qed\n  finally show ?case unfolding Suc by simp\nqed simp\n\ntext \\<open>The conversion of multivariate into univariate polynomials permits us to define resultants in the multivariate\n  setting. Since in our application one of the polynomials is already univariate, we use a non-symmetric definition\n  where only one of the input polynomials is multivariate.\\<close>\ndefinition resultant_mpoly_poly :: \"nat \\<Rightarrow> 'a :: comm_ring_1 mpoly \\<Rightarrow> 'a poly \\<Rightarrow> 'a mpoly\" where\n  \"resultant_mpoly_poly x p q = resultant (mpoly_to_mpoly_poly x p) (map_poly Const q)\"\n\ntext \\<open>This lemma tells us that there is only a minor difference between computing the multivariate resultant and then\n  plugging in values, or first inserting values and then evaluate the univariate resultant.\\<close>\nlemma insertion_resultant_mpoly_poly: \"insertion \\<alpha> (resultant_mpoly_poly x p q) = resultant (partial_insertion \\<alpha> x p) q * \n  (lead_coeff q * (-1)^ degree q)^(degree (mpoly_to_mpoly_poly x p) - degree (partial_insertion \\<alpha> x p))\" \nproof -\n  let ?pa = \"partial_insertion \\<alpha> x\" \n  let ?a = \"insertion \\<alpha>\" \n  let ?q = \"map_poly Const q\" \n  let ?m = \"mpoly_to_mpoly_poly x\" \n  interpret a: comm_ring_hom ?a by (rule comm_ring_hom_insertion)\n  define m where \"m = degree (?m p) - degree (?pa p)\" \n  from degree_partial_insertion_le_mpoly[of \\<alpha> x p] have deg: \"degree (?m p) = degree (?pa p) + m\" unfolding m_def by simp\n  define k where \"k = degree (?pa p) + m\" \n  define l where \"l = degree q\" \n  have \"resultant (?pa p) q = det (sylvester_mat_sub (degree (?pa p)) (degree q) (?pa p) q)\" \n    unfolding resultant_def sylvester_mat_def by simp\n  have \"?a (resultant_mpoly_poly x p q) = ?a (det (sylvester_mat_sub (degree (?pa p) + m) (degree q) (?m p) ?q))\" \n    unfolding resultant_mpoly_poly_def resultant_def sylvester_mat_def degree_map_poly_Const deg ..\n  also have \"\\<dots> =\n    det (a.mat_hom (sylvester_mat_sub (degree (?pa p) + m) (degree q) (?m p) ?q))\" \n    unfolding a.hom_det ..\n  also have \"a.mat_hom (sylvester_mat_sub (degree (?pa p) + m) (degree q) (?m p) ?q)\n    = sylvester_mat_sub (degree (?pa p) + m) (degree q) (?pa p) q\" \n    unfolding k_def[symmetric] l_def[symmetric] \n    by (intro eq_matI, auto simp: sylvester_mat_sub_def coeff_map_poly)\n  also have \"det \\<dots> = det (sylvester_mat_sub (degree (?pa p)) (degree q) (?pa p) q) * (lead_coeff q * (- 1) ^ degree q) ^ m\" \n    by (subst det_sylvester_matrix_higher_degree, simp)\n  also have \"det (sylvester_mat_sub (degree (?pa p)) (degree q) (?pa p) q) = resultant (?pa p) q\" \n    unfolding resultant_def sylvester_mat_def by simp\n  finally show ?thesis unfolding m_def by auto\nqed\n\nlemma insertion_resultant_mpoly_poly_zero: fixes q :: \"'a :: idom poly\" \n  assumes q: \"q \\<noteq> 0\" \n  shows \"insertion \\<alpha> (resultant_mpoly_poly x p q) = 0 \\<longleftrightarrow> resultant (partial_insertion \\<alpha> x p) q = 0\" \n  unfolding insertion_resultant_mpoly_poly using q by auto\n\nlemma vars_resultant: \"vars (resultant p q) \\<subseteq> \\<Union> (vars ` (range (coeff p) \\<union> range (coeff q)))\" \n  unfolding resultant_def det_def sylvester_mat_def sylvester_mat_sub_def \n  apply simp\n  apply (rule order.trans[OF vars_setsum]) \n  subgoal using finite_permutations by blast\n  apply (rule UN_least)\n  apply (rule order.trans[OF vars_mult]) \n  apply simp\n  apply (rule order.trans[OF vars_prod])\n  apply (rule UN_least)\n  by auto\n\ntext \\<open>By taking the resultant, one variable is deleted.\\<close>\nlemma vars_resultant_mpoly_poly: \"vars (resultant_mpoly_poly x p q) \\<subseteq> vars p - {x}\" \nproof\n  fix y\n  assume \"y \\<in> vars (resultant_mpoly_poly x p q)\" \n  from set_mp[OF vars_resultant this[unfolded resultant_mpoly_poly_def]] obtain i \n    where \"y \\<in> vars (coeff (mpoly_to_mpoly_poly x p) i) \\<or> y \\<in> vars (coeff (map_poly Const q) i)\" \n    by auto\n  moreover have \"vars (coeff (map_poly Const q) i) = {}\" \n    by (subst coeff_map_poly, auto)\n  ultimately have \"y \\<in> vars (coeff (mpoly_to_mpoly_poly x p) i)\" by auto\n  thus \"y \\<in> More_MPoly_Type.vars p - {x}\" using vars_coeff_mpoly_to_mpoly_poly by blast\nqed\n\ntext \\<open>For resultants, we manually have to select the implementation that \n  works on integral domains, because there is no factorial ring instance for @{typ \"int mpoly\"}.\\<close>\n\nlemma resultant_mpoly_poly_code[code]:\n  \"resultant_mpoly_poly x p q = resultant_impl_basic (mpoly_to_mpoly_poly x p) (map_poly Const q)\"\n  unfolding resultant_mpoly_poly_def div_exp_basic.resultant_impl by simp\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/Factor_Algebraic_Polynomial/Multivariate_Resultant.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8840392939666335, "lm_q2_score": 0.8104789109591832, "lm_q1q2_score": 0.7164952042192023}}
{"text": "\\<^marker>\\<open>creator \"Alexander Krauss\"\\<close>\n\\<^marker>\\<open>creator \"Kevin Kappelmann\"\\<close>\n\\<^marker>\\<open>creator \"Larry Paulson\"\\<close>\nsection \\<open>Set Difference\\<close>\ntheory Set_Difference\n  imports Union_Intersection\nbegin\n\ndefinition \"diff A B \\<equiv> {x \\<in> A | x \\<notin> B}\"\n\nbundle hotg_diff_syntax begin notation diff (infixl \"\\<setminus>\" 65) end\nbundle no_hotg_diff_syntax begin no_notation diff (infixl \"\\<setminus>\" 65) end\nunbundle hotg_diff_syntax\n\nlemma mem_diff_iff [iff]: \"a \\<in> A \\<setminus> B \\<longleftrightarrow> (a \\<in> A \\<and> a \\<notin> B)\"\n  unfolding diff_def by auto\n\nlemma mem_if_mem_diff: \"a \\<in> A \\<setminus> B \\<Longrightarrow> a \\<in> A\" by simp\n\nlemma not_mem_if_mem_diff: \"a \\<in> A \\<setminus> B \\<Longrightarrow> a \\<notin> B\" by simp\n\nlemma diff_subset [iff]: \"A \\<setminus> B \\<subseteq> A\" by blast\n\nlemma subset_diff_if_inter_eq_empty_if_subset:\n  \"C \\<subseteq> A \\<Longrightarrow> C \\<inter> B = {} \\<Longrightarrow> C \\<subseteq> A \\<setminus> B\"\n  by blast\n\nlemma diff_self_eq [simp]: \"A \\<setminus> A = {}\" by blast\n\nlemma diff_eq_left_if_inter_eq_empty: \"A \\<inter> B = {} \\<Longrightarrow> A \\<setminus> B = A\" by auto\n\nlemma empty_diff_eq [simp]: \"{} \\<setminus> A = {}\" by blast\n\nlemma diff_empty_eq [simp]: \"A \\<setminus> {} = A\"\n  by (rule eq_if_subset_if_subset) auto\n\nlemma diff_eq_empty_iff_subset: \"A \\<setminus> B = {} \\<longleftrightarrow> A \\<subseteq> B\"\n  unfolding subset_def by auto\n\nlemma inter_diff_eq_empty [simp]: \"A \\<inter> (B \\<setminus> A) = {}\" by blast\n\nlemma bin_union_diff_eq [simp]: \"A \\<union> (B \\<setminus> A) = A \\<union> B\"\n  by (rule eq_if_subset_if_subset) auto\n\nlemma bin_union_diff_eq_if_subset: \"A \\<subseteq> B \\<Longrightarrow> A \\<union> (B \\<setminus> A) = B\"\n  by (rule eq_if_subset_if_subset) auto\n\nlemma subset_bin_union_diff: \"A \\<subseteq> B \\<union> (A \\<setminus> B)\"\n  by blast\n\nlemma diff_diff_eq_if_subset_if_subset: \"A \\<subseteq> B \\<Longrightarrow> B \\<subseteq> C \\<Longrightarrow> B \\<setminus> (C \\<setminus> A) = A\"\n  by auto\n\nlemma bin_union_diff_diff_eq [simp]: \"(A \\<union> B) \\<setminus> (B \\<setminus> A) = A\"\n  by (rule eq_if_subset_if_subset) auto\n\nlemma diff_bin_union_eq_bin_inter_diff: \"A \\<setminus> (B \\<union> C) = (A \\<setminus> B) \\<inter> (A \\<setminus> C)\"\n  by (rule eq_if_subset_if_subset) auto\n\nlemma diff_bin_inter_eq_bin_union_diff: \"A \\<setminus> (B \\<inter> C) = (A \\<setminus> B) \\<union> (A \\<setminus> C)\"\n  by (rule eq_if_subset_if_subset) auto\n\nlemma bin_union_diff_eq_bin_union_diff: \"(A \\<union> B) \\<setminus> C = (A \\<setminus> C) \\<union> (B \\<setminus> C)\"\n  by (rule eq_if_subset_if_subset) auto\n\nlemma bin_union_diff_eq_diff_right [simp]: \"(A \\<union> B) \\<setminus> B = A \\<setminus> B\"\n  using bin_union_diff_eq_bin_union_diff by auto\n\nlemma bin_union_diff_eq_diff_left [simp]: \"(B \\<union> A) \\<setminus> B = A \\<setminus> B\"\n  using bin_union_diff_eq_bin_union_diff by auto\n\nlemma bin_inter_diff_eq_bin_inter_diff: \"(A \\<inter> B) \\<setminus> C = A \\<inter> (B \\<setminus> C)\"\n  by (rule eq_if_subset_if_subset) auto\n\nlemma diff_bin_inter_eq_diff_if_subset: \"C \\<subseteq> A \\<Longrightarrow> ((A \\<setminus> B) \\<inter> C) = (C \\<setminus> B)\"\n  by auto\n\nlemma diff_bin_inter_distrib_right: \"C \\<inter> (A \\<setminus> B) = (C \\<inter> A) \\<setminus> (C \\<inter> B)\"\n  by (rule eq_if_subset_if_subset) auto\n\nlemma diff_bin_inter_distrib_left: \"(A \\<setminus> B) \\<inter> C = (A \\<inter> C) \\<setminus> (B \\<inter> C)\"\n  by (rule eq_if_subset_if_subset) auto\n\nlemma diff_idx_union_eq_idx_union:\n  assumes \"I \\<noteq> {}\"\n  shows \"B \\<setminus> (\\<Union>i\\<in> I. A i) = (\\<Inter>i\\<in> I. B \\<setminus> A i)\"\n  using assms by (intro eq_if_subset_if_subset) auto\n\nlemma diff_idx_inter_eq_idx_inter:\n  assumes \"I \\<noteq> {}\"\n  shows \"B \\<setminus> (\\<Inter>i\\<in> I. A i) = (\\<Union>i\\<in> I. B \\<setminus> A i)\"\n  using assms by (intro eq_if_subset_if_subset) auto\n\nlemma collect_diff: \"{x \\<in> (A \\<setminus> B) | P x} = {x \\<in> A | P x} \\<setminus> {x \\<in> B | P x}\"\n  by (rule eq_if_subset_if_subset) auto\n\nlemma mono_diff_left: \"mono (\\<lambda>A. A \\<setminus> B)\"\n  by (intro monoI) auto\n\nlemma antimono_diff_right: \"antimono (\\<lambda>B. A \\<setminus> B)\"\n  by (intro antimonoI) auto\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/HOTG/Set_Difference.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789178257654, "lm_q2_score": 0.8840392817460332, "lm_q1q2_score": 0.7164952003849919}}
{"text": "theory Exercise3\nimports Main\nbegin\n\n(* Abstract Syntax Tree *)\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\n(* Evaluate the expression to its value *)\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\n(* examples *)\nvalue \"aval (Plus (N 3) (V ''x'')) (\\<lambda>x.0)\"\n(* value \"aval (Plus (N 3) (V ''x'')) (<>)\" *)\n(* not works *)\n\n(* constant folding *)\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 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(* lemma \\<open>aval (asimp_const a) s = aval a s\\<close>\napply(induction a)\napply(auto split: aexp.split)\ndone *)\n\n(* local optimization for plus *)\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\"\napply(induction rule: plus.induct)\napply(auto)\ndone\n\n(* local optimazation for times *)\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\"\napply(induction rule: times.induct)\napply(auto)\ndone\n\n(* global optimazation *)\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 \\<open>aval (asimp a) s = aval a s\\<close>\napply(induction a)\napply(auto simp add: aval_plus aval_times)\ndone\n\n(* value \"True\" *)\n(* value \"True \\<and> True\" *)\n\n(* Exercise 3.1 *)\n(* fun optimal :: \"aexp \\<Rightarrow> bool\" where\n(* base case *)\n\"optimal (N n) = True\" |\n\"optimal (V x) = True\" |\n(* top most trivial case *)\n\"optimal (Plus (N i) (N j)) = False\" |\n\"optimal (Plus a1 a2) = ((optimal a1) \\<and> (optimal a2))\"\n\nlemma \\<open>optimal (asimp_const a)\\<close>\napply(induction a)\napply(auto split: aexp.split)\ndone *)\n\n(* Exercise 3.2 *)\n(* Use case *)\n(* full_asimp (Plus (N 1) (Plus (V x) (N 2))) = Plus (V x) (N 3) *)\n\n(* local optimization for full_asimp *)\nfun full_times :: \"aexp \\<Rightarrow> aexp \\<Rightarrow> aexp\" where\n\"full_times (N i1) (N i2) = N (i1 * i2)\" |\n\"full_times (N i1) (Times a (N i2)) = Times a (N (i1 * i2))\" |\n\"full_times (Times a (N i1)) (N i2) = Times a (N (i1 * i2))\" |\n\"full_times (N i) a = (if i=0 then (N 0) else (if i=1 then a else Times (N i) a))\" |\n\"full_times a (N i) = (if i=0 then (N 0) else (if i=1 then a else Times a (N i)))\" |\n\"full_times a1 a2 = Times a1 a2\"\n\n(* local optimazation for full_asimp *)\nfun full_plus :: \"aexp \\<Rightarrow> aexp \\<Rightarrow> aexp\" where\n\"full_plus (N i1) (N i2) = N (i1 + i2)\" |\n\"full_plus (N i1) (Plus a (N i2)) = Plus a (N (i1 + i2))\" |\n\"full_plus (Plus a (N i1)) (N i2) = Plus a (N (i1 + i2))\" |\n\"full_plus (N i) a = (if i=0 then a else Plus a (N i))\" |\n\"full_plus a (N i) = (if i=0 then a else Plus a (N i))\" |\n\"full_plus a1 a2 = Plus a1 a2\"\n\n(* global optimization *)\nfun full_asimp :: \"aexp \\<Rightarrow> aexp\" where\n(* base case *)\n\"full_asimp (N n) = N n\" |\n\"full_asimp (V x) = V x\" |\n(* recursive case, i.e wishful thinking *)\n\"full_asimp (Plus a1 a2) = full_plus (full_asimp a1) (full_asimp a2)\" |\n\"full_asimp (Times a1 a2) = full_times (full_asimp a1) (full_asimp a2)\"\n\nlemma aval_full_times: \"aval (full_times a1 a2) s = aval a1 s * aval a2 s\"\napply(induction rule: full_times.induct)\napply(auto)\ndone\n\nlemma aval_full_plus: \"aval (full_plus a1 a2) s = aval a1 s + aval a2 s\"\napply(induction rule: full_plus.induct)\napply(auto)\ndone\n\nlemma \\<open>aval (full_asimp a) s = aval a s\\<close>\napply(induction a)\napply(auto simp: aval_full_plus aval_full_times)\ndone\n\n(* test case *)\n(* full_asimp (Plus (N 1) (Plus (V x) (N 2))) = Plus (V x) (N 3) *)\nlemma \\<open>full_asimp (Plus (N 1) (Plus (V x) (N 2))) = Plus (V x) (N 3)\\<close>\napply(auto)\ndone\n\n(* Exercise 3.3 *)\n\n(* Use case *)\n(* subst ''x'' (N 3) (Plus (V ''x'') (V ''y'')) = Plus (N 3) (V ''y'') *)\n\nfun subst :: \"vname \\<Rightarrow> aexp \\<Rightarrow> aexp \\<Rightarrow> aexp\" where\n(* base case *)\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 e1 e2) = Plus (subst x a e1) (subst x a e2)\" |\n\"subst x a (Times e1 e2) = Times (subst x a e1) (subst x a e2)\"\n\n(* test *)\nvalue \"subst ''x'' (N 3) (Plus (V ''x'') (V ''y'')) = Plus (N 3) (V ''y'')\"\n\nlemma substitution_lemma: \"aval (subst x a e) s = aval e (s(x := aval a s))\"\napply(induction e)\napply(auto)\ndone\n\ncorollary \"aval a1 s = aval a2 s \\<Longrightarrow> aval (subst x a1 e) s = aval (subst x a2 e) s\"\napply(auto simp: substitution_lemma)\ndone\n\n(* Exercise 3.4 *)\n(* see the git diff from b9bb9114f43f5a2d8d348cdec4169ecf3de183a8 *)\n", "meta": {"author": "HyunggyuJang", "repo": "Isabelle", "sha": "725c866251790c808116638c28c115207938086a", "save_path": "github-repos/isabelle/HyunggyuJang-Isabelle", "path": "github-repos/isabelle/HyunggyuJang-Isabelle/Isabelle-725c866251790c808116638c28c115207938086a/Exercise3.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392848011834, "lm_q2_score": 0.8104789109591832, "lm_q1q2_score": 0.7164951967907984}}
{"text": "section \"Bitvector based Sets of Naturals\"\ntheory Impl_Bit_Set\nimports \n  \"../../Iterator/Iterator\" \n  \"../Intf/Intf_Set\" \n  Native_Word.Bits_Integer\nbegin\n  text \\<open>\n    Based on the Native-Word library, using bit-operations on arbitrary\n    precision integers. Fast for sets of small numbers, \n    direct and fast implementations of equal, union, inter, diff.\n\n    Note: On Poly/ML 5.5.1, bit-operations on arbitrary precision integers are \n      rather inefficient. Use MLton instead, here they are efficiently implemented.\n\\<close>\n\n  type_synonym bitset = integer\n\n  definition bs_\\<alpha> :: \"bitset \\<Rightarrow> nat set\" where \"bs_\\<alpha> s \\<equiv> { n . test_bit s n}\"\n\n\ncontext includes integer.lifting begin\n\n  definition bs_empty :: \"unit \\<Rightarrow> bitset\" where \"bs_empty \\<equiv> \\<lambda>_. 0\"\n\n\n  lemma bs_empty_correct: \"bs_\\<alpha> (bs_empty ()) = {}\"\n    unfolding bs_\\<alpha>_def bs_empty_def \n    apply transfer\n    by auto\n\n  definition bs_isEmpty :: \"bitset \\<Rightarrow> bool\" where \"bs_isEmpty s \\<equiv> s=0\"\n\n  lemma bs_isEmpty_correct: \"bs_isEmpty s \\<longleftrightarrow> bs_\\<alpha> s = {}\"\n    unfolding bs_isEmpty_def bs_\\<alpha>_def \n    by transfer (auto simp: bin_eq_iff) \n    \n  term set_bit\n  definition bs_insert :: \"nat \\<Rightarrow> bitset \\<Rightarrow> bitset\" where\n    \"bs_insert i s \\<equiv> set_bit s i True\"\n\n  lemma bs_insert_correct: \"bs_\\<alpha> (bs_insert i s) = insert i (bs_\\<alpha> s)\"\n    unfolding bs_\\<alpha>_def bs_insert_def\n    apply transfer\n    apply auto\n    apply (metis bin_nth_sc_gen bin_set_conv_OR int_set_bit_True_conv_OR)\n    apply (metis bin_nth_sc_gen bin_set_conv_OR int_set_bit_True_conv_OR)\n    by (metis bin_nth_sc_gen bin_set_conv_OR int_set_bit_True_conv_OR)\n\n  definition bs_delete :: \"nat \\<Rightarrow> bitset \\<Rightarrow> bitset\" where\n    \"bs_delete i s \\<equiv> set_bit s i False\"\n\n  lemma bs_delete_correct: \"bs_\\<alpha> (bs_delete i s) = (bs_\\<alpha> s) - {i}\"\n    unfolding bs_\\<alpha>_def bs_delete_def\n    apply transfer\n    apply auto\n    apply (metis bin_nth_ops(1) int_set_bit_False_conv_NAND)\n    apply (metis (full_types) bin_nth_sc set_bit_int_def)\n    by (metis (full_types) bin_nth_sc_gen set_bit_int_def)\n  \n  definition bs_mem :: \"nat \\<Rightarrow> bitset \\<Rightarrow> bool\" where\n    \"bs_mem i s \\<equiv> test_bit s i\"\n\n  lemma bs_mem_correct: \"bs_mem i s \\<longleftrightarrow> i\\<in>bs_\\<alpha> s\"\n    unfolding bs_mem_def bs_\\<alpha>_def by transfer auto\n\n\n  definition bs_eq :: \"bitset \\<Rightarrow> bitset \\<Rightarrow> bool\" where \n    \"bs_eq s1 s2 \\<equiv> (s1=s2)\"\n\n  lemma bs_eq_correct: \"bs_eq s1 s2 \\<longleftrightarrow> bs_\\<alpha> s1 = bs_\\<alpha> s2\"\n    unfolding bs_eq_def bs_\\<alpha>_def\n    including integer.lifting\n    apply transfer\n    apply auto\n    by (metis bin_eqI mem_Collect_eq test_bit_int_def)\n\n  definition bs_subset_eq :: \"bitset \\<Rightarrow> bitset \\<Rightarrow> bool\" where\n    \"bs_subset_eq s1 s2 \\<equiv> s1 AND NOT s2 = 0\"\n  \n  lemma bs_subset_eq_correct: \"bs_subset_eq s1 s2 \\<longleftrightarrow> bs_\\<alpha> s1 \\<subseteq> bs_\\<alpha> s2\"\n    unfolding bs_\\<alpha>_def bs_subset_eq_def\n    apply transfer\n    apply rule\n    apply auto []\n    apply (metis bin_nth_code(1) bin_nth_ops(1) bin_nth_ops(4))\n    apply (auto intro!: bin_eqI simp: bin_nth_ops)\n    done\n\n  definition bs_disjoint :: \"bitset \\<Rightarrow> bitset \\<Rightarrow> bool\" where\n    \"bs_disjoint s1 s2 \\<equiv> s1 AND s2 = 0\"\n  \n  lemma bs_disjoint_correct: \"bs_disjoint s1 s2 \\<longleftrightarrow> bs_\\<alpha> s1 \\<inter> bs_\\<alpha> s2 = {}\"\n    unfolding bs_\\<alpha>_def bs_disjoint_def\n    apply transfer\n    apply rule\n    apply auto []\n    apply (metis bin_nth_code(1) bin_nth_ops(1))\n    apply (auto intro!: bin_eqI simp: bin_nth_ops)\n    done\n\n  definition bs_union :: \"bitset \\<Rightarrow> bitset \\<Rightarrow> bitset\" where\n    \"bs_union s1 s2 = s1 OR s2\"\n\n  lemma bs_union_correct: \"bs_\\<alpha> (bs_union s1 s2) = bs_\\<alpha> s1 \\<union> bs_\\<alpha> s2\"\n    unfolding bs_\\<alpha>_def bs_union_def\n    by transfer (auto simp: bin_nth_ops)\n\n  definition bs_inter :: \"bitset \\<Rightarrow> bitset \\<Rightarrow> bitset\" where\n    \"bs_inter s1 s2 = s1 AND s2\"\n\n  lemma bs_inter_correct: \"bs_\\<alpha> (bs_inter s1 s2) = bs_\\<alpha> s1 \\<inter> bs_\\<alpha> s2\"\n    unfolding bs_\\<alpha>_def bs_inter_def\n    by transfer (auto simp: bin_nth_ops)\n\n  definition bs_diff :: \"bitset \\<Rightarrow> bitset \\<Rightarrow> bitset\" where\n    \"bs_diff s1 s2 = s1 AND NOT s2\"\n\n  lemma bs_diff_correct: \"bs_\\<alpha> (bs_diff s1 s2) = bs_\\<alpha> s1 - bs_\\<alpha> s2\"\n    unfolding bs_\\<alpha>_def bs_diff_def\n    by transfer (auto simp: bin_nth_ops)\n\n  definition bs_UNIV :: \"unit \\<Rightarrow> bitset\" where \"bs_UNIV \\<equiv> \\<lambda>_. -1\"\n\n  lemma bs_UNIV_correct: \"bs_\\<alpha> (bs_UNIV ()) = UNIV\"\n    unfolding bs_\\<alpha>_def bs_UNIV_def\n    by transfer (auto)\n\n  definition bs_complement :: \"bitset \\<Rightarrow> bitset\" where\n    \"bs_complement s = NOT s\"\n\n  lemma bs_complement_correct: \"bs_\\<alpha> (bs_complement s) = - bs_\\<alpha> s\"\n    unfolding bs_\\<alpha>_def bs_complement_def\n    by transfer (auto simp: bin_nth_ops)\n\nend\n\n  lemmas bs_correct[simp] = \n    bs_empty_correct\n    bs_isEmpty_correct\n    bs_insert_correct\n    bs_delete_correct\n    bs_mem_correct\n    bs_eq_correct\n    bs_subset_eq_correct\n    bs_disjoint_correct\n    bs_union_correct\n    bs_inter_correct\n    bs_diff_correct\n    bs_UNIV_correct\n    bs_complement_correct\n\n\nsubsection \\<open>Autoref Setup\\<close>\n\ndefinition bs_set_rel_def_internal: \n  \"bs_set_rel Rk \\<equiv> \n    if Rk=nat_rel then br bs_\\<alpha> (\\<lambda>_. True) else {}\"\nlemma bs_set_rel_def: \n  \"\\<langle>nat_rel\\<rangle>bs_set_rel \\<equiv> br bs_\\<alpha> (\\<lambda>_. True)\" \n  unfolding bs_set_rel_def_internal relAPP_def by simp\n\nlemmas [autoref_rel_intf] = REL_INTFI[of \"bs_set_rel\" i_set]\n\nlemma bs_set_rel_sv[relator_props]: \"single_valued (\\<langle>nat_rel\\<rangle>bs_set_rel)\"\n  unfolding bs_set_rel_def by auto\n\n\nterm bs_empty\n\nlemma [autoref_rules]: \"(bs_empty (),{})\\<in>\\<langle>nat_rel\\<rangle>bs_set_rel\"\n  by (auto simp: bs_set_rel_def br_def)\n\nlemma [autoref_rules]: \"(bs_UNIV (),UNIV)\\<in>\\<langle>nat_rel\\<rangle>bs_set_rel\"\n  by (auto simp: bs_set_rel_def br_def)\n\nlemma [autoref_rules]: \"(bs_isEmpty,op_set_isEmpty)\\<in>\\<langle>nat_rel\\<rangle>bs_set_rel \\<rightarrow> bool_rel\"\n  by (auto simp: bs_set_rel_def br_def)\n\nterm insert\nlemma [autoref_rules]: \"(bs_insert,insert)\\<in>nat_rel \\<rightarrow> \\<langle>nat_rel\\<rangle>bs_set_rel \\<rightarrow> \\<langle>nat_rel\\<rangle>bs_set_rel\"\n  by (auto simp: bs_set_rel_def br_def)\n\nterm op_set_delete\nlemma [autoref_rules]: \"(bs_delete,op_set_delete)\\<in>nat_rel \\<rightarrow> \\<langle>nat_rel\\<rangle>bs_set_rel \\<rightarrow> \\<langle>nat_rel\\<rangle>bs_set_rel\"\n  by (auto simp: bs_set_rel_def br_def)\n\nlemma [autoref_rules]: \"(bs_mem,(\\<in>))\\<in>nat_rel \\<rightarrow> \\<langle>nat_rel\\<rangle>bs_set_rel \\<rightarrow> bool_rel\"\n  by (auto simp: bs_set_rel_def br_def)\n\nlemma [autoref_rules]: \"(bs_eq,(=))\\<in>\\<langle>nat_rel\\<rangle>bs_set_rel \\<rightarrow> \\<langle>nat_rel\\<rangle>bs_set_rel \\<rightarrow> bool_rel\"\n  by (auto simp: bs_set_rel_def br_def)\n\nlemma [autoref_rules]: \"(bs_subset_eq,(\\<subseteq>))\\<in>\\<langle>nat_rel\\<rangle>bs_set_rel \\<rightarrow> \\<langle>nat_rel\\<rangle>bs_set_rel \\<rightarrow> bool_rel\"\n  by (auto simp: bs_set_rel_def br_def)\n\nlemma [autoref_rules]: \"(bs_union,(\\<union>))\\<in>\\<langle>nat_rel\\<rangle>bs_set_rel \\<rightarrow> \\<langle>nat_rel\\<rangle>bs_set_rel \\<rightarrow> \\<langle>nat_rel\\<rangle>bs_set_rel\"\n  by (auto simp: bs_set_rel_def br_def)\n\nlemma [autoref_rules]: \"(bs_inter,(\\<inter>))\\<in>\\<langle>nat_rel\\<rangle>bs_set_rel \\<rightarrow> \\<langle>nat_rel\\<rangle>bs_set_rel \\<rightarrow> \\<langle>nat_rel\\<rangle>bs_set_rel\"\n  by (auto simp: bs_set_rel_def br_def)\n\nlemma [autoref_rules]: \"(bs_diff,(-))\\<in>\\<langle>nat_rel\\<rangle>bs_set_rel \\<rightarrow> \\<langle>nat_rel\\<rangle>bs_set_rel \\<rightarrow> \\<langle>nat_rel\\<rangle>bs_set_rel\"\n  by (auto simp: bs_set_rel_def br_def)\n\nlemma [autoref_rules]: \"(bs_complement,uminus)\\<in>\\<langle>nat_rel\\<rangle>bs_set_rel \\<rightarrow> \\<langle>nat_rel\\<rangle>bs_set_rel\"\n  by (auto simp: bs_set_rel_def br_def)\n\nlemma [autoref_rules]: \"(bs_disjoint,op_set_disjoint)\\<in>\\<langle>nat_rel\\<rangle>bs_set_rel \\<rightarrow> \\<langle>nat_rel\\<rangle>bs_set_rel \\<rightarrow> bool_rel\"\n  by (auto simp: bs_set_rel_def br_def)\n\n\nexport_code \n    bs_empty\n    bs_isEmpty\n    bs_insert\n    bs_delete\n    bs_mem\n    bs_eq\n    bs_subset_eq\n    bs_disjoint\n    bs_union\n    bs_inter\n    bs_diff\n    bs_UNIV\n    bs_complement\n in SML\n\n(*\n\n    TODO: Iterator\n\n  definition \"maxbi s \\<equiv> GREATEST i. s!!i\"\n\n  lemma cmp_BIT_append_conv[simp]: \"i < i BIT b \\<longleftrightarrow> ((i\\<ge>0 \\<and> b=1) \\<or> i>0)\"\n    by (cases b) (auto simp: Bit_B0 Bit_B1)\n\n  lemma BIT_append_cmp_conv[simp]: \"i BIT b < i \\<longleftrightarrow> ((i<0 \\<and> (i=-1 \\<longrightarrow> b=0)))\"\n    by (cases b) (auto simp: Bit_B0 Bit_B1)\n\n  lemma BIT_append_eq[simp]: fixes i :: int shows \"i BIT b = i \\<longleftrightarrow> (i=0 \\<and> b=0) \\<or> (i=-1 \\<and> b=1)\"\n    by (cases b) (auto simp: Bit_B0 Bit_B1)\n\n  lemma int_no_bits_eq_zero[simp]:\n    fixes s::int shows \"(\\<forall>i. \\<not>s!!i) \\<longleftrightarrow> s=0\"\n    apply clarsimp\n    by (metis bin_eqI bin_nth_code(1))\n\n  lemma int_obtain_bit:\n    fixes s::int\n    assumes \"s\\<noteq>0\"\n    obtains i where \"s!!i\"\n    by (metis assms int_no_bits_eq_zero)\n    \n  lemma int_bit_bound:\n    fixes s::int\n    assumes \"s\\<ge>0\" and \"s!!i\"\n    shows \"i \\<le> Bits_Integer.log2 s\"\n  proof (rule ccontr)\n    assume \"\\<not>i\\<le>Bits_Integer.log2 s\"\n    hence \"i>Bits_Integer.log2 s\" by simp\n    hence \"i - 1 \\<ge> Bits_Integer.log2 s\" by simp\n    hence \"s AND bin_mask (i - 1) = s\" by (simp add: int_and_mask `s\\<ge>0`)\n    hence \"\\<not> (s!!i)\"  \n      by clarsimp (metis Nat.diff_le_self bin_nth_mask bin_nth_ops(1) leD)\n    thus False using `s!!i` ..\n  qed\n\n  lemma int_bit_bound':\n    fixes s::int\n    assumes \"s\\<ge>0\" and \"s!!i\"\n    shows \"i < Bits_Integer.log2 s + 1\"\n    using assms int_bit_bound by smt\n\n  lemma int_obtain_bit_pos:\n    fixes s::int\n    assumes \"s>0\"\n    obtains i where \"s!!i\" \"i < Bits_Integer.log2 s + 1\"\n    by (metis assms int_bit_bound' int_no_bits_eq_zero less_imp_le less_irrefl)\n\n  lemma maxbi_set: fixes s::int shows \"s>0 \\<Longrightarrow> s!!maxbi s\"\n    unfolding maxbi_def\n    apply (rule int_obtain_bit_pos, assumption)\n    apply (rule GreatestI_nat, assumption)\n    apply (intro allI impI)\n    apply (rule int_bit_bound'[rotated], assumption)\n    by auto\n\n  lemma maxbi_max: fixes s::int shows \"i>maxbi s \\<Longrightarrow> \\<not> s!!i\"\n    oops\n\n  function get_maxbi :: \"nat \\<Rightarrow> int \\<Rightarrow> nat\" where\n    \"get_maxbi n s = (let\n        b = 1<<n\n      in\n        if b\\<le>s then get_maxbi (n+1) s\n        else n\n    )\"\n    by pat_completeness auto\n\n  termination\n    apply (rule \"termination\"[of \"measure (\\<lambda>(n,s). nat (s + 1 - (1<<n)))\"])\n    apply simp\n    apply auto\n    by (smt bin_mask_ge0 bin_mask_p1_conv_shift)\n\n\n  partial_function (tailrec) \n    bs_iterate_aux :: \"nat \\<Rightarrow> bitset \\<Rightarrow> ('\\<sigma> \\<Rightarrow> bool) \\<Rightarrow> (nat \\<Rightarrow> '\\<sigma> \\<Rightarrow> '\\<sigma>) \\<Rightarrow> '\\<sigma> \\<Rightarrow> '\\<sigma>\"\n    where \"bs_iterate_aux i s c f \\<sigma> = (\n    if s < 1 << i then \\<sigma>\n    else if \\<not>c \\<sigma> then \\<sigma>\n    else if test_bit s i then bs_iterate_aux (i+1) s c f (f i \\<sigma>)\n    else bs_iterate_aux (i+1) s c f \\<sigma>\n  )\"\n\n  definition bs_iteratei :: \"bitset \\<Rightarrow> (nat,'\\<sigma>) set_iterator\" where \n    \"bs_iteratei s = bs_iterate_aux 0 s\"\n\n\n  definition bs_set_rel_def_internal: \n    \"bs_set_rel Rk \\<equiv> \n      if Rk=nat_rel then br bs_\\<alpha> (\\<lambda>_. True) else {}\"\n  lemma bs_set_rel_def: \n    \"\\<langle>nat_rel\\<rangle>bs_set_rel \\<equiv> br bs_\\<alpha> (\\<lambda>_. True)\" \n    unfolding bs_set_rel_def_internal relAPP_def by simp\n\n\n  definition \"bs_to_list \\<equiv> it_to_list bs_iteratei\"\n\n  lemma \"(1::int)<<i = 2^i\"\n    by (simp add: shiftl_int_def)\n\n  lemma \n    fixes s :: int\n    assumes \"s\\<ge>0\"  \n    shows \"s < 1<<i \\<longleftrightarrow> Bits_Integer.log2 s \\<le> i\"\n    using assms\n  proof (induct i arbitrary: s)\n    case 0 thus ?case by auto\n  next\n    case (Suc i)\n    note GE=`0\\<le>s`\n    show ?case proof\n      assume \"s < 1 << Suc i\"\n\n      have \"s \\<le> (s >> 1) BIT 1\"\n\n      hence \"(s >> 1) < (1<<i)\" using GE apply auto\n      with Suc.hyps[of \"s div 2\"]\n\n\n    apply auto\n    \n\n\n  lemma \"distinct (bs_to_list s)\"\n    unfolding bs_to_list_def it_to_list_def bs_iteratei_def[abs_def]\n  proof -\n    {\n      fix l i\n      assume \"distinct l\"\n      show \"distinct (bs_iterate_aux 0 s (\\<lambda>_. True) (\\<lambda>x l. l @ [x]) [])\"\n\n    }\n\n\n    apply auto\n    \n\n\n\n    lemma \"set (bs_to_list s) = bs_\\<alpha> s\"\n\n\n  lemma autoref_iam_is_iterator[autoref_ga_rules]: \n    shows \"is_set_to_list nat_rel bs_set_rel bs_to_list\"\n    unfolding is_set_to_list_def is_set_to_sorted_list_def\n    apply clarsimp\n    unfolding it_to_sorted_list_def\n    apply (refine_rcg refine_vcg)\n    apply (simp_all add: bs_set_rel_def br_def)\n\n  proof (clarsimp)\n\n\n\n  definition \n\n\"iterate s c f \\<sigma> \\<equiv> let\n    i=0;\n    b=0;\n    (_,_,s) = while \n  in\n\n  end\"\n\n\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/Collections/GenCF/Impl/Impl_Bit_Set.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8840392725805822, "lm_q2_score": 0.8104789155369047, "lm_q1q2_score": 0.7164951909331443}}
{"text": "(*\n  File:    Product_PMF.thy\n  Authors: Manuel Eberl, Max W. Haslbeck\n*)\nsection \\<open>Indexed products of PMFs\\<close>\ntheory Product_PMF\n  imports Probability_Mass_Function Independent_Family\nbegin\n\ntext \\<open>Conflicting notation from \\<^theory>\\<open>HOL-Analysis.Infinite_Sum\\<close>\\<close>\nno_notation Infinite_Sum.abs_summable_on (infixr \"abs'_summable'_on\" 46)\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 Pi_pmf_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>fa. if \\<forall>x. x \\<notin> A \\<longrightarrow> fa x = dflt then \\<Prod>x\\<in>A. pmf (f x) (fa x) else 0) =\n        (\\<lambda>f. if \\<forall>x. x \\<notin> A' \\<longrightarrow> f x = dflt' then \\<Prod>x\\<in>A'. pmf (f' x) (f x) else 0)\"\n    using assms by (intro ext) (auto intro!: prod.cong)\n  thus ?thesis\n    by (simp only: Pi_pmf_def)\nqed\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\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\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 set_Pi_pmf:\n  assumes \"finite A\"\n  shows   \"set_pmf (Pi_pmf A dflt p) = PiE_dflt A dflt (set_pmf \\<circ> p)\"\nproof (rule equalityI)\n  show \"PiE_dflt A dflt (set_pmf \\<circ> p) \\<subseteq> set_pmf (Pi_pmf A dflt p)\"\n  proof safe\n    fix f assume f: \"f \\<in> PiE_dflt A dflt (set_pmf \\<circ> p)\"\n    hence \"pmf (Pi_pmf A dflt p) f = (\\<Prod>x\\<in>A. pmf (p x) (f x))\"\n      using assms by (auto simp: pmf_Pi PiE_dflt_def)\n    also have \"\\<dots> > 0\"\n      using f by (intro prod_pos) (auto simp: PiE_dflt_def set_pmf_eq)\n    finally show \"f \\<in> set_pmf (Pi_pmf A dflt p)\"\n      by (auto simp: set_pmf_eq)\n  qed\nqed (use set_Pi_pmf_subset'[OF assms, of dflt p] in auto)\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 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\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)\"\n  using assms by (intro pmf_eqI) (auto simp: pmf_Pi simp: indicator_def split: if_splits)\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>Additional properties\\<close>\n\nlemma nn_integral_prod_Pi_pmf:\n  assumes \"finite A\"\n  shows   \"nn_integral (Pi_pmf A dflt p) (\\<lambda>y. \\<Prod>x\\<in>A. f x (y x)) = (\\<Prod>x\\<in>A. nn_integral (p x) (f x))\"\n  using assms\nproof (induction rule: finite_induct)\n  case (insert x A)\n  have \"nn_integral (Pi_pmf (insert x A) dflt p) (\\<lambda>y. \\<Prod>z\\<in>insert x A. f z (y z)) =\n          (\\<integral>\\<^sup>+a. \\<integral>\\<^sup>+b. f x a * (\\<Prod>z\\<in>A. f z (if z = x then a else b z)) \\<partial>Pi_pmf A dflt p \\<partial>p x)\"\n    using insert by (auto simp: Pi_pmf_insert case_prod_unfold nn_integral_pair_pmf' cong: if_cong)\n  also have \"(\\<lambda>a b. \\<Prod>z\\<in>A. f z (if z = x then a else b z)) = (\\<lambda>a b. \\<Prod>z\\<in>A. f z (b z))\"\n    by (intro ext prod.cong) (use insert.hyps in auto)\n  also have \"(\\<integral>\\<^sup>+a. \\<integral>\\<^sup>+b. f x a * (\\<Prod>z\\<in>A. f z (b z)) \\<partial>Pi_pmf A dflt p \\<partial>p x) =\n             (\\<integral>\\<^sup>+y. f x y \\<partial>(p x)) * (\\<integral>\\<^sup>+y. (\\<Prod>z\\<in>A. f z (y z)) \\<partial>(Pi_pmf A dflt p))\"\n    by (simp add: nn_integral_multc nn_integral_cmult)\n  also have \"(\\<integral>\\<^sup>+y. (\\<Prod>z\\<in>A. f z (y z)) \\<partial>(Pi_pmf A dflt p)) = (\\<Prod>x\\<in>A. nn_integral (p x) (f x))\"\n    by (rule insert.IH)\n  also have \"(\\<integral>\\<^sup>+y. f x y \\<partial>(p x)) * \\<dots> = (\\<Prod>x\\<in>insert x A. nn_integral (p x) (f x))\"\n    using insert.hyps by simp\n  finally show ?case .\nqed auto\n\nlemma integrable_prod_Pi_pmf:\n  fixes f :: \"'a \\<Rightarrow> 'b \\<Rightarrow> 'c :: {real_normed_field, second_countable_topology, banach}\"\n  assumes \"finite A\" and \"\\<And>x. x \\<in> A \\<Longrightarrow> integrable (measure_pmf (p x)) (f x)\"\n  shows   \"integrable (measure_pmf (Pi_pmf A dflt p)) (\\<lambda>h. \\<Prod>x\\<in>A. f x (h x))\"\nproof (intro integrableI_bounded)\n  have \"(\\<integral>\\<^sup>+ x. ennreal (norm (\\<Prod>xa\\<in>A. f xa (x xa))) \\<partial>measure_pmf (Pi_pmf A dflt p)) =\n        (\\<integral>\\<^sup>+ x. (\\<Prod>y\\<in>A. ennreal (norm (f y (x y)))) \\<partial>measure_pmf (Pi_pmf A dflt p))\"\n    by (simp flip: prod_norm prod_ennreal)\n  also have \"\\<dots> = (\\<Prod>x\\<in>A. \\<integral>\\<^sup>+ a. ennreal (norm (f x a)) \\<partial>measure_pmf (p x))\"\n    by (intro nn_integral_prod_Pi_pmf) fact\n  also have \"(\\<integral>\\<^sup>+a. ennreal (norm (f i a)) \\<partial>measure_pmf (p i)) \\<noteq> top\" if i: \"i \\<in> A\" for i\n    using assms(2)[OF i] by (simp add: integrable_iff_bounded)\n  hence \"(\\<Prod>x\\<in>A. \\<integral>\\<^sup>+ a. ennreal (norm (f x a)) \\<partial>measure_pmf (p x)) \\<noteq> top\"\n    by (subst ennreal_prod_eq_top) auto\n  finally show \"(\\<integral>\\<^sup>+ x. ennreal (norm (\\<Prod>xa\\<in>A. f xa (x xa))) \\<partial>measure_pmf (Pi_pmf A dflt p)) < \\<infinity>\"\n    by (simp add: top.not_eq_extremum)\nqed auto\n\nlemma expectation_prod_Pi_pmf:\n  fixes f :: \"_ \\<Rightarrow> _ \\<Rightarrow> real\"\n  assumes \"finite A\"\n  assumes \"\\<And>x. x \\<in> A \\<Longrightarrow> integrable (measure_pmf (p x)) (f x)\"\n  assumes \"\\<And>x y. x \\<in> A \\<Longrightarrow> y \\<in> set_pmf (p x) \\<Longrightarrow> f x y \\<ge> 0\"\n  shows   \"measure_pmf.expectation (Pi_pmf A dflt p) (\\<lambda>y. \\<Prod>x\\<in>A. f x (y x)) =\n             (\\<Prod>x\\<in>A. measure_pmf.expectation (p x) (\\<lambda>v. f x v))\"\nproof -\n  have nonneg: \"measure_pmf.expectation (p x) (f x) \\<ge> 0\" if \"x \\<in> A\" for x\n    using that by (intro Bochner_Integration.integral_nonneg_AE AE_pmfI assms)\n  have nonneg': \"0 \\<le> measure_pmf.expectation (Pi_pmf A dflt p) (\\<lambda>y. \\<Prod>x\\<in>A. f x (y x))\"\n    by (intro Bochner_Integration.integral_nonneg_AE AE_pmfI assms prod_nonneg)\n       (use assms in \\<open>auto simp: set_Pi_pmf PiE_dflt_def\\<close>)\n\n  have \"ennreal (measure_pmf.expectation (Pi_pmf A dflt p) (\\<lambda>y. \\<Prod>x\\<in>A. f x (y x))) =\n          nn_integral (Pi_pmf A dflt p) (\\<lambda>y. ennreal (\\<Prod>x\\<in>A. f x (y x)))\" using assms\n    by (intro nn_integral_eq_integral [symmetric] assms integrable_prod_Pi_pmf)\n       (auto simp: AE_measure_pmf_iff set_Pi_pmf PiE_dflt_def prod_nonneg)\n  also have \"\\<dots> = nn_integral (Pi_pmf A dflt p) (\\<lambda>y. (\\<Prod>x\\<in>A. ennreal (f x (y x))))\"\n    by (intro nn_integral_cong_AE AE_pmfI prod_ennreal [symmetric])\n       (use assms(1) in \\<open>auto simp: set_Pi_pmf PiE_dflt_def intro!: assms(3)\\<close>)\n  also have \"\\<dots> = (\\<Prod>x\\<in>A. \\<integral>\\<^sup>+ a. ennreal (f x a) \\<partial>measure_pmf (p x))\"\n    by (rule nn_integral_prod_Pi_pmf) fact+\n  also have \"\\<dots> = (\\<Prod>x\\<in>A. ennreal (measure_pmf.expectation (p x) (f x)))\"\n    by (intro prod.cong nn_integral_eq_integral assms AE_pmfI) auto\n  also have \"\\<dots> = ennreal (\\<Prod>x\\<in>A. measure_pmf.expectation (p x) (f x))\"\n    by (intro prod_ennreal nonneg)\n  finally show ?thesis\n    using nonneg nonneg' by (subst (asm) ennreal_inj) (auto intro!: prod_nonneg)\nqed\n\nlemma indep_vars_Pi_pmf:\n  assumes fin: \"finite I\"\n  shows   \"prob_space.indep_vars (measure_pmf (Pi_pmf I dflt p))\n             (\\<lambda>_. count_space UNIV) (\\<lambda>x f. f x) I\"\nproof (cases \"I = {}\")\n  case True\n  show ?thesis \n    by (subst prob_space.indep_vars_def [OF measure_pmf.prob_space_axioms],\n        subst prob_space.indep_sets_def [OF measure_pmf.prob_space_axioms]) (simp_all add: True)\nnext\n  case [simp]: False\n  show ?thesis\n  proof (subst prob_space.indep_vars_iff_distr_eq_PiM')\n    show \"distr (measure_pmf (Pi_pmf I dflt p)) (Pi\\<^sub>M I (\\<lambda>i. count_space UNIV)) (\\<lambda>x. restrict x I) =\n          Pi\\<^sub>M I (\\<lambda>i. distr (measure_pmf (Pi_pmf I dflt p)) (count_space UNIV) (\\<lambda>f. f i))\"\n    proof (rule product_sigma_finite.PiM_eqI, goal_cases)\n      case 1\n      interpret product_prob_space \"\\<lambda>i. distr (measure_pmf (Pi_pmf I dflt p)) (count_space UNIV) (\\<lambda>f. f i)\"\n        by (intro product_prob_spaceI prob_space.prob_space_distr measure_pmf.prob_space_axioms)\n           simp_all\n      show ?case by unfold_locales\n    next\n      case 3\n      have \"sets (Pi\\<^sub>M I (\\<lambda>i. distr (measure_pmf (Pi_pmf I dflt p)) (count_space UNIV) (\\<lambda>f. f i))) =\n            sets (Pi\\<^sub>M I (\\<lambda>_. count_space UNIV))\"\n        by (intro sets_PiM_cong) simp_all\n      thus ?case by simp\n    next\n      case (4 A)\n      have \"Pi\\<^sub>E I A \\<in> sets (Pi\\<^sub>M I (\\<lambda>i. count_space UNIV))\"\n        using 4 by (intro sets_PiM_I_finite fin) auto\n      hence \"emeasure (distr (measure_pmf (Pi_pmf I dflt p)) (Pi\\<^sub>M I (\\<lambda>i. count_space UNIV))\n              (\\<lambda>x. restrict x I)) (Pi\\<^sub>E I A) =\n             emeasure (measure_pmf (Pi_pmf I dflt p)) ((\\<lambda>x. restrict x I) -` Pi\\<^sub>E I A)\"\n        using 4 by (subst emeasure_distr) (auto simp: space_PiM)\n      also have \"\\<dots> = emeasure (measure_pmf (Pi_pmf I dflt p)) (PiE_dflt I dflt A)\"\n        by (intro emeasure_eq_AE AE_pmfI) (auto simp: PiE_dflt_def set_Pi_pmf fin)\n      also have \"\\<dots> = (\\<Prod>i\\<in>I. emeasure (measure_pmf (p i)) (A i))\"\n        by (simp add: measure_pmf.emeasure_eq_measure measure_Pi_pmf_PiE_dflt fin prod_ennreal)\n      also have \"\\<dots> = (\\<Prod>i\\<in>I. emeasure (measure_pmf (map_pmf (\\<lambda>f. f i) (Pi_pmf I dflt p))) (A i))\"\n        by (intro prod.cong refl, subst Pi_pmf_component) (auto simp: fin)\n      finally show ?case\n        by (simp add: map_pmf_rep_eq)\n    qed fact+\n  qed (simp_all add: measure_pmf.prob_space_axioms)\nqed\n\nlemma\n  fixes h :: \"'a :: comm_monoid_add \\<Rightarrow> 'b::{banach, second_countable_topology}\"\n  assumes fin: \"finite I\"\n  assumes integrable: \"\\<And>i. i \\<in> I \\<Longrightarrow> integrable (measure_pmf (D i)) h\"\n  shows   integrable_sum_Pi_pmf: \"integrable (Pi_pmf I dflt D) (\\<lambda>g. \\<Sum>i\\<in>I. h (g i))\"\n    and   expectation_sum_Pi_pmf:\n            \"measure_pmf.expectation (Pi_pmf I dflt D) (\\<lambda>g. \\<Sum>i\\<in>I. h (g i)) =\n             (\\<Sum>i\\<in>I. measure_pmf.expectation (D i) h)\"\nproof -\n  have integrable': \"integrable (Pi_pmf I dflt D) (\\<lambda>g. h (g i))\" if i: \"i \\<in> I\" for i\n  proof -\n    have \"integrable (D i) h\"\n      using i by (rule assms)\n    also have \"D i = map_pmf (\\<lambda>g. g i) (Pi_pmf I dflt D)\"\n      by (subst Pi_pmf_component) (use fin i in auto)\n    finally show \"integrable (measure_pmf (Pi_pmf I dflt D)) (\\<lambda>x. h (x i))\"\n      by simp\n  qed\n  thus \"integrable (Pi_pmf I dflt D) (\\<lambda>g. \\<Sum>i\\<in>I. h (g i))\"\n    by (intro Bochner_Integration.integrable_sum)\n\n  have \"measure_pmf.expectation (Pi_pmf I dflt D) (\\<lambda>x. \\<Sum>i\\<in>I. h (x i)) =\n               (\\<Sum>i\\<in>I. measure_pmf.expectation (map_pmf (\\<lambda>x. x i) (Pi_pmf I dflt D)) h)\"\n    using integrable' by (subst Bochner_Integration.integral_sum) auto\n  also have \"\\<dots> = (\\<Sum>i\\<in>I. measure_pmf.expectation (D i) h)\"\n    by (intro sum.cong refl, subst Pi_pmf_component) (use fin in auto)\n  finally show \"measure_pmf.expectation (Pi_pmf I dflt D) (\\<lambda>g. \\<Sum>i\\<in>I. h (g i)) =\n                  (\\<Sum>i\\<in>I. measure_pmf.expectation (D i) h)\" .\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": "seL4", "repo": "isabelle", "sha": "e1ab32a3bb41728cd19541063283e37919978a4c", "save_path": "github-repos/isabelle/seL4-isabelle", "path": "github-repos/isabelle/seL4-isabelle/isabelle-e1ab32a3bb41728cd19541063283e37919978a4c/src/HOL/Probability/Product_PMF.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8947894548800271, "lm_q2_score": 0.8006919949619793, "lm_q1q2_score": 0.7164507536988309}}
{"text": "theory Exercise_3_1\nimports Main\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) = (set l) \\<union> (set r) \\<union> {a}\"\n\nfun min_opt :: \"int option \\<Rightarrow> int option \\<Rightarrow> int option\" where\n  \"min_opt None None = None\" |\n  \"min_opt (Some a) None = Some a\" |\n  \"min_opt None (Some a) = Some a\" |\n  \"min_opt (Some a) (Some b) = Some (min a b)\"\n\nfun max_opt :: \"int option \\<Rightarrow> int option \\<Rightarrow> int option\" where\n  \"max_opt None None = None\" |\n  \"max_opt (Some a) None = Some a\" |\n  \"max_opt None (Some a) = Some a\" |\n  \"max_opt (Some a) (Some b) = Some (max a b)\"\n  \nfun le_opt :: \"int option \\<Rightarrow> int \\<Rightarrow> bool\" where\n  \"le_opt None _ = True\" |\n  \"le_opt (Some a) b = (a\\<le>b)\"\n\nfun ge_opt :: \"int option \\<Rightarrow> int \\<Rightarrow> bool\" where\n  \"ge_opt None _ = True\" |\n  \"ge_opt (Some a) b = (a\\<ge>b)\"  \n \nfun min_tree :: \"int tree \\<Rightarrow> int option\" where\n  \"min_tree Tip = None\" |\n  \"min_tree (Node l a r) = min_opt (min_opt (min_tree l) (Some a)) (min_tree r)\"\n\nfun max_tree :: \"int tree \\<Rightarrow> int option\" where\n  \"max_tree Tip = None\" |\n  \"max_tree (Node l a r) = max_opt (max_opt (max_tree l) (Some a)) (max_tree r)\"\n  \nfun ord :: \"int tree \\<Rightarrow> bool\" where\n  \"ord Tip = True\" |\n  \"ord (Node l a r) = ((le_opt (max_tree l) a) \\<and> (ge_opt (min_tree r) a) \\<and> (ord l) \\<and> (ord r))\"\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) = (if (a=b) then (Node l b r) else (if (a<b) then (Node (ins a l) b r) else (Node l b (ins a r))))\"\n\nlemma \"set(ins x t) = {x} \\<union> (set t)\"\n  apply(induction t)\n  apply(auto)\n  done\n\nlemma max_opt_none: \"max_opt None x = max_opt x None\"\n  apply(induction x)\n  apply(auto)\n  done\n    \nlemma max_opt_some: \"max_opt (Some a) x = max_opt x (Some a)\"\n  apply(induction x)\n  apply(auto)\n  done\n\nlemma max_opt_none_2: \"max_opt(max_opt x y) None = max_opt x y\"\n  apply(induction x; induction y)\n  apply(auto)\n  done\n    \nlemma max_opt_none_3: \"max_opt(max_opt x None) y = max_opt x y\"\n  apply(induction x; induction y)\n  apply(auto)\n  done\n\nlemma max_opt_none_4: \"max_opt x (max_opt y None) = max_opt x y\"\n  apply(induction x; induction y)\n  apply(auto)\n  done\n    \nlemma max_opt_none_5: \"max_opt (max_opt None x) y = max_opt x y\"\n  apply(induction x; induction y)\n  apply(auto)\n  done\n\nlemma max_opt_none_6: \"max_opt (max_opt x None) y = max_opt x y\"\n  apply(induction x; induction y)\n  apply(auto)\n  done\n\nlemma max_opt_none_7: \"max_opt x (max_opt None y) = max_opt x y\"\n  apply(induction x; induction y)\n  apply(auto)\n  done\n    \nlemma max_opt_none_8: \"max_opt None (max_opt x y) = max_opt x y\"\n  apply(induction x; induction y)\n  apply(auto)\n  done\n\nlemma max_opt_commutative: \"max_opt x y = max_opt y x\"\n  apply(induction x)\n  apply(auto simp add: max_opt_none, simp add: max_opt_some)\n  done\n\nlemma max_opt_swap: \"max_opt(max_opt x y) z = max_opt(max_opt x z) y\"\n  apply(induction x)\n  apply(auto simp add: max_opt_none_5, simp add:max_opt_commutative)\n  apply(induction y)\n  apply(auto simp add: max_opt_none_5, simp add: max_opt_none_2)\n  apply(induction z)\n  apply(auto)\n  done\n    \nlemma max_opt_associative: \"max_opt x (max_opt y z) = max_opt (max_opt x y) z\"\n  apply(induction x)\n  apply(auto simp add:max_opt_none, simp add:max_opt_none_2, simp add:max_opt_none_3)\n  apply(induction y)\n  apply(auto simp add:max_opt_none, simp add:max_opt_none_4)\n  apply(induction z)\n  apply(auto)\n  done\n\nlemma max_opt_some_2: \"max_opt(max_opt x (Some y)) z = max_opt x (max_opt z (Some y))\"\n  apply(induction x)\n  apply(auto simp add:max_opt_none_7, simp add:max_opt_none_8, simp add:max_opt_some)\n  apply(induction z)\n  apply(auto)\n  done\n    \nlemma max_opt_dense: \"max_opt x (max_opt y z) = max_opt(max_opt x y) z\"\n  apply(induction x)\n  apply(simp_all add:max_opt_none_8)\n  apply(induction y)\n  apply(auto simp add:max_opt_some)\n  apply(auto simp add:max_opt_some_2)\n  apply(auto simp add:max_opt_associative)\n  done\n    \nlemma max_opt_double_some: \"max_opt (max_opt x (Some y)) (Some z) = max_opt x (Some (max y z))\"\n  apply(induction x)\n  apply(simp_all add:max_opt_none_8)\n  done\n\nlemma max_tree_ins: \"max_tree(ins i t) = max_opt (Some i) (max_tree t)\"\n  apply(induction t)\n  apply(auto simp add: max_opt_some)\n  apply(auto simp add: max_opt_some_2)\n  apply(auto simp add: max_opt_dense)\n  apply(auto simp add: max_opt_double_some)\n  done\n    \nlemma le_opt_max_opt: \"le_opt x z \\<Longrightarrow> le_opt y z \\<Longrightarrow> le_opt(max_opt x y) z\"\n  apply(induction x; induction y)\n  apply(auto)\n  done\n\nlemma min_opt_none: \"min_opt None x = min_opt x None\"\n  apply(induction x)\n  apply(auto)\n  done\n    \nlemma min_opt_some: \"min_opt (Some a) x = min_opt x (Some a)\"\n  apply(induction x)\n  apply(auto)\n  done\n\nlemma min_opt_none_2: \"min_opt(min_opt x y) None = min_opt x y\"\n  apply(induction x; induction y)\n  apply(auto)\n  done\n    \nlemma min_opt_none_3: \"min_opt(min_opt x None) y = min_opt x y\"\n  apply(induction x; induction y)\n  apply(auto)\n  done\n\nlemma min_opt_none_4: \"min_opt x (min_opt y None) = min_opt x y\"\n  apply(induction x; induction y)\n  apply(auto)\n  done\n    \nlemma min_opt_none_5: \"min_opt (min_opt None x) y = min_opt x y\"\n  apply(induction x; induction y)\n  apply(auto)\n  done\n\nlemma max_opt_none_6: \"max_opt (max_opt x None) y = max_opt x y\"\n  apply(induction x; induction y)\n  apply(auto)\n  done\n\nlemma min_opt_none_7: \"min_opt x (min_opt None y) = min_opt x y\"\n  apply(induction x; induction y)\n  apply(auto)\n  done\n    \nlemma min_opt_none_8: \"min_opt None (min_opt x y) = min_opt x y\"\n  apply(induction x; induction y)\n  apply(auto)\n  done\n\nlemma min_opt_commutative: \"min_opt x y = min_opt y x\"\n  apply(induction x)\n  apply(auto simp add: min_opt_none, simp add: min_opt_some)\n  done\n\nlemma min_opt_swap: \"min_opt(min_opt x y) z = min_opt(min_opt x z) y\"\n  apply(induction x)\n  apply(auto simp add: min_opt_none_5, simp add:min_opt_commutative)\n  apply(induction y)\n  apply(auto simp add: min_opt_none_5, simp add: min_opt_none_2)\n  apply(induction z)\n  apply(auto)\n  done\n\nlemma min_opt_associative: \"min_opt x (min_opt y z) = min_opt (min_opt x y) z\"\n  apply(induction x)\n  apply(auto simp add:min_opt_none, simp add:min_opt_none_2, simp add:min_opt_none_3)\n  apply(induction y)\n  apply(auto simp add:min_opt_none, simp add:min_opt_none_4)\n  apply(induction z)\n  apply(auto)\n  done\n\nlemma min_opt_some_2: \"min_opt(min_opt x (Some y)) z = min_opt x (min_opt z (Some y))\"\n  apply(induction x)\n  apply(auto simp add:min_opt_none_7, simp add:min_opt_none_8, simp add:min_opt_some)\n  apply(induction z)\n  apply(auto)\n  done\n    \nlemma min_opt_dense: \"min_opt x (min_opt y z) = min_opt(min_opt x y) z\"\n  apply(induction x)\n  apply(simp_all add:min_opt_none_8)\n  apply(induction y)\n  apply(auto simp add:min_opt_some)\n  apply(auto simp add:min_opt_some_2)\n  apply(auto simp add:min_opt_associative)\n  done\n    \nlemma min_opt_double_some: \"min_opt (min_opt x (Some y)) (Some z) = min_opt x (Some (min y z))\"\n  apply(induction x)\n  apply(simp_all add:min_opt_none_8)\n  done\n\nlemma min_tree_ins: \"min_tree(ins i t) = min_opt (Some i) (min_tree t)\"\n  apply(induction t)\n  apply(auto simp add: min_opt_some)\n  apply(auto simp add: min_opt_some_2)\n  apply(auto simp add: min_opt_dense)\n  apply(auto simp add: min_opt_double_some)\n  done\n    \nlemma ge_opt_min_opt: \"ge_opt x z \\<Longrightarrow> ge_opt y z \\<Longrightarrow> ge_opt(min_opt x y) z\"\n  apply(induction x; induction y)\n  apply(auto)\n  done\n    \n\nlemma \"ord t \\<Longrightarrow> ord (ins i t)\"\n  apply(induction t)\n  apply(auto simp add:max_tree_ins)\n  apply(auto simp add:le_opt_max_opt)\n  apply(auto simp add:min_tree_ins)\n  apply(auto simp add:ge_opt_min_opt)\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_3_1.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942171172603, "lm_q2_score": 0.7931059585194573, "lm_q1q2_score": 0.7164080258918676}}
{"text": "theory Why3_Map\nimports Why3_Setup\nbegin\n\nsection {* Generic Maps *}\n\nwhy3_open \"map/Map.xml\"\n\nwhy3_vc setqtdef by auto\n\nwhy3_end\n\n\nsection {* Constant Maps *}\n\ndefinition abs_const :: \"'a \\<Rightarrow> ('b \\<Rightarrow> 'a)\" where\n  \"abs_const v y = v\"\n\nwhy3_open \"map/Const.xml\"\n  constants\n    const=abs_const\n\nwhy3_vc constqtdef\n  by (simp add: abs_const_def)\n\nwhy3_end\n\nsection {* Number of occurrences *}\n\ndefinition occ :: \"'a \\<Rightarrow> (int \\<Rightarrow> 'a) \\<Rightarrow> int \\<Rightarrow> int \\<Rightarrow> int\" where\n  \"occ v m l u = int (card (m -` {v} \\<inter> {l..<u}))\"\n\nwhy3_open \"map/Occ.xml\"\n  constants\n    occ = occ\n\nwhy3_vc occ_empty\n  using assms\n  by (simp add: occ_def)\n\nwhy3_vc occ_right_no_add\nproof -\n  from assms have \"{l..<u} = {l..<u - 1} \\<union> {u - 1}\" by auto\n  with assms show ?thesis by (simp add: occ_def)\nqed\n\nwhy3_vc occ_right_add\nproof -\n  from assms have \"{l..<u} = {l..<u - 1} \\<union> {u - 1}\" by auto\n  with assms show ?thesis by (simp add: occ_def)\nqed\n\nwhy3_vc occ_bounds\nproof -\n  have \"card ({l..<u} \\<inter> m -` {v}) \\<le> card {l..<u}\"\n    by (blast intro: card_mono)\n  moreover have \"card ({l..<u} - m -` {v}) = card {l..<u} - card ({l..<u} \\<inter> m -` {v})\"\n    by (blast intro: card_Diff_subset_Int)\n  ultimately have \"card {l..<u} = card ({l..<u} - m -` {v}) + card ({l..<u} \\<inter> m -` {v})\"\n    by simp\n  with assms show ?C2\n    by (simp add: occ_def Int_commute)\nqed (simp add: occ_def)\n\nwhy3_vc occ_append\nproof -\n  from assms have \"{l..<u} = {l..<mid} \\<union> {mid..<u}\"\n    by (simp add: ivl_disj_un)\n  moreover have \"m -` {v} \\<inter> {l..<mid} \\<inter> (m -` {v} \\<inter> {mid..<u}) =\n    m -` {v} \\<inter> ({l..<mid} \\<inter> {mid..<u})\"\n    by auto\n  ultimately show ?thesis\n    by (simp add: occ_def Int_Un_distrib card_Un_disjoint)\nqed\n\nwhy3_vc occ_neq\n  using assms\n  by (auto simp add: occ_def)\n\nwhy3_vc occ_exists\n  using assms\n  by (auto simp add: occ_def card_gt_0_iff)\n\nwhy3_vc occ_pos\n  using assms\n  by (auto simp add: occ_def card_gt_0_iff)\n\nwhy3_vc occ_eq\nproof -\n  from assms have \"m1 -` {v} \\<inter> {l..<u} = m2 -` {v} \\<inter> {l..<u}\" by auto\n  then show ?thesis by (simp add: occ_def)\nqed\n\nlemma vimage_update:\n  \"m(i := x) -` {z} = (if x = z then m -` {z} \\<union> {i} else m -` {z} - {i})\"\n  by auto\n\nwhy3_vc occ_exchange\n  using assms\n  by (simp add: occ_def vimage_update insert_Diff_if card.insert_remove)\n    (auto simp add: Diff_Int_distrib2 card_Diff_subset_Int)\n\nwhy3_vc occ_left_add\nproof -\n  from assms have \"{l..<u} = {l} \\<union> {l + 1..<u}\" by auto\n  with assms show ?thesis by (simp add: occ_def)\nqed\n\nwhy3_vc occ_left_no_add\nproof -\n  from assms have \"{l..<u} = {l} \\<union> {l + 1..<u}\" by auto\n  with assms show ?thesis by (simp add: occ_def)\nqed\n\nwhy3_end\n\nwhy3_open \"map/MapPermut.xml\"\n\nwhy3_vc permut_trans\n  using assms\n  by (simp add: permut_def)\n\nwhy3_vc permut_exists\nproof -\n  from assms have \"0 < occ (a2 i) a1 l u\"\n    by (simp add: permut_def occ_pos)\n  then show ?thesis by (auto dest: occ_exists)\nqed\n\nwhy3_end\n\n\nsection {* Injectivity and surjectivity for maps (indexed by integers) *}\n\nwhy3_open \"map/MapInjection.xml\"\n\nwhy3_vc injective_surjective\nproof -\n  have \"finite {0..<n}\" by simp\n  moreover from assms have \"a ` {0..<n} \\<subseteq> {0..<n}\"\n    by (auto simp add: range_def)\n  moreover from assms have \"inj_on a {0..<n}\"\n    by (force intro!: inj_onI simp add: injective_def)\n  ultimately have \"a ` {0..<n} = {0..<n}\" by (rule endo_inj_surj)\n  then have \"{0..<n} \\<subseteq> a ` {0..<n}\" by simp\n  then show ?thesis by (force simp add: surjective_def)\nqed\n\nwhy3_vc injection_occ\n  unfolding injective_def occ_def\nproof\n  assume H: \"\\<forall>i j. 0 \\<le> i \\<and> i < n \\<longrightarrow> 0 \\<le> j \\<and> j < n \\<longrightarrow> i \\<noteq> j \\<longrightarrow> m i \\<noteq> m j\"\n  show \"\\<forall>v. int (card (m -` {v} \\<inter> {0..<n})) \\<le> 1\"\n  proof\n    fix v\n    let ?S = \"m -` {v} \\<inter> {0..<n}\"\n    show \"int (card ?S) \\<le> 1\"\n    proof (rule ccontr)\n      assume \"\\<not> int (card ?S) \\<le> 1\"\n      with card_le_Suc_iff [of 1 ?S]\n      obtain x S where \"?S = insert x S\"\n        \"x \\<notin> S\" \"1 \\<le> card S\" \"finite S\"\n        by auto\n      with card_le_Suc_iff [of 0 S]\n      obtain x' S' where \"S = insert x' S'\" by auto\n      with `?S = insert x S` `x \\<notin> S`\n      have \"m x = v\" \"m x' = v\" \"x \\<noteq> x'\" \"0 \\<le> x\" \"x < n\" \"0 \\<le> x'\" \"x' < n\"\n        by auto\n      with H show False by auto\n    qed\n  qed\nnext\n  assume H: \"\\<forall>v. int (card (m -` {v} \\<inter> {0..<n})) \\<le> 1\"\n  show \"\\<forall>i j. 0 \\<le> i \\<and> i < n \\<longrightarrow> 0 \\<le> j \\<and> j < n \\<longrightarrow> i \\<noteq> j \\<longrightarrow> m i \\<noteq> m j\"\n  proof (intro strip notI)\n    fix i j\n    let ?S = \"m -` {m i} \\<inter> {0..<n}\"\n    assume \"0 \\<le> i \\<and> i < n\" \"0 \\<le> j \\<and> j < n\" \"i \\<noteq> j\" \"m i = m j\"\n    have \"finite ?S\" by simp\n    moreover from `0 \\<le> i \\<and> i < n` have \"i \\<in> ?S\" by simp\n    ultimately have S: \"card ?S = Suc (card (?S - {i}))\"\n      by (rule card.remove)\n    have \"finite (?S - {i})\" by simp\n    moreover from `0 \\<le> j \\<and> j < n` `i \\<noteq> j` `m i = m j`\n    have \"j \\<in> ?S - {i}\" by simp\n    ultimately have \"card (?S - {i}) = Suc (card (?S - {i} - {j}))\"\n      by (rule card.remove)\n    with S have \"\\<not> int (card ?S) \\<le> 1\" by simp\n    with H show False by simp\n  qed\nqed\n\nwhy3_end\n\nend\n", "meta": {"author": "Frederic-Boulanger-UPS", "repo": "Why3-Isabelle2021-lib", "sha": "55025659a286bb060d97e61beda7d3830343aabf", "save_path": "github-repos/isabelle/Frederic-Boulanger-UPS-Why3-Isabelle2021-lib", "path": "github-repos/isabelle/Frederic-Boulanger-UPS-Why3-Isabelle2021-lib/Why3-Isabelle2021-lib-55025659a286bb060d97e61beda7d3830343aabf/isabelle/Why3_Map.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246118695629, "lm_q2_score": 0.8596637505099167, "lm_q1q2_score": 0.7163789612320091}}
{"text": "theory Birkhoff_Finite_Distributive_Lattices\n  imports\n    \"HOL-Library.Finite_Lattice\"\n    \"HOL.Transcendental\"\nbegin\n\nunbundle lattice_syntax\n\ntext \\<open> The proof of Birkhoff's representation theorem for finite\n       distributive lattices @{cite birkhoffRingsSets1937} presented\n       here follows Davey and Priestley @{cite daveyChapterRepresentationFinite2002}. \\<close>\n\nsection \\<open> Atoms, Join Primes and Join Irreducibles \\label{sec:join-irreducibles} \\<close>\n\ntext \\<open> Atomic elements are defined as follows. \\<close>\n\ndefinition (in bounded_lattice_bot) atomic :: \"'a \\<Rightarrow> bool\" where\n  \"atomic x \\<equiv> x \\<noteq> \\<bottom> \\<and> (\\<forall> y. y \\<le> x \\<longrightarrow> y = \\<bottom> \\<or> y = x)\"\n\ntext \\<open> Two related concepts are \\<^emph>\\<open>join-prime\\<close> elements and \\<^emph>\\<open>join-irreducible\\<close> \n       elements. \\<close>\n\ndefinition (in bounded_lattice_bot) join_prime :: \"'a \\<Rightarrow> bool\" where\n  \"join_prime x \\<equiv> x \\<noteq> \\<bottom> \\<and> (\\<forall> y z . x \\<le> y \\<squnion> z \\<longrightarrow> x \\<le> y \\<or> x \\<le> z)\"\n\ndefinition (in bounded_lattice_bot) join_irreducible :: \"'a \\<Rightarrow> bool\" where\n  \"join_irreducible x \\<equiv> x \\<noteq> \\<bottom> \\<and> (\\<forall> y z . y < x \\<longrightarrow> z < x \\<longrightarrow> y \\<squnion> z < x)\"\n\nlemma (in bounded_lattice_bot) join_irreducible_def':\n  \"join_irreducible x = (x \\<noteq> \\<bottom> \\<and> (\\<forall> y z . x = y \\<squnion> z \\<longrightarrow> x = y \\<or> x = z))\"\n  unfolding join_irreducible_def\n  by (metis \n        nless_le\n        sup.bounded_iff\n        sup.cobounded1\n        sup_ge2)\n\ntext \\<open> Every join-prime is also join-irreducible. \\<close>\n\nlemma (in bounded_lattice_bot) join_prime_implies_join_irreducible:\n  assumes \"join_prime x\"\n  shows \"join_irreducible x\"\n  using assms\n  unfolding \n    join_irreducible_def' \n    join_prime_def\n  by (simp add: dual_order.eq_iff)\n\ntext \\<open> In the special case when the underlying lattice is\n       distributive, the join-prime elements and join-irreducible\n       elements coincide. \\<close>\n\nclass bounded_distrib_lattice_bot = bounded_lattice_bot +\n  assumes sup_inf_distrib1: \"x \\<squnion> (y \\<sqinter> z) = (x \\<squnion> y) \\<sqinter> (x \\<squnion> z)\"\nbegin\n\nsubclass distrib_lattice\n  by (unfold_locales, metis (full_types) sup_inf_distrib1)\n\nend\n\ncontext complete_distrib_lattice\nbegin\n\nsubclass bounded_distrib_lattice_bot\n  by (unfold_locales, \n      metis (full_types) \n        sup_inf_distrib1)\n\nend\n\nlemma (in bounded_distrib_lattice_bot) join_irreducible_is_join_prime:\n  \"join_irreducible x = join_prime x\"\nproof\n  assume \"join_prime x\"\n  thus \"join_irreducible x\"\n    by (simp add: join_prime_implies_join_irreducible)\nnext\n  assume \"join_irreducible x\"\n  {\n    fix y z\n    assume \"x \\<le> y \\<squnion> z\"\n    hence \"x = x \\<sqinter> (y \\<squnion> z)\"\n      by (metis local.inf.orderE)\n    hence \"x = (x \\<sqinter> y) \\<squnion> (x \\<sqinter> z)\"\n      using inf_sup_distrib1 by auto\n    hence \"(x = x \\<sqinter> y) \\<or> (x = x \\<sqinter> z)\"\n      using \\<open>join_irreducible x\\<close>\n      unfolding join_irreducible_def'\n      by metis\n    hence \"(x \\<le> y) \\<or> (x \\<le> z)\"\n      by (metis (full_types) local.inf.cobounded2)\n  }\n  thus \"join_prime x\"\n    by (metis \n          \\<open>join_irreducible x\\<close> \n          join_irreducible_def' \n          join_prime_def)\nqed\n\ntext \\<open> Every atomic element is join-irreducible. \\<close>\n\nlemma (in bounded_lattice_bot) atomic_implies_join_prime:\n  assumes \"atomic x\"\n  shows \"join_irreducible x\"\n  using assms\n  unfolding \n    atomic_def \n    join_irreducible_def'\n  by (metis (no_types, opaque_lifting) \n        sup.cobounded2 \n        sup_bot.right_neutral)   \n\ntext \\<open> In the case of Boolean algebras, atomic elements and\n       join-prime elements are one-in-the-same. \\<close>\n\nlemma (in boolean_algebra) join_prime_is_atomic:\n  \"atomic x = join_prime x\"\nproof\n  assume \"atomic x\"\n  {\n    fix y z\n    assume \"x \\<le> y \\<squnion> z\"\n    hence \"x = (x \\<sqinter> y) \\<squnion> (x \\<sqinter> z)\"\n      using inf.absorb1 inf_sup_distrib1 by fastforce\n    moreover\n    have \"x \\<le> y \\<or> (x \\<sqinter> y) = \\<bottom>\"\n         \"x \\<le> z \\<or> (x \\<sqinter> z) = \\<bottom>\"\n      using \\<open>atomic x\\<close> inf.cobounded1 inf.cobounded2\n      unfolding atomic_def\n      by fastforce+\n    ultimately have \"x \\<le> y \\<or> x \\<le> z\"\n      using \\<open>atomic x\\<close> atomic_def by auto\n  }\n  thus \"join_prime x\"\n    using \\<open>atomic x\\<close> join_prime_def atomic_def\n    by auto\nnext\n  assume \"join_prime x\"\n  {\n    fix y\n    assume \"y \\<le> x\" \"y \\<noteq> x\"\n    hence \"x = x \\<squnion> y\"\n      using sup.orderE by blast\n    also have \"\\<dots> = (x \\<squnion> y) \\<sqinter> (y \\<squnion> -y)\"\n      by simp\n    finally have \"x = (x \\<sqinter> -y) \\<squnion> y\"\n      by (simp add: sup_inf_distrib2)\n    hence \"x \\<le> -y\"\n      using \n        \\<open>join_prime x\\<close>\n        \\<open>y \\<noteq> x\\<close> \n        \\<open>y \\<le> x\\<close>\n        antisym_conv\n        inf_le2\n        sup_neg_inf \n      unfolding join_prime_def\n      by blast\n    hence \"y \\<le> y \\<sqinter> -y\"\n      by (metis\n            \\<open>x = x \\<squnion> y\\<close>\n            inf.orderE\n            inf_compl_bot_right\n            inf_sup_absorb\n            order_refl\n            sup.commute)\n    hence \"y = \\<bottom>\"\n      using sup_absorb2 by fastforce\n  }\n  thus \"atomic x\" \n    using \\<open>join_prime x\\<close>\n    unfolding \n      atomic_def\n      join_prime_def \n    by auto\nqed\n\ntext \\<open> All atomic elements are disjoint. \\<close>\n\nlemma (in bounded_lattice_bot) atomic_disjoint:\n  assumes \"atomic \\<alpha>\"\n      and \"atomic \\<beta>\"\n    shows \"(\\<alpha> = \\<beta>) \\<longleftrightarrow> (\\<alpha> \\<sqinter> \\<beta> \\<noteq> \\<bottom>)\"\nproof\n  assume \"\\<alpha> = \\<beta>\"\n  hence \"\\<alpha> \\<sqinter> \\<beta> = \\<alpha>\"\n    by simp\n  thus \"\\<alpha> \\<sqinter> \\<beta> \\<noteq> \\<bottom>\"\n    using \\<open>atomic \\<alpha>\\<close>\n    unfolding atomic_def\n    by auto\nnext\n  assume \"\\<alpha> \\<sqinter> \\<beta> \\<noteq> \\<bottom>\"\n  hence \"\\<beta> \\<le> \\<alpha> \\<and> \\<alpha> \\<le> \\<beta>\"\n    by (metis \n          assms \n          atomic_def \n          inf_absorb2 \n          inf_le1 \n          inf_le2)\n  thus \"\\<alpha> = \\<beta>\" by auto\nqed\n\ndefinition (in bounded_lattice_bot) atomic_elements (\"\\<A>\") where\n  \"\\<A> \\<equiv> {a . atomic a}\"\n\ndefinition (in bounded_lattice_bot) join_irreducible_elements (\"\\<J>\") where\n  \"\\<J> \\<equiv> {a . join_irreducible a}\"\n\nsection \\<open> Birkhoff's Representation Theorem For Finite Distributive Lattices \\label{section:birkhoffs-theorem} \\<close>\n\ntext \\<open> Birkhoff's representation theorem for finite distributive\n       lattices follows from the fact that every non-\\<open>\\<bottom>\\<close> element\n       can be represented by the join-irreducible elements beneath it. \\<close>\n\ntext \\<open> In this section we merely demonstrate the representation aspect of\n       Birkhoff's theorem. In \\S\\ref{section:isomorphism} we show this \n       representation is a lattice homomorphism. \\<close>\n\ntext \\<open> The fist step to representing elements is to show that there \\<^emph>\\<open>exist\\<close>\n       join-irreducible elements beneath them. This is done by showing if there is \n       no join-irreducible element, we can make a descending chain with more elements \n       than the finite Boolean algebra under consideration. \\<close>\n\nfun (in order) descending_chain_list :: \"'a list \\<Rightarrow> bool\" where\n  \"descending_chain_list [] = True\"\n| \"descending_chain_list [x] = True\"\n| \"descending_chain_list (x # x' # xs)\n     = (x < x' \\<and> descending_chain_list (x' # xs))\"\n\nlemma (in order) descending_chain_list_tail:\n  assumes \"descending_chain_list (s # S)\"\n  shows \"descending_chain_list S\"\n  using assms\n  by (induct S, auto)\n\nlemma (in order) descending_chain_list_drop_penultimate:\n  assumes \"descending_chain_list (s # s' # S)\"\n  shows \"descending_chain_list (s # S)\"\n  using assms\n  by (induct S, simp, auto)\n\nlemma (in order) descending_chain_list_less_than_others:\n  assumes \"descending_chain_list (s # S)\"\n  shows   \"\\<forall>s' \\<in> set S. s < s'\"\n  using assms\n  by (induct S, \n        auto, \n        simp add: descending_chain_list_drop_penultimate)\n\nlemma (in order) descending_chain_list_distinct:\n  assumes \"descending_chain_list S\"\n  shows \"distinct S\"\n  using assms\n  by (induct S,\n      simp,\n      meson\n        descending_chain_list_less_than_others\n        descending_chain_list_tail\n        distinct.simps(2)\n        less_irrefl)\n\nlemma (in finite_distrib_lattice) join_irreducible_lower_bound_exists:\n  assumes \"\\<not> (x \\<le> y)\"\n  shows \"\\<exists> z \\<in> \\<J>. z \\<le> x \\<and> \\<not> (z \\<le> y)\"\nproof (rule ccontr)\n  assume \\<star>: \"\\<not> (\\<exists> z \\<in> \\<J>. z \\<le> x \\<and> \\<not> (z \\<le> y))\"\n  {\n    fix z :: 'a\n    assume \n      \"z \\<le> x\"\n      \"\\<not> (z \\<le> y)\"\n    with \\<star> obtain p q where\n        \"p < z\"\n        \"q < z\"\n        \"p \\<squnion> q = z\"\n      by (metis (full_types) \n            bot_least\n            dual_order.not_eq_order_implies_strict\n            join_irreducible_def'\n            join_irreducible_elements_def\n            sup_ge1\n            sup_ge2 \n            mem_Collect_eq)\n    hence \"\\<not> (p \\<le> y) \\<or> \\<not> (q \\<le> y)\"\n      by (metis (full_types) \\<open>\\<not> z \\<le> y\\<close> sup_least)\n    hence \"\\<exists> p < z. \\<not> (p \\<le> y)\"\n      by (metis \\<open>p < z\\<close> \\<open>q < z\\<close>)\n  }\n  note fresh = this\n  {\n    fix n :: nat\n    have \"\\<exists> S . descending_chain_list S\n                  \\<and> length S = n\n                  \\<and> (\\<forall>s \\<in> set S. s \\<le> x \\<and> \\<not> (s \\<le> y))\"\n    proof (induct n)\n      case 0\n      then show ?case by simp\n    next\n      case (Suc n)\n      then show ?case proof (cases \"n = 0\")\n        case True\n        hence \"descending_chain_list [x]\n                 \\<and> length [x] = Suc n\n                 \\<and> (\\<forall>s \\<in> set [x]. s \\<le> x \\<and> \\<not> (s \\<le> y))\"\n          by (metis \n                Suc \n                assms \n                length_0_conv \n                length_Suc_conv \n                descending_chain_list.simps(2)\n                le_less set_ConsD)\n        then show ?thesis\n          by blast\n      next\n        case False\n        from this obtain s S where\n            \"descending_chain_list (s # S)\"\n            \"length (s # S) = n\"\n            \"\\<forall>s \\<in> set (s # S). s \\<le> x \\<and> \\<not> (s \\<le> y)\"\n          using \n            Suc.hyps \n            length_0_conv \n            descending_chain_list.elims(2)\n          by metis\n        note A = this\n        hence \"s \\<le> x\" \"\\<not> (s \\<le> y)\" by auto\n        obtain s' :: 'a where\n          \"s' < s\"\n          \"\\<not> (s' \\<le> y)\"\n          using \n            fresh [OF \\<open>s \\<le> x\\<close> \\<open>\\<not> (s \\<le> y)\\<close>]\n          by auto\n        note B = this\n        let ?S' = \"s' # s # S\"\n        from A and B have\n          \"descending_chain_list ?S'\"\n          \"length ?S' = Suc n\"\n          \"\\<forall>s \\<in> set ?S'. s \\<le> x \\<and> \\<not> (s \\<le> y)\"\n            by auto\n        then show ?thesis by blast\n      qed\n    qed\n  }\n  from this obtain S :: \"'a list\" where\n    \"descending_chain_list S\"\n    \"length S = 1 + (card (UNIV::'a set))\"\n    by auto\n  hence \"card (set S) = 1 + (card (UNIV::'a set))\"\n    using descending_chain_list_distinct\n          distinct_card\n    by fastforce\n  hence \"\\<not> card (set S) \\<le> card (UNIV::'a set)\"\n    by presburger\n  thus \"False\"\n    using card_mono finite_UNIV by blast\nqed\n\ndefinition (in bounded_lattice_bot)\n  join_irreducibles_embedding :: \"'a \\<Rightarrow> 'a set\" (\"\\<lbrace> _ \\<rbrace>\" [50]) where\n  \"\\<lbrace> x \\<rbrace> \\<equiv> {a \\<in> \\<J>. a \\<le> x}\"\n\ntext \\<open> We can now show every element is exactly the suprema of the \n       join-irreducible elements beneath them in any distributive lattice. \\<close>\n\ntheorem (in finite_distrib_lattice) sup_join_prime_embedding_ident:\n   \"x = \\<Squnion> \\<lbrace> x \\<rbrace>\"\nproof -\n  have \"\\<forall> a \\<in> \\<lbrace> x \\<rbrace>. a \\<le> x\"\n    by (metis (no_types, lifting) \n          join_irreducibles_embedding_def \n          mem_Collect_eq)\n  hence \"\\<Squnion> \\<lbrace> x \\<rbrace> \\<le> x\"\n    by (simp add: Sup_least)\n  moreover\n  {\n    fix y :: 'a\n    assume \"\\<Squnion> \\<lbrace> x \\<rbrace> \\<le> y\"\n    have \"x \\<le> y\"\n    proof (rule ccontr)\n      assume \"\\<not> x \\<le> y\"\n      from this obtain a where\n          \"a \\<in> \\<J>\"\n          \"a \\<le> x\"\n          \"\\<not> a \\<le> y\"\n        using join_irreducible_lower_bound_exists [OF \\<open>\\<not> x \\<le> y\\<close>]\n        by metis\n      hence \"a \\<in> \\<lbrace> x \\<rbrace>\"\n        by (metis (no_types, lifting) \n              join_irreducibles_embedding_def \n              mem_Collect_eq)\n      hence \"a \\<le> y\"\n        using \\<open>\\<Squnion>\\<lbrace> x \\<rbrace> \\<le> y\\<close>\n              Sup_upper\n              order.trans\n        by blast\n      thus \"False\"\n        by (metis (full_types) \\<open>\\<not> a \\<le> y\\<close>)\n    qed\n  }\n  ultimately show ?thesis\n    using antisym_conv by blast\nqed\n\n\ntext \\<open> Just as \\<open>x = \\<Squnion> \\<lbrace> x \\<rbrace>\\<close>, the reverse is also true; \\<open>\\<lambda> x. \\<lbrace> x \\<rbrace>\\<close>\n       and \\<open>\\<lambda> S. \\<Squnion> S\\<close> are inverses where \\<open>S \\<in> \\<O>\\<J>\\<close>, the set of downsets\n       in \\<open>Pow \\<J>\\<close>. \\<close>\n\ndefinition (in bounded_lattice_bot) down_irreducibles (\"\\<O>\\<J>\") where\n  \"\\<O>\\<J> \\<equiv> { S \\<in> Pow \\<J> . (\\<exists> x . S = \\<lbrace> x \\<rbrace>) }\"\n\nlemma (in finite_distrib_lattice) join_irreducible_embedding_sup_ident:\n  assumes \"S \\<in> \\<O>\\<J>\"\n  shows \"S = \\<lbrace> \\<Squnion> S \\<rbrace>\"\nproof -\n  obtain x where\n      \"S = \\<lbrace> x \\<rbrace>\"\n    using \n      \\<open>S \\<in> \\<O>\\<J>\\<close>\n    unfolding \n      down_irreducibles_def\n    by auto\n  with \\<open>S \\<in> \\<O>\\<J>\\<close> have \"\\<forall> s \\<in> S. s \\<in> \\<J> \\<and> s \\<le> \\<Squnion> S\"\n    unfolding \n      down_irreducibles_def\n      Pow_def\n    using Sup_upper\n    by fastforce\n  hence \"S \\<subseteq> \\<lbrace> \\<Squnion> S \\<rbrace>\"\n    unfolding join_irreducibles_embedding_def\n    by blast\n  moreover\n  {\n    fix y\n    assume\n      \"y \\<in> \\<J>\"\n      \"y \\<le> \\<Squnion> S\"\n    have \"finite S\" by auto\n    from \\<open>finite S\\<close> and \\<open>y \\<le> \\<Squnion> S\\<close> have \"\\<exists> s \\<in> S. y \\<le> s\"\n    proof (induct S rule: finite_induct)\n      case empty\n      hence \"y \\<le> \\<bottom>\"\n        by (metis Sup_empty)\n      then show ?case\n        using\n          \\<open>y \\<in> \\<J>\\<close>\n        unfolding \n          join_irreducible_elements_def\n          join_irreducible_def\n        by (metis (mono_tags, lifting) \n              le_bot \n              mem_Collect_eq)\n    next\n      case (insert s S)\n      hence \"y \\<le> s \\<or> y \\<le> \\<Squnion> S\"\n        using\n          \\<open>y \\<in> \\<J>\\<close>\n        unfolding \n          join_irreducible_elements_def\n          join_irreducible_is_join_prime\n          join_prime_def\n        by auto\n      then show ?case\n        by (metis (full_types) \n              insert.hyps(3) \n              insertCI)\n    qed\n    hence \"y \\<le> x\"\n      by (metis (no_types, lifting) \n            \\<open>S = \\<lbrace> x \\<rbrace>\\<close>\n            join_irreducibles_embedding_def\n            order_trans \n            mem_Collect_eq)\n    hence \"y \\<in> S\"\n      by (metis (no_types, lifting) \n            \\<open>S = \\<lbrace> x \\<rbrace>\\<close> \n            \\<open>y \\<in> \\<J>\\<close> \n            join_irreducibles_embedding_def \n            mem_Collect_eq)\n  }\n  hence \"\\<lbrace> \\<Squnion> S \\<rbrace> \\<subseteq> S\"\n    unfolding \n      join_irreducibles_embedding_def\n    by blast\n  ultimately show ?thesis by auto\nqed\n\ntext \\<open> Given that \\<open>\\<lambda> x. \\<lbrace> x \\<rbrace>\\<close> has a left and right inverse, we can show\n       it is a \\<^emph>\\<open>bijection\\<close>. \\<close>\n\ntext \\<open> The bijection below is recognizable as a form of \\<^emph>\\<open>Birkhoff's Representation Theorem\\<close> \n       for finite distributive lattices. \\<close>\n\ntheorem (in finite_distrib_lattice) birkhoffs_theorem:\n  \"bij_betw (\\<lambda> x. \\<lbrace> x \\<rbrace>) UNIV \\<O>\\<J>\"\n  unfolding bij_betw_def\nproof\n  {\n    fix x y\n    assume \"\\<lbrace> x \\<rbrace> = \\<lbrace> y \\<rbrace>\"\n    hence \"\\<Squnion> \\<lbrace> x \\<rbrace> = \\<Squnion> \\<lbrace> y \\<rbrace>\"\n      by simp\n    hence \"x = y\"\n      using sup_join_prime_embedding_ident\n      by auto\n  }\n  thus \"inj (\\<lambda> x. \\<lbrace> x \\<rbrace>)\"\n    unfolding inj_def\n    by auto\nnext\n  show \"range (\\<lambda> x. \\<lbrace> x \\<rbrace>) = \\<O>\\<J>\"\n    unfolding \n      down_irreducibles_def\n      join_irreducibles_embedding_def\n    by auto\nqed\n\nsection \\<open> Finite Ditributive Lattice Isomorphism \\label{section:isomorphism} \\<close>\n\ntext \\<open> The form of Birkhoff's theorem presented in \\S\\ref{section:birkhoffs-theorem}\n       simply gave a bijection between a finite distributive lattice and the\n       downsets of its join-irreducible elements. This relationship can be\n       extended to a full-blown \\<^emph>\\<open>lattice homomorphism\\<close>. In particular\n       we have the following properties:\n\n       \\<^item> \\<open>\\<bottom>\\<close> and \\<open>\\<top>\\<close> are preserved; specifically \\<open>\\<lbrace> \\<bottom> \\<rbrace> = {}\\<close> and\n         \\<open>\\<lbrace> \\<top> \\<rbrace> = \\<J>\\<close>.\n\n       \\<^item> Order is preserved: \\<open>x \\<le> y = (\\<lbrace> x \\<rbrace> \\<subseteq> \\<lbrace> y \\<rbrace>)\\<close>.\n\n       \\<^item> \\<open>\\<lambda> x . \\<lbrace> x \\<rbrace>\\<close> is a lower complete semi-lattice homomorphism, mapping\n         \\<open>\\<lbrace> \\<Squnion> X \\<rbrace> = (\\<Union> x \\<in> X . \\<lbrace> x \\<rbrace>)\\<close>.\n\n       \\<^item> In addition to preserving arbitrary joins, \\<open>\\<lambda> x . \\<lbrace> x \\<rbrace>\\<close> is a\n         lattice homomorphism, since it also preserves finitary meets with\n         \\<open> \\<lbrace> x \\<sqinter> y \\<rbrace> = \\<lbrace> x \\<rbrace> \\<inter> \\<lbrace> y \\<rbrace> \\<close>. Arbitrary meets are also preserved, \n         but relative to a top element \\<open>\\<J>\\<close>, or in other words \n         \\<open> \\<lbrace> \\<Sqinter> X \\<rbrace> = \\<J> \\<inter> (\\<Inter> x \\<in> X. \\<lbrace> x \\<rbrace>) \\<close>.\n\n       \\<^item> In the case of a Boolean algebra, complementation corresponds to \n         relative set complementation via \\<open>\\<lbrace> - x \\<rbrace> = \\<J> - \\<lbrace> x \\<rbrace>\\<close>.\n\\<close>\n\nlemma (in finite_distrib_lattice) join_irreducibles_bot:\n  \"\\<lbrace> \\<bottom> \\<rbrace> = {}\"\n  unfolding\n    join_irreducibles_embedding_def\n    join_irreducible_elements_def\n    join_irreducible_is_join_prime\n    join_prime_def\n  by (simp add: bot_unique)\n\nlemma (in finite_distrib_lattice) join_irreducibles_top:\n  \"\\<lbrace> \\<top> \\<rbrace> = \\<J>\"\n  unfolding\n    join_irreducibles_embedding_def\n    join_irreducible_elements_def\n    join_irreducible_is_join_prime\n    join_prime_def\n  by auto\n\nlemma (in finite_distrib_lattice) join_irreducibles_order_isomorphism:\n  \"x \\<le> y = (\\<lbrace> x \\<rbrace> \\<subseteq> \\<lbrace> y \\<rbrace>)\"\n  by (rule iffI, \n        metis (mono_tags, lifting) \n          join_irreducibles_embedding_def \n          order_trans \n          mem_Collect_eq \n          subsetI,\n        metis (full_types) \n          Sup_subset_mono \n          sup_join_prime_embedding_ident)\n\nlemma (in finite_distrib_lattice) join_irreducibles_join_homomorphism:\n  \"\\<lbrace> x \\<squnion> y \\<rbrace> = \\<lbrace> x \\<rbrace> \\<union> \\<lbrace> y \\<rbrace>\"\nproof\n  show \"\\<lbrace> x \\<squnion> y \\<rbrace> \\<subseteq> \\<lbrace> x \\<rbrace> \\<union> \\<lbrace> y \\<rbrace>\"\n    unfolding\n      join_irreducibles_embedding_def\n      join_irreducible_elements_def\n      join_irreducible_is_join_prime\n      join_prime_def\n    by blast\nnext\n  show \"\\<lbrace> x \\<rbrace> \\<union> \\<lbrace> y \\<rbrace> \\<subseteq> \\<lbrace> x \\<squnion> y \\<rbrace>\"\n    unfolding\n      join_irreducibles_embedding_def\n      join_irreducible_elements_def\n      join_irreducible_is_join_prime\n      join_prime_def\n    using\n      le_supI1\n      sup.absorb_iff1\n      sup.assoc\n    by force\nqed\n\nlemma (in finite_distrib_lattice) join_irreducibles_sup_homomorphism:\n  \"\\<lbrace> \\<Squnion> X \\<rbrace> = (\\<Union> x \\<in> X . \\<lbrace> x \\<rbrace>)\"\nproof -\n  have \"finite X\"\n    by simp\n  thus ?thesis\n  proof (induct X rule: finite_induct)\n    case empty\n    then show ?case by (simp add: join_irreducibles_bot)\n  next\n    case (insert x X)\n    then show ?case by (simp add: join_irreducibles_join_homomorphism)\n  qed\nqed\n\n\nlemma (in finite_distrib_lattice) join_irreducibles_meet_homomorphism:\n  \"\\<lbrace> x \\<sqinter> y \\<rbrace> = \\<lbrace> x \\<rbrace> \\<inter> \\<lbrace> y \\<rbrace>\"\n  unfolding\n    join_irreducibles_embedding_def\n  by auto\n\ntext \\<open> Arbitrary meets are also preserved, but relative to a top element \\<open>\\<J>\\<close>. \\<close>\n\nlemma (in finite_distrib_lattice) join_irreducibles_inf_homomorphism:\n  \"\\<lbrace> \\<Sqinter> X \\<rbrace> = \\<J> \\<inter> (\\<Inter> x \\<in> X. \\<lbrace> x \\<rbrace>)\"\nproof -\n  have \"finite X\"\n    by simp\n  thus ?thesis\n  proof (induct X rule: finite_induct)\n    case empty\n    then show ?case by (simp add: join_irreducibles_top)\n  next\n    case (insert x X)\n    then show ?case by (simp add: join_irreducibles_meet_homomorphism, blast)\n  qed\nqed\n\ntext \\<open> Finally, we show that complementation is preserved. \\<close>\n\ntext \\<open> To begin, we define the class of finite Boolean algebras.\n       This class is simply an extension of @{class boolean_algebra},\n       extended with \\<^term>\\<open>finite UNIV\\<close> as per the axiom class @{class finite}. We also\n       also extend the language of the class with \\<^emph>\\<open>infima\\<close> and \\<^emph>\\<open>suprema\\<close> \n       (i.e. \\<open>\\<Sqinter> A\\<close> and \\<open>\\<Squnion> A\\<close> respectively). \\<close>\n\nclass finite_boolean_algebra = boolean_algebra + finite + Inf + Sup +\n  assumes Inf_def: \"\\<Sqinter> A = Finite_Set.fold (\\<sqinter>) \\<top> A\"\n  assumes Sup_def: \"\\<Squnion> A = Finite_Set.fold (\\<squnion>) \\<bottom> A\"\nbegin\n\ntext \\<open> Finite Boolean algebras are trivially a subclass of finite\n       distributive lattices, which are necessarily \\<^emph>\\<open>complete\\<close>. \\<close>\n\nsubclass finite_distrib_lattice_complete\n  using\n    Inf_fin.coboundedI\n    Sup_fin.coboundedI\n    finite_UNIV\n    le_bot\n    top_unique\n    Inf_def\n    Sup_def\n  by (unfold_locales, blast, fastforce+)\n\nsubclass bounded_distrib_lattice_bot\n  by (unfold_locales, metis sup_inf_distrib1)\nend\n\nlemma (in finite_boolean_algebra) join_irreducibles_complement_homomorphism:\n  \"\\<lbrace> - x \\<rbrace> = \\<J> - \\<lbrace> x \\<rbrace>\"\nproof\n  show \"\\<lbrace> - x \\<rbrace> \\<subseteq> \\<J> - \\<lbrace> x \\<rbrace>\"\n  proof\n    fix j\n    assume \"j \\<in> \\<lbrace> - x \\<rbrace>\"\n    hence \"j \\<notin> \\<lbrace> x \\<rbrace>\"\n      unfolding\n        join_irreducibles_embedding_def\n        join_irreducible_elements_def\n        join_irreducible_is_join_prime\n        join_prime_def\n      by (metis\n            (mono_tags, lifting)\n            CollectD\n            bot_unique\n            inf.boundedI\n            inf_compl_bot)\n    thus \"j \\<in> \\<J> - \\<lbrace> x \\<rbrace>\"\n      using \\<open>j \\<in> \\<lbrace> - x \\<rbrace>\\<close>\n      unfolding\n        join_irreducibles_embedding_def\n      by blast\n  qed\nnext\n  show \"\\<J> - \\<lbrace> x \\<rbrace> \\<subseteq> \\<lbrace> - x \\<rbrace>\"\n  proof\n    fix j\n    assume \"j \\<in> \\<J> - \\<lbrace> x \\<rbrace>\"\n    hence \"j \\<in> \\<J>\" and \"\\<not> j \\<le> x\"\n      unfolding join_irreducibles_embedding_def\n      by blast+\n    moreover have \"j \\<le> x \\<squnion> -x\"\n      by auto\n    ultimately have \"j \\<le> -x\"\n      unfolding\n        join_irreducible_elements_def\n        join_irreducible_is_join_prime\n        join_prime_def\n      by blast\n    thus \"j \\<in> \\<lbrace> - x \\<rbrace>\"\n      unfolding join_irreducibles_embedding_def\n      using \\<open>j \\<in> \\<J>\\<close>\n      by auto\n  qed\nqed\n\n\nsection \\<open> Cardinality \\<close>\n\ntext \\<open> Another consequence of Birkhoff's theorem from \\S\\ref{section:birkhoffs-theorem}\n       is that every finite Boolean algebra has a cardinality which is \n       a power of two. This gives a bound on the number of \n       atoms/join-prime/irreducible elements, which must be logarithmic in \n       the size of the finite Boolean algebra they belong to. \\<close>\n\ntext \\<open> We first show that \\<open>\\<O>\\<J>\\<close>, the downsets of the join-irreducible elements \n       \\<open>\\<J>\\<close>, are the same as the powerset of \\<open>\\<J>\\<close> in any finite Boolean algebra. \\<close>\n\nlemma (in finite_boolean_algebra) \\<O>\\<J>_is_Pow_\\<J>:\n  \"\\<O>\\<J> = Pow \\<J>\"\nproof\n  show \"\\<O>\\<J> \\<subseteq> Pow \\<J>\"\n    unfolding down_irreducibles_def\n    by auto\nnext\n  show \"Pow \\<J> \\<subseteq> \\<O>\\<J>\"\n  proof (rule ccontr)\n    assume \"\\<not> Pow \\<J> \\<subseteq> \\<O>\\<J>\"\n    from this obtain S where\n        \"S \\<subseteq> \\<J>\"\n        \"\\<forall> x. S \\<noteq> {a \\<in> \\<J>. a \\<le> x}\"\n      unfolding \n        down_irreducibles_def\n        join_irreducibles_embedding_def\n      by auto\n    hence \"S \\<noteq> {a \\<in> \\<J>. a \\<le> \\<Squnion> S}\"\n      by auto\n    moreover \n    have \"\\<forall> s \\<in> S . s \\<in> \\<J> \\<and> s \\<le> \\<Squnion> S\"\n      by (metis (no_types, lifting) \n            \\<open>S \\<subseteq> \\<J>\\<close> \n            Sup_upper subsetD)\n    hence \"S \\<subseteq> {a \\<in> \\<J>. a \\<le> \\<Squnion> S}\"\n      by (metis (mono_tags, lifting) Ball_Collect)\n    ultimately have \"\\<exists> y \\<in> \\<J> . y \\<le> \\<Squnion> S \\<and> y \\<notin> S\"\n      by (metis (mono_tags, lifting) \n            mem_Collect_eq \n            subsetI \n            subset_antisym)\n    moreover\n    {\n      fix y\n      assume \n        \"y \\<in> \\<J>\"\n        \"y \\<le> \\<Squnion> S\"\n      from \n        finite [of S]\n        \\<open>y \\<le> \\<Squnion> S\\<close>\n        \\<open>S \\<subseteq> \\<J>\\<close>\n      have \"y \\<in> S\"\n      proof (induct S rule: finite_induct)\n        case empty\n        hence \"y \\<le> \\<bottom>\"\n          by (metis (full_types) local.Sup_empty)\n        then show ?case\n          using \\<open>y \\<in> \\<J>\\<close>\n          unfolding \n            join_irreducible_elements_def\n            join_irreducible_def\n          by (metis (mono_tags, lifting) \n                le_bot \n                mem_Collect_eq)\n      next\n        case (insert s S)\n        hence \"y \\<le> s \\<or> y \\<le> \\<Squnion> S\"\n          using \\<open>y \\<in> \\<J>\\<close>\n          unfolding \n            join_irreducible_elements_def\n            join_irreducible_is_join_prime\n            join_prime_def\n          by simp\n        moreover\n        {\n          assume \"y \\<le> s\"\n          have \"atomic s\"\n            by (metis in_mono \n                  insert.prems(2) \n                  insertCI \n                  join_irreducible_elements_def \n                  join_irreducible_is_join_prime \n                  join_prime_is_atomic \n                  mem_Collect_eq)\n          hence \"y = s\"\n            by (metis (no_types, lifting) \n                  \\<open>y \\<in> \\<J>\\<close> \n                  \\<open>y \\<le> s\\<close> \n                  atomic_def \n                  join_irreducible_def \n                  join_irreducible_elements_def \n                  mem_Collect_eq)\n        }\n        ultimately show ?case\n          by (metis   \n                insert.prems(2) \n                insert_iff \n                insert_subset \n                insert(3))\n      qed\n    }\n    ultimately show False by auto\n  qed\nqed\n  \n\nlemma (in finite_boolean_algebra) UNIV_card:\n  \"card (UNIV::'a set) = card (Pow \\<J>)\"\n  using \n    bij_betw_same_card [where f=\"\\<lambda>x. \\<lbrace> x \\<rbrace>\"]\n    birkhoffs_theorem\n  unfolding \n    \\<O>\\<J>_is_Pow_\\<J>\n  by blast\n\nlemma finite_Pow_card:\n  assumes \"finite X\"\n  shows \"card (Pow X) = 2 powr (card X)\"\n  using assms\nproof (induct X rule: finite_induct)\n  case empty\n  then show ?case by fastforce\nnext\n  case (insert x X)\n  have \"0 \\<le> (2 :: real)\" by auto\n  hence two_powr_one: \"(2 :: real) = 2 powr 1\" by fastforce\n  have \"bij_betw (\\<lambda> x. fst x \\<union> snd x) ({{},{x}} \\<times> Pow X) (Pow (insert x X))\"\n    unfolding bij_betw_def\n  proof\n    {\n      fix y z\n      assume \n        \"y \\<in> {{}, {x}} \\<times> Pow X\"\n        \"z \\<in> {{}, {x}} \\<times> Pow X\"\n        \"fst y \\<union> snd y = fst z \\<union> snd z\"\n        (is \"?Uy = ?Uz\")\n      hence \n          \"x \\<notin> snd y\"\n          \"x \\<notin> snd z\"\n          \"fst y = {x} \\<or> fst y = {}\"\n          \"fst z = {x} \\<or> fst z = {}\"\n        using insert.hyps(2) by auto\n      hence \n          \"x \\<in> ?Uy \\<longleftrightarrow> fst y = {x}\"\n          \"x \\<in> ?Uz \\<longleftrightarrow> fst z = {x}\"\n          \"x \\<notin> ?Uy \\<longleftrightarrow> fst y = {}\"\n          \"x \\<notin> ?Uz \\<longleftrightarrow> fst z = {}\"\n          \"snd y = ?Uy - {x}\"\n          \"snd z = ?Uz - {x}\"\n        by auto\n      hence \n          \"x \\<in> ?Uy \\<longleftrightarrow> y = ({x}, ?Uy - {x})\"\n          \"x \\<in> ?Uz \\<longleftrightarrow> z = ({x}, ?Uz - {x})\"\n          \"x \\<notin> ?Uy \\<longleftrightarrow> y = ({}, ?Uy - {x})\"\n          \"x \\<notin> ?Uz \\<longleftrightarrow> z = ({}, ?Uz - {x})\"\n        by (metis fst_conv prod.collapse)+\n      hence \"y = z\"\n        using \\<open>?Uy = ?Uz\\<close>\n        by metis\n    }\n    thus \"inj_on (\\<lambda>x. fst x \\<union> snd x) ({{}, {x}} \\<times> Pow X)\"\n      unfolding inj_on_def\n      by auto\n  next\n    show \"(\\<lambda>x. fst x \\<union> snd x) ` ({{}, {x}} \\<times> Pow X) = Pow (insert x X)\"\n    proof (intro equalityI subsetI)\n      fix y\n      assume \"y \\<in> (\\<lambda>x. fst x \\<union> snd x) ` ({{}, {x}} \\<times> Pow X)\"\n      from this obtain z where\n         \"z \\<in> ({{}, {x}} \\<times> Pow X)\"\n         \"y = fst z \\<union> snd z\"\n        by auto\n      hence \n          \"snd z \\<subseteq> X\"\n          \"fst z \\<subseteq> insert x X\"\n        using SigmaE by auto\n      thus \"y \\<in> Pow (insert x X)\"\n        using \\<open>y = fst z \\<union> snd z\\<close> by blast\n    next\n      fix y\n      assume \"y \\<in> Pow (insert x X)\"\n      let ?z = \"(if x \\<in> y then {x} else {}, y - {x})\"\n      have \"?z \\<in> ({{}, {x}} \\<times> Pow X)\"\n        using \\<open>y \\<in> Pow (insert x X)\\<close> by auto\n      moreover have \"(\\<lambda>x. fst x \\<union> snd x) ?z = y\"\n        by auto\n      ultimately show \"y \\<in> (\\<lambda>x. fst x \\<union> snd x) ` ({{}, {x}} \\<times> Pow X)\"\n        by blast\n    qed\n  qed\n  hence \"card (Pow (insert x X)) = card ({{},{x}} \\<times> Pow X)\"\n    using bij_betw_same_card by fastforce\n  also have \"\\<dots> = 2 * card (Pow X)\"\n    by (simp add: insert.hyps(1))\n  also have \"\\<dots> = 2 * (2 powr (card X))\"\n    by (simp add: insert.hyps(3))\n  also have \"\\<dots> = (2 powr 1) * 2 powr (card X)\"\n    using two_powr_one\n    by fastforce\n  also have \"\\<dots> = 2 powr (1 + card X)\"\n    by (simp add: powr_add)\n  also have \"\\<dots> = 2 powr (card (insert x X))\"\n    by (simp add: insert.hyps(1) insert.hyps(2))\n  finally show ?case .\nqed\n\nlemma (in finite_boolean_algebra) UNIV_card_powr_2:\n  \"card (UNIV::'a set) = 2 powr (card \\<J>)\"\n  using \n    finite [of \\<J>]\n    finite_Pow_card [of \\<J>]\n    UNIV_card\n  by linarith\n\nlemma (in finite_boolean_algebra) join_irreducibles_card_log_2:\n  \"card \\<J> = log 2 (card (UNIV :: 'a set))\"\nproof (cases \"card (UNIV :: 'a set) = 1\")\n  case True\n  hence \"\\<exists> x :: 'a. UNIV = {x}\"\n    using card_1_singletonE by blast\n  hence \"\\<forall> x y :: 'a. x \\<in> UNIV \\<longrightarrow> y \\<in> UNIV \\<longrightarrow> x = y\"\n    by (metis (mono_tags) singletonD)\n  hence \"\\<forall> x y :: 'a. x = y\"\n    by blast\n  hence \"\\<forall> x. x = \\<bottom>\"\n    by blast\n  hence \"\\<J> = {}\"\n    unfolding \n      join_irreducible_elements_def\n      join_irreducible_is_join_prime\n      join_prime_def\n    by blast\n  hence \"card \\<J> = (0 :: real)\"\n    by simp\n  moreover\n  have \"log 2 (card (UNIV :: 'a set)) = 0\"\n    by (simp add: True)\n  ultimately show ?thesis by auto\nnext\n  case False\n  hence \"0 < 2 powr (card \\<J>)\" \"2 powr (card \\<J>) \\<noteq> 1\"\n    using finite_UNIV_card_ge_0 finite UNIV_card_powr_2\n    by (simp, linarith)\n  hence \"log 2 (2 powr (card \\<J>)) = card \\<J>\"\n    by simp\n  then show ?thesis\n    using UNIV_card_powr_2\n    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/Birkhoff_Finite_Distributive_Lattices/Birkhoff_Finite_Distributive_Lattices.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8333246035907932, "lm_q2_score": 0.8596637469145054, "lm_q1q2_score": 0.7163789511189061}}
{"text": "(*  Author:  S\u00e9bastien Gou\u00ebzel   sebastien.gouezel@univ-rennes1.fr\n    License: BSD\n*)\n\nsection \\<open>Gromov hyperbolic spaces\\<close>\n\ntheory Gromov_Hyperbolicity\n  imports Isometries Metric_Completion\nbegin\n\nsubsection \\<open>Definition, basic properties\\<close>\n\ntext \\<open>Although we will mainly work with type classes later on, we introduce the definition\nof hyperbolicity on subsets of a metric space.\n\nA set is $\\delta$-hyperbolic if it satisfies the following inequality. It is very obscure at first sight,\nbut we will see several equivalent characterizations later on. For instance, a space is hyperbolic\n(maybe for a different constant $\\delta$) if all geodesic triangles are thin, i.e., every side is\nclose to the union of the two other sides. This definition captures the main features of negative\ncurvature at a large scale, and has proved extremely fruitful and influential.\n\nTwo important references on this topic are~\\<^cite>\\<open>\"ghys_hyperbolique\"\\<close> and~\\<^cite>\\<open>\"bridson_haefliger\"\\<close>.\nWe will sometimes follow them, sometimes depart from them.\\<close>\n\ndefinition Gromov_hyperbolic_subset::\"real \\<Rightarrow> ('a::metric_space) set \\<Rightarrow> bool\"\n  where \"Gromov_hyperbolic_subset delta A = (\\<forall>x\\<in>A. \\<forall>y\\<in>A. \\<forall>z\\<in>A. \\<forall>t\\<in>A. dist x y + dist z t \\<le> max (dist x z + dist y t) (dist x t + dist y z) + 2 * delta)\"\n\nlemma Gromov_hyperbolic_subsetI [intro]:\n  assumes \"\\<And>x y z t. x \\<in> A \\<Longrightarrow> y \\<in> A \\<Longrightarrow> z \\<in> A \\<Longrightarrow> t \\<in> A \\<Longrightarrow> dist x y + dist z t \\<le> max (dist x z + dist y t) (dist x t + dist y z) + 2 * delta\"\n  shows \"Gromov_hyperbolic_subset delta A\"\nusing assms unfolding Gromov_hyperbolic_subset_def by auto\n\ntext \\<open>When the four points are not all distinct, the above inequality is always satisfied for\n$\\delta = 0$.\\<close>\n\nlemma Gromov_hyperbolic_ineq_not_distinct:\n  assumes \"x = y \\<or> x = z \\<or> x = t \\<or> y = z \\<or> y = t \\<or> z = (t::'a::metric_space)\"\n  shows \"dist x y + dist z t \\<le> max (dist x z + dist y t) (dist x t + dist y z)\"\nusing assms by (auto simp add: dist_commute, simp add: dist_triangle add.commute, simp add: dist_triangle3)\n\ntext \\<open>It readily follows from the definition that hyperbolicity passes to the closure of the set.\\<close>\n\n\n\ntext \\<open>A good formulation of hyperbolicity is in terms of Gromov products. Intuitively, the\nGromov product of $x$ and $y$ based at $e$ is the distance between $e$ and the geodesic between\n$x$ and $y$. It is also the time after which the geodesics from $e$ to $x$ and from $e$ to $y$\nstop travelling together.\\<close>\n\ndefinition Gromov_product_at::\"('a::metric_space) \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> real\"\n  where \"Gromov_product_at e x y = (dist e x + dist e y - dist x y) / 2\"\n\nlemma Gromov_hyperbolic_subsetI2:\n  fixes delta::real\n  assumes \"\\<And>e x y z. e \\<in> A \\<Longrightarrow> x \\<in> A \\<Longrightarrow> y \\<in> A \\<Longrightarrow> z \\<in> A \\<Longrightarrow> Gromov_product_at (e::'a::metric_space) x z \\<ge> min (Gromov_product_at e x y) (Gromov_product_at e y z) - delta\"\n  shows \"Gromov_hyperbolic_subset delta A\"\nproof (rule Gromov_hyperbolic_subsetI)\n  fix x y z t assume H: \"x \\<in> A\" \"z \\<in> A\" \"y \\<in> A\" \"t \\<in> A\"\n  show \"dist x y + dist z t \\<le> max (dist x z + dist y t) (dist x t + dist y z) + 2 * delta\"\n    using assms[OF H] unfolding Gromov_product_at_def min_def max_def\n    by (auto simp add: divide_simps algebra_simps dist_commute)\nqed\n\nlemma Gromov_product_nonneg [simp, mono_intros]:\n  \"Gromov_product_at e x y \\<ge> 0\"\nunfolding Gromov_product_at_def by (simp add: dist_triangle3)\n\nlemma Gromov_product_commute:\n  \"Gromov_product_at e x y = Gromov_product_at e y x\"\nunfolding Gromov_product_at_def by (auto simp add: dist_commute)\n\nlemma Gromov_product_le_dist [simp, mono_intros]:\n  \"Gromov_product_at e x y \\<le> dist e x\"\n  \"Gromov_product_at e x y \\<le> dist e y\"\nunfolding Gromov_product_at_def by (auto simp add: diff_le_eq dist_triangle dist_triangle2)\n\nlemma Gromov_product_le_infdist [mono_intros]:\n  assumes \"geodesic_segment_between G x y\"\n  shows \"Gromov_product_at e x y \\<le> infdist e G\"\nproof -\n  have [simp]: \"G \\<noteq> {}\" using assms by auto\n  have \"Gromov_product_at e x y \\<le> dist e z\" if \"z \\<in> G\" for z\n  proof -\n    have \"dist e x + dist e y \\<le> (dist e z + dist z x) + (dist e z + dist z y)\"\n      by (intro add_mono dist_triangle)\n    also have \"... = 2 * dist e z + dist x y\"\n      apply (auto simp add: dist_commute) using \\<open>z \\<in> G\\<close> assms by (metis dist_commute geodesic_segment_dist)\n    finally show ?thesis unfolding Gromov_product_at_def by auto\n  qed\n  then show ?thesis\n    apply (subst infdist_notempty) by (auto intro: cINF_greatest)\nqed\n\nlemma Gromov_product_add:\n  \"Gromov_product_at e x y + Gromov_product_at x e y = dist e x\"\nunfolding Gromov_product_at_def by (auto simp add: algebra_simps divide_simps dist_commute)\n\nlemma Gromov_product_geodesic_segment:\n  assumes \"geodesic_segment_between G x y\" \"t \\<in> {0..dist x y}\"\n  shows \"Gromov_product_at x y (geodesic_segment_param G x t) = t\"\nproof -\n  have \"dist x (geodesic_segment_param G x t) = t\"\n    using assms(1) assms(2) geodesic_segment_param(6) by auto\n  moreover have \"dist y (geodesic_segment_param G x t) = dist x y - t\"\n    by (metis \\<open>dist x (geodesic_segment_param G x t) = t\\<close> add_diff_cancel_left' assms(1) assms(2) dist_commute geodesic_segment_dist geodesic_segment_param(3))\n  ultimately show ?thesis unfolding Gromov_product_at_def by auto\nqed\n\nlemma Gromov_product_e_x_x [simp]:\n  \"Gromov_product_at e x x = dist e x\"\nunfolding Gromov_product_at_def by auto\n\nlemma Gromov_product_at_diff:\n  \"\\<bar>Gromov_product_at x y z - Gromov_product_at a b c\\<bar> \\<le> dist x a + dist y b + dist z c\"\nunfolding Gromov_product_at_def abs_le_iff apply (auto simp add: divide_simps)\nby (smt dist_commute dist_triangle4)+\n\nlemma Gromov_product_at_diff1:\n  \"\\<bar>Gromov_product_at a x y - Gromov_product_at b x y\\<bar> \\<le> dist a b\"\nusing Gromov_product_at_diff[of a x y b x y] by auto\n\nlemma Gromov_product_at_diff2:\n  \"\\<bar>Gromov_product_at e x z - Gromov_product_at e y z\\<bar> \\<le> dist x y\"\nusing Gromov_product_at_diff[of e x z e y z] by auto\n\nlemma Gromov_product_at_diff3:\n  \"\\<bar>Gromov_product_at e x y - Gromov_product_at e x z\\<bar> \\<le> dist y z\"\nusing Gromov_product_at_diff[of e x y e x z] by auto\n\ntext \\<open>The Gromov product is continuous in its three variables. We formulate it in terms of sequences,\nas it is the way it will be used below (and moreover continuity for functions of several variables\nis very poor in the library).\\<close>\n\n\n\n\nsubsection \\<open>Typeclass for Gromov hyperbolic spaces\\<close>\n\ntext \\<open>We could (should?) just derive \\verb+Gromov_hyperbolic_space+ from \\verb+metric_space+.\nHowever, in this case, properties of metric spaces are not available when working in the locale!\nIt is more efficient to ensure that we have a metric space by putting a type class restriction\nin the definition. The $\\delta$ in Gromov-hyperbolicity type class is called \\verb+deltaG+ to\navoid name clashes.\n\\<close>\n\nclass metric_space_with_deltaG = metric_space +\n  fixes deltaG::\"('a::metric_space) itself \\<Rightarrow> real\"\n\nclass Gromov_hyperbolic_space = metric_space_with_deltaG +\n  assumes hyperb_quad_ineq0: \"Gromov_hyperbolic_subset (deltaG(TYPE('a::metric_space))) (UNIV::'a set)\"\n\nclass Gromov_hyperbolic_space_geodesic = Gromov_hyperbolic_space + geodesic_space\n\nlemma (in Gromov_hyperbolic_space) hyperb_quad_ineq [mono_intros]:\n  shows \"dist x y + dist z t \\<le> max (dist x z + dist y t) (dist x t + dist y z) + 2 * deltaG(TYPE('a))\"\nusing hyperb_quad_ineq0 unfolding Gromov_hyperbolic_subset_def by auto\n\ntext \\<open>It readily follows from the definition that the completion of a $\\delta$-hyperbolic\nspace is still $\\delta$-hyperbolic.\\<close>\n\ninstantiation metric_completion :: (Gromov_hyperbolic_space) Gromov_hyperbolic_space\nbegin\ndefinition deltaG_metric_completion::\"('a metric_completion) itself \\<Rightarrow> real\" where\n  \"deltaG_metric_completion _ = deltaG(TYPE('a))\"\n\ninstance proof (standard, rule Gromov_hyperbolic_subsetI)\n  have \"Gromov_hyperbolic_subset (deltaG(TYPE('a))) (range (to_metric_completion::'a \\<Rightarrow> _))\"\n    unfolding Gromov_hyperbolic_subset_def\n    apply (auto simp add: isometry_onD[OF to_metric_completion_isometry])\n    by (metis hyperb_quad_ineq)\n  then have \"Gromov_hyperbolic_subset (deltaG TYPE('a metric_completion)) (UNIV::'a metric_completion set)\"\n    unfolding deltaG_metric_completion_def to_metric_completion_dense'[symmetric]\n    using Gromov_hyperbolic_closure by auto\n  then show \"dist x y + dist z t \\<le> max (dist x z + dist y t) (dist x t + dist y z) + 2 * deltaG TYPE('a metric_completion)\"\n      for x y z t::\"'a metric_completion\"\n    unfolding Gromov_hyperbolic_subset_def by auto\nqed\nend (*of instantiation metric_completion (of Gromov_hyperbolic_space) is Gromov_hyperbolic*)\n\n\ncontext Gromov_hyperbolic_space\nbegin\n\nlemma delta_nonneg [simp, mono_intros]:\n  \"deltaG(TYPE('a)) \\<ge> 0\"\nproof -\n  obtain x::'a where True by auto\n  show ?thesis using hyperb_quad_ineq[of x x x x] by auto\nqed\n\n\n\nlemma hyperb_ineq' [mono_intros]:\n  \"Gromov_product_at (e::'a) x z + deltaG(TYPE('a)) \\<ge> min (Gromov_product_at e x y) (Gromov_product_at e y z)\"\nusing hyperb_ineq[of e x y z] by auto\n\nlemma hyperb_ineq_4_points [mono_intros]:\n  \"Min {Gromov_product_at (e::'a) x y, Gromov_product_at e y z, Gromov_product_at e z t} - 2 * deltaG(TYPE('a)) \\<le> Gromov_product_at e x t\"\nusing hyperb_ineq[of e x y z] hyperb_ineq[of e x z t] apply auto using delta_nonneg by linarith\n\nlemma hyperb_ineq_4_points' [mono_intros]:\n  \"Min {Gromov_product_at (e::'a) x y, Gromov_product_at e y z, Gromov_product_at e z t} \\<le> Gromov_product_at e x t + 2 * deltaG(TYPE('a))\"\nusing hyperb_ineq_4_points[of e x y z t] by auto\n\ntext \\<open>In Gromov-hyperbolic spaces, geodesic triangles are thin, i.e., a point on one side of a\ngeodesic triangle is close to the union of the two other sides (where the constant in \"close\"\nis $4\\delta$, independent of the size of the triangle). We prove this basic property\n(which, in fact, is a characterization of Gromov-hyperbolic spaces: a geodesic space in which\ntriangles are thin is hyperbolic).\\<close>\n\nlemma thin_triangles1:\n  assumes \"geodesic_segment_between G x y\" \"geodesic_segment_between H x (z::'a)\"\n          \"t \\<in> {0..Gromov_product_at x y z}\"\n  shows \"dist (geodesic_segment_param G x t) (geodesic_segment_param H x t) \\<le> 4 * deltaG(TYPE('a))\"\nproof -\n  have *: \"Gromov_product_at x z (geodesic_segment_param H x t) = t\"\n    apply (rule Gromov_product_geodesic_segment[OF assms(2)]) using assms(3) Gromov_product_le_dist(2)\n    by (metis atLeastatMost_subset_iff subset_iff)\n  have \"Gromov_product_at x y (geodesic_segment_param H x t)\n        \\<ge> min (Gromov_product_at x y z) (Gromov_product_at x z (geodesic_segment_param H x t)) - deltaG(TYPE('a))\"\n    by (rule hyperb_ineq)\n  then have I: \"Gromov_product_at x y (geodesic_segment_param H x t) \\<ge> t - deltaG(TYPE('a))\"\n    using assms(3) unfolding * by auto\n\n  have *: \"Gromov_product_at x (geodesic_segment_param G x t) y = t\"\n    apply (subst Gromov_product_commute)\n    apply (rule Gromov_product_geodesic_segment[OF assms(1)]) using assms(3) Gromov_product_le_dist(1)\n    by (metis atLeastatMost_subset_iff subset_iff)\n  have \"t - 2 * deltaG(TYPE('a)) = min t (t- deltaG(TYPE('a))) - deltaG(TYPE('a))\"\n    unfolding min_def using antisym by fastforce\n  also have \"... \\<le> min (Gromov_product_at x (geodesic_segment_param G x t) y) (Gromov_product_at x y (geodesic_segment_param H x t)) - deltaG(TYPE('a))\"\n    using I * by (simp add: algebra_simps)\n  also have \"... \\<le> Gromov_product_at x (geodesic_segment_param G x t) (geodesic_segment_param H x t)\"\n    by (rule hyperb_ineq)\n  finally have I: \"Gromov_product_at x (geodesic_segment_param G x t) (geodesic_segment_param H x t) \\<ge> t - 2 * deltaG(TYPE('a))\"\n    by simp\n\n  have A: \"dist x (geodesic_segment_param G x t) = t\"\n    by (meson assms(1) assms(3) atLeastatMost_subset_iff geodesic_segment_param(6) Gromov_product_le_dist(1) subset_eq)\n  have B: \"dist x (geodesic_segment_param H x t) = t\"\n    by (meson assms(2) assms(3) atLeastatMost_subset_iff geodesic_segment_param(6) Gromov_product_le_dist(2) subset_eq)\n  show ?thesis\n    using I unfolding Gromov_product_at_def A B by auto\nqed\n\ntheorem thin_triangles:\n  assumes \"geodesic_segment_between Gxy x y\"\n          \"geodesic_segment_between Gxz x z\"\n          \"geodesic_segment_between Gyz y z\"\n          \"(w::'a) \\<in> Gyz\"\n  shows \"infdist w (Gxy \\<union> Gxz) \\<le> 4 * deltaG(TYPE('a))\"\nproof -\n  obtain t where w: \"t \\<in> {0..dist y z}\" \"w = geodesic_segment_param Gyz y t\"\n    using geodesic_segment_param[OF assms(3)] assms(4) by (metis imageE)\n  show ?thesis\n  proof (cases \"t \\<le> Gromov_product_at y x z\")\n    case True\n    have *: \"dist w (geodesic_segment_param Gxy y t) \\<le> 4 * deltaG(TYPE('a))\" unfolding w(2)\n      apply (rule thin_triangles1[of _ _ z _ x])\n      using True assms(1) assms(3) w(1) by (auto simp add: geodesic_segment_commute Gromov_product_commute)\n    show ?thesis\n      apply (rule infdist_le2[OF _ *])\n      by (metis True assms(1) box_real(2) geodesic_segment_commute geodesic_segment_param(3) Gromov_product_le_dist(1) mem_box_real(2) order_trans subset_eq sup.cobounded1 w(1))\n  next\n    case False\n    define s where \"s = dist y z - t\"\n    have s: \"s \\<in> {0..Gromov_product_at z y x}\"\n      unfolding s_def using Gromov_product_add[of y z x] w(1) False by (auto simp add: Gromov_product_commute)\n    have w2: \"w = geodesic_segment_param Gyz z s\"\n      unfolding s_def w(2) apply (rule geodesic_segment_reverse_param[symmetric]) using assms(3) w(1) by auto\n    have *: \"dist w (geodesic_segment_param Gxz z s) \\<le> 4 * deltaG(TYPE('a))\" unfolding w2\n      apply (rule thin_triangles1[of _ _ y _ x])\n      using s assms by (auto simp add: geodesic_segment_commute)\n    show ?thesis\n      apply (rule infdist_le2[OF _ *])\n      by (metis Un_iff assms(2) atLeastAtMost_iff geodesic_segment_commute geodesic_segment_param(3) Gromov_product_commute Gromov_product_le_dist(1) order_trans s)\n  qed\nqed\n\ntext \\<open>A consequence of the thin triangles property is that, although the geodesic between\ntwo points is in general not unique in a Gromov-hyperbolic space, two such geodesics are\nwithin $O(\\delta)$ of each other.\\<close>\n\nlemma geodesics_nearby:\n  assumes \"geodesic_segment_between G x y\" \"geodesic_segment_between H x y\"\n          \"(z::'a) \\<in> G\"\n  shows \"infdist z H \\<le> 4 * deltaG(TYPE('a))\"\nusing thin_triangles[OF geodesic_segment_between_x_x(1) assms(2) assms(1) assms(3)]\ngeodesic_segment_endpoints(1)[OF assms(2)] insert_absorb by fastforce\n\ntext \\<open>A small variant of the property of thin triangles is that triangles are slim, i.e., there is\na point which is close to the three sides of the triangle (a \"center\" of the triangle, but\nonly defined up to $O(\\delta)$). And one can take it on any side, and its distance to the corresponding\nvertices is expressed in terms of a Gromov product.\\<close>\n\nlemma slim_triangle:\n  assumes \"geodesic_segment_between Gxy x y\"\n          \"geodesic_segment_between Gxz x z\"\n          \"geodesic_segment_between Gyz y (z::'a)\"\n  shows \"\\<exists>w. infdist w Gxy \\<le> 4 * deltaG(TYPE('a)) \\<and>\n             infdist w Gxz \\<le> 4 * deltaG(TYPE('a)) \\<and>\n             infdist w Gyz \\<le> 4 * deltaG(TYPE('a)) \\<and>\n             dist w x = (Gromov_product_at x y z) \\<and> w \\<in> Gxy\"\nproof -\n  define w where \"w = geodesic_segment_param Gxy x (Gromov_product_at x y z)\"\n  have \"w \\<in> Gxy\" unfolding w_def\n    by (rule geodesic_segment_param(3)[OF assms(1)], auto)\n  then have xy: \"infdist w Gxy \\<le> 4 * deltaG(TYPE('a))\" by simp\n  have *: \"dist w x = (Gromov_product_at x y z)\"\n    unfolding w_def using assms(1)\n    by (metis Gromov_product_le_dist(1) Gromov_product_nonneg atLeastAtMost_iff geodesic_segment_param(6) metric_space_class.dist_commute)\n\n  define w2 where \"w2 = geodesic_segment_param Gxz x (Gromov_product_at x y z)\"\n  have \"w2 \\<in> Gxz\" unfolding w2_def\n    by (rule geodesic_segment_param(3)[OF assms(2)], auto)\n  moreover have \"dist w w2 \\<le> 4 * deltaG(TYPE('a))\"\n    unfolding w_def w2_def by (rule thin_triangles1[OF assms(1) assms(2)], auto)\n  ultimately have xz: \"infdist w Gxz \\<le> 4 * deltaG(TYPE('a))\"\n    using infdist_le2 by blast\n\n  have \"w = geodesic_segment_param Gxy y (dist x y - Gromov_product_at x y z)\"\n    unfolding w_def by (rule geodesic_segment_reverse_param[OF assms(1), symmetric], auto)\n  then have w: \"w = geodesic_segment_param Gxy y (Gromov_product_at y x z)\"\n    using Gromov_product_add[of x y z] by (metis add_diff_cancel_left')\n\n  define w3 where \"w3 = geodesic_segment_param Gyz y (Gromov_product_at y x z)\"\n  have \"w3 \\<in> Gyz\" unfolding w3_def\n    by (rule geodesic_segment_param(3)[OF assms(3)], auto)\n  moreover have \"dist w w3 \\<le> 4 * deltaG(TYPE('a))\"\n    unfolding w w3_def by (rule thin_triangles1[OF geodesic_segment_commute[OF assms(1)] assms(3)], auto)\n  ultimately have yz: \"infdist w Gyz \\<le> 4 * deltaG(TYPE('a))\"\n    using infdist_le2 by blast\n\n  show ?thesis using xy xz yz * \\<open>w \\<in> Gxy\\<close> by force\nqed\n\ntext \\<open>The distance of a vertex of a triangle to the opposite side is essentially given by the\nGromov product, up to $2\\delta$.\\<close>\n\nlemma dist_triangle_side_middle:\n  assumes \"geodesic_segment_between G x (y::'a)\"\n  shows \"dist z (geodesic_segment_param G x (Gromov_product_at x z y)) \\<le> Gromov_product_at z x y + 2 * deltaG(TYPE('a))\"\nproof -\n  define m where \"m = geodesic_segment_param G x (Gromov_product_at x z y)\"\n  have \"m \\<in> G\"\n    unfolding m_def using assms(1) by auto\n  have A: \"dist x m = Gromov_product_at x z y\"\n    unfolding m_def by (rule geodesic_segment_param(6)[OF assms(1)], auto)\n  have B: \"dist y m = dist x y - dist x m\"\n    using geodesic_segment_dist[OF assms \\<open>m \\<in> G\\<close>] by (auto simp add: metric_space_class.dist_commute)\n  have *: \"dist x z + dist y m = Gromov_product_at z x y + dist x y\"\n          \"dist x m + dist y z = Gromov_product_at z x y + dist x y\"\n    unfolding B A Gromov_product_at_def by (auto simp add: metric_space_class.dist_commute divide_simps)\n\n  have \"dist x y + dist z m \\<le> max (dist x z + dist y m) (dist x m + dist y z) + 2 * deltaG(TYPE('a))\"\n    by (rule hyperb_quad_ineq)\n  then have \"dist z m \\<le> Gromov_product_at z x y + 2 * deltaG(TYPE('a))\"\n    unfolding * by auto\n  then show ?thesis\n    unfolding m_def by auto\nqed\n\nlemma infdist_triangle_side [mono_intros]:\n  assumes \"geodesic_segment_between G x (y::'a)\"\n  shows \"infdist z G \\<le> Gromov_product_at z x y + 2 * deltaG(TYPE('a))\"\nproof -\n  have \"infdist z G \\<le> dist z (geodesic_segment_param G x (Gromov_product_at x z y))\"\n    using assms by (auto intro!: infdist_le)\n  then show ?thesis\n    using dist_triangle_side_middle[OF assms, of z] by auto\nqed\n\ntext \\<open>The distance of a point on a side of triangle to the opposite vertex is controlled by\nthe length of the opposite sides, up to $\\delta$.\\<close>\n\nlemma dist_le_max_dist_triangle:\n  assumes \"geodesic_segment_between G x y\"\n          \"m \\<in> G\"\n  shows \"dist m z \\<le> max (dist x z) (dist y z) + deltaG(TYPE('a))\"\nproof -\n  consider \"dist m x \\<le> deltaG(TYPE('a))\" | \"dist m y \\<le> deltaG(TYPE('a))\" |\n           \"dist m x \\<ge> deltaG(TYPE('a)) \\<and> dist m y \\<ge> deltaG(TYPE('a)) \\<and> Gromov_product_at z x m \\<le> Gromov_product_at z m y\" |\n           \"dist m x \\<ge> deltaG(TYPE('a)) \\<and> dist m y \\<ge> deltaG(TYPE('a)) \\<and> Gromov_product_at z m y \\<le> Gromov_product_at z x m\"\n    by linarith\n  then show ?thesis\n  proof (cases)\n    case 1\n    have \"dist m z \\<le> dist m x + dist x z\"\n      by (intro mono_intros)\n    then show ?thesis using 1 by auto\n  next\n    case 2\n    have \"dist m z \\<le> dist m y + dist y z\"\n      by (intro mono_intros)\n    then show ?thesis using 2 by auto\n  next\n    case 3\n    then have \"Gromov_product_at z x m = min (Gromov_product_at z x m) (Gromov_product_at z m y)\"\n      by auto\n    also have \"... \\<le> Gromov_product_at z x y + deltaG(TYPE('a))\"\n      by (intro mono_intros)\n    finally have \"dist z m \\<le> dist z y + dist x m - dist x y + 2 * deltaG(TYPE('a))\"\n      unfolding Gromov_product_at_def by (auto simp add: divide_simps algebra_simps)\n    also have \"... = dist z y - dist m y + 2 * deltaG(TYPE('a))\"\n      using geodesic_segment_dist[OF assms] by auto\n    also have \"... \\<le> dist z y + deltaG(TYPE('a))\"\n      using 3 by auto\n    finally show ?thesis\n      by (simp add: metric_space_class.dist_commute)\n  next\n    case 4\n    then have \"Gromov_product_at z m y = min (Gromov_product_at z x m) (Gromov_product_at z m y)\"\n      by auto\n    also have \"... \\<le> Gromov_product_at z x y + deltaG(TYPE('a))\"\n      by (intro mono_intros)\n    finally have \"dist z m \\<le> dist z x + dist m y - dist x y + 2 * deltaG(TYPE('a))\"\n      unfolding Gromov_product_at_def by (auto simp add: divide_simps algebra_simps)\n    also have \"... = dist z x - dist x m + 2 * deltaG(TYPE('a))\"\n      using geodesic_segment_dist[OF assms] by auto\n    also have \"... \\<le> dist z x + deltaG(TYPE('a))\"\n      using 4 by (simp add: metric_space_class.dist_commute)\n    finally show ?thesis\n      by (simp add: metric_space_class.dist_commute)\n  qed\nqed\n\nend (* of locale Gromov_hyperbolic_space *)\n\ntext \\<open>A useful variation around the previous properties is that quadrilaterals are thin, in the\nfollowing sense: if one has a union of three geodesics from $x$ to $t$, then a geodesic from $x$\nto $t$ remains within distance $8\\delta$ of the union of these 3 geodesics. We formulate the\nstatement in geodesic hyperbolic spaces as the proof requires the construction of an additional\ngeodesic, but in fact the statement is true without this assumption, thanks to the Bonk-Schramm\nextension theorem.\\<close>\n\nlemma (in Gromov_hyperbolic_space_geodesic) thin_quadrilaterals:\n  assumes \"geodesic_segment_between Gxy x y\"\n          \"geodesic_segment_between Gyz y z\"\n          \"geodesic_segment_between Gzt z t\"\n          \"geodesic_segment_between Gxt x t\"\n          \"(w::'a) \\<in> Gxt\"\n  shows \"infdist w (Gxy \\<union> Gyz \\<union> Gzt) \\<le> 8 * deltaG(TYPE('a))\"\nproof -\n  have I: \"infdist w ({x--z} \\<union> Gzt) \\<le> 4 * deltaG(TYPE('a))\"\n    apply (rule thin_triangles[OF _ assms(3) assms(4) assms(5)])\n    by (simp add: geodesic_segment_commute)\n  have \"\\<exists>u \\<in> {x--z} \\<union> Gzt. infdist w ({x--z} \\<union> Gzt) = dist w u\"\n    apply (rule infdist_proper_attained, auto intro!: proper_Un simp add: geodesic_segment_topology(7))\n    by (meson assms(3) geodesic_segmentI geodesic_segment_topology)\n  then obtain u where u: \"u \\<in> {x--z} \\<union> Gzt\" \"infdist w ({x--z} \\<union> Gzt) = dist w u\"\n    by auto\n  have \"infdist u (Gxy \\<union> Gyz \\<union> Gzt) \\<le> 4 * deltaG(TYPE('a))\"\n  proof (cases \"u \\<in> {x--z}\")\n    case True\n    have \"infdist u (Gxy \\<union> Gyz \\<union> Gzt) \\<le> infdist u (Gxy \\<union> Gyz)\"\n      apply (intro mono_intros) using assms(1) by auto\n    also have \"... \\<le> 4 * deltaG(TYPE('a))\"\n      using thin_triangles[OF geodesic_segment_commute[OF assms(1)] assms(2) _ True] by auto\n    finally show ?thesis\n      by auto\n  next\n    case False\n    then have *: \"u \\<in> Gzt\" using u(1) by auto\n    have \"infdist u (Gxy \\<union> Gyz \\<union> Gzt) \\<le> infdist u Gzt\"\n      apply (intro mono_intros) using assms(3) by auto\n    also have \"... = 0\" using * by auto\n    finally show ?thesis\n      using local.delta_nonneg by linarith\n  qed\n  moreover have \"infdist w (Gxy \\<union> Gyz \\<union> Gzt) \\<le> infdist u (Gxy \\<union> Gyz \\<union> Gzt) + dist w u\"\n    by (intro mono_intros)\n  ultimately show ?thesis\n    using I u(2) by auto\nqed\n\ntext \\<open>There are converses to the above statements: if triangles are thin, or slim, then the space\nis Gromov-hyperbolic, for some $\\delta$. We prove these criteria here, following the proofs in\nGhys (with a simplification in the case of slim triangles.\\<close>\n\ntext \\<open>The basic result we will use twice below is the following: if points on sides of triangles\nat the same distance of the basepoint are close to each other up to the Gromov product, then the\nspace is hyperbolic. The proof goes as follows. One wants to show that $(x,z)_e \\geq\n\\min((x,y)_e, (y,z)_e) - \\delta = t-\\delta$. On $[ex]$, $[ey]$ and $[ez]$, consider points\n$wx$, $wy$ and $wz$ at distance $t$ of $e$. Then $wx$ and $wy$ are $\\delta$-close by assumption,\nand so are $wy$ and $wz$. Then $wx$ and $wz$ are $2\\delta$-close. One can use these two points\nto express $(x,z)_e$, and the result follows readily.\\<close>\n\nlemma (in geodesic_space) controlled_thin_triangles_implies_hyperbolic:\n  assumes \"\\<And>(x::'a) y z t Gxy Gxz. geodesic_segment_between Gxy x y \\<Longrightarrow> geodesic_segment_between Gxz x z \\<Longrightarrow> t \\<in> {0..Gromov_product_at x y z}\n      \\<Longrightarrow> dist (geodesic_segment_param Gxy x t) (geodesic_segment_param Gxz x t) \\<le> delta\"\n  shows \"Gromov_hyperbolic_subset delta (UNIV::'a set)\"\nproof (rule Gromov_hyperbolic_subsetI2)\n  fix e x y z::'a\n  define t where \"t = min (Gromov_product_at e x y) (Gromov_product_at e y z)\"\n  define wx where \"wx = geodesic_segment_param {e--x} e t\"\n  define wy where \"wy = geodesic_segment_param {e--y} e t\"\n  define wz where \"wz = geodesic_segment_param {e--z} e t\"\n  have \"dist wx wy \\<le> delta\"\n    unfolding wx_def wy_def t_def by (rule assms[of _ _ x _ y], auto)\n  have \"dist wy wz \\<le> delta\"\n    unfolding wy_def wz_def t_def by (rule assms[of _ _ y _ z], auto)\n\n  have \"t + dist wy x = dist e wx + dist wy x\"\n    unfolding wx_def apply (auto intro!: geodesic_segment_param_in_geodesic_spaces(6)[symmetric])\n    unfolding t_def by (auto, meson Gromov_product_le_dist(1) min.absorb_iff2 min.left_idem order.trans)\n  also have \"... \\<le> dist e wx + (dist wy wx + dist wx x)\"\n    by (intro mono_intros)\n  also have \"... \\<le> dist e wx + (delta + dist wx x)\"\n    using \\<open>dist wx wy \\<le> delta\\<close> by (auto simp add: metric_space_class.dist_commute)\n  also have \"... = delta + dist e x\"\n    apply auto apply (rule geodesic_segment_dist[of \"{e--x}\"])\n    unfolding wx_def t_def by (auto simp add: geodesic_segment_param_in_segment)\n  finally have *: \"t + dist wy x - delta \\<le> dist e x\" by simp\n\n  have \"t + dist wy z = dist e wz + dist wy z\"\n    unfolding wz_def apply (auto intro!: geodesic_segment_param_in_geodesic_spaces(6)[symmetric])\n    unfolding t_def by (auto, meson Gromov_product_le_dist(2) min.absorb_iff1 min.right_idem order.trans)\n  also have \"... \\<le> dist e wz + (dist wy wz + dist wz z)\"\n    by (intro mono_intros)\n  also have \"... \\<le> dist e wz + (delta + dist wz z)\"\n    using \\<open>dist wy wz \\<le> delta\\<close> by (auto simp add: metric_space_class.dist_commute)\n  also have \"... = delta + dist e z\"\n    apply auto apply (rule geodesic_segment_dist[of \"{e--z}\"])\n    unfolding wz_def t_def by (auto simp add: geodesic_segment_param_in_segment)\n  finally have \"t + dist wy z - delta \\<le> dist e z\" by simp\n\n  then have \"(t + dist wy x - delta) + (t + dist wy z - delta) \\<le> dist e x + dist e z\"\n    using * by simp\n  also have \"... = dist x z + 2 * Gromov_product_at e x z\"\n    unfolding Gromov_product_at_def by (auto simp add: algebra_simps divide_simps)\n  also have \"... \\<le> dist wy x + dist wy z + 2 * Gromov_product_at e x z\"\n    using metric_space_class.dist_triangle[of x z wy] by (auto simp add: metric_space_class.dist_commute)\n  finally have \"2 * t - 2 * delta \\<le> 2 * Gromov_product_at e x z\"\n    by auto\n  then show \"min (Gromov_product_at e x y) (Gromov_product_at e y z) - delta \\<le> Gromov_product_at e x z\"\n    unfolding t_def by auto\nqed\n\ntext \\<open>We prove that if triangles are thin, i.e., they satisfy the Rips condition, i.e., every side\nof a triangle is included in the $\\delta$-neighborhood of the union of the other triangles, then\nthe space is hyperbolic. If a point $w$ on $[xy]$ satisfies $d(x,w) < (y,z)_x - \\delta$, then its\nfriend on $[xz] \\cup [yz]$ has to be on $[xz]$, and roughly at the same distance of the origin.\nThen it follows that the point on $[xz]$ with $d(x,w') = d(x,w)$ is close to $w$, as desired.\nIf $d(x,w) \\in [(y,z)_x - \\delta, (y,z)_x)$, we argue in the same way but for the point which\nis closer to $x$ by an amount $\\delta$. Finally, the last case $d(x,w) = (y,z)_x$ follows by\ncontinuity.\\<close>\n\nproposition (in geodesic_space) thin_triangles_implies_hyperbolic:\n  assumes \"\\<And>(x::'a) y z w Gxy Gyz Gxz. geodesic_segment_between Gxy x y \\<Longrightarrow> geodesic_segment_between Gxz x z \\<Longrightarrow> geodesic_segment_between Gyz y z\n        \\<Longrightarrow> w \\<in> Gxy \\<Longrightarrow> infdist w (Gxz \\<union> Gyz) \\<le> delta\"\n  shows \"Gromov_hyperbolic_subset (4 * delta) (UNIV::'a set)\"\nproof -\n  obtain x0::'a where True by auto\n  have \"infdist x0 ({x0} \\<union> {x0}) \\<le> delta\"\n    by (rule assms[of \"{x0}\" x0 x0 \"{x0}\" x0 \"{x0}\" x0], auto)\n  then have [simp]: \"delta \\<ge> 0\"\n    using infdist_nonneg by auto\n\n  have \"dist (geodesic_segment_param Gxy x t) (geodesic_segment_param Gxz x t) \\<le> 4 * delta\"\n    if H: \"geodesic_segment_between Gxy x y\" \"geodesic_segment_between Gxz x z\" \"t \\<in> {0..Gromov_product_at x y z}\"\n    for x y z t Gxy Gxz\n  proof -\n    have Main: \"dist (geodesic_segment_param Gxy x u) (geodesic_segment_param Gxz x u) \\<le> 4 * delta\"\n      if \"u \\<in> {delta..<Gromov_product_at x y z}\" for u\n    proof -\n      define wy where \"wy = geodesic_segment_param Gxy x (u-delta)\"\n      have \"dist wy (geodesic_segment_param Gxy x u) = abs((u-delta) - u)\"\n        unfolding wy_def apply (rule geodesic_segment_param(7)[OF H(1)]) using that apply auto\n        using Gromov_product_le_dist(1)[of x y z] \\<open>delta \\<ge> 0\\<close> by linarith+\n      then have I1: \"dist wy (geodesic_segment_param Gxy x u) = delta\" by auto\n\n      have \"infdist wy (Gxz \\<union> {y--z}) \\<le> delta\"\n        unfolding wy_def apply (rule assms[of Gxy x y _ z]) using H by (auto simp add: geodesic_segment_param_in_segment)\n      moreover have \"\\<exists>wz \\<in> Gxz \\<union> {y--z}. infdist wy (Gxz \\<union> {y--z}) = dist wy wz\"\n        apply (rule infdist_proper_attained, intro proper_Un)\n        using H(2) by (auto simp add: geodesic_segment_topology)\n      ultimately obtain wz where wz: \"wz \\<in> Gxz \\<union> {y--z}\" \"dist wy wz \\<le> delta\"\n        by force\n\n      have \"dist wz x \\<le> dist wz wy + dist wy x\"\n        by (rule metric_space_class.dist_triangle)\n      also have \"... \\<le> delta + (u-delta)\"\n        apply (intro add_mono) using wz(2) unfolding wy_def apply (auto simp add: metric_space_class.dist_commute)\n        apply (intro eq_refl geodesic_segment_param(6)[OF H(1)])\n        using that apply auto\n        by (metis diff_0_right diff_mono dual_order.trans Gromov_product_le_dist(1) less_eq_real_def metric_space_class.dist_commute metric_space_class.zero_le_dist wy_def)\n      finally have \"dist wz x \\<le> u\" by auto\n      also have \"... < Gromov_product_at x y z\"\n        using that by auto\n      also have \"... \\<le> infdist x {y--z}\"\n        by (rule Gromov_product_le_infdist, auto)\n      finally have \"dist x wz < infdist x {y--z}\"\n        by (simp add: metric_space_class.dist_commute)\n      then have \"wz \\<notin> {y--z}\"\n        by (metis add.left_neutral infdist_triangle infdist_zero leD)\n      then have \"wz \\<in> Gxz\"\n        using wz by auto\n\n      have \"u - delta = dist x wy\"\n        unfolding wy_def apply (rule geodesic_segment_param(6)[symmetric, OF H(1)])\n        using that apply auto\n        using Gromov_product_le_dist(1)[of x y z] \\<open>delta \\<ge> 0\\<close> by linarith\n      also have \"... \\<le> dist x wz + dist wz wy\"\n        by (rule metric_space_class.dist_triangle)\n      also have \"... \\<le> dist x wz + delta\"\n        using wz(2) by (simp add: metric_space_class.dist_commute)\n      finally have \"dist x wz \\<ge> u - 2 * delta\" by auto\n\n      define dz where \"dz = dist x wz\"\n      have *: \"wz = geodesic_segment_param Gxz x dz\"\n        unfolding dz_def using \\<open>wz \\<in> Gxz\\<close> H(2) by auto\n      have \"dist wz (geodesic_segment_param Gxz x u) = abs(dz - u)\"\n        unfolding * apply (rule geodesic_segment_param(7)[OF H(2)])\n        unfolding dz_def using \\<open>dist wz x \\<le> u\\<close> that apply (auto simp add: metric_space_class.dist_commute)\n        using Gromov_product_le_dist(2)[of x y z] \\<open>delta \\<ge> 0\\<close> by linarith+\n      also have \"... \\<le> 2 * delta\"\n        unfolding dz_def using \\<open>dist wz x \\<le> u\\<close> \\<open>dist x wz \\<ge> u - 2 * delta\\<close>\n        by (auto simp add: metric_space_class.dist_commute)\n      finally have I3: \"dist wz (geodesic_segment_param Gxz x u) \\<le> 2 * delta\"\n        by simp\n\n      have \"dist (geodesic_segment_param Gxy x u) (geodesic_segment_param Gxz x u)\n              \\<le> dist (geodesic_segment_param Gxy x u) wy + dist wy wz + dist wz (geodesic_segment_param Gxz x u)\"\n        by (rule dist_triangle4)\n      also have \"... \\<le> delta + delta + (2 * delta)\"\n        using I1 wz(2) I3 by (auto simp add: metric_space_class.dist_commute)\n      finally show ?thesis by simp\n    qed\n    have \"t \\<in> {0..dist x y}\" \"t \\<in> {0..dist x z}\" \"t \\<ge> 0\"\n      using \\<open>t \\<in> {0..Gromov_product_at x y z}\\<close> apply auto\n      using Gromov_product_le_dist[of x y z] by linarith+\n    consider \"t \\<le> delta\" | \"t \\<in> {delta..<Gromov_product_at x y z}\" | \"t = Gromov_product_at x y z \\<and> t > delta\"\n      using \\<open>t \\<in> {0..Gromov_product_at x y z}\\<close> by (auto, linarith)\n    then show ?thesis\n    proof (cases)\n      case 1\n      have \"dist (geodesic_segment_param Gxy x t) (geodesic_segment_param Gxz x t) \\<le> dist x (geodesic_segment_param Gxy x t) + dist x (geodesic_segment_param Gxz x t)\"\n        by (rule metric_space_class.dist_triangle3)\n      also have \"... = t + t\"\n        using geodesic_segment_param(6)[OF H(1) \\<open>t \\<in> {0..dist x y}\\<close>] geodesic_segment_param(6)[OF H(2) \\<open>t \\<in> {0..dist x z}\\<close>]\n        by auto\n      also have \"... \\<le> 4 * delta\" using 1 \\<open>delta \\<ge> 0\\<close> by linarith\n      finally show ?thesis by simp\n    next\n      case 2\n      show ?thesis using Main[OF 2] by simp\n    next\n      case 3\n      text \\<open>In this case, we argue by approximating $t$ by a slightly smaller parameter, for which\n      the result has already been proved above. We need to argue that all functions are continuous\n      on the sets we are considering, which is straightforward but tedious.\\<close>\n      define u::\"nat \\<Rightarrow> real\" where \"u = (\\<lambda>n. t-1/n)\"\n      have \"u \\<longlonglongrightarrow> t - 0\"\n        unfolding u_def by (intro tendsto_intros)\n      then have \"u \\<longlonglongrightarrow> t\" by simp\n      then have *: \"eventually (\\<lambda>n. u n > delta) sequentially\"\n        using 3 by (auto simp add: order_tendsto_iff)\n      have **: \"eventually (\\<lambda>n. u n \\<ge> 0) sequentially\"\n        apply (rule eventually_elim2[OF *, of \"(\\<lambda>n. delta \\<ge> 0)\"]) apply auto\n        using \\<open>delta \\<ge> 0\\<close> by linarith\n      have ***: \"u n \\<le> t\" for n unfolding u_def by auto\n      have A: \"eventually (\\<lambda>n. u n \\<in> {delta..<Gromov_product_at x y z}) sequentially\"\n        apply (auto intro!: eventually_conj)\n        apply (rule eventually_mono[OF *], simp)\n        unfolding u_def using 3 by auto\n      have B: \"eventually (\\<lambda>n. dist (geodesic_segment_param Gxy x (u n)) (geodesic_segment_param Gxz x (u n)) \\<le> 4 * delta) sequentially\"\n        by (rule eventually_mono[OF A Main], simp)\n      have C: \"(\\<lambda>n. dist (geodesic_segment_param Gxy x (u n)) (geodesic_segment_param Gxz x (u n)))\n            \\<longlonglongrightarrow> dist (geodesic_segment_param Gxy x t) (geodesic_segment_param Gxz x t)\"\n        apply (intro tendsto_intros)\n        apply (rule continuous_on_tendsto_compose[OF _ \\<open>u \\<longlonglongrightarrow> t\\<close> \\<open>t \\<in> {0..dist x y}\\<close>])\n        apply (simp add: isometry_on_continuous H(1))\n        using ** *** \\<open>t \\<in> {0..dist x y}\\<close> apply (simp, intro eventually_conj, simp, meson dual_order.trans eventually_mono)\n        apply (rule continuous_on_tendsto_compose[OF _ \\<open>u \\<longlonglongrightarrow> t\\<close> \\<open>t \\<in> {0..dist x z}\\<close>])\n        apply (simp add: isometry_on_continuous H(2))\n        using ** *** \\<open>t \\<in> {0..dist x z}\\<close> apply (simp, intro eventually_conj, simp, meson dual_order.trans eventually_mono)\n        done\n      show ?thesis\n        using B unfolding eventually_sequentially using LIMSEQ_le_const2[OF C] by simp\n    qed\n  qed\n  with controlled_thin_triangles_implies_hyperbolic[OF this]\n  show ?thesis by auto\nqed\n\ntext \\<open>Then, we prove that if triangles are slim (i.e., there is a point that is $\\delta$-close to\nall sides), then the space is hyperbolic. Using the previous statement, we should show that points\non $[xy]$ and $[xz]$ at the same distance $t$ of the origin are close, if $t \\leq (y,z)_x$.\nThere are two steps:\n- for $t = (y,z)_x$, then the two points are in fact close to the middle of the triangle\n(as this point satisfies $d(x,y) = d(x,w) + d(w,y) + O(\\delta)$, and similarly for the other sides,\none gets readily $d(x,w) = (y,z)_w + O(\\delta)$ by expanding the formula for the Gromov product).\nHence, they are close together.\n- For $t < (y,z)_x$, we argue that there are points $y' \\in [xy]$ and $z' \\in [xz]$ for which\n$t = (y',z')_x$, by a continuity argument and the intermediate value theorem.\nThen the result follows from the first step in the triangle $xy'z'$.\n\nThe proof we give is simpler than the one in~\\<^cite>\\<open>\"ghys_hyperbolique\"\\<close>, and gives better constants.\\<close>\n\nproposition (in geodesic_space) slim_triangles_implies_hyperbolic:\n  assumes \"\\<And>(x::'a) y z Gxy Gyz Gxz. geodesic_segment_between Gxy x y \\<Longrightarrow> geodesic_segment_between Gxz x z \\<Longrightarrow> geodesic_segment_between Gyz y z\n        \\<Longrightarrow> \\<exists>w. infdist w Gxy \\<le> delta \\<and> infdist w Gxz \\<le> delta \\<and> infdist w Gyz \\<le> delta\"\n  shows \"Gromov_hyperbolic_subset (6 * delta) (UNIV::'a set)\"\nproof -\n  text \\<open>First step: the result is true for $t = (y,z)_x$.\\<close>\n  have Main: \"dist (geodesic_segment_param Gxy x (Gromov_product_at x y z)) (geodesic_segment_param Gxz x (Gromov_product_at x y z)) \\<le> 6 * delta\"\n    if H: \"geodesic_segment_between Gxy x y\" \"geodesic_segment_between Gxz x z\"\n    for x y z Gxy Gxz\n  proof -\n    obtain w where w: \"infdist w Gxy \\<le> delta\" \"infdist w Gxz \\<le> delta\" \"infdist w {y--z} \\<le> delta\"\n      using assms[OF H, of \"{y--z}\"] by auto\n    have \"\\<exists>wxy \\<in> Gxy. infdist w Gxy = dist w wxy\"\n      apply (rule infdist_proper_attained) using H(1) by (auto simp add: geodesic_segment_topology)\n    then obtain wxy where wxy: \"wxy \\<in> Gxy\" \"dist w wxy \\<le> delta\"\n      using w by auto\n    have \"\\<exists>wxz \\<in> Gxz. infdist w Gxz = dist w wxz\"\n      apply (rule infdist_proper_attained) using H(2) by (auto simp add: geodesic_segment_topology)\n    then obtain wxz where wxz: \"wxz \\<in> Gxz\" \"dist w wxz \\<le> delta\"\n      using w by auto\n    have \"\\<exists>wyz \\<in> {y--z}. infdist w {y--z} = dist w wyz\"\n      apply (rule infdist_proper_attained) by (auto simp add: geodesic_segment_topology)\n    then obtain wyz where wyz: \"wyz \\<in> {y--z}\" \"dist w wyz \\<le> delta\"\n      using w by auto\n\n    have I: \"dist wxy wxz \\<le> 2 * delta\" \"dist wxy wyz \\<le> 2 * delta\" \"dist wxz wyz \\<le> 2 * delta\"\n      using metric_space_class.dist_triangle[of wxy wxz w] metric_space_class.dist_triangle[of wxy wyz w] metric_space_class.dist_triangle[of wxz wyz w]\n            wxy(2) wyz(2) wxz(2) by (auto simp add: metric_space_class.dist_commute)\n\n    text \\<open>We show that $d(x, wxy)$ is close to the Gromov product of $y$ and $z$ seen from $x$.\n    This follows from the fact that $w$ is essentially on all geodesics, so that everything simplifies\n    when one writes down the Gromov products, leaving only $d(x, w)$ up to $O(\\delta)$.\n    To get the right $O(\\delta)$, one has to be a little bit careful, using the triangular inequality\n    when possible. This means that the computations for the upper and lower bounds are different,\n    making them a little bit tedious, although straightforward.\\<close>\n    have \"dist y wxy -4 * delta + dist wxy z \\<le> dist y wxy - dist wxy wyz + dist wxy z - dist wxy wyz\"\n      using I by simp\n    also have \"... \\<le> dist wyz y + dist wyz z\"\n      using metric_space_class.dist_triangle[of y wxy wyz] metric_space_class.dist_triangle[of wxy z wyz]\n      by (auto simp add: metric_space_class.dist_commute)\n    also have \"... = dist y z\"\n      using wyz(1) by (metis geodesic_segment_dist local.some_geodesic_is_geodesic_segment(1) metric_space_class.dist_commute)\n    finally have *: \"dist y wxy + dist wxy z - 4 * delta \\<le> dist y z\" by simp\n    have \"2 * Gromov_product_at x y z = dist x y + dist x z - dist y z\"\n      unfolding Gromov_product_at_def by simp\n    also have \"... \\<le> dist x wxy + dist wxy y + dist x wxy + dist wxy z - (dist y wxy + dist wxy z - 4 * delta)\"\n      using metric_space_class.dist_triangle[of x y wxy] metric_space_class.dist_triangle[of x z wxy] *\n      by (auto simp add: metric_space_class.dist_commute)\n    also have \"... = 2 * dist x wxy + 4 * delta\"\n      by (auto simp add: metric_space_class.dist_commute)\n    finally have A: \"Gromov_product_at x y z \\<le> dist x wxy + 2 * delta\" by simp\n\n    have \"dist x wxy -4 * delta + dist wxy z \\<le> dist x wxy - dist wxy wxz + dist wxy z - dist wxy wxz\"\n      using I by simp\n    also have \"... \\<le> dist wxz x + dist wxz z\"\n      using metric_space_class.dist_triangle[of x wxy wxz] metric_space_class.dist_triangle[of wxy z wxz]\n      by (auto simp add: metric_space_class.dist_commute)\n    also have \"... = dist x z\"\n      using wxz(1) H(2) by (metis geodesic_segment_dist metric_space_class.dist_commute)\n    finally have *: \"dist x wxy + dist wxy z - 4 * delta \\<le> dist x z\" by simp\n    have \"2 * dist x wxy - 4 * delta = (dist x wxy + dist wxy y) + (dist x wxy + dist wxy z - 4 * delta) - (dist y wxy + dist wxy z)\"\n      by (auto simp add: metric_space_class.dist_commute)\n    also have \"... \\<le> dist x y + dist x z - dist y z\"\n      using * metric_space_class.dist_triangle[of y z wxy] geodesic_segment_dist[OF H(1) wxy(1)] by auto\n    also have \"... = 2 * Gromov_product_at x y z\"\n      unfolding Gromov_product_at_def by simp\n    finally have B: \"Gromov_product_at x y z \\<ge> dist x wxy - 2 * delta\" by simp\n\n    define dy where \"dy = dist x wxy\"\n    have *: \"wxy = geodesic_segment_param Gxy x dy\"\n      unfolding dy_def using \\<open>wxy \\<in> Gxy\\<close> H(1) by auto\n    have \"dist wxy (geodesic_segment_param Gxy x (Gromov_product_at x y z)) = abs(dy - Gromov_product_at x y z)\"\n      unfolding * apply (rule geodesic_segment_param(7)[OF H(1)])\n      unfolding dy_def using that geodesic_segment_dist_le[OF H(1) wxy(1), of x] by (auto simp add: metric_space_class.dist_commute)\n    also have \"... \\<le> 2 * delta\"\n      using A B unfolding dy_def by auto\n    finally have Iy: \"dist wxy (geodesic_segment_param Gxy x (Gromov_product_at x y z)) \\<le> 2 * delta\"\n      by simp\n\n    text \\<open>We need the same estimate for $wxz$. The proof is exactly the same, copied and pasted.\n    It would be better to have a separate statement, but since its assumptions would be rather\n    cumbersome I decided to keep the two proofs.\\<close>\n    have \"dist z wxz -4 * delta + dist wxz y \\<le> dist z wxz - dist wxz wyz + dist wxz y - dist wxz wyz\"\n      using I by simp\n    also have \"... \\<le> dist wyz z + dist wyz y\"\n      using metric_space_class.dist_triangle[of z wxz wyz] metric_space_class.dist_triangle[of wxz y wyz]\n      by (auto simp add: metric_space_class.dist_commute)\n    also have \"... = dist z y\"\n      using \\<open>dist wyz y + dist wyz z = dist y z\\<close> by (auto simp add: metric_space_class.dist_commute)\n    finally have *: \"dist z wxz + dist wxz y - 4 * delta \\<le> dist z y\" by simp\n    have \"2 * Gromov_product_at x y z = dist x z + dist x y - dist z y\"\n      unfolding Gromov_product_at_def by (simp add: metric_space_class.dist_commute)\n    also have \"... \\<le> dist x wxz + dist wxz z + dist x wxz + dist wxz y - (dist z wxz + dist wxz y - 4 * delta)\"\n      using metric_space_class.dist_triangle[of x z wxz] metric_space_class.dist_triangle[of x y wxz] *\n      by (auto simp add: metric_space_class.dist_commute)\n    also have \"... = 2 * dist x wxz + 4 * delta\"\n      by (auto simp add: metric_space_class.dist_commute)\n    finally have A: \"Gromov_product_at x y z \\<le> dist x wxz + 2 * delta\" by simp\n\n    have \"dist x wxz -4 * delta + dist wxz y \\<le> dist x wxz - dist wxz wxy + dist wxz y - dist wxz wxy\"\n      using I by (simp add: metric_space_class.dist_commute)\n    also have \"... \\<le> dist wxy x + dist wxy y\"\n      using metric_space_class.dist_triangle[of x wxz wxy] metric_space_class.dist_triangle[of wxz y wxy]\n      by (auto simp add: metric_space_class.dist_commute)\n    also have \"... = dist x y\"\n      using wxy(1) H(1) by (metis geodesic_segment_dist metric_space_class.dist_commute)\n    finally have *: \"dist x wxz + dist wxz y - 4 * delta \\<le> dist x y\" by simp\n    have \"2 * dist x wxz - 4 * delta = (dist x wxz + dist wxz z) + (dist x wxz + dist wxz y - 4 * delta) - (dist z wxz + dist wxz y)\"\n      by (auto simp add: metric_space_class.dist_commute)\n    also have \"... \\<le> dist x z + dist x y - dist z y\"\n      using * metric_space_class.dist_triangle[of z y wxz] geodesic_segment_dist[OF H(2) wxz(1)] by auto\n    also have \"... = 2 * Gromov_product_at x y z\"\n      unfolding Gromov_product_at_def by (simp add: metric_space_class.dist_commute)\n    finally have B: \"Gromov_product_at x y z \\<ge> dist x wxz - 2 * delta\" by simp\n\n    define dz where \"dz = dist x wxz\"\n    have *: \"wxz = geodesic_segment_param Gxz x dz\"\n      unfolding dz_def using \\<open>wxz \\<in> Gxz\\<close> H(2) by auto\n    have \"dist wxz (geodesic_segment_param Gxz x (Gromov_product_at x y z)) = abs(dz - Gromov_product_at x y z)\"\n      unfolding * apply (rule geodesic_segment_param(7)[OF H(2)])\n      unfolding dz_def using that geodesic_segment_dist_le[OF H(2) wxz(1), of x] by (auto simp add: metric_space_class.dist_commute)\n    also have \"... \\<le> 2 * delta\"\n      using A B unfolding dz_def by auto\n    finally have Iz: \"dist wxz (geodesic_segment_param Gxz x (Gromov_product_at x y z)) \\<le> 2 * delta\"\n      by simp\n\n    have \"dist (geodesic_segment_param Gxy x (Gromov_product_at x y z)) (geodesic_segment_param Gxz x (Gromov_product_at x y z))\n      \\<le> dist (geodesic_segment_param Gxy x (Gromov_product_at x y z)) wxy + dist wxy wxz + dist wxz (geodesic_segment_param Gxz x (Gromov_product_at x y z))\"\n      by (rule dist_triangle4)\n    also have \"... \\<le> 2 * delta + 2 * delta + 2 * delta\"\n      using Iy Iz I by (auto simp add: metric_space_class.dist_commute)\n    finally show ?thesis by simp\n  qed\n\n  text \\<open>Second step: the result is true for $t \\leq (y,z)_x$, by a continuity argument and a\n  reduction to the first step.\\<close>\n  have \"dist (geodesic_segment_param Gxy x t) (geodesic_segment_param Gxz x t) \\<le> 6 * delta\"\n    if H: \"geodesic_segment_between Gxy x y\" \"geodesic_segment_between Gxz x z\" \"t \\<in> {0..Gromov_product_at x y z}\"\n    for x y z t Gxy Gxz\n  proof -\n    define ys where \"ys = (\\<lambda>s. geodesic_segment_param Gxy x (s * dist x y))\"\n    define zs where \"zs = (\\<lambda>s. geodesic_segment_param Gxz x (s * dist x z))\"\n    define F where \"F = (\\<lambda>s. Gromov_product_at x (ys s) (zs s))\"\n    have \"\\<exists>s. 0 \\<le> s \\<and> s \\<le> 1 \\<and> F s = t\"\n    proof (rule IVT')\n      show \"F 0 \\<le> t\" \"t \\<le> F 1\"\n        unfolding F_def using that unfolding ys_def zs_def by (auto simp add: Gromov_product_e_x_x)\n      show \"continuous_on {0..1} F\"\n        unfolding F_def Gromov_product_at_def ys_def zs_def\n        apply (intro continuous_intros continuous_on_compose2[of \"{0..dist x y}\" _ _ \"\\<lambda>t. t * dist x y\"] continuous_on_compose2[of \"{0..dist x z}\" _ _ \"\\<lambda>t. t * dist x z\"])\n        apply (auto intro!: isometry_on_continuous geodesic_segment_param(4) that)\n        using metric_space_class.zero_le_dist mult_left_le_one_le by blast+\n    qed (simp)\n    then obtain s where s: \"s \\<in> {0..1}\" \"t = Gromov_product_at x (ys s) (zs s)\"\n      unfolding F_def by auto\n\n    have a: \"x = geodesic_segment_param Gxy x 0\" using H(1) by auto\n    have b: \"x = geodesic_segment_param Gxz x 0\" using H(2) by auto\n    have dy: \"dist x (ys s) = s * dist x y\"\n      unfolding ys_def apply (rule geodesic_segment_param[OF H(1)]) using s(1) by (auto simp add: mult_left_le_one_le)\n    have dz: \"dist x (zs s) = s * dist x z\"\n      unfolding zs_def apply (rule geodesic_segment_param[OF H(2)]) using s(1) by (auto simp add: mult_left_le_one_le)\n\n    define Gxy2 where \"Gxy2 = geodesic_subsegment Gxy x 0 (s * dist x y)\"\n    define Gxz2 where \"Gxz2 = geodesic_subsegment Gxz x 0 (s * dist x z)\"\n\n    have \"dist (geodesic_segment_param Gxy2 x t) (geodesic_segment_param Gxz2 x t) \\<le> 6 * delta\"\n    unfolding s(2) proof (rule Main)\n      show \"geodesic_segment_between Gxy2 x (ys s)\"\n        apply (subst a) unfolding Gxy2_def ys_def apply (rule geodesic_subsegment[OF H(1)])\n        using s(1) by (auto simp add: mult_left_le_one_le)\n      show \"geodesic_segment_between Gxz2 x (zs s)\"\n        apply (subst b) unfolding Gxz2_def zs_def apply (rule geodesic_subsegment[OF H(2)])\n        using s(1) by (auto simp add: mult_left_le_one_le)\n    qed\n    moreover have \"geodesic_segment_param Gxy2 x (t-0) = geodesic_segment_param Gxy x t\"\n      apply (subst a) unfolding Gxy2_def apply (rule geodesic_subsegment(3)[OF H(1)])\n      using s(1) H(3) unfolding s(2) apply (auto simp add: mult_left_le_one_le)\n      unfolding dy[symmetric] by (rule Gromov_product_le_dist)\n    moreover have \"geodesic_segment_param Gxz2 x (t-0) = geodesic_segment_param Gxz x t\"\n      apply (subst b) unfolding Gxz2_def apply (rule geodesic_subsegment(3)[OF H(2)])\n      using s(1) H(3) unfolding s(2) apply (auto simp add: mult_left_le_one_le)\n      unfolding dz[symmetric] by (rule Gromov_product_le_dist)\n    ultimately show ?thesis by simp\n  qed\n  with controlled_thin_triangles_implies_hyperbolic[OF this]\n  show ?thesis by auto\nqed\n\n\n\nsection \\<open>Metric trees\\<close>\n\ntext \\<open>Metric trees have several equivalent definitions. The simplest one is probably that it\nis a geodesic space in which the union of two geodesic segments intersecting only at one endpoint is\nstill a geodesic segment.\n\nMetric trees are Gromov hyperbolic, with $\\delta = 0$.\\<close>\n\nclass metric_tree = geodesic_space +\n  assumes geod_union: \"geodesic_segment_between G x y \\<Longrightarrow> geodesic_segment_between H y z \\<Longrightarrow> G \\<inter> H = {y} \\<Longrightarrow> geodesic_segment_between (G \\<union> H) x z\"\n\ntext \\<open>We will now show that the real line is a metric tree, by identifying its geodesic\nsegments, i.e., the compact intervals.\\<close>\n\nlemma geodesic_segment_between_real:\n  assumes \"x \\<le> (y::real)\"\n  shows \"geodesic_segment_between (G::real set) x y = (G = {x..y})\"\nproof\n  assume H: \"geodesic_segment_between G x y\"\n  then have \"connected G\" \"x \\<in> G\" \"y \\<in> G\"\n    using geodesic_segment_topology(2) geodesic_segmentI geodesic_segment_endpoints by auto\n  then have *: \"{x..y} \\<subseteq> G\"\n    by (simp add: connected_contains_Icc)\n  moreover have \"G \\<subseteq> {x..y}\"\n  proof\n    fix s assume \"s \\<in> G\"\n    have \"abs(s-x) + abs(s-y) = abs(x-y)\"\n      using geodesic_segment_dist[OF H \\<open>s \\<in> G\\<close>] unfolding dist_real_def by auto\n    then show \"s \\<in> {x..y}\" using \\<open>x \\<le> y\\<close> by auto\n  qed\n  ultimately show \"G = {x..y}\" by auto\nnext\n  assume H: \"G = {x..y}\"\n  define g where \"g = (\\<lambda>t. t + x)\"\n  have \"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    unfolding g_def isometry_on_def H using \\<open>x \\<le> y\\<close> by (auto simp add: dist_real_def)\n  then have \"\\<exists>g. 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    by auto\n  then show \"geodesic_segment_between G x y\" unfolding geodesic_segment_between_def by auto\nqed\n\nlemma geodesic_segment_between_real':\n  \"{x--y} = {min x y..max x (y::real)}\"\nby (metis geodesic_segment_between_real geodesic_segment_commute some_geodesic_is_geodesic_segment(1) max_def min.cobounded1 min_def)\n\nlemma geodesic_segment_real:\n  \"geodesic_segment (G::real set) = (\\<exists>x y. x \\<le> y \\<and> G = {x..y})\"\nproof\n  assume \"geodesic_segment G\"\n  then obtain x y where *: \"geodesic_segment_between G x y\" unfolding geodesic_segment_def by auto\n  have \"(x \\<le> y \\<and> G = {x..y}) \\<or> (y \\<le> x \\<and> G = {y..x})\"\n    apply (rule le_cases[of x y])\n    using geodesic_segment_between_real * geodesic_segment_commute apply simp\n    using geodesic_segment_between_real * geodesic_segment_commute by metis\n  then show \"\\<exists>x y. x \\<le> y \\<and> G = {x..y}\" by auto\nnext\n  assume \"\\<exists>x y. x \\<le> y \\<and> G = {x..y}\"\n  then show \"geodesic_segment G\"\n    unfolding geodesic_segment_def using geodesic_segment_between_real by metis\nqed\n\ninstance real::metric_tree\nproof\n  fix G H::\"real set\" and x y z::real assume GH: \"geodesic_segment_between G x y\" \"geodesic_segment_between H y z\" \"G \\<inter> H = {y}\"\n  have G: \"G = {min x y..max x y}\" using GH\n    by (metis geodesic_segment_between_real geodesic_segment_commute inf_real_def inf_sup_ord(2) max.coboundedI2 max_def min_def)\n  have H: \"H = {min y z..max y z}\" using GH\n    by (metis geodesic_segment_between_real geodesic_segment_commute inf_real_def inf_sup_ord(2) max.coboundedI2 max_def min_def)\n  have *: \"(x \\<le> y \\<and> y \\<le> z) \\<or> (z \\<le> y \\<and> y \\<le> x)\"\n    using G H \\<open>G \\<inter> H = {y}\\<close> unfolding min_def max_def\n    apply auto\n    apply (metis (mono_tags, opaque_lifting) min_le_iff_disj order_refl)\n    by (metis (full_types) less_eq_real_def max_def)\n  show \"geodesic_segment_between (G \\<union> H) x z\"\n    using * apply rule\n    using \\<open>G \\<inter> H = {y}\\<close> unfolding G H apply (metis G GH(1) GH(2) H geodesic_segment_between_real ivl_disj_un_two_touch(4) order_trans)\n    using \\<open>G \\<inter> H = {y}\\<close> unfolding G H\n    by (metis (full_types) Un_commute geodesic_segment_between_real geodesic_segment_commute ivl_disj_un_two_touch(4) le_max_iff_disj max.absorb_iff2 max.commute min_absorb2)\nqed\n\ncontext metric_tree begin\n\ntext \\<open>We show that a metric tree is uniquely geodesic.\\<close>\n\nsubclass uniquely_geodesic_space\nproof\n  fix x y G H assume H: \"geodesic_segment_between G x y\" \"geodesic_segment_between H x (y::'a)\"\n  show \"G = H\"\n  proof (rule uniquely_geodesic_spaceI[OF _ H])\n    fix G H x y assume \"geodesic_segment_between G x y\" \"geodesic_segment_between H x y\" \"G \\<inter> H = {x, (y::'a)}\"\n    show \"x = y\"\n    proof (rule ccontr)\n      assume \"x \\<noteq> y\"\n      then have \"dist x y > 0\" 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 G2 where \"G2 = g`{0..dist x y/2}\"\n      have \"G2 \\<subseteq> G\" unfolding G2_def g(4) by auto\n      define z where \"z = g(dist x y/2)\"\n      have \"dist x z = dist x y/2\"\n        using isometry_onD[OF g(3), of 0 \"dist x y/2\"] g(1) z_def unfolding dist_real_def by auto\n      have \"dist y z = dist x y/2\"\n        using isometry_onD[OF g(3), of \"dist x y\" \"dist x y/2\"] g(2) z_def unfolding dist_real_def by auto\n\n      have G2: \"geodesic_segment_between G2 x z\" unfolding \\<open>g 0 = x\\<close>[symmetric] z_def G2_def\n        apply (rule geodesic_segmentI2) by (rule isometry_on_subset[OF g(3)], auto simp add: \\<open>g 0 = x\\<close>)\n      have [simp]: \"x \\<in> G2\" \"z \\<in> G2\" using geodesic_segment_endpoints G2 by auto\n      have \"dist x a \\<le> dist x z\" if \"a \\<in> G2\" for a\n        apply (rule geodesic_segment_dist_le) using G2 that by auto\n      also have \"... < dist x y\" unfolding \\<open>dist x z = dist x y/2\\<close> using \\<open>dist x y > 0\\<close> by auto\n      finally have \"y \\<notin> G2\" by auto\n\n      then have \"G2 \\<inter> H = {x}\"\n        using \\<open>G2 \\<subseteq> G\\<close> \\<open>x \\<in> G2\\<close> \\<open>G \\<inter> H = {x, y}\\<close> by auto\n      have *: \"geodesic_segment_between (G2 \\<union> H) z y\"\n        apply (rule geod_union[of _ _ x])\n        using \\<open>G2 \\<inter> H = {x}\\<close> \\<open>geodesic_segment_between H x y\\<close> G2 by (auto simp add: geodesic_segment_commute)\n      have \"dist x y \\<le> dist z x + dist x y\" by auto\n      also have \"... = dist z y\"\n        apply (rule geodesic_segment_dist[OF *]) using \\<open>G \\<inter> H = {x, y}\\<close> by auto\n      also have \"... = dist x y / 2\"\n        by (simp add: \\<open>dist y z = dist x y / 2\\<close> metric_space_class.dist_commute)\n      finally show False using \\<open>dist x y > 0\\<close> by auto\n    qed\n  qed\nqed\n\ntext \\<open>An important property of metric trees is that any geodesic triangle is degenerate, i.e., the\nthree sides intersect at a unique point, the center of the triangle, that we introduce now.\\<close>\n\ndefinition center::\"'a \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> 'a\"\n  where \"center x y z = (SOME t. t \\<in> {x--y} \\<inter> {x--z} \\<inter> {y--z})\"\n\nlemma center_as_intersection:\n  \"{x--y} \\<inter> {x--z} \\<inter> {y--z} = {center x y z}\"\nproof -\n  obtain g where g: \"g 0 = x\" \"g (dist x y) = y\" \"isometry_on {0..dist x y} g\" \"{x--y} = g`{0..dist x y}\"\n    by (meson geodesic_segment_between_def some_geodesic_is_geodesic_segment(1))\n  obtain h where h: \"h 0 = x\" \"h (dist x z) = z\" \"isometry_on {0..dist x z} h\" \"{x--z} = h`{0..dist x z}\"\n    by (meson geodesic_segment_between_def some_geodesic_is_geodesic_segment(1))\n\n  define Z where \"Z = {t \\<in> {0..min (dist x y) (dist x z)}. g t = h t}\"\n  have \"0 \\<in> Z\" unfolding Z_def using g(1) h(1) by auto\n  have [simp]: \"closed Z\"\n  proof -\n    have *: \"Z = (\\<lambda>s. dist (g s) (h s))-`{0} \\<inter> {0..min (dist x y) (dist x z)}\"\n      unfolding Z_def by auto\n    show ?thesis\n      unfolding * apply (rule closed_vimage_Int)\n      using continuous_on_subset[OF isometry_on_continuous[OF g(3)], of \"{0..min (dist x y) (dist x z)}\"]\n            continuous_on_subset[OF isometry_on_continuous[OF h(3)], of \"{0..min (dist x y) (dist x z)}\"]\n            continuous_on_dist by auto\n  qed\n  define a where \"a = Sup Z\"\n  have \"a \\<in> Z\"\n    unfolding a_def apply (rule closed_contains_Sup, auto) using \\<open>0 \\<in> Z\\<close> Z_def by auto\n  define c where \"c = h a\"\n  then have a: \"g a = c\" \"h a = c\" \"a \\<ge> 0\" \"a \\<le> dist x y\" \"a \\<le> dist x z\"\n    using \\<open>a \\<in> Z\\<close> unfolding Z_def c_def by auto\n\n  define G2 where \"G2 = g`{a..dist x y}\"\n  have G2: \"geodesic_segment_between G2 (g a) (g (dist x y))\"\n    unfolding G2_def apply (rule geodesic_segmentI2)\n    using isometry_on_subset[OF g(3)] \\<open>a \\<in> Z\\<close> unfolding Z_def by auto\n  define H2 where \"H2 = h`{a..dist x z}\"\n  have H2: \"geodesic_segment_between H2 (h a) (h (dist x z))\"\n    unfolding H2_def apply (rule geodesic_segmentI2)\n    using isometry_on_subset[OF h(3)] \\<open>a \\<in> Z\\<close> unfolding Z_def by auto\n  have \"G2 \\<inter> H2 \\<subseteq> {c}\"\n  proof\n    fix w assume w: \"w \\<in> G2 \\<inter> H2\"\n    obtain sg where sg: \"w = g sg\" \"sg \\<in> {a..dist x y}\" using w unfolding G2_def by auto\n    obtain sh where sh: \"w = h sh\" \"sh \\<in> {a..dist x z}\" using w unfolding H2_def by auto\n    have \"dist w x = sg\"\n      unfolding g(1)[symmetric] sg(1) using isometry_onD[OF g(3), of 0 sg] sg(2)\n      unfolding dist_real_def using a by (auto simp add: metric_space_class.dist_commute)\n    moreover have \"dist w x = sh\"\n      unfolding h(1)[symmetric] sh(1) using isometry_onD[OF h(3), of 0 sh] sh(2)\n      unfolding dist_real_def using a by (auto simp add: metric_space_class.dist_commute)\n    ultimately have \"sg = sh\" by simp\n    have \"sh \\<in> Z\" unfolding Z_def using sg sh \\<open>a \\<ge> 0\\<close> unfolding \\<open>sg = sh\\<close> by auto\n    then have \"sh \\<le> a\"\n      unfolding a_def apply (rule cSup_upper) unfolding Z_def by auto\n    then have \"sh = a\" using sh(2) by auto\n    then show \"w \\<in> {c}\" unfolding sh(1) using a(2) by auto\n  qed\n  then have *: \"G2 \\<inter> H2 = {c}\"\n    unfolding G2_def H2_def using a by (auto simp add: image_iff, force)\n  have \"geodesic_segment_between (G2 \\<union> H2) y z\"\n    apply (subst g(2)[symmetric], subst h(2)[symmetric]) apply(rule geod_union[of _ _ \"h a\"])\n    using geodesic_segment_commute G2 H2 a * by force+\n  then have \"G2 \\<union> H2 = {y--z}\"\n    using geodesic_segment_unique by auto\n  then have \"c \\<in> {y--z}\" using * by auto\n  then have *: \"c \\<in> {x--y} \\<inter> {x--z} \\<inter> {y--z}\"\n    using g(4) h(4) c_def a by force\n  have center: \"center x y z \\<in> {x--y} \\<inter> {x--z} \\<inter> {y--z}\"\n    unfolding center_def using someI[of \"\\<lambda>p. p \\<in> {x--y} \\<inter> {x--z} \\<inter> {y--z}\", OF *] by blast\n  have *: \"dist x d = Gromov_product_at x y z\" if \"d \\<in> {x--y} \\<inter> {x--z} \\<inter> {y--z}\" for d\n  proof -\n    have \"dist x y = dist x d + dist d y\"\n         \"dist x z = dist x d + dist d z\"\n         \"dist y z = dist y d + dist d z\"\n      using that by (auto simp add: geodesic_segment_dist geodesic_segment_unique)\n    then show ?thesis unfolding Gromov_product_at_def by (auto simp add: metric_space_class.dist_commute)\n  qed\n  have \"d = center x y z\" if \"d \\<in> {x--y} \\<inter> {x--z} \\<inter> {y--z}\" for d\n    apply (rule geodesic_segment_dist_unique[of \"{x--y}\" x y])\n    using *[OF that] *[OF center] that center by auto\n  then show \"{x--y} \\<inter> {x--z} \\<inter> {y--z} = {center x y z}\" using center by blast\nqed\n\nlemma center_on_geodesic [simp]:\n  \"center x y z \\<in> {x--y}\"\n  \"center x y z \\<in> {x--z}\"\n  \"center x y z \\<in> {y--z}\"\n  \"center x y z \\<in> {y--x}\"\n  \"center x y z \\<in> {z--x}\"\n  \"center x y z \\<in> {z--y}\"\nusing center_as_intersection by (auto simp add: some_geodesic_commute)\n\nlemma center_commute:\n  \"center x y z = center x z y\"\n  \"center x y z = center y x z\"\n  \"center x y z = center y z x\"\n  \"center x y z = center z x y\"\n  \"center x y z = center z y x\"\nusing center_as_intersection some_geodesic_commute by blast+\n\nlemma center_dist:\n  \"dist x (center x y z) = Gromov_product_at x y z\"\nproof -\n  have \"dist x y = dist x (center x y z) + dist (center x y z) y\"\n       \"dist x z = dist x (center x y z) + dist (center x y z) z\"\n       \"dist y z = dist y (center x y z) + dist (center x y z) z\"\n    by (auto simp add: geodesic_segment_dist geodesic_segment_unique)\n  then show ?thesis unfolding Gromov_product_at_def by (auto simp add: metric_space_class.dist_commute)\nqed\n\nlemma geodesic_intersection:\n  \"{x--y} \\<inter> {x--z} = {x--center x y z}\"\nproof -\n  have \"{x--y} = {x--center x y z} \\<union> {center x y z--y}\"\n    using center_as_intersection geodesic_segment_split by blast\n  moreover have \"{x--z} = {x--center x y z} \\<union> {center x y z--z}\"\n    using center_as_intersection geodesic_segment_split by blast\n  ultimately have \"{x--y} \\<inter> {x--z} = {x--center x y z} \\<union> ({center x y z--y} \\<inter> {x--center x y z}) \\<union> ({center x y z--y} \\<inter> {x--center x y z}) \\<union> ({center x y z--y} \\<inter> {center x y z--z})\"\n    by auto\n  moreover have \"{center x y z--y} \\<inter> {x--center x y z} = {center x y z}\"\n    using geodesic_segment_split(2) center_as_intersection[of x y z] by auto\n  moreover have \"{center x y z--y} \\<inter> {x--center x y z} = {center x y z}\"\n    using geodesic_segment_split(2) center_as_intersection[of x y z] by auto\n  moreover have \"{center x y z--y} \\<inter> {center x y z--z} = {center x y z}\"\n    using geodesic_segment_split(2)[of \"center x y z\" y z] center_as_intersection[of x y z] by (auto simp add: some_geodesic_commute)\n  ultimately show \"{x--y} \\<inter> {x--z} = {x--center x y z}\" by auto\nqed\nend (*of context metric_tree*)\n\ntext \\<open>We can now prove that a metric tree is Gromov hyperbolic, for $\\delta = 0$. The simplest\nproof goes through the slim triangles property: it suffices to show that, given a geodesic triangle,\nthere is a point at distance at most $0$ of each of its sides. This is the center we have\nconstructed above.\\<close>\n\nclass metric_tree_with_delta = metric_tree + metric_space_with_deltaG +\n  assumes delta0: \"deltaG(TYPE('a::metric_space)) = 0\"\n\nclass Gromov_hyperbolic_space_0 = Gromov_hyperbolic_space +\n  assumes delta0 [simp]: \"deltaG(TYPE('a::metric_space)) = 0\"\n\nclass Gromov_hyperbolic_space_0_geodesic = Gromov_hyperbolic_space_0 + geodesic_space\n\ntext \\<open>Isabelle does not accept cycles in the class graph. So, we will show that\n\\verb+metric_tree_with_delta+ is a subclass of \\verb+Gromov_hyperbolic_space_0_geodesic+, and\nconversely that \\verb+Gromov_hyperbolic_space_0_geodesic+ is a subclass of \\verb+metric_tree+.\n\nIn a tree, we have already proved that triangles are $0$-slim (the center is common to all sides\nof the triangle). The $0$-hyperbolicity follows from one of the equivalent characterizations\nof hyperbolicity (the other characterizations could be used as well, but the proofs would be\nless immediate.)\\<close>\n\nsubclass (in metric_tree_with_delta) Gromov_hyperbolic_space_0\nproof (standard)\n  show \"deltaG TYPE('a) = 0\" unfolding delta0 by auto\n  have \"Gromov_hyperbolic_subset (6 * 0) (UNIV::'a set)\"\n  proof (rule slim_triangles_implies_hyperbolic)\n    fix x::'a and y z Gxy Gyz Gxz\n    define w where \"w = center x y z\"\n    assume \"geodesic_segment_between Gxy x y\"\n        \"geodesic_segment_between Gxz x z\" \"geodesic_segment_between Gyz y z\"\n    then have \"Gxy = {x--y}\" \"Gyz = {y--z}\" \"Gxz = {x--z}\"\n      by (auto simp add: local.geodesic_segment_unique)\n    then have \"w \\<in> Gxy\" \"w \\<in> Gyz\" \"w \\<in> Gxz\"\n      unfolding w_def by auto\n    then have \"infdist w Gxy \\<le> 0 \\<and> infdist w Gxz \\<le> 0 \\<and> infdist w Gyz \\<le> 0\"\n      by auto\n    then show \"\\<exists>w. infdist w Gxy \\<le> 0 \\<and> infdist w Gxz \\<le> 0 \\<and> infdist w Gyz \\<le> 0\"\n      by blast\n  qed\n  then show \"Gromov_hyperbolic_subset (deltaG TYPE('a)) (UNIV::'a set)\" unfolding delta0 by auto\nqed\n\ntext \\<open>To use the fact that reals are Gromov hyperbolic, given that they are a metric tree,\nwe need to instantiate them as \\verb+metric_tree_with_delta+.\\<close>\n\ninstantiation real::metric_tree_with_delta\nbegin\ndefinition deltaG_real::\"real itself \\<Rightarrow> real\"\n  where \"deltaG_real _ = 0\"\ninstance apply standard unfolding deltaG_real_def by auto\nend\n\ntext \\<open>Let us now prove the converse: a geodesic space which is $\\delta$-hyperbolic for $\\delta = 0$\nis a metric tree. For the proof, we consider two geodesic segments $G = [x,y]$ and $H = [y,z]$ with a common\nendpoint, and we have to show that their union is still a geodesic segment from $x$ to $z$. For\nthis, introduce a geodesic segment $L = [x,z]$. By the property of thin triangles, $G$ is included\nin $H \\cup L$. In particular, a point $Y$ close to $y$ but different from $y$ on $G$ is on $L$,\nand therefore realizes the equality $d(x,z) = d(x, Y) + d(Y, z)$. Passing to the limit, $y$\nalso satisfies this equality. The conclusion readily follows thanks to Lemma\n\\verb+geodesic_segment_union+.\n\\<close>\n\nsubclass (in Gromov_hyperbolic_space_0_geodesic) metric_tree\nproof\n  fix G H x y z assume A: \"geodesic_segment_between G x y\" \"geodesic_segment_between H y z\" \"G \\<inter> H = {y::'a}\"\n  show \"geodesic_segment_between (G \\<union> H) x z\"\n  proof (cases \"x = y\")\n    case True\n    then show ?thesis\n      by (metis A Un_commute geodesic_segment_between_x_x(3) inf.commute sup_inf_absorb)\n  next\n    case False\n    define D::\"nat \\<Rightarrow> real\" where \"D = (\\<lambda>n. dist x y - (dist x y) * (1/(real(n+1))))\"\n    have D: \"D n \\<in> {0..< dist x y}\" \"D n \\<in> {0..dist x y}\" for n\n      unfolding D_def by (auto simp add: False divide_simps algebra_simps)\n    have Dlim: \"D \\<longlonglongrightarrow> dist x y - dist x y * 0\"\n      unfolding D_def by (intro tendsto_intros LIMSEQ_ignore_initial_segment[OF lim_1_over_n, of 1])\n\n    define Y::\"nat \\<Rightarrow> 'a\" where \"Y = (\\<lambda>n. geodesic_segment_param G x (D n))\"\n    have *: \"Y \\<longlonglongrightarrow> y\"\n      unfolding Y_def apply (subst geodesic_segment_param(2)[OF A(1), symmetric])\n      using isometry_on_continuous[OF geodesic_segment_param(4)[OF A(1)]]\n      unfolding continuous_on_sequentially comp_def using D(2) Dlim by auto\n\n    have \"dist x z = dist x (Y n) + dist (Y n) z\" for n\n    proof -\n      obtain L where L: \"geodesic_segment_between L x z\" using geodesic_subsetD[OF geodesic] by blast\n      have \"Y n \\<in> G\" unfolding Y_def\n        apply (rule geodesic_segment_param(3)[OF A(1)]) using D[of n] by auto\n      have \"dist x (Y n) = D n\"\n        unfolding Y_def apply (rule geodesic_segment_param[OF A(1)]) using D[of n] by auto\n      then have \"Y n \\<noteq> y\"\n        using D[of n] by auto\n      then have \"Y n \\<notin> H\" using A(3) \\<open>Y n \\<in> G\\<close> by auto\n      have \"infdist (Y n) (H \\<union> L) \\<le> 4 * deltaG(TYPE('a))\"\n        apply (rule thin_triangles[OF geodesic_segment_commute[OF A(2)] geodesic_segment_commute[OF L] geodesic_segment_commute[OF A(1)]])\n        using \\<open>Y n \\<in> G\\<close> by simp\n      then have \"infdist (Y n) (H \\<union> L) = 0\"\n        using infdist_nonneg[of \"Y n\" \"H \\<union> L\"] unfolding delta0 by auto\n      have \"Y n \\<in> H \\<union> L\"\n      proof (subst in_closed_iff_infdist_zero)\n        have \"closed H\"\n          using A(2) geodesic_segment_topology geodesic_segment_def by fastforce\n        moreover have \"closed L\"\n          using L geodesic_segment_topology geodesic_segment_def by fastforce\n        ultimately show \"closed (H \\<union> L)\" by auto\n        show \"H \\<union> L \\<noteq> {}\" using A(2) geodesic_segment_endpoints(1) by auto\n      qed (fact)\n      then have \"Y n \\<in> L\" using \\<open>Y n \\<notin> H\\<close> by simp\n      show ?thesis using geodesic_segment_dist[OF L \\<open>Y n \\<in> L\\<close>] by simp\n    qed\n    moreover have \"(\\<lambda>n. dist x (Y n) + dist (Y n) z) \\<longlonglongrightarrow> dist x y + dist y z\"\n      by (intro tendsto_intros *)\n    ultimately have \"(\\<lambda>n. dist x z) \\<longlonglongrightarrow> dist x y + dist y z\"\n      using filterlim_cong eventually_sequentially by auto\n    then have *: \"dist x z = dist x y + dist y z\"\n      using LIMSEQ_unique by auto\n    show \"geodesic_segment_between (G \\<union> H) x z\"\n      by (rule geodesic_segment_union[OF * A(1) A(2)])\n  qed\nqed\n\nend (*of theory Gromov_Hyperbolic*)\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/Gromov_Hyperbolicity/Gromov_Hyperbolicity.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8596637361282707, "lm_q2_score": 0.8333246035907932, "lm_q1q2_score": 0.7163789421304715}}
{"text": "(*by Ammer*)\ntheory VEBT_Space imports VEBT_Definitions Complex_Main\nbegin\n\nsection \\<open>Space Complexity and $buildup$ Time Consumption\\<close>\nsubsection \\<open>Space Comlexity of valid van Emde Boas Trees\\<close>\ntext \\<open>Space Complexity is linear in relation to universe sizes\\<close>\n\ncontext VEBT_internal begin\n\nfun space:: \"VEBT \\<Rightarrow> nat\" where\n\"space (Leaf a b) = 3\"|\n\"space (Node info deg treeList summary) = 5 + space summary + length treeList + foldr (\\<lambda> a b. a+b) (map space treeList) 0\"\n\nfun space':: \"VEBT \\<Rightarrow> nat\" where\n\"space' (Leaf a b) = 4\"|\n\"space' (Node info deg treeList summary) = 6 + space' summary + foldr (\\<lambda> a b. a+b) (map space' treeList) 0\"\n\ntext \\<open>Count in reals\\<close>\n\nfun cnt:: \"VEBT \\<Rightarrow> real\" where\n\"cnt (Leaf a b) = 1\"|\n\"cnt (Node info deg treeList summary) = 1 + cnt summary + foldr (\\<lambda> a b. a+b) (map cnt treeList) 0\"\n\nsubsection \\<open>Auxiliary Lemmas for List Summation\\<close>\n\nlemma list_every_elemnt_bound_sum_bound:\"\\<forall> x \\<in> set xs. f x \\<le> bound \\<Longrightarrow>  foldr (\\<lambda> a b. a+b) (map f xs) i \\<le> length xs * bound + i\"\n  by(induction xs) auto \n\nlemma list_every_elemnt_bound_sum_bound_real:\"\\<forall> x \\<in> set (xs::'a list). (f::'a\\<Rightarrow>real) x \\<le> (bound::real) \\<Longrightarrow>  foldr (\\<lambda> a b. a+b) (map f xs) i \\<le> real(length xs) * bound + i\"\n  apply(induction xs) apply simp\n  apply (simp add: algebra_simps)\n  done\n\nlemma foldr_one: \"d \\<le> foldr (+) ys (d::nat)\"\n  by (induction ys) auto\n\nlemma foldr_zero: \"\\<forall> i < length xs. xs !  i > 0 \\<Longrightarrow>\n        foldr (\\<lambda> a b. a+b) xs (d::nat) - d  \\<ge> length xs\"\nproof(induction xs)\n  case Nil\n  then show ?case by simp\nnext\n  case (Cons a xs)\n  hence \"\\<forall>i<length xs. 0 < xs ! i\" \n    by auto\n  hence \" length xs \\<le> foldr (+) xs d - d\" using Cons.IH by simp\n  have \"a \\<ge> 1\" \n    by (metis gr0_conv_Suc length_Cons less_one local.Cons(2) not_gr0 not_less nth_Cons_0)\n  then show ?case\n    by (metis Nat.add_diff_assoc \\<open>length xs \\<le> foldr (+) xs d - d\\<close> add_mono_thms_linordered_semiring(1) foldr.simps(2) foldr_one length_Cons o_apply plus_1_eq_Suc)\nqed\n\nlemma foldr_mono: \"length xs = length ys  \\<Longrightarrow>\\<forall> i < length xs. xs ! i < ys ! i \\<Longrightarrow> c \\<le> d \\<Longrightarrow>\n       foldr (\\<lambda> a b. a+b) xs c  + length ys \\<le> foldr (\\<lambda> a b. a+b) ys (d::nat)\"\nproof(induction xs arbitrary: d c ys)\n  case Nil\n  then show ?case using length_0_conv list.size(3)  foldr_one by simp\nnext\n  case (Cons a xs)\n  then obtain y ys1 where \"ys = y #ys1\" \n    by (metis Suc_leI Suc_le_length_iff nth_equalityI)\n  hence 0:\"length xs = length ys1\"\n    using Cons.prems(1) by force\n  hence 1:\"\\<forall>i<length xs. xs ! i < ys1 ! i\" using Cons.prems(2)\n    using \\<open>ys = y # ys1\\<close> by force\n  hence 3: \"\\<forall>i<length ys1. ys1 ! i > 0\"\n    by (metis \"0\" less_nat_zero_code neq0_conv)\n  have \"foldr (+) (a # xs)c = a +foldr (+) xs (c)\" by simp\n  have \"foldr (+) (ys) d = y +foldr (+) ys1 (d)\" \n    by (simp add: \\<open>ys = y # ys1\\<close>)\n  have 2:\"a < y\" using Cons.prems(2) \\<open>ys = y # ys1\\<close> \n    by (metis length_Cons nth_Cons_0 zero_less_Suc)\n  have 4:\"foldr (+) xs c \\<le> foldr (+) ys1 d - length ys1\" \n    using Cons.IH[of ys1 c d] 0 1 Cons.prems(3) by simp\n  have \"foldr (+) ys1 d \\<ge> length ys1\"using foldr_zero[of ys1 d]  3 by simp\n  hence \"a + foldr (+) xs c < y + foldr (+) ys1 d - length ys1 \" using 2 foldr_zero[of ys1 d] 4  by simp\n then show ?case \n   using \\<open>ys = y # ys1\\<close> by auto\nqed \n\nlemma two_realpow_ge_two :\"(n::real)\\<ge> 1 \\<Longrightarrow> (2::real)^n \\<ge> 2\"  \n  by (metis less_one not_less of_nat_1 of_nat_le_iff of_nat_numeral power_increasing power_one_right zero_neq_numeral)\n\nlemma foldr0: \"foldr (+) xs (c+d) = foldr (+) xs (d::real) + c\"\n  by(induction xs) auto\n\nlemma  f_g_map_foldr_bound:\" (\\<forall> x \\<in> set xs.  f x \\<le> c * g x) \n \\<Longrightarrow> foldr (\\<lambda> a b. a+b) (map f xs) d \\<le> c * foldr (\\<lambda> a b. a+b) (map g xs) (0::real) + d\" \n  by(induction xs) (auto simp add: algebra_simps)\n\nlemma real_nat_list: \"real (foldr (+) ( map f xs) (c::nat)) \n     = foldr (+) (map (\\<lambda> x. real(f x))xs) c\"\n  by(induction xs arbitrary: c) auto\n\nsubsection \\<open>Actual Space Reasoning\\<close>\n\nlemma space_space': \"space' t > space t\" \nproof(induction t)\n  case (Node info deg treeList summary)\n  hence \"\\<forall> i < length treeList . (map space treeList)!i < ( map space' treeList)!i\" \n    by simp\n  hence 0:\"foldr (+) (map space treeList) 0  + length treeList \\<le> foldr (+) (map space' treeList) 0 \"\n    using foldr_mono[of \"(map space treeList)\"  \"(map space' treeList)\" 0 0] by simp  \n  have 1:\"space summary < space' summary\" using Node by simp\n  hence \"foldr (+) (map space treeList) 0 + length treeList + space summary \\<le>\n         foldr (+) (map space' treeList) 0 + space' summary\" using 0 by simp\n  then show ?case using space'.simps(2)[of info deg treeList summary] \n       space.simps(2)[of info deg treeList summary] by simp\nqed simp\n\nlemma cnt_bound: \n  defines  \"c \\<equiv> 1.5\" \n  shows \"invar_vebt t n \\<Longrightarrow> cnt t \\<le> 2*((2^n - c)::real)\"\nproof(induction t n rule: invar_vebt.induct)\ncase (2 treeList n summary m deg)\n  hence \"\\<forall>t\\<in>set treeList.  (cnt t) \\<le> 2 * (2 ^ n - c)\" by simp\n  hence \" foldr (\\<lambda> a b. a+b) (map cnt treeList) 0 \\<le> 2^n*2 * ((2^n - c)::real)\" \n    using list_every_elemnt_bound_sum_bound_real[of treeList cnt \"2*((2^n - c)::real)\" 0 ] 2\n    by (auto simp add: algebra_simps)\n  hence \"cnt ( Node None deg treeList summary) \\<le> 2*(2^n+1)*(2^n-c) + 1\" using 2 \n    by(auto simp add: algebra_simps)\n  hence \"cnt ( Node None deg treeList summary) \\<le> 2*(2^(n+n) + (1-c)*2^n - c + 1/2)\" \n    by(auto simp add: algebra_simps power_add) \n  moreover have \"2*(2^(n+n) + (1-c)*2^n - c + 1/2) \\<le> 2*(2^(n+n) + -0.5*1 - 1.5 + 1/2)\" \n    by(auto simp add: algebra_simps two_realpow_ge_one c_def)\n  moreover hence \"2*(2^(n+n) + (1-c)*2^n - c + 1/2) \\<le> 2*(2^(n+n)  -  1.5 )\" \n    by(auto simp add: algebra_simps power_add)\n  ultimately have  \"cnt ( Node None deg treeList summary) \\<le> 2*(2^(n+n)  -  1.5 )\" by simp\n  then show ?case  using c_def 2(5) 2(6) by simp\nnext\n  case (3 treeList n summary m deg)\n  hence \"\\<forall>t\\<in>set treeList.  (cnt t) \\<le> 2 * (2 ^ n - c)\" by simp\n  hence \" foldr (\\<lambda> a b. a+b) (map cnt treeList) 0 \\<le> 2^(n+1)*2 * ((2^n - c)::real)\" \n    using list_every_elemnt_bound_sum_bound_real[of treeList cnt \"2*((2^n - c)::real)\" 0 ] 3\n    by (auto simp add: algebra_simps)\n  moreover \n  hence \"cnt ( Node None deg treeList summary) \\<le> 2*(2^n*2^m - c* 2^(m) + 2^(m) - c  + 1/2)\"\n    using 3\n    by (auto simp add: algebra_simps powr_add)\n  moreover have \"2*(2^n*2^m - c* 2^(m) + 2^(m) - c  + 1/2) =  2*(2^(n+m) + (1-c)* 2^(m) - c  + 1/2)\"\n    by (auto simp add: algebra_simps power_add) \n   moreover have \" 2*(2^(n+m) + (1-c)* 2^(m) - c  + 1/2) \\<le> 2*(2^(n+m) + -0.5*1 - 1.5 + 1/2)\" \n     by(auto simp add: algebra_simps two_realpow_ge_one c_def)\n  moreover hence \"2*(2^(n+m) + (1-c)*2^m - c + 1/2) \\<le> 2*(2^(n+m)  -  1.5 )\" \n    by(auto simp add: algebra_simps power_add)\n  ultimately have  \"cnt ( Node None deg treeList summary) \\<le> 2*(2^(n+m)  -  1.5 )\" by simp\n  then show ?case  using c_def 3(5) 3(6) by simp\nnext\n  case (4 treeList n summary m deg mi ma)\nhence \"\\<forall>t\\<in>set treeList.  (cnt t) \\<le> 2 * (2 ^ n - c)\" by simp\n  hence \" foldr (\\<lambda> a b. a+b) (map cnt treeList) 0 \\<le> 2^n*2 * ((2^n - c)::real)\" \n    using list_every_elemnt_bound_sum_bound_real[of treeList cnt \"2*((2^n - c)::real)\" 0 ] 4\n    by (auto simp add: algebra_simps)\n  hence \"cnt ( Node (Some (mi, ma)) deg treeList summary) \\<le> 2*(2^n+1)*(2^n-c) + 1\" using 4 \n    by(auto simp add: algebra_simps)\n  hence \"cnt ( Node None deg treeList summary) \\<le> 2*(2^(n+n) + (1-c)*2^n - c + 1/2)\" \n    by(auto simp add: algebra_simps power_add) \n  moreover have \"2*(2^(n+n) + (1-c)*2^n - c + 1/2) \\<le> 2*(2^(n+n) + -0.5*1 - 1.5 + 1/2)\" \n    by(auto simp add: algebra_simps two_realpow_ge_one c_def)\n  moreover hence \"2*(2^(n+n) + (1-c)*2^n - c + 1/2) \\<le> 2*(2^(n+n)  -  1.5 )\" \n    by(auto simp add: algebra_simps power_add)\n  ultimately have  \"cnt ( Node None deg treeList summary) \\<le> 2*(2^(n+n)  -  1.5 )\" by simp\n  then show ?case  using c_def 4 by simp\nnext\n  case (5 treeList n summary m deg mi ma)\n hence \"\\<forall>t\\<in>set treeList.  (cnt t) \\<le> 2 * (2 ^ n - c)\" by simp\n  hence \" foldr (\\<lambda> a b. a+b) (map cnt treeList) 0 \\<le> 2^(n+1)*2 * ((2^n - c)::real)\" \n    using list_every_elemnt_bound_sum_bound_real[of treeList cnt \"2*((2^n - c)::real)\" 0 ] 5\n    by (auto simp add: algebra_simps)\n  moreover \n  hence \"cnt ( Node (Some (mi, ma)) deg treeList summary) \\<le> 2*(2^n*2^m - c* 2^(m) + 2^(m) - c  + 1/2)\"\n    using 5\n    by (auto simp add: algebra_simps powr_add)\n  moreover have \"2*(2^n*2^m - c* 2^(m) + 2^(m) - c  + 1/2) =  2*(2^(n+m) + (1-c)* 2^(m) - c  + 1/2)\"\n    by (auto simp add: algebra_simps power_add) \n   moreover have \" 2*(2^(n+m) + (1-c)* 2^(m) - c  + 1/2) \\<le> 2*(2^(n+m) + -0.5*1 - 1.5 + 1/2)\" \n     by(auto simp add: algebra_simps two_realpow_ge_one c_def)\n  moreover hence \"2*(2^(n+m) + (1-c)*2^m - c + 1/2) \\<le> 2*(2^(n+m)  -  1.5 )\" \n    by(auto simp add: algebra_simps power_add)\n  ultimately have  \"cnt ( Node None deg treeList summary) \\<le> 2*(2^(n+m)  -  1.5 )\" by simp\n  then show ?case  using c_def 5 by simp\nqed (simp add: cnt.simps c_def)\n\ntheorem cnt_bound': \"invar_vebt t n \\<Longrightarrow> cnt t \\<le> 2 * (2 ^ n - 1)\" \n  using cnt_bound by fastforce\n\nlemma space_cnt: \"space' t \\<le> 6*cnt t\" \nproof(induction t)\n  case (Node info deg treeList summary)\n hence \" \\<forall>t\\<in>set treeList.  space' t \\<le> 6 * cnt t\" by blast\n  hence \" foldr (\\<lambda> a b. a+b) (map space' treeList) 0 \\<le>\n     6 *foldr (\\<lambda> a b. a+b) (map cnt treeList) 0\"  \n    using  f_g_map_foldr_bound[of treeList space' 6 cnt 0]\n    by(auto simp add: algebra_simps real_nat_list)\nthen show ?case\n  using Node.IH(2) by force\nqed simp\n\nlemma space_2_pow_bound:  assumes \"invar_vebt t n \" shows \"real (space' t) \\<le> 12 * (2^n -1)\" \nproof-\n  have \"space' t \\<le> 6 * cnt t\" \n    using space_cnt[of t] assms by simp\n  moreover have \"6 * cnt t \\<le> 12 * (2^n -1)\" \n    using cnt_bound'[of t n]  assms by simp\n  ultimately show ?thesis by linarith\nqed\n\nlemma space'_bound: assumes \"invar_vebt t n\" \"u = 2^n\"\n  shows \"space' t \\<le> 12 * u\"\n  using  space_2_pow_bound[of t n] \nproof -\nhave \"real u - 1 = real (u - 1)\"\nby (simp add: assms(2) of_nat_diff)\nthen show ?thesis\n  using \\<open>invar_vebt t n \\<Longrightarrow> real (space' t) \\<le> 12 * (2 ^ n - 1)\\<close> assms(1) assms(2) by auto\nqed\n\ntext \\<open>Main Theorem\\<close>\n\ntheorem space_bound: assumes \"invar_vebt t n\" \"u = 2^n\"\n  shows \"space t \\<le> 12 * u\"\n  by (metis assms(1) assms(2) dual_order.trans less_imp_le_nat space'_bound space_space')\n\nsubsection \\<open>Complexity of Generation Time \\<close>\ntext \\<open>Space complexity is closely related to tree generation time complexity\\<close>\n\ntext \\<open>Time approximation for replicate function. $T_{replicate} \\; n \\; t \\;x$ denotes runnig time of the $n$-times replication of $x$ into a list. \n$t$ models runtime for generation of a single $x$.\\<close>\n\nfun T\\<^sub>b\\<^sub>u\\<^sub>i\\<^sub>l\\<^sub>d\\<^sub>u\\<^sub>p::\"nat \\<Rightarrow> nat\" where\n\"T\\<^sub>b\\<^sub>u\\<^sub>i\\<^sub>l\\<^sub>d\\<^sub>u\\<^sub>p 0 = 3\"|\n\"T\\<^sub>b\\<^sub>u\\<^sub>i\\<^sub>l\\<^sub>d\\<^sub>u\\<^sub>p (Suc 0) = 3\"|\n\"T\\<^sub>b\\<^sub>u\\<^sub>i\\<^sub>l\\<^sub>d\\<^sub>u\\<^sub>p  n = (if even n then 1 + (let half = n div 2 in \n                 9 + T\\<^sub>b\\<^sub>u\\<^sub>i\\<^sub>l\\<^sub>d\\<^sub>u\\<^sub>p half +  (2^half) * (T\\<^sub>b\\<^sub>u\\<^sub>i\\<^sub>l\\<^sub>d\\<^sub>u\\<^sub>p half  + 1))\n                else (let half = n div 2 in\n                      11 + T\\<^sub>b\\<^sub>u\\<^sub>i\\<^sub>l\\<^sub>d\\<^sub>u\\<^sub>p (Suc half) +  (2^(Suc half))* (T\\<^sub>b\\<^sub>u\\<^sub>i\\<^sub>l\\<^sub>d\\<^sub>u\\<^sub>p half + 1 )))\"\n\nfun T\\<^sub>b\\<^sub>u\\<^sub>i\\<^sub>l\\<^sub>d::\"nat \\<Rightarrow> nat\" where\n\"T\\<^sub>b\\<^sub>u\\<^sub>i\\<^sub>l\\<^sub>d 0 = 4\"|\n\"T\\<^sub>b\\<^sub>u\\<^sub>i\\<^sub>l\\<^sub>d (Suc 0) = 4\"|\n\"T\\<^sub>b\\<^sub>u\\<^sub>i\\<^sub>l\\<^sub>d  n = (if even n then 1 + (let half = n div 2 in \n                 10 + T\\<^sub>b\\<^sub>u\\<^sub>i\\<^sub>l\\<^sub>d half +  (2^half) * (T\\<^sub>b\\<^sub>u\\<^sub>i\\<^sub>l\\<^sub>d half))\n                else (let half = n div 2 in\n                      12 + T\\<^sub>b\\<^sub>u\\<^sub>i\\<^sub>l\\<^sub>d (Suc half) +  (2^(Suc half))* (T\\<^sub>b\\<^sub>u\\<^sub>i\\<^sub>l\\<^sub>d half)))\"\n\nlemma buildup_build_time: \"T\\<^sub>b\\<^sub>u\\<^sub>i\\<^sub>l\\<^sub>d\\<^sub>u\\<^sub>p  n < T\\<^sub>b\\<^sub>u\\<^sub>i\\<^sub>l\\<^sub>d  n\"\nproof(induction n rule: T\\<^sub>b\\<^sub>u\\<^sub>i\\<^sub>l\\<^sub>d\\<^sub>u\\<^sub>p.induct)\n  case (3 va)\n  then show ?case\n  proof(cases \"even (Suc (Suc va))\")\n    case True\n    then show ?thesis \n      apply(subst T\\<^sub>b\\<^sub>u\\<^sub>i\\<^sub>l\\<^sub>d\\<^sub>u\\<^sub>p.simps)\n      apply(subst T\\<^sub>b\\<^sub>u\\<^sub>i\\<^sub>l\\<^sub>d.simps) \n      using True apply simp\n      by (smt (z3) \"3.IH\"(1) Suc_1 True add_mono_thms_linordered_semiring(1) distrib_left div2_Suc_Suc less_mult_imp_div_less linorder_not_le mult.commute mult_numeral_1_right nat_0_less_mult_iff nat_less_le nat_zero_less_power_iff nonzero_mult_div_cancel_left not_less_eq numerals(1) plus_1_eq_Suc zero_le_one)\n  next\n    case False\n    hence *: \"(let half = Suc (Suc va) div 2\n          in 11 + T\\<^sub>b\\<^sub>u\\<^sub>i\\<^sub>l\\<^sub>d\\<^sub>u\\<^sub>p (Suc half) + 2 ^ Suc half * (T\\<^sub>b\\<^sub>u\\<^sub>i\\<^sub>l\\<^sub>d\\<^sub>u\\<^sub>p half + 1))\n           <  (let half = Suc (Suc va) div 2\n            in 12 + T\\<^sub>b\\<^sub>u\\<^sub>i\\<^sub>l\\<^sub>d (Suc half) + 2 ^ Suc half * T\\<^sub>b\\<^sub>u\\<^sub>i\\<^sub>l\\<^sub>d half)\"\n      unfolding Let_def\n    proof-\n      assume \"odd (Suc (Suc va))\"\n    have \" 11 + T\\<^sub>b\\<^sub>u\\<^sub>i\\<^sub>l\\<^sub>d\\<^sub>u\\<^sub>p (Suc (Suc (Suc va) div 2))\n          < 12 + T\\<^sub>b\\<^sub>u\\<^sub>i\\<^sub>l\\<^sub>d (Suc (Suc (Suc va) div 2))\"\n      using \"3.IH\"(3) False add_less_mono by presburger\n    moreover have \" 2 ^ Suc (Suc (Suc va) div 2) * (T\\<^sub>b\\<^sub>u\\<^sub>i\\<^sub>l\\<^sub>d\\<^sub>u\\<^sub>p (Suc (Suc va) div 2) + 1)\n                   \\<le> 2 ^ Suc (Suc (Suc va) div 2) * T\\<^sub>b\\<^sub>u\\<^sub>i\\<^sub>l\\<^sub>d (Suc (Suc va) div 2)\"\n      by (metis \"3.IH\"(4) False Suc_leI add.commute mult_le_mono2 plus_1_eq_Suc)\n    ultimately show \" 11 + T\\<^sub>b\\<^sub>u\\<^sub>i\\<^sub>l\\<^sub>d\\<^sub>u\\<^sub>p (Suc (Suc (Suc va) div 2)) +\n                     2 ^ Suc (Suc (Suc va) div 2) * (T\\<^sub>b\\<^sub>u\\<^sub>i\\<^sub>l\\<^sub>d\\<^sub>u\\<^sub>p (Suc (Suc va) div 2) + 1)\n                     < 12 + T\\<^sub>b\\<^sub>u\\<^sub>i\\<^sub>l\\<^sub>d (Suc (Suc (Suc va) div 2)) +\n                       2 ^ Suc (Suc (Suc va) div 2) * T\\<^sub>b\\<^sub>u\\<^sub>i\\<^sub>l\\<^sub>d (Suc (Suc va) div 2)\" \n      using add_mono_thms_linordered_field(3) by blast\n  qed\n    show ?thesis apply(subst T\\<^sub>b\\<^sub>u\\<^sub>i\\<^sub>l\\<^sub>d\\<^sub>u\\<^sub>p.simps)\n      apply(subst T\\<^sub>b\\<^sub>u\\<^sub>i\\<^sub>l\\<^sub>d.simps) \n      using False *\n      by simp\n  qed\nqed simp+\n \n\nlemma listsum_bound: \"(\\<And> x. x \\<in> set xs \\<Longrightarrow> f x \\<ge> (0::real)) \\<Longrightarrow>\n        foldr (+) (map f xs) y \\<ge> y\"\n  apply(induction xs arbitrary: y)\n  apply simp\n  apply(subst list.map(2))\n  apply(subst foldr.simps)\n  apply (simp add: add_increasing)\n  done\n\nlemma cnt_non_neg: \"cnt t \\<ge> 0\"\n  by (induction t) (simp add: VEBT_internal.listsum_bound)+\n\nlemma foldr_same: \"(\\<And> x y. x \\<in> set (xs::real list) \\<Longrightarrow> y \\<in> set xs \\<Longrightarrow> x = y) \\<Longrightarrow>\n                   (\\<And> x . (x::real) \\<in> set xs \\<Longrightarrow> x = (y::real)) \\<Longrightarrow> \n                   foldr (\\<lambda> (a::real) (b::real). a+b) xs 0 = real (length xs) * y\"\n  apply(induction xs)\n    apply simp\n  apply(subst foldr.simps)\n  unfolding comp_def\nproof -\n  fix a :: real and xsa :: \"real list\"\n  assume a1: \"\\<lbrakk>\\<And>x y. \\<lbrakk>x \\<in> set xsa; y \\<in> set xsa\\<rbrakk> \\<Longrightarrow> x = y; \\<And>x. x \\<in> set xsa \\<Longrightarrow> x = y\\<rbrakk> \\<Longrightarrow> foldr (+) xsa 0 = real (length xsa) * y\"\n  assume \"\\<And>x y. \\<lbrakk>x \\<in> set (a # xsa); y \\<in> set (a # xsa)\\<rbrakk> \\<Longrightarrow> x = y\"\nassume a2: \"\\<And>x. x \\<in> set (a # xsa) \\<Longrightarrow> x = y\"\n  then have f3: \"a = y\"\n    by simp\n  then have \"a * real (length xsa) = foldr (+) xsa 0\"\n    using a2 a1 by (metis (no_types) list.set_intros(2) mult.commute)\n  then show \"a + foldr (+) xsa 0 = real (length (a # xsa)) * y\"\n    using f3 by (simp add: distrib_left mult.commute)\nqed \n\nlemma foldr_same_int: \"(\\<And> x y. x \\<in> set xs \\<Longrightarrow> y \\<in> set xs \\<Longrightarrow> x = y) \\<Longrightarrow>\n                   (\\<And> x . x \\<in> set xs \\<Longrightarrow> x = y) \\<Longrightarrow> \n                   foldr (+) xs 0 =  (length xs) * y\"\n  apply(induction xs)\n    apply simp\n    apply(subst foldr.simps) \n    apply fastforce\n  done\n\nlemma t_build_cnt: \"T\\<^sub>b\\<^sub>u\\<^sub>i\\<^sub>l\\<^sub>d n \\<le> cnt (vebt_buildup n) * 13\"  \nproof(induction n rule: T\\<^sub>b\\<^sub>u\\<^sub>i\\<^sub>l\\<^sub>d.induct)\n  case 1\n  then show ?case by simp\nnext\n  case 2\n  then show ?case by simp\nnext\n  case (3 va)\n  then show ?case \n  proof(cases \"even (Suc (Suc va))\")\n    case True\n    hence *: \"T\\<^sub>b\\<^sub>u\\<^sub>i\\<^sub>l\\<^sub>d (Suc (Suc va)) = 11+\n           T\\<^sub>b\\<^sub>u\\<^sub>i\\<^sub>l\\<^sub>d (Suc (Suc va) div 2) +\n         2 ^ (Suc (Suc va) div 2) * (T\\<^sub>b\\<^sub>u\\<^sub>i\\<^sub>l\\<^sub>d (Suc (Suc va) div 2))\"\n      apply(subst T\\<^sub>b\\<^sub>u\\<^sub>i\\<^sub>l\\<^sub>d.simps)\n      by simp\n    have \" real (T\\<^sub>b\\<^sub>u\\<^sub>i\\<^sub>l\\<^sub>d (Suc (va div 2))) \\<le> 13 * cnt (vebt_buildup (Suc (va div 2)))\" \n      using \"3.IH\"(1) True by force\n    moreover hence 1:\"  2 ^ (Suc (Suc va) div 2)* (T\\<^sub>b\\<^sub>u\\<^sub>i\\<^sub>l\\<^sub>d (Suc (Suc va) div 2)) \\<le>\n                    2 ^ (Suc (Suc va) div 2) * ((cnt (vebt_buildup (Suc (Suc va) div 2)))*13)\"\n      using ordered_semiring_class.mult_mono[of \"(T\\<^sub>b\\<^sub>u\\<^sub>i\\<^sub>l\\<^sub>d (Suc (Suc va) div 2))\" \" ((cnt (vebt_buildup (Suc (Suc va) div 2)))*13)\" \n            \"2 ^ (Suc (Suc va) div 2)\" \"2 ^ (Suc (Suc va) div 2)\"] by simp\n    ultimately have \" T\\<^sub>b\\<^sub>u\\<^sub>i\\<^sub>l\\<^sub>d (Suc (Suc va) div 2) +\n         2 ^ (Suc (Suc va) div 2) * (T\\<^sub>b\\<^sub>u\\<^sub>i\\<^sub>l\\<^sub>d (Suc (Suc va) div 2)) \\<le> \n             cnt (vebt_buildup (Suc (Suc va) div 2))*13 + \n          2 ^ (Suc (Suc va) div 2) * ((cnt (vebt_buildup (Suc (Suc va) div 2)))*13)\"\n           by (smt (verit) \"3.IH\"(1) True of_nat_add)\n         have 10: \"(foldr (+) \n                 (replicate (l) ((cnt (vebt_buildup (Suc (Suc va) div 2)))\n                  )) 0) = \n                   l * ((cnt (vebt_buildup (Suc (Suc va) div 2))))\" for l\n           using foldr_same[of \"(replicate l (cnt (vebt_buildup (Suc (Suc va) div 2))))\"\n                             \"cnt (vebt_buildup (Suc (Suc va) div 2))\" ] \n              length_replicate by simp\n         have \" cnt (vebt_buildup (Suc (Suc va) div 2))*13 + \n          2 ^ (Suc (Suc va) div 2) * ((cnt (vebt_buildup (Suc (Suc va) div 2)))*13) + 11\\<le>\n          13* cnt (vebt_buildup (Suc (Suc va)))\" \n          apply(subst vebt_buildup.simps)\n      using True apply simp\n      apply(subst sym[OF foldr_replicate]) \n    proof-\n      assume \"even va\"\n      have \" 2* (2 ^ (va div 2) * cnt (vebt_buildup (Suc (va div 2)))) = \n             foldr (+) (replicate (2 * 2 ^ (va div 2)) (cnt (vebt_buildup (Suc (va div 2))))) 0\"\n        apply(rule sym)\n        using 10 div2_Suc_Suc[of va] by simp\n      then show \"26 * (2 ^ (va div 2) * cnt (vebt_buildup (Suc (va div 2))))\n    \\<le> 2 + 13 * foldr (+) (replicate (2 * 2 ^ (va div 2)) (cnt (vebt_buildup (Suc (va div 2))))) 0\"\n        by simp\n    qed\n    then show ?thesis\n      by (smt (verit, ccfv_SIG) \"*\" \"1\" \"3.IH\"(1) True numeral_Bit1 numeral_plus_numeral numeral_plus_one of_nat_add of_nat_numeral semiring_norm(2))\n  next\n    case False\n    have \"12 + T\\<^sub>b\\<^sub>u\\<^sub>i\\<^sub>l\\<^sub>d (Suc ( Suc (va div 2))) + 2 ^ Suc ( Suc ( va div 2)) * T\\<^sub>b\\<^sub>u\\<^sub>i\\<^sub>l\\<^sub>d ( Suc ( va div 2))\n          \\<le> cnt ( Node None (Suc (Suc va)) (replicate (2 ^ Suc ( Suc ( va div 2))) (vebt_buildup ( Suc ( va div 2))))\n                     (vebt_buildup (Suc ( Suc ( va div 2))))) * 13\" \n      apply(subst cnt.simps)\n    proof-\n       have 10: \"(foldr (+) \n                 (replicate (l) ((cnt (vebt_buildup (Suc (Suc va) div 2)))\n                  )) 0) = \n                   l * ((cnt (vebt_buildup (Suc (Suc va) div 2))))\" for l\n           using foldr_same[of \"(replicate l (cnt (vebt_buildup (Suc (Suc va) div 2))))\"\n                             \"cnt (vebt_buildup (Suc (Suc va) div 2))\" ] \n              length_replicate by simp\n        hence map_cnt: \" foldr (+) (map cnt (replicate (2 ^ Suc (Suc (va div 2))) (vebt_buildup (Suc (va div 2))))) 0 = \n                 2 ^ Suc (Suc (va div 2)) * cnt (vebt_buildup (Suc (va div 2))) \" by simp\n        have \"T\\<^sub>b\\<^sub>u\\<^sub>i\\<^sub>l\\<^sub>d (Suc (Suc (va div 2))) \\<le> 13 * cnt (vebt_buildup (Suc (Suc (va div 2))))\"\n          using \"3.IH\"(3) False by force\n        moreover have \"T\\<^sub>b\\<^sub>u\\<^sub>i\\<^sub>l\\<^sub>d (Suc (va div 2)) \\<le> 13 * cnt(vebt_buildup (Suc (va div 2)))\"\n          using \"3.IH\"(4) False by force\n        moreover have add_double_trans: \"(a::real) \\<le> b \\<Longrightarrow> c \\<le> d \\<Longrightarrow> \n                           i \\<ge> 0\\<Longrightarrow> a + c*i \\<le> b + d*i\" for a b c d i\n          using mult_right_mono by fastforce\n        ultimately have \" real(T\\<^sub>b\\<^sub>u\\<^sub>i\\<^sub>l\\<^sub>d (Suc (Suc (va div 2)))) +  2 ^ Suc (Suc (va div 2)) * real( T\\<^sub>b\\<^sub>u\\<^sub>i\\<^sub>l\\<^sub>d (Suc (va div 2))) \\<le>\n                13 * cnt (vebt_buildup (Suc (Suc (va div 2)))) + \n                    2 ^ Suc (Suc (va div 2)) * (13 * cnt(vebt_buildup (Suc (va div 2))))\" \n          by (meson add_mono_thms_linordered_semiring(1) mult_mono of_nat_0_le_iff order_refl zero_le_numeral zero_le_power)\n        hence 11:\"(12 + T\\<^sub>b\\<^sub>u\\<^sub>i\\<^sub>l\\<^sub>d (Suc (Suc (va div 2))) +  2 ^ Suc (Suc (va div 2)) * T\\<^sub>b\\<^sub>u\\<^sub>i\\<^sub>l\\<^sub>d (Suc (va div 2))) \\<le>\n               12 + 13 * cnt (vebt_buildup (Suc (Suc (va div 2)))) + \n                    2 ^ Suc (Suc (va div 2)) * 13 * cnt(vebt_buildup (Suc (va div 2)))\"\n          using algebra_simps by simp\n        show \" (12 + T\\<^sub>b\\<^sub>u\\<^sub>i\\<^sub>l\\<^sub>d (Suc (Suc (va div 2))) +\n      2 ^ Suc (Suc (va div 2)) * T\\<^sub>b\\<^sub>u\\<^sub>i\\<^sub>l\\<^sub>d (Suc (va div 2)))\n    \\<le> (1 + cnt (vebt_buildup (Suc (Suc (va div 2)))) +\n        foldr (+) (map cnt (replicate (2 ^ Suc (Suc (va div 2))) (vebt_buildup (Suc (va div 2))))) 0) * 13\" \n          apply(subst map_cnt)\n          using 11 algebra_simps by simp\n      qed        \n  then show ?thesis\n    apply(subst vebt_buildup.simps)\n    apply(subst T\\<^sub>b\\<^sub>u\\<^sub>i\\<^sub>l\\<^sub>d.simps)\n    using False by force\nqed\nqed\n\nlemma t_buildup_cnt: \"T\\<^sub>b\\<^sub>u\\<^sub>i\\<^sub>l\\<^sub>d\\<^sub>u\\<^sub>p  n \\<le> cnt (vebt_buildup n) * 13\"\n  apply(rule order.trans[where b = \"real(T\\<^sub>b\\<^sub>u\\<^sub>i\\<^sub>l\\<^sub>d n)\"])\n  apply(rule order.strict_implies_order)\n  apply (simp add: VEBT_internal.buildup_build_time)\n  apply(rule t_build_cnt)\n done\n\nlemma count_buildup: \"cnt (vebt_buildup n) \\<le> 2 * 2^n\"\n  by (smt (verit, ccfv_threshold) VEBT_internal.cnt_bound' add.right_neutral add_less_mono buildup_gives_valid cnt.simps(1) even_Suc lessI odd_pos one_le_power plus_1_eq_Suc vebt_buildup.elims)\n\nlemma count_buildup': \"cnt (vebt_buildup n) \\<le> 2 * (2::nat)^n\"\n   by (simp add: VEBT_internal.count_buildup)\n\ntheorem vebt_buildup_bound: \"u = 2^n \\<Longrightarrow> T\\<^sub>b\\<^sub>u\\<^sub>i\\<^sub>l\\<^sub>d\\<^sub>u\\<^sub>p  n \\<le> 26 * u\"\n  using count_buildup'[of n] t_buildup_cnt[of n] by linarith\n\ntext \\<open>Count in natural numbers\\<close>\n\nfun cnt':: \"VEBT \\<Rightarrow> nat\" where\n\"cnt' (Leaf a b) = 1\"|\n\"cnt' (Node info deg treeList summary) = 1 + cnt' summary + foldr (\\<lambda> a b. a+b) (map cnt' treeList) 0\"\n\nlemma cnt_cnt_eq:\"cnt t = cnt' t\"\n  apply(induction t)\n  apply auto\n  apply (smt (z3) VEBT_internal.real_nat_list map_eq_conv of_nat_0)\n  done\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/Van_Emde_Boas_Trees/VEBT_Space.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8596637433190939, "lm_q2_score": 0.8333245953120234, "lm_q1q2_score": 0.7163789410058031}}
{"text": "\nsection \\<open>Index-based manipulation of lists\\<close>\n\ntheory List_Index imports Main begin\n\ntext \\<open>\\noindent\nThis theory collects functions for index-based manipulation of lists.\n\\<close>\n\nsubsection \\<open>Finding an index\\<close>\n\ntext \\<open>\nThis subsection defines three functions for finding the index of items in a list:\n\\begin{description}\n\\item[\\<open>find_index P xs\\<close>] finds the index of the first element in\n \\<open>xs\\<close> that satisfies \\<open>P\\<close>.\n\\item[\\<open>index xs x\\<close>] finds the index of the first occurrence of\n \\<open>x\\<close> in \\<open>xs\\<close>.\n\\item[\\<open>last_index xs x\\<close>] finds the index of the last occurrence of\n \\<open>x\\<close> in \\<open>xs\\<close>.\n\\end{description}\nAll functions return @{term \"length xs\"} if \\<open>xs\\<close> does not contain a\nsuitable element.\n\nThe argument order of \\<open>find_index\\<close> follows the function of the same\nname in the Haskell standard library. For \\<open>index\\<close> (and \\<open>last_index\\<close>) the order is intentionally reversed: \\<open>index\\<close> maps\nlists to a mapping from elements to their indices, almost the inverse of\nfunction \\<open>nth\\<close>.\\<close>\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_append: \"find_index P (xs @ ys) =\n  (if \\<exists>x\\<in>set xs. P x then find_index P xs else size xs + find_index P ys)\"\n  by (induct xs) simp_all\n  \nlemma find_index_le_size[simp]: \"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) = (\\<forall>x \\<in> 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) = (\\<forall>x \\<in> 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) = (\\<exists>x \\<in> 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_rev: \"\\<lbrakk> distinct xs; x \\<in> set xs \\<rbrakk> \\<Longrightarrow>\n  index (rev xs) x = length xs - index xs x - 1\"\nby (induct xs) (auto simp: index_append)\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_upt[simp]: \"m \\<le> i \\<Longrightarrow> i < n \\<Longrightarrow> index [m..<n] i = i-m\"\nby (induction n) (auto simp add: index_append)\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_index2: \"I \\<subseteq> set xs \\<Longrightarrow> inj_on (index xs) I\"\nby (rule inj_onI) auto\n\nlemma inj_on_last_index: \"inj_on (last_index xs) (set xs)\"\nby (simp add:inj_on_def)\n\nlemma find_index_conv_takeWhile: \n  \"find_index P xs = size(takeWhile (Not o P) xs)\"\nby(induct xs) auto\n\nlemma index_conv_takeWhile: \"index xs x = size(takeWhile (\\<lambda>y. x\\<noteq>y) xs)\"\nby(induct xs) auto\n\nlemma find_index_first: \"i < find_index P xs \\<Longrightarrow> \\<not>P (xs!i)\"\nunfolding find_index_conv_takeWhile\nby (metis comp_apply nth_mem set_takeWhileD takeWhile_nth)\n\nlemma index_first: \"i<index xs x \\<Longrightarrow> x\\<noteq>xs!i\"\nusing find_index_first unfolding index_def by blast\n\nlemma find_index_eqI:\n  assumes \"i\\<le>length xs\"  \n  assumes \"\\<forall>j<i. \\<not>P (xs!j)\"\n  assumes \"i<length xs \\<Longrightarrow> P (xs!i)\"\n  shows \"find_index P xs = i\"\nby (metis (mono_tags, lifting) antisym_conv2 assms find_index_eq_size_conv \n  find_index_first find_index_less_size_conv linorder_neqE_nat nth_find_index)\n  \nlemma find_index_eq_iff:\n  \"find_index P xs = i \n  \\<longleftrightarrow> (i\\<le>length xs \\<and> (\\<forall>j<i. \\<not>P (xs!j)) \\<and> (i<length xs \\<longrightarrow> P (xs!i)))\"  \nby (auto intro: find_index_eqI \n         simp: nth_find_index find_index_le_size find_index_first)\n\nlemma find_index_property:\n  \"find_index P xs \\<le> length xs \\<and> (\\<forall>j < find_index P xs. \\<not>P (xs ! j)) \\<and>\n    (find_index P xs < length xs \\<longrightarrow> P (xs ! find_index P xs))\" \n  by (meson find_index_eq_iff)\n\nlemma index_eqI:\n  assumes \"i\\<le>length xs\"  \n  assumes \"\\<forall>j<i. xs!j \\<noteq> x\"\n  assumes \"i<length xs \\<Longrightarrow> xs!i = x\"\n  shows \"index xs x = i\"\nunfolding index_def by (simp add: find_index_eqI assms)\n  \nlemma index_eq_iff:\n  \"index xs x = i \n  \\<longleftrightarrow> (i\\<le>length xs \\<and> (\\<forall>j<i. xs!j \\<noteq> x) \\<and> (i<length xs \\<longrightarrow> xs!i = x))\"  \nby (auto intro: index_eqI \n         simp: index_le_size index_less_size_conv \n         dest: index_first)\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 ((\\<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:if_split_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\n\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\nlemma bij_betw_index:\n  \"distinct xs \\<Longrightarrow> X = set xs \\<Longrightarrow> l = size xs \\<Longrightarrow> bij_betw (index xs) X {0..<l}\"\napply simp\napply(rule bij_betw_imageI[OF inj_on_index])\nby (auto simp: image_def) (metis index_nth_id nth_mem)\n\nlemma index_image: \"distinct xs \\<Longrightarrow> set xs = X \\<Longrightarrow> index xs ` X = {0..<size xs}\"\nby (simp add: bij_betw_imp_surj_on bij_betw_index)\n\nlemma index_map_inj_on:\n  \"\\<lbrakk> inj_on f S; y \\<in> S; set xs \\<subseteq> S \\<rbrakk> \\<Longrightarrow> index (map f xs) (f y) = index xs y\"\nby (induct xs) (auto simp: inj_on_eq_iff)\n\nlemma index_map_inj: \"inj f \\<Longrightarrow> index (map f xs) (f y) = index xs y\"\nby (simp add: index_map_inj_on[where S=UNIV])\n\nsubsection \\<open>Map with index\\<close>\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 (case_prod 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 (case_prod f) (zip [Suc n ..< n + length (x # xs)] xs)\" by simp\n  also have \"\\<dots> =  map (case_prod 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 _ \"case_prod 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 _ \"case_prod f\"])\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 \\<open>Insert at position\\<close>\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\nlemma set_insert_nth:\n  \"set (insert_nth i x xs) = insert x (set xs)\"\nby (simp add: set_append[symmetric])\n\nlemma distinct_insert_nth:\n  assumes \"distinct xs\"\n  assumes \"x \\<notin> set xs\"\n  shows \"distinct (insert_nth i x xs)\"\nusing assms proof (induct xs arbitrary: i)\n  case Nil\n  then show ?case by (cases i) auto\nnext\n  case (Cons a xs)\n  then show ?case\n    by (cases i) (auto simp add: set_insert_nth simp del: insert_nth_take_drop)\nqed\n\nlemma nth_insert_nth_front:\n  assumes \"i < j\" \"j \\<le> length xs\"\n  shows \"insert_nth j x xs ! i = xs ! i\"\nusing assms by (simp add: nth_append)\n\nlemma nth_insert_nth_index_eq:\n  assumes \"i \\<le> length xs\"\n  shows \"insert_nth i x xs ! i = x\"\nusing assms by (simp add: nth_append)\n\nlemma nth_insert_nth_back:\n  assumes \"j < i\" \"i \\<le> length xs\"\n  shows \"insert_nth j x xs ! i = xs ! (i - 1)\"\nusing assms by (cases i) (auto simp add: nth_append min_def)\n\nlemma nth_insert_nth:\n  assumes \"i \\<le> length xs\" \"j \\<le> length xs\"\n  shows \"insert_nth j x xs ! i = (if i = j then x else if i < j then xs ! i else xs ! (i - 1))\"\nusing assms by (simp add: nth_insert_nth_front nth_insert_nth_index_eq nth_insert_nth_back del: insert_nth_take_drop)\n\nlemma insert_nth_inverse:\n  assumes \"j \\<le> length xs\" \"j' \\<le> length xs'\"\n  assumes \"x \\<notin> set xs\" \"x \\<notin> set xs'\"\n  assumes \"insert_nth j x xs = insert_nth j' x xs'\"\n  shows \"j = j'\"\nproof -\n  from assms(1,3) have \"\\<forall>i\\<le>length xs. insert_nth j x xs ! i = x \\<longleftrightarrow> i = j\"\n    by (auto simp add: nth_insert_nth simp del: insert_nth_take_drop)\n  moreover from assms(2,4) have \"\\<forall>i\\<le>length xs'. insert_nth j' x xs' ! i = x \\<longleftrightarrow> i = j'\"\n    by (auto simp add: nth_insert_nth simp del: insert_nth_take_drop)\n  ultimately show \"j = j'\"\n    using assms(1,2,5) by (metis dual_order.trans nat_le_linear)\nqed\n\ntext \\<open>Insert several elements at given (ascending) positions\\<close>\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_append le_eq_less_or_eq)\n      with snoc.prems show ?case by (intro snoc(1)) (auto simp: 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: 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))\n  qed\nqed simp\n\nsubsection \\<open>Remove at position\\<close>\n\nfun remove_nth :: \"nat \\<Rightarrow> 'a list \\<Rightarrow> 'a list\"\nwhere\n  \"remove_nth i [] = []\"\n| \"remove_nth 0 (x # xs) = xs\"\n| \"remove_nth (Suc i) (x # xs) = x # remove_nth i xs\"\n\nlemma remove_nth_take_drop:\n  \"remove_nth i xs = take i xs @ drop (Suc i) xs\"\nproof (induct xs arbitrary: i)\n  case Nil\n  then show ?case by simp\nnext\n  case (Cons a xs)\n  then show ?case by (cases i) auto\nqed\n\nlemma remove_nth_insert_nth:\n  assumes \"i \\<le> length xs\"\n  shows \"remove_nth i (insert_nth i x xs) = xs\"\nusing assms proof (induct xs arbitrary: i)\n  case Nil\n  then show ?case by simp\nnext\n  case (Cons a xs)\n  then show ?case by (cases i) auto\nqed\n\nlemma insert_nth_remove_nth:\n  assumes \"i < length xs\"\n  shows \"insert_nth i (xs ! i) (remove_nth i xs) = xs\"\nusing assms proof (induct xs arbitrary: i)\n  case Nil\n  then show ?case by simp\nnext\n  case (Cons a xs)\n  then show ?case by (cases i) auto\nqed\n\nlemma length_remove_nth:\n  assumes \"i < length xs\"\n  shows \"length (remove_nth i xs) = length xs - 1\"\nusing assms unfolding remove_nth_take_drop by simp\n\nlemma set_remove_nth_subset:\n  \"set (remove_nth j xs) \\<subseteq> set xs\"\nproof (induct xs arbitrary: j)\n  case Nil\n  then show ?case by simp\nnext\n  case (Cons a xs)\n  then show ?case by (cases j) auto\nqed\n\nlemma set_remove_nth:\n  assumes \"distinct xs\" \"j < length xs\"\n  shows \"set (remove_nth j xs) = set xs - {xs ! j}\"\nusing assms proof (induct xs arbitrary: j)\n  case Nil\n  then show ?case by simp\nnext\n  case (Cons a xs)\n  then show ?case by (cases j) auto\nqed\n\nlemma distinct_remove_nth:\n  assumes \"distinct xs\"\n  shows \"distinct (remove_nth i xs)\"\nusing assms proof (induct xs arbitrary: i)\n  case Nil\n  then show ?case by simp\nnext\n  case (Cons a xs)\n  then show ?case\n    by (cases i) (auto simp add: set_remove_nth_subset rev_subsetD)\nqed\n\nlemma find_index_sorted_le[simp]: \"sorted xs \\<Longrightarrow> i < length xs \\<Longrightarrow> xs ! i < x \\<Longrightarrow> i < find_index ((\\<le>) x) xs\" \n    and find_index_sorted_leq[simp]: \"sorted xs \\<Longrightarrow> i < length xs \\<Longrightarrow> x \\<le> xs ! i \\<Longrightarrow> find_index ((\\<le>) x) xs \\<le> i\"\n  unfolding sorted_iff_nth_mono\n  by (metis less_le_trans linorder_neqE_nat not_le find_index_property find_index_property)+\n\nend\n", "meta": {"author": "nusystem", "repo": "nu-system", "sha": "148c5a354ad8780cc4da9b91e1291414c91b2eda", "save_path": "github-repos/isabelle/nusystem-nu-system", "path": "github-repos/isabelle/nusystem-nu-system/nu-system-148c5a354ad8780cc4da9b91e1291414c91b2eda/List_Index.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8333245870332531, "lm_q2_score": 0.8596637469145053, "lm_q1q2_score": 0.7163789368849891}}
{"text": "(* Author: Tobias Nipkow *)\n\nsection \\<open>Creating Almost Complete 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 acomplete_bal:\n  assumes \"n \\<le> length xs\" \"bal n xs = (t,ys)\" shows \"acomplete t\"\nunfolding acomplete_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 acomplete_bal_list[simp]: \"n \\<le> length xs \\<Longrightarrow> acomplete (bal_list n xs)\"\nunfolding bal_list_def by (metis  acomplete_bal prod.collapse)\n\ncorollary acomplete_balance_list[simp]: \"acomplete (balance_list xs)\"\nby (simp add: balance_list_def)\n\ncorollary acomplete_bal_tree[simp]: \"n \\<le> size t \\<Longrightarrow> acomplete (bal_tree n t)\"\nby (simp add: bal_tree_def)\n\ncorollary acomplete_balance_tree[simp]: \"acomplete (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 acomplete_if_wbalanced}:\\<close>\nlemma \"\\<lbrakk> n \\<le> length xs; bal n xs = (t,ys) \\<rbrakk> \\<Longrightarrow> acomplete t\"\nby(rule acomplete_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": "seL4", "repo": "isabelle", "sha": "e1ab32a3bb41728cd19541063283e37919978a4c", "save_path": "github-repos/isabelle/seL4-isabelle", "path": "github-repos/isabelle/seL4-isabelle/isabelle-e1ab32a3bb41728cd19541063283e37919978a4c/src/HOL/Data_Structures/Balance.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8688267762381843, "lm_q2_score": 0.8244619220634457, "lm_q1q2_score": 0.7163145938775206}}
{"text": "header {* \\isaheader{Auxiliary lemmas} *}\n\ntheory AuxLemmas imports Main begin\n\nabbreviation \"arbitrary == undefined\"\n\ntext {* Lemmas about left- and rightmost elements in lists *}\n\nlemma leftmost_element_property:\n  assumes \"\\<exists>x \\<in> set xs. P x\"\n  obtains zs x' ys where \"xs = zs@x'#ys\" and \"P x'\" and \"\\<forall>z \\<in> set zs. \\<not> P z\"\nproof(atomize_elim)\n  from `\\<exists>x \\<in> set xs. P x` \n  show \"\\<exists>zs x' ys. xs = zs @ x' # ys \\<and> P x' \\<and> (\\<forall>z\\<in>set zs. \\<not> P z)\"\n  proof(induct xs)\n    case Nil thus ?case by simp\n  next\n    case (Cons x' xs')\n    note IH = `\\<exists>a\\<in>set xs'. P a\n      \\<Longrightarrow> \\<exists>zs x' ys. xs' = zs@x'#ys \\<and> P x' \\<and> (\\<forall>z\\<in>set zs. \\<not> P z)`\n    show ?case\n    proof (cases \"P x'\")\n      case True\n      then have \"(\\<exists>ys. x' # xs' = [] @ x' # ys) \\<and> P x' \\<and> (\\<forall>x\\<in>set []. \\<not> P x)\" by simp\n      then show ?thesis by blast\n    next\n      case False\n      with `\\<exists>y\\<in>set (x'#xs'). P y` have \"\\<exists>y\\<in>set xs'. P y\" by simp\n      from IH[OF this] obtain y ys zs where \"xs' = zs@y#ys\"\n        and \"P y\" and \"\\<forall>z\\<in>set zs. \\<not> P z\" by blast\n      from `\\<forall>z\\<in>set zs. \\<not> P z` False have \"\\<forall>z\\<in>set (x'#zs). \\<not> P z\" by simp\n      with `xs' = zs@y#ys` `P y` show ?thesis by (metis Cons_eq_append_conv)\n    qed\n  qed\nqed\n\n\n\nlemma rightmost_element_property:\n  assumes \"\\<exists>x \\<in> set xs. P x\"\n  obtains ys x' zs where \"xs = ys@x'#zs\" and \"P x'\" and \"\\<forall>z \\<in> set zs. \\<not> P z\"\nproof(atomize_elim)\n  from `\\<exists>x \\<in> set xs. P x`\n  show \"\\<exists>ys x' zs. xs = ys @ x' # zs \\<and> P x' \\<and> (\\<forall>z\\<in>set zs. \\<not> P z)\"\n  proof(induct xs)\n    case Nil thus ?case by simp\n  next\n    case (Cons x' xs')\n    note IH = `\\<exists>a\\<in>set xs'. P a\n      \\<Longrightarrow> \\<exists>ys x' zs. xs' = ys @ x' # zs \\<and> P x' \\<and> (\\<forall>z\\<in>set zs. \\<not> P z)`\n    show ?case\n    proof(cases \"\\<exists>y\\<in>set xs'. P y\")\n      case True\n      from IH[OF this] obtain y ys zs where \"xs' = ys @ y # zs\"\n        and \"P y\" and \"\\<forall>z\\<in>set zs. \\<not> P z\" by blast\n      thus ?thesis by (metis Cons_eq_append_conv)\n    next\n      case False\n      with `\\<exists>y\\<in>set (x'#xs'). P y` have \"P x'\" by simp\n      with False show ?thesis by (metis eq_Nil_appendI)\n    qed\n  qed\nqed\n\n\ntext {* Lemma concerning maps and @{text @} *}\n\nlemma map_append_append_maps:\n  assumes map:\"map f xs = ys@zs\"\n  obtains xs' xs'' where \"map f xs' = ys\" and \"map f xs'' = zs\" and \"xs=xs'@xs''\"\nby (metis append_eq_conv_conj append_take_drop_id assms drop_map take_map that)\n\n\ntext {* Lemma concerning splitting of @{term list}s *}\n\nlemma  path_split_general:\nassumes all:\"\\<forall>zs. xs \\<noteq> ys@zs\"\nobtains j zs where \"xs = (take j ys)@zs\" and \"j < length ys\"\n  and \"\\<forall>k > j. \\<forall>zs'. xs \\<noteq> (take k ys)@zs'\"\nproof(atomize_elim)\n  from `\\<forall>zs. xs \\<noteq> ys@zs`\n  show \"\\<exists>j zs. xs = take j ys @ zs \\<and> j < length ys \\<and> \n               (\\<forall>k>j. \\<forall>zs'. xs \\<noteq> take k ys @ zs')\"\n  proof(induct ys arbitrary:xs)\n    case Nil thus ?case by auto\n  next\n    case (Cons y' ys')\n    note IH = `\\<And>xs. \\<forall>zs. xs \\<noteq> ys' @ zs \\<Longrightarrow>\n      \\<exists>j zs. xs = take j ys' @ zs \\<and> j < length ys' \\<and> \n      (\\<forall>k. j < k \\<longrightarrow> (\\<forall>zs'. xs \\<noteq> take k ys' @ zs'))`\n    show ?case\n    proof(cases xs)\n      case Nil thus ?thesis by simp\n    next\n      case (Cons x' xs')\n      with `\\<forall>zs. xs \\<noteq> (y' # ys') @ zs` have \"x' \\<noteq> y' \\<or> (\\<forall>zs. xs' \\<noteq> ys' @ zs)\"\n        by simp\n      show ?thesis\n      proof(cases \"x' = y'\")\n        case True\n        with `x' \\<noteq> y' \\<or> (\\<forall>zs. xs' \\<noteq> ys' @ zs)` have \"\\<forall>zs. xs' \\<noteq> ys' @ zs\" by simp\n        from IH[OF this] have \"\\<exists>j zs. xs' = take j ys' @ zs \\<and> j < length ys' \\<and>\n          (\\<forall>k. j < k \\<longrightarrow> (\\<forall>zs'. xs' \\<noteq> take k ys' @ zs'))\" .\n        then obtain j zs where \"xs' = take j ys' @ zs\"\n          and \"j < length ys'\"\n          and all_sub:\"\\<forall>k. j < k \\<longrightarrow> (\\<forall>zs'. xs' \\<noteq> take k ys' @ zs')\"\n          by blast\n        from `xs' = take j ys' @ zs` True\n          have \"(x'#xs') = take (Suc j) (y' # ys') @ zs\"\n          by simp\n        from all_sub True have all_imp:\"\\<forall>k. j < k \\<longrightarrow> \n          (\\<forall>zs'. (x'#xs') \\<noteq> take (Suc k) (y' # ys') @ zs')\"\n          by auto\n        { fix l assume \"(Suc j) < l\"\n          then obtain k where [simp]:\"l = Suc k\" by(cases l) auto\n          with `(Suc j) < l` have \"j < k\" by simp\n          with all_imp \n          have \"\\<forall>zs'. (x'#xs') \\<noteq> take (Suc k) (y' # ys') @ zs'\"\n            by simp\n          hence \"\\<forall>zs'. (x'#xs') \\<noteq> take l (y' # ys') @ zs'\"\n            by simp }\n        with `(x'#xs') = take (Suc j) (y' # ys') @ zs` `j < length ys'` Cons\n        show ?thesis by (metis Suc_length_conv less_Suc_eq_0_disj)\n      next\n        case False\n        with Cons have \"\\<forall>i zs'. i > 0 \\<longrightarrow> xs \\<noteq> take i (y' # ys') @ zs'\"\n          by auto(case_tac i,auto)\n        moreover\n        have \"\\<exists>zs. xs = take 0 (y' # ys') @ zs\" by simp\n        ultimately show ?thesis by(rule_tac x=\"0\" in exI,auto)\n      qed\n    qed\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/Slicing/Basic/AuxLemmas.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430436757313, "lm_q2_score": 0.8615382076534742, "lm_q1q2_score": 0.7160614881520428}}
{"text": "(*  Title:      HOL/Number_Theory/MiscAlgebra.thy\n    Author:     Jeremy Avigad\n*)\n\nsection \\<open>Things that can be added to the Algebra library\\<close>\n\ntheory MiscAlgebra\nimports\n  \"~~/src/HOL/Algebra/Ring\"\n  \"~~/src/HOL/Algebra/FiniteProduct\"\nbegin\n\nsubsection \\<open>Finiteness stuff\\<close>\n\nlemma bounded_set1_int [intro]: \"finite {(x::int). a < x & x < b & P x}\"\n  apply (subgoal_tac \"{x. a < x & x < b & P x} <= {a<..<b}\")\n  apply (erule finite_subset)\n  apply auto\n  done\n\n\nsubsection \\<open>The rest is for the algebra libraries\\<close>\n\nsubsubsection \\<open>These go in Group.thy\\<close>\n\ntext \\<open>\n  Show that the units in any monoid give rise to a group.\n\n  The file Residues.thy provides some infrastructure to use\n  facts about the unit group within the ring locale.\n\\<close>\n\ndefinition units_of :: \"('a, 'b) monoid_scheme => 'a monoid\" where\n  \"units_of G == (| carrier = Units G,\n     Group.monoid.mult = Group.monoid.mult G,\n     one  = one G |)\"\n\n(*\n\nlemma (in monoid) Units_mult_closed [intro]:\n  \"x : Units G ==> y : Units G ==> x \\<otimes> y : Units G\"\n  apply (unfold Units_def)\n  apply (clarsimp)\n  apply (rule_tac x = \"xaa \\<otimes> xa\" in bexI)\n  apply auto\n  apply (subst m_assoc)\n  apply auto\n  apply (subst (2) m_assoc [symmetric])\n  apply auto\n  apply (subst m_assoc)\n  apply auto\n  apply (subst (2) m_assoc [symmetric])\n  apply auto\ndone\n\n*)\n\nlemma (in monoid) units_group: \"group(units_of G)\"\n  apply (unfold units_of_def)\n  apply (rule groupI)\n  apply auto\n  apply (subst m_assoc)\n  apply auto\n  apply (rule_tac x = \"inv x\" in bexI)\n  apply auto\n  done\n\nlemma (in comm_monoid) units_comm_group: \"comm_group(units_of G)\"\n  apply (rule group.group_comm_groupI)\n  apply (rule units_group)\n  apply (insert comm_monoid_axioms)\n  apply (unfold units_of_def Units_def comm_monoid_def comm_monoid_axioms_def)\n  apply auto\n  done\n\nlemma units_of_carrier: \"carrier (units_of G) = Units G\"\n  unfolding units_of_def by auto\n\nlemma units_of_mult: \"mult(units_of G) = mult G\"\n  unfolding units_of_def by auto\n\nlemma units_of_one: \"one(units_of G) = one G\"\n  unfolding units_of_def by auto\n\nlemma (in monoid) units_of_inv: \"x : Units G ==> m_inv (units_of G) x = m_inv G x\"\n  apply (rule sym)\n  apply (subst m_inv_def)\n  apply (rule the1_equality)\n  apply (rule ex_ex1I)\n  apply (subst (asm) Units_def)\n  apply auto\n  apply (erule inv_unique)\n  apply auto\n  apply (rule Units_closed)\n  apply (simp_all only: units_of_carrier [symmetric])\n  apply (insert units_group)\n  apply auto\n  apply (subst units_of_mult [symmetric])\n  apply (subst units_of_one [symmetric])\n  apply (erule group.r_inv, assumption)\n  apply (subst units_of_mult [symmetric])\n  apply (subst units_of_one [symmetric])\n  apply (erule group.l_inv, assumption)\n  done\n\nlemma (in group) inj_on_const_mult: \"a: (carrier G) ==> inj_on (%x. a \\<otimes> x) (carrier G)\"\n  unfolding inj_on_def by auto\n\nlemma (in group) surj_const_mult: \"a : (carrier G) ==> (%x. a \\<otimes> x) ` (carrier G) = (carrier G)\"\n  apply (auto simp add: image_def)\n  apply (rule_tac x = \"(m_inv G a) \\<otimes> x\" in bexI)\n  apply auto\n(* auto should get this. I suppose we need \"comm_monoid_simprules\"\n   for ac_simps rewriting. *)\n  apply (subst m_assoc [symmetric])\n  apply auto\n  done\n\nlemma (in group) l_cancel_one [simp]:\n    \"x : carrier G \\<Longrightarrow> a : carrier G \\<Longrightarrow> (x \\<otimes> a = x) = (a = one G)\"\n  apply auto\n  apply (subst l_cancel [symmetric])\n  prefer 4\n  apply (erule ssubst)\n  apply auto\n  done\n\nlemma (in group) r_cancel_one [simp]: \"x : carrier G \\<Longrightarrow> a : carrier G \\<Longrightarrow>\n    (a \\<otimes> x = x) = (a = one G)\"\n  apply auto\n  apply (subst r_cancel [symmetric])\n  prefer 4\n  apply (erule ssubst)\n  apply auto\n  done\n\n(* Is there a better way to do this? *)\nlemma (in group) l_cancel_one' [simp]: \"x : carrier G \\<Longrightarrow> a : carrier G \\<Longrightarrow>\n    (x = x \\<otimes> a) = (a = one G)\"\n  apply (subst eq_commute)\n  apply simp\n  done\n\nlemma (in group) r_cancel_one' [simp]: \"x : carrier G \\<Longrightarrow> a : carrier G \\<Longrightarrow>\n    (x = a \\<otimes> x) = (a = one G)\"\n  apply (subst eq_commute)\n  apply simp\n  done\n\n(* This should be generalized to arbitrary groups, not just commutative\n   ones, using Lagrange's theorem. *)\n\nlemma (in comm_group) power_order_eq_one:\n  assumes fin [simp]: \"finite (carrier G)\"\n    and a [simp]: \"a : carrier G\"\n  shows \"a (^) card(carrier G) = one G\"\nproof -\n  have \"(\\<Otimes>x\\<in>carrier G. x) = (\\<Otimes>x\\<in>carrier G. a \\<otimes> x)\"\n    by (subst (2) finprod_reindex [symmetric],\n      auto simp add: Pi_def inj_on_const_mult surj_const_mult)\n  also have \"\\<dots> = (\\<Otimes>x\\<in>carrier G. a) \\<otimes> (\\<Otimes>x\\<in>carrier G. x)\"\n    by (auto simp add: finprod_multf Pi_def)\n  also have \"(\\<Otimes>x\\<in>carrier G. a) = a (^) card(carrier G)\"\n    by (auto simp add: finprod_const)\n  finally show ?thesis\n(* uses the preceeding lemma *)\n    by auto\nqed\n\n\nsubsubsection \\<open>Miscellaneous\\<close>\n\nlemma (in cring) field_intro2: \"\\<zero>\\<^bsub>R\\<^esub> ~= \\<one>\\<^bsub>R\\<^esub> \\<Longrightarrow> \\<forall>x \\<in> carrier R - {\\<zero>\\<^bsub>R\\<^esub>}. x \\<in> Units R \\<Longrightarrow> field R\"\n  apply (unfold_locales)\n  apply (insert cring_axioms, auto)\n  apply (rule trans)\n  apply (subgoal_tac \"a = (a \\<otimes> b) \\<otimes> inv b\")\n  apply assumption\n  apply (subst m_assoc)\n  apply auto\n  apply (unfold Units_def)\n  apply auto\n  done\n\nlemma (in monoid) inv_char: \"x : carrier G \\<Longrightarrow> y : carrier G \\<Longrightarrow>\n    x \\<otimes> y = \\<one> \\<Longrightarrow> y \\<otimes> x = \\<one> \\<Longrightarrow> inv x = y\"\n  apply (subgoal_tac \"x : Units G\")\n  apply (subgoal_tac \"y = inv x \\<otimes> \\<one>\")\n  apply simp\n  apply (erule subst)\n  apply (subst m_assoc [symmetric])\n  apply auto\n  apply (unfold Units_def)\n  apply auto\n  done\n\nlemma (in comm_monoid) comm_inv_char: \"x : carrier G \\<Longrightarrow> y : carrier G \\<Longrightarrow>\n  x \\<otimes> y = \\<one> \\<Longrightarrow> inv x = y\"\n  apply (rule inv_char)\n  apply auto\n  apply (subst m_comm, auto)\n  done\n\nlemma (in ring) inv_neg_one [simp]: \"inv (\\<ominus> \\<one>) = \\<ominus> \\<one>\"\n  apply (rule inv_char)\n  apply (auto simp add: l_minus r_minus)\n  done\n\nlemma (in monoid) inv_eq_imp_eq: \"x : Units G \\<Longrightarrow> y : Units G \\<Longrightarrow>\n    inv x = inv y \\<Longrightarrow> x = y\"\n  apply (subgoal_tac \"inv(inv x) = inv(inv y)\")\n  apply (subst (asm) Units_inv_inv)+\n  apply auto\n  done\n\nlemma (in ring) Units_minus_one_closed [intro]: \"\\<ominus> \\<one> : Units R\"\n  apply (unfold Units_def)\n  apply auto\n  apply (rule_tac x = \"\\<ominus> \\<one>\" in bexI)\n  apply auto\n  apply (simp add: l_minus r_minus)\n  done\n\nlemma (in monoid) inv_one [simp]: \"inv \\<one> = \\<one>\"\n  apply (rule inv_char)\n  apply auto\n  done\n\nlemma (in ring) inv_eq_neg_one_eq: \"x : Units R \\<Longrightarrow> (inv x = \\<ominus> \\<one>) = (x = \\<ominus> \\<one>)\"\n  apply auto\n  apply (subst Units_inv_inv [symmetric])\n  apply auto\n  done\n\nlemma (in monoid) inv_eq_one_eq: \"x : Units G \\<Longrightarrow> (inv x = \\<one>) = (x = \\<one>)\"\n  by (metis Units_inv_inv inv_one)\n\n\nsubsubsection \\<open>This goes in FiniteProduct\\<close>\n\nlemma (in comm_monoid) finprod_UN_disjoint:\n  \"finite I \\<Longrightarrow> (ALL i:I. finite (A i)) \\<longrightarrow> (ALL i:I. ALL j:I. i ~= j \\<longrightarrow>\n     (A i) Int (A j) = {}) \\<longrightarrow>\n      (ALL i:I. ALL x: (A i). g x : carrier G) \\<longrightarrow>\n        finprod G g (UNION I A) = finprod G (%i. finprod G g (A i)) I\"\n  apply (induct set: finite)\n  apply force\n  apply clarsimp\n  apply (subst finprod_Un_disjoint)\n  apply blast\n  apply (erule finite_UN_I)\n  apply blast\n  apply (fastforce)\n  apply (auto intro!: funcsetI finprod_closed)\n  done\n\nlemma (in comm_monoid) finprod_Union_disjoint:\n  \"[| finite C; (ALL A:C. finite A & (ALL x:A. f x : carrier G));\n      (ALL A:C. ALL B:C. A ~= B --> A Int B = {}) |]\n   ==> finprod G f (\\<Union>C) = finprod G (finprod G f) C\"\n  apply (frule finprod_UN_disjoint [of C id f])\n  apply auto\n  done\n\nlemma (in comm_monoid) finprod_one:\n    \"finite A \\<Longrightarrow> (\\<And>x. x:A \\<Longrightarrow> f x = \\<one>) \\<Longrightarrow> finprod G f A = \\<one>\"\n  by (induct set: finite) auto\n\n\n(* need better simplification rules for rings *)\n(* the next one holds more generally for abelian groups *)\n\nlemma (in cring) sum_zero_eq_neg: \"x : carrier R \\<Longrightarrow> y : carrier R \\<Longrightarrow> x \\<oplus> y = \\<zero> \\<Longrightarrow> x = \\<ominus> y\"\n  by (metis minus_equality)\n\nlemma (in domain) square_eq_one:\n  fixes x\n  assumes [simp]: \"x : carrier R\"\n    and \"x \\<otimes> x = \\<one>\"\n  shows \"x = \\<one> | x = \\<ominus>\\<one>\"\nproof -\n  have \"(x \\<oplus> \\<one>) \\<otimes> (x \\<oplus> \\<ominus> \\<one>) = x \\<otimes> x \\<oplus> \\<ominus> \\<one>\"\n    by (simp add: ring_simprules)\n  also from \\<open>x \\<otimes> x = \\<one>\\<close> have \"\\<dots> = \\<zero>\"\n    by (simp add: ring_simprules)\n  finally have \"(x \\<oplus> \\<one>) \\<otimes> (x \\<oplus> \\<ominus> \\<one>) = \\<zero>\" .\n  then have \"(x \\<oplus> \\<one>) = \\<zero> | (x \\<oplus> \\<ominus> \\<one>) = \\<zero>\"\n    by (intro integral, auto)\n  then show ?thesis\n    apply auto\n    apply (erule notE)\n    apply (rule sum_zero_eq_neg)\n    apply auto\n    apply (subgoal_tac \"x = \\<ominus> (\\<ominus> \\<one>)\")\n    apply (simp add: ring_simprules)\n    apply (rule sum_zero_eq_neg)\n    apply auto\n    done\nqed\n\nlemma (in Ring.domain) inv_eq_self: \"x : Units R \\<Longrightarrow> x = inv x \\<Longrightarrow> x = \\<one> \\<or> x = \\<ominus>\\<one>\"\n  by (metis Units_closed Units_l_inv square_eq_one)\n\n\ntext \\<open>\n  The following translates theorems about groups to the facts about\n  the units of a ring. (The list should be expanded as more things are\n  needed.)\n\\<close>\n\nlemma (in ring) finite_ring_finite_units [intro]: \"finite (carrier R) \\<Longrightarrow> finite (Units R)\"\n  by (rule finite_subset) auto\n\nlemma (in monoid) units_of_pow:\n  fixes n :: nat\n  shows \"x \\<in> Units G \\<Longrightarrow> x (^)\\<^bsub>units_of G\\<^esub> n = x (^)\\<^bsub>G\\<^esub> n\"\n  apply (induct n)\n  apply (auto simp add: units_group group.is_monoid\n    monoid.nat_pow_0 monoid.nat_pow_Suc units_of_one units_of_mult)\n  done\n\nlemma (in cring) units_power_order_eq_one: \"finite (Units R) \\<Longrightarrow> a : Units R\n    \\<Longrightarrow> a (^) card(Units R) = \\<one>\"\n  apply (subst units_of_carrier [symmetric])\n  apply (subst units_of_one [symmetric])\n  apply (subst units_of_pow [symmetric])\n  apply assumption\n  apply (rule comm_group.power_order_eq_one)\n  apply (rule units_comm_group)\n  apply (unfold units_of_def, auto)\n  done\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/MiscAlgebra.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8311430353105599, "lm_q2_score": 0.8615382076534742, "lm_q1q2_score": 0.716061480945128}}
{"text": "(*  Title:      HOL/Probability/Sigma_Algebra.thy\n    Author:     Stefan Richter, Markus Wenzel, TU M\u00fcnchen\n    Author:     Johannes H\u00f6lzl, TU M\u00fcnchen\n    Plus material from the Hurd/Coble measure theory development,\n    translated by Lawrence Paulson.\n*)\n\nsection {* Describing measurable sets *}\n\ntheory Sigma_Algebra\nimports\n  Complex_Main\n  \"~~/src/HOL/Library/Countable_Set\"\n  \"~~/src/HOL/Library/FuncSet\"\n  \"~~/src/HOL/Library/Indicator_Function\"\n  \"~~/src/HOL/Library/Extended_Real\"\nbegin\n\ntext {* 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\nsubsection {* Families of sets *}\n\nlocale subset_class =\n  fixes \\<Omega> :: \"'a set\" and M :: \"'a set set\"\n  assumes space_closed: \"M \\<subseteq> Pow \\<Omega>\"\n\nlemma (in subset_class) sets_into_space: \"x \\<in> M \\<Longrightarrow> x \\<subseteq> \\<Omega>\"\n  by (metis PowD contra_subsetD space_closed)\n\nsubsubsection {* Semiring of sets *}\n\ndefinition \"disjoint A \\<longleftrightarrow> (\\<forall>a\\<in>A. \\<forall>b\\<in>A. a \\<noteq> b \\<longrightarrow> a \\<inter> b = {})\"\n\nlemma disjointI:\n  \"(\\<And>a b. a \\<in> A \\<Longrightarrow> b \\<in> A \\<Longrightarrow> a \\<noteq> b \\<Longrightarrow> a \\<inter> b = {}) \\<Longrightarrow> disjoint A\"\n  unfolding disjoint_def by auto\n\nlemma disjointD:\n  \"disjoint A \\<Longrightarrow> a \\<in> A \\<Longrightarrow> b \\<in> A \\<Longrightarrow> a \\<noteq> b \\<Longrightarrow> a \\<inter> b = {}\"\n  unfolding disjoint_def by auto\n\nlemma disjoint_empty[iff]: \"disjoint {}\"\n  by (auto simp: disjoint_def)\n\nlemma disjoint_union: \n  assumes C: \"disjoint C\" and B: \"disjoint B\" and disj: \"\\<Union>C \\<inter> \\<Union>B = {}\"\n  shows \"disjoint (C \\<union> B)\"\nproof (rule disjointI)\n  fix c d assume sets: \"c \\<in> C \\<union> B\" \"d \\<in> C \\<union> B\" and \"c \\<noteq> d\"\n  show \"c \\<inter> d = {}\"\n  proof cases\n    assume \"(c \\<in> C \\<and> d \\<in> C) \\<or> (c \\<in> B \\<and> d \\<in> B)\"\n    then show ?thesis\n    proof \n      assume \"c \\<in> C \\<and> d \\<in> C\" with `c \\<noteq> d` C show \"c \\<inter> d = {}\"\n        by (auto simp: disjoint_def)\n    next\n      assume \"c \\<in> B \\<and> d \\<in> B\" with `c \\<noteq> d` B show \"c \\<inter> d = {}\"\n        by (auto simp: disjoint_def)\n    qed\n  next\n    assume \"\\<not> ((c \\<in> C \\<and> d \\<in> C) \\<or> (c \\<in> B \\<and> d \\<in> B))\"\n    with sets have \"(c \\<subseteq> \\<Union>C \\<and> d \\<subseteq> \\<Union>B) \\<or> (c \\<subseteq> \\<Union>B \\<and> d \\<subseteq> \\<Union>C)\"\n      by auto\n    with disj show \"c \\<inter> d = {}\" by auto\n  qed\nqed\n\nlemma disjoint_singleton [simp]: \"disjoint {A}\"\nby(simp add: disjoint_def)\n\nlocale semiring_of_sets = subset_class +\n  assumes empty_sets[iff]: \"{} \\<in> M\"\n  assumes Int[intro]: \"\\<And>a b. a \\<in> M \\<Longrightarrow> b \\<in> M \\<Longrightarrow> a \\<inter> b \\<in> M\"\n  assumes Diff_cover:\n    \"\\<And>a b. a \\<in> M \\<Longrightarrow> b \\<in> M \\<Longrightarrow> \\<exists>C\\<subseteq>M. finite C \\<and> disjoint C \\<and> a - b = \\<Union>C\"\n\nlemma (in semiring_of_sets) finite_INT[intro]:\n  assumes \"finite I\" \"I \\<noteq> {}\" \"\\<And>i. i \\<in> I \\<Longrightarrow> A i \\<in> M\"\n  shows \"(\\<Inter>i\\<in>I. A i) \\<in> M\"\n  using assms by (induct rule: finite_ne_induct) auto\n\nlemma (in semiring_of_sets) Int_space_eq1 [simp]: \"x \\<in> M \\<Longrightarrow> \\<Omega> \\<inter> x = x\"\n  by (metis Int_absorb1 sets_into_space)\n\nlemma (in semiring_of_sets) Int_space_eq2 [simp]: \"x \\<in> M \\<Longrightarrow> x \\<inter> \\<Omega> = x\"\n  by (metis Int_absorb2 sets_into_space)\n\nlemma (in semiring_of_sets) sets_Collect_conj:\n  assumes \"{x\\<in>\\<Omega>. P x} \\<in> M\" \"{x\\<in>\\<Omega>. Q x} \\<in> M\"\n  shows \"{x\\<in>\\<Omega>. Q x \\<and> P x} \\<in> M\"\nproof -\n  have \"{x\\<in>\\<Omega>. Q x \\<and> P x} = {x\\<in>\\<Omega>. Q x} \\<inter> {x\\<in>\\<Omega>. P x}\"\n    by auto\n  with assms show ?thesis by auto\nqed\n\nlemma (in semiring_of_sets) sets_Collect_finite_All':\n  assumes \"\\<And>i. i \\<in> S \\<Longrightarrow> {x\\<in>\\<Omega>. P i x} \\<in> M\" \"finite S\" \"S \\<noteq> {}\"\n  shows \"{x\\<in>\\<Omega>. \\<forall>i\\<in>S. P i x} \\<in> M\"\nproof -\n  have \"{x\\<in>\\<Omega>. \\<forall>i\\<in>S. P i x} = (\\<Inter>i\\<in>S. {x\\<in>\\<Omega>. P i x})\"\n    using `S \\<noteq> {}` by auto\n  with assms show ?thesis by auto\nqed\n\nlocale ring_of_sets = semiring_of_sets +\n  assumes Un [intro]: \"\\<And>a b. a \\<in> M \\<Longrightarrow> b \\<in> M \\<Longrightarrow> a \\<union> b \\<in> M\"\n\nlemma (in ring_of_sets) finite_Union [intro]:\n  \"finite X \\<Longrightarrow> X \\<subseteq> M \\<Longrightarrow> Union X \\<in> M\"\n  by (induct set: finite) (auto simp add: Un)\n\nlemma (in ring_of_sets) finite_UN[intro]:\n  assumes \"finite I\" and \"\\<And>i. i \\<in> I \\<Longrightarrow> A i \\<in> M\"\n  shows \"(\\<Union>i\\<in>I. A i) \\<in> M\"\n  using assms by induct auto\n\nlemma (in ring_of_sets) Diff [intro]:\n  assumes \"a \\<in> M\" \"b \\<in> M\" shows \"a - b \\<in> M\"\n  using Diff_cover[OF assms] by auto\n\nlemma ring_of_setsI:\n  assumes space_closed: \"M \\<subseteq> Pow \\<Omega>\"\n  assumes empty_sets[iff]: \"{} \\<in> M\"\n  assumes Un[intro]: \"\\<And>a b. a \\<in> M \\<Longrightarrow> b \\<in> M \\<Longrightarrow> a \\<union> b \\<in> M\"\n  assumes Diff[intro]: \"\\<And>a b. a \\<in> M \\<Longrightarrow> b \\<in> M \\<Longrightarrow> a - b \\<in> M\"\n  shows \"ring_of_sets \\<Omega> M\"\nproof\n  fix a b assume ab: \"a \\<in> M\" \"b \\<in> M\"\n  from ab show \"\\<exists>C\\<subseteq>M. finite C \\<and> disjoint C \\<and> a - b = \\<Union>C\"\n    by (intro exI[of _ \"{a - b}\"]) (auto simp: disjoint_def)\n  have \"a \\<inter> b = a - (a - b)\" by auto\n  also have \"\\<dots> \\<in> M\" using ab by auto\n  finally show \"a \\<inter> b \\<in> M\" .\nqed fact+\n\nlemma ring_of_sets_iff: \"ring_of_sets \\<Omega> M \\<longleftrightarrow> M \\<subseteq> Pow \\<Omega> \\<and> {} \\<in> M \\<and> (\\<forall>a\\<in>M. \\<forall>b\\<in>M. a \\<union> b \\<in> M) \\<and> (\\<forall>a\\<in>M. \\<forall>b\\<in>M. a - b \\<in> M)\"\nproof\n  assume \"ring_of_sets \\<Omega> M\"\n  then interpret ring_of_sets \\<Omega> M .\n  show \"M \\<subseteq> Pow \\<Omega> \\<and> {} \\<in> M \\<and> (\\<forall>a\\<in>M. \\<forall>b\\<in>M. a \\<union> b \\<in> M) \\<and> (\\<forall>a\\<in>M. \\<forall>b\\<in>M. a - b \\<in> M)\"\n    using space_closed by auto\nqed (auto intro!: ring_of_setsI)\n\nlemma (in ring_of_sets) insert_in_sets:\n  assumes \"{x} \\<in> M\" \"A \\<in> M\" shows \"insert x A \\<in> M\"\nproof -\n  have \"{x} \\<union> A \\<in> M\" using assms by (rule Un)\n  thus ?thesis by auto\nqed\n\nlemma (in ring_of_sets) sets_Collect_disj:\n  assumes \"{x\\<in>\\<Omega>. P x} \\<in> M\" \"{x\\<in>\\<Omega>. Q x} \\<in> M\"\n  shows \"{x\\<in>\\<Omega>. Q x \\<or> P x} \\<in> M\"\nproof -\n  have \"{x\\<in>\\<Omega>. Q x \\<or> P x} = {x\\<in>\\<Omega>. Q x} \\<union> {x\\<in>\\<Omega>. P x}\"\n    by auto\n  with assms show ?thesis by auto\nqed\n\nlemma (in ring_of_sets) sets_Collect_finite_Ex:\n  assumes \"\\<And>i. i \\<in> S \\<Longrightarrow> {x\\<in>\\<Omega>. P i x} \\<in> M\" \"finite S\"\n  shows \"{x\\<in>\\<Omega>. \\<exists>i\\<in>S. P i x} \\<in> M\"\nproof -\n  have \"{x\\<in>\\<Omega>. \\<exists>i\\<in>S. P i x} = (\\<Union>i\\<in>S. {x\\<in>\\<Omega>. P i x})\"\n    by auto\n  with assms show ?thesis by auto\nqed\n\nlocale algebra = ring_of_sets +\n  assumes top [iff]: \"\\<Omega> \\<in> M\"\n\nlemma (in algebra) compl_sets [intro]:\n  \"a \\<in> M \\<Longrightarrow> \\<Omega> - a \\<in> M\"\n  by auto\n\nlemma algebra_iff_Un:\n  \"algebra \\<Omega> M \\<longleftrightarrow>\n    M \\<subseteq> Pow \\<Omega> \\<and>\n    {} \\<in> M \\<and>\n    (\\<forall>a \\<in> M. \\<Omega> - a \\<in> M) \\<and>\n    (\\<forall>a \\<in> M. \\<forall> b \\<in> M. a \\<union> b \\<in> M)\" (is \"_ \\<longleftrightarrow> ?Un\")\nproof\n  assume \"algebra \\<Omega> M\"\n  then interpret algebra \\<Omega> M .\n  show ?Un using sets_into_space by auto\nnext\n  assume ?Un\n  then have \"\\<Omega> \\<in> M\" by auto\n  interpret ring_of_sets \\<Omega> M\n  proof (rule ring_of_setsI)\n    show \\<Omega>: \"M \\<subseteq> Pow \\<Omega>\" \"{} \\<in> M\"\n      using `?Un` by auto\n    fix a b assume a: \"a \\<in> M\" and b: \"b \\<in> M\"\n    then show \"a \\<union> b \\<in> M\" using `?Un` by auto\n    have \"a - b = \\<Omega> - ((\\<Omega> - a) \\<union> b)\"\n      using \\<Omega> a b by auto\n    then show \"a - b \\<in> M\"\n      using a b  `?Un` by auto\n  qed\n  show \"algebra \\<Omega> M\" proof qed fact\nqed\n\nlemma algebra_iff_Int:\n     \"algebra \\<Omega> M \\<longleftrightarrow>\n       M \\<subseteq> Pow \\<Omega> & {} \\<in> M &\n       (\\<forall>a \\<in> M. \\<Omega> - a \\<in> M) &\n       (\\<forall>a \\<in> M. \\<forall> b \\<in> M. a \\<inter> b \\<in> M)\" (is \"_ \\<longleftrightarrow> ?Int\")\nproof\n  assume \"algebra \\<Omega> M\"\n  then interpret algebra \\<Omega> M .\n  show ?Int using sets_into_space by auto\nnext\n  assume ?Int\n  show \"algebra \\<Omega> M\"\n  proof (unfold algebra_iff_Un, intro conjI ballI)\n    show \\<Omega>: \"M \\<subseteq> Pow \\<Omega>\" \"{} \\<in> M\"\n      using `?Int` by auto\n    from `?Int` show \"\\<And>a. a \\<in> M \\<Longrightarrow> \\<Omega> - a \\<in> M\" by auto\n    fix a b assume M: \"a \\<in> M\" \"b \\<in> M\"\n    hence \"a \\<union> b = \\<Omega> - ((\\<Omega> - a) \\<inter> (\\<Omega> - b))\"\n      using \\<Omega> by blast\n    also have \"... \\<in> M\"\n      using M `?Int` by auto\n    finally show \"a \\<union> b \\<in> M\" .\n  qed\nqed\n\nlemma (in algebra) sets_Collect_neg:\n  assumes \"{x\\<in>\\<Omega>. P x} \\<in> M\"\n  shows \"{x\\<in>\\<Omega>. \\<not> P x} \\<in> M\"\nproof -\n  have \"{x\\<in>\\<Omega>. \\<not> P x} = \\<Omega> - {x\\<in>\\<Omega>. P x}\" by auto\n  with assms show ?thesis by auto\nqed\n\nlemma (in algebra) sets_Collect_imp:\n  \"{x\\<in>\\<Omega>. P x} \\<in> M \\<Longrightarrow> {x\\<in>\\<Omega>. Q x} \\<in> M \\<Longrightarrow> {x\\<in>\\<Omega>. Q x \\<longrightarrow> P x} \\<in> M\"\n  unfolding imp_conv_disj by (intro sets_Collect_disj sets_Collect_neg)\n\nlemma (in algebra) sets_Collect_const:\n  \"{x\\<in>\\<Omega>. P} \\<in> M\"\n  by (cases P) auto\n\nlemma algebra_single_set:\n  \"X \\<subseteq> S \\<Longrightarrow> algebra S { {}, X, S - X, S }\"\n  by (auto simp: algebra_iff_Int)\n\nsubsubsection {* Restricted algebras *}\n\nabbreviation (in algebra)\n  \"restricted_space A \\<equiv> (op \\<inter> A) ` M\"\n\nlemma (in algebra) restricted_algebra:\n  assumes \"A \\<in> M\" shows \"algebra A (restricted_space A)\"\n  using assms by (auto simp: algebra_iff_Int)\n\nsubsubsection {* Sigma Algebras *}\n\nlocale sigma_algebra = algebra +\n  assumes countable_nat_UN [intro]: \"\\<And>A. range A \\<subseteq> M \\<Longrightarrow> (\\<Union>i::nat. A i) \\<in> M\"\n\nlemma (in algebra) is_sigma_algebra:\n  assumes \"finite M\"\n  shows \"sigma_algebra \\<Omega> M\"\nproof\n  fix A :: \"nat \\<Rightarrow> 'a set\" assume \"range A \\<subseteq> M\"\n  then have \"(\\<Union>i. A i) = (\\<Union>s\\<in>M \\<inter> range A. s)\"\n    by auto\n  also have \"(\\<Union>s\\<in>M \\<inter> range A. s) \\<in> M\"\n    using `finite M` by auto\n  finally show \"(\\<Union>i. A i) \\<in> M\" .\nqed\n\nlemma countable_UN_eq:\n  fixes A :: \"'i::countable \\<Rightarrow> 'a set\"\n  shows \"(range A \\<subseteq> M \\<longrightarrow> (\\<Union>i. A i) \\<in> M) \\<longleftrightarrow>\n    (range (A \\<circ> from_nat) \\<subseteq> M \\<longrightarrow> (\\<Union>i. (A \\<circ> from_nat) i) \\<in> M)\"\nproof -\n  let ?A' = \"A \\<circ> from_nat\"\n  have *: \"(\\<Union>i. ?A' i) = (\\<Union>i. A i)\" (is \"?l = ?r\")\n  proof safe\n    fix x i assume \"x \\<in> A i\" thus \"x \\<in> ?l\"\n      by (auto intro!: exI[of _ \"to_nat i\"])\n  next\n    fix x i assume \"x \\<in> ?A' i\" thus \"x \\<in> ?r\"\n      by (auto intro!: exI[of _ \"from_nat i\"])\n  qed\n  have **: \"range ?A' = range A\"\n    using surj_from_nat\n    by (auto simp: image_comp [symmetric] intro!: imageI)\n  show ?thesis unfolding * ** ..\nqed\n\nlemma (in sigma_algebra) countable_Union [intro]:\n  assumes \"countable X\" \"X \\<subseteq> M\" shows \"Union X \\<in> M\"\nproof cases\n  assume \"X \\<noteq> {}\"\n  hence \"\\<Union>X = (\\<Union>n. from_nat_into X n)\"\n    using assms by (auto intro: from_nat_into) (metis from_nat_into_surj)\n  also have \"\\<dots> \\<in> M\" using assms\n    by (auto intro!: countable_nat_UN) (metis `X \\<noteq> {}` from_nat_into set_mp)\n  finally show ?thesis .\nqed simp\n\nlemma (in sigma_algebra) countable_UN[intro]:\n  fixes A :: \"'i::countable \\<Rightarrow> 'a set\"\n  assumes \"A`X \\<subseteq> M\"\n  shows  \"(\\<Union>x\\<in>X. A x) \\<in> M\"\nproof -\n  let ?A = \"\\<lambda>i. if i \\<in> X then A i else {}\"\n  from assms have \"range ?A \\<subseteq> M\" by auto\n  with countable_nat_UN[of \"?A \\<circ> from_nat\"] countable_UN_eq[of ?A M]\n  have \"(\\<Union>x. ?A x) \\<in> M\" by auto\n  moreover have \"(\\<Union>x. ?A x) = (\\<Union>x\\<in>X. A x)\" by (auto split: split_if_asm)\n  ultimately show ?thesis by simp\nqed\n\nlemma (in sigma_algebra) countable_UN':\n  fixes A :: \"'i \\<Rightarrow> 'a set\"\n  assumes X: \"countable X\"\n  assumes A: \"A`X \\<subseteq> M\"\n  shows  \"(\\<Union>x\\<in>X. A x) \\<in> M\"\nproof -\n  have \"(\\<Union>x\\<in>X. A x) = (\\<Union>i\\<in>to_nat_on X ` X. A (from_nat_into X i))\"\n    using X by auto\n  also have \"\\<dots> \\<in> M\"\n    using A X\n    by (intro countable_UN) auto\n  finally show ?thesis .\nqed\n\nlemma (in sigma_algebra) countable_INT [intro]:\n  fixes A :: \"'i::countable \\<Rightarrow> 'a set\"\n  assumes A: \"A`X \\<subseteq> M\" \"X \\<noteq> {}\"\n  shows \"(\\<Inter>i\\<in>X. A i) \\<in> M\"\nproof -\n  from A have \"\\<forall>i\\<in>X. A i \\<in> M\" by fast\n  hence \"\\<Omega> - (\\<Union>i\\<in>X. \\<Omega> - A i) \\<in> M\" by blast\n  moreover\n  have \"(\\<Inter>i\\<in>X. A i) = \\<Omega> - (\\<Union>i\\<in>X. \\<Omega> - A i)\" using space_closed A\n    by blast\n  ultimately show ?thesis by metis\nqed\n\nlemma (in sigma_algebra) countable_INT':\n  fixes A :: \"'i \\<Rightarrow> 'a set\"\n  assumes X: \"countable X\" \"X \\<noteq> {}\"\n  assumes A: \"A`X \\<subseteq> M\"\n  shows  \"(\\<Inter>x\\<in>X. A x) \\<in> M\"\nproof -\n  have \"(\\<Inter>x\\<in>X. A x) = (\\<Inter>i\\<in>to_nat_on X ` X. A (from_nat_into X i))\"\n    using X by auto\n  also have \"\\<dots> \\<in> M\"\n    using A X\n    by (intro countable_INT) auto\n  finally show ?thesis .\nqed\n\nlemma (in sigma_algebra) countable_INT'':\n  \"UNIV \\<in> M \\<Longrightarrow> countable I \\<Longrightarrow> (\\<And>i. i \\<in> I \\<Longrightarrow> F i \\<in> M) \\<Longrightarrow> (\\<Inter>i\\<in>I. F i) \\<in> M\"\n  by (cases \"I = {}\") (auto intro: countable_INT')\n\nlemma (in sigma_algebra) countable:\n  assumes \"\\<And>a. a \\<in> A \\<Longrightarrow> {a} \\<in> M\" \"countable A\"\n  shows \"A \\<in> M\"\nproof -\n  have \"(\\<Union>a\\<in>A. {a}) \\<in> M\"\n    using assms by (intro countable_UN') auto\n  also have \"(\\<Union>a\\<in>A. {a}) = A\" by auto\n  finally show ?thesis by auto\nqed\n\nlemma ring_of_sets_Pow: \"ring_of_sets sp (Pow sp)\"\n  by (auto simp: ring_of_sets_iff)\n\nlemma algebra_Pow: \"algebra sp (Pow sp)\"\n  by (auto simp: algebra_iff_Un)\n\nlemma sigma_algebra_iff:\n  \"sigma_algebra \\<Omega> M \\<longleftrightarrow>\n    algebra \\<Omega> M \\<and> (\\<forall>A. range A \\<subseteq> M \\<longrightarrow> (\\<Union>i::nat. A i) \\<in> M)\"\n  by (simp add: sigma_algebra_def sigma_algebra_axioms_def)\n\nlemma sigma_algebra_Pow: \"sigma_algebra sp (Pow sp)\"\n  by (auto simp: sigma_algebra_iff algebra_iff_Int)\n\nlemma (in sigma_algebra) sets_Collect_countable_All:\n  assumes \"\\<And>i. {x\\<in>\\<Omega>. P i x} \\<in> M\"\n  shows \"{x\\<in>\\<Omega>. \\<forall>i::'i::countable. P i x} \\<in> M\"\nproof -\n  have \"{x\\<in>\\<Omega>. \\<forall>i::'i::countable. P i x} = (\\<Inter>i. {x\\<in>\\<Omega>. P i x})\" by auto\n  with assms show ?thesis by auto\nqed\n\nlemma (in sigma_algebra) sets_Collect_countable_Ex:\n  assumes \"\\<And>i. {x\\<in>\\<Omega>. P i x} \\<in> M\"\n  shows \"{x\\<in>\\<Omega>. \\<exists>i::'i::countable. P i x} \\<in> M\"\nproof -\n  have \"{x\\<in>\\<Omega>. \\<exists>i::'i::countable. P i x} = (\\<Union>i. {x\\<in>\\<Omega>. P i x})\" by auto\n  with assms show ?thesis by auto\nqed\n\nlemma (in sigma_algebra) sets_Collect_countable_Ex':\n  assumes \"\\<And>i. i \\<in> I \\<Longrightarrow> {x\\<in>\\<Omega>. P i x} \\<in> M\"\n  assumes \"countable I\"\n  shows \"{x\\<in>\\<Omega>. \\<exists>i\\<in>I. P i x} \\<in> M\"\nproof -\n  have \"{x\\<in>\\<Omega>. \\<exists>i\\<in>I. P i x} = (\\<Union>i\\<in>I. {x\\<in>\\<Omega>. P i x})\" by auto\n  with assms show ?thesis \n    by (auto intro!: countable_UN')\nqed\n\nlemma (in sigma_algebra) sets_Collect_countable_All':\n  assumes \"\\<And>i. i \\<in> I \\<Longrightarrow> {x\\<in>\\<Omega>. P i x} \\<in> M\"\n  assumes \"countable I\"\n  shows \"{x\\<in>\\<Omega>. \\<forall>i\\<in>I. P i x} \\<in> M\"\nproof -\n  have \"{x\\<in>\\<Omega>. \\<forall>i\\<in>I. P i x} = (\\<Inter>i\\<in>I. {x\\<in>\\<Omega>. P i x}) \\<inter> \\<Omega>\" by auto\n  with assms show ?thesis \n    by (cases \"I = {}\") (auto intro!: countable_INT')\nqed\n\nlemma (in sigma_algebra) sets_Collect_countable_Ex1':\n  assumes \"\\<And>i. i \\<in> I \\<Longrightarrow> {x\\<in>\\<Omega>. P i x} \\<in> M\"\n  assumes \"countable I\"\n  shows \"{x\\<in>\\<Omega>. \\<exists>!i\\<in>I. P i x} \\<in> M\"\nproof -\n  have \"{x\\<in>\\<Omega>. \\<exists>!i\\<in>I. P i x} = {x\\<in>\\<Omega>. \\<exists>i\\<in>I. P i x \\<and> (\\<forall>j\\<in>I. P j x \\<longrightarrow> i = j)}\"\n    by auto\n  with assms show ?thesis \n    by (auto intro!: sets_Collect_countable_All' sets_Collect_countable_Ex' sets_Collect_conj sets_Collect_imp sets_Collect_const)\nqed\n\nlemmas (in sigma_algebra) sets_Collect =\n  sets_Collect_imp sets_Collect_disj sets_Collect_conj sets_Collect_neg sets_Collect_const\n  sets_Collect_countable_All sets_Collect_countable_Ex sets_Collect_countable_All\n\nlemma (in sigma_algebra) sets_Collect_countable_Ball:\n  assumes \"\\<And>i. {x\\<in>\\<Omega>. P i x} \\<in> M\"\n  shows \"{x\\<in>\\<Omega>. \\<forall>i::'i::countable\\<in>X. P i x} \\<in> M\"\n  unfolding Ball_def by (intro sets_Collect assms)\n\nlemma (in sigma_algebra) sets_Collect_countable_Bex:\n  assumes \"\\<And>i. {x\\<in>\\<Omega>. P i x} \\<in> M\"\n  shows \"{x\\<in>\\<Omega>. \\<exists>i::'i::countable\\<in>X. P i x} \\<in> M\"\n  unfolding Bex_def by (intro sets_Collect assms)\n\nlemma sigma_algebra_single_set:\n  assumes \"X \\<subseteq> S\"\n  shows \"sigma_algebra S { {}, X, S - X, S }\"\n  using algebra.is_sigma_algebra[OF algebra_single_set[OF `X \\<subseteq> S`]] by simp\n\nsubsubsection {* Binary Unions *}\n\ndefinition binary :: \"'a \\<Rightarrow> 'a \\<Rightarrow> nat \\<Rightarrow> 'a\"\n  where \"binary a b =  (\\<lambda>x. b)(0 := a)\"\n\nlemma range_binary_eq: \"range(binary a b) = {a,b}\"\n  by (auto simp add: binary_def)\n\nlemma Un_range_binary: \"a \\<union> b = (\\<Union>i::nat. binary a b i)\"\n  by (simp add: SUP_def range_binary_eq)\n\nlemma Int_range_binary: \"a \\<inter> b = (\\<Inter>i::nat. binary a b i)\"\n  by (simp add: INF_def range_binary_eq)\n\nlemma sigma_algebra_iff2:\n     \"sigma_algebra \\<Omega> M \\<longleftrightarrow>\n       M \\<subseteq> Pow \\<Omega> \\<and>\n       {} \\<in> M \\<and> (\\<forall>s \\<in> M. \\<Omega> - s \\<in> M) \\<and>\n       (\\<forall>A. range A \\<subseteq> M \\<longrightarrow> (\\<Union>i::nat. A i) \\<in> M)\"\n  by (auto simp add: range_binary_eq sigma_algebra_def sigma_algebra_axioms_def\n         algebra_iff_Un Un_range_binary)\n\nsubsubsection {* Initial Sigma Algebra *}\n\ntext {*Sigma algebras can naturally be created as the closure of any set of\n  M with regard to the properties just postulated.  *}\n\ninductive_set sigma_sets :: \"'a set \\<Rightarrow> 'a set set \\<Rightarrow> 'a set set\"\n  for sp :: \"'a set\" and A :: \"'a set set\"\n  where\n    Basic[intro, simp]: \"a \\<in> A \\<Longrightarrow> a \\<in> sigma_sets sp A\"\n  | Empty: \"{} \\<in> sigma_sets sp A\"\n  | Compl: \"a \\<in> sigma_sets sp A \\<Longrightarrow> sp - a \\<in> sigma_sets sp A\"\n  | Union: \"(\\<And>i::nat. a i \\<in> sigma_sets sp A) \\<Longrightarrow> (\\<Union>i. a i) \\<in> sigma_sets sp A\"\n\nlemma (in sigma_algebra) sigma_sets_subset:\n  assumes a: \"a \\<subseteq> M\"\n  shows \"sigma_sets \\<Omega> a \\<subseteq> M\"\nproof\n  fix x\n  assume \"x \\<in> sigma_sets \\<Omega> a\"\n  from this show \"x \\<in> M\"\n    by (induct rule: sigma_sets.induct, auto) (metis a subsetD)\nqed\n\nlemma sigma_sets_into_sp: \"A \\<subseteq> Pow sp \\<Longrightarrow> x \\<in> sigma_sets sp A \\<Longrightarrow> x \\<subseteq> sp\"\n  by (erule sigma_sets.induct, auto)\n\nlemma sigma_algebra_sigma_sets:\n     \"a \\<subseteq> Pow \\<Omega> \\<Longrightarrow> sigma_algebra \\<Omega> (sigma_sets \\<Omega> a)\"\n  by (auto simp add: sigma_algebra_iff2 dest: sigma_sets_into_sp\n           intro!: sigma_sets.Union sigma_sets.Empty sigma_sets.Compl)\n\nlemma sigma_sets_least_sigma_algebra:\n  assumes \"A \\<subseteq> Pow S\"\n  shows \"sigma_sets S A = \\<Inter>{B. A \\<subseteq> B \\<and> sigma_algebra S B}\"\nproof safe\n  fix B X assume \"A \\<subseteq> B\" and sa: \"sigma_algebra S B\"\n    and X: \"X \\<in> sigma_sets S A\"\n  from sigma_algebra.sigma_sets_subset[OF sa, simplified, OF `A \\<subseteq> B`] X\n  show \"X \\<in> B\" by auto\nnext\n  fix X assume \"X \\<in> \\<Inter>{B. A \\<subseteq> B \\<and> sigma_algebra S B}\"\n  then have [intro!]: \"\\<And>B. A \\<subseteq> B \\<Longrightarrow> sigma_algebra S B \\<Longrightarrow> X \\<in> B\"\n     by simp\n  have \"A \\<subseteq> sigma_sets S A\" using assms by auto\n  moreover have \"sigma_algebra S (sigma_sets S A)\"\n    using assms by (intro sigma_algebra_sigma_sets[of A]) auto\n  ultimately show \"X \\<in> sigma_sets S A\" by auto\nqed\n\nlemma sigma_sets_top: \"sp \\<in> sigma_sets sp A\"\n  by (metis Diff_empty sigma_sets.Compl sigma_sets.Empty)\n\nlemma sigma_sets_Un:\n  \"a \\<in> sigma_sets sp A \\<Longrightarrow> b \\<in> sigma_sets sp A \\<Longrightarrow> a \\<union> b \\<in> sigma_sets sp A\"\napply (simp add: Un_range_binary range_binary_eq)\napply (rule Union, simp add: binary_def)\ndone\n\nlemma sigma_sets_Inter:\n  assumes Asb: \"A \\<subseteq> Pow sp\"\n  shows \"(\\<And>i::nat. a i \\<in> sigma_sets sp A) \\<Longrightarrow> (\\<Inter>i. a i) \\<in> sigma_sets sp A\"\nproof -\n  assume ai: \"\\<And>i::nat. a i \\<in> sigma_sets sp A\"\n  hence \"\\<And>i::nat. sp-(a i) \\<in> sigma_sets sp A\"\n    by (rule sigma_sets.Compl)\n  hence \"(\\<Union>i. sp-(a i)) \\<in> sigma_sets sp A\"\n    by (rule sigma_sets.Union)\n  hence \"sp-(\\<Union>i. sp-(a i)) \\<in> sigma_sets sp A\"\n    by (rule sigma_sets.Compl)\n  also have \"sp-(\\<Union>i. sp-(a i)) = sp Int (\\<Inter>i. a i)\"\n    by auto\n  also have \"... = (\\<Inter>i. a i)\" using ai\n    by (blast dest: sigma_sets_into_sp [OF Asb])\n  finally show ?thesis .\nqed\n\nlemma sigma_sets_INTER:\n  assumes Asb: \"A \\<subseteq> Pow sp\"\n      and ai: \"\\<And>i::nat. i \\<in> S \\<Longrightarrow> a i \\<in> sigma_sets sp A\" and non: \"S \\<noteq> {}\"\n  shows \"(\\<Inter>i\\<in>S. a i) \\<in> sigma_sets sp A\"\nproof -\n  from ai have \"\\<And>i. (if i\\<in>S then a i else sp) \\<in> sigma_sets sp A\"\n    by (simp add: sigma_sets.intros(2-) sigma_sets_top)\n  hence \"(\\<Inter>i. (if i\\<in>S then a i else sp)) \\<in> sigma_sets sp A\"\n    by (rule sigma_sets_Inter [OF Asb])\n  also have \"(\\<Inter>i. (if i\\<in>S then a i else sp)) = (\\<Inter>i\\<in>S. a i)\"\n    by auto (metis ai non sigma_sets_into_sp subset_empty subset_iff Asb)+\n  finally show ?thesis .\nqed\n\nlemma sigma_sets_UNION: \"countable B \\<Longrightarrow> (\\<And>b. b \\<in> B \\<Longrightarrow> b \\<in> sigma_sets X A) \\<Longrightarrow> (\\<Union>B) \\<in> sigma_sets X A\"\n  using from_nat_into[of B] range_from_nat_into[of B] sigma_sets.Union[of \"from_nat_into B\" X A]\n  apply (cases \"B = {}\")\n  apply (simp add: sigma_sets.Empty)\n  apply (simp del: Union_image_eq add: Union_image_eq[symmetric])\n  done\n\nlemma (in sigma_algebra) sigma_sets_eq:\n     \"sigma_sets \\<Omega> M = M\"\nproof\n  show \"M \\<subseteq> sigma_sets \\<Omega> M\"\n    by (metis Set.subsetI sigma_sets.Basic)\n  next\n  show \"sigma_sets \\<Omega> M \\<subseteq> M\"\n    by (metis sigma_sets_subset subset_refl)\nqed\n\nlemma sigma_sets_eqI:\n  assumes A: \"\\<And>a. a \\<in> A \\<Longrightarrow> a \\<in> sigma_sets M B\"\n  assumes B: \"\\<And>b. b \\<in> B \\<Longrightarrow> b \\<in> sigma_sets M A\"\n  shows \"sigma_sets M A = sigma_sets M B\"\nproof (intro set_eqI iffI)\n  fix a assume \"a \\<in> sigma_sets M A\"\n  from this A show \"a \\<in> sigma_sets M B\"\n    by induct (auto intro!: sigma_sets.intros(2-) del: sigma_sets.Basic)\nnext\n  fix b assume \"b \\<in> sigma_sets M B\"\n  from this B show \"b \\<in> sigma_sets M A\"\n    by induct (auto intro!: sigma_sets.intros(2-) del: sigma_sets.Basic)\nqed\n\nlemma sigma_sets_subseteq: assumes \"A \\<subseteq> B\" shows \"sigma_sets X A \\<subseteq> sigma_sets X B\"\nproof\n  fix x assume \"x \\<in> sigma_sets X A\" then show \"x \\<in> sigma_sets X B\"\n    by induct (insert `A \\<subseteq> B`, auto intro: sigma_sets.intros(2-))\nqed\n\nlemma sigma_sets_mono: assumes \"A \\<subseteq> sigma_sets X B\" shows \"sigma_sets X A \\<subseteq> sigma_sets X B\"\nproof\n  fix x assume \"x \\<in> sigma_sets X A\" then show \"x \\<in> sigma_sets X B\"\n    by induct (insert `A \\<subseteq> sigma_sets X B`, auto intro: sigma_sets.intros(2-))\nqed\n\nlemma sigma_sets_mono': assumes \"A \\<subseteq> B\" shows \"sigma_sets X A \\<subseteq> sigma_sets X B\"\nproof\n  fix x assume \"x \\<in> sigma_sets X A\" then show \"x \\<in> sigma_sets X B\"\n    by induct (insert `A \\<subseteq> B`, auto intro: sigma_sets.intros(2-))\nqed\n\nlemma sigma_sets_superset_generator: \"A \\<subseteq> sigma_sets X A\"\n  by (auto intro: sigma_sets.Basic)\n\nlemma (in sigma_algebra) restriction_in_sets:\n  fixes A :: \"nat \\<Rightarrow> 'a set\"\n  assumes \"S \\<in> M\"\n  and *: \"range A \\<subseteq> (\\<lambda>A. S \\<inter> A) ` M\" (is \"_ \\<subseteq> ?r\")\n  shows \"range A \\<subseteq> M\" \"(\\<Union>i. A i) \\<in> (\\<lambda>A. S \\<inter> A) ` M\"\nproof -\n  { fix i have \"A i \\<in> ?r\" using * by auto\n    hence \"\\<exists>B. A i = B \\<inter> S \\<and> B \\<in> M\" by auto\n    hence \"A i \\<subseteq> S\" \"A i \\<in> M\" using `S \\<in> M` by auto }\n  thus \"range A \\<subseteq> M\" \"(\\<Union>i. A i) \\<in> (\\<lambda>A. S \\<inter> A) ` M\"\n    by (auto intro!: image_eqI[of _ _ \"(\\<Union>i. A i)\"])\nqed\n\nlemma (in sigma_algebra) restricted_sigma_algebra:\n  assumes \"S \\<in> M\"\n  shows \"sigma_algebra S (restricted_space S)\"\n  unfolding sigma_algebra_def sigma_algebra_axioms_def\nproof safe\n  show \"algebra S (restricted_space S)\" using restricted_algebra[OF assms] .\nnext\n  fix A :: \"nat \\<Rightarrow> 'a set\" assume \"range A \\<subseteq> restricted_space S\"\n  from restriction_in_sets[OF assms this[simplified]]\n  show \"(\\<Union>i. A i) \\<in> restricted_space S\" by simp\nqed\n\nlemma sigma_sets_Int:\n  assumes \"A \\<in> sigma_sets sp st\" \"A \\<subseteq> sp\"\n  shows \"op \\<inter> A ` sigma_sets sp st = sigma_sets A (op \\<inter> A ` st)\"\nproof (intro equalityI subsetI)\n  fix x assume \"x \\<in> op \\<inter> A ` sigma_sets sp st\"\n  then obtain y where \"y \\<in> sigma_sets sp st\" \"x = y \\<inter> A\" by auto\n  then have \"x \\<in> sigma_sets (A \\<inter> sp) (op \\<inter> A ` st)\"\n  proof (induct arbitrary: x)\n    case (Compl a)\n    then show ?case\n      by (force intro!: sigma_sets.Compl simp: Diff_Int_distrib ac_simps)\n  next\n    case (Union a)\n    then show ?case\n      by (auto intro!: sigma_sets.Union\n               simp add: UN_extend_simps simp del: UN_simps)\n  qed (auto intro!: sigma_sets.intros(2-))\n  then show \"x \\<in> sigma_sets A (op \\<inter> A ` st)\"\n    using `A \\<subseteq> sp` by (simp add: Int_absorb2)\nnext\n  fix x assume \"x \\<in> sigma_sets A (op \\<inter> A ` st)\"\n  then show \"x \\<in> op \\<inter> A ` sigma_sets sp st\"\n  proof induct\n    case (Compl a)\n    then obtain x where \"a = A \\<inter> x\" \"x \\<in> sigma_sets sp st\" by auto\n    then show ?case using `A \\<subseteq> sp`\n      by (force simp add: image_iff intro!: bexI[of _ \"sp - x\"] sigma_sets.Compl)\n  next\n    case (Union a)\n    then have \"\\<forall>i. \\<exists>x. x \\<in> sigma_sets sp st \\<and> a i = A \\<inter> x\"\n      by (auto simp: image_iff Bex_def)\n    from choice[OF this] guess f ..\n    then show ?case\n      by (auto intro!: bexI[of _ \"(\\<Union>x. f x)\"] sigma_sets.Union\n               simp add: image_iff)\n  qed (auto intro!: sigma_sets.intros(2-))\nqed\n\nlemma sigma_sets_empty_eq: \"sigma_sets A {} = {{}, A}\"\nproof (intro set_eqI iffI)\n  fix a assume \"a \\<in> sigma_sets A {}\" then show \"a \\<in> {{}, A}\"\n    by induct blast+\nqed (auto intro: sigma_sets.Empty sigma_sets_top)\n\nlemma sigma_sets_single[simp]: \"sigma_sets A {A} = {{}, A}\"\nproof (intro set_eqI iffI)\n  fix x assume \"x \\<in> sigma_sets A {A}\"\n  then show \"x \\<in> {{}, A}\"\n    by induct blast+\nnext\n  fix x assume \"x \\<in> {{}, A}\"\n  then show \"x \\<in> sigma_sets A {A}\"\n    by (auto intro: sigma_sets.Empty sigma_sets_top)\nqed\n\nlemma sigma_sets_sigma_sets_eq:\n  \"M \\<subseteq> Pow S \\<Longrightarrow> sigma_sets S (sigma_sets S M) = sigma_sets S M\"\n  by (rule sigma_algebra.sigma_sets_eq[OF sigma_algebra_sigma_sets, of M S]) auto\n\nlemma sigma_sets_singleton:\n  assumes \"X \\<subseteq> S\"\n  shows \"sigma_sets S { X } = { {}, X, S - X, S }\"\nproof -\n  interpret sigma_algebra S \"{ {}, X, S - X, S }\"\n    by (rule sigma_algebra_single_set) fact\n  have \"sigma_sets S { X } \\<subseteq> sigma_sets S { {}, X, S - X, S }\"\n    by (rule sigma_sets_subseteq) simp\n  moreover have \"\\<dots> = { {}, X, S - X, S }\"\n    using sigma_sets_eq by simp\n  moreover\n  { fix A assume \"A \\<in> { {}, X, S - X, S }\"\n    then have \"A \\<in> sigma_sets S { X }\"\n      by (auto intro: sigma_sets.intros(2-) sigma_sets_top) }\n  ultimately have \"sigma_sets S { X } = sigma_sets S { {}, X, S - X, S }\"\n    by (intro antisym) auto\n  with sigma_sets_eq show ?thesis by simp\nqed\n\nlemma restricted_sigma:\n  assumes S: \"S \\<in> sigma_sets \\<Omega> M\" and M: \"M \\<subseteq> Pow \\<Omega>\"\n  shows \"algebra.restricted_space (sigma_sets \\<Omega> M) S =\n    sigma_sets S (algebra.restricted_space M S)\"\nproof -\n  from S sigma_sets_into_sp[OF M]\n  have \"S \\<in> sigma_sets \\<Omega> M\" \"S \\<subseteq> \\<Omega>\" by auto\n  from sigma_sets_Int[OF this]\n  show ?thesis by simp\nqed\n\nlemma sigma_sets_vimage_commute:\n  assumes X: \"X \\<in> \\<Omega> \\<rightarrow> \\<Omega>'\"\n  shows \"{X -` A \\<inter> \\<Omega> |A. A \\<in> sigma_sets \\<Omega>' M'}\n       = sigma_sets \\<Omega> {X -` A \\<inter> \\<Omega> |A. A \\<in> M'}\" (is \"?L = ?R\")\nproof\n  show \"?L \\<subseteq> ?R\"\n  proof clarify\n    fix A assume \"A \\<in> sigma_sets \\<Omega>' M'\"\n    then show \"X -` A \\<inter> \\<Omega> \\<in> ?R\"\n    proof induct\n      case Empty then show ?case\n        by (auto intro!: sigma_sets.Empty)\n    next\n      case (Compl B)\n      have [simp]: \"X -` (\\<Omega>' - B) \\<inter> \\<Omega> = \\<Omega> - (X -` B \\<inter> \\<Omega>)\"\n        by (auto simp add: funcset_mem [OF X])\n      with Compl show ?case\n        by (auto intro!: sigma_sets.Compl)\n    next\n      case (Union F)\n      then show ?case\n        by (auto simp add: vimage_UN UN_extend_simps(4) simp del: UN_simps\n                 intro!: sigma_sets.Union)\n    qed auto\n  qed\n  show \"?R \\<subseteq> ?L\"\n  proof clarify\n    fix A assume \"A \\<in> ?R\"\n    then show \"\\<exists>B. A = X -` B \\<inter> \\<Omega> \\<and> B \\<in> sigma_sets \\<Omega>' M'\"\n    proof induct\n      case (Basic B) then show ?case by auto\n    next\n      case Empty then show ?case\n        by (auto intro!: sigma_sets.Empty exI[of _ \"{}\"])\n    next\n      case (Compl B)\n      then obtain A where A: \"B = X -` A \\<inter> \\<Omega>\" \"A \\<in> sigma_sets \\<Omega>' M'\" by auto\n      then have [simp]: \"\\<Omega> - B = X -` (\\<Omega>' - A) \\<inter> \\<Omega>\"\n        by (auto simp add: funcset_mem [OF X])\n      with A(2) show ?case\n        by (auto intro: sigma_sets.Compl)\n    next\n      case (Union F)\n      then have \"\\<forall>i. \\<exists>B. F i = X -` B \\<inter> \\<Omega> \\<and> B \\<in> sigma_sets \\<Omega>' M'\" by auto\n      from choice[OF this] guess A .. note A = this\n      with A show ?case\n        by (auto simp: vimage_UN[symmetric] intro: sigma_sets.Union)\n    qed\n  qed\nqed\n\nsubsubsection \"Disjoint families\"\n\ndefinition\n  disjoint_family_on  where\n  \"disjoint_family_on A S \\<longleftrightarrow> (\\<forall>m\\<in>S. \\<forall>n\\<in>S. m \\<noteq> n \\<longrightarrow> A m \\<inter> A n = {})\"\n\nabbreviation\n  \"disjoint_family A \\<equiv> disjoint_family_on A UNIV\"\n\nlemma range_subsetD: \"range f \\<subseteq> B \\<Longrightarrow> f i \\<in> B\"\n  by blast\n\nlemma disjoint_family_onD: \"disjoint_family_on A I \\<Longrightarrow> i \\<in> I \\<Longrightarrow> j \\<in> I \\<Longrightarrow> i \\<noteq> j \\<Longrightarrow> A i \\<inter> A j = {}\"\n  by (auto simp: disjoint_family_on_def)\n\nlemma Int_Diff_disjoint: \"A \\<inter> B \\<inter> (A - B) = {}\"\n  by blast\n\nlemma Int_Diff_Un: \"A \\<inter> B \\<union> (A - B) = A\"\n  by blast\n\nlemma disjoint_family_subset:\n     \"disjoint_family A \\<Longrightarrow> (!!x. B x \\<subseteq> A x) \\<Longrightarrow> disjoint_family B\"\n  by (force simp add: disjoint_family_on_def)\n\nlemma disjoint_family_on_bisimulation:\n  assumes \"disjoint_family_on f S\"\n  and \"\\<And>n m. n \\<in> S \\<Longrightarrow> m \\<in> S \\<Longrightarrow> n \\<noteq> m \\<Longrightarrow> f n \\<inter> f m = {} \\<Longrightarrow> g n \\<inter> g m = {}\"\n  shows \"disjoint_family_on g S\"\n  using assms unfolding disjoint_family_on_def by auto\n\nlemma disjoint_family_on_mono:\n  \"A \\<subseteq> B \\<Longrightarrow> disjoint_family_on f B \\<Longrightarrow> disjoint_family_on f A\"\n  unfolding disjoint_family_on_def by auto\n\nlemma disjoint_family_Suc:\n  assumes Suc: \"!!n. A n \\<subseteq> A (Suc n)\"\n  shows \"disjoint_family (\\<lambda>i. A (Suc i) - A i)\"\nproof -\n  {\n    fix m\n    have \"!!n. A n \\<subseteq> A (m+n)\"\n    proof (induct m)\n      case 0 show ?case by simp\n    next\n      case (Suc m) thus ?case\n        by (metis Suc_eq_plus1 assms add.commute add.left_commute subset_trans)\n    qed\n  }\n  hence \"!!m n. m < n \\<Longrightarrow> A m \\<subseteq> A n\"\n    by (metis add.commute le_add_diff_inverse nat_less_le)\n  thus ?thesis\n    by (auto simp add: disjoint_family_on_def)\n      (metis insert_absorb insert_subset le_SucE le_antisym not_leE)\nqed\n\nlemma setsum_indicator_disjoint_family:\n  fixes f :: \"'d \\<Rightarrow> 'e::semiring_1\"\n  assumes d: \"disjoint_family_on A P\" and \"x \\<in> A j\" and \"finite P\" and \"j \\<in> P\"\n  shows \"(\\<Sum>i\\<in>P. f i * indicator (A i) x) = f j\"\nproof -\n  have \"P \\<inter> {i. x \\<in> A i} = {j}\"\n    using d `x \\<in> A j` `j \\<in> P` unfolding disjoint_family_on_def\n    by auto\n  thus ?thesis\n    unfolding indicator_def\n    by (simp add: if_distrib setsum.If_cases[OF `finite P`])\nqed\n\ndefinition disjointed :: \"(nat \\<Rightarrow> 'a set) \\<Rightarrow> nat \\<Rightarrow> 'a set \"\n  where \"disjointed A n = A n - (\\<Union>i\\<in>{0..<n}. A i)\"\n\nlemma finite_UN_disjointed_eq: \"(\\<Union>i\\<in>{0..<n}. disjointed A i) = (\\<Union>i\\<in>{0..<n}. A i)\"\nproof (induct n)\n  case 0 show ?case by simp\nnext\n  case (Suc n)\n  thus ?case by (simp add: atLeastLessThanSuc disjointed_def)\nqed\n\nlemma UN_disjointed_eq: \"(\\<Union>i. disjointed A i) = (\\<Union>i. A i)\"\n  apply (rule UN_finite2_eq [where k=0])\n  apply (simp add: finite_UN_disjointed_eq)\n  done\n\nlemma less_disjoint_disjointed: \"m<n \\<Longrightarrow> disjointed A m \\<inter> disjointed A n = {}\"\n  by (auto simp add: disjointed_def)\n\nlemma disjoint_family_disjointed: \"disjoint_family (disjointed A)\"\n  by (simp add: disjoint_family_on_def)\n     (metis neq_iff Int_commute less_disjoint_disjointed)\n\nlemma disjointed_subset: \"disjointed A n \\<subseteq> A n\"\n  by (auto simp add: disjointed_def)\n\nlemma (in ring_of_sets) UNION_in_sets:\n  fixes A:: \"nat \\<Rightarrow> 'a set\"\n  assumes A: \"range A \\<subseteq> M\"\n  shows  \"(\\<Union>i\\<in>{0..<n}. A i) \\<in> M\"\nproof (induct n)\n  case 0 show ?case by simp\nnext\n  case (Suc n)\n  thus ?case\n    by (simp add: atLeastLessThanSuc) (metis A Un UNIV_I image_subset_iff)\nqed\n\nlemma (in ring_of_sets) range_disjointed_sets:\n  assumes A: \"range A \\<subseteq> M\"\n  shows  \"range (disjointed A) \\<subseteq> M\"\nproof (auto simp add: disjointed_def)\n  fix n\n  show \"A n - (\\<Union>i\\<in>{0..<n}. A i) \\<in> M\" using UNION_in_sets\n    by (metis A Diff UNIV_I image_subset_iff)\nqed\n\nlemma (in algebra) range_disjointed_sets':\n  \"range A \\<subseteq> M \\<Longrightarrow> range (disjointed A) \\<subseteq> M\"\n  using range_disjointed_sets .\n\nlemma disjointed_0[simp]: \"disjointed A 0 = A 0\"\n  by (simp add: disjointed_def)\n\nlemma incseq_Un:\n  \"incseq A \\<Longrightarrow> (\\<Union>i\\<le>n. A i) = A n\"\n  unfolding incseq_def by auto\n\nlemma disjointed_incseq:\n  \"incseq A \\<Longrightarrow> disjointed A (Suc n) = A (Suc n) - A n\"\n  using incseq_Un[of A]\n  by (simp add: disjointed_def atLeastLessThanSuc_atLeastAtMost atLeast0AtMost)\n\nlemma sigma_algebra_disjoint_iff:\n  \"sigma_algebra \\<Omega> M \\<longleftrightarrow> algebra \\<Omega> M \\<and>\n    (\\<forall>A. range A \\<subseteq> M \\<longrightarrow> disjoint_family A \\<longrightarrow> (\\<Union>i::nat. A i) \\<in> M)\"\nproof (auto simp add: sigma_algebra_iff)\n  fix A :: \"nat \\<Rightarrow> 'a set\"\n  assume M: \"algebra \\<Omega> M\"\n     and A: \"range A \\<subseteq> M\"\n     and UnA: \"\\<forall>A. range A \\<subseteq> M \\<longrightarrow> disjoint_family A \\<longrightarrow> (\\<Union>i::nat. A i) \\<in> M\"\n  hence \"range (disjointed A) \\<subseteq> M \\<longrightarrow>\n         disjoint_family (disjointed A) \\<longrightarrow>\n         (\\<Union>i. disjointed A i) \\<in> M\" by blast\n  hence \"(\\<Union>i. disjointed A i) \\<in> M\"\n    by (simp add: algebra.range_disjointed_sets'[of \\<Omega>] M A disjoint_family_disjointed)\n  thus \"(\\<Union>i::nat. A i) \\<in> M\" by (simp add: UN_disjointed_eq)\nqed\n\nlemma disjoint_family_on_disjoint_image:\n  \"disjoint_family_on A I \\<Longrightarrow> disjoint (A ` I)\"\n  unfolding disjoint_family_on_def disjoint_def by force\n\nlemma disjoint_image_disjoint_family_on:\n  assumes d: \"disjoint (A ` I)\" and i: \"inj_on A I\"\n  shows \"disjoint_family_on A I\"\n  unfolding disjoint_family_on_def\nproof (intro ballI impI)\n  fix n m assume nm: \"m \\<in> I\" \"n \\<in> I\" and \"n \\<noteq> m\"\n  with i[THEN inj_onD, of n m] show \"A n \\<inter> A m = {}\"\n    by (intro disjointD[OF d]) auto\nqed\n\nsubsubsection {* Ring generated by a semiring *}\n\ndefinition (in semiring_of_sets)\n  \"generated_ring = { \\<Union>C | C. C \\<subseteq> M \\<and> finite C \\<and> disjoint C }\"\n\nlemma (in semiring_of_sets) generated_ringE[elim?]:\n  assumes \"a \\<in> generated_ring\"\n  obtains C where \"finite C\" \"disjoint C\" \"C \\<subseteq> M\" \"a = \\<Union>C\"\n  using assms unfolding generated_ring_def by auto\n\nlemma (in semiring_of_sets) generated_ringI[intro?]:\n  assumes \"finite C\" \"disjoint C\" \"C \\<subseteq> M\" \"a = \\<Union>C\"\n  shows \"a \\<in> generated_ring\"\n  using assms unfolding generated_ring_def by auto\n\nlemma (in semiring_of_sets) generated_ringI_Basic:\n  \"A \\<in> M \\<Longrightarrow> A \\<in> generated_ring\"\n  by (rule generated_ringI[of \"{A}\"]) (auto simp: disjoint_def)\n\nlemma (in semiring_of_sets) generated_ring_disjoint_Un[intro]:\n  assumes a: \"a \\<in> generated_ring\" and b: \"b \\<in> generated_ring\"\n  and \"a \\<inter> b = {}\"\n  shows \"a \\<union> b \\<in> generated_ring\"\nproof -\n  from a guess Ca .. note Ca = this\n  from b guess Cb .. note Cb = this\n  show ?thesis\n  proof\n    show \"disjoint (Ca \\<union> Cb)\"\n      using `a \\<inter> b = {}` Ca Cb by (auto intro!: disjoint_union)\n  qed (insert Ca Cb, auto)\nqed\n\nlemma (in semiring_of_sets) generated_ring_empty: \"{} \\<in> generated_ring\"\n  by (auto simp: generated_ring_def disjoint_def)\n\nlemma (in semiring_of_sets) generated_ring_disjoint_Union:\n  assumes \"finite A\" shows \"A \\<subseteq> generated_ring \\<Longrightarrow> disjoint A \\<Longrightarrow> \\<Union>A \\<in> generated_ring\"\n  using assms by (induct A) (auto simp: disjoint_def intro!: generated_ring_disjoint_Un generated_ring_empty)\n\nlemma (in semiring_of_sets) generated_ring_disjoint_UNION:\n  \"finite I \\<Longrightarrow> disjoint (A ` I) \\<Longrightarrow> (\\<And>i. i \\<in> I \\<Longrightarrow> A i \\<in> generated_ring) \\<Longrightarrow> UNION I A \\<in> generated_ring\"\n  unfolding SUP_def by (intro generated_ring_disjoint_Union) auto\n\nlemma (in semiring_of_sets) generated_ring_Int:\n  assumes a: \"a \\<in> generated_ring\" and b: \"b \\<in> generated_ring\"\n  shows \"a \\<inter> b \\<in> generated_ring\"\nproof -\n  from a guess Ca .. note Ca = this\n  from b guess Cb .. note Cb = this\n  def C \\<equiv> \"(\\<lambda>(a,b). a \\<inter> b)` (Ca\\<times>Cb)\"\n  show ?thesis\n  proof\n    show \"disjoint C\"\n    proof (simp add: disjoint_def C_def, intro ballI impI)\n      fix a1 b1 a2 b2 assume sets: \"a1 \\<in> Ca\" \"b1 \\<in> Cb\" \"a2 \\<in> Ca\" \"b2 \\<in> Cb\"\n      assume \"a1 \\<inter> b1 \\<noteq> a2 \\<inter> b2\"\n      then have \"a1 \\<noteq> a2 \\<or> b1 \\<noteq> b2\" by auto\n      then show \"(a1 \\<inter> b1) \\<inter> (a2 \\<inter> b2) = {}\"\n      proof\n        assume \"a1 \\<noteq> a2\"\n        with sets Ca have \"a1 \\<inter> a2 = {}\"\n          by (auto simp: disjoint_def)\n        then show ?thesis by auto\n      next\n        assume \"b1 \\<noteq> b2\"\n        with sets Cb have \"b1 \\<inter> b2 = {}\"\n          by (auto simp: disjoint_def)\n        then show ?thesis by auto\n      qed\n    qed\n  qed (insert Ca Cb, auto simp: C_def)\nqed\n\nlemma (in semiring_of_sets) generated_ring_Inter:\n  assumes \"finite A\" \"A \\<noteq> {}\" shows \"A \\<subseteq> generated_ring \\<Longrightarrow> \\<Inter>A \\<in> generated_ring\"\n  using assms by (induct A rule: finite_ne_induct) (auto intro: generated_ring_Int)\n\nlemma (in semiring_of_sets) generated_ring_INTER:\n  \"finite I \\<Longrightarrow> I \\<noteq> {} \\<Longrightarrow> (\\<And>i. i \\<in> I \\<Longrightarrow> A i \\<in> generated_ring) \\<Longrightarrow> INTER I A \\<in> generated_ring\"\n  unfolding INF_def by (intro generated_ring_Inter) auto\n\nlemma (in semiring_of_sets) generating_ring:\n  \"ring_of_sets \\<Omega> generated_ring\"\nproof (rule ring_of_setsI)\n  let ?R = generated_ring\n  show \"?R \\<subseteq> Pow \\<Omega>\"\n    using sets_into_space by (auto simp: generated_ring_def generated_ring_empty)\n  show \"{} \\<in> ?R\" by (rule generated_ring_empty)\n\n  { fix a assume a: \"a \\<in> ?R\" then guess Ca .. note Ca = this\n    fix b assume b: \"b \\<in> ?R\" then guess Cb .. note Cb = this\n  \n    show \"a - b \\<in> ?R\"\n    proof cases\n      assume \"Cb = {}\" with Cb `a \\<in> ?R` show ?thesis\n        by simp\n    next\n      assume \"Cb \\<noteq> {}\"\n      with Ca Cb have \"a - b = (\\<Union>a'\\<in>Ca. \\<Inter>b'\\<in>Cb. a' - b')\" by auto\n      also have \"\\<dots> \\<in> ?R\"\n      proof (intro generated_ring_INTER generated_ring_disjoint_UNION)\n        fix a b assume \"a \\<in> Ca\" \"b \\<in> Cb\"\n        with Ca Cb Diff_cover[of a b] show \"a - b \\<in> ?R\"\n          by (auto simp add: generated_ring_def)\n      next\n        show \"disjoint ((\\<lambda>a'. \\<Inter>b'\\<in>Cb. a' - b')`Ca)\"\n          using Ca by (auto simp add: disjoint_def `Cb \\<noteq> {}`)\n      next\n        show \"finite Ca\" \"finite Cb\" \"Cb \\<noteq> {}\" by fact+\n      qed\n      finally show \"a - b \\<in> ?R\" .\n    qed }\n  note Diff = this\n\n  fix a b assume sets: \"a \\<in> ?R\" \"b \\<in> ?R\"\n  have \"a \\<union> b = (a - b) \\<union> (a \\<inter> b) \\<union> (b - a)\" by auto\n  also have \"\\<dots> \\<in> ?R\"\n    by (intro sets generated_ring_disjoint_Un generated_ring_Int Diff) auto\n  finally show \"a \\<union> b \\<in> ?R\" .\nqed\n\nlemma (in semiring_of_sets) sigma_sets_generated_ring_eq: \"sigma_sets \\<Omega> generated_ring = sigma_sets \\<Omega> M\"\nproof\n  interpret M: sigma_algebra \\<Omega> \"sigma_sets \\<Omega> M\"\n    using space_closed by (rule sigma_algebra_sigma_sets)\n  show \"sigma_sets \\<Omega> generated_ring \\<subseteq> sigma_sets \\<Omega> M\"\n    by (blast intro!: sigma_sets_mono elim: generated_ringE)\nqed (auto intro!: generated_ringI_Basic sigma_sets_mono)\n\nsubsubsection {* A Two-Element Series *}\n\ndefinition binaryset :: \"'a set \\<Rightarrow> 'a set \\<Rightarrow> nat \\<Rightarrow> 'a set \"\n  where \"binaryset A B = (\\<lambda>x. {})(0 := A, Suc 0 := B)\"\n\nlemma range_binaryset_eq: \"range(binaryset A B) = {A,B,{}}\"\n  apply (simp add: binaryset_def)\n  apply (rule set_eqI)\n  apply (auto simp add: image_iff)\n  done\n\nlemma UN_binaryset_eq: \"(\\<Union>i. binaryset A B i) = A \\<union> B\"\n  by (simp add: SUP_def range_binaryset_eq)\n\nsubsubsection {* Closed CDI *}\n\ndefinition closed_cdi where\n  \"closed_cdi \\<Omega> M \\<longleftrightarrow>\n   M \\<subseteq> Pow \\<Omega> &\n   (\\<forall>s \\<in> M. \\<Omega> - s \\<in> M) &\n   (\\<forall>A. (range A \\<subseteq> M) & (A 0 = {}) & (\\<forall>n. A n \\<subseteq> A (Suc n)) \\<longrightarrow>\n        (\\<Union>i. A i) \\<in> M) &\n   (\\<forall>A. (range A \\<subseteq> M) & disjoint_family A \\<longrightarrow> (\\<Union>i::nat. A i) \\<in> M)\"\n\ninductive_set\n  smallest_ccdi_sets :: \"'a set \\<Rightarrow> 'a set set \\<Rightarrow> 'a set set\"\n  for \\<Omega> M\n  where\n    Basic [intro]:\n      \"a \\<in> M \\<Longrightarrow> a \\<in> smallest_ccdi_sets \\<Omega> M\"\n  | Compl [intro]:\n      \"a \\<in> smallest_ccdi_sets \\<Omega> M \\<Longrightarrow> \\<Omega> - a \\<in> smallest_ccdi_sets \\<Omega> M\"\n  | Inc:\n      \"range A \\<in> Pow(smallest_ccdi_sets \\<Omega> M) \\<Longrightarrow> A 0 = {} \\<Longrightarrow> (\\<And>n. A n \\<subseteq> A (Suc n))\n       \\<Longrightarrow> (\\<Union>i. A i) \\<in> smallest_ccdi_sets \\<Omega> M\"\n  | Disj:\n      \"range A \\<in> Pow(smallest_ccdi_sets \\<Omega> M) \\<Longrightarrow> disjoint_family A\n       \\<Longrightarrow> (\\<Union>i::nat. A i) \\<in> smallest_ccdi_sets \\<Omega> M\"\n\nlemma (in subset_class) smallest_closed_cdi1: \"M \\<subseteq> smallest_ccdi_sets \\<Omega> M\"\n  by auto\n\nlemma (in subset_class) smallest_ccdi_sets: \"smallest_ccdi_sets \\<Omega> M \\<subseteq> Pow \\<Omega>\"\n  apply (rule subsetI)\n  apply (erule smallest_ccdi_sets.induct)\n  apply (auto intro: range_subsetD dest: sets_into_space)\n  done\n\nlemma (in subset_class) smallest_closed_cdi2: \"closed_cdi \\<Omega> (smallest_ccdi_sets \\<Omega> M)\"\n  apply (auto simp add: closed_cdi_def smallest_ccdi_sets)\n  apply (blast intro: smallest_ccdi_sets.Inc smallest_ccdi_sets.Disj) +\n  done\n\nlemma closed_cdi_subset: \"closed_cdi \\<Omega> M \\<Longrightarrow> M \\<subseteq> Pow \\<Omega>\"\n  by (simp add: closed_cdi_def)\n\nlemma closed_cdi_Compl: \"closed_cdi \\<Omega> M \\<Longrightarrow> s \\<in> M \\<Longrightarrow> \\<Omega> - s \\<in> M\"\n  by (simp add: closed_cdi_def)\n\nlemma closed_cdi_Inc:\n  \"closed_cdi \\<Omega> M \\<Longrightarrow> range A \\<subseteq> M \\<Longrightarrow> A 0 = {} \\<Longrightarrow> (!!n. A n \\<subseteq> A (Suc n)) \\<Longrightarrow> (\\<Union>i. A i) \\<in> M\"\n  by (simp add: closed_cdi_def)\n\nlemma closed_cdi_Disj:\n  \"closed_cdi \\<Omega> M \\<Longrightarrow> range A \\<subseteq> M \\<Longrightarrow> disjoint_family A \\<Longrightarrow> (\\<Union>i::nat. A i) \\<in> M\"\n  by (simp add: closed_cdi_def)\n\nlemma closed_cdi_Un:\n  assumes cdi: \"closed_cdi \\<Omega> M\" and empty: \"{} \\<in> M\"\n      and A: \"A \\<in> M\" and B: \"B \\<in> M\"\n      and disj: \"A \\<inter> B = {}\"\n    shows \"A \\<union> B \\<in> M\"\nproof -\n  have ra: \"range (binaryset A B) \\<subseteq> M\"\n   by (simp add: range_binaryset_eq empty A B)\n have di:  \"disjoint_family (binaryset A B)\" using disj\n   by (simp add: disjoint_family_on_def binaryset_def Int_commute)\n from closed_cdi_Disj [OF cdi ra di]\n show ?thesis\n   by (simp add: UN_binaryset_eq)\nqed\n\nlemma (in algebra) smallest_ccdi_sets_Un:\n  assumes A: \"A \\<in> smallest_ccdi_sets \\<Omega> M\" and B: \"B \\<in> smallest_ccdi_sets \\<Omega> M\"\n      and disj: \"A \\<inter> B = {}\"\n    shows \"A \\<union> B \\<in> smallest_ccdi_sets \\<Omega> M\"\nproof -\n  have ra: \"range (binaryset A B) \\<in> Pow (smallest_ccdi_sets \\<Omega> M)\"\n    by (simp add: range_binaryset_eq  A B smallest_ccdi_sets.Basic)\n  have di:  \"disjoint_family (binaryset A B)\" using disj\n    by (simp add: disjoint_family_on_def binaryset_def Int_commute)\n  from Disj [OF ra di]\n  show ?thesis\n    by (simp add: UN_binaryset_eq)\nqed\n\nlemma (in algebra) smallest_ccdi_sets_Int1:\n  assumes a: \"a \\<in> M\"\n  shows \"b \\<in> smallest_ccdi_sets \\<Omega> M \\<Longrightarrow> a \\<inter> b \\<in> smallest_ccdi_sets \\<Omega> M\"\nproof (induct rule: smallest_ccdi_sets.induct)\n  case (Basic x)\n  thus ?case\n    by (metis a Int smallest_ccdi_sets.Basic)\nnext\n  case (Compl x)\n  have \"a \\<inter> (\\<Omega> - x) = \\<Omega> - ((\\<Omega> - a) \\<union> (a \\<inter> x))\"\n    by blast\n  also have \"... \\<in> smallest_ccdi_sets \\<Omega> M\"\n    by (metis smallest_ccdi_sets.Compl a Compl(2) Diff_Int2 Diff_Int_distrib2\n           Diff_disjoint Int_Diff Int_empty_right smallest_ccdi_sets_Un\n           smallest_ccdi_sets.Basic smallest_ccdi_sets.Compl)\n  finally show ?case .\nnext\n  case (Inc A)\n  have 1: \"(\\<Union>i. (\\<lambda>i. a \\<inter> A i) i) = a \\<inter> (\\<Union>i. A i)\"\n    by blast\n  have \"range (\\<lambda>i. a \\<inter> A i) \\<in> Pow(smallest_ccdi_sets \\<Omega> M)\" using Inc\n    by blast\n  moreover have \"(\\<lambda>i. a \\<inter> A i) 0 = {}\"\n    by (simp add: Inc)\n  moreover have \"!!n. (\\<lambda>i. a \\<inter> A i) n \\<subseteq> (\\<lambda>i. a \\<inter> A i) (Suc n)\" using Inc\n    by blast\n  ultimately have 2: \"(\\<Union>i. (\\<lambda>i. a \\<inter> A i) i) \\<in> smallest_ccdi_sets \\<Omega> M\"\n    by (rule smallest_ccdi_sets.Inc)\n  show ?case\n    by (metis 1 2)\nnext\n  case (Disj A)\n  have 1: \"(\\<Union>i. (\\<lambda>i. a \\<inter> A i) i) = a \\<inter> (\\<Union>i. A i)\"\n    by blast\n  have \"range (\\<lambda>i. a \\<inter> A i) \\<in> Pow(smallest_ccdi_sets \\<Omega> M)\" using Disj\n    by blast\n  moreover have \"disjoint_family (\\<lambda>i. a \\<inter> A i)\" using Disj\n    by (auto simp add: disjoint_family_on_def)\n  ultimately have 2: \"(\\<Union>i. (\\<lambda>i. a \\<inter> A i) i) \\<in> smallest_ccdi_sets \\<Omega> M\"\n    by (rule smallest_ccdi_sets.Disj)\n  show ?case\n    by (metis 1 2)\nqed\n\n\nlemma (in algebra) smallest_ccdi_sets_Int:\n  assumes b: \"b \\<in> smallest_ccdi_sets \\<Omega> M\"\n  shows \"a \\<in> smallest_ccdi_sets \\<Omega> M \\<Longrightarrow> a \\<inter> b \\<in> smallest_ccdi_sets \\<Omega> M\"\nproof (induct rule: smallest_ccdi_sets.induct)\n  case (Basic x)\n  thus ?case\n    by (metis b smallest_ccdi_sets_Int1)\nnext\n  case (Compl x)\n  have \"(\\<Omega> - x) \\<inter> b = \\<Omega> - (x \\<inter> b \\<union> (\\<Omega> - b))\"\n    by blast\n  also have \"... \\<in> smallest_ccdi_sets \\<Omega> M\"\n    by (metis Compl(2) Diff_disjoint Int_Diff Int_commute Int_empty_right b\n           smallest_ccdi_sets.Compl smallest_ccdi_sets_Un)\n  finally show ?case .\nnext\n  case (Inc A)\n  have 1: \"(\\<Union>i. (\\<lambda>i. A i \\<inter> b) i) = (\\<Union>i. A i) \\<inter> b\"\n    by blast\n  have \"range (\\<lambda>i. A i \\<inter> b) \\<in> Pow(smallest_ccdi_sets \\<Omega> M)\" using Inc\n    by blast\n  moreover have \"(\\<lambda>i. A i \\<inter> b) 0 = {}\"\n    by (simp add: Inc)\n  moreover have \"!!n. (\\<lambda>i. A i \\<inter> b) n \\<subseteq> (\\<lambda>i. A i \\<inter> b) (Suc n)\" using Inc\n    by blast\n  ultimately have 2: \"(\\<Union>i. (\\<lambda>i. A i \\<inter> b) i) \\<in> smallest_ccdi_sets \\<Omega> M\"\n    by (rule smallest_ccdi_sets.Inc)\n  show ?case\n    by (metis 1 2)\nnext\n  case (Disj A)\n  have 1: \"(\\<Union>i. (\\<lambda>i. A i \\<inter> b) i) = (\\<Union>i. A i) \\<inter> b\"\n    by blast\n  have \"range (\\<lambda>i. A i \\<inter> b) \\<in> Pow(smallest_ccdi_sets \\<Omega> M)\" using Disj\n    by blast\n  moreover have \"disjoint_family (\\<lambda>i. A i \\<inter> b)\" using Disj\n    by (auto simp add: disjoint_family_on_def)\n  ultimately have 2: \"(\\<Union>i. (\\<lambda>i. A i \\<inter> b) i) \\<in> smallest_ccdi_sets \\<Omega> M\"\n    by (rule smallest_ccdi_sets.Disj)\n  show ?case\n    by (metis 1 2)\nqed\n\nlemma (in algebra) sigma_property_disjoint_lemma:\n  assumes sbC: \"M \\<subseteq> C\"\n      and ccdi: \"closed_cdi \\<Omega> C\"\n  shows \"sigma_sets \\<Omega> M \\<subseteq> C\"\nproof -\n  have \"smallest_ccdi_sets \\<Omega> M \\<in> {B . M \\<subseteq> B \\<and> sigma_algebra \\<Omega> B}\"\n    apply (auto simp add: sigma_algebra_disjoint_iff algebra_iff_Int\n            smallest_ccdi_sets_Int)\n    apply (metis Union_Pow_eq Union_upper subsetD smallest_ccdi_sets)\n    apply (blast intro: smallest_ccdi_sets.Disj)\n    done\n  hence \"sigma_sets (\\<Omega>) (M) \\<subseteq> smallest_ccdi_sets \\<Omega> M\"\n    by clarsimp\n       (drule sigma_algebra.sigma_sets_subset [where a=\"M\"], auto)\n  also have \"...  \\<subseteq> C\"\n    proof\n      fix x\n      assume x: \"x \\<in> smallest_ccdi_sets \\<Omega> M\"\n      thus \"x \\<in> C\"\n        proof (induct rule: smallest_ccdi_sets.induct)\n          case (Basic x)\n          thus ?case\n            by (metis Basic subsetD sbC)\n        next\n          case (Compl x)\n          thus ?case\n            by (blast intro: closed_cdi_Compl [OF ccdi, simplified])\n        next\n          case (Inc A)\n          thus ?case\n               by (auto intro: closed_cdi_Inc [OF ccdi, simplified])\n        next\n          case (Disj A)\n          thus ?case\n               by (auto intro: closed_cdi_Disj [OF ccdi, simplified])\n        qed\n    qed\n  finally show ?thesis .\nqed\n\nlemma (in algebra) sigma_property_disjoint:\n  assumes sbC: \"M \\<subseteq> C\"\n      and compl: \"!!s. s \\<in> C \\<inter> sigma_sets (\\<Omega>) (M) \\<Longrightarrow> \\<Omega> - s \\<in> C\"\n      and inc: \"!!A. range A \\<subseteq> C \\<inter> sigma_sets (\\<Omega>) (M)\n                     \\<Longrightarrow> A 0 = {} \\<Longrightarrow> (!!n. A n \\<subseteq> A (Suc n))\n                     \\<Longrightarrow> (\\<Union>i. A i) \\<in> C\"\n      and disj: \"!!A. range A \\<subseteq> C \\<inter> sigma_sets (\\<Omega>) (M)\n                      \\<Longrightarrow> disjoint_family A \\<Longrightarrow> (\\<Union>i::nat. A i) \\<in> C\"\n  shows \"sigma_sets (\\<Omega>) (M) \\<subseteq> C\"\nproof -\n  have \"sigma_sets (\\<Omega>) (M) \\<subseteq> C \\<inter> sigma_sets (\\<Omega>) (M)\"\n    proof (rule sigma_property_disjoint_lemma)\n      show \"M \\<subseteq> C \\<inter> sigma_sets (\\<Omega>) (M)\"\n        by (metis Int_greatest Set.subsetI sbC sigma_sets.Basic)\n    next\n      show \"closed_cdi \\<Omega> (C \\<inter> sigma_sets (\\<Omega>) (M))\"\n        by (simp add: closed_cdi_def compl inc disj)\n           (metis PowI Set.subsetI le_infI2 sigma_sets_into_sp space_closed\n             IntE sigma_sets.Compl range_subsetD sigma_sets.Union)\n    qed\n  thus ?thesis\n    by blast\nqed\n\nsubsubsection {* Dynkin systems *}\n\nlocale dynkin_system = subset_class +\n  assumes space: \"\\<Omega> \\<in> M\"\n    and   compl[intro!]: \"\\<And>A. A \\<in> M \\<Longrightarrow> \\<Omega> - A \\<in> M\"\n    and   UN[intro!]: \"\\<And>A. disjoint_family A \\<Longrightarrow> range A \\<subseteq> M\n                           \\<Longrightarrow> (\\<Union>i::nat. A i) \\<in> M\"\n\nlemma (in dynkin_system) empty[intro, simp]: \"{} \\<in> M\"\n  using space compl[of \"\\<Omega>\"] by simp\n\nlemma (in dynkin_system) diff:\n  assumes sets: \"D \\<in> M\" \"E \\<in> M\" and \"D \\<subseteq> E\"\n  shows \"E - D \\<in> M\"\nproof -\n  let ?f = \"\\<lambda>x. if x = 0 then D else if x = Suc 0 then \\<Omega> - E else {}\"\n  have \"range ?f = {D, \\<Omega> - E, {}}\"\n    by (auto simp: image_iff)\n  moreover have \"D \\<union> (\\<Omega> - E) = (\\<Union>i. ?f i)\"\n    by (auto simp: image_iff split: split_if_asm)\n  moreover\n  have \"disjoint_family ?f\" unfolding disjoint_family_on_def\n    using `D \\<in> M`[THEN sets_into_space] `D \\<subseteq> E` by auto\n  ultimately have \"\\<Omega> - (D \\<union> (\\<Omega> - E)) \\<in> M\"\n    using sets by auto\n  also have \"\\<Omega> - (D \\<union> (\\<Omega> - E)) = E - D\"\n    using assms sets_into_space by auto\n  finally show ?thesis .\nqed\n\nlemma dynkin_systemI:\n  assumes \"\\<And> A. A \\<in> M \\<Longrightarrow> A \\<subseteq> \\<Omega>\" \"\\<Omega> \\<in> M\"\n  assumes \"\\<And> A. A \\<in> M \\<Longrightarrow> \\<Omega> - A \\<in> M\"\n  assumes \"\\<And> A. disjoint_family A \\<Longrightarrow> range A \\<subseteq> M\n          \\<Longrightarrow> (\\<Union>i::nat. A i) \\<in> M\"\n  shows \"dynkin_system \\<Omega> M\"\n  using assms by (auto simp: dynkin_system_def dynkin_system_axioms_def subset_class_def)\n\nlemma dynkin_systemI':\n  assumes 1: \"\\<And> A. A \\<in> M \\<Longrightarrow> A \\<subseteq> \\<Omega>\"\n  assumes empty: \"{} \\<in> M\"\n  assumes Diff: \"\\<And> A. A \\<in> M \\<Longrightarrow> \\<Omega> - A \\<in> M\"\n  assumes 2: \"\\<And> A. disjoint_family A \\<Longrightarrow> range A \\<subseteq> M\n          \\<Longrightarrow> (\\<Union>i::nat. A i) \\<in> M\"\n  shows \"dynkin_system \\<Omega> M\"\nproof -\n  from Diff[OF empty] have \"\\<Omega> \\<in> M\" by auto\n  from 1 this Diff 2 show ?thesis\n    by (intro dynkin_systemI) auto\nqed\n\nlemma dynkin_system_trivial:\n  shows \"dynkin_system A (Pow A)\"\n  by (rule dynkin_systemI) auto\n\nlemma sigma_algebra_imp_dynkin_system:\n  assumes \"sigma_algebra \\<Omega> M\" shows \"dynkin_system \\<Omega> M\"\nproof -\n  interpret sigma_algebra \\<Omega> M by fact\n  show ?thesis using sets_into_space by (fastforce intro!: dynkin_systemI)\nqed\n\nsubsubsection \"Intersection sets systems\"\n\ndefinition \"Int_stable M \\<longleftrightarrow> (\\<forall> a \\<in> M. \\<forall> b \\<in> M. a \\<inter> b \\<in> M)\"\n\nlemma (in algebra) Int_stable: \"Int_stable M\"\n  unfolding Int_stable_def by auto\n\nlemma Int_stableI:\n  \"(\\<And>a b. a \\<in> A \\<Longrightarrow> b \\<in> A \\<Longrightarrow> a \\<inter> b \\<in> A) \\<Longrightarrow> Int_stable A\"\n  unfolding Int_stable_def by auto\n\nlemma Int_stableD:\n  \"Int_stable M \\<Longrightarrow> a \\<in> M \\<Longrightarrow> b \\<in> M \\<Longrightarrow> a \\<inter> b \\<in> M\"\n  unfolding Int_stable_def by auto\n\nlemma (in dynkin_system) sigma_algebra_eq_Int_stable:\n  \"sigma_algebra \\<Omega> M \\<longleftrightarrow> Int_stable M\"\nproof\n  assume \"sigma_algebra \\<Omega> M\" then show \"Int_stable M\"\n    unfolding sigma_algebra_def using algebra.Int_stable by auto\nnext\n  assume \"Int_stable M\"\n  show \"sigma_algebra \\<Omega> M\"\n    unfolding sigma_algebra_disjoint_iff algebra_iff_Un\n  proof (intro conjI ballI allI impI)\n    show \"M \\<subseteq> Pow (\\<Omega>)\" using sets_into_space by auto\n  next\n    fix A B assume \"A \\<in> M\" \"B \\<in> M\"\n    then have \"A \\<union> B = \\<Omega> - ((\\<Omega> - A) \\<inter> (\\<Omega> - B))\"\n              \"\\<Omega> - A \\<in> M\" \"\\<Omega> - B \\<in> M\"\n      using sets_into_space by auto\n    then show \"A \\<union> B \\<in> M\"\n      using `Int_stable M` unfolding Int_stable_def by auto\n  qed auto\nqed\n\nsubsubsection \"Smallest Dynkin systems\"\n\ndefinition dynkin where\n  \"dynkin \\<Omega> M =  (\\<Inter>{D. dynkin_system \\<Omega> D \\<and> M \\<subseteq> D})\"\n\nlemma dynkin_system_dynkin:\n  assumes \"M \\<subseteq> Pow (\\<Omega>)\"\n  shows \"dynkin_system \\<Omega> (dynkin \\<Omega> M)\"\nproof (rule dynkin_systemI)\n  fix A assume \"A \\<in> dynkin \\<Omega> M\"\n  moreover\n  { fix D assume \"A \\<in> D\" and d: \"dynkin_system \\<Omega> D\"\n    then have \"A \\<subseteq> \\<Omega>\" by (auto simp: dynkin_system_def subset_class_def) }\n  moreover have \"{D. dynkin_system \\<Omega> D \\<and> M \\<subseteq> D} \\<noteq> {}\"\n    using assms dynkin_system_trivial by fastforce\n  ultimately show \"A \\<subseteq> \\<Omega>\"\n    unfolding dynkin_def using assms\n    by auto\nnext\n  show \"\\<Omega> \\<in> dynkin \\<Omega> M\"\n    unfolding dynkin_def using dynkin_system.space by fastforce\nnext\n  fix A assume \"A \\<in> dynkin \\<Omega> M\"\n  then show \"\\<Omega> - A \\<in> dynkin \\<Omega> M\"\n    unfolding dynkin_def using dynkin_system.compl by force\nnext\n  fix A :: \"nat \\<Rightarrow> 'a set\"\n  assume A: \"disjoint_family A\" \"range A \\<subseteq> dynkin \\<Omega> M\"\n  show \"(\\<Union>i. A i) \\<in> dynkin \\<Omega> M\" unfolding dynkin_def\n  proof (simp, safe)\n    fix D assume \"dynkin_system \\<Omega> D\" \"M \\<subseteq> D\"\n    with A have \"(\\<Union>i. A i) \\<in> D\"\n      by (intro dynkin_system.UN) (auto simp: dynkin_def)\n    then show \"(\\<Union>i. A i) \\<in> D\" by auto\n  qed\nqed\n\nlemma dynkin_Basic[intro]: \"A \\<in> M \\<Longrightarrow> A \\<in> dynkin \\<Omega> M\"\n  unfolding dynkin_def by auto\n\nlemma (in dynkin_system) restricted_dynkin_system:\n  assumes \"D \\<in> M\"\n  shows \"dynkin_system \\<Omega> {Q. Q \\<subseteq> \\<Omega> \\<and> Q \\<inter> D \\<in> M}\"\nproof (rule dynkin_systemI, simp_all)\n  have \"\\<Omega> \\<inter> D = D\"\n    using `D \\<in> M` sets_into_space by auto\n  then show \"\\<Omega> \\<inter> D \\<in> M\"\n    using `D \\<in> M` by auto\nnext\n  fix A assume \"A \\<subseteq> \\<Omega> \\<and> A \\<inter> D \\<in> M\"\n  moreover have \"(\\<Omega> - A) \\<inter> D = (\\<Omega> - (A \\<inter> D)) - (\\<Omega> - D)\"\n    by auto\n  ultimately show \"\\<Omega> - A \\<subseteq> \\<Omega> \\<and> (\\<Omega> - A) \\<inter> D \\<in> M\"\n    using  `D \\<in> M` by (auto intro: diff)\nnext\n  fix A :: \"nat \\<Rightarrow> 'a set\"\n  assume \"disjoint_family A\" \"range A \\<subseteq> {Q. Q \\<subseteq> \\<Omega> \\<and> Q \\<inter> D \\<in> M}\"\n  then have \"\\<And>i. A i \\<subseteq> \\<Omega>\" \"disjoint_family (\\<lambda>i. A i \\<inter> D)\"\n    \"range (\\<lambda>i. A i \\<inter> D) \\<subseteq> M\" \"(\\<Union>x. A x) \\<inter> D = (\\<Union>x. A x \\<inter> D)\"\n    by ((fastforce simp: disjoint_family_on_def)+)\n  then show \"(\\<Union>x. A x) \\<subseteq> \\<Omega> \\<and> (\\<Union>x. A x) \\<inter> D \\<in> M\"\n    by (auto simp del: UN_simps)\nqed\n\nlemma (in dynkin_system) dynkin_subset:\n  assumes \"N \\<subseteq> M\"\n  shows \"dynkin \\<Omega> N \\<subseteq> M\"\nproof -\n  have \"dynkin_system \\<Omega> M\" by default\n  then have \"dynkin_system \\<Omega> M\"\n    using assms unfolding dynkin_system_def dynkin_system_axioms_def subset_class_def by simp\n  with `N \\<subseteq> M` show ?thesis by (auto simp add: dynkin_def)\nqed\n\nlemma sigma_eq_dynkin:\n  assumes sets: \"M \\<subseteq> Pow \\<Omega>\"\n  assumes \"Int_stable M\"\n  shows \"sigma_sets \\<Omega> M = dynkin \\<Omega> M\"\nproof -\n  have \"dynkin \\<Omega> M \\<subseteq> sigma_sets (\\<Omega>) (M)\"\n    using sigma_algebra_imp_dynkin_system\n    unfolding dynkin_def sigma_sets_least_sigma_algebra[OF sets] by auto\n  moreover\n  interpret dynkin_system \\<Omega> \"dynkin \\<Omega> M\"\n    using dynkin_system_dynkin[OF sets] .\n  have \"sigma_algebra \\<Omega> (dynkin \\<Omega> M)\"\n    unfolding sigma_algebra_eq_Int_stable Int_stable_def\n  proof (intro ballI)\n    fix A B assume \"A \\<in> dynkin \\<Omega> M\" \"B \\<in> dynkin \\<Omega> M\"\n    let ?D = \"\\<lambda>E. {Q. Q \\<subseteq> \\<Omega> \\<and> Q \\<inter> E \\<in> dynkin \\<Omega> M}\"\n    have \"M \\<subseteq> ?D B\"\n    proof\n      fix E assume \"E \\<in> M\"\n      then have \"M \\<subseteq> ?D E\" \"E \\<in> dynkin \\<Omega> M\"\n        using sets_into_space `Int_stable M` by (auto simp: Int_stable_def)\n      then have \"dynkin \\<Omega> M \\<subseteq> ?D E\"\n        using restricted_dynkin_system `E \\<in> dynkin \\<Omega> M`\n        by (intro dynkin_system.dynkin_subset) simp_all\n      then have \"B \\<in> ?D E\"\n        using `B \\<in> dynkin \\<Omega> M` by auto\n      then have \"E \\<inter> B \\<in> dynkin \\<Omega> M\"\n        by (subst Int_commute) simp\n      then show \"E \\<in> ?D B\"\n        using sets `E \\<in> M` by auto\n    qed\n    then have \"dynkin \\<Omega> M \\<subseteq> ?D B\"\n      using restricted_dynkin_system `B \\<in> dynkin \\<Omega> M`\n      by (intro dynkin_system.dynkin_subset) simp_all\n    then show \"A \\<inter> B \\<in> dynkin \\<Omega> M\"\n      using `A \\<in> dynkin \\<Omega> M` sets_into_space by auto\n  qed\n  from sigma_algebra.sigma_sets_subset[OF this, of \"M\"]\n  have \"sigma_sets (\\<Omega>) (M) \\<subseteq> dynkin \\<Omega> M\" by auto\n  ultimately have \"sigma_sets (\\<Omega>) (M) = dynkin \\<Omega> M\" by auto\n  then show ?thesis\n    by (auto simp: dynkin_def)\nqed\n\nlemma (in dynkin_system) dynkin_idem:\n  \"dynkin \\<Omega> M = M\"\nproof -\n  have \"dynkin \\<Omega> M = M\"\n  proof\n    show \"M \\<subseteq> dynkin \\<Omega> M\"\n      using dynkin_Basic by auto\n    show \"dynkin \\<Omega> M \\<subseteq> M\"\n      by (intro dynkin_subset) auto\n  qed\n  then show ?thesis\n    by (auto simp: dynkin_def)\nqed\n\nlemma (in dynkin_system) dynkin_lemma:\n  assumes \"Int_stable E\"\n  and E: \"E \\<subseteq> M\" \"M \\<subseteq> sigma_sets \\<Omega> E\"\n  shows \"sigma_sets \\<Omega> E = M\"\nproof -\n  have \"E \\<subseteq> Pow \\<Omega>\"\n    using E sets_into_space by force\n  then have *: \"sigma_sets \\<Omega> E = dynkin \\<Omega> E\"\n    using `Int_stable E` by (rule sigma_eq_dynkin)\n  then have \"dynkin \\<Omega> E = M\"\n    using assms dynkin_subset[OF E(1)] by simp\n  with * show ?thesis\n    using assms by (auto simp: dynkin_def)\nqed\n\nsubsubsection {* Induction rule for intersection-stable generators *}\n\ntext {* The reason to introduce Dynkin-systems is the following induction rules for $\\sigma$-algebras\ngenerated by a generator closed under intersection. *}\n\nlemma sigma_sets_induct_disjoint[consumes 3, case_names basic empty compl union]:\n  assumes \"Int_stable G\"\n    and closed: \"G \\<subseteq> Pow \\<Omega>\"\n    and A: \"A \\<in> sigma_sets \\<Omega> G\"\n  assumes basic: \"\\<And>A. A \\<in> G \\<Longrightarrow> P A\"\n    and empty: \"P {}\"\n    and compl: \"\\<And>A. A \\<in> sigma_sets \\<Omega> G \\<Longrightarrow> P A \\<Longrightarrow> P (\\<Omega> - A)\"\n    and union: \"\\<And>A. disjoint_family A \\<Longrightarrow> range A \\<subseteq> sigma_sets \\<Omega> G \\<Longrightarrow> (\\<And>i. P (A i)) \\<Longrightarrow> P (\\<Union>i::nat. A i)\"\n  shows \"P A\"\nproof -\n  let ?D = \"{ A \\<in> sigma_sets \\<Omega> G. P A }\"\n  interpret sigma_algebra \\<Omega> \"sigma_sets \\<Omega> G\"\n    using closed by (rule sigma_algebra_sigma_sets)\n  from compl[OF _ empty] closed have space: \"P \\<Omega>\" by simp\n  interpret dynkin_system \\<Omega> ?D\n    by default (auto dest: sets_into_space intro!: space compl union)\n  have \"sigma_sets \\<Omega> G = ?D\"\n    by (rule dynkin_lemma) (auto simp: basic `Int_stable G`)\n  with A show ?thesis by auto\nqed\n\nsubsection {* Measure type *}\n\ndefinition positive :: \"'a set set \\<Rightarrow> ('a set \\<Rightarrow> ereal) \\<Rightarrow> bool\" where\n  \"positive M \\<mu> \\<longleftrightarrow> \\<mu> {} = 0 \\<and> (\\<forall>A\\<in>M. 0 \\<le> \\<mu> A)\"\n\ndefinition countably_additive :: \"'a set set \\<Rightarrow> ('a set \\<Rightarrow> ereal) \\<Rightarrow> bool\" where\n  \"countably_additive M f \\<longleftrightarrow> (\\<forall>A. range A \\<subseteq> M \\<longrightarrow> disjoint_family A \\<longrightarrow> (\\<Union>i. A i) \\<in> M \\<longrightarrow>\n    (\\<Sum>i. f (A i)) = f (\\<Union>i. A i))\"\n\ndefinition measure_space :: \"'a set \\<Rightarrow> 'a set set \\<Rightarrow> ('a set \\<Rightarrow> ereal) \\<Rightarrow> bool\" where\n  \"measure_space \\<Omega> A \\<mu> \\<longleftrightarrow> sigma_algebra \\<Omega> A \\<and> positive A \\<mu> \\<and> countably_additive A \\<mu>\"\n\ntypedef 'a measure = \"{(\\<Omega>::'a set, A, \\<mu>). (\\<forall>a\\<in>-A. \\<mu> a = 0) \\<and> measure_space \\<Omega> A \\<mu> }\"\nproof\n  have \"sigma_algebra UNIV {{}, UNIV}\"\n    by (auto simp: sigma_algebra_iff2)\n  then show \"(UNIV, {{}, UNIV}, \\<lambda>A. 0) \\<in> {(\\<Omega>, A, \\<mu>). (\\<forall>a\\<in>-A. \\<mu> a = 0) \\<and> measure_space \\<Omega> A \\<mu>} \"\n    by (auto simp: measure_space_def positive_def countably_additive_def)\nqed\n\ndefinition space :: \"'a measure \\<Rightarrow> 'a set\" where\n  \"space M = fst (Rep_measure M)\"\n\ndefinition sets :: \"'a measure \\<Rightarrow> 'a set set\" where\n  \"sets M = fst (snd (Rep_measure M))\"\n\ndefinition emeasure :: \"'a measure \\<Rightarrow> 'a set \\<Rightarrow> ereal\" where\n  \"emeasure M = snd (snd (Rep_measure M))\"\n\ndefinition measure :: \"'a measure \\<Rightarrow> 'a set \\<Rightarrow> real\" where\n  \"measure M A = real (emeasure M A)\"\n\ndeclare [[coercion sets]]\n\ndeclare [[coercion measure]]\n\ndeclare [[coercion emeasure]]\n\nlemma measure_space: \"measure_space (space M) (sets M) (emeasure M)\"\n  by (cases M) (auto simp: space_def sets_def emeasure_def Abs_measure_inverse)\n\ninterpretation sets!: sigma_algebra \"space M\" \"sets M\" for M :: \"'a measure\"\n  using measure_space[of M] by (auto simp: measure_space_def)\n\ndefinition measure_of :: \"'a set \\<Rightarrow> 'a set set \\<Rightarrow> ('a set \\<Rightarrow> ereal) \\<Rightarrow> 'a measure\" where\n  \"measure_of \\<Omega> A \\<mu> = Abs_measure (\\<Omega>, if A \\<subseteq> Pow \\<Omega> then sigma_sets \\<Omega> A else {{}, \\<Omega>},\n    \\<lambda>a. if a \\<in> sigma_sets \\<Omega> A \\<and> measure_space \\<Omega> (sigma_sets \\<Omega> A) \\<mu> then \\<mu> a else 0)\"\n\nabbreviation \"sigma \\<Omega> A \\<equiv> measure_of \\<Omega> A (\\<lambda>x. 0)\"\n\nlemma measure_space_0: \"A \\<subseteq> Pow \\<Omega> \\<Longrightarrow> measure_space \\<Omega> (sigma_sets \\<Omega> A) (\\<lambda>x. 0)\"\n  unfolding measure_space_def\n  by (auto intro!: sigma_algebra_sigma_sets simp: positive_def countably_additive_def)\n\nlemma sigma_algebra_trivial: \"sigma_algebra \\<Omega> {{}, \\<Omega>}\"\nby unfold_locales(fastforce intro: exI[where x=\"{{}}\"] exI[where x=\"{\\<Omega>}\"])+\n\nlemma measure_space_0': \"measure_space \\<Omega> {{}, \\<Omega>} (\\<lambda>x. 0)\"\nby(simp add: measure_space_def positive_def countably_additive_def sigma_algebra_trivial)\n\nlemma measure_space_closed:\n  assumes \"measure_space \\<Omega> M \\<mu>\"\n  shows \"M \\<subseteq> Pow \\<Omega>\"\nproof -\n  interpret sigma_algebra \\<Omega> M using assms by(simp add: measure_space_def)\n  show ?thesis by(rule space_closed)\nqed\n\nlemma (in ring_of_sets) positive_cong_eq:\n  \"(\\<And>a. a \\<in> M \\<Longrightarrow> \\<mu>' a = \\<mu> a) \\<Longrightarrow> positive M \\<mu>' = positive M \\<mu>\"\n  by (auto simp add: positive_def)\n\nlemma (in sigma_algebra) countably_additive_eq:\n  \"(\\<And>a. a \\<in> M \\<Longrightarrow> \\<mu>' a = \\<mu> a) \\<Longrightarrow> countably_additive M \\<mu>' = countably_additive M \\<mu>\"\n  unfolding countably_additive_def\n  by (intro arg_cong[where f=All] ext) (auto simp add: countably_additive_def subset_eq)\n\nlemma measure_space_eq:\n  assumes closed: \"A \\<subseteq> Pow \\<Omega>\" and eq: \"\\<And>a. a \\<in> sigma_sets \\<Omega> A \\<Longrightarrow> \\<mu> a = \\<mu>' a\"\n  shows \"measure_space \\<Omega> (sigma_sets \\<Omega> A) \\<mu> = measure_space \\<Omega> (sigma_sets \\<Omega> A) \\<mu>'\"\nproof -\n  interpret sigma_algebra \\<Omega> \"sigma_sets \\<Omega> A\" using closed by (rule sigma_algebra_sigma_sets)\n  from positive_cong_eq[OF eq, of \"\\<lambda>i. i\"] countably_additive_eq[OF eq, of \"\\<lambda>i. i\"] show ?thesis\n    by (auto simp: measure_space_def)\nqed\n\nlemma measure_of_eq:\n  assumes closed: \"A \\<subseteq> Pow \\<Omega>\" and eq: \"(\\<And>a. a \\<in> sigma_sets \\<Omega> A \\<Longrightarrow> \\<mu> a = \\<mu>' a)\"\n  shows \"measure_of \\<Omega> A \\<mu> = measure_of \\<Omega> A \\<mu>'\"\nproof -\n  have \"measure_space \\<Omega> (sigma_sets \\<Omega> A) \\<mu> = measure_space \\<Omega> (sigma_sets \\<Omega> A) \\<mu>'\"\n    using assms by (rule measure_space_eq)\n  with eq show ?thesis\n    by (auto simp add: measure_of_def intro!: arg_cong[where f=Abs_measure])\nqed\n\nlemma\n  shows space_measure_of_conv: \"space (measure_of \\<Omega> A \\<mu>) = \\<Omega>\" (is ?space)\n  and sets_measure_of_conv:\n  \"sets (measure_of \\<Omega> A \\<mu>) = (if A \\<subseteq> Pow \\<Omega> then sigma_sets \\<Omega> A else {{}, \\<Omega>})\" (is ?sets)\n  and emeasure_measure_of_conv: \n  \"emeasure (measure_of \\<Omega> A \\<mu>) = \n  (\\<lambda>B. if B \\<in> sigma_sets \\<Omega> A \\<and> measure_space \\<Omega> (sigma_sets \\<Omega> A) \\<mu> then \\<mu> B else 0)\" (is ?emeasure)\nproof -\n  have \"?space \\<and> ?sets \\<and> ?emeasure\"\n  proof(cases \"measure_space \\<Omega> (sigma_sets \\<Omega> A) \\<mu>\")\n    case True\n    from measure_space_closed[OF this] sigma_sets_superset_generator[of A \\<Omega>]\n    have \"A \\<subseteq> Pow \\<Omega>\" by simp\n    hence \"measure_space \\<Omega> (sigma_sets \\<Omega> A) \\<mu> = measure_space \\<Omega> (sigma_sets \\<Omega> A)\n      (\\<lambda>a. if a \\<in> sigma_sets \\<Omega> A then \\<mu> a else 0)\"\n      by(rule measure_space_eq) auto\n    with True `A \\<subseteq> Pow \\<Omega>` show ?thesis\n      by(simp add: measure_of_def space_def sets_def emeasure_def Abs_measure_inverse)\n  next\n    case False thus ?thesis\n      by(cases \"A \\<subseteq> Pow \\<Omega>\")(simp_all add: Abs_measure_inverse measure_of_def sets_def space_def emeasure_def measure_space_0 measure_space_0')\n  qed\n  thus ?space ?sets ?emeasure by simp_all\nqed\n\n\n\nlemma (in sigma_algebra) sets_measure_of_eq[simp]: \"sets (measure_of \\<Omega> M \\<mu>) = M\"\n  using space_closed by (auto intro!: sigma_sets_eq)\n\nlemma (in sigma_algebra) space_measure_of_eq[simp]: \"space (measure_of \\<Omega> M \\<mu>) = \\<Omega>\"\n  by (rule space_measure_of_conv)\n\nlemma measure_of_subset: \"M \\<subseteq> Pow \\<Omega> \\<Longrightarrow> M' \\<subseteq> M \\<Longrightarrow> sets (measure_of \\<Omega> M' \\<mu>) \\<subseteq> sets (measure_of \\<Omega> M \\<mu>')\"\n  by (auto intro!: sigma_sets_subseteq)\n\nlemma emeasure_sigma: \"emeasure (sigma \\<Omega> A) = (\\<lambda>x. 0)\"\n  unfolding measure_of_def emeasure_def\n  by (subst Abs_measure_inverse)\n     (auto simp: measure_space_def positive_def countably_additive_def\n           intro!: sigma_algebra_sigma_sets sigma_algebra_trivial)\n\nlemma sigma_sets_mono'':\n  assumes \"A \\<in> sigma_sets C D\"\n  assumes \"B \\<subseteq> D\"\n  assumes \"D \\<subseteq> Pow C\"\n  shows \"sigma_sets A B \\<subseteq> sigma_sets C D\"\nproof\n  fix x assume \"x \\<in> sigma_sets A B\"\n  thus \"x \\<in> sigma_sets C D\"\n  proof induct\n    case (Basic a) with assms have \"a \\<in> D\" by auto\n    thus ?case ..\n  next\n    case Empty show ?case by (rule sigma_sets.Empty)\n  next\n    from assms have \"A \\<in> sets (sigma C D)\" by (subst sets_measure_of[OF `D \\<subseteq> Pow C`])\n    moreover case (Compl a) hence \"a \\<in> sets (sigma C D)\" by (subst sets_measure_of[OF `D \\<subseteq> Pow C`])\n    ultimately have \"A - a \\<in> sets (sigma C D)\" ..\n    thus ?case by (subst (asm) sets_measure_of[OF `D \\<subseteq> Pow C`])\n  next\n    case (Union a)\n    thus ?case by (intro sigma_sets.Union)\n  qed\nqed\n\nlemma in_measure_of[intro, simp]: \"M \\<subseteq> Pow \\<Omega> \\<Longrightarrow> A \\<in> M \\<Longrightarrow> A \\<in> sets (measure_of \\<Omega> M \\<mu>)\"\n  by auto\n\nlemma space_empty_iff: \"space N = {} \\<longleftrightarrow> sets N = {{}}\"\n  by (metis Pow_empty Sup_bot_conv(1) cSup_singleton empty_iff\n            sets.sigma_sets_eq sets.space_closed sigma_sets_top subset_singletonD)\n\nsubsubsection {* Constructing simple @{typ \"'a measure\"} *}\n\nlemma emeasure_measure_of:\n  assumes M: \"M = measure_of \\<Omega> A \\<mu>\"\n  assumes ms: \"A \\<subseteq> Pow \\<Omega>\" \"positive (sets M) \\<mu>\" \"countably_additive (sets M) \\<mu>\"\n  assumes X: \"X \\<in> sets M\"\n  shows \"emeasure M X = \\<mu> X\"\nproof -\n  interpret sigma_algebra \\<Omega> \"sigma_sets \\<Omega> A\" by (rule sigma_algebra_sigma_sets) fact\n  have \"measure_space \\<Omega> (sigma_sets \\<Omega> A) \\<mu>\"\n    using ms M by (simp add: measure_space_def sigma_algebra_sigma_sets)\n  thus ?thesis using X ms\n    by(simp add: M emeasure_measure_of_conv sets_measure_of_conv)\nqed\n\nlemma emeasure_measure_of_sigma:\n  assumes ms: \"sigma_algebra \\<Omega> M\" \"positive M \\<mu>\" \"countably_additive M \\<mu>\"\n  assumes A: \"A \\<in> M\"\n  shows \"emeasure (measure_of \\<Omega> M \\<mu>) A = \\<mu> A\"\nproof -\n  interpret sigma_algebra \\<Omega> M by fact\n  have \"measure_space \\<Omega> (sigma_sets \\<Omega> M) \\<mu>\"\n    using ms sigma_sets_eq by (simp add: measure_space_def)\n  thus ?thesis by(simp add: emeasure_measure_of_conv A)\nqed\n\nlemma measure_cases[cases type: measure]:\n  obtains (measure) \\<Omega> A \\<mu> where \"x = Abs_measure (\\<Omega>, A, \\<mu>)\" \"\\<forall>a\\<in>-A. \\<mu> a = 0\" \"measure_space \\<Omega> A \\<mu>\"\n  by atomize_elim (cases x, auto)\n\nlemma sets_eq_imp_space_eq:\n  \"sets M = sets M' \\<Longrightarrow> space M = space M'\"\n  using sets.top[of M] sets.top[of M'] sets.space_closed[of M] sets.space_closed[of M']\n  by blast\n\nlemma emeasure_notin_sets: \"A \\<notin> sets M \\<Longrightarrow> emeasure M A = 0\"\n  by (cases M) (auto simp: sets_def emeasure_def Abs_measure_inverse measure_space_def)\n\nlemma emeasure_neq_0_sets: \"emeasure M A \\<noteq> 0 \\<Longrightarrow> A \\<in> sets M\"\n  using emeasure_notin_sets[of A M] by blast\n\nlemma measure_notin_sets: \"A \\<notin> sets M \\<Longrightarrow> measure M A = 0\"\n  by (simp add: measure_def emeasure_notin_sets)\n\nlemma measure_eqI:\n  fixes M N :: \"'a measure\"\n  assumes \"sets M = sets N\" and eq: \"\\<And>A. A \\<in> sets M \\<Longrightarrow> emeasure M A = emeasure N A\"\n  shows \"M = N\"\nproof (cases M N rule: measure_cases[case_product measure_cases])\n  case (measure_measure \\<Omega> A \\<mu> \\<Omega>' A' \\<mu>')\n  interpret M: sigma_algebra \\<Omega> A using measure_measure by (auto simp: measure_space_def)\n  interpret N: sigma_algebra \\<Omega>' A' using measure_measure by (auto simp: measure_space_def)\n  have \"A = sets M\" \"A' = sets N\"\n    using measure_measure by (simp_all add: sets_def Abs_measure_inverse)\n  with `sets M = sets N` have AA': \"A = A'\" by simp\n  moreover from M.top N.top M.space_closed N.space_closed AA' have \"\\<Omega> = \\<Omega>'\" by auto\n  moreover { fix B have \"\\<mu> B = \\<mu>' B\"\n    proof cases\n      assume \"B \\<in> A\"\n      with eq `A = sets M` have \"emeasure M B = emeasure N B\" by simp\n      with measure_measure show \"\\<mu> B = \\<mu>' B\"\n        by (simp add: emeasure_def Abs_measure_inverse)\n    next\n      assume \"B \\<notin> A\"\n      with `A = sets M` `A' = sets N` `A = A'` have \"B \\<notin> sets M\" \"B \\<notin> sets N\"\n        by auto\n      then have \"emeasure M B = 0\" \"emeasure N B = 0\"\n        by (simp_all add: emeasure_notin_sets)\n      with measure_measure show \"\\<mu> B = \\<mu>' B\"\n        by (simp add: emeasure_def Abs_measure_inverse)\n    qed }\n  then have \"\\<mu> = \\<mu>'\" by auto\n  ultimately show \"M = N\"\n    by (simp add: measure_measure)\nqed\n\nlemma sigma_eqI:\n  assumes [simp]: \"M \\<subseteq> Pow \\<Omega>\" \"N \\<subseteq> Pow \\<Omega>\" \"sigma_sets \\<Omega> M = sigma_sets \\<Omega> N\"\n  shows \"sigma \\<Omega> M = sigma \\<Omega> N\"\n  by (rule measure_eqI) (simp_all add: emeasure_sigma)\n\nsubsubsection {* Measurable functions *}\n\ndefinition measurable :: \"'a measure \\<Rightarrow> 'b measure \\<Rightarrow> ('a \\<Rightarrow> 'b) set\" where\n  \"measurable A B = {f \\<in> space A -> space B. \\<forall>y \\<in> sets B. f -` y \\<inter> space A \\<in> sets A}\"\n\nlemma measurable_space:\n  \"f \\<in> measurable M A \\<Longrightarrow> x \\<in> space M \\<Longrightarrow> f x \\<in> space A\"\n   unfolding measurable_def by auto\n\nlemma measurable_sets:\n  \"f \\<in> measurable M A \\<Longrightarrow> S \\<in> sets A \\<Longrightarrow> f -` S \\<inter> space M \\<in> sets M\"\n   unfolding measurable_def by auto\n\nlemma measurable_sets_Collect:\n  assumes f: \"f \\<in> measurable M N\" and P: \"{x\\<in>space N. P x} \\<in> sets N\" shows \"{x\\<in>space M. P (f x)} \\<in> sets M\"\nproof -\n  have \"f -` {x \\<in> space N. P x} \\<inter> space M = {x\\<in>space M. P (f x)}\"\n    using measurable_space[OF f] by auto\n  with measurable_sets[OF f P] show ?thesis\n    by simp\nqed\n\nlemma measurable_sigma_sets:\n  assumes B: \"sets N = sigma_sets \\<Omega> A\" \"A \\<subseteq> Pow \\<Omega>\"\n      and f: \"f \\<in> space M \\<rightarrow> \\<Omega>\"\n      and ba: \"\\<And>y. y \\<in> A \\<Longrightarrow> (f -` y) \\<inter> space M \\<in> sets M\"\n  shows \"f \\<in> measurable M N\"\nproof -\n  interpret A: sigma_algebra \\<Omega> \"sigma_sets \\<Omega> A\" using B(2) by (rule sigma_algebra_sigma_sets)\n  from B sets.top[of N] A.top sets.space_closed[of N] A.space_closed have \\<Omega>: \"\\<Omega> = space N\" by force\n  \n  { fix X assume \"X \\<in> sigma_sets \\<Omega> A\"\n    then have \"f -` X \\<inter> space M \\<in> sets M \\<and> X \\<subseteq> \\<Omega>\"\n      proof induct\n        case (Basic a) then show ?case\n          by (auto simp add: ba) (metis B(2) subsetD PowD)\n      next\n        case (Compl a)\n        have [simp]: \"f -` \\<Omega> \\<inter> space M = space M\"\n          by (auto simp add: funcset_mem [OF f])\n        then show ?case\n          by (auto simp add: vimage_Diff Diff_Int_distrib2 sets.compl_sets Compl)\n      next\n        case (Union a)\n        then show ?case\n          by (simp add: vimage_UN, simp only: UN_extend_simps(4)) blast\n      qed auto }\n  with f show ?thesis\n    by (auto simp add: measurable_def B \\<Omega>)\nqed\n\nlemma measurable_measure_of:\n  assumes B: \"N \\<subseteq> Pow \\<Omega>\"\n      and f: \"f \\<in> space M \\<rightarrow> \\<Omega>\"\n      and ba: \"\\<And>y. y \\<in> N \\<Longrightarrow> (f -` y) \\<inter> space M \\<in> sets M\"\n  shows \"f \\<in> measurable M (measure_of \\<Omega> N \\<mu>)\"\nproof -\n  have \"sets (measure_of \\<Omega> N \\<mu>) = sigma_sets \\<Omega> N\"\n    using B by (rule sets_measure_of)\n  from this assms show ?thesis by (rule measurable_sigma_sets)\nqed\n\nlemma measurable_iff_measure_of:\n  assumes \"N \\<subseteq> Pow \\<Omega>\" \"f \\<in> space M \\<rightarrow> \\<Omega>\"\n  shows \"f \\<in> measurable M (measure_of \\<Omega> N \\<mu>) \\<longleftrightarrow> (\\<forall>A\\<in>N. f -` A \\<inter> space M \\<in> sets M)\"\n  by (metis assms in_measure_of measurable_measure_of assms measurable_sets)\n\nlemma measurable_cong_sets:\n  assumes sets: \"sets M = sets M'\" \"sets N = sets N'\"\n  shows \"measurable M N = measurable M' N'\"\n  using sets[THEN sets_eq_imp_space_eq] sets by (simp add: measurable_def)\n\nlemma measurable_cong:\n  assumes \"\\<And> w. w \\<in> space M \\<Longrightarrow> f w = g w\"\n  shows \"f \\<in> measurable M M' \\<longleftrightarrow> g \\<in> measurable M M'\"\n  unfolding measurable_def using assms\n  by (simp cong: vimage_inter_cong Pi_cong)\n\nlemma measurable_cong_strong:\n  \"M = N \\<Longrightarrow> M' = N' \\<Longrightarrow> (\\<And>w. w \\<in> space M \\<Longrightarrow> f w = g w) \\<Longrightarrow>\n    f \\<in> measurable M M' \\<longleftrightarrow> g \\<in> measurable N N'\"\n  by (metis measurable_cong)\n\nlemma measurable_compose:\n  assumes f: \"f \\<in> measurable M N\" and g: \"g \\<in> measurable N L\"\n  shows \"(\\<lambda>x. g (f x)) \\<in> measurable M L\"\nproof -\n  have \"\\<And>A. (\\<lambda>x. g (f x)) -` A \\<inter> space M = f -` (g -` A \\<inter> space N) \\<inter> space M\"\n    using measurable_space[OF f] by auto\n  with measurable_space[OF f] measurable_space[OF g] show ?thesis\n    by (auto intro: measurable_sets[OF f] measurable_sets[OF g]\n             simp del: vimage_Int simp add: measurable_def)\nqed\n\nlemma measurable_comp:\n  \"f \\<in> measurable M N \\<Longrightarrow> g \\<in> measurable N L \\<Longrightarrow> g \\<circ> f \\<in> measurable M L\"\n  using measurable_compose[of f M N g L] by (simp add: comp_def)\n\nlemma measurable_const:\n  \"c \\<in> space M' \\<Longrightarrow> (\\<lambda>x. c) \\<in> measurable M M'\"\n  by (auto simp add: measurable_def)\n\nlemma measurable_If:\n  assumes measure: \"f \\<in> measurable M M'\" \"g \\<in> measurable M M'\"\n  assumes P: \"{x\\<in>space M. P x} \\<in> sets M\"\n  shows \"(\\<lambda>x. if P x then f x else g x) \\<in> measurable M M'\"\n  unfolding measurable_def\nproof safe\n  fix x assume \"x \\<in> space M\"\n  thus \"(if P x then f x else g x) \\<in> space M'\"\n    using measure unfolding measurable_def by auto\nnext\n  fix A assume \"A \\<in> sets M'\"\n  hence *: \"(\\<lambda>x. if P x then f x else g x) -` A \\<inter> space M =\n    ((f -` A \\<inter> space M) \\<inter> {x\\<in>space M. P x}) \\<union>\n    ((g -` A \\<inter> space M) \\<inter> (space M - {x\\<in>space M. P x}))\"\n    using measure unfolding measurable_def by (auto split: split_if_asm)\n  show \"(\\<lambda>x. if P x then f x else g x) -` A \\<inter> space M \\<in> sets M\"\n    using `A \\<in> sets M'` measure P unfolding * measurable_def\n    by (auto intro!: sets.Un)\nqed\n\nlemma measurable_If_set:\n  assumes measure: \"f \\<in> measurable M M'\" \"g \\<in> measurable M M'\"\n  assumes P: \"A \\<inter> space M \\<in> sets M\"\n  shows \"(\\<lambda>x. if x \\<in> A then f x else g x) \\<in> measurable M M'\"\nproof (rule measurable_If[OF measure])\n  have \"{x \\<in> space M. x \\<in> A} = A \\<inter> space M\" by auto\n  thus \"{x \\<in> space M. x \\<in> A} \\<in> sets M\" using `A \\<inter> space M \\<in> sets M` by auto\nqed\n\nlemma measurable_ident: \"id \\<in> measurable M M\"\n  by (auto simp add: measurable_def)\n\nlemma measurable_id: \"(\\<lambda>x. x) \\<in> measurable M M\"\n  by (simp add: measurable_def)\n\nlemma measurable_ident_sets:\n  assumes eq: \"sets M = sets M'\" shows \"(\\<lambda>x. x) \\<in> measurable M M'\"\n  using measurable_ident[of M]\n  unfolding id_def measurable_def eq sets_eq_imp_space_eq[OF eq] .\n\nlemma sets_Least:\n  assumes meas: \"\\<And>i::nat. {x\\<in>space M. P i x} \\<in> M\"\n  shows \"(\\<lambda>x. LEAST j. P j x) -` A \\<inter> space M \\<in> sets M\"\nproof -\n  { fix i have \"(\\<lambda>x. LEAST j. P j x) -` {i} \\<inter> space M \\<in> sets M\"\n    proof cases\n      assume i: \"(LEAST j. False) = i\"\n      have \"(\\<lambda>x. LEAST j. P j x) -` {i} \\<inter> space M =\n        {x\\<in>space M. P i x} \\<inter> (space M - (\\<Union>j<i. {x\\<in>space M. P j x})) \\<union> (space M - (\\<Union>i. {x\\<in>space M. P i x}))\"\n        by (simp add: set_eq_iff, safe)\n           (insert i, auto dest: Least_le intro: LeastI intro!: Least_equality)\n      with meas show ?thesis\n        by (auto intro!: sets.Int)\n    next\n      assume i: \"(LEAST j. False) \\<noteq> i\"\n      then have \"(\\<lambda>x. LEAST j. P j x) -` {i} \\<inter> space M =\n        {x\\<in>space M. P i x} \\<inter> (space M - (\\<Union>j<i. {x\\<in>space M. P j x}))\"\n      proof (simp add: set_eq_iff, safe)\n        fix x assume neq: \"(LEAST j. False) \\<noteq> (LEAST j. P j x)\"\n        have \"\\<exists>j. P j x\"\n          by (rule ccontr) (insert neq, auto)\n        then show \"P (LEAST j. P j x) x\" by (rule LeastI_ex)\n      qed (auto dest: Least_le intro!: Least_equality)\n      with meas show ?thesis\n        by auto\n    qed }\n  then have \"(\\<Union>i\\<in>A. (\\<lambda>x. LEAST j. P j x) -` {i} \\<inter> space M) \\<in> sets M\"\n    by (intro sets.countable_UN) auto\n  moreover have \"(\\<Union>i\\<in>A. (\\<lambda>x. LEAST j. P j x) -` {i} \\<inter> space M) =\n    (\\<lambda>x. LEAST j. P j x) -` A \\<inter> space M\" by auto\n  ultimately show ?thesis by auto\nqed\n\nlemma measurable_strong:\n  fixes f :: \"'a \\<Rightarrow> 'b\" and g :: \"'b \\<Rightarrow> 'c\"\n  assumes f: \"f \\<in> measurable a b\" and g: \"g \\<in> space b \\<rightarrow> space c\"\n      and t: \"f ` (space a) \\<subseteq> t\"\n      and cb: \"\\<And>s. s \\<in> sets c \\<Longrightarrow> (g -` s) \\<inter> t \\<in> sets b\"\n  shows \"(g o f) \\<in> measurable a c\"\nproof -\n  have fab: \"f \\<in> (space a -> space b)\"\n   and ba: \"\\<And>y. y \\<in> sets b \\<Longrightarrow> (f -` y) \\<inter> (space a) \\<in> sets a\" using f\n     by (auto simp add: measurable_def)\n  have eq: \"\\<And>y. (g \\<circ> f) -` y \\<inter> space a = f -` (g -` y \\<inter> t) \\<inter> space a\" using t\n    by force\n  show ?thesis\n    apply (auto simp add: measurable_def vimage_comp)\n    apply (metis funcset_mem fab g)\n    apply (subst eq)\n    apply (metis ba cb)\n    done\nqed\n\nlemma measurable_discrete_difference:\n  assumes f: \"f \\<in> measurable M N\"\n  assumes X: \"countable X\"\n  assumes sets: \"\\<And>x. x \\<in> X \\<Longrightarrow> {x} \\<in> sets M\"\n  assumes space: \"\\<And>x. x \\<in> X \\<Longrightarrow> g x \\<in> space N\"\n  assumes eq: \"\\<And>x. x \\<in> space M \\<Longrightarrow> x \\<notin> X \\<Longrightarrow> f x = g x\"\n  shows \"g \\<in> measurable M N\"\n  unfolding measurable_def\nproof safe\n  fix x assume \"x \\<in> space M\" then show \"g x \\<in> space N\"\n    using measurable_space[OF f, of x] eq[of x] space[of x] by (cases \"x \\<in> X\") auto\nnext\n  fix S assume S: \"S \\<in> sets N\"\n  have \"g -` S \\<inter> space M = (f -` S \\<inter> space M) - (\\<Union>x\\<in>X. {x}) \\<union> (\\<Union>x\\<in>{x\\<in>X. g x \\<in> S}. {x})\"\n    using sets.sets_into_space[OF sets] eq by auto\n  also have \"\\<dots> \\<in> sets M\"\n    by (safe intro!: sets.Diff sets.Un measurable_sets[OF f] S sets.countable_UN' X countable_Collect sets)\n  finally show \"g -` S \\<inter> space M \\<in> sets M\" .\nqed\n\nlemma measurable_mono1:\n  \"M' \\<subseteq> Pow \\<Omega> \\<Longrightarrow> M \\<subseteq> M' \\<Longrightarrow>\n    measurable (measure_of \\<Omega> M \\<mu>) N \\<subseteq> measurable (measure_of \\<Omega> M' \\<mu>') N\"\n  using measure_of_subset[of M' \\<Omega> M] by (auto simp add: measurable_def)\n\nsubsubsection {* Counting space *}\n\ndefinition count_space :: \"'a set \\<Rightarrow> 'a measure\" where\n  \"count_space \\<Omega> = measure_of \\<Omega> (Pow \\<Omega>) (\\<lambda>A. if finite A then ereal (card A) else \\<infinity>)\"\n\nlemma \n  shows space_count_space[simp]: \"space (count_space \\<Omega>) = \\<Omega>\"\n    and sets_count_space[simp]: \"sets (count_space \\<Omega>) = Pow \\<Omega>\"\n  using sigma_sets_into_sp[of \"Pow \\<Omega>\" \\<Omega>]\n  by (auto simp: count_space_def)\n\nlemma measurable_count_space_eq1[simp]:\n  \"f \\<in> measurable (count_space A) M \\<longleftrightarrow> f \\<in> A \\<rightarrow> space M\"\n unfolding measurable_def by simp\n\nlemma measurable_count_space_eq2:\n  assumes \"finite A\"\n  shows \"f \\<in> measurable M (count_space A) \\<longleftrightarrow> (f \\<in> space M \\<rightarrow> A \\<and> (\\<forall>a\\<in>A. f -` {a} \\<inter> space M \\<in> sets M))\"\nproof -\n  { fix X assume \"X \\<subseteq> A\" \"f \\<in> space M \\<rightarrow> A\"\n    with `finite A` have \"f -` X \\<inter> space M = (\\<Union>a\\<in>X. f -` {a} \\<inter> space M)\" \"finite X\"\n      by (auto dest: finite_subset)\n    moreover assume \"\\<forall>a\\<in>A. f -` {a} \\<inter> space M \\<in> sets M\"\n    ultimately have \"f -` X \\<inter> space M \\<in> sets M\"\n      using `X \\<subseteq> A` by (auto intro!: sets.finite_UN simp del: UN_simps) }\n  then show ?thesis\n    unfolding measurable_def by auto\nqed\n\nlemma measurable_count_space_eq2_countable:\n  fixes f :: \"'a => 'c::countable\"\n  shows \"f \\<in> measurable M (count_space A) \\<longleftrightarrow> (f \\<in> space M \\<rightarrow> A \\<and> (\\<forall>a\\<in>A. f -` {a} \\<inter> space M \\<in> sets M))\"\nproof -\n  { fix X assume \"X \\<subseteq> A\" \"f \\<in> space M \\<rightarrow> A\"\n    assume *: \"\\<And>a. a\\<in>A \\<Longrightarrow> f -` {a} \\<inter> space M \\<in> sets M\"\n    have \"f -` X \\<inter> space M = (\\<Union>a\\<in>X. f -` {a} \\<inter> space M)\"\n      by auto\n    also have \"\\<dots> \\<in> sets M\"\n      using * `X \\<subseteq> A` by (intro sets.countable_UN) auto\n    finally have \"f -` X \\<inter> space M \\<in> sets M\" . }\n  then show ?thesis\n    unfolding measurable_def by auto\nqed\n\nlemma measurable_compose_countable':\n  assumes f: \"\\<And>i. i \\<in> I \\<Longrightarrow> (\\<lambda>x. f i x) \\<in> measurable M N\"\n  and g: \"g \\<in> measurable M (count_space I)\" and I: \"countable I\"\n  shows \"(\\<lambda>x. f (g x) x) \\<in> measurable M N\"\n  unfolding measurable_def\nproof safe\n  fix x assume \"x \\<in> space M\" then show \"f (g x) x \\<in> space N\"\n    using measurable_space[OF f] g[THEN measurable_space] by auto\nnext\n  fix A assume A: \"A \\<in> sets N\"\n  have \"(\\<lambda>x. f (g x) x) -` A \\<inter> space M = (\\<Union>i\\<in>I. (g -` {i} \\<inter> space M) \\<inter> (f i -` A \\<inter> space M))\"\n    using measurable_space[OF g] by auto\n  also have \"\\<dots> \\<in> sets M\" using f[THEN measurable_sets, OF _ A] g[THEN measurable_sets]\n    apply (auto intro!: sets.countable_UN' measurable_sets I)\n    apply (rule sets.Int)\n    apply auto\n    done\n  finally show \"(\\<lambda>x. f (g x) x) -` A \\<inter> space M \\<in> sets M\" .\nqed\n\nlemma measurable_compose_countable:\n  assumes f: \"\\<And>i::'i::countable. (\\<lambda>x. f i x) \\<in> measurable M N\" and g: \"g \\<in> measurable M (count_space UNIV)\"\n  shows \"(\\<lambda>x. f (g x) x) \\<in> measurable M N\"\n  by (rule measurable_compose_countable'[OF assms]) auto\nlemma measurable_count_space_const:\n  \"(\\<lambda>x. c) \\<in> measurable M (count_space UNIV)\"\n  by (simp add: measurable_const)\n\nlemma measurable_count_space:\n  \"f \\<in> measurable (count_space A) (count_space UNIV)\"\n  by simp\n\nlemma measurable_compose_rev:\n  assumes f: \"f \\<in> measurable L N\" and g: \"g \\<in> measurable M L\"\n  shows \"(\\<lambda>x. f (g x)) \\<in> measurable M N\"\n  using measurable_compose[OF g f] .\n\nlemma measurable_count_space_eq_countable:\n  assumes \"countable A\"\n  shows \"f \\<in> measurable M (count_space A) \\<longleftrightarrow> (f \\<in> space M \\<rightarrow> A \\<and> (\\<forall>a\\<in>A. f -` {a} \\<inter> space M \\<in> sets M))\"\nproof -\n  { fix X assume \"X \\<subseteq> A\" \"f \\<in> space M \\<rightarrow> A\"\n    with `countable A` have \"f -` X \\<inter> space M = (\\<Union>a\\<in>X. f -` {a} \\<inter> space M)\" \"countable X\"\n      by (auto dest: countable_subset)\n    moreover assume \"\\<forall>a\\<in>A. f -` {a} \\<inter> space M \\<in> sets M\"\n    ultimately have \"f -` X \\<inter> space M \\<in> sets M\"\n      using `X \\<subseteq> A` by (auto intro!: sets.countable_UN' simp del: UN_simps) }\n  then show ?thesis\n    unfolding measurable_def by auto\nqed\n\nlemma measurable_empty_iff: \n  \"space N = {} \\<Longrightarrow> f \\<in> measurable M N \\<longleftrightarrow> space M = {}\"\n  by (auto simp add: measurable_def Pi_iff)\n\nsubsubsection {* Extend measure *}\n\ndefinition \"extend_measure \\<Omega> I G \\<mu> =\n  (if (\\<exists>\\<mu>'. (\\<forall>i\\<in>I. \\<mu>' (G i) = \\<mu> i) \\<and> measure_space \\<Omega> (sigma_sets \\<Omega> (G`I)) \\<mu>') \\<and> \\<not> (\\<forall>i\\<in>I. \\<mu> i = 0)\n      then measure_of \\<Omega> (G`I) (SOME \\<mu>'. (\\<forall>i\\<in>I. \\<mu>' (G i) = \\<mu> i) \\<and> measure_space \\<Omega> (sigma_sets \\<Omega> (G`I)) \\<mu>')\n      else measure_of \\<Omega> (G`I) (\\<lambda>_. 0))\"\n\nlemma space_extend_measure: \"G ` I \\<subseteq> Pow \\<Omega> \\<Longrightarrow> space (extend_measure \\<Omega> I G \\<mu>) = \\<Omega>\"\n  unfolding extend_measure_def by simp\n\nlemma sets_extend_measure: \"G ` I \\<subseteq> Pow \\<Omega> \\<Longrightarrow> sets (extend_measure \\<Omega> I G \\<mu>) = sigma_sets \\<Omega> (G`I)\"\n  unfolding extend_measure_def by simp\n\nlemma emeasure_extend_measure:\n  assumes M: \"M = extend_measure \\<Omega> I G \\<mu>\"\n    and eq: \"\\<And>i. i \\<in> I \\<Longrightarrow> \\<mu>' (G i) = \\<mu> i\"\n    and ms: \"G ` I \\<subseteq> Pow \\<Omega>\" \"positive (sets M) \\<mu>'\" \"countably_additive (sets M) \\<mu>'\"\n    and \"i \\<in> I\"\n  shows \"emeasure M (G i) = \\<mu> i\"\nproof cases\n  assume *: \"(\\<forall>i\\<in>I. \\<mu> i = 0)\"\n  with M have M_eq: \"M = measure_of \\<Omega> (G`I) (\\<lambda>_. 0)\"\n   by (simp add: extend_measure_def)\n  from measure_space_0[OF ms(1)] ms `i\\<in>I`\n  have \"emeasure M (G i) = 0\"\n    by (intro emeasure_measure_of[OF M_eq]) (auto simp add: M measure_space_def sets_extend_measure)\n  with `i\\<in>I` * show ?thesis\n    by simp\nnext\n  def P \\<equiv> \"\\<lambda>\\<mu>'. (\\<forall>i\\<in>I. \\<mu>' (G i) = \\<mu> i) \\<and> measure_space \\<Omega> (sigma_sets \\<Omega> (G`I)) \\<mu>'\"\n  assume \"\\<not> (\\<forall>i\\<in>I. \\<mu> i = 0)\"\n  moreover\n  have \"measure_space (space M) (sets M) \\<mu>'\"\n    using ms unfolding measure_space_def by auto default\n  with ms eq have \"\\<exists>\\<mu>'. P \\<mu>'\"\n    unfolding P_def\n    by (intro exI[of _ \\<mu>']) (auto simp add: M space_extend_measure sets_extend_measure)\n  ultimately have M_eq: \"M = measure_of \\<Omega> (G`I) (Eps P)\"\n    by (simp add: M extend_measure_def P_def[symmetric])\n\n  from `\\<exists>\\<mu>'. P \\<mu>'` have P: \"P (Eps P)\" by (rule someI_ex)\n  show \"emeasure M (G i) = \\<mu> i\"\n  proof (subst emeasure_measure_of[OF M_eq])\n    have sets_M: \"sets M = sigma_sets \\<Omega> (G`I)\"\n      using M_eq ms by (auto simp: sets_extend_measure)\n    then show \"G i \\<in> sets M\" using `i \\<in> I` by auto\n    show \"positive (sets M) (Eps P)\" \"countably_additive (sets M) (Eps P)\" \"Eps P (G i) = \\<mu> i\"\n      using P `i\\<in>I` by (auto simp add: sets_M measure_space_def P_def)\n  qed fact\nqed\n\nlemma emeasure_extend_measure_Pair:\n  assumes M: \"M = extend_measure \\<Omega> {(i, j). I i j} (\\<lambda>(i, j). G i j) (\\<lambda>(i, j). \\<mu> i j)\"\n    and eq: \"\\<And>i j. I i j \\<Longrightarrow> \\<mu>' (G i j) = \\<mu> i j\"\n    and ms: \"\\<And>i j. I i j \\<Longrightarrow> G i j \\<in> Pow \\<Omega>\" \"positive (sets M) \\<mu>'\" \"countably_additive (sets M) \\<mu>'\"\n    and \"I i j\"\n  shows \"emeasure M (G i j) = \\<mu> i j\"\n  using emeasure_extend_measure[OF M _ _ ms(2,3), of \"(i,j)\"] eq ms(1) `I i j`\n  by (auto simp: subset_eq)\n\nsubsubsection {* Supremum of a set of $\\sigma$-algebras *}\n\ndefinition \"Sup_sigma M = sigma (\\<Union>x\\<in>M. space x) (\\<Union>x\\<in>M. sets x)\"\n\nsyntax\n  \"_SUP_sigma\"   :: \"pttrn \\<Rightarrow> 'a set \\<Rightarrow> 'b \\<Rightarrow> 'b\"  (\"(3\\<Squnion>\\<^sub>\\<sigma> _\\<in>_./ _)\" [0, 0, 10] 10)\n\ntranslations\n  \"\\<Squnion>\\<^sub>\\<sigma> x\\<in>A. B\"   == \"CONST Sup_sigma ((\\<lambda>x. B) ` A)\"\n\nlemma space_Sup_sigma: \"space (Sup_sigma M) = (\\<Union>x\\<in>M. space x)\"\n  unfolding Sup_sigma_def by (rule space_measure_of) (auto dest: sets.sets_into_space)\n\nlemma sets_Sup_sigma: \"sets (Sup_sigma M) = sigma_sets (\\<Union>x\\<in>M. space x) (\\<Union>x\\<in>M. sets x)\"\n  unfolding Sup_sigma_def by (rule sets_measure_of) (auto dest: sets.sets_into_space)\n\nlemma in_Sup_sigma: \"m \\<in> M \\<Longrightarrow> A \\<in> sets m \\<Longrightarrow> A \\<in> sets (Sup_sigma M)\"\n  unfolding sets_Sup_sigma by auto\n\nlemma SUP_sigma_cong: \n  assumes *: \"\\<And>i. i \\<in> I \\<Longrightarrow> sets (M i) = sets (N i)\" shows \"sets (\\<Squnion>\\<^sub>\\<sigma> i\\<in>I. M i) = sets (\\<Squnion>\\<^sub>\\<sigma> i\\<in>I. N i)\"\n  using * sets_eq_imp_space_eq[OF *] by (simp add: Sup_sigma_def)\n\nlemma sets_Sup_in_sets: \n  assumes \"M \\<noteq> {}\"\n  assumes \"\\<And>m. m \\<in> M \\<Longrightarrow> space m = space N\"\n  assumes \"\\<And>m. m \\<in> M \\<Longrightarrow> sets m \\<subseteq> sets N\"\n  shows \"sets (Sup_sigma M) \\<subseteq> sets N\"\nproof -\n  have *: \"UNION M space = space N\"\n    using assms by auto\n  show ?thesis\n    unfolding sets_Sup_sigma * using assms by (auto intro!: sets.sigma_sets_subset)\nqed\n\nlemma measurable_Sup_sigma1:\n  assumes m: \"m \\<in> M\" and f: \"f \\<in> measurable m N\"\n    and const_space: \"\\<And>m n. m \\<in> M \\<Longrightarrow> n \\<in> M \\<Longrightarrow> space m = space n\"\n  shows \"f \\<in> measurable (Sup_sigma M) N\"\nproof -\n  have \"space (Sup_sigma M) = space m\"\n    using m by (auto simp add: space_Sup_sigma dest: const_space)\n  then show ?thesis\n    using m f unfolding measurable_def by (auto intro: in_Sup_sigma)\nqed\n\nlemma measurable_Sup_sigma2:\n  assumes M: \"M \\<noteq> {}\"\n  assumes f: \"\\<And>m. m \\<in> M \\<Longrightarrow> f \\<in> measurable N m\"\n  shows \"f \\<in> measurable N (Sup_sigma M)\"\n  unfolding Sup_sigma_def\nproof (rule measurable_measure_of)\n  show \"f \\<in> space N \\<rightarrow> UNION M space\"\n    using measurable_space[OF f] M by auto\nqed (auto intro: measurable_sets f dest: sets.sets_into_space)\n\nlemma Sup_sigma_sigma:\n  assumes [simp]: \"M \\<noteq> {}\" and M: \"\\<And>m. m \\<in> M \\<Longrightarrow> m \\<subseteq> Pow \\<Omega>\"\n  shows \"(\\<Squnion>\\<^sub>\\<sigma> m\\<in>M. sigma \\<Omega> m) = sigma \\<Omega> (\\<Union>M)\"\nproof (rule measure_eqI)\n  { fix a m assume \"a \\<in> sigma_sets \\<Omega> m\" \"m \\<in> M\"\n    then have \"a \\<in> sigma_sets \\<Omega> (\\<Union>M)\"\n     by induction (auto intro: sigma_sets.intros) }\n  then show \"sets (\\<Squnion>\\<^sub>\\<sigma> m\\<in>M. sigma \\<Omega> m) = sets (sigma \\<Omega> (\\<Union>M))\"\n    apply (simp add: sets_Sup_sigma space_measure_of_conv M Union_least)\n    apply (rule sigma_sets_eqI)\n    apply auto\n    done\nqed (simp add: Sup_sigma_def emeasure_sigma)\n\nlemma SUP_sigma_sigma:\n  assumes M: \"M \\<noteq> {}\" \"\\<And>m. m \\<in> M \\<Longrightarrow> f m \\<subseteq> Pow \\<Omega>\"\n  shows \"(\\<Squnion>\\<^sub>\\<sigma> m\\<in>M. sigma \\<Omega> (f m)) = sigma \\<Omega> (\\<Union>m\\<in>M. f m)\"\nproof -\n  have \"Sup_sigma (sigma \\<Omega> ` f ` M) = sigma \\<Omega> (\\<Union>(f ` M))\"\n    using M by (intro Sup_sigma_sigma) auto\n  then show ?thesis\n    by (simp add: image_image)\nqed\n\nsubsection {* The smallest $\\sigma$-algebra regarding a function *}\n\ndefinition\n  \"vimage_algebra X f M = sigma X {f -` A \\<inter> X | A. A \\<in> sets M}\"\n\nlemma space_vimage_algebra[simp]: \"space (vimage_algebra X f M) = X\"\n  unfolding vimage_algebra_def by (rule space_measure_of) auto\n\nlemma sets_vimage_algebra: \"sets (vimage_algebra X f M) = sigma_sets X {f -` A \\<inter> X | A. A \\<in> sets M}\"\n  unfolding vimage_algebra_def by (rule sets_measure_of) auto\n\nlemma sets_vimage_algebra2:\n  \"f \\<in> X \\<rightarrow> space M \\<Longrightarrow> sets (vimage_algebra X f M) = {f -` A \\<inter> X | A. A \\<in> sets M}\"\n  using sigma_sets_vimage_commute[of f X \"space M\" \"sets M\"]\n  unfolding sets_vimage_algebra sets.sigma_sets_eq by simp\n\nlemma sets_vimage_algebra_cong: \"sets M = sets N \\<Longrightarrow> sets (vimage_algebra X f M) = sets (vimage_algebra X f N)\"\n  by (simp add: sets_vimage_algebra)\n\nlemma vimage_algebra_cong:\n  assumes \"X = Y\"\n  assumes \"\\<And>x. x \\<in> Y \\<Longrightarrow> f x = g x\"\n  assumes \"sets M = sets N\"\n  shows \"vimage_algebra X f M = vimage_algebra Y g N\"\n  by (auto simp: vimage_algebra_def assms intro!: arg_cong2[where f=sigma])\n\nlemma in_vimage_algebra: \"A \\<in> sets M \\<Longrightarrow> f -` A \\<inter> X \\<in> sets (vimage_algebra X f M)\"\n  by (auto simp: vimage_algebra_def)\n\nlemma sets_image_in_sets:\n  assumes N: \"space N = X\"\n  assumes f: \"f \\<in> measurable N M\"\n  shows \"sets (vimage_algebra X f M) \\<subseteq> sets N\"\n  unfolding sets_vimage_algebra N[symmetric]\n  by (rule sets.sigma_sets_subset) (auto intro!: measurable_sets f)\n\nlemma measurable_vimage_algebra1: \"f \\<in> X \\<rightarrow> space M \\<Longrightarrow> f \\<in> measurable (vimage_algebra X f M) M\"\n  unfolding measurable_def by (auto intro: in_vimage_algebra)\n\nlemma measurable_vimage_algebra2:\n  assumes g: \"g \\<in> space N \\<rightarrow> X\" and f: \"(\\<lambda>x. f (g x)) \\<in> measurable N M\"\n  shows \"g \\<in> measurable N (vimage_algebra X f M)\"\n  unfolding vimage_algebra_def\nproof (rule measurable_measure_of)\n  fix A assume \"A \\<in> {f -` A \\<inter> X | A. A \\<in> sets M}\"\n  then obtain Y where Y: \"Y \\<in> sets M\" and A: \"A = f -` Y \\<inter> X\"\n    by auto\n  then have \"g -` A \\<inter> space N = (\\<lambda>x. f (g x)) -` Y \\<inter> space N\"\n    using g by auto\n  also have \"\\<dots> \\<in> sets N\"\n    using f Y by (rule measurable_sets)\n  finally show \"g -` A \\<inter> space N \\<in> sets N\" .\nqed (insert g, auto)\n\nlemma vimage_algebra_sigma:\n  assumes X: \"X \\<subseteq> Pow \\<Omega>'\" and f: \"f \\<in> \\<Omega> \\<rightarrow> \\<Omega>'\"\n  shows \"vimage_algebra \\<Omega> f (sigma \\<Omega>' X) = sigma \\<Omega> {f -` A \\<inter> \\<Omega> | A. A \\<in> X }\" (is \"?V = ?S\")\nproof (rule measure_eqI)\n  have \\<Omega>: \"{f -` A \\<inter> \\<Omega> |A. A \\<in> X} \\<subseteq> Pow \\<Omega>\" by auto\n  show \"sets ?V = sets ?S\"\n    using sigma_sets_vimage_commute[OF f, of X]\n    by (simp add: space_measure_of_conv f sets_vimage_algebra2 \\<Omega> X)\nqed (simp add: vimage_algebra_def emeasure_sigma)\n\nlemma vimage_algebra_vimage_algebra_eq:\n  assumes *: \"f \\<in> X \\<rightarrow> Y\" \"g \\<in> Y \\<rightarrow> space M\"\n  shows \"vimage_algebra X f (vimage_algebra Y g M) = vimage_algebra X (\\<lambda>x. g (f x)) M\"\n    (is \"?VV = ?V\")\nproof (rule measure_eqI)\n  have \"(\\<lambda>x. g (f x)) \\<in> X \\<rightarrow> space M\" \"\\<And>A. A \\<inter> f -` Y \\<inter> X = A \\<inter> X\"\n    using * by auto\n  with * show \"sets ?VV = sets ?V\"\n    by (simp add: sets_vimage_algebra2 ex_simps[symmetric] vimage_comp comp_def del: ex_simps)\nqed (simp add: vimage_algebra_def emeasure_sigma)\n\nlemma sets_vimage_Sup_eq:\n  assumes *: \"M \\<noteq> {}\" \"\\<And>m. m \\<in> M \\<Longrightarrow> f \\<in> X \\<rightarrow> space m\"\n  shows \"sets (vimage_algebra X f (Sup_sigma M)) = sets (\\<Squnion>\\<^sub>\\<sigma> m \\<in> M. vimage_algebra X f m)\"\n  (is \"?IS = ?SI\")\nproof\n  show \"?IS \\<subseteq> ?SI\"\n    by (intro sets_image_in_sets measurable_Sup_sigma2 measurable_Sup_sigma1)\n       (auto simp: space_Sup_sigma measurable_vimage_algebra1 *)\n  { fix m assume \"m \\<in> M\"\n    moreover then have \"f \\<in> X \\<rightarrow> space (Sup_sigma M)\" \"f \\<in> X \\<rightarrow> space m\"\n      using * by (auto simp: space_Sup_sigma)\n    ultimately have \"f \\<in> measurable (vimage_algebra X f (Sup_sigma M)) m\"\n      by (auto simp add: measurable_def sets_vimage_algebra2 intro: in_Sup_sigma) }\n  then show \"?SI \\<subseteq> ?IS\"\n    by (auto intro!: sets_image_in_sets sets_Sup_in_sets del: subsetI simp: *)\nqed\n\nlemma vimage_algebra_Sup_sigma:\n  assumes [simp]: \"MM \\<noteq> {}\" and \"\\<And>M. M \\<in> MM \\<Longrightarrow> f \\<in> X \\<rightarrow> space M\"\n  shows \"vimage_algebra X f (Sup_sigma MM) = Sup_sigma (vimage_algebra X f ` MM)\"\nproof (rule measure_eqI)\n  show \"sets (vimage_algebra X f (Sup_sigma MM)) = sets (Sup_sigma (vimage_algebra X f ` MM))\"\n    using assms by (rule sets_vimage_Sup_eq)\nqed (simp add: vimage_algebra_def Sup_sigma_def emeasure_sigma)\n\nsubsubsection {* Restricted Space Sigma Algebra *}\n\ndefinition restrict_space where\n  \"restrict_space M \\<Omega> = measure_of (\\<Omega> \\<inter> space M) ((op \\<inter> \\<Omega>) ` sets M) (emeasure M)\"\n\nlemma space_restrict_space: \"space (restrict_space M \\<Omega>) = \\<Omega> \\<inter> space M\"\n  using sets.sets_into_space unfolding restrict_space_def by (subst space_measure_of) auto\n\nlemma space_restrict_space2: \"\\<Omega> \\<in> sets M \\<Longrightarrow> space (restrict_space M \\<Omega>) = \\<Omega>\"\n  by (simp add: space_restrict_space sets.sets_into_space)\n\nlemma sets_restrict_space: \"sets (restrict_space M \\<Omega>) = (op \\<inter> \\<Omega>) ` sets M\"\n  unfolding restrict_space_def\nproof (subst sets_measure_of)\n  show \"op \\<inter> \\<Omega> ` sets M \\<subseteq> Pow (\\<Omega> \\<inter> space M)\"\n    by (auto dest: sets.sets_into_space)\n  have \"sigma_sets (\\<Omega> \\<inter> space M) {((\\<lambda>x. x) -` X) \\<inter> (\\<Omega> \\<inter> space M) | X. X \\<in> sets M} =\n    (\\<lambda>X. X \\<inter> (\\<Omega> \\<inter> space M)) ` sets M\"\n    by (subst sigma_sets_vimage_commute[symmetric, where \\<Omega>' = \"space M\"])\n       (auto simp add: sets.sigma_sets_eq)\n  moreover have \"{((\\<lambda>x. x) -` X) \\<inter> (\\<Omega> \\<inter> space M) | X. X \\<in> sets M} = (\\<lambda>X. X \\<inter> (\\<Omega> \\<inter> space M)) `  sets M\"\n    by auto\n  moreover have \"(\\<lambda>X. X \\<inter> (\\<Omega> \\<inter> space M)) `  sets M = (op \\<inter> \\<Omega>) ` sets M\"\n    by (intro image_cong) (auto dest: sets.sets_into_space)\n  ultimately show \"sigma_sets (\\<Omega> \\<inter> space M) (op \\<inter> \\<Omega> ` sets M) = op \\<inter> \\<Omega> ` sets M\"\n    by simp\nqed\n\nlemma sets_restrict_space_iff:\n  \"\\<Omega> \\<inter> space M \\<in> sets M \\<Longrightarrow> A \\<in> sets (restrict_space M \\<Omega>) \\<longleftrightarrow> (A \\<subseteq> \\<Omega> \\<and> A \\<in> sets M)\"\nproof (subst sets_restrict_space, safe)\n  fix A assume \"\\<Omega> \\<inter> space M \\<in> sets M\" and A: \"A \\<in> sets M\"\n  then have \"(\\<Omega> \\<inter> space M) \\<inter> A \\<in> sets M\"\n    by rule\n  also have \"(\\<Omega> \\<inter> space M) \\<inter> A = \\<Omega> \\<inter> A\"\n    using sets.sets_into_space[OF A] by auto\n  finally show \"\\<Omega> \\<inter> A \\<in> sets M\"\n    by auto\nqed auto\n\nlemma sets_restrict_space_cong: \"sets M = sets N \\<Longrightarrow> sets (restrict_space M \\<Omega>) = sets (restrict_space N \\<Omega>)\"\n  by (simp add: sets_restrict_space)\n\nlemma restrict_space_eq_vimage_algebra:\n  \"\\<Omega> \\<subseteq> space M \\<Longrightarrow> sets (restrict_space M \\<Omega>) = sets (vimage_algebra \\<Omega> (\\<lambda>x. x) M)\"\n  unfolding restrict_space_def\n  apply (subst sets_measure_of)\n  apply (auto simp add: image_subset_iff dest: sets.sets_into_space) []\n  apply (auto simp add: sets_vimage_algebra intro!: arg_cong2[where f=sigma_sets])\n  done\n\nlemma sets_Collect_restrict_space_iff: \n  assumes \"S \\<in> sets M\"\n  shows \"{x\\<in>space (restrict_space M S). P x} \\<in> sets (restrict_space M S) \\<longleftrightarrow> {x\\<in>space M. x \\<in> S \\<and> P x} \\<in> sets M\"\nproof -\n  have \"{x\\<in>S. P x} = {x\\<in>space M. x \\<in> S \\<and> P x}\"\n    using sets.sets_into_space[OF assms] by auto\n  then show ?thesis\n    by (subst sets_restrict_space_iff) (auto simp add: space_restrict_space assms)\nqed\n\nlemma measurable_restrict_space1:\n  assumes \\<Omega>: \"\\<Omega> \\<inter> space M \\<in> sets M\" and f: \"f \\<in> measurable M N\"\n  shows \"f \\<in> measurable (restrict_space M \\<Omega>) N\"\n  unfolding measurable_def\nproof (intro CollectI conjI ballI)\n  show sp: \"f \\<in> space (restrict_space M \\<Omega>) \\<rightarrow> space N\"\n    using measurable_space[OF f] sets.sets_into_space[OF \\<Omega>] by (auto simp: space_restrict_space)\n\n  fix A assume \"A \\<in> sets N\"\n  have \"f -` A \\<inter> space (restrict_space M \\<Omega>) = (f -` A \\<inter> space M) \\<inter> (\\<Omega> \\<inter> space M)\"\n    using sets.sets_into_space[OF \\<Omega>] by (auto simp: space_restrict_space)\n  also have \"\\<dots> \\<in> sets (restrict_space M \\<Omega>)\"\n    unfolding sets_restrict_space_iff[OF \\<Omega>]\n    using measurable_sets[OF f `A \\<in> sets N`] \\<Omega> by blast\n  finally show \"f -` A \\<inter> space (restrict_space M \\<Omega>) \\<in> sets (restrict_space M \\<Omega>)\" .\nqed\n\nlemma measurable_restrict_space2:\n  \"\\<Omega> \\<inter> space N \\<in> sets N \\<Longrightarrow> f \\<in> space M \\<rightarrow> \\<Omega> \\<Longrightarrow> f \\<in> measurable M N \\<Longrightarrow>\n    f \\<in> measurable M (restrict_space N \\<Omega>)\"\n  by (simp add: measurable_def space_restrict_space sets_restrict_space_iff Pi_Int[symmetric])\n\nlemma measurable_restrict_space_iff:\n  assumes \\<Omega>[simp, intro]: \"\\<Omega> \\<inter> space M \\<in> sets M\" \"c \\<in> space N\"\n  shows \"f \\<in> measurable (restrict_space M \\<Omega>) N \\<longleftrightarrow>\n    (\\<lambda>x. if x \\<in> \\<Omega> then f x else c) \\<in> measurable M N\" (is \"f \\<in> measurable ?R N \\<longleftrightarrow> ?f \\<in> measurable M N\")\n  unfolding measurable_def\nproof safe\n  fix x assume \"f \\<in> space ?R \\<rightarrow> space N\" \"x \\<in> space M\" then show \"?f x \\<in> space N\"\n    using `c\\<in>space N` by (auto simp: space_restrict_space)\nnext\n  fix x assume \"?f \\<in> space M \\<rightarrow> space N\" \"x \\<in> space ?R\" then show \"f x \\<in> space N\"\n    using `c\\<in>space N` by (auto simp: space_restrict_space Pi_iff)\nnext\n  fix X assume X: \"X \\<in> sets N\"\n  assume *[THEN bspec]: \"\\<forall>y\\<in>sets N. f -` y \\<inter> space ?R \\<in> sets ?R\"\n  have \"?f -` X \\<inter> space M = (f -` X \\<inter> (\\<Omega> \\<inter> space M)) \\<union> (if c \\<in> X then (space M - (\\<Omega> \\<inter> space M)) else {})\"\n    by (auto split: split_if_asm)\n  also have \"\\<dots> \\<in> sets M\"\n    using *[OF X] by (auto simp add: space_restrict_space sets_restrict_space_iff)\n  finally show \"?f -` X \\<inter> space M \\<in> sets M\" .\nnext\n  assume *[THEN bspec]: \"\\<forall>y\\<in>sets N. ?f -` y \\<inter> space M \\<in> sets M\"\n  fix X :: \"'b set\" assume X: \"X \\<in> sets N\"\n  have \"f -` X \\<inter> (\\<Omega> \\<inter> space M) = (?f -` X \\<inter> space M) \\<inter> (\\<Omega> \\<inter> space M)\"\n    by (auto simp: space_restrict_space)\n  also have \"\\<dots> \\<in> sets M\"\n    using *[OF X] by auto\n  finally show \"f -` X \\<inter> space ?R \\<in> sets ?R\"\n    by (auto simp add: sets_restrict_space_iff space_restrict_space)\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/Probability/Sigma_Algebra.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744850834649, "lm_q2_score": 0.8757869884059266, "lm_q1q2_score": 0.7160210960887738}}
{"text": "(*  Title:      HOL/Algebra/Ideal.thy\n    Author:     Stephan Hohe, TU Muenchen\n*)\n\ntheory Ideal\nimports Ring AbelCoset\nbegin\n\nsection \\<open>Ideals\\<close>\n\nsubsection \\<open>Definitions\\<close>\n\nsubsubsection \\<open>General definition\\<close>\n\nlocale ideal = additive_subgroup I R + ring R for I and R (structure) +\n  assumes I_l_closed: \"\\<lbrakk>a \\<in> I; x \\<in> carrier R\\<rbrakk> \\<Longrightarrow> x \\<otimes> a \\<in> I\"\n      and I_r_closed: \"\\<lbrakk>a \\<in> I; x \\<in> carrier R\\<rbrakk> \\<Longrightarrow> a \\<otimes> x \\<in> I\"\n\nsublocale ideal \\<subseteq> abelian_subgroup I R\nproof (intro abelian_subgroupI3 abelian_group.intro)\n  show \"additive_subgroup I R\"\n    by (simp add: is_additive_subgroup)\n  show \"abelian_monoid R\"\n    by (simp add: abelian_monoid_axioms)\n  show \"abelian_group_axioms R\"\n    using abelian_group_def is_abelian_group by blast\nqed\n\nlemma (in ideal) is_ideal: \"ideal I R\"\n  by (rule ideal_axioms)\n\nlemma idealI:\n  fixes R (structure)\n  assumes \"ring R\"\n  assumes a_subgroup: \"subgroup I (add_monoid R)\"\n    and I_l_closed: \"\\<And>a x. \\<lbrakk>a \\<in> I; x \\<in> carrier R\\<rbrakk> \\<Longrightarrow> x \\<otimes> a \\<in> I\"\n    and I_r_closed: \"\\<And>a x. \\<lbrakk>a \\<in> I; x \\<in> carrier R\\<rbrakk> \\<Longrightarrow> a \\<otimes> x \\<in> I\"\n  shows \"ideal I R\"\nproof -\n  interpret ring R by fact\n  show ?thesis  \n    by (auto simp: ideal.intro ideal_axioms.intro additive_subgroupI a_subgroup ring_axioms I_l_closed I_r_closed)\nqed\n\n\nsubsubsection (in ring) \\<open>Ideals Generated by a Subset of @{term \"carrier R\"}\\<close>\n\ndefinition genideal :: \"_ \\<Rightarrow> 'a set \\<Rightarrow> 'a set\"  (\"Idl\\<index> _\" [80] 79)\n  where \"genideal R S = \\<Inter>{I. ideal I R \\<and> S \\<subseteq> I}\"\n\nsubsubsection \\<open>Principal Ideals\\<close>\n\nlocale principalideal = ideal +\n  assumes generate: \"\\<exists>i \\<in> carrier R. I = Idl {i}\"\n\nlemma (in principalideal) is_principalideal: \"principalideal I R\"\n  by (rule principalideal_axioms)\n\nlemma principalidealI:\n  fixes R (structure)\n  assumes \"ideal I R\"\n    and generate: \"\\<exists>i \\<in> carrier R. I = Idl {i}\"\n  shows \"principalideal I R\"\nproof -\n  interpret ideal I R by fact\n  show ?thesis\n    by (intro principalideal.intro principalideal_axioms.intro)\n      (rule is_ideal, rule generate)\nqed\n\n(* NEW ====== *)\nlemma (in ideal) rcos_const_imp_mem:\n  assumes \"i \\<in> carrier R\" and \"I +> i = I\" shows \"i \\<in> I\"\n  using additive_subgroup.zero_closed[OF ideal.axioms(1)[OF ideal_axioms]] assms\n  by (force simp add: a_r_coset_def')\n(* ========== *)\n\n(* NEW ====== *)\nlemma (in ring) a_rcos_zero:\n  assumes \"ideal I R\" \"i \\<in> I\" shows \"I +> i = I\"\n  using abelian_subgroupI3[OF ideal.axioms(1) is_abelian_group]\n  by (simp add: abelian_subgroup.a_rcos_const assms)\n(* ========== *)\n\n(* NEW ====== *)\nlemma (in ring) ideal_is_normal:\n  assumes \"ideal I R\" shows \"I \\<lhd> (add_monoid R)\"\n  using abelian_subgroup.a_normal[OF abelian_subgroupI3[OF ideal.axioms(1)]]\n        abelian_group_axioms assms\n  by auto \n(* ========== *)\n\n(* NEW ====== *)\nlemma (in ideal) a_rcos_sum:\n  assumes \"a \\<in> carrier R\" and \"b \\<in> carrier R\" shows \"(I +> a) <+> (I +> b) = I +> (a \\<oplus> b)\"\n  using normal.rcos_sum[OF ideal_is_normal[OF ideal_axioms]] assms\n  unfolding set_add_def a_r_coset_def by simp\n(* ========== *)\n\n(* NEW ====== *)\nlemma (in ring) set_add_comm:\n  assumes \"I \\<subseteq> carrier R\" \"J \\<subseteq> carrier R\" shows \"I <+> J = J <+> I\"\nproof -\n  { fix I J assume \"I \\<subseteq> carrier R\" \"J \\<subseteq> carrier R\" hence \"I <+> J \\<subseteq> J <+> I\"\n      using a_comm unfolding set_add_def' by (auto, blast) }\n  thus ?thesis\n    using assms by auto\nqed\n(* ========== *)\n\n\nsubsubsection \\<open>Maximal Ideals\\<close>\n\nlocale maximalideal = ideal +\n  assumes I_notcarr: \"carrier R \\<noteq> I\"\n    and I_maximal: \"\\<lbrakk>ideal J R; I \\<subseteq> J; J \\<subseteq> carrier R\\<rbrakk> \\<Longrightarrow> (J = I) \\<or> (J = carrier R)\"\n\nlemma (in maximalideal) is_maximalideal: \"maximalideal I R\"\n  by (rule maximalideal_axioms)\n\nlemma maximalidealI:\n  fixes R\n  assumes \"ideal I R\"\n    and I_notcarr: \"carrier R \\<noteq> I\"\n    and I_maximal: \"\\<And>J. \\<lbrakk>ideal J R; I \\<subseteq> J; J \\<subseteq> carrier R\\<rbrakk> \\<Longrightarrow> (J = I) \\<or> (J = carrier R)\"\n  shows \"maximalideal I R\"\nproof -\n  interpret ideal I R by fact\n  show ?thesis\n    by (intro maximalideal.intro maximalideal_axioms.intro)\n      (rule is_ideal, rule I_notcarr, rule I_maximal)\nqed\n\n\nsubsubsection \\<open>Prime Ideals\\<close>\n\nlocale primeideal = ideal + cring +\n  assumes I_notcarr: \"carrier R \\<noteq> I\"\n    and I_prime: \"\\<lbrakk>a \\<in> carrier R; b \\<in> carrier R; a \\<otimes> b \\<in> I\\<rbrakk> \\<Longrightarrow> a \\<in> I \\<or> b \\<in> I\"\n\nlemma (in primeideal) primeideal: \"primeideal I R\"\n  by (rule primeideal_axioms)\n\nlemma primeidealI:\n  fixes R (structure)\n  assumes \"ideal I R\"\n    and \"cring R\"\n    and I_notcarr: \"carrier R \\<noteq> I\"\n    and I_prime: \"\\<And>a b. \\<lbrakk>a \\<in> carrier R; b \\<in> carrier R; a \\<otimes> b \\<in> I\\<rbrakk> \\<Longrightarrow> a \\<in> I \\<or> b \\<in> I\"\n  shows \"primeideal I R\"\nproof -\n  interpret ideal I R by fact\n  interpret cring R by fact\n  show ?thesis\n    by (intro primeideal.intro primeideal_axioms.intro)\n      (rule is_ideal, rule is_cring, rule I_notcarr, rule I_prime)\nqed\n\nlemma primeidealI2:\n  fixes R (structure)\n  assumes \"additive_subgroup I R\"\n    and \"cring R\"\n    and I_l_closed: \"\\<And>a x. \\<lbrakk>a \\<in> I; x \\<in> carrier R\\<rbrakk> \\<Longrightarrow> x \\<otimes> a \\<in> I\"\n    and I_r_closed: \"\\<And>a x. \\<lbrakk>a \\<in> I; x \\<in> carrier R\\<rbrakk> \\<Longrightarrow> a \\<otimes> x \\<in> I\"\n    and I_notcarr: \"carrier R \\<noteq> I\"\n    and I_prime: \"\\<And>a b. \\<lbrakk>a \\<in> carrier R; b \\<in> carrier R; a \\<otimes> b \\<in> I\\<rbrakk> \\<Longrightarrow> a \\<in> I \\<or> b \\<in> I\"\n  shows \"primeideal I R\"\nproof -\n  interpret additive_subgroup I R by fact\n  interpret cring R by fact\n  show ?thesis apply intro_locales\n    apply (intro ideal_axioms.intro)\n    apply (erule (1) I_l_closed)\n    apply (erule (1) I_r_closed)\n    by (simp add: I_notcarr I_prime primeideal_axioms.intro)\nqed\n\n\nsubsection \\<open>Special Ideals\\<close>\n\nlemma (in ring) zeroideal: \"ideal {\\<zero>} R\"\n  by (intro idealI subgroup.intro) (simp_all add: ring_axioms)\n\nlemma (in ring) oneideal: \"ideal (carrier R) R\"\n  by (rule idealI) (auto intro: ring_axioms add.subgroupI)\n\nlemma (in \"domain\") zeroprimeideal: \"primeideal {\\<zero>} R\"\nproof -\n  have \"carrier R \\<noteq> {\\<zero>}\"\n    by (simp add: carrier_one_not_zero)\n  then show ?thesis\n    by (metis (no_types, lifting) domain_axioms domain_def integral primeidealI singleton_iff zeroideal)\nqed\n\n\nsubsection \\<open>General Ideal Properies\\<close>\n\nlemma (in ideal) one_imp_carrier:\n  assumes I_one_closed: \"\\<one> \\<in> I\"\n  shows \"I = carrier R\"\nproof\n  show \"carrier R \\<subseteq> I\"\n    using I_r_closed assms by fastforce\n  show \"I \\<subseteq> carrier R\"\n    by (rule a_subset)\nqed\n\nlemma (in ideal) Icarr:\n  assumes iI: \"i \\<in> I\"\n  shows \"i \\<in> carrier R\"\n  using iI by (rule a_Hcarr)\n\n\nsubsection \\<open>Intersection of Ideals\\<close>\n\nparagraph \\<open>Intersection of two ideals\\<close>\ntext \\<open>The intersection of any two ideals is again an ideal in @{term R}\\<close>\n\nlemma (in ring) i_intersect:\n  assumes \"ideal I R\"\n  assumes \"ideal J R\"\n  shows \"ideal (I \\<inter> J) R\"\nproof -\n  interpret ideal I R by fact\n  interpret ideal J R by fact\n  have IJ: \"I \\<inter> J \\<subseteq> carrier R\"\n    by (force simp: a_subset)\n  show ?thesis\n    apply (intro idealI subgroup.intro)\n    apply (simp_all add: IJ ring_axioms I_l_closed assms ideal.I_l_closed ideal.I_r_closed flip: a_inv_def)\n    done\nqed\n\ntext \\<open>The intersection of any Number of Ideals is again an Ideal in @{term R}\\<close>\n\nlemma (in ring) i_Intersect:\n  assumes Sideals: \"\\<And>I. I \\<in> S \\<Longrightarrow> ideal I R\" and notempty: \"S \\<noteq> {}\"\n  shows \"ideal (\\<Inter>S) R\"\nproof -\n  { fix x y J\n    assume \"\\<forall>I\\<in>S. x \\<in> I\" \"\\<forall>I\\<in>S. y \\<in> I\" and JS: \"J \\<in> S\"\n    interpret ideal J R by (rule Sideals[OF JS])\n    have \"x \\<oplus> y \\<in> J\"\n      by (simp add: JS \\<open>\\<forall>I\\<in>S. x \\<in> I\\<close> \\<open>\\<forall>I\\<in>S. y \\<in> I\\<close>) }\n  moreover\n    have \"\\<zero> \\<in> J\" if \"J \\<in> S\" for J\n      by (simp add: that Sideals additive_subgroup.zero_closed ideal.axioms(1)) \n  moreover\n  { fix x J\n    assume \"\\<forall>I\\<in>S. x \\<in> I\" and JS: \"J \\<in> S\"\n    interpret ideal J R by (rule Sideals[OF JS])\n    have \"\\<ominus> x \\<in> J\"\n      by (simp add: JS \\<open>\\<forall>I\\<in>S. x \\<in> I\\<close>) }\n  moreover\n  { fix x y J\n    assume \"\\<forall>I\\<in>S. x \\<in> I\" and ycarr: \"y \\<in> carrier R\" and JS: \"J \\<in> S\"\n    interpret ideal J R by (rule Sideals[OF JS])\n    have \"y \\<otimes> x \\<in> J\" \"x \\<otimes> y \\<in> J\" \n      using I_l_closed I_r_closed JS \\<open>\\<forall>I\\<in>S. x \\<in> I\\<close> ycarr by blast+ }\n  moreover\n  { fix x\n    assume \"\\<forall>I\\<in>S. x \\<in> I\"\n    obtain I0 where I0S: \"I0 \\<in> S\"\n      using notempty by blast\n    interpret ideal I0 R by (rule Sideals[OF I0S])\n    have \"x \\<in> I0\"\n      by (simp add: I0S \\<open>\\<forall>I\\<in>S. x \\<in> I\\<close>) \n    with a_subset have \"x \\<in> carrier R\" by fast }\n  ultimately show ?thesis\n    by unfold_locales (auto simp: Inter_eq simp flip: a_inv_def)\nqed\n\n\nsubsection \\<open>Addition of Ideals\\<close>\n\nlemma (in ring) add_ideals:\n  assumes idealI: \"ideal I R\" and idealJ: \"ideal J R\"\n  shows \"ideal (I <+> J) R\"\nproof (rule ideal.intro)\n  show \"additive_subgroup (I <+> J) R\"\n    by (intro ideal.axioms[OF idealI] ideal.axioms[OF idealJ] add_additive_subgroups)\n  show \"ring R\"\n    by (rule ring_axioms)\n  show \"ideal_axioms (I <+> J) R\"\n  proof -\n    { fix x i j\n      assume xcarr: \"x \\<in> carrier R\" and iI: \"i \\<in> I\" and jJ: \"j \\<in> J\"\n      from xcarr ideal.Icarr[OF idealI iI] ideal.Icarr[OF idealJ jJ]\n      have \"\\<exists>h\\<in>I. \\<exists>k\\<in>J. (i \\<oplus> j) \\<otimes> x = h \\<oplus> k\"\n        by (meson iI ideal.I_r_closed idealJ jJ l_distr local.idealI) }\n    moreover\n    { fix x i j\n      assume xcarr: \"x \\<in> carrier R\" and iI: \"i \\<in> I\" and jJ: \"j \\<in> J\"\n      from xcarr ideal.Icarr[OF idealI iI] ideal.Icarr[OF idealJ jJ]\n      have \"\\<exists>h\\<in>I. \\<exists>k\\<in>J. x \\<otimes> (i \\<oplus> j) = h \\<oplus> k\"\n        by (meson iI ideal.I_l_closed idealJ jJ local.idealI r_distr) }\n    ultimately show \"ideal_axioms (I <+> J) R\"\n      by (intro ideal_axioms.intro) (auto simp: set_add_defs)\n  qed\nqed\n\nsubsection (in ring) \\<open>Ideals generated by a subset of @{term \"carrier R\"}\\<close>\n\ntext \\<open>@{term genideal} generates an ideal\\<close>\nlemma (in ring) genideal_ideal:\n  assumes Scarr: \"S \\<subseteq> carrier R\"\n  shows \"ideal (Idl S) R\"\nunfolding genideal_def\nproof (rule i_Intersect, fast, simp)\n  from oneideal and Scarr\n  show \"\\<exists>I. ideal I R \\<and> S \\<le> I\" by fast\nqed\n\nlemma (in ring) genideal_self:\n  assumes \"S \\<subseteq> carrier R\"\n  shows \"S \\<subseteq> Idl S\"\n  unfolding genideal_def by fast\n\nlemma (in ring) genideal_self':\n  assumes carr: \"i \\<in> carrier R\"\n  shows \"i \\<in> Idl {i}\"\n  by (simp add: genideal_def)\n\ntext \\<open>@{term genideal} generates the minimal ideal\\<close>\nlemma (in ring) genideal_minimal:\n  assumes \"ideal I R\" \"S \\<subseteq> I\"\n  shows \"Idl S \\<subseteq> I\"\n  unfolding genideal_def by rule (elim InterD, simp add: assms)\n\ntext \\<open>Generated ideals and subsets\\<close>\nlemma (in ring) Idl_subset_ideal:\n  assumes Iideal: \"ideal I R\"\n    and Hcarr: \"H \\<subseteq> carrier R\"\n  shows \"(Idl H \\<subseteq> I) = (H \\<subseteq> I)\"\nproof\n  assume a: \"Idl H \\<subseteq> I\"\n  from Hcarr have \"H \\<subseteq> Idl H\" by (rule genideal_self)\n  with a show \"H \\<subseteq> I\" by simp\nnext\n  fix x\n  assume \"H \\<subseteq> I\"\n  with Iideal have \"I \\<in> {I. ideal I R \\<and> H \\<subseteq> I}\" by fast\n  then show \"Idl H \\<subseteq> I\" unfolding genideal_def by fast\nqed\n\nlemma (in ring) subset_Idl_subset:\n  assumes Icarr: \"I \\<subseteq> carrier R\"\n    and HI: \"H \\<subseteq> I\"\n  shows \"Idl H \\<subseteq> Idl I\"\nproof -\n  from Icarr have Iideal: \"ideal (Idl I) R\"\n    by (rule genideal_ideal)\n  from HI and Icarr have \"H \\<subseteq> carrier R\"\n    by fast\n  with Iideal have \"(H \\<subseteq> Idl I) = (Idl H \\<subseteq> Idl I)\"\n    by (rule Idl_subset_ideal[symmetric])\n  then show \"Idl H \\<subseteq> Idl I\"\n    by (meson HI Icarr genideal_self order_trans)\nqed\n\nlemma (in ring) Idl_subset_ideal':\n  assumes acarr: \"a \\<in> carrier R\" and bcarr: \"b \\<in> carrier R\"\n  shows \"Idl {a} \\<subseteq> Idl {b} \\<longleftrightarrow> a \\<in> Idl {b}\"\nproof -\n  have \"Idl {a} \\<subseteq> Idl {b} \\<longleftrightarrow> {a} \\<subseteq> Idl {b}\"\n    by (simp add: Idl_subset_ideal acarr bcarr genideal_ideal)\n  also have \"\\<dots> \\<longleftrightarrow> a \\<in> Idl {b}\"\n    by blast\n  finally show ?thesis .\nqed\n\nlemma (in ring) genideal_zero: \"Idl {\\<zero>} = {\\<zero>}\"\nproof\n  show \"Idl {\\<zero>} \\<subseteq> {\\<zero>}\"\n    by (simp add: genideal_minimal zeroideal)\n  show \"{\\<zero>} \\<subseteq> Idl {\\<zero>}\"\n    by (simp add: genideal_self')\nqed\n\nlemma (in ring) genideal_one: \"Idl {\\<one>} = carrier R\"\nproof -\n  interpret ideal \"Idl {\\<one>}\" \"R\" by (rule genideal_ideal) fast\n  show \"Idl {\\<one>} = carrier R\"\n    using genideal_self' one_imp_carrier by blast\nqed\n\n\ntext \\<open>Generation of Principal Ideals in Commutative Rings\\<close>\n\ndefinition cgenideal :: \"_ \\<Rightarrow> 'a \\<Rightarrow> 'a set\"  (\"PIdl\\<index> _\" [80] 79)\n  where \"cgenideal R a = {x \\<otimes>\\<^bsub>R\\<^esub> a | x. x \\<in> carrier R}\"\n\ntext \\<open>genhideal (?) really generates an ideal\\<close>\nlemma (in cring) cgenideal_ideal:\n  assumes acarr: \"a \\<in> carrier R\"\n  shows \"ideal (PIdl a) R\"\n  unfolding cgenideal_def\nproof (intro subgroup.intro idealI[OF ring_axioms], simp_all)\n  show \"{x \\<otimes> a |x. x \\<in> carrier R} \\<subseteq> carrier R\"\n    by (blast intro: acarr)\n  show \"\\<And>x y. \\<lbrakk>\\<exists>u. x = u \\<otimes> a \\<and> u \\<in> carrier R; \\<exists>x. y = x \\<otimes> a \\<and> x \\<in> carrier R\\<rbrakk>\n              \\<Longrightarrow> \\<exists>v. x \\<oplus> y = v \\<otimes> a \\<and> v \\<in> carrier R\"\n    by (metis assms cring.cring_simprules(1) is_cring l_distr)\n  show \"\\<exists>x. \\<zero> = x \\<otimes> a \\<and> x \\<in> carrier R\"\n    by (metis assms l_null zero_closed)\n  show \"\\<And>x. \\<exists>u. x = u \\<otimes> a \\<and> u \\<in> carrier R \n            \\<Longrightarrow> \\<exists>v. inv\\<^bsub>add_monoid R\\<^esub> x = v \\<otimes> a \\<and> v \\<in> carrier R\"\n    by (metis a_inv_def add.inv_closed assms l_minus)\n  show \"\\<And>b x. \\<lbrakk>\\<exists>x. b = x \\<otimes> a \\<and> x \\<in> carrier R; x \\<in> carrier R\\<rbrakk>\n       \\<Longrightarrow> \\<exists>z. x \\<otimes> b = z \\<otimes> a \\<and> z \\<in> carrier R\"\n    by (metis assms m_assoc m_closed)\n  show \"\\<And>b x. \\<lbrakk>\\<exists>x. b = x \\<otimes> a \\<and> x \\<in> carrier R; x \\<in> carrier R\\<rbrakk>\n       \\<Longrightarrow> \\<exists>z. b \\<otimes> x = z \\<otimes> a \\<and> z \\<in> carrier R\"\n    by (metis assms m_assoc m_comm m_closed)\nqed\n\nlemma (in ring) cgenideal_self:\n  assumes icarr: \"i \\<in> carrier R\"\n  shows \"i \\<in> PIdl i\"\n  unfolding cgenideal_def\nproof simp\n  from icarr have \"i = \\<one> \\<otimes> i\"\n    by simp\n  with icarr show \"\\<exists>x. i = x \\<otimes> i \\<and> x \\<in> carrier R\"\n    by fast\nqed\n\ntext \\<open>@{const \"cgenideal\"} is minimal\\<close>\n\nlemma (in ring) cgenideal_minimal:\n  assumes \"ideal J R\"\n  assumes aJ: \"a \\<in> J\"\n  shows \"PIdl a \\<subseteq> J\"\nproof -\n  interpret ideal J R by fact\n  show ?thesis\n    unfolding cgenideal_def\n    using I_l_closed aJ by blast\nqed\n\nlemma (in cring) cgenideal_eq_genideal:\n  assumes icarr: \"i \\<in> carrier R\"\n  shows \"PIdl i = Idl {i}\"\nproof\n  show \"PIdl i \\<subseteq> Idl {i}\"\n    by (simp add: cgenideal_minimal genideal_ideal genideal_self' icarr)\n  show \"Idl {i} \\<subseteq> PIdl i\"\n    by (simp add: cgenideal_ideal cgenideal_self genideal_minimal icarr)\nqed\n\nlemma (in cring) cgenideal_eq_rcos: \"PIdl i = carrier R #> i\"\n  unfolding cgenideal_def r_coset_def by fast\n\nlemma (in cring) cgenideal_is_principalideal:\n  assumes \"i \\<in> carrier R\"\n  shows \"principalideal (PIdl i) R\"\nproof -\n  have \"\\<exists>i'\\<in>carrier R. PIdl i = Idl {i'}\"\n    using cgenideal_eq_genideal assms by auto\n  then show ?thesis\n    by (simp add: cgenideal_ideal assms principalidealI)\nqed\n\n\nsubsection \\<open>Union of Ideals\\<close>\n\nlemma (in ring) union_genideal:\n  assumes idealI: \"ideal I R\" and idealJ: \"ideal J R\"\n  shows \"Idl (I \\<union> J) = I <+> J\"\nproof\n  show \"Idl (I \\<union> J) \\<subseteq> I <+> J\"\n  proof (rule ring.genideal_minimal [OF ring_axioms])\n    show \"ideal (I <+> J) R\"\n      by (rule add_ideals[OF idealI idealJ])\n    have \"\\<And>x. x \\<in> I \\<Longrightarrow> \\<exists>xa\\<in>I. \\<exists>xb\\<in>J. x = xa \\<oplus> xb\"\n      by (metis additive_subgroup.zero_closed ideal.Icarr idealJ ideal_def local.idealI r_zero)\n    moreover have \"\\<And>x. x \\<in> J \\<Longrightarrow> \\<exists>xa\\<in>I. \\<exists>xb\\<in>J. x = xa \\<oplus> xb\"\n      by (metis additive_subgroup.zero_closed ideal.Icarr idealJ ideal_def l_zero local.idealI)\n    ultimately show \"I \\<union> J \\<subseteq> I <+> J\"\n      by (auto simp: set_add_defs) \n  qed\nnext\n  show \"I <+> J \\<subseteq> Idl (I \\<union> J)\"\n    by (auto simp: set_add_defs genideal_def additive_subgroup.a_closed ideal_def set_mp)\nqed\n\nsubsection \\<open>Properties of Principal Ideals\\<close>\n\ntext \\<open>The zero ideal is a principal ideal\\<close>\ncorollary (in ring) zeropideal: \"principalideal {\\<zero>} R\"\n  using genideal_zero principalidealI zeroideal by blast\n\ntext \\<open>The unit ideal is a principal ideal\\<close>\ncorollary (in ring) onepideal: \"principalideal (carrier R) R\"\n  using genideal_one oneideal principalidealI by blast\n\ntext \\<open>Every principal ideal is a right coset of the carrier\\<close>\nlemma (in principalideal) rcos_generate:\n  assumes \"cring R\"\n  shows \"\\<exists>x\\<in>I. I = carrier R #> x\"\nproof -\n  interpret cring R by fact\n  from generate obtain i where icarr: \"i \\<in> carrier R\" and I1: \"I = Idl {i}\"\n    by fast+\n  then have \"I = PIdl i\"\n    by (simp add: cgenideal_eq_genideal)\n  moreover have \"i \\<in> I\"\n    by (simp add: I1 genideal_self' icarr)\n  moreover have \"PIdl i = carrier R #> i\"\n    unfolding cgenideal_def r_coset_def by fast\n  ultimately show \"\\<exists>x\\<in>I. I = carrier R #> x\"\n    by fast\nqed\n\n\n(* Next lemma contributed by Paulo Em\u00edlio de Vilhena. *)\n\ntext \\<open>This next lemma would be trivial if placed in a theory that imports QuotRing,\n      but it makes more sense to have it here (easier to find and coherent with the\n      previous developments).\\<close>\n\nlemma (in cring) cgenideal_prod:\n  assumes \"a \\<in> carrier R\" \"b \\<in> carrier R\"\n  shows \"(PIdl a) <#> (PIdl b) = PIdl (a \\<otimes> b)\"\nproof -\n  have \"(carrier R #> a) <#> (carrier R #> b) = carrier R #> (a \\<otimes> b)\"\n  proof\n    show \"(carrier R #> a) <#> (carrier R #> b) \\<subseteq> carrier R #> a \\<otimes> b\"\n    proof\n      fix x assume \"x \\<in> (carrier R #> a) <#> (carrier R #> b)\"\n      then obtain r1 r2 where r1: \"r1 \\<in> carrier R\" and r2: \"r2 \\<in> carrier R\"\n                          and \"x = (r1 \\<otimes> a) \\<otimes> (r2 \\<otimes> b)\"\n        unfolding set_mult_def r_coset_def by blast\n      hence \"x = (r1 \\<otimes> r2) \\<otimes> (a \\<otimes> b)\"\n        by (simp add: assms local.ring_axioms m_lcomm ring.ring_simprules(11))\n      thus \"x \\<in> carrier R #> a \\<otimes> b\"\n        unfolding r_coset_def using r1 r2 assms by blast \n    qed\n  next\n    show \"carrier R #> a \\<otimes> b \\<subseteq> (carrier R #> a) <#> (carrier R #> b)\"\n    proof\n      fix x assume \"x \\<in> carrier R #> a \\<otimes> b\"\n      then obtain r where r: \"r \\<in> carrier R\" \"x = r \\<otimes> (a \\<otimes> b)\"\n        unfolding r_coset_def by blast\n      hence \"x = (r \\<otimes> a) \\<otimes> (\\<one> \\<otimes> b)\"\n        using assms by (simp add: m_assoc)\n      thus \"x \\<in> (carrier R #> a) <#> (carrier R #> b)\"\n        unfolding set_mult_def r_coset_def using assms r by blast\n    qed\n  qed\n  thus ?thesis\n    using cgenideal_eq_rcos[of a] cgenideal_eq_rcos[of b] cgenideal_eq_rcos[of \"a \\<otimes> b\"] by simp\nqed\n\n\nsubsection \\<open>Prime Ideals\\<close>\n\nlemma (in ideal) primeidealCD:\n  assumes \"cring R\"\n  assumes notprime: \"\\<not> primeideal I R\"\n  shows \"carrier R = I \\<or> (\\<exists>a b. a \\<in> carrier R \\<and> b \\<in> carrier R \\<and> a \\<otimes> b \\<in> I \\<and> a \\<notin> I \\<and> b \\<notin> I)\"\nproof (rule ccontr, clarsimp)\n  interpret cring R by fact\n  assume InR: \"carrier R \\<noteq> I\"\n    and \"\\<forall>a. a \\<in> carrier R \\<longrightarrow> (\\<forall>b. a \\<otimes> b \\<in> I \\<longrightarrow> b \\<in> carrier R \\<longrightarrow> a \\<in> I \\<or> b \\<in> I)\"\n  then have I_prime: \"\\<And> a b. \\<lbrakk>a \\<in> carrier R; b \\<in> carrier R; a \\<otimes> b \\<in> I\\<rbrakk> \\<Longrightarrow> a \\<in> I \\<or> b \\<in> I\"\n    by simp\n  have \"primeideal I R\"\n    by (simp add: I_prime InR is_cring is_ideal primeidealI)\n  with notprime show False by simp\nqed\n\nlemma (in ideal) primeidealCE:\n  assumes \"cring R\"\n  assumes notprime: \"\\<not> primeideal I R\"\n  obtains \"carrier R = I\"\n    | \"\\<exists>a b. a \\<in> carrier R \\<and> b \\<in> carrier R \\<and> a \\<otimes> b \\<in> I \\<and> a \\<notin> I \\<and> b \\<notin> I\"\nproof -\n  interpret R: cring R by fact\n  assume \"carrier R = I ==> thesis\"\n    and \"\\<exists>a b. a \\<in> carrier R \\<and> b \\<in> carrier R \\<and> a \\<otimes> b \\<in> I \\<and> a \\<notin> I \\<and> b \\<notin> I \\<Longrightarrow> thesis\"\n  then show thesis using primeidealCD [OF R.is_cring notprime] by blast\nqed\n\ntext \\<open>If \\<open>{\\<zero>}\\<close> is a prime ideal of a commutative ring, the ring is a domain\\<close>\nlemma (in cring) zeroprimeideal_domainI:\n  assumes pi: \"primeideal {\\<zero>} R\"\n  shows \"domain R\"\nproof (intro domain.intro is_cring domain_axioms.intro)\n  show \"\\<one> \\<noteq> \\<zero>\"\n    using genideal_one genideal_zero pi primeideal.I_notcarr by force\n  show \"a = \\<zero> \\<or> b = \\<zero>\" if ab: \"a \\<otimes> b = \\<zero>\" and carr: \"a \\<in> carrier R\" \"b \\<in> carrier R\" for a b\n  proof -\n    interpret primeideal \"{\\<zero>}\" \"R\" by (rule pi)\n    show \"a = \\<zero> \\<or> b = \\<zero>\"\n      using I_prime ab carr by blast\n  qed\nqed\n\ncorollary (in cring) domain_eq_zeroprimeideal: \"domain R = primeideal {\\<zero>} R\"\n  using domain.zeroprimeideal zeroprimeideal_domainI by blast\n\n\nsubsection \\<open>Maximal Ideals\\<close>\n\nlemma (in ideal) helper_I_closed:\n  assumes carr: \"a \\<in> carrier R\" \"x \\<in> carrier R\" \"y \\<in> carrier R\"\n    and axI: \"a \\<otimes> x \\<in> I\"\n  shows \"a \\<otimes> (x \\<otimes> y) \\<in> I\"\nproof -\n  from axI and carr have \"(a \\<otimes> x) \\<otimes> y \\<in> I\"\n    by (simp add: I_r_closed)\n  also from carr have \"(a \\<otimes> x) \\<otimes> y = a \\<otimes> (x \\<otimes> y)\"\n    by (simp add: m_assoc)\n  finally show \"a \\<otimes> (x \\<otimes> y) \\<in> I\" .\nqed\n\nlemma (in ideal) helper_max_prime:\n  assumes \"cring R\"\n  assumes acarr: \"a \\<in> carrier R\"\n  shows \"ideal {x\\<in>carrier R. a \\<otimes> x \\<in> I} R\"\nproof -\n  interpret cring R by fact\n  show ?thesis \n  proof (rule idealI, simp_all)\n    show \"ring R\"\n      by (simp add: local.ring_axioms)\n    show \"subgroup {x \\<in> carrier R. a \\<otimes> x \\<in> I} (add_monoid R)\"\n      by (rule subgroup.intro) (auto simp: r_distr acarr r_minus simp flip: a_inv_def)\n    show \"\\<And>b x. \\<lbrakk>b \\<in> carrier R \\<and> a \\<otimes> b \\<in> I; x \\<in> carrier R\\<rbrakk>\n                 \\<Longrightarrow> a \\<otimes> (x \\<otimes> b) \\<in> I\"\n      using acarr helper_I_closed m_comm by auto\n    show \"\\<And>b x. \\<lbrakk>b \\<in> carrier R \\<and> a \\<otimes> b \\<in> I; x \\<in> carrier R\\<rbrakk>\n                \\<Longrightarrow> a \\<otimes> (b \\<otimes> x) \\<in> I\"\n      by (simp add: acarr helper_I_closed)\n  qed\nqed\n\ntext \\<open>In a cring every maximal ideal is prime\\<close>\nlemma (in cring) maximalideal_prime:\n  assumes \"maximalideal I R\"\n  shows \"primeideal I R\"\nproof -\n  interpret maximalideal I R by fact\n  show ?thesis \n  proof (rule ccontr)\n    assume neg: \"\\<not> primeideal I R\"\n    then obtain a b where acarr: \"a \\<in> carrier R\" and bcarr: \"b \\<in> carrier R\"\n      and abI: \"a \\<otimes> b \\<in> I\" and anI: \"a \\<notin> I\" and bnI: \"b \\<notin> I\" \n      using primeidealCE [OF is_cring]\n      by (metis I_notcarr)\n    define J where \"J = {x\\<in>carrier R. a \\<otimes> x \\<in> I}\"\n    from is_cring and acarr have idealJ: \"ideal J R\"\n      unfolding J_def by (rule helper_max_prime)\n    have IsubJ: \"I \\<subseteq> J\"\n      using I_l_closed J_def a_Hcarr acarr by blast\n    from abI and acarr bcarr have \"b \\<in> J\"\n      unfolding J_def by fast\n    with bnI have JnI: \"J \\<noteq> I\" by fast\n    have \"\\<one> \\<notin> J\"\n      unfolding J_def by (simp add: acarr anI)\n    then have Jncarr: \"J \\<noteq> carrier R\" by fast\n    interpret ideal J R by (rule idealJ)    \n    have \"J = I \\<or> J = carrier R\"\n      by (simp add: I_maximal IsubJ a_subset is_ideal)\n    with JnI and Jncarr show False by simp\n  qed\nqed\n\n\nsubsection \\<open>Derived Theorems\\<close>\n\ntext \\<open>A non-zero cring that has only the two trivial ideals is a field\\<close>\nlemma (in cring) trivialideals_fieldI:\n  assumes carrnzero: \"carrier R \\<noteq> {\\<zero>}\"\n    and haveideals: \"{I. ideal I R} = {{\\<zero>}, carrier R}\"\n  shows \"field R\"\nproof (intro cring_fieldI equalityI)\n  show \"Units R \\<subseteq> carrier R - {\\<zero>}\"\n    by (metis Diff_empty Units_closed Units_r_inv_ex carrnzero l_null one_zeroD subsetI subset_Diff_insert)\n  show \"carrier R - {\\<zero>} \\<subseteq> Units R\"\n  proof\n    fix x\n    assume xcarr': \"x \\<in> carrier R - {\\<zero>}\"\n    then have xcarr: \"x \\<in> carrier R\" and xnZ: \"x \\<noteq> \\<zero>\" by auto\n    from xcarr have xIdl: \"ideal (PIdl x) R\"\n      by (intro cgenideal_ideal) fast\n    have \"PIdl x \\<noteq> {\\<zero>}\"\n      using xcarr xnZ cgenideal_self by blast \n    with haveideals have \"PIdl x = carrier R\"\n      by (blast intro!: xIdl)\n    then have \"\\<one> \\<in> PIdl x\" by simp\n    then have \"\\<exists>y. \\<one> = y \\<otimes> x \\<and> y \\<in> carrier R\"\n      unfolding cgenideal_def by blast\n    then obtain y where ycarr: \" y \\<in> carrier R\" and ylinv: \"\\<one> = y \\<otimes> x\"\n      by fast    \n    have \"\\<exists>y \\<in> carrier R. y \\<otimes> x = \\<one> \\<and> x \\<otimes> y = \\<one>\"\n      using m_comm xcarr ycarr ylinv by auto\n    with xcarr show \"x \\<in> Units R\"\n      unfolding Units_def by fast\n  qed\nqed\n\nlemma (in field) all_ideals: \"{I. ideal I R} = {{\\<zero>}, carrier R}\"\nproof (intro equalityI subsetI)\n  fix I\n  assume a: \"I \\<in> {I. ideal I R}\"\n  then interpret ideal I R by simp\n\n  show \"I \\<in> {{\\<zero>}, carrier R}\"\n  proof (cases \"\\<exists>a. a \\<in> I - {\\<zero>}\")\n    case True\n    then obtain a where aI: \"a \\<in> I\" and anZ: \"a \\<noteq> \\<zero>\"\n      by fast+\n    have aUnit: \"a \\<in> Units R\"\n      by (simp add: aI anZ field_Units)\n    then have a: \"a \\<otimes> inv a = \\<one>\" by (rule Units_r_inv)\n    from aI and aUnit have \"a \\<otimes> inv a \\<in> I\"\n      by (simp add: I_r_closed del: Units_r_inv)\n    then have oneI: \"\\<one> \\<in> I\" by (simp add: a[symmetric])\n    have \"carrier R \\<subseteq> I\"\n      using oneI one_imp_carrier by auto\n    with a_subset have \"I = carrier R\" by fast\n    then show \"I \\<in> {{\\<zero>}, carrier R}\" by fast\n  next\n    case False\n    then have IZ: \"\\<And>a. a \\<in> I \\<Longrightarrow> a = \\<zero>\" by simp\n    have a: \"I \\<subseteq> {\\<zero>}\"\n      using False by auto\n    have \"\\<zero> \\<in> I\" by simp\n    with a have \"I = {\\<zero>}\" by fast\n    then show \"I \\<in> {{\\<zero>}, carrier R}\" by fast\n  qed\nqed (auto simp: zeroideal oneideal)\n\n\\<comment>\\<open>\"Jacobson Theorem 2.2\"\\<close>\nlemma (in cring) trivialideals_eq_field:\n  assumes carrnzero: \"carrier R \\<noteq> {\\<zero>}\"\n  shows \"({I. ideal I R} = {{\\<zero>}, carrier R}) = field R\"\n  by (fast intro!: trivialideals_fieldI[OF carrnzero] field.all_ideals)\n\n\ntext \\<open>Like zeroprimeideal for domains\\<close>\nlemma (in field) zeromaximalideal: \"maximalideal {\\<zero>} R\"\nproof (intro maximalidealI zeroideal)\n  from one_not_zero have \"\\<one> \\<notin> {\\<zero>}\" by simp\n  with one_closed show \"carrier R \\<noteq> {\\<zero>}\" by fast\nnext\n  fix J\n  assume Jideal: \"ideal J R\"\n  then have \"J \\<in> {I. ideal I R}\" by fast\n  with all_ideals show \"J = {\\<zero>} \\<or> J = carrier R\"\n    by simp\nqed\n\nlemma (in cring) zeromaximalideal_fieldI:\n  assumes zeromax: \"maximalideal {\\<zero>} R\"\n  shows \"field R\"\nproof (intro trivialideals_fieldI maximalideal.I_notcarr[OF zeromax])\n  have \"J = carrier R\" if Jn0: \"J \\<noteq> {\\<zero>}\" and idealJ: \"ideal J R\" for J\n  proof -\n    interpret ideal J R by (rule idealJ)\n    have \"{\\<zero>} \\<subseteq> J\"\n      by force\n    from zeromax idealJ this a_subset\n    have \"J = {\\<zero>} \\<or> J = carrier R\"\n      by (rule maximalideal.I_maximal)\n    with Jn0 show \"J = carrier R\"\n      by simp\n  qed\n  then show \"{I. ideal I R} = {{\\<zero>}, carrier R}\"\n    by (auto simp: zeroideal oneideal)\nqed\n\nlemma (in cring) zeromaximalideal_eq_field: \"maximalideal {\\<zero>} R = field R\"\n  using field.zeromaximalideal zeromaximalideal_fieldI by blast\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/Ideal.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869948899665, "lm_q2_score": 0.8175744695262777, "lm_q1q2_score": 0.7160210877651771}}
{"text": "(*  Title:      Fun With Functions\n    Author:     Tobias Nipkow\n*)\n\ntheory FunWithFunctions imports Complex_Main begin\n\ntext\\<open>See \\cite{Tao2006}. Was first brought to our attention by Herbert\nEhler who provided a similar proof.\\<close>\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 \\<open>n \\<le> f(n)\\<close> show \"f n = n\" by arith\nqed\n\n\ntext\\<open>See \\cite{Tao2006}. Possible extension:\nShould also hold if the range of \\<open>f\\<close> is the reals!\n\\<close>\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 \\<open>k \\<ge> 2\\<close> by arith\n    hence \"f(2) \\<le> 2\"\n      using mono_nat_linear_lb[of f 2 \"k - 2\",OF f_mono] \\<open>f k = k\\<close>\n      by simp\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 \"\\<exists>k. i=2*k\" by arith\n        then obtain k where \"i = 2*k\" ..\n        hence \"0 < k\" and \"k<i\" using \\<open>~i\\<le>1\\<close> by arith+\n        hence \"f(k) = k\" using less(1) by blast\n        thus \"f(i) = i\" using \\<open>i = 2*k\\<close> by(simp add:f_times 2)\n      next\n        assume \"i mod 2 \\<noteq> 0\"\n        hence \"\\<exists>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 \\<open>~i\\<le>1\\<close> by arith+\n        have \"2*k < f(2*k+1)\"\n        proof -\n          have \"2*k = 2*f(k)\" using less(1) \\<open>i=2*k+1\\<close> 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) \\<open>i=2*k+1\\<close> \\<open>~i\\<le>1\\<close> by simp\n          finally show ?thesis .\n        qed\n        ultimately show \"f(i) = i\" using \\<open>i = 2*k+1\\<close> by arith\n      qed\n    qed\n  qed\nqed\n\n\ntext\\<open>One more from Tao's booklet. If \\<open>f\\<close> is also assumed to be\ncontinuous, @{term\"f(x::real) = x+1\"} holds for all reals, not only\nrationals. Extend the proof!\\<close>\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 have \"f(of_int i) = of_int 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(of_int (i+1)) = f(of_int i + 0 + 1)\" by simp\n      also have \"\\<dots> = f(of_int i) + f 0\" by(rule f_add)\n      also have \"\\<dots> = of_int (i+1) + 1\" using step1 0 by simp\n      finally show ?case .\n    next\n      case (step2 i)\n      have \"f(of_int i) = f(of_int (i - 1) + 0 + 1)\" by simp\n      also have \"\\<dots> = f(of_int (i - 1)) + f 0\" by(rule f_add)\n      also have \"\\<dots> = f(of_int (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(of_int (Suc n)*r + of_int n) = of_int (Suc n) * f r\"\n    proof(induct n)\n      case 0 show ?case by simp\n    next\n      case (Suc n)\n      have \"of_int (Suc(Suc n))*r + of_int (Suc n) =\n            r + (of_int (Suc n)*r + of_int n) + 1\" (is \"?a = ?b\")\n        by(simp add: field_simps)\n      hence \"f ?a = f ?b\"\n        by presburger\n      also have \"\\<dots> = f r + f(of_int (Suc n)*r + of_int n)\" by(rule f_add)\n      also have \"\\<dots> = f r + of_int (Suc n) * f r\" by(simp only:Suc)\n      finally show ?case by(simp add: field_simps)\n    qed }\n  note 1 = this\n  { fix n::nat and r assume \"n\\<noteq>0\"\n    have \"f(of_int (n)*r + of_int (n - 1)) = of_int (n) * f r\"\n    proof(cases n)\n      case 0 thus ?thesis using \\<open>n\\<noteq>0\\<close> by simp\n    next\n      case Suc thus ?thesis using \\<open>n\\<noteq>0\\<close> using \"1\" by auto\n    qed }\n  note f_mult = this\n  from \\<open>r:\\<rat>\\<close> obtain i::int and n::nat where r: \"r = of_int i/of_int n\" and \"n\\<noteq>0\"\n    by(fastforce simp:Rats_eq_int_div_nat)\n  have \"of_int (n) * f(of_int i / of_int n) = f(of_int i + of_int (n - 1))\"\n    using \\<open>n\\<noteq>0\\<close>\n    by (metis (no_types, hide_lams) f_mult mult.commute nonzero_divide_eq_eq of_int_of_nat_eq of_nat_0_eq_iff) \n  also have \"\\<dots> = f(of_int (i + int n - 1))\" using \\<open>n\\<noteq>0\\<close>[simplified]\n    by (metis One_nat_def Suc_leI of_nat_1 add_diff_eq of_int_add of_nat_diff)\n  also have \"\\<dots> = of_int (i + int n - 1) + 1\" by(rule f_int)\n  also have \"\\<dots> = of_int i + of_int n\" by arith\n  finally show ?thesis using \\<open>n\\<noteq>0\\<close> unfolding r by (simp add:field_simps)\nqed\n\n\ntext\\<open>The only total model of a naive recursion equation of factorial on\nintegers is 0 for all negative arguments. Probably folklore.\\<close>\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 \\<open>j\\<le>i\\<close>])\n       apply(rule \\<open>ifac i \\<noteq> 0\\<close>)\n      apply (metis \\<open>i<0\\<close> 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 \\<open>j<i\\<close> \\<open>i<0\\<close> by arith\n    have \"ifac(j - 1) \\<noteq> 0\" using \\<open>j<i\\<close> by(simp add: below0)\n    then have \"\\<bar>ifac (j - 1)\\<bar> < (-j) * \\<bar>ifac (j - 1)\\<bar>\" using \\<open>j<i\\<close>\n      mult_le_less_imp_less[OF order_refl[of \"abs(ifac(j - 1))\"] \\<open>1 < -j\\<close>]\n      by(simp add:mult.commute)\n    hence \"abs(ifac(j - 1)) < abs(ifac j)\"\n      using \\<open>1 < -j\\<close> 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": "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/FunWithFunctions/FunWithFunctions.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.817574471748733, "lm_q2_score": 0.8757869867849167, "lm_q1q2_score": 0.7160210830850929}}
{"text": "(*  Title:      HOL/Metis_Examples/Trans_Closure.thy\n    Author:     Lawrence C. Paulson, Cambridge University Computer Laboratory\n    Author:     Jasmin Blanchette, TU Muenchen\n\nMetis example featuring the transitive closure.\n*)\n\nsection \\<open>Metis Example Featuring the Transitive Closure\\<close>\n\ntheory Trans_Closure\nimports Main\nbegin\n\ndeclare [[metis_new_skolem]]\n\ntype_synonym addr = nat\n\ndatatype val\n  = Unit        \\<comment> \"dummy result value of void expressions\"\n  | Null        \\<comment> \"null reference\"\n  | Bool bool   \\<comment> \"Boolean value\"\n  | Intg int    \\<comment> \"integer value\"\n  | Addr addr   \\<comment> \"addresses of objects in the heap\"\n\nconsts R :: \"(addr \\<times> addr) set\"\n\nconsts f :: \"addr \\<Rightarrow> val\"\n\nlemma \"\\<lbrakk>f c = Intg x; \\<forall>y. f b = Intg y \\<longrightarrow> y \\<noteq> x; (a, b) \\<in> R\\<^sup>*; (b, c) \\<in> R\\<^sup>*\\<rbrakk>\n       \\<Longrightarrow> \\<exists>c. (b, c) \\<in> R \\<and> (a, c) \\<in> R\\<^sup>*\"\n(* sledgehammer *)\nproof -\n  assume A1: \"f c = Intg x\"\n  assume A2: \"\\<forall>y. f b = Intg y \\<longrightarrow> y \\<noteq> x\"\n  assume A3: \"(a, b) \\<in> R\\<^sup>*\"\n  assume A4: \"(b, c) \\<in> R\\<^sup>*\"\n  have F1: \"f c \\<noteq> f b\" using A2 A1 by metis\n  have F2: \"\\<forall>u. (b, u) \\<in> R \\<longrightarrow> (a, u) \\<in> R\\<^sup>*\" using A3 by (metis transitive_closure_trans(6))\n  have F3: \"\\<exists>x. (b, x b c R) \\<in> R \\<or> c = b\" using A4 by (metis converse_rtranclE)\n  have \"c \\<noteq> b\" using F1 by metis\n  hence \"\\<exists>u. (b, u) \\<in> R\" using F3 by metis\n  thus \"\\<exists>c. (b, c) \\<in> R \\<and> (a, c) \\<in> R\\<^sup>*\" using F2 by metis\nqed\n\nlemma \"\\<lbrakk>f c = Intg x; \\<forall>y. f b = Intg y \\<longrightarrow> y \\<noteq> x; (a, b) \\<in> R\\<^sup>*; (b,c) \\<in> R\\<^sup>*\\<rbrakk>\n       \\<Longrightarrow> \\<exists>c. (b, c) \\<in> R \\<and> (a, c) \\<in> R\\<^sup>*\"\n(* sledgehammer [isar_proofs, compress = 2] *)\nproof -\n  assume A1: \"f c = Intg x\"\n  assume A2: \"\\<forall>y. f b = Intg y \\<longrightarrow> y \\<noteq> x\"\n  assume A3: \"(a, b) \\<in> R\\<^sup>*\"\n  assume A4: \"(b, c) \\<in> R\\<^sup>*\"\n  have \"b \\<noteq> c\" using A1 A2 by metis\n  hence \"\\<exists>x\\<^sub>1. (b, x\\<^sub>1) \\<in> R\" using A4 by (metis converse_rtranclE)\n  thus \"\\<exists>c. (b, c) \\<in> R \\<and> (a, c) \\<in> R\\<^sup>*\" using A3 by (metis transitive_closure_trans(6))\nqed\n\nlemma \"\\<lbrakk>f c = Intg x; \\<forall>y. f b = Intg y \\<longrightarrow> y \\<noteq> x; (a, b) \\<in> R\\<^sup>*; (b, c) \\<in> R\\<^sup>*\\<rbrakk>\n       \\<Longrightarrow> \\<exists>c. (b, c) \\<in> R \\<and> (a, c) \\<in> R\\<^sup>*\"\napply (erule_tac x = b in converse_rtranclE)\n apply metis\nby (metis transitive_closure_trans(6))\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/Metis_Examples/Trans_Closure.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887588052782737, "lm_q2_score": 0.8056321983146848, "lm_q1q2_score": 0.7160127100678685}}
{"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_MSortBU2Sorts\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 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 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\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_MSortBU2Sorts.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587993853655, "lm_q2_score": 0.8056321983146848, "lm_q1q2_score": 0.716012705320352}}
{"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 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\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 xperm_empty_imp: \"[] <~~> ys \\<Longrightarrow> ys = []\"\n  by (induct xs == \"[] :: '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_empty_imp: \"[] <~~> xs \\<Longrightarrow> xs = []\"\n  by (drule perm_length) auto\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  apply auto\n  apply (erule perm_sym [THEN perm_empty_imp])\n  done\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\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 (blast intro: cons_perm_imp_perm)\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  apply (safe intro!: perm_append2)\n  apply (rule append_perm_imp_perm)\n  apply (rule perm_append_swap [THEN perm.trans])\n    \\<comment> \\<open>the previous step helps this \\<open>blast\\<close> call succeed quickly\\<close>\n  apply (blast intro: perm_append_swap)\n  done\n\ntheorem mset_eq_perm: \"mset xs = mset 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_mset in arg_cong)\n  apply simp\n  done\n\nproposition mset_le_perm_append: \"mset xs \\<le># mset ys \\<longleftrightarrow> (\\<exists>zs. xs @ zs <~~> ys)\"\n  apply (auto simp: mset_eq_perm[THEN sym] mset_subset_eq_exists_conv)\n  apply (insert surj_mset)\n  apply (drule surjD)\n  apply (blast intro: sym)+\n  done\n\nproposition perm_set_eq: \"xs <~~> ys \\<Longrightarrow> set xs = set ys\"\n  by (metis mset_eq_perm mset_eq_setD)\n\nproposition 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\ntheorem 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\nproposition 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\ntheorem 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 \\<open>i < length xs\\<close> show \"xs ! i = zs ! (g \\<circ> f) i\"\n      using trans(1,3)[THEN perm_length] perm by auto\n  qed\nqed\n\nproposition perm_finite: \"finite {B. B <~~> A}\"\nproof (rule finite_subset[where B=\"{xs. set xs \\<subseteq> set A \\<and> length xs \\<le> length A}\"])\n show \"finite {xs. set xs \\<subseteq> set A \\<and> length xs \\<le> length A}\"\n   apply (cases A, simp)\n   apply (rule card_ge_0_finite)\n   apply (auto simp: card_lists_length_le)\n   done\nnext\n show \"{B. B <~~> A} \\<subseteq> {xs. set xs \\<subseteq> set A \\<and> length xs \\<le> length A}\"\n   by (clarsimp simp add: perm_length perm_set_eq)\nqed\n\nproposition perm_swap:\n    assumes \"i < length xs\" \"j < length xs\"\n    shows \"xs[i := xs ! j, j := xs ! i] <~~> xs\"\n  using assms by (simp add: mset_eq_perm[symmetric] mset_swap)\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/Permutation.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.80563219364797, "lm_q2_score": 0.8887588038050466, "lm_q1q2_score": 0.7160127047334055}}
{"text": "theory OneThirdRuleDefs\nimports \"../HOModel\"\nbegin\n\nsection \\<open>Verification of the \\emph{One-Third Rule} Consensus Algorithm\\<close>\n\ntext \\<open>\n  We now apply the framework introduced so far to the verification of\n  concrete algorithms, starting with algorithm \\emph{One-Third Rule},\n  which is one of the simplest algorithms presented in~\\<^cite>\\<open>\"charron:heardof\"\\<close>.\n  Nevertheless, the algorithm has some interesting characteristics:\n  it ensures safety (i.e., the Integrity and Agreement) properties in the\n  presence of arbitrary benign faults, and if everything works perfectly,\n  it terminates in just two rounds. \\emph{One-Third Rule} is an uncoordinated\n  algorithm tolerating benign faults, hence SHO or coordinator sets do not\n  play a role in its definition.\n\\<close>\n\n\nsubsection \\<open>Model of the Algorithm\\<close>\n\ntext \\<open>\n  We begin by introducing an anonymous type of processes of finite\n  cardinality that will instantiate the type variable \\<open>'proc\\<close>\n  of the generic HO model.\n\\<close>\n\ntypedecl Proc \\<comment> \\<open>the set of processes\\<close>\naxiomatization where Proc_finite: \"OFCLASS(Proc, finite_class)\"\ninstance Proc :: finite by (rule Proc_finite)\n\nabbreviation\n  \"N \\<equiv> card (UNIV::Proc set)\"\n\ntext \\<open>\n  The state of each process consists of two fields: \\<open>x\\<close> holds\n  the current value proposed by the process and \\<open>decide\\<close> the\n  value (if any, hence the option type) it has decided.\n\\<close>\n\nrecord 'val pstate =\n  x :: \"'val\"\n  decide :: \"'val option\"\n\ntext \\<open>\n  The initial value of field \\<open>x\\<close> is unconstrained, but no decision\n  has been taken initially.\n\\<close>\n\ndefinition OTR_initState where\n  \"OTR_initState p st \\<equiv> decide st = None\"\n\ntext \\<open>\n  Given a vector \\<open>msgs\\<close> of values (possibly null) received from \n  each process, @{term \"HOV msgs v\"} denotes the set of processes from\n  which value \\<open>v\\<close> was received.\n\\<close>\n\ndefinition HOV :: \"(Proc \\<Rightarrow> 'val option) \\<Rightarrow> 'val \\<Rightarrow> Proc set\" where\n  \"HOV msgs v \\<equiv> { q . msgs q = Some v }\"\n\ntext \\<open>\n  @{term \"MFR msgs v\"} (``most frequently received'') holds for\n  vector \\<open>msgs\\<close> if no value has been received more frequently\n  than \\<open>v\\<close>.\n\n  Some such value always exists, since there is only a finite set of\n  processes and thus a finite set of possible cardinalities of the\n  sets @{term \"HOV msgs v\"}.\n\\<close>\n\ndefinition MFR :: \"(Proc \\<Rightarrow> 'val option) \\<Rightarrow> 'val \\<Rightarrow> bool\" where\n  \"MFR msgs v \\<equiv> \\<forall>w. card (HOV msgs w) \\<le> card (HOV msgs v)\"\n\nlemma MFR_exists: \"\\<exists>v. MFR msgs v\"\nproof -\n  let ?cards = \"{ card (HOV msgs v) | v . True }\"\n  let ?mfr = \"Max ?cards\"\n  have \"\\<forall>v. card (HOV msgs v) \\<le> N\" by (auto intro: card_mono)\n  hence \"?cards \\<subseteq> { 0 .. N }\" by auto\n  hence fin: \"finite ?cards\" by (metis atLeast0AtMost finite_atMost finite_subset)\n  hence \"?mfr \\<in> ?cards\" by (rule Max_in) auto\n  then obtain v where v: \"?mfr = card (HOV msgs v)\" by auto\n  have \"MFR msgs v\"\n  proof (auto simp: MFR_def)\n    fix w\n    from fin have \"card (HOV msgs w) \\<le> ?mfr\" by (rule Max_ge) auto\n    thus \"card (HOV msgs w) \\<le> card (HOV msgs v)\" by (unfold v)\n  qed\n  thus ?thesis ..\nqed\n\ntext \\<open>\n  Also, if a process has heard from at least one other process,\n  the most frequently received values are among the received messages.\n\\<close>\n\nlemma MFR_in_msgs:\n  assumes HO:\"HOs m p \\<noteq> {}\"\n      and v: \"MFR (HOrcvdMsgs OTR_M m p (HOs m p) (rho m)) v\"\n             (is \"MFR ?msgs v\")\n  shows \"\\<exists>q \\<in> HOs m p. v = the (?msgs q)\"\nproof -\n  from HO obtain q where q: \"q \\<in> HOs m p\"\n    by auto\n  with v have \"HOV ?msgs (the (?msgs q)) \\<noteq> {}\"\n    by (auto simp: HOV_def HOrcvdMsgs_def)\n  hence HOp: \"0 < card (HOV ?msgs (the (?msgs q)))\"\n    by auto\n  also from v have \"\\<dots> \\<le> card (HOV ?msgs v)\"\n    by (simp add: MFR_def)\n  finally have \"HOV ?msgs v \\<noteq> {}\"\n    by auto\n  thus ?thesis\n    by (auto simp: HOV_def HOrcvdMsgs_def)\nqed\n\ntext \\<open>\n  @{term \"TwoThirds msgs v\"} holds if value \\<open>v\\<close> has been\n  received from more than $2/3$ of all processes.\n\\<close>\n\ndefinition TwoThirds where\n  \"TwoThirds msgs v \\<equiv> (2*N) div 3 < card (HOV msgs v)\"\n\ntext \\<open>\n  The next-state relation of algorithm \\emph{One-Third Rule} for every process\n  is defined as follows:\n  if the process has received values from more than $2/3$ of all processes,\n  the \\<open>x\\<close> field is set to the smallest among the most frequently received\n  values, and the process decides value $v$ if it received $v$ from more than\n  $2/3$ of all processes. If \\<open>p\\<close> hasn't heard from more than $2/3$ of\n  all processes, the state remains unchanged.\n  (Note that \\<open>Some\\<close> is the constructor of the option datatype, whereas\n  \\<open>\\<some>\\<close> is Hilbert's choice operator.)\n  We require the type of values to be linearly ordered so that the minimum\n  is guaranteed to be well-defined.\n\\<close>\n\ndefinition OTR_nextState where\n  \"OTR_nextState r p (st::('val::linorder) pstate) msgs st' \\<equiv> \n   if (2*N) div 3 < card {q. msgs q \\<noteq> None}\n   then st' = \\<lparr> x = Min {v . MFR msgs v},\n          decide = (if (\\<exists>v. TwoThirds msgs v)\n                    then Some (\\<some>v. TwoThirds msgs v)\n                    else decide st) \\<rparr>\n   else st' = st\"\n\ntext \\<open>\n  The message sending function is very simple: at every round, every process\n  sends its current proposal (field \\<open>x\\<close> of its local state) to all \n  processes.\n\\<close>\n\ndefinition OTR_sendMsg where\n  \"OTR_sendMsg r p q st \\<equiv> x st\"\n\nsubsection \\<open>Communication Predicate for \\emph{One-Third Rule}\\<close>\n\ntext \\<open>\n  We now define the communication predicate for the \\emph{One-Third Rule}\n  algorithm to be correct.\n  It requires that, infinitely often, there is a round where all processes\n  receive messages from the same set \\<open>\\<Pi>\\<close> of processes where \\<open>\\<Pi>\\<close>\n  contains more than two thirds of all processes.\n  The ``per-round'' part of the communication predicate is trivial.\n\\<close>\n\ndefinition OTR_commPerRd where\n  \"OTR_commPerRd HOrs \\<equiv> True\"\n\ndefinition OTR_commGlobal where\n  \"OTR_commGlobal HOs \\<equiv>\n    \\<forall>r. \\<exists>r0 \\<Pi>. r0 \\<ge> r \\<and> (\\<forall>p. HOs r0 p = \\<Pi>) \\<and> card \\<Pi> > (2*N) div 3\"\n\nsubsection \\<open>The \\emph{One-Third Rule} Heard-Of Machine\\<close>\n\ntext \\<open>\n  We now define the HO machine for the \\emph{One-Third Rule} algorithm\n  by assembling the algorithm definition and its communication-predicate.\n  Because this is an uncoordinated algorithm, the \\<open>crd\\<close> arguments\n  of the initial- and next-state predicates are unused.\n\\<close>\n\ndefinition OTR_HOMachine where\n  \"OTR_HOMachine =\n    \\<lparr> CinitState =  (\\<lambda> p st crd. OTR_initState p st),\n     sendMsg =  OTR_sendMsg,\n     CnextState = (\\<lambda> r p st msgs crd st'. OTR_nextState r p st msgs st'),\n     HOcommPerRd = OTR_commPerRd,\n     HOcommGlobal = OTR_commGlobal \\<rparr>\"\n\nabbreviation \"OTR_M \\<equiv> OTR_HOMachine::(Proc, 'val::linorder pstate, 'val) HOMachine\"\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/Heard_Of/otr/OneThirdRuleDefs.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8887587846530938, "lm_q2_score": 0.8056321796478255, "lm_q1q2_score": 0.7160126768612243}}
{"text": "theory tut3 \nimports\nMain\n\nbegin\n\nlocale Geom =\n  fixes on :: \"'p \\<Rightarrow> 'l \\<Rightarrow> bool\"\n  assumes line_on_two_pts: \"a \\<noteq> b \\<Longrightarrow> \\<exists>l. on a l \\<and> on b l\" \n  and line_on_two_pts_unique: \"\\<lbrakk> a \\<noteq> b; on a l; on b l; on a m; on b m \\<rbrakk> \\<Longrightarrow> l = m\"\n  and two_points_on_line: \"\\<exists>a b. a \\<noteq> b \\<and> on a l \\<and> on b l\"\n  and three_points_not_on_line: \"\\<exists>a b c. a \\<noteq> b \\<and> a \\<noteq> c \\<and> b \\<noteq> c \\<and> \n                                    \\<not> (\\<exists>l. on a l \\<and> on b l \\<and> on c l)\"\nbegin\n  \n\n(* Not asked for in tutorial: An alternative way of writing Axiom 4 *)  \nlemma three_points_not_on_line_alt:\n  \"\\<exists>a b c. a \\<noteq> b \\<and> a \\<noteq> c \\<and> b \\<noteq> c \\<and> (\\<forall>l. on a l \\<and> on b l \\<longrightarrow> \\<not> on c l)\"\nproof -\n  obtain a b c where distinct: \"a \\<noteq> b \\<and> a \\<noteq> c \\<and> b \\<noteq> c\" \"\\<not> (\\<exists>l. on a l \\<and> on b l \\<and> on c l)\" \n    using three_points_not_on_line by blast\n  then have \"\\<forall>l. on a l \\<and> on b l \\<longrightarrow> \\<not> on c l\"\n    by blast\n  thus ?thesis using distinct by blast\nqed        \n  \nlemma exists_pt_not_on_line: \"\\<exists>x. \\<not> on x l\"\nproof -\n   obtain a b c where l3: \"\\<not> (on a l \\<and> on b l \\<and> on c l)\" using three_points_not_on_line by blast \n   thus ?thesis by blast \nqed\n\nlemma two_lines_through_each_point: \"\\<exists>l m. on x l \\<and> on x m \\<and> l \\<noteq> m\"\nproof -\n  have \"\\<exists>z. z \\<noteq> x\" \n  proof (rule ccontr)\n    from two_points_on_line obtain a b where ab: \"(a::'p) \\<noteq> b\" by blast\n    assume \"\\<nexists>z. z \\<noteq> x\" then have univ: \"\\<forall>z. z = x\" by blast\n    then have \"a = x\" \"b = x\" by auto\n    then show False using ab by simp\n  qed\n  then obtain z where \"z \\<noteq> x\" by blast\n  then obtain l where xl: \"on x l\" and zl: \"on z l\" using line_on_two_pts by blast \n  obtain w where n_wl: \"\\<not> on w l\" using exists_pt_not_on_line by blast\n  obtain m where wm: \"on x m\" and zm: \"on w m\" using line_on_two_pts xl by force\n  then have \"l \\<noteq> m\" using n_wl by blast  \n  thus ?thesis using wm xl by blast \nqed\n\n(* Alternative proof of the above that uses Metis *)\nlemma two_lines_through_each_point2: \"\\<exists>l m. on x l \\<and> on x m \\<and> l \\<noteq> m\"\nproof -\n  obtain z where \"z \\<noteq> x\" using two_points_on_line by metis \n  then obtain l where xl: \"on x l\" and zl: \"on z l\" using line_on_two_pts by blast \n  obtain w where n_wl: \"\\<not> on w l\" using exists_pt_not_on_line by blast\n  obtain m where wm: \"on x m\" and zm: \"on w m\" using line_on_two_pts xl by force\n  then have \"l \\<noteq> m\" using n_wl by blast  \n  thus ?thesis using wm xl by blast \nqed\n\n\nlemma two_lines_through_each_point2: \"\\<exists>l m. on x l \\<and> on x m \\<and> l \\<noteq> m\"\nproof -\n  obtain z where \"z \\<noteq> x\" using two_points_on_line by metis \n  then obtain l where xl: \"on x l\" and zl: \"on z l\" using line_on_two_pts by blast \n  obtain w where n_wl: \"\\<not> on w l\" using exists_pt_not_on_line by blast\n  obtain m where wm: \"on x m\" and zm: \"on w m\" using line_on_two_pts xl by force\n  then have \"l \\<noteq> m\" using n_wl by blast  \n  thus ?thesis using wm xl by blast \nqed\n\nlemma two_lines_unique_intersect_pt: \n   assumes lm: \"l \\<noteq> m\" and \"on x l\" and \"on x m\" and \"on y l\" and \"on y m\" shows \"x = y\"\nproof (rule ccontr)\n   assume \"x \\<noteq> y\" then have \"l = m\" using line_on_two_pts_unique assms by simp\n   thus \"False\" using lm by simp\nqed\n\nend\n\n(* Not asked for in tutorial: An extension of the locale with a new definition \n   using the \"in\" keyword *)\n\ndefinition (in Geom) \n  collinear :: \"'p \\<Rightarrow> 'p \\<Rightarrow> 'p \\<Rightarrow> bool\" \n  where \"collinear a b c \\<equiv> \\<exists>l. on a l \\<and> on b l \\<and> on c l\"\n\n\nend\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/tut3sol.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972616934406, "lm_q2_score": 0.8221891370573388, "lm_q1q2_score": 0.715795611316212}}
{"text": "(*\n    Author:   Benedikt Seidl\n    Author:   Salomon Sickert\n    License:  BSD\n*)\n\nsection \\<open>Disjunctive Normal Form of LTL formulas\\<close>\n\ntheory Disjunctive_Normal_Form\nimports\n  LTL Equivalence_Relations \"HOL-Library.FSet\"\n\"Eval_Base.Eval_Base\" \nbegin\n\ntext \\<open>\n  We use the propositional representation of LTL formulas to define\n  the minimal disjunctive normal form of our formulas. For this purpose\n  we define the minimal product \\<open>\\<otimes>\\<^sub>m\\<close> and union \\<open>\\<union>\\<^sub>m\\<close>.\n  In the end we show that for a set \\<open>\\<A>\\<close> of literals,\n  @{term \"\\<A> \\<Turnstile>\\<^sub>P \\<phi>\"} if, and only if, there exists a subset\n  of \\<open>\\<A>\\<close> in the minimal DNF of \\<open>\\<phi>\\<close>.\n\\<close>\n\nsubsection \\<open>Definition of Minimum Sets\\<close>\n\ndefinition (in ord) min_set :: \"'a set \\<Rightarrow> 'a set\" where\n  \"min_set X = {y \\<in> X. \\<forall>x \\<in> X. x \\<le> y \\<longrightarrow> x = y}\"\n\nlemma min_set_iff:\n  \"x \\<in> min_set X \\<longleftrightarrow> x \\<in> X \\<and> (\\<forall>y \\<in> X. y \\<le> x \\<longrightarrow> y = x)\"\n  unfolding min_set_def by blast\n\nlemma min_set_subset:\n  \"min_set X \\<subseteq> X\"\n  by (auto simp: min_set_def)\n\nlemma min_set_idem[simp]:\n  \"min_set (min_set X) = min_set X\"\n  by (auto simp: min_set_def)\n\nlemma min_set_empty[simp]:\n  \"min_set {} = {}\"\n  using min_set_subset by blast\n\nlemma min_set_singleton[simp]:\n  \"min_set {x} = {x}\"\n  by (auto simp: min_set_def)\n\n\n\nlemma min_set_obtains_helper:\n  \"A \\<in> B \\<Longrightarrow> \\<exists>C. C |\\<subseteq>| A \\<and> C \\<in> min_set B\"\nproof2 (induction \"fcard A\" arbitrary: A rule: less_induct)\n  case less\n\n  then have \"(\\<forall>A'. A' \\<notin> B \\<or> \\<not> A' |\\<subseteq>| A \\<or> A' = A) \\<or> (\\<exists>A'. A' |\\<subseteq>| A \\<and> A' \\<in> min_set B)\"\n    by (metis (no_types) dual_order.trans order.not_eq_order_implies_strict pfsubset_fcard_mono)\n\n  then show ?case\n    using less.prems min_set_def by auto\nqed\n\nlemma min_set_obtains:\n  assumes \"A \\<in> B\"\n  obtains C where \"C |\\<subseteq>| A\" and \"C \\<in> min_set B\"\n  using min_set_obtains_helper assms by metis\n\n\n\nsubsection \\<open>Minimal operators on sets\\<close>\n\ndefinition product :: \"'a fset set \\<Rightarrow> 'a fset set \\<Rightarrow> 'a fset set\" (infixr \"\\<otimes>\" 65)\n  where \"A \\<otimes> B = {a |\\<union>| b | a b. a \\<in> A \\<and> b \\<in> B}\"\n\ndefinition min_product :: \"'a fset set \\<Rightarrow> 'a fset set \\<Rightarrow> 'a fset set\" (infixr \"\\<otimes>\\<^sub>m\" 65)\n  where \"A \\<otimes>\\<^sub>m B = min_set (A \\<otimes> B)\"\n\ndefinition min_union :: \"'a fset set \\<Rightarrow> 'a fset set \\<Rightarrow> 'a fset set\" (infixr \"\\<union>\\<^sub>m\" 65)\n  where \"A \\<union>\\<^sub>m B = min_set (A \\<union> B)\"\n\ndefinition product_set :: \"'a fset set set \\<Rightarrow> 'a fset set\" (\"\\<Otimes>\")\n  where \"\\<Otimes> X = Finite_Set.fold product {{||}} X\"\n\ndefinition min_product_set :: \"'a fset set set \\<Rightarrow> 'a fset set\" (\"\\<Otimes>\\<^sub>m\")\n  where \"\\<Otimes>\\<^sub>m X = Finite_Set.fold min_product {{||}} X\"\n\n\nlemma min_product_idem[simp]:\n  \"A \\<otimes>\\<^sub>m A = min_set A\"\n  by (auto simp: min_product_def product_def min_set_def) fastforce\n\nlemma min_union_idem[simp]:\n  \"A \\<union>\\<^sub>m A = min_set A\"\n  by (simp add: min_union_def)\n\n\nlemma product_empty[simp]:\n  \"A \\<otimes> {} = {}\"\n  \"{} \\<otimes> A = {}\"\n  by (simp_all add: product_def)\n\nlemma min_product_empty[simp]:\n  \"A \\<otimes>\\<^sub>m {} = {}\"\n  \"{} \\<otimes>\\<^sub>m A = {}\"\n  by (simp_all add: min_product_def)\n\nlemma min_union_empty[simp]:\n  \"A \\<union>\\<^sub>m {} = min_set A\"\n  \"{} \\<union>\\<^sub>m A = min_set A\"\n  by (simp_all add: min_union_def)\n\nlemma product_empty_singleton[simp]:\n  \"A \\<otimes> {{||}} = A\"\n  \"{{||}} \\<otimes> A = A\"\n  by (simp_all add: product_def)\n\nlemma min_product_empty_singleton[simp]:\n  \"A \\<otimes>\\<^sub>m {{||}} = min_set A\"\n  \"{{||}} \\<otimes>\\<^sub>m A = min_set A\"\n  by (simp_all add: min_product_def)\n\nlemma product_singleton_singleton:\n  \"A \\<otimes> {{|x|}} = finsert x ` A\"\n  \"{{|x|}} \\<otimes> A = finsert x ` A\"\n  unfolding product_def by blast+\n\nlemma product_mono:\n  \"A \\<subseteq> B \\<Longrightarrow> A \\<otimes> C \\<subseteq> B \\<otimes> C\"\n  \"B \\<subseteq> C \\<Longrightarrow> A \\<otimes> B \\<subseteq> A \\<otimes> C\"\n  unfolding product_def by auto\n\n\n\nlemma product_finite:\n  \"finite A \\<Longrightarrow> finite B \\<Longrightarrow> finite (A \\<otimes> B)\"\n  by (simp add: product_def finite_image_set2)\n\nlemma min_product_finite:\n  \"finite A \\<Longrightarrow> finite B \\<Longrightarrow> finite (A \\<otimes>\\<^sub>m B)\"\n  by (metis min_product_def product_finite min_set_finite)\n\nlemma min_union_finite:\n  \"finite A \\<Longrightarrow> finite B \\<Longrightarrow> finite (A \\<union>\\<^sub>m B)\"\n  by (simp add: min_union_def min_set_finite)\n\n\nlemma product_set_infinite[simp]:\n  \"infinite X \\<Longrightarrow> \\<Otimes> X = {{||}}\"\n  by (simp add: product_set_def)\n\nlemma min_product_set_infinite[simp]:\n  \"infinite X \\<Longrightarrow> \\<Otimes>\\<^sub>m X = {{||}}\"\n  by (simp add: min_product_set_def)\n\n\nlemma product_comm:\n  \"A \\<otimes> B = B \\<otimes> A\"\n  unfolding product_def by blast\n\n\n\nlemma min_union_comm:\n  \"A \\<union>\\<^sub>m B = B \\<union>\\<^sub>m A\"\n  unfolding min_union_def\n  by (simp add: sup.commute)\n\n\nlemma product_iff:\n  \"x \\<in> A \\<otimes> B \\<longleftrightarrow> (\\<exists>a \\<in> A. \\<exists>b \\<in> B. x = a |\\<union>| b)\"\n  unfolding product_def by blast\n\nlemma min_product_iff:\n  \"x \\<in> A \\<otimes>\\<^sub>m B \\<longleftrightarrow> (\\<exists>a \\<in> A. \\<exists>b \\<in> B. x = a |\\<union>| b) \\<and> (\\<forall>a \\<in> A. \\<forall>b \\<in> B. a |\\<union>| b |\\<subseteq>| x \\<longrightarrow> a |\\<union>| b = x)\"\n  unfolding min_product_def min_set_iff product_iff product_def by blast\n\nlemma min_union_iff:\n  \"x \\<in> A \\<union>\\<^sub>m B \\<longleftrightarrow> x \\<in> A \\<union> B \\<and> (\\<forall>a \\<in> A. a |\\<subseteq>| x \\<longrightarrow> a = x) \\<and> (\\<forall>b \\<in> B. b |\\<subseteq>| x \\<longrightarrow> b = x)\"\n  unfolding min_union_def min_set_iff by blast\n\n\n\n\n  then obtain a b where \"a \\<in> min_set A\" and \"b \\<in> B\" and \"x = a |\\<union>| b\" and 1: \"\\<forall>a \\<in> min_set A. \\<forall>b \\<in> B. a |\\<union>| b |\\<subseteq>| x \\<longrightarrow> a |\\<union>| b = x\"\n    unfolding min_product_iff by blast\n\n  moreover\n\n  {\n    fix a' b'\n    assume \"a' \\<in> A\" and \"b' \\<in> B\" and \"a' |\\<union>| b' |\\<subseteq>| x\"\n\n    then obtain a'' where \"a'' |\\<subseteq>| a'\" and \"a'' \\<in> min_set A\"\n      using min_set_obtains by metis\n\n    then have \"a'' |\\<union>| b' = x\"\n      by (metis (full_types) 1 \\<open>b' \\<in> B\\<close> \\<open>a' |\\<union>| b' |\\<subseteq>| x\\<close> dual_order.trans le_sup_iff)\n\n    then have \"a' |\\<union>| b' = x\"\n      using \\<open>a' |\\<union>| b' |\\<subseteq>| x\\<close> \\<open>a'' |\\<subseteq>| a'\\<close> by blast\n  }\n\n  ultimately show \"x \\<in> A \\<otimes>\\<^sub>m B\"\n    by (metis min_product_iff min_set_iff)\nnext\n  fix x\n  assume \"x \\<in> A \\<otimes>\\<^sub>m B\"\n\n  then have 1: \"x \\<in> A \\<otimes> B\" and \"\\<forall>y \\<in> A \\<otimes> B. y |\\<subseteq>| x \\<longrightarrow> y = x\"\n    unfolding min_product_def min_set_iff by simp+\n\n  then have 2: \"\\<forall>y\\<in>min_set A \\<otimes> B. y |\\<subseteq>| x \\<longrightarrow> y = x\"\n    by (metis product_iff min_set_iff)\n\n  then have \"x \\<in> min_set A \\<otimes> B\"\n    by (metis 1 funion_mono min_set_obtains order_refl product_iff)\n\n  then show \"x \\<in> min_set A \\<otimes>\\<^sub>m B\"\n    by (simp add: 2 min_product_def min_set_iff)\nqed\n\nlemma min_set_min_product[simp]:\n  \"(min_set A) \\<otimes>\\<^sub>m B = A \\<otimes>\\<^sub>m B\"\n  \"A \\<otimes>\\<^sub>m (min_set B) = A \\<otimes>\\<^sub>m B\"\n  using min_product_comm min_set_min_product_helper by blast+\n\nlemma min_set_min_union[simp]:\n  \"(min_set A) \\<union>\\<^sub>m B = A \\<union>\\<^sub>m B\"\n  \"A \\<union>\\<^sub>m (min_set B) = A \\<union>\\<^sub>m B\"\nproof (unfold min_union_def min_set_def, safe)\n  show \"\\<And>x xa xb. \\<lbrakk>\\<forall>xa\\<in>{y \\<in> A. \\<forall>x\\<in>A. x |\\<subseteq>| y \\<longrightarrow> x = y} \\<union> B. xa |\\<subseteq>| x \\<longrightarrow> xa = x; x \\<in> B; xa |\\<subseteq>| x; xb |\\<in>| x; xa \\<in> A\\<rbrakk> \\<Longrightarrow> xb |\\<in>| xa\"\n    by (metis (mono_tags) UnCI dual_order.trans fequalityI min_set_def min_set_obtains)\nnext\n  show \"\\<And>x xa xb. \\<lbrakk>\\<forall>xa\\<in>A \\<union> {y \\<in> B. \\<forall>x\\<in>B. x |\\<subseteq>| y \\<longrightarrow> x = y}. xa |\\<subseteq>| x \\<longrightarrow> xa = x; x \\<in> A; xa |\\<subseteq>| x; xb |\\<in>| x; xa \\<in> B\\<rbrakk> \\<Longrightarrow> xb |\\<in>| xa\"\n    by (metis (mono_tags) UnCI dual_order.trans fequalityI min_set_def min_set_obtains)\nqed blast+\n\n\nlemma product_assoc[simp]:\n  \"(A \\<otimes> B) \\<otimes> C = A \\<otimes> (B \\<otimes> C)\"\nproof (unfold product_def, safe)\n  fix a b c\n  assume \"a \\<in> A\" and \"c \\<in> C\" and \"b \\<in> B\"\n  then have \"b |\\<union>| c \\<in> {b |\\<union>| c |b c. b \\<in> B \\<and> c \\<in> C}\"\n    by blast\n  then show \"\\<exists>a' bc. a |\\<union>| b |\\<union>| c = a' |\\<union>| bc \\<and> a' \\<in> A \\<and> bc \\<in> {b |\\<union>| c |b c. b \\<in> B \\<and> c \\<in> C}\"\n    using `a \\<in> A` by (metis (no_types) inf_sup_aci(5) sup_left_commute)\nqed (metis (mono_tags, lifting) mem_Collect_eq sup_assoc)\n\nlemma min_product_assoc[simp]:\n  \"(A \\<otimes>\\<^sub>m B) \\<otimes>\\<^sub>m C = A \\<otimes>\\<^sub>m (B \\<otimes>\\<^sub>m C)\"\n  unfolding min_product_def[of A B] min_product_def[of B C]\n  by simp (simp add: min_product_def)\n\nlemma min_union_assoc[simp]:\n  \"(A \\<union>\\<^sub>m B) \\<union>\\<^sub>m C = A \\<union>\\<^sub>m (B \\<union>\\<^sub>m C)\"\n  unfolding min_union_def[of A B] min_union_def[of B C]\n  by simp (simp add: min_union_def sup_assoc)\n\n\nlemma min_product_comp:\n  \"a \\<in> A \\<Longrightarrow> b \\<in> B \\<Longrightarrow> \\<exists>c. c |\\<subseteq>| (a |\\<union>| b) \\<and> c \\<in> A \\<otimes>\\<^sub>m B\"\n  by (metis (mono_tags, lifting) mem_Collect_eq min_product_def product_def min_set_obtains)\n\nlemma min_union_comp:\n  \"a \\<in> A \\<Longrightarrow> \\<exists>c. c |\\<subseteq>| a \\<and> c \\<in> A \\<union>\\<^sub>m B\"\n  by (metis Un_iff min_set_obtains min_union_def)\n\n\ninterpretation product_set_thms: Finite_Set.comp_fun_commute product\nproof unfold_locales\n  have \"\\<And>x y z. x \\<otimes> (y \\<otimes> z) = y \\<otimes> (x \\<otimes> z)\"\n    by (simp only: product_assoc[symmetric]) (simp only: product_comm)\n\n  then show \"\\<And>x y. (\\<otimes>) y \\<circ> (\\<otimes>) x = (\\<otimes>) x \\<circ> (\\<otimes>) y\"\n    by fastforce\nqed\n\ninterpretation min_product_set_thms: Finite_Set.comp_fun_idem min_product\nproof unfold_locales\n  have \"\\<And>x y z. x \\<otimes>\\<^sub>m (y \\<otimes>\\<^sub>m z) = y \\<otimes>\\<^sub>m (x \\<otimes>\\<^sub>m z)\"\n    by (simp only: min_product_assoc[symmetric]) (simp only: min_product_comm)\n\n  then show \"\\<And>x y. (\\<otimes>\\<^sub>m) y \\<circ> (\\<otimes>\\<^sub>m) x = (\\<otimes>\\<^sub>m) x \\<circ> (\\<otimes>\\<^sub>m) y\"\n    by fastforce\nnext\n  have \"\\<And>x y. x \\<otimes>\\<^sub>m (x \\<otimes>\\<^sub>m y) = x \\<otimes>\\<^sub>m y\"\n    by (simp add: min_product_assoc[symmetric])\n\n  then show \"\\<And>x. (\\<otimes>\\<^sub>m) x \\<circ> (\\<otimes>\\<^sub>m) x = (\\<otimes>\\<^sub>m) x\"\n    by fastforce\nqed\n\n\ninterpretation min_union_set_thms: Finite_Set.comp_fun_idem min_union\nproof unfold_locales\n  have \"\\<And>x y z. x \\<union>\\<^sub>m (y \\<union>\\<^sub>m z) = y \\<union>\\<^sub>m (x \\<union>\\<^sub>m z)\"\n    by (simp only: min_union_assoc[symmetric]) (simp only: min_union_comm)\n\n  then show \"\\<And>x y. (\\<union>\\<^sub>m) y \\<circ> (\\<union>\\<^sub>m) x = (\\<union>\\<^sub>m) x \\<circ> (\\<union>\\<^sub>m) y\"\n    by fastforce\nnext\n  have \"\\<And>x y. x \\<union>\\<^sub>m (x \\<union>\\<^sub>m y) = x \\<union>\\<^sub>m y\"\n    by (simp add: min_union_assoc[symmetric])\n\n  then show \"\\<And>x. (\\<union>\\<^sub>m) x \\<circ> (\\<union>\\<^sub>m) x = (\\<union>\\<^sub>m) x\"\n    by fastforce\nqed\n\n\nlemma product_set_empty[simp]:\n  \"\\<Otimes> {} = {{||}}\"\n  \"\\<Otimes> {{}} = {}\"\n  \"\\<Otimes> {{{||}}} = {{||}}\"\n  by (simp_all add: product_set_def)\n\nlemma min_product_set_empty[simp]:\n  \"\\<Otimes>\\<^sub>m {} = {{||}}\"\n  \"\\<Otimes>\\<^sub>m {{}} = {}\"\n  \"\\<Otimes>\\<^sub>m {{{||}}} = {{||}}\"\n  by (simp_all add: min_product_set_def)\n\nlemma product_set_code[code]:\n  \"\\<Otimes> (set xs) = fold product (remdups xs) {{||}}\"\n  by (simp add: product_set_def product_set_thms.fold_set_fold_remdups)\n\nlemma min_product_set_code[code]:\n  \"\\<Otimes>\\<^sub>m (set xs) = fold min_product (remdups xs) {{||}}\"\n  by (simp add: min_product_set_def min_product_set_thms.fold_set_fold_remdups)\n\nlemma product_set_insert[simp]:\n  \"finite X \\<Longrightarrow> \\<Otimes> (insert x X) = x \\<otimes> (\\<Otimes> (X - {x}))\"\n  unfolding product_set_def product_set_thms.fold_insert_remove ..\n\nlemma min_product_set_insert[simp]:\n  \"finite X \\<Longrightarrow> \\<Otimes>\\<^sub>m (insert x X) = x \\<otimes>\\<^sub>m (\\<Otimes>\\<^sub>m X)\"\n  unfolding min_product_set_def min_product_set_thms.fold_insert_idem ..\n\nlemma min_product_subseteq:\n  \"x \\<in> A \\<otimes>\\<^sub>m B \\<Longrightarrow> \\<exists>a. a |\\<subseteq>| x \\<and> a \\<in> A\"\n  by (metis funion_upper1 min_product_iff)\n\nlemma min_product_set_subseteq:\n  \"finite X \\<Longrightarrow> x \\<in> \\<Otimes>\\<^sub>m X \\<Longrightarrow> A \\<in> X \\<Longrightarrow> \\<exists>a \\<in> A. a |\\<subseteq>| x\"\n  apply2 (induction X rule: finite_induct) by (blast, metis finite_insert insert_absorb min_product_set_insert min_product_subseteq)\n\n\n\nlemma min_product_min_set[simp]:\n  \"min_set (A \\<otimes>\\<^sub>m B) = A \\<otimes>\\<^sub>m B\"\n  by (simp add: min_product_def)\n\nlemma min_union_min_set[simp]:\n  \"min_set (A \\<union>\\<^sub>m B) = A \\<union>\\<^sub>m B\"\n  by (simp add: min_union_def)\n\nlemma min_product_set_min_set[simp]:\n  \"finite X \\<Longrightarrow> min_set (\\<Otimes>\\<^sub>m X) = \\<Otimes>\\<^sub>m X\"\n  apply2 (induction X rule: finite_induct) by (auto simp add: min_product_set_def min_set_iff)\n\nlemma min_set_min_product_set[simp]:\n  \"finite X \\<Longrightarrow> \\<Otimes>\\<^sub>m (min_set ` X) = \\<Otimes>\\<^sub>m X\"\n  apply2 (induction X rule: finite_induct) by simp_all\n\nlemma min_product_set_union[simp]:\n  \"finite X \\<Longrightarrow> finite Y \\<Longrightarrow> \\<Otimes>\\<^sub>m (X \\<union> Y) = (\\<Otimes>\\<^sub>m X) \\<otimes>\\<^sub>m (\\<Otimes>\\<^sub>m Y)\"\n  apply2 (induction X rule: finite_induct) by simp_all\n\n\nlemma product_set_finite:\n  \"(\\<And>x. x \\<in> X \\<Longrightarrow> finite x) \\<Longrightarrow> finite (\\<Otimes> X)\"\n  apply (cases \"finite X\", rotate_tac) apply2(induction X rule: finite_induct) by (simp_all add: product_set_def, insert product_finite, blast)(*Yutaka rewrote this for evaluation. Originally it was: apply (cases \"finite X\", rotate_tac, induction X rule: finite_induct, simp_all add: product_set_def, insert product_finite, blast)*)\n\nlemma min_product_set_finite:\n  \"(\\<And>x. x \\<in> X \\<Longrightarrow> finite x) \\<Longrightarrow> finite (\\<Otimes>\\<^sub>m X)\"\n  apply (cases \"finite X\", rotate_tac) apply2(induction X rule: finite_induct) by (simp_all add: min_product_set_def, insert min_product_finite, blast)(*Yutaka rewrote this for evaluation. Originally it was: by (cases \"finite X\", rotate_tac, induction X rule: finite_induct, simp_all add: min_product_set_def, insert min_product_finite, blast)*)\n\n\n\nsubsection \\<open>Disjunctive Normal Form\\<close>\n\nfun dnf :: \"'a ltln \\<Rightarrow> 'a ltln fset set\"\nwhere\n  \"dnf true\\<^sub>n = {{||}}\"\n| \"dnf false\\<^sub>n = {}\"\n| \"dnf (\\<phi> and\\<^sub>n \\<psi>) = (dnf \\<phi>) \\<otimes> (dnf \\<psi>)\"\n| \"dnf (\\<phi> or\\<^sub>n \\<psi>) = (dnf \\<phi>) \\<union> (dnf \\<psi>)\"\n| \"dnf \\<phi> = {{|\\<phi>|}}\"\n\nfun min_dnf :: \"'a ltln \\<Rightarrow> 'a ltln fset set\"\nwhere\n  \"min_dnf true\\<^sub>n = {{||}}\"\n| \"min_dnf false\\<^sub>n = {}\"\n| \"min_dnf (\\<phi> and\\<^sub>n \\<psi>) = (min_dnf \\<phi>) \\<otimes>\\<^sub>m (min_dnf \\<psi>)\"\n| \"min_dnf (\\<phi> or\\<^sub>n \\<psi>) = (min_dnf \\<phi>) \\<union>\\<^sub>m (min_dnf \\<psi>)\"\n| \"min_dnf \\<phi> = {{|\\<phi>|}}\"\n\nlemma dnf_min_set:\n  \"min_dnf \\<phi> = min_set (dnf \\<phi>)\"\n  apply2 (induction \\<phi>) by (simp_all, simp_all only: min_product_def min_union_def)\n\nlemma dnf_finite:\n  \"finite (dnf \\<phi>)\"\n  apply2 (induction \\<phi>) by (auto simp: product_finite)\n\nlemma min_dnf_finite:\n  \"finite (min_dnf \\<phi>)\"\n  apply2 (induction \\<phi>) by (auto simp: min_product_finite min_union_finite)\n\nlemma dnf_Abs_fset[simp]:\n  \"fset (Abs_fset (dnf \\<phi>)) = dnf \\<phi>\"\n  by (simp add: dnf_finite Abs_fset_inverse)\n\nlemma min_dnf_Abs_fset[simp]:\n  \"fset (Abs_fset (min_dnf \\<phi>)) = min_dnf \\<phi>\"\n  by (simp add: min_dnf_finite Abs_fset_inverse)\n\nlemma dnf_prop_atoms:\n  \"\\<Phi> \\<in> dnf \\<phi> \\<Longrightarrow> fset \\<Phi> \\<subseteq> prop_atoms \\<phi>\"\n  apply2 (induction \\<phi> arbitrary: \\<Phi>) by (auto simp: product_def, blast+)\n\nlemma min_dnf_prop_atoms:\n  \"\\<Phi> \\<in> min_dnf \\<phi> \\<Longrightarrow> fset \\<Phi> \\<subseteq> prop_atoms \\<phi>\"\n  using dnf_min_set dnf_prop_atoms min_set_subset by blast\n\nlemma min_dnf_atoms_dnf:\n  \"\\<Phi> \\<in> min_dnf \\<psi> \\<Longrightarrow> \\<phi> \\<in> fset \\<Phi> \\<Longrightarrow> dnf \\<phi> = {{|\\<phi>|}}\"\nproof2 (induction \\<phi>)\n  case True_ltln\n  then show ?case\n    using min_dnf_prop_atoms prop_atoms_notin(1) by blast\nnext\n  case False_ltln\n  then show ?case\n    using min_dnf_prop_atoms prop_atoms_notin(2) by blast\nnext\n  case (And_ltln \\<phi>1 \\<phi>2)\n  then show ?case\n    using min_dnf_prop_atoms prop_atoms_notin(3) by force\nnext\n  case (Or_ltln \\<phi>1 \\<phi>2)\n  then show ?case\n    using min_dnf_prop_atoms prop_atoms_notin(4) by force\nqed auto\n\nlemma min_dnf_min_set[simp]:\n  \"min_set (min_dnf \\<phi>) = min_dnf \\<phi>\"\n  apply2 (induction \\<phi>) by (simp_all add: min_set_def min_product_def min_union_def, blast+)\n\n\nlemma min_dnf_iff_prop_assignment_subset:\n  \"\\<A> \\<Turnstile>\\<^sub>P \\<phi> \\<longleftrightarrow> (\\<exists>B. fset B \\<subseteq> \\<A> \\<and> B \\<in> min_dnf \\<phi>)\"\nproof\n  assume \"\\<A> \\<Turnstile>\\<^sub>P \\<phi>\"\n\n  then show \"\\<exists>B. fset B \\<subseteq> \\<A> \\<and> B \\<in> min_dnf \\<phi>\"\n  proof2 (induction \\<phi> arbitrary: \\<A>)\n    case (And_ltln \\<phi>\\<^sub>1 \\<phi>\\<^sub>2)\n\n    then obtain B\\<^sub>1 B\\<^sub>2 where 1: \"fset B\\<^sub>1 \\<subseteq> \\<A> \\<and> B\\<^sub>1 \\<in> min_dnf \\<phi>\\<^sub>1\" and 2: \"fset B\\<^sub>2 \\<subseteq> \\<A> \\<and> B\\<^sub>2 \\<in> min_dnf \\<phi>\\<^sub>2\"\n      by fastforce\n\n    then obtain C where \"C |\\<subseteq>| B\\<^sub>1 |\\<union>| B\\<^sub>2\" and \"C \\<in> min_dnf \\<phi>\\<^sub>1 \\<otimes>\\<^sub>m min_dnf \\<phi>\\<^sub>2\"\n      using min_product_comp by metis\n\n    then show ?case\n      by (metis 1 2 le_sup_iff min_dnf.simps(3) sup.absorb_iff1 sup_fset.rep_eq)\n  next\n    case (Or_ltln \\<phi>\\<^sub>1 \\<phi>\\<^sub>2)\n\n    {\n      assume \"\\<A> \\<Turnstile>\\<^sub>P \\<phi>\\<^sub>1\"\n\n      then obtain B where 1: \"fset B \\<subseteq> \\<A> \\<and> B \\<in> min_dnf \\<phi>\\<^sub>1\"\n        using Or_ltln by fastforce\n\n      then obtain C where \"C |\\<subseteq>| B\" and \"C \\<in> min_dnf \\<phi>\\<^sub>1 \\<union>\\<^sub>m min_dnf \\<phi>\\<^sub>2\"\n        using min_union_comp by metis\n\n      then have ?case\n        by (metis 1 dual_order.trans less_eq_fset.rep_eq min_dnf.simps(4))\n    }\n\n    moreover\n\n    {\n      assume \"\\<A> \\<Turnstile>\\<^sub>P \\<phi>\\<^sub>2\"\n\n      then obtain B where 2: \"fset B \\<subseteq> \\<A> \\<and> B \\<in> min_dnf \\<phi>\\<^sub>2\"\n        using Or_ltln by fastforce\n\n      then obtain C where \"C |\\<subseteq>| B\" and \"C \\<in> min_dnf \\<phi>\\<^sub>1 \\<union>\\<^sub>m min_dnf \\<phi>\\<^sub>2\"\n        using min_union_comp min_union_comm by metis\n\n      then have ?case\n        by (metis 2 dual_order.trans less_eq_fset.rep_eq min_dnf.simps(4))\n    }\n\n    ultimately show ?case\n      using Or_ltln.prems by auto\n  qed simp_all\nnext\n  assume \"\\<exists>B. fset B \\<subseteq> \\<A> \\<and> B \\<in> min_dnf \\<phi>\"\n\n  then obtain B where \"fset B \\<subseteq> \\<A>\" and \"B \\<in> min_dnf \\<phi>\"\n    by auto\n\n  then have \"fset B \\<Turnstile>\\<^sub>P \\<phi>\"\n    apply2 (induction \\<phi> arbitrary: B) by (auto simp: min_set_def min_product_def product_def min_union_def, blast+)\n\n  then show \"\\<A> \\<Turnstile>\\<^sub>P \\<phi>\"\n    using \\<open>fset B \\<subseteq> \\<A>\\<close> by blast\nqed\n\n\nlemma ltl_prop_implies_min_dnf:\n  \"\\<phi> \\<longrightarrow>\\<^sub>P \\<psi> = (\\<forall>A \\<in> min_dnf \\<phi>. \\<exists>B \\<in> min_dnf \\<psi>. B |\\<subseteq>| A)\"\n  by (meson less_eq_fset.rep_eq ltl_prop_implies_def min_dnf_iff_prop_assignment_subset order_refl dual_order.trans)\n\nlemma ltl_prop_equiv_min_dnf:\n  \"\\<phi> \\<sim>\\<^sub>P \\<psi> = (min_dnf \\<phi> = min_dnf \\<psi>)\"\nproof\n  assume \"\\<phi> \\<sim>\\<^sub>P \\<psi>\"\n\n  then have \"\\<And>x. x \\<in> min_set (min_dnf \\<phi>) \\<longleftrightarrow> x \\<in> min_set (min_dnf \\<psi>)\"\n    unfolding ltl_prop_implies_equiv ltl_prop_implies_min_dnf min_set_iff\n    by fastforce\n\n  then show \"min_dnf \\<phi> = min_dnf \\<psi>\"\n    by auto\nqed (simp add: ltl_prop_equiv_def min_dnf_iff_prop_assignment_subset)\n\n\n\n\nsubsection \\<open>Folding of \\<open>and\\<^sub>n\\<close> and \\<open>or\\<^sub>n\\<close> over Finite Sets\\<close>\n\ndefinition And\\<^sub>n :: \"'a ltln set \\<Rightarrow> 'a ltln\"\nwhere\n  \"And\\<^sub>n \\<Phi> \\<equiv> SOME \\<phi>. fold_graph And_ltln True_ltln \\<Phi> \\<phi>\"\n\ndefinition Or\\<^sub>n :: \"'a ltln set \\<Rightarrow> 'a ltln\"\nwhere\n  \"Or\\<^sub>n \\<Phi> \\<equiv> SOME \\<phi>. fold_graph Or_ltln False_ltln \\<Phi> \\<phi>\"\n\nlemma fold_graph_And\\<^sub>n:\n  \"finite \\<Phi> \\<Longrightarrow> fold_graph And_ltln True_ltln \\<Phi> (And\\<^sub>n \\<Phi>)\"\n  unfolding And\\<^sub>n_def by (rule someI2_ex[OF finite_imp_fold_graph])\n\nlemma fold_graph_Or\\<^sub>n:\n  \"finite \\<Phi> \\<Longrightarrow> fold_graph Or_ltln False_ltln \\<Phi> (Or\\<^sub>n \\<Phi>)\"\n  unfolding Or\\<^sub>n_def by (rule someI2_ex[OF finite_imp_fold_graph])\n\nlemma Or\\<^sub>n_empty[simp]:\n  \"Or\\<^sub>n {} = False_ltln\"\n  by (metis empty_fold_graphE finite.emptyI fold_graph_Or\\<^sub>n)\n\nlemma And\\<^sub>n_empty[simp]:\n  \"And\\<^sub>n {} = True_ltln\"\n  by (metis empty_fold_graphE finite.emptyI fold_graph_And\\<^sub>n)\n\ninterpretation dnf_union_thms: Finite_Set.comp_fun_commute \"\\<lambda>\\<phi>. (\\<union>) (f \\<phi>)\"\n  by unfold_locales fastforce\n\ninterpretation dnf_product_thms: Finite_Set.comp_fun_commute \"\\<lambda>\\<phi>. (\\<otimes>) (f \\<phi>)\"\n  by unfold_locales (simp add: product_set_thms.comp_fun_commute)\n\n\\<comment> \\<open>Copied from locale @{locale comp_fun_commute}\\<close>\n\n\n\ntext \\<open>Taking the DNF of @{const And\\<^sub>n} and @{const Or\\<^sub>n} is the same as folding over the individual DNFs.\\<close>\n\nlemma And\\<^sub>n_dnf:\n  \"finite \\<Phi> \\<Longrightarrow> dnf (And\\<^sub>n \\<Phi>) = Finite_Set.fold (\\<lambda>\\<phi>. (\\<otimes>) (dnf \\<phi>)) {{||}} \\<Phi>\"\n  apply (drule fold_graph_And\\<^sub>n) proof2 (induction rule: fold_graph.induct)(*Yutaka rewrote this for evaluation. Originally, it was: proof (drule fold_graph_And\\<^sub>n, induction rule: fold_graph.induct)*)\n  case (insertI x A y)\n\n  then have \"finite A\"\n    using fold_graph_finite by fast\n\n  then show ?case\n    using insertI by auto\nqed simp\n\nlemma Or\\<^sub>n_dnf:\n  \"finite \\<Phi> \\<Longrightarrow> dnf (Or\\<^sub>n \\<Phi>) = Finite_Set.fold (\\<lambda>\\<phi>. (\\<union>) (dnf \\<phi>)) {} \\<Phi>\"\n  apply (drule fold_graph_Or\\<^sub>n)proof2(induction rule: fold_graph.induct)(*Yutaka rewrote this for evaluation. Originally, it was: proof (drule fold_graph_Or\\<^sub>n, induction rule: fold_graph.induct)*)\n  case (insertI x A y)\n\n  then have \"finite A\"\n    using fold_graph_finite by fast\n\n  then show ?case\n    using insertI by auto\nqed simp\n\n\ntext \\<open>@{const And\\<^sub>n} and @{const Or\\<^sub>n} are injective on finite sets.\\<close>\n\nlemma And\\<^sub>n_inj:\n  \"inj_on And\\<^sub>n {s. finite s}\"\nproof (standard, simp)\n  fix x y :: \"'a ltln set\"\n  assume \"finite x\" and \"finite y\"\n\n  then have 1: \"fold_graph And_ltln True_ltln x (And\\<^sub>n x)\" and 2: \"fold_graph And_ltln True_ltln y (And\\<^sub>n y)\"\n    using fold_graph_And\\<^sub>n by blast+\n\n  assume \"And\\<^sub>n x = And\\<^sub>n y\"\n\n  with 1 show \"x = y\"\n  proof2 (induction rule: fold_graph.induct)\n    case emptyI\n    then show ?case\n      using 2 fold_graph.cases by force\n  next\n    case (insertI x A y)\n    with 2 show ?case\n    proof2 (induction arbitrary: x A y rule: fold_graph.induct)\n      case (insertI x A y)\n      then show ?case\n        by (metis fold_graph.cases insertI1 ltln.distinct(7) ltln.inject(3))\n    qed blast\n  qed\nqed\n\nlemma Or\\<^sub>n_inj:\n  \"inj_on Or\\<^sub>n {s. finite s}\"\nproof (standard, simp)\n  fix x y :: \"'a ltln set\"\n  assume \"finite x\" and \"finite y\"\n\n  then have 1: \"fold_graph Or_ltln False_ltln x (Or\\<^sub>n x)\" and 2: \"fold_graph Or_ltln False_ltln y (Or\\<^sub>n y)\"\n    using fold_graph_Or\\<^sub>n by blast+\n\n  assume \"Or\\<^sub>n x = Or\\<^sub>n y\"\n\n  with 1 show \"x = y\"\n  proof2 (induction rule: fold_graph.induct)\n    case emptyI\n    then show ?case\n      using 2 fold_graph.cases by force\n  next\n    case (insertI x A y)\n    with 2 show ?case\n    proof2 (induction arbitrary: x A y rule: fold_graph.induct)\n      case (insertI x A y)\n      then show ?case\n        by (metis fold_graph.cases insertI1 ltln.distinct(27) ltln.inject(4))\n    qed blast\n  qed\nqed\n\n\ntext \\<open>The semantics of @{const And\\<^sub>n} and @{const Or\\<^sub>n} can be expressed using quantifiers.\\<close>\n\nlemma And\\<^sub>n_semantics:\n  \"finite \\<Phi> \\<Longrightarrow> w \\<Turnstile>\\<^sub>n And\\<^sub>n \\<Phi> \\<longleftrightarrow> (\\<forall>\\<phi> \\<in> \\<Phi>. w \\<Turnstile>\\<^sub>n \\<phi>)\"\nproof -\n  assume \"finite \\<Phi>\"\n  have \"\\<And>\\<psi>. fold_graph And_ltln True_ltln \\<Phi> \\<psi> \\<Longrightarrow> w \\<Turnstile>\\<^sub>n \\<psi> \\<longleftrightarrow> (\\<forall>\\<phi> \\<in> \\<Phi>. w \\<Turnstile>\\<^sub>n \\<phi>)\"\n    by (rule fold_graph.induct) auto\n  then show ?thesis\n    using fold_graph_And\\<^sub>n[OF \\<open>finite \\<Phi>\\<close>] by simp\nqed\n\nlemma Or\\<^sub>n_semantics:\n  \"finite \\<Phi> \\<Longrightarrow> w \\<Turnstile>\\<^sub>n Or\\<^sub>n \\<Phi> \\<longleftrightarrow> (\\<exists>\\<phi> \\<in> \\<Phi>. w \\<Turnstile>\\<^sub>n \\<phi>)\"\nproof -\n  assume \"finite \\<Phi>\"\n  have \"\\<And>\\<psi>. fold_graph Or_ltln False_ltln \\<Phi> \\<psi> \\<Longrightarrow> w \\<Turnstile>\\<^sub>n \\<psi> \\<longleftrightarrow> (\\<exists>\\<phi> \\<in> \\<Phi>. w \\<Turnstile>\\<^sub>n \\<phi>)\"\n    by (rule fold_graph.induct) auto\n  then show ?thesis\n    using fold_graph_Or\\<^sub>n[OF \\<open>finite \\<Phi>\\<close>] by simp\nqed\n\nlemma And\\<^sub>n_prop_semantics:\n  \"finite \\<Phi> \\<Longrightarrow> \\<A> \\<Turnstile>\\<^sub>P And\\<^sub>n \\<Phi> \\<longleftrightarrow> (\\<forall>\\<phi> \\<in> \\<Phi>. \\<A> \\<Turnstile>\\<^sub>P \\<phi>)\"\nproof -\n  assume \"finite \\<Phi>\"\n  have \"\\<And>\\<psi>. fold_graph And_ltln True_ltln \\<Phi> \\<psi> \\<Longrightarrow> \\<A> \\<Turnstile>\\<^sub>P \\<psi> \\<longleftrightarrow> (\\<forall>\\<phi> \\<in> \\<Phi>. \\<A> \\<Turnstile>\\<^sub>P \\<phi>)\"\n    by (rule fold_graph.induct) auto\n  then show ?thesis\n    using fold_graph_And\\<^sub>n[OF \\<open>finite \\<Phi>\\<close>] by simp\nqed\n\nlemma Or\\<^sub>n_prop_semantics:\n  \"finite \\<Phi> \\<Longrightarrow> \\<A> \\<Turnstile>\\<^sub>P Or\\<^sub>n \\<Phi> \\<longleftrightarrow> (\\<exists>\\<phi> \\<in> \\<Phi>. \\<A> \\<Turnstile>\\<^sub>P \\<phi>)\"\nproof -\n  assume \"finite \\<Phi>\"\n  have \"\\<And>\\<psi>. fold_graph Or_ltln False_ltln \\<Phi> \\<psi> \\<Longrightarrow> \\<A> \\<Turnstile>\\<^sub>P \\<psi> \\<longleftrightarrow> (\\<exists>\\<phi> \\<in> \\<Phi>. \\<A> \\<Turnstile>\\<^sub>P \\<phi>)\"\n    by (rule fold_graph.induct) auto\n  then show ?thesis\n    using fold_graph_Or\\<^sub>n[OF \\<open>finite \\<Phi>\\<close>] by simp\nqed\n\nlemma Or\\<^sub>n_And\\<^sub>n_image_semantics:\n  assumes \"finite \\<A>\" and \"\\<And>\\<Phi>. \\<Phi> \\<in> \\<A> \\<Longrightarrow> finite \\<Phi>\"\n  shows \"w \\<Turnstile>\\<^sub>n Or\\<^sub>n (And\\<^sub>n ` \\<A>) \\<longleftrightarrow> (\\<exists>\\<Phi> \\<in> \\<A>. \\<forall>\\<phi> \\<in> \\<Phi>. w \\<Turnstile>\\<^sub>n \\<phi>)\"\nproof -\n  have \"w \\<Turnstile>\\<^sub>n Or\\<^sub>n (And\\<^sub>n ` \\<A>) \\<longleftrightarrow> (\\<exists>\\<Phi> \\<in> \\<A>. w \\<Turnstile>\\<^sub>n And\\<^sub>n \\<Phi>)\"\n    using Or\\<^sub>n_semantics assms by auto\n  then show ?thesis\n    using And\\<^sub>n_semantics assms by fast\nqed\n\nlemma Or\\<^sub>n_And\\<^sub>n_image_prop_semantics:\n  assumes \"finite \\<A>\" and \"\\<And>\\<Phi>. \\<Phi> \\<in> \\<A> \\<Longrightarrow> finite \\<Phi>\"\n  shows \"\\<I> \\<Turnstile>\\<^sub>P Or\\<^sub>n (And\\<^sub>n ` \\<A>) \\<longleftrightarrow> (\\<exists>\\<Phi> \\<in> \\<A>. \\<forall>\\<phi> \\<in> \\<Phi>. \\<I> \\<Turnstile>\\<^sub>P \\<phi>)\"\nproof -\n  have \"\\<I> \\<Turnstile>\\<^sub>P Or\\<^sub>n (And\\<^sub>n ` \\<A>) \\<longleftrightarrow> (\\<exists>\\<Phi> \\<in> \\<A>. \\<I> \\<Turnstile>\\<^sub>P And\\<^sub>n \\<Phi>)\"\n    using Or\\<^sub>n_prop_semantics assms by blast\n  then show ?thesis\n    using And\\<^sub>n_prop_semantics assms by metis\nqed\n\n\nsubsection \\<open>DNF to LTL conversion\\<close>\n\ndefinition ltln_of_dnf :: \"'a ltln fset set \\<Rightarrow> 'a ltln\"\nwhere\n  \"ltln_of_dnf \\<A> = Or\\<^sub>n (And\\<^sub>n ` fset ` \\<A>)\"\n\nlemma ltln_of_dnf_semantics:\n  assumes \"finite \\<A>\"\n  shows \"w \\<Turnstile>\\<^sub>n ltln_of_dnf \\<A> \\<longleftrightarrow> (\\<exists>\\<Phi> \\<in> \\<A>. \\<forall>\\<phi>. \\<phi> |\\<in>| \\<Phi> \\<longrightarrow> w \\<Turnstile>\\<^sub>n \\<phi>)\"\nproof -\n  have \"finite (fset ` \\<A>)\"\n    using assms by blast\n\n  then have \"w \\<Turnstile>\\<^sub>n ltln_of_dnf \\<A> \\<longleftrightarrow> (\\<exists>\\<Phi> \\<in> fset ` \\<A>. \\<forall>\\<phi> \\<in> \\<Phi>. w \\<Turnstile>\\<^sub>n \\<phi>)\"\n    unfolding ltln_of_dnf_def using Or\\<^sub>n_And\\<^sub>n_image_semantics by fastforce\n\n  then show ?thesis\n    by (metis image_iff notin_fset)\nqed\n\nlemma ltln_of_dnf_prop_semantics:\n  assumes \"finite \\<A>\"\n  shows \"\\<I> \\<Turnstile>\\<^sub>P ltln_of_dnf \\<A> \\<longleftrightarrow> (\\<exists>\\<Phi> \\<in> \\<A>. \\<forall>\\<phi>. \\<phi> |\\<in>| \\<Phi> \\<longrightarrow> \\<I> \\<Turnstile>\\<^sub>P \\<phi>)\"\nproof -\n  have \"finite (fset ` \\<A>)\"\n    using assms by blast\n\n  then have \"\\<I> \\<Turnstile>\\<^sub>P ltln_of_dnf \\<A> \\<longleftrightarrow> (\\<exists>\\<Phi> \\<in> fset ` \\<A>. \\<forall>\\<phi> \\<in> \\<Phi>. \\<I> \\<Turnstile>\\<^sub>P \\<phi>)\"\n    unfolding ltln_of_dnf_def using Or\\<^sub>n_And\\<^sub>n_image_prop_semantics by fastforce\n\n  then show ?thesis\n    by (metis image_iff notin_fset)\nqed\n\nlemma ltln_of_dnf_prop_equiv:\n  \"ltln_of_dnf (min_dnf \\<phi>) \\<sim>\\<^sub>P \\<phi>\"\n  unfolding ltl_prop_equiv_def\nproof\n  fix \\<A>\n  have \"\\<A> \\<Turnstile>\\<^sub>P ltln_of_dnf (min_dnf \\<phi>) \\<longleftrightarrow> (\\<exists>\\<Phi> \\<in> min_dnf \\<phi>. \\<forall>\\<phi>. \\<phi> |\\<in>| \\<Phi> \\<longrightarrow> \\<A> \\<Turnstile>\\<^sub>P \\<phi>)\"\n    using ltln_of_dnf_prop_semantics min_dnf_finite by metis\n  also have \"\\<dots> \\<longleftrightarrow> (\\<exists>\\<Phi> \\<in> min_dnf \\<phi>. fset \\<Phi> \\<subseteq> \\<A>)\"\n    by (metis min_dnf_prop_atoms prop_atoms_entailment_iff notin_fset subset_eq)\n  also have \"\\<dots> \\<longleftrightarrow> \\<A> \\<Turnstile>\\<^sub>P \\<phi>\"\n    using min_dnf_iff_prop_assignment_subset by blast\n  finally show \"\\<A> \\<Turnstile>\\<^sub>P ltln_of_dnf (min_dnf \\<phi>) = \\<A> \\<Turnstile>\\<^sub>P \\<phi>\" .\nqed\n\nlemma min_dnf_ltln_of_dnf[simp]:\n  \"min_dnf (ltln_of_dnf (min_dnf \\<phi>)) = min_dnf \\<phi>\"\n  using ltl_prop_equiv_min_dnf ltln_of_dnf_prop_equiv by blast\n\n\nsubsection \\<open>Substitution in DNF formulas\\<close>\n\ndefinition subst_clause :: \"'a ltln fset \\<Rightarrow> ('a ltln \\<rightharpoonup> 'a ltln) \\<Rightarrow> 'a ltln fset set\"\nwhere\n  \"subst_clause \\<Phi> m = \\<Otimes>\\<^sub>m {min_dnf (subst \\<phi> m) | \\<phi>. \\<phi> \\<in> fset \\<Phi>}\"\n\ndefinition subst_dnf :: \"'a ltln fset set \\<Rightarrow> ('a ltln \\<rightharpoonup> 'a ltln) \\<Rightarrow> 'a ltln fset set\"\nwhere\n  \"subst_dnf \\<A> m = (\\<Union>\\<Phi> \\<in> \\<A>. subst_clause \\<Phi> m)\"\n\nlemma subst_clause_empty[simp]:\n  \"subst_clause {||} m = {{||}}\"\n  by (simp add: subst_clause_def)\n\nlemma subst_dnf_empty[simp]:\n  \"subst_dnf {} m = {}\"\n  by (simp add: subst_dnf_def)\n\nlemma subst_clause_inner_finite:\n  \"finite {min_dnf (subst \\<phi> m) | \\<phi>. \\<phi> \\<in> \\<Phi>}\" if \"finite \\<Phi>\"\n  using that by simp\n\nlemma subst_clause_finite:\n  \"finite (subst_clause \\<Phi> m)\"\n  unfolding subst_clause_def\n  by (auto intro: min_dnf_finite min_product_set_finite)\n\nlemma subst_dnf_finite:\n  \"finite \\<A> \\<Longrightarrow> finite (subst_dnf \\<A> m)\"\n  unfolding subst_dnf_def using subst_clause_finite by blast\n\nlemma subst_dnf_mono:\n  \"\\<A> \\<subseteq> \\<B> \\<Longrightarrow> subst_dnf \\<A> m \\<subseteq> subst_dnf \\<B> m\"\n  unfolding subst_dnf_def by blast\n\nlemma subst_clause_min_set[simp]:\n  \"min_set (subst_clause \\<Phi> m) = subst_clause \\<Phi> m\"\n  unfolding subst_clause_def by simp\n\nlemma subst_clause_finsert[simp]:\n  \"subst_clause (finsert \\<phi> \\<Phi>) m = (min_dnf (subst \\<phi> m)) \\<otimes>\\<^sub>m (subst_clause \\<Phi> m)\"\nproof -\n  have \"{min_dnf (subst \\<psi> m) | \\<psi>. \\<psi> \\<in> fset (finsert \\<phi> \\<Phi>)}\n    = insert (min_dnf (subst \\<phi> m)) {min_dnf (subst \\<psi> m) | \\<psi>. \\<psi> \\<in> fset \\<Phi>}\"\n    by auto\n\n  then show ?thesis\n    by (simp add: subst_clause_def)\nqed\n\nlemma subst_clause_funion[simp]:\n  \"subst_clause (\\<Phi> |\\<union>| \\<Psi>) m = (subst_clause \\<Phi> m) \\<otimes>\\<^sub>m (subst_clause \\<Psi> m)\"\nproof2 (induction \\<Psi>)\n  case (insert x F)\n  then show ?case\n    using min_product_set_thms.fun_left_comm by fastforce\nqed simp\n\n\ntext \\<open>For the proof of correctness, we redefine the @{const product} operator on lists.\\<close>\n\ndefinition list_product :: \"'a list set \\<Rightarrow> 'a list set \\<Rightarrow> 'a list set\" (infixl \"\\<otimes>\\<^sub>l\" 65)\nwhere\n  \"A \\<otimes>\\<^sub>l B = {a @ b | a b. a \\<in> A \\<and> b \\<in> B}\"\n\nlemma list_product_fset_of_list[simp]:\n  \"fset_of_list ` (A \\<otimes>\\<^sub>l B) = (fset_of_list ` A) \\<otimes> (fset_of_list ` B)\"\n  unfolding list_product_def product_def image_def by fastforce\n\nlemma list_product_finite:\n  \"finite A \\<Longrightarrow> finite B \\<Longrightarrow> finite (A \\<otimes>\\<^sub>l B)\"\n  unfolding list_product_def by (simp add: finite_image_set2)\n\nlemma list_product_iff:\n  \"x \\<in> A \\<otimes>\\<^sub>l B \\<longleftrightarrow> (\\<exists>a b. a \\<in> A \\<and> b \\<in> B \\<and> x = a @ b)\"\n  unfolding list_product_def by blast\n\nlemma list_product_assoc[simp]:\n  \"A \\<otimes>\\<^sub>l (B \\<otimes>\\<^sub>l C) = A \\<otimes>\\<^sub>l B \\<otimes>\\<^sub>l C\"\n  unfolding set_eq_iff list_product_iff by fastforce\n\n\ntext \\<open>Furthermore, we introduct DNFs where the clauses are represented as lists.\\<close>\n\nfun list_dnf :: \"'a ltln \\<Rightarrow> 'a ltln list set\"\nwhere\n  \"list_dnf true\\<^sub>n = {[]}\"\n| \"list_dnf false\\<^sub>n = {}\"\n| \"list_dnf (\\<phi> and\\<^sub>n \\<psi>) = (list_dnf \\<phi>) \\<otimes>\\<^sub>l (list_dnf \\<psi>)\"\n| \"list_dnf (\\<phi> or\\<^sub>n \\<psi>) = (list_dnf \\<phi>) \\<union> (list_dnf \\<psi>)\"\n| \"list_dnf \\<phi> = {[\\<phi>]}\"\n\ndefinition list_dnf_to_dnf :: \"'a list set \\<Rightarrow> 'a fset set\"\nwhere\n  \"list_dnf_to_dnf X = fset_of_list ` X\"\n\nlemma list_dnf_to_dnf_list_dnf[simp]:\n  \"list_dnf_to_dnf (list_dnf \\<phi>) = dnf \\<phi>\"\n  apply2 (induction \\<phi>) by (simp_all add: list_dnf_to_dnf_def image_Un)\n\nlemma list_dnf_finite:\n  \"finite (list_dnf \\<phi>)\"\n  apply2 (induction \\<phi>) by (simp_all add: list_product_finite)\n\n\ntext \\<open>We use this to redefine @{const subst_clause} and @{const subst_dnf} on list DNFs.\\<close>\n\ndefinition subst_clause' :: \"'a ltln list \\<Rightarrow> ('a ltln \\<rightharpoonup> 'a ltln) \\<Rightarrow> 'a ltln list set\"\nwhere\n  \"subst_clause' \\<Phi> m = fold (\\<lambda>\\<phi> acc. acc \\<otimes>\\<^sub>l list_dnf (subst \\<phi> m)) \\<Phi> {[]}\"\n\ndefinition subst_dnf' :: \"'a ltln list set \\<Rightarrow> ('a ltln \\<rightharpoonup> 'a ltln) \\<Rightarrow> 'a ltln list set\"\nwhere\n  \"subst_dnf' \\<A> m = (\\<Union>\\<Phi> \\<in> \\<A>. subst_clause' \\<Phi> m)\"\n\nlemma subst_clause'_finite:\n  \"finite (subst_clause' \\<Phi> m)\"\n  apply2 (induction \\<Phi> rule: rev_induct) by (simp_all add: subst_clause'_def list_dnf_finite list_product_finite)\n\nlemma subst_clause'_nil[simp]:\n  \"subst_clause' [] m = {[]}\"\n  by (simp add: subst_clause'_def)\n\nlemma subst_clause'_cons[simp]:\n  \"subst_clause' (xs @ [x]) m = subst_clause' xs m \\<otimes>\\<^sub>l list_dnf (subst x m)\"\n  by (simp add: subst_clause'_def)\n\nlemma subst_clause'_append[simp]:\n  \"subst_clause' (A @ B) m = subst_clause' A m \\<otimes>\\<^sub>l subst_clause' B m\"\nproof2 (induction B rule: rev_induct)\n  case (snoc x xs)\n  then show ?case\n    by simp (metis append_assoc subst_clause'_cons)\nqed(simp add: list_product_def)\n\n\nlemma subst_dnf'_iff:\n  \"x \\<in> subst_dnf' A m \\<longleftrightarrow> (\\<exists>\\<Phi> \\<in> A. x \\<in> subst_clause' \\<Phi> m)\"\n  by (simp add: subst_dnf'_def)\n\nlemma subst_dnf'_product:\n  \"subst_dnf' (A \\<otimes>\\<^sub>l B) m = (subst_dnf' A m) \\<otimes>\\<^sub>l (subst_dnf' B m)\" (is \"?lhs = ?rhs\")\nproof (unfold set_eq_iff, safe)\n  fix x\n  assume \"x \\<in> ?lhs\"\n\n  then obtain \\<Phi> where \"\\<Phi> \\<in> A \\<otimes>\\<^sub>l B\" and \"x \\<in> subst_clause' \\<Phi> m\"\n    unfolding subst_dnf'_iff by blast\n\n  then obtain a b where \"a \\<in> A\" and \"b \\<in> B\" and \"\\<Phi> = a @ b\"\n    unfolding list_product_def by blast\n\n  then have \"x \\<in> (subst_clause' a m) \\<otimes>\\<^sub>l (subst_clause' b m)\"\n    using \\<open>x \\<in> subst_clause' \\<Phi> m\\<close> by simp\n\n  then obtain a' b' where \"a' \\<in> subst_clause' a m\" and \"b' \\<in> subst_clause' b m\" and \"x = a' @ b'\"\n    unfolding list_product_iff by blast\n\n  then have \"a' \\<in> subst_dnf' A m\" and \"b' \\<in> subst_dnf' B m\"\n    unfolding subst_dnf'_iff using \\<open>a \\<in> A\\<close> \\<open>b \\<in> B\\<close> by auto\n\n  then have \"\\<exists>a\\<in>subst_dnf' A m. \\<exists>b\\<in>subst_dnf' B m. x = a @ b\"\n    using \\<open>x = a' @ b'\\<close> by blast\n\n  then show \"x \\<in> ?rhs\"\n    unfolding list_product_iff by blast\nnext\n  fix x\n  assume \"x \\<in> ?rhs\"\n\n  then obtain a b where \"a \\<in> subst_dnf' A m\" and \"b \\<in> subst_dnf' B m\" and \"x = a @ b\"\n    unfolding list_product_iff by blast\n\n  then obtain a' b' where \"a' \\<in> A\" and \"b' \\<in> B\" and a: \"a \\<in> subst_clause' a' m\" and b: \"b \\<in> subst_clause' b' m\"\n    unfolding subst_dnf'_iff by blast\n\n  then have \"x \\<in> (subst_clause' a' m) \\<otimes>\\<^sub>l (subst_clause' b' m)\"\n    unfolding list_product_iff using \\<open>x = a @ b\\<close> by blast\n\n  moreover\n\n  have \"a' @ b' \\<in> A \\<otimes>\\<^sub>l B\"\n    unfolding list_product_iff using \\<open>a' \\<in> A\\<close> \\<open>b' \\<in> B\\<close> by blast\n\n  ultimately show \"x \\<in> ?lhs\"\n    unfolding subst_dnf'_iff by force\nqed\n\nlemma subst_dnf'_list_dnf:\n  \"subst_dnf' (list_dnf \\<phi>) m = list_dnf (subst \\<phi> m)\"\nproof2 (induction \\<phi>)\n  case (And_ltln \\<phi>1 \\<phi>2)\n  then show ?case\n    by (simp add: subst_dnf'_product)\nqed (simp_all add: subst_dnf'_def subst_clause'_def list_product_def)\n\n\nlemma min_set_Union:\n  \"finite X \\<Longrightarrow> min_set (\\<Union> (min_set ` X)) = min_set (\\<Union> X)\" for X :: \"'a fset set set\"\n  apply2 (induction X rule: finite_induct) by (force, metis Sup_insert image_insert min_set_min_union min_union_def)\n\nlemma min_set_Union_image:\n  \"finite X \\<Longrightarrow> min_set (\\<Union>x \\<in> X. min_set (f x)) = min_set (\\<Union>x \\<in> X. f x)\" for f :: \"'b \\<Rightarrow> 'a fset set\"\nproof -\n  assume \"finite X\"\n\n  then have *: \"finite (f ` X)\" by auto\n\n  with min_set_Union show ?thesis\n    unfolding image_image by fastforce\nqed\n\nlemma subst_clause_fset_of_list:\n  \"subst_clause (fset_of_list \\<Phi>) m = min_set (list_dnf_to_dnf (subst_clause' \\<Phi> m))\"\n  unfolding list_dnf_to_dnf_def subst_clause'_def\nproof2 (induction \\<Phi> rule: rev_induct)\n  case (snoc x xs)\n  then show ?case\n    by simp (metis (no_types, lifting) dnf_min_set list_dnf_to_dnf_def list_dnf_to_dnf_list_dnf min_product_comm min_product_def min_set_min_product(1))\nqed simp\n\nlemma min_set_list_dnf_to_dnf_subst_dnf':\n  \"finite X \\<Longrightarrow> min_set (list_dnf_to_dnf (subst_dnf' X m)) = min_set (subst_dnf (list_dnf_to_dnf X) m)\"\n  by (simp add: subst_dnf'_def subst_dnf_def subst_clause_fset_of_list list_dnf_to_dnf_def min_set_Union_image image_Union)\n\nlemma subst_dnf_dnf:\n  \"min_set (subst_dnf (dnf \\<phi>) m) = min_dnf (subst \\<phi> m)\"\n  unfolding dnf_min_set\n  unfolding list_dnf_to_dnf_list_dnf[symmetric]\n  unfolding subst_dnf'_list_dnf[symmetric]\n  unfolding min_set_list_dnf_to_dnf_subst_dnf'[OF list_dnf_finite]\n  by simp\n\n\ntext \\<open>This is almost the lemma we need. However, we need to show that the same holds for @{term \"min_dnf \\<phi>\"}, too.\\<close>\n\nlemma fold_product:\n  \"Finite_Set.fold (\\<lambda>x. (\\<otimes>) {{|x|}}) {{||}} (fset x) = {x}\"\n  apply2 (induction x) by (simp_all add: notin_fset, simp add: product_singleton_singleton)\n\nlemma fold_union:\n  \"Finite_Set.fold (\\<lambda>x. (\\<union>) {x}) {} (fset x) = fset x\"\n  apply2 (induction x) by (simp_all add: notin_fset comp_fun_idem.fold_insert_idem comp_fun_idem_insert)\n\nlemma fold_union_fold_product:\n  assumes \"finite X\" and \"\\<And>\\<Psi> \\<psi>. \\<Psi> \\<in> X \\<Longrightarrow> \\<psi> \\<in> fset \\<Psi> \\<Longrightarrow> dnf \\<psi> = {{|\\<psi>|}}\"\n  shows \"Finite_Set.fold (\\<lambda>x. (\\<union>) (Finite_Set.fold (\\<lambda>\\<phi>. (\\<otimes>) (dnf \\<phi>)) {{||}} (fset x))) {} X = X\" (is \"?lhs = X\")\nproof -\n  from assms have \"?lhs = Finite_Set.fold (\\<lambda>x. (\\<union>) (Finite_Set.fold (\\<lambda>\\<phi>. (\\<otimes>) {{|\\<phi>|}}) {{||}} (fset x))) {} X\"\n  proof2 (induction X rule: finite_induct)\n    case (insert \\<Phi> X)\n\n    from insert.prems have 1: \"\\<And>\\<Psi> \\<psi>. \\<lbrakk>\\<Psi> \\<in> X; \\<psi> \\<in> fset \\<Psi>\\<rbrakk> \\<Longrightarrow> dnf \\<psi> = {{|\\<psi>|}}\"\n      by force\n\n    from insert.prems have \"Finite_Set.fold (\\<lambda>\\<phi>. (\\<otimes>) (dnf \\<phi>)) {{||}} (fset \\<Phi>) = Finite_Set.fold (\\<lambda>\\<phi>. (\\<otimes>) {{|\\<phi>|}}) {{||}} (fset \\<Phi>)\"\n      apply2 (induction \\<Phi>) by (force simp: notin_fset)+\n\n    with insert 1 show ?case\n      by simp\n  qed simp\n\n  with \\<open>finite X\\<close> show ?thesis\n    unfolding fold_product by (metis fset_to_fset fold_union)\nqed\n\nlemma dnf_ltln_of_dnf_min_dnf:\n  \"dnf (ltln_of_dnf (min_dnf \\<phi>)) = min_dnf \\<phi>\"\nproof -\n  have 1: \"finite (And\\<^sub>n ` fset ` min_dnf \\<phi>)\"\n    using min_dnf_finite by blast\n\n  have 2: \"inj_on And\\<^sub>n (fset ` min_dnf \\<phi>)\"\n    by (metis (mono_tags, lifting) And\\<^sub>n_inj f_inv_into_f fset inj_onI inj_on_contraD)\n\n  have 3: \"inj_on fset (min_dnf \\<phi>)\"\n    by (meson fset_inject inj_onI)\n\n  show ?thesis\n    unfolding ltln_of_dnf_def\n    unfolding Or\\<^sub>n_dnf[OF 1]\n    unfolding fold_image[OF 2]\n    unfolding fold_image[OF 3]\n    unfolding comp_def\n    unfolding And\\<^sub>n_dnf[OF finite_fset]\n    by (metis fold_union_fold_product min_dnf_finite min_dnf_atoms_dnf)\nqed\n\nlemma min_dnf_subst:\n  \"min_set (subst_dnf (min_dnf \\<phi>) m) = min_dnf (subst \\<phi> m)\" (is \"?lhs = ?rhs\")\nproof -\n  let ?\\<phi>' = \"ltln_of_dnf (min_dnf \\<phi>)\"\n\n  have \"?lhs = min_set (subst_dnf (dnf ?\\<phi>') m)\"\n    unfolding dnf_ltln_of_dnf_min_dnf ..\n\n  also have \"\\<dots> = min_dnf (subst ?\\<phi>' m)\"\n    unfolding subst_dnf_dnf ..\n\n  also have \"\\<dots> = min_dnf (subst \\<phi> m)\"\n    using ltl_prop_equiv_min_dnf ltln_of_dnf_prop_equiv subst_respects_ltl_prop_entailment(2) by blast\n\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/Evaluation_PLDI_Small/LTL/Disjunctive_Normal_Form.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8705972616934408, "lm_q2_score": 0.8221891348788759, "lm_q1q2_score": 0.7157956094196484}}
{"text": "(*  \n    Author:      Ren\u00e9 Thiemann \n                 Akihisa Yamada\n    License:     BSD\n*)\nsection \\<open>Complex Roots of Real Valued Polynomials\\<close>\n\ntext \\<open>We provide conversion functions between polynomials over the real and the complex numbers,\n  and prove that the complex roots of real-valued polynomial always come in conjugate pairs.\n  We further show that also the order of the complex conjugate roots is identical.\n\n  As a consequence, we derive that every real-valued polynomial can be factored into real factors of \n  degree at most 2, and we prove that every polynomial over the reals with odd degree has a real\n  root.\\<close>\n\ntheory Complex_Roots_Real_Poly\nimports \n  \"HOL-Computational_Algebra.Fundamental_Theorem_Algebra\"\n  Polynomial_Factorization.Order_Polynomial\n  Polynomial_Factorization.Explicit_Roots\n  Polynomial_Interpolation.Ring_Hom_Poly\nbegin\n\ninterpretation of_real_poly_hom: map_poly_idom_hom complex_of_real..\n\nlemma real_poly_real_coeff: assumes \"set (coeffs p) \\<subseteq> \\<real>\"\n  shows \"coeff p x \\<in> \\<real>\"\nproof -\n  have \"coeff p x \\<in> range (coeff p)\" by auto\n  from this[unfolded range_coeff] assms show ?thesis by auto\nqed\n\n\nlemma complex_conjugate_root: \n  assumes real: \"set (coeffs p) \\<subseteq> \\<real>\" and rt: \"poly p c = 0\"\n  shows \"poly p (cnj c) = 0\"\nproof -\n  let ?c = \"cnj c\"\n  {\n    fix x\n    have \"coeff p x \\<in> \\<real>\" \n      by (rule real_poly_real_coeff[OF real]) \n    hence \"cnj (coeff p x) = coeff p x\" by (cases \"coeff p x\", auto)\n  } note cnj_coeff = this\n  have \"poly p ?c = poly (\\<Sum>x\\<le>degree p. monom (coeff p x) x) ?c\"\n    unfolding poly_as_sum_of_monoms ..\n  also have \"\\<dots> = (\\<Sum>x\\<le>degree p . coeff p x * cnj (c ^ x))\"\n    unfolding poly_sum poly_monom complex_cnj_power ..\n  also have \"\\<dots> = (\\<Sum>x\\<le>degree p . cnj (coeff p x * c ^ x))\"\n    unfolding complex_cnj_mult cnj_coeff ..\n  also have \"\\<dots> = cnj (\\<Sum>x\\<le>degree p . coeff p x * c ^ x)\"\n    unfolding cnj_sum ..\n  also have \"(\\<Sum>x\\<le>degree p . coeff p x * c ^ x) = \n    poly (\\<Sum>x\\<le>degree p. monom (coeff p x) x) c\"\n    unfolding poly_sum poly_monom ..\n  also have \"\\<dots> = 0\" unfolding poly_as_sum_of_monoms rt ..\n  also have \"cnj 0 = 0\" by simp\n  finally show ?thesis .\nqed\n\ncontext\n  fixes p :: \"complex poly\"\n  assumes coeffs: \"set (coeffs p) \\<subseteq> \\<real>\"\nbegin\nlemma map_poly_Re_poly: fixes x :: real \n  shows \"poly (map_poly Re p) x = poly p (of_real x)\"\nproof -\n  have id: \"map_poly (of_real o Re) p = p\"\n    by (rule map_poly_idI, insert coeffs, auto)\n  show ?thesis unfolding arg_cong[OF id, of poly, symmetric]\n    by (subst map_poly_map_poly[symmetric], auto)\nqed\n\nlemma map_poly_Re_coeffs:\n  \"coeffs (map_poly Re p) = map Re (coeffs p)\"\nproof (rule coeffs_map_poly)\n  have \"lead_coeff p \\<in> range (coeff p)\" by auto\n  hence x: \"lead_coeff p \\<in> \\<real>\" using coeffs by (auto simp: range_coeff)\n  show \"(Re (lead_coeff p) = 0) = (p = 0)\"\n    using of_real_Re[OF x] by auto\nqed\n\nlemma map_poly_Re_0: \"map_poly Re p = 0 \\<Longrightarrow> p = 0\"\n  using map_poly_Re_coeffs by auto\n\nend\n\n\nlemma real_poly_add: \n  assumes \"set (coeffs p) \\<subseteq> \\<real>\" \"set (coeffs q) \\<subseteq> \\<real>\"\n  shows \"set (coeffs (p + q)) \\<subseteq> \\<real>\" \nproof -\n  define pp where \"pp = coeffs p\" \n  define qq where \"qq = coeffs q\"\n  show ?thesis using assms\n  unfolding coeffs_plus_eq_plus_coeffs pp_def[symmetric] qq_def[symmetric]\n    by (induct pp qq rule: plus_coeffs.induct, auto simp: cCons_def)\nqed\n\nlemma real_poly_sum: \n  assumes \"\\<And> x. x \\<in> S \\<Longrightarrow> set (coeffs (f x)) \\<subseteq> \\<real>\"\n  shows \"set (coeffs (sum f S)) \\<subseteq> \\<real>\" \n  using assms\nproof (induct S rule: infinite_finite_induct)\n  case (insert x S) \n  hence id: \"sum f (insert x S) = f x + sum f S\" by auto\n  show ?case unfolding id\n    by (rule real_poly_add[OF _ insert(3)], insert insert, auto)\nqed auto\n\nlemma real_poly_smult: fixes p :: \"'a :: {idom,real_algebra_1} poly\"\n  assumes \"c \\<in> \\<real>\" \"set (coeffs p) \\<subseteq> \\<real>\"\n  shows \"set (coeffs (smult c p)) \\<subseteq> \\<real>\" \n  using assms by (auto simp: coeffs_smult)\n\nlemma real_poly_pCons: \n  assumes \"c \\<in> \\<real>\" \"set (coeffs p) \\<subseteq> \\<real>\"\n  shows \"set (coeffs (pCons c p)) \\<subseteq> \\<real>\" \n  using assms by (auto simp: cCons_def)\n\n\nlemma real_poly_mult: fixes p :: \"'a :: {idom,real_algebra_1} poly\"\n  assumes p: \"set (coeffs p) \\<subseteq> \\<real>\" and q: \"set (coeffs q) \\<subseteq> \\<real>\"\n  shows \"set (coeffs (p * q)) \\<subseteq> \\<real>\" using p\nproof (induct p)\n  case (pCons a p)\n  show ?case unfolding mult_pCons_left\n    by (intro real_poly_add real_poly_smult real_poly_pCons pCons(2) q,\n    insert pCons(1,3), auto simp: cCons_def if_splits)\nqed simp\n\nlemma real_poly_power: fixes p :: \"'a :: {idom,real_algebra_1} poly\"\n  assumes p: \"set (coeffs p) \\<subseteq> \\<real>\"\n  shows \"set (coeffs (p ^ n)) \\<subseteq> \\<real>\"\nproof (induct n)\n  case (Suc n)\n  from real_poly_mult[OF p this]\n  show ?case by simp\nqed simp\n\n\nlemma real_poly_prod: fixes f :: \"'a \\<Rightarrow> 'b :: {idom,real_algebra_1} poly\"\n  assumes \"\\<And> x. x \\<in> S \\<Longrightarrow> set (coeffs (f x)) \\<subseteq> \\<real>\"\n  shows \"set (coeffs (prod f S)) \\<subseteq> \\<real>\" \n  using assms\nproof (induct S rule: infinite_finite_induct)\n  case (insert x S) \n  hence id: \"prod f (insert x S) = f x * prod f S\" by auto\n  show ?case unfolding id\n    by (rule real_poly_mult[OF _ insert(3)], insert insert, auto)\nqed auto\n\nlemma real_poly_uminus: \n  assumes \"set (coeffs p) \\<subseteq> \\<real>\" \n  shows \"set (coeffs (-p)) \\<subseteq> \\<real>\" \n  using assms unfolding coeffs_uminus by auto\n\nlemma real_poly_minus: \n  assumes \"set (coeffs p) \\<subseteq> \\<real>\" \"set (coeffs q) \\<subseteq> \\<real>\"\n  shows \"set (coeffs (p - q)) \\<subseteq> \\<real>\" \n  using assms unfolding diff_conv_add_uminus\n  by (intro real_poly_uminus real_poly_add, auto)\n\nlemma fixes p :: \"'a :: real_field poly\" \n  assumes p: \"set (coeffs p) \\<subseteq> \\<real>\" and *: \"set (coeffs q) \\<subseteq> \\<real>\"\n  shows real_poly_div: \"set (coeffs (q div p)) \\<subseteq> \\<real>\"\n    and real_poly_mod: \"set (coeffs (q mod p)) \\<subseteq> \\<real>\"\nproof (atomize(full), insert *, induct q)\n  case 0\n  thus ?case by auto\nnext\n  case (pCons a q)\n  from pCons(1,3) have a: \"a \\<in> \\<real>\" and q: \"set (coeffs q) \\<subseteq> \\<real>\" by auto\n  note res = pCons\n  show ?case\n  proof (cases \"p = 0\")\n    case True\n    with res pCons(3) show ?thesis by auto\n  next\n    case False\n    from pCons have IH: \"set (coeffs (q div p)) \\<subseteq> \\<real>\" \"set (coeffs (q mod p)) \\<subseteq> \\<real>\" by auto\n    define c where \"c = coeff (pCons a (q mod p)) (degree p) / coeff p (degree p)\"\n    {\n      have \"coeff (pCons a (q mod p)) (degree p) \\<in> \\<real>\"\n        by (rule real_poly_real_coeff, insert IH a, intro real_poly_pCons)\n      moreover have \"coeff p (degree p) \\<in> \\<real>\" \n        by (rule real_poly_real_coeff[OF p])\n      ultimately have \"c \\<in> \\<real>\" unfolding c_def by simp\n    } note c = this\n    from False\n    have r: \"pCons a q div p = pCons c (q div p)\" and s: \"pCons a q mod p = pCons a (q mod p) - smult c p\" \n      unfolding c_def div_pCons_eq mod_pCons_eq by simp_all\n    show ?thesis unfolding r s using a p c IH by (intro conjI real_poly_pCons real_poly_minus real_poly_smult)\n  qed\nqed\n\nlemma real_poly_factor: fixes p :: \"'a :: real_field poly\"\n  assumes \"set (coeffs (p * q)) \\<subseteq> \\<real>\"\n   \"set (coeffs p) \\<subseteq> \\<real>\"\n  \"p \\<noteq> 0\"\n  shows \"set (coeffs q) \\<subseteq> \\<real>\" \nproof -\n  have \"q = p * q div p\" using \\<open>p \\<noteq> 0\\<close> by simp\n  hence id: \"coeffs q = coeffs (p * q div p)\" by simp\n  show ?thesis unfolding id\n    by (rule real_poly_div, insert assms, auto)\nqed\n\nlemma complex_conjugate_order: assumes real: \"set (coeffs p) \\<subseteq> \\<real>\"\n  \"p \\<noteq> 0\"\n  shows \"order (cnj c) p = order c p\"\nproof -\n  define n where \"n = degree p\"\n  have \"degree p \\<le> n\" unfolding n_def by auto\n  thus ?thesis using assms\n  proof (induct n arbitrary: p)\n    case (0 p)\n    {\n      fix x\n      have \"order x p \\<le> degree p\"\n        by (rule order_degree[OF 0(3)])\n      hence \"order x p = 0\" using 0 by auto\n    }\n    thus ?case by simp\n  next\n    case (Suc m p)\n    note order = order[OF \\<open>p \\<noteq> 0\\<close>]\n    let ?c = \"cnj c\"\n    show ?case\n    proof (cases \"poly p c = 0\")\n      case True note rt1 = this\n      from complex_conjugate_root[OF Suc(3) True]\n      have rt2: \"poly p ?c = 0\" .\n      show ?thesis\n      proof (cases \"c \\<in> \\<real>\")\n        case True\n        hence \"?c = c\" by (cases c, auto)\n        thus ?thesis by auto\n      next\n        case False\n        hence neq: \"?c \\<noteq> c\" by (simp add: Reals_cnj_iff)\n        let ?fac1 = \"[: -c, 1 :]\"\n        let ?fac2 = \"[: -?c, 1 :]\"\n        let ?fac = \"?fac1 * ?fac2\"\n        from rt1 have \"?fac1 dvd p\" unfolding poly_eq_0_iff_dvd .\n        from this[unfolded dvd_def] obtain q where p: \"p = ?fac1 * q\" by auto\n        from rt2[unfolded p poly_mult] neq have \"poly q ?c = 0\" by auto\n        hence \"?fac2 dvd q\" unfolding poly_eq_0_iff_dvd .\n        from this[unfolded dvd_def] obtain r where q: \"q = ?fac2 * r\" by auto\n        have p: \"p = ?fac * r\" unfolding p q by algebra\n        from \\<open>p \\<noteq> 0\\<close> have nz: \"?fac1 \\<noteq> 0\" \"?fac2 \\<noteq> 0\" \"?fac \\<noteq> 0\" \"r \\<noteq> 0\" unfolding p by auto\n        have id: \"?fac = [: ?c * c, - (?c + c), 1 :]\" by simp\n        have cfac: \"coeffs ?fac = [ ?c * c, - (?c + c), 1 ]\" unfolding id by simp\n        have cfac: \"set (coeffs ?fac) \\<subseteq> \\<real>\" unfolding cfac by (cases c, auto simp: Reals_cnj_iff)\n        have \"degree p = degree ?fac + degree r\" unfolding p\n          by (rule degree_mult_eq, insert nz, auto)\n        also have \"degree ?fac = degree ?fac1 + degree ?fac2\"\n          by (rule degree_mult_eq, insert nz, auto)\n        finally have \"degree p = 2 + degree r\" by simp\n        with Suc have deg: \"degree r \\<le> m\" by auto\n        from real_poly_factor[OF Suc(3)[unfolded p] cfac] nz  have \"set (coeffs r) \\<subseteq> \\<real>\" by auto\n        from Suc(1)[OF deg this \\<open>r \\<noteq> 0\\<close>] have IH: \"order ?c r = order c r\" .\n        {\n          fix cc\n          have \"order cc p = order cc ?fac + order cc r\" using \\<open>p \\<noteq> 0\\<close> unfolding p\n            by (rule order_mult)\n          also have \"order cc ?fac = order cc ?fac1 + order cc ?fac2\"\n            by (rule order_mult, rule nz)\n          also have \"order cc ?fac1 = (if cc = c then 1 else 0)\" \n            unfolding order_linear' by simp\n          also have \"order cc ?fac2 = (if cc = ?c then 1 else 0)\"\n            unfolding order_linear' by simp\n          finally have \"order cc p = \n            (if cc = c then 1 else 0) + (if cc = cnj c then 1 else 0) + order cc r\" .\n        } note order = this\n        show ?thesis unfolding order IH by auto\n      qed\n    next\n      case False note rt1 = this\n      {\n        assume \"poly p ?c = 0\"\n        from complex_conjugate_root[OF Suc(3) this] rt1\n        have False by auto\n      }\n      hence rt2: \"poly p ?c \\<noteq> 0\" by auto\n      from rt1 rt2 show ?thesis \n        unfolding order_root by simp\n    qed\n  qed\nqed\n\nlemma map_poly_of_real_Re: assumes \"set (coeffs p) \\<subseteq> \\<real>\"\n  shows \"map_poly of_real (map_poly Re p) = p\"\n  by (subst map_poly_map_poly, force+, rule map_poly_idI, insert assms, auto)\n\nlemma map_poly_Re_of_real: \"map_poly Re (map_poly of_real p) = p\"\n  by (subst map_poly_map_poly, force+, rule map_poly_idI, auto)\n\nlemma map_poly_Re_mult: assumes p: \"set (coeffs p) \\<subseteq> \\<real>\"\n  and q: \"set (coeffs q) \\<subseteq> \\<real>\" shows \"map_poly Re (p * q) = map_poly Re p * map_poly Re q\"\nproof -\n  let ?r = \"map_poly Re\"\n  let ?c = \"map_poly complex_of_real\"\n  have \"?r (p * q) = ?r (?c (?r p) * ?c (?r q))\" \n    unfolding map_poly_of_real_Re[OF p] map_poly_of_real_Re[OF q] by simp\n  also have \"?c (?r p) * ?c (?r q) = ?c (?r p * ?r q)\" by (simp add: hom_distribs)\n  also have \"?r \\<dots> = ?r p * ?r q\" unfolding map_poly_Re_of_real ..\n  finally show ?thesis .\nqed\n  \nlemma map_poly_Re_power: assumes p: \"set (coeffs p) \\<subseteq> \\<real>\"\n shows \"map_poly Re (p^n) = (map_poly Re p)^n\" \nproof (induct n)\n  case (Suc n)\n  let ?r = \"map_poly Re\"\n  have \"?r (p^Suc n) = ?r (p * p^n)\" by simp\n  also have \"\\<dots> = ?r p * ?r (p^n)\"\n    by (rule map_poly_Re_mult[OF p real_poly_power[OF p]])\n  also have \"?r (p^n) = (?r p)^n\" by (rule Suc)\n  finally show ?case by simp\nqed simp\n\nlemma real_degree_2_factorization_exists_complex: fixes p :: \"complex poly\"\n  assumes pR: \"set (coeffs p) \\<subseteq> \\<real>\"\n  shows \"\\<exists> qs. p = prod_list qs \\<and> (\\<forall> q \\<in> set qs. set (coeffs q) \\<subseteq> \\<real> \\<and> degree q \\<le> 2)\"\nproof -\n  obtain n where \"degree p = n\" by auto\n  thus ?thesis using pR\n  proof (induct n arbitrary: p rule: less_induct)\n    case (less n p)\n    hence pR: \"set (coeffs p) \\<subseteq> \\<real>\" by auto\n    show ?case\n    proof (cases \"n \\<le> 2\")\n      case True\n      thus ?thesis using pR\n        by (intro exI[of _ \"[p]\"], insert less(2), auto)\n    next\n      case False\n      hence degp: \"degree p \\<ge> 2\" using less(2) by auto\n      hence \"\\<not> constant (poly p)\" by (simp add: constant_degree)\n      from fundamental_theorem_of_algebra[OF this] obtain x where x: \"poly p x = 0\" by auto\n      from x have dvd: \"[: -x, 1 :] dvd p\" using poly_eq_0_iff_dvd by blast\n      have \"\\<exists> f. f dvd p \\<and> set (coeffs f) \\<subseteq> \\<real> \\<and> 1 \\<le> degree f \\<and> degree f \\<le> 2\"\n      proof (cases \"x \\<in> \\<real>\")\n        case True\n        with dvd show ?thesis \n          by (intro exI[of _ \"[: -x, 1:]\"], auto)\n      next\n        case False\n        let ?x = \"cnj x\"\n        let ?a = \"?x * x\"\n        let ?b = \"- ?x - x\"\n        from complex_conjugate_root[OF pR x]\n        have xx: \"poly p ?x = 0\" by auto\n        from False have diff: \"x \\<noteq> ?x\" by (simp add: Reals_cnj_iff)\n        from dvd obtain r where p: \"p = [: -x, 1 :] * r\" unfolding dvd_def by auto\n        from xx[unfolded this] diff have \"poly r ?x = 0\" by simp\n        hence \"[: -?x, 1 :] dvd r\" using poly_eq_0_iff_dvd by blast\n        then obtain s where r: \"r = [: -?x, 1 :] * s\" unfolding dvd_def by auto\n        have \"p = ([: -x, 1:] * [: -?x, 1 :]) * s\" unfolding p r by algebra\n        also have \"[: -x, 1:] * [: -?x, 1 :] = [: ?a, ?b, 1 :]\" by simp\n        finally have \"[: ?a, ?b, 1 :] dvd p\" unfolding dvd_def by auto\n        moreover have \"?a \\<in> \\<real>\" by (simp add: Reals_cnj_iff)\n        moreover have \"?b \\<in> \\<real>\" by (simp add: Reals_cnj_iff)\n        ultimately show ?thesis by (intro exI[of _ \"[:?a,?b,1:]\"], auto)\n      qed\n      then obtain f where dvd: \"f dvd p\" and fR: \"set (coeffs f) \\<subseteq> \\<real>\" and degf: \"1 \\<le> degree f\" \"degree f \\<le> 2\" by auto\n      from dvd obtain r where p: \"p = f * r\" unfolding dvd_def by auto\n      from degp have p0: \"p \\<noteq> 0\" by auto\n      with p have f0: \"f \\<noteq> 0\" and r0: \"r \\<noteq> 0\" by auto\n      from real_poly_factor[OF pR[unfolded p] fR f0] have rR: \"set (coeffs r) \\<subseteq> \\<real>\" .\n      have deg: \"degree p = degree f + degree r\" unfolding p\n        by (rule degree_mult_eq[OF f0 r0])\n      with degf less(2) have degr: \"degree r < n\" by auto        \n      from less(1)[OF this refl rR] obtain qs \n        where IH: \"r = prod_list qs\" \"(\\<forall>q\\<in>set qs. set (coeffs q) \\<subseteq> \\<real> \\<and> degree q \\<le> 2)\" by auto\n      from IH(1) have p: \"p = prod_list (f # qs)\" unfolding p by auto\n      with IH(2) fR degf show ?thesis\n        by (intro exI[of _ \"f # qs\"], auto)\n    qed\n  qed\nqed\n\nlemma real_degree_2_factorization_exists: fixes p :: \"real poly\"\n  shows \"\\<exists> qs. p = prod_list qs \\<and> (\\<forall> q \\<in> set qs. degree q \\<le> 2)\"\nproof -\n  let ?cp = \"map_poly complex_of_real\"\n  let ?rp = \"map_poly Re\"\n  let ?p = \"?cp p\"\n  have \"set (coeffs ?p) \\<subseteq> \\<real>\" by auto\n  from real_degree_2_factorization_exists_complex[OF this]\n  obtain qs where p: \"?p = prod_list qs\" and \n    qs: \"\\<And> q. q \\<in> set qs \\<Longrightarrow> set (coeffs q) \\<subseteq> \\<real> \\<and> degree q \\<le> 2\" by auto\n  have p: \"p = ?rp (prod_list qs)\" unfolding arg_cong[OF p, of ?rp, symmetric]\n    by (subst map_poly_map_poly, force, rule sym, rule map_poly_idI, auto)\n  from qs have \"\\<exists> rs. prod_list qs = ?cp (prod_list rs) \\<and> (\\<forall> r \\<in> set rs. degree r \\<le> 2)\"\n  proof (induct qs)\n    case Nil\n    show ?case by (auto intro!: exI[of _ Nil])\n  next\n    case (Cons q qs)\n    then obtain rs where qs: \"prod_list qs = ?cp (prod_list rs)\"\n      and rs: \"\\<And> q. q\\<in>set rs \\<Longrightarrow> degree q \\<le> 2\" by force+\n    from Cons(2)[of q] have q: \"set (coeffs q) \\<subseteq> \\<real>\" and dq: \"degree q \\<le> 2\" by auto\n    define r where \"r = ?rp q\"\n    have q: \"q = ?cp r\" unfolding r_def\n      by (subst map_poly_map_poly, force, rule sym, rule map_poly_idI, insert q, auto)\n    have dr: \"degree r \\<le> 2\" using dq unfolding q by (simp add: degree_map_poly)\n    show ?case\n      by (rule exI[of _ \"r # rs\"], unfold prod_list.Cons qs q, insert dr rs, auto simp: hom_distribs)\n  qed\n  then obtain rs where id: \"prod_list qs = ?cp (prod_list rs)\" and deg: \"\\<forall> r \\<in> set rs. degree r \\<le> 2\" by auto\n  show ?thesis unfolding p id\n    by (intro exI, rule conjI[OF _ deg], subst map_poly_map_poly, force, rule map_poly_idI, auto)\nqed\n    \n  \nlemma odd_degree_imp_real_root: assumes \"odd (degree p)\"\n  shows \"\\<exists> x. poly p x = (0 :: real)\"\nproof -\n  from real_degree_2_factorization_exists[of p] obtain qs where\n    id: \"p = prod_list qs\" and qs: \"\\<And> q. q \\<in> set qs \\<Longrightarrow> degree q \\<le> 2\" by auto\n  show ?thesis using assms qs unfolding id\n  proof (induct qs)\n    case (Cons q qs)\n    from Cons(3)[of q] have dq: \"degree q \\<le> 2\" by auto    \n    show ?case\n    proof (cases \"degree q = 1\")\n      case True\n      from roots1[OF this] show ?thesis by auto\n    next\n      case False\n      with dq have deg: \"degree q = 0 \\<or> degree q = 2\" by arith\n      from Cons(2) have \"q * prod_list qs \\<noteq> 0\" by fastforce\n      hence \"q \\<noteq> 0\" \"prod_list qs \\<noteq> 0\" by auto\n      from degree_mult_eq[OF this]\n      have \"degree (prod_list (q # qs)) = degree q + degree (prod_list qs)\" by simp\n      from Cons(2)[unfolded this] deg have \"odd (degree (prod_list qs))\" by auto\n      from Cons(1)[OF this Cons(3)] obtain x where \"poly (prod_list qs) x = 0\" by auto\n      thus ?thesis by auto\n    qed\n  qed 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/Algebraic_Numbers/Complex_Roots_Real_Poly.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8221891218080991, "lm_q2_score": 0.8705972566572503, "lm_q1q2_score": 0.7157955938995649}}
{"text": "(* Author: Tobias Nipkow *)\n\nsection \\<open>Leftist Heap\\<close>\n\ntheory Leftist_Heap\nimports\n  \"HOL-Library.Pattern_Aliases\"\n  Tree2\n  Priority_Queue_Specs\n  Complex_Main\nbegin\n\nfun mset_tree :: \"('a*'b) tree \\<Rightarrow> 'a multiset\" where\n\"mset_tree Leaf = {#}\" |\n\"mset_tree (Node l (a, _) r) = {#a#} + mset_tree l + mset_tree r\"\n\ntype_synonym 'a lheap = \"('a*nat)tree\"\n\nfun mht :: \"'a lheap \\<Rightarrow> nat\" where\n\"mht Leaf = 0\" |\n\"mht (Node _ (_, n) _) = n\"\n\ntext\\<open>The invariants:\\<close>\n\nfun (in linorder) heap :: \"('a*'b) tree \\<Rightarrow> bool\" where\n\"heap Leaf = True\" |\n\"heap (Node l (m, _) r) =\n  ((\\<forall>x \\<in> set_tree l \\<union> set_tree r. m \\<le> x) \\<and> heap l \\<and> heap r)\"\n\nfun ltree :: \"'a lheap \\<Rightarrow> bool\" where\n\"ltree Leaf = True\" |\n\"ltree (Node l (a, n) r) =\n (min_height l \\<ge> min_height r \\<and> n = min_height r + 1 \\<and> ltree l & ltree r)\"\n\ndefinition empty :: \"'a lheap\" where\n\"empty = Leaf\"\n\ndefinition node :: \"'a lheap \\<Rightarrow> 'a \\<Rightarrow> 'a lheap \\<Rightarrow> 'a lheap\" where\n\"node l a r =\n (let mhl = mht l; mhr = mht r\n  in if mhl \\<ge> mhr then Node l (a,mhr+1) r else Node r (a,mhl+1) l)\"\n\nfun get_min :: \"'a lheap \\<Rightarrow> 'a\" where\n\"get_min(Node l (a, n) r) = a\"\n\ntext \\<open>For function \\<open>merge\\<close>:\\<close>\nunbundle pattern_aliases\n\nfun merge :: \"'a::ord lheap \\<Rightarrow> 'a lheap \\<Rightarrow> 'a lheap\" where\n\"merge Leaf t = t\" |\n\"merge t Leaf = t\" |\n\"merge (Node l1 (a1, n1) r1 =: t1) (Node l2 (a2, n2) r2 =: t2) =\n   (if a1 \\<le> a2 then node l1 a1 (merge r1 t2)\n    else node l2 a2 (merge t1 r2))\"\n\ntext \\<open>Termination of @{const merge}: by sum or lexicographic product of the sizes\nof the two arguments. Isabelle uses a lexicographic product.\\<close>\n\nlemma merge_code: \"merge t1 t2 = (case (t1,t2) of\n  (Leaf, _) \\<Rightarrow> t2 |\n  (_, Leaf) \\<Rightarrow> t1 |\n  (Node l1 (a1, n1) r1, Node l2 (a2, n2) r2) \\<Rightarrow>\n    if a1 \\<le> a2 then node l1 a1 (merge r1 t2) else node l2 a2 (merge t1 r2))\"\nby(induction t1 t2 rule: merge.induct) (simp_all split: tree.split)\n\nhide_const (open) insert\n\ndefinition insert :: \"'a::ord \\<Rightarrow> 'a lheap \\<Rightarrow> 'a lheap\" where\n\"insert x t = merge (Node Leaf (x,1) Leaf) t\"\n\nfun del_min :: \"'a::ord lheap \\<Rightarrow> 'a lheap\" where\n\"del_min Leaf = Leaf\" |\n\"del_min (Node l _ r) = merge l r\"\n\n\nsubsection \"Lemmas\"\n\nlemma mset_tree_empty: \"mset_tree t = {#} \\<longleftrightarrow> t = Leaf\"\nby(cases t) auto\n\nlemma mht_eq_min_height: \"ltree t \\<Longrightarrow> mht t = min_height t\"\nby(cases t) auto\n\nlemma ltree_node: \"ltree (node l a r) \\<longleftrightarrow> ltree l \\<and> ltree r\"\nby(auto simp add: node_def mht_eq_min_height)\n\nlemma heap_node: \"heap (node l a r) \\<longleftrightarrow>\n  heap l \\<and> heap r \\<and> (\\<forall>x \\<in> set_tree l \\<union> set_tree r. a \\<le> x)\"\nby(auto simp add: node_def)\n\nlemma set_tree_mset: \"set_tree t = set_mset(mset_tree t)\"\nby(induction t) auto\n\nsubsection \"Functional Correctness\"\n\nlemma mset_merge: \"mset_tree (merge t1 t2) = mset_tree t1 + mset_tree t2\"\nby (induction t1 t2 rule: merge.induct) (auto simp add: node_def ac_simps)\n\nlemma mset_insert: \"mset_tree (insert x t) = mset_tree t + {#x#}\"\nby (auto simp add: insert_def mset_merge)\n\nlemma get_min: \"\\<lbrakk> heap t;  t \\<noteq> Leaf \\<rbrakk> \\<Longrightarrow> get_min t = Min(set_tree t)\"\nby (cases t) (auto simp add: eq_Min_iff)\n\nlemma mset_del_min: \"mset_tree (del_min t) = mset_tree t - {# get_min t #}\"\nby (cases t) (auto simp: mset_merge)\n\nlemma ltree_merge: \"\\<lbrakk> ltree l; ltree r \\<rbrakk> \\<Longrightarrow> ltree (merge l r)\"\nby(induction l r rule: merge.induct)(auto simp: ltree_node)\n\nlemma heap_merge: \"\\<lbrakk> heap l; heap r \\<rbrakk> \\<Longrightarrow> heap (merge l r)\"\nproof(induction l r rule: merge.induct)\n  case 3 thus ?case by(auto simp: heap_node mset_merge ball_Un set_tree_mset)\nqed simp_all\n\nlemma ltree_insert: \"ltree t \\<Longrightarrow> ltree(insert x t)\"\nby(simp add: insert_def ltree_merge del: merge.simps split: tree.split)\n\nlemma heap_insert: \"heap t \\<Longrightarrow> heap(insert x t)\"\nby(simp add: insert_def heap_merge del: merge.simps split: tree.split)\n\nlemma ltree_del_min: \"ltree t \\<Longrightarrow> ltree(del_min t)\"\nby(cases t)(auto simp add: ltree_merge simp del: merge.simps)\n\nlemma heap_del_min: \"heap t \\<Longrightarrow> heap(del_min t)\"\nby(cases t)(auto simp add: heap_merge simp del: merge.simps)\n\ntext \\<open>Last step of functional correctness proof: combine all the above lemmas\nto show that leftist heaps satisfy the specification of priority queues with merge.\\<close>\n\ninterpretation lheap: Priority_Queue_Merge\nwhere empty = empty and is_empty = \"\\<lambda>t. t = Leaf\"\nand insert = insert and del_min = del_min\nand get_min = get_min and merge = merge\nand invar = \"\\<lambda>t. heap t \\<and> ltree t\" and mset = mset_tree\nproof(standard, goal_cases)\n  case 1 show ?case by (simp add: empty_def)\nnext\n  case (2 q) show ?case by (cases q) auto\nnext\n  case 3 show ?case by(rule mset_insert)\nnext\n  case 4 show ?case by(rule mset_del_min)\nnext\n  case 5 thus ?case by(simp add: get_min mset_tree_empty set_tree_mset)\nnext\n  case 6 thus ?case by(simp add: empty_def)\nnext\n  case 7 thus ?case by(simp add: heap_insert ltree_insert)\nnext\n  case 8 thus ?case by(simp add: heap_del_min ltree_del_min)\nnext\n  case 9 thus ?case by (simp add: mset_merge)\nnext\n  case 10 thus ?case by (simp add: heap_merge ltree_merge)\nqed\n\n\nsubsection \"Complexity\"\n\ntext\\<open>Explicit termination argument: sum of sizes\\<close>\n\nfun T_merge :: \"'a::ord lheap \\<Rightarrow> 'a lheap \\<Rightarrow> nat\" where\n\"T_merge Leaf t = 1\" |\n\"T_merge t Leaf = 1\" |\n\"T_merge (Node l1 (a1, n1) r1 =: t1) (Node l2 (a2, n2) r2 =: t2) =\n  (if a1 \\<le> a2 then T_merge r1 t2\n   else T_merge t1 r2) + 1\"\n\ndefinition T_insert :: \"'a::ord \\<Rightarrow> 'a lheap \\<Rightarrow> nat\" where\n\"T_insert x t = T_merge (Node Leaf (x, 1) Leaf) t + 1\"\n\nfun T_del_min :: \"'a::ord lheap \\<Rightarrow> nat\" where\n\"T_del_min Leaf = 1\" |\n\"T_del_min (Node l _ r) = T_merge l r + 1\"\n\nlemma T_merge_min_height: \"ltree l \\<Longrightarrow> ltree r \\<Longrightarrow> T_merge l r \\<le> min_height l + min_height r + 1\"\nproof(induction l r rule: merge.induct)\n  case 3 thus ?case by(auto)\nqed simp_all\n\ncorollary T_merge_log: assumes \"ltree l\" \"ltree r\"\n  shows \"T_merge l r \\<le> log 2 (size1 l) + log 2 (size1 r) + 1\"\nusing le_log2_of_power[OF min_height_size1[of l]]\n  le_log2_of_power[OF min_height_size1[of r]] T_merge_min_height[of l r] assms\nby linarith\n\ncorollary T_insert_log: \"ltree t \\<Longrightarrow> T_insert x t \\<le> log 2 (size1 t) + 3\"\nusing T_merge_log[of \"Node Leaf (x, 1) Leaf\" t]\nby(simp add: T_insert_def split: tree.split)\n\n(* FIXME mv ? *)\nlemma ld_ld_1_less:\n  assumes \"x > 0\" \"y > 0\" shows \"log 2 x + log 2 y + 1 < 2 * log 2 (x+y)\"\nproof -\n  have \"2 powr (log 2 x + log 2 y + 1) = 2*x*y\"\n    using assms by(simp add: powr_add)\n  also have \"\\<dots> < (x+y)^2\" using assms\n    by(simp add: numeral_eq_Suc algebra_simps add_pos_pos)\n  also have \"\\<dots> = 2 powr (2 * log 2 (x+y))\"\n    using assms by(simp add: powr_add log_powr[symmetric])\n  finally show ?thesis by simp\nqed\n\ncorollary T_del_min_log: assumes \"ltree t\"\n  shows \"T_del_min t \\<le> 2 * log 2 (size1 t) + 1\"\nproof(cases t rule: tree2_cases)\n  case Leaf thus ?thesis using assms by simp\nnext\n  case [simp]: (Node l _ _ r)\n  have \"T_del_min t = T_merge l r + 1\" by simp\n  also have \"\\<dots> \\<le> log 2 (size1 l) + log 2 (size1 r) + 2\"\n    using \\<open>ltree t\\<close> T_merge_log[of l r] by (auto simp del: T_merge.simps)\n  also have \"\\<dots> \\<le> 2 * log 2 (size1 t) + 1\"\n    using ld_ld_1_less[of \"size1 l\" \"size1 r\"] 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/Data_Structures/Leftist_Heap.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916205190225, "lm_q2_score": 0.8289388104343892, "lm_q1q2_score": 0.7156988228520581}}
{"text": "(****************************************************************************)\nchapter {* Automated Reasoning Course\n          Jacques Fleuriot\n          Propositional Logic in Isabelle *}\n(****************************************************************************)\n\ntheory Prop\nimports Main\n\nbegin\n\n(****************************************************************************)\nsection {* Introduction *}\n\ntext {* This Isabelle theory file accompanies Lectures 2-4 of the\n        Automated Reasoning course. By stepping through it you should become\n        familiar with how to undertake propositional logic proofs in Isabelle. *}\n\n(****************************************************************************)\nsection {* First theorems *}\n\ntheorem K: \"A \\<longrightarrow> B \\<longrightarrow> A\"\napply (rule impI)\napply (rule impI)\napply assumption\ndone\n\ntext {* The rules \"impI\" and \"assumption\" above are examples of\n        Isabelle proof methods.\n\n         After processing \"done\" above, the front-end will\n        display a version of the theorem with the A and B replaced by\n        ?A and ?B.  These are schematic or meta\n        variables that can be freely instantiated if theorem K is used\n        in some further proof.\n\n        Theorems can involve assumptions from the start.  For example,\n        here is the Isabelle version of the natural deduction\n        derivation of A, B \\<turnstile> A \\<and> (B \\<and> A) *}\n\ntheorem a_conj_theorem: \"\\<lbrakk> A ; B \\<rbrakk> \\<Longrightarrow> A \\<and> (B \\<and> A)\"\napply (rule conjI)\napply assumption\napply (rule conjI)\napply assumption \napply assumption\ndone \n\ntext {* We can add \"+\" to the end of a method in order to apply it\n        more than once. We can also use the keyword \"by\" instead\n        of \"apply\" for the final line of the proof. This allows us\n        to discard the \"done\".  So, the same theorem can be proved\n        as follows: *}\n\n\ntheorem a_conj_theorem2: \"\\<lbrakk> A ; B \\<rbrakk> \\<Longrightarrow> A \\<and> (B \\<and> A)\"\napply (rule conjI)\napply assumption\napply (rule conjI)\nby assumption+\n\n(****************************************************************************)\nsection {* More On Applying Rules *}\n\n\ntext {* A simple propositional fact is B \\<or> A from the\n        assumption A \\<or> B. In Isabelle, this lemma can\n        be proved as follows: *}\n\nlemma \"A \\<or> B \\<Longrightarrow> B \\<or> A\"\napply (erule disjE)\napply (rule disjI2)\napply assumption\napply (rule disjI1)\nby assumption\n\ntext {* It is instructive to see what happens when we apply a rule\n        backward such that not all of its variables can be immediately\n        instantiated.  Look at what happens below after \"rule\n        disjE\".  We get schematic variables in both subgoals that then\n        are instantiated once we apply the assumption method on the\n        1st subgoal.  *}\n\nlemma \"A \\<or> B \\<Longrightarrow> B \\<or> A\"\napply (rule disjE)\napply assumption\napply (rule disjI2)\napply assumption\napply (rule disjI1)\nby assumption\n\n\n(****************************************************************************)\nsection {* More Methods *}\n\ntext {* Isabelle also provides the methods \"drule\" and \"frule\" for\n        forwards reasoning. These are best used with destruction rules. For\n        example:\n      *}\n\nlemma \"A \\<and> B \\<Longrightarrow> A\"\napply (drule conjunct1)\nby assumption \n\nlemma \"A \\<and> B \\<Longrightarrow> A\"\napply (frule conjunct1)\nby assumption\n\n\n(****************************************************************************)\nsection {* Problems Revisited *}\n\ntext{* We can now return to the three problems first posed in Lecture\n       2.  The written proof of Example 1 is shown in Lecture 3. Its\n       equivalent Isabelle proof is: *}\n   \nlemma example1: \"(SunnyTomorrow \\<or> RainyTomorrow) \\<and> \\<not>SunnyTomorrow \n                  \\<longrightarrow> RainyTomorrow\" \napply (rule impI)\napply (erule conjE)\napply (erule disjE)\napply (erule notE)\nby assumption+\n\ntext{* The proofs of Examples 2 and 3 are: *}\n\nlemma example2: \"(Class \\<or> Pop) \\<and> (Class \\<longrightarrow> Soph) \\<and> \\<not>Pop \\<longrightarrow> Soph\"\napply (rule impI)\napply (erule conjE)+\napply (erule disjE)\napply (erule impE)\napply assumption+\napply (erule notE)\nby assumption\n\n\nlemma example3: \"(M \\<or> L) \\<and> (M \\<or> W) \\<and> \\<not>(L \\<and> W) \\<longrightarrow> M \\<or> (M \\<and> L) \\<or> (M \\<and> W)\" \napply (rule impI)\napply (erule conjE)+\napply (erule disjE)\napply (erule disjE)\napply (rule disjI1)\napply assumption\napply (rule disjI1)\napply assumption\napply (erule disjE)\napply (rule disjI1)\napply assumption\napply (erule notE)\napply (rule conjI)\nby assumption+\n\n(*****************************************************************************)\nsection {* Applying Rules to Correct Assumptions *}\n\ntext {* Consider the following lemma and proof: *}\n\nlemma conj_elim1: \"\\<lbrakk> A \\<and> B; C \\<and> D \\<rbrakk> \\<Longrightarrow> D\" \napply (erule conjE)\napply (erule conjE)\nby assumption\n\ntext {* Notice that in this proof we had to apply the rule \"conjE\" \n        twice in order to eliminate the conjunction in the second \n        assumption. We could have avoided writing the extra proof step \n        by using \"+\":\n      *}  \n\nlemma conj_elim2: \"\\<lbrakk> A \\<and> B; C \\<and> D \\<rbrakk> \\<Longrightarrow> D\"\napply (erule conjE)+\nby assumption\n\ntext {* Although this new proof is shorter, we have still carried out an \n       unnecessary step: we do not need to eliminate the \n       conjunction in the first assumption. If we want to apply \"conjE\"\n       to a an assumption different from the first one it matches, then\n       we can rotate the ordering of our assumptions. To do this Isabelle \n       provides a tactic called \"rotate_tac\". An alternative proof is \n       thus: \n     *}  \n\nlemma conj_elim3: \"\\<lbrakk> A \\<and> B; C \\<and> D \\<rbrakk> \\<Longrightarrow> D\"\napply (rotate_tac 1)\napply (erule conjE)\nby assumption\n\ntext {* If our list of assumptions is very large, we may not want to use\n        \"rotate_tac\". A better approach is to explicitly tell Isabelle\n       what instantiations the variables in a rule should take when we apply \n       it. To do this we use the methods \"rule_tac\", \"erule_tac\",\n       \"drule_tac\" and \"frule_tac\". Our alternative proof of\n       \"conj_elim\" is:\n    *}     \n\nlemma conj_elim4: \"\\<lbrakk> A \\<and> B; C \\<and> D \\<rbrakk> \\<Longrightarrow> D\"\napply (erule_tac P=C and Q=D in conjE)\nby assumption\n\ntext {* In the above proof it is not neccessary to tell Isabelle the variable\n        Q in the rule \"conjE\" should be instantiated to D. \n        Isabelle can automatically infer this! So our proof becomes:\n      *}  \n\nlemma conj_elim5: \"\\<lbrakk> A \\<and> B; C \\<and> D \\<rbrakk> \\<Longrightarrow> D\"\napply (erule_tac P=C in conjE)\nby assumption\n\n(*****************************************************************************)\nsection{* More Rules of the Game *}\n\ntext {* If you start proving a lemma but get stuck, you can always\n        type the command \"oops\" to abandon the proof. For example:\n      *}  \n\nlemma A_and_B_imp_B_or_A: \"A \\<and> B \\<longrightarrow> B \\<or> A\"\noops\n\n\ntext {* Now imagine we want to use A \\<and> B \\<longrightarrow> B \\<or> A to prove \n        later lemmas and theorems. As it is not a rule (since it does\n        not have the \\<Longrightarrow>) we use it by inserting it as an \n        assumption in our proof. This is done using\n        a tactic called \"cut_tac\". Consider the following lemma and \n        try uncommenting the \"apply\" command.\n      *} \n\nlemma \"A \\<and> B \\<Longrightarrow> B \\<or> A\"\n(* apply (cut_tac A_and_B_imp_B_or_A)*)\n(* Isabelle complains! *)\noops\n\ntext {*  When we try to insert  A \\<and> B \\<longrightarrow> B \\<or> A into our proof\n         Isabelle complains. This is because Isabelle does not know\n         the theorem. The command \"oops\" allowed us to abandon our \n         proof, but it also told Isabelle to forget the lemma completely. \n\n         To allow Isabelle to continue checking this theory, comment out\n         again the \"apply\" command above.\n\n         Instead of using \"oops\", we could have used the command \n         \"sorry\":\n      *}\n          \nlemma A_and_B_imp_B_or_A_take2: \"A \\<and> B \\<longrightarrow> B \\<or> A\"\nsorry\n\ntext {* The command \"sorry\" tells Isabelle to abandon the proof\n        but pretend that the lemma has been proved. This allows us to use it\n        in later proofs: \n      *}   \n\nlemma cut_in_action: \"A \\<and> B \\<Longrightarrow> B \\<or> A\"\napply (cut_tac A_and_B_imp_B_or_A_take2) \napply (erule impE)\napply assumption+\ndone\n\ntext {* A word of warning: \"sorry\" is a cheat allowing you to make \n        progress. You should return to the incomplete proof and finish it\n        to be completely sure the rest of your theory is valid.\n      *}\n\n(*****************************************************************************)\nsection {* Automation *}\n\ntext{* It may seem tedious having to type in all these commands. Isabelle does\n       provide a fair amount of automation. The tactics \"simp\" and \"auto\" both\n       use the classical reasoner of Isabelle and can make life a lot easier.\n       Example:\n     *} \n\nlemma proved_by_simp: \"A \\<and> B \\<Longrightarrow> B \\<or> A\"\nby simp \n\nlemma proved_by_auto: \"A \\<and> B \\<Longrightarrow> B \\<or> A\"\nby auto\n\n\nend\n\n\n\n\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/Prop.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388125473629, "lm_q2_score": 0.8633916134888613, "lm_q1q2_score": 0.7156988188488084}}
{"text": "(*  Title:      HOL/Library/FSet.thy\n    Author:     Ondrej Kuncar, TU Muenchen\n    Author:     Cezary Kaliszyk and Christian Urban\n    Author:     Andrei Popescu, TU Muenchen\n*)\n\nsection \\<open>Type of finite sets defined as a subtype of sets\\<close>\n\ntheory FSet\nimports \"MainRLT\" Countable\nbegin\n\nsubsection \\<open>Definition of the type\\<close>\n\ntypedef 'a fset = \"{A :: 'a set. finite A}\"  morphisms fset Abs_fset\nby auto\n\nsetup_lifting type_definition_fset\n\n\nsubsection \\<open>Basic operations and type class instantiations\\<close>\n\n(* FIXME transfer and right_total vs. bi_total *)\ninstantiation fset :: (finite) finite\nbegin\ninstance by (standard; transfer; simp)\nend\n\ninstantiation fset :: (type) \"{bounded_lattice_bot, distrib_lattice, minus}\"\nbegin\n\nlift_definition bot_fset :: \"'a fset\" is \"{}\" parametric empty_transfer by simp\n\nlift_definition less_eq_fset :: \"'a fset \\<Rightarrow> 'a fset \\<Rightarrow> bool\" is subset_eq parametric subset_transfer\n  .\n\ndefinition less_fset :: \"'a fset \\<Rightarrow> 'a fset \\<Rightarrow> bool\" where \"xs < ys \\<equiv> xs \\<le> ys \\<and> xs \\<noteq> (ys::'a fset)\"\n\nlemma less_fset_transfer[transfer_rule]:\n  includes lifting_syntax\n  assumes [transfer_rule]: \"bi_unique A\"\n  shows \"((pcr_fset A) ===> (pcr_fset A) ===> (=)) (\\<subset>) (<)\"\n  unfolding less_fset_def[abs_def] psubset_eq[abs_def] by transfer_prover\n\n\nlift_definition sup_fset :: \"'a fset \\<Rightarrow> 'a fset \\<Rightarrow> 'a fset\" is union parametric union_transfer\n  by simp\n\nlift_definition inf_fset :: \"'a fset \\<Rightarrow> 'a fset \\<Rightarrow> 'a fset\" is inter parametric inter_transfer\n  by simp\n\nlift_definition minus_fset :: \"'a fset \\<Rightarrow> 'a fset \\<Rightarrow> 'a fset\" is minus parametric Diff_transfer\n  by simp\n\ninstance\n  by (standard; transfer; auto)+\n\nend\n\nabbreviation fempty :: \"'a fset\" (\"{||}\") where \"{||} \\<equiv> bot\"\nabbreviation fsubset_eq :: \"'a fset \\<Rightarrow> 'a fset \\<Rightarrow> bool\" (infix \"|\\<subseteq>|\" 50) where \"xs |\\<subseteq>| ys \\<equiv> xs \\<le> ys\"\nabbreviation fsubset :: \"'a fset \\<Rightarrow> 'a fset \\<Rightarrow> bool\" (infix \"|\\<subset>|\" 50) where \"xs |\\<subset>| ys \\<equiv> xs < ys\"\nabbreviation funion :: \"'a fset \\<Rightarrow> 'a fset \\<Rightarrow> 'a fset\" (infixl \"|\\<union>|\" 65) where \"xs |\\<union>| ys \\<equiv> sup xs ys\"\nabbreviation finter :: \"'a fset \\<Rightarrow> 'a fset \\<Rightarrow> 'a fset\" (infixl \"|\\<inter>|\" 65) where \"xs |\\<inter>| ys \\<equiv> inf xs ys\"\nabbreviation fminus :: \"'a fset \\<Rightarrow> 'a fset \\<Rightarrow> 'a fset\" (infixl \"|-|\" 65) where \"xs |-| ys \\<equiv> minus xs ys\"\n\ninstantiation fset :: (equal) equal\nbegin\ndefinition \"HOL.equal A B \\<longleftrightarrow> A |\\<subseteq>| B \\<and> B |\\<subseteq>| A\"\ninstance by intro_classes (auto simp add: equal_fset_def)\nend\n\ninstantiation fset :: (type) conditionally_complete_lattice\nbegin\n\ncontext includes lifting_syntax\nbegin\n\nlemma right_total_Inf_fset_transfer:\n  assumes [transfer_rule]: \"bi_unique A\" and [transfer_rule]: \"right_total A\"\n  shows \"(rel_set (rel_set A) ===> rel_set A)\n    (\\<lambda>S. if finite (\\<Inter>S \\<inter> Collect (Domainp A)) then \\<Inter>S \\<inter> Collect (Domainp A) else {})\n      (\\<lambda>S. if finite (Inf S) then Inf S else {})\"\n    by transfer_prover\n\nlemma Inf_fset_transfer:\n  assumes [transfer_rule]: \"bi_unique A\" and [transfer_rule]: \"bi_total A\"\n  shows \"(rel_set (rel_set A) ===> rel_set A) (\\<lambda>A. if finite (Inf A) then Inf A else {})\n    (\\<lambda>A. if finite (Inf A) then Inf A else {})\"\n  by transfer_prover\n\nlift_definition Inf_fset :: \"'a fset set \\<Rightarrow> 'a fset\" is \"\\<lambda>A. if finite (Inf A) then Inf A else {}\"\nparametric right_total_Inf_fset_transfer Inf_fset_transfer by simp\n\nlemma Sup_fset_transfer:\n  assumes [transfer_rule]: \"bi_unique A\"\n  shows \"(rel_set (rel_set A) ===> rel_set A) (\\<lambda>A. if finite (Sup A) then Sup A else {})\n  (\\<lambda>A. if finite (Sup A) then Sup A else {})\" by transfer_prover\n\nlift_definition Sup_fset :: \"'a fset set \\<Rightarrow> 'a fset\" is \"\\<lambda>A. if finite (Sup A) then Sup A else {}\"\nparametric Sup_fset_transfer by simp\n\nlemma finite_Sup: \"\\<exists>z. finite z \\<and> (\\<forall>a. a \\<in> X \\<longrightarrow> a \\<le> z) \\<Longrightarrow> finite (Sup X)\"\nby (auto intro: finite_subset)\n\nlemma transfer_bdd_below[transfer_rule]: \"(rel_set (pcr_fset (=)) ===> (=)) bdd_below bdd_below\"\n  by auto\n\nend\n\ninstance\nproof\n  fix x z :: \"'a fset\"\n  fix X :: \"'a fset set\"\n  {\n    assume \"x \\<in> X\" \"bdd_below X\"\n    then show \"Inf X |\\<subseteq>| x\" by transfer auto\n  next\n    assume \"X \\<noteq> {}\" \"(\\<And>x. x \\<in> X \\<Longrightarrow> z |\\<subseteq>| x)\"\n    then show \"z |\\<subseteq>| Inf X\" by transfer (clarsimp, blast)\n  next\n    assume \"x \\<in> X\" \"bdd_above X\"\n    then obtain z where \"x \\<in> X\" \"(\\<And>x. x \\<in> X \\<Longrightarrow> x |\\<subseteq>| z)\"\n      by (auto simp: bdd_above_def)\n    then show \"x |\\<subseteq>| Sup X\"\n      by transfer (auto intro!: finite_Sup)\n  next\n    assume \"X \\<noteq> {}\" \"(\\<And>x. x \\<in> X \\<Longrightarrow> x |\\<subseteq>| z)\"\n    then show \"Sup X |\\<subseteq>| z\" by transfer (clarsimp, blast)\n  }\nqed\nend\n\ninstantiation fset :: (finite) complete_lattice\nbegin\n\nlift_definition top_fset :: \"'a fset\" is UNIV parametric right_total_UNIV_transfer UNIV_transfer\n  by simp\n\ninstance\n  by (standard; transfer; auto)\n\nend\n\ninstantiation fset :: (finite) complete_boolean_algebra\nbegin\n\nlift_definition uminus_fset :: \"'a fset \\<Rightarrow> 'a fset\" is uminus\n  parametric right_total_Compl_transfer Compl_transfer by simp\n\ninstance\n  by (standard; transfer) (simp_all add: Inf_Sup Diff_eq)\nend\n\nabbreviation fUNIV :: \"'a::finite fset\" where \"fUNIV \\<equiv> top\"\nabbreviation fuminus :: \"'a::finite fset \\<Rightarrow> 'a fset\" (\"|-| _\" [81] 80) where \"|-| x \\<equiv> uminus x\"\n\ndeclare top_fset.rep_eq[simp]\n\n\nsubsection \\<open>Other operations\\<close>\n\nlift_definition finsert :: \"'a \\<Rightarrow> 'a fset \\<Rightarrow> 'a fset\" is insert parametric Lifting_Set.insert_transfer\n  by simp\n\nsyntax\n  \"_insert_fset\"     :: \"args => 'a fset\"  (\"{|(_)|}\")\n\ntranslations\n  \"{|x, xs|}\" == \"CONST finsert x {|xs|}\"\n  \"{|x|}\"     == \"CONST finsert x {||}\"\n\nlift_definition fmember :: \"'a \\<Rightarrow> 'a fset \\<Rightarrow> bool\" (infix \"|\\<in>|\" 50) is Set.member\n  parametric member_transfer .\n\nabbreviation notin_fset :: \"'a \\<Rightarrow> 'a fset \\<Rightarrow> bool\" (infix \"|\\<notin>|\" 50) where \"x |\\<notin>| S \\<equiv> \\<not> (x |\\<in>| S)\"\n\ncontext includes lifting_syntax\nbegin\n\nlift_definition ffilter :: \"('a \\<Rightarrow> bool) \\<Rightarrow> 'a fset \\<Rightarrow> 'a fset\" is Set.filter\n  parametric Lifting_Set.filter_transfer unfolding Set.filter_def by simp\n\nlift_definition fPow :: \"'a fset \\<Rightarrow> 'a fset fset\" is Pow parametric Pow_transfer\nby (simp add: finite_subset)\n\nlift_definition fcard :: \"'a fset \\<Rightarrow> nat\" is card parametric card_transfer .\n\nlift_definition fimage :: \"('a \\<Rightarrow> 'b) \\<Rightarrow> 'a fset \\<Rightarrow> 'b fset\" (infixr \"|`|\" 90) is image\n  parametric image_transfer by simp\n\nlift_definition fthe_elem :: \"'a fset \\<Rightarrow> 'a\" is the_elem .\n\nlift_definition fbind :: \"'a fset \\<Rightarrow> ('a \\<Rightarrow> 'b fset) \\<Rightarrow> 'b fset\" is Set.bind parametric bind_transfer\nby (simp add: Set.bind_def)\n\nlift_definition ffUnion :: \"'a fset fset \\<Rightarrow> 'a fset\" is Union parametric Union_transfer by simp\n\nlift_definition fBall :: \"'a fset \\<Rightarrow> ('a \\<Rightarrow> bool) \\<Rightarrow> bool\" is Ball parametric Ball_transfer .\nlift_definition fBex :: \"'a fset \\<Rightarrow> ('a \\<Rightarrow> bool) \\<Rightarrow> bool\" is Bex parametric Bex_transfer .\n\nlift_definition ffold :: \"('a \\<Rightarrow> 'b \\<Rightarrow> 'b) \\<Rightarrow> 'b \\<Rightarrow> 'a fset \\<Rightarrow> 'b\" is Finite_Set.fold .\n\nlift_definition fset_of_list :: \"'a list \\<Rightarrow> 'a fset\" is set by (rule finite_set)\n\nlift_definition sorted_list_of_fset :: \"'a::linorder fset \\<Rightarrow> 'a list\" is sorted_list_of_set .\n\nsubsection \\<open>Transferred lemmas from Set.thy\\<close>\n\nlemmas fset_eqI = set_eqI[Transfer.transferred]\nlemmas fset_eq_iff[no_atp] = set_eq_iff[Transfer.transferred]\nlemmas fBallI[intro!] = ballI[Transfer.transferred]\nlemmas fbspec[dest?] = bspec[Transfer.transferred]\nlemmas fBallE[elim] = ballE[Transfer.transferred]\nlemmas fBexI[intro] = bexI[Transfer.transferred]\nlemmas rev_fBexI[intro?] = rev_bexI[Transfer.transferred]\nlemmas fBexCI = bexCI[Transfer.transferred]\nlemmas fBexE[elim!] = bexE[Transfer.transferred]\nlemmas fBall_triv[simp] = ball_triv[Transfer.transferred]\nlemmas fBex_triv[simp] = bex_triv[Transfer.transferred]\nlemmas fBex_triv_one_point1[simp] = bex_triv_one_point1[Transfer.transferred]\nlemmas fBex_triv_one_point2[simp] = bex_triv_one_point2[Transfer.transferred]\nlemmas fBex_one_point1[simp] = bex_one_point1[Transfer.transferred]\nlemmas fBex_one_point2[simp] = bex_one_point2[Transfer.transferred]\nlemmas fBall_one_point1[simp] = ball_one_point1[Transfer.transferred]\nlemmas fBall_one_point2[simp] = ball_one_point2[Transfer.transferred]\nlemmas fBall_conj_distrib = ball_conj_distrib[Transfer.transferred]\nlemmas fBex_disj_distrib = bex_disj_distrib[Transfer.transferred]\nlemmas fBall_cong[fundef_cong] = ball_cong[Transfer.transferred]\nlemmas fBex_cong[fundef_cong] = bex_cong[Transfer.transferred]\nlemmas fsubsetI[intro!] = subsetI[Transfer.transferred]\nlemmas fsubsetD[elim, intro?] = subsetD[Transfer.transferred]\nlemmas rev_fsubsetD[no_atp,intro?] = rev_subsetD[Transfer.transferred]\nlemmas fsubsetCE[no_atp,elim] = subsetCE[Transfer.transferred]\nlemmas fsubset_eq[no_atp] = subset_eq[Transfer.transferred]\nlemmas contra_fsubsetD[no_atp] = contra_subsetD[Transfer.transferred]\nlemmas fsubset_refl = subset_refl[Transfer.transferred]\nlemmas fsubset_trans = subset_trans[Transfer.transferred]\nlemmas fset_rev_mp = rev_subsetD[Transfer.transferred]\nlemmas fset_mp = subsetD[Transfer.transferred]\nlemmas fsubset_not_fsubset_eq[code] = subset_not_subset_eq[Transfer.transferred]\nlemmas eq_fmem_trans = eq_mem_trans[Transfer.transferred]\nlemmas fsubset_antisym[intro!] = subset_antisym[Transfer.transferred]\nlemmas fequalityD1 = equalityD1[Transfer.transferred]\nlemmas fequalityD2 = equalityD2[Transfer.transferred]\nlemmas fequalityE = equalityE[Transfer.transferred]\nlemmas fequalityCE[elim] = equalityCE[Transfer.transferred]\nlemmas eqfset_imp_iff = eqset_imp_iff[Transfer.transferred]\nlemmas eqfelem_imp_iff = eqelem_imp_iff[Transfer.transferred]\nlemmas fempty_iff[simp] = empty_iff[Transfer.transferred]\nlemmas fempty_fsubsetI[iff] = empty_subsetI[Transfer.transferred]\nlemmas equalsffemptyI = equals0I[Transfer.transferred]\nlemmas equalsffemptyD = equals0D[Transfer.transferred]\nlemmas fBall_fempty[simp] = ball_empty[Transfer.transferred]\nlemmas fBex_fempty[simp] = bex_empty[Transfer.transferred]\nlemmas fPow_iff[iff] = Pow_iff[Transfer.transferred]\nlemmas fPowI = PowI[Transfer.transferred]\nlemmas fPowD = PowD[Transfer.transferred]\nlemmas fPow_bottom = Pow_bottom[Transfer.transferred]\nlemmas fPow_top = Pow_top[Transfer.transferred]\nlemmas fPow_not_fempty = Pow_not_empty[Transfer.transferred]\nlemmas finter_iff[simp] = Int_iff[Transfer.transferred]\nlemmas finterI[intro!] = IntI[Transfer.transferred]\nlemmas finterD1 = IntD1[Transfer.transferred]\nlemmas finterD2 = IntD2[Transfer.transferred]\nlemmas finterE[elim!] = IntE[Transfer.transferred]\nlemmas funion_iff[simp] = Un_iff[Transfer.transferred]\nlemmas funionI1[elim?] = UnI1[Transfer.transferred]\nlemmas funionI2[elim?] = UnI2[Transfer.transferred]\nlemmas funionCI[intro!] = UnCI[Transfer.transferred]\nlemmas funionE[elim!] = UnE[Transfer.transferred]\nlemmas fminus_iff[simp] = Diff_iff[Transfer.transferred]\nlemmas fminusI[intro!] = DiffI[Transfer.transferred]\nlemmas fminusD1 = DiffD1[Transfer.transferred]\nlemmas fminusD2 = DiffD2[Transfer.transferred]\nlemmas fminusE[elim!] = DiffE[Transfer.transferred]\nlemmas finsert_iff[simp] = insert_iff[Transfer.transferred]\nlemmas finsertI1 = insertI1[Transfer.transferred]\nlemmas finsertI2 = insertI2[Transfer.transferred]\nlemmas finsertE[elim!] = insertE[Transfer.transferred]\nlemmas finsertCI[intro!] = insertCI[Transfer.transferred]\nlemmas fsubset_finsert_iff = subset_insert_iff[Transfer.transferred]\nlemmas finsert_ident = insert_ident[Transfer.transferred]\nlemmas fsingletonI[intro!,no_atp] = singletonI[Transfer.transferred]\nlemmas fsingletonD[dest!,no_atp] = singletonD[Transfer.transferred]\nlemmas fsingleton_iff = singleton_iff[Transfer.transferred]\nlemmas fsingleton_inject[dest!] = singleton_inject[Transfer.transferred]\nlemmas fsingleton_finsert_inj_eq[iff,no_atp] = singleton_insert_inj_eq[Transfer.transferred]\nlemmas fsingleton_finsert_inj_eq'[iff,no_atp] = singleton_insert_inj_eq'[Transfer.transferred]\nlemmas fsubset_fsingletonD = subset_singletonD[Transfer.transferred]\nlemmas fminus_single_finsert = Diff_single_insert[Transfer.transferred]\nlemmas fdoubleton_eq_iff = doubleton_eq_iff[Transfer.transferred]\nlemmas funion_fsingleton_iff = Un_singleton_iff[Transfer.transferred]\nlemmas fsingleton_funion_iff = singleton_Un_iff[Transfer.transferred]\nlemmas fimage_eqI[simp, intro] = image_eqI[Transfer.transferred]\nlemmas fimageI = imageI[Transfer.transferred]\nlemmas rev_fimage_eqI = rev_image_eqI[Transfer.transferred]\nlemmas fimageE[elim!] = imageE[Transfer.transferred]\nlemmas Compr_fimage_eq = Compr_image_eq[Transfer.transferred]\nlemmas fimage_funion = image_Un[Transfer.transferred]\nlemmas fimage_iff = image_iff[Transfer.transferred]\nlemmas fimage_fsubset_iff[no_atp] = image_subset_iff[Transfer.transferred]\nlemmas fimage_fsubsetI = image_subsetI[Transfer.transferred]\nlemmas fimage_ident[simp] = image_ident[Transfer.transferred]\nlemmas if_split_fmem1 = if_split_mem1[Transfer.transferred]\nlemmas if_split_fmem2 = if_split_mem2[Transfer.transferred]\nlemmas pfsubsetI[intro!,no_atp] = psubsetI[Transfer.transferred]\nlemmas pfsubsetE[elim!,no_atp] = psubsetE[Transfer.transferred]\nlemmas pfsubset_finsert_iff = psubset_insert_iff[Transfer.transferred]\nlemmas pfsubset_eq = psubset_eq[Transfer.transferred]\nlemmas pfsubset_imp_fsubset = psubset_imp_subset[Transfer.transferred]\nlemmas pfsubset_trans = psubset_trans[Transfer.transferred]\nlemmas pfsubsetD = psubsetD[Transfer.transferred]\nlemmas pfsubset_fsubset_trans = psubset_subset_trans[Transfer.transferred]\nlemmas fsubset_pfsubset_trans = subset_psubset_trans[Transfer.transferred]\nlemmas pfsubset_imp_ex_fmem = psubset_imp_ex_mem[Transfer.transferred]\nlemmas fimage_fPow_mono = image_Pow_mono[Transfer.transferred]\nlemmas fimage_fPow_surj = image_Pow_surj[Transfer.transferred]\nlemmas fsubset_finsertI = subset_insertI[Transfer.transferred]\nlemmas fsubset_finsertI2 = subset_insertI2[Transfer.transferred]\nlemmas fsubset_finsert = subset_insert[Transfer.transferred]\nlemmas funion_upper1 = Un_upper1[Transfer.transferred]\nlemmas funion_upper2 = Un_upper2[Transfer.transferred]\nlemmas funion_least = Un_least[Transfer.transferred]\nlemmas finter_lower1 = Int_lower1[Transfer.transferred]\nlemmas finter_lower2 = Int_lower2[Transfer.transferred]\nlemmas finter_greatest = Int_greatest[Transfer.transferred]\nlemmas fminus_fsubset = Diff_subset[Transfer.transferred]\nlemmas fminus_fsubset_conv = Diff_subset_conv[Transfer.transferred]\nlemmas fsubset_fempty[simp] = subset_empty[Transfer.transferred]\nlemmas not_pfsubset_fempty[iff] = not_psubset_empty[Transfer.transferred]\nlemmas finsert_is_funion = insert_is_Un[Transfer.transferred]\nlemmas finsert_not_fempty[simp] = insert_not_empty[Transfer.transferred]\nlemmas fempty_not_finsert = empty_not_insert[Transfer.transferred]\nlemmas finsert_absorb = insert_absorb[Transfer.transferred]\nlemmas finsert_absorb2[simp] = insert_absorb2[Transfer.transferred]\nlemmas finsert_commute = insert_commute[Transfer.transferred]\nlemmas finsert_fsubset[simp] = insert_subset[Transfer.transferred]\nlemmas finsert_inter_finsert[simp] = insert_inter_insert[Transfer.transferred]\nlemmas finsert_disjoint[simp,no_atp] = insert_disjoint[Transfer.transferred]\nlemmas disjoint_finsert[simp,no_atp] = disjoint_insert[Transfer.transferred]\nlemmas fimage_fempty[simp] = image_empty[Transfer.transferred]\nlemmas fimage_finsert[simp] = image_insert[Transfer.transferred]\nlemmas fimage_constant = image_constant[Transfer.transferred]\nlemmas fimage_constant_conv = image_constant_conv[Transfer.transferred]\nlemmas fimage_fimage = image_image[Transfer.transferred]\nlemmas finsert_fimage[simp] = insert_image[Transfer.transferred]\nlemmas fimage_is_fempty[iff] = image_is_empty[Transfer.transferred]\nlemmas fempty_is_fimage[iff] = empty_is_image[Transfer.transferred]\nlemmas fimage_cong = image_cong[Transfer.transferred]\nlemmas fimage_finter_fsubset = image_Int_subset[Transfer.transferred]\nlemmas fimage_fminus_fsubset = image_diff_subset[Transfer.transferred]\nlemmas finter_absorb = Int_absorb[Transfer.transferred]\nlemmas finter_left_absorb = Int_left_absorb[Transfer.transferred]\nlemmas finter_commute = Int_commute[Transfer.transferred]\nlemmas finter_left_commute = Int_left_commute[Transfer.transferred]\nlemmas finter_assoc = Int_assoc[Transfer.transferred]\nlemmas finter_ac = Int_ac[Transfer.transferred]\nlemmas finter_absorb1 = Int_absorb1[Transfer.transferred]\nlemmas finter_absorb2 = Int_absorb2[Transfer.transferred]\nlemmas finter_fempty_left = Int_empty_left[Transfer.transferred]\nlemmas finter_fempty_right = Int_empty_right[Transfer.transferred]\nlemmas disjoint_iff_fnot_equal = disjoint_iff_not_equal[Transfer.transferred]\nlemmas finter_funion_distrib = Int_Un_distrib[Transfer.transferred]\nlemmas finter_funion_distrib2 = Int_Un_distrib2[Transfer.transferred]\nlemmas finter_fsubset_iff[no_atp, simp] = Int_subset_iff[Transfer.transferred]\nlemmas funion_absorb = Un_absorb[Transfer.transferred]\nlemmas funion_left_absorb = Un_left_absorb[Transfer.transferred]\nlemmas funion_commute = Un_commute[Transfer.transferred]\nlemmas funion_left_commute = Un_left_commute[Transfer.transferred]\nlemmas funion_assoc = Un_assoc[Transfer.transferred]\nlemmas funion_ac = Un_ac[Transfer.transferred]\nlemmas funion_absorb1 = Un_absorb1[Transfer.transferred]\nlemmas funion_absorb2 = Un_absorb2[Transfer.transferred]\nlemmas funion_fempty_left = Un_empty_left[Transfer.transferred]\nlemmas funion_fempty_right = Un_empty_right[Transfer.transferred]\nlemmas funion_finsert_left[simp] = Un_insert_left[Transfer.transferred]\nlemmas funion_finsert_right[simp] = Un_insert_right[Transfer.transferred]\nlemmas finter_finsert_left = Int_insert_left[Transfer.transferred]\nlemmas finter_finsert_left_ifffempty[simp] = Int_insert_left_if0[Transfer.transferred]\nlemmas finter_finsert_left_if1[simp] = Int_insert_left_if1[Transfer.transferred]\nlemmas finter_finsert_right = Int_insert_right[Transfer.transferred]\nlemmas finter_finsert_right_ifffempty[simp] = Int_insert_right_if0[Transfer.transferred]\nlemmas finter_finsert_right_if1[simp] = Int_insert_right_if1[Transfer.transferred]\nlemmas funion_finter_distrib = Un_Int_distrib[Transfer.transferred]\nlemmas funion_finter_distrib2 = Un_Int_distrib2[Transfer.transferred]\nlemmas funion_finter_crazy = Un_Int_crazy[Transfer.transferred]\nlemmas fsubset_funion_eq = subset_Un_eq[Transfer.transferred]\nlemmas funion_fempty[iff] = Un_empty[Transfer.transferred]\nlemmas funion_fsubset_iff[no_atp, simp] = Un_subset_iff[Transfer.transferred]\nlemmas funion_fminus_finter = Un_Diff_Int[Transfer.transferred]\nlemmas ffunion_empty[simp] = Union_empty[Transfer.transferred]\nlemmas ffunion_mono = Union_mono[Transfer.transferred]\nlemmas ffunion_insert[simp] = Union_insert[Transfer.transferred]\nlemmas fminus_finter2 = Diff_Int2[Transfer.transferred]\nlemmas funion_finter_assoc_eq = Un_Int_assoc_eq[Transfer.transferred]\nlemmas fBall_funion = ball_Un[Transfer.transferred]\nlemmas fBex_funion = bex_Un[Transfer.transferred]\nlemmas fminus_eq_fempty_iff[simp,no_atp] = Diff_eq_empty_iff[Transfer.transferred]\nlemmas fminus_cancel[simp] = Diff_cancel[Transfer.transferred]\nlemmas fminus_idemp[simp] = Diff_idemp[Transfer.transferred]\nlemmas fminus_triv = Diff_triv[Transfer.transferred]\nlemmas fempty_fminus[simp] = empty_Diff[Transfer.transferred]\nlemmas fminus_fempty[simp] = Diff_empty[Transfer.transferred]\nlemmas fminus_finsertffempty[simp,no_atp] = Diff_insert0[Transfer.transferred]\nlemmas fminus_finsert = Diff_insert[Transfer.transferred]\nlemmas fminus_finsert2 = Diff_insert2[Transfer.transferred]\nlemmas finsert_fminus_if = insert_Diff_if[Transfer.transferred]\nlemmas finsert_fminus1[simp] = insert_Diff1[Transfer.transferred]\nlemmas finsert_fminus_single[simp] = insert_Diff_single[Transfer.transferred]\nlemmas finsert_fminus = insert_Diff[Transfer.transferred]\nlemmas fminus_finsert_absorb = Diff_insert_absorb[Transfer.transferred]\nlemmas fminus_disjoint[simp] = Diff_disjoint[Transfer.transferred]\nlemmas fminus_partition = Diff_partition[Transfer.transferred]\nlemmas double_fminus = double_diff[Transfer.transferred]\nlemmas funion_fminus_cancel[simp] = Un_Diff_cancel[Transfer.transferred]\nlemmas funion_fminus_cancel2[simp] = Un_Diff_cancel2[Transfer.transferred]\nlemmas fminus_funion = Diff_Un[Transfer.transferred]\nlemmas fminus_finter = Diff_Int[Transfer.transferred]\nlemmas funion_fminus = Un_Diff[Transfer.transferred]\nlemmas finter_fminus = Int_Diff[Transfer.transferred]\nlemmas fminus_finter_distrib = Diff_Int_distrib[Transfer.transferred]\nlemmas fminus_finter_distrib2 = Diff_Int_distrib2[Transfer.transferred]\nlemmas fUNIV_bool[no_atp] = UNIV_bool[Transfer.transferred]\nlemmas fPow_fempty[simp] = Pow_empty[Transfer.transferred]\nlemmas fPow_finsert = Pow_insert[Transfer.transferred]\nlemmas funion_fPow_fsubset = Un_Pow_subset[Transfer.transferred]\nlemmas fPow_finter_eq[simp] = Pow_Int_eq[Transfer.transferred]\nlemmas fset_eq_fsubset = set_eq_subset[Transfer.transferred]\nlemmas fsubset_iff[no_atp] = subset_iff[Transfer.transferred]\nlemmas fsubset_iff_pfsubset_eq = subset_iff_psubset_eq[Transfer.transferred]\nlemmas all_not_fin_conv[simp] = all_not_in_conv[Transfer.transferred]\nlemmas ex_fin_conv = ex_in_conv[Transfer.transferred]\nlemmas fimage_mono = image_mono[Transfer.transferred]\nlemmas fPow_mono = Pow_mono[Transfer.transferred]\nlemmas finsert_mono = insert_mono[Transfer.transferred]\nlemmas funion_mono = Un_mono[Transfer.transferred]\nlemmas finter_mono = Int_mono[Transfer.transferred]\nlemmas fminus_mono = Diff_mono[Transfer.transferred]\nlemmas fin_mono = in_mono[Transfer.transferred]\nlemmas fthe_felem_eq[simp] = the_elem_eq[Transfer.transferred]\nlemmas fLeast_mono = Least_mono[Transfer.transferred]\nlemmas fbind_fbind = bind_bind[Transfer.transferred]\nlemmas fempty_fbind[simp] = empty_bind[Transfer.transferred]\nlemmas nonfempty_fbind_const = nonempty_bind_const[Transfer.transferred]\nlemmas fbind_const = bind_const[Transfer.transferred]\nlemmas ffmember_filter[simp] = member_filter[Transfer.transferred]\nlemmas fequalityI = equalityI[Transfer.transferred]\nlemmas fset_of_list_simps[simp] = set_simps[Transfer.transferred]\nlemmas fset_of_list_append[simp] = set_append[Transfer.transferred]\nlemmas fset_of_list_rev[simp] = set_rev[Transfer.transferred]\nlemmas fset_of_list_map[simp] = set_map[Transfer.transferred]\n\n\nsubsection \\<open>Additional lemmas\\<close>\n\nsubsubsection \\<open>\\<open>ffUnion\\<close>\\<close>\n\nlemmas ffUnion_funion_distrib[simp] = Union_Un_distrib[Transfer.transferred]\n\n\nsubsubsection \\<open>\\<open>fbind\\<close>\\<close>\n\nlemma fbind_cong[fundef_cong]: \"A = B \\<Longrightarrow> (\\<And>x. x |\\<in>| B \\<Longrightarrow> f x = g x) \\<Longrightarrow> fbind A f = fbind B g\"\nby transfer force\n\n\nsubsubsection \\<open>\\<open>fsingleton\\<close>\\<close>\n\nlemmas fsingletonE = fsingletonD [elim_format]\n\n\nsubsubsection \\<open>\\<open>femepty\\<close>\\<close>\n\nlemma fempty_ffilter[simp]: \"ffilter (\\<lambda>_. False) A = {||}\"\nby transfer auto\n\n(* FIXME, transferred doesn't work here *)\nlemma femptyE [elim!]: \"a |\\<in>| {||} \\<Longrightarrow> P\"\n  by simp\n\n\nsubsubsection \\<open>\\<open>fset\\<close>\\<close>\n\nlemmas fset_simps[simp] = bot_fset.rep_eq finsert.rep_eq\n\nlemma finite_fset [simp]:\n  shows \"finite (fset S)\"\n  by transfer simp\n\nlemmas fset_cong = fset_inject\n\nlemma filter_fset [simp]:\n  shows \"fset (ffilter P xs) = Collect P \\<inter> fset xs\"\n  by transfer auto\n\nlemma notin_fset: \"x |\\<notin>| S \\<longleftrightarrow> x \\<notin> fset S\" by (simp add: fmember.rep_eq)\n\nlemmas inter_fset[simp] = inf_fset.rep_eq\n\nlemmas union_fset[simp] = sup_fset.rep_eq\n\nlemmas minus_fset[simp] = minus_fset.rep_eq\n\n\nsubsubsection \\<open>\\<open>ffilter\\<close>\\<close>\n\nlemma subset_ffilter:\n  \"ffilter P A |\\<subseteq>| ffilter Q A = (\\<forall> x. x |\\<in>| A \\<longrightarrow> P x \\<longrightarrow> Q x)\"\n  by transfer auto\n\nlemma eq_ffilter:\n  \"(ffilter P A = ffilter Q A) = (\\<forall>x. x |\\<in>| A \\<longrightarrow> P x = Q x)\"\n  by transfer auto\n\nlemma pfsubset_ffilter:\n  \"(\\<And>x. x |\\<in>| A \\<Longrightarrow> P x \\<Longrightarrow> Q x) \\<Longrightarrow> (x |\\<in>| A \\<and> \\<not> P x \\<and> Q x) \\<Longrightarrow>\n    ffilter P A |\\<subset>| ffilter Q A\"\n  unfolding less_fset_def by (auto simp add: subset_ffilter eq_ffilter)\n\n\nsubsubsection \\<open>\\<open>fset_of_list\\<close>\\<close>\n\nlemma fset_of_list_filter[simp]:\n  \"fset_of_list (filter P xs) = ffilter P (fset_of_list xs)\"\n  by transfer (auto simp: Set.filter_def)\n\nlemma fset_of_list_subset[intro]:\n  \"set xs \\<subseteq> set ys \\<Longrightarrow> fset_of_list xs |\\<subseteq>| fset_of_list ys\"\n  by transfer simp\n\nlemma fset_of_list_elem: \"(x |\\<in>| fset_of_list xs) \\<longleftrightarrow> (x \\<in> set xs)\"\n  by transfer simp\n\n\nsubsubsection \\<open>\\<open>finsert\\<close>\\<close>\n\n(* FIXME, transferred doesn't work here *)\nlemma set_finsert:\n  assumes \"x |\\<in>| A\"\n  obtains B where \"A = finsert x B\" and \"x |\\<notin>| B\"\nusing assms by transfer (metis Set.set_insert finite_insert)\n\nlemma mk_disjoint_finsert: \"a |\\<in>| A \\<Longrightarrow> \\<exists>B. A = finsert a B \\<and> a |\\<notin>| B\"\n  by (rule exI [where x = \"A |-| {|a|}\"]) blast\n\nlemma finsert_eq_iff:\n  assumes \"a |\\<notin>| A\" and \"b |\\<notin>| B\"\n  shows \"(finsert a A = finsert b B) =\n    (if a = b then A = B else \\<exists>C. A = finsert b C \\<and> b |\\<notin>| C \\<and> B = finsert a C \\<and> a |\\<notin>| C)\"\n  using assms by transfer (force simp: insert_eq_iff)\n\n\nsubsubsection \\<open>\\<open>fimage\\<close>\\<close>\n\nlemma subset_fimage_iff: \"(B |\\<subseteq>| f|`|A) = (\\<exists> AA. AA |\\<subseteq>| A \\<and> B = f|`|AA)\"\nby transfer (metis mem_Collect_eq rev_finite_subset subset_image_iff)\n\n\nsubsubsection \\<open>bounded quantification\\<close>\n\nlemma bex_simps [simp, no_atp]:\n  \"\\<And>A P Q. fBex A (\\<lambda>x. P x \\<and> Q) = (fBex A P \\<and> Q)\"\n  \"\\<And>A P Q. fBex A (\\<lambda>x. P \\<and> Q x) = (P \\<and> fBex A Q)\"\n  \"\\<And>P. fBex {||} P = False\"\n  \"\\<And>a B P. fBex (finsert a B) P = (P a \\<or> fBex B P)\"\n  \"\\<And>A P f. fBex (f |`| A) P = fBex A (\\<lambda>x. P (f x))\"\n  \"\\<And>A P. (\\<not> fBex A P) = fBall A (\\<lambda>x. \\<not> P x)\"\nby auto\n\nlemma ball_simps [simp, no_atp]:\n  \"\\<And>A P Q. fBall A (\\<lambda>x. P x \\<or> Q) = (fBall A P \\<or> Q)\"\n  \"\\<And>A P Q. fBall A (\\<lambda>x. P \\<or> Q x) = (P \\<or> fBall A Q)\"\n  \"\\<And>A P Q. fBall A (\\<lambda>x. P \\<longrightarrow> Q x) = (P \\<longrightarrow> fBall A Q)\"\n  \"\\<And>A P Q. fBall A (\\<lambda>x. P x \\<longrightarrow> Q) = (fBex A P \\<longrightarrow> Q)\"\n  \"\\<And>P. fBall {||} P = True\"\n  \"\\<And>a B P. fBall (finsert a B) P = (P a \\<and> fBall B P)\"\n  \"\\<And>A P f. fBall (f |`| A) P = fBall A (\\<lambda>x. P (f x))\"\n  \"\\<And>A P. (\\<not> fBall A P) = fBex A (\\<lambda>x. \\<not> P x)\"\nby auto\n\nlemma atomize_fBall:\n    \"(\\<And>x. x |\\<in>| A ==> P x) == Trueprop (fBall A (\\<lambda>x. P x))\"\napply (simp only: atomize_all atomize_imp)\napply (rule equal_intr_rule)\n  by (transfer, simp)+\n\nlemma fBall_mono[mono]: \"P \\<le> Q \\<Longrightarrow> fBall S P \\<le> fBall S Q\"\nby auto\n\nlemma fBex_mono[mono]: \"P \\<le> Q \\<Longrightarrow> fBex S P \\<le> fBex S Q\"\nby auto\n\nend\n\n\nsubsubsection \\<open>\\<open>fcard\\<close>\\<close>\n\n(* FIXME: improve transferred to handle bounded meta quantification *)\n\nlemma fcard_fempty:\n  \"fcard {||} = 0\"\n  by transfer (rule card.empty)\n\nlemma fcard_finsert_disjoint:\n  \"x |\\<notin>| A \\<Longrightarrow> fcard (finsert x A) = Suc (fcard A)\"\n  by transfer (rule card_insert_disjoint)\n\nlemma fcard_finsert_if:\n  \"fcard (finsert x A) = (if x |\\<in>| A then fcard A else Suc (fcard A))\"\n  by transfer (rule card_insert_if)\n\nlemma fcard_0_eq [simp, no_atp]:\n  \"fcard A = 0 \\<longleftrightarrow> A = {||}\"\n  by transfer (rule card_0_eq)\n\nlemma fcard_Suc_fminus1:\n  \"x |\\<in>| A \\<Longrightarrow> Suc (fcard (A |-| {|x|})) = fcard A\"\n  by transfer (rule card_Suc_Diff1)\n\nlemma fcard_fminus_fsingleton:\n  \"x |\\<in>| A \\<Longrightarrow> fcard (A |-| {|x|}) = fcard A - 1\"\n  by transfer (rule card_Diff_singleton)\n\nlemma fcard_fminus_fsingleton_if:\n  \"fcard (A |-| {|x|}) = (if x |\\<in>| A then fcard A - 1 else fcard A)\"\n  by transfer (rule card_Diff_singleton_if)\n\nlemma fcard_fminus_finsert[simp]:\n  assumes \"a |\\<in>| A\" and \"a |\\<notin>| B\"\n  shows \"fcard (A |-| finsert a B) = fcard (A |-| B) - 1\"\nusing assms by transfer (rule card_Diff_insert)\n\nlemma fcard_finsert: \"fcard (finsert x A) = Suc (fcard (A |-| {|x|}))\"\nby transfer (rule card.insert_remove)\n\nlemma fcard_finsert_le: \"fcard A \\<le> fcard (finsert x A)\"\nby transfer (rule card_insert_le)\n\nlemma fcard_mono:\n  \"A |\\<subseteq>| B \\<Longrightarrow> fcard A \\<le> fcard B\"\nby transfer (rule card_mono)\n\nlemma fcard_seteq: \"A |\\<subseteq>| B \\<Longrightarrow> fcard B \\<le> fcard A \\<Longrightarrow> A = B\"\nby transfer (rule card_seteq)\n\nlemma pfsubset_fcard_mono: \"A |\\<subset>| B \\<Longrightarrow> fcard A < fcard B\"\nby transfer (rule psubset_card_mono)\n\nlemma fcard_funion_finter:\n  \"fcard A + fcard B = fcard (A |\\<union>| B) + fcard (A |\\<inter>| B)\"\nby transfer (rule card_Un_Int)\n\nlemma fcard_funion_disjoint:\n  \"A |\\<inter>| B = {||} \\<Longrightarrow> fcard (A |\\<union>| B) = fcard A + fcard B\"\nby transfer (rule card_Un_disjoint)\n\nlemma fcard_funion_fsubset:\n  \"B |\\<subseteq>| A \\<Longrightarrow> fcard (A |-| B) = fcard A - fcard B\"\nby transfer (rule card_Diff_subset)\n\nlemma diff_fcard_le_fcard_fminus:\n  \"fcard A - fcard B \\<le> fcard(A |-| B)\"\nby transfer (rule diff_card_le_card_Diff)\n\nlemma fcard_fminus1_less: \"x |\\<in>| A \\<Longrightarrow> fcard (A |-| {|x|}) < fcard A\"\nby transfer (rule card_Diff1_less)\n\nlemma fcard_fminus2_less:\n  \"x |\\<in>| A \\<Longrightarrow> y |\\<in>| A \\<Longrightarrow> fcard (A |-| {|x|} |-| {|y|}) < fcard A\"\nby transfer (rule card_Diff2_less)\n\nlemma fcard_fminus1_le: \"fcard (A |-| {|x|}) \\<le> fcard A\"\nby transfer (rule card_Diff1_le)\n\nlemma fcard_pfsubset: \"A |\\<subseteq>| B \\<Longrightarrow> fcard A < fcard B \\<Longrightarrow> A < B\"\nby transfer (rule card_psubset)\n\n\nsubsubsection \\<open>\\<open>sorted_list_of_fset\\<close>\\<close>\n\nlemma sorted_list_of_fset_simps[simp]:\n  \"set (sorted_list_of_fset S) = fset S\"\n  \"fset_of_list (sorted_list_of_fset S) = S\"\nby (transfer, simp)+\n\n\nsubsubsection \\<open>\\<open>ffold\\<close>\\<close>\n\n(* FIXME: improve transferred to handle bounded meta quantification *)\n\ncontext comp_fun_commute\nbegin\n  lemmas ffold_empty[simp] = fold_empty[Transfer.transferred]\n\n  lemma ffold_finsert [simp]:\n    assumes \"x |\\<notin>| A\"\n    shows \"ffold f z (finsert x A) = f x (ffold f z A)\"\n    using assms by (transfer fixing: f) (rule fold_insert)\n\n  lemma ffold_fun_left_comm:\n    \"f x (ffold f z A) = ffold f (f x z) A\"\n    by (transfer fixing: f) (rule fold_fun_left_comm)\n\n  lemma ffold_finsert2:\n    \"x |\\<notin>| A \\<Longrightarrow> ffold f z (finsert x A) = ffold f (f x z) A\"\n    by (transfer fixing: f) (rule fold_insert2)\n\n  lemma ffold_rec:\n    assumes \"x |\\<in>| A\"\n    shows \"ffold f z A = f x (ffold f z (A |-| {|x|}))\"\n    using assms by (transfer fixing: f) (rule fold_rec)\n\n  lemma ffold_finsert_fremove:\n    \"ffold f z (finsert x A) = f x (ffold f z (A |-| {|x|}))\"\n     by (transfer fixing: f) (rule fold_insert_remove)\nend\n\nlemma ffold_fimage:\n  assumes \"inj_on g (fset A)\"\n  shows \"ffold f z (g |`| A) = ffold (f \\<circ> g) z A\"\nusing assms by transfer' (rule fold_image)\n\nlemma ffold_cong:\n  assumes \"comp_fun_commute f\" \"comp_fun_commute g\"\n  \"\\<And>x. x |\\<in>| A \\<Longrightarrow> f x = g x\"\n    and \"s = t\" and \"A = B\"\n  shows \"ffold f s A = ffold g t B\"\n  using assms[unfolded comp_fun_commute_def']\n  by transfer (meson Finite_Set.fold_cong subset_UNIV)\n\ncontext comp_fun_idem\nbegin\n\n  lemma ffold_finsert_idem:\n    \"ffold f z (finsert x A) = f x (ffold f z A)\"\n    by (transfer fixing: f) (rule fold_insert_idem)\n\n  declare ffold_finsert [simp del] ffold_finsert_idem [simp]\n\n  lemma ffold_finsert_idem2:\n    \"ffold f z (finsert x A) = ffold f (f x z) A\"\n    by (transfer fixing: f) (rule fold_insert_idem2)\n\nend\n\n\nsubsubsection \\<open>Group operations\\<close>\n\nlocale comm_monoid_fset = comm_monoid\nbegin\n\nsublocale set: comm_monoid_set ..\n\nlift_definition F :: \"('b \\<Rightarrow> 'a) \\<Rightarrow> 'b fset \\<Rightarrow> 'a\" is set.F .\n\nlemmas cong[fundef_cong] = set.cong[Transfer.transferred]\n\nlemma cong_simp[cong]:\n  \"\\<lbrakk> A = B;  \\<And>x. x |\\<in>| B =simp=> g x = h x \\<rbrakk> \\<Longrightarrow> F g A = F h B\"\nunfolding simp_implies_def by (auto cong: cong)\n\nend\n\ncontext comm_monoid_add begin\n\nsublocale fsum: comm_monoid_fset plus 0\n  rewrites \"comm_monoid_set.F plus 0 = sum\"\n  defines fsum = fsum.F\nproof -\n  show \"comm_monoid_fset (+) 0\" by standard\n\n  show \"comm_monoid_set.F (+) 0 = sum\" unfolding sum_def ..\nqed\n\nend\n\n\nsubsubsection \\<open>Semilattice operations\\<close>\n\nlocale semilattice_fset = semilattice\nbegin\n\nsublocale set: semilattice_set ..\n\nlift_definition F :: \"'a fset \\<Rightarrow> 'a\" is set.F .\n\nlemma eq_fold: \"F (finsert x A) = ffold f x A\"\n  by transfer (rule set.eq_fold)\n\nlemma singleton [simp]: \"F {|x|} = x\"\n  by transfer (rule set.singleton)\n\nlemma insert_not_elem: \"x |\\<notin>| A \\<Longrightarrow> A \\<noteq> {||} \\<Longrightarrow> F (finsert x A) = x \\<^bold>* F A\"\n  by transfer (rule set.insert_not_elem)\n\nlemma in_idem: \"x |\\<in>| A \\<Longrightarrow> x \\<^bold>* F A = F A\"\n  by transfer (rule set.in_idem)\n\nlemma insert [simp]: \"A \\<noteq> {||} \\<Longrightarrow> F (finsert x A) = x \\<^bold>* F A\"\n  by transfer (rule set.insert)\n\nend\n\nlocale semilattice_order_fset = binary?: semilattice_order + semilattice_fset\nbegin\n\nend\n\n\ncontext linorder begin\n\nsublocale fMin: semilattice_order_fset min less_eq less\n  rewrites \"semilattice_set.F min = Min\"\n  defines fMin = fMin.F\nproof -\n  show \"semilattice_order_fset min (\\<le>) (<)\" by standard\n\n  show \"semilattice_set.F min = Min\" unfolding Min_def ..\nqed\n\nsublocale fMax: semilattice_order_fset max greater_eq greater\n  rewrites \"semilattice_set.F max = Max\"\n  defines fMax = fMax.F\nproof -\n  show \"semilattice_order_fset max (\\<ge>) (>)\"\n    by standard\n\n  show \"semilattice_set.F max = Max\"\n    unfolding Max_def ..\nqed\n\nend\n\nlemma mono_fMax_commute: \"mono f \\<Longrightarrow> A \\<noteq> {||} \\<Longrightarrow> f (fMax A) = fMax (f |`| A)\"\n  by transfer (rule mono_Max_commute)\n\nlemma mono_fMin_commute: \"mono f \\<Longrightarrow> A \\<noteq> {||} \\<Longrightarrow> f (fMin A) = fMin (f |`| A)\"\n  by transfer (rule mono_Min_commute)\n\nlemma fMax_in[simp]: \"A \\<noteq> {||} \\<Longrightarrow> fMax A |\\<in>| A\"\n  by transfer (rule Max_in)\n\nlemma fMin_in[simp]: \"A \\<noteq> {||} \\<Longrightarrow> fMin A |\\<in>| A\"\n  by transfer (rule Min_in)\n\nlemma fMax_ge[simp]: \"x |\\<in>| A \\<Longrightarrow> x \\<le> fMax A\"\n  by transfer (rule Max_ge)\n\nlemma fMin_le[simp]: \"x |\\<in>| A \\<Longrightarrow> fMin A \\<le> x\"\n  by transfer (rule Min_le)\n\nlemma fMax_eqI: \"(\\<And>y. y |\\<in>| A \\<Longrightarrow> y \\<le> x) \\<Longrightarrow> x |\\<in>| A \\<Longrightarrow> fMax A = x\"\n  by transfer (rule Max_eqI)\n\nlemma fMin_eqI: \"(\\<And>y. y |\\<in>| A \\<Longrightarrow> x \\<le> y) \\<Longrightarrow> x |\\<in>| A \\<Longrightarrow> fMin A = x\"\n  by transfer (rule Min_eqI)\n\nlemma fMax_finsert[simp]: \"fMax (finsert x A) = (if A = {||} then x else max x (fMax A))\"\n  by transfer simp\n\nlemma fMin_finsert[simp]: \"fMin (finsert x A) = (if A = {||} then x else min x (fMin A))\"\n  by transfer simp\n\ncontext linorder begin\n\nlemma fset_linorder_max_induct[case_names fempty finsert]:\n  assumes \"P {||}\"\n  and     \"\\<And>x S. \\<lbrakk>\\<forall>y. y |\\<in>| S \\<longrightarrow> y < x; P S\\<rbrakk> \\<Longrightarrow> P (finsert x S)\"\n  shows \"P S\"\nproof -\n  (* FIXME transfer and right_total vs. bi_total *)\n  note Domainp_forall_transfer[transfer_rule]\n  show ?thesis\n  using assms by (transfer fixing: less) (auto intro: finite_linorder_max_induct)\nqed\n\nlemma fset_linorder_min_induct[case_names fempty finsert]:\n  assumes \"P {||}\"\n  and     \"\\<And>x S. \\<lbrakk>\\<forall>y. y |\\<in>| S \\<longrightarrow> y > x; P S\\<rbrakk> \\<Longrightarrow> P (finsert x S)\"\n  shows \"P S\"\nproof -\n  (* FIXME transfer and right_total vs. bi_total *)\n  note Domainp_forall_transfer[transfer_rule]\n  show ?thesis\n  using assms by (transfer fixing: less) (auto intro: finite_linorder_min_induct)\nqed\n\nend\n\n\nsubsection \\<open>Choice in fsets\\<close>\n\nlemma fset_choice:\n  assumes \"\\<forall>x. x |\\<in>| A \\<longrightarrow> (\\<exists>y. P x y)\"\n  shows \"\\<exists>f. \\<forall>x. x |\\<in>| A \\<longrightarrow> P x (f x)\"\n  using assms by transfer metis\n\n\nsubsection \\<open>Induction and Cases rules for fsets\\<close>\n\nlemma fset_exhaust [case_names empty insert, cases type: fset]:\n  assumes fempty_case: \"S = {||} \\<Longrightarrow> P\"\n  and     finsert_case: \"\\<And>x S'. S = finsert x S' \\<Longrightarrow> P\"\n  shows \"P\"\n  using assms by transfer blast\n\nlemma fset_induct [case_names empty insert]:\n  assumes fempty_case: \"P {||}\"\n  and     finsert_case: \"\\<And>x S. P S \\<Longrightarrow> P (finsert x S)\"\n  shows \"P S\"\nproof -\n  (* FIXME transfer and right_total vs. bi_total *)\n  note Domainp_forall_transfer[transfer_rule]\n  show ?thesis\n  using assms by transfer (auto intro: finite_induct)\nqed\n\nlemma fset_induct_stronger [case_names empty insert, induct type: fset]:\n  assumes empty_fset_case: \"P {||}\"\n  and     insert_fset_case: \"\\<And>x S. \\<lbrakk>x |\\<notin>| S; P S\\<rbrakk> \\<Longrightarrow> P (finsert x S)\"\n  shows \"P S\"\nproof -\n  (* FIXME transfer and right_total vs. bi_total *)\n  note Domainp_forall_transfer[transfer_rule]\n  show ?thesis\n  using assms by transfer (auto intro: finite_induct)\nqed\n\nlemma fset_card_induct:\n  assumes empty_fset_case: \"P {||}\"\n  and     card_fset_Suc_case: \"\\<And>S T. Suc (fcard S) = (fcard T) \\<Longrightarrow> P S \\<Longrightarrow> P T\"\n  shows \"P S\"\nproof (induct S)\n  case empty\n  show \"P {||}\" by (rule empty_fset_case)\nnext\n  case (insert x S)\n  have h: \"P S\" by fact\n  have \"x |\\<notin>| S\" by fact\n  then have \"Suc (fcard S) = fcard (finsert x S)\"\n    by transfer auto\n  then show \"P (finsert x S)\"\n    using h card_fset_Suc_case by simp\nqed\n\nlemma fset_strong_cases:\n  obtains \"xs = {||}\"\n    | ys x where \"x |\\<notin>| ys\" and \"xs = finsert x ys\"\nby transfer blast\n\nlemma fset_induct2:\n  \"P {||} {||} \\<Longrightarrow>\n  (\\<And>x xs. x |\\<notin>| xs \\<Longrightarrow> P (finsert x xs) {||}) \\<Longrightarrow>\n  (\\<And>y ys. y |\\<notin>| ys \\<Longrightarrow> P {||} (finsert y ys)) \\<Longrightarrow>\n  (\\<And>x xs y ys. \\<lbrakk>P xs ys; x |\\<notin>| xs; y |\\<notin>| ys\\<rbrakk> \\<Longrightarrow> P (finsert x xs) (finsert y ys)) \\<Longrightarrow>\n  P xsa ysa\"\n  apply (induct xsa arbitrary: ysa)\n  apply (induct_tac x rule: fset_induct_stronger)\n  apply simp_all\n  apply (induct_tac xa rule: fset_induct_stronger)\n  apply simp_all\n  done\n\n\nsubsection \\<open>Setup for Lifting/Transfer\\<close>\n\nsubsubsection \\<open>Relator and predicator properties\\<close>\n\nlift_definition rel_fset :: \"('a \\<Rightarrow> 'b \\<Rightarrow> bool) \\<Rightarrow> 'a fset \\<Rightarrow> 'b fset \\<Rightarrow> bool\" is rel_set\nparametric rel_set_transfer .\n\nlemma rel_fset_alt_def: \"rel_fset R = (\\<lambda>A B. (\\<forall>x.\\<exists>y. x|\\<in>|A \\<longrightarrow> y|\\<in>|B \\<and> R x y)\n  \\<and> (\\<forall>y. \\<exists>x. y|\\<in>|B \\<longrightarrow> x|\\<in>|A \\<and> R x y))\"\napply (rule ext)+\napply transfer'\napply (subst rel_set_def[unfolded fun_eq_iff])\nby blast\n\nlemma finite_rel_set:\n  assumes fin: \"finite X\" \"finite Z\"\n  assumes R_S: \"rel_set (R OO S) X Z\"\n  shows \"\\<exists>Y. finite Y \\<and> rel_set R X Y \\<and> rel_set S Y Z\"\nproof -\n  obtain f where f: \"\\<forall>x\\<in>X. R x (f x) \\<and> (\\<exists>z\\<in>Z. S (f x) z)\"\n  apply atomize_elim\n  apply (subst bchoice_iff[symmetric])\n  using R_S[unfolded rel_set_def OO_def] by blast\n\n  obtain g where g: \"\\<forall>z\\<in>Z. S (g z) z \\<and> (\\<exists>x\\<in>X. R x (g z))\"\n  apply atomize_elim\n  apply (subst bchoice_iff[symmetric])\n  using R_S[unfolded rel_set_def OO_def] by blast\n\n  let ?Y = \"f ` X \\<union> g ` Z\"\n  have \"finite ?Y\" by (simp add: fin)\n  moreover have \"rel_set R X ?Y\"\n    unfolding rel_set_def\n    using f g by clarsimp blast\n  moreover have \"rel_set S ?Y Z\"\n    unfolding rel_set_def\n    using f g by clarsimp blast\n  ultimately show ?thesis by metis\nqed\n\nsubsubsection \\<open>Transfer rules for the Transfer package\\<close>\n\ntext \\<open>Unconditional transfer rules\\<close>\n\ncontext includes lifting_syntax\nbegin\n\nlemmas fempty_transfer [transfer_rule] = empty_transfer[Transfer.transferred]\n\nlemma finsert_transfer [transfer_rule]:\n  \"(A ===> rel_fset A ===> rel_fset A) finsert finsert\"\n  unfolding rel_fun_def rel_fset_alt_def by blast\n\nlemma funion_transfer [transfer_rule]:\n  \"(rel_fset A ===> rel_fset A ===> rel_fset A) funion funion\"\n  unfolding rel_fun_def rel_fset_alt_def by blast\n\nlemma ffUnion_transfer [transfer_rule]:\n  \"(rel_fset (rel_fset A) ===> rel_fset A) ffUnion ffUnion\"\n  unfolding rel_fun_def rel_fset_alt_def by transfer (simp, fast)\n\nlemma fimage_transfer [transfer_rule]:\n  \"((A ===> B) ===> rel_fset A ===> rel_fset B) fimage fimage\"\n  unfolding rel_fun_def rel_fset_alt_def by simp blast\n\nlemma fBall_transfer [transfer_rule]:\n  \"(rel_fset A ===> (A ===> (=)) ===> (=)) fBall fBall\"\n  unfolding rel_fset_alt_def rel_fun_def by blast\n\nlemma fBex_transfer [transfer_rule]:\n  \"(rel_fset A ===> (A ===> (=)) ===> (=)) fBex fBex\"\n  unfolding rel_fset_alt_def rel_fun_def by blast\n\n(* FIXME transfer doesn't work here *)\nlemma fPow_transfer [transfer_rule]:\n  \"(rel_fset A ===> rel_fset (rel_fset A)) fPow fPow\"\n  unfolding rel_fun_def\n  using Pow_transfer[unfolded rel_fun_def, rule_format, Transfer.transferred]\n  by blast\n\nlemma rel_fset_transfer [transfer_rule]:\n  \"((A ===> B ===> (=)) ===> rel_fset A ===> rel_fset B ===> (=))\n    rel_fset rel_fset\"\n  unfolding rel_fun_def\n  using rel_set_transfer[unfolded rel_fun_def,rule_format, Transfer.transferred, where A = A and B = B]\n  by simp\n\nlemma bind_transfer [transfer_rule]:\n  \"(rel_fset A ===> (A ===> rel_fset B) ===> rel_fset B) fbind fbind\"\n  unfolding rel_fun_def\n  using bind_transfer[unfolded rel_fun_def, rule_format, Transfer.transferred] by blast\n\ntext \\<open>Rules requiring bi-unique, bi-total or right-total relations\\<close>\n\nlemma fmember_transfer [transfer_rule]:\n  assumes \"bi_unique A\"\n  shows \"(A ===> rel_fset A ===> (=)) (|\\<in>|) (|\\<in>|)\"\n  using assms unfolding rel_fun_def rel_fset_alt_def bi_unique_def by metis\n\nlemma finter_transfer [transfer_rule]:\n  assumes \"bi_unique A\"\n  shows \"(rel_fset A ===> rel_fset A ===> rel_fset A) finter finter\"\n  using assms unfolding rel_fun_def\n  using inter_transfer[unfolded rel_fun_def, rule_format, Transfer.transferred] by blast\n\nlemma fminus_transfer [transfer_rule]:\n  assumes \"bi_unique A\"\n  shows \"(rel_fset A ===> rel_fset A ===> rel_fset A) (|-|) (|-|)\"\n  using assms unfolding rel_fun_def\n  using Diff_transfer[unfolded rel_fun_def, rule_format, Transfer.transferred] by blast\n\nlemma fsubset_transfer [transfer_rule]:\n  assumes \"bi_unique A\"\n  shows \"(rel_fset A ===> rel_fset A ===> (=)) (|\\<subseteq>|) (|\\<subseteq>|)\"\n  using assms unfolding rel_fun_def\n  using subset_transfer[unfolded rel_fun_def, rule_format, Transfer.transferred] by blast\n\nlemma fSup_transfer [transfer_rule]:\n  \"bi_unique A \\<Longrightarrow> (rel_set (rel_fset A) ===> rel_fset A) Sup Sup\"\n  unfolding rel_fun_def\n  apply clarify\n  apply transfer'\n  using Sup_fset_transfer[unfolded rel_fun_def] by blast\n\n(* FIXME: add right_total_fInf_transfer *)\n\nlemma fInf_transfer [transfer_rule]:\n  assumes \"bi_unique A\" and \"bi_total A\"\n  shows \"(rel_set (rel_fset A) ===> rel_fset A) Inf Inf\"\n  using assms unfolding rel_fun_def\n  apply clarify\n  apply transfer'\n  using Inf_fset_transfer[unfolded rel_fun_def] by blast\n\nlemma ffilter_transfer [transfer_rule]:\n  assumes \"bi_unique A\"\n  shows \"((A ===> (=)) ===> rel_fset A ===> rel_fset A) ffilter ffilter\"\n  using assms unfolding rel_fun_def\n  using Lifting_Set.filter_transfer[unfolded rel_fun_def, rule_format, Transfer.transferred] by blast\n\nlemma card_transfer [transfer_rule]:\n  \"bi_unique A \\<Longrightarrow> (rel_fset A ===> (=)) fcard fcard\"\n  unfolding rel_fun_def\n  using card_transfer[unfolded rel_fun_def, rule_format, Transfer.transferred] by blast\n\nend\n\nlifting_update fset.lifting\nlifting_forget fset.lifting\n\n\nsubsection \\<open>BNF setup\\<close>\n\ncontext\nincludes fset.lifting\nbegin\n\nlemma rel_fset_alt:\n  \"rel_fset R a b \\<longleftrightarrow> (\\<forall>t \\<in> fset a. \\<exists>u \\<in> fset b. R t u) \\<and> (\\<forall>t \\<in> fset b. \\<exists>u \\<in> fset a. R u t)\"\nby transfer (simp add: rel_set_def)\n\nlemma fset_to_fset: \"finite A \\<Longrightarrow> fset (the_inv fset A) = A\"\napply (rule f_the_inv_into_f[unfolded inj_on_def])\napply (simp add: fset_inject)\napply (rule range_eqI Abs_fset_inverse[symmetric] CollectI)+\n.\n\nlemma rel_fset_aux:\n\"(\\<forall>t \\<in> fset a. \\<exists>u \\<in> fset b. R t u) \\<and> (\\<forall>u \\<in> fset b. \\<exists>t \\<in> fset a. R t u) \\<longleftrightarrow>\n ((BNF_Def.Grp {a. fset a \\<subseteq> {(a, b). R a b}} (fimage fst))\\<inverse>\\<inverse> OO\n  BNF_Def.Grp {a. fset a \\<subseteq> {(a, b). R a b}} (fimage snd)) a b\" (is \"?L = ?R\")\nproof\n  assume ?L\n  define R' where \"R' =\n    the_inv fset (Collect (case_prod R) \\<inter> (fset a \\<times> fset b))\" (is \"_ = the_inv fset ?L'\")\n  have \"finite ?L'\" by (intro finite_Int[OF disjI2] finite_cartesian_product) (transfer, simp)+\n  hence *: \"fset R' = ?L'\" unfolding R'_def by (intro fset_to_fset)\n  show ?R unfolding Grp_def relcompp.simps conversep.simps\n  proof (intro CollectI case_prodI exI[of _ a] exI[of _ b] exI[of _ R'] conjI refl)\n    from * show \"a = fimage fst R'\" using conjunct1[OF \\<open>?L\\<close>]\n      by (transfer, auto simp add: image_def Int_def split: prod.splits)\n    from * show \"b = fimage snd R'\" using conjunct2[OF \\<open>?L\\<close>]\n      by (transfer, auto simp add: image_def Int_def split: prod.splits)\n  qed (auto simp add: *)\nnext\n  assume ?R thus ?L unfolding Grp_def relcompp.simps conversep.simps\n  apply (simp add: subset_eq Ball_def)\n  apply (rule conjI)\n  apply (transfer, clarsimp, metis snd_conv)\n  by (transfer, clarsimp, metis fst_conv)\nqed\n\nbnf \"'a fset\"\n  map: fimage\n  sets: fset\n  bd: natLeq\n  wits: \"{||}\"\n  rel: rel_fset\napply -\n          apply transfer' apply simp\n         apply transfer' apply force\n        apply transfer apply force\n       apply transfer' apply force\n      apply (rule natLeq_card_order)\n     apply (rule natLeq_cinfinite)\n    apply transfer apply (metis ordLess_imp_ordLeq finite_iff_ordLess_natLeq)\n   apply (fastforce simp: rel_fset_alt)\n apply (simp add: Grp_def relcompp.simps conversep.simps fun_eq_iff rel_fset_alt\n   rel_fset_aux[unfolded OO_Grp_alt])\napply transfer apply simp\ndone\n\nlemma rel_fset_fset: \"rel_set \\<chi> (fset A1) (fset A2) = rel_fset \\<chi> A1 A2\"\n  by transfer (rule refl)\n\nend\n\nlemmas [simp] = fset.map_comp fset.map_id fset.set_map\n\n\nsubsection \\<open>Size setup\\<close>\n\ncontext includes fset.lifting begin\nlift_definition size_fset :: \"('a \\<Rightarrow> nat) \\<Rightarrow> 'a fset \\<Rightarrow> nat\" is \"\\<lambda>f. sum (Suc \\<circ> f)\" .\nend\n\ninstantiation fset :: (type) size begin\ndefinition size_fset where\n  size_fset_overloaded_def: \"size_fset = FSet.size_fset (\\<lambda>_. 0)\"\ninstance ..\nend\n\nlemmas size_fset_simps[simp] =\n  size_fset_def[THEN meta_eq_to_obj_eq, THEN fun_cong, THEN fun_cong,\n    unfolded map_fun_def comp_def id_apply]\n\nlemmas size_fset_overloaded_simps[simp] =\n  size_fset_simps[of \"\\<lambda>_. 0\", unfolded add_0_left add_0_right,\n    folded size_fset_overloaded_def]\n\nlemma fset_size_o_map: \"inj f \\<Longrightarrow> size_fset g \\<circ> fimage f = size_fset (g \\<circ> f)\"\n  apply (subst fun_eq_iff)\n  including fset.lifting by transfer (auto intro: sum.reindex_cong subset_inj_on)\n\nsetup \\<open>\nBNF_LFP_Size.register_size_global \\<^type_name>\\<open>fset\\<close> \\<^const_name>\\<open>size_fset\\<close>\n  @{thm size_fset_overloaded_def} @{thms size_fset_simps size_fset_overloaded_simps}\n  @{thms fset_size_o_map}\n\\<close>\n\nlifting_update fset.lifting\nlifting_forget fset.lifting\n\nsubsection \\<open>Advanced relator customization\\<close>\n\ntext \\<open>Set vs. sum relators:\\<close>\n\nlemma rel_set_rel_sum[simp]:\n\"rel_set (rel_sum \\<chi> \\<phi>) A1 A2 \\<longleftrightarrow>\n rel_set \\<chi> (Inl -` A1) (Inl -` A2) \\<and> rel_set \\<phi> (Inr -` A1) (Inr -` A2)\"\n(is \"?L \\<longleftrightarrow> ?Rl \\<and> ?Rr\")\nproof safe\n  assume L: \"?L\"\n  show ?Rl unfolding rel_set_def Bex_def vimage_eq proof safe\n    fix l1 assume \"Inl l1 \\<in> A1\"\n    then obtain a2 where a2: \"a2 \\<in> A2\" and \"rel_sum \\<chi> \\<phi> (Inl l1) a2\"\n    using L unfolding rel_set_def by auto\n    then obtain l2 where \"a2 = Inl l2 \\<and> \\<chi> l1 l2\" by (cases a2, auto)\n    thus \"\\<exists> l2. Inl l2 \\<in> A2 \\<and> \\<chi> l1 l2\" using a2 by auto\n  next\n    fix l2 assume \"Inl l2 \\<in> A2\"\n    then obtain a1 where a1: \"a1 \\<in> A1\" and \"rel_sum \\<chi> \\<phi> a1 (Inl l2)\"\n    using L unfolding rel_set_def by auto\n    then obtain l1 where \"a1 = Inl l1 \\<and> \\<chi> l1 l2\" by (cases a1, auto)\n    thus \"\\<exists> l1. Inl l1 \\<in> A1 \\<and> \\<chi> l1 l2\" using a1 by auto\n  qed\n  show ?Rr unfolding rel_set_def Bex_def vimage_eq proof safe\n    fix r1 assume \"Inr r1 \\<in> A1\"\n    then obtain a2 where a2: \"a2 \\<in> A2\" and \"rel_sum \\<chi> \\<phi> (Inr r1) a2\"\n    using L unfolding rel_set_def by auto\n    then obtain r2 where \"a2 = Inr r2 \\<and> \\<phi> r1 r2\" by (cases a2, auto)\n    thus \"\\<exists> r2. Inr r2 \\<in> A2 \\<and> \\<phi> r1 r2\" using a2 by auto\n  next\n    fix r2 assume \"Inr r2 \\<in> A2\"\n    then obtain a1 where a1: \"a1 \\<in> A1\" and \"rel_sum \\<chi> \\<phi> a1 (Inr r2)\"\n    using L unfolding rel_set_def by auto\n    then obtain r1 where \"a1 = Inr r1 \\<and> \\<phi> r1 r2\" by (cases a1, auto)\n    thus \"\\<exists> r1. Inr r1 \\<in> A1 \\<and> \\<phi> r1 r2\" using a1 by auto\n  qed\nnext\n  assume Rl: \"?Rl\" and Rr: \"?Rr\"\n  show ?L unfolding rel_set_def Bex_def vimage_eq proof safe\n    fix a1 assume a1: \"a1 \\<in> A1\"\n    show \"\\<exists> a2. a2 \\<in> A2 \\<and> rel_sum \\<chi> \\<phi> a1 a2\"\n    proof(cases a1)\n      case (Inl l1) then obtain l2 where \"Inl l2 \\<in> A2 \\<and> \\<chi> l1 l2\"\n      using Rl a1 unfolding rel_set_def by blast\n      thus ?thesis unfolding Inl by auto\n    next\n      case (Inr r1) then obtain r2 where \"Inr r2 \\<in> A2 \\<and> \\<phi> r1 r2\"\n      using Rr a1 unfolding rel_set_def by blast\n      thus ?thesis unfolding Inr by auto\n    qed\n  next\n    fix a2 assume a2: \"a2 \\<in> A2\"\n    show \"\\<exists> a1. a1 \\<in> A1 \\<and> rel_sum \\<chi> \\<phi> a1 a2\"\n    proof(cases a2)\n      case (Inl l2) then obtain l1 where \"Inl l1 \\<in> A1 \\<and> \\<chi> l1 l2\"\n      using Rl a2 unfolding rel_set_def by blast\n      thus ?thesis unfolding Inl by auto\n    next\n      case (Inr r2) then obtain r1 where \"Inr r1 \\<in> A1 \\<and> \\<phi> r1 r2\"\n      using Rr a2 unfolding rel_set_def by blast\n      thus ?thesis unfolding Inr by auto\n    qed\n  qed\nqed\n\n\nsubsubsection \\<open>Countability\\<close>\n\n\n\nlemma fset_of_list_surj[simp, intro]: \"surj fset_of_list\"\nproof -\n  have \"x \\<in> range fset_of_list\" for x :: \"'a fset\"\n    unfolding image_iff\n    using exists_fset_of_list by fastforce\n  thus ?thesis by auto\nqed\n\ninstance fset :: (countable) countable\nproof\n  obtain to_nat :: \"'a list \\<Rightarrow> nat\" where \"inj to_nat\"\n    by (metis ex_inj)\n  moreover have \"inj (inv fset_of_list)\"\n    using fset_of_list_surj by (rule surj_imp_inj_inv)\n  ultimately have \"inj (to_nat \\<circ> inv fset_of_list)\"\n    by (rule inj_compose)\n  thus \"\\<exists>to_nat::'a fset \\<Rightarrow> nat. inj to_nat\"\n    by auto\nqed\n\n\nsubsection \\<open>Quickcheck setup\\<close>\n\ntext \\<open>Setup adapted from sets.\\<close>\n\nnotation Quickcheck_Exhaustive.orelse (infixr \"orelse\" 55)\n\ncontext\n  includes term_syntax\nbegin\n\ndefinition [code_unfold]:\n\"valterm_femptyset = Code_Evaluation.valtermify ({||} :: ('a :: typerep) fset)\"\n\ndefinition [code_unfold]:\n\"valtermify_finsert x s = Code_Evaluation.valtermify finsert {\\<cdot>} (x :: ('a :: typerep * _)) {\\<cdot>} s\"\n\nend\n\ninstantiation fset :: (exhaustive) exhaustive\nbegin\n\nfun exhaustive_fset where\n\"exhaustive_fset f i = (if i = 0 then None else (f {||} orelse exhaustive_fset (\\<lambda>A. f A orelse Quickcheck_Exhaustive.exhaustive (\\<lambda>x. if x |\\<in>| A then None else f (finsert x A)) (i - 1)) (i - 1)))\"\n\ninstance ..\n\nend\n\ninstantiation fset :: (full_exhaustive) full_exhaustive\nbegin\n\nfun full_exhaustive_fset where\n\"full_exhaustive_fset f i = (if i = 0 then None else (f valterm_femptyset orelse full_exhaustive_fset (\\<lambda>A. f A orelse Quickcheck_Exhaustive.full_exhaustive (\\<lambda>x. if fst x |\\<in>| fst A then None else f (valtermify_finsert x A)) (i - 1)) (i - 1)))\"\n\ninstance ..\n\nend\n\nno_notation Quickcheck_Exhaustive.orelse (infixr \"orelse\" 55)\n\ninstantiation fset :: (random) random\nbegin\n\ncontext\n  includes state_combinator_syntax\nbegin\n\nfun random_aux_fset :: \"natural \\<Rightarrow> natural \\<Rightarrow> natural \\<times> natural \\<Rightarrow> ('a fset \\<times> (unit \\<Rightarrow> term)) \\<times> natural \\<times> natural\" where\n\"random_aux_fset 0 j = Quickcheck_Random.collapse (Random.select_weight [(1, Pair valterm_femptyset)])\" |\n\"random_aux_fset (Code_Numeral.Suc i) j =\n  Quickcheck_Random.collapse (Random.select_weight\n    [(1, Pair valterm_femptyset),\n     (Code_Numeral.Suc i,\n      Quickcheck_Random.random j \\<circ>\\<rightarrow> (\\<lambda>x. random_aux_fset i j \\<circ>\\<rightarrow> (\\<lambda>s. Pair (valtermify_finsert x s))))])\"\n\n\n\ndefinition \"random_fset i = random_aux_fset i i\"\n\ninstance ..\n\nend\n\nend\n\n\n(*******************)\n(* the fset type-definition is wide *)\n\n\nlemma neper_rel_fset[simp]: \"neper R \\<Longrightarrow> neper (rel_fset R)\"\nby (metis (no_types, lifting) fempty_transfer fset.rel_flip fset.rel_transp \n       neper_conversep neper_def per_def transp_def) \n\ndefinition gg where \"gg R X \\<equiv> {x \\<in> fset X. R x x}\"\n   \nlemma bij_upto_gg: \nassumes R: \"neper R\"\nshows \"bij_upto (rel_fset R) (restr (rel_set R) (finite_rlt R)) (gg R)\"\nproof(rule bij_uptoI)\n  show \"neper (restr (rel_set R) (finite_rlt R))\" \n    by (meson assms empty_transfer finite_rlt_empty neper_restr set.rrel_neper)\nnext\n  fix A1 A2\n  assume RA12: \"rel_fset R A1 A2\"\n  show \"restr (rel_set R) (finite_rlt R) (gg R A1) (gg R A2)\"\n  unfolding restr_def proof safe\n    show \"rel_set R (gg R A1) (gg R A2)\" \n    using RA12 unfolding gg_def rel_fset_def rel_set_def  \n    by simp (metis assms neper_per per_def)\n  next\n    show \"finite_rlt R (gg R A1)\"\n    unfolding gg_def by (simp add: assms finite_imp_finite_rlt)\n  next\n    show \"finite_rlt R (gg R A2)\"\n    unfolding gg_def by (simp add: assms finite_imp_finite_rlt)\n  qed\nnext\n  fix A1 A2\n  assume A1: \"rel_fset R A1 A1\" and A2: \"rel_fset R A2 A2\"\n  and A12: \"restr (rel_set R) (finite_rlt R) (gg R A1) (gg R A2)\"\n  have \"rel_set R (fset A1) (fset A2)\" \n  using A12 A1 A2 unfolding restr_def gg_def rel_set_def \n  by simp (metis (mono_tags, lifting) assms neper_per per_def rel_fset_fset rel_setD2)\n  thus \"rel_fset R A1 A2\" unfolding rel_fset_def by auto\nnext\n  fix A assume \"restr (rel_set R) (finite_rlt R) A A\"\n  hence A: \"rel_set R A A\" \"finite_rlt R A\" unfolding restr_def by auto\n  define F where \"F = Abs_fset {getRepr R a | a.  a \\<in> A}\"\n  have [simp]: \"fset (Abs_fset {getRepr R a |a. a \\<in> A}) = {getRepr R a |a. a \\<in> A}\"\n  by (metis (mono_tags, lifting) A(1) A(2) Abs_fset_inverse assms \n    finite_rlt_imp_finite_getRepr mem_Collect_eq)\n  have fF: \"fset F = {getRepr R a | a.  a \\<in> A}\" \n  by (metis (mono_tags, lifting) A(1) A(2) Abs_fset_inverse F_def assms \n    finite_rlt_imp_finite_getRepr mem_Collect_eq)\n\n  show \"\\<exists>F. rel_fset R F F \\<and> restr (rel_set R) (finite_rlt R) A (gg R F)\"\n  proof(rule exI[of _ F], unfold restr_def, safe)\n    show \"rel_fset R F F\"\n    unfolding F_def rel_fset_def \n    unfolding rel_set_def \n    by simp (metis A(1) assms geterRepr_related neper_per per_def rel_setD2)\n  next\n    show \"rel_set R A (gg R F)\"\n    unfolding gg_def rel_set_def F_def \n    by auto (metis A(1) assms getRepr_neper neper_per per_def rel_setD2)+\n  next\n    show \"finite_rlt R A\" by fact\n  next\n    show \"finite_rlt R (gg R F)\" \n    unfolding gg_def  \n    by (simp add: assms finite_imp_finite_rlt)\n  qed\nqed\n\nlemma gg_eq[simp]: \"gg (=) = fset\"\nunfolding gg_def by auto\n\nwide_typedef fset rel: rel_fset rep: gg\n  subgoal using neper_rel_fset .\n  subgoal using FSet.fset.rel_eq .\n  subgoal using bij_upto_gg .\n  subgoal using gg_eq . .\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/FSet.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916134888613, "lm_q2_score": 0.8289388104343893, "lm_q1q2_score": 0.7156988170244847}}
{"text": "(*\n  Title:    HOL/Analysis/Infinite_Sum.thy\n  Author:   Dominique Unruh, University of Tartu\n            Manuel Eberl, University of Innsbruck\n\n  A theory of sums over possibly infinite sets.\n*)\n\nsection \\<open>Infinite sums\\<close>\n\\<^latex>\\<open>\\label{section:Infinite_Sum}\\<close>\n\ntext \\<open>In this theory, we introduce the definition of infinite sums, i.e., sums ranging over an\ninfinite, potentially uncountable index set with no particular ordering.\n(This is different from series. Those are sums indexed by natural numbers,\nand the order of the index set matters.)\n\nOur definition is quite standard: $s:=\\sum_{x\\in A} f(x)$ is the limit of finite sums $s_F:=\\sum_{x\\in F} f(x)$ for increasing $F$.\nThat is, $s$ is the limit of the net $s_F$ where $F$ are finite subsets of $A$ ordered by inclusion.\nWe believe that this is the standard definition for such sums.\nSee, e.g., Definition 4.11 in \\cite{conway2013course}.\nThis definition is quite general: it is well-defined whenever $f$ takes values in some\ncommutative monoid endowed with a Hausdorff topology.\n(Examples are reals, complex numbers, normed vector spaces, and more.)\\<close>\n\ntheory Infinite_Sum\n  imports\n    Elementary_Topology\n    \"HOL-Library.Extended_Nonnegative_Real\"\n    \"HOL-Library.Complex_Order\"\nbegin\n\nsubsection \\<open>Definition and syntax\\<close>\n\ndefinition has_sum :: \\<open>('a \\<Rightarrow> 'b :: {comm_monoid_add, topological_space}) \\<Rightarrow> 'a set \\<Rightarrow> 'b \\<Rightarrow> bool\\<close> where\n  \\<open>has_sum f A x \\<longleftrightarrow> (sum f \\<longlongrightarrow> x) (finite_subsets_at_top A)\\<close>\n\ndefinition summable_on :: \"('a \\<Rightarrow> 'b::{comm_monoid_add, topological_space}) \\<Rightarrow> 'a set \\<Rightarrow> bool\" (infixr \"summable'_on\" 46) where\n  \"f summable_on A \\<longleftrightarrow> (\\<exists>x. has_sum f A x)\"\n\ndefinition infsum :: \"('a \\<Rightarrow> 'b::{comm_monoid_add,t2_space}) \\<Rightarrow> 'a set \\<Rightarrow> 'b\" where\n  \"infsum f A = (if f summable_on A then Lim (finite_subsets_at_top A) (sum f) else 0)\"\n\nabbreviation abs_summable_on :: \"('a \\<Rightarrow> 'b::real_normed_vector) \\<Rightarrow> 'a set \\<Rightarrow> bool\" (infixr \"abs'_summable'_on\" 46) where\n  \"f abs_summable_on A \\<equiv> (\\<lambda>x. norm (f x)) summable_on A\"\n\nsyntax (ASCII)\n  \"_infsum\" :: \"pttrn \\<Rightarrow> 'a set \\<Rightarrow> 'b \\<Rightarrow> 'b::topological_comm_monoid_add\"  (\"(3INFSUM (_/:_)./ _)\" [0, 51, 10] 10)\nsyntax\n  \"_infsum\" :: \"pttrn \\<Rightarrow> 'a set \\<Rightarrow> 'b \\<Rightarrow> 'b::topological_comm_monoid_add\"  (\"(2\\<Sum>\\<^sub>\\<infinity>(_/\\<in>_)./ _)\" [0, 51, 10] 10)\ntranslations \\<comment> \\<open>Beware of argument permutation!\\<close>\n  \"\\<Sum>\\<^sub>\\<infinity>i\\<in>A. b\" \\<rightleftharpoons> \"CONST infsum (\\<lambda>i. b) A\"\n\nsyntax (ASCII)\n  \"_univinfsum\" :: \"pttrn \\<Rightarrow> 'a \\<Rightarrow> 'a\"  (\"(3INFSUM _./ _)\" [0, 10] 10)\nsyntax\n  \"_univinfsum\" :: \"pttrn \\<Rightarrow> 'a \\<Rightarrow> 'a\"  (\"(2\\<Sum>\\<^sub>\\<infinity>_./ _)\" [0, 10] 10)\ntranslations\n  \"\\<Sum>\\<^sub>\\<infinity>x. t\" \\<rightleftharpoons> \"CONST infsum (\\<lambda>x. t) (CONST UNIV)\"\n\nsyntax (ASCII)\n  \"_qinfsum\" :: \"pttrn \\<Rightarrow> bool \\<Rightarrow> 'a \\<Rightarrow> 'a\"  (\"(3INFSUM _ |/ _./ _)\" [0, 0, 10] 10)\nsyntax\n  \"_qinfsum\" :: \"pttrn \\<Rightarrow> bool \\<Rightarrow> 'a \\<Rightarrow> 'a\"  (\"(2\\<Sum>\\<^sub>\\<infinity>_ | (_)./ _)\" [0, 0, 10] 10)\ntranslations\n  \"\\<Sum>\\<^sub>\\<infinity>x|P. t\" => \"CONST infsum (\\<lambda>x. t) {x. P}\"\n\nprint_translation \\<open>\nlet\n  fun sum_tr' [Abs (x, Tx, t), Const (@{const_syntax Collect}, _) $ Abs (y, Ty, P)] =\n        if x <> y then raise Match\n        else\n          let\n            val x' = Syntax_Trans.mark_bound_body (x, Tx);\n            val t' = subst_bound (x', t);\n            val P' = subst_bound (x', P);\n          in\n            Syntax.const @{syntax_const \"_qinfsum\"} $ Syntax_Trans.mark_bound_abs (x, Tx) $ P' $ t'\n          end\n    | sum_tr' _ = raise Match;\nin [(@{const_syntax infsum}, K sum_tr')] end\n\\<close>\n\nsubsection \\<open>General properties\\<close>\n\nlemma infsumI:\n  fixes f g :: \\<open>'a \\<Rightarrow> 'b::{comm_monoid_add, t2_space}\\<close>\n  assumes \\<open>has_sum f A x\\<close>\n  shows \\<open>infsum f A = x\\<close>\n  by (metis assms finite_subsets_at_top_neq_bot infsum_def summable_on_def has_sum_def tendsto_Lim)\n\nlemma infsum_eqI:\n  fixes f g :: \\<open>'a \\<Rightarrow> 'b::{comm_monoid_add, t2_space}\\<close>\n  assumes \\<open>x = y\\<close>\n  assumes \\<open>has_sum f A x\\<close>\n  assumes \\<open>has_sum g B y\\<close>\n  shows \\<open>infsum f A = infsum g B\\<close>\n  by (metis assms(1) assms(2) assms(3) finite_subsets_at_top_neq_bot infsum_def summable_on_def has_sum_def tendsto_Lim)\n\nlemma infsum_eqI':\n  fixes f g :: \\<open>'a \\<Rightarrow> 'b::{comm_monoid_add, t2_space}\\<close>\n  assumes \\<open>\\<And>x. has_sum f A x \\<longleftrightarrow> has_sum g B x\\<close>\n  shows \\<open>infsum f A = infsum g B\\<close>\n  by (metis assms infsum_def infsum_eqI summable_on_def)\n\nlemma infsum_not_exists:\n  fixes f :: \\<open>'a \\<Rightarrow> 'b::{comm_monoid_add, t2_space}\\<close>\n  assumes \\<open>\\<not> f summable_on A\\<close>\n  shows \\<open>infsum f A = 0\\<close>\n  by (simp add: assms infsum_def)\n\nlemma summable_iff_has_sum_infsum: \"f summable_on A \\<longleftrightarrow> has_sum f A (infsum f A)\"\n  using infsumI summable_on_def by blast\n\nlemma has_sum_infsum[simp]:\n  assumes \\<open>f summable_on S\\<close>\n  shows \\<open>has_sum f S (infsum f S)\\<close>\n  using assms by (auto simp: summable_on_def infsum_def has_sum_def tendsto_Lim)\n\nlemma has_sum_cong_neutral:\n  fixes f g :: \\<open>'a \\<Rightarrow> 'b::{comm_monoid_add, topological_space}\\<close>\n  assumes \\<open>\\<And>x. x\\<in>T-S \\<Longrightarrow> g x = 0\\<close>\n  assumes \\<open>\\<And>x. x\\<in>S-T \\<Longrightarrow> f x = 0\\<close>\n  assumes \\<open>\\<And>x. x\\<in>S\\<inter>T \\<Longrightarrow> f x = g x\\<close>\n  shows \"has_sum f S x \\<longleftrightarrow> has_sum g T x\"\nproof -\n  have \\<open>eventually P (filtermap (sum f) (finite_subsets_at_top S))\n      = eventually P (filtermap (sum g) (finite_subsets_at_top T))\\<close> for P\n  proof \n    assume \\<open>eventually P (filtermap (sum f) (finite_subsets_at_top S))\\<close>\n    then obtain F0 where \\<open>finite F0\\<close> and \\<open>F0 \\<subseteq> S\\<close> and F0_P: \\<open>\\<And>F. finite F \\<Longrightarrow> F \\<subseteq> S \\<Longrightarrow> F \\<supseteq> F0 \\<Longrightarrow> P (sum f F)\\<close>\n      by (metis (no_types, lifting) eventually_filtermap eventually_finite_subsets_at_top)\n    define F0' where \\<open>F0' = F0 \\<inter> T\\<close>\n    have [simp]: \\<open>finite F0'\\<close> \\<open>F0' \\<subseteq> T\\<close>\n      by (simp_all add: F0'_def \\<open>finite F0\\<close>)\n    have \\<open>P (sum g F)\\<close> if \\<open>finite F\\<close> \\<open>F \\<subseteq> T\\<close> \\<open>F \\<supseteq> F0'\\<close> for F\n    proof -\n      have \\<open>P (sum f ((F\\<inter>S) \\<union> (F0\\<inter>S)))\\<close>\n        apply (rule F0_P)\n        using \\<open>F0 \\<subseteq> S\\<close>  \\<open>finite F0\\<close> that by auto\n      also have \\<open>sum f ((F\\<inter>S) \\<union> (F0\\<inter>S)) = sum g F\\<close>\n        apply (rule sum.mono_neutral_cong)\n        using that \\<open>finite F0\\<close> F0'_def assms by auto\n      finally show ?thesis .\n    qed\n    with \\<open>F0' \\<subseteq> T\\<close> \\<open>finite F0'\\<close> show \\<open>eventually P (filtermap (sum g) (finite_subsets_at_top T))\\<close>\n      by (metis (no_types, lifting) eventually_filtermap eventually_finite_subsets_at_top)\n  next\n    assume \\<open>eventually P (filtermap (sum g) (finite_subsets_at_top T))\\<close>\n    then obtain F0 where \\<open>finite F0\\<close> and \\<open>F0 \\<subseteq> T\\<close> and F0_P: \\<open>\\<And>F. finite F \\<Longrightarrow> F \\<subseteq> T \\<Longrightarrow> F \\<supseteq> F0 \\<Longrightarrow> P (sum g F)\\<close>\n      by (metis (no_types, lifting) eventually_filtermap eventually_finite_subsets_at_top)\n    define F0' where \\<open>F0' = F0 \\<inter> S\\<close>\n    have [simp]: \\<open>finite F0'\\<close> \\<open>F0' \\<subseteq> S\\<close>\n      by (simp_all add: F0'_def \\<open>finite F0\\<close>)\n    have \\<open>P (sum f F)\\<close> if \\<open>finite F\\<close> \\<open>F \\<subseteq> S\\<close> \\<open>F \\<supseteq> F0'\\<close> for F\n    proof -\n      have \\<open>P (sum g ((F\\<inter>T) \\<union> (F0\\<inter>T)))\\<close>\n        apply (rule F0_P)\n        using \\<open>F0 \\<subseteq> T\\<close>  \\<open>finite F0\\<close> that by auto\n      also have \\<open>sum g ((F\\<inter>T) \\<union> (F0\\<inter>T)) = sum f F\\<close>\n        apply (rule sum.mono_neutral_cong)\n        using that \\<open>finite F0\\<close> F0'_def assms by auto\n      finally show ?thesis .\n    qed\n    with \\<open>F0' \\<subseteq> S\\<close> \\<open>finite F0'\\<close> show \\<open>eventually P (filtermap (sum f) (finite_subsets_at_top S))\\<close>\n      by (metis (no_types, lifting) eventually_filtermap eventually_finite_subsets_at_top)\n  qed\n\n  then have tendsto_x: \"(sum f \\<longlongrightarrow> x) (finite_subsets_at_top S) \\<longleftrightarrow> (sum g \\<longlongrightarrow> x) (finite_subsets_at_top T)\" for x\n    by (simp add: le_filter_def filterlim_def)\n\n  then show ?thesis\n    by (simp add: has_sum_def)\nqed\n\nlemma summable_on_cong_neutral: \n  fixes f g :: \\<open>'a \\<Rightarrow> 'b::{comm_monoid_add, topological_space}\\<close>\n  assumes \\<open>\\<And>x. x\\<in>T-S \\<Longrightarrow> g x = 0\\<close>\n  assumes \\<open>\\<And>x. x\\<in>S-T \\<Longrightarrow> f x = 0\\<close>\n  assumes \\<open>\\<And>x. x\\<in>S\\<inter>T \\<Longrightarrow> f x = g x\\<close>\n  shows \"f summable_on S \\<longleftrightarrow> g summable_on T\"\n  using has_sum_cong_neutral[of T S g f, OF assms]\n  by (simp add: summable_on_def)\n\nlemma infsum_cong_neutral: \n  fixes f g :: \\<open>'a \\<Rightarrow> 'b::{comm_monoid_add, t2_space}\\<close>\n  assumes \\<open>\\<And>x. x\\<in>T-S \\<Longrightarrow> g x = 0\\<close>\n  assumes \\<open>\\<And>x. x\\<in>S-T \\<Longrightarrow> f x = 0\\<close>\n  assumes \\<open>\\<And>x. x\\<in>S\\<inter>T \\<Longrightarrow> f x = g x\\<close>\n  shows \\<open>infsum f S = infsum g T\\<close>\n  apply (rule infsum_eqI')\n  using assms by (rule has_sum_cong_neutral)\n\nlemma has_sum_cong: \n  assumes \"\\<And>x. x\\<in>A \\<Longrightarrow> f x = g x\"\n  shows \"has_sum f A x \\<longleftrightarrow> has_sum g A x\"\n  using assms by (intro has_sum_cong_neutral) auto\n\nlemma summable_on_cong:\n  assumes \"\\<And>x. x\\<in>A \\<Longrightarrow> f x = g x\"\n  shows \"f summable_on A \\<longleftrightarrow> g summable_on A\"\n  by (metis assms summable_on_def has_sum_cong)\n\nlemma infsum_cong:\n  assumes \"\\<And>x. x\\<in>A \\<Longrightarrow> f x = g x\"\n  shows \"infsum f A = infsum g A\"\n  using assms infsum_eqI' has_sum_cong by blast\n\nlemma summable_on_cofin_subset:\n  fixes f :: \"'a \\<Rightarrow> 'b::topological_ab_group_add\"\n  assumes \"f summable_on A\" and [simp]: \"finite F\"\n  shows \"f summable_on (A - F)\"\nproof -\n  from assms(1) obtain x where lim_f: \"(sum f \\<longlongrightarrow> x) (finite_subsets_at_top A)\"\n    unfolding summable_on_def has_sum_def by auto\n  define F' where \"F' = F\\<inter>A\"\n  with assms have \"finite F'\" and \"A-F = A-F'\"\n    by auto\n  have \"filtermap ((\\<union>)F') (finite_subsets_at_top (A-F))\n      \\<le> finite_subsets_at_top A\"\n  proof (rule filter_leI)\n    fix P assume \"eventually P (finite_subsets_at_top A)\"\n    then obtain X where [simp]: \"finite X\" and XA: \"X \\<subseteq> A\" \n      and P: \"\\<forall>Y. finite Y \\<and> X \\<subseteq> Y \\<and> Y \\<subseteq> A \\<longrightarrow> P Y\"\n      unfolding eventually_finite_subsets_at_top by auto\n    define X' where \"X' = X-F\"\n    hence [simp]: \"finite X'\" and [simp]: \"X' \\<subseteq> A-F\"\n      using XA by auto\n    hence \"finite Y \\<and> X' \\<subseteq> Y \\<and> Y \\<subseteq> A - F \\<longrightarrow> P (F' \\<union> Y)\" for Y\n      using P XA unfolding X'_def using F'_def \\<open>finite F'\\<close> by blast\n    thus \"eventually P (filtermap ((\\<union>) F') (finite_subsets_at_top (A - F)))\"\n      unfolding eventually_filtermap eventually_finite_subsets_at_top\n      by (rule_tac x=X' in exI, simp)\n  qed\n  with lim_f have \"(sum f \\<longlongrightarrow> x) (filtermap ((\\<union>)F') (finite_subsets_at_top (A-F)))\"\n    using tendsto_mono by blast\n  have \"((\\<lambda>G. sum f (F' \\<union> G)) \\<longlongrightarrow> x) (finite_subsets_at_top (A - F))\"\n    if \"((sum f \\<circ> (\\<union>) F') \\<longlongrightarrow> x) (finite_subsets_at_top (A - F))\"\n    using that unfolding o_def by auto\n  hence \"((\\<lambda>G. sum f (F' \\<union> G)) \\<longlongrightarrow> x) (finite_subsets_at_top (A-F))\"\n    using tendsto_compose_filtermap [symmetric]\n    by (simp add: \\<open>(sum f \\<longlongrightarrow> x) (filtermap ((\\<union>) F') (finite_subsets_at_top (A - F)))\\<close> \n        tendsto_compose_filtermap)\n  have \"\\<forall>Y. finite Y \\<and> Y \\<subseteq> A - F \\<longrightarrow> sum f (F' \\<union> Y) = sum f F' + sum f Y\"\n    by (metis Diff_disjoint Int_Diff \\<open>A - F = A - F'\\<close> \\<open>finite F'\\<close> inf.orderE sum.union_disjoint)\n  hence \"\\<forall>\\<^sub>F x in finite_subsets_at_top (A - F). sum f (F' \\<union> x) = sum f F' + sum f x\"\n    unfolding eventually_finite_subsets_at_top\n    using exI [where x = \"{}\"]\n    by (simp add: \\<open>\\<And>P. P {} \\<Longrightarrow> \\<exists>x. P x\\<close>) \n  hence \"((\\<lambda>G. sum f F' + sum f G) \\<longlongrightarrow> x) (finite_subsets_at_top (A-F))\"\n    using tendsto_cong [THEN iffD1 , rotated]\n      \\<open>((\\<lambda>G. sum f (F' \\<union> G)) \\<longlongrightarrow> x) (finite_subsets_at_top (A - F))\\<close> by fastforce\n  hence \"((\\<lambda>G. sum f F' + sum f G) \\<longlongrightarrow> sum f F' + (x-sum f F')) (finite_subsets_at_top (A-F))\"\n    by simp\n  hence \"(sum f \\<longlongrightarrow> x - sum f F') (finite_subsets_at_top (A-F))\"\n    using tendsto_add_const_iff by blast    \n  thus \"f summable_on (A - F)\"\n    unfolding summable_on_def has_sum_def by auto\nqed\n\nlemma\n  fixes f :: \"'a \\<Rightarrow> 'b::{topological_ab_group_add}\"\n  assumes \\<open>has_sum f B b\\<close> and \\<open>has_sum f A a\\<close> and AB: \"A \\<subseteq> B\"\n  shows has_sum_Diff: \"has_sum f (B - A) (b - a)\"\nproof -\n  have finite_subsets1:\n    \"finite_subsets_at_top (B - A) \\<le> filtermap (\\<lambda>F. F - A) (finite_subsets_at_top B)\"\n  proof (rule filter_leI)\n    fix P assume \"eventually P (filtermap (\\<lambda>F. F - A) (finite_subsets_at_top B))\"\n    then obtain X where \"finite X\" and \"X \\<subseteq> B\" \n      and P: \"finite Y \\<and> X \\<subseteq> Y \\<and> Y \\<subseteq> B \\<longrightarrow> P (Y - A)\" for Y\n      unfolding eventually_filtermap eventually_finite_subsets_at_top by auto\n\n    hence \"finite (X-A)\" and \"X-A \\<subseteq> B - A\"\n      by auto\n    moreover have \"finite Y \\<and> X-A \\<subseteq> Y \\<and> Y \\<subseteq> B - A \\<longrightarrow> P Y\" for Y\n      using P[where Y=\"Y\\<union>X\"] \\<open>finite X\\<close> \\<open>X \\<subseteq> B\\<close>\n      by (metis Diff_subset Int_Diff Un_Diff finite_Un inf.orderE le_sup_iff sup.orderE sup_ge2)\n    ultimately show \"eventually P (finite_subsets_at_top (B - A))\"\n      unfolding eventually_finite_subsets_at_top by meson\n  qed\n  have finite_subsets2: \n    \"filtermap (\\<lambda>F. F \\<inter> A) (finite_subsets_at_top B) \\<le> finite_subsets_at_top A\"\n    apply (rule filter_leI)\n      using assms unfolding eventually_filtermap eventually_finite_subsets_at_top\n      by (metis Int_subset_iff finite_Int inf_le2 subset_trans)\n\n  from assms(1) have limB: \"(sum f \\<longlongrightarrow> b) (finite_subsets_at_top B)\"\n    using has_sum_def by auto\n  from assms(2) have limA: \"(sum f \\<longlongrightarrow> a) (finite_subsets_at_top A)\"\n    using has_sum_def by blast\n  have \"((\\<lambda>F. sum f (F\\<inter>A)) \\<longlongrightarrow> a) (finite_subsets_at_top B)\"\n  proof (subst asm_rl [of \"(\\<lambda>F. sum f (F\\<inter>A)) = sum f o (\\<lambda>F. F\\<inter>A)\"])\n    show \"(\\<lambda>F. sum f (F \\<inter> A)) = sum f \\<circ> (\\<lambda>F. F \\<inter> A)\"\n      unfolding o_def by auto\n    show \"((sum f \\<circ> (\\<lambda>F. F \\<inter> A)) \\<longlongrightarrow> a) (finite_subsets_at_top B)\"\n      unfolding o_def \n      using tendsto_compose_filtermap finite_subsets2 limA tendsto_mono\n        \\<open>(\\<lambda>F. sum f (F \\<inter> A)) = sum f \\<circ> (\\<lambda>F. F \\<inter> A)\\<close> by fastforce\n  qed\n\n  with limB have \"((\\<lambda>F. sum f F - sum f (F\\<inter>A)) \\<longlongrightarrow> b - a) (finite_subsets_at_top B)\"\n    using tendsto_diff by blast\n  have \"sum f X - sum f (X \\<inter> A) = sum f (X - A)\" if \"finite X\" and \"X \\<subseteq> B\" for X :: \"'a set\"\n    using that by (metis add_diff_cancel_left' sum.Int_Diff)\n  hence \"\\<forall>\\<^sub>F x in finite_subsets_at_top B. sum f x - sum f (x \\<inter> A) = sum f (x - A)\"\n    by (rule eventually_finite_subsets_at_top_weakI)  \n  hence \"((\\<lambda>F. sum f (F-A)) \\<longlongrightarrow> b - a) (finite_subsets_at_top B)\"\n    using tendsto_cong [THEN iffD1 , rotated]\n      \\<open>((\\<lambda>F. sum f F - sum f (F \\<inter> A)) \\<longlongrightarrow> b - a) (finite_subsets_at_top B)\\<close> by fastforce\n  hence \"(sum f \\<longlongrightarrow> b - a) (filtermap (\\<lambda>F. F-A) (finite_subsets_at_top B))\"\n    by (subst tendsto_compose_filtermap[symmetric], simp add: o_def)\n  hence limBA: \"(sum f \\<longlongrightarrow> b - a) (finite_subsets_at_top (B-A))\"\n    apply (rule tendsto_mono[rotated])\n    by (rule finite_subsets1)\n  thus ?thesis\n    by (simp add: has_sum_def)\nqed\n\n\nlemma\n  fixes f :: \"'a \\<Rightarrow> 'b::{topological_ab_group_add}\"\n  assumes \"f summable_on B\" and \"f summable_on A\" and \"A \\<subseteq> B\"\n  shows summable_on_Diff: \"f summable_on (B-A)\"\n  by (meson assms summable_on_def has_sum_Diff)\n\nlemma\n  fixes f :: \"'a \\<Rightarrow> 'b::{topological_ab_group_add,t2_space}\"\n  assumes \"f summable_on B\" and \"f summable_on A\" and AB: \"A \\<subseteq> B\"\n  shows infsum_Diff: \"infsum f (B - A) = infsum f B - infsum f A\"\n  by (metis AB assms has_sum_Diff infsumI summable_on_def)\n\nlemma has_sum_mono_neutral:\n  fixes f :: \"'a\\<Rightarrow>'b::{ordered_comm_monoid_add,linorder_topology}\"\n  (* Does this really require a linorder topology? (Instead of order topology.) *)\n  assumes \\<open>has_sum f A a\\<close> and \"has_sum g B b\"\n  assumes \\<open>\\<And>x. x \\<in> A\\<inter>B \\<Longrightarrow> f x \\<le> g x\\<close>\n  assumes \\<open>\\<And>x. x \\<in> A-B \\<Longrightarrow> f x \\<le> 0\\<close>\n  assumes \\<open>\\<And>x. x \\<in> B-A \\<Longrightarrow> g x \\<ge> 0\\<close>\n  shows \"a \\<le> b\"\nproof -\n  define f' g' where \\<open>f' x = (if x \\<in> A then f x else 0)\\<close> and \\<open>g' x = (if x \\<in> B then g x else 0)\\<close> for x\n  have [simp]: \\<open>f summable_on A\\<close> \\<open>g summable_on B\\<close>\n    using assms(1,2) summable_on_def by auto\n  have \\<open>has_sum f' (A\\<union>B) a\\<close>\n    apply (subst has_sum_cong_neutral[where g=f and T=A])\n    by (auto simp: f'_def assms(1))\n  then have f'_lim: \\<open>(sum f' \\<longlongrightarrow> a) (finite_subsets_at_top (A\\<union>B))\\<close>\n    by (meson has_sum_def)\n  have \\<open>has_sum g' (A\\<union>B) b\\<close>\n    apply (subst has_sum_cong_neutral[where g=g and T=B])\n    by (auto simp: g'_def assms(2))\n  then have g'_lim: \\<open>(sum g' \\<longlongrightarrow> b) (finite_subsets_at_top (A\\<union>B))\\<close>\n    using has_sum_def by blast\n\n  have *: \\<open>\\<forall>\\<^sub>F x in finite_subsets_at_top (A \\<union> B). sum f' x \\<le> sum g' x\\<close>\n    apply (rule eventually_finite_subsets_at_top_weakI)\n    apply (rule sum_mono)\n    using assms by (auto simp: f'_def g'_def)\n  show ?thesis\n    apply (rule tendsto_le)\n    using * g'_lim f'_lim by auto\nqed\n\nlemma infsum_mono_neutral:\n  fixes f :: \"'a\\<Rightarrow>'b::{ordered_comm_monoid_add,linorder_topology}\"\n  assumes \"f summable_on A\" and \"g summable_on B\"\n  assumes \\<open>\\<And>x. x \\<in> A\\<inter>B \\<Longrightarrow> f x \\<le> g x\\<close>\n  assumes \\<open>\\<And>x. x \\<in> A-B \\<Longrightarrow> f x \\<le> 0\\<close>\n  assumes \\<open>\\<And>x. x \\<in> B-A \\<Longrightarrow> g x \\<ge> 0\\<close>\n  shows \"infsum f A \\<le> infsum g B\"\n  by (rule has_sum_mono_neutral[of f A _ g B _]) (use assms in \\<open>auto intro: has_sum_infsum\\<close>)\n\nlemma has_sum_mono:\n  fixes f :: \"'a\\<Rightarrow>'b::{ordered_comm_monoid_add,linorder_topology}\"\n  assumes \"has_sum f A x\" and \"has_sum g A y\"\n  assumes \\<open>\\<And>x. x \\<in> A \\<Longrightarrow> f x \\<le> g x\\<close>\n  shows \"x \\<le> y\"\n  apply (rule has_sum_mono_neutral)\n  using assms by auto\n\nlemma infsum_mono:\n  fixes f :: \"'a\\<Rightarrow>'b::{ordered_comm_monoid_add,linorder_topology}\"\n  assumes \"f summable_on A\" and \"g summable_on A\"\n  assumes \\<open>\\<And>x. x \\<in> A \\<Longrightarrow> f x \\<le> g x\\<close>\n  shows \"infsum f A \\<le> infsum g A\"\n  apply (rule infsum_mono_neutral)\n  using assms by auto\n\nlemma has_sum_finite[simp]:\n  assumes \"finite F\"\n  shows \"has_sum f F (sum f F)\"\n  using assms\n  by (auto intro: tendsto_Lim simp: finite_subsets_at_top_finite infsum_def has_sum_def principal_eq_bot_iff)\n\nlemma summable_on_finite[simp]:\n  fixes f :: \\<open>'a \\<Rightarrow> 'b::{comm_monoid_add,topological_space}\\<close>\n  assumes \"finite F\"\n  shows \"f summable_on F\"\n  using assms summable_on_def has_sum_finite by blast\n\nlemma infsum_finite[simp]:\n  assumes \"finite F\"\n  shows \"infsum f F = sum f F\"\n  using assms by (auto intro: tendsto_Lim simp: finite_subsets_at_top_finite infsum_def principal_eq_bot_iff)\n\nlemma has_sum_finite_approximation:\n  fixes f :: \"'a \\<Rightarrow> 'b::{comm_monoid_add,metric_space}\"\n  assumes \"has_sum f A x\" and \"\\<epsilon> > 0\"\n  shows \"\\<exists>F. finite F \\<and> F \\<subseteq> A \\<and> dist (sum f F) x \\<le> \\<epsilon>\"\nproof -\n  have \"(sum f \\<longlongrightarrow> x) (finite_subsets_at_top A)\"\n    by (meson assms(1) has_sum_def)\n  hence *: \"\\<forall>\\<^sub>F F in (finite_subsets_at_top A). dist (sum f F) x < \\<epsilon>\"\n    using assms(2) by (rule tendstoD)\n  thus ?thesis\n    unfolding eventually_finite_subsets_at_top by fastforce\nqed\n\nlemma infsum_finite_approximation:\n  fixes f :: \"'a \\<Rightarrow> 'b::{comm_monoid_add,metric_space}\"\n  assumes \"f summable_on A\" and \"\\<epsilon> > 0\"\n  shows \"\\<exists>F. finite F \\<and> F \\<subseteq> A \\<and> dist (sum f F) (infsum f A) \\<le> \\<epsilon>\"\nproof -\n  from assms have \"has_sum f A (infsum f A)\"\n    by (simp add: summable_iff_has_sum_infsum)\n  from this and \\<open>\\<epsilon> > 0\\<close> show ?thesis\n    by (rule has_sum_finite_approximation)\nqed\n\nlemma abs_summable_summable:\n  fixes f :: \\<open>'a \\<Rightarrow> 'b :: banach\\<close>\n  assumes \\<open>f abs_summable_on A\\<close>\n  shows \\<open>f summable_on A\\<close>\nproof -\n  from assms obtain L where lim: \\<open>(sum (\\<lambda>x. norm (f x)) \\<longlongrightarrow> L) (finite_subsets_at_top A)\\<close>\n    unfolding has_sum_def summable_on_def by blast\n  then have *: \\<open>cauchy_filter (filtermap (sum (\\<lambda>x. norm (f x))) (finite_subsets_at_top A))\\<close>\n    by (auto intro!: nhds_imp_cauchy_filter simp: filterlim_def)\n  have \\<open>\\<exists>P. eventually P (finite_subsets_at_top A) \\<and>\n              (\\<forall>F F'. P F \\<and> P F' \\<longrightarrow> dist (sum f F) (sum f F') < e)\\<close> if \\<open>e>0\\<close> for e\n  proof -\n    define d P where \\<open>d = e/4\\<close> and \\<open>P F \\<longleftrightarrow> finite F \\<and> F \\<subseteq> A \\<and> dist (sum (\\<lambda>x. norm (f x)) F) L < d\\<close> for F\n    then have \\<open>d > 0\\<close>\n      by (simp add: d_def that)\n    have ev_P: \\<open>eventually P (finite_subsets_at_top A)\\<close>\n      using lim\n      by (auto simp add: P_def[abs_def] \\<open>0 < d\\<close> eventually_conj_iff eventually_finite_subsets_at_top_weakI tendsto_iff)\n    \n    moreover have \\<open>dist (sum f F1) (sum f F2) < e\\<close> if \\<open>P F1\\<close> and \\<open>P F2\\<close> for F1 F2\n    proof -\n      from ev_P\n      obtain F' where \\<open>finite F'\\<close> and \\<open>F' \\<subseteq> A\\<close> and P_sup_F': \\<open>finite F \\<and> F \\<supseteq> F' \\<and> F \\<subseteq> A \\<Longrightarrow> P F\\<close> for F\n        by atomize_elim (simp add: eventually_finite_subsets_at_top)\n      define F where \\<open>F = F' \\<union> F1 \\<union> F2\\<close>\n      have \\<open>finite F\\<close> and \\<open>F \\<subseteq> A\\<close>\n        using F_def P_def[abs_def] that \\<open>finite F'\\<close> \\<open>F' \\<subseteq> A\\<close> by auto\n      have dist_F: \\<open>dist (sum (\\<lambda>x. norm (f x)) F) L < d\\<close>\n        by (metis F_def \\<open>F \\<subseteq> A\\<close> P_def P_sup_F' \\<open>finite F\\<close> le_supE order_refl)\n\n      have dist_F_subset: \\<open>dist (sum f F) (sum f F') < 2*d\\<close> if F': \\<open>F' \\<subseteq> F\\<close> \\<open>P F'\\<close> for F'\n      proof -\n        have \\<open>dist (sum f F) (sum f F') = norm (sum f (F-F'))\\<close>\n          unfolding dist_norm using \\<open>finite F\\<close> F' by (subst sum_diff) auto\n        also have \\<open>\\<dots> \\<le> norm (\\<Sum>x\\<in>F-F'. norm (f x))\\<close>\n          by (rule order.trans[OF sum_norm_le[OF order.refl]]) auto\n        also have \\<open>\\<dots> = dist (\\<Sum>x\\<in>F. norm (f x)) (\\<Sum>x\\<in>F'. norm (f x))\\<close>\n          unfolding dist_norm using \\<open>finite F\\<close> F' by (subst sum_diff) auto\n        also have \\<open>\\<dots> < 2 * d\\<close>\n          using dist_F F' unfolding P_def dist_norm real_norm_def by linarith\n        finally show \\<open>dist (sum f F) (sum f F') < 2*d\\<close> .\n      qed\n\n      have \\<open>dist (sum f F1) (sum f F2) \\<le> dist (sum f F) (sum f F1) + dist (sum f F) (sum f F2)\\<close>\n        by (rule dist_triangle3)\n      also have \\<open>\\<dots> < 2 * d + 2 * d\\<close>\n        by (intro add_strict_mono dist_F_subset that) (auto simp: F_def)\n      also have \\<open>\\<dots> \\<le> e\\<close>\n        by (auto simp: d_def)\n      finally show \\<open>dist (sum f F1) (sum f F2) < e\\<close> .\n    qed\n    then show ?thesis\n      using ev_P by blast\n  qed\n  then have \\<open>cauchy_filter (filtermap (sum f) (finite_subsets_at_top A))\\<close>\n    by (simp add: cauchy_filter_metric_filtermap)\n  then obtain L' where \\<open>(sum f \\<longlongrightarrow> L') (finite_subsets_at_top A)\\<close>\n    apply atomize_elim unfolding filterlim_def\n    apply (rule complete_uniform[where S=UNIV, simplified, THEN iffD1, rule_format])\n      apply (auto simp add: filtermap_bot_iff)\n    by (meson Cauchy_convergent UNIV_I complete_def convergent_def)\n  then show ?thesis\n    using summable_on_def has_sum_def by blast\nqed\n\ntext \\<open>The converse of @{thm [source] abs_summable_summable} does not hold:\n  Consider the Hilbert space of square-summable sequences.\n  Let $e_i$ denote the sequence with 1 in the $i$th position and 0 elsewhere.\n  Let $f(i) := e_i/i$ for $i\\geq1$. We have \\<^term>\\<open>\\<not> f abs_summable_on UNIV\\<close> because $\\lVert f(i)\\rVert=1/i$\n  and thus the sum over $\\lVert f(i)\\rVert$ diverges. On the other hand, we have \\<^term>\\<open>f summable_on UNIV\\<close>;\n  the limit is the sequence with $1/i$ in the $i$th position.\n\n  (We have not formalized this separating example here because to the best of our knowledge,\n  this Hilbert space has not been formalized in Isabelle/HOL yet.)\\<close>\n\nlemma norm_has_sum_bound:\n  fixes f :: \"'b \\<Rightarrow> 'a::real_normed_vector\"\n    and A :: \"'b set\"\n  assumes \"has_sum (\\<lambda>x. norm (f x)) A n\"\n  assumes \"has_sum f A a\"\n  shows \"norm a \\<le> n\"\nproof -\n  have \"norm a \\<le> n + \\<epsilon>\" if \"\\<epsilon>>0\" for \\<epsilon>\n  proof-\n    have \"\\<exists>F. norm (a - sum f F) \\<le> \\<epsilon> \\<and> finite F \\<and> F \\<subseteq> A\"\n      using has_sum_finite_approximation[where A=A and f=f and \\<epsilon>=\"\\<epsilon>\"] assms \\<open>0 < \\<epsilon>\\<close>\n      by (metis dist_commute dist_norm)\n    then obtain F where \"norm (a - sum f F) \\<le> \\<epsilon>\"\n      and \"finite F\" and \"F \\<subseteq> A\"\n      by (simp add: atomize_elim)\n    hence \"norm a \\<le> norm (sum f F) + \\<epsilon>\"\n      by (metis add.commute diff_add_cancel dual_order.refl norm_triangle_mono)\n    also have \"\\<dots> \\<le> sum (\\<lambda>x. norm (f x)) F + \\<epsilon>\"\n      using norm_sum by auto\n    also have \"\\<dots> \\<le> n + \\<epsilon>\"\n      apply (rule add_right_mono)\n      apply (rule has_sum_mono_neutral[where A=F and B=A and f=\\<open>\\<lambda>x. norm (f x)\\<close> and g=\\<open>\\<lambda>x. norm (f x)\\<close>])\n      using \\<open>finite F\\<close> \\<open>F \\<subseteq> A\\<close> assms by auto\n    finally show ?thesis \n      by assumption\n  qed\n  thus ?thesis\n    using linordered_field_class.field_le_epsilon by blast\nqed\n\nlemma norm_infsum_bound:\n  fixes f :: \"'b \\<Rightarrow> 'a::real_normed_vector\"\n    and A :: \"'b set\"\n  assumes \"f abs_summable_on A\"\n  shows \"norm (infsum f A) \\<le> infsum (\\<lambda>x. norm (f x)) A\"\nproof (cases \"f summable_on A\")\n  case True\n  show ?thesis\n    apply (rule norm_has_sum_bound[where A=A and f=f and a=\\<open>infsum f A\\<close> and n=\\<open>infsum (\\<lambda>x. norm (f x)) A\\<close>])\n    using assms True\n    by (metis finite_subsets_at_top_neq_bot infsum_def summable_on_def has_sum_def tendsto_Lim)+\nnext\n  case False\n  obtain t where t_def: \"(sum (\\<lambda>x. norm (f x)) \\<longlongrightarrow> t) (finite_subsets_at_top A)\"\n    using assms unfolding summable_on_def has_sum_def by blast\n  have sumpos: \"sum (\\<lambda>x. norm (f x)) X \\<ge> 0\"\n    for X\n    by (simp add: sum_nonneg)\n  have tgeq0:\"t \\<ge> 0\"\n  proof(rule ccontr)\n    define S::\"real set\" where \"S = {s. s < 0}\"\n    assume \"\\<not> 0 \\<le> t\"\n    hence \"t < 0\" by simp\n    hence \"t \\<in> S\"\n      unfolding S_def by blast\n    moreover have \"open S\"\n    proof-\n      have \"closed {s::real. s \\<ge> 0}\"\n        using Elementary_Topology.closed_sequential_limits[where S = \"{s::real. s \\<ge> 0}\"]\n        by (metis Lim_bounded2 mem_Collect_eq)\n      moreover have \"{s::real. s \\<ge> 0} = UNIV - S\"\n        unfolding S_def by auto\n      ultimately have \"closed (UNIV - S)\"\n        by simp\n      thus ?thesis\n        by (simp add: Compl_eq_Diff_UNIV open_closed) \n    qed\n    ultimately have \"\\<forall>\\<^sub>F X in finite_subsets_at_top A. (\\<Sum>x\\<in>X. norm (f x)) \\<in> S\"\n      using t_def unfolding tendsto_def by blast\n    hence \"\\<exists>X. (\\<Sum>x\\<in>X. norm (f x)) \\<in> S\"\n      by (metis (no_types, lifting) eventually_mono filterlim_iff finite_subsets_at_top_neq_bot tendsto_Lim)\n    then obtain X where \"(\\<Sum>x\\<in>X. norm (f x)) \\<in> S\"\n      by blast\n    hence \"(\\<Sum>x\\<in>X. norm (f x)) < 0\"\n      unfolding S_def by auto      \n    thus False by (simp add: leD sumpos)\n  qed\n  have \"\\<exists>!h. (sum (\\<lambda>x. norm (f x)) \\<longlongrightarrow> h) (finite_subsets_at_top A)\"\n    using t_def finite_subsets_at_top_neq_bot tendsto_unique by blast\n  hence \"t = (Topological_Spaces.Lim (finite_subsets_at_top A) (sum (\\<lambda>x. norm (f x))))\"\n    using t_def unfolding Topological_Spaces.Lim_def\n    by (metis the_equality)     \n  hence \"Lim (finite_subsets_at_top A) (sum (\\<lambda>x. norm (f x))) \\<ge> 0\"\n    using tgeq0 by blast\n  thus ?thesis unfolding infsum_def \n    using False by auto\nqed\n\nlemma infsum_tendsto:\n  assumes \\<open>f summable_on S\\<close>\n  shows \\<open>((\\<lambda>F. sum f F) \\<longlongrightarrow> infsum f S) (finite_subsets_at_top S)\\<close>\n  using assms by (simp flip: has_sum_def)\n\n\nlemma has_sum_0: \n  assumes \\<open>\\<And>x. x\\<in>M \\<Longrightarrow> f x = 0\\<close>\n  shows \\<open>has_sum f M 0\\<close>\n  unfolding has_sum_def\n  apply (subst tendsto_cong[where g=\\<open>\\<lambda>_. 0\\<close>])\n   apply (rule eventually_finite_subsets_at_top_weakI)\n  using assms by (auto simp add: subset_iff)\n\nlemma summable_on_0:\n  assumes \\<open>\\<And>x. x\\<in>M \\<Longrightarrow> f x = 0\\<close>\n  shows \\<open>f summable_on M\\<close>\n  using assms summable_on_def has_sum_0 by blast\n\nlemma infsum_0:\n  assumes \\<open>\\<And>x. x\\<in>M \\<Longrightarrow> f x = 0\\<close>\n  shows \\<open>infsum f M = 0\\<close>\n  by (metis assms finite_subsets_at_top_neq_bot infsum_def has_sum_0 has_sum_def tendsto_Lim)\n\ntext \\<open>Variants of @{thm [source] infsum_0} etc. suitable as simp-rules\\<close>\nlemma infsum_0_simp[simp]: \\<open>infsum (\\<lambda>_. 0) M = 0\\<close>\n  by (simp_all add: infsum_0)\nlemma summable_on_0_simp[simp]: \\<open>(\\<lambda>_. 0) summable_on M\\<close>\n  by (simp_all add: summable_on_0)\nlemma has_sum_0_simp[simp]: \\<open>has_sum (\\<lambda>_. 0) M 0\\<close>\n  by (simp_all add: has_sum_0)\n\n\nlemma has_sum_add:\n  fixes f g :: \"'a \\<Rightarrow> 'b::{topological_comm_monoid_add}\"\n  assumes \\<open>has_sum f A a\\<close>\n  assumes \\<open>has_sum g A b\\<close>\n  shows \\<open>has_sum (\\<lambda>x. f x + g x) A (a + b)\\<close>\nproof -\n  from assms have lim_f: \\<open>(sum f \\<longlongrightarrow> a)  (finite_subsets_at_top A)\\<close>\n    and lim_g: \\<open>(sum g \\<longlongrightarrow> b)  (finite_subsets_at_top A)\\<close>\n    by (simp_all add: has_sum_def)\n  then have lim: \\<open>(sum (\\<lambda>x. f x + g x) \\<longlongrightarrow> a + b) (finite_subsets_at_top A)\\<close>\n    unfolding sum.distrib by (rule tendsto_add)\n  then show ?thesis\n    by (simp_all add: has_sum_def)\nqed\n\nlemma summable_on_add:\n  fixes f g :: \"'a \\<Rightarrow> 'b::{topological_comm_monoid_add}\"\n  assumes \\<open>f summable_on A\\<close>\n  assumes \\<open>g summable_on A\\<close>\n  shows \\<open>(\\<lambda>x. f x + g x) summable_on A\\<close>\n  by (metis (full_types) assms(1) assms(2) summable_on_def has_sum_add)\n\nlemma infsum_add:\n  fixes f g :: \"'a \\<Rightarrow> 'b::{topological_comm_monoid_add, t2_space}\"\n  assumes \\<open>f summable_on A\\<close>\n  assumes \\<open>g summable_on A\\<close>\n  shows \\<open>infsum (\\<lambda>x. f x + g x) A = infsum f A + infsum g A\\<close>\nproof -\n  have \\<open>has_sum (\\<lambda>x. f x + g x) A (infsum f A + infsum g A)\\<close>\n    by (simp add: assms(1) assms(2) has_sum_add)\n  then show ?thesis\n    using infsumI by blast\nqed\n\n\nlemma has_sum_Un_disjoint:\n  fixes f :: \"'a \\<Rightarrow> 'b::topological_comm_monoid_add\"\n  assumes \"has_sum f A a\"\n  assumes \"has_sum f B b\"\n  assumes disj: \"A \\<inter> B = {}\"\n  shows \\<open>has_sum f (A \\<union> B) (a + b)\\<close>\nproof -\n  define fA fB where \\<open>fA x = (if x \\<in> A then f x else 0)\\<close>\n    and \\<open>fB x = (if x \\<notin> A then f x else 0)\\<close> for x\n  have fA: \\<open>has_sum fA (A \\<union> B) a\\<close>\n    apply (subst has_sum_cong_neutral[where T=A and g=f])\n    using assms by (auto simp: fA_def)\n  have fB: \\<open>has_sum fB (A \\<union> B) b\\<close>\n    apply (subst has_sum_cong_neutral[where T=B and g=f])\n    using assms by (auto simp: fB_def)\n  have fAB: \\<open>f x = fA x + fB x\\<close> for x\n    unfolding fA_def fB_def by simp\n  show ?thesis\n    unfolding fAB\n    using fA fB by (rule has_sum_add)\nqed\n\nlemma summable_on_Un_disjoint:\n  fixes f :: \"'a \\<Rightarrow> 'b::topological_comm_monoid_add\"\n  assumes \"f summable_on A\"\n  assumes \"f summable_on B\"\n  assumes disj: \"A \\<inter> B = {}\"\n  shows \\<open>f summable_on (A \\<union> B)\\<close>\n  by (meson assms(1) assms(2) disj summable_on_def has_sum_Un_disjoint)\n\nlemma infsum_Un_disjoint:\n  fixes f :: \"'a \\<Rightarrow> 'b::{topological_comm_monoid_add, t2_space}\"\n  assumes \"f summable_on A\"\n  assumes \"f summable_on B\"\n  assumes disj: \"A \\<inter> B = {}\"\n  shows \\<open>infsum f (A \\<union> B) = infsum f A + infsum f B\\<close>\n  by (intro infsumI has_sum_Un_disjoint has_sum_infsum assms)  \n\nlemma norm_summable_imp_has_sum:\n  fixes f :: \"nat \\<Rightarrow> 'a :: banach\"\n  assumes \"summable (\\<lambda>n. norm (f n))\" and \"f sums S\"\n  shows   \"has_sum f (UNIV :: nat set) S\"\n  unfolding has_sum_def tendsto_iff eventually_finite_subsets_at_top\nproof (safe, goal_cases)\n  case (1 \\<epsilon>)\n  from assms(1) obtain S' where S': \"(\\<lambda>n. norm (f n)) sums S'\"\n    by (auto simp: summable_def)\n  with 1 obtain N where N: \"\\<And>n. n \\<ge> N \\<Longrightarrow> \\<bar>S' - (\\<Sum>i<n. norm (f i))\\<bar> < \\<epsilon>\"\n    by (auto simp: tendsto_iff eventually_at_top_linorder sums_def dist_norm abs_minus_commute)\n  \n  show ?case\n  proof (rule exI[of _ \"{..<N}\"], safe, goal_cases)\n    case (2 Y)\n    from 2 have \"(\\<lambda>n. if n \\<in> Y then 0 else f n) sums (S - sum f Y)\"\n      by (intro sums_If_finite_set'[OF \\<open>f sums S\\<close>]) (auto simp: sum_negf)\n    hence \"S - sum f Y = (\\<Sum>n. if n \\<in> Y then 0 else f n)\"\n      by (simp add: sums_iff)\n    also have \"norm \\<dots> \\<le> (\\<Sum>n. norm (if n \\<in> Y then 0 else f n))\"\n      by (rule summable_norm[OF summable_comparison_test'[OF assms(1)]]) auto\n    also have \"\\<dots> \\<le> (\\<Sum>n. if n < N then 0 else norm (f n))\"\n      using 2 by (intro suminf_le summable_comparison_test'[OF assms(1)]) auto\n    also have \"(\\<lambda>n. if n \\<in> {..<N} then 0 else norm (f n)) sums (S' - (\\<Sum>i<N. norm (f i)))\" \n      by (intro sums_If_finite_set'[OF S']) (auto simp: sum_negf)\n    hence \"(\\<Sum>n. if n < N then 0 else norm (f n)) = S' - (\\<Sum>i<N. norm (f i))\"\n      by (simp add: sums_iff)\n    also have \"S' - (\\<Sum>i<N. norm (f i)) \\<le> \\<bar>S' - (\\<Sum>i<N. norm (f i))\\<bar>\" by simp\n    also have \"\\<dots> < \\<epsilon>\" by (rule N) auto\n    finally show ?case by (simp add: dist_norm norm_minus_commute)\n  qed auto\nqed\n\nlemma norm_summable_imp_summable_on:\n  fixes f :: \"nat \\<Rightarrow> 'a :: banach\"\n  assumes \"summable (\\<lambda>n. norm (f n))\"\n  shows   \"f summable_on UNIV\"\n  using norm_summable_imp_has_sum[OF assms, of \"suminf f\"] assms\n  by (auto simp: sums_iff summable_on_def dest: summable_norm_cancel)\n\ntext \\<open>The following lemma indeed needs a complete space (as formalized by the premise \\<^term>\\<open>complete UNIV\\<close>).\n  The following two counterexamples show this:\n  \\begin{itemize}\n  \\item Consider the real vector space $V$ of sequences with finite support, and with the $\\ell_2$-norm (sum of squares).\n      Let $e_i$ denote the sequence with a $1$ at position $i$.\n      Let $f : \\mathbb Z \\to V$ be defined as $f(n) := e_{\\lvert n\\rvert} / n$ (with $f(0) := 0$).\n      We have that $\\sum_{n\\in\\mathbb Z} f(n) = 0$ (it even converges absolutely). \n      But $\\sum_{n\\in\\mathbb N} f(n)$ does not exist (it would converge against a sequence with infinite support).\n  \n  \\item Let $f$ be a positive rational valued function such that $\\sum_{x\\in B} f(x)$ is $\\sqrt 2$ and $\\sum_{x\\in A} f(x)$ is 1 (over the reals, with $A\\subseteq B$).\n      Then $\\sum_{x\\in B} f(x)$ does not exist over the rationals. But $\\sum_{x\\in A} f(x)$ exists.\n  \\end{itemize}\n\n  The lemma also requires uniform continuity of the addition. And example of a topological group with continuous \n  but not uniformly continuous addition would be the positive reals with the usual multiplication as the addition.\n  We do not know whether the lemma would also hold for such topological groups.\\<close>\n\nlemma summable_on_subset:\n  fixes A B and f :: \\<open>'a \\<Rightarrow> 'b::{ab_group_add, uniform_space}\\<close>\n  assumes \\<open>complete (UNIV :: 'b set)\\<close>\n  assumes plus_cont: \\<open>uniformly_continuous_on UNIV (\\<lambda>(x::'b,y). x+y)\\<close>\n  assumes \\<open>f summable_on A\\<close>\n  assumes \\<open>B \\<subseteq> A\\<close>\n  shows \\<open>f summable_on B\\<close>\nproof -\n  let ?filter_fB = \\<open>filtermap (sum f) (finite_subsets_at_top B)\\<close>\n  from \\<open>f summable_on A\\<close>\n  obtain S where \\<open>(sum f \\<longlongrightarrow> S) (finite_subsets_at_top A)\\<close> (is \\<open>(sum f \\<longlongrightarrow> S) ?filter_A\\<close>)\n    using summable_on_def has_sum_def by blast\n  then have cauchy_fA: \\<open>cauchy_filter (filtermap (sum f) (finite_subsets_at_top A))\\<close> (is \\<open>cauchy_filter ?filter_fA\\<close>)\n    by (auto intro!: nhds_imp_cauchy_filter simp: filterlim_def)\n\n  have \\<open>cauchy_filter (filtermap (sum f) (finite_subsets_at_top B))\\<close>\n  proof (unfold cauchy_filter_def, rule filter_leI)\n    fix E :: \\<open>('b\\<times>'b) \\<Rightarrow> bool\\<close> assume \\<open>eventually E uniformity\\<close>\n    then obtain E' where \\<open>eventually E' uniformity\\<close> and E'E'E: \\<open>E' (x, y) \\<longrightarrow> E' (y, z) \\<longrightarrow> E (x, z)\\<close> for x y z\n      using uniformity_trans by blast\n    obtain D where \\<open>eventually D uniformity\\<close> and DE: \\<open>D (x, y) \\<Longrightarrow> E' (x+c, y+c)\\<close> for x y c\n      using plus_cont \\<open>eventually E' uniformity\\<close>\n      unfolding uniformly_continuous_on_uniformity filterlim_def le_filter_def uniformity_prod_def\n      by (auto simp: case_prod_beta eventually_filtermap eventually_prod_same uniformity_refl)\n    have DE': \"E' (x, y)\" if \"D (x + c, y + c)\" for x y c\n      using DE[of \"x + c\" \"y + c\" \"-c\"] that by simp\n\n    from \\<open>eventually D uniformity\\<close> and cauchy_fA have \\<open>eventually D (?filter_fA \\<times>\\<^sub>F ?filter_fA)\\<close>\n      unfolding cauchy_filter_def le_filter_def by simp\n    then obtain P1 P2\n      where ev_P1: \\<open>eventually (\\<lambda>F. P1 (sum f F)) ?filter_A\\<close> \n        and ev_P2: \\<open>eventually (\\<lambda>F. P2 (sum f F)) ?filter_A\\<close>\n        and P1P2E: \\<open>P1 x \\<Longrightarrow> P2 y \\<Longrightarrow> D (x, y)\\<close> for x y\n      unfolding eventually_prod_filter eventually_filtermap\n      by auto\n    from ev_P1 obtain F1 where F1: \\<open>finite F1\\<close> \\<open>F1 \\<subseteq> A\\<close> \\<open>\\<And>F. F\\<supseteq>F1 \\<Longrightarrow> finite F \\<Longrightarrow> F\\<subseteq>A \\<Longrightarrow> P1 (sum f F)\\<close>\n      by (metis eventually_finite_subsets_at_top)\n    from ev_P2 obtain F2 where F2: \\<open>finite F2\\<close> \\<open>F2 \\<subseteq> A\\<close> \\<open>\\<And>F. F\\<supseteq>F2 \\<Longrightarrow> finite F \\<Longrightarrow> F\\<subseteq>A \\<Longrightarrow> P2 (sum f F)\\<close>\n      by (metis eventually_finite_subsets_at_top)\n    define F0 F0A F0B where \\<open>F0 \\<equiv> F1 \\<union> F2\\<close> and \\<open>F0A \\<equiv> F0 - B\\<close> and \\<open>F0B \\<equiv> F0 \\<inter> B\\<close>\n    have [simp]: \\<open>finite F0\\<close>  \\<open>F0 \\<subseteq> A\\<close>\n      using \\<open>F1 \\<subseteq> A\\<close> \\<open>F2 \\<subseteq> A\\<close> \\<open>finite F1\\<close> \\<open>finite F2\\<close> unfolding F0_def by blast+\n \n    have *: \"E' (sum f F1', sum f F2')\"\n      if \"F1'\\<supseteq>F0B\" \"F2'\\<supseteq>F0B\" \"finite F1'\" \"finite F2'\" \"F1'\\<subseteq>B\" \"F2'\\<subseteq>B\" for F1' F2'\n    proof (intro DE'[where c = \"sum f F0A\"] P1P2E)\n      have \"P1 (sum f (F1' \\<union> F0A))\"\n        using that assms F1(1,2) F2(1,2) by (intro F1) (auto simp: F0A_def F0B_def F0_def)\n      thus \"P1 (sum f F1' + sum f F0A)\"\n        by (subst (asm) sum.union_disjoint) (use that in \\<open>auto simp: F0A_def\\<close>)\n    next\n      have \"P2 (sum f (F2' \\<union> F0A))\"\n        using that assms F1(1,2) F2(1,2) by (intro F2) (auto simp: F0A_def F0B_def F0_def)\n      thus \"P2 (sum f F2' + sum f F0A)\"\n        by (subst (asm) sum.union_disjoint) (use that in \\<open>auto simp: F0A_def\\<close>)      \n    qed\n\n    show \\<open>eventually E (?filter_fB \\<times>\\<^sub>F ?filter_fB)\\<close>\n      unfolding eventually_prod_filter\n    proof (safe intro!: exI)\n      show \"eventually (\\<lambda>x. E' (x, sum f F0B)) (filtermap (sum f) (finite_subsets_at_top B))\"\n       and \"eventually (\\<lambda>x. E' (sum f F0B, x)) (filtermap (sum f) (finite_subsets_at_top B))\"\n        unfolding eventually_filtermap eventually_finite_subsets_at_top\n        by (rule exI[of _ F0B]; use * in \\<open>force simp: F0B_def\\<close>)+\n    next\n      show \"E (x, y)\" if \"E' (x, sum f F0B)\" and \"E' (sum f F0B, y)\" for x y\n        using E'E'E that by blast\n    qed\n  qed\n\n  then obtain x where \\<open>?filter_fB \\<le> nhds x\\<close>\n    using cauchy_filter_complete_converges[of ?filter_fB UNIV] \\<open>complete (UNIV :: _)\\<close>\n    by (auto simp: filtermap_bot_iff)\n  then have \\<open>(sum f \\<longlongrightarrow> x) (finite_subsets_at_top B)\\<close>\n    by (auto simp: filterlim_def)\n  then show ?thesis\n    by (auto simp: summable_on_def has_sum_def)\nqed\n\ntext \\<open>A special case of @{thm [source] summable_on_subset} for Banach spaces with less premises.\\<close>\n\nlemma summable_on_subset_banach:\n  fixes A B and f :: \\<open>'a \\<Rightarrow> 'b::banach\\<close>\n  assumes \\<open>f summable_on A\\<close>\n  assumes \\<open>B \\<subseteq> A\\<close>\n  shows \\<open>f summable_on B\\<close>\n  by (rule summable_on_subset[OF _ _ assms])\n     (auto simp: complete_def convergent_def dest!: Cauchy_convergent)\n\nlemma has_sum_empty[simp]: \\<open>has_sum f {} 0\\<close>\n  by (meson ex_in_conv has_sum_0)\n\nlemma summable_on_empty[simp]: \\<open>f summable_on {}\\<close>\n  by auto\n\nlemma infsum_empty[simp]: \\<open>infsum f {} = 0\\<close>\n  by simp\n\nlemma sum_has_sum:\n  fixes f :: \"'a \\<Rightarrow> 'b::topological_comm_monoid_add\"\n  assumes finite: \\<open>finite A\\<close>\n  assumes conv: \\<open>\\<And>a. a \\<in> A \\<Longrightarrow> has_sum f (B a) (s a)\\<close>\n  assumes disj: \\<open>\\<And>a a'. a\\<in>A \\<Longrightarrow> a'\\<in>A \\<Longrightarrow> a\\<noteq>a' \\<Longrightarrow> B a \\<inter> B a' = {}\\<close>\n  shows \\<open>has_sum f (\\<Union>a\\<in>A. B a) (sum s A)\\<close>\n  using assms\nproof (insert finite conv disj, induction)\n  case empty\n  then show ?case \n    by simp\nnext\n  case (insert x A)\n  have \\<open>has_sum f (B x) (s x)\\<close>\n    by (simp add: insert.prems)\n  moreover have IH: \\<open>has_sum f (\\<Union>a\\<in>A. B a) (sum s A)\\<close>\n    using insert by simp\n  ultimately have \\<open>has_sum f (B x \\<union> (\\<Union>a\\<in>A. B a)) (s x + sum s A)\\<close>\n    apply (rule has_sum_Un_disjoint)\n    using insert by auto\n  then show ?case\n    using insert.hyps by auto\nqed\n\n\nlemma summable_on_finite_union_disjoint:\n  fixes f :: \"'a \\<Rightarrow> 'b::topological_comm_monoid_add\"\n  assumes finite: \\<open>finite A\\<close>\n  assumes conv: \\<open>\\<And>a. a \\<in> A \\<Longrightarrow> f summable_on (B a)\\<close>\n  assumes disj: \\<open>\\<And>a a'. a\\<in>A \\<Longrightarrow> a'\\<in>A \\<Longrightarrow> a\\<noteq>a' \\<Longrightarrow> B a \\<inter> B a' = {}\\<close>\n  shows \\<open>f summable_on (\\<Union>a\\<in>A. B a)\\<close>\n  using finite conv disj apply induction by (auto intro!: summable_on_Un_disjoint)\n\nlemma sum_infsum:\n  fixes f :: \"'a \\<Rightarrow> 'b::{topological_comm_monoid_add, t2_space}\"\n  assumes finite: \\<open>finite A\\<close>\n  assumes conv: \\<open>\\<And>a. a \\<in> A \\<Longrightarrow> f summable_on (B a)\\<close>\n  assumes disj: \\<open>\\<And>a a'. a\\<in>A \\<Longrightarrow> a'\\<in>A \\<Longrightarrow> a\\<noteq>a' \\<Longrightarrow> B a \\<inter> B a' = {}\\<close>\n  shows \\<open>sum (\\<lambda>a. infsum f (B a)) A = infsum f (\\<Union>a\\<in>A. B a)\\<close>\n  by (rule sym, rule infsumI)\n     (use sum_has_sum[of A f B \\<open>\\<lambda>a. infsum f (B a)\\<close>] assms in auto)\n\ntext \\<open>The lemmas \\<open>infsum_comm_additive_general\\<close> and \\<open>infsum_comm_additive\\<close> (and variants) below both state that the infinite sum commutes with\n  a continuous additive function. \\<open>infsum_comm_additive_general\\<close> is stated more for more general type classes\n  at the expense of a somewhat less compact formulation of the premises.\n  E.g., by avoiding the constant \\<^const>\\<open>additive\\<close> which introduces an additional sort constraint\n  (group instead of monoid). For example, extended reals (\\<^typ>\\<open>ereal\\<close>, \\<^typ>\\<open>ennreal\\<close>) are not covered\n  by \\<open>infsum_comm_additive\\<close>.\\<close>\n\n\nlemma has_sum_comm_additive_general: \n  fixes f :: \\<open>'b :: {comm_monoid_add,topological_space} \\<Rightarrow> 'c :: {comm_monoid_add,topological_space}\\<close>\n  assumes f_sum: \\<open>\\<And>F. finite F \\<Longrightarrow> F \\<subseteq> S \\<Longrightarrow> sum (f o g) F = f (sum g F)\\<close>\n      \\<comment> \\<open>Not using \\<^const>\\<open>additive\\<close> because it would add sort constraint \\<^class>\\<open>ab_group_add\\<close>\\<close>\n  assumes cont: \\<open>f \\<midarrow>x\\<rightarrow> f x\\<close>\n    \\<comment> \\<open>For \\<^class>\\<open>t2_space\\<close>, this is equivalent to \\<open>isCont f x\\<close> by @{thm [source] isCont_def}.\\<close>\n  assumes infsum: \\<open>has_sum g S x\\<close>\n  shows \\<open>has_sum (f o g) S (f x)\\<close> \nproof -\n  have \\<open>(sum g \\<longlongrightarrow> x) (finite_subsets_at_top S)\\<close>\n    using infsum has_sum_def by blast\n  then have \\<open>((f o sum g) \\<longlongrightarrow> f x) (finite_subsets_at_top S)\\<close>\n    apply (rule tendsto_compose_at)\n    using assms by auto\n  then have \\<open>(sum (f o g) \\<longlongrightarrow> f x) (finite_subsets_at_top S)\\<close>\n    apply (rule tendsto_cong[THEN iffD1, rotated])\n    using f_sum by fastforce\n  then show \\<open>has_sum (f o g) S (f x)\\<close>\n    using has_sum_def by blast \nqed\n\nlemma summable_on_comm_additive_general:\n  fixes f :: \\<open>'b :: {comm_monoid_add,topological_space} \\<Rightarrow> 'c :: {comm_monoid_add,topological_space}\\<close>\n  assumes \\<open>\\<And>F. finite F \\<Longrightarrow> F \\<subseteq> S \\<Longrightarrow> sum (f o g) F = f (sum g F)\\<close>\n    \\<comment> \\<open>Not using \\<^const>\\<open>additive\\<close> because it would add sort constraint \\<^class>\\<open>ab_group_add\\<close>\\<close>\n  assumes \\<open>\\<And>x. has_sum g S x \\<Longrightarrow> f \\<midarrow>x\\<rightarrow> f x\\<close>\n    \\<comment> \\<open>For \\<^class>\\<open>t2_space\\<close>, this is equivalent to \\<open>isCont f x\\<close> by @{thm [source] isCont_def}.\\<close>\n  assumes \\<open>g summable_on S\\<close>\n  shows \\<open>(f o g) summable_on S\\<close>\n  by (meson assms summable_on_def has_sum_comm_additive_general has_sum_def infsum_tendsto)\n\nlemma infsum_comm_additive_general:\n  fixes f :: \\<open>'b :: {comm_monoid_add,t2_space} \\<Rightarrow> 'c :: {comm_monoid_add,t2_space}\\<close>\n  assumes f_sum: \\<open>\\<And>F. finite F \\<Longrightarrow> F \\<subseteq> S \\<Longrightarrow> sum (f o g) F = f (sum g F)\\<close>\n      \\<comment> \\<open>Not using \\<^const>\\<open>additive\\<close> because it would add sort constraint \\<^class>\\<open>ab_group_add\\<close>\\<close>\n  assumes \\<open>isCont f (infsum g S)\\<close>\n  assumes \\<open>g summable_on S\\<close>\n  shows \\<open>infsum (f o g) S = f (infsum g S)\\<close>\n  using assms\n  by (intro infsumI has_sum_comm_additive_general has_sum_infsum) (auto simp: isCont_def)\n\nlemma has_sum_comm_additive: \n  fixes f :: \\<open>'b :: {ab_group_add,topological_space} \\<Rightarrow> 'c :: {ab_group_add,topological_space}\\<close>\n  assumes \\<open>additive f\\<close>\n  assumes \\<open>f \\<midarrow>x\\<rightarrow> f x\\<close>\n    \\<comment> \\<open>For \\<^class>\\<open>t2_space\\<close>, this is equivalent to \\<open>isCont f x\\<close> by @{thm [source] isCont_def}.\\<close>\n  assumes infsum: \\<open>has_sum g S x\\<close>\n  shows \\<open>has_sum (f o g) S (f x)\\<close>\n  using assms\n  by (intro has_sum_comm_additive_general has_sum_infsum) (auto simp: isCont_def additive.sum) \n\nlemma summable_on_comm_additive:\n  fixes f :: \\<open>'b :: {ab_group_add,t2_space} \\<Rightarrow> 'c :: {ab_group_add,topological_space}\\<close>\n  assumes \\<open>additive f\\<close>\n  assumes \\<open>isCont f (infsum g S)\\<close>\n  assumes \\<open>g summable_on S\\<close>\n  shows \\<open>(f o g) summable_on S\\<close>\n  by (meson assms(1) assms(2) assms(3) summable_on_def has_sum_comm_additive has_sum_infsum isContD)\n\nlemma infsum_comm_additive:\n  fixes f :: \\<open>'b :: {ab_group_add,t2_space} \\<Rightarrow> 'c :: {ab_group_add,t2_space}\\<close>\n  assumes \\<open>additive f\\<close>\n  assumes \\<open>isCont f (infsum g S)\\<close>\n  assumes \\<open>g summable_on S\\<close>\n  shows \\<open>infsum (f o g) S = f (infsum g S)\\<close>\n  by (rule infsum_comm_additive_general; auto simp: assms additive.sum)\n\nlemma nonneg_bdd_above_has_sum:\n  fixes f :: \\<open>'a \\<Rightarrow> 'b :: {conditionally_complete_linorder, ordered_comm_monoid_add, linorder_topology}\\<close>\n  assumes \\<open>\\<And>x. x\\<in>A \\<Longrightarrow> f x \\<ge> 0\\<close>\n  assumes \\<open>bdd_above (sum f ` {F. F\\<subseteq>A \\<and> finite F})\\<close>\n  shows \\<open>has_sum f A (SUP F\\<in>{F. finite F \\<and> F\\<subseteq>A}. sum f F)\\<close>\nproof -\n  have \\<open>(sum f \\<longlongrightarrow> (SUP F\\<in>{F. finite F \\<and> F\\<subseteq>A}. sum f F)) (finite_subsets_at_top A)\\<close>\n  proof (rule order_tendstoI)\n    fix a assume \\<open>a < (SUP F\\<in>{F. finite F \\<and> F\\<subseteq>A}. sum f F)\\<close>\n    then obtain F where \\<open>a < sum f F\\<close> and \\<open>finite F\\<close> and \\<open>F \\<subseteq> A\\<close>\n      by (metis (mono_tags, lifting) Collect_cong Collect_empty_eq assms(2) empty_subsetI finite.emptyI less_cSUP_iff mem_Collect_eq)\n    show \\<open>\\<forall>\\<^sub>F x in finite_subsets_at_top A. a < sum f x\\<close>\n      unfolding eventually_finite_subsets_at_top\n    proof (rule exI[of _ F], safe)\n      fix Y assume Y: \"finite Y\" \"F \\<subseteq> Y\" \"Y \\<subseteq> A\"\n      have \"a < sum f F\"\n        by fact\n      also have \"\\<dots> \\<le> sum f Y\"\n        using assms Y by (intro sum_mono2) auto\n      finally show \"a < sum f Y\" .\n    qed (use \\<open>finite F\\<close> \\<open>F \\<subseteq> A\\<close> in auto)\n  next\n    fix a assume *: \\<open>(SUP F\\<in>{F. finite F \\<and> F\\<subseteq>A}. sum f F) < a\\<close>\n    have \\<open>sum f F < a\\<close> if \\<open>F\\<subseteq>A\\<close> and \\<open>finite F\\<close> for F\n    proof -\n      have \"sum f F \\<le> (SUP F\\<in>{F. finite F \\<and> F\\<subseteq>A}. sum f F)\"\n        by (rule cSUP_upper) (use that assms(2) in \\<open>auto simp: conj_commute\\<close>)\n      also have \"\\<dots> < a\"\n        by fact\n      finally show ?thesis .\n    qed\n    then show \\<open>\\<forall>\\<^sub>F x in finite_subsets_at_top A. sum f x < a\\<close>\n      by (rule eventually_finite_subsets_at_top_weakI)\n  qed\n  then show ?thesis\n    using has_sum_def by blast\nqed\n\nlemma nonneg_bdd_above_summable_on:\n  fixes f :: \\<open>'a \\<Rightarrow> 'b :: {conditionally_complete_linorder, ordered_comm_monoid_add, linorder_topology}\\<close>\n  assumes \\<open>\\<And>x. x\\<in>A \\<Longrightarrow> f x \\<ge> 0\\<close>\n  assumes \\<open>bdd_above (sum f ` {F. F\\<subseteq>A \\<and> finite F})\\<close>\n  shows \\<open>f summable_on A\\<close>\n  using assms(1) assms(2) summable_on_def nonneg_bdd_above_has_sum by blast\n\nlemma nonneg_bdd_above_infsum:\n  fixes f :: \\<open>'a \\<Rightarrow> 'b :: {conditionally_complete_linorder, ordered_comm_monoid_add, linorder_topology}\\<close>\n  assumes \\<open>\\<And>x. x\\<in>A \\<Longrightarrow> f x \\<ge> 0\\<close>\n  assumes \\<open>bdd_above (sum f ` {F. F\\<subseteq>A \\<and> finite F})\\<close>\n  shows \\<open>infsum f A = (SUP F\\<in>{F. finite F \\<and> F\\<subseteq>A}. sum f F)\\<close>\n  using assms by (auto intro!: infsumI nonneg_bdd_above_has_sum)\n\nlemma nonneg_has_sum_complete:\n  fixes f :: \\<open>'a \\<Rightarrow> 'b :: {complete_linorder, ordered_comm_monoid_add, linorder_topology}\\<close>\n  assumes \\<open>\\<And>x. x\\<in>A \\<Longrightarrow> f x \\<ge> 0\\<close>\n  shows \\<open>has_sum f A (SUP F\\<in>{F. finite F \\<and> F\\<subseteq>A}. sum f F)\\<close>\n  using assms nonneg_bdd_above_has_sum by blast\n\nlemma nonneg_summable_on_complete:\n  fixes f :: \\<open>'a \\<Rightarrow> 'b :: {complete_linorder, ordered_comm_monoid_add, linorder_topology}\\<close>\n  assumes \\<open>\\<And>x. x\\<in>A \\<Longrightarrow> f x \\<ge> 0\\<close>\n  shows \\<open>f summable_on A\\<close>\n  using assms nonneg_bdd_above_summable_on by blast\n\nlemma nonneg_infsum_complete:\n  fixes f :: \\<open>'a \\<Rightarrow> 'b :: {complete_linorder, ordered_comm_monoid_add, linorder_topology}\\<close>\n  assumes \\<open>\\<And>x. x\\<in>A \\<Longrightarrow> f x \\<ge> 0\\<close>\n  shows \\<open>infsum f A = (SUP F\\<in>{F. finite F \\<and> F\\<subseteq>A}. sum f F)\\<close>\n  using assms nonneg_bdd_above_infsum by blast\n\nlemma has_sum_nonneg:\n  fixes f :: \"'a \\<Rightarrow> 'b::{ordered_comm_monoid_add,linorder_topology}\"\n  assumes \"has_sum f M a\"\n    and \"\\<And>x. x \\<in> M \\<Longrightarrow> 0 \\<le> f x\"\n  shows \"a \\<ge> 0\"\n  by (metis (no_types, lifting) DiffD1 assms(1) assms(2) empty_iff has_sum_0 has_sum_mono_neutral order_refl)\n\nlemma infsum_nonneg:\n  fixes f :: \"'a \\<Rightarrow> 'b::{ordered_comm_monoid_add,linorder_topology}\"\n  assumes \"\\<And>x. x \\<in> M \\<Longrightarrow> 0 \\<le> f x\"\n  shows \"infsum f M \\<ge> 0\" (is \"?lhs \\<ge> _\")\n  apply (cases \\<open>f summable_on M\\<close>)\n   apply (metis assms infsum_0_simp summable_on_0_simp infsum_mono)\n  using assms by (auto simp add: infsum_not_exists)\n\nlemma has_sum_mono2:\n  fixes f :: \"'a \\<Rightarrow> 'b::{topological_ab_group_add, ordered_comm_monoid_add,linorder_topology}\"\n  assumes \"has_sum f A S\" \"has_sum f B S'\" \"A \\<subseteq> B\"\n  assumes \"\\<And>x. x \\<in> B - A \\<Longrightarrow> f x \\<ge> 0\"\n  shows   \"S \\<le> S'\"\nproof -\n  have \"has_sum f (B - A) (S' - S)\"\n    by (rule has_sum_Diff) fact+\n  hence \"S' - S \\<ge> 0\"\n    by (rule has_sum_nonneg) (use assms(4) in auto)\n  thus ?thesis\n    by (metis add_0 add_mono_thms_linordered_semiring(3) diff_add_cancel)\nqed\n\nlemma infsum_mono2:\n  fixes f :: \"'a \\<Rightarrow> 'b::{topological_ab_group_add, ordered_comm_monoid_add,linorder_topology}\"\n  assumes \"f summable_on A\" \"f summable_on B\" \"A \\<subseteq> B\"\n  assumes \"\\<And>x. x \\<in> B - A \\<Longrightarrow> f x \\<ge> 0\"\n  shows   \"infsum f A \\<le> infsum f B\"\n  by (rule has_sum_mono2[OF has_sum_infsum has_sum_infsum]) (use assms in auto)\n\nlemma finite_sum_le_has_sum:\n  fixes f :: \"'a \\<Rightarrow> 'b::{topological_ab_group_add, ordered_comm_monoid_add,linorder_topology}\"\n  assumes \"has_sum f A S\" \"finite B\" \"B \\<subseteq> A\"\n  assumes \"\\<And>x. x \\<in> A - B \\<Longrightarrow> f x \\<ge> 0\"\n  shows   \"sum f B \\<le> S\"\nproof (rule has_sum_mono2)\n  show \"has_sum f A S\"\n    by fact\n  show \"has_sum f B (sum f B)\"\n    by (rule has_sum_finite) fact+\nqed (use assms in auto)\n\nlemma finite_sum_le_infsum:\n  fixes f :: \"'a \\<Rightarrow> 'b::{topological_ab_group_add, ordered_comm_monoid_add,linorder_topology}\"\n  assumes \"f summable_on A\" \"finite B\" \"B \\<subseteq> A\"\n  assumes \"\\<And>x. x \\<in> A - B \\<Longrightarrow> f x \\<ge> 0\"\n  shows   \"sum f B \\<le> infsum f A\"\n  by (rule finite_sum_le_has_sum[OF has_sum_infsum]) (use assms in auto)\n\nlemma has_sum_reindex:\n  assumes \\<open>inj_on h A\\<close>\n  shows \\<open>has_sum g (h ` A) x \\<longleftrightarrow> has_sum (g \\<circ> h) A x\\<close>\nproof -\n  have \\<open>has_sum g (h ` A) x \\<longleftrightarrow> (sum g \\<longlongrightarrow> x) (finite_subsets_at_top (h ` A))\\<close>\n    by (simp add: has_sum_def)\n  also have \\<open>\\<dots> \\<longleftrightarrow> ((\\<lambda>F. sum g (h ` F)) \\<longlongrightarrow> x) (finite_subsets_at_top A)\\<close>\n    apply (subst filtermap_image_finite_subsets_at_top[symmetric])\n    using assms by (auto simp: filterlim_def filtermap_filtermap)\n  also have \\<open>\\<dots> \\<longleftrightarrow> (sum (g \\<circ> h) \\<longlongrightarrow> x) (finite_subsets_at_top A)\\<close>\n    apply (rule tendsto_cong)\n    apply (rule eventually_finite_subsets_at_top_weakI)\n    apply (rule sum.reindex)\n    using assms subset_inj_on by blast\n  also have \\<open>\\<dots> \\<longleftrightarrow> has_sum (g \\<circ> h) A x\\<close>\n    by (simp add: has_sum_def)\n  finally show ?thesis .\nqed\n\nlemma summable_on_reindex:\n  assumes \\<open>inj_on h A\\<close>\n  shows \\<open>g summable_on (h ` A) \\<longleftrightarrow> (g \\<circ> h) summable_on A\\<close>\n  by (simp add: assms summable_on_def has_sum_reindex)\n\nlemma infsum_reindex:\n  assumes \\<open>inj_on h A\\<close>\n  shows \\<open>infsum g (h ` A) = infsum (g \\<circ> h) A\\<close>\n  by (metis (no_types, opaque_lifting) assms finite_subsets_at_top_neq_bot infsum_def \n        summable_on_reindex has_sum_def has_sum_infsum has_sum_reindex tendsto_Lim)\n\nlemma summable_on_reindex_bij_betw:\n  assumes \"bij_betw g A B\"\n  shows   \"(\\<lambda>x. f (g x)) summable_on A \\<longleftrightarrow> f summable_on B\"\nproof -\n  thm summable_on_reindex\n  have \\<open>(\\<lambda>x. f (g x)) summable_on A \\<longleftrightarrow> f summable_on g ` A\\<close>\n    apply (rule summable_on_reindex[symmetric, unfolded o_def])\n    using assms bij_betw_imp_inj_on by blast\n  also have \\<open>\\<dots> \\<longleftrightarrow> f summable_on B\\<close>\n    using assms bij_betw_imp_surj_on by blast\n  finally show ?thesis .\nqed\n\nlemma infsum_reindex_bij_betw:\n  assumes \"bij_betw g A B\"\n  shows   \"infsum (\\<lambda>x. f (g x)) A = infsum f B\"\nproof -\n  have \\<open>infsum (\\<lambda>x. f (g x)) A = infsum f (g ` A)\\<close>\n    by (metis (mono_tags, lifting) assms bij_betw_imp_inj_on infsum_cong infsum_reindex o_def)\n  also have \\<open>\\<dots> = infsum f B\\<close>\n    using assms bij_betw_imp_surj_on by blast\n  finally show ?thesis .\nqed\n\nlemma sum_uniformity:\n  assumes plus_cont: \\<open>uniformly_continuous_on UNIV (\\<lambda>(x::'b::{uniform_space,comm_monoid_add},y). x+y)\\<close>\n  assumes \\<open>eventually E uniformity\\<close>\n  obtains D where \\<open>eventually D uniformity\\<close> \n    and \\<open>\\<And>M::'a set. \\<And>f f' :: 'a \\<Rightarrow> 'b. card M \\<le> n \\<and> (\\<forall>m\\<in>M. D (f m, f' m)) \\<Longrightarrow> E (sum f M, sum f' M)\\<close>\nproof (atomize_elim, insert \\<open>eventually E uniformity\\<close>, induction n arbitrary: E rule:nat_induct)\n  case 0\n  then show ?case\n    by (metis card_eq_0_iff equals0D le_zero_eq sum.infinite sum.not_neutral_contains_not_neutral uniformity_refl)\nnext\n  case (Suc n)\n  from plus_cont[unfolded uniformly_continuous_on_uniformity filterlim_def le_filter_def, rule_format, OF Suc.prems]\n  obtain D1 D2 where \\<open>eventually D1 uniformity\\<close> and \\<open>eventually D2 uniformity\\<close> \n    and D1D2E: \\<open>D1 (x, y) \\<Longrightarrow> D2 (x', y') \\<Longrightarrow> E (x + x', y + y')\\<close> for x y x' y'\n    apply atomize_elim\n    by (auto simp: eventually_prod_filter case_prod_beta uniformity_prod_def eventually_filtermap)\n\n  from Suc.IH[OF \\<open>eventually D2 uniformity\\<close>]\n  obtain D3 where \\<open>eventually D3 uniformity\\<close> and D3: \\<open>card M \\<le> n \\<Longrightarrow> (\\<forall>m\\<in>M. D3 (f m, f' m)) \\<Longrightarrow> D2 (sum f M, sum f' M)\\<close> \n    for M :: \\<open>'a set\\<close> and f f'\n    by metis\n\n  define D where \\<open>D x \\<equiv> D1 x \\<and> D3 x\\<close> for x\n  have \\<open>eventually D uniformity\\<close>\n    using D_def \\<open>eventually D1 uniformity\\<close> \\<open>eventually D3 uniformity\\<close> eventually_elim2 by blast\n\n  have \\<open>E (sum f M, sum f' M)\\<close> \n    if \\<open>card M \\<le> Suc n\\<close> and DM: \\<open>\\<forall>m\\<in>M. D (f m, f' m)\\<close>\n    for M :: \\<open>'a set\\<close> and f f'\n  proof (cases \\<open>card M = 0\\<close>)\n    case True\n    then show ?thesis\n      by (metis Suc.prems card_eq_0_iff sum.empty sum.infinite uniformity_refl) \n  next\n    case False\n    with \\<open>card M \\<le> Suc n\\<close> obtain N x where \\<open>card N \\<le> n\\<close> and \\<open>x \\<notin> N\\<close> and \\<open>M = insert x N\\<close>\n      by (metis card_Suc_eq less_Suc_eq_0_disj less_Suc_eq_le)\n\n    from DM have \\<open>\\<And>m. m\\<in>N \\<Longrightarrow> D (f m, f' m)\\<close>\n      using \\<open>M = insert x N\\<close> by blast\n    with D3[OF \\<open>card N \\<le> n\\<close>]\n    have D2_N: \\<open>D2 (sum f N, sum f' N)\\<close>\n      using D_def by blast\n\n    from DM \n    have \\<open>D (f x, f' x)\\<close>\n      using \\<open>M = insert x N\\<close> by blast\n    then have \\<open>D1 (f x, f' x)\\<close>\n      by (simp add: D_def)\n\n    with D2_N\n    have \\<open>E (f x + sum f N, f' x + sum f' N)\\<close>\n      using D1D2E by presburger\n\n    then show \\<open>E (sum f M, sum f' M)\\<close>\n      by (metis False \\<open>M = insert x N\\<close> \\<open>x \\<notin> N\\<close> card.infinite finite_insert sum.insert)\n  qed\n  with \\<open>eventually D uniformity\\<close>\n  show ?case \n    by auto\nqed\n\nlemma has_sum_Sigma:\n  fixes A :: \"'a set\" and B :: \"'a \\<Rightarrow> 'b set\"\n    and f :: \\<open>'a \\<times> 'b \\<Rightarrow> 'c::{comm_monoid_add,uniform_space}\\<close>\n  assumes plus_cont: \\<open>uniformly_continuous_on UNIV (\\<lambda>(x::'c,y). x+y)\\<close>\n  assumes summableAB: \"has_sum f (Sigma A B) a\"\n  assumes summableB: \\<open>\\<And>x. x\\<in>A \\<Longrightarrow> has_sum (\\<lambda>y. f (x, y)) (B x) (b x)\\<close>\n  shows \"has_sum b A a\"\nproof -\n  define F FB FA where \\<open>F = finite_subsets_at_top (Sigma A B)\\<close> and \\<open>FB x = finite_subsets_at_top (B x)\\<close>\n    and \\<open>FA = finite_subsets_at_top A\\<close> for x\n\n  from summableB\n  have sum_b: \\<open>(sum (\\<lambda>y. f (x, y)) \\<longlongrightarrow> b x) (FB x)\\<close> if \\<open>x \\<in> A\\<close> for x\n    using FB_def[abs_def] has_sum_def that by auto\n  from summableAB\n  have sum_S: \\<open>(sum f \\<longlongrightarrow> a) F\\<close>\n    using F_def has_sum_def by blast\n\n  have finite_proj: \\<open>finite {b| b. (a,b) \\<in> H}\\<close> if \\<open>finite H\\<close> for H :: \\<open>('a\\<times>'b) set\\<close> and a\n    apply (subst asm_rl[of \\<open>{b| b. (a,b) \\<in> H} = snd ` {ab. ab \\<in> H \\<and> fst ab = a}\\<close>])\n    by (auto simp: image_iff that)\n\n  have \\<open>(sum b \\<longlongrightarrow> a) FA\\<close>\n  proof (rule tendsto_iff_uniformity[THEN iffD2, rule_format])\n    fix E :: \\<open>('c \\<times> 'c) \\<Rightarrow> bool\\<close>\n    assume \\<open>eventually E uniformity\\<close>\n    then obtain D where D_uni: \\<open>eventually D uniformity\\<close> and DDE': \\<open>\\<And>x y z. D (x, y) \\<Longrightarrow> D (y, z) \\<Longrightarrow> E (x, z)\\<close>\n      by (metis (no_types, lifting) \\<open>eventually E uniformity\\<close> uniformity_transE)\n    from sum_S obtain G where \\<open>finite G\\<close> and \\<open>G \\<subseteq> Sigma A B\\<close>\n      and G_sum: \\<open>G \\<subseteq> H \\<Longrightarrow> H \\<subseteq> Sigma A B \\<Longrightarrow> finite H \\<Longrightarrow> D (sum f H, a)\\<close> for H\n      unfolding tendsto_iff_uniformity\n      by (metis (mono_tags, lifting) D_uni F_def eventually_finite_subsets_at_top)\n    have \\<open>finite (fst ` G)\\<close> and \\<open>fst ` G \\<subseteq> A\\<close>\n      using \\<open>finite G\\<close> \\<open>G \\<subseteq> Sigma A B\\<close> by auto\n    thm uniformity_prod_def\n    define Ga where \\<open>Ga a = {b. (a,b) \\<in> G}\\<close> for a\n    have Ga_fin: \\<open>finite (Ga a)\\<close> and Ga_B: \\<open>Ga a \\<subseteq> B a\\<close> for a\n      using \\<open>finite G\\<close> \\<open>G \\<subseteq> Sigma A B\\<close> finite_proj by (auto simp: Ga_def finite_proj)\n\n    have \\<open>E (sum b M, a)\\<close> if \\<open>M \\<supseteq> fst ` G\\<close> and \\<open>finite M\\<close> and \\<open>M \\<subseteq> A\\<close> for M\n    proof -\n      define FMB where \\<open>FMB = finite_subsets_at_top (Sigma M B)\\<close>\n      have \\<open>eventually (\\<lambda>H. D (\\<Sum>a\\<in>M. b a, \\<Sum>(a,b)\\<in>H. f (a,b))) FMB\\<close>\n      proof -\n        obtain D' where D'_uni: \\<open>eventually D' uniformity\\<close> \n          and \\<open>card M' \\<le> card M \\<and> (\\<forall>m\\<in>M'. D' (g m, g' m)) \\<Longrightarrow> D (sum g M', sum g' M')\\<close>\n            for M' :: \\<open>'a set\\<close> and g g'\n          apply (rule sum_uniformity[OF plus_cont \\<open>eventually D uniformity\\<close>, where n=\\<open>card M\\<close>])\n          by auto\n        then have D'_sum_D: \\<open>(\\<forall>m\\<in>M. D' (g m, g' m)) \\<Longrightarrow> D (sum g M, sum g' M)\\<close> for g g'\n          by auto\n\n        obtain Ha where \\<open>Ha a \\<supseteq> Ga a\\<close> and Ha_fin: \\<open>finite (Ha a)\\<close> and Ha_B: \\<open>Ha a \\<subseteq> B a\\<close>\n          and D'_sum_Ha: \\<open>Ha a \\<subseteq> L \\<Longrightarrow> L \\<subseteq> B a \\<Longrightarrow> finite L \\<Longrightarrow> D' (b a, sum (\\<lambda>b. f (a,b)) L)\\<close> if \\<open>a \\<in> A\\<close> for a L\n        proof -\n          from sum_b[unfolded tendsto_iff_uniformity, rule_format, OF _ D'_uni[THEN uniformity_sym]]\n          obtain Ha0 where \\<open>finite (Ha0 a)\\<close> and \\<open>Ha0 a \\<subseteq> B a\\<close>\n            and \\<open>Ha0 a \\<subseteq> L \\<Longrightarrow> L \\<subseteq> B a \\<Longrightarrow> finite L \\<Longrightarrow> D' (b a, sum (\\<lambda>b. f (a,b)) L)\\<close> if \\<open>a \\<in> A\\<close> for a L\n            unfolding FB_def eventually_finite_subsets_at_top unfolding prod.case by metis\n          moreover define Ha where \\<open>Ha a = Ha0 a \\<union> Ga a\\<close> for a\n          ultimately show ?thesis\n            using that[where Ha=Ha]\n            using Ga_fin Ga_B by auto\n        qed\n\n        have \\<open>D (\\<Sum>a\\<in>M. b a, \\<Sum>(a,b)\\<in>H. f (a,b))\\<close> if \\<open>finite H\\<close> and \\<open>H \\<subseteq> Sigma M B\\<close> and \\<open>H \\<supseteq> Sigma M Ha\\<close> for H\n        proof -\n          define Ha' where \\<open>Ha' a = {b| b. (a,b) \\<in> H}\\<close> for a\n          have [simp]: \\<open>finite (Ha' a)\\<close> and [simp]: \\<open>Ha' a \\<supseteq> Ha a\\<close> and [simp]: \\<open>Ha' a \\<subseteq> B a\\<close> if \\<open>a \\<in> M\\<close> for a\n            unfolding Ha'_def using \\<open>finite H\\<close> \\<open>H \\<subseteq> Sigma M B\\<close> \\<open>Sigma M Ha \\<subseteq> H\\<close> that finite_proj by auto\n          have \\<open>Sigma M Ha' = H\\<close>\n            using that by (auto simp: Ha'_def)\n          then have *: \\<open>(\\<Sum>(a,b)\\<in>H. f (a,b)) = (\\<Sum>a\\<in>M. \\<Sum>b\\<in>Ha' a. f (a,b))\\<close>\n            apply (subst sum.Sigma)\n            using \\<open>finite M\\<close> by auto\n          have \\<open>D' (b a, sum (\\<lambda>b. f (a,b)) (Ha' a))\\<close> if \\<open>a \\<in> M\\<close> for a\n            apply (rule D'_sum_Ha)\n            using that \\<open>M \\<subseteq> A\\<close> by auto\n          then have \\<open>D (\\<Sum>a\\<in>M. b a, \\<Sum>a\\<in>M. sum (\\<lambda>b. f (a,b)) (Ha' a))\\<close>\n            by (rule_tac D'_sum_D, auto)\n          with * show ?thesis\n            by auto\n        qed\n        moreover have \\<open>Sigma M Ha \\<subseteq> Sigma M B\\<close>\n          using Ha_B \\<open>M \\<subseteq> A\\<close> by auto\n        ultimately show ?thesis\n          unfolding FMB_def eventually_finite_subsets_at_top\n          by (intro exI[of _ \"Sigma M Ha\"])\n             (use Ha_fin that(2,3) in \\<open>fastforce intro!: finite_SigmaI\\<close>)\n      qed\n      moreover have \\<open>eventually (\\<lambda>H. D (\\<Sum>(a,b)\\<in>H. f (a,b), a)) FMB\\<close>\n        unfolding FMB_def eventually_finite_subsets_at_top\n      proof (rule exI[of _ G], safe)\n        fix Y assume Y: \"finite Y\" \"G \\<subseteq> Y\" \"Y \\<subseteq> Sigma M B\"\n        have \"Y \\<subseteq> Sigma A B\"\n          using Y \\<open>M \\<subseteq> A\\<close> by blast\n        thus \"D (\\<Sum>(a,b)\\<in>Y. f (a, b), a)\"\n          using G_sum[of Y] Y by auto\n      qed (use \\<open>finite G\\<close> \\<open>G \\<subseteq> Sigma A B\\<close> that in auto)\n      ultimately have \\<open>\\<forall>\\<^sub>F x in FMB. E (sum b M, a)\\<close>\n        by eventually_elim (use DDE' in auto)\n      then show \\<open>E (sum b M, a)\\<close>\n        by (rule eventually_const[THEN iffD1, rotated]) (force simp: FMB_def)\n    qed\n    then show \\<open>\\<forall>\\<^sub>F x in FA. E (sum b x, a)\\<close>\n      using \\<open>finite (fst ` G)\\<close> and \\<open>fst ` G \\<subseteq> A\\<close>\n      by (auto intro!: exI[of _ \\<open>fst ` G\\<close>] simp add: FA_def eventually_finite_subsets_at_top)\n  qed\n  then show ?thesis\n    by (simp add: FA_def has_sum_def)\nqed\n\nlemma summable_on_Sigma:\n  fixes A :: \"'a set\" and B :: \"'a \\<Rightarrow> 'b set\"\n    and f :: \\<open>'a \\<Rightarrow> 'b \\<Rightarrow> 'c::{comm_monoid_add, t2_space, uniform_space}\\<close>\n  assumes plus_cont: \\<open>uniformly_continuous_on UNIV (\\<lambda>(x::'c,y). x+y)\\<close>\n  assumes summableAB: \"(\\<lambda>(x,y). f x y) summable_on (Sigma A B)\"\n  assumes summableB: \\<open>\\<And>x. x\\<in>A \\<Longrightarrow> (f x) summable_on (B x)\\<close>\n  shows \\<open>(\\<lambda>x. infsum (f x) (B x)) summable_on A\\<close>\nproof -\n  from summableAB obtain a where a: \\<open>has_sum (\\<lambda>(x,y). f x y) (Sigma A B) a\\<close>\n    using has_sum_infsum by blast\n  from summableB have b: \\<open>\\<And>x. x\\<in>A \\<Longrightarrow> has_sum (f x) (B x) (infsum (f x) (B x))\\<close>\n    by (auto intro!: has_sum_infsum)\n  show ?thesis\n    using plus_cont a b \n    by (auto intro: has_sum_Sigma[where f=\\<open>\\<lambda>(x,y). f x y\\<close>, simplified] simp: summable_on_def)\nqed\n\nlemma infsum_Sigma:\n  fixes A :: \"'a set\" and B :: \"'a \\<Rightarrow> 'b set\"\n    and f :: \\<open>'a \\<times> 'b \\<Rightarrow> 'c::{comm_monoid_add, t2_space, uniform_space}\\<close>\n  assumes plus_cont: \\<open>uniformly_continuous_on UNIV (\\<lambda>(x::'c,y). x+y)\\<close>\n  assumes summableAB: \"f summable_on (Sigma A B)\"\n  assumes summableB: \\<open>\\<And>x. x\\<in>A \\<Longrightarrow> (\\<lambda>y. f (x, y)) summable_on (B x)\\<close>\n  shows \"infsum f (Sigma A B) = infsum (\\<lambda>x. infsum (\\<lambda>y. f (x, y)) (B x)) A\"\nproof -\n  from summableAB have a: \\<open>has_sum f (Sigma A B) (infsum f (Sigma A B))\\<close>\n    using has_sum_infsum by blast\n  from summableB have b: \\<open>\\<And>x. x\\<in>A \\<Longrightarrow> has_sum (\\<lambda>y. f (x, y)) (B x) (infsum (\\<lambda>y. f (x, y)) (B x))\\<close>\n    by (auto intro!: has_sum_infsum)\n  show ?thesis\n    using plus_cont a b by (auto intro: infsumI[symmetric] has_sum_Sigma simp: summable_on_def)\nqed\n\nlemma infsum_Sigma':\n  fixes A :: \"'a set\" and B :: \"'a \\<Rightarrow> 'b set\"\n    and f :: \\<open>'a \\<Rightarrow> 'b \\<Rightarrow> 'c::{comm_monoid_add, t2_space, uniform_space}\\<close>\n  assumes plus_cont: \\<open>uniformly_continuous_on UNIV (\\<lambda>(x::'c,y). x+y)\\<close>\n  assumes summableAB: \"(\\<lambda>(x,y). f x y) summable_on (Sigma A B)\"\n  assumes summableB: \\<open>\\<And>x. x\\<in>A \\<Longrightarrow> (f x) summable_on (B x)\\<close>\n  shows \\<open>infsum (\\<lambda>x. infsum (f x) (B x)) A = infsum (\\<lambda>(x,y). f x y) (Sigma A B)\\<close>\n  using infsum_Sigma[of \\<open>\\<lambda>(x,y). f x y\\<close> A B]\n  using assms by auto\n\ntext \\<open>A special case of @{thm [source] infsum_Sigma} etc. for Banach spaces. It has less premises.\\<close>\nlemma\n  fixes A :: \"'a set\" and B :: \"'a \\<Rightarrow> 'b set\"\n    and f :: \\<open>'a \\<Rightarrow> 'b \\<Rightarrow> 'c::banach\\<close>\n  assumes [simp]: \"(\\<lambda>(x,y). f x y) summable_on (Sigma A B)\"\n  shows infsum_Sigma'_banach: \\<open>infsum (\\<lambda>x. infsum (f x) (B x)) A = infsum (\\<lambda>(x,y). f x y) (Sigma A B)\\<close> (is ?thesis1)\n    and summable_on_Sigma_banach: \\<open>(\\<lambda>x. infsum (f x) (B x)) summable_on A\\<close> (is ?thesis2)\nproof -\n  have [simp]: \\<open>(f x) summable_on (B x)\\<close> if \\<open>x \\<in> A\\<close> for x\n  proof -\n    from assms\n    have \\<open>(\\<lambda>(x,y). f x y) summable_on (Pair x ` B x)\\<close>\n      by (meson image_subset_iff summable_on_subset_banach mem_Sigma_iff that)\n    then have \\<open>((\\<lambda>(x,y). f x y) o Pair x) summable_on (B x)\\<close>\n      apply (rule_tac summable_on_reindex[THEN iffD1])\n      by (simp add: inj_on_def)\n    then show ?thesis\n      by (auto simp: o_def)\n  qed\n  show ?thesis1\n    apply (rule infsum_Sigma')\n    by auto\n  show ?thesis2\n    apply (rule summable_on_Sigma)\n    by auto\nqed\n\nlemma infsum_Sigma_banach:\n  fixes A :: \"'a set\" and B :: \"'a \\<Rightarrow> 'b set\"\n    and f :: \\<open>'a \\<times> 'b \\<Rightarrow> 'c::banach\\<close>\n  assumes [simp]: \"f summable_on (Sigma A B)\"\n  shows \\<open>infsum (\\<lambda>x. infsum (\\<lambda>y. f (x,y)) (B x)) A = infsum f (Sigma A B)\\<close>\n  using assms\n  by (subst infsum_Sigma'_banach) auto\n\nlemma infsum_swap:\n  fixes A :: \"'a set\" and B :: \"'b set\"\n  fixes f :: \"'a \\<Rightarrow> 'b \\<Rightarrow> 'c::{comm_monoid_add,t2_space,uniform_space}\"\n  assumes plus_cont: \\<open>uniformly_continuous_on UNIV (\\<lambda>(x::'c,y). x+y)\\<close>\n  assumes \\<open>(\\<lambda>(x, y). f x y) summable_on (A \\<times> B)\\<close>\n  assumes \\<open>\\<And>a. a\\<in>A \\<Longrightarrow> (f a) summable_on B\\<close>\n  assumes \\<open>\\<And>b. b\\<in>B \\<Longrightarrow> (\\<lambda>a. f a b) summable_on A\\<close>\n  shows \\<open>infsum (\\<lambda>x. infsum (\\<lambda>y. f x y) B) A = infsum (\\<lambda>y. infsum (\\<lambda>x. f x y) A) B\\<close>\nproof -\n  have [simp]: \\<open>(\\<lambda>(x, y). f y x) summable_on (B \\<times> A)\\<close>\n    apply (subst product_swap[symmetric])\n    apply (subst summable_on_reindex)\n    using assms by (auto simp: o_def)\n  have \\<open>infsum (\\<lambda>x. infsum (\\<lambda>y. f x y) B) A = infsum (\\<lambda>(x,y). f x y) (A \\<times> B)\\<close>\n    apply (subst infsum_Sigma)\n    using assms by auto\n  also have \\<open>\\<dots> = infsum (\\<lambda>(x,y). f y x) (B \\<times> A)\\<close>\n    apply (subst product_swap[symmetric])\n    apply (subst infsum_reindex)\n    using assms by (auto simp: o_def)\n  also have \\<open>\\<dots> = infsum (\\<lambda>y. infsum (\\<lambda>x. f x y) A) B\\<close>\n    apply (subst infsum_Sigma)\n    using assms by auto\n  finally show ?thesis .\nqed\n\nlemma infsum_swap_banach:\n  fixes A :: \"'a set\" and B :: \"'b set\"\n  fixes f :: \"'a \\<Rightarrow> 'b \\<Rightarrow> 'c::banach\"\n  assumes \\<open>(\\<lambda>(x, y). f x y) summable_on (A \\<times> B)\\<close>\n  shows \"infsum (\\<lambda>x. infsum (\\<lambda>y. f x y) B) A = infsum (\\<lambda>y. infsum (\\<lambda>x. f x y) A) B\"\nproof -\n  have [simp]: \\<open>(\\<lambda>(x, y). f y x) summable_on (B \\<times> A)\\<close>\n    apply (subst product_swap[symmetric])\n    apply (subst summable_on_reindex)\n    using assms by (auto simp: o_def)\n  have \\<open>infsum (\\<lambda>x. infsum (\\<lambda>y. f x y) B) A = infsum (\\<lambda>(x,y). f x y) (A \\<times> B)\\<close>\n    apply (subst infsum_Sigma'_banach)\n    using assms by auto\n  also have \\<open>\\<dots> = infsum (\\<lambda>(x,y). f y x) (B \\<times> A)\\<close>\n    apply (subst product_swap[symmetric])\n    apply (subst infsum_reindex)\n    using assms by (auto simp: o_def)\n  also have \\<open>\\<dots> = infsum (\\<lambda>y. infsum (\\<lambda>x. f x y) A) B\\<close>\n    apply (subst infsum_Sigma'_banach)\n    using assms by auto\n  finally show ?thesis .\nqed\n\nlemma nonneg_infsum_le_0D:\n  fixes f :: \"'a \\<Rightarrow> 'b::{topological_ab_group_add,ordered_ab_group_add,linorder_topology}\"\n  assumes \"infsum f A \\<le> 0\"\n    and abs_sum: \"f summable_on A\"\n    and nneg: \"\\<And>x. x \\<in> A \\<Longrightarrow> f x \\<ge> 0\"\n    and \"x \\<in> A\"\n  shows \"f x = 0\"\nproof (rule ccontr)\n  assume \\<open>f x \\<noteq> 0\\<close>\n  have ex: \\<open>f summable_on (A-{x})\\<close>\n    by (rule summable_on_cofin_subset) (use assms in auto)\n  have pos: \\<open>infsum f (A - {x}) \\<ge> 0\\<close>\n    by (rule infsum_nonneg) (use nneg in auto)\n\n  have [trans]: \\<open>x \\<ge> y \\<Longrightarrow> y > z \\<Longrightarrow> x > z\\<close> for x y z :: 'b by auto\n\n  have \\<open>infsum f A = infsum f (A-{x}) + infsum f {x}\\<close>\n    by (subst infsum_Un_disjoint[symmetric]) (use assms ex in \\<open>auto simp: insert_absorb\\<close>)\n  also have \\<open>\\<dots> \\<ge> infsum f {x}\\<close> (is \\<open>_ \\<ge> \\<dots>\\<close>)\n    using pos by (rule add_increasing) simp\n  also have \\<open>\\<dots> = f x\\<close> (is \\<open>_ = \\<dots>\\<close>)\n    by (subst infsum_finite) auto\n  also have \\<open>\\<dots> > 0\\<close>\n    using \\<open>f x \\<noteq> 0\\<close> assms(4) nneg by fastforce\n  finally show False\n    using assms by auto\nqed\n\nlemma nonneg_has_sum_le_0D:\n  fixes f :: \"'a \\<Rightarrow> 'b::{topological_ab_group_add,ordered_ab_group_add,linorder_topology}\"\n  assumes \"has_sum f A a\" \\<open>a \\<le> 0\\<close>\n    and nneg: \"\\<And>x. x \\<in> A \\<Longrightarrow> f x \\<ge> 0\"\n    and \"x \\<in> A\"\n  shows \"f x = 0\"\n  by (metis assms(1) assms(2) assms(4) infsumI nonneg_infsum_le_0D summable_on_def nneg)\n\nlemma has_sum_cmult_left:\n  fixes f :: \"'a \\<Rightarrow> 'b :: {topological_semigroup_mult, semiring_0}\"\n  assumes \\<open>has_sum f A a\\<close>\n  shows \"has_sum (\\<lambda>x. f x * c) A (a * c)\"\nproof -\n  from assms have \\<open>(sum f \\<longlongrightarrow> a) (finite_subsets_at_top A)\\<close>\n    using has_sum_def by blast\n  then have \\<open>((\\<lambda>F. sum f F * c) \\<longlongrightarrow> a * c) (finite_subsets_at_top A)\\<close>\n    by (simp add: tendsto_mult_right)\n  then have \\<open>(sum (\\<lambda>x. f x * c) \\<longlongrightarrow> a * c) (finite_subsets_at_top A)\\<close>\n    apply (rule tendsto_cong[THEN iffD1, rotated])\n    apply (rule eventually_finite_subsets_at_top_weakI)\n    using sum_distrib_right by blast\n  then show ?thesis\n    using infsumI has_sum_def by blast\nqed\n\nlemma infsum_cmult_left:\n  fixes f :: \"'a \\<Rightarrow> 'b :: {t2_space, topological_semigroup_mult, semiring_0}\"\n  assumes \\<open>c \\<noteq> 0 \\<Longrightarrow> f summable_on A\\<close>\n  shows \"infsum (\\<lambda>x. f x * c) A = infsum f A * c\"\nproof (cases \\<open>c=0\\<close>)\n  case True\n  then show ?thesis by auto\nnext\n  case False\n  then have \\<open>has_sum f A (infsum f A)\\<close>\n    by (simp add: assms)\n  then show ?thesis\n    by (auto intro!: infsumI has_sum_cmult_left)\nqed\n\nlemma summable_on_cmult_left:\n  fixes f :: \"'a \\<Rightarrow> 'b :: {t2_space, topological_semigroup_mult, semiring_0}\"\n  assumes \\<open>f summable_on A\\<close>\n  shows \"(\\<lambda>x. f x * c) summable_on A\"\n  using assms summable_on_def has_sum_cmult_left by blast\n\nlemma has_sum_cmult_right:\n  fixes f :: \"'a \\<Rightarrow> 'b :: {topological_semigroup_mult, semiring_0}\"\n  assumes \\<open>has_sum f A a\\<close>\n  shows \"has_sum (\\<lambda>x. c * f x) A (c * a)\"\nproof -\n  from assms have \\<open>(sum f \\<longlongrightarrow> a) (finite_subsets_at_top A)\\<close>\n    using has_sum_def by blast\n  then have \\<open>((\\<lambda>F. c * sum f F) \\<longlongrightarrow> c * a) (finite_subsets_at_top A)\\<close>\n    by (simp add: tendsto_mult_left)\n  then have \\<open>(sum (\\<lambda>x. c * f x) \\<longlongrightarrow> c * a) (finite_subsets_at_top A)\\<close>\n    apply (rule tendsto_cong[THEN iffD1, rotated])\n    apply (rule eventually_finite_subsets_at_top_weakI)\n    using sum_distrib_left by blast\n  then show ?thesis\n    using infsumI has_sum_def by blast\nqed\n\nlemma infsum_cmult_right:\n  fixes f :: \"'a \\<Rightarrow> 'b :: {t2_space, topological_semigroup_mult, semiring_0}\"\n  assumes \\<open>c \\<noteq> 0 \\<Longrightarrow> f summable_on A\\<close>\n  shows \\<open>infsum (\\<lambda>x. c * f x) A = c * infsum f A\\<close>\nproof (cases \\<open>c=0\\<close>)\n  case True\n  then show ?thesis by auto\nnext\n  case False\n  then have \\<open>has_sum f A (infsum f A)\\<close>\n    by (simp add: assms)\n  then show ?thesis\n    by (auto intro!: infsumI has_sum_cmult_right)\nqed\n\nlemma summable_on_cmult_right:\n  fixes f :: \"'a \\<Rightarrow> 'b :: {t2_space, topological_semigroup_mult, semiring_0}\"\n  assumes \\<open>f summable_on A\\<close>\n  shows \"(\\<lambda>x. c * f x) summable_on A\"\n  using assms summable_on_def has_sum_cmult_right by blast\n\nlemma summable_on_cmult_left':\n  fixes f :: \"'a \\<Rightarrow> 'b :: {t2_space, topological_semigroup_mult, division_ring}\"\n  assumes \\<open>c \\<noteq> 0\\<close>\n  shows \"(\\<lambda>x. f x * c) summable_on A \\<longleftrightarrow> f summable_on A\"\nproof\n  assume \\<open>f summable_on A\\<close>\n  then show \\<open>(\\<lambda>x. f x * c) summable_on A\\<close>\n    by (rule summable_on_cmult_left)\nnext\n  assume \\<open>(\\<lambda>x. f x * c) summable_on A\\<close>\n  then have \\<open>(\\<lambda>x. f x * c * inverse c) summable_on A\\<close>\n    by (rule summable_on_cmult_left)\n  then show \\<open>f summable_on A\\<close>\n    by (metis (no_types, lifting) assms summable_on_cong mult.assoc mult.right_neutral right_inverse)\nqed\n\nlemma summable_on_cmult_right':\n  fixes f :: \"'a \\<Rightarrow> 'b :: {t2_space, topological_semigroup_mult, division_ring}\"\n  assumes \\<open>c \\<noteq> 0\\<close>\n  shows \"(\\<lambda>x. c * f x) summable_on A \\<longleftrightarrow> f summable_on A\"\nproof\n  assume \\<open>f summable_on A\\<close>\n  then show \\<open>(\\<lambda>x. c * f x) summable_on A\\<close>\n    by (rule summable_on_cmult_right)\nnext\n  assume \\<open>(\\<lambda>x. c * f x) summable_on A\\<close>\n  then have \\<open>(\\<lambda>x. inverse c * (c * f x)) summable_on A\\<close>\n    by (rule summable_on_cmult_right)\n  then show \\<open>f summable_on A\\<close>\n    by (metis (no_types, lifting) assms summable_on_cong left_inverse mult.assoc mult.left_neutral)\nqed\n\nlemma infsum_cmult_left':\n  fixes f :: \"'a \\<Rightarrow> 'b :: {t2_space, topological_semigroup_mult, division_ring}\"\n  shows \"infsum (\\<lambda>x. f x * c) A = infsum f A * c\"\nproof (cases \\<open>c \\<noteq> 0 \\<longrightarrow> f summable_on A\\<close>)\n  case True\n  then show ?thesis\n    apply (rule_tac infsum_cmult_left) by auto\nnext\n  case False\n  note asm = False\n  then show ?thesis\n  proof (cases \\<open>c=0\\<close>)\n    case True\n    then show ?thesis by auto\n  next\n    case False\n    with asm have nex: \\<open>\\<not> f summable_on A\\<close>\n      by simp\n    moreover have nex': \\<open>\\<not> (\\<lambda>x. f x * c) summable_on A\\<close>\n      using asm False apply (subst summable_on_cmult_left') by auto\n    ultimately show ?thesis\n      unfolding infsum_def by simp\n  qed\nqed\n\nlemma infsum_cmult_right':\n  fixes f :: \"'a \\<Rightarrow> 'b :: {t2_space,topological_semigroup_mult,division_ring}\"\n  shows \"infsum (\\<lambda>x. c * f x) A = c * infsum f A\"\nproof (cases \\<open>c \\<noteq> 0 \\<longrightarrow> f summable_on A\\<close>)\n  case True\n  then show ?thesis\n    apply (rule_tac infsum_cmult_right) by auto\nnext\n  case False\n  note asm = False\n  then show ?thesis\n  proof (cases \\<open>c=0\\<close>)\n    case True\n    then show ?thesis by auto\n  next\n    case False\n    with asm have nex: \\<open>\\<not> f summable_on A\\<close>\n      by simp\n    moreover have nex': \\<open>\\<not> (\\<lambda>x. c * f x) summable_on A\\<close>\n      using asm False apply (subst summable_on_cmult_right') by auto\n    ultimately show ?thesis\n      unfolding infsum_def by simp\n  qed\nqed\n\n\nlemma has_sum_constant[simp]:\n  assumes \\<open>finite F\\<close>\n  shows \\<open>has_sum (\\<lambda>_. c) F (of_nat (card F) * c)\\<close>\n  by (metis assms has_sum_finite sum_constant)\n\nlemma infsum_constant[simp]:\n  assumes \\<open>finite F\\<close>\n  shows \\<open>infsum (\\<lambda>_. c) F = of_nat (card F) * c\\<close>\n  apply (subst infsum_finite[OF assms]) by simp\n\nlemma infsum_diverge_constant:\n  \\<comment> \\<open>This probably does not really need all of \\<^class>\\<open>archimedean_field\\<close> but Isabelle/HOL\n       has no type class such as, e.g., \"archimedean ring\".\\<close>\n  fixes c :: \\<open>'a::{archimedean_field, comm_monoid_add, linorder_topology, topological_semigroup_mult}\\<close>\n  assumes \\<open>infinite A\\<close> and \\<open>c \\<noteq> 0\\<close>\n  shows \\<open>\\<not> (\\<lambda>_. c) summable_on A\\<close>\nproof (rule notI)\n  assume \\<open>(\\<lambda>_. c) summable_on A\\<close>\n  then have \\<open>(\\<lambda>_. inverse c * c) summable_on A\\<close>\n    by (rule summable_on_cmult_right)\n  then have [simp]: \\<open>(\\<lambda>_. 1::'a) summable_on A\\<close>\n    using assms by auto\n  have \\<open>infsum (\\<lambda>_. 1) A \\<ge> d\\<close> for d :: 'a\n  proof -\n    obtain n :: nat where \\<open>of_nat n \\<ge> d\\<close>\n      by (meson real_arch_simple)\n    from assms\n    obtain F where \\<open>F \\<subseteq> A\\<close> and \\<open>finite F\\<close> and \\<open>card F = n\\<close>\n      by (meson infinite_arbitrarily_large)\n    note \\<open>d \\<le> of_nat n\\<close>\n    also have \\<open>of_nat n = infsum (\\<lambda>_. 1::'a) F\\<close>\n      by (simp add: \\<open>card F = n\\<close> \\<open>finite F\\<close>)\n    also have \\<open>\\<dots> \\<le> infsum (\\<lambda>_. 1::'a) A\\<close>\n      apply (rule infsum_mono_neutral)\n      using \\<open>finite F\\<close> \\<open>F \\<subseteq> A\\<close> by auto\n    finally show ?thesis .\n  qed\n  then show False\n    by (meson linordered_field_no_ub not_less)\nqed\n\nlemma has_sum_constant_archimedean[simp]:\n  \\<comment> \\<open>This probably does not really need all of \\<^class>\\<open>archimedean_field\\<close> but Isabelle/HOL\n       has no type class such as, e.g., \"archimedean ring\".\\<close>\n  fixes c :: \\<open>'a::{archimedean_field, comm_monoid_add, linorder_topology, topological_semigroup_mult}\\<close>\n  shows \\<open>infsum (\\<lambda>_. c) A = of_nat (card A) * c\\<close>\n  apply (cases \\<open>finite A\\<close>)\n   apply simp\n  apply (cases \\<open>c = 0\\<close>)\n   apply simp\n  by (simp add: infsum_diverge_constant infsum_not_exists)\n\nlemma has_sum_uminus:\n  fixes f :: \\<open>'a \\<Rightarrow> 'b::topological_ab_group_add\\<close>\n  shows \\<open>has_sum (\\<lambda>x. - f x) A a \\<longleftrightarrow> has_sum f A (- a)\\<close>\n  by (auto simp add: sum_negf[abs_def] tendsto_minus_cancel_left has_sum_def)\n\nlemma summable_on_uminus:\n  fixes f :: \\<open>'a \\<Rightarrow> 'b::topological_ab_group_add\\<close>\n  shows\\<open>(\\<lambda>x. - f x) summable_on A \\<longleftrightarrow> f summable_on A\\<close>\n  by (metis summable_on_def has_sum_uminus verit_minus_simplify(4))\n\nlemma infsum_uminus:\n  fixes f :: \\<open>'a \\<Rightarrow> 'b::{topological_ab_group_add, t2_space}\\<close>\n  shows \\<open>infsum (\\<lambda>x. - f x) A = - infsum f A\\<close>\n  by (metis (full_types) add.inverse_inverse add.inverse_neutral infsumI infsum_def has_sum_infsum has_sum_uminus)\n\nlemma has_sum_le_finite_sums:\n  fixes a :: \\<open>'a::{comm_monoid_add,topological_space,linorder_topology}\\<close>\n  assumes \\<open>has_sum f A a\\<close>\n  assumes \\<open>\\<And>F. finite F \\<Longrightarrow> F \\<subseteq> A \\<Longrightarrow> sum f F \\<le> b\\<close>\n  shows \\<open>a \\<le> b\\<close>\nproof -\n  from assms(1)\n  have 1: \\<open>(sum f \\<longlongrightarrow> a) (finite_subsets_at_top A)\\<close>\n    unfolding has_sum_def .\n  from assms(2)\n  have 2: \\<open>\\<forall>\\<^sub>F F in finite_subsets_at_top A. sum f F \\<le> b\\<close>\n    by (rule_tac eventually_finite_subsets_at_top_weakI)\n  show \\<open>a \\<le> b\\<close>\n    using _ _ 1 2\n    apply (rule tendsto_le[where f=\\<open>\\<lambda>_. b\\<close>])\n    by auto\nqed\n\nlemma infsum_le_finite_sums:\n  fixes b :: \\<open>'a::{comm_monoid_add,topological_space,linorder_topology}\\<close>\n  assumes \\<open>f summable_on A\\<close>\n  assumes \\<open>\\<And>F. finite F \\<Longrightarrow> F \\<subseteq> A \\<Longrightarrow> sum f F \\<le> b\\<close>\n  shows \\<open>infsum f A \\<le> b\\<close>\n  by (meson assms(1) assms(2) has_sum_infsum has_sum_le_finite_sums)\n\n\nlemma summable_on_scaleR_left [intro]:\n  fixes c :: \\<open>'a :: real_normed_vector\\<close>\n  assumes \"c \\<noteq> 0 \\<Longrightarrow> f summable_on A\"\n  shows   \"(\\<lambda>x. f x *\\<^sub>R c) summable_on A\"\n  apply (cases \\<open>c \\<noteq> 0\\<close>)\n   apply (subst asm_rl[of \\<open>(\\<lambda>x. f x *\\<^sub>R c) = (\\<lambda>y. y *\\<^sub>R c) o f\\<close>], simp add: o_def)\n   apply (rule summable_on_comm_additive)\n  using assms by (auto simp add: scaleR_left.additive_axioms)\n\n\nlemma summable_on_scaleR_right [intro]:\n  fixes f :: \\<open>'a \\<Rightarrow> 'b :: real_normed_vector\\<close>\n  assumes \"c \\<noteq> 0 \\<Longrightarrow> f summable_on A\"\n  shows   \"(\\<lambda>x. c *\\<^sub>R f x) summable_on A\"\n  apply (cases \\<open>c \\<noteq> 0\\<close>)\n   apply (subst asm_rl[of \\<open>(\\<lambda>x. c *\\<^sub>R f x) = (\\<lambda>y. c *\\<^sub>R y) o f\\<close>], simp add: o_def)\n   apply (rule summable_on_comm_additive)\n  using assms by (auto simp add: scaleR_right.additive_axioms)\n\nlemma infsum_scaleR_left:\n  fixes c :: \\<open>'a :: real_normed_vector\\<close>\n  assumes \"c \\<noteq> 0 \\<Longrightarrow> f summable_on A\"\n  shows   \"infsum (\\<lambda>x. f x *\\<^sub>R c) A = infsum f A *\\<^sub>R c\"\n  apply (cases \\<open>c \\<noteq> 0\\<close>)\n   apply (subst asm_rl[of \\<open>(\\<lambda>x. f x *\\<^sub>R c) = (\\<lambda>y. y *\\<^sub>R c) o f\\<close>], simp add: o_def)\n   apply (rule infsum_comm_additive)\n  using assms by (auto simp add: scaleR_left.additive_axioms)\n\nlemma infsum_scaleR_right:\n  fixes f :: \\<open>'a \\<Rightarrow> 'b :: real_normed_vector\\<close>\n  shows   \"infsum (\\<lambda>x. c *\\<^sub>R f x) A = c *\\<^sub>R infsum f A\"\nproof -\n  consider (summable) \\<open>f summable_on A\\<close> | (c0) \\<open>c = 0\\<close> | (not_summable) \\<open>\\<not> f summable_on A\\<close> \\<open>c \\<noteq> 0\\<close>\n    by auto\n  then show ?thesis\n  proof cases\n    case summable\n    then show ?thesis\n      apply (subst asm_rl[of \\<open>(\\<lambda>x. c *\\<^sub>R f x) = (\\<lambda>y. c *\\<^sub>R y) o f\\<close>], simp add: o_def)\n      apply (rule infsum_comm_additive)\n      using summable by (auto simp add: scaleR_right.additive_axioms)\n  next\n    case c0\n    then show ?thesis by auto\n  next\n    case not_summable\n    have \\<open>\\<not> (\\<lambda>x. c *\\<^sub>R f x) summable_on A\\<close>\n    proof (rule notI)\n      assume \\<open>(\\<lambda>x. c *\\<^sub>R f x) summable_on A\\<close>\n      then have \\<open>(\\<lambda>x. inverse c *\\<^sub>R c *\\<^sub>R f x) summable_on A\\<close>\n        using summable_on_scaleR_right by blast\n      then have \\<open>f summable_on A\\<close>\n        using not_summable by auto\n      with not_summable show False\n        by simp\n    qed\n    then show ?thesis\n      by (simp add: infsum_not_exists not_summable(1)) \n  qed\nqed\n\n\nlemma infsum_Un_Int:\n  fixes f :: \"'a \\<Rightarrow> 'b::{topological_ab_group_add, t2_space}\"\n  assumes [simp]: \"f summable_on A - B\" \"f summable_on B - A\" \\<open>f summable_on A \\<inter> B\\<close>\n  shows   \"infsum f (A \\<union> B) = infsum f A + infsum f B - infsum f (A \\<inter> B)\"\nproof -\n  have [simp]: \\<open>f summable_on A\\<close>\n    apply (subst asm_rl[of \\<open>A = (A-B) \\<union> (A\\<inter>B)\\<close>]) apply auto[1]\n    apply (rule summable_on_Un_disjoint)\n    by auto\n  have \\<open>infsum f (A \\<union> B) = infsum f A + infsum f (B - A)\\<close>\n    apply (subst infsum_Un_disjoint[symmetric])\n    by auto\n  moreover have \\<open>infsum f (B - A \\<union> A \\<inter> B) = infsum f (B - A) + infsum f (A \\<inter> B)\\<close>\n    by (rule infsum_Un_disjoint) auto\n  moreover have \"B - A \\<union> A \\<inter> B = B\"\n    by blast\n  ultimately show ?thesis\n    by auto\nqed\n\nlemma inj_combinator':\n  assumes \"x \\<notin> F\"\n  shows \\<open>inj_on (\\<lambda>(g, y). g(x := y)) (Pi\\<^sub>E F B \\<times> B x)\\<close>\nproof -\n  have \"inj_on ((\\<lambda>(y, g). g(x := y)) \\<circ> prod.swap) (Pi\\<^sub>E F B \\<times> B x)\"\n    using inj_combinator[of x F B] assms by (intro comp_inj_on) (auto simp: product_swap)\n  thus ?thesis\n    by (simp add: o_def)\nqed\n\nlemma infsum_prod_PiE:\n  \\<comment> \\<open>See also \\<open>infsum_prod_PiE_abs\\<close> below with incomparable premises.\\<close>\n  fixes f :: \"'a \\<Rightarrow> 'b \\<Rightarrow> 'c :: {comm_monoid_mult, topological_semigroup_mult, division_ring, banach}\"\n  assumes finite: \"finite A\"\n  assumes \"\\<And>x. x \\<in> A \\<Longrightarrow> f x summable_on B x\"\n  assumes \"(\\<lambda>g. \\<Prod>x\\<in>A. f x (g x)) summable_on (PiE A B)\"\n  shows   \"infsum (\\<lambda>g. \\<Prod>x\\<in>A. f x (g x)) (PiE A B) = (\\<Prod>x\\<in>A. infsum (f x) (B x))\"\nproof (use finite assms(2-) in induction)\n  case empty\n  then show ?case \n    by auto\nnext\n  case (insert x F)\n  have pi: \\<open>Pi\\<^sub>E (insert x F) B = (\\<lambda>(g,y). g(x:=y)) ` (Pi\\<^sub>E F B \\<times> B x)\\<close>\n    unfolding PiE_insert_eq \n    by (subst swap_product [symmetric]) (simp add: image_image case_prod_unfold)\n  have prod: \\<open>(\\<Prod>x'\\<in>F. f x' ((p(x:=y)) x')) = (\\<Prod>x'\\<in>F. f x' (p x'))\\<close> for p y\n    by (rule prod.cong) (use insert.hyps in auto)\n  have inj: \\<open>inj_on (\\<lambda>(g, y). g(x := y)) (Pi\\<^sub>E F B \\<times> B x)\\<close>\n    using \\<open>x \\<notin> F\\<close> by (rule inj_combinator')\n\n  have summable1: \\<open>(\\<lambda>g. \\<Prod>x\\<in>insert x F. f x (g x)) summable_on Pi\\<^sub>E (insert x F) B\\<close>\n    using insert.prems(2) .\n  also have \\<open>Pi\\<^sub>E (insert x F) B = (\\<lambda>(g,y). g(x:=y)) ` (Pi\\<^sub>E F B \\<times> B x)\\<close>\n    by (simp only: pi)\n  also have \"(\\<lambda>g. \\<Prod>x\\<in>insert x F. f x (g x)) summable_on \\<dots> \\<longleftrightarrow>\n               ((\\<lambda>g. \\<Prod>x\\<in>insert x F. f x (g x)) \\<circ> (\\<lambda>(g,y). g(x:=y))) summable_on (Pi\\<^sub>E F B \\<times> B x)\"\n    using inj by (rule summable_on_reindex)\n  also have \"(\\<Prod>z\\<in>F. f z ((g(x := y)) z)) = (\\<Prod>z\\<in>F. f z (g z))\" for g y\n    using insert.hyps by (intro prod.cong) auto\n  hence \"((\\<lambda>g. \\<Prod>x\\<in>insert x F. f x (g x)) \\<circ> (\\<lambda>(g,y). g(x:=y))) =\n             (\\<lambda>(p, y). f x y * (\\<Prod>x'\\<in>F. f x' (p x')))\"\n    using insert.hyps by (auto simp: fun_eq_iff cong: prod.cong_simp)\n  finally have summable2: \\<open>(\\<lambda>(p, y). f x y * (\\<Prod>x'\\<in>F. f x' (p x'))) summable_on Pi\\<^sub>E F B \\<times> B x\\<close> .\n\n  then have \\<open>(\\<lambda>p. \\<Sum>\\<^sub>\\<infinity>y\\<in>B x. f x y * (\\<Prod>x'\\<in>F. f x' (p x'))) summable_on Pi\\<^sub>E F B\\<close>\n    by (rule summable_on_Sigma_banach)\n  then have \\<open>(\\<lambda>p. (\\<Sum>\\<^sub>\\<infinity>y\\<in>B x. f x y) * (\\<Prod>x'\\<in>F. f x' (p x'))) summable_on Pi\\<^sub>E F B\\<close>\n    apply (subst infsum_cmult_left[symmetric])\n    using insert.prems(1) by blast\n  then have summable3: \\<open>(\\<lambda>p. (\\<Prod>x'\\<in>F. f x' (p x'))) summable_on Pi\\<^sub>E F B\\<close> if \\<open>(\\<Sum>\\<^sub>\\<infinity>y\\<in>B x. f x y) \\<noteq> 0\\<close>\n    apply (subst (asm) summable_on_cmult_right')\n    using that by auto\n\n  have \\<open>(\\<Sum>\\<^sub>\\<infinity>g\\<in>Pi\\<^sub>E (insert x F) B. \\<Prod>x\\<in>insert x F. f x (g x))\n     = (\\<Sum>\\<^sub>\\<infinity>(p,y)\\<in>Pi\\<^sub>E F B \\<times> B x. \\<Prod>x'\\<in>insert x F. f x' ((p(x:=y)) x'))\\<close>\n    apply (subst pi)\n    apply (subst infsum_reindex)\n    using inj by (auto simp: o_def case_prod_unfold)\n  also have \\<open>\\<dots> = (\\<Sum>\\<^sub>\\<infinity>(p, y)\\<in>Pi\\<^sub>E F B \\<times> B x. f x y * (\\<Prod>x'\\<in>F. f x' ((p(x:=y)) x')))\\<close>\n    apply (subst prod.insert)\n    using insert by auto\n  also have \\<open>\\<dots> = (\\<Sum>\\<^sub>\\<infinity>(p, y)\\<in>Pi\\<^sub>E F B \\<times> B x. f x y * (\\<Prod>x'\\<in>F. f x' (p x')))\\<close>\n    apply (subst prod) by rule\n  also have \\<open>\\<dots> = (\\<Sum>\\<^sub>\\<infinity>p\\<in>Pi\\<^sub>E F B. \\<Sum>\\<^sub>\\<infinity>y\\<in>B x. f x y * (\\<Prod>x'\\<in>F. f x' (p x')))\\<close>\n    apply (subst infsum_Sigma_banach[symmetric])\n    using summable2 apply blast\n    by fastforce\n  also have \\<open>\\<dots> = (\\<Sum>\\<^sub>\\<infinity>y\\<in>B x. f x y) * (\\<Sum>\\<^sub>\\<infinity>p\\<in>Pi\\<^sub>E F B. \\<Prod>x'\\<in>F. f x' (p x'))\\<close>\n    apply (subst infsum_cmult_left')\n    apply (subst infsum_cmult_right')\n    by (rule refl)\n  also have \\<open>\\<dots> = (\\<Prod>x\\<in>insert x F. infsum (f x) (B x))\\<close>\n    apply (subst prod.insert)\n    using \\<open>finite F\\<close> \\<open>x \\<notin> F\\<close> apply auto[2]\n    apply (cases \\<open>infsum (f x) (B x) = 0\\<close>)\n     apply simp\n    apply (subst insert.IH)\n      apply (simp add: insert.prems(1))\n     apply (rule summable3)\n    by auto\n  finally show ?case\n    by simp\nqed\n\nlemma infsum_prod_PiE_abs:\n  \\<comment> \\<open>See also @{thm [source] infsum_prod_PiE} above with incomparable premises.\\<close>\n  fixes f :: \"'a \\<Rightarrow> 'b \\<Rightarrow> 'c :: {banach, real_normed_div_algebra, comm_semiring_1}\"\n  assumes finite: \"finite A\"\n  assumes \"\\<And>x. x \\<in> A \\<Longrightarrow> f x abs_summable_on B x\"\n  shows   \"infsum (\\<lambda>g. \\<Prod>x\\<in>A. f x (g x)) (PiE A B) = (\\<Prod>x\\<in>A. infsum (f x) (B x))\"\nproof (use finite assms(2) in induction)\n  case empty\n  then show ?case \n    by auto\nnext\n  case (insert x F)\n  \n  have pi: \\<open>Pi\\<^sub>E (insert x F) B = (\\<lambda>(g,y). g(x:=y)) ` (Pi\\<^sub>E F B \\<times> B x)\\<close> for x F and B :: \"'a \\<Rightarrow> 'b set\"\n    unfolding PiE_insert_eq \n    by (subst swap_product [symmetric]) (simp add: image_image case_prod_unfold)\n  have prod: \\<open>(\\<Prod>x'\\<in>F. f x' ((p(x:=y)) x')) = (\\<Prod>x'\\<in>F. f x' (p x'))\\<close> for p y\n    by (rule prod.cong) (use insert.hyps in auto)\n  have inj: \\<open>inj_on (\\<lambda>(g, y). g(x := y)) (Pi\\<^sub>E F B \\<times> B x)\\<close>\n    using \\<open>x \\<notin> F\\<close> by (rule inj_combinator')\n\n  define s where \\<open>s x = infsum (\\<lambda>y. norm (f x y)) (B x)\\<close> for x\n\n  have *: \\<open>(\\<Sum>p\\<in>P. norm (\\<Prod>x\\<in>F. f x (p x))) \\<le> prod s F\\<close> \n    if P: \\<open>P \\<subseteq> Pi\\<^sub>E F B\\<close> and [simp]: \\<open>finite P\\<close> \\<open>finite F\\<close> \n      and sum: \\<open>\\<And>x. x \\<in> F \\<Longrightarrow> f x abs_summable_on B x\\<close> for P F\n  proof -\n    define B' where \\<open>B' x = {p x| p. p\\<in>P}\\<close> for x\n    have [simp]: \\<open>finite (B' x)\\<close> for x\n      using that by (auto simp: B'_def)\n    have [simp]: \\<open>finite (Pi\\<^sub>E F B')\\<close>\n      by (simp add: finite_PiE)\n    have [simp]: \\<open>P \\<subseteq> Pi\\<^sub>E F B'\\<close>\n      using that by (auto simp: B'_def)\n    have B'B: \\<open>B' x \\<subseteq> B x\\<close> if \\<open>x \\<in> F\\<close> for x\n      unfolding B'_def using P that \n      by auto\n    have s_bound: \\<open>(\\<Sum>y\\<in>B' x. norm (f x y)) \\<le> s x\\<close> if \\<open>x \\<in> F\\<close> for x\n      apply (simp_all add: s_def flip: infsum_finite)\n      apply (rule infsum_mono_neutral)\n      using that sum B'B by auto\n    have \\<open>(\\<Sum>p\\<in>P. norm (\\<Prod>x\\<in>F. f x (p x))) \\<le> (\\<Sum>p\\<in>Pi\\<^sub>E F B'. norm (\\<Prod>x\\<in>F. f x (p x)))\\<close>\n      apply (rule sum_mono2)\n      by auto\n    also have \\<open>\\<dots> = (\\<Sum>p\\<in>Pi\\<^sub>E F B'. \\<Prod>x\\<in>F. norm (f x (p x)))\\<close>\n      apply (subst prod_norm[symmetric])\n      by simp\n    also have \\<open>\\<dots> = (\\<Prod>x\\<in>F. \\<Sum>y\\<in>B' x. norm (f x y))\\<close>\n    proof (use \\<open>finite F\\<close> in induction)\n      case empty\n      then show ?case by simp\n    next\n      case (insert x F)\n      have aux: \\<open>a = b \\<Longrightarrow> c * a = c * b\\<close> for a b c :: real\n        by auto\n      have inj: \\<open>inj_on (\\<lambda>(g, y). g(x := y)) (Pi\\<^sub>E F B' \\<times> B' x)\\<close>\n        by (rule inj_combinator') (use insert.hyps in auto)\n      have \\<open>(\\<Sum>p\\<in>Pi\\<^sub>E (insert x F) B'. \\<Prod>x\\<in>insert x F. norm (f x (p x)))\n         =  (\\<Sum>(p,y)\\<in>Pi\\<^sub>E F B' \\<times> B' x. \\<Prod>x'\\<in>insert x F. norm (f x' ((p(x := y)) x')))\\<close>\n        apply (subst pi)\n        apply (subst sum.reindex)\n        using inj by (auto simp: case_prod_unfold)\n      also have \\<open>\\<dots> = (\\<Sum>(p,y)\\<in>Pi\\<^sub>E F B' \\<times> B' x. norm (f x y) * (\\<Prod>x'\\<in>F. norm (f x' ((p(x := y)) x'))))\\<close>\n        apply (subst prod.insert)\n        using insert.hyps by (auto simp: case_prod_unfold)\n      also have \\<open>\\<dots> = (\\<Sum>(p, y)\\<in>Pi\\<^sub>E F B' \\<times> B' x. norm (f x y) * (\\<Prod>x'\\<in>F. norm (f x' (p x'))))\\<close>\n        apply (rule sum.cong)\n         apply blast\n        unfolding case_prod_unfold\n        apply (rule aux)\n        apply (rule prod.cong)\n        using insert.hyps(2) by auto\n      also have \\<open>\\<dots> = (\\<Sum>y\\<in>B' x. norm (f x y)) * (\\<Sum>p\\<in>Pi\\<^sub>E F B'. \\<Prod>x'\\<in>F. norm (f x' (p x')))\\<close>\n        apply (subst sum_product)\n        apply (subst sum.swap)\n        apply (subst sum.cartesian_product)\n        by simp\n      also have \\<open>\\<dots> = (\\<Sum>y\\<in>B' x. norm (f x y)) * (\\<Prod>x\\<in>F. \\<Sum>y\\<in>B' x. norm (f x y))\\<close>\n        by (simp add: insert.IH)\n      also have \\<open>\\<dots> = (\\<Prod>x\\<in>insert x F. \\<Sum>y\\<in>B' x. norm (f x y))\\<close>\n        using insert.hyps(1) insert.hyps(2) by force\n      finally show ?case .\n    qed\n    also have \\<open>\\<dots> = (\\<Prod>x\\<in>F. \\<Sum>\\<^sub>\\<infinity>y\\<in>B' x. norm (f x y))\\<close>\n      by auto\n    also have \\<open>\\<dots> \\<le> (\\<Prod>x\\<in>F. s x)\\<close>\n      apply (rule prod_mono)\n      apply auto\n      apply (simp add: sum_nonneg)\n      using s_bound by presburger\n    finally show ?thesis .\n  qed\n  have \\<open>(\\<lambda>g. \\<Prod>x\\<in>insert x F. f x (g x)) abs_summable_on Pi\\<^sub>E (insert x F) B\\<close>\n    apply (rule nonneg_bdd_above_summable_on)\n     apply (simp; fail)\n    apply (rule bdd_aboveI[where M=\\<open>\\<Prod>x'\\<in>insert x F. s x'\\<close>])\n    using * insert.hyps insert.prems by blast\n\n  also have \\<open>Pi\\<^sub>E (insert x F) B = (\\<lambda>(g,y). g(x:=y)) ` (Pi\\<^sub>E F B \\<times> B x)\\<close>\n    by (simp only: pi)\n  also have \"(\\<lambda>g. \\<Prod>x\\<in>insert x F. f x (g x)) abs_summable_on \\<dots> \\<longleftrightarrow>\n               ((\\<lambda>g. \\<Prod>x\\<in>insert x F. f x (g x)) \\<circ> (\\<lambda>(g,y). g(x:=y))) abs_summable_on (Pi\\<^sub>E F B \\<times> B x)\"\n    using inj by (subst summable_on_reindex) (auto simp: o_def)\n  also have \"(\\<Prod>z\\<in>F. f z ((g(x := y)) z)) = (\\<Prod>z\\<in>F. f z (g z))\" for g y\n    using insert.hyps by (intro prod.cong) auto\n  hence \"((\\<lambda>g. \\<Prod>x\\<in>insert x F. f x (g x)) \\<circ> (\\<lambda>(g,y). g(x:=y))) =\n             (\\<lambda>(p, y). f x y * (\\<Prod>x'\\<in>F. f x' (p x')))\"\n    using insert.hyps by (auto simp: fun_eq_iff cong: prod.cong_simp)\n  finally have summable2: \\<open>(\\<lambda>(p, y). f x y * (\\<Prod>x'\\<in>F. f x' (p x'))) abs_summable_on Pi\\<^sub>E F B \\<times> B x\\<close> .\n\n  have \\<open>(\\<Sum>\\<^sub>\\<infinity>g\\<in>Pi\\<^sub>E (insert x F) B. \\<Prod>x\\<in>insert x F. f x (g x))\n     = (\\<Sum>\\<^sub>\\<infinity>(p,y)\\<in>Pi\\<^sub>E F B \\<times> B x. \\<Prod>x'\\<in>insert x F. f x' ((p(x:=y)) x'))\\<close>\n    apply (subst pi)\n    apply (subst infsum_reindex)\n    using inj by (auto simp: o_def case_prod_unfold)\n  also have \\<open>\\<dots> = (\\<Sum>\\<^sub>\\<infinity>(p, y)\\<in>Pi\\<^sub>E F B \\<times> B x. f x y * (\\<Prod>x'\\<in>F. f x' ((p(x:=y)) x')))\\<close>\n    apply (subst prod.insert)\n    using insert by auto\n  also have \\<open>\\<dots> = (\\<Sum>\\<^sub>\\<infinity>(p, y)\\<in>Pi\\<^sub>E F B \\<times> B x. f x y * (\\<Prod>x'\\<in>F. f x' (p x')))\\<close>\n    apply (subst prod) by rule\n  also have \\<open>\\<dots> = (\\<Sum>\\<^sub>\\<infinity>p\\<in>Pi\\<^sub>E F B. \\<Sum>\\<^sub>\\<infinity>y\\<in>B x. f x y * (\\<Prod>x'\\<in>F. f x' (p x')))\\<close>\n    apply (subst infsum_Sigma_banach[symmetric])\n    using summable2 abs_summable_summable apply blast\n    by fastforce\n  also have \\<open>\\<dots> = (\\<Sum>\\<^sub>\\<infinity>y\\<in>B x. f x y) * (\\<Sum>\\<^sub>\\<infinity>p\\<in>Pi\\<^sub>E F B. \\<Prod>x'\\<in>F. f x' (p x'))\\<close>\n    apply (subst infsum_cmult_left')\n    apply (subst infsum_cmult_right')\n    by (rule refl)\n  also have \\<open>\\<dots> = (\\<Prod>x\\<in>insert x F. infsum (f x) (B x))\\<close>\n    apply (subst prod.insert)\n    using \\<open>finite F\\<close> \\<open>x \\<notin> F\\<close> apply auto[2]\n    apply (cases \\<open>infsum (f x) (B x) = 0\\<close>)\n     apply (simp; fail)\n    apply (subst insert.IH)\n      apply (auto simp add: insert.prems(1))\n    done\n  finally show ?case\n    by simp\nqed\n\n\n\nsubsection \\<open>Absolute convergence\\<close>\n\nlemma abs_summable_countable:\n  assumes \\<open>f abs_summable_on A\\<close>\n  shows \\<open>countable {x\\<in>A. f x \\<noteq> 0}\\<close>\nproof -\n  have fin: \\<open>finite {x\\<in>A. norm (f x) \\<ge> t}\\<close> if \\<open>t > 0\\<close> for t\n  proof (rule ccontr)\n    assume *: \\<open>infinite {x \\<in> A. t \\<le> norm (f x)}\\<close>\n    have \\<open>infsum (\\<lambda>x. norm (f x)) A \\<ge> b\\<close> for b\n    proof -\n      obtain b' where b': \\<open>of_nat b' \\<ge> b / t\\<close>\n        by (meson real_arch_simple)\n      from *\n      obtain F where cardF: \\<open>card F \\<ge> b'\\<close> and \\<open>finite F\\<close> and F: \\<open>F \\<subseteq> {x \\<in> A. t \\<le> norm (f x)}\\<close>\n        by (meson finite_if_finite_subsets_card_bdd nle_le)\n      have \\<open>b \\<le> of_nat b' * t\\<close>\n        using b' \\<open>t > 0\\<close> by (simp add: field_simps split: if_splits)\n      also have \\<open>\\<dots> \\<le> of_nat (card F) * t\\<close>\n        by (simp add: cardF that)\n      also have \\<open>\\<dots> = sum (\\<lambda>x. t) F\\<close>\n        by simp\n      also have \\<open>\\<dots> \\<le> sum (\\<lambda>x. norm (f x)) F\\<close>\n        by (metis (mono_tags, lifting) F in_mono mem_Collect_eq sum_mono)\n      also have \\<open>\\<dots> = infsum (\\<lambda>x. norm (f x)) F\\<close>\n        using \\<open>finite F\\<close> by (rule infsum_finite[symmetric])\n      also have \\<open>\\<dots> \\<le> infsum (\\<lambda>x. norm (f x)) A\\<close>\n        by (rule infsum_mono_neutral) (use \\<open>finite F\\<close> assms F in auto)\n      finally show ?thesis .\n    qed\n    then show False\n      by (meson gt_ex linorder_not_less)\n  qed\n  have \\<open>countable (\\<Union>i\\<in>{1..}. {x\\<in>A. norm (f x) \\<ge> 1/of_nat i})\\<close>\n    by (rule countable_UN) (use fin in \\<open>auto intro!: countable_finite\\<close>)\n  also have \\<open>\\<dots> = {x\\<in>A. f x \\<noteq> 0}\\<close>\n  proof safe\n    fix x assume x: \"x \\<in> A\" \"f x \\<noteq> 0\"\n    define i where \"i = max 1 (nat (ceiling (1 / norm (f x))))\"\n    have \"i \\<ge> 1\"\n      by (simp add: i_def)\n    moreover have \"real i \\<ge> 1 / norm (f x)\"\n      unfolding i_def by linarith\n    hence \"1 / real i \\<le> norm (f x)\" using \\<open>f x \\<noteq> 0\\<close>\n      by (auto simp: divide_simps mult_ac)\n    ultimately show \"x \\<in> (\\<Union>i\\<in>{1..}. {x \\<in> A. 1 / real i \\<le> norm (f x)})\"\n      using \\<open>x \\<in> A\\<close> by auto\n  qed auto\n  finally show ?thesis .\nqed\n\n(* Logically belongs in the section about reals, but needed as a dependency here *)\nlemma summable_on_iff_abs_summable_on_real:\n  fixes f :: \\<open>'a \\<Rightarrow> real\\<close>\n  shows \\<open>f summable_on A \\<longleftrightarrow> f abs_summable_on A\\<close>\nproof (rule iffI)\n  assume \\<open>f summable_on A\\<close>\n  define n A\\<^sub>p A\\<^sub>n\n    where \\<open>n x = norm (f x)\\<close> and \\<open>A\\<^sub>p = {x\\<in>A. f x \\<ge> 0}\\<close> and \\<open>A\\<^sub>n = {x\\<in>A. f x < 0}\\<close> for x\n  have [simp]: \\<open>A\\<^sub>p \\<union> A\\<^sub>n = A\\<close> \\<open>A\\<^sub>p \\<inter> A\\<^sub>n = {}\\<close>\n    by (auto simp: A\\<^sub>p_def A\\<^sub>n_def)\n  from \\<open>f summable_on A\\<close> have [simp]: \\<open>f summable_on A\\<^sub>p\\<close> \\<open>f summable_on A\\<^sub>n\\<close>\n    using A\\<^sub>p_def A\\<^sub>n_def summable_on_subset_banach by fastforce+\n  then have [simp]: \\<open>n summable_on A\\<^sub>p\\<close>\n    apply (subst summable_on_cong[where g=f])\n    by (simp_all add: A\\<^sub>p_def n_def)\n  moreover have [simp]: \\<open>n summable_on A\\<^sub>n\\<close>\n    apply (subst summable_on_cong[where g=\\<open>\\<lambda>x. - f x\\<close>])\n     apply (simp add: A\\<^sub>n_def n_def[abs_def])\n    by (simp add: summable_on_uminus)\n  ultimately have [simp]: \\<open>n summable_on (A\\<^sub>p \\<union> A\\<^sub>n)\\<close>\n    apply (rule summable_on_Un_disjoint) by simp\n  then show \\<open>n summable_on A\\<close>\n    by simp\nnext\n  show \\<open>f abs_summable_on A \\<Longrightarrow> f summable_on A\\<close>\n    using abs_summable_summable by blast\nqed\n\nlemma abs_summable_on_Sigma_iff:\n  shows   \"f abs_summable_on Sigma A B \\<longleftrightarrow>\n             (\\<forall>x\\<in>A. (\\<lambda>y. f (x, y)) abs_summable_on B x) \\<and>\n             ((\\<lambda>x. infsum (\\<lambda>y. norm (f (x, y))) (B x)) abs_summable_on A)\"\nproof (intro iffI conjI ballI)\n  assume asm: \\<open>f abs_summable_on Sigma A B\\<close>\n  then have \\<open>(\\<lambda>x. infsum (\\<lambda>y. norm (f (x,y))) (B x)) summable_on A\\<close>\n    apply (rule_tac summable_on_Sigma_banach)\n    by (auto simp: case_prod_unfold)\n  then show \\<open>(\\<lambda>x. \\<Sum>\\<^sub>\\<infinity>y\\<in>B x. norm (f (x, y))) abs_summable_on A\\<close>\n    using summable_on_iff_abs_summable_on_real by force\n\n  show \\<open>(\\<lambda>y. f (x, y)) abs_summable_on B x\\<close> if \\<open>x \\<in> A\\<close> for x\n  proof -\n    from asm have \\<open>f abs_summable_on Pair x ` B x\\<close>\n      apply (rule summable_on_subset_banach)\n      using that by auto\n    then show ?thesis\n      apply (subst (asm) summable_on_reindex)\n      by (auto simp: o_def inj_on_def)\n  qed\nnext\n  assume asm: \\<open>(\\<forall>x\\<in>A. (\\<lambda>xa. f (x, xa)) abs_summable_on B x) \\<and>\n    (\\<lambda>x. \\<Sum>\\<^sub>\\<infinity>y\\<in>B x. norm (f (x, y))) abs_summable_on A\\<close>\n  have \\<open>(\\<Sum>xy\\<in>F. norm (f xy)) \\<le> (\\<Sum>\\<^sub>\\<infinity>x\\<in>A. \\<Sum>\\<^sub>\\<infinity>y\\<in>B x. norm (f (x, y)))\\<close>\n    if \\<open>F \\<subseteq> Sigma A B\\<close> and [simp]: \\<open>finite F\\<close> for F\n  proof -\n    have [simp]: \\<open>(SIGMA x:fst ` F. {y. (x, y) \\<in> F}) = F\\<close>\n      by (auto intro!: set_eqI simp add: Domain.DomainI fst_eq_Domain)\n    have [simp]: \\<open>finite {y. (x, y) \\<in> F}\\<close> for x\n      by (metis \\<open>finite F\\<close> Range.intros finite_Range finite_subset mem_Collect_eq subsetI)\n    have \\<open>(\\<Sum>xy\\<in>F. norm (f xy)) = (\\<Sum>x\\<in>fst ` F. \\<Sum>y\\<in>{y. (x,y)\\<in>F}. norm (f (x,y)))\\<close>\n      apply (subst sum.Sigma)\n      by auto\n    also have \\<open>\\<dots> = (\\<Sum>\\<^sub>\\<infinity>x\\<in>fst ` F. \\<Sum>\\<^sub>\\<infinity>y\\<in>{y. (x,y)\\<in>F}. norm (f (x,y)))\\<close>\n      apply (subst infsum_finite)\n      by auto\n    also have \\<open>\\<dots> \\<le> (\\<Sum>\\<^sub>\\<infinity>x\\<in>fst ` F. \\<Sum>\\<^sub>\\<infinity>y\\<in>B x. norm (f (x,y)))\\<close>\n      apply (rule infsum_mono)\n        apply (simp; fail)\n       apply (simp; fail)\n      apply (rule infsum_mono_neutral)\n      using asm that(1) by auto\n    also have \\<open>\\<dots> \\<le> (\\<Sum>\\<^sub>\\<infinity>x\\<in>A. \\<Sum>\\<^sub>\\<infinity>y\\<in>B x. norm (f (x,y)))\\<close>\n      by (rule infsum_mono_neutral) (use asm that(1) in \\<open>auto simp add: infsum_nonneg\\<close>)\n    finally show ?thesis .\n  qed\n  then show \\<open>f abs_summable_on Sigma A B\\<close>\n    by (intro nonneg_bdd_above_summable_on) (auto simp: bdd_above_def)\nqed\n\nlemma abs_summable_on_comparison_test:\n  assumes \"g abs_summable_on A\"\n  assumes \"\\<And>x. x \\<in> A \\<Longrightarrow> norm (f x) \\<le> norm (g x)\"\n  shows   \"f abs_summable_on A\"\nproof (rule nonneg_bdd_above_summable_on)\n  show \"bdd_above (sum (\\<lambda>x. norm (f x)) ` {F. F \\<subseteq> A \\<and> finite F})\"\n  proof (rule bdd_aboveI2)\n    fix F assume F: \"F \\<in> {F. F \\<subseteq> A \\<and> finite F}\"\n    have \\<open>sum (\\<lambda>x. norm (f x)) F \\<le> sum (\\<lambda>x. norm (g x)) F\\<close>\n      using assms F by (intro sum_mono) auto\n    also have \\<open>\\<dots> = infsum (\\<lambda>x. norm (g x)) F\\<close>\n      using F by simp\n    also have \\<open>\\<dots> \\<le> infsum (\\<lambda>x. norm (g x)) A\\<close>\n    proof (rule infsum_mono_neutral)\n      show \"g abs_summable_on F\"\n        by (rule summable_on_subset_banach[OF assms(1)]) (use F in auto)\n    qed (use F assms in auto)\n    finally show \"(\\<Sum>x\\<in>F. norm (f x)) \\<le> (\\<Sum>\\<^sub>\\<infinity>x\\<in>A. norm (g x))\" .\n  qed\nqed auto\n\nlemma abs_summable_iff_bdd_above:\n  fixes f :: \\<open>'a \\<Rightarrow> 'b::real_normed_vector\\<close>\n  shows \\<open>f abs_summable_on A \\<longleftrightarrow> bdd_above (sum (\\<lambda>x. norm (f x)) ` {F. F\\<subseteq>A \\<and> finite F})\\<close>\nproof (rule iffI)\n  assume \\<open>f abs_summable_on A\\<close>\n  show \\<open>bdd_above (sum (\\<lambda>x. norm (f x)) ` {F. F \\<subseteq> A \\<and> finite F})\\<close>\n  proof (rule bdd_aboveI2)\n    fix F assume F: \"F \\<in> {F. F \\<subseteq> A \\<and> finite F}\"\n    show \"(\\<Sum>x\\<in>F. norm (f x)) \\<le> (\\<Sum>\\<^sub>\\<infinity>x\\<in>A. norm (f x))\"\n      by (rule finite_sum_le_infsum) (use \\<open>f abs_summable_on A\\<close> F in auto)\n  qed\nnext\n  assume \\<open>bdd_above (sum (\\<lambda>x. norm (f x)) ` {F. F\\<subseteq>A \\<and> finite F})\\<close>\n  then show \\<open>f abs_summable_on A\\<close>\n    by (simp add: nonneg_bdd_above_summable_on)\nqed\n\nlemma abs_summable_product:\n  fixes x :: \"'a \\<Rightarrow> 'b::{real_normed_div_algebra,banach,second_countable_topology}\"\n  assumes x2_sum: \"(\\<lambda>i. (x i) * (x i)) abs_summable_on A\"\n    and y2_sum: \"(\\<lambda>i. (y i) * (y i)) abs_summable_on A\"\n  shows \"(\\<lambda>i. x i * y i) abs_summable_on A\"\nproof (rule nonneg_bdd_above_summable_on)\n  show \"bdd_above (sum (\\<lambda>xa. norm (x xa * y xa)) ` {F. F \\<subseteq> A \\<and> finite F})\"\n  proof (rule bdd_aboveI2)\n    fix F assume F: \\<open>F \\<in> {F. F \\<subseteq> A \\<and> finite F}\\<close>\n    then have r1: \"finite F\" and b4: \"F \\<subseteq> A\"\n      by auto\n  \n    have a1: \"(\\<Sum>\\<^sub>\\<infinity>i\\<in>F. norm (x i * x i)) \\<le> (\\<Sum>\\<^sub>\\<infinity>i\\<in>A. norm (x i * x i))\"\n      apply (rule infsum_mono_neutral)\n      using b4 r1 x2_sum by auto\n\n    have \"norm (x i * y i) \\<le> norm (x i * x i) + norm (y i * y i)\" for i\n      unfolding norm_mult by (smt mult_left_mono mult_nonneg_nonneg mult_right_mono norm_ge_zero)\n    hence \"(\\<Sum>i\\<in>F. norm (x i * y i)) \\<le> (\\<Sum>i\\<in>F. norm (x i * x i) + norm (y i * y i))\"\n      by (simp add: sum_mono)\n    also have \"\\<dots> = (\\<Sum>i\\<in>F. norm (x i * x i)) + (\\<Sum>i\\<in>F. norm (y i * y i))\"\n      by (simp add: sum.distrib)\n    also have \"\\<dots> = (\\<Sum>\\<^sub>\\<infinity>i\\<in>F. norm (x i * x i)) + (\\<Sum>\\<^sub>\\<infinity>i\\<in>F. norm (y i * y i))\"\n      by (simp add: \\<open>finite F\\<close>)\n    also have \"\\<dots> \\<le> (\\<Sum>\\<^sub>\\<infinity>i\\<in>A. norm (x i * x i)) + (\\<Sum>\\<^sub>\\<infinity>i\\<in>A. norm (y i * y i))\"\n      using F assms\n      by (intro add_mono infsum_mono2) auto\n    finally show \\<open>(\\<Sum>xa\\<in>F. norm (x xa * y xa)) \\<le> (\\<Sum>\\<^sub>\\<infinity>i\\<in>A. norm (x i * x i)) + (\\<Sum>\\<^sub>\\<infinity>i\\<in>A. norm (y i * y i))\\<close>\n      by simp\n  qed\nqed auto\n\nsubsection \\<open>Extended reals and nats\\<close>\n\nlemma summable_on_ennreal[simp]: \\<open>(f::_ \\<Rightarrow> ennreal) summable_on S\\<close>\n  by (rule nonneg_summable_on_complete) simp\n\nlemma summable_on_enat[simp]: \\<open>(f::_ \\<Rightarrow> enat) summable_on S\\<close>\n  by (rule nonneg_summable_on_complete) simp\n\nlemma has_sum_superconst_infinite_ennreal:\n  fixes f :: \\<open>'a \\<Rightarrow> ennreal\\<close>\n  assumes geqb: \\<open>\\<And>x. x \\<in> S \\<Longrightarrow> f x \\<ge> b\\<close>\n  assumes b: \\<open>b > 0\\<close>\n  assumes \\<open>infinite S\\<close>\n  shows \"has_sum f S \\<infinity>\"\nproof -\n  have \\<open>(sum f \\<longlongrightarrow> \\<infinity>) (finite_subsets_at_top S)\\<close>\n  proof (rule order_tendstoI[rotated], simp)\n    fix y :: ennreal assume \\<open>y < \\<infinity>\\<close>\n    then have \\<open>y / b < \\<infinity>\\<close>\n      by (metis b ennreal_divide_eq_top_iff gr_implies_not_zero infinity_ennreal_def top.not_eq_extremum)\n    then obtain F where \\<open>finite F\\<close> and \\<open>F \\<subseteq> S\\<close> and cardF: \\<open>card F > y / b\\<close>\n      using \\<open>infinite S\\<close>\n      by (metis ennreal_Ex_less_of_nat infinite_arbitrarily_large infinity_ennreal_def)\n    moreover have \\<open>sum f Y > y\\<close> if \\<open>finite Y\\<close> and \\<open>F \\<subseteq> Y\\<close> and \\<open>Y \\<subseteq> S\\<close> for Y\n    proof -\n      have \\<open>y < b * card F\\<close>\n        by (metis \\<open>y < \\<infinity>\\<close> b cardF divide_less_ennreal ennreal_mult_eq_top_iff gr_implies_not_zero infinity_ennreal_def mult.commute top.not_eq_extremum)\n      also have \\<open>\\<dots> \\<le> b * card Y\\<close>\n        by (meson b card_mono less_imp_le mult_left_mono of_nat_le_iff that(1) that(2))\n      also have \\<open>\\<dots> = sum (\\<lambda>_. b) Y\\<close>\n        by (simp add: mult.commute)\n      also have \\<open>\\<dots> \\<le> sum f Y\\<close>\n        using geqb by (meson subset_eq sum_mono that(3))\n      finally show ?thesis .\n    qed\n    ultimately show \\<open>\\<forall>\\<^sub>F x in finite_subsets_at_top S. y < sum f x\\<close>\n      unfolding eventually_finite_subsets_at_top \n      by auto\n  qed\n  then show ?thesis\n    by (simp add: has_sum_def)\nqed\n\nlemma infsum_superconst_infinite_ennreal:\n  fixes f :: \\<open>'a \\<Rightarrow> ennreal\\<close>\n  assumes \\<open>\\<And>x. x \\<in> S \\<Longrightarrow> f x \\<ge> b\\<close>\n  assumes \\<open>b > 0\\<close>\n  assumes \\<open>infinite S\\<close>\n  shows \"infsum f S = \\<infinity>\"\n  using assms infsumI has_sum_superconst_infinite_ennreal by blast\n\nlemma infsum_superconst_infinite_ereal:\n  fixes f :: \\<open>'a \\<Rightarrow> ereal\\<close>\n  assumes geqb: \\<open>\\<And>x. x \\<in> S \\<Longrightarrow> f x \\<ge> b\\<close>\n  assumes b: \\<open>b > 0\\<close>\n  assumes \\<open>infinite S\\<close>\n  shows \"infsum f S = \\<infinity>\"\nproof -\n  obtain b' where b': \\<open>e2ennreal b' = b\\<close> and \\<open>b' > 0\\<close>\n    using b by blast\n  have \"0 < e2ennreal b\"\n    using b' b\n    by (metis dual_order.refl enn2ereal_e2ennreal gr_zeroI order_less_le zero_ennreal.abs_eq)\n  hence *: \\<open>infsum (e2ennreal o f) S = \\<infinity>\\<close>\n    using assms b'\n    by (intro infsum_superconst_infinite_ennreal[where b=b']) (auto intro!: e2ennreal_mono)\n  have \\<open>infsum f S = infsum (enn2ereal o (e2ennreal o f)) S\\<close>\n    using geqb b by (intro infsum_cong) (fastforce simp: enn2ereal_e2ennreal)\n  also have \\<open>\\<dots> = enn2ereal \\<infinity>\\<close>\n    apply (subst infsum_comm_additive_general)\n    using * by (auto simp: continuous_at_enn2ereal)\n  also have \\<open>\\<dots> = \\<infinity>\\<close>\n    by simp\n  finally show ?thesis .\nqed\n\nlemma has_sum_superconst_infinite_ereal:\n  fixes f :: \\<open>'a \\<Rightarrow> ereal\\<close>\n  assumes \\<open>\\<And>x. x \\<in> S \\<Longrightarrow> f x \\<ge> b\\<close>\n  assumes \\<open>b > 0\\<close>\n  assumes \\<open>infinite S\\<close>\n  shows \"has_sum f S \\<infinity>\"\n  by (metis Infty_neq_0(1) assms infsum_def has_sum_infsum infsum_superconst_infinite_ereal)\n\nlemma infsum_superconst_infinite_enat:\n  fixes f :: \\<open>'a \\<Rightarrow> enat\\<close>\n  assumes geqb: \\<open>\\<And>x. x \\<in> S \\<Longrightarrow> f x \\<ge> b\\<close>\n  assumes b: \\<open>b > 0\\<close>\n  assumes \\<open>infinite S\\<close>\n  shows \"infsum f S = \\<infinity>\"\nproof -\n  have \\<open>ennreal_of_enat (infsum f S) = infsum (ennreal_of_enat o f) S\\<close>\n    apply (rule infsum_comm_additive_general[symmetric])\n    by auto\n  also have \\<open>\\<dots> = \\<infinity>\\<close>\n    by (metis assms(3) b comp_apply ennreal_of_enat_0 ennreal_of_enat_inj ennreal_of_enat_le_iff geqb infsum_superconst_infinite_ennreal not_gr_zero)\n  also have \\<open>\\<dots> = ennreal_of_enat \\<infinity>\\<close>\n    by simp\n  finally show ?thesis\n    by (rule ennreal_of_enat_inj[THEN iffD1])\nqed\n\nlemma has_sum_superconst_infinite_enat:\n  fixes f :: \\<open>'a \\<Rightarrow> enat\\<close>\n  assumes \\<open>\\<And>x. x \\<in> S \\<Longrightarrow> f x \\<ge> b\\<close>\n  assumes \\<open>b > 0\\<close>\n  assumes \\<open>infinite S\\<close>\n  shows \"has_sum f S \\<infinity>\"\n  by (metis assms i0_lb has_sum_infsum infsum_superconst_infinite_enat nonneg_summable_on_complete)\n\ntext \\<open>This lemma helps to relate a real-valued infsum to a supremum over extended nonnegative reals.\\<close>\n\nlemma infsum_nonneg_is_SUPREMUM_ennreal:\n  fixes f :: \"'a \\<Rightarrow> real\"\n  assumes summable: \"f summable_on A\"\n    and fnn: \"\\<And>x. x\\<in>A \\<Longrightarrow> f x \\<ge> 0\"\n  shows \"ennreal (infsum f A) = (SUP F\\<in>{F. finite F \\<and> F \\<subseteq> A}. (ennreal (sum f F)))\"\nproof -\n  have \\<open>ennreal (infsum f A) = infsum (ennreal o f) A\\<close>\n    apply (rule infsum_comm_additive_general[symmetric])\n    apply (subst sum_ennreal[symmetric])\n    using assms by auto\n  also have \\<open>\\<dots> = (SUP F\\<in>{F. finite F \\<and> F \\<subseteq> A}. (ennreal (sum f F)))\\<close>\n    apply (subst nonneg_infsum_complete, simp)\n    apply (rule SUP_cong, blast)\n    apply (subst sum_ennreal[symmetric])\n    using fnn by auto\n  finally show ?thesis .\nqed\n\ntext \\<open>This lemma helps to related a real-valued infsum to a supremum over extended reals.\\<close>\n\nlemma infsum_nonneg_is_SUPREMUM_ereal:\n  fixes f :: \"'a \\<Rightarrow> real\"\n  assumes summable: \"f summable_on A\"\n    and fnn: \"\\<And>x. x\\<in>A \\<Longrightarrow> f x \\<ge> 0\"\n  shows \"ereal (infsum f A) = (SUP F\\<in>{F. finite F \\<and> F \\<subseteq> A}. (ereal (sum f F)))\"\nproof -\n  have \\<open>ereal (infsum f A) = infsum (ereal o f) A\\<close>\n    apply (rule infsum_comm_additive_general[symmetric])\n    using assms by auto\n  also have \\<open>\\<dots> = (SUP F\\<in>{F. finite F \\<and> F \\<subseteq> A}. (ereal (sum f F)))\\<close>\n    by (subst nonneg_infsum_complete) (simp_all add: assms)\n  finally show ?thesis .\nqed\n\n\nsubsection \\<open>Real numbers\\<close>\n\ntext \\<open>Most lemmas in the general property section already apply to real numbers.\n      A few ones that are specific to reals are given here.\\<close>\n\nlemma infsum_nonneg_is_SUPREMUM_real:\n  fixes f :: \"'a \\<Rightarrow> real\"\n  assumes summable: \"f summable_on A\"\n    and fnn: \"\\<And>x. x\\<in>A \\<Longrightarrow> f x \\<ge> 0\"\n  shows \"infsum f A = (SUP F\\<in>{F. finite F \\<and> F \\<subseteq> A}. (sum f F))\"\nproof -\n  have \"ereal (infsum f A) = (SUP F\\<in>{F. finite F \\<and> F \\<subseteq> A}. (ereal (sum f F)))\"\n    using assms by (rule infsum_nonneg_is_SUPREMUM_ereal)\n  also have \"\\<dots> = ereal (SUP F\\<in>{F. finite F \\<and> F \\<subseteq> A}. (sum f F))\"\n  proof (subst ereal_SUP)\n    show \"\\<bar>SUP a\\<in>{F. finite F \\<and> F \\<subseteq> A}. ereal (sum f a)\\<bar> \\<noteq> \\<infinity>\"\n      using calculation by fastforce      \n    show \"(SUP F\\<in>{F. finite F \\<and> F \\<subseteq> A}. ereal (sum f F)) = (SUP a\\<in>{F. finite F \\<and> F \\<subseteq> A}. ereal (sum f a))\"\n      by simp      \n  qed\n  finally show ?thesis by simp\nqed\n\n\nlemma has_sum_nonneg_SUPREMUM_real:\n  fixes f :: \"'a \\<Rightarrow> real\"\n  assumes \"f summable_on A\" and \"\\<And>x. x\\<in>A \\<Longrightarrow> f x \\<ge> 0\"\n  shows \"has_sum f A (SUP F\\<in>{F. finite F \\<and> F \\<subseteq> A}. (sum f F))\"\n  by (metis (mono_tags, lifting) assms has_sum_infsum infsum_nonneg_is_SUPREMUM_real)\n\nlemma summable_countable_real:\n  fixes f :: \\<open>'a \\<Rightarrow> real\\<close>\n  assumes \\<open>f summable_on A\\<close>\n  shows \\<open>countable {x\\<in>A. f x \\<noteq> 0}\\<close>\n  using abs_summable_countable assms summable_on_iff_abs_summable_on_real by blast\n\nsubsection \\<open>Complex numbers\\<close>\n\nlemma has_sum_cnj_iff[simp]: \n  fixes f :: \\<open>'a \\<Rightarrow> complex\\<close>\n  shows \\<open>has_sum (\\<lambda>x. cnj (f x)) M (cnj a) \\<longleftrightarrow> has_sum f M a\\<close>\n  by (simp add: has_sum_def lim_cnj del: cnj_sum add: cnj_sum[symmetric, abs_def, of f])\n\nlemma summable_on_cnj_iff[simp]:\n  \"(\\<lambda>i. cnj (f i)) summable_on A \\<longleftrightarrow> f summable_on A\"\n  by (metis complex_cnj_cnj summable_on_def has_sum_cnj_iff)\n\nlemma infsum_cnj[simp]: \\<open>infsum (\\<lambda>x. cnj (f x)) M = cnj (infsum f M)\\<close>\n  by (metis complex_cnj_zero infsumI has_sum_cnj_iff infsum_def summable_on_cnj_iff has_sum_infsum)\n\nlemma infsum_Re:\n  assumes \"f summable_on M\"\n  shows \"infsum (\\<lambda>x. Re (f x)) M = Re (infsum f M)\"\n  apply (rule infsum_comm_additive[where f=Re, unfolded o_def])\n  using assms by (auto intro!: additive.intro)\n\nlemma has_sum_Re:\n  assumes \"has_sum f M a\"\n  shows \"has_sum (\\<lambda>x. Re (f x)) M (Re a)\"\n  apply (rule has_sum_comm_additive[where f=Re, unfolded o_def])\n  using assms by (auto intro!: additive.intro tendsto_Re)\n\nlemma summable_on_Re: \n  assumes \"f summable_on M\"\n  shows \"(\\<lambda>x. Re (f x)) summable_on M\"\n  apply (rule summable_on_comm_additive[where f=Re, unfolded o_def])\n  using assms by (auto intro!: additive.intro)\n\nlemma infsum_Im: \n  assumes \"f summable_on M\"\n  shows \"infsum (\\<lambda>x. Im (f x)) M = Im (infsum f M)\"\n  apply (rule infsum_comm_additive[where f=Im, unfolded o_def])\n  using assms by (auto intro!: additive.intro)\n\nlemma has_sum_Im:\n  assumes \"has_sum f M a\"\n  shows \"has_sum (\\<lambda>x. Im (f x)) M (Im a)\"\n  apply (rule has_sum_comm_additive[where f=Im, unfolded o_def])\n  using assms by (auto intro!: additive.intro tendsto_Im)\n\nlemma summable_on_Im: \n  assumes \"f summable_on M\"\n  shows \"(\\<lambda>x. Im (f x)) summable_on M\"\n  apply (rule summable_on_comm_additive[where f=Im, unfolded o_def])\n  using assms by (auto intro!: additive.intro)\n\nlemma nonneg_infsum_le_0D_complex:\n  fixes f :: \"'a \\<Rightarrow> complex\"\n  assumes \"infsum f A \\<le> 0\"\n    and abs_sum: \"f summable_on A\"\n    and nneg: \"\\<And>x. x \\<in> A \\<Longrightarrow> f x \\<ge> 0\"\n    and \"x \\<in> A\"\n  shows \"f x = 0\"\nproof -\n  have \\<open>Im (f x) = 0\\<close>\n    apply (rule nonneg_infsum_le_0D[where A=A])\n    using assms\n    by (auto simp add: infsum_Im summable_on_Im less_eq_complex_def)\n  moreover have \\<open>Re (f x) = 0\\<close>\n    apply (rule nonneg_infsum_le_0D[where A=A])\n    using assms by (auto simp add: summable_on_Re infsum_Re less_eq_complex_def)\n  ultimately show ?thesis\n    by (simp add: complex_eqI)\nqed\n\nlemma nonneg_has_sum_le_0D_complex:\n  fixes f :: \"'a \\<Rightarrow> complex\"\n  assumes \"has_sum f A a\" and \\<open>a \\<le> 0\\<close>\n    and \"\\<And>x. x \\<in> A \\<Longrightarrow> f x \\<ge> 0\" and \"x \\<in> A\"\n  shows \"f x = 0\"\n  by (metis assms infsumI nonneg_infsum_le_0D_complex summable_on_def)\n\ntext \\<open>The lemma @{thm [source] infsum_mono_neutral} above applies to various linear ordered monoids such as the reals but not to the complex numbers.\n      Thus we have a separate corollary for those:\\<close>\n\nlemma infsum_mono_neutral_complex:\n  fixes f :: \"'a \\<Rightarrow> complex\"\n  assumes [simp]: \"f summable_on A\"\n    and [simp]: \"g summable_on B\"\n  assumes \\<open>\\<And>x. x \\<in> A\\<inter>B \\<Longrightarrow> f x \\<le> g x\\<close>\n  assumes \\<open>\\<And>x. x \\<in> A-B \\<Longrightarrow> f x \\<le> 0\\<close>\n  assumes \\<open>\\<And>x. x \\<in> B-A \\<Longrightarrow> g x \\<ge> 0\\<close>\n  shows \\<open>infsum f A \\<le> infsum g B\\<close>\nproof -\n  have \\<open>infsum (\\<lambda>x. Re (f x)) A \\<le> infsum (\\<lambda>x. Re (g x)) B\\<close>\n    apply (rule infsum_mono_neutral)\n    using assms(3-5) by (auto simp add: summable_on_Re less_eq_complex_def)\n  then have Re: \\<open>Re (infsum f A) \\<le> Re (infsum g B)\\<close>\n    by (metis assms(1-2) infsum_Re)\n  have \\<open>infsum (\\<lambda>x. Im (f x)) A = infsum (\\<lambda>x. Im (g x)) B\\<close>\n    apply (rule infsum_cong_neutral)\n    using assms(3-5) by (auto simp add: summable_on_Re less_eq_complex_def)\n  then have Im: \\<open>Im (infsum f A) = Im (infsum g B)\\<close>\n    by (metis assms(1-2) infsum_Im)\n  from Re Im show ?thesis\n    by (auto simp: less_eq_complex_def)\nqed\n\nlemma infsum_mono_complex:\n  \\<comment> \\<open>For \\<^typ>\\<open>real\\<close>, @{thm [source] infsum_mono} can be used. \n      But \\<^typ>\\<open>complex\\<close> does not have the right typeclass.\\<close>\n  fixes f g :: \"'a \\<Rightarrow> complex\"\n  assumes f_sum: \"f summable_on A\" and g_sum: \"g summable_on A\"\n  assumes leq: \"\\<And>x. x \\<in> A \\<Longrightarrow> f x \\<le> g x\"\n  shows   \"infsum f A \\<le> infsum g A\"\n  by (metis DiffE IntD1 f_sum g_sum infsum_mono_neutral_complex leq)\n\n\nlemma infsum_nonneg_complex:\n  fixes f :: \"'a \\<Rightarrow> complex\"\n  assumes \"f summable_on M\"\n    and \"\\<And>x. x \\<in> M \\<Longrightarrow> 0 \\<le> f x\"\n  shows \"infsum f M \\<ge> 0\" (is \"?lhs \\<ge> _\")\n  by (metis assms(1) assms(2) infsum_0_simp summable_on_0_simp infsum_mono_complex)\n\nlemma infsum_cmod:\n  assumes \"f summable_on M\"\n    and fnn: \"\\<And>x. x \\<in> M \\<Longrightarrow> 0 \\<le> f x\"\n  shows \"infsum (\\<lambda>x. cmod (f x)) M = cmod (infsum f M)\"\nproof -\n  have \\<open>complex_of_real (infsum (\\<lambda>x. cmod (f x)) M) = infsum (\\<lambda>x. complex_of_real (cmod (f x))) M\\<close>\n  proof (rule infsum_comm_additive[symmetric, unfolded o_def])\n    have \"(\\<lambda>z. Re (f z)) summable_on M\"\n      using assms summable_on_Re by blast\n    also have \"?this \\<longleftrightarrow> f abs_summable_on M\"\n      using fnn by (intro summable_on_cong) (auto simp: less_eq_complex_def cmod_def)\n    finally show \\<dots> .\n  qed (auto simp: additive_def)\n  also have \\<open>\\<dots> = infsum f M\\<close>\n    apply (rule infsum_cong)\n    using fnn cmod_eq_Re complex_is_Real_iff less_eq_complex_def by force\n  finally show ?thesis\n    by (metis abs_of_nonneg infsum_def le_less_trans norm_ge_zero norm_infsum_bound norm_of_real not_le order_refl)\nqed\n\n\nlemma summable_on_iff_abs_summable_on_complex:\n  fixes f :: \\<open>'a \\<Rightarrow> complex\\<close>\n  shows \\<open>f summable_on A \\<longleftrightarrow> f abs_summable_on A\\<close>\nproof (rule iffI)\n  assume \\<open>f summable_on A\\<close>\n  define i r ni nr n where \\<open>i x = Im (f x)\\<close> and \\<open>r x = Re (f x)\\<close>\n    and \\<open>ni x = norm (i x)\\<close> and \\<open>nr x = norm (r x)\\<close> and \\<open>n x = norm (f x)\\<close> for x\n  from \\<open>f summable_on A\\<close> have \\<open>i summable_on A\\<close>\n    by (simp add: i_def[abs_def] summable_on_Im)\n  then have [simp]: \\<open>ni summable_on A\\<close>\n    using ni_def[abs_def] summable_on_iff_abs_summable_on_real by force\n\n  from \\<open>f summable_on A\\<close> have \\<open>r summable_on A\\<close>\n    by (simp add: r_def[abs_def] summable_on_Re)\n  then have [simp]: \\<open>nr summable_on A\\<close>\n    by (metis nr_def summable_on_cong summable_on_iff_abs_summable_on_real)\n\n  have n_sum: \\<open>n x \\<le> nr x + ni x\\<close> for x\n    by (simp add: n_def nr_def ni_def r_def i_def cmod_le)\n\n  have *: \\<open>(\\<lambda>x. nr x + ni x) summable_on A\\<close>\n    apply (rule summable_on_add) by auto\n  show \\<open>n summable_on A\\<close>\n    apply (rule nonneg_bdd_above_summable_on)\n     apply (simp add: n_def; fail)\n    apply (rule bdd_aboveI[where M=\\<open>infsum (\\<lambda>x. nr x + ni x) A\\<close>])\n    using * n_sum by (auto simp flip: infsum_finite simp: ni_def[abs_def] nr_def[abs_def] intro!: infsum_mono_neutral)\nnext\n  show \\<open>f abs_summable_on A \\<Longrightarrow> f summable_on A\\<close>\n    using abs_summable_summable by blast\nqed\n\nlemma summable_countable_complex:\n  fixes f :: \\<open>'a \\<Rightarrow> complex\\<close>\n  assumes \\<open>f summable_on A\\<close>\n  shows \\<open>countable {x\\<in>A. f x \\<noteq> 0}\\<close>\n  using abs_summable_countable assms summable_on_iff_abs_summable_on_complex by blast\n\nend\n\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/Analysis/Infinite_Sum.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916099737806, "lm_q2_score": 0.8289388083214156, "lm_q1q2_score": 0.7156988122863742}}
{"text": "(*  Title:      HOL/UNITY/ProgressSets.thy\n    Author:     Lawrence C Paulson, Cambridge University Computer Laboratory\n    Copyright   2003  University of Cambridge\n\nProgress Sets.  From \n\n    David Meier and Beverly Sanders,\n    Composing Leads-to Properties\n    Theoretical Computer Science 243:1-2 (2000), 339-361.\n\n    David Meier,\n    Progress Properties in Program Refinement and Parallel Composition\n    Swiss Federal Institute of Technology Zurich (1997)\n*)\n\nsection{*Progress Sets*}\n\ntheory ProgressSets imports Transformers begin\n\nsubsection {*Complete Lattices and the Operator @{term cl}*}\n\ndefinition lattice :: \"'a set set => bool\" where\n   --{*Meier calls them closure sets, but they are just complete lattices*}\n   \"lattice L ==\n         (\\<forall>M. M \\<subseteq> L --> \\<Inter>M \\<in> L) & (\\<forall>M. M \\<subseteq> L --> \\<Union>M \\<in> L)\"\n\ndefinition cl :: \"['a set set, 'a set] => 'a set\" where\n   --{*short for ``closure''*}\n   \"cl L r == \\<Inter>{x. x\\<in>L & r \\<subseteq> x}\"\n\nlemma UNIV_in_lattice: \"lattice L ==> UNIV \\<in> L\"\nby (force simp add: lattice_def)\n\nlemma empty_in_lattice: \"lattice L ==> {} \\<in> L\"\nby (force simp add: lattice_def)\n\nlemma Union_in_lattice: \"[|M \\<subseteq> L; lattice L|] ==> \\<Union>M \\<in> L\"\nby (simp add: lattice_def)\n\nlemma Inter_in_lattice: \"[|M \\<subseteq> L; lattice L|] ==> \\<Inter>M \\<in> L\"\nby (simp add: lattice_def)\n\nlemma UN_in_lattice:\n     \"[|lattice L; !!i. i\\<in>I ==> r i \\<in> L|] ==> (\\<Union>i\\<in>I. r i) \\<in> L\"\napply (unfold SUP_def)\napply (blast intro: Union_in_lattice) \ndone\n\nlemma INT_in_lattice:\n     \"[|lattice L; !!i. i\\<in>I ==> r i \\<in> L|] ==> (\\<Inter>i\\<in>I. r i)  \\<in> L\"\napply (unfold INF_def)\napply (blast intro: Inter_in_lattice) \ndone\n\nlemma Un_in_lattice: \"[|x\\<in>L; y\\<in>L; lattice L|] ==> x\\<union>y \\<in> L\"\n  using Union_in_lattice [of \"{x, y}\" L] by simp\n\nlemma Int_in_lattice: \"[|x\\<in>L; y\\<in>L; lattice L|] ==> x\\<inter>y \\<in> L\"\n  using Inter_in_lattice [of \"{x, y}\" L] by simp\n\nlemma lattice_stable: \"lattice {X. F \\<in> stable X}\"\nby (simp add: lattice_def stable_def constrains_def, blast)\n\ntext{*The next three results state that @{term \"cl L r\"} is the minimal\n element of @{term L} that includes @{term r}.*}\nlemma cl_in_lattice: \"lattice L ==> cl L r \\<in> L\"\napply (simp add: lattice_def cl_def)\napply (erule conjE)  \napply (drule spec, erule mp, blast) \ndone\n\nlemma cl_least: \"[|c\\<in>L; r\\<subseteq>c|] ==> cl L r \\<subseteq> c\" \nby (force simp add: cl_def)\n\ntext{*The next three lemmas constitute assertion (4.61)*}\nlemma cl_mono: \"r \\<subseteq> r' ==> cl L r \\<subseteq> cl L r'\"\nby (simp add: cl_def, blast)\n\nlemma subset_cl: \"r \\<subseteq> cl L r\"\nby (simp add: cl_def le_Inf_iff)\n\ntext{*A reformulation of @{thm subset_cl}*}\nlemma clI: \"x \\<in> r ==> x \\<in> cl L r\"\nby (simp add: cl_def, blast)\n\ntext{*A reformulation of @{thm cl_least}*}\nlemma clD: \"[|c \\<in> cl L r; B \\<in> L; r \\<subseteq> B|] ==> c \\<in> B\"\nby (force simp add: cl_def)\n\nlemma cl_UN_subset: \"(\\<Union>i\\<in>I. cl L (r i)) \\<subseteq> cl L (\\<Union>i\\<in>I. r i)\"\nby (simp add: cl_def, blast)\n\nlemma cl_Un: \"lattice L ==> cl L (r\\<union>s) = cl L r \\<union> cl L s\"\napply (rule equalityI) \n prefer 2 \n  apply (simp add: cl_def, blast)\napply (rule cl_least)\n apply (blast intro: Un_in_lattice cl_in_lattice)\napply (blast intro: subset_cl [THEN subsetD])  \ndone\n\nlemma cl_UN: \"lattice L ==> cl L (\\<Union>i\\<in>I. r i) = (\\<Union>i\\<in>I. cl L (r i))\"\napply (rule equalityI) \n prefer 2 apply (simp add: cl_def, blast)\napply (rule cl_least)\n apply (blast intro: UN_in_lattice cl_in_lattice)\napply (blast intro: subset_cl [THEN subsetD])  \ndone\n\nlemma cl_Int_subset: \"cl L (r\\<inter>s) \\<subseteq> cl L r \\<inter> cl L s\"\nby (simp add: cl_def, blast)\n\nlemma cl_idem [simp]: \"cl L (cl L r) = cl L r\"\nby (simp add: cl_def, blast)\n\nlemma cl_ident: \"r\\<in>L ==> cl L r = r\" \nby (force simp add: cl_def)\n\nlemma cl_empty [simp]: \"lattice L ==> cl L {} = {}\"\nby (simp add: cl_ident empty_in_lattice)\n\nlemma cl_UNIV [simp]: \"lattice L ==> cl L UNIV = UNIV\"\nby (simp add: cl_ident UNIV_in_lattice)\n\ntext{*Assertion (4.62)*}\nlemma cl_ident_iff: \"lattice L ==> (cl L r = r) = (r\\<in>L)\" \napply (rule iffI) \n apply (erule subst)\n apply (erule cl_in_lattice)  \napply (erule cl_ident) \ndone\n\nlemma cl_subset_in_lattice: \"[|cl L r \\<subseteq> r; lattice L|] ==> r\\<in>L\" \nby (simp add: cl_ident_iff [symmetric] equalityI subset_cl)\n\n\nsubsection {*Progress Sets and the Main Lemma*}\ntext{*A progress set satisfies certain closure conditions and is a \nsimple way of including the set @{term \"wens_set F B\"}.*}\n\ndefinition closed :: \"['a program, 'a set, 'a set,  'a set set] => bool\" where\n   \"closed F T B L == \\<forall>M. \\<forall>act \\<in> Acts F. B\\<subseteq>M & T\\<inter>M \\<in> L -->\n                              T \\<inter> (B \\<union> wp act M) \\<in> L\"\n\ndefinition progress_set :: \"['a program, 'a set, 'a set] => 'a set set set\" where\n   \"progress_set F T B ==\n      {L. lattice L & B \\<in> L & T \\<in> L & closed F T B L}\"\n\nlemma closedD:\n   \"[|closed F T B L; act \\<in> Acts F; B\\<subseteq>M; T\\<inter>M \\<in> L|] \n    ==> T \\<inter> (B \\<union> wp act M) \\<in> L\" \nby (simp add: closed_def) \n\ntext{*Note: the formalization below replaces Meier's @{term q} by @{term B}\nand @{term m} by @{term X}. *}\n\ntext{*Part of the proof of the claim at the bottom of page 97.  It's\nproved separately because the argument requires a generalization over\nall @{term \"act \\<in> Acts F\"}.*}\nlemma lattice_awp_lemma:\n  assumes TXC:  \"T\\<inter>X \\<in> C\" --{*induction hypothesis in theorem below*}\n      and BsubX:  \"B \\<subseteq> X\"   --{*holds in inductive step*}\n      and latt: \"lattice C\"\n      and TC:   \"T \\<in> C\"\n      and BC:   \"B \\<in> C\"\n      and clos: \"closed F T B C\"\n    shows \"T \\<inter> (B \\<union> awp F (X \\<union> cl C (T\\<inter>r))) \\<in> C\"\napply (simp del: INT_simps add: awp_def INT_extend_simps) \napply (rule INT_in_lattice [OF latt]) \napply (erule closedD [OF clos]) \napply (simp add: subset_trans [OF BsubX Un_upper1]) \napply (subgoal_tac \"T \\<inter> (X \\<union> cl C (T\\<inter>r)) = (T\\<inter>X) \\<union> cl C (T\\<inter>r)\")\n prefer 2 apply (blast intro: TC clD) \napply (erule ssubst) \napply (blast intro: Un_in_lattice latt cl_in_lattice TXC) \ndone\n\ntext{*Remainder of the proof of the claim at the bottom of page 97.*}\nlemma lattice_lemma:\n  assumes TXC:  \"T\\<inter>X \\<in> C\" --{*induction hypothesis in theorem below*}\n      and BsubX:  \"B \\<subseteq> X\"   --{*holds in inductive step*}\n      and act:  \"act \\<in> Acts F\"\n      and latt: \"lattice C\"\n      and TC:   \"T \\<in> C\"\n      and BC:   \"B \\<in> C\"\n      and clos: \"closed F T B C\"\n    shows \"T \\<inter> (wp act X \\<inter> awp F (X \\<union> cl C (T\\<inter>r)) \\<union> X) \\<in> C\"\napply (subgoal_tac \"T \\<inter> (B \\<union> wp act X) \\<in> C\")\n prefer 2 apply (simp add: closedD [OF clos] act BsubX TXC)\napply (drule Int_in_lattice\n              [OF _ lattice_awp_lemma [OF TXC BsubX latt TC BC clos, of r]\n                    latt])\napply (subgoal_tac\n         \"T \\<inter> (B \\<union> wp act X) \\<inter> (T \\<inter> (B \\<union> awp F (X \\<union> cl C (T\\<inter>r)))) = \n          T \\<inter> (B \\<union> wp act X \\<inter> awp F (X \\<union> cl C (T\\<inter>r)))\") \n prefer 2 apply blast \napply simp  \napply (drule Un_in_lattice [OF _ TXC latt])  \napply (subgoal_tac\n         \"T \\<inter> (B \\<union> wp act X \\<inter> awp F (X \\<union> cl C (T\\<inter>r))) \\<union> T\\<inter>X = \n          T \\<inter> (wp act X \\<inter> awp F (X \\<union> cl C (T\\<inter>r)) \\<union> X)\")\n apply simp \napply (blast intro: BsubX [THEN subsetD]) \ndone\n\n\ntext{*Induction step for the main lemma*}\nlemma progress_induction_step:\n  assumes TXC:  \"T\\<inter>X \\<in> C\" --{*induction hypothesis in theorem below*}\n      and act:  \"act \\<in> Acts F\"\n      and Xwens: \"X \\<in> wens_set F B\"\n      and latt: \"lattice C\"\n      and  TC:  \"T \\<in> C\"\n      and  BC:  \"B \\<in> C\"\n      and clos: \"closed F T B C\"\n      and Fstable: \"F \\<in> stable T\"\n  shows \"T \\<inter> wens F act X \\<in> C\"\nproof -\n  from Xwens have BsubX: \"B \\<subseteq> X\"\n    by (rule wens_set_imp_subset) \n  let ?r = \"wens F act X\"\n  have \"?r \\<subseteq> (wp act X \\<inter> awp F (X\\<union>?r)) \\<union> X\"\n    by (simp add: wens_unfold [symmetric])\n  then have \"T\\<inter>?r \\<subseteq> T \\<inter> ((wp act X \\<inter> awp F (X\\<union>?r)) \\<union> X)\"\n    by blast\n  then have \"T\\<inter>?r \\<subseteq> T \\<inter> ((wp act X \\<inter> awp F (T \\<inter> (X\\<union>?r))) \\<union> X)\"\n    by (simp add: awp_Int_eq Fstable stable_imp_awp_ident, blast) \n  then have \"T\\<inter>?r \\<subseteq> T \\<inter> ((wp act X \\<inter> awp F (X \\<union> cl C (T\\<inter>?r))) \\<union> X)\"\n    by (blast intro: awp_mono [THEN [2] rev_subsetD] subset_cl [THEN subsetD])\n  then have \"cl C (T\\<inter>?r) \\<subseteq> \n             cl C (T \\<inter> ((wp act X \\<inter> awp F (X \\<union> cl C (T\\<inter>?r))) \\<union> X))\"\n    by (rule cl_mono) \n  then have \"cl C (T\\<inter>?r) \\<subseteq> \n             T \\<inter> ((wp act X \\<inter> awp F (X \\<union> cl C (T\\<inter>?r))) \\<union> X)\"\n    by (simp add: cl_ident lattice_lemma [OF TXC BsubX act latt TC BC clos])\n  then have \"cl C (T\\<inter>?r) \\<subseteq> (wp act X \\<inter> awp F (X \\<union> cl C (T\\<inter>?r))) \\<union> X\"\n    by blast\n  then have \"cl C (T\\<inter>?r) \\<subseteq> ?r\"\n    by (blast intro!: subset_wens) \n  then have cl_subset: \"cl C (T\\<inter>?r) \\<subseteq> T\\<inter>?r\"\n    by (simp add: cl_ident TC\n                  subset_trans [OF cl_mono [OF Int_lower1]]) \n  show ?thesis\n    by (rule cl_subset_in_lattice [OF cl_subset latt]) \nqed\n\ntext{*Proved on page 96 of Meier's thesis.  The special case when\n   @{term \"T=UNIV\"} states that every progress set for the program @{term F}\n   and set @{term B} includes the set @{term \"wens_set F B\"}.*}\nlemma progress_set_lemma:\n     \"[|C \\<in> progress_set F T B; r \\<in> wens_set F B; F \\<in> stable T|] ==> T\\<inter>r \\<in> C\"\napply (simp add: progress_set_def, clarify) \napply (erule wens_set.induct) \n  txt{*Base*}\n  apply (simp add: Int_in_lattice) \n txt{*The difficult @{term wens} case*}\n apply (simp add: progress_induction_step) \ntxt{*Disjunctive case*}\napply (subgoal_tac \"(\\<Union>U\\<in>W. T \\<inter> U) \\<in> C\") \n apply simp \napply (blast intro: UN_in_lattice) \ndone\n\n\nsubsection {*The Progress Set Union Theorem*}\n\nlemma closed_mono:\n  assumes BB':  \"B \\<subseteq> B'\"\n      and TBwp: \"T \\<inter> (B \\<union> wp act M) \\<in> C\"\n      and B'C:  \"B' \\<in> C\"\n      and TC:   \"T \\<in> C\"\n      and latt: \"lattice C\"\n  shows \"T \\<inter> (B' \\<union> wp act M) \\<in> C\"\nproof -\n  from TBwp have \"(T\\<inter>B) \\<union> (T \\<inter> wp act M) \\<in> C\"\n    by (simp add: Int_Un_distrib)\n  then have TBBC: \"(T\\<inter>B') \\<union> ((T\\<inter>B) \\<union> (T \\<inter> wp act M)) \\<in> C\"\n    by (blast intro: Int_in_lattice Un_in_lattice TC B'C latt) \n  show ?thesis\n    by (rule eqelem_imp_iff [THEN iffD1, OF _ TBBC], \n        blast intro: BB' [THEN subsetD]) \nqed\n\n\nlemma progress_set_mono:\n    assumes BB':  \"B \\<subseteq> B'\"\n    shows\n     \"[| B' \\<in> C;  C \\<in> progress_set F T B|] \n      ==> C \\<in> progress_set F T B'\"\nby (simp add: progress_set_def closed_def closed_mono [OF BB'] \n                 subset_trans [OF BB']) \n\ntheorem progress_set_Union:\n  assumes leadsTo: \"F \\<in> A leadsTo B'\"\n      and prog: \"C \\<in> progress_set F T B\"\n      and Fstable: \"F \\<in> stable T\"\n      and BB':  \"B \\<subseteq> B'\"\n      and B'C:  \"B' \\<in> C\"\n      and Gco: \"!!X. X\\<in>C ==> G \\<in> X-B co X\"\n  shows \"F\\<squnion>G \\<in> T\\<inter>A leadsTo B'\"\napply (insert prog Fstable) \napply (rule leadsTo_Join [OF leadsTo]) \n  apply (force simp add: progress_set_def awp_iff_stable [symmetric]) \napply (simp add: awp_iff_constrains)\napply (drule progress_set_mono [OF BB' B'C]) \napply (blast intro: progress_set_lemma Gco constrains_weaken_L \n                    BB' [THEN subsetD]) \ndone\n\n\nsubsection {*Some Progress Sets*}\n\nlemma UNIV_in_progress_set: \"UNIV \\<in> progress_set F T B\"\nby (simp add: progress_set_def lattice_def closed_def)\n\n\n\nsubsubsection {*Lattices and Relations*}\ntext{*From Meier's thesis, section 4.5.3*}\n\ndefinition relcl :: \"'a set set => ('a * 'a) set\" where\n    -- {*Derived relation from a lattice*}\n    \"relcl L == {(x,y). y \\<in> cl L {x}}\"\n  \ndefinition latticeof :: \"('a * 'a) set => 'a set set\" where\n    -- {*Derived lattice from a relation: the set of upwards-closed sets*}\n    \"latticeof r == {X. \\<forall>s t. s \\<in> X & (s,t) \\<in> r --> t \\<in> X}\"\n\n\nlemma relcl_refl: \"(a,a) \\<in> relcl L\"\nby (simp add: relcl_def subset_cl [THEN subsetD])\n\nlemma relcl_trans:\n     \"[| (a,b) \\<in> relcl L; (b,c) \\<in> relcl L; lattice L |] ==> (a,c) \\<in> relcl L\"\napply (simp add: relcl_def)\napply (blast intro: clD cl_in_lattice)\ndone\n\nlemma refl_relcl: \"lattice L ==> refl (relcl L)\"\nby (simp add: refl_onI relcl_def subset_cl [THEN subsetD])\n\nlemma trans_relcl: \"lattice L ==> trans (relcl L)\"\nby (blast intro: relcl_trans transI)\n\nlemma lattice_latticeof: \"lattice (latticeof r)\"\nby (auto simp add: lattice_def latticeof_def)\n\nlemma lattice_singletonI:\n     \"[|lattice L; !!s. s \\<in> X ==> {s} \\<in> L|] ==> X \\<in> L\"\napply (cut_tac UN_singleton [of X]) \napply (erule subst) \napply (simp only: UN_in_lattice) \ndone\n\ntext{*Equation (4.71) of Meier's thesis.  He gives no proof.*}\nlemma cl_latticeof:\n     \"[|refl r; trans r|] \n      ==> cl (latticeof r) X = {t. \\<exists>s. s\\<in>X & (s,t) \\<in> r}\" \napply (rule equalityI) \n apply (rule cl_least) \n  apply (simp (no_asm_use) add: latticeof_def trans_def, blast)\n apply (simp add: latticeof_def refl_on_def, blast)\napply (simp add: latticeof_def, clarify)\napply (unfold cl_def, blast) \ndone\n\ntext{*Related to (4.71).*}\nlemma cl_eq_Collect_relcl:\n     \"lattice L ==> cl L X = {t. \\<exists>s. s\\<in>X & (s,t) \\<in> relcl L}\" \napply (cut_tac UN_singleton [of X]) \napply (erule subst) \napply (force simp only: relcl_def cl_UN)\ndone\n\ntext{*Meier's theorem of section 4.5.3*}\ntheorem latticeof_relcl_eq: \"lattice L ==> latticeof (relcl L) = L\"\napply (rule equalityI) \n prefer 2 apply (force simp add: latticeof_def relcl_def cl_def, clarify) \napply (rename_tac X)\napply (rule cl_subset_in_lattice)   \n prefer 2 apply assumption\napply (drule cl_ident_iff [OF lattice_latticeof, THEN iffD2])\napply (drule equalityD1)   \napply (rule subset_trans) \n prefer 2 apply assumption\napply (thin_tac \"?U \\<subseteq> X\") \napply (cut_tac A=X in UN_singleton) \napply (erule subst) \napply (simp only: cl_UN lattice_latticeof \n                  cl_latticeof [OF refl_relcl trans_relcl]) \napply (simp add: relcl_def) \ndone\n\ntheorem relcl_latticeof_eq:\n     \"[|refl r; trans r|] ==> relcl (latticeof r) = r\"\nby (simp add: relcl_def cl_latticeof)\n\n\nsubsubsection {*Decoupling Theorems*}\n\ndefinition decoupled :: \"['a program, 'a program] => bool\" where\n   \"decoupled F G ==\n        \\<forall>act \\<in> Acts F. \\<forall>B. G \\<in> stable B --> G \\<in> stable (wp act B)\"\n\n\ntext{*Rao's Decoupling Theorem*}\nlemma stableco: \"F \\<in> stable A ==> F \\<in> A-B co A\"\nby (simp add: stable_def constrains_def, blast) \n\ntheorem decoupling:\n  assumes leadsTo: \"F \\<in> A leadsTo B\"\n      and Gstable: \"G \\<in> stable B\"\n      and dec:     \"decoupled F G\"\n  shows \"F\\<squnion>G \\<in> A leadsTo B\"\nproof -\n  have prog: \"{X. G \\<in> stable X} \\<in> progress_set F UNIV B\"\n    by (simp add: progress_set_def lattice_stable Gstable closed_def\n                  stable_Un [OF Gstable] dec [unfolded decoupled_def]) \n  have \"F\\<squnion>G \\<in> (UNIV\\<inter>A) leadsTo B\" \n    by (rule progress_set_Union [OF leadsTo prog],\n        simp_all add: Gstable stableco)\n  thus ?thesis by simp\nqed\n\n\ntext{*Rao's Weak Decoupling Theorem*}\ntheorem weak_decoupling:\n  assumes leadsTo: \"F \\<in> A leadsTo B\"\n      and stable: \"F\\<squnion>G \\<in> stable B\"\n      and dec:     \"decoupled F (F\\<squnion>G)\"\n  shows \"F\\<squnion>G \\<in> A leadsTo B\"\nproof -\n  have prog: \"{X. F\\<squnion>G \\<in> stable X} \\<in> progress_set F UNIV B\" \n    by (simp del: Join_stable\n             add: progress_set_def lattice_stable stable closed_def\n                  stable_Un [OF stable] dec [unfolded decoupled_def])\n  have \"F\\<squnion>G \\<in> (UNIV\\<inter>A) leadsTo B\" \n    by (rule progress_set_Union [OF leadsTo prog],\n        simp_all del: Join_stable add: stable,\n        simp add: stableco) \n  thus ?thesis by simp\nqed\n\ntext{*The ``Decoupling via @{term G'} Union Theorem''*}\ntheorem decoupling_via_aux:\n  assumes leadsTo: \"F \\<in> A leadsTo B\"\n      and prog: \"{X. G' \\<in> stable X} \\<in> progress_set F UNIV B\"\n      and GG':  \"G \\<le> G'\"  \n               --{*Beware!  This is the converse of the refinement relation!*}\n  shows \"F\\<squnion>G \\<in> A leadsTo B\"\nproof -\n  from prog have stable: \"G' \\<in> stable B\"\n    by (simp add: progress_set_def)\n  have \"F\\<squnion>G \\<in> (UNIV\\<inter>A) leadsTo B\" \n    by (rule progress_set_Union [OF leadsTo prog],\n        simp_all add: stable stableco component_stable [OF GG'])\n  thus ?thesis by simp\nqed\n\n\nsubsection{*Composition Theorems Based on Monotonicity and Commutativity*}\n\nsubsubsection{*Commutativity of @{term \"cl L\"} and assignment.*}\ndefinition commutes :: \"['a program, 'a set, 'a set,  'a set set] => bool\" where\n   \"commutes F T B L ==\n       \\<forall>M. \\<forall>act \\<in> Acts F. B \\<subseteq> M --> \n           cl L (T \\<inter> wp act M) \\<subseteq> T \\<inter> (B \\<union> wp act (cl L (T\\<inter>M)))\"\n\n\ntext{*From Meier's thesis, section 4.5.6*}\nlemma commutativity1_lemma:\n  assumes commutes: \"commutes F T B L\" \n      and lattice:  \"lattice L\"\n      and BL: \"B \\<in> L\"\n      and TL: \"T \\<in> L\"\n  shows \"closed F T B L\"\napply (simp add: closed_def, clarify)\napply (rule ProgressSets.cl_subset_in_lattice [OF _ lattice])  \napply (simp add: Int_Un_distrib cl_Un [OF lattice] \n                 cl_ident Int_in_lattice [OF TL BL lattice] Un_upper1)\napply (subgoal_tac \"cl L (T \\<inter> wp act M) \\<subseteq> T \\<inter> (B \\<union> wp act (cl L (T \\<inter> M)))\") \n prefer 2 \n apply (cut_tac commutes, simp add: commutes_def) \napply (erule subset_trans) \napply (simp add: cl_ident)\napply (blast intro: rev_subsetD [OF _ wp_mono]) \ndone\n\ntext{*Version packaged with @{thm progress_set_Union}*}\nlemma commutativity1:\n  assumes leadsTo: \"F \\<in> A leadsTo B\"\n      and lattice:  \"lattice L\"\n      and BL: \"B \\<in> L\"\n      and TL: \"T \\<in> L\"\n      and Fstable: \"F \\<in> stable T\"\n      and Gco: \"!!X. X\\<in>L ==> G \\<in> X-B co X\"\n      and commutes: \"commutes F T B L\" \n  shows \"F\\<squnion>G \\<in> T\\<inter>A leadsTo B\"\nby (rule progress_set_Union [OF leadsTo _ Fstable subset_refl BL Gco],\n    simp add: progress_set_def commutativity1_lemma commutes lattice BL TL) \n\n\n\ntext{*Possibly move to Relation.thy, after @{term single_valued}*}\ndefinition funof :: \"[('a*'b)set, 'a] => 'b\" where\n   \"funof r == (\\<lambda>x. THE y. (x,y) \\<in> r)\"\n\nlemma funof_eq: \"[|single_valued r; (x,y) \\<in> r|] ==> funof r x = y\"\nby (simp add: funof_def single_valued_def, blast)\n\nlemma funof_Pair_in:\n     \"[|single_valued r; x \\<in> Domain r|] ==> (x, funof r x) \\<in> r\"\nby (force simp add: funof_eq) \n\nlemma funof_in:\n     \"[|r``{x} \\<subseteq> A; single_valued r; x \\<in> Domain r|] ==> funof r x \\<in> A\" \nby (force simp add: funof_eq)\n \nlemma funof_imp_wp: \"[|funof act t \\<in> A; single_valued act|] ==> t \\<in> wp act A\"\nby (force simp add: in_wp_iff funof_eq)\n\n\nsubsubsection{*Commutativity of Functions and Relation*}\ntext{*Thesis, page 109*}\n\n(*FIXME: this proof is still an ungodly mess*)\ntext{*From Meier's thesis, section 4.5.6*}\nlemma commutativity2_lemma:\n  assumes dcommutes: \n      \"\\<And>act s t. act \\<in> Acts F \\<Longrightarrow> s \\<in> T \\<Longrightarrow> (s, t) \\<in> relcl L \\<Longrightarrow>\n        s \\<in> B | t \\<in> B | (funof act s, funof act t) \\<in> relcl L\"\n    and determ: \"!!act. act \\<in> Acts F ==> single_valued act\"\n    and total: \"!!act. act \\<in> Acts F ==> Domain act = UNIV\"\n    and lattice:  \"lattice L\"\n    and BL: \"B \\<in> L\"\n    and TL: \"T \\<in> L\"\n    and Fstable: \"F \\<in> stable T\"\n  shows  \"commutes F T B L\"\nproof -\n  { fix M and act and t\n    assume 1: \"B \\<subseteq> M\" \"act \\<in> Acts F\" \"t \\<in> cl L (T \\<inter> wp act M)\"\n    then have \"\\<exists>s. (s,t) \\<in> relcl L \\<and> s \\<in> T \\<inter> wp act M\"\n      by (force simp add: cl_eq_Collect_relcl [OF lattice])\n    then obtain s where 2: \"(s, t) \\<in> relcl L\" \"s \\<in> T\" \"s \\<in> wp act M\"\n      by blast\n    then have 3: \"\\<forall>u\\<in>L. s \\<in> u --> t \\<in> u\"\n      apply (intro ballI impI) \n      apply (subst cl_ident [symmetric], assumption)\n      apply (simp add: relcl_def)  \n      apply (blast intro: cl_mono [THEN [2] rev_subsetD])\n      done\n    with 1 2 Fstable have 4: \"funof act s \\<in> T\\<inter>M\"\n      by (force intro!: funof_in \n        simp add: wp_def stable_def constrains_def determ total)\n    with 1 2 3 have 5: \"s \\<in> B | t \\<in> B | (funof act s, funof act t) \\<in> relcl L\"\n      by (intro dcommutes) assumption+ \n    with 1 2 3 4 have \"t \\<in> B | funof act t \\<in> cl L (T\\<inter>M)\"\n      by (simp add: relcl_def) (blast intro: BL cl_mono [THEN [2] rev_subsetD])  \n    with 1 2 3 4 5 have \"t \\<in> B | t \\<in> wp act (cl L (T\\<inter>M))\"\n      by (blast intro: funof_imp_wp determ) \n    with 2 3 have \"t \\<in> T \\<and> (t \\<in> B \\<or> t \\<in> wp act (cl L (T \\<inter> M)))\"\n      by (blast intro: TL cl_mono [THEN [2] rev_subsetD])\n    then have\"t \\<in> T \\<inter> (B \\<union> wp act (cl L (T \\<inter> M)))\"\n      by simp\n  }\n  then show \"commutes F T B L\" unfolding commutes_def by clarify\nqed\n  \ntext{*Version packaged with @{thm progress_set_Union}*}\nlemma commutativity2:\n  assumes leadsTo: \"F \\<in> A leadsTo B\"\n      and dcommutes: \n        \"\\<forall>act \\<in> Acts F. \n         \\<forall>s \\<in> T. \\<forall>t. (s,t) \\<in> relcl L --> \n                      s \\<in> B | t \\<in> B | (funof act s, funof act t) \\<in> relcl L\"\n      and determ: \"!!act. act \\<in> Acts F ==> single_valued act\"\n      and total: \"!!act. act \\<in> Acts F ==> Domain act = UNIV\"\n      and lattice:  \"lattice L\"\n      and BL: \"B \\<in> L\"\n      and TL: \"T \\<in> L\"\n      and Fstable: \"F \\<in> stable T\"\n      and Gco: \"!!X. X\\<in>L ==> G \\<in> X-B co X\"\n  shows \"F\\<squnion>G \\<in> T\\<inter>A leadsTo B\"\napply (rule commutativity1 [OF leadsTo lattice]) \napply (simp_all add: Gco commutativity2_lemma dcommutes determ total\n                     lattice BL TL Fstable)\ndone\n\n\nsubsection {*Monotonicity*}\ntext{*From Meier's thesis, section 4.5.7, page 110*}\n(*to be continued?*)\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/ProgressSets.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8633916099737806, "lm_q2_score": 0.8289388040954683, "lm_q1q2_score": 0.7156988086377267}}
{"text": "section \\<open>Union-Find Data-Structure\\<close>\ntheory Union_Find_Fun\nimports \n  Collections.Partial_Equivalence_Relation\n (* \"../Sep_Main\" \n  \"HOL-Library.Code_Target_Numeral\" *)\nbegin\ntext \\<open>\n  We implement a simple union-find data-structure based on an array.\n  It uses path compression and a size-based union heuristics.\n\\<close>\n\nsubsection \\<open>Abstract Union-Find on Lists\\<close>\ntext \\<open>\n  We first formulate union-find structures on lists, and later implement \n  them using Imperative/HOL. This is a separation of proof concerns\n  between proving the algorithmic idea correct and generating the verification\n  conditions.\n\\<close>\n\nsubsubsection \\<open>Representatives\\<close>\ntext \\<open>\n  We define a function that searches for the representative of an element.\n  This function is only partially defined, as it does not terminate on all\n  lists. We use the domain of this function to characterize valid union-find \n  lists. \n\\<close>\nfunction (domintros) rep_of \n  where \"rep_of l i = (if l!i = i then i else rep_of l (l!i))\"\n  by pat_completeness auto\n\ntext \\<open>A valid union-find structure only contains valid indexes, and\n  the \\<open>rep_of\\<close> function terminates for all indexes.\\<close>\ndefinition \n  \"ufa_invar l \\<equiv> \\<forall>i<length l. rep_of_dom (l,i) \\<and> l!i<length l\"\n\nlemma ufa_invarD: \n  \"\\<lbrakk>ufa_invar l; i<length l\\<rbrakk> \\<Longrightarrow> rep_of_dom (l,i)\" \n  \"\\<lbrakk>ufa_invar l; i<length l\\<rbrakk> \\<Longrightarrow> l!i<length l\" \n  unfolding ufa_invar_def by auto\n\ntext \\<open>We derive the following equations for the \\<open>rep-of\\<close> function.\\<close>\nlemma rep_of_refl: \"l!i=i \\<Longrightarrow> rep_of l i = i\"\n  apply (subst rep_of.psimps)\n  apply (rule rep_of.domintros)\n  apply (auto)\n  done\n\nlemma rep_of_step: \n  \"\\<lbrakk>ufa_invar l; i<length l; l!i\\<noteq>i\\<rbrakk> \\<Longrightarrow> rep_of l i = rep_of l (l!i)\"\n  apply (subst rep_of.psimps)\n  apply (auto dest: ufa_invarD)\n  done\n\nlemmas rep_of_simps = rep_of_refl rep_of_step\n\nlemma rep_of_iff: \"\\<lbrakk>ufa_invar l; i<length l\\<rbrakk> \n  \\<Longrightarrow> rep_of l i = (if l!i=i then i else rep_of l (l!i))\"\n  by (simp add: rep_of_simps)\n\ntext \\<open>We derive a custom induction rule, that is more suited to\n  our purposes.\\<close>\nlemma rep_of_induct[case_names base step, consumes 2]:\n  assumes I: \"ufa_invar l\" \n  assumes L: \"i<length l\"\n  assumes BASE: \"\\<And>i. \\<lbrakk> ufa_invar l; i<length l; l!i=i \\<rbrakk> \\<Longrightarrow> P l i\"\n  assumes STEP: \"\\<And>i. \\<lbrakk> ufa_invar l; i<length l; l!i\\<noteq>i; P l (l!i) \\<rbrakk> \n    \\<Longrightarrow> P l i\"\n  shows \"P l i\"\nproof -\n  from ufa_invarD[OF I L] have \"ufa_invar l \\<and> i<length l \\<longrightarrow> P l i\"\n    apply (induct l\\<equiv>l i rule: rep_of.pinduct)\n    apply (auto intro: STEP BASE dest: ufa_invarD)\n    done\n  thus ?thesis using I L by simp\nqed\n\ntext \\<open>In the following, we define various properties of \\<open>rep_of\\<close>.\\<close>\nlemma rep_of_min: \n  \"\\<lbrakk> ufa_invar l; i<length l \\<rbrakk> \\<Longrightarrow> l!(rep_of l i) = rep_of l i\"\nproof -\n  have \"\\<lbrakk>rep_of_dom (l,i) \\<rbrakk> \\<Longrightarrow> l!(rep_of l i) = rep_of l i\"\n    apply (induct arbitrary:  rule: rep_of.pinduct)\n    apply (subst rep_of.psimps, assumption)\n    apply (subst (2) rep_of.psimps, assumption)\n    apply auto\n    done \n  thus \"\\<lbrakk> ufa_invar l; i<length l \\<rbrakk> \\<Longrightarrow> l!(rep_of l i) = rep_of l i\"\n    by (metis ufa_invarD(1))\nqed\n\nlemma rep_of_bound: \n  \"\\<lbrakk> ufa_invar l; i<length l \\<rbrakk> \\<Longrightarrow> rep_of l i < length l\"\n  apply (induct rule: rep_of_induct)\n  apply (auto simp: rep_of_iff)\n  done\n\nlemma rep_of_idem: \n  \"\\<lbrakk> ufa_invar l; i<length l \\<rbrakk> \\<Longrightarrow> rep_of l (rep_of l i) = rep_of l i\"\n  by (auto simp: rep_of_min rep_of_refl)\n\nlemma rep_of_min_upd: \"\\<lbrakk> ufa_invar l; x<length l; i<length l \\<rbrakk> \\<Longrightarrow> \n  rep_of (l[rep_of l x := rep_of l x]) i = rep_of l i\"\n  by (metis list_update_id rep_of_min)   \n\nlemma rep_of_idx: \n  \"\\<lbrakk>ufa_invar l; i<length l\\<rbrakk> \\<Longrightarrow> rep_of l (l!i) = rep_of l i\"\n  by (metis rep_of_step)\n\nsubsubsection \\<open>Abstraction to Partial Equivalence Relation\\<close>\ndefinition ufa_\\<alpha> :: \"nat list \\<Rightarrow> (nat\\<times>nat) set\" \n  where \"ufa_\\<alpha> l \n    \\<equiv> {(x,y). x<length l \\<and> y<length l \\<and> rep_of l x = rep_of l y}\"\n\nlemma ufa_\\<alpha>_equiv[simp, intro!]: \"part_equiv (ufa_\\<alpha> l)\"\n  by rule (auto simp: ufa_\\<alpha>_def intro: symI transI)\n\nlemma ufa_\\<alpha>_lenD: \n  \"(x,y)\\<in>ufa_\\<alpha> l \\<Longrightarrow> x<length l\"\n  \"(x,y)\\<in>ufa_\\<alpha> l \\<Longrightarrow> y<length l\"\n  unfolding ufa_\\<alpha>_def by auto\n\nlemma ufa_\\<alpha>_dom[simp]: \"Domain (ufa_\\<alpha> l) = {0..<length l}\"\n  unfolding ufa_\\<alpha>_def by auto\n\nlemma ufa_\\<alpha>_refl[simp]: \"(i,i)\\<in>ufa_\\<alpha> l \\<longleftrightarrow> i<length l\"\n  unfolding ufa_\\<alpha>_def\n  by simp\n\nlemma ufa_\\<alpha>_len_eq: \n  assumes \"ufa_\\<alpha> l = ufa_\\<alpha> l'\"  \n  shows \"length l = length l'\"\n  by (metis assms le_antisym less_not_refl linorder_le_less_linear ufa_\\<alpha>_refl)\n\nsubsubsection \\<open>Operations\\<close>\nlemma ufa_init_invar: \"ufa_invar [0..<n]\"\n  unfolding ufa_invar_def\n  by (auto intro: rep_of.domintros)\n\nlemma ufa_init_correct: \"ufa_\\<alpha> [0..<n] = {(x,x) | x. x<n}\"\n  unfolding ufa_\\<alpha>_def\n  using ufa_init_invar[of n]\n  apply (auto simp: rep_of_refl)\n  done\n\nlemma ufa_find_correct: \"\\<lbrakk>ufa_invar l; x<length l; y<length l\\<rbrakk> \n  \\<Longrightarrow> rep_of l x = rep_of l y \\<longleftrightarrow> (x,y)\\<in>ufa_\\<alpha> l\"\n  unfolding ufa_\\<alpha>_def\n  by auto\n\nabbreviation \"ufa_union l x y \\<equiv> l[rep_of l x := rep_of l y]\"\n\nlemma ufa_union_invar:\n  assumes I: \"ufa_invar l\"\n  assumes L: \"x<length l\" \"y<length l\"\n  shows \"ufa_invar (ufa_union l x y)\"\n  unfolding ufa_invar_def\nproof (intro allI impI, simp only: length_list_update)\n  fix i\n  assume A: \"i<length l\"\n  with I have \"rep_of_dom (l,i)\" by (auto dest: ufa_invarD)\n\n  have \"ufa_union l x y ! i < length l\" using I L A\n    apply (cases \"i=rep_of l x\")\n    apply (auto simp: rep_of_bound dest: ufa_invarD)\n    done\n  moreover have \"rep_of_dom (ufa_union l x y, i)\" using I A L\n  proof (induct rule: rep_of_induct)\n    case (base i)\n    thus ?case\n      apply -\n      apply (rule rep_of.domintros)\n      apply (cases \"i=rep_of l x\")\n      apply auto\n      apply (rule rep_of.domintros)\n      apply (auto simp: rep_of_min)\n      done\n  next\n    case (step i)\n\n    from step.prems \\<open>ufa_invar l\\<close> \\<open>i<length l\\<close> \\<open>l!i\\<noteq>i\\<close> \n    have [simp]: \"ufa_union l x y ! i = l!i\"\n      apply (auto simp: rep_of_min rep_of_bound nth_list_update)\n      done\n\n    from step show ?case\n      apply -\n      apply (rule rep_of.domintros)\n      apply simp\n      done\n  qed\n  ultimately show \n    \"rep_of_dom (ufa_union l x y, i) \\<and> ufa_union l x y ! i < length l\"\n    by blast\n\nqed\n\nlemma ufa_union_aux:\n  assumes I: \"ufa_invar l\"\n  assumes L: \"x<length l\" \"y<length l\" \n  assumes IL: \"i<length l\"\n  shows \"rep_of (ufa_union l x y) i = \n    (if rep_of l i = rep_of l x then rep_of l y else rep_of l i)\"\n  using I IL\nproof (induct rule: rep_of_induct)\n  case (base i)\n  have [simp]: \"rep_of l i = i\" using \\<open>l!i=i\\<close> by (simp add: rep_of_refl)\n  note [simp] = \\<open>ufa_invar l\\<close> \\<open>i<length l\\<close>\n  show ?case proof (cases)\n    assume A[simp]: \"rep_of l x = i\"\n    have [simp]: \"l[i := rep_of l y] ! i = rep_of l y\" \n      by (auto simp: rep_of_bound)\n\n    show ?thesis proof (cases)\n      assume [simp]: \"rep_of l y = i\" \n      show ?thesis by (simp add: rep_of_refl)\n    next\n      assume A: \"rep_of l y \\<noteq> i\"\n      have [simp]: \"rep_of (l[i := rep_of l y]) i = rep_of l y\"\n        apply (subst rep_of_step[OF ufa_union_invar[OF I L], simplified])\n        using A apply simp_all\n        apply (subst rep_of_refl[where i=\"rep_of l y\"])\n        using I L\n        apply (simp_all add: rep_of_min)\n        done\n      show ?thesis by (simp add: rep_of_refl)\n    qed\n  next\n    assume A: \"rep_of l x \\<noteq> i\"\n    hence \"ufa_union l x y ! i = l!i\" by (auto)\n    also note \\<open>l!i=i\\<close>\n    finally have \"rep_of (ufa_union l x y) i = i\" by (simp add: rep_of_refl)\n    thus ?thesis using A by auto\n  qed\nnext    \n  case (step i)\n\n  note [simp] = I L \\<open>i<length l\\<close>\n\n  have \"rep_of l x \\<noteq> i\" by (metis I L(1) rep_of_min \\<open>l!i\\<noteq>i\\<close>)\n  hence [simp]: \"ufa_union l x y ! i = l!i\"\n    by (auto simp add: nth_list_update rep_of_bound \\<open>l!i\\<noteq>i\\<close>) []\n\n  have \"rep_of (ufa_union l x y) i = rep_of (ufa_union l x y) (l!i)\" \n    by (auto simp add: rep_of_iff[OF ufa_union_invar[OF I L]])\n  also note step.hyps(4)\n  finally show ?case\n    by (auto simp: rep_of_idx)\nqed\n  \nlemma ufa_union_correct: \"\\<lbrakk> ufa_invar l; x<length l; y<length l \\<rbrakk> \n  \\<Longrightarrow> ufa_\\<alpha> (ufa_union l x y) = per_union (ufa_\\<alpha> l) x y\"\n  unfolding ufa_\\<alpha>_def per_union_def\n  by (auto simp: ufa_union_aux\n    split: if_split_asm\n  )\n\nlemma ufa_compress_aux:\n  assumes I: \"ufa_invar l\"\n  assumes L[simp]: \"x<length l\"\n  shows \"ufa_invar (l[x := rep_of l x])\" \n  and \"\\<forall>i<length l. rep_of (l[x := rep_of l x]) i = rep_of l i\"\nproof -\n  {\n    fix i\n    assume \"i<length (l[x := rep_of l x])\"\n    hence IL: \"i<length l\" by simp\n\n    have G1: \"l[x := rep_of l x] ! i < length (l[x := rep_of l x])\"\n      using I IL \n      by (auto dest: ufa_invarD[OF I] simp: nth_list_update rep_of_bound)\n    from I IL have G2: \"rep_of (l[x := rep_of l x]) i = rep_of l i \n      \\<and> rep_of_dom (l[x := rep_of l x], i)\"\n    proof (induct rule: rep_of_induct)\n      case (base i)\n      thus ?case\n        apply (cases \"x=i\")\n        apply (auto intro: rep_of.domintros simp: rep_of_refl)\n        done\n    next\n      case (step i) \n      hence D: \"rep_of_dom (l[x := rep_of l x], i)\"\n        apply -\n        apply (rule rep_of.domintros)\n        apply (cases \"x=i\")\n        apply (auto intro: rep_of.domintros simp: rep_of_min)\n        done\n      \n      thus ?case apply simp using step\n        apply -\n        apply (subst rep_of.psimps[OF D])\n        apply (cases \"x=i\")\n        apply (auto simp: rep_of_min rep_of_idx)\n        apply (subst rep_of.psimps[where i=\"rep_of l i\"])\n        apply (auto intro: rep_of.domintros simp: rep_of_min)\n        done\n    qed\n    note G1 G2\n  } note G=this\n\n  thus \"\\<forall>i<length l. rep_of (l[x := rep_of l x]) i = rep_of l i\"\n    by auto\n\n  from G show \"ufa_invar (l[x := rep_of l x])\" \n    by (auto simp: ufa_invar_def)\nqed\n\nlemma ufa_compress_invar:\n  assumes I: \"ufa_invar l\"\n  assumes L[simp]: \"x<length l\"\n  shows \"ufa_invar (l[x := rep_of l x])\" \n  using assms by (rule ufa_compress_aux)\n\nlemma ufa_compress_correct:\n  assumes I: \"ufa_invar l\"\n  assumes L[simp]: \"x<length l\"\n  shows \"ufa_\\<alpha> (l[x := rep_of l x]) = ufa_\\<alpha> l\"\n  by (auto simp: ufa_\\<alpha>_def ufa_compress_aux[OF I])\n\nend\n", "meta": {"author": "adrilow", "repo": "Proof-of-the-amortized-time-complexity-of-the-Union-Find-data-structure-in-Isabelle-HOL", "sha": "293b12752261dac7f741483b62b27891bf4be1cc", "save_path": "github-repos/isabelle/adrilow-Proof-of-the-amortized-time-complexity-of-the-Union-Find-data-structure-in-Isabelle-HOL", "path": "github-repos/isabelle/adrilow-Proof-of-the-amortized-time-complexity-of-the-Union-Find-data-structure-in-Isabelle-HOL/Proof-of-the-amortized-time-complexity-of-the-Union-Find-data-structure-in-Isabelle-HOL-293b12752261dac7f741483b62b27891bf4be1cc/Union_Find_Fun.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8289387998695209, "lm_q2_score": 0.8633916082162402, "lm_q1q2_score": 0.7156988035321857}}
{"text": "section \\<open>Transposition function\\<close>\n\ntheory Transposition\n  imports MainRLT\nbegin\n\ndefinition transpose :: \\<open>'a \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> 'a\\<close>\n  where \\<open>transpose a b c = (if c = a then b else if c = b then a else c)\\<close>\n\nlemma transpose_apply_first [simp]:\n  \\<open>transpose a b a = b\\<close>\n  by (simp add: transpose_def)\n\nlemma transpose_apply_second [simp]:\n  \\<open>transpose a b b = a\\<close>\n  by (simp add: transpose_def)\n\nlemma transpose_apply_other [simp]:\n  \\<open>transpose a b c = c\\<close> if \\<open>c \\<noteq> a\\<close> \\<open>c \\<noteq> b\\<close>\n  using that by (simp add: transpose_def)\n\nlemma transpose_same [simp]:\n  \\<open>transpose a a = id\\<close>\n  by (simp add: fun_eq_iff transpose_def)\n\nlemma transpose_eq_iff:\n  \\<open>transpose a b c = d \\<longleftrightarrow> (c \\<noteq> a \\<and> c \\<noteq> b \\<and> d = c) \\<or> (c = a \\<and> d = b) \\<or> (c = b \\<and> d = a)\\<close>\n  by (auto simp add: transpose_def)\n\nlemma transpose_eq_imp_eq:\n  \\<open>c = d\\<close> if \\<open>transpose a b c = transpose a b d\\<close>\n  using that by (auto simp add: transpose_eq_iff)\n\nlemma transpose_commute [ac_simps]:\n  \\<open>transpose b a = transpose a b\\<close>\n  by (auto simp add: fun_eq_iff transpose_eq_iff)\n\nlemma transpose_involutory [simp]:\n  \\<open>transpose a b (transpose a b c) = c\\<close>\n  by (auto simp add: transpose_eq_iff)\n\nlemma transpose_comp_involutory [simp]:\n  \\<open>transpose a b \\<circ> transpose a b = id\\<close>\n  by (rule ext) simp\n\nlemma transpose_triple:\n  \\<open>transpose a b (transpose b c (transpose a b d)) = transpose a c d\\<close>\n  if \\<open>a \\<noteq> c\\<close> and \\<open>b \\<noteq> c\\<close>\n  using that by (simp add: transpose_def)\n\nlemma transpose_comp_triple:\n  \\<open>transpose a b \\<circ> transpose b c \\<circ> transpose a b = transpose a c\\<close>\n  if \\<open>a \\<noteq> c\\<close> and \\<open>b \\<noteq> c\\<close>\n  using that by (simp add: fun_eq_iff transpose_triple)\n\nlemma transpose_image_eq [simp]:\n  \\<open>transpose a b ` A = A\\<close> if \\<open>a \\<in> A \\<longleftrightarrow> b \\<in> A\\<close>\n  using that by (auto simp add: transpose_def [abs_def])\n\nlemma inj_on_transpose [simp]:\n  \\<open>inj_on (transpose a b) A\\<close>\n  by rule (drule transpose_eq_imp_eq)\n\nlemma inj_transpose:\n  \\<open>inj (transpose a b)\\<close>\n  by (fact inj_on_transpose)\n\nlemma surj_transpose:\n  \\<open>surj (transpose a b)\\<close>\n  by simp\n\nlemma bij_betw_transpose_iff [simp]:\n  \\<open>bij_betw (transpose a b) A A\\<close> if \\<open>a \\<in> A \\<longleftrightarrow> b \\<in> A\\<close>\n  using that by (auto simp: bij_betw_def)\n\nlemma bij_transpose [simp]:\n  \\<open>bij (transpose a b)\\<close>\n  by (rule bij_betw_transpose_iff) simp\n\nlemma bijection_transpose:\n  \\<open>bijection (transpose a b)\\<close>\n  by standard (fact bij_transpose)\n\nlemma inv_transpose_eq [simp]:\n  \\<open>inv (transpose a b) = transpose a b\\<close>\n  by (rule inv_unique_comp) simp_all\n\nlemma transpose_apply_commute:\n  \\<open>transpose a b (f c) = f (transpose (inv f a) (inv f b) c)\\<close>\n  if \\<open>bij f\\<close>\nproof -\n  from that have \\<open>surj f\\<close>\n    by (rule bij_is_surj)\n  with that show ?thesis\n    by (simp add: transpose_def bij_inv_eq_iff surj_f_inv_f)\nqed\n\nlemma transpose_comp_eq:\n  \\<open>transpose a b \\<circ> f = f \\<circ> transpose (inv f a) (inv f b)\\<close>\n  if \\<open>bij f\\<close>\n  using that by (simp add: fun_eq_iff transpose_apply_commute)\n\nlemma in_transpose_image_iff:\n  \\<open>x \\<in> transpose a b ` S \\<longleftrightarrow> transpose a b x \\<in> S\\<close>\n  by (auto intro!: image_eqI)\n\n\ntext \\<open>Legacy input alias\\<close>\n\nsetup \\<open>Context.theory_map (Name_Space.map_naming (Name_Space.qualified_path true \\<^binding>\\<open>Fun\\<close>))\\<close>\n\nabbreviation (input) swap :: \\<open>'a \\<Rightarrow> 'a \\<Rightarrow> ('a \\<Rightarrow> 'b) \\<Rightarrow> 'a \\<Rightarrow> 'b\\<close>\n  where \\<open>swap a b f \\<equiv> f \\<circ> transpose a b\\<close>\n\nlemma swap_def:\n  \\<open>Fun.swap a b f = f (a := f b, b:= f a)\\<close>\n  by (simp add: fun_eq_iff)\n\nsetup \\<open>Context.theory_map (Name_Space.map_naming (Name_Space.parent_path))\\<close>\n\nlemma swap_apply:\n  \"Fun.swap a b f a = f b\"\n  \"Fun.swap a b f b = f a\"\n  \"c \\<noteq> a \\<Longrightarrow> c \\<noteq> b \\<Longrightarrow> Fun.swap a b f c = f c\"\n  by simp_all\n\nlemma swap_self: \"Fun.swap a a f = f\"\n  by simp\n\nlemma swap_commute: \"Fun.swap a b f = Fun.swap b a f\"\n  by (simp add: ac_simps)\n\nlemma swap_nilpotent: \"Fun.swap a b (Fun.swap a b f) = f\"\n  by (simp add: comp_assoc)\n\nlemma swap_comp_involutory: \"Fun.swap a b \\<circ> Fun.swap a b = id\"\n  by (simp add: fun_eq_iff)\n\nlemma swap_triple:\n  assumes \"a \\<noteq> c\" and \"b \\<noteq> c\"\n  shows \"Fun.swap a b (Fun.swap b c (Fun.swap a b f)) = Fun.swap a c f\"\n  using assms transpose_comp_triple [of a c b]\n  by (simp add: comp_assoc)\n\nlemma comp_swap: \"f \\<circ> Fun.swap a b g = Fun.swap a b (f \\<circ> g)\"\n  by (simp add: comp_assoc)\n\nlemma swap_image_eq:\n  assumes \"a \\<in> A\" \"b \\<in> A\"\n  shows \"Fun.swap a b f ` A = f ` A\"\n  using assms by (metis image_comp transpose_image_eq)\n\nlemma inj_on_imp_inj_on_swap: \"inj_on f A \\<Longrightarrow> a \\<in> A \\<Longrightarrow> b \\<in> A \\<Longrightarrow> inj_on (Fun.swap a b f) A\"\n  by (simp add: comp_inj_on)\n  \nlemma inj_on_swap_iff:\n  assumes A: \"a \\<in> A\" \"b \\<in> A\"\n  shows \"inj_on (Fun.swap a b f) A \\<longleftrightarrow> inj_on f A\"\n  using assms by (metis inj_on_imageI inj_on_imp_inj_on_swap transpose_image_eq)\n\nlemma surj_imp_surj_swap: \"surj f \\<Longrightarrow> surj (Fun.swap a b f)\"\n  by (meson comp_surj surj_transpose)\n\nlemma surj_swap_iff: \"surj (Fun.swap a b f) \\<longleftrightarrow> surj f\"\n  by (metis fun.set_map surj_transpose)\n\nlemma bij_betw_swap_iff: \"x \\<in> A \\<Longrightarrow> y \\<in> A \\<Longrightarrow> bij_betw (Fun.swap x y f) A B \\<longleftrightarrow> bij_betw f A B\"\n  by (meson bij_betw_comp_iff bij_betw_transpose_iff)\n\nlemma bij_swap_iff: \"bij (Fun.swap a b f) \\<longleftrightarrow> bij f\"\n  by (simp add: bij_betw_swap_iff)\n\nlemma swap_image:\n  \\<open>Fun.swap i j f ` A = f ` (A - {i, j}\n    \\<union> (if i \\<in> A then {j} else {}) \\<union> (if j \\<in> A then {i} else {}))\\<close>\n  by (auto simp add: Fun.swap_def)\n\nlemma inv_swap_id: \"inv (Fun.swap a b id) = Fun.swap a b id\"\n  by simp\n\nlemma bij_swap_comp:\n  assumes \"bij p\"\n  shows \"Fun.swap a b id \\<circ> p = Fun.swap (inv p a) (inv p b) p\"\n  using assms by (simp add: transpose_comp_eq) \n\nlemma swap_id_eq: \"Fun.swap a b id x = (if x = a then b else if x = b then a else x)\"\n  by (simp add: Fun.swap_def)\n\nlemma swap_unfold:\n  \\<open>Fun.swap a b p = p \\<circ> Fun.swap a b id\\<close>\n  by simp\n\nlemma swap_id_idempotent: \"Fun.swap a b id \\<circ> Fun.swap a b id = id\"\n  by simp\n\nlemma bij_swap_compose_bij:\n  \\<open>bij (Fun.swap a b id \\<circ> p)\\<close> if \\<open>bij p\\<close>\n  using that by (rule bij_comp) simp\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/Transposition.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.84594244507642, "lm_q2_score": 0.8459424353665381, "lm_q1q2_score": 0.7156186121678707}}
{"text": "(*  Title:       Examples of hybrid systems verifications\n    Author:      Jonathan Juli\u00e1n Huerta y Munive, 2020\n    Maintainer:  Jonathan Juli\u00e1n 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\nrecently described verification components.\\<close>\n\ntheory HS_VC_PT_Examples\n  imports HS_VC_PT\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 by providing the dynamics\\<close>\n\nlemma pendulum_dyn: \"{s. r\\<^sup>2 = (s$1)\\<^sup>2 + (s$2)\\<^sup>2} \\<le> fb\\<^sub>\\<F> (EVOL \\<phi> G T) {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: \"{s. r\\<^sup>2 = (s$1)\\<^sup>2 + (s$2)\\<^sup>2} \\<le> fb\\<^sub>\\<F> (x\\<acute>= f & G) {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: \"{s. r\\<^sup>2 = (s$1)\\<^sup>2 + (s$2)\\<^sup>2} \\<le> fb\\<^sub>\\<F> (x\\<acute>= f & G) {s. r\\<^sup>2 = (s$1)\\<^sup>2 + (s$2)\\<^sup>2}\"\n  by (force simp: local_flow.ffb_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 bouncing_ball_inv: \"g < 0 \\<Longrightarrow> h \\<ge> 0 \\<Longrightarrow>\n  {s. s$1 = h \\<and> s$2 = 0} \\<le> fb\\<^sub>\\<F>\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  {s. 0 \\<le> s$1 \\<and> s$1 \\<le> h}\"\n  apply(rule ffb_loopI, simp_all)\n    apply(force, force simp: bb_real_arith)\n  apply(rule ffb_g_odei)\n  by (auto intro!: diff_invariant_rules poly_derivatives simp: bb_real_arith)\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> * (g * \\<tau> + v) + 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> * (g * \\<tau> + v) + 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  {s. s$1 = h \\<and> s$2 = 0} \\<le> fb\\<^sub>\\<F>\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  {s. 0 \\<le> s$1 \\<and> s$1 \\<le> h}\"\n  by (rule ffb_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  {s. s$1 = h \\<and> s$2 = 0} \\<le> fb\\<^sub>\\<F>\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  {s. 0 \\<le> s$1 \\<and> s$1 \\<le> h}\"\n  by (rule ffb_loopI) (auto simp: bb_real_arith local_flow.ffb_g_ode[OF local_flow_ball])\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_all 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 ffb_temp_dyn = local_flow.ffb_g_ode_ivl[OF local_flow_temp _ UNIV_I]\n\nlemma thermostat:\n  assumes \"a > 0\" and \"0 \\<le> t\" and \"0 < Tmin\" and \"Tmax < L\"\n  shows \"{s. Tmin \\<le> s$1 \\<and> s$1 \\<le> Tmax \\<and> s$4 = 0} \\<le> fb\\<^sub>\\<F>\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>=(\\<lambda>t. f a 0) & (\\<lambda>s. s$2 \\<le> - (ln (Tmin/s$3))/a) on (\\<lambda>s. {0..t}) UNIV @ 0)\n    ELSE (x\\<acute>=(\\<lambda>t. f a L) & (\\<lambda>s. s$2 \\<le> - (ln ((L-Tmax)/(L-s$3)))/a) on (\\<lambda>s. {0..t}) UNIV @ 0)) )\n  INV (\\<lambda>s. Tmin \\<le>s$1 \\<and> s$1 \\<le> Tmax \\<and> (s$4 = 0 \\<or> s$4 = 1)))\n  {s. Tmin \\<le> s$1 \\<and> s$1 \\<le> Tmax}\"\n  apply(rule ffb_loopI, simp_all add: ffb_temp_dyn[OF assms(1,2)] le_fun_def, safe)\n  using temp_dyn_up_real_arith[OF assms(1) _ _ assms(4), of Tmin]\n    and temp_dyn_down_real_arith[OF assms(1,3), 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 \"Collect (I hmin hmax) \\<le> fb\\<^sub>\\<F>\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  (Collect (I hmin hmax))\"\n  apply(rule ffb_loopI, simp_all add: le_fun_def)\n  apply(clarsimp simp: le_fun_def local_flow.ffb_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/PredicateTransformers/HS_VC_PT_Examples.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8459424373085145, "lm_q2_score": 0.8459424373085146, "lm_q1q2_score": 0.71561860723947}}
{"text": "(* Title: Kleene Algebra\n   Author: Peixin You\n*)\n\nsection \\<open>Kleene Algebra\\<close>\n\ntheory KA\n  imports Main\n\nbegin\n\nsubsection \\<open>Monoids\\<close>\n\nnotation times (infixl \"\\<cdot>\" 70)\n\nclass mult_monoid = times + one +\n  assumes mult_assoc: \"x \\<cdot> (y \\<cdot> z) = (x \\<cdot> y) \\<cdot> z\"\n  and mult_unitl: \"1 \\<cdot> x = x\"\n  and mult_unitr: \"x \\<cdot> 1 = x\"\n\nclass add_monoid = plus + zero +\n  assumes add_assoc: \"x + (y + z) = (x + y) + z\"\n  and add_unitl: \"0 + x = x\"\n  and add_unitr: \"x + 0 = x\"\n\nclass abelian_add_monoid = add_monoid +\n  assumes add_comm: \"x + y = y + x\"\n\n\nsubsection \\<open>Semilattices\\<close>\n\nclass sup_semilattice = comm_monoid_add + ord +\n  assumes add_idem: \"x + x = x\"\n  and order_def: \"x \\<le> y \\<longleftrightarrow> x + y = y\"\n  and strict_order_def: \"x < y \\<longleftrightarrow> x \\<le> y \\<and> x \\<noteq> y\"\n\nbegin\n\nsubclass order \nproof unfold_locales\n  fix x y z\n  show \"(x < y) = (x \\<le> y \\<and> \\<not> y \\<le> x)\"\n    using add_commute order_def strict_order_def by auto\n  show \"x \\<le> x\"\n    by (simp add: add_idem order_def)\n  show \"x \\<le> y \\<Longrightarrow> y \\<le> z \\<Longrightarrow> x \\<le> z\"\n    by (metis add_assoc order_def)\n  show \"x \\<le> y \\<Longrightarrow> y \\<le> x \\<Longrightarrow> x = y\"\n    by (simp add: add_commute order_def)\nqed\n\nlemma zero_least: \"0 \\<le> x\"\nproof-\n  have \"0 + x = x\"\n    by simp\n  thus \"0 \\<le> x\"\n    by (simp add: order_def)\nqed\n\nlemma add_isor: \"x \\<le> y \\<Longrightarrow> x + z \\<le> y + z\" \nproof-\n  assume \"x \\<le> y\"\n  hence a: \"x + y = y\"\n    by (simp add: order_def)\n  have \"x + z + y + z = x + y + z\"\n    by (metis add_commute local.add_assoc local.add_idem)\n  also have \"\\<dots> = y + z\"\n    by (simp add: a)\n  finally have \"x + z + y + z = y + z\".\n  thus \"x + z \\<le> y + z\"\n    by (simp add: add_assoc order_def)\nqed\n\ntext \\<open>This proof shows three things: First you can use the label a: to use a hypothesis/intermediate result \nlater in a proof (not just in the next step writing hence. In this case in the third step of the proof. \nSecond you can do textbook style equational reasoning using also have and finally have. Third, you can type  dot after the finally \nhave to chain the proof steps together.\\<close>\n\nlemma add_iso: \"x \\<le> y \\<Longrightarrow> x' \\<le> y' \\<Longrightarrow> x + x' \\<le> y + y'\"\nproof-\n  assume a: \"x \\<le> y\"\n  assume b: \"x'\\<le> y'\"\n  have c: \"x + y = y\"\n    using a local.order_def by force\n  have d: \"x' + y' = y'\"\n    using b local.order_def by force\n  have \"x + x' + y + y' = y + x' + y'\"\n    by (metis add_commute c local.add_assoc)\n  also have \"\\<dots> = y + y'\"\n    by (simp add: d local.add_assoc)\n  finally show \"x + x' \\<le> y + y'\"\n    by (simp add: local.add_assoc local.order_def)\nqed\n\nlemma add_ubl: \"x \\<le> x + y\" \nproof-\n  have \"x + y = x + x + y\"\n    by (simp add: add_idem)\n  thus ?thesis\n    by (metis add_assoc order_def)\nqed\n\nlemma add_ubr: \"y \\<le> x + y\"\n  using add_commute add_ubl by fastforce\n\nlemma add_least: \"x \\<le> z \\<Longrightarrow> y \\<le> z \\<Longrightarrow> x + y \\<le> z\" \nproof-\n  assume \"x \\<le> z\" and \"y \\<le> z\"\n  hence \"x + z = z\" and \"y + z = z\"\n    by (simp add: order_def)+\n  hence \"x + y + z = z\"\n    by (simp add: add_assoc)\n  thus \"x + y \\<le> z\"\n    by (simp add: order_def)\nqed\n\nlemma add_lub: \"(x + y \\<le> z) = (x \\<le> z \\<and> y \\<le> z)\"\n  using add_least add_ubl add_ubr dual_order.trans by blast\n\nend\n\n\nsubsection \\<open>Semirings and Dioids\\<close>\n\nclass semiring = comm_monoid_add + monoid_mult +\n  assumes distl: \"x \\<cdot> (y + z) = x \\<cdot> y + x \\<cdot> z\"\n  and distr: \"(x + y) \\<cdot> z = x \\<cdot> z + y \\<cdot> z\"\n  and annil [simp]: \"0 \\<cdot> x = 0\"\n  and annir [simp]: \"x \\<cdot> 0 = 0\"\n\nclass dioid = semiring + sup_semilattice\n\nbegin\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: order_def)\n  hence \"z \\<cdot> (x + y) = z \\<cdot> y\"\n    by simp\n  hence \"z \\<cdot> x + z \\<cdot> y = z \\<cdot> y\"\n    by (simp add: distl)\n  thus \"z \\<cdot> x \\<le> z \\<cdot> y\"\n    by (simp add: order_def)\nqed\n\nlemma mult_isor: \"x \\<le> y \\<Longrightarrow> x \\<cdot> z \\<le> y \\<cdot> z\"\n  by (metis distr order_def)\n\nlemma mult_iso: \"x \\<le> y \\<Longrightarrow> x' \\<le> y' \\<Longrightarrow> x \\<cdot> x' \\<le> y \\<cdot> y'\"\n  using order_trans mult_isol mult_isor by blast\n\nend\n\nsubsection \\<open>Kleene Algebras\\<close>\n\nclass kleene_algebra = dioid + \n  fixes star :: \"'a \\<Rightarrow> 'a\" (\"_\\<^sup>\\<star>\" [101] 100)\n  assumes star_unfoldl: \"1 + x \\<cdot> x\\<^sup>\\<star> \\<le> x\\<^sup>\\<star>\"  \n  and star_unfoldr: \"1 + x\\<^sup>\\<star> \\<cdot> x \\<le> x\\<^sup>\\<star>\"\n  and star_inductl: \"z + x \\<cdot> y \\<le> y \\<Longrightarrow> x\\<^sup>\\<star> \\<cdot> z \\<le> y\"\n  and star_inductr: \"z + y \\<cdot> x \\<le> y \\<Longrightarrow> z \\<cdot> x\\<^sup>\\<star> \\<le> y\"\n\nbegin\n\nlemma one_le_star: \"1 \\<le> x\\<^sup>\\<star>\" \nproof-\n  have \"1 + x \\<cdot> x\\<^sup>\\<star> \\<le> x\\<^sup>\\<star>\"\n    by (simp add: star_unfoldl) \n  thus \"1 \\<le> x\\<^sup>\\<star>\"\n    by (simp add: add_lub)\nqed\n\nlemma star_unfoldlr: \"x \\<cdot> x\\<^sup>\\<star> \\<le> x\\<^sup>\\<star>\"\n  using add_lub star_unfoldl by simp\n\nlemma star_unfoldrr: \"x\\<^sup>\\<star> \\<cdot> x \\<le> x\\<^sup>\\<star>\"\n  using add_lub star_unfoldr by simp\n\nlemma star_infl: \"x \\<le> x\\<^sup>\\<star>\" \nproof-\n  have \"x = x \\<cdot> 1\"\n    by simp\n  also have \"\\<dots> \\<le> x \\<cdot> x\\<^sup>\\<star>\"\n    using mult_isol one_le_star by force\n  also have \"\\<dots> \\<le> x\\<^sup>\\<star>\"\n    by (simp add: star_unfoldlr)\n  finally show \"x \\<le> x\\<^sup>\\<star>\".\nqed\n\nlemma star_power: \"x ^ i \\<le> x\\<^sup>\\<star>\"\nproof (induct i)\ncase 0\n  show \"x ^ 0 \\<le> x\\<^sup>\\<star>\"\n    by (simp add: one_le_star)\nnext\n  case (Suc i)\n  assume \"x ^ i \\<le> x\\<^sup>\\<star>\"\n  have \"x ^ Suc i = x \\<cdot> x ^ i\"\n    by simp\n  also have \"\\<dots> \\<le> x \\<cdot> x\\<^sup>\\<star>\"\n    by (simp add: Suc.hyps mult_isol)\n  also have \"\\<dots>  \\<le> x\\<^sup>\\<star>\"\n    by (simp add: star_unfoldlr)\n  finally show \"x ^ Suc i \\<le> x\\<^sup>\\<star>\".\nqed\n\nlemma star_trans [simp]: \"x\\<^sup>\\<star> \\<cdot> x\\<^sup>\\<star> = x\\<^sup>\\<star>\" \nproof (rule antisym)\n  have \"x\\<^sup>\\<star> + x \\<cdot> x\\<^sup>\\<star> \\<le> x\\<^sup>\\<star>\"\n    by (simp add: add_least star_unfoldlr)\n  thus \"x\\<^sup>\\<star> \\<cdot> x\\<^sup>\\<star> \\<le> x\\<^sup>\\<star>\"\n    by (simp add: star_inductl)\n  have \"x\\<^sup>\\<star> = 1 \\<cdot> x\\<^sup>\\<star>\"\n    by simp\n  also have \"\\<dots> \\<le> x\\<^sup>\\<star> \\<cdot> x\\<^sup>\\<star>\"\n    using mult_isor one_le_star by force\n  finally show \"x\\<^sup>\\<star> \\<le> x\\<^sup>\\<star> \\<cdot> x\\<^sup>\\<star>\".\nqed\n\nlemma star_idem [simp]: \"(x\\<^sup>\\<star>)\\<^sup>\\<star> = x\\<^sup>\\<star>\" \nproof (rule antisym)\n  have \"1 + x\\<^sup>\\<star> \\<cdot> x\\<^sup>\\<star> \\<le> x\\<^sup>\\<star>\"\n    by (simp add: add_least one_le_star)\n  thus  \"(x\\<^sup>\\<star>)\\<^sup>\\<star> \\<le> x\\<^sup>\\<star>\"\n    using star_inductl by fastforce\n  show \"x\\<^sup>\\<star> \\<le> (x\\<^sup>\\<star>)\\<^sup>\\<star>\"\n    by (simp add: star_infl)\nqed\n\nlemma star_unfoldl_eq [simp]: \"1 + x \\<cdot> x\\<^sup>\\<star> = x\\<^sup>\\<star>\"  \nproof (rule antisym)\n  show le: \"1 + x \\<cdot> x\\<^sup>\\<star> \\<le> x\\<^sup>\\<star>\" \n    by (simp add: star_unfoldl) \n  have \"1 + x \\<cdot> (1 + x \\<cdot> x\\<^sup>\\<star>) = 1 + x + x \\<cdot> x \\<cdot> x\\<^sup>\\<star>\"\n    by (simp add: add_assoc distl mult_assoc)\n  also have \"\\<dots> \\<le> 1 + x \\<cdot> x\\<^sup>\\<star>\"\n    by (smt calculation le add_assoc distl add_idem order_def)\n  finally have \"1 + x \\<cdot> (1 + x \\<cdot> x\\<^sup>\\<star>) \\<le> 1 + x \\<cdot> x\\<^sup>\\<star>\".\n  thus \"x\\<^sup>\\<star> \\<le> 1 + x \\<cdot> x\\<^sup>\\<star>\"\n    using star_inductl by fastforce\nqed\n\nlemma star_unfoldr_eq [simp]: \"1 + x\\<^sup>\\<star> \\<cdot> x = x\\<^sup>\\<star>\"\n   apply (rule antisym)\n   apply (simp add: star_unfoldr)\n  by (smt distl distr mult.semigroup_axioms mult_1_left mult_1_right order_refl star_inductl semigroup.assoc star_unfoldl_eq)\n\nlemma star_iso: \"x \\<le> y \\<Longrightarrow> x\\<^sup>\\<star> \\<le> y\\<^sup>\\<star>\" \nproof-\n  assume \"x \\<le> y\"\n  hence \"1 + x \\<cdot> y\\<^sup>\\<star> \\<le> 1 + y \\<cdot> y\\<^sup>\\<star>\"\n    using add_iso mult_iso by blast\n  also have \"\\<dots> \\<le> y\\<^sup>\\<star>\"\n    by (simp add: star_unfoldl)\n  finally show \" x\\<^sup>\\<star> \\<le> y\\<^sup>\\<star>\"\n    using star_inductl by fastforce\nqed\n\nlemma star_slide: \"(x \\<cdot> y)\\<^sup>\\<star> \\<cdot> x = x \\<cdot> (y \\<cdot> x)\\<^sup>\\<star>\" \nproof (rule antisym)\n  have \"1 + y \\<cdot> x \\<cdot> (y \\<cdot> x)\\<^sup>\\<star> \\<le> (y \\<cdot> x)\\<^sup>\\<star>\"\n    by (simp add: star_unfoldl)\n  hence \"x + x \\<cdot> y \\<cdot> x \\<cdot> (y \\<cdot> x)\\<^sup>\\<star> \\<le> x \\<cdot> (y \\<cdot> x)\\<^sup>\\<star>\"\n    by (metis distl eq_iff mult_1_right mult_assoc star_unfoldl_eq)\n  thus \"(x \\<cdot> y)\\<^sup>\\<star> \\<cdot> x \\<le> x \\<cdot> (y \\<cdot> x)\\<^sup>\\<star>\"\n    by (simp add: star_inductl mult_assoc)\n  have \"1 + (x \\<cdot> y)\\<^sup>\\<star> \\<cdot> x \\<cdot> y \\<le> (x \\<cdot> y)\\<^sup>\\<star>\"\n    by (simp add: mult_assoc)\n  hence \"x + (x \\<cdot> y)\\<^sup>\\<star> \\<cdot> x \\<cdot> y \\<cdot> x \\<le> (x \\<cdot> y)\\<^sup>\\<star> \\<cdot> x\"\n    by (metis distr eq_refl mult_1_left mult_assoc star_unfoldr_eq)\n  thus \"x \\<cdot> (y \\<cdot> x)\\<^sup>\\<star> \\<le> (x \\<cdot> y)\\<^sup>\\<star> \\<cdot> x\"\n    by (simp add: star_inductr mult_assoc)\nqed\n\nlemma star_denest: \"(x + y)\\<^sup>\\<star> = x\\<^sup>\\<star> \\<cdot> (y \\<cdot> x\\<^sup>\\<star>)\\<^sup>\\<star>\" \nproof (rule antisym)\n  have a: \"1 \\<le> x\\<^sup>\\<star> \\<cdot> (y \\<cdot> x\\<^sup>\\<star>)\\<^sup>\\<star>\"\n    by (metis mult_1_right mult_isol order_trans one_le_star)\n  have b: \"x \\<cdot> x\\<^sup>\\<star> \\<cdot> (y \\<cdot> x\\<^sup>\\<star>)\\<^sup>\\<star> \\<le> x\\<^sup>\\<star> \\<cdot> (y \\<cdot> x\\<^sup>\\<star>)\\<^sup>\\<star>\"\n    by (simp add: mult_isor star_unfoldlr)\n  have \"y \\<cdot> x\\<^sup>\\<star> \\<cdot> (y \\<cdot> x\\<^sup>\\<star>)\\<^sup>\\<star> \\<le> (y \\<cdot> x\\<^sup>\\<star>)\\<^sup>\\<star>\"\n    by (simp add: star_unfoldlr)\n  also have  \"\\<dots> = 1 \\<cdot> (y \\<cdot> x\\<^sup>\\<star>)\\<^sup>\\<star>\"\n    by simp\n  also have \"\\<dots> \\<le>  x\\<^sup>\\<star> \\<cdot> (y \\<cdot> x\\<^sup>\\<star>)\\<^sup>\\<star>\"\n    using mult_isor one_le_star by blast\n  finally have \"y \\<cdot> x\\<^sup>\\<star> \\<cdot> (y \\<cdot> x\\<^sup>\\<star>)\\<^sup>\\<star> \\<le> x\\<^sup>\\<star> \\<cdot> (y \\<cdot> x\\<^sup>\\<star>)\\<^sup>\\<star>\".\n  hence \"1 + (x + y) \\<cdot> x\\<^sup>\\<star> \\<cdot> (y \\<cdot> x\\<^sup>\\<star>)\\<^sup>\\<star> \\<le> x\\<^sup>\\<star> \\<cdot> (y \\<cdot> x\\<^sup>\\<star>)\\<^sup>\\<star>\"\n    by (simp add: a b add_lub distr)\n  thus  \"(x + y)\\<^sup>\\<star> \\<le> x\\<^sup>\\<star> \\<cdot> (y \\<cdot> x\\<^sup>\\<star>)\\<^sup>\\<star>\"\n    using mult_assoc star_inductl by fastforce\n  have a: \"x\\<^sup>\\<star> \\<le> (x + y)\\<^sup>\\<star>\"\n    by (simp add: add_ubl star_iso)\n  have \"y \\<le> (x + y)\\<^sup>\\<star>\"\n    using add_lub star_infl by blast\n  hence \"(y \\<cdot> x\\<^sup>\\<star>)\\<^sup>\\<star> \\<le> ((x + y)\\<^sup>\\<star> \\<cdot> (x + y)\\<^sup>\\<star>)\\<^sup>\\<star>\"\n    using a mult_iso star_iso by blast\n  also have \"\\<dots> = (x + y)\\<^sup>\\<star>\"\n    by simp\n  finally have \"(y \\<cdot> x\\<^sup>\\<star>)\\<^sup>\\<star> \\<le> (x + y)\\<^sup>\\<star>\".\n  hence \"x\\<^sup>\\<star> \\<cdot> (y \\<cdot> x\\<^sup>\\<star>)\\<^sup>\\<star> \\<le> (x + y)\\<^sup>\\<star> \\<cdot> (x + y)\\<^sup>\\<star>\"\n    using a mult_iso by blast\n  also have \"\\<dots> \\<le> (x + y)\\<^sup>\\<star>\"\n    by simp\n  finally show \"x\\<^sup>\\<star> \\<cdot> (y \\<cdot> x\\<^sup>\\<star>)\\<^sup>\\<star> \\<le> (x + y)\\<^sup>\\<star>\".\nqed\n\nlemma star_subid: \"x \\<le> 1 \\<Longrightarrow> x\\<^sup>\\<star> = 1\"\nproof-\n  assume \"x \\<le> 1\" \n  hence \"1 + x \\<cdot> 1 \\<le> 1\"\n    by (simp add: add_least)\n  hence \"x\\<^sup>\\<star> \\<le> 1\"\n    using star_inductl by fastforce\n  thus \" x\\<^sup>\\<star> = 1\"\n    by (simp add: antisym one_le_star)\nqed\n\nlemma zero_star [simp]: \"0\\<^sup>\\<star> = 1\" \n  by (simp add: zero_least star_subid)\n\nlemma one_star [simp]: \"1\\<^sup>\\<star> = 1\" \n  by (simp add: star_subid)\n\nlemma star_sim1: \"z \\<cdot> x \\<le> y \\<cdot> z \\<Longrightarrow> z \\<cdot> x\\<^sup>\\<star> \\<le> y\\<^sup>\\<star> \\<cdot> z\" \nproof - \n  assume \"z \\<cdot> x \\<le> y \\<cdot> z\"\n  hence \"z + y\\<^sup>\\<star> \\<cdot> z \\<cdot> x \\<le> z + y\\<^sup>\\<star> \\<cdot> y \\<cdot> z\"\n    by (simp add: add_iso mult_assoc mult_iso)\n  also have  \"\\<dots> = y\\<^sup>\\<star> \\<cdot> z\"\n    by (metis distr mult_1_left star_unfoldr_eq)\n  finally show ?thesis\n    by (simp add: star_inductr) \nqed\n\nlemma star_sim2: \"x \\<cdot> z \\<le> z \\<cdot> y \\<Longrightarrow> x\\<^sup>\\<star> \\<cdot> z  \\<le> z \\<cdot> y\\<^sup>\\<star>\"\n  by (smt add_commute add_assoc distl distr mult_1_right mult_assoc order_def star_inductl one_le_star star_unfoldl_eq)\n\nlemma star_inductl_var: \"x \\<cdot> y \\<le> y \\<Longrightarrow> x\\<^sup>\\<star> \\<cdot> y \\<le> y\" \nproof-\n  assume \"x \\<cdot> y \\<le> y\"\n  hence \"y + x \\<cdot> y \\<le> y\"\n    by (simp add: add_lub)\n  thus \"x\\<^sup>\\<star> \\<cdot> y \\<le> y\"\n    by (simp add: star_inductl)\nqed\n\nlemma star_inductr_var: \"y \\<cdot> x \\<le> y \\<Longrightarrow> y \\<cdot> x\\<^sup>\\<star> \\<le> y\"\n  by (simp add: add_least star_inductr)\n\nlemma church_rosser: \"y\\<^sup>\\<star> \\<cdot> x\\<^sup>\\<star> \\<le> x\\<^sup>\\<star> \\<cdot> y\\<^sup>\\<star> \\<Longrightarrow> (x + y)\\<^sup>\\<star> = x\\<^sup>\\<star> \\<cdot> y\\<^sup>\\<star>\" \nproof-\n  assume h: \"y\\<^sup>\\<star> \\<cdot> x\\<^sup>\\<star> \\<le> x\\<^sup>\\<star> \\<cdot> y\\<^sup>\\<star>\"\n  have a: \"1 \\<le> x\\<^sup>\\<star> \\<cdot> y\\<^sup>\\<star>\"\n    by (metis dual_order.trans mult_1_right mult_isol one_le_star)\n  have b: \"x \\<cdot> x\\<^sup>\\<star> \\<cdot> y\\<^sup>\\<star> \\<le> x\\<^sup>\\<star> \\<cdot> y\\<^sup>\\<star>\"\n    by (simp add: mult_isor star_unfoldlr)\n  have \"y \\<cdot> x\\<^sup>\\<star> \\<cdot> y\\<^sup>\\<star> \\<le> y\\<^sup>\\<star> \\<cdot> x\\<^sup>\\<star> \\<cdot> y\\<^sup>\\<star>\"\n    by (simp add: mult_isor star_infl)\n  also have \"\\<dots> \\<le> x\\<^sup>\\<star> \\<cdot> y\\<^sup>\\<star> \\<cdot> y\\<^sup>\\<star>\"\n    by (simp add: h mult_isor)\n  finally have \"y \\<cdot> x\\<^sup>\\<star> \\<cdot> y\\<^sup>\\<star> \\<le> x\\<^sup>\\<star> \\<cdot> y\\<^sup>\\<star>\"\n    by (metis mult_assoc star_trans)\n  hence \"1 + (x + y) \\<cdot> x\\<^sup>\\<star> \\<cdot> y\\<^sup>\\<star> \\<le> x\\<^sup>\\<star> \\<cdot> y\\<^sup>\\<star>\"\n    by (simp add: a b add_lub distr)\n  hence c: \"(x + y)\\<^sup>\\<star> \\<le> x\\<^sup>\\<star> \\<cdot> y\\<^sup>\\<star>\"\n    using mult_assoc star_inductl by fastforce\n  have \"y\\<^sup>\\<star> \\<le> (x + y)\\<^sup>\\<star>\"\n    by (simp add: add_ubr star_iso)\n  hence \"x\\<^sup>\\<star> \\<cdot> y\\<^sup>\\<star> \\<le> (x + y)\\<^sup>\\<star> \\<cdot> (x + y)\\<^sup>\\<star>\"\n    using add_commute add_ubr mult_iso star_iso by presburger\n  hence \"x\\<^sup>\\<star> \\<cdot> y\\<^sup>\\<star> \\<le> (x + y)\\<^sup>\\<star>\"\n    by simp\n  thus \"(x + y)\\<^sup>\\<star> = x\\<^sup>\\<star> \\<cdot> y\\<^sup>\\<star>\"\n    using c by auto\nqed\n\nlemma power_sup: \"((\\<Sum>i=0..n. x^i) \\<le> y) = (\\<forall>i. 0 \\<le> i \\<and> i \\<le> n \\<longrightarrow> x^i \\<le> y)\"\nproof (induct n)\n  case 0\n  show \"(sum ((^) x) {0..0} \\<le> y) = (\\<forall>i. 0 \\<le> i \\<and> i \\<le> 0 \\<longrightarrow> x ^ i \\<le> y)\"\n    by simp\nnext\n  case (Suc n)\n  fix n :: nat\n  assume \"(sum ((^) x) {0..n} \\<le> y) = (\\<forall>i. 0 \\<le> i \\<and> i \\<le> n \\<longrightarrow> x ^ i \\<le> y)\"\n  thus \"(sum ((^) x) {0..Suc n} \\<le> y) = (\\<forall>i. 0 \\<le> i \\<and> i \\<le> Suc n \\<longrightarrow> x ^ i \\<le> y)\"\n    using le_Suc_eq local.add_lub by force\nqed\n\nlemma power_dist: \"(\\<Sum>i=0..n. x ^ i) \\<cdot> x = (\\<Sum>i=0..n. x ^ Suc i)\"\nproof (induct n)\n  case 0\n  show ?case by simp\nnext \n  case (Suc n)\n  show ?case\n    using Suc local.distr local.power_Suc2 local.sum.atLeast0_atMost_Suc by presburger \nqed\n\nlemma power_sum: \"(\\<Sum>i=0..n. x ^ Suc i) = (\\<Sum>i=1..n. x ^ i) + x ^ Suc n\"\nproof (induct n)\n  case 0\n  show ?case by simp\nnext \n  case (Suc n)\n  show ?case\n    using Suc.hyps by force\nqed\n\nlemma sum_star: \"x\\<^sup>\\<star> = (x ^ Suc n)\\<^sup>\\<star> \\<cdot> (\\<Sum>i=0..n. x ^ i)\"\nproof (rule antisym)\n  have \"1 + (x ^ Suc n)\\<^sup>\\<star> \\<cdot> (\\<Sum>i=0..n. x ^ i) \\<cdot> x = 1 + (x ^ Suc n)\\<^sup>\\<star> \\<cdot> (\\<Sum>i=0..n. x ^ Suc i)\"\n    using local.mult_assoc power_dist by presburger\n  also have \"\\<dots> =  1 + (x ^ Suc n)\\<^sup>\\<star> \\<cdot> (\\<Sum>i=1..n. x ^ i) + (x ^ Suc n)\\<^sup>\\<star> \\<cdot> x ^ Suc n\"\n    using local.add_assoc local.distl local.power_sum by presburger\n  also have \"\\<dots> = (x ^ Suc n)\\<^sup>\\<star> \\<cdot> (\\<Sum>i=1..n. x ^ i) + (x ^ Suc n)\\<^sup>\\<star>\"\n    by (metis local.add.left_commute local.add_assoc star_unfoldr_eq)\n  also have \"\\<dots> = (x ^ Suc n)\\<^sup>\\<star> \\<cdot> (1 + (\\<Sum>i=1..n. x ^ i))\"\n    using add_commute local.distl local.mult_1_right by presburger\n  also have \"\\<dots> = (x ^ Suc n)\\<^sup>\\<star> \\<cdot> (\\<Sum>i=0..n. x ^ i)\"\n    by (simp add: local.sum.atLeast_Suc_atMost)\n  finally show \"x\\<^sup>\\<star> \\<le> (x ^ Suc n)\\<^sup>\\<star> \\<cdot> sum ((^) x) {0..n}\"\n    by (metis local.mult_1_left local.order_refl local.star_inductr)\nnext\n  have a: \"(x ^ Suc n)\\<^sup>\\<star> \\<le> x\\<^sup>\\<star>\"\n    by (metis star_idem star_iso star_power)\n  have \"(\\<Sum>i=0..n. x ^ i) \\<le> x\\<^sup>\\<star>\"\n    using power_sup star_power by presburger\n  thus \"(x ^ Suc n)\\<^sup>\\<star> \\<cdot> sum ((^) x) {0..n} \\<le> x\\<^sup>\\<star>\"\n    by (metis a local.mult_iso star_trans)\nqed\n\nend\n\nsubsection \\<open>Linking Algebras with Models by Instantiation\\<close>\n\ninstantiation nat :: mult_monoid\nbegin\n\ninstance\nproof\n  fix x y z :: nat\n  show \"x \\<cdot> (y \\<cdot> z) = (x \\<cdot> y) \\<cdot> z\"\n    by simp\n  show \"1 \\<cdot> x = x\"\n    by simp\n  show \"x \\<cdot> 1 = x \"\n    by simp\nqed\n\nend\n\ninstantiation nat :: abelian_add_monoid\nbegin\n\ninstance\nproof\n  fix x y z :: nat\n  show \"x + (y + z) = (x + y) + z\"\n    by simp\n  show \"0 + x = x\"\n    by simp\n  show \"x + 0 = x \"\n    by simp\n  show \"x + y = y + x\"\n    by simp\nqed\n\nend\n\ntypedef 'a endo = \"{f::'a \\<Rightarrow> 'a . True}\"\n  by simp\n\nsetup_lifting type_definition_endo\n\ninstantiation endo :: (type) mult_monoid\nbegin\n\nlift_definition one_endo :: \"'a endo\" is\n  \"Abs_endo id\".\n\nlift_definition times_endo :: \"'a endo \\<Rightarrow> 'a endo \\<Rightarrow> 'a endo\" is\n  \"\\<lambda>x y. Abs_endo (Rep_endo x \\<circ> Rep_endo y)\".\n\ninstance\nproof\n  fix x y z :: \"'a endo\"\n  show \"x \\<cdot> (y \\<cdot> z) = (x \\<cdot> y) \\<cdot> z\"\n    by transfer (simp add: Abs_endo_inverse fun.map_comp)\n  show \"1 \\<cdot> x = x\"\n    by transfer (simp add: Abs_endo_inverse Rep_endo_inverse)\n  show \"x \\<cdot> 1 = x \"\n    by transfer (simp add: Abs_endo_inverse Rep_endo_inverse)\nqed\n\nend \n\ninstantiation set :: (type) sup_semilattice\nbegin\n\ndefinition plus_set :: \"'a set \\<Rightarrow> 'a set \\<Rightarrow> 'a set\" where\n  \"plus_set x y = x \\<union> y\"\n\ndefinition zero_set :: \"'a set\" where \n  \"zero_set = {}\"\n\ninstance \nproof\n  fix x y z :: \"'a set\"\n  show \"x + y + z = x + (y + z)\"\n    by (simp add: KA.plus_set_def sup_assoc)\n  show \"0 + x = x\"\n    by (simp add: plus_set_def zero_set_def)\n  show \"x + x = x\"\n    by (simp add: KA.plus_set_def)\n  show \"x + y = y + x\"\n    by (simp add: KA.plus_set_def sup_commute)\n  show \"(x \\<subseteq> y) = (x + y = y)\"\n    by (simp add: KA.plus_set_def subset_Un_eq)\n  show \"(x \\<subset> y) = (x \\<subseteq> y \\<and> x \\<noteq> y)\"\n    by force\nqed\n\nend\n\ninterpretation inter_sl: sup_semilattice \"(\\<inter>)\" UNIV \"(\\<supseteq>)\" \"(\\<supset>)\"\nproof \n  fix X Y Z :: \"'a set\"\n  show \"X \\<inter> Y \\<inter> Z = X \\<inter> (Y \\<inter> Z)\"\n    by (simp add: Int_assoc)\n  show \"X \\<inter> Y = Y \\<inter> X\"\n    by (simp add: inf_commute)\n  show \"UNIV \\<inter> X = X\"\n    by simp\n  show \"X \\<inter> X = X\"\n    by simp \n  show \"(Y \\<subseteq> X) = (X \\<inter> Y = Y)\"\n    by blast\n  show \"(Y \\<subset> X) = (Y \\<subseteq> X \\<and> X \\<noteq> Y)\"\n    by auto\nqed\n\ncontext dioid\nbegin\n\nlemma power_inductl: \"z + x \\<cdot> y \\<le> y \\<Longrightarrow> x ^ i \\<cdot> z \\<le> y\"\nproof (induct i)\n  case 0\n  have \"x ^ 0 \\<cdot> z = z\"\n    by simp\n  also have \"\\<dots> \\<le> y\"\n    using \"0.prems\" local.add_lub by fastforce\n  finally show ?case.\nnext\n  case (Suc i)\n  have \"x ^ Suc i \\<cdot> z = x \\<cdot> x ^ i \\<cdot> z\"\n    by simp\n  also have \"\\<dots> \\<le> x \\<cdot> y\"\n    by (simp add: Suc.hyps Suc.prems local.mult_assoc local.mult_isol)\n  also have \"\\<dots> \\<le> y\"\n    using Suc.prems local.add_lub by auto\n  finally show ?case.\nqed\n\nlemma power_inductr: \"z + y \\<cdot> x \\<le> y \\<Longrightarrow> z \\<cdot> x ^ i \\<le> y\"\nproof (induct i)\ncase 0\n  thus ?case\n    by (simp add: add_lub)\nnext\n  case (Suc i)\n  thus ?case\n    by (smt add_lub distr mult_assoc order_def power_Suc2)\nqed\n\nend\n\nsubsection \\<open>Relational Model of Kleene algebra\\<close>\n\nnotation relcomp (infixl \";\" 70)\n\ntext \\<open>rel is not a type in Isabelle, so we need to do an interpretation statement instead of an \ninstantiation. That for dioids (Proposition 4.5) is trivial because relations are well supported\nin Isabelle.\\<close>\n\ninterpretation rel_d: dioid \"(\\<union>)\" \"{}\" Id \"(;)\" \"(\\<subseteq>)\" \"(\\<subset>)\"\n  by unfold_locales auto\n\nlemma power_is_relpow: \"rel_d.power R i = R ^^ i\"\n  by (induct i) (simp_all add: relpow_commute)\n\nlemma rel_star_def: \"R\\<^sup>* = (\\<Union>i. rel_d.power R i)\"\n  by (simp add: power_is_relpow rtrancl_is_UN_relpow)\n\nlemma rel_star_contl: \"R ; S\\<^sup>* = (\\<Union>i. R ; rel_d.power S i)\"\nproof-\n  have \"R ; S\\<^sup>* = R ; (\\<Union>i. rel_d.power S i)\"\n    unfolding rel_star_def by simp\n  also have \"\\<dots> = (\\<Union>i. R ; rel_d.power S i)\"\n    by (simp add: relcomp_UNION_distrib)\n  finally show ?thesis.\nqed\n\nlemma rel_star_contr: \"R\\<^sup>* ; S = (\\<Union>i. (rel_d.power R i) ; S)\"\n  by (simp add: rel_star_def relcomp_UNION_distrib2)\n\nlemma rel_star_unfoldl: \"Id \\<union> R ; R\\<^sup>* = R\\<^sup>*\"\nproof-\n  have \"Id \\<union> R ; R\\<^sup>* = Id \\<union> R ; (\\<Union>i. rel_d.power R i)\"\n    by (simp add: rel_star_def)\n  also have \"\\<dots> = Id \\<union> (\\<Union>i. R ; rel_d.power R i)\"\n    by (simp add: relcomp_UNION_distrib)\n  also have \"\\<dots> = rel_d.power R 0  \\<union> (\\<Union>i. rel_d.power R (Suc i))\"\n    by auto\n  also have \"\\<dots> = (\\<Union>i. rel_d.power R i)\"\n    by (metis calculation r_comp_rtrancl_eq rel_star_def rtrancl_unfold)\n  also have \"\\<dots> = R\\<^sup>*\"\n    by (simp add: rel_star_def)\n  finally show ?thesis.\nqed\n\nlemma rel_star_unfoldr: \"Id \\<union> R\\<^sup>* ; R = R\\<^sup>*\"\n  using rtrancl_unfold by blast\n\nlemma rel_star_inductl: \n  fixes R S T :: \"'a rel\"\n  assumes \"T \\<union> R ; S \\<subseteq> S\"\n  shows \"R\\<^sup>* ; T \\<subseteq> S\"\nproof-\n  have \"\\<forall>i. rel_d.power R i ; T \\<subseteq> S\"\n    by (meson assms rel_d.power_inductl)\n  hence \"(\\<Union>i. (rel_d.power R i) ; T) \\<subseteq> S\"\n    by (simp add: SUP_least)\n  hence \"(\\<Union>i. rel_d.power R i) ; T \\<subseteq> S\"\n    by (simp add: relcomp_UNION_distrib2)\n  thus ?thesis\n    unfolding rel_star_def by simp\nqed\n\nlemma rel_star_inductr: \"(T::'a rel) \\<union> S ; R \\<subseteq> S \\<Longrightarrow> T ; R\\<^sup>* \\<subseteq> S\"\n  unfolding rel_star_def by (simp add: SUP_le_iff rel_d.power_inductr relcomp_UNION_distrib)\n\ninterpretation rel_ka: kleene_algebra \"(\\<union>)\" \"{}\" Id \"(;)\" \"(\\<subseteq>)\" \"(\\<subset>)\" rtrancl\nproof unfold_locales\n  fix x y z :: \"'a rel\"  \n  show \"Id \\<union> x ; x\\<^sup>* \\<subseteq> x\\<^sup>*\"\n    by (simp add: rel_star_unfoldl)\n  show \"Id \\<union> x\\<^sup>* ; x \\<subseteq> x\\<^sup>*\"\n    by fastforce\n  show  \"z \\<union> x ; y \\<subseteq> y \\<Longrightarrow> x\\<^sup>* ; z \\<subseteq> y\"\n    by (simp add: rel_star_inductl)\n  show \"z \\<union> y ; x \\<subseteq> y \\<Longrightarrow> z ; x\\<^sup>* \\<subseteq> y\"\n    by (simp add: rel_star_inductr)\nqed\n\nsubsection \\<open>State Transformer Model of Kleene Algebra\\<close>\n\ntype_synonym 'a sta = \"'a \\<Rightarrow> 'a set\"\n\nabbreviation eta :: \"'a sta\" (\"\\<eta>\") where\n  \"\\<eta> x \\<equiv> {x}\"\n\nabbreviation nsta :: \"'a sta\" (\"\\<nu>\") where \n  \"\\<nu> x \\<equiv> {}\" \n\ndefinition kcomp :: \"'a sta \\<Rightarrow> 'a sta \\<Rightarrow> 'a sta\" (infixl \"\\<circ>\\<^sub>K\" 75) where\n  \"(f \\<circ>\\<^sub>K g) x = \\<Union>{g y |y. y \\<in> f x}\"\n\ndefinition kadd :: \"'a sta \\<Rightarrow> 'a sta \\<Rightarrow> 'a sta\" (infixl \"+\\<^sub>K\" 65) where\n  \"(f +\\<^sub>K g) x = f x \\<union> g x\" \n\ndefinition kleq :: \"'a sta \\<Rightarrow> 'a sta \\<Rightarrow> bool\" (infix \"\\<sqsubseteq>\" 50) where\n  \"f \\<sqsubseteq> g = (\\<forall>x. f x \\<subseteq> g x)\"\n\ndefinition kle :: \"'a sta \\<Rightarrow> 'a sta \\<Rightarrow> bool\" (infix \"\\<sqsubset>\" 50) where\n  \"f \\<sqsubset> g = (f \\<sqsubseteq> g \\<and> f \\<noteq> g)\"\n\nlemma sta_iff: \"((f::'a sta) = g) = (\\<forall>x y. y \\<in> f x \\<longleftrightarrow> y \\<in> g x)\"\n  unfolding fun_eq_iff by force\n    \nlemma kcomp_iff: \"y \\<in> (f \\<circ>\\<^sub>K g) x = (\\<exists>z. y \\<in> g z \\<and> z \\<in> f x)\"\n  unfolding kcomp_def by force\n\nlemma kadd_iff: \"y \\<in> (f +\\<^sub>K g) x = (y \\<in> f x \\<or> y \\<in> g x)\"\n  unfolding kadd_def by simp\n\nlemma kleq_iff: \"f \\<sqsubseteq> g = (\\<forall>x y. y \\<in> f x \\<longrightarrow> y \\<in> g x)\"\n  unfolding kleq_def by blast\n\nnamed_theorems sta_unfolds\n\ndeclare\nsta_iff [sta_unfolds]\nkcomp_iff [sta_unfolds]\nkadd_iff [sta_unfolds]\nkleq_iff [sta_unfolds]\n\nlemma kcomp_assoc: \"(f \\<circ>\\<^sub>K g) \\<circ>\\<^sub>K h = f \\<circ>\\<^sub>K (g \\<circ>\\<^sub>K h)\"\nproof-\n  {fix x y\n  have \"y \\<in> ((f \\<circ>\\<^sub>K g) \\<circ>\\<^sub>K h) x = (\\<exists>v. y \\<in> h v \\<and> (\\<exists>w. v \\<in> g w \\<and> w \\<in> f x))\"\n    unfolding sta_unfolds by simp\n  also have \"\\<dots> = (\\<exists>v w. y \\<in> h v \\<and> v \\<in> g w \\<and> w \\<in> f x)\"\n    by blast\n  also have \"\\<dots> = (\\<exists>w. (\\<exists>v. y \\<in> h v \\<and> v \\<in> g w) \\<and> w \\<in> f x)\"\n    by blast\n  also have \"\\<dots> = (y \\<in> (f \\<circ>\\<^sub>K (g \\<circ>\\<^sub>K h)) x)\"\n    unfolding sta_unfolds by simp\n  finally have \"y \\<in> ((f \\<circ>\\<^sub>K g) \\<circ>\\<^sub>K h) x = (y \\<in> (f \\<circ>\\<^sub>K (g \\<circ>\\<^sub>K h)) x)\".}\n  thus ?thesis\n    unfolding sta_unfolds by simp\nqed\n\ninterpretation sta_monm: monoid_mult \"\\<eta>\" \"(\\<circ>\\<^sub>K)\"\n  by unfold_locales (auto simp: sta_unfolds)\n\ninterpretation sta_di: dioid \"(+\\<^sub>K)\" \"\\<nu>\" \"\\<eta>\" \"(\\<circ>\\<^sub>K)\" \"(\\<sqsubseteq>)\" \"(\\<sqsubset>)\"\n  by unfold_locales (auto simp: sta_unfolds kle_def)\n\nabbreviation \"kpow \\<equiv> sta_monm.power\"\n\ndefinition kstar :: \"'a sta \\<Rightarrow> 'a sta\" where\n  \"kstar f x = (\\<Union>i. kpow f i x)\"\n\nlemma kstar_iff: \"y \\<in> kstar f x = (\\<exists>i. y \\<in> kpow f i x)\"\n  unfolding kstar_def by blast\n\ndeclare kstar_iff [sta_unfolds]\n\nlemma kstar_unfoldl: \"\\<eta> +\\<^sub>K f \\<circ>\\<^sub>K kstar f \\<sqsubseteq> kstar f\"\n  by (unfold sta_unfolds, metis (mono_tags) kcomp_iff power.power_eq_if sta_monm.power_Suc)\n\nlemma kstar_unfoldr: \"\\<eta> +\\<^sub>K kstar f \\<circ>\\<^sub>K f \\<sqsubseteq> kstar f\"\n  by (unfold sta_unfolds, metis (mono_tags, lifting) kcomp_iff power.power.power_0 sta_monm.power_Suc2) \n\nlemma kstar_contl: \"(f \\<circ>\\<^sub>K kstar g) x = (\\<Union>i. (f \\<circ>\\<^sub>K kpow g i) x)\"\nproof-\n  {fix y\n  have \"y \\<in> (f \\<circ>\\<^sub>K kstar g) x = (\\<exists>z. z \\<in> f x \\<and> (\\<exists>i. y \\<in> kpow g i z))\"\n    unfolding sta_unfolds  by auto \n  also have \"\\<dots> = (\\<exists>i. (\\<exists>z. z \\<in> f x \\<and> y \\<in> kpow g i z))\"\n    by blast\n  also have \"\\<dots> = (\\<exists>i. (y \\<in> (f \\<circ>\\<^sub>K kpow g i) x))\"\n    by (meson kcomp_iff)\n  also have \"\\<dots> = (y \\<in> (\\<Union>i. (f \\<circ>\\<^sub>K kpow g i) x))\"\n    by blast\n  finally have  \"y \\<in> (f \\<circ>\\<^sub>K kstar g) x = (y \\<in> (\\<Union>i. (f \\<circ>\\<^sub>K kpow g i) x))\"\n    by blast}\n  thus ?thesis\n    by blast\nqed\n\nlemma kstar_contr: \"(kstar f \\<circ>\\<^sub>K g) x = (\\<Union>i. (kpow f i \\<circ>\\<^sub>K g) x)\"\n  by (force simp: set_eq_iff sta_unfolds)\n\nlemma kstar_inductl: \"h +\\<^sub>K f \\<circ>\\<^sub>K g \\<sqsubseteq> g \\<Longrightarrow> kstar f \\<circ>\\<^sub>K h \\<sqsubseteq> g\"\nproof-\n  assume \"h +\\<^sub>K f \\<circ>\\<^sub>K g \\<sqsubseteq> g\"\n  hence \"\\<forall>i. kpow f i \\<circ>\\<^sub>K h \\<sqsubseteq> g\"\n    using sta_di.power_inductl by blast\n  thus \"kstar f \\<circ>\\<^sub>K h \\<sqsubseteq> g\"\n    by (unfold sta_unfolds, metis UN_E kstar_contr)\nqed\n\nlemma kstar_inductr: \"h +\\<^sub>K g \\<circ>\\<^sub>K f \\<sqsubseteq> g \\<Longrightarrow> h \\<circ>\\<^sub>K kstar f \\<sqsubseteq> g\"\nproof-\n  assume \"h +\\<^sub>K g \\<circ>\\<^sub>K f \\<sqsubseteq> g\"\n  hence \"\\<forall>i. h \\<circ>\\<^sub>K kpow f i  \\<sqsubseteq> g\"\n    using sta_di.power_inductr by blast\n  thus \"h \\<circ>\\<^sub>K kstar f  \\<sqsubseteq> g\"\n    by (unfold sta_unfolds, metis UN_E kstar_contl)\nqed\n\ninterpretation sta_ka: kleene_algebra \"(+\\<^sub>K)\" \"\\<nu>\" \"\\<eta>\" \"(\\<circ>\\<^sub>K)\" \"(\\<sqsubseteq>)\" \"(\\<sqsubset>)\" kstar\n  by unfold_locales (simp_all add: kstar_unfoldl kstar_unfoldr kstar_inductl kstar_inductr)\n\n\nsubsection \\<open>Isomorphism between the models\\<close>\n\ndefinition r2s :: \"'a rel \\<Rightarrow> 'a sta\" (\"\\<S>\") where\n  \"\\<S> R = Image R \\<circ> \\<eta>\" \n\ndefinition s2r :: \"'a sta \\<Rightarrow> 'a rel\" (\"\\<R>\") where\n  \"\\<R> f = {(x,y). y \\<in> f x}\"\n\nlemma r2s_iff: \"y \\<in> \\<S> R x \\<longleftrightarrow> (x,y) \\<in> R\"\n  by (simp add: r2s_def)\n\nlemma s2r_iff: \"(x,y) \\<in> \\<R> f \\<longleftrightarrow> y \\<in> f x\"\n  by (simp add: s2r_def)\n\ntext \\<open>The functors form a bijective pair.\\<close>\n\nlemma r2s2r_inv1 [simp]: \"\\<R> \\<circ> \\<S> = id\"\n  unfolding s2r_def r2s_def by force\n\nlemma s2r2s_inv2 [simp]: \"\\<S> \\<circ> \\<R> = id\"\n  unfolding s2r_def r2s_def by force\n\nlemma r2s2r_galois: \"(\\<R> f = R) = (\\<S> R = f)\"\n  by (force simp: s2r_def r2s_def)\n\nlemma r2s_inj: \"inj \\<S>\"\n  by (meson inj_on_inverseI r2s2r_galois)\n\nlemma s2r_inj: \"inj \\<R>\"\n  unfolding inj_def using r2s2r_galois by metis\n\nlemma r2s_surj: \"surj \\<S>\"\n  by (metis r2s2r_galois surj_def)\n\nlemma s2r_surj: \"surj \\<R>\"\n  using r2s2r_galois by auto\n\nlemma r2s_bij: \"bij \\<S>\"\n  by (simp add: bijI r2s_inj r2s_surj)\n\nlemma s2r_bij: \"bij \\<R>\"\n  by (simp add: bij_def s2r_inj s2r_surj)\n\nlemma s2r_comp: \"\\<S> (R ; S) = \\<S> R \\<circ>\\<^sub>K \\<S> S\"\n  unfolding sta_unfolds r2s_iff by force\n\nlemma r2s_comp: \"\\<R> (f \\<circ>\\<^sub>K g) = \\<R> f ; \\<R> g\"\n  by (metis s2r_comp r2s2r_galois)\n\nlemma s2r_id: \"\\<S> Id = \\<eta>\"\n  by (metis empty_iff insert_iff pair_in_Id_conv r2s_iff subsetI subset_singletonD)\n\nlemma r2s_id: \"\\<R> \\<eta> = Id\"\n  by (metis R_O_Id power.power.power_0 r2s_comp r2s2r_galois rel_d.power_Suc rel_d.power_Suc2 sta_monm.mult_1_right)\n\nlemma s2r_zero: \"\\<S> {} = \\<nu>\"\n  unfolding r2s_def by force\n\nlemma r2s_zero: \"\\<R> \\<nu> = {}\"\n  by (simp add: s2r_def)\n\nlemma r2s_add: \"\\<S> (R \\<union> S) = \\<S> R +\\<^sub>K \\<S> S\"\n  unfolding sta_unfolds r2s_iff by force\n\nlemma s2r_add: \"\\<R> (f +\\<^sub>K g) = \\<R> f \\<union> \\<R> g\"\n  by (metis r2s_add r2s2r_galois)\n\nlemma s2r_pow: \"\\<S> (rel_d.power R i) = kpow (\\<S> R) i\"\nproof (induct i)\n  case 0\n  thus \"\\<S> (rel_d.power R 0) = kpow (\\<S> R) 0\"\n    by (metis power.power.power_0 r2s2r_galois r2s_id)\nnext\n  case (Suc i)\n  assume h: \"\\<S> (rel_d.power R i) = kpow (\\<S> R) i\"\n  have \"\\<S> (rel_d.power R (Suc i)) =\\<S> R \\<circ>\\<^sub>K \\<S> (rel_d.power R i)\"\n    by (simp add: s2r_comp)\n  also have \"... = \\<S> R \\<circ>\\<^sub>K  kpow (\\<S> R) i\"\n    by (simp add: h)\n  also have \"\\<dots> = kpow (\\<S> R) (Suc i)\"\n    by simp\n  finally show \"\\<S> (rel_d.power R (Suc i)) = kpow (\\<S> R) (Suc i)\"\n    by blast\nqed\n\nlemma s2r_star: \"\\<S> (R\\<^sup>*) = kstar (\\<S> R)\"\nproof-\n  {fix x y\n    have \"y \\<in> \\<S> (R\\<^sup>*) x = (\\<exists>i. (x,y) \\<in> rel_d.power R i)\"\n      by (simp add: power_is_relpow r2s_iff rtrancl_power)\n  also have \"\\<dots> = (y \\<in> (\\<Union>i. \\<S> (rel_d.power R i) x))\"\n    by (simp add: r2s_iff)\n  also have \"\\<dots> = (y \\<in> (\\<Union>i. kpow (\\<S> R) i x))\"\n    by (simp add: s2r_pow)\n  also have \"\\<dots> = (y \\<in> kstar (\\<S> R) x)\"\n    by (simp add: kstar_iff)\n  finally have \"y \\<in> \\<S> (R\\<^sup>*) x = (y \\<in> kstar (\\<S> R) x)\".}\n  thus ?thesis\n    by blast\nqed\n\nlemma r2s_pow: \"rel_d.power (\\<R> f) i = \\<R> (kpow f i)\"\n  by (metis s2r_pow r2s2r_galois)\n\nlemma r2s_star: \"\\<R> (kstar f) = (\\<R> f)\\<^sup>*\"\n  by (metis s2r_star r2s2r_galois)\n\nlemma kcomp_assoc2: \"(f \\<circ>\\<^sub>K g) \\<circ>\\<^sub>K h = f \\<circ>\\<^sub>K (g \\<circ>\\<^sub>K h)\"\nproof-\n  have \"(f \\<circ>\\<^sub>K g) \\<circ>\\<^sub>K h = \\<S> (\\<R> ((f \\<circ>\\<^sub>K g) \\<circ>\\<^sub>K h))\"\n    by (metis r2s2r_galois)\n  also have \"\\<dots> = \\<S> ((\\<R> f ; \\<R> g) ; \\<R> h)\"\n    by (simp add: r2s_comp)\n  also have \"\\<dots> = \\<S> (\\<R> f ; (\\<R> g ; \\<R> h))\"\n    by (simp add: rel_d.mult_assoc)\n  also have \"\\<dots> = \\<S> (\\<R> (f \\<circ>\\<^sub>K (g \\<circ>\\<^sub>K h)))\"\n    by (simp add: r2s_comp)\n  also have \"\\<dots> = f \\<circ>\\<^sub>K (g \\<circ>\\<^sub>K h)\"\n    using r2s2r_galois by blast\n  finally show ?thesis.\nqed\n\n\nsubsection \\<open>Embedding Predicates into State Transformers and Relations\\<close>\n\ntype_synonym 'a pred = \"'a \\<Rightarrow> bool\"\n\nnotation inf (infixl \"\\<sqinter>\" 70) \nnotation sup (infixl \"\\<squnion>\" 65)\n\ntext \\<open>First we consider relations.\\<close>\n\ndefinition p2r :: \"'a pred \\<Rightarrow> 'a rel\" (\"\\<lceil>_\\<rceil>\\<^sub>r\") where\n  \"\\<lceil>P\\<rceil>\\<^sub>r = {(s,s) |s. P s}\"\n\ndefinition r2p :: \"'a rel \\<Rightarrow> 'a pred\" (\"\\<lfloor>_\\<rfloor>\\<^sub>r\")where\n  \"\\<lfloor>R\\<rfloor>\\<^sub>r \\<equiv> (\\<lambda>s. s \\<in> Domain R)\"\n\nlemma r2p2r [simp]: \"\\<lfloor>\\<lceil>P\\<rceil>\\<^sub>r\\<rfloor>\\<^sub>r = P\"\n  unfolding p2r_def r2p_def by force\n\nlemma p2r2p: \"R \\<subseteq> Id \\<Longrightarrow> \\<lceil>\\<lfloor>R\\<rfloor>\\<^sub>r\\<rceil>\\<^sub>r = R\"\n  unfolding p2r_def r2p_def by force\n\nlemma p2r_r2p_galois: \"R \\<subseteq> Id \\<Longrightarrow> (\\<lfloor>R\\<rfloor>\\<^sub>r = P) = (R = \\<lceil>P\\<rceil>\\<^sub>r)\"\n  using p2r2p by auto\n\nlemma p2r_comp [simp]: \"\\<lceil>P\\<rceil>\\<^sub>r ; \\<lceil>Q\\<rceil>\\<^sub>r = \\<lceil>\\<lambda>s. P s \\<and> Q s\\<rceil>\\<^sub>r\" \n  unfolding p2r_def by auto\n\nlemma r2p_comp: \"R \\<subseteq> Id \\<Longrightarrow> S \\<subseteq> Id \\<Longrightarrow> \\<lfloor>R ; S\\<rfloor>\\<^sub>r = (\\<lambda>s. \\<lfloor>R\\<rfloor>\\<^sub>r s \\<and> \\<lfloor>S\\<rfloor>\\<^sub>r s)\" \n  unfolding r2p_def by force\n\nlemma p2r_imp [simp]: \"\\<lceil>P\\<rceil>\\<^sub>r \\<subseteq> \\<lceil>Q\\<rceil>\\<^sub>r = (\\<forall>s. P s \\<longrightarrow> Q s)\"\n  unfolding p2r_def by force\n\ntext \\<open>Next we repeat the development with state transformers.\\<close>\n\ndefinition p2s :: \"'a pred \\<Rightarrow> 'a sta\" (\"\\<lceil>_\\<rceil>\\<^sub>s\") where\n  \"\\<lceil>P\\<rceil>\\<^sub>s x \\<equiv> if P x then {x} else {}\"\n\ndefinition s2p :: \"'a sta \\<Rightarrow> 'a pred\" (\"\\<lfloor>_\\<rfloor>\\<^sub>s\")where\n  \"\\<lfloor>f\\<rfloor>\\<^sub>s s \\<equiv> (f s \\<noteq> {})\"\n\nlemma s2p2s [simp]: \"\\<lfloor>\\<lceil>P\\<rceil>\\<^sub>s\\<rfloor>\\<^sub>s = P\"\n  unfolding p2s_def s2p_def by force\n\nlemma p2s2p: \"f \\<sqsubseteq> \\<eta> \\<Longrightarrow> \\<lceil>\\<lfloor>f\\<rfloor>\\<^sub>s\\<rceil>\\<^sub>s = f\"\n  unfolding p2s_def s2p_def sta_iff kleq_iff by force \n\nlemma p2s_s2p_galois: \"f \\<sqsubseteq> \\<eta> \\<Longrightarrow> (\\<lfloor>f\\<rfloor>\\<^sub>s = P) = (f = \\<lceil>P\\<rceil>\\<^sub>s)\"\n  unfolding p2s_def s2p_def sta_iff kleq_iff by force\n\nlemma p2s_comp [simp]: \"\\<lceil>P\\<rceil>\\<^sub>s \\<circ>\\<^sub>K \\<lceil>Q\\<rceil>\\<^sub>s = \\<lceil>\\<lambda>s. P s \\<and> Q s\\<rceil>\\<^sub>s\" \n  unfolding  p2s_def s2p_def sta_iff kcomp_iff by force\n\nlemma s2p_comp: \"f \\<sqsubseteq> \\<eta> \\<Longrightarrow> g \\<sqsubseteq> \\<eta> \\<Longrightarrow> \\<lfloor>f \\<circ>\\<^sub>K g\\<rfloor>\\<^sub>s = (\\<lambda>s. \\<lfloor>f\\<rfloor>\\<^sub>s s \\<and> \\<lfloor>g\\<rfloor>\\<^sub>s s)\" \n  unfolding s2p_def kleq_iff kcomp_iff kcomp_def by blast\n\nlemma p2s_imp [simp]: \"\\<lceil>P\\<rceil>\\<^sub>s \\<sqsubseteq> \\<lceil>Q\\<rceil>\\<^sub>s = (\\<forall>s. P s \\<longrightarrow> Q s)\"\n  unfolding  p2s_def s2p_def kleq_iff by simp\n\nlemma p2r2s: \"\\<lceil>P\\<rceil>\\<^sub>s = \\<S> \\<lceil>P\\<rceil>\\<^sub>r\"\n  unfolding p2r_def p2s_def sta_iff r2s_iff by simp\n\nlemma p2s2r: \"\\<lceil>P\\<rceil>\\<^sub>r = \\<R> \\<lceil>P\\<rceil>\\<^sub>s\"\n  by (metis (no_types) p2r2s r2s2r_galois)\n\nend\n\n\n\n\n\n", "meta": {"author": "hyleIndex", "repo": "Kleene-Algebras-From-Foundations-to-Program-Verification", "sha": "9ec491714e5925c7a6e42738ad6af17be8e70e9f", "save_path": "github-repos/isabelle/hyleIndex-Kleene-Algebras-From-Foundations-to-Program-Verification", "path": "github-repos/isabelle/hyleIndex-Kleene-Algebras-From-Foundations-to-Program-Verification/Kleene-Algebras-From-Foundations-to-Program-Verification-9ec491714e5925c7a6e42738ad6af17be8e70e9f/KA.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8479677737461007, "lm_q2_score": 0.8438951045175642, "lm_q1q2_score": 0.7155958530529919}}
{"text": "(*  Title:      HOL/Library/Subseq_Order.thy\n    Author:     Peter Lammich, Uni Muenster <peter.lammich@uni-muenster.de>\n    Author:     Florian Haftmann, TU Muenchen\n    Author:     Tobias Nipkow, TU Muenchen\n*)\n\nsection \\<open>Subsequence Ordering\\<close>\n\ntheory Subseq_Order\nimports Sublist\nbegin\n\ntext \\<open>\n  This theory defines subsequence ordering on lists. A list \\<open>ys\\<close> is a subsequence of a\n  list \\<open>xs\\<close>, iff one obtains \\<open>ys\\<close> by erasing some elements from \\<open>xs\\<close>.\n\\<close>\n\nsubsection \\<open>Definitions and basic lemmas\\<close>\n\ninstantiation list :: (type) ord\nbegin\n\ndefinition \"xs \\<le> ys \\<longleftrightarrow> subseq xs ys\" for xs ys :: \"'a list\"\ndefinition \"xs < ys \\<longleftrightarrow> xs \\<le> ys \\<and> \\<not> ys \\<le> xs\" for xs ys :: \"'a list\"\n\ninstance ..\n\nend\n\ninstance list :: (type) order\nproof\n  fix xs ys zs :: \"'a list\"\n  show \"xs < ys \\<longleftrightarrow> xs \\<le> ys \\<and> \\<not> ys \\<le> xs\"\n    unfolding less_list_def ..\n  show \"xs \\<le> xs\"\n    by (simp add: less_eq_list_def)\n  show \"xs = ys\" if \"xs \\<le> ys\" and \"ys \\<le> xs\"\n    using that unfolding less_eq_list_def by (rule subseq_order.antisym)\n  show \"xs \\<le> zs\" if \"xs \\<le> ys\" and \"ys \\<le> zs\"\n    using that unfolding less_eq_list_def by (rule subseq_order.order_trans)\nqed\n\nlemmas less_eq_list_induct [consumes 1, case_names empty drop take] =\n  list_emb.induct [of \"(=)\", folded less_eq_list_def]\nlemmas less_eq_list_drop = list_emb.list_emb_Cons [of \"(=)\", folded less_eq_list_def]\nlemmas le_list_Cons2_iff [simp, code] = subseq_Cons2_iff [folded less_eq_list_def]\nlemmas le_list_map = subseq_map [folded less_eq_list_def]\nlemmas le_list_filter = subseq_filter [folded less_eq_list_def]\nlemmas le_list_length = list_emb_length [of \"(=)\", folded less_eq_list_def]\n\nlemma less_list_length: \"xs < ys \\<Longrightarrow> length xs < length ys\"\n  by (metis list_emb_length subseq_same_length le_neq_implies_less less_list_def less_eq_list_def)\n\nlemma less_list_empty [simp]: \"[] < xs \\<longleftrightarrow> xs \\<noteq> []\"\n  by (metis less_eq_list_def list_emb_Nil order_less_le)\n\nlemma less_list_below_empty [simp]: \"xs < [] \\<longleftrightarrow> False\"\n  by (metis list_emb_Nil less_eq_list_def less_list_def)\n\nlemma less_list_drop: \"xs < ys \\<Longrightarrow> xs < x # ys\"\n  by (unfold less_le less_eq_list_def) (auto)\n\nlemma less_list_take_iff: \"x # xs < x # ys \\<longleftrightarrow> xs < ys\"\n  by (metis subseq_Cons2_iff less_list_def less_eq_list_def)\n\nlemma less_list_drop_many: \"xs < ys \\<Longrightarrow> xs < zs @ ys\"\n  by (metis subseq_append_le_same_iff subseq_drop_many order_less_le\n      self_append_conv2 less_eq_list_def)\n\nlemma less_list_take_many_iff: \"zs @ xs < zs @ ys \\<longleftrightarrow> xs < ys\"\n  by (metis less_list_def less_eq_list_def subseq_append')\n\nlemma less_list_rev_take: \"xs @ zs < ys @ zs \\<longleftrightarrow> xs < ys\"\n  by (unfold less_le less_eq_list_def) 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/Library/Subseq_Order.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8479677737461007, "lm_q2_score": 0.8438950966654774, "lm_q1q2_score": 0.7155958463946752}}
{"text": "section \\<open>Pratt's Primality Certificates\\<close>\ntext_raw \\<open>\\label{sec:pratt}\\<close>\ntheory Pratt_Certificate\nimports\n  Complex_Main\n  Lehmer.Lehmer\nbegin\n\ntext \\<open>\n  This work formalizes Pratt's proof system as described in his article\n  ``Every Prime has a Succinct Certificate''\\<^cite>\\<open>\"pratt1975certificate\"\\<close>.\n\n  The proof system makes use of two types of predicates:\n  \\begin{itemize}\n    \\item $\\text{Prime}(p)$: $p$ is a prime number\n    \\item $(p, a, x)$: \\<open>\\<forall>q \\<in> prime_factors(x). [a^((p - 1) div q) \\<noteq> 1] (mod p)\\<close>\n  \\end{itemize}\n  We represent these predicates with the following datatype:\n\\<close>\n\ndatatype pratt = Prime nat | Triple nat nat nat\n\ntext \\<open>\n  Pratt describes an inference system consisting of the axiom $(p, a, 1)$\n  and the following inference rules:\n  \\begin{itemize}\n  \\item R1: If we know that $(p, a, x)$ and \\<open>[a^((p - 1) div q) \\<noteq> 1] (mod p)\\<close> hold for some\n              prime number $q$ we can conclude $(p, a, qx)$ from that.\n  \\item R2: If we know that $(p, a, p - 1)$ and  \\<open>[a^(p - 1) = 1] (mod p)\\<close> hold, we can\n              infer $\\text{Prime}(p)$.\n  \\end{itemize}\n  Both rules follow from Lehmer's theorem as we will show later on.\n\n  A list of predicates (i.e., values of type @{type pratt}) is a \\emph{certificate}, if it is\n  built according to the inference system described above. I.e., a list @{term \"x # xs :: pratt list\"}\n  is a certificate if @{term \"xs :: pratt list\"} is a certificate and @{term \"x :: pratt\"} is\n  either an axiom or all preconditions of @{term \"x :: pratt\"} occur in @{term \"xs :: pratt list\"}.\n\n  We call a certificate @{term \"xs :: pratt list\"} a \\emph{certificate for @{term p}},\n  if @{term \"Prime p\"} occurs in @{term \"xs :: pratt list\"}.\n\n  The function \\<open>valid_cert\\<close> checks whether a list is a certificate.\n\\<close>\n\nfun valid_cert :: \"pratt list \\<Rightarrow> bool\" where\n  \"valid_cert [] = True\"\n| R2: \"valid_cert (Prime p#xs) \\<longleftrightarrow> 1 < p \\<and> valid_cert xs\n    \\<and> (\\<exists> a . [a^(p - 1) = 1] (mod p) \\<and> Triple p a (p - 1) \\<in> set xs)\"\n| R1: \"valid_cert (Triple p a x # xs) \\<longleftrightarrow> p > 1 \\<and> 0 < x  \\<and> valid_cert xs \\<and> (x=1 \\<or>\n    (\\<exists>q y. x = q * y \\<and> Prime q \\<in> set xs \\<and> Triple p a y \\<in> set xs\n      \\<and> [a^((p - 1) div q) \\<noteq> 1] (mod p)))\"\n\ntext \\<open>\n  We define a function @{term size_cert} to measure the size of a certificate, assuming\n  a binary encoding of numbers. We will use this to show that there is a certificate for a\n  prime number $p$ such that the size of the certificate is polynomially bounded in the size\n  of the binary representation of $p$.\n\\<close>\nfun size_pratt :: \"pratt \\<Rightarrow> real\" where\n  \"size_pratt (Prime p) = log 2 p\" |\n  \"size_pratt (Triple p a x) = log 2 p + log 2 a + log 2 x\"\n\nfun size_cert :: \"pratt list \\<Rightarrow> real\" where\n  \"size_cert [] = 0\" |\n  \"size_cert (x # xs) = 1 + size_pratt x + size_cert xs\"\n\n\nsubsection \\<open>Soundness\\<close>\n\ntext \\<open>\n  In Section \\ref{sec:pratt} we introduced the predicates $\\text{Prime}(p)$ and $(p, a, x)$.\n  In this section we show that for a certificate every predicate occurring in this certificate\n  holds. In particular, if $\\text{Prime}(p)$ occurs in a certificate, $p$ is prime.\n\\<close>\n\nlemma prime_factors_one [simp]: shows \"prime_factors (Suc 0) = {}\"\n  using prime_factorization_1 [where ?'a = nat] by simp\n\nlemma prime_factors_of_prime: fixes p :: nat assumes \"prime p\" shows \"prime_factors p = {p}\"\n  using assms by (fact prime_prime_factors)\n\ndefinition pratt_triple :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> bool\" where\n  \"pratt_triple p a x \\<longleftrightarrow> x > 0 \\<and> (\\<forall>q\\<in>prime_factors x. [a ^ ((p - 1) div q) \\<noteq> 1] (mod p))\"\n\nlemma pratt_triple_1: \"p > 1 \\<Longrightarrow> x = 1 \\<Longrightarrow> pratt_triple p a x\"\n  by (auto simp: pratt_triple_def)\n\nlemma pratt_triple_extend:\n  assumes \"prime q\" \"pratt_triple p a y\"\n          \"p > 1\" \"x > 0\" \"x = q * y\" \"[a ^ ((p - 1) div q) \\<noteq> 1] (mod p)\"\n  shows   \"pratt_triple p a x\"\nproof -\n  have \"prime_factors x = insert q (prime_factors y)\"\n    using assms by (simp add: prime_factors_product prime_prime_factors)\n  also have \"\\<forall>r\\<in>\\<dots>. [a ^ ((p - 1) div r) \\<noteq> 1] (mod p)\"\n    using assms by (auto simp: pratt_triple_def)\n  finally show ?thesis using assms\n    unfolding pratt_triple_def by blast\nqed\n\nlemma pratt_triple_imp_prime:\n  assumes \"pratt_triple p a x\" \"p > 1\" \"x = p - 1\" \"[a ^ (p - 1) = 1] (mod p)\"\n  shows   \"prime p\"\n  using lehmers_theorem[of p a] assms by (auto simp: pratt_triple_def)\n\ntheorem pratt_sound:\n  assumes 1: \"valid_cert c\"\n  assumes 2: \"t \\<in> set c\"\n  shows \"(t = Prime p \\<longrightarrow> prime p) \\<and>\n         (t = Triple p a x \\<longrightarrow> ((\\<forall>q \\<in> prime_factors x . [a^((p - 1) div q) \\<noteq> 1] (mod p)) \\<and> 0<x))\"\nusing assms\nproof (induction c arbitrary: p a x t)\n  case Nil then show ?case by force\n  next\n  case (Cons y ys)\n  { assume \"y=Triple p a x\" \"x=1\"\n    then have \"(\\<forall> q \\<in> prime_factors x . [a^((p - 1) div q) \\<noteq> 1] (mod p)) \\<and> 0<x\" by simp\n    }\n  moreover\n  { assume x_y: \"y=Triple p a x\" \"x~=1\"\n    hence \"x>0\" using Cons.prems by auto\n    obtain q z where \"x=q*z\" \"Prime q \\<in> set ys \\<and> Triple p a z \\<in> set ys\"\n               and cong:\"[a^((p - 1) div q) \\<noteq> 1] (mod p)\" using Cons.prems x_y by auto\n    then have factors_IH:\"(\\<forall> r \\<in> prime_factors z . [a^((p - 1) div r) \\<noteq> 1] (mod p))\" \"prime q\" \"z>0\"\n      using Cons.IH Cons.prems \\<open>x>0\\<close> \\<open>y=Triple p a x\\<close>\n      by force+\n    then have \"prime_factors x = prime_factors z \\<union> {q}\"  using \\<open>x =q*z\\<close> \\<open>x>0\\<close>\n      by (simp add: prime_factors_product prime_factors_of_prime)\n    then have \"(\\<forall> q \\<in> prime_factors x . [a^((p - 1) div q) \\<noteq> 1] (mod p)) \\<and> 0 < x\"\n      using factors_IH cong by (simp add: \\<open>x>0\\<close>)\n    }\n  ultimately have y_Triple:\"y=Triple p a x \\<Longrightarrow> (\\<forall> q \\<in> prime_factors x .\n                                                [a^((p - 1) div q) \\<noteq> 1] (mod p)) \\<and> 0<x\" by linarith\n  { assume y: \"y=Prime p\" \"p>2\" then\n    obtain a where a:\"[a^(p - 1) = 1] (mod p)\" \"Triple p a (p - 1) \\<in> set ys\"\n      using Cons.prems by auto\n    then have Bier:\"(\\<forall>q\\<in>prime_factors (p - 1). [a^((p - 1) div q) \\<noteq> 1] (mod p))\"\n      using Cons.IH Cons.prems(1) by (simp add:y(1))\n    then have \"prime p\" using lehmers_theorem[OF _ _a(1)] \\<open>p>2\\<close> by fastforce\n    }\n  moreover\n  { assume \"y=Prime p\" \"p=2\" hence \"prime p\" by simp }\n  moreover\n  { assume \"y=Prime p\" then have \"p>1\"  using Cons.prems  by simp }\n  ultimately have y_Prime:\"y = Prime p \\<Longrightarrow> prime p\" by linarith\n\n  show ?case\n  proof (cases \"t \\<in> set ys\")\n    case True\n      show ?thesis using Cons.IH[OF _ True] Cons.prems(1) by (cases y) auto\n    next\n    case False\n      thus ?thesis using Cons.prems(2) y_Prime y_Triple by force\n  qed\nqed\n\ncorollary pratt_primeI:\n  assumes \"valid_cert xs\" \"Prime p \\<in> set xs\"\n  shows   \"prime p\"\n  using pratt_sound[OF assms] by simp\n\n\nsubsection \\<open>Completeness\\<close>\n\ntext \\<open>\n  In this section we show completeness of Pratt's proof system, i.e., we show that for\n  every prime number $p$ there exists a certificate for $p$. We also give an upper\n  bound for the size of a minimal certificate\n\n  The prove we give is constructive. We assume that we have certificates for all prime\n  factors of $p - 1$ and use these to build a certificate for $p$ from that. It is\n  important to note that certificates can be concatenated.\n\\<close>\n\nlemma valid_cert_appendI:\n  assumes \"valid_cert r\"\n  assumes \"valid_cert s\"\n  shows \"valid_cert (r @ s)\"\n  using assms\nproof (induction r)\n  case (Cons y ys) then show ?case by (cases y) auto\nqed simp\n\nlemma valid_cert_concatI: \"(\\<forall>x \\<in> set xs . valid_cert x) \\<Longrightarrow> valid_cert (concat xs)\"\n  by (induction xs) (auto simp add: valid_cert_appendI)\n\nlemma size_pratt_le:\n fixes d::real\n assumes \"\\<forall> x \\<in> set c. size_pratt x \\<le> d\"\n shows \"size_cert c \\<le> length c * (1 + d)\" using assms\n by (induction c) (simp_all add: algebra_simps)\n\nfun build_fpc :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> nat list \\<Rightarrow> pratt list\" where\n  \"build_fpc p a r [] = [Triple p a r]\" |\n  \"build_fpc p a r (y # ys) = Triple p a r # build_fpc p a (r div y) ys\"\n\ntext \\<open>\n  The function @{term build_fpc} helps us to construct a certificate for $p$ from\n  the certificates for the prime factors of $p - 1$. Called as\n  @{term \"build_fpc p a (p - 1) qs\"} where $@{term \"qs\"} = q_1 \\ldots q_n$\n  is prime decomposition of $p - 1$ such that $q_1 \\cdot \\dotsb \\cdot q_n = @{term \"p - 1 :: nat\"}$,\n  it returns the following list of predicates:\n  \\[\n  (p,a,p-1), (p,a,\\frac{p - 1}{q_1}), (p,a,\\frac{p - 1}{q_1 q_2}), \\ldots, (p,a,\\frac{p-1}{q_1 \\ldots q_n}) = (p,a,1)\n  \\]\n\n  I.e., if there is an appropriate $a$ and and a certificate @{term rs} for all\n  prime factors of $p$, then we can construct a certificate for $p$ as\n  @{term [display] \"Prime p # build_fpc p a (p - 1) qs @ rs\"}\n\\<close>\n\ntext \\<open>\n  The following lemma shows that \\<open>build_fpc\\<close> extends a certificate that\n  satisfies the preconditions described before to a correct certificate.\n\\<close>\n\nlemma correct_fpc:\n  assumes \"valid_cert xs\" \"p > 1\"\n  assumes \"prod_list qs = r\" \"r \\<noteq> 0\"\n  assumes \"\\<forall> q \\<in> set qs . Prime q \\<in> set xs\"\n  assumes \"\\<forall> q \\<in> set qs . [a^((p - 1) div q) \\<noteq> 1] (mod p)\"\n  shows \"valid_cert (build_fpc p a r qs @ xs)\"\n  using assms\nproof (induction qs arbitrary: r)\n  case Nil thus ?case by auto\nnext\n  case (Cons y ys)\n  have \"prod_list ys = r div y\" using Cons.prems by auto\n  then have T_in: \"Triple p a (prod_list ys) \\<in> set (build_fpc p a (r div y) ys @ xs)\"\n    by (cases ys) auto\n\n  have \"valid_cert (build_fpc p a (r div y) ys @ xs)\"\n    using Cons.prems by (intro Cons.IH) auto\n  then have \"valid_cert (Triple p a r # build_fpc p a (r div y) ys @ xs)\"\n    using \\<open>r \\<noteq> 0\\<close> T_in Cons.prems by auto\n  then show ?case by simp\nqed\n\nlemma length_fpc:\n  \"length (build_fpc p a r qs) = length qs + 1\" by (induction qs arbitrary: r) auto\n\nlemma div_gt_0:\n  fixes m n :: nat assumes \"m \\<le> n\" \"0 < m\" shows \"0 < n div m\"\nproof -\n  have \"0 < m div m\" using \\<open>0 < m\\<close> div_self by auto\n  also have \"m div m \\<le> n div m\" using \\<open>m \\<le> n\\<close> by (rule div_le_mono)\n  finally show ?thesis .\nqed\n\nlemma size_pratt_fpc:\n  assumes \"a \\<le> p\" \"r \\<le> p\" \"0 < a\" \"0 < r\" \"0 < p\" \"prod_list qs = r\"\n  shows \"\\<forall>x \\<in> set (build_fpc p a r qs) . size_pratt x \\<le> 3 * log 2 p\" using assms\nproof (induction qs arbitrary: r)\n  case Nil\n  then have \"log 2 a \\<le> log 2 p\" \"log 2 r \\<le> log 2 p\" by auto\n  then show ?case by simp\nnext\n  case (Cons q qs)\n  then have \"log 2 a \\<le> log 2 p\" \"log 2 r \\<le> log 2 p\" by auto\n  then have  \"log 2 a + log 2 r \\<le> 2 * log 2 p\" by arith\n  moreover have \"r div q > 0\" using Cons.prems by (fastforce intro: div_gt_0)\n  moreover hence \"prod_list qs = r div q\" using Cons.prems(6) by auto\n  moreover have \"r div q \\<le> p\" using \\<open>r\\<le>p\\<close> div_le_dividend[of r q] by linarith\n  ultimately show ?case using Cons by simp\nqed\n\nlemma concat_set:\n  assumes \"\\<forall> q \\<in> qs . \\<exists> c \\<in> set cs . Prime q \\<in> set c\"\n  shows \"\\<forall> q \\<in> qs . Prime q \\<in> set (concat cs)\"\n  using assms by (induction cs) auto\n\nlemma p_in_prime_factorsE:\n  fixes n :: nat\n  assumes \"p \\<in> prime_factors n\" \"0 < n\"\n  obtains \"2 \\<le> p\" \"p \\<le> n\" \"p dvd n\" \"prime p\"\nproof\n  from assms show \"prime p\" by auto\n  then show \"2 \\<le> p\" by (auto dest: prime_gt_1_nat)\n\n  from assms show \"p dvd n\" by auto\n  then show \"p \\<le> n\" using  \\<open>0 < n\\<close> by (rule dvd_imp_le)\nqed\n\nlemma prime_factors_list_prime:\n  fixes n :: nat\n  assumes \"prime n\"\n  shows \"\\<exists> qs. prime_factors n = set qs \\<and> prod_list qs = n \\<and> length qs = 1\"\n  using assms by (auto simp add: prime_factorization_prime intro: exI [of _ \"[n]\"])\n\nlemma prime_factors_list:\n  fixes n :: nat assumes \"3 < n\" \"\\<not> prime n\"\n  shows \"\\<exists> qs. prime_factors n = set qs \\<and> prod_list qs = n \\<and> length qs \\<ge> 2\"\n  using assms\nproof (induction n rule: less_induct)\n  case (less n)\n    obtain p where \"p \\<in> prime_factors n\" using \\<open>n > 3\\<close> prime_factors_elem by force\n    then have p':\"2 \\<le> p\" \"p \\<le> n\" \"p dvd n\" \"prime p\"\n      using \\<open>3 < n\\<close> by (auto elim: p_in_prime_factorsE)\n    { assume \"n div p > 3\" \"\\<not> prime (n div p)\"\n      then obtain qs\n        where \"prime_factors (n div p) = set qs\" \"prod_list qs = (n div p)\" \"length qs \\<ge> 2\"\n        using p' by atomize_elim (auto intro: less simp: div_gt_0)\n      moreover\n      have \"prime_factors (p * (n div p)) = insert p (prime_factors (n div p))\"\n        using \\<open>3 < n\\<close> \\<open>2 \\<le> p\\<close> \\<open>p \\<le> n\\<close> \\<open>prime p\\<close>\n      by (auto simp: prime_factors_product div_gt_0 prime_factors_of_prime)\n      ultimately\n      have \"prime_factors n = set (p # qs)\" \"prod_list (p # qs) = n\" \"length (p#qs) \\<ge> 2\"\n        using \\<open>p dvd n\\<close> by simp_all\n      hence ?case by blast\n    }\n    moreover\n    { assume \"prime (n div p)\"\n      then obtain qs\n        where \"prime_factors (n div p) = set qs\" \"prod_list qs = (n div p)\" \"length qs = 1\"\n        using prime_factors_list_prime by blast\n      moreover\n      have \"prime_factors (p * (n div p)) = insert p (prime_factors (n div p))\"\n        using \\<open>3 < n\\<close> \\<open>2 \\<le> p\\<close> \\<open>p \\<le> n\\<close> \\<open>prime p\\<close>\n      by (auto simp: prime_factors_product div_gt_0 prime_factors_of_prime)\n      ultimately\n      have \"prime_factors n = set (p # qs)\" \"prod_list (p # qs) = n\" \"length (p#qs) \\<ge> 2\"\n        using \\<open>p dvd n\\<close> by simp_all\n      hence ?case by blast\n    } note case_prime = this\n    moreover\n    { assume \"n div p = 1\"\n      hence \"n = p\" using \\<open>n>3\\<close>  using One_leq_div[OF \\<open>p dvd n\\<close>] p'(2) by force\n      hence ?case using \\<open>prime p\\<close> \\<open>\\<not> prime n\\<close> by auto\n    }\n    moreover\n    { assume \"n div p = 2\"\n      hence ?case using case_prime by force\n    }\n    moreover\n    { assume \"n div p = 3\"\n      hence ?case using p' case_prime by force\n    }\n    ultimately show ?case using p' div_gt_0[of p n] case_prime by fastforce\n\nqed\n\nlemma prod_list_ge:\n  fixes xs::\"nat list\"\n  assumes \"\\<forall> x \\<in> set xs . x \\<ge> 1\"\n  shows \"prod_list xs \\<ge> 1\" using assms by (induction xs) auto\n\nlemma sum_list_log:\n  fixes b::real\n  fixes xs::\"nat list\"\n  assumes b: \"b > 0\" \"b \\<noteq> 1\"\n  assumes xs:\"\\<forall> x \\<in> set xs . x \\<ge> b\"\n  shows \"(\\<Sum>x\\<leftarrow>xs. log b x) = log b (prod_list xs)\"\n  using assms\nproof (induction xs)\n  case Nil\n    thus ?case by simp\n  next\n  case (Cons y ys)\n    have \"real (prod_list ys) > 0\" using prod_list_ge Cons.prems by fastforce\n    thus ?case using log_mult[OF Cons.prems(1-2)] Cons by force\nqed\n\nlemma concat_length_le:\n  fixes g :: \"nat \\<Rightarrow> real\"\n  assumes \"\\<forall> x \\<in> set xs . real (length (f x)) \\<le> g x\"\n  shows \"length (concat (map f xs)) \\<le> (\\<Sum>x\\<leftarrow>xs. g x)\" using assms\n  by (induction xs) force+\n\nlemma prime_gt_3_impl_p_minus_one_not_prime:\n  fixes p::nat\n  assumes \"prime p\" \"p>3\"\n  shows \"\\<not> prime (p - 1)\"\nproof\n  assume \"prime (p - 1)\"\n  have \"\\<not> even p\" using assms by (simp add: prime_odd_nat)\n  hence \"2 dvd (p - 1)\" by presburger\n  then obtain q where \"p - 1 = 2 * q\" ..\n  then have \"2 \\<in> prime_factors (p - 1)\" using \\<open>p>3\\<close>\n    by (auto simp: prime_factorization_times_prime)\n  thus False using prime_factors_of_prime \\<open>p>3\\<close> \\<open>prime (p - 1)\\<close> by auto\nqed\n\ntext \\<open>\n  We now prove that Pratt's proof system is complete and derive upper bounds for\n  the length and the size of the entries of a minimal certificate.\n\\<close>\n\ntheorem pratt_complete':\n  assumes \"prime p\"\n  shows \"\\<exists>c. Prime p \\<in> set c \\<and> valid_cert c \\<and> length c \\<le> 6*log 2 p - 4 \\<and> (\\<forall> x \\<in> set c. size_pratt x \\<le> 3 * log 2 p)\" using assms\nproof (induction p rule: less_induct)\n  case (less p)\n  from \\<open>prime p\\<close> have \"p > 1\" by (rule prime_gt_1_nat)\n  then consider \"p = 2\" | \" p = 3\" | \"p > 3\" by force\n  thus ?case\n  proof cases\n    assume [simp]: \"p = 2\"\n    have \"Prime p \\<in> set [Prime 2, Triple 2 1 1]\" by simp\n    thus ?case by fastforce\n  next\n    assume [simp]: \"p = 3\"\n    let ?cert = \"[Prime 3, Triple 3 2 2, Triple 3 2 1, Prime 2, Triple 2 1 1]\"\n\n    have \"length ?cert \\<le> 6*log 2 p - 4 \\<longleftrightarrow> 3 \\<le> 2 * log 2 3\" by simp\n    also have \"2 * log 2 3 = log 2 (3 ^ 2 :: real)\" by (subst log_nat_power) simp_all\n    also have \"\\<dots> = log 2 9\" by simp\n    also have \"3 \\<le> log 2 9 \\<longleftrightarrow> True\" by (subst le_log_iff) simp_all\n    finally show ?case\n      by (intro exI[where x = \"?cert\"]) (simp add: cong_def)\n  next\n    assume \"p > 3\"\n    have qlp: \"\\<forall>q \\<in> prime_factors (p - 1) . q < p\" using \\<open>prime p\\<close>\n      by (metis One_nat_def Suc_pred le_imp_less_Suc lessI less_trans p_in_prime_factorsE prime_gt_1_nat zero_less_diff)\n    hence factor_certs:\"\\<forall>q \\<in> prime_factors (p - 1) . (\\<exists>c . ((Prime q \\<in> set c) \\<and> (valid_cert c)\n                                                      \\<and> length c \\<le> 6*log 2 q - 4) \\<and> (\\<forall> x \\<in> set c. size_pratt x \\<le> 3 * log 2 q))\"\n      by (auto intro: less.IH)\n    obtain a where a:\"[a^(p - 1) = 1] (mod p) \\<and> (\\<forall> q. q \\<in> prime_factors (p - 1)\n              \\<longrightarrow> [a^((p - 1) div q) \\<noteq> 1] (mod p))\" and a_size: \"a > 0\" \"a < p\"\n      using converse_lehmer[OF \\<open>prime p\\<close>] by blast\n\n    have \"\\<not> prime (p - 1)\" using \\<open>p>3\\<close> prime_gt_3_impl_p_minus_one_not_prime \\<open>prime p\\<close> by auto\n    have \"p \\<noteq> 4\" using \\<open>prime p\\<close> by auto\n    hence \"p - 1 > 3\" using \\<open>p > 3\\<close> by auto\n\n    then obtain qs where prod_qs_eq:\"prod_list qs = p - 1\"\n        and qs_eq:\"set qs = prime_factors (p - 1)\" and qs_length_eq: \"length qs \\<ge> 2\"\n      using prime_factors_list[OF _ \\<open>\\<not> prime (p - 1)\\<close>] by auto\n    obtain f where f:\"\\<forall>q \\<in> prime_factors (p - 1) . \\<exists> c. f q = c\n                     \\<and> ((Prime q \\<in> set c) \\<and> (valid_cert c) \\<and> length c \\<le> 6*log 2 q - 4)\n                     \\<and> (\\<forall> x \\<in> set c. size_pratt x \\<le> 3 * log 2 q)\"\n      using factor_certs by metis\n    let ?cs = \"map f qs\"\n    have cs: \"\\<forall>q \\<in> prime_factors (p - 1) . (\\<exists>c \\<in> set ?cs . (Prime q \\<in> set c) \\<and> (valid_cert c)\n                                           \\<and> length c \\<le> 6*log 2 q - 4\n                                           \\<and> (\\<forall> x \\<in> set c. size_pratt x \\<le> 3 * log 2 q))\"\n      using f qs_eq by auto\n\n    have cs_cert_size: \"\\<forall>c \\<in> set ?cs . \\<forall> x \\<in> set c. size_pratt x \\<le> 3 * log 2 p\"\n    proof\n      fix c assume \"c \\<in> set (map f qs)\"\n      then obtain q where \"c = f q\" and \"q \\<in> set qs\" by auto\n      hence *:\"\\<forall> x \\<in> set c. size_pratt x \\<le> 3 * log 2 q\" using f qs_eq by blast\n      have \"q < p\" \"q > 0\" using qlp \\<open>q \\<in> set qs\\<close> qs_eq prime_factors_gt_0_nat by auto\n      show \"\\<forall> x \\<in> set c. size_pratt x \\<le> 3 * log 2 p\"\n      proof\n        fix x assume \"x \\<in> set c\"\n        hence \"size_pratt x \\<le> 3 * log 2 q\" using * by fastforce\n        also have \"\\<dots> \\<le> 3 * log 2 p\" using \\<open>q < p\\<close> \\<open>q > 0\\<close> \\<open>p > 3\\<close> by simp\n        finally show \"size_pratt x \\<le> 3 * log 2 p\" .\n      qed\n    qed\n\n    have cs_valid_all: \"\\<forall>c \\<in> set ?cs . valid_cert c\"\n      using f qs_eq by fastforce\n\n    have \"\\<forall>x \\<in> set (build_fpc p a (p - 1) qs). size_pratt x \\<le> 3 * log 2 p\"\n      using cs_cert_size a_size \\<open>p > 3\\<close> prod_qs_eq by (intro size_pratt_fpc) auto\n    hence \"\\<forall>x \\<in> set (build_fpc p a (p - 1) qs @ concat ?cs) . size_pratt x \\<le> 3 * log 2 p\"\n      using cs_cert_size by auto\n    moreover\n    have \"Triple p a (p - 1) \\<in> set (build_fpc p a (p - 1) qs @ concat ?cs)\" by (cases qs) auto\n    moreover\n    have \"valid_cert ((build_fpc p a (p - 1) qs)@ concat ?cs)\"\n    proof (rule correct_fpc)\n      show \"valid_cert (concat ?cs)\"\n        using cs_valid_all by (auto simp: valid_cert_concatI)\n      show \"prod_list qs = p - 1\" by (rule prod_qs_eq)\n      show \"p - 1 \\<noteq> 0\" using prime_gt_1_nat[OF \\<open>prime p\\<close>] by arith\n      show \"\\<forall> q \\<in> set qs . Prime q \\<in> set (concat ?cs)\"\n        using concat_set[of \"prime_factors (p - 1)\"] cs qs_eq by blast\n      show \"\\<forall> q \\<in> set qs . [a^((p - 1) div q) \\<noteq> 1] (mod p)\" using qs_eq a by auto\n    qed (insert \\<open>p > 3\\<close>, simp_all)\n    moreover\n    { let ?k = \"length qs\"\n\n      have qs_ge_2:\"\\<forall>q \\<in> set qs . q \\<ge> 2\" using qs_eq\n        by (auto intro: prime_ge_2_nat)\n\n      have \"\\<forall>x\\<in>set qs. real (length (f x)) \\<le> 6 * log 2 (real x) - 4\" using f qs_eq by blast\n      hence \"length (concat ?cs) \\<le> (\\<Sum>q\\<leftarrow>qs. 6*log 2 q - 4)\" using concat_length_le\n        by fast\n      hence \"length (Prime p # ((build_fpc p a (p - 1) qs)@ concat ?cs))\n            \\<le> ((\\<Sum>q\\<leftarrow>(map real qs). 6*log 2 q - 4) + ?k + 2)\"\n            by (simp add: o_def length_fpc)\n      also have \"\\<dots> = (6*(\\<Sum>q\\<leftarrow>(map real qs). log 2 q) + (-4 * real ?k) + ?k + 2)\"\n        by (simp add: o_def sum_list_subtractf sum_list_triv sum_list_const_mult)\n      also have \"\\<dots> \\<le> 6*log 2 (p - 1) - 4\" using \\<open>?k\\<ge>2\\<close> prod_qs_eq sum_list_log[of 2 qs] qs_ge_2\n        by force\n      also have \"\\<dots> \\<le> 6*log 2 p - 4\" using log_le_cancel_iff[of 2 \"p - 1\" p] \\<open>p>3\\<close> by force\n      ultimately have \"length (Prime p # ((build_fpc p a (p - 1) qs)@ concat ?cs))\n                       \\<le> 6*log 2 p - 4\" by linarith }\n    ultimately obtain c where c:\"Triple p a (p - 1) \\<in> set c\" \"valid_cert c\"\n                               \"length (Prime p #c) \\<le> 6*log 2 p - 4\"\n                               \"(\\<forall> x \\<in> set c. size_pratt x \\<le> 3 * log 2 p)\" by blast\n    hence \"Prime p \\<in> set (Prime p # c)\" \"valid_cert (Prime p # c)\"\n         \"(\\<forall> x \\<in> set (Prime p # c). size_pratt x \\<le> 3 * log 2 p)\"\n    using a \\<open>prime p\\<close> by (auto simp: Primes.prime_gt_Suc_0_nat)\n    thus ?case using c by blast\n  qed\nqed\n\ntext \\<open>\n  We now recapitulate our results. A number $p$ is prime if and only if there\n  is a certificate for $p$. Moreover, for a prime $p$ there always is a certificate\n  whose size is polynomially bounded in the logarithm of $p$.\n\\<close>\n\ncorollary pratt:\n  \"prime p \\<longleftrightarrow> (\\<exists>c. Prime p \\<in> set c \\<and> valid_cert c)\"\n  using pratt_complete' pratt_sound(1) by blast\n\ncorollary pratt_size:\n  assumes \"prime p\"\n  shows \"\\<exists>c. Prime p \\<in> set c \\<and> valid_cert c \\<and> size_cert c \\<le> (6 * log 2 p - 4) * (1 + 3 * log 2 p)\"\nproof -\n  obtain c where c: \"Prime p \\<in> set c\" \"valid_cert c\"\n      and len: \"length c \\<le> 6*log 2 p - 4\" and \"(\\<forall> x \\<in> set c. size_pratt x \\<le> 3 * log 2 p)\"\n    using pratt_complete' assms by blast\n  hence \"size_cert c \\<le> length c * (1 + 3 * log 2 p)\" by (simp add: size_pratt_le)\n  also have \"\\<dots> \\<le> (6*log 2 p - 4) * (1 + 3 * log 2 p)\" using len by simp\n  finally show ?thesis using c by blast\nqed\n\n\nsubsection \\<open>Efficient modular exponentiation\\<close>\n\nlocale efficient_power =\n  fixes f :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a\"\n  assumes f_assoc: \"\\<And>x z. f x (f x z) = f (f x x) z\"\nbegin\n\nfunction efficient_power :: \"'a \\<Rightarrow> 'a \\<Rightarrow> nat \\<Rightarrow> 'a\" where\n  \"efficient_power y x 0 = y\"\n| \"efficient_power y x (Suc 0) = f x y\"\n| \"n \\<noteq> 0 \\<Longrightarrow> even n \\<Longrightarrow> efficient_power y x n = efficient_power y (f x x) (n div 2)\"\n| \"n \\<noteq> 1 \\<Longrightarrow> odd n \\<Longrightarrow> efficient_power y x n = efficient_power (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_power_code:\n  \"efficient_power 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_power y (f x x) (n div 2)\n      else efficient_power (f x y) (f x x) (n div 2))\"\n  by (induction y x n rule: efficient_power.induct) auto\n\nlemma efficient_power_correct: \"efficient_power 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_power.induct)\n       (auto elim!: evenE oddE simp: funpow_mult [symmetric] funpow_Suc_right f_assoc\n             simp del: funpow.simps(2))\nqed\n\nend\n\ninterpretation mod_exp_nat: efficient_power \"\\<lambda>x y :: nat. (x * y) mod m\"\n  by standard (simp add: mod_mult_left_eq mod_mult_right_eq mult_ac)\n\ndefinition mod_exp_nat_aux where \"mod_exp_nat_aux = mod_exp_nat.efficient_power\"\n\nlemma mod_exp_nat_aux_code [code]:\n  \"mod_exp_nat_aux m y x n =\n     (if n = 0 then y\n      else if n = 1 then (x * y) mod m\n      else if even n then mod_exp_nat_aux m y ((x * x) mod m) (n div 2)\n      else mod_exp_nat_aux m ((x * y) mod m) ((x * x) mod m) (n div 2))\"\n  unfolding mod_exp_nat_aux_def by (rule mod_exp_nat.efficient_power_code)\n\nlemma mod_exp_nat_aux_correct:\n  \"mod_exp_nat_aux m y x n mod m = (x ^ n * y) mod m\"\nproof -\n  have \"mod_exp_nat_aux m y x n = ((\\<lambda>y. x * y mod m) ^^ n) y\"\n    by (simp add: mod_exp_nat_aux_def mod_exp_nat.efficient_power_correct)\n  also have \"((\\<lambda>y. x * y mod m) ^^ n) y mod m = (x ^ n * y) mod m\"\n  proof (induction n)\n    case (Suc n)\n    hence \"x * ((\\<lambda>y. x * y mod m) ^^ n) y mod m = x * x ^ n * y mod m\"\n      by (metis mod_mult_right_eq mult.assoc)\n    thus ?case by auto\n  qed auto\n  finally show ?thesis .\nqed\n\ndefinition mod_exp_nat :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> nat\"\n  where [code_abbrev]: \"mod_exp_nat b e m = (b ^ e) mod m\"\n\nlemma mod_exp_nat_code [code]: \"mod_exp_nat b e m = mod_exp_nat_aux m 1 b e mod m\"\n  by (simp add: mod_exp_nat_def mod_exp_nat_aux_correct)\n\nlemmas [code_unfold] = cong_def\n\nlemma eval_mod_exp_nat_aux [simp]:\n  \"mod_exp_nat_aux m y x 0 = y\"\n  \"mod_exp_nat_aux m y x (Suc 0) = (x * y) mod m\"\n  \"mod_exp_nat_aux m y x (numeral (num.Bit0 n)) =\n     mod_exp_nat_aux m y (x\\<^sup>2 mod m) (numeral n)\"\n  \"mod_exp_nat_aux m y x (numeral (num.Bit1 n)) =\n     mod_exp_nat_aux m ((x * y) mod m) (x\\<^sup>2 mod m) (numeral n)\"\nproof -\n  define n' where \"n' = (numeral n :: nat)\"\n  have [simp]: \"n' \\<noteq> 0\" by (auto simp: n'_def)\n  \n  show \"mod_exp_nat_aux m y x 0 = y\" and \"mod_exp_nat_aux m y x (Suc 0) = (x * y) mod m\"\n    by (simp_all add: mod_exp_nat_aux_def)\n\n  have \"numeral (num.Bit0 n) = (2 * n')\"\n    by (subst numeral.numeral_Bit0) (simp del: arith_simps add: n'_def)\n  also have \"mod_exp_nat_aux m y x \\<dots> = mod_exp_nat_aux m y (x^2 mod m) n'\"\n    by (subst mod_exp_nat_aux_code) (simp_all add: power2_eq_square)\n  finally show \"mod_exp_nat_aux m y x (numeral (num.Bit0 n)) =\n                  mod_exp_nat_aux m y (x\\<^sup>2 mod m) (numeral n)\"\n    by (simp add: n'_def)\n\n  have \"numeral (num.Bit1 n) = Suc (2 * n')\"\n    by (subst numeral.numeral_Bit1) (simp del: arith_simps add: n'_def)\n  also have \"mod_exp_nat_aux m y x \\<dots> = mod_exp_nat_aux m ((x * y) mod m) (x^2 mod m) n'\"\n    by (subst mod_exp_nat_aux_code) (simp_all add: power2_eq_square)\n  finally show \"mod_exp_nat_aux m y x (numeral (num.Bit1 n)) =\n                  mod_exp_nat_aux m ((x * y) mod m) (x\\<^sup>2 mod m) (numeral n)\"\n    by (simp add: n'_def)\nqed\n\nlemma eval_mod_exp [simp]:\n  \"mod_exp_nat b' 0 m' = 1 mod m'\"\n  \"mod_exp_nat b' 1 m' = b' mod m'\"\n  \"mod_exp_nat b' (Suc 0) m' = b' mod m'\"\n  \"mod_exp_nat b' e' 0 = b' ^ e'\"  \n  \"mod_exp_nat b' e' 1 = 0\"\n  \"mod_exp_nat b' e' (Suc 0) = 0\"\n  \"mod_exp_nat 0 1 m' = 0\"\n  \"mod_exp_nat 0 (Suc 0) m' = 0\"\n  \"mod_exp_nat 0 (numeral e) m' = 0\"\n  \"mod_exp_nat 1 e' m' = 1 mod m'\"\n  \"mod_exp_nat (Suc 0) e' m' = 1 mod m'\"\n  \"mod_exp_nat (numeral b) (numeral e) (numeral m) =\n     mod_exp_nat_aux (numeral m) 1 (numeral b) (numeral e) mod numeral m\"\n  by (simp_all add: mod_exp_nat_def mod_exp_nat_aux_correct)\n\n\n\nsubsection \\<open>Executable certificate checker\\<close>\n\nlemmas [code] = valid_cert.simps(1)\n\ncontext\nbegin\n\nlemma valid_cert_Cons1 [code]:\n  \"valid_cert (Prime p # xs) \\<longleftrightarrow>\n     p > 1 \\<and> (\\<exists>t\\<in>set xs. case t of Prime _ \\<Rightarrow> False | \n     Triple p' a x \\<Rightarrow> p' = p \\<and> x = p - 1 \\<and> mod_exp_nat a (p-1) p = 1 ) \\<and> valid_cert xs\"\n  (is \"?lhs = ?rhs\")\nproof\n  assume ?lhs thus ?rhs by (auto simp: mod_exp_nat_def cong_def split: pratt.splits)\nnext\n  assume ?rhs\n  hence \"p > 1\" \"valid_cert xs\" by blast+\n  moreover from \\<open>?rhs\\<close> obtain t where \"t \\<in> set xs\" \"case t of Prime _ \\<Rightarrow> False | \n     Triple p' a x \\<Rightarrow> p' = p \\<and> x = p - 1 \\<and> [a^(p-1) = 1] (mod p)\" \n     by (auto simp: cong_def mod_exp_nat_def cong: pratt.case_cong)\n  ultimately show ?lhs by (cases t) auto\nqed\n\nprivate lemma Suc_0_mod_eq_Suc_0_iff:\n  \"Suc 0 mod n = Suc 0 \\<longleftrightarrow> n \\<noteq> Suc 0\"\nproof -\n  consider \"n = 0\" | \"n = Suc 0\" | \"n > 1\" by (cases n) auto\n  thus ?thesis by cases auto\nqed\n\nprivate lemma Suc_0_eq_Suc_0_mod_iff:\n  \"Suc 0 = Suc 0 mod n \\<longleftrightarrow> n \\<noteq> Suc 0\"\n  using Suc_0_mod_eq_Suc_0_iff by (simp add: eq_commute)\n\nlemma valid_cert_Cons2 [code]:\n  \"valid_cert (Triple p a x # xs) \\<longleftrightarrow> x > 0 \\<and> p > 1 \\<and> (x = 1 \\<or> (\n     (\\<exists>t\\<in>set xs. case t of Prime _ \\<Rightarrow> False |\n        Triple p' a' y \\<Rightarrow> p' = p \\<and> a' = a \\<and> y dvd x \\<and> \n        (let q = x div y in Prime q \\<in> set xs \\<and> mod_exp_nat a ((p-1) div q) p \\<noteq> 1)))) \\<and> valid_cert xs\"\n  (is \"?lhs = ?rhs\")\nproof\n  assume ?lhs\n  from \\<open>?lhs\\<close> have pos: \"x > 0\" and gt_1: \"p > 1\" and valid: \"valid_cert xs\" by simp_all\n  show ?rhs\n  proof (cases \"x = 1\")\n    case True\n    with \\<open>?lhs\\<close> show ?thesis by auto\n  next\n    case False\n    with \\<open>?lhs\\<close> have \"(\\<exists>q y. x = q * y \\<and> Prime q \\<in> set xs \\<and> Triple p a y \\<in> set xs\n      \\<and> [a^((p - 1) div q) \\<noteq> 1] (mod p))\" by auto\n    then obtain q y where qy:\n      \"x = q * y\"\n      \"Prime q \\<in> set xs\"\n      \"Triple p a y \\<in> set xs\"\n      \"[a ^ ((p - 1) div q) \\<noteq> 1] (mod p)\"\n      by blast\n    hence \"(\\<exists>t\\<in>set xs. case t of Prime _ \\<Rightarrow> False |\n        Triple p' a' y \\<Rightarrow> p' = p \\<and> a' = a \\<and> y dvd x \\<and> \n        (let q = x div y in Prime q \\<in> set xs \\<and> mod_exp_nat a ((p-1) div q) p \\<noteq> 1))\"\n    using pos gt_1 by (intro bexI [of _ \"Triple p a y\"]) \n      (auto simp: Suc_0_mod_eq_Suc_0_iff Suc_0_eq_Suc_0_mod_iff cong_def mod_exp_nat_def)\n    with pos gt_1 valid show ?thesis by blast\n  qed\nnext\n  assume ?rhs\n  hence pos: \"x > 0\" and gt_1: \"p > 1\" and valid: \"valid_cert xs\" by simp_all\n  show ?lhs\n  proof (cases \"x = 1\")\n    case True\n    with \\<open>?rhs\\<close> show ?thesis by auto\n  next\n    case False\n    with \\<open>?rhs\\<close> obtain t where t: \"t \\<in> set xs\" \"case t of Prime x \\<Rightarrow> False\n         | Triple p' a' y \\<Rightarrow> p' = p \\<and> a' = a \\<and> y dvd x \\<and> (let q = x div y\n              in Prime q \\<in> set xs \\<and> mod_exp_nat a ((p - 1) div q) p \\<noteq> 1)\" by auto\n    then obtain y where y: \"t = Triple p a y\" \"y dvd x\" \"let q = x div y in Prime q \\<in> set xs \\<and> \n                              mod_exp_nat a ((p - 1) div q) p \\<noteq> 1\" \n      by (cases t rule: pratt.exhaust) auto\n    with gt_1 have y': \"let q = x div y in Prime q \\<in> set xs \\<and> [a^((p - 1) div q) \\<noteq> 1] (mod p)\"\n      by (auto simp: cong_def Let_def mod_exp_nat_def Suc_0_mod_eq_Suc_0_iff Suc_0_eq_Suc_0_mod_iff)\n    define q where \"q = x div y\"\n    have \"\\<exists>q y. x = q * y \\<and> Prime q \\<in> set xs \\<and> Triple p a y \\<in> set xs\n                     \\<and> [a^((p - 1) div q) \\<noteq> 1] (mod p)\"\n      by (rule exI[of _ q], rule exI[of _ y]) (insert t y y', auto simp: Let_def q_def)\n    with pos gt_1 valid show ?thesis by simp\n  qed\nqed\n\ndeclare valid_cert.simps(2,3) [simp del]\n\nlemmas eval_valid_cert = valid_cert.simps(1) valid_cert_Cons1 valid_cert_Cons2\n\nend\n\n\ntext \\<open>\n  The following alternative tree representation of certificates is better suited for \n  efficient checking.\n\\<close>\n\ndatatype pratt_tree = Pratt_Node \"nat \\<times> nat \\<times> pratt_tree list\"\n\nfun pratt_tree_number where\n  \"pratt_tree_number (Pratt_Node (n, _, _)) = n\"\n\n\ntext \\<open>\n  The following function checks that a given list contains all the prime factors of the given\n  number.\n\\<close>\n\nfun check_prime_factors_subset :: \"nat \\<Rightarrow> nat list \\<Rightarrow> bool\" where\n  \"check_prime_factors_subset n [] \\<longleftrightarrow> n = 1\"\n| \"check_prime_factors_subset n (p # ps) \\<longleftrightarrow> (if n = 0 then False else\n     (if p > 1 \\<and> p dvd n then check_prime_factors_subset (n div p) (p # ps)\n                         else check_prime_factors_subset n ps))\"\n\nlemma check_prime_factors_subset_0 [simp]: \"\\<not>check_prime_factors_subset 0 ps\"\n  by (induction ps) auto\n\nlemmas [simp del] = check_prime_factors_subset.simps(2)\n\nlemma check_prime_factors_subset_Cons [simp]:\n  \"check_prime_factors_subset (Suc 0) (p # ps) \\<longleftrightarrow> check_prime_factors_subset (Suc 0) ps\"\n  \"check_prime_factors_subset 1 (p # ps) \\<longleftrightarrow> check_prime_factors_subset 1 ps\"\n  \"p > 1 \\<Longrightarrow> p dvd numeral n \\<Longrightarrow> check_prime_factors_subset (numeral n) (p # ps) \\<longleftrightarrow>\n                           check_prime_factors_subset (numeral n div p) (p # ps)\"\n  \"p \\<le> 1 \\<or> \\<not>p dvd numeral n \\<Longrightarrow> check_prime_factors_subset (numeral n) (p # ps) \\<longleftrightarrow>\n                           check_prime_factors_subset (numeral n) ps\"\n by (subst check_prime_factors_subset.simps; force)+\n\nlemma check_prime_factors_subset_correct:\n  assumes \"check_prime_factors_subset n ps\" \"list_all prime ps\"\n  shows   \"prime_factors n \\<subseteq> set ps\"\n  using assms\nproof (induction n ps rule: check_prime_factors_subset.induct)\n  case (2 n p ps)\n  note * = this\n  from \"2.prems\" have \"prime p\" and \"p > 1\"\n    by (auto simp: prime_gt_Suc_0_nat)\n\n  consider \"n = 0\" | \"n > 0\" \"p dvd n\" | \"n > 0\" \"\\<not>(p dvd n)\"\n    by blast\n  thus ?case\n  proof cases\n    case 2\n    hence \"n div p > 0\" by auto\n    hence \"prime_factors ((n div p) * p) = insert p (prime_factors (n div p))\"\n      using \\<open>p > 1\\<close> \\<open>prime p\\<close> by (auto simp: prime_factors_product prime_prime_factors)\n    also have \"(n div p) * p = n\"\n      using 2 by auto\n    finally show ?thesis using 2 \\<open>p > 1\\<close> *\n      by (auto simp: check_prime_factors_subset.simps(2)[of n])\n  next\n    case 3\n    with * and \\<open>p > 1\\<close> show ?thesis\n      by (auto simp: check_prime_factors_subset.simps(2)[of n])\n  qed auto\nqed auto\n\n\nfun valid_pratt_tree where\n  \"valid_pratt_tree (Pratt_Node (n, a, ts)) \\<longleftrightarrow>\n     n \\<ge> 2 \\<and>\n     check_prime_factors_subset (n - 1) (map pratt_tree_number ts) \\<and>\n     [a ^ (n - 1) = 1] (mod n) \\<and>\n     (\\<forall>t\\<in>set ts. [a ^ ((n - 1) div pratt_tree_number t) \\<noteq> 1] (mod n)) \\<and>\n     (\\<forall>t\\<in>set ts. valid_pratt_tree t)\"\n\nlemma valid_pratt_tree_code [code]:\n  \"valid_pratt_tree (Pratt_Node (n, a, ts)) \\<longleftrightarrow>\n     n \\<ge> 2 \\<and>\n     check_prime_factors_subset (n - 1) (map pratt_tree_number ts) \\<and>\n     mod_exp_nat a (n - 1) n = 1 \\<and>\n     (\\<forall>t\\<in>set ts. mod_exp_nat a ((n - 1) div pratt_tree_number t) n \\<noteq> 1) \\<and>\n     (\\<forall>t\\<in>set ts. valid_pratt_tree t)\"\n  by (simp add: mod_exp_nat_def cong_def)\n\nlemma valid_pratt_tree_imp_prime:\n  assumes \"valid_pratt_tree t\"\n  shows   \"prime (pratt_tree_number t)\"\n  using assms\nproof (induction t rule: valid_pratt_tree.induct)\n  case (1 n a ts)\n  from 1 have \"prime_factors (n - 1) \\<subseteq> set (map pratt_tree_number ts)\"\n    by (intro check_prime_factors_subset_correct) (auto simp: list.pred_set)\n  with 1 show ?case\n    by (intro lehmers_theorem[where a = a]) auto\nqed\n\nlemma valid_pratt_tree_imp_prime':\n  assumes \"PROP (Trueprop (valid_pratt_tree (Pratt_Node (n, a, ts)))) \\<equiv> PROP (Trueprop True)\"\n  shows   \"prime n\"\nproof -\n  have \"valid_pratt_tree (Pratt_Node (n, a, ts))\"\n    by (subst assms) auto\n  from valid_pratt_tree_imp_prime[OF this] show ?thesis by simp\nqed\n\n\nsubsection \\<open>Proof method setup\\<close>\n\ntheorem lehmers_theorem':\n  fixes p :: nat\n  assumes \"list_all prime ps\" \"a \\<equiv> a\" \"n \\<equiv> n\"\n  assumes \"list_all (\\<lambda>p. mod_exp_nat a ((n - 1) div p) n \\<noteq> 1) ps\" \"mod_exp_nat a (n - 1) n = 1\"\n  assumes \"check_prime_factors_subset (n - 1) ps\" \"2 \\<le> n\"\n  shows \"prime n\"\n  using assms check_prime_factors_subset_correct[OF assms(6,1)]\n  by (intro lehmers_theorem[where a = a]) (auto simp: cong_def mod_exp_nat_def list.pred_set)\n\nlemma list_all_ConsI: \"P x \\<Longrightarrow> list_all P xs \\<Longrightarrow> list_all P (x # xs)\"\n  by simp\n\nML_file \\<open>pratt.ML\\<close>\n\nmethod_setup pratt = \\<open>\n  Scan.lift (Pratt.tac_config_parser -- Scan.option Pratt.cert_cartouche) >> \n    (fn (config, cert) => fn ctxt => SIMPLE_METHOD (HEADGOAL (Pratt.tac config cert ctxt)))\n\\<close> \"Prove primality of natural numbers using Pratt certificates.\"\n\ntext \\<open>\n  The proof method replays a given Pratt certificate to prove the primality of a given number.\n  If no certificate is given, the method attempts to compute one. The computed certificate is then\n  also printed with a prompt to insert it into the proof document so that it does not have to\n  be recomputed the next time.\n\n  The format of the certificates is compatible with those generated by Mathematica. Therefore,\n  for larger numbers, certificates generated by Mathematica can be used with this method directly.\n\\<close>\nlemma \"prime (47 :: nat)\"\n  by (pratt (silent))\n\nlemma \"prime (2503 :: nat)\"\n  by pratt\n\nlemma \"prime (7919 :: nat)\"\n  by pratt\n\nlemma \"prime (131059 :: nat)\"\n  by (pratt \\<open>{131059, 2, {2, {3, 2, {2}}, {809, 3, {2, {101, 2, {2, {5, 2, {2}}}}}}}}\\<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/Pratt_Certificate/Pratt_Certificate.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8479677583778258, "lm_q2_score": 0.8438951084436076, "lm_q1q2_score": 0.7155958434129381}}
{"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 Main \"~~/src/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\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\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": "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/Functions.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.843895106480586, "lm_q2_score": 0.8479677583778258, "lm_q1q2_score": 0.7155958417483591}}
{"text": "(*<*)\ntheory Untyped_Arithmetic_Expressions\nimports Main\nbegin\n(*>*)\n\nsection {* Untyped Arithmetic Expressions *}\ntext {* \\label{sec:untyped-arith-expr} *}\n\ntext {*\nThe language of untyped arithmetic expressions consists of Boolean expressions, containing the\nconstants \\texttt{true} and \\texttt{false} and conditionals as primitives, and natural numbers,\ncontaining the constant \\texttt{zero}, the successor and predecessor functions and an operation to\ntest equality with zero as primitives. Following the book, we start with a subset containing only\nthe Boolean expression and carry on with fully fledged arithmetic expressions.\n*}\n\nsubsection {* Booleans *}\n\ntext \\<open>\nThe syntax of this language is defined, in the book, in the following way:\n\\begin{align*}\n  t ::= & \\\\\n    & \\text{true} && \\text{constant true} \\\\\n    & \\text{false} && \\text{constant false} \\\\\n    & \\text{if } t \\text{ then } t \\text{ else } t && \\text{conditional}\n\\end{align*}\n\nIts counterpart, using Isabelle/HOL's syntax, is a recursive datatype: \\footnote{To prevent\nname clashes with Isabelle's predefined types and constants of the same name, our types and type\nconstructors are prefixed with \\texttt{b}, which stand for \\emph{Booleans}. Functions use a suffix\nfor the same purpose.}\n\\<close>\n\ndatatype bterm =\n  BTrue |\n  BFalse |\n  BIf bterm bterm bterm\n\ntext \\<open>\nThe semantics of the language is defined using the small-step operational semantics which consists\nof an evaluation relation that performs the smallest possible step towards the final value. Values\nare a subset of terms that are considered as the final output of a computation. For the Booleans,\nthe only values are the constants @{term BTrue} and @{term BFalse}. To describe these, the book uses\nthe following notation:\n\\begin{align*}\n  t ::= & \\\\\n    & \\text{true} && \\text{true value} \\\\\n    & \\text{false} && \\text{false value}\n\\end{align*}\n\nWe translate this in Isabelle/HOL using an inductive predicate that returns true if its argument is\na value:\n\\<close>\n\ninductive is_value_B :: \"bterm \\<Rightarrow> bool\" where\n  \"is_value_B BTrue\" |\n  \"is_value_B BFalse\"\n\ntext \\<open>\nThe evaluation relation is concerned with the way a conditional expression will be reduced. The book\nuses the standard mathematical notation for inference rules:\n\\begin{gather}\n  \\inferrule {}{\\text{if true then } t_2 \\text{ else } t_3 \\implies t_2} \\\\[0.8em]\n  \\inferrule {}{\\text{if false then } t_2 \\text{ else } t_3 \\implies t_3} \\\\[0.8em]\n  \\inferrule {t_1 \\implies t_1'}\n    {\\text{if } t_1 \\text{ then } t_2 \\text{ else } t_3\n      \\implies \\text{if } t_1' \\text{ then } t_2 \\text{ else } t_3}\n\\end{gather}\n\nThe first rule states that the evaluation of a conditional with a true condition leads to the\n``then'' branch, the second rule states that the evaluation of a conditional with a false condition\nleads to the ``else'' branch and the third rule states that, if the condition is not a Boolean\nconstant, it must be itself evaluated. These rules translate easily into another inductive predicate\nthat returns true if the first argument can be reduced in one step to the second argument:\n\\<close>\n\ninductive eval1_B :: \"bterm \\<Rightarrow> bterm \\<Rightarrow> bool\" where\n  eval1_BIf_BTrue:\n    \"eval1_B (BIf BTrue t2 t3) t2\" |\n  eval1_BIf_BFalse:\n    \"eval1_B (BIf BFalse t2 t3) t3\" |\n  eval1_BIf:\n    \"eval1_B t1 t1' \\<Longrightarrow> eval1_B (BIf t1 t2 t3) (BIf t1' t2 t3)\"\n\n(*<*)\n(* Example of definition 3.5.3 *)\n\nlemma\n  assumes\n    s: \"s = BIf BTrue BFalse BFalse\" and\n    t: \"t = BIf s BTrue BTrue\" and\n    u: \"u = BIf BFalse BTrue BTrue\"\n  shows \"eval1_B (BIf t BFalse BFalse) (BIf u BFalse BFalse)\"\nproof -\n  have \"eval1_B s BFalse\" unfolding s by (rule eval1_BIf_BTrue)\n  hence \"eval1_B t u\" unfolding t u by (rule eval1_BIf)\n  thus ?thesis by (rule eval1_BIf)\nqed\n(*>*)\n(* subsubsection {* Theorem 3.5.4 *} *)\n\ntext {*\nWith these basic definitions, we can turn to the first theorem: the determinacy of one-step\nevaluation. This theorem states that the evaluation relation is deterministic (i.e. there is only\none way in which a given term can be evaluate). The focus of this paper being on the definitions and\ntheorems, we can skim over the proof, just highlighting that it goes by induction over the\nevaluation relation and that it involves some case analyses:\n*}\n\ntheorem eval1_B_determinacy:\n  \"eval1_B t t' \\<Longrightarrow> eval1_B t t'' \\<Longrightarrow> t' = t''\"\nproof (induction t t' arbitrary: t'' rule: eval1_B.induct)\n  case (eval1_BIf_BTrue t1 t2)\n  thus ?case by (auto elim: eval1_B.cases)\nnext\n  case (eval1_BIf_BFalse t1 t2)\n  thus ?case by (auto elim: eval1_B.cases)\nnext\n  case (eval1_BIf t1 t1' t2 t3)\n  from eval1_BIf.prems eval1_BIf.hyps show ?case\n    by (auto dest: eval1_BIf.IH elim: eval1_B.cases)\nqed\n\n(* subsubsection {* Theorem 3.5.7 *} *)\n\ntext {*\nA key concept is that of normal form, for which the book gives the following definition:\n\\begin{quotation}\n  \\noindent A term $t$ is in \\emph{normal form} if no evaluation rule applies to it --- i.e.,\n  if there is no $t'$ such that $t \\to t'$.\n\\end{quotation}\nSince this definition mainly introduces some standard terminology for a property of terms with\nrespect to the single-step evaluation relation, we translate it using a simple definition:\n\\newpage\n*}\n\ndefinition is_normal_form_B :: \"bterm \\<Rightarrow> bool\" where\n  \"is_normal_form_B t \\<longleftrightarrow> (\\<forall>t'. \\<not> eval1_B t t')\"\n\ntext {*\nWe continue by proving that every value is in normal form:\n*}\n\ntheorem value_imp_normal_form:\n  \"is_value_B t \\<Longrightarrow> is_normal_form_B t\"\nby (auto elim: is_value_B.cases eval1_B.cases simp: is_normal_form_B_def)\n\n(* subsubsection {* Theorem 3.5.8 *} *)\n\ntext {*\nFor this simple language, the converse is also true: every term in normal form is a value. Our proof\nfollows the book and use contradiction, structural induction over @{term t} and case analysis over\nthe possible values.\n*}\n\ntheorem normal_form_imp_value:\n  \"is_normal_form_B t \\<Longrightarrow> is_value_B t\"\nby (rule ccontr, induction t rule: bterm.induct)\n  (auto\n    intro: eval1_B.intros is_value_B.intros\n    elim: is_value_B.cases\n    simp: is_normal_form_B_def)\n\n(* subsubsection {* Definition 3.5.9 *} *)\n\ntext {*\nThe one-step evaluation is a useful representation of the semantic of a language, but it does not\nrepresent what really interests us: the final value of an evaluation. To this end, the book defines\na multi-step evaluation relation based on the single-step one:\n\n\\begin{quotation}\n  \\noindent The \\emph{multi-step evaluation} relation $\\to^*$ is the reflexive, transitive closure\n  of one-step evaluation. That is, it is the smallest relation such that (1)~if t $t \\to t'$ then\n  $t \\to^* t'$, (2)~$t \\to^* t$ for all $t$, and (3)~if $t \\to^* t'$ and $t' \\to^* t''$, then\n  $t \\to^* t''$.\n\\end{quotation}\n\nA direct translation to Isabelle/HOL would lead to the following definition:\n*}\n\ninductive eval_direct :: \"bterm \\<Rightarrow> bterm \\<Rightarrow> bool\" where\n  e_once:\n    \"eval1_B t t' \\<Longrightarrow> eval_direct t t'\" |\n  e_self:\n    \"eval_direct t t\" |\n  e_transitive:\n    \"eval_direct t t' \\<Longrightarrow> eval_direct t' t'' \\<Longrightarrow> eval_direct t t''\"\n\ntext {*\nHowever, this definition is inconvenient for theorem proving because it requires us to consider\nthree cases for each induction on a evaluation relation. Instead, we choose to define the multi-step\nevaluation relation using a shape similar to a list of one-step evaluations. The inductive\ndefinition consists of a base case, the reflexive application, and of an inductive case where one\nstep of evaluation is performed:\n\\newpage\n*}\n\ninductive eval_B :: \"bterm \\<Rightarrow> bterm \\<Rightarrow> bool\" where\n  eval_B_base:\n    \"eval_B t t\" |\n  eval_B_step:\n    \"eval1_B t t' \\<Longrightarrow> eval_B t' t'' \\<Longrightarrow> eval_B t t''\"\n\ntext {*\nWe then prove that this definition is equivalent to the direct translation of the definition found\nin the book:\n*}\n\nlemma eval_B_once:\n  \"eval1_B t t' \\<Longrightarrow> eval_B t t'\"\nby (simp add: eval_B.intros)\n\nlemma eval_B_transitive:\n  \"eval_B t t' \\<Longrightarrow> eval_B t' t'' \\<Longrightarrow> eval_B t t''\"\nby (induction t t' rule: eval_B.induct) (auto intro: eval_B.intros)\n\nlemma eval_direct_eq_eval_B:\n  \"eval_direct = eval_B\"\nproof ((rule ext)+, rule iffI)\n  fix t t'\n  assume \"eval_direct t t'\"\n  thus \"eval_B t t'\"\n    by (auto intro: eval_B.intros elim: eval_direct.induct eval_B_once eval_B_transitive)\nnext\n  fix t t'\n  assume \"eval_B t t'\"\n  thus \"eval_direct t t'\"\n    by (auto intro: e_self dest!: e_once elim: eval_B.induct e_transitive)\nqed\n\n(* subsubsection {* Corollary 3.5.11 *} *)\n\ntext {*\nThe next theorem we consider is the uniqueness of normal form, which is a corollary of the\ndeterminacy of the single-step evaluation:\n*}\n\ncorollary uniqueness_of_normal_form:\n  \"eval_B t u \\<Longrightarrow> is_normal_form_B u \\<Longrightarrow>\n  eval_B t u' \\<Longrightarrow> is_normal_form_B u' \\<Longrightarrow>\n  u = u'\"\nby (induction t u rule: eval_B.induct)\n  (metis eval_B.cases is_normal_form_B_def eval1_B_determinacy)+\n\ntext {*\nThe last theorem we consider is the termination of evaluation. To prove it, we need first to add a\nhelper lemma, which was implicitly assumed in the book, about the size of terms after evaluation:\n\\newline\n*}\n(*<*)\n(* subsubsection {* Theorem 3.5.12 *} *)\n\nprimrec size_B :: \"bterm \\<Rightarrow> nat\" where\n  \"size_B BTrue = 1\" |\n  \"size_B BFalse = 1\" |\n  \"size_B (BIf t1 t2 t3) = 1 + size_B t1 + size_B t2 + size_B t3\"\n(*>*)\nlemma eval_once_size_B:\n  \"eval1_B t t' \\<Longrightarrow> size_B t > size_B t'\"\nby (induction t t' rule: eval1_B.induct) simp_all\n\ntheorem termination_of_evaluation:\n  \"\\<exists>t'. eval_B t t' \\<and> is_normal_form_B t'\"\nby (induction rule: measure_induct_rule[of size_B])\n  (metis eval_B.intros eval_once_size_B is_normal_form_B_def)\n\nsubsection {* Arithmetic Expressions *}\n\ntext {*\nWe now turn to the fully fledged arithmetic expression language. The syntax is defined in the same\nway as for Booleans:\\footnote{The prefix \\emph{nb} stands for \\emph{numeric and Booleans}.}\n*}\n\ndatatype nbterm =\n  NBTrue |\n  NBFalse |\n  NBIf nbterm nbterm nbterm |\n  NBZero |\n  NBSucc nbterm |\n  NBPred nbterm |\n  NBIs_zero nbterm\n(*<*)\n\n(* subsubsection {* Definition 3.3.1 *} *)\n\nprimrec const_NB :: \"nbterm \\<Rightarrow> nbterm set\" where\n  \"const_NB NBTrue = {NBTrue}\" |\n  \"const_NB NBFalse = {NBFalse}\" |\n  \"const_NB NBZero = {NBZero}\" |\n  \"const_NB (NBSucc t) = const_NB t\" |\n  \"const_NB (NBPred t) = const_NB t\" |\n  \"const_NB (NBIs_zero t) = const_NB t\" |\n  \"const_NB (NBIf t1 t2 t3) = const_NB t1 \\<union> const_NB t2 \\<union> const_NB t3\"\n\n(* subsubsection {* Definition 3.3.2 *} *)\n\nprimrec size_NB :: \"nbterm \\<Rightarrow> nat\" where\n  \"size_NB NBTrue = 1\" |\n  \"size_NB NBFalse = 1\" |\n  \"size_NB NBZero = 1\" |\n  \"size_NB (NBSucc t) = size_NB t + 1\" |\n  \"size_NB (NBPred t) = size_NB t + 1\" |\n  \"size_NB (NBIs_zero t) = size_NB t + 1\" |\n  \"size_NB (NBIf t1 t2 t3) = size_NB t1 + size_NB t2 + size_NB t3 + 1\"\n\nprimrec depth_NB :: \"nbterm \\<Rightarrow> nat\" where\n  \"depth_NB NBTrue = 1\" |\n  \"depth_NB NBFalse = 1\" |\n  \"depth_NB NBZero = 1\" |\n  \"depth_NB (NBSucc t) = depth_NB t + 1\" |\n  \"depth_NB (NBPred t) = depth_NB t + 1\" |\n  \"depth_NB (NBIs_zero t) = depth_NB t + 1\" |\n  \"depth_NB (NBIf t1 t2 t3) = max (depth_NB t1) (max (depth_NB t2) (depth_NB t3)) + 1\"\n\n(* subsubsection {* Lemma 3.3.3 *} *)\n\nlemma card_union_leq_sum_card: \"card (A \\<union> B) \\<le> card A + card B\"\n  by (cases \"finite A \\<and> finite B\") (simp only: card_Un_Int, auto)\n\nlemma \"card (const_NB t) \\<le> size_NB t\"\nproof (induction t)\n  case (NBIf t1 t2 t3)\n  show ?case\n  proof -\n    let ?t1 = \"const_NB t1\"\n    let ?t2 = \"const_NB t2\"\n    let ?t3 = \"const_NB t3\"\n    have \"card (?t1 \\<union> ?t2 \\<union> ?t3) \\<le> card ?t1 + card ?t2 + card ?t3\"\n      by (smt card_union_leq_sum_card add_le_imp_le_right le_antisym le_trans nat_le_linear)\n    also have \"\\<dots> \\<le> size_NB t1 + size_NB t2 + size_NB t3\"\n      using NBIf.IH by simp\n    finally show ?thesis by simp\n  qed\nqed (simp_all add: le_SucI)\n\n(* subsubsection {* Theorem 3.3.4 *} *)\n\nlemmas induct_depth = measure_induct_rule[of depth_NB]\nlemmas induct_size = measure_induct_rule[of size_NB]\nlemmas structural_induction = nbterm.induct\n\n(*>*)\ntext \\<open>\nValues now consist either of Booleans or numeric values, for which a separate inductive\ndefinition is given. Here is the definition as found in the book:\n\\begin{align*}\n  v ::= & \\\\\n    & \\text{true} && \\text{true value} \\\\\n    & \\text{false} && \\text{false value} \\\\\n    & \\text{nv} && \\text{numeric value} \\\\\n  nv ::= & \\\\\n    & \\text{0} && \\text{zero value} \\\\\n    & \\text{succ nv} && \\text{successor value}\n\\end{align*}\n\nOur inductive definition is very similar, but contains explicit assumptions on the nature of\n\\texttt{nv}. The book uses naming conventions which define letters such as \\texttt{t} as\nalways representing terms, letters such as \\texttt{v} as always representing values and variants of\n\\texttt{nv} as always representing numeric values. In our formalization, such implicit assumption is\npossible for \\texttt{t} because Isabelle/HOL infers that @{term nberm} is the only type that could\nbe place at this position. Since values and numeric values do not have a proper type but\ncharacterize a subset of terms, we must add assumptions to declare the nature of these variables:\n\\<close>\n\ninductive is_numeric_value_NB :: \"nbterm \\<Rightarrow> bool\" where\n  \"is_numeric_value_NB NBZero\" |\n  \"is_numeric_value_NB nv \\<Longrightarrow> is_numeric_value_NB (NBSucc nv)\"\n\ninductive is_value_NB :: \"nbterm \\<Rightarrow> bool\" where\n  \"is_value_NB NBTrue\" |\n  \"is_value_NB NBFalse\" |\n  \"is_numeric_value_NB nv \\<Longrightarrow> is_value_NB nv\"\n\ntext {*\nThe single-step evaluation relation is a superset of the one defined for Booleans:\n*}\n\ninductive eval1_NB :: \"nbterm \\<Rightarrow> nbterm \\<Rightarrow> bool\" where\n  \\<comment> \\<open>Rules relating to the evaluation of Booleans\\<close>\n  eval1_NBIf_NBTrue:\n    \"eval1_NB (NBIf NBTrue t2 t3) t2\" |\n  eval1_NBIf_NBFalse:\n    \"eval1_NB (NBIf NBFalse t2 t3) t3\" |\n  eval1_NBIf:\n    \"eval1_NB t1 t1' \\<Longrightarrow> eval1_NB (NBIf t1 t2 t3) (NBIf t1' t2 t3)\" |\n\n  \\<comment> \\<open>Rules relating to the evaluation of natural numbers\\<close>\n  eval1_NBSucc:\n    \"eval1_NB t t' \\<Longrightarrow> eval1_NB (NBSucc t) (NBSucc t')\" |\n  eval1_NBPred_NBZero:\n    \"eval1_NB (NBPred NBZero) NBZero\" |\n  eval1_NBPred_NBSucc:\n    \"is_numeric_value_NB nv \\<Longrightarrow> eval1_NB (NBPred (NBSucc nv)) nv\" |\n  eval1_NBPred:\n    \"eval1_NB t t' \\<Longrightarrow> eval1_NB (NBPred t) (NBPred t')\" |\n\n  \\<comment> \\<open>Rules relating to the evaluation of the test for equality with zero\\<close>\n  eval1_NBIs_zero_NBZero:\n    \"eval1_NB (NBIs_zero NBZero) NBTrue\" |\n  eval1_NBIs_zero_NBSucc:\n    \"is_numeric_value_NB nv \\<Longrightarrow> eval1_NB (NBIs_zero (NBSucc nv)) NBFalse\" |\n  eval1_NBIs_zero:\n    \"eval1_NB t t' \\<Longrightarrow> eval1_NB (NBIs_zero t) (NBIs_zero t')\"\n\ntext {*\nThe multi-step evaluation relation and the definition of normal form are perfectly analogous to\nthese for Booleans:\n\\newpage\n*}\n\ninductive eval_NB :: \"nbterm \\<Rightarrow> nbterm \\<Rightarrow> bool\" where\n  eval_NB_base:\n    \"eval_NB t t\" |\n  eval_NB_step:\n    \"eval1_NB t t' \\<Longrightarrow> eval_NB t' t'' \\<Longrightarrow> eval_NB t t''\"\n\ndefinition is_normal_form_NB :: \"nbterm \\<Rightarrow> bool\" where\n  \"is_normal_form_NB t \\<longleftrightarrow> (\\<forall>t'. \\<not> eval1_NB t t')\"\n\ntext {*\nThe reason is that all the actual work is performed by the single-step evaluation relation.\n\nIn the book, the section covering this fully fledged arithmetic expression language is mainly an\nexplanation of the constructions not present in the Boolean expression language and does not\ncontains any proper theorems. Nevertheless, we revisit the properties introduced for the language of\nBooleans and either prove that they are still theorems or disprove them.\n*}\n\n(*<*)\n(* Usefull lemmas *)\n\nlemma eval1_NB_impl_eval_NB:\n  \"eval1_NB t t' \\<Longrightarrow> eval_NB t t'\"\nby (simp add: eval_NB.intros)\n\nlemma eval_NB_transitive:\n  \"eval_NB t t' \\<Longrightarrow> eval_NB t' t'' \\<Longrightarrow> eval_NB t t''\"\nby (induction t t' rule: eval_NB.induct) (auto intro: eval_NB.intros)\n\nlemma not_eval_once_numeric_value:\n  \"is_numeric_value_NB nv \\<Longrightarrow> eval1_NB nv t \\<Longrightarrow> P\"\nby (induction nv arbitrary: t rule: is_numeric_value_NB.induct)\n  (auto elim: eval1_NB.cases)\n\n(* subsubsection {* Theorem 3.5.4 for Arithmetic Expressions *} *)\n(*>*)\n\ntext {*\nThe determinacy of the single-step evaluation still holds:\n*}\n\ntheorem eval1_NB_determinacy:\n  \"eval1_NB t t' \\<Longrightarrow> eval1_NB t t'' \\<Longrightarrow> t' = t''\"\nproof (induction t t' arbitrary: t'' rule: eval1_NB.induct)\n  case (eval1_NBIf t1 t1' t2 t3)\n  from eval1_NBIf.prems eval1_NBIf.hyps show ?case\n    by (auto intro: eval1_NB.cases dest: eval1_NBIf.IH)\nnext\n  case (eval1_NBSucc t1 t2)\n  from eval1_NBSucc.prems eval1_NBSucc.IH show ?case\n    by (auto elim: eval1_NB.cases)\nnext\n  case (eval1_NBPred_NBSucc nv1)\n  from eval1_NBPred_NBSucc.prems eval1_NBPred_NBSucc.hyps show ?case\n    by (cases rule: eval1_NB.cases)\n      (auto\n        intro: is_numeric_value_NB.intros\n        elim: not_eval_once_numeric_value[rotated])\nnext\n  case (eval1_NBPred t1 t2)\n  from eval1_NBPred.hyps eval1_NBPred.prems show ?case\n    by (auto\n      intro: eval1_NBPred.IH is_numeric_value_NB.intros\n      elim: eval1_NB.cases\n      dest: not_eval_once_numeric_value)\nnext\n  case (eval1_NBIs_zero_NBSucc nv)\n  thus ?case by (auto\n    intro: eval1_NB.cases not_eval_once_numeric_value is_numeric_value_NB.intros)\nnext\n  case (eval1_NBIs_zero t1 t2)\n  from eval1_NBIs_zero.prems eval1_NBIs_zero.hyps show ?case\n    by (cases rule: eval1_NB.cases) (auto\n      elim: eval1_NB.cases\n      intro: eval1_NBIs_zero.IH is_numeric_value_NB.intros\n      elim: not_eval_once_numeric_value[rotated])\nqed (auto elim: eval1_NB.cases)\n\n(* subsubsection {* Theorem 3.5.7 for Arithmetic Expressions *} *)\n\ntext {*\nEvery value is in normal form:\n*}\n\ntheorem value_imp_normal_form_NB:\n  \"is_value_NB t \\<Longrightarrow> is_normal_form_NB t\"\nby (auto\n  intro: not_eval_once_numeric_value\n  elim: eval1_NB.cases is_value_NB.cases\n  simp: is_normal_form_NB_def)\n\n(* subsubsection {* Theorem 3.5.8 does not hold for Arithmetic Expressions *} *)\n\ntext {*\nBut, unlike for Boolean expressions, some terms that are in normal form are not values. An example\nof such term is @{term \"NBSucc NBTrue\"}.\n*}\n\ntheorem not_normal_form_imp_value_NB:\n  \"\\<exists>t. is_normal_form_NB t \\<and> \\<not> is_value_NB t\" (is \"\\<exists>t. ?P t\")\nproof\n  have a: \"is_normal_form_NB (NBSucc NBTrue)\"\n    by (auto elim: eval1_NB.cases simp: is_normal_form_NB_def)\n  have b: \"\\<not> is_value_NB (NBSucc NBTrue)\"\n    by (auto elim: is_numeric_value_NB.cases simp: is_value_NB.simps)\n  from a b show \"?P (NBSucc NBTrue)\" by simp\nqed\n\n(* subsubsection {* Corollary 3.5.11 for Arithmetic Expressions *} *)\n\ntext {*\nThe uniqueness of normal form still holds:\n*}\n\ncorollary uniqueness_of_normal_form_NB:\n  \"eval_NB t u \\<Longrightarrow> eval_NB t u' \\<Longrightarrow> is_normal_form_NB u \\<Longrightarrow> is_normal_form_NB u' \\<Longrightarrow> u = u'\"\nproof (induction t u arbitrary: u' rule: eval_NB.induct)\n  case (eval_NB_base t)\n  thus ?case by (auto elim: eval_NB.cases simp: is_normal_form_NB_def)\nnext\n  case (eval_NB_step t1 t2 t3)\n  thus ?case by (metis eval_NB.cases is_normal_form_NB_def eval1_NB_determinacy)\nqed\n\n(* subsubsection {* Theorem 3.5.12 for Arithmetic Expressions *} *)\n\ntext {*\nSo does the termination of the evaluation function:\n*}\n(*<*)\n\nlemma eval_once_size_NB:\n  \"eval1_NB t t' \\<Longrightarrow> size_NB t > size_NB t'\"\nby (induction t t' rule: eval1_NB.induct) auto\n\n(*>*)\ntheorem eval_NB_always_terminate:\n  \"\\<exists>t'. eval_NB t t' \\<and> is_normal_form_NB t'\"\nproof (induction rule: measure_induct_rule[of size_NB])\n  case (less t)\n  show ?case\n    apply (cases \"is_normal_form_NB t\")\n    apply (auto intro: eval_NB_base)\n    using eval_NB_step eval_once_size_NB is_normal_form_NB_def less.IH\n    by blast\nqed\n\n(*<*)\nend\n(*>*)\n", "meta": {"author": "mdesharnais", "repo": "log792-type-systems-formalization", "sha": "6b82d50845ee2603da295dfa972f45a258602a1c", "save_path": "github-repos/isabelle/mdesharnais-log792-type-systems-formalization", "path": "github-repos/isabelle/mdesharnais-log792-type-systems-formalization/log792-type-systems-formalization-6b82d50845ee2603da295dfa972f45a258602a1c/Untyped_Arithmetic_Expressions.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8479677468516188, "lm_q2_score": 0.8438951045175643, "lm_q1q2_score": 0.7155958303568704}}
{"text": "(*  Title:      HOL/Cardinals/Fun_More.thy\n    Author:     Andrei Popescu, TU Muenchen\n    Copyright   2012\n\nMore on injections, bijections and inverses.\n*)\n\nsection \\<open>More on Injections, Bijections and Inverses\\<close>\n\ntheory Fun_More\n  imports Main\nbegin\n\nsubsection \\<open>Purely functional properties\\<close>\n\n(* unused *)\n(*1*)lemma bij_betw_diff_singl:\n  assumes BIJ: \"bij_betw f A A'\" and IN: \"a \\<in> A\"\n  shows \"bij_betw f (A - {a}) (A' - {f a})\"\nproof-\n  let ?B = \"A - {a}\"   let ?B' = \"A' - {f a}\"\n  have \"f a \\<in> A'\" using IN BIJ unfolding bij_betw_def by blast\n  hence \"a \\<notin> ?B \\<and> f a \\<notin> ?B' \\<and> A = ?B \\<union> {a} \\<and> A' = ?B' \\<union> {f a}\"\n    using IN by blast\n  thus ?thesis using notIn_Un_bij_betw3[of a ?B f ?B'] BIJ by simp\nqed\n\n\nsubsection \\<open>Properties involving finite and infinite sets\\<close>\n\n(* unused *)\n(*1*)lemma bij_betw_inv_into_RIGHT:\n  assumes BIJ: \"bij_betw f A A'\" and SUB: \"B' \\<le> A'\"\n  shows \"f `((inv_into A f)`B') = B'\"\n  by (metis BIJ SUB bij_betw_imp_surj_on image_inv_into_cancel)\n\n\n(* unused *)\n(*1*)lemma bij_betw_inv_into_RIGHT_LEFT:\n  assumes BIJ: \"bij_betw f A A'\" and SUB: \"B' \\<le> A'\" and\n    IM: \"(inv_into A f) ` B' = B\"\n  shows \"f ` B = B'\"\n  by (metis BIJ IM SUB bij_betw_inv_into_RIGHT)\n\n(* unused *)\n(*2*)lemma bij_betw_inv_into_twice:\n  assumes \"bij_betw f A A'\"\n  shows \"\\<forall>a \\<in> A. inv_into A' (inv_into A f) a = f a\"\n  by (simp add: assms inv_into_inv_into_eq)\n\n\nsubsection \\<open>Properties involving Hilbert choice\\<close>\n\n(*1*)lemma bij_betw_inv_into_LEFT:\n  assumes BIJ: \"bij_betw f A A'\" and SUB: \"B \\<le> A\"\n  shows \"(inv_into A f)`(f ` B) = B\"\n  using assms unfolding bij_betw_def using inv_into_image_cancel by force\n\n(*1*)lemma bij_betw_inv_into_LEFT_RIGHT:\n  assumes BIJ: \"bij_betw f A A'\" and SUB: \"B \\<le> A\" and\n    IM: \"f ` B = B'\"\n  shows \"(inv_into A f) ` B' = B\"\n  using assms bij_betw_inv_into_LEFT[of f A A' B] by fast\n\n\nsubsection \\<open>Other facts\\<close>\n\n(*3*)lemma atLeastLessThan_injective:\n  assumes \"{0 ..< m::nat} = {0 ..< n}\"\n  shows \"m = n\"\n  using assms atLeast0LessThan by force\n\n(*2*)lemma atLeastLessThan_injective2:\n  \"bij_betw f {0 ..< m::nat} {0 ..< n} \\<Longrightarrow> m = n\"\n  using bij_betw_same_card by fastforce\n\n(*2*)lemma atLeastLessThan_less_eq:\n  \"({0..<m} \\<le> {0..<n}) = ((m::nat) \\<le> n)\"\n  by auto\n\n(*2*)lemma atLeastLessThan_less_eq2:\n  assumes \"inj_on f {0..<(m::nat)}\" \"f ` {0..<m} \\<le> {0..<n}\"\n  shows \"m \\<le> n\"\n  by (metis assms card_inj_on_le card_lessThan finite_lessThan lessThan_atLeast0)\n\n(* unused *)\n(*3*)lemma atLeastLessThan_less:\n  \"({0..<m} < {0..<n}) = ((m::nat) < n)\"\n  by 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/Cardinals/Fun_More.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9111797148356995, "lm_q2_score": 0.785308580887758, "lm_q1q2_score": 0.7155572487913352}}
{"text": "(*  Title:      SetIntervalStep.thy\n    Date:       Oct 2006\n    Author:     David Trachtenherz\n*)\n\nheader {* Stepping through sets of natural numbers *}\n\ntheory SetIntervalStep\nimports SetIntervalCut\nbegin\n\nsubsection {* Function @{text inext} and @{text iprev} for stepping through natural sets *}\n\ndefinition\n  inext :: \"nat \\<Rightarrow> nat set \\<Rightarrow> nat\"\nwhere\n  \"inext n I \\<equiv> (\n    if (n \\<in> I \\<and> (I \\<down>> n \\<noteq> {}))\n    then iMin (I \\<down>> n)\n    else n)\"\n\ndefinition\n  iprev :: \"nat \\<Rightarrow> nat set \\<Rightarrow> nat\"\nwhere\n  \"iprev n I \\<equiv> (\n    if (n \\<in> I \\<and> (I \\<down>< n \\<noteq> {}))\n    then Max (I \\<down>< n)\n    else n)\"\n\ntext {* @{text inext} and @{text iprev} can be viewed as generalisations of @{text Suc} and @{text prev} *}\n\nlemma inext_UNIV: \"inext n UNIV = Suc n\"\napply (simp add: inext_def cut_greater_def, safe)\napply (rule iMin_equality)\napply fastforce+\ndone\nlemma iprev_UNIV: \"iprev n UNIV = n - Suc 0\"\napply (simp add: iprev_def cut_less_def, safe)\napply (rule Max_equality)\napply fastforce+\ndone\n\nlemma inext_empty: \"inext n {} = n\"\nunfolding inext_def by simp\nlemma iprev_empty: \"iprev n {} = n\"\nunfolding iprev_def by simp\n\nthm \n  finite_nat_iff_bounded_le\n  finite_nat_iff_bounded_le2\n\nlemma not_in_inext_fix: \"n \\<notin> I \\<Longrightarrow> inext n I = n\"\nunfolding inext_def by simp\nlemma not_in_iprev_fix: \"n \\<notin> I \\<Longrightarrow> iprev n I = n\"\nunfolding iprev_def by simp\n\n\nlemma inext_all_le_fix: \"\\<forall>x\\<in>I. x \\<le> n \\<Longrightarrow> inext n I = n\"\nunfolding inext_def by force\nlemma iprev_all_ge_fix: \"\\<forall>x\\<in>I. n \\<le> x \\<Longrightarrow> iprev n I = n\"\nunfolding iprev_def by force\n\nlemma inext_Max: \"finite I \\<Longrightarrow> inext (Max I) I = Max I\"\nunfolding inext_def cut_greater_def by (fastforce dest: Max_ge)\nlemma iprev_iMin: \"iprev (iMin I) I = iMin I\"\nunfolding iprev_def cut_less_def by fastforce\n\nlemma inext_ge_Max: \"\\<lbrakk> finite I; Max I \\<le> n \\<rbrakk> \\<Longrightarrow> inext n I = n\"\nunfolding inext_def cut_greater_def by (fastforce dest: Max_ge)\nthm iprev_iMin\n\n\nlemma inext_singleton: \"inext n {a} = n\"\nunfolding inext_def by fastforce\n\nlemma iprev_singleton: \"iprev n {a} = n\"\nunfolding iprev_def by fastforce\n\nlemma inext_closed: \"n \\<in> I \\<Longrightarrow> inext n I \\<in> I\"\napply (clarsimp simp: inext_def)\nthm subsetD[of \"I \\<down>> n\" I]\napply (rule subsetD[OF cut_greater_subset])\napply (rule iMinI_ex2, assumption)\ndone\n\nlemma iprev_closed: \"n \\<in> I \\<Longrightarrow> iprev n I \\<in> I\"\napply (clarsimp simp: iprev_def)\nthm subsetD[of \"I \\<down>< n\" I]\napply (rule subsetD[of \"I \\<down>< n\"], fastforce)\nthm Max_in[OF nat_cut_less_finite]\nby (rule Max_in[OF nat_cut_less_finite])\n\n\n\n\nthm inext_closed\nlemma inext_in_imp_in: \"inext n I \\<in> I \\<Longrightarrow> n \\<in> I\"\nby (case_tac \"n \\<in> I\", simp_all add: not_in_inext_fix)\n\nlemma inext_in_iff: \"(inext n I \\<in> I) = (n \\<in> I)\"\napply (rule iffI)\napply (rule inext_in_imp_in, assumption)\napply (rule inext_closed, assumption)\ndone\n\nlemma subset_inext_closed: \"\\<lbrakk> n \\<in> B; A \\<subseteq> B \\<rbrakk> \\<Longrightarrow> inext n A \\<in> B\"\napply (case_tac \"n \\<in> A\")\n apply (fastforce simp: inext_closed)\napply (simp add: not_in_inext_fix)\ndone\nlemma subset_inext_in_imp_in: \"\\<lbrakk> inext n A \\<in> B; A \\<subseteq> B \\<rbrakk> \\<Longrightarrow> n \\<in> B\"\napply (case_tac \"n \\<in> A\")\n apply fastforce\napply (simp add: not_in_inext_fix)\ndone\nlemma subset_inext_in_iff: \"A \\<subseteq> B \\<Longrightarrow> (inext n A \\<in> B) = (n \\<in> B)\"\napply (rule iffI)\napply (rule subset_inext_in_imp_in, assumption+)\napply (rule subset_inext_closed, assumption+)\ndone\n\n\n\nthm iprev_closed\nlemma iprev_in_imp_in: \"iprev n I \\<in> I \\<Longrightarrow> n \\<in> I\"\napply (case_tac \"n \\<in> I\")\napply (simp_all add: not_in_iprev_fix)\ndone\nlemma iprev_in_iff: \"(iprev n I \\<in> I) = (n \\<in> I)\"\napply (rule iffI)\napply (rule iprev_in_imp_in, assumption)\napply (rule iprev_closed, assumption)\ndone\n\nlemma subset_iprev_closed: \"\\<lbrakk> n \\<in> B; A \\<subseteq> B \\<rbrakk> \\<Longrightarrow> iprev n A \\<in> B\"\napply (case_tac \"n \\<in> A\")\n apply (fastforce simp: iprev_closed)\napply (simp add: not_in_iprev_fix)\ndone\nlemma subset_iprev_in_imp_in: \"\\<lbrakk> iprev n A \\<in> B; A \\<subseteq> B \\<rbrakk> \\<Longrightarrow> n \\<in> B\"\napply (case_tac \"n \\<in> A\")\n apply fastforce\napply (simp add: not_in_iprev_fix)\ndone\nlemma subset_iprev_in_iff: \"A \\<subseteq> B \\<Longrightarrow> (iprev n A \\<in> B) = (n \\<in> B)\"\napply (rule iffI)\napply (rule subset_iprev_in_imp_in, assumption+)\napply (rule subset_iprev_closed, assumption+)\ndone\n\n\n\nlemma inext_mono: \"n \\<le> inext n I\"\nby (simp add: inext_def i_cut_defs iMin_ge_iff)\ncorollary inext_neq_imp_less: \"n \\<noteq> inext n I \\<Longrightarrow> n < inext n I\"\nby (insert inext_mono[of n I], simp)\n\nlemma inext_mono2: \"\\<lbrakk> n \\<in> I; \\<exists>x\\<in>I. n < x \\<rbrakk> \\<Longrightarrow> n < inext n I\"\nby (fastforce simp add: inext_def i_cut_defs iMin_gr_iff)\n\nlemma inext_mono2_infin: \"\\<lbrakk> n \\<in> I; infinite I \\<rbrakk> \\<Longrightarrow> n < inext n I\"\napply (simp add: inext_def i_cut_defs iMin_gr_iff)\napply (fastforce simp: infinite_nat_iff_unbounded)\ndone\n\nlemma inext_mono2_fin: \"\\<lbrakk> n \\<in> I; finite I; n \\<noteq> Max I \\<rbrakk> \\<Longrightarrow> n < inext n I\"\napply (simp add: inext_def i_cut_defs iMin_gr_iff)\napply (blast intro: Max_ge Max_in)\ndone\n\nthm inext_mono2\nlemma inext_mono2_infin_fin: \"\n  \\<lbrakk> n \\<in> I; n \\<noteq> Max I \\<or> infinite I \\<rbrakk> \\<Longrightarrow> n < inext n I\"\nby (blast intro: inext_mono2_infin inext_mono2_fin)\n\nthm Nat.zero_less_Suc\nlemma inext_neq_iMin: \"\\<exists>x\\<in>I. n < x \\<Longrightarrow> inext n I \\<noteq> iMin I\"\napply (case_tac \"n \\<in> I\")\n prefer 2\n apply (simp add: not_in_inext_fix)\n apply (blast dest: iMinI)\napply (rule not_sym, rule less_imp_neq)\nthm le_less_trans[OF iMin_le[of n], OF _ inext_mono2]\nby (rule le_less_trans[OF iMin_le[of n], OF _ inext_mono2])\n\nlemma inext_neq_iMin_infin: \"infinite I \\<Longrightarrow> inext n I \\<noteq> iMin I\"\napply (rule inext_neq_iMin)\nthm infinite_nat_iff_unbounded[THEN iffD1]\napply (blast dest: infinite_nat_iff_unbounded[THEN iffD1])\ndone\n\nthm Max_le_Min_imp_singleton\nlemma Max_le_iMin_imp_singleton: \"\\<lbrakk> finite I; I \\<noteq> {}; Max I \\<le> iMin I \\<rbrakk> \\<Longrightarrow> I = {iMin I}\"\nby (simp add: iMin_Min_conv Max_le_Min_imp_singleton)\n\nlemma inext_neq_iMin_not_singleton: \"\n  \\<lbrakk> I \\<noteq> {}; \\<not>(\\<exists>a. I = {a}) \\<rbrakk> \\<Longrightarrow> inext n I \\<noteq> iMin I\"\napply (case_tac \"finite I\")\n prefer 2\n apply (simp add: inext_neq_iMin_infin)\napply (case_tac \"n \\<in> I\")\n prefer 2\n apply (simp add: not_in_inext_fix)\n apply (blast intro: iMinI_ex2)\nby (metis Max_le_iMin_imp_singleton iMin_le_Max inext_Max inext_mono2_infin_fin not_less_iMin)\ncorollary inext_neq_iMin_not_card_1: \"\n  \\<lbrakk> I \\<noteq> {}; card I \\<noteq> Suc 0 \\<rbrakk> \\<Longrightarrow> inext n I \\<noteq> iMin I\"\nby (simp add: inext_neq_iMin_not_singleton card_1_singleton_conv)\n\nlemma inext_neq_imp_Max: \"n \\<noteq> inext n I \\<Longrightarrow> n < Max I \\<or> infinite I\"\nby (rule ccontr, clarsimp simp: inext_ge_Max)\n\nlemma inext_less_conv: \"(n \\<in> I \\<and> (n < Max I \\<or> infinite I)) = (n < inext n I)\"\napply (rule iffI)\n apply (blast intro: inext_mono2_infin_fin)\napply (rule conjI)\n apply (rule ccontr)\n apply (simp add: not_in_inext_fix)\napply (blast dest: inext_neq_imp_Max less_imp_neq)\ndone\n\n\n\n\nlemma inext_min_step: \"\\<lbrakk> n < k; k < inext n I \\<rbrakk> \\<Longrightarrow> k \\<notin> I\"\napply (case_tac \"n \\<in> I\")\n prefer 2 \n apply (simp add: inext_def)\nthm contrapos_pn[of \"k < inext n I\" \"k \\<in> I\"]\napply (rule contrapos_pn[of \"k < inext n I\" \"k \\<in> I\"], simp)\napply (simp add: inext_def i_cut_defs)\napply (case_tac \"\\<exists>x. x \\<in> I \\<and> n < x\")\n apply simp\n thm not_less_iMin\n thm not_less_iMin[of k \"{x \\<in> I. n < x}\"]\n apply (blast dest: not_less_iMin)\napply blast\ndone\ncorollary inext_min_step2: \"\\<not>(\\<exists>k\\<in>I. n < k \\<and> k < inext n I)\"\nby (clarsimp simp add: inext_min_step)\n\nlemma min_step_inext[rule_format]: \"\n  \\<lbrakk> x < y; x \\<in> I; y \\<in> I; \\<And>k. \\<lbrakk> x < k; k < y \\<rbrakk> \\<Longrightarrow> k \\<notin> I \\<rbrakk> \\<Longrightarrow> \n  inext x I = y\"\napply (rule ccontr)\nthm nat_neq_iff\napply (simp add: nat_neq_iff, safe)\nthm inext_closed[of x I]\nthm inext_mono2[of x I]\napply (blast dest: inext_closed inext_mono2)\nthm inext_min_step[of x y I]\napply (simp add: inext_min_step)\ndone\n\ncorollary min_step_inext2[rule_format]: \"\n  \\<lbrakk> x < y; x \\<in> I; y \\<in> I; \\<not>(\\<exists>k \\<in> I. x < k \\<and> k < y) \\<rbrakk> \\<Longrightarrow> \n  inext x I = y\"\nby (blast intro: min_step_inext)\nlemma between_empty_imp_inext_eq: \"\n  \\<lbrakk> n \\<in> A; n < inext n A; n \\<in> B; inext n A \\<in> B; B \\<down>> n \\<down>< (inext n A) = {} \\<rbrakk> \\<Longrightarrow> \n  inext n B = inext n A\"\nby (blast intro: min_step_inext2)\n\n\n\n\nlemma inext_le_mono: \"\\<lbrakk> a \\<le> b; a \\<in> I; b \\<in> I \\<rbrakk> \\<Longrightarrow> inext a I \\<le> inext b I\"\napply (drule order_le_less[THEN iffD1], erule disjE)\n prefer 2 \n apply simp\napply (rule order_trans[of _ b])\n apply (rule ccontr, simp add: linorder_not_le)\n thm inext_min_step\n apply (blast dest: inext_min_step) \nby (rule inext_mono)\n\nthm inext_mono2\nlemma inext_less_mono: \"\n  \\<lbrakk> a < b; a \\<in> I; b \\<in> I; \\<exists>x\\<in>I. b < x \\<rbrakk> \\<Longrightarrow> inext a I < inext b I\"\napply (rule le_less_trans[of _ b])\n apply (rule ccontr, simp add: linorder_not_le)\n thm inext_min_step\n apply (blast dest: inext_min_step) \nby (rule inext_mono2)\n\nthm inext_mono2_fin\nlemma inext_less_mono_fin: \"\n  \\<lbrakk> a < b; a \\<in> I; b \\<in> I; finite I; b \\<noteq> Max I \\<rbrakk> \\<Longrightarrow> inext a I < inext b I\"\nthm inext_less_mono Max_in\nby (blast intro: inext_less_mono Max_in)\n\nthm inext_mono2_infin\nlemma inext_less_mono_infin: \"\n  \\<lbrakk> a < b; a \\<in> I; b \\<in> I; infinite I \\<rbrakk> \\<Longrightarrow> inext a I < inext b I\"\napply (rule inext_less_mono, assumption+)\napply (blast dest: infinite_imp_asc_chain)\ndone\nthm inext_mono2_infin_fin\nlemma inext_less_mono_infin_fin: \"\n  \\<lbrakk> a < b; a \\<in> I; b \\<in> I; b \\<noteq> Max I \\<or> infinite I \\<rbrakk> \\<Longrightarrow> inext a I < inext b I\"\nby (blast intro: inext_less_mono_infin inext_less_mono_fin)\n\n\nlemma inext_le_mono_rev: \"\n  \\<lbrakk> inext a I \\<le> inext b I; a \\<in> I; b \\<in> I; \\<exists>x\\<in>I. inext a I < x \\<rbrakk> \\<Longrightarrow> a \\<le> b\"\napply (rule ccontr, simp add: linorder_not_le)\nthm inext_less_mono\napply (frule inext_less_mono, assumption+)\n apply (blast intro: le_less_trans inext_mono)\napply simp\ndone\nlemma inext_le_mono_fin_rev: \"\n  \\<lbrakk> inext a I \\<le> inext b I; a \\<in> I; b \\<in> I; finite I; inext a I \\<noteq> Max I\\<rbrakk> \\<Longrightarrow> a \\<le> b\"\nby (metis inext_in_iff inext_le_mono_rev inext_mono2_infin_fin)\nlemma inext_le_mono_infin_rev: \"\n  \\<lbrakk> inext a I \\<le> inext b I; a \\<in> I; b \\<in> I; infinite I \\<rbrakk> \\<Longrightarrow> a \\<le> b\"\nby (metis inext_in_iff inext_le_mono_rev inext_mono2_infin_fin)\nlemma inext_le_mono_infin_fin_rev: \"\n  \\<lbrakk> inext a I \\<le> inext b I; a \\<in> I; b \\<in> I; inext a I \\<noteq> Max I \\<or> infinite I \\<rbrakk> \\<Longrightarrow> a \\<le> b\"\nby (blast intro: inext_le_mono_infin_rev inext_le_mono_fin_rev)\n\n\nlemma inext_less_mono_rev: \"\n  \\<lbrakk> inext a I < inext b I; a \\<in> I; b \\<in> I \\<rbrakk> \\<Longrightarrow> a < b\"\nby (metis inext_le_mono not_le)\n\nlemma less_imp_inext_le: \"\\<lbrakk> a < b; a \\<in> I; b \\<in> I \\<rbrakk> \\<Longrightarrow> inext a I \\<le> b\"\nby (metis inext_min_step not_le)\n\nlemma iprev_mono: \"iprev n I \\<le> n\"\nunfolding iprev_def i_cut_defs by simp\ncorollary iprev_neq_imp_greater: \"n \\<noteq> iprev n I \\<Longrightarrow> iprev n I < n\"\nby (insert iprev_mono[of n I], simp)\n\n\nlemma iprev_mono2: \"\\<lbrakk> n \\<in> I; \\<exists>x\\<in>I. x < n\\<rbrakk> \\<Longrightarrow> iprev n I < n\"\napply (unfold iprev_def i_cut_defs, clarsimp)\nthm finite_nat_iff_bounded\napply (blast intro: finite_nat_iff_bounded)+\ndone\n\nthm inext_mono2_fin\nlemma iprev_mono2_if_neq_iMin: \"\\<lbrakk> n \\<in> I; iMin I \\<noteq> n\\<rbrakk> \\<Longrightarrow> iprev n I < n\"\nthm iMinI\nthm iprev_mono2\nby (blast intro: iMinI iprev_mono2)\n\n\n\nthm inext_neq_iMin\nlemma iprev_neq_Max: \"\\<lbrakk> finite I; \\<exists>x\\<in>I. x < n \\<rbrakk>  \\<Longrightarrow> iprev n I \\<noteq> Max I\"\napply (case_tac \"n \\<in> I\")\n prefer 2\n apply (simp add: not_in_iprev_fix)\n apply (blast dest: Max_in)\napply (rule less_imp_neq)\nthm less_le_trans[OF iprev_mono2 Max_ge]\nby (rule less_le_trans[OF iprev_mono2 Max_ge])\n\nthm inext_neq_iMin_not_singleton\nlemma iprev_neq_Max_not_singleton: \"\n  \\<lbrakk> finite I; I \\<noteq> {}; \\<not>(\\<exists>a. I = {a}) \\<rbrakk> \\<Longrightarrow> iprev n I \\<noteq> Max I\"\napply (case_tac \"n \\<in> I\")\n prefer 2\n thm not_in_iprev_fix\n apply (simp add: not_in_iprev_fix)\n apply (blast intro: Max_in)\napply (case_tac \"n = iMin I\")\n apply (metis Max_le_Min_conv_singleton iMin_Min_conv iMin_le_Max iprev_iMin)\napply (metis iprev_mono2_if_neq_iMin not_greater_Max)\ndone\ncorollary iprev_neq_Max_not_card_1: \"\n  \\<lbrakk> finite I; I \\<noteq> {}; card I \\<noteq> Suc 0 \\<rbrakk> \\<Longrightarrow> iprev n I \\<noteq> Max I\"\napply (rule iprev_neq_Max_not_singleton, assumption+)\napply (simp add: card_1_singleton_conv)\ndone\n\nlemma iprev_neq_imp_iMin: \"iprev n I \\<noteq> n \\<Longrightarrow> iMin I < n\"\nby (rule ccontr, clarsimp simp: iprev_le_iMin)\n\nlemma iprev_greater_conv: \"(n \\<in> I \\<and> iMin I < n) = (iprev n I < n)\"\napply (rule iffI)\n apply (blast intro: iprev_mono2_if_neq_iMin)\napply (rule conjI)\n apply (rule ccontr)\n apply (simp add: not_in_iprev_fix)\napply (blast dest: iprev_neq_imp_iMin less_imp_neq)\ndone\n\n\n\n\nlemma inext_fix_iff: \"(n \\<notin> I \\<or> (finite I \\<and> Max I = n)) = (inext n I = n)\"\napply (case_tac \"n \\<notin> I\", simp add: not_in_inext_fix)\nby (metis inext_Max inext_min_step2 inext_mono2_infin_fin)\nlemma iprev_fix_iff: \"(n \\<notin> I \\<or> iMin I = n) = (iprev n I = n)\"\napply (case_tac \"n \\<notin> I\", simp add: not_in_iprev_fix)\nby (metis iprev_iMin iprev_mono2_if_neq_iMin less_not_refl3)\n\n\nlemma iprev_min_step: \"\\<lbrakk> iprev n I < k; k < n \\<rbrakk> \\<Longrightarrow> k \\<notin> I\"\napply (case_tac \"n \\<in> I\")\n prefer 2 \n apply (simp add: iprev_def)\nthm contrapos_pn[of \"iprev n I < k\" \"k \\<in> I\"]\napply (rule contrapos_pn[of \"iprev n I < k\" \"k \\<in> I\"], simp)\napply (unfold iprev_def i_cut_defs, simp)\napply (split split_if_asm)\nthm Max_ge[of \"{x \\<in> I. x < n}\" k]\napply (cut_tac Max_ge[of \"{x \\<in> I. x < n}\" k])\napply fastforce+\ndone\n\ncorollary iprev_min_step2: \"\\<not>(\\<exists>x\\<in>I. iprev n I < x \\<and> x < n)\"\nby (clarsimp simp add: iprev_min_step)\n\n\nlemma min_step_iprev: \"\n  \\<lbrakk> x < y; x \\<in> I; y \\<in> I; \\<And>k. \\<lbrakk> x < k; k < y \\<rbrakk> \\<Longrightarrow> k \\<notin> I \\<rbrakk> \\<Longrightarrow> \n  iprev y I = x\"\nthm ccontr\napply (rule ccontr)\nthm nat_neq_iff\napply (simp add: nat_neq_iff, elim disjE)\n thm iprev_min_step\n apply (simp add: iprev_min_step)\nthm iprev_closed\nthm iprev_mono2\napply (blast dest: iprev_closed iprev_mono2 iprev_min_step)\ndone\ncorollary min_step_iprev2[rule_format]: \"\n  \\<lbrakk> x < y; x \\<in> I; y \\<in> I; \\<not>(\\<exists>k \\<in> I. x < k \\<and> k < y) \\<rbrakk> \\<Longrightarrow>\n  iprev y I = x\"\nby (blast intro: min_step_iprev)\nlemma between_empty_imp_iprev_eq: \"\n  \\<lbrakk> n \\<in> A; iprev n A < n; n \\<in> B; iprev n A \\<in> B; B \\<down>> (iprev n A) \\<down>< n = {} \\<rbrakk> \\<Longrightarrow> \n  iprev n B = iprev n A\"\nby (blast intro: min_step_iprev2)\n\n\n\nlemma iprev_le_mono: \"\\<lbrakk> a \\<le> b; a \\<in> I; b \\<in> I \\<rbrakk> \\<Longrightarrow> iprev a I \\<le> iprev b I\"\napply (drule order_le_less[THEN iffD1], erule disjE)\n prefer 2 \n apply simp\napply (rule order_trans[OF iprev_mono])\n apply (rule ccontr, simp add: linorder_not_le)\nthm iprev_min_step\nby (blast dest: iprev_min_step)\nlemma iprev_less_mono: \"\n  \\<lbrakk> a < b; a \\<in> I; b \\<in> I; \\<exists>x\\<in>I. x < a \\<rbrakk> \\<Longrightarrow> iprev a I < iprev b I\"\napply (rule less_le_trans[of _ a])\n apply (blast intro: iprev_mono2)\napply (rule ccontr, simp add: linorder_not_le)\nthm iprev_min_step\nby (blast dest: iprev_min_step) \n\nlemma iprev_less_mono_if_neq_iMin: \"\n  \\<lbrakk> a < b; a \\<in> I; b \\<in> I; iMin I \\<noteq> a \\<rbrakk> \\<Longrightarrow> iprev a I < iprev b I\"\nby (metis iprev_in_iff iprev_less_mono iprev_mono2_if_neq_iMin)\n\nthm inext_le_mono_rev\nlemma iprev_le_mono_rev: \"\n  \\<lbrakk> iprev a I \\<le> iprev b I; a \\<in> I; b \\<in> I; iMin I \\<noteq> iprev b I \\<rbrakk> \\<Longrightarrow> a \\<le> b\"\napply (rule ccontr, simp add: linorder_not_le)\nby (metis iprev_fix_iff iprev_less_mono_if_neq_iMin less_le_not_le)\n\nthm inext_less_mono_rev\nlemma iprev_less_mono_rev: \"\n  \\<lbrakk> iprev a I < iprev b I; a \\<in> I; b \\<in> I \\<rbrakk> \\<Longrightarrow> a < b\"\napply (rule ccontr, simp add: linorder_not_less)\nby (metis iprev_le_mono less_le_not_le)\n\n\n\nlemma set_restriction_inext_eq: \"\n  \\<lbrakk> set_restriction interval_fun; n \\<in> interval_fun I; inext n I \\<in> interval_fun I \\<rbrakk> \\<Longrightarrow> \n  inext n (interval_fun I) = inext n I\"\napply (subgoal_tac \"n \\<in> I\")\n prefer 2\n apply (blast intro: set_restriction_in_imp)\napply (case_tac \"inext n I = n\")\n apply simp\n thm inext_fix_iff\n thm inext_fix_iff[THEN iffD1]\n apply (frule inext_fix_iff[THEN iffD2], clarsimp)\n apply (frule set_restriction_finite, assumption)\n apply (subgoal_tac \"Max (interval_fun I) = Max I\")\n  prefer 2\n  apply (blast intro: Max_equality Max_ge set_restriction_in_imp)\n thm inext_fix_iff\n apply (blast intro: inext_fix_iff[THEN iffD1])\nthm inext_mono\nthm le_neq_implies_less[OF inext_mono, OF not_sym]\napply (drule le_neq_implies_less[OF inext_mono, OF not_sym])\napply (rule between_empty_imp_inext_eq, assumption+)\nthm not_ex_in_conv\napply (simp add: not_ex_in_conv[symmetric] i_cut_mem_iff)\nby (metis inext_min_step2 set_restriction_in_imp)\n\nthm set_restriction_inext_eq\nlemma set_restriction_inext_singleton_eq: \"\n  \\<lbrakk> set_restriction interval_fun; n \\<in> interval_fun I; inext n I \\<in> interval_fun I \\<rbrakk> \\<Longrightarrow> \n  {inext n (interval_fun I)} = interval_fun {inext n I}\"\napply (case_tac \"n \\<notin> I\")\n apply (blast dest: set_restriction_not_in_imp)\napply (frule set_restrictionD, erule exE, rename_tac P)\napply (simp add: singleton_iff set_eq_iff)\nby (metis set_restriction_inext_eq)\n\n\n\n\n\nlemma iprev_inext_infin: \"infinite I \\<Longrightarrow> iprev (inext n I) I = n\"\napply (case_tac \"n \\<notin> I\")\n apply (simp add: inext_def iprev_def)\napply simp\nby (metis inext_in_iff inext_min_step2 inext_mono2_infin_fin min_step_iprev2)\n\nlemma iprev_inext_fin: \"\n  \\<lbrakk> finite I; n \\<noteq> Max I \\<rbrakk> \\<Longrightarrow> iprev (inext n I) I = n\"\napply (case_tac \"n \\<notin> I\")\n apply (simp add: inext_def iprev_def)\napply simp\nby (metis inext_in_iff inext_min_step2 inext_mono2_infin_fin min_step_iprev2)\n\nlemma iprev_inext: \"\n  n \\<noteq> Max I \\<or> infinite I \\<Longrightarrow> iprev (inext n I) I = n\"\nby (blast intro: iprev_inext_infin iprev_inext_fin)\n\n\n\nlemma inext_eq_infin: \"\n  \\<lbrakk> inext a I = inext b I; infinite I \\<rbrakk> \\<Longrightarrow> a = b\"\nthm arg_cong[where f=\"\\<lambda>x. iprev x I\"]\napply (drule arg_cong[where f=\"\\<lambda>x. iprev x I\"])\napply (simp add: iprev_inext_infin)\ndone\nlemma inext_eq_fin: \"\n  \\<lbrakk> inext a I = inext b I; finite I; a \\<noteq> Max I; b \\<noteq> Max I \\<rbrakk> \\<Longrightarrow> a = b\"\napply (drule arg_cong[where f=\"\\<lambda>x. iprev x I\"])\napply (simp add: iprev_inext_fin)\ndone\nthm inext_mono2_infin_fin\nlemma inext_eq_infin_fin: \"\n  \\<lbrakk> inext a I = inext b I; a \\<noteq> Max I \\<and> b \\<noteq> Max I \\<or> infinite I \\<rbrakk> \\<Longrightarrow> a = b\"\nthm inext_eq_fin inext_eq_infin\nby (blast intro: inext_eq_fin inext_eq_infin)+\nlemma inext_eq: \"\n  \\<lbrakk> inext a I = inext b I; \\<exists>x\\<in>I. a < x; \\<exists>x\\<in>I. b < x \\<rbrakk> \\<Longrightarrow> a = b\"\nby (metis iprev_inext not_le wellorder_Max_lemma)\n\n\n\nlemma iprev_eq_if_neq_iMin: \"\n  \\<lbrakk> iprev a I = iprev b I; iMin I \\<noteq> a; iMin I \\<noteq> b \\<rbrakk> \\<Longrightarrow> a = b\"\napply (drule arg_cong[where f=\"\\<lambda>x. inext x I\"])\napply (simp add: inext_iprev)\ndone\nlemma iprev_eq: \"\n  \\<lbrakk> iprev a I = iprev b I; \\<exists>x\\<in>I. x < a; \\<exists>x\\<in>I. x < b \\<rbrakk> \\<Longrightarrow> a = b\"\nby (metis iprev_eq_if_neq_iMin not_less_iMin)\n\nlemma greater_imp_iprev_ge: \"\\<lbrakk> b < a; a \\<in> I; b \\<in> I \\<rbrakk> \\<Longrightarrow> b \\<le> iprev a I\"\napply (rule ccontr, simp add: linorder_not_le)\napply (blast dest: iprev_min_step)\ndone\n\n\n\n\nlemma inext_cut_less_conv: \"inext n I < t \\<Longrightarrow> inext n (I \\<down>< t) = inext n I\"\nthm le_less_trans[OF inext_mono]\napply (frule le_less_trans[OF inext_mono])\napply (case_tac \"n \\<in> I\")\n apply (simp add: inext_def)\n thm i_cut_commute_disj[of \"op \\<down><\" \"op \\<down>>\", simplified]\n apply (simp add: i_cut_commute_disj[of \"op \\<down><\" \"op \\<down>>\"] cut_less_mem_iff)\n apply (case_tac \"I \\<down>> n \\<noteq> {}\")\n  apply simp\n  apply (metis cut_less_Min_eq cut_less_Min_not_empty)\n apply (simp add: i_cut_empty)\napply (simp add: not_in_inext_fix cut_less_not_in_imp)\ndone\n\n\nlemma inext_cut_greater_conv: \"t < n \\<Longrightarrow> inext n (I \\<down>> t) = inext n I\"\napply (case_tac \"n \\<in> I\")\n thm cut_greater_mem_iff[THEN iffD2, OF conjI]\n apply (frule cut_greater_mem_iff[THEN iffD2, OF conjI], simp)\n thm i_cut_commute_disj[of \"op \\<down>>\" \"op \\<down>>\", simplified]\n thm cut_cut_greater\n apply (simp add: inext_def i_cut_commute_disj[of \"op \\<down>>\" \"op \\<down>>\"] cut_cut_greater max_def)\napply (simp add: not_in_inext_fix cut_greater_not_in_imp)\ndone\nlemma inext_cut_ge_conv: \"t \\<le> n \\<Longrightarrow> inext n (I \\<down>\\<ge> t) = inext n I\"\napply (case_tac \"t = 0\")\n apply (simp add: cut_ge_0_all)\nthm nat_cut_greater_ge_conv[symmetric]\napply (simp add: nat_cut_greater_ge_conv[symmetric] inext_cut_greater_conv)\ndone\n\nlemmas inext_cut_conv =\n  inext_cut_less_conv inext_cut_le_conv\n  inext_cut_greater_conv inext_cut_ge_conv\n\n\n\nlemma iprev_cut_greater_conv: \"t < iprev n I \\<Longrightarrow> iprev n (I \\<down>> t) = iprev n I\"\nthm less_le_trans[OF _ iprev_mono]\napply (frule less_le_trans[OF _ iprev_mono])\napply (case_tac \"n \\<in> I\")\n apply (simp add: iprev_def)\n thm i_cut_commute_disj[of \"op \\<down>>\" \"op \\<down><\", simplified]\n apply (simp add: i_cut_commute_disj[of \"op \\<down>>\" \"op \\<down><\"] cut_greater_mem_iff)\n apply (case_tac \"I \\<down>< n \\<noteq> {}\")\n  apply simp\n  apply (metis cut_greater_Max_eq cut_greater_Max_not_empty nat_cut_less_finite)\n apply (simp add: i_cut_empty)\napply (simp add: not_in_iprev_fix cut_greater_not_in_imp)\ndone\nlemma iprev_cut_ge_conv: \"t \\<le> iprev n I \\<Longrightarrow> iprev n (I \\<down>\\<ge> t) = iprev n I\"\napply (case_tac \"t = 0\")\n apply (simp add: cut_ge_0_all)\nthm nat_cut_greater_ge_conv\napply (simp add: nat_cut_greater_ge_conv[symmetric] iprev_cut_greater_conv)\ndone\nlemma iprev_cut_less_conv: \"n < t \\<Longrightarrow> iprev n (I \\<down>< t) = iprev n I\"\napply (case_tac \"n \\<in> I\")\n thm cut_less_mem_iff[THEN iffD2, OF conjI]\n apply (frule cut_less_mem_iff[THEN iffD2, OF conjI], simp)\n thm i_cut_commute_disj[of \"op \\<down><\" \"op \\<down><\", simplified]\n apply (simp add: iprev_def i_cut_commute_disj[of \"op \\<down><\" \"op \\<down><\"] cut_cut_less min_def)\napply (simp add: not_in_iprev_fix cut_less_not_in_imp)\ndone\nlemma iprev_cut_le_conv: \"n \\<le> t \\<Longrightarrow> iprev n (I \\<down>\\<le> t) = iprev n I\"\nthm nat_cut_le_less_conv iprev_cut_less_conv\nby (simp add: nat_cut_le_less_conv iprev_cut_less_conv)\n\nlemmas iprev_cut_conv =\n  iprev_cut_less_conv iprev_cut_le_conv\n  iprev_cut_greater_conv iprev_cut_ge_conv\nthm \n  inext_cut_conv\n  iprev_cut_conv\n\n\n\nthm inext_cut_less_conv\nlemma inext_cut_less_fix: \"t \\<le> inext n I \\<Longrightarrow> inext n (I \\<down>< t) = n\"\napply (case_tac \"n \\<in> I\")\n prefer 2\n thm contra_subsetD[OF cut_less_subset]\n apply (frule contra_subsetD[OF cut_less_subset[of _ t]])\n apply (simp add: not_in_inext_fix)\napply (case_tac \"t \\<le> n\")\n apply (metis cut_less_mem_iff not_in_inext_fix not_le)\napply (rule_tac t=n and s=\"Max (I \\<down>< t)\" in subst)\n apply (rule Max_equality[OF _ nat_cut_less_finite])\n  apply (simp add: cut_less_mem_iff)\n apply (rule ccontr)\n apply (clarsimp simp: cut_less_mem_iff linorder_not_le)\n thm inext_min_step\n apply (simp add: inext_min_step)\nthm inext_Max nat_cut_less_finite\napply (blast intro: inext_Max nat_cut_less_finite)\ndone\nlemma inext_cut_le_fix: \"t < inext n I \\<Longrightarrow> inext n (I \\<down>\\<le> t) = n\"\nthm nat_cut_le_less_conv\nby (simp add: nat_cut_le_less_conv inext_cut_less_fix)\n\nlemma iprev_cut_greater_fix: \"iprev n I \\<le> t \\<Longrightarrow> iprev n (I \\<down>> t) = n\"\napply (case_tac \"n \\<in> I\")\n prefer 2\n thm contra_subsetD[OF cut_greater_subset]\n apply (frule contra_subsetD[OF cut_greater_subset[of _ t]])\n apply (simp add: not_in_iprev_fix)\napply (case_tac \"n \\<le> t\")\n apply (metis cut_greater_mem_iff not_in_iprev_fix not_le)\napply (rule_tac t=n and s=\"iMin (I \\<down>> t)\" in subst)\n apply (rule iMin_equality)\n  apply (simp add: cut_greater_mem_iff)\n apply (metis cut_greater_mem_iff iprev_min_step2 not_leE order_le_less_trans)\nthm iprev_iMin\napply (rule iprev_iMin)\ndone\nlemma iprev_cut_ge_fix: \"iprev n I < t \\<Longrightarrow> iprev n (I \\<down>\\<ge> t) = n\"\napply (case_tac \"t = 0\")\n apply (simp add: cut_ge_0_all)\nthm nat_cut_greater_ge_conv[symmetric] iprev_cut_greater_fix\napply (simp add: nat_cut_greater_ge_conv[symmetric] iprev_cut_greater_fix)\ndone\n\ndefinition\n  CommuteWithIntervalCut4 :: \"(('a::linorder) set \\<Rightarrow> 'a set) \\<Rightarrow> bool\"\nwhere\n  \"CommuteWithIntervalCut4 fun \\<equiv> \n  \\<forall>t fun2 I. \n  (fun2 = (\\<lambda>I. I \\<down>< t) \\<or> fun2 = (\\<lambda>I. I \\<down>\\<le> t) \\<or> fun2 = (\\<lambda>I. I \\<down>> t) \\<or> fun2 = (\\<lambda>I. I \\<down>\\<ge> t) ) \\<longrightarrow> \n  fun (fun2 I) = fun2 (fun I)\"\ndefinition CommuteWithIntervalCut2 :: \"(('a::linorder) set \\<Rightarrow> 'a set) \\<Rightarrow> bool\"\nwhere \n  \"CommuteWithIntervalCut2 fun \\<equiv> \n  \\<forall>t fun2 I. \n  (fun2 = (\\<lambda>I. I \\<down>< t) \\<or> fun2 = (\\<lambda>I. I \\<down>> t)) \\<longrightarrow> \n  fun (fun2 I) = fun2 (fun I)\"\n\nlemma CommuteWithIntervalCut4_imp_2: \"CommuteWithIntervalCut4 fun \\<Longrightarrow> CommuteWithIntervalCut2 fun\"\nunfolding CommuteWithIntervalCut2_def CommuteWithIntervalCut4_def by blast\n\nlemma nat_CommuteWithIntervalCut2_4_eq: \"\n  CommuteWithIntervalCut4 (fun::nat set \\<Rightarrow> nat set) = CommuteWithIntervalCut2 fun\"\napply (unfold CommuteWithIntervalCut2_def CommuteWithIntervalCut4_def)\napply (rule iffI)\n apply blast\napply clarify\napply (case_tac \"fun2 = (\\<lambda>I. I \\<down>< t)\", simp)\napply (case_tac \"fun2 = (\\<lambda>I. I \\<down>> t)\", simp)\napply simp\napply (erule disjE)\n apply (simp add: nat_cut_le_less_conv)\napply (case_tac \"t = 0\")\n apply (simp add: cut_ge_0_all)\napply (simp add: nat_cut_greater_ge_conv[symmetric])\ndone\n\nlemma \n  cut_less_CommuteWithIntervalCut4:    \"CommuteWithIntervalCut4 (\\<lambda>I. I \\<down>< t)\" and\n  cut_le_CommuteWithIntervalCut4:      \"CommuteWithIntervalCut4 (\\<lambda>I. I \\<down>\\<le> t)\" and\n  cut_greater_CommuteWithIntervalCut4: \"CommuteWithIntervalCut4 (\\<lambda>I. I \\<down>> t)\" and\n  cut_ge_CommuteWithIntervalCut4:      \"CommuteWithIntervalCut4 (\\<lambda>I. I \\<down>\\<ge> t)\"\nthm i_cut_commute_disj\nunfolding CommuteWithIntervalCut4_def by (simp_all add: i_cut_commute_disj)\nlemmas i_cut_CommuteWithIntervalCut4 = \n  cut_less_CommuteWithIntervalCut4 cut_le_CommuteWithIntervalCut4\n  cut_greater_CommuteWithIntervalCut4 cut_ge_CommuteWithIntervalCut4\n\n\n\n\n\n\n\nthm cut_greater_image\nlemma inext_image: \"\n  \\<lbrakk> n \\<in> I; strict_mono_on f I \\<rbrakk> \\<Longrightarrow> inext (f n) (f ` I) = f (inext n I)\"\napply (case_tac \"\\<exists>x\\<in>I. n < x\")\n thm inext_mono2\n apply (frule inext_mono2, assumption)\n thm cut_greater_not_empty_iff[THEN iffD2]\n apply (frule cut_greater_not_empty_iff[THEN iffD2])\n apply (simp add: inext_def image_iff)\n apply (subgoal_tac \"\\<exists>x\\<in>I. f n = f x\")\n  prefer 2 \n  apply blast\n thm cut_greater_image\n apply (simp add: cut_greater_image)\n thm iMin_mono_on2[OF strict_mono_on_imp_mono_on]\n thm strict_mono_on_subset\n apply (blast intro: strict_mono_on_subset iMin_mono_on2 strict_mono_on_imp_mono_on)\napply (drule strict_mono_on_imp_mono_on)\nthm inext_all_le_fix\napply (simp add: inext_all_le_fix linorder_not_less mono_on_def)\ndone\n\nlemma iprev_image: \"\n  \\<lbrakk> n \\<in> I; strict_mono_on f I \\<rbrakk> \\<Longrightarrow> iprev (f n) (f ` I) = f (iprev n I)\"\napply (case_tac \"\\<exists>x\\<in>I. x < n\")\n thm iprev_mono2\n apply (frule iprev_mono2, assumption)\n thm cut_less_not_empty_iff[THEN iffD2]\n apply (frule cut_less_not_empty_iff[THEN iffD2])\n apply (simp add: iprev_def image_iff)\n apply (subgoal_tac \"\\<exists>x\\<in>I. f n = f x\")\n  prefer 2 \n  apply blast\n thm cut_less_image\n apply (simp add: cut_less_image)\n thm Max_mono_on2[OF strict_mono_on_imp_mono_on]\n thm strict_mono_on_subset\n thm nat_cut_less_finite\n apply (blast intro: strict_mono_on_subset Max_mono_on2 strict_mono_on_imp_mono_on nat_cut_less_finite)\napply (drule strict_mono_on_imp_mono_on)\nthm inext_all_le_fix\napply (simp add: iprev_all_ge_fix linorder_not_less mono_on_def)\ndone\n\nlemma inext_image2: \"\n  strict_mono f \\<Longrightarrow> inext (f n) (f ` I) = f (inext n I)\"\napply (case_tac \"n \\<in> I\")\n apply (blast intro: strict_mono_imp_strict_mono_on inext_image)\nthm inj_image_mem_iff strict_mono_imp_inj\napply (simp add: not_in_inext_fix inj_image_mem_iff strict_mono_imp_inj)\ndone\nlemma iprev_image2: \"\n  strict_mono f \\<Longrightarrow> iprev (f n) (f ` I) = f (iprev n I)\"\napply (case_tac \"n \\<in> I\")\n apply (blast intro: strict_mono_imp_strict_mono_on iprev_image)\napply (simp add: not_in_iprev_fix inj_image_mem_iff strict_mono_imp_inj)\ndone\n\n\n\n\n\nlemma inext_imirror_iprev_conv: \"\n  \\<lbrakk> finite I; n \\<le> iMin I + Max I \\<rbrakk> \\<Longrightarrow> \n  inext (mirror_elem n I) (imirror I) = mirror_elem (iprev n I) I\"\napply (case_tac \"n \\<in> I\")\n prefer 2\n thm imirror_mem_conv\n apply (simp add: not_in_iprev_fix not_in_inext_fix imirror_mem_conv)\napply (frule in_imp_not_empty[of _ I])\napply (frule in_imp_mirror_elem_in[of _ n], assumption)\napply (simp add: inext_def iprev_def)\napply (case_tac \"n = iMin I\")\n thm cut_less_Min_empty\n thm mirror_elem_Min\n apply (simp add: cut_less_Min_empty mirror_elem_Min)\n thm imirror_Max\n apply (subst imirror_Max[symmetric], assumption)\n thm cut_greater_Max_empty[OF _ order_refl]\n apply (simp add: cut_greater_Max_empty imirror_finite)\napply (frule iMin_le[of n I])\napply (intro conjI impI)\n  thm imirror_cut_greater'\n  apply (simp add: imirror_cut_greater')\n  thm imirror_bounds_iMin nat_cut_less_finite\n  apply (simp add: imirror_bounds_iMin nat_cut_less_finite cut_less_Min_eq)\n  apply (simp add: mirror_elem_def nat_mirror_def)\n apply (simp add: imirror_cut_greater')\n apply (simp add: imirror_bounds_def)\nthm cut_less_Min_not_empty\napply (simp add: cut_less_Min_not_empty)\ndone\ncorollary inext_imirror_iprev_conv': \"\n  \\<lbrakk> finite I; n \\<in> I \\<rbrakk> \\<Longrightarrow> \n  inext (mirror_elem n I) (imirror I) = mirror_elem (iprev n I) I\"\nthm inext_imirror_iprev_conv[OF _ trans_le_add2[OF Max_ge]]\nby (simp add: inext_imirror_iprev_conv trans_le_add2)\n\nlemma iprev_imirror_inext_conv: \"\n  \\<lbrakk> finite I; n \\<le> iMin I + Max I \\<rbrakk> \\<Longrightarrow> \n  iprev (mirror_elem n I) (imirror I) = mirror_elem (inext n I) I\"\napply (case_tac \"n \\<in> I\")\n prefer 2\n thm imirror_mem_conv\n apply (simp add: not_in_iprev_fix not_in_inext_fix imirror_mem_conv)\napply (frule in_imp_not_empty[of _ I])\napply (frule in_imp_mirror_elem_in[of _ n], assumption)\napply (simp add: inext_def iprev_def)\napply (case_tac \"n = Max I\")\n thm cut_greater_Max_empty\n thm mirror_elem_Max\n apply (simp add: cut_greater_Max_empty mirror_elem_Max)\n thm imirror_iMin\n apply (subst imirror_iMin[symmetric], assumption)\n thm cut_less_Min_empty[OF order_refl]\n apply (simp add: cut_less_Min_empty imirror_finite)\nthm Max_ge[of I n]\napply (frule Max_ge[of I n], assumption)\napply (drule le_neq_trans, assumption)\napply (intro conjI impI)\n  thm imirror_cut_less\n  apply (simp add: imirror_cut_less)\n  thm imirror_bounds_Max cut_greater_finite cut_greater_Max_eq\n  thm imirror_bounds_Max[OF cut_greater_finite]\n  thm Max_le_iff\n  apply (simp add: imirror_bounds_Max cut_greater_finite cut_greater_Max_eq del: Max_le_iff)\n  apply (simp add: mirror_elem_def nat_mirror_def)\n apply (simp add: imirror_cut_less)\n apply (simp add: imirror_bounds_def)\nthm cut_greater_Max_not_empty[of I n]\napply (simp add: cut_greater_Max_not_empty)\ndone\ncorollary iprev_imirror_inext_conv': \"\n  \\<lbrakk> finite I; n \\<in> I \\<rbrakk> \\<Longrightarrow> \n  iprev (mirror_elem n I) (imirror I) = mirror_elem (inext n I) I\"\nby (simp add: iprev_imirror_inext_conv trans_le_add2)\n\nthm \n  inext_imirror_iprev_conv\n  inext_imirror_iprev_conv'\n  iprev_imirror_inext_conv\n  iprev_imirror_inext_conv'\n\nlemma inext_insert_ge_Max: \"\n  \\<lbrakk> finite I; I \\<noteq> {}; Max I \\<le> a \\<rbrakk> \\<Longrightarrow> inext (Max I) (insert a I) = a\"\napply (case_tac \"a = Max I\")\n apply (simp add: insert_absorb inext_Max)\nthm le_neq_trans\napply (drule le_neq_trans, simp)\napply (rule min_step_inext2)\napply (simp, simp, simp)\napply (simp_all, blast?) (* blast is optional for the case, that the last goal could be solved by the simplifier in a future version, making the blast command superfluous. *)\ndone\n\nlemma iprev_insert_le_iMin: \"\n  \\<lbrakk> finite I; I \\<noteq> {}; a \\<le> iMin I \\<rbrakk> \\<Longrightarrow> iprev (iMin I) (insert a I) = a\"\napply (case_tac \"a = iMin I\")\n apply (simp add: iMinI_ex2 insert_absorb iprev_iMin)\nthm le_neq_trans\napply (drule le_neq_trans, simp)\napply (rule min_step_iprev2)\napply (simp_all add: iMin_Min_conv, blast?)\ndone\n\n\n\nthm cut_le_less_conv\nlemma cut_less_le_iprev_conv: \"\n  \\<lbrakk> t \\<in> I; t \\<noteq> iMin I \\<rbrakk> \\<Longrightarrow> I \\<down>< t = I \\<down>\\<le> (iprev t I)\"\napply (unfold iprev_def)\napply (rule set_eqI, safe)\n apply (simp add: i_cut_defs)\napply simp\napply (split split_if_asm)\n thm Max_ge_iff nat_cut_less_finite\n apply (simp add: Max_ge_iff nat_cut_less_finite)\n apply (blast intro: le_less_trans)\napply (frule iMin_neq_imp_greater, assumption)\napply (blast intro: iMin_in)\ndone\n\nlemma neq_Max_imp_inext_neq_iMin: \"\n  \\<lbrakk> t \\<in> I; t \\<noteq> Max I \\<or> infinite I \\<rbrakk> \\<Longrightarrow> inext t I \\<noteq> iMin I\"\napply (case_tac \"finite I\")\n apply (metis inext_mono2_infin_fin not_less_iMin)\napply (blast dest: inext_neq_iMin_infin)\ndone\ncorollary neq_Max_imp_inext_gr_iMin: \"\n  \\<lbrakk> t \\<in> I; t \\<noteq> Max I \\<or> infinite I\\<rbrakk> \\<Longrightarrow> iMin I < inext t I\"\napply (frule neq_Max_imp_inext_neq_iMin[THEN not_sym], assumption)\napply (drule neq_le_trans)\n thm inext_closed\n apply (blast dest: inext_closed)\napply simp\ndone\n\nlemma cut_le_less_inext_conv: \"\n  \\<lbrakk> t \\<in> I; t \\<noteq> Max I \\<or> infinite I\\<rbrakk> \\<Longrightarrow> I \\<down>\\<le> t = I \\<down>< (inext t I)\"\nthm cut_less_le_iprev_conv[of \"inext t I\" I]\napply (cut_tac cut_less_le_iprev_conv[of \"inext t I\" I])\nthm iprev_inext[of t I]\napply (cut_tac iprev_inext[of t I], simp)\napply assumption\napply (rule inext_closed, assumption)\napply (rule neq_Max_imp_inext_neq_iMin, assumption+)\ndone\nlemma cut_ge_greater_iprev_conv: \"\n  \\<lbrakk> t \\<in> I; t \\<noteq> iMin I \\<rbrakk> \\<Longrightarrow> I \\<down>\\<ge> t = I \\<down>> (iprev t I)\"\napply (frule iMin_neq_imp_greater, simp+)\napply (unfold iprev_def)\napply (rule set_eqI, safe)\n apply (simp add: i_cut_defs linorder_not_less)\n apply (drule iMinI, fastforce)\napply (split split_if_asm)\n apply (rule ccontr)\n apply (simp add: nat_cut_less_finite linorder_not_le)\n apply blast\napply simp\ndone\nlemma cut_greater_ge_inext_conv: \"\n  \\<lbrakk> t \\<in> I; t \\<noteq> Max I \\<or> infinite I \\<rbrakk> \\<Longrightarrow> I \\<down>> t = I \\<down>\\<ge> (inext t I)\"\nthm cut_ge_greater_iprev_conv[of \"inext t I\" I]\napply (cut_tac cut_ge_greater_iprev_conv[of \"inext t I\" I])\nthm iprev_inext[of t I]\napply (cut_tac iprev_inext[of t I], simp)\napply blast\napply (rule inext_closed, assumption)\napply (rule neq_Max_imp_inext_neq_iMin, assumption+)\ndone\n\nthm \n  cut_less_le_iprev_conv\n  cut_le_less_inext_conv\n  cut_ge_greater_iprev_conv\n  cut_greater_ge_inext_conv\n\n\n\n\n\n\n\nlemma inext_append: \"\n  \\<lbrakk> finite A; A \\<noteq> {}; B \\<noteq> {}; Max A < iMin B \\<rbrakk> \\<Longrightarrow> \n  inext n (A \\<union> B) = (if n \\<in> B then inext n B else (if n = Max A then iMin B else inext n A))\"\napply (case_tac \"n \\<in> A \\<union> B\")\n prefer 2\n apply (simp add: not_in_inext_fix)\n apply (blast dest: Max_in)\napply (frule Max_less_iMin_imp_disjoint, assumption)\napply (drule Un_iff[THEN iffD1], elim disjE)\n apply (drule disjoint_iff_in_not_in1[THEN iffD1])\n apply simp\n apply (intro conjI impI)\n  apply (simp add: inext_def cut_greater_Un cut_greater_Max_empty cut_greater_Min_all)\n apply (frule Max_neq_imp_less[of A], simp+)\n apply (simp add: inext_def cut_greater_Un cut_greater_Min_all)\n apply (subgoal_tac \"A \\<down>> n \\<noteq> {}\")\n  prefer 2\n  apply (simp add: cut_greater_not_empty_iff)\n  apply (blast intro: Max_in)\n apply (simp add: iMin_Un)\n apply (drule iMin_in[THEN cut_greater_in_imp])\n apply (rule min_eqL)\n apply (rule less_imp_le)\n apply blast\napply (drule disjoint_iff_in_not_in2[THEN iffD1])\napply simp\napply (subgoal_tac \"A \\<down>> n = {}\")\n prefer 2\n apply (simp add: cut_greater_empty_iff)\n apply fastforce \napply (simp add: inext_def cut_greater_Un)\ndone\ncorollary inext_append_eq1: \"\n  \\<lbrakk> finite A; A \\<noteq> {}; B \\<noteq> {}; Max A < iMin B; n \\<in> A; n \\<noteq> Max A \\<rbrakk> \\<Longrightarrow> \n  inext n (A \\<union> B) = inext n A\"\napply (frule Max_less_iMin_imp_disjoint, assumption)\napply (drule disjoint_iff_in_not_in1[THEN iffD1])\napply (simp add: inext_append Max_less_iMin_imp_disjoint)\ndone\ncorollary inext_append_eq2: \"\n  \\<lbrakk> finite A; A \\<noteq> {}; B \\<noteq> {}; Max A < iMin B; n \\<in> B \\<rbrakk> \\<Longrightarrow> \n  inext n (A \\<union> B) = inext n B\"\nby (simp add: inext_append)\ncorollary inext_append_eq3: \"\n  \\<lbrakk> finite A; A \\<noteq> {}; B \\<noteq> {}; Max A < iMin B \\<rbrakk> \\<Longrightarrow> \n  inext (Max A) (A \\<union> B) = iMin B\"\nby (simp add: inext_append not_less_iMin)\n\nlemma iprev_append: \"\\<lbrakk> finite A; A \\<noteq> {}; B \\<noteq> {}; Max A < iMin B \\<rbrakk> \\<Longrightarrow> \n  iprev n (A \\<union> B) = (if n \\<in> A then iprev n A else (if n = iMin B then Max A else iprev n B))\"\napply (case_tac \"n \\<in> A \\<union> B\")\n prefer 2\n apply (simp add: not_in_iprev_fix)\n apply (blast intro: iMin_in)\napply (frule Max_less_iMin_imp_disjoint, assumption)\napply (drule Un_iff[THEN iffD1], elim disjE)\n apply (drule disjoint_iff_in_not_in1[THEN iffD1])\n apply simp\n apply (subgoal_tac \"B \\<down>< n = {}\")\n  prefer 2\n  apply (simp add: cut_less_empty_iff)\n  apply fastforce \n apply (simp add: iprev_def cut_less_Un)\napply (drule disjoint_iff_in_not_in2[THEN iffD1])\napply simp\napply (intro conjI impI)\n apply (simp add: iprev_def cut_less_Un cut_less_Min_empty cut_less_Max_all)\napply (frule iMin_neq_imp_greater[of _ B], simp+)\napply (simp add: iprev_def cut_less_Un)\napply (subgoal_tac \"A \\<down>< n = A\")\n prefer 2\n apply (simp add: cut_less_all_iff)\n apply fastforce\napply (subgoal_tac \"B \\<down>< n \\<noteq> {}\")\n prefer 2\n apply (simp add: cut_less_not_empty_iff)\n apply (blast intro: iMin_in)\napply (simp add: Max_Un nat_cut_less_finite)\napply (rule max_eqR)\napply (rule less_imp_le)\nthm Max_in[OF nat_cut_less_finite, THEN cut_less_in_imp]\napply (drule Max_in[OF nat_cut_less_finite, THEN cut_less_in_imp])\napply (blast intro: iMin_le Max_in order_less_le_trans)\ndone\n\ncorollary iprev_append_eq1: \"\n  \\<lbrakk> finite A; A \\<noteq> {}; B \\<noteq> {}; Max A < iMin B; n \\<in> A \\<rbrakk> \\<Longrightarrow> \n  iprev n (A \\<union> B) = iprev n A\"\nby (simp add: iprev_append)\ncorollary iprev_append_eq2: \"\n  \\<lbrakk> finite A; A \\<noteq> {}; B \\<noteq> {}; Max A < iMin B; n \\<in> B; n \\<noteq> iMin B \\<rbrakk> \\<Longrightarrow> \n  iprev n (A \\<union> B) = iprev n B\"\napply (frule Max_less_iMin_imp_disjoint, assumption)\napply (drule disjoint_iff_in_not_in2[THEN iffD1])\napply (simp add: iprev_append)\ndone\ncorollary iprev_append_eq3: \"\n  \\<lbrakk> finite A; A \\<noteq> {}; B \\<noteq> {}; Max A < iMin B \\<rbrakk> \\<Longrightarrow> \n  iprev (iMin B) (A \\<union> B) = Max A\"\nby (simp add: iprev_append not_greater_Max[of _ \"iMin B\"])\n\n\n\n\nlemma inext_predicate_change_exists_aux: \"\\<And>a. \n  \\<lbrakk> c = card (I \\<down>\\<ge> a \\<down>< b); a < b; a \\<in> I; b \\<in> I; \\<not> P a; P b \\<rbrakk> \\<Longrightarrow> \n  \\<exists>n \\<in> (I \\<down>\\<ge> a \\<down>< b). \\<not> P n \\<and> P (inext n I)\"\napply (subgoal_tac \"0 < c\")\n prefer 2\n apply clarify\n apply (rule_tac x=a in not_empty_card_gr0_conv[OF nat_cut_less_finite, THEN iffD1, OF in_imp_not_empty, rule_format])\n apply (simp add: i_cut_mem_iff)\napply (induct c)\n apply simp\napply (subgoal_tac \"a < inext a I\")\n prefer 2\n apply (blast intro: inext_mono2)\napply (drule_tac x=\"inext a I\" in meta_spec)\nthm less_imp_inext_le[of _ b I]\napply (frule less_imp_inext_le[of _ b I], assumption+)\napply (case_tac \"inext a I < b\")\n prefer 2\n apply simp\n apply (subgoal_tac \"I \\<down>\\<ge> a \\<down>< b = {a}\")\n  prefer 2\n  apply (simp add: set_eq_iff i_cut_mem_iff, clarify)\n  apply (rule iffI)\n   prefer 2 \n   apply simp\n  apply clarify\n  apply (case_tac \"a < x\")\n   apply (simp add: inext_min_step)\n  apply simp+\napply (subgoal_tac \"I \\<down>\\<ge> inext a I = I \\<down>> a\")\n prefer 2\n apply (rule cut_greater_ge_inext_conv[symmetric], assumption)\n apply (case_tac \"finite I\")\n  apply (simp, rule less_imp_neq)\n  thm Max_gr_iff[OF _ in_imp_not_empty]\n  apply (simp add: Max_gr_iff in_imp_not_empty)\n  apply (blast intro: inext_closed)\n apply simp\napply (simp add: inext_closed)\napply (subgoal_tac \"a \\<notin> (I \\<down>> a \\<down>< b)\")\n prefer 2\n apply blast\napply (subgoal_tac \"(I \\<down>\\<ge> a \\<down>< b) = insert a (I \\<down>> a \\<down>< b)\")\n prefer 2\n apply (simp add:\n   i_cut_commute_disj[of \"op \\<down>\\<ge>\" \"op \\<down><\"] i_cut_commute_disj[of \"op \\<down>>\" \"op \\<down><\"])\n apply (simp add: cut_ge_greater_conv_if i_cut_mem_iff)\napply (simp add: card_insert_disjoint[OF nat_cut_less_finite])\napply (case_tac \"P (inext a I)\")\n apply blast\napply (case_tac \"card (I \\<down>> a \\<down>< b) = 0\")\n apply (drule card_0_eq[OF nat_cut_less_finite, THEN iffD1])\n apply (simp add: cut_less_empty_iff)\n apply (drule_tac x=\"inext a I\" in bspec)\n  apply (blast intro: inext_closed)\n apply simp\napply simp\ndone\n\nlemma inext_predicate_change_exists: \"\n  \\<lbrakk> a \\<le> b; a \\<in> I; b \\<in> I; \\<not> P a; P b \\<rbrakk> \\<Longrightarrow> \n  \\<exists>n\\<in>I. a \\<le> n \\<and> n < b \\<and> \\<not> P n \\<and> P (inext n I)\"\napply (drule order_le_less[THEN iffD1], erule disjE)\n prefer 2 \n apply blast\nthm inext_predicate_change_exists_aux[OF refl]\napply (drule inext_predicate_change_exists_aux[OF refl], assumption+)\napply blast\ndone\n\nlemma iprev_predicate_change_exists: \"\n  \\<lbrakk> a \\<le> b; a \\<in> I; b \\<in> I; \\<not> P b; P a \\<rbrakk> \\<Longrightarrow> \n  \\<exists>n\\<in>I. a < n \\<and> n \\<le> b \\<and> \\<not> P n \\<and> P (iprev n I)\"\napply (frule inext_predicate_change_exists[of a b I \"\\<lambda>x. \\<not> P x\"], simp+)\napply clarify\napply (rule_tac x=\"inext n I\" in bexI)\n prefer 2\n apply (blast intro: inext_closed)\napply (subgoal_tac \"n < inext n I\")\n prefer 2\n apply (blast intro: inext_mono2)\napply (frule_tac x=a and z=\"inext n I\" in le_less_trans, assumption)\napply (frule less_imp_inext_le, assumption+)\napply (cut_tac n=n and I=I in iprev_inext)\n apply (case_tac \"finite I\")\n  apply simp\n  apply (rule less_imp_neq)\n  apply (blast intro: inext_closed Max_ge order_less_le_trans)\napply simp+\ndone\n\ncorollary nat_Suc_predicate_change_exists: \"\n  \\<lbrakk> a \\<le> b; \\<not> P a; P b \\<rbrakk> \\<Longrightarrow> \\<exists>n\\<ge>a. n < b \\<and> \\<not> P n \\<and> P (Suc n)\"\napply (drule inext_predicate_change_exists[OF _ UNIV_I UNIV_I], assumption+)\napply (simp add: inext_UNIV)\ndone\n\ncorollary nat_pred_predicate_change_exists: \"\n  \\<lbrakk> a \\<le> b; \\<not> P b; P a \\<rbrakk> \\<Longrightarrow> \\<exists>n\\<le>b. a < n \\<and> \\<not> P n \\<and> P (n - Suc 0)\"\napply (drule iprev_predicate_change_exists[OF _ UNIV_I UNIV_I], assumption+)\napply (fastforce simp add: iprev_UNIV)\ndone\n\n\n\nlemma inext_predicate_change_exists2_all: \"\n  \\<lbrakk> (a::nat) \\<le> b; a \\<in> I; b \\<in> I; \\<not> P a; \\<forall>k \\<in> I \\<down>\\<ge> b. P k \\<rbrakk> \\<Longrightarrow> \n  \\<exists>n\\<in>I. a \\<le> n \\<and> n < b \\<and> \\<not> P n \\<and> (\\<forall>k \\<in> I \\<down>> n. P k)\"\napply (drule order_le_less[THEN iffD1], erule disjE)\n prefer 2 \n apply blast\nthm inext_predicate_change_exists[of a b I \"\\<lambda>n. if (n = a) then P n else (\\<forall>k\\<in>I\\<down>\\<ge>n. P k)\"]\napply (frule inext_predicate_change_exists[OF less_imp_le,\n  of a b I \"\\<lambda>n. if (n = a) then P n else (\\<forall>k\\<in>I\\<down>\\<ge>n. P k)\"])\n apply simp+\napply clarify\napply (rule_tac x=n in bexI)\n prefer 2 \n apply assumption\napply (case_tac \"a < n\")\n prefer 2\n apply simp\n apply (split split_if_asm)\n  apply (subgoal_tac \"I \\<down>> n = {}\", simp+)\n apply (drule not_sym)\n thm cut_greater_ge_inext_conv\n apply (rule ssubst[OF cut_greater_ge_inext_conv])\n  apply assumption\n  apply (case_tac \"finite I\")\n   prefer 2 \n   apply simp\n  apply simp\n  apply (rule less_imp_neq)\n  thm inext_neq_imp_less\n  apply (drule inext_neq_imp_less)\n  apply (rule less_le_trans[OF _ Max_ge])\n  apply assumption+\napply (subgoal_tac \"a < inext n I\")\n prefer 2\n apply (blast intro: inext_mono order_less_le_trans)\napply (subgoal_tac \"I \\<down>\\<ge> inext n I = I \\<down>> n\")\n prefer 2\n apply (rule cut_greater_ge_inext_conv[symmetric], assumption)\n apply (case_tac \"finite I\")\n  apply simp\n  apply (rule less_imp_neq)\n  apply (blast intro: inext_closed Max_ge order_less_le_trans)\n apply simp\napply simp\nthm cut_greater_ge_conv_if\napply (simp add: cut_greater_ge_conv_if)\napply blast\ndone\n\ncorollary inext_predicate_change_exists2: \"\n  \\<lbrakk> (a::nat) \\<le> b; a \\<in> I; b \\<in> I; \\<not> P a; P b \\<rbrakk> \\<Longrightarrow> \n  \\<exists>n\\<in>I. a \\<le> n \\<and> n < b \\<and> \\<not> P n \\<and> (\\<forall>k\\<in>I. n < k \\<and> k \\<le> b \\<longrightarrow> P k)\"\nthm inext_predicate_change_exists2_all[of a b \"I \\<down>\\<le> b\"]\napply (frule inext_predicate_change_exists2_all[of a b \"I \\<down>\\<le> b\"])\n apply (simp add: i_cut_mem_iff)+\n apply fastforce\napply blast\ndone\n\ncorollary nat_Suc_predicate_change_exists2_all: \"\n  \\<lbrakk> (a::nat) \\<le> b; \\<not> P a; \\<forall>k\\<ge>b. P k \\<rbrakk> \\<Longrightarrow> \n  \\<exists>n\\<ge>a. n < b \\<and> \\<not> P n \\<and> (\\<forall>k>n. P k)\"\napply (drule inext_predicate_change_exists2_all[rule_format, OF _ UNIV_I UNIV_I])\napply (simp add: i_cut_mem_iff Ball_def)+\ndone\ncorollary nat_Suc_predicate_change_exists2: \"\n  \\<lbrakk> (a::nat) \\<le> b; \\<not> P a; P b \\<rbrakk> \\<Longrightarrow> \n  \\<exists>n\\<ge>a. n < b \\<and> \\<not> P n \\<and> (\\<forall>k\\<le>b. n < k \\<longrightarrow> P k)\"\nthm inext_predicate_change_exists2[of a b UNIV]\napply (drule inext_predicate_change_exists2[of a b UNIV])\napply simp+\napply blast\ndone\n\nthm inext_predicate_change_exists2_all\nlemma iprev_predicate_change_exists2_all: \"\n  \\<lbrakk> (a::nat) \\<le> b; a \\<in> I; b \\<in> I; \\<not> P b; \\<forall>k\\<in>I\\<down>\\<le>a. P k \\<rbrakk> \\<Longrightarrow> \n  \\<exists>n\\<in>I. a < n \\<and> n \\<le> b \\<and> \\<not> P n \\<and> (\\<forall>k\\<in>I\\<down><n. P k)\"\napply (drule order_le_less[THEN iffD1], erule disjE)\n prefer 2 \n apply blast\nthm iprev_predicate_change_exists[of a b I \"\\<lambda>n. if (n = b) then P n else (\\<forall>k\\<in>I\\<down>\\<le>n. P k)\"]\napply (frule iprev_predicate_change_exists[OF less_imp_le, \n  of a b I \"\\<lambda>n. if (n = b) then P n else (\\<forall>k\\<in>I\\<down>\\<le>n. P k)\"])\n apply simp+\napply clarify\napply (rule_tac x=n in bexI)\n prefer 2 \n apply assumption\napply (case_tac \"a < n\")\n prefer 2\n apply simp\napply simp\napply (subgoal_tac \"iMin I < n\")\n prefer 2\n apply (blast intro: order_le_less_trans)\napply (split split_if_asm)\n apply clarsimp\n apply (split split_if_asm)\n  apply simp\n thm cut_less_le_iprev_conv[symmetric]\n apply (simp add: cut_less_le_iprev_conv[symmetric])\n apply blast\napply (split split_if_asm)\n apply simp\napply (simp add: cut_less_le_iprev_conv[symmetric])\napply (clarsimp, rename_tac x)\napply (case_tac \"x < n\")\n apply blast\napply simp\ndone\n\n\n\nthm inext_predicate_change_exists2\ncorollary iprev_predicate_change_exists2: \"\n  \\<lbrakk> (a::nat) \\<le> b; a \\<in> I; b \\<in> I; \\<not> P b; P a \\<rbrakk> \\<Longrightarrow> \n  \\<exists>n\\<in>I. a < n \\<and> n \\<le> b \\<and> \\<not> P n \\<and> (\\<forall>k\\<in>I. a \\<le> k \\<and> k < n \\<longrightarrow> P k)\"\nthm iprev_predicate_change_exists2_all[of a b \"I \\<down>\\<ge> a\"]\napply (frule iprev_predicate_change_exists2_all[of a b \"I \\<down>\\<ge> a\"])\n apply (simp add: i_cut_mem_iff)+\n apply fastforce\napply blast\ndone\n\nthm nat_Suc_predicate_change_exists2_all\ncorollary nat_pred_predicate_change_exists2_all: \"\n  \\<lbrakk> (a::nat) \\<le> b; \\<not> P b; \\<forall>k\\<le>a. P k \\<rbrakk> \\<Longrightarrow> \n  \\<exists>n>a. n \\<le> b \\<and> \\<not> P n \\<and> (\\<forall>k<n. P k)\"\napply (drule iprev_predicate_change_exists2_all[rule_format, OF _ UNIV_I UNIV_I])\napply (simp add: i_cut_mem_iff Ball_def)+\ndone\n\nthm nat_Suc_predicate_change_exists2\ncorollary nat_pred_predicate_change_exists2: \"\n  \\<lbrakk> (a::nat) \\<le> b; \\<not> P b; P a \\<rbrakk> \\<Longrightarrow> \n  \\<exists>n>a. n \\<le> b \\<and> \\<not> P n \\<and> (\\<forall>k\\<ge>a. k < n \\<longrightarrow> P k)\"\nthm iprev_predicate_change_exists2[of a b UNIV]\napply (drule iprev_predicate_change_exists2[of a b UNIV])\napply simp+\napply blast\ndone\n\n\n\n\nsubsection {* @{text inext_nth} and @{text iprev_nth} -- nth element of a natural set *}\n\nterm inext\nprimrec\n  inext_nth :: \"nat set \\<Rightarrow> nat \\<Rightarrow> nat\" \nwhere\n  \"inext_nth I 0 = iMin I\"\n| \"inext_nth I (Suc n) = inext (inext_nth I n) I\"\n\n(*<*)\n(*\nsyntax (xsymbols)\n  \"inext_nth\" :: \"nat set \\<Rightarrow> nat \\<Rightarrow> nat\" (\"(_ \\<rightarrow> _)\" [100, 100] 60)\nsyntax (HTML output)\n  \"inext_nth\" :: \"nat set \\<Rightarrow> nat \\<Rightarrow> nat\" (\"(_ \\<rightarrow> _)\" [100, 100] 60)\n*)\n(*>*)\nnotation (xsymbols)\n  \"inext_nth\" (\"(_ \\<rightarrow> _)\" [100, 100] 60)\nnotation (HTML output)\n  \"inext_nth\" (\"(_ \\<rightarrow> _)\" [100, 100] 60)\n\nterm \"(I \\<rightarrow> a) + b\"\nterm \"(I \\<rightarrow> n) \\<in> I\"\nterm \"(A \\<rightarrow> n) + (B \\<rightarrow> n)\"\n\n\n\nlemma inext_nth_closed: \"I \\<noteq> {} \\<Longrightarrow> I \\<rightarrow> n \\<in> I\"\napply (induct n)\n apply (simp add: iMinI_ex2)\napply (simp add: inext_closed)\ndone\n\nthm inext_image\nlemma inext_nth_image: \"\n  \\<lbrakk> I \\<noteq> {}; strict_mono_on f I \\<rbrakk> \\<Longrightarrow> (f ` I) \\<rightarrow> n = f (I \\<rightarrow> n)\"\napply (induct n)\n apply (simp add: iMin_mono_on2 strict_mono_on_imp_mono_on)\napply (simp add: inext_image inext_nth_closed)\ndone\n\nthm inext_mono2\nlemma inext_nth_Suc_mono: \"I \\<rightarrow> n \\<le> I \\<rightarrow> Suc n\"\nby (simp add: inext_mono)\n\nlemma inext_nth_mono: \"a \\<le> b \\<Longrightarrow> I \\<rightarrow> a \\<le> I \\<rightarrow> b\"\napply (induct b)\n apply simp\napply (drule le_Suc_eq[THEN iffD1], erule disjE)\napply (rule_tac y=\"I \\<rightarrow> b\" in order_trans)\n apply simp\n apply (rule inext_nth_Suc_mono)\napply simp\ndone\n\nthm inext_mono2\nlemma inext_nth_Suc_mono2: \"\\<exists>x\\<in>I. I \\<rightarrow> n < x \\<Longrightarrow> I \\<rightarrow> n < I \\<rightarrow> Suc n\"\napply simp\napply (rule inext_mono2)\napply (blast intro: inext_nth_closed inext_mono2)+\ndone\n\nlemma inext_nth_mono2: \"\\<exists>x\\<in>I. I \\<rightarrow> a < x \\<Longrightarrow> (I \\<rightarrow> a < I \\<rightarrow> b) = (a < b)\"\napply (subgoal_tac \"I \\<noteq> {}\")\n prefer 2 \n apply blast\napply (rule iffI)\n apply (rule ccontr)\n apply (simp add: linorder_not_less)\n apply (drule inext_nth_mono[of _ _ I])\n apply simp\napply clarify\napply (induct b)\n apply blast\napply (drule less_Suc_eq[THEN iffD1], erule disjE)\n apply (blast intro: order_less_le_trans inext_nth_Suc_mono)\napply (blast intro: inext_nth_Suc_mono2)\ndone\n\nlemma inext_nth_mono2_infin: \"\n  infinite I \\<Longrightarrow> (I \\<rightarrow> a < I \\<rightarrow> b) = (a < b)\"\napply (drule infinite_nat_iff_unbounded[THEN iffD1])\napply (rule inext_nth_mono2)\napply blast\ndone\n\nlemma inext_nth_Max_fix: \"\n  \\<lbrakk> finite I; I \\<noteq> {}; I \\<rightarrow> a = Max I; a \\<le> b \\<rbrakk> \\<Longrightarrow> I \\<rightarrow> b = Max I\"\napply (induct b)\n apply simp\napply (drule le_Suc_eq[THEN iffD1], erule disjE)\n apply (simp add: inext_Max)\napply blast\ndone\n\n\n\nthm inext_cut_less_conv\nlemma inext_nth_cut_less_conv: \"\n  \\<And>I. I \\<rightarrow> n < t \\<Longrightarrow> (I \\<down>< t) \\<rightarrow> n = I \\<rightarrow> n\"\napply (case_tac \"I = {}\")\n apply (simp add: cut_less_empty)\napply (induct n)\n apply (simp add: cut_less_Min_eq cut_less_Min_not_empty)\napply simp\nthm order_le_less_trans[OF inext_mono]\napply (frule order_le_less_trans[OF inext_mono])\nthm inext_cut_less_conv\napply (simp add: inext_cut_less_conv)\ndone\nthm \n  inext_cut_less_conv\n  inext_nth_cut_less_conv\n\nlemma remove_Min_inext_nth_Suc_conv: \"\\<And>I. \n  Suc 0 < card I \\<or> infinite I \\<Longrightarrow> \n  (I - {iMin I}) \\<rightarrow> n = I \\<rightarrow> Suc n\"\n(*apply (frule card_gt_0_iff[THEN iffD1, OF gr_implies_gr0], clarify)*)\napply (subgoal_tac \"I \\<noteq> {}\")\n prefer 2\n thm card_gr0_imp_not_empty[OF gr_implies_gr0]\n apply (blast dest: card_gr0_imp_not_empty[OF gr_implies_gr0])\napply (subgoal_tac \"I - {iMin I} \\<noteq> {}\")\n prefer 2\n apply (rule ccontr, simp)\n apply (erule disjE)\n  apply (drule card_mono[OF singleton_finite])\n  apply simp\n apply (simp add: subset_singleton_conv)\n apply (blast dest: infinite_imp_nonempty infinite_imp_not_singleton)\napply (induct n)\n thm cut_greater_Min_eq_Diff[symmetric]\n apply (simp add: cut_greater_Min_eq_Diff[symmetric] inext_def iMinI_ex2)\napply simp\nthm ssubst[OF inext_def[THEN meta_eq_to_obj_eq], rule_format]\napply (rule_tac n=\"(inext (I \\<rightarrow> n) I)\" in ssubst[OF inext_def[THEN meta_eq_to_obj_eq], rule_format])\napply (rule_tac n=\"(inext (I \\<rightarrow> n) I)\" in ssubst[OF inext_def[THEN meta_eq_to_obj_eq], rule_format])\napply (simp add: inext_closed inext_nth_closed)\napply (subgoal_tac \"inext (I \\<rightarrow> n) I \\<noteq> iMin I\")\n prefer 2\n apply (erule disjE)\n thm inext_neq_iMin_not_card_1\n thm inext_neq_iMin_infin\n apply (simp add: inext_neq_iMin_not_card_1 inext_neq_iMin_infin)+\napply (subgoal_tac \"iMin I < (I \\<rightarrow> Suc n)\")\n prefer 2\n thm iMin_le[OF inext_nth_closed, rule_format]\n apply (drule_tac n=\"Suc n\" in iMin_le[OF inext_nth_closed, rule_format])\n apply simp\napply (simp add: cut_greater_Diff cut_greater_singleton)\ndone\n\ncorollary remove_Min_inext_nth_Suc_conv_finite: \"Suc 0 < card I \\<Longrightarrow> (I - {iMin I}) \\<rightarrow> n = I \\<rightarrow> Suc n\"\nby (simp add: remove_Min_inext_nth_Suc_conv)\ncorollary remove_Min_inext_nth_Suc_conv_infinite: \"infinite I \\<Longrightarrow> (I - {iMin I}) \\<rightarrow> n = I \\<rightarrow> Suc n\"\nby (simp add: remove_Min_inext_nth_Suc_conv)\n\n\nlemma remove_Max_eq: \"\\<lbrakk> finite I; I \\<noteq> {}; n \\<noteq> Max I \\<rbrakk> \\<Longrightarrow> Max (I - {n}) = Max I\"\nby (rule Max_equality, simp+)\nlemma remove_iMin_eq: \"\\<lbrakk> I \\<noteq> {}; n \\<noteq> iMin I \\<rbrakk> \\<Longrightarrow> iMin (I - {n}) = iMin I\"\nby (rule iMin_equality, simp_all add: iMinI_ex2 iMin_le)\nlemma remove_Min_eq: \"\\<lbrakk> finite I; I \\<noteq> {}; n \\<noteq> Min I \\<rbrakk> \\<Longrightarrow> Min (I - {n}) = Min I\"\nby (rule Min_eqI, simp+)\nlemma Max_le_iMin_conv_singleton: \"\\<lbrakk> finite I; I \\<noteq> {} \\<rbrakk> \\<Longrightarrow> (Max I \\<le> iMin I) = (\\<exists>x. I = {x})\"\nby (simp add: iMin_Min_conv Max_le_Min_conv_singleton del: Max_le_iff Min_ge_iff)\n\n\nlemma inext_nth_card_less_Max: \"\n  \\<And>I. Suc n < card I \\<Longrightarrow> I \\<rightarrow> n < Max I\"\nthm card_gr0_imp_not_empty[OF less_trans[OF zero_less_Suc]]\napply (frule card_gr0_imp_not_empty[OF less_trans[OF zero_less_Suc]])\napply (frule card_gr0_imp_finite[OF less_trans[OF zero_less_Suc]])\napply (induct n)\n apply (rule ccontr)\n apply (simp add: linorder_not_less iMin_Min_conv del: Max_le_iff Min_ge_iff)\n thm Max_le_Min_conv_singleton\n apply (drule Max_le_Min_conv_singleton[THEN iffD1], assumption+)\n apply clarsimp\napply (drule_tac x=\"I - {iMin I}\" in meta_spec)\nthm remove_Min_inext_nth_Suc_conv\napply (simp add: remove_Min_inext_nth_Suc_conv)\napply (subgoal_tac \"\\<not> I \\<subseteq> {iMin I}\")\n prefer 2\n apply (rule ccontr, simp)\n apply (drule card_mono[OF singleton_finite])\n apply simp\napply (simp add: card_Diff_singleton iMin_in Suc_less_pred_conv)\napply (subgoal_tac \"Max I \\<noteq> iMin I\")\n prefer 2\n apply (rule ccontr, simp)\n thm Max_le_iMin_conv_singleton[THEN iffD1]\n apply (frule Max_le_iMin_conv_singleton[THEN iffD1], clarsimp+)\nthm remove_Max_eq\napply (simp add: remove_Max_eq Max_le_iMin_conv_singleton)\ndone\nthm inext_nth_card_less_Max\nlemma inext_nth_card_less_Max': \"\n  n < card I - Suc 0 \\<Longrightarrow> I \\<rightarrow> n < Max I\"\nby (simp add: inext_nth_card_less_Max)\n\n\nlemma inext_nth_card_Max_aux: \"\n  \\<And>I. card I = Suc n \\<Longrightarrow> I \\<rightarrow> n = Max I\"\nthm card_gr0_imp_not_empty[OF less_le_trans[OF zero_less_Suc, OF eq_imp_le[OF sym]]]\napply (frule card_gr0_imp_not_empty[OF less_le_trans[OF zero_less_Suc, OF eq_imp_le[OF sym]]])\napply (frule card_gr0_imp_finite[OF less_le_trans[OF zero_less_Suc, OF eq_imp_le[OF sym]]])\napply (induct n)\n apply (clarsimp simp: card_1_singleton_conv)\napply simp\napply (cut_tac I=I and t=\"Max I\" in nat_cut_less_finite)\napply (subgoal_tac \"card (I \\<down>< Max I) = Suc n\")\n prefer 2\n apply (simp add: cut_less_le_conv cut_le_Max_all)\nthm card_gr0_imp_not_empty[OF less_le_trans[OF zero_less_Suc, OF eq_imp_le[OF sym]], rule_format]\napply (frule_tac n=n in card_gr0_imp_not_empty[OF less_le_trans[OF zero_less_Suc, OF eq_imp_le[OF sym]], rule_format])\napply (subgoal_tac \"Max (I \\<down>< Max I) < iMin {Max I}\")\n prefer 2\n apply (simp, blast)\napply (subgoal_tac \"inext_nth I n < Max I\")\n prefer 2\n thm inext_nth_card_less_Max\n apply (simp add: inext_nth_card_less_Max)\napply (frule inext_nth_cut_less_conv[symmetric])\napply simp\napply (rule min_step_inext)\n apply simp\n apply (rule subsetD, rule cut_less_subset, rule Max_in, assumption+)\n apply simp\napply (frule_tac A=\"I \\<down>< Max I\" and k=k in not_greater_Max, assumption)\napply (simp add: cut_less_mem_iff)\ndone\nlemma inext_nth_card_Max_aux': \"\n  \\<And>I. \\<lbrakk> finite I; I \\<noteq> {} \\<rbrakk> \\<Longrightarrow> I \\<rightarrow> (card I - Suc 0) = Max I\"\nby (simp add: inext_nth_card_Max_aux not_empty_card_gr0_conv)\n\nthm \n  inext_nth_card_Max_aux\n  inext_nth_card_Max_aux'\nthm \n  inext_nth_card_less_Max\n  inext_nth_Max_fix\nlemma inext_nth_card_Max: \"\n  \\<lbrakk> finite I; I \\<noteq> {}; card I \\<le> Suc n \\<rbrakk> \\<Longrightarrow> I \\<rightarrow> n = Max I\"\nthm inext_nth_Max_fix[of _ \"card I - Suc 0\"]\napply (rule inext_nth_Max_fix[of _ \"card I - Suc 0\"], assumption+)\napply (simp add: inext_nth_card_Max_aux')\napply simp\ndone\nlemma inext_nth_card_Max': \"\n  \\<lbrakk> finite I; I \\<noteq> {}; card I - Suc 0 \\<le> n \\<rbrakk> \\<Longrightarrow> I \\<rightarrow> n = Max I\"\nby (simp add: inext_nth_card_Max)\n\nthm \n  inext_nth_card_less_Max\n  inext_nth_card_Max\n  inext_nth_card_Max'\n\n\n\nlemma inext_nth_singleton: \"{a} \\<rightarrow> n = a\"\nthm inext_nth_Max_fix[OF singleton_finite singleton_not_empty _ le0]\nby (simp add: inext_nth_Max_fix[OF singleton_finite singleton_not_empty _ le0])\n\nlemma inext_nth_eq_Min_conv: \"\n  I \\<noteq> {} \\<Longrightarrow> (I \\<rightarrow> n = iMin I) = (n = 0 \\<or> (\\<exists>a. I = {a}))\"\napply (rule iffI) \n apply (case_tac n, simp)\n apply (rename_tac n')\n apply (rule ccontr)\n apply (drule_tac n=\"I \\<rightarrow> n'\" in  inext_neq_iMin_not_singleton, simp)\n apply simp\napply (erule disjE, simp)\napply (clarsimp simp: inext_nth_singleton)\ndone\n\nlemma inext_nth_gr_Min_conv: \"\n  I \\<noteq> {} \\<Longrightarrow> (iMin I < I \\<rightarrow> n) = (0 < n \\<and> \\<not>(\\<exists>a. I = {a}))\"\napply (rule subst[of \"iMin I \\<noteq> I \\<rightarrow> n\" \"iMin I < I \\<rightarrow> n\"])\n apply (frule iMin_le[OF inext_nth_closed[of _ n]])\n apply (simp add: linorder_neq_iff)\napply (subst neq_commute[of \"iMin I\"])\napply (simp add: inext_nth_eq_Min_conv)\ndone\n\nlemma inext_nth_gr_Min_conv_infinite: \"\n  infinite I \\<Longrightarrow> (iMin I < I \\<rightarrow> n) = (0 < n)\"\nby (simp add: inext_nth_gr_Min_conv infinite_imp_nonempty infinite_imp_not_singleton)\n\n\nlemma inext_nth_cut_ge_inext_nth: \"\\<And>I b. \n  I \\<noteq> {} \\<Longrightarrow> I \\<down>\\<ge> (I \\<rightarrow> a) \\<rightarrow> b = I \\<rightarrow> (a + b)\"\napply (induct a)\n apply (simp add: cut_ge_Min_all)\napply (case_tac \"card I = Suc 0\")\n apply (drule card_1_imp_singleton, clarify)\n apply (simp add: inext_nth_singleton inext_singleton cut_ge_Min_all)\napply (subgoal_tac \"Suc 0 < card I \\<or> infinite I\")\n prefer 2\n apply (rule ccontr, clarsimp simp: linorder_not_less not_empty_card_gr0_conv)\napply (case_tac \"I - {iMin I} = {}\")\n apply (rule_tac t=I and s=\"{iMin I}\" in subst, blast)\n apply (simp (no_asm) add: inext_nth_singleton inext_singleton cut_ge_Min_all)\napply (simp add: subset_singleton_conv)\nthm remove_Min_inext_nth_Suc_conv\napply (drule_tac x=\"I - {iMin I}\" in meta_spec)\napply (drule_tac x=b in meta_spec)\napply (drule meta_mp, blast)\nthm remove_Min_inext_nth_Suc_conv\napply (simp add: remove_Min_inext_nth_Suc_conv)\napply (simp add: cut_ge_Diff cut_ge_singleton)\napply (subgoal_tac \"iMin I < inext (I \\<rightarrow> a) I\", simp)\napply (rule le_neq_trans[OF _ not_sym])\n apply (simp add: iMin_le inext_closed inext_nth_closed)\napply (erule disjE)\napply (simp add: inext_neq_iMin_not_card_1 inext_neq_iMin_infin)+\ndone\n\nthm inext_append_eq1\nlemma inext_nth_append_eq1: \"\n  \\<lbrakk> finite A; A \\<noteq> {}; Max A < iMin B; A \\<rightarrow> n \\<noteq> Max A \\<rbrakk> \\<Longrightarrow>\n  (A \\<union> B) \\<rightarrow> n = A \\<rightarrow> n\"\napply (case_tac \"B = {}\", simp)\napply (induct n)\n apply (simp add: iMin_Un del: Max_less_iff)\n apply (rule min_eq)\n thm iMin_le_Max\n apply (blast intro: order_less_imp_le order_le_less_trans iMin_le_Max)\nthm Max_ge[OF _ inext_nth_closed]\napply (frule_tac n=\"Suc n\" in Max_ge[OF _ inext_nth_closed, rule_format], assumption)\napply (drule order_le_neq_trans, simp+)\nthm order_le_less_trans[OF inext_mono]\napply (drule order_le_less_trans[OF inext_mono])\nthm inext_append_eq1\napply (simp add: inext_append_eq1 inext_nth_closed)\ndone\n\n\nthm inext_nth_append_eq1\nthm inext_append_eq2\nlemma inext_nth_card_append_eq1: \"\n  \\<And>A B.\\<lbrakk> Max A < iMin B; n < card A \\<rbrakk> \\<Longrightarrow>\n  (A \\<union> B) \\<rightarrow> n = A \\<rightarrow> n\"\napply (case_tac \"B = {}\", simp)\nthm card_gr0_imp_finite[OF le_less_trans[OF le0]]\napply (frule card_gr0_imp_finite[OF le_less_trans[OF le0]])\napply (frule card_gr0_imp_not_empty[OF le_less_trans[OF le0]])\napply (drule Suc_leI[of n], drule order_le_less[THEN iffD1], erule disjE)\n apply (rule inext_nth_append_eq1, assumption+)\n apply (simp add: inext_nth_card_less_Max less_imp_neq)\nthm inext_nth_card_Max[OF _ _ eq_imp_le[OF sym]]\napply (simp add: inext_nth_card_Max[OF _ _ eq_imp_le[OF sym]] del: Max_less_iff)\napply (induct n)\n apply (frule card_1_imp_singleton[OF sym], erule exE)\n apply (simp add: iMin_insert)\napply simp\napply (subgoal_tac \"inext_nth A n < Max A\")\n prefer 2\n apply (rule inext_nth_card_less_Max, simp)\nthm inext_nth_append_eq1\napply (simp add: inext_nth_append_eq1)\napply (rule min_step_inext)\napply (simp add: inext_nth_closed)+\napply (rule conjI)\n apply (subgoal_tac \"k < A \\<rightarrow> Suc n\")\n  prefer 2\n  apply (subgoal_tac \"A \\<rightarrow> Suc n = Max A\")\n   prefer 2\n   thm inext_nth_card_Max\n   apply (rule inext_nth_card_Max)\n   apply simp+\n apply (rule_tac n=\"A \\<rightarrow> n\" and k=k in inext_min_step, simp+)\napply (rule not_less_iMin)\napply (rule_tac y=\"Max A\" in order_less_trans)\napply simp+\ndone\n\nthm inext_append_eq3\n\n\n\nlemma inext_nth_card_append_eq2: \"\n  \\<lbrakk> finite A; A \\<noteq> {}; B \\<noteq> {}; Max A < iMin B; card A \\<le> n \\<rbrakk> \\<Longrightarrow>\n  (A \\<union> B) \\<rightarrow> n = B \\<rightarrow> (n - card A)\"\nthm inext_nth_cut_ge_inext_nth\napply (rule_tac t=\"(A \\<union> B) \\<rightarrow> n\" and s=\"(A \\<union> B) \\<rightarrow> (card A + (n - card A))\" in subst, simp)\nthm inext_nth_cut_ge_inext_nth[symmetric]\napply (subst inext_nth_cut_ge_inext_nth[symmetric], simp)\napply (subst inext_nth_card_append_eq3, assumption+)\napply (simp add: cut_ge_Un cut_ge_Max_empty cut_ge_Min_all del: Max_less_iff)\ndone\n\n\n\n\nthm inext_append\nlemma inext_nth_card_append: \"\n  \\<lbrakk> finite A; A \\<noteq> {}; B \\<noteq> {}; Max A < iMin B \\<rbrakk> \\<Longrightarrow>\n  (A \\<union> B) \\<rightarrow> n = (if n < card A then A \\<rightarrow> n else B \\<rightarrow> (n - card A))\"\nby (simp add: inext_nth_card_append_eq1 inext_nth_card_append_eq2)\n\nlemma inext_nth_insert_Suc: \"\n  \\<lbrakk> I \\<noteq> {}; a < iMin I \\<rbrakk> \\<Longrightarrow> (insert a I) \\<rightarrow> Suc n = I \\<rightarrow> n\"\napply (frule not_less_iMin)\napply (rule_tac t=\"I \\<rightarrow> n\" and s=\"(insert a I - {iMin (insert a I)}) \\<rightarrow> n\" in subst)\n apply (simp add: iMin_insert min_eqL)\nthm remove_Min_inext_nth_Suc_conv\napply (subst remove_Min_inext_nth_Suc_conv)\napply (case_tac \"finite I\")\napply (simp add: not_empty_card_gr0_conv)+\ndone\n\nlemma inext_nth_cut_less_eq: \"\n  n < card (I \\<down>< t) \\<Longrightarrow> (I \\<down>< t) \\<rightarrow> n = I \\<rightarrow> n\"\napply (rule_tac t=\"I \\<rightarrow> n\" and s=\"(I \\<down>< t \\<union> I \\<down>\\<ge> t) \\<rightarrow> n\" in subst)\n apply (simp add: cut_less_cut_ge_ident)\nthm inext_nth_card_append_eq1\napply (case_tac \"I \\<down>\\<ge> t = {}\", simp)\napply (rule sym, rule inext_nth_card_append_eq1)\n apply (drule card_gt_0_iff[THEN iffD1, OF gr_implies_gr0], clarify)\n apply (simp add: Ball_def i_cut_mem_iff iMin_gr_iff)\napply simp\ndone\n\nlemma less_card_cut_less_imp_inext_nth_less: \"\n  n < card (I \\<down>< t) \\<Longrightarrow> I \\<rightarrow> n < t\"\napply (case_tac \"I \\<down>< t = {}\", simp)\napply (rule subst[OF inext_nth_cut_less_eq], assumption)\napply (rule cut_less_bound[OF inext_nth_closed], assumption)\ndone\n\nlemma inext_nth_less_less_card_conv: \"\n  I \\<down>\\<ge> t \\<noteq> {} \\<Longrightarrow> (I \\<rightarrow> n < t) = (n < card (I \\<down>< t))\"\napply (case_tac \"I = {}\", blast)\napply (case_tac \"I \\<down>< t = {}\")\n apply (simp add: linorder_not_less)\n thm cut_less_empty_iff inext_nth_closed\n apply (simp add: cut_less_empty_iff inext_nth_closed)\napply (rule iffI)\n apply (rule ccontr, simp add: linorder_not_less)\n apply (subgoal_tac \"Max (I \\<down>< t) < iMin (I \\<down>\\<ge> t)\")\n  prefer 2\n  apply (simp add: nat_cut_less_finite iMin_gr_iff Ball_def i_cut_mem_iff)\n thm ssubst[OF cut_less_cut_ge_ident[OF order_refl], of \"\\<lambda>x. x \\<rightarrow> n < t\" _ t]\n apply (drule ssubst[OF cut_less_cut_ge_ident[OF order_refl], of \"\\<lambda>x. x \\<rightarrow> n < t\" _ t])\n thm inext_nth_card_append_eq2[OF nat_cut_less_finite, of I t \"I \\<down>\\<ge> t\" n]\n apply (drule inext_nth_card_append_eq2[OF nat_cut_less_finite, of I t \"I \\<down>\\<ge> t\" n], assumption+)\n apply (simp add: inext_nth_card_append_eq2 nat_cut_less_finite)\n apply (subgoal_tac \"\\<And>x. I \\<down>\\<ge> t \\<rightarrow> x \\<ge> t\")\n  prefer 2\n  apply (rule cut_ge_bound[OF inext_nth_closed], assumption)\n apply (simp add: linorder_not_le[symmetric])\napply (rule subst[OF inext_nth_cut_less_eq], assumption)\napply (rule cut_less_bound[OF inext_nth_closed], assumption)\ndone\n\n\nlemma cut_less_inext_nth_card_eq1: \"\n  n < card I \\<or> infinite I \\<Longrightarrow> card (I \\<down>< (I \\<rightarrow> n)) = n\"\napply (case_tac \"I = {}\", simp)\napply (induct n)\n apply (simp add: card_eq_0_iff nat_cut_less_finite cut_less_Min_empty)\napply (subgoal_tac \"n < card I \\<or> infinite I\")\n prefer 2\n apply fastforce\napply simp\napply (subgoal_tac \"I \\<rightarrow> n \\<noteq> Max I \\<or> infinite I\")\n prefer 2\n thm inext_nth_card_less_Max[THEN less_imp_neq]\n apply (blast dest: inext_nth_card_less_Max less_imp_neq)\napply (rule subst[OF cut_le_less_inext_conv[OF inext_nth_closed]], assumption+)\napply (simp add: cut_le_less_conv_if inext_nth_closed cut_less_mem_iff card_insert_if nat_cut_less_finite)\ndone\n\nlemma cut_less_inext_nth_card_eq2: \"\n  \\<lbrakk> finite I; card I \\<le> Suc n \\<rbrakk> \\<Longrightarrow> card (I \\<down>< (I \\<rightarrow> n)) = card I - Suc 0\"\napply (case_tac \"I = {}\", simp add: cut_less_empty)\napply (simp add: inext_nth_card_Max cut_less_Max_eq_Diff)\ndone\n\nlemma cut_less_inext_nth_card_if: \"\n  card (I \\<down>< (I \\<rightarrow> n)) = (\n  if (n < card I \\<or> infinite I) then n else card I - Suc 0)\"\nby (simp add: cut_less_inext_nth_card_eq1 cut_less_inext_nth_card_eq2)\n\nlemma cut_le_inext_nth_card_eq1: \"\n  n < card I \\<or> infinite I \\<Longrightarrow> card (I \\<down>\\<le> (I \\<rightarrow> n)) = Suc n\"\napply (case_tac \"I = {}\", simp)\nthm cut_le_less_inext_conv[OF inext_nth_closed]\napply (simp add: cut_le_less_conv_if inext_nth_closed card_insert_if nat_cut_less_finite cut_less_mem_iff cut_less_inext_nth_card_eq1)\ndone\nlemma cut_le_inext_nth_card_eq2: \"\n  \\<lbrakk> finite I; card I \\<le> Suc n \\<rbrakk> \\<Longrightarrow> card (I \\<down>\\<le> (I \\<rightarrow> n)) = card I\"\napply (case_tac \"I = {}\", simp add: cut_le_empty)\napply (simp add: inext_nth_card_Max cut_le_Max_all)\ndone\n\nlemma cut_le_inext_nth_card_if: \"\n  card (I \\<down>\\<le> (I \\<rightarrow> n)) = (\n  if (n < card I \\<or> infinite I) then Suc n else card I)\"\nby (simp add: cut_le_inext_nth_card_eq1 cut_le_inext_nth_card_eq2)\n\n\n\n\nterm iprev\nprimrec\n  iprev_nth :: \"nat set \\<Rightarrow> nat \\<Rightarrow> nat\"\nwhere\n  \"iprev_nth I 0 = Max I\"\n| \"iprev_nth I (Suc n) = iprev (iprev_nth I n) I\"\nthm inext_iprev\n\n(*<*)\n(*\nsyntax (xsymbols)\n  \"iprev_nth\" :: \"nat set \\<Rightarrow> nat \\<Rightarrow> nat\" (\"(_ \\<leftarrow> _)\" [100, 100] 60)\nsyntax (HTML output)\n  \"iprev_nth\" :: \"nat set \\<Rightarrow> nat \\<Rightarrow> nat\" (\"(_ \\<leftarrow> _)\" [100, 100] 60)\n*)\n(*>*)\nnotation (xsymbols)\n  \"iprev_nth\" (\"(_ \\<leftarrow> _)\" [100, 100] 60)\nnotation (HTML output)\n  \"iprev_nth\" (\"(_ \\<leftarrow> _)\" [100, 100] 60)\n\nlemma iprev_nth_closed: \"\\<lbrakk> finite I; I \\<noteq> {} \\<rbrakk> \\<Longrightarrow> I \\<leftarrow> n \\<in> I\"\napply (induct n)\n apply simp\napply (simp add: iprev_closed)\ndone\n\nthm iprev_image\nlemma iprev_nth_image: \"\n  \\<lbrakk> finite I; I \\<noteq> {}; strict_mono_on f I \\<rbrakk> \\<Longrightarrow> (f ` I) \\<leftarrow> n = f (I \\<leftarrow> n)\"\napply (induct n)\n apply (simp add: Max_mono_on2 strict_mono_on_imp_mono_on)\napply (simp add: iprev_image iprev_nth_closed)\ndone\n\nthm iprev_mono\nlemma iprev_nth_Suc_mono: \"I \\<leftarrow> (Suc n) \\<le> I \\<leftarrow> n\"\nby (simp add: iprev_mono)\nlemma iprev_nth_mono: \"a \\<le> b \\<Longrightarrow> I \\<leftarrow> b \\<le> I \\<leftarrow> a\"\napply (induct b)\n apply simp\napply (drule le_Suc_eq[THEN iffD1], erule disjE)\n apply (rule_tac y=\"iprev_nth I b\" in order_trans)\n apply (rule iprev_nth_Suc_mono)\n apply simp\napply simp\ndone\nlemma iprev_nth_Suc_mono2:\n  \"\\<lbrakk> finite I; \\<exists>x\\<in>I. x < I \\<leftarrow> n \\<rbrakk> \\<Longrightarrow> I \\<leftarrow> (Suc n) < I \\<leftarrow> n\"\nthm iprev_mono2\napply simp\napply (rule iprev_mono2)\nthm iprev_nth_closed\napply (blast intro: iprev_nth_closed)+\ndone\n\nlemma iprev_nth_mono2: \"\n  \\<lbrakk> finite I; \\<exists>x\\<in>I. x < I \\<leftarrow> a \\<rbrakk> \\<Longrightarrow> (I \\<leftarrow> b < I \\<leftarrow> a) = (a < b)\"\napply (subgoal_tac \"I \\<noteq> {}\")\n prefer 2 \n apply blast\napply (rule iffI)\n apply (rule ccontr)\n apply (simp add: linorder_not_less)\n apply (drule iprev_nth_mono[of _ _ I])\n apply simp\napply clarify\napply (induct b)\n apply blast\napply (drule less_Suc_eq[THEN iffD1], erule disjE)\n apply (blast intro: order_le_less_trans iprev_nth_Suc_mono)\napply (blast intro: iprev_nth_Suc_mono2)\ndone\n\nlemma iprev_nth_iMin_fix: \"\n  \\<lbrakk> I \\<noteq> {}; I \\<leftarrow> a = iMin I; a \\<le> b \\<rbrakk> \\<Longrightarrow> I \\<leftarrow> b = iMin I\"\napply (induct b)\n apply simp\napply (drule le_Suc_eq[THEN iffD1], erule disjE)\n apply (simp add: iprev_iMin)\napply blast\ndone\n\nlemma iprev_nth_singleton: \"{a} \\<leftarrow> n= a\"\nthm iprev_nth_iMin_fix[OF singleton_not_empty _ le0]\nby (simp add: iprev_nth_iMin_fix[OF singleton_not_empty _ le0])\n\n\n\n\n\nsubsection {* Induction over arbitrary natural sets using the functions @{text inext} and @{text iprev} *}\n\nlemma inext_nth_surj_aux1:\"\n  {x \\<in> I. \\<not>(\\<exists>n. I \\<rightarrow> n = x)} = {}\"\n  (is \"?S = {}\"\n   is \"{ x \\<in> I. ?P x} = {}\")\napply (case_tac \"I = {}\", blast)\nproof (rule ccontr)\n  assume as_S_not_empty: \"?S \\<noteq> {}\"\n\n  obtain S where s_S: \"S = ?S\" by blast\n  hence S_not_empty: \"S \\<noteq> {}\" \n    using as_S_not_empty by blast\n  \n  have s_not_ex: \"\\<And>x. \\<lbrakk> x \\<in> I; ?P x \\<rbrakk> \\<Longrightarrow> x \\<in> S\"\n    using s_S by blast\n\n  have s_subset:\"S \\<subseteq> I\"\n    using s_S by blast\n  have i_not_empty: \"I \\<noteq> {}\"\n    using as_S_not_empty by blast\n  \n  have s_iMin_S: \"iMin S \\<in> S\"\n    thm iMinI_ex2\n    using S_not_empty by (simp add: iMinI_ex2)\n  hence s_iMin_i: \"iMin S \\<in> I\"\n    using s_subset by blast\n  \n  show False\n  proof cases\n    assume as:\"iMin I < iMin S\"\n    \n    obtain prev where s_prev: \"prev = iprev (iMin S) I\" by blast\n    have s_prev_in: \"prev \\<in> I\"\n      apply (simp add: s_prev)\n      thm iprev_closed[of \"iMin S\" i]\n      apply (rule iprev_closed)\n      apply (rule s_iMin_i)\n      done\n\n    have s_prev_next_min: \"inext prev I = iMin S\"\n      apply (simp add: s_prev)\n      thm inext_iprev[of I \"iMin S\"]\n      apply (rule inext_iprev)\n      apply (insert as, simp)\n      done\n\n    have s_prev_min_1: \"prev < iMin S\"\n      apply (simp only: s_prev)\n      thm iprev_mono2[of \"iMin S\" I]\n      apply (rule iprev_mono2[of \"iMin S\" ])\n      apply (rule s_iMin_i)\n      apply (rule_tac x=\"iMin I\" in bexI)\n      apply (rule as)\n      apply (simp add: iMinI_ex2 i_not_empty)\n      done\n    hence prev_not_in_s: \"prev \\<notin> S\"\n      thm not_less_iMin\n      by (simp add: not_less_iMin)\n    have \"\\<exists>n. I \\<rightarrow> n = prev\"\n      by (insert prev_not_in_s s_not_ex[of prev] s_prev_in, blast)\n    then obtain nPrev where s_nPrev: \"I \\<rightarrow> nPrev = prev\" by blast\n    hence \"I \\<rightarrow> (Suc nPrev) = inext prev I\" by simp\n    hence \"I \\<rightarrow> (Suc nPrev) = iMin S\" \n      using s_prev_next_min by simp\n    hence \"\\<exists>n. I \\<rightarrow> n = iMin S\" by blast\n    hence \"iMin S \\<notin> S\"\n      using s_iMin_i s_S by blast\n    thus False\n      using s_iMin_S by blast\n  next\n    assume as:\"\\<not>(iMin I < iMin S)\"\n\n    have \"iMin S = iMin I\"\n      apply (insert s_subset S_not_empty as)\n      thm iMin_subset\n      apply (frule_tac A=S and B=I in iMin_subset)\n      by simp_all\n    hence \"\\<exists>n. I \\<rightarrow> n \\<in> S\"\n      apply (rule_tac x=0 in exI)\n      apply (insert s_iMin_S)\n      apply simp\n      done\n    thus False\n      using s_S by blast\n  qed\nqed\n\nterm inext_nth\nterm \"\\<lambda>n. I \\<rightarrow> n\"\nlemma inext_nth_surj_on:\"surj_on (\\<lambda>n. I \\<rightarrow> n) UNIV I\"\napply (simp add: surj_on_conv)\nthm inext_nth_surj_aux1[of I]\nby (insert inext_nth_surj_aux1[of I], blast)\ncorollary in_imp_ex_inext_nth: \"x \\<in> I \\<Longrightarrow> \\<exists>n. x = I \\<rightarrow> n\"\nthm surj_onD\nthm surj_onD[where A=UNIV, simplified]\napply (rule surj_onD[where A=UNIV, simplified])\napply (rule inext_nth_surj_on)\napply assumption\ndone\n\nlemma inext_induct: \"\n  \\<lbrakk> P (iMin I); \\<And>n. \\<lbrakk> n \\<in> I; P n \\<rbrakk> \\<Longrightarrow> P (inext n I); n \\<in> I \\<rbrakk> \\<Longrightarrow> P n\"\nthm image_nat_induct\nthm image_nat_induct[where P=P and f=\"\\<lambda>n. I \\<rightarrow> n\" and I=I and a=n]\napply (rule_tac f=\"\\<lambda>n. I \\<rightarrow> n\" and I=I in image_nat_induct)\nthm inext_nth_closed[OF in_imp_not_empty] \nthm inext_nth_surj_on\napply (simp add: inext_nth_closed[OF in_imp_not_empty] inext_nth_surj_on)+\ndone\nthm inext_induct\n\n\nlemma iprev_nth_surj_aux1:\"\n  finite I \\<Longrightarrow> { x \\<in> I. \\<not>(\\<exists>n. I \\<leftarrow> n = x)} = {}\"\napply (case_tac \"I = {}\", blast)\nproof (rule ccontr)\n  assume as_finite_i: \"finite I\"\n  let ?S = \"{x \\<in> I. \\<not> (\\<exists>n. I \\<leftarrow> n = x)}\"\n  assume as_S_not_empty: \"?S \\<noteq> {}\"\n\n  obtain S where s_S: \"S = ?S\" by blast\n  hence S_not_empty: \"S \\<noteq> {}\" \n    using as_S_not_empty by blast\n\n  have s_not_ex: \"\\<And>x. \\<lbrakk> x \\<in> I; \\<not>(\\<exists>n. I \\<leftarrow> n = x) \\<rbrakk> \\<Longrightarrow> x \\<in> S\"\n    using s_S by blast\n\n  have s_subset:\"S \\<subseteq> I\"\n    using s_S by blast\n  have i_not_empty: \"I \\<noteq> {}\"\n    using as_S_not_empty by blast\n\n  from as_finite_i\n  have S_finite: \"finite S\"\n    using s_subset by (blast intro: finite_subset)\n  \n  have s_Max_S: \"Max S \\<in> S\"\n    thm Max_in\n    using S_not_empty S_finite by simp\n  hence s_Max_i: \"Max S \\<in> I\"\n    using s_subset by blast\n  \n  show False\n  proof cases\n    assume as:\"Max S < Max I\"\n    \n    obtain next' where s_next: \"next' = inext (Max S) I\" by blast\n    have s_next_in: \"next' \\<in> I\"\n      thm inext_closed[of \"Max S\" I]\n      by (simp add: s_next inext_closed s_Max_i)\n\n    have s_next_prev_max: \"iprev next' I = Max S\"\n      apply (simp add: s_next)\n      thm iprev_inext[of \"Max S\" I]\n      apply (rule iprev_inext)\n      apply (insert as, simp)\n      done\n\n    have s_next_max_1: \"Max S < next'\"\n      apply (simp add: s_next)\n      thm inext_mono2[of \"Max S\" I]\n      apply (rule inext_mono2[of \"Max S\" I])\n      apply (rule s_Max_i)\n      apply (rule_tac x=\"Max I\" in bexI)\n      apply (rule as)\n      apply (simp add: as_finite_i i_not_empty)\n      done\n    hence next_not_in_s: \"next' \\<notin> S\"\n      using S_finite S_not_empty\n      apply clarify\n      thm Max_ge[of S next']\n      apply (drule Max_ge[of _ next'])\n      apply simp_all\n      done\n    have \"\\<exists>n. I \\<leftarrow> n = next'\"\n      by (insert next_not_in_s s_not_ex[of next'] s_next_in, blast)\n    then obtain nNext where s_nNext: \"I \\<leftarrow> nNext = next'\" by blast\n    hence \"I \\<leftarrow> (Suc nNext) = iprev next' I\" by simp\n    hence \"I \\<leftarrow> (Suc nNext) = Max S\" \n      using s_next_prev_max by simp\n    hence \"\\<exists>n. I \\<leftarrow> n = Max S\" by blast\n    hence \"Max S \\<notin> S\"\n      using s_Max_i s_S by blast\n    thus False\n      using s_Max_S by blast+\n  next\n    assume as:\"\\<not>(Max S < Max I)\"\n\n    have \"Max S = Max I\"\n      apply (insert s_subset S_not_empty as_finite_i as)\n      thm Max_subset[of S I]\n      apply (drule Max_subset[of _ I])\n      by simp_all\n    hence \"\\<exists>n. I \\<leftarrow> n \\<in> S\"\n      apply (rule_tac x=0 in exI)\n      apply (insert s_Max_S)\n      apply simp\n      done\n    thus False\n      using s_S by blast\n  qed\nqed\n\nterm iprev_nth\nterm \"\\<lambda>n. iprev_nth I n\"\nlemma iprev_nth_surj_on: \"finite I \\<Longrightarrow> surj_on (\\<lambda>n. I \\<leftarrow> n) UNIV I\"\napply (simp add: surj_on_def)\nthm iprev_nth_surj_aux1[of I]\nby (insert iprev_nth_surj_aux1[of I], blast)\ncorollary in_imp_ex_iprev_nth: \"\n  \\<lbrakk> finite I;  x \\<in> I \\<rbrakk> \\<Longrightarrow> \\<exists>n. x = I \\<leftarrow> n\"\nthm surj_onD\nthm surj_onD[of _ UNIV I, simplified]\napply (rule surj_onD[of _ UNIV I, simplified])\napply (rule iprev_nth_surj_on)\napply assumption+\ndone\n\nlemma iprev_induct: \"\n  \\<lbrakk> P (Max I); \\<And>n. \\<lbrakk> n \\<in> I; P n \\<rbrakk> \\<Longrightarrow> P (iprev n I); finite I; n \\<in> I \\<rbrakk> \\<Longrightarrow> P n\"\nthm image_nat_induct\nthm image_nat_induct[where P=P and f=\"\\<lambda>n. I \\<leftarrow> n\" and I=I and a=n]\napply (rule_tac f=\"\\<lambda>n. I \\<leftarrow> n\" and I=I in image_nat_induct)\nthm iprev_nth_closed[OF _ in_imp_not_empty]\napply (simp add: iprev_nth_closed[OF _ in_imp_not_empty] iprev_nth_surj_on)+\ndone\nthm \n  inext_induct\n  iprev_induct\n\n\n\n\n\nsubsection {* Natural intervals with @{text inext} and @{text iprev} *}\n\nlemma inext_atLeast: \"n \\<le> t \\<Longrightarrow> inext t {n..} = Suc t\"\napply (unfold inext_def)\napply (subgoal_tac \"Suc t \\<in> {n..} \\<down>> t\")\n prefer 2\n apply (simp add: cut_greater_mem_iff)\napply (simp add: in_imp_not_empty)\napply (rule iMin_equality, assumption)\napply (simp add: cut_greater_mem_iff)\ndone\n\nlemma iprev_atLeast': \"n \\<le> t \\<Longrightarrow> iprev (Suc t) {n..} = t\"\napply (rule subst[OF inext_atLeast], assumption)\napply (rule iprev_inext_infin[OF infinite_atLeast])\ndone\nlemma iprev_atLeast: \"n < t  \\<Longrightarrow> iprev t {n..} = t - Suc 0\"\nby (insert iprev_atLeast'[of n \"t - Suc 0\"], simp)\n\nlemma inext_atMost: \"t < n \\<Longrightarrow> inext t {..n} = Suc t\"\napply (unfold inext_def)\napply (subgoal_tac \"Suc t \\<in> {..n} \\<down>> t\")\n prefer 2\n apply (simp add: cut_greater_mem_iff)\napply (simp add: in_imp_not_empty)\napply (rule iMin_equality, assumption)\napply (simp add: cut_greater_mem_iff)\ndone\nlemma iprev_atMost: \"t \\<le> n \\<Longrightarrow> iprev t {..n} = t - Suc 0\"\napply (case_tac t)\n apply simp\n thm subst[OF iMin_atMost[of n]]\n apply (rule subst[OF iMin_atMost[of n]])\n apply (rule iprev_iMin)\napply simp\napply (drule Suc_le_lessD)\napply (rule subst[OF inext_atMost], assumption)\napply (simp add: Max_atMost iprev_inext_fin)\ndone\n\nlemma inext_lessThan: \"Suc t < n \\<Longrightarrow> inext t {..<n} = Suc t\"\napply (rule subst[OF Suc_pred, of n], simp)\napply (subst lessThan_Suc_atMost)\napply (simp add: inext_atMost)\ndone\nlemma iprev_lessThan: \"t < n \\<Longrightarrow> iprev t {..<n} = t - Suc 0\"\napply (case_tac n, simp)\napply (simp add: lessThan_Suc_atMost iprev_atMost)\ndone\n\nlemma inext_atLeastAtMost: \"\\<lbrakk> m \\<le> t; t < n \\<rbrakk> \\<Longrightarrow> inext t {m..n} = Suc t\"\nby (simp add: atLeastAtMost_def cut_le_Int_conv[symmetric] inext_atLeast inext_cut_le_conv)\nlemma iprev_atLeastAtMost: \"\\<lbrakk> m < t; t \\<le> n \\<rbrakk> \\<Longrightarrow> iprev t {m..n} = t - Suc 0\"\nby (simp add: atLeastAtMost_def cut_le_Int_conv[symmetric] iprev_atLeast iprev_cut_le_conv)\nlemma iprev_atLeastAtMost': \"\\<lbrakk> m \\<le> t; t < n \\<rbrakk> \\<Longrightarrow> iprev (Suc t) {m..n} = t\"\nby (simp add: iprev_atLeastAtMost[of _ \"Suc t\"])\n\nlemma inext_nth_atLeast : \"{n..} \\<rightarrow> a = n + a\"\napply (induct a, simp add: iMin_atLeast)\napply (simp add: inext_atLeast)\ndone\n\n\nlemma inext_nth_lessThan : \"a < n \\<Longrightarrow> {..<n} \\<rightarrow> a = a\"\napply (case_tac n, simp)\napply (simp add: lessThan_Suc_atMost inext_nth_atMost)\ndone\nlemma iprev_nth_lessThan: \"a < n \\<Longrightarrow> {..<n} \\<leftarrow> a = n - Suc a\"\napply (case_tac n, simp)\napply (simp add: lessThan_Suc_atMost iprev_nth_atMost)\ndone\n\nlemma inext_nth_UNIV: \"UNIV \\<rightarrow> a = a\"\nby (simp add: inext_nth_atLeast del: atLeast_0 add: atLeast_0[symmetric])\n\n\n\nsubsection {* Further result for @{text inext_nth} and @{text iprev_nth} *}\n\nthm inext_iprev\nlemma inext_iprev_nth_Suc: \"\n  iMin I \\<noteq> I \\<leftarrow> n \\<Longrightarrow> inext (I \\<leftarrow> Suc n) I = I \\<leftarrow> n\"\nby (simp add: inext_iprev)\nlemma inext_iprev_nth_pred: \"\n  \\<lbrakk> finite I; iMin I \\<noteq> I \\<leftarrow> (n - Suc 0) \\<rbrakk> \\<Longrightarrow>\n  inext (I \\<leftarrow> n) I = I \\<leftarrow> (n - Suc 0)\"\napply (case_tac n)\n apply (simp add: inext_Max)\napply (simp add: inext_iprev)\ndone\n\nlemma iprev_inext_nth_Suc: \"\n  I \\<rightarrow> n \\<noteq> Max I \\<or> infinite I \\<Longrightarrow> iprev (I \\<rightarrow> Suc n) I = I \\<rightarrow> n\"\nby (simp add: iprev_inext)\nlemma iprev_inext_nth_pred: \"\n  I \\<rightarrow> (n - Suc 0) \\<noteq> Max I \\<or> infinite I \\<Longrightarrow> \n  iprev (I \\<rightarrow> n) I = I \\<rightarrow> (n - Suc 0)\"\napply (case_tac n)\n apply (simp add: iprev_iMin)\napply (simp add: iprev_inext)\ndone\n\nthm inext_imirror_iprev_conv\nlemma inext_nth_imirror_iprev_nth_conv: \"\n  \\<lbrakk> finite I; I \\<noteq> {} \\<rbrakk> \\<Longrightarrow> \n  (imirror I) \\<rightarrow> n = mirror_elem (I \\<leftarrow> n) I\"\napply (induct n)\n apply (simp add: imirror_iMin mirror_elem_Max)\napply (simp add: inext_imirror_iprev_conv' iprev_nth_closed)\ndone\ncorollary inext_nth_imirror_iprev_nth_conv2: \"\n  \\<lbrakk> finite I; I \\<noteq> {} \\<rbrakk> \\<Longrightarrow> \n  mirror_elem ((imirror I) \\<leftarrow> n) I = I \\<rightarrow> n\"\nthm inext_nth_imirror_iprev_nth_conv[OF imirror_finite imirror_not_empty]\napply (frule inext_nth_imirror_iprev_nth_conv[OF imirror_finite imirror_not_empty, of _ n], assumption)\napply (simp add: imirror_imirror_ident mirror_elem_imirror)\ndone\n\n \n\n\nlemma iprev_nth_imirror_inext_nth_conv: \"\n  \\<lbrakk> finite I; I \\<noteq> {} \\<rbrakk> \\<Longrightarrow> \n  (imirror I) \\<leftarrow> n = mirror_elem (I \\<rightarrow> n) I\"\napply (induct n)\n apply (simp add: imirror_Max mirror_elem_Min)\napply (simp add: iprev_imirror_inext_conv' inext_nth_closed)\ndone\ncorollary iprev_nth_imirror_inext_nth_conv2: \"\n  \\<lbrakk> finite I; I \\<noteq> {} \\<rbrakk> \\<Longrightarrow> \n  mirror_elem ((imirror I) \\<rightarrow> n) I = (I \\<leftarrow> n)\"\nthm iprev_nth_imirror_inext_nth_conv[OF imirror_finite imirror_not_empty]\napply (frule iprev_nth_imirror_inext_nth_conv[OF imirror_finite imirror_not_empty, of _ n], assumption)\napply (simp add: imirror_imirror_ident mirror_elem_imirror)\ndone\n\n\n\n\nthm inext_nth_card_less_Max\nlemma iprev_nth_card_greater_iMin: \"Suc n < card I \\<Longrightarrow> iMin I < I \\<leftarrow> n\"\napply (subgoal_tac \"I \\<noteq> {}\" \"finite I\")\n prefer 2\n apply (rule card_gr0_imp_finite, simp)\n prefer 2\n apply (rule card_gr0_imp_not_empty, simp)\nthm subst[OF iprev_nth_imirror_inext_nth_conv2]\napply (subst iprev_nth_imirror_inext_nth_conv2[symmetric], assumption+)\nthm subst[OF mirror_elem_Max]\napply (subst mirror_elem_Max[symmetric], assumption+)\nthm subst[OF mirror_elem_imirror, of I]\napply (subst mirror_elem_imirror[symmetric], assumption)\napply (subst mirror_elem_imirror[symmetric], assumption)\napply (frule imirror_finite, frule imirror_not_empty)\nthm mirror_elem_less_conv\napply (rule mirror_elem_less_conv[THEN iffD2])\n apply assumption\n apply (rule inext_nth_closed, assumption)\n apply (rule subst[OF imirror_Max], assumption)\n apply (rule Max_in, assumption+)\napply (rule subst[OF imirror_Max], assumption)\nthm inext_nth_card_less_Max\napply (simp add: inext_nth_card_less_Max imirror_card)\ndone\n\nlemma iprev_nth_card_iMin: \"\n  \\<lbrakk> finite I; I \\<noteq> {}; card I \\<le> Suc n \\<rbrakk> \\<Longrightarrow> I \\<leftarrow> n = iMin I\"\nthm subst[OF iprev_nth_imirror_inext_nth_conv2]\napply (subst iprev_nth_imirror_inext_nth_conv2[symmetric], assumption+)\nthm subst[OF mirror_elem_Max]\napply (subst mirror_elem_Max[symmetric], assumption+)\nthm subst[OF mirror_elem_imirror, of I]\napply (subst mirror_elem_imirror[symmetric], assumption)\napply (subst mirror_elem_imirror[symmetric], assumption)\nthm subst[OF imirror_Max]\napply (rule subst[OF imirror_Max], assumption)\napply (frule imirror_finite, frule imirror_not_empty)\nthm mirror_elem_eq_conv'\napply (simp add: mirror_elem_eq_conv' inext_nth_closed inext_nth_card_Max imirror_card)\ndone\nlemma iprev_nth_card_iMin': \"\n  \\<lbrakk> finite I; I \\<noteq> {}; card I - Suc 0 \\<le> n \\<rbrakk> \\<Longrightarrow> I \\<leftarrow> n = iMin I\"\nby (simp add: iprev_nth_card_iMin)\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/SetIntervalStep.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256472515683, "lm_q2_score": 0.8499711718571774, "lm_q1q2_score": 0.7155275318938423}}
{"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.*)\n  theory TIP_prop_02\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 length :: \"'a list => Nat\" where\n  \"length (nil2) = Z\"\n| \"length (cons2 z xs) = S (length xs)\"\n\n(*nested induction with generalization*)\ntheorem property0 :\n  \"((length (x y z)) = (length (x z y)))\"\n  (*why \"induct y\" rather than \"induct z\"?*)\n  apply(induct y)\n   apply auto[1]\n   apply(induct z)\n    apply fastforce+\n    (*clarsimp can rewrite \"length (x (cons2 x1 y) z)\" to \"S (length (x z y))\"\n      because \"x\" is defined recursively on the first argument.*)\n  apply(subst x.simps)\n  apply(subst length.simps)\n  apply clarsimp(*This clarsimp uses induction hypothesis.*)\n  apply(rule meta_allI)(*because we cannot use the arbitrary keyword with induct_tac*)\n  back\n  back\n  back\n  back\n  apply (induct_tac z rule: TIP_prop_02.length.induct)(*z is optional*)\n   apply auto\n  done\n\ntheorem property0_again :\n  \"((length (x y z)) = (length (x z y)))\"\n  (*why \"induct y\" rather than \"induct z\"?\n    \\<rightarrow> Because \"induct z\" leads to the following step case:\n    \"TIP_prop_02.length (x y (cons2 x1 z)) = TIP_prop_02.length (x (cons2 x1 z) y)\".\n    Here we have different terms for the first argument of \"x\". *)\n  apply(induct z arbitrary:)\n   apply clarsimp\n   apply(induct y arbitrary:)\n    apply fastforce+\n    (* This clarsimp does not rewrite \"(x y (cons2 x1 z))\"\n       because \"x\" is defined recursively on the first argument.\n       We can detect this problem just after applying \"induct z\".\n       So, we cannot induct on the first argument of the innermost recursively defined function, \"x\".*)\n  apply(subst x.simps)\n  apply(subst length.simps)\n  apply(drule HOL.sym)\n  apply simp\n  apply(rule meta_allI)(*because we cannot use the arbitrary keyword with induct_tac*)\n  back\n  back\n  back\n  back\n  apply (induct_tac y rule: TIP_prop_02.length.induct)(*y is optional*)\n  apply auto\n  done\n\nlemma aux_1_0:\n  \"S (TIP_prop_02.length (x z a)) = TIP_prop_02.length (x z (cons2 x1 a))\"\n  apply(induct z rule: TIP_prop_02.length.induct)\n   apply clarsimp\n  apply clarsimp\n  done\n\nlemma aux_1:\n  \"TIP_prop_02.length (x y z) = TIP_prop_02.length (x z y) \\<Longrightarrow> \n   S (TIP_prop_02.length (x z y)) = TIP_prop_02.length (x z (cons2 x1 y))\"\n  apply(induct z)\n   apply clarsimp\n  apply clarsimp\n  apply(rule aux_1_0)\n  done\n\nlemma aux_0:\n  \"TIP_prop_02.length z = TIP_prop_02.length (x z nil2)\"\n  apply(induct z)\n   apply auto\n  done\n\ntheorem property :\n  \"((length (x y z)) = (length (x z y)))\"\n  apply(induct y)\n   apply clarsimp\n   apply(rule aux_0)(*just a nested induction*)\n  apply clarsimp\n  apply(rule aux_1)(*just a nested induction*)\n  apply assumption\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_02.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256393148981, "lm_q2_score": 0.8499711794579722, "lm_q1q2_score": 0.7155275315464454}}
{"text": "theory Clique_Large_Monotone_Circuits\n  imports \n  Sunflowers.Erdos_Rado_Sunflower\n  Preliminaries\n  Assumptions_and_Approximations\n  Monotone_Formula\nbegin\n\ntext \\<open>disable list-syntax\\<close>\nno_syntax \"_list\" :: \"args \\<Rightarrow> 'a list\" (\"[(_)]\")\nno_syntax \"__listcompr\" :: \"args \\<Rightarrow> 'a list\" (\"[(_)]\")\n\nhide_const (open) Sigma_Algebra.measure\n\nsubsection \\<open>Plain Graphs\\<close>\n\ndefinition binprod :: \"'a set \\<Rightarrow> 'a set \\<Rightarrow> 'a set set\" (infixl \"\\<cdot>\" 60) where\n  \"X \\<cdot> Y = {{x,y} | x y. x \\<in> X \\<and> y \\<in> Y \\<and> x \\<noteq> y}\"\n\nabbreviation sameprod :: \"'a set \\<Rightarrow> 'a set set\" (\"(_)^\\<two>\") where\n  \"X^\\<two> \\<equiv> X \\<cdot> X\" \n\nlemma sameprod_altdef: \"X^\\<two> = {Y. Y \\<subseteq> X \\<and> card Y = 2}\" \n  unfolding binprod_def by (auto simp: card_2_iff)\n\ndefinition numbers :: \"nat \\<Rightarrow> nat set\" (\"[(_)]\") where\n  \"[n] \\<equiv> {..<n}\" \n\nlemma card_sameprod: \"finite X \\<Longrightarrow> card (X^\\<two>) = card X choose 2\" \n  unfolding sameprod_altdef\n  by (subst n_subsets, auto)\n\nlemma sameprod_mono: \"X \\<subseteq> Y \\<Longrightarrow> X^\\<two> \\<subseteq> Y^\\<two>\"\n  unfolding sameprod_altdef by auto\n\nlemma sameprod_finite: \"finite X \\<Longrightarrow> finite (X^\\<two>)\" \n  unfolding sameprod_altdef by simp\n\nlemma numbers2_mono: \"x \\<le> y \\<Longrightarrow> [x]^\\<two> \\<subseteq> [y]^\\<two>\"\n  by (rule sameprod_mono, auto simp: numbers_def)\n\nlemma card_numbers[simp]: \"card [n] = n\" \n  by (simp add: numbers_def)\n\nlemma card_numbers2[simp]: \"card ([n]^\\<two>) = n choose 2\" \n  by (subst card_sameprod, auto simp: numbers_def)\n\n\ntype_synonym vertex = nat\ntype_synonym graph = \"vertex set set\" \n\ndefinition Graphs :: \"vertex set \\<Rightarrow> graph set\" where\n  \"Graphs V = { G. G \\<subseteq> V^\\<two> }\"  \n\ndefinition Clique :: \"vertex set \\<Rightarrow> nat \\<Rightarrow> graph set\" where\n  \"Clique V k = { G. G \\<in> Graphs V \\<and> (\\<exists> C \\<subseteq> V. C^\\<two> \\<subseteq> G \\<and> card C = k) }\" \n\ncontext first_assumptions\nbegin\n\nabbreviation \\<G> where \"\\<G> \\<equiv> Graphs [m]\" \n\nlemmas \\<G>_def = Graphs_def[of \"[m]\"]\n\nlemma empty_\\<G>[simp]: \"{} \\<in> \\<G>\" unfolding \\<G>_def by auto\n\ndefinition v :: \"graph \\<Rightarrow> vertex set\" where\n \"v G = { x . \\<exists> y. {x,y} \\<in> G}\" \n\nlemma v_union: \"v (G \\<union> H) = v G \\<union> v H\" \n  unfolding v_def by auto\n\ndefinition \\<K> :: \"graph set\" where\n  \"\\<K> = { K . K \\<in> \\<G> \\<and> card (v K) = k \\<and> K = (v K)^\\<two> }\" \n\nlemma v_\\<G>: \"G \\<in> \\<G> \\<Longrightarrow> v G \\<subseteq> [m]\" \n  unfolding v_def \\<G>_def sameprod_altdef by auto\n\nlemma v_mono: \"G \\<subseteq> H \\<Longrightarrow> v G \\<subseteq> v H\" unfolding v_def by auto\n\nlemma v_sameprod[simp]: assumes \"card X \\<ge> 2\" \n  shows \"v (X^\\<two>) = X\" \nproof -\n  from obtain_subset_with_card_n[OF assms] obtain Y where \"Y \\<subseteq> X\" \n    and Y: \"card Y = 2\" by auto\n  then obtain x y where \"x \\<in> X\" \"y \\<in> X\" and \"x \\<noteq> y\"\n    by (auto simp: card_2_iff)\n  thus ?thesis unfolding sameprod_altdef v_def\n    by (auto simp: card_2_iff doubleton_eq_iff) blast\nqed\n\nlemma v_mem_sub: assumes \"card e = 2\" \"e \\<in> G\" shows \"e \\<subseteq> v G\" \nproof -\n  obtain x y where e: \"e = {x,y}\" and xy: \"x \\<noteq> y\" using assms\n    by (auto simp: card_2_iff)\n  from assms(2) have x: \"x \\<in> v G\" unfolding e\n    by (auto simp: v_def)\n  from e have e: \"e = {y,x}\" unfolding e by auto\n  from assms(2) have y: \"y \\<in> v G\" unfolding e\n    by (auto simp: v_def)\n  show \"e \\<subseteq> v G\" using x y unfolding e by auto\nqed\n\nlemma v_\\<G>_2: assumes \"G \\<in> \\<G>\" shows \"G \\<subseteq> (v G)^\\<two>\" \nproof\n  fix e\n  assume eG: \"e \\<in> G\" \n  with assms[unfolded \\<G>_def binprod_def] obtain x y where e: \"e = {x,y}\" and xy: \"x \\<noteq> y\" by auto\n  from eG e xy have x: \"x \\<in> v G\" by (auto simp: v_def)\n  from e have e: \"e = {y,x}\" unfolding e by auto\n  from eG e xy have y: \"y \\<in> v G\" by (auto simp: v_def)\n  from x y xy show \"e \\<in> (v G)^\\<two>\" unfolding binprod_def e by auto\nqed\n\n  \nlemma v_numbers2[simp]: \"x \\<ge> 2 \\<Longrightarrow> v ([x]^\\<two>) = [x]\" \n  by (rule v_sameprod, auto)\n\nlemma sameprod_\\<G>: assumes \"X \\<subseteq> [m]\" \"card X \\<ge> 2\" \n  shows \"X^\\<two> \\<in> \\<G>\" \n  unfolding \\<G>_def using assms(2) sameprod_mono[OF assms(1)] \n  by auto\n\nlemma finite_numbers[simp,intro]: \"finite [n]\" \n  unfolding numbers_def by auto\n\nlemma finite_numbers2[simp,intro]: \"finite ([n]^\\<two>)\" \n  unfolding sameprod_altdef using finite_subset[of _ \"[m]\"] by auto\n\nlemma finite_members_\\<G>: \"G \\<in> \\<G> \\<Longrightarrow> finite G\"\n  unfolding \\<G>_def using finite_subset[of G \"[m]^\\<two>\"] by auto\n\nlemma finite_\\<G>[simp,intro]: \"finite \\<G>\" \n  unfolding \\<G>_def by simp\n\nlemma finite_vG: assumes \"G \\<in> \\<G>\"\n  shows \"finite (v G)\"\nproof -\n  from finite_members_\\<G>[OF assms]\n  show ?thesis \n  proof (induct rule: finite_induct)\n    case (insert xy F)\n    show ?case\n    proof (cases \"\\<exists> x y. xy = {x,y}\")\n      case False\n      hence \"v (insert xy F) = v F\" unfolding v_def by auto\n      thus ?thesis using insert by auto\n    next\n      case True\n      then obtain x y where xy: \"xy = {x,y}\" by auto\n      hence \"v (insert xy F) = insert x (insert y (v F))\" \n        unfolding v_def by auto\n      thus ?thesis using insert by auto\n    qed\n  qed (auto simp: v_def)\nqed\n\nlemma v_empty[simp]: \"v {} = {}\" unfolding v_def by auto\n\nlemma v_card2: assumes \"G \\<in> \\<G>\" \"G \\<noteq> {}\" \n  shows \"2 \\<le> card (v G)\" \nproof -\n  from assms[unfolded \\<G>_def] obtain edge where *: \"edge \\<in> G\" \"edge \\<in> [m]^\\<two>\" by auto\n  then obtain x y where edge: \"edge = {x,y}\" \"x \\<noteq> y\" unfolding binprod_def by auto\n  with * have sub: \"{x,y} \\<subseteq> v G\" unfolding v_def\n    by (smt (verit, best) insert_commute insert_compr mem_Collect_eq singleton_iff subsetI)\n  from assms finite_vG have \"finite (v G)\" by auto\n  from sub \\<open>x \\<noteq> y\\<close> this show \"2 \\<le> card (v G)\"\n    by (metis card_2_iff card_mono)\nqed\n\n\nlemma \\<K>_altdef: \"\\<K> = {V^\\<two> | V. V \\<subseteq> [m] \\<and> card V = k}\" \n  (is \"_ = ?R\")\nproof -\n  {\n    fix K \n    assume \"K \\<in> \\<K>\"\n    hence K: \"K \\<in> \\<G>\" and card: \"card (v K) = k\" and KvK: \"K = (v K)^\\<two>\" \n      unfolding \\<K>_def by auto\n    from v_\\<G>[OF K] card KvK have \"K \\<in> ?R\" by auto\n  }\n  moreover\n  {\n    fix V\n    assume 1: \"V \\<subseteq> [m]\" and \"card V = k\" \n    hence \"V^\\<two> \\<in> \\<K>\" unfolding \\<K>_def using k2 sameprod_\\<G>[OF 1]\n      by auto\n  }\n  ultimately show ?thesis by auto\nqed\n    \nlemma \\<K>_\\<G>: \"\\<K> \\<subseteq> \\<G>\" \n  unfolding \\<K>_def by auto\n  \ndefinition CLIQUE :: \"graph set\" where\n  \"CLIQUE = { G. G \\<in> \\<G> \\<and> (\\<exists> K \\<in> \\<K>. K \\<subseteq> G) }\" \n\nlemma empty_CLIQUE[simp]: \"{} \\<notin> CLIQUE\" unfolding CLIQUE_def \\<K>_def using k2 by (auto simp: v_def)\n\nsubsection \\<open>Test Graphs\\<close>\n\ntext \\<open>Positive test graphs are precisely the cliques of size @{term k}.\\<close>\n\nabbreviation \"POS \\<equiv> \\<K>\"\n\nlemma POS_\\<G>: \"POS \\<subseteq> \\<G>\" by (rule \\<K>_\\<G>)\n\ntext \\<open>Negative tests are coloring-functions of vertices that encode graphs\n  which have cliques of size at most @{term \"k - 1\"}.\\<close>\n\ntype_synonym colorf = \"vertex \\<Rightarrow> nat\" \n\ndefinition \\<F> :: \"colorf set\" where\n  \"\\<F> = [m] \\<rightarrow>\\<^sub>E [k - 1]\" \n\nlemma finite_\\<F>: \"finite \\<F>\"\n  unfolding \\<F>_def numbers_def\n  by (meson finite_PiE finite_lessThan)\n\ndefinition C :: \"colorf \\<Rightarrow> graph\" where\n  \"C f = { {x, y} | x y . {x,y} \\<in> [m]^\\<two> \\<and> f x \\<noteq> f y}\" \n\ndefinition NEG :: \"graph set\" where\n  \"NEG = C ` \\<F>\"\n\nparagraph \\<open>Lemma 1\\<close>\n\nlemma CLIQUE_NEG: \"CLIQUE \\<inter> NEG = {}\" \nproof -\n  {\n    fix G\n    assume GC: \"G \\<in> CLIQUE\" and GN: \"G \\<in> NEG\" \n    from GC[unfolded CLIQUE_def] obtain K where \n      K: \"K \\<in> \\<K>\" and G: \"G \\<in> \\<G>\" and KsubG: \"K \\<subseteq> G\" by auto\n    from GN[unfolded NEG_def] obtain f where fF: \"f \\<in> \\<F>\" and \n      GCf: \"G = C f\" by auto\n    from K[unfolded \\<K>_def] have KG: \"K \\<in> \\<G>\" and \n      KvK: \"K = v K^\\<two>\" and card1: \"card (v K) = k\" by auto\n    from k2 card1 have ineq: \"card (v K) > card [k - 1]\" by auto\n    from v_\\<G>[OF KG] have vKm: \"v K \\<subseteq> [m]\" by auto\n    from fF[unfolded \\<F>_def] vKm have f: \"f \\<in> v K \\<rightarrow> [k - 1]\"  \n      by auto\n    from card_inj[OF f] ineq \n    have \"\\<not> inj_on f (v K)\" by auto\n    then obtain x y where *: \"x \\<in> v K\" \"y \\<in> v K\" \"x \\<noteq> y\" and ineq: \"f x = f y\" \n      unfolding inj_on_def by auto\n    have \"{x,y} \\<notin> G\" unfolding GCf C_def using ineq\n      by (auto simp: doubleton_eq_iff)\n    with KsubG KvK have \"{x,y} \\<notin> v K^\\<two>\" by auto\n    with * have False unfolding binprod_def by auto\n  }\n  thus ?thesis by auto\nqed\n\nlemma NEG_\\<G>: \"NEG \\<subseteq> \\<G>\" \nproof -\n  {\n    fix f\n    assume \"f \\<in> \\<F>\" \n    hence \"C f \\<in> \\<G>\" \n      unfolding NEG_def C_def \\<G>_def \n      by (auto simp: sameprod_altdef)\n  }\n  thus \"NEG \\<subseteq> \\<G>\" unfolding NEG_def by auto\nqed\n\nlemma finite_POS_NEG: \"finite (POS \\<union> NEG)\" \n  using POS_\\<G> NEG_\\<G> \n  by (intro finite_subset[OF _ finite_\\<G>], auto)\n\nlemma POS_sub_CLIQUE: \"POS \\<subseteq> CLIQUE\" \n  unfolding CLIQUE_def using \\<K>_\\<G> by auto\n\nlemma POS_CLIQUE: \"POS \\<subset> CLIQUE\" \nproof -\n  have \"[k+1]^\\<two> \\<in> CLIQUE\" \n    unfolding CLIQUE_def\n  proof (standard, intro conjI bexI[of _ \"[k]^\\<two>\"])\n    show \"[k]^\\<two> \\<subseteq> [k+1]^\\<two>\" \n      by (rule numbers2_mono, auto)\n    show \"[k]^\\<two> \\<in> \\<K>\" unfolding \\<K>_altdef using km \n      by (auto intro!: exI[of _ \"[k]\"], auto simp: numbers_def)\n    show \"[k+1]^\\<two> \\<in> \\<G>\" using km k2\n      by (intro sameprod_\\<G>, auto simp: numbers_def)\n  qed\n  moreover have \"[k+1]^\\<two> \\<notin> POS\" unfolding \\<K>_def using v_numbers2[of \"k + 1\"] k2 \n    by auto\n  ultimately show ?thesis using POS_sub_CLIQUE by blast\nqed\n\nlemma card_POS: \"card POS = m choose k\" \nproof -\n  have \"m choose k =\n    card {B. B \\<subseteq> [m] \\<and> card B = k}\" (is \"_ = card ?A\")\n    by (subst n_subsets[of \"[m]\" k], auto simp: numbers_def) \n  also have \"\\<dots> = card (sameprod ` ?A)\" \n  proof (rule card_image[symmetric])\n    { \n      fix A\n      assume \"A \\<in> ?A\" \n      hence \"v (sameprod A) = A\" using k2\n        by (subst v_sameprod, auto)\n    }\n    thus \"inj_on sameprod ?A\" by (rule inj_on_inverseI)\n  qed\n  also have \"sameprod ` {B. B \\<subseteq> [m] \\<and> card B = k} = POS\" \n    unfolding \\<K>_altdef by auto\n  finally show ?thesis by simp\nqed\n\nsubsection \\<open>Basic operations on sets of graphs\\<close>\n\ndefinition odot :: \"graph set \\<Rightarrow> graph set \\<Rightarrow> graph set\" (infixl \"\\<odot>\" 65) where \n  \"X \\<odot> Y = { D \\<union> E | D E. D \\<in> X \\<and> E \\<in> Y}\" \n\nlemma union_\\<G>[intro]: \"G \\<in> \\<G> \\<Longrightarrow> H \\<in> \\<G> \\<Longrightarrow> G \\<union> H \\<in> \\<G>\" \n  unfolding \\<G>_def by auto\n\nlemma odot_\\<G>: \"X \\<subseteq> \\<G> \\<Longrightarrow> Y \\<subseteq> \\<G> \\<Longrightarrow> X \\<odot> Y \\<subseteq> \\<G>\" \n  unfolding odot_def by auto\n\nsubsection \\<open>Acceptability\\<close>\n\ntext \\<open>Definition 2\\<close>\n\ndefinition accepts :: \"graph set \\<Rightarrow> graph \\<Rightarrow> bool\" (infixl \"\\<tturnstile>\" 55) where\n  \"(X \\<tturnstile> G) = (\\<exists> D \\<in> X. D \\<subseteq> G)\" \n\n\nlemma acceptsI[intro]: \"D \\<subseteq> G \\<Longrightarrow> D \\<in> X \\<Longrightarrow> X \\<tturnstile> G\" \n  unfolding accepts_def by auto\n\ndefinition ACC :: \"graph set \\<Rightarrow> graph set\" where\n  \"ACC X = { G. G \\<in> \\<G> \\<and> X \\<tturnstile> G}\" \n\ndefinition ACC_cf :: \"graph set \\<Rightarrow> colorf set\" where\n  \"ACC_cf X = { F. F \\<in> \\<F> \\<and> X \\<tturnstile> C F}\" \n\nlemma ACC_cf_\\<F>: \"ACC_cf X \\<subseteq> \\<F>\" \n  unfolding ACC_cf_def by auto\n\nlemma finite_ACC[intro,simp]: \"finite (ACC_cf X)\" \n  by (rule finite_subset[OF ACC_cf_\\<F> finite_\\<F>])\n\nlemma ACC_I[intro]: \"G \\<in> \\<G> \\<Longrightarrow> X \\<tturnstile> G \\<Longrightarrow> G \\<in> ACC X\" \n  unfolding ACC_def by auto\n\nlemma ACC_cf_I[intro]: \"F \\<in> \\<F> \\<Longrightarrow> X \\<tturnstile> C F \\<Longrightarrow> F \\<in> ACC_cf X\" \n  unfolding ACC_cf_def by auto\n\nlemma ACC_cf_mono: \"X \\<subseteq> Y \\<Longrightarrow> ACC_cf X \\<subseteq> ACC_cf Y\"\n  unfolding ACC_cf_def accepts_def by auto\n\ntext \\<open>Lemma 3\\<close>\n\nlemma ACC_cf_empty: \"ACC_cf {} = {}\" \n  unfolding ACC_cf_def accepts_def by auto\n\nlemma ACC_empty[simp]: \"ACC {} = {}\" \n  unfolding ACC_def accepts_def by auto\n\nlemma ACC_cf_union: \"ACC_cf (X \\<union> Y) = ACC_cf X \\<union> ACC_cf Y\" \n  unfolding ACC_cf_def accepts_def by blast\n\nlemma ACC_union: \"ACC (X \\<union> Y) = ACC X \\<union> ACC Y\" \n  unfolding ACC_def accepts_def by blast\n\nlemma ACC_odot: \"ACC (X \\<odot> Y) = ACC X \\<inter> ACC Y\"\nproof -\n  {\n    fix G\n    assume \"G \\<in> ACC (X \\<odot> Y)\" \n    from this[unfolded ACC_def accepts_def]\n    obtain D E F :: graph where *: \"D \\<in> X\" \"E \\<in> Y\" \"G \\<in> \\<G>\" \"D \\<union> E \\<subseteq> G\"       \n      by (force simp: odot_def)\n    hence \"G \\<in> ACC X \\<inter> ACC Y\" \n      unfolding ACC_def accepts_def by auto\n  }\n  moreover\n  {\n    fix G\n    assume \"G \\<in> ACC X \\<inter> ACC Y\" \n    from this[unfolded ACC_def accepts_def]\n    obtain D E where *: \"D \\<in> X\" \"E \\<in> Y\" \"G \\<in> \\<G>\" \"D \\<subseteq> G\" \"E \\<subseteq> G\" \n      by auto\n    let ?F = \"D \\<union> E\" \n    from * have \"?F \\<in> X \\<odot> Y\" unfolding odot_def using * by blast\n    moreover have \"?F \\<subseteq> G\" using * by auto\n    ultimately have \"G \\<in> ACC (X \\<odot> Y)\" using *\n      unfolding ACC_def accepts_def by blast\n  }\n  ultimately show ?thesis by blast\nqed\n\nlemma ACC_cf_odot: \"ACC_cf (X \\<odot> Y) = ACC_cf X \\<inter> ACC_cf Y\"\nproof -\n  {\n    fix G\n    assume \"G \\<in> ACC_cf (X \\<odot> Y)\" \n    from this[unfolded ACC_cf_def accepts_def]\n    obtain D E :: graph where *: \"D \\<in> X\" \"E \\<in> Y\" \"G \\<in> \\<F>\" \"D \\<union> E \\<subseteq> C G\"       \n      by (force simp: odot_def)\n    hence \"G \\<in> ACC_cf X \\<inter> ACC_cf Y\" \n      unfolding ACC_cf_def accepts_def by auto\n  }\n  moreover\n  {\n    fix F\n    assume \"F \\<in> ACC_cf X \\<inter> ACC_cf Y\" \n    from this[unfolded ACC_cf_def accepts_def]\n    obtain D E where *: \"D \\<in> X\" \"E \\<in> Y\" \"F \\<in> \\<F>\" \"D \\<subseteq> C F\" \"E \\<subseteq> C F\" \n      by auto\n    let ?F = \"D \\<union> E\" \n    from * have \"?F \\<in> X \\<odot> Y\" unfolding odot_def using * by blast\n    moreover have \"?F \\<subseteq> C F\" using * by auto\n    ultimately have \"F \\<in> ACC_cf (X \\<odot> Y)\" using *\n      unfolding ACC_cf_def accepts_def by blast \n  }\n  ultimately show ?thesis by blast\nqed\n\nsubsection \\<open>Approximations and deviations\\<close>\n\ndefinition \\<G>l :: \"graph set\" where \n  \"\\<G>l = { G. G \\<in> \\<G> \\<and> card (v G) \\<le> l }\" \n\ndefinition v_gs :: \"graph set \\<Rightarrow> vertex set set\" where\n  \"v_gs X = v ` X\" \n\nlemma v_gs_empty[simp]: \"v_gs {} = {}\" \n  unfolding v_gs_def by auto\n\nlemma v_gs_union: \"v_gs (X \\<union> Y) = v_gs X \\<union> v_gs Y\"\n  unfolding v_gs_def by auto\n\nlemma v_gs_mono: \"X \\<subseteq> Y \\<Longrightarrow> v_gs X \\<subseteq> v_gs Y\" \n  using v_gs_def by auto  \n\nlemma finite_v_gs: assumes \"X \\<subseteq> \\<G>\" \n  shows \"finite (v_gs X)\" \nproof -\n  have \"v_gs X \\<subseteq> v ` \\<G>\"\n    using assms unfolding v_gs_def by force\n  moreover have \"finite \\<G>\" using finite_\\<G> by auto\n  ultimately show ?thesis by (metis finite_surj)\nqed\n\nlemma finite_v_gs_Gl: assumes \"X \\<subseteq> \\<G>l\" \n  shows \"finite (v_gs X)\" \n  by (rule finite_v_gs, insert assms, auto simp: \\<G>l_def)\n\n\ndefinition \\<P>L\\<G>l :: \"graph set set\" where\n  \"\\<P>L\\<G>l = { X . X \\<subseteq> \\<G>l \\<and> card (v_gs X) \\<le> L}\"\n\ndefinition odotl :: \"graph set \\<Rightarrow> graph set \\<Rightarrow> graph set\" (infixl \"\\<odot>l\" 65) where\n  \"X \\<odot>l Y = (X \\<odot> Y) \\<inter> \\<G>l\" \n\n\nlemma joinl_join: \"X \\<odot>l Y \\<subseteq> X \\<odot> Y\" \n  unfolding odot_def odotl_def by blast\n\nlemma card_v_gs_join: assumes X: \"X \\<subseteq> \\<G>\" and Y: \"Y \\<subseteq> \\<G>\" \n  and Z: \"Z \\<subseteq> X \\<odot> Y\" \n  shows \"card (v_gs Z) \\<le> card (v_gs X) * card (v_gs Y)\" \nproof -\n  note fin = finite_v_gs[OF X] finite_v_gs[OF Y]\n  have \"card (v_gs Z) \\<le> card ((\\<lambda> (A, B). A \\<union> B) ` (v_gs X \\<times> v_gs Y))\" \n  proof (rule card_mono[OF finite_imageI])\n    show \"finite (v_gs X \\<times> v_gs Y)\" \n      using fin by auto\n    have \"v_gs Z \\<subseteq> v_gs (X \\<odot> Y)\" \n      using v_gs_mono[OF Z] .\n    also have \"\\<dots> \\<subseteq> (\\<lambda>(x, y). x \\<union> y) ` (v_gs X \\<times> v_gs Y)\" (is \"?L \\<subseteq> ?R\")\n      unfolding odot_def v_gs_def by (force split: if_splits simp: v_union)\n    finally show \"v_gs Z \\<subseteq> (\\<lambda>(x, y). x \\<union> y) ` (v_gs X \\<times> v_gs Y)\" .\n  qed\n  also have \"\\<dots> \\<le> card (v_gs X \\<times> v_gs Y)\" \n    by (rule card_image_le, insert fin, auto)\n  also have \"\\<dots> = card (v_gs X) * card (v_gs Y)\" \n    by (rule card_cartesian_product)\n  finally show ?thesis .\nqed\n\ntext \\<open>Definition 6 -- elementary plucking step\\<close>\n\ndefinition plucking_step :: \"graph set \\<Rightarrow> graph set\" where\n  \"plucking_step X = (let vXp = v_gs X;\n      S = (SOME S. S \\<subseteq> vXp \\<and> sunflower S \\<and> card S = p);\n      U = {E \\<in> X. v E \\<in> S};\n      Vs = \\<Inter> S;\n      Gs = Vs^\\<two>\n     in X - U \\<union> {Gs})\"\nend\n\ncontext second_assumptions\nbegin\n\ntext \\<open>Lemma 9 -- for elementary plucking step\\<close>\n\nlemma v_sameprod_subset: \"v (Vs^\\<two>) \\<subseteq> Vs\" unfolding binprod_def v_def\n  by (auto simp: doubleton_eq_iff)\n\nlemma plucking_step: assumes X: \"X \\<subseteq> \\<G>l\"\n  and L: \"card (v_gs X) > L\" \n  and Y: \"Y = plucking_step X\" \nshows \"card (v_gs Y) \\<le> card (v_gs X) - p + 1\" \n  \"Y \\<subseteq> \\<G>l\" \n  \"POS \\<inter> ACC X \\<subseteq> ACC Y\" \n  \"2 ^ p * card (ACC_cf Y - ACC_cf X) \\<le> (k - 1) ^ m\"\n  \"Y \\<noteq> {}\"\nproof -\n  let ?vXp = \"v_gs X\"\n  have sf_precond: \"\\<forall>A\\<in> ?vXp. finite A \\<and> card A \\<le> l\" \n    using X unfolding \\<G>l_def \\<G>l_def v_gs_def by (auto intro: finite_vG intro!: v_\\<G> v_card2)\n  note sunflower = Erdos_Rado_sunflower[OF sf_precond]\n  from p have p0: \"p \\<noteq> 0\" by auto\n  have \"(p - 1) ^ l * fact l < card ?vXp\"  using L[unfolded L_def]\n    by (simp add: ac_simps)\n  note sunflower = sunflower[OF this]\n  define S where \"S = (SOME S. S \\<subseteq> ?vXp \\<and> sunflower S \\<and> card S = p)\" \n  define U where \"U = {E \\<in> X. v E \\<in> S}\" \n  define Vs where \"Vs = \\<Inter> S\"\n  define Gs where \"Gs = Vs^\\<two>\"\n  let ?U = U \n  let ?New = \"Gs :: graph\" \n  have Y: \"Y = X - U \\<union> {?New}\" \n    using Y[unfolded plucking_step_def Let_def, folded S_def, folded U_def, \n        folded Vs_def, folded Gs_def] .\n  have U: \"U \\<subseteq> \\<G>l\" using X unfolding U_def by auto \n  hence \"U \\<subseteq> \\<G>\" unfolding \\<G>l_def by auto\n  from sunflower\n  have \"\\<exists> S. S \\<subseteq> ?vXp \\<and> sunflower S \\<and> card S = p\" by auto\n  from someI_ex[OF this, folded S_def]\n  have S: \"S \\<subseteq> ?vXp\" \"sunflower S\" \"card S = p\" by (auto simp: Vs_def)\n  have fin1: \"finite ?vXp\" using finite_v_gs_Gl[OF X] .\n  from X have finX: \"finite X\" unfolding \\<G>l_def \n    using finite_subset[of X, OF _  finite_\\<G>] by auto\n  from fin1 S have finS: \"finite S\" by (metis finite_subset)\n  from finite_subset[OF _ finX] have finU: \"finite U\" unfolding U_def by auto\n  from S p have Snempty: \"S \\<noteq> {}\" by auto  \n  have UX: \"U \\<subseteq> X\" unfolding U_def by auto\n  {\n    from Snempty obtain s where sS: \"s \\<in> S\" by auto\n    with S have \"s \\<in> v_gs X\" by auto\n    then obtain Sp where \"Sp \\<in> X\" and sSp: \"s = v Sp\" \n      unfolding v_gs_def by auto\n    hence *: \"Sp \\<in> U\" using \\<open>s \\<in> S\\<close> unfolding U_def by auto\n    from * X UX have le: \"card (v Sp) \\<le> l\" \"finite (v Sp)\" \"Sp \\<in> \\<G>\" \n      unfolding \\<G>l_def \\<G>l_def using finite_vG[of Sp] by auto\n    hence m: \"v Sp \\<subseteq> [m]\" by (intro v_\\<G>)\n    have \"Vs \\<subseteq> v Sp\" using sS sSp unfolding Vs_def by auto\n    with card_mono[OF \\<open>finite (v Sp)\\<close> this] finite_subset[OF this \\<open>finite (v Sp)\\<close>] le * m\n    have \"card Vs \\<le> l\" \"U \\<noteq> {}\" \"finite Vs\" \"Vs \\<subseteq> [m]\" by auto\n  } \n  hence card_Vs: \"card Vs \\<le> l\" and Unempty: \"U \\<noteq> {}\" \n    and fin_Vs: \"finite Vs\" and Vsm: \"Vs \\<subseteq> [m]\" by auto\n  have vGs: \"v Gs \\<subseteq> Vs\" unfolding Gs_def by (rule v_sameprod_subset)\n  have GsG: \"Gs \\<in> \\<G>\" unfolding Gs_def \\<G>_def\n    by (intro CollectI Inter_subset sameprod_mono Vsm)\n  have GsGl: \"Gs \\<in> \\<G>l\" unfolding \\<G>l_def using GsG vGs card_Vs card_mono[OF _ vGs] \n    by (simp add: fin_Vs)\n  hence DsDl: \"?New \\<in> \\<G>l\" using UX  \n    unfolding \\<G>l_def \\<G>_def \\<G>l_def \\<G>_def by auto\n  with X U show \"Y \\<subseteq> \\<G>l\" unfolding Y by auto\n  from X have XD: \"X \\<subseteq> \\<G>\" unfolding \\<G>l_def by auto\n  have vplus_dsU: \"v_gs U = S\" using S(1)\n    unfolding v_gs_def U_def by force\n  have vplus_dsXU: \"v_gs (X - U) = v_gs X - v_gs U\"\n    unfolding v_gs_def U_def by auto\n  have \"card (v_gs Y) = card (v_gs (X - U \\<union> {?New}))\"  \n    unfolding Y by simp\n  also have \"v_gs (X - U \\<union> {?New}) = v_gs (X - U) \\<union> v_gs ({?New})\"\n    unfolding v_gs_union ..\n  also have \"v_gs ({?New}) = {v (Gs)}\" unfolding v_gs_def image_comp o_def by simp\n  also have \"card (v_gs (X - U) \\<union> \\<dots>) \\<le> card (v_gs (X - U)) + card \\<dots>\"\n    by (rule card_Un_le)\n  also have \"\\<dots> \\<le> card (v_gs (X - U)) + 1\" by auto\n  also have \"v_gs (X - U) = v_gs X - v_gs U\" by fact\n  also have \"card \\<dots> = card (v_gs X) - card (v_gs U)\" \n    by (rule card_Diff_subset, force simp: vplus_dsU finS, \n      insert UX, auto simp: v_gs_def)\n  also have \"card (v_gs U) = card S\" unfolding vplus_dsU ..\n  finally show \"card (v_gs Y) \\<le> card (v_gs X) - p + 1\" \n    using S by auto\n  show \"Y \\<noteq> {}\" unfolding Y using Unempty by auto\n  {\n    fix G\n    assume \"G \\<in> ACC X\" and GPOS: \"G \\<in> POS\"  \n    from this[unfolded ACC_def] POS_\\<G> have G: \"G \\<in> \\<G>\" \"X \\<tturnstile> G\" by auto\n    from this[unfolded accepts_def] obtain D :: graph where \n      D: \"D \\<in> X\" \"D \\<subseteq> G\" by auto\n    have \"G \\<in> ACC Y\" \n    proof (cases \"D \\<in> Y\")\n      case True\n      with D G show ?thesis unfolding accepts_def ACC_def by auto\n    next\n      case False\n      with D have DU: \"D \\<in> U\" unfolding Y by auto\n      from GPOS[unfolded POS_def \\<K>_def] obtain K where GK: \"G = (v K)^\\<two>\" \"card (v K) = k\" by auto\n      from DU[unfolded U_def] have \"v D \\<in> S\" by auto\n      hence \"Vs \\<subseteq> v D\" unfolding Vs_def by auto\n      also have \"\\<dots> \\<subseteq> v G\" \n        by (intro v_mono D)\n      also have \"\\<dots> = v K\" unfolding GK \n        by (rule v_sameprod, unfold GK, insert k2, auto)\n      finally have \"Gs \\<subseteq> G\" unfolding Gs_def GK\n        by (intro sameprod_mono)\n      with D DU have \"D \\<in> ?U\" \"?New \\<subseteq> G\" by (auto)\n      hence \"Y \\<tturnstile> G\" unfolding accepts_def Y by auto \n      thus ?thesis using G by auto\n    qed\n  }\n  thus \"POS \\<inter> ACC X \\<subseteq> ACC Y\" by auto\n\n  from ex_bij_betw_nat_finite[OF finS, unfolded \\<open>card S = p\\<close>]\n  obtain Si where Si: \"bij_betw Si {0 ..< p} S\" by auto\n  define G where \"G = (\\<lambda> i. SOME Gb. Gb \\<in> X \\<and> v Gb = Si i)\" \n  {\n    fix i\n    assume \"i < p\" \n    with Si have SiS: \"Si i \\<in> S\" unfolding bij_betw_def by auto\n    with S have \"Si i \\<in> v_gs X\" by auto\n    hence \"\\<exists> G. G \\<in> X \\<and> v G = Si i\" \n      unfolding v_gs_def by auto\n    from someI_ex[OF this] \n    have \"(G i) \\<in> X \\<and> v (G i) = Si i\" \n      unfolding G_def by blast\n    hence \"G i \\<in> X\" \"v (G i) = Si i\" \n      \"G i \\<in> U\" \"v (G i) \\<in> S\" using SiS unfolding U_def \n      by auto\n  } note G = this\n  have SvG: \"S = v ` G ` {0 ..< p}\" unfolding Si[unfolded bij_betw_def, \n        THEN conjunct2, symmetric] image_comp o_def using G(2) by auto\n  have injG: \"inj_on G {0 ..< p}\" \n  proof (standard, goal_cases)\n    case (1 i j)\n    hence \"Si i = Si j\" using G[of i] G[of j] by simp\n    with 1(1,2) Si show \"i = j\"  \n      by (metis Si bij_betw_iff_bijections)\n  qed\n  define r where \"r = card U\" \n  have rq: \"r \\<ge> p\" unfolding r_def \\<open>card S = p\\<close>[symmetric] vplus_dsU[symmetric]\n    unfolding v_gs_def\n    by (rule card_image_le[OF finU])\n\n  let ?Vi = \"\\<lambda> i. v (G i)\"\n  let ?Vis = \"\\<lambda> i. ?Vi i - Vs\"\n  define s where \"s = card Vs\" \n  define si where \"si i = card (?Vi i)\" for i\n  define ti where \"ti i = card (?Vis i)\" for i\n  {\n    fix i\n    assume i: \"i < p\" \n    have Vs_Vi: \"Vs \\<subseteq> ?Vi i\" using i unfolding Vs_def \n      using G[OF i] unfolding SvG by auto\n    have finVi: \"finite (?Vi i)\"  \n      using G(4)[OF i] S(1) sf_precond\n      by (meson finite_numbers finite_subset subset_eq)\n    from S(1) have \"G i \\<in> \\<G>\" using G(1)[OF i] X unfolding \\<G>l_def \\<G>_def \\<G>l_def by auto\n    hence finGi: \"finite (G i)\"\n      using finite_members_\\<G> by auto\n    have ti: \"ti i = si i - s\" unfolding ti_def si_def s_def\n      by (rule card_Diff_subset[OF fin_Vs Vs_Vi])\n    have size1: \"s \\<le> si i\" unfolding s_def si_def\n      by (intro card_mono finVi Vs_Vi)\n    have size2: \"si i \\<le> l\" unfolding si_def using G(4)[OF i] S(1) sf_precond by auto\n    note Vs_Vi finVi ti size1 size2 finGi \\<open>G i \\<in> \\<G>\\<close>\n  } note i_props = this\n  define fstt where \"fstt e = (SOME x. x \\<in> e \\<and> x \\<notin> Vs)\" for e\n  define sndd where \"sndd e = (SOME x. x \\<in> e \\<and> x \\<noteq> fstt e)\" for e\n  {\n    fix e :: \"nat set\" \n    assume *: \"card e = 2\" \"\\<not> e \\<subseteq> Vs\" \n    from *(1) obtain x y where e: \"e = {x,y}\" \"x \\<noteq> y\" \n      by (meson card_2_iff)\n    with * have \"\\<exists> x. x \\<in> e \\<and> x \\<notin> Vs\" by auto\n    from someI_ex[OF this, folded fstt_def]\n    have fst: \"fstt e \\<in> e\" \"fstt e \\<notin> Vs\" by auto\n    with * e have \"\\<exists> x. x \\<in> e \\<and> x \\<noteq> fstt e\"\n      by (metis insertCI)\n    from someI_ex[OF this, folded sndd_def] have snd: \"sndd e \\<in> e\" \"sndd e \\<noteq> fstt e\" by auto\n    from fst snd e have \"{fstt e, sndd e} = e\" \"fstt e \\<notin> Vs\" \"fstt e \\<noteq> sndd e\" by auto\n  } note fstt = this\n  {\n    fix f\n    assume \"f \\<in> ACC_cf Y - ACC_cf X\" \n    hence fake: \"f \\<in> ACC_cf {?New} - ACC_cf U\" unfolding Y ACC_cf_def accepts_def \n      Diff_iff U_def Un_iff mem_Collect_eq by blast\n    hence f: \"f \\<in> \\<F>\" using ACC_cf_\\<F> by auto\n    hence \"C f \\<in> NEG\" unfolding NEG_def by auto\n    with NEG_\\<G> have Cf: \"C f \\<in> \\<G>\" by auto\n    from fake have \"f \\<in> ACC_cf {?New}\" by auto\n    from this[unfolded ACC_cf_def accepts_def] Cf\n    have GsCf: \"Gs \\<subseteq> C f\" and Cf: \"C f \\<in> \\<G>\" by auto\n    from fake have \"f \\<notin> ACC_cf U\" by auto\n    from this[unfolded ACC_cf_def] Cf f have \"\\<not> (U \\<tturnstile> C f)\" by auto\n    from this[unfolded accepts_def] \n    have UCf: \"D \\<in> U \\<Longrightarrow> \\<not> D \\<subseteq> C f\" for D by auto\n    let ?prop = \"\\<lambda> i e. fstt e \\<in> v (G i) - Vs \\<and> \n           sndd e \\<in> v (G i) \\<and> e \\<in> G i \\<inter> ([m]^\\<two>)\n         \\<and> f (fstt e) = f (sndd e) \\<and> f (sndd e) \\<in> [k - 1] \\<and> {fstt e, sndd e} = e\" \n    define pair where \"pair i = (if i < p then (SOME pair. ?prop i pair) else undefined)\" for i \n    define u where \"u i = fstt (pair i)\" for i\n    define w where \"w i = sndd (pair i)\" for i\n    {\n      fix i\n      assume i: \"i < p\" \n      from i have \"?Vi i \\<in> S\" unfolding SvG by auto\n      hence \"Vs \\<subseteq> ?Vi i\" unfolding Vs_def by auto\n      from sameprod_mono[OF this, folded Gs_def] \n      have *: \"Gs \\<subseteq> v (G i)^\\<two>\" .  \n      from i have Gi: \"G i \\<in> U\" using G[OF i] by auto\n      from UCf[OF Gi] i_props[OF i] have \"\\<not> G i \\<subseteq> C f\" and Gi: \"G i \\<in> \\<G>\" by auto\n      then obtain edge where \n        edgep: \"edge \\<in> G i\" and edgen: \"edge \\<notin> C f\" by auto\n      from edgep Gi obtain x y where edge: \"edge = {x,y}\" \n        and xy: \"{x,y} \\<in> [m]^\\<two>\" \"{x,y} \\<subseteq> [m]\" \"card {x,y} = 2\" unfolding \\<G>_def binprod_def\n        by force        \n      define a where \"a = fstt edge\" \n      define b where \"b = sndd edge\" \n      from edgen[unfolded C_def edge] xy have id: \"f x = f y\" by simp\n      from edgen GsCf edge have edgen: \"{x,y} \\<notin> Gs\" by auto\n      from edgen[unfolded Gs_def sameprod_altdef] xy have \"\\<not> {x,y} \\<subseteq> Vs\" by auto\n      from fstt[OF \\<open>card {x,y} = 2\\<close> this, folded edge, folded a_def b_def] edge\n      have  a: \"a \\<notin> Vs\" and id_ab: \"{x,y} = {a,b}\" by auto\n      from id_ab id have id: \"f a = f b\" by (auto simp: doubleton_eq_iff)\n      let ?pair = \"(a,b)\" \n      note ab = xy[unfolded id_ab]\n      from f[unfolded \\<F>_def] ab have fb: \"f b \\<in> [k - 1]\" by auto\n      note edge = edge[unfolded id_ab]\n      from edgep[unfolded edge] v_mem_sub[OF \\<open>card {a,b} = 2\\<close>, of \"G i\"] id\n      have \"?prop i edge\" using edge ab a fb unfolding a_def b_def by auto\n      from someI[of \"?prop i\", OF this] have \"?prop i (pair i)\" using i unfolding pair_def by auto\n      from this[folded u_def w_def] edgep\n      have \"u i \\<in> v (G i) - Vs\" \"w i \\<in> v (G i)\" \"pair i \\<in> G i \\<inter> [m]^\\<two>\" \n        \"f (u i) = f (w i)\" \"f (w i) \\<in> [k - 1]\" \"pair i = {u i, w i}\" \n        by auto\n    } note uw = this\n    from uw(3) have Pi: \"pair \\<in> Pi\\<^sub>E {0 ..< p} G\" unfolding pair_def by auto\n    define Us where \"Us = u ` {0 ..< p}\" \n    define Ws where \"Ws = [m] - Us\"\n    {\n      fix i\n      assume i: \"i < p\"\n      note uwi = uw[OF this]\n      from uwi have ex: \"\\<exists> x \\<in> [k - 1]. f ` {u i, w i} = {x}\" by auto\n      from uwi have *: \"u i \\<in> [m]\" \"w i \\<in> [m]\" \"{u i, w i} \\<in> G i\" by (auto simp: sameprod_altdef)\n      have \"w i \\<notin> Us\" \n      proof\n        assume \"w i \\<in> Us\" \n        then obtain j where j: \"j < p\" and wij: \"w i = u j\" unfolding Us_def by auto\n        with uwi have ij: \"i \\<noteq> j\" unfolding binprod_def by auto\n        note uwj = uw[OF j]\n        from ij i j Si[unfolded bij_betw_def] \n        have diff: \"v (G i) \\<noteq> v (G j)\" unfolding G(2)[OF i] G(2)[OF j] inj_on_def by auto      \n        from uwi wij have uj: \"u j \\<in> v (G i)\" by auto\n        with \\<open>sunflower S\\<close>[unfolded sunflower_def, rule_format] G(4)[OF i] G(4)[OF j] uwj(1) diff\n        have \"u j \\<in> \\<Inter> S\" by blast\n        with uwj(1)[unfolded Vs_def] show False by simp\n      qed\n      with * have wi: \"w i \\<in> Ws\" unfolding Ws_def by auto\n      from uwi have wi2: \"w i \\<in> v (G i)\" by auto\n      define W where \"W = Ws \\<inter> v (G i)\" \n      from G(1)[OF i] X[unfolded \\<G>l_def \\<G>l_def] i_props[OF i] \n      have \"finite (v (G i))\" \"card (v (G i)) \\<le> l\" by auto\n      with card_mono[OF this(1), of W] have \n        W: \"finite W\" \"card W \\<le> l\" \"W \\<subseteq> [m] - Us\" unfolding W_def Ws_def by auto\n      from wi wi2 have wi: \"w i \\<in> W\" unfolding W_def by auto\n      from wi ex W * have \"{u i, w i} \\<in> G i \\<and> u i \\<in> [m] \\<and> w i \\<in> [m] - Us \\<and> f (u i) = f (w i)\" by force\n    } note uw1 = this\n    have inj: \"inj_on u {0 ..< p}\" \n    proof -\n      {\n        fix i j\n        assume i: \"i < p\" and j: \"j < p\" \n          and id: \"u i = u j\" and ij: \"i \\<noteq> j\" \n        from ij i j Si[unfolded bij_betw_def] \n        have diff: \"v (G i) \\<noteq> v (G j)\" unfolding G(2)[OF i] G(2)[OF j] inj_on_def by auto      \n        from uw[OF i] have ui: \"u i \\<in> v (G i) - Vs\" by auto\n        from uw[OF j, folded id] have uj: \"u i \\<in> v (G j)\" by auto\n        with \\<open>sunflower S\\<close>[unfolded sunflower_def, rule_format] G(4)[OF i] G(4)[OF j] uw[OF i] diff\n        have \"u i \\<in> \\<Inter> S\" by blast\n        with ui have False unfolding Vs_def by auto\n      }\n      thus ?thesis unfolding inj_on_def by fastforce\n    qed\n    have card: \"card ([m] - Us) = m - p\" \n    proof (subst card_Diff_subset)\n      show \"finite Us\" unfolding Us_def by auto\n      show \"Us \\<subseteq> [m]\" unfolding Us_def using uw1 by auto\n      have \"card Us = p\" unfolding Us_def using inj\n        by (simp add: card_image)\n      thus \"card [m] - card Us = m - p\" by simp\n    qed\n    hence \"(\\<forall> i < p. pair i \\<in> G i) \\<and> inj_on u {0 ..< p} \\<and> (\\<forall> i < p. w i \\<in> [m] - u ` {0 ..< p} \\<and> f (u i) = f (w i))\" \n      using inj uw1 uw unfolding Us_def by auto\n    from this[unfolded u_def w_def] Pi card[unfolded Us_def u_def w_def]\n    have \"\\<exists> e \\<in> Pi\\<^sub>E {0..<p} G. (\\<forall>i<p. e i \\<in> G i) \\<and>\n      card ([m] - (\\<lambda>i. fstt (e i)) ` {0..<p}) = m - p \\<and>\n      (\\<forall>i<p. sndd (e i) \\<in> [m] - (\\<lambda>i. fstt (e i)) ` {0..<p} \\<and> f (fstt (e i)) = f (sndd (e i)))\" \n      by blast\n  } note fMem = this\n  define Pi2 where \"Pi2 W = Pi\\<^sub>E ([m] - W) (\\<lambda> _. [k - 1])\" for W\n  define merge where \"merge = \n    (\\<lambda> e  (g :: nat \\<Rightarrow> nat) v. if v \\<in> (\\<lambda> i. fstt (e i)) ` {0 ..< p} then g (sndd (e (SOME i. i < p \\<and> v = fstt (e i)))) else g v)\"     \n  let ?W = \"\\<lambda> e. (\\<lambda> i. fstt (e i)) ` {0..<p}\" \n  have \"ACC_cf Y - ACC_cf X \\<subseteq> { merge e g | e g. e \\<in> Pi\\<^sub>E {0..<p} G \\<and> card ([m] - ?W e) = m - p \\<and> g \\<in> Pi2 (?W e)}\"\n    (is \"_ \\<subseteq> ?R\")\n  proof\n    fix f\n    assume mem: \"f \\<in> ACC_cf Y - ACC_cf X\" \n    with ACC_cf_\\<F> have \"f \\<in> \\<F>\" by auto\n    hence f: \"f \\<in> [m] \\<rightarrow>\\<^sub>E [k - 1]\" unfolding \\<F>_def .\n    from fMem[OF mem] obtain e where e: \"e \\<in> Pi\\<^sub>E {0..<p} G\" \n     \"\\<And> i. i<p \\<Longrightarrow> e i \\<in> G i\" \n     \"card ([m] - ?W e) = m - p\" \n     \"\\<And> i. i<p \\<Longrightarrow> sndd (e i) \\<in> [m] - ?W e \\<and> f (fstt (e i)) = f (sndd (e i))\" by auto\n    define W where \"W = ?W e\" \n    note e = e[folded W_def]\n    let ?g = \"restrict f ([m] - W)\" \n    let ?h = \"merge e ?g\" \n    have \"f \\<in> ?R\"\n    proof (intro CollectI exI[of _ e] exI[of _ ?g], unfold W_def[symmetric], intro conjI e)\n      show \"?g \\<in> Pi2 W\" unfolding Pi2_def using f by auto\n      {\n        fix v :: nat\n        have \"?h v = f v\" \n        proof (cases \"v \\<in> W\")\n          case False\n          thus ?thesis using f unfolding merge_def unfolding W_def[symmetric] by auto\n        next\n          case True\n          from this[unfolded W_def] obtain i where i: \"i < p\" and v: \"v = fstt (e i)\" by auto\n          define j where \"j = (SOME j. j < p \\<and> v = fstt (e j))\" \n          from i v have \"\\<exists> j. j < p \\<and> v = fstt (e j)\" by auto\n          from someI_ex[OF this, folded j_def] have j: \"j < p\" and v: \"v = fstt (e j)\" by auto\n          have \"?h v = restrict f ([m] - W) (sndd (e j))\" \n            unfolding merge_def unfolding W_def[symmetric] j_def using True by auto\n          also have \"\\<dots> = f (sndd (e j))\" using e(4)[OF j] by auto\n          also have \"\\<dots> = f (fstt (e j))\" using e(4)[OF j] by auto\n          also have \"\\<dots> = f v\" using v by simp\n          finally show ?thesis .\n        qed\n      }\n      thus \"f = ?h\" by auto\n    qed\n    thus \"f \\<in> ?R\" by auto\n  qed\n  also have \"\\<dots> \\<subseteq> (\\<lambda> (e,g). (merge e g)) ` (Sigma (Pi\\<^sub>E {0..<p} G \\<inter> {e. card ([m] - ?W e) = m - p}) (\\<lambda> e. Pi2 (?W e)))\" \n    (is \"_ \\<subseteq> ?f ` ?R\")\n    by auto\n  finally have sub: \"ACC_cf Y - ACC_cf X \\<subseteq> ?f ` ?R\" .\n  have fin[simp,intro]: \"finite [m]\" \"finite [k - Suc 0]\" unfolding numbers_def by auto\n  have finPie[simp, intro]: \"finite (Pi\\<^sub>E {0..<p} G)\" \n    by (intro finite_PiE, auto intro: i_props)\n  have finR: \"finite ?R\" unfolding Pi2_def\n    by (intro finite_SigmaI finite_Int allI finite_PiE i_props, auto)\n  have \"card (ACC_cf Y - ACC_cf X) \\<le> card (?f ` ?R)\" \n    by (rule card_mono[OF finite_imageI[OF finR] sub])\n  also have \"\\<dots> \\<le> card ?R\" \n    by (rule card_image_le[OF finR])\n  also have \"\\<dots> = (\\<Sum>e\\<in>(Pi\\<^sub>E {0..<p} G \\<inter> {e. card ([m] - ?W e) = m - p}). card (Pi2 (?W e)))\" \n    by (rule card_SigmaI, unfold Pi2_def,\n    (intro finite_SigmaI allI finite_Int finite_PiE i_props, auto)+)\n  also have \"\\<dots> = (\\<Sum>e\\<in>Pi\\<^sub>E {0..<p} G \\<inter> {e. card ([m] - ?W e) = m - p}. (k - 1) ^ (card ([m] - ?W e)))\" \n    by (rule sum.cong[OF refl], unfold Pi2_def, subst card_PiE, auto)\n  also have \"\\<dots> = (\\<Sum>e\\<in>Pi\\<^sub>E {0..<p} G \\<inter> {e. card ([m] - ?W e) = m - p}. (k - 1) ^ (m - p))\" \n    by (rule sum.cong[OF refl], rule arg_cong[of _ _ \"\\<lambda> n. (k - 1)^n\"], auto)\n  also have \"\\<dots> \\<le> (\\<Sum>e\\<in>Pi\\<^sub>E {0..<p} G. (k - 1) ^ (m - p))\" \n    by (rule sum_mono2, auto)\n  also have \"\\<dots> = card (Pi\\<^sub>E {0..<p} G) * (k - 1) ^ (m - p)\" by simp\n  also have \"\\<dots> = (\\<Prod>i = 0..<p. card (G i)) * (k - 1) ^ (m - p)\"\n    by (subst card_PiE, auto)\n  also have \"\\<dots> \\<le> (\\<Prod>i = 0..<p. (k - 1) div 2) * (k - 1) ^ (m - p)\"\n  proof - \n    {\n      fix i\n      assume i: \"i < p\" \n      from G[OF i] X\n      have GiG: \"G i \\<in> \\<G>\"\n        unfolding \\<G>l_def \\<G>_def \\<G>_def sameprod_altdef by force\n      from i_props[OF i] have finGi: \"finite (G i)\" by auto\n      have finvGi: \"finite (v (G i))\" by (rule finite_vG, insert i_props[OF i], auto)\n      have \"card (G i) \\<le> card ((v (G i))^\\<two>)\" \n        by (intro card_mono[OF sameprod_finite], rule finvGi, rule v_\\<G>_2[OF GiG])\n      also have \"\\<dots> \\<le> l choose 2\"\n      proof (subst card_sameprod[OF finvGi], rule choose_mono)\n        show \"card (v (G i)) \\<le> l\" using i_props[OF i] unfolding ti_def si_def by simp\n      qed\n      also have \"l choose 2 = l * (l - 1) div 2\" unfolding choose_two by simp\n      also have \"l * (l - 1) = k - l\" unfolding kl2 power2_eq_square by (simp add: algebra_simps)\n      also have \"\\<dots> div 2 \\<le> (k - 1) div 2\" \n        by (rule div_le_mono, insert l2, auto)    \n      finally have \"card (G i) \\<le> (k - 1) div 2\" .\n    } \n    thus ?thesis by (intro mult_right_mono prod_mono, auto)\n  qed\n  also have \"\\<dots> = ((k - 1) div 2) ^ p * (k - 1) ^ (m - p)\" \n    by simp\n  also have \"\\<dots> \\<le> ((k - 1) ^ p div (2^p)) * (k - 1) ^ (m - p)\" \n    by (rule mult_right_mono; auto simp: div_mult_pow_le)\n  also have \"\\<dots> \\<le> ((k - 1) ^ p * (k - 1) ^ (m - p)) div 2^p\" \n    by (rule div_mult_le)\n  also have \"\\<dots> = (k - 1)^m div 2^p\"  \n  proof - \n    have \"p + (m - p) = m\" using mp by simp\n    thus ?thesis by (subst power_add[symmetric], simp)\n  qed\n  finally have \"card (ACC_cf Y - ACC_cf X) \\<le> (k - 1) ^ m div 2 ^ p\" .\n  hence \"2 ^ p * card (ACC_cf Y - ACC_cf X) \\<le> 2^p * ((k - 1) ^ m div 2 ^ p)\" by simp\n  also have \"\\<dots> \\<le> (k - 1)^m\"  by simp\n  finally show \"2^p * card (ACC_cf Y - ACC_cf X) \\<le> (k - 1) ^ m\" .\nqed\n\n\ntext \\<open>Definition 6\\<close>\n\nfunction PLU_main :: \"graph set \\<Rightarrow> graph set \\<times> nat\" where\n  \"PLU_main X = (if X \\<subseteq> \\<G>l \\<and> L < card (v_gs X) then\n     map_prod id Suc (PLU_main (plucking_step X)) else\n     (X, 0))\"\n  by pat_completeness auto\n\ntermination \nproof (relation \"measure (\\<lambda> X. card (v_gs X))\", force, goal_cases)\n  case (1 X)\n  hence \"X \\<subseteq> \\<G>l\" and LL: \"L < card (v_gs X)\" by auto\n  from plucking_step(1)[OF this refl]\n  have \"card (v_gs (plucking_step X)) \\<le> card (v_gs X) - p + 1\" .\n  also have \"\\<dots> < card (v_gs X)\" using p L3 LL\n    by auto\n  finally show ?case by simp\nqed\n\ndeclare PLU_main.simps[simp del]\n\ndefinition PLU :: \"graph set \\<Rightarrow> graph set\" where\n  \"PLU X = fst (PLU_main X)\" \n\ntext \\<open>Lemma 7\\<close>\n\nlemma PLU_main_n: assumes \"X \\<subseteq> \\<G>l\" and \"PLU_main X = (Z, n)\" \n  shows \"n * (p - 1) \\<le> card (v_gs X)\" \n  using assms \nproof (induct X  arbitrary: Z n  rule: PLU_main.induct)\n  case (1 X Z n)\n  note [simp] = PLU_main.simps[of X]\n  show ?case\n  proof (cases \"card (v_gs X) \\<le> L\")\n    case True\n    thus ?thesis using 1 by auto\n  next\n    case False\n    define Y where \"Y = plucking_step X\" \n    obtain q where PLU: \"PLU_main Y = (Z, q)\" and n: \"n = Suc q\" \n      using \\<open>PLU_main X = (Z,n)\\<close>[unfolded PLU_main.simps[of X], folded Y_def] using False 1(2) by (cases \"PLU_main Y\", auto)    \n    from False have L: \"card (v_gs X) > L\" by auto\n    note step = plucking_step[OF 1(2) this Y_def]\n    from False 1 have \"X \\<subseteq> \\<G>l \\<and> L < card (v_gs X)\" by auto\n    note IH = 1(1)[folded Y_def, OF this step(2) PLU]\n    have \"n * (p - 1) = (p - 1) + q * (p - 1)\" unfolding n by simp\n    also have \"\\<dots> \\<le> (p - 1) + card (v_gs Y)\" using IH by simp\n    also have \"\\<dots> \\<le> p - 1 + (card (v_gs X) - p + 1)\" using step(1) by simp\n    also have \"\\<dots> = card (v_gs X)\" using L Lp p by simp\n    finally show ?thesis .\n  qed\nqed\n\ntext \\<open>Definition 8\\<close>\n\ndefinition sqcup :: \"graph set \\<Rightarrow> graph set \\<Rightarrow> graph set\" (infixl \"\\<squnion>\" 65) where\n  \"X \\<squnion> Y = PLU (X \\<union> Y)\" \n\ndefinition sqcap :: \"graph set \\<Rightarrow> graph set \\<Rightarrow> graph set\" (infixl \"\\<sqinter>\" 65) where\n  \"X \\<sqinter> Y = PLU (X \\<odot>l Y)\" \n\ndefinition deviate_pos_cup :: \"graph set \\<Rightarrow> graph set \\<Rightarrow> graph set\" (\"\\<partial>\\<squnion>Pos\") where\n  \"\\<partial>\\<squnion>Pos X Y = POS \\<inter> ACC (X \\<union> Y) - ACC (X \\<squnion> Y)\" \n\ndefinition deviate_pos_cap :: \"graph set \\<Rightarrow> graph set \\<Rightarrow> graph set\" (\"\\<partial>\\<sqinter>Pos\") where\n  \"\\<partial>\\<sqinter>Pos X Y = POS \\<inter> ACC (X \\<odot> Y) - ACC (X \\<sqinter> Y)\" \n\ndefinition deviate_neg_cup :: \"graph set \\<Rightarrow> graph set \\<Rightarrow> colorf set\" (\"\\<partial>\\<squnion>Neg\") where\n  \"\\<partial>\\<squnion>Neg X Y = ACC_cf (X \\<squnion> Y) - ACC_cf (X \\<union> Y)\" \n\ndefinition deviate_neg_cap :: \"graph set \\<Rightarrow> graph set \\<Rightarrow> colorf set\" (\"\\<partial>\\<sqinter>Neg\") where\n  \"\\<partial>\\<sqinter>Neg X Y = ACC_cf (X \\<sqinter> Y) - ACC_cf (X \\<odot> Y)\" \n\ntext \\<open>Lemma 9 -- without applying Lemma 7\\<close>\n\nlemma PLU_main: assumes \"X \\<subseteq> \\<G>l\" \n  and \"PLU_main X = (Z, n)\" \nshows \"Z \\<in> \\<P>L\\<G>l\n  \\<and> (Z = {} \\<longleftrightarrow> X = {})\n  \\<and> POS \\<inter> ACC X \\<subseteq> ACC Z\n  \\<and> 2 ^ p * card (ACC_cf Z - ACC_cf X) \\<le> (k - 1) ^ m * n\" \n  using assms\nproof (induct X  arbitrary: Z n  rule: PLU_main.induct)\n  case (1 X Z n)\n  note [simp] = PLU_main.simps[of X]\n  show ?case\n  proof (cases \"card (v_gs X) \\<le> L\")\n    case True\n    from True show ?thesis using 1 by (auto simp: id \\<P>L\\<G>l_def)\n  next\n    case False\n    define Y where \"Y = plucking_step X\" \n    obtain q where PLU: \"PLU_main Y = (Z, q)\" and n: \"n = Suc q\" \n      using \\<open>PLU_main X = (Z,n)\\<close>[unfolded PLU_main.simps[of X], folded Y_def] using False 1(2) by (cases \"PLU_main Y\", auto)    \n    from False have \"card (v_gs X) > L\" by auto\n    note step = plucking_step[OF 1(2) this Y_def]\n    from False 1 have \"X \\<subseteq> \\<G>l \\<and> L < card (v_gs X)\" by auto\n    note IH = 1(1)[folded Y_def, OF this step(2) PLU] \\<open>Y \\<noteq> {}\\<close>\n    let ?Diff = \"\\<lambda> X Y. ACC_cf X - ACC_cf Y\" \n    have finNEG: \"finite NEG\"\n      using NEG_\\<G> infinite_super by blast\n    have \"?Diff Z X \\<subseteq> ?Diff Z Y \\<union> ?Diff Y X\" by auto\n    from card_mono[OF finite_subset[OF _ finite_\\<F>] this] ACC_cf_\\<F>\n    have \"2 ^ p * card (?Diff Z X) \\<le> 2 ^ p * card (?Diff Z Y \\<union> ?Diff Y X)\" by auto\n    also have \"\\<dots> \\<le> 2 ^ p * (card (?Diff Z Y) + card (?Diff Y X))\" \n      by (rule mult_left_mono, rule card_Un_le, simp)\n    also have \"\\<dots> = 2 ^ p * card (?Diff Z Y) + 2 ^ p * card (?Diff Y X)\" \n      by (simp add: algebra_simps)\n    also have \"\\<dots> \\<le> ((k - 1) ^ m) * q + (k - 1) ^ m\" using IH step by auto\n    also have \"\\<dots> = ((k - 1) ^ m) * Suc q\" by (simp add: ac_simps)\n    finally have c: \"2 ^ p * card (ACC_cf Z - ACC_cf X) \\<le> ((k - 1) ^ m) * Suc q\" by simp\n    from False have \"X \\<noteq> {}\" by auto\n    thus ?thesis unfolding n using IH step c by auto\n  qed\nqed\n\ntext \\<open>Lemma 9\\<close>\n\nlemma assumes X: \"X \\<in> \\<P>L\\<G>l\" and Y: \"Y \\<in> \\<P>L\\<G>l\"\n  shows PLU_union: \"PLU (X \\<union> Y) \\<in> \\<P>L\\<G>l\" and\n  sqcup: \"X \\<squnion> Y \\<in> \\<P>L\\<G>l\" and\n  sqcup_sub: \"POS \\<inter> ACC (X \\<union> Y) \\<subseteq> ACC (X \\<squnion> Y)\" and\n  deviate_pos_cup: \"\\<partial>\\<squnion>Pos X Y = {}\" and\n  deviate_neg_cup: \"card (\\<partial>\\<squnion>Neg X Y) < (k - 1)^m * L / 2^(p - 1)\" \nproof -\n  obtain Z n where res: \"PLU_main (X \\<union> Y) = (Z, n)\" by force\n  hence PLU: \"PLU (X \\<union> Y) = Z\" unfolding PLU_def by simp\n  from X Y have XY: \"X \\<union> Y \\<subseteq> \\<G>l\" unfolding \\<P>L\\<G>l_def by auto\n  note main = PLU_main[OF this(1) res]\n  from main show \"PLU (X \\<union> Y) \\<in> \\<P>L\\<G>l\" unfolding PLU by simp\n  thus \"X \\<squnion> Y \\<in> \\<P>L\\<G>l\" unfolding sqcup_def .\n  from main show \"POS \\<inter> ACC (X \\<union> Y) \\<subseteq> ACC (X \\<squnion> Y)\" \n    unfolding sqcup_def PLU by simp\n  thus \"\\<partial>\\<squnion>Pos X Y = {}\" unfolding deviate_pos_cup_def PLU sqcup_def by auto\n  have \"card (v_gs (X \\<union> Y)) \\<le> card (v_gs X) + card (v_gs Y)\" \n    unfolding v_gs_union by (rule card_Un_le)\n  also have \"\\<dots> \\<le> L + L\" using X Y unfolding \\<P>L\\<G>l_def by simp\n  finally have \"card (v_gs (X \\<union> Y)) \\<le> 2 * L\" by simp\n  with PLU_main_n[OF XY(1) res] have \"n * (p - 1) \\<le> 2 * L\" by simp\n  with p Lm m2 have n: \"n < 2 * L\" by (cases n, auto, cases \"p - 1\", auto)\n  let ?r = real\n  have *: \"(k - 1) ^ m > 0\" using k l2 by simp\n  have \"2 ^ p * card (\\<partial>\\<squnion>Neg X Y) \\<le> 2 ^ p * card (ACC_cf Z - ACC_cf (X \\<union> Y))\" unfolding deviate_neg_cup_def PLU sqcup_def\n    by (rule mult_left_mono, rule card_mono[OF finite_subset[OF _ finite_\\<F>]], insert ACC_cf_\\<F>, force, auto)\n  also have \"\\<dots> \\<le> (k - 1) ^ m * n\" using main by simp\n  also have \"\\<dots> < (k - 1) ^ m * (2 * L)\" unfolding mult_less_cancel1 using n * by simp\n  also have \"\\<dots> = 2 * ((k - 1) ^ m * L)\" by simp\n  finally have \"2 * (2^(p - 1) * card (\\<partial>\\<squnion>Neg X Y)) < 2 * ((k - 1) ^ m * L)\" using p by (cases p, auto)\n  hence \"2 ^ (p - 1) * card (\\<partial>\\<squnion>Neg X Y) < (k - 1)^m * L\" by simp\n  hence \"?r (2 ^ (p - 1) * card (\\<partial>\\<squnion>Neg X Y)) < ?r ((k - 1)^m * L)\" by linarith\n  thus \"card (\\<partial>\\<squnion>Neg X Y) < (k - 1)^m * L / 2^(p - 1)\" by (simp add: field_simps)\nqed\n\ntext \\<open>Lemma 10\\<close>\n\nlemma assumes X: \"X \\<in> \\<P>L\\<G>l\" and Y: \"Y \\<in> \\<P>L\\<G>l\"\n  shows PLU_joinl: \"PLU (X \\<odot>l Y) \\<in> \\<P>L\\<G>l\" and\n  sqcap: \"X \\<sqinter> Y \\<in> \\<P>L\\<G>l\" and\n  deviate_neg_cap: \"card (\\<partial>\\<sqinter>Neg X Y) < (k - 1)^m * L^2 / 2^(p - 1)\" and\n  deviate_pos_cap: \"card (\\<partial>\\<sqinter>Pos X Y) \\<le> ((m - l - 1) choose (k - l - 1)) * L^2\" \nproof -\n  obtain Z n where res: \"PLU_main (X \\<odot>l Y) = (Z, n)\" by force\n  hence PLU: \"PLU (X \\<odot>l Y) = Z\" unfolding PLU_def by simp\n  from X Y have XY: \"X \\<subseteq> \\<G>l\" \"Y \\<subseteq> \\<G>l\" \"X \\<subseteq> \\<G>\" \"Y \\<subseteq> \\<G>\" unfolding \\<P>L\\<G>l_def \\<G>l_def by auto  \n  have sub: \"X \\<odot>l Y \\<subseteq> \\<G>l\" unfolding odotl_def using XY \n    by (auto split: option.splits)\n  note main = PLU_main[OF sub res]\n  note finV = finite_v_gs_Gl[OF XY(1)] finite_v_gs_Gl[OF XY(2)]\n  have \"X \\<odot> Y \\<subseteq> \\<G>\" by (rule odot_\\<G>, insert XY, auto simp: \\<G>l_def) \n  hence XYD: \"X \\<odot> Y \\<subseteq> \\<G>\" by auto\n  have finvXY: \"finite (v_gs (X \\<odot> Y))\" by (rule finite_v_gs[OF XYD])\n  have \"card (v_gs (X \\<odot> Y)) \\<le> card (v_gs X) * card (v_gs Y)\" \n    using XY(1-2) by (intro card_v_gs_join, auto simp: \\<G>l_def)\n  also have \"\\<dots> \\<le> L * L\" using X Y unfolding \\<P>L\\<G>l_def \n    by (intro mult_mono, auto)\n  also have \"\\<dots> = L^2\" by algebra\n  finally have card_join: \"card (v_gs (X \\<odot> Y)) \\<le> L^2\" .\n  with card_mono[OF finvXY v_gs_mono[OF joinl_join]]\n  have card: \"card (v_gs (X \\<odot>l Y)) \\<le> L^2\" by simp\n  with PLU_main_n[OF sub res] have \"n * (p - 1) \\<le> L^2\" by simp\n  with p Lm m2 have n: \"n < 2 * L^2\" by (cases n, auto, cases \"p - 1\", auto)\n  have *: \"(k - 1) ^ m > 0\" using k l2 by simp\n  show \"PLU (X \\<odot>l Y) \\<in> \\<P>L\\<G>l\" unfolding PLU using main by auto\n  thus \"X \\<sqinter> Y \\<in> \\<P>L\\<G>l\" unfolding sqcap_def .\n  let ?r = real\n  have \"2^p * card (\\<partial>\\<sqinter>Neg X Y) \\<le> 2 ^ p * card (ACC_cf Z - ACC_cf (X \\<odot>l Y))\"\n    unfolding deviate_neg_cap_def PLU sqcap_def\n    by (rule mult_left_mono, rule card_mono[OF finite_subset[OF _ finite_\\<F>]], insert ACC_cf_\\<F>, force, \n      insert ACC_cf_mono[OF joinl_join, of X Y], auto)\n  also have \"\\<dots> \\<le> (k - 1) ^ m * n\" using main by simp\n  also have \"\\<dots> < (k - 1) ^ m * (2 * L^2)\" unfolding mult_less_cancel1 using n * by simp\n  finally have \"2 * (2^(p - 1) * card (\\<partial>\\<sqinter>Neg X Y)) < 2 * ((k - 1) ^ m * L^2)\" using p by (cases p, auto)\n  hence \"2 ^ (p - 1) * card (\\<partial>\\<sqinter>Neg X Y) < (k - 1)^m * L^2\" by simp\n  hence \"?r (2 ^ (p - 1) * card (\\<partial>\\<sqinter>Neg X Y)) < (k - 1)^m * L^2\" by linarith\n  thus \"card (\\<partial>\\<sqinter>Neg X Y) < (k - 1)^m * L^2 / 2^(p - 1)\" by (simp add: field_simps)\n  (* now for the next approximation *)\n  define Vs where \"Vs = v_gs (X \\<odot> Y) \\<inter> {V . V \\<subseteq> [m] \\<and> card V \\<ge> Suc l}\" \n  define C where \"C (V :: nat set) = (SOME C. C \\<subseteq> V \\<and> card C = Suc l)\" for V\n  define K where \"K C = { W. W \\<subseteq> [m] - C \\<and> card W = k - Suc l }\" for C\n  define merge where \"merge C V = (C \\<union> V)^\\<two>\" for C V :: \"nat set\" \n  define GS where \"GS = { merge (C V) W | V W. V \\<in> Vs \\<and> W \\<in> K (C V)}\"\n  {\n    fix V\n    assume V: \"V \\<in> Vs\" \n    hence card: \"card V \\<ge> Suc l\" and Vm: \"V \\<subseteq> [m]\" unfolding Vs_def by auto\n    from card obtain D where C: \"D \\<subseteq> V\" and cardV: \"card D = Suc l\" \n      by (rule obtain_subset_with_card_n)\n    hence \"\\<exists> C. C \\<subseteq> V \\<and> card C = Suc l\" by blast\n    from someI_ex[OF this, folded C_def] have *: \"C V \\<subseteq> V\" \"card (C V) = Suc l\" \n      by blast+\n    with Vm have sub: \"C V \\<subseteq> [m]\" by auto\n    from finite_subset[OF this] have finCV: \"finite (C V)\" unfolding numbers_def by simp\n    have \"card (K (C V)) = (m - Suc l) choose (k - Suc l)\" unfolding K_def\n    proof (subst n_subsets, (rule finite_subset[of _ \"[m]\"], auto)[1], rule arg_cong[of _ _ \"\\<lambda> x. x choose _\"])\n      show \"card ([m] - C V) = m - Suc l\" \n        by (subst card_Diff_subset, insert sub * finCV, auto)\n    qed\n    note * finCV sub this\n  } note Vs_C = this\n  have finK: \"finite (K V)\" for V unfolding K_def by auto\n  {\n    fix G\n    assume G: \"G \\<in> POS \\<inter> ACC (X \\<odot> Y)\" \n    have \"G \\<in> ACC (X \\<odot>l Y) \\<union> GS\"\n    proof (rule ccontr)\n      assume \"\\<not> ?thesis\" \n      with G have G: \"G \\<in> POS\" \"G \\<in> ACC (X \\<odot> Y)\" \"G \\<notin> ACC (X \\<odot>l Y)\" \n        and contra: \"G \\<notin> GS\" by auto\n      from G(1)[unfolded \\<K>_def] have \"card (v G) = k \\<and> (v G)^\\<two> = G\" and G0: \"G \\<in> \\<G>\"\n        by auto\n      hence vGk: \"card (v G) = k\" \"(v G)^\\<two> = G\" by auto\n      from G0 have vm: \"v G \\<subseteq> [m]\" by (rule v_\\<G>)\n      from G(2-3)[unfolded ACC_def accepts_def] obtain H \n        where H: \"H \\<in> X \\<odot> Y\" \"H \\<notin> X \\<odot>l Y\" \n          and HG: \"H \\<subseteq> G\" by auto\n      from v_mono[OF HG] have vHG: \"v H \\<subseteq> v G\" by auto\n      {\n        from H(1)[unfolded odot_def] obtain D E where D: \"D \\<in> X\" and E: \"E \\<in> Y\" and HDE: \"H = D \\<union> E\" \n          by force\n        from D E X Y have Dl: \"D \\<in> \\<G>l\" \"E \\<in> \\<G>l\" unfolding \\<P>L\\<G>l_def by auto\n        have Dp: \"D \\<in> \\<G>\" using Dl by (auto simp: \\<G>l_def)\n        have Ep: \"E \\<in> \\<G>\" using Dl by (auto simp: \\<G>l_def)\n        from Dl HDE have HD: \"H \\<in> \\<G>\" unfolding \\<G>l_def by auto\n        have HG0: \"H \\<in> \\<G>\" using Dp Ep unfolding HDE by auto\n        have HDL: \"H \\<notin> \\<G>l\"\n        proof\n          assume \"H \\<in> \\<G>l\"\n          hence \"H \\<in> X \\<odot>l Y\"\n            unfolding odotl_def HDE odot_def using D E by blast\n          thus False using H by auto\n        qed\n        from HDL HD have HGl: \"H \\<notin> \\<G>l\" unfolding \\<G>l_def by auto\n        have vm: \"v H \\<subseteq> [m]\" using HG0 by (rule v_\\<G>)\n        have lower: \"l < card (v H)\" using HGl HG0 unfolding \\<G>l_def by auto\n        have \"v H \\<in> Vs\" unfolding Vs_def using lower vm H unfolding v_gs_def by auto\n      } note in_Vs = this\n      note C = Vs_C[OF this]\n      let ?C = \"C (v H)\" \n      from C vHG have CG: \"?C \\<subseteq> v G\" by auto\n      hence id: \"v G = ?C \\<union> (v G - ?C)\" by auto\n      from arg_cong[OF this, of card] vGk(1) C\n      have \"card (v G - ?C) = k - Suc l\"\n        by (metis CG card_Diff_subset)\n      hence \"v G - ?C \\<in> K ?C\" unfolding K_def using vm by auto\n      hence \"merge ?C (v G - ?C) \\<in> GS\" unfolding GS_def using in_Vs by auto\n      also have \"merge ?C (v G - ?C) = v G^\\<two>\" unfolding merge_def\n        by (rule arg_cong[of _ _ sameprod], insert id, auto)\n      also have \"\\<dots> = G\" by fact\n      finally have \"G \\<in> GS\" .\n      with contra show False ..\n    qed\n  }\n  hence \"\\<partial>\\<sqinter>Pos X Y \\<subseteq> (POS \\<inter> ACC (X \\<odot>l Y) - ACC (X \\<sqinter> Y)) \\<union> GS\"\n    unfolding deviate_pos_cap_def by auto\n  also have \"POS \\<inter> ACC (X \\<odot>l Y) - ACC (X \\<sqinter> Y) = {}\"\n  proof -\n    have \"POS - ACC (X \\<sqinter> Y) \\<subseteq> UNIV - ACC (X \\<odot>l Y)\" \n      unfolding sqcap_def using PLU main by auto\n    thus ?thesis by auto\n  qed\n  finally have sub: \"\\<partial>\\<sqinter>Pos X Y \\<subseteq> GS\" by auto\n  have finVs: \"finite Vs\" unfolding Vs_def numbers_def by simp \n  let ?Sig = \"Sigma Vs (\\<lambda> V. K (C V))\" \n  have GS_def: \"GS = (\\<lambda> (V,W). merge (C V) W) ` ?Sig\" unfolding GS_def \n    by auto\n  have finSig: \"finite ?Sig\" using finVs finK by simp\n  have finGS: \"finite GS\" unfolding GS_def \n    by (rule finite_imageI[OF finSig])\n  have \"card (\\<partial>\\<sqinter>Pos X Y) \\<le> card GS\" by (rule card_mono[OF finGS sub])\n  also have \"\\<dots> \\<le> card ?Sig\" unfolding GS_def\n    by (rule card_image_le[OF finSig])\n  also have \"\\<dots> = (\\<Sum>a\\<in>Vs. card (K (C a)))\"\n    by (rule card_SigmaI[OF finVs], auto simp: finK)\n  also have \"\\<dots> = (\\<Sum>a\\<in>Vs. (m - Suc l) choose (k - Suc l))\" using Vs_C\n    by (intro sum.cong, auto)\n  also have \"\\<dots> = ((m - Suc l) choose (k - Suc l)) * card Vs\" \n    by simp\n  also have \"\\<dots> \\<le> ((m - Suc l) choose (k - Suc l)) * L^2\" \n  proof (rule mult_left_mono)\n    have \"card Vs \\<le> card (v_gs (X \\<odot> Y))\" \n      by (rule card_mono[OF finvXY], auto simp: Vs_def)\n    also have \"\\<dots> \\<le> L^2\" by fact\n    finally show \"card Vs \\<le> L^2\" .\n  qed simp\n  finally show \"card (\\<partial>\\<sqinter>Pos X Y) \\<le> ((m - l - 1) choose (k - l - 1)) * L^2\"\n    by simp \nqed\nend\n\n  \nsubsection \\<open>Formalism\\<close>\n\ntext \\<open>Fix a variable set of cardinality m over 2.\\<close>\n\nlocale forth_assumptions = third_assumptions + \n  fixes \\<V> :: \"'a set\" and \\<pi> :: \"'a \\<Rightarrow> vertex set\" \n  assumes cV: \"card \\<V> = (m choose 2)\" \n  and bij_betw_\\<pi>: \"bij_betw \\<pi> \\<V> ([m]^\\<two>)\" \nbegin\n\ndefinition n where \"n = (m choose 2)\" \n\ntext \\<open>the formulas over the fixed variable set\\<close>\n\ndefinition \\<A> :: \"'a mformula set\" where\n  \"\\<A> = { \\<phi>. vars \\<phi> \\<subseteq> \\<V>}\" \n\nlemma \\<A>_simps[simp]: \n  \"FALSE \\<in> \\<A>\" \n  \"(Var x \\<in> \\<A>) = (x \\<in> \\<V>)\" \n  \"(Conj \\<phi> \\<psi> \\<in> \\<A>) = (\\<phi> \\<in> \\<A> \\<and> \\<psi> \\<in> \\<A>)\" \n  \"(Disj \\<phi> \\<psi> \\<in> \\<A>) = (\\<phi> \\<in> \\<A> \\<and> \\<psi> \\<in> \\<A>)\" \n  by (auto simp: \\<A>_def)\n\nlemma inj_on_\\<pi>: \"inj_on \\<pi> \\<V>\"\n  using bij_betw_\\<pi> by (metis bij_betw_imp_inj_on) \n\nlemma \\<pi>m2[simp,intro]: \"x \\<in> \\<V> \\<Longrightarrow> \\<pi> x \\<in> [m]^\\<two>\" \n  using bij_betw_\\<pi> by (rule bij_betw_apply)\n\nlemma card_v_\\<pi>[simp,intro]: assumes \"x \\<in> \\<V>\" \n  shows \"card (v {\\<pi> x}) = 2\" \nproof -\n  from \\<pi>m2[OF assms] have mem: \"\\<pi> x \\<in> [m]^\\<two>\" by auto\n  from this[unfolded binprod_def] obtain a b where \\<pi>: \"\\<pi> x = {a,b}\" and diff: \"a \\<noteq> b\" \n    by auto\n  hence \"v {\\<pi> x} = {a,b}\" unfolding v_def by auto\n  thus ?thesis using diff by simp\nqed\n\nlemma \\<pi>_singleton[simp,intro]: assumes \"x \\<in> \\<V>\"\n  shows \"{\\<pi> x} \\<in> \\<G>\"  \n    \"{{\\<pi> x}} \\<in> \\<P>L\\<G>l\"  \n  using assms L3 l2\n  by (auto simp: \\<G>_def \\<P>L\\<G>l_def v_gs_def \\<G>l_def)\n\nlemma empty_\\<P>L\\<G>l[simp,intro]: \"{} \\<in> \\<P>L\\<G>l\" \n  by (auto simp: \\<G>_def \\<P>L\\<G>l_def v_gs_def \\<G>l_def)\n\nfun SET :: \"'a mformula \\<Rightarrow> graph set\" where\n  \"SET FALSE = {}\" \n| \"SET (Var x) = {{\\<pi> x}}\" \n| \"SET (Disj \\<phi> \\<psi>) = SET \\<phi> \\<union> SET \\<psi>\" \n| \"SET (Conj \\<phi> \\<psi>) = SET \\<phi> \\<odot> SET \\<psi>\" \n\nlemma ACC_cf_SET[simp]: \n  \"ACC_cf (SET (Var x)) = {f \\<in> \\<F>. \\<pi> x \\<in> C f}\" \n  \"ACC_cf (SET FALSE) = {}\"\n  \"ACC_cf (SET (Disj \\<phi> \\<psi>)) = ACC_cf (SET \\<phi>) \\<union> ACC_cf (SET \\<psi>)\"\n  \"ACC_cf (SET (Conj \\<phi> \\<psi>)) = ACC_cf (SET \\<phi>) \\<inter> ACC_cf (SET \\<psi>)\"\n  using ACC_cf_odot \n  by (auto simp: ACC_cf_union ACC_cf_empty, auto simp: ACC_cf_def accepts_def)\n\nlemma ACC_SET[simp]: \n  \"ACC (SET (Var x)) = {G \\<in> \\<G>. \\<pi> x \\<in> G}\" \n  \"ACC (SET FALSE) = {}\"\n  \"ACC (SET (Disj \\<phi> \\<psi>)) = ACC (SET \\<phi>) \\<union> ACC (SET \\<psi>)\"\n  \"ACC (SET (Conj \\<phi> \\<psi>)) = ACC (SET \\<phi>) \\<inter> ACC (SET \\<psi>)\"\n  by (auto simp: ACC_union ACC_odot, auto simp: ACC_def accepts_def)\n\nlemma SET_\\<G>: \"\\<phi> \\<in> tf_mformula \\<Longrightarrow> \\<phi> \\<in> \\<A> \\<Longrightarrow> SET \\<phi> \\<subseteq> \\<G>\" \nproof (induct \\<phi> rule: tf_mformula.induct)\n  case (tf_Conj \\<phi> \\<psi>)\n  hence \"SET \\<phi> \\<subseteq> \\<G>\" \"SET \\<psi> \\<subseteq> \\<G>\" by auto\n  from odot_\\<G>[OF this] show ?case by simp\nqed auto\n  \nfun APR :: \"'a mformula \\<Rightarrow> graph set\" where\n  \"APR FALSE = {}\" \n| \"APR (Var x) = {{\\<pi> x}}\" \n| \"APR (Disj \\<phi> \\<psi>) = APR \\<phi> \\<squnion> APR \\<psi>\" \n| \"APR (Conj \\<phi> \\<psi>) = APR \\<phi> \\<sqinter> APR \\<psi>\" \n\nlemma APR: \"\\<phi> \\<in> tf_mformula \\<Longrightarrow> \\<phi> \\<in> \\<A> \\<Longrightarrow> APR \\<phi> \\<in> \\<P>L\\<G>l\"\n  by (induct \\<phi> rule: tf_mformula.induct, auto intro!: sqcup sqcap)\n\ndefinition ACC_cf_mf :: \"'a mformula \\<Rightarrow> colorf set\" where\n  \"ACC_cf_mf \\<phi> = ACC_cf (SET \\<phi>)\" \n\ndefinition ACC_mf :: \"'a mformula \\<Rightarrow> graph set\" where\n  \"ACC_mf \\<phi> = ACC (SET \\<phi>)\" \n\ndefinition deviate_pos :: \"'a mformula \\<Rightarrow> graph set\" (\"\\<partial>Pos\") where\n  \"\\<partial>Pos \\<phi> = POS \\<inter> ACC_mf \\<phi> - ACC (APR \\<phi>)\" \n\ndefinition deviate_neg :: \"'a mformula \\<Rightarrow> colorf set\" (\"\\<partial>Neg\") where\n  \"\\<partial>Neg \\<phi> = ACC_cf (APR \\<phi>) - ACC_cf_mf \\<phi>\" \n\ntext \\<open>Lemma 11.1\\<close>\n\nlemma deviate_subset_Disj: \n  \"\\<partial>Pos (Disj \\<phi> \\<psi>) \\<subseteq> \\<partial>\\<squnion>Pos (APR \\<phi>) (APR \\<psi>) \\<union> \\<partial>Pos \\<phi> \\<union> \\<partial>Pos \\<psi>\"\n  \"\\<partial>Neg (Disj \\<phi> \\<psi>) \\<subseteq> \\<partial>\\<squnion>Neg (APR \\<phi>) (APR \\<psi>) \\<union> \\<partial>Neg \\<phi> \\<union> \\<partial>Neg \\<psi>\"\n  unfolding \n    deviate_pos_def deviate_pos_cup_def  \n    deviate_neg_def deviate_neg_cup_def \n    ACC_cf_mf_def ACC_cf_SET ACC_cf_union \n    ACC_mf_def ACC_SET ACC_union \n  by auto\n\ntext \\<open>Lemma 11.2\\<close>\n\nlemma deviate_subset_Conj: \n  \"\\<partial>Pos (Conj \\<phi> \\<psi>) \\<subseteq> \\<partial>\\<sqinter>Pos (APR \\<phi>) (APR \\<psi>) \\<union> \\<partial>Pos \\<phi> \\<union> \\<partial>Pos \\<psi>\" \n  \"\\<partial>Neg (Conj \\<phi> \\<psi>) \\<subseteq> \\<partial>\\<sqinter>Neg (APR \\<phi>) (APR \\<psi>) \\<union> \\<partial>Neg \\<phi> \\<union> \\<partial>Neg \\<psi>\" \n   unfolding \n    deviate_pos_def deviate_pos_cap_def \n    ACC_mf_def ACC_SET ACC_odot\n    deviate_neg_def deviate_neg_cap_def \n    ACC_cf_mf_def ACC_cf_SET ACC_cf_odot \n   by auto \n\nlemmas deviate_subset = deviate_subset_Disj deviate_subset_Conj\n\nlemma deviate_finite: \n  \"finite (\\<partial>Pos \\<phi>)\" \n  \"finite (\\<partial>Neg \\<phi>)\" \n  \"finite (\\<partial>\\<squnion>Pos A B)\" \n  \"finite (\\<partial>\\<squnion>Neg A B)\" \n  \"finite (\\<partial>\\<sqinter>Pos A B)\" \n  \"finite (\\<partial>\\<sqinter>Neg A B)\" \n  unfolding \n    deviate_pos_def deviate_pos_cup_def deviate_pos_cap_def \n    deviate_neg_def deviate_neg_cup_def deviate_neg_cap_def \n  by (intro finite_subset[OF _ finite_POS_NEG], auto)+\n\ntext \\<open>Lemma 12\\<close>\n\nlemma no_deviation[simp]: \n  \"\\<partial>Pos FALSE = {}\"\n  \"\\<partial>Neg FALSE = {}\"\n  \"\\<partial>Pos (Var x) = {}\"\n  \"\\<partial>Neg (Var x) = {}\"\n  unfolding deviate_pos_def deviate_neg_def\n  by (auto simp add: ACC_cf_mf_def ACC_mf_def)\n\ntext \\<open>Lemma 12.1-2\\<close>\n\nfun approx_pos where\n  \"approx_pos (Conj phi psi) = \\<partial>\\<sqinter>Pos (APR phi) (APR psi)\" \n| \"approx_pos _ = {}\" \n\nfun approx_neg where\n  \"approx_neg (Conj phi psi) = \\<partial>\\<sqinter>Neg (APR phi) (APR psi)\" \n| \"approx_neg (Disj phi psi) = \\<partial>\\<squnion>Neg (APR phi) (APR psi)\" \n| \"approx_neg _ = {}\"  \n\nlemma finite_approx_pos: \"finite (approx_pos \\<phi>)\"\n  by (cases \\<phi>, auto intro: deviate_finite)\n\nlemma finite_approx_neg: \"finite (approx_neg \\<phi>)\"\n  by (cases \\<phi>, auto intro: deviate_finite)\n\nlemma card_deviate_Pos: assumes phi: \"\\<phi> \\<in> tf_mformula\" \"\\<phi> \\<in> \\<A>\" \n  shows \"card (\\<partial>Pos \\<phi>) \\<le> cs \\<phi> * L\\<^sup>2 * ( (m - l - 1) choose (k - l - 1))\" \nproof -\n  let ?Pos = \"\\<lambda> \\<phi>. \\<Union> (approx_pos ` SUB \\<phi>)\"  \n  have \"\\<partial>Pos \\<phi> \\<subseteq> ?Pos \\<phi>\" \n    using phi\n  proof (induct \\<phi> rule: tf_mformula.induct)\n    case (tf_Disj \\<phi> \\<psi>)\n    from tf_Disj have *: \"\\<phi> \\<in> tf_mformula\" \"\\<psi> \\<in> tf_mformula\" \"\\<phi> \\<in> \\<A>\" \"\\<psi> \\<in> \\<A>\" by auto\n    note IH = tf_Disj(2)[OF *(3)] tf_Disj(4)[OF *(4)]\n    have \"\\<partial>Pos (Disj \\<phi> \\<psi>) \\<subseteq> \\<partial>\\<squnion>Pos (APR \\<phi>) (APR \\<psi>) \\<union> \\<partial>Pos \\<phi> \\<union> \\<partial>Pos \\<psi>\"\n      by (rule deviate_subset)\n    also have \"\\<partial>\\<squnion>Pos (APR \\<phi>) (APR \\<psi>) = {}\"  \n      by (rule deviate_pos_cup; intro APR * )\n    also have \"\\<dots> \\<union> \\<partial>Pos \\<phi> \\<union> \\<partial>Pos \\<psi> \\<subseteq> ?Pos \\<phi> \\<union> ?Pos \\<psi>\" using IH by auto\n    also have \"\\<dots> \\<subseteq> ?Pos (Disj \\<phi> \\<psi>) \\<union> ?Pos (Disj \\<phi> \\<psi>)\" \n      by (intro Un_mono, auto)\n    finally show ?case by simp\n  next\n    case (tf_Conj \\<phi> \\<psi>)\n    from tf_Conj have *: \"\\<phi> \\<in> \\<A>\" \"\\<psi> \\<in> \\<A>\"  \n      by (auto intro: tf_mformula.intros)\n    note IH = tf_Conj(2)[OF *(1)] tf_Conj(4)[OF *(2)]\n    have \"\\<partial>Pos (Conj \\<phi> \\<psi>) \\<subseteq> \\<partial>\\<sqinter>Pos (APR \\<phi>) (APR \\<psi>) \\<union> \\<partial>Pos \\<phi> \\<union> \\<partial>Pos \\<psi>\"\n      by (rule deviate_subset)\n    also have \"\\<dots> \\<subseteq> \\<partial>\\<sqinter>Pos (APR \\<phi>) (APR \\<psi>) \\<union> ?Pos \\<phi> \\<union> ?Pos \\<psi>\" using IH by auto\n    also have \"\\<dots> \\<subseteq> ?Pos (Conj \\<phi> \\<psi>) \\<union> ?Pos (Conj \\<phi> \\<psi>) \\<union> ?Pos (Conj \\<phi> \\<psi>)\" \n      by (intro Un_mono, insert *, auto)\n    finally show ?case by simp\n  qed auto\n  from card_mono[OF finite_UN_I[OF finite_SUB finite_approx_pos] this]\n  have \"card (\\<partial>Pos \\<phi>) \\<le> card (\\<Union> (approx_pos ` SUB \\<phi>))\" by simp\n  also have \"\\<dots> \\<le> (\\<Sum>i\\<in>SUB \\<phi>. card (approx_pos i))\" \n    by (rule card_UN_le[OF finite_SUB])\n  also have \"\\<dots> \\<le> (\\<Sum>i\\<in>SUB \\<phi>. L\\<^sup>2 * ( (m - l - 1) choose (k - l - 1)))\" \n  proof (rule sum_mono, goal_cases)\n    case (1 psi)\n    from phi 1 have psi: \"psi \\<in> tf_mformula\" \"psi \\<in> \\<A>\"\n      by (induct \\<phi> rule: tf_mformula.induct, auto intro: tf_mformula.intros)\n    show ?case \n    proof (cases psi)\n      case (Conj phi1 phi2)\n      from psi this have *: \"phi1 \\<in> tf_mformula\" \"phi1 \\<in> \\<A>\" \"phi2 \\<in> tf_mformula\" \"phi2 \\<in> \\<A>\" \n        by (cases rule: tf_mformula.cases, auto)+\n      from deviate_pos_cap[OF APR[OF *(1-2)] APR[OF *(3-4)]]\n      show ?thesis unfolding Conj by (simp add: ac_simps)\n    qed auto\n  qed\n  also have \"\\<dots> = cs \\<phi> * L\\<^sup>2 * ( (m - l - 1) choose (k - l - 1))\" unfolding cs_def by simp\n  finally show \"card (\\<partial>Pos \\<phi>) \\<le> cs \\<phi> * L\\<^sup>2 * (m - l - 1 choose (k - l - 1))\" by simp\nqed\n\nlemma card_deviate_Neg: assumes phi: \"\\<phi> \\<in> tf_mformula\" \"\\<phi> \\<in> \\<A>\" \n  shows \"card (\\<partial>Neg \\<phi>) \\<le> cs \\<phi> * L\\<^sup>2 * (k - 1)^m / 2^(p - 1)\"\nproof -\n  let ?r = real\n  let ?Neg = \"\\<lambda> \\<phi>. \\<Union> (approx_neg ` SUB \\<phi>)\"  \n  have \"\\<partial>Neg \\<phi> \\<subseteq> ?Neg \\<phi>\" \n    using phi\n  proof (induct \\<phi> rule: tf_mformula.induct)\n    case (tf_Disj \\<phi> \\<psi>)\n    from tf_Disj have *: \"\\<phi> \\<in> tf_mformula\" \"\\<psi> \\<in> tf_mformula\" \"\\<phi> \\<in> \\<A>\" \"\\<psi> \\<in> \\<A>\" by auto\n    note IH = tf_Disj(2)[OF *(3)] tf_Disj(4)[OF *(4)]\n    have \"\\<partial>Neg (Disj \\<phi> \\<psi>) \\<subseteq> \\<partial>\\<squnion>Neg (APR \\<phi>) (APR \\<psi>) \\<union> \\<partial>Neg \\<phi> \\<union> \\<partial>Neg \\<psi>\"\n      by (rule deviate_subset)\n    also have \"\\<dots> \\<subseteq> \\<partial>\\<squnion>Neg (APR \\<phi>) (APR \\<psi>) \\<union> ?Neg \\<phi> \\<union> ?Neg \\<psi>\" using IH by auto\n    also have \"\\<dots> \\<subseteq> ?Neg (Disj \\<phi> \\<psi>) \\<union> ?Neg (Disj \\<phi> \\<psi>)  \\<union> ?Neg (Disj \\<phi> \\<psi>)\" \n      by (intro Un_mono, auto)\n    finally show ?case by simp\n  next\n    case (tf_Conj \\<phi> \\<psi>)\n    from tf_Conj have *: \"\\<phi> \\<in> \\<A>\" \"\\<psi> \\<in> \\<A>\"  \n      by (auto intro: tf_mformula.intros)\n    note IH = tf_Conj(2)[OF *(1)] tf_Conj(4)[OF *(2)]\n    have \"\\<partial>Neg (Conj \\<phi> \\<psi>) \\<subseteq> \\<partial>\\<sqinter>Neg (APR \\<phi>) (APR \\<psi>) \\<union> \\<partial>Neg \\<phi> \\<union> \\<partial>Neg \\<psi>\"\n      by (rule deviate_subset)\n    also have \"\\<dots> \\<subseteq> \\<partial>\\<sqinter>Neg (APR \\<phi>) (APR \\<psi>) \\<union> ?Neg \\<phi> \\<union> ?Neg \\<psi>\" using IH by auto\n    also have \"\\<dots> \\<subseteq> ?Neg (Conj \\<phi> \\<psi>) \\<union> ?Neg (Conj \\<phi> \\<psi>)  \\<union> ?Neg (Conj \\<phi> \\<psi>)\" \n      by (intro Un_mono, auto)\n    finally show ?case by simp\n  qed auto\n  hence \"\\<partial>Neg \\<phi> \\<subseteq> \\<Union> (approx_neg ` SUB \\<phi>)\" by auto\n  from card_mono[OF finite_UN_I[OF finite_SUB finite_approx_neg] this]\n  have \"card (\\<partial>Neg \\<phi>) \\<le> card (\\<Union> (approx_neg ` SUB \\<phi>))\" .\n  also have \"\\<dots> \\<le> (\\<Sum>i\\<in>SUB \\<phi>. card (approx_neg i))\" \n    by (rule card_UN_le[OF finite_SUB])\n  finally have \"?r (card (\\<partial>Neg \\<phi>)) \\<le> (\\<Sum>i\\<in>SUB \\<phi>. card (approx_neg i))\" by linarith\n  also have \"\\<dots> = (\\<Sum>i\\<in>SUB \\<phi>. ?r (card (approx_neg i)))\" by simp \n  also have \"\\<dots> \\<le> (\\<Sum>i\\<in>SUB \\<phi>. L^2 * (k - 1)^m / 2^(p - 1))\" \n  proof (rule sum_mono, goal_cases)\n    case (1 psi)\n    from phi 1 have psi: \"psi \\<in> tf_mformula\" \"psi \\<in> \\<A>\"\n      by (induct \\<phi> rule: tf_mformula.induct, auto intro: tf_mformula.intros)\n    show ?case \n    proof (cases psi)\n      case (Conj phi1 phi2)\n      from psi this have *: \"phi1 \\<in> tf_mformula\" \"phi1 \\<in> \\<A>\" \"phi2 \\<in> tf_mformula\" \"phi2 \\<in> \\<A>\" \n        by (cases rule: tf_mformula.cases, auto)+\n      from deviate_neg_cap[OF APR[OF *(1-2)] APR[OF *(3-4)]]\n      show ?thesis unfolding Conj by (simp add: ac_simps)\n    next\n      case (Disj phi1 phi2)\n      from psi this have *: \"phi1 \\<in> tf_mformula\" \"phi1 \\<in> \\<A>\" \"phi2 \\<in> tf_mformula\" \"phi2 \\<in> \\<A>\" \n        by (cases rule: tf_mformula.cases, auto)+\n      from deviate_neg_cup[OF APR[OF *(1-2)] APR[OF *(3-4)]]\n      have \"card (approx_neg psi) \\<le> ((L * 1) * (k - 1) ^ m) / 2 ^ (p - 1)\" \n        unfolding Disj by (simp add: ac_simps)\n      also have \"\\<dots> \\<le> ((L * L) * (k - 1) ^ m) / 2 ^ (p - 1)\" \n        by (intro divide_right_mono, unfold of_nat_le_iff, intro mult_mono, insert L3, auto)  \n      finally show ?thesis unfolding power2_eq_square by simp\n    qed auto\n  qed\n  also have \"\\<dots> = cs \\<phi> * L^2 * (k - 1)^m / 2^(p - 1)\" unfolding cs_def by simp\n  finally show \"card (\\<partial>Neg \\<phi>) \\<le> cs \\<phi> * L\\<^sup>2 * (k - 1)^m / 2^(p - 1)\" . \nqed\n\n\ntext \\<open>Lemma 12.3\\<close>\n\nlemma ACC_cf_non_empty_approx: assumes phi: \"\\<phi> \\<in> tf_mformula\" \"\\<phi> \\<in> \\<A>\"\n  and ne: \"APR \\<phi> \\<noteq> {}\" \nshows \"card (ACC_cf (APR \\<phi>)) > (k - 1)^m / 3\" \nproof -\n  from ne obtain E :: graph where Ephi: \"E \\<in> APR \\<phi>\"   \n    by (auto simp: ACC_def accepts_def)\n  from APR[OF phi, unfolded \\<P>L\\<G>l_def] Ephi \n  have EDl: \"E \\<in> \\<G>l\" by auto\n  hence vEl: \"card (v E) \\<le> l\" and ED: \"E \\<in> \\<G>\" \n    unfolding \\<G>l_def \\<G>l_def by auto\n  have E: \"E \\<in> \\<G>\" using ED[unfolded \\<G>l_def] by auto\n  have sub: \"v E \\<subseteq> [m]\" by (rule v_\\<G>[OF E]) \n  have \"l \\<le> card [m]\" using lm by auto\n  from exists_subset_between[OF vEl this sub finite_numbers]\n  obtain V where V: \"v E \\<subseteq> V\" \"V \\<subseteq> [m]\" \"card V = l\" by auto\n  from finite_subset[OF V(2)] have finV: \"finite V\" by auto\n  have finPart: \"finite A\" if \"A \\<subseteq> {P. partition_on [n] P}\" for n A\n    by (rule finite_subset[OF that finitely_many_partition_on], simp)\n  have finmv: \"finite ([m] - V)\" using finite_numbers[of m] by auto\n  have finK: \"finite [k - 1]\" unfolding numbers_def by auto\n  define F where \"F = {f \\<in> [m] \\<rightarrow>\\<^sub>E [k - 1]. inj_on f V}\" \n  have FF: \"F \\<subseteq> \\<F>\" unfolding \\<F>_def F_def by auto\n  {\n    fix f\n    assume f: \"f \\<in> F\" \n    {\n      from this[unfolded F_def]\n      have f: \"f \\<in> [m] \\<rightarrow>\\<^sub>E [k - 1]\" and inj: \"inj_on f V\" by auto\n      from V l2 have 2: \"card V \\<ge> 2\" by auto\n      then obtain x where x: \"x \\<in> V\" by (cases \"V = {}\", auto)\n      have \"card V = card (V - {x}) + 1\" using x finV\n        by (metis One_nat_def add.right_neutral add_Suc_right card_Suc_Diff1)\n      with 2 have \"card (V - {x}) > 0\" by auto\n      hence \"V - {x} \\<noteq> {}\" by fastforce\n      then obtain y where y: \"y \\<in> V\" and diff: \"x \\<noteq> y\" by auto\n      from inj diff x y have neq: \"f x \\<noteq> f y\" by (auto simp: inj_on_def)\n      from x y diff V have \"{x, y} \\<in> [m]^\\<two>\" unfolding sameprod_altdef by auto\n      with neq have \"{x,y} \\<in> C f\" unfolding C_def by auto\n      hence \"C f \\<noteq> {}\" by auto\n    }\n    with NEG_\\<G> FF f have CfG: \"C f \\<in> \\<G>\" \"C f \\<noteq> {}\" by (auto simp: NEG_def)\n    have \"E \\<subseteq> C f\" \n    proof\n      fix e\n      assume eE: \"e \\<in> E\" \n      with E[unfolded \\<G>_def] have em: \"e \\<in> [m]^\\<two>\" by auto\n      then obtain x y where e: \"e = {x,y}\" \"x \\<noteq> y\" \"{x,y} \\<subseteq> [m]\" \n        and card: \"card e = 2\" \n        unfolding binprod_def by auto\n      from v_mem_sub[OF card eE]\n      have \"{x,y} \\<subseteq> v E\" using e by auto\n      hence \"{x,y} \\<subseteq> V\" using V by auto\n      hence \"f x \\<noteq> f y\" using e(2) f[unfolded F_def] by (auto simp: inj_on_def)\n      thus \"e \\<in> C f\" unfolding C_def using em e by auto\n    qed\n    with Ephi CfG have \"APR \\<phi> \\<tturnstile> C f\" \n      unfolding accepts_def by auto\n    hence \"f \\<in> ACC_cf (APR \\<phi>)\" using CfG f FF unfolding ACC_cf_def by auto\n  }  \n  with FF have sub: \"F \\<subseteq> ACC_cf (APR \\<phi>)\" by auto\n  from card_mono[OF finite_subset[OF _ finite_ACC] this]\n  have approx: \"card F \\<le> card (ACC_cf (APR \\<phi>))\" by auto\n  from card_inj_on_subset_funcset[OF finite_numbers finK V(2), unfolded card_numbers V(3),\n      folded F_def]\n  have \"real (card F) = (real (k - 1)) ^ (m - l) * prod (\\<lambda> i. real (k - 1 - i)) {0..<l}\" \n    by simp\n  also have \"\\<dots> > (real (k - 1)) ^ m / 3\" \n    by (rule approximation1)\n  finally have cardF: \"card F > (k - 1) ^ m / 3\" by simp\n  with approx show ?thesis by simp\nqed\n\ntext \\<open>Theorem 13\\<close>\n                                \nlemma theorem_13: assumes phi: \"\\<phi> \\<in> tf_mformula\" \"\\<phi> \\<in> \\<A>\" \n  and sub: \"POS \\<subseteq> ACC_mf \\<phi>\" \"ACC_cf_mf \\<phi> = {}\" \nshows \"cs \\<phi> > k powr (4 / 7 * sqrt k)\" \nproof -\n  let ?r = \"real :: nat \\<Rightarrow> real\" \n  have \"cs \\<phi> > ((m - l) / k)^l / (6 * L^2)\" \n  proof (cases \"POS \\<inter> ACC (APR \\<phi>) = {}\")\n    case empty: True\n    have \"\\<partial>Pos \\<phi> = POS \\<inter> ACC_mf \\<phi> - ACC (APR \\<phi>)\" unfolding deviate_pos_def by auto\n    also have \"\\<dots> = POS - ACC (APR \\<phi>)\" using sub by blast\n    also have \"\\<dots> = POS\" using empty by auto\n    finally have id: \"\\<partial>Pos \\<phi> = POS\" by simp \n    have \"m choose k = card POS\" by (simp add: card_POS)\n    also have \"\\<dots> = card (\\<partial>Pos \\<phi>)\" unfolding id by simp\n    also have \"\\<dots> \\<le> cs \\<phi> * L\\<^sup>2 * (m - l - 1 choose (k - l - 1))\" using card_deviate_Pos[OF phi] by auto\n    finally have \"m choose k \\<le> cs \\<phi> * L\\<^sup>2 * (m - l - 1 choose (k - l - 1))\" \n      by simp\n    from approximation2[OF this]\n    show \"((m - l) / k)^l / (6 * L^2) < cs \\<phi>\" by simp\n  next\n    case False    \n    have \"POS \\<inter> ACC (APR \\<phi>) \\<noteq> {}\" by fact\n    hence nempty: \"APR \\<phi> \\<noteq> {}\" by auto\n    have \"card (\\<partial>Neg \\<phi>) = card (ACC_cf (APR \\<phi>) - ACC_cf_mf \\<phi>)\" unfolding deviate_neg_def by auto\n    also have \"\\<dots> = card (ACC_cf (APR \\<phi>))\" using sub by auto\n    also have \"\\<dots> > (k - 1)^m / 3\" using ACC_cf_non_empty_approx[OF phi nempty] . \n    finally have \"(k - 1)^m / 3 < card (\\<partial>Neg \\<phi>)\" .\n    also have \"\\<dots> \\<le> cs \\<phi> * L\\<^sup>2 * (k - 1) ^ m / 2 ^ (p - 1)\" \n      using card_deviate_Neg[OF phi] sub by auto\n    finally have \"(k - 1)^m / 3 < (cs \\<phi> * (L\\<^sup>2 * (k - 1) ^ m)) / 2 ^ (p - 1)\" by simp\n    from approximation3[OF this] show ?thesis .\n  qed\n  hence part1: \"cs \\<phi> > ((m - l) / k)^l / (6 * L^2)\" .\n  from approximation4[OF this] show ?thesis using k2 by simp\nqed\n\ntext \\<open>Definition 14\\<close>\n\ndefinition eval_g :: \"'a VAS \\<Rightarrow> graph \\<Rightarrow> bool\" where\n  \"eval_g \\<theta> G = (\\<forall> v \\<in> \\<V>. (\\<pi> v \\<in> G \\<longrightarrow> \\<theta> v))\" \n\ndefinition eval_gs :: \"'a VAS \\<Rightarrow> graph set \\<Rightarrow> bool\" where\n  \"eval_gs \\<theta> X = (\\<exists> G \\<in> X. eval_g \\<theta> G)\" \n\n\nlemmas eval_simps = eval_g_def eval_gs_def eval.simps\n\nlemma eval_gs_union: \n  \"eval_gs \\<theta> (X \\<union> Y) = (eval_gs \\<theta> X \\<or> eval_gs \\<theta> Y)\" \n  by (auto simp: eval_gs_def)\n\nlemma eval_gs_odot: assumes \"X \\<subseteq> \\<G>\" \"Y \\<subseteq> \\<G>\"  \n  shows \"eval_gs \\<theta> (X \\<odot> Y) = (eval_gs \\<theta> X \\<and> eval_gs \\<theta> Y)\" \nproof\n  assume \"eval_gs \\<theta> (X \\<odot> Y)\" \n  from this[unfolded eval_gs_def] obtain DE where DE: \"DE \\<in> X \\<odot> Y\"  \n    and eval: \"eval_g \\<theta> DE\" by auto\n  from DE[unfolded odot_def] obtain D E where id: \"DE = D \\<union> E\" and DE: \"D \\<in> X\" \"E \\<in> Y\" \n    by auto\n  from eval have \"eval_g \\<theta> D\" \"eval_g \\<theta> E\" unfolding id eval_g_def\n    by auto\n  with DE show \"eval_gs \\<theta> X \\<and> eval_gs \\<theta> Y\" unfolding eval_gs_def by auto\nnext\n  assume \"eval_gs \\<theta> X \\<and> eval_gs \\<theta> Y\" \n  then obtain D E where DE: \"D \\<in> X\" \"E \\<in> Y\" and eval: \"eval_g \\<theta> D\" \"eval_g \\<theta> E\" \n    unfolding eval_gs_def by auto\n  from DE assms have D: \"D \\<in> \\<G>\" \"E \\<in> \\<G>\" by auto  \n  let ?U = \"D \\<union> E\" \n  from eval have eval: \"eval_g \\<theta> ?U\" \n    unfolding eval_g_def by auto\n  from DE have 1: \"?U \\<in> X \\<odot> Y\" unfolding odot_def by auto\n  with 1 eval show \"eval_gs \\<theta> (X \\<odot> Y)\" unfolding eval_gs_def by auto\nqed \n\n\ntext \\<open>Lemma 15\\<close>\n\nlemma eval_set: assumes phi: \"\\<phi> \\<in> tf_mformula\" \"\\<phi> \\<in> \\<A>\"  \n  shows \"eval \\<theta> \\<phi> = eval_gs \\<theta> (SET \\<phi>)\" \n  using phi\nproof (induct \\<phi> rule: tf_mformula.induct)\n  case tf_False\n  then show ?case unfolding eval_simps by simp\nnext\n  case (tf_Var x)\n  then show ?case using inj_on_\\<pi> unfolding eval_simps \n    by (auto simp add: inj_on_def)\nnext\n  case (tf_Disj \\<phi>1 \\<phi>2)\n  thus ?case by (auto simp: eval_gs_union)\nnext\n  case (tf_Conj \\<phi>1 \\<phi>2)\n  thus ?case by (simp, intro eval_gs_odot[symmetric]; intro SET_\\<G>, auto)\nqed\n\ndefinition \\<theta>\\<^sub>g :: \"graph \\<Rightarrow> 'a VAS\" where\n  \"\\<theta>\\<^sub>g G x = (x \\<in> \\<V> \\<and> \\<pi> x \\<in> G)\" \n\ntext \\<open>From here on we deviate from Gordeev's paper as we do not use positive bases, but a more\n  direct approach.\\<close>\n\nlemma eval_ACC: assumes phi: \"\\<phi> \\<in> tf_mformula\"  \"\\<phi> \\<in> \\<A>\" \n  and G: \"G \\<in> \\<G>\" \nshows \"eval (\\<theta>\\<^sub>g G) \\<phi> = (G \\<in> ACC_mf \\<phi>)\"  \n  using phi unfolding ACC_mf_def\nproof (induct \\<phi> rule: tf_mformula.induct)\n  case (tf_Var x)\n  thus ?case by (auto simp: ACC_def G accepts_def \\<theta>\\<^sub>g_def)\nnext\n  case (tf_Disj phi psi)\n  thus ?case by (auto simp: ACC_union)\nnext\n  case (tf_Conj phi psi)\n  thus ?case by (auto simp: ACC_odot)\nqed simp\n\nlemma CLIQUE_solution_imp_POS_sub_ACC: assumes solution: \"\\<forall> G \\<in> \\<G>. G \\<in> CLIQUE \\<longleftrightarrow> eval (\\<theta>\\<^sub>g G) \\<phi>\" \n    and tf: \"\\<phi> \\<in> tf_mformula\"\n    and phi: \"\\<phi> \\<in> \\<A>\" \n  shows \"POS \\<subseteq> ACC_mf \\<phi>\" \nproof \n  fix G\n  assume POS: \"G \\<in> POS\" \n  with POS_\\<G> have G: \"G \\<in> \\<G>\" by auto\n  with POS solution POS_CLIQUE \n  have \"eval (\\<theta>\\<^sub>g G) \\<phi>\" by auto\n  thus \"G \\<in> ACC_mf \\<phi>\" unfolding eval_ACC[OF tf phi G] .\nqed\n\nlemma CLIQUE_solution_imp_ACC_cf_empty: assumes solution: \"\\<forall> G \\<in> \\<G>. G \\<in> CLIQUE \\<longleftrightarrow> eval (\\<theta>\\<^sub>g G) \\<phi>\" \n    and tf: \"\\<phi> \\<in> tf_mformula\"\n    and phi: \"\\<phi> \\<in> \\<A>\" \n  shows \"ACC_cf_mf \\<phi> = {}\" \nproof (rule ccontr)\n  assume \"\\<not> ?thesis\" \n  from this[unfolded ACC_cf_mf_def ACC_cf_def]\n  obtain F where F: \"F \\<in> \\<F>\" \"SET \\<phi> \\<tturnstile> C F\" by auto\n  define G where \"G = C F\" \n  have NEG: \"G \\<in> NEG\" unfolding NEG_def G_def using F by auto\n  hence \"G \\<notin> CLIQUE\" using CLIQUE_NEG by auto\n  have GG: \"G \\<in> \\<G>\" unfolding G_def using F\n    using G_def NEG NEG_\\<G> by blast\n  have GAcc: \"SET \\<phi> \\<tturnstile> G\" using F[folded G_def] by auto  \n  then obtain D :: graph where \n    D: \"D \\<in> SET \\<phi>\" and sub: \"D \\<subseteq> G\"\n    unfolding accepts_def by blast  \n  from SET_\\<G>[OF tf phi] D \n  have DG: \"D \\<in> \\<G>\" by auto\n  have eval: \"eval (\\<theta>\\<^sub>g D) \\<phi>\" unfolding eval_set[OF tf phi] eval_gs_def\n    by (intro bexI[OF _ D], unfold eval_g_def, insert DG, auto simp: \\<theta>\\<^sub>g_def) \n  hence \"D \\<in> CLIQUE\" using solution[rule_format, OF DG] by auto\n  hence \"G \\<in> CLIQUE\" using GG sub unfolding CLIQUE_def by blast\n  with \\<open>G \\<notin> CLIQUE\\<close> show False by auto\nqed\n\nsubsection \\<open>Conclusion\\<close>\n\ntext \\<open>Theorem 22\\<close>\n\ntext \\<open>We first consider monotone formulas without TRUE.\\<close>\n\ntheorem Clique_not_solvable_by_small_tf_mformula: assumes solution: \"\\<forall> G \\<in> \\<G>. G \\<in> CLIQUE \\<longleftrightarrow> eval (\\<theta>\\<^sub>g G) \\<phi>\" \n  and tf: \"\\<phi> \\<in> tf_mformula\"\n  and phi: \"\\<phi> \\<in> \\<A>\" \nshows \"cs \\<phi> > k powr (4 / 7 * sqrt k)\"\nproof -\n  from CLIQUE_solution_imp_POS_sub_ACC[OF solution tf phi] have POS: \"POS \\<subseteq> ACC_mf \\<phi>\" .\n  from CLIQUE_solution_imp_ACC_cf_empty[OF solution tf phi] have CF: \"ACC_cf_mf \\<phi> = {}\" .\n  from theorem_13[OF tf phi POS CF]\n  show ?thesis by auto \nqed\n\ntext \\<open>Next we consider general monotone formulas.\\<close>\n\ntheorem Clique_not_solvable_by_poly_mono: assumes solution: \"\\<forall> G \\<in> \\<G>. G \\<in> CLIQUE \\<longleftrightarrow> eval (\\<theta>\\<^sub>g G) \\<phi>\" \n  and phi: \"\\<phi> \\<in> \\<A>\" \nshows \"cs \\<phi> > k powr (4 / 7 * sqrt k)\"\nproof -\n  note vars = phi[unfolded \\<A>_def]\n  have CL: \"CLIQUE = Clique [k^4] k\" \"\\<G> = Graphs [k^4]\" \n    unfolding CLIQUE_def \\<K>_altdef m_def Clique_def by auto\n  with empty_CLIQUE have \"{} \\<notin> Clique [k^4] k\" by simp\n  with solution[rule_format, of \"{}\"] \n  have \"\\<not> eval (\\<theta>\\<^sub>g {}) \\<phi>\" by (auto simp: Graphs_def)\n  from to_tf_mformula[OF this]\n  obtain \\<psi> where *: \"\\<psi> \\<in> tf_mformula\" \n    \"(\\<forall>\\<theta>. eval \\<theta> \\<phi> = eval \\<theta> \\<psi>)\" \"vars \\<psi> \\<subseteq> vars \\<phi>\" \"cs \\<psi> \\<le> cs \\<phi>\" by auto\n  with phi solution have psi: \"\\<psi> \\<in> \\<A>\" \n    and solution: \"\\<forall>G\\<in>\\<G>. (G \\<in> CLIQUE) = eval (\\<theta>\\<^sub>g G) \\<psi>\" unfolding \\<A>_def by auto\n  from Clique_not_solvable_by_small_tf_mformula[OF solution *(1) psi]\n  show ?thesis using *(4) by auto\nqed\n\ntext \\<open>We next expand all abbreviations and definitions of the locale, but stay within the locale\\<close>\n\ntheorem Clique_not_solvable_by_small_monotone_circuit_in_locale: assumes phi_solves_clique: \n  \"\\<forall> G \\<in> Graphs [k^4]. G \\<in> Clique [k^4] k \\<longleftrightarrow> eval (\\<lambda> x. \\<pi> x \\<in> G) \\<phi>\" \n  and vars: \"vars \\<phi> \\<subseteq> \\<V>\" \nshows \"cs \\<phi> > k powr (4 / 7 * sqrt k)\"\nproof - \n  {\n    fix G\n    assume G: \"G \\<in> \\<G>\" \n    have \"eval (\\<lambda> x. \\<pi> x \\<in> G) \\<phi> = eval (\\<theta>\\<^sub>g G) \\<phi>\" using vars\n      by (intro eval_vars, auto simp: \\<theta>\\<^sub>g_def)\n  }\n  have CL: \"CLIQUE = Clique [k^4] k\" \"\\<G> = Graphs [k^4]\" \n    unfolding CLIQUE_def \\<K>_altdef m_def Clique_def by auto\n  {\n    fix G\n    assume G: \"G \\<in> \\<G>\" \n    have \"eval (\\<lambda> x. \\<pi> x \\<in> G) \\<phi> = eval (\\<theta>\\<^sub>g G) \\<phi>\" using vars\n      by (intro eval_vars, auto simp: \\<theta>\\<^sub>g_def)\n  }\n  with phi_solves_clique  CL have solves: \"\\<forall> G \\<in> \\<G>. G \\<in> CLIQUE \\<longleftrightarrow> eval (\\<theta>\\<^sub>g G) \\<phi>\"\n    by auto\n  from vars have inA: \"\\<phi> \\<in> \\<A>\" by (auto simp: \\<A>_def)\n  from Clique_not_solvable_by_poly_mono[OF solves inA] \n  show ?thesis by auto\nqed\nend\n\n\ntext \\<open>Let us now move the theorem outside the locale\\<close>\n\ndefinition Large_Number where \"Large_Number = Max {64, L0''^2, L0^2, L0'^2, M0, M0'}\" \n\ntheorem Clique_not_solvable_by_small_monotone_circuit_squared: \n  fixes \\<phi> :: \"'a mformula\" \n  assumes k: \"\\<exists> l. k = l^2\" \n  and LARGE: \"k \\<ge> Large_Number\" \n  and \\<pi>: \"bij_betw \\<pi> V [k^4]^\\<two>\" \n  and solution: \"\\<forall>G\\<in>Graphs [k ^ 4]. (G \\<in> Clique [k ^ 4] k) = eval (\\<lambda> x. \\<pi> x \\<in> G) \\<phi>\" \n  and vars: \"vars \\<phi> \\<subseteq> V\" \n  shows \"cs \\<phi> > k powr (4 / 7 * sqrt k)\" \nproof -\n  from k obtain l where kk: \"k = l^2\" by auto\n  note LARGE = LARGE[unfolded Large_Number_def]\n  have k8: \"k \\<ge> 8^2\" using LARGE by auto\n  from this[unfolded kk power2_nat_le_eq_le] \n  have l8: \"l \\<ge> 8\" .  \n  define p where \"p = nat (ceiling (l * log 2 (k^4)))\"  \n  have tedious: \"l * log 2 (k ^ 4) \\<ge> 0\" using l8 k8 by auto\n  have \"int p = ceiling (l * log 2 (k ^ 4))\" unfolding p_def\n    by (rule nat_0_le, insert tedious, auto)\n  from arg_cong[OF this, of real_of_int]\n  have rp: \"real p = ceiling (l * log 2 (k ^ 4))\" by simp  \n  have one: \"real l * log 2 (k ^ 4) \\<le> p\" unfolding rp by simp\n  have two: \"p \\<le> real l * log 2 (k ^ 4) + 1\" unfolding rp by simp\n  have \"real l < real l + 1 \" by simp\n  also have \"\\<dots> \\<le> real l + real l\" using l8 by simp\n  also have \"\\<dots> = real l * 2\" by simp\n  also have \"\\<dots> = real l * log 2 (2^2)\" \n    by (subst log_pow_cancel, auto)\n  also have \"\\<dots> \\<le> real l * log 2 (k ^ 4)\" \n  proof (intro mult_left_mono, subst log_le_cancel_iff)\n    have \"(4 :: real) \\<le> 2^4\" by simp\n    also have \"\\<dots> \\<le> real k^4\" \n      by (rule power_mono, insert k8, auto)\n    finally show \"2\\<^sup>2 \\<le> real (k ^ 4)\" by simp\n  qed (insert k8, auto)\n  also have \"\\<dots> \\<le> p\" by fact\n  finally have lp: \"l < p\" by auto  \n  interpret second_assumptions l p k\n  proof (unfold_locales)\n    show \"2 < l\" using l8 by auto\n    show \"8 \\<le> l\" by fact\n    show \"k = l^2\" by fact\n    show \"l < p\" by fact\n    from LARGE have \"L0''^2 \\<le> k\" by auto\n    from this[unfolded kk power2_nat_le_eq_le] \n    have L0''l: \"L0'' \\<le> l\" .\n    have \"p \\<le> real l * log 2 (k ^ 4) + 1\" by fact\n    also have \"\\<dots> < k\" unfolding kk \n      by (intro L0'' L0''l)\n    finally show \"p < k\" by simp\n  qed    \n  interpret third_assumptions l p k  \n  proof \n    show \"real l * log 2 (real m) \\<le> p\" using one unfolding m_def .\n    show \"p \\<le> real l * log 2 (real m) + 1\" using two unfolding m_def .\n    from LARGE have \"L0^2 \\<le> k\" by auto\n    from this[unfolded kk power2_nat_le_eq_le] \n    show \"L0 \\<le> l\" .\n    from LARGE have \"L0'^2 \\<le> k\" by auto\n    from this[unfolded kk power2_nat_le_eq_le] \n    show \"L0' \\<le> l\" .\n    show \"M0' \\<le> m\" using km LARGE by simp\n    show \"M0 \\<le> m\" using km LARGE by simp\n  qed\n  interpret forth_assumptions l p k V \\<pi> \n    by (standard, insert \\<pi> m_def, auto simp: bij_betw_same_card[OF \\<pi>])\n  from Clique_not_solvable_by_small_monotone_circuit_in_locale[OF solution vars] \n  show ?thesis .\nqed\n\ntext \\<open>A variant where we get rid of the @{term \"k = l^2\"}-assumption by just taking squares everywhere.\\<close>\n\ntheorem Clique_not_solvable_by_small_monotone_circuit: \n  fixes \\<phi> :: \"'a mformula\" \n  assumes LARGE: \"k \\<ge> Large_Number\" \n  and \\<pi>: \"bij_betw \\<pi> V [k^8]^\\<two>\" \n  and solution: \"\\<forall>G\\<in>Graphs [k ^ 8]. (G \\<in> Clique [k ^ 8] (k^2)) = eval (\\<lambda> x. \\<pi> x \\<in> G) \\<phi>\" \n  and vars: \"vars \\<phi> \\<subseteq> V\" \nshows \"cs \\<phi> > k powr (8 / 7 * k)\" \nproof -\n  from LARGE have LARGE: \"Large_Number \\<le> k\\<^sup>2\" \n    by (simp add: power2_nat_le_imp_le)\n  have id: \"k\\<^sup>2 ^ 4 = k^8\" \"sqrt (k^2) = k\" by auto\n  from Clique_not_solvable_by_small_monotone_circuit_squared[of \"k^2\", unfolded id, OF _ LARGE \\<pi> solution vars]\n  have \"cs \\<phi> > (k^2) powr (4 / 7 * k)\" by auto\n  also have \"(k^2) powr (4 / 7 * k) = k powr (8 / 7 * k)\"\n    unfolding of_nat_power using powr_powr[of \"real k\" 2] by simp\n  finally show ?thesis .\nqed\n\ndefinition large_number where \"large_number = Large_Number^8\" \n\ntext \\<open>Finally a variant, where the size is formulated depending on $n$, the number of vertices.\\<close>\n\ntheorem Clique_with_n_nodes_not_solvable_by_small_monotone_circuit:\n  fixes \\<phi> :: \"'a mformula\" \n  assumes large: \"n \\<ge> large_number\" \n  and kn: \"\\<exists> k. n = k^8\" \n  and \\<pi>: \"bij_betw \\<pi> V [n]^\\<two>\" \n  and s: \"s = root 4 n\" \n  and solution: \"\\<forall>G\\<in>Graphs [n]. (G \\<in> Clique [n] s) = eval (\\<lambda> x. \\<pi> x \\<in> G) \\<phi>\" \n  and vars: \"vars \\<phi> \\<subseteq> V\" \nshows \"cs \\<phi> > (root 7 n) powr (root 8 n)\" \nproof -\n  from kn obtain k where nk: \"n = k^8\" by auto\n  have kn: \"k = root 8 n\" unfolding nk of_nat_power\n    by (subst real_root_pos2, auto)\n  have \"root 4 n = root 4 ((real (k^2))^4)\" unfolding nk by simp\n  also have \"\\<dots> = k^2\" by (simp add: real_root_pos_unique)\n  finally have r4: \"root 4 n = k^2\" by simp\n  have s: \"s = k^2\" using s unfolding r4 by simp\n  from large[unfolded nk large_number_def] have Large: \"k \\<ge> Large_Number\" by simp\n  have \"0 < Large_Number\" unfolding Large_Number_def by simp\n  with Large have k0: \"k > 0\" by auto\n  hence n0: \"n > 0\" using nk by simp\n  from Clique_not_solvable_by_small_monotone_circuit[OF Large \\<pi>[unfolded nk] _ vars]\n    solution[unfolded s] nk\n  have \"real k powr (8 / 7 * real k) < cs \\<phi>\" by auto\n  also have \"real k powr (8 / 7 * real k) = root 8 n powr (8 / 7 * root 8 n)\" \n    unfolding kn by simp\n  also have \"\\<dots> = ((root 8 n) powr (8 / 7)) powr (root 8 n)\" \n    unfolding powr_powr by simp\n  also have \"(root 8 n) powr (8 / 7) = root 7 n\" using n0\n    by (simp add: root_powr_inverse powr_powr)\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/Clique_and_Monotone_Circuits/Clique_Large_Monotone_Circuits.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527944504227, "lm_q2_score": 0.8397339736884711, "lm_q1q2_score": 0.7154137054788507}}
{"text": "section\\<open>Additions to standard library\\<close>\n\ntext\\<open>In this section we define some additional functions and prove some\n additional lemmas about lists and multisets.\\<close>\n\nsubsection \\<open>Additions to the List library\\<close>\n\ntheory More_List\n  imports Main \"HOL-Library.Product_Lexorder\"\nbegin\n\ntext \\<open>@{text rev}\\<close>\n\nlemma nth_rev: \"n < length xs \\<Longrightarrow> rev xs ! n = xs ! (length xs - 1 - n)\"\n  using rev_nth by simp\n\ntext \\<open>@{text takeWhile}\\<close>\n\nlemma length_takeWhile:\n  assumes \"i < length l\" \"\\<forall> i' < i. P (l ! i')\" \"\\<not> P (l ! i)\" \n  shows \"length (takeWhile P l) = i\"\n  using assms\nproof (induction l arbitrary: i)\n  case Nil\n  thus ?case\n    by simp\nnext\n  case (Cons x l)\n  show ?case\n  proof (cases \"i = 0\")\n    case True\n    thus ?thesis\n      using Cons(4)\n      by simp\n  next\n    case False\n    hence \"length (takeWhile P l) = i - 1\"\n      using Cons(1)[of \"i-1\"] Cons(2) Cons(3) Cons(4)\n      by (auto simp add: nth_Cons) (metis Cons.prems(2) Cons.prems(3) Suc_less_SucD diff_Suc_Suc gr0_implies_Suc less_Suc_eq_0_disj minus_nat.diff_0 nth_Cons old.nat.simps(5))\n    thus ?thesis\n      using Cons(3)[rule_format, of 0] `i \\<noteq> 0`\n      by simp\n  qed\nqed\n\nlemma length_takeWhile':\n  assumes \"length (takeWhile P xs) = n\"\n  shows \"(\\<forall> i < n. P (xs ! i)) \\<and> ((n < length xs \\<and> \\<not> P (xs ! n)) \\<or> n = length xs)\"\n  using assms\n  by (metis length_takeWhile_le nat_less_le nth_length_takeWhile nth_mem set_takeWhileD takeWhile_nth)\n\ntext \\<open>@{text min_list}\\<close>\n\nlemma min_list_map_iff:\n  fixes f :: \"'a \\<Rightarrow> 'b::linorder\"\n  assumes \"ps \\<noteq> []\"\n  shows \"((\\<exists> i \\<in> set ps. s = f i) \\<and> list_all (\\<lambda>p. s \\<le> f p) ps) \\<longleftrightarrow> \n          (min_list (map (\\<lambda>p. f p) ps) = s)\"\n  using assms\n  unfolding list_all_iff\nproof safe\n  fix i\n  assume \"\\<forall>p\\<in>set ps. f i \\<le> f p\" \"i \\<in> set ps\"\n  thus \"min_list (map f ps) = f i\"\n    using `ps \\<noteq> []` min_list_Min[of  \"map f ps\"] eq_Min_iff[of \"set (map f ps)\" \"f i\"]\n    by auto\nnext\n  show \"\\<exists>i\\<in>set ps. min_list (map f ps) = f i\"\n    using `ps \\<noteq> []` min_list_Min[of  \"map f ps\"] eq_Min_iff[of \"set (map f ps)\"]\n    by auto\nnext\n  fix p\n  assume \"p \\<in> set ps\"\n  thus \"min_list (map f ps) \\<le> f p\"\n    using `ps \\<noteq> []` min_list_Min[of  \"map f ps\"] eq_Min_iff[of \"set (map f ps)\"]\n    by auto\nqed\n\nlemma P_min_list:\n  fixes l :: \"'a::{linorder} list\"\n  assumes \"l \\<noteq> []\" \"\\<forall> x \\<in> set l. P x\" \n  shows \"P (min_list l)\"\n  using assms\n  using min_list_Min[of l] Min_in[of \"set l\"]\n  by simp\n\nlemma min_list_map_is_min:\n  fixes f :: \"'a \\<Rightarrow> 'b::linorder\"\n  assumes \"ps \\<noteq> []\"\n  shows \"list_all (\\<lambda>p. min_list (map (\\<lambda>p. f p) ps) \\<le> f p) ps\"\n  using assms\n  unfolding list_all_iff\n  by (simp add: min_list_Min)\n\ntext \\<open>@{text max_list}\\<close>\n\nfun max_list where\n  \"max_list (x#xs) = fold max xs x\"\n\nlemma max_list_ubound:\n  assumes \"xs \\<noteq> []\" \"\\<forall> x \\<in> set xs. x \\<le> n\"\n  shows \"max_list xs \\<le> n\"\nproof-\n  from assms obtain x xs' where \"xs = x # xs'\"\n    by (cases xs) auto\n  hence \"x \\<le> n\" \"\\<forall> x \\<in> set xs'. x \\<le> n\"\n    using assms\n    by auto\n  hence \"fold max xs' x \\<le> n\"\n    by (induction xs' rule: rev_induct) (auto simp add: max_def)\n  thus ?thesis\n    using `xs = x # xs'`\n    by auto\nqed\n\nlemma max_list_max:\n  fixes xs :: \"('a :: linorder) list\"\n  shows \"\\<forall> x \\<in> set xs. max_list xs \\<ge> x\"\nproof (cases xs)\n  case (Cons x xs)\n  have \"x \\<le> fold max xs x\"\n    by (induction xs) (auto, smt List.finite_set Max.in_idem Max.set_eq_fold insertCI list.set(2) max.assoc max.commute max_def)\n  moreover\n  have \"\\<forall>x'\\<in>set xs. x' \\<le> fold max xs x\"\n    by (induction xs, auto,\n        smt List.finite_set Max.in_idem Max.set_eq_fold list.set_intros(1) max.assoc max_def min.orderI min_def,\n        metis List.finite_set Max.in_idem Max.set_eq_fold insertCI list.set(2) max.commute max.orderI)\n  ultimately\n  show ?thesis\n    using Cons\n    by simp\nqed simp\n \nlemma max_list_is_nth:\n  assumes \"l \\<noteq> []\"\n  shows \"\\<exists> i. i < length l \\<and> l ! i = max_list l\"\n  using assms\nproof-\n  from assms obtain a l' where \"l = a # l'\"\n    by (cases l) auto\n  have \"\\<exists>i. i < length (a # l') \\<and> (a # l') ! i = fold max l' a\"\n  proof (induction l' rule: rev_induct)\n    case Nil\n    then show ?case \n      by (rule_tac x=0 in exI, simp)\n  next\n    case (snoc x xs)\n    show ?case\n    proof (cases \"x \\<le> (fold max xs a)\")\n      case True\n      obtain i where i: \"i < length (a # xs)\" \"(a # xs) ! i = fold max xs a\"\n        using snoc\n        by auto\n      have \"(a # xs @ [x]) ! i = (a # xs) ! i\"\n        using `i < length (a # xs)`\n        by (metis (mono_tags, lifting) append_Cons butlast_snoc nth_butlast)\n      moreover\n      have \"fold max (xs @ [x]) a = fold max xs a\"\n        using True\n        by (simp add: max_def)\n      ultimately\n      show ?thesis\n        using i\n        by (rule_tac x=i in exI, simp)\n    next\n      case False\n      hence \"fold max (xs @ [x]) a = x\"\n        by (simp add: max_def)\n      moreover\n      have \"(a # xs @ [x]) ! (length (a # xs)) = x\"\n        by (simp add: nth_append)\n      ultimately\n      show ?thesis\n        by (rule_tac x=\"length (a # xs)\" in exI, simp)\n    qed\n  qed\n  thus ?thesis\n    using `l = a # l'`\n    by simp\nqed\n\ntext \\<open>@{text index_of}\\<close>\n\ndefinition index_of where\n  \"index_of xs x = snd (hd (filter (\\<lambda> (a, b). a = x) (zip xs [0..<length xs])))\"\n\nlemma index_of_in_set:\n  assumes \"x \\<in> set xs\"\n  shows \"index_of xs x < length xs \\<and> xs ! index_of xs x = x\"\nproof-\n  obtain i where \"x = xs ! i\" \"i < length xs\"\n    using assms in_set_conv_nth[of x xs]\n    by auto\n  hence \"(x, i) \\<in> set (zip xs [0..<length xs])\"\n    using assms\n    by (auto simp add: set_zip)\n  hence \"filter (\\<lambda>(a, b). a = x) (zip xs [0..<length xs]) \\<noteq> []\"\n    by (metis (mono_tags, lifting) filter_empty_conv old.prod.case)\n  thus ?thesis\n    unfolding index_of_def\n    using hd_in_set[of \"(filter (\\<lambda>(a, b). a = x) (zip xs [0..<length xs]))\"]\n    by (auto split: prod.split_asm simp add: set_zip)\nqed\n\nlemma singleton_list_iff: \n  \"xs = [x] \\<longleftrightarrow> set xs = {x} \\<and> distinct xs\"\n  by auto (metis distinct.simps(2) distinct_length_2_or_more insert_not_empty  neq_Nil_conv set_empty2 singletonD)\n\nlemma index_of_list_element:\n  assumes \"p < length xs\" \"distinct xs\"\n  shows \"index_of xs (xs ! p) = p\"\nproof-\n  have \"(xs ! p, p) \\<in> set (zip xs [0..<length xs])\"\n    using assms\n    by (auto simp add: set_zip)\n  moreover\n  hence \"\\<forall> p'. (xs ! p, p') \\<in> set (zip xs [0..<length xs]) \\<longrightarrow> p = p'\"\n    using `distinct xs` `p < length xs`\n    by (auto simp add: set_zip nth_eq_iff_index_eq)\n  ultimately\n  have \"set (filter (\\<lambda>(a, b). a = xs ! p) (zip xs [0..<length xs])) = {(xs ! p, p)}\"\n    by auto\n  moreover\n  have \"distinct (filter (\\<lambda>(a, b). a = xs ! p) (zip xs [0..<length xs]))\"\n    by  (rule distinct_filter, rule distinct_zipI2, simp)\n  ultimately\n  have \"filter (\\<lambda>(a, b). a = xs ! p) (zip xs [0..<length xs]) = [(xs ! p, p)]\"\n    by (simp add: singleton_list_iff)\n  thus ?thesis\n    unfolding index_of_def\n    by auto\nqed\n\ntext \\<open>@{text sum_list}\\<close>\n\nlemma sum_list_ge_eq:\n  fixes xs ys :: \"nat list\"\n  assumes \"length xs = length ys\" \"\\<forall> i < length xs. xs ! i \\<ge> ys ! i\" \"sum_list xs = sum_list ys\"\n  shows \"\\<forall> i < length xs. xs ! i = ys ! i\"\n  using assms\nproof safe\n  fix i\n  assume \"i < length xs\" \n  show \"xs ! i = ys ! i\"\n  proof (rule ccontr)\n    assume \"\\<not> ?thesis\"\n    hence \"xs ! i > ys ! i\"\n      using assms `i < length xs`\n      by auto\n    moreover\n    have \"xs = take i xs @ [xs ! i] @ drop (i + 1) xs\"\n         \"ys = take i ys @ [ys ! i] @ drop (i + 1) ys\"\n      using `i < length xs` `length xs = length ys`\n      by (metis One_nat_def add.right_neutral add_Suc_right append.assoc append_take_drop_id hd_drop_conv_nth take_hd_drop)+\n    hence \"sum_list (take i xs) + xs ! i + sum_list (drop (i + 1) xs) =\n           sum_list (take i ys) + ys ! i + sum_list (drop (i + 1) ys)\"\n      using `sum_list xs = sum_list ys`\n      by (metis (mono_tags, lifting) add.assoc add.right_neutral sum_list.Cons sum_list.Nil sum_list.append)\n    moreover\n    have \"sum_list (take i xs) \\<ge> sum_list (take i ys)\"\n    proof-\n      have \"map ((!) xs) [0..<i] = take i xs\"  \"map ((!) ys) [0..<i] = take i ys\"       \n        using  `i < length xs` `length xs = length ys`\n        by (auto intro: nth_equalityI)+\n      thus ?thesis\n        using sum_list_mono[of \"[0..<i]\" \"(!) ys\" \"(!) xs\"] assms `i < length xs`\n        by auto\n    qed\n    moreover\n    have \"sum_list (drop (i+1) xs) \\<ge> sum_list (drop (i+1) ys)\"\n    proof-\n      have \"map ((!) xs) [i+1..<length xs] = drop (i+1) xs\"  \"map ((!) ys) [i+1..<length ys] = drop (i+1) ys\"       \n        using  `i < length xs` `length xs = length ys`\n        by (auto intro: nth_equalityI)+\n      thus ?thesis\n        using sum_list_mono[of \"[i+1..<length xs]\" \"(!) ys\" \"(!) xs\"] assms `i < length xs`\n        by auto\n    qed\n    ultimately\n    show False\n      by simp\n  qed\nqed                                                     \n\nlemma sum_list_const:\n  assumes \"\\<forall> x \\<in> set L. f x = y\"\n  shows \"sum_list (map f L) = y * length L\"\n  using assms\n  by (induction L) auto\n\nlemma sum_list_replicate [simp]:\n  fixes x :: nat\n  shows \"sum_list (replicate n x) = n * x\"\n  by (induction n) auto\n\nlemma sum_list_nonempty_gt:\n  fixes xs :: \"nat list\"\n  assumes \"x \\<in> set xs\" \"x > 1\" \"\\<forall> x \\<in> set xs. x \\<ge> 1\"\n  shows \"sum_list xs > List.length xs\"\nproof-\n  obtain i where \"i < List.length xs\" \"xs ! i = x\"\n    by (meson assms(1) in_set_conv_nth)\n  then have \"xs = (take i xs) @ [x] @ (drop (i + 1) xs)\" (is \"?l = ?l1 @ ?x @ ?l2\")\n    using id_take_nth_drop by auto\n  then have \"sum_list xs = sum_list ?l1 + sum_list [x] + sum_list ?l2\"\n    by (metis append.assoc sum_list_append)\n  moreover\n  have \"sum_list ?l1 \\<ge> i\"\n    using sum_list_mono[of \"take i xs\" \"\\<lambda> x. 1\" \"\\<lambda> x. x\"]\n    by (metis \\<open>i < List.length xs\\<close> assms(3) in_set_takeD lambda_one length_take less_or_eq_imp_le map_ident min.bounded_iff order_antisym_conv sum_list_const take_map)\n  moreover\n  have \"sum_list ?l2 \\<ge> List.length xs - 1 - i\"\n    using sum_list_mono[of \"drop (i + 1) xs\" \"\\<lambda> x. 1\" \"\\<lambda> x. x\"]\n    by (metis assms(3) drop_drop in_set_dropD lambda_one length_drop map_ident sum_list_const)\n  moreover\n  have \"sum_list ?x > 1\"\n    using \\<open>1 < x\\<close>\n    by fastforce\n  ultimately\n  show ?thesis\n    using `i < List.length xs`\n    by auto\nqed\n\ntext \\<open>@{text insort}\\<close>\n\nlemma insort_middle:\n  \"\\<exists> p s. xs = p @ s \\<and> insort x xs = p @ [x] @ s\"\n  by (induct xs) (auto, meson Cons_eq_appendI)\n\nlemma insort_append:\n   \"(\\<exists> p s. l1 = p @ s \\<and> insort x (l1 @ l2) = p @ [x] @ s @ l2) \\<or>\n    (\\<exists> p s. l2 = p @ s \\<and> insort x (l1 @ l2) = l1 @ p @ [x] @ s)\"\nproof-\n  obtain p s where \"l1 @ l2 = p @ s\" and ps: \"insort x (l1 @ l2) = p @ [x] @ s\"\n    using insort_middle[of \"l1 @ l2\" x]\n    by auto\n  then obtain us where \"l1 = p @ us \\<and> us @ l2 = s \\<or> l1 @ us = p \\<and> l2 = us @ s\"\n    by (subst (asm) append_eq_append_conv2) auto\n  thus ?thesis\n  proof\n    assume \"l1 = p @ us \\<and> us @ l2 = s\"\n    thus ?thesis\n      using ps\n      by blast\n  next\n    assume \"l1 @ us = p \\<and> l2 = us @ s\"\n    thus ?thesis\n      using ps\n      by - (rule disjI2, rule_tac x=us in exI, rule_tac x=s in exI, simp)\n  qed\nqed\n\nlemma insort_append_skip_first:\n  assumes \"\\<forall> b \\<in> set xs. b < a\"\n  shows \"insort a (xs @ ys) = xs @ insort a ys\"\n  using assms\n  by (induction xs) auto\n\ntext \\<open>@{text sort}\\<close>\n\nlemma sort_snoc [simp]:\n  shows \"sort (xs @ [a]) = insort a (sort xs)\"\nby (induction xs) (auto simp add: insort_left_comm)\n\nlemma sort_rev [simp]:\n  shows \"sort (rev s) = sort s\"\n  by (induction s, auto)\n\nlemma sort_append_swapped:\n  assumes \"\\<forall> A \\<in> set xs. \\<forall> B \\<in> set ys. A > B\"\n  shows \"sort (xs @ ys) = sort ys @ sort xs\"\n  using assms\nproof (induction xs)\n  case Nil\n  then show ?case by simp\nnext\n  case (Cons a xs)\n  then show ?case\n    using insort_append_skip_first[of \"sort ys\"]\n    by (auto simp add: sorted_append)\nqed\n\ntext \\<open>@{text sorted}\\<close>\n\nlemma sorted_rev_cons:\n  assumes \"sorted (rev xs)\" \"x \\<ge> hd xs\" \n  shows \"sorted (rev (x # xs))\"\nproof (cases \"xs = []\")\n  case True\n  thus ?thesis\n    by simp\nnext\n  case False\n  hence \"last (rev xs) = hd xs\"\n    by (simp add: last_rev)\n  moreover\n  have  \"\\<forall> x' \\<in> set xs. x' \\<le> last (rev xs)\"\n    using `sorted (rev xs)`\n    using last_conv_nth[OF `xs \\<noteq> []`]\n    by (metis False calculation hd_conv_nth in_set_conv_nth le0 sorted_rev_nth_mono)\n  ultimately\n  show ?thesis\n    using assms\n    by (auto simp add: sorted_append)\nqed\n\nlemma sorted_filter [simp]:\n  assumes \"sorted xs\"\n  shows  \"sorted (filter P xs)\"\n  using assms\n  by (induction xs) auto\n\nlemma sorted_rev_tl:\n  assumes \"sorted (rev l)\"\n  shows \"sorted (rev (tl l))\"                                                            \n  using assms\n  using sorted_butlast \n  by (cases \"l = []\") force+\n\nlemma sorted_hd:\n  assumes \"x \\<in> set xs\" \"sorted xs\"\n  shows \"hd xs \\<le> x\"\n  using assms\n  by (metis dual_order.eq_iff empty_set equals0D list.exhaust_sel set_ConsD sorted_simps(2))\n\nlemma sorted_last_Max:\n  assumes \"sorted xs\" \"set xs \\<noteq> {}\"\n  shows \"last xs = Max (set xs)\"\n  using assms\nproof (induction rule: rev_induct)\n  case Nil\n  then show ?case \n    by simp\nnext\n  case (snoc x xs)\n  then show ?case\n    by (cases \"xs = []\") (auto simp add: sorted_append max_def antisym)\nqed\n\nlemma sorted_map_mono:\n  assumes \"sorted xs\" \"\\<forall> x \\<in> set xs. \\<forall> y \\<in> set xs. x \\<le> y \\<longrightarrow> f x \\<le> f y\" \n  shows \"sorted (map f xs)\"\n  using assms\n  by (metis (no_types, lifting) sorted_map sorted_wrt_mono_rel)\n\nlemma sorted_map_rev:\n  assumes \"sorted xs\"\n  assumes \"\\<forall> x y. x \\<in> set xs \\<and> y \\<in> set xs \\<and> x < y \\<longrightarrow> f x > f y\"\n  shows \"sorted (map f (rev xs))\"\n  using assms\n  by (induction xs, simp, auto simp add: sorted_append less_imp_le antisym_conv2)\n     (metis antisym_conv2 eq_iff less_imp_le)\n\nlemma distinct_last_not_in_butlast:\n  assumes \"distinct xs\" \"xs \\<noteq> []\"\n  shows \"last xs \\<notin> set (butlast xs)\"\n  using assms\n  by (metis append_butlast_last_id distinct_butlast not_distinct_conv_prefix)\n\ntext \\<open>@{text sorted_list_of_set}\\<close>\n\nlemma sorted_list_of_set_remove_Max:\n  assumes \"A \\<noteq> {}\" \"finite A\"\n  shows \"sorted_list_of_set (A - {Max A}) = butlast (sorted_list_of_set A)\" (is \"?lhs = ?rhs\")\nproof (rule sorted_distinct_set_unique)\n  show \"sorted ?lhs\" \"distinct ?lhs\"\n    using assms\n    by auto\nnext\n  show \"sorted ?rhs\" \"distinct ?rhs\"\n    using assms\n    by (auto simp add: sorted_butlast distinct_butlast)\nnext\n  let ?A = \"sorted_list_of_set A\" \n  let ?B = \"butlast ?A\"\n  have \"A = set ?B \\<union> {Max A}\"\n    using assms append_butlast_last_id[of \"sorted_list_of_set A\"]\n    using sorted_last_Max[of \"sorted_list_of_set A\"]\n    by (metis empty_set list.simps(15) set_append set_sorted_list_of_set sorted_sorted_list_of_set)\n  moreover\n  have \"Max A \\<notin> set ?B\"\n    using sorted_last_Max[of \"sorted_list_of_set A\"]\n    using distinct_last_not_in_butlast[of ?A] assms\n    by auto\n  moreover\n  have \"Max A \\<in> A\"\n    using assms\n    by auto\n  ultimately\n  show \"set ?lhs = set ?rhs\"\n    using assms \n    by (auto simp add: sorted_list_of_set_remove)\nqed\n\nlemma sorted_list_of_set_insert_Max [simp]:\n  assumes \"finite F\" \"\\<forall> s' \\<in> F. s' < s\" \n  shows \"sorted_list_of_set (insert s F) = sorted_list_of_set F @ [s]\" (is \"?lhs = ?rhs @ [s]\")\nproof-\n  have \"s \\<notin> F\"\n    using assms\n    by auto\n\n  have s1Max: \"Max (insert s F) = s\"\n    using assms\n    apply (cases \"F = {}\")\n    apply simp\n    apply (metis (no_types, lifting) Max_gr_iff Max_in Un_insert_right finite_insert infinite_growing insert_iff sup_bot.comm_neutral)\n    done\n\n  hence \"butlast ?lhs = ?rhs\"\n    using assms sorted_list_of_set_remove_Max[of \"insert s F\"] `s \\<notin> F`\n    by simp\n\n  moreover\n\n  have \"last ?lhs = s\"\n    using s1Max sorted_last_Max[of \"sorted_list_of_set (insert s F)\"]\n    using assms  \\<open>s \\<notin> F\\<close>\n    by (metis Un_insert_right finite_insert insert_iff set_sorted_list_of_set sorted_sorted_list_of_set sup_bot.comm_neutral)\n\n  ultimately\n\n  show ?thesis\n    using assms append_butlast_last_id[of \"?lhs\"]\n    by auto\nqed\n\nlemma sorted_list_of_set_inj:\n  assumes \"finite x\" \"finite y\" \"sorted_list_of_set x = sorted_list_of_set y\"\n  shows \"x = y\"\n  using assms\n  using set_sorted_list_of_set by fastforce\n\nlemma sorted_list_of_set_union:\n  assumes \"\\<forall> x \\<in> p. \\<forall> y \\<in> s. x \\<le> y\" \"p \\<inter> s = {}\" \"finite p\" \"finite s\"\n  shows \"sorted_list_of_set (p \\<union> s) = sorted_list_of_set p @ sorted_list_of_set s\" (is \"?lhs = ?rhs\")\n  by (rule sorted_distinct_set_unique) (auto simp add: assms sorted_append)\n\nlemma sorted_list_of_set_image_rev:\n  assumes \"\\<forall> x y. x \\<in> A \\<and> y \\<in> A \\<and> x < y \\<longrightarrow> f x > f y\" \"inj_on f A\" \"finite A\"\n  shows \"sorted_list_of_set (f ` A) = rev (map f (sorted_list_of_set A))\" (is \"?lhs = ?rhs\")\nproof (rule sorted_distinct_set_unique)\n  show \"sorted ?lhs\" \"distinct ?lhs\"\n    using assms\n    by auto\nnext\n  show \"sorted ?rhs\"\n    using assms\n    by (simp add: rev_map sorted_map_rev)\nnext\n  show \"distinct ?rhs\"\n    using assms\n    by (simp add: distinct_map inj_on_def)\nnext\n  show \"set ?lhs = set ?rhs\"\n    using assms\n    by auto\nqed\n\ntext \\<open>@{text map2}\\<close>\n\nlemma map2_map:\n   \"map2 f (map g xs) xs = map (\\<lambda> k. f (g k) k) xs\"\n  by (induction xs) auto\n\ntext \\<open>@{text replicate}\\<close>\n\nlemma list_eq_replicate:\n  assumes \"\\<forall> x \\<in> set l. x = a\" \n  shows \"l = replicate (length l) a\"\nproof (rule nth_equalityI)\n  show \"length l = length (replicate (length l) a)\"\n    by simp\nnext\n  fix i\n  assume \"i < length l\"\n  thus \"l ! i = replicate (length l) a ! i\"\n    using assms in_set_conv_nth[of \"l ! i\" l]\n    by auto\nqed\n\ntext \\<open>@{text concat}\\<close>\n\nlemma concat_nth:\n  assumes \"\\<forall> x \\<in> set M. length x = n\" \"i < n * length M\"\n  shows \"concat M ! i = M ! (i div n) ! (i mod n)\"\n  using assms\nproof (induction M rule: rev_induct)\n  case Nil\n  then show ?case \n    by simp\nnext\n  case (snoc a M)\n  show ?case\n  proof (cases \"i < n * length M\")\n    case True\n    hence \"i div n < length M\"\n      by (simp add: Groups.mult_ac(2) less_mult_imp_div_less)\n    moreover\n    have \"length (concat M) = n * length M\"\n      using snoc(2)\n      by (induction M) auto\n    ultimately\n    show ?thesis\n      using snoc True\n      by (simp add: nth_append)\n  next\n    case False\n    hence \"i div n \\<ge> length M\"\n      by (metis assms(2) div_le_mono le_less_linear mult_is_0 nonzero_mult_div_cancel_left)\n    moreover\n    have \"length (concat M) = n * length M\"\n      using snoc(2)\n      by (induction M) auto\n    moreover\n    have \"i div n = length M\"\n      using snoc(3) False div_nat_eqI\n      by auto\n    moreover\n    have \"i - n * length M = i mod n\"\n      using False\n      by (metis `i div n = length M` minus_mult_div_eq_mod)\n    ultimately\n    show ?thesis\n      using False\n      by(simp add: nth_append)\n  qed\nqed\n\nlemma drop_concat:\n  assumes \"\\<forall> x \\<in> set M. length x = n\" \"i < length M\"\n  shows \"drop (i * n) (concat M) = (concat (drop i M))\"\n  using assms \nproof (induct M rule: rev_induct)\n  case Nil\n  then show ?case \n    by simp\nnext\n  case (snoc x xs)\n  show ?case\n  proof (cases \"i < length xs\")\n    case True\n    then show ?thesis\n      using snoc\n      using length_concat[of xs]\n      using sum_list_const[of xs length n]\n      by auto\n  next\n    case False\n    hence \"i = length xs\"\n      using snoc(3)\n      by simp\n    then show ?thesis\n      using snoc(2)\n      using length_concat[of xs]\n      using sum_list_const[of xs length n]\n      by simp\n  qed\nqed\n\nlemma take_concat:\n  assumes \"length (hd M) = n\" \"M \\<noteq> []\"\n  shows \"take n (concat M) = hd M\"\n  using assms\n  by (metis append_eq_conv_conj concat.simps(2) hd_Cons_tl)\n\nlemma take_drop_concat:\n  assumes \"\\<forall> x \\<in> set M. length x = n\" \"i < length M\"\n  shows \"take n (drop (i * n) (concat M)) = M ! i\"\n  using assms\n  using drop_concat[OF assms]\n  using take_concat[of \"drop i M\" n]\n  by (simp add: hd_drop_conv_nth)\n\nlemma hd_concat [simp]:\n  assumes \"xs \\<noteq> []\" \"hd xs \\<noteq> []\"\n  shows \"hd (concat xs) = hd (hd xs)\"\n  using assms\n  by (induction xs, auto)\n\nlemma concat_filter_empty:\n  shows \"concat xs = concat (filter (\\<lambda> x. x \\<noteq> []) xs)\"\n  by (induction xs) auto\n\nlemma sorted_concat:\n  assumes \"\\<forall> xs \\<in> set xss. sorted xs\"\n          \"\\<forall> i j. i < j \\<and> j < length xss \\<longrightarrow> (\\<forall> x \\<in> set (xss ! i). \\<forall> y \\<in> set (xss ! j). x \\<le> y)\"\n shows \"sorted (concat xss)\"\n  using assms\nproof (induction xss)\n  case Nil\n  then show ?case\n    by simp\nnext\n  case (Cons a xss)\n  have \"sorted a\"\n    using Cons(2)\n    by simp\n  moreover\n  have \"sorted (concat xss)\"\n  proof (rule Cons(1))\n    show \"\\<forall> a \\<in> set xss. sorted a\"\n      using Cons(2)\n      by simp\n  next\n    show \"\\<forall>i j. i < j \\<and> j < length xss \\<longrightarrow> (\\<forall>x\\<in>set (xss ! i). \\<forall>a\\<in>set (xss ! j). x \\<le> a)\"\n    proof safe                                                                                  \n      fix i j x y\n      assume \"x \\<in> set (xss ! i)\" \"y \\<in> set (xss ! j)\" \"i < j\" \"j < length xss\"\n      thus \"x \\<le> y\"\n        using Cons(3)[rule_format, of \"i+1\" \"j+1\" x y]\n        by simp\n    qed\n  qed\n\n  moreover\n  have \"\\<forall> x \\<in> set a. \\<forall> y \\<in> set xss. \\<forall>z\\<in>set y. x \\<le> z\"\n  proof safe\n    fix x y z\n    assume *: \"x \\<in> set a\" \"y \\<in> set xss\" \"z \\<in> set y\"\n    then obtain j where \"j < length xss\" \"xss ! j = y\"\n      using in_set_conv_nth[of y xss]\n      by auto\n    thus \"x \\<le> z\" \n      using Cons(3)[rule_format, of 0 \"j+1\" x z] *\n      by simp\n  qed\n\n  ultimately\n\n  show ?case \n    by (simp add: sorted_append)\nqed\n\nlemma concat_nonempty_singletons:\n  assumes \"List.length (concat xs) = List.length xs\" \"\\<forall> x \\<in> set xs. x \\<noteq> []\" \"x \\<in> set xs\"\n  shows \"List.length x = 1\"\nproof (rule ccontr)\n  assume \"\\<not> ?thesis\"\n  then have \"List.length x > 1\"\n    using assms(2-3)\n    using antisym_conv3 by auto\n  moreover\n  have \"\\<forall> x \\<in> set xs. List.length x \\<ge> 1\"\n    using assms(2)\n    by (simp add: Suc_leI)\n  ultimately\n  have \"sum_list (map List.length xs) > List.length xs\"\n    using sum_list_nonempty_gt[of \"List.length x\" \"map List.length xs\"] `x \\<in> set xs`\n    by auto\n  then show False\n    using assms(1)\n    by (simp add: length_concat)\nqed\n\n\ndefinition concat_prefix_length :: \"'a list list \\<Rightarrow> nat \\<Rightarrow> nat\" where \n  \"concat_prefix_length xs n = sum_list (map length (take n xs))\"\n\nlemma concat_prefix_length_Suc [simp]:\n  assumes \"n < List.length xs\"\n  shows \"concat_prefix_length xs (n + 1) = concat_prefix_length xs n  + length (xs ! n)\"\nproof-\n  have \"take (n + 1) xs = take n xs @ [xs ! n]\"\n    using assms\n    using take_Suc_conv_app_nth by auto\n  then show ?thesis\n    unfolding concat_prefix_length_def\n    by auto\nqed\n\nlemma concat_prefix_length_ub:\n  shows \"concat_prefix_length xs n \\<le> length (concat xs)\"\n  unfolding concat_prefix_length_def\n  by (metis append_take_drop_id concat_append length_append length_concat linorder_not_less not_add_less1)\n\nlemma length_prefix_mono:\n  assumes \"n1 \\<le> n2\"\n  shows \"concat_prefix_length xs n1 \\<le> concat_prefix_length xs n2\"\nproof-\n  obtain ys where \"take n2 xs = take n1 xs @ ys\"\n    by (metis assms nat_le_iff_add take_add)\n  then have \"sum_list (map List.length (take n2 xs)) = sum_list (map List.length (take n1 xs)) + sum_list (map List.length ys)\"\n    by auto\n  moreover have \"sum_list (map List.length ys) \\<ge> 0\"\n    by auto\n  ultimately show ?thesis\n    unfolding concat_prefix_length_def\n    by auto\nqed\n\nlemma concat_in_nth_list:\n  assumes \"j < length xs\" \"k < length (xs ! j)\"\n  assumes \"x = (xs ! j ! k)\" \"i = concat_prefix_length xs j + k\"\n  shows \"(concat xs) ! i = x\"\nproof-\n  let ?p = \"take j xs\"\n  let ?s = \"drop (j+1) xs\"\n  have \"xs = ?p @ [xs ! j] @ ?s\"\n    by (metis add.commute append_assoc append_take_drop_id assms(1) hd_drop_conv_nth plus_1_eq_Suc take_hd_drop)\n  then have \"concat xs = concat ?p @ (xs ! j) @ concat ?s\"\n    by (metis append.right_neutral concat.simps(1) concat.simps(2) concat_append)\n  moreover have \"length (concat ?p) = sum_list (map length ?p)\"\n    by (rule length_concat)\n  ultimately have \"concat xs ! i = ((xs ! j) @ concat ?s) ! k\"\n    using `i = concat_prefix_length xs j + k`\n    by (metis nth_append_length_plus concat_prefix_length_def)\n  also have \"... = (xs ! j) ! k\"\n    using `k < length (xs ! j)`\n    thm nth_append\n    by (simp add: nth_append)\n  finally show ?thesis\n    using `x = (xs ! j) ! k`\n    by simp\nqed\n\ntext \\<open>@{text positions}\\<close>\n\ndefinition positions :: \"bool list \\<Rightarrow> nat list\" where\n  \"positions xs = map snd (filter (\\<lambda> (x, p). x) (zip xs [0..<length xs]))\"\n\nlemma sorted_positions:\n  shows \"sorted (positions xs)\"\n  unfolding positions_def\n  by (induction xs rule: rev_induct) (auto simp add: sorted_append set_zip)\n\nlemma distinct_positions:\n  shows \"distinct (positions xs)\"\n  unfolding positions_def\n  by (induction xs rule: rev_induct) (auto simp add: set_zip)\n\nlemma set_positions:\n  shows \"set (positions xs) = {p. p < length xs \\<and> xs ! p}\"\n  unfolding positions_def\n  by (induction xs rule: rev_induct) (auto simp add: nth_append)\n\nlemma positions_sorted_list_of_set:\n  shows \"positions xs = sorted_list_of_set {p. p < length xs \\<and> xs ! p}\"\n  using sorted_distinct_set_unique[of \"positions xs\" \"sorted_list_of_set {p. p < length xs \\<and> xs ! p}\"]\n  by (simp add: sorted_positions distinct_positions set_positions)\n\ntext \\<open>@{text of_positions}\\<close>\n\ndefinition of_positions where\n  \"of_positions n xs = map (\\<lambda> k. k \\<in> set xs) [0..<n]\"\n\nlemma of_positions_positions: \n  shows \"of_positions (length xs) (positions xs) = xs\"\nproof-\n  have \"map (\\<lambda>k. k < length xs \\<and> xs ! k) [0..<length xs] = map (\\<lambda> k. xs ! k) [0..<length xs]\"\n    by simp\n  thus ?thesis\n    using map_nth[of xs]\n    unfolding of_positions_def\n    by (simp add: set_positions)\nqed\n\nlemma positions_of_positions:\n  assumes \"set ps \\<subseteq> {0..<n}\" \"distinct ps\" \"sorted ps\"\n  shows \"positions (of_positions n ps) = ps\"\nproof-\n  let ?A = \"{k. k < length (of_positions n ps) \\<and> of_positions n ps ! k}\"\n  have \"set ps = ?A\"\n    using `set ps \\<subseteq> {0..<n}`\n    unfolding of_positions_def\n    by auto\n  hence \"ps = sorted_list_of_set ?A\"\n    using `sorted ps` `distinct ps`\n    using sorted_distinct_set_unique[of ps \"sorted_list_of_set ?A\"]\n    by simp\n  thus ?thesis\n    using positions_sorted_list_of_set[of \"of_positions n ps\"]\n    by simp\nqed\n\n\ndefinition max_by_prop :: \"'a set \\<Rightarrow> ('a \\<Rightarrow> 'b::linorder) \\<Rightarrow> 'a set\" where \n  \"max_by_prop A f = (\n    let max = Max (f ` A)\n     in {x \\<in> A. f x = max}\n  )\"\n\nlemma max_by_prop_nonempty [simp]:\n  assumes \"finite A\" \"A \\<noteq> {}\"\n  shows \"max_by_prop A f \\<noteq> {}\"\n  using assms Max_in[of \"f ` A\"]\n  unfolding max_by_prop_def Let_def\n  by fastforce\n\nlemma max_by_prop_finite [simp]:\n  assumes \"finite A\" \n  shows \"finite (max_by_prop A f)\"\n  using assms\n  unfolding max_by_prop_def Let_def\n  by auto\n\nlemma max_by_prop_subseteq:\n  shows \"max_by_prop A f \\<subseteq> A\"\n  unfolding max_by_prop_def\n  by auto\n\nlemma max_by_prop_max_prop:\n  assumes \"finite A\" \"x \\<in> max_by_prop A f\" \"x' \\<in> A\"\n  shows \"f x \\<ge> f x'\"\n  using assms\n  unfolding max_by_prop_def Let_def\n  by simp\n\nlemma max_by_prop_max_prop_eq:\n  assumes \"finite A\" \"x \\<in> max_by_prop A f\" \"x' \\<in> max_by_prop A f\"\n  shows \"f x = f x'\"\n  using assms\n  unfolding max_by_prop_def Let_def\n  by simp\n\nlemma max_by_prop_max_prop_gt:\n  assumes \"finite A\" \"x \\<in> max_by_prop A f\" \"x' \\<in> A\" \"x' \\<notin> max_by_prop A f\"\n  shows \"f x > f x'\"\n  using assms\n  unfolding max_by_prop_def Let_def\n  by (simp add: order_less_le)\n\nlemma max_by_prop_iff:\n  assumes \"finite A\" \"A \\<noteq> {}\"\n  shows \"x \\<in> max_by_prop A f \\<longleftrightarrow> x \\<in> A \\<and> (\\<forall> x' \\<in> A. f x' \\<le> f x)\"\n  unfolding max_by_prop_def Let_def\n  by (smt (verit, best) Max.coboundedI Max_in assms(1) assms(2) finite_has_maximal2 finite_imageI imageE image_eqI image_is_empty mem_Collect_eq)\n\n\nlemma max_by_prop_pair:\n  assumes \"finite A\" \"A \\<noteq> {}\"\n  shows \"max_by_prop (max_by_prop A f1) f2 = max_by_prop A (\\<lambda> x. (f1 x, f2 x))\" (is \"?lhs = ?rhs\")\nproof-\n  have \"\\<forall> x. x \\<in> ?lhs \\<longleftrightarrow> x \\<in> ?rhs\"\n  proof\n    fix x\n    have \"x \\<in> ?lhs \\<longleftrightarrow> x \\<in> max_by_prop A f1 \\<and> (\\<forall> x' \\<in> max_by_prop A f1. f2 x \\<ge> f2 x')\"\n      using assms max_by_prop_iff\n      by (metis max_by_prop_finite max_by_prop_nonempty)\n    also have \"... \\<longleftrightarrow> x \\<in> A \\<and> (\\<forall> x' \\<in> A. f1 x' \\<le> f1 x) \\<and> (\\<forall> x' \\<in> A. (\\<forall> x'' \\<in> A. f1 x'' \\<le> f1 x') \\<longrightarrow> f2 x \\<ge> f2 x')\"\n      using assms max_by_prop_iff\n      by metis\n    also have \"... \\<longleftrightarrow> x \\<in> ?rhs\"\n      by (subst max_by_prop_iff[OF assms]) (force simp add: less_eq_prod_def nless_le)\n    finally show \"x \\<in> ?lhs \\<longleftrightarrow> x \\<in> ?rhs\"\n      .\n  qed\n  then show ?thesis\n    by blast\nqed\n\nlemma max_by_prop_cong:\n  assumes \"finite A\" \"A \\<noteq> {}\"\n  assumes \"\\<forall> x1 \\<in> A. \\<forall> x2 \\<in> A. f1 x1 < f1 x2 \\<longleftrightarrow> f2 x1 < f2 x2\"\n  shows \"max_by_prop A f1 = max_by_prop A f2\"\n  using assms\n  unfolding max_by_prop_def\n  by (smt (verit, ccfv_SIG) Collect_cong Max_ge Max_in finite_imageI imageE image_eqI image_is_empty linorder_not_less not_less_iff_gr_or_eq) \n\n\ndefinition split_by_prop :: \"'a set => ('a => 'b) => 'a set set\" where\n  \"split_by_prop A f = { {y \\<in> A. f y = x} | x. x \\<in> f ` A}\" \n\nlemma split_by_prop_finite [simp]:\n  assumes \"finite A\"\n  shows \"finite (split_by_prop A f)\"\n  unfolding split_by_prop_def\n  using assms\n  by auto\n\nlemma split_by_prop_nonempty [simp]:\n  shows \"{} \\<notin> split_by_prop A f\"\n  unfolding split_by_prop_def\n  by auto\n\nlemma split_by_prop_set [simp]:\n  shows \"\\<Union> (split_by_prop A f) = A\"\n  unfolding split_by_prop_def\n  by auto\n\nlemma split_by_prop_disjoint:\n  assumes \"x \\<in> split_by_prop A f\" \"y \\<in> split_by_prop A f\"\n  shows \"x = y \\<or> x \\<inter> y = {}\"\n  using assms\n  unfolding split_by_prop_def\n  by auto\n\ndefinition is_split_by_prop where\n  \"is_split_by_prop cs f \\<longleftrightarrow> \n    (\\<forall> cl \\<in> cs. \\<forall> v1 \\<in> cl. \\<forall> v2 \\<in> cl. f v1 = f v2) \\<and> \n    (\\<forall> cl1 \\<in> cs. \\<forall> cl2 \\<in> cs. cl1 \\<noteq> cl2  \\<longrightarrow> (\\<forall> v1 \\<in> cl1. \\<forall> v2 \\<in> cl2. f v1 \\<noteq> f v2)) \\<and>\n    (\\<forall> cl \\<in> cs. cl \\<noteq> {})\"\n\nlemma split_by_prop_is_split_by_prop [simp]:\n  shows \"is_split_by_prop (split_by_prop A f) f\"\n  unfolding is_split_by_prop_def split_by_prop_def\n  by auto\n\nlemma split_by_prop_singleton:\n  assumes \"A \\<noteq> {}\"\n  shows \"split_by_prop A f = {A} \\<longleftrightarrow> (\\<forall> x \\<in> A. \\<forall> y \\<in> A. f x = f y)\"\nproof\n  assume \"split_by_prop A f = {A}\"\n  then show \"\\<forall> x \\<in> A. \\<forall> y \\<in> A. f x = f y\"\n    by (metis is_split_by_prop_def singletonI split_by_prop_is_split_by_prop)\nnext\n  assume *: \"\\<forall> x \\<in> A. \\<forall> y \\<in> A. f x = f y\"\n  from assms obtain x where \"x \\<in> A\"\n    by auto\n  then have \"\\<forall> x' \\<in> A. f x' = f x\"\n    using *\n    by blast\n  then have \"f ` A = {f x}\"\n    using \\<open>x \\<in> A\\<close> by blast\n  then have \"{{y \\<in> A. f y = x} |x. x \\<in> f ` A} = {{y \\<in> A. f y = f x}}\"\n    by auto\n  then show \"split_by_prop A f = {A}\"\n    unfolding split_by_prop_def\n    using *\n    by blast\nqed\n\nend\n", "meta": {"author": "milanbankovic", "repo": "isocert", "sha": "0b160702bc0196739915541478fdfc9bb67a35db", "save_path": "github-repos/isabelle/milanbankovic-isocert", "path": "github-repos/isabelle/milanbankovic-isocert/isocert-0b160702bc0196739915541478fdfc9bb67a35db/thy/More_List.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8397339556397749, "lm_q2_score": 0.8519528057272543, "lm_q1q2_score": 0.7154136995717519}}
{"text": "(*\n * Copyright Data61, CSIRO (ABN 41 687 119 230)\n *\n * SPDX-License-Identifier: BSD-2-Clause\n *)\n\nsection \\<open>Arithmetic lemmas\\<close>\n\ntheory More_Arithmetic\n  imports Main \"HOL-Library.Type_Length\"\nbegin\n\nlemma n_less_equal_power_2:\n  \"n < 2 ^ n\"\n  by (fact less_exp)\n\nlemma min_pm [simp]: \"min a b + (a - b) = a\"\n  for a b :: nat\n  by arith\n\nlemma min_pm1 [simp]: \"a - b + min a b = a\"\n  for a b :: nat\n  by arith\n\nlemma rev_min_pm [simp]: \"min b a + (a - b) = a\"\n  for a b :: nat\n  by arith\n\nlemma rev_min_pm1 [simp]: \"a - b + min b a = a\"\n  for a b :: nat\n  by arith\n\nlemma min_minus [simp]: \"min m (m - k) = m - k\"\n  for m k :: nat\n  by arith\n\nlemma min_minus' [simp]: \"min (m - k) m = m - k\"\n  for m k :: nat\n  by arith\n\nlemma nat_less_power_trans:\n  fixes n :: nat\n  assumes nv: \"n < 2 ^ (m - k)\"\n  and     kv: \"k \\<le> m\"\n  shows \"2 ^ k * n < 2 ^ m\"\nproof (rule order_less_le_trans)\n  show \"2 ^ k * n < 2 ^ k * 2 ^ (m - k)\"\n    by (rule mult_less_mono2 [OF nv zero_less_power]) simp\n  show \"(2::nat) ^ k * 2 ^ (m - k) \\<le> 2 ^ m\" using nv kv\n    by (subst power_add [symmetric]) simp\nqed\n\nlemma nat_le_power_trans:\n  fixes n :: nat\n  shows \"\\<lbrakk>n \\<le> 2 ^ (m - k); k \\<le> m\\<rbrakk> \\<Longrightarrow> 2 ^ k * n \\<le> 2 ^ m\"\n  by (metis le_add_diff_inverse mult_le_mono2 semiring_normalization_rules(26))\n\nlemma nat_add_offset_less:\n  fixes x :: nat\n  assumes yv: \"y < 2 ^ n\"\n  and     xv: \"x < 2 ^ m\"\n  and     mn: \"sz = m + n\"\n  shows   \"x * 2 ^ n + y < 2 ^ sz\"\nproof (subst mn)\n  from yv obtain qy where \"y + qy = 2 ^ n\" and \"0 < qy\"\n    by (auto dest: less_imp_add_positive)\n\n  have \"x * 2 ^ n + y < x * 2 ^ n + 2 ^ n\" by simp fact+\n  also have \"\\<dots> = (x + 1) * 2 ^ n\" by simp\n  also have \"\\<dots> \\<le> 2 ^ (m + n)\" using xv\n    by (subst power_add) (rule mult_le_mono1, simp)\n  finally show \"x * 2 ^ n + y < 2 ^ (m + n)\" .\nqed\n\nlemma nat_power_less_diff:\n  assumes lt: \"(2::nat) ^ n * q < 2 ^ m\"\n  shows \"q < 2 ^ (m - n)\"\n  using lt\nproof (induct n arbitrary: m)\n  case 0\n  then show ?case by simp\nnext\n  case (Suc n)\n\n  have ih: \"\\<And>m. 2 ^ n * q < 2 ^ m \\<Longrightarrow> q < 2 ^ (m - n)\"\n    and prem: \"2 ^ Suc n * q < 2 ^ m\" by fact+\n\n  show ?case\n  proof (cases m)\n    case 0\n    then show ?thesis using Suc by simp\n  next\n    case (Suc m')\n    then show ?thesis using prem\n      by (simp add: ac_simps ih)\n  qed\nqed\n\nlemma power_2_mult_step_le:\n  \"\\<lbrakk>n' \\<le> n; 2 ^ n' * k' < 2 ^ n * k\\<rbrakk> \\<Longrightarrow> 2 ^ n' * (k' + 1) \\<le> 2 ^ n * (k::nat)\"\n  apply (cases \"n'=n\", simp)\n   apply (metis Suc_leI le_refl mult_Suc_right mult_le_mono semiring_normalization_rules(7))\n  apply (drule (1) le_neq_trans)\n  apply clarsimp\n  apply (subgoal_tac \"\\<exists>m. n = n' + m\")\n   prefer 2\n   apply (simp add: le_Suc_ex)\n  apply (clarsimp simp: power_add)\n  apply (metis Suc_leI mult.assoc mult_Suc_right nat_mult_le_cancel_disj)\n  done\n\nlemma nat_mult_power_less_eq:\n  \"b > 0 \\<Longrightarrow> (a * b ^ n < (b :: nat) ^ m) = (a < b ^ (m - n))\"\n  using mult_less_cancel2[where m = a and k = \"b ^ n\" and n=\"b ^ (m - n)\"]\n        mult_less_cancel2[where m=\"a * b ^ (n - m)\" and k=\"b ^ m\" and n=1]\n  apply (simp only: power_add[symmetric] nat_minus_add_max)\n  apply (simp only: power_add[symmetric] nat_minus_add_max ac_simps)\n  apply (simp add: max_def split: if_split_asm)\n  done\n\nlemma diff_diff_less:\n  \"(i < m - (m - (n :: nat))) = (i < m \\<and> i < n)\"\n  by auto\n\nlemma small_powers_of_2:\n  \\<open>x < 2 ^ (x - 1)\\<close> if \\<open>x \\<ge> 3\\<close> for x :: nat\nproof -\n  define m where \\<open>m = x - 3\\<close>\n  with that have \\<open>x = m + 3\\<close>\n    by simp\n  moreover have \\<open>m + 3 < 4 * 2 ^ m\\<close>\n    by (induction m) simp_all\n  ultimately show ?thesis\n    by simp\nqed\n\nlemma msrevs:\n  \"0 < n \\<Longrightarrow> (k * n + m) div n = m div n + k\"\n  \"(k * n + m) mod n = m mod n\"\n  for n :: nat\n  by simp_all\n\nend\n", "meta": {"author": "seL4", "repo": "l4v", "sha": "9ba34e269008732d4f89fb7a7e32337ffdd09ff9", "save_path": "github-repos/isabelle/seL4-l4v", "path": "github-repos/isabelle/seL4-l4v/l4v-9ba34e269008732d4f89fb7a7e32337ffdd09ff9/lib/Word_Lib/More_Arithmetic.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527982093668, "lm_q2_score": 0.8397339616560072, "lm_q1q2_score": 0.7154136983842725}}
{"text": "(*\n    File:     Finite_And_Cyclic_Groups.thy\n    Author:   Joseph Thommes, TU M\u00fcnchen; Manuel Eberl, TU M\u00fcnchen\n*)\nsection \\<open>Finite and cyclic groups\\<close>\n\ntheory Finite_And_Cyclic_Groups\n  imports Group_Hom Generated_Groups_Extend General_Auxiliary\nbegin\n\nsubsection \\<open>Finite groups\\<close>\n\ntext \\<open>We define the notion of finite groups and prove some trivial facts about them.\\<close>\n\nlocale finite_group = group +\n  assumes fin[simp]: \"finite (carrier G)\"\n\n(* Manuel Eberl *)\nlemma (in finite_group) ord_pos: \n  assumes \"x \\<in> carrier G\"\n  shows   \"ord x > 0\"\n  using ord_ge_1[of x] assms by auto\n\nlemma (in finite_group) order_gt_0 [simp,intro]: \"order G > 0\"\n  by (subst order_gt_0_iff_finite) auto\n\nlemma (in finite_group) finite_ord_conv_Least:\n  assumes \"x \\<in> carrier G\"\n  shows \"ord x = (LEAST n::nat. 0 < n \\<and> x [^] n = \\<one>)\"\n  using pow_order_eq_1 order_gt_0_iff_finite ord_conv_Least assms by auto\n\nlemma (in finite_group) non_trivial_group_ord_gr_1:\n  assumes \"carrier G \\<noteq> {\\<one>}\"\n  shows \"\\<exists>e \\<in> carrier G. ord e > 1\"\nproof -\n  from one_closed obtain e where e: \"e \\<noteq> \\<one>\" \"e \\<in> carrier G\" using assms carrier_not_empty by blast\n  thus ?thesis using ord_eq_1[of e] le_neq_implies_less ord_ge_1 by fastforce\nqed\n\n(* Manuel Eberl *)\nlemma (in finite_group) max_order_elem:\n  obtains a where \"a \\<in> carrier G\" \"\\<forall>x \\<in> carrier G. ord x \\<le> ord a\"\nproof -\n  have \"\\<exists>x. x \\<in> carrier G \\<and> (\\<forall>y. y \\<in> carrier G \\<longrightarrow> ord y \\<le> ord x)\"\n  proof (rule ex_has_greatest_nat[of _ \\<one> _ \"order G + 1\"], safe)\n    show \"\\<one> \\<in> carrier G\"\n      by auto\n  next\n    fix x assume \"x \\<in> carrier G\"\n    hence \"ord x \\<le> order G\"\n      by (intro ord_le_group_order fin)\n    also have \"\\<dots> < order G + 1\"\n      by simp\n    finally show \"ord x < order G + 1\" .\n  qed\n  thus ?thesis using that by blast\nqed\n\nlemma (in finite_group) iso_imp_finite:\n  assumes \"G \\<cong> H\" \"group H\"\n  shows \"finite_group H\"\nproof -\n  interpret H: group H by fact\n  show ?thesis\n  proof(unfold_locales)\n    show \"finite (carrier H)\" using iso_same_card[OF assms(1)]\n      by (metis card_gt_0_iff order_def order_gt_0)\n  qed\nqed\n\nlemma (in finite_group) finite_FactGroup:\n  assumes \"H \\<lhd> G\"\n  shows \"finite_group (G Mod H)\"\nproof -\n  interpret H: normal H G by fact\n  interpret Mod: group \"G Mod H\" using H.factorgroup_is_group .\n  show ?thesis\n    by (unfold_locales, unfold FactGroup_def RCOSETS_def, simp)\nqed\n\nlemma (in finite_group) bigger_subgroup_is_group:\n  assumes \"subgroup H G\" \"card H \\<ge> order G\"\n  shows \"H = carrier G\"\n  using subgroup.subset fin assms by (metis card_seteq order_def)\n\ntext \\<open>All generated subgroups of a finite group are obviously also finite.\\<close>\n\nlemma (in finite_group) finite_generate:\n  assumes \"A \\<subseteq> carrier G\"\n  shows \"finite (generate G A)\"\n  using generate_incl[of A] rev_finite_subset[of \"carrier G\" \"generate G A\"] assms by simp\n\ntext \\<open>We also provide an induction rule for finite groups inspired by Manuel Eberl's AFP entry\n\"Dirichlet L-Functions and Dirichlet's Theorem\" and the contained theory \"Group\\_Adjoin\". A property\nthat is true for a subgroup generated by some set and stays true when adjoining an element, is also\ntrue for the whole group.\\<close>\n\nlemma (in finite_group) generate_induct[consumes 1, case_names base adjoin]:\n  assumes \"A0 \\<subseteq> carrier G\"\n  assumes \"A0 \\<subseteq> carrier G \\<Longrightarrow> P (G\\<lparr>carrier := generate G A0\\<rparr>)\"\n  assumes \"\\<And>a A. \\<lbrakk>A \\<subseteq> carrier G; a \\<in> carrier G - generate G A; A0 \\<subseteq> A;\n           P (G\\<lparr>carrier := generate G A\\<rparr>)\\<rbrakk> \\<Longrightarrow> P (G\\<lparr>carrier := generate G (A \\<union> {a})\\<rparr>)\"\n  shows \"P G\"\nproof -\n  define A where A: \"A = carrier G\"\n  hence gA: \"generate G A = carrier G\"\n    using generate_incl[of \"carrier G\"] generate_sincl[of \"carrier G\"] by simp\n  hence \"finite A\" using fin A by argo\n  moreover have \"A0 \\<subseteq> A\" using assms(1) A by argo\n  moreover have \"A \\<subseteq> carrier G\" using A by simp\n  moreover have \"generate G A0 \\<subseteq> generate G A\" using gA generate_incl[OF assms(1)] by argo\n  ultimately have \"P (G\\<lparr>carrier := generate G A\\<rparr>)\" using assms(2, 3)\n  proof (induction \"A\" taking: card rule: measure_induct_rule)\n    case (less A)\n    then show ?case\n    proof(cases \"generate G A0 = generate G A\")\n      case True\n      thus ?thesis using less by force\n    next\n      case gA0: False\n      with less(3) have s: \"A0 \\<subset> A\" by blast\n      then obtain a where a: \"a \\<in> A - A0\" by blast\n      have P1: \"P (G\\<lparr>carrier := generate G (A - {a})\\<rparr>)\"\n      proof(rule less(1))\n        show \"card (A - {a}) < card A\" using a less(2) by (meson DiffD1 card_Diff1_less)\n        show \"A0 \\<subseteq> A - {a}\" using a s by blast\n        thus \"generate G A0 \\<subseteq> generate G (A - {a})\" using mono_generate by presburger\n      qed (use less a s in auto)\n      show ?thesis\n      proof (cases \"generate G A = generate G (A - {a})\")\n        case True\n        then show ?thesis using P1 by simp\n      next\n        case False\n        have \"a \\<in> carrier G - generate G (A - {a})\"\n        proof -\n          have \"a \\<notin> generate G (A - {a})\"\n          proof\n            assume a2: \"a \\<in> generate G (A - {a})\"\n            have \"generate G (A - {a}) = generate G A\"\n            proof (rule equalityI)\n              show \"generate G (A - {a}) \\<subseteq> generate G A\" using mono_generate by auto\n              show \"generate G A \\<subseteq> generate G (A - {a})\"\n              proof(subst (2) generate_idem[symmetric])\n                show \"generate G A \\<subseteq> generate G (generate G (A - {a}))\"\n                  by (intro mono_generate, use generate_sincl[of \"A - {a}\"] a2 in blast)\n              qed (use less in auto)\n            qed\n            with False show False by argo\n          qed\n          with a less show ?thesis by fast\n        qed\n        from less(7)[OF _ this _ P1] less(4) s a have \"P (G\\<lparr>carrier := generate G (A - {a} \\<union> {a})\\<rparr>)\"\n          by blast\n        moreover have \"A - {a} \\<union> {a} = A\" using a by blast\n        ultimately show ?thesis by auto\n      qed\n    qed\n  qed\n  with gA show ?thesis by simp\nqed\n\nsubsection \\<open>Finite abelian groups\\<close>\n\ntext \\<open>Another trivial locale: the finite abelian group with some trivial facts.\\<close>\n\nlocale finite_comm_group = finite_group + comm_group\n\nlemma (in finite_comm_group) iso_imp_finite_comm:\n  assumes \"G \\<cong> H\" \"group H\"\n  shows \"finite_comm_group H\"\nproof -\n  interpret H: group H by fact\n  interpret H: comm_group H by (intro iso_imp_comm_group[OF assms(1)], unfold_locales)\n  interpret H: finite_group H by (intro iso_imp_finite[OF assms(1)], unfold_locales)\n  show ?thesis by unfold_locales\nqed\n\nlemma (in finite_comm_group) finite_comm_FactGroup:\n  assumes \"subgroup H G\"\n  shows \"finite_comm_group (G Mod H)\"\n  unfolding finite_comm_group_def\nproof(safe)\n  show \"finite_group (G Mod H)\" using finite_FactGroup[OF subgroup_imp_normal[OF assms]] .\n  show \"comm_group (G Mod H)\" by (simp add: abelian_FactGroup assms)\nqed\n\n(* Manuel Eberl *)\nlemma (in finite_comm_group) 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 (use finite_subset[OF H.subset] in \\<open>auto simp: m_comm\\<close>)\nqed\n\n\nsubsection \\<open>Cyclic groups\\<close>\n\ntext \\<open>Now, the central notion of a cyclic group is introduced: a group generated\nby a single element.\\<close>\n\nlocale cyclic_group = group +\n  fixes gen :: \"'a\"\n  assumes gen_closed[intro, simp]: \"gen \\<in> carrier G\"\n  assumes generator: \"carrier G = generate G {gen}\"\n\nlemma (in cyclic_group) elem_is_gen_pow:\n  assumes \"x \\<in> carrier G\"\n  shows \"\\<exists>n :: int. x = gen [^] n\"\nproof -\n  from generator have x_g:\"x \\<in> generate G {gen}\" using assms by fast\n  with generate_pow[of gen] show ?thesis using gen_closed by blast\nqed\n\ntext \\<open>Every cyclic group is commutative/abelian.\\<close>\n\nsublocale cyclic_group \\<subseteq> comm_group\nproof(unfold_locales)\n  fix x y\n  assume \"x \\<in> carrier G\" \"y \\<in> carrier G\"\n  then obtain a b where ab:\"x = gen [^] (a::int)\" \"y = gen [^] (b::int)\"\n    using elem_is_gen_pow by presburger\n  then have \"x \\<otimes> y = gen [^] (a + b)\" by (simp add: int_pow_mult)                 \n  also have \"\\<dots> = y \\<otimes> x\" using ab int_pow_mult\n    by (metis add.commute gen_closed)\n  finally show \"x \\<otimes> y = y \\<otimes> x\" .\nqed\n\ntext \\<open>Some trivial intro rules for showing that a group is cyclic.\\<close>\n\nlemma (in group) cyclic_groupI0:\n  assumes \"a \\<in> carrier G\" \"carrier G = generate G {a}\"\n  shows \"cyclic_group G a\"\n  using assms by (unfold_locales; auto) \n\nlemma (in group) cyclic_groupI1:\n  assumes \"a \\<in> carrier G\" \"carrier G \\<subseteq> generate G {a}\"\n  shows \"cyclic_group G a\"\n  using assms by (unfold_locales, use generate_incl[of \"{a}\"] in auto)\n\nlemma (in group) cyclic_groupI2:\n  assumes \"a \\<in> carrier G\"\n  shows \"cyclic_group (G\\<lparr>carrier := generate G {a}\\<rparr>) a\"\nproof (intro group.cyclic_groupI0)\n  show \"group (G\\<lparr>carrier := generate G {a}\\<rparr>)\"\n    by (intro subgroup.subgroup_is_group group.generate_is_subgroup, use assms in simp_all)\n  show \"a \\<in> carrier (G\\<lparr>carrier := generate G {a}\\<rparr>)\" using generate.incl[of a \"{a}\"] by auto\n  show \"carrier (G\\<lparr>carrier := generate G {a}\\<rparr>) = generate (G\\<lparr>carrier := generate G {a}\\<rparr>) {a}\"\n    using assms\n    by (simp add: generate_consistent generate.incl group.generate_is_subgroup)\nqed\n\ntext \\<open>The order of the generating element is always the same as the group order.\\<close>\n\nlemma (in cyclic_group) ord_gen_is_group_order:\n  shows \"ord gen = order G\"\nproof (cases \"finite (carrier G)\")\n  case True\n  with generator show \"ord gen = order G\"\n    using generate_pow_card[of gen] order_def[of G] gen_closed by simp\nnext\n  case False\n  thus ?thesis\n    using generate_pow_card generator order_def[of G] card_eq_0_iff[of \"carrier G\"] by force\nqed\n\ntext \\<open>In the case of a finite group, it is sufficient to have one element of group order to know\nthat the group is cyclic.\\<close>\n\nlemma (in finite_group) element_ord_generates_cyclic:\n  assumes \"a \\<in> carrier G\" \"ord a = order G\"\n  shows \"cyclic_group G a\"\nproof (unfold_locales)\n  show \"a \\<in> carrier G\" using assms(1) by simp\n  show \"carrier G = generate G {a}\"\n    using assms bigger_subgroup_is_group[OF generate_is_subgroup]\n    by (metis empty_subsetI fin generate_pow_card insert_subset ord_le_group_order)\nqed\n\ntext \\<open>Another useful fact is that a group of prime order is also cyclic.\\<close>\n\nlemma (in group) prime_order_group_is_cyc:\n  assumes \"Factorial_Ring.prime (order G)\"\n  obtains g where \"cyclic_group G g\"\nproof (unfold_locales)\n  obtain p where order_p: \"order G = p\" and p_prime: \"Factorial_Ring.prime p\" using assms by blast\n  then have \"card (carrier G) \\<ge> 2\" by (simp add: order_def prime_ge_2_nat)\n  then obtain a where a_in: \"a \\<in> carrier G\" and a_not_one: \"a \\<noteq> \\<one>\" using one_unique\n    by (metis (no_types, lifting) card_2_iff' obtain_subset_with_card_n subset_iff)\n  interpret fin: finite_group G\n    using assms order_gt_0_iff_finite unfolding order_def by unfold_locales auto\n  have \"ord a dvd p\" using a_in order_p ord_dvd_group_order by blast\n  hence \"ord a = p\" using prime_nat_iff[of p] p_prime ord_eq_1 a_in a_not_one by blast\n  then interpret cyclic_group G a\n    using fin.element_ord_generates_cyclic order_p a_in by simp\n  show ?thesis using that cyclic_group_axioms .\nqed\n\ntext \\<open>What follows is an induction principle for cyclic groups: a predicate is true for all elements\nof the group if it is true for all elements that can be formed by the generating element by just\nmultiplication and if it also holds under the forming of the inverse (as we by this cover\nall elements of the group),\\<close>\n\n(* Manuel Eberl *)\nlemma (in cyclic_group) generator_induct [consumes 1, case_names generate inv]:\n  assumes x: \"x \\<in> carrier G\"\n  assumes IH1: \"\\<And>n::nat. P (gen [^] n)\"\n  assumes IH2: \"\\<And>x. x \\<in> carrier G \\<Longrightarrow> P x \\<Longrightarrow> P (inv x)\"\n  shows   \"P x\"\nproof -\n  from x obtain n :: int where n: \"x = gen [^] n\"\n    using elem_is_gen_pow[of x] by auto\n  show ?thesis\n  proof (cases \"n \\<ge> 0\")\n    case True\n    have \"P (gen [^] nat n)\"\n      by (rule IH1)\n    with True n show ?thesis by simp\n  next\n    case False\n    have \"P (inv (gen [^] nat (-n)))\"\n      by (intro IH1 IH2) auto\n    also have \"gen [^] nat (-n) = gen [^] (-n)\"\n      using False by simp\n    also have \"inv \\<dots> = x\"\n      using n by (simp add: int_pow_neg)\n    finally show ?thesis .\n  qed\nqed\n\n\nsubsection \\<open>Finite cyclic groups\\<close>\n\ntext \\<open>Additionally, the notion of the finite cyclic group is introduced.\\<close>\n\nlocale finite_cyclic_group = finite_group + cyclic_group\n\nsublocale finite_cyclic_group \\<subseteq> finite_comm_group\n  by unfold_locales\n\nlemma (in finite_cyclic_group) ord_gen_gt_zero:\n  \"ord gen > 0\"\n  using ord_ge_1[OF fin gen_closed] by simp\n\ntext \\<open>In order to prove something about an element in a finite abelian group, it is possible to show\nthis property for the neutral element or the generating element and inductively for the elements\nthat are formed by multiplying with the generator.\\<close>\n\nlemma (in finite_cyclic_group) generator_induct0 [consumes 1, case_names one step]:\n  assumes x: \"x \\<in> carrier G\"\n  assumes IH1: \"P \\<one>\"\n  assumes IH2: \"\\<And>x. \\<lbrakk>x \\<in> carrier G; P x\\<rbrakk> \\<Longrightarrow> P (x \\<otimes> gen)\"\n  shows   \"P x\"\nproof -\n  from ord_gen_gt_zero generate_nat_pow[OF _ gen_closed] obtain n::nat where n: \"x = gen [^] n\"\n    using generator x by blast\n  thus ?thesis by (induction n arbitrary: x, use assms in auto)\nqed\n\nlemma (in finite_cyclic_group) generator_induct1 [consumes 1, case_names gen step]:\n  assumes x: \"x \\<in> carrier G\"\n  assumes IH1: \"P gen\"\n  assumes IH2: \"\\<And>x. \\<lbrakk>x \\<in> carrier G; P x\\<rbrakk> \\<Longrightarrow> P (x \\<otimes> gen)\"\n  shows   \"P x\"\nproof(rule generator_induct0[OF x])\n  show \"\\<And>x. \\<lbrakk>x \\<in> carrier G; P x\\<rbrakk> \\<Longrightarrow> P (x \\<otimes> gen)\" using IH2 by blast\n  have \"P x\" if \"n > 0\" \"x = gen [^] n\" for n::nat and x using that\n    by (induction n arbitrary: x; use assms in fastforce)\n  from this[OF ord_pos[OF gen_closed] pow_ord_eq_1[OF gen_closed, symmetric]] show \"P \\<one>\" .\nqed\n\nsubsection \\<open>\\<open>get_exp\\<close> - discrete logarithm\\<close>\n\ntext \\<open>What now follows is the discrete logarithm for groups. It is used at several times througout\nthis entry and is initially used to show that two cyclic groups of the same order are isomorphic.\\<close>\n\ndefinition (in group) get_exp where\n  \"get_exp g = (\\<lambda>a. SOME k::int. a = g [^] k)\"\n\ntext \\<open>For each element with itself as the basis the discrete logarithm indeed does what expected.\nThis is not the strongest possible statement, but sufficient for our needs.\\<close>\n\nlemma (in group) get_exp_self_fulfills:\n  assumes \"a \\<in> carrier G\"\n  shows \"a = a [^] get_exp a a\"\nproof -\n  have \"a = a [^] (1::int)\" using assms by auto\n  moreover have \"a [^] (1::int) = a [^] (SOME x::int. a [^] (1::int) = a [^] x)\"\n    by (intro someI_ex[of \"\\<lambda>x::int. a [^] (1::int) = a [^] x\"]; blast)\n  ultimately show ?thesis unfolding get_exp_def by simp\nqed\n\nlemma (in group) get_exp_self:\n  assumes \"a \\<in> carrier G\"\n  shows \"get_exp a a mod ord a = (1::int) mod ord a\"\n  by (intro pow_eq_int_mod[OF assms], use get_exp_self_fulfills[OF assms] assms in auto)\n\ntext \\<open>For cyclic groups, the discrete logarithm \"works\" for every element.\\<close>\n\nlemma (in cyclic_group) get_exp_fulfills:\n  assumes \"a \\<in> carrier G\"\n  shows \"a = gen [^] get_exp gen a\"\nproof -\n  from elem_is_gen_pow[OF assms] obtain k::int where k: \"a = gen [^] k\" by blast\n  moreover have \"gen [^] k = gen [^] (SOME x::int. gen [^] k = gen [^] x)\"\n    by(intro someI_ex[of \"\\<lambda>x::int. gen [^] k = gen [^] x\"]; blast)\n  ultimately show ?thesis unfolding get_exp_def by blast\nqed\n\nlemma (in cyclic_group) get_exp_non_zero:\n  assumes\"b \\<in> carrier G\" \"b \\<noteq> \\<one>\"\n  shows \"get_exp gen b \\<noteq> 0\"\n  using assms get_exp_fulfills[OF assms(1)] by auto \n\ntext \\<open>One well-known logarithmic identity.\\<close>\n\nlemma (in cyclic_group) get_exp_mult_mod:\n  assumes \"a \\<in> carrier G\" \"b \\<in> carrier G\"\n  shows \"get_exp gen (a \\<otimes> b) mod (ord gen) = (get_exp gen a + get_exp gen b) mod (ord gen)\"\nproof (intro pow_eq_int_mod[OF gen_closed])\n  from get_exp_fulfills[of \"a \\<otimes> b\"] have \"gen [^] get_exp gen (a \\<otimes> b) = a \\<otimes> b\" using assms by simp\n  moreover have \"gen [^] (get_exp gen a + get_exp gen b) = a \\<otimes> b\"\n  proof -\n    have \"gen [^] (get_exp gen a + get_exp gen b) = gen [^] (get_exp gen a) \\<otimes> gen [^] (get_exp gen b)\"\n      using int_pow_mult by blast\n    with get_exp_fulfills assms show ?thesis by simp\n  qed\n  ultimately show \"gen [^] get_exp gen (a \\<otimes> b) = gen [^] (get_exp gen a + get_exp gen b)\" by simp\nqed\n\ntext \\<open>We now show that all functions from a group generated by 'a' to a group generated by 'b'\nthat map elements from $a^k$ to $b^k$ in the other group are in fact isomorphisms between these two\ngroups.\\<close>\n\nlemma (in group) iso_cyclic_groups_generate:\n  assumes \"a \\<in> carrier G\" \"b \\<in> carrier H\" \"group.ord G a = group.ord H b\" \"group H\"\n  shows \"{f. \\<forall>k \\<in> (UNIV::int set). f (a [^] k) = b [^]\\<^bsub>H\\<^esub> k}\n         \\<subseteq> iso (G\\<lparr>carrier := generate G {a}\\<rparr>) (H\\<lparr>carrier := generate H {b}\\<rparr>)\"\nproof\n  interpret H: group H by fact\n  let ?A = \"G\\<lparr>carrier := generate G {a}\\<rparr>\"\n  let ?B = \"H\\<lparr>carrier := generate H {b}\\<rparr>\"\n  interpret A: cyclic_group ?A a by (intro group.cyclic_groupI2; use assms(1) in simp)\n  interpret B: cyclic_group ?B b by (intro group.cyclic_groupI2; use assms(2) in simp)\n  have sA: \"subgroup (generate G {a}) G\" by (intro generate_is_subgroup, use assms(1) in simp)\n  have sB: \"subgroup (generate H {b}) H\" by (intro H.generate_is_subgroup, use assms(2) in simp)\n  fix x\n  assume x: \"x \\<in> {f. \\<forall>k\\<in>(UNIV::int set). f (a [^] k) = b [^]\\<^bsub>H\\<^esub> k}\"\n  have hom: \"x \\<in> hom ?A ?B\"\n  proof (intro homI)\n    fix c\n    assume c: \"c \\<in> carrier ?A\"\n    from A.elem_is_gen_pow[OF this] obtain k::int where k: \"c = a [^] k\"\n      using int_pow_consistent[OF sA generate.incl[of a]] by auto\n    with x have \"x c = b [^]\\<^bsub>H\\<^esub> k\" by blast\n    thus \"x c \\<in> carrier ?B\"\n      using B.int_pow_closed H.int_pow_consistent[OF sB] generate.incl[of b \"{b}\" H] by simp\n    fix d\n    assume d: \"d \\<in> carrier ?A\"\n    from A.elem_is_gen_pow[OF this] obtain l::int where l: \"d = a [^] l\"\n      using int_pow_consistent[OF sA generate.incl[of a]] by auto\n    with k have \"c \\<otimes> d = a [^] (k + l)\" by (simp add: int_pow_mult assms(1))\n    with x have \"x (c \\<otimes>\\<^bsub>?A\\<^esub> d) = b [^]\\<^bsub>H\\<^esub> (k + l)\" by simp\n    also have \"\\<dots> = b [^]\\<^bsub>H\\<^esub> k \\<otimes>\\<^bsub>H\\<^esub> b [^]\\<^bsub>H\\<^esub> l\" by (simp add: H.int_pow_mult assms(2))\n    finally show \"x (c \\<otimes>\\<^bsub>?A\\<^esub> d) = x c \\<otimes>\\<^bsub>?B\\<^esub> x d\" using x k l by simp\n  qed\n  then interpret xgh: group_hom ?A ?B x unfolding group_hom_def group_hom_axioms_def by blast\n  have \"kernel ?A ?B x = {\\<one>}\"\n  proof(intro equalityI)\n    show \"{\\<one>} \\<subseteq> kernel ?A ?B x\" using xgh.one_in_kernel by auto\n    have \"c = \\<one>\" if \"c \\<in> kernel ?A ?B x\" for c\n    proof -\n      from that have c: \"c \\<in> carrier ?A\" unfolding kernel_def by blast\n      from A.elem_is_gen_pow[OF this] obtain k::int where k: \"c = a [^] k\"\n        using int_pow_consistent[OF sA generate.incl[of a]] by auto\n      moreover have \"x c = \\<one>\\<^bsub>H\\<^esub>\" using that x unfolding kernel_def by auto\n      ultimately have \"\\<one>\\<^bsub>H\\<^esub> = b [^]\\<^bsub>H\\<^esub> k\" using x by simp\n      with assms(3) have \"a [^] k = \\<one>\"\n        using int_pow_eq_id[OF assms(1), of k] H.int_pow_eq_id[OF assms(2), of k] by simp\n      thus \"c = \\<one>\" using k by blast\n    qed\n    thus \"kernel ?A ?B x \\<subseteq> {\\<one>}\" by blast             \n  qed\n  moreover have \"carrier ?B \\<subseteq> x ` carrier ?A\"\n  proof\n    fix c\n    assume c: \"c \\<in> carrier ?B\"\n    from B.elem_is_gen_pow[OF this] obtain k::int where k: \"c = b [^]\\<^bsub>H\\<^esub> k\"\n      using H.int_pow_consistent[OF sB generate.incl[of b]] by auto\n    then have \"x (a [^] k) = c\" using x by blast\n    moreover have \"a [^] k \\<in> carrier ?A\"\n      using int_pow_consistent[OF sA generate.incl[of a]] A.int_pow_closed generate.incl[of a]\n      by fastforce\n    ultimately show \"c \\<in> x ` carrier ?A\" by blast\n  qed\n  ultimately show \"x \\<in> iso ?A ?B\" using hom xgh.iso_iff unfolding kernel_def by auto\nqed\n\ntext \\<open>This is then used to derive the isomorphism of two cyclic groups of the same order as a\ndirect consequence.\\<close>\n\nlemma (in cyclic_group) iso_cyclic_groups_same_order:\n  assumes \"cyclic_group H h\" \"order G = order H\"\n  shows \"G \\<cong> H\"\nproof(intro is_isoI)\n  interpret H: cyclic_group H h by fact\n  define f where \"f = (\\<lambda>a. h [^]\\<^bsub>H\\<^esub> get_exp gen a)\"\n  from assms(2) have o: \"ord gen = H.ord h\" using ord_gen_is_group_order H.ord_gen_is_group_order\n    by simp\n  have \"\\<forall>k \\<in> (UNIV::int set). f (gen [^] k) = h [^]\\<^bsub>H\\<^esub> k\"\n  proof\n    fix k\n    assume k: \"k \\<in> (UNIV::int set)\"\n    have \"gen [^] k = gen [^] (SOME x::int. gen [^] k = gen [^] x)\"\n      by(intro someI_ex[of \"\\<lambda>x::int. gen [^] k = gen [^] x\"]; blast)\n    moreover have \"(SOME x::int. gen [^] k = gen [^] x) = (SOME x::int. h [^]\\<^bsub>H\\<^esub> k = h [^]\\<^bsub>H\\<^esub> x)\"\n    proof -\n      have \"gen [^] k = gen [^] x \\<longleftrightarrow> h [^]\\<^bsub>H\\<^esub> k = h [^]\\<^bsub>H\\<^esub> x\" for x::int\n        by (simp add: o group.int_pow_eq)  \n      thus ?thesis by simp\n    qed\n    moreover have \"h [^]\\<^bsub>H\\<^esub> k = h [^]\\<^bsub>H\\<^esub> (SOME x::int. h [^]\\<^bsub>H\\<^esub> k = h [^]\\<^bsub>H\\<^esub> x)\"\n      by(intro someI_ex[of \"\\<lambda>x::int. h [^]\\<^bsub>H\\<^esub> k = h [^]\\<^bsub>H\\<^esub> x\"]; blast)\n    ultimately show \"f (gen [^] k) = h [^]\\<^bsub>H\\<^esub> k\" unfolding f_def get_exp_def by metis\n  qed\n  thus \"f \\<in> iso G H\"\n    using iso_cyclic_groups_generate[OF gen_closed H.gen_closed o H.is_group]\n    by (auto simp flip: generator H.generator)\nqed\n\nsubsection \\<open>Integer modular groups\\<close>\n\ntext \\<open>We show that \\<open>integer_mod_group\\<close> (written as \\<open>Z n\\<close>) is in fact a cyclic group.\nFor $n \\neq 1$ it is generated by $1$ and in the other case by $0$.\\<close>\n\nnotation integer_mod_group (\"Z\")\n\nlemma Zn_neq1_cyclic_group:\n  assumes \"n \\<noteq> 1\"\n  shows \"cyclic_group (Z n) 1\"\nproof(unfold cyclic_group_def cyclic_group_axioms_def, safe)\n  show \"group (Z n)\" using group_integer_mod_group .\n  then interpret group \"Z n\" .\n  show oc: \"1 \\<in> carrier (Z n)\"\n    unfolding integer_mod_group_def integer_group_def using assms by force\n  show \"x \\<in> generate (Z n) {1}\" if \"x \\<in> carrier (Z n)\" for x\n    using generate_pow[OF oc] that int_pow_integer_mod_group solve_equation subgroup_self\n    by fastforce\n  show \"x \\<in> carrier (Z n)\" if \"x \\<in> generate (Z n) {1}\" for x using generate_incl[of \"{1}\"] that oc\n    by fast\nqed\n\nlemma Z1_cyclic_group: \"cyclic_group (Z 1) 0\"\nproof(unfold cyclic_group_def cyclic_group_axioms_def, safe)\n  show \"group (Z 1)\" using group_integer_mod_group .\n  then interpret group \"Z 1\" .\n  show \"0 \\<in> carrier (Z 1)\" unfolding integer_mod_group_def by simp\n  thus \"x \\<in> carrier (Z 1)\" if \"x \\<in> generate (Z 1) {0}\" for x using generate_incl[of \"{0}\"] that\n    by fast\n  show \"x \\<in> generate (Z 1) {0}\" if \"x \\<in> carrier (Z 1)\" for x\n  proof -\n    from that have \"x = 0\" unfolding integer_mod_group_def by auto\n    with generate.one[of \"Z 1\" \"{0}\"] show \"x \\<in> generate (Z 1) {0}\" unfolding integer_mod_group_def\n      by simp\n  qed\nqed\n\nlemma Zn_cyclic_group:\n  obtains x where \"cyclic_group (Z n) x\"\n  using Z1_cyclic_group Zn_neq1_cyclic_group by metis\n\ntext \\<open>Moreover, its order is just $n$.\\<close>\n\nlemma Zn_order: \"order (Z n) = n\"\n  by (unfold integer_mod_group_def integer_group_def order_def, auto)\n\ntext \\<open>Consequently, \\<open>Z n\\<close> is isomorphic to any cyclic group of order $n$.\\<close>\n\nlemma (in cyclic_group) Zn_iso:\n  assumes \"order G = n\"\n  shows \"G \\<cong> Z n\"\n  using Zn_order Zn_cyclic_group iso_cyclic_groups_same_order assms by metis\n\nno_notation integer_mod_group (\"Z\")\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/Finitely_Generated_Abelian_Groups/Finite_And_Cyclic_Groups.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8397339516289534, "lm_q2_score": 0.8519528076067262, "lm_q1q2_score": 0.7154136977329776}}
{"text": "theory PathRel\nimports Main\nbegin\n\ndefinition path :: \"'a rel \\<Rightarrow> 'a list \\<Rightarrow> bool\" where\n\"path r lst = (\\<forall>i < length lst-1. (lst!i, lst!(i+1)) \\<in> r)\"\n\nfun pathR :: \"'a rel \\<Rightarrow> 'a list \\<Rightarrow> bool\" where\n\"pathR r (a#b#rest) = ((a,b) \\<in> r \\<and> pathR r (b#rest))\"\n| \"pathR r _ = True\"\n\nlemma path_defs : \"pathR r lst = path r lst\"\napply (simp add:path_def)\napply (induction lst; simp)\napply (case_tac lst; auto simp add:less_Suc_eq_0_disj)\ndone\n\ndefinition tlR :: \"'a list rel\" where\n\"tlR = {(a#lst,lst) | a lst. True }\"\n\ndefinition push_pop :: \"'a list rel\" where\n\"push_pop = (Id \\<union> tlR \\<union> converse tlR)\"\n\ndefinition sucR :: \"nat rel\" where\n\"sucR = {(Suc n,n) | n. True }\"\n\ndefinition inc_dec :: \"nat rel\" where\n\"inc_dec = (Id \\<union> sucR \\<union> converse sucR)\"\n\nlemma inc_dec_expand : \"inc_dec = {(a,b) | a b. a+1 = b \\<or> a=b \\<or> a = b+1}\"\nby (auto simp:inc_dec_def sucR_def)\n\ntype_synonym 'a lang = \"'a list \\<Rightarrow> bool\"\n\nfun invL :: \"'a set \\<Rightarrow> 'a lang\" where\n\"invL s [] = True\"\n| \"invL s lst = (hd lst \\<in> s \\<and> last lst \\<in> s)\"\n\ndefinition seq :: \"'a lang \\<Rightarrow> 'a lang \\<Rightarrow> 'a lang\" where\n\"seq a b lst = (\\<exists>u v. a u \\<and> b v \\<and> lst = u@v)\"\n\ndefinition star :: \"'a lang \\<Rightarrow> 'a lang\" where\n\"star x lst = (\\<exists>l. \\<forall>el. el \\<in> set l \\<and> concat l = lst)\"\n\n(* *)\ndefinition inc_decL :: \"nat lang\" where\n\"inc_decL lst = pathR inc_dec lst\"\n\nlemma test :\n   \"inc_decL lst \\<Longrightarrow>\n    i < length lst - 1 \\<Longrightarrow>\n    lst!i = lst!(i+1) \\<or> lst!i = lst!(i+1)+1 \\<or> lst!i+1 = lst!(i+1)\"\nby (auto simp add:inc_decL_def inc_dec_def sucR_def path_defs path_def)\n\ndefinition push_popL :: \"'a list lang\" where\n\"push_popL lst = pathR push_pop lst\"\n\nlemma push_pop_inc_dec :\n   \"(a,b) \\<in> push_pop \\<Longrightarrow>\n    (length a, length b) \\<in> inc_dec\"\nby (auto simp: push_pop_def inc_dec_def sucR_def tlR_def)\n\ndefinition mapR :: \"'a rel \\<Rightarrow> ('a \\<Rightarrow> 'b) \\<Rightarrow> 'b rel\" where\n\"mapR r f = {(f x,f y) | x y. (x,y) \\<in> r}\"\n\ndefinition mapR2 :: \"'a rel \\<Rightarrow> ('b \\<Rightarrow> 'a) \\<Rightarrow> 'b rel\" where\n\"mapR2 r f = {(x, y) | x y. (f x,f y) \\<in> r}\"\n\nlemma push_pop_inc_dec_map : \"mapR push_pop length \\<subseteq> inc_dec\"\nunfolding mapR_def\nusing push_pop_inc_dec by fastforce\n\ndefinition hd_last :: \"'a list \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> bool\" where\n\"hd_last lst a b = (hd lst = a \\<and> last lst = b \\<and> length lst > 0)\"\n\nlemma converse_rev : \"pathR r lst \\<Longrightarrow> pathR (converse r) (rev lst)\"\nunfolding path_defs path_def\n  by (smt Suc_diff_Suc Suc_eq_plus1_left add.commute add.right_neutral converse.intros diff_Suc_less le_less_trans length_rev less_diff_conv not_add_less1 not_less rev_nth)\n\nlemma sym_rev : \"sym r \\<Longrightarrow> pathR r lst \\<Longrightarrow> pathR r (rev lst)\"\n  by (metis converse_rev sym_conv_converse_eq)\n\nlemma list_all_values :\n   \"inc_decL lst \\<Longrightarrow>\n    length lst > 0 \\<Longrightarrow>\n    last lst \\<le> hd lst \\<Longrightarrow>\n    {last lst .. hd lst} \\<subseteq> set lst\"\napply (induction lst)\napply (auto simp add:inc_decL_def inc_dec_def sucR_def)\napply (case_tac lst; auto; fastforce)\ndone\n\nlemma sym_inc_dec : \"sym inc_dec\"\n  by (simp add: inc_dec_def sup_assoc sym_Id sym_Un sym_Un_converse)\n\n\nlemma list_all_values2 :\n   \"inc_decL lst \\<Longrightarrow>\n    length lst > 0 \\<Longrightarrow>\n    {min (hd lst) (last lst) .. max (hd lst) (last lst)} \\<subseteq> set lst\"\napply (cases \"last lst \\<le> hd lst\")\n  using list_all_values apply fastforce\n  using list_all_values [of \"rev lst\"]\n  by (simp add: sym_rev hd_rev inc_decL_def sym_inc_dec last_rev max_def min_def)\n\ndefinition takeLast :: \"nat \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where\n\"takeLast n lst = rev (take n (rev lst))\"\n\nlemma takeLast_drop :\n  \"takeLast n lst = drop (length lst - n) lst\"\napply (induction lst arbitrary:n)\napply (auto simp add:takeLast_def)\n  by (metis length_Cons length_rev rev.simps(2) rev_append rev_rev_ident take_append take_rev)\n\n(* unchanged *)\nlemma next_unchanged :\n  \"(st1, st2) \\<in> push_pop \\<Longrightarrow>\n   l \\<le> length st2 \\<Longrightarrow>\n   l \\<le> length st1 \\<Longrightarrow>\n   takeLast l st2 = takeLast l st1\"\nby (auto simp:push_pop_def tlR_def takeLast_def)\n\nlemma pathR2 : \"pathR r [a, b] = ((a,b) \\<in> r)\"\nby auto\n\nlemma pathR3 :\n \"pathR r (a # b # list) = ((a,b) \\<in> r \\<and> pathR r (b#list))\"\nby auto\n\ndeclare pathR.simps [simp del]\n\nlemma stack_unchanged :\n  \"push_popL lst \\<Longrightarrow>\n   length lst > 0 \\<Longrightarrow>\n   (* hd_last lst a b \\<Longrightarrow> *)\n   \\<forall>sti \\<in> set lst. l \\<le> length sti \\<Longrightarrow>\n   takeLast l (hd lst) = takeLast l (last lst)\"\napply (induction lst)\napply (auto simp:push_popL_def hd_last_def)\nby (metis (no_types, lifting) hd_conv_nth list.set_cases list.set_sel(1) next_unchanged nth_Cons_0 pathR.simps(1))\n\nlemma take_all [simp] : \"takeLast (length a) a = a\"\nby (simp add:takeLast_def)\n\nlemma find_return :\n   \"push_popL lst \\<Longrightarrow>\n    length lst > 0 \\<Longrightarrow>\n    length (last lst) \\<le> length (hd lst) \\<Longrightarrow>\n    takeLast (length (last lst)) (hd lst) \\<in> set lst\"\napply (induction lst; auto simp:push_pop_def push_popL_def)\napply (case_tac lst; auto)\n  apply (metis PathRel.take_all le_refl next_unchanged pathR.simps(1) push_pop_def)\napply (auto simp:pathR.simps)\n  apply (smt Nitpick.size_list_simp(2) PathRel.take_all basic_trans_rules(31) inf_sup_aci(5) le_SucE list.sel(3) mem_Collect_eq next_unchanged prod.sel(1) prod.sel(2) push_pop_def sup.cobounded2 tlR_def zero_order(2))\n  by (smt Suc_leD Suc_leI inf_sup_aci(5) inf_sup_ord(3) le_imp_less_Suc length_Cons mem_Collect_eq next_unchanged prod.inject push_pop_def subset_eq tlR_def)\n\ndefinition monoI :: \"('a \\<Rightarrow> bool) \\<Rightarrow> ('a * 'a list) \\<Rightarrow> bool\" where\n\"monoI iv v = (\\<forall>i < length (snd v). iv (snd v!i) \\<longrightarrow> iv ((fst v#snd v)!i))\"\n\ndefinition mono_same :: \"('a \\<Rightarrow> bool) \\<Rightarrow> ('a * 'a list) rel\" where\n\"mono_same iv = {((g1,lst), (g2,lst)) | lst g1 g2. iv g1 \\<longrightarrow> iv g2}\"\n\ndefinition mono_pop :: \"('a \\<Rightarrow> bool) \\<Rightarrow> ('a * 'a list) rel\" where\n\"mono_pop iv =\n   {((g1,a#lst), (g2,lst)) | lst g1 g2 a. iv g1 \\<longrightarrow> iv a \\<longrightarrow> iv g2}\"\n\ndefinition mono_push :: \"('a \\<Rightarrow> bool) \\<Rightarrow> ('a * 'a list) rel\" where\n\"mono_push iv =\n   {((g1,lst), (g2,a#lst)) | lst g1 g2 a. iv g1 \\<longrightarrow> iv a} \\<inter>\n   {((g1,lst), (g2,a#lst)) | lst g1 g2 a. iv a \\<longrightarrow> iv g2}\"\n\ndefinition mono_rules :: \"('a \\<Rightarrow> bool) \\<Rightarrow> ('a * 'a list) rel\" where\n\"mono_rules iv = mono_same iv \\<union> mono_pop iv \\<union> mono_push iv\"\n\nlemma mono_same :\n   \"monoI iv a \\<Longrightarrow>\n    (a,b) \\<in> mono_same iv \\<Longrightarrow>\n    monoI iv b\"\nunfolding monoI_def mono_same_def\n  using less_SucI less_Suc_eq_0_disj by fastforce\n\nlemma mono_push :\n   \"monoI iv (v1,lst) \\<Longrightarrow>\n    ((v1, lst), (v2,a#lst)) \\<in> mono_push iv \\<Longrightarrow>\n    monoI iv (v2,a#lst)\"\nunfolding monoI_def mono_push_def\napply auto\n  apply (metis diff_Suc_1 less_Suc_eq_0_disj nth_Cons')\n  apply (metis diff_Suc_1 less_Suc_eq_0_disj nth_Cons')\n  apply (metis diff_Suc_1 less_Suc_eq_0_disj nth_Cons')\ndone\n\nlemma mono_pop :\n   \"monoI iv (v1,a#lst) \\<Longrightarrow>\n    ((v1,a#lst), (v2,lst)) \\<in> mono_pop iv \\<Longrightarrow>\n    monoI iv (v2,lst)\"\nunfolding monoI_def mono_pop_def\napply auto\n  apply (metis Suc_mono length_Cons less_SucI list.sel(3) nth_Cons' nth_tl)\n  apply (metis Suc_mono length_Cons less_SucI list.sel(3) nth_Cons' nth_tl)\n  apply (metis Suc_mono length_Cons less_SucI list.sel(3) nth_Cons' nth_tl)\ndone\n\nlemma mono_works :\n   \"monoI iv (v1,lst1) \\<Longrightarrow>\n    ((v1,lst1), (v2,lst2)) \\<in> mono_rules iv \\<Longrightarrow>\n    (lst1, lst2) \\<in> push_pop \\<Longrightarrow>\n    monoI iv (v2,lst2)\"\napply (auto simp add: push_pop_def)\nusing mono_same [of iv \"(v1,lst2)\" \"(v2,lst2)\"]\n  apply (smt Int_iff Pair_inject UnE mem_Collect_eq mono_pop mono_pop_def mono_push_def mono_rules_def)\n  apply (smt Int_iff UnE fst_conv mem_Collect_eq mono_pop mono_push mono_push_def mono_rules_def mono_same snd_conv tlR_def)\n  by (smt UnE fst_conv mem_Collect_eq mono_pop mono_pop_def mono_push mono_rules_def mono_same snd_conv tlR_def)\n\ndefinition first :: \"('a \\<Rightarrow> bool) \\<Rightarrow> nat \\<Rightarrow> 'a list \\<Rightarrow> bool\" where\n\"first P k lst ==\n   k < length lst \\<and> P (lst!k) \\<and> (\\<forall>k2 < k. \\<not>P (lst!k2))\"\n\ndefinition first_smaller :: \"nat \\<Rightarrow> nat list \\<Rightarrow> bool\" where\n\"first_smaller k lst = first (\\<lambda>b. b < hd lst) k lst\"\n\ndefinition first_one_smaller :: \"nat \\<Rightarrow> nat list \\<Rightarrow> bool\" where\n\"first_one_smaller k lst = first (\\<lambda>b. Suc b = hd lst) k lst\"\n\nlemma pathR_take : \"pathR r lst \\<Longrightarrow> pathR r (take k lst)\"\nby (simp add:path_defs path_def)\n\nlemma pathR_drop : \"pathR r lst \\<Longrightarrow> pathR r (drop k lst)\"\nby (simp add:path_defs path_def)\n\ndefinition clip :: \"nat \\<Rightarrow> nat \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where\n\"clip k k3 lst = take (k - k3 + 1) (drop k3 lst)\"\n\nlemma pathR_clip : \"pathR r lst \\<Longrightarrow> pathR r (clip k1 k2 lst)\"\nby (simp add:pathR_drop pathR_take clip_def)\n\nlemma hd_clip :\n   \"k3 < k \\<Longrightarrow> k < length lst \\<Longrightarrow>\n    hd (clip k k3 lst) = lst!k3\"\nunfolding clip_def\n  by (metis Cons_nth_drop_Suc Nat.add_0_right One_nat_def add_Suc_right list.sel(1) order.strict_trans take_Suc_Cons)\n\nlemma last_index :\n   \"length lst > 0 \\<Longrightarrow> last lst = lst!(length lst-1)\"\n  using last_conv_nth by auto\n\nlemma last_clip :\n   \"k3 < k \\<Longrightarrow> k < length lst \\<Longrightarrow>\n    last (clip k k3 lst) = lst!k\"\nunfolding clip_def\nby (auto simp add: last_conv_nth min.absorb2)\n\nlemma hd_take : \"hd (take (Suc k3) lst) = hd lst\"\n  by (metis list.sel(1) take_Nil take_Suc)\n\nlemma last_take :\n  \"length lst > k3 \\<Longrightarrow>\n   last (take (Suc k3) lst) = lst!k3\"\n  by (simp add: take_Suc_conv_app_nth)\n\n\nlemma first_smaller1 :\n   \"inc_decL lst \\<Longrightarrow>\n    first_one_smaller k lst \\<Longrightarrow>\n    first_smaller k lst\"\napply (cases \"length lst > 0\")\napply (auto simp:first_one_smaller_def first_def first_smaller_def)\nsubgoal for k3\nusing list_all_values [of \"take (Suc k3) lst\"]\napply (auto simp:inc_decL_def pathR_take hd_clip last_clip\n  hd_take last_take)\napply (cases \"lst!k \\<in> set (take (Suc k3) lst)\")\n  apply (smt Suc_leI in_set_conv_nth le_neq_implies_less length_take min.absorb2 nth_take order.strict_trans)\n  by (simp add: less_Suc_eq_le set_mp)\ndone\n\nlemma inc_dec_too_large :\n\"z \\<ge> y \\<Longrightarrow>\n (z, x) \\<in> inc_dec \\<Longrightarrow>  \n Suc x < y \\<Longrightarrow> False\"\nby (auto simp add:inc_dec_def sucR_def)\n\nlemma first_smaller2 :\n   \"inc_decL lst \\<Longrightarrow>\n    first_smaller k lst \\<Longrightarrow>\n    first_one_smaller k lst\"\napply (cases \"length lst > 0\")\napply (auto simp:first_one_smaller_def first_def first_smaller_def)\nusing list_all_values [of \"take (Suc k) lst\"]\napply (auto simp:inc_decL_def pathR_take hd_clip last_clip\n  hd_take last_take)\napply (cases \"Suc (lst ! k) < hd lst\"; auto)\napply (cases \"length lst > 1\"; auto)\ndefer\napply (cases \"length lst = 1\"; auto)\n  apply (simp add: hd_conv_nth)\napply (rule inc_dec_too_large [of \"hd lst\" \"lst!(k-1)\" \"lst!k\"])\napply auto\n  apply (metis diff_is_0_eq diff_less dual_order.strict_implies_order hd_conv_nth less_Suc_eq_le not_le)\napply (auto simp add:path_defs path_def)\n  by (smt One_nat_def Suc_eq_plus1 Suc_lessI Suc_n_not_le_n diff_less hd_conv_nth less_diff_conv less_or_eq_imp_le neq0_conv)\n\ndefinition minList :: \"nat list \\<Rightarrow> nat\" where\n\"minList lst = foldr min lst (hd lst)\"\n\ndefinition maxList :: \"nat list \\<Rightarrow> nat\" where\n\"maxList lst = foldr max lst (hd lst)\"\n\nlemma min_exists_aux :\n   \"n < length lst \\<Longrightarrow>\n    0 < length lst \\<Longrightarrow>\n    foldr min lst (x::nat) \\<le> lst!n\"\napply (induction lst arbitrary:n x; auto)\n  using less_Suc_eq_0_disj min.coboundedI2 by fastforce\n\nlemma max_exists_aux :\n   \"n < length lst \\<Longrightarrow>\n    0 < length lst \\<Longrightarrow>\n    foldr max lst (x::nat) \\<ge> lst!n\"\napply (induction lst arbitrary:n x; auto)\n  using less_Suc_eq_0_disj max.coboundedI2 by fastforce\n\nlemma min_exists :\n   \"length lst > 0 \\<Longrightarrow> n < length lst \\<Longrightarrow>\n    minList lst \\<le> lst!n\"\nunfolding minList_def\nusing min_exists_aux by simp\n\nlemma max_exists :\n   \"length lst > 0 \\<Longrightarrow> n < length lst \\<Longrightarrow>\n    maxList lst \\<ge> lst!n\"\nunfolding maxList_def\nusing max_exists_aux by simp\n\n\nlemma min_max :\n  \"length lst > 0 \\<Longrightarrow>\n   set lst \\<subseteq> {minList lst .. maxList lst}\"\nby (metis atLeastAtMost_iff in_set_conv_nth max_exists min_exists subsetI)\n\nlemma minList_one : \"minList [a] = a\"\nby (simp add:minList_def)\n\nlemma min_aux : \"foldr min lst (x::nat) \\<le> x\"\nby (induction lst arbitrary:x; auto simp add: min.coboundedI2)\n\nlemma max_aux : \"foldr max lst (x::nat) \\<ge> x\"\nby (induction lst arbitrary:x; auto simp add: max.coboundedI2)\n\nlemma minlist1 : \"a \\<le> b \\<Longrightarrow> minList (a # b # list) = minList (a#list)\"\nby (simp add: minList_def)\n\nlemma maxlist1 : \"a \\<ge> b \\<Longrightarrow> maxList (a # b # list) = maxList (a#list)\"\nby (simp add: maxList_def)\n\nlemma min_smaller :\n   \"x \\<le> y \\<Longrightarrow> foldr min lst (x::nat) \\<le> foldr min lst y\"\nby (induction lst arbitrary:x; auto simp add: min.coboundedI2)\n\nlemma min_min : \"a \\<ge> (b::nat) \\<Longrightarrow> min a (min b c) = min b c\"\nby simp\n\nlemma min_min2 : \"a \\<le> (b::nat) \\<Longrightarrow> min a (min b c) = min a c\"\nby simp\n\nlemma min_simp : \"a < (b::nat) \\<Longrightarrow> min b a = a\"\nby simp\n\nlemma min_of_min :\n   \"b \\<le> (a::nat) \\<Longrightarrow> min b (foldr min lst a) = min b (foldr min lst b)\"\nby (induction lst; auto)\n\nlemma max_of_max :\n   \"b \\<ge> (a::nat) \\<Longrightarrow> max b (foldr max lst a) = max b (foldr max lst b)\"\nby (induction lst; auto)\n\nlemma minlist_swap :\n   \"minList (a # b # list) = minList (b # a # list)\"\napply (simp add: minList_def)\napply (cases \"a \\<ge> b\")\napply (auto simp add:min_min min_min2)\napply (rule min_of_min; auto)\nusing min_of_min [of a b list]\n  by auto\n\nlemma maxlist_swap :\n   \"maxList (a # b # list) = maxList (b # a # list)\"\nby (simp add: maxList_def;cases \"a \\<le> b\"; metis linear max.left_commute max_of_max)\n\nlemma minlist2 : \"a \\<ge> b \\<Longrightarrow> minList (a # b # list) = minList (b#list)\"\n  using minlist1 minlist_swap by fastforce\n\nlemma maxlist2 : \"a \\<le> b \\<Longrightarrow> maxList (a # b # list) = maxList (b#list)\"\n  using maxlist1 maxlist_swap by fastforce\n\nlemma find_min :\n  \"length lst > 0 \\<Longrightarrow> \\<exists>k. minList lst = lst!k\"\napply (induction lst; auto)\napply (case_tac lst; auto simp add:minList_one)\n  apply (metis nth_Cons_0)\napply (case_tac \"aa \\<le> a\")\napply (simp add:minlist2)\n  apply (metis nth_Cons_Suc)\napply (case_tac \"a \\<le> aa\")\napply (case_tac k)\napply auto\napply (simp add:minList_def min_min2)\napply (rule exI[where x = 0])\napply auto\n  apply (metis min_absorb2 min_aux min_def min_of_min)\napply (case_tac \"a \\<le> minList (aa#list)\")\napply auto\napply (rule exI[where x = 0])\napply auto\napply (simp add:minList_def min_min2)\n  apply (metis min.absorb2 min_aux min_def min_of_min)\nsubgoal for a b list nat\napply (rule exI[where x = \"nat+2\"])\napply auto\napply (simp add:minList_def min_min2)\n  by (metis min_def min_of_min)\ndone\n\nlemma find_max :\n  \"length lst > 0 \\<Longrightarrow> \\<exists>k. maxList lst = lst!k\"\napply (induction lst; auto)\napply (case_tac lst; auto)\napply (simp add:maxList_def)\n  apply (metis nth_Cons_0)\napply (case_tac \"aa \\<ge> a\")\napply (simp add:maxlist2)\n  apply (metis nth_Cons_Suc)\napply (case_tac \"a \\<ge> aa\")\napply (case_tac k)\napply auto\napply (rule exI[where x = 0])\n  apply (metis foldr.simps(2) list.sel(1) max.orderE maxList_def max_of_max nth_Cons_0 o_apply)\napply (case_tac \"a \\<ge> maxList (aa#list)\")\napply auto\napply (rule exI[where x = 0])\napply auto\n  apply (metis foldr.simps(2) list.sel(1) max.orderE maxList_def max_of_max o_apply)\nsubgoal for a b list nat\napply (rule exI[where x = \"nat+2\"])\napply auto\napply (simp add:maxList_def)\n  by (smt inf_sup_aci(5) max_def max_of_max sup_nat_def)\ndone\n\nlemma find_max2 :\n  \"length lst > 0 \\<Longrightarrow> \\<exists>k < length lst. maxList lst = lst!k\"\napply (induction lst; auto)\napply (case_tac lst; auto)\napply (simp add:maxList_def)\napply (case_tac \"aa \\<ge> a\")\napply (simp add:maxlist2)\n  apply auto[1]\napply (case_tac \"a \\<ge> aa\")\napply (case_tac k)\napply auto\napply (rule exI[where x = 0])\nsubgoal for a b list\napply auto\n  apply (metis foldr.simps(2) list.sel(1) max.orderE maxList_def max_of_max o_apply)\ndone\napply (case_tac \"a \\<ge> maxList (aa#list)\")\napply auto\napply (rule exI[where x = 0])\napply auto\n  apply (metis foldr.simps(2) list.sel(1) max.orderE maxList_def max_of_max o_apply)\nsubgoal for a b list nat\napply (rule exI[where x = \"nat+2\"])\napply auto\napply (simp add:maxList_def)\n  by (smt inf_sup_aci(5) max_def max_of_max sup_nat_def)\ndone\n\nlemma find_min2 :\n  \"length lst > 0 \\<Longrightarrow> \\<exists>k < length lst. minList lst = lst!k\"\napply (induction lst; auto)\napply (case_tac lst; auto)\napply (simp add:minList_def)\napply (case_tac \"aa \\<le> a\")\napply (simp add:minlist2)\n  apply auto[1]\napply (case_tac \"a \\<le> aa\")\napply (case_tac k)\napply auto\napply (rule exI[where x = 0])\nsubgoal for a b list\napply auto\n  apply (metis foldr.simps(2) list.sel(1) min.orderE minList_def min_of_min o_apply)\ndone\napply (case_tac \"a \\<le> minList (aa#list)\")\napply auto\napply (rule exI[where x = 0])\napply auto\n  apply (metis foldr.simps(2) list.sel(1) min.orderE minList_def min_of_min o_apply)\nsubgoal for a b list nat\napply (rule exI[where x = \"nat+2\"])\napply auto\napply (simp add:minList_def)\n  by (smt inf_sup_aci(5) min_def min_of_min sup_nat_def)\ndone\n\nlemma clip_set : \"set (clip imin imax lst) \\<subseteq> set lst\"\n  by (metis clip_def dual_order.trans set_drop_subset set_take_subset)\n\nlemma min_max_all_values :\n   \"inc_decL lst \\<Longrightarrow>\n    length lst > 0 \\<Longrightarrow>\n    {minList lst .. maxList lst} \\<subseteq> set lst\"\nusing find_min2 [of lst] find_max2 [of lst]\napply clarsimp\nsubgoal for x imin imax\napply (case_tac \"imax = imin\")\napply simp\n\napply (case_tac \"imax < imin\")\nusing list_all_values [of \"clip imin imax lst\"]\napply (simp add:hd_clip last_clip inc_decL_def\n  pathR_clip)\napply (cases \"clip imin imax lst = []\"; auto)\napply (simp add:clip_def)\nusing clip_set [of imin imax lst]\n  using atLeastAtMost_iff apply blast\n\napply (case_tac \"imin < imax\"; auto)\nusing list_all_values2 [of \"clip imax imin lst\"]\napply (simp add:hd_clip last_clip inc_decL_def\n  pathR_clip)\napply (cases \"clip imax imin lst = []\"; auto)\napply (simp add:clip_def)\nusing clip_set [of imax imin lst]\n  by fastforce\ndone\n\nlemma min_max_all_values2 :\n   \"inc_decL lst \\<Longrightarrow>\n    length lst > 0 \\<Longrightarrow>\n    {minList lst .. maxList lst} = set lst\"\n  by (simp add: antisym min_max min_max_all_values)\n\nlemma push_popL_inc_decL :\n   \"push_popL lst \\<Longrightarrow> inc_decL (map length lst)\"\nby (auto simp add:push_popL_def inc_decL_def path_defs path_def\n                     push_pop_inc_dec)\n\ndefinition first_return :: \"nat \\<Rightarrow> 'a list list \\<Rightarrow> bool\" where\n\"first_return k lst =\n    first (\\<lambda>b. (hd lst,b) \\<in> tlR) k lst\"\n\nlemma takeLast_cons :\n  \"takeLast (length lst) (a # lst) = lst\"\nby (simp add:takeLast_def)\n\n(* *)\nlemma first_return_smaller :\n   \"push_popL lst \\<Longrightarrow>\n    first_return k lst \\<Longrightarrow>\n    first_one_smaller k (map length lst)\"\napply (cases \"length lst > 0\")\napply (auto simp:first_one_smaller_def first_def\n   first_return_def tlR_def hd_map)\nsubgoal for a k1\nusing find_return [of \"take (Suc k1) lst\"]\napply (simp add:hd_take last_take)\napply (cases \"push_popL (take (Suc k1) lst)\")\napply (auto simp add:takeLast_cons push_popL_def pathR_take)\napply (smt in_set_conv_nth length_take less_SucE less_imp_le_nat less_trans_Suc min.absorb2 nth_take order.strict_trans)\ndone\ndone\n\nlemma first_smaller_return :\n   \"push_popL lst \\<Longrightarrow>\n    first_smaller k (map length lst) \\<Longrightarrow>\n    first_one_smaller k (map length lst) \\<Longrightarrow>\n    first_return k lst\"\napply (cases \"length lst > 0\")\napply (auto simp:first_one_smaller_def\n   first_smaller_def first_def\n   first_return_def tlR_def hd_map)\napply (cases \"hd lst\"; auto)\nsubgoal for a list\nusing stack_unchanged [of \"take (Suc k) lst\" \"length list\"]\napply (simp add:push_popL_def pathR_take hd_take last_take\n  takeLast_def)\n  by (smt Suc_leD in_set_conv_nth length_take less_SucE less_or_eq_imp_le min.absorb2 not_le nth_take)\ndone\n\n(* call includes enter and exit *)\ndefinition call :: \"'a list list \\<Rightarrow> bool\" where\n\"call lst = (\n   length lst > 2 \\<and>\n   (lst!1, lst!0) \\<in> tlR \\<and>\n   push_popL lst \\<and>\n   first_return (length lst-2) (tl lst))\"\n\ndefinition ncall :: \"nat list \\<Rightarrow> bool\" where\n\"ncall lst = (\n   length lst > 2 \\<and>\n   (lst!1, lst!0) \\<in> sucR \\<and>\n   inc_decL lst \\<and>\n   first_one_smaller (length lst-2) (tl lst))\"\n\n(* a call is a kind of a cycle...\n   perhaps cycles have useful features *)\nlemma call_stack_length :\n  \"call lst \\<Longrightarrow> hd lst = last lst\"\napply (auto simp add:call_def first_return_def first_def tlR_def)\n  by (metis One_nat_def Suc_diff_Suc Suc_lessD hd_conv_nth last_conv_nth length_tl less_numeral_extra(2) list.inject list.size(3) nth_tl numeral_2_eq_2 zero_less_diff)\n\nlemma ncall_stack_length :\n  \"ncall lst \\<Longrightarrow> hd lst = last lst\"\napply (auto simp add:ncall_def first_one_smaller_def first_def sucR_def)\n  by (metis (no_types, hide_lams) One_nat_def Suc_1 Suc_diff_Suc diff_Suc_1 gr_implies_not_zero hd_conv_nth in_set_conv_nth last_index length_pos_if_in_set length_tl less_trans_Suc list.size(3) nth_tl zero_less_numeral)\n\nlemma pathR_tl : \"pathR r lst \\<Longrightarrow> pathR r (tl lst)\"\napply (auto simp add:path_defs path_def)\n  by (simp add: nth_tl)\n\n\nlemma call_ncall : \"call lst \\<Longrightarrow> ncall (map length lst)\"\napply (auto simp add:call_def ncall_def tlR_def sucR_def)\n  apply (metis Suc_lessD nth_map numeral_2_eq_2)\n  using push_popL_inc_decL apply auto[1]\nusing first_return_smaller [of \"tl lst\" \"length lst - 2\"]\nby (simp add:push_popL_def pathR_tl map_tl)\n\nlemma ncall_call :\n   \"ncall (map length lst) \\<Longrightarrow>\n    push_popL lst \\<Longrightarrow>\n    call lst\"\napply (auto simp add:call_def ncall_def tlR_def sucR_def)\napply (cases \"lst!1\"; auto)\napply (subst (asm) nth_map)\napply auto\napply (simp add:push_popL_def path_defs path_def push_pop_def\n  tlR_def)\nsubgoal for a list proof -\n  fix a :: 'a and list :: \"'a list\"\n  assume a1: \"\\<forall>i<length lst - Suc 0. lst ! i = lst ! Suc i \\<or> (\\<exists>a. lst ! i = a # lst ! Suc i) \\<or> (\\<exists>a. lst ! Suc i = a # lst ! i)\"\n  assume a2: \"2 < length lst\"\n  assume a3: \"length list = length (lst ! 0)\"\n  assume a4: \"lst ! Suc 0 = a # list\"\n  have \"[] \\<noteq> tl lst\"\n    using a2 by (metis (no_types) One_nat_def Suc_pred length_tl less_Suc_eq less_trans_Suc list.size(3) nat_neq_iff zero_less_numeral)\n  then show \"list = lst ! 0\"\n  using a4 a3 a1 by (metis (no_types) One_nat_def length_Cons length_greater_0_conv length_tl less_Suc_eq list.sel(3) nat_neq_iff)\nqed\napply (rule first_smaller_return)\napply (simp add:push_popL_def pathR_tl)\napply (rule first_smaller1)\napply (auto simp add:inc_decL_def pathR_tl map_tl)\ndone\n\n(* extended call might have some stuff around it *)\ndefinition ecall :: \"'a list list \\<Rightarrow> 'a list \\<Rightarrow> bool\" where\n\"ecall lst s = (\\<exists>k1 k2.\n   k1 < k2 \\<and> k2 < length lst \\<and> call (clip k2 k1 lst) \\<and>\n   set (take (Suc k1) lst) = {s} \\<and>\n   set (drop k2 lst) = {s})\"\n\ndefinition scall :: \"'a list list \\<Rightarrow> 'a list \\<Rightarrow> bool\" where\n\"scall lst s = (call lst \\<and> hd lst = s)\"\n\ndefinition sncall :: \"nat list \\<Rightarrow> nat \\<Rightarrow> bool\" where\n\"sncall lst s = (ncall lst \\<and> hd lst = s)\"\n\ndefinition const_seq :: \"'a list \\<Rightarrow> 'a \\<Rightarrow> bool\" where\n\"const_seq lst s = (set lst \\<subseteq> {s})\"\n\nlemma const_single : \"const_seq [x] x\"\nby (simp add:const_seq_def)\n\n(* perhaps naturals can be divided into sequences easier? *)\n\ndefinition call_end :: \"nat list \\<Rightarrow> nat \\<Rightarrow> bool\" where\n\"call_end lst s = (\n   length lst > 1 \\<and>\n   Suc s = hd lst \\<and>\n   inc_decL lst \\<and>\n   first_one_smaller (length lst-1) lst)\"\n\n(*\n\nfind index\n\nfun split_at :: \"nat \\<Rightarrow> nat list \\<Rightarrow> nat list * nat list\" where\n\"split_at a [] = [[]]\"\n\"\"\n*)\n\nfun decompose :: \"nat list \\<Rightarrow> nat \\<Rightarrow> nat list list\" where\n\"decompose lst n = (\n   let l1 = takeWhile (%k. k > n) lst in\n   let rest = dropWhile (%k. k > n) lst in\n   if length rest = 0 then [l1] else\n   if length rest = 1 \\<or> length (tl rest) \\<ge> length lst\n      then [l1@[hd rest]] else\n   (l1@[hd rest]) # decompose (tl rest) n\n)\"\n\nlemma concat_decompose_base :\n   \"dropWhile pred lst = [] \\<Longrightarrow> takeWhile pred lst = lst\"\nby (induction lst; auto; metis list.distinct(1))\n\nlemma concat_decompose_base2 :\n   \"dropWhile pred lst = [a] \\<Longrightarrow> takeWhile pred lst @ [a] = lst\"\nby (induction lst; auto; metis list.distinct(1))\n\nlemma concat_decompose_step :\n   \"dropWhile pred lst = a#rest \\<Longrightarrow>\n    takeWhile pred lst @ [a] @ rest = lst\"\n  by (metis append_Cons append_Nil takeWhile_dropWhile_id)\n\nfun findIndices :: \"'a list \\<Rightarrow> 'a \\<Rightarrow> nat list\" where\n\"findIndices (b#rest) a =\n   (if a = b then [0] else []) @ map Suc (findIndices rest a)\"\n| \"findIndices [] a = []\"\n\nlemma get_index :\n   \"i \\<in> set (findIndices lst a) \\<Longrightarrow> lst!i = a\"\nby (induction lst arbitrary:i; auto)\n\nlemma do_find :\n   \"length (findIndices lst a) > 0 \\<Longrightarrow>\n    take (hd (findIndices lst a)) lst @ [a] @\n    drop (hd (findIndices lst a)+1) lst = lst\"\nby (induction lst; auto simp add: hd_map)\n\nlemma tl_map_suc :\n   \"tl lst = map f lst2 \\<Longrightarrow>\n    tl (map g lst) = map (%x. g (f x)) lst2\"\nby (induction lst arbitrary:lst2; auto)\n\nlemma split_findIndices :\n   \"length (findIndices lst a) > 0 \\<Longrightarrow>\n    tl (findIndices lst a) =\n    map (%i. i + (hd (findIndices lst a)) + 1)\n    (findIndices (drop (hd (findIndices lst a)+1) lst) a)\"\nby (induction lst; auto simp add: hd_map tl_map_suc)\n\nlemma sorted_indices_aux :\n  \"findIndices lst a = i1 # i2 # ilst \\<Longrightarrow>\n   i1 < i2\"\nusing split_findIndices [of lst a]\nby auto\n\nlemma tl_suc_rule :\n   \"length lst > 1 \\<Longrightarrow>\n    tl lst! i < tl lst ! Suc i \\<Longrightarrow>\n    lst! Suc i < lst ! Suc (Suc i)\"\nby (cases lst; auto)\n\nlemma map_suc_rule :\n\"n < length lst \\<Longrightarrow> m < length lst \\<Longrightarrow>\n lst!n < lst!m \\<Longrightarrow>\n map (\\<lambda>i. Suc (i + x)) lst ! n < map (\\<lambda>i. Suc (i + x)) lst ! m\"\n  by simp\n\nlemma sorted_again :\n   \"i + 1 < length (findIndices lst a) \\<Longrightarrow>\n    findIndices lst a ! i < findIndices lst a ! (i+1)\"\napply (induction i arbitrary:lst)\napply auto\napply (case_tac \"findIndices lst a\"; auto)\napply (case_tac \"list\"; auto)\nusing sorted_indices_aux apply force\napply (rule tl_suc_rule)\napply auto\nsubgoal for i lst\nusing split_findIndices [of lst a]\napply simp\napply (cases \"findIndices lst a = []\"; auto)\napply (rule map_suc_rule)\n  apply (metis Suc_lessD Suc_lessE diff_Suc_1 length_map length_tl)\n  apply (metis Suc_lessE diff_Suc_1 length_map length_tl)\n  by (metis Nitpick.size_list_simp(2) Suc_less_eq length_map)\ndone\n\n(*\nlemma nth_split_findIndices :\n   \"length (findIndices lst a) > n \\<Longrightarrow>\n    drop (Suc n) (findIndices lst a) =\n    map (%i. i + (findIndices lst a!n) + 1)\n    (findIndices (drop ((findIndices lst a!n)+1) lst) a)\"\napply (induction n arbitrary:lst)\napply auto\nsubgoal for lst\nusing split_findIndices [of lst a]\napply auto\nby (simp add: drop_Suc hd_conv_nth)\napply (case_tac lst)\napply auto\n\n*)\n\nlemma weird_mono_aux :\n   \"(\\<forall>n. Suc n < limit \\<longrightarrow> f n < f (Suc n)) \\<Longrightarrow> k+m < limit \\<Longrightarrow> (f k::nat) \\<le> f (k+m)\"\nby (induction m; auto)\n\nlemma weird_mono :\n   \"(\\<forall>n. Suc n < limit \\<longrightarrow> f n < f (Suc n)) \\<Longrightarrow>\n   k < limit \\<Longrightarrow> m < limit \\<Longrightarrow> m \\<le> k \\<Longrightarrow> (f m::nat) \\<le> f k\"\nusing weird_mono_aux [of limit f]\n  by (metis le_add_diff_inverse)\n\n\nlemma sorted_indices : \"sorted (findIndices lst a)\"\napply (rule sorted_nth_monoI)\napply (rule weird_mono [of \"length (findIndices lst a)\"\n  \"%i. findIndices lst a ! i\"])\napply auto\nusing sorted_again by force\n\n(* do splitting based on indexes *)\nfun indexSplit :: \"nat list \\<Rightarrow> 'a list \\<Rightarrow> 'a list list\" where\n\"indexSplit (i1#ilst) lst =\n   take (Suc i1) lst # indexSplit (map (%x. x-i1-1) ilst) (drop (Suc i1) lst)\"\n| \"indexSplit [] lst = [lst]\"\n\nvalue \"findIndices [a,a] a\"\n\nvalue \"((\\<lambda>x. x - Suc 0) \\<circ> Suc) 0\"\n\nlemma funext : \"(\\<forall>x. f x = g x) \\<Longrightarrow> f = g\"\nby auto\n\nlemma inc_dec : \"((\\<lambda>x. x - Suc 0) \\<circ> Suc) = id\"\nby (rule funext; auto)\n\nlemma duh : \"map ((\\<lambda>x. x - Suc 0) \\<circ> Suc) lst = lst\"\nby (simp add:inc_dec)\n\nlemma empty_split :\n   \"set (indexSplit ilst []) = {[]}\"\nby (induction ilst \"[]\" rule:indexSplit.induct; auto)\n\nlemma empty_length : \"set lst = {[]} \\<Longrightarrow> concat lst = []\"\n  by (simp add: empty_split)\n\nlemma empty_split2 : \"concat (indexSplit ilst []) = []\"\n  by (simp add: empty_split)\n\nlemma split_combine_step :\n   \"concat (indexSplit (map Suc ilst) (aa # lst)) =\n    aa # concat (indexSplit ilst lst)\"\napply (induction ilst lst rule:indexSplit.induct)\napply auto\n  by (metis comp_apply diff_Suc_Suc)\n\nlemma split_and_combine :\n   \"concat (indexSplit (findIndices lst a) lst) = lst\"\nby (induction lst; auto simp add:duh split_combine_step)\n\nlemma call_end_ends :\n   \"call_end lst s \\<Longrightarrow> s = last lst\"\napply (auto simp add:call_end_def first_one_smaller_def first_def)\n  by (metis One_nat_def Suc_inject last_conv_nth less_numeral_extra(2) list.size(3))\n\ndefinition split :: \"'a list \\<Rightarrow> 'a \\<Rightarrow> 'a list list\" where\n\"split lst a = indexSplit (findIndices lst a) lst\"\n\n(* split into a constant sequence *)\nlemma split_one : \"hd (split (a#lst) a) = [a]\"\nby (auto simp add:split_def)\n\ndefinition first_elem :: \"'a \\<Rightarrow> nat \\<Rightarrow> 'a list \\<Rightarrow> bool\" where\n\"first_elem el k lst = first (%x. x = el) k lst\"\n\nlemma feq_aux : \"x > 0 \\<Longrightarrow> (\\<lambda>b. Suc b = x) = (\\<lambda>b. b = x - Suc 0)\"\nby (rule funext; auto)\n\nlemma one_smaller_elem :\n  \"length lst > 0 \\<Longrightarrow>\n   hd lst > 0 \\<Longrightarrow>\n   first_one_smaller k lst = first_elem (hd lst - 1) k lst\"\nby (simp add:first_one_smaller_def first_elem_def feq_aux)\n\nlemma find_index :\n   \"i < length lst \\<Longrightarrow> i \\<in> set (findIndices lst (lst!i))\"\napply (induction lst \"lst!i\" arbitrary:i rule:findIndices.induct)\nby (auto simp add: less_Suc_eq_0_disj)\n\nlemma more_mono_aux :\n   \"(\\<forall>n. Suc n < limit \\<longrightarrow> f n < f (Suc n)) \\<Longrightarrow>\n     k+m+1 < limit \\<Longrightarrow> (f k::nat) < f (k+m+1)\"\nby (induction m; auto)\n\nlemma more_mono :\n   \"(\\<forall>n. Suc n < limit \\<longrightarrow> f n < f (Suc n)) \\<Longrightarrow>\n   k < limit \\<Longrightarrow> m < limit \\<Longrightarrow> m < k \\<Longrightarrow> (f m::nat) < f k\"\nusing more_mono_aux [of limit f]\n  by (metis Suc_eq_plus1 less_imp_Suc_add)\n\nlemma use_sorting_aux :\n   \"length (findIndices lst el) > m \\<Longrightarrow>\n    m > n \\<Longrightarrow>\n    findIndices lst el!n < findIndices lst el!m\"\napply (rule more_mono [of \"length (findIndices lst el)\"\n   \"%i. findIndices lst el!i\"]; auto)\nusing sorted_again apply force\ndone\n\nlemma use_sorting :\n   \"findIndices lst el = a # list \\<Longrightarrow>\n    x \\<in> set list \\<Longrightarrow>\n    a < x\"\nusing use_sorting_aux [of _ lst el]\n  by (smt in_set_conv_nth length_Cons lessI less_trans_Suc list.sel(3) nth_Cons_0 nth_tl zero_less_Suc)\n\nlemma find_elem :\n \"first_elem el k lst \\<Longrightarrow>\n  hd (findIndices lst el) = k\"\napply (auto simp:first_elem_def first_def)\napply (cases \"findIndices lst (lst ! k)\")\n  using find_index apply fastforce\napply auto\napply (case_tac \"\\<forall>x \\<in> set list. x > a\")\ndefer\nusing use_sorting apply force\n  by (metis find_index get_index list.set_intros(1) set_ConsD)\n\nlemma split_first :\n   \"hd (indexSplit (i#ilst) lst) = take (Suc i) lst\"\nby auto\n\nlemma get_to_end :\n  \"hd lst = Suc (last lst) \\<Longrightarrow>\n   length lst > 0 \\<Longrightarrow>\n   first_one_smaller k lst \\<Longrightarrow>\n   hd (indexSplit (findIndices lst (last lst)) lst) =\n   take (Suc k) lst\"\napply (cases \"\\<not>first_elem (last lst) k lst\")\nusing one_smaller_elem apply fastforce\napply auto\nusing find_elem [of \"last lst\" k lst]\n  by (metis (full_types) find_index first_def first_elem_def hd_Cons_tl length_pos_if_in_set less_numeral_extra(3) list.size(3) split_first)\n\nlemma make_call_end :\n  \"hd lst = Suc (last lst) \\<Longrightarrow>\n   length lst > 0 \\<Longrightarrow>\n   first_one_smaller k lst \\<Longrightarrow>\n   inc_decL lst \\<Longrightarrow>\n   call_end (take (Suc k) lst) (last lst)\"\napply (auto simp add:call_end_def hd_take inc_decL_def\n pathR_take first_one_smaller_def first_def min.absorb2)\nby (metis gr_zeroI hd_conv_nth n_not_Suc_n)\n\nlemma find_first :\n   \"P (lst!i) \\<Longrightarrow> i < length lst \\<Longrightarrow> \\<exists>k \\<le> i. first P k lst\"\napply (induction lst arbitrary:i)\napply (auto simp add:first_def)\napply (case_tac i;auto)\napply (case_tac \"P a\")\nsubgoal for a lst nat\napply (rule exI[where x = 0])\nby auto\napply (case_tac \"\\<forall>j < Suc nat. \\<not> P ((a # lst) ! j)\")\nsubgoal for a lst nat by (rule exI[where x = \"Suc nat\"]; auto)\napply auto\napply (case_tac j; auto)\napply (case_tac \"\\<exists>k\\<le>nata.\n                k < length lst \\<and>\n                P (lst ! k) \\<and> (\\<forall>k2<k. \\<not> P (lst ! k2))\")\napply (thin_tac \"(\\<And>i. P (lst ! i) \\<Longrightarrow>\n             i < length lst \\<Longrightarrow>\n             \\<exists>k\\<le>i.\n                k < length lst \\<and>\n                P (lst ! k) \\<and> (\\<forall>k2<k. \\<not> P (lst ! k2)))\")\napply auto\nsubgoal for a lst nat nata k\napply (rule exI [where x = \"Suc k\"])\napply auto\n  using less_Suc_eq_0_disj by auto\ndone\n\nlemma find_first_one_smaller :\n  \"1 < length lst \\<Longrightarrow>\n   hd lst = Suc (last lst) \\<Longrightarrow>\n   \\<exists>k. first_one_smaller k lst\"\napply (simp add:first_one_smaller_def)\nusing find_first [of \"\\<lambda>b. b = last lst\" lst \"length lst - 1\"]\nby (metis One_nat_def Suc_lessD diff_Suc_less last_conv_nth less_numeral_extra(2) list.size(3))\n\nlemma hd_good :\n  \"inc_decL lst \\<Longrightarrow>\n   hd lst = last lst \\<or> hd lst = Suc (last lst) \\<Longrightarrow>\n   length lst > 0 \\<Longrightarrow>\n   x = hd (split lst (last lst)) \\<Longrightarrow>\n   call_end x (last lst) \\<or> const_seq x (last lst)\"\napply (auto simp:split_def)\n  apply (metis PathRel.split_def const_single list.collapse split_one)\nusing find_first_one_smaller [of lst]\napply auto\napply (cases \"length lst = 1\")\n  apply (simp add: hd_conv_nth last_conv_nth)\napply (cases \"Suc 0 < length lst\")\napply auto\ndefer\n  apply (simp add: hd_conv_nth last_conv_nth)\nsubgoal for k\nusing get_to_end [of lst k]\n  make_call_end [of lst k]\n  by simp\ndone\n\n(* splitting split *)\nlemma split_index_split :\n   \"tl (indexSplit (i#ilst) lst) =\n    indexSplit (map (%j. j - Suc i) ilst)\n                   (drop (Suc i) lst)\"\nby auto\n\nlemma split_index_split2 :\n   \"indexSplit (i#ilst) lst = a#rest \\<Longrightarrow>\n    length a < length lst \\<Longrightarrow>\n    length a = Suc i\"\nby auto\n\nlemma split_index_split3 :\n   \"indexSplit (i#ilst) lst = a#rest \\<Longrightarrow>\n    length a < length lst \\<Longrightarrow>\n    rest = indexSplit (map (%j. j - length a) ilst)\n                   (drop (length a) lst)\"\nusing split_index_split split_index_split2 by fastforce\n\nlemma duh2 :\n \"((\\<lambda>x. x - Suc aa) \\<circ> (\\<lambda>i. Suc (i + aa))) = id\"\nby (rule funext; auto)\n\nlemma aux1 :\n  \"findIndices lst el = aa # list \\<Longrightarrow>\n   map (\\<lambda>x. x - Suc aa) list =\n   findIndices (drop (Suc aa) lst) el\"\nusing split_findIndices [of lst el]\nby (simp add:duh2)\n\nlemma split_split :\n   \"split lst (last lst) = a # rest \\<Longrightarrow>\n    length a < length lst \\<Longrightarrow>\n    rest = split (drop (length a) lst) (last lst)\"\napply (simp add:split_def)\napply (case_tac \"findIndices lst (last lst)\")\napply auto\nsubgoal for aa list\napply (cases \"aa < length lst\")\ndefer\n  apply linarith\napply (cases \"min (length lst) (Suc aa) = Suc aa\")\napply auto\nusing aux1 apply fastforce\ndone done\n\nlemma split_combine : \"concat (split lst el) = lst\"\nunfolding split_def\nusing split_and_combine [of lst el]\nby simp\n\nlemma split_final_aux : \n  \"split lst el = a # rest \\<Longrightarrow>\n   length a = length lst \\<Longrightarrow>\n   concat rest = []\"\nusing split_combine [of lst el]\n  by auto\n\nlemma split_final : \n  \"split lst el = a # rest \\<Longrightarrow>\n   length a = length lst \\<Longrightarrow>\n   set rest \\<subseteq> {[]}\"\nusing split_final_aux [of lst el a rest]\n  by auto\n\n\nlemma split_length : \n  \"split lst el = a # rest \\<Longrightarrow>\n   length a \\<le> length lst\"\nusing split_combine [of lst el]\n  by auto\n\nlemma split_last_aux1 :\n\"split lst (last lst) = a # rest \\<Longrightarrow>\n length a > 0 \\<Longrightarrow>\n length lst > 0\"\n  using split_length by fastforce\n\nlemma find_first_elem :\n  \"0 < length lst \\<Longrightarrow>\n   \\<exists>k. first_elem (last lst) k lst\"\napply (simp add:first_elem_def)\nusing find_first [of \"\\<lambda>b. b = last lst\" lst \"length lst - 1\"]\n  by (metis One_nat_def diff_Suc_less last_conv_nth length_greater_0_conv)\n\n\nlemma split_last :\n\"split lst (last lst) = a # rest \\<Longrightarrow>\n length a > 0 \\<Longrightarrow>\n last a = last lst\"\nusing split_last_aux1 [of lst a rest]\napply simp\nusing find_first_elem [of lst]\napply (auto simp:split_def)\napply (cases \"findIndices lst (last lst)\")\napply simp\nsubgoal for k aa list\nusing find_elem  [of \"last lst\" k lst]\napply auto\n  by (metis List.take_all Suc_lessD get_index last_take list.set_intros(1) not_le)\ndone\n\nlemma split_last_nth :\n\"split lst (last lst) = a # rest \\<Longrightarrow>\n length a > 0 \\<Longrightarrow>\n lst!(length a - 1) = last lst\"\nusing split_last [of lst a rest]\n  split_combine [of lst \"last lst\"]\n  by (metis One_nat_def concat.simps(2) diff_Suc_less last_index nth_append)\n\n\nlemma correct_pieces_aux :\n  \"inc_decL lst \\<Longrightarrow>\n   hd lst = last lst \\<or> hd lst = Suc (last lst) \\<Longrightarrow>\n   length lst > 0 \\<Longrightarrow>\n   n < length (split lst (last lst)) \\<Longrightarrow>\n   x = split lst (last lst) ! n \\<Longrightarrow>\n   \\<forall>t \\<in> set lst. t \\<ge> last lst \\<Longrightarrow>\n   call_end x (last lst) \\<or> const_seq x (last lst)\"\napply (induction n arbitrary: x lst)\n  apply (simp add: hd_conv_nth hd_good)\napply (case_tac \"split lst (last lst)\")\napply simp\nsubgoal for n x lst a rest\nusing split_split [of lst a rest]\napply simp\napply (cases \"length a = length lst\")\nusing split_final [of lst \"last lst\" a rest]\napply (cases \"rest!n = []\")\n  apply (simp add: const_seq_def)\n  apply (meson in_set_conv_nth singleton_iff subsetCE)\napply (cases \"length a < length lst\")\ndefer\nusing split_length apply fastforce\napply simp\nproof -\nassume a : \"(\\<And>x lst.\n        inc_decL lst \\<Longrightarrow>\n        hd lst = last lst \\<or> hd lst = Suc (last lst) \\<Longrightarrow>\n        lst \\<noteq> [] \\<Longrightarrow>\n        n < length (split lst (last lst)) \\<Longrightarrow>\n        x = split lst (last lst) ! n \\<Longrightarrow>\n        \\<forall>x\\<in>set lst. last lst \\<le> x \\<Longrightarrow>\n        call_end (split lst (last lst) ! n) (last lst) \\<or>\n        const_seq (split lst (last lst) ! n)\n         (last lst))\"\nassume b : \"inc_decL lst\"\nshow \"(\\<And>x lst.\n        inc_decL lst \\<Longrightarrow>\n        hd lst = last lst \\<or> hd lst = Suc (last lst) \\<Longrightarrow>\n        lst \\<noteq> [] \\<Longrightarrow>\n        n < length (split lst (last lst)) \\<Longrightarrow>\n        x = split lst (last lst) ! n \\<Longrightarrow>\n        \\<forall>x\\<in>set lst. last lst \\<le> x \\<Longrightarrow>\n        call_end (split lst (last lst) ! n) (last lst) \\<or>\n        const_seq (split lst (last lst) ! n)\n         (last lst)) \\<Longrightarrow>\n    inc_decL lst \\<Longrightarrow>\n    hd lst = last lst \\<or> hd lst = Suc (last lst) \\<Longrightarrow>\n    lst \\<noteq> [] \\<Longrightarrow>\n    n < length (split (drop (length a) lst) (last lst)) \\<Longrightarrow>\n    x = split (drop (length a) lst) (last lst) ! n \\<Longrightarrow>\n    \\<forall>x\\<in>set lst. last lst \\<le> x \\<Longrightarrow>\n    split lst (last lst) =\n    a # split (drop (length a) lst) (last lst) \\<Longrightarrow>\n    rest = split (drop (length a) lst) (last lst) \\<Longrightarrow>\n    length a < length lst \\<Longrightarrow>\n    call_end (split (drop (length a) lst) (last lst) ! n)\n     (last lst) \\<or>\n    const_seq (split (drop (length a) lst) (last lst) ! n)\n     (last lst)\"\nusing a [of \"drop (length a) lst\" x]\napply simp\napply (cases \"inc_decL (drop (length a) lst)\")\ndefer\napply (simp add:inc_decL_def pathR_drop)\napply simp\napply (cases \"\\<forall>x\\<in>set (drop (length a) lst). last lst \\<le> x\")\ndefer\n  apply (meson in_set_dropD)\napply simp\napply (cases \"length a\")\n  apply (metis drop_0)\nusing split_last_nth [of lst a rest]\nproof -\n  fix nat :: nat\n  assume a1: \"inc_decL lst\"\n  assume a2: \"lst \\<noteq> []\"\n  assume a3: \"x = split (drop (length a) lst) (last lst) ! n\"\n  assume a4: \"split lst (last lst) = a # split (drop (length a) lst) (last lst)\"\n  assume a5: \"rest = split (drop (length a) lst) (last lst)\"\n  assume a6: \"length a < length lst\"\n  assume a7: \"hd (drop (length a) lst) = last lst \\<or> hd (drop (length a) lst) = Suc (last lst) \\<Longrightarrow> call_end (split (drop (length a) lst) (last lst) ! n) (last lst) \\<or> const_seq (split (drop (length a) lst) (last lst) ! n) (last lst)\"\n  assume a8: \"\\<forall>x\\<in>set (drop (length a) lst). last lst \\<le> x\"\n  assume a9: \"length a = Suc nat\"\n  have \"\\<forall>n. \\<not> Suc n \\<le> n\"\n  by (metis le_imp_less_Suc nat_less_le)\n  moreover\n  { assume \"last lst = lst ! Suc nat\"\n    then have \"const_seq x (last lst) \\<or> call_end x (last lst)\"\n      using a9 a7 a6 a3 by (metis (full_types) hd_drop_conv_nth) }\n    ultimately show ?thesis\n      using a9 a8 a7 a6 a5 a4 a2 a1 by (metis (no_types) Suc_eq_plus1 Suc_less_SucD Suc_pred' \\<open>\\<lbrakk>split lst (last lst) = a # rest; 0 < length a\\<rbrakk> \\<Longrightarrow> lst ! (length a - 1) = last lst\\<close> drop_eq_Nil hd_drop_conv_nth length_pos_if_in_set list.set_sel(1) nat_less_le not_le test zero_less_Suc)\nqed\nqed\ndone\n\nlemma correct_pieces :\n  \"inc_decL lst \\<Longrightarrow>\n   hd lst = last lst \\<Longrightarrow>\n   length lst > 0 \\<Longrightarrow>\n   \\<forall>t \\<in> set lst. t \\<ge> last lst \\<Longrightarrow>\n   x \\<in> set (split lst (last lst)) \\<Longrightarrow>\n   call_end x (last lst) \\<or> const_seq x (last lst)\"\nusing correct_pieces_aux [of lst]\n  by (metis in_set_conv_nth)\n\nlemma first_one_smaller_prev :\n\"inc_decL lst \\<Longrightarrow>\n length lst > 0 \\<Longrightarrow>\n k > 0 \\<Longrightarrow>\n first_one_smaller k lst \\<Longrightarrow>\n lst!(k-1) = lst!0\"\nusing first_smaller1 [of lst k]\napply simp\napply (auto simp add: first_one_smaller_def\n  first_smaller_def first_def inc_decL_def\n  path_defs inc_dec_def path_def sucR_def)\napply (simp add:hd_conv_nth)\n  by (smt Suc_less_SucD Suc_pred lessI order.strict_trans)\n\n\nlemma ncall_last :\n  \"ncall lst \\<Longrightarrow>\n   (last (clip (length lst - 2) 1 lst)) = lst!1\"\nusing ncall_stack_length [of lst]\napply (auto simp add:ncall_def clip_def last_conv_nth\n  sucR_def)\napply (cases\n\"min (length lst - Suc 0) (Suc (length lst - 3)) = length lst -2\")\napply auto\nusing first_one_smaller_prev [of \"tl lst\" \"length lst-2\"]\napply auto\napply (cases \"inc_decL (tl lst)\")\ndefer\napply (simp add:inc_decL_def path_defs path_def)\n  apply (metis (no_types, lifting) One_nat_def Suc_diff_Suc Suc_lessD Suc_mono length_tl nth_tl numeral_2_eq_2)\napply auto\n  by (metis (no_types, lifting) One_nat_def Suc_diff_Suc diff_Suc_eq_diff_pred diff_less_Suc length_tl less_diff_conv less_numeral_extra(2) neq0_conv nth_tl numeral_2_eq_2 numeral_3_eq_3 one_add_one)\n\n\n(*\nusing first_smaller1 [of  \"tl lst\" \"length lst - 2\"]\napply (auto simp add:first_smaller_def first_def)\napply (cases \"inc_decL (tl lst)\")\ndefer\napply (simp add:inc_decL_def path_defs path_def)\n  apply (metis (no_types, lifting) One_nat_def Suc_diff_Suc Suc_lessD Suc_mono length_tl nth_tl numeral_2_eq_2)\napply auto\n*)\n\nlemma ncall_inc_dec :\n   \"ncall lst \\<Longrightarrow> inc_decL (clip a b lst)\"\nby (simp add: ncall_def inc_decL_def pathR_clip)\n\nlemma ncall_sub_length :\n\"ncall lst \\<Longrightarrow> length (clip (length lst - 2) 1 lst) > 0\"\nby (simp add: ncall_def clip_def)\n\nlemma ncall_second :\n\"ncall lst \\<Longrightarrow> hd (clip (length lst - 2) 1 lst) = lst ! 1\"\nby (auto simp add: ncall_def clip_def sucR_def\n hd_drop_conv_nth hd_take)\n\nlemma inc_dec_tl : \"inc_decL lst \\<Longrightarrow> inc_decL (tl lst)\"\nby (auto simp add: inc_decL_def pathR_tl)\n\nlemma first_smaller_before :\n \"first_smaller k lst \\<Longrightarrow>\n  x \\<in> set (take k lst) \\<Longrightarrow>\n  x \\<ge> lst!0\"\napply (auto simp add:first_smaller_def first_def)\n  by (metis gr_implies_not_zero hd_conv_nth in_set_conv_nth length_take less_imp_le_nat list.size(3) min.absorb2 not_le nth_take)\n\nlemma ncall_inside_big :\n\"ncall lst \\<Longrightarrow>\n x\\<in>set (clip (length lst - 2) 1 lst) \\<Longrightarrow>\n lst ! 1 \\<le> x\"\napply (auto simp add:ncall_def sucR_def)\nusing first_smaller1 [of \"tl lst\" \"length lst - 2\"]\napply (auto simp add:inc_dec_tl)\nusing first_smaller_before [of \"length lst -2\" \"tl lst\"\n  x]\napply auto\napply (simp add:clip_def)\napply (cases \"take (Suc (length lst - 3))\n               (drop (Suc 0) lst) = take (length lst - 2) (tl lst)\")\ndefer\n  apply (simp add: Suc_diff_Suc drop_Suc numeral_2_eq_2 numeral_3_eq_3)\napply simp\n  by (simp add: nth_tl)\n\ndefinition seqSplit :: \"(nat*nat) list \\<Rightarrow> 'a list \\<Rightarrow> 'a list list\" where\n\"seqSplit ilst lst =\n   map (%ival. take (snd ival) (drop (fst ival) lst)) ilst\"\n\n\nlemma decompose_ncall :\n  \"ncall lst \\<Longrightarrow>\n   \\<exists>pieces. concat pieces = clip (length lst-2) 1 lst \\<and>\n   (\\<forall>x \\<in> set pieces. call_end x (lst!1) \\<or> const_seq x (lst!1))\"\napply (rule exI[where x =\n   \"split (clip (length lst-2) 1 lst) (lst!1)\"])\napply auto\nusing split_combine apply fastforce\nsubgoal for x\nusing ncall_last [of lst]\napply simp\nusing correct_pieces [of \"clip (length lst-2) 1 lst\" x]\napply (simp add:ncall_inc_dec)\napply (cases \"clip (length lst - 2) (Suc 0) lst = []\")\nusing ncall_sub_length apply fastforce\napply simp\nusing ncall_second [of lst]\napply simp\nusing ncall_inside_big apply force\ndone\ndone\n\ndefinition call_e :: \"'a list list \\<Rightarrow> 'a list \\<Rightarrow> bool\" where\n\"call_e lst s = (\n   length lst > 1 \\<and>\n   (hd lst,s) \\<in> tlR  \\<and>\n   push_popL lst \\<and>\n   first_return (length lst-1) lst)\"\n\nlemma call_end1 :\n   \"call_e lst s \\<Longrightarrow> call_end (map length lst) (length s)\"\napply (auto simp add:call_e_def call_end_def tlR_def sucR_def\n   hd_map)\n  apply (metis Suc_lessE length_Suc_conv list.sel(1) list.simps(9))\n\n  using push_popL_inc_decL apply auto[1]\nusing first_return_smaller [of \"lst\" \"length lst - 1\"]\nby (simp add:push_popL_def pathR_tl map_tl)\n\nlemma first_smaller_return2 :\n  \"push_popL lst \\<Longrightarrow>\n   first_one_smaller k (map length lst) \\<Longrightarrow>\n   first_return k lst\"\n  by (simp add: first_smaller1 first_smaller_return push_popL_inc_decL)\n\nlemma first_return_nil :\n  \"length lst > 0 \\<Longrightarrow>\n   first_return k lst \\<Longrightarrow>\n   length (hd lst) > 0\"\nby (auto simp add: first_return_def first_def tlR_def)\n\nlemma first_return_get :\n  \"hd lst = a # list \\<Longrightarrow>\n   length lst > 0 \\<Longrightarrow>\n   first_return (length lst - 1) lst \\<Longrightarrow>\n   list = last lst\"\napply (auto simp add: first_return_def first_def tlR_def)\n  by (simp add: last_conv_nth)\n\n\nlemma call_end2 :\n   \"call_end (map length lst) (length s) \\<Longrightarrow>\n    push_popL lst \\<Longrightarrow>\n    last lst = s \\<Longrightarrow>\n    call_e lst s\"\napply (auto simp add:call_end_def call_e_def tlR_def sucR_def)\napply (cases \"hd lst\"; auto)\n  apply (metis Suc_lessD length_greater_0_conv list.map_sel(1) list.size(3) nat.distinct(1))\nusing first_smaller_return2 [of lst \"length lst - 1\"]\napply simp\nusing first_return_get apply force\nusing first_smaller_return2 [of lst \"length lst - 1\"]\napply force\ndone\n\nlemma split_and_combine2 :\n   \"concat (indexSplit ilst lst) = lst\"\nby (induction ilst lst rule:indexSplit.induct; auto)\n\nlemma decompose_ncall_index :\n  \"ncall lst \\<Longrightarrow>\n   \\<exists>ilst. (\\<forall>x \\<in> set (indexSplit ilst (clip (length lst-2) 1 lst)).\n    call_end x (lst!1) \\<or> const_seq x (lst!1))\"\napply (rule exI[where x =\n   \"findIndices (clip (length lst-2) 1 lst) (lst!1)\"])\napply auto\nsubgoal for x\nusing ncall_last [of lst]\napply simp\nusing correct_pieces [of \"clip (length lst-2) 1 lst\" x]\napply (simp add:ncall_inc_dec)\napply (cases \"clip (length lst - 2) (Suc 0) lst = []\")\nusing ncall_sub_length apply fastforce\napply simp\nusing ncall_second [of lst]\napply (simp add:split_def)\nusing ncall_inside_big apply force\ndone\ndone\n\nlemma index_split_map :\n\"x \\<in> set (indexSplit ilst lst) \\<Longrightarrow>\n map f x \\<in> set (indexSplit ilst (map f lst))\"\nby (induction ilst lst arbitrary:x rule:indexSplit.induct;\n    auto simp add: take_map drop_map)\n\nlemma const_seq_convert :\n  \"push_popL lst \\<Longrightarrow>\n   const_seq (map length lst) n \\<Longrightarrow>\n   \\<exists>t. const_seq lst t\"\napply (cases lst)\napply (auto simp add:const_seq_def)\nsubgoal for a list x\napply (induction list arbitrary: x a lst n)\napply (auto simp add:push_popL_def pathR.simps\n  push_pop_def)\n  apply (metis PathRel.take_all Un_upper2 converseD converse_converse le_refl next_unchanged push_pop_def subset_iff)\n  apply (metis PathRel.take_all Un_upper2 converseD converse_converse le_refl next_unchanged push_pop_def subset_iff)\n  apply (metis (mono_tags, lifting) PathRel.take_all converse.intros le_refl next_unchanged push_pop_def set_mp sup.cobounded2)\n  apply (metis (mono_tags, lifting) PathRel.take_all converse.intros le_refl next_unchanged push_pop_def set_mp sup.cobounded2)\ndone done\n\nlemma index_split_get :\n\"x \\<in> set (indexSplit ilst lst) \\<Longrightarrow>\n \\<exists>a b. x = take a (drop b lst)\"\napply (induction ilst lst arbitrary:x rule:indexSplit.induct)\napply auto\n  apply (metis drop_0)\n  apply metis\n  by (metis List.take_all drop_0 le_add2)\n\nlemma pathR_split :\n   \"pathR r lst \\<Longrightarrow>\n    x \\<in> set (indexSplit ilst lst) \\<Longrightarrow>\n    pathR r x\"\nusing index_split_get pathR_take pathR_drop\n  by blast\n\nlemma call_pathR : \"call lst \\<Longrightarrow> pathR push_pop lst\"\nby (auto simp: call_def push_popL_def)\n\nlemma call_inside_pushpopL : \n  \"call lst \\<Longrightarrow> push_popL (clip (length lst - 2) 1 lst)\"\nby (simp add:call_def push_popL_def pathR_clip)\n\nlemma foo_aux2 :\n\"j < length lst - 1 \\<Longrightarrow>\n sti \\<in> set (take j (drop (Suc 0) lst)) \\<Longrightarrow>\n sti \\<in> set (take (length lst - 2) (drop (Suc 0) lst))\"\nusing List.set_take_subset_set_take [of j \"length lst-2\"\n  \"drop (Suc 0) lst\"]\napply auto\napply (cases \"length lst\")\napply auto\n  by fastforce\n\nlemma foo_aux :\n\"j < length lst - 1 \\<Longrightarrow>\n sti \\<in> set (take j (drop (Suc 0) lst)) \\<Longrightarrow>\n length sti\n    \\<in> length `\n       set\n        (take (length lst - 2) (drop (Suc 0) lst))\"\nusing foo_aux2 [of j lst sti]\n  by blast\n\nlemma call_inside_big_idx :\n\"call lst \\<Longrightarrow>\n j \\<ge> 1 \\<Longrightarrow> j < length lst - 1 \\<Longrightarrow>\n takeLast (length (lst!1)) (lst!j) = lst ! 1\"\nusing stack_unchanged [of \"clip j 1 lst\"\n   \"length (lst!1)\"]\napply simp\napply (cases \"push_popL (clip j (Suc 0) lst)\")\ndefer\napply (simp add:call_def push_popL_def pathR_clip)\napply (cases \"clip j (Suc 0) lst = []\")\napply (simp add:clip_def call_def)\napply (simp add:last_clip hd_clip)\napply (subgoal_tac \"\\<forall>sti\\<in>set (clip j (Suc 0) lst).\n        length (lst ! Suc 0) \\<le> length sti\")\napply simp\napply auto\n  apply (metis (mono_tags, lifting) Nitpick.size_list_simp(2) One_nat_def PathRel.take_all hd_clip last_clip le_less length_tl less_SucI nat_diff_split zero_less_one)\n\nsubgoal for sti\nusing ncall_inside_big [of \"map length lst\" \"length sti\"]\napply (simp add:call_ncall)\napply (cases \"length sti\n     \\<in> set (clip (length (map length lst) - 2) (Suc 0)\n              (map length lst))\")\napply auto\n  apply (simp add: clip_def drop_map take_map)\napply (cases \"Suc (length lst - 3) = length lst - 2\")\ndefer\napply (simp)\napply simp\nusing foo_aux apply fastforce\ndone\ndone\n\nlemma ex_idx : \"x \\<in> set lst \\<Longrightarrow> \\<exists>i<length lst. x = lst!i\"\n  by (metis in_set_conv_nth)\n\nlemma call_inside_big :\n\"call lst \\<Longrightarrow>\n x\\<in>set (clip (length lst - 2) 1 lst) \\<Longrightarrow>\n takeLast (length (lst!1)) x = lst ! 1\"\nusing ex_idx [of x \"clip (length lst - 2) 1 lst\"]\napply auto\nsubgoal for j\nusing call_inside_big_idx [of lst \"Suc j\"]\napply (simp add:clip_def)\napply (subgoal_tac \"Suc j < length lst - Suc 0\")\napply simp\n  by (metis One_nat_def Suc_diff_Suc Suc_lessI call_def diff_Suc_1 diff_diff_left nat_neq_iff numeral_2_eq_2 numeral_3_eq_3 one_add_one)\ndone\n\nlemma const_seq_empty : \"const_seq [] x\"\nby (simp add:const_seq_def)\n\nlemma const_seq_eq : \"const_seq (a # list) b \\<Longrightarrow> b = a\"\nby (simp add:const_seq_def)\n\nlemma in_index_split :\n\"x \\<in> set (indexSplit ilst lst) \\<Longrightarrow>\n y \\<in> set x \\<Longrightarrow>\n y \\<in> set lst\"\n  by (metis in_set_dropD in_set_takeD index_split_get)\n\nlemma call_end_last : \"call_end lst x \\<Longrightarrow> last lst = x\"\napply (auto simp add:call_end_def)\n  by (metis (mono_tags, lifting) One_nat_def Suc_lessD diff_Suc_1 first_def first_one_smaller_def last_index)\n\n(* decompose call to sub calls ...\n   cycle could also be split into subcycles *)\nlemma decompose_call :\n  \"call lst \\<Longrightarrow>\n   \\<exists>ilst. (\\<forall>x \\<in> set (indexSplit ilst (clip (length lst-2) 1 lst)).\n    call_e x (lst!1) \\<or> const_seq x (lst!1))\"\nusing decompose_ncall_index [of \"map length lst\"]\n      call_ncall [of lst]\napply auto\nsubgoal for ilst\napply (rule exI[where x=ilst])\napply clarsimp\n(* because internally the stack is high,\n   it should not change *)\napply (case_tac \"const_seq (map length x) (map length lst ! Suc 0) \\<or>\n    call_end (map length x) (map length lst ! Suc 0)\")\ndefer\nsubgoal for x\nusing index_split_map [of x ilst \"clip (length lst - 2) (Suc 0)\n                 lst\" length]\napply (simp add:clip_def take_map drop_map)\napply force\ndone\nsubgoal for x\nusing pathR_split [of \"push_pop\"\n   \"clip (length lst - 2) (Suc 0) lst\" x ilst]\n  pathR_clip [of \"push_pop\" lst \"length lst-2\" \"Suc 0\"]\n  call_pathR [of lst]\napply simp\n\napply auto\nsubgoal (* constant *)\nusing const_seq_convert [of x \"map length lst ! Suc 0\"]\napply (auto simp add:push_popL_def)\napply (cases x)\nusing const_seq_empty apply force\nsubgoal for xa a list\napply (simp add:map_nth)\nusing const_seq_eq [of a list xa]\napply simp\napply (subgoal_tac \"a \\<in> set (clip (length lst - 2) (Suc 0) lst)\")\ndefer\nusing in_index_split apply fastforce\napply (subgoal_tac \"lst ! Suc 0 = a\")\napply auto\nusing call_inside_big [of lst a]\n  by (metis One_nat_def PathRel.take_all Suc_lessD call_def const_seq_eq nth_map numeral_2_eq_2)\ndone\napply (rule call_end2)\n  apply (simp add: call_def)\n  using push_popL_def apply blast\nusing call_end_last [of \"map length x\" \"length (lst ! Suc 0)\"]\nusing call_inside_big [of lst \"last x\"]\napply simp\n  by (smt One_nat_def PathRel.take_all Suc_lessD call_def call_end_def diff_less in_index_split last_index length_map nth_map nth_mem numeral_2_eq_2 zero_less_one)\ndone done\n\ndefinition ncall_pieces :: \"nat list \\<Rightarrow> nat list list\" where\n\"ncall_pieces lst =\n  (let ilst =  findIndices (clip (length lst-2) 1 lst) (lst!1) in\n   indexSplit ilst (clip (length lst-2) 1 lst))\"\n\nlemma decompose_ncall_pieces :\n  \"ncall lst \\<Longrightarrow>\n   x \\<in> set (ncall_pieces lst) \\<Longrightarrow>\n   call_end x (lst!1) \\<or> const_seq x (lst!1)\"\napply (simp add:ncall_pieces_def)\napply auto\nusing ncall_last [of lst]\napply simp\nusing correct_pieces [of \"clip (length lst-2) 1 lst\" x]\napply (simp add:ncall_inc_dec)\napply (cases \"clip (length lst - 2) (Suc 0) lst = []\")\nusing ncall_sub_length apply fastforce\napply simp\nusing ncall_second [of lst]\napply (simp add:split_def)\nusing ncall_inside_big apply force\ndone\n\ndefinition call_pieces :: \"'a list list \\<Rightarrow> 'a list list list\" where\n\"call_pieces lst =\n  (let ilst = findIndices (clip (length lst-2) 1 (map length lst)) (length (lst!1)) in\n   indexSplit ilst (clip (length lst-2) 1 lst))\"\n\n\nlemma lengths_aux :\n\"length lst > 1 \\<Longrightarrow>\n x \\<in> set (call_pieces lst) \\<Longrightarrow>\n map length x \\<in> set (ncall_pieces (map length lst))\"\napply (subgoal_tac \"map length lst ! 1 = length (lst!1)\")\napply (auto simp add: clip_def drop_map index_split_map take_map\n  call_pieces_def ncall_pieces_def)\ndone\n\n(*\nlemma lengths_aux :\n\"length lst > 1 \\<Longrightarrow>\n x \\<in> set (indexSplit\n               (findIndices\n                 (clip (length lst - 2)\n                   (Suc 0) (map length lst))\n                 (length (lst ! Suc 0)))\n               (clip (length lst - 2) (Suc 0)\n                 lst)) \\<Longrightarrow>\n    map length x\n     \\<in> set (indexSplit\n              (findIndices\n                (clip (length lst - 2)\n                  (Suc 0) (map length lst))\n                (map length lst ! Suc 0))\n              (clip (length lst - 2) (Suc 0)\n                (map length lst)))\"\napply (subgoal_tac \"map length lst ! 1 = length (lst!1)\")\napply (auto simp add: clip_def drop_map index_split_map take_map)\ndone\n*)\n\nlemma decompose_call_pieces :\n  \"call lst \\<Longrightarrow>\n   x \\<in> set (call_pieces lst) \\<Longrightarrow>\n   call_e x (lst!1) \\<or> const_seq x (lst!1)\"\nusing decompose_ncall_pieces [of \"map length lst\" \"map length x\"]\n      call_ncall [of lst]\napply (case_tac \"const_seq (map length x) (map length lst ! Suc 0) \\<or>\n    call_end (map length x) (map length lst ! Suc 0)\")\napply (simp add:call_pieces_def)\nusing pathR_split [of \"push_pop\"\n   \"clip (length lst - 2) (Suc 0) lst\" x \"findIndices\n                 (clip (length lst - 2)\n                   (Suc 0) (map length lst))\n                 (length (lst ! Suc 0))\"]\n  pathR_clip [of \"push_pop\" lst \"length lst-2\" \"Suc 0\"]\n  call_pathR [of lst]\napply simp\n\napply auto\nsubgoal (* constant *)\nusing const_seq_convert [of x \"map length lst ! Suc 0\"]\napply (auto simp add:push_popL_def)\napply (cases x)\nusing const_seq_empty apply force\nsubgoal for xa a list\napply (simp add:map_nth)\nusing const_seq_eq [of a list xa]\napply simp\napply (subgoal_tac \"a \\<in> set (clip (length lst - 2) (Suc 0) lst)\")\ndefer\nusing in_index_split apply fastforce\napply (subgoal_tac \"lst ! Suc 0 = a\")\napply auto\nusing call_inside_big [of lst a]\n  by (metis One_nat_def PathRel.take_all Suc_lessD call_def const_seq_eq nth_map numeral_2_eq_2)\ndone\napply (rule call_end2)\n  apply (simp add: call_def)\n  using push_popL_def apply blast\nusing call_end_last [of \"map length x\" \"length (lst ! Suc 0)\"]\nusing call_inside_big [of lst \"last x\"]\napply simp\n  apply (metis PathRel.take_all Suc_lessD call_def call_end_def in_index_split last_in_set last_map length_map less_numeral_extra(2) list.size(3) nth_map numeral_2_eq_2)\nusing lengths_aux [of lst x]\napply simp\n  by (simp add: call_def less_imp_le_nat)\n\n\nlemma sucR_add : \"(a,b) \\<in> sucR \\<Longrightarrow> (a+m,b+m) \\<in> sucR\"\nby (simp add:sucR_def)\n\nlemma inc_dec_add : \"(a,b) \\<in> inc_dec \\<Longrightarrow> (a+m,b+m) \\<in> inc_dec\"\nby (simp add:inc_dec_def sucR_def)\n\nlemma pathR_map :\n  \"(\\<forall>a b. (a,b) \\<in> r \\<longrightarrow> (f a, f b) \\<in> r) \\<Longrightarrow>\n    pathR r lst \\<Longrightarrow> pathR r (map f lst)\"\nby (simp add:path_defs path_def)\n\nlemma tl_map : \"tl (map f lst) = map f (tl lst)\"\n  by (simp add: map_tl)\n\nlemma ncall_plus : \"ncall lst \\<Longrightarrow> ncall (map (%a. a +m) lst)\"\napply (auto simp: ncall_def)\napply (simp add:sucR_def)\n  using less_iff_Suc_add apply auto[1]\napply (simp add:inc_decL_def)\napply (rule pathR_map)\napply (auto simp add:inc_dec_add)\napply (auto simp add:first_one_smaller_def first_def)\napply (simp add:tl_map hd_map)\n  apply (metis add_Suc length_tl less_diff_conv less_numeral_extra(2) list.map_sel(1) list.size(3) one_add_one)\napply (simp add:tl_map hd_map)\napply (subgoal_tac \"hd (map (\\<lambda>a. a + m) (tl lst)) = hd (tl lst) + m\")\napply simp\n  by (metis length_tl less_diff_conv less_numeral_extra(2) list.map_sel(1) list.size(3) one_add_one)\n\nend\n", "meta": {"author": "pirapira", "repo": "eth-isabelle", "sha": "d0bb02b3e64a2046a7c9670545d21f10bccd7b27", "save_path": "github-repos/isabelle/pirapira-eth-isabelle", "path": "github-repos/isabelle/pirapira-eth-isabelle/eth-isabelle-d0bb02b3e64a2046a7c9670545d21f10bccd7b27/Hoare/PathRel.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213772699435, "lm_q2_score": 0.7956581000631541, "lm_q1q2_score": 0.7153932067647696}}
{"text": "theory seminarski\n  imports Complex_Main\nbegin\n\nprimrec suma_prvih :: \"nat \\<Rightarrow> nat\" where\n\"suma_prvih 0 = 0\"\n| \"suma_prvih (Suc n) = suma_prvih n + (n+1)\"\n\n\nlemma dorada_prvi_stepen:\n  shows \"(\\<Sum>k\\<leftarrow>[0..<Suc n]. k) = n*(n+1) div 2\"\nproof(induction n)\n  case 0\n  then show ?case \n    by simp\nnext\n  case (Suc n)\n  have \"(\\<Sum>k\\<leftarrow>[0..<Suc (Suc n)]. k) = (\\<Sum>k\\<leftarrow>[0..<Suc n]. k) + Suc n\"\n    by simp\n  also have \"... = n * ( n + 1 ) div 2 + Suc n\"\n    using Suc\n    by simp\n  also have \"... = (n * ( n + 1 ) + 2*(Suc n)) div 2\"\n    by simp\n  also have \"... = (n + 1) * (n+2) div 2\"\n    by simp\n  finally show ?case by simp\nqed\n\n\nlemma prvi_stepen:\n  shows \"suma_prvih n = n*(n+1) div 2\"\nproof (induction n)\ncase 0\n  then show ?case\n    by auto\nnext\n  case (Suc n)\n  then show ?case\n  proof-\n    have \"suma_prvih (Suc n) = suma_prvih n + (n+1)\"\n      by simp\n    also have \"... = n*(n+1) div 2 + (n+1)\"\n      using Suc\n      by auto\n    also have \"... = (n+1)*(n+2) div 2\"\n      by auto\n    finally show ?thesis by auto\n  qed\nqed\n\n\nprimrec suma_prvih_2 :: \"nat \\<Rightarrow> nat\" where\n\"suma_prvih_2 0 = 0\"\n| \"suma_prvih_2 (Suc n) = suma_prvih_2 n + (n+1)^2\"\n\n\nlemma dorada_drugi_stepen:\n  shows \"(\\<Sum>k\\<leftarrow>[0..<Suc n]. k^2) = n*(n+1)*(2*n+1) div 6\"\nproof(induction n)\n  case 0\n  then show ?case \n    by simp\nnext\n  case (Suc n)\n  have \"(\\<Sum>k\\<leftarrow>[0..<Suc (Suc n)]. k^2) = (\\<Sum>k\\<leftarrow>[0..<Suc n]. k^2) + (Suc n)^2\"\n    by (auto simp add: power2_eq_square)\n  also have \"... = n * ( n + 1 ) * (2*n + 1) div 6 + (Suc n)^2\"\n    using Suc\n    by simp\n  also have \"... = (n + 1) * (n + 2) * (2 * n + 3) div 6\"\n      by (auto simp add: power2_eq_square algebra_simps)\n  also have \"... = (n + 1) * (n + 2)*(2 * (n + 1) + 1) div 6\"\n    by (auto simp add: algebra_simps)\n  finally show ?case by simp\nqed\n\nlemma drugi_stepen:\n  shows \"suma_prvih_2 n = n*(n+1)*(2*n+1) div 6\"\nproof (induction n)\ncase 0\n  then show ?case\n    by auto\nnext\n  case (Suc n)\n  then show ?case\n  proof-\n    have \"suma_prvih_2 (Suc n) = suma_prvih_2 n + (n+1)^2\"\n      by simp\n    also have \"... = n*(n+1)*(2*n+1) div 6 + (n+1)^2\"\n      using Suc\n      by auto\n    also have \"... = (n+1)*(n+2)*(2*n+3) div 6\"\n      by (auto simp add: power2_eq_square algebra_simps)\n    also have \"... = (n+1)*(n+2)*(2*(n+1)+1) div 6\"\n      by (auto simp add: algebra_simps)\n    finally show ?thesis by auto\n  qed\nqed\n\n\nprimrec suma_prvih_3 :: \"nat \\<Rightarrow> nat\" where\n\"suma_prvih_3 0 = 0\"\n| \"suma_prvih_3 (Suc n) = suma_prvih_3 n + (n+1)^3\"\n\n\nlemma dorada_treci_stepen:\n  shows \"(\\<Sum>k\\<leftarrow>[0..< Suc n]. k^3) = n^2 * (n + 1)^2 div 4\"\nproof(induction n)\ncase 0\n  then show ?case by simp\nnext\n  case (Suc n)\n  have \"(\\<Sum>k\\<leftarrow>[0..< Suc (Suc n)]. k^3) = (\\<Sum>k\\<leftarrow>[0..< Suc n]. k^3) + (Suc n)^3\"\n    by simp\n  also have \"... = n^2 * (n + 1)^2 div 4 + (Suc n)^3\"\n    using Suc\n    by simp\n  also have \"... = n^2 * (n + 1)^2 div 4 + 4 * (n + 1)^3 div 4\"\n    by auto\n  also have \"... = (n + 1)^2 * (n^2 + 4 * (n + 1)) div 4\"\n    by (auto simp add: algebra_simps power3_eq_cube power2_eq_square)\n  also have \"... = (n + 1)^2 * (n + 2)^2 div 4\"\n    by (auto simp add: algebra_simps power2_eq_square)\n  finally show ?case\n    by simp\nqed\n\nlemma treci_stepen:\n  shows \"suma_prvih_3 n = n^2*(n+1)^2 div 4\"\nproof (induction n)\ncase 0\n  then show ?case\n    by auto\nnext\n  case (Suc n)\n  then show ?case\n  proof-\n    have \"suma_prvih_3 (Suc n) = suma_prvih_3 n + (n+1)^3\"\n      by simp\n    also have \"... = n^2*(n+1)^2 div 4 + (n+1)^3\"\n      using Suc\n      by auto\n    also have \"... = n^2*(n+1)^2 div 4 + 4*(n+1)^3 div 4\"\n      by auto\n    also have \"... = (n+1)^2 *(n^2 + 4*(n+1)) div 4\"\n      by (auto simp add: algebra_simps power3_eq_cube power2_eq_square)\n    also have \"... = (n+1)^2 *(n+2)^2 div 4\"\n      by (auto simp add: algebra_simps power2_eq_square)\n    finally show ?thesis by auto\n  qed\nqed\n\n\nlemma *: \"(n+1)^3 = 2*(n+1)*(suma_prvih n) + (n+1)^2\" \nproof-\n  have \"2*(n+1)*(suma_prvih n) + (n+1)^2 = 2*(n+1)*(n*(n+1) div 2) + (n+1)^2\"\n    using prvi_stepen\n    by auto\n  also have \"... = (n+1)*n*(n+1) + (n+1)^2\"\n    by auto\n  also have \"... = n*(n+1)^2 + (n+1)^2\"\n    by (auto simp add: algebra_simps power2_eq_square)\n  also have \"... = (n+1)^2*(n+1)\"\n    by auto\n  also have \"... = (n+1)^3\"\n    by (auto simp add: algebra_simps power2_eq_square power3_eq_cube)\n  finally show ?thesis by auto\nqed\n\nlemma\n  shows \"(suma_prvih n)^2 = suma_prvih_3 n\"\nproof (induction n)\ncase 0\n  then show ?case\n    by auto\nnext\n  case (Suc n)\n  then show ?case\n  proof-\n    have \"(suma_prvih (Suc n))^2 = (suma_prvih n + (n+1))^2\"\n      by simp\n    also have \"... = (suma_prvih n)^2 + 2*(n+1)*(suma_prvih n) + (n+1)^2\"\n      by (auto simp add: algebra_simps power2_eq_square)\n    also have \"... =  suma_prvih_3 n +  2*(n+1)*(suma_prvih n) + (n+1)^2\"\n      using Suc\n      by auto\n    also have \"... = suma_prvih_3 n + (n+1)^3\"\n      using *\n      by auto\n    also have \"... = suma_prvih_3 (n+1)\"\n      by auto\n    finally show ?thesis by auto\n  qed\nqed\n\n\n\nlemma bernulli_inequality:\n  fixes n::nat\n  assumes \"n >= 1\" \"a > -1\"\n  shows \"(1 + a)^n \\<ge> 1 + n*a\"\n  using assms\nproof (induction n rule: nat_induct_at_least)\ncase base\n  then show ?case\n    by simp\nnext\ncase (Suc n)\n  have \"1 + (Suc n)*a \\<le> 1 + (Suc n)*a + n*a^2\"\n    using `a >-1`\n    by auto\n  also have \"... = 1 + n*a + a + n*a^2\"\n    by simp\n  also have \"... = (1+ n*a)*(1+a)\"\n    by (auto simp add: algebra_simps power2_eq_square)\n  also have \"... \\<le> (1 + a)^(n) * (1 + a)\"\n    using Suc\n    using mult_le_mono1 \n    by blast\n  also have \"... = (1 + a)^(Suc n)\"\n    by auto\n  finally show ?case .\nqed\n\n\n(* zadaci iz knjige *)\n(* zadatak 3 *)\nprimrec razlomak_proizvoda_suseda :: \"nat \\<Rightarrow> real\" where\n  \"razlomak_proizvoda_suseda 0 = 0\"\n| \"razlomak_proizvoda_suseda (Suc n) = (1::real) / ( Suc n * ((Suc n) + 1)) + razlomak_proizvoda_suseda n\"\n\nvalue \"(\\<Sum>k\\<leftarrow>[1..<Suc 5]. (1::real) / (k * (k + 1)))\"\n\nvalue \"[1..<Suc 4] @ [5]\"\n\n\n\nterm \"sum_list (map (\\<lambda> k. (1::real) / ((k+1) * (k+2))) [1..<Suc 5])\"\n\n\n\nvalue \"razlomak_proizvoda_suseda 2\"\n\nthm add_divide_distrib\n\nlemma sabiranje_razlomaka:\n  fixes a::real\n  fixes b::real\n  fixes c::real\n  shows \"a/b + c/b = (a+c)/b\"\n  by (simp add: add_divide_distrib)\n\nfind_theorems \"_ / _ + _ / _ = _ / _\"\n\n\nlemma dorada:\n  fixes n::nat\n  assumes \"n\\<ge>1\"\n  shows \"(\\<Sum>k\\<leftarrow>[1..<Suc n]. (1::real) / (k * (k + 1))) = real n / (n + 1)\"\n  using assms\nproof(induction n rule: nat_induct_at_least)\n  case base\n  then show ?case by simp\nnext\n  case (Suc n)\n  then show ?case \n  proof-\n    have \"(\\<Sum>k\\<leftarrow>[1..<Suc (Suc n)]. (1::real) / (k * (k + 1))) = \n    (\\<Sum>k\\<leftarrow>([1..<Suc n] @ [n+1]). (1::real) / (k * (k + 1)))\"\n      by auto\n    also have \"... = \n    (\\<Sum>k\\<leftarrow>[1..<Suc n]. (1::real) / (k * (k + 1))) + (\\<Sum>k\\<leftarrow>[n+1]. (1::real) / (k * (k + 1)))\"\n      by auto\n    also have \"... = \n    (\\<Sum>k\\<leftarrow>[1..<Suc n]. (1::real) / (k * (k + 1))) +  (1::real) / ((n+1) * (n+2))\"\n      by (auto simp add:field_simps)\n    also have \"... = n/(n+1) + 1/((n+1)*(n+2))\"\n      using Suc\n      by auto\n    also have \"... =(n+2)/(n+2)* n/((n+1)) + 1/((n+1)*(n+2))\"\n      by auto\n    also have \"... =((n+2)*n)/((n+2)*(n+1)) + 1/((n+1)*(n+2))\"\n      by (metis (no_types, lifting) divide_divide_eq_left of_nat_mult times_divide_eq_left)\n    also have \"... =((n+2)*n)/((n+2)*(n+1)) + 1/((n+2)*(n+1))\"\n      by auto\n    also have \"... =(n*n+2*n)/((n+2)*(n+1)) + 1/((n+2)*(n+1))\"\n      by auto  \n    also have \"... =(n*n+2*n+1)/((n+2)*(n+1))\"\n      using sabiranje_razlomaka\n      by (auto simp add: algebra_simps)     \n    also have \"... = (n^2 + 2*n + 1)/((n+1)*(n+2))\"\n      by (auto simp add: algebra_simps power2_eq_square)\n    also have \"... = (n+1)^2/((n+1)*(n+2))\"\n      by (auto simp add: algebra_simps power2_eq_square)\n    also have \"... = (n+1)/(n+2)\"\n      by (smt Suc.hyps divide_divide_eq_right nonzero_mult_div_cancel_left of_nat_1 of_nat_add of_nat_mono of_nat_mult power2_eq_square)\n    finally show ?thesis by auto\n  qed\nqed\n\n\nlemma zbir_razlomka_proizvoda_suseda: \n  fixes n::nat\n  assumes \"n \\<ge> 1\"\n  shows \"razlomak_proizvoda_suseda n = real(n) div (n+1)\"\n  using assms\nproof(induction n rule: nat_induct_at_least)\n  case base\n  then show ?case by simp\nnext\n  case (Suc n)\n  then show ?case \n  proof-\n    have \"razlomak_proizvoda_suseda (Suc n) = \n    razlomak_proizvoda_suseda n + 1/((n+1)*(n+2))\"\n      by auto\n    also have \"... = n/(n+1) + 1/((n+1)*(n+2))\"\n      using Suc\n      by auto\n    also have \"... =(n+2)/(n+2)* n/((n+1)) + 1/((n+1)*(n+2))\"\n      by auto\n    also have \"... =((n+2)*n)/((n+2)*(n+1)) + 1/((n+1)*(n+2))\"\n      by (metis (no_types, lifting) divide_divide_eq_left of_nat_mult times_divide_eq_left)\n    also have \"... =((n+2)*n)/((n+2)*(n+1)) + 1/((n+2)*(n+1))\"\n      by auto\n    also have \"... =(n*n+2*n)/((n+2)*(n+1)) + 1/((n+2)*(n+1))\"\n      by auto  \n    also have \"... =(n*n+2*n+1)/((n+2)*(n+1))\"\n      using sabiranje_razlomaka\n      by (auto simp add: algebra_simps)     \n    also have \"... = (n^2 + 2*n + 1)/((n+1)*(n+2))\"\n      by (auto simp add: algebra_simps power2_eq_square)\n    also have \"... = (n+1)^2/((n+1)*(n+2))\"\n      by (auto simp add: algebra_simps power2_eq_square)\n    also have \"... = (n+1)/(n+2)\"\n      by (smt Suc.hyps divide_divide_eq_right nonzero_mult_div_cancel_left of_nat_1 of_nat_add of_nat_mono of_nat_mult power2_eq_square)\n    finally show ?thesis by auto\n  qed\nqed\n\n\n\n(* 5. zadatak *)\n\nprimrec cetiri_n_minus_1 :: \"nat \\<Rightarrow> nat\" where\n  \"cetiri_n_minus_1 0 = 1\"\n| \"cetiri_n_minus_1 (Suc n) = (4*(Suc n) - 1) * cetiri_n_minus_1 n\"\n\nvalue \"cetiri_n_minus_1 2\"\n\nprimrec cetiri_n_plus_1 :: \"nat \\<Rightarrow> nat\" where\n  \"cetiri_n_plus_1 0 = 1\"\n| \"cetiri_n_plus_1 (Suc n) = (4*(Suc n) + 1) * cetiri_n_plus_1 n\"\n\n\nlemma poredjenje_razlomaka:\n  fixes a::real\n  fixes b::real\n  fixes c::real\n  assumes \"a > c\" \"a > 0\" \"b > 0\"\n  shows \"sqrt(a/b) > sqrt(c/b)\"\n  using assms\n  by (simp add: divide_strict_right_mono)\n\nfind_theorems \"(_*_)^_ = _^_*_^_\"\n\nfind_theorems \"_ < _ \\<Longrightarrow> _/_ < _/_\"\n\nfind_theorems \"_<_ \\<Longrightarrow> _*_ < _*_\"\n\nfind_theorems \"_^2 \\<ge> 0\"\n\n\n(* primer 5. *)\n\nprimrec faktorijel :: \"nat \\<Rightarrow> nat\" where\n  \"faktorijel 0 = 1\"\n| \"faktorijel (Suc n) = Suc n * faktorijel n\"\n\nlemma fact2_veci_2naN:\n  fixes n::nat\n  assumes \"n \\<ge> 4\"\n  shows \"faktorijel n > (2::nat)^n\"\n  using assms\nproof(induction n rule: nat_induct_at_least)\n  case base\n  thus ?case\n    by (simp add: numeral.simps(2))\nnext\n  case (Suc n)\n  have \"2^(Suc n) = 2 * 2^n\"\n    by simp\n  also have \"... < (Suc n) * 2^n\"\n    using Suc \n    by auto\n  also have \"... \\<le> (Suc n) * faktorijel n\"\n    using Suc less_imp_le_nat mult_le_mono2\n    by blast\n  also have \"... = faktorijel (n + 1)\"\n    by auto\n  finally show ?case by simp\nqed\n\n(* zadatak 6. *)\n(* Dokazati da vazi 2^n > n^2 za n \\<ge> 5*)\n\nlemma pomocna_1_dva_na_stepen_n_na_kvadrat:\n  fixes n::nat\n  assumes \"n \\<ge> 5\"\n  shows \"n^2 > 2*n + 1\"\n  using assms\nproof(induction n rule: nat_induct_at_least)\n  case base\n  then show ?case by simp\nnext\n  case (Suc n)\n    have *:\"(Suc n)^2 = n^2 + 2*n + 1\"\n      by (simp add: power2_eq_square)\n    also have \"... > 2*(n + 1) + 1 \"\n      using assms Suc \n      by auto\n    finally show ?case\n      by simp \nqed\n\nlemma dva_na_stepen_n_na_kvadrat:\n  fixes n::nat\n  assumes \"n\\<ge>5\"\n  shows \"2^n > n^2\"\n  using assms\nproof(induction n rule: nat_induct_at_least)\n  case base\n  then show ?case\n    by auto\nnext\n  case (Suc n)\n  have \"(n + 1)^2 = n^2 + 2*n + 1\"\n    by (simp add: power2_eq_square)\n  also have \"... < 2*n^2\"\n    using pomocna_1_dva_na_stepen_n_na_kvadrat Suc\n    by auto\n  also have \"... < 2*2^n\"\n    using Suc\n    by auto\n  also have \"... = 2^(n+1)\"\n    by auto\n  finally show ?case by simp\nqed\n\nlemma n_n_kvadrat:\n  fixes n::nat\n  assumes \"n\\<ge>2\"\n  shows \"n < n^2\"\n  using assms\nproof (induction n rule: nat_induct_at_least)\n  case base\n  then show ?case\n    by auto\nnext\n  case (Suc n)\n  then show ?case\n  proof-\n    have \"Suc n = n+1\"\n      by auto\n    also have \"... < n^2 + 1\"\n      using Suc\n      by auto\n    also have \"... < n^2 + 1 + 2*n\"\n      using Suc.hyps by linarith\n    also have \"... = (n+1)^2\"\n      by (auto simp add: power2_eq_square)\n    finally show ?thesis by auto\n  qed\nqed\n\nlemma\n  fixes n::nat\n  assumes \"n \\<ge> 3\"\n  shows \"4^(n-1) > n^2\"\n  using assms\nproof (induction n rule: nat_induct_at_least)\ncase base\n  then show ?case\n    by auto\nnext\n  case (Suc n)\n  then show ?case\n  proof-\n    have \"(Suc n)^2 = n^2 + 2*n + 1\"\n      by (auto simp add: power2_eq_square)\n    also  have \"... = n^2 + n + n + 1\"\n      by auto\n    also have \"... < n^2 + n^2 + n +1\"\n      using assms\n      by (metis Suc.hyps Suc_le_mono add_less_mono1 eval_nat_numeral(3) le_SucI n_n_kvadrat nat_add_left_cancel_less)\n    also have \"... < n^2 + n^2 + n^2 +1\"\n      using assms\n      by (metis Suc.hyps Suc_le_mono add_less_mono1 eval_nat_numeral(3) le_SucI n_n_kvadrat nat_add_left_cancel_less)\n    also have \"... < n^2 + n^2 + n^2 +n\"\n      using assms\n      using Suc.hyps by linarith\n    also have \"... < n^2 + n^2 + n^2 +n^2\"\n      using assms\n      by (metis Suc.hyps Suc_le_mono  eval_nat_numeral(3) le_SucI n_n_kvadrat nat_add_left_cancel_less)\n    also have \"... = 4*n^2\"\n      by auto\n    also have \"... <4*4^(n-1)\"\n      using Suc\n      by auto\n    also have \"... = 4^n\"\n      by (metis One_nat_def Suc_pred \\<open>n\\<^sup>2 + n\\<^sup>2 + n\\<^sup>2 + 1 < n\\<^sup>2 + n\\<^sup>2 + n\\<^sup>2 + n\\<close> add_Suc add_Suc_shift less_SucI nat_add_left_cancel_less power_Suc)\n    finally show ?thesis by auto\n  qed\nqed\n\nprimrec zbir_stepena :: \"nat \\<Rightarrow> real \\<Rightarrow> real\" where\n\"zbir_stepena 0 x = 1\"\n|\"zbir_stepena (Suc n) x = zbir_stepena n x + x^(n+1)\"\n\nvalue \"zbir_stepena 2 2\"\n\nlemma\n  fixes x::real\n  fixes n::nat\n  assumes \"x \\<noteq> 1\"\n  shows \"zbir_stepena n x = (x^(n+1)-1)/(x-1)\"\n  using assms\nproof (induction n)\n  case 0\n  then show ?case\n    by auto\nnext\n  case (Suc n)\n  then show ?case\n  proof-\n    have \"zbir_stepena (Suc n) x = zbir_stepena n x + x^(n+1)\"\n      by simp\n    also have \"... =  (x^(n+1)-1)/(x-1) +  x^(n+1)\"\n      using Suc\n      by auto\n    also have \"... =  (x^(n+1)-1)/(x-1) + (x-1)*x^(n+1)/(x-1)\"\n      using assms\n      by simp\n    also have \"... = (x^(n+1)-1 +(x-1)*x^(n+1))/(x-1)\"\n      using sabiranje_razlomaka by blast\n    also have \"... = (x^(n+1)-1 + x*x^(n+1)-x^(n+1))/(x-1)\"\n      by (auto simp add : field_simps)\n    also have \"... = (-1 + x*x^(n+1))/(x-1)\"\n      by auto\n    also have \"... = (x^(n+2)-1)/(x-1)\"\n      by auto\n    finally show ?thesis by auto\n  qed\nqed\n\n(* zadatak 16. a) *)\n(* (1 - 1/4) * (1-1/9)*...*(1 - 1/n^2) = (n + 1)/2*n za n \\<ge> 2 *)\n\n(* zadatak 4. *)\n\nlemma deljivost_sa_19: \n  \"(19::nat) dvd 7 * 5^(2*n) + 12 * 6 ^ n\"\nproof(induction n)\n  case 0\n  thus ?case\n    by auto\nnext\n  case (Suc n)\n  have \"(7::nat) * 5 ^ (2 * Suc n) + 12 * 6 ^ (Suc n) = 7 * 25 * 5 ^ (2 * n) + 12 * 6 * 6 ^ n\"\n    using [[show_types]]\n    by auto\n  also have \"... = 7 * 25 * 5 ^ (2 * n) + 6 * (7 * 5^(2*n) + 12 * 6 ^ n - 7 * 5 ^(2*n))\"\n    by auto\n  also have \"... = 7 * 25 * 5 ^ (2 * n) + 6 * (7 * 5^(2*n) + 12 * 6 ^ n) - 6 * 7 * 5 ^(2*n)\"\n    by auto\n  also have \"... = 19 * 7 * 5 ^ (2 * n) + 6 * (7 * 5^(2*n) + 12 * 6 ^ n)\"\n    by auto\n  finally show ?case\n    by (smt Suc.IH dvd_add_left_iff dvd_trans dvd_triv_right mult.commute)\nqed\n\n(* Dokazati da je broj f(n) = 2^(n+1) + 3^(2*n-1)\n deljiv sa 7 za sve prirodne brojeve. *)\n(* Zadatak je Primer 2. iz knjige Analiza sa algebrom 2 \n i u knjizi se javlja greska u dokazu.*)\n\n\nlemma pomocna_deljivost_sa_7:\n assumes \"n \\<ge> 1\"\n shows \"(3::nat)^ (n * 2) = 3 * 3 ^ (n*2 - Suc 0)\"\n  using [[show_types]]\n  using assms\n  by (induction n rule: nat_induct_at_least) auto\n\nlemma deljivost_sa_7:\n  fixes n::nat\n  assumes \"n \\<ge> 1\" \n  shows \"(7::nat) dvd 2^(n+1) + 3^(2*n - 1)\"\n  using assms\nproof(induction n rule: nat_induct_at_least)\n  case base\n  thus ?case \n    by auto\nnext\n  case (Suc n)\n  have \"(2::nat)^(Suc n + 1) + (3::nat)^(2*(Suc n) - 1) = 2 ^ (n + 2) + 3 ^ (2*n +1)\"\n    using [[show_types]]\n    by auto\n  also have \"... = 2 * 2^(n + 1) + 3 * 3 * 3 ^(2*n - 1)\"\n    using [[show_types]]\n    using pomocna_deljivost_sa_7\n    by (smt Groups.add_ac(2) Groups.mult_ac(1) \n       One_nat_def Suc.hyps add_Suc_right mult.commute one_add_one plus_1_eq_Suc power_Suc)\n  also have \"... = 2 * (2^(n+1) + 3^(2*n - 1) - 3^(2*n-1)) + 9 * 3 ^ (2*n - 1)\"\n    by auto\n  also have \"... = 2 * (2^(n+1) + 3^(2*n - 1)) - 2 * 3 ^ (2*n-1) + 9 * 3 ^(2*n-1)\"\n    by auto\n  also have \"... = 2 * (2^(n+1) + 3^(2*n - 1)) + 7 * 3 ^(2*n-1)\"\n    by auto\n  finally show ?case\n    by (metis Suc.IH dvd_add dvd_add_times_triv_right_iff mult.commute mult_2)\nqed\n\n(* zadatak 18. a) *)\n\nlemma deljivost_sa_3:\n  fixes n::nat\n  shows \"(3::nat) dvd 5^n + 2^(n+1)\"\nproof(induction n)\n  case 0\n  thus ?case\n    by (simp add: numeral_3_eq_3)\nnext\n  case (Suc n)\n  have \"5^(Suc n) + 2^(Suc n + 1) = 5 * 5^n + 2*2^( n + 1)\"\n      by simp\n    also have \"... = (5::nat) * (5^n + 2^(n+1) - 2^(n+1)) + 2 * 2^(n + 1)\"\n      using Suc\n      by simp\n    also have \"... = 5 * (5^n + 2^(n+1)) - 5*2^(n+1) + 2 * 2^(n+1)\"\n      by simp\n    also have \"... = 5 * (5^n + 2^(n+1)) - 3*2^(n+1)\"\n      by simp\n    finally show ?case\n      using Suc\n      by (auto simp only: dvdI dvd_diff_nat dvd_trans dvd_triv_right)\nqed\n(* zadatak 18. b) *)\nlemma deljivost_sa_59:\n  fixes n::nat\n  shows \"(59::nat) dvd 5^(n+2) + 26 * 5^n + 8^(2*n+1)\"\nproof (induction n)\n  case 0\n  thus ?case\n    by simp\nnext\n  case (Suc n)\n  have \"(5::nat)^(Suc n+2) + 26 * 5^(Suc n) + 8^(2*(Suc n)+1) =\n        5 * 5^(n + 2) + 26 * 5 * 5^n + 8^2 * 8^(2*n + 1)\"\n    by simp\n  also have \"... = 5 * 5^(n + 2) + \n            5 *(5^(n+2) + 26 * 5^n + 8^(2*n+1) - 5^(n+2)- 8^(2*n+1))\n            + 8^2 * 8^(2*n + 1)\"\n    by simp\n  also have \"... = 5 * 5^(n + 2) + 5 *(5^(n+2) + 26 * 5^n + 8^(2*n+1)) -\n             5*5^(n+2)- 5*8^(2*n+1)\n            + 8^2 * 8^(2*n + 1)\"\n    by simp\n  also have \"... = 5 *(5^(n+2) + 26 * 5^n + 8^(2*n+1)) + 59* 8^(2*n+1)\"\n    by simp\n  finally show ?case\n    using Suc\n    by (auto simp only: add_2_eq_Suc' dvd_add_left_iff dvd_triv_left dvd_triv_right gcd_nat.trans)\nqed\n(* zadatak 18. c) *)\nlemma deljivost_sa_133: \n  fixes n::nat\n  shows \"(133::nat) dvd 11^(n+2)+ 12^(2*n+1)\"\nproof(induction n)\n  case 0\n  thus ?case\n    by simp\nnext\n  case (Suc n)\n  have \"(11::nat)^(Suc n + 2) + 12^(2*(Suc n) + 1) = 11 * 11^(n + 2) + 12^2 * 12^(2*n+1)\"\n    by simp\n  also have \"... = 11 * (11^(n+2)+ 12^(2*n+1) - 12^(2*n+1))+ 12^2 * 12^(2*n+1)\"\n    by simp\n  also have \"... = 11 * (11^(n+2)+ 12^(2*n+1)) + 133 * 12^(2*n+1)\"\n    by simp\n  finally show ?case\n    using Suc\n    by (auto simp only: add_2_eq_Suc' dvd_add_left_iff dvd_triv_left dvd_triv_right gcd_nat.trans)\nqed\n\n(* zadatak 18. g) *)\n(* 11 | 30^n + 4^n * (3^n - 2^n) - 1 *)\n\n(* n! < n^(n-1) *)\nthm Suc_mult_less_cancel1\nthm power_eq_if\n\nprimrec n_na_m :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\" where\n  \"n_na_m n 0 = n\"\n| \"n_na_m n (Suc m) = n + n_na_m n m\" \n\n\nthm power_decreasing\nthm power_Suc\nthm power_Suc2\nthm power_Suc_le_self\nthm power_add\nthm power_Suc_less_one\nthm power_add_numeral\nthm power_dict\nthm power_diff\n\nfind_theorems \"_ < _ \\<Longrightarrow> _^_ < _^_\"\nthm power_less_imp_less_base\nthm power_strict_mono\n\nlemma n_faktorijel_n_n_minus_jedan_pomocna:\n  fixes n::nat\n  assumes \"n \\<ge> 2\"\n  shows \"(n+1)^(n-1) > n^(n-1)\"\n  using assms\n  by (auto simp add:power_strict_mono)\n\nlemma n_faktorijel_n_n_minus_jedan:\n  fixes n::nat\n  assumes \"n \\<ge> 3\"\n  shows \"faktorijel n < n^(n-1)\"\n  using assms\nproof(induction n rule: nat_induct_at_least)\n  case base\n  then show ?case\n    by (simp add: numeral_3_eq_3)\nnext\n  case (Suc n)\n  have \"faktorijel (Suc n) = Suc n * faktorijel n\"\n    by (simp only: faktorijel.simps(2))\n  also have \"... < (n + 1) * n^(n - 1)\"\n    using Suc Suc_mult_less_cancel1\n    by auto\n  also have \"... \\<le> (n + 1)*(n + 1)^(n - 1)\"  \n    using Suc n_faktorijel_n_n_minus_jedan_pomocna\n    by (metis Suc_eq_plus1 Suc_mult_less_cancel1 add.commute eval_nat_numeral(3) le_SucI less_imp_le_nat nat_add_left_cancel_le)\n  also have \"... = (n + 1)^n\"\n    by (metis Suc(1) add_leD1 not_one_le_zero numeral_3_eq_3 plus_1_eq_Suc power_eq_if)\n  finally show ?case by simp\nqed\n\n\n(* Knjiga Nejednakosti DMS strana 43 *)\nprimrec suma_levo :: \"nat \\<Rightarrow> real\" where\n\"suma_levo 0 = 0\"\n| \"suma_levo (Suc n) = suma_levo n + 1/(1+2*n) + 1/(2+2*n) - 1/(1+n)\"\n\nvalue \"suma_levo 2\"\n\n(* pomocna tvrdjenja *)\nlemma pom:\n  fixes n::nat\n  shows \"1/(2*n+1) - 1/(2*n+2) \\<ge> 0\"\n  by (auto simp add : field_simps)\n\nlemma pom2:\n  fixes n::nat\n  shows \"1/real(2*n+2) - 1/real(n+1) = - 1/real(2*n+2)\"\nproof-\n  have \"1/real(2*n+2) - 1/real(n+1) = 1/real(2*n+2)/((n+1)/(n+1)) - 1/real(n+1)\"\n    by auto\n  also have \"1/real(2*n+2) - 1/real(n+1) = 1*real(n+1)/(real(2*n+2)*(n+1)) - 1/real(n+1)\"\n    by auto\n  also have \"... = real(n+1)/(real(2*n+2)*(n+1)) - 1/real(n+1)/(real(2*n+2)/(2*n+2))\"\n    by auto\n  also have  \"... = real(n+1)/(real(2*n+2)*(n+1)) - real(2*n+2)/(real(n+1)*(2*n+2))\"\n    by auto\n  also have  \"... = real(n+1)/(real(n+1)*(2*n+2)) - real(2*n+2)/(real(n+1)*(2*n+2))\"\n    by auto\n  also have \"... =  (real(n+1)-real(2*n+2))/(real(n+1)*(2*n+2))\"\n    by (smt sabiranje_razlomaka)\n  also have \"... = -real(n+1)/(real(1+n)*real(2+2*n))\"\n    by auto\n  also have \"... = -1/real(2+2*n)\"\n    using field_simps\n    by (smt \\<open>1 / real (2 * n + 2) - 1 / real (n + 1) = 1 * real (n + 1) / (real (2 * n + 2) * real (n + 1)) - 1 / real (n + 1)\\<close> divide_minus_left)\n  finally show ?thesis by auto\nqed\n\n(* tvrdjenje u zadatku *)\nlemma \n  fixes n::nat\n  assumes \"n\\<ge>1\"\n  shows \"suma_levo n \\<ge> 1/2\"\n  using assms\nproof (induction n rule:nat_induct_at_least)\ncase base\n  then show ?case\n    by auto\nnext\n  case (Suc n)\n  then show ?case\n  proof-\n    have \"1/2 \\<le> 1/2 + 1/(2*n+1) - 1/(2*n+2)\"\n      using pom\n      by smt\n    also have \"... =1/2 + 1/(2*n+1) + 1/(2*n+2) - 1/(n+1)\"\n      using pom2\n      by auto\n    also have \"... \\<le> suma_levo n  + 1/(2*n+1) + 1/(2*n+2) - 1/(n+1)\"\n      using Suc\n      by auto\n    also have \"... = suma_levo (Suc n)\"\n      by auto\n    finally show ?thesis by auto\n  qed\nqed\n\n\n(* da se brojevi oblika 2^2^n + 1 (n = 2, 3 , . . . ) zavr\u0161avaju cifrom 7 *)\n\nlemma dva_na_dva_na_n_cifra:\n  fixes n::nat\n  assumes \"n \\<ge> 2\"\n  shows \" 2^2^n mod (10::nat) = (6::nat)\"\n  using assms\nproof(induction n rule: nat_induct_at_least)\n  case base\n  then show ?case by simp\nnext\n  case (Suc n)\n  then show ?case\n  proof-\n  have \"(2::nat)^2^(n+1) mod (10::nat) = 2^(2^n * 2) mod (10::nat)\"\n    by (metis power_add power_one_right)\n  also have \"... = 2^2^n * 2^2^n mod (10::nat)\"\n    by (simp add: power2_eq_square power_mult)\n  also have *:\"...  =  (2^2^n mod (10::nat) *  2^2^n mod (10::nat)) mod (10::nat)\"\n    using mod_mult_left_eq\n    by (simp add: mod_mult_left_eq)\n  also have \"... = ((6::nat)*(6::nat)) mod (10::nat)\"\n    using Suc *\n    by (metis mod_mult_eq)\n  also have \"... = 6\"\n    by auto\n  finally show ?thesis by auto\n qed\nqed\n\n\nlemma dva_na_dva_na_n_plus_jedan_cifra:\n  fixes n::nat\n  assumes \"n \\<ge> 2\"\n  shows \" (2^2^n + 1) mod (10::nat) = (7::nat)\"\n  using assms\n  using dva_na_dva_na_n_cifra\n  by (metis Suc3_eq_add_3 Suc_1 add_Suc_right mod_add_left_eq mod_less nat_add_left_cancel_less numeral_Bit0 numeral_nat(3) one_less_numeral_iff plus_nat.simps(2) semiring_norm(76))\n\n\n(* da se brojevi oblika 2^4^n (n = 1, 2 , . . . ) zavr\u0161avaju cifrom 6 *)\n\nlemma dva_na_cetiri_na_n_cifra_pomocna:\n  fixes n::nat\n  assumes \"n \\<ge> 1\"\n  shows \" 2^2^(2*n) mod (10::nat) = (6::nat)\"\n  using assms dva_na_dva_na_n_cifra\n  by simp\n\nlemma dva_na_cetiri_na_n_cifra_pomocna2: \n  \"2^4^n = 2^(2^(2*n))\"\n  by (smt Suc_1 mult_2 numeral_Bit0 one_power2 plus_1_eq_Suc power2_sum power_mult)\n\nlemma dva_na_cetiri_na_n_cifra:\n  fixes n::nat\n  assumes \"n \\<ge> 1\"\n  shows \" 2^4^n mod (10::nat) = (6::nat)\"\n  using assms dva_na_cetiri_na_n_cifra_pomocna\n  by (simp add: dva_na_cetiri_na_n_cifra_pomocna2)\n\n(* Neke nasumicne leme iz kongruencije *)\n\nlemma mod_distrib_plus:\n  fixes a b c :: int  \n  shows \"(a + b) mod c = (a mod c + b mod c) mod c\"\n  by (simp add: mod_add_eq)\n\nlemma mod_distrib_sub:\n  fixes a b ::int\n  fixes c :: nat\n  shows \"(a - b) mod c = (a mod c - b mod c) mod c\"\n  by (simp add: mod_diff_eq)\n\nlemma mod_distrib_diff:\n  fixes a b c d m :: int\n  assumes \"a mod m = b\" \"c mod m = d\"\n  shows \"(a - c) mod m = (b - d) mod m\"\n  using assms\n  by (metis mod_diff_cong mod_mod_trivial)\n\n\nlemma mod_distrib_add:\n  fixes a b c d m :: int\n  assumes \"a mod m = b\" \"c mod m = d\"\n  shows \"(a + c) mod m = (b + d) mod m\"\n  using assms\n  by (metis mod_add_cong mod_add_left_eq mod_mod_trivial)\n\n\nlemma mod_distrib_prod:\n  fixes a b c d m :: int\n  assumes \"a mod m = b\" \"c mod m = d\"\n  shows \"(a * c) mod m = (b * d) mod m\"\n  using assms\n  by (auto simp add: mod_mult_eq)\n\n(*kongruencije krugova zbirka 3. god *)\nthm semiring_normalization_rules\nlemma dvanaest_na_n_mod_11:\n  fixes n::nat\n  shows \"(12::nat)^n mod 11 = 1\"\nproof(induction n)\n  case 0\n  then show ?case by simp\nnext\n  case (Suc n)\n  have \"(12::nat)^(Suc n) mod 11 = (12 * (12^n)) mod 11\"\n    by simp\n  also have \"... =( 12 mod 11 )* (12^n mod 11)\"\n    by (metis Suc.IH mod_mult_right_eq mult.right_neutral)\n  also have \"... = 1 * 1\"\n    using Suc\n    by simp\n  finally show ?case by simp \nqed\n\nlemma deljivost_sa_11:\n  fixes n::nat\n  shows \"(12^n - 1) mod (11::nat) = (0::nat)\"\nproof(induction n)\n  case 0\nthen show ?case by simp\nnext\n  case (Suc n)\n  then show ?case\n  proof-\n    have \"(12^(Suc n) - 1) mod (11::nat) = (12*12^n - 1) mod (11::nat)\"\n      by simp\n    also have \"... = (12*12^n) mod 11 - 1 mod 11\"\n      by (metis One_nat_def add_diff_cancel_left' add_diff_cancel_right' calculation div_mult_mod_eq dvanaest_na_n_mod_11 \n           mod_mod_trivial mod_mult_self2_is_0 plus_1_eq_Suc power_Suc)\n    also have \"... = 1 - 1\"\n      by (metis dvanaest_na_n_mod_11 mod_mod_trivial power_Suc)\n    also have \"... = 0\"\n      by simp\n    finally show ?case by simp\n  qed\nqed\n\n\nlemma deset_na_3_n_mod_37:\n  fixes n ::nat\n  shows \"10^(3*n) mod (37::nat) = 1\"\nproof(induction n)\ncase 0\n  then show ?case by simp\nnext\n  case (Suc n)\n  then show ?case\n  proof-\n    have \"(10::nat)^(3*(Suc n)) mod (37::nat) = (10::nat)^(3*n + 3) mod (37::nat)\"\n      by (simp add: semiring_normalization_rules(24))\n    also have \"... = 10^3 * 10^(3*n) mod 37\"\n      by (simp add: power_add semiring_normalization_rules(7))\n    also have \"... = (10^3 mod 37) * 10^(3*n) mod 37\"\n      by (metis mod_mult_left_eq)\n    also have \"... = 1 * 1\"\n      using Suc\n      by simp\n    finally show ?case by simp\n  qed\nqed\n\nlemma deljivost_sa_37:\n  fixes n::nat\n  shows \"(10^(3*n) - 1) mod (37::nat) = 0\" \nproof(induction n)\n  case 0\n  then show ?case by simp\nnext\n  case (Suc n)\n  then show ?case\n  proof-\n    have \"((10::nat)^(3*(Suc n)) - 1) mod (37::nat) = (10^(3*(n+1)) - 1) mod (37::nat)\"\n      by simp\n    also have \"... = (10^(3*n+3) - 1) mod (37::nat)\"\n      by (simp add: semiring_normalization_rules(24))\n    also have \"... = (10^3 * 10^(3*n) - 1) mod (37::nat)\"\n      by (simp add: power_add semiring_normalization_rules(24))\n    also have \"... = (10^3 * 10^(3*n)) mod (37::nat) - 1 mod (37::nat)\"\n      by (metis (no_types, lifting) One_nat_def  add_diff_cancel_left' add_diff_cancel_right' \n          deset_na_3_n_mod_37 div_mult_mod_eq mod_mod_trivial mod_mult_self2_is_0 mult_Suc_right \n          plus_1_eq_Suc power_add)   \n    also have \"... = 1 - 1\"\n      using Suc\n      by (metis deset_na_3_n_mod_37 mod_mod_trivial mult_Suc_right power_add)\n    finally show ?case by simp\n  qed\nqed\n\n\ntype_synonym mat2 = \"int \\<times> int \\<times> int \\<times> int\"\n\n(* Mnozenje matrica dimenzije 2x2 *)\nfun mat_mul :: \"mat2 \\<Rightarrow> mat2 \\<Rightarrow> mat2\" where\n  \"mat_mul (a1, b1, c1, d1) (a2, b2, c2, d2) = (a1*a2 + b1*c2, a1*b2 + b1*d2, c1*a2 + d1*c2, c1*b2 + d1*d2)\"\n\n(* Jedinicna matrica *)\ndefinition eye :: mat2 where\n  \"eye = (1, 0, 0, 1)\"\n\nprimrec mat_pow :: \"mat2 \\<Rightarrow> nat \\<Rightarrow> mat2\" where\n  \"mat_pow A 0 = eye\"\n| \"mat_pow A (Suc n) = mat_mul A (mat_pow A n)\"\n\ndefinition M :: mat2 where\n  \"M = (-2, 9, -1, 4)\"\n\nlemma \"mat_pow M n = (1-3*n, 9*n, -n, 1+3*n)\"\nproof (induction n)\ncase 0\n  then show ?case\n   by (simp add: eye_def)\nnext\ncase (Suc n)\n  then show ?case\n  proof-\n    have \"mat_pow M (Suc n) = mat_mul M (mat_pow M n)\"\n      by simp\n    also have \"... = mat_mul M (1-3*(n::int), 9*n, -n, 1+3*n)\"\n      using Suc\n      by auto\n    also have \"... = mat_mul (-2, 9, -1, 4) (1-3*(n::int), 9*n, -n, 1+3*n)\"\n      unfolding M_def\n      by auto\n    also have \"... = (-2+6*(n::int)-9*(n::int), -18*n+9+27*n, -1+3*n-4*n, -9*n+4+12*n)\"\n      by auto\n    also have \"... = (-2-3*(n::int), 9+9*n, -1-n, 4+3*n)\"\n      by auto\n    also have \"... = (1-3*((n::int)+1), 9*(n+1), -(n+1), 1+3*(n+1))\"\n      by auto\n    finally show ?thesis by auto\n  qed\nqed\n\n\n\n\nend\n", "meta": {"author": "AlexJakovljevic", "repo": "teoreme", "sha": "ff570bd54ecfd7a2a41495c21d1f04b27a478d29", "save_path": "github-repos/isabelle/AlexJakovljevic-teoreme", "path": "github-repos/isabelle/AlexJakovljevic-teoreme/teoreme-ff570bd54ecfd7a2a41495c21d1f04b27a478d29/seminarski.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513786759492, "lm_q2_score": 0.7981867825403177, "lm_q1q2_score": 0.7153760042926798}}
{"text": "theory PALandWiseMenPuzzle2021_4Agents imports Main    (* Sebastian Reiche and Christoph Benzm\u00fcller, 2021 *)\n\n\nbegin\n (* Parameter settings for Nitpick *) nitpick_params[user_axioms=true, format=4, show_all]\n  \n typedecl i (* Type of possible worlds *)\n type_synonym \\<sigma> = \"i\\<Rightarrow>bool\" (* \\<D> *)\n type_synonym \\<tau> = \"\\<sigma>\\<Rightarrow>i\\<Rightarrow>bool\" (* Type of world depended formulas (truth sets) *) \n type_synonym \\<alpha> = \"i\\<Rightarrow>i\\<Rightarrow>bool\" (* Type of accessibility relations between world *)\n\n (* Some useful relations (for constraining accessibility relations) *)\n definition reflexive::\"\\<alpha>\\<Rightarrow>bool\" where \"reflexive R \\<equiv> \\<forall>x. R x x\"\n definition symmetric::\"\\<alpha>\\<Rightarrow>bool\" where \"symmetric R \\<equiv> \\<forall>x y. R x y \\<longrightarrow> R y x\"\n definition transitive::\"\\<alpha>\\<Rightarrow>bool\" where \"transitive R \\<equiv> \\<forall>x y z. R x y \\<and> R y z \\<longrightarrow> R x z\"\n definition euclidean::\"\\<alpha>\\<Rightarrow>bool\" where \"euclidean R \\<equiv> \\<forall>x y z. R x y \\<and> R x z \\<longrightarrow> R y z\"\n definition intersection_rel::\"\\<alpha>\\<Rightarrow>\\<alpha>\\<Rightarrow>\\<alpha>\" where \"intersection_rel R Q \\<equiv> \\<lambda>u v. R u v \\<and> Q u v\"\n definition union_rel::\"\\<alpha>\\<Rightarrow>\\<alpha>\\<Rightarrow>\\<alpha>\" where \"union_rel R Q \\<equiv> \\<lambda>u v. R u v \\<or> Q u v\"\n definition sub_rel::\"\\<alpha>\\<Rightarrow>\\<alpha>\\<Rightarrow>bool\" where \"sub_rel R Q \\<equiv> \\<forall>u v. R u v \\<longrightarrow> Q u v\"\n definition inverse_rel::\"\\<alpha>\\<Rightarrow>\\<alpha>\" where \"inverse_rel R \\<equiv> \\<lambda>u v. R v u\"\n definition bigunion_rel::\"(\\<alpha>\\<Rightarrow>bool)\\<Rightarrow>\\<alpha>\" (\"\\<^bold>\\<Union>_\") where \"\\<^bold>\\<Union> X \\<equiv> \\<lambda>u v. \\<exists>R. (X R) \\<and> (R u v)\"\n definition bigintersection_rel::\"(\\<alpha>\\<Rightarrow>bool)\\<Rightarrow>\\<alpha>\" (\"\\<^bold>\\<Inter>_\") where \"\\<^bold>\\<Inter> X \\<equiv> \\<lambda>u v. \\<forall>R. (X R) \\<longrightarrow> (R u v)\"\n\n (*In HOL the transitive closure of a relation can be defined in a single line.*)\n definition tc::\"\\<alpha>\\<Rightarrow>\\<alpha>\" where \"tc R \\<equiv> \\<lambda>x y.\\<forall>Q. transitive Q \\<longrightarrow> (sub_rel R Q \\<longrightarrow> Q x y)\"\n\n (* Lifted HOMML connectives for PAL *)\n abbreviation patom::\"\\<sigma>\\<Rightarrow>\\<tau>\" (\"\\<^sup>A_\"[79]80) where \"\\<^sup>Ap \\<equiv> \\<lambda>W w. W w \\<and> p w\"\n abbreviation ptop::\"\\<tau>\" (\"\\<^bold>\\<top>\") where \"\\<^bold>\\<top> \\<equiv> \\<lambda>W w. True\" \n abbreviation pneg::\"\\<tau>\\<Rightarrow>\\<tau>\" (\"\\<^bold>\\<not>_\"[52]53) where \"\\<^bold>\\<not>\\<phi> \\<equiv> \\<lambda>W w. \\<not>(\\<phi> W w)\" \n abbreviation pand::\"\\<tau>\\<Rightarrow>\\<tau>\\<Rightarrow>\\<tau>\" (infixr\"\\<^bold>\\<and>\"51) where \"\\<phi>\\<^bold>\\<and>\\<psi> \\<equiv> \\<lambda>W w. (\\<phi> W w) \\<and> (\\<psi> W w)\"   \n abbreviation por::\"\\<tau>\\<Rightarrow>\\<tau>\\<Rightarrow>\\<tau>\" (infixr\"\\<^bold>\\<or>\"50) where \"\\<phi>\\<^bold>\\<or>\\<psi> \\<equiv> \\<lambda>W w. (\\<phi> W w) \\<or> (\\<psi> W w)\"   \n abbreviation pimp::\"\\<tau>\\<Rightarrow>\\<tau>\\<Rightarrow>\\<tau>\" (infixr\"\\<^bold>\\<rightarrow>\"49) where \"\\<phi>\\<^bold>\\<rightarrow>\\<psi> \\<equiv> \\<lambda>W w. (\\<phi> W w) \\<longrightarrow> (\\<psi> W w)\"  \n abbreviation pequ::\"\\<tau>\\<Rightarrow>\\<tau>\\<Rightarrow>\\<tau>\" (infixr\"\\<^bold>\\<leftrightarrow>\"48) where \"\\<phi>\\<^bold>\\<leftrightarrow>\\<psi> \\<equiv> \\<lambda>W w. (\\<phi> W w) \\<longleftrightarrow> (\\<psi> W w)\"\n abbreviation pknow::\"\\<alpha>\\<Rightarrow>\\<tau>\\<Rightarrow>\\<tau>\" (\"\\<^bold>K_ _\") where \"\\<^bold>K r \\<phi> \\<equiv> \\<lambda>W w.\\<forall>v. (W v \\<and> r w v) \\<longrightarrow> (\\<phi> W v)\"\n abbreviation ppal::\"\\<tau>\\<Rightarrow>\\<tau>\\<Rightarrow>\\<tau>\" (\"\\<^bold>[\\<^bold>!_\\<^bold>]_\") where \"\\<^bold>[\\<^bold>!\\<phi>\\<^bold>]\\<psi> \\<equiv> \\<lambda>W w. (\\<phi> W w) \\<longrightarrow> (\\<psi> (\\<lambda>z. W z \\<and> \\<phi> W z) w)\"\n\n (* Validity of \\<tau>-type lifted PAL formulas *)\n abbreviation pvalid::\"\\<tau> \\<Rightarrow> bool\" (\"\\<^bold>\\<lfloor>_\\<^bold>\\<rfloor>\"[7]8) where \"\\<^bold>\\<lfloor>\\<phi>\\<^bold>\\<rfloor> \\<equiv> \\<forall>W.\\<forall>w. W w \\<longrightarrow> \\<phi> W w\"\n\n (* Agent Knowledge, Mutual Knowledge, Common Knowledge *)\n abbreviation  \"EVR A \\<equiv> \\<^bold>\\<Union> A\"\n abbreviation  \"DIS A \\<equiv> \\<^bold>\\<Inter> A\"\n abbreviation agttknows::\"\\<alpha>\\<Rightarrow>\\<tau>\\<Rightarrow>\\<tau>\" (\"\\<^bold>K\\<^sub>_ _\") where \"\\<^bold>K\\<^sub>r \\<phi> \\<equiv>  \\<^bold>K r \\<phi>\" \n abbreviation evrknows::\"(\\<alpha>\\<Rightarrow>bool)\\<Rightarrow>\\<tau>\\<Rightarrow>\\<tau>\" (\"\\<^bold>E\\<^sub>_ _\") where \"\\<^bold>E\\<^sub>A \\<phi> \\<equiv>  \\<^bold>K (EVR A) \\<phi>\"\n abbreviation prck::\"(\\<alpha>\\<Rightarrow>bool)\\<Rightarrow>\\<tau>\\<Rightarrow>\\<tau>\\<Rightarrow>\\<tau>\" (\"\\<^bold>C\\<^sub>_\\<^bold>\\<lparr>_\\<^bold>|_\\<^bold>\\<rparr>\")\n   where \"\\<^bold>C\\<^sub>A\\<^bold>\\<lparr>\\<phi>\\<^bold>|\\<psi>\\<^bold>\\<rparr> \\<equiv> \\<lambda>W w. \\<forall>v. \\<not>(tc (intersection_rel (EVR A) (\\<lambda>u v. W v \\<and> \\<phi> W v)) w v) \\<or> (\\<psi> W v)\"\n abbreviation pcmn::\"(\\<alpha>\\<Rightarrow>bool)\\<Rightarrow>\\<tau>\\<Rightarrow>\\<tau>\" (\"\\<^bold>C\\<^sub>_ _\") where \"\\<^bold>C\\<^sub>A \\<phi> \\<equiv>  \\<^bold>C\\<^sub>A\\<^bold>\\<lparr>\\<^bold>\\<top>\\<^bold>|\\<phi>\\<^bold>\\<rparr>\"\n abbreviation disknows :: \"(\\<alpha>\\<Rightarrow>bool)\\<Rightarrow>\\<tau>\\<Rightarrow>\\<tau>\" (\"\\<^bold>D\\<^sub>_ _\") where \"\\<^bold>D\\<^sub>A \\<phi> \\<equiv> \\<^bold>K (DIS A) \\<phi>\"\n\n (* Introducing \"Defs\" as the set of the above definitions; useful for convenient unfolding *)\n named_theorems Defs\n declare reflexive_def[Defs] symmetric_def[Defs] transitive_def[Defs] euclidean_def[Defs] \n   intersection_rel_def[Defs] union_rel_def[Defs] sub_rel_def[Defs] inverse_rel_def[Defs] \n   bigunion_rel_def[Defs] tc_def[Defs]\n\n abbreviation \"S5Agent i \\<equiv> reflexive i \\<and> transitive i \\<and> euclidean i\"\n abbreviation \"S5Agents A \\<equiv> \\<forall>i. (A i \\<longrightarrow> S5Agent i)\"\n\n (***********************************************************************************************)\n (*****                         Wise Men Puzzle                                             *****)\n (***********************************************************************************************)\n (*** Encoding of the wise men puzzle in PAL ***)\n (* Agents *)\n consts a::\"\\<alpha>\" b::\"\\<alpha>\" c::\"\\<alpha>\" d::\"\\<alpha>\" (* Agents modeled as accessibility relations *)\n abbreviation  Agent::\"\\<alpha>\\<Rightarrow>bool\" (\"\\<A>\") where \"\\<A> x \\<equiv> x = a \\<or> x = b \\<or> x = c \\<or> x = d\"\n axiomatization where  group_S5: \"S5Agents \\<A>\"\n\n (*** Encoding of the wise men puzzle in PAL ***)\n consts ws::\"\\<alpha>\\<Rightarrow>\\<sigma>\" \n axiomatization where WM1: \"\\<^bold>\\<lfloor>\\<^bold>C\\<^sub>\\<A> (\\<^sup>Aws a \\<^bold>\\<or> \\<^sup>Aws b \\<^bold>\\<or> \\<^sup>Aws c \\<^bold>\\<or> \\<^sup>Aws d)\\<^bold>\\<rfloor>\" \n\n axiomatization where\n   (* Common knowledge: If x not has a white spot then y know this *)\n   WM2ab: \"\\<^bold>\\<lfloor>\\<^bold>C\\<^sub>\\<A> (\\<^bold>\\<not>(\\<^sup>Aws a) \\<^bold>\\<rightarrow> (\\<^bold>K\\<^sub>b (\\<^bold>\\<not>(\\<^sup>Aws a))))\\<^bold>\\<rfloor>\" and\n   WM2ac: \"\\<^bold>\\<lfloor>\\<^bold>C\\<^sub>\\<A> (\\<^bold>\\<not>(\\<^sup>Aws a) \\<^bold>\\<rightarrow> (\\<^bold>K\\<^sub>c (\\<^bold>\\<not>(\\<^sup>Aws a))))\\<^bold>\\<rfloor>\" and\n   WM2ad: \"\\<^bold>\\<lfloor>\\<^bold>C\\<^sub>\\<A> (\\<^bold>\\<not>(\\<^sup>Aws a) \\<^bold>\\<rightarrow> (\\<^bold>K\\<^sub>d (\\<^bold>\\<not>(\\<^sup>Aws a))))\\<^bold>\\<rfloor>\" and\n   WM2ba: \"\\<^bold>\\<lfloor>\\<^bold>C\\<^sub>\\<A> (\\<^bold>\\<not>(\\<^sup>Aws b) \\<^bold>\\<rightarrow> (\\<^bold>K\\<^sub>a (\\<^bold>\\<not>(\\<^sup>Aws b))))\\<^bold>\\<rfloor>\" and\n   WM2bc: \"\\<^bold>\\<lfloor>\\<^bold>C\\<^sub>\\<A> (\\<^bold>\\<not>(\\<^sup>Aws b) \\<^bold>\\<rightarrow> (\\<^bold>K\\<^sub>c (\\<^bold>\\<not>(\\<^sup>Aws b))))\\<^bold>\\<rfloor>\" and\n   WM2bd: \"\\<^bold>\\<lfloor>\\<^bold>C\\<^sub>\\<A> (\\<^bold>\\<not>(\\<^sup>Aws b) \\<^bold>\\<rightarrow> (\\<^bold>K\\<^sub>d (\\<^bold>\\<not>(\\<^sup>Aws b))))\\<^bold>\\<rfloor>\" and\n   WM2ca: \"\\<^bold>\\<lfloor>\\<^bold>C\\<^sub>\\<A> (\\<^bold>\\<not>(\\<^sup>Aws c) \\<^bold>\\<rightarrow> (\\<^bold>K\\<^sub>a (\\<^bold>\\<not>(\\<^sup>Aws c))))\\<^bold>\\<rfloor>\" and\n   WM2cb: \"\\<^bold>\\<lfloor>\\<^bold>C\\<^sub>\\<A> (\\<^bold>\\<not>(\\<^sup>Aws c) \\<^bold>\\<rightarrow> (\\<^bold>K\\<^sub>b (\\<^bold>\\<not>(\\<^sup>Aws c))))\\<^bold>\\<rfloor>\" and\n   WM2cd: \"\\<^bold>\\<lfloor>\\<^bold>C\\<^sub>\\<A> (\\<^bold>\\<not>(\\<^sup>Aws c) \\<^bold>\\<rightarrow> (\\<^bold>K\\<^sub>d (\\<^bold>\\<not>(\\<^sup>Aws c))))\\<^bold>\\<rfloor>\" and\n   WM2da: \"\\<^bold>\\<lfloor>\\<^bold>C\\<^sub>\\<A> (\\<^bold>\\<not>(\\<^sup>Aws d) \\<^bold>\\<rightarrow> (\\<^bold>K\\<^sub>a (\\<^bold>\\<not>(\\<^sup>Aws d))))\\<^bold>\\<rfloor>\" and\n   WM2db: \"\\<^bold>\\<lfloor>\\<^bold>C\\<^sub>\\<A> (\\<^bold>\\<not>(\\<^sup>Aws d) \\<^bold>\\<rightarrow> (\\<^bold>K\\<^sub>b (\\<^bold>\\<not>(\\<^sup>Aws d))))\\<^bold>\\<rfloor>\" and\n   WM2dc: \"\\<^bold>\\<lfloor>\\<^bold>C\\<^sub>\\<A> (\\<^bold>\\<not>(\\<^sup>Aws d) \\<^bold>\\<rightarrow> (\\<^bold>K\\<^sub>c (\\<^bold>\\<not>(\\<^sup>Aws d))))\\<^bold>\\<rfloor>\" \n\n\n (* Automated solutions of the Wise Men Puzzle with 4 Agents*)\n\n theorem whitespot_c_1: \"\\<^bold>\\<lfloor>\\<^bold>[\\<^bold>!\\<^bold>\\<not>\\<^bold>K\\<^sub>a(\\<^sup>Aws a)\\<^bold>](\\<^bold>[\\<^bold>!\\<^bold>\\<not>\\<^bold>K\\<^sub>b(\\<^sup>Aws b)\\<^bold>](\\<^bold>[\\<^bold>!\\<^bold>\\<not>\\<^bold>K\\<^sub>c(\\<^sup>Aws c)\\<^bold>](\\<^bold>K\\<^sub>d (\\<^sup>Aws d))))\\<^bold>\\<rfloor>\" \n   using WM1 WM2ba WM2ca WM2cb WM2da WM2db WM2dc\n   unfolding Defs \n   by (smt (verit)) \n\n theorem whitespot_c_2: \n     \"\\<^bold>\\<lfloor>\\<^bold>[\\<^bold>!\\<^bold>\\<not>((\\<^bold>K\\<^sub>a (\\<^sup>Aws a)) \\<^bold>\\<or> (\\<^bold>K\\<^sub>a (\\<^bold>\\<not>\\<^sup>Aws a)))\\<^bold>](\\<^bold>[\\<^bold>!\\<^bold>\\<not>((\\<^bold>K\\<^sub>b (\\<^sup>Aws b)) \\<^bold>\\<or> (\\<^bold>K\\<^sub>b (\\<^bold>\\<not>\\<^sup>Aws b)))\\<^bold>](\\<^bold>[\\<^bold>!\\<^bold>\\<not>((\\<^bold>K\\<^sub>c (\\<^sup>Aws c)) \\<^bold>\\<or> (\\<^bold>K\\<^sub>c (\\<^bold>\\<not>\\<^sup>Aws c)))\\<^bold>](\\<^bold>K\\<^sub>d (\\<^sup>Aws d))))\\<^bold>\\<rfloor>\" \n   using whitespot_c_1\n   unfolding Defs sledgehammer[verbose]()\n   oops\n\n (* Consistency confirmed by nitpick *)\n lemma True nitpick [satisfy] oops  (* model found *)\n\nend", "meta": {"author": "cbenzmueller", "repo": "LogiKEy", "sha": "5c16bdeb68bf8131e24ba9c8d774d4af663cb2cf", "save_path": "github-repos/isabelle/cbenzmueller-LogiKEy", "path": "github-repos/isabelle/cbenzmueller-LogiKEy/LogiKEy-5c16bdeb68bf8131e24ba9c8d774d4af663cb2cf/Public-Announcement-Logic/PALandWiseMenPuzzle2021_4Agents.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513786759492, "lm_q2_score": 0.7981867801399695, "lm_q1q2_score": 0.7153760021413643}}
{"text": "(*<*)\n\\<comment>\\<open> ******************************************************************** \n * Project         : AGM Theory\n * Version         : 1.0\n *\n * Authors         : Valentin Fouillard, Safouan Taha, Frederic Boulanger\n                     and Nicolas Sabouret\n *\n * This file       : AGM Remainders\n *\n * Copyright (c) 2021 Universit\u00e9 Paris Saclay, France\n *\n ******************************************************************************\\<close>\n\ntheory AGM_Remainder\n\nimports AGM_Logic\n\nbegin\n\n(*>*)\n\n\n\nsection \\<open>Remainders\\<close>\n\ntext\\<open>In AGM, one important feature is to eliminate some proposition from a set of propositions by ensuring \nthat the set of retained clauses is maximal and that nothing among these clauses allows to retrieve the eliminated proposition\\<close>\n\nsubsection \\<open>Remainders in a Tarskian logic\\<close>\ntext \\<open>In a general context of a Tarskian logic, we consider a descriptive definition (by comprehension)\\<close>\ncontext Tarskian_logic\n\nbegin\ndefinition remainder::\\<open>'a set \\<Rightarrow> 'a \\<Rightarrow> 'a set set\\<close> (infix \\<open>.\\<bottom>.\\<close> 55)\n  where rem: \\<open>A .\\<bottom>. \\<phi> \\<equiv> {B. B \\<subseteq> A \\<and> \\<not> B \\<turnstile> \\<phi> \\<and> (\\<forall>B'\\<subseteq> A. B \\<subset> B' \\<longrightarrow> B' \\<turnstile> \\<phi>)}\\<close> \n\nlemma rem_inclusion: \\<open>B \\<in> A .\\<bottom>. \\<phi> \\<Longrightarrow> B \\<subseteq> A\\<close> \n  by (auto simp add:rem split:if_splits) \n\nlemma rem_closure: \"K = Cn(A) \\<Longrightarrow> B \\<in> K .\\<bottom>. \\<phi> \\<Longrightarrow> B = Cn(B)\"\n  apply(cases \\<open>K .\\<bottom>. \\<phi> = {}\\<close>, simp)\n  by (simp add:rem infer_def) (metis idempotency_L inclusion_L monotonicity_L psubsetI)\n\nlemma remainder_extensionality: \\<open>Cn({\\<phi>}) = Cn({\\<psi>}) \\<Longrightarrow> A .\\<bottom>. \\<phi> = A .\\<bottom>. \\<psi>\\<close> \n  unfolding rem infer_def apply safe \n  by (simp_all add: Cn_same) blast+\n\nlemma nonconsequence_remainder: \\<open>A .\\<bottom>. \\<phi> = {A} \\<longleftrightarrow> \\<not> A \\<turnstile> \\<phi>\\<close>\n  unfolding rem by auto                           \n\n\\<comment> \\<open>As we will see further, the other direction requires compactness!\\<close>\nlemma taut2emptyrem: \\<open>\\<tturnstile> \\<phi> \\<Longrightarrow> A .\\<bottom>. \\<phi> = {}\\<close>\n  unfolding rem by (simp add: infer_def validD_L)\n\nend\n\nsubsection \\<open>Remainders in a supraclassical logic\\<close>\ntext\\<open>In case of a supraclassical logic, remainders get impressive properties\\<close>\ncontext Supraclassical_logic\n\nbegin\n\n\\<comment> \\<open>As an effect of being maximal, a remainder keeps the eliminated proposition in its propositions hypothesis\\<close>\nlemma remainder_recovery: \\<open>K = Cn(A) \\<Longrightarrow> K \\<turnstile> \\<psi> \\<Longrightarrow> B \\<in> K .\\<bottom>. \\<phi> \\<Longrightarrow> B \\<turnstile> \\<phi> .\\<longrightarrow>. \\<psi>\\<close> \nproof -\n  { fix \\<psi> and B\n    assume  a:\\<open>K = Cn(A)\\<close> and c:\\<open>\\<psi> \\<in> K\\<close> and d:\\<open>B \\<in> K .\\<bottom>. \\<phi>\\<close> and e:\\<open>\\<phi> .\\<longrightarrow>. \\<psi> \\<notin> Cn(B)\\<close>\n    with a have f:\\<open>\\<phi> .\\<longrightarrow>. \\<psi> \\<in> K\\<close> using impI2 infer_def by blast\n    with d e have \\<open>\\<phi> \\<in> Cn(B \\<union> {\\<phi> .\\<longrightarrow>. \\<psi>})\\<close> \n      apply (simp add:rem, elim conjE)\n      by (metis dual_order.order_iff_strict inclusion_L insert_subset)\n    with d have False using rem imp_recovery1 \n      by (metis (no_types, lifting) CollectD infer_def)\n  }\n  thus \\<open>K = Cn(A) \\<Longrightarrow> K \\<turnstile> \\<psi> \\<Longrightarrow> B \\<in> K .\\<bottom>. \\<phi> \\<Longrightarrow> B \\<turnstile> \\<phi> .\\<longrightarrow>. \\<psi>\\<close>\n    using idempotency_L by auto\nqed\n\n\\<comment> \\<open>When you remove some proposition \\<open>\\<phi>\\<close> several other propositions can be lost. \nAn important lemma states that the resulting remainder is also a remainder of any lost proposition\\<close>\nlemma remainder_recovery_bis: \\<open>K = Cn(A) \\<Longrightarrow> K \\<turnstile> \\<psi> \\<Longrightarrow> \\<not> B \\<turnstile> \\<psi> \\<Longrightarrow> B \\<in> K .\\<bottom>. \\<phi> \\<Longrightarrow> B \\<in> K .\\<bottom>. \\<psi>\\<close>\nproof-\n  assume a:\\<open>K = Cn(A)\\<close> and b:\\<open>\\<not> B \\<turnstile> \\<psi>\\<close> and c:\\<open>B \\<in> K .\\<bottom>. \\<phi>\\<close> and d:\\<open>K \\<turnstile> \\<psi>\\<close>\n  hence d:\\<open>B \\<turnstile> \\<phi> .\\<longrightarrow>. \\<psi>\\<close> using remainder_recovery by simp\n  with c show \\<open>B \\<in> K .\\<bottom>. \\<psi>\\<close>\n    by (simp add:rem) (meson b dual_order.trans infer_def insert_subset monotonicity_L mp_PL order_refl psubset_imp_subset)\nqed\n\ncorollary remainder_recovery_imp: \\<open>K = Cn(A) \\<Longrightarrow> K \\<turnstile> \\<psi> \\<Longrightarrow> \\<tturnstile> (\\<psi> .\\<longrightarrow>. \\<phi>) \\<Longrightarrow> B \\<in> K .\\<bottom>. \\<phi> \\<Longrightarrow> B \\<in> K .\\<bottom>. \\<psi>\\<close>\n  apply(rule remainder_recovery_bis, simp_all)\n  by (simp add:rem) (meson infer_def mp_PL validD_L)\n\n\\<comment> \\<open>If we integrate back the eliminated proposition into the remainder, we retrieve the original set!\\<close>\nlemma remainder_expansion: \\<open>K = Cn(A) \\<Longrightarrow> K \\<turnstile> \\<psi> \\<Longrightarrow> \\<not> B \\<turnstile> \\<psi> \\<Longrightarrow> B \\<in> K .\\<bottom>. \\<phi> \\<Longrightarrow> B \\<oplus> \\<psi> = K\\<close>\nproof \n  assume a:\\<open>K = Cn(A)\\<close> and b:\\<open>K \\<turnstile> \\<psi>\\<close> and c:\\<open>\\<not> B \\<turnstile> \\<psi>\\<close> and d:\\<open>B \\<in> K .\\<bottom>. \\<phi>\\<close>\n  then show \\<open>B \\<oplus> \\<psi> \\<subseteq> K\\<close>\n    by (metis Un_insert_right expansion_def idempotency_L infer_def insert_subset \n              monotonicity_L rem_inclusion sup_bot.right_neutral)\nnext\n  assume a:\\<open>K = Cn(A)\\<close> and b:\\<open>K \\<turnstile> \\<psi>\\<close> and c:\\<open>\\<not> B \\<turnstile> \\<psi>\\<close> and d:\\<open>B \\<in> K .\\<bottom>. \\<phi>\\<close>\n  { fix \\<chi>\n    assume \\<open>\\<chi> \\<in> K\\<close>\n    hence e:\\<open>B \\<turnstile> \\<phi> .\\<longrightarrow>.\\<chi>\\<close> using remainder_recovery[OF a _ d, of \\<chi>] assumption_L by blast \n    have \\<open>\\<psi> \\<in> K\\<close> using a b idempotency_L infer_def by blast\n    hence f:\\<open>B \\<union> {\\<psi>} \\<turnstile> \\<phi>\\<close> using b c d apply(simp add:rem)\n      by (meson inclusion_L insert_iff insert_subsetI less_le_not_le subset_iff) \n    from e f have \\<open>B \\<union> {\\<psi>} \\<turnstile> \\<chi>\\<close> using imp_PL imp_trans by blast\n  }\n  then show \\<open>K \\<subseteq> B \\<oplus> \\<psi>\\<close> \n    by (simp add: expansion_def subsetI)\nqed\n\ntext\\<open>To eliminate a conjunction, we only need to remove one side\\<close>\nlemma remainder_conj: \\<open>K = Cn(A) \\<Longrightarrow> K \\<turnstile> \\<phi> .\\<and>. \\<psi> \\<Longrightarrow> K .\\<bottom>. (\\<phi> .\\<and>. \\<psi>) = (K .\\<bottom>. \\<phi>) \\<union> (K .\\<bottom>. \\<psi>)\\<close>\n  apply(intro subset_antisym Un_least subsetI, simp add:rem)\n    apply (meson conj_PL infer_def)\n   using remainder_recovery_imp[of K A \\<open>\\<phi> .\\<and>. \\<psi>\\<close> \\<phi>] \n   apply (meson assumption_L conjE1_PL singletonI subsetI valid_imp_PL)\n  using remainder_recovery_imp[of K A \\<open>\\<phi> .\\<and>. \\<psi>\\<close> \\<psi>]\n  by (meson assumption_L conjE2_PL singletonI subsetI valid_imp_PL)\n\nend\n\nsubsection \\<open>Remainders in a compact logic\\<close>\ntext\\<open>In case of a supraclassical logic, remainders get impressive properties\\<close>\ncontext Compact_logic\nbegin\n\ntext \\<open>The following lemma is the Lindembaum's lemma requiring the Zorn's lemma (already available in standard Isabelle/HOL). \n  For more details, please refer to the book \"Theory of logical calculi\" \\<^cite>\\<open>wojcicki2013theory\\<close>. \nThis very important lemma states that we can get a maximal set (remainder \\<open>B'\\<close>) starting from any set \n\\<open>B\\<close> if this latter does not infer the proposition \\<open>\\<phi>\\<close> we want to eliminate\\<close>\nlemma upper_remainder: \\<open>B \\<subseteq> A \\<Longrightarrow> \\<not> B \\<turnstile> \\<phi> \\<Longrightarrow> \\<exists>B'. B \\<subseteq> B' \\<and>  B' \\<in> A .\\<bottom>. \\<phi>\\<close> \nproof -\n  assume a:\\<open>B \\<subseteq> A\\<close> and b:\\<open>\\<not> B \\<turnstile> \\<phi>\\<close>\n  have c:\\<open>\\<not> \\<tturnstile> \\<phi>\\<close>\n    using b infer_def validD_L by blast\n  define \\<B> where \"\\<B> \\<equiv> {B'. B \\<subseteq> B' \\<and> B' \\<subseteq> A \\<and> \\<not> B' \\<turnstile> \\<phi>}\"\n  have d:\\<open>subset.chain \\<B> C \\<Longrightarrow> subset.chain {B. \\<not> B \\<turnstile> \\<phi>} C\\<close> for C\n    unfolding \\<B>_def\n    by (simp add: le_fun_def less_eq_set_def subset_chain_def)\n  have e:\\<open>C \\<noteq> {} \\<Longrightarrow> subset.chain \\<B> C \\<Longrightarrow> B \\<subseteq> \\<Union> C\\<close> for C \n    by (metis (no_types, lifting) \\<B>_def subset_chain_def less_eq_Sup mem_Collect_eq subset_iff)\n  { fix C\n    assume f:\\<open>C \\<noteq> {}\\<close> and g:\\<open>subset.chain \\<B> C\\<close> \n    have \\<open>\\<Union> C \\<in> \\<B>\\<close>\n      using \\<B>_def  e[OF f g] chain_closure[OF c d[OF g]] \n      by simp (metis (no_types, lifting) CollectD Sup_least Sup_subset_mono g subset.chain_def subset_trans)\n  } note f=this \n  have \\<open>subset.chain \\<B> C \\<Longrightarrow> \\<exists>U\\<in>\\<B>. \\<forall>X\\<in>C. X \\<subseteq> U\\<close> for C\n    apply (cases \\<open>C \\<noteq> {}\\<close>) \n     apply (meson Union_upper f) \n    using \\<B>_def a b by blast\n  with subset_Zorn[OF this, simplified] obtain B' where f:\\<open>B'\\<in> \\<B> \\<and> (\\<forall>X\\<in>\\<B>. B' \\<subseteq> X \\<longrightarrow> X = B')\\<close> by auto\n  then show ?thesis \n    by (simp add:rem \\<B>_def, rule_tac x=B' in exI) (metis psubsetE subset_trans)\nqed\n\n\\<comment> \\<open>An immediate corollary ruling tautologies\\<close>\ncorollary emptyrem2taut: \\<open>A .\\<bottom>. \\<phi> = {} \\<Longrightarrow> \\<tturnstile> \\<phi>\\<close>\n  by (metis bot.extremum empty_iff upper_remainder valid_def)\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/Belief_Revision/AGM_Remainder.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.877476784277755, "lm_q2_score": 0.8152324938410784, "lm_q1q2_score": 0.7153475871344042}}
{"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_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 lt :: \"Nat => Nat => bool\" where\n\"lt y (Z) = False\"\n| \"lt (Z) (S z2) = True\"\n| \"lt (S n) (S z2) = lt n z2\"\n\n(*fun did not finish the proof*)\nfunction mod2 :: \"Nat => Nat => Nat\" where\n\"mod2 y (Z) = Z\"\n| \"mod2 y (S z2) =\n     (if lt y (S z2) then y else mod2 (minus y (S z2)) (S z2))\"\nby pat_completeness auto\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 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 (mod2 n (length xs)) xs) (take (mod2 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_mod.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206844384594, "lm_q2_score": 0.7931059560743422, "lm_q1q2_score": 0.7153186667347894}}
{"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_TSortSorts\nimports \"../../Test_Base\"\nbegin\n\ndatatype 'a list = nil2 | cons2 \"'a\" \"'a list\"\n\ndatatype Tree = TNode \"Tree\" \"int\" \"Tree\" | TNil\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 flatten :: \"Tree => int list => int list\" where\n\"flatten (TNode p z q) y = flatten p (cons2 z (flatten q y))\"\n| \"flatten (TNil) y = y\"\n\nfun add :: \"int => Tree => Tree\" where\n\"add x (TNode p z q) =\n   (if x <= z then TNode (add x p) z q else TNode p z (add x q))\"\n| \"add x (TNil) = TNode TNil x TNil\"\n\nfun toTree :: \"int list => Tree\" where\n\"toTree (nil2) = TNil\"\n| \"toTree (cons2 y xs) = add y (toTree xs)\"\n\nfun tsort :: \"int list => int 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_TSortSorts.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206738932334, "lm_q2_score": 0.7931059536292271, "lm_q1q2_score": 0.715318656166008}}
{"text": "theory Chapter3Sols\nimports Main Chapter3Defs\nbegin\n\n(*  Exercise 3.1  *)\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(* not complete *)\n\n(*  Exercise 3.2  *)\ninductive palindrome:: \"'a list \\<Rightarrow> bool\" where\nemptyP: \"palindrome []\" |\nsinglP: \"palindrome [x]\" |\nindctP: \"palindrome xs \\<Longrightarrow> palindrome(a # xs @ [a])\"\n\nlemma \"palindrome xs \\<Longrightarrow> rev xs = xs\"\n  apply(induction xs rule: palindrome.induct)\n    apply(simp_all)\n  done\n\n(*  Exercise 3.3  *)\n(* not complete *)\n\n(*  Exercise 3.4  *)\n(* not complete *)\n\n(*  Exercise 3.5  *)\n(* Adapted from: https://isabelle.in.tum.de/exercises/logic/parentheses/sol.pdf *)\ndatatype alpha = a | b\n\ninductive S:: \"alpha list \\<Rightarrow> bool\" where\nS1: \"S []\" |\nS2: \"S [v] \\<Longrightarrow> S (a # [v] @ [b])\" |\nS3: \"S [v] \\<Longrightarrow> S [w] \\<Longrightarrow> S([v] @ [w])\"\n\ndeclare S1 [iff] S2 [intro!, simp]\n\ninductive T:: \"alpha list \\<Rightarrow> bool\" where\nT1: \"T []\" |\nT2: \"T [v] \\<Longrightarrow> T[w] \\<Longrightarrow> T([v] @ a # [w] @ [b])\"\n\ndeclare T1 [iff]\n\nlemma T2S:\"T w \\<Longrightarrow> S w\"\n  apply(erule T.induct)\n   apply(simp)\n  (* found by sledgehammer *)\n  using S.cases by auto\n\nlemma S2T:\"S w \\<Longrightarrow> T w\"\n  apply(erule S.induct)\n    apply(simp)\n  (* found by sledgehammer *)\n  using S.cases by auto\n\nlemma \"S w == T w\"\n  by (smt (verit) S2T T2S)\n  \nend", "meta": {"author": "mrtkp9993", "repo": "Isabelle-HOL-Examples", "sha": "37a31d2aefce20eb5c49d358c1ea236f5e693458", "save_path": "github-repos/isabelle/mrtkp9993-Isabelle-HOL-Examples", "path": "github-repos/isabelle/mrtkp9993-Isabelle-HOL-Examples/Isabelle-HOL-Examples-37a31d2aefce20eb5c49d358c1ea236f5e693458/Programming and Proving in Isabelle-Hol Exercise Solutions/Chapter3Sols.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117940706735, "lm_q2_score": 0.8652240773641087, "lm_q1q2_score": 0.7152909492708255}}
{"text": "theory Ex3_2\n  imports Main \nbegin \n  \n  \nprimrec sq :: \"nat \\<Rightarrow> nat\" where \n  \"sq 0 = 0\"|\n  \"sq (Suc n) = sq n + n + (Suc n)\"\n  \ntheorem \"sq n = n * n\" by (induction n ; simp)\n    \n    \ndefinition mm2 ::\"nat \\<Rightarrow> nat \\<Rightarrow> nat\" where \n  \"mm2 base value \\<equiv> let diff = value - base ; qdiff = diff * diff in (value + diff)  * base + qdiff\"\n  \ndeclare mm2_def [simp]  \n  \n\n  \ntheorem \" n \\<le> m   \\<Longrightarrow>  mm2 n m = m * m\" \nproof (induction n arbitrary : m)\n  case 0\n  then show ?case by simp\nnext\n  case (Suc n)\n  assume hyp:\"\\<And>m . n \\<le> m \\<Longrightarrow> mm2 n m = m * m\"\n    and hyp2:\"Suc n \\<le> m\"\n  then show ?case \n  proof (cases \"m = 0\")\n    case True\n    then show ?thesis using hyp2 by simp\n  next\n    case False\n      assume c1:\"m \\<noteq> 0\"\n      \n    from hyp[of \"m - 1\"] hyp2 have tmp':\"mm2 n (m - 1) = (m - 1) * (m - 1)\" by simp\n      \n    have \"mm2 n (m - 1) = (let diff = (m-1) - n ; qdiff = diff * diff in ((m - 1) + diff)  * n + qdiff)\" by simp\n    also have \" \\<dots> = ((m - 1) + ((m - 1) - n)) * n + ((m -1) -n)* ((m - 1) -n)\"  by (simp only : Let_def)\n    also have \"\\<dots> = (m - 1 + (m  - Suc n)) * n + (m - Suc n)* (m  - Suc n)\" by simp\n    also have \"\\<dots> = (m - 1) * n + (m - Suc n)* n + (m - Suc n) * (m - Suc n)\" using distrib_right by simp\n    finally have tmp:\"mm2 n (m - 1) =  (m - 1) * n + (m - Suc n)* n + (m - Suc n) * (m - Suc n)\"  by assumption\n\n    have tmp2:\"m * m = m + (m - 1) + (m - 1) * (m - 1)\" by (induction m; simp)\n     \n    have \"mm2 (Suc n) m =(let diff = m - (Suc n) ; qdiff = diff * diff in (m + diff)  * (Suc n) + qdiff)\" by simp\n    also have \"\\<dots> = (m + (m- (Suc n))) * (Suc n) + (m - Suc n) * (m - Suc n)\" by (simp only : Let_def) \n    also have \"\\<dots> = (m + m- (Suc n)) * (Suc n) + (m - Suc n) * (m - Suc n)\" using hyp2 by simp\n    also have \"\\<dots> = (m + m - (Suc n)) + (m + m - (Suc n))* n + (m - Suc n) * (m - Suc n)\" by simp\n    also have \"\\<dots> = m + (m - 1) - n + (m + m - (Suc n))* n + (m - Suc n) * (m - Suc n)\" by simp\n    also have \"\\<dots> = m + (m - 1) - n + (m + (m - (Suc n)))* n + (m - Suc n) * (m - Suc n)\" using hyp2 by simp\n    also have \"\\<dots> = m + (m - 1) - n + m * n + (m - (Suc n))* n + (m - Suc n) * (m - Suc n) \" by (simp add: distrib_right)\n    also have \"\\<dots> =  m + (m - 1) +m * n - n + (m - (Suc n))* n + (m - Suc n) * (m - Suc n) \" using Suc_leD hyp2 le_add1 order_trans ordered_cancel_comm_monoid_diff_class.add_diff_assoc2 by simp\n    also have \"\\<dots> =  m + (m - 1) + (m  - 1)*n + (m - (Suc n))* n + (m - Suc n) * (m - Suc n)\" by (simp add: c1 algebra_simps mult_eq_if)\n    finally have tmp3:\"mm2 (Suc n) m = m + (m - 1) + (m  - 1)*n + (m - (Suc n))* n + (m - Suc n) * (m - Suc n)\" by assumption\n    show ?thesis using tmp tmp2 tmp3 tmp' by simp\n  qed    \nqed\n  \nlemma helper : \"m \\<le> n \\<longrightarrow> sq n =  ((n + (n - m)) * m)  + sq (n - m)\"\nproof (induction n arbitrary : m)\n  case 0\n  then show ?case by simp\nnext\n  case (Suc n)\n  then show ?case by (cases m ; simp)\nqed\n  \ntheorem \"100 \\<le> n \\<Longrightarrow> sq n =  ((n + (n - 100)) * 100)  + sq (n - 100)\"using helper by (induction n; simp)\n\n\ndefinition \"eq1 (n::nat) = (n -5)*(n-5 + 10) + 25\" \ndefinition \"eq2 (n::nat) = (n div 10 )* (n div 10 + 1) * 100 + 25\"\n\n\nlemma helper2:\"(n::nat) mod 10 = 5 \\<Longrightarrow>  n div 10 * 10 = n - 5\" by (metis minus_mod_eq_div_mult)\n\ntheorem \"(n::nat) mod 10 = 5 \\<Longrightarrow>  n*n  = (n div 10 )* (n div 10 + 1) * 100 + 25\" \nproof -\n  assume hyp:\"n mod 10 = 5\"\n  hence tmp:\"5 \\<le> n\" by simp\n\n\n  from tmp have tmp2:\"(n - 5)*(n - 5) = n*n + 25 - 10*n\" \n  proof (induction n)\n    case 0\n    then show ?case by simp\n  next\n    case (Suc n)\n    assume hyp1:\"5 \\<le> n \\<Longrightarrow> (n - 5) * (n - 5) = n * n + 25 - 10 * n\"\n       and hyp2:\"5 \\<le> Suc n\"\n    then show ?case \n    proof (cases \"n = 4\")\n      case True\n      then show ?thesis by simp \n    next\n      case False\n      assume c1:\"n \\<noteq> 4\"\n      with hyp2 have tmp:\"5 \\<le> n\" by simp\n      with hyp1 have tmp2:\" (n - 5) * (n - 5) = n * n + 25 - 10 * n\" by simp\n\n      have tmp3:\"Suc n - 5 = Suc (n - 5)\" \n      proof -\n        have \"Suc n - 5 = 1 + n - 5\" by simp\n        also have \"\\<dots> = 1+ (n - 5)\" using tmp by simp\n        also have \"\\<dots> = Suc (n - 5)\" by simp\n        finally show ?thesis by assumption\n      qed\n\n      from tmp have h:\"n * n + 25 \\<ge> n*10\" \n      proof  (induction n)\n        case 0\n        then show ?case by simp\n      next\n        case (Suc n)\n        assume a:\"5 \\<le> n \\<Longrightarrow> n * 10 \\<le> n * n + 25\"\n           and b:\"5 \\<le> Suc n\"\n        then show ?case\n        proof (cases \"n = 4\")\n          case True\n          then show ?thesis by simp\n        next\n          case False\n          with b have c:\"5 \\<le> n\" by simp\n          with a have d:\"n * 10 \\<le> n * n + 25\" by simp\n          have \"Suc n + n  > 10\" using c by simp\n          with c d show ?thesis by simp\n        qed\n      qed\n\n      have \"(Suc n - 5) * (Suc n - 5) =  (n + 1 - 5)* ( n + 1 - 5)\" using hyp2 by simp\n      also have \"\\<dots> = Suc n * Suc n + 25 - 10*Suc n\" using tmp tmp2 tmp3 algebra_simps h by simp\n      finally show ?thesis by assumption\n    qed\n  qed\n\n  from tmp have tmp3:\"n*n + 25 \\<ge> 10*n\" \n  proof (induction n)\n    case 0\n    then show ?case by simp\n  next\n    case (Suc n)\n    assume a:\"5 \\<le> n \\<Longrightarrow> 10 * n \\<le> n * n + 25\"\n       and b:\"5 \\<le> Suc n\"\n    then show ?case \n    proof (cases \"n = 4\")\n      case True\n      then show ?thesis by simp\n    next\n      case False\n      assume c:\"n \\<noteq>4\"\n      from c and b have d:\"5 \\<le> n\" by simp\n      with a have e:\"10 * n \\<le> n * n + 25\" by simp\n      have \"Suc n + n \\<ge> 10\" using d by simp \n      with d e show ?thesis by simp\n    qed\n  qed\n\n  from tmp have tmp4:\"n*n \\<ge> 25\" \n  proof (induction n )\n    case 0\n    then show ?case by simp\n  next\n    case (Suc n)\n    assume a:\"5 \\<le> n \\<Longrightarrow> 25 \\<le> n * n\"\n       and b:\"5 \\<le> Suc n\"\n    then show ?case \n    proof (cases \"n = 4\")\n      case True\n      then show ?thesis by simp\n    next\n      case False\n      with b have \"5 \\<le> n\" by simp\n      with a have \"25 \\<le> n*n\" by simp\n      then show ?thesis by simp\n    qed\n  qed\n\n  have \"(n div 10 )* (n div 10 + 1) * 100 + 25 = (n div 10 )*  Suc (n div 10 ) * 100 + 25\" by simp\n  also have \"\\<dots> = n div 10 * 10 *10 + (n div 10 )*  (n div 10 ) * 100 + 25 \" using algebra_simps  by simp\n  also have \"\\<dots> = (n - 5 ) *10 + (n div 10 ) * (n div 10  ) * 10  * 10 + 25\" using hyp  by (simp add : helper2 )\n  also have \"\\<dots> = (n - 5 ) *10 + (n div 10  * 10)  * (n div 10 * 10)   + 25\" by simp\n  also have \"\\<dots> = n*n + 10*n -25 - 10*n + 25\" using tmp tmp3 tmp2 hyp helper2 algebra_simps by simp\n  also have \"\\<dots> = n*n \" using tmp4 by simp\n  finally show ?thesis by (rule sym)\nqed\n\n\ntheorem \"sq((10 * n) + 5) = ((n * (Suc n)) * 100) + 25\" \nproof (induction n)\ncase 0\n  then show ?case by (simp add : sq_def)\nnext\n  case (Suc n)\n  then show ?case by (simp add: sq_def algebra_simps)\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/3. Arithmetic/Ex3_2.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094174159127, "lm_q2_score": 0.8006920116079209, "lm_q1q2_score": 0.7152657144190471}}
{"text": "theory Alg_Varieties_Theory\n  imports Field_Theory \n\n\nbegin\n\n(* We formalize below our blueprint, first with n=1, but this should be generalized. \nIf n=1 then the affine space is just carrier k. *)\n\ncontext field\nbegin\n\n(* def. 0.0.3 *)\ndefinition zero_set :: \"('a upoly) set \\<Rightarrow> 'a set\"\n  where \"zero_set T \\<equiv> {p \\<in> R. \\<forall>f\\<in>T. eval_poly f p = \\<zero>}\"\n\n(* def 0.0.4 *)\ndefinition algebraic :: \"'a set \\<Rightarrow> bool\"\n  where \"algebraic Y \\<equiv> (\\<exists>T. Y = zero_set T)\"\n\n(* exercise 0.0.5 *)\nlemma empty_set_is_algebraic:\n  shows \"algebraic empty\" sorry\n\nlemma whole_space_is_algebraic:\n  shows \"algebraic R\" \n  by (auto simp: algebraic_def zero_set_def)\n\n(* exercise 0.0.6 *)\nlemma inter_of_alg_family_is_algebraic:\n  fixes f :: \"'a set set\"\n  assumes \"Y \\<in> f \\<Longrightarrow> algebraic Y\"\n  shows \"algebraic (\\<Inter>f)\" sorry\n\n(* exercise 0.0.7 *)\nlemma union_of_two_algebraic_is_algebraic:\n  assumes \"algebraic Y\" and \"algebraic Z\"\n  shows \"algebraic (Y \\<union> Z)\" sorry\n\n(* def. 0.0.8 *)\ndefinition zariski_open :: \"'a set \\<Rightarrow> bool\"\n  where \"zariski_open S = (\\<exists>Y. algebraic Y \\<and> S = R - Y)\"\n\n(* exercise 0.0.9 *)\nlemma zariski_topology_is_topology:\n  shows \"istopology zariski_open\" sorry\n\ndefinition  zariski_closed :: \"'a set \\<Rightarrow> bool\"\n  where \"zariski_closed S \\<equiv> zariski_open (R - S)\"\n\n(* def. 0.0.10 *)\ndefinition irreducible :: \"'a set \\<Rightarrow> bool\"\n  where \"irreducible S \\<equiv> S \\<subseteq> R \\<and> S \\<noteq> empty \\<and> \\<not>(\\<exists>U V. S = U \\<union> V \\<and> zariski_closed U \\<and> \nzariski_closed V \\<and> U \\<subset> R \\<and> V \\<subset> R)\"\n\n(* def 0.0.11 *)\ndefinition aff_alg_variety :: \"'a set \\<Rightarrow> bool\"\n  where \"aff_alg_variety S \\<equiv> irreducible S \\<and> zariski_closed S\"\n\n(* def 0.0.12 *)\ndefinition quasi_aff_variety :: \"'a set \\<Rightarrow> bool\"\n  where \"quasi_aff_variety U \\<equiv> \\<exists>S Y. aff_alg_variety S \\<and> zariski_open Y \\<and> U = S \\<inter> Y\"\n \nend\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/Alg_Varieties_Theory.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094003735664, "lm_q2_score": 0.8006920092299292, "lm_q1q2_score": 0.7152656986490942}}
{"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_SSortIsSort\n  imports \"../../Test_Base\"\nbegin\n\ndatatype 'a list = nil2 | cons2 \"'a\" \"'a list\"\n\nfun ssortminimum1 :: \"int => int list => int\" where\n  \"ssortminimum1 x (nil2) = x\"\n| \"ssortminimum1 x (cons2 y1 ys1) =\n     (if y1 <= x then ssortminimum1 y1 ys1 else ssortminimum1 x ys1)\"\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\nfun deleteBy :: \"('a => ('a => bool)) => 'a => 'a list =>\n                 'a list\" where\n  \"deleteBy x y (nil2) = nil2\"\n| \"deleteBy x y (cons2 y2 ys) =\n     (if (x y) y2 then ys else cons2 y2 (deleteBy x y ys))\"\n\n(*fun did not finish the proof*)\nfunction ssort :: \"int list => int list\" where\n  \"ssort (nil2) = nil2\"\n| \"ssort (cons2 y ys) =\n     (let m :: int = ssortminimum1 y ys\n     in cons2\n          m\n          (ssort\n             (deleteBy\n                (% (z :: int) => % (x2 :: int) => (z = x2)) m (cons2 y ys))))\"\n  by pat_completeness auto\n\ntheorem property0 :\n  \"((ssort 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_SSortIsSort.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094003735663, "lm_q2_score": 0.800691997339971, "lm_q1q2_score": 0.7152656880276826}}
{"text": "theory Isar_Induction_Demo\nimports Main\nbegin\n\nsection{*Case distinction and induction*}\n\nsubsection{*Case distinction*}\n\ntext{* Explicit: *}\n\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\"\n  thus ?thesis by simp\nqed\n\ntext{* Implicit: *}\n\nlemma \"length(tl xs) = length xs - 1\"\nproof (cases xs)\nprint_cases\n  case Nil\nthm Nil\n  thus ?thesis by simp\nnext\n  case (Cons y ys)\nthm Cons\n  thus ?thesis by simp\nqed\n\n\nsubsection{*Structural induction for nat*}\n\ntext{* Explicit: *}\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\ntext{* Implicit: *}\n\nlemma \"\\<Sum>{0..n::nat} = n*(n+1) div 2\"\nproof (induction n)\nprint_cases\n  case 0\n  show ?case by simp\nnext\n  case (Suc n)\nthm Suc\n  thus ?case by simp\nqed\n\ntext{* After the induction or cases step,\n the PG menu item Isabelle/Show me/cases displays\n the different cases. *}\n\ntext{* Induction with @{text \"\\<Longrightarrow>\"} *}\n\nlemma split_list: \"x : set xs \\<Longrightarrow> \\<exists>ys zs. xs = ys @ x # zs\"\nproof (induction xs)\n  case Nil thus ?case by simp\nnext\nprint_cases\n  case (Cons a xs)\nthm Cons.IH --\"Induction hypothesis\"\nthm Cons.prems --\"Premises of the step case\"\nthm Cons\n  from Cons.prems have \"x = a \\<or> x : set xs\" by simp\n  thus ?case\n  proof\n    assume \"x = a\"\n    hence \"a#xs = [] @ x # xs\" by simp\n    thus ?thesis by blast\n  next\n    assume \"x : set xs\"\n    then obtain ys zs where \"xs = ys @ x # zs\" using Cons.IH by auto\n    hence \"a#xs = (a#ys) @ x # zs\" by simp\n    thus ?thesis by blast\n  qed\nqed\n\n\nsubsection{*Rule induction*}\n\n\ninductive ev :: \"nat => bool\" where\nev0:  \"ev 0\" |\nevSS:  \"ev n \\<Longrightarrow> ev(Suc(Suc n))\"\n\ndeclare ev.intros [simp]\n\n\nlemma \"ev n \\<Longrightarrow> \\<exists>k. n = 2*k\"\nproof (induction rule: ev.induct)\n  case ev0 show ?case by simp\nnext\n  case evSS thus ?case by arith\nqed\n\n\nlemma \"ev n \\<Longrightarrow> \\<exists>k. n = 2*k\"\nproof (induction rule: ev.induct)\n  case ev0 show ?case by simp\nnext\n  case (evSS m)\nthm evSS\nthm evSS.IH\nthm evSS.hyps\n  then obtain k where \"m = 2*k\" by blast\n  hence \"Suc(Suc m) = 2*(k+1)\" by simp\n  thus \"\\<exists>k. Suc(Suc m) = 2*k\" by blast\nqed\n\n\nsubsection{*Inductive definition of the reflexive transitive closure *}\n\nconsts step :: \"'a \\<Rightarrow> 'a \\<Rightarrow> bool\" (infix \"\\<rightarrow>\" 55)\n\ninductive steps :: \"'a \\<Rightarrow> 'a \\<Rightarrow> bool\" (infix \"\\<rightarrow>*\" 55) where\nrefl: \"x \\<rightarrow>* x\" |\nstep: \"\\<lbrakk> x \\<rightarrow> y; y \\<rightarrow>* z \\<rbrakk> \\<Longrightarrow> x \\<rightarrow>* z\"\n\ndeclare refl[simp, intro]\n\ntext{* Explicit and by hand: *}\n\nlemma \"x \\<rightarrow>* y  \\<Longrightarrow>  y \\<rightarrow>* z \\<Longrightarrow> x \\<rightarrow>* z\"\nproof(induction rule: steps.induct)\n  fix x assume \"x \\<rightarrow>* z\"\n  thus \"x \\<rightarrow>* z\" . --\"by assumption\"\nnext\n  fix x' x y :: 'a\n  assume \"x' \\<rightarrow> x\" and \"x \\<rightarrow>* y\"\n  assume IH: \"y \\<rightarrow>* z \\<Longrightarrow> x \\<rightarrow>* z\"\n  assume \"y \\<rightarrow>* z\"\n  show \"x' \\<rightarrow>* z\" by(rule step[OF `x' \\<rightarrow> x` IH[OF `y\\<rightarrow>*z`]])\nqed\n\ntext{* Implicit and automatic: *}\n\nlemma \"x \\<rightarrow>* y  \\<Longrightarrow>  y \\<rightarrow>* z \\<Longrightarrow> x \\<rightarrow>* z\"\nproof(induction rule: steps.induct)\n  case refl thus ?case .\nnext\n  case (step x' x y)\n  --\"x' x y not used in proof text, just for demo\"\nthm step\nthm step.IH\nthm step.hyps\nthm step.prems\n  show ?case\n    by (metis step.hyps(1) step.IH step.prems steps.step)\nqed\n\n\nsubsection{*Rule inversion*}\n\n\nlemma assumes \"ev n\" shows \"ev(n - 2)\"\nproof-\n  from `ev n` show \"ev(n - 2)\"\n  proof cases\n    case ev0\nthm ev0\n    then show ?thesis by simp\n  next\n    case (evSS k)\nthm evSS\n    then show ?thesis by simp\n  qed\nqed\n\n\ntext{* Impossible cases are proved automatically: *}\n\nlemma \"\\<not> ev(Suc 0)\"\nproof\n  assume \"ev(Suc 0)\"\n  then show False\n  proof cases\n  qed\nqed\n\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/Isar_Induction_Demo.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127455162773, "lm_q2_score": 0.8376199653600372, "lm_q1q2_score": 0.7152543643198385}}
{"text": "(* Author: Maximilian Sch\u00e4ffeler *)\n\ntheory Policy_Iteration\n  imports \"MDP-Rewards.MDP_reward\"\n\nbegin\n\nsection \\<open>Policy Iteration\\<close>\ntext \\<open>\nThe Policy Iteration algorithms provides another way to find optimal policies under the expected \ntotal reward criterion.\nIt differs from Value Iteration in that it continuously improves an initial guess for an optimal \ndecision rule. Its execution can be subdivided into two alternating steps: policy evaluation and \npolicy improvement.\n\nPolicy evaluation means the calculation of the value of the current decision rule.\n\nDuring the improvement phase, we choose the decision rule with the maximum value for L, \nwhile we prefer to keep the old action selection in case of ties.\n\\<close>\n\ncontext MDP_att_\\<L> begin\ndefinition \"policy_eval d = \\<nu>\\<^sub>b (mk_stationary_det d)\"\nend\n\ncontext MDP_act_disc\nbegin\n\ndefinition \"policy_improvement d v s = (\n  if is_arg_max (\\<lambda>a. L\\<^sub>a a (apply_bfun v) s) (\\<lambda>a. a \\<in> A s) (d s) \n  then d s\n  else arb_act (opt_acts v s))\"\n\ndefinition \"policy_step d = policy_improvement d (policy_eval d)\"\n\n(* todo: move check is_dec_det outside the recursion *)\nfunction policy_iteration :: \"('s \\<Rightarrow> 'a) \\<Rightarrow> ('s \\<Rightarrow> 'a)\" where\n  \"policy_iteration d = (\n  let d' = policy_step d in\n  if d = d' \\<or> \\<not>is_dec_det d then d else policy_iteration d')\"\n  by auto\n\ntext \\<open>\nThe policy iteration algorithm as stated above does require that the supremum in @{const \\<L>\\<^sub>b} is\nalways attained.\n\\<close>\n\ntext \\<open>\nEach policy improvement returns a valid decision rule.\n\\<close>\nlemma is_dec_det_pi: \"is_dec_det (policy_improvement d v)\"\n  unfolding policy_improvement_def is_dec_det_def is_arg_max_def\n  by (auto simp: some_opt_acts_in_A)\n\nlemma policy_improvement_is_dec_det: \"d \\<in> D\\<^sub>D \\<Longrightarrow> policy_improvement d v \\<in> D\\<^sub>D\"\n  unfolding policy_improvement_def is_dec_det_def\n  using some_opt_acts_in_A\n  by auto\n\nlemma policy_improvement_improving: \n  assumes \"d \\<in> D\\<^sub>D\" \n  shows \"\\<nu>_improving v (mk_dec_det (policy_improvement d v))\"\nproof -\n  have \"\\<L>\\<^sub>b v x = L (mk_dec_det (policy_improvement d v)) v x\" for x\n    using is_opt_act_some\n    by (fastforce simp: \\<L>\\<^sub>b_eq_argmax_L\\<^sub>a L_eq_L\\<^sub>a_det is_opt_act_def policy_improvement_def arg_max_SUP)\n  thus ?thesis\n    using policy_improvement_is_dec_det assms by (auto simp: \\<nu>_improving_alt)\nqed\n\nlemma eval_policy_step_L:\n \"is_dec_det d \\<Longrightarrow> L (mk_dec_det (policy_step d)) (policy_eval d) = \\<L>\\<^sub>b (policy_eval d)\"\n  by (auto simp: policy_step_def \\<nu>_improving_imp_\\<L>\\<^sub>b[OF policy_improvement_improving])\n\ntext \\<open> The sequence of policies generated by policy iteration has monotonically increasing \ndiscounted reward.\\<close>\nlemma policy_eval_mon:\n  assumes \"is_dec_det d\"\n  shows \"policy_eval d \\<le> policy_eval (policy_step d)\"\nproof -\n  let ?d' = \"mk_dec_det (policy_step d)\"\n  let ?dp = \"mk_stationary_det d\"\n  let ?P = \"\\<Sum>t. l ^ t *\\<^sub>R \\<P>\\<^sub>1 ?d' ^^ t\"\n\n  have \"L (mk_dec_det d) (policy_eval d) \\<le> L ?d' (policy_eval d)\"\n    using assms by (auto simp: L_le_\\<L>\\<^sub>b eval_policy_step_L)\n  hence \"policy_eval d \\<le> L ?d' (policy_eval d)\"\n    using L_\\<nu>_fix policy_eval_def by auto\n  hence \"\\<nu>\\<^sub>b ?dp \\<le> r_dec\\<^sub>b ?d' + l *\\<^sub>R \\<P>\\<^sub>1 ?d' (\\<nu>\\<^sub>b ?dp)\"\n    unfolding policy_eval_def L_def by auto\n  hence \"(id_blinfun - l *\\<^sub>R \\<P>\\<^sub>1 ?d') (\\<nu>\\<^sub>b ?dp) \\<le> r_dec\\<^sub>b ?d'\"\n    by (simp add: blinfun.diff_left diff_le_eq scaleR_blinfun.rep_eq)\n  hence \"?P ((id_blinfun - l *\\<^sub>R \\<P>\\<^sub>1 ?d') (\\<nu>\\<^sub>b ?dp)) \\<le> ?P (r_dec\\<^sub>b ?d')\"\n    using lemma_6_1_2_b by auto\n  hence \"\\<nu>\\<^sub>b ?dp \\<le> ?P (r_dec\\<^sub>b ?d')\"\n    using inv_norm_le'(2)[OF norm_\\<P>\\<^sub>1_l_less] by (auto simp: blincomp_scaleR_right)\n  thus ?thesis\n    by (auto simp: policy_eval_def \\<nu>_stationary)\nqed\n\ntext \\<open>\nIf policy iteration terminates, i.e. @{term \"d = policy_step d\"}, then it does so with optimal value.\n\\<close>\nlemma policy_step_eq_imp_opt:\n  assumes \"is_dec_det d\" \"d = policy_step d\" \n  shows \"\\<nu>\\<^sub>b (mk_stationary_det d) = \\<nu>\\<^sub>b_opt\"\n  using L_\\<nu>_fix assms eval_policy_step_L[unfolded policy_eval_def] \n  by (fastforce intro: \\<L>_fix_imp_opt)\n\nend\n\ntext \\<open>We prove termination of policy iteration only if both the state and action sets are finite.\\<close>\nlocale MDP_PI_finite = MDP_act_disc arb_act A K r l \n  for\n    A and\n    K :: \"'s ::countable \\<times> 'a ::countable \\<Rightarrow> 's pmf\" and r l arb_act +\n  assumes fin_states: \"finite (UNIV :: 's set)\" and fin_actions: \"\\<And>s. finite (A s)\"\nbegin\n\ntext \\<open>If the state and action sets are both finite, \n  then so is the set of deterministic decision rules @{const \"D\\<^sub>D\"}\\<close>\nlemma finite_D\\<^sub>D[simp]: \"finite D\\<^sub>D\"\nproof -\n  let ?set = \"{d. \\<forall>x :: 's. (x \\<in> UNIV \\<longrightarrow> d x \\<in> (\\<Union>s. A s)) \\<and> (x \\<notin> UNIV \\<longrightarrow> d x = undefined)}\"\n  have \"finite (\\<Union>s. A s)\"\n    using fin_actions fin_states by blast\n  hence \"finite ?set\"\n    using fin_states by (fastforce intro: finite_set_of_finite_funs)\n  moreover have \"D\\<^sub>D \\<subseteq> ?set\"\n    unfolding is_dec_det_def by auto\n  ultimately show ?thesis\n    using finite_subset by auto\nqed\n\nlemma finite_rel: \"finite {(u, v). is_dec_det u \\<and> is_dec_det v \\<and> \\<nu>\\<^sub>b (mk_stationary_det u) > \n  \\<nu>\\<^sub>b (mk_stationary_det v)}\"\nproof-\n  have aux: \"finite {(u, v). is_dec_det u \\<and> is_dec_det v}\"\n    by auto\n  show ?thesis\n    by (auto intro: finite_subset[OF _ aux])\nqed\n\ntext \\<open>\nThis auxiliary lemma shows that policy iteration terminates if no improvement to the value of \nthe policy could be made, as then the policy remains unchanged.\n\\<close>\nlemma eval_eq_imp_policy_eq: \n  assumes \"policy_eval d = policy_eval (policy_step d)\" \"is_dec_det d\"\n  shows \"d = policy_step d\"\nproof -\n  have \"policy_eval d s = policy_eval (policy_step d) s\" for s\n    using assms by auto\n  have \"policy_eval d = L (mk_dec_det d) (policy_eval (policy_step d))\"\n    unfolding policy_eval_def\n    using L_\\<nu>_fix \n    by (auto simp: assms(1)[symmetric, unfolded policy_eval_def])\n  hence \"policy_eval d = \\<L>\\<^sub>b (policy_eval d)\"\n    by (metis L_\\<nu>_fix policy_eval_def assms eval_policy_step_L)\n  hence \"L (mk_dec_det d) (policy_eval d) s = \\<L>\\<^sub>b (policy_eval d) s\" for s\n    using \\<open>policy_eval d = L (mk_dec_det d) (policy_eval (policy_step d))\\<close> assms(1) by auto\n  hence \"is_arg_max (\\<lambda>a. L\\<^sub>a a (\\<nu>\\<^sub>b (mk_stationary (mk_dec_det d))) s) (\\<lambda>a. a \\<in> A s) (d s)\" for s\n    unfolding L_eq_L\\<^sub>a_det\n    unfolding policy_eval_def \\<L>\\<^sub>b.rep_eq \\<L>_eq_SUP_det SUP_step_det_eq\n    using assms(2) is_dec_det_def L\\<^sub>a_le\n    by (auto intro!: SUP_is_arg_max boundedI bounded_imp_bdd_above)\n  thus ?thesis\n    unfolding policy_eval_def policy_step_def policy_improvement_def\n    by auto\nqed\n\ntext \\<open>\nWe are now ready to prove termination in the context of finite state-action spaces.\nIntuitively, the algorithm terminates as there are only finitely many decision rules,\nand in each recursive call the value of the decision rule increases.\n\\<close>\ntermination policy_iteration\nproof (relation \"{(u, v). u \\<in> D\\<^sub>D \\<and> v \\<in> D\\<^sub>D \\<and> \\<nu>\\<^sub>b (mk_stationary_det u) > \\<nu>\\<^sub>b (mk_stationary_det v)}\")\n  show \"wf {(u, v). u \\<in> D\\<^sub>D \\<and> v \\<in> D\\<^sub>D \\<and> \\<nu>\\<^sub>b (mk_stationary_det v) < \\<nu>\\<^sub>b (mk_stationary_det u)}\"\n    using finite_rel by (auto intro!: finite_acyclic_wf acyclicI_order)\nnext\n  fix d x\n  assume h: \"x = policy_step d\" \"\\<not> (d = x \\<or> \\<not> is_dec_det d)\"\n  have \"is_dec_det d \\<Longrightarrow> \\<nu>\\<^sub>b (mk_stationary_det d) \\<le> \\<nu>\\<^sub>b (mk_stationary_det (policy_step d))\"\n    using policy_eval_mon by (simp add: policy_eval_def)\n  hence \"is_dec_det d \\<Longrightarrow> d \\<noteq> policy_step d \\<Longrightarrow>\n    \\<nu>\\<^sub>b (mk_stationary_det d) < \\<nu>\\<^sub>b (mk_stationary_det (policy_step d))\"\n    using eval_eq_imp_policy_eq policy_eval_def\n    by (force intro!: order.not_eq_order_implies_strict)\n  thus \"(x, d) \\<in> {(u, v). u \\<in> D\\<^sub>D \\<and> v \\<in> D\\<^sub>D \\<and> \\<nu>\\<^sub>b (mk_stationary_det v) < \\<nu>\\<^sub>b (mk_stationary_det u)}\"\n    using is_dec_det_pi policy_step_def h by auto\nqed\n\ntext \\<open>\nThe termination proof gives us access to the induction rule/simplification lemmas associated \nwith the @{const policy_iteration} definition.\nThus we can prove that the algorithm finds an optimal policy.\n\\<close>\n\nlemma is_dec_det_pi': \"d \\<in> D\\<^sub>D \\<Longrightarrow> is_dec_det (policy_iteration d)\"\n  using is_dec_det_pi\n  by (induction d rule: policy_iteration.induct) (auto simp: Let_def policy_step_def)\n\nlemma pi_pi[simp]: \"d \\<in> D\\<^sub>D \\<Longrightarrow> policy_step (policy_iteration d) = policy_iteration d\"\n  using is_dec_det_pi\n  by (induction d rule: policy_iteration.induct) (auto simp: policy_step_def Let_def)\n\nlemma policy_iteration_correct: \n  \"d \\<in> D\\<^sub>D \\<Longrightarrow> \\<nu>\\<^sub>b (mk_stationary_det (policy_iteration d)) = \\<nu>\\<^sub>b_opt\" \n  by (induction d rule: policy_iteration.induct)\n    (fastforce intro!: policy_step_eq_imp_opt is_dec_det_pi' simp del: policy_iteration.simps)\nend\n\ncontext MDP_finite_type begin\ntext \\<open>\nThe following proofs concern code generation, i.e. how to represent @{const \\<P>\\<^sub>1} as a matrix.\n\\<close>\n\nsublocale MDP_att_\\<L>\n  by (auto simp: A_ne finite_is_arg_max MDP_att_\\<L>_def MDP_att_\\<L>_axioms_def max_L_ex_def \n      has_arg_max_def MDP_reward_disc_axioms) \n \ndefinition \"fun_to_matrix f = matrix (\\<lambda>v. (\\<chi> j. f (vec_nth v) j))\"\ndefinition \"Ek_mat d = fun_to_matrix (\\<lambda>v. ((\\<P>\\<^sub>1 d) (Bfun v)))\"\ndefinition \"nu_inv_mat d = fun_to_matrix ((\\<lambda>v. ((id_blinfun - l *\\<^sub>R \\<P>\\<^sub>1 d) (Bfun v))))\"\ndefinition \"nu_mat d = fun_to_matrix (\\<lambda>v. ((\\<Sum>i. (l *\\<^sub>R \\<P>\\<^sub>1 d) ^^ i) (Bfun v)))\"\n\nlemma apply_nu_inv_mat: \n  \"(id_blinfun - l *\\<^sub>R \\<P>\\<^sub>1 d) v = Bfun (\\<lambda>i. ((nu_inv_mat d) *v (vec_lambda v)) $ i)\"\nproof -\n  have eq_onpI: \"P x \\<Longrightarrow> eq_onp P x x\" for P x\n    by(simp add: eq_onp_def)\n\n  have \"Real_Vector_Spaces.linear (\\<lambda>v. vec_lambda (((id_blinfun - l *\\<^sub>R \\<P>\\<^sub>1 d) (bfun.Bfun (($) v)))))\"\n    by (auto simp del: real_scaleR_def intro: linearI\n        simp: scaleR_vec_def eq_onpI plus_vec_def vec_lambda_inverse plus_bfun.abs_eq[symmetric] \n        scaleR_bfun.abs_eq[symmetric] blinfun.scaleR_right blinfun.add_right)\n  thus ?thesis\n    unfolding Ek_mat_def fun_to_matrix_def nu_inv_mat_def\n    by (auto simp: apply_bfun_inverse vec_lambda_inverse)\nqed\n\nlemma bounded_linear_vec_lambda: \"bounded_linear (\\<lambda>x. vec_lambda (x :: 's \\<Rightarrow>\\<^sub>b real))\"\nproof (intro bounded_linear_intro)\n  fix x :: \"'s \\<Rightarrow>\\<^sub>b real\"\n  have \"sqrt (\\<Sum> i \\<in> UNIV . (apply_bfun x i)\\<^sup>2) \\<le> (\\<Sum> i \\<in> UNIV . \\<bar>(apply_bfun x i)\\<bar>)\"\n    using L2_set_le_sum_abs \n    unfolding L2_set_def\n    by auto\n  also have \"(\\<Sum> i \\<in> UNIV . \\<bar>(apply_bfun x i)\\<bar>) \\<le> (card (UNIV :: 's set) * (\\<Squnion>xa. \\<bar>apply_bfun x xa\\<bar>))\"\n    by (auto intro!: cSup_upper sum_bounded_above)\n  finally show \"norm (vec_lambda (apply_bfun x)) \\<le> norm x * CARD('s)\"\n    unfolding norm_vec_def norm_bfun_def dist_bfun_def L2_set_def\n    by (auto simp add: mult.commute)\nqed (auto simp: plus_vec_def scaleR_vec_def)\n\nlemma bounded_linear_vec_lambda_blinfun: \n  fixes f :: \"('s \\<Rightarrow>\\<^sub>b real) \\<Rightarrow>\\<^sub>L ('s \\<Rightarrow>\\<^sub>b real)\"\n  shows \"bounded_linear (\\<lambda>v. vec_lambda (apply_bfun (blinfun_apply f (bfun.Bfun (($) v)))))\" \n  using blinfun.bounded_linear_right\n  by (fastforce intro: bounded_linear_compose[OF bounded_linear_vec_lambda] \n      bounded_linear_bfun_nth bounded_linear_compose[of f])\n\nlemma invertible_nu_inv_max: \"invertible (nu_inv_mat d)\"\n  unfolding nu_inv_mat_def fun_to_matrix_def\n  by (auto simp: matrix_invertible inv_norm_le' vec_lambda_inverse apply_bfun_inverse \n      bounded_linear.linear[OF bounded_linear_vec_lambda_blinfun]\n      intro!: exI[of _ \"\\<lambda>v. (\\<chi> j. (\\<lambda>v. (\\<Sum>i. (l *\\<^sub>R \\<P>\\<^sub>1 d) ^^ i) (Bfun v)) (vec_nth v) j)\"])\nend\n      \nlocale MDP_ord = MDP_finite_type A K r l\n  for A and                \n    K :: \"'s :: {finite, wellorder} \\<times> 'a :: {finite, wellorder} \\<Rightarrow> 's pmf\"\n    and r l\nbegin\n\nlemma \\<L>_fin_eq_det: \"\\<L> v s = (\\<Squnion>a \\<in> A s. L\\<^sub>a a v s)\"\n  by (simp add: SUP_step_det_eq \\<L>_eq_SUP_det)\n\nlemma \\<L>\\<^sub>b_fin_eq_det: \"\\<L>\\<^sub>b v s = (\\<Squnion>a \\<in> A s. L\\<^sub>a a v s)\"\n  by (simp add: SUP_step_det_eq \\<L>\\<^sub>b.rep_eq \\<L>_eq_SUP_det)\n\nsublocale MDP_PI_finite A K r l \"\\<lambda>X. Least (\\<lambda>x. x \\<in> X)\"\n  by unfold_locales (auto intro: LeastI)\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/MDP-Algorithms/Policy_Iteration.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8376199592797929, "lm_q2_score": 0.8539127473751341, "lm_q1q2_score": 0.7152543606848559}}
{"text": "(*\n  File: Quicksort.thy\n  Author: Bohua Zhan\n*)\n\nsection \\<open>Quicksort\\<close>\n\ntheory Quicksort\n  imports Arrays_Ex\nbegin\n\ntext \\<open>\n  Functional version of quicksort.\n\n  Implementation of quicksort is largely based on theory\n  Imperative\\_Quicksort in HOL/Imperative\\_HOL/ex in the Isabelle\n  library.\n\\<close>\n\nsubsection \\<open>Outer remains\\<close>\n  \ndefinition outer_remains :: \"'a list \\<Rightarrow> 'a list \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> bool\" where [rewrite]:\n  \"outer_remains xs xs' l r \\<longleftrightarrow> (length xs = length xs' \\<and> (\\<forall>i. i < l \\<or> r < i \\<longrightarrow> xs ! i = xs' ! i))\"\n\nlemma outer_remains_length [forward]:\n  \"outer_remains xs xs' l r \\<Longrightarrow> length xs = length xs'\" by auto2\n\nlemma outer_remains_eq [rewrite_back]:\n  \"outer_remains xs xs' l r \\<Longrightarrow> i < l \\<Longrightarrow> xs ! i = xs' ! i\"\n  \"outer_remains xs xs' l r \\<Longrightarrow> r < i \\<Longrightarrow> xs ! i = xs' ! i\" by auto2+\n\nlemma outer_remains_sublist [backward2]:\n  \"outer_remains xs xs' l r \\<Longrightarrow> i < l \\<Longrightarrow> take i xs = take i xs'\"\n  \"outer_remains xs xs' l r \\<Longrightarrow> r < i \\<Longrightarrow> drop i xs = drop i xs'\"\n  \"i \\<le> j \\<Longrightarrow> j \\<le> length xs \\<Longrightarrow> outer_remains xs xs' l r \\<Longrightarrow> j \\<le> l \\<Longrightarrow> sublist i j xs = sublist i j xs'\"\n  \"i \\<le> j \\<Longrightarrow> j \\<le> length xs \\<Longrightarrow> outer_remains xs xs' l r \\<Longrightarrow> i > r \\<Longrightarrow> sublist i j xs = sublist i j xs'\" by auto2+\nsetup \\<open>del_prfstep_thm_eqforward @{thm outer_remains_def}\\<close>\n\nsubsection \\<open>part1 function\\<close>  \n\nfunction part1 :: \"('a::linorder) list \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> 'a \\<Rightarrow> (nat \\<times> 'a list)\" where\n  \"part1 xs l r a = (\n     if r \\<le> l then (r, xs)\n     else if xs ! l \\<le> a then part1 xs (l + 1) r a\n     else part1 (list_swap xs l r) l (r - 1) a)\"\n  by auto\n  termination by (relation \"measure (\\<lambda>(_,l,r,_). r - l)\") auto\nsetup \\<open>register_wellform_data (\"part1 xs l r a\", [\"r < length xs\"])\\<close>\nsetup \\<open>add_prfstep_check_req (\"part1 xs l r a\", \"r < length xs\")\\<close>\n\nlemma part1_basic:\n  \"r < length xs \\<Longrightarrow> l \\<le> r \\<Longrightarrow> (rs, xs') = part1 xs l r a \\<Longrightarrow>\n   outer_remains xs xs' l r \\<and> mset xs' = mset xs \\<and> l \\<le> rs \\<and> rs \\<le> r\"\n@proof @fun_induct \"part1 xs l r a\" @unfold \"part1 xs l r a\" @qed\nsetup \\<open>add_forward_prfstep_cond @{thm part1_basic} [with_term \"part1 ?xs ?l ?r ?a\"]\\<close>\n\nlemma part1_partitions1 [backward]:\n  \"r < length xs \\<Longrightarrow> (rs, xs') = part1 xs l r a \\<Longrightarrow> l \\<le> i \\<Longrightarrow> i < rs \\<Longrightarrow> xs' ! i \\<le> a\"\n@proof @fun_induct \"part1 xs l r a\" @unfold \"part1 xs l r a\" @qed\n\nlemma part1_partitions2 [backward]:\n  \"r < length xs \\<Longrightarrow> (rs, xs') = part1 xs l r a \\<Longrightarrow> rs < i \\<Longrightarrow> i \\<le> r \\<Longrightarrow> xs' ! i \\<ge> a\"\n@proof @fun_induct \"part1 xs l r a\" @unfold \"part1 xs l r a\" @qed\n\nsubsection \\<open>Paritition function\\<close>\n\ndefinition partition :: \"('a::linorder list) \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> (nat \\<times> 'a list)\" where [rewrite]:\n  \"partition xs l r = (\n    let p = xs ! r;\n      (m, xs') = part1 xs l (r - 1) p;\n      m' = if xs' ! m \\<le> p then m + 1 else m\n    in\n      (m', list_swap xs' m' r))\"\nsetup \\<open>register_wellform_data (\"partition xs l r\", [\"l < r\", \"r < length xs\"])\\<close>\n\nlemma partition_basic:\n  \"l < r \\<Longrightarrow> r < length xs \\<Longrightarrow> (rs, xs') = partition xs l r \\<Longrightarrow>\n   outer_remains xs xs' l r \\<and> mset xs' = mset xs \\<and> l \\<le> rs \\<and> rs \\<le> r\" by auto2\nsetup \\<open>add_forward_prfstep_cond @{thm partition_basic} [with_term \"partition ?xs ?l ?r\"]\\<close>\n  \nlemma partition_partitions1 [forward]:\n  \"l < r \\<Longrightarrow> r < length xs \\<Longrightarrow> (rs, xs') = partition xs l r \\<Longrightarrow>\n   x \\<in> set (sublist l rs xs') \\<Longrightarrow> x \\<le> xs' ! rs\"\n@proof @obtain i where \"i \\<ge> l\" \"i < rs\" \"x = xs' ! i\" @qed\n\nlemma partition_partitions2 [forward]:\n  \"l < r \\<Longrightarrow> r < length xs \\<Longrightarrow> (rs, xs'') = partition xs l r \\<Longrightarrow>\n   x \\<in> set (sublist (rs + 1) (r + 1) xs'') \\<Longrightarrow> x \\<ge> xs'' ! rs\"\n@proof\n  @obtain i where \"i \\<ge> rs + 1\" \"i < r + 1\" \"x = xs'' ! i\"\n  @let \"p = xs ! r\"\n  @let \"m = fst (part1 xs l (r - 1) p)\"\n  @let \"xs' = snd (part1 xs l (r - 1) p)\"\n  @case \"xs' ! m \\<le> p\"\n@qed\nsetup \\<open>del_prfstep_thm @{thm partition_def}\\<close>\n\nlemma quicksort_term1:\n  \"\\<not>r \\<le> l \\<Longrightarrow> \\<not> length xs \\<le> r \\<Longrightarrow> x = partition xs l r \\<Longrightarrow> (p, xs1) = x \\<Longrightarrow> p - Suc l < r - l\"\n@proof @have \"fst (partition xs l r) - l - 1 < r - l\" @qed\n\nlemma quicksort_term2:\n  \"\\<not>r \\<le> l \\<Longrightarrow> \\<not> length xs \\<le> r \\<Longrightarrow> x = partition xs l r \\<Longrightarrow> (p, xs2) = x \\<Longrightarrow> r - Suc p < r - l\"\n@proof @have \"r - fst (partition xs l r) - 1 < r - l\" @qed\n\nsubsection \\<open>Quicksort function\\<close>\n\nfunction quicksort :: \"('a::linorder) list \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> 'a list\" where\n  \"quicksort xs l r = (\n    if l \\<ge> r then xs\n    else if r \\<ge> length xs then xs\n    else let\n      (p, xs1) = partition xs l r;\n      xs2 = quicksort xs1 l (p - 1)\n    in\n      quicksort xs2 (p + 1) r)\"\n  by auto termination apply (relation \"measure (\\<lambda>(a, l, r). (r - l))\") \n  by (auto simp add: quicksort_term1 quicksort_term2)\n\nlemma quicksort_basic [rewrite_arg]:\n  \"mset (quicksort xs l r) = mset xs \\<and> outer_remains xs (quicksort xs l r) l r\"\n@proof @fun_induct \"quicksort xs l r\" @unfold \"quicksort xs l r\" @qed\n\nlemma quicksort_trivial1 [rewrite]:\n  \"l \\<ge> r \\<Longrightarrow> quicksort xs l r = xs\"\n@proof @unfold \"quicksort xs l r\" @qed\n\nlemma quicksort_trivial2 [rewrite]:\n  \"r \\<ge> length xs \\<Longrightarrow> quicksort xs l r = xs\"\n@proof @unfold \"quicksort xs l r\" @qed\n\nlemma quicksort_permutes [resolve]:\n  \"xs' = quicksort xs l r \\<Longrightarrow> set (sublist l (r + 1) xs') = set (sublist l (r + 1) xs)\"\n@proof\n  @case \"l \\<ge> r\" @case \"r \\<ge> length xs\"\n  @have \"xs = take l xs @ sublist l (r + 1) xs @ drop (r + 1) xs\"\n  @have \"xs' = take l xs' @ sublist l (r + 1) xs' @ drop (r + 1) xs'\"\n  @have \"take l xs = take l xs'\"\n  @have \"drop (r + 1) xs = drop (r + 1) xs'\"\n@qed\n\nlemma quicksort_sorts [forward_arg]:\n  \"r < length xs \\<Longrightarrow> sorted (sublist l (r + 1) (quicksort xs l r))\"\n@proof @fun_induct \"quicksort xs l r\"\n  @case \"l \\<ge> r\" @with @case \"l = r\" @end\n  @case \"r \\<ge> length xs\"\n  @let \"p = fst (partition xs l r)\"\n  @let \"xs1 = snd (partition xs l r)\"\n  @let \"xs2 = quicksort xs1 l (p - 1)\"\n  @let \"xs3 = quicksort xs2 (p + 1) r\"\n  @have \"sorted (sublist l (r + 1) xs3)\" @with\n    @have \"l \\<le> p\" @have \"p + 1 \\<le> r + 1\" @have \"r + 1 \\<le> length xs3\"\n    @have \"sublist l p xs2 = sublist l p xs3\"\n    @have \"set (sublist l p xs1) = set (sublist l p xs2)\"\n    @have \"sublist (p + 1) (r + 1) xs1 = sublist (p + 1) (r + 1) xs2\"\n    @have \"set (sublist (p + 1) (r + 1) xs2) = set (sublist (p + 1) (r + 1) xs3)\"\n    @have \"\\<forall>x\\<in>set (sublist l p xs3). x \\<le> xs3 ! p\"\n    @have \"\\<forall>x\\<in>set (sublist (p + 1) (r + 1) xs3). x \\<ge> xs3 ! p\"\n    @have \"sorted (sublist l p xs3)\"\n    @have \"sorted (sublist (p + 1) (r + 1) xs3)\"\n    @have \"sublist l (r + 1) xs3 = sublist l p xs3 @ (xs3 ! p) # sublist (p + 1) (r + 1) xs3\"\n  @end\n  @unfold \"quicksort xs l r\"\n@qed\n\ntext \\<open>Main result: correctness of functional quicksort.\\<close>\ntheorem quicksort_sorts_all [rewrite]:\n  \"xs \\<noteq> [] \\<Longrightarrow> quicksort xs 0 (length xs - 1) = sort xs\"\n@proof\n  @let \"xs' = quicksort xs 0 (length xs - 1)\"\n  @have \"sublist 0 (length xs - 1 + 1) xs' = xs'\"\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/Quicksort.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.819893335913536, "lm_q2_score": 0.8723473779969194, "lm_q1q2_score": 0.7152318018213206}}
{"text": "(*  Title:       Countable Ordinals\n\n    Author:      Brian Huffman, 2005\n    Maintainer:  Brian Huffman <brianh at cse.ogi.edu>\n*)\n\nheader {* Fixed-points *}\n\ntheory OrdinalFix\nimports OrdinalInverse\nbegin\n\nprimrec iter :: \"nat \\<Rightarrow> ('a \\<Rightarrow> 'a) \\<Rightarrow> ('a \\<Rightarrow> 'a)\"\nwhere\n  \"iter 0       F x = x\"\n| \"iter (Suc n) F x = F (iter n F x)\"\n\ndefinition\n  oFix :: \"(ordinal \\<Rightarrow> ordinal) \\<Rightarrow> ordinal \\<Rightarrow> ordinal\" where\n  \"oFix F a = oLimit (\\<lambda>n. iter n F a)\"\n\nlemma oFix_fixed:\n\"\\<lbrakk>continuous F; a \\<le> F a\\<rbrakk> \\<Longrightarrow> F (oFix F a) = oFix F a\"\n apply (unfold oFix_def)\n apply (simp only: continuousD)\n apply (rule order_antisym)\n  apply (rule oLimit_leI, clarify)\n  apply (rule_tac n=\"Suc n\" in le_oLimitI, simp)\n apply (rule oLimit_leI, clarify)\n apply (rule_tac n=n in le_oLimitI)\n apply (induct_tac n, simp)\n apply (simp add: continuous.monoD)\ndone\n\nlemma oFix_least:\n\"\\<lbrakk>mono F; F x = x; a \\<le> x\\<rbrakk> \\<Longrightarrow> oFix F a \\<le> x\"\n apply (unfold oFix_def)\n apply (rule oLimit_leI, clarify)\n apply (induct_tac n, simp_all)\n apply (erule subst)\n apply (erule monoD, assumption)\ndone\n\nlemma mono_oFix: \"mono F \\<Longrightarrow> mono (oFix F)\"\n apply (rule monoI, unfold oFix_def)\n apply (subgoal_tac \"\\<forall>n. iter n F x \\<le> iter n F y\")\n  apply (rule oLimit_leI, clarify)\n  apply (rule_tac n=n in le_oLimitI, erule spec)\n apply (rule allI, induct_tac n)\n  apply simp\n apply (simp add: monoD)\ndone\n\nlemma less_oFixD:\n\"\\<lbrakk>x < oFix F a; mono F; F x = x\\<rbrakk> \\<Longrightarrow> x < a\"\n apply (simp add: linorder_not_le[symmetric])\n apply (erule contrapos_nn)\nby (rule oFix_least)\n\nlemma less_oFixI: \"a < F a \\<Longrightarrow> a < oFix F a\"\n apply (unfold oFix_def)\n apply (erule order_less_le_trans)\n apply (rule_tac n=1 in le_oLimitI)\n apply simp\ndone\n\nlemma le_oFix: \"a \\<le> oFix F a\"\n apply (unfold oFix_def)\n apply (rule_tac n=0 in le_oLimitI)\n apply simp\ndone\n\nlemma le_oFix1: \"F a \\<le> oFix F a\"\n apply (unfold oFix_def)\n apply (rule_tac n=1 in le_oLimitI)\n apply simp\ndone\n\nlemma less_oFix_0D:\n\"\\<lbrakk>x < oFix F 0; mono F\\<rbrakk> \\<Longrightarrow> x < F x\"\n apply (unfold oFix_def, drule less_oLimitD, clarify)\n apply (erule_tac P=\"x < iter n F 0\" in rev_mp)\n apply (induct_tac n, auto simp add: linorder_not_less)\n apply (erule order_less_le_trans)\n apply (erule monoD, assumption)\ndone\n\nlemma zero_less_oFix_eq: \"(0 < oFix F 0) = (0 < F 0)\"\n apply (safe)\n  apply (erule contrapos_pp)\n  apply (simp only: linorder_not_less oFix_def)\n  apply (rule oLimit_leI[rule_format])\n  apply (induct_tac n, simp, simp)\n apply (erule less_oFixI)\ndone\n\nlemma oFix_eq_self: \"F a = a \\<Longrightarrow> oFix F a = a\"\n apply (unfold oFix_def)\n apply (subgoal_tac \"\\<forall>n. iter n F a = a\", simp)\n apply (rule allI, induct_tac n, simp_all)\ndone\n\n\nsubsection {* Derivatives of ordinal functions *}\n\ntext \"The derivative of F enumerates all the fixed-points of F\"\n\ndefinition\n  oDeriv :: \"(ordinal \\<Rightarrow> ordinal) \\<Rightarrow> ordinal \\<Rightarrow> ordinal\" where\n  \"oDeriv F = ordinal_rec (oFix F 0) (\\<lambda>p x. oFix F (oSuc x))\"\n\nlemma oDeriv_0 [simp]:\n\"oDeriv F 0 = oFix F 0\"\nby (simp add: oDeriv_def)\n\nlemma oDeriv_oSuc [simp]:\n\"oDeriv F (oSuc x) = oFix F (oSuc (oDeriv F x))\"\nby (simp add: oDeriv_def)\n\nlemma oDeriv_oLimit [simp]:\n\"oDeriv F (oLimit f) = oLimit (\\<lambda>n. oDeriv F (f n))\"\n apply (unfold oDeriv_def)\n apply (rule ordinal_rec_oLimit, clarify)\n apply (rule order_trans[OF order_less_imp_le[OF less_oSuc]])\n apply (rule le_oFix)\ndone\n\nlemma oDeriv_fixed:\n\"normal F \\<Longrightarrow> F (oDeriv F n) = oDeriv F n\"\n apply (rule_tac a=n in oLimit_induct, simp_all)\n   apply (rule oFix_fixed)\n    apply (erule normal.continuous)\n   apply simp\n  apply (rule oFix_fixed)\n   apply (erule normal.continuous)\n  apply (erule normal.increasing)\n apply (simp add: normal.oLimit)\ndone\n\nlemma oDeriv_fixedD:\n\"\\<lbrakk>oDeriv F x = x; normal F\\<rbrakk> \\<Longrightarrow> F x = x\"\nby (erule subst, erule oDeriv_fixed)\n\nlemma normal_oDeriv:\n\"normal (oDeriv F)\"\n apply (rule normalI, simp_all)\n apply (rule order_less_le_trans[OF less_oSuc])\n apply (rule le_oFix)\ndone\n\nlemma oDeriv_increasing:\n\"continuous F \\<Longrightarrow> F x \\<le> oDeriv F x\"\n apply (rule_tac a=x in oLimit_induct)\n   apply (simp add: le_oFix1)\n  apply simp\n  apply (rule order_trans[OF _ le_oFix1])\n  apply (erule continuous.monoD)\n  apply simp\n  apply (rule normal.increasing)\n  apply (rule normal_oDeriv)\n apply (simp add: continuousD)\n apply (rule oLimit_leI[rule_format])\n apply (rule_tac n=n in le_oLimitI)\n apply (erule spec)\ndone\n\nlemma oDeriv_total:\n\"\\<lbrakk>normal F; F x = x\\<rbrakk> \\<Longrightarrow> \\<exists>n. x = oDeriv F n\"\n apply (subgoal_tac \"\\<exists>n. oDeriv F n \\<le> x \\<and> x < oDeriv F (oSuc n)\")\n  apply clarsimp\n  apply (drule less_oFixD)\n    apply (erule normal.mono)\n   apply assumption\n  apply (rule_tac x=n in exI, simp add: less_oSuc_eq_le)\n apply (rule normal.oInv_ex[OF normal_oDeriv])\n apply (simp add: oFix_least normal.mono)\ndone\n\nlemma range_oDeriv:\n\"normal F \\<Longrightarrow> range (oDeriv F) = {x. F x = x}\"\nby (auto intro: oDeriv_fixed dest: oDeriv_total)\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/Ordinal/OrdinalFix.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.872347368040789, "lm_q2_score": 0.8198933293122506, "lm_q1q2_score": 0.7152317878997417}}
{"text": "theory HSV_tasks_2022 imports Complex_Main begin\n\nsection {* Task 1: Full adders *}\n\nfun fulladder :: \"bool * bool * bool \\<Rightarrow> bool * bool\"\nwhere\n  \"fulladder (a,b,cin) = (\n   let (tmp1, tmp2) = halfadder(a,b) in\n   let (tmp3, s) = halfadder(cin,tmp2) in\n   let cout = tmp1 | tmp3 in\n   (cout, s))\"\n\n\nsection {* Task 2: Fifth powers *}\n\ntheorem \"(n::nat) ^ 5 mod 10 = n mod 10\"\n  oops\n\nsection {* Task 3: Logic optimisation *}\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 | a = a`\n  `a & a = a`\n *)\nfun opt_ident where\n  \"opt_ident (NOT c) = NOT (opt_ident c)\"\n| \"opt_ident (AND c1 c2) = (\n   let c1' = opt_ident c1 in\n   let c2' = opt_ident c2 in\n   if c1' = c2' then c1' else AND c1' c2')\"\n| \"opt_ident (OR c1 c2) = (\n   let c1' = opt_ident c1 in\n   let c2' = opt_ident c2 in\n   if c1' = c2' then c1' else OR c1' c2')\"\n| \"opt_ident TRUE = TRUE\"\n| \"opt_ident FALSE = FALSE\"\n| \"opt_ident (INPUT i) = INPUT i\"\n\nlemma (* test case *) \n  \"opt_ident (AND (INPUT 1) (OR (INPUT 1) (INPUT 1))) = INPUT 1\" \nby eval\n\ntheorem opt_ident_is_sound: \"opt_ident c \\<sim> c\"\n  oops\n\nfun area :: \"circuit \\<Rightarrow> nat\" where\n  \"area (NOT c) = 1 + area c\"\n| \"area (AND c1 c2) = 1 + area c1 + area c2\"\n| \"area (OR c1 c2) = 1 + area c1 + area c2\"\n| \"area _ = 0\"\n\nsection {* Task 4: More logic optimisation *}\n\nlemma (* test case *) \n  \"opt_redundancy (AND (INPUT 1) (OR (INPUT 1) (INPUT 2))) \n   = INPUT 1\" \n  (* by eval *) oops\nlemma (* test case *) \n  \"opt_redundancy (AND (AND (INPUT 1) (OR (INPUT 1) (INPUT 2)))\n                       (OR (AND (INPUT 1) (OR (INPUT 1) (INPUT 2))) (INPUT 2))) \n   = INPUT 1\" \n  (* by eval *) oops\nlemma (* test case *) \n  \"opt_redundancy (AND (AND (INPUT 1) (OR (INPUT 1) (INPUT 2))) \n                       (OR (INPUT 2) (AND (INPUT 1) (OR (INPUT 1) (INPUT 2))))) \n   = INPUT 1\"\n  (* by eval *) oops\nlemma (* test case *) \n  \"opt_redundancy (AND (AND (AND (INPUT 1) (OR (INPUT 1) (INPUT 2))) \n                            (OR (INPUT 2) (AND (INPUT 1) (OR (INPUT 1) (INPUT 2))))) \n                       (OR (INPUT 1) (INPUT 2))) \n  = INPUT 1\" \n  (* by eval *) oops\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/2022/HSV_tasks_2022.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505325302034, "lm_q2_score": 0.7905303285397349, "lm_q1q2_score": 0.7151536826947479}}
{"text": "theory Clauses imports\n  Main\n  Containers.Containers\nbegin\n\ntype_synonym literal = \"nat \\<times> bool\"\ntype_synonym clause = \"literal set\"\ntype_synonym cnf = \"clause set\"\n\ndatatype bexp\n  = Var nat\n  | not bexp\n  | Or bexp bexp (infixl \"or\" 110)\n  | And bexp bexp (infixl \"and\" 120)\n\ndeclare [[coercion Var]] [[coercion_enabled]]\n\ndeclare SUP_cong_simp[fundef_cong del]\nfunction cnf :: \"bexp \\<Rightarrow> cnf\"\nwhere\n  \"cnf v = {{(v, True)}}\"\n| \"cnf (b and b') = cnf b \\<union> cnf b'\"\n| \"cnf (b or b') = (\\<Union>c \\<in> cnf b. (\\<lambda>c'. c \\<union> c') ` cnf b')\"\n| \"cnf (not v) = {{(v, False)}}\"\n| \"cnf (not (not b)) = cnf b\"\n| \"cnf (not (b and b')) = cnf (not b or not b')\"\n| \"cnf (not (b or b')) = cnf (not b and not b')\"\nby pat_completeness simp_all\ntermination by(relation \"measure (rec_bexp (\\<lambda>_. 1) (\\<lambda>_ n. 3 * n + 1) (\\<lambda>_ _ n m. n + m + 1) (\\<lambda>_ _ n m. n + m + 1))\") simp_all\ndeclare SUP_cong_simp[fundef_cong]\n\ndefinition test \nwhere \n  \"test = \n  (1 and 2) or (not 1 and not 2) or\n  (3 and 4) or (not 3 and not 4) or\n  (5 and 6) or (not 5 and not 6) or\n  (7 and 8) or (not 7 and not 8) or\n  (9 and 10) or (not 9 and not 10) or\n  (11 and 12) or (not 11 and not 12) or\n  (1 and 2) or (3 and 4) or\n  (1 and 3) or (2 and 4)\"\n\nvalue \"cnf test = {}\"\n\ntext \\<open>Sanity check for correctness\\<close>\n\ntype_synonym env = \"nat \\<Rightarrow> bool\"\n\nprimrec eval_bexp :: \"env \\<Rightarrow> bexp \\<Rightarrow> bool\" (\"_ \\<Turnstile> _\" [100, 100] 70)\nwhere\n  \"\\<Phi> \\<Turnstile> v \\<longleftrightarrow> \\<Phi> v\"\n| \"\\<Phi> \\<Turnstile> not b \\<longleftrightarrow> \\<not> \\<Phi> \\<Turnstile> b\"\n| \"\\<Phi> \\<Turnstile> b and b' \\<longleftrightarrow> \\<Phi> \\<Turnstile> b \\<and> \\<Phi> \\<Turnstile> b'\"\n| \"\\<Phi> \\<Turnstile> b or b' \\<longleftrightarrow> \\<Phi> \\<Turnstile> b \\<or> \\<Phi> \\<Turnstile> b'\"\n\ndefinition eval_cnf :: \"env \\<Rightarrow> cnf \\<Rightarrow> bool\" (\"_ \\<turnstile> _\" [100, 100] 70)\nwhere \"\\<Phi> \\<turnstile> F \\<longleftrightarrow> (\\<forall>C \\<in> F. \\<exists>(n, b) \\<in> C. \\<Phi> n = b)\"\n\nlemma cnf_correct: \"\\<Phi> \\<turnstile> cnf b \\<longleftrightarrow> \\<Phi> \\<Turnstile> b\"\nproof(rule sym, induction b rule: cnf.induct)\n  case 2 show ?case by(simp add: \"2.IH\")(auto simp add: eval_cnf_def)\nnext\n  case 3 then show ?case\n    by (auto simp add: \"3.IH\" eval_cnf_def split_beta) blast+\nqed(auto simp add: eval_cnf_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/Evaluation/Containers/ITP-2013/Clauses.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505325302034, "lm_q2_score": 0.7905303236047049, "lm_q1q2_score": 0.7151536782302703}}
{"text": "section \\<open>Exponentiation of ordinals\\<close>\n\ntheory Ordinal_Exp\n  imports Kirby\n\nbegin\n\ntext \\<open>Source: Schl\u00f6der, Julian.  Ordinal Arithmetic; available online at\n    \\url{http://www.math.uni-bonn.de/ag/logik/teaching/2012WS/Set%20theory/oa.pdf}\\<close>\n\ndefinition oexp :: \"[V,V] \\<Rightarrow> V\" (infixr \"\\<up>\" 80)\n  where \"oexp a b \\<equiv> transrec (\\<lambda>f x. if x=0 then 1\n                                    else if Limit x then if a=0 then 0 else SUP \\<xi> \\<in> elts x. f \\<xi>\n                                    else f (\\<Squnion>(elts x)) * a)  b\"\n\ntext \\<open>@{term \"0\\<up>\\<omega> = 1\"} if we don't make a special case for Limit ordinals and zero\\<close>\n\n\nlemma oexp_0_right [simp]: \"\\<alpha>\\<up>0 = 1\"\n  by (simp add: def_transrec [OF oexp_def])\n\nlemma oexp_succ [simp]: \"Ord \\<beta> \\<Longrightarrow> \\<alpha>\\<up>(succ \\<beta>) = \\<alpha>\\<up>\\<beta> * \\<alpha>\"\n  by (simp add: def_transrec [OF oexp_def])\n\nlemma oexp_Limit: \"Limit \\<beta> \\<Longrightarrow> \\<alpha>\\<up>\\<beta> = (if \\<alpha>=0 then 0 else SUP \\<xi> \\<in> elts \\<beta>. \\<alpha>\\<up>\\<xi>)\"\n  by (auto simp: def_transrec [OF oexp_def, of _ \\<beta>])\n\nlemma oexp_1_right [simp]: \"\\<alpha>\\<up>1 = \\<alpha>\"\n  using one_V_def oexp_succ by fastforce\n\nlemma oexp_1 [simp]: \"Ord \\<alpha> \\<Longrightarrow> 1\\<up>\\<alpha> = 1\"\n  by (induction rule: Ord_induct3) (use Limit_def oexp_Limit in auto)\n\nlemma oexp_0 [simp]: \"Ord \\<alpha> \\<Longrightarrow> 0\\<up>\\<alpha> = (if \\<alpha> = 0 then 1 else 0)\"\n  by (induction rule: Ord_induct3) (use Limit_def oexp_Limit in auto)\n\nlemma oexp_eq_0_iff [simp]:\n  assumes \"Ord \\<beta>\" shows \"\\<alpha>\\<up>\\<beta> = 0 \\<longleftrightarrow> \\<alpha>=0 \\<and> \\<beta>\\<noteq>0\"\n  using \\<open>Ord \\<beta>\\<close>\nproof (induction rule: Ord_induct3)\n  case (Limit \\<mu>)\n  then show ?case\n    using Limit_def oexp_Limit by auto\nqed auto\n\nlemma oexp_gt_0_iff [simp]:\n  assumes \"Ord \\<beta>\" shows \"\\<alpha>\\<up>\\<beta> > 0 \\<longleftrightarrow> \\<alpha>>0 \\<or> \\<beta>=0\"\n  by (simp add: assms less_V_def)\n\nlemma ord_of_nat_oexp: \"ord_of_nat (m^n) = ord_of_nat m\\<up>ord_of_nat n\"\nproof (induction n)\n  case (Suc n)\n  then show ?case\n    by (simp add: mult.commute [of m]) (simp add: ord_of_nat_mult)\nqed auto\n\nlemma omega_closed_oexp [intro]:\n  assumes \"\\<alpha> \\<in> elts \\<omega>\" \"\\<beta> \\<in> elts \\<omega>\" shows \"\\<alpha>\\<up>\\<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>\\<up>\\<beta> = ord_of_nat (m^n)\"\n    by (simp add: ord_of_nat_oexp)\n  then show ?thesis\n    by (simp add: \\<omega>_def)\nqed\n\n\nlemma Ord_oexp [simp]:\n  assumes \"Ord \\<alpha>\" \"Ord \\<beta>\" shows \"Ord (\\<alpha>\\<up>\\<beta>)\"\n  using \\<open>Ord \\<beta>\\<close>\nproof (induction rule: Ord_induct3)\n  case (Limit \\<alpha>)\n  then show ?case\n    by (auto simp: oexp_Limit image_iff intro: Ord_Sup)\nqed (auto intro: Ord_mult assms)\n\ntext \\<open>Lemma 3.19\\<close>\nlemma le_oexp:\n  assumes \"Ord \\<alpha>\" \"Ord \\<beta>\" \"\\<beta> \\<noteq> 0\" shows \"\\<alpha> \\<le> \\<alpha>\\<up>\\<beta>\"\n  using \\<open>Ord \\<beta>\\<close> \\<open>\\<beta> \\<noteq> 0\\<close>\nproof (induction rule: Ord_induct3)\n  case (succ \\<beta>)\n  then show ?case\n    by simp (metis \\<open>Ord \\<alpha>\\<close> le_0 le_mult mult.left_neutral oexp_0_right order_refl order_trans)\nnext\n  case (Limit \\<mu>)\n  then show ?case\n    by (metis Limit_def Limit_eq_Sup_self ZFC_in_HOL.Sup_upper eq_iff image_eqI image_ident oexp_1_right oexp_Limit replacement small_elts one_V_def)\nqed auto\n\n\ntext \\<open>Lemma 3.20\\<close>\nlemma le_oexp':\n  assumes \"Ord \\<alpha>\" \"1 < \\<alpha>\" \"Ord \\<beta>\" shows \"\\<beta> \\<le> \\<alpha>\\<up>\\<beta>\"\nproof (cases \"\\<beta> = 0\")\n  case True\n  then show ?thesis\n    by auto\nnext\n  case False\n  show ?thesis\n    using \\<open>Ord \\<beta>\\<close>\n  proof (induction rule: Ord_induct3)\n    case 0\n    then show ?case\n      by auto\n  next\n    case (succ \\<gamma>)\n    then have \"\\<alpha>\\<up>\\<gamma> * 1 < \\<alpha>\\<up>\\<gamma> * \\<alpha>\"\n      using \\<open>Ord \\<alpha>\\<close> \\<open>1 < \\<alpha>\\<close>\n      by (metis le_mult less_V_def mult.right_neutral mult_cancellation not_less_0 oexp_eq_0_iff succ.hyps)\n    then have \" \\<gamma> < \\<alpha>\\<up>succ \\<gamma>\"\n      using succ.IH succ.hyps by auto\n    then show ?case\n      using False \\<open>Ord \\<alpha>\\<close> \\<open>1 < \\<alpha>\\<close> succ\n      by (metis Ord_mem_iff_lt Ord_oexp Ord_succ elts_succ insert_subset less_eq_V_def less_imp_le)\n  next\n    case (Limit \\<mu>)\n    with False \\<open>1 < \\<alpha>\\<close> show ?case\n      by (force simp: Limit_def oexp_Limit intro: elts_succ)\n  qed\nqed\n\n\nlemma oexp_Limit_le:\n  assumes \"\\<beta> < \\<gamma>\" \"Limit \\<gamma>\" \"Ord \\<beta>\" \"\\<alpha> > 0\" shows \"\\<alpha>\\<up>\\<beta> \\<le> \\<alpha>\\<up>\\<gamma>\"\nproof -\n  have \"Ord \\<gamma>\"\n    using Limit_def assms(2) by blast\n  with assms show ?thesis\n    using Ord_mem_iff_lt ZFC_in_HOL.Sup_upper oexp_Limit by auto\nqed\n\nproposition oexp_less:\n  assumes \\<beta>: \"\\<beta> \\<in> elts \\<gamma>\" and \"Ord \\<gamma>\" and \\<alpha>: \"\\<alpha> > 1\" \"Ord \\<alpha>\" shows \"\\<alpha>\\<up>\\<beta> < \\<alpha>\\<up>\\<gamma>\"\nproof -\n  obtain \"\\<beta> < \\<gamma>\" \"Ord \\<beta>\"\n    using Ord_in_Ord OrdmemD assms by auto\n  have gt0: \"\\<alpha>\\<up>\\<beta> > 0\"\n    using \\<open>Ord \\<beta>\\<close> \\<alpha> dual_order.order_iff_strict by auto\n  show ?thesis\n    using \\<open>Ord \\<gamma>\\<close> \\<beta>\n  proof (induction rule: Ord_induct3)\n    case 0\n    then show ?case\n      by auto\n  next\n    case (succ \\<delta>)\n    then consider \"\\<beta> = \\<delta>\" | \"\\<beta> < \\<delta>\"\n      using OrdmemD elts_succ by blast\n    then show ?case\n    proof cases\n      case 1\n      then have \"(\\<alpha>\\<up>\\<beta>) * 1 < (\\<alpha>\\<up>\\<delta>) * \\<alpha>\"\n        using Ord_1 Ord_oexp \\<alpha> gt0 mult_cancel_less_iff succ.hyps by metis\n      then show ?thesis\n        by (simp add: succ.hyps)\n    next\n      case 2\n      then have \"(\\<alpha>\\<up>\\<delta>) * 1 < (\\<alpha>\\<up>\\<delta>) * \\<alpha>\"\n        by (meson Ord_1 Ord_mem_iff_lt Ord_oexp \\<open>Ord \\<beta>\\<close> \\<alpha> gt0 less_trans mult_cancel_less_iff succ)\n      with 2 show ?thesis\n        using Ord_mem_iff_lt \\<open>Ord \\<beta>\\<close> succ by auto\n    qed\n  next\n    case (Limit \\<gamma>)\n    then obtain \"Ord \\<gamma>\" \"succ \\<beta> < \\<gamma>\"\n      using Limit_def Ord_in_Ord OrdmemD assms by auto\n    have \"\\<alpha>\\<up>\\<beta> = (\\<alpha>\\<up>\\<beta>) * 1\"\n      by simp\n    also have \"\\<dots> < (\\<alpha>\\<up>\\<beta>) * \\<alpha>\"\n      using Ord_oexp \\<open>Ord \\<beta>\\<close> assms gt0 mult_cancel_less_iff by blast\n    also have \"\\<dots> = \\<alpha>\\<up>succ \\<beta>\"\n      by (simp add: \\<open>Ord \\<beta>\\<close>)\n    also have \"\\<dots> \\<le> (SUP \\<xi> \\<in> elts \\<gamma>. \\<alpha>\\<up>\\<xi>)\"\n    proof -\n      have \"succ \\<beta> \\<in> elts \\<gamma>\"\n        using Limit.hyps Limit.prems Limit_def by auto\n      then show ?thesis\n        by (simp add: ZFC_in_HOL.Sup_upper)\n    qed\n    finally\n    have \"\\<alpha>\\<up>\\<beta> < (SUP \\<xi> \\<in> elts \\<gamma>. \\<alpha>\\<up>\\<xi>)\" .\n    then show ?case\n      using Limit.hyps oexp_Limit \\<open>\\<alpha> > 1\\<close> by auto\n  qed\nqed\n\ncorollary oexp_less_iff:\n  assumes \"\\<alpha> > 0\" \"Ord \\<alpha>\" \"Ord \\<beta>\" \"Ord \\<gamma>\" shows \"\\<alpha>\\<up>\\<beta> < \\<alpha>\\<up>\\<gamma> \\<longleftrightarrow> \\<beta> \\<in> elts \\<gamma> \\<and> \\<alpha> > 1\"\nproof safe\n  show \"\\<beta> \\<in> elts \\<gamma>\" \"1 < \\<alpha>\"\n    if \"\\<alpha>\\<up>\\<beta> < \\<alpha>\\<up>\\<gamma>\"\n  proof -\n    show \"\\<alpha> > 1\"\n    proof (rule ccontr)\n      assume \"\\<not> \\<alpha> > 1\"\n      then consider \"\\<alpha>=0\" | \"\\<alpha>=1\"\n        using \\<open>Ord \\<alpha>\\<close> less_V_def mem_0_Ord by fastforce\n      then show False\n        by cases (use that \\<open>\\<alpha> > 0\\<close> \\<open>Ord \\<beta>\\<close> \\<open>Ord \\<gamma>\\<close> in \\<open>auto split: if_split_asm\\<close>)\n    qed\n    show \\<beta>: \"\\<beta> \\<in> elts \\<gamma>\"\n    proof (rule ccontr)\n      assume \"\\<beta> \\<notin> elts \\<gamma>\"\n      then have \"\\<gamma> \\<le> \\<beta>\"\n        by (meson Ord_linear_le Ord_mem_iff_lt assms less_le_not_le)\n      then consider \"\\<gamma> = \\<beta>\" | \"\\<gamma> < \\<beta>\"\n        using less_V_def by blast\n      then show False\n      proof cases\n        case 1\n        then show ?thesis\n          using that by blast\n      next\n        case 2\n        with \\<open>\\<alpha> > 1\\<close> have \"\\<alpha>\\<up>\\<gamma> < \\<alpha>\\<up>\\<beta>\"\n          by (simp add: Ord_mem_iff_lt assms oexp_less)\n        with that show ?thesis\n          by auto\n      qed\n    qed\n  qed\n  show \"\\<alpha>\\<up>\\<beta> < \\<alpha>\\<up>\\<gamma>\" if \"\\<beta> \\<in> elts \\<gamma>\" \"1 < \\<alpha>\"\n    using that by (simp add: assms oexp_less)\nqed\n\nlemma \\<omega>_oexp_iff [simp]: \"\\<lbrakk>Ord \\<alpha>; Ord \\<beta>\\<rbrakk> \\<Longrightarrow> \\<omega>\\<up>\\<alpha> = \\<omega>\\<up>\\<beta> \\<longleftrightarrow> \\<alpha>=\\<beta>\"\n  by (metis Ord_\\<omega> Ord_linear \\<omega>_gt1 less_irrefl oexp_less)\n\nlemma Limit_oexp:\n  assumes \"Limit \\<gamma>\" \"Ord \\<alpha>\" \"\\<alpha> > 1\" shows \"Limit (\\<alpha>\\<up>\\<gamma>)\"\n  unfolding Limit_def\nproof safe\n  show O\\<alpha>\\<gamma>: \"Ord (\\<alpha>\\<up>\\<gamma>)\"\n    using Limit_def Ord_oexp \\<open>Limit \\<gamma>\\<close> assms(2) by blast\n  show 0: \"0 \\<in> elts (\\<alpha>\\<up>\\<gamma>)\"\n    using Limit_def oexp_Limit \\<open>Limit \\<gamma>\\<close> \\<open>\\<alpha> > 1\\<close> by fastforce\n  have \"Ord \\<gamma>\"\n    using Limit_def \\<open>Limit \\<gamma>\\<close> by blast\n  fix x\n  assume x: \"x \\<in> elts (\\<alpha>\\<up>\\<gamma>)\"\n  with \\<open>Limit \\<gamma>\\<close> \\<open>\\<alpha> > 1\\<close>\n  obtain \\<beta> where \"\\<beta> < \\<gamma>\" \"Ord \\<beta>\" \"Ord x\" and x\\<beta>: \"x \\<in> elts (\\<alpha>\\<up>\\<beta>)\"\n    apply (simp add: oexp_Limit split: if_split_asm)\n    using Ord_in_Ord OrdmemD \\<open>Ord \\<gamma>\\<close> O\\<alpha>\\<gamma> x by blast\n  then have O\\<alpha>\\<beta>: \"Ord (\\<alpha>\\<up>\\<beta>)\"\n    using Ord_oexp assms(2) by blast\n  have \"\\<beta> \\<in> elts \\<gamma>\"\n    by (simp add: Ord_mem_iff_lt \\<open>Ord \\<beta>\\<close> \\<open>Ord \\<gamma>\\<close> \\<open>\\<beta> < \\<gamma>\\<close>)\n  moreover have \"\\<alpha> \\<noteq> 0\"\n    using \\<open>\\<alpha> > 1\\<close> by blast\n  ultimately have \\<alpha>\\<beta>\\<gamma>: \"\\<alpha>\\<up>\\<beta> \\<le> \\<alpha>\\<up>\\<gamma>\"\n    by (simp add: Sup_upper oexp_Limit \\<open>Limit \\<gamma>\\<close>)\n  have \"succ x \\<le> \\<alpha>\\<up>\\<beta>\"\n    by (simp add: OrdmemD O\\<alpha>\\<beta> \\<open>Ord x\\<close> succ_le_iff x\\<beta>)\n  then consider \"succ x < \\<alpha>\\<up>\\<beta>\" | \"succ x = \\<alpha>\\<up>\\<beta>\"\n    using le_neq_trans by blast\n  then show \"succ x \\<in> elts (\\<alpha>\\<up>\\<gamma>)\"\n  proof cases\n    case 1\n    with \\<alpha>\\<beta>\\<gamma> show ?thesis\n      using O\\<alpha>\\<beta> Ord_mem_iff_lt \\<open>Ord x\\<close> by blast\n  next\n    case 2\n    then have \"succ \\<beta> < \\<gamma>\"\n      using Limit_def OrdmemD \\<open>\\<beta> \\<in> elts \\<gamma>\\<close> assms(1) by auto\n    have ge1: \"1 \\<le> \\<alpha>\\<up>\\<beta>\"\n      by (metis \"2\" Ord_0 \\<open>Ord x\\<close> le_0 le_succ_iff one_V_def)\n    have \"succ x < succ (\\<alpha>\\<up>\\<beta>)\"\n      using \"2\" O\\<alpha>\\<beta> succ_le_iff by auto\n    also have \"\\<dots> \\<le> (\\<alpha>\\<up>\\<beta>) + (\\<alpha>\\<up>\\<beta>)\"\n      using ge1 by (simp add: succ_eq_add1)\n    also have \"\\<dots> = (\\<alpha>\\<up>\\<beta>) * succ (succ 0)\"\n      by (simp add: mult_succ)\n    also have \"\\<dots> \\<le> (\\<alpha>\\<up>\\<beta>) * \\<alpha>\"\n      using O\\<alpha>\\<beta> Ord_succ assms(2) assms(3) one_V_def succ_le_iff by auto\n    also have \"\\<dots> = \\<alpha>\\<up>succ \\<beta>\"\n      by (simp add: \\<open>Ord \\<beta>\\<close>)\n    also have \"\\<dots> \\<le> \\<alpha>\\<up>\\<gamma>\"\n      by (meson Limit_def \\<open>\\<beta> \\<in> elts \\<gamma>\\<close> assms dual_order.order_iff_strict oexp_less)\n  finally show ?thesis\n    by (simp add: \"2\" O\\<alpha>\\<beta> O\\<alpha>\\<gamma> Ord_mem_iff_lt)\n  qed\nqed\n\n\n\nlemma oexp_mono:\n  assumes \\<alpha>: \"Ord \\<alpha>\" \"\\<alpha> \\<noteq> 0\" and \\<beta>: \"Ord \\<beta>\" \"\\<gamma> \\<sqsubseteq> \\<beta>\" shows \"\\<alpha>\\<up>\\<gamma> \\<le> \\<alpha>\\<up>\\<beta>\"\n  using \\<beta>\nproof (induction rule: Ord_induct3)\n  case 0\n  then show ?case\n    by simp\nnext\n  case (succ \\<beta>)\n  with \\<alpha> le_mult show ?case\n    by (auto simp: le_TC_succ)\nnext\n  case (Limit \\<mu>)\n  then have \"\\<alpha>\\<up>\\<gamma> \\<le> \\<Squnion> ((\\<up>) \\<alpha> ` elts \\<mu>)\"\n    using Limit.hyps Ord_less_TC_mem \\<open>\\<alpha> \\<noteq> 0\\<close> le_TC_def by (auto simp: oexp_Limit Limit_def)\n  then show ?case\n    using \\<alpha> by (simp add: oexp_Limit Limit.hyps)\nqed\n\nlemma oexp_mono_le:\n  assumes \"\\<gamma> \\<le> \\<beta>\" \"\\<alpha> \\<noteq> 0\" \"Ord \\<alpha>\" \"Ord \\<beta>\" \"Ord \\<gamma>\" shows \"\\<alpha>\\<up>\\<gamma> \\<le> \\<alpha>\\<up>\\<beta>\"\n  by (simp add: assms oexp_mono vle2 vle_iff_le_Ord)\n\nlemma oexp_sup:\n  assumes \"\\<alpha> \\<noteq> 0\" \"Ord \\<alpha>\" \"Ord \\<beta>\" \"Ord \\<gamma>\" shows \"\\<alpha>\\<up>(\\<beta> \\<squnion> \\<gamma>) = \\<alpha>\\<up>\\<beta> \\<squnion> \\<alpha>\\<up>\\<gamma>\"\n  by (metis Ord_linear_le assms oexp_mono_le sup.absorb2 sup.orderE)\n\nlemma oexp_Sup:\n  assumes \\<alpha>: \"\\<alpha> \\<noteq> 0\" \"Ord \\<alpha>\" and X: \"X \\<subseteq> ON\" \"small X\" \"X \\<noteq> {}\" shows \"\\<alpha>\\<up>\\<Squnion> X = \\<Squnion> ((\\<up>) \\<alpha> ` X)\"\nproof (rule order_antisym)\n  show \"\\<Squnion> ((\\<up>) \\<alpha> ` X) \\<le> \\<alpha>\\<up>\\<Squnion> X\"\n    by (metis ON_imp_Ord Ord_Sup ZFC_in_HOL.Sup_upper assms cSUP_least oexp_mono_le)\nnext\n  have \"Ord (Sup X)\"\n    using Ord_Sup X by auto\n  then show \"\\<alpha>\\<up>\\<Squnion> X \\<le> \\<Squnion> ((\\<up>) \\<alpha> ` X)\"\n  proof (cases rule: Ord_cases)\n    case 0\n    then show ?thesis\n      using X dual_order.antisym by fastforce\n  next\n    case (succ \\<beta>)\n    then show ?thesis\n      using ZFC_in_HOL.Sup_upper X succ_in_Sup_Ord by auto\n  next\n    case limit\n    show ?thesis\n    proof (clarsimp simp: assms oexp_Limit limit)\n      fix x y z\n      assume x: \"x \\<in> elts (\\<alpha> \\<up> y)\" and \"z \\<in> X\" \"y \\<in> elts z\"\n      then have \"\\<alpha> \\<up> y \\<le> \\<alpha> \\<up> z\"\n        by (meson ON_imp_Ord Ord_in_Ord OrdmemD \\<alpha> \\<open>X \\<subseteq> ON\\<close> le_less oexp_mono_le)\n      with x have \"x \\<in> elts (\\<alpha> \\<up> z)\" by blast\n      then show \"\\<exists>u\\<in>X. x \\<in> elts (\\<alpha> \\<up> u)\"\n        using \\<open>z \\<in> X\\<close> by blast\n    qed\n  qed\nqed\n\n\nlemma omega_le_Limit:\n  assumes \"Limit \\<mu>\" shows \"\\<omega> \\<le> \\<mu>\"\nproof\n  fix \\<rho>\n  assume \"\\<rho> \\<in> elts \\<omega>\"\n  then obtain n where \"\\<rho> = ord_of_nat n\"\n    using elts_\\<omega> by auto\n  have \"ord_of_nat n \\<in> elts \\<mu>\"\n    by (induction n) (use Limit_def assms in auto)\n  then show \"\\<rho> \\<in> elts \\<mu>\"\n    using \\<open>\\<rho> = ord_of_nat n\\<close> by auto\nqed\n\nlemma finite_omega_power [simp]:\n  assumes \"1 < n\" \"n \\<in> elts \\<omega>\" shows \"n\\<up>\\<omega> = \\<omega>\"\nproof (rule order_antisym)\n  have \"\\<Squnion> ((\\<up>) (ord_of_nat k) ` elts \\<omega>) \\<le> \\<omega>\" for k\n  proof (induction k)\n    case 0\n    then show ?case\n      by auto\n  next\n    case (Suc k)\n    then show ?case\n      by (metis Ord_\\<omega> OrdmemD Sup_eq_0_iff ZFC_in_HOL.SUP_le_iff le_0 le_less omega_closed_oexp ord_of_nat_\\<omega>)\n  qed\n  then show \"n\\<up>\\<omega> \\<le> \\<omega>\"\n    using assms\n    by (simp add: elts_\\<omega> oexp_Limit) metis\n  show \"\\<omega> \\<le> n\\<up>\\<omega>\"\n    using Ord_in_Ord assms le_oexp' by blast\nqed\n\n\nproposition oexp_add:\n  assumes \"Ord \\<alpha>\" \"Ord \\<beta>\" \"Ord \\<gamma>\" shows \"\\<alpha>\\<up>(\\<beta> + \\<gamma>) = \\<alpha>\\<up>\\<beta> * \\<alpha>\\<up>\\<gamma>\"\nproof (cases \\<open>\\<alpha> = 0\\<close>)\n  case True\n  then show ?thesis\n    using assms by simp\nnext\n  case False\n  show ?thesis\n    using \\<open>Ord \\<gamma>\\<close>\n  proof (induction rule: Ord_induct3)\n    case 0\n    then show ?case\n      by auto\n  next\n    case (succ \\<xi>)\n    then show ?case\n      using \\<open>Ord \\<beta>\\<close> by (auto simp: plus_V_succ_right mult.assoc)\n  next\n    case (Limit \\<mu>)\n    have \"\\<alpha>\\<up>(\\<beta> + (SUP \\<xi>\\<in>elts \\<mu>. \\<xi>)) = (SUP \\<xi>\\<in>elts (\\<beta> + \\<mu>). \\<alpha>\\<up>\\<xi>)\"\n      by (simp add: Limit.hyps oexp_Limit assms False)\n    also have \"\\<dots> = (SUP \\<xi> \\<in> {\\<xi>. Ord \\<xi> \\<and> \\<beta> + \\<xi> < \\<beta> + \\<mu>}. \\<alpha>\\<up>(\\<beta> + \\<xi>))\"\n    proof (rule Sup_eq_Sup)\n      show \"(\\<lambda>\\<xi>. \\<alpha>\\<up>(\\<beta> + \\<xi>)) ` {\\<xi>. Ord \\<xi> \\<and> \\<beta> + \\<xi> < \\<beta> + \\<mu>} \\<subseteq> (\\<up>) \\<alpha> ` elts (\\<beta> + \\<mu>)\"\n        using Limit.hyps Limit_def Ord_mem_iff_lt imageI by blast\n      fix x\n      assume \"x \\<in> (\\<up>) \\<alpha> ` elts (\\<beta> + \\<mu>)\"\n      then obtain \\<xi> where \\<xi>: \"\\<xi> \\<in> elts (\\<beta> + \\<mu>)\" and x: \"x = \\<alpha>\\<up>\\<xi>\"\n        by auto\n      have \"\\<exists>\\<gamma>. Ord \\<gamma> \\<and> \\<gamma> < \\<mu> \\<and> \\<alpha>\\<up>\\<xi> \\<le> \\<alpha>\\<up>(\\<beta> + \\<gamma>)\"\n      proof (rule mem_plus_V_E [OF \\<xi>])\n        assume \"\\<xi> \\<in> elts \\<beta>\"\n        then have \"\\<alpha>\\<up>\\<xi> \\<le> \\<alpha>\\<up>\\<beta>\"\n          by (meson arg_subset_TC assms False le_TC_def less_TC_def oexp_mono vsubsetD)\n        with zero_less_Limit [OF \\<open>Limit \\<mu>\\<close>]\n        show \"\\<exists>\\<gamma>. Ord \\<gamma> \\<and> \\<gamma> < \\<mu> \\<and> \\<alpha>\\<up>\\<xi> \\<le> \\<alpha>\\<up>(\\<beta> + \\<gamma>)\"\n          by force\n      next\n        fix \\<delta>\n        assume \"\\<delta> \\<in> elts \\<mu>\" and \"\\<xi> = \\<beta> + \\<delta>\"\n        have \"Ord \\<delta>\"\n          using Limit.hyps Limit_def Ord_in_Ord \\<open>\\<delta> \\<in> elts \\<mu>\\<close> by blast\n        moreover have \"\\<delta> < \\<mu>\"\n          using Limit.hyps Limit_def OrdmemD \\<open>\\<delta> \\<in> elts \\<mu>\\<close> by auto\n        ultimately show \"\\<exists>\\<gamma>. Ord \\<gamma> \\<and> \\<gamma> < \\<mu> \\<and> \\<alpha>\\<up>\\<xi> \\<le> \\<alpha>\\<up>(\\<beta> + \\<gamma>)\"\n          using \\<open>\\<xi> = \\<beta> + \\<delta>\\<close> by blast\n      qed\n      then show \"\\<exists>y\\<in>(\\<lambda>\\<xi>. \\<alpha>\\<up>(\\<beta> + \\<xi>)) ` {\\<xi>. Ord \\<xi> \\<and> \\<beta> + \\<xi> < \\<beta> + \\<mu>}. x \\<le> y\"\n        using x by auto\n    qed auto\n    also have \"\\<dots> = (SUP \\<xi>\\<in>elts \\<mu>. \\<alpha>\\<up>(\\<beta> + \\<xi>))\"\n      using \\<open>Limit \\<mu>\\<close>\n      by (simp add: Ord_Collect_lt Limit_def)\n    also have \"\\<dots> = (SUP \\<xi>\\<in>elts \\<mu>. \\<alpha>\\<up>\\<beta> * \\<alpha>\\<up>\\<xi>)\"\n      using Limit.IH by auto\n    also have \"\\<dots> = \\<alpha>\\<up>\\<beta> * \\<alpha>\\<up>(SUP \\<xi>\\<in>elts \\<mu>. \\<xi>)\"\n      using \\<open>\\<alpha> \\<noteq> 0\\<close> Limit.hyps\n      by (simp add: image_image oexp_Limit mult_Sup_distrib)\n    finally show ?case .\n  qed\nqed\n\nproposition oexp_mult:\n  assumes \"Ord \\<alpha>\" \"Ord \\<beta>\" \"Ord \\<gamma>\" shows \"\\<alpha>\\<up>(\\<beta> * \\<gamma>) = (\\<alpha>\\<up>\\<beta>)\\<up>\\<gamma>\"\nproof (cases \"\\<alpha> = 0 \\<or> \\<beta> = 0\")\n  case True\n  then show ?thesis\n    by (auto simp: \\<open>Ord \\<beta>\\<close> \\<open>Ord \\<gamma>\\<close>)\nnext\n  case False\n  show ?thesis\n    using \\<open>Ord \\<gamma>\\<close>\n  proof (induction rule: Ord_induct3)\n    case 0\n    then show ?case\n      by auto\n  next\n    case succ\n    then show ?case\n      using assms by (auto simp: mult_succ oexp_add)\n  next\n    case (Limit \\<mu>)\n    have Lim: \"Limit (\\<Squnion> ((*) \\<beta> ` elts \\<mu>))\"\n      unfolding Limit_def\n    proof (intro conjI allI impI)\n      show \"Ord (\\<Squnion> ((*) \\<beta> ` elts \\<mu>))\"\n        using Limit.hyps Limit_def Ord_in_Ord \\<open>Ord \\<beta>\\<close> by (auto intro: Ord_Sup)\n      have \"succ 0 \\<in> elts \\<mu>\"\n        using Limit.hyps Limit_def by blast\n      then show \"0 \\<in> elts (\\<Squnion> ((*) \\<beta> ` elts \\<mu>))\"\n        using False \\<open>Ord \\<beta>\\<close> mem_0_Ord by force\n      show \"succ y \\<in> elts (\\<Squnion> ((*) \\<beta> ` elts \\<mu>))\"\n        if \"y \\<in> elts (\\<Squnion> ((*) \\<beta> ` elts \\<mu>))\" for y\n        using that False Limit.hyps\n        apply (clarsimp simp: Limit_def)\n        by (metis Ord_in_Ord Ord_linear Ord_mem_iff_lt Ord_mult Ord_succ assms(2) less_V_def mult_cancellation mult_succ not_add_mem_right succ_le_iff succ_ne_self)\n    qed\n    have \"\\<alpha>\\<up>(\\<beta> * (SUP \\<xi>\\<in>elts \\<mu>. \\<xi>)) = \\<alpha>\\<up>\\<Squnion> ((*) \\<beta> ` elts \\<mu>)\"\n      by (simp add: mult_Sup_distrib)\n    also have \"\\<dots> = \\<Squnion> (\\<Union>x\\<in>elts \\<mu>. (\\<up>) \\<alpha> ` elts (\\<beta> * x))\"\n      using False Lim oexp_Limit by fastforce\n    also have \"\\<dots> = (SUP x\\<in>elts \\<mu>. \\<alpha>\\<up>(\\<beta> * x))\"\n    proof (rule Sup_eq_Sup)\n      show \"(\\<lambda>x. \\<alpha>\\<up>(\\<beta> * x)) ` elts \\<mu> \\<subseteq> (\\<Union>x\\<in>elts \\<mu>. (\\<up>) \\<alpha> ` elts (\\<beta> * x))\"\n        using \\<open>Ord \\<alpha>\\<close> \\<open>Ord \\<beta>\\<close> False Limit\n        apply clarsimp\n        by (metis Limit_def elts_succ imageI insertI1 mem_0_Ord mult_add_mem_0)\n      show \"\\<exists>y\\<in>(\\<lambda>x. \\<alpha>\\<up>(\\<beta> * x)) ` elts \\<mu>. x \\<le> y\"\n        if \"x \\<in> (\\<Union>x\\<in>elts \\<mu>. (\\<up>) \\<alpha> ` elts (\\<beta> * x))\" for x\n        using that \\<open>Ord \\<alpha>\\<close> \\<open>Ord \\<beta>\\<close> False Limit\n        by clarsimp (metis Limit_def Ord_in_Ord Ord_mult VWO_TC_le mem_imp_VWO oexp_mono)\n    qed auto\n    also have \"\\<dots> = \\<Squnion> ((\\<up>) (\\<alpha>\\<up>\\<beta>) ` elts (SUP \\<xi>\\<in>elts \\<mu>. \\<xi>))\"\n      using Limit.IH Limit.hyps by auto\n    also have \"\\<dots> = (\\<alpha>\\<up>\\<beta>)\\<up>(SUP \\<xi>\\<in>elts \\<mu>. \\<xi>)\"\n      using False Limit.hyps oexp_Limit \\<open>Ord \\<beta>\\<close> by auto\n    finally show ?case .\n  qed\nqed\n\nlemma Limit_omega_oexp:\n  assumes \"Ord \\<delta>\" \"\\<delta> \\<noteq> 0\"\n  shows \"Limit (\\<omega>\\<up>\\<delta>)\"\n  using assms\nproof (cases \\<delta> rule: Ord_cases)\n  case 0\n  then show ?thesis\n    using assms(2) by blast\nnext\n  case (succ l)\n  have *: \"succ \\<beta> \\<in> elts (\\<omega>\\<up>l * n + \\<omega>\\<up>l)\"\n    if n: \"n \\<in> elts \\<omega>\" and \\<beta>: \"\\<beta> \\<in> elts (\\<omega>\\<up>l * n)\" for n \\<beta>\n  proof -\n    obtain \"Ord n\" \"Ord \\<beta>\"\n      by (meson Ord_\\<omega> Ord_in_Ord Ord_mult Ord_oexp \\<beta> n succ(1))\n    obtain oo: \"Ord (\\<omega>\\<up>l)\" \"Ord (\\<omega>\\<up>l * n)\"\n      by (simp add: \\<open>Ord n\\<close> succ(1))\n    moreover have f4: \"\\<beta> < \\<omega>\\<up>l * n\"\n      using oo Ord_mem_iff_lt \\<open>Ord \\<beta>\\<close> \\<open>\\<beta> \\<in> elts (\\<omega>\\<up>l * n)\\<close> by blast\n    moreover have f5: \"Ord (succ \\<beta>)\"\n      using \\<open>Ord \\<beta>\\<close> by blast\n    moreover have \"\\<omega>\\<up>l \\<noteq> 0\"\n      using oexp_eq_0_iff omega_nonzero succ(1) by blast\n    ultimately show ?thesis\n      by (metis add_less_cancel_left Ord_\\<omega> Ord_add Ord_mem_iff_lt OrdmemD \\<open>Ord \\<beta>\\<close> add.right_neutral dual_order.strict_trans2 oexp_gt_0_iff succ(1) succ_le_iff zero_in_omega)\n  qed\n  show ?thesis\n    using succ\n    apply (clarsimp simp: Limit_def mem_0_Ord)\n    apply (simp add: mult_Limit)\n    by (metis * mult_succ succ_in_omega)\nnext\n  case limit\n  then show ?thesis\n    by (metis Limit_oexp Ord_\\<omega> OrdmemD one_V_def succ_in_omega zero_in_omega)\nqed\n\nlemma oexp_mult_commute:\n  fixes j::nat\n  assumes \"Ord \\<alpha>\"\n  shows \"(\\<alpha> \\<up> j) * \\<alpha> = \\<alpha> * (\\<alpha> \\<up> j)\"\nproof -\n  have \"(\\<alpha> \\<up> j) * \\<alpha> = \\<alpha> \\<up> (1 + ord_of_nat j)\"\n    by (simp add: one_V_def)\n  also have \"... = \\<alpha> * (\\<alpha> \\<up> j)\"\n    by (simp add: assms oexp_add)\n  finally show ?thesis .\nqed\n\nlemma oexp_\\<omega>_Limit: \"Limit \\<beta> \\<Longrightarrow> \\<omega>\\<up>\\<beta> = (SUP \\<xi> \\<in> elts \\<beta>. \\<omega>\\<up>\\<xi>)\"\n  by (simp add: oexp_Limit)\n\nlemma \\<omega>_power_succ_gtr: \"Ord \\<alpha> \\<Longrightarrow> \\<omega> \\<up> \\<alpha> * ord_of_nat n < \\<omega> \\<up> succ \\<alpha>\"\n  by (simp add: OrdmemD)\n\nlemma countable_oexp:\n  assumes \\<nu>: \"\\<alpha> \\<in> elts \\<omega>1\" \n  shows \"\\<omega> \\<up> \\<alpha> \\<in> elts \\<omega>1\"\nproof -\n  have \"Ord \\<alpha>\"\n    using Ord_\\<omega>1 Ord_in_Ord assms by blast\n  then show ?thesis\n    using assms\n  proof (induction rule: Ord_induct3)\n    case 0\n    then show ?case\n      by (simp add: Ord_mem_iff_lt)\n  next\n    case (succ \\<alpha>)\n    then have \"countable (elts (\\<omega> \\<up> \\<alpha> * \\<omega>))\"\n      by (simp add: succ_in_Limit_iff countable_mult less_\\<omega>1_imp_countable)\n    then show ?case\n      using Ord_mem_iff_lt countable_iff_less_\\<omega>1 succ.hyps by auto\n  next\n    case (Limit \\<alpha>)\n    with Ord_\\<omega>1 have \"countable (\\<Union>\\<beta>\\<in>elts \\<alpha>. elts (\\<omega> \\<up> \\<beta>))\" \"Ord (\\<omega> \\<up> \\<Squnion> (elts \\<alpha>))\"\n      by (force simp: Limit_def intro: Ord_trans less_\\<omega>1_imp_countable)+\n    then have \"\\<omega> \\<up> \\<Squnion> (elts \\<alpha>) < \\<omega>1\"\n      using Limit.hyps countable_iff_less_\\<omega>1 oexp_Limit by fastforce\n    then show ?case\n      using Limit.hyps Limit_def Ord_mem_iff_lt by auto\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/ZFC_in_HOL/Ordinal_Exp.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9046505376715775, "lm_q2_score": 0.7905303112671294, "lm_q1q2_score": 0.7151536711334882}}
{"text": "(*  Title:      HOL/Algebra/Ideal.thy\n    Author:     Stephan Hohe, TU Muenchen\n*)\n\ntheory Ideal\nimports Ring AbelCoset\nbegin\n\nsection {* Ideals *}\n\nsubsection {* Definitions *}\n\nsubsubsection {* General definition *}\n\nlocale ideal = additive_subgroup I R + ring R for I and R (structure) +\n  assumes I_l_closed: \"\\<lbrakk>a \\<in> I; x \\<in> carrier R\\<rbrakk> \\<Longrightarrow> x \\<otimes> a \\<in> I\"\n    and I_r_closed: \"\\<lbrakk>a \\<in> I; x \\<in> carrier R\\<rbrakk> \\<Longrightarrow> a \\<otimes> x \\<in> I\"\n\nsublocale ideal \\<subseteq> abelian_subgroup I R\n  apply (intro abelian_subgroupI3 abelian_group.intro)\n    apply (rule ideal.axioms, rule ideal_axioms)\n   apply (rule abelian_group.axioms, rule ring.axioms, rule ideal.axioms, rule ideal_axioms)\n  apply (rule abelian_group.axioms, rule ring.axioms, rule ideal.axioms, rule ideal_axioms)\n  done\n\nlemma (in ideal) is_ideal: \"ideal I R\"\n  by (rule ideal_axioms)\n\nlemma idealI:\n  fixes R (structure)\n  assumes \"ring R\"\n  assumes a_subgroup: \"subgroup I \\<lparr>carrier = carrier R, mult = add R, one = zero R\\<rparr>\"\n    and I_l_closed: \"\\<And>a x. \\<lbrakk>a \\<in> I; x \\<in> carrier R\\<rbrakk> \\<Longrightarrow> x \\<otimes> a \\<in> I\"\n    and I_r_closed: \"\\<And>a x. \\<lbrakk>a \\<in> I; x \\<in> carrier R\\<rbrakk> \\<Longrightarrow> a \\<otimes> x \\<in> I\"\n  shows \"ideal I R\"\nproof -\n  interpret ring R by fact\n  show ?thesis  apply (intro ideal.intro ideal_axioms.intro additive_subgroupI)\n     apply (rule a_subgroup)\n    apply (rule is_ring)\n   apply (erule (1) I_l_closed)\n  apply (erule (1) I_r_closed)\n  done\nqed\n\n\nsubsubsection (in ring) {* Ideals Generated by a Subset of @{term \"carrier R\"} *}\n\ndefinition genideal :: \"_ \\<Rightarrow> 'a set \\<Rightarrow> 'a set\"  (\"Idl\\<index> _\" [80] 79)\n  where \"genideal R S = Inter {I. ideal I R \\<and> S \\<subseteq> I}\"\n\nsubsubsection {* Principal Ideals *}\n\nlocale principalideal = ideal +\n  assumes generate: \"\\<exists>i \\<in> carrier R. I = Idl {i}\"\n\nlemma (in principalideal) is_principalideal: \"principalideal I R\"\n  by (rule principalideal_axioms)\n\nlemma principalidealI:\n  fixes R (structure)\n  assumes \"ideal I R\"\n    and generate: \"\\<exists>i \\<in> carrier R. I = Idl {i}\"\n  shows \"principalideal I R\"\nproof -\n  interpret ideal I R by fact\n  show ?thesis\n    by (intro principalideal.intro principalideal_axioms.intro)\n      (rule is_ideal, rule generate)\nqed\n\n\nsubsubsection {* Maximal Ideals *}\n\nlocale maximalideal = ideal +\n  assumes I_notcarr: \"carrier R \\<noteq> I\"\n    and I_maximal: \"\\<lbrakk>ideal J R; I \\<subseteq> J; J \\<subseteq> carrier R\\<rbrakk> \\<Longrightarrow> J = I \\<or> J = carrier R\"\n\nlemma (in maximalideal) is_maximalideal: \"maximalideal I R\"\n  by (rule maximalideal_axioms)\n\nlemma maximalidealI:\n  fixes R\n  assumes \"ideal I R\"\n    and I_notcarr: \"carrier R \\<noteq> I\"\n    and I_maximal: \"\\<And>J. \\<lbrakk>ideal J R; I \\<subseteq> J; J \\<subseteq> carrier R\\<rbrakk> \\<Longrightarrow> J = I \\<or> J = carrier R\"\n  shows \"maximalideal I R\"\nproof -\n  interpret ideal I R by fact\n  show ?thesis\n    by (intro maximalideal.intro maximalideal_axioms.intro)\n      (rule is_ideal, rule I_notcarr, rule I_maximal)\nqed\n\n\nsubsubsection {* Prime Ideals *}\n\nlocale primeideal = ideal + cring +\n  assumes I_notcarr: \"carrier R \\<noteq> I\"\n    and I_prime: \"\\<lbrakk>a \\<in> carrier R; b \\<in> carrier R; a \\<otimes> b \\<in> I\\<rbrakk> \\<Longrightarrow> a \\<in> I \\<or> b \\<in> I\"\n\nlemma (in primeideal) is_primeideal: \"primeideal I R\"\n  by (rule primeideal_axioms)\n\nlemma primeidealI:\n  fixes R (structure)\n  assumes \"ideal I R\"\n    and \"cring R\"\n    and I_notcarr: \"carrier R \\<noteq> I\"\n    and I_prime: \"\\<And>a b. \\<lbrakk>a \\<in> carrier R; b \\<in> carrier R; a \\<otimes> b \\<in> I\\<rbrakk> \\<Longrightarrow> a \\<in> I \\<or> b \\<in> I\"\n  shows \"primeideal I R\"\nproof -\n  interpret ideal I R by fact\n  interpret cring R by fact\n  show ?thesis\n    by (intro primeideal.intro primeideal_axioms.intro)\n      (rule is_ideal, rule is_cring, rule I_notcarr, rule I_prime)\nqed\n\nlemma primeidealI2:\n  fixes R (structure)\n  assumes \"additive_subgroup I R\"\n    and \"cring R\"\n    and I_l_closed: \"\\<And>a x. \\<lbrakk>a \\<in> I; x \\<in> carrier R\\<rbrakk> \\<Longrightarrow> x \\<otimes> a \\<in> I\"\n    and I_r_closed: \"\\<And>a x. \\<lbrakk>a \\<in> I; x \\<in> carrier R\\<rbrakk> \\<Longrightarrow> a \\<otimes> x \\<in> I\"\n    and I_notcarr: \"carrier R \\<noteq> I\"\n    and I_prime: \"\\<And>a b. \\<lbrakk>a \\<in> carrier R; b \\<in> carrier R; a \\<otimes> b \\<in> I\\<rbrakk> \\<Longrightarrow> a \\<in> I \\<or> b \\<in> I\"\n  shows \"primeideal I R\"\nproof -\n  interpret additive_subgroup I R by fact\n  interpret cring R by fact\n  show ?thesis apply (intro_locales)\n    apply (intro ideal_axioms.intro)\n    apply (erule (1) I_l_closed)\n    apply (erule (1) I_r_closed)\n    apply (intro primeideal_axioms.intro)\n    apply (rule I_notcarr)\n    apply (erule (2) I_prime)\n    done\nqed\n\n\nsubsection {* Special Ideals *}\n\nlemma (in ring) zeroideal: \"ideal {\\<zero>} R\"\n  apply (intro idealI subgroup.intro)\n        apply (rule is_ring)\n       apply simp+\n    apply (fold a_inv_def, simp)\n   apply simp+\n  done\n\nlemma (in ring) oneideal: \"ideal (carrier R) R\"\n  by (rule idealI) (auto intro: is_ring add.subgroupI)\n\nlemma (in \"domain\") zeroprimeideal: \"primeideal {\\<zero>} R\"\n  apply (intro primeidealI)\n     apply (rule zeroideal)\n    apply (rule domain.axioms, rule domain_axioms)\n   defer 1\n   apply (simp add: integral)\nproof (rule ccontr, simp)\n  assume \"carrier R = {\\<zero>}\"\n  then have \"\\<one> = \\<zero>\" by (rule one_zeroI)\n  with one_not_zero show False by simp\nqed\n\n\nsubsection {* General Ideal Properies *}\n\nlemma (in ideal) one_imp_carrier:\n  assumes I_one_closed: \"\\<one> \\<in> I\"\n  shows \"I = carrier R\"\n  apply (rule)\n  apply (rule)\n  apply (rule a_Hcarr, simp)\nproof\n  fix x\n  assume xcarr: \"x \\<in> carrier R\"\n  with I_one_closed have \"x \\<otimes> \\<one> \\<in> I\" by (intro I_l_closed)\n  with xcarr show \"x \\<in> I\" by simp\nqed\n\nlemma (in ideal) Icarr:\n  assumes iI: \"i \\<in> I\"\n  shows \"i \\<in> carrier R\"\n  using iI by (rule a_Hcarr)\n\n\nsubsection {* Intersection of Ideals *}\n\ntext {* \\paragraph{Intersection of two ideals} The intersection of any\n  two ideals is again an ideal in @{term R} *}\nlemma (in ring) i_intersect:\n  assumes \"ideal I R\"\n  assumes \"ideal J R\"\n  shows \"ideal (I \\<inter> J) R\"\nproof -\n  interpret ideal I R by fact\n  interpret ideal J R by fact\n  show ?thesis\n    apply (intro idealI subgroup.intro)\n          apply (rule is_ring)\n         apply (force simp add: a_subset)\n        apply (simp add: a_inv_def[symmetric])\n       apply simp\n      apply (simp add: a_inv_def[symmetric])\n     apply (clarsimp, rule)\n      apply (fast intro: ideal.I_l_closed ideal.intro assms)+\n    apply (clarsimp, rule)\n     apply (fast intro: ideal.I_r_closed ideal.intro assms)+\n    done\nqed\n\ntext {* The intersection of any Number of Ideals is again\n        an Ideal in @{term R} *}\nlemma (in ring) i_Intersect:\n  assumes Sideals: \"\\<And>I. I \\<in> S \\<Longrightarrow> ideal I R\"\n    and notempty: \"S \\<noteq> {}\"\n  shows \"ideal (Inter S) R\"\n  apply (unfold_locales)\n  apply (simp_all add: Inter_eq)\n        apply rule unfolding mem_Collect_eq defer 1\n        apply rule defer 1\n        apply rule defer 1\n        apply (fold a_inv_def, rule) defer 1\n        apply rule defer 1\n        apply rule defer 1\nproof -\n  fix x y\n  assume \"\\<forall>I\\<in>S. x \\<in> I\"\n  then have xI: \"\\<And>I. I \\<in> S \\<Longrightarrow> x \\<in> I\" by simp\n  assume \"\\<forall>I\\<in>S. y \\<in> I\"\n  then have yI: \"\\<And>I. I \\<in> S \\<Longrightarrow> y \\<in> I\" by simp\n\n  fix J\n  assume JS: \"J \\<in> S\"\n  interpret ideal J R by (rule Sideals[OF JS])\n  from xI[OF JS] and yI[OF JS] show \"x \\<oplus> y \\<in> J\" by (rule a_closed)\nnext\n  fix J\n  assume JS: \"J \\<in> S\"\n  interpret ideal J R by (rule Sideals[OF JS])\n  show \"\\<zero> \\<in> J\" by simp\nnext\n  fix x\n  assume \"\\<forall>I\\<in>S. x \\<in> I\"\n  then have xI: \"\\<And>I. I \\<in> S \\<Longrightarrow> x \\<in> I\" by simp\n\n  fix J\n  assume JS: \"J \\<in> S\"\n  interpret ideal J R by (rule Sideals[OF JS])\n\n  from xI[OF JS] show \"\\<ominus> x \\<in> J\" by (rule a_inv_closed)\nnext\n  fix x y\n  assume \"\\<forall>I\\<in>S. x \\<in> I\"\n  then have xI: \"\\<And>I. I \\<in> S \\<Longrightarrow> x \\<in> I\" by simp\n  assume ycarr: \"y \\<in> carrier R\"\n\n  fix J\n  assume JS: \"J \\<in> S\"\n  interpret ideal J R by (rule Sideals[OF JS])\n\n  from xI[OF JS] and ycarr show \"y \\<otimes> x \\<in> J\" by (rule I_l_closed)\nnext\n  fix x y\n  assume \"\\<forall>I\\<in>S. x \\<in> I\"\n  then have xI: \"\\<And>I. I \\<in> S \\<Longrightarrow> x \\<in> I\" by simp\n  assume ycarr: \"y \\<in> carrier R\"\n\n  fix J\n  assume JS: \"J \\<in> S\"\n  interpret ideal J R by (rule Sideals[OF JS])\n\n  from xI[OF JS] and ycarr show \"x \\<otimes> y \\<in> J\" by (rule I_r_closed)\nnext\n  fix x\n  assume \"\\<forall>I\\<in>S. x \\<in> I\"\n  then have xI: \"\\<And>I. I \\<in> S \\<Longrightarrow> x \\<in> I\" by simp\n\n  from notempty have \"\\<exists>I0. I0 \\<in> S\" by blast\n  then obtain I0 where I0S: \"I0 \\<in> S\" by auto\n\n  interpret ideal I0 R by (rule Sideals[OF I0S])\n\n  from xI[OF I0S] have \"x \\<in> I0\" .\n  with a_subset show \"x \\<in> carrier R\" by fast\nnext\n\nqed\n\n\nsubsection {* Addition of Ideals *}\n\nlemma (in ring) add_ideals:\n  assumes idealI: \"ideal I R\"\n      and idealJ: \"ideal J R\"\n  shows \"ideal (I <+> J) R\"\n  apply (rule ideal.intro)\n    apply (rule add_additive_subgroups)\n     apply (intro ideal.axioms[OF idealI])\n    apply (intro ideal.axioms[OF idealJ])\n   apply (rule is_ring)\n  apply (rule ideal_axioms.intro)\n   apply (simp add: set_add_defs, clarsimp) defer 1\n   apply (simp add: set_add_defs, clarsimp) defer 1\nproof -\n  fix x i j\n  assume xcarr: \"x \\<in> carrier R\"\n    and iI: \"i \\<in> I\"\n    and jJ: \"j \\<in> J\"\n  from xcarr ideal.Icarr[OF idealI iI] ideal.Icarr[OF idealJ jJ]\n  have c: \"(i \\<oplus> j) \\<otimes> x = (i \\<otimes> x) \\<oplus> (j \\<otimes> x)\"\n    by algebra\n  from xcarr and iI have a: \"i \\<otimes> x \\<in> I\"\n    by (simp add: ideal.I_r_closed[OF idealI])\n  from xcarr and jJ have b: \"j \\<otimes> x \\<in> J\"\n    by (simp add: ideal.I_r_closed[OF idealJ])\n  from a b c show \"\\<exists>ha\\<in>I. \\<exists>ka\\<in>J. (i \\<oplus> j) \\<otimes> x = ha \\<oplus> ka\"\n    by fast\nnext\n  fix x i j\n  assume xcarr: \"x \\<in> carrier R\"\n    and iI: \"i \\<in> I\"\n    and jJ: \"j \\<in> J\"\n  from xcarr ideal.Icarr[OF idealI iI] ideal.Icarr[OF idealJ jJ]\n  have c: \"x \\<otimes> (i \\<oplus> j) = (x \\<otimes> i) \\<oplus> (x \\<otimes> j)\" by algebra\n  from xcarr and iI have a: \"x \\<otimes> i \\<in> I\"\n    by (simp add: ideal.I_l_closed[OF idealI])\n  from xcarr and jJ have b: \"x \\<otimes> j \\<in> J\"\n    by (simp add: ideal.I_l_closed[OF idealJ])\n  from a b c show \"\\<exists>ha\\<in>I. \\<exists>ka\\<in>J. x \\<otimes> (i \\<oplus> j) = ha \\<oplus> ka\"\n    by fast\nqed\n\n\nsubsection (in ring) {* Ideals generated by a subset of @{term \"carrier R\"} *}\n\ntext {* @{term genideal} generates an ideal *}\nlemma (in ring) genideal_ideal:\n  assumes Scarr: \"S \\<subseteq> carrier R\"\n  shows \"ideal (Idl S) R\"\nunfolding genideal_def\nproof (rule i_Intersect, fast, simp)\n  from oneideal and Scarr\n  show \"\\<exists>I. ideal I R \\<and> S \\<le> I\" by fast\nqed\n\nlemma (in ring) genideal_self:\n  assumes \"S \\<subseteq> carrier R\"\n  shows \"S \\<subseteq> Idl S\"\n  unfolding genideal_def by fast\n\nlemma (in ring) genideal_self':\n  assumes carr: \"i \\<in> carrier R\"\n  shows \"i \\<in> Idl {i}\"\nproof -\n  from carr have \"{i} \\<subseteq> Idl {i}\" by (fast intro!: genideal_self)\n  then show \"i \\<in> Idl {i}\" by fast\nqed\n\ntext {* @{term genideal} generates the minimal ideal *}\nlemma (in ring) genideal_minimal:\n  assumes a: \"ideal I R\"\n    and b: \"S \\<subseteq> I\"\n  shows \"Idl S \\<subseteq> I\"\n  unfolding genideal_def by rule (elim InterD, simp add: a b)\n\ntext {* Generated ideals and subsets *}\nlemma (in ring) Idl_subset_ideal:\n  assumes Iideal: \"ideal I R\"\n    and Hcarr: \"H \\<subseteq> carrier R\"\n  shows \"(Idl H \\<subseteq> I) = (H \\<subseteq> I)\"\nproof\n  assume a: \"Idl H \\<subseteq> I\"\n  from Hcarr have \"H \\<subseteq> Idl H\" by (rule genideal_self)\n  with a show \"H \\<subseteq> I\" by simp\nnext\n  fix x\n  assume \"H \\<subseteq> I\"\n  with Iideal have \"I \\<in> {I. ideal I R \\<and> H \\<subseteq> I}\" by fast\n  then show \"Idl H \\<subseteq> I\" unfolding genideal_def by fast\nqed\n\nlemma (in ring) subset_Idl_subset:\n  assumes Icarr: \"I \\<subseteq> carrier R\"\n    and HI: \"H \\<subseteq> I\"\n  shows \"Idl H \\<subseteq> Idl I\"\nproof -\n  from HI and genideal_self[OF Icarr] have HIdlI: \"H \\<subseteq> Idl I\"\n    by fast\n\n  from Icarr have Iideal: \"ideal (Idl I) R\"\n    by (rule genideal_ideal)\n  from HI and Icarr have \"H \\<subseteq> carrier R\"\n    by fast\n  with Iideal have \"(H \\<subseteq> Idl I) = (Idl H \\<subseteq> Idl I)\"\n    by (rule Idl_subset_ideal[symmetric])\n\n  with HIdlI show \"Idl H \\<subseteq> Idl I\" by simp\nqed\n\nlemma (in ring) Idl_subset_ideal':\n  assumes acarr: \"a \\<in> carrier R\" and bcarr: \"b \\<in> carrier R\"\n  shows \"(Idl {a} \\<subseteq> Idl {b}) = (a \\<in> Idl {b})\"\n  apply (subst Idl_subset_ideal[OF genideal_ideal[of \"{b}\"], of \"{a}\"])\n    apply (fast intro: bcarr, fast intro: acarr)\n  apply fast\n  done\n\nlemma (in ring) genideal_zero: \"Idl {\\<zero>} = {\\<zero>}\"\n  apply rule\n   apply (rule genideal_minimal[OF zeroideal], simp)\n  apply (simp add: genideal_self')\n  done\n\nlemma (in ring) genideal_one: \"Idl {\\<one>} = carrier R\"\nproof -\n  interpret ideal \"Idl {\\<one>}\" \"R\" by (rule genideal_ideal) fast\n  show \"Idl {\\<one>} = carrier R\"\n  apply (rule, rule a_subset)\n  apply (simp add: one_imp_carrier genideal_self')\n  done\nqed\n\n\ntext {* Generation of Principal Ideals in Commutative Rings *}\n\ndefinition cgenideal :: \"_ \\<Rightarrow> 'a \\<Rightarrow> 'a set\"  (\"PIdl\\<index> _\" [80] 79)\n  where \"cgenideal R a = {x \\<otimes>\\<^bsub>R\\<^esub> a | x. x \\<in> carrier R}\"\n\ntext {* genhideal (?) really generates an ideal *}\nlemma (in cring) cgenideal_ideal:\n  assumes acarr: \"a \\<in> carrier R\"\n  shows \"ideal (PIdl a) R\"\n  apply (unfold cgenideal_def)\n  apply (rule idealI[OF is_ring])\n     apply (rule subgroup.intro)\n        apply simp_all\n        apply (blast intro: acarr)\n        apply clarsimp defer 1\n        defer 1\n        apply (fold a_inv_def, clarsimp) defer 1\n        apply clarsimp defer 1\n        apply clarsimp defer 1\nproof -\n  fix x y\n  assume xcarr: \"x \\<in> carrier R\"\n    and ycarr: \"y \\<in> carrier R\"\n  note carr = acarr xcarr ycarr\n\n  from carr have \"x \\<otimes> a \\<oplus> y \\<otimes> a = (x \\<oplus> y) \\<otimes> a\"\n    by (simp add: l_distr)\n  with carr show \"\\<exists>z. x \\<otimes> a \\<oplus> y \\<otimes> a = z \\<otimes> a \\<and> z \\<in> carrier R\"\n    by fast\nnext\n  from l_null[OF acarr, symmetric] and zero_closed\n  show \"\\<exists>x. \\<zero> = x \\<otimes> a \\<and> x \\<in> carrier R\" by fast\nnext\n  fix x\n  assume xcarr: \"x \\<in> carrier R\"\n  note carr = acarr xcarr\n\n  from carr have \"\\<ominus> (x \\<otimes> a) = (\\<ominus> x) \\<otimes> a\"\n    by (simp add: l_minus)\n  with carr show \"\\<exists>z. \\<ominus> (x \\<otimes> a) = z \\<otimes> a \\<and> z \\<in> carrier R\"\n    by fast\nnext\n  fix x y\n  assume xcarr: \"x \\<in> carrier R\"\n     and ycarr: \"y \\<in> carrier R\"\n  note carr = acarr xcarr ycarr\n  \n  from carr have \"y \\<otimes> a \\<otimes> x = (y \\<otimes> x) \\<otimes> a\"\n    by (simp add: m_assoc) (simp add: m_comm)\n  with carr show \"\\<exists>z. y \\<otimes> a \\<otimes> x = z \\<otimes> a \\<and> z \\<in> carrier R\"\n    by fast\nnext\n  fix x y\n  assume xcarr: \"x \\<in> carrier R\"\n     and ycarr: \"y \\<in> carrier R\"\n  note carr = acarr xcarr ycarr\n\n  from carr have \"x \\<otimes> (y \\<otimes> a) = (x \\<otimes> y) \\<otimes> a\"\n    by (simp add: m_assoc)\n  with carr show \"\\<exists>z. x \\<otimes> (y \\<otimes> a) = z \\<otimes> a \\<and> z \\<in> carrier R\"\n    by fast\nqed\n\nlemma (in ring) cgenideal_self:\n  assumes icarr: \"i \\<in> carrier R\"\n  shows \"i \\<in> PIdl i\"\n  unfolding cgenideal_def\nproof simp\n  from icarr have \"i = \\<one> \\<otimes> i\"\n    by simp\n  with icarr show \"\\<exists>x. i = x \\<otimes> i \\<and> x \\<in> carrier R\"\n    by fast\nqed\n\ntext {* @{const \"cgenideal\"} is minimal *}\n\nlemma (in ring) cgenideal_minimal:\n  assumes \"ideal J R\"\n  assumes aJ: \"a \\<in> J\"\n  shows \"PIdl a \\<subseteq> J\"\nproof -\n  interpret ideal J R by fact\n  show ?thesis\n    unfolding cgenideal_def\n    apply rule\n    apply clarify\n    using aJ\n    apply (erule I_l_closed)\n    done\nqed\n\nlemma (in cring) cgenideal_eq_genideal:\n  assumes icarr: \"i \\<in> carrier R\"\n  shows \"PIdl i = Idl {i}\"\n  apply rule\n   apply (intro cgenideal_minimal)\n    apply (rule genideal_ideal, fast intro: icarr)\n   apply (rule genideal_self', fast intro: icarr)\n  apply (intro genideal_minimal)\n   apply (rule cgenideal_ideal [OF icarr])\n  apply (simp, rule cgenideal_self [OF icarr])\n  done\n\nlemma (in cring) cgenideal_eq_rcos: \"PIdl i = carrier R #> i\"\n  unfolding cgenideal_def r_coset_def by fast\n\nlemma (in cring) cgenideal_is_principalideal:\n  assumes icarr: \"i \\<in> carrier R\"\n  shows \"principalideal (PIdl i) R\"\n  apply (rule principalidealI)\n  apply (rule cgenideal_ideal [OF icarr])\nproof -\n  from icarr have \"PIdl i = Idl {i}\"\n    by (rule cgenideal_eq_genideal)\n  with icarr show \"\\<exists>i'\\<in>carrier R. PIdl i = Idl {i'}\"\n    by fast\nqed\n\n\nsubsection {* Union of Ideals *}\n\nlemma (in ring) union_genideal:\n  assumes idealI: \"ideal I R\"\n    and idealJ: \"ideal J R\"\n  shows \"Idl (I \\<union> J) = I <+> J\"\n  apply rule\n   apply (rule ring.genideal_minimal)\n     apply (rule is_ring)\n    apply (rule add_ideals[OF idealI idealJ])\n   apply (rule)\n   apply (simp add: set_add_defs) apply (elim disjE) defer 1 defer 1\n   apply (rule) apply (simp add: set_add_defs genideal_def) apply clarsimp defer 1\nproof -\n  fix x\n  assume xI: \"x \\<in> I\"\n  have ZJ: \"\\<zero> \\<in> J\"\n    by (intro additive_subgroup.zero_closed) (rule ideal.axioms[OF idealJ])\n  from ideal.Icarr[OF idealI xI] have \"x = x \\<oplus> \\<zero>\"\n    by algebra\n  with xI and ZJ show \"\\<exists>h\\<in>I. \\<exists>k\\<in>J. x = h \\<oplus> k\"\n    by fast\nnext\n  fix x\n  assume xJ: \"x \\<in> J\"\n  have ZI: \"\\<zero> \\<in> I\"\n    by (intro additive_subgroup.zero_closed, rule ideal.axioms[OF idealI])\n  from ideal.Icarr[OF idealJ xJ] have \"x = \\<zero> \\<oplus> x\"\n    by algebra\n  with ZI and xJ show \"\\<exists>h\\<in>I. \\<exists>k\\<in>J. x = h \\<oplus> k\"\n    by fast\nnext\n  fix i j K\n  assume iI: \"i \\<in> I\"\n    and jJ: \"j \\<in> J\"\n    and idealK: \"ideal K R\"\n    and IK: \"I \\<subseteq> K\"\n    and JK: \"J \\<subseteq> K\"\n  from iI and IK have iK: \"i \\<in> K\" by fast\n  from jJ and JK have jK: \"j \\<in> K\" by fast\n  from iK and jK show \"i \\<oplus> j \\<in> K\"\n    by (intro additive_subgroup.a_closed) (rule ideal.axioms[OF idealK])\nqed\n\n\nsubsection {* Properties of Principal Ideals *}\n\ntext {* @{text \"\\<zero>\"} generates the zero ideal *}\nlemma (in ring) zero_genideal: \"Idl {\\<zero>} = {\\<zero>}\"\n  apply rule\n  apply (simp add: genideal_minimal zeroideal)\n  apply (fast intro!: genideal_self)\n  done\n\ntext {* @{text \"\\<one>\"} generates the unit ideal *}\nlemma (in ring) one_genideal: \"Idl {\\<one>} = carrier R\"\nproof -\n  have \"\\<one> \\<in> Idl {\\<one>}\"\n    by (simp add: genideal_self')\n  then show \"Idl {\\<one>} = carrier R\"\n    by (intro ideal.one_imp_carrier) (fast intro: genideal_ideal)\nqed\n\n\ntext {* The zero ideal is a principal ideal *}\ncorollary (in ring) zeropideal: \"principalideal {\\<zero>} R\"\n  apply (rule principalidealI)\n   apply (rule zeroideal)\n  apply (blast intro!: zero_genideal[symmetric])\n  done\n\ntext {* The unit ideal is a principal ideal *}\ncorollary (in ring) onepideal: \"principalideal (carrier R) R\"\n  apply (rule principalidealI)\n   apply (rule oneideal)\n  apply (blast intro!: one_genideal[symmetric])\n  done\n\n\ntext {* Every principal ideal is a right coset of the carrier *}\nlemma (in principalideal) rcos_generate:\n  assumes \"cring R\"\n  shows \"\\<exists>x\\<in>I. I = carrier R #> x\"\nproof -\n  interpret cring R by fact\n  from generate obtain i where icarr: \"i \\<in> carrier R\" and I1: \"I = Idl {i}\"\n    by fast+\n\n  from icarr and genideal_self[of \"{i}\"] have \"i \\<in> Idl {i}\"\n    by fast\n  then have iI: \"i \\<in> I\" by (simp add: I1)\n\n  from I1 icarr have I2: \"I = PIdl i\"\n    by (simp add: cgenideal_eq_genideal)\n\n  have \"PIdl i = carrier R #> i\"\n    unfolding cgenideal_def r_coset_def by fast\n\n  with I2 have \"I = carrier R #> i\"\n    by simp\n\n  with iI show \"\\<exists>x\\<in>I. I = carrier R #> x\"\n    by fast\nqed\n\n\nsubsection {* Prime Ideals *}\n\nlemma (in ideal) primeidealCD:\n  assumes \"cring R\"\n  assumes notprime: \"\\<not> primeideal I R\"\n  shows \"carrier R = I \\<or> (\\<exists>a b. a \\<in> carrier R \\<and> b \\<in> carrier R \\<and> a \\<otimes> b \\<in> I \\<and> a \\<notin> I \\<and> b \\<notin> I)\"\nproof (rule ccontr, clarsimp)\n  interpret cring R by fact\n  assume InR: \"carrier R \\<noteq> I\"\n    and \"\\<forall>a. a \\<in> carrier R \\<longrightarrow> (\\<forall>b. a \\<otimes> b \\<in> I \\<longrightarrow> b \\<in> carrier R \\<longrightarrow> a \\<in> I \\<or> b \\<in> I)\"\n  then have I_prime: \"\\<And> a b. \\<lbrakk>a \\<in> carrier R; b \\<in> carrier R; a \\<otimes> b \\<in> I\\<rbrakk> \\<Longrightarrow> a \\<in> I \\<or> b \\<in> I\"\n    by simp\n  have \"primeideal I R\"\n    apply (rule primeideal.intro [OF is_ideal is_cring])\n    apply (rule primeideal_axioms.intro)\n     apply (rule InR)\n    apply (erule (2) I_prime)\n    done\n  with notprime show False by simp\nqed\n\nlemma (in ideal) primeidealCE:\n  assumes \"cring R\"\n  assumes notprime: \"\\<not> primeideal I R\"\n  obtains \"carrier R = I\"\n    | \"\\<exists>a b. a \\<in> carrier R \\<and> b \\<in> carrier R \\<and> a \\<otimes> b \\<in> I \\<and> a \\<notin> I \\<and> b \\<notin> I\"\nproof -\n  interpret R: cring R by fact\n  assume \"carrier R = I ==> thesis\"\n    and \"\\<exists>a b. a \\<in> carrier R \\<and> b \\<in> carrier R \\<and> a \\<otimes> b \\<in> I \\<and> a \\<notin> I \\<and> b \\<notin> I \\<Longrightarrow> thesis\"\n  then show thesis using primeidealCD [OF R.is_cring notprime] by blast\nqed\n\ntext {* If @{text \"{\\<zero>}\"} is a prime ideal of a commutative ring, the ring is a domain *}\nlemma (in cring) zeroprimeideal_domainI:\n  assumes pi: \"primeideal {\\<zero>} R\"\n  shows \"domain R\"\n  apply (rule domain.intro, rule is_cring)\n  apply (rule domain_axioms.intro)\nproof (rule ccontr, simp)\n  interpret primeideal \"{\\<zero>}\" \"R\" by (rule pi)\n  assume \"\\<one> = \\<zero>\"\n  then have \"carrier R = {\\<zero>}\" by (rule one_zeroD)\n  from this[symmetric] and I_notcarr show False\n    by simp\nnext\n  interpret primeideal \"{\\<zero>}\" \"R\" by (rule pi)\n  fix a b\n  assume ab: \"a \\<otimes> b = \\<zero>\" and carr: \"a \\<in> carrier R\" \"b \\<in> carrier R\"\n  from ab have abI: \"a \\<otimes> b \\<in> {\\<zero>}\"\n    by fast\n  with carr have \"a \\<in> {\\<zero>} \\<or> b \\<in> {\\<zero>}\"\n    by (rule I_prime)\n  then show \"a = \\<zero> \\<or> b = \\<zero>\" by simp\nqed\n\ncorollary (in cring) domain_eq_zeroprimeideal: \"domain R = primeideal {\\<zero>} R\"\n  apply rule\n   apply (erule domain.zeroprimeideal)\n  apply (erule zeroprimeideal_domainI)\n  done\n\n\nsubsection {* Maximal Ideals *}\n\nlemma (in ideal) helper_I_closed:\n  assumes carr: \"a \\<in> carrier R\" \"x \\<in> carrier R\" \"y \\<in> carrier R\"\n    and axI: \"a \\<otimes> x \\<in> I\"\n  shows \"a \\<otimes> (x \\<otimes> y) \\<in> I\"\nproof -\n  from axI and carr have \"(a \\<otimes> x) \\<otimes> y \\<in> I\"\n    by (simp add: I_r_closed)\n  also from carr have \"(a \\<otimes> x) \\<otimes> y = a \\<otimes> (x \\<otimes> y)\"\n    by (simp add: m_assoc)\n  finally show \"a \\<otimes> (x \\<otimes> y) \\<in> I\" .\nqed\n\nlemma (in ideal) helper_max_prime:\n  assumes \"cring R\"\n  assumes acarr: \"a \\<in> carrier R\"\n  shows \"ideal {x\\<in>carrier R. a \\<otimes> x \\<in> I} R\"\nproof -\n  interpret cring R by fact\n  show ?thesis apply (rule idealI)\n    apply (rule cring.axioms[OF is_cring])\n    apply (rule subgroup.intro)\n    apply (simp, fast)\n    apply clarsimp apply (simp add: r_distr acarr)\n    apply (simp add: acarr)\n    apply (simp add: a_inv_def[symmetric], clarify) defer 1\n    apply clarsimp defer 1\n    apply (fast intro!: helper_I_closed acarr)\n  proof -\n    fix x\n    assume xcarr: \"x \\<in> carrier R\"\n      and ax: \"a \\<otimes> x \\<in> I\"\n    from ax and acarr xcarr\n    have \"\\<ominus>(a \\<otimes> x) \\<in> I\" by simp\n    also from acarr xcarr\n    have \"\\<ominus>(a \\<otimes> x) = a \\<otimes> (\\<ominus>x)\" by algebra\n    finally show \"a \\<otimes> (\\<ominus>x) \\<in> I\" .\n    from acarr have \"a \\<otimes> \\<zero> = \\<zero>\" by simp\n  next\n    fix x y\n    assume xcarr: \"x \\<in> carrier R\"\n      and ycarr: \"y \\<in> carrier R\"\n      and ayI: \"a \\<otimes> y \\<in> I\"\n    from ayI and acarr xcarr ycarr have \"a \\<otimes> (y \\<otimes> x) \\<in> I\"\n      by (simp add: helper_I_closed)\n    moreover\n    from xcarr ycarr have \"y \\<otimes> x = x \\<otimes> y\"\n      by (simp add: m_comm)\n    ultimately\n    show \"a \\<otimes> (x \\<otimes> y) \\<in> I\" by simp\n  qed\nqed\n\ntext {* In a cring every maximal ideal is prime *}\nlemma (in cring) maximalideal_is_prime:\n  assumes \"maximalideal I R\"\n  shows \"primeideal I R\"\nproof -\n  interpret maximalideal I R by fact\n  show ?thesis apply (rule ccontr)\n    apply (rule primeidealCE)\n    apply (rule is_cring)\n    apply assumption\n    apply (simp add: I_notcarr)\n  proof -\n    assume \"\\<exists>a b. a \\<in> carrier R \\<and> b \\<in> carrier R \\<and> a \\<otimes> b \\<in> I \\<and> a \\<notin> I \\<and> b \\<notin> I\"\n    then obtain a b where\n      acarr: \"a \\<in> carrier R\" and\n      bcarr: \"b \\<in> carrier R\" and\n      abI: \"a \\<otimes> b \\<in> I\" and\n      anI: \"a \\<notin> I\" and\n      bnI: \"b \\<notin> I\" by fast\n    def J \\<equiv> \"{x\\<in>carrier R. a \\<otimes> x \\<in> I}\"\n    \n    from is_cring and acarr have idealJ: \"ideal J R\"\n      unfolding J_def by (rule helper_max_prime)\n    \n    have IsubJ: \"I \\<subseteq> J\"\n    proof\n      fix x\n      assume xI: \"x \\<in> I\"\n      with acarr have \"a \\<otimes> x \\<in> I\"\n        by (intro I_l_closed)\n      with xI[THEN a_Hcarr] show \"x \\<in> J\"\n        unfolding J_def by fast\n    qed\n    \n    from abI and acarr bcarr have \"b \\<in> J\"\n      unfolding J_def by fast\n    with bnI have JnI: \"J \\<noteq> I\" by fast\n    from acarr\n    have \"a = a \\<otimes> \\<one>\" by algebra\n    with anI have \"a \\<otimes> \\<one> \\<notin> I\" by simp\n    with one_closed have \"\\<one> \\<notin> J\"\n      unfolding J_def by fast\n    then have Jncarr: \"J \\<noteq> carrier R\" by fast\n    \n    interpret ideal J R by (rule idealJ)\n    \n    have \"J = I \\<or> J = carrier R\"\n      apply (intro I_maximal)\n      apply (rule idealJ)\n      apply (rule IsubJ)\n      apply (rule a_subset)\n      done\n    \n    with JnI and Jncarr show False by simp\n  qed\nqed\n\n\nsubsection {* Derived Theorems *}\n\n--\"A non-zero cring that has only the two trivial ideals is a field\"\nlemma (in cring) trivialideals_fieldI:\n  assumes carrnzero: \"carrier R \\<noteq> {\\<zero>}\"\n    and haveideals: \"{I. ideal I R} = {{\\<zero>}, carrier R}\"\n  shows \"field R\"\n  apply (rule cring_fieldI)\n  apply (rule, rule, rule)\n   apply (erule Units_closed)\n  defer 1\n    apply rule\n  defer 1\nproof (rule ccontr, simp)\n  assume zUnit: \"\\<zero> \\<in> Units R\"\n  then have a: \"\\<zero> \\<otimes> inv \\<zero> = \\<one>\" by (rule Units_r_inv)\n  from zUnit have \"\\<zero> \\<otimes> inv \\<zero> = \\<zero>\"\n    by (intro l_null) (rule Units_inv_closed)\n  with a[symmetric] have \"\\<one> = \\<zero>\" by simp\n  then have \"carrier R = {\\<zero>}\" by (rule one_zeroD)\n  with carrnzero show False by simp\nnext\n  fix x\n  assume xcarr': \"x \\<in> carrier R - {\\<zero>}\"\n  then have xcarr: \"x \\<in> carrier R\" by fast\n  from xcarr' have xnZ: \"x \\<noteq> \\<zero>\" by fast\n  from xcarr have xIdl: \"ideal (PIdl x) R\"\n    by (intro cgenideal_ideal) fast\n\n  from xcarr have \"x \\<in> PIdl x\"\n    by (intro cgenideal_self) fast\n  with xnZ have \"PIdl x \\<noteq> {\\<zero>}\" by fast\n  with haveideals have \"PIdl x = carrier R\"\n    by (blast intro!: xIdl)\n  then have \"\\<one> \\<in> PIdl x\" by simp\n  then have \"\\<exists>y. \\<one> = y \\<otimes> x \\<and> y \\<in> carrier R\"\n    unfolding cgenideal_def by blast\n  then obtain y where ycarr: \" y \\<in> carrier R\" and ylinv: \"\\<one> = y \\<otimes> x\"\n    by fast+\n  from ylinv and xcarr ycarr have yrinv: \"\\<one> = x \\<otimes> y\"\n    by (simp add: m_comm)\n  from ycarr and ylinv[symmetric] and yrinv[symmetric]\n  have \"\\<exists>y \\<in> carrier R. y \\<otimes> x = \\<one> \\<and> x \\<otimes> y = \\<one>\" by fast\n  with xcarr show \"x \\<in> Units R\"\n    unfolding Units_def by fast\nqed\n\nlemma (in field) all_ideals: \"{I. ideal I R} = {{\\<zero>}, carrier R}\"\n  apply (rule, rule)\nproof -\n  fix I\n  assume a: \"I \\<in> {I. ideal I R}\"\n  then interpret ideal I R by simp\n\n  show \"I \\<in> {{\\<zero>}, carrier R}\"\n  proof (cases \"\\<exists>a. a \\<in> I - {\\<zero>}\")\n    case True\n    then obtain a where aI: \"a \\<in> I\" and anZ: \"a \\<noteq> \\<zero>\"\n      by fast+\n    from aI[THEN a_Hcarr] anZ have aUnit: \"a \\<in> Units R\"\n      by (simp add: field_Units)\n    then have a: \"a \\<otimes> inv a = \\<one>\" by (rule Units_r_inv)\n    from aI and aUnit have \"a \\<otimes> inv a \\<in> I\"\n      by (simp add: I_r_closed del: Units_r_inv)\n    then have oneI: \"\\<one> \\<in> I\" by (simp add: a[symmetric])\n\n    have \"carrier R \\<subseteq> I\"\n    proof\n      fix x\n      assume xcarr: \"x \\<in> carrier R\"\n      with oneI have \"\\<one> \\<otimes> x \\<in> I\" by (rule I_r_closed)\n      with xcarr show \"x \\<in> I\" by simp\n    qed\n    with a_subset have \"I = carrier R\" by fast\n    then show \"I \\<in> {{\\<zero>}, carrier R}\" by fast\n  next\n    case False\n    then have IZ: \"\\<And>a. a \\<in> I \\<Longrightarrow> a = \\<zero>\" by simp\n\n    have a: \"I \\<subseteq> {\\<zero>}\"\n    proof\n      fix x\n      assume \"x \\<in> I\"\n      then have \"x = \\<zero>\" by (rule IZ)\n      then show \"x \\<in> {\\<zero>}\" by fast\n    qed\n\n    have \"\\<zero> \\<in> I\" by simp\n    then have \"{\\<zero>} \\<subseteq> I\" by fast\n\n    with a have \"I = {\\<zero>}\" by fast\n    then show \"I \\<in> {{\\<zero>}, carrier R}\" by fast\n  qed\nqed (simp add: zeroideal oneideal)\n\n--\"Jacobson Theorem 2.2\"\nlemma (in cring) trivialideals_eq_field:\n  assumes carrnzero: \"carrier R \\<noteq> {\\<zero>}\"\n  shows \"({I. ideal I R} = {{\\<zero>}, carrier R}) = field R\"\n  by (fast intro!: trivialideals_fieldI[OF carrnzero] field.all_ideals)\n\n\ntext {* Like zeroprimeideal for domains *}\nlemma (in field) zeromaximalideal: \"maximalideal {\\<zero>} R\"\n  apply (rule maximalidealI)\n    apply (rule zeroideal)\nproof-\n  from one_not_zero have \"\\<one> \\<notin> {\\<zero>}\" by simp\n  with one_closed show \"carrier R \\<noteq> {\\<zero>}\" by fast\nnext\n  fix J\n  assume Jideal: \"ideal J R\"\n  then have \"J \\<in> {I. ideal I R}\" by fast\n  with all_ideals show \"J = {\\<zero>} \\<or> J = carrier R\"\n    by simp\nqed\n\nlemma (in cring) zeromaximalideal_fieldI:\n  assumes zeromax: \"maximalideal {\\<zero>} R\"\n  shows \"field R\"\n  apply (rule trivialideals_fieldI, rule maximalideal.I_notcarr[OF zeromax])\n  apply rule apply clarsimp defer 1\n   apply (simp add: zeroideal oneideal)\nproof -\n  fix J\n  assume Jn0: \"J \\<noteq> {\\<zero>}\"\n    and idealJ: \"ideal J R\"\n  interpret ideal J R by (rule idealJ)\n  have \"{\\<zero>} \\<subseteq> J\" by (rule ccontr) simp\n  from zeromax and idealJ and this and a_subset\n  have \"J = {\\<zero>} \\<or> J = carrier R\"\n    by (rule maximalideal.I_maximal)\n  with Jn0 show \"J = carrier R\"\n    by simp\nqed\n\nlemma (in cring) zeromaximalideal_eq_field: \"maximalideal {\\<zero>} R = field R\"\n  apply rule\n   apply (erule zeromaximalideal_fieldI)\n  apply (erule field.zeromaximalideal)\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/HOL/Algebra/Ideal.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942377652497, "lm_q2_score": 0.8031738057795402, "lm_q1q2_score": 0.7150610112095105}}
{"text": "theory BTree_Height\n  imports BTree\nbegin\n\nsection \"Maximum and minimum height\"\n\ntext \"Textbooks usually provide some proofs relating the maxmimum and minimum height of the BTree\nfor a given number of nodes. We therefore introduce this counting and show the respective proofs.\"\n\nsubsection \"Definition of node/size\"\n\nthm BTree.btree.size\n  (* the automatically derived size is a bit weird for our purposes *)\nvalue \"size (Node [(Leaf, (0::nat)), (Node [(Leaf, 1), (Leaf, 10)] Leaf, 12), (Leaf, 30), (Leaf, 100)] Leaf)\"\n\n\ntext \"The default size function does not suit our needs as it regards the length of the list in each node.\n We would like to count the number of nodes in the tree only, not regarding the number of keys.\"\n\n(* we want a different counting method,\n  namely only the number of nodes in a tree *)\n\n(* TODO what if we count Leafs as nodes? *)\n\nfun nodes::\"'a btree \\<Rightarrow> nat\" where\n  \"nodes Leaf = 0\" |\n  \"nodes (Node ts t) = 1 + (\\<Sum>t\\<leftarrow>subtrees ts. nodes t) + (nodes t)\"\n\nvalue \"nodes (Node [(Leaf, (0::nat)), (Node [(Leaf, 1), (Leaf, 10)] Leaf, 12), (Leaf, 30), (Leaf, 100)] Leaf)\"\n\n\n(* maximum number of nodes for given height *)\nsubsection \"Maximum number of nodes for a given height\"\n\n\nlemma sum_list_replicate: \"sum_list (replicate n c) = n*c\"\n  apply(induction n)\n   apply(auto simp add: ring_class.ring_distribs(2))\n  done\n\nabbreviation \"bound k h \\<equiv> ((k+1)^h - 1)\"\n\nlemma nodes_height_upper_bound:\n  \"\\<lbrakk>order k t; bal t\\<rbrakk> \\<Longrightarrow> nodes t * (2*k) \\<le> bound (2*k) (height t)\"\nproof(induction t rule: nodes.induct)\n  case (2 ts t)\n  let ?sub_height = \"((2 * k + 1) ^ height t - 1)\"\n  have \"sum_list (map nodes (subtrees ts)) * (2*k) =\n        sum_list (map (\\<lambda>t. nodes t * (2 * k)) (subtrees ts))\"\n    using sum_list_mult_const by metis\n  also have \"\\<dots> \\<le> sum_list (map (\\<lambda>x.?sub_height) (subtrees ts))\"\n    using 2\n    using sum_list_mono[of \"subtrees ts\" \"\\<lambda>t. nodes t * (2 * k)\" \"\\<lambda>x. bound (2 * k) (height t)\"]\n    by (metis bal.simps(2) order.simps(2))\n  also have \"\\<dots> = sum_list (replicate (length ts) ?sub_height)\"\n    using map_replicate_const[of ?sub_height \"subtrees ts\"] length_map\n    by simp\n  also have \"\\<dots> = (length ts)*(?sub_height)\"\n    using sum_list_replicate by simp\n  also have \"\\<dots> \\<le> (2*k)*(?sub_height)\"\n    using \"2.prems\"(1)\n    by simp\n  finally have \"sum_list (map nodes (subtrees ts))*(2*k) \\<le> ?sub_height*(2*k)\"\n    by simp\n  moreover have \"(nodes t)*(2*k) \\<le> ?sub_height\"\n    using 2 by simp\n  ultimately have \"(nodes (Node ts t))*(2*k) \\<le>\n         2*k\n        + ?sub_height * (2*k)\n        + ?sub_height\"\n    unfolding nodes.simps add_mult_distrib\n    by linarith\n  also have \"\\<dots> =  2*k + (2*k)*((2 * k + 1) ^ height t) - 2*k + (2 * k + 1) ^ height t - 1\"\n    by (simp add: diff_mult_distrib2 mult.assoc mult.commute)\n  also have \"\\<dots> = (2*k)*((2 * k + 1) ^ height t) + (2 * k + 1) ^ height t - 1\"\n    by simp\n  also have \"\\<dots> = (2*k+1)^(Suc(height t)) - 1\"\n    by simp\n  finally show ?case\n    by (metis \"2.prems\"(2) height_bal_tree)\nqed simp\n\ntext \"To verify our lower bound is sharp, we compare it to the height of artificially constructed\nfull trees.\"\n\nfun full_node::\"nat \\<Rightarrow> 'a \\<Rightarrow> nat \\<Rightarrow> 'a btree\" where\n  \"full_node k c 0 = Leaf\"|\n  \"full_node k c (Suc n) = (Node (replicate (2*k) ((full_node k c n),c)) (full_node k c n))\"\n\nvalue \"let k = (2::nat) in map (\\<lambda>x. nodes x * 2*k) (map (full_node k (1::nat)) [0,1,2,3,4])\"\nvalue \"let k = (2::nat) in map (\\<lambda>x. ((2*k+(1::nat))^(x)-1)) [0,1,2,3,4]\"\n\nlemma compow_comp_id: \"c > 0 \\<Longrightarrow> f \\<circ> f = f \\<Longrightarrow> (f ^^ c) = f\"\n  apply(induction c)\n   apply auto\n  by fastforce\n\n(* required only for the fold definition of height *)\nlemma compow_id_point: \"f x = x \\<Longrightarrow> (f ^^ c) x = x\"\n  apply(induction c)\n   apply auto\n  done\n\nlemma height_full_node: \"height (full_node k a h) = h\"\n  apply(induction k a h rule: full_node.induct)\n   apply (auto simp add: set_replicate_conv_if)\n  done\n\nlemma bal_full_node: \"bal (full_node k a h)\"\n  apply(induction k a h rule: full_node.induct)\n   apply auto\n  done\n\nlemma order_full_node: \"order k (full_node k a h)\"\n  apply(induction k a h rule: full_node.induct)\n   apply auto\n  done\n\nlemma full_btrees_sharp: \"nodes (full_node k a h) * (2*k) = bound (2*k) h\"\n  apply(induction k a h rule: full_node.induct)\n   apply (auto simp add: height_full_node algebra_simps sum_list_replicate)\n  done\n\nlemma upper_bound_sharp_node:\n  \"t = full_node k a h \\<Longrightarrow> height t = h \\<and> order k t \\<and> bal t \\<and> bound (2*k) h = nodes t * (2*k)\"\n  by (simp add: bal_full_node height_full_node order_full_node full_btrees_sharp)\n\n\n(* maximum number of nodes *)\nsubsection \"Maximum height for a given number of nodes\"\n\n\nlemma nodes_height_lower_bound:\n  \"\\<lbrakk>order k t; bal t\\<rbrakk> \\<Longrightarrow> bound k (height t) \\<le> nodes t * k\"\nproof(induction t rule: nodes.induct)\n  case (2 ts t)\n  let ?sub_height = \"((k + 1) ^ height t - 1)\"\n  have \"k*(?sub_height) \\<le> (length ts)*(?sub_height)\"\n    using \"2.prems\"(1)\n    by simp\n  also have \"\\<dots> = sum_list (replicate (length ts) ?sub_height)\"\n    using sum_list_replicate by simp\n  also have \"\\<dots> = sum_list (map (\\<lambda>x.?sub_height) (subtrees ts))\"\n    using map_replicate_const[of ?sub_height \"subtrees ts\"] length_map\n    by simp\n  also have \"\\<dots> \\<le> sum_list (map (\\<lambda>t. nodes t * k) (subtrees ts))\"\n    using 2\n    using sum_list_mono[of \"subtrees ts\" \"\\<lambda>x. bound k (height t)\" \"\\<lambda>t. nodes t * k\"]\n    by (metis bal.simps(2) order.simps(2))\n  also have \"\\<dots> = sum_list (map nodes (subtrees ts)) * k\"\n    using sum_list_mult_const[of nodes k \"subtrees ts\"] by auto\n  finally have \"sum_list (map nodes (subtrees ts))*k \\<ge> ?sub_height*k\"\n    by simp\n  moreover have \"(nodes t)*k \\<ge> ?sub_height\"\n    using 2 by simp\n  ultimately have \"(nodes (Node ts t))*k \\<ge>\n        k\n        + ?sub_height * k\n        + ?sub_height\"\n    unfolding nodes.simps add_mult_distrib\n    by linarith\n  also have\n    \"k + ?sub_height * k + ?sub_height =\n     k + k*((k + 1) ^ height t) - k + (k + 1) ^ height t - 1\"\n    by (simp add: diff_mult_distrib2 mult.assoc mult.commute)\n  also have \"\\<dots> = k*((k + 1) ^ height t) + (k + 1) ^ height t - 1\"\n    by simp\n  also have \"\\<dots> = (k+1)^(Suc(height t)) - 1\"\n    by simp\n  finally show ?case\n    by (metis \"2.prems\"(2) height_bal_tree)\nqed simp\n\ntext \"To verify our upper bound is sharp, we compare it to the height of artificially constructed\nminimally filled (=slim) trees.\"\n\nfun slim_node::\"nat \\<Rightarrow> 'a \\<Rightarrow> nat \\<Rightarrow> 'a btree\" where\n  \"slim_node k c 0 = Leaf\"|\n  \"slim_node k c (Suc n) = (Node (replicate k ((slim_node k c n),c)) (slim_node k c n))\"\n\nvalue \"let k = (2::nat) in map (\\<lambda>x. nodes x * k) (map (slim_node k (1::nat)) [0,1,2,3,4])\"\nvalue \"let k = (2::nat) in map (\\<lambda>x. ((k+1::nat)^(x)-1)) [0,1,2,3,4]\"\n\n\nlemma height_slim_node: \"height (slim_node k a h) = h\"\n  apply(induction k a h rule: full_node.induct)\n   apply (auto simp add: set_replicate_conv_if)\n  done\n\nlemma bal_slim_node: \"bal (slim_node k a h)\"\n  apply(induction k a h rule: full_node.induct)\n   apply auto\n  done\n\nlemma order_slim_node: \"order k (slim_node k a h)\"\n  apply(induction k a h rule: full_node.induct)\n   apply auto\n  done\n\nlemma slim_nodes_sharp: \"nodes (slim_node k a h) * k = bound k h\"\n  apply(induction k a h rule: slim_node.induct)\n   apply (auto simp add: height_slim_node algebra_simps sum_list_replicate compow_id_point)\n  done\n\nlemma lower_bound_sharp_node:\n  \"t = slim_node k a h \\<Longrightarrow> height t = h \\<and> order k t \\<and> bal t \\<and> bound k h = nodes t * k\"\n  by (simp add: bal_slim_node height_slim_node order_slim_node slim_nodes_sharp)\n\n(* TODO results for root_order/bal *)\ntext \"Since BTrees have special roots, we need to show the overall nodes seperately\"\n\nlemma nodes_root_height_lower_bound:\n  assumes \"root_order k t\"\n    and \"bal t\"\n  shows \"2*((k+1)^(height t - 1) - 1) + (of_bool (t \\<noteq> Leaf))*k  \\<le> nodes t * k\"\nproof (cases t)\n  case (Node ts t)\n  let ?sub_height = \"((k + 1) ^ height t - 1)\"\n  from Node have \"?sub_height \\<le> length ts * ?sub_height\"\n    using assms\n    by (simp add: Suc_leI)\n  also have \"\\<dots> = sum_list (replicate (length ts) ?sub_height)\"\n    using sum_list_replicate\n    by simp\n  also have \"\\<dots> = sum_list (map (\\<lambda>x. ?sub_height) (subtrees ts))\"\n    using map_replicate_const[of ?sub_height \"subtrees ts\"] length_map\n    by simp\n  also have \"\\<dots> \\<le> sum_list (map (\\<lambda>t. nodes t * k) (subtrees ts))\"\n    using Node\n      sum_list_mono[of \"subtrees ts\" \"\\<lambda>x. (k+1)^(height t) - 1\" \"\\<lambda>x. nodes x * k\"]\n      nodes_height_lower_bound assms\n    by fastforce\n  also have \"\\<dots> = sum_list (map nodes (subtrees ts)) * k\"\n    using sum_list_mult_const[of nodes k \"subtrees ts\"] by simp\n  finally have \"sum_list (map nodes (subtrees ts))*k \\<ge> ?sub_height\"\n    by simp\n\n  moreover have \"(nodes t)*k \\<ge> ?sub_height\"\n    using Node assms nodes_height_lower_bound\n    by auto\n  ultimately have \"(nodes (Node ts t))*k \\<ge>\n        ?sub_height\n        + ?sub_height + k\"\n    unfolding nodes.simps add_mult_distrib\n    by linarith\n  then show ?thesis\n    using Node assms(2) height_bal_tree by fastforce\nqed simp\n\nlemma nodes_root_height_upper_bound:\n  assumes \"root_order k t\"\n    and \"bal t\"\n  shows \"nodes t * (2*k) \\<le> (2*k+1)^(height t) - 1\"\nproof(cases t)\n  case (Node ts t)\n  let ?sub_height = \"((2 * k + 1) ^ height t - 1)\"\n  have \"sum_list (map nodes (subtrees ts)) * (2*k) =\n        sum_list (map (\\<lambda>t. nodes t * (2 * k)) (subtrees ts))\"\n    using sum_list_mult_const by metis\n  also have \"\\<dots> \\<le> sum_list (map (\\<lambda>x.?sub_height) (subtrees ts))\"\n    using Node\n      sum_list_mono[of \"subtrees ts\" \"\\<lambda>x. nodes x * (2*k)\"  \"\\<lambda>x. (2*k+1)^(height t) - 1\"]\n      nodes_height_upper_bound assms\n    by fastforce\n  also have \"\\<dots> = sum_list (replicate (length ts) ?sub_height)\"\n    using map_replicate_const[of ?sub_height \"subtrees ts\"] length_map\n    by simp\n  also have \"\\<dots> = (length ts)*(?sub_height)\"\n    using sum_list_replicate by simp\n  also have \"\\<dots> \\<le> (2*k)*?sub_height\"\n    using assms Node\n    by simp\n  finally have \"sum_list (map nodes (subtrees ts))*(2*k) \\<le> ?sub_height*(2*k)\"\n    by simp\n  moreover have \"(nodes t)*(2*k) \\<le> ?sub_height\"\n    using Node assms nodes_height_upper_bound\n    by auto\n  ultimately have \"(nodes (Node ts t))*(2*k) \\<le>\n         2*k\n        + ?sub_height * (2*k)\n        + ?sub_height\"\n    unfolding nodes.simps add_mult_distrib\n    by linarith\n  also have \"\\<dots> =  2*k + (2*k)*((2 * k + 1) ^ height t) - 2*k + (2 * k + 1) ^ height t - 1\"\n    by (simp add: diff_mult_distrib2 mult.assoc mult.commute)\n  also have \"\\<dots> = (2*k)*((2 * k + 1) ^ height t) + (2 * k + 1) ^ height t - 1\"\n    by simp\n  also have \"\\<dots> = (2*k+1)^(Suc(height t)) - 1\"\n    by simp\n  finally show ?thesis\n    by (metis Node assms(2) height_bal_tree)\nqed simp\n\nlemma root_order_imp_divmuleq: \"root_order k t \\<Longrightarrow> (nodes t * k) div k = nodes t\"\n  using root_order.elims(2) by fastforce\n\nlemma nodes_root_height_lower_bound_simp:\n  assumes \"root_order k t\"\n    and \"bal t\"\n    and \"k > 0\"\n  shows \"(2*((k+1)^(height t - 1) - 1)) div k + (of_bool (t \\<noteq> Leaf)) \\<le> nodes t\"\nproof (cases t)\n  case Node\n  have \"(2*((k+1)^(height t - 1) - 1)) div k + (of_bool (t \\<noteq> Leaf)) =\n(2*((k+1)^(height t - 1) - 1) + (of_bool (t \\<noteq> Leaf))*k) div k\"\n    using Node assms\n    using div_plus_div_distrib_dvd_left[of k k \"(2 * Suc k ^ (height t - Suc 0) - Suc (Suc 0))\"]\n    by (auto simp add: algebra_simps simp del: height_btree.simps)\n  also have \"\\<dots> \\<le> (nodes t * k) div k\"\n    using nodes_root_height_lower_bound[OF assms(1,2)] div_le_mono\n    by blast\n  also have \"\\<dots> = nodes t\"\n    using root_order_imp_divmuleq[OF assms(1)]\n    by simp\n  finally show ?thesis .\nqed simp\n\nlemma nodes_root_height_upper_bound_simp:\n  assumes \"root_order k t\"\n    and \"bal t\"\n  shows \"nodes t \\<le> ((2*k+1)^(height t) - 1) div (2*k)\"\nproof -\n  have \"nodes t = (nodes t * (2*k)) div (2*k)\"\n    using root_order_imp_divmuleq[OF assms(1)]\n    by simp\n  also have \"\\<dots> \\<le> ((2*k+1)^(height t) - 1) div (2*k)\"\n    using div_le_mono nodes_root_height_upper_bound[OF assms] by blast\n  finally show ?thesis .\nqed\n\ndefinition \"full_tree = full_node\"\n\nfun slim_tree where\n  \"slim_tree k c 0 = Leaf\" |\n  \"slim_tree k c (Suc h) = Node [(slim_node k c h, c)] (slim_node k c h)\"\n\nlemma lower_bound_sharp:\n  \"k > 0 \\<Longrightarrow> t = slim_tree k a h \\<Longrightarrow> height t = h \\<and> root_order k t \\<and> bal t \\<and> nodes t * k = 2*((k+1)^(height t - 1) - 1) + (of_bool (t \\<noteq> Leaf))*k\"\n  apply (cases h)\n  using slim_nodes_sharp[of k a]\n   apply (auto simp add: algebra_simps bal_slim_node height_slim_node order_slim_node)\n  done\n\nlemma upper_bound_sharp:\n  \"k > 0 \\<Longrightarrow> t = full_tree k a h \\<Longrightarrow> height t = h \\<and> root_order k t \\<and> bal t \\<and> ((2*k+1)^(height t) - 1) = nodes t * (2*k)\"\n  unfolding full_tree_def\n  using order_impl_root_order[of k t]\n  by (simp add: bal_full_node height_full_node order_full_node full_btrees_sharp)\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/BTree/BTree_Height.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8354835452961425, "lm_q2_score": 0.8558511488056151, "lm_q1q2_score": 0.7150495520498917}}
{"text": "(*\n    File:      Dirichlet_Characters.thy\n    Author:    Manuel Eberl, TU M\u00fcnchen\n*)\nsection \\<open>Dirichlet Characters\\<close>\ntheory Dirichlet_Characters\nimports\n  Multiplicative_Characters\n  \"HOL-Number_Theory.Residues\"\n  \"Dirichlet_Series.Multiplicative_Function\"\nbegin\n\ntext \\<open>\n  Dirichlet characters are essentially just the characters of the multiplicative group of\n  integer residues $\\mathbb{ZZ}/n\\mathbb{ZZ}$ for some fixed $n$. For convenience, these residues\n  are usually represented by natural numbers from $0$ to $n - 1$, and we extend the characters to \n  all natural numbers periodically, so that $\\chi(k\\mod n) = \\chi(k)$ holds.\n\n  Numbers that are not coprime to $n$ are not in the group and therefore are assigned $0$ by\n  all characters.\n\\<close>\n\nsubsection \\<open>The multiplicative group of residues\\<close>\n\ndefinition residue_mult_group :: \"nat \\<Rightarrow> nat monoid\" where\n  \"residue_mult_group n = \\<lparr> carrier = totatives n, monoid.mult = (\\<lambda>x y. (x * y) mod n), one = 1 \\<rparr>\"\n\ndefinition principal_dchar :: \"nat \\<Rightarrow> nat \\<Rightarrow> complex\" where\n  \"principal_dchar n = (\\<lambda>k. if coprime k n then 1 else 0)\"\n\nlemma principal_dchar_coprime [simp]: \"coprime k n \\<Longrightarrow> principal_dchar n k = 1\"\n  and principal_dchar_not_coprime [simp]: \"\\<not>coprime k n \\<Longrightarrow> principal_dchar n k = 0\"\n  by (simp_all add: principal_dchar_def)\n\nlemma principal_dchar_1 [simp]: \"principal_dchar n 1 = 1\"\n  by simp\n\nlemma principal_dchar_minus1 [simp]:\n  assumes \"n > 0\"\n  shows   \"principal_dchar n (n - Suc 0) = 1\"\nproof (cases \"n = 1\")\n  case False\n  with assms have \"n > 1\" by linarith\n  thus ?thesis using coprime_diff_one_left_nat[of n]\n    by (intro principal_dchar_coprime) auto\nqed auto\n\nlemma mod_in_totatives: \"n > 1 \\<Longrightarrow> a mod n \\<in> totatives n \\<longleftrightarrow> coprime a n\"\n  by (auto simp: totatives_def mod_greater_zero_iff_not_dvd dest: coprime_common_divisor_nat)\n\nbundle dcharacter_syntax\nbegin\nnotation principal_dchar (\"\\<chi>\\<^sub>0\\<index>\")\nend\n\nlocale residues_nat =\n  fixes n :: nat (structure) and G\n  assumes n: \"n > 1\"\n  defines \"G \\<equiv> residue_mult_group n\"\nbegin\n\nlemma order [simp]: \"order G = totient n\"\n  by (simp add: order_def G_def totient_def residue_mult_group_def)\n\nlemma totatives_mod [simp]: \"x \\<in> totatives n \\<Longrightarrow> x mod n = x\"\n  using n by (intro mod_less) (auto simp: totatives_def intro!: order.not_eq_order_implies_strict)\n\nlemma principal_dchar_minus1 [simp]: \"principal_dchar n (n - Suc 0) = 1\"\n  using principal_dchar_minus1[of n] n by simp\n\nsublocale finite_comm_group G\nproof\n  fix x y assume xy: \"x \\<in> carrier G\" \"y \\<in> carrier G\"\n  hence \"coprime (x * y) n\" \n    by (auto simp: G_def residue_mult_group_def totatives_def)\n  with xy and n show \"x \\<otimes>\\<^bsub>G\\<^esub> y \\<in> carrier G\"\n    using coprime_common_divisor_nat[of \"x * y\" n]\n    by (auto simp: G_def residue_mult_group_def totatives_def\n                   mod_greater_zero_iff_not_dvd le_Suc_eq simp del: coprime_mult_left_iff)\nnext\n  fix x y z assume xyz: \"x \\<in> carrier G\" \"y \\<in> carrier G\" \"z \\<in> carrier G\"\n  thus \"x \\<otimes>\\<^bsub>G\\<^esub> y \\<otimes>\\<^bsub>G\\<^esub> z = x \\<otimes>\\<^bsub>G\\<^esub> (y \\<otimes>\\<^bsub>G\\<^esub> z)\"\n    by (auto simp: G_def residue_mult_group_def mult_ac mod_mult_right_eq)\nnext\n  fix x assume \"x \\<in> carrier G\"\n  with n have \"x < n\" by (auto simp: G_def residue_mult_group_def totatives_def \n                               intro!: order.not_eq_order_implies_strict)\n  thus \" \\<one>\\<^bsub>G\\<^esub> \\<otimes>\\<^bsub>G\\<^esub> x = x\" and \"x \\<otimes>\\<^bsub>G\\<^esub> \\<one>\\<^bsub>G\\<^esub> = x\"\n    by (simp_all add: G_def residue_mult_group_def)\nnext\n  have \"x \\<in> Units G\" if \"x \\<in> carrier G\" for x unfolding Units_def\n  proof safe\n    from that have \"x > 0\" \"coprime x n\" \n      by (auto simp: G_def residue_mult_group_def totatives_def)\n    from \\<open>coprime x n\\<close> and n obtain y where y: \"y < n\" \"[x * y = 1] (mod n)\"\n      by (subst (asm) coprime_iff_invertible'_nat) auto\n    hence \"x * y mod n = 1\" \n      using n by (simp add: cong_def mult_ac)\n    moreover from y have \"coprime y n\"\n      by (subst coprime_iff_invertible_nat) (auto simp: mult.commute)\n    ultimately show \"\\<exists>a\\<in>carrier G. a \\<otimes>\\<^bsub>G\\<^esub> x = \\<one>\\<^bsub>G\\<^esub> \\<and> x \\<otimes>\\<^bsub>G\\<^esub> a = \\<one>\\<^bsub>G\\<^esub>\" using y\n      by (intro bexI[of _ y]) \n         (auto simp: G_def residue_mult_group_def totatives_def mult.commute intro!: Nat.gr0I)\n  qed fact+\n  thus \"carrier G \\<subseteq> Units G\" ..\nqed (insert n, auto simp: G_def residue_mult_group_def mult_ac)\n\n\nsubsection \\<open>Definition of Dirichlet characters\\<close>\n\ntext \\<open>\n  The following two functions make the connection between Dirichlet characters and the\n  multiplicative characters of the residue group.\n\\<close>\ndefinition c2dc :: \"(nat \\<Rightarrow> complex) \\<Rightarrow> (nat \\<Rightarrow> complex)\" where\n  \"c2dc \\<chi> = (\\<lambda>x. \\<chi> (x mod n))\"\n\ndefinition dc2c :: \"(nat \\<Rightarrow> complex) \\<Rightarrow> (nat \\<Rightarrow> complex)\" where\n  \"dc2c \\<chi> = (\\<lambda>x. if x < n then \\<chi> x else 0)\"\n\nlemma dc2c_c2dc [simp]:\n  assumes \"character G \\<chi>\"\n  shows   \"dc2c (c2dc \\<chi>) = \\<chi>\"\nproof -\n  interpret character G \\<chi> by fact\n  show ?thesis\n    using n by (auto simp: fun_eq_iff dc2c_def c2dc_def char_eq_0_iff G_def\n                           residue_mult_group_def totatives_def)\nqed\n\nend\n\nlocale dcharacter = residues_nat +\n  fixes \\<chi> :: \"nat \\<Rightarrow> complex\"\n  assumes mult_aux: \"a \\<in> totatives n \\<Longrightarrow> b \\<in> totatives n \\<Longrightarrow> \\<chi> (a * b) = \\<chi> a * \\<chi> b\"\n  assumes eq_zero:  \"\\<not>coprime a n \\<Longrightarrow> \\<chi> a = 0\"\n  assumes periodic: \"\\<chi> (a + n) = \\<chi> a\"\n  assumes one_not_zero: \"\\<chi> 1 \\<noteq> 0\"\nbegin\n\nlemma zero_eq_0 [simp]: \"\\<chi> 0 = 0\"\n  using n by (intro eq_zero) auto\n\nlemma Suc_0 [simp]: \"\\<chi> (Suc 0) = 1\"\n  using n mult_aux[of 1 1] one_not_zero by (simp add: totatives_def)   \n\nlemma periodic_mult: \"\\<chi> (a + m * n) = \\<chi> a\"\nproof (induction m)\n  case (Suc m)\n  have \"a + Suc m * n = a + m * n+ n\" by simp\n  also have \"\\<chi> \\<dots> = \\<chi> (a + m * n)\" by (rule periodic)\n  also have \"\\<dots> = \\<chi> a\" by (rule Suc.IH)\n  finally show ?case .\nqed simp_all\n\nlemma minus_one_periodic [simp]:\n  assumes \"k > 0\"\n  shows   \"\\<chi> (k * n - 1) = \\<chi> (n - 1)\"\nproof -\n  have \"k * n - 1 = n - 1 + (k - 1) * n\"\n    using assms n by (simp add: algebra_simps)\n  also have \"\\<chi> \\<dots> = \\<chi> (n - 1)\"\n    by (rule periodic_mult)\n  finally show ?thesis .\nqed\n\nlemma cong:\n  assumes \"[a = b] (mod n)\"\n  shows   \"\\<chi> a = \\<chi> b\"\nproof -\n  from assms obtain k1 k2 where *: \"b + k1 * n = a + k2 * n\"\n    by (subst (asm) cong_iff_lin_nat) auto\n  have \"\\<chi> a = \\<chi> (a + k2 * n)\" by (rule periodic_mult [symmetric])\n  also note * [symmetric]\n  also have \"\\<chi> (b + k1 * n) = \\<chi> b\" by (rule periodic_mult)\n  finally show ?thesis .\nqed\n\nlemma mod [simp]: \"\\<chi> (a mod n) = \\<chi> a\"\n  by (rule cong) (simp_all add: cong_def)\n\nlemma mult [simp]: \"\\<chi> (a * b) = \\<chi> a * \\<chi> b\"\nproof (cases \"coprime a n \\<and> coprime b n\")\n  case True\n  hence \"a mod n \\<in> totatives n\" \"b mod n \\<in> totatives n\"\n    using n by (auto simp: totatives_def mod_greater_zero_iff_not_dvd coprime_absorb_right)\n  hence \"\\<chi> ((a mod n) * (b mod n)) = \\<chi> (a mod n) * \\<chi> (b mod n)\"\n    by (rule mult_aux)\n  also have \"\\<chi> ((a mod n) * (b mod n)) = \\<chi> (a * b)\"\n    by (rule cong) (auto simp: cong_def mod_mult_eq)\n  finally show ?thesis by simp\nnext\n  case False\n  hence \"\\<not>coprime (a * b) n\" by simp\n  with False show ?thesis by (auto simp: eq_zero)\nqed\n\nsublocale mult: completely_multiplicative_function \\<chi>\n  by standard auto\n\nlemma eq_zero_iff: \"\\<chi> x = 0 \\<longleftrightarrow> \\<not>coprime x n\"\nproof safe\n  assume \"\\<chi> x = 0\" and \"coprime x n\"\n  from cong_solve_coprime_nat [OF this(2)] \n    obtain y where \"[x * y = Suc 0] (mod n)\" by blast\n  hence \"\\<chi> (x * y) = \\<chi> (Suc 0)\" by (rule cong)\n  with \\<open>\\<chi> x = 0\\<close> show False by simp\nqed (auto simp: eq_zero)\n\nlemma minus_one': \"\\<chi> (n - 1) \\<in> {-1, 1}\"\nproof -\n  define n' where \"n' = n - 2\"\n  have n: \"n = Suc (Suc n')\" using n by (simp add: n'_def)\n  have \"(n - 1) ^ 2 = 1 + (n - 2) * n\"\n    by (simp add: power2_eq_square algebra_simps n)\n  also have \"\\<chi> \\<dots> = 1\"\n    by (subst periodic_mult) auto\n  also have \"\\<chi> ((n - 1) ^ 2) = \\<chi> (n - 1) ^ 2\"\n    by (rule mult.power)\n  finally show ?thesis\n    by (subst (asm) power2_eq_1_iff) auto\nqed\n\nlemma c2dc_dc2c [simp]: \"c2dc (dc2c \\<chi>) = \\<chi>\"\n  using n by (auto simp: c2dc_def dc2c_def fun_eq_iff intro!: cong simp: cong_def)\n\nlemma character_dc2c: \"character G (dc2c \\<chi>)\"\n  by standard (insert n, auto simp: G_def residue_mult_group_def dc2c_def totatives_def\n                              intro!: eq_zero)\n\nsublocale dc2c: character G \"dc2c \\<chi>\"\n  by (fact character_dc2c)\n\nlemma dcharacter_inv_character [intro]: \"dcharacter n (inv_character \\<chi>)\"\n  by standard (auto simp: inv_character_def eq_zero periodic)\n\nlemma norm: \"norm (\\<chi> k) = (if coprime k n then 1 else 0)\"\nproof -\n  have \"\\<chi> k = \\<chi> (k mod n)\" by (intro cong) (auto simp: cong_def)\n  also from n have \"\\<dots> = dc2c \\<chi> (k mod n)\" by (simp add: dc2c_def)\n  also from n have \"norm \\<dots> = (if coprime k n then 1 else 0)\"\n    by (subst dc2c.norm_char) (auto simp: G_def residue_mult_group_def mod_in_totatives)\n  finally show ?thesis .\nqed\n\n\n\nend\n\n\ndefinition dcharacters :: \"nat \\<Rightarrow> (nat \\<Rightarrow> complex) set\" where\n  \"dcharacters n = {\\<chi>. dcharacter n \\<chi>}\"\n\ncontext residues_nat\nbegin\n\nlemma character_dc2c: \"dcharacter n \\<chi> \\<Longrightarrow> character G (dc2c \\<chi>)\"\n  using dcharacter.character_dc2c[of n \\<chi>] by (simp add: G_def)\n\nlemma dcharacter_c2dc: \n  assumes \"character G \\<chi>\"\n  shows   \"dcharacter n (c2dc \\<chi>)\"\nproof -\n  interpret character G \\<chi> by fact\n  show ?thesis\n  proof\n    fix x assume \"\\<not>coprime x n\"\n    thus \"c2dc \\<chi> x = 0\"\n      by (auto simp: c2dc_def char_eq_0_iff G_def residue_mult_group_def totatives_def)\n  qed (insert char_mult char_one n, \n       auto simp: c2dc_def G_def residue_mult_group_def simp del: char_mult char_one)\nqed\n\nlemma principal_dchar_altdef: \"principal_dchar n = c2dc (principal_char G)\"\n  using n by (auto simp: c2dc_def principal_dchar_def principal_char_def G_def\n                residue_mult_group_def fun_eq_iff mod_in_totatives)\n\nsublocale principal: dcharacter n G \"principal_dchar n\"\n  by (simp add: principal_dchar_altdef dcharacter_c2dc | rule G_def)+\n\nlemma c2dc_principal [simp]: \"c2dc (principal_char G) = principal_dchar n\"\n  by (simp add: principal_dchar_altdef)\n\nlemma dc2c_principal [simp]: \"dc2c (principal_dchar n) = principal_char G\"\nproof -\n  have \"dc2c (c2dc (principal_char G)) = dc2c (principal_dchar n)\"\n    by (subst c2dc_principal) (rule refl)\n  thus ?thesis by (subst (asm) dc2c_c2dc) simp_all\nqed\n\n\nlemma bij_betw_dcharacters_characters:\n  \"bij_betw dc2c (dcharacters n) (characters G)\"\n  by (intro bij_betwI[where ?g = c2dc])\n     (auto simp: characters_def dcharacters_def dcharacter_c2dc \n                 character_dc2c dcharacter.c2dc_dc2c)\n\nlemma bij_betw_characters_dcharacters:\n  \"bij_betw c2dc (characters G) (dcharacters n)\"\n  by (intro bij_betwI[where ?g = dc2c])\n     (auto simp: characters_def dcharacters_def dcharacter_c2dc \n                 character_dc2c dcharacter.c2dc_dc2c)\n\nlemma finite_dcharacters [intro]: \"finite (dcharacters n)\"\n  using bij_betw_finite [OF bij_betw_dcharacters_characters] by auto\n\nlemma card_dcharacters [simp]: \"card (dcharacters n) = totient n\"\n  using bij_betw_same_card [OF bij_betw_dcharacters_characters] card_characters by simp\n\nend\n\nlemma inv_character_eq_principal_dchar_iff [simp]: \n  \"inv_character \\<chi> = principal_dchar n \\<longleftrightarrow> \\<chi> = principal_dchar n\"\n  by (auto simp add: fun_eq_iff inv_character_def principal_dchar_def)\n\n\nsubsection \\<open>Sums of Dirichlet characters\\<close>\n\nlemma (in dcharacter) sum_dcharacter_totatives:\n  \"(\\<Sum>x\\<in>totatives n. \\<chi> x) = (if \\<chi> = principal_dchar n then of_nat (totient n) else 0)\"\nproof -\n  from n have \"(\\<Sum>x\\<in>totatives n. \\<chi> x) = (\\<Sum>x\\<in>carrier G. dc2c \\<chi> x)\"\n    by (intro sum.cong) (auto simp: totatives_def dc2c_def G_def residue_mult_group_def)\n  also have \"\\<dots> = (if dc2c \\<chi> = principal_char G then of_nat (order G) else 0)\"\n    by (rule dc2c.sum_character)\n  also have \"dc2c \\<chi> = principal_char G \\<longleftrightarrow> \\<chi> = principal_dchar n\"\n    by (metis c2dc_dc2c dc2c_principal principal_dchar_altdef)\n  finally show ?thesis by simp\nqed\n\nlemma (in dcharacter) sum_dcharacter_block:\n  \"(\\<Sum>x<n. \\<chi> x) = (if \\<chi> = principal_dchar n then of_nat (totient n) else 0)\"\nproof -\n  from n have \"(\\<Sum>x<n. \\<chi> x) = (\\<Sum>x\\<in>totatives n. \\<chi> x)\"\n    by (intro sum.mono_neutral_right) \n       (auto simp: totatives_def eq_zero_iff intro!: Nat.gr0I order.not_eq_order_implies_strict)\n  also have \"\\<dots> = (if \\<chi> = principal_dchar n then of_nat (totient n) else 0)\"\n    by (rule sum_dcharacter_totatives)\n  finally show ?thesis .\nqed\n\nlemma (in dcharacter) sum_dcharacter_block':\n  \"sum \\<chi> {Suc 0..n} = (if \\<chi> = principal_dchar n then of_nat (totient n) else 0)\"\nproof -\n  let ?f = \"\\<lambda>k. if k = n then 0 else k\" and ?g = \"\\<lambda>k. if k = 0 then n else k\"\n  have \"sum \\<chi> {1..n} = sum \\<chi> {..<n}\"\n    using n by (intro sum.reindex_bij_witness[where j = ?f and i = ?g]) (auto simp: eq_zero_iff)\n  thus ?thesis by (simp add: sum_dcharacter_block)\nqed\n\nlemma (in dcharacter) sum_lessThan_dcharacter:\n  assumes \"\\<chi> \\<noteq> principal_dchar n\"\n  shows   \"(\\<Sum>x<m. \\<chi> x) = (\\<Sum>x<m mod n. \\<chi> x)\"\nproof (induction m rule: less_induct)\n  case (less m)\n  show ?case\n  proof (cases \"m < n\")\n    case True\n    thus ?thesis by simp\n  next\n    case False\n    hence \"{..<m} = {..<n} \\<union> {n..<m}\" by auto\n    also have \"(\\<Sum>x\\<in>\\<dots>. \\<chi> x) = (\\<Sum>x<n. \\<chi> x) + (\\<Sum>x\\<in>{n..<m}. \\<chi> x)\"\n      by (intro sum.union_disjoint) auto\n    also from assms have \"(\\<Sum>x<n. \\<chi> x) = 0\"\n      by (subst sum_dcharacter_block) simp_all\n    also from False have \"(\\<Sum>x\\<in>{n..<m}. \\<chi> x) = (\\<Sum>x\\<in>{..<m - n}. \\<chi> (x + n))\"\n      by (intro sum.reindex_bij_witness[of _ \"\\<lambda>x. x + n\" \"\\<lambda>x. x - n\"]) (auto simp: periodic)\n    also have \"\\<dots> = (\\<Sum>x\\<in>{..<m - n}. \\<chi> x)\" by (simp add: periodic)\n    also have \"\\<dots> = (\\<Sum>x<(m - n) mod n. \\<chi> x)\"\n      using False and n by (intro less.IH) auto\n    also from False and n have \"(m - n) mod n = m mod n\" \n      by (simp add: mod_geq [symmetric])\n    finally show ?thesis by simp\n  qed\nqed\n\nlemma (in dcharacter) sum_dcharacter_lessThan_le:\n  assumes \"\\<chi> \\<noteq> principal_dchar n\"\n  shows   \"norm (\\<Sum>x<m. \\<chi> x) \\<le> totient n\"\nproof -\n  have \"(\\<Sum>x<m. \\<chi> x) = (\\<Sum>x<m mod n. \\<chi> x)\" by (rule sum_lessThan_dcharacter) fact\n  also have \"\\<dots> = (\\<Sum>x | x < m mod n \\<and> coprime x n. \\<chi> x)\"\n    by (intro sum.mono_neutral_right) (auto simp: eq_zero_iff)\n  also have \"norm \\<dots> \\<le> (\\<Sum>x | x < m mod n \\<and> coprime x n. 1)\"\n    by (rule sum_norm_le) (auto simp: norm)\n  also have \"\\<dots> = card {x. x < m mod n \\<and> coprime x n}\" by simp\n  also have \"\\<dots> \\<le> card (totatives n)\" unfolding of_nat_le_iff\n  proof (intro card_mono subsetI)\n    fix x assume x: \"x \\<in> {x. x < m mod n \\<and> coprime x n}\"\n    hence \"x < m mod n\" by simp\n    also have \"\\<dots> < n\" using n by simp\n    finally show \"x \\<in> totatives n\" using x\n      by (auto simp: totatives_def intro!: Nat.gr0I)\n  qed auto\n  also have \"\\<dots> = totient n\" by (simp add: totient_def)\n  finally show ?thesis .\nqed\n\nlemma (in dcharacter) sum_dcharacter_atMost_le:\n  assumes \"\\<chi> \\<noteq> principal_dchar n\"\n  shows   \"norm (\\<Sum>x\\<le>m. \\<chi> x) \\<le> totient n\"\n  using sum_dcharacter_lessThan_le[OF assms, of \"Suc m\"] by (subst (asm) lessThan_Suc_atMost)\n\nlemma (in residues_nat) sum_dcharacters:\n  \"(\\<Sum>\\<chi>\\<in>dcharacters n. \\<chi> x) = (if [x = 1] (mod n) then of_nat (totient n) else 0)\"\nproof (cases \"coprime x n\")\n  case True\n  with n have x: \"x mod n \\<in> totatives n\" by (auto simp: mod_in_totatives)\n  have \"(\\<Sum>\\<chi>\\<in>dcharacters n. \\<chi> x) = (\\<Sum>\\<chi>\\<in>characters G. c2dc \\<chi> x)\"\n    by (rule sum.reindex_bij_betw [OF bij_betw_characters_dcharacters, symmetric])\n  also from x have \"\\<dots> = (\\<Sum>\\<chi>\\<in>characters G. \\<chi> (x mod n))\"\n    by (simp add: c2dc_def)\n  also from x have \"\\<dots> = (if x mod n = 1 then order G else 0)\"\n    by (subst sum_characters) (unfold G_def residue_mult_group_def, auto)\n  also from n have \"x mod n = 1 \\<longleftrightarrow> [x = 1] (mod n)\"\n    by (simp add: cong_def)\n  finally show ?thesis by simp\nnext\n  case False\n  have \"x mod n \\<noteq> 1\"\n  proof\n    assume *: \"x mod n = 1\"\n    have \"gcd (x mod n) n = 1\" by (subst *) simp\n    also have \"gcd (x mod n) n = gcd x n\" \n      by (subst gcd.commute) (simp only: gcd_red_nat [symmetric])\n    finally show False using \\<open>\\<not>coprime x n\\<close> unfolding coprime_iff_gcd_eq_1 by contradiction\n  qed\n  from False have \"(\\<Sum>\\<chi>\\<in>dcharacters n. \\<chi> x) = 0\"\n    by (intro sum.neutral) (auto simp: dcharacters_def dcharacter.eq_zero)\n  with \\<open>x mod n \\<noteq> 1\\<close> and n show ?thesis by (simp add: cong_def)\nqed\n\nlemma (in dcharacter) even_dcharacter_linear_sum_eq_0 [simp]:\n  assumes \"\\<chi> \\<noteq> principal_dchar n\" and \"\\<chi> (n - 1) = 1\"\n  shows   \"(\\<Sum>k=Suc 0..<n. of_nat k * \\<chi> k) = 0\"\nproof -\n  have \"(\\<Sum>k=1..<n. of_nat k * \\<chi> k) = (\\<Sum>k=1..<n. (of_nat n - of_nat k) * \\<chi> (n - k))\"\n    by (intro sum.reindex_bij_witness[where i = \"\\<lambda>k. n - k\" and j = \"\\<lambda>k. n - k\"])\n       (auto simp: of_nat_diff)\n  also have \"\\<dots> = n * (\\<Sum>k=1..<n. \\<chi> (n - k)) - (\\<Sum>k=1..<n. k * \\<chi> (n - k))\"\n    by (simp add: algebra_simps sum_subtractf sum_distrib_left)\n  also have \"(\\<Sum>k=1..<n. \\<chi> (n - k)) = (\\<Sum>k=1..<n. \\<chi> k)\"\n    by (intro sum.reindex_bij_witness[where i = \"\\<lambda>k. n - k\" and j = \"\\<lambda>k. n - k\"]) auto\n  also have \"\\<dots> = (\\<Sum>k<n. \\<chi> k)\"\n    by (intro sum.mono_neutral_left) (auto simp: Suc_le_eq)\n  also have \"\\<dots> = 0\" using assms by (simp add: sum_dcharacter_block)\n  also have \"(\\<Sum>k=1..<n. of_nat k * \\<chi> (n - k)) = (\\<Sum>k=1..<n. k * \\<chi> k)\"\n  proof (intro sum.cong refl)\n    fix k assume k: \"k \\<in> {1..<n}\"\n    have \"of_nat k * \\<chi> k = of_nat k * \\<chi> ((n - 1) * k)\"\n      using assms by (subst mult) simp_all\n    also have \"(n - 1) * k = n - k + (k - 1) * n\"\n      using k by (simp add: algebra_simps)\n    also have \"\\<chi> \\<dots> = \\<chi> (n - k)\"\n      by (rule periodic_mult)\n    finally show \"of_nat k * \\<chi> (n - k) = of_nat k * \\<chi> k\" ..\n  qed\n  finally show ?thesis 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/Dirichlet_L/Dirichlet_Characters.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8354835330070839, "lm_q2_score": 0.8558511469672594, "lm_q1q2_score": 0.7150495399963709}}
{"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_ISortCount\nimports \"../../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 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 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 (isort 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_ISortCount.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.923039160069787, "lm_q2_score": 0.7745833945721304, "lm_q1q2_score": 0.7149708059298637}}
{"text": "section {* Monoid variants and extra properties *}\n\ntheory Monoid_extra\n  imports List_extra \"~~/src/HOL/Library/Prefix_Order\"\nbegin\n\nclass ordered_semigroup = semigroup_add + order +\n  assumes add_left_mono: \"a \\<le> b \\<Longrightarrow> c + a \\<le> c + b\"\n  and add_right_mono: \"a \\<le> b \\<Longrightarrow> a + c \\<le> b + c\"\nbegin\n\nlemma add_mono:\n  \"a \\<le> b \\<Longrightarrow> c \\<le> d \\<Longrightarrow> a + c \\<le> b + d\"\n  using local.add_left_mono local.add_right_mono local.order.trans by blast\n\nend\n\nthm cancel_semigroup_add_axioms\n\nclass left_cancel_monoid = monoid_add +\n  assumes add_left_imp_eq: \"a + b = a + c \\<Longrightarrow> b = c\"\n\nclass right_cancel_monoid = monoid_add +\n  assumes add_right_imp_eq: \"b + a = c + a \\<Longrightarrow> b = c\"\n\nclass monoid_sum_0 = monoid_add +\n  assumes zero_sum_left: \"a + b = 0 \\<Longrightarrow> a = 0\"\nbegin\n\nlemma zero_sum_right: \"a + b = 0 \\<Longrightarrow> b = 0\"\n  by (metis local.add_0_left local.zero_sum_left)\n\nlemma zero_sum: \"a + b = 0 \\<longleftrightarrow> a = 0 \\<and> b = 0\"\n  by (metis local.add_0_right zero_sum_right)\n\nend\n\ncontext monoid_add\nbegin\n\ndefinition monoid_le (infix \"\\<le>\\<^sub>m\" 50) \nwhere \"a \\<le>\\<^sub>m b \\<longleftrightarrow> (\\<exists>c. b = a + c)\"\n\ndefinition monoid_subtract (infixl \"-\\<^sub>m\" 65)\nwhere \"a -\\<^sub>m b = (if (b \\<le>\\<^sub>m a) then THE c. a = b + c else 0)\"\n\nend\n\nclass cancel_monoid = left_cancel_monoid + right_cancel_monoid + monoid_sum_0\nbegin\n\nlemma monoid_le_least_zero: \"0 \\<le>\\<^sub>m a\"\n  by (simp add: monoid_le_def)\n\nlemma monoid_le_refl: \"a \\<le>\\<^sub>m a\"\n  by (simp add: monoid_le_def, metis add.right_neutral)\n\nlemma monoid_le_trans: \"\\<lbrakk> a \\<le>\\<^sub>m b; b \\<le>\\<^sub>m c \\<rbrakk> \\<Longrightarrow> a \\<le>\\<^sub>m c\"\n  by (metis add.assoc monoid_le_def)\n\nlemma monoid_le_antisym: \n  assumes \"a \\<le>\\<^sub>m b\" \"b \\<le>\\<^sub>m a\"\n  shows \"a = b\"\nproof -\n  obtain a' where a': \"b = a + a'\"\n    using assms(1) monoid_le_def by auto\n\n  obtain b' where b': \"a = b + b'\"\n    using assms(2) monoid_le_def by auto\n\n  have \"b' = (b' + a' + b')\"\n    by (metis a' add_assoc b' local.add_left_imp_eq)\n    \n  hence \"a' + b' = 0\"\n    by (metis add_assoc local.add_0_right local.add_left_imp_eq)\n\n  hence \"a' = 0\" \"b' = 0\"\n    by (simp add: zero_sum)+\n\n  with a' b' show ?thesis\n    by simp\nqed\n\nlemma monoid_le_add: \"a \\<le>\\<^sub>m a + b\"\n  by (auto simp add: monoid_le_def)\n\nlemma monoid_le_add_left_mono: \"a \\<le>\\<^sub>m b \\<Longrightarrow> c + a \\<le>\\<^sub>m c + b\"\n  using add_assoc by (auto simp add: monoid_le_def)\n\nlemma add_monoid_diff_cancel_left [simp]: \"(a + b) -\\<^sub>m a = b\"\n  apply (simp add: monoid_subtract_def monoid_le_add)\n  apply (rule the_equality)\n  apply (simp)\n  using local.add_left_imp_eq apply blast\ndone\n    \nend\n\nclass ordered_cancel_monoid_diff = cancel_monoid + ord + minus +\n  assumes le_is_monoid_le: \"a \\<le> b \\<longleftrightarrow> (a \\<le>\\<^sub>m b)\"\n  and less_iff: \"a < b \\<longleftrightarrow> a \\<le> b \\<and> \\<not> (b \\<le> a)\"\n  and minus_def: \"a - b = a -\\<^sub>m b\"\n\ninstance ordered_cancel_monoid_diff \\<subseteq> order\n  apply (intro_classes)\n  apply (simp_all add: less_iff le_is_monoid_le monoid_le_refl)\n  using monoid_le_trans apply blast\n  apply (simp add: monoid_le_antisym)\ndone\n\ncontext ordered_cancel_monoid_diff\nbegin\n\n  lemma le_iff_add: \"a \\<le> b \\<longleftrightarrow> (\\<exists> c. b = a + c)\"\n    by (simp add: local.le_is_monoid_le local.monoid_le_def)\n\n  lemma least_zero [simp]: \"0 \\<le> a\"\n    by (simp add: local.le_is_monoid_le local.monoid_le_least_zero)\n\n  lemma le_add [simp]: \"a \\<le> a + b\"\n    by (simp add: le_is_monoid_le local.monoid_le_add)\n\n  lemma not_le_minus [simp]:  \"\\<not> (a \\<le> b) \\<Longrightarrow> b - a = 0\"\n    by (simp add: le_is_monoid_le local.minus_def local.monoid_subtract_def)\n\n  lemma add_diff_cancel_left [simp]: \"(a + b) - a = b\"\n    by (simp add: minus_def)\n\n  lemma diff_zero [simp]: \"a - 0 = a\"\n    by (metis local.add_0_left local.add_diff_cancel_left)\n\n  lemma diff_cancel [simp]: \"a - a = 0\"\n    by (metis local.add_0_right local.add_diff_cancel_left)\n\n  lemma add_left_mono: \"a \\<le> b \\<Longrightarrow> c + a \\<le> c + b\"\n    by (simp add: local.le_is_monoid_le local.monoid_le_add_left_mono)\n\n  lemma add_le_imp_le_left: \"c + a \\<le> c + b \\<Longrightarrow> a \\<le> b\"\n    by (auto simp add: le_iff_add, metis add_assoc local.add_diff_cancel_left)\n\n  lemma add_diff_cancel_left' [simp]:  \"(c + a) - (c + b) = a - b\"\n  proof (cases \"b \\<le> a\")\n    case True thus ?thesis\n      by (metis add_assoc local.add_diff_cancel_left local.le_iff_add local.monoid_le_def)\n  next\n    case False thus ?thesis\n      using local.add_le_imp_le_left not_le_minus by blast\n  qed\n\n  lemma minus_zero_eq: \"\\<lbrakk> b \\<le> a; a - b = 0 \\<rbrakk> \\<Longrightarrow> a = b\"\n    using local.le_iff_add local.monoid_le_def by auto\n\n  lemma diff_add_cancel_left': \"a \\<le> b \\<Longrightarrow> a + (b - a) = b\"\n    using local.le_iff_add local.monoid_le_def by auto\n\nend\n\ninstantiation list :: (type) monoid_add\nbegin\n\n  definition zero_list :: \"'a list\" where \"zero_list = []\"\n  definition plus_list :: \"'a list \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where \"plus_list = op @\"\n\ninstance\n  by (intro_classes, simp_all add: zero_list_def plus_list_def)\n\nend\n\nlemma monoid_le_list:\n  \"(xs :: 'a list) \\<le>\\<^sub>m ys \\<longleftrightarrow> xs \\<le> ys\"\n  apply (simp add: monoid_le_def plus_list_def)\n  using Prefix_Order.prefixE Prefix_Order.prefixI apply blast\ndone\n\nlemma monoid_subtract_list:\n  \"(xs :: 'a list) -\\<^sub>m ys = xs - ys\"\n  apply (auto simp add: monoid_subtract_def monoid_le_list minus_list_def less_eq_list_def)\n  apply (rule the_equality)\n  apply (simp_all add: zero_list_def plus_list_def prefix_drop)\ndone\n\ninstance list :: (type) ordered_cancel_monoid_diff\n  apply (intro_classes, simp_all add: zero_list_def plus_list_def monoid_le_def monoid_subtract_list)\n  using Prefix_Order.prefixE Prefix_Order.prefixI apply blast\n  apply (simp add: less_list_def)\ndone\n\nlemma monoid_le_nat:\n  \"(x :: nat) \\<le>\\<^sub>m y \\<longleftrightarrow> x \\<le> y\"\n  using ordered_cancel_comm_monoid_diff_class.le_iff_add \n  by (auto simp add: monoid_le_def )\n\nlemma monoid_subtract_nat:\n  \"(x :: nat) -\\<^sub>m y = x - y\"\n  by (auto simp add: monoid_subtract_def monoid_le_nat) \n\ninstance nat :: ordered_cancel_monoid_diff\n  apply (intro_classes, simp_all add: monoid_subtract_nat)\n  apply (simp add: monoid_le_nat)\n  apply linarith\ndone\n\nend", "meta": {"author": "git-vt", "repo": "orca", "sha": "92bda0f9cfe5cc680b9c405fc38f07a960087a36", "save_path": "github-repos/isabelle/git-vt-orca", "path": "github-repos/isabelle/git-vt-orca/orca-92bda0f9cfe5cc680b9c405fc38f07a960087a36/Archive/Programming-Languages-Semantics/WP11-C-semantics/src/IMP-Lenses/utils/Monoid_extra.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357666736772, "lm_q2_score": 0.824461932846258, "lm_q1q2_score": 0.7148379840386171}}
{"text": "section \\<open>Basic Concepts\\<close>\ntheory Refine_Basic\nimports Main \n  \"HOL-Library.Monad_Syntax\" \n  Refine_Misc\n  \"Generic/RefineG_Recursion\"\n  \"Generic/RefineG_Assert\"\nbegin\n\n\nsubsection \\<open>Nondeterministic Result Lattice and Monad\\<close>\ntext \\<open>\n  In this section we introduce a complete lattice of result sets with an\n  additional top element that represents failure. On this lattice, we define\n  a monad: The return operator models a result that consists of a single value,\n  and the bind operator models applying a function to all results.\n  Binding a failure yields always a failure.\n  \n  In addition to the return operator, we also introduce the operator \n  \\<open>RES\\<close>, that embeds a set of results into our lattice. Its synonym for\n  a predicate is \\<open>SPEC\\<close>.\n\n  Program correctness is expressed by refinement, i.e., the expression\n  \\<open>M \\<le> SPEC \\<Phi>\\<close> means that \\<open>M\\<close> is correct w.r.t.\\ \n  specification \\<open>\\<Phi>\\<close>. This suggests the following view on the program \n  lattice: The top-element is the result that is never correct. We call this\n  result \\<open>FAIL\\<close>. The bottom element is the program that is always correct.\n  It is called \\<open>SUCCEED\\<close>. An assertion can be encoded by failing if the\n  asserted predicate is not true. Symmetrically, an assumption is encoded by\n  succeeding if the predicate is not true. \n\\<close>\n\n\ndatatype 'a nres = FAILi | RES \"'a set\"\ntext \\<open>\n  \\<open>FAILi\\<close> is only an internal notation, that should not be exposed to \n  the user.\n  Instead, \\<open>FAIL\\<close> should be used, that is defined later as abbreviation \n  for the top element of the lattice.\n\\<close>\ninstantiation nres :: (type) complete_lattice\nbegin\nfun less_eq_nres where\n  \"_ \\<le> FAILi \\<longleftrightarrow> True\" |\n  \"(RES a) \\<le> (RES b) \\<longleftrightarrow> a\\<subseteq>b\" |\n  \"FAILi \\<le> (RES _) \\<longleftrightarrow> False\"\n\nfun less_nres where\n  \"FAILi < _ \\<longleftrightarrow> False\" |\n  \"(RES _) < FAILi \\<longleftrightarrow> True\" |\n  \"(RES a) < (RES b) \\<longleftrightarrow> a\\<subset>b\"\n\nfun sup_nres where\n  \"sup _ FAILi = FAILi\" |\n  \"sup FAILi _ = FAILi\" |\n  \"sup (RES a) (RES b) = RES (a\\<union>b)\"\n\nfun inf_nres where \n  \"inf x FAILi = x\" |\n  \"inf FAILi x = x\" |\n  \"inf (RES a) (RES b) = RES (a\\<inter>b)\"\n\ndefinition \"Sup X \\<equiv> if FAILi\\<in>X then FAILi else RES (\\<Union>{x . RES x \\<in> X})\"\ndefinition \"Inf X \\<equiv> if \\<exists>x. RES x\\<in>X then RES (\\<Inter>{x . RES x \\<in> X}) else FAILi\"\n\ndefinition \"bot \\<equiv> RES {}\"\ndefinition \"top \\<equiv> FAILi\"\n\ninstance\n  apply (intro_classes)\n  unfolding Sup_nres_def Inf_nres_def bot_nres_def top_nres_def\n  apply (case_tac x, case_tac [!] y, auto) []\n  apply (case_tac x, auto) []\n  apply (case_tac x, case_tac [!] y, case_tac [!] z, auto) []\n  apply (case_tac x, (case_tac [!] y)?, auto) []\n  apply (case_tac x, (case_tac [!] y)?, simp_all) []\n  apply (case_tac x, (case_tac [!] y)?, auto) []\n  apply (case_tac x, case_tac [!] y, case_tac [!] z, auto) []\n  apply (case_tac x, (case_tac [!] y)?, auto) []\n  apply (case_tac x, (case_tac [!] y)?, auto) []\n  apply (case_tac x, case_tac [!] y, case_tac [!] z, auto) []\n  apply (case_tac x, auto) []\n  apply (case_tac z, fastforce+) []\n  apply (case_tac x, auto) []\n  apply (case_tac z, fastforce+) []\n  apply auto []\n  apply auto []\n  done\n  \nend\n\nabbreviation \"FAIL \\<equiv> top::'a nres\"\nabbreviation \"SUCCEED \\<equiv> bot::'a nres\"\nabbreviation \"SPEC \\<Phi> \\<equiv> RES (Collect \\<Phi>)\"\ndefinition \"RETURN x \\<equiv> RES {x}\"\n\ntext \\<open>We try to hide the original \\<open>FAILi\\<close>-element as well as possible. \n\\<close>\nlemma nres_cases[case_names FAIL RES, cases type]:\n  obtains \"M=FAIL\" | X where \"M=RES X\"\n  apply (cases M, fold top_nres_def) by auto\n\nlemma nres_simp_internals: \n  \"RES {} = SUCCEED\"\n  \"FAILi = FAIL\" \n  unfolding top_nres_def bot_nres_def by simp_all\n\nlemma nres_inequalities[simp]: \n  \"FAIL \\<noteq> RES X\"\n  \"FAIL \\<noteq> SUCCEED\" \n  \"FAIL \\<noteq> RETURN x\"\n  \"SUCCEED \\<noteq> FAIL\"\n  \"SUCCEED \\<noteq> RETURN x\"\n  \"RES X \\<noteq> FAIL\"\n  \"RETURN x \\<noteq> FAIL\"\n  \"RETURN x \\<noteq> SUCCEED\"\n  unfolding top_nres_def bot_nres_def RETURN_def\n  by auto\n\nlemma nres_more_simps[simp]:\n  \"SUCCEED = RES X \\<longleftrightarrow> X={}\"\n  \"RES X = SUCCEED \\<longleftrightarrow> X={}\"\n  \"RES X = RETURN x \\<longleftrightarrow> X={x}\"\n  \"RES X = RES Y \\<longleftrightarrow> X=Y\"\n  \"RETURN x = RES X \\<longleftrightarrow> {x}=X\"\n  \"RETURN x = RETURN y \\<longleftrightarrow> x=y\"\n  unfolding top_nres_def bot_nres_def RETURN_def by auto\n\nlemma nres_order_simps[simp]:\n  \"\\<And>M. SUCCEED \\<le> M\"\n  \"\\<And>M. M \\<le> SUCCEED \\<longleftrightarrow> M=SUCCEED\"\n  \"\\<And>M. M \\<le> FAIL\"\n  \"\\<And>M. FAIL \\<le> M \\<longleftrightarrow> M=FAIL\"\n  \"\\<And>X Y. RES X \\<le> RES Y \\<longleftrightarrow> X\\<le>Y\"\n  \"\\<And>X. Sup X = FAIL \\<longleftrightarrow> FAIL\\<in>X\"\n  \"\\<And>X f. Sup (f ` X) = FAIL \\<longleftrightarrow> FAIL \\<in> f ` X\"\n  \"\\<And>X. FAIL = Sup X \\<longleftrightarrow> FAIL\\<in>X\"\n  \"\\<And>X f. FAIL = Sup (f ` X) \\<longleftrightarrow> FAIL \\<in> f ` X\"\n  \"\\<And>X. FAIL\\<in>X \\<Longrightarrow> Sup X = FAIL\"\n  \"\\<And>X. FAIL\\<in>f ` X \\<Longrightarrow> Sup (f ` X) = FAIL\"\n  \"\\<And>A. Sup (RES ` A) = RES (Sup A)\"\n  \"\\<And>A. Sup (RES ` A) = RES (Sup A)\"\n  \"\\<And>A. A\\<noteq>{} \\<Longrightarrow> Inf (RES`A) = RES (Inf A)\"\n  \"\\<And>A. A\\<noteq>{} \\<Longrightarrow> Inf (RES ` A) = RES (Inf A)\"\n  \"Inf {} = FAIL\"\n  \"Inf UNIV = SUCCEED\"\n  \"Sup {} = SUCCEED\"\n  \"Sup UNIV = FAIL\"\n  \"\\<And>x y. RETURN x \\<le> RETURN y \\<longleftrightarrow> x=y\"\n  \"\\<And>x Y. RETURN x \\<le> RES Y \\<longleftrightarrow> x\\<in>Y\"\n  \"\\<And>X y. RES X \\<le> RETURN y \\<longleftrightarrow> X \\<subseteq> {y}\"\n  unfolding Sup_nres_def Inf_nres_def RETURN_def\n  by (auto simp add: bot_unique top_unique nres_simp_internals)\n\nlemma Sup_eq_RESE:\n  assumes \"Sup A = RES B\"\n  obtains C where \"A=RES`C\" and \"B=Sup C\"\nproof -\n  show ?thesis\n    using assms unfolding Sup_nres_def\n    apply (simp split: if_split_asm)\n    apply (rule_tac C=\"{X. RES X \\<in> A}\" in that)\n    apply auto []\n    apply (case_tac x, auto simp: nres_simp_internals) []\n    apply (auto simp: nres_simp_internals) []\n    done\nqed\n\ndeclare nres_simp_internals[simp]\n\nsubsubsection \\<open>Pointwise Reasoning\\<close>\n\nML \\<open>\n  structure refine_pw_simps = Named_Thms\n    ( val name = @{binding refine_pw_simps}\n      val description = \"Refinement Framework: \" ^\n        \"Simplifier rules for pointwise reasoning\" )\n\\<close>    \nsetup \\<open>refine_pw_simps.setup\\<close>\n  \ndefinition \"nofail S \\<equiv> S\\<noteq>FAIL\"\ndefinition \"inres S x \\<equiv> RETURN x \\<le> S\"\n\nlemma nofail_simps[simp, refine_pw_simps]:\n  \"nofail FAIL \\<longleftrightarrow> False\"\n  \"nofail (RES X) \\<longleftrightarrow> True\"\n  \"nofail (RETURN x) \\<longleftrightarrow> True\"\n  \"nofail SUCCEED \\<longleftrightarrow> True\"\n  unfolding nofail_def\n  by (simp_all add: RETURN_def)\n\nlemma inres_simps[simp, refine_pw_simps]:\n  \"inres FAIL = (\\<lambda>_. True)\"\n  \"inres (RES X) = (\\<lambda>x. x\\<in>X)\"\n  \"inres (RETURN x) = (\\<lambda>y. x=y)\"\n  \"inres SUCCEED = (\\<lambda>_. False)\"\n  unfolding inres_def [abs_def]\n  by (auto simp add: RETURN_def)\n\nlemma not_nofail_iff: \n  \"\\<not>nofail S \\<longleftrightarrow> S=FAIL\" by (cases S) auto\n\nlemma not_nofail_inres[simp, refine_pw_simps]: \n  \"\\<not>nofail S \\<Longrightarrow> inres S x\" \n  apply (cases S) by auto\n\nlemma intro_nofail[refine_pw_simps]: \n  \"S\\<noteq>FAIL \\<longleftrightarrow> nofail S\"\n  \"FAIL\\<noteq>S \\<longleftrightarrow> nofail S\"\n  by (cases S, simp_all)+\n\ntext \\<open>The following two lemmas will introduce pointwise reasoning for\n  orderings and equalities.\\<close>\nlemma pw_le_iff: \n  \"S \\<le> S' \\<longleftrightarrow> (nofail S'\\<longrightarrow> (nofail S \\<and> (\\<forall>x. inres S x \\<longrightarrow> inres S' x)))\"\n  apply (cases S, simp_all)\n  apply (case_tac [!] S', auto)\n  done\n\nlemma pw_eq_iff:\n  \"S=S' \\<longleftrightarrow> (nofail S = nofail S' \\<and> (\\<forall>x. inres S x \\<longleftrightarrow> inres S' x))\"\n  apply (rule iffI)\n  apply simp\n  apply (rule antisym)\n  apply (simp_all add: pw_le_iff)\n  done\n\nlemma pw_flat_le_iff: \"flat_le S S' \\<longleftrightarrow> \n  (\\<exists>x. inres S x) \\<longrightarrow> (nofail S \\<longleftrightarrow> nofail S') \\<and> (\\<forall>x. inres S x \\<longleftrightarrow> inres S' x)\"\n  by (auto simp : flat_ord_def pw_eq_iff)\n  \nlemma pw_flat_ge_iff: \"flat_ge S S' \\<longleftrightarrow> \n  (nofail S) \\<longrightarrow> nofail S' \\<and> (\\<forall>x. inres S x \\<longleftrightarrow> inres S' x)\"\n  apply (simp add: flat_ord_def pw_eq_iff) apply safe\n  apply simp\n  apply simp\n  apply simp\n  apply (rule ccontr)\n  apply simp\n  done\n\nlemmas pw_ords_iff = pw_le_iff pw_flat_le_iff pw_flat_ge_iff\n\nlemma pw_leI: \n  \"(nofail S'\\<longrightarrow> (nofail S \\<and> (\\<forall>x. inres S x \\<longrightarrow> inres S' x))) \\<Longrightarrow> S \\<le> S'\"\n  by (simp add: pw_le_iff)\n\nlemma pw_leI': \n  assumes \"nofail S' \\<Longrightarrow> nofail S\"\n  assumes \"\\<And>x. \\<lbrakk>nofail S'; inres S x\\<rbrakk> \\<Longrightarrow> inres S' x\"\n  shows \"S \\<le> S'\"\n  using assms\n  by (simp add: pw_le_iff)\n\nlemma pw_eqI: \n  assumes \"nofail S = nofail S'\" \n  assumes \"\\<And>x. inres S x \\<longleftrightarrow> inres S' x\" \n  shows \"S=S'\"\n  using assms by (simp add: pw_eq_iff)\n\nlemma pwD1:\n  assumes \"S\\<le>S'\" \"nofail S'\" \n  shows \"nofail S\"\n  using assms by (simp add: pw_le_iff)\n\nlemma pwD2:\n  assumes \"S\\<le>S'\" \"inres S x\"\n  shows \"inres S' x\"\n  using assms \n  by (auto simp add: pw_le_iff)\n\nlemmas pwD = pwD1 pwD2\n\ntext \\<open>\n  When proving refinement, we may assume that the refined program does not \n  fail.\\<close>\nlemma le_nofailI: \"\\<lbrakk> nofail M' \\<Longrightarrow> M \\<le> M' \\<rbrakk> \\<Longrightarrow> M \\<le> M'\"\n  by (cases M') auto\n\ntext \\<open>The following lemmas push pointwise reasoning over operators,\n  thus converting an expression over lattice operators into a logical\n  formula.\\<close>\n\nlemma pw_sup_nofail[refine_pw_simps]:\n  \"nofail (sup a b) \\<longleftrightarrow> nofail a \\<and> nofail b\"\n  apply (cases a, simp)\n  apply (cases b, simp_all)\n  done\n\nlemma pw_sup_inres[refine_pw_simps]:\n  \"inres (sup a b) x \\<longleftrightarrow> inres a x \\<or> inres b x\"\n  apply (cases a, simp)\n  apply (cases b, simp)\n  apply (simp)\n  done\n\nlemma pw_Sup_inres[refine_pw_simps]: \"inres (Sup X) r \\<longleftrightarrow> (\\<exists>M\\<in>X. inres M r)\"\n  apply (cases \"Sup X\")\n  apply (simp)\n  apply (erule bexI[rotated])\n  apply simp\n  apply (erule Sup_eq_RESE)\n  apply (simp)\n  done\n\nlemma pw_SUP_inres [refine_pw_simps]: \"inres (Sup (f ` X)) r \\<longleftrightarrow> (\\<exists>M\\<in>X. inres (f M) r)\"\n  using pw_Sup_inres [of \"f ` X\"] by simp\n\nlemma pw_Sup_nofail[refine_pw_simps]: \"nofail (Sup X) \\<longleftrightarrow> (\\<forall>x\\<in>X. nofail x)\"\n  apply (cases \"Sup X\")\n  apply force\n  apply simp\n  apply (erule Sup_eq_RESE)\n  apply auto\n  done\n\nlemma pw_SUP_nofail [refine_pw_simps]: \"nofail (Sup (f ` X)) \\<longleftrightarrow> (\\<forall>x\\<in>X. nofail (f x))\"\n  using pw_Sup_nofail [of \"f ` X\"] by simp\n\nlemma pw_inf_nofail[refine_pw_simps]:\n  \"nofail (inf a b) \\<longleftrightarrow> nofail a \\<or> nofail b\"\n  apply (cases a, simp)\n  apply (cases b, simp_all)\n  done\n\nlemma pw_inf_inres[refine_pw_simps]:\n  \"inres (inf a b) x \\<longleftrightarrow> inres a x \\<and> inres b x\"\n  apply (cases a, simp)\n  apply (cases b, simp)\n  apply (simp)\n  done\n\nlemma pw_Inf_nofail[refine_pw_simps]: \"nofail (Inf C) \\<longleftrightarrow> (\\<exists>x\\<in>C. nofail x)\"\n  apply (cases \"C={}\")\n  apply simp\n  apply (cases \"Inf C\")\n  apply (subgoal_tac \"C={FAIL}\")\n  apply simp\n  apply auto []\n  apply (subgoal_tac \"C\\<noteq>{FAIL}\")\n  apply (auto simp: not_nofail_iff) []\n  apply auto []\n  done\n\nlemma pw_INF_nofail [refine_pw_simps]: \"nofail (Inf (f ` C)) \\<longleftrightarrow> (\\<exists>x\\<in>C. nofail (f x))\"\n  using pw_Inf_nofail [of \"f ` C\"] by simp\n\nlemma pw_Inf_inres[refine_pw_simps]: \"inres (Inf C) r \\<longleftrightarrow> (\\<forall>M\\<in>C. inres M r)\"\n  apply (unfold Inf_nres_def)\n  apply auto\n  apply (case_tac M)\n  apply force\n  apply force\n  apply (case_tac M)\n  apply force\n  apply force\n  done\n\nlemma pw_INF_inres [refine_pw_simps]: \"inres (Inf (f ` C)) r \\<longleftrightarrow> (\\<forall>M\\<in>C. inres (f M) r)\"\n  using pw_Inf_inres [of \"f ` C\"] by simp\n\nlemma nofail_RES_conv: \"nofail m \\<longleftrightarrow> (\\<exists>M. m=RES M)\" by (cases m) auto\n\nprimrec the_RES where \"the_RES (RES X) = X\"\nlemma the_RES_inv[simp]: \"nofail m \\<Longrightarrow> RES (the_RES m) = m\"\n  by (cases m) auto\n\ndefinition [refine_pw_simps]: \"nf_inres m x \\<equiv> nofail m \\<and> inres m x\"\n\nlemma nf_inres_RES[simp]: \"nf_inres (RES X) x \\<longleftrightarrow> x\\<in>X\" \n  by (simp add: refine_pw_simps)\n  \nlemma nf_inres_SPEC[simp]: \"nf_inres (SPEC \\<Phi>) x \\<longleftrightarrow> \\<Phi> x\" \n  by (simp add: refine_pw_simps)\n\nlemma nofail_antimono_fun: \"f \\<le> g \\<Longrightarrow> (nofail (g x) \\<longrightarrow> nofail (f x))\"\n  by (auto simp: pw_le_iff dest: le_funD)\n\n\nsubsubsection \\<open>Monad Operators\\<close>\ndefinition bind where \"bind M f \\<equiv> case M of \n  FAILi \\<Rightarrow> FAIL |\n  RES X \\<Rightarrow> Sup (f`X)\"\n\nlemma bind_FAIL[simp]: \"bind FAIL f = FAIL\"\n  unfolding bind_def by (auto split: nres.split)\n\nlemma bind_SUCCEED[simp]: \"bind SUCCEED f = SUCCEED\"\n  unfolding bind_def by (auto split: nres.split)\n\nlemma bind_RES: \"bind (RES X) f = Sup (f`X)\" unfolding bind_def \n  by (auto)\n\nadhoc_overloading\n  Monad_Syntax.bind Refine_Basic.bind\n\nlemma pw_bind_nofail[refine_pw_simps]:\n  \"nofail (bind M f) \\<longleftrightarrow> (nofail M \\<and> (\\<forall>x. inres M x \\<longrightarrow> nofail (f x)))\"\n  apply (cases M)\n  by (auto simp: bind_RES refine_pw_simps)\n  \nlemma pw_bind_inres[refine_pw_simps]:\n  \"inres (bind M f) = (\\<lambda>x. nofail M \\<longrightarrow> (\\<exists>y. (inres M y \\<and> inres (f y) x)))\"\n  apply (rule ext)\n  apply (cases M)\n  apply (auto simp add: bind_RES refine_pw_simps)\n  done\n\nlemma pw_bind_le_iff:\n  \"bind M f \\<le> S \\<longleftrightarrow> (nofail S \\<longrightarrow> nofail M) \\<and> \n    (\\<forall>x. nofail M \\<and> inres M x \\<longrightarrow> f x \\<le> S)\"\n  by (auto simp: pw_le_iff refine_pw_simps)\n\nlemma pw_bind_leI: \"\\<lbrakk> \n  nofail S \\<Longrightarrow> nofail M; \\<And>x. \\<lbrakk>nofail M; inres M x\\<rbrakk> \\<Longrightarrow> f x \\<le> S\\<rbrakk> \n  \\<Longrightarrow> bind M f \\<le> S\"\n  by (simp add: pw_bind_le_iff)\n\ntext \\<open>\\paragraph{Monad Laws}\\<close>\n\n\ntext \\<open>\\paragraph{Congruence rule for bind}\\<close>\nlemma bind_cong:\n  assumes \"m=m'\"\n  assumes \"\\<And>x. RETURN x \\<le> m' \\<Longrightarrow> f x = f' x\"\n  shows \"bind m f = bind m' f'\"  \n  using assms\n  by (auto simp: refine_pw_simps pw_eq_iff pw_le_iff)\n\ntext \\<open>\\paragraph{Monotonicity and Related Properties}\\<close>\nlemma bind_mono[refine_mono]:\n  \"\\<lbrakk> M \\<le> M'; \\<And>x. RETURN x \\<le> M \\<Longrightarrow> f x \\<le> f' x \\<rbrakk> \\<Longrightarrow> bind M f \\<le> bind M' f'\"\n  (*\"\\<lbrakk> flat_le M M'; \\<And>x. flat_le (f x) (f' x) \\<rbrakk> \\<Longrightarrow> flat_le (bind M f) (bind M' f')\"*)\n  \"\\<lbrakk> flat_ge M M'; \\<And>x. flat_ge (f x) (f' x) \\<rbrakk> \\<Longrightarrow> flat_ge (bind M f) (bind M' f')\"\n  apply (auto simp: refine_pw_simps pw_ords_iff) []\n  apply (auto simp: refine_pw_simps pw_ords_iff) []\n  done\n\nlemma bind_mono1[simp, intro!]: \"mono (\\<lambda>M. bind M f)\"\n  apply (rule monoI)\n  apply (rule bind_mono)\n  by auto\n\nlemma bind_mono1'[simp, intro!]: \"mono bind\"\n  apply (rule monoI)\n  apply (rule le_funI)\n  apply (rule bind_mono)\n  by auto\n\nlemma bind_mono2'[simp, intro!]: \"mono (bind M)\"\n  apply (rule monoI)\n  apply (rule bind_mono)\n  by (auto dest: le_funD)\n\n\nlemma bind_distrib_sup1: \"bind (sup M N) f = sup (bind M f) (bind N f)\"\n  by (auto simp add: pw_eq_iff refine_pw_simps)\n\nlemma  bind_distrib_sup2: \"bind m (\\<lambda>x. sup (f x) (g x)) = sup (bind m f) (bind m g)\"\n  by (auto simp: pw_eq_iff refine_pw_simps)\n\nlemma bind_distrib_Sup1: \"bind (Sup M) f = (SUP m\\<in>M. bind m f)\" \n  by (auto simp: pw_eq_iff refine_pw_simps)\n\nlemma bind_distrib_Sup2: \"F\\<noteq>{} \\<Longrightarrow> bind m (Sup F) = (SUP f\\<in>F. bind m f)\"\n  by (auto simp: pw_eq_iff refine_pw_simps)\n\n\nlemma RES_Sup_RETURN: \"Sup (RETURN`X) = RES X\"\n  by (rule pw_eqI) (auto simp add: refine_pw_simps)\n\n    \nsubsection \\<open>VCG Setup\\<close>\n  \nlemma SPEC_cons_rule:\n  assumes \"m \\<le> SPEC \\<Phi>\"\n  assumes \"\\<And>x. \\<Phi> x \\<Longrightarrow> \\<Psi> x\"\n  shows \"m \\<le> SPEC \\<Psi>\"\n  using assms by (auto simp: pw_le_iff)\n  \nlemmas SPEC_trans = order_trans[where z=\"SPEC Postcond\" for Postcond, zero_var_indexes]\n  \nML \\<open>\nstructure Refine = struct\n\n  structure vcg = Named_Thms\n    ( val name = @{binding refine_vcg}\n      val description = \"Refinement Framework: \" ^ \n        \"Verification condition generation rules (intro)\" )\n\n  structure vcg_cons = Named_Thms\n    ( val name = @{binding refine_vcg_cons}\n      val description = \"Refinement Framework: \" ^\n        \"Consequence rules tried by VCG\" )\n\n  structure refine0 = Named_Thms\n    ( val name = @{binding refine0}\n      val description = \"Refinement Framework: \" ^\n        \"Refinement rules applied first (intro)\" )\n\n  structure refine = Named_Thms\n    ( val name = @{binding refine}\n      val description = \"Refinement Framework: Refinement rules (intro)\" )\n\n  structure refine2 = Named_Thms\n    ( val name = @{binding refine2}\n      val description = \"Refinement Framework: \" ^\n        \"Refinement rules 2nd stage (intro)\" )\n\n  (* If set to true, the product splitter of refine_rcg is disabled. *)\n  val no_prod_split = \n    Attrib.setup_config_bool @{binding refine_no_prod_split} (K false);\n\n  fun rcg_tac add_thms ctxt = \n    let \n      val cons_thms = vcg_cons.get ctxt\n      val ref_thms = (refine0.get ctxt \n        @ add_thms @ refine.get ctxt @ refine2.get ctxt);\n      val prod_ss = (Splitter.add_split @{thm prod.split} \n        (put_simpset HOL_basic_ss ctxt));\n      val prod_simp_tac = \n        if Config.get ctxt no_prod_split then \n          K no_tac\n        else\n          (simp_tac prod_ss THEN' \n            REPEAT_ALL_NEW (resolve_tac ctxt @{thms impI allI}));\n    in\n      REPEAT_ALL_NEW_FWD (DETERM o FIRST' [\n        resolve_tac ctxt ref_thms,\n        resolve_tac ctxt cons_thms THEN' resolve_tac ctxt ref_thms,\n        prod_simp_tac\n      ])\n    end;\n\n  fun post_tac ctxt = REPEAT_ALL_NEW_FWD (FIRST' [\n    eq_assume_tac,\n    (*match_tac ctxt thms,*)\n    SOLVED' (Tagged_Solver.solve_tac ctxt)]) \n         \n\nend;\n\\<close>\nsetup \\<open>Refine.vcg.setup\\<close>\nsetup \\<open>Refine.vcg_cons.setup\\<close>\nsetup \\<open>Refine.refine0.setup\\<close>\nsetup \\<open>Refine.refine.setup\\<close>\nsetup \\<open>Refine.refine2.setup\\<close>\n(*setup {* Refine.refine_post.setup *}*)\n\nmethod_setup refine_rcg = \n  \\<open>Attrib.thms >> (fn add_thms => fn ctxt => SIMPLE_METHOD' (\n    Refine.rcg_tac add_thms ctxt THEN_ALL_NEW_FWD (TRY o Refine.post_tac ctxt)\n  ))\\<close> \n  \"Refinement framework: Generate refinement conditions\"\n\nmethod_setup refine_vcg = \n  \\<open>Attrib.thms >> (fn add_thms => fn ctxt => SIMPLE_METHOD' (\n    Refine.rcg_tac (add_thms @ Refine.vcg.get ctxt) ctxt THEN_ALL_NEW_FWD (TRY o Refine.post_tac ctxt)\n  ))\\<close> \n  \"Refinement framework: Generate refinement and verification conditions\"\n\n\n  (* Use tagged-solver instead!\n  method_setup refine_post = \n    {* Scan.succeed (fn ctxt => SIMPLE_METHOD' (\n      Refine.post_tac ctxt\n    )) *} \n    \"Refinement framework: Postprocessing of refinement goals\"\n    *)\n\ndeclare SPEC_cons_rule[refine_vcg_cons]    \n    \n    \nsubsection \\<open>Data Refinement\\<close>\ntext \\<open>\n  In this section we establish a notion of pointwise data refinement, by\n  lifting a relation \\<open>R\\<close> between concrete and abstract values to \n  our result lattice.\n\n  Given a relation \\<open>R\\<close>, we define a {\\em concretization function}\n  \\<open>\\<Down>R\\<close> that takes an abstract result, and returns a concrete result.\n  The concrete result contains all values that are mapped by \\<open>R\\<close> to\n  a value in the abstract result.\n\n  Note that our concretization function forms no Galois connection, i.e.,\n  in general there is no \\<open>\\<alpha>\\<close> such that \n  \\<open>m \\<le>\\<Down> R m'\\<close> is equivalent to \\<open>\\<alpha> m \\<le> m'\\<close>.\n  However, we get a Galois connection for the special case of \n  single-valued relations.\n \n  Regarding data refinement as Galois connections is inspired by \\cite{mmo97},\n  that also uses the adjuncts of\n  a Galois connection to express data refinement by program refinement.\n\\<close>\n\ndefinition conc_fun (\"\\<Down>\") where\n  \"conc_fun R m \\<equiv> case m of FAILi \\<Rightarrow> FAIL | RES X \\<Rightarrow> RES (R\\<inverse>``X)\"\n\ndefinition abs_fun (\"\\<Up>\") where\n  \"abs_fun R m \\<equiv> case m of FAILi \\<Rightarrow> FAIL \n    | RES X \\<Rightarrow> if X\\<subseteq>Domain R then RES (R``X) else FAIL\"\n\nlemma \n  conc_fun_FAIL[simp]: \"\\<Down>R FAIL = FAIL\" and\n  conc_fun_RES: \"\\<Down>R (RES X) = RES (R\\<inverse>``X)\"\n  unfolding conc_fun_def by (auto split: nres.split)\n\nlemma abs_fun_simps[simp]: \n  \"\\<Up>R FAIL = FAIL\"\n  \"X\\<subseteq>Domain R \\<Longrightarrow> \\<Up>R (RES X) = RES (R``X)\"\n  \"\\<not>(X\\<subseteq>Domain R) \\<Longrightarrow> \\<Up>R (RES X) = FAIL\"\n  unfolding abs_fun_def by (auto split: nres.split)\n  \ncontext fixes R assumes SV: \"single_valued R\" begin\nlemma conc_abs_swap: \"m' \\<le> \\<Down>R m \\<longleftrightarrow> \\<Up>R m' \\<le> m\"\n  unfolding conc_fun_def abs_fun_def using SV\n  by (auto split: nres.split)\n    (metis ImageE converseD single_valuedD subsetD)\n\nlemma ac_galois: \"galois_connection (\\<Up>R) (\\<Down>R)\"\n  apply (unfold_locales)\n  by (rule conc_abs_swap)\n\nend\n\nlemma pw_abs_nofail[refine_pw_simps]: \n  \"nofail (\\<Up>R M) \\<longleftrightarrow> (nofail M \\<and> (\\<forall>x. inres M x \\<longrightarrow> x\\<in>Domain R))\"\n  apply (cases M)\n  apply simp\n  apply (auto simp: abs_fun_simps abs_fun_def)\n  done\n\nlemma pw_abs_inres[refine_pw_simps]: \n  \"inres (\\<Up>R M) a \\<longleftrightarrow> (nofail (\\<Up>R M) \\<longrightarrow> (\\<exists>c. inres M c \\<and> (c,a)\\<in>R))\"\n  apply (cases M)\n  apply simp\n  apply (auto simp: abs_fun_def)\n  done\n\nlemma pw_conc_nofail[refine_pw_simps]: \n  \"nofail (\\<Down>R S) = nofail S\"\n  by (cases S) (auto simp: conc_fun_RES)\n\nlemma pw_conc_inres[refine_pw_simps]:\n  \"inres (\\<Down>R S') = (\\<lambda>s. nofail S' \n  \\<longrightarrow> (\\<exists>s'. (s,s')\\<in>R \\<and> inres S' s'))\"\n  apply (rule ext)\n  apply (cases S')\n  apply (auto simp: conc_fun_RES)\n  done\n\nlemma abs_fun_strict[simp]:\n  \"\\<Up> R SUCCEED = SUCCEED\"\n  unfolding abs_fun_def by (auto split: nres.split)\n\nlemma conc_fun_strict[simp]:\n  \"\\<Down> R SUCCEED = SUCCEED\"\n  unfolding conc_fun_def by (auto split: nres.split)\n\nlemma conc_fun_mono[simp, intro!]: \"mono (\\<Down>R)\"\n  by rule (auto simp: pw_le_iff refine_pw_simps)\n\nlemma abs_fun_mono[simp, intro!]: \"mono (\\<Up>R)\"\n  by rule (auto simp: pw_le_iff refine_pw_simps)\n\nlemma conc_fun_R_mono:\n  assumes \"R \\<subseteq> R'\"\n  shows \"\\<Down>R M \\<le> \\<Down>R' M\"\n  using assms\n  by (auto simp: pw_le_iff refine_pw_simps)\n    \nlemma conc_fun_chain: \"\\<Down>R (\\<Down>S M) = \\<Down>(R O S) M\"\n  unfolding conc_fun_def\n  by (auto split: nres.split)\n\nlemma conc_Id[simp]: \"\\<Down>Id = id\"\n  unfolding conc_fun_def [abs_def] by (auto split: nres.split)\n\nlemma abs_Id[simp]: \"\\<Up>Id = id\"\n  unfolding abs_fun_def [abs_def] by (auto split: nres.split)\n\nlemma conc_fun_fail_iff[simp]: \n  \"\\<Down>R S = FAIL \\<longleftrightarrow> S=FAIL\"\n  \"FAIL = \\<Down>R S \\<longleftrightarrow> S=FAIL\"\n  by (auto simp add: pw_eq_iff refine_pw_simps)\n\nlemma conc_trans[trans]:\n  assumes A: \"C \\<le> \\<Down>R B\" and B: \"B \\<le> \\<Down>R' A\" \n  shows \"C \\<le> \\<Down>R (\\<Down>R' A)\"\n  using assms by (fastforce simp: pw_le_iff refine_pw_simps)\n\nlemma abs_trans[trans]:\n  assumes A: \"\\<Up>R C \\<le> B\" and B: \"\\<Up>R' B \\<le> A\" \n  shows \"\\<Up>R' (\\<Up>R C) \\<le> A\"\n  using assms by (fastforce simp: pw_le_iff refine_pw_simps)\n\nsubsubsection \\<open>Transitivity Reasoner Setup\\<close>\n\ntext \\<open>WARNING: The order of the single statements is important here!\\<close>\nlemma conc_trans_additional[trans]:\n  \"\\<And>A B C. A\\<le>\\<Down>R  B \\<Longrightarrow> B\\<le>    C \\<Longrightarrow> A\\<le>\\<Down>R  C\"\n  \"\\<And>A B C. A\\<le>\\<Down>Id B \\<Longrightarrow> B\\<le>\\<Down>R  C \\<Longrightarrow> A\\<le>\\<Down>R  C\"\n  \"\\<And>A B C. A\\<le>\\<Down>R  B \\<Longrightarrow> B\\<le>\\<Down>Id C \\<Longrightarrow> A\\<le>\\<Down>R  C\"\n\n  \"\\<And>A B C. A\\<le>\\<Down>Id B \\<Longrightarrow> B\\<le>\\<Down>Id C \\<Longrightarrow> A\\<le>    C\"\n  \"\\<And>A B C. A\\<le>\\<Down>Id B \\<Longrightarrow> B\\<le>    C \\<Longrightarrow> A\\<le>    C\"\n  \"\\<And>A B C. A\\<le>    B \\<Longrightarrow> B\\<le>\\<Down>Id C \\<Longrightarrow> A\\<le>    C\"\n  using conc_trans[where R=R and R'=Id]\n  by (auto intro: order_trans)\n\ntext \\<open>WARNING: The order of the single statements is important here!\\<close>\nlemma abs_trans_additional[trans]:\n  \"\\<And>A B C. \\<lbrakk> A \\<le> B; \\<Up> R B \\<le> C\\<rbrakk> \\<Longrightarrow> \\<Up> R A \\<le> C\"\n  \"\\<And>A B C. \\<lbrakk>\\<Up> Id A \\<le> B; \\<Up> R B \\<le> C\\<rbrakk> \\<Longrightarrow> \\<Up> R A \\<le> C\"\n  \"\\<And>A B C. \\<lbrakk>\\<Up> R A \\<le> B; \\<Up> Id B \\<le> C\\<rbrakk> \\<Longrightarrow> \\<Up> R A \\<le> C\"\n\n  \"\\<And>A B C. \\<lbrakk>\\<Up> Id A \\<le> B; \\<Up> Id B \\<le> C\\<rbrakk> \\<Longrightarrow> A \\<le> C\"\n  \"\\<And>A B C. \\<lbrakk>\\<Up> Id A \\<le> B; B \\<le> C\\<rbrakk> \\<Longrightarrow> A \\<le> C\"\n  \"\\<And>A B C. \\<lbrakk>A \\<le> B; \\<Up> Id B \\<le> C\\<rbrakk> \\<Longrightarrow> A \\<le> C\"\n\n  apply (auto simp: refine_pw_simps pw_le_iff)\n  apply fastforce+\n  done\n\n\nsubsection \\<open>Derived Program Constructs\\<close>\ntext \\<open>\n  In this section, we introduce some programming constructs that are derived \n  from the basic monad and ordering operations of our nondeterminism monad.\n\\<close>\nsubsubsection \\<open>ASSUME and ASSERT\\<close>\n\ndefinition ASSERT where \"ASSERT \\<equiv> iASSERT RETURN\"\ndefinition ASSUME where \"ASSUME \\<equiv> iASSUME RETURN\"\ninterpretation assert?: generic_Assert bind RETURN ASSERT ASSUME\n  apply unfold_locales\n  by (simp_all add: ASSERT_def ASSUME_def)\n\ntext \\<open>Order matters! \\<close>\nlemmas [refine_vcg] = ASSERT_leI \nlemmas [refine_vcg] = le_ASSUMEI \nlemmas [refine_vcg] = le_ASSERTI \nlemmas [refine_vcg] = ASSUME_leI\n    \n    \nlemma pw_ASSERT[refine_pw_simps]:\n  \"nofail (ASSERT \\<Phi>) \\<longleftrightarrow> \\<Phi>\"\n  \"inres (ASSERT \\<Phi>) x\"\n  by (cases \\<Phi>, simp_all)+\n\nlemma pw_ASSUME[refine_pw_simps]:\n  \"nofail (ASSUME \\<Phi>)\"\n  \"inres (ASSUME \\<Phi>) x \\<longleftrightarrow> \\<Phi>\"\n  by (cases \\<Phi>, simp_all)+\n\nsubsubsection \\<open>Recursion\\<close>\nlemma pw_REC_nofail: \n  shows \"nofail (REC B x) \\<longleftrightarrow> trimono B \\<and>\n  (\\<exists>F. (\\<forall>x. \n    nofail (F x) \\<longrightarrow> nofail (B F x) \n    \\<and> (\\<forall>x'. inres (B F x) x' \\<longrightarrow> inres (F x) x')\n  ) \\<and> nofail (F x))\"\nproof -\n  have \"nofail (REC B x) \\<longleftrightarrow> trimono B \\<and>\n  (\\<exists>F. (\\<forall>x. B F x \\<le> F x) \\<and> nofail (F x))\"\n    unfolding REC_def lfp_def\n    apply (auto simp: refine_pw_simps intro: le_funI dest: le_funD)\n    done\n  thus ?thesis\n    unfolding pw_le_iff .\nqed\n\nlemma pw_REC_inres: \n  \"inres (REC B x) x' = (trimono B \\<longrightarrow>\n  (\\<forall>F. (\\<forall>x''. \n    nofail (F x'') \\<longrightarrow> nofail (B F x'') \n    \\<and> (\\<forall>x. inres (B F x'') x \\<longrightarrow> inres (F x'') x)) \n    \\<longrightarrow> inres (F x) x'))\"\nproof -\n  have \"inres (REC B x) x' \n    \\<longleftrightarrow> (trimono B \\<longrightarrow> (\\<forall>F. (\\<forall>x''. B F x'' \\<le> F x'') \\<longrightarrow> inres (F x) x'))\"\n    unfolding REC_def lfp_def\n    by (auto simp: refine_pw_simps intro: le_funI dest: le_funD)\n  thus ?thesis unfolding pw_le_iff .\nqed\n  \nlemmas pw_REC = pw_REC_inres pw_REC_nofail\n\nlemma pw_RECT_nofail: \n  shows \"nofail (RECT B x) \\<longleftrightarrow> trimono B \\<and>\n  (\\<forall>F. (\\<forall>y. nofail (B F y) \\<longrightarrow>\n             nofail (F y) \\<and> (\\<forall>x. inres (F y) x \\<longrightarrow> inres (B F y) x)) \\<longrightarrow>\n        nofail (F x))\"\nproof -\n  have \"nofail (RECT B x) \\<longleftrightarrow> (trimono B \\<and> (\\<forall>F. (\\<forall>y. F y \\<le> B F y) \\<longrightarrow> nofail (F x)))\"\n    unfolding RECT_gfp_def gfp_def\n    by (auto simp: refine_pw_simps intro: le_funI dest: le_funD)\n  thus ?thesis\n    unfolding pw_le_iff .\nqed\n\nlemma pw_RECT_inres: \n  shows \"inres (RECT B x) x' = (trimono B \\<longrightarrow>\n   (\\<exists>M. (\\<forall>y. nofail (B M y) \\<longrightarrow>\n             nofail (M y) \\<and> (\\<forall>x. inres (M y) x \\<longrightarrow> inres (B M y) x)) \\<and>\n        inres (M x) x'))\"\nproof -\n  have \"inres (RECT B x) x' \\<longleftrightarrow> trimono B \\<longrightarrow> (\\<exists>M. (\\<forall>y. M y \\<le> B M y) \\<and> inres (M x) x')\"\n    unfolding RECT_gfp_def gfp_def\n    by (auto simp: refine_pw_simps intro: le_funI dest: le_funD)\n  thus ?thesis unfolding pw_le_iff .\nqed\n  \nlemmas pw_RECT = pw_RECT_inres pw_RECT_nofail\n\n  \n  \nsubsection \\<open>Proof Rules\\<close>\n\nsubsubsection \\<open>Proving Correctness\\<close>\ntext \\<open>\n  In this section, we establish Hoare-like rules to prove that a program\n  meets its specification.\n\\<close>\nlemma le_SPEC_UNIV_rule [refine_vcg]: \n  \"m \\<le> SPEC (\\<lambda>_. True) \\<Longrightarrow> m \\<le> RES UNIV\" by auto\n  \nlemma RETURN_rule[refine_vcg]: \"\\<Phi> x \\<Longrightarrow> RETURN x \\<le> SPEC \\<Phi>\"\n  by (auto simp: RETURN_def)\nlemma RES_rule[refine_vcg]: \"\\<lbrakk>\\<And>x. x\\<in>S \\<Longrightarrow> \\<Phi> x\\<rbrakk> \\<Longrightarrow> RES S \\<le> SPEC \\<Phi>\"\n  by auto\nlemma SUCCEED_rule[refine_vcg]: \"SUCCEED \\<le> SPEC \\<Phi>\" by auto\nlemma FAIL_rule: \"False \\<Longrightarrow> FAIL \\<le> SPEC \\<Phi>\" by auto\nlemma SPEC_rule[refine_vcg]: \"\\<lbrakk>\\<And>x. \\<Phi> x \\<Longrightarrow> \\<Phi>' x\\<rbrakk> \\<Longrightarrow> SPEC \\<Phi> \\<le> SPEC \\<Phi>'\" by auto\n\nlemma RETURN_to_SPEC_rule[refine_vcg]: \"m\\<le>SPEC ((=) v) \\<Longrightarrow> m\\<le>RETURN v\"\n  by (simp add: pw_le_iff refine_pw_simps)\n\nlemma Sup_img_rule_complete: \n  \"(\\<forall>x. x\\<in>S \\<longrightarrow> f x \\<le> SPEC \\<Phi>) \\<longleftrightarrow> Sup (f`S) \\<le> SPEC \\<Phi>\"\n  apply rule\n  apply (rule pw_leI)\n  apply (auto simp: pw_le_iff refine_pw_simps) []\n  apply (intro allI impI)\n  apply (rule pw_leI)\n  apply (auto simp: pw_le_iff refine_pw_simps) []\n  done\n\nlemma SUP_img_rule_complete: \n  \"(\\<forall>x. x\\<in>S \\<longrightarrow> f x \\<le> SPEC \\<Phi>) \\<longleftrightarrow> Sup (f ` S) \\<le> SPEC \\<Phi>\"\n  using Sup_img_rule_complete [of S f] by simp\n\nlemma Sup_img_rule[refine_vcg]: \n  \"\\<lbrakk> \\<And>x. x\\<in>S \\<Longrightarrow> f x \\<le> SPEC \\<Phi> \\<rbrakk> \\<Longrightarrow> Sup(f`S) \\<le> SPEC \\<Phi>\"\n  by (auto simp: SUP_img_rule_complete[symmetric])\n\ntext \\<open>This lemma is just to demonstrate that our rule is complete.\\<close>\nlemma bind_rule_complete: \"bind M f \\<le> SPEC \\<Phi> \\<longleftrightarrow> M \\<le> SPEC (\\<lambda>x. f x \\<le> SPEC \\<Phi>)\"\n  by (auto simp: pw_le_iff refine_pw_simps)\nlemma bind_rule[refine_vcg]: \n  \"\\<lbrakk> M \\<le> SPEC (\\<lambda>x. f x \\<le> SPEC \\<Phi>) \\<rbrakk> \\<Longrightarrow> bind M (\\<lambda>x. f x) \\<le> SPEC \\<Phi>\"\n  \\<comment> \\<open>Note: @{text \"\\<eta>\"}-expanded version helps Isabelle's unification to keep meaningful \n      variable names from the program\\<close>\n  by (auto simp: bind_rule_complete)\n\nlemma ASSUME_rule[refine_vcg]: \"\\<lbrakk>\\<Phi> \\<Longrightarrow> \\<Psi> ()\\<rbrakk> \\<Longrightarrow> ASSUME \\<Phi> \\<le> SPEC \\<Psi>\"\n  by (cases \\<Phi>) auto\n\nlemma ASSERT_rule[refine_vcg]: \"\\<lbrakk>\\<Phi>; \\<Phi> \\<Longrightarrow> \\<Psi> ()\\<rbrakk> \\<Longrightarrow> ASSERT \\<Phi> \\<le> SPEC \\<Psi>\" by auto\n\nlemma prod_rule[refine_vcg]: \n  \"\\<lbrakk>\\<And>a b. p=(a,b) \\<Longrightarrow> S a b \\<le> SPEC \\<Phi>\\<rbrakk> \\<Longrightarrow> case_prod S p \\<le> SPEC \\<Phi>\"\n  by (auto split: prod.split)\n\n(* TODO: Add a simplifier setup that normalizes nested case-expressions to\n  the vcg! *)\nlemma prod2_rule[refine_vcg]:\n  assumes \"\\<And>a b c d. \\<lbrakk>ab=(a,b); cd=(c,d)\\<rbrakk> \\<Longrightarrow> f a b c d \\<le> SPEC \\<Phi>\"\n  shows \"(\\<lambda>(a,b) (c,d). f a b c d) ab cd \\<le> SPEC \\<Phi>\"\n  using assms\n  by (auto split: prod.split)\n\nlemma if_rule[refine_vcg]: \n  \"\\<lbrakk> b \\<Longrightarrow> S1 \\<le> SPEC \\<Phi>; \\<not>b \\<Longrightarrow> S2 \\<le> SPEC \\<Phi>\\<rbrakk> \n  \\<Longrightarrow> (if b then S1 else S2) \\<le> SPEC \\<Phi>\"\n  by (auto)\n\nlemma option_rule[refine_vcg]: \n  \"\\<lbrakk> v=None \\<Longrightarrow> S1 \\<le> SPEC \\<Phi>; \\<And>x. v=Some x \\<Longrightarrow> f2 x \\<le> SPEC \\<Phi>\\<rbrakk> \n  \\<Longrightarrow> case_option S1 f2 v \\<le> SPEC \\<Phi>\"\n  by (auto split: option.split)\n\nlemma Let_rule[refine_vcg]:\n  \"f x \\<le> SPEC \\<Phi> \\<Longrightarrow> Let x f \\<le> SPEC \\<Phi>\" by auto\n\nlemma Let_rule':\n  assumes \"\\<And>x. x=v \\<Longrightarrow> f x \\<le> SPEC \\<Phi>\"\n  shows \"Let v (\\<lambda>x. f x) \\<le> SPEC \\<Phi>\"\n  using assms by simp\n\n\n(* Obsolete, use RECT_eq_REC_tproof instead\ntext {* The following lemma shows that greatest and least fixed point are equal,\n  if we can provide a variant. *}\nthm RECT_eq_REC\nlemma RECT_eq_REC_old:\n  assumes WF: \"wf V\"\n  assumes I0: \"I x\"\n  assumes IS: \"\\<And>f x. I x \\<Longrightarrow> \n    body (\\<lambda>x'. do { ASSERT (I x' \\<and> (x',x)\\<in>V); f x'}) x \\<le> body f x\"\n  shows \"REC\\<^sub>T body x = REC body x\"\n  apply (rule RECT_eq_REC)\n  apply (rule WF)\n  apply (rule I0)\n  apply (rule order_trans[OF _ IS])\n  apply (subgoal_tac \"(\\<lambda>x'. if I x' \\<and> (x', x) \\<in> V then f x' else FAIL) = \n    (\\<lambda>x'. ASSERT (I x' \\<and> (x', x) \\<in> V) \\<bind> (\\<lambda>_. f x'))\")\n  apply simp\n  apply (rule ext)\n  apply (rule pw_eqI)\n  apply (auto simp add: refine_pw_simps)\n  done\n*)\n\n(* TODO: Also require RECT_le_rule. Derive RECT_invisible_refine from that. *)\nlemma REC_le_rule:\n  assumes M: \"trimono body\"\n  assumes I0: \"(x,x')\\<in>R\"\n  assumes IS: \"\\<And>f x x'. \\<lbrakk> \\<And>x x'. (x,x')\\<in>R \\<Longrightarrow> f x \\<le> M x'; (x,x')\\<in>R \\<rbrakk> \n    \\<Longrightarrow> body f x \\<le> M x'\"\n  shows \"REC body x \\<le> M x'\"\n  by (rule REC_rule_arb[OF M, where pre=\"\\<lambda>x' x. (x,x')\\<in>R\", OF I0 IS])\n\n(* TODO: Invariant annotations and vcg-rule\n  Possibility 1: Semantically alter the program, such that it fails if the \n    invariant does not hold\n  Possibility 2: Only syntactically annotate the invariant, as hint for the VCG.\n*)\n\nsubsubsection \\<open>Proving Monotonicity\\<close>\n\nlemma nr_mono_bind:\n  assumes MA: \"mono A\" and MB: \"\\<And>s. mono (B s)\"\n  shows \"mono (\\<lambda>F s. bind (A F s) (\\<lambda>s'. B s F s'))\"\n  apply (rule monoI)\n  apply (rule le_funI)\n  apply (rule bind_mono)\n  apply (auto dest: monoD[OF MA, THEN le_funD]) []\n  apply (auto dest: monoD[OF MB, THEN le_funD]) []\n  done\n\n\nlemma nr_mono_bind': \"mono (\\<lambda>F s. bind (f s) F)\"\n  apply rule\n  apply (rule le_funI)\n  apply (rule bind_mono)\n  apply (auto dest: le_funD)\n  done\n\nlemmas nr_mono = nr_mono_bind nr_mono_bind' mono_const mono_if mono_id\n\nsubsubsection \\<open>Proving Refinement\\<close>\ntext \\<open>In this subsection, we establish rules to prove refinement between \n  structurally similar programs. All rules are formulated including a possible\n  data refinement via a refinement relation. If this is not required, the \n  refinement relation can be chosen to be the identity relation.\n\\<close>\n\ntext \\<open>If we have two identical programs, this rule solves the refinement goal\n  immediately, using the identity refinement relation.\\<close>\nlemma Id_refine[refine0]: \"S \\<le> \\<Down>Id S\" by auto\n\nlemma RES_refine: \n  \"\\<lbrakk> \\<And>s. s\\<in>S \\<Longrightarrow> \\<exists>s'\\<in>S'. (s,s')\\<in>R\\<rbrakk> \\<Longrightarrow> RES S \\<le> \\<Down>R (RES S')\" \n  by (auto simp: conc_fun_RES)\n\nlemma SPEC_refine: \n  assumes \"S \\<le> SPEC (\\<lambda>x. \\<exists>x'. (x,x')\\<in>R \\<and> \\<Phi> x')\"\n  shows \"S \\<le> \\<Down>R (SPEC \\<Phi>)\"\n  using assms\n  by (force simp: pw_le_iff refine_pw_simps)\n\n(* TODO/FIXME: This is already part of a type-based heuristics! *)\nlemma Id_SPEC_refine[refine]: \n  \"S \\<le> SPEC \\<Phi> \\<Longrightarrow> S \\<le> \\<Down>Id (SPEC \\<Phi>)\" by simp\n\n\n\nlemma RETURN_SPEC_refine:\n  assumes \"\\<exists>x'. (x,x')\\<in>R \\<and> \\<Phi> x'\"\n  shows \"RETURN x \\<le> \\<Down>R (SPEC \\<Phi>)\"\n  using assms \n  by (auto simp: pw_le_iff refine_pw_simps)\n\nlemma FAIL_refine[refine]: \"X \\<le> \\<Down>R FAIL\" by auto\nlemma SUCCEED_refine[refine]: \"SUCCEED \\<le> \\<Down>R X'\" by auto\n\nlemma sup_refine[refine]:\n  assumes \"ai \\<le>\\<Down>R a\"\n  assumes \"bi \\<le>\\<Down>R b\"\n  shows \"sup ai bi \\<le>\\<Down>R (sup a b)\"\n  using assms by (auto simp: pw_le_iff refine_pw_simps)\n    \n    \ntext \\<open>The next two rules are incomplete, but a good approximation for refining\n  structurally similar programs.\\<close>\nlemma bind_refine':\n  fixes R' :: \"('a\\<times>'b) set\" and R::\"('c\\<times>'d) set\"\n  assumes R1: \"M \\<le> \\<Down> R' M'\"\n  assumes R2: \"\\<And>x x'. \\<lbrakk> (x,x')\\<in>R'; inres M x; inres M' x';\n    nofail M; nofail M'\n  \\<rbrakk> \\<Longrightarrow> f x \\<le> \\<Down> R (f' x')\"\n  shows \"bind M (\\<lambda>x. f x) \\<le> \\<Down> R (bind M' (\\<lambda>x'. f' x'))\"\n  using assms\n  apply (simp add: pw_le_iff refine_pw_simps)\n  apply fast\n  done\n\nlemma bind_refine[refine]:\n  fixes R' :: \"('a\\<times>'b) set\" and R::\"('c\\<times>'d) set\"\n  assumes R1: \"M \\<le> \\<Down> R' M'\"\n  assumes R2: \"\\<And>x x'. \\<lbrakk> (x,x')\\<in>R' \\<rbrakk> \n    \\<Longrightarrow> f x \\<le> \\<Down> R (f' x')\"\n  shows \"bind M (\\<lambda>x. f x) \\<le> \\<Down> R (bind M' (\\<lambda>x'. f' x'))\"\n  apply (rule bind_refine') using assms by auto\n\nlemma bind_refine_abs': (* Only keep nf_inres-information for abstract *)\n  fixes R' :: \"('a\\<times>'b) set\" and R::\"('c\\<times>'d) set\"\n  assumes R1: \"M \\<le> \\<Down> R' M'\"\n  assumes R2: \"\\<And>x x'. \\<lbrakk> (x,x')\\<in>R'; nf_inres M' x'\n  \\<rbrakk> \\<Longrightarrow> f x \\<le> \\<Down> R (f' x')\"\n  shows \"bind M (\\<lambda>x. f x) \\<le> \\<Down> R (bind M' (\\<lambda>x'. f' x'))\"\n  using assms\n  apply (simp add: pw_le_iff refine_pw_simps)\n  apply blast\n  done\n\n\n\ntext \\<open>Special cases for refinement of binding to \\<open>RES\\<close>\n  statements\\<close>\nlemma bind_refine_RES:\n  \"\\<lbrakk>RES X \\<le> \\<Down> R' M';\n  \\<And>x x'. \\<lbrakk>(x, x') \\<in> R'; x \\<in> X \\<rbrakk> \\<Longrightarrow> f x \\<le> \\<Down> R (f' x')\\<rbrakk>\n  \\<Longrightarrow> RES X \\<bind> (\\<lambda>x. f x) \\<le> \\<Down> R (M' \\<bind> (\\<lambda>x'. f' x'))\"\n\n  \"\\<lbrakk>M \\<le> \\<Down> R' (RES X');\n  \\<And>x x'. \\<lbrakk>(x, x') \\<in> R'; x' \\<in> X' \\<rbrakk> \\<Longrightarrow> f x \\<le> \\<Down> R (f' x')\\<rbrakk>\n  \\<Longrightarrow> M \\<bind> (\\<lambda>x. f x) \\<le> \\<Down> R (RES X' \\<bind> (\\<lambda>x'. f' x'))\"\n\n  \"\\<lbrakk>RES X \\<le> \\<Down> R' (RES X');\n  \\<And>x x'. \\<lbrakk>(x, x') \\<in> R'; x \\<in> X; x' \\<in> X'\\<rbrakk> \\<Longrightarrow> f x \\<le> \\<Down> R (f' x')\\<rbrakk>\n  \\<Longrightarrow> RES X \\<bind> (\\<lambda>x. f x) \\<le> \\<Down> R (RES X' \\<bind> (\\<lambda>x'. f' x'))\"\n  by (auto intro!: bind_refine')\n\ndeclare bind_refine_RES(1,2)[refine]\ndeclare bind_refine_RES(3)[refine]\n\n\nlemma ASSERT_refine[refine]:\n  \"\\<lbrakk> \\<Phi>'\\<Longrightarrow>\\<Phi> \\<rbrakk> \\<Longrightarrow> ASSERT \\<Phi> \\<le> \\<Down>Id (ASSERT \\<Phi>')\"\n  by (cases \\<Phi>') auto\n\nlemma ASSUME_refine[refine]: \n  \"\\<lbrakk> \\<Phi> \\<Longrightarrow> \\<Phi>' \\<rbrakk> \\<Longrightarrow> ASSUME \\<Phi> \\<le> \\<Down>Id (ASSUME \\<Phi>')\"\n  by (cases \\<Phi>) auto\n\ntext \\<open>\n  Assertions and assumptions are treated specially in bindings\n\\<close>\nlemma ASSERT_refine_right:\n  assumes \"\\<Phi> \\<Longrightarrow> S \\<le>\\<Down>R S'\"\n  shows \"S \\<le>\\<Down>R (do {ASSERT \\<Phi>; S'})\"\n  using assms by (cases \\<Phi>) auto\nlemma ASSERT_refine_right_pres:\n  assumes \"\\<Phi> \\<Longrightarrow> S \\<le>\\<Down>R (do {ASSERT \\<Phi>; S'})\"\n  shows \"S \\<le>\\<Down>R (do {ASSERT \\<Phi>; S'})\"\n  using assms by (cases \\<Phi>) auto\n\nlemma ASSERT_refine_left:\n  assumes \"\\<Phi>\"\n  assumes \"\\<Phi> \\<Longrightarrow> S \\<le> \\<Down>R S'\"\n  shows \"do{ASSERT \\<Phi>; S} \\<le> \\<Down>R S'\"\n  using assms by (cases \\<Phi>) auto\n\nlemma ASSUME_refine_right:\n  assumes \"\\<Phi>\"\n  assumes \"\\<Phi> \\<Longrightarrow> S \\<le>\\<Down>R S'\"\n  shows \"S \\<le>\\<Down>R (do {ASSUME \\<Phi>; S'})\"\n  using assms by (cases \\<Phi>) auto\n\nlemma ASSUME_refine_left:\n  assumes \"\\<Phi> \\<Longrightarrow> S \\<le> \\<Down>R S'\"\n  shows \"do {ASSUME \\<Phi>; S} \\<le> \\<Down>R S'\"\n  using assms by (cases \\<Phi>) auto\n\nlemma ASSUME_refine_left_pres:\n  assumes \"\\<Phi> \\<Longrightarrow> do {ASSUME \\<Phi>; S} \\<le> \\<Down>R S'\"\n  shows \"do {ASSUME \\<Phi>; S} \\<le> \\<Down>R S'\"\n  using assms by (cases \\<Phi>) auto\n\ntext \\<open>Warning: The order of \\<open>[refine]\\<close>-declarations is \n  important here, as preconditions should be generated before \n  additional proof obligations.\\<close>\nlemmas [refine0] = ASSUME_refine_right\nlemmas [refine0] = ASSERT_refine_left\nlemmas [refine0] = ASSUME_refine_left\nlemmas [refine0] = ASSERT_refine_right\n\ntext \\<open>For backward compatibility, as \\<open>intro refine\\<close> still\n  seems to be used instead of \\<open>refine_rcg\\<close>.\\<close>\nlemmas [refine] = ASSUME_refine_right\nlemmas [refine] = ASSERT_refine_left\nlemmas [refine] = ASSUME_refine_left\nlemmas [refine] = ASSERT_refine_right\n\n\ndefinition lift_assn :: \"('a \\<times> 'b) set \\<Rightarrow> ('b \\<Rightarrow> bool) \\<Rightarrow> ('a \\<Rightarrow> bool)\"\n  \\<comment> \\<open>Lift assertion over refinement relation\\<close>\n  where \"lift_assn R \\<Phi> s \\<equiv> \\<exists>s'. (s,s')\\<in>R \\<and> \\<Phi> s'\"\nlemma lift_assnI: \"\\<lbrakk>(s,s')\\<in>R; \\<Phi> s'\\<rbrakk> \\<Longrightarrow> lift_assn R \\<Phi> s\"\n  unfolding lift_assn_def by auto\n\n\n\n\nlemma REC_refine[refine]:\n  assumes M: \"trimono body\"\n  assumes R0: \"(x,x')\\<in>R\"\n  assumes RS: \"\\<And>f f' x x'. \\<lbrakk> \\<And>x x'. (x,x')\\<in>R \\<Longrightarrow> f x \\<le>\\<Down>S (f' x'); (x,x')\\<in>R; \n        REC body' = f' \\<rbrakk> \n    \\<Longrightarrow> body f x \\<le>\\<Down>S (body' f' x')\"\n  shows \"REC (\\<lambda>f x. body f x) x \\<le>\\<Down>S (REC (\\<lambda>f' x'. body' f' x') x')\"\n  unfolding REC_def\n  apply (clarsimp simp add: M)\n  apply (rule lfp_induct_pointwise[where pre=\"\\<lambda>x' x. (x,x')\\<in>R\" and B=body])\n\n  apply rule\n  apply clarsimp\n  apply (blast intro: SUP_least)\n\n  apply simp\n\n  apply (simp add: trimonoD[OF M])\n\n  apply (rule R0)\n\n  apply (subst lfp_unfold, simp add: trimonoD)\n  apply (rule RS)\n  apply blast\n  apply blast\n  apply (simp add: REC_def[abs_def])\n  done\n\nlemma RECT_refine[refine]:\n  assumes M: \"trimono body\"\n  assumes R0: \"(x,x')\\<in>R\"\n  assumes RS: \"\\<And>f f' x x'. \\<lbrakk> \\<And>x x'. (x,x')\\<in>R \\<Longrightarrow> f x \\<le>\\<Down>S (f' x'); (x,x')\\<in>R \\<rbrakk> \n    \\<Longrightarrow> body f x \\<le>\\<Down>S (body' f' x')\"\n  shows \"RECT (\\<lambda>f x. body f x) x \\<le>\\<Down>S (RECT (\\<lambda>f' x'. body' f' x') x')\"\n  unfolding RECT_def\n  apply (clarsimp simp add: M)\n\n  apply (rule flatf_fixp_transfer[where \n        fp'=\"flatf_gfp body\" \n    and B'=body \n    and P=\"\\<lambda>x x'. (x',x)\\<in>R\", \n    OF _ _ flatf_ord.fixp_unfold[OF M[THEN trimonoD_flatf_ge]] R0])\n  apply simp\n  apply (simp add: trimonoD)\n  by (rule RS)\n\nlemma if_refine[refine]:\n  assumes \"b \\<longleftrightarrow> b'\"\n  assumes \"\\<lbrakk>b;b'\\<rbrakk> \\<Longrightarrow> S1 \\<le> \\<Down>R S1'\"\n  assumes \"\\<lbrakk>\\<not>b;\\<not>b'\\<rbrakk> \\<Longrightarrow> S2 \\<le> \\<Down>R S2'\"\n  shows \"(if b then S1 else S2) \\<le> \\<Down>R (if b' then S1' else S2')\"\n  using assms by auto\n\nlemma Let_unfold_refine[refine]:\n  assumes \"f x \\<le> \\<Down>R (f' x')\"\n  shows \"Let x f \\<le> \\<Down>R (Let x' f')\"\n  using assms by auto\n\ntext \\<open>The next lemma is sometimes more convenient, as it prevents\n  large let-expressions from exploding by being completely unfolded.\\<close>\nlemma Let_refine:\n  assumes \"(m,m')\\<in>R'\"\n  assumes \"\\<And>x x'. (x,x')\\<in>R' \\<Longrightarrow> f x \\<le> \\<Down>R (f' x')\"\n  shows \"Let m (\\<lambda>x. f x) \\<le>\\<Down>R (Let m' (\\<lambda>x'. f' x'))\"\n  using assms by auto\n\nlemma Let_refine':\n  assumes \"(m,m')\\<in>R\"\n  assumes \"(m,m')\\<in>R \\<Longrightarrow> f m \\<le>\\<Down>S (f' m')\"\n  shows \"Let m f \\<le> \\<Down>S (Let m' f')\"\n  using assms by simp\n\n    \nlemma case_option_refine[refine]:\n  assumes \"(v,v')\\<in>\\<langle>Ra\\<rangle>option_rel\"\n  assumes \"\\<lbrakk>v=None; v'=None\\<rbrakk> \\<Longrightarrow> n \\<le> \\<Down> Rb n'\"\n  assumes \"\\<And>x x'. \\<lbrakk> v=Some x; v'=Some x'; (x, x') \\<in> Ra \\<rbrakk> \n    \\<Longrightarrow> f x \\<le> \\<Down> Rb (f' x')\"\n  shows \"case_option n f v \\<le>\\<Down>Rb (case_option n' f' v')\"\n  using assms\n  by (auto split: option.split simp: option_rel_def)\n\nlemma list_case_refine[refine]: \n  assumes \"(li,l)\\<in>\\<langle>S\\<rangle>list_rel\"\n  assumes \"fni \\<le>\\<Down>R fn\"  \n  assumes \"\\<And>xi x xsi xs. \\<lbrakk> (xi,x)\\<in>S; (xsi,xs)\\<in>\\<langle>S\\<rangle>list_rel; li=xi#xsi; l=x#xs \\<rbrakk> \\<Longrightarrow> fci xi xsi \\<le>\\<Down>R (fc x xs)\"  \n  shows \"(case li of [] \\<Rightarrow> fni | xi#xsi \\<Rightarrow> fci xi xsi) \\<le> \\<Down>R (case l of [] \\<Rightarrow> fn | x#xs \\<Rightarrow> fc x xs)\"  \n  using assms by (auto split: list.split)  \n    \ntext \\<open>It is safe to split conjunctions in refinement goals.\\<close>\ndeclare conjI[refine]\n\ntext \\<open>The following rules try to compensate for some structural changes,\n  like inlining lets or converting binds to lets.\\<close>\nlemma remove_Let_refine[refine2]:\n  assumes \"M \\<le> \\<Down>R (f x)\"\n  shows \"M \\<le> \\<Down>R (Let x f)\" using assms by auto\n\nlemma intro_Let_refine[refine2]:\n  assumes \"f x \\<le> \\<Down>R M'\"\n  shows \"Let x f \\<le> \\<Down>R M'\" using assms by auto\n  \n\n\nlemma bind_Let_refine2[refine2]: \"\\<lbrakk> \n    m' \\<le>\\<Down>R' (RETURN x);\n    \\<And>x'. \\<lbrakk>inres m' x'; (x',x)\\<in>R'\\<rbrakk> \\<Longrightarrow> f' x' \\<le> \\<Down>R (f x) \n  \\<rbrakk> \\<Longrightarrow> m'\\<bind>(\\<lambda>x'. f' x') \\<le> \\<Down>R (Let x (\\<lambda>x. f x))\"\n  apply (simp add: pw_le_iff refine_pw_simps)\n  apply blast\n  done\n\nlemma bind2letRETURN_refine[refine2]:\n  assumes \"RETURN x \\<le> \\<Down>R' M'\"\n  assumes \"\\<And>x'. (x,x')\\<in>R' \\<Longrightarrow> RETURN (f x) \\<le> \\<Down>R (f' x')\"\n  shows \"RETURN (Let x f) \\<le> \\<Down>R (bind M' (\\<lambda>x'. f' x'))\"\n  using assms\n  apply (simp add: pw_le_iff refine_pw_simps)\n  apply fast\n  done\n\nlemma RETURN_as_SPEC_refine[refine2]:\n  assumes \"M \\<le> SPEC (\\<lambda>c. (c,a)\\<in>R)\"\n  shows \"M \\<le> \\<Down>R (RETURN a)\"\n  using assms\n  by (simp add: pw_le_iff refine_pw_simps)\n\nlemma RETURN_as_SPEC_refine_old:\n  \"\\<And>M R. M \\<le> \\<Down>R (SPEC (\\<lambda>x. x=v)) \\<Longrightarrow> M \\<le>\\<Down>R (RETURN v)\"\n  by (simp add: RETURN_def)\n\nlemma if_RETURN_refine [refine2]:\n  assumes \"b \\<longleftrightarrow> b'\"\n  assumes \"\\<lbrakk>b;b'\\<rbrakk> \\<Longrightarrow> RETURN S1 \\<le> \\<Down>R S1'\"\n  assumes \"\\<lbrakk>\\<not>b;\\<not>b'\\<rbrakk> \\<Longrightarrow> RETURN S2 \\<le> \\<Down>R S2'\"\n  shows \"RETURN (if b then S1 else S2) \\<le> \\<Down>R (if b' then S1' else S2')\"\n  (* this is nice to have for small functions, hence keep it in refine2 *)\n  using assms\n  by (simp add: pw_le_iff refine_pw_simps)\n\nlemma RES_sng_as_SPEC_refine[refine2]:\n  assumes \"M \\<le> SPEC (\\<lambda>c. (c,a)\\<in>R)\"\n  shows \"M \\<le> \\<Down>R (RES {a})\"\n  using assms\n  by (simp add: pw_le_iff refine_pw_simps)\n\n\nlemma intro_spec_refine_iff:\n  \"(bind (RES X) f \\<le> \\<Down>R M) \\<longleftrightarrow> (\\<forall>x\\<in>X. f x \\<le> \\<Down>R M)\"\n  apply (simp add: pw_le_iff refine_pw_simps)\n  apply blast\n  done\n\nlemma intro_spec_refine[refine2]:\n  assumes \"\\<And>x. x\\<in>X \\<Longrightarrow> f x \\<le> \\<Down>R M\"\n  shows \"bind (RES X) (\\<lambda>x. f x) \\<le> \\<Down>R M\"\n  using assms\n  by (simp add: intro_spec_refine_iff)\n\n\ntext \\<open>The following rules are intended for manual application, to reflect \n  some common structural changes, that, however, are not suited to be applied\n  automatically.\\<close>\n\ntext \\<open>Replacing a let by a deterministic computation\\<close>\nlemma let2bind_refine:\n  assumes \"m \\<le> \\<Down>R' (RETURN m')\"\n  assumes \"\\<And>x x'. (x,x')\\<in>R' \\<Longrightarrow> f x \\<le> \\<Down>R (f' x')\"\n  shows \"bind m (\\<lambda>x. f x) \\<le> \\<Down>R (Let m' (\\<lambda>x'. f' x'))\"\n  using assms\n  apply (simp add: pw_le_iff refine_pw_simps)\n  apply blast\n  done\n\n\n\ntext \\<open>Introduce a new binding, without a structural match in the abstract \n  program\\<close>\nlemma intro_bind_refine:\n  assumes \"m \\<le> \\<Down>R' (RETURN m')\"\n  assumes \"\\<And>x. (x,m')\\<in>R' \\<Longrightarrow> f x \\<le> \\<Down>R m''\"\n  shows \"bind m (\\<lambda>x. f x) \\<le> \\<Down>R m''\"\n  using assms\n  apply (simp add: pw_le_iff refine_pw_simps)\n  apply blast\n  done\n\nlemma intro_bind_refine_id:\n  assumes \"m \\<le> (SPEC ((=) m'))\"\n  assumes \"f m' \\<le> \\<Down>R m''\"\n  shows \"bind m f \\<le> \\<Down>R m''\"\n  using assms\n  apply (simp add: pw_le_iff refine_pw_simps)\n  apply blast\n  done\n\ntext \\<open>The following set of rules executes a step on the LHS or RHS of \n  a refinement proof obligation, without changing the other side.\n  These kind of rules is useful for performing refinements with \n  invisible steps.\\<close>  \nlemma lhs_step_If:\n  \"\\<lbrakk> b \\<Longrightarrow> t \\<le> m; \\<not>b \\<Longrightarrow> e \\<le> m \\<rbrakk> \\<Longrightarrow> If b t e \\<le> m\" by simp\n\n\n\nlemma lhs_step_SPEC:\n  \"\\<lbrakk> \\<And>x. \\<Phi> x \\<Longrightarrow> RETURN x \\<le> m \\<rbrakk> \\<Longrightarrow> SPEC (\\<lambda>x. \\<Phi> x) \\<le> m\" \n  by (simp add: pw_le_iff)\n\nlemma lhs_step_bind:\n  fixes m :: \"'a nres\" and f :: \"'a \\<Rightarrow> 'b nres\"\n  assumes \"nofail m' \\<Longrightarrow> nofail m\"\n  assumes \"\\<And>x. nf_inres m x \\<Longrightarrow> f x \\<le> m'\"\n  shows \"do {x\\<leftarrow>m; f x} \\<le> m'\"\n  using assms\n  by (simp add: pw_le_iff refine_pw_simps) blast\n\nlemma rhs_step_bind:\n  assumes \"m \\<le> \\<Down>R m'\" \"inres m x\" \"\\<And>x'. (x,x')\\<in>R \\<Longrightarrow> lhs \\<le>\\<Down>S (f' x')\"\n  shows \"lhs \\<le> \\<Down>S (m' \\<bind> f')\"\n  using assms\n  by (simp add: pw_le_iff refine_pw_simps) blast\n\n\n\nlemma rhs_step_bind_SPEC:\n  assumes \"\\<Phi> x'\"\n  assumes \"m \\<le> \\<Down>R (f' x')\"\n  shows \"m \\<le> \\<Down>R (SPEC \\<Phi> \\<bind> f')\"\n  using assms by (simp add: pw_le_iff refine_pw_simps) blast\n\nlemma RES_bind_choose:\n  assumes \"x\\<in>X\"\n  assumes \"m \\<le> f x\"\n  shows \"m \\<le> RES X \\<bind> f\"\n  using assms by (auto simp: pw_le_iff refine_pw_simps)\n\nlemma pw_RES_bind_choose: \n  \"nofail (RES X \\<bind> f) \\<longleftrightarrow> (\\<forall>x\\<in>X. nofail (f x))\"\n  \"inres (RES X \\<bind> f) y \\<longleftrightarrow> (\\<exists>x\\<in>X. inres (f x) y)\"\n  by (auto simp: refine_pw_simps)\n\nlemma prod_case_refine:  \n  assumes \"(p',p)\\<in>R1\\<times>\\<^sub>rR2\"\n  assumes \"\\<And>x1' x2' x1 x2. \\<lbrakk> p'=(x1',x2'); p=(x1,x2); (x1',x1)\\<in>R1; (x2',x2)\\<in>R2\\<rbrakk> \\<Longrightarrow> f' x1' x2' \\<le> \\<Down>R (f x1 x2)\"\n  shows \"(case p' of (x1',x2') \\<Rightarrow> f' x1' x2') \\<le>\\<Down>R (case p of (x1,x2) \\<Rightarrow> f x1 x2)\"\n  using assms by (auto split: prod.split)\n\n\n\nsubsection \\<open>Relators\\<close>\ndeclare fun_relI[refine]\n  \ndefinition nres_rel where \n  nres_rel_def_internal: \"nres_rel R \\<equiv> {(c,a). c \\<le> \\<Down>R a}\"\n\nlemma nres_rel_def: \"\\<langle>R\\<rangle>nres_rel \\<equiv> {(c,a). c \\<le> \\<Down>R a}\"\n  by (simp add: nres_rel_def_internal relAPP_def)\n\nlemma nres_relD: \"(c,a)\\<in>\\<langle>R\\<rangle>nres_rel \\<Longrightarrow> c \\<le>\\<Down>R a\" by (simp add: nres_rel_def)\nlemma nres_relI[refine]: \"c \\<le>\\<Down>R a \\<Longrightarrow> (c,a)\\<in>\\<langle>R\\<rangle>nres_rel\" by (simp add: nres_rel_def)\n\nlemma nres_rel_comp: \"\\<langle>A\\<rangle>nres_rel O \\<langle>B\\<rangle>nres_rel = \\<langle>A O B\\<rangle>nres_rel\"\n  by (auto simp: nres_rel_def conc_fun_chain[symmetric] conc_trans)\n\nlemma pw_nres_rel_iff: \"(a,b)\\<in>\\<langle>A\\<rangle>nres_rel \\<longleftrightarrow> nofail (\\<Down> A b) \\<longrightarrow> nofail a \\<and> (\\<forall>x. inres a x \\<longrightarrow> inres (\\<Down> A b) x)\"\n  by (simp add: pw_le_iff nres_rel_def)\n    \n    \nlemma param_SUCCEED[param]: \"(SUCCEED,SUCCEED) \\<in> \\<langle>R\\<rangle>nres_rel\"\n  by (auto simp: nres_rel_def)\n\nlemma param_FAIL[param]: \"(FAIL,FAIL) \\<in> \\<langle>R\\<rangle>nres_rel\"\n  by (auto simp: nres_rel_def)\n\nlemma param_RES[param]:\n  \"(RES,RES) \\<in> \\<langle>R\\<rangle>set_rel \\<rightarrow> \\<langle>R\\<rangle>nres_rel\"\n  unfolding set_rel_def nres_rel_def\n  by (fastforce intro: RES_refine)\n\nlemma param_RETURN[param]: \n  \"(RETURN,RETURN) \\<in> R \\<rightarrow> \\<langle>R\\<rangle>nres_rel\"\n  by (auto simp: nres_rel_def RETURN_refine)\n\nlemma param_bind[param]:\n  \"(bind,bind) \\<in> \\<langle>Ra\\<rangle>nres_rel \\<rightarrow> (Ra\\<rightarrow>\\<langle>Rb\\<rangle>nres_rel) \\<rightarrow> \\<langle>Rb\\<rangle>nres_rel\"\n  by (auto simp: nres_rel_def intro: bind_refine dest: fun_relD)\n\nlemma param_ASSERT_bind[param]: \"\\<lbrakk> \n    (\\<Phi>,\\<Psi>) \\<in> bool_rel; \n    \\<lbrakk> \\<Phi>; \\<Psi> \\<rbrakk> \\<Longrightarrow> (f,g)\\<in>\\<langle>R\\<rangle>nres_rel\n  \\<rbrakk> \\<Longrightarrow> (ASSERT \\<Phi> \\<then> f, ASSERT \\<Psi> \\<then> g) \\<in> \\<langle>R\\<rangle>nres_rel\"\n  by (auto intro: nres_relI)\n\nsubsection \\<open>Autoref Setup\\<close>\n\nconsts i_nres :: \"interface \\<Rightarrow> interface\"\nlemmas [autoref_rel_intf] = REL_INTFI[of nres_rel i_nres]\n\n(*lemma id_nres[autoref_id_self]: \"ID_LIST \n  (l SUCCEED FAIL bind (REC::_ \\<Rightarrow> _ \\<Rightarrow> _ nres,1) (RECT::_ \\<Rightarrow> _ \\<Rightarrow> _ nres,1))\"\n  by simp_all\n*)\n(*definition [simp]: \"op_RETURN x \\<equiv> RETURN x\"\nlemma [autoref_op_pat_def]: \"RETURN x \\<equiv> op_RETURN x\" by simp\n*)\n\ndefinition [simp]: \"op_nres_ASSERT_bnd \\<Phi> m \\<equiv> do {ASSERT \\<Phi>; m}\"\n\n\nlemma param_op_nres_ASSERT_bnd[param]:\n  assumes \"\\<Phi>' \\<Longrightarrow> \\<Phi>\"\n  assumes \"\\<lbrakk>\\<Phi>'; \\<Phi>\\<rbrakk> \\<Longrightarrow> (m,m')\\<in>\\<langle>R\\<rangle>nres_rel\"\n  shows \"(op_nres_ASSERT_bnd \\<Phi> m, op_nres_ASSERT_bnd \\<Phi>' m') \\<in> \\<langle>R\\<rangle>nres_rel\"\n  using assms\n  by (auto simp: pw_le_iff refine_pw_simps nres_rel_def)\n\n\n\ncontext begin interpretation autoref_syn .\nlemma id_ASSERT[autoref_op_pat_def]:\n  \"do {ASSERT \\<Phi>; m} \\<equiv> OP (op_nres_ASSERT_bnd \\<Phi>)$m\"\n  by simp\n\ndefinition [simp]: \"op_nres_ASSUME_bnd \\<Phi> m \\<equiv> do {ASSUME \\<Phi>; m}\"\nlemma id_ASSUME[autoref_op_pat_def]:\n  \"do {ASSUME \\<Phi>; m} \\<equiv> OP (op_nres_ASSUME_bnd \\<Phi>)$m\"\n  by simp\n\nend\n\nlemma autoref_SUCCEED[autoref_rules]: \"(SUCCEED,SUCCEED) \\<in> \\<langle>R\\<rangle>nres_rel\"\n  by (auto simp: nres_rel_def)\n\nlemma autoref_FAIL[autoref_rules]: \"(FAIL,FAIL) \\<in> \\<langle>R\\<rangle>nres_rel\"\n  by (auto simp: nres_rel_def)\n\nlemma autoref_RETURN[autoref_rules]: \n  \"(RETURN,RETURN) \\<in> R \\<rightarrow> \\<langle>R\\<rangle>nres_rel\"\n  by (auto simp: nres_rel_def RETURN_refine)\n\nlemma autoref_bind[autoref_rules]: \n  \"(bind,bind) \\<in> \\<langle>R1\\<rangle>nres_rel \\<rightarrow> (R1\\<rightarrow>\\<langle>R2\\<rangle>nres_rel) \\<rightarrow> \\<langle>R2\\<rangle>nres_rel\"\n  apply (intro fun_relI)\n  apply (rule nres_relI)\n  apply (rule bind_refine)\n  apply (erule nres_relD)\n  apply (erule (1) fun_relD[THEN nres_relD])\n  done\n\n\ncontext begin interpretation autoref_syn .\nlemma autoref_ASSERT[autoref_rules]:\n  assumes \"\\<Phi> \\<Longrightarrow> (m',m)\\<in>\\<langle>R\\<rangle>nres_rel\"\n  shows \"(\n    m',\n    (OP (op_nres_ASSERT_bnd \\<Phi>) ::: \\<langle>R\\<rangle>nres_rel \\<rightarrow> \\<langle>R\\<rangle>nres_rel) $ m)\\<in>\\<langle>R\\<rangle>nres_rel\"\n  using assms unfolding nres_rel_def\n  by (simp add: ASSERT_refine_right)\n\nlemma autoref_ASSUME[autoref_rules]:\n  assumes \"SIDE_PRECOND \\<Phi>\"\n  assumes \"\\<Phi> \\<Longrightarrow> (m',m)\\<in>\\<langle>R\\<rangle>nres_rel\"\n  shows \"(\n    m',\n    (OP (op_nres_ASSUME_bnd \\<Phi>) ::: \\<langle>R\\<rangle>nres_rel \\<rightarrow> \\<langle>R\\<rangle>nres_rel) $ m)\\<in>\\<langle>R\\<rangle>nres_rel\"\n  using assms unfolding nres_rel_def\n  by (simp add: ASSUME_refine_right)\n\nlemma autoref_REC[autoref_rules]:\n  assumes \"(B,B')\\<in>(Ra\\<rightarrow>\\<langle>Rr\\<rangle>nres_rel) \\<rightarrow> Ra \\<rightarrow> \\<langle>Rr\\<rangle>nres_rel\"\n  assumes \"DEFER trimono B\"\n  shows \"(REC B,\n    (OP REC \n      ::: ((Ra\\<rightarrow>\\<langle>Rr\\<rangle>nres_rel) \\<rightarrow> Ra \\<rightarrow> \\<langle>Rr\\<rangle>nres_rel) \\<rightarrow> Ra \\<rightarrow> \\<langle>Rr\\<rangle>nres_rel)$B'\n    ) \\<in> Ra \\<rightarrow> \\<langle>Rr\\<rangle>nres_rel\"\n  apply (intro fun_relI)\n  using assms\n  apply (auto simp: nres_rel_def intro!: REC_refine)\n  apply (simp add: fun_rel_def)\n  apply blast\n  done\n\ntheorem param_RECT[param]:\n  assumes \"(B, B') \\<in> (Ra \\<rightarrow> \\<langle>Rr\\<rangle>nres_rel) \\<rightarrow> Ra \\<rightarrow> \\<langle>Rr\\<rangle>nres_rel\"\n    and \"trimono B\"\n  shows \"(REC\\<^sub>T B, REC\\<^sub>T B')\\<in> Ra \\<rightarrow> \\<langle>Rr\\<rangle>nres_rel\"\n  apply (intro fun_relI)\n  using assms\n  apply (auto simp: nres_rel_def intro!: RECT_refine)\n  apply (simp add: fun_rel_def)\n  apply blast\n  done\n\nlemma autoref_RECT[autoref_rules]:\n  assumes \"(B,B') \\<in> (Ra\\<rightarrow>\\<langle>Rr\\<rangle>nres_rel) \\<rightarrow> Ra\\<rightarrow>\\<langle>Rr\\<rangle>nres_rel\"\n  assumes \"DEFER trimono B\"\n  shows \"(RECT B,\n    (OP RECT \n      ::: ((Ra\\<rightarrow>\\<langle>Rr\\<rangle>nres_rel) \\<rightarrow> Ra \\<rightarrow> \\<langle>Rr\\<rangle>nres_rel) \\<rightarrow> Ra \\<rightarrow> \\<langle>Rr\\<rangle>nres_rel)$B'\n    ) \\<in> Ra \\<rightarrow> \\<langle>Rr\\<rangle>nres_rel\"\n  using assms\n  unfolding autoref_tag_defs \n  by (rule param_RECT)\n\nend\n\nsubsection \\<open>Convenience Rules\\<close>\ntext \\<open>\n  In this section, we define some lemmas that simplify common prover tasks.\n\\<close>\n\nlemma ref_two_step: \"A\\<le>\\<Down>R  B \\<Longrightarrow> B\\<le>C \\<Longrightarrow> A\\<le>\\<Down>R  C\" \n  by (rule conc_trans_additional)\n\n   \nlemma pw_ref_iff:\n  shows \"S \\<le> \\<Down>R S' \n  \\<longleftrightarrow> (nofail S' \n    \\<longrightarrow> nofail S \\<and> (\\<forall>x. inres S x \\<longrightarrow> (\\<exists>s'. (x, s') \\<in> R \\<and> inres S' s')))\"\n  by (simp add: pw_le_iff refine_pw_simps)\n\nlemma pw_ref_I:\n  assumes \"nofail S' \n    \\<longrightarrow> nofail S \\<and> (\\<forall>x. inres S x \\<longrightarrow> (\\<exists>s'. (x, s') \\<in> R \\<and> inres S' s'))\"\n  shows \"S \\<le> \\<Down>R S'\"\n  using assms\n  by (simp add: pw_ref_iff)\n\ntext \\<open>Introduce an abstraction relation. Usage: \n  \\<open>rule introR[where R=absRel]\\<close>\n\\<close>\nlemma introR: \"(a,a')\\<in>R \\<Longrightarrow> (a,a')\\<in>R\" .\n\nlemma intro_prgR: \"c \\<le> \\<Down>R a \\<Longrightarrow> c \\<le> \\<Down>R a\" by auto\n\nlemma refine_IdI: \"m \\<le> m' \\<Longrightarrow> m \\<le> \\<Down>Id m'\" by simp\n    \n\nlemma le_ASSERTI_pres:\n  assumes \"\\<Phi> \\<Longrightarrow> S \\<le> do {ASSERT \\<Phi>; S'}\"\n  shows \"S \\<le> do {ASSERT \\<Phi>; S'}\"\n  using assms by (auto intro: le_ASSERTI)\n\nlemma RETURN_ref_SPECD:\n  assumes \"RETURN c \\<le> \\<Down>R (SPEC \\<Phi>)\"\n  obtains a where \"(c,a)\\<in>R\" \"\\<Phi> a\"\n  using assms\n  by (auto simp: pw_le_iff refine_pw_simps)\n\nlemma RETURN_ref_RETURND:\n  assumes \"RETURN c \\<le> \\<Down>R (RETURN a)\"\n  shows \"(c,a)\\<in>R\"\n  using assms\n  apply (auto simp: pw_le_iff refine_pw_simps)\n  done\n\nlemma return_refine_prop_return:\n  assumes \"nofail m\"\n  assumes \"RETURN x \\<le> \\<Down>R m\"\n  obtains x' where \"(x,x')\\<in>R\" \"RETURN x' \\<le> m\"\n  using assms\n  by (auto simp: refine_pw_simps pw_le_iff)\n    \nlemma ignore_snd_refine_conv: \n  \"(m \\<le> \\<Down>(R\\<times>\\<^sub>rUNIV) m') \\<longleftrightarrow> m\\<bind>(RETURN o fst) \\<le>\\<Down>R (m'\\<bind>(RETURN o fst))\"\n  by (auto simp: pw_le_iff refine_pw_simps)\n    \n    \nlemma ret_le_down_conv: \n  \"nofail m \\<Longrightarrow> RETURN c \\<le> \\<Down>R m \\<longleftrightarrow> (\\<exists>a. (c,a)\\<in>R \\<and> RETURN a \\<le> m)\"\n  by (auto simp: pw_le_iff refine_pw_simps)\n    \nlemma SPEC_eq_is_RETURN:\n  \"SPEC ((=) x) = RETURN x\"\n  \"SPEC (\\<lambda>x. x=y) = RETURN y\"\n  by (auto simp: RETURN_def)\n\nlemma RETURN_SPEC_conv: \"RETURN r = SPEC (\\<lambda>x. x=r)\"\n  by (simp add: RETURN_def)\n\nlemma refine2spec_aux:\n  \"a \\<le> \\<Down>R b \\<longleftrightarrow> ( (nofail b \\<longrightarrow> a \\<le> SPEC ( \\<lambda>r. (\\<exists>x. inres b x \\<and> (r,x)\\<in>R) )) )\"\n  by (auto simp: pw_le_iff refine_pw_simps)\n  \n\n\nlemma build_rel_SPEC_conv: \"\\<Down>(br \\<alpha> I) (SPEC \\<Phi>) = SPEC (\\<lambda>x. I x \\<and> \\<Phi> (\\<alpha> x))\"  \n  by (auto simp: br_def pw_eq_iff refine_pw_simps)\n    \nlemma refine_IdD: \"c \\<le> \\<Down>Id a \\<Longrightarrow> c \\<le> a\" by simp\n\nlemma bind_sim_select_rule:\n  assumes \"m\\<bind>f' \\<le> SPEC \\<Psi>\"\n  assumes \"\\<And>x. \\<lbrakk>nofail m; inres m x; f' x\\<le>SPEC \\<Psi>\\<rbrakk> \\<Longrightarrow> f x\\<le>SPEC \\<Phi>\"\n  shows \"m\\<bind>f \\<le> SPEC \\<Phi>\"\n  \\<comment> \\<open>Simultaneously select a result from assumption and verification goal.\n    Useful to work with assumptions that restrict the current program to \n    be verified.\\<close>\n  using assms \n  by (auto simp: pw_le_iff refine_pw_simps)\n\nlemma assert_bind_spec_conv: \"ASSERT \\<Phi> \\<then> m \\<le> SPEC \\<Psi> \\<longleftrightarrow> (\\<Phi> \\<and> m \\<le> SPEC \\<Psi>)\"  \n  \\<comment> \\<open>Simplify a bind-assert verification condition. \n    Useful if this occurs in the assumptions, and considerably faster than \n    using pointwise reasoning, which may causes a blowup for many chained \n    assertions.\\<close>\n  by (auto simp: pw_le_iff refine_pw_simps)\n\nlemma summarize_ASSERT_conv: \"do {ASSERT \\<Phi>; ASSERT \\<Psi>; m} = do {ASSERT (\\<Phi> \\<and> \\<Psi>); m}\"\n  by (auto simp: pw_eq_iff refine_pw_simps)\n\nlemma bind_ASSERT_eq_if: \"do { ASSERT \\<Phi>; m } = (if \\<Phi> then m else FAIL)\"\n  by auto\n    \n    \nlemma le_RES_nofailI:\n  assumes \"a\\<le>RES x\"\n  shows \"nofail a\"\n  using assms\n  by (metis nofail_simps(2) pwD1)\n\nlemma add_invar_refineI:\n  assumes \"f x \\<le>\\<Down>R (f' x')\"\n    and \"nofail (f x) \\<Longrightarrow> f x \\<le> SPEC I\"\n  shows \"f x \\<le> \\<Down> {(c, a). (c, a) \\<in> R \\<and> I c} (f' x')\"\n  using assms\n  by (simp add: pw_le_iff refine_pw_simps sv_add_invar)\n\n\nlemma bind_RES_RETURN_eq: \"bind (RES X) (\\<lambda>x. RETURN (f x)) = \n  RES { f x | x. x\\<in>X }\"\n  by (simp add: pw_eq_iff refine_pw_simps)\n    blast\n\nlemma bind_RES_RETURN2_eq: \"bind (RES X) (\\<lambda>(x,y). RETURN (f x y)) = \n  RES { f x y | x y. (x,y)\\<in>X }\"\n  apply (simp add: pw_eq_iff refine_pw_simps)\n  apply blast\n  done\n\nlemma le_SPEC_bindI: \n  assumes \"\\<Phi> x\"\n  assumes \"m \\<le> f x\"\n  shows \"m \\<le> SPEC \\<Phi> \\<bind> f\"\n  using assms by (auto simp add: pw_le_iff refine_pw_simps)\n\nlemma bind_assert_refine: \n  assumes \"m1 \\<le> SPEC \\<Phi>\"\n  assumes \"\\<And>x. \\<Phi> x \\<Longrightarrow> m2 x \\<le> m'\"\n  shows \"do {x\\<leftarrow>m1; ASSERT (\\<Phi> x); m2 x} \\<le> m'\"\n  using assms\n  by (simp add: pw_le_iff refine_pw_simps) blast\n\n\nlemma RETURN_refine_iff[simp]: \"RETURN x \\<le>\\<Down>R (RETURN y) \\<longleftrightarrow> (x,y)\\<in>R\"\n  by (auto simp: pw_le_iff refine_pw_simps)\n\nlemma RETURN_RES_refine_iff: \n  \"RETURN x \\<le>\\<Down>R (RES Y) \\<longleftrightarrow> (\\<exists>y\\<in>Y. (x,y)\\<in>R)\"\n  by (auto simp: pw_le_iff refine_pw_simps)\n\nlemma RETURN_RES_refine:\n  assumes \"\\<exists>x'. (x,x')\\<in>R \\<and> x'\\<in>X\"\n  shows \"RETURN x \\<le> \\<Down>R (RES X)\"\n  using assms \n  by (auto simp: pw_le_iff refine_pw_simps)\n\nlemma in_nres_rel_iff: \"(a,b)\\<in>\\<langle>R\\<rangle>nres_rel \\<longleftrightarrow> a \\<le>\\<Down>R b\"\n  by (auto simp: nres_rel_def)\n\nlemma inf_RETURN_RES: \n  \"inf (RETURN x) (RES X) = (if x\\<in>X then RETURN x else SUCCEED)\"\n  \"inf (RES X) (RETURN x) = (if x\\<in>X then RETURN x else SUCCEED)\"\n  by (auto simp: pw_eq_iff refine_pw_simps)\n\n\nlemma inf_RETURN_SPEC[simp]:\n  \"inf (RETURN x) (SPEC (\\<lambda>y. \\<Phi> y)) = SPEC (\\<lambda>y. y=x \\<and> \\<Phi> x)\"\n  \"inf (SPEC (\\<lambda>y. \\<Phi> y)) (RETURN x) = SPEC (\\<lambda>y. y=x \\<and> \\<Phi> x)\"\n  by (auto simp: pw_eq_iff refine_pw_simps)\n\nlemma RES_sng_eq_RETURN: \"RES {x} = RETURN x\"\n  by simp\n\nlemma nofail_inf_serialize:\n  \"\\<lbrakk>nofail a; nofail b\\<rbrakk> \\<Longrightarrow> inf a b = do {x\\<leftarrow>a; ASSUME (inres b x); RETURN x}\"\n  by (auto simp: pw_eq_iff refine_pw_simps)\n\n\nlemma conc_fun_SPEC: \n  \"\\<Down>R (SPEC (\\<lambda>x. \\<Phi> x)) = SPEC (\\<lambda>y. \\<exists>x. (y,x)\\<in>R \\<and> \\<Phi> x)\"  \n  by (auto simp: pw_eq_iff refine_pw_simps)\n\nlemma conc_fun_RETURN: \n  \"\\<Down>R (RETURN x) = SPEC (\\<lambda>y. (y,x)\\<in>R)\"  \n  by (auto simp: pw_eq_iff refine_pw_simps)\n\n\nlemma use_spec_rule:\n  assumes \"m \\<le> SPEC \\<Psi>\"\n  assumes \"m \\<le> SPEC (\\<lambda>s. \\<Psi> s \\<longrightarrow> \\<Phi> s)\"\n  shows \"m \\<le> SPEC \\<Phi>\"\n  using assms\n  by (auto simp: pw_le_iff refine_pw_simps)\n\nlemma strengthen_SPEC: \"m \\<le> SPEC \\<Phi> \\<Longrightarrow> m \\<le> SPEC(\\<lambda>s. inres m s \\<and> nofail m \\<and> \\<Phi> s)\"\n  \\<comment> \\<open>Strengthen SPEC by adding trivial upper bound for result\\<close>\n  by (auto simp: pw_le_iff refine_pw_simps)\n\nlemma weaken_SPEC:\n  \"m \\<le> SPEC \\<Phi> \\<Longrightarrow> (\\<And>x. \\<Phi> x \\<Longrightarrow> \\<Psi> x) \\<Longrightarrow> m \\<le> SPEC \\<Psi>\"\n  by (force elim!: order_trans)\n\nlemma bind_le_nofailI:\n  assumes \"nofail m\"\n  assumes \"\\<And>x. RETURN x \\<le> m \\<Longrightarrow> f x \\<le> m'\"\n  shows \"m\\<bind>f \\<le> m'\"\n  using assms \n  by (simp add: refine_pw_simps pw_le_iff) blast\n\nlemma bind_le_shift:\n  \"bind m f \\<le> m' \n  \\<longleftrightarrow> m \\<le> (if nofail m' then SPEC (\\<lambda>x. f x \\<le> m') else FAIL)\"\n  by (auto simp: pw_le_iff refine_pw_simps)\n\nlemma If_bind_distrib[simp]:\n  fixes t e :: \"'a nres\"\n  shows \"(If b t e \\<bind> (\\<lambda>x. f x)) = (If b (t\\<bind>(\\<lambda>x. f x)) (e\\<bind>(\\<lambda>x. f x)))\"  \n  by simp\n    \n(* TODO: Can we make this a simproc, using NO_MATCH? *)  \nlemma unused_bind_conv: \n  assumes \"NO_MATCH (ASSERT \\<Phi>) m\"\n  assumes \"NO_MATCH (ASSUME \\<Phi>) m\"\n  shows \"(m\\<bind>(\\<lambda>x. c))  = (ASSERT (nofail m) \\<bind> (\\<lambda>_. ASSUME (\\<exists>x. inres m x) \\<bind> (\\<lambda>x. c)))\" \n  by (auto simp: pw_eq_iff refine_pw_simps)\n\ntext \\<open>The following rules are useful for massaging programs before the \n  refinement takes place\\<close>\nlemma let_to_bind_conv: \n  \"Let x f = RETURN x\\<bind>f\"\n  by simp\n\nlemmas bind_to_let_conv = let_to_bind_conv[symmetric]\n\nlemma pull_out_let_conv: \"RETURN (Let x f) = Let x (\\<lambda>x. RETURN (f x))\"\n  by simp\n\nlemma push_in_let_conv: \n  \"Let x (\\<lambda>x. RETURN (f x)) = RETURN (Let x f)\"\n  \"Let x (RETURN o f) = RETURN (Let x f)\"\n  by simp_all\n\nlemma pull_out_RETURN_case_option: \n  \"case_option (RETURN a) (\\<lambda>v. RETURN (f v)) x = RETURN (case_option a f x)\"\n  by (auto split: option.splits)\n\nlemma if_bind_cond_refine: \n  assumes \"ci \\<le> RETURN b\"\n  assumes \"b \\<Longrightarrow> ti\\<le>\\<Down>R t\"\n  assumes \"\\<not>b \\<Longrightarrow> ei\\<le>\\<Down>R e\"\n  shows \"do {b\\<leftarrow>ci; if b then ti else ei} \\<le> \\<Down>R (if b then t else e)\"\n  using assms\n  by (auto simp add: refine_pw_simps pw_le_iff)\n\nlemma intro_RETURN_Let_refine:\n  assumes \"RETURN (f x) \\<le> \\<Down>R M'\"\n  shows \"RETURN (Let x f) \\<le> \\<Down>R M'\" \n  (* this should be needed very rarely - so don't add it *)\n  using assms by auto\n\nlemma ife_FAIL_to_ASSERT_cnv: \n  \"(if \\<Phi> then m else FAIL) = op_nres_ASSERT_bnd \\<Phi> m\"\n  by (cases \\<Phi>, auto)\n\nlemma nres_bind_let_law: \"(do { x \\<leftarrow> do { let y=v; f y }; g x } :: _ nres)\n  = do { let y=v; x\\<leftarrow> f y; g x }\" by auto\n\nlemma unused_bind_RES_ne[simp]: \"X\\<noteq>{} \\<Longrightarrow> do { _ \\<leftarrow> RES X; m} = m\"\n  by (auto simp: pw_eq_iff refine_pw_simps)\n\n\nlemma le_ASSERT_defI1:\n  assumes \"c \\<equiv> do {ASSERT \\<Phi>; m}\"\n  assumes \"\\<Phi> \\<Longrightarrow> m' \\<le> c\"\n  shows \"m' \\<le> c\"\n  using assms\n  by (simp add: le_ASSERTI)\n\nlemma refine_ASSERT_defI1:\n  assumes \"c \\<equiv> do {ASSERT \\<Phi>; m}\"\n  assumes \"\\<Phi> \\<Longrightarrow> m' \\<le> \\<Down>R c\"\n  shows \"m' \\<le> \\<Down>R c\"\n  using assms\n  by (simp, refine_vcg)\n\nlemma le_ASSERT_defI2:\n  assumes \"c \\<equiv> do {ASSERT \\<Phi>; ASSERT \\<Psi>; m}\"\n  assumes \"\\<lbrakk>\\<Phi>; \\<Psi>\\<rbrakk> \\<Longrightarrow> m' \\<le> c\"\n  shows \"m' \\<le> c\"\n  using assms\n  by (simp add: le_ASSERTI)\n\nlemma refine_ASSERT_defI2:\n  assumes \"c \\<equiv> do {ASSERT \\<Phi>; ASSERT \\<Psi>; m}\"\n  assumes \"\\<lbrakk>\\<Phi>; \\<Psi>\\<rbrakk> \\<Longrightarrow> m' \\<le> \\<Down>R c\"\n  shows \"m' \\<le> \\<Down>R c\"\n  using assms\n  by (simp, refine_vcg)\n\nlemma ASSERT_le_defI:\n  assumes \"c \\<equiv> do { ASSERT \\<Phi>; m'}\"\n  assumes \"\\<Phi>\"\n  assumes \"\\<Phi> \\<Longrightarrow> m' \\<le> m\"\n  shows \"c \\<le> m\"\n  using assms by (auto)\n\nlemma ASSERT_same_eq_conv: \"(ASSERT \\<Phi> \\<then> m) = (ASSERT \\<Phi> \\<then> n) \\<longleftrightarrow> (\\<Phi> \\<longrightarrow> m=n)\"  \n  by auto\n\nlemma case_prod_bind_simp[simp]: \"\n  (\\<lambda>x. (case x of (a, b) \\<Rightarrow> f a b) \\<le> SPEC \\<Phi>) = (\\<lambda>(a,b). f a b \\<le> SPEC \\<Phi>)\"\n  by auto\n    \nlemma RECT_eq_REC': \"nofail (RECT B x) \\<Longrightarrow> RECT B x = REC B x\"\n  by (subst RECT_eq_REC; simp_all add: nofail_def)\n    \n    \nlemma rel2p_nres_RETURN[rel2p]: \"rel2p (\\<langle>A\\<rangle>nres_rel) (RETURN x) (RETURN y) = rel2p A x y\"   \n  by (auto simp: rel2p_def dest: nres_relD intro: nres_relI)\n\n\nsubsubsection \\<open>Boolean Operations on Specifications\\<close>\nlemma SPEC_iff:\n  assumes \"P \\<le> SPEC (\\<lambda>s. Q s \\<longrightarrow> R s)\"\n  and \"P \\<le> SPEC (\\<lambda>s. \\<not> Q s \\<longrightarrow> \\<not> R s)\"\n  shows \"P \\<le> SPEC (\\<lambda>s. Q s \\<longleftrightarrow> R s)\"\n  using assms[THEN pw_le_iff[THEN iffD1]]\n  by (auto intro!: pw_leI)\n\nlemma SPEC_rule_conjI:\n  assumes \"A \\<le> SPEC P\" and \"A \\<le> SPEC Q\"\n    shows \"A \\<le> SPEC (\\<lambda>v. P v \\<and> Q v)\"\nproof -\n  have \"A \\<le> inf (SPEC P) (SPEC Q)\" using assms by (rule_tac inf_greatest) assumption\n  thus ?thesis by (auto simp add:Collect_conj_eq)\nqed\n\nlemma SPEC_rule_conjunct1:\n  assumes \"A \\<le> SPEC (\\<lambda>v. P v \\<and> Q v)\"\n    shows \"A \\<le> SPEC P\"\nproof -\n  note assms\n  also have \"\\<dots> \\<le> SPEC P\" by (rule SPEC_rule) auto\n  finally show ?thesis .\nqed\n\nlemma SPEC_rule_conjunct2:\n  assumes \"A \\<le> SPEC (\\<lambda>v. P v \\<and> Q v)\"\n    shows \"A \\<le> SPEC Q\"\nproof -\n  note assms\n  also have \"\\<dots> \\<le> SPEC Q\" by (rule SPEC_rule) auto\n  finally show ?thesis .\nqed\n\n\nsubsubsection \\<open>Pointwise Reasoning\\<close>\nlemma inres_if:\n  \"\\<lbrakk> inres (if P then Q else R) x; \\<lbrakk>P; inres Q x\\<rbrakk> \\<Longrightarrow> S; \\<lbrakk>\\<not> P; inres R x\\<rbrakk> \\<Longrightarrow> S \\<rbrakk> \\<Longrightarrow> S\"\nby (metis (full_types))\n\nlemma inres_SPEC:\n  \"inres M x \\<Longrightarrow> M \\<le> SPEC \\<Phi> \\<Longrightarrow> \\<Phi> x\"\nby (auto dest: pwD2)\n\nlemma SPEC_nofail:\n  \"X \\<le> SPEC \\<Phi> \\<Longrightarrow> nofail X\"\nby (auto dest: pwD1)\n\nlemma nofail_SPEC: \"nofail m \\<Longrightarrow> m \\<le> SPEC (\\<lambda>_. True)\"\n  by (simp add: pw_le_iff)\n\nlemma nofail_SPEC_iff: \"nofail m \\<longleftrightarrow> m \\<le> SPEC (\\<lambda>_. True)\"\n  by (simp add: pw_le_iff)\n\nlemma nofail_SPEC_triv_refine: \"\\<lbrakk> nofail m; \\<And>x. \\<Phi> x \\<rbrakk> \\<Longrightarrow> m \\<le> SPEC \\<Phi>\"\n  by (simp add: pw_le_iff)\n\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/Refine_Monadic/Refine_Basic.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8670357494949105, "lm_q2_score": 0.8244619350028204, "lm_q1q2_score": 0.7148379717451946}}
{"text": "theory week03A_Isar_demo imports Main begin\n\n\\<comment> \\<open> ------------------------------------------------------------------ \\<close>\n\n\\<comment> \\<open>  {* Motivation *} \\<close>\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 (cases 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\\<comment> \\<open> ------------------------------------------------------------------\\<close>\n\n\\<comment> \\<open>  {* Isar *} \\<close>\n\nlemma \"\\<lbrakk> A; B \\<rbrakk> \\<Longrightarrow> A \\<and> B\"\nproof\n  assume A_is_true: \"A\"\n  from A_is_true show \"A\" by assumption\nnext\n  assume B_is_true: \"B\"\n  from B_is_true show \"B\" by simp\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\\<comment> \\<open> ------------------------------------------------------------------\\<close>\n\nsection \"More Isar\"\n\n\\<comment> \\<open>  {* . = by assumption,  .. = by rule *} \\<close>\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\n\\<comment> \\<open>  {* backward/forward *} \\<close>\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\n\\<comment> \\<open> {* fix *} \\<close>\n\nlemma\n  assumes P: \"\\<forall>x. P x\"\n  shows \"\\<forall>x. P (f x)\"\nproof\n  fix x\n  from P show \"P (f x)\" by(rule spec)\nqed\n\n\\<comment> \\<open> {* Proof text can only refer to global constants, free variables\nin the lemma, and local names introduced via fix or obtain. *} \\<close>\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\n\\<comment> \\<open>  {* obtain *} \\<close>\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\n\\<comment> \\<open>  {* moreover *} \\<close>\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\\<comment> \\<open> ------------------------------------------------------------------\\<close>\n\n\\<comment> \\<open> {* Isar, case distinction *} \\<close>\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\\<comment> \\<open> {* structural induction *} \\<close>\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) thus ?case by simp\nqed\n\n\\<comment> \\<open> {* induction with @{text\"\\<And>\"} or @{text\"\\<Longrightarrow>\"} *} \\<close>\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\\<comment> \\<open> ---------------------------------------------------------------\\<close>\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/week03A_Isar_demo.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619177503205, "lm_q2_score": 0.8670357477770336, "lm_q1q2_score": 0.7148379553703363}}
{"text": "(*<*)\ntheory EnumArbolesBinariosIngles\nimports T10MaximalHintikkaIngles \nbegin\n(*>*)\n\nsection \\<open> Enumeraci\u00f3n de f\u00f3rmulas proposicionales \\<close>\n\ntext \\<open>\n  \\label{enumeration} \n  En esta secci\u00f3n presentamos en un estilo declarativo en Isabelle/Isar una forma de enumerar las f\u00f3rmulas de\n  cualquier lenguaje de la l\u00f3gica proposicional, de acuerdo a la secci\u00f3n 6.4 de la teor\u00eda FOL_Fitting, v 1.2-\n  2007 (Stefan Berghofer, First-Order Logic According to Fitting).\n  La manera de enumerar las f\u00f3rmulas est\u00e1  basada en representarlas \n  por medio de \u00e1rboles binarios de n\u00fameros naturales.  De esta forma, si\n  se tiene una numeraci\u00f3n del conjunto de \u00e1rboles binarios entonces se\n  tiene una enumeraci\u00f3n del conjunto de f\u00f3rmulas del lenguaje dado.\n\n  Recordemos que una enumeraci\u00f3n de un conjunto $A$ es cualquier funci\u00f3n\n  sobreyectiva $f\\colon \\mathbb{N}\\to A$ definici\u00f3n (\\ref{enumerar}).\n\n  En forma equivalente, los siguientes dos lemas demuestran que, una\n  funci\u00f3n \\linebreak\n  $f\\colon \\mathbb{N}\\to A$ es una enumeraci\u00f3n si existe una funci\u00f3n $g$\n  inversa por derecha de $f$. \n\n  \\begin{lema}\\label{enum1}\n  Si $f$ es una func\u00edon sobreyectiva entonces, existe una funci\u00f3n $g$\n  inversa por derecha de $f$. \n  \\end{lema}\n\n  \\noindent Su formalizaci\u00f3n es\n\\<close>\n\nlemma enum1:\n  assumes \"(\\<forall>y.\\<exists>x. y = (f x))\"\n  shows \"\\<exists>g. \\<forall>y. f(g y) = y\"\n(*<*)\nproof -\n  fix y\n  { have \"\\<forall>y. y = f (SOME x. y = (f x))\"  \n    proof(rule allI)\n      fix y\n      obtain x where x: \"y= (f x)\" using assms by auto\n      thus \"y = f (SOME x. y = (f x))\" by (rule someI)\n    qed }\n  hence \"\\<forall>y. f((\\<lambda>y. SOME x. y = (f x)) y) = y\" by simp\n  thus \"\\<exists>g. \\<forall>y. f(g y) = y\"\n    by (rule_tac x = \"(\\<lambda>y. SOME x. y = (f x)) \" in exI)\nqed \n\n(*>*)\ntext \\<open>\n  \\begin{lema}\\label{enum2}\n  Si la funci\u00f3n $f$ tiene una inversa por derecha entonces, $f$ es\n  sobreyectiva. \n  \\end{lema}\n\n  \\noindent Su formalizaci\u00f3n es\n\\<close>\n \nlemma enum2:\n  assumes  \"\\<forall>x. f(g x) = x\"\n  shows \"\\<forall>y.\\<exists>x. y = f x\"\n(*<*)\nproof -  \n  { fix y\n    have \"\\<exists>x. y = f x\" using assms by(rule_tac x= \"g y\" in exI) simp } \n  thus \"\\<forall>y.\\<exists>x. y = f x\" by auto\nqed\n\n(*>*)\ntext \\<open> \n  As\u00ed, tenemos otra forma equivalente de definir la noci\u00f3n de\n enumeraci\u00f3n la cual se utilizar\u00e1 en esta secci\u00f3n: \n\n  \\begin{lema}\\label{enumera}\n  $f\\colon \\mathbb{N}\\to A$ es una enumeraci\u00f3n siysi tiene una inversa\n  por derecha. \n  \\end{lema}\n\n  \\noindent Su formalizaci\u00f3n es\n\\<close>\n\nlemma enumeration: \"enumeration f = (\\<exists>g. \\<forall>y. f(g y) = y)\"\nusing enum1 enum2 \nby (unfold enumeration_def) blast\n\nsubsection \\<open> Enumeraci\u00f3n de \u00e1rboles binarios \\<close>\n\ntext \\<open>\n  \\label{sec:enumeration} \n\n  En esta secci\u00f3n mostramos una manera de enumerar los \u00e1rboles binarios.\n  Conside\\-raremos formalmente el tipo de dato {\\em \u00e1rbol binario} donde\n  sus elementos son \u00e1rboles binarios cuyas hojas son n\u00fameros naturales.\n\\<close>\n\ndatatype arbolb = Hoja nat | Arbol arbolb arbolb\n\n(*\ndefinition numerable :: \"'b set  \\<Rightarrow> bool\" where\n  \"numerable A = (\\<exists>(f:: (nat set) \\<Rightarrow> A). surj f)\" \n*)\n\ntext \\<open>\n  La enumeraci\u00f3n del tipo de dato \u00e1rbol binario est\u00e1 basada en una\n  enumeraci\u00f3n del producto cartesiano $\\mathbb{N}\\times \\mathbb{N}$ de\n  los n\u00fameros naturales.\n\\<close>\n\nsubsubsection \\<open> \n  Enumeraci\u00f3n del producto cartesiano $\\mathbb{N}\\times \\mathbb{N}$ \n\\<close>\n \ntext \\<open>\n Se listan los elementos de $\\mathbb{N}\\times \\mathbb{N}$ por la suma de sus componentes y los que tienen\n  la misma suma se ordenan por su primera componente. La funci\u00f3n {\\em\n  diag}, que le asigna a cada n\u00famero natural el par que ocupa la\n  posici\u00f3n $n$ en la anterior ordenaci\u00f3n, se puede definir por recursi\u00f3n\n  como sigue:\n\n  \\begin{enumerate}\n      \\item $diag(0)=(0,0)$\n      \\item $diag(n+1) = \n              \\begin{cases}             \n                (0, x+1), & \\mbox{si $diag(n)= (x,0)$}\\\\ \n                (x+1, y), & \\mbox{si $diag(n)= (x, y+1)$}                 \n              \\end{cases}$    \n  \\end{enumerate}\n\n  \\noindent Su formalizaci\u00f3n es\n\\<close>\n\nprimrec diag :: \"nat \\<Rightarrow> (nat \\<times> nat)\" where\n  \"diag 0 = (0, 0)\"\n| \"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))\"\n\ntext \\<open> \n  Para demostrar que @{text \"diag\"} es sobreyectiva, definimos la\n  siguiente funci\u00f3n {\\em undiag} inversa (por derecha) de @{text\n  \"diag\"}, \n  \\begin{enumerate}\n      \\item $undiag(0, 0) = 0$\n      \\item $undiag(0, y+1) = undiag(y,0)+1$\n      \\item $undiag(x+1, y) = undiag(x,y+1)+1$\n  \\end{enumerate}\n\\<close>\n\nfunction undiag :: \"nat \\<times> nat \\<Rightarrow> nat\" where\n  \"undiag (0, 0) = 0\"\n| \"undiag (0, Suc y) = Suc (undiag (y, 0))\"\n| \"undiag (Suc x, y) = Suc (undiag (x, Suc y))\"\nby pat_completeness auto\n\ntermination\n  by (relation \"measure (\\<lambda>(x, y). ((x + y) * (x + y + 1)) div 2 + x)\") auto\n\ntext \\<open> \n  N\u00f3tese que la funci\u00f3n de medida de la funci\u00f3n {\\em undiag} est\u00e1\n  definida justamente por la expresi\u00f3n que define expl\u00edcitamente a la\n  funci\u00f3n {\\em undiag}.\n\\<close>\n\ntext \\<open> \n  El siguiente resultado demuestra que {\\em undiag} es inversa por\n  derecha de {\\em diag.} \n\\<close>\n\nlemma diag_undiag [simp]: \"diag (undiag (x, y)) = (x, y)\"\nby (rule undiag.induct) (simp add: Let_def)+\n\ntext \\<open> \n  De esta forma, se tiene que  la funci\u00f3n {\\em diag} es una enumeraci\u00f3n\n  de $\\mathbb{N}\\times \\mathbb{N}$. Formalmente: \n\\<close>\n\nlemma enumeration_natxnat: \"enumeration (diag::nat \\<Rightarrow> (nat \\<times> nat))\"\nproof -\n  have \"\\<forall>x y. diag (undiag (x, y)) = (x, y)\" using diag_undiag by auto\n  hence \"\\<exists>undiag. \\<forall>x y. diag (undiag (x, y)) = (x, y)\" by blast\n  thus ?thesis using enumeration[of diag] by auto\nqed\n\nsubsubsection \\<open> Enumeraci\u00f3n del tipo de datos \u00e1rbol binario  \\<close>\n\ntext \\<open> \n  \\label{enumarbolb}\n\n  Con base a la enumeraci\u00f3n @{text \"diag\"} del producto cartesiano\n  $\\mathbb{N}\\times \\mathbb{N}$, definimos la siguiente enumeraci\u00f3n\n  @{text \"diag_arbolb :\"} $\\mathbb{N}\\to arbolb$ del tipo de datos \n  @{text \"arbolb\"}.\n\n  Dado $n\\in \\mathbb{N}$, supogamos que $diag(n) = (x,y)$.\n  \\begin{enumerate}\n    \\qtreecenterfalse\n    \\item Si $x=0$ entonces @{text \"diag_arbolb(n)\"} es el \u00e1rbol\n      \\begin{center}\n         \\Tree [[.$y$ ]] \n      \\end{center}\n    \\item Si $x=z+1$ para alg\u00fan $z\\in \\mathbb{N}$ entonces, @{text\n      \"diag_arbolb(n)\"} es el \u00e1rbol         \n       \\begin{center}\n         \\qtreecenterfalse\n        \\Tree [ \\qroof{@{text \"diag_arbolb(z)\"}}.{\\textbullet}  \n                \\qroof{@{text \"diag_arbolb(y)\"}}.{\\textbullet}  ]\n        \\end{center}                \n    \\end{enumerate}\n\\<close>\n\nfunction diag_arbolb :: \"nat \\<Rightarrow> arbolb\" where\n\"diag_arbolb n = (case fst (diag n) of\n       0 \\<Rightarrow> Hoja (snd (diag n))\n      | Suc z \\<Rightarrow> Arbol (diag_arbolb z) (diag_arbolb (snd (diag n))))\"\nby auto\n\n(*<*)\ntext \\<open> \n  Los siguientes lemas permiten demostrar la terminaci\u00f3n de la funcion\n  {\\em diag-arbolb}. \n\\<close>\n(*>*)\n\n(*<*)\nlemma diag_le1: \"fst (diag (Suc n)) < Suc n\"\nby (induct n) (simp_all add: Let_def split_def split: nat.split) \n\nlemma diag_le2: \"snd (diag (Suc (Suc n))) < Suc (Suc n)\"\nusing diag_le1 by (induct n) (simp_all add: Let_def split_def split: nat.split) \n\nlemma diag_le3:\n  assumes \"fst (diag n) = Suc x\"\n  shows \"snd (diag n) < n\"\nproof (cases n) \n  assume \"n=0\" thus \"snd (diag n) < n\" using assms by simp\nnext\n  fix nat\n  assume h1: \"n = Suc nat\"\n  show \"snd (diag n) < n\"\n  proof (cases nat)\n    assume \"nat = 0\"\n    thus \"snd (diag n) < n\" using assms h1 by (simp add: Let_def)\n  next \n    fix nata\n    assume \"nat = Suc nata\"\n    thus \"snd (diag n) < n\" using assms h1 by hypsubst (rule diag_le2)\n  qed\nqed\n\nlemma diag_le4: \n  assumes \"fst (diag n) = Suc x\"\n  shows \"x < n\"\nproof (cases n)  \n  assume \"n = 0\" thus \"x < n\" using assms by simp\nnext\n  fix nat\n  assume h1: \"n = Suc nat\" \n  show \"x < n\"\n  proof (cases nat)\n    assume \"nat = 0\" thus \"x < n\" using assms h1 by hypsubst (simp add: Let_def)\n  next\n    fix nata\n    assume h2: \"nat = Suc nata\"\n    hence \"fst(diag n) = fst(diag (Suc(Suc nata)))\" using h1 by simp\n    hence \"fst(diag (Suc(Suc nata))) = Suc x\" using assms by simp\n    moreover\n    have \"fst(diag (Suc(Suc nata))) < Suc(Suc nata)\" by (rule diag_le1)\n    ultimately\n    have \"Suc x < Suc (Suc nata)\" by simp\n    thus \"x < n\" using h1 h2 by simp\n  qed\nqed\n\ntermination diag_arbolb\nby (relation \"measure (\\<lambda>x. x)\") (auto intro: diag_le3 diag_le4)\n(*>*)\n\ntext \\<open> \n  La siguiente funci\u00f3n {\\em undiag-arbolb} corresponde a una inversa\n  (por derecha) de la funci\u00f3n {\\em diag-arbolb}.\n\\<close> \n\nprimrec undiag_arbolb :: \"arbolb \\<Rightarrow> nat\" where\n  \"undiag_arbolb (Hoja n) = undiag (0, n)\"\n| \"undiag_arbolb (Arbol t1 t2) =\n   undiag (Suc (undiag_arbolb t1), undiag_arbolb t2)\"\n\ntext \\<open> \n  El siguiente lema demuestra que {\\em undiag-arbolb} es inversa por\n  derecha de \\linebreak \n  {\\em diag-arbolb}.\n\\<close>\n\nlemma diag_undiag_arbolb [simp]: \"diag_arbolb (undiag_arbolb t) = t\"\nby (induct t) (simp_all add: Let_def)\n\ntext \\<open> \n  Por consiguiente, la funci\u00f3n  @{text \"diag_arbolb\"} es una enumeraci\u00f3n\n  del tipo de dato @{text \"arbolb\"}: \n\\<close>\n\nlemma enumeration_arbolb: \"enumeration (diag_arbolb :: nat \\<Rightarrow> arbolb)\"\nproof - \n  have \"\\<forall>x. diag_arbolb (undiag_arbolb x) = x\" \n    using diag_undiag_arbolb by blast\n  hence \"\\<exists>undiag_arbolb. \\<forall>x . diag_arbolb (undiag_arbolb x) = x\" by blast\n  thus ?thesis using enumeration[of diag_arbolb] by auto\nqed\n\n(*<*)\ndeclare diag_arbolb.simps [simp del] undiag_arbolb.simps [simp del]\n(*>*)\n\n(*<*)\nend\n(*>*)\n", "meta": {"author": "mayalarincon", "repo": "halltheorem", "sha": "6c694d6b154df4576b648810a5ec2f1814a0c99b", "save_path": "github-repos/isabelle/mayalarincon-halltheorem", "path": "github-repos/isabelle/mayalarincon-halltheorem/halltheorem-6c694d6b154df4576b648810a5ec2f1814a0c99b/ExistenciaModelosIngles/EnumArbolesBinariosIngles.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681158979307, "lm_q2_score": 0.8333245953120233, "lm_q1q2_score": 0.7147992680521997}}
{"text": "(*\nTitle:  Allen's qualitative temporal calculus\nAuthor:  Fadoua Ghourabi (fadouaghourabi@gmail.com)\nAffiliation: Ochanomizu University, Japan\n*)\n\nsection \\<open>Time interval relations\\<close>\n\n\ntheory allen\n\nimports\n\n  Main axioms \n  \"HOL-Eisbach.Eisbach_Tools\"\n\n\nbegin\n\nsection \\<open>Basic relations\\<close>\n\ntext\\<open>We  define 7 binary relations  between time intervals. \nRelations e, m, b, ov, d, s and f stand for equal, meets, before, overlaps, during, starts and finishes, respectively.\\<close>\n\nclass arelations = interval + \n fixes \n  e::\"('a\\<times>'a) set\" and\n  m::\"('a\\<times>'a) set\" and \n  b::\"('a\\<times>'a) set\" and\n  ov::\"('a\\<times>'a) set\" and\n  d::\"('a\\<times>'a) set\" and\n  s::\"('a\\<times>'a) set\" and\n  f::\"('a\\<times>'a) set\"  \nassumes\n  e:\"(p,q) \\<in> e = (p = q)\" and\n  m:\"(p,q) \\<in> m = p\\<parallel>q\" and\n  b:\"(p,q) \\<in> b = (\\<exists>t::'a. p\\<parallel>t \\<and> t\\<parallel>q)\" and\n  ov:\"(p,q) \\<in> ov = (\\<exists>k l u v t::'a. \n                   (k\\<parallel>p \\<and> p\\<parallel>u \\<and> u\\<parallel>v) \\<and> (k\\<parallel>l \\<and> l\\<parallel>q \\<and> q\\<parallel>v) \\<and> (l\\<parallel>t \\<and> t\\<parallel>u))\" and\n  s:\"(p,q) \\<in> s =  (\\<exists>k u v::'a. k\\<parallel>p \\<and> p\\<parallel>u \\<and> u\\<parallel>v \\<and> k\\<parallel>q \\<and> q\\<parallel>v)\" and\n  f:\"(p,q) \\<in> f = (\\<exists>k l  u ::'a. k\\<parallel>l \\<and> l\\<parallel>p \\<and> p\\<parallel>u \\<and> k\\<parallel>q \\<and> q\\<parallel>u)\" and\n  d:\"(p,q) \\<in> d = (\\<exists>k l u v::'a. k\\<parallel>l \\<and> l\\<parallel>p \\<and> p\\<parallel>u \\<and>u\\<parallel>v \\<and> k\\<parallel>q \\<and> q\\<parallel>v)\" \n \n\n(** e compositions **)\nsubsection \\<open>e-composition\\<close>\ntext \\<open>Relation e is the identity relation for composition.\\<close>\n\nlemma cer:\nassumes  \"r \\<in> {e,m,b,ov,s,f,d,m^-1,b^-1,ov^-1,s^-1,f^-1,d^-1}\" \nshows \"e O r = r\"\nproof -\n  { fix x y assume a:\"(x,y) \\<in> e O r\" \n    then obtain z where \"(x,z) \\<in> e\" and \"(z,y) \\<in> r\" by auto\n    from \\<open>(x,z) \\<in> e\\<close> have \"x = z\" using e by auto\n    with \\<open>(z,y)\\<in> r\\<close> have \"(x,y) \\<in> r\" by simp} note c1 = this\n  \n { fix x y assume a:\"(x,y) \\<in>  r\"\n   have \"(x,x) \\<in> e\" using e by auto\n   with a have \"(x,y) \\<in> e O r\" by blast} note c2 = this\n \n from c1 c2 show ?thesis by auto\nqed\n\nlemma cre:\nassumes  \"r \\<in> {e,m,b,ov,s,f,d,m^-1,b^-1,ov^-1,s^-1,f^-1,d^-1}\"\nshows \" r O e = r\"\nproof -\n  { fix x y assume a:\"(x,y) \\<in> r O e\" \n    then obtain z where \"(x,z) \\<in> r\" and \"(z,y) \\<in> e\" by auto\n    from \\<open>(z,y) \\<in> e\\<close> have \"z = y\" using e by auto\n    with \\<open>(x,z)\\<in> r\\<close> have \"(x,y) \\<in> r\" by simp} note c1 = this\n  \n { fix x y assume a:\"(x,y) \\<in>  r\"\n   have \"(y,y) \\<in> e\" using e by auto\n   with a have \"(x,y) \\<in> r O e\" by blast} note c2 = this\n \n from c1 c2 show ?thesis by auto\nqed\n\nlemmas ceb = cer[of b]\nlemmas cebi = cer[of \"b^-1\"]\nlemmas cem = cer[of m]\nlemmas cemi = cer[of \"m^-1\"]\nlemmas cee = cer[of e]\nlemmas ces = cer[of s]\nlemmas cesi = cer[of \"s^-1\"]\nlemmas cef = cer[of f]\nlemmas cefi = cer[of \"f^-1\"]\nlemmas ceov = cer[of ov]\nlemmas ceovi = cer[of \"ov^-1\"]\nlemmas ced = cer[of d]\nlemmas cedi = cer[of \"d^-1\"]\nlemmas cbe = cre[of b]\nlemmas cbie = cre[of \"b^-1\"]\nlemmas cme = cre[of m]\nlemmas cmie = cre[of \"m^-1\"]\nlemmas cse = cre[of s]\nlemmas csie = cre[of \"s^-1\"]\nlemmas cfe = cre[of f]\nlemmas cfie = cre[of \"f^-1\"]\nlemmas cove = cre[of ov]\nlemmas covie = cre[of \"ov^-1\"]\nlemmas cde = cre[of d]\nlemmas cdie = cre[of \"d^-1\"]\n\n(*******)\n\n(* composition with single relation *)\nsubsection \\<open>r-composition\\<close>\ntext \\<open>We prove compositions of the form $r_1 \\circ r_2 \\subseteq r$, where $r$ is a basic relation.\\<close>\n\nmethod (in arelations) r_compose uses r1 r2 r3 = ((auto, (subst (asm) r1 ), (subst (asm) r2), (subst r3)) ,  (meson M5exist_var))\n\n\nlemma (in arelations) cbb:\"b O b \\<subseteq> b\"\n  by (r_compose r1:b r2:b r3:b)\n\nlemma  (in arelations)  cbm:\"b O m \\<subseteq> b\"\n  by (r_compose r1:b r2:m r3:b)\n\nlemma cbov:\"b O ov \\<subseteq> b\"\n  apply (auto simp:b ov)\n  using M1 M5exist_var by blast\n\nlemma cbfi:\"b O f^-1 \\<subseteq> b\"\n  apply (auto simp:b f)\n  by (meson M1 M5exist_var)\n\nlemma cbdi:\"b O d^-1 \\<subseteq> b\"\n  apply (auto simp: b d)\n  by (meson M1 M5exist_var)\n \nlemma cbs:\"b O s \\<subseteq> b\"\n  apply (auto simp: b s)\n  by (meson M1 M5exist_var)\n\nlemma cbsi:\"b O s^-1 \\<subseteq> b\"\n  apply (auto simp: b s)\n  by (meson M1 M5exist_var)\n\nlemma (in arelations) cmb:\"m O b \\<subseteq> b\"\n  by (r_compose r1:m r2:b r3:b)\n\nlemma cmm:\"m O m \\<subseteq> b\"\n  by (auto simp: b m)\n\nlemma cmov:\"m O ov \\<subseteq> b\"\n  apply (auto simp:b m ov)\n  using M1 M5exist_var by blast\n\nlemma cmfi:\"m O f^-1 \\<subseteq> b\"\n  apply (r_compose r1:m r2:f r3:b)\n  by (meson M1)\n\nlemma cmdi:\"m O d^-1 \\<subseteq> b\"\n  apply (auto simp add:m d b)\n  using M1 by blast\n\nlemma cms:\"m O s \\<subseteq> m\"\n  apply (auto simp add:m s)\n  using M1 by auto\n\nlemma cmsi:\"m O s^-1 \\<subseteq> m\"\n  apply (auto simp add:m s)\n  using M1 by blast\n\nlemma covb:\"ov O b \\<subseteq> b\"\n  apply (auto simp:ov b)\n  using M1 M5exist_var by blast\n\nlemma covm:\"ov O m \\<subseteq> b\"\n  apply (auto simp:ov m b)\n  using M1 by blast\n\nlemma covs:\"ov O s \\<subseteq> ov\" \nproof\n  fix p::\"'a\\<times>'a\" assume \"p \\<in> ov O s\" then obtain x y z where p:\"p = (x,z)\" and xyov:\"(x,y)\\<in> ov\" and yzs:\"(y,z) \\<in> s\" by auto\n  from xyov obtain r u v t k where rx:\"r\\<parallel>x\" and xu:\"x\\<parallel>u\" and uv:\"u\\<parallel>v\" and rt:\"r\\<parallel>t\" and tk:\"t\\<parallel>k\" and ty:\"t\\<parallel>y\" and yv:\"y\\<parallel>v\" and ku:\"k\\<parallel>u\" using ov by blast\n  from yzs obtain l1 l2 where yl1:\"y\\<parallel>l1\" and l1l2:\"l1\\<parallel>l2\" and zl2:\"z\\<parallel>l2\" using s by blast\n  from uv yl1 yv have \"u\\<parallel>l1\" using M1 by blast\n  with xu l1l2 obtain ul1 where xul1:\"x\\<parallel>ul1\" and ul1l2:\"ul1\\<parallel>l2\" using M5exist_var by blast\n  from ku xu xul1 l1l2 have kul1:\"k\\<parallel>ul1\" using M1 by blast\n  from ty yzs have \"t\\<parallel>z\" using s M1 by blast\n  with rx rt xul1 ul1l2 zl2 tk kul1 have \"(x,z) \\<in> ov\" using ov by blast\n  with p show \"p \\<in> ov\" by simp\nqed\n\nlemma cfib:\"f^-1 O b \\<subseteq> b\" \n  apply (auto simp:f b)\n  using M1 by blast\n\nlemma cfim:\"f^-1 O m \\<subseteq> m\"\n  apply (auto simp:f m)\n  using M1 by auto\n\nlemma cfiov:\"f^-1 O ov \\<subseteq> ov\" \nproof \n    fix p::\"'a\\<times>'a\" assume \"p \\<in> f^-1 O ov\" then obtain x y z where p:\"p = (x,z)\" and xyfi:\"(x,y)\\<in> f^-1\" and yzov:\"(y,z) \\<in> ov\" by auto\n    from xyfi yzov obtain t' r u   where tpr:\"t'\\<parallel>r\" and ry:\"r\\<parallel>y\" and yu:\"y\\<parallel>u\" and tpx:\"t'\\<parallel>x\" and xu:\"x\\<parallel>u\"  using f  by blast\n    from yzov  ry  obtain v k t u' where yup:\"y\\<parallel>u'\" and upv:\"u'\\<parallel>v\" and rk:\"r\\<parallel>k\" and kz:\"k\\<parallel>z\" and zv:\"z\\<parallel>v\" and kt:\"k\\<parallel>t\" and tup:\"t\\<parallel>u'\" \n    using ov using M1 by blast\n    from yu xu yup have xup:\"x\\<parallel>u'\" using M1 by blast\n    from tpr rk kt obtain r' where tprp:\"t'\\<parallel>r'\" and rpt:\"r'\\<parallel>t\" using M5exist_var by blast\n    from kt rpt kz have rpz:\"r'\\<parallel>z\" using M1 by blast\n    from tprp rpz rpt tpx xup zv upv tup have \"(x,z) \\<in> ov\" using ov by blast\n    with p show \"p \\<in> ov\" by simp\nqed\n\nlemma cfifi:\"f^-1 O f^-1 \\<subseteq> f^-1\"\nproof\n  fix x::\"'a\\<times>'a\" assume \"x \\<in> f^-1 O f^-1\" then obtain p q z where x:\"x = (p, q)\" and \"(p,z) \\<in> f^-1\" and \"(z,q) \\<in> f^-1\" by auto\n  from \\<open>(p,z) \\<in> f^-1\\<close> obtain k l u  where kp:\"k\\<parallel>p\" and kl:\"k\\<parallel>l\" and lz:\"l\\<parallel>z\" and pu:\"p\\<parallel>u\" and zu:\"z\\<parallel>u\"  using f  by blast\n  from \\<open>(z,q) \\<in> f^-1\\<close> obtain k' u' l' where kpz:\"k'\\<parallel>z\" and kplp:\"k'\\<parallel>l'\" and lpq:\"l'\\<parallel>q\" and qup:\"q\\<parallel>u'\" and zup:\"z\\<parallel>u'\"  using f  by blast\n  from zu zup pu have \"p\\<parallel>u'\" using M1 by blast\n  from lz kpz kplp have \"l\\<parallel>l'\" using M1 by blast\n  with kl lpq obtain ll where \"k\\<parallel>ll\" and \"ll\\<parallel>q\" using M5exist_var by blast\n  with kp \\<open>p\\<parallel>u'\\<close> qup show \"x \\<in> f^-1\" using x f by blast\nqed\n\nlemma cfidi:\"f^-1 O d^-1 \\<subseteq> d^-1\"\nproof\n  fix x::\"'a\\<times>'a\" assume \"x : f^-1 O d^-1\" then obtain p q z where x:\"x = (p,q)\" and \"(p,z) \\<in> f^-1\" and \"(z,q) \\<in> d^-1\" by auto\n  then obtain k l u where kp:\"k \\<parallel> p\" and kl:\"k\\<parallel>l\" and lz:\"l\\<parallel>z\" and pu:\"p \\<parallel>u\" and  zu:\"z\\<parallel>u\" using f  by blast\n  obtain k' l' u' v' where kpz:\"k' \\<parallel>z\" and kplp:\"k' \\<parallel>l'\" and lpq:\"l' \\<parallel>q\" and  qup:\"q \\<parallel>u'\" and  upvp:\"u'\\<parallel>v'\" and zvp:\"z\\<parallel>v'\" using d \\<open>(z,q)\\<in>d^-1\\<close> by blast\n  from lz kpz kplp have \"l\\<parallel>l'\" using M1 by blast\n  with kl lpq obtain ll where \"k\\<parallel>ll\" and \"ll\\<parallel>q\" using M5exist_var by blast\n  moreover from zu zvp upvp have \"u' \\<parallel> u \" using M1 by blast\n  ultimately show \"x \\<in> d^-1\" using x kp pu qup d  by blast\nqed\n\nlemma cfis:\"f^-1 O s \\<subseteq> ov\"\nproof\n   fix x::\"'a\\<times>'a\" assume \"x \\<in> f^-1 O s\" then obtain p q z where x:\"x = (p,q)\" and \"(p,z)\\<in> f^-1\" and \"(z,q) \\<in> s\" by auto\n   from \\<open>(p,z)\\<in> f^-1\\<close> obtain k l u where kp:\"k\\<parallel>p\" and kl:\"k\\<parallel>l\" and lz:\"l\\<parallel>z\" and pu:\"p\\<parallel>u\" and zu:\"z\\<parallel>u\" using f by blast\n   from \\<open>(z,q)\\<in> s\\<close> obtain k' u' v' where kpz:\"k'\\<parallel>z\" and kpq:\"k'\\<parallel>q\" and zup:\"z\\<parallel>u'\" and upvp:\"u'\\<parallel>v'\" and qvp:\"q\\<parallel>v'\" using s M1 by blast\n   from pu zu zup have pup:\"p\\<parallel>u'\" using M1 by blast\n   moreover from lz kpz kpq have lq:\"l\\<parallel>q\" using M1 by blast\n   ultimately show \"x \\<in> ov\" using x lz zup kp kl upvp upvp ov qvp by blast\nqed\n\nlemma cfisi:\"f^-1 O s^-1 \\<subseteq> d^-1\"\nproof\n  fix x::\"'a\\<times>'a\" assume \"x \\<in> f^-1 O s^-1\" then obtain p q z where x:\"x = (p,q)\" and \"(p,z) \\<in> f^-1\" and \"(z,q) \\<in> s^-1\" by auto\n  then obtain k l u where kp:\"k \\<parallel> p\" and kl:\"k\\<parallel>l\" and lz:\"l\\<parallel>z\"  and pu:\"p \\<parallel>u\" and  zu:\"z\\<parallel>u\" using f  by blast\n  obtain k' u' v' where kpz:\"k' \\<parallel>z\" and kpq:\"k' \\<parallel>q\" and qup:\"q \\<parallel>u'\" and  upvp:\"u'\\<parallel>v'\" and  zvp:\"z\\<parallel>v'\" using s \\<open>(z,q): s^-1\\<close> by blast\n  from zu zvp upvp have \"u'\\<parallel>u\" using M1 by blast\n  moreover from lz kpz kpq have \"l \\<parallel>q \" using M1 by blast\n  ultimately show \"x \\<in> d^-1\" using x d kl kp qup  pu  by blast\nqed\n\nlemma cdifi:\"d^-1 O f^-1 \\<subseteq> d^-1\"\nproof\n  fix x::\"'a\\<times>'a\" assume \"x : d^-1 O f^-1\" then obtain p q z where x:\"x = (p,q)\" and \"(p,z) \\<in> d^-1\" and \"(z,q) \\<in> f^-1\" by auto\n  then obtain k l u v  where kp:\"k \\<parallel> p\" and kl:\"k\\<parallel>l\" and lz:\"l\\<parallel>z\" and zu:\"z \\<parallel>u\" and uv:\"u\\<parallel>v\" and pv:\"p\\<parallel>v\" using d  by blast\n  obtain k' l' u' where kpz:\"k' \\<parallel>z\" and kplp:\"k' \\<parallel>l'\" and lpq:\"l' \\<parallel>q\" and  qup:\"q \\<parallel>u'\" and zup:\"z\\<parallel>u'\" using f \\<open>(z,q): f^-1\\<close> by blast\n  from lz kpz kplp  have \"l\\<parallel>l'\" using M1 by blast\n  with kl lpq obtain ll where \"k\\<parallel>ll\" and \"ll\\<parallel>q\" using M5exist_var by blast\n  moreover from zu qup zup have \"q \\<parallel> u \" using M1 by blast\n  ultimately show \"x \\<in> d^-1\" using x d kp uv pv  by blast\nqed\n\nlemma cdidi:\"d^-1 O d^-1 \\<subseteq> d^-1\" \nproof\n  fix x::\"'a\\<times>'a\" assume \"x : d^-1 O d^-1\" then obtain p q z where x:\"x = (p,q)\" and \"(p,z) \\<in> d^-1\" and \"(z,q) \\<in> d^-1\" by auto\n  then obtain k l u v where kp:\"k \\<parallel> p\" and kl:\"k\\<parallel>l\" and lz:\"l\\<parallel>z\" and zu:\"z \\<parallel>u\" and uv:\"u\\<parallel>v\" and pv:\"p\\<parallel>v\" using d  by blast\n  obtain k' l' u' v' where kpz:\"k' \\<parallel>z\" and kplp:\"k' \\<parallel>l'\" and lpq:\"l' \\<parallel>q\" and  qup:\"q \\<parallel>u'\" and upvp:\"u' \\<parallel>v'\" and zvp:\"z \\<parallel>v'\" using d \\<open>(z,q): d^-1\\<close> by blast\n  from lz kpz kplp  have \"l\\<parallel>l'\" using M1 by blast\n  with kl lpq obtain ll where \"k\\<parallel>ll\" and \"ll\\<parallel>q\" using M5exist_var by blast\n  moreover from zvp zu upvp have \"u' \\<parallel> u \" using M1 by blast\n  moreover with qup uv obtain uu where \"q\\<parallel>uu\" and \"uu\\<parallel>v\" using M5exist_var  by blast\n  ultimately show \"x \\<in> d^-1\" using x d kp pv   by blast\nqed\n\nlemma cdisi:\"d^-1 O s^-1 \\<subseteq> d^-1\"\nproof\n  fix x::\"'a\\<times>'a\" assume \"x : d^-1 O s^-1\" then obtain p q z where x:\"x = (p,q)\" and \"(p,z) \\<in> d^-1\" and \"(z,q) \\<in> s^-1\" by auto\n  then obtain k l  u v where kp:\"k \\<parallel>p\" and kl:\"k\\<parallel>l\"  and lz:\"l\\<parallel>z\" and zu:\"z\\<parallel>u\" and uv:\"u\\<parallel>v\" and pv:\"p\\<parallel>v\" using d by blast\n  obtain k' u' v' where kpz:\"k' \\<parallel>z\" and kpq:\"k' \\<parallel>q\" and  qup:\"q \\<parallel>u'\" and upvp:\"u' \\<parallel>v'\" and zvp:\"z \\<parallel>v'\" using s \\<open>(z,q): s^-1\\<close> by blast\n  from upvp zvp zu have \"u'\\<parallel>u\" using M1 by blast\n  with qup uv obtain uu where \"q\\<parallel>uu\" and \"uu\\<parallel>v\" using M5exist_var by blast\n  moreover from kpz lz kpq have \"l \\<parallel>q \" using M1 by blast\n  ultimately show \"x \\<in> d^-1\" using x d kp kl pv  by blast\nqed\n\nlemma csb:\"s O b \\<subseteq> b\"\napply (auto simp:s b)\nusing M1 M5exist_var by blast\n\nlemma csm:\"s O m \\<subseteq> b\"\napply (auto simp:s m b)\nusing M1 by blast\n\nlemma css:\"s O s \\<subseteq> s\"\nproof\n  fix x::\"'a\\<times>'a\" assume \"x \\<in> s O s\" then obtain p q z where x:\"x = (p,q)\" and \"(p,z) \\<in> s\" and \"(z,q) \\<in> s\" by auto\n  from \\<open>(p,z) \\<in> s\\<close> obtain k u v where kp:\"k\\<parallel>p\" and kz:\"k\\<parallel>z\" and pu:\"p\\<parallel>u\" and uv:\"u\\<parallel>v\" and zv:\"z\\<parallel>v\" using s by blast\n  from \\<open>(z,q) \\<in> s\\<close> obtain k' u' v' where kpq:\"k'\\<parallel>q\" and kpz:\"k'\\<parallel>z\" and zup:\"z\\<parallel>u'\" and upvp:\"u'\\<parallel>v'\" and qvp:\"q\\<parallel>v'\" using s by blast\n  from kp kpz kz have \"k'\\<parallel>p\" using M1 by blast\n  moreover from uv zup zv have \"u\\<parallel>u'\" using M1 by blast\n  moreover with pu upvp obtain uu where \"p\\<parallel>uu\" and \"uu\\<parallel>v'\" using M5exist_var by blast\n  ultimately show \"x \\<in> s\" using x s kpq qvp  by blast\nqed\n\nlemma csifi:\"s^-1 O f^-1 \\<subseteq> d^-1\"\nproof\n  fix x::\"'a\\<times>'a\" assume \"x : s^-1 O f^-1\" then obtain p q z where x:\"x = (p,q)\" and \"(p,z) \\<in> s^-1\" and \"(z,q) \\<in> f^-1\" by auto\n  then obtain k u v where kp:\"k \\<parallel> p\" and kz:\"k\\<parallel>z\" and zu:\"z \\<parallel>u\" and uv:\"u\\<parallel>v\" and pv:\"p\\<parallel>v\" using s  by blast\n  obtain k' l' u' where kpz:\"k' \\<parallel>z\" and kplp:\"k' \\<parallel>l'\" and lpq:\"l' \\<parallel>q\"  and zup:\"z\\<parallel>u'\" and qup:\"q\\<parallel>u'\" using f \\<open>(z,q): f^-1\\<close> by blast\n  from kz kpz kplp have \"k\\<parallel>l'\" using M1 by blast\n  moreover from qup zup zu have \"q \\<parallel> u \" using M1 by blast\n  ultimately show \"x \\<in> d^-1\" using x d kp lpq pv uv by blast\nqed\n\nlemma csidi:\"s^-1 O d^-1 \\<subseteq> d^-1\"\nproof\n  fix x::\"'a\\<times>'a\" assume \"x : s^-1 O d^-1\" then obtain p q z where x:\"x = (p,q)\" and \"(p,z) \\<in> s^-1\" and \"(z,q) \\<in> d^-1\" by auto\n  then obtain k u v where kp:\"k \\<parallel> p\" and kz:\"k\\<parallel>z\"  and zu:\"z \\<parallel>u\" and uv:\"u\\<parallel>v\" and pv:\"p\\<parallel>v\" using s  by blast\n  obtain k' l' u' v' where kpz:\"k' \\<parallel>z\" and kplp:\"k' \\<parallel>l'\" and lpq:\"l'\\<parallel>q\" and qup:\"q \\<parallel>u'\" and upvp:\"u' \\<parallel>v'\" and zvp:\"z\\<parallel>v'\" using d \\<open>(z,q): d^-1\\<close> by blast\n  from zvp upvp zu have \"u'\\<parallel>u\" using M1 by blast\n  with qup uv obtain uu where \"q\\<parallel>uu\" and \"uu\\<parallel>v\" using M5exist_var by blast\n  moreover from kz kpz kplp have \"k \\<parallel>l' \" using M1 by blast\n  ultimately show \"x \\<in> d^-1\" using x d kp lpq pv  by blast\nqed\n\nlemma cdb:\"d O b \\<subseteq> b\"\napply (auto simp:d b)\nusing M1 M5exist_var by blast\n\nlemma cdm:\"d O m \\<subseteq> b\"\napply (auto simp:d m b)\nusing M1 by blast\n\nlemma cfb:\"f O b \\<subseteq> b\"\napply (auto simp:f b)\nusing M1 by blast\n\nlemma cfm:\"f O m \\<subseteq> m\"\nproof \n  fix x::\"'a\\<times>'a\" assume \"x \\<in> f O m\" then obtain p q z where x:\"x = (p,q)\" and 1:\"(p,z) \\<in> f\" and 2:\"(z,q) \\<in> m\" by auto\n  from 1 obtain u where pu:\"p\\<parallel>u\" and zu:\"z\\<parallel>u\" using f by auto\n  with 2   have \"(p,q) \\<in> m\" using M1 m by blast\n  thus \"x\\<in> m\" using x by auto\nqed\n\n\n(* ========= $\\alpah_1$ compositions ============ *)\nsubsection \\<open>$\\alpha$-composition\\<close>\ntext \\<open>We prove compositions of the form $r_1 \\circ r_2 \\subseteq s \\cup ov \\cup d$.\\<close>\n\n\nlemma (in arelations) cmd:\"m O d \\<subseteq> s \\<union> ov \\<union> d\"\nproof \n  fix x::\"'a\\<times>'a\" assume a:\"x \\<in> m O d\" then obtain p q z where x:\"x =(p,q)\" and 1:\"(p,z) \\<in> m\" and 2:\"(z,q) \\<in> d\" by auto\n  then obtain k l u v  where pz:\"p\\<parallel>z\" and kq:\"k\\<parallel>q\" and kl:\"k\\<parallel>l\" and lz:\"l\\<parallel>z\" and zu:\"z\\<parallel>u\" and uv:\"u\\<parallel>v\" and qv:\"q\\<parallel>v\" using m d by blast\n  obtain k' where kpp:\"k'\\<parallel>p\" using M3 meets_wd pz by blast\n  from pz zu uv obtain zu where pzu:\"p\\<parallel>zu\" and zuv:\"zu\\<parallel>v\" using M5exist_var  by blast\n  from kpp kq have \"k'\\<parallel>q \\<oplus> ((\\<exists>t. k'\\<parallel>t \\<and> t\\<parallel>q) \\<oplus> (\\<exists>t. k\\<parallel>t \\<and> t\\<parallel>p))\" (is \"?A \\<oplus> (?B \\<oplus> ?C)\") using M2 by blast \n  then have \"(?A\\<and>\\<not>?B\\<and>\\<not>?C)\\<or>(\\<not>?A\\<and>?B\\<and>\\<not>?C)\\<or>(\\<not>?A\\<and>\\<not>?B\\<and>?C)\"  using local.meets_atrans xor_distr_L[of ?A ?B ?C]  by blast\n  thus \"x \\<in> s \\<union> ov \\<union> d\"    \n  proof (elim disjE)\n    {assume \"(?A\\<and>\\<not>?B\\<and>\\<not>?C)\" then have \"?A\" by simp \n     then have \"(p,q) \\<in> s\" using  s qv kpp pzu zuv by blast\n     thus ?thesis using x by simp }\n    next\n    {assume \"(\\<not>?A\\<and>?B\\<and>\\<not>?C)\" then have \"?B\" by simp\n     then obtain t where kpt:\"k'\\<parallel>t\" and tq:\"t\\<parallel>q\" by auto\n     moreover from kq kl tq have \"t\\<parallel>l\" using M1 by blast\n     moreover from lz pz pzu have \"l\\<parallel>zu\" using M1 by blast\n     ultimately have \"(p,q) \\<in> ov\" using ov kpp qv pzu zuv by blast\n     thus ?thesis using x by simp}\n    next\n    {assume \"(\\<not>?A\\<and>\\<not>?B\\<and>?C)\" then have \"?C\" by simp\n     then obtain t where kt:\"k\\<parallel>t\" and tp:\"t\\<parallel>p\" by auto\n     with kq pzu zuv qv  have \"(p,q)\\<in>d\" using d by blast\n     thus ?thesis using x by simp}\n  qed\nqed\n\nlemma (in arelations) cmf:\"m O f \\<subseteq> s \\<union> ov \\<union> d\"\nproof\n  fix x::\"'a\\<times>'a\" assume a:\"x \\<in> m O f\" then obtain p q z where x:\"x =(p,q)\" and 1:\"(p,z) \\<in> m\" and 2:\"(z,q) \\<in> f\" by auto\n  then obtain k l u   where pz:\"p\\<parallel>z\" and kq:\"k\\<parallel>q\" and kl:\"k\\<parallel>l\" and lz:\"l\\<parallel>z\" and zu:\"z\\<parallel>u\" and qu:\"q\\<parallel>u\" using m f by blast\n  obtain k' where kpp:\"k'\\<parallel>p\" using M3 meets_wd pz by blast\n  from kpp kq have \"k'\\<parallel>q \\<oplus> ((\\<exists>t. k'\\<parallel>t \\<and> t\\<parallel>q) \\<oplus> (\\<exists>t. k\\<parallel>t \\<and> t\\<parallel>p))\" (is \"?A \\<oplus> (?B \\<oplus> ?C)\") using M2 by blast \n  then have \"(?A\\<and>\\<not>?B\\<and>\\<not>?C)\\<or>(\\<not>?A\\<and>?B\\<and>\\<not>?C)\\<or>(\\<not>?A\\<and>\\<not>?B\\<and>?C)\" using local.meets_atrans xor_distr_L[of ?A ?B ?C]  by blast\n  thus \"x \\<in> s \\<union> ov \\<union> d\"    \n  proof (elim disjE)\n    {assume \"(?A\\<and>\\<not>?B\\<and>\\<not>?C)\" then have \"?A\" by simp \n     then have \"(p,q) \\<in> s\" using  s qu kpp pz zu by blast\n     thus ?thesis using x by simp }\n    next\n    {assume \"(\\<not>?A\\<and>?B\\<and>\\<not>?C)\" then have \"?B\" by simp\n     then obtain t where kpt:\"k'\\<parallel>t\" and tq:\"t\\<parallel>q\" by auto\n     moreover from kq kl tq have \"t\\<parallel>l\" using M1 by blast \n     moreover from lz pz pz have \"l\\<parallel>z\" using M1 by blast\n     ultimately have \"(p,q) \\<in> ov\" using ov kpp qu pz zu by blast\n     thus ?thesis using x by simp}\n    next\n    {assume \"(\\<not>?A\\<and>\\<not>?B\\<and>?C)\" then have \"?C\" by simp\n     then obtain t where kt:\"k\\<parallel>t\" and tp:\"t\\<parallel>p\" by auto\n     with kq pz zu qu  have \"(p,q)\\<in>d\" using d by blast\n     thus ?thesis using x by simp}\n  qed\nqed\n\nlemma cmovi:\"m O ov^-1  \\<subseteq> s \\<union> ov \\<union> d\"\nproof \n  fix x::\"'a\\<times>'a\" assume a:\"x \\<in> m O ov^-1\" then obtain p q z where x:\"x =(p,q)\" and 1:\"(p,z) \\<in> m\" and 2:\"(z,q) \\<in> ov^-1\" by auto\n  then obtain k l c u v  where pz:\"p\\<parallel>z\" and kq:\"k\\<parallel>q\" and kl:\"k\\<parallel>l\" and lz:\"l\\<parallel>z\" and qu:\"q\\<parallel>u\" and uv:\"u\\<parallel>v\" and zv:\"z\\<parallel>v\" and lc:\"l\\<parallel>c\" and cu:\"c\\<parallel>u\" using m ov by blast\n  obtain k' where kpp:\"k'\\<parallel>p\" using M3 meets_wd pz by blast\n  from lz lc pz have pc:\"p\\<parallel>c\" using M1 by auto\n  from kpp kq have \"k'\\<parallel>q \\<oplus> ((\\<exists>t. k'\\<parallel>t \\<and> t\\<parallel>q) \\<oplus> (\\<exists>t. k\\<parallel>t \\<and> t\\<parallel>p))\" (is \"?A \\<oplus> (?B \\<oplus> ?C)\") using M2 by blast \n  then have \"(?A\\<and>\\<not>?B\\<and>\\<not>?C)\\<or>(\\<not>?A\\<and>?B\\<and>\\<not>?C)\\<or>(\\<not>?A\\<and>\\<not>?B\\<and>?C)\" by (insert xor_distr_L[of ?A ?B ?C], auto simp:elimmeets)\n  thus \"x \\<in> s \\<union> ov \\<union> d\"    \n  proof (elim disjE)\n    {assume \"(?A\\<and>\\<not>?B\\<and>\\<not>?C)\" then have \"?A\" by simp \n     then have \"(p,q) \\<in> s\" using s kpp qu cu pc by blast\n     thus ?thesis using x by simp }\n    next\n    {assume \"(\\<not>?A\\<and>?B\\<and>\\<not>?C)\" then have \"?B\" by simp\n     then obtain t where kpt:\"k'\\<parallel>t\" and tq:\"t\\<parallel>q\" by auto\n     moreover from kq kl tq have \"t\\<parallel>l\" using M1 by auto\n     ultimately have \"(p,q) \\<in> ov\" using ov kpp qu cu lc pc by blast\n     thus ?thesis using x by simp}\n    next\n    {assume \"(\\<not>?A\\<and>\\<not>?B\\<and>?C)\" then have \"?C\" by simp\n     then obtain t where kt:\"k\\<parallel>t\" and tp:\"t\\<parallel>p\" by auto\n     then  have \"(p,q)\\<in>d\" using d kq cu qu pc by blast\n     thus ?thesis using x by simp}\n  qed\nqed\n\nlemma covd:\"ov O d \\<subseteq> s \\<union> ov \\<union> d\"\nproof\n  fix x::\"'a\\<times>'a\" assume \"x \\<in> ov O d\" then obtain p q z where x:\"x=(p,q)\" and \"(p,z) \\<in> ov\" and \"(z,q) \\<in> d\" by auto\n  from \\<open>(p,z) \\<in> ov\\<close> obtain k u v l c where kp:\"k\\<parallel>p\" and pu:\"p\\<parallel>u\" and uv:\"u\\<parallel>v\" and zv:\"z\\<parallel>v\" and lc:\"l\\<parallel>c\" and cu:\"c\\<parallel>u\" and kl:\"k\\<parallel>l\" and lz:\"l\\<parallel>z\" and cu:\"c\\<parallel>u\" using ov by blast\n  from \\<open>(z,q) \\<in> d\\<close> obtain k' l' u' v' where kpq:\"k'\\<parallel>q\" and kplp:\"k'\\<parallel>l'\" and lpz:\"l'\\<parallel>z\" and qvp:\"q\\<parallel>v'\" and zup:\"z\\<parallel>u'\" and upvp:\"u'\\<parallel>v'\" using d by blast\n  from uv zv zup have \"u\\<parallel>u'\" using M1 by auto\n  from pu upvp obtain uu where puu:\"p\\<parallel>uu\" and uuvp:\"uu\\<parallel>v'\" using \\<open>u\\<parallel>u'\\<close> using M5exist_var by blast\n  from kp kpq have \"k\\<parallel>q \\<oplus> ((\\<exists>t. k\\<parallel>t \\<and> t\\<parallel>q) \\<oplus> (\\<exists>t. k'\\<parallel>t \\<and> t\\<parallel>p))\" (is \"?A \\<oplus> (?B \\<oplus> ?C)\") using M2 by blast\n  then have \"(?A\\<and>\\<not>?B\\<and>\\<not>?C) \\<or> ((\\<not>?A\\<and>?B\\<and>\\<not>?C) \\<or> (\\<not>?A\\<and>\\<not>?B\\<and>?C))\" by (insert xor_distr_L[of ?A ?B ?C], auto simp:elimmeets)\n  thus \"x \\<in>  s \\<union> ov \\<union> d\"\n  proof (elim disjE)\n    { assume \"?A\\<and>\\<not>?B\\<and>\\<not>?C\" then have ?A by simp\n      then have \"(p,q) \\<in> s\" using s kp qvp puu uuvp by blast\n      thus ?thesis using x by blast}\n    next\n    { assume \"\\<not>?A\\<and>?B\\<and>\\<not>?C\" then have ?B by simp\n      then obtain t where kt:\"k\\<parallel>t\" and tq:\"t\\<parallel>q\" by auto\n      from cu pu puu have \"c\\<parallel>uu\" using M1 by auto\n      moreover from kpq tq kplp have \"t\\<parallel>l'\" using M1 by auto\n      moreover from lpz lz lc have lpc:\"l'\\<parallel>c\" using M1 by auto\n      ultimately obtain lc where \"t\\<parallel>lc\" and \"lc\\<parallel>uu\" using M5exist_var by blast\n      then have \"(p,q) \\<in> ov\" using ov kp kt tq puu uuvp qvp  by blast\n      thus ?thesis using x by auto}\n    next\n    { assume \"\\<not>?A \\<and> \\<not>?B \\<and> ?C\" then have ?C by simp\n      then obtain t where \"k'\\<parallel>t\" and \"t\\<parallel>p\" by auto\n      with puu uuvp qvp kpq have \"(p,q) \\<in> d\" using d by blast\n      thus ?thesis using x by auto}\n  qed\nqed\n\n\nlemma covf:\"ov O f \\<subseteq> s \\<union> ov \\<union> d\"\nproof\n  fix x::\"'a\\<times>'a\" assume \"x \\<in> ov O f\" then obtain p q z where x:\"x=(p,q)\" and \"(p,z) \\<in> ov\" and \"(z,q) \\<in> f\" by auto\n  from \\<open>(p,z) \\<in> ov\\<close> obtain k u v l c where kp:\"k\\<parallel>p\" and pu:\"p\\<parallel>u\" and uv:\"u\\<parallel>v\" and zv:\"z\\<parallel>v\" and lc:\"l\\<parallel>c\" and cu:\"c\\<parallel>u\" and kl:\"k\\<parallel>l\" and lz:\"l\\<parallel>z\" and cu:\"c\\<parallel>u\" using ov by blast\n  from \\<open>(z,q) \\<in> f\\<close> obtain k' l' u'  where kpq:\"k'\\<parallel>q\" and kplp:\"k'\\<parallel>l'\" and lpz:\"l'\\<parallel>z\" and qup:\"q\\<parallel>u'\" and zup:\"z\\<parallel>u'\" using f by blast\n  from uv zv zup have uu:\"u\\<parallel>u'\" using M1 by auto\n  from kp kpq have \"k\\<parallel>q \\<oplus> ((\\<exists>t. k\\<parallel>t \\<and> t\\<parallel>q) \\<oplus> (\\<exists>t. k'\\<parallel>t \\<and> t\\<parallel>p))\" (is \"?A \\<oplus> (?B \\<oplus> ?C)\") using M2 by blast\n  then have \"(?A\\<and>\\<not>?B\\<and>\\<not>?C) \\<or> ((\\<not>?A\\<and>?B\\<and>\\<not>?C) \\<or> (\\<not>?A\\<and>\\<not>?B\\<and>?C))\" by (insert xor_distr_L[of ?A ?B ?C], auto simp:elimmeets)\n  thus \"x \\<in>  s \\<union> ov \\<union> d\"\n  proof (elim disjE)\n    { assume \"?A\\<and>\\<not>?B\\<and>\\<not>?C\" then have ?A by simp\n      then have \"(p,q) \\<in> s\" using s kp qup uu pu by blast\n      thus ?thesis using x by blast}\n    next\n    { assume \"\\<not>?A\\<and>?B\\<and>\\<not>?C\" then have ?B by simp\n      then obtain t where kt:\"k\\<parallel>t\" and tq:\"t\\<parallel>q\" by auto\n      moreover from kpq tq kplp have \"t\\<parallel>l'\" using M1 by auto\n      moreover from lpz lz lc have lpc:\"l'\\<parallel>c\" using M1 by auto\n      ultimately obtain lc where \"t\\<parallel>lc\" and \"lc\\<parallel>u\" using cu M5exist_var by blast\n      then have \"(p,q) \\<in> ov\" using ov kp kt tq pu uu qup  by blast\n      thus ?thesis using x by auto}\n    next\n    { assume \"\\<not>?A \\<and> \\<not>?B \\<and> ?C\" then have ?C by simp\n      then obtain t where \"k'\\<parallel>t\" and \"t\\<parallel>p\" by auto\n      with pu uu qup kpq have \"(p,q) \\<in> d\" using d by blast\n      thus ?thesis using x by auto}\n  qed\nqed\n\nlemma cfid:\"f^-1 O d \\<subseteq> s \\<union> ov \\<union> d\"\nproof\n  fix x::\"'a\\<times>'a\" assume \"x \\<in> f^-1 O d\" then obtain p q z where x:\"x = (p,q)\" and \"(p,z) \\<in> f^-1\" and \"(z,q)\\<in> d\" by auto\n  from \\<open>(p,z) \\<in> f^-1\\<close> obtain k l u where \"k\\<parallel>l\" and \"l\\<parallel>z\" and kp:\"k\\<parallel>p\" and pu:\"p\\<parallel>u\" and zu:\"z\\<parallel>u\" using f by blast\n  from \\<open>(z,q) \\<in> d\\<close> obtain k' l' u' v where kplp:\"k'\\<parallel>l'\" and kpq:\"k'\\<parallel>q\" and lpz:\"l'\\<parallel>z\" and zup:\"z\\<parallel>u'\" and upv:\"u'\\<parallel>v\" and qv:\"q\\<parallel>v\" using d by blast\n  from pu zu zup have pup:\"p\\<parallel>u'\" using M1 by blast\n  from kp kpq have \"k\\<parallel>q \\<oplus> ((\\<exists>t. k\\<parallel>t \\<and> t\\<parallel>q) \\<oplus> (\\<exists>t. k'\\<parallel>t \\<and> t\\<parallel>p))\" (is \"?A \\<oplus> (?B \\<oplus> ?C)\") using M2 by blast\n  then have \"(?A\\<and>\\<not>?B\\<and>\\<not>?C) \\<or> ((\\<not>?A\\<and>?B\\<and>\\<not>?C) \\<or> (\\<not>?A\\<and>\\<not>?B\\<and>?C))\" by (insert xor_distr_L[of ?A ?B ?C], auto simp:elimmeets)\n  thus \"x \\<in> s \\<union> ov \\<union> d\"\n  proof (elim disjE)\n    { assume \"?A\\<and>\\<not>?B\\<and>\\<not>?C\" then have ?A by simp\n      with pup upv kp qv have \"(p,q) \\<in> s\" using s by blast\n      thus ?thesis using x by auto}\n    next\n    { assume \"\\<not>?A\\<and>?B\\<and>\\<not>?C\" then have ?B by simp\n      then obtain t where kt:\"k\\<parallel>t\" and tq:\"t\\<parallel>q\" by auto\n      from tq kpq kplp have \"t\\<parallel>l'\" using M1 by blast\n      with lpz zup obtain lpz where \"t\\<parallel>lpz\" and \"lpz\\<parallel>u'\" using M5exist_var by blast\n      with kp pup upv kt tq qv have \"(p,q)\\<in>ov\" using ov by blast\n      thus ?thesis using x by blast}\n       next\n    { assume \"\\<not>?A \\<and> \\<not>?B \\<and> ?C\" then have ?C by simp\n      then obtain t where \"k'\\<parallel>t\" and \"t\\<parallel>p\" by auto\n      with pup upv kpq qv have \"(p,q) \\<in> d\" using d by blast\n      thus ?thesis using x by auto}\n    qed\nqed\n\nlemma cfov:\"f O ov \\<subseteq> ov \\<union> s \\<union> d\"\nproof\n    fix x::\"'a\\<times>'a\" assume \"x \\<in> f O ov\" then obtain p q z where x:\"x = (p,q)\" and \"(p,z) \\<in> f\" and \"(z,q)\\<in> ov\" by auto\n    from \\<open>(p,z) \\<in> f\\<close> obtain  k l u where \"k\\<parallel>l\" and kz:\"k\\<parallel>z\" and lp:\"l\\<parallel>p\" and pu:\"p\\<parallel>u\" and zu:\"z\\<parallel>u\" using f by blast\n    from \\<open>(z,q) \\<in> ov\\<close> obtain k' l' c  u' v where \"k'\\<parallel>l'\" and kpz:\"k'\\<parallel>z\" and lpq:\"l'\\<parallel> q\" and  zup:\"z\\<parallel>u'\" and upv:\"u'\\<parallel>v\" and qv:\"q\\<parallel>v\" and lpc:\"l'\\<parallel>c\" and cup:\"c\\<parallel>u'\"  using  ov by blast\n    from pu zu zup have pup:\"p\\<parallel>u'\" using M1 by blast\n    from lp lpq have \"l\\<parallel>q \\<oplus> ((\\<exists>t. l\\<parallel>t \\<and> t\\<parallel>q) \\<oplus> (\\<exists>t. l'\\<parallel>t \\<and> t\\<parallel>p))\" (is \"?A \\<oplus> (?B \\<oplus> ?C)\") using M2 by blast\n    then have \"(?A\\<and>\\<not>?B\\<and>\\<not>?C) \\<or> ((\\<not>?A\\<and>?B\\<and>\\<not>?C) \\<or> (\\<not>?A\\<and>\\<not>?B\\<and>?C))\" by (insert xor_distr_L[of ?A ?B ?C], auto simp:elimmeets)\n    thus \"x \\<in> ov \\<union> s \\<union> d\"\n    proof (elim disjE)\n      { assume \"?A\\<and>\\<not>?B\\<and>\\<not>?C\" then have ?A by simp\n        with  lp pup upv qv have \"(p,q) \\<in> s\" using s by blast\n        thus ?thesis using x by auto}\n      next\n      { assume \"\\<not>?A\\<and>?B\\<and>\\<not>?C\" then have ?B by simp\n      then obtain t where lt:\"l\\<parallel>t\" and tq:\"t\\<parallel>q\" by auto\n      from tq lpq lpc have \"t\\<parallel>c\" using M1 by blast\n      with lp lt tq pup upv qv cup have \"(p,q)\\<in>ov\" using ov by blast\n      thus ?thesis using x by blast}\n      next\n      { assume \"\\<not>?A \\<and> \\<not>?B \\<and> ?C\" then have ?C by simp\n      then obtain t where \"l'\\<parallel>t\" and \"t\\<parallel>p\" by auto\n      with lpq pup upv qv have \"(p,q) \\<in> d\" using d by blast\n      thus ?thesis using x by auto}\n    qed\nqed\n\n(* ========= $\\alpha_2$ composition ========== *)\ntext \\<open>We prove compositions of the form $r_1 \\circ r_2 \\subseteq ov \\cup f^{-1} \\cup d^{-1}$.\\<close>\n\nlemma covsi:\"ov O s^-1 \\<subseteq> ov \\<union> f^-1 \\<union> d^-1\"\nproof\n    fix x::\"'a\\<times>'a\" assume \"x \\<in> ov O s^-1\" then obtain p q z where x:\"x = (p,q)\" and \"(p,z) \\<in> ov\" and \"(z,q) \\<in> s^-1\" by auto\n    from \\<open>(p,z) \\<in> ov\\<close> obtain k l c u  where kp:\"k\\<parallel>p\" and pu:\"p\\<parallel>u\" and kl:\"k\\<parallel>l\" and lz:\"l\\<parallel>z\" and lc:\"l\\<parallel>c\" and cu:\"c\\<parallel>u\" using ov by blast\n    from \\<open>(z,q) \\<in> s^-1\\<close> obtain k' u' v' where kpz:\"k'\\<parallel>z\" and kpq:\"k'\\<parallel>q\" and kpz:\"k'\\<parallel>z\" and  zup:\"z\\<parallel>u'\"  and qvp:\"q\\<parallel>v'\" using s by blast\n    from lz kpz kpq have lq:\"l\\<parallel>q\" using M1 by blast\n    from pu qvp have \"p\\<parallel>v' \\<oplus> ((\\<exists>t. p\\<parallel>t \\<and> t\\<parallel>v') \\<oplus> (\\<exists>t. q\\<parallel>t \\<and> t\\<parallel>u))\" (is \"?A \\<oplus> (?B \\<oplus> ?C)\") using M2 by blast\n    then have \"(?A\\<and>\\<not>?B\\<and>\\<not>?C) \\<or> ((\\<not>?A\\<and>?B\\<and>\\<not>?C) \\<or> (\\<not>?A\\<and>\\<not>?B\\<and>?C))\" by (insert xor_distr_L[of ?A ?B ?C], auto simp:elimmeets)\n    thus \"x \\<in> ov \\<union> f^-1 \\<union> d^-1\"\n    proof (elim disjE)\n      { assume \"?A\\<and>\\<not>?B\\<and>\\<not>?C\" then have ?A by simp\n        with qvp kp kl lq have \"(p,q) \\<in> f^-1\" using f by blast\n        thus ?thesis using x by auto}\n      next\n      { assume \"\\<not>?A\\<and>?B\\<and>\\<not>?C\" then have ?B by simp \n        then obtain t where ptp:\"p\\<parallel>t\" and \"t\\<parallel>v'\" by auto\n        moreover with pu cu have \"c\\<parallel>t\" using M1 by blast\n        ultimately have \"(p,q)\\<in> ov\" using kp kl lc cu lq qvp  ov by blast\n        thus ?thesis using x by auto}        \n     next\n      { assume \"\\<not>?A \\<and> \\<not>?B \\<and> ?C\" then have ?C by simp\n        then obtain t where qt:\"q\\<parallel>t\" and \"t\\<parallel>u\" by auto\n        with kp kl lq pu  have \"(p,q) \\<in> d^-1\" using d by blast \n        thus ?thesis using x by auto}\n      qed\nqed\n\n\nlemma cdim:\"d^-1 O m \\<subseteq>  ov \\<union> d^-1 \\<union> f^-1\"\nproof \n    fix x::\"'a\\<times>'a\" assume \"x \\<in> d^-1 O m\" then obtain p q z where x:\"x = (p,q)\" and \"(p,z) \\<in> d^-1\" and \"(z,q) \\<in> m\" by auto\n    from \\<open>(p,z) \\<in> d^-1\\<close> obtain k l u v where kp:\"k\\<parallel>p\" and pv:\"p\\<parallel>v\" and kl:\"k\\<parallel>l\" and lz:\"l\\<parallel>z\" and zu:\"z\\<parallel>u\" and uv:\"u\\<parallel>v\" using d by blast\n    from \\<open>(z,q) \\<in> m\\<close>  have zq:\"z\\<parallel>q\" using m by blast\n    obtain v' where qvp:\"q\\<parallel>v'\" using M3 meets_wd zq by blast\n    from kl lz zq obtain lz where klz:\"k\\<parallel>lz\" and lzq:\"lz\\<parallel>q\" using M5exist_var  by blast\n    from pv qvp have \"p\\<parallel>v' \\<oplus> ((\\<exists>t. p\\<parallel>t \\<and> t\\<parallel>v') \\<oplus> (\\<exists>t. q\\<parallel>t \\<and> t\\<parallel>v))\" (is \"?A \\<oplus> (?B \\<oplus> ?C)\") using M2 by blast\n    then have \"(?A\\<and>\\<not>?B\\<and>\\<not>?C) \\<or> ((\\<not>?A\\<and>?B\\<and>\\<not>?C) \\<or> (\\<not>?A\\<and>\\<not>?B\\<and>?C))\" by (insert xor_distr_L[of ?A ?B ?C], auto simp:elimmeets)\n    thus \"x \\<in>  ov \\<union> d^-1 \\<union> f^-1\"\n    proof (elim disjE)\n      { assume \"?A\\<and>\\<not>?B\\<and>\\<not>?C\" then have ?A by simp\n        with qvp kp klz lzq\\<open>?A\\<close> have \"(p,q) \\<in> f^-1\" using f by blast\n        thus ?thesis using x by auto}\n      next\n      { assume \"\\<not>?A\\<and>?B\\<and>\\<not>?C\" then have ?B by simp \n        then obtain t where pt:\"p\\<parallel>t\" and tvp:\"t\\<parallel>v'\" by auto\n        from zq lzq zu have \"lz\\<parallel>u\" using M1 by auto\n        moreover from pt pv uv have \"u\\<parallel>t\" using M1 by auto\n        ultimately have \"(p,q)\\<in> ov\" using kp klz lzq pt tvp qvp ov by blast\n        thus ?thesis using x by auto}        \n     next\n      { assume \"\\<not>?A \\<and> \\<not>?B \\<and> ?C\" then have ?C by simp\n        then obtain t where qt:\"q\\<parallel>t\" and \"t\\<parallel>v\" by auto\n        with kp klz lzq pv have \"(p,q) \\<in> d^-1\" using d by blast \n        thus ?thesis using x by auto}\n      qed\nqed\n\nlemma cdiov:\"d^-1 O ov \\<subseteq> ov \\<union> f^-1 \\<union> d^-1\"\nproof\n    fix x::\"'a\\<times>'a\" assume \"x \\<in> d^-1 O ov\" then obtain p q r where x:\"x = (p,r)\" and \"(p,q) \\<in> d^-1\" and \"(q,r) \\<in> ov\" by auto\n    from \\<open>(p,q) \\<in> d^-1\\<close> obtain u v k l  where kp:\"k\\<parallel>p\" and pv:\"p\\<parallel>v\" and kl:\"k\\<parallel>l\" and lq:\"l\\<parallel>q\"  and qu:\"q\\<parallel>u\" and uv:\"u\\<parallel>v\" using d by blast\n    from \\<open>(q,r) \\<in> ov\\<close> obtain k' l' t u' v' where lpr:\"l'\\<parallel>r\" and kpq:\"k'\\<parallel>q\" and kplp:\"k'\\<parallel>l'\" and qup:\"q\\<parallel>u'\" and \"u'\\<parallel>v'\" and rvp:\"r\\<parallel>v'\" and lpt:\"l'\\<parallel>t\" and tup:\"t\\<parallel>u'\" using ov by blast\n    from lq kplp kpq have \"l\\<parallel>l'\" using M1 by blast\n    with kl lpr  obtain ll where  kll:\"k\\<parallel>ll\" and llr:\"ll\\<parallel>r\"  using M5exist_var by blast\n    from pv rvp have \"p\\<parallel>v' \\<oplus> ((\\<exists>t'. p\\<parallel>t' \\<and> t'\\<parallel>v') \\<oplus> (\\<exists>t'. r\\<parallel>t' \\<and> t'\\<parallel>v))\" (is \"?A \\<oplus> (?B \\<oplus> ?C)\") using M2 by blast\n    then have \"(?A\\<and>\\<not>?B\\<and>\\<not>?C) \\<or> ((\\<not>?A\\<and>?B\\<and>\\<not>?C) \\<or> (\\<not>?A\\<and>\\<not>?B\\<and>?C))\" by (insert xor_distr_L[of ?A ?B ?C], auto simp:elimmeets)\n    thus \"x \\<in> ov \\<union> f^-1 \\<union> d^-1\"\n    proof (elim disjE)\n      { assume \"?A\\<and>\\<not>?B\\<and>\\<not>?C\" then have ?A by simp\n        with rvp llr kp kll have \"(p,r) \\<in> f^-1\" using f by blast\n        thus ?thesis using x by auto}\n      next\n      { assume \"\\<not>?A\\<and>?B\\<and>\\<not>?C\" then have ?B by simp \n        then obtain t' where ptp:\"p\\<parallel>t'\" and tpvp:\"t'\\<parallel>v'\" by auto\n        moreover from lpt lpr llr have llt:\"ll\\<parallel>t\" using M1 by blast\n        moreover from ptp uv pv have utp:\"u\\<parallel>t'\" using M1 by blast\n        moreover from qu tup qup have \"t\\<parallel>u\" using M1 by blast\n        moreover with utp llt obtain tu where \"ll\\<parallel>tu\" and \"tu\\<parallel>t'\" using M5exist_var by blast\n        with kp ptp tpvp kll llr rvp  have \"(p,r)\\<in> ov\" using  ov by blast\n        thus ?thesis using x by auto}        \n     next\n      { assume \"\\<not>?A \\<and> \\<not>?B \\<and> ?C\" then have ?C by simp\n        then obtain t' where rtp:\"r\\<parallel>t'\" and \"t'\\<parallel>v\" by auto\n        with kll llr kp pv have \"(p,r) \\<in> d^-1\" using d by blast \n        thus ?thesis using x by auto}\n      qed\nqed\n\nlemma cdis:\"d^-1 O s \\<subseteq> ov \\<union> f^-1 \\<union> d^-1\"\nproof\n  fix x::\"'a\\<times>'a\" assume \"x \\<in> d^-1 O s\" then obtain p q z where x:\"x = (p,q)\" and \"(p,z) \\<in> d^-1\" and \"(z,q) \\<in> s\" by auto\n  from \\<open>(p,z)\\<in>d^-1\\<close> obtain k l u v where kl:\"k\\<parallel>l\" and lz:\"l\\<parallel>z\" and kp:\"k\\<parallel>p\" and zu:\"z\\<parallel>u\" and uv:\"u\\<parallel>v\" and pv:\"p\\<parallel>v\" using d by blast\n  from \\<open>(z,q) \\<in> s\\<close> obtain l'  v' where lpz:\"l'\\<parallel>z\" and lpq:\"l'\\<parallel>q\" and qvp:\"q\\<parallel>v'\" using s by blast\n  from lz lpz lpq have lq:\"l\\<parallel>q\" using M1 by blast\n  from pv qvp have \"p\\<parallel>v' \\<oplus> ((\\<exists>t. p\\<parallel>t \\<and> t\\<parallel>v') \\<oplus> (\\<exists>t. q\\<parallel>t \\<and> t\\<parallel>v))\" (is \"?A \\<oplus> (?B \\<oplus> ?C)\") using M2 by blast\n  then have \"(?A\\<and>\\<not>?B\\<and>\\<not>?C) \\<or> ((\\<not>?A\\<and>?B\\<and>\\<not>?C) \\<or> (\\<not>?A\\<and>\\<not>?B\\<and>?C))\" by (insert xor_distr_L[of ?A ?B ?C], auto simp:elimmeets)\n  thus \"x \\<in> ov \\<union> f^-1 \\<union> d^-1\"\n    proof (elim disjE)\n      { assume \"?A\\<and>\\<not>?B\\<and>\\<not>?C\" then have ?A by simp\n        with kl lq qvp kp have \"(p,q) \\<in> f^-1\" using f by blast\n        thus ?thesis using x by auto}\n      next\n      { assume \"\\<not>?A\\<and>?B\\<and>\\<not>?C\" then have ?B by simp \n        then obtain t where pt:\"p\\<parallel>t\" and tvp:\"t\\<parallel>v'\" by auto\n        from pt pv uv have \"u\\<parallel>t\" using M1 by blast\n        with lz zu obtain zu where \"l\\<parallel>zu\" and \"zu\\<parallel>t\" using M5exist_var by blast\n        with kp pt tvp kl lq qvp have \"(p,q) \\<in> ov\" using ov by blast\n        thus ?thesis using x by auto}\n      next\n      { assume \"\\<not>?A \\<and> \\<not>?B \\<and> ?C\" then have ?C by simp\n        then obtain t where \"q\\<parallel>t\" and \"t\\<parallel>v\" by auto\n        with kl lq kp pv have \"(p,q)\\<in>d^-1\" using d by blast\n        thus ?thesis using x by auto}\n      qed\nqed\n\nlemma csim:\"s^-1 O m \\<subseteq> ov \\<union> f^-1 \\<union> d^-1\"\nproof \n  fix x::\"'a\\<times>'a\" assume \"x \\<in> s^-1 O m\" then obtain p q z where x:\"x = (p,q)\" and \"(p,z) \\<in> s^-1\" and \"(z,q) \\<in> m\" by auto\n  from \\<open>(p,z)\\<in>s^-1\\<close> obtain k u v where kp:\"k\\<parallel>p\" and kz:\"k\\<parallel>z\" and zu:\"z\\<parallel>u\" and uv:\"u\\<parallel>v\" and pv:\"p\\<parallel>v\" using s by blast\n  from \\<open>(z,q) \\<in> m\\<close> have zq:\"z\\<parallel>q\" using m by auto\n  obtain v' where qvp:\"q\\<parallel>v'\" using M3 meets_wd zq by blast\n  from pv qvp have \"p\\<parallel>v' \\<oplus> ((\\<exists>t. p\\<parallel>t \\<and> t\\<parallel>v') \\<oplus> (\\<exists>t. q\\<parallel>t \\<and> t\\<parallel>v))\" (is \"?A \\<oplus> (?B \\<oplus> ?C)\") using M2 by blast\n  then have \"(?A\\<and>\\<not>?B\\<and>\\<not>?C) \\<or> ((\\<not>?A\\<and>?B\\<and>\\<not>?C) \\<or> (\\<not>?A\\<and>\\<not>?B\\<and>?C))\" by (insert xor_distr_L[of ?A ?B ?C], auto simp:elimmeets)\n  thus \"x \\<in> ov \\<union> f^-1 \\<union> d^-1\"\n    proof (elim disjE)\n      { assume \"?A\\<and>\\<not>?B\\<and>\\<not>?C\" then have ?A by simp\n        with kp kz zq qvp have \"(p,q) \\<in> f^-1\" using f by blast\n        thus ?thesis using x by auto}\n      next\n      { assume \"\\<not>?A\\<and>?B\\<and>\\<not>?C\" then have ?B by simp \n        then obtain t where pt:\"p\\<parallel>t\" and tvp:\"t\\<parallel>v'\" by auto\n        from pt pv uv have \"u\\<parallel>t\" using M1 by blast\n        with kp pt tvp kz zq qvp zu  have \"(p,q) \\<in> ov\" using ov by blast\n        thus ?thesis using x by auto}\n      next\n      { assume \"\\<not>?A \\<and> \\<not>?B \\<and> ?C\" then have ?C by simp\n        then obtain t where \"q\\<parallel>t\" and \"t\\<parallel>v\" by auto\n        with kp kz zq pv have \"(p,q)\\<in>d^-1\" using d by blast\n        thus ?thesis using x by auto}\n      qed\nqed\n \nlemma csiov:\"s^-1 O ov \\<subseteq> ov \\<union> f^-1 \\<union> d^-1\"\nproof \n  fix x::\"'a\\<times>'a\" assume \"x \\<in> s^-1 O ov\" then obtain p q z where x:\"x = (p,q)\" and \"(p,z) \\<in> s^-1\" and \"(z,q) \\<in> ov\" by auto\n  from \\<open>(p,z)\\<in>s^-1\\<close> obtain k u v where kp:\"k\\<parallel>p\" and kz:\"k\\<parallel>z\" and zu:\"z\\<parallel>u\" and uv:\"u\\<parallel>v\" and pv:\"p\\<parallel>v\" using s by blast\n  from \\<open>(z,q) \\<in> ov\\<close> obtain k' l' u' v' c where kpz:\"k'\\<parallel>z\" and zup:\"z\\<parallel>u'\" and upvp:\"u'\\<parallel>v'\" and kplp:\"k'\\<parallel>l'\" and lpq:\"l'\\<parallel>q\" and qvp:\"q\\<parallel>v'\" and lpc:\"l'\\<parallel>c\" and cup:\"c\\<parallel>u'\" using ov by blast\n  from kz kpz kplp have klp:\"k\\<parallel>l'\" using M1 by auto\n  from pv qvp have \"p\\<parallel>v' \\<oplus> ((\\<exists>t. p\\<parallel>t \\<and> t\\<parallel>v') \\<oplus> (\\<exists>t. q\\<parallel>t \\<and> t\\<parallel>v))\" (is \"?A \\<oplus> (?B \\<oplus> ?C)\") using M2 by blast\n  then have \"(?A\\<and>\\<not>?B\\<and>\\<not>?C) \\<or> ((\\<not>?A\\<and>?B\\<and>\\<not>?C) \\<or> (\\<not>?A\\<and>\\<not>?B\\<and>?C))\" by (insert xor_distr_L[of ?A ?B ?C], auto simp:elimmeets)\n  thus \"x \\<in> ov \\<union> f^-1 \\<union> d^-1\"\n    proof (elim disjE)\n      { assume \"?A\\<and>\\<not>?B\\<and>\\<not>?C\" then have ?A by simp\n        with kp kplp lpq qvp klp have \"(p,q) \\<in> f^-1\" using f by blast\n        thus ?thesis using x by auto}\n      next\n      { assume \"\\<not>?A\\<and>?B\\<and>\\<not>?C\" then have ?B by simp \n        then obtain t where pt:\"p\\<parallel>t\" and tvp:\"t\\<parallel>v'\" by auto\n        from pt pv uv have \"u\\<parallel>t\" using M1 by blast\n        moreover from cup zup zu have cu:\"c\\<parallel>u\" using M1 by auto\n        ultimately obtain cu where \"l'\\<parallel>cu\" and \"cu\\<parallel>t\" using lpc M5exist_var by blast\n        with kp pt tvp klp lpq qvp have \"(p,q) \\<in> ov\" using ov by blast\n        thus ?thesis using x by auto}\n      next\n      { assume \"\\<not>?A \\<and> \\<not>?B \\<and> ?C\" then have ?C by simp\n        then obtain t where \"q\\<parallel>t\" and \"t\\<parallel>v\" by auto\n        with kp klp lpq pv have \"(p,q)\\<in>d^-1\" using d by blast\n        thus ?thesis using x by auto}\n      qed\nqed\n\nlemma covim:\"ov^-1 O m \\<subseteq> ov \\<union> f^-1 \\<union> d^-1\"\nproof\n    fix x::\"'a\\<times>'a\" assume \"x \\<in> ov^-1 O m\" then obtain p q z where x:\"x = (p,q)\" and \"(p,z) \\<in> ov^-1\" and \"(z,q) \\<in> m\" by auto\n    from \\<open>(p,z) \\<in> ov^-1\\<close> obtain k l c u v  where kz:\"k\\<parallel>z\" and zu:\"z\\<parallel>u\" and kl:\"k\\<parallel>l\" and lp:\"l\\<parallel>p\" and lc:\"l\\<parallel>c\" and cu:\"c\\<parallel>u\" and pv:\"p\\<parallel>v\" and uv:\"u\\<parallel>v\" using ov by blast\n    from \\<open>(z,q) \\<in> m\\<close>  have zq:\"z\\<parallel>q\" using m by auto\n    obtain v' where qvp:\"q\\<parallel>v'\" using M3 meets_wd zq by blast\n    from zu zq cu have cq:\"c\\<parallel>q\" using M1 by blast\n    from pv qvp have \"p\\<parallel>v' \\<oplus> ((\\<exists>t. p\\<parallel>t \\<and> t\\<parallel>v') \\<oplus> (\\<exists>t. q\\<parallel>t \\<and> t\\<parallel>v))\" (is \"?A \\<oplus> (?B \\<oplus> ?C)\") using M2 by blast\n    then have \"(?A\\<and>\\<not>?B\\<and>\\<not>?C) \\<or> ((\\<not>?A\\<and>?B\\<and>\\<not>?C) \\<or> (\\<not>?A\\<and>\\<not>?B\\<and>?C))\" by (insert xor_distr_L[of ?A ?B ?C], auto simp:elimmeets)\n    thus \"x \\<in> ov \\<union> f^-1 \\<union> d^-1\"\n    proof (elim disjE)\n      { assume \"?A\\<and>\\<not>?B\\<and>\\<not>?C\" then have ?A by simp\n        with lp lc cq qvp have \"(p,q) \\<in> f^-1\" using f by blast\n        thus ?thesis using x by auto}\n      next\n      { assume \"\\<not>?A\\<and>?B\\<and>\\<not>?C\" then have ?B by simp \n        then obtain t where ptp:\"p\\<parallel>t\" and \"t\\<parallel>v'\" by auto\n        moreover with pv uv have \"u\\<parallel>t\" using M1 by blast\n        ultimately have \"(p,q)\\<in> ov\" using lp lc cq qvp cu ov by blast\n        thus ?thesis using x by auto}        \n     next\n      { assume \"\\<not>?A \\<and> \\<not>?B \\<and> ?C\" then have ?C by simp\n        then obtain t where qt:\"q\\<parallel>t\" and \"t\\<parallel>v\" by auto\n        with lp lc cq pv have \"(p,q) \\<in> d^-1\" using d by blast \n        thus ?thesis using x by auto}\n      qed\nqed\n\n(* =========$\\alpha_3$ compositions========== *)\ntext \\<open>We prove compositions of the form $r_1 \\circ r_2 \\subseteq b \\cup m \\cup ov$.\\<close>\n\nlemma covov:\"ov O ov \\<subseteq> b \\<union> m \\<union> ov\"\nproof\n   fix x::\"'a\\<times>'a\" assume \"x \\<in> ov O ov\" then obtain p q z where x:\"x = (p,q)\" and \"(p,z) \\<in> ov\" and \"(z,q)\\<in> ov\" by auto\n   from \\<open>(p,z) \\<in> ov\\<close> obtain k u l t v where kp:\"k\\<parallel>p\" and pu:\"p\\<parallel>u\" and kl:\"k\\<parallel>l\" and lz:\"l\\<parallel>z\" and \"l\\<parallel>t\" and \"t\\<parallel>u\" and uv:\"u\\<parallel>v\" and zv:\"z\\<parallel>v\" using ov by blast\n   from  \\<open>(z,q) \\<in> ov\\<close> obtain k' l' y u' v' where kplp:\"k'\\<parallel>l'\" and kpz:\"k'\\<parallel>z\" and lpq:\"l'\\<parallel>q\" and lpy:\"l'\\<parallel>y\" and \"y\\<parallel>u'\" and zup:\"z\\<parallel>u'\" and upvp:\"u'\\<parallel>v'\" and qvp:\"q\\<parallel>v'\" using ov by blast\n   from lz kplp kpz have llp:\"l\\<parallel>l'\" using M1 by blast\n   from uv zv zup have \"u\\<parallel>u'\" using M1 by blast\n   with pu upvp obtain uu where puu:\"p\\<parallel>uu\" and uuv:\"uu\\<parallel>v'\" using M5exist_var by blast\n   from puu lpq have \"p\\<parallel>q \\<oplus> ((\\<exists>t'. p\\<parallel>t' \\<and> t'\\<parallel>q) \\<oplus> (\\<exists>t'. l'\\<parallel>t' \\<and> t'\\<parallel>uu))\" (is \"?A \\<oplus> (?B \\<oplus> ?C)\") using M2 by blast\n    then have \"(?A\\<and>\\<not>?B\\<and>\\<not>?C) \\<or> ((\\<not>?A\\<and>?B\\<and>\\<not>?C) \\<or> (\\<not>?A\\<and>\\<not>?B\\<and>?C))\" by (insert xor_distr_L[of ?A ?B ?C], auto simp:elimmeets)\n    thus \"x \\<in> b \\<union> m \\<union> ov\"\n    proof (elim disjE)\n      { assume \"?A\\<and>\\<not>?B\\<and>\\<not>?C\" then have ?A by simp\n        then have \"(p,q) \\<in> m\" using m by auto\n        thus ?thesis using x by auto}\n      next\n      { assume \"\\<not>?A\\<and>?B\\<and>\\<not>?C\" then have ?B by simp \n        then have \"(p,q) \\<in> b\" using b by auto\n        thus ?thesis using x by auto}\n     next\n      { assume \"\\<not>?A \\<and> \\<not>?B \\<and> ?C\" then have ?C by simp\n        then obtain t' where lptp:\"l'\\<parallel>t'\" and \"t'\\<parallel>uu\" by auto\n        from kl llp lpq obtain ll where  kll:\"k\\<parallel>ll\" and llq:\"ll\\<parallel>q\" using M5exist_var by blast\n        with lpq lptp  have \"ll\\<parallel>t'\" using M1 by blast\n        with kp puu uuv kll llq qvp \\<open>t'\\<parallel>uu\\<close> have \"(p,q) \\<in> ov\" using ov by blast\n        thus ?thesis using x by auto}\n      qed\nqed\n\nlemma covfi:\"ov O f^-1 \\<subseteq> b \\<union> m \\<union> ov\"\nproof\n   fix x::\"'a\\<times>'a\" assume \"x \\<in> ov O f^-1\" then obtain p q z where x:\"x = (p,q)\" and \"(p,z) \\<in> ov\" and \"(z,q)\\<in> f^-1\" by auto\n   from \\<open>(p,z) \\<in> ov\\<close> obtain k u l c v where kp:\"k\\<parallel>p\" and pu:\"p\\<parallel>u\" and kl:\"k\\<parallel>l\" and lz:\"l\\<parallel>z\" and \"l\\<parallel>c\" and \"c\\<parallel>u\" and uv:\"u\\<parallel>v\" and zv:\"z\\<parallel>v\" using ov by blast\n   from  \\<open>(z,q) \\<in> f^-1\\<close> obtain k' l' v'  where kplp:\"k'\\<parallel>l'\" and kpz:\"k'\\<parallel>z\" and lpq:\"l'\\<parallel>q\"  and qvp:\"q\\<parallel>v'\" and zvp:\"z\\<parallel>v'\" using f by blast\n   from lz kplp kpz have llp:\"l\\<parallel>l'\" using M1 by blast\n   from  zv qvp zvp have qv:\"q\\<parallel>v\" using M1 by blast\n   from pu lpq have \"p\\<parallel>q \\<oplus> ((\\<exists>t. p\\<parallel>t \\<and> t\\<parallel>q) \\<oplus> (\\<exists>t. l'\\<parallel>t \\<and> t\\<parallel>u))\" (is \"?A \\<oplus> (?B \\<oplus> ?C)\") using M2 by blast\n    then have \"(?A\\<and>\\<not>?B\\<and>\\<not>?C) \\<or> ((\\<not>?A\\<and>?B\\<and>\\<not>?C) \\<or> (\\<not>?A\\<and>\\<not>?B\\<and>?C))\" by (insert xor_distr_L[of ?A ?B ?C], auto simp:elimmeets)\n    thus \"x \\<in> b \\<union> m \\<union> ov\"\n    proof (elim disjE)\n      { assume \"?A\\<and>\\<not>?B\\<and>\\<not>?C\" then have ?A by simp\n        then have \"(p,q) \\<in> m\" using m by auto\n        thus ?thesis using x by auto}\n      next\n      { assume \"\\<not>?A\\<and>?B\\<and>\\<not>?C\" then have ?B by simp \n        then have \"(p,q) \\<in> b\" using b by auto\n        thus ?thesis using x by auto}\n     next\n      { assume \"\\<not>?A \\<and> \\<not>?B \\<and> ?C\" then have ?C by simp\n        then obtain t where lptp:\"l'\\<parallel>t\" and \"t\\<parallel>u\" by auto\n        from kl llp lpq obtain ll where  kll:\"k\\<parallel>ll\" and llr:\"ll\\<parallel>q\" using M5exist_var by blast\n        with lpq lptp  have \"ll\\<parallel>t\" using M1 by blast\n        with kp pu uv kll llr qv \\<open>t\\<parallel>u\\<close> have \"(p,q) \\<in> ov\" using ov by blast\n        thus ?thesis using x by auto}\n      qed\nqed\n\n\nlemma csov:\"s O ov \\<subseteq> b \\<union> m \\<union> ov\"\nproof\n   fix x::\"'a\\<times>'a\" assume \"x \\<in> s O ov\" then obtain p q z where x:\"x = (p,q)\" and \"(p,z) \\<in> s\" and \"(z,q)\\<in> ov\" by auto\n   from \\<open>(p,z) \\<in> s\\<close> obtain k u v where kp:\"k\\<parallel>p\" and kz:\"k\\<parallel>z\" and  pu:\"p\\<parallel>u\" and uv:\"u\\<parallel>v\" and zv:\"z\\<parallel>v\" using s by blast\n   from  \\<open>(z,q) \\<in> ov\\<close> obtain k' l'  u' v'   where kpz:\"k'\\<parallel>z\"  and kplp:\"k'\\<parallel>l'\" and lpq:\"l'\\<parallel>q\" and zup:\"z\\<parallel>u'\"  and qvp:\"q\\<parallel>v'\" and upvp:\"u'\\<parallel>v'\" using ov by blast\n   from  kz kpz kplp have klp:\"k\\<parallel>l'\" using M1 by blast\n   from  uv zv zup  have uup:\"u\\<parallel>u'\" using M1 by blast\n   with pu upvp obtain uu where puu:\"p\\<parallel>uu\" and uuvp:\"uu\\<parallel>v'\" using M5exist_var by blast\n   from pu lpq have \"p\\<parallel>q \\<oplus> ((\\<exists>t. p\\<parallel>t \\<and> t\\<parallel>q) \\<oplus> (\\<exists>t. l'\\<parallel>t \\<and> t\\<parallel>u))\" (is \"?A \\<oplus> (?B \\<oplus> ?C)\") using M2 by blast\n   then have \"(?A\\<and>\\<not>?B\\<and>\\<not>?C) \\<or> ((\\<not>?A\\<and>?B\\<and>\\<not>?C) \\<or> (\\<not>?A\\<and>\\<not>?B\\<and>?C))\" by (insert xor_distr_L[of ?A ?B ?C], auto simp:elimmeets)\n   thus \"x \\<in> b \\<union> m \\<union> ov\"\n   proof (elim disjE)\n      { assume \"?A\\<and>\\<not>?B\\<and>\\<not>?C\" then have ?A by simp\n        then have \"(p,q) \\<in> m\" using m by auto\n        thus ?thesis using x by auto}\n      next\n      { assume \"\\<not>?A\\<and>?B\\<and>\\<not>?C\" then have ?B by simp \n        then have \"(p,q) \\<in> b\" using b by auto\n        thus ?thesis using x by auto}\n     next\n      { assume \"\\<not>?A \\<and> \\<not>?B \\<and> ?C\" then have ?C by simp\n        then obtain t where lpt:\"l'\\<parallel>t\" and \"t\\<parallel>u\" by auto\n        with pu puu have \"t\\<parallel>uu\" using M1 by blast\n        with lpt kp puu uuvp klp lpq qvp  have \"(p,q) \\<in> ov\" using ov by blast\n        thus ?thesis using x by auto}\n      qed\nqed\n\n\nlemma csfi:\"s O f^-1 \\<subseteq> b \\<union> m \\<union> ov\"\nproof\n   fix x::\"'a\\<times>'a\" assume \"x \\<in> s O f^-1\" then obtain p q r where x:\"x = (p,r)\" and \"(p,q) \\<in> s\" and \"(q,r)\\<in> f^-1\" by auto\n   from \\<open>(p,q) \\<in> s\\<close> obtain k u v where kp:\"k\\<parallel>p\" and kq:\"k\\<parallel>q\" and  pu:\"p\\<parallel>u\" and uv:\"u\\<parallel>v\"  and qv:\"q\\<parallel>v\"  using s by blast\n   from  \\<open>(q,r) \\<in> f^-1\\<close> obtain k' l  v'  where kpq:\"k'\\<parallel>q\"  and kpl:\"k'\\<parallel>l\" and lr:\"l\\<parallel>r\"   and rvp:\"r\\<parallel>v'\" and qvp:\"q\\<parallel>v'\" using f by blast\n   from kpq kpl kq have kl:\"k\\<parallel>l\" using M1 by blast \n   from qvp qv uv have uvp:\"u\\<parallel>v'\" using M1 by blast\n   from pu lr have \"p\\<parallel>r \\<oplus> ((\\<exists>t'. p\\<parallel>t' \\<and> t'\\<parallel>r) \\<oplus> (\\<exists>t'. l\\<parallel>t' \\<and> t'\\<parallel>u))\" (is \"?A \\<oplus> (?B \\<oplus> ?C)\") using M2 by blast\n   then have \"(?A\\<and>\\<not>?B\\<and>\\<not>?C) \\<or> ((\\<not>?A\\<and>?B\\<and>\\<not>?C) \\<or> (\\<not>?A\\<and>\\<not>?B\\<and>?C))\" by (insert xor_distr_L[of ?A ?B ?C], auto simp:elimmeets)\n   thus \"x \\<in> b \\<union> m \\<union> ov\"\n   proof (elim disjE)\n      { assume \"?A\\<and>\\<not>?B\\<and>\\<not>?C\" then have ?A by simp\n        then have \"(p,r) \\<in> m\" using m by auto\n        thus ?thesis using x by auto}\n      next\n      { assume \"\\<not>?A\\<and>?B\\<and>\\<not>?C\" then have ?B by simp \n        then have \"(p,r) \\<in> b\" using b by auto\n        thus ?thesis using x by auto}\n     next\n      { assume \"\\<not>?A \\<and> \\<not>?B \\<and> ?C\" then have ?C by simp\n        then obtain t' where ltp:\"l\\<parallel>t'\" and \"t'\\<parallel>u\" by auto\n        with kp pu uvp kl lr rvp have \"(p,r) \\<in> ov\" using ov by blast\n        thus ?thesis using x by auto}\n      qed\nqed\n\n(* =========$\\alpha_4$ compositions========== *)\ntext \\<open>We prove compositions of the form $r_1 \\circ r_2 \\subseteq f \\cup f^{-1} \\cup e$.\\<close>\n\nlemma cmmi:\"m O m^-1 \\<subseteq> f \\<union> f^-1 \\<union> e\"\nproof \n  fix x::\"'a\\<times>'a\" assume a:\"x \\<in> m O m^-1\" then obtain p q z where x:\"x =(p,q)\" and 1:\"(p,z) \\<in> m\" and 2:\"(z,q) \\<in> m^-1\" by auto\n  then have pz:\"p\\<parallel>z\" and qz:\"q\\<parallel>z\" using m by auto\n  obtain k k' where kp:\"k\\<parallel>p\" and kpq:\"k'\\<parallel>q\" using M3 meets_wd qz pz by blast\n  from kp kpq have \"k\\<parallel>q \\<oplus> ((\\<exists>t. k\\<parallel>t \\<and> t\\<parallel>q) \\<oplus> (\\<exists>t. k'\\<parallel>t \\<and> t\\<parallel>p))\" (is \"?A \\<oplus> (?B \\<oplus> ?C)\") using M2 by blast \n  then have \"(?A\\<and>\\<not>?B\\<and>\\<not>?C)\\<or>(\\<not>?A\\<and>?B\\<and>\\<not>?C)\\<or>(\\<not>?A\\<and>\\<not>?B\\<and>?C)\" by (insert xor_distr_L[of ?A ?B ?C], auto simp:elimmeets)\n  thus \"x \\<in>f \\<union> f^-1 \\<union> e\"    \n  proof (elim disjE)\n    {assume \"(?A\\<and>\\<not>?B\\<and>\\<not>?C)\" then have \"?A\" by simp \n     then have \"p = q\" using M4 kp pz qz by blast \n     then have \"(p,q) \\<in> e\" using e by auto\n     thus ?thesis using x by simp }\n    next\n    {assume \"(\\<not>?A\\<and>?B\\<and>\\<not>?C)\" then have \"?B\" by simp\n     then obtain t where kt:\"k\\<parallel>t\" and tq:\"t\\<parallel>q\" by auto\n     then have \"(p,q) \\<in> f^-1\" using f qz pz kp by blast\n     thus ?thesis using x by simp}\n    next\n    {assume \"(\\<not>?A\\<and>\\<not>?B\\<and>?C)\" then have \"?C\" by simp\n     then obtain t where kt:\"k'\\<parallel>t\" and tp:\"t\\<parallel>p\" by auto\n     with kpq pz qz have \"(p,q)\\<in>f\" using f by blast\n     thus ?thesis using x by simp}\n  qed\nqed\n  \n\n\n\nlemma cffi:\"f O f^-1 \\<subseteq> e \\<union> f \\<union> f^-1\"\nproof\n   fix x::\"'a\\<times>'a\" assume \"x \\<in> f O f^-1\" then obtain p q r where x:\"x = (p,r)\" and \"(p,q)\\<in>f\" and \"(q,r) \\<in>f^-1\" by auto\n   from \\<open>(p,q)\\<in>f\\<close> \\<open>(q,r) \\<in> f^-1\\<close> obtain k k' where kp:\"k\\<parallel>p\" and kpr:\"k'\\<parallel>r\" using f by blast\n   from \\<open>(p,q)\\<in>f\\<close> \\<open>(q,r) \\<in> f^-1\\<close> obtain u where pu:\"p\\<parallel>u\" and \"q\\<parallel>u\" and ru:\"r\\<parallel>u\" using f M1 by blast\n   from kp kpr have \"k\\<parallel>r \\<oplus> ((\\<exists>t. k\\<parallel>t \\<and> t\\<parallel>r) \\<oplus> (\\<exists>t. k'\\<parallel>t \\<and> t\\<parallel>p))\" (is \"?A \\<oplus> (?B \\<oplus> ?C)\") using M2 by blast\n   then have \"(?A\\<and>\\<not>?B\\<and>\\<not>?C) \\<or> ((\\<not>?A\\<and>?B\\<and>\\<not>?C) \\<or> (\\<not>?A\\<and>\\<not>?B\\<and>?C))\" by (insert xor_distr_L[of ?A ?B ?C], auto simp:elimmeets)\n   thus \"x \\<in> e \\<union> f \\<union> f^-1\"\n   proof (elim disjE)\n      { assume \"?A\\<and>\\<not>?B\\<and>\\<not>?C\" then have ?A by simp\n        with pu ru kp have \"p = r\" using M4 by auto\n        thus ?thesis using x e by auto}\n      next\n      { assume \"\\<not>?A\\<and>?B\\<and>\\<not>?C\" then have ?B by simp \n        then obtain t where kt:\"k\\<parallel>t\" and tr:\"t\\<parallel>r\" by auto\n        with ru kp pu show ?thesis using x f by blast}\n      next\n      { assume \"\\<not>?A \\<and> \\<not>?B \\<and> ?C\" then have ?C by simp\n        then obtain t where rtp:\"k'\\<parallel>t\" and \"t\\<parallel>p\" by auto\n        with kpr ru pu show ?thesis using x f by blast}\n    qed\nqed\n\n(* =========$\\alpha_5$ composition========== *)\ntext \\<open>We prove compositions of the form $r_1 \\circ r_2 \\subseteq e \\cup s \\cup s^{-1}$.\\<close>\n\nlemma cssi:\"s O s^-1 \\<subseteq> e \\<union> s \\<union> s^-1\"\nproof\n   fix x::\"'a\\<times>'a\" assume \"x \\<in> s O s^-1\" then obtain p q r where x:\"x = (p,r)\" and \"(p,q)\\<in>s\" and \"(q,r) \\<in>s^-1\" by auto\n   from \\<open>(p,q)\\<in>s\\<close> \\<open>(q,r) \\<in> s^-1\\<close> obtain k  where kp:\"k\\<parallel>p\" and kr:\"k\\<parallel>r\" and kq:\"k\\<parallel>q\" using s M1  by blast\n   from \\<open>(p,q)\\<in>s\\<close> \\<open>(q,r) \\<in> s^-1\\<close> obtain u u' where pu:\"p\\<parallel>u\" and  rup:\"r\\<parallel>u'\" using s by blast\n   then have \"p\\<parallel>u' \\<oplus> ((\\<exists>t. p\\<parallel>t \\<and> t\\<parallel>u') \\<oplus> (\\<exists>t. r\\<parallel>t \\<and> t\\<parallel>u))\" (is \"?A \\<oplus> (?B \\<oplus> ?C)\") using M2 by blast\n   then have \"(?A\\<and>\\<not>?B\\<and>\\<not>?C) \\<or> ((\\<not>?A\\<and>?B\\<and>\\<not>?C) \\<or> (\\<not>?A\\<and>\\<not>?B\\<and>?C))\" by (insert xor_distr_L[of ?A ?B ?C], auto simp:elimmeets)\n   thus \"x \\<in> e \\<union> s \\<union> s^-1\"\n   proof (elim disjE)\n      { assume \"?A\\<and>\\<not>?B\\<and>\\<not>?C\" then have ?A by simp\n        with rup kp kr have \"p = r\" using M4 by auto\n        thus ?thesis using x e by auto}\n      next\n      { assume \"\\<not>?A\\<and>?B\\<and>\\<not>?C\" then have ?B by simp \n        then obtain t where kt:\"p\\<parallel>t\" and tr:\"t\\<parallel>u'\" by auto\n        with rup kp kr  show ?thesis using x s by blast}\n      next\n      { assume \"\\<not>?A \\<and> \\<not>?B \\<and> ?C\" then have ?C by simp\n        then obtain t where rtp:\"r\\<parallel>t\" and \"t\\<parallel>u\" by auto\n        with pu kp kr show ?thesis using x s  by blast}\n    qed\nqed\n\nlemma csis:\"s^-1 O s \\<subseteq> e \\<union> s \\<union> s^-1\"\nproof\n   fix x::\"'a\\<times>'a\" assume \"x \\<in> s^-1 O s\" then obtain p q r where x:\"x = (p,r)\" and \"(p,q)\\<in>s^-1\" and \"(q,r) \\<in>s\" by auto\n   from \\<open>(p,q)\\<in>s^-1\\<close> \\<open>(q,r) \\<in> s\\<close> obtain k  where kp:\"k\\<parallel>p\" and kr:\"k\\<parallel>r\" and kq:\"k\\<parallel>q\" using s M1  by blast\n   from \\<open>(p,q)\\<in>s^-1\\<close> \\<open>(q,r) \\<in> s\\<close> obtain u u' where pu:\"p\\<parallel>u\" and  rup:\"r\\<parallel>u'\" using s by blast\n   then have \"p\\<parallel>u' \\<oplus> ((\\<exists>t. p\\<parallel>t \\<and> t\\<parallel>u') \\<oplus> (\\<exists>t. r\\<parallel>t \\<and> t\\<parallel>u))\" (is \"?A \\<oplus> (?B \\<oplus> ?C)\") using M2 by blast\n   then have \"(?A\\<and>\\<not>?B\\<and>\\<not>?C) \\<or> ((\\<not>?A\\<and>?B\\<and>\\<not>?C) \\<or> (\\<not>?A\\<and>\\<not>?B\\<and>?C))\" by (insert xor_distr_L[of ?A ?B ?C], auto simp:elimmeets)\n   thus \"x \\<in> e \\<union> s \\<union> s^-1\"\n   proof (elim disjE)\n      { assume \"?A\\<and>\\<not>?B\\<and>\\<not>?C\" then have ?A by simp\n        with rup kp kr have \"p = r\" using M4 by auto\n        thus ?thesis using x e by auto}\n      next\n      { assume \"\\<not>?A\\<and>?B\\<and>\\<not>?C\" then have ?B by simp \n        then obtain t where kt:\"p\\<parallel>t\" and tr:\"t\\<parallel>u'\" by auto\n        with rup kp kr  show ?thesis using x s by blast}\n      next\n      { assume \"\\<not>?A \\<and> \\<not>?B \\<and> ?C\" then have ?C by simp\n        then obtain t where rtp:\"r\\<parallel>t\" and \"t\\<parallel>u\" by auto\n        with pu kp kr show ?thesis using x s  by blast}\n    qed\nqed\n\nlemma cmim:\"m^-1 O m \\<subseteq> s \\<union> s^-1 \\<union> e\"\nproof\n   fix x::\"'a\\<times>'a\" assume \"x \\<in> m^-1 O m\" then obtain p q r where x:\"x = (p,r)\" and \"(p,q)\\<in>m^-1\" and \"(q,r) \\<in>m\" by auto\n   from \\<open>(p,q)\\<in>m^-1\\<close> \\<open>(q,r) \\<in> m\\<close>  have qp:\"q\\<parallel>p\" and qr:\"q\\<parallel>r\" using m  by auto\n   obtain u u'  where pu:\"p\\<parallel>u\" and  rup:\"r\\<parallel>u'\" using M3 meets_wd qp qr by fastforce\n   then have \"p\\<parallel>u' \\<oplus> ((\\<exists>t. p\\<parallel>t \\<and> t\\<parallel>u') \\<oplus> (\\<exists>t. r\\<parallel>t \\<and> t\\<parallel>u))\" (is \"?A \\<oplus> (?B \\<oplus> ?C)\") using M2 by blast\n   then have \"(?A\\<and>\\<not>?B\\<and>\\<not>?C) \\<or> ((\\<not>?A\\<and>?B\\<and>\\<not>?C) \\<or> (\\<not>?A\\<and>\\<not>?B\\<and>?C))\" by (insert xor_distr_L[of ?A ?B ?C], auto simp:elimmeets)\n   thus \"x \\<in>  s \\<union> s^-1 \\<union> e\"\n   proof (elim disjE)\n      { assume \"?A\\<and>\\<not>?B\\<and>\\<not>?C\" then have ?A by simp\n        with rup qp qr have \"p = r\" using M4 by auto\n        thus ?thesis using x e by auto}\n      next\n      { assume \"\\<not>?A\\<and>?B\\<and>\\<not>?C\" then have ?B by simp \n        then obtain t where kt:\"p\\<parallel>t\" and tr:\"t\\<parallel>u'\" by auto\n        with rup qp qr  show ?thesis using x s by blast}\n      next\n      { assume \"\\<not>?A \\<and> \\<not>?B \\<and> ?C\" then have ?C by simp\n        then obtain t where rtp:\"r\\<parallel>t\" and \"t\\<parallel>u\" by auto\n        with pu qp qr show ?thesis using x s  by blast}\n    qed\nqed\n\n(* =========$\\beta_1$ composition========== *)\nsubsection \\<open>$\\beta$-composition\\<close>\ntext \\<open>We prove compositions of the form $r_1 \\circ r_2 \\subseteq b \\cup m \\cup ov \\cup s \\cup d$.\\<close>\n\nlemma cbd:\"b O d \\<subseteq> b \\<union> m \\<union> ov \\<union> s \\<union> d\"\nproof \n  fix x::\"'a\\<times>'a\" assume \"x \\<in> b O d\" then obtain p q z where x:\"x = (p,q)\" and \"(p,z) \\<in> b\" and \"(z,q) \\<in> d\" by auto\n  from \\<open>(p,z) \\<in> b\\<close> obtain c where pc:\"p\\<parallel>c\" and cz:\"c\\<parallel>z\" using b by auto\n  obtain a where ap:\"a\\<parallel>p\" using M3 meets_wd pc by blast\n  from \\<open>(z,q) \\<in> d\\<close> obtain k l u v where \"k\\<parallel>l\" and \"l\\<parallel>z\" and kq:\"k\\<parallel>q\" and zu:\"z\\<parallel>u\" and uv:\"u\\<parallel>v\" and qv:\"q\\<parallel>v\" using d by blast\n  from pc cz zu obtain cz where pcz:\"p\\<parallel>cz\" and czu:\"cz\\<parallel>u\" using M5exist_var by blast\n  with uv obtain czu where pczu:\"p\\<parallel>czu\" and czuv:\"czu\\<parallel>v\" using M5exist_var by blast\n  from ap kq  have \"a\\<parallel>q \\<oplus> ((\\<exists>t. a\\<parallel>t \\<and> t\\<parallel>q) \\<oplus> (\\<exists>t. k\\<parallel>t \\<and> t\\<parallel>p))\" (is \"?A \\<oplus> (?B \\<oplus> ?C)\") using M2 by blast\n  then have \"(?A\\<and>\\<not>?B\\<and>\\<not>?C) \\<or> ((\\<not>?A\\<and>?B\\<and>\\<not>?C) \\<or> (\\<not>?A\\<and>\\<not>?B\\<and>?C))\" by (insert xor_distr_L[of ?A ?B ?C], auto simp:elimmeets)\n  thus \"x \\<in> b \\<union> m \\<union> ov \\<union> s \\<union> d\"\n  proof (elim disjE)\n      { assume \"?A\\<and>\\<not>?B\\<and>\\<not>?C\" then have ?A by simp\n        with ap pczu czuv uv qv have \"(p,q) \\<in> s\" using s by blast\n        thus ?thesis using x  by auto} \n      next\n      { assume \"\\<not>?A\\<and>?B\\<and>\\<not>?C\" then have ?B by simp \n        then obtain t where at:\"a\\<parallel>t\" and tq:\"t\\<parallel>q\" by auto\n        from pc  tq have \"p\\<parallel>q \\<oplus> ((\\<exists>t'. p\\<parallel>t' \\<and> t'\\<parallel>q) \\<oplus> (\\<exists>t'. t\\<parallel>t' \\<and> t'\\<parallel>c))\" (is \"?A \\<oplus> (?B \\<oplus> ?C)\") using M2 by blast\n        then have \"(?A\\<and>\\<not>?B\\<and>\\<not>?C) \\<or> ((\\<not>?A\\<and>?B\\<and>\\<not>?C) \\<or> (\\<not>?A\\<and>\\<not>?B\\<and>?C))\" by (insert xor_distr_L[of ?A ?B ?C], auto simp:elimmeets)\n        thus \"x \\<in> b \\<union> m \\<union> ov \\<union> s \\<union> d\"\n        proof (elim disjE)\n           { assume \"?A\\<and>\\<not>?B\\<and>\\<not>?C\" then have ?A by simp\n             thus ?thesis using x m by auto}\n           next\n           { assume \"\\<not>?A\\<and>?B\\<and>\\<not>?C\" then have ?B by simp\n             thus ?thesis using x b by auto}\n           next\n           { assume \"\\<not>?A \\<and> \\<not>?B \\<and> ?C\" then have ?C by simp\n             then obtain t' where \"t\\<parallel>t'\" and \"t'\\<parallel>c\" by auto\n             with pc pczu have \"t'\\<parallel>czu\" using M1 by auto\n             with at tq ap pczu czuv qv \\<open>t\\<parallel>t'\\<close> have \"(p,q)\\<in>ov\" using ov by blast\n             thus ?thesis using x by auto}\n        qed\n        }  \n      next\n      { assume \"\\<not>?A \\<and> \\<not>?B \\<and> ?C\" then have ?C by simp\n        then obtain t where \"k\\<parallel>t\" and \"t\\<parallel>p\" by auto\n        with kq pczu czuv uv qv have \"(p,q) \\<in> d\" using d by blast\n        thus ?thesis using x  by auto}\n       qed\nqed\n\nlemma cbf:\"b O f \\<subseteq> b \\<union> m \\<union> ov \\<union> s \\<union> d\"\nproof \n  fix x::\"'a\\<times>'a\" assume \"x \\<in> b O f\" then obtain p q z where x:\"x = (p,q)\" and \"(p,z) \\<in> b\" and \"(z,q) \\<in> f\" by auto\n  from \\<open>(p,z) \\<in> b\\<close> obtain c where pc:\"p\\<parallel>c\" and cz:\"c\\<parallel>z\" using b by auto\n  obtain a where ap:\"a\\<parallel>p\" using M3 meets_wd pc by blast\n  from \\<open>(z,q) \\<in> f\\<close> obtain k l u  where \"k\\<parallel>l\" and \"l\\<parallel>z\" and kq:\"k\\<parallel>q\" and zu:\"z\\<parallel>u\" and qu:\"q\\<parallel>u\" using f  by blast\n  from pc cz zu obtain cz where pcz:\"p\\<parallel>cz\" and czu:\"cz\\<parallel>u\" using M5exist_var by blast\n  from ap kq  have \"a\\<parallel>q \\<oplus> ((\\<exists>t. a\\<parallel>t \\<and> t\\<parallel>q) \\<oplus> (\\<exists>t. k\\<parallel>t \\<and> t\\<parallel>p))\" (is \"?A \\<oplus> (?B \\<oplus> ?C)\") using M2 by blast\n  then have \"(?A\\<and>\\<not>?B\\<and>\\<not>?C) \\<or> ((\\<not>?A\\<and>?B\\<and>\\<not>?C) \\<or> (\\<not>?A\\<and>\\<not>?B\\<and>?C))\" by (insert xor_distr_L[of ?A ?B ?C], auto simp:elimmeets)\n  thus \"x \\<in> b \\<union> m \\<union> ov \\<union> s \\<union> d\"\n  proof (elim disjE)\n      { assume \"?A\\<and>\\<not>?B\\<and>\\<not>?C\" then have ?A by simp\n        with ap pcz czu  qu have \"(p,q) \\<in> s\" using s by blast\n        thus ?thesis using x  by auto} \n      next\n      { assume \"\\<not>?A\\<and>?B\\<and>\\<not>?C\" then have ?B by simp \n        then obtain t where at:\"a\\<parallel>t\" and tq:\"t\\<parallel>q\" by auto\n        from pc  tq have \"p\\<parallel>q \\<oplus> ((\\<exists>t'. p\\<parallel>t' \\<and> t'\\<parallel>q) \\<oplus> (\\<exists>t'. t\\<parallel>t' \\<and> t'\\<parallel>c))\" (is \"?A \\<oplus> (?B \\<oplus> ?C)\") using M2 by blast\n        then have \"(?A\\<and>\\<not>?B\\<and>\\<not>?C) \\<or> ((\\<not>?A\\<and>?B\\<and>\\<not>?C) \\<or> (\\<not>?A\\<and>\\<not>?B\\<and>?C))\" by (insert xor_distr_L[of ?A ?B ?C], auto simp:elimmeets)\n        thus \"x \\<in> b \\<union> m \\<union> ov \\<union> s \\<union> d\"\n        proof (elim disjE)\n           { assume \"?A\\<and>\\<not>?B\\<and>\\<not>?C\" then have ?A by simp\n             thus ?thesis using x m by auto}\n           next\n           { assume \"\\<not>?A\\<and>?B\\<and>\\<not>?C\" then have ?B by simp\n             thus ?thesis using x b by auto}\n           next\n           { assume \"\\<not>?A \\<and> \\<not>?B \\<and> ?C\" then have ?C by simp\n             then obtain t' where \"t\\<parallel>t'\" and \"t'\\<parallel>c\" by auto\n             with pc pcz have \"t'\\<parallel>cz\" using M1 by auto\n             with at tq ap pcz czu qu \\<open>t\\<parallel>t'\\<close> have \"(p,q)\\<in>ov\" using ov by blast\n             thus ?thesis using x by auto}\n        qed\n        }  \n      next\n      { assume \"\\<not>?A \\<and> \\<not>?B \\<and> ?C\" then have ?C by simp\n        then obtain t where \"k\\<parallel>t\" and \"t\\<parallel>p\" by auto\n        with kq pcz czu  qu have \"(p,q) \\<in> d\" using d by blast\n        thus ?thesis using x  by auto}\n       qed\nqed\n\nlemma cbovi:\"b O ov^-1 \\<subseteq> b \\<union> m \\<union> ov \\<union> s \\<union> d\"\nproof \n  fix x::\"'a\\<times>'a\" assume \"x \\<in> b O ov^-1\" then obtain p q z where x:\"x = (p,q)\" and \"(p,z) \\<in> b\" and \"(z,q) \\<in> ov^-1\" by auto\n  from \\<open>(p,z) \\<in> b\\<close> obtain c where pc:\"p\\<parallel>c\" and cz:\"c\\<parallel>z\" using b by auto\n  obtain a where ap:\"a\\<parallel>p\" using M3 meets_wd pc by blast\n  from \\<open>(z,q) \\<in> ov^-1\\<close> obtain k l u v w where \"k\\<parallel>l\" and lz:\"l\\<parallel>z\" and kq:\"k\\<parallel>q\" and zv:\"z\\<parallel>v\" and qu:\"q\\<parallel>u\" and uv:\"u\\<parallel>v\" and lw:\"l\\<parallel>w\" and wu:\"w\\<parallel>u\" using ov  by blast\n  from cz lz lw have \"c\\<parallel>w\" using M1 by auto\n  with pc wu obtain cw where pcw:\"p\\<parallel>cw\" and cwu:\"cw\\<parallel>u\" using M5exist_var by blast\n  from ap kq  have \"a\\<parallel>q \\<oplus> ((\\<exists>t. a\\<parallel>t \\<and> t\\<parallel>q) \\<oplus> (\\<exists>t. k\\<parallel>t \\<and> t\\<parallel>p))\" (is \"?A \\<oplus> (?B \\<oplus> ?C)\") using M2 by blast\n  then have \"(?A\\<and>\\<not>?B\\<and>\\<not>?C) \\<or> ((\\<not>?A\\<and>?B\\<and>\\<not>?C) \\<or> (\\<not>?A\\<and>\\<not>?B\\<and>?C))\" by (insert xor_distr_L[of ?A ?B ?C], auto simp:elimmeets)\n  thus \"x \\<in> b \\<union> m \\<union> ov \\<union> s \\<union> d\"\n  proof (elim disjE)\n      { assume \"?A\\<and>\\<not>?B\\<and>\\<not>?C\" then have ?A by simp\n        with ap qu pcw cwu  have \"(p,q) \\<in> s\" using s by blast\n        thus ?thesis using x  by auto} \n      next\n      { assume \"\\<not>?A\\<and>?B\\<and>\\<not>?C\" then have ?B by simp \n        then obtain t where at:\"a\\<parallel>t\" and tq:\"t\\<parallel>q\" by auto\n        from pc  tq have \"p\\<parallel>q \\<oplus> ((\\<exists>t'. p\\<parallel>t' \\<and> t'\\<parallel>q) \\<oplus> (\\<exists>t'. t\\<parallel>t' \\<and> t'\\<parallel>c))\" (is \"?A \\<oplus> (?B \\<oplus> ?C)\") using M2 by blast\n        then have \"(?A\\<and>\\<not>?B\\<and>\\<not>?C) \\<or> ((\\<not>?A\\<and>?B\\<and>\\<not>?C) \\<or> (\\<not>?A\\<and>\\<not>?B\\<and>?C))\" by (insert xor_distr_L[of ?A ?B ?C], auto simp:elimmeets)\n        thus \"x \\<in> b \\<union> m \\<union> ov \\<union> s \\<union> d\"\n        proof (elim disjE)\n           { assume \"?A\\<and>\\<not>?B\\<and>\\<not>?C\" then have ?A by simp\n             thus ?thesis using x m by auto}\n           next\n           { assume \"\\<not>?A\\<and>?B\\<and>\\<not>?C\" then have ?B by simp\n             thus ?thesis using x b by auto}\n           next\n           { assume \"\\<not>?A \\<and> \\<not>?B \\<and> ?C\" then have ?C by simp\n             then obtain t' where \"t\\<parallel>t'\" and \"t'\\<parallel>c\" by auto\n             with pc pcw have \"t'\\<parallel>cw\" using M1 by auto\n             with at tq ap pcw cwu qu \\<open>t\\<parallel>t'\\<close> have \"(p,q)\\<in>ov\" using ov by blast\n             thus ?thesis using x by auto}\n        qed\n        }  \n      next\n      { assume \"\\<not>?A \\<and> \\<not>?B \\<and> ?C\" then have ?C by simp\n        then obtain t where \"k\\<parallel>t\" and \"t\\<parallel>p\" by auto\n        with kq pcw cwu  qu have \"(p,q) \\<in> d\" using d by blast\n        thus ?thesis using x  by auto}\n       qed\nqed\n\nlemma cbmi:\"b O m^-1 \\<subseteq> b \\<union> m \\<union> ov \\<union> s \\<union> d\"\nproof \n   fix x::\"'a\\<times>'a\" assume \"x \\<in> b O m^-1\" then obtain p q z where x:\"x = (p,q)\" and \"(p,z) \\<in> b\" and \"(z,q) \\<in> m^-1\" by auto\n   from \\<open>(p,z) \\<in> b\\<close> obtain c where pc:\"p\\<parallel>c\" and cz:\"c\\<parallel>z\" using b by auto\n   obtain k where kp:\"k\\<parallel>p\" using M3 meets_wd pc by blast\n   from \\<open>(z,q) \\<in> m^-1\\<close> have qz:\"q\\<parallel>z\" using m by auto\n   obtain k' where kpq:\"k'\\<parallel>q\" using M3 meets_wd qz by blast \n   from kp kpq  have \"k\\<parallel>q \\<oplus> ((\\<exists>t. k\\<parallel>t \\<and> t\\<parallel>q) \\<oplus> (\\<exists>t. k'\\<parallel>t \\<and> t\\<parallel>p))\" (is \"?A \\<oplus> (?B \\<oplus> ?C)\") using M2 by blast\n   then have \"(?A\\<and>\\<not>?B\\<and>\\<not>?C) \\<or> ((\\<not>?A\\<and>?B\\<and>\\<not>?C) \\<or> (\\<not>?A\\<and>\\<not>?B\\<and>?C))\" by (insert xor_distr_L[of ?A ?B ?C], auto simp:elimmeets)\n   thus \"x \\<in> b \\<union> m \\<union> ov \\<union> s \\<union> d\"\n   proof (elim disjE)\n      { assume \"?A\\<and>\\<not>?B\\<and>\\<not>?C\" then have ?A by simp\n        with kp pc cz qz  have \"(p,q) \\<in> s\" using s by blast\n        thus ?thesis using x  by auto} \n      next\n      { assume \"\\<not>?A\\<and>?B\\<and>\\<not>?C\" then have ?B by simp \n        then obtain t where kt:\"k\\<parallel>t\" and tq:\"t\\<parallel>q\" by auto\n        from pc tq have \"p\\<parallel>q \\<oplus> ((\\<exists>t'. p\\<parallel>t' \\<and> t'\\<parallel>q) \\<oplus> (\\<exists>t'. t\\<parallel>t' \\<and> t'\\<parallel>c))\" (is \"?A \\<oplus> (?B \\<oplus> ?C)\") using M2 by blast\n        then have \"(?A\\<and>\\<not>?B\\<and>\\<not>?C) \\<or> ((\\<not>?A\\<and>?B\\<and>\\<not>?C) \\<or> (\\<not>?A\\<and>\\<not>?B\\<and>?C))\" by (insert xor_distr_L[of ?A ?B ?C], auto simp:elimmeets)\n        thus \"x \\<in> b \\<union> m \\<union> ov \\<union> s \\<union> d\"\n        proof (elim disjE)\n           { assume \"?A\\<and>\\<not>?B\\<and>\\<not>?C\" then have ?A by simp\n             thus ?thesis using x m by auto}\n           next\n           { assume \"\\<not>?A\\<and>?B\\<and>\\<not>?C\" then have ?B by simp\n             thus ?thesis using x b by auto}\n           next\n           { assume \"\\<not>?A \\<and> \\<not>?B \\<and> ?C\" then have ?C by simp\n             then obtain t' where \"t\\<parallel>t'\" and \"t'\\<parallel>c\" by auto\n             with pc cz qz kt tq kp have \"(p,q) \\<in> ov\" using ov by blast\n             thus ?thesis using x by auto}\n        qed\n        }  \n      next\n      { assume \"\\<not>?A \\<and> \\<not>?B \\<and> ?C\" then have ?C by simp\n        then obtain t where \"k'\\<parallel>t\" and \"t\\<parallel>p\" by auto\n        with kpq pc cz qz have \"(p,q) \\<in> d\" using d by blast\n        thus ?thesis using x  by auto}\n       qed\nqed\n\nlemma cdov:\"d O ov \\<subseteq>b \\<union> m \\<union> ov \\<union> s \\<union> d\"\nproof\n   fix x::\"'a\\<times>'a\" assume \"x \\<in> d O ov\" then obtain p q z where x:\"x = (p,q)\" and \"(p,z) \\<in> d\" and \"(z,q) \\<in> ov\" by auto\n   from \\<open>(p,z) \\<in> d\\<close> obtain k l u v where kl:\"k\\<parallel>l\" and lp:\"l\\<parallel>p\" and kz:\"k\\<parallel>z\" and pu:\"p\\<parallel>u\" and uv:\"u\\<parallel>v\" and zv:\"z\\<parallel>v\" using d by blast\n   from \\<open>(z,q) \\<in> ov\\<close> obtain k' l' u' v' c where kplp:\"k'\\<parallel>l'\" and kpz:\"k'\\<parallel>z\" and lpq:\"l'\\<parallel>q\" and zup:\"z\\<parallel>u'\" and upvp:\"u'\\<parallel>v'\" and qvp:\"q\\<parallel>v'\" and \"l'\\<parallel>c\" and \"c\\<parallel>u'\" using ov by blast\n   from zup zv uv have \"u\\<parallel>u'\" using M1 by auto\n   with pu upvp obtain uu where puu:\"p\\<parallel>uu\" and uuvp:\"uu\\<parallel>v'\" using M5exist_var by blast\n   from lp lpq  have \"l\\<parallel>q \\<oplus> ((\\<exists>t. l\\<parallel>t \\<and> t\\<parallel>q) \\<oplus> (\\<exists>t. l'\\<parallel>t \\<and> t\\<parallel>p))\" (is \"?A \\<oplus> (?B \\<oplus> ?C)\") using M2 by blast\n   then have \"(?A\\<and>\\<not>?B\\<and>\\<not>?C) \\<or> ((\\<not>?A\\<and>?B\\<and>\\<not>?C) \\<or> (\\<not>?A\\<and>\\<not>?B\\<and>?C))\" by (insert xor_distr_L[of ?A ?B ?C], auto simp:elimmeets)\n   thus \"x \\<in> b \\<union> m \\<union> ov \\<union> s \\<union> d\"\n   proof (elim disjE)\n      { assume \"?A\\<and>\\<not>?B\\<and>\\<not>?C\" then have ?A by simp\n        with lp puu uuvp qvp  have \"(p,q) \\<in> s\" using s by blast\n        thus ?thesis using x  by auto} \n      next\n      { assume \"\\<not>?A\\<and>?B\\<and>\\<not>?C\" then have ?B by simp \n        then obtain t where lt:\"l\\<parallel>t\" and tq:\"t\\<parallel>q\" by auto\n        from pu tq have \"p\\<parallel>q \\<oplus> ((\\<exists>t'. p\\<parallel>t' \\<and> t'\\<parallel>q) \\<oplus> (\\<exists>t'. t\\<parallel>t' \\<and> t'\\<parallel>u))\" (is \"?A \\<oplus> (?B \\<oplus> ?C)\") using M2 by blast\n        then have \"(?A\\<and>\\<not>?B\\<and>\\<not>?C) \\<or> ((\\<not>?A\\<and>?B\\<and>\\<not>?C) \\<or> (\\<not>?A\\<and>\\<not>?B\\<and>?C))\" by (insert xor_distr_L[of ?A ?B ?C], auto simp:elimmeets)\n        thus \"x \\<in> b \\<union> m \\<union> ov \\<union> s \\<union> d\"\n        proof (elim disjE)\n           { assume \"?A\\<and>\\<not>?B\\<and>\\<not>?C\" then have ?A by simp\n             thus ?thesis using x m by auto}\n           next\n           { assume \"\\<not>?A\\<and>?B\\<and>\\<not>?C\" then have ?B by simp\n             thus ?thesis using x b by auto}\n           next\n           { assume \"\\<not>?A \\<and> \\<not>?B \\<and> ?C\" then have ?C by simp\n             then obtain t' where ttp:\"t\\<parallel>t'\" and \"t'\\<parallel>u\" by auto\n             with pu puu have \"t'\\<parallel>uu\" using M1 by auto\n             with lp puu qvp uuvp lt tq  ttp have \"(p,q) \\<in> ov\" using ov by blast\n             thus ?thesis using x by auto}\n        qed\n        }  \n      next\n      { assume \"\\<not>?A \\<and> \\<not>?B \\<and> ?C\" then have ?C by simp\n        then obtain t where \"l'\\<parallel>t\" and \"t\\<parallel>p\" by auto\n         with lpq puu uuvp qvp have \"(p,q) \\<in> d\" using d by blast\n        thus ?thesis using x  by auto}\n       qed\nqed\n\nlemma cdfi:\"d O f^-1 \\<subseteq> b \\<union> m \\<union> ov \\<union> s \\<union> d\"\nproof\n   fix x::\"'a\\<times>'a\" assume \"x \\<in> d O f^-1\" then obtain p q z where x:\"x = (p,q)\" and \"(p,z) \\<in> d\" and \"(z,q) \\<in> f^-1\" by auto\n   from \\<open>(p,z) \\<in> d\\<close> obtain k l u v where kl:\"k\\<parallel>l\" and lp:\"l\\<parallel>p\" and kz:\"k\\<parallel>z\" and pu:\"p\\<parallel>u\" and uv:\"u\\<parallel>v\" and zv:\"z\\<parallel>v\" using d by blast\n   from \\<open>(z,q) \\<in> f^-1\\<close> obtain k' l' u'  where kpz:\"k'\\<parallel>z\" and kplp:\"k'\\<parallel>l'\" and lpq:\"l'\\<parallel>q\" and zup:\"z\\<parallel>u'\" and  qup:\"q\\<parallel>u'\" using f by blast\n   from zup zv uv have uup:\"u\\<parallel>u'\" using M1 by auto\n   from lp lpq  have \"l\\<parallel>q \\<oplus> ((\\<exists>t. l\\<parallel>t \\<and> t\\<parallel>q) \\<oplus> (\\<exists>t. l'\\<parallel>t \\<and> t\\<parallel>p))\" (is \"?A \\<oplus> (?B \\<oplus> ?C)\") using M2 by blast\n   then have \"(?A\\<and>\\<not>?B\\<and>\\<not>?C) \\<or> ((\\<not>?A\\<and>?B\\<and>\\<not>?C) \\<or> (\\<not>?A\\<and>\\<not>?B\\<and>?C))\" by (insert xor_distr_L[of ?A ?B ?C], auto simp:elimmeets)\n   thus \"x \\<in> b \\<union> m \\<union> ov \\<union> s \\<union> d\"\n   proof (elim disjE)\n      { assume \"?A\\<and>\\<not>?B\\<and>\\<not>?C\" then have ?A by simp\n        with lp pu uup qup  have \"(p,q) \\<in> s\" using s by blast\n        thus ?thesis using x  by auto} \n      next\n      { assume \"\\<not>?A\\<and>?B\\<and>\\<not>?C\" then have ?B by simp \n        then obtain t where lt:\"l\\<parallel>t\" and tq:\"t\\<parallel>q\" by auto\n        from pu tq have \"p\\<parallel>q \\<oplus> ((\\<exists>t'. p\\<parallel>t' \\<and> t'\\<parallel>q) \\<oplus> (\\<exists>t'. t\\<parallel>t' \\<and> t'\\<parallel>u))\" (is \"?A \\<oplus> (?B \\<oplus> ?C)\") using M2 by blast\n        then have \"(?A\\<and>\\<not>?B\\<and>\\<not>?C) \\<or> ((\\<not>?A\\<and>?B\\<and>\\<not>?C) \\<or> (\\<not>?A\\<and>\\<not>?B\\<and>?C))\" by (insert xor_distr_L[of ?A ?B ?C], auto simp:elimmeets)\n        thus \"x \\<in> b \\<union> m \\<union> ov \\<union> s \\<union> d\"\n        proof (elim disjE)\n           { assume \"?A\\<and>\\<not>?B\\<and>\\<not>?C\" then have ?A by simp\n             thus ?thesis using x m by auto}\n           next\n           { assume \"\\<not>?A\\<and>?B\\<and>\\<not>?C\" then have ?B by simp\n             thus ?thesis using x b by auto}\n           next\n           { assume \"\\<not>?A \\<and> \\<not>?B \\<and> ?C\" then have ?C by simp\n             then obtain t' where ttp:\"t\\<parallel>t'\" and tpu:\"t'\\<parallel>u\" by auto\n             with lt tq lp pu uup qup  have \"(p,q) \\<in> ov\" using ov by blast\n             thus ?thesis using x by auto}\n        qed\n        }  \n      next\n      { assume \"\\<not>?A \\<and> \\<not>?B \\<and> ?C\" then have ?C by simp\n        then obtain t where \"l'\\<parallel>t\" and \"t\\<parallel>p\" by auto\n        with lpq pu uup qup  have \"(p,q) \\<in> d\" using d by blast\n        thus ?thesis using x  by auto}\n       qed\nqed\n\n(* =========$\\beta_2$ composition ==========*)\ntext \\<open>We prove compositions of the form $r_1 \\circ r_2 \\subseteq b \\cup m \\cup ov \\cup f^{-1} \\cup d^{-1}$.\\<close>\n\n\n\nlemma cdib:\"d^-1 O b \\<subseteq> b \\<union> m \\<union> ov \\<union> f^-1 \\<union> d^-1\"\nproof\n  fix x::\"'a\\<times>'a\" assume \"x \\<in> d^-1 O b\" then obtain p q z where \"(p,z) : d^-1\" and \"(z,q) : b\" and x:\"x = (p,q)\" by auto\n  from \\<open>(p,z) : d^-1\\<close> obtain k l u v  where kp:\"k\\<parallel>p\" and kl:\"k\\<parallel>l\" and lz:\"l\\<parallel>z\" and pv:\"p\\<parallel>v\" and uv:\"u\\<parallel>v\"  and zu:\"z\\<parallel>u\"  using d by blast\n  from \\<open>(z,q) : b\\<close> obtain c  where  zc:\"z\\<parallel>c\" and cq:\"c\\<parallel>q\"  using b by blast\n  with kl lz obtain lzc where klzc:\"k\\<parallel>lzc\" and lzcq:\"lzc\\<parallel>q\" using M5exist_var by blast\n  obtain v' where qvp:\"q\\<parallel>v'\" using M3 meets_wd cq by blast\n  from pv qvp  have \"p\\<parallel>v' \\<oplus> ((\\<exists>t. p\\<parallel>t \\<and> t\\<parallel>v') \\<oplus> (\\<exists>t. q\\<parallel>t \\<and> t\\<parallel>v))\" (is \"?A \\<oplus> (?B \\<oplus> ?C)\") using M2 by blast\n  then have \"(?A\\<and>\\<not>?B\\<and>\\<not>?C) \\<or> ((\\<not>?A\\<and>?B\\<and>\\<not>?C) \\<or> (\\<not>?A\\<and>\\<not>?B\\<and>?C))\" by (insert xor_distr_L[of ?A ?B ?C], auto simp:elimmeets)\n  thus \"x \\<in> b \\<union> m \\<union> ov \\<union> f^-1 \\<union> d^-1\"\n  proof (elim disjE)\n      { assume \"?A\\<and>\\<not>?B\\<and>\\<not>?C\" then have ?A by simp\n        with qvp kp klzc lzcq  have \"(p,q) \\<in> f^-1\" using f by blast\n        thus ?thesis using x  by auto} \n      next\n      { assume \"\\<not>?A\\<and>?B\\<and>\\<not>?C\" then have ?B by simp \n        then obtain t where pt:\"p\\<parallel>t\" and tvp:\"t\\<parallel>v'\" by auto\n        from pt cq have \"p\\<parallel>q \\<oplus> ((\\<exists>t'. p\\<parallel>t' \\<and> t'\\<parallel>q) \\<oplus> (\\<exists>t'. c\\<parallel>t' \\<and> t'\\<parallel>t))\" (is \"?A \\<oplus> (?B \\<oplus> ?C)\") using M2 by blast\n        then have \"(?A\\<and>\\<not>?B\\<and>\\<not>?C) \\<or> ((\\<not>?A\\<and>?B\\<and>\\<not>?C) \\<or> (\\<not>?A\\<and>\\<not>?B\\<and>?C))\" by (insert xor_distr_L[of ?A ?B ?C], auto simp:elimmeets)\n        thus \"x \\<in> b \\<union> m \\<union> ov \\<union> f^-1 \\<union> d^-1\"\n        proof (elim disjE)\n           { assume \"?A\\<and>\\<not>?B\\<and>\\<not>?C\" then have ?A by simp\n             thus ?thesis using x m by auto}\n           next\n           { assume \"\\<not>?A\\<and>?B\\<and>\\<not>?C\" then have ?B by simp\n             thus ?thesis using x b by auto}\n           next\n           { assume \"\\<not>?A \\<and> \\<not>?B \\<and> ?C\" then have ?C by simp\n             then obtain t' where ctp:\"c\\<parallel>t'\" and tpt:\"t'\\<parallel>t\" by auto\n             from lzcq cq ctp have \"lzc\\<parallel>t'\" using M1 by auto\n             with pt tvp qvp kp klzc lzcq tpt have \"(p,q) \\<in> ov\" using ov by blast\n             thus ?thesis using x by auto}\n        qed\n        }  \n      next\n      { assume \"\\<not>?A \\<and> \\<not>?B \\<and> ?C\" then have ?C by simp\n        then obtain t where \"q\\<parallel>t\" and \"t\\<parallel>v\" by auto\n        with pv kp klzc lzcq  have \"(p,q) \\<in> d^-1\" using d by blast\n        thus ?thesis using x  by auto}\n       qed\nqed\n\nlemma csdi:\"s O d^-1 \\<subseteq> b \\<union> m \\<union> ov \\<union> f^-1 \\<union> d^-1\"\nproof\n  fix x::\"'a\\<times>'a\" assume \"x \\<in> s O d^-1\" then obtain p q z where \"(p,z) : s\" and \"(z,q) : d^-1\" and x:\"x = (p,q)\" by auto\n  from \\<open>(p,z) : s\\<close> obtain k  u v  where kp:\"k\\<parallel>p\" and kz:\"k\\<parallel>z\" and pu:\"p\\<parallel>u\" and uv:\"u\\<parallel>v\"  and zv:\"z\\<parallel>v\"  using s by blast\n  from \\<open>(z,q) : d^-1\\<close> obtain l' k' u' v'  where lpq:\"l'\\<parallel>q\" and kplp:\"k'\\<parallel>l'\" and kpz:\"k'\\<parallel>z\" and qup:\"q\\<parallel>u'\" and upvp:\"u'\\<parallel>v'\" and zvp:\"z\\<parallel>v'\"  using d  by blast\n  from kp kz kpz have kpp:\"k'\\<parallel>p\" using M1 by auto\n  from pu qup  have \"p\\<parallel>u' \\<oplus> ((\\<exists>t. p\\<parallel>t \\<and> t\\<parallel>u') \\<oplus> (\\<exists>t. q\\<parallel>t \\<and> t\\<parallel>u))\" (is \"?A \\<oplus> (?B \\<oplus> ?C)\") using M2 by blast\n  then have \"(?A\\<and>\\<not>?B\\<and>\\<not>?C) \\<or> ((\\<not>?A\\<and>?B\\<and>\\<not>?C) \\<or> (\\<not>?A\\<and>\\<not>?B\\<and>?C))\" by (insert xor_distr_L[of ?A ?B ?C], auto simp:elimmeets)\n  thus \"x \\<in> b \\<union> m \\<union> ov \\<union> f^-1 \\<union> d^-1\"\n  proof (elim disjE)\n      { assume \"?A\\<and>\\<not>?B\\<and>\\<not>?C\" then have ?A by simp\n        with qup kpp kplp lpq  have \"(p,q) \\<in> f^-1\" using f by blast\n        thus ?thesis using x  by auto} \n      next\n      { assume \"\\<not>?A\\<and>?B\\<and>\\<not>?C\" then have ?B by simp \n        then obtain t where pt:\"p\\<parallel>t\" and tup:\"t\\<parallel>u'\" by auto\n        from pt lpq have \"p\\<parallel>q \\<oplus> ((\\<exists>t'. p\\<parallel>t' \\<and> t'\\<parallel>q) \\<oplus> (\\<exists>t'. l'\\<parallel>t' \\<and> t'\\<parallel>t))\" (is \"?A \\<oplus> (?B \\<oplus> ?C)\") using M2 by blast\n        then have \"(?A\\<and>\\<not>?B\\<and>\\<not>?C) \\<or> ((\\<not>?A\\<and>?B\\<and>\\<not>?C) \\<or> (\\<not>?A\\<and>\\<not>?B\\<and>?C))\" by (insert xor_distr_L[of ?A ?B ?C], auto simp:elimmeets)\n        thus \"x \\<in> b \\<union> m \\<union> ov \\<union> f^-1 \\<union> d^-1\"\n        proof (elim disjE)\n           { assume \"?A\\<and>\\<not>?B\\<and>\\<not>?C\" then have ?A by simp\n             thus ?thesis using x m by auto}\n           next\n           { assume \"\\<not>?A\\<and>?B\\<and>\\<not>?C\" then have ?B by simp\n             thus ?thesis using x b by auto}\n           next\n           { assume \"\\<not>?A \\<and> \\<not>?B \\<and> ?C\" then have ?C by simp\n             then obtain t' where lptp:\"l'\\<parallel>t'\" and tpt:\"t'\\<parallel>t\" by auto\n             with pt tup qup kpp kplp lpq  have \"(p,q) \\<in> ov\" using ov by blast\n             thus ?thesis using x by auto}\n        qed\n        }  \n      next\n      { assume \"\\<not>?A \\<and> \\<not>?B \\<and> ?C\" then have ?C by simp\n        then obtain t where \"q\\<parallel>t\" and \"t\\<parallel>u\" by auto\n        with pu kpp kplp lpq   have \"(p,q) \\<in> d^-1\" using d by blast\n        thus ?thesis using x  by auto}\n       qed\nqed\n\nlemma csib:\"s^-1 O b \\<subseteq> b \\<union> m \\<union> ov \\<union> f^-1 \\<union> d^-1\"\nproof\n  fix x::\"'a\\<times>'a\" assume \"x \\<in> s^-1 O b\" then obtain p q z where \"(p,z) : s^-1\" and \"(z,q) : b\" and x:\"x = (p,q)\" by auto\n  from \\<open>(p,z) : s^-1\\<close> obtain k  u v  where kp:\"k\\<parallel>p\" and kz:\"k\\<parallel>z\" and zu:\"z\\<parallel>u\" and uv:\"u\\<parallel>v\"  and pv:\"p\\<parallel>v\"  using s by blast\n  from \\<open>(z,q) : b\\<close> obtain c  where  zc:\"z\\<parallel>c\" and cq:\"c\\<parallel>q\"  using b by blast\n  from kz zc cq obtain zc where kzc:\"k\\<parallel>zc\" and zcq:\"zc\\<parallel>q\" using M5exist_var by blast\n  obtain v' where qvp:\"q\\<parallel>v'\" using M3 meets_wd cq by blast\n  from pv qvp  have \"p\\<parallel>v' \\<oplus> ((\\<exists>t. p\\<parallel>t \\<and> t\\<parallel>v') \\<oplus> (\\<exists>t. q\\<parallel>t \\<and> t\\<parallel>v))\" (is \"?A \\<oplus> (?B \\<oplus> ?C)\") using M2 by blast\n  then have \"(?A\\<and>\\<not>?B\\<and>\\<not>?C) \\<or> ((\\<not>?A\\<and>?B\\<and>\\<not>?C) \\<or> (\\<not>?A\\<and>\\<not>?B\\<and>?C))\" by (insert xor_distr_L[of ?A ?B ?C], auto simp:elimmeets)\n  thus \"x \\<in> b \\<union> m \\<union> ov \\<union> f^-1 \\<union> d^-1\"\n  proof (elim disjE)\n      { assume \"?A\\<and>\\<not>?B\\<and>\\<not>?C\" then have ?A by simp\n        with qvp kp kzc zcq  have \"(p,q) \\<in> f^-1\" using f by blast\n        thus ?thesis using x  by auto} \n      next\n      { assume \"\\<not>?A\\<and>?B\\<and>\\<not>?C\" then have ?B by simp \n        then obtain t where pt:\"p\\<parallel>t\" and tvp:\"t\\<parallel>v'\" by auto\n        from pt cq have \"p\\<parallel>q \\<oplus> ((\\<exists>t'. p\\<parallel>t' \\<and> t'\\<parallel>q) \\<oplus> (\\<exists>t'. c\\<parallel>t' \\<and> t'\\<parallel>t))\" (is \"?A \\<oplus> (?B \\<oplus> ?C)\") using M2 by blast\n        then have \"(?A\\<and>\\<not>?B\\<and>\\<not>?C) \\<or> ((\\<not>?A\\<and>?B\\<and>\\<not>?C) \\<or> (\\<not>?A\\<and>\\<not>?B\\<and>?C))\" by (insert xor_distr_L[of ?A ?B ?C], auto simp:elimmeets)\n        thus \"x \\<in> b \\<union> m \\<union> ov \\<union> f^-1 \\<union> d^-1\"\n        proof (elim disjE)\n           { assume \"?A\\<and>\\<not>?B\\<and>\\<not>?C\" then have ?A by simp\n             thus ?thesis using x m by auto}\n           next\n           { assume \"\\<not>?A\\<and>?B\\<and>\\<not>?C\" then have ?B by simp\n             thus ?thesis using x b by auto}\n           next\n           { assume \"\\<not>?A \\<and> \\<not>?B \\<and> ?C\" then have ?C by simp\n             then obtain t' where ctp:\"c\\<parallel>t'\" and tpt:\"t'\\<parallel>t\" by auto\n             from zcq cq ctp have \"zc\\<parallel>t'\" using M1 by auto\n             with zcq  pt tvp qvp kzc kp ctp tpt have \"(p,q) \\<in> ov\" using ov by blast\n             thus ?thesis using x by auto}\n        qed\n        }  \n      next\n      { assume \"\\<not>?A \\<and> \\<not>?B \\<and> ?C\" then have ?C by simp\n        then obtain t where \"q\\<parallel>t\" and \"t\\<parallel>v\" by auto\n        with pv kp kzc zcq   have \"(p,q) \\<in> d^-1\" using d by blast\n        thus ?thesis using x  by auto}\n       qed\nqed\n\nlemma covib:\"ov^-1 O b \\<subseteq> b \\<union> m \\<union> ov \\<union> f^-1 \\<union> d^-1\"\nproof\n  fix x::\"'a\\<times>'a\" assume \"x \\<in> ov^-1 O b\" then obtain p q z where \"(p,z) : ov^-1\" and \"(z,q) : b\" and x:\"x = (p,q)\" by auto\n  from \\<open>(p,z) : ov^-1\\<close> obtain k l u v c  where kz:\"k\\<parallel>z\" and kl:\"k\\<parallel>l\" and lp:\"l\\<parallel>p\" and zu:\"z\\<parallel>u\" and uv:\"u\\<parallel>v\"  and pv:\"p\\<parallel>v\" and lc:\"l\\<parallel>c\" and cu:\"c\\<parallel>u\" using ov by blast\n  from \\<open>(z,q) : b\\<close> obtain w  where  zw:\"z\\<parallel>w\" and wq:\"w\\<parallel>q\"  using b by blast\n  from cu zu zw have cw:\"c\\<parallel>w\" using M1 by auto\n  with lc wq obtain cw where lcw:\"l\\<parallel>cw\" and cwq:\"cw\\<parallel>q\" using M5exist_var by blast\n  obtain v' where qvp:\"q\\<parallel>v'\" using M3 meets_wd wq by blast\n  from pv qvp  have \"p\\<parallel>v' \\<oplus> ((\\<exists>t. p\\<parallel>t \\<and> t\\<parallel>v') \\<oplus> (\\<exists>t. q\\<parallel>t \\<and> t\\<parallel>v))\" (is \"?A \\<oplus> (?B \\<oplus> ?C)\") using M2 by blast\n  then have \"(?A\\<and>\\<not>?B\\<and>\\<not>?C) \\<or> ((\\<not>?A\\<and>?B\\<and>\\<not>?C) \\<or> (\\<not>?A\\<and>\\<not>?B\\<and>?C))\" by (insert xor_distr_L[of ?A ?B ?C], auto simp:elimmeets)\n  thus \"x \\<in> b \\<union> m \\<union> ov \\<union> f^-1 \\<union> d^-1\"\n  proof (elim disjE)\n      { assume \"?A\\<and>\\<not>?B\\<and>\\<not>?C\" then have ?A by simp\n        with qvp lp lcw cwq  have \"(p,q) \\<in> f^-1\" using f by blast\n        thus ?thesis using x  by auto} \n      next\n      { assume \"\\<not>?A\\<and>?B\\<and>\\<not>?C\" then have ?B by simp \n        then obtain t where pt:\"p\\<parallel>t\" and tvp:\"t\\<parallel>v'\" by auto\n        from pt wq have \"p\\<parallel>q \\<oplus> ((\\<exists>t'. p\\<parallel>t' \\<and> t'\\<parallel>q) \\<oplus> (\\<exists>t'. w\\<parallel>t' \\<and> t'\\<parallel>t))\" (is \"?A \\<oplus> (?B \\<oplus> ?C)\") using M2 by blast\n        then have \"(?A\\<and>\\<not>?B\\<and>\\<not>?C) \\<or> ((\\<not>?A\\<and>?B\\<and>\\<not>?C) \\<or> (\\<not>?A\\<and>\\<not>?B\\<and>?C))\" by (insert xor_distr_L[of ?A ?B ?C], auto simp:elimmeets)\n        thus \"x \\<in> b \\<union> m \\<union> ov \\<union> f^-1 \\<union> d^-1\"\n        proof (elim disjE)\n           { assume \"?A\\<and>\\<not>?B\\<and>\\<not>?C\" then have ?A by simp\n             thus ?thesis using x m by auto}\n           next\n           { assume \"\\<not>?A\\<and>?B\\<and>\\<not>?C\" then have ?B by simp\n             thus ?thesis using x b by auto}\n           next\n           { assume \"\\<not>?A \\<and> \\<not>?B \\<and> ?C\" then have ?C by simp\n             then obtain t' where wtp:\"w\\<parallel>t'\" and tpt:\"t'\\<parallel>t\" by auto\n             moreover with wq cwq have \"cw\\<parallel>t'\" using M1 by auto\n             ultimately have \"(p,q) \\<in> ov\" using ov cwq lp lcw pt tvp qvp by blast\n             thus ?thesis using x by auto}\n        qed\n        }  \n      next\n      { assume \"\\<not>?A \\<and> \\<not>?B \\<and> ?C\" then have ?C by simp\n        then obtain t where \"q\\<parallel>t\" and \"t\\<parallel>v\" by auto\n        with pv lp lcw cwq  have \"(p,q) \\<in> d^-1\" using d by blast\n        thus ?thesis using x  by auto}\n       qed\nqed\n\nlemma cmib:\"m^-1 O b \\<subseteq> b \\<union> m \\<union> ov \\<union> f^-1 \\<union> d^-1\"\nproof\n  fix x::\"'a\\<times>'a\" assume \"x \\<in> m^-1 O b\" then obtain p q z where \"(p,z) : m^-1\" and \"(z,q) : b\" and x:\"x = (p,q)\" by auto\n  from \\<open>(p,z) : m^-1\\<close> have zp:\"z\\<parallel>p\" using m by auto\n  from \\<open>(z,q) : b\\<close> obtain w  where  zw:\"z\\<parallel>w\" and wq:\"w\\<parallel>q\"  using b by blast\n  obtain v where pv:\"p\\<parallel>v\" using M3 meets_wd zp  by blast\n  obtain v' where qvp:\"q\\<parallel>v'\" using M3 meets_wd wq by blast\n\n  from pv qvp  have \"p\\<parallel>v' \\<oplus> ((\\<exists>t. p\\<parallel>t \\<and> t\\<parallel>v') \\<oplus> (\\<exists>t. q\\<parallel>t \\<and> t\\<parallel>v))\" (is \"?A \\<oplus> (?B \\<oplus> ?C)\") using M2 by blast\n  then have \"(?A\\<and>\\<not>?B\\<and>\\<not>?C) \\<or> ((\\<not>?A\\<and>?B\\<and>\\<not>?C) \\<or> (\\<not>?A\\<and>\\<not>?B\\<and>?C))\" by (insert xor_distr_L[of ?A ?B ?C], auto simp:elimmeets)\n  thus \"x \\<in> b \\<union> m \\<union> ov \\<union> f^-1 \\<union> d^-1\"\n  proof (elim disjE)\n      { assume \"?A\\<and>\\<not>?B\\<and>\\<not>?C\" then have ?A by simp\n        with zp zw wq qvp  have \"(p,q) \\<in> f^-1\" using f by blast\n        thus ?thesis using x  by auto} \n      next\n      { assume \"\\<not>?A\\<and>?B\\<and>\\<not>?C\" then have ?B by simp \n        then obtain t where pt:\"p\\<parallel>t\" and tvp:\"t\\<parallel>v'\" by auto\n        from pt wq have \"p\\<parallel>q \\<oplus> ((\\<exists>t'. p\\<parallel>t' \\<and> t'\\<parallel>q) \\<oplus> (\\<exists>t'. w\\<parallel>t' \\<and> t'\\<parallel>t))\" (is \"?A \\<oplus> (?B \\<oplus> ?C)\") using M2 by blast\n        then have \"(?A\\<and>\\<not>?B\\<and>\\<not>?C) \\<or> ((\\<not>?A\\<and>?B\\<and>\\<not>?C) \\<or> (\\<not>?A\\<and>\\<not>?B\\<and>?C))\" by (insert xor_distr_L[of ?A ?B ?C], auto simp:elimmeets)\n        thus \"x \\<in> b \\<union> m \\<union> ov \\<union> f^-1 \\<union> d^-1\"\n        proof (elim disjE)\n           { assume \"?A\\<and>\\<not>?B\\<and>\\<not>?C\" then have ?A by simp\n             thus ?thesis using x m by auto}\n           next\n           { assume \"\\<not>?A\\<and>?B\\<and>\\<not>?C\" then have ?B by simp\n             thus ?thesis using x b by auto}\n           next\n           { assume \"\\<not>?A \\<and> \\<not>?B \\<and> ?C\" then have ?C by simp\n             then obtain t' where wtp:\"w\\<parallel>t'\" and tpt:\"t'\\<parallel>t\" by auto\n             with zp zw wq pt tvp qvp have \"(p,q) \\<in> ov\" using ov  by blast\n             thus ?thesis using x by auto}\n        qed\n        }  \n      next\n      { assume \"\\<not>?A \\<and> \\<not>?B \\<and> ?C\" then have ?C by simp\n        then obtain t where \"q\\<parallel>t\" and \"t\\<parallel>v\" by auto\n        with zp zw wq pv   have \"(p,q) \\<in> d^-1\" using d by blast\n        thus ?thesis using x  by auto}\n       qed\nqed\n\n(*==========$\\gamma$ composition =======*)\nsubsection \\<open>$\\gamma$-composition\\<close>\ntext \\<open>We prove compositions of the form $r_1 \\circ r_2 \\subseteq ov \\cup s \\cup d \\cup f \\cup e \\cup f^{-1} \\cup d^{-1} \\cup s^{-1} \\cup ov^{-1}$.\\<close>\n\nlemma covovi:\"ov O ov^-1 \\<subseteq> e \\<union> ov \\<union> ov^-1 \\<union> d \\<union> d^-1 \\<union> s \\<union> s^-1 \\<union> f \\<union> f^-1 \"\nproof\n  fix x::\"'a\\<times>'a\" assume \"x \\<in> ov O ov^-1\" then obtain p q z where x:\"x = (p,q)\" and \"(p,z) \\<in> ov\" and \"(z, q) \\<in> ov^-1\" by auto\n  from \\<open>(p,z) \\<in> ov\\<close> obtain k l c u  where kp:\"k\\<parallel>p\" and kl:\"k\\<parallel>l\" and lz:\"l\\<parallel>z\" and lc:\"l\\<parallel>c\" and pu:\"p\\<parallel>u\" and cu:\"c\\<parallel>u\"  using ov by blast\n  from \\<open>(z,q) \\<in> ov^-1\\<close> obtain k' l' c' u'  where kpq:\"k'\\<parallel>q\" and kplp:\"k'\\<parallel>l'\" and lpz:\"l'\\<parallel>z\" and lpcp:\"l'\\<parallel>c'\" and qup:\"q\\<parallel>u'\" and cpup:\"c'\\<parallel>u'\"  using ov by blast\n\n  from kp kpq  have \"k\\<parallel>q \\<oplus> ((\\<exists>t. k\\<parallel>t \\<and> t\\<parallel>q) \\<oplus> (\\<exists>t. k'\\<parallel>t \\<and> t\\<parallel>p))\" (is \"?A \\<oplus> (?B \\<oplus> ?C)\") using M2 by blast\n  then have \"(?A\\<and>\\<not>?B\\<and>\\<not>?C) \\<or> ((\\<not>?A\\<and>?B\\<and>\\<not>?C) \\<or> (\\<not>?A\\<and>\\<not>?B\\<and>?C))\" by (insert xor_distr_L[of ?A ?B ?C], auto simp:elimmeets)\n  thus \"x \\<in> e \\<union> ov \\<union> ov^-1 \\<union> d \\<union> d^-1 \\<union> s \\<union> s^-1 \\<union> f \\<union> f^-1\"\n  proof (elim disjE)\n      { assume \"?A\\<and>\\<not>?B\\<and>\\<not>?C\" then have kq:?A by simp\n        from pu qup have \"p\\<parallel>u' \\<oplus> ((\\<exists>t'. p\\<parallel>t' \\<and> t'\\<parallel>u') \\<oplus> (\\<exists>t'. q\\<parallel>t' \\<and> t'\\<parallel>u))\" (is \"?A \\<oplus> (?B \\<oplus> ?C)\") using M2 by blast\n        then have \"(?A\\<and>\\<not>?B\\<and>\\<not>?C) \\<or> ((\\<not>?A\\<and>?B\\<and>\\<not>?C) \\<or> (\\<not>?A\\<and>\\<not>?B\\<and>?C))\" by (insert xor_distr_L[of ?A ?B ?C], auto simp:elimmeets)\n        thus ?thesis\n        proof (elim disjE)\n          { assume \"?A\\<and>\\<not>?B\\<and>\\<not>?C\" then have ?A by simp\n            with kq kp qup have \"p = q\" using M4 by auto\n            thus ?thesis using x e by auto}\n          next\n          { assume \"\\<not>?A\\<and>?B\\<and>\\<not>?C\" then have ?B by simp\n            with kq kp qup show ?thesis using x s by blast}\n          next\n          { assume \"\\<not>?A\\<and>\\<not>?B\\<and>?C\" then have ?C by simp\n            with kq kp pu show ?thesis using x s by blast}\n        qed}\n      next\n      { assume \"\\<not>?A\\<and>?B\\<and>\\<not>?C\" then have ?B by simp\n        then obtain t where kt:\"k\\<parallel>t\" and tq:\"t\\<parallel>q\" by auto\n        from pu qup have \"p\\<parallel>u' \\<oplus> ((\\<exists>t'. p\\<parallel>t' \\<and> t'\\<parallel>u') \\<oplus> (\\<exists>t'. q\\<parallel>t' \\<and> t'\\<parallel>u))\" (is \"?A \\<oplus> (?B \\<oplus> ?C)\") using M2 by blast\n        then have \"(?A\\<and>\\<not>?B\\<and>\\<not>?C) \\<or> ((\\<not>?A\\<and>?B\\<and>\\<not>?C) \\<or> (\\<not>?A\\<and>\\<not>?B\\<and>?C))\" by (insert xor_distr_L[of ?A ?B ?C], auto simp:elimmeets)\n        thus ?thesis\n        proof (elim disjE)\n          { assume \"?A\\<and>\\<not>?B\\<and>\\<not>?C\" then have ?A by simp\n            with qup kp kt tq  show ?thesis using x f  by blast}\n          next\n          { assume \"\\<not>?A\\<and>?B\\<and>\\<not>?C\" then have ?B by simp\n            then obtain t' where ptp:\"p\\<parallel>t'\" and tpup:\"t'\\<parallel>u'\" by auto\n            from tq kpq kplp have \"t\\<parallel>l'\" using M1 by auto\n            moreover with lpz lz lc have \"l'\\<parallel>c\" using M1 by auto\n            moreover with cu pu ptp have \"c\\<parallel>t'\" using M1 by auto\n            ultimately obtain lc where \"t\\<parallel>lc\" and \"lc\\<parallel>t'\" using M5exist_var by blast\n            with ptp tpup kp kt tq qup  show ?thesis using x ov by blast}\n          next\n          { assume \"\\<not>?A\\<and>\\<not>?B\\<and>?C\" then have ?C by simp\n            with pu kp kt tq  show ?thesis using x d  by blast}\n\n        qed}\n      next\n      {assume \"\\<not>?A\\<and>\\<not>?B\\<and>?C\" then have ?C by auto\n       then obtain t where kpt:\"k'\\<parallel>t\" and tp:\"t\\<parallel>p\" by auto\n        from pu qup have \"p\\<parallel>u' \\<oplus> ((\\<exists>t'. p\\<parallel>t' \\<and> t'\\<parallel>u') \\<oplus> (\\<exists>t'. q\\<parallel>t' \\<and> t'\\<parallel>u))\" (is \"?A \\<oplus> (?B \\<oplus> ?C)\") using M2 by blast\n        then have \"(?A\\<and>\\<not>?B\\<and>\\<not>?C) \\<or> ((\\<not>?A\\<and>?B\\<and>\\<not>?C) \\<or> (\\<not>?A\\<and>\\<not>?B\\<and>?C))\" by (insert xor_distr_L[of ?A ?B ?C], auto simp:elimmeets)\n        thus ?thesis\n        proof (elim disjE)\n          { assume \"?A\\<and>\\<not>?B\\<and>\\<not>?C\" then have ?A by simp\n            with kpq kpt tp qup show ?thesis using x f  by blast}\n          next\n          { assume \"\\<not>?A\\<and>?B\\<and>\\<not>?C\" then have ?B by simp\n            then obtain t' where \"p\\<parallel>t'\" and \"t'\\<parallel>u'\" by auto\n            with  kpq kpt tp qup show ?thesis using x d by blast}\n          next\n          { assume \"\\<not>?A\\<and>\\<not>?B\\<and>?C\" then have ?C by simp\n            then obtain t' where qtp:\"q\\<parallel>t'\" and tpu:\"t'\\<parallel>u\" by auto\n            from tp kp kl have \"t\\<parallel>l\" using M1 by auto\n            moreover with lpcp lpz lz have \"l\\<parallel>c'\" using M1 by auto\n            moreover with cpup qup qtp have \"c'\\<parallel>t'\" using M1 by auto\n            ultimately obtain lc where \"t\\<parallel>lc\" and \"lc\\<parallel>t'\" using M5exist_var by blast\n            with kpt tp kpq qtp tpu pu show ?thesis using x ov by blast}\n          qed}\n      qed\nqed\n\n\nlemma cdid:\"d^-1 O d \\<subseteq> e \\<union> ov \\<union> ov^-1 \\<union> d \\<union> d^-1 \\<union> s \\<union> s^-1 \\<union> f \\<union> f^-1 \"\nproof\n  fix x::\"'a\\<times>'a\" assume \"x \\<in> d^-1 O d\" then obtain p q z where x:\"x = (p,q)\" and \"(p,z) \\<in> d^-1\" and \"(z, q) \\<in> d\" by auto\n  from \\<open>(p,z) \\<in> d^-1\\<close> obtain k l u v where kp:\"k\\<parallel>p\" and kl:\"k\\<parallel>l\" and lz:\"l\\<parallel>z\" and pv:\"p\\<parallel>v\" and zu:\"z\\<parallel>u\" and uv:\"u\\<parallel>v\"  using d by blast\n  from \\<open>(z,q) \\<in> d\\<close> obtain k' l'  u' v'  where kpq:\"k'\\<parallel>q\" and kplp:\"k'\\<parallel>l'\" and lpz:\"l'\\<parallel>z\"  and qvp:\"q\\<parallel>v'\" and zup:\"z\\<parallel>u'\" and upvp:\"u'\\<parallel>v'\"  using d by blast\n\n  from kp kpq  have \"k\\<parallel>q \\<oplus> ((\\<exists>t. k\\<parallel>t \\<and> t\\<parallel>q) \\<oplus> (\\<exists>t. k'\\<parallel>t \\<and> t\\<parallel>p))\" (is \"?A \\<oplus> (?B \\<oplus> ?C)\") using M2 by blast\n  then have \"(?A\\<and>\\<not>?B\\<and>\\<not>?C) \\<or> ((\\<not>?A\\<and>?B\\<and>\\<not>?C) \\<or> (\\<not>?A\\<and>\\<not>?B\\<and>?C))\" by (insert xor_distr_L[of ?A ?B ?C], auto simp:elimmeets)\n  thus \"x \\<in> e \\<union> ov \\<union> ov^-1 \\<union> d \\<union> d^-1 \\<union> s \\<union> s^-1 \\<union> f \\<union> f^-1\"\n  proof (elim disjE)\n      { assume \"?A\\<and>\\<not>?B\\<and>\\<not>?C\" then have kq:?A by simp\n        from pv qvp have \"p\\<parallel>v' \\<oplus> ((\\<exists>t'. p\\<parallel>t' \\<and> t'\\<parallel>v') \\<oplus> (\\<exists>t'. q\\<parallel>t' \\<and> t'\\<parallel>v))\" (is \"?A \\<oplus> (?B \\<oplus> ?C)\") using M2 by blast\n        then have \"(?A\\<and>\\<not>?B\\<and>\\<not>?C) \\<or> ((\\<not>?A\\<and>?B\\<and>\\<not>?C) \\<or> (\\<not>?A\\<and>\\<not>?B\\<and>?C))\" by (insert xor_distr_L[of ?A ?B ?C], auto simp:elimmeets)\n        thus ?thesis\n        proof (elim disjE)\n          { assume \"?A\\<and>\\<not>?B\\<and>\\<not>?C\" then have ?A by simp\n            with kq kp qvp have \"p = q\" using M4 by auto\n            thus ?thesis using x e by auto}\n          next\n          { assume \"\\<not>?A\\<and>?B\\<and>\\<not>?C\" then have ?B by simp\n            with kq kp qvp show ?thesis using x s by blast}\n          next\n          { assume \"\\<not>?A\\<and>\\<not>?B\\<and>?C\" then have ?C by simp\n            with kq kp pv show ?thesis using x s by blast}\n        qed}\n      next\n      { assume \"\\<not>?A\\<and>?B\\<and>\\<not>?C\" then have ?B by simp\n        then obtain t where kt:\"k\\<parallel>t\" and tq:\"t\\<parallel>q\" by auto\n        from pv qvp have \"p\\<parallel>v' \\<oplus> ((\\<exists>t'. p\\<parallel>t' \\<and> t'\\<parallel>v') \\<oplus> (\\<exists>t'. q\\<parallel>t' \\<and> t'\\<parallel>v))\" (is \"?A \\<oplus> (?B \\<oplus> ?C)\") using M2 by blast\n        then have \"(?A\\<and>\\<not>?B\\<and>\\<not>?C) \\<or> ((\\<not>?A\\<and>?B\\<and>\\<not>?C) \\<or> (\\<not>?A\\<and>\\<not>?B\\<and>?C))\" by (insert xor_distr_L[of ?A ?B ?C], auto simp:elimmeets)\n        thus ?thesis\n        proof (elim disjE)\n          { assume \"?A\\<and>\\<not>?B\\<and>\\<not>?C\" then have ?A by simp\n            with qvp kp kt tq  show ?thesis using x f  by blast}\n          next\n          { assume \"\\<not>?A\\<and>?B\\<and>\\<not>?C\" then have ?B by simp\n            then obtain t' where ptp:\"p\\<parallel>t'\" and tpvp:\"t'\\<parallel>v'\" by auto\n            from tq kpq kplp have \"t\\<parallel>l'\" using M1 by auto\n            moreover with ptp pv uv have \"u\\<parallel>t'\" using M1 by auto\n            moreover with lpz zu \\<open>t\\<parallel>l'\\<close> obtain lzu where \"t\\<parallel>lzu\" and \"lzu\\<parallel>t'\" using  M5exist_var   by blast\n            ultimately  show ?thesis using x ov kt tq kp ptp tpvp qvp by blast}\n          next\n          { assume \"\\<not>?A\\<and>\\<not>?B\\<and>?C\" then have ?C by simp\n            with pv kp kt tq  show ?thesis using x d  by blast}\n\n        qed}\n      next\n      {assume \"\\<not>?A\\<and>\\<not>?B\\<and>?C\" then have ?C by auto\n       then obtain t where kpt:\"k'\\<parallel>t\" and tp:\"t\\<parallel>p\" by auto\n        from pv qvp have \"p\\<parallel>v' \\<oplus> ((\\<exists>t'. p\\<parallel>t' \\<and> t'\\<parallel>v') \\<oplus> (\\<exists>t'. q\\<parallel>t' \\<and> t'\\<parallel>v))\" (is \"?A \\<oplus> (?B \\<oplus> ?C)\") using M2 by blast\n        then have \"(?A\\<and>\\<not>?B\\<and>\\<not>?C) \\<or> ((\\<not>?A\\<and>?B\\<and>\\<not>?C) \\<or> (\\<not>?A\\<and>\\<not>?B\\<and>?C))\" by (insert xor_distr_L[of ?A ?B ?C], auto simp:elimmeets)\n        thus ?thesis\n        proof (elim disjE)\n          { assume \"?A\\<and>\\<not>?B\\<and>\\<not>?C\" then have ?A by simp\n            with kpq kpt tp qvp show ?thesis using x f  by blast}\n          next\n          { assume \"\\<not>?A\\<and>?B\\<and>\\<not>?C\" then have ?B by simp\n            then obtain t' where \"p\\<parallel>t'\" and \"t'\\<parallel>v'\" by auto\n            with  kpq kpt tp qvp show ?thesis using x d by blast}\n          next\n          { assume \"\\<not>?A\\<and>\\<not>?B\\<and>?C\" then have ?C by simp\n            then obtain t' where qtp:\"q\\<parallel>t'\" and tpv:\"t'\\<parallel>v\" by auto\n            from tp kp kl have \"t\\<parallel>l\" using M1 by auto\n            moreover with qtp qvp upvp have \"u'\\<parallel>t'\" using M1 by auto\n            moreover with lz zup \\<open>t\\<parallel>l\\<close> obtain lzu where \"t\\<parallel>lzu\" and \"lzu\\<parallel>t'\" using  M5exist_var by blast\n            ultimately show ?thesis using x ov kpt tp kpq qtp tpv pv  by blast}\n          qed}\n      qed\nqed\n\nlemma coviov:\"ov^-1 O ov \\<subseteq> e \\<union> ov \\<union> ov^-1 \\<union> d \\<union> d^-1 \\<union> s \\<union> s^-1 \\<union> f \\<union> f^-1\"\nproof\n  fix x::\"'a\\<times>'a\" assume \"x \\<in> ov^-1 O ov\" then obtain p q z where x:\"x = (p,q)\" and \"(p,z) \\<in> ov^-1\" and \"(z, q) \\<in> ov\" by auto\n  from \\<open>(p,z) \\<in> ov^-1\\<close> obtain k l c u v where kz:\"k\\<parallel>z\" and kl:\"k\\<parallel>l\" and lp:\"l\\<parallel>p\" and lc:\"l\\<parallel>c\" and zu:\"z\\<parallel>u\" and pv:\"p\\<parallel>v\" and cu:\"c\\<parallel>u\" and uv:\"u\\<parallel>v\"  using ov by blast\n  from \\<open>(z,q) \\<in> ov\\<close> obtain k' l' c' u' v' where kpz:\"k'\\<parallel>z\" and kplp:\"k'\\<parallel>l'\" and lpq:\"l'\\<parallel>q\" and lpcp:\"l'\\<parallel>c'\" and qvp:\"q\\<parallel>v'\" and zup:\"z\\<parallel>u'\" and cpup:\"c'\\<parallel>u'\" and upvp:\"u'\\<parallel>v'\" using ov by blast\n\n  from lp lpq  have \"l\\<parallel>q \\<oplus> ((\\<exists>t. l\\<parallel>t \\<and> t\\<parallel>q) \\<oplus> (\\<exists>t. l'\\<parallel>t \\<and> t\\<parallel>p))\" (is \"?A \\<oplus> (?B \\<oplus> ?C)\") using M2 by blast\n  then have \"(?A\\<and>\\<not>?B\\<and>\\<not>?C) \\<or> ((\\<not>?A\\<and>?B\\<and>\\<not>?C) \\<or> (\\<not>?A\\<and>\\<not>?B\\<and>?C))\" by (insert xor_distr_L[of ?A ?B ?C], auto simp:elimmeets)\n  thus \"x \\<in> e \\<union> ov \\<union> ov^-1 \\<union> d \\<union> d^-1 \\<union> s \\<union> s^-1 \\<union> f \\<union> f^-1\"\n  proof (elim disjE)\n      { assume \"?A\\<and>\\<not>?B\\<and>\\<not>?C\" then have lq:?A by simp\n        from pv qvp have \"p\\<parallel>v' \\<oplus> ((\\<exists>t'. p\\<parallel>t' \\<and> t'\\<parallel>v') \\<oplus> (\\<exists>t'. q\\<parallel>t' \\<and> t'\\<parallel>v))\" (is \"?A \\<oplus> (?B \\<oplus> ?C)\") using M2 by blast\n        then have \"(?A\\<and>\\<not>?B\\<and>\\<not>?C) \\<or> ((\\<not>?A\\<and>?B\\<and>\\<not>?C) \\<or> (\\<not>?A\\<and>\\<not>?B\\<and>?C))\" by (insert xor_distr_L[of ?A ?B ?C], auto simp:elimmeets)\n        thus ?thesis\n        proof (elim disjE)\n          { assume \"?A\\<and>\\<not>?B\\<and>\\<not>?C\" then have ?A by simp\n            with lq lp qvp have \"p = q\" using M4 by auto\n            thus ?thesis using x e by auto}\n          next\n          { assume \"\\<not>?A\\<and>?B\\<and>\\<not>?C\" then have ?B by simp\n            with lq lp qvp show ?thesis using x s by blast}\n          next\n          { assume \"\\<not>?A\\<and>\\<not>?B\\<and>?C\" then have ?C by simp\n            with lq lp pv show ?thesis using x s by blast}\n        qed}\n      next\n      { assume \"\\<not>?A\\<and>?B\\<and>\\<not>?C\" then have ?B by simp\n        then obtain t where lt:\"l\\<parallel>t\" and tq:\"t\\<parallel>q\" by auto\n        from pv qvp have \"p\\<parallel>v' \\<oplus> ((\\<exists>t'. p\\<parallel>t' \\<and> t'\\<parallel>v') \\<oplus> (\\<exists>t'. q\\<parallel>t' \\<and> t'\\<parallel>v))\" (is \"?A \\<oplus> (?B \\<oplus> ?C)\") using M2 by blast\n        then have \"(?A\\<and>\\<not>?B\\<and>\\<not>?C) \\<or> ((\\<not>?A\\<and>?B\\<and>\\<not>?C) \\<or> (\\<not>?A\\<and>\\<not>?B\\<and>?C))\" by (insert xor_distr_L[of ?A ?B ?C], auto simp:elimmeets)\n        thus ?thesis\n        proof (elim disjE)\n          { assume \"?A\\<and>\\<not>?B\\<and>\\<not>?C\" then have ?A by simp\n            with qvp lp lt tq  show ?thesis using x f  by blast}\n          next\n          { assume \"\\<not>?A\\<and>?B\\<and>\\<not>?C\" then have ?B by simp\n            then obtain t' where ptp:\"p\\<parallel>t'\" and tpvp:\"t'\\<parallel>v'\" by auto\n            from tq lpq lpcp have \"t\\<parallel>c'\" using M1 by auto\n            moreover with cpup zup zu have \"c'\\<parallel>u\" using M1 by auto\n            moreover with ptp pv uv have \"u\\<parallel>t'\" using M1 by auto\n            ultimately obtain cu where \"t\\<parallel>cu\" and \"cu\\<parallel>t'\" using M5exist_var by blast\n            with lt tq lp ptp tpvp qvp  show ?thesis using x ov by blast}\n          next\n          { assume \"\\<not>?A\\<and>\\<not>?B\\<and>?C\" then have ?C by simp\n            with pv lp lt tq  show ?thesis using x d  by blast}\n\n        qed}\n      next\n      {assume \"\\<not>?A\\<and>\\<not>?B\\<and>?C\" then have ?C by auto\n       then obtain t where lpt:\"l'\\<parallel>t\" and tp:\"t\\<parallel>p\" by auto\n        from pv qvp have \"p\\<parallel>v' \\<oplus> ((\\<exists>t'. p\\<parallel>t' \\<and> t'\\<parallel>v') \\<oplus> (\\<exists>t'. q\\<parallel>t' \\<and> t'\\<parallel>v))\" (is \"?A \\<oplus> (?B \\<oplus> ?C)\") using M2 by blast\n        then have \"(?A\\<and>\\<not>?B\\<and>\\<not>?C) \\<or> ((\\<not>?A\\<and>?B\\<and>\\<not>?C) \\<or> (\\<not>?A\\<and>\\<not>?B\\<and>?C))\" by (insert xor_distr_L[of ?A ?B ?C], auto simp:elimmeets)\n        thus ?thesis\n        proof (elim disjE)\n          { assume \"?A\\<and>\\<not>?B\\<and>\\<not>?C\" then have ?A by simp\n            with qvp lpq lpt tp show ?thesis using x f  by blast}\n          next\n          { assume \"\\<not>?A\\<and>?B\\<and>\\<not>?C\" then have ?B by simp\n            then obtain t' where \"p\\<parallel>t'\" and \"t'\\<parallel>v'\" by auto\n            with  qvp lpq lpt tp show ?thesis using x d by blast}\n          next\n          { assume \"\\<not>?A\\<and>\\<not>?B\\<and>?C\" then have ?C by simp\n            then obtain t' where qtp:\"q\\<parallel>t'\" and tpv:\"t'\\<parallel>v\" by auto\n            from tp lp lc have \"t\\<parallel>c\" using M1 by auto\n            moreover with cu zu zup have \"c\\<parallel>u'\" using M1 by auto\n            moreover with qtp qvp upvp have \"u'\\<parallel>t'\" using M1 by auto\n            ultimately obtain cu where \"t\\<parallel>cu\" and \"cu\\<parallel>t'\" using M5exist_var by blast\n            with lpt tp lpq pv qtp tpv show ?thesis using x ov by blast}\n          qed}\n      qed\nqed\n\n(* ===========$\\delta$ composition =========*)\nsubsection \\<open>$\\gamma$-composition\\<close>\ntext \\<open>We prove compositions of the form $r_1 \\circ r_2 \\subseteq b \\cup m \\cup ov \\cup s \\cup d \\cup f \\cup e \\cup f^{-1} \\cup d^{-1} \\cup s^{-1} \\cup ov^{-1} \\cup b^{-1} \\cup m^{-1}$.\\<close>\n\n\nlemma cbbi:\"b O b^-1 \\<subseteq> b \\<union> b^-1 \\<union> m \\<union> m^-1 \\<union> e \\<union> ov \\<union> ov^-1 \\<union> s \\<union> s^-1 \\<union> d \\<union> d^-1 \\<union> f \\<union> f^-1\" (is \"b O b^-1 \\<subseteq> ?R\")\nproof\n  fix x::\"'a\\<times>'a\" assume \"x \\<in> b O b^-1\" then obtain p q z::'a where x:\"x = (p,q)\" and \"(p,z) \\<in> b\" and \"(z,q) \\<in> b^-1\" by auto\n  from \\<open>(p,z)\\<in>b\\<close> obtain c where pc:\"p\\<parallel>c\" and \"c\\<parallel>z\" using b  by blast\n  from \\<open>(z,q) \\<in> b^-1\\<close> obtain c' where qcp:\"q\\<parallel>c'\" and \"c'\\<parallel>z\" using b  by blast\n  obtain k k' where kp:\"k\\<parallel>p\" and kpq:\"k'\\<parallel>q\" using M3 meets_wd pc qcp by fastforce\n  then have \"k\\<parallel>q \\<oplus> ((\\<exists>t. k\\<parallel>t \\<and> t\\<parallel>q) \\<oplus> (\\<exists>t. k'\\<parallel>t \\<and> t\\<parallel>p))\" (is \"?A \\<oplus> (?B \\<oplus> ?C)\") using M2 by blast\n  then have \"(?A\\<and>\\<not>?B\\<and>\\<not>?C) \\<or> ((\\<not>?A\\<and>?B\\<and>\\<not>?C) \\<or> (\\<not>?A\\<and>\\<not>?B\\<and>?C))\" by (insert xor_distr_L[of ?A ?B ?C], auto simp:elimmeets)\n  thus \"x \\<in>?R\"\n  proof (elim disjE)\n      { assume \"?A\\<and>\\<not>?B\\<and>\\<not>?C\" then have kq:?A by simp\n        from pc qcp have \"p\\<parallel>c' \\<oplus> ((\\<exists>t'. p\\<parallel>t' \\<and> t'\\<parallel>c') \\<oplus> (\\<exists>t'. q\\<parallel>t' \\<and> t'\\<parallel>c))\" (is \"?A \\<oplus> (?B \\<oplus> ?C)\") using M2 by blast\n        then have \"(?A\\<and>\\<not>?B\\<and>\\<not>?C) \\<or> ((\\<not>?A\\<and>?B\\<and>\\<not>?C) \\<or> (\\<not>?A\\<and>\\<not>?B\\<and>?C))\" by (insert xor_distr_L[of ?A ?B ?C], auto simp:elimmeets)\n        thus ?thesis\n        proof (elim disjE)\n          {assume \"(?A\\<and>\\<not>?B\\<and>\\<not>?C)\" then have \"?A\" by simp\n           with kp kq qcp have \"p = q\" using M4 by auto\n           thus ?thesis using x e  by auto}\n          next\n          {assume \"\\<not>?A\\<and>?B\\<and>\\<not>?C\" then have \"?B\" by simp\n           with kq kp qcp show ?thesis using x s by blast}\n          next\n          {assume \"(\\<not>?A\\<and>\\<not>?B\\<and>?C)\" then have \"?C\" by simp\n           with kq kp pc show ?thesis using x s by blast}\n        qed}\n      next\n      { assume \"\\<not>?A\\<and>?B\\<and>\\<not>?C\" then have ?B by simp\n        then obtain t where kt:\"k\\<parallel>t\" and tq:\"t\\<parallel>q\" by auto\n        from pc qcp have \"p\\<parallel>c' \\<oplus> ((\\<exists>t'. p\\<parallel>t' \\<and> t'\\<parallel>c') \\<oplus> (\\<exists>t'. q\\<parallel>t' \\<and> t'\\<parallel>c))\" (is \"?A \\<oplus> (?B \\<oplus> ?C)\") using M2 by blast\n        then have \"(?A\\<and>\\<not>?B\\<and>\\<not>?C) \\<or> ((\\<not>?A\\<and>?B\\<and>\\<not>?C) \\<or> (\\<not>?A\\<and>\\<not>?B\\<and>?C))\" by (insert xor_distr_L[of ?A ?B ?C], auto simp:elimmeets)\n        thus ?thesis\n        proof (elim disjE)\n          {assume \"?A\\<and>\\<not>?B\\<and>\\<not>?C\" then have ?A by simp\n           with kp qcp kt tq show ?thesis using f x by blast}\n          next\n          {assume \"\\<not>?A\\<and>?B\\<and>\\<not>?C\"  then have ?B by simp\n           then obtain t' where ptp:\"p\\<parallel>t'\" and tpcp:\"t'\\<parallel>c'\" by auto\n           from pc tq  have \"p\\<parallel>q \\<oplus> ((\\<exists>t''. p\\<parallel>t'' \\<and> t''\\<parallel>q) \\<oplus> (\\<exists>t''. t\\<parallel>t'' \\<and> t''\\<parallel>c))\" (is \"?A \\<oplus> (?B \\<oplus> ?C)\") using M2 by blast\n           then have \"(?A\\<and>\\<not>?B\\<and>\\<not>?C) \\<or> ((\\<not>?A\\<and>?B\\<and>\\<not>?C) \\<or> (\\<not>?A\\<and>\\<not>?B\\<and>?C))\" by (insert xor_distr_L[of ?A ?B ?C], auto simp:elimmeets)\n           thus ?thesis\n           proof (elim disjE)\n              {assume \"?A\\<and>\\<not>?B\\<and>\\<not>?C\" then have ?A by simp\n               thus ?thesis using x m by auto}\n              next\n              {assume \"\\<not>?A\\<and>?B\\<and>\\<not>?C\" then have ?B by simp\n               thus ?thesis using x b by auto}\n              next\n              { assume \"\\<not>?A\\<and>\\<not>?B\\<and>?C\" then have ?C by simp\n                then obtain g where \"t\\<parallel>g\" and \"g\\<parallel>c\" by auto\n                moreover with pc ptp have \"g\\<parallel>t'\" using M1 by blast\n                ultimately  show ?thesis using x ov kt tq kp ptp tpcp qcp   by blast}\n           qed}\n         next\n          {assume \"\\<not>?A\\<and>\\<not>?B\\<and>?C\" then have ?C by simp\n           then obtain t' where \"q\\<parallel>t'\" and \"t'\\<parallel>c\" by auto\n           with kp  kt tq pc show ?thesis using d x by blast}\n         qed}\n      next\n      { assume \"\\<not>?A\\<and>\\<not>?B\\<and>?C\" then have ?C by simp\n        then obtain t where kpt:\"k'\\<parallel>t\" and tp:\"t\\<parallel>p\" by auto\n        from  pc qcp have \"p\\<parallel>c' \\<oplus> ((\\<exists>t'. p\\<parallel>t' \\<and> t'\\<parallel>c') \\<oplus> (\\<exists>t'. q\\<parallel>t' \\<and> t'\\<parallel>c))\" (is \"?A \\<oplus> (?B \\<oplus> ?C)\") using M2 by blast\n        then have \"(?A\\<and>\\<not>?B\\<and>\\<not>?C) \\<or> ((\\<not>?A\\<and>?B\\<and>\\<not>?C) \\<or> (\\<not>?A\\<and>\\<not>?B\\<and>?C))\" by (insert xor_distr_L[of ?A ?B ?C], auto simp:elimmeets)\n        thus ?thesis\n        proof (elim disjE)\n          {assume \"?A\\<and>\\<not>?B\\<and>\\<not>?C\" then have ?A by simp\n           with qcp kpt tp kpq show ?thesis using x f by blast}\n          next\n          {assume \"\\<not>?A\\<and>?B\\<and>\\<not>?C\" then have ?B by simp\n           with qcp kpt tp kpq show ?thesis using x d by blast}\n          next\n          {assume \"\\<not>?A\\<and>\\<not>?B\\<and>?C\" then obtain t' where qt':\"q\\<parallel>t'\" and tpc:\"t'\\<parallel>c\" by auto\n           from qcp tp have \"q\\<parallel>p \\<oplus> ((\\<exists>t''. q\\<parallel>t'' \\<and> t''\\<parallel>p) \\<oplus> (\\<exists>t''. t\\<parallel>t'' \\<and> t''\\<parallel>c'))\" (is \"?A \\<oplus> (?B \\<oplus> ?C)\") using M2 by blast\n           then have \"(?A\\<and>\\<not>?B\\<and>\\<not>?C) \\<or> ((\\<not>?A\\<and>?B\\<and>\\<not>?C) \\<or> (\\<not>?A\\<and>\\<not>?B\\<and>?C))\" by (insert xor_distr_L[of ?A ?B ?C], auto simp:elimmeets)\n           thus ?thesis\n           proof (elim disjE)\n              {assume \"?A\\<and>\\<not>?B\\<and>\\<not>?C\" then have ?A by simp\n               thus ?thesis using x m by auto}\n              next\n              {assume \"\\<not>?A\\<and>?B\\<and>\\<not>?C\" then have ?B by simp\n               thus ?thesis using x b by auto}\n              next\n              { assume \"\\<not>?A\\<and>\\<not>?B\\<and>?C\" then obtain g where tg:\"t\\<parallel>g\" and \"g\\<parallel>c'\" by auto\n                with qcp qt' have \"g\\<parallel>t'\" using M1 by blast\n                with qt' tpc pc kpq kpt tp tg show ?thesis using x ov by blast}\n          qed}\n     qed}\n qed\nqed\n       \n\n\nlemma cbib:\"b^-1 O b \\<subseteq> b \\<union> b^-1 \\<union> m \\<union> m^-1 \\<union> e \\<union> ov \\<union> ov^-1 \\<union> s \\<union> s^-1 \\<union> d \\<union> d^-1 \\<union> f \\<union> f^-1\" (is \"b^-1 O b \\<subseteq> ?R\")\nproof\n  fix x::\"'a\\<times>'a\" assume \"x \\<in> b^-1 O b\" then obtain p q z::'a where x:\"x = (p,q)\" and \"(p,z) \\<in> b^-1\" and \"(z,q) \\<in> b\" by auto\n  from \\<open>(p,z)\\<in>b^-1\\<close> obtain c where zc:\"z\\<parallel>c\" and cp:\"c\\<parallel>p\" using b  by blast\n  from \\<open>(z,q) \\<in> b\\<close> obtain c' where zcp:\"z\\<parallel>c'\" and cpq:\"c'\\<parallel>q\" using b  by blast\n  obtain u u' where pu:\"p\\<parallel>u\" and qup:\"q\\<parallel>u'\" using M3 meets_wd cp cpq by fastforce\n  from cp cpq have \"c\\<parallel>q \\<oplus> ((\\<exists>t. c\\<parallel>t \\<and> t\\<parallel>q) \\<oplus> (\\<exists>t. c'\\<parallel>t \\<and> t\\<parallel>p))\" (is \"?A \\<oplus> (?B \\<oplus> ?C)\") using M2 by blast\n  then have \"(?A\\<and>\\<not>?B\\<and>\\<not>?C) \\<or> ((\\<not>?A\\<and>?B\\<and>\\<not>?C) \\<or> (\\<not>?A\\<and>\\<not>?B\\<and>?C))\" by (insert xor_distr_L[of ?A ?B ?C], auto simp:elimmeets)\n  thus \"x \\<in>?R\"\n  proof (elim disjE)\n      { assume \"?A\\<and>\\<not>?B\\<and>\\<not>?C\" then have cq:?A by simp\n        from pu qup have \"p\\<parallel>u' \\<oplus> ((\\<exists>t'. p\\<parallel>t' \\<and> t'\\<parallel>u') \\<oplus> (\\<exists>t'. q\\<parallel>t' \\<and> t'\\<parallel>u))\" (is \"?A \\<oplus> (?B \\<oplus> ?C)\") using M2 by blast\n        then have \"(?A\\<and>\\<not>?B\\<and>\\<not>?C) \\<or> ((\\<not>?A\\<and>?B\\<and>\\<not>?C) \\<or> (\\<not>?A\\<and>\\<not>?B\\<and>?C))\" by (insert xor_distr_L[of ?A ?B ?C], auto simp:elimmeets)\n        thus ?thesis\n        proof (elim disjE)\n          {assume \"(?A\\<and>\\<not>?B\\<and>\\<not>?C)\" then have \"?A\" by simp\n           with cq cp qup have \"p = q\" using M4 by auto\n           thus ?thesis using x e  by auto}\n          next\n          {assume \"\\<not>?A\\<and>?B\\<and>\\<not>?C\" then have \"?B\" by simp\n           with cq cp qup show ?thesis using x s by blast}\n          next\n          {assume \"(\\<not>?A\\<and>\\<not>?B\\<and>?C)\" then have \"?C\" by simp\n           with pu cq cp show ?thesis using x s by blast}\n        qed}\n      next\n      { assume \"\\<not>?A\\<and>?B\\<and>\\<not>?C\" then have ?B by simp\n        then obtain t where ct:\"c\\<parallel>t\" and tq:\"t\\<parallel>q\" by auto\n        from pu qup have \"p\\<parallel>u' \\<oplus> ((\\<exists>t'. p\\<parallel>t' \\<and> t'\\<parallel>u') \\<oplus> (\\<exists>t'. q\\<parallel>t' \\<and> t'\\<parallel>u))\" (is \"?A \\<oplus> (?B \\<oplus> ?C)\") using M2 by blast\n        then have \"(?A\\<and>\\<not>?B\\<and>\\<not>?C) \\<or> ((\\<not>?A\\<and>?B\\<and>\\<not>?C) \\<or> (\\<not>?A\\<and>\\<not>?B\\<and>?C))\" by (insert xor_distr_L[of ?A ?B ?C], auto simp:elimmeets)\n        thus ?thesis\n        proof (elim disjE)\n          {assume \"?A\\<and>\\<not>?B\\<and>\\<not>?C\" then have ?A by simp\n           with qup ct tq cp show ?thesis using f x by blast}\n          next\n          {assume \"\\<not>?A\\<and>?B\\<and>\\<not>?C\"  then have ?B by simp\n           then obtain t' where ptp:\"p\\<parallel>t'\" and tpup:\"t'\\<parallel>u'\" by auto\n           from pu tq  have \"p\\<parallel>q \\<oplus> ((\\<exists>t''. p\\<parallel>t'' \\<and> t''\\<parallel>q) \\<oplus> (\\<exists>t''. t\\<parallel>t'' \\<and> t''\\<parallel>u))\" (is \"?A \\<oplus> (?B \\<oplus> ?C)\") using M2 by blast\n           then have \"(?A\\<and>\\<not>?B\\<and>\\<not>?C) \\<or> ((\\<not>?A\\<and>?B\\<and>\\<not>?C) \\<or> (\\<not>?A\\<and>\\<not>?B\\<and>?C))\" by (insert xor_distr_L[of ?A ?B ?C], auto simp:elimmeets)\n           thus ?thesis\n           proof (elim disjE)\n              {assume \"?A\\<and>\\<not>?B\\<and>\\<not>?C\" then have ?A by simp\n               thus ?thesis using x m by auto}\n              next\n              {assume \"\\<not>?A\\<and>?B\\<and>\\<not>?C\" then have ?B by simp\n               thus ?thesis using x b by auto}\n              next\n              { assume \"\\<not>?A\\<and>\\<not>?B\\<and>?C\" then have ?C by simp\n                then obtain g where \"t\\<parallel>g\" and \"g\\<parallel>u\" by auto\n                moreover with pu ptp have \"g\\<parallel>t'\" using M1 by blast\n                ultimately  show ?thesis using x ov ct tq cp ptp tpup qup   by blast}\n           qed}\n         next\n          {assume \"\\<not>?A\\<and>\\<not>?B\\<and>?C\" then have ?C by simp\n           then obtain t' where \"q\\<parallel>t'\" and \"t'\\<parallel>u\" by auto\n           with cp  ct tq pu  show ?thesis using d x by blast}\n         qed}\n      next\n      { assume \"\\<not>?A\\<and>\\<not>?B\\<and>?C\" then have ?C by simp\n        then obtain t where cpt:\"c'\\<parallel>t\" and tp:\"t\\<parallel>p\" by auto\n        from  pu qup have \"p\\<parallel>u' \\<oplus> ((\\<exists>t'. p\\<parallel>t' \\<and> t'\\<parallel>u') \\<oplus> (\\<exists>t'. q\\<parallel>t' \\<and> t'\\<parallel>u))\" (is \"?A \\<oplus> (?B \\<oplus> ?C)\") using M2 by blast\n        then have \"(?A\\<and>\\<not>?B\\<and>\\<not>?C) \\<or> ((\\<not>?A\\<and>?B\\<and>\\<not>?C) \\<or> (\\<not>?A\\<and>\\<not>?B\\<and>?C))\" by (insert xor_distr_L[of ?A ?B ?C], auto simp:elimmeets)\n        thus ?thesis\n        proof (elim disjE)\n          {assume \"?A\\<and>\\<not>?B\\<and>\\<not>?C\" then have ?A by simp\n           with qup cpt tp cpq show ?thesis using x f by blast}\n          next\n          {assume \"\\<not>?A\\<and>?B\\<and>\\<not>?C\" then have ?B by simp\n           with qup cpt tp cpq show ?thesis using x d by blast}\n          next\n          {assume \"\\<not>?A\\<and>\\<not>?B\\<and>?C\" then obtain t' where qt':\"q\\<parallel>t'\" and tpc:\"t'\\<parallel>u\" by auto\n           from qup tp have \"q\\<parallel>p \\<oplus> ((\\<exists>t''. q\\<parallel>t'' \\<and> t''\\<parallel>p) \\<oplus> (\\<exists>t''. t\\<parallel>t'' \\<and> t''\\<parallel>u'))\" (is \"?A \\<oplus> (?B \\<oplus> ?C)\") using M2 by blast\n           then have \"(?A\\<and>\\<not>?B\\<and>\\<not>?C) \\<or> ((\\<not>?A\\<and>?B\\<and>\\<not>?C) \\<or> (\\<not>?A\\<and>\\<not>?B\\<and>?C))\" by (insert xor_distr_L[of ?A ?B ?C], auto simp:elimmeets)\n           thus ?thesis\n           proof (elim disjE)\n              {assume \"?A\\<and>\\<not>?B\\<and>\\<not>?C\" then have ?A by simp\n               thus ?thesis using x m by auto}\n              next\n              {assume \"\\<not>?A\\<and>?B\\<and>\\<not>?C\" then have ?B by simp\n               thus ?thesis using x b by auto}\n              next\n              { assume \"\\<not>?A\\<and>\\<not>?B\\<and>?C\" then obtain g where tg:\"t\\<parallel>g\" and \"g\\<parallel>u'\" by auto\n                with qup qt' have \"g\\<parallel>t'\" using M1 by blast\n                with qt' tpc pu cpq cpt tp tg show ?thesis using x ov by blast}\n          qed}\n     qed}\n qed\nqed\n\nlemma cddi:\"d O d^-1 \\<subseteq> b \\<union> b^-1 \\<union> m \\<union> m^-1 \\<union> e \\<union> ov \\<union> ov^-1 \\<union> s \\<union> s^-1 \\<union> d \\<union> d^-1 \\<union> f \\<union> f^-1\" (is \"d O d^-1 \\<subseteq> ?R\")\nproof\n  fix x::\"'a\\<times>'a\" assume \"x \\<in> d O d^-1\" then obtain p q z::'a where x:\"x = (p,q)\" and \"(p,z) \\<in> d\" and \"(z,q) \\<in> d^-1\" by auto\n  from \\<open>(p,z) \\<in> d\\<close> obtain k l u v where lp:\"l\\<parallel>p\" and kl:\"k\\<parallel>l\" and kz:\"k\\<parallel>z\" and pu:\"p\\<parallel>u\" and uv:\"u\\<parallel>v\" and zv:\"z\\<parallel>v\"  using d  by blast\n  from \\<open>(z,q) \\<in> d^-1\\<close> obtain k' l' u' v' where lpq:\"l'\\<parallel>q\" and kplp:\"k'\\<parallel>l'\" and kpz:\"k'\\<parallel>z\" and qup:\"q\\<parallel>u'\" and upvp:\"u'\\<parallel>v'\" and zv':\"z\\<parallel>v'\"  using d  by blast\n  from lp lpq have \"l\\<parallel>q \\<oplus> ((\\<exists>t. l\\<parallel>t \\<and> t\\<parallel>q) \\<oplus> (\\<exists>t. l'\\<parallel>t \\<and> t\\<parallel>p))\" (is \"?A \\<oplus> (?B \\<oplus> ?C)\") using M2 by blast\n  then have \"(?A\\<and>\\<not>?B\\<and>\\<not>?C) \\<or> ((\\<not>?A\\<and>?B\\<and>\\<not>?C) \\<or> (\\<not>?A\\<and>\\<not>?B\\<and>?C))\" by (insert xor_distr_L[of ?A ?B ?C], auto simp:elimmeets)\n  thus \"x \\<in>?R\"\n  proof (elim disjE)\n      { assume \"?A\\<and>\\<not>?B\\<and>\\<not>?C\" then have lq:?A by simp\n        from pu qup have \"p\\<parallel>u' \\<oplus> ((\\<exists>t'. p\\<parallel>t' \\<and> t'\\<parallel>u') \\<oplus> (\\<exists>t'. q\\<parallel>t' \\<and> t'\\<parallel>u))\" (is \"?A \\<oplus> (?B \\<oplus> ?C)\") using M2 by blast\n        then have \"(?A\\<and>\\<not>?B\\<and>\\<not>?C) \\<or> ((\\<not>?A\\<and>?B\\<and>\\<not>?C) \\<or> (\\<not>?A\\<and>\\<not>?B\\<and>?C))\" by (insert xor_distr_L[of ?A ?B ?C], auto simp:elimmeets)\n        thus ?thesis\n        proof (elim disjE)\n          {assume \"(?A\\<and>\\<not>?B\\<and>\\<not>?C)\" then have \"?A\" by simp\n           with lq lp qup have \"p = q\" using M4 by auto\n           thus ?thesis using x e  by auto}\n          next\n          {assume \"\\<not>?A\\<and>?B\\<and>\\<not>?C\" then have \"?B\" by simp\n           with lq lp qup show ?thesis using x s by blast}\n          next\n          {assume \"(\\<not>?A\\<and>\\<not>?B\\<and>?C)\" then have \"?C\" by simp\n           with pu lq lp show ?thesis using x s by blast}\n        qed}\n      next\n      { assume \"\\<not>?A\\<and>?B\\<and>\\<not>?C\" then have ?B by simp\n        then obtain t where lt:\"l\\<parallel>t\" and tq:\"t\\<parallel>q\" by auto\n        from pu qup have \"p\\<parallel>u' \\<oplus> ((\\<exists>t'. p\\<parallel>t' \\<and> t'\\<parallel>u') \\<oplus> (\\<exists>t'. q\\<parallel>t' \\<and> t'\\<parallel>u))\" (is \"?A \\<oplus> (?B \\<oplus> ?C)\") using M2 by blast\n        then have \"(?A\\<and>\\<not>?B\\<and>\\<not>?C) \\<or> ((\\<not>?A\\<and>?B\\<and>\\<not>?C) \\<or> (\\<not>?A\\<and>\\<not>?B\\<and>?C))\" by (insert xor_distr_L[of ?A ?B ?C], auto simp:elimmeets)\n        thus ?thesis\n        proof (elim disjE)\n          {assume \"?A\\<and>\\<not>?B\\<and>\\<not>?C\" then have ?A by simp\n           with qup lt tq lp show ?thesis using f x by blast}\n          next\n          {assume \"\\<not>?A\\<and>?B\\<and>\\<not>?C\"  then have ?B by simp\n           then obtain t' where ptp:\"p\\<parallel>t'\" and tpup:\"t'\\<parallel>u'\" by auto\n           from pu tq  have \"p\\<parallel>q \\<oplus> ((\\<exists>t''. p\\<parallel>t'' \\<and> t''\\<parallel>q) \\<oplus> (\\<exists>t''. t\\<parallel>t'' \\<and> t''\\<parallel>u))\" (is \"?A \\<oplus> (?B \\<oplus> ?C)\") using M2 by blast\n           then have \"(?A\\<and>\\<not>?B\\<and>\\<not>?C) \\<or> ((\\<not>?A\\<and>?B\\<and>\\<not>?C) \\<or> (\\<not>?A\\<and>\\<not>?B\\<and>?C))\" by (insert xor_distr_L[of ?A ?B ?C], auto simp:elimmeets)\n           thus ?thesis\n           proof (elim disjE)\n              {assume \"?A\\<and>\\<not>?B\\<and>\\<not>?C\" then have ?A by simp\n               thus ?thesis using x m by auto}\n              next\n              {assume \"\\<not>?A\\<and>?B\\<and>\\<not>?C\" then have ?B by simp\n               thus ?thesis using x b by auto}\n              next\n              { assume \"\\<not>?A\\<and>\\<not>?B\\<and>?C\" then have ?C by simp\n                then obtain g where \"t\\<parallel>g\" and \"g\\<parallel>u\" by auto\n                moreover with pu ptp have \"g\\<parallel>t'\" using M1 by blast\n                ultimately  show ?thesis using x ov lt tq lp ptp tpup qup by blast}\n           qed}\n         next\n          {assume \"\\<not>?A\\<and>\\<not>?B\\<and>?C\" then have ?C by simp\n           then obtain t' where \"q\\<parallel>t'\" and \"t'\\<parallel>u\" by auto\n           with lp  lt tq pu  show ?thesis using d x by blast}\n         qed}\n      next\n      { assume \"\\<not>?A\\<and>\\<not>?B\\<and>?C\" then have ?C by simp\n        then obtain t where lpt:\"l'\\<parallel>t\" and tp:\"t\\<parallel>p\" by auto\n        from  pu qup have \"p\\<parallel>u' \\<oplus> ((\\<exists>t'. p\\<parallel>t' \\<and> t'\\<parallel>u') \\<oplus> (\\<exists>t'. q\\<parallel>t' \\<and> t'\\<parallel>u))\" (is \"?A \\<oplus> (?B \\<oplus> ?C)\") using M2 by blast\n        then have \"(?A\\<and>\\<not>?B\\<and>\\<not>?C) \\<or> ((\\<not>?A\\<and>?B\\<and>\\<not>?C) \\<or> (\\<not>?A\\<and>\\<not>?B\\<and>?C))\" by (insert xor_distr_L[of ?A ?B ?C], auto simp:elimmeets)\n        thus ?thesis\n        proof (elim disjE)\n          {assume \"?A\\<and>\\<not>?B\\<and>\\<not>?C\" then have ?A by simp\n           with qup lpt tp lpq show ?thesis using x f by blast}\n          next\n          {assume \"\\<not>?A\\<and>?B\\<and>\\<not>?C\" then have ?B by simp\n           with qup lpt tp lpq show ?thesis using x d by blast}\n          next\n          {assume \"\\<not>?A\\<and>\\<not>?B\\<and>?C\" then obtain t' where qt':\"q\\<parallel>t'\" and tpc:\"t'\\<parallel>u\" by auto\n           from qup tp have \"q\\<parallel>p \\<oplus> ((\\<exists>t''. q\\<parallel>t'' \\<and> t''\\<parallel>p) \\<oplus> (\\<exists>t''. t\\<parallel>t'' \\<and> t''\\<parallel>u'))\" (is \"?A \\<oplus> (?B \\<oplus> ?C)\") using M2 by blast\n           then have \"(?A\\<and>\\<not>?B\\<and>\\<not>?C) \\<or> ((\\<not>?A\\<and>?B\\<and>\\<not>?C) \\<or> (\\<not>?A\\<and>\\<not>?B\\<and>?C))\" by (insert xor_distr_L[of ?A ?B ?C], auto simp:elimmeets)\n           thus ?thesis\n           proof (elim disjE)\n              {assume \"?A\\<and>\\<not>?B\\<and>\\<not>?C\" then have ?A by simp\n               thus ?thesis using x m by auto}\n              next\n              {assume \"\\<not>?A\\<and>?B\\<and>\\<not>?C\" then have ?B by simp\n               thus ?thesis using x b by auto}\n              next\n              { assume \"\\<not>?A\\<and>\\<not>?B\\<and>?C\" then obtain g where tg:\"t\\<parallel>g\" and \"g\\<parallel>u'\" by auto\n                with qup qt' have \"g\\<parallel>t'\" using M1 by blast\n                with qt' tpc pu lpq lpt tp tg show ?thesis using x ov by blast}\n          qed}\n     qed}\n qed\nqed\n\n\n(* ========= inverse ========== *)\nsubsection \\<open>The rest of the composition table\\<close>\ntext \\<open>Because of the symmetry $(r_1 \\circ r_2)^{-1} = r_2^{-1} \\circ r_1^{-1} $, the rest of the compositions is easily deduced.\\<close>\n\n\nlemma cmbi:\"m O b^-1 \\<subseteq> b^-1 \\<union> m^-1 \\<union> s^-1 \\<union> ov^-1 \\<union> d^-1\"\n  using cbmi by auto\n\n\nlemma covmi:\"ov O m^-1 \\<subseteq> ov^-1 \\<union> d^-1 \\<union> s^-1\"\n  using  cmovi by auto\n\nlemma covbi:\"ov O b^-1 \\<subseteq> b^-1 \\<union> m^-1 \\<union> s^-1 \\<union> ov^-1 \\<union> d^-1\"\n  using cbovi by auto\n\nlemma cfiovi:\"f^-1 O ov^-1 \\<subseteq> ov^-1 \\<union> s^-1 \\<union> d^-1\"\n  using covf by auto\n\nlemma cfimi:\"(f^-1 O m^-1) \\<subseteq> s^-1 \\<union> ov^-1 \\<union> d^-1\"\n  using cmf by auto\n\nlemma cfibi:\"f^-1 O b^-1 \\<subseteq> b^-1 \\<union> m^-1 \\<union> ov^-1 \\<union> s^-1 \\<union> d^-1\"\n  using cbf by auto\n\nlemma cdif:\"d^-1 O f \\<subseteq> ov^-1 \\<union> s^-1 \\<union> d^-1\"\n  using cfid by auto\n\nlemma cdiovi:\"d^-1 O ov ^-1 \\<subseteq> ov^-1 \\<union> s^-1 \\<union> d^-1\"\n  using covd by auto\n\nlemma cdimi:\"d^-1 O m^-1 \\<subseteq> s^-1 \\<union> ov^-1 \\<union> d^-1 \"\n  using cmd by auto\n\nlemma cdibi:\"d^-1 O b^-1 \\<subseteq> b^-1 \\<union> m^-1 \\<union> ov^-1 \\<union> s^-1 \\<union> d^-1\"\n  using cbd by auto \n\nlemma csd:\"s O d \\<subseteq> d\"\n  using cdisi by auto\n\nlemma csf:\"s O f \\<subseteq> d\"\n  using cfisi by auto\n\nlemma csovi:\"s O ov^-1 \\<subseteq> ov^-1 \\<union> f \\<union> d\"\n  using covsi by auto\n\n\n\nlemma csbi:\"s O b^-1 \\<subseteq> b^-1\"\n  using cbsi by auto\n\nlemma csisi:\"s^-1 O s^-1 \\<subseteq> s^-1\"\n  using css by auto\n\nlemma csid:\"s^-1 O d \\<subseteq> ov^-1 \\<union> f \\<union> d\"\n  using cdis by auto\n\nlemma csif:\"s^-1 O f \\<subseteq> ov^-1\"\n  using cfis by auto\n\nlemma csiovi:\"s^-1 O ov^-1 \\<subseteq> ov^-1\"\n  using covs by auto\n\nlemma csimi:\"s^-1 O m^-1 \\<subseteq> m^-1\"\n  using cms by auto\n\nlemma csibi:\"s^-1 O b^-1 \\<subseteq> b^-1\"\n  using cbs by auto\n\nlemma cds:\"d O s \\<subseteq> d\"\n  using csidi by auto\n\nlemma cdsi:\"d O s^-1 \\<subseteq> b^-1 \\<union> m^-1 \\<union> ov^-1 \\<union> f \\<union> d\"\n  using csdi by auto\n\nlemma cdd:\"d O d \\<subseteq> d\"\n  using cdidi by auto\n\nlemma cdf:\"d O f \\<subseteq> d\" \n  using cfidi by auto\n\nlemma cdovi:\"d O ov^-1 \\<subseteq> b^-1 \\<union> m^-1 \\<union> ov^-1 \\<union> f \\<union> d\"\n  using covdi by auto\n\nlemma cdmi:\"d O m^-1 \\<subseteq> b^-1\"\n  using cmdi by auto\n\nlemma cdbi:\"d O b^-1 \\<subseteq> b^-1\"\n  using cbdi by auto\n\nlemma cfdi:\"f O d^-1 \\<subseteq>  b^-1 \\<union> m^-1 \\<union> ov^-1 \\<union> s^-1 \\<union> d^-1 \"\n  using cdfi by auto\n\nlemma cfs:\"f O s \\<subseteq> d\"\n  using csifi by auto\n\nlemma cfsi:\"f O s^-1 \\<subseteq> b ^-1 \\<union> m^-1 \\<union> ov ^-1\"\n  using csfi by auto\n\nlemma cfd:\"f O d \\<subseteq> d\"\n  using cdifi by auto\n\n\nlemma cff:\"f O f \\<subseteq> f\"\n  using cfifi by auto\n\nlemma cfovi:\"f O ov^-1 \\<subseteq> b^-1 \\<union> m^-1 \\<union> ov^-1\"\n  using covfi by auto\n\nlemma cfmi:\"f O m^-1 \\<subseteq> b^-1\"\n  using cmfi by auto\n\nlemma cfbi:\"f O b^-1 \\<subseteq> b^-1\"\n  using cbfi by auto\n\nlemma covifi:\"ov^-1 O f^-1 \\<subseteq> ov^-1 \\<union> s^-1 \\<union> d^-1\"\n  using cfov by auto\n\nlemma covidi:\"ov^-1 O d^-1 \\<subseteq> b^-1 \\<union> m^-1 \\<union> s^-1 \\<union> ov^-1 \\<union> d^-1\"\n  using cdov by auto\n\nlemma covis:\"ov^-1 O s \\<subseteq> ov^-1 \\<union> f \\<union> d\"\n  using csiov by auto\n\nlemma covisi:\"ov^-1 O s^-1 \\<subseteq> b^-1 \\<union> m^-1 \\<union> ov^-1\"\n  using csov by auto\n\nlemma covid:\"ov^-1 O d \\<subseteq> ov^-1 \\<union> f \\<union> d\"\n  using cdiov by auto\n\nlemma covif:\"ov^-1 O f \\<subseteq> ov^-1\"\n  using cfiov by auto\n\nlemma coviovi:\"ov^-1 O ov^-1 \\<subseteq> b^-1 \\<union> m^-1 \\<union> ov^-1\"\n  using covov by auto\n\nlemma covimi:\"ov^-1 O m^-1 \\<subseteq> b^-1\"\n  using cmov by auto\n\nlemma covibi:\"ov^-1 O b^-1 \\<subseteq> b^-1\"\n  using cbov by auto\n\nlemma cmiov:\"m^-1 O ov \\<subseteq> ov^-1 \\<union> d \\<union> f\"\n  using covim by auto\n\nlemma cmifi:\"m^-1 O f^-1 \\<subseteq> m^-1\"\n  using cfm by auto\n\nlemma cmidi:\"m^-1 O d^-1 \\<subseteq> b^-1\"\n  using cdm by auto\n\nlemma cmis:\"m^-1 O s \\<subseteq> ov^-1 \\<union> d \\<union> f\"\n  using csim by auto\n\nlemma cmisi:\"m^-1 O s^-1 \\<subseteq> b^-1\"\n  using csm by auto\n\nlemma cmid:\"m^-1 O d \\<subseteq> ov^-1 \\<union> d \\<union> f\"\n  using cdim by auto\n\nlemma cmif:\"m^-1 O f \\<subseteq> m^-1\"\n  using cfim by auto\n\nlemma cmiovi:\"m^-1 O ov^-1 \\<subseteq> b^-1\"\n  using covm by auto\n\nlemma cmimi:\"m^-1 O m^-1 \\<subseteq> b^-1\"\n  using cmm by auto\n\nlemma cmibi:\"m^-1 O b^-1 \\<subseteq> b^-1\"\n  using cbm by auto\n\nlemma cbim:\"b^-1 O m \\<subseteq> b^-1 \\<union> m^-1 \\<union> ov^-1 \\<union> f \\<union> d\"\n  using cmib by auto\n\nlemma cbiov:\"b^-1 O ov \\<subseteq> b^-1 \\<union> m^-1 \\<union> ov^-1 \\<union> f \\<union> d\"\n  using covib by auto\n\nlemma cbifi:\"b^-1 O f^-1 \\<subseteq> b^-1\"\n  using cfb by auto\n\nlemma cbidi:\"b^-1 O d^-1 \\<subseteq> b^-1\"\n  using cdb by auto\n\nlemma cbis:\"b^-1 O s \\<subseteq> b^-1 \\<union> m^-1 \\<union> ov^-1 \\<union> f \\<union> d\"\n  using csib by auto\n\nlemma cbisi:\"b^-1 O s^-1 \\<subseteq> b^-1\"\n  using csb by auto\n\nlemma cbid:\"b^-1 O d  \\<subseteq> b^-1 \\<union> m^-1 \\<union> ov^-1 \\<union> f \\<union> d\"\n  using cdib by auto\n\nlemma cbif:\"b^-1 O f \\<subseteq> b^-1\"\n  using cfib by auto\n\nlemma cbiovi:\"b^-1 O ov^-1 \\<subseteq> b^-1\"\n  using covb by auto\n\nlemma cbimi:\"b^-1 O m^-1 \\<subseteq> b^-1\"\n  using cmb by auto\n\nlemma cbibi:\"b^-1 O b^-1 \\<subseteq> b^-1\"\n  using cbb by auto \n\n(****)\n\nsubsection \\<open>Composition rules\\<close> \nnamed_theorems ce_rules declare cem[ce_rules] and ceb[ce_rules] and ceov[ce_rules] and ces[ce_rules] and cef[ce_rules] and ced[ce_rules] and \ncemi[ce_rules] and cebi[ce_rules] and ceovi[ce_rules] and cesi[ce_rules] and cefi[ce_rules] and cedi[ce_rules]\n\nnamed_theorems cm_rules declare cme[cm_rules] and cmb[cm_rules] and cmm[cm_rules] and cmov[cm_rules] and cms [cm_rules] and cmd[cm_rules] and cmf[cm_rules] and\ncmbi[cm_rules] and cmmi[cm_rules] and cmovi[cm_rules] and cmsi[cm_rules] and cmdi[cm_rules] and cmfi[cm_rules]\n\nnamed_theorems cb_rules declare cbe[cb_rules] and cbm[cb_rules] and cbb[cb_rules] and cbov[cb_rules] and cbs [cb_rules] and cbd[cb_rules] and cbf[cb_rules] and\ncbbi[cb_rules] and cbbi[cb_rules] and cbovi[cb_rules] and cbsi[cb_rules] and cbdi[cb_rules] and cbfi[cb_rules]\n\nnamed_theorems cov_rules declare cove[cov_rules] and covb[cov_rules] and covb[cov_rules] and covov[cov_rules] and covs [cov_rules] and covd[cov_rules] and covf[cov_rules] and\ncovbi[cov_rules] and covbi[cov_rules] and covovi[cov_rules] and covsi[cov_rules] and covdi[cov_rules] and covfi[cov_rules]\n\nnamed_theorems cs_rules declare cse[cs_rules] and csb[cs_rules] and csb[cs_rules] and csov[cs_rules] and css [cs_rules] and csd[cs_rules] and csf[cs_rules] and\ncsbi[cs_rules] and csbi[cs_rules] and csovi[cs_rules] and cssi[cs_rules] and csdi[cs_rules] and csfi[cs_rules]\n\nnamed_theorems cf_rules declare cfe[cf_rules] and cfb[cf_rules] and cfb[cf_rules] and cfov[cf_rules] and cfs [cf_rules] and cfd[cf_rules] and cff[cf_rules] and\ncfbi[cf_rules] and cfbi[cf_rules] and cfovi[cf_rules] and cfsi[cf_rules] and cfdi[cf_rules] and cffi[cf_rules]\n\nnamed_theorems cd_rules declare cde[cd_rules] and cdb[cd_rules] and cdb[cd_rules] and cdov[cd_rules] and cds [cd_rules] and cdd[cd_rules] and cdf[cd_rules] and\ncdbi[cd_rules] and cdbi[cd_rules] and cdovi[cd_rules] and cdsi[cd_rules] and cddi[cd_rules] and cdfi[cd_rules]\n\nnamed_theorems cmi_rules declare cmie[cmi_rules] and cmib[cmi_rules] and cmib[cmi_rules] and cmiov[cmi_rules] and cmis [cmi_rules] and cmid[cmi_rules] and cmif[cmi_rules] and\ncmibi[cmi_rules] and cmibi[cmi_rules] and cmiovi[cmi_rules] and cmisi[cmi_rules] and cmidi[cmi_rules] and cmifi[cmi_rules]\n\nnamed_theorems cbi_rules declare cbie[cbi_rules] and cbim[cbi_rules] and cbib[cbi_rules] and cbiov[cbi_rules] and cbis [cbi_rules] and cbid[cbi_rules] and cbif[cbi_rules] and\ncbimi[cbi_rules] and cbibi[cbi_rules] and cbiovi[cbi_rules] and cbisi[cbi_rules] and cbidi[cbi_rules] and cbifi[cbi_rules]\n\nnamed_theorems covi_rules declare covie[covi_rules] and covib[covi_rules] and covib[covi_rules] and coviov[covi_rules] and covis [covi_rules] and covid[covi_rules] and covif[covi_rules] and\ncovibi[covi_rules] and covibi[covi_rules] and coviovi[covi_rules] and covisi[covi_rules] and covidi[covi_rules] and covifi[covi_rules]\n\nnamed_theorems csi_rules declare csie[csi_rules] and csib[csi_rules] and csib[csi_rules] and csiov[csi_rules] and csis [csi_rules] and csid[csi_rules] and csif[csi_rules] and\ncsibi[csi_rules] and csibi[csi_rules] and csiovi[csi_rules] and csisi[csi_rules] and csidi[csi_rules] and csifi[csi_rules]\n\nnamed_theorems cfi_rules declare cfie[cfi_rules] and cfib[cfi_rules] and cfib[cfi_rules] and cfiov[cfi_rules] and cfis [cfi_rules] and cfid[cfi_rules] and cfif[cfi_rules] and\ncfibi[cfi_rules] and cfibi[cfi_rules] and cfiovi[cfi_rules] and cfisi[cfi_rules] and cfidi[cfi_rules] and cfifi[cfi_rules]\n\nnamed_theorems cdi_rules declare cdie[cdi_rules] and cdib[cdi_rules] and cdib[cdi_rules] and cdiov[cdi_rules] and cdis [cdi_rules] and cdid[cdi_rules] and cdif[cdi_rules] and\ncdibi[cdi_rules] and cdibi[cdi_rules] and cdiovi[cdi_rules] and cdisi[cdi_rules] and cdidi[cdi_rules] and cdifi[cdi_rules]\n(**)\nnamed_theorems cre_rules declare cee[cre_rules] and cme[cre_rules] and cbe[cre_rules] and cove[cre_rules] and cse[cre_rules] and cfe[cre_rules] and cde[cre_rules] and \ncmie[cre_rules] and cbie[cre_rules] and covie[cre_rules] and csie[cre_rules] and cfie[cre_rules] and cdie[cre_rules]\n\nnamed_theorems crm_rules declare cem[crm_rules] and cbm[crm_rules] and cmm[crm_rules]  and covm[crm_rules] and csm[crm_rules] and cfm[crm_rules] and cdm[crm_rules] and \ncmim[crm_rules] and cbim[crm_rules] and covim[crm_rules] and csim[crm_rules] and cfim[crm_rules] and cdim[crm_rules]\n\nnamed_theorems crmi_rules declare cemi[crmi_rules] and cbmi[crmi_rules] and cmmi[crmi_rules]  and covmi[crmi_rules] and csmi[crmi_rules] and cfmi[crmi_rules] and cdmi[crmi_rules] and \ncmimi[crmi_rules] and cbimi[crmi_rules] and covimi[crmi_rules] and csimi[crmi_rules] and cfimi[crmi_rules] and cdimi[crmi_rules]\n\nnamed_theorems crs_rules declare ces[crs_rules] and cbs[crs_rules] and cms[crs_rules]  and covs[crs_rules] and css[crs_rules] and cfs[crs_rules] and cds[crs_rules] and \ncmis[crs_rules] and cbis[crs_rules] and covis[crs_rules] and csis[crs_rules] and cfis[crs_rules] and cdis[crs_rules]\n\nnamed_theorems crsi_rules declare cesi[crsi_rules] and cbsi[crsi_rules] and cmsi[crsi_rules]  and covsi[crsi_rules] and cssi[crsi_rules] and cfsi[crsi_rules] and cdsi[crsi_rules] and \ncmisi[crsi_rules] and cbisi[crsi_rules] and covisi[crsi_rules] and csisi[crsi_rules] and cfisi[crsi_rules] and cdisi[crsi_rules]\n\nnamed_theorems crb_rules declare ceb[crb_rules] and cbb[crb_rules] and cmb[crb_rules]  and covb[crb_rules] and csb[crb_rules] and cfb[crb_rules] and cdb[crb_rules] and \ncmib[crb_rules] and cbib[crb_rules] and covib[crb_rules] and csib[crb_rules] and cfib[crb_rules] and cdib[crb_rules]\n\nnamed_theorems crbi_rules declare cebi[crbi_rules] and cbbi[crbi_rules] and cmbi[crbi_rules]  and covbi[crbi_rules] and csbi[crbi_rules] and cfbi[crbi_rules] and cdbi[crbi_rules] and \ncmibi[crbi_rules] and cbibi[crbi_rules] and covibi[crbi_rules] and csibi[crbi_rules] and cfibi[crbi_rules] and cdibi[crbi_rules]\n\nnamed_theorems crov_rules declare ceov[crov_rules] and cbov[crov_rules] and cmov[crov_rules]  and covov[crov_rules] and csov[crov_rules] and cfov[crov_rules] and cdov[crov_rules] and \ncmiov[crov_rules] and cbiov[crov_rules] and coviov[crov_rules] and csiov[crov_rules] and cfiov[crov_rules] and cdiov[crov_rules]\n\nnamed_theorems crovi_rules declare ceovi[crovi_rules] and cbovi[crovi_rules] and cmovi[crovi_rules]  and covovi[crovi_rules] and csovi[crovi_rules] and cfovi[crovi_rules] and cdovi[crovi_rules] and \ncmiovi[crovi_rules] and cbiovi[crovi_rules] and coviovi[crovi_rules] and csiovi[crovi_rules] and cfiovi[crovi_rules] and cdiovi[crovi_rules]\n\nnamed_theorems crf_rules declare cef[crf_rules] and cbf[crf_rules] and cmf[crf_rules]  and covf[crf_rules] and csf[crf_rules] and cff[crf_rules] and cdf[crf_rules] and \ncmif[crf_rules] and cbif[crf_rules] and covif[crf_rules] and csif[crf_rules] and cfif[crf_rules] and cdif[crf_rules]\n\nnamed_theorems crfi_rules declare cefi[crfi_rules] and cbfi[crfi_rules] and cmfi[crfi_rules]  and covfi[crfi_rules] and csfi[crfi_rules] and cffi[crfi_rules] and cdfi[crfi_rules] and \ncmifi[crfi_rules] and cbifi[crfi_rules] and covifi[crfi_rules] and csifi[crfi_rules] and cfifi[crfi_rules] and cdifi[crfi_rules]\n\nnamed_theorems crd_rules declare ced[crd_rules] and cbd[crd_rules] and cmd[crd_rules]  and covd[crd_rules] and csd[crd_rules] and cfd[crd_rules] and cdd[crd_rules] and \ncmid[crd_rules] and cbid[crd_rules] and covid[crd_rules] and csid[crd_rules] and cfid[crd_rules] and cdid[crd_rules]\n\nnamed_theorems crdi_rules declare cedi[crdi_rules] and cbdi[crdi_rules] and cmdi[crdi_rules]  and covdi[crdi_rules] and csdi[crdi_rules] and cfdi[crdi_rules] and cddi[crdi_rules] and \ncmidi[crdi_rules] and cbidi[crdi_rules] and covidi[crdi_rules] and csidi[crdi_rules] and cfidi[crdi_rules] and cdidi[crdi_rules]\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/Allen_Calculus/allen.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8577681049901037, "lm_q2_score": 0.8333246035907933, "lm_q1q2_score": 0.7147992660637041}}
{"text": "theory Isar_Demo\nimports Main\nbegin\n\nsection{* An introductory 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\ntext{* A bit shorter: *}\n\nlemma \"\\<not> surj(f :: 'a \\<Rightarrow> 'a set)\"\nproof\n  assume 0: \"surj f\"\n  from 0 have 1: \"\\<exists>a. {x. x \\<notin> f x} = f a\" by(auto simp: surj_def)\n  from 1 show \"False\" by blast\nqed\n\nsubsection{* this, then, hence and thus *}\n\ntext{* Avoid labels, use this: *}\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 simp: surj_def)\n  from this show \"False\" by blast\nqed\n\ntext{* then = from this *}\n\nlemma \"\\<not> surj(f :: 'a \\<Rightarrow> 'a set)\"\nproof\n  assume \"surj f\"\n  then have \"\\<exists>a. {x. x \\<notin> f x} = f a\" by(auto simp: surj_def)\n  then show \"False\" by blast\nqed\n\ntext{* hence = then have, thus = then show *}\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  thus \"False\" by blast\nqed\n\n\nsubsection{* Structured statements: fixes, assumes, shows *}\n\nlemma\n  fixes f :: \"'a \\<Rightarrow> 'a set\"\n  assumes s: \"surj f\"\n  shows \"False\"\nproof -  --\"no automatic proof step!\"\n  have \"\\<exists> a. {x. x \\<notin> f x} = f a\" using s\n    by(auto simp: surj_def)\n  thus \"False\" by blast\nqed\n\n\nsection{* Proof patterns *}\n\nlemma \"P \\<longleftrightarrow> Q\"\nproof\n  assume \"P\"\n  show \"Q\" sorry\nnext\n  assume \"Q\"\n  show \"P\" sorry\nqed\n\nlemma \"A = (B::'a set)\"\nproof\n  show \"A \\<subseteq> B\" sorry\nnext\n  show \"B \\<subseteq> A\" sorry\nqed\n\nlemma \"A \\<subseteq> B\"\nproof\n  fix a\n  assume \"a \\<in> A\"\n  show \"a \\<in> B\" sorry\nqed\n\ntext{* Contradiction *}\n\nlemma P\nproof (rule ccontr)\n  assume \"\\<not>P\"\n  show \"False\" sorry\nqed\n\ntext{* Case distinction *}\n\nlemma \"R\"\nproof cases\n  assume \"P\"\n  show \"R\" sorry\nnext\n  assume \"\\<not> P\"\n  show \"R\" sorry\nqed\n\nlemma \"R\"\nproof -\n  have \"P \\<or> Q\" sorry\n  then show \"R\"\n  proof\n    assume \"P\"\n    show \"R\" sorry\n  next\n    assume \"Q\"\n    show \"R\" sorry\n  qed\nqed\n\n\ntext{* obtain example *}\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\ntext{* Interactive exercise: *}\n\nlemma assumes \"EX x. ALL y. P x y\" shows \"ALL y. EX x. P x y\"\noops\n\n\nsection{* Streamlining proofs *}\n\nsubsection{* Pattern matching and ?-variables *}\n\ntext{* Show EX *}\n\nlemma \"EX xs. length xs = 0\" (is \"EX xs. ?P xs\")\nproof\n  show \"?P([])\" by simp\nqed\n\ntext{* Multiple EX easier with forward proof: *}\n\nlemma \"EX x y :: int. x < z & z < y\" (is \"EX x y. ?P x y\")\nproof -\n  have \"?P (z - 1) (z + 1)\" by arith\n  thus ?thesis by blast\nqed\n\n\nsubsection{* Quoting facts: *}\n\nlemma assumes \"x < (0::int)\" shows \"x*x > 0\"\nproof -\n  from `x<0` show ?thesis by(metis mult_neg_neg)\nqed\n\n\nsubsection {* Example: Top Down Proof Development *}\n\ntext{* The key idea: case distinction on length: *}\n\nlemma \"(EX ys zs. xs = ys @ zs \\<and> length ys = length zs) |\n  (EX ys zs. xs = ys @ zs & length ys = length zs + 1)\"\nproof cases\n  assume \"EX n. length xs = n+n\"\n  show ?thesis sorry\nnext\n  assume \"\\<not> (EX n. length xs = n+n)\"\n  show ?thesis sorry\nqed\n\ntext{* A proof skeleton: *}\n\nlemma \"(EX ys zs. xs = ys @ zs \\<and> length ys = length zs) |\n  (EX ys zs. xs = ys @ zs & length ys = length zs + 1)\"\nproof cases\n  assume \"EX n. length xs = n+n\"\n  then obtain n where \"length xs = n+n\" by blast\n  let ?ys = \"take n xs\"\n  let ?zs = \"take n (drop n xs)\"\n  have \"xs = ?ys @ ?zs \\<and> length ?ys = length ?zs\" sorry\n  thus ?thesis by blast\nnext\n  assume \"\\<not> (EX n. length xs = n+n)\"\n  then obtain n where \"length xs = Suc(n+n)\" sorry\n  let ?ys = \"take (Suc n) xs\"\n  let ?zs = \"take n (drop (Suc n) xs)\"\n  have \"xs = ?ys @ ?zs \\<and> length ?ys = length ?zs + 1\" sorry\n  then show ?thesis by blast\nqed\n\ntext{* The complete proof: *}\n\nlemma \"(EX ys zs. xs = ys @ zs \\<and> length ys = length zs) |\n  (EX ys zs. xs = ys @ zs & length ys = length zs + 1)\"\nproof cases\n  assume \"EX n. length xs = n+n\"\n  then obtain n where \"length xs = n+n\" by blast\n  let ?ys = \"take n xs\"\n  let ?zs = \"take n (drop n xs)\"\n  have \"xs = ?ys @ ?zs \\<and> length ?ys = length ?zs\"\n    by (metis `length xs = n + n` add_diff_cancel_right' append_Nil2 append_eq_conv_conj length_append length_drop take_add)\n  thus ?thesis by blast\nnext\n  assume \"\\<not> (EX n. length xs = n+n)\"\n  hence \"EX n. length xs = Suc(n+n)\" by arith\n  then obtain n where l: \"length xs = Suc(n+n)\" by blast\n  let ?ys = \"take (Suc n) xs\"\n  let ?zs = \"take n (drop (Suc n) xs)\"\n  have 1: \"xs = ?ys @ ?zs\"\n    by (metis l add_Suc_right add_Suc_shift le_refl take_add take_all)\n  have 2: \"length ?ys = length ?zs + 1\" using l by simp\n  from 1 2 show ?thesis by blast\nqed\n\n\nsubsection {* moreover *}\n\nlemma assumes \"A \\<and> B\" shows \"B \\<and> A\"\nproof -\n  from `A \\<and> B` have \"A\" by auto\n  moreover\n  from `A \\<and> B` have \"B\" by auto\n  ultimately show \"B \\<and> A\" by auto\nqed\n\n\nsubsection{* Raw proof blocks *}\n\nlemma fixes k :: int assumes \"k dvd (n+k)\" shows \"k dvd n\"\nproof -\n  { fix a assume a: \"n+k = k*a\"\n    have \"EX b. n = k*b\"\n    proof\n      show \"n = k*(a - 1)\" using a by(simp add: algebra_simps)\n    qed }\n  with assms show ?thesis by (auto simp add: dvd_def)\nqed\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/Isar_Demo.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245911726382, "lm_q2_score": 0.8577681049901036, "lm_q1q2_score": 0.7147992554118067}}
{"text": "(*  Title:       Cauchy's Mean Theorem\n    Author:      Benjamin Porter <Benjamin.Porter at gmail.com>, 2006\n                 cleaned up a bit by Tobias Nipkow, 2007\n    Maintainer:  Benjamin Porter <Benjamin.Porter at gmail.com>\n*)\n\nheader {* Cauchy's Mean Theorem *}\n\ntheory CauchysMeanTheorem\nimports Complex_Main\nbegin\n\nsection {* Abstract *}\n\ntext {* The following document presents a proof of Cauchy's Mean\ntheorem formalised in the Isabelle/Isar theorem proving system.\n\n{\\em Theorem}: For any collection of positive real numbers the\ngeometric mean is always less than or equal to the arithmetic mean. In\nmathematical terms: $$\\sqrt[n]{x_1 x_2 \\dots x_n} \\leq \\frac{x_1 +\n\\dots + x_n}{n}$$ We will use the term {\\em mean} to denote the\narithmetic mean and {\\em gmean} to denote the geometric mean.\n\n{\\em Informal Proof}:\n\nThis proof is based on the proof presented in [1]. First we need an\nauxiliary lemma (the proof of which is presented formally below) that\nstates:\n\nGiven two pairs of numbers of equal sum, the pair with the greater\nproduct is the pair with the least difference. Using this lemma we now\npresent the proof -\n\nGiven any collection $C$ of positive numbers with mean $M$ and product\n$P$ and with some element not equal to M we can choose two elements\nfrom the collection, $a$ and $b$ where $a>M$ and $b<M$. Remove these\nelements from the collection and replace them with two new elements,\n$a'$ and $b'$ such that $a' = M$ and $a' + b' = a + b$. This new\ncollection $C'$ now has a greater product $P'$ but equal mean with\nrespect to $C$. We can continue in this fashion until we have a\ncollection $C_n$ such that $P_n > P$ and $M_n = M$, but $C_n$ has all\nits elements equal to $M$ and thus $P_n = M^n$. Using the definition\nof geometric and arithmetic means above we can see that for any\ncollection of positive elements $E$ it is always true that gmean E\n$\\leq$ mean E. QED.\n\n\n[1] Dorrie, H. \"100 Great Problems of Elementary Mathematics.\" 1965, Dover.\n*}\n\n\nsection {* Formal proof *}\n\n(* ============================================================================= *)\n(* ============================================================================= *)\n(* ============================================================================= *)\n\nsubsection {* Collection sum and product *}\n\ntext {* The finite collections of numbers will be modelled as\nlists. We then define sum and product operations over these lists. *}\n\nsubsubsection {* Sum and product definitions *}\n\ndefinition\n  listsum :: \"(real list) \\<Rightarrow> real\" (\"\\<Sum>:_\" [999] 998) where\n  \"listsum xs = foldr op+ xs 0\"\n\ndefinition\n  listprod :: \"(real list) \\<Rightarrow> real\" (\"\\<Prod>:_\" [999] 998) where\n  \"listprod xs = foldr op* xs 1\"\n\nlemma listsum_empty [simp]: \"\\<Sum>:[] = 0\"\n  unfolding listsum_def by simp\n\nlemma listsum_cons [simp]: \"\\<Sum>:(a#b) = a + \\<Sum>:b\"\n  unfolding listsum_def by (induct b) simp_all\n\nlemma listprod_empty [simp]: \"\\<Prod>:[] = 1\"\n  unfolding listprod_def by simp\n\nlemma listprod_cons [simp]: \"\\<Prod>:(a#b) = a * \\<Prod>:b\"\n  unfolding listprod_def by (induct b) simp_all\n\n\nsubsubsection {* Properties of sum and product *}\n\ntext {* We now present some useful properties of sum and product over\ncollections. *}\n\ntext {* These lemmas just state that if all the elements in a\ncollection $C$ are less (greater than) than some value $m$, then the\nsum will less than (greater than) $m*length(C)$. *}\n\nlemma listsum_mono_lt [rule_format]:\n  fixes xs::\"real list\"\n  shows \"xs \\<noteq> [] \\<and> (\\<forall>x\\<in> set xs. x < m)\n         \\<longrightarrow> ((\\<Sum>:xs) < (m*(real (length xs))))\"\nproof (induct xs)\n  case Nil show ?case by simp\nnext\n  case (Cons y ys)\n  {\n    assume ant: \"y#ys \\<noteq> [] \\<and> (\\<forall>x\\<in>set(y#ys). x < m)\"\n    hence ylm: \"y < m\" by simp\n    have \"\\<Sum>:(y#ys) < m * real (length (y#ys))\"\n    proof cases\n      assume \"ys \\<noteq> []\"\n      moreover with ant have \"\\<forall>x\\<in>set ys. x < m\" by simp\n      moreover with calculation Cons have \"\\<Sum>:ys < m*real (length ys)\" by simp\n      hence \"\\<Sum>:ys + y < m*real(length ys) + y\" by simp\n      with ylm have \"\\<Sum>:(y#ys) < m*(real(length ys) + 1)\" by(simp add:field_simps)\n      with real_of_nat_Suc have \"\\<Sum>:(y#ys) < m*(real(length ys + 1))\"\n        apply -\n        apply (drule meta_spec [of _ \"length ys\"])\n        apply (subst(asm) eq_sym_conv)\n        by simp\n      hence \"\\<Sum>:(y#ys) < m*(real (length(y#ys)))\" by simp\n      thus ?thesis .\n    next\n      assume \"\\<not> (ys \\<noteq> [])\"\n      hence \"ys = []\" by simp\n      with ylm show ?thesis by simp\n    qed\n  }\n  thus ?case by simp\nqed\n\n\nlemma listsum_mono_gt [rule_format]:\n  fixes xs::\"real list\"\n  shows \"xs \\<noteq> [] \\<and> (\\<forall>x\\<in>set xs. x > m)\n         \\<longrightarrow> ((\\<Sum>:xs) > (m*(real (length xs))))\"\ntxt {* proof omitted *}\n(*<*)\nproof (induct xs)\n  case Nil show ?case by simp\nnext\n  case (Cons y ys)\n  {\n    assume ant: \"y#ys \\<noteq> [] \\<and> (\\<forall>x\\<in>set(y#ys). x > m)\"\n    hence ylm: \"y > m\" by simp\n    have \"\\<Sum>:(y#ys) > m * real (length (y#ys))\"\n    proof cases\n      assume \"ys \\<noteq> []\"\n      moreover with ant have \"\\<forall>x\\<in>set ys. x > m\" by simp\n      moreover with calculation Cons have \"\\<Sum>:ys > m*real (length ys)\" by simp\n      hence \"\\<Sum>:ys + y > m*real(length ys) + y\" by simp\n      with ylm have \"\\<Sum>:(y#ys) > m*(real(length ys) + 1)\" by(simp add:field_simps)\n      with real_of_nat_Suc have \"\\<Sum>:(y#ys) > m*(real(length ys + 1))\"\n        apply -\n        apply (drule meta_spec [of _ \"length ys\"])\n        apply (subst(asm) eq_sym_conv)\n        by simp\n      hence \"\\<Sum>:(y#ys) > m*(real (length(y#ys)))\" by simp\n      thus ?thesis .\n    next\n      assume \"\\<not> (ys \\<noteq> [])\"\n      hence \"ys = []\" by simp\n      with ylm show ?thesis by simp\n    qed\n  }\n  thus ?case by simp\n(*>*)\nqed\n\ntext {* If $a$ is in $C$ then the sum of the collection $D$ where $D$\nis $C$ with $a$ removed is the sum of $C$ minus $a$. *}\n\nlemma listsum_rmv1:\n  \"a \\<in> set xs \\<Longrightarrow> \\<Sum>:(remove1 a xs) = \\<Sum>:xs - a\"\nby (induct xs) auto\n\ntext {* A handy addition and division distribution law over collection\nsums. *}\n\nlemma list_sum_distrib_aux:\n  shows \"(\\<Sum>:xs/n + \\<Sum>:xs) = (1 + (1/n)) * \\<Sum>:xs\"\nproof (induct xs)\n  case Nil show ?case by simp\nnext\n  case (Cons x xs)\n  show ?case\n  proof -\n    have\n      \"\\<Sum>:(x#xs)/n = x/n + \\<Sum>:xs/n\"\n      by (simp add: add_divide_distrib)\n    also with Cons have\n      \"\\<dots> = x/n + (1+1/n)*\\<Sum>:xs - \\<Sum>:xs\"\n      by simp\n    finally have\n      \"\\<Sum>:(x#xs) / n + \\<Sum>:(x#xs) = x/n + (1+1/n)*\\<Sum>:xs - \\<Sum>:xs + \\<Sum>:(x#xs)\"\n      by simp\n    also have\n      \"\\<dots> = x/n + (1+(1/n)- 1)*\\<Sum>:xs + \\<Sum>:(x#xs)\"\n      by (subst mult_1_left [symmetric, of \"\\<Sum>:xs\"]) (simp add: field_simps)\n    also have\n      \"\\<dots> = x/n + (1/n)*\\<Sum>:xs + \\<Sum>:(x#xs)\"\n      by simp\n    also have\n      \"\\<dots> = (1/n)*\\<Sum>:(x#xs) + 1*\\<Sum>:(x#xs)\" by(simp add: divide_simps)\n    finally show ?thesis by (simp add: field_simps)\n  qed\nqed\n\nlemma remove1_retains_prod:\n  fixes a::real and xs::\"real list\"\n  shows \"a : set xs \\<longrightarrow> \\<Prod>:xs = \\<Prod>:(remove1 a xs) * a\"\n  (is \"?P xs\")\nproof (induct xs)\n  case Nil\n  show ?case by simp\nnext\n  case (Cons aa list)\n  assume plist: \"?P list\"\n  show \"?P (aa#list)\"\n  proof\n    assume aml: \"a : set(aa#list)\"\n    show \"\\<Prod>:(aa # list) = \\<Prod>:remove1 a (aa # list) * a\"\n    proof (cases)\n      assume aeq: \"a = aa\"\n      hence\n        \"remove1 a (aa#list) = list\"\n        by simp\n      hence\n        \"\\<Prod>:(remove1 a (aa#list)) = \\<Prod>:list\"\n        by simp\n      moreover with aeq have\n        \"\\<Prod>:(aa#list) = \\<Prod>:list * a\"\n        by simp\n      ultimately show\n        \"\\<Prod>:(aa#list) = \\<Prod>:remove1 a (aa # list) * a\"\n        by simp\n    next\n      assume naeq: \"a \\<noteq> aa\"\n      with aml have aml2: \"a : set list\" by simp\n      from naeq have\n        \"remove1 a (aa#list) = aa#(remove1 a list)\"\n        by simp\n      moreover hence\n        \"\\<Prod>:(remove1 a (aa#list)) = aa * \\<Prod>:(remove1 a list)\"\n        by simp\n      moreover from aml2 plist have\n        \"\\<Prod>:list = \\<Prod>:(remove1 a list) * a\"\n        by simp\n      ultimately show\n        \"\\<Prod>:(aa#list) = \\<Prod>:remove1 a (aa # list) * a\"\n        by simp\n    qed\n  qed\nqed\n\ntext {* The final lemma of this section states that if all elements\nare positive and non-zero then the product of these elements is also\npositive and non-zero. *}\n\nlemma el_gt0_imp_prod_gt0 [rule_format]:\n  fixes xs::\"real list\"\n  shows \"\\<forall>y. y : set xs \\<longrightarrow> y > 0 \\<Longrightarrow> \\<Prod>:xs > 0\"\nproof (induct xs)\n  case Nil show ?case by simp\nnext\n  case (Cons a xs)\n  have exp: \"\\<Prod>:(a#xs) = \\<Prod>:xs * a\" by simp\n  with Cons have \"a > 0\" by simp\n  with exp Cons show ?case by simp\nqed\n\n\n(* ============================================================================= *)\n(* ============================================================================= *)\n(* ============================================================================= *)\n\nsubsection {* Auxiliary lemma *}\n\ntext {* This section presents a proof of the auxiliary lemma required\nfor this theorem. *}\n\nlemma prod_exp:\n  fixes x::real\n  shows \"4*(x*y) = (x+y)^2 - (x-y)^2\"\n  by (simp add: power2_diff power2_sum)\n\nlemma abs_less_imp_sq_less [rule_format]:\n  fixes x::real and y::real and z::real and w::real\n  assumes diff: \"abs (x-y) < abs (z-w)\"\n  shows \"(x-y)^2 < (z-w)^2\"\nproof cases\n  assume \"x=y\"\n  hence \"abs (x-y) = 0\" by simp\n  moreover with diff have \"abs(z-w) > 0\" by simp\n  hence \"(z-w)^2 > 0\" by simp\n  ultimately show ?thesis by auto\nnext\n  assume \"x\\<noteq>y\"\n  hence \"abs (x - y) > 0\" by simp\n  with diff have \"(abs (x-y))^2 < (abs (z-w))^2\"\n    by - (drule power_strict_mono [where a=\"abs (x-y)\" and n=2 and b=\"abs (z-w)\"], auto)\n  thus ?thesis by simp\nqed\n\ntext {* The required lemma (phrased slightly differently than in the\ninformal proof.) Here we show that for any two pairs of numbers with\nequal sums the pair with the least difference has the greater\nproduct. *}\n\nlemma le_diff_imp_gt_prod [rule_format]:\n  fixes x::real and y::real and z::real and w::real\n  assumes diff: \"abs (x-y) < abs (z-w)\" and sum: \"x+y = z+w\"\n  shows \"x*y > z*w\"\nproof -\n  from sum have \"(x+y)^2 = (z+w)^2\" by simp\n  moreover from diff have \"(x-y)^2 < (z-w)^2\" by (rule abs_less_imp_sq_less)\n  ultimately have \"(x+y)^2 - (x-y)^2 > (z+w)^2 - (z-w)^2\" by auto\n  thus \"x*y > z*w\" by (simp only: prod_exp [symmetric])\nqed\n\n(* ============================================================================= *)\n(* ============================================================================= *)\n(* ============================================================================= *)\n\nsubsection {* Mean and GMean *}\n\ntext {* Now we introduce definitions and properties of arithmetic and\ngeometric means over collections of real numbers. *}\n\nsubsubsection {* Definitions *}\n\ntext {* {\\em Arithmetic mean} *}\n\ndefinition\n  mean :: \"(real list)\\<Rightarrow>real\" where\n  \"mean s = (\\<Sum>:s / real (length s))\"\n\ntext {* {\\em Geometric mean} *}\n\ndefinition\n  gmean :: \"(real list)\\<Rightarrow>real\" where\n  \"gmean s = root (length s) (\\<Prod>:s)\"\n\n\nsubsubsection {* Properties *}\n\ntext {* Here we present some trival properties of {\\em mean} and {\\em gmean}. *}\n\n\n\nlemma list_mean_eq_iff:\n  fixes one::\"real list\" and two::\"real list\"\n  assumes\n    se: \"( \\<Sum>:one = \\<Sum>:two )\" and\n    le: \"(length one = length two)\"\n  shows \"(mean one = mean two)\"\nproof -\n  from se le have\n    \"(\\<Sum>:one / real (length one)) = (\\<Sum>:two / real (length two))\"\n    by auto\n  thus ?thesis unfolding mean_def .\nqed\n\nlemma list_gmean_gt_iff:\n  fixes one::\"real list\" and two::\"real list\"\n  assumes\n    gz1: \"\\<Prod>:one > 0\" and gz2: \"\\<Prod>:two > 0\" and\n    ne1: \"one \\<noteq> []\" and ne2: \"two \\<noteq> []\" and\n    pe: \"(\\<Prod>:one > \\<Prod>:two)\" and\n    le: \"(length one = length two)\"\n  shows \"(gmean one > gmean two)\"\n  unfolding gmean_def\n  using le ne2 pe by simp\n\ntext {* This slightly more complicated lemma shows that for every non-empty collection with mean $M$, adding another element $a$ where $a=M$ results in a new list with the same mean $M$. *}\n\nlemma list_mean_cons [rule_format]:\n  fixes xs::\"real list\"\n  shows \"xs \\<noteq> [] \\<longrightarrow> mean ((mean xs)#xs) = mean xs\"\nproof\n  assume lne: \"xs \\<noteq> []\"\n  obtain len where ld: \"len = real (length xs)\" by simp\n  with lne have lgt0: \"len > 0\" by simp\n  hence lnez: \"len \\<noteq> 0\" by simp\n  from lgt0 have l1nez: \"len + 1 \\<noteq> 0\" by simp\n  from ld have mean: \"mean xs = \\<Sum>:xs / len\" unfolding mean_def by simp\n  with ld real_of_nat_add real_of_one mean_def\n  have \"mean ((mean xs)#xs) = (\\<Sum>:xs/len + \\<Sum>:xs) / (1+len)\"\n    by simp\n  also from list_sum_distrib_aux have\n    \"\\<dots> = (1 + (1/len))*\\<Sum>:xs / (1+len)\" by simp\n  also with lnez have\n    \"\\<dots> = (len + 1)*\\<Sum>:xs / (len * (1+len))\"\n    apply -\n    apply (drule mult_divide_mult_cancel_left\n      [symmetric, where c=\"len\" and a=\"(1 + 1 / len) * \\<Sum>:xs\" and b=\"1+len\"])\n    apply (clarsimp simp:field_simps)\n    done\n  also from l1nez have \"\\<dots> = \\<Sum>:xs / len\"\n    apply (subst mult.commute [where a=\"len\"])\n    apply (drule mult_divide_mult_cancel_left\n      [where c=\"len+1\" and a=\"\\<Sum>:xs\" and b=\"len\"])\n    by (simp add: ac_simps ac_simps)\n  finally show \"mean ((mean xs)#xs) = mean xs\" by (simp add: mean)\nqed\n\ntext {* For a non-empty collection with positive mean, if we add a positive number to the collection then the mean remains positive. *}\n\nlemma mean_gt_0 [rule_format]:\n  \"xs\\<noteq>[] \\<and> 0 < x \\<and> 0 < (mean xs) \\<longrightarrow> 0 < (mean (x#xs))\"\nproof\n  assume a: \"xs \\<noteq> [] \\<and> 0 < x \\<and> 0 < mean xs\"\n  hence xgt0: \"0 < x\" and mgt0: \"0 < mean xs\" by auto\n  from a have lxsgt0: \"length xs \\<noteq> 0\" by simp\n  from mgt0 have xsgt0: \"0 < \\<Sum>:xs\"\n  proof -\n    have \"mean xs = \\<Sum>:xs / real (length xs)\" unfolding mean_def by simp\n    hence \"\\<Sum>:xs = mean xs * real (length xs)\" by simp\n    moreover from lxsgt0 have \"real (length xs) > 0\" by simp\n    moreover with calculation lxsgt0 mgt0 show ?thesis by auto\n  qed\n  with xgt0 have \"\\<Sum>:(x#xs) > 0\" by simp\n  thus \"0 < (mean (x#xs))\"\n  proof -\n    assume \"0 < \\<Sum>:(x#xs)\"\n    moreover have \"real (length (x#xs)) > 0\" by simp\n    ultimately show ?thesis unfolding mean_def by simp\n  qed\nqed\n\n(* ============================================================================= *)\n(* ============================================================================= *)\n(* ============================================================================= *)\n\nsubsection {* @{text \"list_neq\"}, @{text \"list_eq\"} *}\n\ntext {* This section presents a useful formalisation of the act of removing all the elements from a collection that are equal (not equal) to a particular value. We use this to extract all the non-mean elements from a collection as is required by the proof. *}\n\nsubsubsection {* Definitions *}\n\ntext {* @{text \"list_neq\"} and @{text \"list_eq\"} just extract elements from a collection that are not equal (or equal) to some value. *}\n\nabbreviation\n  list_neq :: \"('a list) \\<Rightarrow> 'a \\<Rightarrow> ('a list)\" where\n  \"list_neq xs el == filter (\\<lambda>x. x\\<noteq>el) xs\"\n\nabbreviation\n  list_eq :: \"('a list) \\<Rightarrow> 'a \\<Rightarrow> ('a list)\" where\n  \"list_eq xs el == filter (\\<lambda>x. x=el) xs\"\n\nsubsubsection {* Properties *}\n\ntext {* This lemma just proves a required fact about @{text\n  \"list_neq\"}, {\\em remove1} and {\\em length}. *}\n\nlemma list_neq_remove1 [rule_format]:\n  shows \"a\\<noteq>m \\<and> a : set xs\n  \\<longrightarrow> length (list_neq (remove1 a xs) m) < length (list_neq xs m)\"\n  (is \"?A xs \\<longrightarrow> ?B xs\" is \"?P xs\")\nproof (induct xs)\n  case Nil show ?case by simp\nnext\n  case (Cons x xs)\n  note `?P xs`\n  {\n    assume a: \"?A (x#xs)\"\n    hence\n      a_ne_m: \"a\\<noteq>m\" and\n      a_mem_x_xs: \"a : set(x#xs)\"\n      by auto\n    have b: \"?B (x#xs)\"\n    proof cases\n      assume \"xs = []\"\n      with a_ne_m a_mem_x_xs show ?thesis\n        apply (cases \"x=a\")\n        by auto\n    next\n      assume xs_ne: \"xs \\<noteq> []\"\n      with a_ne_m a_mem_x_xs show ?thesis\n      proof cases\n        assume \"a=x\" with a_ne_m show ?thesis by simp\n      next\n        assume a_ne_x: \"a\\<noteq>x\"\n        with a_mem_x_xs have a_mem_xs: \"a : set xs\" by simp\n        with xs_ne a_ne_m Cons have\n          rel: \"length (list_neq (remove1 a xs) m) < length (list_neq xs m)\"\n          by simp\n        show ?thesis\n        proof cases\n          assume x_e_m: \"x=m\"\n          with Cons xs_ne a_ne_m a_mem_xs show ?thesis by simp\n        next\n          assume x_ne_m: \"x\\<noteq>m\"\n          from a_ne_x have\n            \"remove1 a (x#xs) = x#(remove1 a xs)\"\n            by simp\n          hence\n            \"length (list_neq (remove1 a (x#xs)) m) =\n             length (list_neq (x#(remove1 a xs)) m)\"\n            by simp\n          also with x_ne_m have\n            \"\\<dots> = 1 + length (list_neq (remove1 a xs) m)\"\n            by simp\n          finally have\n            \"length (list_neq (remove1 a (x#xs)) m) =\n             1 + length (list_neq (remove1 a xs) m)\"\n            by simp\n          moreover with x_ne_m a_ne_x have\n            \"length (list_neq (x#xs) m) =\n             1 + length (list_neq xs m)\"\n            by simp\n          moreover with rel show ?thesis by simp\n        qed\n      qed\n    qed\n  }\n  thus \"?P (x#xs)\" by simp\nqed\n\ntext {* We now prove some facts about @{text \"list_eq\"}, @{text \"list_neq\"}, length, sum and product. *}\n\nlemma list_eq_sum [simp]:\n  fixes xs::\"real list\"\n  shows \"\\<Sum>:(list_eq xs m) = (m * (real (length (list_eq xs m))))\"\napply (induct_tac xs)\napply simp\napply clarsimp\napply (subst real_of_nat_Suc)\napply (simp add:field_simps)\ndone\n\nlemma list_eq_prod [simp]:\n  fixes xs::\"real list\"\n  shows \"\\<Prod>:(list_eq xs m) = (m ^ (length (list_eq xs m)))\"\napply (induct_tac xs)\napply simp\napply clarsimp\ndone\n\nlemma listsum_split:\n  fixes xs::\"real list\"\n  shows \"\\<Sum>:xs = (\\<Sum>:(list_neq xs m) + \\<Sum>:(list_eq xs m))\"\napply (induct xs)\napply simp\napply clarsimp\ndone\n\nlemma listprod_split:\n  fixes xs::\"real list\"\n  shows \"\\<Prod>:xs = (\\<Prod>:(list_neq xs m) * \\<Prod>:(list_eq xs m))\"\napply (induct xs)\napply simp\napply clarsimp\ndone\n\nlemma listsum_length_split:\n  fixes xs::\"real list\"\n  shows \"length xs = length (list_neq xs m) + length (list_eq xs m)\"\napply (induct xs)\napply simp+\ndone\n\n\n\n(* ============================================================================= *)\n(* ============================================================================= *)\n(* ============================================================================= *)\n\nsubsection {* Element selection *}\n\ntext {* We now show that given after extracting all the elements not equal to the mean there exists one that is greater then (or less than) the mean. *}\n\nlemma pick_one_gt:\n  fixes xs::\"real list\" and m::real\n  defines m: \"m \\<equiv> (mean xs)\" and neq: \"noteq \\<equiv> list_neq xs m\"\n  assumes asum: \"noteq\\<noteq>[]\"\n  shows \"\\<exists>e. e : set noteq \\<and> e > m\"\nproof (rule ccontr)\n  let ?m = \"(mean xs)\"\n  let ?neq = \"list_neq xs ?m\"\n  let ?eq = \"list_eq xs ?m\"\n  from list_eq_sum have \"(\\<Sum>:?eq) = ?m * (real (length ?eq))\" by simp\n  from asum have neq_ne: \" ?neq \\<noteq> []\" unfolding m neq .\n  assume not_el: \"\\<not>(\\<exists>e. e : set noteq \\<and> m < e)\"\n  hence not_el_exp: \"\\<not>(\\<exists>e. e : set ?neq \\<and> ?m < e)\" unfolding m neq .\n  hence \"\\<forall>e. \\<not>(e : set ?neq) \\<or> \\<not>(e > ?m)\" by simp\n  hence \"\\<forall>e. e : set ?neq \\<longrightarrow> \\<not>(e > ?m)\" by blast\n  hence \"\\<forall>e. e : set ?neq \\<longrightarrow> e \\<le> ?m\" by (simp add: linorder_not_less)\n  hence \"\\<forall>e. e : set ?neq \\<longrightarrow> e < ?m\" by (simp add:order_le_less)\n  with assms listsum_mono_lt have \"(\\<Sum>:?neq) < ?m * (real (length ?neq))\" by blast\n  hence\n    \"(\\<Sum>:?neq) + (\\<Sum>:?eq) < ?m * (real (length ?neq)) + (\\<Sum>:?eq)\" by simp\n  also have\n    \"\\<dots> = (?m * ((real (length ?neq) + (real (length ?eq)))))\"\n      by (simp add:field_simps)\n  also have\n    \"\\<dots> = (?m * (real (length xs)))\"\n      apply (subst real_of_nat_add [symmetric])\n      by (simp add: listsum_length_split [symmetric])\n  also have\n    \"\\<dots> = \\<Sum>:xs\"\n      by (simp add: list_sum_mean [symmetric])\n  also from not_el calculation show False by (simp only: listsum_split [symmetric])\nqed\n\nlemma pick_one_lt:\n  fixes xs::\"real list\" and m::real\n  defines m: \"m \\<equiv> (mean xs)\" and neq: \"noteq \\<equiv> list_neq xs m\"\n  assumes asum: \"noteq\\<noteq>[]\"\n  shows \"\\<exists>e. e : set noteq \\<and> e < m\"\nproof (rule ccontr) -- \"reductio ad absurdum\"\n  let ?m = \"(mean xs)\"\n  let ?neq = \"list_neq xs ?m\"\n  let ?eq = \"list_eq xs ?m\"\n  from list_eq_sum have \"(\\<Sum>:?eq) = ?m * (real (length ?eq))\" by simp\n  from asum have neq_ne: \" ?neq \\<noteq> []\" unfolding m neq .\n  assume not_el: \"\\<not>(\\<exists>e. e : set noteq \\<and> m > e)\"\n  hence not_el_exp: \"\\<not>(\\<exists>e. e : set ?neq \\<and> ?m > e)\" unfolding m neq .\n  hence \"\\<forall>e. \\<not>(e : set ?neq) \\<or> \\<not>(e < ?m)\" by simp\n  hence \"\\<forall>e. e : set ?neq \\<longrightarrow> \\<not>(e < ?m)\" by blast\n  hence \"\\<forall>e. e : set ?neq \\<longrightarrow> e \\<ge> ?m\" by (simp add: linorder_not_less)\n  hence \"\\<forall>e. e : set ?neq \\<longrightarrow> e > ?m\" by (auto simp: order_le_less)\n  with assms listsum_mono_gt have \"(\\<Sum>:?neq) > ?m * (real (length ?neq))\" by blast\n  hence\n    \"(\\<Sum>:?neq) + (\\<Sum>:?eq) > ?m * (real (length ?neq)) + (\\<Sum>:?eq)\" by simp\n  also have\n    \"(?m * (real (length ?neq)) + (\\<Sum>:?eq)) =\n     (?m * (real (length ?neq)) + (?m * (real (length ?eq))))\"\n    by simp\n  also have\n    \"\\<dots> = (?m * ((real (length ?neq) + (real (length ?eq)))))\"\n      by (simp add:field_simps)\n  also have\n    \"\\<dots> = (?m * (real (length xs)))\"\n      apply (subst real_of_nat_add [symmetric])\n      by (simp add: listsum_length_split [symmetric])\n  also have\n    \"\\<dots> = \\<Sum>:xs\"\n      by (simp add: list_sum_mean [symmetric])\n  also from not_el calculation show False by (simp only: listsum_split [symmetric])\nqed\n\n(* =================================================================== *)\n(* =================================================================== *)\n(* =================================================================== *)\n(* =================================================================== *)\n\nsubsection {* Abstract properties *}\n\ntext {* In order to maintain some comprehension of the following proofs we now introduce some properties of collections. *}\n\nsubsubsection {* Definitions *}\n\n\n\n\ntext {* {\\em het}: The heterogeneity of a collection is the number of elements not equal to its mean. A heterogeneity of zero implies the all the elements in the collection are the same (i.e. homogeneous). *}\n\ndefinition\n  het :: \"real list \\<Rightarrow> nat\" where\n  \"het l = length (list_neq l (mean l))\"\n\nlemma het_gt_0_imp_noteq_ne: \"het l > 0 \\<Longrightarrow> list_neq l (mean l) \\<noteq> []\"\n  unfolding het_def by simp\n\nlemma het_gt_0I: assumes a: \"a \\<in> set xs\" and b: \"b \\<in> set xs\" and neq: \"a \\<noteq> b\"\n  shows \"het xs > 0\"\nproof (rule ccontr)\n  assume \"\\<not> ?thesis\"\n  hence \"het xs = 0\" by auto\n  from this[unfolded het_def] have \"list_neq xs (mean xs) = []\" by simp\n  from arg_cong[OF this, of set] have mean: \"\\<And> x. x \\<in> set xs \\<Longrightarrow> x = mean xs\" by auto\n  from mean[OF a] mean[OF b] neq show False by auto\nqed\n\n\ntext {* @{text \"\\<gamma>-eq\"}: Two lists are $\\gamma$-equivalent if and only\nif they both have the same number of elements and the same arithmetic\nmeans. *}\n\ndefinition\n  \\<gamma>_eq :: \"((real list)*(real list)) \\<Rightarrow> bool\" where\n  \"\\<gamma>_eq a \\<longleftrightarrow> mean (fst a) = mean (snd a) \\<and> length (fst a) = length (snd a)\"\n\ntext {* @{text \"\\<gamma>_eq\"} is transitive and symmetric. *}\n\nlemma \\<gamma>_eq_sym: \"\\<gamma>_eq (a,b) = \\<gamma>_eq (b,a)\"\n  unfolding \\<gamma>_eq_def by auto\n\nlemma \\<gamma>_eq_trans:\n  \"\\<gamma>_eq (x,y) \\<Longrightarrow> \\<gamma>_eq (y,z) \\<Longrightarrow> \\<gamma>_eq (x,z)\"\n  unfolding \\<gamma>_eq_def by simp\n\n\ntext {* {\\em pos}: A list is positive if all its elements are greater than 0. *}\n\ndefinition\n  pos :: \"real list \\<Rightarrow> bool\" where\n  \"pos l \\<longleftrightarrow> (if l=[] then False else \\<forall>e. e : set l \\<longrightarrow> e > 0)\"\n\nlemma pos_empty [simp]: \"pos [] = False\" unfolding pos_def by simp\nlemma pos_single [simp]: \"pos [x] = (x > 0)\" unfolding pos_def by simp\nlemma pos_imp_ne: \"pos xs \\<Longrightarrow> xs\\<noteq>[]\" unfolding pos_def by auto\n\nlemma pos_cons [simp]:\n  \"xs \\<noteq> [] \\<longrightarrow> pos (x#xs) =\n   (if (x>0) then pos xs else False)\"\n  (is \"?P x xs\" is \"?A xs \\<longrightarrow> ?S x xs\")\nproof (simp add: split_if, rule impI)\n  assume xsne: \"xs \\<noteq> []\"\n  hence pxs_simp:\n    \"pos xs = (\\<forall>e. e : set xs \\<longrightarrow> e > 0)\"\n    unfolding pos_def by simp\n  show\n    \"(0 < x \\<longrightarrow> pos (x # xs) = pos xs) \\<and>\n     (\\<not> 0 < x \\<longrightarrow> \\<not> pos (x # xs))\"\n  proof\n    {\n      assume xgt0: \"0 < x\"\n      {\n        assume pxs: \"pos xs\"\n        with pxs_simp have \"\\<forall>e. e : set xs \\<longrightarrow> e > 0\" by simp\n        with xgt0 have \"\\<forall>e. e : set (x#xs) \\<longrightarrow> e > 0\" by simp\n        hence \"pos (x#xs)\" unfolding pos_def by simp\n      }\n      moreover\n      {\n        assume pxxs: \"pos (x#xs)\"\n        hence \"\\<forall>e. e : set (x#xs) \\<longrightarrow> e > 0\" unfolding pos_def by simp\n        hence \"\\<forall>e. e : set xs \\<longrightarrow> e > 0\" by simp\n        with xsne have \"pos xs\" unfolding pos_def by simp\n      }\n      ultimately have \"pos (x # xs) = pos xs\"\n        apply -\n        apply (rule iffI)\n        apply auto\n        done\n    }\n    thus \"0 < x \\<longrightarrow> pos (x # xs) = pos xs\" by simp\n  next\n    {\n      assume xngt0: \"\\<not> (0<x)\"\n      {\n        assume pxs: \"pos xs\"\n        with pxs_simp have \"\\<forall>e. e : set xs \\<longrightarrow> e > 0\" by simp\n        with xngt0 have \"\\<not> (\\<forall>e. e : set (x#xs) \\<longrightarrow> e > 0)\" by auto\n        hence \"\\<not> (pos (x#xs))\" unfolding pos_def by simp\n      }\n      moreover\n      {\n        assume pxxs: \"\\<not>pos xs\"\n        with xsne have \"\\<not> (\\<forall>e. e : set xs \\<longrightarrow> e > 0)\" unfolding pos_def by simp\n        hence \"\\<not> (\\<forall>e. e : set (x#xs) \\<longrightarrow> e > 0)\" by auto\n        hence \"\\<not> (pos (x#xs))\" unfolding pos_def by simp\n      }\n      ultimately have \"\\<not> pos (x#xs)\" by auto\n    }\n    thus \"\\<not> 0 < x \\<longrightarrow> \\<not> pos (x # xs)\" by simp\n  qed\nqed\n\nsubsubsection {* Properties *}\n\ntext {* Here we prove some non-trivial properties of the abstract properties. *}\n\ntext {* Two lemmas regarding {\\em pos}. The first states the removing\nan element from a positive collection (of more than 1 element) results\nin a positive collection. The second asserts that the mean of a\npositive collection is positive. *}\n\nlemma pos_imp_rmv_pos:\n  assumes \"(remove1 a xs)\\<noteq>[]\" \"pos xs\" shows \"pos (remove1 a xs)\"\nproof -\n  from assms have pl: \"pos xs\" and rmvne: \"(remove1 a xs)\\<noteq>[]\" by auto\n  from pl have \"xs \\<noteq> []\" by (rule pos_imp_ne)\n  with pl pos_def have \"\\<forall>x. x : set xs \\<longrightarrow> x > 0\" by simp\n  hence \"\\<forall>x. x : set (remove1 a xs) \\<longrightarrow> x > 0\"\n    using set_remove1_subset[of _ xs] by(blast)\n  with rmvne show \"pos (remove1 a xs)\" unfolding pos_def by simp\nqed\n\nlemma pos_mean: \"pos xs \\<Longrightarrow> mean xs > 0\"\nproof (induct xs)\n  case Nil thus ?case by(simp add: pos_def)\nnext\n  case (Cons x xs)\n  show ?case\n  proof cases\n    assume xse: \"xs = []\"\n    hence \"pos (x#xs) = (x > 0)\" by simp\n    with Cons(2) have \"x>0\" by(simp)\n    with xse have \"0 < mean (x#xs)\" by(auto simp:mean_def)\n    thus ?thesis by simp\n  next\n    assume xsne: \"xs \\<noteq> []\"\n    show ?thesis\n    proof cases\n      assume pxs: \"pos xs\"\n      with Cons(1) have z_le_mxs: \"0 < mean xs\" by(simp)\n      {\n        assume ass: \"x > 0\"\n        with ass z_le_mxs xsne have \"0 < mean (x#xs)\"\n          apply -\n          apply (rule mean_gt_0)\n          by simp\n      }\n      moreover\n      {\n        from xsne pxs have \"0 < x\"\n        proof cases\n          assume \"0 < x\" thus ?thesis by simp\n        next\n          assume \"\\<not>(0 < x)\"\n          with xsne pos_cons have \"pos (x#xs) = False\" by simp\n          with Cons(2) show ?thesis by simp\n        qed\n      }\n      ultimately have \"0 < mean (x#xs)\" by simp\n      thus ?thesis by simp\n    next\n      assume npxs: \"\\<not>pos xs\"\n      with xsne pos_cons have \"pos (x#xs) = False\"  by simp\n      thus ?thesis using Cons(2) by simp\n    qed\n  qed\nqed\n\ntext {* We now show that homogeneity of a non-empty collection $x$\nimplies that its product is equal to @{text \"(mean x)^(length x)\"}. *}\n\nlemma listprod_het0:\n  shows \"x\\<noteq>[] \\<and> het x = 0 \\<Longrightarrow> \\<Prod>:x = (mean x) ^ (length x)\"\nproof -\n  assume \"x\\<noteq>[] \\<and> het x = 0\"\n  hence xne: \"x\\<noteq>[]\" and hetx: \"het x = 0\" by auto\n  from hetx have lz: \"length (list_neq x (mean x)) = 0\" unfolding het_def .\n  hence \"\\<Prod>:(list_neq x (mean x)) = 1\" by simp\n  with listprod_split have \"\\<Prod>:x = \\<Prod>:(list_eq x (mean x))\"\n    apply -\n    apply (drule meta_spec [of _ x])\n    apply (drule meta_spec [of _ \"mean x\"])\n    by simp\n  also with list_eq_prod have\n    \"\\<dots> = (mean x) ^ (length (list_eq x (mean x)))\" by simp\n  also with calculation lz listsum_length_split have\n    \"\\<Prod>:x = (mean x) ^ (length x)\"\n    apply -\n    apply (drule meta_spec [of _ x])\n    apply (drule meta_spec [of _ \"mean x\"])\n    by simp\n  thus ?thesis by simp\nqed\n\ntext {* Furthermore we present an important result - that a\nhomogeneous collection has equal geometric and arithmetic means. *}\n\nlemma het_base:\n  shows \"pos x \\<and> het x = 0 \\<Longrightarrow> gmean x = mean x\"\nproof -\n  assume ass: \"pos x \\<and> het x = 0\"\n  hence\n    xne: \"x\\<noteq>[]\" and\n    hetx: \"het x = 0\" and\n    posx: \"pos x\"\n    by auto\n  from posx pos_mean have mxgt0: \"mean x > 0\" by simp\n  from xne have lxgt0: \"length x > 0\" by simp\n  with ass listprod_het0 have\n    \"root (length x) (\\<Prod>:x) = root (length x) ((mean x)^(length x))\"\n    by simp\n  also from lxgt0 mxgt0 real_root_power_cancel have \"\\<dots> = mean x\" by auto\n  finally show \"gmean x = mean x\" unfolding gmean_def .\nqed\n\n(* =================================================================== *)\n(* =================================================================== *)\n(* =================================================================== *)\n(* =================================================================== *)\n\n\nsubsection {* Existence of a new collection *}\n\ntext {* We now present the largest and most important proof in this\ndocument. Given any positive and non-homogeneous collection of real\nnumbers there exists a new collection that is $\\gamma$-equivalent,\npositive, has a strictly lower heterogeneity and a greater geometric\nmean. *}\n\nlemma new_list_gt_gmean:\n  fixes xs :: \"real list\" and m :: real\n  and neq and eq\n  defines\n    m: \"m \\<equiv> mean xs\" and\n    neq: \"noteq \\<equiv> list_neq xs m\" and\n    eq: \"eq \\<equiv> list_eq xs m\"\n  assumes pos_xs: \"pos xs\" and het_gt_0: \"het xs > 0\"\n  shows\n  \"\\<exists>xs'. gmean xs' > gmean xs \\<and> \\<gamma>_eq (xs',xs) \\<and>\n          het xs' < het xs \\<and> pos xs'\"\nproof -\n  from pos_xs pos_imp_ne have\n    pos_els: \"\\<forall>y. y : set xs \\<longrightarrow> y > 0\" by (unfold pos_def, simp)\n  with el_gt0_imp_prod_gt0 have pos_asm: \"\\<Prod>:xs > 0\" by simp\n  from neq het_gt_0 het_gt_0_imp_noteq_ne m have\n    neqne: \"noteq \\<noteq> []\" by simp\n\n  txt {* Pick two elements from xs, one greater than m, one less than m. *}\n  from assms pick_one_gt neqne obtain \\<alpha> where\n    \\<alpha>_def: \"\\<alpha> : set noteq \\<and> \\<alpha> > m\" unfolding neq m by auto\n  from assms pick_one_lt neqne obtain \\<beta> where\n    \\<beta>_def: \"\\<beta> : set noteq \\<and> \\<beta> < m\" unfolding neq m by auto\n  from \\<alpha>_def \\<beta>_def have \\<alpha>_gt: \"\\<alpha> > m\" and \\<beta>_lt: \"\\<beta> < m\" by auto\n  from \\<alpha>_def \\<beta>_def have el_neq: \"\\<beta> \\<noteq> \\<alpha>\" by simp\n  from neqne neq have xsne: \"xs \\<noteq> []\" by auto\n\n  from \\<beta>_def have \\<beta>_mem: \"\\<beta> : set xs\" by (auto simp: neq)\n  from \\<alpha>_def have \\<alpha>_mem: \"\\<alpha> : set xs\" by (auto simp: neq)\n\n  from pos_xs pos_def xsne \\<alpha>_mem \\<beta>_mem \\<alpha>_def \\<beta>_def have\n    \\<alpha>_pos: \"\\<alpha> > 0\" and \\<beta>_pos: \"\\<beta> > 0\" by auto\n\n  -- \"remove these elements from xs, and insert two new elements\"\n  obtain left_over where lo: \"left_over = (remove1 \\<beta> (remove1 \\<alpha> xs))\" by simp\n  obtain b where bdef: \"m + b = \\<alpha> + \\<beta>\"\n    by (drule meta_spec [of _ \"\\<alpha> + \\<beta> - m\"], simp)\n\n  from m pos_xs pos_def pos_mean have m_pos: \"m > 0\" by simp\n  with bdef \\<alpha>_pos \\<beta>_pos \\<alpha>_gt \\<beta>_lt have b_pos: \"b > 0\" by simp\n\n  obtain new_list where nl: \"new_list = m#b#(left_over)\" by auto\n\n  from el_neq \\<beta>_mem \\<alpha>_mem have \"\\<beta> : set xs \\<and> \\<alpha> : set xs \\<and> \\<beta> \\<noteq> \\<alpha>\" by simp\n  hence \"\\<alpha> : set (remove1 \\<beta> xs) \\<and> \\<beta> : set(remove1 \\<alpha> xs)\" by (auto simp add: in_set_remove1)\n  moreover hence \"(remove1 \\<alpha> xs) \\<noteq> [] \\<and> (remove1 \\<beta> xs) \\<noteq> []\" by (auto)\n  ultimately have\n    mem : \"\\<alpha> : set(remove1 \\<beta> xs) \\<and> \\<beta> : set(remove1 \\<alpha> xs) \\<and>\n          (remove1 \\<alpha> xs) \\<noteq> [] \\<and> (remove1 \\<beta> xs) \\<noteq> []\" by simp\n  -- \"prove that new list is positive\"\n  from nl have nl_pos: \"pos new_list\"\n  proof cases\n    assume \"left_over = []\"\n    with nl b_pos m_pos show ?thesis by simp\n  next\n    assume lone: \"left_over \\<noteq> []\"\n    from mem pos_imp_rmv_pos pos_xs have \"pos (remove1 \\<alpha> xs)\" by simp\n    with lo lone pos_imp_rmv_pos have \"pos left_over\" by simp\n    with lone mem nl m_pos b_pos show ?thesis by simp\n  qed\n\n  -- \"now show that the new list has the same mean as the old list\"\n  with mem nl lo bdef \\<alpha>_mem \\<beta>_mem\n    have \"\\<Sum>:new_list = \\<Sum>:xs\"\n      apply clarsimp\n      apply (subst listsum_rmv1)\n        apply simp\n      apply (subst listsum_rmv1)\n        apply simp\n      apply clarsimp\n    done\n  moreover from lo nl \\<beta>_mem \\<alpha>_mem mem have\n    leq: \"length new_list = length xs\"\n    apply -\n    apply (erule conjE)+\n    apply (clarsimp)\n    apply (subst length_remove1, simp)\n    apply (simp add: length_remove1)\n    apply (auto dest!:length_pos_if_in_set)\n    done\n  ultimately have eq_mean: \"mean new_list = mean xs\" by (rule list_mean_eq_iff)\n\n  -- \"finally show that the new list has a greater gmean than the old list\"\n  have gt_gmean: \"gmean new_list > gmean xs\"\n  proof -\n    from bdef \\<alpha>_gt \\<beta>_lt have \"abs (m - b) < abs (\\<alpha> - \\<beta>)\" by arith\n    moreover from bdef have \"m+b = \\<alpha>+\\<beta>\" .\n    ultimately have mb_gt_gt: \"m*b > \\<alpha>*\\<beta>\" by (rule le_diff_imp_gt_prod)\n    moreover from nl have\n      \"\\<Prod>:new_list = \\<Prod>:left_over * (m*b)\" by auto\n    moreover\n    from lo \\<alpha>_mem \\<beta>_mem mem remove1_retains_prod have\n      xsprod: \"\\<Prod>:xs = \\<Prod>:left_over * (\\<alpha>*\\<beta>)\" by auto\n    moreover from xsne have\n      \"xs \\<noteq> []\" .\n    moreover from nl have\n      nlne: \"new_list \\<noteq> []\" by simp\n    moreover from pos_asm lo have\n      \"\\<Prod>:left_over > 0\"\n      proof -\n        from pos_asm have \"\\<Prod>:xs > 0\" .\n        moreover\n        from xsprod have \"\\<Prod>:xs = \\<Prod>:left_over * (\\<alpha>*\\<beta>)\" .\n        ultimately have \"\\<Prod>:left_over * (\\<alpha>*\\<beta>) > 0\" by simp\n        moreover\n        from pos_els \\<alpha>_mem \\<beta>_mem have \"\\<alpha> > 0\" and \"\\<beta> > 0\" by auto\n        hence \"\\<alpha>*\\<beta> > 0\" by simp\n        ultimately show \"\\<Prod>:left_over > 0\"\n          apply -\n          apply (rule zero_less_mult_pos2 [where a=\"(\\<alpha> * \\<beta>)\"])\n          by auto\n      qed\n    ultimately have \"\\<Prod>:new_list > \\<Prod>:xs\"\n      by simp\n    moreover with pos_asm nl have \"\\<Prod>:new_list > 0\" by auto\n    moreover from calculation pos_asm xsne nlne leq list_gmean_gt_iff\n    show \"gmean new_list > gmean xs\" by simp\n  qed\n\n  -- \"auxiliary info\"\n  from \\<beta>_lt have \\<beta>_ne_m: \"\\<beta> \\<noteq> m\" by simp\n  from mem have\n    \\<beta>_mem_rmv_\\<alpha>: \"\\<beta> : set (remove1 \\<alpha> xs)\" and rmv_\\<alpha>_ne: \"(remove1 \\<alpha> xs) \\<noteq> []\" by auto\n\n  from \\<alpha>_def have \\<alpha>_ne_m: \"\\<alpha> \\<noteq> m\" by simp\n\n  -- \"now show that new list is more homogeneous\"\n  have lt_het: \"het new_list < het xs\"\n  proof cases\n    assume bm: \"b=m\"\n    with het_def have\n      \"het new_list = length (list_neq new_list (mean new_list))\"\n      by simp\n    also with m nl eq_mean have\n      \"\\<dots> = length (list_neq (m#b#(left_over)) m)\"\n      by simp\n    also with bm have\n      \"\\<dots> = length (list_neq left_over m)\"\n      by simp\n    also with lo \\<beta>_def \\<alpha>_def have\n      \"\\<dots> = length (list_neq (remove1 \\<beta> (remove1 \\<alpha> xs)) m)\"\n      by simp\n    also from \\<beta>_ne_m \\<beta>_mem_rmv_\\<alpha> rmv_\\<alpha>_ne have\n      \"\\<dots> < length (list_neq (remove1 \\<alpha> xs) m)\"\n      apply -\n      apply (rule list_neq_remove1)\n      by simp\n    also from \\<alpha>_mem \\<alpha>_ne_m xsne have\n      \"\\<dots> < length (list_neq xs m)\"\n      apply -\n      apply (rule list_neq_remove1)\n      by simp\n    also with m het_def have \"\\<dots> = het xs\" by simp\n    finally show \"het new_list < het xs\" .\n  next\n    assume bnm: \"b\\<noteq>m\"\n    with het_def have\n      \"het new_list = length (list_neq new_list (mean new_list))\"\n      by simp\n    also with m nl eq_mean have\n      \"\\<dots> = length (list_neq (m#b#(left_over)) m)\"\n      by simp\n    also with bnm have\n      \"\\<dots> = length (b#(list_neq left_over m))\"\n      by simp\n    also have\n      \"\\<dots> = 1 + length (list_neq left_over m)\"\n      by simp\n    also with lo \\<beta>_def \\<alpha>_def have\n      \"\\<dots> = 1 + length (list_neq (remove1 \\<beta> (remove1 \\<alpha> xs)) m)\"\n      by simp\n    also from \\<beta>_ne_m \\<beta>_mem_rmv_\\<alpha> rmv_\\<alpha>_ne have\n      \"\\<dots> < 1 + length (list_neq (remove1 \\<alpha> xs) m)\"\n      apply -\n      apply (simp only: nat_add_left_cancel_less)\n      apply (rule list_neq_remove1)\n      by simp\n    finally have\n      \"het new_list \\<le> length (list_neq (remove1 \\<alpha> xs) m)\"\n      by simp\n    also from \\<alpha>_mem \\<alpha>_ne_m xsne have \"\\<dots> < length (list_neq xs m)\"\n      apply -\n      apply (rule list_neq_remove1)\n      by simp\n    also with m het_def have \"\\<dots> = het xs\" by simp\n    finally show \"het new_list < het xs\" .\n  qed\n\n      -- \"thus thesis by existence of newlist\"\n  from \\<gamma>_eq_def lt_het gt_gmean eq_mean leq nl_pos show ?thesis by auto\nqed\n\n\ntext {* Furthermore we show that for all non-homogeneous positive\ncollections there exists another collection that is\n$\\gamma$-equivalent, positive, has a greater geometric mean {\\em and}\nis homogeneous. *}\n\nlemma existence_of_het0 [rule_format]:\n  shows \"\\<forall>x. p = het x \\<and> p > 0 \\<and> pos x \\<longrightarrow>\n  (\\<exists>y. gmean y > gmean x \\<and> \\<gamma>_eq (x,y) \\<and> het y = 0 \\<and> pos y)\"\n  (is \"?Q p\" is \"\\<forall>x. (?A x p \\<longrightarrow> ?S x)\")\nproof (induct p rule: nat_less_induct)\n  fix n\n  assume ind: \"\\<forall>m<n. ?Q m\"\n  {\n    fix x\n    assume ass: \"?A x n\"\n    hence \"het x > 0\" and \"pos x\" by auto\n    with new_list_gt_gmean have\n      \"\\<exists>y. gmean y > gmean x \\<and> \\<gamma>_eq (x,y) \\<and> het y < het x \\<and> pos y\"\n      apply - \n      apply (drule meta_spec [of _ x])\n      apply (drule meta_mp)\n        apply assumption\n      apply (drule meta_mp)\n        apply assumption\n      apply (subst(asm) \\<gamma>_eq_sym)\n      apply simp\n      done\n    then obtain \\<beta> where\n      \\<beta>_def: \"gmean \\<beta> > gmean x \\<and> \\<gamma>_eq (x,\\<beta>) \\<and> het \\<beta> < het x \\<and> pos \\<beta>\" ..\n    then obtain b where bdef: \"b = het \\<beta>\" by simp\n    with ass \\<beta>_def have \"b < n\" by auto\n    with ind have \"?Q b\" by simp\n    with \\<beta>_def have\n      ind2: \"b = het \\<beta> \\<and> 0 < b \\<and> pos \\<beta> \\<longrightarrow>\n      (\\<exists>y. gmean \\<beta> < gmean y \\<and> \\<gamma>_eq (\\<beta>, y) \\<and> het y = 0 \\<and> pos y)\" by simp\n    {\n      assume \"\\<not>(0<b)\"\n      hence \"b=0\" by simp\n      with bdef have \"het \\<beta> = 0\" by simp\n      with \\<beta>_def have \"?S x\" by auto\n    }\n    moreover\n    {\n      assume \"0 < b\"\n      with bdef ind2 \\<beta>_def have \"?S \\<beta>\" by simp\n      then obtain \\<gamma> where\n        \"gmean \\<beta> < gmean \\<gamma> \\<and> \\<gamma>_eq (\\<beta>, \\<gamma>) \\<and> het \\<gamma> = 0 \\<and> pos \\<gamma>\" ..\n      with \\<beta>_def have \"gmean x < gmean \\<gamma> \\<and> \\<gamma>_eq (x,\\<gamma>) \\<and> het \\<gamma> = 0 \\<and> pos \\<gamma>\"\n        apply clarsimp\n        apply (rule \\<gamma>_eq_trans)\n        by auto\n      hence \"?S x\" by auto\n    }\n    ultimately have \"?S x\" by auto\n  }\n  thus \"?Q n\" by simp\nqed\n\n\nsubsection {* Cauchy's Mean Theorem *}\n\ntext {* We now present the final proof of the theorem. For any\npositive collection we show that its geometric mean is less than or\nequal to its arithmetic mean. *}\n\ntheorem CauchysMeanTheorem:\n  fixes z::\"real list\"\n  assumes \"pos z\"\n  shows \"gmean z \\<le> mean z\"\nproof -\n  from `pos z` have zne: \"z\\<noteq>[]\" by (rule pos_imp_ne)\n  show \"gmean z \\<le> mean z\"\n  proof cases\n    assume \"het z = 0\"\n    with `pos z` zne het_base have \"gmean z = mean z\" by simp\n    thus ?thesis by simp\n  next\n    assume \"het z \\<noteq> 0\"\n    hence \"het z > 0\" by simp\n    moreover obtain k where \"k = het z\" by simp\n    moreover with calculation `pos z` existence_of_het0 have\n      \"\\<exists>y. gmean y > gmean z \\<and> \\<gamma>_eq (z,y) \\<and> het y = 0 \\<and> pos y\" by auto\n    then obtain \\<alpha> where\n      \"gmean \\<alpha> > gmean z \\<and> \\<gamma>_eq (z,\\<alpha>) \\<and> het \\<alpha> = 0 \\<and> pos \\<alpha>\" ..\n    with het_base \\<gamma>_eq_def pos_imp_ne have\n      \"mean z = mean \\<alpha>\" and\n      \"gmean \\<alpha> > gmean z\" and\n      \"gmean \\<alpha> = mean \\<alpha>\" by auto\n    hence \"gmean z < mean z\" by simp\n    thus ?thesis by simp\n  qed\nqed\n\ntext {* In the equality version we prove that the geometric mean\n  is identical to the arithmetic mean iff the collection is \n  homogeneous. *}\ntheorem CauchysMeanTheorem_Eq:\n  fixes z::\"real list\"\n  assumes \"pos z\"\n  shows \"gmean z = mean z \\<longleftrightarrow> het z = 0\"\nproof \n  assume \"het z = 0\"\n  with het_base[of z] `pos z` show \"gmean z = mean z\" by auto\nnext\n  assume eq: \"gmean z = mean z\"\n  show \"het z = 0\"\n  proof (rule ccontr)\n    assume \"het z \\<noteq> 0\"\n    hence \"het z > 0\" by auto\n    moreover obtain k where \"k = het z\" by simp\n    moreover with calculation `pos z` existence_of_het0 have\n      \"\\<exists>y. gmean y > gmean z \\<and> \\<gamma>_eq (z,y) \\<and> het y = 0 \\<and> pos y\" by auto\n    then obtain \\<alpha> where\n      \"gmean \\<alpha> > gmean z \\<and> \\<gamma>_eq (z,\\<alpha>) \\<and> het \\<alpha> = 0 \\<and> pos \\<alpha>\" ..\n    with het_base \\<gamma>_eq_def pos_imp_ne have\n      \"mean z = mean \\<alpha>\" and\n      \"gmean \\<alpha> > gmean z\" and\n      \"gmean \\<alpha> = mean \\<alpha>\" by auto\n    hence \"gmean z < mean z\" by simp\n    thus False using eq by auto\n  qed\nqed\n \ncorollary CauchysMeanTheorem_Less:\n  fixes z::\"real list\"\n  assumes \"pos z\" and \"het z > 0\"\n  shows \"gmean z < mean z\"\n  using \n    CauchysMeanTheorem[OF `pos z`] \n    CauchysMeanTheorem_Eq[OF `pos z`]\n    `het z > 0`\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/Cauchy/CauchysMeanTheorem.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245828938678, "lm_q2_score": 0.8577680977182187, "lm_q1q2_score": 0.714799242250701}}
{"text": "(*  Title:      Sort.thy\n    Author:     Danijela Petrovi\\'c, Facylty of Mathematics, University of Belgrade *)\n\nheader {* Verification of Imperative Heap Sort *}\n\ntheory HeapImperative\nimports Heap\nbegin \n\nprimrec left :: \"'a Tree \\<Rightarrow> 'a Tree\" where\n  \"left (T v l r) = l\"\n\nabbreviation left_val :: \"'a Tree \\<Rightarrow> 'a\" where\n  \"left_val t \\<equiv> val (left t)\"\n\nprimrec right :: \"'a Tree \\<Rightarrow> 'a Tree\" where\n  \"right (T v l r) = r\"\n\nabbreviation right_val :: \"'a Tree \\<Rightarrow> 'a\" where\n  \"right_val t \\<equiv> val (right t)\"\n\nabbreviation set_val :: \"'a Tree \\<Rightarrow> 'a \\<Rightarrow> 'a Tree\" where\n  \"set_val t x \\<equiv> T x (left t) (right t)\"\n\ntext{* The first step is to implement function {\\em siftDown}. If some node\ndoes not satisfy heap property, this function moves it down the heap\nuntil it does. For a node is checked weather it satisfies heap property or not. If it\ndoes nothing is changed. If it does not, value of the root node\nbecomes a value of the larger child and the value of that child\nbecomes the value of the root node. This is the reason this function\nis called {\\tt siftDown} -- value of the node is places down in the\nheap. Now, the problem is that the child node may not satisfy the heap\nproperty and that is the reason why function {\\tt siftDown} is\nrecursively applied. *}\n\nfun siftDown :: \"'a::linorder Tree \\<Rightarrow> 'a Tree\" where\n   \"siftDown E = E\"\n|  \"siftDown (T v E E) = T v E E\"\n|  \"siftDown (T v l E) = \n        (if v \\<ge> val l then T v l E else T (val l) (siftDown (set_val l v)) E)\"\n|  \"siftDown (T v E r) = \n        (if v \\<ge> val r then T v E r else T (val r) E (siftDown (set_val r v)))\"\n|  \"siftDown (T v l r) = \n        (if val l \\<ge> val r then \n            if v \\<ge> val l then T v l r else T (val l) (siftDown (set_val l v)) r\n        else\n            if v \\<ge> val r then T v l r else T (val r) l (siftDown (set_val r v)))\"\n\nlemma siftDown_Node:\n  assumes \"t = T v l r\"\n  shows \"\\<exists> l' v' r'. siftDown t = T v' l' r' \\<and> v' \\<ge> v\"\nusing assms\napply(induct t rule:siftDown.induct)\nby auto\n\nlemma siftDown_in_tree:\n  assumes \"t \\<noteq> E\"\n  shows \"in_tree (val (siftDown t)) t\"\nusing assms\napply(induct t rule:siftDown.induct)\nby auto\n\nlemma siftDown_in_tree_set: \n  shows \"in_tree v t \\<longleftrightarrow> in_tree v (siftDown t)\"\nproof\n  assume \"in_tree v t\"\n  thus \"in_tree v (siftDown t)\"\n    apply (induct t rule:siftDown.induct)\n    by auto\nnext\n  assume \" in_tree v (siftDown t)\"\n  thus \"in_tree v t\"\n  proof (induct t rule:siftDown.induct)\n    case 1\n    thus ?case\n      by auto\n  next\n    case (2 v1)\n    thus ?case\n      by auto\n  next\n    case (3 v2 v1 l1 r1)\n    show ?case\n    proof(cases \"v2 \\<ge> v1\")\n      case True\n      thus ?thesis\n        using 3\n        by auto\n    next\n      case False\n      show ?thesis\n      proof(cases \"v1 = v\")\n        case True\n        thus ?thesis\n          using 3 False\n          by auto\n      next\n        case False\n        hence \"in_tree v (siftDown (set_val (T v1 l1 r1) v2))\"\n          using `\\<not> v2 \\<ge> v1` 3(2)\n          by auto\n        hence \"in_tree v (T v2 l1 r1)\"\n          using 3(1) `\\<not> v2 \\<ge> v1`\n          by auto\n        thus ?thesis\n        proof(cases \"v2 = v\")\n          case True\n          thus ?thesis\n            by auto\n        next\n          case False\n          hence \"in_tree v (T v1 l1 r1)\"\n            using `in_tree v (T v2 l1 r1)`\n            by auto\n          thus ?thesis\n            by auto\n        qed\n      qed\n    qed\n  next\n    case (4 v2 v1 l1 r1)\n    show ?case\n    proof(cases \"v2 \\<ge> v1\")\n      case True\n      thus ?thesis\n        using 4\n        by auto\n    next\n      case False\n      show ?thesis\n      proof(cases \"v1 = v\")\n        case True\n        thus ?thesis\n          using 4 False\n          by auto\n      next\n        case False\n        hence \"in_tree v (siftDown (set_val (T v1 l1 r1) v2))\"\n          using `\\<not> v2 \\<ge> v1` 4(2)\n          by auto\n        hence \"in_tree v (T v2 l1 r1)\"\n          using 4(1) `\\<not> v2 \\<ge> v1`\n          by auto\n        thus ?thesis\n        proof(cases \"v2 = v\")\n          case True\n          thus ?thesis\n            by auto\n        next\n          case False\n          hence \"in_tree v (T v1 l1 r1)\"\n            using `in_tree v (T v2 l1 r1)`\n            by auto\n          thus ?thesis\n            by auto\n        qed\n      qed\n    qed\n  next\n    case (\"5_1\" v' v1 l1 r1 v2 l2 r2)\n    show ?case\n    proof(cases \"v = v' \\<or> v= v1 \\<or> v = v2\")\n      case True\n      thus ?thesis\n        by auto\n    next\n      case False\n      show ?thesis\n      proof(cases \"v1 \\<ge> v2\")\n        case True\n        show ?thesis\n        proof(cases \"v' \\<ge> v1\")\n          case True\n          thus ?thesis \n            using `v1 \\<ge> v2` \"5_1\"\n            by auto\n        next\n          case False\n          thus ?thesis\n          proof(cases \"in_tree v (T v2 l2 r2)\")\n            case True\n            thus ?thesis\n              by auto\n          next\n            case False\n            hence \"in_tree v (siftDown (set_val (T v1 l1 r1) v'))\"\n              using \"5_1\"(3) `\\<not> in_tree v (T v2 l2 r2)` `v1 \\<ge> v2` `\\<not> v' \\<ge> v1`\n              using ` \\<not> (v = v' \\<or> v = v1 \\<or> v = v2)`\n              by auto\n            hence \"in_tree v (T v' l1 r1)\"\n              using \"5_1\"(1) `v1 \\<ge> v2` `\\<not> v' \\<ge> v1`\n              by auto\n            hence \"in_tree v (T v1 l1 r1)\"\n              using  `\\<not> (v = v' \\<or> v = v1 \\<or> v = v2)`\n              by auto\n            thus ?thesis\n              by auto\n          qed\n        qed\n      next\n        case False\n        show ?thesis\n        proof(cases \"v' \\<ge> v2\")\n          case True\n          thus ?thesis \n            using `\\<not> v1 \\<ge> v2` \"5_1\"\n            by auto\n        next\n          case False\n          thus ?thesis\n          proof(cases \"in_tree v (T v1 l1 r1)\")\n            case True\n            thus ?thesis\n              by auto\n          next\n            case False\n            hence \"in_tree v (siftDown (set_val (T v2 l2 r2) v'))\"\n              using \"5_1\"(3) `\\<not> in_tree v (T v1 l1 r1)` `\\<not> v1 \\<ge> v2` `\\<not> v' \\<ge> v2`\n              using ` \\<not> (v = v' \\<or> v = v1 \\<or> v = v2)`\n              by auto\n            hence \"in_tree v (T v' l2 r2)\"\n              using \"5_1\"(2) `\\<not> v1 \\<ge> v2` `\\<not> v' \\<ge> v2`\n              by auto\n            hence \"in_tree v (T v2 l2 r2)\"\n              using  `\\<not> (v = v' \\<or> v = v1 \\<or> v = v2)`\n              by auto\n            thus ?thesis\n              by auto\n          qed\n        qed\n      qed\n    qed\n  next\n    case (\"5_2\" v' v1 l1 r1 v2 l2 r2)\n    show ?case\n    proof(cases \"v = v' \\<or> v= v1 \\<or> v = v2\")\n      case True\n      thus ?thesis\n        by auto\n    next\n      case False\n      show ?thesis\n      proof(cases \"v1 \\<ge> v2\")\n        case True\n        show ?thesis\n        proof(cases \"v' \\<ge> v1\")\n          case True\n          thus ?thesis \n            using `v1 \\<ge> v2` \"5_2\"\n            by auto\n        next\n          case False\n          thus ?thesis\n          proof(cases \"in_tree v (T v2 l2 r2)\")\n            case True\n            thus ?thesis\n              by auto\n          next\n            case False\n            hence \"in_tree v (siftDown (set_val (T v1 l1 r1) v'))\"\n              using \"5_2\"(3) `\\<not> in_tree v (T v2 l2 r2)` `v1 \\<ge> v2` `\\<not> v' \\<ge> v1`\n              using ` \\<not> (v = v' \\<or> v = v1 \\<or> v = v2)`\n              by auto\n            hence \"in_tree v (T v' l1 r1)\"\n              using \"5_2\"(1) `v1 \\<ge> v2` `\\<not> v' \\<ge> v1`\n              by auto\n            hence \"in_tree v (T v1 l1 r1)\"\n              using  `\\<not> (v = v' \\<or> v = v1 \\<or> v = v2)`\n              by auto\n            thus ?thesis\n              by auto\n          qed\n        qed\n      next\n        case False\n        show ?thesis\n        proof(cases \"v' \\<ge> v2\")\n          case True\n          thus ?thesis \n            using `\\<not> v1 \\<ge> v2` \"5_2\"\n            by auto\n        next\n          case False\n          thus ?thesis\n          proof(cases \"in_tree v (T v1 l1 r1)\")\n            case True\n            thus ?thesis\n              by auto\n          next\n            case False\n            hence \"in_tree v (siftDown (set_val (T v2 l2 r2) v'))\"\n              using \"5_2\"(3) `\\<not> in_tree v (T v1 l1 r1)` `\\<not> v1 \\<ge> v2` `\\<not> v' \\<ge> v2`\n              using ` \\<not> (v = v' \\<or> v = v1 \\<or> v = v2)`\n              by auto\n            hence \"in_tree v (T v' l2 r2)\"\n              using \"5_2\"(2) `\\<not> v1 \\<ge> v2` `\\<not> v' \\<ge> v2`\n              by auto\n            hence \"in_tree v (T v2 l2 r2)\"\n              using  `\\<not> (v = v' \\<or> v = v1 \\<or> v = v2)`\n              by auto\n            thus ?thesis\n              by auto\n          qed\n        qed\n      qed\n    qed\n  qed\nqed\n\nlemma siftDown_heap_is_heap:\n  assumes \"is_heap l\" \"is_heap r\" \"t = T v l r\"\n  shows \"is_heap (siftDown t)\"\nusing assms\nproof (induct t arbitrary: v l r  rule:siftDown.induct)\n  case 1\n  thus ?case\n    by simp\nnext\n  case (2 v')\n  show ?case\n    by simp\nnext\n  case (3 v2 v1 l1 r1)\n  show ?case\n  proof (cases \"v2 \\<ge> v1\")\n    case True\n    thus ?thesis\n      using 3(2) 3(4)\n      by auto\n  next\n    case False\n    show ?thesis\n    proof-\n      let ?t = \"siftDown (T v2 l1 r1)\"\n      obtain l' v' r' where *: \"?t = T v' l' r'\" \"v' \\<ge> v2\"\n        using siftDown_Node[of \"T v2 l1 r1\" v2 l1 r1]\n        by auto\n      have \"l = T v1 l1 r1\"\n        using 3(4)\n        by auto\n      hence \"is_heap l1\" \"is_heap r1\"\n        using 3(2)\n        apply (induct l rule:is_heap.induct)\n        by auto        \n      hence \"is_heap ?t\"\n        using 3(1)[of l1 r1 v2] False 3\n        by auto\n      show ?thesis\n      proof (cases \"v' = v2\")\n        case True\n        thus ?thesis\n          using False `is_heap ?t` *\n          by auto\n      next\n        case False\n        have \"in_tree v' ?t\"\n          using *\n          using siftDown_in_tree[of ?t]\n          by simp\n        hence \"in_tree v' (T v2 l1 r1)\"\n          using siftDown_in_tree_set[symmetric, of v' \"T v2 l1 r1\"]\n          by auto\n        hence \"in_tree v' (T v1 l1 r1)\"\n          using False\n          by simp\n        hence \"v1 \\<ge> v'\"\n          using 3\n          using is_heap_max[of v' \"T v1 l1 r1\"]\n          by auto\n        thus ?thesis\n          using `is_heap ?t` * `\\<not> v2 \\<ge> v1`\n          by auto\n      qed\n    qed\n  qed\nnext\n  case (4 v2 v1 l1 r1) \n  show ?case\n  proof(cases \"v2 \\<ge> v1\")\n    case True\n    thus ?thesis\n      using 4(2-4)\n      by auto\n  next\n    case False\n    let ?t = \"siftDown (T v2 l1 r1)\" \n    obtain v' l' r' where *: \"?t = T v' l' r'\" \"v' \\<ge> v2\"\n      using siftDown_Node[of \"T v2 l1 r1\" v2 l1 r1]\n      by auto\n    have \"r = T v1 l1 r1\"\n      using 4(4)\n      by auto\n    hence \"is_heap l1\" \"is_heap r1\"\n      using 4(3)\n      apply (induct r rule:is_heap.induct)\n      by auto\n    hence \"is_heap ?t\"\n      using False  4(1)[of l1 r1 v2]\n      by auto\n    show ?thesis\n    proof(cases \"v' = v2\")\n      case True\n      thus ?thesis\n        using * `is_heap ?t` False\n        by auto\n    next\n      case False\n      have \"in_tree v' ?t\"\n        using *\n        using siftDown_in_tree[of ?t]\n        by auto\n      hence \"in_tree v' (T v2 l1 r1)\"\n        using * siftDown_in_tree_set[of v' \"T v2 l1 r1\"]\n        by auto\n      hence \"in_tree v' (T v1 l1 r1)\"\n        using False\n        by auto\n      hence \"v1 \\<ge> v'\"\n        using is_heap_max[of v' \"T v1 l1 r1\"] 4\n        by auto\n      thus ?thesis\n        using `is_heap ?t` False *\n        by auto\n    qed\n  qed\nnext\n  case (\"5_1\" v1 v2 l2 r2 v3 l3 r3)\n  show ?case\n  proof(cases \"v2 \\<ge> v3\")\n    case True\n    show ?thesis\n    proof(cases \"v1 \\<ge> v2\")\n      case True\n      thus ?thesis\n        using `v2 \\<ge> v3` \"5_1\"\n        by auto\n    next\n      case False\n      let ?t = \"siftDown (T v1 l2 r2)\"\n      obtain l' v' r' where *: \"?t = T v' l' r'\" \"v' \\<ge> v1\"\n        using siftDown_Node\n        by blast\n      have \"is_heap l2\" \"is_heap r2\"\n        using \"5_1\"(3, 5)\n        apply(induct l rule:is_heap.induct)\n        by auto\n      hence \"is_heap ?t\"\n        using \"5_1\"(1)[of l2 r2 v1] `v2 \\<ge> v3` False \n        by auto\n      have \"v2 \\<ge> v'\"\n      proof(cases \"v' = v1\")\n        case True\n        thus ?thesis\n          using False\n          by auto\n      next\n        case False\n        have \"in_tree v' ?t\"\n          using * siftDown_in_tree\n          by auto\n        hence \"in_tree v' (T v1 l2 r2)\"\n          using siftDown_in_tree_set[of v' \"T v1 l2 r2\"]\n          by auto\n        hence \"in_tree v' (T v2 l2 r2)\"\n          using False\n          by auto\n        thus ?thesis\n          using is_heap_max[of v' \"T v2 l2 r2\"] \"5_1\"\n          by auto\n      qed\n      thus ?thesis\n        using `is_heap ?t` `v2 \\<ge> v3` * False \"5_1\"\n        by auto\n    qed\n  next\n    case False\n    show ?thesis\n    proof(cases \"v1 \\<ge> v3\")\n      case True\n      thus ?thesis\n        using `\\<not> v2 \\<ge> v3` \"5_1\"\n        by auto\n    next\n      case False\n      let ?t = \"siftDown (T v1 l3 r3)\"\n      obtain l' v' r' where *: \"?t = T v' l' r'\" \"v' \\<ge> v1\"\n        using siftDown_Node\n        by blast\n      have \"is_heap l3\" \"is_heap r3\"\n        using \"5_1\"(4, 5)\n        apply(induct r rule:is_heap.induct)\n        by auto\n      hence \"is_heap ?t\"\n        using \"5_1\"(2)[of l3 r3 v1] `\\<not> v2 \\<ge> v3` False \n        by auto\n      have \"v3 \\<ge> v'\"\n      proof(cases \"v' = v1\")\n        case True\n        thus ?thesis\n          using False\n          by auto\n      next\n        case False\n        have \"in_tree v' ?t\"\n          using * siftDown_in_tree\n          by auto\n        hence \"in_tree v' (T v1 l3 r3)\"\n          using siftDown_in_tree_set[of v' \"T v1 l3 r3\"]\n          by auto\n        hence \"in_tree v' (T v3 l3 r3)\"\n          using False\n          by auto\n        thus ?thesis\n          using is_heap_max[of v' \"T v3 l3 r3\"] \"5_1\"\n          by auto\n      qed\n      thus ?thesis\n        using `is_heap ?t` `\\<not> v2 \\<ge> v3` * False \"5_1\"\n        by auto\n    qed\n  qed          \nnext\n  case (\"5_2\" v1 v2 l2 r2 v3 l3 r3)\n  show ?case\n  proof(cases \"v2 \\<ge> v3\")\n    case True\n    show ?thesis\n    proof(cases \"v1 \\<ge> v2\")\n      case True\n      thus ?thesis\n        using `v2 \\<ge> v3` \"5_2\"\n        by auto\n    next\n      case False\n      let ?t = \"siftDown (T v1 l2 r2)\"\n      obtain l' v' r' where *: \"?t = T v' l' r'\" \"v1 \\<le> v'\"\n        using siftDown_Node\n        by blast\n      have \"is_heap l2\" \"is_heap r2\"\n        using \"5_2\"(3, 5)\n        apply(induct l rule:is_heap.induct)\n        by auto\n      hence \"is_heap ?t\"\n        using \"5_2\"(1)[of l2 r2 v1] `v2 \\<ge> v3` False \n        by auto\n      have \"v2 \\<ge> v'\"\n      proof(cases \"v' = v1\")\n        case True\n        thus ?thesis\n          using False\n          by auto\n      next\n        case False\n        have \"in_tree v' ?t\"\n          using * siftDown_in_tree\n          by auto\n        hence \"in_tree v' (T v1 l2 r2)\"\n          using siftDown_in_tree_set[of v' \"T v1 l2 r2\"]\n          by auto\n        hence \"in_tree v' (T v2 l2 r2)\"\n          using False\n          by auto\n        thus ?thesis\n          using is_heap_max[of v' \"T v2 l2 r2\"] \"5_2\"\n          by auto\n      qed\n      thus ?thesis\n        using `is_heap ?t` `v2 \\<ge> v3` * False \"5_2\"\n        by auto\n    qed\n  next\n    case False\n    show ?thesis\n    proof(cases \"v1 \\<ge> v3\")\n      case True\n      thus ?thesis\n        using `\\<not> v2 \\<ge> v3` \"5_2\"\n        by auto\n    next\n      case False\n      let ?t = \"siftDown (T v1 l3 r3)\"\n      obtain l' v' r' where *: \"?t = T v' l' r'\" \"v' \\<ge> v1\"\n        using siftDown_Node\n        by blast\n      have \"is_heap l3\" \"is_heap r3\"\n        using \"5_2\"(4, 5)\n        apply(induct r rule:is_heap.induct)\n        by auto\n      hence \"is_heap ?t\"\n        using \"5_2\"(2)[of l3 r3 v1] `\\<not> v2 \\<ge> v3` False \n        by auto\n      have \"v3 \\<ge> v'\"\n      proof(cases \"v' = v1\")\n        case True\n        thus ?thesis\n          using False\n          by auto\n      next\n        case False\n        have \"in_tree v' ?t\"\n          using * siftDown_in_tree\n          by auto\n        hence \"in_tree v' (T v1 l3 r3)\"\n          using siftDown_in_tree_set[of v' \"T v1 l3 r3\"]\n          by auto\n        hence \"in_tree v' (T v3 l3 r3)\"\n          using False\n          by auto\n        thus ?thesis\n          using is_heap_max[of v' \"T v3 l3 r3\"] \"5_2\"\n          by auto\n      qed\n      thus ?thesis\n        using `is_heap ?t` `\\<not> v2 \\<ge> v3` * False \"5_2\"\n        by auto\n    qed\n  qed          \nqed\n\ntext{* Definition of the function {\\em heapify} which\nmakes a heap from any given binary tree. *}\n\nprimrec heapify where\n   \"heapify E = E\"\n|  \"heapify (T v l r) = siftDown (T v (heapify l) (heapify r))\"\n\nlemma heapify_heap_is_heap:\n  \"is_heap (heapify t)\"\nproof(induct t)\n  case E\n  thus ?case\n    by auto\nnext\n  case (T v l r)\n  thus ?case\n    using siftDown_heap_is_heap[of \"heapify l\" \"heapify r\" \"T v (heapify l) (heapify r)\" v]\n    by auto\nqed\n\ntext{* Definition of {\\em removeLeaf} function.  Function returns two values. The first one\nis the value of romoved leaf element. The second returned value is tree without that leaf. *}\n\nfun removeLeaf:: \"'a::linorder Tree \\<Rightarrow> 'a \\<times> 'a Tree\" where\n  \"removeLeaf (T v E E) = (v, E)\"\n| \"removeLeaf (T v l E) = (fst (removeLeaf l), T v (snd (removeLeaf l)) E)\"\n| \"removeLeaf (T v E r) = (fst (removeLeaf r), T v E (snd (removeLeaf r)))\"\n| \"removeLeaf (T v l r) = (fst (removeLeaf l), T v (snd (removeLeaf l)) r)\"\n\ntext{* Function {\\em of\\_list\\_tree} makes a binary tree from any given\nlist. *}\n\nprimrec of_list_tree:: \"'a::linorder list \\<Rightarrow> 'a Tree\" where\n  \"of_list_tree [] = E\"\n| \"of_list_tree (v # tail) = T v (of_list_tree tail) E\"\n\ntext{* By applying {\\em heapify} binary tree is transformed into\nheap.  *}\n\ndefinition hs_of_list where\n  \"hs_of_list l = heapify (of_list_tree l)\"\n\ntext{* Definition of function {\\em hs\\_remove\\_max}. As it is already well\nestablished, finding maximum is not a problem, since it is in the root\nelement of the heap. The root element is replaced with leaf of the\nheap and that leaf is erased from its previous position. However, now\nthe new root element may not satisfy heap property and that is the\nreason to apply function {\\em siftDown}. *}\n\ndefinition hs_remove_max :: \"'a::linorder Tree \\<Rightarrow> 'a \\<times> 'a Tree\" where\n  \"hs_remove_max t \\<equiv>\n     (let v' = fst (removeLeaf t);\n          t' = snd (removeLeaf t) in\n     (if t' = E then (val t, E)\n      else (val t, siftDown (set_val t' v'))))\"\n\ndefinition hs_is_empty where\n[simp]: \"hs_is_empty t \\<longleftrightarrow>  t = E\"\n\nlemma siftDown_multiset:\n  \"multiset (siftDown t) = multiset t\"\nproof(induct t rule:siftDown.induct)\n  case 1\n  thus ?case\n    by simp\nnext\n  case (2 v)\n  thus ?case\n    by simp\nnext\n  case (3 v1 v l r)\n  thus ?case\n  proof(cases \"v \\<le> v1\")\n    case True\n    thus ?thesis\n      by auto\n  next\n    case False\n    hence \"multiset (siftDown (T v1 (T v l r) E)) = \n           multiset l + {#v1#} + multiset r + {#v#}\"\n      using 3\n      by auto\n    moreover\n    have \"multiset (T v1 (T v l r) E) = \n          multiset l + {#v#} + multiset r + {#v1#}\"\n      by auto\n    moreover\n    have \"multiset l + {#v1#} + multiset r + {#v#} = \n          multiset l + {#v#} + multiset r + {#v1#}\"\n      by (metis union_commute union_lcomm)\n    ultimately\n    show ?thesis\n      by auto\n  qed\nnext\n  case (4 v1 v l r)\n  thus ?case\n  proof(cases \"v \\<le> v1\")\n    case True\n    thus ?thesis\n      by auto\n  next\n    case False\n    have \"multiset (set_val (T v l r) v1) = \n          multiset l + {#v1#} + multiset r\"\n      by auto\n    hence \"multiset (siftDown (T v1 E (T v l r))) = \n           {#v#} +  multiset (set_val (T v l r) v1)\"\n      using 4 False\n      by auto\n    hence \"multiset (siftDown (T v1 E (T v l r))) = \n           {#v#} + multiset l + {#v1#} + multiset r\"\n      using `multiset (set_val (T v l r) v1) = \n             multiset l + {#v1#} + multiset r`\n      by (metis union_commute union_lcomm)\n    moreover\n    have \"multiset (T v1 E (T v l r)) =  \n          {#v1#} + multiset l + {#v#} + multiset r\"\n      by (metis calculation comm_monoid_add_class.add.left_neutral \n          multiset.simps(1) multiset.simps(2) union_commute union_lcomm)\n    moreover\n    have \"{#v#} + multiset l + {#v1#} + multiset r = \n          {#v1#} + multiset l + {#v#} + multiset r\"\n      by (metis union_commute union_lcomm)\n    ultimately\n    show ?thesis\n      by auto\n  qed\nnext\n  case (\"5_1\" v v1 l1 r1 v2 l2 r2)\n  thus ?case\n  proof(cases \"v1 \\<ge> v2\")\n    case True\n    thus ?thesis\n    proof(cases \"v \\<ge> v1\")\n      case True\n      thus ?thesis\n        using `v1 \\<ge> v2`\n        by auto\n    next\n      case False\n      hence \"multiset (siftDown (T v (T v1 l1 r1) (T v2 l2 r2))) = \n             multiset l1 + {#v#} + multiset r1 + {#v1#} + \n             multiset (T v2 l2 r2)\"\n        using `v1 \\<ge> v2` \"5_1\"(1)\n        by auto\n      moreover\n      have \"multiset (T v (T v1 l1 r1) (T v2 l2 r2)) = \n              multiset l1 + {#v1#} + multiset r1 + {#v#} +\n              multiset(T v2 l2 r2)\"\n        by auto\n      moreover\n      have \"multiset l1 + {#v1#} + multiset r1 + {#v#} + \n            multiset(T v2 l2 r2) = \n                multiset l1 + {#v#} + multiset r1 + {#v1#} + \n                multiset (T v2 l2 r2)\"\n        by (metis union_commute union_lcomm)\n      ultimately\n      show ?thesis\n        by auto\n    qed\n  next\n    case False\n    show ?thesis\n    proof(cases \"v \\<ge> v2\")\n      case True\n      thus ?thesis\n        using False\n        by auto\n    next\n      case False\n      hence \"multiset (siftDown (T v (T v1 l1 r1) (T v2 l2 r2))) = \n             multiset (T v1 l1 r1) + {#v2#} + \n             multiset l2 + {#v#} + multiset r2\"\n        using `\\<not> v1 \\<ge> v2` \"5_1\"(2)\n        by (simp add: ac_simps)\n      moreover\n      have \n        \"multiset (T v (T v1 l1 r1) (T v2 l2 r2)) = \n         multiset (T v1 l1 r1) + {#v#} + multiset l2 + \n         {#v2#} + multiset r2\"\n        by (metis (hide_lams, no_types) multiset.simps(2) \n            union_assoc union_commute union_lcomm)\n      moreover\n      have \n        \"multiset (T v1 l1 r1) + {#v#} + multiset l2 + {#v2#} + \n         multiset r2 = \n            multiset (T v1 l1 r1) + {#v2#} + multiset l2 + \n            {#v#} + multiset r2\"\n        by (metis union_commute union_lcomm)\n      ultimately\n      show ?thesis\n        by auto\n    qed\n  qed\nnext\n  case (\"5_2\" v v1 l1 r1 v2 l2 r2)\n  thus ?case\n  proof(cases \"v1 \\<ge> v2\")\n    case True\n    thus ?thesis\n    proof(cases \"v \\<ge> v1\")\n      case True\n      thus ?thesis\n        using `v1 \\<ge> v2`\n        by auto\n    next\n      case False\n      hence \"multiset (siftDown (T v (T v1 l1 r1) (T v2 l2 r2))) = \n               multiset l1 + {#v#} + multiset r1 + {#v1#} + \n               multiset (T v2 l2 r2)\"\n        using `v1 \\<ge> v2` \"5_2\"(1)\n        by auto\n      moreover\n      have \"multiset (T v (T v1 l1 r1) (T v2 l2 r2)) = \n              multiset l1 + {#v1#} + multiset r1 + \n              {#v#} + multiset(T v2 l2 r2)\"\n        by auto\n      moreover\n      have \"multiset l1 + {#v1#} + multiset r1 + {#v#} + \n            multiset(T v2 l2 r2) = \n              multiset l1 + {#v#} + multiset r1 + {#v1#} + \n              multiset (T v2 l2 r2)\"\n        by (metis union_commute union_lcomm)\n      ultimately\n      show ?thesis\n        by auto\n    qed\n  next\n    case False\n    show ?thesis\n    proof(cases \"v \\<ge> v2\")\n      case True\n      thus ?thesis\n        using False\n        by auto\n    next\n      case False\n      hence \"multiset (siftDown (T v (T v1 l1 r1) (T v2 l2 r2))) = \n               multiset (T v1 l1 r1) + {#v2#} + multiset l2 + {#v#} + \n               multiset r2\"\n        using `\\<not> v1 \\<ge> v2` \"5_2\"(2)\n        by (simp add: ac_simps)\n      moreover\n      have \"multiset (T v (T v1 l1 r1) (T v2 l2 r2)) = \n              multiset (T v1 l1 r1) + {#v#} + multiset l2 + {#v2#} + \n              multiset r2\"\n        by (metis (hide_lams, no_types) multiset.simps(2) \n            union_assoc union_commute union_lcomm)\n      moreover\n      have \"multiset (T v1 l1 r1) + {#v#} + multiset l2 + {#v2#} + \n            multiset r2 = \n              multiset (T v1 l1 r1) + {#v2#} + multiset l2 + {#v#} + \n              multiset r2\"\n        by (metis union_commute union_lcomm)\n      ultimately\n      show ?thesis\n        by auto\n    qed\n  qed\nqed\n\nlemma multiset_of_list_tree:\n \"multiset (of_list_tree l) = multiset_of l\"\nproof(induct l)\n  case Nil\n  thus ?case\n    by auto\nnext\n  case (Cons v tail)\n  hence \"multiset (of_list_tree (v # tail)) = multiset_of tail + {#v#}\"\n    by auto\n  also have \"... = multiset_of (v # tail)\"\n    by auto\n  finally show \"multiset (of_list_tree (v # tail)) = multiset_of (v # tail)\"\n    by auto\nqed\n  \n\nlemma multiset_heapify:\n  \"multiset (heapify t) = multiset t\"\nproof(induct t)\n  case E\n  thus ?case\n    by auto\nnext\n  case (T v l r)\n  hence \"multiset (heapify (T v l r)) = multiset l + {#v#} + multiset r\"\n    using siftDown_multiset[of \"T v (heapify l) (heapify r)\"]\n    by auto\n  thus ?case\n    by auto\nqed\n    \n\nlemma multiset_heapify_of_list_tree:\n  \"multiset (heapify (of_list_tree l)) = multiset_of l\"\nusing multiset_heapify[of \"of_list_tree l\"]\nusing multiset_of_list_tree[of l]\nby auto\n\nlemma removeLeaf_val_val:\n  assumes \"snd (removeLeaf t) \\<noteq> E\" \"t \\<noteq> E\"\n  shows \"val t = val (snd (removeLeaf t))\"\nusing assms\napply (induct t rule:removeLeaf.induct)\nby auto\n\nlemma removeLeaf_heap_is_heap: \n  assumes \"is_heap t\" \"t \\<noteq> E\"\n  shows \"is_heap (snd (removeLeaf t))\"\nusing assms\nproof(induct t rule:removeLeaf.induct)\n  case (1 v)\n  thus ?case\n    by auto\nnext\n  case (2 v v1 l1 r1)\n  have \"is_heap (T v1 l1 r1)\"\n    using 2(3)\n    by auto\n  hence \"is_heap (snd (removeLeaf (T v1 l1 r1)))\"\n    using 2(1)\n    by auto\n  let ?t = \"(snd (removeLeaf (T v1 l1 r1)))\"\n  show ?case\n  proof(cases \"?t = E\")\n    case True\n    thus ?thesis\n      by auto\n  next\n    case False\n    have \"v \\<ge> v1\"\n      using 2(3)\n      by auto\n    hence \"v \\<ge> val ?t\"\n      using False removeLeaf_val_val[of \"T v1 l1 r1\"]\n      by auto\n    hence \"is_heap (T v (snd (removeLeaf (T v1 l1 r1))) E)\"\n      using `is_heap (snd (removeLeaf (T v1 l1 r1)))`\n      by (metis Tree.exhaust is_heap.simps(2) is_heap.simps(4))\n    thus ?thesis\n      using 2\n      by auto\n  qed\nnext\n  case (3 v v1 l1 r1)\n  have \"is_heap (T v1 l1 r1)\"\n    using 3(3)\n    by auto\n  hence \"is_heap (snd (removeLeaf (T v1 l1 r1)))\"\n    using 3(1)\n    by auto\n  let ?t = \"(snd (removeLeaf (T v1 l1 r1)))\"\n  show ?case\n  proof(cases \"?t = E\")\n    case True\n    thus ?thesis\n      by auto\n  next\n    case False\n    have \"v \\<ge> v1\"\n      using 3(3)\n      by auto\n    hence \"v \\<ge> val ?t\"\n      using False removeLeaf_val_val[of \"T v1 l1 r1\"]\n      by auto\n    hence \"is_heap (T v E (snd (removeLeaf (T v1 l1 r1))))\"\n      using `is_heap (snd (removeLeaf (T v1 l1 r1)))`\n      by (metis False Tree.exhaust is_heap.simps(3))\n    thus ?thesis\n      using 3\n      by auto\n  qed\nnext\n  case (\"4_1\" v v1 l1 r1 v2 l2 r2)\n  have \"is_heap (T v1 l1 r1)\" \"is_heap (T v2 l2 r2)\" \"v \\<ge> v1\" \"v \\<ge> v2\"\n    using \"4_1\"(3)\n    by (simp add:is_heap.simps(5))+\n  hence \"is_heap (snd (removeLeaf (T v1 l1 r1)))\"\n    using \"4_1\"(1)\n    by auto\n  let ?t = \"(snd (removeLeaf (T v1 l1 r1)))\"\n  show ?case\n  proof(cases \"?t = E\")\n    case True\n    thus ?thesis\n      using `is_heap (T v2 l2 r2)` `v \\<ge> v2`\n      by auto\n  next\n    case False\n    then obtain v1' l1' r1' where \"?t = T v1' l1' r1'\"\n      by (metis Tree.exhaust)\n    hence \"is_heap (T v1' l1' r1')\"\n      using `is_heap (snd (removeLeaf (T v1 l1 r1)))`\n      by auto\n    have \"v \\<ge> v1\"\n      using \"4_1\"(3)\n      by auto\n    hence \"v \\<ge> val ?t\"\n      using False removeLeaf_val_val[of \"T v1 l1 r1\"]\n      by auto\n    hence \"v \\<ge> v1'\"\n      using `?t = T v1' l1' r1'`\n      by auto\n    hence \"is_heap (T v (T v1' l1' r1') (T v2 l2 r2))\"\n      using `is_heap (T v1' l1' r1')`\n      using `is_heap (T v2 l2 r2)` `v \\<ge> v2`\n      by (simp add: is_heap.simps(5))\n    thus ?thesis\n      using \"4_1\" `?t = T v1' l1' r1'`\n      by auto\n  qed\nnext\n  case (\"4_2\" v v1 l1 r1 v2 l2 r2)\n  have \"is_heap (T v1 l1 r1)\" \"is_heap (T v2 l2 r2)\" \"v \\<ge> v1\" \"v \\<ge> v2\"\n    using \"4_2\"(3)\n    by (simp add:is_heap.simps(5))+\n  hence \"is_heap (snd (removeLeaf (T v1 l1 r1)))\"\n    using \"4_2\"(1)\n    by auto\n  let ?t = \"(snd (removeLeaf (T v1 l1 r1)))\"\n  show ?case\n  proof(cases \"?t = E\")\n    case True\n    thus ?thesis\n      using `is_heap (T v2 l2 r2)` `v \\<ge> v2`\n      by auto\n  next\n    case False\n    then obtain v1' l1' r1' where \"?t = T v1' l1' r1'\"\n      by (metis Tree.exhaust)\n    hence \"is_heap (T v1' l1' r1')\"\n      using `is_heap (snd (removeLeaf (T v1 l1 r1)))`\n      by auto\n    have \"v \\<ge> v1\"\n      using \"4_2\"(3)\n      by auto\n    hence \"v \\<ge> val ?t\"\n      using False removeLeaf_val_val[of \"T v1 l1 r1\"]\n      by auto\n    hence \"v \\<ge> v1'\"\n      using `?t = T v1' l1' r1'`\n      by auto\n    hence \"is_heap (T v (T v1' l1' r1') (T v2 l2 r2))\"\n      using `is_heap (T v1' l1' r1')`\n      using `is_heap (T v2 l2 r2)` `v \\<ge> v2`\n      by (simp add: is_heap.simps(5))\n    thus ?thesis\n      using \"4_2\" `?t = T v1' l1' r1'`\n      by auto\n  qed\nnext\n  case 5\n  thus ?case\n    by auto\nqed\n\ntext{* Difined functions satisfy conditions of locale {\\em Collection} and thus represent \n       interpretation of this locale. *}\n\ninterpretation HS: Collection \"E\" hs_is_empty hs_of_list multiset\nproof\n  fix t\n  assume \"hs_is_empty t\"\n  thus \"t = E\"\n    by auto\nnext\n  show \"hs_is_empty E\"\n    by auto\nnext\n  show \"multiset E = {#}\"\n    by auto\nnext\n  fix l\n  show \"multiset (hs_of_list l) = multiset_of l\"\n    unfolding hs_of_list_def\n    using multiset_heapify_of_list_tree[of l]\n    by auto\nqed\n\nlemma removeLeaf_multiset:\n  assumes \"(v', t') = removeLeaf t\" \"t \\<noteq> E\"\n  shows \"{#v'#} + multiset t' = multiset t\"\nusing assms\nproof(induct t arbitrary: v' t' rule:removeLeaf.induct)\n  case 1\n  thus ?case\n    by auto\nnext\n  case (2 v v1 l1 r1)\n  have \"t' = T v (snd (removeLeaf (T v1 l1 r1))) E\"\n    using 2(3)\n    by auto\n  have \"v' = fst (removeLeaf (T v1 l1 r1))\"\n    using 2(3)\n    by auto\n  hence \"{#v'#} + multiset t' = \n           {#fst (removeLeaf (T v1 l1 r1))#} + \n           multiset (snd (removeLeaf (T v1 l1 r1))) + \n           {#v#}\"\n    using `t' = T v (snd (removeLeaf (T v1 l1 r1))) E`\n    by (simp add: ac_simps)\n  have \"{#fst (removeLeaf (T v1 l1 r1))#} + \n        multiset (snd (removeLeaf (T v1 l1 r1))) = \n          multiset (T v1 l1 r1)\"\n    using 2(1)\n    by auto\n  hence \"{#v'#} + multiset t' = multiset (T v1 l1 r1) + {#v#}\"\n    using `{#v'#} + multiset t' = \n           {#fst (removeLeaf (T v1 l1 r1))#} + \n           multiset (snd (removeLeaf (T v1 l1 r1))) + {#v#}`\n    by auto\n  thus ?case\n    by auto\nnext\n  case (3 v v1 l1 r1)\n  have \"t' = T v E (snd (removeLeaf (T v1 l1 r1)))\"\n    using 3(3)\n    by auto\n  have \"v' = fst (removeLeaf (T v1 l1 r1))\"\n    using 3(3)\n    by auto\n  hence \"{#v'#} + multiset t' = \n          {#fst (removeLeaf (T v1 l1 r1))#} + \n          multiset (snd (removeLeaf (T v1 l1 r1))) + \n          {#v#}\"\n    using `t' = T v E (snd (removeLeaf (T v1 l1 r1)))`\n    by (simp add: ac_simps)\n  have \"{#fst (removeLeaf (T v1 l1 r1))#} + \n        multiset (snd (removeLeaf (T v1 l1 r1))) = \n          multiset (T v1 l1 r1)\"\n    using 3(1)\n    by auto\n  hence \"{#v'#} + multiset t' = multiset (T v1 l1 r1) + {#v#}\"\n    using `{#v'#} + multiset t' = \n           {#fst (removeLeaf (T v1 l1 r1))#} + \n           multiset (snd (removeLeaf (T v1 l1 r1))) + {#v#}`\n    by auto\n  thus ?case\n    by (metis comm_monoid_add_class.add.right_neutral \n        multiset.simps(1) multiset.simps(2) union_commute)\nnext\n  case (\"4_1\" v v1 l1 r1 v2 l2 r2)\n  have \"t' = T v (snd (removeLeaf (T v1 l1 r1))) (T v2 l2 r2)\"\n    using \"4_1\"(3)\n    by auto\n  have \"v' = fst (removeLeaf (T v1 l1 r1))\"\n    using \"4_1\"(3)\n    by auto\n  hence \"{#v'#} + multiset t' = \n         {#fst (removeLeaf (T v1 l1 r1))#} + \n         multiset (snd (removeLeaf (T v1 l1 r1))) + \n         {#v#} + multiset (T v2 l2 r2)\"\n    using `t' = T v (snd (removeLeaf (T v1 l1 r1))) (T v2 l2 r2)`\n    by (metis multiset.simps(2) union_assoc)\n  have \"{#fst (removeLeaf (T v1 l1 r1))#} + \n        multiset (snd (removeLeaf (T v1 l1 r1))) = \n          multiset (T v1 l1 r1)\"\n    using \"4_1\"(1)\n    by auto\n  hence \"{#v'#} + multiset t' = \n           multiset (T v1 l1 r1) + {#v#} + multiset (T v2 l2 r2)\"\n    using `{#v'#} + multiset t' = \n           {#fst (removeLeaf (T v1 l1 r1))#} + \n           multiset (snd (removeLeaf (T v1 l1 r1))) + \n           {#v#} + multiset (T v2 l2 r2)`\n    by auto\n  thus ?case\n    by auto\nnext\n  case (\"4_2\" v v1 l1 r1 v2 l2 r2)\n  have \"t' = T v (snd (removeLeaf (T v1 l1 r1))) (T v2 l2 r2)\"\n    using \"4_2\"(3)\n    by auto\n  have \"v' = fst (removeLeaf (T v1 l1 r1))\"\n    using \"4_2\"(3)\n    by auto\n  hence \"{#v'#} + multiset t' = \n         {#fst (removeLeaf (T v1 l1 r1))#} + \n         multiset (snd (removeLeaf (T v1 l1 r1))) + \n         {#v#} + multiset (T v2 l2 r2)\"\n    using `t' = T v (snd (removeLeaf (T v1 l1 r1))) (T v2 l2 r2)`\n    by (metis multiset.simps(2) union_assoc)\n  have \"{#fst (removeLeaf (T v1 l1 r1))#} + \n        multiset (snd (removeLeaf (T v1 l1 r1))) = \n          multiset (T v1 l1 r1)\"\n    using \"4_2\"(1)\n    by auto\n  hence \"{#v'#} + multiset t' = \n         multiset (T v1 l1 r1) + {#v#} + multiset (T v2 l2 r2)\"\n    using `{#v'#} + multiset t' = \n           {#fst (removeLeaf (T v1 l1 r1))#} + \n           multiset (snd (removeLeaf (T v1 l1 r1))) + \n           {#v#} + multiset (T v2 l2 r2)`\n    by auto\n  thus ?case\n    by auto\nnext\n  case 5\n  thus ?case\n    by auto\nqed\n\nlemma set_val_multiset:\n  assumes \"t \\<noteq> E\"\n  shows \"multiset (set_val t v') +  {#val t#} = {#v'#} + multiset t\"\nproof-\n  obtain v l r where \"t = T v l r\"\n    using assms\n    by (metis Tree.exhaust)\n  hence \"multiset (set_val t v') + {#val t#} = \n         multiset l + {#v'#} + multiset r + {#v#}\"\n    by auto\n  have \"{#v'#} + multiset t = \n        {#v'#} + multiset l + {#v#} + multiset r\"\n    using `t = T v l r`\n    by (metis multiset.simps(2) union_assoc)\n  have \"{#v'#} + multiset l + {#v#} + multiset r = \n        multiset l + {#v'#} + multiset r + {#v#}\"\n    by (metis union_commute union_lcomm)\n  thus ?thesis\n    using `multiset (set_val t v') + {#val t#} = \n           multiset l + {#v'#} + multiset r + {#v#}`\n    using `{#v'#} + multiset t = \n           {#v'#} + multiset l + {#v#} + multiset r`\n    by auto\nqed\n\nlemma hs_remove_max_multiset:\n  assumes \"(m, t') = hs_remove_max t\" \"t \\<noteq> E\"\n  shows \"{#m#} + multiset t' = multiset t\"\nproof-\n  let ?v1 = \"fst (removeLeaf t)\"\n  let ?t1 = \"snd (removeLeaf t)\"\n  show ?thesis\n  proof(cases \"?t1 = E\")\n    case True\n    hence \"{#m#} + multiset t' = {#m#}\"\n      using assms\n      unfolding hs_remove_max_def\n      by auto\n    have \"?v1 = val t\"\n      using True assms(2)\n      apply (induct t rule:removeLeaf.induct)\n      by auto\n    hence \"?v1 = m\"\n      using assms(1) True\n      unfolding hs_remove_max_def\n      by auto\n    hence \"multiset t = {#m#}\"\n      using removeLeaf_multiset[of ?v1 ?t1 t] True assms(2)\n      by (metis empty_neutral(2) multiset.simps(1) pair_collapse)\n    thus ?thesis\n      using `{#m#} + multiset t' = {#m#}`\n      by auto\n  next\n    case False\n    hence \"t' = siftDown (set_val ?t1 ?v1)\"\n      using assms(1)\n      by (auto simp add: hs_remove_max_def) (metis prod.inject)\n    hence \"multiset t' + {#val ?t1#} = multiset t\"\n      using siftDown_multiset[of \"set_val ?t1 ?v1\"]\n      using set_val_multiset[of ?t1 ?v1] False\n      using removeLeaf_multiset[of ?v1 ?t1 t] assms(2)\n      by auto\n    have \"val ?t1 = val t\"\n      using False assms(2)\n      apply (induct t rule:removeLeaf.induct)\n      by auto\n    have \"val t = m\"\n      using assms(1) False\n      using `t' = siftDown (set_val ?t1 ?v1)`\n      unfolding hs_remove_max_def\n      by (metis (full_types) fst_conv removeLeaf.simps(1))    \n    hence \"val ?t1 = m\"\n      using `val ?t1 = val t`\n      by auto\n    hence \"multiset t' + {#m#} = multiset t\"\n      using `multiset t' + {#val ?t1#} = multiset t`\n      by metis\n    thus ?thesis\n      by (metis union_commute)\n  qed\nqed\n\ntext{* Difined functions satisfy conditions of locale {\\em Heap} and thus represent \n       interpretation of this locale. *}\n\ninterpretation Heap \"E\" hs_is_empty hs_of_list multiset id hs_remove_max\nproof\n  fix t\n  show \"multiset t = multiset (id t)\"\n    by auto\nnext\n  fix t\n  show \" is_heap (id (hs_of_list t))\"\n    unfolding hs_of_list_def\n    using heapify_heap_is_heap[of \"of_list_tree t\"]\n    by auto\nnext\n  fix t\n  show \"(id t = E) = hs_is_empty t\"\n    by auto\nnext\n  fix t m t'\n  assume \"\\<not> hs_is_empty t\" \"(m, t') = hs_remove_max t\"\n  thus \"multiset t' + {#m#} = multiset t\"\n    using hs_remove_max_multiset[of m t' t]\n    by (auto, metis union_commute)\nnext\n  fix t v' t' \n  assume \"\\<not> hs_is_empty t\" \"is_heap (id t)\" \"(v', t') = hs_remove_max t\"\n  let ?v1 = \"fst (removeLeaf t)\"\n  let ?t1 = \"snd (removeLeaf t)\"\n  have \"is_heap ?t1\"\n    using `\\<not> hs_is_empty t` `is_heap (id t)`\n    using removeLeaf_heap_is_heap[of t]\n    by auto\n  show \"is_heap (id t')\"\n  proof(cases \"?t1 = E\")\n    case True\n    hence \"t' = E\"\n      using `(v', t') = hs_remove_max t`\n      unfolding hs_remove_max_def\n      by auto\n    thus ?thesis\n      by auto\n  next\n    case False\n    then obtain v_t1 l_t1 r_t1 where \"?t1 = T v_t1 l_t1 r_t1\"\n      by (metis Tree.exhaust)\n    hence \"is_heap l_t1\" \"is_heap r_t1\"\n      using `is_heap ?t1`\n      by (auto, metis (full_types) Tree.exhaust \n         is_heap.simps(1) is_heap.simps(4) is_heap.simps(5))\n         (metis (full_types) Tree.exhaust \n          is_heap.simps(1) is_heap.simps(3) is_heap.simps(5))\n    have \"set_val ?t1 ?v1 = T ?v1 l_t1 r_t1\"\n      using `?t1 = T v_t1 l_t1 r_t1`\n      by auto\n    hence \"is_heap (siftDown (set_val ?t1 ?v1))\"\n      using `is_heap l_t1` `is_heap r_t1`\n      using siftDown_heap_is_heap[of l_t1 r_t1 \"set_val ?t1 ?v1\" ?v1]\n      by auto\n    have \"t' = siftDown (set_val ?t1 ?v1)\"\n      using `(v', t') = hs_remove_max t` False\n      by (auto simp add: hs_remove_max_def) (metis prod.inject)\n    thus ?thesis\n      using `is_heap (siftDown (set_val ?t1 ?v1))`\n      by auto\n  qed\nnext\n  fix t m t'\n  let ?t1 = \"snd (removeLeaf t)\"\n  assume \"\\<not> hs_is_empty t\" \"(m, t') = hs_remove_max t\"\n  hence \"m = val t\"\n    apply (simp add: hs_remove_max_def)\n    apply (cases \"?t1 = E\")\n    by (auto, metis prod.inject)    \n  thus \"m = val (id t)\"\n    by auto\nqed\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/Selection_Heap_Sort/HeapImperative.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8872046026642945, "lm_q2_score": 0.8056321936479701, "lm_q1q2_score": 0.7147605902590113}}
{"text": "(*\n  Authors: Asta Halkj\u00e6r From, Agnes Moesg\u00e5rd Eschen & J\u00f8rgen Villadsen, DTU Compute\n*)\n\ntheory System_V imports Main begin\n\nsection \\<open>Syntax / Semantics\\<close>\n\ndatatype form = Falsity (\\<open>\\<bottom>\\<close>) | Pro nat (\\<open>\\<cdot>\\<close>) | Imp form form (infix \\<open>\\<rightarrow>\\<close> 0)\n\nprimrec semantics (infix \\<open>\\<Turnstile>\\<close> 0) where\n  \\<open>(I \\<Turnstile> \\<bottom>) = False\\<close> |\n  \\<open>(I \\<Turnstile> \\<cdot> n) = I n\\<close> |\n  \\<open>(I \\<Turnstile> (p \\<rightarrow> q)) = ((I \\<Turnstile> p) \\<longrightarrow> (I \\<Turnstile> q))\\<close>\n\nabbreviation \\<open>valid p \\<equiv> \\<forall>I. (I \\<Turnstile> p)\\<close>\n\nsection \\<open>Axiomatic System\\<close>\n\ninductive V (\\<open>\\<then>\\<close>) where\n  MP: \\<open>\\<then> p\\<close> if \\<open>\\<then> q\\<close> and \\<open>\\<then> (q \\<rightarrow> p)\\<close> |\n  CC: \\<open>\\<then> p\\<close> if \\<open>\\<then> ((p \\<rightarrow> q) \\<rightarrow> p)\\<close> |\n  Tran: \\<open>\\<then> ((q \\<rightarrow> r) \\<rightarrow> ((r \\<rightarrow> p) \\<rightarrow> (q \\<rightarrow> p)))\\<close> |\n  Simp: \\<open>\\<then> (p \\<rightarrow> (q \\<rightarrow> p))\\<close> |\n  Expl: \\<open>\\<then> (\\<bottom> \\<rightarrow> p)\\<close>\n\nsection \\<open>Soundness\\<close>\n\ntheorem soundness: \\<open>valid p\\<close> if \\<open>\\<then> p\\<close>\n  using that by induct auto\n\nsection \\<open>Derived Rules\\<close>\n\nlemma MPA: \\<open>\\<then> (p \\<rightarrow> ((p \\<rightarrow> q) \\<rightarrow> q))\\<close>\n  by (metis Simp Tran CC MP)\n\nlemma Swap: \\<open>\\<then> ((p \\<rightarrow> (q \\<rightarrow> r)) \\<rightarrow> (q \\<rightarrow> (p \\<rightarrow> r)))\\<close>\n  by (meson MPA Tran MP)\n\nlemma Peirce: \\<open>\\<then> (((p \\<rightarrow> q) \\<rightarrow> p) \\<rightarrow> p)\\<close>\n  by (metis Simp Swap Tran CC MP)\n\nlemma Hilbert: \\<open>\\<then> ((p \\<rightarrow> (p \\<rightarrow> q)) \\<rightarrow> (p \\<rightarrow> q))\\<close>\n  by (meson Peirce Tran MP)\n\nlemma Tran': \\<open>\\<then> ((r \\<rightarrow> p) \\<rightarrow> ((q \\<rightarrow> r) \\<rightarrow> (q \\<rightarrow> p)))\\<close>\n  by (meson Swap Tran MP)\n\nlemma Frege: \\<open>\\<then> ((p \\<rightarrow> (q \\<rightarrow> r)) \\<rightarrow> ((p \\<rightarrow> q) \\<rightarrow> (p \\<rightarrow> r)))\\<close>\n  by (meson Hilbert Tran' MP Swap)\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>\\<then> (imply (p # ps) p)\\<close>\n  by (induct ps) (metis Frege Simp MP imply.simps, metis Frege Simp MP imply.simps(2))\n\nlemma imply_Cons: \\<open>\\<then> (imply ps q) \\<Longrightarrow> \\<then> (imply (p # ps) q)\\<close>\n  by (metis Simp MP imply.simps(2))\n\nlemma imply_mem: \\<open>p \\<in> set ps \\<Longrightarrow> \\<then> (imply ps p)\\<close>\n  using imply_head imply_Cons by (induct ps) auto\n\nlemma imply_MP: \\<open>\\<then> (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 (metis Frege Simp MP imply.simps(1))\nnext\n  case (Cons r ps)\n  then have \\<open>\\<then> ((r \\<rightarrow> imply ps p) \\<rightarrow> (r \\<rightarrow> (imply ps (p \\<rightarrow> q) \\<rightarrow> imply ps q)))\\<close>\n    by (meson Frege Simp MP)\n  then have \\<open>\\<then> ((r \\<rightarrow> imply ps p) \\<rightarrow> ((r \\<rightarrow> imply ps (p \\<rightarrow> q)) \\<rightarrow> (r \\<rightarrow> imply ps q)))\\<close>\n    by (meson Frege Simp MP)\n  then show ?case\n    by simp\nqed\n\nlemma imply_mp': \\<open>\\<then> (imply ps p) \\<Longrightarrow> \\<then> (imply ps (p \\<rightarrow> q)) \\<Longrightarrow> \\<then> (imply ps q)\\<close>\n  using imply_MP MP by meson\n\nlemma add_imply: \\<open>\\<then> q \\<Longrightarrow> \\<then> (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>\\<then> (imply (ps @ qs) r) \\<Longrightarrow> \\<then> (imply (qs @ ps) r)\\<close>\nproof (induct qs arbitrary: ps)\n  case Cons\n  then show ?case\n    using imply_Cons imply_head imply_mp' imply.simps(2) imply_append by metis\nqed simp\n\nlemma deduct: \\<open>\\<then> (imply (p # ps) q) \\<longleftrightarrow> \\<then> (imply ps (p \\<rightarrow> q))\\<close>\n  using imply_append imply_swap imply.simps by metis\n\ntheorem imply_weaken: \\<open>\\<then> (imply ps q) \\<Longrightarrow> set ps \\<subseteq> set ps' \\<Longrightarrow> \\<then> (imply ps' q)\\<close>\nproof (induct ps arbitrary: q)\n  case (Cons p ps)\n  note \\<open>\\<then> (imply (p # ps) q)\\<close>\n  then have \\<open>\\<then> (imply ps (p \\<rightarrow> q))\\<close>\n    using deduct by blast\n  then have \\<open>\\<then> (imply ps' (p \\<rightarrow> q))\\<close>\n    using Cons by simp\n  then show ?case\n    using Cons(3) imply_mem imply_mp' by (metis list.set_intros(1) subset_code(1))\nqed (simp add: add_imply)\n\nlemma cut: \\<open>\\<then> (imply ps p) \\<Longrightarrow> \\<then> (imply (p # ps) q) \\<Longrightarrow> \\<then> (imply ps q)\\<close>\n  using deduct imply_mp' by meson\n\nlemma cut': \\<open>\\<then> (imply (p # ps) r) \\<Longrightarrow> \\<then> (imply (q # ps) p) \\<Longrightarrow> \\<then> (imply (q # ps) r)\\<close>\n  using cut deduct imply_Cons by meson\n\nabbreviation Neg (\\<open>\\<sim>\\<close>) where \\<open>\\<sim> p \\<equiv> (p \\<rightarrow> \\<bottom>)\\<close>\n\nlemma Neg: \\<open>\\<then> (\\<sim> (\\<sim> p) \\<rightarrow> p)\\<close>\n  by (meson Expl Peirce Tran' MP)\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> \\<then> (imply S' \\<bottom>)\\<close>\n\nlemma UN_finite_bound:\n  assumes \\<open>finite A\\<close> \\<open>A \\<subseteq> (\\<Union>n. f n)\\<close>\n  shows \\<open>\\<exists>m :: nat. A \\<subseteq> (\\<Union>n \\<le> m. f n)\\<close>\n  using assms\nproof (induct rule: finite_induct)\n  case (insert x A)\n  then obtain m where \\<open>A \\<subseteq> (\\<Union>n \\<le> m. f n)\\<close>\n    by fast\n  then have \\<open>A \\<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> A \\<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>\\<then> (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>\\<then> (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 n where n: \\<open>f n = p\\<close>\n    using \\<open>surj f\\<close> unfolding surj_def by metis\n  then have \\<open>p \\<notin> extend S f (Suc n)\\<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 n)\\<close>\n    using n by fastforce\n  moreover have \\<open>{p} \\<union> extend S f n \\<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\ndefinition hintikka :: \\<open>form set \\<Rightarrow> bool\\<close> where\n  \\<open>hintikka H \\<equiv>\n    \\<bottom> \\<notin> H \\<and>\n    (\\<forall>n. \\<cdot> n \\<in> H \\<longrightarrow> (\\<sim> (\\<cdot> n)) \\<notin> H) \\<and>\n    (\\<forall>p q. (p \\<rightarrow> q) \\<in> H \\<longrightarrow> (\\<sim> p) \\<in> H \\<or> q \\<in> H) \\<and>\n    (\\<forall>p q. (\\<sim> (p \\<rightarrow> q)) \\<in> H \\<longrightarrow> p \\<in> H \\<and> \\<sim> q \\<in> H)\\<close>\n\nabbreviation (input) \\<open>model H n \\<equiv> \\<cdot> n \\<in> H\\<close>\n\nlemma hintikka_model:\n  assumes \\<open>hintikka H\\<close>\n  shows \\<open>(p \\<in> H \\<longrightarrow> (model H \\<Turnstile> p)) \\<and> (\\<sim> p \\<in> H \\<longrightarrow> \\<not> (model H \\<Turnstile> p))\\<close>\n  using assms 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'. \\<then> (imply (p # S') \\<bottom>) \\<and> set S' \\<subseteq> S\\<close>\nproof -\n  obtain S' where S': \\<open>\\<then> (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>\\<then> (imply (p # S'') \\<bottom>)\\<close> \\<open>set S'' = set S' - {p}\\<close>\n    using imply_weaken by (metis Diff_single_insert list.set(2) 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>\n  unfolding hintikka_def\nproof safe\n  assume \\<open>\\<bottom> \\<in> S\\<close>\n  then show False\n    using assms(2) imply_head unfolding consistent_def\n    by (metis all_not_in_conv empty_set insert_subset list.simps(15) subsetI)\nnext\n  fix n\n  assume \\<open>\\<cdot> n \\<in> S\\<close> \\<open>(\\<sim> (\\<cdot> n)) \\<in> S\\<close>\n  moreover have \\<open>\\<then> (imply [\\<cdot> n, \\<sim> (\\<cdot> n)] \\<bottom>)\\<close>\n    using deduct imply_head by blast\n  ultimately show False\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 \\<rightarrow> q) \\<in> S\\<close> \\<open>q \\<notin> S\\<close>\n  then obtain Sq' where Sq': \\<open>\\<then> (imply (q # Sq') \\<bottom>)\\<close> \\<open>set Sq' \\<subseteq> S\\<close>\n    using assms inconsistent_head by blast\n  show \\<open>\\<sim> p \\<in> S\\<close>\n  proof (rule ccontr)\n    assume \\<open>\\<sim> p \\<notin> S\\<close>\n    then obtain Sp' where Sp': \\<open>\\<then> (imply (\\<sim> 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>\n      by (meson set_append)\n    then have \\<open>\\<then> (imply (\\<sim> p # S') \\<bottom>)\\<close> \\<open>\\<then> (imply (q # S') \\<bottom>)\\<close>\n    proof -\n      have \\<open>set Sp' \\<subseteq> set S'\\<close>\n        using S' by blast\n      then show \\<open>\\<then> (imply (\\<sim> p # S') \\<bottom>)\\<close>\n        by (metis Sp'(1) deduct imply_weaken)\n      have \\<open>set Sq' \\<subseteq> set S'\\<close>\n        using S' by blast\n      then show \\<open>\\<then> (imply (q # S') \\<bottom>)\\<close>\n        by (metis Sq'(1) deduct imply_weaken)\n    qed\n    then have \\<open>\\<then> (imply ((p \\<rightarrow> q) # S') \\<bottom>)\\<close>\n      using Neg add_imply cut' deduct imply_Cons imply_head imply_mp' by metis\n    moreover have \\<open>set ((p \\<rightarrow> q) # S') \\<subseteq> S\\<close>\n      using *(1) 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>(\\<sim> (p \\<rightarrow> q)) \\<in> S\\<close>\n  show \\<open>p \\<in> S\\<close>\n  proof (rule ccontr)\n    assume \\<open>p \\<notin> S\\<close>\n    then obtain S' where S': \\<open>\\<then> (imply (p # S') \\<bottom>)\\<close> \\<open>set S' \\<subseteq> S\\<close>\n      using assms inconsistent_head by blast\n    then have \\<open>\\<then> (imply ((\\<sim> (p \\<rightarrow> q)) # S') p)\\<close>\n      using Frege Simp Neg Tran MP add_imply deduct by metis\n    then have \\<open>\\<then> (imply ((\\<sim> (p \\<rightarrow> q)) # S') \\<bottom>)\\<close>\n      using cut' S'(1) by blast\n    moreover have \\<open>set ((\\<sim> (p \\<rightarrow> q)) # S') \\<subseteq> S\\<close>\n      using *(1) S'(2) by fastforce\n    ultimately show False\n      using assms unfolding consistent_def by blast\n  qed\nnext\n  fix p q\n  assume *: \\<open>(\\<sim> (p \\<rightarrow> q)) \\<in> S\\<close>\n  show \\<open>\\<sim> q \\<in> S\\<close>\n  proof (rule ccontr)\n    assume \\<open>\\<sim> q \\<notin> S\\<close>\n    then obtain S' where S': \\<open>\\<then> (imply (\\<sim> q # S') \\<bottom>)\\<close> \\<open>set S' \\<subseteq> S\\<close>\n      using assms inconsistent_head by blast\n    then have \\<open>\\<then> (imply ((\\<sim> (p \\<rightarrow> q)) # S') (\\<sim> q))\\<close>\n      using Frege Simp Neg Tran MP add_imply deduct by metis\n    then have \\<open>\\<then> (imply ((\\<sim> (p \\<rightarrow> q)) # S') \\<bottom>)\\<close>\n      using cut' S'(1) by blast\n    moreover have \\<open>set ((\\<sim> (p \\<rightarrow> q)) # S') \\<subseteq> S\\<close>\n      using *(1) S'(2) by fastforce\n    ultimately show False\n      using assms unfolding consistent_def by blast\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 0) = Falsity\\<close>\n| \\<open>form_of_btree (Branch (Leaf 0) (Leaf n)) = \\<cdot> n\\<close>\n| \\<open>form_of_btree (Branch (Leaf (Suc 0)) (Branch t1 t2)) =\n     ((form_of_btree t1) \\<rightarrow> (form_of_btree t2))\\<close>\n| \\<open>form_of_btree (Leaf (Suc _)) = undefined\\<close>\n| \\<open>form_of_btree (Branch (Leaf 0) (Branch _ _)) = undefined\\<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 Falsity = Leaf 0\\<close>\n| \\<open>btree_of_form (\\<cdot> n) = Branch (Leaf 0) (Leaf n)\\<close>\n| \\<open>btree_of_form (p \\<rightarrow> 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. list_all (\\<lambda>q. (I \\<Turnstile> q)) ps \\<longrightarrow> (I \\<Turnstile> p)\\<close>\n  shows \\<open>\\<then> (imply ps p)\\<close>\nproof (rule ccontr)\n  assume \\<open>\\<not> \\<then> (imply ps p)\\<close>\n  then have *: \\<open>\\<not> \\<then> (imply (\\<sim> p # ps) \\<bottom>)\\<close>\n    using Neg add_imply deduct imply_mp' by metis\n  let ?S = \\<open>set (\\<sim> p # ps)\\<close>\n  let ?H = \\<open>Extend ?S from_nat\\<close>\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  then have \\<open>model ?H \\<Turnstile> p\\<close> if \\<open>p \\<in> ?S\\<close> for p\n    using that Extend_subset hintikka_model by blast\n  then have \\<open>model ?H \\<Turnstile> \\<sim> 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> \\<sim> p\\<close> by simp\nqed\n\ntheorem completeness: \\<open>\\<then> p\\<close> if \\<open>valid p\\<close>\n  using that imply_completeness[where ps=\\<open>[]\\<close>] by simp\n\nsection \\<open>Main Result\\<close>\n\ntheorem main: \\<open>valid p \\<longleftrightarrow> \\<then> p\\<close>\nproof\n  assume \\<open>valid p\\<close>\n  with completeness show \\<open>\\<then> p\\<close> .\nnext\n  assume \\<open>\\<then> p\\<close>\n  with soundness show \\<open>valid p\\<close> .\nqed\n\nsection \\<open>Appendix Isabelle Workshop\\<close>\n\ninductive U (\\<open>\\<turnstile>\\<close>) where\n  \\<open>\\<turnstile> p\\<close> if \\<open>\\<turnstile> q\\<close> and \\<open>\\<turnstile> (q \\<rightarrow> p)\\<close> |\n  \\<open>\\<turnstile> ((q \\<rightarrow> r) \\<rightarrow> ((r \\<rightarrow> (r \\<rightarrow> p)) \\<rightarrow> (q \\<rightarrow> p)))\\<close> |\n  \\<open>\\<turnstile> (p \\<rightarrow> (q \\<rightarrow> p))\\<close> |\n  \\<open>\\<turnstile> (\\<sim> (\\<sim> p) \\<rightarrow> p)\\<close>\n\ninductive W (\\<open>\\<tturnstile>\\<close>) where\n  \\<open>\\<tturnstile> p\\<close> if \\<open>\\<tturnstile> q\\<close> and \\<open>\\<tturnstile> (q \\<rightarrow> p)\\<close> |\n  \\<open>\\<tturnstile> ((r \\<rightarrow> q) \\<rightarrow> ((r \\<rightarrow> (q \\<rightarrow> p)) \\<rightarrow> (r \\<rightarrow> p)))\\<close> |\n  \\<open>\\<tturnstile> (p \\<rightarrow> (r \\<rightarrow> p))\\<close> |\n  \\<open>\\<tturnstile> (\\<sim> (\\<sim> p) \\<rightarrow> p)\\<close>\n\ntheorem\n  \\<open>valid p \\<longleftrightarrow> \\<turnstile> p\\<close>\n  \\<open>valid p \\<longleftrightarrow> \\<tturnstile> p\\<close>\nproof -\n  have H: \\<open>\\<turnstile> ((r \\<rightarrow> (r \\<rightarrow> p)) \\<rightarrow> (r \\<rightarrow> p))\\<close> for p r\n    by (metis U.intros(1-3))\n  have T: \\<open>\\<turnstile> ((r \\<rightarrow> q) \\<rightarrow> ((q \\<rightarrow> p) \\<rightarrow> (r \\<rightarrow> p)))\\<close> for p q r\n    by (meson U.intros(1-3))\n  have S: \\<open>\\<turnstile> ((r \\<rightarrow> (q \\<rightarrow> p)) \\<rightarrow> (q \\<rightarrow> (r \\<rightarrow> p)))\\<close> for p q r\n    by (meson U.intros(1-3) T)\n  have T': \\<open>\\<turnstile> ((q \\<rightarrow> p) \\<rightarrow> ((r \\<rightarrow> q) \\<rightarrow> (r \\<rightarrow> p)))\\<close> for p q r\n    by (meson U.intros(1) S T)\n  have F: \\<open>\\<turnstile> ((r \\<rightarrow> (q \\<rightarrow> p)) \\<rightarrow> ((r \\<rightarrow> q) \\<rightarrow> (r \\<rightarrow> p)))\\<close> for p q r\n    by (meson T' U.intros(1) S H)\n  have F': \\<open>\\<turnstile> ((r \\<rightarrow> q) \\<rightarrow> ((r \\<rightarrow> (q \\<rightarrow> p)) \\<rightarrow> (r \\<rightarrow> p)))\\<close> for p q r\n    by (meson U.intros(1) S F)\n  have \\<open>\\<tturnstile> ((r \\<rightarrow> (q \\<rightarrow> p)) \\<rightarrow> ((r \\<rightarrow> q) \\<rightarrow> (r \\<rightarrow> p)))\\<close> for p q r\n    by (use W.intros(1-3) in metis)\n  with W.intros(1,3) have *: \\<open>\\<tturnstile> ((r \\<rightarrow> q) \\<rightarrow> ((q \\<rightarrow> p) \\<rightarrow> (r \\<rightarrow> p)))\\<close> for p q r\n    by metis\n  note main\n  moreover have \\<open>\\<tturnstile> p\\<close> if \\<open>\\<then> p\\<close>\n    using that by induct (use * W.intros in metis)+\n  moreover have \\<open>\\<then> p\\<close> if \\<open>\\<tturnstile> p\\<close>\n    using that by induct (use MP Frege Simp Neg Swap in metis)+\n  ultimately show \\<open>valid p \\<longleftrightarrow> \\<tturnstile> p\\<close>\n    by fast\n  note this\n  moreover have \\<open>\\<turnstile> p\\<close> if \\<open>\\<tturnstile> p\\<close>\n    using that by induct (use F' U.intros(1,3,4) in metis)+\n  moreover have \\<open>\\<tturnstile> p\\<close> if \\<open>\\<turnstile> p\\<close>\n    using that by induct (use * W.intros in metis)+\n  ultimately show \\<open>valid p \\<longleftrightarrow> \\<turnstile> p\\<close>\n    by fast\nqed\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_V.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8791467643431002, "lm_q2_score": 0.8128673201042492, "lm_q1q2_score": 0.7146296743098978}}
{"text": "(*<*)\ntheory hw08tmpl\n  imports Complex_Main \"HOL-Library.Tree\"\nbegin\n(*>*)\n\ntext {* \\NumHomework{Bounding Fibonacci}{June 8}\n\n  We start by defining the Fibonacci sequence, and an alternative\n  induction scheme for indexes greater 0:\n*}\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\nlemma f_alt_induct [consumes 1, case_names 1 2 rec]:\n  assumes \"n > 0\"\n      and \"P (Suc 0)\" \"P 2\" \"\\<And>n. n > 0 \\<Longrightarrow> P n \\<Longrightarrow> P (Suc n) \\<Longrightarrow> P (Suc (Suc n))\"\n  shows   \"P n\"\n  using assms(1)\nproof (induction n rule: fib.induct)\n  case (3 n)\n  thus ?case using assms by (cases n) (auto simp: eval_nat_numeral)\nqed (auto simp: \\<open>P (Suc 0)\\<close> \\<open>P 2\\<close>)\n\ntext \\<open>Show that the Fibonacci numbers grow exponentially, i.e., that they are\n  bounded from below by \\<open>1.5\\<^sup>n/3\\<close>.\n\n  Use the alternative induction scheme defined above.\n\\<close>\nlemma fib_lowerbound: \"n > 0 \\<Longrightarrow> real (fib n) \\<ge> 1.5 ^ n / 3\"\nproof (induction n rule: f_alt_induct)\noops\n\ntext \\<open>\n  \\NumHomework{AVL Trees}{June 8}\n\n  AVL trees are binary search trees where, for each node, the heights of\n  its subtrees differ by at most one. In this homework, you are to bound\n  the minimal number of nodes in an AVL tree of a given height.\n\n  First, define the AVL invariant on binary trees.\n  Note: In practice, one additionally stores the heights or height difference\n  in the nodes, but this is not required for this exercise.\n\\<close>\n\n\nfun avl :: \"'a tree \\<Rightarrow> bool\"\nwhere\n\"avl _ = undefined\"\n\n\ntext \\<open>Show that an AVL tree of height \\<open>h\\<close> has at least \\<open>fib (h+2)\\<close> nodes:\\<close>\nlemma avl_fib_bound: \"avl t \\<Longrightarrow> height t = h \\<Longrightarrow> fib (h+2) \\<le> size1 t\"\n  oops\n\ntext \\<open>Combine your results to get an exponential lower bound on the number\n  of nodes in an AVL tree.\\<close>\nlemma avl_lowerbound:\n  assumes \"avl t\"\n  shows \"1.5 ^ (height t + 2) / 3 \\<le> real (size1 t)\"\n  oops\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/hw08tmpl.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467580102418, "lm_q2_score": 0.8128673223709251, "lm_q1q2_score": 0.7146296711548649}}
{"text": "(* Title: Quantales\n   Author: Georg Struth \n   Maintainer: Georg Struth <g.struth@sheffield.ac.uk> \n   Contributions by Brijesh Dongol, Victor Gomes, Ian Hayes\n*)\n\nsection \\<open>Quantales\\<close>\n\ntheory Quantales\n  imports\n    \"Order_Lattice_Props.Closure_Operators\"\n   Kleene_Algebra.Dioid\nbegin\n\nsubsection \\<open>Families of Proto-Quantales\\<close>\n  \ntext \\<open>Proto-Quanales are complete lattices equipped with an operation of composition or multiplication\nthat need not be associative. The notation in this component differs from Rosenthal's \\cite{Rosenthal90}, but is consistent with the one we use \nfor semirings and Kleene algebras.\\<close>\n  \nclass proto_near_quantale = complete_lattice + times + \n  assumes Sup_distr: \"\\<Squnion>X \\<cdot> y = (\\<Squnion>x \\<in> X. x \\<cdot> y)\"\n\nlemma Sup_pres_multr: \"Sup_pres (\\<lambda>(z::'a::proto_near_quantale). z \\<cdot> y)\"\n  unfolding fun_eq_iff comp_def Sup_distr by simp \n\nlemma sup_pres_multr: \"sup_pres (\\<lambda>(z::'a::proto_near_quantale). z \\<cdot> y)\"\n  using Sup_pres_multr Sup_sup_pres by fastforce\n\nlemma bot_pres_multr: \"bot_pres (\\<lambda>(z::'a::proto_near_quantale). z \\<cdot> y)\"\n  by (metis SUP_empty Sup_distr Sup_empty)\n\ncontext proto_near_quantale\nbegin\n\nlemma mult_botl [simp]: \"\\<bottom> \\<cdot> x = \\<bottom>\"\nproof -\n  have \"\\<bottom> \\<cdot> x = (\\<Squnion>a\\<in>{}. a \\<cdot> x)\"\n    using Sup_distr Sup_empty by blast\n  thus ?thesis\n    by simp\nqed\n  \nlemma sup_distr: \"(x \\<squnion> y) \\<cdot> z = (x \\<cdot> z) \\<squnion> (y \\<cdot> z)\"\n  by (smt SUP_empty SUP_insert Sup_distr sup_Sup sup_bot.right_neutral)\n   \nlemma mult_isor: \"x \\<le> y \\<Longrightarrow> x \\<cdot> z \\<le> y \\<cdot> z\"\n  by (metis sup.absorb_iff1 sup_distr)\n\ntext \\<open>Left and right residuals can be defined in every proto-nearquantale.\\<close>\n    \ndefinition bres :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a\" (infixr \"\\<rightarrow>\" 60) where \n  \"x \\<rightarrow> z = \\<Squnion>{y. x \\<cdot> y \\<le> z}\"\n\ndefinition fres :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a\" (infixl \"\\<leftarrow>\" 60) where \n  \"z \\<leftarrow> y = \\<Squnion>{x. x \\<cdot> y \\<le> z}\"\n\ntext \\<open>The left one is a right adjoint  to composition. For the right one, additional assumptions are needed\\<close>\n\nlemma bres_galois_imp: \"x \\<cdot> y \\<le> z \\<Longrightarrow> y \\<le> x \\<rightarrow> z\"\n  by (simp add: Sup_upper bres_def)\n    \nlemma fres_galois: \"(x \\<cdot> y \\<le> z) = (x \\<le> z \\<leftarrow> y)\"\nproof \n  show \"x \\<cdot> y \\<le> z \\<Longrightarrow> x \\<le> z \\<leftarrow> y\"\n    by (simp add: Sup_upper fres_def)\nnext\n  assume \"x \\<le> z \\<leftarrow> y\"\n  hence \"x \\<cdot> y \\<le> \\<Squnion>{x. x \\<cdot> y \\<le> z} \\<cdot> y\"\n    by (simp add: fres_def mult_isor)\n  also have \"... = \\<Squnion>{x \\<cdot> y |x. x \\<cdot> y \\<le> z}\"\n    by (simp add: Sup_distr setcompr_eq_image)\n  also have \"... \\<le> z\"\n    by (rule Sup_least, auto)\n  finally show \"x \\<cdot> y \\<le> z\" .\nqed\n\nend\n\nlemma fres_adj: \"(\\<lambda>(x::'a::proto_near_quantale). x \\<cdot> y) \\<stileturn> (\\<lambda>x. x \\<leftarrow> y)\"\n  by (simp add: adj_def fres_galois)\n\ncontext proto_near_quantale\nbegin\n\nlemma fres_canc1: \"(y \\<leftarrow> x) \\<cdot> x \\<le> y\"\n  by (simp add: fres_galois)\n\nlemma fres_canc2: \"y \\<le> (y \\<cdot> x) \\<leftarrow> x\"\n  using fres_galois by force\n\nlemma inf_fres: \"y \\<cdot> x = \\<Sqinter>{z. y \\<le> z \\<leftarrow> x}\"\n  by (metis (mono_tags, lifting) fres_canc2 Inf_eqI fres_galois mem_Collect_eq)\n\nlemma bres_iso: \"x \\<le> y \\<Longrightarrow> z \\<rightarrow> x \\<le> z \\<rightarrow> y\"\n  using Sup_le_iff bres_def bres_galois_imp by force\n\nlemma bres_anti: \"x \\<le> y \\<Longrightarrow> y \\<rightarrow> z \\<le> x \\<rightarrow> z\"\n  by (smt Sup_le_iff bres_def bres_galois_imp fres_galois order_trans mem_Collect_eq)\n\nlemma fres_iso: \"x \\<le> y \\<Longrightarrow> x \\<leftarrow> z \\<le> y \\<leftarrow> z\"\n  using fres_galois dual_order.trans by blast\n\nlemma bres_top_top [simp]: \"\\<top> \\<rightarrow> \\<top> = \\<top>\"\n  by (simp add: bres_galois_imp dual_order.antisym)\n\nlemma fres_top_top [simp]: \"\\<top> \\<leftarrow> \\<top> = \\<top>\"\n  using fres_galois top_greatest top_le by blast\n\nlemma bres_bot_bot [simp]: \"\\<bottom> \\<rightarrow> \\<bottom> = \\<top>\"\n  by (simp add: bres_galois_imp top_le)\n\nlemma left_sided_localp: \"\\<top> \\<cdot> y = y \\<Longrightarrow> x \\<cdot> y \\<le> y\"\n  by (metis mult_isor top_greatest)\n\nlemma fres_sol: \"((y \\<leftarrow> x) \\<cdot> x = y) = (\\<exists>z. z \\<cdot> x = y)\"\n  using dual_order.antisym fres_canc1 fres_canc2 mult_isor by fastforce\n\nlemma sol_fres: \"((y \\<cdot> x) \\<leftarrow> x = y) = (\\<exists>z. y = z \\<leftarrow> x)\"\n  by (metis fres_canc1 fres_canc2 fres_sol eq_iff fres_galois)\n\nend\n\nclass proto_pre_quantale = proto_near_quantale + \n  assumes Sup_subdistl: \"(\\<Squnion>y \\<in> Y. x \\<cdot> y) \\<le> x \\<cdot> \\<Squnion>Y\"\n    \nbegin\n\nlemma sup_subdistl: \"(x \\<cdot> y) \\<squnion> (x \\<cdot> z) \\<le> x \\<cdot> (y \\<squnion> z)\"\n  by (smt SUP_empty SUP_insert Sup_subdistl sup_Sup sup_bot_right)\n\nlemma mult_isol: \"x \\<le> y \\<Longrightarrow> z \\<cdot> x \\<le> z \\<cdot> y\"\n  by (metis le_iff_sup le_sup_iff sup_subdistl)\n\nlemma fres_anti: \"x \\<le> y \\<Longrightarrow> z \\<leftarrow> y \\<le> z \\<leftarrow> x\"\n  using dual_order.trans fres_galois mult_isol by blast\n\nend\n    \nclass weak_proto_quantale = proto_near_quantale +\n  assumes weak_Sup_distl: \"Y \\<noteq> {} \\<Longrightarrow> x \\<cdot> \\<Squnion>Y = (\\<Squnion>y \\<in> Y. x \\<cdot> y)\" \n\nbegin\n\nsubclass proto_pre_quantale\nproof unfold_locales\n  have a: \"\\<And>x Y. Y = {} \\<Longrightarrow> (\\<Squnion>y \\<in> Y. x \\<cdot> y) \\<le> x \\<cdot> \\<Squnion>Y\"\n    by simp\n  have b: \"\\<And>x Y. Y \\<noteq> {} \\<Longrightarrow> (\\<Squnion>y \\<in> Y. x \\<cdot> y) \\<le> x \\<cdot> \\<Squnion>Y\"\n    by (simp add: weak_Sup_distl)\n  show  \"\\<And>x Y. (\\<Squnion>y \\<in> Y. x \\<cdot> y) \\<le> x \\<cdot> \\<Squnion>Y\"\n    using a b by blast\nqed\n  \nlemma  sup_distl: \"x \\<cdot> (y \\<squnion> z) = (x \\<cdot> y) \\<squnion> (x \\<cdot> z)\"  \n  using weak_Sup_distl[where Y=\"{y, z}\"] by (fastforce intro!: Sup_eqI)\n\nlemma \"y \\<le> x \\<rightarrow> z \\<longrightarrow> x \\<cdot> y \\<le> z\" (* nitpick [expect = genuine] *)\noops\n\nend\n  \nclass proto_quantale = proto_near_quantale +\n  assumes Sup_distl: \"x \\<cdot> \\<Squnion>Y = (\\<Squnion>y \\<in> Y. x \\<cdot> y)\"  \n\nlemma Sup_pres_multl: \"Sup_pres (\\<lambda>(z::'a::proto_quantale). x \\<cdot> z)\"\n  unfolding fun_eq_iff comp_def Sup_distl by simp \n\nlemma sup_pres_multl: \"sup_pres (\\<lambda>(z::'a::proto_quantale). x \\<cdot> z)\"\n  by (metis (no_types, lifting) SUP_insert Sup_distl Sup_empty Sup_insert sup_bot_right)\n\nlemma bot_pres_multl: \"bot_pres (\\<lambda>(z::'a::proto_quantale). x \\<cdot> z)\"\n  by (metis SUP_empty Sup_distl Sup_empty)\n\ncontext proto_quantale\nbegin\n \nsubclass weak_proto_quantale\n  by standard (simp add: Sup_distl)\n\nlemma mult_botr [simp]: \"x \\<cdot> \\<bottom> = \\<bottom>\"\n  by (smt image_empty Sup_distl Sup_empty)\n\ntext \\<open>Now there is also an adjunction for the other residual.\\<close>\n    \nlemma bres_galois: \"x \\<cdot> y \\<le> z \\<longleftrightarrow> y \\<le> x \\<rightarrow> z\"\nproof \n  show \"x \\<cdot> y \\<le> z \\<Longrightarrow> y \\<le> x \\<rightarrow> z\"\n    by (simp add: Sup_upper bres_def)\nnext\n  assume \"y \\<le> x \\<rightarrow> z\"\n  hence \"x \\<cdot> y \\<le> x \\<cdot> \\<Squnion>{y. x \\<cdot> y \\<le> z}\"\n    by (simp add: bres_def mult_isol)\n  also have \"... = \\<Squnion>{x \\<cdot> y |y. x \\<cdot> y \\<le> z}\"\n    by (simp add: Sup_distl setcompr_eq_image)\n  also have \"... \\<le> z\"\n    by (rule Sup_least, safe)\n  finally show \"x \\<cdot> y \\<le> z\" .\nqed \n\nend\n\nlemma bres_adj: \"(\\<lambda>(y::'a::proto_quantale). x \\<cdot> y) \\<stileturn> (\\<lambda>y. x \\<rightarrow> y)\"\n  by (simp add: adj_def bres_galois)\n\ncontext proto_quantale\nbegin\n\nlemma bres_canc1: \"x \\<cdot> (x \\<rightarrow> y) \\<le> y\"\n  by (simp add: bres_galois)\n\nlemma bres_canc2: \"y \\<le> x \\<rightarrow> (x \\<cdot> y)\"\n  by (simp add: bres_galois_imp)\n\nlemma  inf_bres: \"x \\<cdot> y = \\<Sqinter>{z. y \\<le> x \\<rightarrow> z}\"\n  using bres_galois fres_galois inf_fres by force\n\nlemma bres_sol: \"(x \\<cdot> (x \\<rightarrow> y) = y) = (\\<exists>z. x \\<cdot> z = y)\"\n  using bres_galois antisym mult_isol by force\n\nlemma sol_bres: \"(x \\<rightarrow> (x \\<cdot> y) = y) = (\\<exists>z. y = x \\<rightarrow> z)\"\n  by (metis bres_canc1 bres_canc2 bres_iso eq_iff)\n\nend \n\nlemma bres_fres_clop: \"clop (\\<lambda>x::'a::proto_quantale. y \\<leftarrow> (x \\<rightarrow> y))\"\n  unfolding clop_def comp_def mono_def le_fun_def\n  by (metis bres_anti bres_canc1 bres_galois_imp fres_anti fres_galois id_apply)\n\nlemma fres_bres_clop: \"clop (\\<lambda>x::'a::proto_quantale. (y \\<leftarrow> x) \\<rightarrow> y)\"\n  unfolding clop_def comp_def mono_def le_fun_def\n  by (metis bres_anti bres_canc1 bres_galois_imp fres_anti fres_canc1 fres_galois id_apply)\n\n\nsubsection \\<open>Families of Quantales\\<close>\n  \nclass near_quantale = proto_near_quantale + semigroup_mult \n\nsublocale near_quantale \\<subseteq> nsrnq: near_dioid \"(\\<squnion>)\" \"(\\<cdot>)\" \"(\\<le>)\" \"(<)\"\n  apply unfold_locales\n       apply (simp add: sup_assoc)\n      apply (simp add: sup_commute)\n     apply (simp_all add: sup_distr)\n   apply (simp add: le_iff_sup)\n  by auto\n\ncontext near_quantale\nbegin\n\nlemma fres_curry: \"(z \\<leftarrow> y) \\<leftarrow> x = z \\<leftarrow> (x \\<cdot> y)\"\n  by (metis eq_iff fres_canc1 fres_galois mult_assoc)\n\nend\n  \nclass unital_near_quantale = near_quantale + monoid_mult\n\nsublocale unital_near_quantale \\<subseteq> nsrnqo: near_dioid_one \"(\\<squnion>)\" \"(\\<cdot>)\" \"1\"\"(\\<le>)\" \"(<)\"\n  by (unfold_locales, simp_all)\n\ncontext unital_near_quantale\nbegin\n\ndefinition iter :: \"'a \\<Rightarrow> 'a\" where\n  \"iter x \\<equiv> \\<Sqinter>i. x ^ i\"\n\nlemma iter_ref [simp]: \"iter x \\<le> 1\"\n  by (metis iter_def Inf_lower power.power_0 rangeI)\n   \nlemma le_top: \"x \\<le> \\<top> \\<cdot> x\"\n  by (metis mult.left_neutral mult_isor top_greatest)\n\nlemma top_times_top [simp]: \"\\<top> \\<cdot> \\<top> = \\<top>\"\n  by (simp add: le_top top_le)\n\nlemma bres_one: \"1 \\<le> x \\<rightarrow> x\"\n  by (simp add: bres_galois_imp)\n\nlemma fres_one: \"1 \\<le> x \\<leftarrow> x\"\n  using fres_galois by fastforce\n\nend\n  \nclass pre_quantale = proto_pre_quantale + semigroup_mult \n\nbegin\n\nsubclass near_quantale ..\n\nlemma fres_interchange: \"z \\<cdot> (x \\<leftarrow> y) \\<le> (z \\<cdot> x) \\<leftarrow> y\"\n  using Sup_upper fres_canc1 fres_def mult_isol mult_assoc by fastforce\n\nend\n\nsublocale pre_quantale \\<subseteq>  psrpq: pre_dioid \"(\\<squnion>)\" \"(\\<cdot>)\" \"(\\<le>)\" \"(<)\"\n  by (unfold_locales, simp add: mult_isol)\n\nclass unital_pre_quantale = pre_quantale + monoid_mult\n\nbegin\n  \nsubclass unital_near_quantale ..\n\ntext \\<open>Abstract rules of Hoare logic without the star can be derived.\\<close>\n\nlemma h_w1: \"x \\<le> x' \\<Longrightarrow>  x' \\<cdot> y \\<le> z \\<Longrightarrow> x \\<cdot> y \\<le> z\"  \n  by (simp add: fres_galois)\n\nlemma h_w2: \"x \\<cdot> y \\<le> z' \\<Longrightarrow> z' \\<le> z \\<Longrightarrow> x \\<cdot> y \\<le> z\"\n  using order_trans by blast\n\nlemma h_seq: \"x \\<cdot> v \\<le> z \\<Longrightarrow> y \\<cdot> w \\<le> v \\<Longrightarrow> x \\<cdot> y \\<cdot> w \\<le> z\"\n  using dual_order.trans mult_isol mult_assoc by presburger\n\nlemma h_sup: \"x \\<cdot> w \\<le> z \\<Longrightarrow> y \\<cdot> w \\<le> z \\<Longrightarrow> (x \\<squnion> y) \\<cdot> w \\<le> z\"\n  by (simp add: fres_galois)\n\nlemma h_Sup: \"\\<forall>x \\<in> X. x \\<cdot> w \\<le> z \\<Longrightarrow> \\<Squnion>X \\<cdot> w \\<le> z\"\n  by (simp add: Sup_least fres_galois)\n\nend\n\nsublocale unital_pre_quantale \\<subseteq>  psrpqo: pre_dioid_one \"(\\<squnion>)\" \"(\\<cdot>)\" \"1\" \"(\\<le>)\" \"(<)\"..\n    \nclass weak_quantale = weak_proto_quantale + semigroup_mult\n\nbegin\n  \nsubclass pre_quantale ..\n    \ntext \\<open>The following counterexample shows an important consequence of weakness: \nthe absence of right annihilation.\\<close>\n    \nlemma \"x \\<cdot> \\<bottom> = \\<bottom>\" (*nitpick[expect=genuine]*)\n  oops\n\nend\n\nclass unital_weak_quantale = weak_quantale + monoid_mult\n    \nlemma (in unital_weak_quantale) \"x \\<cdot> \\<bottom> = \\<bottom>\" (*nitpick[expect=genuine]*)\n  oops\n  \nsubclass (in unital_weak_quantale) unital_pre_quantale ..\n\nsublocale unital_weak_quantale \\<subseteq>  wswq: dioid_one_zerol \"(\\<squnion>)\" \"(\\<cdot>)\" \"1\" \"\\<bottom>\" \"(\\<le>)\" \"(<)\"\n  by (unfold_locales, simp_all add: sup_distl)\n\n    \nclass quantale = proto_quantale + semigroup_mult \n  \nbegin\n  \nsubclass weak_quantale ..   \n\nlemma Inf_subdistl: \"x \\<cdot> \\<Sqinter>Y \\<le> (\\<Sqinter>y \\<in> Y. x \\<cdot> y)\"\n  by (auto intro!: Inf_greatest Inf_lower mult_isol)\n\nlemma Inf_subdistr: \"\\<Sqinter> X \\<cdot> y \\<le> (\\<Sqinter>x \\<in> X. x \\<cdot> y)\"\n  by (auto intro!: Inf_greatest Inf_lower mult_isor)\n    \nlemma fres_bot_bot [simp]: \"\\<bottom> \\<leftarrow> \\<bottom> = \\<top>\"\n  by (simp add: fres_def)\n\nlemma bres_interchange: \"(x \\<rightarrow> y) \\<cdot> z \\<le> x \\<rightarrow> (y \\<cdot> z)\"\n  by (metis bres_canc1 bres_galois mult_isor mult_assoc)\n\nlemma bres_curry: \"x \\<rightarrow> (y \\<rightarrow> z) = (y \\<cdot> x) \\<rightarrow> z\"\n  by (metis bres_canc1 bres_galois dual_order.antisym mult_assoc)\n\nlemma fres_bres: \"x \\<rightarrow> (y \\<leftarrow> z) = (x \\<rightarrow> y) \\<leftarrow> z\"\nproof-\n  {fix w\n  have \"(w \\<le> x \\<rightarrow> (y \\<leftarrow> z)) = (x \\<cdot> w \\<le> y \\<leftarrow> z)\"\n    by (simp add: bres_galois)\n  also have \"... = (x \\<cdot> w \\<cdot> z \\<le> y)\"\n    by (simp add: fres_galois)\n  also have \"... = (w \\<cdot> z \\<le> x \\<rightarrow> y)\"\n    by (simp add: bres_galois mult_assoc)\n  also have \"... = (w \\<le> (x \\<rightarrow> y) \\<leftarrow> z)\"\n    by (simp add: fres_galois)\n  finally have \"(w \\<le> x \\<rightarrow> (y \\<leftarrow> z)) = (w \\<le> (x \\<rightarrow> y) \\<leftarrow> z)\".}\n  thus ?thesis\n    using eq_iff by blast\nqed\n\nend\n\nclass quantale_with_dual = quantale + complete_lattice_with_dual\n\nclass unital_quantale = quantale + monoid_mult\n\nclass unital_quantale_with_dual = unital_quantale + quantale_with_dual\n  \nsubclass (in unital_quantale) unital_weak_quantale ..\n\nsublocale unital_quantale \\<subseteq> wswq: dioid_one_zero \"(\\<squnion>)\" \"(\\<cdot>)\" \"1\" \"\\<bottom>\" \"(\\<le>)\" \"(<)\"\n  by (unfold_locales, simp)\n\nclass ab_quantale = quantale + ab_semigroup_mult\n\nbegin\n\nlemma bres_fres_eq: \"x \\<rightarrow> y = y \\<leftarrow> x\" \n  by (simp add: fres_def bres_def mult_commute)\n\nend\n\nclass ab_unital_quantale = ab_quantale + unital_quantale\n\nsublocale complete_heyting_algebra \\<subseteq> chaq: ab_unital_quantale \"(\\<sqinter>)\" _ _ _ _ _ _ _ _ \\<top>\n  by (unfold_locales, simp add: inf.assoc, simp_all add: inf.assoc ch_dist inf.commute)\n\nclass distrib_quantale = quantale + distrib_lattice\n  \nclass bool_quantale = quantale + complete_boolean_algebra_alt \n  \nclass distrib_unital_quantale = unital_quantale + distrib_lattice\n  \nclass bool_unital_quantale = unital_quantale + complete_boolean_algebra_alt\n  \nclass distrib_ab_quantale = distrib_quantale + ab_quantale\n  \nclass bool_ab_quantale = bool_quantale + ab_quantale\n  \nclass distrib_ab_unital_quantale = distrib_quantale + unital_quantale\n  \nclass bool_ab_unital_quantale = bool_ab_quantale + unital_quantale\n\nsublocale complete_boolean_algebra \\<subseteq> cba_quantale: bool_ab_unital_quantale inf _ _ _ _ _ _ _ _ _ _ \\<top>\n  by (unfold_locales, simp add: inf.assoc, simp_all add: inf.commute Setcompr_eq_image inf_Sup Sup_inf)\n\ncontext complete_boolean_algebra\nbegin\n\ntext \\<open>In this setting, residuation is classical implication.\\<close>\n  \nlemma cba_bres1: \"x \\<sqinter> y \\<le> z \\<longleftrightarrow> x \\<le> cba_quantale.bres y z\"\n  using cba_quantale.bres_galois inf.commute by fastforce\n    \nlemma cba_bres2: \"x \\<le> -y \\<squnion> z \\<longleftrightarrow> x \\<le> cba_quantale.bres y z\"\n  using cba_bres1 shunt1 by auto\n    \nlemma cba_bres_prop: \"cba_quantale.bres x y = -x \\<squnion> y\"\n  using cba_bres2 eq_iff by blast\n  \nend\n\nsubsection \\<open>Quantales Based on Sup-Lattices and Inf-Lattices\\<close>\n\ntext \\<open>These classes are defined for convenience in instantiation and interpretation proofs, or likewise. \nThey are useful, e.g., in the context of predicate transformers, where only one of Sup or Inf may be well behaved.\\<close>\n\nclass Sup_quantale = Sup_lattice + semigroup_mult + \n  assumes Supq_distr: \"\\<Squnion>X \\<cdot> y = (\\<Squnion>x \\<in> X. x \\<cdot> y)\"\n  and Supq_distl: \"x \\<cdot> \\<Squnion>Y = (\\<Squnion>y \\<in> Y. x \\<cdot> y)\"\n\nclass unital_Sup_quantale = Sup_quantale + monoid_mult\n\nclass Inf_quantale = Inf_lattice + monoid_mult + \n  assumes Supq_distr: \"\\<Sqinter>X \\<cdot> y = (\\<Sqinter>x \\<in> X. x \\<cdot> y)\"\n  and Supq_distl: \"x \\<cdot> \\<Sqinter>Y = (\\<Sqinter>y \\<in> Y. x \\<cdot> y)\"\n\nclass unital_Inf_quantale = Inf_quantale + monoid_mult\n\nsublocale Inf_quantale \\<subseteq> qdual: Sup_quantale _ Inf \"(\\<ge>)\"\n  by (unfold_locales, simp_all add: Supq_distr Supq_distl)\n\nsublocale unital_Inf_quantale \\<subseteq> uqdual: unital_Sup_quantale _ _ Inf  \"(\\<ge>)\"..\n\nsublocale Sup_quantale \\<subseteq> supq: quantale _ Infs Sup_class.Sup infs \"(\\<le>)\" le sups bots tops\n  by (unfold_locales, simp_all add: Supq_distr Supq_distl)\n\nsublocale unital_Sup_quantale \\<subseteq> usupq: unital_quantale _ _ Infs Sup_class.Sup infs \"(\\<le>)\" le sups bots tops..\n\n\nsubsection \\<open>Products of Quantales\\<close>\n  \ndefinition \"Inf_prod X = ((\\<Sqinter>x \\<in> X. fst x), (\\<Sqinter>x \\<in> X. snd x))\"\n  \ndefinition \"inf_prod x y = (fst x \\<sqinter> fst y, snd x \\<sqinter> snd y)\"\n\ndefinition \"bot_prod = (bot,bot)\"\n  \ndefinition \"Sup_prod X = ((\\<Squnion>x \\<in> X. fst x), (\\<Squnion>x \\<in> X. snd x))\"\n    \ndefinition \"sup_prod x y = (fst x \\<squnion> fst y, snd x \\<squnion> snd y)\"\n    \ndefinition \"top_prod = (top,top)\"\n    \ndefinition \"less_eq_prod x y \\<equiv> less_eq (fst x) (fst y) \\<and> less_eq (snd x) (snd y)\"\n\ndefinition \"less_prod x y \\<equiv> less_eq (fst x) (fst y) \\<and> less_eq (snd x) (snd y) \\<and> x \\<noteq> y\"\n  \ndefinition \"times_prod' x y = (fst x \\<cdot> fst y, snd x \\<cdot> snd y)\"\n\ndefinition \"one_prod = (1,1)\"\n\ndefinition \"dual_prod x = (\\<partial> (fst x),\\<partial> (snd x))\"\n  \ninterpretation prod: complete_lattice Inf_prod Sup_prod inf_prod less_eq_prod less_prod sup_prod bot_prod \"top_prod :: ('a::complete_lattice \\<times> 'b::complete_lattice)\"\n  by standard (auto simp add: Inf_prod_def Sup_prod_def inf_prod_def sup_prod_def bot_prod_def top_prod_def less_eq_prod_def less_prod_def Sup_distl Sup_distr intro: Inf_lower Inf_greatest Sup_upper Sup_least)\n\ninterpretation prod: complete_lattice_with_dual Inf_prod Sup_prod inf_prod less_eq_prod less_prod sup_prod bot_prod \"top_prod :: ('a::complete_lattice_with_dual \\<times> 'b::complete_lattice_with_dual)\" dual_prod\n  by standard (simp_all add: dual_prod_def fun_eq_iff inj_def Sup_prod_def Inf_prod_def inj_dual_iff Sup_dual_def_var image_comp)\n\ninterpretation prod: proto_near_quantale Inf_prod Sup_prod inf_prod less_eq_prod less_prod sup_prod bot_prod \"top_prod :: ('a::proto_near_quantale \\<times> 'b::proto_near_quantale)\" times_prod'\n  by standard (simp add: times_prod'_def Sup_prod_def Sup_distr image_comp)\n\ninterpretation prod: proto_quantale Inf_prod Sup_prod inf_prod less_eq_prod less_prod sup_prod bot_prod \"top_prod :: ('a::proto_quantale \\<times> 'b::proto_quantale)\" times_prod'\n  by standard (simp add: times_prod'_def Sup_prod_def less_eq_prod_def Sup_distl image_comp)\n\ninterpretation prod: unital_quantale one_prod times_prod' Inf_prod Sup_prod inf_prod less_eq_prod less_prod sup_prod bot_prod \"top_prod :: ('a::unital_quantale \\<times> 'b::unital_quantale)\" \n  by standard (simp_all add: one_prod_def times_prod'_def ac_simps image_comp)\n\n\nsubsection \\<open>Quantale Morphisms\\<close>\n\ntext \\<open>There are various ways of defining quantale morphisms, depending on the application. Following Rosenthal, \nI present the most important one.\\<close>\n\nabbreviation comp_pres :: \"('a::times \\<Rightarrow> 'b::times) \\<Rightarrow> bool\" where\n  \"comp_pres f \\<equiv> (\\<forall>x y. f (x \\<cdot> y) = f x \\<cdot> f y)\"\n\nabbreviation un_pres :: \"('a::one \\<Rightarrow> 'b::one) \\<Rightarrow> bool\" where\n  \"un_pres f \\<equiv> (f 1 = 1)\"\n\ndefinition \"comp_closed_set X = (\\<forall>x \\<in> X. \\<forall>y \\<in> X. x \\<cdot> y \\<in> X)\" \n\ndefinition \"un_closed_set X = (1 \\<in> X)\" \n\ndefinition quantale_homset :: \"('a::quantale \\<Rightarrow> 'b::quantale) set\" where\n  \"quantale_homset = {f. comp_pres f \\<and> Sup_pres f}\"\n\nlemma quantale_homset_iff: \"f \\<in> quantale_homset = (comp_pres f \\<and> Sup_pres f)\"\n  unfolding quantale_homset_def by clarsimp\n\ndefinition unital_quantale_homset :: \"('a::unital_quantale \\<Rightarrow> 'b::unital_quantale) set\" where\n  \"unital_quantale_homset = {f. comp_pres f \\<and> Sup_pres f \\<and> un_pres f}\"\n\nlemma unital_quantale_homset_iff: \"f \\<in> unital_quantale_homset = (comp_pres f \\<and> Sup_pres f \\<and> un_pres f)\"\n  unfolding unital_quantale_homset_def by clarsimp\n\ntext \\<open>Though Infs can be defined from Sups in any quantale, quantale morphisms do not generally preserve Infs.\nA different kind of morphism is needed if this is to be guaranteed.\\<close>\n\nlemma \"f \\<in> quantale_homset \\<Longrightarrow> Inf_pres f\" (*nitpick*)\n  oops\n\ntext \\<open>The images of quantale morphisms are closed under compositions and Sups, hence they form quantales.\\<close>\n\nlemma quantale_hom_q_pres: \"f \\<in> quantale_homset \\<Longrightarrow> Sup_closed_set (range f) \\<and> comp_closed_set (range f)\"\n  apply safe\n   apply (simp add: Sup_pres_Sup_closed quantale_homset_iff)\n  unfolding quantale_homset_iff comp_closed_set_def by (metis (no_types, lifting) imageE range_eqI) \n\ntext \\<open>Yet the image need not be Inf-closed.\\<close>\n\nlemma \"f \\<in> quantale_homset \\<Longrightarrow> Inf_closed_set (range f)\" (*nitpick*)\n  oops\n\ntext \\<open>Of course Sups are preserved by quantale-morphisms, hence they are the same in subsets as in the original set.\nInfs in the subset, however, exist, since they subset forms a quantale in which Infs can be defined, but these are generally\ndifferent from the Infs in the superstructure. \n\nThis fact is hidden in Isabelle's definition of complete lattices, where Infs are axiomatised. There is no easy way in general to\nshow that images of quantale morphisms form quantales, though the statement for Sup-quantales is straightforward. I show this for quantic nuclei \nand left-sided elements.\\<close>\n\ntypedef (overloaded) ('a,'b) quantale_homset = \"quantale_homset::('a::quantale \\<Rightarrow> 'b::quantale) set\"\nproof-\n  have a: \"comp_pres (\\<lambda>x::'a::quantale. bot::'b)\"\n    by simp\n  have b: \"Sup_pres (\\<lambda>x::'a::quantale. bot::'b)\"\n    unfolding fun_eq_iff comp_def by simp\n  hence \"(\\<lambda>x::'a::quantale. bot::'b) \\<in> quantale_homset\"\n    by (simp add: quantale_homset_iff)\n  thus ?thesis\n    by auto\nqed\n\nsetup_lifting type_definition_quantale_homset\n\ntext \\<open>Interestingly, the following type is not (gobally) inhabited.\\<close>\n\ntypedef (overloaded) ('a,'b) unital_quantale_homset = \"unital_quantale_homset::('a::unital_quantale \\<Rightarrow> 'b::unital_quantale) set\" (*nitpick*)\n  oops\n\nlemma quantale_hom_radj: \n  fixes f :: \"'a::quantale_with_dual \\<Rightarrow> 'b::quantale_with_dual\"\n  shows \"f \\<in> quantale_homset \\<Longrightarrow> f \\<stileturn> radj f\"\n  unfolding quantale_homset_iff by (simp add: Sup_pres_ladj_aux)\n\nlemma quantale_hom_prop1: \n  fixes f :: \"'a::quantale_with_dual \\<Rightarrow> 'b::quantale_with_dual\"\n  shows \"f \\<in> quantale_homset \\<Longrightarrow> radj f (f x \\<rightarrow> y) = x \\<rightarrow> radj f y\"\nproof-\n  assume h: \"f \\<in> quantale_homset\"\n  have \"f x \\<cdot> f (radj f (f x \\<rightarrow> y)) \\<le> y\"\n    by (meson h adj_def bres_galois order_refl quantale_hom_radj)\n  hence \"f (x \\<cdot> radj f (f x \\<rightarrow> y)) \\<le> y\"\n    by (metis h quantale_homset_iff)\n  hence \"x \\<cdot> radj f (f x \\<rightarrow> y) \\<le> radj f y\"\n    using adj_def h quantale_hom_radj by blast\n  hence le: \"radj f (f x \\<rightarrow> y) \\<le> x \\<rightarrow> radj f y\"\n    by (simp add: bres_galois)\n  have \"x \\<cdot> (x \\<rightarrow> radj f y) \\<le> radj f y\"\n    by (simp add: bres_canc1)\n  hence  \"f (x \\<cdot> (x \\<rightarrow> radj f y)) \\<le> y\"\n    using adj_def h quantale_hom_radj by blast\n  hence \"f x \\<cdot> f (x \\<rightarrow> radj f y) \\<le> y\"\n    by (metis h quantale_homset_iff)\n  hence \"f (x \\<rightarrow> radj f y) \\<le> f x \\<rightarrow> y\"\n    by (simp add: bres_galois)\n  hence \"x \\<rightarrow> radj f y \\<le> radj f (f x \\<rightarrow> y)\"\n    using adj_def h quantale_hom_radj by blast\n  thus ?thesis\n    by (simp add: dual_order.antisym le)\nqed\n\nlemma quantale_hom_prop2: \n  fixes f :: \"'a::quantale_with_dual \\<Rightarrow> 'b::quantale_with_dual\"\n  shows \"f \\<in> quantale_homset \\<Longrightarrow> radj f (y \\<leftarrow> f x) = radj f y \\<leftarrow> x\"\nproof-\n  assume h: \"f \\<in> quantale_homset\"\n  have \"f (radj f (y \\<leftarrow> f x)) \\<cdot> f x \\<le> y\"\n    by (meson adj_def fres_galois h order_refl quantale_hom_radj)\n  hence \"f (radj f (y \\<leftarrow> f x) \\<cdot> x) \\<le> y\"\n    by (metis h quantale_homset_iff)\n  hence \"radj f (y \\<leftarrow> f x) \\<cdot> x\\<le> radj f y\"\n    using adj_def h quantale_hom_radj by blast\n  hence le: \"radj f (y \\<leftarrow> f x) \\<le> radj f y \\<leftarrow> x\"\n    by (simp add: fres_galois)\n  have \"(radj f y \\<leftarrow> x) \\<cdot> x \\<le> radj f y\"\n    by (simp add: fres_canc1)\n  hence  \"f ((radj f y \\<leftarrow> x) \\<cdot> x) \\<le> y\"\n    using adj_def h quantale_hom_radj by blast\n  hence \"f (radj f y \\<leftarrow> x) \\<cdot> f x\\<le> y\"\n    by (metis h quantale_homset_iff)\n  hence \"f (radj f y \\<leftarrow> x) \\<le> y \\<leftarrow> f x\"\n    by (simp add: fres_galois)\n  hence \"radj f y \\<leftarrow> x\\<le> radj f (y \\<leftarrow> f x)\"\n    using adj_def h quantale_hom_radj by blast\n  thus ?thesis\n    by (simp add: dual_order.antisym le)\nqed\n\ndefinition quantale_closed_maps :: \"('a::quantale \\<Rightarrow> 'b::quantale) set\" where\n  \"quantale_closed_maps = {f. (\\<forall>x y. f x \\<cdot> f y \\<le> f (x \\<cdot> y))}\"\n\nlemma quantale_closed_maps_iff: \"f \\<in> quantale_closed_maps = (\\<forall> x y. f x \\<cdot> f y \\<le> f (x \\<cdot> y))\"\n  unfolding quantale_closed_maps_def by clarsimp\n\ndefinition quantale_closed_Sup_maps :: \"('a::quantale \\<Rightarrow> 'b::quantale) set\" where\n  \"quantale_closed_Sup_maps = {f. (\\<forall> x y. f x \\<cdot> f y \\<le> f (x \\<cdot> y)) \\<and> Sup_pres f}\"\n\nlemma quantale_closed_Sup_maps_iff: \"f \\<in> quantale_closed_Sup_maps = (\\<forall> x y. f x \\<cdot> f y \\<le> f (x \\<cdot> y) \\<and> Sup_pres f)\"\n  unfolding quantale_closed_Sup_maps_def by clarsimp\n\ndefinition quantale_closed_unital_maps :: \"('a::unital_quantale \\<Rightarrow> 'b::unital_quantale) set\" where\n  \"quantale_closed_unital_maps = {f. (\\<forall> x y. f x \\<cdot> f y \\<le> f (x \\<cdot> y)) \\<and> 1 \\<le> f 1}\"\n\nlemma quantale_closed_unital_maps_iff: \"f \\<in> quantale_closed_unital_maps = (\\<forall> x y. f x \\<cdot> f y \\<le> f (x \\<cdot> y) \\<and> 1 \\<le> f 1)\"\n  unfolding quantale_closed_unital_maps_def by clarsimp\n\ndefinition quantale_closed_unital_Sup_maps :: \"('a::unital_quantale \\<Rightarrow> 'b::unital_quantale) set\" where\n  \"quantale_closed_unital_Sup_maps = {f. (\\<forall> x y. f x \\<cdot> f y \\<le> f (x \\<cdot> y)) \\<and> Sup_pres f \\<and> 1 \\<le> f 1}\"\n\nlemma quantale_closed_unital_Sup_maps_iff: \"f \\<in> quantale_closed_unital_Sup_maps = (\\<forall> x y. f x \\<cdot> f y \\<le> f (x \\<cdot> y) \\<and> Sup_pres f \\<and> 1 \\<le> f 1)\"\n  unfolding quantale_closed_unital_Sup_maps_def by clarsimp\n\ntext \\<open>Closed maps are the right adjoints of quantale morphisms.\\<close>\n\nlemma quantale_hom_closed_map:\n  fixes f :: \"'a::quantale_with_dual \\<Rightarrow> 'b::quantale_with_dual\"\n  shows \"(f \\<in> quantale_homset) \\<Longrightarrow> (radj f \\<in> quantale_closed_maps)\"\nproof-\n  assume h: \"f \\<in> quantale_homset\"\n  have \"\\<forall>x y. f (radj f x) \\<cdot> f (radj f y) \\<le> x \\<cdot> y\"\n    by (metis adj_def h order_refl psrpq.mult_isol_var quantale_hom_radj) \n  hence \"\\<forall>x y. f (radj f x \\<cdot> radj f y) \\<le> x \\<cdot> y\"\n    by (metis h quantale_homset_iff)\n  hence \"\\<forall>x y. radj f x \\<cdot> radj f y \\<le> radj f (x \\<cdot> y)\"\n    using adj_def h quantale_hom_radj by blast\n  thus ?thesis\n    by (simp add: quantale_closed_maps_iff)\nqed\n\nlemma unital_quantale_hom_closed_unital_map:\n  fixes f :: \"'a::unital_quantale_with_dual \\<Rightarrow> 'b::unital_quantale_with_dual\"\n  shows \"(f \\<in> unital_quantale_homset) \\<Longrightarrow> (radj f \\<in> quantale_closed_unital_maps)\"\n  by (metis (no_types, hide_lams) adj_def order_refl quantale_closed_maps_iff quantale_closed_unital_maps_iff quantale_hom_closed_map quantale_hom_radj quantale_homset_iff unital_quantale_homset_iff)\n\n end\n\n\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/Quantales/Quantales.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8740772450055545, "lm_q2_score": 0.8175744850834648, "lm_q1q2_score": 0.7146232535085897}}
{"text": "(*  Title:      HOL/Library/List_lexord.thy\n    Author:     Norbert Voelker\n*)\n\nsection {* Lexicographic order on lists *}\n\ntheory List_lexord\nimports Main\nbegin\n\ninstantiation list :: (ord) ord\nbegin\n\ndefinition\n  list_less_def: \"xs < ys \\<longleftrightarrow> (xs, ys) \\<in> lexord {(u, v). u < v}\"\n\ndefinition\n  list_le_def: \"(xs :: _ list) \\<le> ys \\<longleftrightarrow> xs < ys \\<or> xs = ys\"\n\ninstance ..\n\nend\n\ninstance list :: (order) order\nproof\n  fix xs :: \"'a list\"\n  show \"xs \\<le> xs\" by (simp add: list_le_def)\nnext\n  fix xs ys zs :: \"'a list\"\n  assume \"xs \\<le> ys\" and \"ys \\<le> zs\"\n  then show \"xs \\<le> zs\"\n    apply (auto simp add: list_le_def list_less_def)\n    apply (rule lexord_trans)\n    apply (auto intro: transI)\n    done\nnext\n  fix xs ys :: \"'a list\"\n  assume \"xs \\<le> ys\" and \"ys \\<le> xs\"\n  then show \"xs = ys\"\n    apply (auto simp add: list_le_def list_less_def)\n    apply (rule lexord_irreflexive [THEN notE])\n    defer\n    apply (rule lexord_trans)\n    apply (auto intro: transI)\n    done\nnext\n  fix xs ys :: \"'a list\"\n  show \"xs < ys \\<longleftrightarrow> xs \\<le> ys \\<and> \\<not> ys \\<le> xs\"\n    apply (auto simp add: list_less_def list_le_def)\n    defer\n    apply (rule lexord_irreflexive [THEN notE])\n    apply auto\n    apply (rule lexord_irreflexive [THEN notE])\n    defer\n    apply (rule lexord_trans)\n    apply (auto intro: transI)\n    done\nqed\n\ninstance list :: (linorder) linorder\nproof\n  fix xs ys :: \"'a list\"\n  have \"(xs, ys) \\<in> lexord {(u, v). u < v} \\<or> xs = ys \\<or> (ys, xs) \\<in> lexord {(u, v). u < v}\"\n    by (rule lexord_linear) auto\n  then show \"xs \\<le> ys \\<or> ys \\<le> xs\"\n    by (auto simp add: list_le_def list_less_def)\nqed\n\ninstantiation list :: (linorder) distrib_lattice\nbegin\n\ndefinition \"(inf \\<Colon> 'a list \\<Rightarrow> _) = min\"\n\ndefinition \"(sup \\<Colon> 'a list \\<Rightarrow> _) = max\"\n\ninstance\n  by default (auto simp add: inf_list_def sup_list_def max_min_distrib2)\n\nend\n\nlemma not_less_Nil [simp]: \"\\<not> x < []\"\n  by (simp add: list_less_def)\n\nlemma Nil_less_Cons [simp]: \"[] < a # x\"\n  by (simp add: list_less_def)\n\nlemma Cons_less_Cons [simp]: \"a # x < b # y \\<longleftrightarrow> a < b \\<or> a = b \\<and> x < y\"\n  by (simp add: list_less_def)\n\nlemma le_Nil [simp]: \"x \\<le> [] \\<longleftrightarrow> x = []\"\n  unfolding list_le_def by (cases x) auto\n\nlemma Nil_le_Cons [simp]: \"[] \\<le> x\"\n  unfolding list_le_def by (cases x) auto\n\nlemma Cons_le_Cons [simp]: \"a # x \\<le> b # y \\<longleftrightarrow> a < b \\<or> a = b \\<and> x \\<le> y\"\n  unfolding list_le_def by auto\n\ninstantiation list :: (order) order_bot\nbegin\n\ndefinition \"bot = []\"\n\ninstance\n  by default (simp add: bot_list_def)\n\nend\n\nlemma less_list_code [code]:\n  \"xs < ([]\\<Colon>'a\\<Colon>{equal, order} list) \\<longleftrightarrow> False\"\n  \"[] < (x\\<Colon>'a\\<Colon>{equal, order}) # xs \\<longleftrightarrow> True\"\n  \"(x\\<Colon>'a\\<Colon>{equal, order}) # xs < y # ys \\<longleftrightarrow> x < y \\<or> x = y \\<and> xs < ys\"\n  by simp_all\n\n\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/List_lexord.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772417253255, "lm_q2_score": 0.8175744761936437, "lm_q1q2_score": 0.7146232430563678}}
{"text": "section \\<open> Kleene Algebra and UTP \\<close>\n\ntheory utp_kleene\n  imports\n    \"KAT_and_DRA.KAT\"\n    \"UTP1.utp\"\nbegin\n\ntext \\<open> This theory instantiates the Kleene Algebra~\\cite{Kozen90} (KA) hierarchy, mechanised in \n  Isabelle/HOL by Armstrong, Gomes, Struth et al~\\cite{Armstrong2015,Gomes2016,Foster11a}., for \n  Isabelle/UTP alphabetised relations~\\cite{Foster16a,Hoare&98}. Specifically, we substantiate the \n  required dioid and KA laws in the type class hierarchy, which allows us to make use of all theorems \n  proved in the former work. Moreover, we also prove an important result that a subclass of UTP \n  theories, which we call ``Kleene UTP theories'', always form Kleene algebras. The proof of the \n  latter is obtained by lifting laws from the KA hierarchy. \\<close>\n\nsubsection \\<open> Syntax setup \\<close>\n\ntext \\<open> It is necessary to replace parts of the KA syntax to ensure compatibility with UTP. We\n  therefore delete various bits of notation, and hide some constants. \\<close>\n\npurge_notation star (\"_\\<^sup>\\<star>\" [101] 100)\n\nrecall_syntax\n\npurge_notation n_op (\"n _\" [90] 91)\npurge_notation ts_ord (infix \"\\<sqsubseteq>\" 50)\n\nnotation n_op (\"\\<^bold>n[_]\")\nnotation t (\"\\<^bold>n\\<^sup>2[_]\")\nnotation ts_ord (infix \"\\<sqsubseteq>\\<^sub>t\" 50)\n\nhide_const t\n\nsubsection \\<open> Kleene Algebra Instantiations \\<close>\n\ntext \\<open> Next, import the laws of Kleene Algebra into the UTP relational calculus. We show\n  that relations form a dioid and a Kleene algebra via two locales, the interpretation of which\n  exports a large library of algebraic laws. \\<close>\n\ninterpretation urel_dioid: dioid\n  where plus = \"(\\<sqinter>)\" and times = \"(;;\\<^sub>h)\" and less_eq = less_eq and less = less\nproof\n  fix P Q R :: \"'\\<alpha> hrel\"\n  show \"(P \\<sqinter> Q) ;; R = (P ;; R) \\<sqinter> (Q ;; R)\"\n    by (simp add: upred_semiring.distrib_right)\n  show \"(Q \\<sqsubseteq> P) = (P \\<sqinter> Q = Q)\"\n    by (simp add: semilattice_sup_class.le_iff_sup)\n  show \"(P < Q) = (Q \\<sqsubseteq> P \\<and> \\<not> P = Q)\"\n    by (simp add: less_le)\n  show \"P \\<sqinter> P = P\"\n    by simp\nqed\n\ninterpretation urel_ka: kleene_algebra\n  where plus = \"(\\<sqinter>)\" and times = \"(;;\\<^sub>h)\" and one = skip_r and zero = false\\<^sub>h and less_eq = less_eq and less = less and star = ustar\nproof\n  fix P Q R :: \"'\\<alpha> hrel\"\n  show \"II ;; P = P\" by simp\n  show \"P ;; II = P\" by simp\n  show \"false \\<sqinter> P = P\" by simp\n  show \"false ;; P = false\" by simp\n  show \"P ;; false = false\" by simp\n  show \"P\\<^sup>\\<star> \\<sqsubseteq> II \\<sqinter> (P ;; P\\<^sup>\\<star>)\"\n    using ustar_sub_unfoldl by blast\n  show \"Q \\<sqsubseteq> R \\<sqinter> (P ;; Q) \\<Longrightarrow> Q \\<sqsubseteq> P\\<^sup>\\<star> ;; R\"\n    by (simp add: ustar_inductl)\n  show \"Q \\<sqsubseteq> R \\<sqinter> (Q ;; P) \\<Longrightarrow> Q \\<sqsubseteq> R ;; P\\<^sup>\\<star>\"\n    by (simp add: ustar_inductr)\nqed\n\ntext \\<open> We also show that UTP relations form a Kleene Algebra with Tests~\\cite{kozen1997kleene,Gomes2016} (KAT). \\<close>\n\ninterpretation urel_kat: kat\n  where plus = \"(\\<sqinter>)\" and times = \"(;;\\<^sub>h)\" and one = skip_r and zero = false\\<^sub>h and less_eq = less_eq and less = less and star = ustar and n_op = \"\\<lambda>x. II \\<and> (\\<not> x)\"\n  by (unfold_locales, rel_auto+)\n\ntext \\<open> We can now access the laws of KA and KAT for UTP relations as below. \\<close>\n\nthm urel_ka.star_inductr_var\nthm urel_ka.star_trans\nthm urel_ka.star_square\nthm urel_ka.independence1\n\nsubsection \\<open> Derived Laws \\<close>\n\ntext \\<open> We prove that UTP assumptions are tests. \\<close>\n\nlemma test_rassume [simp]: \"urel_kat.test [b]\\<^sup>\\<top>\"\n  by (simp add: urel_kat.test_def, rel_auto)\n\ntext \\<open> The KAT laws can be used to prove results like the one below. \\<close>\n\nlemma while_kat_form:\n  \"while b do P od = ([b]\\<^sup>\\<top> ;; P)\\<^sup>\\<star> ;; [(\\<not> b)]\\<^sup>\\<top>\" (is \"?lhs = ?rhs\")\nproof -\n  have 1:\"(II::'a hrel) \\<sqinter> ((II::'a hrel) ;; [(\\<not> b)]\\<^sup>\\<top>) = II\"\n    by (metis assume_true test_rassume urel_kat.test_absorb1)\n  have \"?lhs = (([b]\\<^sup>\\<top> ;; P) \\<sqinter> ([(\\<not> b)]\\<^sup>\\<top> ;; II))\\<^sup>\\<star> ;; [(\\<not> b)]\\<^sup>\\<top>\"\n    by (simp add: while_star_form rcond_rassume_expand)\n  also have \"... = (([b]\\<^sup>\\<top> ;; P)\\<^sup>\\<star> ;; [(\\<not> b)]\\<^sup>\\<top>\\<^sup>\\<star>)\\<^sup>\\<star> ;; [(\\<not> b)]\\<^sup>\\<top>\"\n    by (metis seqr_right_unit urel_ka.star_denest)\n  also have \"... = (([b]\\<^sup>\\<top> ;; P)\\<^sup>\\<star> ;; (II \\<sqinter> [(\\<not> b)]\\<^sup>\\<top>)\\<^sup>\\<star>)\\<^sup>\\<star> ;; [(\\<not> b)]\\<^sup>\\<top>\"\n    by (metis urel_ka.star2)\n  also have \"... = (([b]\\<^sup>\\<top> ;; P)\\<^sup>\\<star> ;; (II)\\<^sup>\\<star>)\\<^sup>\\<star> ;; [(\\<not> b)]\\<^sup>\\<top>\"\n    by (metis 1 seqr_left_unit)\n  also have \"... = (([b]\\<^sup>\\<top> ;; P)\\<^sup>\\<star>)\\<^sup>\\<star> ;; [(\\<not> b)]\\<^sup>\\<top>\"\n    by (metis urel_ka.mult_oner urel_ka.star_one)\n  also have \"... = ?rhs\"\n    by (metis urel_ka.star_invol)\n  finally show ?thesis .\nqed\n\nlemma uplus_invol [simp]: \"(P\\<^sup>+)\\<^sup>+ = P\\<^sup>+\"\n  by (metis RA1 uplus_def urel_ka.conway.dagger_trans_eq urel_ka.star_denest_var_2 urel_ka.star_invol)\n\nlemma uplus_alt_def: \"P\\<^sup>+ = P\\<^sup>\\<star> ;; P\"\n  by (simp add: uplus_def urel_ka.star_slide_var)\n\nsubsection \\<open> UTP Theories with Kleene Algebra \\<close>\n\ntext \\<open> A Kleene UTP theory is continuous UTP theory with left and right units, and the top element as\n  a left zero. The star in such a context has already been defined by lifting the relational Kleene star. Here, \n  we use the KA theorems obtained above to provide corresponding theorems for a Kleene UTP theory. \\<close>\n\nlocale utp_theory_kleene = utp_theory_cont_unital_zerol\nbegin                                             \n\nlemma Star_def: \"P\\<^bold>\\<star> = P\\<^sup>\\<star> ;; \\<I>\\<I>\"\n  by (simp add: utp_star_def)\n  \nlemma Star_alt_def:\n  assumes \"P is \\<H>\"\n  shows \"P\\<^bold>\\<star> = \\<I>\\<I> \\<sqinter> P\\<^sup>+\"\nproof -\n  from assms have \"P\\<^sup>+ = P\\<^sup>\\<star> ;; P ;; \\<I>\\<I>\"\n    by (simp add: Unit_Right uplus_alt_def)\n  then show ?thesis\n    by (simp add: RA1 utp_star_def)\nqed\n\nlemma Star_Healthy [closure]:\n  assumes \"P is \\<H>\"\n  shows \"P\\<^bold>\\<star> is \\<H>\"\n  by (simp add: assms closure Star_alt_def)\n\nlemma Star_unfoldl:\n  \"P\\<^bold>\\<star> \\<sqsubseteq> \\<I>\\<I> \\<sqinter> (P ;; P\\<^bold>\\<star>)\"\n  by (simp add: RA1 utp_star_def)\n\nlemma Star_inductl:\n  assumes \"R is \\<H>\" \"Q \\<sqsubseteq> (P ;; Q) \\<sqinter> R\"\n  shows \"Q \\<sqsubseteq> P\\<^bold>\\<star>;;R\"\nproof -\n  from assms(2) have \"Q \\<sqsubseteq> R\" \"Q \\<sqsubseteq> P ;; Q\"\n    by auto\n  thus ?thesis\n    by (simp add: Unit_Left assms(1) upred_semiring.mult_assoc urel_ka.star_inductl utp_star_def)\nqed\n\nlemma Star_invol:\n  assumes \"P is \\<H>\"\n  shows \"P\\<^bold>\\<star>\\<^bold>\\<star> = P\\<^bold>\\<star>\"\n  by (metis (no_types) RA1 Unit_Left Unit_self assms urel_ka.star_invol urel_ka.star_sim3 utp_star_def)\n\nlemma Star_test: \n  assumes \"P is \\<H>\" \"utp_test P\"\n  shows \"P\\<^bold>\\<star> = \\<I>\\<I>\"\n  by (metis utp_star_def Star_alt_def Unit_Right Unit_self assms semilattice_sup_class.sup.absorb1 semilattice_sup_class.sup_left_idem urel_ka.star_inductr_var_eq2 urel_ka.star_sim1 utp_test_def)\n\nlemma Star_lemma_1:\n  \"P is \\<H> \\<Longrightarrow> \\<I>\\<I> ;; P\\<^sup>\\<star> ;; \\<I>\\<I> = P\\<^sup>\\<star> ;; \\<I>\\<I>\"\n  by (metis utp_star_def Star_Healthy Unit_Left)\n  \nlemma Star_lemma_2:\n  assumes \"P is \\<H>\" \"Q is \\<H>\"\n  shows \"(P\\<^sup>\\<star> ;; Q\\<^sup>\\<star> ;; \\<I>\\<I>)\\<^sup>\\<star> ;; \\<I>\\<I> = (P\\<^sup>\\<star> ;; Q\\<^sup>\\<star>)\\<^sup>\\<star> ;; \\<I>\\<I>\"\n  by (metis (no_types) assms RA1 Star_lemma_1 Unit_self urel_ka.star_sim3)\n\nlemma Star_denest:\n  assumes \"P is \\<H>\" \"Q is \\<H>\"\n  shows \"(P \\<sqinter> Q)\\<^bold>\\<star> = (P\\<^bold>\\<star> ;; Q\\<^bold>\\<star>)\\<^bold>\\<star>\"\n  by (metis (no_types, lifting) RA1 utp_star_def Star_lemma_1 Star_lemma_2 assms urel_ka.star_denest)  \n\nlemma Star_denest_disj: \n  assumes \"P is \\<H>\" \"Q is \\<H>\"\n  shows \"(P \\<or> Q)\\<^bold>\\<star> = (P\\<^bold>\\<star> ;; Q\\<^bold>\\<star>)\\<^bold>\\<star>\"\n  by (simp add: disj_upred_def Star_denest assms)\n\nlemma Star_unfoldl_eq: \n  assumes \"P is \\<H>\"\n  shows \"\\<I>\\<I> \\<sqinter> (P ;; P\\<^bold>\\<star>) = P\\<^bold>\\<star>\"\n  by (simp add: RA1 utp_star_def)\n\nlemma uplus_Star_def:\n  assumes \"P is \\<H>\"\n  shows \"P\\<^sup>+ = (P ;; P\\<^bold>\\<star>)\"\n  by (metis (full_types) RA1 utp_star_def Unit_Left Unit_Right assms uplus_def urel_ka.conway.dagger_slide)\n\nlemma Star_trade_skip:\n  \"P is \\<H> \\<Longrightarrow> \\<I>\\<I> ;; P\\<^sup>\\<star> = P\\<^sup>\\<star> ;; \\<I>\\<I>\"\n  by (simp add: Unit_Left Unit_Right urel_ka.star_sim3)\n\nlemma Star_slide:\n  assumes \"P is \\<H>\"\n  shows \"(P ;; P\\<^bold>\\<star>) = (P\\<^bold>\\<star> ;; P)\" (is \"?lhs = ?rhs\")\nproof -\n  have \"?lhs = P ;; P\\<^sup>\\<star> ;; \\<I>\\<I>\"\n    by (simp add: utp_star_def)\n  also have \"... = P ;; \\<I>\\<I> ;; P\\<^sup>\\<star>\"\n    by (simp add: Star_trade_skip assms)\n  also have \"... = P ;; P\\<^sup>\\<star>\"\n    by (simp add: RA1 Unit_Right assms)\n  also have \"... = P\\<^sup>\\<star> ;; P\"\n    by (simp add: urel_ka.star_slide_var)\n  also have \"... = ?rhs\"\n    by (metis RA1 utp_star_def Unit_Left assms)\n  finally show ?thesis .\nqed\n\nlemma Star_unfoldr_eq:\n  assumes \"P is \\<H>\"\n  shows \"\\<I>\\<I> \\<sqinter> (P\\<^bold>\\<star> ;; P) = P\\<^bold>\\<star>\"\n  using Star_slide Star_unfoldl_eq assms by auto\n\nlemma Star_inductr:\n  assumes \"P is \\<H>\" \"R is \\<H>\" \"Q \\<sqsubseteq> P \\<sqinter> (Q ;; R)\"\n  shows \"Q \\<sqsubseteq> P;;R\\<^bold>\\<star>\"\n  by (metis (full_types) RA1 Star_def Star_trade_skip Unit_Right assms urel_ka.star_inductr')\n\nlemma Star_Top: \"\\<^bold>\\<top>\\<^bold>\\<star> = \\<I>\\<I>\"\n  by (simp add: Star_test top_healthy utest_Top)\n\nend\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/theories/kleene/utp_kleene.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8175744761936437, "lm_q2_score": 0.8740772384450967, "lm_q1q2_score": 0.7146232403745365}}
{"text": "(*\n    $Id: ex.thy,v 1.4 2010/11/29 07:13:36 kleing Exp $\n    Author: Martin Strecker\n*)\n\nheader {* The Euclidean Algorithm -- Inductively *}\n\n(*<*) theory ex imports Main begin (*>*)\n\nsubsection {* Rules without base case *}\n\ntext {* Show that the following *}\n\ninductive_set evenempty :: \"nat set\" where\nAdd2Ie: \"n \\<in> evenempty \\<Longrightarrow> Suc(Suc n) \\<in> evenempty\"\n\ntext {* defines the empty set: *}\n\nlemma evenempty_empty: \"evenempty = {}\"\n(*<*) oops (*>*)\n\n\nsubsection {* The Euclidean algorithm *}\n\ntext {* Define inductively the set @{text gcd}, which characterizes\nthe greatest common divisor of two natural numbers: *}\n\n(*<*)consts(*>*)\n  gcd :: \"(nat \\<times> nat \\<times> nat) set\"\n\ntext {* Here, @{text \"(a,b,g) \\<in> gcd\"} means that @{text g} is the gcd\nof @{text a} und @{text b}. The definition should closely follow the\nEuclidean algorithm.\n\nReminder: The Euclidean algorithm repeatedly subtracts the smaller\nfrom the larger number, until one of the numbers is 0. Then, the other\nnumber is the gcd. *}\n\n\ntext {* Now, compute the gcd of 15 and 10: *}\n\nschematic_lemma \"(15, 10, ?g)  \\<in> gcd\"\n(*<*) oops (*>*)\n\n\ntext {* How does your algorithm behave on special cases as the following? *}\n\nschematic_lemma \"(0, 0, ?g)  \\<in> gcd\"\n(*<*) oops (*>*)\n\n\ntext {* Show that the gcd is really a divisor (for the proof, you need an\nappropriate lemma): *}\n\nlemma gcd_divides: \"(a,b,g) \\<in> gcd \\<Longrightarrow> g dvd a \\<and> g dvd b\"\n(*<*) oops (*>*)\n\n\ntext {* Show that the gcd is the greatest common divisor: *}\n\nlemma gcd_greatest [rule_format]: \"(a,b,g) \\<in> gcd \\<Longrightarrow>\n  0 < a \\<or> 0 < b \\<longrightarrow> (\\<forall> d. d dvd a \\<longrightarrow> d dvd b \\<longrightarrow> d \\<le> g)\"\n(*<*) oops (*>*)\n\n\ntext {* Here as well, you will have to prove a suitable lemma. What is the\nprecondition @{text \"0 < a \\<or> 0 < b\"} good for?\n\nSo far, we have only shown that @{text gcd} is correct, but your algorithm\nmight not compute a result for all values @{text \"a,b\"}.  Thus, show\ncompleteness of the algorithm: *}\n\nlemma gcd_defined: \"\\<forall> a b. \\<exists> g. (a, b, g) \\<in> gcd\"\n(*<*) oops (*>*)\n\ntext {* The following lemma, proved by course-of-value recursion over @{text\nn}, may be useful.  Why does standard induction over natural numbers not work\nhere? *}\n\nlemma gcd_defined_aux [rule_format]: \n  \"\\<forall> a b. (a + b) \\<le> n \\<longrightarrow> (\\<exists> g. (a, b, g) \\<in> gcd)\"\n  apply (induct rule: nat_less_induct)\n  apply clarify\n(*<*) oops (*>*)\n\ntext {* The idea is to show that @{text gcd} yields a result for all @{text \"a,\nb\"} whenever it is known that @{text gcd} yields a result for all @{text \"a',\nb'\"} whose sum is smaller than @{text \"a + b\"}.\n\nIn order to prove this lemma, make case distinctions corresponding to the\ndifferent clauses of the algorithm, and show how to reduce computation of\n@{text gcd} for @{text \"a, b\"} to computation of @{text gcd} for suitable\nsmaller @{text \"a', b'\"}. *}\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/euclid/ex.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8740772318846386, "lm_q2_score": 0.8175744761936437, "lm_q1q2_score": 0.7146232350108734}}
{"text": "theory Kyber_NTT_Values\n\nimports Kyber_Values\n        NTT_Scheme\n        Powers3844\n\nbegin\nsection \\<open>Specification of Kyber with NTT\\<close>\ntext \\<open>Calculations for NTT specifications\\<close>\n\nlemma \"3844 * 6584 = (1 :: fin7681 mod_ring)\"\nby simp \n\nlemma \"62 * 1115 = (1 :: fin7681 mod_ring)\"\nby simp\n\nlemma \"256 * 7651 = (1:: fin7681 mod_ring)\"\nby simp\n\nlemma \"7681 = 30 * 256 + (1::int)\" by simp \n\n\nlemma powr256:  \"3844 ^ 256 = (1::fin7681 mod_ring)\" \nproof -\n  have calc1: \"3844^16 = (7154::fin7681 mod_ring)\" by simp\n  have calc2: \"7154^16 = (1::fin7681 mod_ring)\" by simp\n  have \"(3844::fin7681 mod_ring)^256 = (3844^16)^16\"\n    by (metis (mono_tags, opaque_lifting) num_double numeral_times_numeral power_mult)\n  also have \"\\<dots> = 1\" unfolding calc1 calc2 by auto\n  finally show ?thesis by blast\nqed\n\n\n\nlemma powr256':\n\"62 ^ 256 = (- 1::fin7681 mod_ring)\" \nproof -\n  have calc1: \"62^16 = (1366::fin7681 mod_ring)\" by simp\n  have calc2: \"1366^16 = (-1::fin7681 mod_ring)\" by simp\n  have \"(62::fin7681 mod_ring)^256 = (62^16)^16\"\n    by (metis (mono_tags, opaque_lifting) num_double numeral_times_numeral power_mult)\n  also have \"\\<dots> = -1\" unfolding calc1 calc2 by auto\n  finally show ?thesis by blast\nqed\n\n(*\npowrs 3844^l for l=1..<256 in Powrs_3844 file\"\n*)\n\n\ninterpretation kyber7681_ntt: kyber_ntt 256 7681 3 8 \n    \"TYPE(fin7681)\" \"TYPE(3)\" 3844 6584 62 1115 7651 30\nproof (unfold_locales, goal_cases)\n  case 5\n  then show ?case using kyber7681.q_prime by fastforce\nnext\n  case 7\n  then show ?case using kyber7681.CARD_k by blast\nnext\n  case 8\n  then show ?case by (simp add: qr_poly'_fin7681_def)\nnext\n  case 9\n  then show ?case using powr256 by blast\nnext\n  case 11\n  then show ?case proof (safe, goal_cases)\n    case (1 m)\n    then show ?case using powr_less256[OF 1(2)]\n    using linorder_not_less by blast\n  qed\nnext\n  case 15\n  then show ?case using powr256' by blast\nnext\n  case 17\n  have mult: \"256 * 7651 = (1::fin7681 mod_ring)\" by simp\n  have of_int: \"of_int_mod_ring (int 256) = 256\"\n    by (metis o_def of_nat_numeral of_nat_of_int_mod_ring)\n  show ?case unfolding of_int mult by simp\nqed (auto)\n\nend", "meta": {"author": "ThikaXer", "repo": "Kyber_Formalization", "sha": "a1832e7b8e29852c35f252b5703083f912cfe5ff", "save_path": "github-repos/isabelle/ThikaXer-Kyber_Formalization", "path": "github-repos/isabelle/ThikaXer-Kyber_Formalization/Kyber_Formalization-a1832e7b8e29852c35f252b5703083f912cfe5ff/Kyber_NTT_Values.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9465966717067252, "lm_q2_score": 0.7549149868676283, "lm_q1q2_score": 0.714600013990423}}
{"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\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 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)\"\n  using mono_Field[of \"r - Id\" r] Diff_subset[of r Id]\nproof auto\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\nqed\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 auto\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 auto\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_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 Wellfounded}:\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 (auto simp add: chi_def R_def)\n      fix b\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    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 (clarsimp simp: trans_wf_iff wf_iff_acyclic_if_finite converse_def assms)\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\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    apply (auto simp: ex_in_conv [THEN sym])\n     apply (erule wfE_min)\n      apply assumption\n     apply blast\n    apply (rule wfI_min)\n    apply fast\n    done\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": "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/Order_Relation.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8311430645886583, "lm_q2_score": 0.8596637559030338, "lm_q1q2_score": 0.7145035685970438}}
{"text": "theory Sort\n  imports\n    Main\n    \"HOL-Library.Multiset\"\n    \"HOL-Library.Code_Target_Nat\"\nbegin\n\nfun sort_list :: \\<open>'a :: linorder list \\<Rightarrow> 'a list\\<close> where\n  \\<open>sort_list [] = []\\<close>\n| \\<open>sort_list (x # xs) = sort_list [y \\<leftarrow> xs. \\<not> x \\<le> y] @ [x] @ sort_list [y \\<leftarrow> xs. x \\<le> y]\\<close>\n\nlemma sort_permutes [simp]: \\<open>mset (sort_list xs) = mset xs\\<close>\n  by (induction xs rule: sort_list.induct) auto\n\nlemma sort_set_permutes [simp]: \\<open>set (sort_list xs) = set xs\\<close>\n  by (induction xs rule: sort_list.induct) auto\n\nlemma sort_sorts: \\<open>sorted (sort_list xs)\\<close>\n  by (induction xs rule: sort_list.induct) (auto simp add: sorted_append)\n\nexport_code sort_list in Haskell (string_classes)\n\nend", "meta": {"author": "fkj", "repo": "isabelle-cabal-demo", "sha": "15a62a57537907530b60eac6801a53fd74d47cff", "save_path": "github-repos/isabelle/fkj-isabelle-cabal-demo", "path": "github-repos/isabelle/fkj-isabelle-cabal-demo/isabelle-cabal-demo-15a62a57537907530b60eac6801a53fd74d47cff/Sort.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8840392878563335, "lm_q2_score": 0.8080672089305841, "lm_q1q2_score": 0.7143631599230487}}
{"text": "theory Ugraphs\nimports\n  Girth_Chromatic_Misc\nbegin\n\nsection \\<open>Undirected Simple Graphs\\<close>\n\ntext \\<open>\n  In this section, we define some basics of graph theory needed to formalize\n  the Chromatic-Girth theorem.\n\\<close>\n\ntext \\<open>\n  For readability, we introduce synonyms for the types of vertexes, edges,\n  graphs and walks.\n\\<close>\ntype_synonym uvert = nat\ntype_synonym uedge = \"nat set\"\ntype_synonym ugraph = \"uvert set \\<times> uedge set\"\ntype_synonym uwalk = \"uvert list\"\n\nabbreviation uedges :: \"ugraph \\<Rightarrow> uedge set\" where\n  \"uedges G \\<equiv> snd G\"\n\nabbreviation uverts :: \"ugraph \\<Rightarrow> uvert set\" where\n  \"uverts G \\<equiv> fst G\"\n\nfun mk_uedge :: \"uvert \\<times> uvert \\<Rightarrow> uedge\" where\n   \"mk_uedge (u,v) = {u,v}\"\n\ntext \\<open>All edges over a set of vertexes @{term S}:\\<close>\ndefinition \"all_edges S \\<equiv> mk_uedge ` {uv \\<in> S \\<times> S. fst uv \\<noteq> snd uv}\"\n\ndefinition uwellformed :: \"ugraph \\<Rightarrow> bool\" where\n  \"uwellformed G \\<equiv> (\\<forall>e\\<in>uedges G. card e = 2 \\<and> (\\<forall>u \\<in> e. u \\<in> uverts G))\"\n\nfun uwalk_edges :: \"uwalk \\<Rightarrow> uedge list\" where\n    \"uwalk_edges [] = []\"\n  | \"uwalk_edges [x] = []\"\n  | \"uwalk_edges (x # y # ys) = {x,y} # uwalk_edges (y # ys)\"\n\ndefinition uwalk_length :: \"uwalk \\<Rightarrow> nat\" where\n  \"uwalk_length p \\<equiv> length (uwalk_edges p)\"\n\ndefinition uwalks :: \"ugraph \\<Rightarrow> uwalk set\" where\n  \"uwalks G \\<equiv> {p. set p \\<subseteq> uverts G \\<and> set (uwalk_edges p) \\<subseteq> uedges G \\<and> p \\<noteq> []}\"\n\ndefinition ucycles :: \"ugraph \\<Rightarrow> uwalk set\" where\n  \"ucycles G \\<equiv> {p. uwalk_length p \\<ge> 3 \\<and> p \\<in> uwalks G \\<and> distinct (tl p) \\<and> hd p = last p}\"\n\ndefinition remove_vertex :: \"ugraph \\<Rightarrow> nat \\<Rightarrow> ugraph\" (\"_ -- _\" [60,60] 60) where\n  \"remove_vertex G u \\<equiv> (uverts G - {u}, uedges G - {A \\<in> uedges G. u \\<in> A})\"\n\n\nsubsection \\<open>Basic Properties\\<close>\n\nlemma uwalk_length_conv: \"uwalk_length p = length p - 1\"\n  by (induct p rule: uwalk_edges.induct) (auto simp: uwalk_length_def)\n\nlemma all_edges_mono:\n  \"vs \\<subseteq> ws \\<Longrightarrow> all_edges vs \\<subseteq> all_edges ws\"\nunfolding all_edges_def by auto\n\nlemma all_edges_subset_Pow: \"all_edges A \\<subseteq> Pow A\"\n  by (auto simp: all_edges_def)\n\nlemma in_mk_uedge_img: \"(a,b) \\<in> A \\<or> (b,a) \\<in> A \\<Longrightarrow> {a,b} \\<in> mk_uedge ` A\"\n  by (auto intro: rev_image_eqI)\n\nlemma distinct_edgesI:\n  assumes \"distinct p\" shows \"distinct (uwalk_edges p)\"\nproof -\n  from assms have \"?thesis\" \"\\<And>u. u \\<notin> set p \\<Longrightarrow> (\\<And>v. u \\<noteq> v \\<Longrightarrow> {u,v} \\<notin> set (uwalk_edges p))\"\n    by (induct p rule: uwalk_edges.induct) auto\n  then show ?thesis by simp\nqed\n\nlemma finite_ucycles:\n  assumes \"finite (uverts G)\"\n  shows \"finite (ucycles G)\"\nproof -\n  have \"ucycles G \\<subseteq> {xs. set xs \\<subseteq> uverts G \\<and> length xs \\<le> Suc (card (uverts G))}\"\n  proof (rule, simp)\n    fix p assume \"p \\<in> ucycles G\"\n    then have \"distinct (tl p)\" and \"set p \\<subseteq> uverts G\"\n      unfolding ucycles_def uwalks_def by auto\n    moreover\n    then have \"set (tl p) \\<subseteq> uverts G\"\n      by (auto simp: list_set_tl)\n    with assms have \"card (set (tl p)) \\<le> card (uverts G)\"\n      by (rule card_mono)\n    then have \"length (p) \\<le> 1 + card (uverts G)\"\n      using distinct_card[OF \\<open>distinct (tl p)\\<close>] by auto\n    ultimately show \"set p \\<subseteq> uverts G \\<and> length p \\<le> Suc (card (uverts G))\" by auto\n  qed\n  moreover\n  have \"finite {xs. set xs \\<subseteq> uverts G \\<and> length xs \\<le> Suc (card (uverts G))}\"\n    using assms by (rule finite_lists_length_le)\n  ultimately\n  show ?thesis by (rule finite_subset)\nqed\n\nlemma ucycles_distinct_edges:\n  assumes \"c \\<in> ucycles G\" shows \"distinct (uwalk_edges c)\"\nproof -\n  from assms have c_props: \"distinct (tl c)\" \"4 \\<le> length c\" \"hd c = last c\"\n    by (auto simp add: ucycles_def uwalk_length_conv)\n  then have \"{hd c, hd (tl c)} \\<notin> set (uwalk_edges (tl c))\"\n  proof (induct c rule: uwalk_edges.induct)\n    case (3 x y ys)\n    then have \"hd ys \\<noteq> last ys\" by (cases ys) auto\n    moreover\n    from 3 have \"uwalk_edges (y # ys) = {y, hd ys} # uwalk_edges ys\"\n      by (cases ys) auto\n    moreover\n    { fix xs have \"set (uwalk_edges xs) \\<subseteq> Pow (set xs)\"\n        by (induct xs rule: uwalk_edges.induct) auto }\n    ultimately\n    show ?case using 3 by auto\n  qed simp_all\n  moreover\n  from assms have \"distinct (uwalk_edges (tl c))\"\n    by (intro distinct_edgesI) (simp add: ucycles_def)\n  ultimately\n  show ?thesis by (cases c rule: list_exhaust3) auto\nqed\n\nlemma card_left_less_pair:\n  fixes A :: \"('a :: linorder) set\"\n  assumes \"finite A\"\n  shows \"card {(a,b). a \\<in> A \\<and> b \\<in> A \\<and> a < b}\n    = (card A * (card A - 1)) div 2\"\nusing assms\nproof (induct A)\n  case (insert x A)\n\n  show ?case\n  proof (cases \"card A\")\n    case (Suc n)\n    have \"{(a,b). a \\<in> insert x A \\<and> b \\<in> insert x A \\<and> a < b}\n        = {(a,b). a \\<in> A \\<and> b \\<in> A \\<and> a < b} \\<union> (\\<lambda>a. if a < x then (a,x) else (x,a)) ` A\"\n      using \\<open>x \\<notin> A\\<close> by (auto simp: order_less_le)\n    moreover\n    have \"finite {(a,b). a \\<in> A \\<and> b \\<in> A \\<and> a < b}\"\n      using insert by (auto intro: finite_subset[of _ \"A \\<times> A\"])\n    moreover \n    have \"{(a,b). a \\<in> A \\<and> b \\<in> A \\<and> a < b} \\<inter> (\\<lambda>a. if a < x then (a,x) else (x,a)) ` A = {}\"\n      using \\<open>x \\<notin> A\\<close> by auto\n    moreover have \"inj_on (\\<lambda>a. if a < x then (a, x) else (x, a)) A\"\n      by (auto intro: inj_onI split: if_split_asm)\n    ultimately show ?thesis using insert Suc\n      by (simp add: card_Un_disjoint card_image del: if_image_distrib)\n  qed (simp add: card_eq_0_iff insert)\nqed simp\n\nlemma card_all_edges:\n  assumes \"finite A\"\n  shows \"card (all_edges A) = card A choose 2\"\nproof -\n  have inj_on_mk_uedge: \"inj_on mk_uedge {(a,b). a < b}\"\n    by (rule inj_onI) (auto simp: doubleton_eq_iff)\n  have \"all_edges A = mk_uedge ` {(a,b). a \\<in> A \\<and> b \\<in> A \\<and> a < b}\" (is \"?L = ?R\")\n    by (auto simp: all_edges_def intro!: in_mk_uedge_img)\n  then have \"card ?L = card ?R\" by simp\n  also have \"\\<dots> = card {(a,b). a \\<in> A \\<and> b \\<in> A \\<and> a < b}\"\n    using inj_on_mk_uedge by (blast intro: card_image subset_inj_on)\n  also have \"\\<dots> = (card A * (card A - 1)) div 2\"\n    using card_left_less_pair using assms by simp\n  also have \"\\<dots> = (card A choose 2)\"\n    by (simp add: n_choose_2_nat)\n  finally show ?thesis .\nqed\n\nlemma verts_Gu: \"uverts (G -- u) = uverts G - {u}\"\n  unfolding remove_vertex_def by simp\n\nlemma edges_Gu: \"uedges (G -- u) \\<subseteq> uedges G\"\n  unfolding remove_vertex_def by auto\n\n\nsubsection \\<open>Girth, Independence and Vertex Colorings\\<close>\n\ndefinition girth :: \"ugraph \\<Rightarrow> enat\" where\n  \"girth G \\<equiv> INF p\\<in> ucycles G. enat (uwalk_length p)\"\n\ndefinition independent_sets :: \"ugraph \\<Rightarrow> uvert set set\" where\n  \"independent_sets Gr \\<equiv> {vs. vs \\<subseteq> uverts Gr \\<and> all_edges vs \\<inter> uedges Gr = {}}\"\n\ndefinition \\<alpha> :: \"ugraph \\<Rightarrow> enat\" where\n   \"\\<alpha> G \\<equiv> SUP vs \\<in> independent_sets G. enat (card vs)\"\n\ndefinition vertex_colorings :: \"ugraph \\<Rightarrow> uvert set set set\" where\n  \"vertex_colorings G \\<equiv> {C. \\<Union>C = uverts G \\<and> (\\<forall>c1\\<in>C. \\<forall>c2\\<in>C. c1 \\<noteq> c2 \\<longrightarrow> c1 \\<inter> c2 = {}) \\<and>\n    (\\<forall>c\\<in>C. c \\<noteq> {} \\<and> (\\<forall>u \\<in> c. \\<forall>v \\<in> c. {u,v} \\<notin> uedges G))}\"\n\ntext \\<open>The chromatic number $\\chi$:\\<close>\ndefinition chromatic_number :: \"ugraph \\<Rightarrow> enat\" where\n  \"chromatic_number G \\<equiv> INF c\\<in> (vertex_colorings G). enat (card c)\"\n\nlemma independent_sets_mono:\n  \"vs \\<in> independent_sets G \\<Longrightarrow> us \\<subseteq> vs \\<Longrightarrow> us \\<in> independent_sets G\"\n  using Int_mono[OF all_edges_mono, of us vs \"uedges G\" \"uedges G\"]\n  unfolding independent_sets_def by auto\n\nlemma le_\\<alpha>_iff:\n  assumes \"0 < k\"\n  shows \"k \\<le> \\<alpha> Gr \\<longleftrightarrow> k \\<in> card ` independent_sets Gr\" (is \"?L \\<longleftrightarrow> ?R\")\nproof\n  assume ?L\n  then obtain vs where \"vs \\<in> independent_sets Gr\" and \"k \\<le> card vs\"\n    using assms unfolding \\<alpha>_def enat_le_Sup_iff by auto\n  moreover\n  then obtain us where \"us \\<subseteq> vs\" and \"k = card us\"\n    using card_Ex_subset by auto\n  ultimately\n  have \"us \\<in> independent_sets Gr\"  by (auto intro: independent_sets_mono)\n  then show ?R using \\<open>k = card us\\<close> by auto\nqed (auto intro: SUP_upper simp: \\<alpha>_def)\n\nlemma zero_less_\\<alpha>:\n  assumes \"uverts G \\<noteq> {}\"\n  shows \"0 < \\<alpha> G\"\nproof -\n  from assms obtain a where \"a \\<in> uverts G\" by auto\n  then have \"0 < enat (card {a})\" \"{a} \\<in> independent_sets G\"\n    by (auto simp: independent_sets_def all_edges_def)\n  then show ?thesis unfolding \\<alpha>_def less_SUP_iff ..\nqed\n\nlemma \\<alpha>_le_card:\n  assumes \"finite (uverts G)\"\n  shows \"\\<alpha> G \\<le> card(uverts G)\"\nproof -\n  { fix x assume \"x \\<in> independent_sets G\"\n    then have \"x \\<subseteq> uverts G\" by (auto simp: independent_sets_def) }\n  with assms show ?thesis unfolding \\<alpha>_def\n    by (intro SUP_least) (auto intro: card_mono)\nqed\n\nlemma \\<alpha>_fin: \"finite (uverts G) \\<Longrightarrow> \\<alpha> G \\<noteq> \\<infinity>\"\n  using \\<alpha>_le_card[of G] by (cases \"\\<alpha> G\") auto\n\nlemma \\<alpha>_remove_le:\n  shows \"\\<alpha> (G -- u) \\<le> \\<alpha> G\"\nproof -\n  have \"independent_sets (G -- u) \\<subseteq> independent_sets G\" (is \"?L \\<subseteq> ?R\")\n    using all_edges_subset_Pow by (simp add: independent_sets_def remove_vertex_def) blast\n  then show ?thesis unfolding \\<alpha>_def\n    by (rule SUP_subset_mono) simp\nqed\n\ntext \\<open>\n  A lower bound for the chromatic number of a graph can be given in terms of\n  the independence number\n\\<close>\nlemma chromatic_lb:\n  assumes wf_G: \"uwellformed G\"\n    and fin_G: \"finite (uverts G)\"\n    and neG: \"uverts G \\<noteq> {}\"\n  shows \"card (uverts G) / \\<alpha> G \\<le> chromatic_number G\"\nproof -\n  from wf_G have \"(\\<lambda>v. {v}) ` uverts G \\<in> vertex_colorings G\"\n    by (auto simp: vertex_colorings_def uwellformed_def)\n  then have \"chromatic_number G \\<noteq> top\"\n    by (simp add: chromatic_number_def) (auto simp: top_enat_def)\n  then obtain vc where vc_vc: \"vc \\<in> vertex_colorings G\"\n    and vc_size:\"chromatic_number G = card vc\"\n    unfolding chromatic_number_def by (rule enat_in_INF)\n\n  have fin_vc_elems: \"\\<And>c. c \\<in> vc \\<Longrightarrow> finite c\"\n    using vc_vc by (intro finite_subset[OF _ fin_G]) (auto simp: vertex_colorings_def)\n\n  have sum_vc_card: \"(\\<Sum>c \\<in> vc. card c) = card (uverts G)\"\n      using fin_vc_elems vc_vc unfolding vertex_colorings_def\n      by (simp add: card_Union_disjoint[symmetric] pairwise_def disjnt_def)\n\n  have \"\\<And>c. c \\<in> vc \\<Longrightarrow> c \\<in> independent_sets G\"\n    using vc_vc by (auto simp: vertex_colorings_def independent_sets_def all_edges_def)\n  then have \"\\<And>c. c \\<in> vc \\<Longrightarrow> card c \\<le> \\<alpha> G\"\n    using vc_vc fin_vc_elems by (subst le_\\<alpha>_iff) (auto simp add: vertex_colorings_def)\n  then have \"(\\<Sum>c\\<in>vc. card c) \\<le> card vc * \\<alpha> G\"\n    using sum_bounded_above[of vc card \"\\<alpha> G\"]\n    by (simp add: of_nat_eq_enat[symmetric] of_nat_sum)\n  then have \"ereal_of_enat (card (uverts G)) \\<le> ereal_of_enat (\\<alpha> G) * ereal_of_enat (card vc)\"\n    by (simp add: sum_vc_card ereal_of_enat_pushout ac_simps del: ereal_of_enat_simps)\n  with zero_less_\\<alpha>[OF neG] \\<alpha>_fin[OF fin_G] vc_size show ?thesis\n    by (simp add: ereal_divide_le_pos)\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/Girth_Chromatic/Ugraphs.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8688267762381844, "lm_q2_score": 0.8221891392358015, "lm_q1q2_score": 0.7143399393002892}}
{"text": "section \\<open> Derived SI-Units\\<close>\n\ntheory SI_Derived\n  imports SI_Prefix\nbegin                                  \n\nsubsection \\<open> Definitions \\<close>\n\nabbreviation \"newton \\<equiv> kilogram \\<^bold>\\<cdot> metre \\<^bold>\\<cdot> second\\<^sup>-\\<^sup>\\<two>\"\n\ntype_synonym 'a newton = \"'a[M \\<cdot> L \\<cdot> T\\<^sup>-\\<^sup>2, SI]\"\n\nabbreviation \"pascal \\<equiv> kilogram \\<^bold>\\<cdot> metre\\<^sup>-\\<^sup>\\<one> \\<^bold>\\<cdot> second\\<^sup>-\\<^sup>\\<two>\"\n\ntype_synonym 'a pascal = \"'a[M \\<cdot> L\\<^sup>-\\<^sup>1 \\<cdot> T\\<^sup>-\\<^sup>2, SI]\"\n\nabbreviation \"volt \\<equiv> kilogram \\<^bold>\\<cdot> metre\\<^sup>\\<two> \\<^bold>\\<cdot> second\\<^sup>-\\<^sup>\\<three> \\<^bold>\\<cdot> ampere\\<^sup>-\\<^sup>\\<one>\"\n\ntype_synonym 'a volt = \"'a[M \\<cdot> L\\<^sup>2 \\<cdot> T\\<^sup>-\\<^sup>3 \\<cdot> I\\<^sup>-\\<^sup>1, SI]\"\n\nabbreviation \"farad \\<equiv> kilogram\\<^sup>-\\<^sup>\\<one> \\<^bold>\\<cdot> metre\\<^sup>-\\<^sup>\\<two> \\<^bold>\\<cdot> second\\<^sup>\\<four> \\<^bold>\\<cdot> ampere\\<^sup>\\<two>\"\n\ntype_synonym 'a farad = \"'a[M\\<^sup>-\\<^sup>1 \\<cdot> L\\<^sup>-\\<^sup>2 \\<cdot> T\\<^sup>4 \\<cdot> I\\<^sup>2, SI]\"\n\nabbreviation \"ohm \\<equiv> kilogram \\<^bold>\\<cdot> metre\\<^sup>\\<two> \\<^bold>\\<cdot> second\\<^sup>-\\<^sup>\\<three> \\<^bold>\\<cdot> ampere\\<^sup>-\\<^sup>\\<two>\"\n\ntype_synonym 'a ohm = \"'a[M \\<cdot> L\\<^sup>2 \\<cdot> T\\<^sup>-\\<^sup>3 \\<cdot> I\\<^sup>-\\<^sup>2, SI]\"\n\nabbreviation \"siemens \\<equiv> kilogram\\<^sup>-\\<^sup>\\<one> \\<^bold>\\<cdot> metre\\<^sup>-\\<^sup>\\<two> \\<^bold>\\<cdot> second\\<^sup>\\<three> \\<^bold>\\<cdot> ampere\\<^sup>\\<two>\"\n\nabbreviation \"weber \\<equiv> kilogram \\<^bold>\\<cdot> metre\\<^sup>\\<two> \\<^bold>\\<cdot> second\\<^sup>-\\<^sup>\\<two> \\<^bold>\\<cdot> ampere\\<^sup>-\\<^sup>\\<one>\"\n\nabbreviation \"tesla \\<equiv> kilogram \\<^bold>\\<cdot> second\\<^sup>-\\<^sup>\\<two> \\<^bold>\\<cdot> ampere\\<^sup>-\\<^sup>\\<one>\"\n\nabbreviation \"henry \\<equiv> kilogram \\<^bold>\\<cdot> metre\\<^sup>\\<two> \\<^bold>\\<cdot> second\\<^sup>-\\<^sup>\\<two> \\<^bold>\\<cdot> ampere\\<^sup>-\\<^sup>\\<two>\"\n\nabbreviation \"lux \\<equiv> candela \\<^bold>\\<cdot> steradian \\<^bold>\\<cdot> metre\\<^sup>-\\<^sup>\\<two>\"\n\nabbreviation (input) \"becquerel \\<equiv> second\\<^sup>-\\<^sup>\\<one>\"\n\nabbreviation \"gray \\<equiv> metre\\<^sup>\\<two> \\<^bold>\\<cdot> second\\<^sup>-\\<^sup>\\<two>\"\n\nabbreviation \"sievert \\<equiv> metre\\<^sup>\\<two> \\<^bold>\\<cdot> second\\<^sup>-\\<^sup>\\<two>\"\n\nabbreviation \"katal \\<equiv> mole \\<^bold>\\<cdot> second\\<^sup>-\\<^sup>\\<one>\"\n\ndefinition degrees_celcius :: \"'a::field_char_0 \\<Rightarrow> 'a[\\<Theta>]\" (\"_\\<degree>C\" [999] 999) \n  where [si_eq]: \"degrees_celcius x = (x *\\<^sub>Q kelvin) + approx_ice_point\"\n\ndefinition [si_eq]: \"gram = milli *\\<^sub>Q kilogram\"\n\nsubsection \\<open> Equivalences \\<close>\n\nlemma joule_alt_def: \"joule \\<cong>\\<^sub>Q newton \\<^bold>\\<cdot> metre\" \n  by si_calc\n\nlemma watt_alt_def: \"watt \\<cong>\\<^sub>Q joule \\<^bold>/ second\"\n  by si_calc\n\nlemma volt_alt_def: \"volt = watt \\<^bold>/ ampere\"\n  by simp\n  \nlemma farad_alt_def: \"farad \\<cong>\\<^sub>Q coulomb \\<^bold>/ volt\"\n  by si_calc\n\n\n\nlemma siemens_alt_def: \"siemens \\<cong>\\<^sub>Q ampere \\<^bold>/ volt\"\n  by si_calc\n\nlemma weber_alt_def: \"weber \\<cong>\\<^sub>Q volt \\<^bold>\\<cdot> second\"\n  by si_calc\n\nlemma tesla_alt_def: \"tesla \\<cong>\\<^sub>Q weber \\<^bold>/ metre\\<^sup>\\<two>\"\n  by si_calc\n\nlemma henry_alt_def: \"henry \\<cong>\\<^sub>Q weber \\<^bold>/ ampere\"\n  by si_calc\n\nlemma lux_alt_def: \"lux = lumen \\<^bold>/ metre\\<^sup>\\<two>\"\n  by simp\n\nlemma gray_alt_def: \"gray \\<cong>\\<^sub>Q joule \\<^bold>/ kilogram\"\n  by si_calc\n\nlemma sievert_alt_def: \"sievert \\<cong>\\<^sub>Q joule \\<^bold>/ kilogram\"\n  by si_calc\n\nsubsection \\<open> Properties \\<close>\n\nlemma kilogram: \"kilo *\\<^sub>Q gram = kilogram\"\n  by (si_simp)\n\nlemma celcius_to_kelvin: \"T\\<degree>C = (T *\\<^sub>Q kelvin) + (273.15 *\\<^sub>Q kelvin)\"\n  by (si_simp)\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/SI_Derived.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297861178929, "lm_q2_score": 0.793105951184112, "lm_q1q2_score": 0.7142155325886563}}
{"text": "theory CFG\nimports Main\nbegin\n\ntypedecl symbol\n\ntype_synonym rule = \"symbol \\<times> symbol list\"\n\ntype_synonym sentence = \"symbol list\"\n\nlocale CFG =\n  fixes \\<NN> :: \"symbol set\"\n  fixes \\<TT> :: \"symbol set\"\n  fixes \\<RR> :: \"rule set\"\n  fixes \\<SS> :: \"symbol\"\n  assumes disjunct_symbols: \"\\<NN> \\<inter> \\<TT> = {}\"\n  assumes startsymbol_dom: \"\\<SS> \\<in> \\<NN>\"\n  assumes validRules: \"\\<forall> (N, \\<alpha>) \\<in> \\<RR>. N \\<in> \\<NN> \\<and> (\\<forall> s \\<in> set \\<alpha>. s \\<in> \\<NN> \\<union> \\<TT>)\"\nbegin\n\ndefinition is_terminal :: \"symbol \\<Rightarrow> bool\"\nwhere\n  \"is_terminal s = (s \\<in> \\<TT>)\"\n\ndefinition is_nonterminal :: \"symbol \\<Rightarrow> bool\"\nwhere\n  \"is_nonterminal s = (s \\<in> \\<NN>)\"\n\nlemma is_nonterminal_startsymbol:\"is_nonterminal \\<SS>\"\n  by (simp add: is_nonterminal_def startsymbol_dom)\n\ndefinition is_symbol :: \"symbol \\<Rightarrow> bool\"\nwhere\n  \"is_symbol s = (is_terminal s \\<or> is_nonterminal s)\"\n\ndefinition is_sentence :: \"sentence \\<Rightarrow> bool\"\nwhere\n  \"is_sentence s = list_all is_symbol s\"\n\ndefinition is_word :: \"sentence \\<Rightarrow> bool\"\nwhere\n  \"is_word s = list_all is_terminal s\"\n   \ndefinition derives1 :: \"sentence \\<Rightarrow> sentence \\<Rightarrow> bool\"\nwhere\n  \"derives1 u v = \n     (\\<exists> x y N \\<alpha>. \n          u = x @ [N] @ y\n        \\<and> v = x @ \\<alpha> @ y\n        \\<and> is_sentence x\n        \\<and> is_sentence y\n        \\<and> (N, \\<alpha>) \\<in> \\<RR>)\"  \n\ndefinition derivations1 :: \"(sentence \\<times> sentence) set\"\nwhere\n  \"derivations1 = { (u,v) | u v. derives1 u v }\"\n\ndefinition derivations :: \"(sentence \\<times> sentence) set\"\nwhere \n  \"derivations = derivations1^*\"\n\ndefinition derives :: \"sentence \\<Rightarrow> sentence \\<Rightarrow> bool\"\nwhere\n  \"derives u v = ((u, v) \\<in> derivations)\"\n\ndefinition is_derivation :: \"sentence \\<Rightarrow> bool\"\nwhere\n  \"is_derivation u = derives [\\<SS>] u\"\n\ndefinition \\<L> :: \"sentence set\"\nwhere\n  \"\\<L> = { v | v. is_word v \\<and> is_derivation v}\"\n\ndefinition \"\\<L>\\<^sub>P\"  :: \"sentence set\"\nwhere\n  \"\\<L>\\<^sub>P = { u | u v. is_word u \\<and> is_derivation (u@v) }\"\n\nend\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/LocalLexing/CFG.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297834483232, "lm_q2_score": 0.7931059487389966, "lm_q1q2_score": 0.7142155282695056}}
{"text": "theory Event_Priority\nimports\n  \"Main\"\nbegin\n\ntext \\<open> This theory defines a partial order type. \\<close>\n\nabbreviation less :: \"('e \\<Rightarrow> 'e \\<Rightarrow> bool) \\<Rightarrow> 'e \\<Rightarrow> 'e \\<Rightarrow> bool\" where\n\"less f a b == f a b \\<and> \\<not>(f b a)\"\n\ntext \\<open> Here less is used to satisfy the axiom less_le_not_le of preorders. \\<close>\n\ntypedef 'e partialorder = \"{x :: 'e \\<Rightarrow> 'e \\<Rightarrow> bool. class.order x (less x)}\"\n  morphisms porder2f f2porder\n  apply (simp add:class.order_def class.preorder_def class.order_axioms_def)\n  apply (rule exI[where x=\"(=)\"])\n  by simp\n\ntext \\<open> Thus @{type partialorder} is the type of all partial orders over the\n       given type. \\<close>\n\nthm porder2f_induct\nthm f2porder_inverse\n\ndefinition my_le :: \"'a partialorder \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> bool\" where \"my_le P = (porder2f P)\"\ndefinition my_lt :: \"'a partialorder \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> bool\" where \"my_lt P = (less (my_le P))\"\n\nlemma porder2f_ref: \"porder2f p x x\"\n  apply (induct p)\n  apply (simp add:f2porder_inverse)\n  by (simp add:class.order_def class.preorder_def class.order_axioms_def)\n\ninterpretation partialorder: order \"my_le p\" \"my_lt p\"\n  apply (unfold_locales)\n     apply (auto simp add:my_le_def my_lt_def)\n    apply (induct p, simp add:f2porder_inverse)\n    apply (simp add:class.order_def class.preorder_def class.order_axioms_def)\n   apply (induct p, simp add:f2porder_inverse)\n   apply (simp add:class.order_def class.order_axioms_def)\n   apply (auto simp only:class.preorder_def)\n  apply (induct p, simp add:f2porder_inverse)\n  by (simp add:class.order_def class.order_axioms_def)\n\ntext \\<open> We define the following notation so that the operator \\<le> and < can be parametrised\n       with a specific partial order. \\<close>\n\nsyntax\n  \"_porder_le\"    :: \"'a \\<Rightarrow> 'a partialorder \\<Rightarrow> 'a \\<Rightarrow> bool\" (\"(_/ \\<le>\\<^sup>*_ _)\" [51, 51] 50)\n  \"_porder_lt\"    :: \"'a \\<Rightarrow> 'a partialorder  \\<Rightarrow> 'a \\<Rightarrow> bool\" (\"(_/ <\\<^sup>*_ _)\" [51, 51] 50)\n\ntranslations\n  \"x \\<le>\\<^sup>*p y\" == \"CONST my_le p x y\"\n  \"x <\\<^sup>*p y\" == \"CONST my_lt p x y\"\n\ndefinition maximal :: \"'a partialorder \\<Rightarrow> 'a \\<Rightarrow> bool\" (\"maximal'(_,_')\" 65) where\n\"maximal(p,a) = (\\<forall>x. (\\<not> (a \\<le>\\<^sup>*p x) \\<or> x \\<le>\\<^sup>*p a))\"\n\nlemma some_higher_not_maximal:\n  assumes \"z <\\<^sup>*p b\"\n  shows \"\\<not>maximal(p,z)\"\n  using assms unfolding maximal_def apply auto\n  by (meson partialorder.less_le_not_le)\n\nlemma maximal_iff:\n  \"maximal(p,z) = (\\<not>(\\<exists>x. z <\\<^sup>*p x))\"\n  unfolding maximal_def apply auto\n  by (meson partialorder.less_le_not_le)+\n\nlemma tau_max: \"(\\<forall>x. (x \\<le>\\<^sup>*(p) \\<tau>)) \\<Longrightarrow> \\<not>(\\<exists>x. (\\<tau> <\\<^sup>*(p) x))\"\n  apply auto\n  by (simp add: partialorder.less_le_not_le)\n\nlemma tau_max_imp_any_le_imp_le_tau:\n  assumes \"(\\<forall>x. (x \\<le>\\<^sup>*(p) \\<tau>))\" \"a <\\<^sup>*p b\"\n  shows \"a <\\<^sup>*(p) \\<tau>\"\n  using assms\n  by (metis my_lt_def partialorder.order.not_eq_order_implies_strict)\n\nend", "meta": {"author": "UoY-RoboStar", "repo": "tick-tock-CSP", "sha": "7186d2e7f70116589850112a7353bc521372c913", "save_path": "github-repos/isabelle/UoY-RoboStar-tick-tock-CSP", "path": "github-repos/isabelle/UoY-RoboStar-tick-tock-CSP/tick-tock-CSP-7186d2e7f70116589850112a7353bc521372c913/Utils/Event_Priority.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894661025424, "lm_q2_score": 0.7981867729389246, "lm_q1q2_score": 0.7142091164081316}}
{"text": "theory Isar_Induction_Demo\nimports Main\nbegin\n\nsection \"Case distinction and induction\"\n\nsubsection \"Case distinction\"\n\ntext \\<open>Explicit:\\<close>\n\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\"\n  thus ?thesis by simp\nqed\n\ntext \\<open>Implicit:\\<close>\n\nlemma \"length(tl xs) = length xs - 1\"\nproof (cases xs)\n  case Nil\nthm Nil\n  thus ?thesis by simp\nnext\n  case (Cons y ys)\nthm Cons\n  thus ?thesis by simp\nqed\n\n\nsubsection \\<open>Structural induction for type @{typ nat}\\<close>\n\ntext \\<open>Explicit:\\<close>\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\ntext \\<open>In more detail:\\<close>\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 IH: \"?P n\"\n  have \"\\<Sum>{0..Suc n} = \\<Sum>{0..n} + Suc n\" by simp\n  also have \"\\<dots> = n*(n+1) div 2 + Suc n\" using IH by simp\n  also have \"\\<dots> = (Suc n)*((Suc n)+1) div 2\" by simp\n  finally show \"?P(Suc n)\" .\nqed\n\ntext \\<open>Implicit:\\<close>\n\nlemma \"\\<Sum>{0..n::nat} = n*(n+1) div 2\"\nproof (induction n)\n  case 0\n  show ?case by simp\nnext\n  case (Suc n)\nthm Suc\n  thus ?case by simp\nqed\n\ntext \\<open>Induction with \\<open>\\<Longrightarrow>\\<close>:\\<close>\n\nlemma split_list: \"x : set xs \\<Longrightarrow> \\<exists>ys zs. xs = ys @ x # zs\"\nproof (induction xs)\n  case Nil thus ?case by simp\nnext\n  case (Cons a xs)\nthm Cons.IH (* Induction hypothesis *)\nthm Cons.prems (* Premises of the step case *)\nthm Cons\n  from Cons.prems have \"x = a \\<or> x : set xs\" by simp\n  thus ?case\n  proof\n    assume \"x = a\"\n    hence \"a#xs = [] @ x # xs\" by simp\n    thus ?thesis by blast\n  next\n    assume \"x : set xs\"\n    then obtain ys zs where \"xs = ys @ x # zs\" using Cons.IH by auto\n    hence \"a#xs = (a#ys) @ x # zs\" by simp\n    thus ?thesis by blast\n  qed\nqed\n\n\nsubsection \"Computation induction\"\n\nfun div2 :: \"nat \\<Rightarrow> nat\" where\n\"div2 0 = 0\" |\n\"div2 (Suc 0) = 0\" |\n\"div2 (Suc(Suc n)) = div2 n + 1\"\n\nlemma \"2 * div2 n \\<le> n\"\nproof(induction n rule: div2.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 \"2 * div2 (Suc(Suc n)) = 2 * div2 n + 2\" by simp\n  also have \"\\<dots> \\<le> n + 2\" using \"3.IH\" by simp\n  also have \"\\<dots> = Suc(Suc n)\" by simp\n  finally show ?case .\nqed\n\ntext \\<open>Note that \\<open>3.IH\\<close> is not a valid name, it needs double quotes: \\<open>\"3.IH\"\\<close>.\\<close>\n\n\nfun sep :: \"'a \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where\n\"sep a (x # y # zs) = x # a # sep a (y # zs)\" |\n\"sep a xs = xs\"\n\nthm sep.simps\n\nlemma \"map f (sep a xs) = sep (f a) (map f xs)\"\nproof (induction a xs rule: sep.induct)\n  case (1 a x y zs)\n  thus ?case by simp\nnext\n  case (\"2_1\" a)\n  show ?case by simp\nnext\n  case (\"2_2\" a v)\n  show ?case by simp\nqed\n\n\n\nsubsection \"Rule induction\"\n\n\ninductive ev :: \"nat => bool\" where\nev0:  \"ev 0\" |\nevSS:  \"ev n \\<Longrightarrow> ev(Suc(Suc n))\"\n\ndeclare ev.intros [simp]\n\n\nlemma \"ev n \\<Longrightarrow> \\<exists>k. n = 2*k\"\nproof (induction rule: ev.induct)\n  case ev0 show ?case by simp\nnext\n  case evSS thus ?case by arith\nqed\n\n\nlemma \"ev n \\<Longrightarrow> \\<exists>k. n = 2*k\"\nproof (induction rule: ev.induct)\n  case ev0 show ?case by simp\nnext\n  case (evSS m)\nthm evSS\nthm evSS.IH\nthm evSS.hyps\n  from evSS.IH obtain k where \"m = 2*k\" by blast\n  hence \"Suc(Suc m) = 2*(k+1)\" by simp\n  thus \"\\<exists>k. Suc(Suc m) = 2*k\" by blast\nqed\n\n\nsubsection \"Inductive definition of the reflexive transitive closure\"\n\nconsts step :: \"'a \\<Rightarrow> 'a \\<Rightarrow> bool\" (infix \"\\<rightarrow>\" 55)\n\ninductive steps :: \"'a \\<Rightarrow> 'a \\<Rightarrow> bool\" (infix \"\\<rightarrow>*\" 55) where\nrefl: \"x \\<rightarrow>* x\" |\nstep: \"\\<lbrakk> x \\<rightarrow> y; y \\<rightarrow>* z \\<rbrakk> \\<Longrightarrow> x \\<rightarrow>* z\"\n\ndeclare refl[simp, intro]\n\ntext \"Explicit and by hand:\"\n\nlemma \"x \\<rightarrow>* y  \\<Longrightarrow>  y \\<rightarrow>* z \\<Longrightarrow> x \\<rightarrow>* z\"\nproof(induction rule: steps.induct)\n  fix x assume \"x \\<rightarrow>* z\"\n  thus \"x \\<rightarrow>* z\" . (* by assumption *)\nnext\n  fix x' x y :: 'a\n  assume \"x' \\<rightarrow> x\" and \"x \\<rightarrow>* y\"\n  assume IH: \"y \\<rightarrow>* z \\<Longrightarrow> x \\<rightarrow>* z\"\n  assume \"y \\<rightarrow>* z\"\n  show \"x' \\<rightarrow>* z\" by(rule step[OF `x' \\<rightarrow> x` IH[OF `y\\<rightarrow>*z`]])\nqed\n\ntext \\<open>Implicit and automatic:\\<close>\n\nlemma \"x \\<rightarrow>* y  \\<Longrightarrow>  y \\<rightarrow>* z \\<Longrightarrow> x \\<rightarrow>* z\"\nproof(induction rule: steps.induct)\n  case refl thus ?case .\nnext\n  case (step x' x y)\n  (* x' x y not used in proof text, just for demo *)\nthm step\nthm step.IH\nthm step.hyps\nthm step.prems\n  show ?case\n    by (metis step.hyps(1) step.IH step.prems steps.step)\nqed\n\n\nsubsection \"Rule inversion\"\n\n\nlemma assumes \"ev n\" shows \"ev(n - 2)\"\nproof-\n  from `ev n` show \"ev(n - 2)\"\n  proof cases\n    case ev0\nthm ev0\n    then show ?thesis by simp\n  next\n    case (evSS k)\nthm evSS\n    then show ?thesis by simp\n  qed\nqed\n\n\ntext \\<open>Impossible cases are proved automatically:\\<close>\n\nlemma \"\\<not> ev(Suc 0)\"\nproof\n  assume \"ev(Suc 0)\"\n  then show False\n  proof cases\n  qed\nqed\n\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/Isar_Induction_Demo.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396211, "lm_q2_score": 0.8947894541786198, "lm_q1q2_score": 0.7142091111862269}}
{"text": "(*<*)\ntheory CNF\n  imports Main\nbegin\n(*>*)\n\n\ndatatype 'a formula = \n  is_Atom: Atom \"'a\"\n  | is_Neg: Neg \"'a formula\" \n  | is_Disj: Or \"'a formula\" \"'a formula\" \n  | is_Conj: And \"'a formula\" \"'a formula\"\n\nprimrec sat :: \"('a \\<Rightarrow> bool) \\<Rightarrow> 'a formula \\<Rightarrow> bool\"\n  where \"sat v (Atom p) = v p\"\n  | \"sat v (Neg \\<phi>) = (\\<not> sat v \\<phi>)\"\n  | \"sat v (Or \\<phi> \\<psi>) = (sat v \\<phi> \\<or> sat v \\<psi>)\"\n  | \"sat v (And \\<phi> \\<psi>) = (sat v \\<phi> \\<and> sat v \\<psi>)\"\n\nprimrec subformula :: \"'a formula \\<Rightarrow> 'a formula \\<Rightarrow> bool\"\n  where \"subformula \\<phi> (Atom p) = (\\<phi> = Atom p)\"\n  | \"subformula \\<phi> (Neg \\<psi>) = (\\<phi> = Neg \\<psi> \\<or> subformula \\<phi> \\<psi>)\"\n  | \"subformula \\<phi> (Or \\<psi> \\<gamma>) = (\\<phi> = Or \\<psi> \\<gamma> \\<or> subformula \\<phi> \\<psi> \\<or> subformula \\<phi> \\<gamma>)\"\n  | \"subformula \\<phi> (And \\<psi> \\<gamma>) = (\\<phi> = And \\<psi> \\<gamma> \\<or> subformula \\<phi> \\<psi> \\<or> subformula \\<phi> \\<gamma>)\"\n\nbundle syntax_no_notation\nbegin\n\nno_notation Atom (\"@\\<^sub>F_\" [85] 85)\n     and formula.Neg (\"\\<not>\\<^sub>F _\" [82] 82)\n     and formula.And (infixr \"\\<and>\\<^sub>F\" 80)\n     and formula.Or (infixr \"\\<or>\\<^sub>F\" 80)\n     and sat (\"_ \\<Turnstile> _\" [55, 55] 55)\n\nend\n\n\nbundle syntax_notation\nbegin\n\nnotation Atom (\"@\\<^sub>F_\" [85] 85)\n     and formula.Neg (\"\\<not>\\<^sub>F _\" [82] 82)\n     and formula.And (infixr \"\\<and>\\<^sub>F\" 80)\n     and formula.Or (infixr \"\\<or>\\<^sub>F\" 80)\n     and sat (\"_ \\<Turnstile> _\" [55, 55] 55)\n\nend\n\nunbundle syntax_notation\n\nfun is_literal :: \"'a formula \\<Rightarrow> bool\"\n  where \"is_literal (@\\<^sub>F p) = True\"\n  | \"is_literal (\\<not>\\<^sub>F (@\\<^sub>F p)) = True\"\n  | \"is_literal _ = False\"\n\nlemma is_literal_iff: \"is_literal \\<phi> \\<longleftrightarrow> (\\<exists>p. \\<phi> = @\\<^sub>F p \\<or> \\<phi> = \\<not>\\<^sub>F @\\<^sub>F p)\"\n  by (cases \\<phi> rule: is_literal.cases, simp_all)\n\nlemma is_literal_NegD: \"is_literal (\\<not>\\<^sub>F \\<phi>) \\<Longrightarrow> \\<exists>p. \\<phi> = @\\<^sub>F p\"\n  by (clarsimp simp: is_literal_iff)\n\nprimrec is_clause :: \"'a formula \\<Rightarrow> bool\"\n  where \"is_clause (@\\<^sub>F p) = True\"\n  | \"is_clause (\\<not>\\<^sub>F \\<phi>) = is_literal (\\<not>\\<^sub>F \\<phi>)\"\n  | \"is_clause (\\<phi> \\<or>\\<^sub>F \\<psi>) = (is_clause \\<phi> \\<and> is_clause \\<psi>)\"\n  | \"is_clause (\\<phi> \\<and>\\<^sub>F \\<psi>) = False\"\n\nlemma is_clause_iff_rec: \n  \"is_clause \\<phi> \\<longleftrightarrow> (is_literal \\<phi> \\<or> (\\<exists>\\<psi> \\<gamma>. is_clause \\<psi> \\<and> is_clause \\<gamma> \\<and> \\<phi> = \\<psi> \\<or>\\<^sub>F \\<gamma>))\"\n  by (induct \\<phi>, simp_all)\n\nfun is_CNF :: \"'a formula \\<Rightarrow> bool\"\n  where \"is_CNF (@\\<^sub>F p) = True\"\n  | \"is_CNF (\\<not>\\<^sub>F (@\\<^sub>F p)) = True\"\n  | \"is_CNF (\\<not>\\<^sub>F \\<phi>) = False\"\n  | \"is_CNF (\\<phi> \\<or>\\<^sub>F \\<psi>) = (is_clause \\<phi> \\<and> is_clause \\<psi>)\"\n  | \"is_CNF (\\<phi> \\<and>\\<^sub>F \\<psi>) = (is_CNF \\<phi> \\<and> is_CNF \\<psi>)\"\n\nlemma is_CNF_iff_rec: \n  \"is_CNF \\<phi> \\<longleftrightarrow> (is_clause \\<phi> \\<or> (\\<exists>\\<psi> \\<gamma>. is_CNF \\<psi> \\<and> is_CNF \\<gamma> \\<and> \\<phi> = \\<psi> \\<and>\\<^sub>F \\<gamma>))\"\n  by (induct \\<phi> rule: is_CNF.induct, simp_all)\n\nlemmas is_CNFD = iffD1[OF is_CNF_iff_rec] \n  and is_CNFI = iffD2[OF is_CNF_iff_rec]\n\nlemma clause_is_CNF: \"is_clause \\<phi> \\<Longrightarrow> is_CNF \\<phi>\"\n  by (induct \\<phi> rule: is_CNF.induct, auto)\n\nlemma is_CNF_NegD: \"is_CNF (\\<not>\\<^sub>F \\<phi>) \\<Longrightarrow> \\<exists>p. \\<phi> = @\\<^sub>F p\"\n  by (cases \\<phi> rule: is_CNF.cases, simp_all)\n\nfun push_neg :: \"'a formula \\<Rightarrow> 'a formula\"\n  where \"push_neg (@\\<^sub>F p) = @\\<^sub>F p\"\n  | \"push_neg (\\<not>\\<^sub>F (@\\<^sub>F p)) = \\<not>\\<^sub>F (@\\<^sub>F p)\"\n  | \"push_neg (\\<not>\\<^sub>F (\\<not>\\<^sub>F \\<phi>)) = push_neg \\<phi>\"\n  | \"push_neg (\\<not>\\<^sub>F (\\<phi> \\<or>\\<^sub>F \\<psi>)) = (push_neg (\\<not>\\<^sub>F \\<phi>)) \\<and>\\<^sub>F (push_neg (\\<not>\\<^sub>F \\<psi>))\"\n  | \"push_neg (\\<not>\\<^sub>F (\\<phi> \\<and>\\<^sub>F \\<psi>)) = (push_neg (\\<not>\\<^sub>F \\<phi>)) \\<or>\\<^sub>F (push_neg (\\<not>\\<^sub>F \\<psi>))\"\n  | \"push_neg (\\<phi> \\<or>\\<^sub>F \\<psi>) = (push_neg \\<phi>) \\<or>\\<^sub>F (push_neg \\<psi>)\"\n  | \"push_neg (\\<phi> \\<and>\\<^sub>F \\<psi>) = (push_neg \\<phi>) \\<and>\\<^sub>F (push_neg \\<psi>)\"\n\nlemma sat_push_neg_iff: \"v \\<Turnstile> push_neg \\<phi> \\<longleftrightarrow> v \\<Turnstile> \\<phi>\"\n  by (induct \\<phi> rule: push_neg.induct, simp_all)\n\nlemma NNF_push_neg: \n  \"subformula \\<psi> (push_neg \\<phi>) \\<Longrightarrow> is_Neg \\<psi> \\<Longrightarrow> is_literal \\<psi>\"\n  by (induct \\<phi> rule: push_neg.induct)\n    (auto simp add: is_literal_iff)\n\nfun distrib_law :: \"'a formula \\<Rightarrow> 'a formula \\<Rightarrow> 'a formula\"\n  where \"distrib_law \\<phi> \\<psi> = \n    (case \\<phi> of \n      \\<phi>\\<^sub>1 \\<and>\\<^sub>F \\<phi>\\<^sub>2 \\<Rightarrow> (distrib_law \\<phi>\\<^sub>1 \\<psi>) \\<and>\\<^sub>F (distrib_law \\<phi>\\<^sub>2 \\<psi>)\n      | _ \\<Rightarrow> (case \\<psi> of \n          \\<psi>\\<^sub>1 \\<and>\\<^sub>F \\<psi>\\<^sub>2 \\<Rightarrow> (distrib_law \\<phi> \\<psi>\\<^sub>1) \\<and>\\<^sub>F (distrib_law \\<phi> \\<psi>\\<^sub>2)\n          | _ \\<Rightarrow> \\<phi> \\<or>\\<^sub>F \\<psi>))\"\n\nlemma distrib_law__clauses:\n  assumes \"is_clause \\<phi>\"\n    and \"is_clause \\<psi>\"\n  shows \"is_clause (distrib_law \\<phi> \\<psi>)\"\n  using assms \n  by - (induct \\<phi>; induct \\<psi>; force simp add: is_literal_iff)\n\nlemma distrib_law_CNF_clause:\n  assumes \"is_CNF \\<phi>\"\n    and \"is_clause \\<psi>\"\n  shows \"is_CNF (distrib_law \\<phi> \\<psi>)\"\n    and \"is_CNF (distrib_law \\<psi> \\<phi>)\"\n  using assms \n  by - (induct \\<phi>; induct \\<psi>; force simp add: is_literal_iff dest: is_CNF_NegD)+\n\nlemma is_CNF_distrib_law:\n  assumes \"is_CNF \\<phi>\"\n    and \"is_CNF \\<psi>\"\n  shows \"is_CNF (distrib_law \\<phi> \\<psi>)\"\n  using assms\n  by (induct \\<phi>; induct \\<psi>; clarsimp simp add: is_literal_iff dest!: is_CNF_NegD)\n    (metis distrib_law.simps distrib_law_CNF_clause(2))\n\nlemma sat_distrib_law1: \n  \"is_clause \\<phi> \\<Longrightarrow> is_clause \\<psi> \\<Longrightarrow> v \\<Turnstile> distrib_law \\<phi> \\<psi> \\<longleftrightarrow> v \\<Turnstile> \\<phi> \\<or>\\<^sub>F \\<psi>\"\n  by (induct \\<phi>; induct \\<psi>; clarsimp)\n\nlemma sat_distrib_law2: \n  \"is_clause \\<phi> \\<Longrightarrow> is_CNF \\<psi> \\<Longrightarrow> \\<psi> = \\<psi>\\<^sub>1 \\<and>\\<^sub>F \\<psi>\\<^sub>2 \\<Longrightarrow> v \\<Turnstile> distrib_law \\<phi> \\<psi> \\<longleftrightarrow> v \\<Turnstile> (\\<phi> \\<or>\\<^sub>F \\<psi>\\<^sub>1) \\<and>\\<^sub>F (\\<phi> \\<or>\\<^sub>F \\<psi>\\<^sub>2)\"\n  apply (induct \\<phi>; induct \\<psi> arbitrary: \\<psi>\\<^sub>1 \\<psi>\\<^sub>2; clarsimp simp: is_literal_iff)\n  oops\n\nfun to_CNF :: \"'a formula \\<Rightarrow> 'a formula\"\n  where \"to_CNF (\\<phi> \\<and>\\<^sub>F \\<psi>) = to_CNF \\<phi> \\<and>\\<^sub>F to_CNF \\<psi>\"\n  | \"to_CNF (\\<phi> \\<or>\\<^sub>F \\<psi>) = distrib_law (to_CNF \\<phi>) (to_CNF \\<psi>)\"\n  | \"to_CNF \\<phi> = \\<phi>\"\n\nlemma \"is_CNF (to_CNF (push_neg \\<phi>))\"\n  by (induct \\<phi> rule: push_neg.induct)\n    (simp_all add: is_CNF_distrib_law \n      del: distrib_law.simps)\n\nvalue \"is_CNF (\\<not>\\<^sub>F ((@\\<^sub>Fp \\<and>\\<^sub>F @\\<^sub>Fq) \\<and>\\<^sub>F \\<not>\\<^sub>F @\\<^sub>Fr))\"\n\nvalue \"to_CNF (push_neg (\\<not>\\<^sub>F ((@\\<^sub>Fp \\<and>\\<^sub>F @\\<^sub>Fq) \\<and>\\<^sub>F \\<not>\\<^sub>F @\\<^sub>Fr)))\"\n\n\n\n(*>*)\nend\n(*<*)\n", "meta": {"author": "yonoteam", "repo": "ipampa", "sha": "5a83501028edae82353ef3bdfdf7611f6449745b", "save_path": "github-repos/isabelle/yonoteam-ipampa", "path": "github-repos/isabelle/yonoteam-ipampa/ipampa-5a83501028edae82353ef3bdfdf7611f6449745b/CNF.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894576856561, "lm_q2_score": 0.7981867705385763, "lm_q1q2_score": 0.7142091075420779}}
{"text": "(*<*)\n\ntheory FOL\nimports Main\n\nbegin\n\n(*>*)\n\nsection {* Quantifier Rules in Action *}\n\n\ntext{* Here is one version of \n       the first example proof from the lecture on predicate logic *}\n\nlemma \"(\\<forall>x. P x) \\<longrightarrow> (\\<exists>y. P y)\"  \n  apply (rule impI)\n  apply (frule_tac x=a in spec)\n  apply (rule_tac x=a in exI)\n  by assumption\n\ntext {* This proof is rather unusual in that in the second step, it is\n  sufficient to instantiate the universally quantified hypothesis with a new\n  variable `a' which is unconstrained by any formulas in the sequent.\n\n  More commonly we instantiate formulas with terms built with free\n  variables already present in the sequent.  See the next couple of\n  proofs. *}\n\n\ntext{* Here is the 2nd example proof from Lecture 5, with some\nrenaming of bound variables to make the formulas and proofs a little\nclearer. This shows use of left and right forall introduction rules. *}\n\nlemma \"(\\<forall>u. P u \\<longrightarrow> Q u) \\<and> (\\<forall>v. P v) \\<longrightarrow> (\\<forall>w. Q w)\"\n  apply (rule impI)\n  apply (erule conjE)\n  apply (rule allI)  \n  apply (erule_tac x=\"w\" in allE)\n  apply (erule_tac x=\"w\" in allE)\n  apply (erule impE)\n  by assumption+\n\n\ntext {* An example showing use of left and right exists introduction rules *}\n\nlemma \" (\\<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\ntext {* Here's a variation on the classical exists right introduction\nrule exCI in the Isabelle library.  The advantage of this one is that\nit doesn't introduce meta-variables into the sequent. *}\n\nlemma exCIF: \"((\\<forall>x. \\<not>(P x)) \\<Longrightarrow> False) \\<Longrightarrow> \\<exists>x. P x\"\nby auto\n\n\ntext {* An example of the use of exCIF *}\n\nlemma \"\\<not>( \\<not> P a \\<and> \\<not> P b) \\<longrightarrow> (\\<exists>z. P z)\"\napply (rule impI)\napply (rule exCIF)\napply (erule notE)\napply (rule conjI)\napply (erule_tac x=\"a\" in allE)\napply assumption\napply (erule_tac x=\"b\" in allE)\napply assumption\ndone\n\nsection {* Cheaters are losers *}\n\nlemma Cheaters:\n  \"\\<lbrakk>(\\<exists>x. cheats x) \\<longrightarrow> (\\<forall>x. loses x);\n    (\\<forall>x. cheats x \\<longrightarrow> loses x) \\<longrightarrow> loses me\\<rbrakk> \\<Longrightarrow> loses me\"\napply (erule mp)      (* View mp rule as special left intro rule for implies*)\napply (rule allI)\napply (rule impI)     (* From here on, is little choice in next rules *)\napply (erule impE)\napply (rule_tac x=\"x\" in exI)\napply assumption\napply (erule_tac x=\"x\" in allE)\napply assumption\ndone\n\nsection {* Use of meta-variables in Isabelle goals *}\n\ntext{* Meta-variables (also called schematic-variables in the Isabelle\ndocumentation) in goals can be considered to be existentially\nquantified at the sequent level.  As a proof proceeds, the proof is\nfree to substitute in more specialised terms for the meta-variables.\n\nOften, the unification that happens when rules are applied will find\nthe needed meta-variable instantiations.  This saves having to enter\ninstantiating terms explicitly.  However using meta-variables in goals\nand instantiating them with unification can be rather confusing when\nfirst starting out.  All the Isabelle exercises and coursework can be\naccomplished without exploiting them.\n\nBelow are some examples of proofs involving meta-variables.  \n*}\n\n\n\ntext {* Example 1 again *}\n\nlemma \"(\\<forall>x. P x) \\<longrightarrow> (\\<exists>y. P y)\"\n  apply (rule impI)\n  apply (rule exI)\n  apply (drule spec)\n  apply assumption\ndone\n\ntext {* Example II again.  Here the meta-variables introduced are\nactually functions taking as argument a variable universally\nmeta-quantified at the sequent level.  This indicates that any\ninstantiating term for the meta-variables can make use of the\nuniversally quantified variable.  *}\n\nlemma \"(\\<forall>x. P x \\<longrightarrow> Q x) \\<and> (\\<forall>x. P x) \\<longrightarrow> (\\<forall>x. Q x)\"\n  apply (rule impI)\n  apply (erule conjE)\n  apply (rule allI)  \n  apply (erule allE)\n  apply (erule allE)\n  apply (erule mp)\n  by assumption\n\ntext {* The example again of how existential quantification\ndistributes over conjunction.  Once you have stepped through the\nproof, try doing it again with the order of the exE and exI rules\nswapped.  Why does the proof fail? *}\n\nlemma \" (\\<exists>z. P z) \\<and> Q \\<longrightarrow> (\\<exists>y. P y \\<and> Q)\"\napply (rule impI)\napply (erule conjE)\napply (erule exE)\napply (rule exI)\napply (rule conjI)\napply assumption+\ndone\n\n  \nend\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/FOL.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388040954683, "lm_q2_score": 0.86153820232079, "lm_q1q2_score": 0.7141624471143553}}
{"text": "section \\<open> Unrestriction \\<close>\n\ntheory utp_unrest\n  imports utp_expr_insts\nbegin\n\nsubsection \\<open> Definitions and Core Syntax \\<close>\n  \ntext \\<open> Unrestriction is an encoding of semantic freshness that allows us to reason about the\n  presence of variables in predicates without being concerned with abstract syntax trees.\n  An expression $p$ is unrestricted by lens $x$, written $x \\mathop{\\sharp} p$, if\n  altering the value of $x$ has no effect on the valuation of $p$. This is a sufficient\n  notion to prove many laws that would ordinarily rely on an \\emph{fv} function. \n\n  Unrestriction was first defined in the work of Marcel Oliveira~\\cite{Oliveira2005-PHD,Oliveira07} in his\n  UTP mechanisation in \\emph{ProofPowerZ}. Our definition modifies his in that our variables\n  are semantically characterised as lenses, and supported by the lens laws, rather than named \n  syntactic entities. We effectively fuse the ideas from both Feliachi~\\cite{Feliachi2010} and \n  Oliveira's~\\cite{Oliveira07} mechanisations of the UTP, the former being also purely semantic\n  in nature.\n\n  We first set up overloaded syntax for unrestriction, as several concepts will have this\n  defined. \\<close>\n\nconsts\n  unrest :: \"'a \\<Rightarrow> 'b \\<Rightarrow> bool\"\n\nsyntax\n  \"_unrest\" :: \"salpha \\<Rightarrow> logic \\<Rightarrow> logic \\<Rightarrow> logic\" (infix \"\\<sharp>\" 20)\n\ntranslations\n  \"_unrest x p\" == \"CONST unrest x p\"                                           \n  \"_unrest (_salphaset (_salphamk (x +\\<^sub>L y))) P\"  <= \"_unrest (x +\\<^sub>L y) P\"\n\ntext \\<open> Our syntax translations support both variables and variable sets such that we can write down \n  predicates like @{term \"&x \\<sharp> P\"} and also @{term \"{&x,&y,&z} \\<sharp> P\"}. \n\n  We set up a simple tactic for discharging unrestriction conjectures using a simplification set. \\<close>\n  \nnamed_theorems unrest\nmethod unrest_tac = (simp add: unrest)?\n\ntext \\<open> Unrestriction for expressions is defined as a lifted construct using the underlying lens\n  operations. It states that lens $x$ is unrestricted by expression $e$ provided that, for any\n  state-space binding $b$ and variable valuation $v$, the value which the expression evaluates\n  to is unaltered if we set $x$ to $v$ in $b$. In other words, we cannot effect the behaviour\n  of $e$ by changing $x$. Thus $e$ does not observe the portion of state-space characterised\n  by $x$. We add this definition to our overloaded constant. \\<close>\n  \nlift_definition unrest_uexpr :: \"('a \\<Longrightarrow> '\\<alpha>) \\<Rightarrow> ('b, '\\<alpha>) uexpr \\<Rightarrow> bool\"\nis \"\\<lambda> x e. \\<forall> b v. e (put\\<^bsub>x\\<^esub> b v) = e b\" .\n\nadhoc_overloading\n  unrest unrest_uexpr\n\nlemma unrest_expr_alt_def:\n  \"weak_lens x \\<Longrightarrow> (x \\<sharp> P) = (\\<forall> b b'. \\<lbrakk>P\\<rbrakk>\\<^sub>e (b \\<oplus>\\<^sub>L b' on x) = \\<lbrakk>P\\<rbrakk>\\<^sub>e b)\"\n  by (transfer, metis lens_override_def weak_lens.put_get)\n  \nsubsection \\<open> Unrestriction laws \\<close>\n  \ntext \\<open> We now prove unrestriction laws for the key constructs of our expression model. Many\n  of these depend on lens properties and so variously employ the assumptions @{term mwb_lens} and\n  @{term vwb_lens}, depending on the number of assumptions from the lenses theory is required.\n\n  Firstly, we prove a general property -- if $x$ and $y$ are both unrestricted in $P$, then their composition\n  is also unrestricted in $P$. One can interpret the composition here as a union -- if the two sets\n  of variables $x$ and $y$ are unrestricted, then so is their union. \\<close>\n  \nlemma unrest_var_comp [unrest]:\n  \"\\<lbrakk> x \\<sharp> P; y \\<sharp> P \\<rbrakk> \\<Longrightarrow> x;y \\<sharp> P\"\n  by (transfer, simp add: lens_defs)\n\nlemma unrest_svar [unrest]: \"(&x \\<sharp> P) \\<longleftrightarrow> (x \\<sharp> P)\"\n  by (transfer, simp add: lens_defs)\n\nlemma unrest_lens_comp [unrest]: \"x \\<sharp> e \\<Longrightarrow> x:y \\<sharp> e\"\n  by (simp add: lens_comp_def unrest_uexpr.rep_eq)\n\ntext \\<open> No lens is restricted by a literal, since it returns the same value for any state binding. \\<close>\n    \nlemma unrest_lit [unrest]: \"x \\<sharp> \\<guillemotleft>v\\<guillemotright>\"\n  by (transfer, simp)\n\ntext \\<open> If one lens is smaller than another, then any unrestriction on the larger lens implies\n  unrestriction on the smaller. \\<close>\n    \nlemma unrest_sublens:\n  fixes P :: \"('a, '\\<alpha>) uexpr\"\n  assumes \"x \\<sharp> P\" \"y \\<subseteq>\\<^sub>L x\"\n  shows \"y \\<sharp> P\" \n  using assms\n  by (transfer, metis (no_types, lifting) lens.select_convs(2) lens_comp_def sublens_def)\n    \ntext \\<open> If two lenses are equivalent, and thus they characterise the same state-space regions,\n  then clearly unrestrictions over them are equivalent. \\<close>\n    \nlemma unrest_equiv:\n  fixes P :: \"('a, '\\<alpha>) uexpr\"\n  assumes \"mwb_lens y\" \"x \\<approx>\\<^sub>L y\" \"x \\<sharp> P\"\n  shows \"y \\<sharp> P\"\n  by (metis assms lens_equiv_def sublens_pres_mwb sublens_put_put unrest_uexpr.rep_eq)\n\ntext \\<open> If we can show that an expression is unrestricted on a bijective lens, then is unrestricted\n  on the entire state-space. \\<close>\n\nlemma bij_lens_unrest_all:\n  fixes P :: \"('a, '\\<alpha>) uexpr\"\n  assumes \"bij_lens X\" \"X \\<sharp> P\"\n  shows \"\\<Sigma> \\<sharp> P\"\n  using assms bij_lens_equiv_id lens_equiv_def unrest_sublens by blast\n\nlemma bij_lens_unrest_all_eq:\n  fixes P :: \"('a, '\\<alpha>) uexpr\"\n  assumes \"bij_lens X\"\n  shows \"(\\<Sigma> \\<sharp> P) \\<longleftrightarrow> (X \\<sharp> P)\"\n  by (meson assms bij_lens_equiv_id lens_equiv_def unrest_sublens)\n\ntext \\<open> If an expression is unrestricted by all variables, then it is unrestricted by any variable \\<close>\n\nlemma unrest_all_var:\n  fixes e :: \"('a, '\\<alpha>) uexpr\"\n  assumes \"\\<Sigma> \\<sharp> e\"\n  shows \"x \\<sharp> e\"\n  by (metis assms id_lens_def lens.simps(2) unrest_uexpr.rep_eq)\n\ntext \\<open> We can split an unrestriction composed by lens plus \\<close>\n\nlemma unrest_plus_split:\n  fixes P :: \"('a, '\\<alpha>) uexpr\"\n  assumes \"x \\<bowtie> y\" \"vwb_lens x\" \"vwb_lens y\"\n  shows \"unrest (x +\\<^sub>L y) P \\<longleftrightarrow> (x \\<sharp> P) \\<and> (y \\<sharp> P)\"\n  using assms\n  by (meson lens_plus_right_sublens lens_plus_ub sublens_refl unrest_sublens unrest_var_comp vwb_lens_wb)\n\ntext \\<open> The following laws demonstrate the primary motivation for lens independence: a variable\n  expression is unrestricted by another variable only when the two variables are independent. \n  Lens independence thus effectively allows us to semantically characterise when two variables,\n  or sets of variables, are different. \\<close>\n\nlemma unrest_var [unrest]: \"\\<lbrakk> mwb_lens x; x \\<bowtie> y \\<rbrakk> \\<Longrightarrow> y \\<sharp> var x\"\n  by (transfer, auto)\n    \nlemma unrest_iuvar [unrest]: \"\\<lbrakk> mwb_lens x; x \\<bowtie> y \\<rbrakk> \\<Longrightarrow> $y \\<sharp> $x\"\n  by (simp add: unrest_var)\n\nlemma unrest_ouvar [unrest]: \"\\<lbrakk> mwb_lens x; x \\<bowtie> y \\<rbrakk> \\<Longrightarrow> $y\\<acute> \\<sharp> $x\\<acute>\"\n  by (simp add: unrest_var)\n\ntext \\<open> The following laws follow automatically from independence of input and output variables. \\<close>\n    \nlemma unrest_iuvar_ouvar [unrest]:\n  fixes x :: \"('a \\<Longrightarrow> '\\<alpha>)\"\n  assumes \"mwb_lens y\"\n  shows \"$x \\<sharp> $y\\<acute>\"\n  by (metis prod.collapse unrest_uexpr.rep_eq var.rep_eq var_lookup_out var_update_in)\n\nlemma unrest_ouvar_iuvar [unrest]:\n  fixes x :: \"('a \\<Longrightarrow> '\\<alpha>)\"\n  assumes \"mwb_lens y\"\n  shows \"$x\\<acute> \\<sharp> $y\"\n  by (metis prod.collapse unrest_uexpr.rep_eq var.rep_eq var_lookup_in var_update_out)\n\ntext \\<open> Unrestriction distributes through the various function lifting expression constructs;\n  this allows us to prove unrestrictions for the majority of the expression language. \\<close>\n\nlemma unrest_appl [unrest]: \"\\<lbrakk> x \\<sharp> f; x \\<sharp> v \\<rbrakk> \\<Longrightarrow> x \\<sharp> f |> v\"\n  by (transfer, simp)\n\nlemma unrest_uop [unrest]: \"x \\<sharp> e \\<Longrightarrow> x \\<sharp> uop f e\"\n  by (simp add: unrest)\n\nlemma unrest_bop [unrest]: \"\\<lbrakk> x \\<sharp> u; x \\<sharp> v \\<rbrakk> \\<Longrightarrow> x \\<sharp> bop f u v\"\n  by (simp add: unrest)\n\nlemma unrest_trop [unrest]: \"\\<lbrakk> x \\<sharp> u; x \\<sharp> v; x \\<sharp> w \\<rbrakk> \\<Longrightarrow> x \\<sharp> trop f u v w\"\n  by (simp add: unrest)\n\nlemma unrest_qtop [unrest]: \"\\<lbrakk> x \\<sharp> u; x \\<sharp> v; x \\<sharp> w; x \\<sharp> y \\<rbrakk> \\<Longrightarrow> x \\<sharp> qtop f u v w y\"\n  by (simp add: unrest)\n\ntext \\<open> For convenience, we also prove unrestriction rules for the bespoke operators on equality,\n  numbers, arithmetic etc. \\<close>\n\nlemma unrest_zero [unrest]: \"x \\<sharp> 0\"\n  by (simp add: unrest_lit zero_uexpr_def)\n\nlemma unrest_one [unrest]: \"x \\<sharp> 1\"\n  by (simp add: one_uexpr_def unrest_lit)\n\nlemma unrest_numeral [unrest]: \"x \\<sharp> (numeral n)\"\n  by (simp add: numeral_uexpr_simp unrest_lit)\n\nlemma unrest_sgn [unrest]: \"x \\<sharp> u \\<Longrightarrow> x \\<sharp> sgn u\"\n  by (simp add: sgn_uexpr_def unrest_uop)\n\nlemma unrest_abs [unrest]: \"x \\<sharp> u \\<Longrightarrow> x \\<sharp> abs u\"\n  by (simp add: abs_uexpr_def unrest_uop)\n\nlemma unrest_plus [unrest]: \"\\<lbrakk> x \\<sharp> u; x \\<sharp> v \\<rbrakk> \\<Longrightarrow> x \\<sharp> u + v\"\n  by (simp add: plus_uexpr_def unrest)\n\nlemma unrest_uminus [unrest]: \"x \\<sharp> u \\<Longrightarrow> x \\<sharp> - u\"\n  by (simp add: uminus_uexpr_def unrest)\n\nlemma unrest_minus [unrest]: \"\\<lbrakk> x \\<sharp> u; x \\<sharp> v \\<rbrakk> \\<Longrightarrow> x \\<sharp> u - v\"\n  by (simp add: minus_uexpr_def unrest)\n\nlemma unrest_times [unrest]: \"\\<lbrakk> x \\<sharp> u; x \\<sharp> v \\<rbrakk> \\<Longrightarrow> x \\<sharp> u * v\"\n  by (simp add: times_uexpr_def unrest)\n\nlemma unrest_divide [unrest]: \"\\<lbrakk> x \\<sharp> u; x \\<sharp> v \\<rbrakk> \\<Longrightarrow> x \\<sharp> u / v\"\n  by (simp add: divide_uexpr_def unrest)\n\nlemma unrest_case_prod [unrest]: \"\\<lbrakk> \\<And> i j. x \\<sharp> P i j \\<rbrakk> \\<Longrightarrow> x \\<sharp> case_prod P v\"\n  by (simp add: prod.split_sel_asm)\n\ntext \\<open> For a $\\lambda$-term we need to show that the characteristic function expression does\n  not restrict $v$ for any input value $x$. \\<close>\n    \nlemma unrest_ulam [unrest]:\n  \"\\<lbrakk> \\<And> x. v \\<sharp> F x \\<rbrakk> \\<Longrightarrow> v \\<sharp> (\\<lambda>\\<^sub>u x \\<bullet> F x)\"\n  by (transfer, simp)\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/utp/utp_unrest.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8615381952105442, "lm_q2_score": 0.8289388062084421, "lm_q1q2_score": 0.7141624430408042}}
{"text": "theory Chapter5\n  imports Main\nbegin\n\nlemma \"\\<not> surj(f :: 'a \\<Rightarrow> 'a set)\"\nproof\n  assume 0: \"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\ntext{*\n\\section*{Chapter 5}\n\n\\exercise\nGive a readable, structured proof of the following lemma:\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 -\n  have \"T x y \\<or> T y x\" using T by blast\n  thus \"T x y\"\n  proof\n    assume \"T x y\"\n    thus \"T x y\" by simp\n  next\n    assume \"T y x\"\n    hence \"A y x\" using TA by blast\n    hence \"x = y\" using assms(4) A by blast\n    thus \"T x y\" using \\<open>T y x\\<close> by auto\n  qed\nqed\n\ntext{*\nEach step should use at most one of the assumptions @{text T}, @{text A}\nor @{text TA}.\n\\endexercise\n\n\\exercise\nGive a readable, structured proof of the following lemma:\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  let ?len_ys = \"length xs div 2\"\n  assume 1: \"length xs mod 2 = 0\" \n  then obtain ys where 2: \"ys = take ?len_ys xs\" by blast\n  then obtain zs where \"zs = drop ?len_ys xs\" by blast\n  hence \"xs = ys @ zs \\<and> length ys = length zs\" \n    using 1 2\n    by fastforce\n  thus ?thesis by blast\nnext\n  let ?len_ys = \"length xs div 2 + 1\"\n  assume 1: \"length xs mod 2 \\<noteq> 0\"\n  then obtain ys where 2: \"ys = take ?len_ys xs\" by blast\n  then obtain zs where \"zs = drop ?len_ys xs\" by blast\n  hence \"xs = ys @ zs \\<and> length ys = length zs + 1\" \n    using 1 2\n    by (smt (verit, ccfv_SIG) add.assoc add.commute add.right_neutral add_diff_cancel_right' add_self_div_2 append_take_drop_id div_add1_eq drop_drop length_append length_drop not_mod_2_eq_0_eq_1)\n  thus ?thesis by blast\nqed\n\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  thus ?thesis by simp\nqed\n  \nlemma \"\\<Sum>{0..n::nat} = n*(n+1) div 2\"\nproof (induction n)\n  case 0\n  show \"?case\" by simp\nnext\n  case (Suc n)\n  thus \"?case\" by simp\nqed\n\ntext{*\nHint: There are predefined functions @{const take} and {const drop} of type\n@{typ \"nat \\<Rightarrow> 'a list \\<Rightarrow> 'a list\"} such that @{text\"take k [x\\<^sub>1,\\<dots>] = [x\\<^sub>1,\\<dots>,x\\<^sub>k]\"}\nand @{text\"drop k [x\\<^sub>1,\\<dots>] = [x\\<^bsub>k+1\\<^esub>,\\<dots>]\"}. Let sledgehammer find and apply\nthe relevant @{const take} and @{const drop} lemmas for you.\n\\endexercise\n\n\\exercise\nGive a structured proof by rule inversion:\n*}\ninductive ev :: \"nat \\<Rightarrow> bool\" where\nev0: \"ev 0\" |\nevSS: \"ev n \\<Longrightarrow> ev(Suc(Suc n))\"\n\nlemma assumes a: \"ev(Suc(Suc n))\" shows \"ev n\"\nproof -\n  show ?thesis using a\n  proof cases\n    case evSS\n    then show ?thesis by auto\n  qed\nqed\n   \n\n\n\ntext{*\n\\exercise\nGive a structured proof by rule inversions:\n*}\n\nlemma \"\\<not> ev(Suc(Suc(Suc 0)))\" (is \"\\<not>?P\")\nproof\n  assume \"?P\"\n  hence \"ev (Suc 0)\" using ev.cases by auto\n  thus \"False\" using ev.cases by auto\nqed\n\ntext{*\nIf there are no cases to be proved you can close\na proof immediateley with \\isacom{qed}.\n\\endexercise\n\n\\exercise\nRecall predicate @{const star} from Section 4.5 and @{const iter}\nfrom Exercise~\\ref{exe:iter}.\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\niter_0: \"iter r 0 x x\" |\niter_Suc: \"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_0 x)\n  thus ?case by (simp add: star.refl)\nnext\n  case (iter_Suc x y n z)\n  thus ?case by (simp add: star.step)\nqed\n\ntext{*\nProve this lemma in a structured style, do not just sledgehammer each case of the\nrequired induction.\n\\endexercise\n\n\\exercise\nDefine a recursive function\n*}\n\nfun elems :: \"'a list \\<Rightarrow> 'a set\" where\n\"elems [] = {}\" |\n\"elems (x#xs) = {x} \\<union> elems xs\"\n\nvalue \"elems ([1,2,2,4,4,3,4]::(nat list))\" \n\ntext{* that collects all elements of a list into a set. Prove *}\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    then obtain ys where ys: \"(ys::'a list) = []\" by auto\n    then obtain zs where zs: \"zs = xs\" by auto\n    then have \"x \\<notin> elems ys\" using ys by auto\n    thus ?case using \\<open>a = x\\<close> ys by blast\n  next\n    assume \"a \\<noteq> x\"\n    then have \"x : elems xs\" using Cons.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 Cons.IH by blast\n  then have \"a # xs = ys @ x # zs \\<and> x \\<notin> elems ys\" using `a \\<noteq> x` by auto\n  then show ?case by auto\n  qed\nqed\n\ntext{*\n\\endexercise\n\n\\exercise\nExtend Exercise~\\ref{exe:cfg} with a function that checks if some\n\\mbox{@{text \"alpha list\"}} is a balanced\nstring of parentheses. More precisely, define a recursive function *}\n(* your definition/proof here *)\nfun balanced :: \"nat \\<Rightarrow> alpha list \\<Rightarrow> bool\" where\n(* your definition/proof here *)\n\ntext{* such that @{term\"balanced n w\"}\nis true iff (informally) @{text\"a\\<^sup>n @ w \\<in> S\"}. Formally, prove *}\n\ncorollary \"balanced n w \\<longleftrightarrow> S (replicate n a @ w)\"\n\n\ntext{* where @{const replicate} @{text\"::\"} @{typ\"nat \\<Rightarrow> 'a \\<Rightarrow> 'a list\"} is predefined\nand @{term\"replicate n x\"} yields the list @{text\"[x, \\<dots>, x]\"} of length @{text n}.\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/Chapter5.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7905303087996143, "lm_q2_score": 0.9032942093072239, "lm_q1q2_score": 0.7140814502205431}}
{"text": "(* \n  Title: Properties of Orderings and Lattices\n  Author: Georg Struth \n  Maintainer: Georg Struth <g.struth@sheffield.ac.uk> \n*)\n\nsection \\<open>Properties of Orderings and Lattices\\<close>\n\ntheory Order_Lattice_Props\n  imports Order_Duality\n\nbegin\n\nsubsection \\<open>Basic Definitions for Orderings and Lattices\\<close>\n\ntext \\<open>The first definition is for order morphisms --- isotone (order-preserving, monotone) functions. \nAn order isomorphism is an order-preserving bijection. This should be defined in the class ord, but mono requires order.\\<close>\n\ndefinition ord_homset :: \"('a::order \\<Rightarrow> 'b::order) set\" where\n \"ord_homset = {f::'a::order \\<Rightarrow> 'b::order. mono f}\"\n\ndefinition ord_embed :: \"('a::order \\<Rightarrow> 'b::order) \\<Rightarrow> bool\" where\n \"ord_embed f = (\\<forall>x y. f x \\<le> f y \\<longleftrightarrow> x \\<le> y)\"\n\ndefinition ord_iso :: \"('a::order \\<Rightarrow> 'b::order) \\<Rightarrow> bool\" where\n  \"ord_iso = bij \\<sqinter> mono \\<sqinter> (mono \\<circ> the_inv)\"\n\nlemma ord_embed_alt: \"ord_embed f = (mono f \\<and> (\\<forall>x y. f x \\<le> f y \\<longrightarrow> x \\<le> y))\"\n  using mono_def ord_embed_def by auto\n\nlemma ord_embed_homset: \"ord_embed f \\<Longrightarrow> f \\<in> ord_homset\"\n  by (simp add: mono_def ord_embed_def ord_homset_def)\n\nlemma ord_embed_inj: \"ord_embed f \\<Longrightarrow> inj f\"\n  unfolding ord_embed_def inj_def by (simp add: eq_iff)\n\nlemma ord_iso_ord_embed: \"ord_iso f \\<Longrightarrow> ord_embed f\"\n  unfolding ord_iso_def ord_embed_def bij_def inj_def mono_def\n  by (clarsimp, metis inj_def the_inv_f_f)\n\nlemma ord_iso_alt: \"ord_iso f = (ord_embed f \\<and> surj f)\"\n  unfolding ord_iso_def ord_embed_def surj_def bij_def inj_def mono_def \n  apply safe\n  by simp_all (metis eq_iff inj_def the_inv_f_f)+\n\nlemma ord_iso_the_inv: \"ord_iso f \\<Longrightarrow> mono (the_inv f)\"\n  by (simp add: ord_iso_def)\n\nlemma ord_iso_inv1: \"ord_iso f \\<Longrightarrow> (the_inv f) \\<circ> f = id\"\n  using ord_embed_inj ord_iso_ord_embed the_inv_into_f_f by fastforce\n\nlemma ord_iso_inv2: \"ord_iso f \\<Longrightarrow> f \\<circ> (the_inv f) = id\"\n  using f_the_inv_into_f ord_embed_inj ord_iso_alt by fastforce\n\ntypedef (overloaded) ('a,'b) ord_homset = \"ord_homset::('a::order \\<Rightarrow> 'b::order) set\" \n  by (force simp: ord_homset_def mono_def) \n\nsetup_lifting type_definition_ord_homset \n\ntext \\<open>The next definition is for the set of fixpoints of a given function. It is important in the context of orders,\nfor instance for proving Tarski's fixpoint theorem, but does not really belong here.\\<close>\n\ndefinition Fix :: \"('a \\<Rightarrow> 'a) \\<Rightarrow> 'a set\" where \n  \"Fix f = {x. f x = x}\"\n\nlemma retraction_prop: \"f \\<circ> f = f \\<Longrightarrow> f x = x \\<longleftrightarrow> x \\<in> range f\"\n  by (metis comp_apply f_inv_into_f rangeI)\n\nlemma retraction_prop_fix: \"f \\<circ> f = f \\<Longrightarrow> range f = Fix f\"\n  unfolding Fix_def using retraction_prop by fastforce\n\nlemma Fix_map_dual: \"Fix \\<circ> \\<partial>\\<^sub>F = (`) \\<partial> \\<circ> Fix\"\n  unfolding Fix_def map_dual_def comp_def fun_eq_iff\n  by (smt Collect_cong invol_dual pointfree_idE setcompr_eq_image)\n\nlemma Fix_map_dual_var: \"Fix (\\<partial>\\<^sub>F f) = \\<partial> ` (Fix f)\"\n  by (metis Fix_map_dual o_def)\n\nlemma gfp_dual: \"(\\<partial>::'a::complete_lattice_with_dual \\<Rightarrow> 'a) \\<circ> gfp = lfp \\<circ> \\<partial>\\<^sub>F\"\nproof-\n  {fix f:: \"'a \\<Rightarrow> 'a\"\n  have \"\\<partial> (gfp f) = \\<partial> (\\<Squnion>{u. u \\<le> f u})\"\n    by (simp add: gfp_def)\n  also have \"... = \\<Sqinter>(\\<partial> ` {u. u \\<le> f u})\"\n    by (simp add: Sup_dual_def_var)\n  also have \"... = \\<Sqinter>{\\<partial> u |u. u \\<le> f u}\"\n    by (simp add: setcompr_eq_image)\n  also have \"... = \\<Sqinter>{u |u. (\\<partial>\\<^sub>F f) u \\<le> u}\"\n    by (metis (no_types, hide_lams) dual_dual_ord dual_iff map_dual_def o_def)\n  finally have \"\\<partial> (gfp f) = lfp (\\<partial>\\<^sub>F f)\"\n    by (metis lfp_def)}\n  thus ?thesis\n    by auto\nqed\n\nlemma gfp_dual_var: \n  fixes f :: \"'a::complete_lattice_with_dual \\<Rightarrow> 'a\"\n  shows \"\\<partial> (gfp f) = lfp (\\<partial>\\<^sub>F f)\"\n  using comp_eq_elim gfp_dual by blast\n\nlemma gfp_to_lfp: \"gfp = (\\<partial>::'a::complete_lattice_with_dual \\<Rightarrow> 'a) \\<circ> lfp \\<circ> \\<partial>\\<^sub>F\"\n  by (simp add: comp_assoc fun_dual2 gfp_dual)\n\nlemma gfp_to_lfp_var: \n  fixes f :: \"'a::complete_lattice_with_dual \\<Rightarrow> 'a\"\n  shows \"gfp f = \\<partial> (lfp (\\<partial>\\<^sub>F f))\"\n  by (metis gfp_dual_var invol_dual_var)\n\nlemma lfp_dual: \"(\\<partial>::'a::complete_lattice_with_dual \\<Rightarrow> 'a) \\<circ> lfp = gfp \\<circ> \\<partial>\\<^sub>F\"\n  by (simp add: comp_assoc gfp_to_lfp map_dual_invol)\n\nlemma lfp_dual_var: \n  fixes f :: \"'a::complete_lattice_with_dual \\<Rightarrow> 'a\"\n  shows \"\\<partial> (lfp f) = gfp (map_dual f)\"\n  using comp_eq_dest_lhs lfp_dual by fastforce\n\nlemma lfp_to_gfp: \"lfp = (\\<partial>::'a::complete_lattice_with_dual \\<Rightarrow> 'a) \\<circ> gfp \\<circ> \\<partial>\\<^sub>F\"\n  by (simp add: comp_assoc gfp_dual map_dual_invol)\n\nlemma lfp_to_gfp_var: \n  fixes f :: \"'a::complete_lattice_with_dual \\<Rightarrow> 'a\"\n  shows \"lfp f = \\<partial> (gfp (\\<partial>\\<^sub>F f))\"\n  by (metis invol_dual_var lfp_dual_var)\n\nlemma lfp_in_Fix: \n  fixes f :: \"'a::complete_lattice \\<Rightarrow> 'a\"\n  shows \"mono f \\<Longrightarrow> lfp f \\<in> Fix f\"\n  by (metis (mono_tags, lifting) Fix_def lfp_unfold mem_Collect_eq)\n\nlemma gfp_in_Fix: \n  fixes f :: \"'a::complete_lattice \\<Rightarrow> 'a\"\n  shows \"mono f \\<Longrightarrow> gfp f \\<in> Fix f\"\n  by (metis (mono_tags, lifting) Fix_def gfp_unfold mem_Collect_eq)\n\nlemma nonempty_Fix: \n  fixes f :: \"'a::complete_lattice \\<Rightarrow> 'a\"\n  shows \"mono f \\<Longrightarrow> Fix f \\<noteq> {}\"\n  using lfp_in_Fix by fastforce\n\n\ntext \\<open>Next the minimal and maximal elements of an ordering are defined.\\<close>\n\ncontext ord\nbegin\n\ndefinition min_set :: \"'a set \\<Rightarrow> 'a set\" where \n  \"min_set X = {y \\<in> X. \\<forall>x \\<in> X. x \\<le> y \\<longrightarrow> x = y}\"\n\ndefinition max_set :: \"'a set \\<Rightarrow> 'a set\" where \n  \"max_set X = {x \\<in> X. \\<forall>y \\<in> X. x \\<le> y \\<longrightarrow> x = y}\"\n\nend\n\ncontext ord_with_dual\nbegin\n\nlemma min_max_set_dual: \"(`) \\<partial> \\<circ> min_set = max_set \\<circ> (`) \\<partial>\"  \n  unfolding max_set_def min_set_def fun_eq_iff comp_def \n  apply safe\n  using dual_dual_ord inj_dual_iff by auto\n\nlemma min_max_set_dual_var: \"\\<partial> ` (min_set X) = max_set (\\<partial> ` X)\"\n  using comp_eq_dest min_max_set_dual by fastforce  \n\nlemma max_min_set_dual: \"(`) \\<partial> \\<circ> max_set = min_set \\<circ> (`) \\<partial>\"\n  by (metis (no_types, hide_lams) comp_id fun.map_comp id_comp image_dual min_max_set_dual)  \n\nlemma min_to_max_set: \"min_set = (`) \\<partial> \\<circ> max_set \\<circ> (`) \\<partial>\"\n  by (metis comp_id image_dual max_min_set_dual o_assoc)\n\nlemma max_min_set_dual_var: \"\\<partial> ` (max_set X) = min_set (\\<partial> ` X)\"\n  using comp_eq_dest max_min_set_dual by fastforce\n\nlemma min_to_max_set_var: \"min_set X = \\<partial> ` (max_set (\\<partial> ` X))\"\n  by (simp add: max_min_set_dual_var pointfree_idE)\n\nend\n\ntext \\<open>Next, directed and filtered sets, upsets, downsets, filters and ideals in posets are defined.\\<close>\n\ncontext ord\nbegin\n\ndefinition directed :: \"'a set \\<Rightarrow> bool\" where\n \"directed X = (\\<forall>Y. finite Y \\<and> Y \\<subseteq> X \\<longrightarrow> (\\<exists>x \\<in> X. \\<forall>y \\<in> Y. y \\<le> x))\"\n\ndefinition filtered :: \"'a set \\<Rightarrow> bool\" where\n \"filtered X = (\\<forall>Y. finite Y \\<and> Y \\<subseteq> X \\<longrightarrow> (\\<exists>x \\<in> X. \\<forall>y \\<in> Y. x \\<le> y))\"\n\ndefinition downset_set :: \"'a set \\<Rightarrow> 'a set\" (\"\\<Down>\") where\n  \"\\<Down>X = {y. \\<exists>x \\<in> X. y \\<le> x}\"\n\ndefinition upset_set :: \"'a set \\<Rightarrow> 'a set\" (\"\\<Up>\") where\n \"\\<Up>X = {y. \\<exists>x \\<in> X. x \\<le> y}\"\n\ndefinition downset :: \"'a \\<Rightarrow> 'a set\" (\"\\<down>\") where \n  \"\\<down> = \\<Down> \\<circ> \\<eta>\"\n\ndefinition upset :: \"'a \\<Rightarrow> 'a set\" (\"\\<up>\") where \n  \"\\<up> = \\<Up> \\<circ> \\<eta>\"\n\ndefinition downsets :: \"'a set set\" where  \n  \"downsets = Fix \\<Down>\"\n \ndefinition upsets :: \"'a set set\" where\n  \"upsets = Fix \\<Up>\"\n\ndefinition \"downclosed_set X = (X \\<in> downsets)\"\n\ndefinition \"upclosed_set X = (X \\<in> upsets)\"\n\ndefinition ideals :: \"'a set set\" where\n  \"ideals = {X. X \\<noteq> {} \\<and> downclosed_set X \\<and> directed X}\"\n\ndefinition filters :: \"'a set set\" where\n  \"filters = {X. X \\<noteq> {} \\<and> upclosed_set X \\<and> filtered X}\"\n\nabbreviation \"idealp X \\<equiv> X \\<in> ideals\"\n\nabbreviation \"filterp X \\<equiv> X \\<in> filters\"\n\nend\n\ntext \\<open>These notions are pair-wise dual.\\<close>\n\ntext \\<open>Filtered and directed sets are dual.\\<close>\n\ncontext ord_with_dual\nbegin\n\nlemma filtered_directed_dual: \"filtered \\<circ> (`) \\<partial> = directed\"\n  unfolding filtered_def directed_def fun_eq_iff comp_def\n  apply clarsimp\n  apply safe\n   apply (meson finite_imageI imageI image_mono dual_dual_ord)\n  by (smt finite_subset_image imageE ord_dual)\n\nlemma directed_filtered_dual: \"directed \\<circ> (`) \\<partial> = filtered\"\n  using filtered_directed_dual by (metis comp_id image_dual o_assoc) \n\nlemma filtered_to_directed: \"filtered X = directed (\\<partial> ` X)\"\n  by (metis comp_apply directed_filtered_dual)\n\ntext \\<open>Upsets and downsets are dual.\\<close>\n\nlemma downset_set_upset_set_dual: \"(`) \\<partial> \\<circ> \\<Down> = \\<Up> \\<circ> (`) \\<partial>\"\n  unfolding downset_set_def upset_set_def fun_eq_iff comp_def\n  apply safe\n   apply (meson image_eqI ord_dual)\n  by (clarsimp, metis (mono_tags, lifting) dual_iff image_iff mem_Collect_eq ord_dual)\n\nlemma upset_set_downset_set_dual: \"(`) \\<partial> \\<circ> \\<Up> = \\<Down> \\<circ> (`) \\<partial>\"\n  using downset_set_upset_set_dual by (metis (no_types, hide_lams) comp_id id_comp image_dual o_assoc)\n\nlemma upset_set_to_downset_set: \"\\<Up> = (`) \\<partial> \\<circ> \\<Down> \\<circ> (`) \\<partial>\"\n  by (simp add: comp_assoc downset_set_upset_set_dual)\n\nlemma upset_set_to_downset_set2: \"\\<Up> X = \\<partial> ` (\\<Down> (\\<partial> ` X))\"\n  by (simp add: upset_set_to_downset_set)\n\nlemma downset_upset_dual: \"(`) \\<partial> \\<circ> \\<down> = \\<up> \\<circ> \\<partial>\"\n  using downset_def upset_def upset_set_to_downset_set by fastforce\n\nlemma upset_to_downset: \"(`) \\<partial> \\<circ> \\<up> = \\<down> \\<circ> \\<partial>\"\n  by (metis comp_assoc id_apply ord.downset_def ord.upset_def power_set_func_nat_trans upset_set_downset_set_dual)\n\nlemma upset_to_downset2: \"\\<up> = (`) \\<partial> \\<circ> \\<down> \\<circ> \\<partial>\"\n  by (simp add: comp_assoc downset_upset_dual)\n\nlemma upset_to_downset3: \"\\<up> x = \\<partial> ` (\\<down> (\\<partial> x))\"\n  by (simp add: upset_to_downset2)\n\nlemma downsets_upsets_dual: \"(X \\<in> downsets) = (\\<partial> ` X \\<in> upsets)\"\n  unfolding downsets_def upsets_def Fix_def\n  by (smt comp_eq_dest downset_set_upset_set_dual image_inv_f_f inj_dual mem_Collect_eq)\n\nlemma downset_setp_upset_setp_dual: \"upclosed_set \\<circ> (`) \\<partial> = downclosed_set\"\n  unfolding downclosed_set_def upclosed_set_def using downsets_upsets_dual by fastforce\n\nlemma upsets_to_downsets: \"(X \\<in> upsets) = (\\<partial> ` X \\<in> downsets)\"\n  by (simp add: downsets_upsets_dual image_comp)\n\nlemma upset_setp_downset_setp_dual: \"downclosed_set \\<circ> (`) \\<partial> = upclosed_set\"\n  by (metis comp_id downset_setp_upset_setp_dual image_dual o_assoc)\n\ntext \\<open>Filters and ideals are dual.\\<close>\n\nlemma ideals_filters_dual: \"(X \\<in> ideals) = ((\\<partial> ` X) \\<in> filters)\"\n  by (smt comp_eq_dest_lhs directed_filtered_dual image_inv_f_f image_is_empty inv_unique_comp filters_def ideals_def inj_dual invol_dual mem_Collect_eq upset_setp_downset_setp_dual)\n\nlemma idealp_filterp_dual: \"idealp = filterp \\<circ> (`) \\<partial>\"\n  unfolding fun_eq_iff by (simp add: ideals_filters_dual)\n\nlemma filters_to_ideals: \"(X \\<in> filters) = ((\\<partial> ` X) \\<in> ideals)\"\n  by (simp add: ideals_filters_dual image_comp)\n\nlemma filterp_idealp_dual: \"filterp = idealp \\<circ> (`) \\<partial>\"\n  unfolding fun_eq_iff by (simp add: filters_to_ideals)\n\nend\n\nsubsection \\<open>Properties of Orderings\\<close>\n\ncontext ord\nbegin\n\nlemma directed_nonempty: \"directed X \\<Longrightarrow> X \\<noteq> {}\"\n  unfolding directed_def by fastforce\n\nlemma directed_ub: \"directed X \\<Longrightarrow> (\\<forall>x \\<in> X. \\<forall>y \\<in> X. \\<exists>z \\<in> X. x \\<le> z \\<and> y \\<le> z)\"\n  by (meson empty_subsetI directed_def finite.emptyI finite_insert insert_subset order_refl)\n\nlemma downset_set_prop: \"\\<Down> = Union \\<circ> (`) \\<down>\"\n  unfolding downset_set_def downset_def fun_eq_iff by fastforce\n\nlemma downset_set_prop_var: \"\\<Down>X = (\\<Union>x \\<in> X. \\<down>x)\"\n  by (simp add: downset_set_prop)\n\nlemma downset_prop: \"\\<down>x = {y. y \\<le> x}\"\n  unfolding downset_def downset_set_def fun_eq_iff by fastforce\n\nlemma downset_prop2: \"y \\<le> x \\<Longrightarrow> y \\<in> \\<down>x\"\n  by (simp add: downset_prop)\n\nlemma ideals_downsets: \"X \\<in> ideals \\<Longrightarrow> X \\<in> downsets\"\n  by (simp add: downclosed_set_def ideals_def)\n\nlemma ideals_directed: \"X \\<in> ideals \\<Longrightarrow> directed X\"\n  by (simp add: ideals_def)\n\nend\n\ncontext preorder\nbegin\n\nlemma directed_prop: \"X \\<noteq> {} \\<Longrightarrow> (\\<forall>x \\<in> X. \\<forall>y \\<in> X. \\<exists>z \\<in> X. x \\<le> z \\<and> y \\<le> z) \\<Longrightarrow> directed X\"\nproof-\n  assume h1: \"X \\<noteq> {}\"\n  and h2: \"\\<forall>x \\<in> X. \\<forall>y \\<in> X. \\<exists>z \\<in> X. x \\<le> z \\<and> y \\<le> z\"\n  {fix Y\n  have \"finite Y \\<Longrightarrow> Y \\<subseteq> X \\<Longrightarrow> (\\<exists>x \\<in> X. \\<forall>y \\<in> Y. y \\<le> x)\"\n  proof (induct rule: finite_induct)\n    case empty\n    then show ?case\n      using h1 by blast \n  next\n    case (insert x F)\n    then show ?case\n      by (metis h2 insert_iff insert_subset order_trans) \n  qed}\n  thus ?thesis\n    by (simp add: directed_def)\nqed\n\nlemma directed_alt: \"directed X = (X \\<noteq> {} \\<and> (\\<forall>x \\<in> X. \\<forall>y \\<in> X. \\<exists>z \\<in> X. x \\<le> z \\<and> y \\<le> z))\"\n  by (metis directed_prop directed_nonempty directed_ub)\n\nlemma downset_set_prop_var2: \"x \\<in> \\<Down>X \\<Longrightarrow> y \\<le> x \\<Longrightarrow> y \\<in> \\<Down>X\"\n  unfolding downset_set_def using order_trans by blast\n\nlemma downclosed_set_iff: \"downclosed_set X = (\\<forall>x \\<in> X. \\<forall>y. y \\<le> x \\<longrightarrow> y \\<in> X)\"\n  unfolding downclosed_set_def downsets_def Fix_def downset_set_def by auto\n\nlemma downclosed_downset_set: \"downclosed_set (\\<Down>X)\"\n  by (simp add: downclosed_set_iff downset_set_prop_var2 downset_def)\n\nlemma downclosed_downset: \"downclosed_set (\\<down>x)\"\n  by (simp add: downclosed_downset_set downset_def)\n \nlemma downset_set_ext: \"id \\<le> \\<Down>\"\n  unfolding le_fun_def id_def downset_set_def by auto \n\nlemma downset_set_iso: \"mono \\<Down>\"\n  unfolding mono_def downset_set_def by blast\n\nlemma downset_set_idem [simp]: \"\\<Down> \\<circ> \\<Down> = \\<Down>\"\n  unfolding fun_eq_iff downset_set_def using order_trans by auto\n\nlemma downset_faithful: \"\\<down>x \\<subseteq> \\<down>y \\<Longrightarrow> x \\<le> y\"\n  by (simp add: downset_prop subset_eq)\n\nlemma downset_iso_iff: \"(\\<down>x \\<subseteq> \\<down>y) = (x \\<le> y)\"\n  using atMost_iff downset_prop order_trans by blast\n\ntext \\<open>The following proof uses the Axiom of Choice.\\<close>\n\nlemma downset_directed_downset_var [simp]: \"directed (\\<Down>X) = directed X\"\nproof\n  assume h1: \"directed X\"\n  {fix Y\n  assume h2: \"finite Y\" and h3: \"Y \\<subseteq> \\<Down>X\"\n  hence \"\\<forall>y. \\<exists>x. y \\<in> Y \\<longrightarrow> x \\<in> X \\<and>  y \\<le> x\"\n    by (force simp: downset_set_def)\n  hence \"\\<exists>f. \\<forall>y. y \\<in> Y \\<longrightarrow>  f y \\<in> X \\<and> y \\<le> f y\"\n    by (rule choice)\n  hence \"\\<exists>f. finite (f ` Y) \\<and> f ` Y \\<subseteq> X \\<and> (\\<forall>y \\<in> Y. y \\<le> f y)\"\n    by (metis finite_imageI h2 image_subsetI)\n  hence \"\\<exists>Z. finite Z \\<and> Z \\<subseteq> X \\<and> (\\<forall>y \\<in> Y. \\<exists> z \\<in> Z. y \\<le> z)\"\n    by fastforce\n  hence \"\\<exists>Z. finite Z \\<and> Z \\<subseteq> X \\<and> (\\<forall>y \\<in> Y. \\<exists> z \\<in> Z. y \\<le> z) \\<and> (\\<exists>x \\<in> X. \\<forall> z \\<in> Z. z \\<le> x)\"\n    by (metis directed_def h1)\n  hence \"\\<exists>x \\<in> X. \\<forall>y \\<in> Y. y \\<le> x\"\n    by (meson order_trans)}\n  thus \"directed (\\<Down>X)\"\n    unfolding directed_def downset_set_def by fastforce\nnext \n  assume \"directed (\\<Down>X)\"\n  thus \"directed X\"\n    unfolding directed_def downset_set_def \n    apply clarsimp\n    by (smt Ball_Collect order_refl order_trans subsetCE)\nqed\n\nlemma downset_directed_downset [simp]: \"directed \\<circ> \\<Down> = directed\"\n  unfolding fun_eq_iff by simp\n\nlemma directed_downset_ideals: \"directed (\\<Down>X) = (\\<Down>X \\<in> ideals)\"\n  by (metis (mono_tags, lifting) CollectI Fix_def directed_alt downset_set_idem downclosed_set_def downsets_def ideals_def o_def ord.ideals_directed)\n\nlemma downclosed_Fix: \"downclosed_set X = (\\<Down>X = X)\"\n  by (metis (mono_tags, lifting) CollectD Fix_def downclosed_downset_set downclosed_set_def downsets_def)\n  \nend\n\nlemma downset_iso: \"mono (\\<down>::'a::order \\<Rightarrow> 'a set)\"\n  by (simp add: downset_iso_iff mono_def)\n\nlemma mono_downclosed: \n  fixes f :: \"'a::order \\<Rightarrow> 'b::order\"\n  assumes \"mono f\"\n  shows \"\\<forall>Y. downclosed_set Y \\<longrightarrow> downclosed_set (f -` Y)\"   \n  by (simp add: assms downclosed_set_iff monoD)\n\nlemma\n  fixes f :: \"'a::order \\<Rightarrow> 'b::order\"\n  assumes \"mono f\"\n  shows \"\\<forall>Y. downclosed_set X \\<longrightarrow> downclosed_set (f ` X)\" (*nitpick*)\n  oops\n\nlemma downclosed_mono:\n  fixes f :: \"'a::order \\<Rightarrow> 'b::order\"\n  assumes \"\\<forall>Y. downclosed_set Y \\<longrightarrow> downclosed_set (f -` Y)\"\n  shows \"mono f\"\nproof-\n  {fix x y :: \"'a::order\"\n  assume h: \"x \\<le> y\"\n  have \"downclosed_set (\\<down> (f y))\"\n    unfolding downclosed_set_def downsets_def Fix_def downset_set_def downset_def by auto\n  hence \"downclosed_set (f -` (\\<down> (f y)))\"\n    by (simp add: assms)\n  hence \"downclosed_set {z. f z \\<le> f y}\"\n    unfolding vimage_def downset_def downset_set_def by auto\n  hence \"\\<forall>z w. (f z \\<le> f y \\<and> w \\<le> z) \\<longrightarrow> f w \\<le> f y\"\n    unfolding downclosed_set_def downclosed_set_def downsets_def Fix_def downset_set_def by force\n  hence \"f x \\<le> f y\"\n    using h by blast}\n  thus ?thesis..\nqed\n\nlemma mono_downclosed_iff: \"mono f = (\\<forall>Y. downclosed_set Y \\<longrightarrow> downclosed_set (f -` Y))\"\n  using mono_downclosed downclosed_mono by auto\n\ncontext order\nbegin\n\nlemma downset_inj: \"inj \\<down>\"\n  by (metis injI downset_iso_iff eq_iff)\n\nlemma \"(X \\<subseteq> Y) = (\\<Down>X \\<subseteq> \\<Down>Y)\" (*nitpick*)\n  oops\n\nend\n\ncontext lattice\nbegin\n\nlemma lat_ideals: \"X \\<in> ideals = (X \\<noteq> {} \\<and> X \\<in> downsets \\<and> (\\<forall>x \\<in> X. \\<forall> y \\<in> X. x \\<squnion> y \\<in> X))\"\n  unfolding ideals_def directed_alt downsets_def Fix_def downset_set_def downclosed_set_def\n  by (clarsimp, smt sup.cobounded1 sup.orderE sup.orderI sup_absorb2 sup_left_commute mem_Collect_eq)\n\nend\n\ncontext bounded_lattice\nbegin\n\nlemma bot_ideal: \"X \\<in> ideals \\<Longrightarrow> \\<bottom> \\<in> X\"\n  unfolding ideals_def downclosed_set_def downsets_def Fix_def downset_set_def by fastforce\n\nend\n\ncontext complete_lattice\nbegin\n\nlemma Sup_downset_id [simp]: \"Sup \\<circ> \\<down> = id\"\n  using Sup_atMost atMost_def downset_prop by fastforce\n\nlemma downset_Sup_id: \"id \\<le> \\<down> \\<circ> Sup\"\n  by (simp add: Sup_upper downset_prop le_funI subsetI)\n\nlemma Inf_Sup_var: \"\\<Squnion>(\\<Inter>x \\<in> X. \\<down>x) = \\<Sqinter>X\"\n  unfolding downset_prop by (simp add: Collect_ball_eq Inf_eq_Sup)\n\nlemma Inf_pres_downset_var: \"(\\<Inter>x \\<in> X. \\<down>x) = \\<down>(\\<Sqinter>X)\"\n  unfolding downset_prop by (safe, simp_all add: le_Inf_iff)\n\nend\n\n\nsubsection \\<open>Dual Properties of Orderings\\<close>\n\ncontext ord_with_dual\nbegin\n\n\n\nlemma filtered_lb: \"filtered X \\<Longrightarrow> (\\<forall>x \\<in> X. \\<forall>y \\<in> X. \\<exists>z \\<in> X. z \\<le> x \\<and> z \\<le> y)\"\n  using filtered_to_directed directed_ub dual_dual_ord by fastforce\n\nlemma upset_set_prop_var: \"\\<Up>X = (\\<Union>x \\<in> X. \\<up>x)\"\n  by (simp add: image_Union downset_set_prop_var upset_set_to_downset_set2 upset_to_downset2)\n\nlemma upset_set_prop: \"\\<Up> = Union \\<circ> (`) \\<up>\"\n  unfolding fun_eq_iff by (simp add: upset_set_prop_var)\n\nlemma upset_prop: \"\\<up>x = {y. x \\<le> y}\"\n  unfolding upset_to_downset3 downset_prop image_def using dual_dual_ord by fastforce\n\nlemma upset_prop2: \"x \\<le> y \\<Longrightarrow> y \\<in> \\<up>x\"\n  by (simp add: upset_prop)\n\nlemma filters_upsets: \"X \\<in> filters \\<Longrightarrow> X \\<in> upsets\"\n  by (simp add: upclosed_set_def filters_def)\n\nlemma filters_filtered: \"X \\<in> filters \\<Longrightarrow> filtered X\"\n  by (simp add: filters_def)\n\nend\n\ncontext preorder_with_dual\nbegin\n\nlemma filtered_prop: \"X \\<noteq> {} \\<Longrightarrow> (\\<forall>x \\<in> X. \\<forall>y \\<in> X. \\<exists>z \\<in> X. z \\<le> x \\<and> z \\<le> y) \\<Longrightarrow> filtered X\"\n  unfolding filtered_to_directed \n    by (rule directed_prop, blast, metis (full_types) image_iff ord_dual)\n \nlemma filtered_alt: \"filtered X = (X \\<noteq> {} \\<and> (\\<forall>x \\<in> X. \\<forall>y \\<in> X. \\<exists>z \\<in> X. z \\<le> x \\<and> z \\<le> y))\"\n  by (metis image_empty directed_alt filtered_to_directed filtered_lb filtered_prop)\n\nlemma up_set_prop_var2: \"x \\<in> \\<Up>X \\<Longrightarrow> x \\<le> y \\<Longrightarrow> y \\<in> \\<Up>X\"\n  using downset_set_prop_var2 dual_iff ord_dual upset_set_to_downset_set2 by fastforce\n\nlemma upclosed_set_iff: \"upclosed_set X = (\\<forall>x \\<in> X. \\<forall>y. x \\<le> y \\<longrightarrow> y \\<in> X)\"\n  unfolding upclosed_set_def upsets_def Fix_def upset_set_def by auto\n\nlemma upclosed_upset_set: \"upclosed_set (\\<Up>X)\"\n  using up_set_prop_var2 upclosed_set_iff by blast\n\nlemma upclosed_upset: \"upclosed_set (\\<up>x)\"\n  by (simp add: upset_def upclosed_upset_set) \n  \nlemma upset_set_ext: \"id \\<le> \\<Up>\"\n  by (smt comp_def comp_id image_mono le_fun_def downset_set_ext image_dual upset_set_to_downset_set2)\n\nlemma upset_set_anti: \"mono \\<Up>\"\n  by (metis image_mono downset_set_iso upset_set_to_downset_set2 mono_def)\n\nlemma up_set_idem [simp]: \"\\<Up> \\<circ> \\<Up> = \\<Up>\"\n  by (metis comp_assoc downset_set_idem upset_set_downset_set_dual upset_set_to_downset_set)\n\nlemma upset_faithful: \"\\<up>x \\<subseteq> \\<up>y \\<Longrightarrow> y \\<le> x\"\n  by (metis inj_image_subset_iff downset_faithful dual_dual_ord inj_dual upset_to_downset3)\n\nlemma upset_anti_iff: \"(\\<up>y \\<subseteq> \\<up>x) = (x \\<le> y)\"\n  by (metis downset_iso_iff ord_dual upset_to_downset3 subset_image_iff upset_faithful)\n\nlemma upset_filtered_upset [simp]: \"filtered \\<circ> \\<Up> = filtered\"\n  by (metis comp_assoc directed_filtered_dual downset_directed_downset upset_set_downset_set_dual)\n\nlemma filtered_upset_filters: \"filtered (\\<Up>X) = (\\<Up>X \\<in> filters)\"\n  by (metis comp_apply directed_downset_ideals filtered_to_directed filterp_idealp_dual upset_set_downset_set_dual)\n\nlemma upclosed_Fix: \"upclosed_set X = (\\<Up>X = X)\"\n  by (simp add: Fix_def upclosed_set_def upsets_def)\n\nend\n\nlemma upset_anti: \"antimono (\\<up>::'a::order_with_dual \\<Rightarrow> 'a set)\"\n  by (simp add: antimono_def upset_anti_iff)\n\nlemma mono_upclosed: \n  fixes f :: \"'a::order_with_dual \\<Rightarrow> 'b::order_with_dual\"\n  assumes \"mono f\"\n  shows \"\\<forall>Y. upclosed_set Y \\<longrightarrow> upclosed_set (f -` Y)\"\n  by (simp add: assms monoD upclosed_set_iff)\n\nlemma mono_upclosed: \n  fixes f :: \"'a::order_with_dual \\<Rightarrow> 'b::order_with_dual\"\n  assumes \"mono f\"\n  shows \"\\<forall>Y. upclosed_set X \\<longrightarrow> upclosed_set (f ` X)\" (*nitpick*)\n  oops\n\nlemma upclosed_mono:\n  fixes f :: \"'a::order_with_dual \\<Rightarrow> 'b::order_with_dual\"\n  assumes \"\\<forall>Y. upclosed_set Y \\<longrightarrow> upclosed_set (f -` Y)\"\n  shows \"mono f\"\n  by (metis (mono_tags, lifting) assms dual_order.refl mem_Collect_eq monoI order.trans upclosed_set_iff vimageE vimageI2)\n\nlemma mono_upclosed_iff: \n  fixes f :: \"'a::order_with_dual \\<Rightarrow> 'b::order_with_dual\"\n  shows \"mono f = (\\<forall>Y. upclosed_set Y \\<longrightarrow> upclosed_set (f -` Y))\"\n  using mono_upclosed upclosed_mono by auto\n\ncontext order_with_dual\nbegin\n\nlemma upset_inj: \"inj \\<up>\"\n  by (metis inj_compose inj_on_imageI2 downset_inj inj_dual upset_to_downset)\n\nlemma \"(X \\<subseteq> Y) = (\\<Up>Y \\<subseteq> \\<Up>X)\" (*nitpick*)\n  oops\n\nend\n\ncontext lattice_with_dual\nbegin\n\n\n\nend\n\ncontext bounded_lattice_with_dual\nbegin\n\nlemma top_filter: \"X \\<in> filters \\<Longrightarrow> \\<top> \\<in> X\"\n  using bot_ideal inj_image_mem_iff inj_dual filters_to_ideals top_dual by fastforce\n\nend\n\ncontext complete_lattice_with_dual\nbegin\n\nlemma Inf_upset_id [simp]: \"Inf \\<circ> \\<up> = id\"\n  by (metis comp_assoc comp_id Sup_downset_id Sups_dual_def downset_upset_dual invol_dual)\n\nlemma upset_Inf_id: \"id \\<le> \\<up> \\<circ> Inf\"\n  by (simp add: Inf_lower le_funI subsetI upset_prop)\n\nlemma Sup_Inf_var: \" \\<Sqinter>(\\<Inter>x \\<in> X. \\<up>x) = \\<Squnion>X\"\n  unfolding upset_prop by (simp add: Collect_ball_eq Sup_eq_Inf)\n\nlemma Sup_dual_upset_var: \"(\\<Inter>x \\<in> X. \\<up>x) = \\<up>(\\<Squnion>X)\"\n  unfolding upset_prop by (safe, simp_all add: Sup_le_iff)\n\nend\n\n\nsubsection \\<open>Shunting Laws\\<close>\n\ntext \\<open>The first set of laws supplies so-called shunting laws for boolean algebras. \nSuch laws rather belong into Isabelle Main.\\<close>\n\ncontext boolean_algebra\nbegin\n    \nlemma shunt1: \"(x \\<sqinter> y \\<le> z) = (x \\<le> -y \\<squnion> z)\"\nproof standard\n  assume \"x \\<sqinter> y \\<le> z\"\n  hence  \"-y \\<squnion> (x \\<sqinter> y) \\<le> -y \\<squnion> z\"\n    using sup.mono by blast\n  hence \"-y \\<squnion> x \\<le> -y \\<squnion> z\"\n    by (simp add: sup_inf_distrib1)\n  thus \"x \\<le> -y \\<squnion> z\"\n    by simp\nnext\n  assume \"x \\<le> -y \\<squnion> z\"\n  hence \"x \\<sqinter> y \\<le> (-y \\<squnion> z) \\<sqinter> y\"\n    using inf_mono by auto\n  thus  \"x \\<sqinter> y \\<le> z\"\n    using inf.boundedE inf_sup_distrib2 by auto\nqed\n\nlemma shunt2: \"(x \\<sqinter> -y \\<le> z) = (x \\<le> y \\<squnion> z)\"\n  by (simp add: shunt1)\n\nlemma meet_shunt: \"(x \\<sqinter> y = \\<bottom>) = (x \\<le> -y)\"\n  by (simp add: eq_iff shunt1)\n  \nlemma join_shunt: \"(x \\<squnion> y = \\<top>) = (-x \\<le> y)\"\n  by (metis compl_sup compl_top_eq double_compl meet_shunt)\n\nlemma meet_shunt_var: \"(x - y = \\<bottom>) = (x \\<le> y)\"\n  by (simp add: diff_eq meet_shunt)\n\n\n\nend\n\nsubsection \\<open>Properties of Complete Lattices\\<close>\n\ndefinition \"Inf_closed_set X = (\\<forall>Y \\<subseteq> X. \\<Sqinter>Y \\<in> X)\"\n\ndefinition \"Sup_closed_set X = (\\<forall>Y \\<subseteq> X. \\<Squnion>Y \\<in> X)\"\n\ndefinition \"inf_closed_set X = (\\<forall>x \\<in> X. \\<forall>y \\<in> X. x \\<sqinter> y \\<in> X)\" \n\ndefinition \"sup_closed_set X = (\\<forall>x \\<in> X. \\<forall>y \\<in> X. x \\<squnion> y \\<in> X)\"\n\ntext \\<open>The following facts about complete lattices add to those in the Isabelle libraries.\\<close>\n\ncontext complete_lattice \nbegin\n\ntext \\<open>The translation between sup and Sup could be improved. The sup-theorems should be direct\nconsequences of Sup-ones. In addition, duality between sup and inf is currently not exploited.\\<close>\n\nlemma sup_Sup: \"x \\<squnion> y = \\<Squnion>{x,y}\"\n  by simp\n\nlemma inf_Inf: \"x \\<sqinter> y = \\<Sqinter>{x,y}\"\n  by simp\n\ntext \\<open>The next two lemmas are about Sups and Infs of indexed families. These are interesting for\niterations and fixpoints.\\<close>\n\nlemma fSup_unfold: \"(f::nat \\<Rightarrow> 'a) 0 \\<squnion> (\\<Squnion>n. f (Suc n)) = (\\<Squnion>n. f n)\"\n  apply (intro antisym sup_least)\n    apply (rule Sup_upper, force)\n   apply (rule Sup_mono, force)\n  apply (safe intro!: Sup_least)\n by (case_tac n, simp_all add: Sup_upper le_supI2)\n\nlemma fInf_unfold: \"(f::nat \\<Rightarrow> 'a) 0 \\<sqinter> (\\<Sqinter>n. f (Suc n)) = (\\<Sqinter>n. f n)\"\n  apply (intro antisym inf_greatest)\n  apply (rule Inf_greatest, safe)\n  apply (case_tac n)\n   apply simp_all\n  using Inf_lower inf.coboundedI2 apply force\n   apply (simp add: Inf_lower)\n  by (auto intro: Inf_mono)\n\nend\n\nlemma Sup_sup_closed: \"Sup_closed_set (X::'a::complete_lattice set) \\<Longrightarrow> sup_closed_set X\"\n  by (metis Sup_closed_set_def empty_subsetI insert_subsetI sup_Sup sup_closed_set_def)\n\nlemma Inf_inf_closed: \"Inf_closed_set (X::'a::complete_lattice set) \\<Longrightarrow> inf_closed_set X\"\n  by (metis Inf_closed_set_def empty_subsetI inf_Inf inf_closed_set_def insert_subset)\n\n\nsubsection \\<open>Sup- and Inf-Preservation\\<close>\n\ntext \\<open>Next, important notation for morphism between posets and lattices is introduced: \nsup-preservation, inf-preservation and related properties.\\<close>\n\nabbreviation Sup_pres :: \"('a::Sup \\<Rightarrow> 'b::Sup) \\<Rightarrow> bool\" where\n  \"Sup_pres f \\<equiv> f \\<circ> Sup = Sup \\<circ> (`) f\"\n\nabbreviation Inf_pres :: \"('a::Inf \\<Rightarrow> 'b::Inf) \\<Rightarrow> bool\" where\n  \"Inf_pres f \\<equiv> f \\<circ> Inf = Inf \\<circ> (`) f\"\n\nabbreviation sup_pres :: \"('a::sup \\<Rightarrow> 'b::sup) \\<Rightarrow> bool\" where\n  \"sup_pres f \\<equiv> (\\<forall>x y. f (x \\<squnion> y) = f x \\<squnion> f y)\"\n\nabbreviation inf_pres :: \"('a::inf \\<Rightarrow> 'b::inf) \\<Rightarrow> bool\" where\n \"inf_pres f \\<equiv> (\\<forall>x y. f (x \\<sqinter> y) = f x \\<sqinter> f y)\"\n\nabbreviation bot_pres :: \"('a::bot \\<Rightarrow> 'b::bot) \\<Rightarrow> bool\" where\n  \"bot_pres f \\<equiv> f \\<bottom> = \\<bottom>\"\n\nabbreviation top_pres :: \"('a::top \\<Rightarrow> 'b::top) \\<Rightarrow> bool\" where\n  \"top_pres f \\<equiv> f \\<top> = \\<top>\"\n\nabbreviation Sup_dual :: \"('a::Sup \\<Rightarrow> 'b::Inf) \\<Rightarrow> bool\" where\n  \"Sup_dual f \\<equiv> f \\<circ> Sup = Inf \\<circ> (`) f\"\n\nabbreviation Inf_dual :: \"('a::Inf \\<Rightarrow> 'b::Sup) \\<Rightarrow> bool\" where\n  \"Inf_dual f \\<equiv> f \\<circ> Inf = Sup \\<circ> (`) f\"\n\nabbreviation sup_dual :: \"('a::sup \\<Rightarrow> 'b::inf) \\<Rightarrow> bool\" where\n  \"sup_dual f \\<equiv> (\\<forall>x y. f (x \\<squnion> y) = f x \\<sqinter> f y)\"\n\nabbreviation inf_dual :: \"('a::inf \\<Rightarrow> 'b::sup) \\<Rightarrow> bool\" where\n \"inf_dual f \\<equiv> (\\<forall>x y. f (x \\<sqinter> y) = f x \\<squnion> f y)\"\n\nabbreviation bot_dual :: \"('a::bot \\<Rightarrow> 'b::top) \\<Rightarrow> bool\" where \n \"bot_dual f \\<equiv> f \\<bottom> = \\<top>\"\n\nabbreviation top_dual :: \"('a::top \\<Rightarrow> 'b::bot) \\<Rightarrow> bool\" where \n  \"top_dual f \\<equiv> f \\<top> = \\<bottom>\"\n\ntext \\<open>Inf-preservation and sup-preservation relate with duality.\\<close>\n\nlemma Inf_pres_map_dual_var: \n  \"Inf_pres f = Sup_pres (\\<partial>\\<^sub>F f)\"\n  for f :: \"'a::complete_lattice_with_dual \\<Rightarrow> 'b::complete_lattice_with_dual\"\nproof -\n  { fix x :: \"'a set\"\n    assume \"\\<partial> (f (\\<Sqinter> (\\<partial> ` x))) = (\\<Squnion>y\\<in>x. \\<partial> (f (\\<partial> y)))\" for x\n    then have \"\\<Sqinter> (f ` \\<partial> ` A) = f (\\<partial> (\\<Squnion> A))\" for A\n      by (metis (no_types) Sup_dual_def_var image_image invol_dual_var subset_dual)\n    then have \"\\<Sqinter> (f ` x) = f (\\<Sqinter> x)\"\n      by (metis Sup_dual_def_var subset_dual) }\n  then show ?thesis\n    by (auto simp add: map_dual_def fun_eq_iff Inf_dual_var Sup_dual_def_var image_comp)\nqed\n\nlemma Inf_pres_map_dual: \"Inf_pres = Sup_pres \\<circ> (\\<partial>\\<^sub>F::('a::complete_lattice_with_dual \\<Rightarrow> 'b::complete_lattice_with_dual) \\<Rightarrow> 'a \\<Rightarrow> 'b)\"\nproof-\n  {fix f::\"'a \\<Rightarrow> 'b\"\n  have \"Inf_pres f = (Sup_pres \\<circ> \\<partial>\\<^sub>F) f\"\n    by (simp add: Inf_pres_map_dual_var)}\n  thus ?thesis\n    by force\nqed\n\nlemma Sup_pres_map_dual_var: \n  fixes f :: \"'a::complete_lattice_with_dual \\<Rightarrow> 'b::complete_lattice_with_dual\"\n  shows \"Sup_pres f = Inf_pres (\\<partial>\\<^sub>F f)\"\n  by (metis Inf_pres_map_dual_var fun_dual5 map_dual_def)\n\nlemma Sup_pres_map_dual: \"Sup_pres = Inf_pres \\<circ> (\\<partial>\\<^sub>F::('a::complete_lattice_with_dual \\<Rightarrow> 'b::complete_lattice_with_dual) \\<Rightarrow> 'a \\<Rightarrow> 'b)\"\n  by (simp add: Inf_pres_map_dual comp_assoc map_dual_invol)\n\ntext \\<open>The following lemmas relate isotonicity of functions between complete lattices \nwith weak (left) preservation properties of sups and infs.\\<close>\n\nlemma fun_isol: \"mono f \\<Longrightarrow> mono ((\\<circ>) f)\"\n  by (simp add: le_fun_def mono_def)\n\nlemma fun_isor: \"mono f \\<Longrightarrow> mono (\\<lambda>x. x \\<circ> f)\"\n  by (simp add: le_fun_def mono_def)\n\nlemma Sup_sup_pres: \n  fixes f :: \"'a::complete_lattice \\<Rightarrow> 'b::complete_lattice\"\n  shows \"Sup_pres f \\<Longrightarrow> sup_pres f\"\n  by (metis (no_types, hide_lams) Sup_empty Sup_insert comp_apply image_insert sup_bot.right_neutral)\n\nlemma Inf_inf_pres: \n  fixes f :: \"'a::complete_lattice \\<Rightarrow> 'b::complete_lattice\"\n  shows\"Inf_pres f \\<Longrightarrow> inf_pres f\"\n  by (smt INF_insert Inf_empty Inf_insert comp_eq_elim inf_top.right_neutral)\n\nlemma Sup_bot_pres: \n  fixes f :: \"'a::complete_lattice \\<Rightarrow> 'b::complete_lattice\"\n  shows \"Sup_pres f \\<Longrightarrow> bot_pres f\"\n  by (metis SUP_empty Sup_empty comp_eq_elim)\n\nlemma Inf_top_pres: \n  fixes f :: \"'a::complete_lattice \\<Rightarrow> 'b::complete_lattice\"\n  shows \"Inf_pres f \\<Longrightarrow> top_pres f\"\n  by (metis INF_empty Inf_empty comp_eq_elim)\n\nlemma Sup_sup_dual: \n  fixes f :: \"'a::complete_lattice \\<Rightarrow> 'b::complete_lattice\"\n  shows \"Sup_dual f \\<Longrightarrow> sup_dual f\"\n  by (smt comp_eq_elim image_empty image_insert inf_Inf sup_Sup)    \n\nlemma Inf_inf_dual: \n  fixes f :: \"'a::complete_lattice \\<Rightarrow> 'b::complete_lattice\"\n  shows \"Inf_dual f \\<Longrightarrow> inf_dual f\"\n  by (smt comp_eq_elim image_empty image_insert inf_Inf sup_Sup)   \n\nlemma Sup_bot_dual: \n  fixes f :: \"'a::complete_lattice \\<Rightarrow> 'b::complete_lattice\"\n  shows \"Sup_dual f \\<Longrightarrow> bot_dual f\"\n  by (metis INF_empty Sup_empty comp_eq_elim)\n\nlemma Inf_top_dual: \n  fixes f :: \"'a::complete_lattice \\<Rightarrow> 'b::complete_lattice\"\n  shows \"Inf_dual f \\<Longrightarrow> top_dual f\"\n  by (metis Inf_empty SUP_empty comp_eq_elim)\n\ntext \\<open>However, Inf-preservation does not imply top-preservation and \nSup-preservation does not imply bottom-preservation.\\<close>\n\nlemma\n  fixes f :: \"'a::complete_lattice \\<Rightarrow> 'b::complete_lattice\"\n  shows \"Sup_pres f \\<Longrightarrow> top_pres f\" (*nitpick*)\n  oops\n\nlemma  \n  fixes f :: \"'a::complete_lattice \\<Rightarrow> 'b::complete_lattice\"\n  shows \"Inf_pres f \\<Longrightarrow> bot_pres f\" (*nitpick*)\n  oops\n\ncontext complete_lattice\nbegin\n\nlemma iso_Inf_subdistl: \n  fixes f :: \"'a \\<Rightarrow> 'b::complete_lattice\"\n  shows \"mono f \\<Longrightarrow>f \\<circ> Inf \\<le> Inf \\<circ> (`) f\"\n  by (simp add: complete_lattice_class.le_Inf_iff le_funI Inf_lower monoD)\n\nlemma iso_Sup_supdistl: \n  fixes f :: \"'a \\<Rightarrow> 'b::complete_lattice\" \n  shows \"mono f \\<Longrightarrow> Sup \\<circ> (`) f \\<le> f \\<circ> Sup\"\n  by (simp add: complete_lattice_class.Sup_le_iff le_funI Sup_upper monoD)\n\nlemma Inf_subdistl_iso: \n  fixes f :: \"'a \\<Rightarrow> 'b::complete_lattice\"\n  shows \"f \\<circ> Inf \\<le> Inf \\<circ> (`) f \\<Longrightarrow> mono f\"\n  unfolding mono_def le_fun_def comp_def by (metis complete_lattice_class.le_INF_iff Inf_atLeast atLeast_iff)\n\nlemma Sup_supdistl_iso: \n  fixes f :: \"'a \\<Rightarrow> 'b::complete_lattice\"\n  shows \"Sup \\<circ> (`) f \\<le> f \\<circ> Sup \\<Longrightarrow> mono f\"\n  unfolding mono_def le_fun_def comp_def by (metis complete_lattice_class.SUP_le_iff Sup_atMost atMost_iff)\n\nlemma supdistl_iso: \n  fixes f :: \"'a \\<Rightarrow> 'b::complete_lattice\"\n  shows \"(Sup \\<circ> (`) f \\<le> f \\<circ> Sup) = mono f\"\n  using Sup_supdistl_iso iso_Sup_supdistl by force\n\nlemma subdistl_iso: \n  fixes f :: \"'a \\<Rightarrow> 'b::complete_lattice\"\n  shows \"(f \\<circ> Inf \\<le> Inf \\<circ> (`) f) = mono f\"\n  using Inf_subdistl_iso iso_Inf_subdistl by force\n\nend\n\nlemma ord_iso_Inf_pres: \n  fixes f :: \"'a::complete_lattice \\<Rightarrow> 'b::complete_lattice\"\n  shows \"ord_iso f \\<Longrightarrow> Inf \\<circ> (`) f = f \\<circ> Inf\"\nproof-\n  let ?g = \"the_inv f\"\n  assume h: \"ord_iso f\"\n  hence a: \"mono ?g\"\n    by (simp add: ord_iso_the_inv)\n  {fix X :: \"'a::complete_lattice set\"\n    {fix y :: \"'b::complete_lattice\"\n   have \"(y \\<le> f (\\<Sqinter>X)) = (?g y \\<le> \\<Sqinter>X)\"\n     by (metis (mono_tags, lifting) UNIV_I f_the_inv_into_f h monoD ord_embed_alt ord_embed_inj ord_iso_alt)\n   also have \"... = (\\<forall>x \\<in> X. ?g y \\<le> x)\"\n    by (simp add: le_Inf_iff)\n  also have \"... = (\\<forall>x \\<in> X. y \\<le> f x)\"\n    by (metis (mono_tags, lifting) UNIV_I f_the_inv_into_f h monoD ord_embed_alt ord_embed_inj ord_iso_alt)\n  also have \"... = (y \\<le> \\<Sqinter> (f ` X))\"\n    by (simp add: le_INF_iff)\n  finally have \"(y \\<le> f (\\<Sqinter>X)) = (y \\<le> \\<Sqinter> (f ` X))\".}\n  hence \"f (\\<Sqinter>X) = \\<Sqinter> (f ` X)\"\n    by (meson dual_order.antisym order_refl)}\n  thus ?thesis\n    unfolding fun_eq_iff by simp\nqed\n\nlemma ord_iso_Sup_pres: \n  fixes f :: \"'a::complete_lattice \\<Rightarrow> 'b::complete_lattice\"\n  shows \"ord_iso f \\<Longrightarrow> Sup \\<circ> (`) f = f \\<circ> Sup\"\nproof-\n  let ?g = \"the_inv f\"\n  assume h: \"ord_iso f\"\n  hence a: \"mono ?g\"\n    by (simp add: ord_iso_the_inv)\n  {fix X :: \"'a::complete_lattice set\"\n    {fix y :: \"'b::complete_lattice\"\n   have \"(f (\\<Squnion>X) \\<le> y) = (\\<Squnion>X \\<le> ?g y)\"\n     by (metis (mono_tags, lifting) UNIV_I f_the_inv_into_f h monoD ord_embed_alt ord_embed_inj ord_iso_alt)\n   also have \"... = (\\<forall>x \\<in> X. x \\<le> ?g y)\"\n     by (simp add: Sup_le_iff)\n     also have \"... = (\\<forall>x \\<in> X. f x \\<le> y)\"\n    by (metis (mono_tags, lifting) UNIV_I f_the_inv_into_f h monoD ord_embed_alt ord_embed_inj ord_iso_alt)\n  also have \"... = (\\<Squnion> (f ` X) \\<le> y)\"\n    by (simp add: SUP_le_iff)\n  finally have \"(f (\\<Squnion>X) \\<le> y) = (\\<Squnion> (f ` X) \\<le> y)\".}\n  hence \"f (\\<Squnion>X) = \\<Squnion> (f ` X)\"\n    by (meson dual_order.antisym order_refl)}\n  thus ?thesis\n    unfolding fun_eq_iff by simp\nqed\n\ntext \\<open>Right preservation of sups and infs is trivial.\\<close>\n\nlemma fSup_distr: \"Sup_pres (\\<lambda>x. x \\<circ> f)\"\n  unfolding fun_eq_iff by (simp add: image_comp)\n\nlemma fSup_distr_var: \"\\<Squnion>F \\<circ> g = (\\<Squnion>f \\<in> F. f \\<circ> g)\"\n  unfolding fun_eq_iff by (simp add: image_comp)\n\nlemma fInf_distr: \"Inf_pres (\\<lambda>x. x \\<circ> f)\"\n  unfolding fun_eq_iff comp_def\n  by (smt INF_apply Inf_fun_def Sup.SUP_cong) \n\nlemma fInf_distr_var: \"\\<Sqinter>F \\<circ> g = (\\<Sqinter>f \\<in> F. f \\<circ> g)\"\n  unfolding fun_eq_iff comp_def\n  by (smt INF_apply INF_cong INF_image Inf_apply image_comp image_def image_image)\n\n\ntext \\<open>The next set of lemma revisits the preservation properties in the function space.\\<close>\n\nlemma fSup_subdistl: \n  assumes \"mono (f::'a::complete_lattice \\<Rightarrow> 'b::complete_lattice)\"\n  shows \"Sup \\<circ> (`) ((\\<circ>) f) \\<le> (\\<circ>) f \\<circ> Sup\"\n  using assms by (simp add: fun_isol supdistl_iso) \n\nlemma fSup_subdistl_var: \n  fixes f :: \"'a::complete_lattice \\<Rightarrow> 'b::complete_lattice\"\n  shows  \"mono f \\<Longrightarrow> (\\<Squnion>g \\<in> G. f \\<circ> g) \\<le> f \\<circ> \\<Squnion>G\"\n  by (simp add: fun_isol mono_Sup)\n\nlemma fInf_subdistl: \n  fixes f :: \"'a::complete_lattice \\<Rightarrow> 'b::complete_lattice\"\n  shows  \"mono f \\<Longrightarrow> (\\<circ>) f \\<circ> Inf \\<le> Inf \\<circ> (`) ((\\<circ>) f)\"\n  by (simp add: fun_isol subdistl_iso)\n\nlemma fInf_subdistl_var: \n  fixes f :: \"'a::complete_lattice \\<Rightarrow> 'b::complete_lattice\"\n  shows \"mono f \\<Longrightarrow> f \\<circ> \\<Sqinter>G \\<le> (\\<Sqinter>g \\<in> G. f \\<circ> g)\"\n  by (simp add: fun_isol mono_Inf)\n\nlemma fSup_distl: \"Sup_pres f \\<Longrightarrow> Sup_pres ((\\<circ>) f)\"\n  unfolding fun_eq_iff by (simp add: image_comp)\n\nlemma fSup_distl_var: \"Sup_pres f \\<Longrightarrow> f \\<circ> \\<Squnion>G = (\\<Squnion>g \\<in> G. f \\<circ> g)\"\n  unfolding fun_eq_iff by (simp add: image_comp)\n\nlemma fInf_distl: \"Inf_pres f \\<Longrightarrow> Inf_pres ((\\<circ>) f)\"\n  unfolding fun_eq_iff by (simp add: image_comp)\n\nlemma fInf_distl_var: \"Inf_pres f \\<Longrightarrow> f \\<circ> \\<Sqinter>G = (\\<Sqinter>g \\<in> G. f \\<circ> g)\"\n  unfolding fun_eq_iff by (simp add: image_comp)\n\ntext \\<open>Downsets preserve infs whereas upsets preserve sups.\\<close>\n\nlemma Inf_pres_downset: \"Inf_pres (\\<down>::'a::complete_lattice_with_dual \\<Rightarrow> 'a set)\"\n  unfolding downset_prop fun_eq_iff\n  by (safe, simp_all add: le_Inf_iff)\n \n\n\ntext \\<open>Images of Sup-morphisms are closed under Sups and images of Inf-morphisms are closed under Infs.\\<close>\n\nlemma Sup_pres_Sup_closed: \"Sup_pres f \\<Longrightarrow> Sup_closed_set (range f)\"\n  by (metis (mono_tags, lifting) Sup_closed_set_def comp_eq_elim range_eqI subset_image_iff)\n\nlemma Inf_pres_Inf_closed: \"Inf_pres f \\<Longrightarrow> Inf_closed_set (range f)\"\n  by (metis (mono_tags, lifting) Inf_closed_set_def comp_eq_elim range_eqI subset_image_iff)\n\ntext \\<open>It is well known that functions into complete lattices form complete lattices. Here, such results are shown for\nthe subclasses of isotone functions, where additional closure conditions must be respected.\\<close>\n\ntypedef (overloaded) 'a iso = \"{f::'a::order \\<Rightarrow> 'a::order. mono f}\"\n  by (metis Abs_ord_homset_cases ord_homset_def)\n\nsetup_lifting type_definition_iso\n\ninstantiation iso :: (complete_lattice) complete_lattice\nbegin\n\nlift_definition Inf_iso :: \"'a::complete_lattice iso set \\<Rightarrow> 'a iso\" is Sup\n  by (metis (mono_tags, lifting) SUP_subset_mono Sup_apply mono_def subsetI)\n\nlift_definition Sup_iso :: \"'a::complete_lattice iso set \\<Rightarrow> 'a iso\" is Inf\n  by (smt INF_lower2 Inf_apply le_INF_iff mono_def)\n\nlift_definition bot_iso :: \"'a::complete_lattice iso\" is \"\\<top>\"\n  by (simp add: monoI)\n\nlift_definition sup_iso :: \"'a::complete_lattice iso \\<Rightarrow> 'a iso \\<Rightarrow> 'a iso\" is inf\n  by (smt inf_apply inf_mono monoD monoI)\n\nlift_definition top_iso :: \"'a::complete_lattice iso\" is \"\\<bottom>\"\n  by (simp add: mono_def)\n\nlift_definition inf_iso :: \"'a::complete_lattice iso \\<Rightarrow> 'a iso \\<Rightarrow> 'a iso\" is sup\n  by (smt mono_def sup.mono sup_apply)\n\nlift_definition less_eq_iso :: \"'a::complete_lattice iso \\<Rightarrow> 'a iso \\<Rightarrow> bool\" is \"(\\<ge>)\".\n\nlift_definition less_iso :: \"'a::complete_lattice iso \\<Rightarrow> 'a iso \\<Rightarrow> bool\" is \"(>)\".\n\ninstance\n  by (intro_classes; transfer, simp_all add: less_fun_def Sup_upper Sup_least Inf_lower Inf_greatest)\n\nend\n\ntext \\<open>Duality has been baked into this result because of its relevance for predicate transformers. A proof\nwhere Sups are mapped to Sups and Infs to Infs is certainly possible, but two instantiation of the same type\nand the same classes are unfortunately impossible. Interpretations could be used instead.\n\nA corresponding result for Inf-preseving functions and Sup-lattices, is proved in components on transformers,\nas more advanced properties about Inf-preserving functions are needed.\\<close>\n\n\nsubsection \\<open>Alternative Definitions for Complete Boolean Algebras\\<close>\n\ntext \\<open>The current definitions of complete boolean algebras deviates from that in most textbooks in that\na distributive law with infinite sups and infinite infs is used. There are interesting applications, for instance \nin topology, where weaker laws are needed --- for instance for frames and locales.\\<close>\n\nclass complete_heyting_algebra = complete_lattice +\n  assumes ch_dist: \"x \\<sqinter> \\<Squnion>Y = (\\<Squnion>y \\<in> Y. x \\<sqinter> y)\"\n\ntext \\<open>Complete Heyting algebras are also known as frames or locales (they differ with respect to their morphisms).\\<close>\n\nclass complete_co_heyting_algebra = complete_lattice +\n  assumes co_ch_dist: \"x \\<squnion> \\<Sqinter>Y = (\\<Sqinter>y \\<in> Y. x \\<squnion> y)\"\n\nclass complete_boolean_algebra_alt = complete_lattice + boolean_algebra\n\ninstance set :: (type) complete_boolean_algebra_alt..\n\ncontext complete_boolean_algebra_alt\nbegin\n\nsubclass complete_heyting_algebra\nproof\n  fix x Y \n  {fix t\n    have \"(x \\<sqinter> \\<Squnion>Y \\<le> t) = (\\<Squnion>Y \\<le> -x \\<squnion> t)\"\n      by (simp add: inf.commute shunt1[symmetric])\n    also have \"... = (\\<forall>y \\<in> Y. y \\<le> -x \\<squnion> t)\"\n      using Sup_le_iff by blast\n    also have \"... = (\\<forall>y \\<in> Y. x \\<sqinter> y \\<le> t)\"\n      by (simp add: inf.commute shunt1)\n    finally have \"(x \\<sqinter> \\<Squnion>Y \\<le> t) = ((\\<Squnion>y\\<in>Y. x \\<sqinter> y) \\<le> t)\"\n      by (simp add: local.SUP_le_iff)}\n  thus \"x \\<sqinter> \\<Squnion>Y = (\\<Squnion>y\\<in>Y. x \\<sqinter> y)\"\n    using eq_iff by blast\nqed\n\nsubclass complete_co_heyting_algebra\n  apply unfold_locales\n  apply (rule antisym)\n   apply (simp add: INF_greatest Inf_lower2)\n  by (meson eq_refl le_INF_iff le_Inf_iff shunt2)\n\nlemma de_morgan1: \"-(\\<Squnion>X) = (\\<Sqinter>x \\<in> X. -x)\"\nproof-\n  {fix y\n  have \"(y \\<le> -(\\<Squnion>X)) = (\\<Squnion>X \\<le> -y)\"\n    using compl_le_swap1 by blast\n  also have \"... = (\\<forall>x \\<in> X. x \\<le> -y)\"\n    by (simp add: Sup_le_iff)\n  also have \"... = (\\<forall>x \\<in> X. y \\<le> -x)\"\n    using compl_le_swap1 by blast\n  also have \"... = (y \\<le> (\\<Sqinter>x \\<in> X. -x))\"\n    using le_INF_iff by force\n  finally have \"(y \\<le> -(\\<Squnion>X)) = (y \\<le>(\\<Sqinter>x \\<in> X. -x))\".}\n  thus ?thesis\n    using antisym by blast\nqed\n\nlemma de_morgan2: \"-(\\<Sqinter>X) = (\\<Squnion>x \\<in> X. -x)\"\n  by (metis de_morgan1 ba_dual.dual_iff ba_dual.image_dual pointfree_idE)\n\nend\n\nclass complete_boolean_algebra_alt_with_dual = complete_lattice_with_dual + complete_boolean_algebra_alt\n\ninstantiation set :: (type) complete_boolean_algebra_alt_with_dual\nbegin\n\ndefinition dual_set :: \"'a set \\<Rightarrow> 'a set\" where\n  \"dual_set = uminus\"\n\ninstance\n  by intro_classes (simp_all add: ba_dual.inj_dual dual_set_def comp_def uminus_Sup id_def)\n\nend\n\ncontext complete_boolean_algebra_alt\nbegin\n\nsublocale cba_dual: complete_boolean_algebra_alt_with_dual _ _ _ _ _ _ _ _ uminus _ _\n  by unfold_locales (auto simp: de_morgan2 de_morgan1)\n\nend\n\n\nsubsection \\<open>Atomic Boolean Algebras\\<close>\n\ntext \\<open>Next, atomic boolean algebras are defined.\\<close>\n\ncontext bounded_lattice\nbegin\n\ntext \\<open>Atoms are covers of bottom.\\<close>\n\ndefinition \"atom x = (x \\<noteq> \\<bottom> \\<and> \\<not>(\\<exists>y. \\<bottom> < y \\<and> y < x))\"\n\ndefinition \"atom_map x = {y. atom y \\<and> y \\<le> x}\"\n\nlemma atom_map_def_var: \"atom_map x = \\<down>x \\<inter> Collect atom\"\n  unfolding atom_map_def downset_def downset_set_def comp_def atom_def by fastforce\n\nlemma atom_map_atoms: \"\\<Union>(range atom_map) = Collect atom\"\n  unfolding atom_map_def atom_def by auto\n\nend\n\ntypedef (overloaded) 'a atoms = \"range (atom_map::'a::bounded_lattice \\<Rightarrow> 'a set)\"\n  by blast\n\nsetup_lifting type_definition_atoms\n\ndefinition at_map :: \"'a::bounded_lattice \\<Rightarrow> 'a atoms\" where\n  \"at_map = Abs_atoms \\<circ> atom_map\"\n\nclass atomic_boolean_algebra = boolean_algebra +\n  assumes atomicity: \"x \\<noteq> \\<bottom> \\<Longrightarrow> (\\<exists>y. atom y \\<and> y \\<le> x)\"\n\nclass complete_atomic_boolean_algebra = complete_lattice + atomic_boolean_algebra\n\nbegin\n\nsubclass complete_boolean_algebra_alt..\n\nend\n\ntext \\<open>Here are two equivalent definitions for atoms; first in boolean algebras, and then in complete \nboolean algebras.\\<close>\n\ncontext boolean_algebra\nbegin\n\ntext \\<open>The following two conditions are taken from Koppelberg's book~\\cite{Koppelberg89}.\\<close>\n\nlemma atom_neg: \"atom x \\<Longrightarrow> x \\<noteq> \\<bottom> \\<and> (\\<forall>y z. x \\<le> y \\<or> x \\<le> -y)\"\n  by (metis atom_def dual_order.order_iff_strict inf.cobounded1 inf.commute meet_shunt)\n\nlemma atom_sup: \"(\\<forall>y. x \\<le> y \\<or> x \\<le> -y) \\<Longrightarrow> (\\<forall>y z. (x \\<le> y \\<or> x \\<le> z) = (x \\<le> y \\<squnion> z))\"\n  by (metis inf.orderE le_supI1 shunt2)\n\nlemma sup_atom: \"x \\<noteq> \\<bottom> \\<Longrightarrow> (\\<forall>y z. (x \\<le> y \\<or> x \\<le> z) = (x \\<le> y \\<squnion> z)) \\<Longrightarrow> atom x\"\n  unfolding atom_def apply clarsimp by (metis bot_less inf.absorb2 less_le_not_le meet_shunt sup_compl_top)\n\nlemma atom_sup_iff: \"atom x = (x \\<noteq> \\<bottom> \\<and> (\\<forall>y z. (x \\<le> y \\<or> x \\<le> z) = (x \\<le> y \\<squnion> z)))\"\n  by  (standard, auto simp add: atom_neg atom_sup sup_atom)  \n\nlemma atom_neg_iff: \"atom x = (x \\<noteq> \\<bottom> \\<and> (\\<forall>y z. x \\<le> y \\<or> x \\<le> -y))\"\n  by  (standard, auto simp add: atom_neg atom_sup sup_atom)\n\nlemma atom_map_bot_pres: \"atom_map \\<bottom> = {}\"\n  using atom_def atom_map_def le_bot by auto\n\nlemma atom_map_top_pres: \"atom_map \\<top> = Collect atom\"\n  using atom_map_def by auto\n\nend\n\ncontext complete_boolean_algebra_alt\nbegin\n\nlemma atom_Sup: \"\\<And>Y. x \\<noteq> \\<bottom> \\<Longrightarrow> (\\<forall>y. x \\<le> y \\<or> x \\<le> -y) \\<Longrightarrow> ((\\<exists>y \\<in> Y. x \\<le> y) = (x \\<le> \\<Squnion>Y))\"\n  by (metis Sup_least Sup_upper2 compl_le_swap1 le_iff_inf meet_shunt)\n\nlemma Sup_atom: \"x \\<noteq> \\<bottom> \\<Longrightarrow> (\\<forall>Y. (\\<exists>y \\<in> Y. x \\<le> y) = (x \\<le> \\<Squnion>Y)) \\<Longrightarrow> atom x\"\nproof-\n  assume h1: \"x \\<noteq> \\<bottom>\"\n  and h2: \"\\<forall>Y. (\\<exists>y \\<in> Y. x \\<le> y) = (x \\<le> \\<Squnion>Y)\"\n  hence \"\\<forall>y z. (x \\<le> y \\<or> x \\<le> z) = (x \\<le> y \\<squnion> z)\"\n\n    by (smt insert_iff sup_Sup sup_bot.right_neutral)\n  thus \"atom x\"\n    by (simp add: h1 sup_atom)\nqed\n\nlemma atom_Sup_iff: \"atom x = (x \\<noteq> \\<bottom> \\<and> (\\<forall>Y. (\\<exists>y \\<in> Y. x \\<le> y) = (x \\<le> \\<Squnion>Y)))\"\n  by standard (auto simp: atom_neg atom_Sup Sup_atom)\n\nend\n\nend\n\n\n\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/Order_Lattice_Props/Order_Lattice_Props.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8918110540642805, "lm_q2_score": 0.800692004473946, "lm_q1q2_score": 0.7140659804907513}}
{"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_MSortTDCount\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 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\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 (msorttd 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_MSortTDCount.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088025362857, "lm_q2_score": 0.7690802370707283, "lm_q1q2_score": 0.7140208619531575}}
{"text": "theory excerise3\n  imports Main\nbegin\n\nlemma \"\\<lbrakk> xs @ zs = ys @ xs; [] @ xs = [] @ [] \\<rbrakk> \\<Longrightarrow> ys = zs\"\n  apply simp\n  done\n\nlemma \"\\<forall> x. f x = g (f (g x)) \\<Longrightarrow> f [] = f [] @ []\"\n  apply (simp (no_asm))\n  done\n\ndefinition xor :: \"bool \\<Rightarrow> bool \\<Rightarrow> bool\" where\n\"xor A B \\<equiv> (A \\<and> \\<not> B) \\<or> (\\<not> A \\<and> B)\"\n\nlemma \"xor A (\\<not> A)\"\n  apply(simp only: xor_def)\n  apply(simp add: xor_def)\n  done\n\nlemma \"(let xs = [] in xs@ys@xs) = ys\"\n  apply(simp add: Let_def)\n  done\n\nlemma hd_Cons_tl[simp]: \"xs \\<noteq> [] \\<Longrightarrow> hd xs # tl xs = xs\"\n  apply(case_tac xs, simp, simp)\n  done\n\nlemma \"\\<forall> xs. if xs = [] then rev xs = [] else rev xs \\<noteq> []\"\n  apply(split split_if)\n  apply(simp)\n  done\n\nlemma \"(case xs of [] \\<Rightarrow> zs | y#ys \\<Rightarrow> y#(ys@zs)) = xs@zs\"\n  apply(simp split: list.split)\n  done\n\nlemma \"if xs = [] then ys \\<noteq> [] else ys = [] \\<Longrightarrow> xs @ ys \\<noteq> []\"\n  apply (split split_if_asm)\n  apply simp\n  apply simp\n  done\n\nprimrec 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 \"\\<forall> ys. itrev xs ys = rev xs @ ys\"\n  apply(induct_tac xs, simp_all)\n  done\n\nprimrec add :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\" where\n  \"add m 0 = m\"|\n  \"add m (Suc n) = add (Suc m) n\"\n\n\n\nlemma \"add m n = m + n\"\n  apply(induct_tac n, simp_all)\n  done\n\ndatatype 'a tree = Tip | Node \"'a tree\" 'a \"'a tree\"\n\nprimrec flatten2 :: \"'a tree \\<Rightarrow> 'a list => 'a list\" where\n  \"flatten2 Tip ys                 = ys\"|\n  \"flatten2 (Node left a right) ys = flatten2 left (a # (flatten2 right ys))\"\n\nprimrec flatten :: \"'a tree \\<Rightarrow> 'a list\"\n  where\n  \"flatten Tip = []\" |\n  \"flatten (Node l x r) = (flatten l) @ (x # (flatten r))\"\n\n\nlemma [simp]:\"\\<forall> xs. flatten2 t xs = flatten t @ xs\"\n    apply (induct_tac t, simp_all)\n    done\n\n\nlemma \"flatten2 t [] = flatten t\"\n  apply simp\n  done\n\ntype_synonym 'v binop = \"'v \\<Rightarrow> 'v \\<Rightarrow> 'v\"\ndatatype ('a, 'v) expr = Cex 'v\n  | Vex 'a\n  | Bex \"'v binop\" \"('a, 'v)expr\" \"('a, 'v)expr\"\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\ndatatype ('a, 'v) instr = Const 'v\n  | Load 'a\n  | Apply \"'v binop\"\n\nprimrec exec :: \"('a, 'v)instr list \\<Rightarrow> ('a \\<Rightarrow> 'v) \\<Rightarrow> 'v list \\<Rightarrow> 'v list\"\n  where\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\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\nlemma exec_ap[simp]: \"\\<forall> vs. exec (xs@ys) s vs = exec ys s (exec xs s vs)\"\n  apply(induct_tac xs, simp_all split: instr.split)\n  done\n\ntheorem \"\\<forall> vs. exec (compile e) s vs = (value e s) # vs\"\n  apply(induct_tac e, simp_all)\n  done\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\n  and 'a bexp = Less \"'a aexp\" \"'a aexp\"\n  | And \"'a bexp\" \"'a bexp\"\n  | Neg \"'a bexp\"\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 = (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\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) = 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\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)\"\n  apply (induct_tac a and b)\n  apply simp_all\n  done\n\n(* primrec norma:: \"'a aexp \\<Rightarrow> 'a aexp\" *)\n(*  (* and *) *)\n(*  (*  normb:: \"'a bexp \\<Rightarrow> 'a aexp \\<Rightarrow> 'a aexp \\<Rightarrow> 'a aexp\" *) *)\n(*   where *)\n(*   \"norma (IF b a1 a2) = (case b of *)\n(*   Less la1 la2 \\<Rightarrow> IF (Less (norma la1) (norma la2)) (norma a1) (norma a2) *)\n(*   | And b1 b2 \\<Rightarrow> norma (IF b1 (IF b2 a1 a2) a2) *)\n(*   | Neg b' \\<Rightarrow> norma (IF b' (norma a2) (norma a1))) \" | *)\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) at ae = IF (Less (norma a1) (norma a2)) (norma at) (norma ae)\" | *)\n  (* \"normb (And b1 b2) at ae = (normb b1 (IF (normb b2 at ae))   (norma ae))\" | *)\n  (* \"normb (Neg b) at ae = IF b (norma at) (norma at)\" *)\n\n\ndatatype ('v, 'f)\"term\" = Var 'v | App 'f \"('v, 'f)term list\"\n\nprimrec\nsubst  :: \"('v \\<Rightarrow> ('v, 'f)term) \\<Rightarrow> ('v, 'f)term      \\<Rightarrow> ('v, 'f)term\" and\nsubsts :: \"('v \\<Rightarrow> ('v, 'f)term) \\<Rightarrow> ('v, 'f)term list \\<Rightarrow> ('v, 'f)term list\"\nwhere\n  \"subst s (Var x) = s x\" |\n  subst_App:\n  \"subst s (App f ts) = App f (substs s ts)\" |\n\n  \"substs s [] = []\" |\n  \"substs s (t#ts) = subst s t # substs s ts\"\n\n\n\nlemma subst_id: \"subst  Var t  = (t ::('v, 'f)term) \\<and>\n  substs Var ts = (ts::('v, 'f)term list)\"\n  apply(induct_tac t and ts, simp_all)\n  done\n\nlemma \"subst (Var \\<circ> f \\<circ> g) t = subst (Var \\<circ> f) (subst (Var \\<circ> g) t)\"\n  apply(induct_tac t)\n  apply simp\n  apply simp\n  apply simp\n  apply simp\n  done\n\n\nprimrec trev:: \"('v, 'f) term \\<Rightarrow> ('v, 'f) term\" and\n  trevs:: \"('v, 'f) term list \\<Rightarrow> ('v, 'f) term list \\<Rightarrow> ('v, 'f) term list\"\n  where\n  \"trev (Var x) = Var x\" |\n  \"trev (App f ts) = App f (trevs ts [])\" |\n\n  \"trevs [] ts' = ts'\" |\n  \"trevs (t#ts) ts' = trevs ts ((trev t) # ts')\"\n\n\n\nlemma [simp]: \"subst s (App f ts) = App f (map (subst s) ts)\"\n  apply (induct_tac ts, simp_all)\n  done\n\ndeclare subst_App [simp del]\n\ndatatype ('a, 'i) bigtree = Tip | Br 'a \"'i \\<Rightarrow> ('a, 'i) bigtree\"\n\nprimrec map_bt ::\"('a \\<Rightarrow> 'b) \\<Rightarrow> ('a, 'i)bigtree \\<Rightarrow> ('b, 'i)bigtree\"\n  where\n  \"map_bt f Tip = Tip\" |\n  \"map_bt f (Br a F) = Br (f a) (\\<lambda>i. map_bt f (F i))\"\n\nlemma \"map_bt (g \\<circ> f) T = map_bt g (map_bt f T)\"\n  apply(induct_tac T, simp_all)\n  done\n\ndatatype ('a, 'v)trie = Trie \"'v option\" \"('a * ('a, 'v) trie) list\"\n\nprimrec \"trvalue\" :: \"('a, 'v)trie \\<Rightarrow> 'v option\" where\n  \"trvalue (Trie ov al) = ov\"\n\nprimrec tralist :: \"('a, 'v)trie \\<Rightarrow> ('a * ('a, 'v)trie)list\" where \n  \"tralist (Trie ov al) = al\"\n\nprimrec assoc:: \"('key * 'val)list \\<Rightarrow> 'key \\<Rightarrow> 'val option\"\n  where\n  \"assoc [] x = None\" |\n  \"assoc (p#ps) x = (let (a, b) = p in\n                    if a=x then Some b else assoc ps x)\"\n\nprimrec lookup :: \"('a, 'v)trie \\<Rightarrow> 'a list \\<Rightarrow> 'v option\"\n  where\n  \"lookup t [] = trvalue t\" |\n  \"lookup t (a#as) = (case assoc (tralist t) a of\n  None \\<Rightarrow> None\n  | Some at \\<Rightarrow> lookup at as)\"\n\n\nlemma [simp]: \"lookup (Trie None []) as = None\"\n  apply(induct_tac as, simp_all)\n  done\n\nprimrec update :: \"('a, 'v)trie \\<Rightarrow> 'a list \\<Rightarrow> 'v \\<Rightarrow> ('a, 'v)trie\"\nwhere\n\"update t [] v = Trie (Some v) (tralist t)\" |\n\"update t (a#as) v = (let tt = (case assoc (tralist t) a of\n  None \\<Rightarrow> Trie None [] | Some at \\<Rightarrow> at)\n  in Trie (trvalue t) ((a, update tt as v)# tralist t))\"\n\ndeclare Let_def[simp] option.split[split]\n\ntheorem \"\\<forall> t v bs. lookup (update t as v) bs = \n  (if as = bs then Some v else lookup t bs)\"\n  apply (induct_tac as , auto)\n  apply(case_tac[!] bs, auto)\n  done\n\nprimrec update2 :: \"('a, 'v)trie \\<Rightarrow> 'a list \\<Rightarrow> 'v option \\<Rightarrow> ('a, 'v)trie\"\nwhere\n\"update2 t [] v = Trie v (tralist t)\" |\n\"update2 t (a#as) v = (let tt = (case assoc (tralist t) a of\n  None \\<Rightarrow> Trie None [] | Some at \\<Rightarrow> at)\n  in Trie (trvalue t) ((a, update2 tt as v)# tralist t))\"\n\ntheorem \"\\<forall> t v bs. lookup (update2 t as (Some v)) bs = \n  (if as = bs then Some v else lookup t bs)\"\n  apply (induct_tac as , auto)\n  apply(case_tac[!] bs, auto)\n  done\n\ntheorem \"\\<forall> t v bs. lookup (update2 t as None) bs = \n  (if as = bs then None else lookup t bs)\"\n  apply (induct_tac as , auto)\n  apply(case_tac[!] bs, auto)\n  done\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\nfun sep :: \"'a \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where\n  \"sep a [] = []\" |\n  \"sep a [x] = [x]\" |\n  \"sep a (x#y#zs) = x # a # sep a (y#zs)\"\n\nfun last :: \"'a list \\<Rightarrow> 'a\" where\n  \"last [x] = x\" |\n  \"last (_#y#zs) = last (y#zs)\"\n\nfun sep1 :: \"'a \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where\n  \"sep1 a (x#y#zs) = x # a # sep1 a (y#zs)\" |\n  \"sep1 _ xs       = xs\"\n\nfun swap12 :: \"'a list \\<Rightarrow> 'a list\" where\n  \"swap12 (x#y#zs) = y#x#zs\" |\n  \"swap12 zs       = zs\"\n\nthm sep.simps\n\nfun ack2 :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\" where\n  \"ack2 n 0 = Suc n\" |\n  \"ack2 0 (Suc m) = ack2 (Suc 0) m\" |\n  \"ack2 (Suc n) (Suc m) = ack2 (ack2 n (Suc m)) m\"\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\nfun gcd1 :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\" where\n  \"gcd1 m 0 = m\" | \n  \"gcd1 m n = gcd1 n (m mod n)\"\n\n\nfun gcd2 :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\" where\n  \"gcd2 m n = (case n = 0 of True \\<Rightarrow> m | False \\<Rightarrow> gcd2 n (m mod n))\"\n\nlemma [simp]: \"gcd m 0 = m\"\n  apply(simp)\n  done\n\nlemma [simp]: \"n \\<noteq> 0 \\<Longrightarrow> gcd m n = gcd n (m mod n)\"\n  apply simp\n  done\n\ndeclare gcd.simps [simp del]\n\nlemma \"map f (sep x xs) = sep (f x) (map f xs)\"\n  apply(induct_tac x xs rule: sep.induct)\n  apply (simp_all)\n  done\n\n\n\n\n\nend", "meta": {"author": "KeenS", "repo": "Isabelle", "sha": "3411f313acf33fb18d2229906b4fd1ea5e8f9033", "save_path": "github-repos/isabelle/KeenS-Isabelle", "path": "github-repos/isabelle/KeenS-Isabelle/Isabelle-3411f313acf33fb18d2229906b4fd1ea5e8f9033/3.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869981319862, "lm_q2_score": 0.8152324803738429, "lm_q1q2_score": 0.7139700067663013}}
{"text": "theory Function_Ring\n  imports \"HOL-Algebra.Ring\" \"HOL-Library.FuncSet\" \"HOL-Algebra.Module\"\nbegin\n\ntext\\<open>\n  This theory formalizes basic facts about the ring of extensional functions from a fixed set to\n  a fixed ring. This will be useful for providing a generic framework for various constructions\n  related to the $p$-adics such as polynomial evaluation and sequences. The rings of semialgebraic\n  functions will be defined as subrings of these function rings, which will be necessary for the\n  proof of $p$-adic quantifier elimination.\n\\<close>\n\n(**************************************************************************************************)\n(**************************************************************************************************)\nsection\\<open>The Ring of Extensional Functions from a Fixed Base Set to a Fixed Base Ring\\<close>\n(**************************************************************************************************)\n(**************************************************************************************************)\n\n  (**************************************************************************************************)\n  (**************************************************************************************************)\n  subsection\\<open>Basic Operations on Extensional Functions\\<close>\n  (**************************************************************************************************)\n  (**************************************************************************************************)\n\ndefinition function_mult:: \"'c set \\<Rightarrow> ('a, 'b) ring_scheme \\<Rightarrow> ('c \\<Rightarrow> 'a) \\<Rightarrow> ('c \\<Rightarrow> 'a) \\<Rightarrow> ('c \\<Rightarrow> 'a)\" where\n\"function_mult S R f g = (\\<lambda>x \\<in> S. (f x) \\<otimes>\\<^bsub>R\\<^esub> (g x))\"\n\nabbreviation(input) ring_function_mult:: \"('a, 'b) ring_scheme \\<Rightarrow> ('a \\<Rightarrow> 'a) \\<Rightarrow> ('a \\<Rightarrow> 'a) \\<Rightarrow> ('a \\<Rightarrow> 'a)\" where\n\"ring_function_mult R f g \\<equiv> function_mult (carrier R) R f g\"\n\ndefinition function_add:: \"'c set \\<Rightarrow> ('a, 'b) ring_scheme \\<Rightarrow> ('c \\<Rightarrow> 'a) \\<Rightarrow> ('c \\<Rightarrow> 'a) \\<Rightarrow> ('c \\<Rightarrow> 'a)\" where\n\"function_add S R f g = (\\<lambda>x \\<in> S. (f x) \\<oplus>\\<^bsub>R\\<^esub> (g x))\"\n\nabbreviation(input) ring_function_add:: \"('a, 'b) ring_scheme \\<Rightarrow> ('a \\<Rightarrow> 'a) \\<Rightarrow> ('a \\<Rightarrow> 'a) \\<Rightarrow> ('a \\<Rightarrow> 'a)\" where\n\"ring_function_add R f g \\<equiv> function_add (carrier R) R f g\"\n\ndefinition function_one:: \"'c set \\<Rightarrow> ('a, 'b) ring_scheme \\<Rightarrow> ('c \\<Rightarrow> 'a)\" where\n\"function_one S R = (\\<lambda>x \\<in> S. \\<one>\\<^bsub>R\\<^esub>)\"\n\nabbreviation(input) ring_function_one :: \"('a, 'b) ring_scheme \\<Rightarrow> ('a \\<Rightarrow> 'a)\" where\n\"ring_function_one R \\<equiv> function_one (carrier R) R\"\n\ndefinition function_zero:: \"'c set \\<Rightarrow> ('a, 'b) ring_scheme \\<Rightarrow> ('c \\<Rightarrow> 'a)\" where\n\"function_zero S R = (\\<lambda>x \\<in> S. \\<zero>\\<^bsub>R\\<^esub>)\"\n\nabbreviation(input) ring_function_zero :: \"('a, 'b) ring_scheme \\<Rightarrow> ('a \\<Rightarrow> 'a)\" where\n\"ring_function_zero R \\<equiv> function_zero (carrier R) R\"\n\ndefinition function_uminus:: \"'c set \\<Rightarrow> ('a, 'b) ring_scheme \\<Rightarrow> ('c \\<Rightarrow> 'a) \\<Rightarrow> ('c \\<Rightarrow> 'a)\" where\n\"function_uminus S R a = (\\<lambda> x \\<in> S. \\<ominus>\\<^bsub>R\\<^esub> (a x))\"\n\ndefinition ring_function_uminus:: \" ('a, 'b) ring_scheme \\<Rightarrow> ('a \\<Rightarrow> 'a) \\<Rightarrow> ('a \\<Rightarrow> 'a)\" where\n\"ring_function_uminus R a = function_uminus (carrier R) R a\"\n\ndefinition function_scalar_mult:: \"'c set \\<Rightarrow> ('a, 'b) ring_scheme \\<Rightarrow> 'a \\<Rightarrow> ('c \\<Rightarrow> 'a) \\<Rightarrow> ('c \\<Rightarrow> 'a)\" where\n\"function_scalar_mult S R a f = (\\<lambda> x \\<in> S. a \\<otimes>\\<^bsub>R\\<^esub> (f x))\"\n\n  (**************************************************************************************************)\n  (**************************************************************************************************)\n  subsection\\<open>Defining the Ring of Extensional Functions\\<close>\n  (**************************************************************************************************)\n  (**************************************************************************************************)\n\ndefinition function_ring:: \"'c set \\<Rightarrow> ('a, 'b) ring_scheme \\<Rightarrow> ( 'a, 'c \\<Rightarrow> 'a) module\" where\n\"function_ring S R = \\<lparr>\n   carrier = extensional_funcset S (carrier R),\n   Group.monoid.mult = (function_mult S R),\n   one = (function_one S R),\n   zero = (function_zero S R),\n   add = (function_add S R),\n   smult = function_scalar_mult S R \\<rparr> \"\n\ntext\\<open>The following locale consists of a struct R, and a distinguished set S which is meant to serve as the domain for a ring of functions $S \\to carrier R$. \\<close>\nlocale struct_functions = \n  fixes R ::\"('a, 'b) partial_object_scheme\"  (structure) \n    and S :: \"'c set\" \n\ntext\\<open>The following are locales which fix a ring R (which may be commutative, a domain, or a field) and a function ring F of extensional functions from a fixed set S to $carrier R$\\<close>\nlocale ring_functions  = struct_functions + R?: ring R +\n  fixes F (structure)\n  defines F_def: \"F \\<equiv> function_ring S R\"\n\nlocale cring_functions = ring_functions + R?: cring R\n\nlocale domain_functions = ring_functions + R?: domain R\n\nlocale field_functions = ring_functions + R?: field R\n\nsublocale cring_functions < ring_functions \n  apply (simp add: ring_functions_axioms)\n  by (simp add: F_def)\n  \nsublocale domain_functions < ring_functions \n  apply (simp add: ring_functions_axioms)\n  by (simp add: F_def)\n  \nsublocale domain_functions < cring_functions \n  apply (simp add: cring_functions_def is_cring ring_functions_axioms)\n  by (simp add: F_def)\n\nsublocale field_functions < domain_functions \n  apply (simp add: domain_axioms domain_functions_def ring_functions_axioms)\n  by (simp add: F_def) \n    \nsublocale field_functions < ring_functions\n  apply (simp add: ring_functions_axioms)\n  by (simp add: F_def) \n\nsublocale field_functions < cring_functions\n  apply (simp add: cring_functions_axioms)\n  by (simp add: F_def)\n\nabbreviation(input) ring_function_ring:: \"('a, 'b) ring_scheme \\<Rightarrow> ('a, 'a \\<Rightarrow> 'a) module\" (\"Fun\") where\n\"ring_function_ring R \\<equiv> function_ring (carrier R) R\"\n\n\n  (**************************************************************************************************)\n  (**************************************************************************************************)\n  subsection\\<open>Algebraic Properties of the Basic Operations\\<close>\n  (**************************************************************************************************)\n  (**************************************************************************************************)\n\n    (**************************************************************************************************)\n    (**************************************************************************************************)\n    subsubsection\\<open>Basic Carrier Facts\\<close>\n    (**************************************************************************************************)\n    (**************************************************************************************************)\n\nlemma(in ring_functions) function_ring_defs:\n\"carrier F = extensional_funcset S (carrier R)\"\n\"(\\<otimes>\\<^bsub>F\\<^esub>) = (function_mult S R)\"\n\"(\\<oplus>\\<^bsub>F\\<^esub>) = (function_add S R)\"\n\"\\<one>\\<^bsub>F\\<^esub> = function_one S R\"\n\"\\<zero>\\<^bsub>F\\<^esub> = function_zero S R\"\n\"(\\<odot>\\<^bsub>F\\<^esub>) = function_scalar_mult S R\"\n  unfolding F_def \n  by ( auto simp add: function_ring_def)\n\nlemma(in ring_functions) function_ring_car_memE:\n  assumes \"a \\<in> carrier F\"\n  shows \"a \\<in> extensional S\"\n        \"a \\<in> S \\<rightarrow> carrier R\"\n  using assms function_ring_defs apply auto[1]\n  using assms function_ring_defs  PiE_iff apply blast\n  using assms  function_ring_defs(1) by fastforce\n  \nlemma(in ring_functions) function_ring_car_closed:\n  assumes \"a \\<in> S\"\n  assumes \"f \\<in> carrier F\"\n  shows \"f a \\<in> carrier R\"\n  using assms   unfolding function_ring_def F_def by auto \n  \nlemma(in ring_functions)  function_ring_not_car:\n  assumes \"a \\<notin> S\"\n  assumes \"f \\<in> carrier F\"\n  shows \"f a = undefined\"\n    using assms   unfolding function_ring_def F_def by auto \n    \nlemma(in ring_functions)  function_ring_car_eqI:\n  assumes \"f \\<in> carrier F\"\n  assumes \"g \\<in> carrier F\"\n  assumes \"\\<And>a. a \\<in> S \\<Longrightarrow> f a = g a\"\n  shows \"f = g\"\n  using assms(1) assms(2) assms(3) extensionalityI function_ring_car_memE(1) by blast\n\nlemma(in ring_functions) function_ring_car_memI:\n  assumes \"\\<And>a. a \\<in> S \\<Longrightarrow> f a \\<in> carrier R\"\n  assumes \"\\<And> a. a \\<notin> S\\<Longrightarrow> f a = undefined\"\n  shows \"f \\<in> carrier F\"\n  using function_ring_defs assms \n  unfolding extensional_funcset_def \n  by (simp add: \\<open>\\<And>a. a \\<in> S \\<Longrightarrow> f a \\<in> carrier R\\<close> extensional_def)\n\nlemma(in ring) function_ring_car_memI:\n  assumes \"\\<And>a. a \\<in> S \\<Longrightarrow> f a \\<in> carrier R\"\n  assumes \"\\<And> a. a \\<notin> S\\<Longrightarrow> f a = undefined\"\n  shows \"f \\<in> carrier (function_ring S R)\"\n by (simp add: assms(1) assms(2) local.ring_axioms ring_functions.function_ring_car_memI ring_functions.intro)\n\n    (**************************************************************************************************)\n    (**************************************************************************************************)\n    subsubsection\\<open>Basic Multiplication Facts\\<close>\n    (**************************************************************************************************)\n    (**************************************************************************************************)\n\nlemma(in ring_functions) function_mult_eval_car:\n  assumes \"a \\<in> S\"\n  assumes \"f \\<in> carrier F\"\n  assumes \"g \\<in> carrier F\"\n  shows \"(f \\<otimes>\\<^bsub>F\\<^esub> g) a = (f a) \\<otimes> (g a)\"\n  using assms function_ring_defs \n  unfolding function_mult_def \n  by simp\n\nlemma(in ring_functions) function_mult_eval_closed:\n  assumes \"a \\<in> S\"\n  assumes \"f \\<in> carrier F\"\n  assumes \"g \\<in> carrier F\"\n  shows \"(f \\<otimes>\\<^bsub>F\\<^esub> g) a \\<in> carrier R\"\n  using assms function_mult_eval_car\n  using F_def ring_functions.function_ring_car_closed ring_functions_axioms by fastforce\n  \nlemma(in ring_functions) fun_mult_closed:\n  assumes \"f \\<in> carrier F\"\n  assumes \"g \\<in> carrier F\"\n  shows \"f \\<otimes>\\<^bsub>F\\<^esub> g \\<in> carrier F\"\n  apply(rule function_ring_car_memI)\n  apply (simp add: assms(1) assms(2) function_mult_eval_closed)\n  by (simp add: function_mult_def function_ring_defs(2))\n\nlemma(in ring_functions) fun_mult_eval_assoc:\n  assumes \"x \\<in> carrier F\"\n  assumes \"y \\<in> carrier F\" \n  assumes \" z \\<in> carrier F\"\n  assumes \"a \\<in> S\"\n  shows \"(x \\<otimes>\\<^bsub>F\\<^esub> y \\<otimes>\\<^bsub>F\\<^esub> z) a = (x \\<otimes>\\<^bsub>F\\<^esub> (y \\<otimes>\\<^bsub>F\\<^esub> z)) a\"\nproof-\n  have 0: \"(x \\<otimes>\\<^bsub>F\\<^esub> y \\<otimes>\\<^bsub>F\\<^esub> z) a = (x a) \\<otimes> (y a) \\<otimes> (z a) \"\n    by (simp add: assms(1) assms(2) assms(3) assms(4) fun_mult_closed function_mult_eval_car)\n  have 1: \"(x \\<otimes>\\<^bsub>F\\<^esub> (y \\<otimes>\\<^bsub>F\\<^esub> z)) a = (x a) \\<otimes> ((y a) \\<otimes> (z a))\"\n    by (simp add: assms(1) assms(2) assms(3) assms(4) fun_mult_closed function_mult_eval_car)\n  have 2:\"(x \\<otimes>\\<^bsub>F\\<^esub> (y \\<otimes>\\<^bsub>F\\<^esub> z)) a = (x a) \\<otimes> (y a) \\<otimes> (z a)\"\n    using 1 assms \n    by (simp add: function_ring_car_closed m_assoc)    \n  show ?thesis \n    using 0 2 by auto \nqed\n\nlemma(in ring_functions) fun_mult_assoc:\n  assumes \"x \\<in> carrier F\"\n  assumes \"y \\<in> carrier F\" \n  assumes \"z \\<in> carrier F\"\n  shows \"(x \\<otimes>\\<^bsub>F\\<^esub> y \\<otimes>\\<^bsub>F\\<^esub> z) = (x \\<otimes>\\<^bsub>F\\<^esub> (y \\<otimes>\\<^bsub>F\\<^esub> z))\"\n  using fun_mult_eval_assoc[of x]\n  by (simp add: assms(1) assms(2) assms(3) fun_mult_closed function_ring_car_eqI)\n    (**************************************************************************************************)\n    (**************************************************************************************************)\n    subsubsection\\<open>Basic Addition Facts\\<close>\n    (**************************************************************************************************)\n    (**************************************************************************************************)\n\nlemma(in ring_functions) fun_add_eval_car:\n  assumes \"a \\<in> S\"\n  assumes \"f \\<in> carrier F\"\n  assumes \"g \\<in> carrier F\"\n  shows \"(f \\<oplus>\\<^bsub>F\\<^esub> g) a = (f a) \\<oplus> (g a)\"\n  by (simp add: assms(1) function_add_def function_ring_defs(3))\n\nlemma(in ring_functions) fun_add_eval_closed:\n  assumes \"a \\<in> S\"\n  assumes \"f \\<in> carrier F\"\n  assumes \"g \\<in> carrier F\"\n  shows \"(f \\<oplus>\\<^bsub>F\\<^esub> g) a \\<in> carrier R\"\n  using assms unfolding F_def \n  using F_def fun_add_eval_car function_ring_car_closed \n  by auto\n\nlemma(in ring_functions) fun_add_closed:\n  assumes \"f \\<in> carrier F\"\n  assumes \"g \\<in> carrier F\"\n  shows \"f \\<oplus>\\<^bsub>F\\<^esub> g \\<in> carrier F\"\n  apply(rule function_ring_car_memI)\n  using assms unfolding F_def\n  using F_def fun_add_eval_closed apply blast\n  by (simp add: function_add_def function_ring_def)\n\nlemma(in ring_functions) fun_add_eval_assoc:\n  assumes \"x \\<in> carrier F\"\n  assumes \"y \\<in> carrier F\" \n  assumes \" z \\<in> carrier F\"\n  assumes \"a \\<in> S\"\n  shows \"(x \\<oplus>\\<^bsub>F\\<^esub> y \\<oplus>\\<^bsub>F\\<^esub> z) a = (x \\<oplus>\\<^bsub>F\\<^esub> (y \\<oplus>\\<^bsub>F\\<^esub> z)) a\"\nproof-\n  have 0: \"(x \\<oplus>\\<^bsub>F\\<^esub> y \\<oplus>\\<^bsub>F\\<^esub> z) a = (x a) \\<oplus> (y a) \\<oplus> (z a) \"\n    by (simp add: assms(1) assms(2) assms(3) assms(4) fun_add_closed fun_add_eval_car)\n  have 1: \"(x \\<oplus>\\<^bsub>F\\<^esub> (y \\<oplus>\\<^bsub>F\\<^esub> z)) a = (x a) \\<oplus> ((y a) \\<oplus> (z a))\"\n    by (simp add: assms(1) assms(2) assms(3) assms(4) fun_add_closed fun_add_eval_car)\n  have 2:\"(x \\<oplus>\\<^bsub>F\\<^esub> (y \\<oplus>\\<^bsub>F\\<^esub> z)) a = (x a) \\<oplus> (y a) \\<oplus> (z a)\"\n    using 1 assms \n    by (simp add: add.m_assoc function_ring_car_closed)   \n  show ?thesis \n    using 0 2 by auto \nqed\n\nlemma(in ring_functions) fun_add_assoc:\n  assumes \"x \\<in> carrier F\"\n  assumes \"y \\<in> carrier F\" \n  assumes \" z \\<in> carrier F\"\n  shows \"x \\<oplus>\\<^bsub>F\\<^esub> y \\<oplus>\\<^bsub>F\\<^esub> z = x \\<oplus>\\<^bsub>F\\<^esub> (y \\<oplus>\\<^bsub>F\\<^esub> z)\"\n  apply(rule function_ring_car_eqI)\n  using assms apply (simp add: fun_add_closed)\n   apply (simp add: assms(1) assms(2) assms(3) fun_add_closed)\n     by (simp add: assms(1) assms(2) assms(3) fun_add_eval_assoc)\n  \nlemma(in ring_functions) fun_add_eval_comm:\n  assumes \"a \\<in> S\"\n  assumes \"x \\<in> carrier F\"\n  assumes \"y \\<in> carrier F\" \n  shows \"(x \\<oplus>\\<^bsub>F\\<^esub> y) a = (y \\<oplus>\\<^bsub>F\\<^esub> x) a\"\n  by (metis F_def assms(1) assms(2) assms(3) fun_add_eval_car ring.ring_simprules(10) ring_functions.function_ring_car_closed ring_functions_axioms ring_functions_def)\n    \nlemma(in ring_functions) fun_add_comm:\n  assumes \"x \\<in> carrier F\"\n  assumes \"y \\<in> carrier F\" \n  shows \"x \\<oplus>\\<^bsub>F\\<^esub> y = y \\<oplus>\\<^bsub>F\\<^esub> x\"\n  using fun_add_eval_comm assms \n  by (metis (no_types, opaque_lifting) fun_add_closed function_ring_car_eqI)\n\n    (**************************************************************************************************)\n    (**************************************************************************************************)\n    subsubsection\\<open>Basic Facts About the Multiplicative Unit\\<close>\n    (**************************************************************************************************)\n    (**************************************************************************************************)\n\nlemma(in ring_functions) function_one_eval:\n  assumes \"a \\<in> S\"\n  shows \"\\<one>\\<^bsub>F\\<^esub> a = \\<one>\"\n  using assms function_ring_defs unfolding function_one_def  \n  by simp\n  \nlemma(in ring_functions) function_one_closed:\n\"\\<one>\\<^bsub>F\\<^esub> \\<in>carrier F\"\n  apply(rule function_ring_car_memI)\n  using function_ring_defs \n  using function_one_eval apply auto[1]\n  by (simp add: function_one_def function_ring_defs(4))\n\nlemma(in ring_functions) function_times_one_l:\n  assumes \"a \\<in> carrier F\"\n  shows \"\\<one>\\<^bsub>F\\<^esub> \\<otimes>\\<^bsub>F\\<^esub> a = a\"\nproof(rule function_ring_car_eqI)\n  show \"\\<one>\\<^bsub>F\\<^esub> \\<otimes>\\<^bsub>F\\<^esub> a \\<in> carrier F\"\n    using assms fun_mult_closed function_one_closed \n    by blast\n  show \" a \\<in> carrier F\"\n    using assms by simp \n  show \"\\<And>c. c \\<in> S \\<Longrightarrow> (\\<one>\\<^bsub>F\\<^esub> \\<otimes>\\<^bsub>F\\<^esub> a) c = a c \"\n    by (simp add: assms function_mult_eval_car function_one_eval function_one_closed function_ring_car_closed)\nqed\n\nlemma(in ring_functions) function_times_one_r:\n  assumes \"a \\<in> carrier F\"\n  shows \"a\\<otimes>\\<^bsub>F\\<^esub> \\<one>\\<^bsub>F\\<^esub>  = a\"\nproof(rule function_ring_car_eqI)\n  show \"a\\<otimes>\\<^bsub>F\\<^esub> \\<one>\\<^bsub>F\\<^esub> \\<in> carrier F\"\n    using assms fun_mult_closed function_one_closed \n    by blast\n  show \" a \\<in> carrier F\"\n    using assms by simp \n  show \"\\<And>c. c \\<in> S \\<Longrightarrow> (a\\<otimes>\\<^bsub>F\\<^esub> \\<one>\\<^bsub>F\\<^esub>) c = a c \"\n    using assms \n    by (simp add: function_mult_eval_car function_one_eval function_one_closed function_ring_car_closed)\nqed\n\n    (**************************************************************************************************)\n    (**************************************************************************************************)\n    subsubsection\\<open>Basic Facts About the Additive Unit\\<close>\n    (**************************************************************************************************)\n    (**************************************************************************************************)\n\nlemma(in ring_functions) function_zero_eval:\n  assumes \"a \\<in> S\"\n  shows \"\\<zero>\\<^bsub>F\\<^esub> a = \\<zero>\"\n  using assms function_ring_defs \n  unfolding function_zero_def\n  by simp\n  \nlemma(in ring_functions) function_zero_closed:\n\"\\<zero>\\<^bsub>F\\<^esub> \\<in>carrier F\"\n  apply(rule function_ring_car_memI)\n  apply (simp add: function_zero_eval)\n  by (simp add: function_ring_defs(5) function_zero_def)\n\nlemma(in ring_functions) fun_add_zeroL:\n  assumes \"a \\<in> carrier F\"\n  shows \"\\<zero>\\<^bsub>F\\<^esub> \\<oplus>\\<^bsub>F\\<^esub> a = a\"\nproof(rule function_ring_car_eqI)\n  show \"\\<zero>\\<^bsub>F\\<^esub> \\<oplus>\\<^bsub>F\\<^esub> a \\<in> carrier F\"\n    using assms fun_add_closed function_zero_closed \n    by blast\n  show \"a \\<in> carrier F\"\n    using assms by simp \n  show \"\\<And>c. c \\<in> S \\<Longrightarrow> (\\<zero>\\<^bsub>F\\<^esub> \\<oplus>\\<^bsub>F\\<^esub> a) c = a c \"\n    using assms F_def fun_add_eval_car function_zero_closed \n      ring_functions.function_zero_eval ring_functions_axioms \n    by (simp add: ring_functions.function_zero_eval function_ring_car_closed)\nqed\n\nlemma(in ring_functions) fun_add_zeroR:\n  assumes \"a \\<in> carrier F\"\n  shows \"a \\<oplus>\\<^bsub>F\\<^esub> \\<zero>\\<^bsub>F\\<^esub> = a\"\n  using assms fun_add_comm fun_add_zeroL \n  by (simp add: function_zero_closed)\n\n    (**************************************************************************************************)\n    (**************************************************************************************************)\n    subsubsection\\<open>Distributive Laws\\<close>\n    (**************************************************************************************************)\n    (**************************************************************************************************)\n\nlemma(in ring_functions) function_mult_r_distr: \n  assumes \"x \\<in> carrier F\"\n  assumes\" y \\<in> carrier F\"\n  assumes \" z \\<in> carrier F\"\n  shows \" (x \\<oplus>\\<^bsub>F\\<^esub> y) \\<otimes>\\<^bsub>F\\<^esub> z = x \\<otimes>\\<^bsub>F\\<^esub> z \\<oplus>\\<^bsub>F\\<^esub> y \\<otimes>\\<^bsub>F\\<^esub> z\"\nproof(rule function_ring_car_eqI)\n  show \"(x \\<oplus>\\<^bsub>F\\<^esub> y) \\<otimes>\\<^bsub>F\\<^esub> z \\<in> carrier F\"\n    by (simp add: assms(1) assms(2) assms(3) fun_add_closed fun_mult_closed)      \n  show \"x \\<otimes>\\<^bsub>F\\<^esub> z \\<oplus>\\<^bsub>F\\<^esub> y \\<otimes>\\<^bsub>F\\<^esub> z \\<in> carrier F\"\n    by (simp add: assms(1) assms(2) assms(3) fun_add_closed fun_mult_closed)   \n  show  \"\\<And>a. a \\<in> S \\<Longrightarrow> ((x \\<oplus>\\<^bsub>F\\<^esub> y) \\<otimes>\\<^bsub>F\\<^esub> z) a = (x \\<otimes>\\<^bsub>F\\<^esub> z \\<oplus>\\<^bsub>F\\<^esub> y \\<otimes>\\<^bsub>F\\<^esub> z) a\"\n  proof-\n    fix a\n    assume A: \"a \\<in> S\"\n    show \"((x \\<oplus>\\<^bsub>F\\<^esub> y) \\<otimes>\\<^bsub>F\\<^esub> z) a = (x \\<otimes>\\<^bsub>F\\<^esub> z \\<oplus>\\<^bsub>F\\<^esub> y \\<otimes>\\<^bsub>F\\<^esub> z) a\"\n      using A assms fun_add_eval_car[of a x y]  fun_add_eval_car[of a \"x \\<otimes>\\<^bsub>F\\<^esub>z\" \"y \\<otimes>\\<^bsub>F\\<^esub> z\"] \n            function_mult_eval_car[of a \"x \\<oplus>\\<^bsub>F\\<^esub> y\" z] semiring_simprules(10) \n            F_def \n      by (smt fun_add_closed function_mult_eval_car function_ring_car_closed \n          ring_functions.fun_mult_closed ring_functions_axioms)            \n  qed\nqed    \n\nlemma(in ring_functions) function_mult_l_distr:\n  assumes \"x \\<in> carrier F\"\n  assumes\" y \\<in> carrier F\"\n  assumes \" z \\<in> carrier F\"\n  shows \"z \\<otimes>\\<^bsub>F\\<^esub> (x \\<oplus>\\<^bsub>F\\<^esub> y) = z \\<otimes>\\<^bsub>F\\<^esub> x \\<oplus>\\<^bsub>F\\<^esub> z \\<otimes>\\<^bsub>F\\<^esub> y\"\nproof(rule function_ring_car_eqI)\n  show \"z \\<otimes>\\<^bsub>F\\<^esub> (x \\<oplus>\\<^bsub>F\\<^esub> y) \\<in> carrier F\"\n    by (simp add: assms(1) assms(2) assms(3) fun_add_closed fun_mult_closed)     \n  show \"z \\<otimes>\\<^bsub>F\\<^esub> x \\<oplus>\\<^bsub>F\\<^esub> z \\<otimes>\\<^bsub>F\\<^esub> y \\<in> carrier F\"\n    by (simp add: assms(1) assms(2) assms(3) fun_add_closed fun_mult_closed)   \n  show  \"\\<And>a. a \\<in> S \\<Longrightarrow> (z \\<otimes>\\<^bsub>F\\<^esub> (x \\<oplus>\\<^bsub>F\\<^esub> y)) a = (z \\<otimes>\\<^bsub>F\\<^esub> x \\<oplus>\\<^bsub>F\\<^esub> z \\<otimes>\\<^bsub>F\\<^esub> y) a\"\n  proof-\n    fix a\n    assume A: \"a \\<in> S\"\n    show \"(z \\<otimes>\\<^bsub>F\\<^esub> (x \\<oplus>\\<^bsub>F\\<^esub> y)) a = (z \\<otimes>\\<^bsub>F\\<^esub> x \\<oplus>\\<^bsub>F\\<^esub> z \\<otimes>\\<^bsub>F\\<^esub> y) a\"\n      using A assms function_ring_defs fun_add_closed fun_mult_closed \n            function_mult_eval_car[of a z \"x \\<oplus>\\<^bsub>F\\<^esub> y\"] \n            function_mult_eval_car[of a z x] \n            function_mult_eval_car[of a z y] \n            fun_add_eval_car[of a x y]\n            semiring_simprules(13) \n            fun_add_eval_car function_ring_car_closed by auto  \n  qed\nqed    \n\n    (**************************************************************************************************)\n    (**************************************************************************************************)\n    subsubsection\\<open>Additive Inverses\\<close>\n    (**************************************************************************************************)\n    (**************************************************************************************************)\n\nlemma(in ring_functions) function_uminus_closed:\n  assumes \"f \\<in> carrier F\"\n  shows \"function_uminus S R f \\<in> carrier F\"\nproof(rule function_ring_car_memI)\n  show \"\\<And>a. a \\<in> S \\<Longrightarrow> function_uminus S R f a \\<in> carrier R\"\n    using assms function_ring_car_closed[of _ f] unfolding function_uminus_def \n    by simp       \n  show \"\\<And>a. a \\<notin> S \\<Longrightarrow> function_uminus S R f a = undefined\"\n    by (simp add: function_uminus_def)\nqed\n\nlemma(in ring_functions) function_uminus_eval:\n  assumes \"a \\<in> S\"\n  assumes \"f \\<in> carrier F\"\n  shows \"(function_uminus S R f) a = \\<ominus> (f a)\"\n  using assms unfolding function_uminus_def \n  by simp\n\nlemma(in ring_functions) function_uminus_add_r:\n  assumes \"a \\<in> S\"\n  assumes \"f \\<in> carrier F\"\n  shows \"f \\<oplus>\\<^bsub>F\\<^esub> function_uminus S R f = \\<zero>\\<^bsub>F\\<^esub>\"\n  apply(rule function_ring_car_eqI) \n  using assms  fun_add_closed function_uminus_closed apply blast\n    unfolding F_def  using F_def function_zero_closed apply blast\n      using F_def assms(2) fun_add_eval_car function_ring_car_closed function_uminus_closed \n      function_uminus_eval function_zero_eval r_neg by auto\n\nlemma(in ring_functions) function_uminus_add_l:\n  assumes \"a \\<in> S\"\n  assumes \"f \\<in> carrier F\"\n  shows \"function_uminus S R f \\<oplus>\\<^bsub>F\\<^esub> f = \\<zero>\\<^bsub>F\\<^esub>\"\n  using assms(1) assms(2) fun_add_comm function_uminus_add_r function_uminus_closed by auto\n  \n\n    (**************************************************************************************************)\n    (**************************************************************************************************)\n    subsubsection\\<open>Scalar Multiplication\\<close>\n    (**************************************************************************************************)\n    (**************************************************************************************************)\n\nlemma(in ring_functions) function_smult_eval:\n  assumes \"a \\<in> carrier R\"\n  assumes  \"f \\<in> carrier F\"\n  assumes \"b \\<in> S\"\n  shows \"(a \\<odot>\\<^bsub>F\\<^esub> f) b = a \\<otimes> (f b)\"\n  using function_ring_defs(6) unfolding function_scalar_mult_def \n  by(simp add: assms)\n\nlemma(in ring_functions) function_smult_closed:\n  assumes \"a \\<in> carrier R\"\n  assumes  \"f \\<in> carrier F\"\n  shows \"a \\<odot>\\<^bsub>F\\<^esub> f \\<in> carrier F\"\n  apply(rule function_ring_car_memI)\n  using function_smult_eval assms \n  apply (simp add: function_ring_car_closed)\n  using function_scalar_mult_def F_def \n  by (metis function_ring_defs(6) restrict_apply)\n\nlemma(in ring_functions) function_smult_assoc1:\n  assumes \"a \\<in> carrier R\"\n  assumes \"b \\<in> carrier R\"\n  assumes  \"f \\<in> carrier F\"\n  shows \"b \\<odot>\\<^bsub>F\\<^esub> (a \\<odot>\\<^bsub>F\\<^esub> f)  = (b \\<otimes> a)\\<odot>\\<^bsub>F\\<^esub>f\"\n  apply(rule function_ring_car_eqI)\n  using assms function_smult_closed apply simp\n    using assms function_smult_closed apply simp\n       by (metis F_def assms(1) assms(2) assms(3) function_mult_eval_closed function_one_closed\n        function_smult_eval function_times_one_r m_assoc m_closed ring_functions.function_smult_closed ring_functions_axioms)\n\nlemma(in ring_functions) function_smult_assoc2:\n  assumes \"a \\<in> carrier R\"\n  assumes  \"f \\<in> carrier F\"\n  assumes \"g \\<in> carrier F\"\n  shows \"(a \\<odot>\\<^bsub>F\\<^esub> f)\\<otimes>\\<^bsub>F\\<^esub>g  = a \\<odot>\\<^bsub>F\\<^esub> (f \\<otimes>\\<^bsub>F\\<^esub> g)\"\n  apply(rule function_ring_car_eqI)\n  using assms function_smult_closed apply (simp add: fun_mult_closed)\n   apply (simp add: assms(1) assms(2) assms(3) fun_mult_closed function_smult_closed)\n     by (metis (full_types) F_def assms(1) assms(2) assms(3) fun_mult_closed \n      function_mult_eval_car function_smult_closed function_smult_eval m_assoc ring_functions.function_ring_car_closed ring_functions_axioms)     \n\nlemma(in ring_functions) function_smult_one:\n  assumes  \"f \\<in> carrier F\"\n  shows \"\\<one>\\<odot>\\<^bsub>F\\<^esub>f = f\"\n  apply(rule function_ring_car_eqI)\n  apply (simp add: assms function_smult_closed)\n   apply (simp add: assms)\n     by (simp add: assms function_ring_car_closed function_smult_eval)\n     \nlemma(in ring_functions) function_smult_l_distr:\n\"[| a \\<in> carrier R; b \\<in> carrier R; x \\<in> carrier F |] ==>\n      (a \\<oplus> b) \\<odot>\\<^bsub>F\\<^esub> x = a \\<odot>\\<^bsub>F\\<^esub> x \\<oplus>\\<^bsub>F\\<^esub> b \\<odot>\\<^bsub>F\\<^esub> x\"\n  apply(rule function_ring_car_eqI)\n  apply (simp add: function_smult_closed)\n   apply (simp add: fun_add_closed function_smult_closed)   \n    using function_smult_eval \n    by (simp add: fun_add_eval_car function_ring_car_closed function_smult_closed l_distr)\n    \nlemma(in ring_functions) function_smult_r_distr:\n \"[| a \\<in> carrier R; x \\<in> carrier F; y \\<in> carrier F |] ==>\n      a \\<odot>\\<^bsub>F\\<^esub> (x \\<oplus>\\<^bsub>F\\<^esub> y) = a \\<odot>\\<^bsub>F\\<^esub> x \\<oplus>\\<^bsub>F\\<^esub> a \\<odot>\\<^bsub>F\\<^esub> y\"\n  apply(rule function_ring_car_eqI)\n  apply (simp add: fun_add_closed function_smult_closed)\n   apply (simp add: fun_add_closed function_smult_closed)\n    by (simp add: fun_add_closed fun_add_eval_car function_ring_car_closed function_smult_closed function_smult_eval r_distr) \n\n    (**************************************************************************************************)\n    (**************************************************************************************************)\n    subsubsection\\<open>The Ring of Functions Forms an Algebra\\<close>\n    (**************************************************************************************************)\n    (**************************************************************************************************)\n\nlemma(in ring_functions) function_ring_is_abelian_group:\n\"abelian_group F\"\n  apply(rule abelian_groupI)\n  apply (simp add: fun_add_closed)\n      apply (simp add: function_zero_closed)\n        using fun_add_assoc apply simp  \n          apply (simp add: fun_add_comm)\n            apply (simp add: fun_add_comm fun_add_zeroR function_zero_closed)\n              using fun_add_zeroL function_ring_car_eqI function_uminus_add_l \n                  function_uminus_closed function_zero_closed by blast\n\nlemma(in ring_functions) function_ring_is_monoid:\n\"monoid F\"\n  apply(rule monoidI)\n    apply (simp add: fun_mult_closed)\n     apply (simp add: function_one_closed)\n      apply (simp add: fun_mult_assoc)\n       apply (simp add: function_times_one_l)\n        by (simp add: function_times_one_r)\n      \nlemma(in ring_functions) function_ring_is_ring:\n\"ring F\"\n  apply(rule ringI)\n     apply (simp add: function_ring_is_abelian_group)\n      apply (simp add: function_ring_is_monoid)\n        apply (simp add: function_mult_r_distr)\n          by (simp add: function_mult_l_distr)\n\nsublocale ring_functions < F?: ring F\n  by (rule function_ring_is_ring)\n\nlemma(in cring_functions) function_mult_comm: \n  assumes \"x \\<in> carrier F\"\n  assumes\" y \\<in> carrier F\"\n  shows \"x \\<otimes>\\<^bsub>F\\<^esub> y = y \\<otimes>\\<^bsub>F\\<^esub> x\"\n  apply(rule function_ring_car_eqI)\n  apply (simp add: assms(1) assms(2) fun_mult_closed)\n   apply (simp add: assms(1) assms(2) fun_mult_closed)\n    by (simp add: assms(1) assms(2) function_mult_eval_car function_ring_car_closed m_comm)  \n\nlemma(in cring_functions) function_ring_is_comm_monoid:\n\"comm_monoid F\"\n  apply(rule comm_monoidI)\n  using fun_mult_assoc function_one_closed\n  apply (simp add: fun_mult_closed)\n     apply (simp add: function_one_closed)\n      apply (simp add: fun_mult_assoc)\n        apply (simp add: function_times_one_l)\n          by (simp add: function_mult_comm)    \n    \nlemma(in cring_functions) function_ring_is_cring:\n\"cring F\"\n  apply(rule cringI)\n    apply (simp add: function_ring_is_abelian_group)\n      apply (simp add: function_ring_is_comm_monoid)\n        by (simp add: function_mult_r_distr)\n\nlemma(in cring_functions) function_ring_is_algebra:\n\"algebra R F\"\n  apply(rule algebraI)\n   apply (simp add: is_cring)\n    apply (simp add: function_ring_is_cring)\n     using function_smult_closed apply blast\n      apply (simp add: function_smult_l_distr)\n       apply (simp add: function_smult_r_distr)\n        apply (simp add: function_smult_assoc1)\n         apply (simp add: function_smult_one)\n          by (simp add: function_smult_assoc2)\n            \nlemma(in ring_functions) function_uminus:\n  assumes \"f \\<in> carrier F\"\n  shows \"\\<ominus>\\<^bsub>F\\<^esub> f = (function_uminus S R) f\"\n  using assms a_inv_def[of F] \n  by (metis F_def abelian_group.a_group abelian_group.r_neg function_uminus_add_r function_uminus_closed group.inv_closed partial_object.select_convs(1) ring.ring_simprules(18) ring_functions.function_ring_car_eqI ring_functions.function_ring_is_abelian_group ring_functions.function_ring_is_ring ring_functions_axioms)\n\nlemma(in ring_functions) function_uminus_eval':\n  assumes \"f \\<in> carrier F\"\n  assumes \"a \\<in> S\"\n  shows \"(\\<ominus>\\<^bsub>F\\<^esub> f) a = (function_uminus S R) f a\"\n  using assms \n  by (simp add: function_uminus)\n\nlemma(in ring_functions) function_uminus_eval'':\n  assumes \"f \\<in> carrier F\"\n  assumes \"a \\<in> S\"\n  shows \"(\\<ominus>\\<^bsub>F\\<^esub> f) a = \\<ominus> (f a)\"\n  using assms(1) assms(2) function_uminus \n  by (simp add: function_uminus_eval)\n\nsublocale cring_functions < F?: algebra R F\n  using function_ring_is_algebra by auto \n\n    (**************************************************************************************************)\n    (**************************************************************************************************)\n    subsection\\<open>Constant Functions\\<close>\n    (**************************************************************************************************)\n    (**************************************************************************************************)\n\ndefinition constant_function  where\n\"constant_function S a =(\\<lambda>x \\<in> S. a)\"\n\nabbreviation(in ring_functions)(input) const   where\n\"const \\<equiv> constant_function S\"\n\nlemma(in ring_functions) constant_function_closed:\n  assumes \"a \\<in> carrier R\"\n  shows \"const a \\<in> carrier F\"\n  apply(rule function_ring_car_memI)\n  unfolding constant_function_def \n  apply (simp add: assms)\n    by simp\n\nlemma(in ring_functions) constant_functionE: \n  assumes \"a \\<in> carrier R\"\n  assumes \"b \\<in> S\"\n  shows \"const a b = a\"\n  by (simp add: assms(2) constant_function_def)\n\nlemma(in ring_functions) constant_function_add: \n  assumes \"a \\<in> carrier R\"\n  assumes \"b \\<in> carrier R\"\n  shows \"const (a \\<oplus>\\<^bsub>R\\<^esub> b) = (const a) \\<oplus>\\<^bsub>F\\<^esub> (const b) \" \n  apply(rule function_ring_car_eqI)\n    apply (simp add: constant_function_closed assms(1) assms(2))\n      using assms(1) constant_function_closed assms(2) fun_add_closed apply auto[1]\n        by (simp add: assms(1) assms(2) constant_function_closed constant_functionE fun_add_eval_car)\n\nlemma(in ring_functions) constant_function_mult: \n  assumes \"a \\<in> carrier R\"\n  assumes \"b \\<in> carrier R\"\n  shows \"const (a \\<otimes>\\<^bsub>R\\<^esub> b) = (const a) \\<otimes>\\<^bsub>F\\<^esub> (const b)\" \n  apply(rule function_ring_car_eqI)\n    apply (simp add: constant_function_closed assms(1) assms(2))\n      using assms(1) constant_function_closed assms(2) fun_mult_closed apply auto[1]\n        by (simp add: constant_function_closed assms(1) assms(2) constant_functionE function_mult_eval_car)\n      \nlemma(in ring_functions) constant_function_minus: \n  assumes \"a \\<in> carrier R\"\n  shows \"\\<ominus>\\<^bsub>F\\<^esub>(const a) = (const (\\<ominus>\\<^bsub>R\\<^esub> a)) \" \napply(rule function_ring_car_eqI)\n  apply (simp add: constant_function_closed assms local.function_uminus)\n   apply (simp add: constant_function_closed assms function_uminus_closed)\n    apply (simp add: constant_function_closed assms)\n      by (simp add: constant_function_closed assms constant_functionE function_uminus_eval'')\n\nlemma(in ring_functions) function_one_is_constant:\n\"const \\<one> = \\<one>\\<^bsub>F\\<^esub>\"\n  unfolding F_def \n  apply(rule function_ring_car_eqI)\n  apply (simp add: constant_function_closed)\n  using F_def function_one_closed apply auto[1]\n  using F_def constant_functionE function_one_eval by auto\n\nlemma(in ring_functions) function_zero_is_constant:\n\"const \\<zero> = \\<zero>\\<^bsub>F\\<^esub>\"\n   apply(rule function_ring_car_eqI)\n  apply (simp add: constant_function_closed)\n  using F_def function_zero_closed apply auto[1]\n  using F_def constant_functionE function_zero_eval by auto\n\n\n  (**************************************************************************************************)\n  (**************************************************************************************************)\n  subsection\\<open>Special Examples of Functions Rings\\<close>\n  (**************************************************************************************************)\n  (**************************************************************************************************)\n\n    (**************************************************************************************************)\n    (**************************************************************************************************)\n    subsubsection\\<open>Functions from the Carrier of a Ring to Itself\\<close>\n    (**************************************************************************************************)\n    (**************************************************************************************************)\n\n\nlocale U_function_ring = ring\n\nlocale U_function_cring = U_function_ring + cring\n\nsublocale U_function_ring <  S?: struct_functions R \"carrier R\" \n  done \n\nsublocale U_function_ring  <  FunR?: ring_functions R \"carrier R\" \"Fun R\"\n  apply (simp add: local.ring_axioms ring_functions.intro)\n    by simp\n\nsublocale U_function_cring <  FunR?: cring_functions R \"carrier R\" \"Fun R\"\n  apply (simp add: cring_functions_def is_cring ring_functions_axioms)\n    by simp\n    \nabbreviation(in U_function_ring)(input) ring_compose :: \"('a \\<Rightarrow> 'a) \\<Rightarrow> ('a \\<Rightarrow> 'a) \\<Rightarrow> ('a \\<Rightarrow> 'a)\" where\n\"ring_compose \\<equiv> compose (carrier R)\"\n  \nlemma(in U_function_ring) ring_function_ring_comp:\n  assumes \"f \\<in> carrier (Fun R)\"\n  assumes \"g \\<in> carrier (Fun R)\"\n  shows \"ring_compose f g \\<in> carrier (Fun R)\"\n  apply(rule function_ring_car_memI) \n  apply (simp add: assms(1) assms(2) compose_eq)\n   apply (simp add: assms(1) assms(2) function_ring_car_closed)\n     by (meson compose_extensional extensional_arb)\n  \nabbreviation(in U_function_ring)(input) ring_const (\"\\<cc>\\<index>\") where\n\"ring_const \\<equiv> constant_function (carrier R)\"\n\nlemma(in ring_functions) function_nat_pow_eval:\n  assumes \"f \\<in> carrier F\"\n  assumes \"s \\<in> S\"\n  shows \"(f[^]\\<^bsub>F\\<^esub>(n::nat)) s = (f s)[^]n\"\n  apply(induction n)\n  using assms(2) function_one_eval apply auto[1]\n  by (simp add: assms(1) assms(2) function_mult_eval_car function_ring_is_monoid monoid.nat_pow_closed)\n    \n\ncontext U_function_ring \nbegin\n\ndefinition a_translate :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a\" where\n\"a_translate = (\\<lambda> r \\<in> carrier R. restrict ((add R) r) (carrier R))\"\n\ndefinition m_translate :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a\" where\n\"m_translate  = (\\<lambda> r \\<in> carrier R. restrict ((mult R) r) (carrier R))\"\n\ndefinition nat_power :: \"nat \\<Rightarrow> 'a \\<Rightarrow> 'a\" where \n\"nat_power = (\\<lambda>(n::nat). restrict (\\<lambda>a.  a[^]\\<^bsub>R\\<^esub>n) (carrier R)) \"\n\ntext\\<open>Restricted operations are in Fs\\<close>\n\nlemma a_translate_functions:\n  assumes \"c \\<in> carrier R\"\n  shows \"a_translate c \\<in> carrier (Fun R)\"\n  apply(rule function_ring_car_memI)\n  using assms a_translate_def \n   apply simp\n  using assms a_translate_def \n  by simp  \n\nlemma m_translate_functions:\n  assumes \"c \\<in> carrier R\"\n  shows \"m_translate c \\<in> carrier (Fun R)\"\n  apply(rule function_ring_car_memI)\n  using assms m_translate_def \n  apply simp\n    using assms m_translate_def \n  by simp\n\nlemma nat_power_functions:\n  shows \"nat_power n \\<in> carrier (Fun R)\"\n  apply(rule function_ring_car_memI)\n  using  nat_power_def \n   apply simp\n  by (simp add: nat_power_def)\n\ntext\\<open>Restricted operations simps\\<close>\n\nlemma a_translate_eq:\n  assumes \"c \\<in> carrier R\"\n  assumes \"a \\<in> carrier R\"\n  shows \"a_translate c a = c \\<oplus> a\"\n  by (simp add: a_translate_def assms(1) assms(2))\n\nlemma a_translate_eq':\n  assumes \"c \\<in> carrier R\"\n  assumes \"a \\<notin> carrier R\"\n  shows \"a_translate c a = undefined\"\n  by (meson a_translate_functions assms(1) assms(2) function_ring_not_car)\n\nlemma a_translate_eq'':\n  assumes \"c \\<notin> carrier R\"\n  shows \"a_translate c = undefined\"\n  by (simp add: a_translate_def assms)\n\nlemma m_translate_eq:\n  assumes \"c \\<in> carrier R\"\n  assumes \"a \\<in> carrier R\"\n  shows \"m_translate c a = c \\<otimes> a\"\n  by (simp add: m_translate_def assms(1) assms(2))\n\nlemma m_translate_eq':\n  assumes \"c \\<in> carrier R\"\n  assumes \"a \\<notin> carrier R\"\n  shows \"m_translate c a = undefined \"\n  by (meson m_translate_functions assms(1) assms(2) function_ring_not_car)\n\nlemma m_translate_eq'':\n  assumes \"c \\<notin> carrier R\"\n  shows \"m_translate c = undefined\"\n  by (simp add: m_translate_def assms)\n\nlemma nat_power_eq:\n  assumes \"a \\<in> carrier R\"\n  shows \"nat_power n a = a[^]\\<^bsub>R\\<^esub> n\"\n  by (simp add: assms nat_power_def)\n\nlemma nat_power_eq':\n  assumes \"a \\<notin> carrier R\"\n  shows \"nat_power n a = undefined\"\n  by (simp add: assms nat_power_def)\n\ntext\\<open>Constant ring\\_function properties\\<close>\n\nlemma constant_function_eq:\n  assumes \"a \\<in> carrier R\"\n  assumes \"b \\<in> carrier R\"\n  shows \"\\<cc>\\<^bsub>a\\<^esub> b = a\"\n  using assms \n    \n  by (simp add: constant_functionE)\n    \nlemma constant_function_eq':\n  assumes \"a \\<in> carrier R\"\n  assumes \"b \\<notin> carrier R\"\n  shows \"\\<cc>\\<^bsub>a\\<^esub> b = undefined\"\n  by (simp add: constant_function_closed assms(1) assms(2) function_ring_not_car)\n    \ntext\\<open>Compound expressions from algebraic operations\\<close>\nend \n\ndefinition monomial_function where\n\"monomial_function R c (n::nat) = (\\<lambda> x \\<in> carrier R. c \\<otimes>\\<^bsub>R\\<^esub> (x[^]\\<^bsub>R\\<^esub>n))\"\n\ncontext U_function_ring\nbegin\n\nabbreviation monomial where\n\"monomial \\<equiv> monomial_function R\"\n\nlemma monomial_functions:\n  assumes \"c \\<in> carrier R\"\n  shows \"monomial c n \\<in> carrier (Fun R)\"\n  apply(rule function_ring_car_memI)\n  unfolding monomial_function_def \n  apply (simp add: assms)\n  by simp\n\ndefinition ring_id  where\n\"ring_id \\<equiv> restrict (\\<lambda>x. x) (carrier R) \"\n\nlemma ring_id_closed[simp]:\n\"ring_id \\<in> carrier (Fun R)\"\n  by (simp add: function_ring_car_memI ring_id_def)\n\nlemma ring_id_eval:\n  assumes \"a \\<in> carrier R\"\n  shows \"ring_id a = a\"\n  using assms unfolding ring_id_def\n  by simp\n  \nlemma constant_a_trans: \n  assumes \"a \\<in>carrier R\"\n  shows \"m_translate a  = \\<cc>\\<^bsub>a\\<^esub> \\<otimes>\\<^bsub>Fun R\\<^esub> ring_id\"\nproof(rule function_ring_car_eqI)\n   show \"m_translate a \\<in> carrier (Fun R)\"\n     using assms\n     using m_translate_functions by blast\n   show \"\\<cc>\\<^bsub>a\\<^esub> \\<otimes>\\<^bsub>Fun R\\<^esub> ring_id \\<in> carrier (Fun R)\"\n     unfolding ring_id_def \n     using assms ring_id_closed ring_id_def \n     by (simp add: constant_function_closed fun_mult_closed)      \n  show \"\\<And>x. x \\<in> carrier R \\<Longrightarrow> m_translate a x = (\\<cc>\\<^bsub>a\\<^esub> \\<otimes>\\<^bsub>Fun R\\<^esub> ring_id) x\"\n    by (simp add: constant_function_closed assms constant_function_eq function_mult_eval_car m_translate_eq ring_id_eval)    \nqed\n\ntext\\<open>polynomials in one variable\\<close>\n\nfun polynomial :: \"'a list \\<Rightarrow> ('a \\<Rightarrow> 'a)\" where\n\"polynomial []  = \\<zero>\\<^bsub>Fun R\\<^esub> \"|\n\"polynomial (a#as) = (\\<lambda>x \\<in> carrier R. a \\<oplus> x \\<otimes> (polynomial as x))\"\n\nlemma polynomial_induct_lemma:\n  assumes \"f \\<in> carrier (Fun R)\"\n  assumes \"a \\<in> carrier R\"\n  shows \"(\\<lambda>x \\<in> carrier R. a \\<oplus> x \\<otimes> (f x)) \\<in> carrier (Fun R)\"\nproof(rule function_ring_car_memI)\n  show \"\\<And>aa. aa \\<in> carrier R \\<Longrightarrow> (\\<lambda>x\\<in>carrier R. a \\<oplus> x \\<otimes> f x) aa \\<in> carrier R\"\n  proof- fix y assume A: \"y \\<in> carrier R\"\n    have \"a \\<oplus> y \\<otimes> f y \\<in> carrier R\"\n      using A assms(1) assms(2) function_ring_car_closed by blast\n    thus \"(\\<lambda>x\\<in>carrier R. a \\<oplus> x \\<otimes> f x) y \\<in> carrier R\"\n      using A by auto \n  qed  \n  show \"\\<And>aa. aa \\<notin> carrier R \\<Longrightarrow> (\\<lambda>x\\<in>carrier R. a \\<oplus> x \\<otimes> f x) aa = undefined\"\n    by auto \nqed\n\nlemma polynomial_function: \n  shows \"set as \\<subseteq> carrier R \\<Longrightarrow> polynomial as \\<in> carrier (Fun R)\"\nproof(induction as)\n  case Nil\n  then show ?case \n    by (simp add: function_zero_closed)  \nnext\n  case (Cons a as)\n  then show \"polynomial (a # as) \\<in> carrier (function_ring (carrier R) R)\"\n    using polynomial.simps(2)[of a as] polynomial_induct_lemma[of \"polynomial as\" a]\n    by simp\nqed\n  \nlemma polynomial_constant:\n  assumes \"a \\<in> carrier R\"\n  shows \"polynomial [a] = \\<cc>\\<^bsub>a\\<^esub>\"\n  apply(rule function_ring_car_eqI)\n      using assms polynomial_function \n      apply (metis (full_types) list.distinct(1) list.set_cases set_ConsD subset_code(1))\n        apply (simp add: constant_function_closed assms)\n          using polynomial.simps(2)[of a \"[]\"] polynomial.simps(1) assms \n          by (simp add: constant_function_eq function_zero_eval)\n          \n\nend\n\n    (**************************************************************************************************)\n    (**************************************************************************************************)\n    subsubsection\\<open>Sequences Indexed by the Natural Numbers\\<close>\n    (**************************************************************************************************)\n    (**************************************************************************************************)\n\ndefinition nat_seqs (\"_\\<^bsup>\\<omega>\\<^esup>\")where\n\"nat_seqs R \\<equiv> function_ring (UNIV::nat set) R\"\n \nabbreviation(input) closed_seqs where\n\"closed_seqs R \\<equiv> carrier (R\\<^bsup>\\<omega>\\<^esup>)\"\n\nlemma closed_seqs_memI:\n  assumes \"\\<And>k. s k \\<in> carrier R\"\n  shows \"s \\<in> closed_seqs R\"\n  unfolding nat_seqs_def function_ring_def \n  by (simp add: PiE_UNIV_domain assms)\n\nlemma closed_seqs_memE:\n  assumes \"s \\<in> closed_seqs R\"\n  shows \"s k \\<in> carrier R\"\n  using assms unfolding nat_seqs_def function_ring_def \n  by (simp add: PiE_iff)  \n\ndefinition is_constant_fun  where\n\"is_constant_fun R f = (\\<exists>x \\<in> carrier R. f = constant_function (carrier R) R x)\"\n\ndefinition is_constant_seq where\n\"is_constant_seq R s = (\\<exists>x \\<in> carrier R. s = constant_function (UNIV::nat set) x)\"\n\nlemma is_constant_seqI:\n  fixes a\n  assumes \"s \\<in> closed_seqs R\"\n  assumes \"\\<And>k. s k = a\"\n  shows \"is_constant_seq R s\"\n  unfolding is_constant_seq_def constant_function_def \n  by (metis assms(1) assms(2) closed_seqs_memE restrict_UNIV restrict_ext)\n   \nlemma is_constant_seqE:\n  assumes \"is_constant_seq R s\"\n  assumes \"s k = a\"\n  shows \"s n = a\"\n  using assms unfolding is_constant_seq_def \n  by (metis constant_function_def restrict_UNIV)\n  \nlemma is_constant_seq_imp_closed:\n  assumes \"is_constant_seq R s\"\n  shows \"s \\<in> closed_seqs R\"\n  apply(rule closed_seqs_memI)\n  using assms unfolding is_constant_seq_def constant_function_def \n  by auto\n  \ncontext U_function_ring\nbegin\n\ntext\\<open>Sequence sums and products are closed\\<close>\n\nlemma seq_plus_closed:\n  assumes \"s \\<in> closed_seqs R\"\n  assumes \"s' \\<in> closed_seqs R\"\n  shows \"s \\<oplus>\\<^bsub>R\\<^bsup>\\<omega>\\<^esup>\\<^esub> s' \\<in> closed_seqs R\"\n  by (metis assms(1) assms(2) nat_seqs_def ring_functions.fun_add_closed ring_functions_axioms)\n \nlemma seq_mult_closed:\n  assumes \"s \\<in> closed_seqs R\"\n  assumes \"s' \\<in> closed_seqs R\"\n  shows \"s \\<otimes>\\<^bsub>R\\<^bsup>\\<omega>\\<^esup>\\<^esub> s' \\<in> closed_seqs R\"\n  apply(rule closed_seqs_memI)\n  by (metis assms(1) assms(2) closed_seqs_memE nat_seqs_def ring_functions.fun_mult_closed ring_functions_axioms)\n \nlemma constant_function_comp_is_closed_seq:\n  assumes \"a \\<in> carrier R\"\n  assumes \"s \\<in> closed_seqs R\"\n  shows \"(const a \\<circ> s) \\<in> closed_seqs R\" \n  by (simp add: constant_functionE assms(1) assms(2) closed_seqs_memE closed_seqs_memI)\n\nlemma constant_function_comp_is_constant_seq:\n  assumes \"a \\<in> carrier R\"\n  assumes \"s \\<in> closed_seqs R\"\n  shows \"is_constant_seq R ((const a) \\<circ> s)\" \n  apply(rule is_constant_seqI[of _ _ a] )\n  apply (simp add: assms(1) assms(2) constant_function_comp_is_closed_seq)\n    using assms(1) assms(2) closed_seqs_memE \n    by (simp add: closed_seqs_memE constant_functionE)\n      \nlemma function_comp_is_closed_seq:\n  assumes \"s \\<in> closed_seqs R\"\n  assumes \"f \\<in> carrier (Fun R)\"\n  shows \"f \\<circ> s \\<in> closed_seqs R\" \n  apply(rule closed_seqs_memI)\n  using assms(1) assms(2) closed_seqs_memE \n  by (metis comp_apply fun_add_eval_closed fun_add_zeroR function_zero_closed)\n  \nlemma function_sum_comp_is_seq_sum:\n  assumes \"s \\<in> closed_seqs R\"\n  assumes \"f \\<in> carrier (Fun R)\"\n  assumes \"g \\<in> carrier (Fun R)\"\n  shows \"(f \\<oplus>\\<^bsub>Fun R\\<^esub> g) \\<circ> s = (f \\<circ> s) \\<oplus>\\<^bsub>R\\<^bsup>\\<omega>\\<^esup>\\<^esub> (g \\<circ> s)\"\n  apply(rule ring_functions.function_ring_car_eqI[of R _ \"UNIV :: nat set\"])\n  apply (simp add: ring_functions_axioms)\n    using function_comp_is_closed_seq \n    apply (metis assms(1) assms(2) assms(3) fun_add_closed nat_seqs_def)\n     apply (metis assms(1) assms(2) assms(3) function_comp_is_closed_seq nat_seqs_def seq_plus_closed)\n  by (smt UNIV_eq_I assms(1) assms(2) assms(3) closed_seqs_memE comp_apply function_comp_is_closed_seq nat_seqs_def ring_functions.fun_add_eval_car ring_functions_axioms)\n\nlemma function_mult_comp_is_seq_mult:\n  assumes \"s \\<in> closed_seqs R\"\n  assumes \"f \\<in> carrier (Fun R)\"\n  assumes \"g \\<in> carrier (Fun R)\"\n  shows \"(f \\<otimes>\\<^bsub>Fun R\\<^esub> g) \\<circ> s = (f \\<circ> s) \\<otimes>\\<^bsub>R\\<^bsup>\\<omega>\\<^esup>\\<^esub> (g \\<circ> s)\"\n  apply(rule ring_functions.function_ring_car_eqI[of R _ \"UNIV :: nat set\"])\n  apply (simp add: ring_functions_axioms)\n  using function_comp_is_closed_seq \n  apply (metis assms(1) assms(2) assms(3) fun_mult_closed nat_seqs_def)\n  apply (metis assms(1) assms(2) assms(3) function_comp_is_closed_seq nat_seqs_def seq_mult_closed)\n  by (metis (no_types, lifting) assms(1) assms(2) assms(3) comp_apply function_comp_is_closed_seq nat_seqs_def ring_functions.function_mult_eval_car ring_functions.function_ring_car_closed ring_functions_axioms)\n\nlemma seq_plus_simp:\n  assumes \"s \\<in> closed_seqs R\"\n  assumes \"t \\<in> closed_seqs R\"\n  shows \"(s \\<oplus>\\<^bsub>R\\<^bsup>\\<omega>\\<^esup>\\<^esub> t) k = s k \\<oplus> t k\"\n  using assms unfolding nat_seqs_def \n  by (simp add: ring_functions.fun_add_eval_car ring_functions_axioms)\n\nlemma seq_mult_simp:\n  assumes \"s \\<in> closed_seqs R\"\n  assumes \"t \\<in> closed_seqs R\"\n  shows \"(s \\<otimes>\\<^bsub>R\\<^bsup>\\<omega>\\<^esup>\\<^esub> t) k = s k \\<otimes> t k\"\n  using assms unfolding nat_seqs_def \n  by (simp add: ring_functions.function_mult_eval_car ring_functions_axioms)\n\nlemma seq_one_simp:\n\"\\<one>\\<^bsub>R\\<^bsup>\\<omega>\\<^esup>\\<^esub> k = \\<one>\"\n  by (simp add: nat_seqs_def ring_functions.function_one_eval ring_functions_axioms)\n\nlemma seq_zero_simp:\n\"\\<zero>\\<^bsub>R\\<^bsup>\\<omega>\\<^esup>\\<^esub> k = \\<zero>\"\n  by (simp add: nat_seqs_def ring_functions.function_zero_eval ring_functions_axioms)\n\nlemma(in U_function_ring) ring_id_seq_comp:\n  assumes \"s \\<in> closed_seqs R\"\n  shows \"ring_id \\<circ> s = s\"\n  apply(rule ring_functions.function_ring_car_eqI[of R _ \"UNIV::nat set\"])\n  using ring_functions_axioms apply auto[1]\n  apply (metis assms function_comp_is_closed_seq nat_seqs_def ring_id_closed)  \n  apply (metis assms nat_seqs_def)\n  by (simp add: assms closed_seqs_memE ring_id_eval)\n  \nlemma(in U_function_ring) ring_seq_smult_closed:\n  assumes \"s \\<in> closed_seqs R\"\n  assumes \"a \\<in> carrier R\"\n  shows \"a \\<odot>\\<^bsub>R\\<^bsup>\\<omega>\\<^esup>\\<^esub> s \\<in> closed_seqs R\"\n  apply(rule closed_seqs_memI) \n  by (metis assms(1) assms(2) closed_seqs_memE nat_seqs_def ring_functions.function_smult_closed ring_functions_axioms)\n\nlemma(in U_function_ring) ring_seq_smult_eval:\n  assumes \"s \\<in> closed_seqs R\"\n  assumes \"a \\<in> carrier R\"\n  shows \"(a \\<odot>\\<^bsub>R\\<^bsup>\\<omega>\\<^esup>\\<^esub> s) k = a \\<otimes> (s k)\"\n  by (metis UNIV_I assms(1) assms(2) nat_seqs_def ring_functions.function_smult_eval ring_functions_axioms)\n\nlemma(in U_function_ring) ring_seq_smult_comp_assoc:\n  assumes \"s \\<in> closed_seqs R\"\n  assumes \"f \\<in> carrier (Fun R)\"\n  assumes \"a \\<in> carrier R\"\n  shows \"((a \\<odot>\\<^bsub>Fun R\\<^esub> f) \\<circ> s) = a \\<odot>\\<^bsub>R\\<^bsup>\\<omega>\\<^esup>\\<^esub> (f \\<circ> s)\"\n  apply(rule ext)\n  using function_smult_eval[of a f] ring_seq_smult_eval[of \"f \\<circ> s\" a] \n  by (simp add: assms(1) assms(2) assms(3) closed_seqs_memE function_comp_is_closed_seq)\n  \nend \n\n(**************************************************************************************************)\n(**************************************************************************************************)\nsection\\<open>Extensional Maps Between the Carriers of two Structures\\<close>\n(**************************************************************************************************)\n(**************************************************************************************************)\n\ndefinition struct_maps :: \"('a, 'c) partial_object_scheme \\<Rightarrow> ('b, 'd) partial_object_scheme \n                              \\<Rightarrow> ('a \\<Rightarrow> 'b) set\" where\n\"struct_maps T S = {f. (f \\<in> (carrier T) \\<rightarrow> (carrier S)) \\<and> f = restrict f (carrier T) }\"\n\ndefinition to_struct_map where\n\"to_struct_map T f = restrict f (carrier T)\"\n\nlemma to_struct_map_closed:\n  assumes \"f \\<in> (carrier T) \\<rightarrow> (carrier S)\"\n  shows \"to_struct_map T f \\<in> (struct_maps T S)\"\n  by (smt PiE_restrict Pi_iff assms mem_Collect_eq restrict_PiE struct_maps_def to_struct_map_def)\n  \nlemma struct_maps_memI:\n  assumes \"\\<And> x. x \\<in> carrier T \\<Longrightarrow> f x \\<in> carrier S\"\n  assumes \"\\<And>x. x \\<notin> carrier T \\<Longrightarrow> f x = undefined\"\n  shows \"f \\<in> struct_maps T S\"\nproof-\n  have 0: \" (f \\<in> (carrier T) \\<rightarrow> (carrier S))\" \n    using assms \n    by blast\n  have 1: \"f  = restrict f (carrier T)\"\n    using assms \n    by (simp add: extensional_def extensional_restrict)\n  show ?thesis \n    using 0 1 \n    unfolding struct_maps_def \n    by blast   \nqed\n\nlemma struct_maps_memE:\n  assumes \"f \\<in> struct_maps T S\"\n  shows  \"\\<And> x. x \\<in> carrier T \\<Longrightarrow> f x \\<in> carrier S\"\n         \"\\<And>x. x \\<notin> carrier T \\<Longrightarrow> f x = undefined\"\n  using assms unfolding struct_maps_def \n  apply blast\n    using assms unfolding struct_maps_def \n    by (metis (mono_tags, lifting) mem_Collect_eq restrict_apply)\n\ntext\\<open>An abbreviation for restricted composition of function of functions. This is necessary for the composition of two struct maps to again be a struct map.\\<close>\nabbreviation(input) rcomp \n  where \"rcomp \\<equiv> FuncSet.compose\"\n\nlemma struct_map_comp:\n  assumes \"g \\<in> (struct_maps T S)\"\n  assumes \"f \\<in> (struct_maps S U)\"\n  shows \"rcomp (carrier T) f g \\<in> (struct_maps T U)\"\nproof(rule struct_maps_memI)\n  show \"\\<And>x. x \\<in> carrier T \\<Longrightarrow> rcomp (carrier T) f g x \\<in> carrier U\"\n    using assms struct_maps_memE(1) \n    by (metis compose_eq)    \n  show \" \\<And>x. x \\<notin> carrier T \\<Longrightarrow> rcomp (carrier T) f g x = undefined\"\n    by (meson compose_extensional extensional_arb)\nqed\n\nlemma r_comp_is_compose:\n  assumes \"g \\<in> (struct_maps T S)\"\n  assumes \"f \\<in> (struct_maps S U)\"\n  assumes \"a \\<in> (carrier T)\"\n  shows \"(rcomp (carrier T) f g) a = (f \\<circ> g) a\"\n  by (simp add: FuncSet.compose_def assms(3))\n\nlemma r_comp_not_in_car:\n  assumes \"g \\<in> (struct_maps T S)\"\n  assumes \"f \\<in> (struct_maps S U)\"\n  assumes \"a \\<notin> (carrier T)\"\n  shows \"(rcomp (carrier T) f g) a = undefined\"\n  by (simp add: FuncSet.compose_def assms(3))\n\ntext\\<open>The reverse composition of two struct maps:\\<close>\n\ndefinition pullback ::\n    \"('a, 'd) partial_object_scheme \\<Rightarrow> ('a \\<Rightarrow> 'b) \\<Rightarrow> ('b \\<Rightarrow> 'c) \\<Rightarrow> ('a \\<Rightarrow> 'c)\" where\n\"pullback T f g = rcomp (carrier T) g f\"\n\nlemma pullback_closed:\n  assumes \"f \\<in> (struct_maps T S)\"\n  assumes \"g \\<in> (struct_maps S U)\"\n  shows \"pullback T f g \\<in> (struct_maps T U)\"\n  by (metis assms(1) assms(2) pullback_def struct_map_comp)\n\ntext\\<open>Composition of struct maps which takes the structure itself rather than the carrier as a parameter:\\<close>\n\ndefinition pushforward :: \n    \"('a, 'd) partial_object_scheme \\<Rightarrow> ('b \\<Rightarrow> 'c) \\<Rightarrow> ('a \\<Rightarrow> 'b)  \\<Rightarrow> ('a \\<Rightarrow> 'c)\" where\n\"pushforward T f g \\<equiv> rcomp (carrier T) f g\"\n\nlemma pushforward_closed:\n  assumes \"g \\<in> (struct_maps T S)\"\n  assumes \"f \\<in> (struct_maps S U)\"\n  shows \"pushforward T f g \\<in> (struct_maps T U)\"\n  using assms(1) assms(2) struct_map_comp \n  by (metis pushforward_def)\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/Padic_Ints/Function_Ring.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9184802484881361, "lm_q2_score": 0.7772998663336157, "lm_q1q2_score": 0.7139345743798944}}
{"text": "theory CommOr\n  imports Main\n\nbegin \n\ntext\\<open> Apply style \\<close>\nlemma lem_w_1 : \"(p \\<or> q) \\<longrightarrow> (q \\<or> p)\"\n  apply (rule impI)\n  apply (erule disjE)\n   apply (rule disjI2)\n   apply assumption\n  apply (rule disjI1)\n  apply assumption\n  done\n\ntext\\<open> Apply style proof, more verbose than the preceding proof \\<close>\nlemma lem_w_2 : \"(p \\<or> q) \\<longrightarrow> (q \\<or> p)\"\n  apply (rule impI)\n  apply (rule disjE)\n    apply assumption\n   apply (rule disjI2)\n   apply assumption\n  apply (rule disjI1)\n  apply assumption\n  done\n\ntext\\<open> Isar style \\<close>\nlemma lem_x_1 : \"(p \\<or> q) \\<longrightarrow> (q \\<or> p)\"\nproof   \n  assume A : \"(p \\<or> q)\" \n  from A show \"(q \\<or> p)\"\n  proof \n    assume \"p\" thus \"(q \\<or> p)\" by (rule disjI2)\n    (* you can substitute '..' for 'by (rule disjI2)'*)\n  next\n    assume \"q\" thus \"(q \\<or> p)\" by (rule disjI1) \n    (* you can substitute '..' for 'by (rule disjI1)'*)\n  qed\nqed\nend", "meta": {"author": "decltypeme", "repo": "cs511", "sha": "be4f4ba351ff94ac35316c1228c0242e1c3449d0", "save_path": "github-repos/isabelle/decltypeme-cs511", "path": "github-repos/isabelle/decltypeme-cs511/cs511-be4f4ba351ff94ac35316c1228c0242e1c3449d0/CommOr.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8438951025545426, "lm_q2_score": 0.8459424295406088, "lm_q1q2_score": 0.713886673332411}}
{"text": "(*  Title:      HOL/Number_Theory/MiscAlgebra.thy\n    Author:     Jeremy Avigad\n\nThese are things that can be added to the Algebra library.\n*)\n\ntheory MiscAlgebra\nimports\n  \"~~/src/HOL/Algebra/Ring\"\n  \"~~/src/HOL/Algebra/FiniteProduct\"\nbegin\n\n(* finiteness stuff *)\n\nlemma bounded_set1_int [intro]: \"finite {(x::int). a < x & x < b & P x}\"\n  apply (subgoal_tac \"{x. a < x & x < b & P x} <= {a<..<b}\")\n  apply (erule finite_subset)\n  apply auto\ndone\n\n\n(* The rest is for the algebra libraries *)\n\n(* These go in Group.thy. *)\n\n(*\n  Show that the units in any monoid give rise to a group.\n\n  The file Residues.thy provides some infrastructure to use\n  facts about the unit group within the ring locale.\n*)\n\n\ndefinition units_of :: \"('a, 'b) monoid_scheme => 'a monoid\" where\n  \"units_of G == (| carrier = Units G,\n     Group.monoid.mult = Group.monoid.mult G,\n     one  = one G |)\"\n\n(*\n\nlemma (in monoid) Units_mult_closed [intro]:\n  \"x : Units G ==> y : Units G ==> x \\<otimes> y : Units G\"\n  apply (unfold Units_def)\n  apply (clarsimp)\n  apply (rule_tac x = \"xaa \\<otimes> xa\" in bexI)\n  apply auto\n  apply (subst m_assoc)\n  apply auto\n  apply (subst (2) m_assoc [symmetric])\n  apply auto\n  apply (subst m_assoc)\n  apply auto\n  apply (subst (2) m_assoc [symmetric])\n  apply auto\ndone\n\n*)\n\nlemma (in monoid) units_group: \"group(units_of G)\"\n  apply (unfold units_of_def)\n  apply (rule groupI)\n  apply auto\n  apply (subst m_assoc)\n  apply auto\n  apply (rule_tac x = \"inv x\" in bexI)\n  apply auto\n  done\n\nlemma (in comm_monoid) units_comm_group: \"comm_group(units_of G)\"\n  apply (rule group.group_comm_groupI)\n  apply (rule units_group)\n  apply (insert comm_monoid_axioms)\n  apply (unfold units_of_def Units_def comm_monoid_def comm_monoid_axioms_def)\n  apply auto\n  done\n\nlemma units_of_carrier: \"carrier (units_of G) = Units G\"\n  unfolding units_of_def by auto\n\nlemma units_of_mult: \"mult(units_of G) = mult G\"\n  unfolding units_of_def by auto\n\nlemma units_of_one: \"one(units_of G) = one G\"\n  unfolding units_of_def by auto\n\nlemma (in monoid) units_of_inv: \"x : Units G ==>\n    m_inv (units_of G) x = m_inv G x\"\n  apply (rule sym)\n  apply (subst m_inv_def)\n  apply (rule the1_equality)\n  apply (rule ex_ex1I)\n  apply (subst (asm) Units_def)\n  apply auto\n  apply (erule inv_unique)\n  apply auto\n  apply (rule Units_closed)\n  apply (simp_all only: units_of_carrier [symmetric])\n  apply (insert units_group)\n  apply auto\n  apply (subst units_of_mult [symmetric])\n  apply (subst units_of_one [symmetric])\n  apply (erule group.r_inv, assumption)\n  apply (subst units_of_mult [symmetric])\n  apply (subst units_of_one [symmetric])\n  apply (erule group.l_inv, assumption)\ndone\n\nlemma (in group) inj_on_const_mult: \"a: (carrier G) ==>\n    inj_on (%x. a \\<otimes> x) (carrier G)\"\n  unfolding inj_on_def by auto\n\nlemma (in group) surj_const_mult: \"a : (carrier G) ==>\n    (%x. a \\<otimes> x) ` (carrier G) = (carrier G)\"\n  apply (auto simp add: image_def)\n  apply (rule_tac x = \"(m_inv G a) \\<otimes> x\" in bexI)\n  apply auto\n(* auto should get this. I suppose we need \"comm_monoid_simprules\"\n   for ac_simps rewriting. *)\n  apply (subst m_assoc [symmetric])\n  apply auto\n  done\n\nlemma (in group) l_cancel_one [simp]: \"x : carrier G \\<Longrightarrow> a : carrier G \\<Longrightarrow>\n    (x \\<otimes> a = x) = (a = one G)\"\n  apply auto\n  apply (subst l_cancel [symmetric])\n  prefer 4\n  apply (erule ssubst)\n  apply auto\n  done\n\nlemma (in group) r_cancel_one [simp]: \"x : carrier G \\<Longrightarrow> a : carrier G \\<Longrightarrow>\n    (a \\<otimes> x = x) = (a = one G)\"\n  apply auto\n  apply (subst r_cancel [symmetric])\n  prefer 4\n  apply (erule ssubst)\n  apply auto\n  done\n\n(* Is there a better way to do this? *)\n\nlemma (in group) l_cancel_one' [simp]: \"x : carrier G \\<Longrightarrow> a : carrier G \\<Longrightarrow>\n    (x = x \\<otimes> a) = (a = one G)\"\n  apply (subst eq_commute)\n  apply simp\n  done\n\nlemma (in group) r_cancel_one' [simp]: \"x : carrier G \\<Longrightarrow> a : carrier G \\<Longrightarrow>\n    (x = a \\<otimes> x) = (a = one G)\"\n  apply (subst eq_commute)\n  apply simp\n  done\n\n(* This should be generalized to arbitrary groups, not just commutative\n   ones, using Lagrange's theorem. *)\n\nlemma (in comm_group) power_order_eq_one:\n  assumes fin [simp]: \"finite (carrier G)\"\n    and a [simp]: \"a : carrier G\"\n  shows \"a (^) card(carrier G) = one G\"\nproof -\n  have \"(\\<Otimes>x:carrier G. x) = (\\<Otimes>x:carrier G. a \\<otimes> x)\"\n    by (subst (2) finprod_reindex [symmetric],\n      auto simp add: Pi_def inj_on_const_mult surj_const_mult)\n  also have \"\\<dots> = (\\<Otimes>x:carrier G. a) \\<otimes> (\\<Otimes>x:carrier G. x)\"\n    by (auto simp add: finprod_multf Pi_def)\n  also have \"(\\<Otimes>x:carrier G. a) = a (^) card(carrier G)\"\n    by (auto simp add: finprod_const)\n  finally show ?thesis\n(* uses the preceeding lemma *)\n    by auto\nqed\n\n\n(* Miscellaneous *)\n\nlemma (in cring) field_intro2: \"\\<zero>\\<^bsub>R\\<^esub> ~= \\<one>\\<^bsub>R\\<^esub> \\<Longrightarrow> ALL x : carrier R - {\\<zero>\\<^bsub>R\\<^esub>}.\n    x : Units R \\<Longrightarrow> field R\"\n  apply (unfold_locales)\n  apply (insert cring_axioms, auto)\n  apply (rule trans)\n  apply (subgoal_tac \"a = (a \\<otimes> b) \\<otimes> inv b\")\n  apply assumption\n  apply (subst m_assoc)\n  apply auto\n  apply (unfold Units_def)\n  apply auto\n  done\n\nlemma (in monoid) inv_char: \"x : carrier G \\<Longrightarrow> y : carrier G \\<Longrightarrow>\n    x \\<otimes> y = \\<one> \\<Longrightarrow> y \\<otimes> x = \\<one> \\<Longrightarrow> inv x = y\"\n  apply (subgoal_tac \"x : Units G\")\n  apply (subgoal_tac \"y = inv x \\<otimes> \\<one>\")\n  apply simp\n  apply (erule subst)\n  apply (subst m_assoc [symmetric])\n  apply auto\n  apply (unfold Units_def)\n  apply auto\n  done\n\nlemma (in comm_monoid) comm_inv_char: \"x : carrier G \\<Longrightarrow> y : carrier G \\<Longrightarrow>\n  x \\<otimes> y = \\<one> \\<Longrightarrow> inv x = y\"\n  apply (rule inv_char)\n  apply auto\n  apply (subst m_comm, auto)\n  done\n\nlemma (in ring) inv_neg_one [simp]: \"inv (\\<ominus> \\<one>) = \\<ominus> \\<one>\"\n  apply (rule inv_char)\n  apply (auto simp add: l_minus r_minus)\n  done\n\nlemma (in monoid) inv_eq_imp_eq: \"x : Units G \\<Longrightarrow> y : Units G \\<Longrightarrow>\n    inv x = inv y \\<Longrightarrow> x = y\"\n  apply (subgoal_tac \"inv(inv x) = inv(inv y)\")\n  apply (subst (asm) Units_inv_inv)+\n  apply auto\n  done\n\nlemma (in ring) Units_minus_one_closed [intro]: \"\\<ominus> \\<one> : Units R\"\n  apply (unfold Units_def)\n  apply auto\n  apply (rule_tac x = \"\\<ominus> \\<one>\" in bexI)\n  apply auto\n  apply (simp add: l_minus r_minus)\n  done\n\nlemma (in monoid) inv_one [simp]: \"inv \\<one> = \\<one>\"\n  apply (rule inv_char)\n  apply auto\n  done\n\nlemma (in ring) inv_eq_neg_one_eq: \"x : Units R \\<Longrightarrow> (inv x = \\<ominus> \\<one>) = (x = \\<ominus> \\<one>)\"\n  apply auto\n  apply (subst Units_inv_inv [symmetric])\n  apply auto\n  done\n\nlemma (in monoid) inv_eq_one_eq: \"x : Units G \\<Longrightarrow> (inv x = \\<one>) = (x = \\<one>)\"\nby (metis Units_inv_inv inv_one)\n\n\n(* This goes in FiniteProduct *)\n\nlemma (in comm_monoid) finprod_UN_disjoint:\n  \"finite I \\<Longrightarrow> (ALL i:I. finite (A i)) \\<longrightarrow> (ALL i:I. ALL j:I. i ~= j \\<longrightarrow>\n     (A i) Int (A j) = {}) \\<longrightarrow>\n      (ALL i:I. ALL x: (A i). g x : carrier G) \\<longrightarrow>\n        finprod G g (UNION I A) = finprod G (%i. finprod G g (A i)) I\"\n  apply (induct set: finite)\n  apply force\n  apply clarsimp\n  apply (subst finprod_Un_disjoint)\n  apply blast\n  apply (erule finite_UN_I)\n  apply blast\n  apply (fastforce)\n  apply (auto intro!: funcsetI finprod_closed)\n  done\n\nlemma (in comm_monoid) finprod_Union_disjoint:\n  \"[| finite C; (ALL A:C. finite A & (ALL x:A. f x : carrier G));\n      (ALL A:C. ALL B:C. A ~= B --> A Int B = {}) |]\n   ==> finprod G f (Union C) = finprod G (finprod G f) C\"\n  apply (frule finprod_UN_disjoint [of C id f])\n  apply (auto simp add: SUP_def)\n  done\n\nlemma (in comm_monoid) finprod_one:\n    \"finite A \\<Longrightarrow> (\\<And>x. x:A \\<Longrightarrow> f x = \\<one>) \\<Longrightarrow> finprod G f A = \\<one>\"\n  by (induct set: finite) auto\n\n\n(* need better simplification rules for rings *)\n(* the next one holds more generally for abelian groups *)\n\nlemma (in cring) sum_zero_eq_neg:\n    \"x : carrier R \\<Longrightarrow> y : carrier R \\<Longrightarrow> x \\<oplus> y = \\<zero> \\<Longrightarrow> x = \\<ominus> y\"\nby (metis minus_equality)\n\n(* there's a name conflict -- maybe \"domain\" should be\n   \"integral_domain\" *)\n\nlemma (in Ring.domain) square_eq_one:\n  fixes x\n  assumes [simp]: \"x : carrier R\" and\n    \"x \\<otimes> x = \\<one>\"\n  shows \"x = \\<one> | x = \\<ominus>\\<one>\"\nproof -\n  have \"(x \\<oplus> \\<one>) \\<otimes> (x \\<oplus> \\<ominus> \\<one>) = x \\<otimes> x \\<oplus> \\<ominus> \\<one>\"\n    by (simp add: ring_simprules)\n  also from `x \\<otimes> x = \\<one>` have \"\\<dots> = \\<zero>\"\n    by (simp add: ring_simprules)\n  finally have \"(x \\<oplus> \\<one>) \\<otimes> (x \\<oplus> \\<ominus> \\<one>) = \\<zero>\" .\n  then have \"(x \\<oplus> \\<one>) = \\<zero> | (x \\<oplus> \\<ominus> \\<one>) = \\<zero>\"\n    by (intro integral, auto)\n  then show ?thesis\n    apply auto\n    apply (erule notE)\n    apply (rule sum_zero_eq_neg)\n    apply auto\n    apply (subgoal_tac \"x = \\<ominus> (\\<ominus> \\<one>)\")\n    apply (simp add: ring_simprules)\n    apply (rule sum_zero_eq_neg)\n    apply auto\n    done\nqed\n\nlemma (in Ring.domain) inv_eq_self: \"x : Units R \\<Longrightarrow>\n    x = inv x \\<Longrightarrow> x = \\<one> | x = \\<ominus> \\<one>\"\nby (metis Units_closed Units_l_inv square_eq_one)\n\n\n(*\n  The following translates theorems about groups to the facts about\n  the units of a ring. (The list should be expanded as more things are\n  needed.)\n*)\n\nlemma (in ring) finite_ring_finite_units [intro]:\n    \"finite (carrier R) \\<Longrightarrow> finite (Units R)\"\n  by (rule finite_subset) auto\n\nlemma (in monoid) units_of_pow:\n    \"x : Units G \\<Longrightarrow> x (^)\\<^bsub>units_of G\\<^esub> (n::nat) = x (^)\\<^bsub>G\\<^esub> n\"\n  apply (induct n)\n  apply (auto simp add: units_group group.is_monoid\n    monoid.nat_pow_0 monoid.nat_pow_Suc units_of_one units_of_mult)\n  done\n\nlemma (in cring) units_power_order_eq_one: \"finite (Units R) \\<Longrightarrow> a : Units R\n    \\<Longrightarrow> a (^) card(Units R) = \\<one>\"\n  apply (subst units_of_carrier [symmetric])\n  apply (subst units_of_one [symmetric])\n  apply (subst units_of_pow [symmetric])\n  apply assumption\n  apply (rule comm_group.power_order_eq_one)\n  apply (rule units_comm_group)\n  apply (unfold units_of_def, auto)\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/HOL/Number_Theory/MiscAlgebra.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950986284992, "lm_q2_score": 0.8459424334245617, "lm_q1q2_score": 0.7138866732888531}}
{"text": "section \\<open>Representing Roots of Polynomials with Algebraic Coefficients\\<close>\n\ntext \\<open>We provide an algorithm to compute a non-zero integer polynomial $q$ from a polynomial\n $p$ with algebraic coefficients such that all roots of $p$ are also roots of $q$.\n\n In this way, we have a constructive proof that the set of complex algebraic numbers \n is algebraically closed.\\<close>\n\ntheory Roots_of_Algebraic_Poly\n  imports \n    Algebraic_Numbers.Complex_Algebraic_Numbers\n    Multivariate_Resultant\n    Is_Int_To_Int\nbegin\n\nsubsection \\<open>Preliminaries\\<close>\n\nhide_const (open) up_ring.monom\nhide_const (open) MPoly_Type.monom\n\nlemma map_mpoly_Const: \"f 0 = 0 \\<Longrightarrow> map_mpoly f (Const i) = Const (f i)\" \n  by (intro mpoly_eqI, auto simp: coeff_map_mpoly mpoly_coeff_Const)\n\nlemma map_mpoly_Var: \"f 1 = 1 \\<Longrightarrow> map_mpoly (f :: 'b :: zero_neq_one \\<Rightarrow> _) (Var i) = Var i\"\n  by (intro mpoly_eqI, auto simp: coeff_map_mpoly coeff_Var when_def)\n\nlemma map_mpoly_monom: \"f 0 = 0 \\<Longrightarrow> map_mpoly f (MPoly_Type.monom m a) = (MPoly_Type.monom m (f a))\" \n  by (intro mpoly_eqI, unfold coeff_map_mpoly if_distrib coeff_monom, simp add: when_def)\n\nlemma remove_key_single': \n  \"remove_key v (Poly_Mapping.single w n) = (if v = w then 0 else Poly_Mapping.single w n)\"\n  by (metis add.right_neutral lookup_single_not_eq remove_key_single remove_key_sum single_zero)\n\ncontext comm_monoid_add_hom\nbegin\nlemma hom_Sum_any: assumes fin: \"finite {x. f x \\<noteq> 0}\"\n  shows \"hom (Sum_any f) = Sum_any (\\<lambda> x. hom (f x))\" \n  unfolding Sum_any.expand_set hom_sum\n  by (rule sum.mono_neutral_right[OF fin], auto)\n \nlemma comm_monoid_add_hom_mpoly_map: \"comm_monoid_add_hom (map_mpoly hom)\" \n  by (unfold_locales; intro mpoly_eqI, auto simp: hom_add)\n\nlemma map_mpoly_hom_Const: \"map_mpoly hom (Const i) = Const (hom i)\" \n  by (rule map_mpoly_Const, simp)\n\nlemma map_mpoly_hom_monom: \"map_mpoly hom (MPoly_Type.monom m a) = MPoly_Type.monom m (hom a)\" \n  by (rule map_mpoly_monom, simp)\nend\n\ncontext comm_ring_hom\nbegin\nlemma mpoly_to_poly_map_mpoly_hom: \"mpoly_to_poly x (map_mpoly hom p) = map_poly hom (mpoly_to_poly x p)\"\n  by (rule poly_eqI, unfold coeff_mpoly_to_poly coeff_map_poly_hom, subst coeff_map_mpoly', auto)\n \nlemma comm_ring_hom_mpoly_map: \"comm_ring_hom (map_mpoly hom)\" \nproof -\n  interpret mp: comm_monoid_add_hom \"map_mpoly hom\" by (rule comm_monoid_add_hom_mpoly_map)\n  show ?thesis\n  proof (unfold_locales)\n    show \"map_mpoly hom 1 = 1\"\n      by (intro mpoly_eqI, simp add: MPoly_Type.coeff_def, transfer fixing: hom, transfer fixing: hom, auto simp: when_def)\n    fix x y\n    show \"map_mpoly hom (x * y) = map_mpoly hom x * map_mpoly hom y\" \n      apply (intro mpoly_eqI)\n      apply (subst coeff_map_mpoly', force)\n      apply (unfold coeff_mpoly_times) \n      apply (subst prod_fun_unfold_prod, blast, blast)\n      apply (subst prod_fun_unfold_prod, blast, blast) \n      apply (subst coeff_map_mpoly', force)\n      apply (subst coeff_map_mpoly', force)\n      apply (subst hom_Sum_any) \n      subgoal \n      proof -\n        let ?X = \"{a. MPoly_Type.coeff x a \\<noteq> 0}\" \n        let ?Y = \"{a. MPoly_Type.coeff y a \\<noteq> 0}\" \n        have fin: \"finite (?X \\<times> ?Y)\" by auto\n        show ?thesis \n          by (rule finite_subset[OF _ fin], auto)\n      qed\n      apply (rule Sum_any.cong)\n      subgoal for mon pair by (cases pair, auto simp: hom_mult when_def)\n      done\n  qed\nqed\n\nlemma mpoly_to_mpoly_poly_map_mpoly_hom: \n  \"mpoly_to_mpoly_poly x (map_mpoly hom p) = map_poly (map_mpoly hom) (mpoly_to_mpoly_poly x p)\" \nproof -\n  interpret mp: comm_ring_hom \"map_mpoly hom\" by (rule comm_ring_hom_mpoly_map)\n  interpret mmp: map_poly_comm_monoid_add_hom \"map_mpoly hom\" ..\n  show ?thesis unfolding mpoly_to_mpoly_poly_def \n    apply (subst mmp.hom_Sum_any, force)\n    apply (rule Sum_any.cong)\n    apply (unfold mp.map_poly_hom_monom map_mpoly_hom_monom)\n    by auto\nqed    \nend\n\ncontext inj_comm_ring_hom\nbegin\nlemma inj_comm_ring_hom_mpoly_map: \"inj_comm_ring_hom (map_mpoly hom)\" \nproof -\n  interpret mp: comm_ring_hom \"map_mpoly hom\" by (rule comm_ring_hom_mpoly_map)\n  show ?thesis\n  proof (unfold_locales)\n    fix x\n    assume 0: \"map_mpoly hom x = 0\"     \n    show \"x = 0\" \n    proof (intro mpoly_eqI)\n      fix m\n      show \"MPoly_Type.coeff x m = MPoly_Type.coeff 0 m\" \n        using arg_cong[OF 0, of \"\\<lambda> p. MPoly_Type.coeff p m\"] by simp\n    qed\n  qed\nqed\n\nlemma resultant_mpoly_poly_hom: \"resultant_mpoly_poly x (map_mpoly hom p) (map_poly hom q) = map_mpoly hom (resultant_mpoly_poly x p q)\"\nproof -\n  interpret mp: inj_comm_ring_hom \"map_mpoly hom\" by (rule inj_comm_ring_hom_mpoly_map)\n  show ?thesis\n  unfolding resultant_mpoly_poly_def \n  unfolding mpoly_to_mpoly_poly_map_mpoly_hom \n  apply (subst mp.resultant_map_poly[symmetric])\n  subgoal by (subst mp.degree_map_poly_hom, unfold_locales, auto) \n  subgoal by (subst mp.degree_map_poly_hom, unfold_locales, auto) \n  subgoal\n    apply (rule arg_cong[of _ _ \"resultant _\"], intro poly_eqI)\n    apply (subst coeff_map_poly, force)+\n    by (simp add: map_mpoly_hom_Const)\n  done\nqed\nend\n\nlemma map_insort_key: assumes [simp]: \"\\<And> x y. g1 x \\<le> g1 y \\<longleftrightarrow> g2 (f x) \\<le> g2 (f y)\"\n  shows \"map f (insort_key g1 a xs) = insort_key g2 (f a) (map f xs)\" \n  by (induct xs, auto)\n\nlemma map_sort_key: assumes [simp]: \"\\<And> x y. g1 x \\<le> g1 y \\<longleftrightarrow> g2 (f x) \\<le> g2 (f y)\"\n  shows \"map f (sort_key g1 xs) = sort_key g2 (map f xs)\" \n  by (induct xs, auto simp: map_insort_key)\n\nhide_const (open) MPoly_Type.degree\nhide_const (open) MPoly_Type.coeffs\nhide_const (open) MPoly_Type.coeff\nhide_const (open) Symmetric_Polynomials.lead_coeff\n\nsubsection \\<open>More Facts about Resultants\\<close>\n\nlemma resultant_iff_coprime_main:\n  fixes f g :: \"'a :: field poly\"\n  assumes deg: \"degree f > 0 \\<or> degree g > 0\" \nshows \"resultant f g = 0 \\<longleftrightarrow> \\<not> coprime f g\" \nproof (cases \"resultant f g = 0\")\n  case True\n  from resultant_zero_imp_common_factor[OF deg True] True\n  show ?thesis by simp\nnext\n  case False\n  from deg have fg: \"f \\<noteq> 0 \\<or> g \\<noteq> 0\" by auto\n  from resultant_non_zero_imp_coprime[OF False fg] deg False\n  show ?thesis by auto\nqed\n\nlemma resultant_zero_iff_coprime: fixes f g :: \"'a :: field poly\" \n  assumes \"f \\<noteq> 0 \\<or> g \\<noteq> 0\" \n  shows \"resultant f g = 0 \\<longleftrightarrow> \\<not> coprime f g\" \nproof (cases \"degree f > 0 \\<or> degree g > 0\")\n  case True\n  thus ?thesis using resultant_iff_coprime_main[OF True] by simp\nnext\n  case False\n  hence \"degree f = 0\" \"degree g = 0\" by auto\n  then obtain c d where f: \"f = [:c:]\" and g: \"g = [:d:]\" using degree0_coeffs by metis+\n  from assms have cd: \"c \\<noteq> 0 \\<or> d \\<noteq> 0\" unfolding f g by auto\n  have res: \"resultant f g = 1\" unfolding f g resultant_const by auto\n  have \"coprime f g\"  \n    by (metis assms one_neq_zero res resultant_non_zero_imp_coprime)\n  with res show ?thesis by auto\nqed\n\ntext \\<open>The problem with the upcoming lemma is that \"root\" and \"irreducibility\" refer to the same type.\n  In the actual application we interested in \"irreducibility\" over the integers, but the roots\n  we are interested in are either real or complex.\\<close>\nlemma resultant_zero_iff_common_root_irreducible: fixes f g :: \"'a :: field poly\"\n  assumes irr: \"irreducible g\" \n  and root: \"poly g a = 0\" (* g has at least some root *)\nshows \"resultant f g = 0 \\<longleftrightarrow> (\\<exists> x. poly f x = 0 \\<and> poly g x = 0)\" \nproof -\n  from irr root have deg: \"degree g \\<noteq> 0\" using degree0_coeffs[of g] by fastforce\n  show ?thesis\n  proof \n    assume \"\\<exists> x. poly f x = 0 \\<and> poly g x = 0\" \n    then obtain x where \"poly f x = 0\" \"poly g x = 0\" by auto\n    from resultant_zero[OF _ this] deg show \"resultant f g = 0\" by auto\n  next\n    assume \"resultant f g = 0\"\n    from resultant_zero_imp_common_factor[OF _ this] deg\n    have \"\\<not> coprime f g\" by auto\n    from this[unfolded not_coprime_iff_common_factor] obtain r where\n       rf: \"r dvd f\" and rg: \"r dvd g\" and r: \"\\<not> is_unit r\" by auto\n    from rg r irr have \"g dvd r\"\n      by (meson algebraic_semidom_class.irreducible_altdef)\n    with rf have \"g dvd f\" by auto\n    with root show \"\\<exists> x. poly f x = 0 \\<and> poly g x = 0\" \n      by (intro exI[of _ a], auto simp: dvd_def)\n  qed\nqed\n\n\nlemma resultant_zero_iff_common_root_complex: fixes f g :: \"complex poly\"\n  assumes g: \"g \\<noteq> 0\" \nshows \"resultant f g = 0 \\<longleftrightarrow> (\\<exists> x. poly f x = 0 \\<and> poly g x = 0)\" \nproof (cases \"degree g = 0\")\n  case deg: False\n  show ?thesis\n  proof \n    assume \"\\<exists> x. poly f x = 0 \\<and> poly g x = 0\" \n    then obtain x where \"poly f x = 0\" \"poly g x = 0\" by auto\n    from resultant_zero[OF _ this] deg show \"resultant f g = 0\" by auto\n  next\n    assume \"resultant f g = 0\"\n    from resultant_zero_imp_common_factor[OF _ this] deg\n    have \"\\<not> coprime f g\" by auto\n    from this[unfolded not_coprime_iff_common_factor] obtain r where\n       rf: \"r dvd f\" and rg: \"r dvd g\" and r: \"\\<not> is_unit r\" by auto\n    from rg g have r0: \"r \\<noteq> 0\" by auto\n    with r have degr: \"degree r \\<noteq> 0\" by simp\n    hence \"\\<not> constant (poly r)\"\n      by (simp add: constant_degree)\n    from fundamental_theorem_of_algebra[OF this] obtain a where root: \"poly r a = 0\" by auto\n    from rf rg root show \"\\<exists> x. poly f x = 0 \\<and> poly g x = 0\" \n      by (intro exI[of _ a], auto simp: dvd_def)\n  qed\nnext\n  case deg: True\n  from degree0_coeffs[OF deg] obtain c where gc: \"g = [:c:]\" by auto\n  from gc g have c: \"c \\<noteq> 0\" by auto\n  hence \"resultant f g \\<noteq> 0\" unfolding gc resultant_const by simp\n  with gc c show ?thesis by auto\nqed\n\nsubsection \\<open>Systems of Polynomials\\<close>\n\ntext \\<open>Definition of solving a system of polynomials, one being multivariate\\<close>\ndefinition mpoly_polys_solution :: \"'a :: field mpoly \\<Rightarrow> (nat \\<Rightarrow> 'a poly) \\<Rightarrow> nat set \\<Rightarrow> (nat \\<Rightarrow> 'a) \\<Rightarrow> bool\" where\n  \"mpoly_polys_solution p qs N \\<alpha> = (\n       insertion \\<alpha> p = 0 \\<and>\n       (\\<forall> i \\<in> N. poly (qs i) (\\<alpha> (Suc i)) = 0))\"\n\ntext \\<open>The upcoming lemma shows how to eliminate single variables in multi-variate root-problems.\n  Because of the problem mentioned in @{thm [source] resultant_zero_iff_common_root_irreducible},\n  we here restrict to polynomials over the complex numbers. Since the result computations are homomorphisms,\n  we are able to lift it to integer polynomials where we are interested in real or complex\n  roots.\\<close>\nlemma resultant_mpoly_polys_solution: fixes p :: \"complex mpoly\" \n  assumes nz: \"0 \\<notin> qs ` N\" \n  and i: \"i \\<in> N\"\nshows \"mpoly_polys_solution (resultant_mpoly_poly (Suc i) p (qs i)) qs (N - {i}) \\<alpha>\n  \\<longleftrightarrow> (\\<exists> v. mpoly_polys_solution p qs N (\\<alpha>((Suc i) := v)))\" \nproof -\n  let ?x = \"Suc i\" \n  let ?q = \"qs i\" \n  let ?mres = \"resultant_mpoly_poly ?x p ?q\"\n  from i obtain M where N: \"N = insert i M\" and MN: \"M = N - {i}\" and iM: \"i \\<notin> M\" by auto\n  from nz i have nzq: \"?q \\<noteq> 0\" by auto\n  hence lc0: \"lead_coeff (qs i) \\<noteq> 0\" by auto\n  have \"mpoly_polys_solution ?mres qs (N - {i}) \\<alpha> \\<longleftrightarrow>\n   insertion \\<alpha> ?mres = 0 \\<and> (\\<forall> i \\<in> M. poly (qs i) (\\<alpha> (Suc i)) = 0)\" \n    unfolding mpoly_polys_solution_def MN ..\n  also have \"insertion \\<alpha> ?mres = 0 \\<longleftrightarrow> resultant (partial_insertion \\<alpha> ?x p) ?q = 0\" \n    by (rule insertion_resultant_mpoly_poly_zero[OF nzq])\n  also have \"\\<dots> \\<longleftrightarrow> (\\<exists>v. poly (partial_insertion \\<alpha> ?x p) v = 0 \\<and> poly ?q v = 0)\" \n    by (rule resultant_zero_iff_common_root_complex[OF nzq])\n  also have \"\\<dots> \\<longleftrightarrow> (\\<exists>v. insertion (\\<alpha>(?x := v)) p = 0 \\<and> poly ?q v = 0)\" (is \"?lhs = ?rhs\")\n  proof (intro iff_exI conj_cong refl arg_cong[of _ _ \"\\<lambda> x. x = 0\"])\n    fix v\n    have \"poly (partial_insertion \\<alpha> ?x p) v = poly (partial_insertion \\<alpha> ?x p) ((\\<alpha>(?x := v)) ?x)\" by simp\n    also have \"\\<dots> = insertion (\\<alpha>(?x := v)) p\" \n      by (rule insertion_partial_insertion, auto)\n    finally show \"poly (partial_insertion \\<alpha> ?x p) v = insertion (\\<alpha>(?x := v)) p\" .\n  qed\n  also have \"\\<dots> \\<and> (\\<forall>i\\<in>M. poly (qs i) (\\<alpha> (Suc i)) = 0)\n    \\<longleftrightarrow> (\\<exists>v. insertion (\\<alpha>(?x := v)) p = 0 \\<and> poly (qs i) v = 0 \\<and> (\\<forall>i\\<in>M. poly (qs i) ((\\<alpha>(?x := v)) (Suc i)) = 0))\"\n    using iM by auto\n  also have \"\\<dots>  \\<longleftrightarrow> (\\<exists> v. mpoly_polys_solution p qs N (\\<alpha>((Suc i) := v)))\" \n    unfolding mpoly_polys_solution_def N by (intro iff_exI, auto)\n  finally\n  show ?thesis .\nqed\n\ntext \\<open>We now restrict solutions to be evaluated to zero outside the variable range. Then there are only finitely \n  many solutions for our applications.\\<close>\ndefinition mpoly_polys_zero_solution :: \"'a :: field mpoly \\<Rightarrow> (nat \\<Rightarrow> 'a poly) \\<Rightarrow> nat set \\<Rightarrow> (nat \\<Rightarrow> 'a) \\<Rightarrow> bool\" where\n  \"mpoly_polys_zero_solution p qs N \\<alpha> = (mpoly_polys_solution p qs N \\<alpha>\n    \\<and> (\\<forall> i. i \\<notin> insert 0 (Suc ` N) \\<longrightarrow> \\<alpha> i = 0))\" \n\nlemma resultant_mpoly_polys_zero_solution: fixes p :: \"complex mpoly\" \n  assumes nz: \"0 \\<notin> qs ` N\" \n  and i: \"i \\<in> N\"\nshows \n  \"mpoly_polys_zero_solution (resultant_mpoly_poly (Suc i) p (qs i)) qs (N - {i}) \\<alpha> \n    \\<Longrightarrow> \\<exists> v. mpoly_polys_zero_solution p qs N (\\<alpha>(Suc i := v))\" \n  \"mpoly_polys_zero_solution p qs N \\<alpha> \n    \\<Longrightarrow> mpoly_polys_zero_solution (resultant_mpoly_poly (Suc i) p (qs i)) qs (N - {i}) (\\<alpha>(Suc i := 0))\" \nproof -\n  assume \"mpoly_polys_zero_solution (resultant_mpoly_poly (Suc i) p (qs i)) qs (N - {i}) \\<alpha>\" \n  hence 1: \"mpoly_polys_solution (resultant_mpoly_poly (Suc i) p (qs i)) qs (N - {i}) \\<alpha>\" and 2: \"(\\<forall> i. i \\<notin> insert 0 (Suc ` (N - {i})) \\<longrightarrow> \\<alpha> i = 0)\" \n    unfolding mpoly_polys_zero_solution_def by auto\n  from resultant_mpoly_polys_solution[of qs N _ p \\<alpha>, OF nz i] 1 obtain v where \"mpoly_polys_solution p qs N (\\<alpha>(Suc i := v))\" by auto\n  with 2 have \"mpoly_polys_zero_solution p qs N (\\<alpha>(Suc i := v))\" using i unfolding mpoly_polys_zero_solution_def by auto\n  thus \"\\<exists> v. mpoly_polys_zero_solution p qs N (\\<alpha>(Suc i := v))\" ..\nnext\n  assume \"mpoly_polys_zero_solution p qs N \\<alpha>\" \n  from this[unfolded mpoly_polys_zero_solution_def] have 1: \"mpoly_polys_solution p qs N \\<alpha>\" and 2: \"\\<forall>i. i \\<notin> insert 0 (Suc ` N) \\<longrightarrow> \\<alpha> i = 0\" by auto\n  from 1 have \"mpoly_polys_solution p qs N (\\<alpha>(Suc i := \\<alpha> (Suc i)))\" by auto\n  hence \"\\<exists> v. mpoly_polys_solution p qs N (\\<alpha>(Suc i := v))\" by blast\n  with resultant_mpoly_polys_solution[of qs N _ p \\<alpha>, OF nz i] have \"mpoly_polys_solution (resultant_mpoly_poly (Suc i) p (qs i)) qs (N - {i}) \\<alpha>\" by auto\n  hence \"mpoly_polys_solution (resultant_mpoly_poly (Suc i) p (qs i)) qs (N - {i}) (\\<alpha> (Suc i := 0))\"\n    unfolding mpoly_polys_solution_def \n    apply simp\n    apply (subst insertion_irrelevant_vars[of _ _ \\<alpha>])\n    by (insert vars_resultant_mpoly_poly, auto)\n  thus \"mpoly_polys_zero_solution (resultant_mpoly_poly (Suc i) p (qs i)) qs (N - {i}) (\\<alpha>(Suc i := 0))\" \n    unfolding mpoly_polys_zero_solution_def using 2 by auto\nqed\n\ntext \\<open>The following two lemmas show that if we start with a system of polynomials with finitely\n  many solutions, then the resulting polynomial cannot be the zero-polynomial.\\<close>\nlemma finite_resultant_mpoly_polys_non_empty: fixes p :: \"complex mpoly\" \n  assumes nz: \"0 \\<notin> qs ` N\" \n  and i: \"i \\<in> N\"\n  and fin: \"finite {\\<alpha>. mpoly_polys_zero_solution p qs N \\<alpha>}\" \nshows \"finite {\\<alpha>. mpoly_polys_zero_solution (resultant_mpoly_poly (Suc i) p (qs i)) qs (N - {i}) \\<alpha>}\" \nproof -\n  let ?solN = \"mpoly_polys_zero_solution p qs N\" \n  let ?solN1 = \"mpoly_polys_zero_solution (resultant_mpoly_poly (Suc i) p (qs i)) qs (N - {i})\" \n  let ?x = \"Suc i\" \n  note defs = mpoly_polys_zero_solution_def\n  define zero where \"zero \\<alpha> = \\<alpha>(?x := 0)\" for \\<alpha> :: \"nat \\<Rightarrow> complex\" \n  {\n    fix \\<alpha>\n    assume sol: \"?solN1 \\<alpha>\" \n    from sol[unfolded defs] have 0: \"\\<alpha> ?x = 0\" by auto\n    from resultant_mpoly_polys_zero_solution(1)[of qs N i p, OF nz i sol] obtain v \n      where \"?solN (\\<alpha>(?x := v))\" by auto\n    hence sol: \"\\<alpha>(?x := v) \\<in> {\\<alpha>. ?solN \\<alpha>}\" by auto\n    hence \"zero (\\<alpha>(?x := v)) \\<in> zero ` {\\<alpha>. ?solN \\<alpha>}\" by auto\n    also have \"zero (\\<alpha>(?x := v)) = \\<alpha>\" using 0 by (auto simp: zero_def)\n    finally have \"\\<alpha> \\<in> zero ` {\\<alpha>. ?solN \\<alpha>}\" .\n  }\n  hence \"{\\<alpha>. ?solN1 \\<alpha>} \\<subseteq> zero ` {\\<alpha>. ?solN \\<alpha>}\" by blast\n  from finite_subset[OF this finite_imageI[OF fin]]\n  show ?thesis .\nqed\n\nlemma finite_resultant_mpoly_polys_empty: fixes p :: \"complex mpoly\" \n  assumes \"finite {\\<alpha>. mpoly_polys_zero_solution p qs {} \\<alpha>}\" \n  shows \"p \\<noteq> 0\" \nproof\n  define g where \"g x = (\\<lambda> i :: nat. if i = 0 then x else 0)\" for x :: complex\n  assume \"p = 0\" \n  hence \"\\<forall> x. mpoly_polys_zero_solution p qs {} (g x)\" \n    unfolding mpoly_polys_zero_solution_def mpoly_polys_solution_def g_def by auto\n  hence \"range g \\<subseteq> {\\<alpha>. mpoly_polys_zero_solution p qs {} \\<alpha>}\" by auto\n  from finite_subset[OF this assms] have \"finite (range g)\" .\n  moreover have \"inj g\" unfolding g_def inj_on_def by metis\n  ultimately have \"finite (UNIV :: complex set)\" by simp\n  thus False using infinite_UNIV_char_0 by auto\nqed\n\nsubsection \\<open>Elimination of Auxiliary Variables\\<close>\n\nfun eliminate_aux_vars :: \"'a :: comm_ring_1 mpoly \\<Rightarrow> (nat \\<Rightarrow> 'a poly) \\<Rightarrow> nat list \\<Rightarrow> 'a poly\" where\n  \"eliminate_aux_vars p qs [] = mpoly_to_poly 0 p\" \n| \"eliminate_aux_vars p qs (i # is) = eliminate_aux_vars (resultant_mpoly_poly (Suc i) p (qs i)) qs is\" \n      \n\nlemma eliminate_aux_vars_of_int_poly: \n  \"eliminate_aux_vars (map_mpoly (of_int :: _ \\<Rightarrow> 'a :: {comm_ring_1,ring_char_0}) mp) (of_int_poly \\<circ> qs) is\n  = of_int_poly (eliminate_aux_vars mp qs is)\"  \nproof -\n  let ?h = \"of_int :: _ \\<Rightarrow> 'a\" \n  interpret mp: comm_ring_hom \"(map_mpoly ?h)\" \n    by (rule of_int_hom.comm_ring_hom_mpoly_map)\n  show ?thesis\n  proof (induct \"is\" arbitrary: mp)\n    case Nil\n    show ?case by (simp add: of_int_hom.mpoly_to_poly_map_mpoly_hom)\n  next\n    case (Cons i \"is\" mp)\n    show ?case unfolding eliminate_aux_vars.simps Cons[symmetric]\n      apply (rule arg_cong[of _ _ \"\\<lambda> x. eliminate_aux_vars x _ _\"], unfold o_def)\n      by (rule of_int_hom.resultant_mpoly_poly_hom)\n  qed\nqed\n\ntext \\<open>The polynomial of the elimination process will represent the first value @{term \"\\<alpha> 0 :: complex\"} of any\n  solution to the multi-polynomial problem.\\<close>\nlemma eliminate_aux_vars: fixes p :: \"complex mpoly\" \n  assumes \"distinct is\" \n  and \"vars p \\<subseteq> insert 0 (Suc ` set is)\" \n  and \"finite {\\<alpha>. mpoly_polys_zero_solution p qs (set is) \\<alpha>}\"\n  and \"0 \\<notin> qs ` set is\" \n  and \"mpoly_polys_solution p qs (set is) \\<alpha>\" \nshows \"poly (eliminate_aux_vars p qs is) (\\<alpha> 0) = 0 \\<and> eliminate_aux_vars p qs is \\<noteq> 0\"\n  using assms\nproof (induct \"is\" arbitrary: p)\n  case (Nil p)\n  from Nil(3) finite_resultant_mpoly_polys_empty[of p] \n  have p0: \"p \\<noteq> 0\" by auto\n  from Nil(2) have vars: \"vars p \\<subseteq> {0}\" by auto\n  note [simp] = poly_eq_insertion[OF this]\n  from Nil(5)[unfolded mpoly_polys_solution_def] \n  have \"insertion \\<alpha> p = 0\" by auto\n  also have \"insertion \\<alpha> p = insertion (\\<lambda>v. \\<alpha> 0) p\" \n    by (rule insertion_irrelevant_vars, insert vars, auto)\n  finally\n  show ?case using p0 mpoly_to_poly_inverse[OF vars] by (auto simp: poly_to_mpoly0)\nnext\n  case (Cons i \"is\" p)\n  let ?x = \"Suc i\" \n  let ?p = \"resultant_mpoly_poly ?x p (qs i)\"\n  have dist: \"distinct is\" using Cons(2) by auto\n  have vars: \"vars ?p \\<subseteq> insert 0 (Suc ` set is)\" using Cons(3) vars_resultant_mpoly_poly[of ?x p \"qs i\"] by auto\n  have fin: \"finite {\\<alpha>. mpoly_polys_zero_solution ?p qs (set is) \\<alpha>}\"\n    using finite_resultant_mpoly_polys_non_empty[of qs \"set (i # is)\" i p, OF Cons(5)] Cons(2,4) by auto\n  have 0: \"0 \\<notin> qs ` set is\" using Cons(5) by auto\n  have \"(\\<exists>v. mpoly_polys_solution p qs (set (i # is)) (\\<alpha>(?x := v)))\"\n    using Cons(6) by (intro exI[of _ \"\\<alpha> ?x\"], auto)\n  from this resultant_mpoly_polys_solution[OF Cons(5), of i p \\<alpha>]\n  have \"mpoly_polys_solution ?p qs (set (i # is) - {i}) \\<alpha>\" \n    by auto\n  also have \"set (i # is) - {i} = set is\" using Cons(2) by auto\n  finally have \"mpoly_polys_solution ?p qs (set is) \\<alpha>\" by auto\n  note IH = Cons(1)[OF dist vars fin 0 this]\n  show ?case unfolding eliminate_aux_vars.simps using IH by simp\nqed\n\nsubsection \\<open>A Representing Polynomial for the Roots of a Polynomial with Algebraic Coefficients\\<close>\n\ntext \\<open>First convert an algebraic polynomial into a system of integer polynomials.\\<close>\ndefinition initial_root_problem :: \"'a :: {is_rat,field_gcd} poly \\<Rightarrow> int mpoly \\<times> (nat \\<times> 'a \\<times> int poly) list\" where\n  \"initial_root_problem p = (let \n      n = degree p;\n      cs = coeffs p;\n      rcs = remdups (filter (\\<lambda> c. c \\<notin> \\<int>) cs);\n      pairs = map (\\<lambda> c. (c, min_int_poly c)) rcs;\n      spairs = sort_key (\\<lambda> (c,f). degree f) pairs; \\<comment> \\<open>sort by degree so that easy computations will be done first\\<close>\n      triples = zip [0 ..< length spairs] spairs;\n      mpoly = (sum (\\<lambda> i. let c = coeff p i in\n            MPoly_Type.monom (Poly_Mapping.single 0 i) 1 * \\<comment> \\<open>$x_0 ^ i * ...$\\<close>\n             (case find (\\<lambda> (j,d,f). d = c) triples of \n             None \\<Rightarrow> Const (to_int c)\n           | Some (j,pair) \\<Rightarrow> Var (Suc j)))\n             {..n})\n     in (mpoly, triples))\" \n\ntext \\<open>And then eliminate all auxiliary variables\\<close>\n\ndefinition representative_poly :: \"'a :: {is_rat,field_char_0,field_gcd} poly \\<Rightarrow> int poly\" where\n  \"representative_poly p = (case initial_root_problem p of\n     (mp, triples) \\<Rightarrow> \n     let is = map fst triples;\n         qs = (\\<lambda> j. snd (snd (triples ! j)))\n       in eliminate_aux_vars mp qs is)\"\n\n\nsubsection \\<open>Soundness Proof for Complex Algebraic Polynomials\\<close>\n\nlemma get_representative_complex: fixes p :: \"complex poly\"\n  assumes p: \"p \\<noteq> 0\" \n  and algebraic: \"Ball (set (coeffs p)) algebraic\"\n  and res: \"initial_root_problem p = (mp, triples)\" \n  and \"is\": \"is = map fst triples\" \n  and qs: \"\\<And> j. j < length is \\<Longrightarrow> qs j = snd (snd (triples ! j))\" \n  and root: \"poly p x = 0\" \nshows \"eliminate_aux_vars mp qs is represents x\" \nproof -\n  define rcs where \"rcs = remdups (filter (\\<lambda>c. c \\<notin> \\<int>) (coeffs p))\" \n  define spairs where \"spairs = sort_key (\\<lambda>(c, f). degree f) (map (\\<lambda>c. (c, min_int_poly c)) rcs)\" \n  let ?find = \"\\<lambda> i. find (\\<lambda>(j, d, f). d = coeff p i) triples\" \n  define trans where \"trans i = (case ?find i of None \\<Rightarrow> Const (to_int (coeff p i)) \n     | Some (j, pair) \\<Rightarrow> Var (Suc j))\" for i \n  note res = res[unfolded initial_root_problem_def Let_def, folded rcs_def, folded spairs_def]\n  have triples: \"triples = zip [0..<length spairs] spairs\" using res by auto\n  note res = res[folded triples, folded trans_def]\n  have mp: \"mp = (\\<Sum>i\\<le>degree p. MPoly_Type.monom (Poly_Mapping.single 0 i) 1 * trans i)\" using res by auto\n  have dist_rcs: \"distinct rcs\" unfolding rcs_def by auto\n  hence \"distinct (map fst (map (\\<lambda>c. (c, min_int_poly c)) rcs))\" by (simp add: o_def)\n  hence dist_spairs: \"distinct (map fst spairs)\" unfolding spairs_def \n    by (metis (no_types, lifting) distinct_map distinct_sort set_sort)\n  {\n    fix c\n    assume \"c \\<in> set rcs\" \n    hence \"c \\<in> set (coeffs p)\" unfolding rcs_def by auto\n    with algebraic have \"algebraic c\" by auto\n  } note rcs_alg = this\n  {\n    fix c\n    assume c: \"c \\<in> range (coeff p)\" \"c \\<notin> \\<int>\" \n    hence \"c \\<in> set (coeffs p)\" unfolding range_coeff by auto\n    with c have crcs: \"c \\<in> set rcs\" unfolding rcs_def by auto\n    from rcs_alg[OF crcs] have \"algebraic c\" .\n    from min_int_poly_represents[OF this]\n    have \"min_int_poly c represents c\" .\n    hence \"\\<exists> f. (c,f) \\<in> set spairs \\<and> f represents c\" using crcs unfolding spairs_def by auto\n  }\n  have dist_is: \"distinct is\" unfolding \"is\" triples by simp\n  note eliminate = eliminate_aux_vars[OF dist_is]\n  let ?mp = \"map_mpoly of_int mp :: complex mpoly\" \n  have vars_mp: \"vars mp \\<subseteq> insert 0 (Suc ` set is)\" \n    unfolding mp\n    apply (rule order.trans[OF vars_setsum], force)\n    apply (rule UN_least, rule order.trans[OF vars_mult], rule Un_least)\n     apply (intro order.trans[OF vars_monom_single], force)\n    subgoal for i \n    proof -\n      show ?thesis \n      proof (cases \"?find i\")\n        case None \n        show ?thesis unfolding trans_def None by auto\n      next\n        case (Some j_pair)\n        then obtain j c f where find: \"?find i = Some (j,c,f)\" by (cases j_pair, auto)\n        from find_Some_D[OF find] have \"Suc j \\<in> Suc ` (fst ` set triples)\"  by force\n        thus ?thesis unfolding trans_def find by (simp add: vars_Var \"is\")\n      qed\n    qed\n    done\n  hence varsMp: \"vars ?mp \\<subseteq> insert 0 (Suc ` set is)\" using vars_map_mpoly_subset by auto\n  note eliminate = eliminate[OF this]\n  let ?f = \"\\<lambda> j. snd (snd (triples ! j))\" \n  let ?c = \"\\<lambda> j. fst (snd (triples ! j))\" \n  {\n    fix j\n    assume \"j \\<in> set is\" \n    hence \"(?c j, ?f j) \\<in> set spairs\" unfolding \"is\" triples by simp\n    hence \"?f j represents ?c j\" \"?f j = min_int_poly (?c j)\" unfolding spairs_def \n      by (auto intro: min_int_poly_represents[OF rcs_alg])\n  } note is_repr = this\n  let ?qs = \"(of_int_poly o qs) :: nat \\<Rightarrow> complex poly\" \n  {\n    fix j\n    assume \"j \\<in> set is\" \n    hence \"j < length is\" unfolding \"is\" triples by simp\n  } note j_len = this\n  have qs_0: \"0 \\<notin> qs ` set is\" \n  proof\n    assume \"0 \\<in> qs ` set is\" \n    then obtain j where j: \"j \\<in> set is\" and 0: \"qs j = 0\" by auto\n    from is_repr[OF j] have \"?f j \\<noteq> 0\" by auto\n    with 0 show False unfolding qs[OF j_len[OF j]] by auto\n  qed\n  hence qs0: \"0 \\<notin> ?qs ` set is\" by auto\n  note eliminate = eliminate[OF _ this] \n  define roots where \"roots p = (SOME xs. set xs = {x . poly p x = 0})\" for p :: \"complex poly\" \n  {\n    fix p :: \"complex poly\" \n    assume \"p \\<noteq> 0\" \n    from someI_ex[OF finite_list[OF poly_roots_finite[OF this]], folded roots_def]\n    have \"set (roots p) = {x. poly p x = 0}\" .\n  } note roots = this\n  define qs_roots where \"qs_roots = concat_lists (map (\\<lambda> i. roots (?qs i)) [0 ..< length triples])\" \n  define evals where \"evals = concat (map (\\<lambda> part. let \n    q = partial_insertion (\\<lambda> i. part ! (i - 1)) 0 ?mp;\n    new_roots = roots q\n    in map (\\<lambda> r. r # part) new_roots) qs_roots)\"  \n  define conv where \"conv roots i = (if i \\<le> length triples then roots ! i else 0 :: complex)\" for roots i\n  define alphas where \"alphas = map conv evals\" \n  {\n    fix n\n    assume n: \"n \\<in> {..degree p}\"\n    let ?cn = \"coeff p n\" \n    from n have mem: \"?cn \\<in> set (coeffs p)\" using p unfolding Polynomial.coeffs_def by force\n    {\n      assume \"?cn \\<notin> \\<int>\"\n      with mem have \"?cn \\<in> set rcs\" unfolding rcs_def by auto\n      hence \"(?cn, min_int_poly ?cn) \\<in> set spairs\" unfolding spairs_def by auto\n      hence \"\\<exists> i. (i, ?cn, min_int_poly ?cn) \\<in> set triples\" unfolding triples set_zip set_conv_nth \n        by force\n      hence \"?find n \\<noteq> None\" unfolding find_None_iff by auto\n    }\n  } note non_int_find = this\n  have fin: \"finite {\\<alpha>. mpoly_polys_zero_solution ?mp ?qs (set is) \\<alpha>}\" \n  proof (rule finite_subset[OF _ finite_set[of alphas]], standard, clarify)\n    fix \\<alpha>\n    assume sol: \"mpoly_polys_zero_solution ?mp ?qs (set is) \\<alpha>\" \n    define part where \"part = map (\\<lambda> i. \\<alpha> (Suc i)) [0 ..< length triples]\" \n    {\n      fix i\n      assume \"i > length triples\" \n      hence \"i \\<notin> insert 0 (Suc ` set is)\" unfolding triples \"is\" by auto\n      hence \"\\<alpha> i = 0\" using sol[unfolded mpoly_polys_zero_solution_def] by auto\n    } note alpha0 = this\n    {\n      fix i\n      assume \"i < length triples\" \n      hence i: \"i \\<in> set is\" unfolding triples \"is\" by auto\n      from qs0 i have 0: \"?qs i \\<noteq> 0\" by auto\n      from i sol[unfolded mpoly_polys_zero_solution_def mpoly_polys_solution_def] \n      have \"poly (?qs i) (\\<alpha> (Suc i)) = 0\" by auto\n      hence \"\\<alpha> (Suc i) \\<in> set (roots (?qs i))\" \"poly (?qs i) (\\<alpha> (Suc i)) = 0\" using roots[OF 0] by auto\n    } note roots2 = this\n    hence part: \"part \\<in> set qs_roots\" \n      unfolding part_def qs_roots_def concat_lists_listset listset by auto\n    let ?gamma = \"(\\<lambda>i. part ! (i - 1))\" \n    let ?f = \"partial_insertion ?gamma 0 ?mp\" \n    have \"\\<alpha> 0 \\<in> set (roots ?f)\" \n    proof -\n      from sol[unfolded mpoly_polys_zero_solution_def mpoly_polys_solution_def]\n      have \"0 = insertion \\<alpha> ?mp\" by simp\n      also have \"\\<dots> = insertion (\\<lambda> i. if i \\<le> length triples then \\<alpha> i else part ! (i - 1)) ?mp\" \n        (is \"_ = insertion ?beta _\")\n      proof (rule insertion_irrelevant_vars)\n        fix i\n        assume \"i \\<in> vars ?mp\" \n        from set_mp[OF varsMp this] have \"i \\<le> length triples\" unfolding triples \"is\" by auto\n        thus \"\\<alpha> i = ?beta i\" by auto\n      qed\n      also have \"\\<dots> = poly (partial_insertion (?beta(0 := part ! 0)) 0 ?mp) (?beta 0)\"\n        by (subst insertion_partial_insertion, auto)\n      also have \"?beta(0 := part ! 0) = ?gamma\" unfolding part_def \n        by (intro ext, auto)\n      finally have root: \"poly ?f (\\<alpha> 0) = 0\" by auto\n      have \"?f \\<noteq> 0\" \n      proof\n        interpret mp: inj_comm_ring_hom \"map_mpoly complex_of_int\" \n          by (rule of_int_hom.inj_comm_ring_hom_mpoly_map)\n        assume \"?f = 0\" \n        hence \"0 = coeff ?f (degree p)\" by simp\n        also have \"\\<dots> = insertion ?gamma (coeff (mpoly_to_mpoly_poly 0 ?mp) (degree p))\" \n          unfolding insertion_coeff_mpoly_to_mpoly_poly[symmetric] ..\n        also have \"coeff (mpoly_to_mpoly_poly 0 ?mp) (degree p) = map_mpoly of_int (coeff (mpoly_to_mpoly_poly 0 mp) (degree p))\" \n          unfolding of_int_hom.mpoly_to_mpoly_poly_map_mpoly_hom \n          by (subst coeff_map_poly, auto)\n        also have \"coeff (mpoly_to_mpoly_poly 0 mp) (degree p) = \n          (\\<Sum>x. MPoly_Type.monom (remove_key 0 x) (MPoly_Type.coeff mp x) when lookup x 0 = degree p)\" \n          unfolding mpoly_to_mpoly_poly_def when_def\n          by (subst coeff_hom.hom_Sum_any, force, unfold Polynomial.coeff_monom, auto)\n        also have \"\\<dots> = (\\<Sum>x. MPoly_Type.monom (remove_key 0 x)\n           (\\<Sum>xa\\<le>degree p. let xx = Poly_Mapping.single 0 xa in\n               \\<Sum>(a, b). MPoly_Type.coeff (trans xa) b when x = xx + b when\n                         a = xx) when\n          lookup x 0 = degree p)\" unfolding mp coeff_sum More_MPoly_Type.coeff_monom coeff_mpoly_times Let_def\n          apply (subst prod_fun_unfold_prod, force, force)\n          apply (unfold when_mult, subst when_commute)\n          by (auto simp: when_def intro!: Sum_any.cong sum.cong if_cong arg_cong[of _ _ \"MPoly_Type.monom _\"])\n        also have \"\\<dots> = (\\<Sum>x. MPoly_Type.monom (remove_key 0 x)\n           (\\<Sum>i\\<le>degree p. \\<Sum>m. MPoly_Type.coeff (trans i) m when x = Poly_Mapping.single 0 i + m) when\n          lookup x 0 = degree p)\" \n          unfolding Sum_any_when_dependent_prod_left Let_def by simp\n        also have \"\\<dots> = (\\<Sum>x. MPoly_Type.monom (remove_key 0 x)\n           (\\<Sum>i \\<in> {degree p}. \\<Sum>m. MPoly_Type.coeff (trans i) m when x = Poly_Mapping.single 0 i + m) when\n          lookup x 0 = degree p)\" \n          apply (intro Sum_any.cong when_cong refl arg_cong[of _ _ \"MPoly_Type.monom _\"] sum.mono_neutral_right, force+)\n          apply (intro ballI Sum_any_zeroI, auto simp: when_def)\n          subgoal for i x\n          proof (goal_cases)\n            case 1\n            hence \"lookup x 0 > 0\" by (auto simp: lookup_add)\n            moreover have \"0 \\<notin> vars (trans i)\" unfolding trans_def\n              by (auto split: option.splits simp: vars_Var)\n            ultimately show ?thesis \n              by (metis set_mp coeff_notin_vars in_keys_iff neq0_conv)\n          qed\n          done\n        also have \"\\<dots> = (\\<Sum>x. MPoly_Type.monom (remove_key 0 x)\n            (\\<Sum>m. MPoly_Type.coeff (trans (degree p)) m when x = Poly_Mapping.single 0 (degree p) + m) when\n          lookup x 0 = degree p)\" (is \"_ = ?mid\")\n          by simp\n        also have \"insertion ?gamma (map_mpoly of_int \\<dots>) \\<noteq> 0\" \n        proof (cases \"?find (degree p)\")\n          case None\n          from non_int_find[of \"degree p\"] None \n          have lcZ: \"lead_coeff p \\<in> \\<int>\" by auto\n          have \"?mid =  (\\<Sum>x. MPoly_Type.monom (remove_key 0 x)\n           (\\<Sum>m. (to_int (lead_coeff p) when\n                 x = Poly_Mapping.single 0 (degree p) + m when m = 0)) when\n              lookup x 0 = degree p)\" \n            using None unfolding trans_def None option.simps mpoly_coeff_Const when_def\n            by (intro Sum_any.cong if_cong refl, intro arg_cong[of _ _ \"MPoly_Type.monom _\"] Sum_any.cong, auto)\n          also have \"\\<dots> = (\\<Sum>x. MPoly_Type.monom (remove_key 0 x)\n           (to_int (lead_coeff p) when x = Poly_Mapping.single 0 (degree p)) when\n               lookup x 0 = degree p when x = Poly_Mapping.single 0 (degree p))\" \n            unfolding Sum_any_when_equal[of _ 0]\n            by (intro Sum_any.cong, auto simp: when_def)\n          also have \"\\<dots> = MPoly_Type.monom (remove_key 0 (Poly_Mapping.single 0 (degree p)))\n           (to_int (lead_coeff p)) \" \n            unfolding Sum_any_when_equal by simp\n          also have \"\\<dots> = Const (to_int (lead_coeff p))\" by (simp add: mpoly_monom_0_eq_Const)\n          also have \"map_mpoly of_int \\<dots> = Const (lead_coeff p)\" \n            unfolding of_int_hom.map_mpoly_hom_Const of_int_to_int[OF lcZ] by simp\n          also have \"insertion ?gamma \\<dots> = lead_coeff p\" by simp\n          also have \"\\<dots> \\<noteq> 0\" using p by auto\n          finally show ?thesis .\n        next\n          case Some\n          from find_Some_D[OF this] Some obtain j f where mem: \"(j,lead_coeff p,f) \\<in> set triples\" and\n            Some: \"?find (degree p) = Some (j, lead_coeff p, f)\" by auto\n          from mem have j: \"j < length triples\" unfolding triples set_zip by auto\n          have \"?mid = (\\<Sum>x. if lookup x 0 = degree p\n              then MPoly_Type.monom (remove_key 0 x)\n                (\\<Sum>m. 1 when m = Poly_Mapping.single (Suc j) 1 when x = Poly_Mapping.single 0 (degree p) + m)\n            else 0)\" \n            unfolding trans_def Some option.simps split when_def coeff_Var by auto\n          also have \"\\<dots> = (\\<Sum>x. if lookup x 0 = degree p\n          then MPoly_Type.monom (remove_key 0 x) 1\n                when x = Poly_Mapping.single 0 (degree p) + Poly_Mapping.single (Suc j) 1\n              else 0 when x = Poly_Mapping.single 0 (degree p) + Poly_Mapping.single (Suc j) 1)\" \n            apply (subst when_commute)\n            apply (unfold Sum_any_when_equal)\n            by (rule Sum_any.cong, auto simp: when_def)\n          also have \"\\<dots> = (\\<Sum>x. (MPoly_Type.monom (remove_key 0 x) 1 when lookup x 0 = degree p)\n            when x = Poly_Mapping.single 0 (degree p) + Poly_Mapping.single (Suc j) 1)\" \n            by (rule Sum_any.cong, auto simp: when_def)\n          also have \"\\<dots> = MPoly_Type.monom (Poly_Mapping.single (Suc j) 1) 1\"  \n            unfolding Sum_any_when_equal unfolding when_def \n            by (simp add: lookup_add remove_key_add[symmetric]\n              remove_key_single' lookup_single)\n          also have \"\\<dots> = Var (Suc j)\"\n            by (intro mpoly_eqI, simp add: coeff_Var coeff_monom)\n          also have \"map_mpoly complex_of_int \\<dots> = Var (Suc j)\"\n            by (simp add: map_mpoly_Var)\n          also have \"insertion ?gamma \\<dots> = part ! j\" by simp\n          also have \"\\<dots> = \\<alpha> (Suc j)\" unfolding part_def using j by auto\n          also have \"\\<dots> \\<noteq> 0\" \n          proof\n            assume \"\\<alpha> (Suc j) = 0\" \n            with roots2(2)[OF j] have root0: \"poly (?qs j) 0 = 0\" by auto\n            from j \"is\" have ji: \"j < length is\" by auto\n            hence jis: \"j \\<in> set is\" unfolding \"is\" triples set_zip by auto\n            from mem have tj: \"triples ! j = (j, lead_coeff p, f)\" unfolding triples set_zip by auto\n            from root0[unfolded qs[OF ji] o_def tj] \n            have rootf: \"poly f 0 = 0\" by auto\n            from is_repr[OF jis, unfolded tj] have rootlc: \"ipoly f (lead_coeff p) = 0\" \n              and f: \"f = min_int_poly (lead_coeff p)\" by auto\n            from f have irr: \"irreducible f\" by auto\n            from rootf have \"[:0,1:] dvd f\" using dvd_iff_poly_eq_0 by fastforce\n            from this[unfolded dvd_def] obtain g where f: \"f = [:0, 1:] * g\" by auto\n            from irreducibleD[OF irr f] have \"is_unit g\"\n              by (metis is_unit_poly_iff one_neq_zero one_pCons pCons_eq_iff) \n            then obtain c where g: \"g = [:c:]\" and c: \"c dvd 1\" unfolding is_unit_poly_iff by auto\n            from rootlc[unfolded f g] c have \"lead_coeff p = 0\" by auto\n            with p show False by auto\n          qed\n          finally show ?thesis .\n        qed\n        finally show False by auto\n      qed\n      from roots[OF this] root show ?thesis by auto\n    qed\n    hence \"\\<alpha> 0 # part \\<in> set evals\" \n      unfolding evals_def set_concat Let_def set_map \n      by (auto intro!: bexI[OF _ part])\n    hence \"map \\<alpha> [0 ..< Suc (length triples)] \\<in> set evals\" unfolding part_def\n      by (metis Utility.map_upt_Suc)\n    hence \"conv (map \\<alpha> [0 ..< Suc (length triples)]) \\<in> set alphas\" unfolding alphas_def by auto\n    also have \"conv (map \\<alpha> [0 ..< Suc (length triples)]) = \\<alpha>\" \n    proof\n      fix i\n      show \"conv (map \\<alpha> [0..<Suc (length triples)]) i = \\<alpha> i\" \n        unfolding conv_def using alpha0\n        by (cases \"i < length triples\"; cases \"i = length triples\"; auto simp: nth_append)\n    qed\n    finally show \"\\<alpha> \\<in> set alphas\" .\n  qed\n  note eliminate = eliminate[OF this]\n  define \\<alpha> where \"\\<alpha> x j = (if j = 0 then x else ?c (j - 1))\" for x j\n  have \\<alpha>: \"\\<alpha> x (Suc j) = ?c j\" \"\\<alpha> x 0 = x\" for j x unfolding \\<alpha>_def by auto\n  interpret mp: inj_comm_ring_hom \"map_mpoly complex_of_int\" by (rule of_int_hom.inj_comm_ring_hom_mpoly_map)\n  have ins: \"insertion (\\<alpha> x) ?mp = poly p x\" for x\n    unfolding poly_altdef mp mp.hom_sum insertion_sum insertion_mult mp.hom_mult\n  proof (rule sum.cong[OF refl], subst mult.commute, rule arg_cong2[of _ _ _ _ \"(*)\"])\n    fix n\n    assume n: \"n \\<in> {..degree p}\"\n    let ?cn = \"coeff p n\" \n    from n have mem: \"?cn \\<in> set (coeffs p)\" using p unfolding Polynomial.coeffs_def by force\n    have \"insertion (\\<alpha> x) (map_mpoly complex_of_int (MPoly_Type.monom (Poly_Mapping.single 0 n) 1)) = (\\<Prod>a. \\<alpha> x a ^ (n when a = 0))\" \n      unfolding of_int_hom.map_mpoly_hom_monom by (simp add: lookup_single)\n    also have \"\\<dots> = (\\<Prod>a. if a = 0 then \\<alpha> x a ^ n else 1)\" \n      by (rule Prod_any.cong, auto simp: when_def)\n    also have \"\\<dots> = \\<alpha> x 0 ^ n\" by simp\n    also have \"\\<dots> = x ^ n\" unfolding \\<alpha> ..\n    finally show \"insertion (\\<alpha> x) (map_mpoly complex_of_int (MPoly_Type.monom (Poly_Mapping.single 0 n) 1)) = x ^ n\" .\n    show \"insertion (\\<alpha> x) (map_mpoly complex_of_int (trans n)) = ?cn\" \n    proof (cases \"?find n\")\n      case None\n      with non_int_find[OF n] have ints: \"?cn \\<in> \\<int>\" by auto\n      from None show ?thesis unfolding trans_def using ints \n        by (simp add: of_int_hom.map_mpoly_hom_Const of_int_to_int)\n    next\n      case (Some triple)\n      from find_Some_D[OF this] this obtain j f \n        where mem: \"(j,?cn,f) \\<in> set triples\" and Some: \"?find n = Some (j,?cn,f)\" \n        by (cases triple, auto)\n      from mem have \"triples ! j = (j,?cn,f)\" unfolding triples set_zip by auto\n      thus ?thesis unfolding trans_def Some by (simp add: map_mpoly_Var \\<alpha>_def)\n    qed\n  qed\n  from root have  \"insertion (\\<alpha> x) ?mp = 0\" unfolding ins by auto\n  hence \"mpoly_polys_solution ?mp ?qs (set is) (\\<alpha> x)\" \n    unfolding mpoly_polys_solution_def\n  proof (standard, intro ballI)\n    fix j\n    assume j: \"j \\<in> set is\" \n    from is_repr[OF this]\n    show \"poly (?qs j) (\\<alpha> x (Suc j)) = 0\" unfolding \\<alpha> qs[OF j_len[OF j]] o_def by auto\n  qed\n  note eliminate = eliminate[OF this, unfolded \\<alpha> eliminate_aux_vars_of_int_poly]\n  thus \"eliminate_aux_vars mp qs is represents x\" by auto\nqed  \n\nlemma representative_poly_complex: fixes x :: complex\n  assumes p: \"p \\<noteq> 0\" \n    and algebraic: \"Ball (set (coeffs p)) algebraic\"\n    and root: \"poly p x = 0\" \n  shows \"representative_poly p represents x\"\nproof -\n  obtain mp triples where init: \"initial_root_problem p = (mp, triples)\" by force\n  from get_representative_complex[OF p algebraic init refl _ root]\n  show ?thesis unfolding representative_poly_def init Let_def by auto\nqed \n\nsubsection \\<open>Soundness Proof for Real Algebraic Polynomials\\<close>\n\ntext \\<open>We basically use the result for complex algebraic polynomials which \n  are a superset of real algebraic polynomials.\\<close>\n\n\nlemma initial_root_problem_complex_of_real_poly: \n  \"initial_root_problem (map_poly complex_of_real p) = \n   map_prod id (map (map_prod id (map_prod complex_of_real id))) (initial_root_problem p)\"\nproof -\n  let ?c = \"of_real :: real \\<Rightarrow> complex\" \n  let ?cp = \"map_poly ?c\" \n  let ?p = \"?cp p :: complex poly\" \n  define cn where \"cn = degree ?p\" \n  define n where \"n = degree p\" \n  have n: \"cn = n\" unfolding n_def cn_def by simp\n  note def = initial_root_problem_def[of ?p]\n  note def = def[folded cn_def, unfolded n]\n  define ccs where \"ccs = coeffs ?p\"\n  define cs where \"cs = coeffs p\" \n  have cs: \"ccs = map ?c cs\" \n    unfolding ccs_def cs_def by auto\n  note def = def[folded ccs_def]\n  define crcs where \"crcs = remdups (filter (\\<lambda>c. c \\<notin> \\<int>) ccs)\" \n  define rcs where \"rcs = remdups (filter (\\<lambda>c. c \\<notin> \\<int>) cs)\" \n  have rcs: \"crcs = map ?c rcs\" \n    unfolding crcs_def rcs_def cs by (induct cs, auto)\n  define cpairs where \"cpairs = map (\\<lambda>c. (c, min_int_poly c)) crcs\" \n  define pairs where \"pairs = map (\\<lambda>c. (c, min_int_poly c)) rcs\" \n  have pairs: \"cpairs = map (map_prod ?c id) pairs\" \n    unfolding pairs_def cpairs_def rcs by auto\n  define cspairs where \"cspairs = sort_key (\\<lambda>(c, y). degree y) cpairs\" \n  define spairs where \"spairs = sort_key (\\<lambda>(c, y). degree y) pairs\" \n  have spairs: \"cspairs = map (map_prod ?c id) spairs\" \n    unfolding spairs_def cspairs_def pairs \n    by (rule sym, rule map_sort_key, auto)\n  define ctriples where \"ctriples = zip [0..<length cspairs] cspairs\" \n  define triples where \"triples = zip [0..<length spairs] spairs\" \n  have triples: \"ctriples = map (map_prod id (map_prod ?c id)) triples\" \n    unfolding ctriples_def triples_def spairs by (rule nth_equalityI, auto)\n  note def = def[unfolded Let_def, folded crcs_def, folded cpairs_def, folded cspairs_def, folded ctriples_def,\n      unfolded of_real_hom.coeff_map_poly_hom]\n  note def2 = initial_root_problem_def[of p, unfolded Let_def, folded n_def cs_def, folded rcs_def, folded pairs_def,\n      folded spairs_def, folded triples_def]\n  show \"initial_root_problem ?p = map_prod id (map (map_prod id (map_prod ?c id))) (initial_root_problem p)\" \n    unfolding def def2 triples to_int_complex_of_real\n    by (simp, intro sum.cong refl arg_cong[of _ _ \"\\<lambda> x. _ * x\"], induct triples, auto)\nqed\n\n\nlemma representative_poly_real: fixes x :: real \n  assumes p: \"p \\<noteq> 0\" \n  and algebraic: \"Ball (set (coeffs p)) algebraic\"\n  and root: \"poly p x = 0\" \nshows \"representative_poly p represents x\" \nproof -\n  obtain mp triples where init: \"initial_root_problem p = (mp, triples)\" by force\n  define \"is\" where \"is = map fst triples\" \n  define qs where \"qs = (\\<lambda> j. snd (snd (triples ! j)))\" \n  let ?c = \"of_real :: real \\<Rightarrow> complex\" \n  let ?cp = \"map_poly ?c\" \n  let ?ct = \"map (map_prod id (map_prod ?c id))\" \n  let ?p = \"?cp p :: complex poly\" \n  have p: \"?p \\<noteq> 0\" using p by auto\n  have \"initial_root_problem ?p = map_prod id ?ct (initial_root_problem p)\" \n    by (rule initial_root_problem_complex_of_real_poly)\n  from this[unfolded init] \n  have res: \"initial_root_problem ?p = (mp, ?ct triples)\" \n    by auto\n  from root have \"0 = ?c (poly p x)\" by simp\n  also have \"\\<dots> = poly ?p (?c x)\" by simp\n  finally have root: \"poly ?p (?c x) = 0\" by simp\n  have qs: \"j < length is \\<Longrightarrow> qs j = snd (snd (?ct triples ! j))\" for j\n    unfolding is_def qs_def by (auto simp: set_conv_nth)\n  have \"is\": \"is = map fst (?ct triples)\" unfolding is_def by auto \n  {\n    fix cc\n    assume \"cc \\<in> set (coeffs ?p)\" \n    then obtain c where \"c \\<in> set (coeffs p)\" and cc: \"cc = ?c c\" by auto\n    from algebraic this(1) have \"algebraic cc\" \n      unfolding cc algebraic_complex_iff by auto\n  }\n  hence algebraic: \"Ball (set (coeffs ?p)) algebraic\" .. \n  from get_representative_complex[OF p this res \"is\" qs root]\n  have \"eliminate_aux_vars mp qs is represents ?c x\" .\n  hence \"eliminate_aux_vars mp qs is represents x\" by simp\n  thus ?thesis unfolding representative_poly_def res init split Let_def qs_def is_def .\nqed\n\nsubsection \\<open>Algebraic Closedness of Complex Algebraic Numbers\\<close>\n\n(* TODO: could be generalised to arbitrary algebraically closed fields? *)\nlemma complex_algebraic_numbers_are_algebraically_closed:\n  assumes nc: \"\\<not> constant (poly p)\"\n    and alg: \"Ball (set (coeffs p)) algebraic\"\n  shows \"\\<exists> z :: complex. algebraic z \\<and> poly p z = 0\"\nproof -\n  from fundamental_theorem_of_algebra[OF nc] obtain z where\n    root: \"poly p z = 0\" by auto\n  from algebraic_representsI[OF representative_poly_complex[OF _ alg root]] nc root\n  have \"algebraic z \\<and> poly p z = 0\" \n    using constant_degree degree_0 by blast\n  thus ?thesis ..\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/Factor_Algebraic_Polynomial/Roots_of_Algebraic_Poly.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8459424217727027, "lm_q2_score": 0.8438951005915208, "lm_q1q2_score": 0.7138866651165098}}
{"text": "(* author:wzh *)\n\n(* then = from this *)\n(* hence = from his have *)\n(* thus = from this show *)\ntheory Exercise5\n  imports Main\nbegin\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 Axy: \"A x y\"\n shows \"T x y\"\nproof (rule ccontr)\n  assume pre: \"\\<not> T x y\"\n  hence \"T y x\" using T by blast\n  hence \"A y x\" using TA by blast\n  hence equal: \"x=y\" using Axy and A by blast\n  hence self: \"T x x\" using T by blast\n  have \"\\<not> T x x\" using equal and pre by blast\n  thus \"False\" using self by blast\nqed\n\n(* Exercise 5.2 *)\nlemma \"\\<exists> ys zs. xs = ys @ zs \\<and> (length ys = length zs \\<or> length ys = length zs + 1)\"\nproof cases\n  assume \"2 dvd length xs\"\n  hence \"\\<exists> k. length xs = 2 * k\" by auto\n  then obtain k where len: \"length xs = 2 * k\" by auto\n  obtain ys where y: \"ys = take k xs\" by auto\n  hence leny: \"length ys = k\" using len by auto\n  obtain zs where z: \"zs = drop k xs\" by auto\n  hence lenz: \"length zs = k\" using len by auto\n  hence l: \"length ys = length zs\" using leny by auto\n  moreover have \"xs = ys @ zs\" using y and z by auto\n  ultimately show ?thesis by auto\nnext\n  assume \"\\<not> 2 dvd length xs\"\n  hence \"\\<exists> k. length xs = 2*k + 1\" by arith\n  then obtain k where len: \"length xs = 2*k + 1\" by auto\n  obtain ys where y: \"ys = take (k+1) xs\" by auto\n  hence leny: \"length ys = k+1\" using len by auto\n  obtain zs where z: \"zs = drop (k+1) xs\" by auto\n  hence lenz: \"length zs = k\" using len by auto\n  have \"xs = ys @ zs\" using y and z by auto\n  moreover have \"length ys = length zs + 1\" using leny and lenz by auto\n  ultimately show ?thesis by auto\nqed\n\n(* Exercise 5.3 *)\ninductive ev :: \"nat \\<Rightarrow> bool\" where\nev0: \"ev 0\"\n| evSS: \"ev n \\<Longrightarrow> ev (Suc (Suc n))\"\n\nlemma assumes a: \"ev (Suc (Suc n))\" shows \"ev n\"\nproof - \n  show \"ev n\" using a\n  proof cases\n    case evSS thus ?thesis by auto\n  qed\nqed\n\n(* Exercise 5.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 5.5 *)\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 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\nlemma \"iter r n x y \\<Longrightarrow> star r x y\"\nproof (induction rule: iter.induct)\n  case refl_iter\n  show ?case by (auto intro: star.refl)\nnext\n  case step_iter\n  thus ?case by (auto intro: star.step)\nqed\n\n(* Exercise 5.6 *)\nfun elems :: \"'a list \\<Rightarrow> 'a set\" where\n\"elems [] = {}\"\n| \"elems (x#xs) = {x} \\<union> elems xs\"\n\nlemma fixes x shows \"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 ks)\n  show ?case\n  proof cases\n    assume eq: \"a = x\"\n    obtain ys where y: \"ys = ([]:: 'a list)\" by auto\n    obtain zs where z: \"zs = ks\" by auto\n    have nin: \"x \\<notin> elems ys\" using y by auto\n    moreover have \"(a # ks) = ys @ (x # zs)\" using eq and y and z by auto\n    ultimately show ?thesis by auto\n  next\n    assume neq: \"\\<not> a = x\"\n    hence \"x \\<in> elems ks\" using Cons.prems by auto\n    then obtain yss zs where nin: \"ks = yss @ (x#zs) \\<and> x \\<notin> elems yss\" using Cons.IH by auto\n    obtain ys where y: \"ys = a # yss\" by auto\n    hence \"x \\<notin> elems ys\" using nin and neq by auto\n    moreover have \"a # ks = ys @ (x # zs)\" using nin and y by auto\n    ultimately show ?thesis by auto\n  qed\nqed\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/Exercise5.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703224, "lm_q2_score": 0.880797071719777, "lm_q1q2_score": 0.7138674494474605}}
{"text": "theory Lab4_Theory\nimports Main\nbegin\n\n(* Lecture *)\nlemma \"A \\<and> B \\<Longrightarrow> B \\<and> A\"\nproof -\n  assume ab: \"A \\<and> B\"\n  from ab have a: \"A\" by (rule conjunct1)\n  from ab have b: \"B\" by (rule conjunct2)\n  from b a show \"B \\<and> A\" by (rule conjI)\nqed\n\n(* Lemma #1 *)\nlemma \"\\<lbrakk>A; B\\<rbrakk> \\<Longrightarrow> A \\<and> B\"\nproof -\n assume a: \"A\"\n assume b: \"B\"\n from a b show \"A \\<and> B\" by (rule conjI)\nqed\n\n(* Lemma #2 *)\nlemma \"A \\<Longrightarrow> A \\<or> B\"\nproof -\n  assume foo: \"A\"\n  from foo show \"A \\<or> B\" by (rule disjI1)\nqed\n\n(* Lemma #3 *)\nlemma \"\\<lbrakk>A \\<and> B; \\<lbrakk>A; B\\<rbrakk> \\<Longrightarrow> C\\<rbrakk> \\<Longrightarrow> C\"\nproof -\n  assume a: \"A \\<and> B\"\n  assume b: \"\\<lbrakk>A; B\\<rbrakk> \\<Longrightarrow> C\"\n  from a b show \"C\" by (rule conjE)\nqed\n\n(* Lemma #4 *)\nlemma \"\\<lbrakk>(A \\<Longrightarrow> B); (B \\<Longrightarrow> A)\\<rbrakk> \\<Longrightarrow> A = B\"\nproof -\n  assume fst: \"A \\<Longrightarrow> B\"\n  assume snd: \"B \\<Longrightarrow> A\"\n  from fst snd show \"A = B\" by (rule iffI)\nqed\n\n(* Lemma #6 *)\nlemma \"\\<lbrakk>A \\<or> B; (A \\<Longrightarrow> C); (B \\<Longrightarrow> C)\\<rbrakk> \\<Longrightarrow> C\"\nproof -\n  assume fst: \"A \\<or> B\"\n  assume snd: \"A \\<Longrightarrow> C\"\n  assume trd: \"B \\<Longrightarrow> C\"\n  from fst snd trd show \"C\" by (rule disjE)\nqed\n\n(* Lemma #7 *)\nlemma \"\\<lbrakk>A \\<longrightarrow> B; A; (B \\<Longrightarrow> C)\\<rbrakk> \\<Longrightarrow> C\"\nproof - \n  assume a: \"A \\<longrightarrow> B\"\n  assume b: \"A\"\n  assume c: \"B \\<Longrightarrow> C\"\n  from a b c show \"C\" by (rule impE)\nqed", "meta": {"author": "NoxChimaera", "repo": "formal-verification", "sha": "b828938e74e9b15e4b03f4ac645e834c7470535f", "save_path": "github-repos/isabelle/NoxChimaera-formal-verification", "path": "github-repos/isabelle/NoxChimaera-formal-verification/formal-verification-b828938e74e9b15e4b03f4ac645e834c7470535f/Lab4. Isar/Lab4_Theory.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898178450964, "lm_q2_score": 0.7879311856832191, "lm_q1q2_score": 0.7138576313916104}}
{"text": "(* \n  File:    Liouville_Numbers_Misc.thy\n  Author:  Manuel Eberl <eberlm@in.tum.de>\n\n*)\n\nsection \\<open>Liouville Numbers\\<close>\nsubsection \\<open>Preliminary lemmas\\<close>\ntheory Liouville_Numbers_Misc\nimports\n  Complex_Main\n  \"HOL-Computational_Algebra.Polynomial\"\nbegin\n\ntext \\<open>\n  We will require these inequalities on factorials to show properties of the standard \n  construction later.\n\\<close>\n\nlemma fact_ineq: \"n \\<ge> 1 \\<Longrightarrow> fact n + k \\<le> fact (n + k)\"\nproof (induction k)\n  case (Suc k)\n  from Suc have \"fact n + Suc k \\<le> fact (n + k) + 1\" by simp\n  also from Suc have \"\\<dots> \\<le> fact (n + Suc k)\" by simp\n  finally show ?case .\nqed simp_all\n\nlemma Ints_sum:\n  assumes \"\\<And>x. x \\<in> A \\<Longrightarrow> f x \\<in> \\<int>\"\n  shows   \"sum f A \\<in> \\<int>\"\n  by (cases \"finite A\", insert assms, induction A rule: finite_induct)\n     (auto intro!: Ints_add)\n\nlemma suminf_split_initial_segment':\n  \"summable (f :: nat \\<Rightarrow> 'a::real_normed_vector) \\<Longrightarrow> \n       suminf f = (\\<Sum>n. f (n + k + 1)) + sum f {..k}\"\n  by (subst suminf_split_initial_segment[of _ \"Suc k\"], assumption, subst lessThan_Suc_atMost) \n     simp_all\n\nlemma Rats_eq_int_div_int': \"(\\<rat> :: real set) = {of_int p / of_int q |p q. q > 0}\"\nproof safe\n  fix x :: real assume \"x \\<in> \\<rat>\"\n  then obtain p q where pq: \"x = of_int p / of_int q\" \"q \\<noteq> 0\" \n    by (subst (asm) Rats_eq_int_div_int) auto\n  show \"\\<exists>p q. x = real_of_int p / real_of_int q \\<and> 0 < q\"\n  proof (cases \"q > 0\")\n    case False\n    show ?thesis by (rule exI[of _ \"-p\"], rule exI[of _ \"-q\"]) (insert False pq, auto)\n  qed (insert pq, force)\nqed auto\n\nlemma Rats_cases':\n  assumes \"(x :: real) \\<in> \\<rat>\"\n  obtains p q where \"q > 0\" \"x = of_int p / of_int q\"\n  using assms by (subst (asm) Rats_eq_int_div_int') auto\n\n\ntext \\<open>\n  The following inequality gives a lower bound for the absolute value of an \n  integer polynomial at a rational point that is not a root.\n\\<close>\nlemma int_poly_rat_no_root_ge: \n  fixes p :: \"real poly\" and a b :: int\n  assumes \"\\<And>n. coeff p n \\<in> \\<int>\"\n  assumes \"b > 0\" \"poly p (a / b) \\<noteq> 0\"\n  defines \"n \\<equiv> degree p\"\n  shows   \"abs (poly p (a / b)) \\<ge> 1 / of_int b ^ n\"\nproof -\n  let ?S = \"(\\<Sum>i\\<le>n. coeff p i * of_int a ^ i * (of_int b ^ (n - i)))\"\n  from \\<open>b > 0\\<close> have eq: \"?S = of_int b ^ n * poly p (a / b)\"\n    by (simp add: poly_altdef power_divide mult_ac n_def sum_distrib_left power_diff)\n  have \"?S \\<in> \\<int>\" by (intro Ints_sum Ints_mult assms Ints_power) simp_all\n  moreover from assms have \"?S \\<noteq> 0\" by (subst eq) auto\n  ultimately have \"abs ?S \\<ge> 1\" by (elim Ints_cases) simp\n  with eq \\<open>b > 0\\<close> show ?thesis by (simp add: field_simps abs_mult)\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/Liouville_Numbers/Liouville_Numbers_Misc.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8479677737461006, "lm_q2_score": 0.8418256551882382, "lm_q1q2_score": 0.7138410267123227}}
{"text": "(*  Author:     Lars Noschinski\n*)\n\nsection \\<open>Permutation orbits\\<close>\n\ntheory Orbits\nimports\n  \"HOL-Library.FuncSet\"\n  \"HOL-Combinatorics.Permutations\"\nbegin\n\nsubsection \\<open>Orbits and 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\"\n    by (auto simp add: orbit_altdef) 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\n    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\"\n    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\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 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 orbit_inverse:\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_image:\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_inverse)\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 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 [of 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 [of f]) (auto intro: orbit.intros)\n  with assms(2) show ?thesis by (simp cong: cyclic_cong)\nqed\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\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\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\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\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\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 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>Function-power distance between values\\<close>\n\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\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_dist_prop funpow_dist_step funpow_simps_right(2) o_apply self_in_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  define n where \\<open>n = funpow_dist1 f x z - funpow_dist1 f x y - 1\\<close>\n  with assms have *: \\<open>funpow_dist1 f x z = Suc (funpow_dist1 f x y + n)\\<close>\n    by simp\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 add: * funpow_add ac_simps funpow_swap1)\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 add: * funpow_add funpow_swap1)\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 add: * funpow_add funpow_swap1)\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 \\<open>(f ^^ funpow_dist1 f x y) x = (f ^^ (funpow_dist1 f x y mod m)) x\\<close> funpow_dist1_prop funpow_dist_least funpow_dist_step leI)\n  with \\<open>m > 0\\<close> show ?thesis\n    by (auto intro: order_trans)\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/Combinatorics/Orbits.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677737461007, "lm_q2_score": 0.841825655188238, "lm_q1q2_score": 0.7138410267123227}}
{"text": "section \\<open>Signed measures\\<close>\n\ntext \\<open>In this section we define signed measures. These are generalizations of measures that can also \ntake negative values but cannot contain both $\\infty$ and $-\\infty$ in their range.\\<close>\n\nsubsection \\<open>Basic definitions\\<close>\ntheory Hahn_Jordan_Decomposition imports \n  \"HOL-Probability.Probability\" \n  Hahn_Jordan_Prelims\nbegin\n\ndefinition signed_measure::\"'a measure \\<Rightarrow> ('a set \\<Rightarrow> ereal) \\<Rightarrow> bool\" where\n  \"signed_measure M \\<mu> \\<longleftrightarrow> \\<mu> {} = 0 \\<and> (-\\<infinity> \\<notin> range \\<mu> \\<or> \\<infinity> \\<notin> range \\<mu>) \\<and> \n  (\\<forall>A. range A \\<subseteq> sets M \\<longrightarrow> disjoint_family A \\<longrightarrow> \\<Union> (range A) \\<in> sets M \\<longrightarrow> \n  (\\<lambda>i. \\<mu> (A i)) sums \\<mu> (\\<Union> (range A))) \\<and>\n  (\\<forall>A. range A \\<subseteq> sets M \\<longrightarrow> disjoint_family A \\<longrightarrow> \\<Union> (range A) \\<in> sets M \\<longrightarrow> \n  \\<bar>\\<mu> (\\<Union> (range A))\\<bar> < \\<infinity> \\<longrightarrow> summable (\\<lambda>i. real_of_ereal \\<bar>\\<mu> (A i)\\<bar>))\"\n\nlemma signed_measure_empty:\n  assumes \"signed_measure M \\<mu>\"\n  shows \"\\<mu> {} = 0\" using assms unfolding signed_measure_def by simp\n\nlemma signed_measure_sums:\n  assumes \"signed_measure M \\<mu>\"\n    and \"range A \\<subseteq> M\"\n    and \"disjoint_family A\"\n    and \"\\<Union> (range A) \\<in> sets M\"\n  shows \"(\\<lambda>i. \\<mu> (A i)) sums \\<mu> (\\<Union> (range A))\"\n  using assms unfolding signed_measure_def by simp\n\nlemma signed_measure_summable:\n  assumes \"signed_measure M \\<mu>\"\n    and \"range A \\<subseteq> M\"\n    and \"disjoint_family A\"\n    and \"\\<Union> (range A) \\<in> sets M\"\n    and \"\\<bar>\\<mu> (\\<Union> (range A))\\<bar> < \\<infinity>\"\n  shows \"summable (\\<lambda>i. real_of_ereal \\<bar>\\<mu> (A i)\\<bar>)\"\n  using assms unfolding signed_measure_def by simp\n\nlemma signed_measure_inf_sum:\n  assumes \"signed_measure M \\<mu>\"\n    and \"range A \\<subseteq> M\"\n    and \"disjoint_family A\"\n    and \"\\<Union> (range A) \\<in> sets M\"\n  shows \"(\\<Sum>i. \\<mu> (A i)) = \\<mu> (\\<Union> (range A))\" using sums_unique assms \n    signed_measure_sums by (metis)\n\nlemma signed_measure_abs_convergent:\n  assumes \"signed_measure M \\<mu>\"\n    and \"range A \\<subseteq> sets M\"\n    and \"disjoint_family A\"\n    and \"\\<Union> (range A) \\<in> sets M\"\n    and \"\\<bar>\\<mu> (\\<Union> (range A))\\<bar> < \\<infinity>\"\n  shows \"summable (\\<lambda>i. real_of_ereal \\<bar>\\<mu> (A i)\\<bar>)\" using assms \n  unfolding signed_measure_def by simp\n\nlemma signed_measure_additive:\n  assumes \"signed_measure M \\<mu>\"\n  shows \"additive M \\<mu>\"\nproof (auto simp add: additive_def)\n  fix x y\n  assume x: \"x \\<in> M\" and y: \"y \\<in> M\" and \"x \\<inter> y = {}\"\n  hence \"disjoint_family (binaryset x y)\"\n    by (auto simp add: disjoint_family_on_def binaryset_def)\n  have \"(\\<lambda>i. \\<mu> ((binaryset x y) i)) sums (\\<mu> x + \\<mu> y)\"  using binaryset_sums \n      signed_measure_empty[of M \\<mu>] assms  by simp\n  have \"range (binaryset x y) = {x, y, {}}\" using range_binaryset_eq by simp\n  moreover have \"{x, y, {}} \\<subseteq> M\" using x y by auto\n  moreover have \"x\\<union>y \\<in> sets M\" using x y by simp\n  moreover have \"(\\<Union> (range (binaryset x y))) = x\\<union> y\"\n    by (simp add: calculation(1))\n  ultimately have \"(\\<lambda>i. \\<mu> ((binaryset x y) i)) sums \\<mu> (x \\<union> y)\" using assms x y\n      signed_measure_empty[of M \\<mu>] signed_measure_sums[of M \\<mu>]\n      \\<open>disjoint_family (binaryset x y)\\<close> by (metis) \n  then show \"\\<mu> (x \\<union> y) = \\<mu> x + \\<mu> y\" \n    using \\<open>(\\<lambda>i. \\<mu> ((binaryset x y) i)) sums (\\<mu> x + \\<mu> y)\\<close> sums_unique2 by force\nqed\n\nlemma signed_measure_add:\n  assumes \"signed_measure M \\<mu>\"\n    and \"a\\<in> sets M\"\n    and \"b\\<in> sets M\"\n    and \"a\\<inter> b = {}\"\n  shows \"\\<mu> (a\\<union> b) = \\<mu> a + \\<mu> b\" using additiveD[OF signed_measure_additive] \n    assms by auto\n\nlemma signed_measure_disj_sum:\n  shows \"finite I \\<Longrightarrow> signed_measure M \\<mu> \\<Longrightarrow> disjoint_family_on A I \\<Longrightarrow> \n    (\\<And>i. i \\<in> I \\<Longrightarrow> A i \\<in> sets M) \\<Longrightarrow> \\<mu> (\\<Union> i\\<in> I. A i) = (\\<Sum> i\\<in> I. \\<mu> (A i))\"\nproof (induct rule:finite_induct)\n  case empty\n  then show ?case  unfolding signed_measure_def by simp\nnext\n  case (insert x F)\n  have \"\\<mu> (\\<Union> (A ` insert x F)) = \\<mu> ((\\<Union> (A `F)) \\<union> A x)\" \n    by (simp add: Un_commute)\n  also have \"... = \\<mu> (\\<Union> (A `F)) + \\<mu> (A x)\"\n  proof -\n    have \"(\\<Union> (A `F)) \\<inter> (A x) = {}\" using insert\n      by (metis disjoint_family_on_insert inf_commute) \n    moreover have \"\\<Union> (A `F) \\<in> sets M\" using insert by auto\n    moreover have \"A x \\<in> sets M\" using insert by simp\n    ultimately show ?thesis by (meson insert.prems(1) signed_measure_add)\n  qed\n  also have \"... = (\\<Sum> i\\<in> F. \\<mu> (A i)) + \\<mu> (A x)\" using insert\n    by (metis disjoint_family_on_insert insert_iff)\n  also have \"... = (\\<Sum>i\\<in>insert x F. \\<mu> (A i))\"\n    by (simp add: add.commute insert.hyps(1) insert.hyps(2)) \n  finally show ?case .\nqed\n\nlemma pos_signed_measure_count_additive:\n  assumes \"signed_measure M \\<mu>\"\n    and \"\\<forall> E \\<in> sets M. 0 \\<le> \\<mu> E\"\n  shows \"countably_additive (sets M) (\\<lambda>A. e2ennreal (\\<mu> A))\" \n  unfolding countably_additive_def\nproof (intro allI impI)\n  fix A::\"nat \\<Rightarrow> 'a set\"\n  assume \"range A \\<subseteq> sets M\"\n    and \"disjoint_family A\"\n    and \"\\<Union> (range A) \\<in> sets M\" note Aprops = this\n  have eq: \"\\<And>i. \\<mu> (A i) = enn2ereal (e2ennreal (\\<mu> (A i)))\" \n    using assms enn2ereal_e2ennreal Aprops by simp\n  have \"(\\<lambda>n. \\<Sum>i\\<le>n. \\<mu> (A i)) \\<longlonglongrightarrow> \\<mu> (\\<Union> (range A))\" using \n      sums_def_le[of \"\\<lambda>i. \\<mu> (A i)\" \"\\<mu> (\\<Union> (range A))\"] assms \n      signed_measure_sums[of M] Aprops by simp\n  hence \"((\\<lambda>n. e2ennreal (\\<Sum>i\\<le>n. \\<mu> (A i))) \\<longlongrightarrow> \n      e2ennreal (\\<mu> (\\<Union> (range A)))) sequentially\"\n    using tendsto_e2ennrealI[of \"(\\<lambda>n. \\<Sum>i\\<le>n. \\<mu> (A i))\" \"\\<mu> (\\<Union> (range A))\"] \n    by simp\n  moreover have \"\\<And>n. e2ennreal (\\<Sum>i\\<le>n. \\<mu> (A i)) = (\\<Sum>i\\<le>n. e2ennreal (\\<mu> (A i)))\"\n    using e2ennreal_finite_sum by (metis enn2ereal_nonneg eq finite_atMost)\n  ultimately have \"((\\<lambda>n. (\\<Sum>i\\<le>n. e2ennreal (\\<mu> (A i)))) \\<longlongrightarrow> \n    e2ennreal (\\<mu> (\\<Union> (range A)))) sequentially\" by simp\n  hence \"(\\<lambda>i. e2ennreal (\\<mu> (A i))) sums e2ennreal (\\<mu> (\\<Union> (range A)))\" \n    using sums_def_le[of \"\\<lambda>i. e2ennreal (\\<mu> (A i))\" \"e2ennreal (\\<mu> (\\<Union> (range A)))\"] \n    by simp\n  thus \"(\\<Sum>i. e2ennreal (\\<mu> (A i))) = e2ennreal (\\<mu> (\\<Union> (range A)))\" \n    using sums_unique assms by (metis)\nqed\n\nlemma signed_measure_minus:\n  assumes \"signed_measure M \\<mu>\"\n  shows \"signed_measure M (\\<lambda>A. - \\<mu> A)\" unfolding signed_measure_def\nproof (intro conjI)\n  show \"- \\<mu> {} = 0\" using assms unfolding signed_measure_def by simp\n  show \"- \\<infinity> \\<notin> range (\\<lambda>A. - \\<mu> A) \\<or> \\<infinity> \\<notin> range (\\<lambda>A. - \\<mu> A)\" \n  proof (cases \"\\<infinity> \\<in> range \\<mu>\")\n    case True\n    hence \"-\\<infinity> \\<notin> range \\<mu>\" using assms unfolding signed_measure_def by simp\n    hence \"\\<infinity> \\<notin> range (\\<lambda>A. - \\<mu> A)\"  using ereal_uminus_eq_reorder by blast\n    thus \"- \\<infinity> \\<notin> range (\\<lambda>A. - \\<mu> A) \\<or> \\<infinity> \\<notin> range (\\<lambda>A. - \\<mu> A)\" by simp\n  next\n    case False\n    hence \"-\\<infinity> \\<notin> range (\\<lambda>A. - \\<mu> A)\"  using ereal_uminus_eq_reorder \n      by (simp add: image_iff)\n    thus \"- \\<infinity> \\<notin> range (\\<lambda>A. - \\<mu> A) \\<or> \\<infinity> \\<notin> range (\\<lambda>A. - \\<mu> A)\" by simp\n  qed\n  show \"\\<forall>A. range A \\<subseteq> sets M \\<longrightarrow> disjoint_family A \\<longrightarrow> \\<Union> (range A) \\<in> sets M \\<longrightarrow> \n    \\<bar>- \\<mu> (\\<Union> (range A))\\<bar> < \\<infinity> \\<longrightarrow> summable (\\<lambda>i. real_of_ereal \\<bar>- \\<mu> (A i)\\<bar>)\" \n  proof (intro allI impI)\n    fix A::\"nat \\<Rightarrow> 'a set\"\n    assume  \"range A \\<subseteq> sets M\" and \"disjoint_family A\" and \"\\<Union> (range A) \\<in> sets M\"\n      and \"\\<bar>- \\<mu> (\\<Union> (range A))\\<bar> < \\<infinity>\" \n    thus \"summable (\\<lambda>i. real_of_ereal \\<bar>- \\<mu> (A i)\\<bar>)\" using assms \n      unfolding signed_measure_def by simp\n  qed\n  show \"\\<forall>A. range A \\<subseteq> sets M \\<longrightarrow> disjoint_family A \\<longrightarrow> \\<Union> (range A) \\<in> sets M \\<longrightarrow> \n    (\\<lambda>i. - \\<mu> (A i)) sums - \\<mu> (\\<Union> (range A))\"\n  proof -\n    {\n      fix A::\"nat \\<Rightarrow> 'a set\"\n      assume  \"range A \\<subseteq> sets M\" and \"disjoint_family A\" and \n        \"\\<Union> (range A) \\<in> sets M\" note Aprops = this\n      have \"- \\<infinity> \\<notin> range (\\<lambda>i. \\<mu> (A i)) \\<or> \\<infinity> \\<notin> range (\\<lambda>i. \\<mu> (A i))\" \n      proof -\n        have \"range (\\<lambda>i. \\<mu> (A i)) \\<subseteq> range \\<mu>\" by auto\n        thus ?thesis  using assms unfolding signed_measure_def by auto\n      qed\n      moreover have \"(\\<lambda>i. \\<mu> (A i)) sums \\<mu> (\\<Union> (range A))\" \n        using signed_measure_sums[of M] Aprops assms by simp\n      ultimately have \"(\\<lambda>i. - \\<mu> (A i)) sums - \\<mu> (\\<Union> (range A))\" \n        using sums_minus'[of \"\\<lambda>i. \\<mu> (A i)\"] by simp\n    }\n    thus ?thesis by auto\n  qed\nqed\n\nlocale near_finite_function =\n  fixes \\<mu>:: \"'b set \\<Rightarrow> ereal\"\n  assumes inf_range: \"- \\<infinity> \\<notin> range \\<mu> \\<or> \\<infinity> \\<notin> range \\<mu>\"\n\nlemma (in near_finite_function) finite_subset:\n  assumes \"\\<bar>\\<mu> E\\<bar> < \\<infinity>\"\n    and \"A\\<subseteq> E\"\n    and \"\\<mu> E = \\<mu> A + \\<mu> (E - A)\"\n  shows \"\\<bar>\\<mu> A\\<bar> < \\<infinity>\"\nproof (cases \"\\<infinity> \\<in> range \\<mu>\")\n  case False\n  show ?thesis\n  proof (cases \"0 < \\<mu> A\")\n    case True\n    hence \"\\<bar>\\<mu> A\\<bar> = \\<mu> A\" by simp\n    also have \"... < \\<infinity>\" using False by (metis ereal_less_PInfty rangeI)\n    finally show ?thesis .\n  next\n    case False\n    hence \"\\<bar>\\<mu> A\\<bar> = -\\<mu> A\" using not_less_iff_gr_or_eq by fastforce \n    also have \"... = \\<mu> (E - A) - \\<mu> E\"\n    proof -\n      have \"\\<mu> E = \\<mu> A + \\<mu> (E - A)\" using assms by simp \n      hence \"\\<mu> E - \\<mu> A = \\<mu> (E - A)\"\n        by (metis abs_ereal_uminus assms(1) calculation ereal_diff_add_inverse \n            ereal_infty_less(2)  ereal_minus(5) ereal_minus_less_iff \n            ereal_minus_less_minus ereal_uminus_uminus less_ereal.simps(2) \n            minus_ereal_def  plus_ereal.simps(3))\n      thus ?thesis using assms(1) ereal_add_uminus_conv_diff ereal_eq_minus \n        by auto \n    qed\n    also have \"... \\<le> \\<mu> (E - A) + \\<bar>\\<mu> E\\<bar>\"\n      by (metis \\<open>- \\<mu> A = \\<mu> (E - A) - \\<mu> E\\<close> abs_ereal_less0 abs_ereal_pos \n          ereal_diff_le_self ereal_le_add_mono1 less_eq_ereal_def \n          minus_ereal_def not_le_imp_less)\n    also have \"... < \\<infinity>\" using assms \\<open>\\<infinity> \\<notin> range \\<mu>\\<close>\n      by (metis UNIV_I ereal_less_PInfty ereal_plus_eq_PInfty image_eqI) \n    finally show ?thesis .\n  qed\nnext\n  case True\n  hence \"-\\<infinity> \\<notin> range \\<mu>\" using inf_range by simp\n  hence \"-\\<infinity> < \\<mu> A\" by (metis ereal_infty_less(2) rangeI) \n  show ?thesis\n  proof (cases \"\\<mu> A < 0\")\n    case True\n    hence \"\\<bar>\\<mu> A\\<bar> = -\\<mu> A\" using not_less_iff_gr_or_eq by fastforce \n    also have \"... < \\<infinity>\" using \\<open>-\\<infinity> < \\<mu> A\\<close> using ereal_uminus_less_reorder \n      by blast \n    finally show ?thesis .\n  next\n    case False\n    hence \"\\<bar>\\<mu> A\\<bar> = \\<mu> A\" by simp\n    also have \"... = \\<mu> E - \\<mu> (E - A)\"\n    proof -\n      have \"\\<mu> E = \\<mu> A + \\<mu> (E - A)\" using assms by simp  \n      thus \"\\<mu> A = \\<mu> E - \\<mu> (E - A)\" by (metis add.right_neutral  assms(1)\n            add_diff_eq_ereal calculation ereal_diff_add_eq_diff_diff_swap \n            ereal_diff_add_inverse ereal_infty_less(1) ereal_plus_eq_PInfty \n            ereal_x_minus_x)\n    qed\n    also have \"... \\<le> \\<bar>\\<mu> E\\<bar> - \\<mu> (E - A)\" \n      by (metis \\<open>\\<bar>\\<mu> A\\<bar> = \\<mu> A\\<close> \\<open>\\<mu> A = \\<mu> E - \\<mu> (E - A)\\<close> abs_ereal_ge0 \n          abs_ereal_pos abs_ereal_uminus antisym_conv ereal_0_le_uminus_iff \n          ereal_abs_diff ereal_diff_le_mono_left ereal_diff_le_self le_cases \n          less_eq_ereal_def minus_ereal_def) \n    also have \"... < \\<infinity>\" \n    proof -\n      have \"-\\<infinity> < \\<mu> (E - A)\" using \\<open>-\\<infinity> \\<notin> range \\<mu>\\<close> \n        by (metis ereal_infty_less(2) rangeI) \n      hence \"- \\<mu> (E - A) < \\<infinity>\" using ereal_uminus_less_reorder by blast\n      thus ?thesis using assms by (simp add: ereal_minus_eq_PInfty_iff \n            ereal_uminus_eq_reorder)\n    qed\n    finally show ?thesis .\n  qed\nqed\n\nlocale signed_measure_space=\n  fixes M::\"'a measure\" and \\<mu>\n  assumes sgn_meas: \"signed_measure M \\<mu>\"\n\nsublocale signed_measure_space \\<subseteq> near_finite_function\nproof (unfold_locales)\n  show \"- \\<infinity> \\<notin> range \\<mu> \\<or> \\<infinity> \\<notin> range \\<mu>\" using sgn_meas \n    unfolding signed_measure_def by simp\nqed\n\ncontext signed_measure_space\nbegin\nlemma signed_measure_finite_subset:\n  assumes \"E \\<in> sets M\"\n    and \"\\<bar>\\<mu> E\\<bar> < \\<infinity>\"\n    and \"A\\<in> sets M\"\n    and \"A\\<subseteq> E\"\n  shows \"\\<bar>\\<mu> A\\<bar> < \\<infinity>\"\nproof (rule finite_subset)\n  show \"\\<bar>\\<mu> E\\<bar> < \\<infinity>\" \"A\\<subseteq> E\" using assms by auto\n  show \"\\<mu> E = \\<mu> A + \\<mu> (E - A)\" using assms \n      sgn_meas signed_measure_add[of M \\<mu> A \"E - A\"]\n    by (metis Diff_disjoint Diff_partition sets.Diff)\nqed\n\nlemma measure_space_e2ennreal :\n  assumes \"measure_space (space M) (sets M) m \\<and> (\\<forall>E \\<in> sets M. m E < \\<infinity>) \\<and> \n    (\\<forall>E \\<in> sets M. m E \\<ge> 0)\"\n  shows \"\\<forall>E \\<in> sets M. e2ennreal (m E) < \\<infinity>\"\nproof \n  fix E\n  assume \"E \\<in> sets M\"\n  show \"e2ennreal (m E) < \\<infinity>\"\n  proof -\n    have \"m E < \\<infinity>\" using assms \\<open>E \\<in> sets M\\<close>\n      by blast\n    then have \"e2ennreal (m E) < \\<infinity>\" using e2ennreal_less_top\n      using \\<open>m E < \\<infinity>\\<close> by auto \n    thus ?thesis by simp\n  qed\nqed\n\nsubsection \\<open>Positive and negative subsets\\<close>\n\ntext \\<open>The Hahn decomposition theorem is based on the notions of positive and negative measurable\nsets. A measurable set is positive (resp. negative) if all its measurable subsets have a positive\n(resp. negative) measure by $\\mu$. The decomposition theorem states that any measure space for\na signed measure can be decomposed into a positive and a negative measurable set.\\<close>\n\ndefinition pos_meas_set  where\n  \"pos_meas_set E \\<longleftrightarrow> E \\<in> sets M \\<and> (\\<forall>A \\<in> sets M. A \\<subseteq> E \\<longrightarrow> 0 \\<le> \\<mu> A)\"\n\ndefinition neg_meas_set  where\n  \"neg_meas_set E \\<longleftrightarrow> E \\<in> sets M \\<and> (\\<forall>A \\<in> sets M. A \\<subseteq> E \\<longrightarrow> \\<mu> A \\<le> 0)\"\n\nlemma pos_meas_setI:\n  assumes \"E \\<in> sets M\"\n    and \"\\<And>A. A \\<in> sets M \\<Longrightarrow> A \\<subseteq> E \\<Longrightarrow> 0 \\<le> \\<mu> A\"\n  shows \"pos_meas_set E\" unfolding pos_meas_set_def using assms by simp\n\nlemma pos_meas_setD1 :\n  assumes \"pos_meas_set E\"\n  shows \"E \\<in> sets M\"\n  using assms unfolding pos_meas_set_def\n  by simp\n\nlemma neg_meas_setD1 :\n  assumes \"neg_meas_set E\"\n  shows \"E \\<in> sets M\" using assms unfolding neg_meas_set_def by simp\n\nlemma neg_meas_setI:\n  assumes \"E \\<in> sets M\"\n    and \"\\<And>A. A \\<in> sets M \\<Longrightarrow> A \\<subseteq> E \\<Longrightarrow> \\<mu> A \\<le> 0\"\n  shows \"neg_meas_set E\" unfolding neg_meas_set_def using assms by simp\n\nlemma pos_meas_self:\n  assumes \"pos_meas_set E\"\n  shows \"0 \\<le> \\<mu> E\" using assms unfolding pos_meas_set_def by simp\n\nlemma empty_pos_meas_set:\n  shows \"pos_meas_set {}\"\n  by (metis bot.extremum_uniqueI eq_iff pos_meas_set_def sets.empty_sets \n      sgn_meas signed_measure_empty)\n\nlemma empty_neg_meas_set:\n  shows \"neg_meas_set {}\"\n  by (metis neg_meas_set_def order_refl sets.empty_sets sgn_meas \n      signed_measure_empty subset_empty)\n\nlemma pos_measure_meas:\n  assumes \"pos_meas_set E\"\n    and \"A\\<subseteq> E\"\n    and \"A\\<in> sets M\"\n  shows \"0 \\<le> \\<mu> A\" using assms unfolding pos_meas_set_def by simp\n\nlemma pos_meas_subset:\n  assumes \"pos_meas_set A\"\n    and \"B\\<subseteq> A\"\n    and \"B\\<in> sets M\"\n  shows \"pos_meas_set B\" using  assms pos_meas_set_def by auto \n\nlemma neg_meas_subset:\n  assumes \"neg_meas_set A\"\n    and \"B\\<subseteq> A\"\n    and \"B\\<in> sets M\"\n  shows \"neg_meas_set B\" using  assms neg_meas_set_def by auto \n\nlemma pos_meas_set_Union:\n  assumes \"\\<And>(i::nat). pos_meas_set (A i)\"\n    and \"\\<And>i. A i \\<in> sets M\"\n    and \"\\<bar>\\<mu> (\\<Union> i. A i)\\<bar> < \\<infinity>\"\n  shows \"pos_meas_set (\\<Union> i. A i)\"\nproof (rule pos_meas_setI)\n  show \"\\<Union> (range A) \\<in> sets M\" using sigma_algebra.countable_UN assms by simp\n  obtain B where \"disjoint_family B\" and \"(\\<Union>(i::nat). B i) = (\\<Union>(i::nat). A i)\"\n    and \"\\<And>i. B i \\<in> sets M\" and \"\\<And>i. B i \\<subseteq> A i\" using disj_Union2 assms by auto \n  fix C\n  assume \"C \\<in> sets M\" and \"C\\<subseteq> (\\<Union> i. A i)\"\n  hence \"C = C \\<inter> (\\<Union> i. A i)\" by auto\n  also have \"... = C \\<inter> (\\<Union> i. B i)\" using \\<open>(\\<Union>i. B i) = (\\<Union>i. A i)\\<close> by simp\n  also have \"... = (\\<Union> i. C \\<inter> B i)\" by auto\n  finally have \"C = (\\<Union> i. C \\<inter> B i)\" .\n  hence \"\\<mu> C = \\<mu> (\\<Union> i. C \\<inter> B i)\" by simp\n  also have \"... = (\\<Sum>i. \\<mu> (C \\<inter> (B i)))\"\n  proof (rule signed_measure_inf_sum[symmetric])\n    show \"signed_measure M \\<mu>\" using sgn_meas by simp\n    show \"disjoint_family (\\<lambda>i. C \\<inter> B i)\" using \\<open>disjoint_family B\\<close>\n      by (meson Int_iff disjoint_family_subset subset_iff)\n    show \"range (\\<lambda>i. C \\<inter> B i) \\<subseteq> sets M\" using \\<open>C\\<in> sets M\\<close> \\<open>\\<And>i. B i \\<in> sets M\\<close> \n      by auto\n    show \"(\\<Union>i. C \\<inter> B i) \\<in> sets M\" using \\<open>C = (\\<Union> i. C \\<inter> B i)\\<close> \\<open>C\\<in> sets M\\<close> \n      by simp\n  qed\n  also have \"... \\<ge> 0\" \n  proof (rule suminf_nonneg)\n    show \"\\<And>n. 0 \\<le> \\<mu> (C \\<inter> B n)\"\n    proof -\n      fix n\n      have \"C\\<inter> B n \\<subseteq> A n\" using \\<open>\\<And>i. B i \\<subseteq> A i\\<close> by auto\n      moreover have \"C \\<inter> B n \\<in> sets M\" using \\<open>C\\<in> sets M\\<close> \\<open>\\<And>i. B i \\<in> sets M\\<close> \n        by simp\n      ultimately show \"0 \\<le> \\<mu> (C \\<inter> B n)\" using assms pos_measure_meas[of \"A n\"] \n        by simp\n    qed\n    have \"summable (\\<lambda>i. real_of_ereal (\\<mu> (C \\<inter> B i)))\"\n    proof (rule summable_norm_cancel)\n      have \"\\<And>n. norm (real_of_ereal (\\<mu> (C \\<inter> B n))) = \n        real_of_ereal \\<bar>\\<mu> (C \\<inter> B n)\\<bar>\" by simp\n      moreover have \"summable (\\<lambda>i. real_of_ereal \\<bar>\\<mu> (C \\<inter> B i)\\<bar>)\"\n      proof (rule signed_measure_abs_convergent)\n        show \"signed_measure M \\<mu>\" using sgn_meas by simp\n        show \"range (\\<lambda>i. C \\<inter> B i) \\<subseteq> sets M\" using \\<open>C\\<in> sets M\\<close> \n            \\<open>\\<And>i. B i \\<in> sets M\\<close> by auto\n        show \"disjoint_family (\\<lambda>i. C \\<inter> B i)\" using \\<open>disjoint_family B\\<close>\n          by (meson Int_iff disjoint_family_subset subset_iff)\n        show \"(\\<Union>i. C \\<inter> B i) \\<in> sets M\" using \\<open>C = (\\<Union> i. C \\<inter> B i)\\<close> \\<open>C\\<in> sets M\\<close> \n          by simp\n        have \"\\<bar>\\<mu> C\\<bar> < \\<infinity>\"\n        proof (rule signed_measure_finite_subset)\n          show \"(\\<Union> i. A i) \\<in> sets M\" using assms by simp\n          show \"\\<bar>\\<mu> (\\<Union> (range A))\\<bar> < \\<infinity>\" using assms by simp\n          show \"C \\<in> sets M\" using \\<open>C \\<in> sets M\\<close> .\n          show \"C \\<subseteq> \\<Union> (range A)\" using \\<open>C \\<subseteq> \\<Union> (range A) \\<close> .\n        qed\n        thus \"\\<bar>\\<mu> (\\<Union>i. C \\<inter> B i)\\<bar> < \\<infinity>\" using \\<open>C = (\\<Union> i. C \\<inter> B i)\\<close> by simp\n      qed\n      ultimately show \"summable (\\<lambda>n. norm (real_of_ereal (\\<mu> (C \\<inter> B n))))\" \n        by auto\n    qed\n    thus \"summable (\\<lambda>i. \\<mu> (C \\<inter> B i))\" by (simp add: \\<open>\\<And>n. 0 \\<le> \\<mu> (C \\<inter> B n)\\<close> \n          summable_ereal_pos)\n  qed\n  finally show \"0 \\<le> \\<mu> C\" .\nqed\n\nlemma pos_meas_set_pos_lim:\n  assumes \"\\<And>(i::nat). pos_meas_set (A i)\"\n    and \"\\<And>i. A i \\<in> sets M\"\n  shows \"0 \\<le> \\<mu> (\\<Union> i. A i)\" \nproof -\n  obtain B where \"disjoint_family B\" and \"(\\<Union>(i::nat). B i) = (\\<Union>(i::nat). A i)\"\n    and \"\\<And>i. B i \\<in> sets M\" and \"\\<And>i. B i \\<subseteq> A i\" using disj_Union2 assms by auto \n  note Bprops = this\n  have sums: \"(\\<lambda>n. \\<mu> (B n)) sums \\<mu> (\\<Union>i. B i)\" \n  proof (rule signed_measure_sums)\n    show \"signed_measure M \\<mu>\" using sgn_meas .\n    show \"range B \\<subseteq> sets M\" using Bprops by auto\n    show \"disjoint_family B\" using Bprops by simp\n    show \"\\<Union> (range B) \\<in> sets M\" using Bprops by blast\n  qed\n  hence \"summable (\\<lambda>n. \\<mu> (B n))\" using sums_summable[of \"\\<lambda>n. \\<mu> (B n)\"] by simp\n  hence \"suminf (\\<lambda>n. \\<mu> (B n)) = \\<mu> (\\<Union>i. B i)\" using sums sums_iff by auto\n  thus ?thesis using suminf_nonneg\n    by (metis Bprops(2) Bprops(3) Bprops(4) \\<open>summable (\\<lambda>n. \\<mu> (B n))\\<close> assms(1) \n        pos_measure_meas)\nqed\n\nlemma pos_meas_disj_union:\n  assumes \"pos_meas_set A\"\n    and \"pos_meas_set B\"\n    and \"A\\<inter> B = {}\"\n  shows \"pos_meas_set (A \\<union> B)\" unfolding pos_meas_set_def\nproof (intro conjI ballI impI)\n  show \"A\\<union> B \\<in> sets M\"\n    by (metis assms(1) assms(2) pos_meas_set_def sets.Un)\nnext\n  fix C\n  assume \"C\\<in> sets M\" and \"C\\<subseteq> A\\<union> B\"\n  define DA where \"DA = C\\<inter> A\"\n  define DB where \"DB = C\\<inter> B\"\n  have \"DA\\<in> sets M\" using DA_def \\<open>C \\<in> sets M\\<close> assms(1) pos_meas_set_def \n    by blast\n  have \"DB\\<in> sets M\" using DB_def \\<open>C \\<in> sets M\\<close> assms(2) pos_meas_set_def \n    by blast \n  have \"DA \\<inter> DB = {}\" unfolding DA_def DB_def using assms by auto\n  have \"C = DA \\<union> DB\" unfolding DA_def DB_def using \\<open>C\\<subseteq> A\\<union> B\\<close> by auto\n  have \"0 \\<le> \\<mu> DB\" using assms unfolding DB_def pos_meas_set_def\n    by (metis  DB_def Int_lower2\\<open>DB \\<in> sets M\\<close>)\n  also have \"... \\<le> \\<mu> DA + \\<mu> DB\" using assms unfolding  pos_meas_set_def\n    by (metis DA_def Diff_Diff_Int Diff_subset Int_commute \\<open>DA \\<in> sets M\\<close> \n        ereal_le_add_self2)\n  also have \"... = \\<mu> C\" using signed_measure_add sgn_meas \\<open>DA \\<in> sets M\\<close> \n      \\<open>DB \\<in> sets M\\<close> \\<open>DA \\<inter> DB = {}\\<close> \\<open>C = DA \\<union> DB\\<close> by metis\n  finally show \"0 \\<le> \\<mu> C\" .\nqed\n\nlemma pos_meas_set_union:\n  assumes \"pos_meas_set A\"\n    and \"pos_meas_set B\"\n  shows \"pos_meas_set (A \\<union> B)\" \nproof -\n  define C where \"C = B - A\"\n  have \"A\\<union> C = A\\<union> B\" unfolding C_def by auto\n  moreover have \"pos_meas_set (A\\<union> C)\" \n  proof (rule pos_meas_disj_union)\n    show \"pos_meas_set C\" unfolding C_def\n      by (meson Diff_subset assms(1) assms(2) sets.Diff \n          signed_measure_space.pos_meas_set_def \n          signed_measure_space.pos_meas_subset signed_measure_space_axioms)\n    show \"pos_meas_set A\" using assms by simp\n    show \"A \\<inter> C = {}\" unfolding C_def by auto\n  qed\n  ultimately show ?thesis by simp\nqed\n\nlemma neg_meas_disj_union:\n  assumes \"neg_meas_set A\"\n    and \"neg_meas_set B\"\n    and \"A\\<inter> B = {}\"\n  shows \"neg_meas_set (A \\<union> B)\" unfolding neg_meas_set_def\nproof (intro conjI ballI impI)\n  show \"A\\<union> B \\<in> sets M\"\n    by (metis assms(1) assms(2) neg_meas_set_def sets.Un)\nnext\n  fix C\n  assume \"C\\<in> sets M\" and \"C\\<subseteq> A\\<union> B\"\n  define DA where \"DA = C\\<inter> A\"\n  define DB where \"DB = C\\<inter> B\"\n  have \"DA\\<in> sets M\" using DA_def \\<open>C \\<in> sets M\\<close> assms(1) neg_meas_set_def \n    by blast\n  have \"DB\\<in> sets M\" using DB_def \\<open>C \\<in> sets M\\<close> assms(2) neg_meas_set_def \n    by blast \n  have \"DA \\<inter> DB = {}\" unfolding DA_def DB_def using assms by auto\n  have \"C = DA \\<union> DB\" unfolding DA_def DB_def using \\<open>C\\<subseteq> A\\<union> B\\<close> by auto\n  have \"\\<mu> C = \\<mu> DA + \\<mu> DB\" using signed_measure_add sgn_meas \\<open>DA \\<in> sets M\\<close> \n      \\<open>DB \\<in> sets M\\<close> \\<open>DA \\<inter> DB = {}\\<close> \\<open>C = DA \\<union> DB\\<close> by metis\n  also have \"... \\<le> \\<mu> DB\" using assms unfolding  neg_meas_set_def\n    by (metis DA_def Int_lower2 \\<open>DA \\<in> sets M\\<close> add_decreasing dual_order.refl)\n  also have \"... \\<le> 0\" using assms unfolding DB_def neg_meas_set_def\n    by (metis  DB_def Int_lower2\\<open>DB \\<in> sets M\\<close>) \n  finally show \"\\<mu> C \\<le> 0\" .\nqed\n\nlemma neg_meas_set_union:\n  assumes \"neg_meas_set A\"\n    and \"neg_meas_set B\"\n  shows \"neg_meas_set (A \\<union> B)\" \nproof -\n  define C where \"C = B - A\"\n  have \"A\\<union> C = A\\<union> B\" unfolding C_def by auto\n  moreover have \"neg_meas_set (A\\<union> C)\" \n  proof (rule neg_meas_disj_union)\n    show \"neg_meas_set C\" unfolding C_def\n      by (meson Diff_subset assms(1) assms(2) sets.Diff neg_meas_set_def \n          neg_meas_subset signed_measure_space_axioms)\n    show \"neg_meas_set A\" using assms by simp\n    show \"A \\<inter> C = {}\" unfolding C_def by auto\n  qed\n  ultimately show ?thesis by simp\nqed\n\nlemma neg_meas_self :\n  assumes \"neg_meas_set E\"\n  shows \"\\<mu> E \\<le> 0\" using assms unfolding neg_meas_set_def by simp\n\nlemma pos_meas_set_opp:\n  assumes \"signed_measure_space.pos_meas_set  M (\\<lambda> A. - \\<mu> A) A\"\n  shows \"neg_meas_set A\"\nproof - \n  have m_meas_pos : \"signed_measure M  (\\<lambda> A. - \\<mu> A)\"\n    using assms signed_measure_space_def \n    by (simp add: sgn_meas signed_measure_minus)\n  thus ?thesis\n    by (metis assms ereal_0_le_uminus_iff neg_meas_setI \n        signed_measure_space.intro signed_measure_space.pos_meas_set_def) \nqed\n\nlemma neg_meas_set_opp:\n  assumes \"signed_measure_space.neg_meas_set M (\\<lambda> A. - \\<mu> A) A\"\n  shows \"pos_meas_set A\"\nproof -\n  have m_meas_neg : \"signed_measure M  (\\<lambda> A. - \\<mu> A)\"\n    using assms signed_measure_space_def \n    by (simp add: sgn_meas signed_measure_minus)\n  thus ?thesis\n    by (metis assms ereal_uminus_le_0_iff m_meas_neg pos_meas_setI \n        signed_measure_space.intro signed_measure_space.neg_meas_set_def)\nqed\nend\n\nlemma signed_measure_inter:\n  assumes \"signed_measure M \\<mu>\"\n    and \"A \\<in> sets M\"\n  shows \"signed_measure M (\\<lambda>E. \\<mu> (E \\<inter> A))\" unfolding signed_measure_def\nproof (intro conjI)\n  show \"\\<mu> ({} \\<inter> A) = 0\" using assms(1) signed_measure_empty by auto \n  show \"- \\<infinity> \\<notin> range (\\<lambda>E. \\<mu> (E \\<inter> A)) \\<or> \\<infinity> \\<notin> range (\\<lambda>E. \\<mu> (E \\<inter> A))\"\n  proof (rule ccontr)\n    assume \"\\<not> (- \\<infinity> \\<notin> range (\\<lambda>E. \\<mu> (E \\<inter> A)) \\<or> \\<infinity> \\<notin> range (\\<lambda>E. \\<mu> (E \\<inter> A)))\"\n    hence \"- \\<infinity> \\<in> range (\\<lambda>E. \\<mu> (E \\<inter> A)) \\<and> \\<infinity> \\<in> range (\\<lambda>E. \\<mu> (E \\<inter> A))\" by simp\n    hence \"- \\<infinity> \\<in> range \\<mu> \\<and> \\<infinity> \\<in> range \\<mu>\" by auto\n    thus False using assms unfolding signed_measure_def by simp\n  qed\n  show \"\\<forall>E. range E \\<subseteq> sets M \\<longrightarrow> disjoint_family E \\<longrightarrow> \\<Union> (range E) \\<in> sets M \\<longrightarrow> \n    (\\<lambda>i. \\<mu> (E i \\<inter> A)) sums \\<mu> (\\<Union> (range E) \\<inter> A)\"\n  proof (intro allI impI)\n    fix E::\"nat \\<Rightarrow> 'a set\"\n    assume \"range E \\<subseteq> sets M\" and \"disjoint_family E\" and \"\\<Union> (range E) \\<in> sets M\" \n    note Eprops = this\n    define F where \"F = (\\<lambda>i. E i \\<inter> A)\"\n    have \"(\\<lambda>i. \\<mu> (F i)) sums \\<mu> (\\<Union> (range F))\" \n    proof (rule signed_measure_sums)\n      show \"signed_measure M \\<mu>\" using assms by simp\n      show \"range F \\<subseteq> sets M\" using Eprops F_def assms by blast\n      show \"disjoint_family F\" using Eprops F_def assms\n        by (metis disjoint_family_subset inf.absorb_iff2 inf_commute \n            inf_right_idem)\n      show \"\\<Union> (range F) \\<in> sets M\" using Eprops assms unfolding F_def\n        by (simp add: Eprops assms countable_Un_Int(1) sets.Int)\n    qed\n    moreover have \"\\<Union> (range F) = A \\<inter> \\<Union> (range E)\" unfolding F_def by auto   \n    ultimately show \"(\\<lambda>i. \\<mu> (E i \\<inter> A)) sums \\<mu> (\\<Union> (range E) \\<inter> A)\" \n      unfolding F_def by simp\n  qed\n  show \"\\<forall>E. range E \\<subseteq> sets M \\<longrightarrow>\n         disjoint_family E \\<longrightarrow>\n         \\<Union> (range E) \\<in> sets M \\<longrightarrow> \\<bar>\\<mu> (\\<Union> (range E) \\<inter> A)\\<bar> < \\<infinity> \\<longrightarrow> \n         summable (\\<lambda>i. real_of_ereal \\<bar>\\<mu> (E i \\<inter> A)\\<bar>)\"\n  proof (intro allI impI)\n    fix E::\"nat \\<Rightarrow> 'a set\"\n    assume \"range E \\<subseteq> sets M\" and \"disjoint_family E\" and \n      \"\\<Union> (range E) \\<in> sets M\" and \"\\<bar>\\<mu> (\\<Union> (range E) \\<inter> A)\\<bar> < \\<infinity>\" note Eprops = this\n    show \"summable (\\<lambda>i. real_of_ereal \\<bar>\\<mu> (E i \\<inter> A)\\<bar>)\"\n    proof (rule signed_measure_summable)\n      show \"signed_measure M \\<mu>\" using assms by simp\n      show \"range (\\<lambda>i. E i \\<inter> A) \\<subseteq> sets M\" using Eprops assms by blast\n      show \"disjoint_family (\\<lambda>i. E i \\<inter> A)\" using Eprops assms \n          disjoint_family_subset inf.absorb_iff2 inf_commute inf_right_idem \n        by fastforce\n      show \"(\\<Union>i. E i \\<inter> A) \\<in> sets M\" using Eprops assms \n        by (simp add: Eprops assms countable_Un_Int(1) sets.Int)\n      show \"\\<bar>\\<mu> (\\<Union>i. E i \\<inter> A)\\<bar> < \\<infinity>\" using Eprops by auto\n    qed\n  qed\nqed\n\ncontext signed_measure_space\nbegin\nlemma pos_signed_to_meas_space :\n  assumes \"pos_meas_set M1\"\n    and \"m1 = (\\<lambda>A. \\<mu> (A \\<inter> M1))\"\n  shows \"measure_space (space M) (sets M) m1\" unfolding measure_space_def\nproof (intro conjI)\n  show \"sigma_algebra (space M) (sets M)\"\n    by (simp add: sets.sigma_algebra_axioms)\n  show \"positive (sets M) m1\" using assms unfolding pos_meas_set_def\n    by (metis Sigma_Algebra.positive_def Un_Int_eq(4) \n        e2ennreal_neg neg_meas_self sup_bot_right empty_neg_meas_set)\n  show \"countably_additive (sets M) m1\" \n  proof (rule pos_signed_measure_count_additive)\n    show \"\\<forall>E\\<in>sets M. 0 \\<le> m1 E\" by (metis assms inf.cobounded2 \n          pos_meas_set_def sets.Int) \n    show \"signed_measure M m1\" using assms pos_meas_set_def \n        signed_measure_inter[of M \\<mu> M1] sgn_meas by blast\n  qed\nqed\n\nlemma neg_signed_to_meas_space :\n  assumes \"neg_meas_set M2\" \n    and \"m2 = (\\<lambda>A. -\\<mu> (A \\<inter> M2))\"\n  shows \"measure_space (space M) (sets M) m2\" unfolding measure_space_def\nproof (intro conjI)\n  show \"sigma_algebra (space M) (sets M)\"\n    by (simp add: sets.sigma_algebra_axioms)\n  show \"positive (sets M) m2\" using assms unfolding neg_meas_set_def\n    by (metis Sigma_Algebra.positive_def e2ennreal_neg ereal_uminus_zero \n        inf.absorb_iff2 inf.orderE inf_bot_right neg_meas_self pos_meas_self \n        empty_neg_meas_set empty_pos_meas_set)\n  show \"countably_additive (sets M) m2\" \n  proof (rule pos_signed_measure_count_additive)\n    show \"\\<forall>E\\<in>sets M. 0 \\<le> m2 E\"\n      by (metis assms ereal_uminus_eq_reorder ereal_uminus_le_0_iff \n          inf.cobounded2 neg_meas_set_def sets.Int) \n    have \"signed_measure M (\\<lambda>A. \\<mu> (A \\<inter> M2))\" using assms neg_meas_set_def\n        signed_measure_inter[of M \\<mu> M2] sgn_meas by blast\n    thus \"signed_measure M m2\" using signed_measure_minus assms by simp \n  qed\nqed\n\nlemma pos_part_meas_nul_neg_set :\n  assumes \"pos_meas_set M1\" \n    and \"neg_meas_set M2\" \n    and \"m1 = (\\<lambda>A. \\<mu> (A \\<inter> M1))\"\n    and \"E \\<in> sets M\"\n    and \"E \\<subseteq> M2\"\n  shows \"m1 E = 0\"\nproof -\n  have \"m1 E \\<ge> 0\" using assms unfolding pos_meas_set_def\n    by (simp add: \\<open>E \\<in> sets M\\<close> sets.Int) \n  have \"\\<mu> E \\<le> 0\" using \\<open>E \\<subseteq> M2\\<close> assms unfolding neg_meas_set_def\n    using \\<open>E \\<in> sets M\\<close> by blast \n  then have \"m1 E \\<le> 0\" using \\<open>\\<mu> E \\<le> 0\\<close> assms\n    by (metis Int_Un_eq(1) Un_subset_iff \\<open>E \\<in> sets M\\<close> \\<open>E \\<subseteq> M2\\<close> pos_meas_setD1 \n        sets.Int signed_measure_space.neg_meas_set_def \n        signed_measure_space_axioms)\n  thus \"m1 E = 0\" using \\<open>m1 E \\<ge> 0\\<close> \\<open>m1 E \\<le> 0\\<close> by auto\nqed\n\nlemma neg_part_meas_nul_pos_set :\n  assumes \"pos_meas_set M1\" \n    and \"neg_meas_set M2\" \n    and \"m2 = (\\<lambda>A. -\\<mu> (A \\<inter> M2))\"\n    and \"E \\<in> sets M\"\n    and \"E \\<subseteq> M1\"\n  shows \"m2 E = 0\"\nproof -\n  have \"m2 E \\<ge> 0\" using assms unfolding neg_meas_set_def\n    by (simp add: \\<open>E \\<in> sets M\\<close> sets.Int) \n  have \"\\<mu> E \\<ge> 0\" using  assms unfolding pos_meas_set_def by blast \n  then have \"m2 E \\<le> 0\" using \\<open>\\<mu> E \\<ge> 0\\<close> assms\n    by (metis \\<open>E \\<in> sets M\\<close> \\<open>E \\<subseteq> M1\\<close> ereal_0_le_uminus_iff ereal_uminus_uminus \n        inf_sup_ord(1) neg_meas_setD1 pos_meas_set_def pos_meas_subset \n        sets.Int)\n  thus \"m2 E = 0\" using \\<open>m2 E \\<ge> 0\\<close> \\<open>m2 E \\<le> 0\\<close> by auto\nqed\n\ndefinition pos_sets where \n  \"pos_sets = {A. A \\<in> sets M   \\<and> pos_meas_set A}\"\n\ndefinition pos_img where \n  \"pos_img = {\\<mu> A|A. A\\<in> pos_sets}\"\n\nsubsection \\<open>Essential uniqueness\\<close>\n\ntext \\<open>In this part, under the assumption that a measure space for a signed measure admits a\ndecomposition into a positive and a negative set, we prove that this decomposition is\nessentially unique; in other words, that if two such decompositions $(P,N)$ and $(X,Y)$ exist, \nthen any measurable subset of $(P\\triangle X) \\cup (N \\triangle Y)$ has a null measure.\\<close>\n\ndefinition hahn_space_decomp where\n  \"hahn_space_decomp M1 M2 \\<equiv> (pos_meas_set M1) \\<and> (neg_meas_set M2) \\<and> \n(space M = M1 \\<union> M2) \\<and> (M1 \\<inter> M2 = {})\"\n\nlemma pos_neg_null_set:\n  assumes \"pos_meas_set A\"\n    and \"neg_meas_set A\"\n  shows \"\\<mu> A = 0\" using assms pos_meas_self[of A] neg_meas_self[of A] by simp\n\nlemma pos_diff_neg_meas_set:\n  assumes \"(pos_meas_set M1)\" \n    and \"(neg_meas_set N2)\" \n    and \"(space M = N1 \\<union> N2)\" \n    and \"N1 \\<in> sets M\"\n  shows \"neg_meas_set ((M1 - N1) \\<inter> space M)\" using assms neg_meas_subset\n  by (metis Diff_subset_conv Int_lower2 pos_meas_setD1 sets.Diff \n      sets.Int_space_eq2)\n\nlemma neg_diff_pos_meas_set:\n  assumes \"(neg_meas_set M2)\" \n    and \"(pos_meas_set N1)\" \n    and \"(space M = N1 \\<union> N2)\" \n    and \"N2 \\<in> sets M\"\n  shows \"pos_meas_set ((M2 - N2) \\<inter> space M)\" \nproof -\n  have \"(M2 - N2) \\<inter> space M \\<subseteq> N1\" using assms by auto\n  thus ?thesis using assms pos_meas_subset neg_meas_setD1 by blast\nqed\n\nlemma pos_sym_diff_neg_meas_set:\n  assumes \"hahn_space_decomp M1 M2\"\n    and \"hahn_space_decomp N1 N2\"\n  shows \"neg_meas_set ((sym_diff M1 N1) \\<inter> space M)\" using assms \n  unfolding hahn_space_decomp_def\n  by (metis Int_Un_distrib2 neg_meas_set_union pos_meas_setD1 \n      pos_diff_neg_meas_set) \n\nlemma neg_sym_diff_pos_meas_set:\n  assumes \"hahn_space_decomp M1 M2\"\n    and \"hahn_space_decomp N1 N2\"\n  shows \"pos_meas_set ((sym_diff M2 N2) \\<inter> space M)\" using assms \n    neg_diff_pos_meas_set unfolding hahn_space_decomp_def\n  by (metis (no_types, lifting) Int_Un_distrib2 neg_meas_setD1 \n      pos_meas_set_union)\n\nlemma pos_meas_set_diff:\n  assumes \"pos_meas_set A\"\n    and \"B\\<in> sets M\"\n  shows \"pos_meas_set ((A - B) \\<inter> (space M))\" using pos_meas_subset\n  by (metis Diff_subset assms(1) assms(2) pos_meas_setD1 sets.Diff \n      sets.Int_space_eq2)\n\nlemma pos_meas_set_sym_diff:\n  assumes \"pos_meas_set A\"\n    and \"pos_meas_set B\"\n  shows \"pos_meas_set ((sym_diff A B) \\<inter> space M)\" using pos_meas_set_diff\n  by (metis Int_Un_distrib2 assms(1) assms(2) pos_meas_setD1 \n      pos_meas_set_union)\n\nlemma neg_meas_set_diff:\n  assumes \"neg_meas_set A\"\n    and \"B\\<in> sets M\"\n  shows \"neg_meas_set ((A - B) \\<inter> (space M))\" using neg_meas_subset\n  by (metis Diff_subset assms(1) assms(2) neg_meas_setD1 sets.Diff \n      sets.Int_space_eq2)\n\nlemma neg_meas_set_sym_diff:\n  assumes \"neg_meas_set A\"\n    and \"neg_meas_set B\"\n  shows \"neg_meas_set ((sym_diff A B) \\<inter> space M)\" using neg_meas_set_diff\n  by (metis Int_Un_distrib2 assms(1) assms(2) neg_meas_setD1 \n      neg_meas_set_union)\n\nlemma hahn_decomp_space_diff:\n  assumes \"hahn_space_decomp M1 M2\"\n    and \"hahn_space_decomp N1 N2\"\n  shows \"pos_meas_set ((sym_diff M1 N1 \\<union> sym_diff M2 N2) \\<inter> space M)\"\n    \"neg_meas_set ((sym_diff M1 N1 \\<union> sym_diff M2 N2) \\<inter> space M)\"\nproof -\n  show \"pos_meas_set ((sym_diff M1 N1 \\<union> sym_diff M2 N2) \\<inter> space M)\"\n    by (metis Int_Un_distrib2 assms(1) assms(2) hahn_space_decomp_def \n        neg_sym_diff_pos_meas_set pos_meas_set_sym_diff pos_meas_set_union)\n  show \"neg_meas_set ((sym_diff M1 N1 \\<union> sym_diff M2 N2) \\<inter> space M)\"\n    by (metis Int_Un_distrib2 assms(1) assms(2) hahn_space_decomp_def \n        neg_meas_set_sym_diff neg_meas_set_union pos_sym_diff_neg_meas_set)\nqed\n\nlemma hahn_decomp_ess_unique:\n  assumes \"hahn_space_decomp M1 M2\"\n    and \"hahn_space_decomp N1 N2\"\n    and \"C \\<subseteq> sym_diff M1 N1 \\<union> sym_diff M2 N2\"\n    and \"C\\<in> sets M\"\n  shows \"\\<mu> C = 0\"\nproof -\n  have \"C\\<subseteq> (sym_diff M1 N1 \\<union> sym_diff M2 N2) \\<inter> space M\" using assms\n    by (simp add: sets.sets_into_space)     \n  thus ?thesis using assms hahn_decomp_space_diff pos_neg_null_set\n    by (meson neg_meas_subset pos_meas_subset)\nqed\n\nsection \\<open>Existence of a positive subset\\<close>\n\ntext \\<open>The goal of this part is to prove that any measurable set of finite and positive measure must \ncontain a positive subset with a strictly positive measure.\\<close>\n\nsubsection \\<open>A sequence of negative subsets\\<close>\n\ndefinition inf_neg where\n  \"inf_neg A = (if (A \\<notin> sets M \\<or> pos_meas_set A) then (0::nat) \n  else Inf {n|n. (1::nat) \\<le> n \\<and> (\\<exists>B \\<in> sets M. B  \\<subseteq> A \\<and> \\<mu> B < ereal(-1/n))})\"\n\nlemma inf_neg_ne:\n  assumes \"A \\<in> sets M\"\n    and \"\\<not> pos_meas_set A\"\n  shows \"{n::nat|n. (1::nat) \\<le> n \\<and> \n  (\\<exists>B \\<in> sets M. B  \\<subseteq> A \\<and> \\<mu> B < ereal (-1/n))} \\<noteq> {}\"  \nproof -\n  define N where \"N = {n::nat|n. (1::nat) \\<le> n \\<and> \n    (\\<exists>B \\<in> sets M. B  \\<subseteq> A \\<and> \\<mu> B < ereal (-1/n))}\"\n  have \"\\<exists>B \\<in> sets M. B\\<subseteq> A \\<and> \\<mu> B < 0\" using assms unfolding pos_meas_set_def \n    by auto\n  from this obtain B where \"B\\<in> sets M\" and \"B\\<subseteq> A\" and \"\\<mu> B < 0\" by auto\n  hence \"\\<exists>n::nat. (1::nat) \\<le> n \\<and> \\<mu> B < ereal (-1/n)\" \n  proof (cases \"\\<mu> B = -\\<infinity>\")\n    case True\n    hence \"\\<mu> B < -1/(2::nat)\" by simp\n    thus ?thesis using numeral_le_real_of_nat_iff one_le_numeral by blast \n  next\n    case False\n    hence \"real_of_ereal (\\<mu> B) < 0\" using \\<open>\\<mu> B < 0\\<close>\n      by (metis Infty_neq_0(3) ereal_mult_eq_MInfty ereal_zero_mult \n          less_eq_ereal_def less_eq_real_def less_ereal.simps(2) \n          real_of_ereal_eq_0 real_of_ereal_le_0)\n    hence \"\\<exists>n::nat. Suc 0 \\<le> n \\<and> real_of_ereal (\\<mu> B) < -1/n\"\n    proof -\n      define nw where \"nw =  Suc (nat (floor (-1/ (real_of_ereal (\\<mu> B)))))\"\n      have \"Suc 0 \\<le> nw\" unfolding nw_def by simp\n      have \"0 < -1/ (real_of_ereal (\\<mu> B))\" using \\<open>real_of_ereal (\\<mu> B) < 0\\<close> \n        by simp\n      have \"-1/ (real_of_ereal (\\<mu> B)) < nw\" unfolding nw_def by linarith\n      hence \"1/nw < 1/(-1/ (real_of_ereal (\\<mu> B)))\" \n        using \\<open>0 < -1/ (real_of_ereal (\\<mu> B))\\<close> by (metis frac_less2 \n            le_eq_less_or_eq of_nat_1 of_nat_le_iff zero_less_one)\n      also have \"... = - (real_of_ereal (\\<mu> B))\" by simp\n      finally have \"1/nw < - (real_of_ereal (\\<mu> B))\" .\n      hence \"real_of_ereal (\\<mu> B) < -1/nw\" by simp\n      thus ?thesis using \\<open>Suc 0 \\<le> nw\\<close> by auto\n    qed\n    from this obtain n1::nat where \"Suc 0 \\<le> n1\" \n      and \"real_of_ereal (\\<mu> B) < -1/n1\" by auto\n    hence \"ereal (real_of_ereal (\\<mu> B)) < -1/n1\" using real_ereal_leq[of \"\\<mu> B\"] \n        \\<open>\\<mu> B < 0\\<close> by simp\n    moreover have \"\\<mu> B = real_of_ereal (\\<mu> B)\" using \\<open>\\<mu> B < 0\\<close> False\n      by (metis less_ereal.simps(2) real_of_ereal.elims zero_ereal_def)\n    ultimately show ?thesis  using \\<open>Suc 0 \\<le> n1\\<close> by auto \n  qed\n  from this obtain n0::nat where \"(1::nat) \\<le> n0\" and \"\\<mu> B < -1/n0\" by auto\n  hence \"n0 \\<in> {n::nat|n. (1::nat) \\<le> n \\<and> \n    (\\<exists>B \\<in> sets M. B  \\<subseteq> A \\<and> \\<mu> B <  ereal(-1/n))}\" \n    using \\<open>B\\<in> sets M\\<close> \\<open>B\\<subseteq> A\\<close> by auto\n  thus ?thesis by auto\nqed\n\nlemma inf_neg_ge_1:\n  assumes \"A \\<in> sets M\"\n    and \"\\<not> pos_meas_set A\"\n  shows \"(1::nat) \\<le> inf_neg A\"\nproof -\n  define N where \"N = {n::nat|n. (1::nat) \\<le> n \\<and> \n    (\\<exists>B \\<in> sets M. B  \\<subseteq> A \\<and> \\<mu> B < ereal (-1/n))}\"  \n  have \"N \\<noteq> {}\" unfolding N_def using assms inf_neg_ne by auto\n  moreover have \"\\<And>n. n\\<in> N \\<Longrightarrow> (1::nat) \\<le> n\" unfolding N_def by simp\n  ultimately show \"1 \\<le> inf_neg A\" unfolding inf_neg_def N_def\n    using Inf_nat_def1 assms(1) assms(2) by presburger\nqed\n\nlemma inf_neg_pos:\n  assumes \"A \\<in> sets M\"\n    and \"\\<not> pos_meas_set A\"\n  shows \"\\<exists> B \\<in> sets M. B\\<subseteq> A \\<and> \\<mu> B < -1/(inf_neg A)\"  \nproof -\n  define N where \"N = {n::nat|n. (1::nat) \\<le> n \\<and> \n    (\\<exists>B \\<in> sets M. B  \\<subseteq> A \\<and> \\<mu> B < ereal (-1/n))}\"  \n  have \"N \\<noteq> {}\" unfolding N_def using assms inf_neg_ne by auto\n  hence \"Inf N \\<in> N\" using Inf_nat_def1[of N] by simp\n  hence \"inf_neg A \\<in> N\" unfolding N_def inf_neg_def using assms by auto\n  thus ?thesis unfolding N_def by auto\nqed\n\ndefinition rep_neg where\n  \"rep_neg A  = (if (A \\<notin> sets M \\<or> pos_meas_set A) then {} else \n  SOME B. B \\<in> sets M \\<and> B \\<subseteq> A \\<and> \\<mu> B \\<le> ereal (-1 / (inf_neg A)))\"\n\nlemma g_rep_neg:\n  assumes \"A\\<in> sets M\"\n    and \"\\<not> pos_meas_set A\"\n  shows \"rep_neg A \\<in> sets M\" \"rep_neg A \\<subseteq> A\"  \n    \"\\<mu> (rep_neg A) \\<le> ereal (-1 / (inf_neg A))\" \nproof -\n  have \"\\<exists> B. B \\<in> sets M \\<and> B\\<subseteq> A \\<and> \\<mu> B \\<le> -1 / (inf_neg A)\" using assms \n      inf_neg_pos[of A] by auto\n  from someI_ex[OF this] show \"rep_neg A \\<in> sets M\" \"rep_neg A \\<subseteq> A\"  \n    \"\\<mu> (rep_neg A) \\<le> -1 / (inf_neg A)\" \n    unfolding rep_neg_def using assms by auto\nqed\n\nlemma rep_neg_sets:\n  shows \"rep_neg A \\<in> sets M\"\nproof (cases \"A \\<notin> sets M \\<or> pos_meas_set A\")\n  case True\n  then show ?thesis unfolding rep_neg_def by simp\nnext\n  case False\n  then show ?thesis using g_rep_neg(1) by blast\nqed\n\nlemma rep_neg_subset:\n  shows \"rep_neg A \\<subseteq> A\"\nproof (cases \"A \\<notin> sets M \\<or> pos_meas_set A\")\n  case True\n  then show ?thesis unfolding rep_neg_def by simp\nnext\n  case False\n  then show ?thesis using g_rep_neg(2) by blast\nqed\n\nlemma rep_neg_less:\n  assumes \"A\\<in> sets M\"\n    and \"\\<not> pos_meas_set A\"\n  shows \"\\<mu> (rep_neg A) \\<le> ereal (-1 / (inf_neg A))\" using assms g_rep_neg(3) \n  by simp\n\nlemma rep_neg_leq:\n  shows \"\\<mu> (rep_neg A) \\<le> 0\"\nproof (cases \"A \\<notin> sets M \\<or> pos_meas_set A\")\n  case True\n  hence \"rep_neg A = {}\" unfolding rep_neg_def by simp\n  then show ?thesis using sgn_meas signed_measure_empty by force \nnext\n  case False\n  then show ?thesis using rep_neg_less by (metis le_ereal_le minus_divide_left \n        neg_le_0_iff_le of_nat_0 of_nat_le_iff zero_ereal_def zero_le \n        zero_le_divide_1_iff) \nqed\n\nsubsection \\<open>Construction of the positive subset\\<close>\n\nfun pos_wtn\n  where\n    pos_wtn_base: \"pos_wtn E 0 = E\"|\n    pos_wtn_step: \"pos_wtn E (Suc n) = pos_wtn E n - rep_neg (pos_wtn E n)\"\n\nlemma pos_wtn_subset:\n  shows \"pos_wtn E n \\<subseteq> E\"\nproof (induct n)\n  case 0\n  then show ?case using pos_wtn_base by simp\nnext\n  case (Suc n)\n  hence \"rep_neg (pos_wtn E n) \\<subseteq> pos_wtn E n\" using rep_neg_subset by simp\n  then show ?case using Suc by auto\nqed\n\nlemma pos_wtn_sets:\n  assumes \"E\\<in> sets M\"\n  shows \"pos_wtn E n \\<in> sets M\"\nproof (induct n)\n  case 0\n  then show ?case using assms by simp\nnext\n  case (Suc n)\n  then show ?case using pos_wtn_step rep_neg_sets by auto\nqed\n\ndefinition neg_wtn where\n  \"neg_wtn E (n::nat) = rep_neg (pos_wtn E n)\"\n\nlemma neg_wtn_neg_meas:\n  shows \"\\<mu> (neg_wtn E n) \\<le> 0\" unfolding neg_wtn_def using rep_neg_leq by simp\n\nlemma neg_wtn_sets:\n  shows \"neg_wtn E n \\<in> sets M\" unfolding neg_wtn_def using rep_neg_sets by simp\n\nlemma neg_wtn_subset:\n  shows \"neg_wtn E n \\<subseteq> E\" unfolding neg_wtn_def  \n  using pos_wtn_subset[of E n] rep_neg_subset[of \"pos_wtn E n\"] by simp\n\nlemma neg_wtn_union_subset:\n  shows \"(\\<Union> i \\<le> n. neg_wtn E i) \\<subseteq> E\" using neg_wtn_subset by auto\n\nlemma pos_wtn_Suc:\n  shows \"pos_wtn E (Suc n) = E - (\\<Union> i \\<le> n. neg_wtn E i)\" unfolding neg_wtn_def\nproof (induct n)\n  case 0\n  then show ?case using pos_wtn_base pos_wtn_step by simp\nnext\n  case (Suc n)\n  have \"pos_wtn E (Suc (Suc n)) = pos_wtn E (Suc n) - \n    rep_neg (pos_wtn E (Suc n))\" \n    using pos_wtn_step by simp\n  also have \"... = (E - (\\<Union> i \\<le> n. rep_neg (pos_wtn E i))) - \n    rep_neg (pos_wtn E (Suc n))\"\n    using Suc by simp\n  also have \"... = E - (\\<Union> i \\<le> (Suc n). rep_neg (pos_wtn E i))\" \n    using diff_union[of E \"\\<lambda>i. rep_neg (pos_wtn E i)\" n] by auto\n  finally show \"pos_wtn E (Suc (Suc n)) = \n    E - (\\<Union> i \\<le> (Suc n). rep_neg (pos_wtn E i))\" .\nqed\n\ndefinition pos_sub where\n  \"pos_sub E = (\\<Inter> n. pos_wtn E n)\"\n\nlemma pos_sub_sets:\n  assumes \"E\\<in> sets M\"\n  shows \"pos_sub E \\<in> sets M\" unfolding pos_sub_def using pos_wtn_sets assms \n  by auto\n\nlemma pos_sub_subset:\n  shows \"pos_sub E \\<subseteq> E\" unfolding pos_sub_def using pos_wtn_subset by blast\n\nlemma pos_sub_infty:\n  assumes \"E \\<in> sets M\"\n    and \"\\<bar>\\<mu> E\\<bar> < \\<infinity>\"\n  shows \"\\<bar>\\<mu> (pos_sub E)\\<bar> < \\<infinity>\" using signed_measure_finite_subset assms \n    pos_sub_sets pos_sub_subset by simp\n\nlemma neg_wtn_djn:\n  shows \"disjoint_family (\\<lambda>n. neg_wtn E n)\" unfolding disjoint_family_on_def\nproof -\n  {\n    fix n \n    fix m::nat\n    assume \"n < m\"\n    hence \"\\<exists>p. m = Suc p\" using old.nat.exhaust by auto\n    from this obtain p where \"m = Suc p\" by auto\n    have \"neg_wtn E m \\<subseteq> pos_wtn E m\" unfolding neg_wtn_def \n      by (simp add: rep_neg_subset)\n    also have \"... = E - (\\<Union> i \\<le> p. neg_wtn E i)\" using pos_wtn_Suc \\<open>m = Suc p\\<close>\n      by simp\n    finally have \"neg_wtn E m \\<subseteq> E - (\\<Union> i \\<le> p. neg_wtn E i)\" .\n    moreover have \"neg_wtn E n \\<subseteq> (\\<Union> i \\<le> p. neg_wtn E i)\" using \\<open>n < m\\<close> \n        \\<open>m = Suc p\\<close> by (simp add: UN_upper) \n    ultimately have \"neg_wtn E n \\<inter> neg_wtn E m = {}\" by auto\n  }\n  thus \"\\<forall>m\\<in>UNIV. \\<forall>n\\<in>UNIV. m \\<noteq> n \\<longrightarrow> neg_wtn E m \\<inter> neg_wtn E n = {}\"  \n    by (metis inf_commute linorder_neqE_nat) \nqed\nend\n\nlemma disjoint_family_imp_on:\n  assumes \"disjoint_family A\"\n  shows \"disjoint_family_on A S\" \n  using assms disjoint_family_on_mono subset_UNIV by blast \n\ncontext signed_measure_space\nbegin\nlemma neg_wtn_union_neg_meas:\n  shows \"\\<mu> (\\<Union> i \\<le> n. neg_wtn E i) \\<le> 0\" \nproof -\n  have \"\\<mu> (\\<Union> i \\<le> n. neg_wtn E i) = (\\<Sum>i\\<in>{.. n}. \\<mu> (neg_wtn E i))\" \n  proof (rule signed_measure_disj_sum, simp+)\n    show \"signed_measure M \\<mu>\" using sgn_meas .\n    show \"disjoint_family_on (neg_wtn E) {..n}\" using neg_wtn_djn \n        disjoint_family_imp_on[of \"neg_wtn E\"] by simp\n    show \"\\<And>i. i \\<in> {..n} \\<Longrightarrow> neg_wtn E i \\<in> sets M\" using neg_wtn_sets by simp\n  qed\n  also have \"... \\<le> 0\" using neg_wtn_neg_meas by (simp add: sum_nonpos) \n  finally show ?thesis .\nqed\n\nlemma pos_wtn_meas_gt:\n  assumes \"0 < \\<mu> E\"\n    and \"E\\<in> sets M\"\n  shows \"0 < \\<mu> (pos_wtn E n)\"\nproof (cases \"n = 0\")\n  case True\n  then show ?thesis using assms by simp\nnext\n  case False\n  hence \"\\<exists>m. n = Suc m\" by (simp add: not0_implies_Suc) \n  from this obtain m where \"n = Suc m\" by auto\n  hence eq: \"pos_wtn E n = E - (\\<Union> i \\<le> m. neg_wtn E i)\" using pos_wtn_Suc \n    by simp\n  hence \"pos_wtn E n \\<inter> (\\<Union> i \\<le> m. neg_wtn E i) = {}\" by auto\n  moreover have \"E = pos_wtn E n \\<union> (\\<Union> i \\<le> m. neg_wtn E i)\" \n    using eq neg_wtn_union_subset[of E m] by auto \n  ultimately have \"\\<mu> E = \\<mu> (pos_wtn E n) + \\<mu> (\\<Union> i \\<le> m. neg_wtn E i)\" \n    using signed_measure_add[of M \\<mu> \"pos_wtn E n\" \"\\<Union> i \\<le> m. neg_wtn E i\"] \n      pos_wtn_sets neg_wtn_sets assms sgn_meas by auto\n  hence \"0 < \\<mu> (pos_wtn E n) + \\<mu> (\\<Union> i \\<le> m. neg_wtn E i)\" using assms by simp\n  thus ?thesis using neg_wtn_union_neg_meas \n    by (metis add.right_neutral add_mono not_le) \nqed\n\ndefinition union_wit where\n  \"union_wit E = (\\<Union> n. neg_wtn E n)\"\n\nlemma union_wit_sets:\n  shows \"union_wit E \\<in> sets M\" unfolding union_wit_def\nproof (intro sigma_algebra.countable_nat_UN)\n  show \"sigma_algebra (space M) (sets M)\" \n    by (simp add: sets.sigma_algebra_axioms) \n  show \"range (neg_wtn E) \\<subseteq> sets M\"\n  proof -\n    {\n      fix n\n      have \"neg_wtn E n \\<in> sets M\" unfolding neg_wtn_def \n        by (simp add: rep_neg_sets)\n    }\n    thus ?thesis by auto\n  qed\nqed\n\nlemma union_wit_subset:\n  shows \"union_wit E \\<subseteq> E\"\nproof -\n  {\n    fix n\n    have \"neg_wtn E n \\<subseteq> E\" unfolding neg_wtn_def using pos_wtn_subset\n        rep_neg_subset[of \"pos_wtn E n\"] by auto\n  }\n  thus ?thesis unfolding union_wit_def by auto\nqed\n\nlemma pos_sub_diff:\n  shows \"pos_sub E = E - union_wit E\"\nproof\n  show \"pos_sub E \\<subseteq> E - union_wit E\"\n  proof -\n    have \"pos_sub E \\<subseteq> E\" using pos_sub_subset by simp\n    moreover have \"pos_sub E \\<inter> union_wit E = {}\" \n    proof (rule ccontr)\n      assume \"pos_sub E \\<inter> union_wit E \\<noteq> {}\"\n      hence \"\\<exists> a. a\\<in> pos_sub E \\<inter> union_wit E\" by auto\n      from this obtain a where \"a\\<in> pos_sub E \\<inter> union_wit E\" by auto\n      hence \"a\\<in> union_wit E\" by simp\n      hence \"\\<exists>n. a \\<in> rep_neg (pos_wtn E n)\" unfolding union_wit_def neg_wtn_def\n        by auto\n      from this obtain n where \"a \\<in> rep_neg (pos_wtn E n)\" by auto\n      have \"a \\<in> pos_wtn E (Suc n)\" using \\<open>a\\<in> pos_sub E \\<inter> union_wit E\\<close> \n        unfolding pos_sub_def by blast\n      hence \"a\\<notin> rep_neg (pos_wtn E n)\" using pos_wtn_step by simp\n      thus False using \\<open>a \\<in> rep_neg (pos_wtn E n)\\<close> by simp\n    qed\n    ultimately show ?thesis by auto\n  qed\nnext\n  show \"E - union_wit E \\<subseteq> pos_sub E\"\n  proof\n    fix a\n    assume \"a \\<in> E - union_wit E\"\n    show \"a \\<in> pos_sub E\" unfolding pos_sub_def\n    proof\n      fix n\n      show \"a \\<in> pos_wtn E n\"\n      proof (cases \"n = 0\")\n        case True\n        thus ?thesis using pos_wtn_base \\<open>a\\<in> E - union_wit E\\<close> by simp\n      next\n        case False\n        hence \"\\<exists>m. n = Suc m\" by (simp add: not0_implies_Suc) \n        from this obtain m where \"n = Suc m\" by auto\n        have \"(\\<Union> i \\<le> m. rep_neg (pos_wtn E i)) \\<subseteq> \n          (\\<Union> n. (rep_neg (pos_wtn E n)))\" by auto\n        hence \"a \\<in> E - (\\<Union> i \\<le> m. rep_neg (pos_wtn E i))\" \n          using \\<open>a \\<in> E - union_wit E\\<close> unfolding union_wit_def neg_wtn_def \n          by auto\n        thus \"a\\<in> pos_wtn E n\" using pos_wtn_Suc \\<open>n = Suc m\\<close> \n          unfolding neg_wtn_def by simp\n      qed\n    qed\n  qed\nqed\n\ndefinition num_wtn where\n  \"num_wtn E n = inf_neg (pos_wtn E n)\"\n\nlemma num_wtn_geq:\n  shows \"\\<mu> (neg_wtn E n) \\<le> ereal (-1/(num_wtn E n))\" \nproof (cases \"(pos_wtn E n) \\<notin> sets M \\<or> pos_meas_set (pos_wtn E n)\")\n  case True\n  hence \"neg_wtn E n = {}\" unfolding neg_wtn_def rep_neg_def by simp\n  moreover have \"num_wtn E n = 0\" using True unfolding num_wtn_def inf_neg_def \n    by simp\n  ultimately show ?thesis using sgn_meas signed_measure_empty by force \nnext\n  case False\n  then show ?thesis using g_rep_neg(3)[of \"pos_wtn E n\"] unfolding neg_wtn_def \n      num_wtn_def by simp\nqed\n\nlemma neg_wtn_infty:\n  assumes \"E \\<in> sets M\"\n    and \"\\<bar>\\<mu> E\\<bar> < \\<infinity>\"\n  shows \"\\<bar>\\<mu> (neg_wtn E i)\\<bar> < \\<infinity>\"\nproof (rule signed_measure_finite_subset)\n  show \"E \\<in> sets M\" \"\\<bar>\\<mu> E\\<bar> < \\<infinity>\" using assms by auto\n  show \"neg_wtn E i \\<in> sets M\" \n  proof (cases \"pos_wtn E i \\<notin> sets M \\<or> pos_meas_set (pos_wtn E i)\")\n    case True\n    then show ?thesis unfolding neg_wtn_def rep_neg_def by simp\n  next\n    case False\n    then show ?thesis unfolding neg_wtn_def \n      using g_rep_neg(1)[of \"pos_wtn E i\"] by simp\n  qed\n  show \"neg_wtn E i \\<subseteq> E\" unfolding neg_wtn_def using pos_wtn_subset[of E] \n      rep_neg_subset[of \"pos_wtn E i\"] by auto\nqed\n\nlemma union_wit_infty:\n  assumes \"E \\<in> sets M\"\n    and \"\\<bar>\\<mu> E\\<bar> < \\<infinity>\"\n  shows \"\\<bar>\\<mu> (union_wit E)\\<bar> < \\<infinity>\" using union_wit_subset union_wit_sets \n    signed_measure_finite_subset assms unfolding union_wit_def by simp\n\nlemma neg_wtn_summable:\n  assumes \"E \\<in> sets M\"\n    and \"\\<bar>\\<mu> E\\<bar> < \\<infinity>\"\n  shows \"summable (\\<lambda>i. - real_of_ereal (\\<mu> (neg_wtn E i)))\"\nproof -\n  have \"signed_measure M \\<mu>\" using sgn_meas .\n  moreover have \"range (neg_wtn E) \\<subseteq> sets M\" unfolding neg_wtn_def \n    using rep_neg_sets by auto\n  moreover have \"disjoint_family (neg_wtn E)\" using neg_wtn_djn by simp\n  moreover have \"\\<Union> (range (neg_wtn E)) \\<in> sets M\" using union_wit_sets \n    unfolding union_wit_def by simp\n  moreover have \"\\<bar>\\<mu> (\\<Union> (range (neg_wtn E)))\\<bar> < \\<infinity>\" \n    using union_wit_subset signed_measure_finite_subset union_wit_sets assms\n    unfolding union_wit_def by simp\n  ultimately have \"summable (\\<lambda>i. real_of_ereal \\<bar>\\<mu> (neg_wtn E i)\\<bar>)\" \n    using signed_measure_abs_convergent[of M ] by simp\n  moreover have \"\\<And>i. \\<bar>\\<mu> (neg_wtn E i)\\<bar> = -(\\<mu> (neg_wtn E i))\"\n  proof -\n    fix i\n    have \"\\<mu> (neg_wtn E i) \\<le> 0\" using rep_neg_leq[of \"pos_wtn E i\"] \n      unfolding neg_wtn_def .\n    thus \"\\<bar>\\<mu> (neg_wtn E i)\\<bar> = -\\<mu> (neg_wtn E i)\" using less_eq_ereal_def by auto \n  qed\n  ultimately show ?thesis by simp\nqed\n\nlemma inv_num_wtn_summable:\n  assumes \"E \\<in> sets M\"\n    and \"\\<bar>\\<mu> E\\<bar> < \\<infinity>\"\n  shows \"summable (\\<lambda>n. 1/(num_wtn E n))\"\nproof (rule summable_bounded)\n  show \"\\<And>i. 0 \\<le> 1 / real (num_wtn E i)\" by simp\n  show \"\\<And>i. 1 / real (num_wtn E i) \\<le> (\\<lambda>n. -real_of_ereal (\\<mu> (neg_wtn E n))) i\"\n  proof -\n    fix i\n    have \"\\<bar>\\<mu> (neg_wtn E i)\\<bar> < \\<infinity>\" using assms neg_wtn_infty by simp\n    have \"ereal (1/(num_wtn E i)) \\<le> -\\<mu> (neg_wtn E i)\" using num_wtn_geq[of E i] \n        ereal_minus_le_minus by fastforce \n    also have \"... = ereal(- real_of_ereal (\\<mu> (neg_wtn E i)))\" \n      using \\<open>\\<bar>\\<mu> (neg_wtn E i)\\<bar> < \\<infinity>\\<close> ereal_real' by auto\n    finally have \"ereal (1/(num_wtn E i)) \\<le> \n      ereal(- real_of_ereal (\\<mu> (neg_wtn E i)))\" .\n    thus \"1 / real (num_wtn E i) \\<le> -real_of_ereal (\\<mu> (neg_wtn E i))\" by simp\n  qed\n  show \"summable (\\<lambda>i. - real_of_ereal (\\<mu> (neg_wtn E i)))\" \n    using assms neg_wtn_summable by simp\nqed\n\nlemma inv_num_wtn_shift_summable:\n  assumes \"E \\<in> sets M\"\n    and \"\\<bar>\\<mu> E\\<bar> < \\<infinity>\"\n  shows \"summable (\\<lambda>n. 1/(num_wtn E n - 1))\"\nproof (rule sum_shift_denum)\n  show \"summable (\\<lambda>n. 1 / real (num_wtn E n))\" using assms inv_num_wtn_summable\n    by simp\nqed\n\nlemma neg_wtn_meas_sums:\n  assumes \"E \\<in> sets M\"\n    and \"\\<bar>\\<mu> E\\<bar> < \\<infinity>\"\n  shows \"(\\<lambda>i. - (\\<mu> (neg_wtn E i))) sums \n  suminf (\\<lambda>i. - real_of_ereal (\\<mu> (neg_wtn E i)))\"\nproof -\n  have \"(\\<lambda>i. ereal (- real_of_ereal (\\<mu> (neg_wtn E i)))) sums \n    suminf (\\<lambda>i. - real_of_ereal (\\<mu> (neg_wtn E i)))\"\n  proof (rule sums_ereal[THEN iffD2])\n    have \"summable (\\<lambda>i. - real_of_ereal (\\<mu> (neg_wtn E i)))\" \n      using neg_wtn_summable assms by simp\n    thus \"(\\<lambda>x. - real_of_ereal (\\<mu> (neg_wtn E x))) \n      sums (\\<Sum>i. - real_of_ereal (\\<mu> (neg_wtn E i)))\" \n      by auto\n  qed\n  moreover have \"\\<And>i. \\<mu> (neg_wtn E i) = ereal (real_of_ereal (\\<mu> (neg_wtn E i)))\"\n  proof -\n    fix i\n    show \"\\<mu> (neg_wtn E i) = ereal (real_of_ereal (\\<mu> (neg_wtn E i)))\"\n      using assms(1) assms(2) ereal_real' neg_wtn_infty by auto\n  qed\n  ultimately show ?thesis \n    by (metis (no_types, lifting) sums_cong uminus_ereal.simps(1)) \nqed\n\nlemma neg_wtn_meas_suminf_le:\n  assumes \"E \\<in> sets M\"\n    and \"\\<bar>\\<mu> E\\<bar> < \\<infinity>\"\n  shows \"suminf (\\<lambda>i. \\<mu> (neg_wtn E i)) \\<le> - suminf (\\<lambda>n. 1/(num_wtn E n))\"\nproof -\n  have \"suminf (\\<lambda>n. 1/(num_wtn E n)) \\<le> \n    suminf (\\<lambda>i. -real_of_ereal (\\<mu> (neg_wtn E i)))\"\n  proof (rule suminf_le)\n    show \"summable (\\<lambda>n.  1 / real (num_wtn E n))\" using assms \n        inv_num_wtn_summable[of E] \n        summable_minus[of \"\\<lambda>n. 1 / real (num_wtn E n)\"]  by simp \n    show \"summable (\\<lambda>i. -real_of_ereal (\\<mu> (neg_wtn E i)))\" \n      using neg_wtn_summable assms\n        summable_minus[of \"\\<lambda>i. real_of_ereal (\\<mu> (neg_wtn E i))\"] \n      by (simp add: summable_minus_iff) \n    show \"\\<And>n. 1 / real (num_wtn E n) \\<le> -real_of_ereal (\\<mu> (neg_wtn E n))\"\n    proof -\n      fix n\n      have \"\\<mu> (neg_wtn E n) \\<le> ereal (- 1 / real (num_wtn E n))\" \n        using num_wtn_geq by simp\n      hence \"ereal (1/ real (num_wtn E n)) \\<le> - \\<mu> (neg_wtn E n)\"\n        by (metis add.inverse_inverse eq_iff ereal_uminus_le_reorder linear \n            minus_divide_left uminus_ereal.simps(1))\n      have \"real_of_ereal (ereal (1 / real (num_wtn E n))) \\<le> \n        real_of_ereal (- \\<mu> (neg_wtn E n))\"\n      proof (rule real_of_ereal_positive_mono)\n        show \"0 \\<le> ereal (1 / real (num_wtn E n))\" by simp\n        show \"ereal (1 / real (num_wtn E n)) \\<le> - \\<mu> (neg_wtn E n)\" \n          using \\<open>ereal (1 / real (num_wtn E n)) \\<le> - \\<mu> (neg_wtn E n)\\<close> .\n        show \"- \\<mu> (neg_wtn E n) \\<noteq> \\<infinity>\" using neg_wtn_infty[of E n] assms by auto\n      qed\n      thus \"(1 / real (num_wtn E n)) \\<le> -real_of_ereal ( \\<mu> (neg_wtn E n))\" \n        by simp\n    qed\n  qed\n  also have \"... = - suminf (\\<lambda>i. real_of_ereal (\\<mu> (neg_wtn E i)))\" \n  proof (rule suminf_minus)\n    show \"summable (\\<lambda>n. real_of_ereal (\\<mu> (neg_wtn E n)))\" \n      using neg_wtn_summable assms\n        summable_minus[of \"\\<lambda>i. real_of_ereal (\\<mu> (neg_wtn E i))\"] \n      by (simp add: summable_minus_iff) \n  qed\n  finally have \"suminf (\\<lambda>n. 1/(num_wtn E n)) \\<le> \n    - suminf (\\<lambda>i. real_of_ereal (\\<mu> (neg_wtn E i)))\" .\n  hence a:  \"suminf (\\<lambda>i. real_of_ereal (\\<mu> (neg_wtn E i))) \\<le> \n    - suminf (\\<lambda>n. 1/(num_wtn E n))\" by simp\n  show \"suminf (\\<lambda>i. (\\<mu> (neg_wtn E i))) \\<le> ereal (-suminf (\\<lambda>n. 1/(num_wtn E n)))\" \n  proof -\n    have sumeq: \"suminf (\\<lambda>i. ereal (real_of_ereal (\\<mu> (neg_wtn E i)))) = \n      suminf (\\<lambda>i. (real_of_ereal (\\<mu> (neg_wtn E i))))\"\n    proof (rule sums_suminf_ereal)\n      have \"summable (\\<lambda>i. -real_of_ereal (\\<mu> (neg_wtn E i)))\" \n        using neg_wtn_summable assms\n          summable_minus[of \"\\<lambda>i. real_of_ereal (\\<mu> (neg_wtn E i))\"] \n        by (simp add: summable_minus_iff)\n      thus \"(\\<lambda>i. real_of_ereal (\\<mu> (neg_wtn E i))) sums \n        (\\<Sum>i. real_of_ereal (\\<mu> (neg_wtn E i)))\" \n        using neg_wtn_summable[of E] assms summable_minus_iff by blast\n    qed\n    hence \"suminf (\\<lambda>i. \\<mu> (neg_wtn E i)) = \n      suminf (\\<lambda>i. (real_of_ereal (\\<mu> (neg_wtn E i))))\" \n    proof -\n      have \"\\<And>i. ereal (real_of_ereal (\\<mu> (neg_wtn E i))) = \\<mu> (neg_wtn E i)\"\n      proof -\n        fix i\n        show \"ereal (real_of_ereal (\\<mu> (neg_wtn E i))) = \\<mu> (neg_wtn E i)\"\n          using neg_wtn_infty[of E] assms by (simp add: ereal_real')\n      qed\n      thus ?thesis using sumeq by auto \n    qed\n    thus ?thesis using a by simp\n  qed\nqed\n\nlemma union_wit_meas_le:\n  assumes \"E \\<in> sets M\"\n    and \"\\<bar>\\<mu> E\\<bar> < \\<infinity>\"\n  shows \"\\<mu> (union_wit E) \\<le> - suminf (\\<lambda>n. 1 / real (num_wtn E n))\" \nproof -\n  have \"\\<mu> (union_wit E) = \\<mu> (\\<Union> (range (neg_wtn E)))\" unfolding union_wit_def \n    by simp\n  also have \"... = (\\<Sum>i. \\<mu> (neg_wtn E i))\" \n  proof (rule signed_measure_inf_sum[symmetric])\n    show \"signed_measure M \\<mu>\" using sgn_meas .\n    show \"range (neg_wtn E) \\<subseteq> sets M\" \n      by (simp add: image_subset_iff neg_wtn_def rep_neg_sets)\n    show \"disjoint_family (neg_wtn E)\" using neg_wtn_djn by simp\n    show \"\\<Union> (range (neg_wtn E)) \\<in> sets M\" using union_wit_sets \n      unfolding union_wit_def by simp\n  qed\n  also have \"... \\<le> - suminf (\\<lambda>n. 1 / real (num_wtn E n))\" \n    using assms neg_wtn_meas_suminf_le by simp\n  finally show ?thesis .\nqed\n\nlemma pos_sub_pos_meas:\n  assumes \"E \\<in> sets M\"\n    and \"\\<bar>\\<mu> E\\<bar> < \\<infinity>\"\n    and \"0 < \\<mu> E\"\n    and \"\\<not> pos_meas_set E\"\n  shows \"0 < \\<mu> (pos_sub E)\"\nproof -\n  have \"0 < \\<mu> E\" using assms by simp\n  also have \"... = \\<mu> (pos_sub E) + \\<mu> (union_wit E)\"\n  proof -\n    have \"E = pos_sub E \\<union> (union_wit E)\" \n      using pos_sub_diff[of E] union_wit_subset by force \n    moreover have \"pos_sub E \\<inter> union_wit E = {}\" \n      using pos_sub_diff by auto\n    ultimately show ?thesis \n      using signed_measure_add[of M \\<mu> \"pos_sub E\" \"union_wit E\"] \n        pos_sub_sets union_wit_sets assms sgn_meas by simp\n  qed\n  also have \"... \\<le> \\<mu> (pos_sub E) + (- suminf (\\<lambda>n. 1 / real (num_wtn E n)))\"\n  proof -\n    have \"\\<mu> (union_wit E) \\<le> - suminf (\\<lambda>n. 1 / real (num_wtn E n))\" \n      using union_wit_meas_le[of E] assms by simp\n    thus ?thesis using union_wit_infty assms using add_left_mono by blast\n  qed\n  also have \"... = \\<mu> (pos_sub E) - suminf (\\<lambda>n. 1 / real (num_wtn E n))\"\n    by (simp add: minus_ereal_def) \n  finally have \"0 < \\<mu> (pos_sub E) - suminf (\\<lambda>n. 1 / real (num_wtn E n))\" .\n  moreover have \"0 < suminf (\\<lambda>n. 1 / real (num_wtn E n))\" \n  proof (rule suminf_pos2)\n    show \"0 < 1 / real (num_wtn E 0)\" \n      using inf_neg_ge_1[of E] assms pos_wtn_base unfolding num_wtn_def by simp\n    show \"\\<And>n. 0 \\<le> 1 / real (num_wtn E n)\" by simp\n    show \"summable (\\<lambda>n. 1 / real (num_wtn E n))\" \n      using assms inv_num_wtn_summable by simp\n  qed\n  ultimately show ?thesis  using pos_sub_infty assms by fastforce\nqed\n\nlemma num_wtn_conv:\n  assumes \"E \\<in> sets M\"\n    and \"\\<bar>\\<mu> E\\<bar> < \\<infinity>\"\n  shows \"(\\<lambda>n. 1/(num_wtn E n)) \\<longlonglongrightarrow> 0\"\nproof (rule summable_LIMSEQ_zero)\n  show \"summable (\\<lambda>n. 1 / real (num_wtn E n))\" \n    using assms inv_num_wtn_summable by simp\nqed\n\nlemma num_wtn_shift_conv:\n  assumes \"E \\<in> sets M\"\n    and \"\\<bar>\\<mu> E\\<bar> < \\<infinity>\"\n  shows \"(\\<lambda>n. 1/(num_wtn E n - 1)) \\<longlonglongrightarrow> 0\"\nproof (rule summable_LIMSEQ_zero)\n  show \"summable (\\<lambda>n. 1 / real (num_wtn E n - 1))\" \n    using assms inv_num_wtn_shift_summable by simp\nqed\n\nlemma inf_neg_E_set:\n  assumes \"0 < inf_neg E\"\n  shows \"E \\<in> sets M\" using assms unfolding inf_neg_def by presburger\n\nlemma inf_neg_pos_meas:\n  assumes \"0 < inf_neg E\"\n  shows \"\\<not> pos_meas_set E\" using assms unfolding inf_neg_def by presburger\n\nlemma inf_neg_mem:\n  assumes \"0 < inf_neg E\"\n  shows \"inf_neg E \\<in> {n::nat|n. (1::nat) \\<le> n \\<and> \n    (\\<exists>B \\<in> sets M. B  \\<subseteq> E \\<and> \\<mu> B < ereal (-1/n))}\"\nproof -\n  have \"E \\<in> sets M\" using assms unfolding inf_neg_def by presburger\n  moreover have \"\\<not> pos_meas_set E\" using assms unfolding inf_neg_def \n    by presburger\n  ultimately have \"{n::nat|n. (1::nat) \\<le> n \\<and> \n    (\\<exists>B \\<in> sets M. B  \\<subseteq> E \\<and> \\<mu> B < ereal (-1/n))} \\<noteq> {}\" \n    using inf_neg_ne[of E] by simp\n  thus ?thesis unfolding inf_neg_def \n    by (meson Inf_nat_def1 \\<open>E \\<in> sets M\\<close> \\<open>\\<not> pos_meas_set E\\<close>)\nqed\n\nlemma prec_inf_neg_pos:\n  assumes \"0 < inf_neg E - 1\"\n    and \"B \\<in> sets M\"\n    and \"B\\<subseteq> E\"\n  shows \"-1/(inf_neg E - 1) \\<le> \\<mu> B\"\nproof (rule ccontr)\n  define S where \"S = {p::nat|p. (1::nat) \\<le> p \\<and> \n    (\\<exists>B \\<in> sets M. B  \\<subseteq> E \\<and> \\<mu> B < ereal (-1/p))}\"\n  assume \"\\<not> ereal (- 1 / real (inf_neg E - 1)) \\<le> \\<mu> B\"\n  hence \"\\<mu> B < -1/(inf_neg E - 1)\" by auto\n  hence \"inf_neg E - 1\\<in> S\" unfolding S_def using assms by auto\n  have \"Suc 0 < inf_neg E\" using assms by simp\n  hence \"inf_neg E \\<in> S\" unfolding  S_def using inf_neg_mem[of E] by simp\n  hence \"S \\<noteq> {}\" by auto\n  have \"inf_neg E = Inf S\" unfolding S_def inf_neg_def \n    using assms inf_neg_E_set inf_neg_pos_meas by auto\n  have  \"inf_neg E - 1 < inf_neg E\" using assms by simp\n  hence \"inf_neg E -1 \\<notin> S\" \n    using cInf_less_iff[of S] \\<open>S \\<noteq> {}\\<close> \\<open>inf_neg E = Inf S\\<close> by auto\n  thus False using \\<open>inf_neg E - 1 \\<in> S\\<close> by simp\nqed\n\nlemma pos_wtn_meas_ge:\n  assumes \"E \\<in> sets M\"\n    and \"\\<bar>\\<mu> E\\<bar> < \\<infinity>\"\n    and \"C\\<in> sets M\"\n    and \"\\<And>n. C\\<subseteq> pos_wtn E n\"\n    and \"\\<And>n. 0 < num_wtn E n\"\n  shows \"\\<exists>N. \\<forall>n\\<ge> N. - 1/ (num_wtn E n - 1) \\<le> \\<mu> C\" \nproof -\n  have \"\\<exists>N. \\<forall>n\\<ge> N. 1/(num_wtn E n) < 1/2\" using num_wtn_conv[of E] \n      conv_0_half[of \"\\<lambda>n. 1 / real (num_wtn E n)\"] assms by simp\n  from this obtain N where \"\\<forall>n\\<ge> N. 1/(num_wtn E n) < 1/2\" by auto\n  {\n    fix n\n    assume \"N \\<le> n\"\n    hence \"1/(num_wtn E n) < 1/2\" using \\<open>\\<forall>n\\<ge> N. 1/(num_wtn E n) < 1/2\\<close> by simp\n    have \"1/(1/2) < 1/(1/(num_wtn E n))\" \n    proof (rule frac_less2, auto)\n      show \"2 / real (num_wtn E n) < 1\" using \\<open>1/(num_wtn E n) < 1/2\\<close> \n        by linarith\n      show \"0 < num_wtn E n\" unfolding num_wtn_def using inf_neg_ge_1 assms\n        by (simp add: num_wtn_def)\n    qed\n    hence \"2 < (num_wtn E n)\" by simp\n    hence \"Suc 0 < num_wtn E n - 1\" unfolding num_wtn_def by simp\n    hence \"- 1/ (num_wtn E n - 1) \\<le> \\<mu> C\" using assms prec_inf_neg_pos \n      unfolding num_wtn_def by simp\n  }\n  thus ?thesis by auto\nqed\n\nlemma pos_sub_pos_meas_subset:\n  assumes \"E \\<in> sets M\"\n    and \"\\<bar>\\<mu> E\\<bar> < \\<infinity>\"\n    and \"C\\<in> sets M\"\n    and \"C\\<subseteq> (pos_sub E)\"\n    and \"\\<And>n. 0 < num_wtn E n\"\n  shows \"0 \\<le> \\<mu> C\"\nproof -\n  have \"\\<And>n. C \\<subseteq> pos_wtn E n\" using assms unfolding pos_sub_def by auto\n  hence \"\\<exists>N. \\<forall>n\\<ge> N. - 1/ (num_wtn E n - 1) \\<le> \\<mu> C\" using  assms  \n      pos_wtn_meas_ge[of E C] by simp\n  from this obtain N where Nprop: \"\\<forall>n\\<ge> N. - 1/ (num_wtn E n - 1) \\<le> \\<mu> C\" by auto\n  show \"0 \\<le> \\<mu> C\"\n  proof (rule lim_mono)\n    show \"\\<And>n. N \\<le> n \\<Longrightarrow> - 1/ (num_wtn E n - 1) \\<le> (\\<lambda>n. \\<mu> C) n\" \n      using Nprop by simp\n    have \"(\\<lambda>n.  ( 1 / real (num_wtn E n - 1))) \\<longlonglongrightarrow> 0\" \n      using assms num_wtn_shift_conv[of E] by simp\n    hence \"(\\<lambda>n.  (- 1 / real (num_wtn E n - 1))) \\<longlonglongrightarrow> 0\" \n      using tendsto_minus[of \"\\<lambda>n. 1 / real (num_wtn E n - 1)\" 0] by simp\n    thus \"(\\<lambda>n. ereal (- 1 / real (num_wtn E n - 1))) \\<longlonglongrightarrow> 0\" \n      by (simp add: zero_ereal_def) \n    show \"(\\<lambda>n. \\<mu> C) \\<longlonglongrightarrow> \\<mu> C\" by simp\n  qed\nqed\n\nlemma pos_sub_pos_meas':\n  assumes \"E \\<in> sets M\"\n    and \"\\<bar>\\<mu> E\\<bar> < \\<infinity>\"\n    and \"0 < \\<mu> E\"\n    and \"\\<forall>n. 0 < num_wtn E n\"\n  shows \"0 < \\<mu> (pos_sub E)\"\nproof -\n  have \"0 < \\<mu> E\" using assms by simp\n  also have \"... = \\<mu> (pos_sub E) + \\<mu> (union_wit E)\"\n  proof -\n    have \"E = pos_sub E \\<union> (union_wit E)\" \n      using pos_sub_diff[of E] union_wit_subset by force \n    moreover have \"pos_sub E \\<inter> union_wit E = {}\" \n      using pos_sub_diff by auto\n    ultimately show ?thesis \n      using signed_measure_add[of M \\<mu> \"pos_sub E\" \"union_wit E\"] \n        pos_sub_sets union_wit_sets assms sgn_meas by simp\n  qed\n  also have \"... \\<le> \\<mu> (pos_sub E) + (- suminf (\\<lambda>n. 1 / real (num_wtn E n)))\"\n  proof -\n    have \"\\<mu> (union_wit E) \\<le> - suminf (\\<lambda>n. 1 / real (num_wtn E n))\" \n      using union_wit_meas_le[of E] assms by simp\n    thus ?thesis using union_wit_infty assms using add_left_mono by blast\n  qed\n  also have \"... = \\<mu> (pos_sub E) - suminf (\\<lambda>n. 1 / real (num_wtn E n))\"\n    by (simp add: minus_ereal_def) \n  finally have \"0 < \\<mu> (pos_sub E) - suminf (\\<lambda>n. 1 / real (num_wtn E n))\" .\n  moreover have \"0 < suminf (\\<lambda>n. 1 / real (num_wtn E n))\" \n  proof (rule suminf_pos2)\n    show \"0 < 1 / real (num_wtn E 0)\" using assms by simp\n    show \"\\<And>n. 0 \\<le> 1 / real (num_wtn E n)\" by simp\n    show \"summable (\\<lambda>n. 1 / real (num_wtn E n))\" \n      using assms inv_num_wtn_summable by simp\n  qed\n  ultimately show ?thesis  using pos_sub_infty assms by fastforce\nqed\n\ntext \\<open>We obtain the main result of this part on the existence of a positive subset.\\<close>\n\nlemma exists_pos_meas_subset:\n  assumes \"E \\<in> sets M\"\n    and \"\\<bar>\\<mu> E\\<bar> < \\<infinity>\"\n    and \"0 < \\<mu> E\"\n  shows \"\\<exists>A. A \\<subseteq> E \\<and> pos_meas_set A \\<and> 0 < \\<mu> A\"\nproof (cases \"\\<forall>n. 0 < num_wtn E n\")\n  case True\n  have \"pos_meas_set (pos_sub E)\" \n  proof (rule pos_meas_setI)\n    show \"pos_sub E \\<in> sets M\" by (simp add: assms(1) pos_sub_sets) \n    fix A\n    assume \"A \\<in> sets M\" and \"A\\<subseteq> pos_sub E\"\n    thus \"0 \\<le> \\<mu> A\" using assms True pos_sub_pos_meas_subset[of E] by simp\n  qed\n  moreover have \"0 < \\<mu> (pos_sub E)\" \n    using pos_sub_pos_meas'[of E] True assms by simp\n  ultimately show ?thesis using pos_meas_set_def by (metis pos_sub_subset)\nnext\n  case False\n  hence \"\\<exists>n. num_wtn E n = 0\" by simp\n  from this obtain n where \"num_wtn E n = 0\" by auto\n  hence \"pos_wtn E n \\<notin> sets M \\<or> pos_meas_set (pos_wtn E n)\" \n    using inf_neg_ge_1 unfolding num_wtn_def by fastforce\n  hence \"pos_meas_set (pos_wtn E n)\" using assms \n    by (simp add: \\<open>E \\<in> sets M\\<close> pos_wtn_sets) \n  moreover have \"0 < \\<mu> (pos_wtn E n)\" using pos_wtn_meas_gt assms by simp\n  ultimately show ?thesis using pos_meas_set_def by (meson pos_wtn_subset)   \nqed\n\nsection \\<open>The Hahn decomposition theorem\\<close>\n\ndefinition seq_meas where\n  \"seq_meas = (SOME f. incseq f \\<and> range f \\<subseteq> pos_img  \\<and> \\<Squnion> pos_img = \\<Squnion> range f)\"\n\nlemma seq_meas_props:\n  shows \"incseq seq_meas \\<and> range seq_meas \\<subseteq> pos_img \\<and> \n    \\<Squnion> pos_img = \\<Squnion> range seq_meas\"\nproof -\n  have ex: \"\\<exists>f. incseq f \\<and> range f \\<subseteq> pos_img  \\<and> \\<Squnion> pos_img = \\<Squnion> range f\"\n  proof (rule Extended_Real.Sup_countable_SUP)\n    show \"pos_img \\<noteq> {}\"\n    proof -\n      have \"{} \\<in> pos_sets\" using empty_pos_meas_set unfolding pos_sets_def \n        by simp\n      hence \"\\<mu> {} \\<in> pos_img\" unfolding pos_img_def by auto\n      thus ?thesis by auto\n    qed \n  qed\n  let ?V = \"SOME f. incseq f \\<and> range f \\<subseteq> pos_img  \\<and> \\<Squnion> pos_img = \\<Squnion> range f\"\n  have vprop: \"incseq ?V \\<and> range ?V \\<subseteq> pos_img \\<and> \\<Squnion> pos_img = \\<Squnion> range ?V\" \n    using someI_ex[of \"\\<lambda>f. incseq f \\<and> range f \\<subseteq> pos_img  \\<and> \n      \\<Squnion> pos_img = \\<Squnion> range f\"] ex by blast\n  show ?thesis using seq_meas_def vprop by presburger\nqed\n\ndefinition seq_meas_rep where\n  \"seq_meas_rep n = (SOME A. A\\<in> pos_sets \\<and> seq_meas n = \\<mu> A)\"\n\nlemma seq_meas_rep_ex:\n  shows \"seq_meas_rep n \\<in> pos_sets \\<and> \\<mu> (seq_meas_rep n) = seq_meas n\"\nproof -\n  have ex: \"\\<exists>A. A \\<in> pos_sets \\<and> seq_meas n = \\<mu> A\" using seq_meas_props\n    by (smt (z3) UNIV_I image_subset_iff mem_Collect_eq pos_img_def) \n  let ?V = \"SOME A. A\\<in> pos_sets \\<and> seq_meas n = \\<mu> A\"\n  have vprop: \"?V\\<in> pos_sets \\<and> seq_meas n = \\<mu> ?V\" using \n      someI_ex[of \"\\<lambda>A. A\\<in> pos_sets \\<and> seq_meas n = \\<mu> A\"] using ex by blast\n  show ?thesis using seq_meas_rep_def vprop by fastforce \nqed\n\nlemma seq_meas_rep_pos:\n  assumes \"\\<forall>E \\<in> sets M. \\<mu> E < \\<infinity>\" \n  shows \"pos_meas_set (\\<Union> i. seq_meas_rep i)\" \nproof (rule pos_meas_set_Union)\n  show \" \\<And>i. pos_meas_set (seq_meas_rep i)\" \n    using seq_meas_rep_ex signed_measure_space.pos_sets_def \n      signed_measure_space_axioms by auto\n  then show \"\\<And>i. seq_meas_rep i \\<in> sets M\"\n    by (simp add: pos_meas_setD1)\n  show \"\\<bar>\\<mu> (\\<Union> (range seq_meas_rep))\\<bar> < \\<infinity>\"\n  proof -\n    have \"(\\<Union> (range seq_meas_rep)) \\<in> sets M\"\n    proof (rule sigma_algebra.countable_Union)\n      show \"sigma_algebra (space M) (sets M)\" \n        by (simp add: sets.sigma_algebra_axioms) \n      show \"countable (range seq_meas_rep)\" by simp\n      show \"range seq_meas_rep \\<subseteq> sets M\" \n        by (simp add: \\<open>\\<And>i. seq_meas_rep i \\<in> sets M\\<close> image_subset_iff)\n    qed\n    hence \"\\<mu> (\\<Union> (range seq_meas_rep)) \\<ge> 0 \" \n      using \\<open>\\<And>i. pos_meas_set (seq_meas_rep i)\\<close> \\<open>\\<And>i. seq_meas_rep i \\<in> sets M\\<close> \n        signed_measure_space.pos_meas_set_pos_lim signed_measure_space_axioms \n      by blast\n    thus ?thesis using assms \\<open>\\<Union> (range seq_meas_rep) \\<in> sets M\\<close> abs_ereal_ge0  \n      by simp\n  qed   \nqed\n\nlemma sup_seq_meas_rep:\n  assumes \"\\<forall>E \\<in> sets M. \\<mu> E < \\<infinity>\" \n    and \"S = (\\<Squnion> pos_img)\"\n    and \"A = (\\<Union> i. seq_meas_rep i)\"\n  shows \"\\<mu> A = S\"\nproof -\n  have pms: \"pos_meas_set (\\<Union> i. seq_meas_rep i)\" \n    using assms seq_meas_rep_pos by simp\n  hence \"\\<mu> A \\<le> S\" \n    by (metis (mono_tags, lifting) Sup_upper \\<open>S = \\<Squnion> pos_img\\<close> mem_Collect_eq \n        pos_img_def pos_meas_setD1 pos_sets_def assms(2) assms(3))  \n  have \"\\<forall>n. (\\<mu> A = \\<mu> (A - seq_meas_rep n) + \\<mu> (seq_meas_rep n))\"\n  proof\n    fix n\n    have \"A = (A - seq_meas_rep n) \\<union> seq_meas_rep n \" \n      using \\<open>A = \\<Union> (range seq_meas_rep)\\<close> by blast\n    hence \"\\<mu> A = \\<mu> ((A - seq_meas_rep n) \\<union> seq_meas_rep n)\"  by simp\n    also have \"... = \\<mu> (A - seq_meas_rep n) + \\<mu> (seq_meas_rep n)\" \n    proof (rule signed_measure_add)\n      show \"signed_measure M \\<mu>\" using sgn_meas by simp\n      show \"seq_meas_rep n \\<in> sets M\"\n        using pos_sets_def seq_meas_rep_ex by auto\n      then show \"A - seq_meas_rep n \\<in> sets M\"\n        by (simp add: assms pms pos_meas_setD1 sets.Diff)\n      show \"(A - seq_meas_rep n) \\<inter> seq_meas_rep n = {}\" by auto\n    qed\n    finally show \"\\<mu> A = \\<mu> (A - seq_meas_rep n) + \\<mu> (seq_meas_rep n)\".\n  qed\n  have \"\\<forall>n. \\<mu> A \\<ge> \\<mu> (seq_meas_rep n)\" \n  proof \n    fix n\n    have \"\\<mu> A \\<ge> 0\" using pms assms unfolding pos_meas_set_def by auto\n    have \"(A - seq_meas_rep n) \\<subseteq> A\" by simp\n    hence \"pos_meas_set (A - seq_meas_rep n)\" \n    proof -\n      have \"(A - seq_meas_rep n) \\<in> sets M\"\n        using pms assms pos_meas_setD1 pos_sets_def seq_meas_rep_ex by auto\n      thus ?thesis using pms assms unfolding pos_meas_set_def by auto\n    qed\n    hence \"\\<mu> (A - seq_meas_rep n) \\<ge> 0\" unfolding pos_meas_set_def by auto\n    thus \"\\<mu> (seq_meas_rep n) \\<le> \\<mu> A\" \n      using \\<open>\\<forall>n. (\\<mu> A = \\<mu> (A - seq_meas_rep n) + \\<mu> (seq_meas_rep n))\\<close>\n      by (metis ereal_le_add_self2) \n  qed\n  hence \"\\<mu> A \\<ge> (\\<Squnion> range seq_meas)\" by (simp add: Sup_le_iff seq_meas_rep_ex)\n  moreover have \"S = (\\<Squnion> range seq_meas)\" \n    using seq_meas_props \\<open>S = (\\<Squnion> pos_img)\\<close> by simp\n  ultimately have \"\\<mu> A \\<ge> S\" by simp\n  thus \"\\<mu> A = S\" using \\<open>\\<mu> A \\<le> S\\<close> by simp\nqed\n\nlemma seq_meas_rep_compl:\n  assumes \"\\<forall>E \\<in> sets M. \\<mu> E < \\<infinity>\"\n    and \"A = (\\<Union> i. seq_meas_rep i)\"\n  shows \"neg_meas_set ((space M) - A)\" unfolding neg_meas_set_def\nproof (rule ccontr)\n  assume asm: \"\\<not> (space M - A \\<in> sets M \\<and> \n    (\\<forall>Aa\\<in>sets M. Aa \\<subseteq> space M - A \\<longrightarrow> \\<mu> Aa \\<le> 0))\" \n  define S where \"S = (\\<Squnion> pos_img)\"\n  have \"pos_meas_set A\"  using assms seq_meas_rep_pos by simp\n  have \"\\<mu> A = S\" using sup_seq_meas_rep assms  S_def by simp\n  hence \"S < \\<infinity>\" using assms \\<open>pos_meas_set A\\<close> pos_meas_setD1 by blast \n  have \"(space M - A \\<in> sets M)\"\n    by (simp add: \\<open>pos_meas_set A\\<close> pos_meas_setD1 sets.compl_sets)\n  hence \" \\<not>(\\<forall>Aa\\<in>sets M. Aa \\<subseteq> space M - A \\<longrightarrow> \\<mu> Aa \\<le> 0)\" using asm by blast\n  hence \"\\<exists> E \\<in> sets M. E \\<subseteq> ((space M) - A) \\<and> \\<mu> E > 0\" \n    by (metis less_eq_ereal_def linear)\n  from this obtain E where \"E \\<in> sets M\" and \"E \\<subseteq> ((space M) - A)\" and \n    \"\\<mu> E > 0\" by auto\n  have \"\\<exists> A0 \\<subseteq> E. pos_meas_set A0 \\<and> \\<mu> A0 > 0\" \n  proof (rule exists_pos_meas_subset) \n    show \"E \\<in> sets M\" using \\<open>E \\<in> sets M\\<close> by simp\n    show \"0 < \\<mu> E\" using \\<open>\\<mu> E > 0\\<close> by simp\n    show \"\\<bar>\\<mu> E\\<bar> < \\<infinity>\" \n    proof -\n      have \"\\<mu> E < \\<infinity>\" using assms \\<open>E \\<in> sets M\\<close> by simp\n      moreover have \"- \\<infinity> < \\<mu> E\" using \\<open>0 < \\<mu> E\\<close> by simp \n      ultimately show ?thesis\n        by (meson ereal_infty_less(1) not_inftyI)\n    qed\n  qed\n  from this obtain A0 where \"A0 \\<subseteq> E\" and \"pos_meas_set A0\" and \" \\<mu> A0 > 0\" \n    by auto\n  have \"pos_meas_set (A \\<union> A0)\" \n    using pos_meas_set_union \\<open>pos_meas_set A0\\<close> \\<open>pos_meas_set A\\<close> by simp\n  have \"\\<mu> (A \\<union> A0) = \\<mu> A + \\<mu> A0\" \n  proof (rule signed_measure_add)\n    show \"signed_measure M \\<mu>\" using sgn_meas by simp\n    show \"A \\<in> sets M\" using \\<open>pos_meas_set A\\<close> \n      unfolding pos_meas_set_def by simp\n    show \"A0 \\<in> sets M\" using \\<open>pos_meas_set A0\\<close> \n      unfolding pos_meas_set_def by simp\n    show \"(A \\<inter> A0) = {}\" using \\<open>A0 \\<subseteq> E\\<close> \\<open>E \\<subseteq> ((space M) - A)\\<close> by auto\n  qed\n  then have \"\\<mu> (A \\<union> A0) > S\" \n    using \\<open>\\<mu> A = S\\<close> \\<open>\\<mu> A0 > 0\\<close>\n    by (metis \\<open>S < \\<infinity>\\<close> \\<open>pos_meas_set (A \\<union> A0)\\<close> abs_ereal_ge0 ereal_between(2) \n        not_inftyI not_less_iff_gr_or_eq pos_meas_self)\n  have \"(A \\<union> A0) \\<in> pos_sets\"\n  proof -\n    have \" (A \\<union> A0) \\<in> sets M\" using sigma_algebra.countable_Union\n      by (simp add: \\<open>pos_meas_set (A \\<union> A0)\\<close> pos_meas_setD1) \n    moreover have \"pos_meas_set (A \\<union> A0)\" using \\<open>pos_meas_set (A \\<union> A0)\\<close> by simp\n    ultimately show ?thesis unfolding pos_sets_def by simp\n  qed\n  then have \"\\<mu> (A \\<union> A0) \\<in> pos_img\" unfolding pos_img_def by auto\n  show False using \\<open>\\<mu> (A \\<union> A0) > S\\<close> \\<open>\\<mu> (A \\<union> A0) \\<in> pos_img\\<close> \\<open>S = (\\<Squnion> pos_img)\\<close>\n    by (metis Sup_upper sup.absorb_iff2 sup.strict_order_iff)\nqed\n\nlemma hahn_decomp_finite:\n  assumes \"\\<forall>E \\<in> sets M. \\<mu> E < \\<infinity>\"\n  shows \"\\<exists> M1 M2. hahn_space_decomp M1 M2\" unfolding hahn_space_decomp_def\nproof -\n  define S where \"S = (\\<Squnion> pos_img)\"\n  define A where \"A = (\\<Union> i. seq_meas_rep i)\" \n  have \"pos_meas_set A\" unfolding A_def using assms seq_meas_rep_pos by simp\n  have \"neg_meas_set ((space M) - A)\" \n    using seq_meas_rep_compl assms unfolding A_def by simp\n  show \"\\<exists>M1 M2. pos_meas_set M1 \\<and> neg_meas_set M2 \\<and> space M = M1 \\<union> M2 \\<and> \n    M1 \\<inter> M2 = {}\"\n  proof (intro exI conjI)\n    show \"pos_meas_set A\" using \\<open>pos_meas_set A\\<close> .\n    show \"neg_meas_set (space M - A)\" using \\<open>neg_meas_set (space M - A)\\<close> .\n    show \"space M = A \\<union> (space M - A)\"\n      by (metis Diff_partition \\<open>pos_meas_set A\\<close> inf.absorb_iff2 pos_meas_setD1 \n          sets.Int_space_eq1) \n    show \"A \\<inter> (space M - A) = {}\" by auto\n  qed\nqed\n\ntheorem hahn_decomposition:\n  shows \"\\<exists> M1 M2. hahn_space_decomp M1 M2\"\nproof (cases \"\\<forall>E \\<in> sets M. \\<mu> E < \\<infinity>\")\n  case True\n  thus ?thesis using hahn_decomp_finite by simp\nnext\n  case False\n  define m where \"m = (\\<lambda>A . - \\<mu> A)\"\n  have \"\\<exists> M1 M2. signed_measure_space.hahn_space_decomp M m M1 M2\"\n  proof (rule signed_measure_space.hahn_decomp_finite)\n    show \"signed_measure_space M m\" \n      using signed_measure_minus sgn_meas \\<open>m = (\\<lambda>A . - \\<mu> A)\\<close>  \n      by (unfold_locales, simp)\n    show \"\\<forall>E\\<in>sets M. m E < \\<infinity>\"\n    proof\n      fix E\n      assume \"E \\<in> sets M\"\n      show \"m E < \\<infinity>\"\n      proof\n        show \"m E \\<noteq> \\<infinity>\"\n        proof (rule ccontr)\n          assume \"\\<not> m E \\<noteq> \\<infinity>\"\n          have \"m E = \\<infinity>\"\n            using \\<open>\\<not> m E \\<noteq> \\<infinity>\\<close> by auto \n          have \"signed_measure M m\"\n            using \\<open>signed_measure_space M m\\<close> signed_measure_space_def by auto\n          moreover have \"m E = - \\<mu> E\" using \\<open>m = (\\<lambda>A . - \\<mu> A)\\<close> by auto\n          then have \"\\<infinity> \\<notin> range m\" using \\<open>signed_measure M m\\<close>\n            by (metis (no_types, lifting) False ereal_less_PInfty \n                ereal_uminus_eq_reorder image_iff inf_range m_def rangeI)\n          show False using \\<open>m E = \\<infinity>\\<close> \\<open>\\<infinity> \\<notin> range m\\<close>\n            by (metis rangeI)\n        qed\n      qed\n    qed\n  qed\n  hence \"\\<exists> M1 M2. (neg_meas_set M1) \\<and> (pos_meas_set M2) \\<and> (space M = M1 \\<union> M2) \\<and>\n    (M1 \\<inter> M2 = {})\" \n    using pos_meas_set_opp neg_meas_set_opp unfolding m_def \n    by (metis sgn_meas signed_measure_minus signed_measure_space_def \n        signed_measure_space.hahn_space_decomp_def)\n  thus ?thesis using hahn_space_decomp_def by (metis inf_commute sup_commute)\nqed\n\nsection \\<open>The Jordan decomposition theorem\\<close>\n\ndefinition jordan_decomp where\n  \"jordan_decomp m1 m2 \\<longleftrightarrow> ((measure_space (space M) (sets M) m1) \\<and> \n    (measure_space (space M) (sets M) m2) \\<and> \n    (\\<forall>A\\<in> sets M. 0 \\<le> m1 A) \\<and>\n    (\\<forall> A\\<in> sets M. 0 \\<le> m2 A) \\<and>\n    (\\<forall>A \\<in> sets M. \\<mu> A = (m1 A) - (m2 A)) \\<and>\n    (\\<forall> P N A. hahn_space_decomp P N \\<longrightarrow> \n      (A \\<in> sets M \\<longrightarrow> A \\<subseteq> P \\<longrightarrow> (m2 A) = 0) \\<and> \n      (A \\<in> sets M \\<longrightarrow> A \\<subseteq> N \\<longrightarrow> (m1 A) = 0)) \\<and>\n    ((\\<forall>A \\<in> sets M. m1 A < \\<infinity>) \\<or> (\\<forall>A \\<in> sets M. m2 A < \\<infinity>)))\"\n\nlemma jordan_decomp_pos_meas:\n  assumes \"jordan_decomp m1 m2\"\n    and \"hahn_space_decomp P N\"\n    and \"A \\<in> sets M\"\n  shows \"m1 A = \\<mu> (A \\<inter> P)\" \nproof -\n  have \"A\\<inter>P \\<in> sets M\" using assms unfolding hahn_space_decomp_def\n    by (simp add: pos_meas_setD1 sets.Int)\n  have \"A\\<inter> N \\<in> sets M\" using assms unfolding hahn_space_decomp_def\n    by (simp add: neg_meas_setD1 sets.Int)\n  have \"(A \\<inter> P) \\<inter> (A\\<inter> N) = {}\" using assms unfolding hahn_space_decomp_def \n    by auto\n  have \"A = (A \\<inter> P) \\<union> (A\\<inter> N)\" using assms unfolding hahn_space_decomp_def\n    by (metis Int_Un_distrib sets.Int_space_eq2)\n  hence \"m1 A = m1 ((A \\<inter> P) \\<union> (A\\<inter> N))\" by simp\n  also have \"... = m1 (A \\<inter> P) + m1 (A \\<inter> N)\" \n    using assms pos_e2ennreal_additive[of M m1] \\<open>A\\<inter>P \\<in> sets M\\<close> \\<open>A\\<inter>N \\<in> sets M\\<close> \n      \\<open>A \\<inter> P \\<inter> (A \\<inter> N) = {}\\<close> \n    unfolding jordan_decomp_def additive_def by simp\n  also have \"... = m1 (A \\<inter> P)\" using assms unfolding jordan_decomp_def\n    by (metis Int_lower2 \\<open>A \\<inter> N \\<in> sets M\\<close> add.right_neutral)\n  also have \"... = m1 (A \\<inter> P) - m2 (A \\<inter> P)\" \n    using assms unfolding jordan_decomp_def\n    by (metis Int_subset_iff \\<open>A \\<inter> P \\<in> sets M\\<close> ereal_minus(7) \n        local.pos_wtn_base pos_wtn_subset)\n  also have \"... = \\<mu> (A \\<inter> P)\" using assms \\<open>A \\<inter> P \\<in> sets M\\<close> \n    unfolding jordan_decomp_def by simp\n  finally show ?thesis .\nqed\n\nlemma jordan_decomp_neg_meas:\n  assumes \"jordan_decomp m1 m2\"\n    and \"hahn_space_decomp P N\"\n    and \"A \\<in> sets M\"\n  shows \"m2 A = -\\<mu> (A \\<inter> N)\" \nproof -\n  have \"A\\<inter>P \\<in> sets M\" using assms unfolding hahn_space_decomp_def\n    by (simp add: pos_meas_setD1 sets.Int)\n  have \"A\\<inter> N \\<in> sets M\" using assms unfolding hahn_space_decomp_def\n    by (simp add: neg_meas_setD1 sets.Int)\n  have \"(A \\<inter> P) \\<inter> (A\\<inter> N) = {}\" \n    using assms unfolding hahn_space_decomp_def by auto\n  have \"A = (A \\<inter> P) \\<union> (A\\<inter> N)\" \n    using assms unfolding hahn_space_decomp_def\n    by (metis Int_Un_distrib sets.Int_space_eq2)\n  hence \"m2 A = m2 ((A \\<inter> P) \\<union> (A\\<inter> N))\" by simp\n  also have \"... = m2 (A \\<inter> P) + m2 (A \\<inter> N)\" \n    using pos_e2ennreal_additive[of M m2] assms\n      \\<open>A\\<inter>P \\<in> sets M\\<close> \\<open>A\\<inter>N \\<in> sets M\\<close> \\<open>A \\<inter> P \\<inter> (A \\<inter> N) = {}\\<close> \n    unfolding jordan_decomp_def additive_def by simp\n  also have \"... = m2 (A \\<inter> N)\" using assms unfolding jordan_decomp_def\n    by (metis Int_lower2 \\<open>A \\<inter> P \\<in> sets M\\<close> add.commute add.right_neutral)\n  also have \"... = m2 (A \\<inter> N) - m1 (A \\<inter> N)\" \n    using assms unfolding jordan_decomp_def\n    by (metis Int_lower2 \\<open>A \\<inter> N \\<in> sets M\\<close> ereal_minus(7))\n  also have \"... = -\\<mu> (A \\<inter> N)\" using assms \\<open>A \\<inter> P \\<in> sets M\\<close> \n    unfolding jordan_decomp_def\n    by (metis Diff_cancel Diff_eq_empty_iff Int_Un_eq(2) \\<open>A \\<inter> N \\<in> sets M\\<close> \n        \\<open>m2 (A \\<inter> N) = m2 (A \\<inter> N) - m1 (A \\<inter> N)\\<close> ereal_minus(8) \n        ereal_uminus_eq_reorder sup.bounded_iff)\n  finally show ?thesis .\nqed\n\nlemma pos_inter_neg_0:\n  assumes \"hahn_space_decomp M1 M2\"\n    and \"hahn_space_decomp P N\"\n    and \"A \\<in> sets M\"\n    and \"A \\<subseteq> N\"\n  shows \"\\<mu> (A \\<inter> M1) = 0\"\nproof -\n  have \"\\<mu> (A \\<inter> M1) = \\<mu> (A \\<inter> ((M1 \\<inter> P) \\<union> (M1 \\<inter> (sym_diff M1 P))))\"\n    by (metis Diff_subset_conv Int_Un_distrib Un_upper1 inf.orderE)\n  also have \"... = \\<mu> ((A \\<inter> (M1 \\<inter> P)) \\<union> (A \\<inter> (M1 \\<inter> (sym_diff M1 P))))\" \n    by (simp add: Int_Un_distrib) \n  also have \"... = \\<mu> (A \\<inter> (M1 \\<inter> P)) + \\<mu> (A \\<inter> (M1 \\<inter> (sym_diff M1 P)))\" \n  proof (rule signed_measure_add)\n    show \"signed_measure M \\<mu>\" using sgn_meas .\n    show \"A \\<inter> (M1 \\<inter> P) \\<in> sets M\"\n      by (meson assms(1) assms(2) assms(3) hahn_space_decomp_def sets.Int \n          signed_measure_space.pos_meas_setD1 signed_measure_space_axioms) \n    show \"A \\<inter> (M1 \\<inter> sym_diff M1 P) \\<in> sets M\"\n      by (meson Diff_subset assms(1) assms(2) assms(3) hahn_space_decomp_def \n          pos_meas_setD1 pos_meas_set_union pos_meas_subset sets.Diff sets.Int)\n    show \"A \\<inter> (M1 \\<inter> P) \\<inter> (A \\<inter> (M1 \\<inter> sym_diff M1 P)) = {}\" by auto\n  qed\n  also have \"... = \\<mu> (A \\<inter> (M1 \\<inter> (sym_diff M1 P)))\"\n  proof -\n    have \"A \\<inter> (M1 \\<inter> P) = {}\" using assms hahn_space_decomp_def by auto\n    thus ?thesis using signed_measure_empty[OF sgn_meas] by simp\n  qed\n  also have \"... = 0\" \n  proof (rule hahn_decomp_ess_unique[OF assms(1) assms(2)]) \n    show \"A \\<inter> (M1 \\<inter> sym_diff M1 P) \\<subseteq> sym_diff M1 P \\<union> sym_diff M2 N\" by auto\n    show \"A \\<inter> (M1 \\<inter> sym_diff M1 P) \\<in> sets M\" \n    proof -\n      have \"sym_diff M1 P \\<in> sets M\" using assms\n        by (meson hahn_space_decomp_def sets.Diff sets.Un \n            signed_measure_space.pos_meas_setD1 signed_measure_space_axioms)\n      hence \"M1 \\<inter> sym_diff M1 P \\<in> sets M\"\n        by (meson assms(1) hahn_space_decomp_def pos_meas_setD1 sets.Int)\n      thus ?thesis by (simp add: assms sets.Int)\n    qed\n  qed\n  finally show ?thesis .\nqed\n\nlemma neg_inter_pos_0:\n  assumes \"hahn_space_decomp M1 M2\"\n    and \"hahn_space_decomp P N\"\n    and \"A \\<in> sets M\"\n    and \"A \\<subseteq> P\"\n  shows \"\\<mu> (A \\<inter> M2) = 0\"\nproof -\n  have \"\\<mu> (A \\<inter> M2) = \\<mu> (A \\<inter> ((M2 \\<inter> N) \\<union> (M2 \\<inter> (sym_diff M2 N))))\"\n    by (metis Diff_subset_conv Int_Un_distrib Un_upper1 inf.orderE)\n  also have \"... = \\<mu> ((A \\<inter> (M2 \\<inter> N)) \\<union> (A \\<inter> (M2 \\<inter> (sym_diff M2 N))))\" \n    by (simp add: Int_Un_distrib) \n  also have \"... = \\<mu> (A \\<inter> (M2 \\<inter> N)) + \\<mu> (A \\<inter> (M2 \\<inter> (sym_diff M2 N)))\" \n  proof (rule signed_measure_add)\n    show \"signed_measure M \\<mu>\" using sgn_meas .\n    show \"A \\<inter> (M2 \\<inter> N) \\<in> sets M\"\n      by (meson assms(1) assms(2) assms(3) hahn_space_decomp_def sets.Int \n          signed_measure_space.neg_meas_setD1 signed_measure_space_axioms) \n    show \"A \\<inter> (M2 \\<inter> sym_diff M2 N) \\<in> sets M\"\n      by (meson Diff_subset assms(1) assms(2) assms(3) hahn_space_decomp_def \n          neg_meas_setD1 neg_meas_set_union neg_meas_subset sets.Diff sets.Int)\n    show \"A \\<inter> (M2 \\<inter> N) \\<inter> (A \\<inter> (M2 \\<inter> sym_diff M2 N)) = {}\" by auto\n  qed\n  also have \"... = \\<mu> (A \\<inter> (M2 \\<inter> (sym_diff M2 N)))\"\n  proof -\n    have \"A \\<inter> (M2 \\<inter> N) = {}\" using assms hahn_space_decomp_def by auto\n    thus ?thesis using signed_measure_empty[OF sgn_meas] by simp\n  qed\n  also have \"... = 0\" \n  proof (rule hahn_decomp_ess_unique[OF assms(1) assms(2)]) \n    show \"A \\<inter> (M2 \\<inter> sym_diff M2 N) \\<subseteq> sym_diff M1 P \\<union> sym_diff M2 N\" by auto\n    show \"A \\<inter> (M2 \\<inter> sym_diff M2 N) \\<in> sets M\" \n    proof -\n      have \"sym_diff M2 N \\<in> sets M\" using assms\n        by (meson hahn_space_decomp_def sets.Diff sets.Un \n            signed_measure_space.neg_meas_setD1 signed_measure_space_axioms)\n      hence \"M2 \\<inter> sym_diff M2 N \\<in> sets M\"\n        by (meson assms(1) hahn_space_decomp_def neg_meas_setD1 sets.Int)\n      thus ?thesis by (simp add: assms sets.Int)\n    qed\n  qed\n  finally show ?thesis .\nqed\n\nlemma jordan_decomposition :\n  shows \"\\<exists> m1 m2. jordan_decomp m1 m2\" \nproof -\n  have \"\\<exists> M1 M2. hahn_space_decomp M1 M2\" using hahn_decomposition \n    unfolding hahn_space_decomp_def by simp\n  from this obtain M1 M2 where \"hahn_space_decomp M1 M2\" by auto \n  note Mprops = this\n  define m1 where \"m1 = (\\<lambda>A. \\<mu> (A \\<inter> M1))\"\n  define m2 where \"m2 = (\\<lambda>A. -\\<mu> (A \\<inter> M2))\"  \n  show ?thesis unfolding jordan_decomp_def\n  proof (intro exI allI impI conjI ballI)\n    show \"measure_space (space M) (sets M) (\\<lambda>x. e2ennreal (m1 x))\" \n      using pos_signed_to_meas_space Mprops m1_def \n      unfolding hahn_space_decomp_def by auto\n  next\n    show \"measure_space (space M) (sets M) (\\<lambda>x. e2ennreal (m2 x))\" \n      using neg_signed_to_meas_space Mprops m2_def \n      unfolding hahn_space_decomp_def by auto\n  next\n    fix A\n    assume \"A\\<in> sets M\"\n    thus \"0 \\<le> m1 A\" unfolding m1_def using Mprops \n      unfolding hahn_space_decomp_def \n      by (meson inf_sup_ord(2) pos_meas_setD1 sets.Int \n          signed_measure_space.pos_measure_meas signed_measure_space_axioms)\n  next\n    fix A \n    assume \"A\\<in> sets M\"\n    thus \"0 \\<le> m2 A\" unfolding m2_def using Mprops \n      unfolding hahn_space_decomp_def\n      by (metis ereal_0_le_uminus_iff inf_sup_ord(2) neg_meas_self \n          neg_meas_setD1 neg_meas_subset sets.Int)\n  next\n    fix A\n    assume \"A \\<in> sets M\"\n    have \"\\<mu> A = \\<mu> ((A \\<inter> M1) \\<union> (A \\<inter> M2))\" using Mprops \n      unfolding hahn_space_decomp_def\n      by (metis Int_Un_distrib \\<open>A \\<in> sets M\\<close> sets.Int_space_eq2)\n    also have \"... = \\<mu> (A \\<inter> M1) + \\<mu> (A \\<inter> M2)\" \n    proof (rule signed_measure_add)\n      show \"signed_measure M \\<mu>\" using sgn_meas .\n      show \"A \\<inter> M1 \\<in> sets M\" using Mprops  \\<open>A \\<in> sets M\\<close> \n        unfolding hahn_space_decomp_def \n        by (simp add: pos_meas_setD1 sets.Int) \n      show \"A \\<inter> M2 \\<in> sets M\" using Mprops \\<open>A \\<in> sets M\\<close> \n        unfolding hahn_space_decomp_def\n        by (simp add: neg_meas_setD1 sets.Int) \n      show \"A \\<inter> M1 \\<inter> (A \\<inter> M2) = {}\" using Mprops \n        unfolding hahn_space_decomp_def by auto\n    qed\n    also have \"... = m1 A - m2 A\" using m1_def m2_def by simp\n    finally show \"\\<mu> A = m1 A - m2 A\" .    \n  next\n    fix P N A\n    assume \"hahn_space_decomp P N\" and \"A \\<in> sets M\" and \"A \\<subseteq> N\" \n    note hn = this\n    have \"\\<mu> (A \\<inter> M1) = 0\"\n    proof (rule pos_inter_neg_0[OF _ hn])\n      show \"hahn_space_decomp M1 M2\" using Mprops \n        unfolding hahn_space_decomp_def by simp\n    qed\n    thus \"m1 A = 0\" unfolding m1_def by simp\n  next\n    fix P N A\n    assume \"hahn_space_decomp P N\" and \"A \\<in> sets M\" and \"A \\<subseteq> P\" \n    note hp = this\n    have \"\\<mu> (A \\<inter> M2) = 0\"\n    proof (rule neg_inter_pos_0[OF _ hp])\n      show \"hahn_space_decomp M1 M2\" using Mprops \n        unfolding hahn_space_decomp_def by simp\n    qed\n    thus \"m2 A = 0\" unfolding m2_def by simp\n  next\n    show \"(\\<forall>E\\<in>sets M. m1 E < \\<infinity>) \\<or> (\\<forall>E\\<in>sets M. m2 E < \\<infinity>)\"\n    proof (cases \"\\<forall> E \\<in> sets M. m1 E < \\<infinity>\")\n      case True\n      thus ?thesis by simp\n    next\n      case False\n      have \"\\<forall> E \\<in> sets M. m2 E < \\<infinity>\"\n      proof\n        fix E\n        assume \"E \\<in> sets M\"\n        show \"m2 E < \\<infinity>\"\n        proof -\n          have \"(m2 E) = -\\<mu> (E \\<inter> M2)\" using m2_def by simp        \n          also have \"... \\<noteq> \\<infinity>\" using False sgn_meas inf_range\n            by (metis ereal_less_PInfty ereal_uminus_uminus m1_def rangeI)\n          finally have \"m2 E \\<noteq> \\<infinity>\" .\n          thus ?thesis by (simp add: top.not_eq_extremum)\n        qed\n      qed\n      thus ?thesis by simp\n    qed\n  qed\nqed\n\nlemma jordan_decomposition_unique :\n  assumes \"jordan_decomp m1 m2\" \n    and \"jordan_decomp n1 n2\"\n    and \"A \\<in> sets M\"\n  shows \"m1 A = n1 A\" \"m2 A = n2 A\"\nproof -\n  have \"\\<exists> M1 M2. hahn_space_decomp M1 M2\" using hahn_decomposition by simp\n  from this obtain M1 M2 where \"hahn_space_decomp M1 M2\" by auto \n  note mprop = this\n  have \"m1 A = \\<mu> (A \\<inter> M1)\" using assms jordan_decomp_pos_meas mprop by simp\n  also have \"... = n1 A\" using assms jordan_decomp_pos_meas[of n1] mprop \n    by simp\n  finally show \"m1 A = n1 A\" .\n  have \"m2 A = -\\<mu> (A \\<inter> M2)\" using assms jordan_decomp_neg_meas mprop by simp\n  also have \"... = n2 A\" using assms jordan_decomp_neg_meas[of n1] mprop \n    by simp\n  finally show \"m2 A = n2 A\" .\nqed\nend\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/Hahn_Jordan_Decomposition/Hahn_Jordan_Decomposition.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8418256472515683, "lm_q2_score": 0.847967764140929, "lm_q1q2_score": 0.7138410118964027}}
{"text": "subsection \"Factorization\"\n\ntheory Finite_Fields_Factorization_Ext\n  imports Finite_Fields_Preliminary_Results\nbegin\n\ntext \\<open>This section contains additional results building on top of the development in\n@{theory \"HOL-Algebra.Divisibility\"} about factorization in a @{locale \"factorial_monoid\"}.\\<close>\n\ndefinition factor_mset where \"factor_mset G x = \n  (THE f. (\\<exists> as. f = fmset G as \\<and> wfactors G as x \\<and> set as \\<subseteq> carrier G))\"\n\ntext \\<open>In @{theory \"HOL-Algebra.Divisibility\"} it is already verified that the multiset representing\nthe factorization of an element of a factorial monoid into irreducible factors is well-defined.\nWith these results it is then possible to define @{term \"factor_mset\"} and show its properties,\nwithout referring to a factorization in list form first.\\<close>\n\ndefinition multiplicity where\n  \"multiplicity G d g = Max {(n::nat). (d [^]\\<^bsub>G\\<^esub> n) divides\\<^bsub>G\\<^esub> g}\"\n\ndefinition canonical_irreducibles where \n  \"canonical_irreducibles G A = (\n    A \\<subseteq> {a. a \\<in> carrier G \\<and> irreducible G a} \\<and>\n    (\\<forall>x y. x \\<in> A \\<longrightarrow> y \\<in> A \\<longrightarrow> x \\<sim>\\<^bsub>G\\<^esub> y \\<longrightarrow> x = y) \\<and>\n    (\\<forall>x \\<in> carrier G. irreducible G x \\<longrightarrow> (\\<exists>y \\<in> A. x \\<sim>\\<^bsub>G\\<^esub> y)))\"\n\ntext \\<open>A set of irreducible elements that contains exactly one element from each equivalence class\nof an irreducible element formed by association, is called a set of \n@{term \"canonical_irreducibles\"}. An example is the set of monic irreducible polynomials as\nrepresentatives of all irreducible polynomials.\\<close>\n\ncontext factorial_monoid\nbegin\n\nlemma assoc_as_fmset_eq:\n  assumes \"wfactors G as a\"\n    and \"wfactors G bs b\"\n    and \"a \\<in> carrier G\"\n    and \"b \\<in> carrier G\"\n    and \"set as \\<subseteq> carrier G\"\n    and \"set bs \\<subseteq> carrier G\"\n  shows \"a \\<sim> b \\<longleftrightarrow> (fmset G as = fmset G bs)\"\nproof -\n  have \"a \\<sim> b \\<longleftrightarrow> (a divides b \\<and> b divides a)\"\n    by (simp add:associated_def)\n  also have \"... \\<longleftrightarrow> \n    (fmset G as \\<subseteq># fmset G bs \\<and> fmset G bs \\<subseteq># fmset G as)\"\n    using divides_as_fmsubset assms by blast\n  also have \"... \\<longleftrightarrow> (fmset G as = fmset G bs)\" by auto\n  finally show ?thesis by simp\nqed\n\nlemma factor_mset_aux_1:\n  assumes \"a \\<in> carrier G\" \"set as \\<subseteq> carrier G\" \"wfactors G as a\"\n  shows \"factor_mset G a = fmset G as\"\nproof -\n  define H where \"H = {as. wfactors G as a \\<and> set as \\<subseteq> carrier G}\"\n  have b:\"as \\<in> H\"\n    using H_def assms by simp\n\n  have c: \"x \\<in> H \\<Longrightarrow> y \\<in> H \\<Longrightarrow> fmset G x = fmset G y\" for x y\n    unfolding H_def using assoc_as_fmset_eq \n    using associated_refl assms by blast \n\n  have \"factor_mset G a = (THE f. \\<exists>as \\<in> H. f= fmset G as)\"\n    by (simp add:factor_mset_def H_def, metis) \n\n  also have \"... = fmset G as\"\n    using b c\n    by (intro the1_equality) blast+\n  finally have \"factor_mset G a = fmset G as\" by simp\n\n  thus ?thesis\n    using b unfolding H_def by auto\nqed\n\nlemma factor_mset_aux:\n  assumes \"a \\<in> carrier G\"\n  shows \"\\<exists>as. factor_mset G a = fmset G as \\<and> wfactors G as a \\<and> \n    set as \\<subseteq> carrier G\"\nproof -\n  obtain as where as_def: \"wfactors G as a\" \"set as \\<subseteq> carrier G\"\n    using wfactors_exist assms by blast\n  thus ?thesis using factor_mset_aux_1 assms by blast\nqed\n\nlemma factor_mset_set:\n  assumes \"a \\<in> carrier G\"\n  assumes \"x \\<in># factor_mset G a\" \n  obtains y where \n    \"y \\<in> carrier G\" \n    \"irreducible G y\" \n    \"assocs G y = x\" \nproof -\n  obtain as where as_def: \n    \"factor_mset G a = fmset G as\" \n    \"wfactors G as a\" \"set as \\<subseteq> carrier G\"\n    using factor_mset_aux assms by blast\n  hence \"x \\<in># fmset G as\"\n    using assms by simp\n  hence \"x \\<in> assocs G ` set as\"\n    using assms as_def by (simp add:fmset_def)\n  hence \"\\<exists>y. y \\<in> set as \\<and> x = assocs G y\"\n    by auto\n  moreover have \"y \\<in> carrier G \\<and> irreducible G y\" \n    if \"y \\<in> set as\" for y\n    using as_def that wfactors_def\n    by (simp add: wfactors_def) auto\n  ultimately show ?thesis\n    using that by blast\nqed\n\nlemma factor_mset_mult:\n  assumes \"a \\<in> carrier G\" \"b \\<in> carrier G\"\n  shows \"factor_mset G (a \\<otimes> b) = factor_mset G a + factor_mset G b\"\nproof -\n  obtain as where as_def: \n    \"factor_mset G a = fmset G as\" \n    \"wfactors G as a\" \"set as \\<subseteq> carrier G\"\n    using factor_mset_aux assms by blast\n  obtain bs where bs_def: \n    \"factor_mset G b = fmset G bs\" \n    \"wfactors G bs b\" \"set bs \\<subseteq> carrier G\"\n    using factor_mset_aux assms(2) by blast\n  have \"a \\<otimes> b \\<in> carrier G\" using assms by auto\n  then obtain cs where cs_def:\n    \"factor_mset G (a \\<otimes> b) = fmset G cs\" \n    \"wfactors G cs (a \\<otimes> b)\" \n    \"set cs \\<subseteq> carrier G\"\n    using factor_mset_aux assms by blast\n  have \"fmset G cs = fmset G as + fmset G bs\"\n    using as_def bs_def cs_def assms \n    by (intro  mult_wfactors_fmset[where a=\"a\" and b=\"b\"]) auto\n  thus ?thesis\n    using as_def bs_def cs_def by auto\nqed\n\nlemma factor_mset_unit: \"factor_mset G \\<one> = {#}\"\nproof -\n  have \"factor_mset G \\<one> = factor_mset G (\\<one> \\<otimes> \\<one>)\"\n    by simp\n  also have \"... = factor_mset G \\<one> + factor_mset G \\<one>\"\n    by (intro factor_mset_mult, auto)\n  finally show \"factor_mset G \\<one> = {#}\"\n    by simp\nqed\n\nlemma factor_mset_irred: \n  assumes \"x \\<in> carrier G\" \"irreducible G x\"\n  shows \"factor_mset G x = image_mset (assocs G) {#x#}\"\nproof -\n  have \"wfactors G [x] x\"\n    using assms by (simp add:wfactors_def)\n  hence \"factor_mset G x = fmset G [x]\"\n    using factor_mset_aux_1 assms by simp\n  also have \"... = image_mset (assocs G) {#x#}\"\n    by (simp add:fmset_def)\n  finally show ?thesis by simp\nqed\n\nlemma factor_mset_divides:\n  assumes \"a \\<in> carrier G\" \"b \\<in> carrier G\"\n  shows \"a divides b \\<longleftrightarrow> factor_mset G a \\<subseteq># factor_mset G b\"\nproof -\n  obtain as where as_def: \n    \"factor_mset G a = fmset G as\" \n    \"wfactors G as a\" \"set as \\<subseteq> carrier G\"\n    using factor_mset_aux assms by blast\n  obtain bs where bs_def: \n    \"factor_mset G b = fmset G bs\" \n    \"wfactors G bs b\" \"set bs \\<subseteq> carrier G\"\n    using factor_mset_aux assms(2) by blast\n  hence \"a divides b \\<longleftrightarrow> fmset G as \\<subseteq># fmset G bs\"\n    using as_def bs_def assms\n    by (intro divides_as_fmsubset) auto\n  also have \"... \\<longleftrightarrow> factor_mset G a \\<subseteq># factor_mset G b\"\n    using as_def bs_def by simp\n  finally show ?thesis by simp\nqed\n\nlemma factor_mset_sim:\n  assumes \"a \\<in> carrier G\" \"b \\<in> carrier G\"\n  shows \"a \\<sim> b \\<longleftrightarrow> factor_mset G a = factor_mset G b\"\n  using factor_mset_divides assms\n  by (simp add:associated_def) auto\n\nlemma factor_mset_prod:\n  assumes \"finite A\"\n  assumes \"f ` A \\<subseteq> carrier G\" \n  shows \"factor_mset G (\\<Otimes>a \\<in> A. f a) = \n    (\\<Sum>a \\<in> A. factor_mset G (f a))\"\n  using assms\nproof (induction A rule:finite_induct)\n  case empty\n  then show ?case by (simp add:factor_mset_unit)\nnext\n  case (insert x F)\n  have \"factor_mset G (finprod G f (insert x F)) = \n    factor_mset G (f x \\<otimes> finprod G f F)\"\n    using insert by (subst finprod_insert) auto\n  also have \"... = factor_mset G (f x) + factor_mset G (finprod G f F)\"\n    using insert by (intro factor_mset_mult finprod_closed) auto\n  also have \n    \"... = factor_mset G (f x) + (\\<Sum>a \\<in> F. factor_mset G (f a))\"\n    using insert by simp\n  also have \"... = (\\<Sum>a\\<in>insert x F. factor_mset G (f a))\"\n    using insert by simp\n  finally show ?case by simp\nqed\n\nlemma factor_mset_pow:\n  assumes \"a \\<in> carrier G\"\n  shows \"factor_mset G (a [^] n) = repeat_mset n (factor_mset G a)\"\nproof (induction n)\n  case 0\n  then show ?case by (simp add:factor_mset_unit)\nnext\n  case (Suc n)\n  have \"factor_mset G (a [^] Suc n) = factor_mset G (a [^] n \\<otimes> a)\"\n    by simp\n  also have \"... = factor_mset G (a [^] n) + factor_mset G a\"\n    using assms by (intro factor_mset_mult) auto\n  also have \"... = repeat_mset n (factor_mset G a) + factor_mset G a\"\n    using Suc by simp\n  also have \"... = repeat_mset (Suc n) (factor_mset G a)\"\n    by simp\n  finally show ?case by simp\nqed\n\nlemma image_mset_sum:\n  assumes \"finite F\"\n  shows \n    \"image_mset h (\\<Sum>x \\<in> F. f x) = (\\<Sum>x \\<in> F. image_mset h (f x))\"\n  using assms\n  by (induction F rule:finite_induct, simp, simp)\n\nlemma decomp_mset: \n  \"(\\<Sum>x\\<in>set_mset R. replicate_mset (count R x) x) = R\"\n  by (rule multiset_eqI, simp add:count_sum count_eq_zero_iff)\n\nlemma factor_mset_count:\n  assumes \"a \\<in> carrier G\" \"d \\<in> carrier G\" \"irreducible G d\"\n  shows \"count (factor_mset G a) (assocs G d) = multiplicity G d a\"\nproof -\n  have a: \n    \"count (factor_mset G a) (assocs G d) \\<ge> m \\<longleftrightarrow> d [^] m divides a\"\n    (is \"?lhs \\<longleftrightarrow> ?rhs\") for m\n  proof -\n    have \"?lhs \\<longleftrightarrow> replicate_mset m (assocs G d) \\<subseteq># factor_mset G a\"\n      by (simp add:count_le_replicate_mset_subset_eq)\n    also have \"... \\<longleftrightarrow> factor_mset G (d [^] m) \\<subseteq># factor_mset G a\"\n      using assms(2,3) by (simp add:factor_mset_pow factor_mset_irred)\n    also have \"... \\<longleftrightarrow> ?rhs\"\n      using assms(1,2) by (subst factor_mset_divides) auto\n    finally show ?thesis by simp\n  qed\n\n  define M where \"M = {(m::nat). d [^] m divides a}\"\n\n  have M_alt: \"M = {m. m \\<le> count (factor_mset G a) (assocs G d)}\"\n    using a by (simp add:M_def)\n\n  hence \"Max M = count (factor_mset G a) (assocs G d)\"\n    by (intro Max_eqI, auto)\n  thus ?thesis\n    unfolding multiplicity_def M_def by auto\nqed\n\nlemma multiplicity_ge_iff:\n  assumes \"d \\<in> carrier G\" \"irreducible G d\" \"a \\<in> carrier G\"\n  shows \"multiplicity G d a \\<ge> k \\<longleftrightarrow> d [^] k divides a\" \n    (is \"?lhs \\<longleftrightarrow> ?rhs\")\nproof -\n  have \"?lhs \\<longleftrightarrow> count (factor_mset G a) (assocs G d) \\<ge> k\"\n    using factor_mset_count[OF assms(3,1,2)] by simp\n  also have \"... \\<longleftrightarrow> replicate_mset k (assocs G d) \\<subseteq># factor_mset G a\"\n    by (subst count_le_replicate_mset_subset_eq, simp) \n  also have \"... \\<longleftrightarrow>\n    repeat_mset k (factor_mset G d) \\<subseteq># factor_mset G a\" \n    by (subst factor_mset_irred[OF assms(1,2)], simp)\n  also have \"... \\<longleftrightarrow> factor_mset G (d [^]\\<^bsub>G\\<^esub> k) \\<subseteq># factor_mset G a\" \n    by (subst factor_mset_pow[OF assms(1)], simp)\n  also have \"... \\<longleftrightarrow> (d [^] k) divides\\<^bsub>G\\<^esub> a\"\n    using assms(1) factor_mset_divides[OF _ assms(3)] by simp\n  finally show ?thesis by simp\nqed\n\nlemma multiplicity_gt_0_iff:\n  assumes \"d \\<in> carrier G\" \"irreducible G d\" \"a \\<in> carrier G\"\n  shows \"multiplicity G d a > 0 \\<longleftrightarrow> d divides a\"\n  using multiplicity_ge_iff[OF assms(1,2,3), where k=\"1\"] assms\n  by auto\n\nlemma factor_mset_count_2:\n  assumes \"a \\<in> carrier G\" \n  assumes \"\\<And>z. z \\<in> carrier G \\<Longrightarrow> irreducible G z \\<Longrightarrow> y \\<noteq> assocs G z\"\n  shows \"count (factor_mset G a) y = 0\"\n  using factor_mset_set [OF assms(1)] assms(2) by (metis count_inI)\n\nlemma factor_mset_choose:\n  assumes \"a \\<in> carrier G\" \"set_mset R \\<subseteq> carrier G\"\n  assumes \"image_mset (assocs G) R = factor_mset G a\" \n  shows \"a \\<sim> (\\<Otimes>x\\<in>set_mset R. x [^] count R x)\" (is \"a \\<sim> ?rhs\")\nproof -\n  have b:\"irreducible G x\" if a:\"x \\<in># R\" for x\n  proof -\n    have x_carr: \"x \\<in> carrier G\" \n      using a assms(2) by auto\n    have \"assocs G x \\<in> assocs G ` set_mset R\"\n      using a by simp\n    hence \"assocs G x \\<in># factor_mset G a\"\n      using assms(3) a in_image_mset by metis\n    then obtain z where z_def: \n      \"z \\<in> carrier G\" \"irreducible G z\" \"assocs G x = assocs G z\"\n      using factor_mset_set assms(1) by metis\n    have \"z \\<sim> x\" using z_def(1,3) assocs_eqD x_carr by simp \n    thus ?thesis using z_def(1,2) x_carr irreducible_cong by simp\n  qed\n\n  have \"factor_mset G ?rhs = \n    (\\<Sum>x\\<in>set_mset R. factor_mset G (x [^] count R x))\"\n    using assms(2) by (subst factor_mset_prod, auto) \n  also have \"... = \n    (\\<Sum>x\\<in>set_mset R. repeat_mset (count R x) (factor_mset G x))\"\n    using assms(2) by (intro sum.cong, auto simp add:factor_mset_pow)\n  also have \"... = (\\<Sum>x\\<in>set_mset R. \n    repeat_mset (count R x) (image_mset (assocs G) {#x#}))\"\n    using assms(2) b by (intro sum.cong, auto simp add:factor_mset_irred)\n  also have \"... = (\\<Sum>x\\<in>set_mset R. \n    image_mset (assocs G) (replicate_mset (count R x) x))\"\n    by simp\n  also have \"... = image_mset (assocs G) \n    (\\<Sum>x\\<in>set_mset R. (replicate_mset (count R x) x))\"\n    by (simp add: image_mset_sum)\n  also have \"... = image_mset (assocs G) R\"\n    by (simp add:decomp_mset)\n  also have \"... = factor_mset G a\"\n    using assms by simp\n  finally have \"factor_mset G ?rhs = factor_mset G a\" by simp\n  moreover have \"(\\<Otimes>x\\<in>set_mset R. x [^] count R x) \\<in> carrier G\"\n    using assms(2) by (intro finprod_closed, auto)\n  ultimately show ?thesis \n    using assms(1) by (subst factor_mset_sim) auto\nqed\n\nlemma divides_iff_mult_mono:\n  assumes \"a \\<in> carrier G\" \"b \\<in> carrier G\" \n  assumes \"canonical_irreducibles G R\"\n  assumes \"\\<And>d. d \\<in> R \\<Longrightarrow> multiplicity G d a \\<le> multiplicity G d b\"\n  shows \"a divides b\"\nproof -\n  have \"count (factor_mset G a) d \\<le> count (factor_mset G b) d\" for d\n  proof (cases \"\\<exists>y \\<in> carrier G. irreducible G y \\<and> d = assocs G y\")\n    case True\n    then obtain y where y_def: \n      \"irreducible G y\" \"y \\<in> carrier G\" \"d = assocs G y\"\n      by blast\n    then obtain z where z_def: \"z \\<in> R\" \"y \\<sim> z\"\n      using assms(3) unfolding canonical_irreducibles_def by metis\n    have z_more: \"irreducible G z\" \"z \\<in> carrier G\"\n      using z_def(1) assms(3)\n      unfolding canonical_irreducibles_def by auto\n    have \"y \\<in> assocs G z\" using z_def(2) z_more(2) y_def(2) \n      by (simp add: closure_ofI2)\n    hence d_def: \"d = assocs G z\"\n      using y_def(2,3) z_more(2) assocs_repr_independence\n      by blast\n    have \"count (factor_mset G a) d = multiplicity G z a\"\n      unfolding d_def\n      by (intro factor_mset_count[OF assms(1) z_more(2,1)])\n    also have \"... \\<le> multiplicity G z b\"\n      using assms(4) z_def(1) by simp\n    also have \"... = count (factor_mset G b) d\"\n      unfolding d_def\n      by (intro factor_mset_count[symmetric, OF assms(2) z_more(2,1)])\n    finally show ?thesis by simp \n  next\n    case False\n    have \"count (factor_mset G a) d = 0\" using False\n      by (intro factor_mset_count_2[OF assms(1)], simp)\n    moreover have \"count (factor_mset G b) d = 0\" using False\n      by (intro factor_mset_count_2[OF assms(2)], simp)\n    ultimately show ?thesis by simp\n  qed\n\n  hence \"factor_mset G a \\<subseteq># factor_mset G b\" \n    unfolding subseteq_mset_def by simp\n  thus ?thesis using factor_mset_divides assms(1,2) by simp\nqed\n\nlemma count_image_mset_inj:\n  assumes \"inj_on f R\" \"x \\<in> R\" \"set_mset A \\<subseteq> R\"\n  shows \"count (image_mset f A) (f x) = count A x\"\nproof (cases \"x \\<in># A\")\n  case True\n  hence \"(f y = f x \\<and> y \\<in># A) = (y = x)\" for y \n    by (meson assms(1) assms(3) inj_onD subsetD)\n  hence \"(f -` {f x} \\<inter> set_mset A) = {x}\" \n    by (simp add:set_eq_iff)\n  thus ?thesis\n    by (subst count_image_mset, simp)\nnext\n  case False\n  hence \"x \\<notin> set_mset A\" by simp\n  hence \"f x \\<notin> f ` set_mset A\" using assms\n    by (simp add: inj_on_image_mem_iff)\n  hence \"count (image_mset f A) (f x) = 0\" \n    by (simp add:count_eq_zero_iff)\n  thus ?thesis by (metis count_inI False)\nqed\n\ntext \\<open>Factorization of an element from a @{locale \"factorial_monoid\"} using a selection of representatives \nfrom each equivalence class formed by @{term \"(\\<sim>)\"}.\\<close>\n\nlemma split_factors:\n  assumes \"canonical_irreducibles G R\"\n  assumes \"a \\<in> carrier G\"\n  shows \n    \"finite {d. d \\<in> R \\<and> multiplicity G d a > 0}\"\n    \"a \\<sim> (\\<Otimes>d\\<in>{d. d \\<in> R \\<and> multiplicity G d a > 0}. \n          d [^] multiplicity G d a)\" (is \"a \\<sim> ?rhs\")\nproof -\n  have r_1: \"R \\<subseteq> {x. x \\<in> carrier G \\<and> irreducible G x}\" \n    using assms(1) unfolding canonical_irreducibles_def by simp\n  have r_2: \"\\<And>x y. x \\<in> R \\<Longrightarrow> y \\<in> R \\<Longrightarrow> x \\<sim> y \\<Longrightarrow> x = y\" \n    using assms(1) unfolding canonical_irreducibles_def by simp\n  \n  have assocs_inj: \"inj_on (assocs G) R\"\n    using r_1 r_2 assocs_eqD by (intro inj_onI, blast) \n  \n  define R' where\n    \"R' = (\\<Sum>d\\<in> {d. d \\<in> R \\<and> multiplicity G d a > 0}.\n    replicate_mset (multiplicity G d a) d)\"\n\n  have \"count (factor_mset G a) (assocs G x) > 0\" \n    if \"x \\<in> R\" \"0 < multiplicity G x a\" for x\n    using assms r_1 r_2 that\n    by (subst factor_mset_count[OF assms(2)]) auto\n  hence \"assocs G ` {d \\<in> R. 0 < multiplicity G d a} \n    \\<subseteq> set_mset (factor_mset G a)\"\n    by (intro image_subsetI, simp)\n  hence a:\"finite (assocs G ` {d \\<in> R. 0 < multiplicity G d a})\"\n    using finite_subset by auto\n\n  show \"finite {d \\<in> R. 0 < multiplicity G d a}\" \n    using assocs_inj inj_on_subset[OF assocs_inj]\n    by (intro finite_imageD[OF a], simp)\n\n  hence count_R': \n    \"count R' d = (if d \\<in> R then multiplicity G d a else 0)\"\n    for d\n    by (auto simp add:R'_def count_sum) \n\n  have set_R': \"set_mset R' = {d \\<in> R. 0 < multiplicity G d a}\"\n    unfolding set_mset_def using count_R' by auto\n\n  have \"count (image_mset (assocs G) R') x = \n    count (factor_mset G a) x\" for x\n  proof (cases \"\\<exists>x'. x' \\<in> R \\<and> x = assocs G x'\")\n    case True\n    then obtain x' where x'_def: \"x' \\<in> R\" \"x = assocs G x'\"\n      by blast\n    have \"count (image_mset (assocs G) R') x = count R' x'\"\n      using assocs_inj inj_on_subset[OF assocs_inj] x'_def\n      by (subst x'_def(2), subst count_image_mset_inj[OF assocs_inj])\n        (auto simp:set_R') \n    also have \"... = multiplicity G x' a\"\n      using count_R' x'_def by simp\n    also have \"... = count (factor_mset G a) (assocs G x')\"\n      using x'_def(1) r_1\n      by (subst factor_mset_count[OF assms(2)]) auto\n    also have \"... = count (factor_mset G a) x\"\n      using x'_def(2) by simp\n    finally show ?thesis by simp\n  next\n    case False\n    have a:\"x \\<noteq> assocs G z\" \n      if a1: \"z \\<in> carrier G\" and a2: \"irreducible G z\" for z\n    proof -\n      obtain v where v_def: \"v \\<in> R\" \"z \\<sim> v\"\n        using a1 a2 assms(1)\n        unfolding canonical_irreducibles_def by auto\n      hence \"z \\<in> assocs G v\"\n        using a1 r_1 v_def(1) by (simp add: closure_ofI2)\n      hence \"assocs G z = assocs G v\"\n        using a1 r_1 v_def(1)  assocs_repr_independence\n        by auto\n      moreover have \"x \\<noteq> assocs G v\"\n        using False v_def(1) by simp\n      ultimately show ?thesis by simp\n    qed\n\n    have \"count (image_mset (assocs G) R') x = 0\"\n      using False count_R' by (simp add: count_image_mset) auto\n    also have \"... = count (factor_mset G a) x\"\n      using a\n      by (intro factor_mset_count_2[OF assms(2), symmetric]) auto \n    finally show ?thesis by simp\n  qed\n\n  hence \"image_mset (assocs G) R' = factor_mset G a\"\n    by (rule multiset_eqI)\n\n  moreover have \"set_mset R' \\<subseteq> carrier G\" \n    using r_1 by (auto simp add:set_R') \n  ultimately have \"a \\<sim> (\\<Otimes>x\\<in>set_mset R'. x [^] count R' x)\"\n    using assms(2) by (intro factor_mset_choose, auto)\n  also have \"... = ?rhs\"\n    using set_R' assms r_1 r_2\n    by (intro finprod_cong', auto simp add:count_R')\n  finally show \"a \\<sim> ?rhs\" by simp\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/Finite_Fields/Finite_Fields_Factorization_Ext.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8418256313782277, "lm_q2_score": 0.8479677583778258, "lm_q1q2_score": 0.7138409935847937}}
{"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.*)\n  theory TIP_prop_48\n  imports \"../../Test_Base\"\nbegin\n\ndatatype 'a list = nil2 | cons2 \"'a\" \"'a list\"\n\ndatatype Nat = Z | S \"Nat\"\n\nfun length :: \"'a list => Nat\" where\n  \"length (nil2) = Z\"\n| \"length (cons2 y xs) = S (length xs)\"\n\nfun t2 :: \"Nat => Nat => bool\" where\n  \"t2 (Z) y = True\"\n| \"t2 (S z) (Z) = False\"\n| \"t2 (S z) (S x2) = t2 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 t2 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  \"((length (isort x)) = (length x))\"\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/Prod/Prod/TIP_prop_48.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887588052782737, "lm_q2_score": 0.8031737963569016, "lm_q1q2_score": 0.7138277836809753}}
{"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_MSortBUSorts\n  imports \"../../Test_Base\"\nbegin\n\ndatatype 'a list = nil2 | cons2 \"'a\" \"'a list\"\n\ndatatype Nat = Z | S \"Nat\"\n\nfun map :: \"('a => 'b) => 'a list => 'b list\" where\n  \"map f (nil2) = nil2\"\n| \"map f (cons2 y xs) = cons2 (f y) (map f xs)\"\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 mergingbu :: \"(Nat list) list => Nat list\" where\n  \"mergingbu (nil2) = nil2\"\n| \"mergingbu (cons2 xs (nil2)) = xs\"\n| \"mergingbu (cons2 xs (cons2 z x2)) =\n     mergingbu (pairwise (cons2 xs (cons2 z x2)))\"\n  by pat_completeness auto\n\nfun msortbu :: \"Nat list => Nat list\" where\n  \"msortbu x = mergingbu (map (% (y :: Nat) => cons2 y (nil2)) x)\"\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\ntheorem property0 :\n  \"ordered (msortbu 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_MSortBUSorts.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887588023318195, "lm_q2_score": 0.8031737892899222, "lm_q1q2_score": 0.7138277750336204}}
{"text": "theory E2_9\n  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 itadd :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\" where\n  \"itadd 0 n = n\" |\n  \"itadd (Suc m) n = itadd m (Suc n)\"\n\nlemma add_help [simp] : \"add m (Suc n) = Suc (add m n)\"\n  apply(induction m)\n  apply(auto)\n  done\n\nlemma \"itadd m n = add m n\"\n  apply(induction m arbitrary: n)\n  apply(auto)\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_9.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8887587817066391, "lm_q2_score": 0.8031737987125612, "lm_q1q2_score": 0.7138277668424693}}
{"text": "(*  Title:       CartesianCategory\n    Author:      Eugene W. Stark <stark@cs.stonybrook.edu>, 2020\n    Maintainer:  Eugene W. Stark <stark@cs.stonybrook.edu>\n*)\n\nchapter \"Cartesian Category\"\n\ntext\\<open>\n  In this chapter, we explore the notion of a ``cartesian category'', which we define\n  to be a category having binary products and a terminal object.\n  We show that every cartesian category extends to an ``elementary cartesian category'',\n  whose definition assumes that specific choices have been made for projections and\n  terminal object.\n  Conversely, the underlying category of an elementary cartesian category is a\n  cartesian category.\n  We also show that cartesian categories are the same thing as categories with\n  finite products.\n\\<close>\n\ntheory CartesianCategory\nimports Limit SetCat CategoryWithPullbacks\nbegin\n\n  section \"Category with Binary Products\"\n\n  subsection \"Binary Product Diagrams\"\n\n  text \\<open>\n    The ``shape'' of a binary product diagram is a category having two distinct identity arrows\n    and no non-identity arrows.\n  \\<close>\n\n  locale binary_product_shape\n  begin\n\n    sublocale concrete_category \\<open>UNIV :: bool set\\<close> \\<open>\\<lambda>a b. if a = b then {()} else {}\\<close>\n                                \\<open>\\<lambda>_. ()\\<close> \\<open>\\<lambda>_ _ _ _ _. ()\\<close>\n      apply (unfold_locales, auto)\n       apply (meson empty_iff)\n      by (meson empty_iff)\n\n    abbreviation comp\n    where \"comp \\<equiv> COMP\"\n\n    abbreviation FF\n    where \"FF \\<equiv> MkIde False\"\n\n    abbreviation TT\n    where \"TT \\<equiv> MkIde True\"\n\n    lemma arr_char:\n    shows \"arr f \\<longleftrightarrow> f = FF \\<or> f = TT\"\n      using arr_char by (cases f, simp_all)\n\n    lemma ide_char:\n    shows \"ide f \\<longleftrightarrow> f = FF \\<or> f = TT\"\n      using ide_char\\<^sub>C\\<^sub>C ide_MkIde by (cases f, auto)\n\n    lemma is_discrete:\n    shows \"ide f \\<longleftrightarrow> arr f\"\n      using arr_char ide_char by simp\n\n    lemma dom_simp [simp]:\n    assumes \"arr f\"\n    shows \"dom f = f\"\n      using assms is_discrete by simp\n\n    lemma cod_simp [simp]:\n    assumes \"arr f\"\n    shows \"cod f = f\"\n      using assms is_discrete by simp\n\n    lemma seq_char:\n    shows \"seq f g \\<longleftrightarrow> arr f \\<and> f = g\"\n      by auto\n\n    lemma comp_simp [simp]:\n    assumes \"seq f g\"\n    shows \"comp f g = f\"\n      using assms seq_char by fastforce\n\n  end\n\n  locale binary_product_diagram =\n    J: binary_product_shape +\n    C: category C\n  for C :: \"'c comp\"      (infixr \"\\<cdot>\" 55)\n  and a0 :: 'c\n  and a1 :: 'c +\n  assumes is_discrete: \"C.ide a0 \\<and> C.ide a1\"\n  begin\n\n    notation J.comp      (infixr \"\\<cdot>\\<^sub>J\" 55)\n\n    fun map\n    where \"map J.FF = a0\"\n        | \"map J.TT = a1\"\n        | \"map _ = C.null\"\n\n    sublocale diagram J.comp C map\n    proof\n      show \"\\<And>f. \\<not> J.arr f \\<Longrightarrow> map f = C.null\"\n        using J.arr_char map.elims by auto\n      fix f\n      assume f: \"J.arr f\"\n      show \"C.arr (map f)\"\n        using f J.arr_char is_discrete C.ideD(1) map.simps(1-2) by metis\n      show \"C.dom (map f) = map (J.dom f)\"\n        using f J.arr_char J.dom_char is_discrete by force\n      show \"C.cod (map f) = map (J.cod f)\"\n        using f J.arr_char J.cod_char is_discrete by force\n      next\n      fix f g\n      assume fg: \"J.seq g f\"\n      show \"map (g \\<cdot>\\<^sub>J f) = map g \\<cdot> map f\"\n        using fg J.arr_char J.seq_char J.null_char J.not_arr_null is_discrete\n        by (metis (no_types, lifting) C.comp_ide_self J.comp_simp map.simps(1-2))\n    qed\n\n  end\n\n  subsection \"Category with Binary Products\"\n\n  text \\<open>\n    A \\emph{binary product} in a category @{term C} is a limit of a binary product diagram\n    in @{term C}.\n  \\<close>\n\n  context binary_product_diagram\n  begin\n\n    definition mkCone\n    where \"mkCone p0 p1 \\<equiv> \\<lambda>j. if j = J.FF then p0 else if j = J.TT then p1 else C.null\"\n\n    abbreviation is_rendered_commutative_by\n    where \"is_rendered_commutative_by p0 p1 \\<equiv>\n           C.seq a0 p0 \\<and> C.seq a1 p1 \\<and> C.dom p0 = C.dom p1\"\n\n    abbreviation has_as_binary_product\n    where \"has_as_binary_product p0 p1 \\<equiv> limit_cone (C.dom p0) (mkCone p0 p1)\"\n\n    lemma cone_mkCone:\n    assumes \"is_rendered_commutative_by p0 p1\"\n    shows \"cone (C.dom p0) (mkCone p0 p1)\"\n    proof -\n      interpret E: constant_functor J.comp C \\<open>C.dom p0\\<close>\n        using assms by unfold_locales auto\n      show \"cone (C.dom p0) (mkCone p0 p1)\"\n        using assms mkCone_def J.arr_char E.map_simp is_discrete C.comp_ide_arr C.comp_arr_dom\n        by unfold_locales auto\n    qed\n\n    lemma is_rendered_commutative_by_cone:\n    assumes \"cone a \\<chi>\"\n    shows \"is_rendered_commutative_by (\\<chi> J.FF) (\\<chi> J.TT)\"\n    proof -\n      interpret \\<chi>: cone J.comp C map a \\<chi>\n        using assms by auto\n      show ?thesis\n        using is_discrete by simp\n    qed\n\n    lemma mkCone_cone:\n    assumes \"cone a \\<chi>\"\n    shows \"mkCone (\\<chi> J.FF) (\\<chi> J.TT) = \\<chi>\"\n    proof -\n      interpret \\<chi>: cone J.comp C map a \\<chi>\n        using assms by auto\n      interpret mkCone_\\<chi>: cone J.comp C map \\<open>C.dom (\\<chi> J.FF)\\<close> \\<open>mkCone (\\<chi> J.FF) (\\<chi> J.TT)\\<close>\n        using assms is_rendered_commutative_by_cone cone_mkCone by blast\n      show ?thesis\n        using mkCone_def \\<chi>.is_extensional J.ide_char mkCone_def\n              NaturalTransformation.eqI [of J.comp C]\n              \\<chi>.natural_transformation_axioms mkCone_\\<chi>.natural_transformation_axioms\n        by fastforce\n    qed\n\n    lemma cone_iff_span:\n    shows \"cone (C.dom h) (mkCone h k) \\<longleftrightarrow> C.span h k \\<and> C.cod h = a0 \\<and> C.cod k = a1\"\n      using cone_mkCone mkCone_def J.arr_char J.ide_char is_rendered_commutative_by_cone\n      apply (intro iffI)\n        apply (metis (no_types, lifting) C.cod_eqI C.comp_ide_arr J.arr.inject is_discrete)\n      by auto\n\n    lemma cones_map_mkCone_eq_iff:\n    assumes \"is_rendered_commutative_by p0 p1\" and \"is_rendered_commutative_by p0' p1'\"\n    and \"\\<guillemotleft>h : C.dom p0' \\<rightarrow> C.dom p0\\<guillemotright>\"\n    shows \"cones_map h (mkCone p0 p1) = mkCone p0' p1' \\<longleftrightarrow> p0 \\<cdot> h = p0' \\<and> p1 \\<cdot> h = p1'\"\n    proof -\n      interpret \\<chi>: cone J.comp C map \\<open>C.dom p0\\<close> \\<open>mkCone p0 p1\\<close>\n        using assms(1) cone_mkCone [of p0 p1] by blast\n      interpret \\<chi>': cone J.comp C map \\<open>C.dom p0'\\<close> \\<open>mkCone p0' p1'\\<close>\n        using assms(2) cone_mkCone [of p0' p1'] by blast\n      show ?thesis\n      proof\n        assume 3: \"cones_map h (mkCone p0 p1) = mkCone p0' p1'\"\n        show \"p0 \\<cdot> h = p0' \\<and> p1 \\<cdot> h = p1'\"\n        proof\n          show \"p0 \\<cdot> h = p0'\"\n          proof -\n            have \"p0' = cones_map h (mkCone p0 p1) J.FF\"\n              using 3 mkCone_def J.arr_char by simp\n            also have \"... = p0 \\<cdot> h\"\n              using assms mkCone_def J.arr_char \\<chi>.cone_axioms by auto\n            finally show ?thesis by auto\n          qed\n          show \"p1 \\<cdot> h = p1'\"\n          proof -\n            have \"p1' = cones_map h (mkCone p0 p1) J.TT\"\n              using 3 mkCone_def J.arr_char by simp\n            also have \"... = p1 \\<cdot> h\"\n              using assms mkCone_def J.arr_char \\<chi>.cone_axioms by auto\n            finally show ?thesis by auto\n          qed\n        qed\n        next\n        assume \"p0 \\<cdot> h = p0' \\<and> p1 \\<cdot> h = p1'\"\n        thus \"cones_map h (mkCone p0 p1) = mkCone p0' p1'\"\n          using assms \\<chi>.cone_axioms mkCone_def J.arr_char by auto\n      qed\n    qed\n\n  end\n\n  locale binary_product_cone =\n    J: binary_product_shape +\n    C: category C +\n    D: binary_product_diagram C f0 f1 +\n    limit_cone J.comp C D.map \\<open>C.dom p0\\<close> \\<open>D.mkCone p0 p1\\<close>\n  for C :: \"'c comp\"      (infixr \"\\<cdot>\" 55)\n  and f0 :: 'c\n  and f1 :: 'c\n  and p0 :: 'c\n  and p1 :: 'c\n  begin\n\n    \n\n    lemma is_universal':\n    assumes \"D.is_rendered_commutative_by p0' p1'\"\n    shows \"\\<exists>!h. \\<guillemotleft>h : C.dom p0' \\<rightarrow> C.dom p0\\<guillemotright> \\<and> p0 \\<cdot> h = p0' \\<and> p1 \\<cdot> h = p1'\"\n    proof -\n      have \"D.cone (C.dom p0') (D.mkCone p0' p1')\"\n        using assms D.cone_mkCone by blast\n      hence \"\\<exists>!h. \\<guillemotleft>h : C.dom p0' \\<rightarrow> C.dom p0\\<guillemotright> \\<and>\n                  D.cones_map h (D.mkCone p0 p1) = D.mkCone p0' p1'\"\n        using is_universal by simp\n      moreover have \"\\<And>h. \\<guillemotleft>h : C.dom p0' \\<rightarrow> C.dom p0\\<guillemotright> \\<Longrightarrow>\n                           D.cones_map h (D.mkCone p0 p1) = D.mkCone p0' p1' \\<longleftrightarrow>\n                           p0 \\<cdot> h = p0' \\<and> p1 \\<cdot> h = p1'\"\n        using assms D.cones_map_mkCone_eq_iff [of p0 p1 p0' p1'] renders_commutative\n        by blast\n      ultimately show ?thesis by blast\n    qed\n\n    lemma induced_arrowI':\n    assumes \"D.is_rendered_commutative_by p0' p1'\"\n    shows \"\\<guillemotleft>induced_arrow (C.dom p0') (D.mkCone p0' p1') : C.dom p0' \\<rightarrow> C.dom p0\\<guillemotright>\"\n    and \"p0 \\<cdot> induced_arrow (C.dom p0') (D.mkCone p0' p1') = p0'\"\n    and \"p1 \\<cdot> induced_arrow (C.dom p1') (D.mkCone p0' p1') = p1'\"\n    proof -\n      interpret A': constant_functor J.comp C \\<open>C.dom p0'\\<close>\n        using assms by (unfold_locales, auto)\n      have cone: \"D.cone (C.dom p0') (D.mkCone p0' p1')\"\n        using assms D.cone_mkCone [of p0' p1'] by blast\n      show 0: \"p0 \\<cdot> induced_arrow (C.dom p0') (D.mkCone p0' p1') = p0'\"\n      proof -\n        have \"p0 \\<cdot> induced_arrow (C.dom p0') (D.mkCone p0' p1') =\n                D.cones_map (induced_arrow (C.dom p0') (D.mkCone p0' p1'))\n                            (D.mkCone p0 p1) J.FF\"\n          using cone induced_arrowI(1) D.mkCone_def J.arr_char cone_\\<chi> by force\n        also have \"... = p0'\"\n        proof -\n          have \"D.cones_map (induced_arrow (C.dom p0') (D.mkCone p0' p1'))\n                            (D.mkCone p0 p1) =\n                D.mkCone p0' p1'\"\n            using cone induced_arrowI by blast\n          thus ?thesis\n            using J.arr_char D.mkCone_def by simp\n        qed\n        finally show ?thesis by auto\n      qed\n      show \"p1 \\<cdot> induced_arrow (C.dom p1') (D.mkCone p0' p1') = p1'\"\n      proof -\n        have \"p1 \\<cdot> induced_arrow (C.dom p1') (D.mkCone p0' p1') =\n                D.cones_map (induced_arrow (C.dom p0') (D.mkCone p0' p1'))\n                            (D.mkCone p0 p1) J.TT\"\n          using assms cone induced_arrowI(1) D.mkCone_def J.arr_char cone_\\<chi> by fastforce\n        also have \"... = p1'\"\n        proof -\n          have \"D.cones_map (induced_arrow (C.dom p0') (D.mkCone p0' p1'))\n                            (D.mkCone p0 p1) =\n                D.mkCone p0' p1'\"\n            using cone induced_arrowI by blast\n          thus ?thesis\n            using J.arr_char D.mkCone_def by simp\n        qed\n        finally show ?thesis by auto\n      qed\n      show \"\\<guillemotleft>induced_arrow (C.dom p0') (D.mkCone p0' p1') : C.dom p0' \\<rightarrow> C.dom p0\\<guillemotright>\"\n        using 0 cone induced_arrowI by simp\n    qed\n\n  end\n\n  context category\n  begin\n\n    definition has_as_binary_product\n    where \"has_as_binary_product a0 a1 p0 p1 \\<equiv>\n           ide a0 \\<and> ide a1 \\<and> binary_product_diagram.has_as_binary_product C a0 a1 p0 p1\"\n\n    definition has_binary_products\n    where \"has_binary_products =\n           (\\<forall>a0 a1. ide a0 \\<and> ide a1 \\<longrightarrow> (\\<exists>p0 p1. has_as_binary_product a0 a1 p0 p1))\"\n\n    lemma has_as_binary_productI [intro]:\n    assumes \"ide a\" and \"ide b\"\n    and \"\\<guillemotleft>p : c \\<rightarrow> a\\<guillemotright>\" and \"\\<guillemotleft>q : c \\<rightarrow> b\\<guillemotright>\"\n    and \"\\<And>x f g. \\<lbrakk>\\<guillemotleft>f : x \\<rightarrow> a\\<guillemotright>; \\<guillemotleft>g : x \\<rightarrow> b\\<guillemotright>\\<rbrakk> \\<Longrightarrow> \\<exists>!h. \\<guillemotleft>h : x \\<rightarrow> c\\<guillemotright> \\<and> p \\<cdot> h = f \\<and> q \\<cdot> h = g\"\n    shows \"has_as_binary_product a b p q\"\n    proof (unfold has_as_binary_product_def, intro conjI)\n      show \"ide a\" by fact\n      show \"ide b\" by fact\n      interpret J: binary_product_shape .\n      interpret D: binary_product_diagram C a b\n        using assms(1-2) by unfold_locales auto\n      show \"D.has_as_binary_product p q\"\n      proof -\n        have 2: \"D.is_rendered_commutative_by p q\"\n          using assms ide_in_hom by blast\n        let ?\\<chi> = \"D.mkCone p q\"\n        interpret \\<chi>: cone J.comp C D.map c ?\\<chi>\n           using assms(4) D.cone_mkCone 2 by auto\n        interpret \\<chi>: limit_cone J.comp C D.map c ?\\<chi>\n        proof\n          fix x \\<chi>'\n          assume \\<chi>': \"D.cone x \\<chi>'\"\n          interpret \\<chi>': cone J.comp C D.map x \\<chi>'\n            using \\<chi>' by simp\n          have 1: \"\\<exists>!h. \\<guillemotleft>h : x \\<rightarrow> c\\<guillemotright> \\<and> p \\<cdot> h = \\<chi>' J.FF \\<and> q \\<cdot> h = \\<chi>' J.TT\"\n          proof -\n            have \"\\<guillemotleft>\\<chi>' J.FF : x \\<rightarrow> a\\<guillemotright> \\<and> \\<guillemotleft>\\<chi>' J.TT : x \\<rightarrow> b\\<guillemotright>\"\n              by auto\n            thus ?thesis\n              using assms(5) [of \"\\<chi>' J.FF\" x \"\\<chi>' J.TT\"] by simp\n          qed\n          have 3: \"D.is_rendered_commutative_by (\\<chi>' J.FF) (\\<chi>' J.TT)\"\n            using assms(1-2) by force\n          obtain h where h: \"\\<guillemotleft>h : x \\<rightarrow> c\\<guillemotright> \\<and> p \\<cdot> h = \\<chi>' J.FF \\<and> q \\<cdot> h = \\<chi>' J.TT\"\n            using 1 by blast\n          have 4: \"\\<guillemotleft>h : dom (\\<chi>' (J.MkIde False)) \\<rightarrow> dom p\\<guillemotright>\"\n            using assms(3) h by auto\n          have \"\\<guillemotleft>h : x \\<rightarrow> c\\<guillemotright> \\<and> D.cones_map h (D.mkCone p q) = \\<chi>'\"\n          proof (intro conjI)\n            show \"\\<guillemotleft>h : x \\<rightarrow> c\\<guillemotright>\"\n              using h by blast\n            show \"D.cones_map h (D.mkCone p q) = \\<chi>'\"\n            proof\n              fix j\n              show \"D.cones_map h (D.mkCone p q) j = \\<chi>' j\"\n                using h 2 3 4 D.cones_map_mkCone_eq_iff [of p q \"\\<chi>' J.FF\" \"\\<chi>' J.TT\"]\n                      \\<chi>.cone_axioms J.is_discrete \\<chi>'.is_extensional\n                      D.mkCone_def binary_product_shape.ide_char\n                apply (cases \"J.ide j\")\n                 apply auto[1]\n                 by auto\n            qed\n          qed\n          moreover have \"\\<And>h'. \\<guillemotleft>h' : x \\<rightarrow> c\\<guillemotright> \\<and> D.cones_map h' (D.mkCone p q) = \\<chi>' \\<Longrightarrow> h' = h\"\n          proof -\n            fix h'\n            assume 1: \"\\<guillemotleft>h' : x \\<rightarrow> c\\<guillemotright> \\<and> D.cones_map h' (D.mkCone p q) = \\<chi>'\"\n            have \"\\<exists>!h. \\<guillemotleft>h : x \\<rightarrow> c\\<guillemotright> \\<and> p \\<cdot> h = \\<chi>' J.FF \\<and> q \\<cdot> h = \\<chi>' J.TT\"\n            proof -\n              have \"\\<guillemotleft>\\<chi>' J.FF : x \\<rightarrow> a\\<guillemotright> \\<and> \\<guillemotleft>\\<chi>' J.TT : x \\<rightarrow> b\\<guillemotright>\"\n                by auto\n              thus ?thesis\n                using h assms(5) [of \"\\<chi>' J.FF\" x \"\\<chi>' J.TT\"] J.ide_char by auto\n            qed\n            moreover have \"\\<guillemotleft>h : x \\<rightarrow> c\\<guillemotright> \\<and> \\<chi>' J.FF = p \\<cdot> h \\<and> q \\<cdot> h = \\<chi>' J.TT\"\n              using h by simp\n            moreover have \"\\<guillemotleft>h' : x \\<rightarrow> c\\<guillemotright> \\<and> \\<chi>' J.FF = p \\<cdot> h' \\<and> q \\<cdot> h' = \\<chi>' J.TT\"\n              using 1 \\<chi>.cone_axioms D.mkCone_def [of p q] by auto\n            ultimately show \"h' = h\" by auto\n          qed\n          ultimately show \"\\<exists>!h. \\<guillemotleft>h : x \\<rightarrow> c\\<guillemotright> \\<and> D.cones_map h (D.mkCone p q) = \\<chi>'\"\n            by blast\n        qed\n        show \"D.has_as_binary_product p q\"\n          using assms \\<chi>.limit_cone_axioms by blast\n      qed\n    qed\n\n    lemma has_as_binary_productE [elim]:\n    assumes \"has_as_binary_product a b p q\"\n    and \"\\<lbrakk>\\<guillemotleft>p : dom p \\<rightarrow> a\\<guillemotright>; \\<guillemotleft>q : dom p \\<rightarrow> b\\<guillemotright>;\n          \\<And>x f g. \\<lbrakk>\\<guillemotleft>f : x \\<rightarrow> a\\<guillemotright>; \\<guillemotleft>g : x \\<rightarrow> b\\<guillemotright>\\<rbrakk> \\<Longrightarrow> \\<exists>!h. p \\<cdot> h = f \\<and> q \\<cdot> h = g\\<rbrakk> \\<Longrightarrow> T\"\n    shows T\n    proof -\n      interpret J: binary_product_shape .\n      interpret D: binary_product_diagram C a b\n        using assms(1) has_as_binary_product_def\n        by (simp add: binary_product_diagram.intro binary_product_diagram_axioms.intro\n                      category_axioms)\n      have 1: \"\\<And>h k. span h k \\<and> cod h = a \\<and> cod k = b \\<longleftrightarrow> D.cone (dom h) (D.mkCone h k)\"\n        using D.cone_iff_span by presburger\n      let ?\\<chi> = \"D.mkCone p q\"\n      interpret \\<chi>: limit_cone J.comp C D.map \\<open>dom p\\<close> ?\\<chi>\n        using assms(1) has_as_binary_product_def D.cone_mkCone by blast\n      have span: \"span p q\"\n        using 1 \\<chi>.cone_axioms by blast\n      moreover have \"\\<guillemotleft>p : dom p \\<rightarrow> a\\<guillemotright> \\<and> \\<guillemotleft>q : dom p \\<rightarrow> b\\<guillemotright>\"\n        using span \\<chi>.preserves_hom \\<chi>.cone_axioms binary_product_shape.arr_char\n        by (metis D.cone_iff_span arr_iff_in_hom)\n      moreover have \"\\<And>x f g. \\<lbrakk>\\<guillemotleft>f : x \\<rightarrow> a\\<guillemotright>; \\<guillemotleft>g : x \\<rightarrow> b\\<guillemotright>\\<rbrakk> \\<Longrightarrow> \\<exists>!l. p \\<cdot> l = f \\<and> q \\<cdot> l = g\"\n      proof -\n        fix x f g\n        assume f: \"\\<guillemotleft>f : x \\<rightarrow> a\\<guillemotright>\" and g: \"\\<guillemotleft>g : x \\<rightarrow> b\\<guillemotright>\"\n        let ?\\<chi>' = \"D.mkCone f g\"\n        interpret \\<chi>': cone J.comp C D.map x ?\\<chi>'\n          using 1 f g by blast\n        have 3: \"\\<exists>!l. \\<guillemotleft>l : x \\<rightarrow> dom p\\<guillemotright> \\<and> D.cones_map l ?\\<chi> = ?\\<chi>'\"\n          using 1 f g \\<chi>.is_universal [of x \"D.mkCone f g\"] \\<chi>'.cone_axioms by fastforce\n        obtain l where l: \"\\<guillemotleft>l : x \\<rightarrow> dom p\\<guillemotright> \\<and> D.cones_map l ?\\<chi> = ?\\<chi>'\"\n          using 3 by blast\n        have \"p \\<cdot> l = f \\<and> q \\<cdot> l = g\"\n        proof\n          have \"p \\<cdot> l = ?\\<chi> J.FF \\<cdot> l\"\n            using D.mkCone_def by presburger\n          also have \"... = D.cones_map l ?\\<chi> J.FF\"\n            using \\<chi>.cone_axioms\n            apply simp\n            using l by fastforce\n          also have \"... = f\"\n            using D.mkCone_def l by presburger\n          finally show \"p \\<cdot> l = f\" by blast\n          have \"q \\<cdot> l = ?\\<chi> J.TT \\<cdot> l\"\n            using D.mkCone_def by simp\n          also have \"... = D.cones_map l ?\\<chi> J.TT\"\n            using \\<chi>.cone_axioms\n            apply simp\n            using l by fastforce\n          also have \"... = g\"\n            using D.mkCone_def l by simp\n          finally show \"q \\<cdot> l = g\" by blast\n        qed\n        moreover have \"\\<And>l'. p \\<cdot> l' = f \\<and> q \\<cdot> l' = g\\<Longrightarrow> l' = l\"\n        proof -\n          fix l'\n          assume 1: \"p \\<cdot> l' = f \\<and> q \\<cdot> l' = g\"\n          have 2: \"\\<guillemotleft>l' : x \\<rightarrow> dom p\\<guillemotright>\"\n            using 1 f by blast\n          moreover have \"D.cones_map l' ?\\<chi> = ?\\<chi>'\"\n            using 1 2 D.cones_map_mkCone_eq_iff [of p q f g l']\n            by (metis (no_types, lifting) f g \\<open>\\<guillemotleft>p : dom p \\<rightarrow> a\\<guillemotright> \\<and> \\<guillemotleft>q : dom p \\<rightarrow> b\\<guillemotright>\\<close>\n                      comp_cod_arr in_homE)\n          ultimately show \"l' = l\"\n            using l \\<chi>.is_universal \\<chi>'.cone_axioms by blast\n        qed\n        ultimately show \"\\<exists>!l. p \\<cdot> l = f \\<and> q \\<cdot> l = g\" by blast\n      qed\n      ultimately show T\n        using assms(2) by simp\n    qed\n\n  end\n\n  locale category_with_binary_products =\n    category +\n  assumes has_binary_products: has_binary_products\n\n  subsection \"Elementary Category with Binary Products\"\n\n  text \\<open>\n    An \\emph{elementary category with binary products} is a category equipped with a specific\n    way of mapping each pair of objects \\<open>a\\<close> and \\<open>b\\<close> to a pair of arrows \\<open>\\<pp>\\<^sub>1[a, b]\\<close> and \\<open>\\<pp>\\<^sub>0[a, b]\\<close>\n    that comprise a universal span.  It is useful to assume that the mappings that produce\n    \\<open>\\<pp>\\<^sub>1[a, b]\\<close> and \\<open>\\<pp>\\<^sub>0[a, b]\\<close> from \\<open>a\\<close> and \\<open>b\\<close> are extensional; that is, if either \\<open>a\\<close> or \\<open>b\\<close>\n    is not an identity, then \\<open>\\<pp>\\<^sub>1[a, b]\\<close> and \\<open>\\<pp>\\<^sub>0[a, b]\\<close> are \\<open>null\\<close>.\n  \\<close>\n\n  locale elementary_category_with_binary_products =\n    category C\n  for C :: \"'a comp\"                             (infixr \"\\<cdot>\" 55)\n  and pr0 :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a\"                    (\"\\<pp>\\<^sub>0[_, _]\")\n  and pr1 :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a\"                    (\"\\<pp>\\<^sub>1[_, _]\") +\n  assumes pr0_ext: \"\\<not> (ide a \\<and> ide b) \\<Longrightarrow> \\<pp>\\<^sub>0[a, b] = null\"\n  and pr1_ext: \"\\<not> (ide a \\<and> ide b) \\<Longrightarrow> \\<pp>\\<^sub>1[a, b] = null\"\n  and span_pr: \"\\<lbrakk> ide a; ide b \\<rbrakk> \\<Longrightarrow> span \\<pp>\\<^sub>1[a, b] \\<pp>\\<^sub>0[a, b]\"\n  and cod_pr0: \"\\<lbrakk> ide a; ide b \\<rbrakk> \\<Longrightarrow> cod \\<pp>\\<^sub>0[a, b] = b\"\n  and cod_pr1: \"\\<lbrakk> ide a; ide b \\<rbrakk> \\<Longrightarrow> cod \\<pp>\\<^sub>1[a, b] = a\"\n  and universal: \"span f g \\<Longrightarrow> \\<exists>!l. \\<pp>\\<^sub>1[cod f, cod g] \\<cdot> l = f \\<and> \\<pp>\\<^sub>0[cod f, cod g] \\<cdot> l = g\"\n  begin\n\n    lemma pr0_in_hom':\n    assumes \"ide a\" and \"ide b\"\n    shows \"\\<guillemotleft>\\<pp>\\<^sub>0[a, b] : dom \\<pp>\\<^sub>0[a, b] \\<rightarrow> b\\<guillemotright>\"\n      using assms span_pr cod_pr0 by auto\n\n    lemma pr1_in_hom':\n    assumes \"ide a\" and \"ide b\"\n    shows \"\\<guillemotleft>\\<pp>\\<^sub>1[a, b] : dom \\<pp>\\<^sub>0[a, b] \\<rightarrow> a\\<guillemotright>\"\n      using assms span_pr cod_pr1 by auto\n\n    text \\<open>\n      We introduce a notation for tupling, which denotes the arrow into a product that\n      is induced by a span.\n    \\<close>\n\n    definition tuple         (\"\\<langle>_, _\\<rangle>\")\n    where \"\\<langle>f, g\\<rangle> \\<equiv> if span f g then\n                      THE l. \\<pp>\\<^sub>1[cod f, cod g] \\<cdot> l = f \\<and> \\<pp>\\<^sub>0[cod f, cod g] \\<cdot> l = g\n                    else null\"\n\n    text \\<open>\n      The following defines product of arrows (not just of objects).  It will take a little\n      while before we can prove that it is functorial, but for right now it is nice to have\n      it as a notation for the apex of a product cone.  We have to go through some slightly\n      unnatural contortions in the development here, though, to avoid having to introduce a\n      separate preliminary notation just for the product of objects.\n    \\<close>\n    (* TODO: I want to use \\<times> but it has already been commandeered for product types. *)\n    definition prod         (infixr \"\\<otimes>\" 51)\n    where \"f \\<otimes> g \\<equiv> \\<langle>f \\<cdot> \\<pp>\\<^sub>1[dom f, dom g], g \\<cdot> \\<pp>\\<^sub>0[dom f, dom g]\\<rangle>\"\n\n    lemma seq_pr_tuple:\n    assumes \"span f g\"\n    shows \"seq \\<pp>\\<^sub>0[cod f, cod g] \\<langle>f, g\\<rangle>\"\n    proof -\n      have \"\\<pp>\\<^sub>0[cod f, cod g] \\<cdot> \\<langle>f, g\\<rangle> = g\"\n        unfolding tuple_def\n        using assms universal theI [of \"\\<lambda>l. \\<pp>\\<^sub>1[cod f, cod g] \\<cdot> l = f \\<and> \\<pp>\\<^sub>0[cod f, cod g] \\<cdot> l = g\"]\n        by simp meson\n      thus ?thesis\n        using assms by simp\n    qed\n\n    lemma tuple_pr_arr:\n    assumes \"ide a\" and \"ide b\" and \"seq \\<pp>\\<^sub>0[a, b] h\"\n    shows \"\\<langle>\\<pp>\\<^sub>1[a, b] \\<cdot> h, \\<pp>\\<^sub>0[a, b] \\<cdot> h\\<rangle> = h\"\n      unfolding tuple_def\n      using assms span_pr cod_pr0 cod_pr1 universal [of \"\\<pp>\\<^sub>1[a, b] \\<cdot> h\" \"\\<pp>\\<^sub>0[a, b] \\<cdot> h\"]\n            theI_unique [of \"\\<lambda>l. \\<pp>\\<^sub>1[a, b] \\<cdot> l = \\<pp>\\<^sub>1[a, b] \\<cdot> h \\<and> \\<pp>\\<^sub>0[a, b] \\<cdot> l = \\<pp>\\<^sub>0[a, b] \\<cdot> h\" h]\n      by auto\n\n    lemma pr_tuple [simp]:\n    assumes \"span f g\" and \"cod f = a\" and \"cod g = b\"\n    shows \"\\<pp>\\<^sub>1[a, b] \\<cdot> \\<langle>f, g\\<rangle> = f\" and \"\\<pp>\\<^sub>0[a, b] \\<cdot> \\<langle>f, g\\<rangle> = g\"\n    proof -\n      have 1: \"\\<pp>\\<^sub>1[a, b] \\<cdot> \\<langle>f, g\\<rangle> = f \\<and> \\<pp>\\<^sub>0[a, b] \\<cdot> \\<langle>f, g\\<rangle> = g\"\n        unfolding tuple_def\n        using assms universal theI [of \"\\<lambda>l. \\<pp>\\<^sub>1[a, b] \\<cdot> l = f \\<and> \\<pp>\\<^sub>0[a, b] \\<cdot> l = g\"]\n        by simp meson\n      show \"\\<pp>\\<^sub>1[a, b] \\<cdot> \\<langle>f, g\\<rangle> = f\" using 1 by simp\n      show \"\\<pp>\\<^sub>0[a, b] \\<cdot> \\<langle>f, g\\<rangle> = g\" using 1 by simp\n    qed\n\n    lemma cod_tuple:\n    assumes \"span f g\"\n    shows \"cod \\<langle>f, g\\<rangle> = cod f \\<otimes> cod g\"\n    proof -\n      have \"cod f \\<otimes> cod g = \\<langle>\\<pp>\\<^sub>1[cod f, cod g], \\<pp>\\<^sub>0[cod f, cod g]\\<rangle>\"\n        unfolding prod_def\n        using assms comp_cod_arr span_pr cod_pr0 cod_pr1 by simp\n      also have \"... = \\<langle>\\<pp>\\<^sub>1[cod f, cod g] \\<cdot> dom \\<pp>\\<^sub>0[cod f, cod g],\n                        \\<pp>\\<^sub>0[cod f, cod g] \\<cdot> dom \\<pp>\\<^sub>0[cod f, cod g]\\<rangle>\"\n        using assms span_pr comp_arr_dom by simp\n      also have \"... = dom \\<pp>\\<^sub>0[cod f, cod g]\"\n        using assms tuple_pr_arr span_pr by simp\n      also have \"... = cod \\<langle>f, g\\<rangle>\"\n        using assms seq_pr_tuple by blast\n      finally show ?thesis by simp\n    qed\n\n    lemma tuple_in_hom [intro]:\n    assumes \"\\<guillemotleft>f : a \\<rightarrow> b\\<guillemotright>\" and \"\\<guillemotleft>g : a \\<rightarrow> c\\<guillemotright>\"\n    shows \"\\<guillemotleft>\\<langle>f, g\\<rangle> : a \\<rightarrow> b \\<otimes> c\\<guillemotright>\"\n      using assms pr_tuple dom_comp cod_tuple\n      apply (elim in_homE, intro in_homI)\n        apply (metis seqE)\n      by metis+\n\n    lemma tuple_in_hom' [simp]:\n    assumes \"arr f\" and \"dom f = a\" and \"cod f = b\"\n    and \"arr g\" and \"dom g = a\" and \"cod g = c\"\n    shows \"\\<guillemotleft>\\<langle>f, g\\<rangle> : a \\<rightarrow> b \\<otimes> c\\<guillemotright>\"\n      using assms by auto\n\n    lemma tuple_ext:\n    assumes \"\\<not> span f g\"\n    shows \"\\<langle>f, g\\<rangle> = null\"\n      unfolding tuple_def\n      by (simp add: assms)\n\n    lemma tuple_simps [simp]:\n    assumes \"span f g\"\n    shows \"arr \\<langle>f, g\\<rangle>\" and \"dom \\<langle>f, g\\<rangle> = dom f\" and \"cod \\<langle>f, g\\<rangle> = cod f \\<otimes> cod g\"\n    proof -\n      show \"arr \\<langle>f, g\\<rangle>\"\n        using assms tuple_in_hom by blast\n      show \"dom \\<langle>f, g\\<rangle> = dom f\"\n        using assms tuple_in_hom\n        by (metis dom_comp pr_tuple(1))\n      show \"cod \\<langle>f, g\\<rangle> = cod f \\<otimes> cod g\"\n        using assms cod_tuple by auto\n    qed\n\n    lemma tuple_pr [simp]:\n    assumes \"ide a\" and \"ide b\"\n    shows \"\\<langle>\\<pp>\\<^sub>1[a, b], \\<pp>\\<^sub>0[a, b]\\<rangle> = a \\<otimes> b\"\n    proof -\n      have 1: \"dom \\<pp>\\<^sub>0[a, b] = a \\<otimes> b\"\n        using assms seq_pr_tuple cod_tuple [of \"\\<pp>\\<^sub>1[a, b]\" \"\\<pp>\\<^sub>0[a, b]\"] span_pr\n              pr0_in_hom' pr1_in_hom'\n        by (metis cod_pr0 cod_pr1 seqE)\n      hence \"\\<langle>\\<pp>\\<^sub>1[a, b], \\<pp>\\<^sub>0[a, b]\\<rangle> = \\<langle>\\<pp>\\<^sub>1[a, b] \\<cdot> (a \\<otimes> b), \\<pp>\\<^sub>0[a, b] \\<cdot> (a \\<otimes> b)\\<rangle>\"\n        using assms pr0_in_hom' pr1_in_hom' comp_arr_dom span_pr by simp\n      thus ?thesis\n        using assms 1 tuple_pr_arr span_pr\n        by (metis comp_arr_dom)\n    qed\n\n    lemma pr_in_hom [intro, simp]:\n    assumes \"ide a\" and \"ide b\"\n    shows \"\\<guillemotleft>\\<pp>\\<^sub>0[a, b] : a \\<otimes> b \\<rightarrow> b\\<guillemotright>\" and \"\\<guillemotleft>\\<pp>\\<^sub>1[a, b] : a \\<otimes> b \\<rightarrow> a\\<guillemotright>\"\n    proof -\n      show 0: \"\\<guillemotleft>\\<pp>\\<^sub>0[a, b] : a \\<otimes> b \\<rightarrow> b\\<guillemotright>\"\n        using assms pr0_in_hom' seq_pr_tuple [of \"\\<pp>\\<^sub>1[a, b]\" \"\\<pp>\\<^sub>0[a, b]\"]\n              cod_tuple [of \"\\<pp>\\<^sub>1[a, b]\" \"\\<pp>\\<^sub>0[a, b]\"] span_pr cod_pr0 cod_pr1\n        by (intro in_homI, auto)\n      show \"\\<guillemotleft>\\<pp>\\<^sub>1[a, b] : a \\<otimes> b \\<rightarrow> a\\<guillemotright>\"\n        using assms 0 span_pr pr1_in_hom' by fastforce\n    qed\n\n    lemma pr_simps [simp]:\n    assumes \"ide a\" and \"ide b\"\n    shows \"arr \\<pp>\\<^sub>0[a, b]\" and \"dom \\<pp>\\<^sub>0[a, b] = a \\<otimes> b\" and \"cod \\<pp>\\<^sub>0[a, b] = b\"\n    and \"arr \\<pp>\\<^sub>1[a, b]\" and \"dom \\<pp>\\<^sub>1[a, b] = a \\<otimes> b\" and \"cod \\<pp>\\<^sub>1[a, b] = a\"\n      using assms pr_in_hom by blast+\n\n    lemma arr_pr0_iff [iff]:\n    shows \"arr \\<pp>\\<^sub>0[a, b] \\<longleftrightarrow> ide a \\<and> ide b\"\n    proof\n      show \"ide a \\<and> ide b \\<Longrightarrow> arr \\<pp>\\<^sub>0[a, b]\"\n        using pr_in_hom by auto\n      show \"arr \\<pp>\\<^sub>0[a, b] \\<Longrightarrow> ide a \\<and> ide b\"\n        using pr0_ext not_arr_null by metis\n    qed\n\n    lemma arr_pr1_iff [iff]:\n    shows \"arr \\<pp>\\<^sub>1[a, b] \\<longleftrightarrow> ide a \\<and> ide b\"\n    proof\n      show \"ide a \\<and> ide b \\<Longrightarrow> arr \\<pp>\\<^sub>1[a, b]\"\n        using pr_in_hom by auto\n      show \"arr \\<pp>\\<^sub>1[a, b] \\<Longrightarrow> ide a \\<and> ide b\"\n        using pr1_ext not_arr_null by metis\n    qed\n\n    lemma pr_joint_monic:\n    assumes \"seq \\<pp>\\<^sub>0[a, b] h\"\n    and \"\\<pp>\\<^sub>0[a, b] \\<cdot> h = \\<pp>\\<^sub>0[a, b] \\<cdot> h'\" and \"\\<pp>\\<^sub>1[a, b] \\<cdot> h = \\<pp>\\<^sub>1[a, b] \\<cdot> h'\"\n    shows \"h = h'\"\n      using assms\n      by (metis arr_pr0_iff seqE tuple_pr_arr)\n\n    lemma comp_tuple_arr [simp]:\n    assumes \"span f g\" and \"arr h\" and \"dom f = cod h\"\n    shows \"\\<langle>f, g\\<rangle> \\<cdot> h = \\<langle>f \\<cdot> h, g \\<cdot> h\\<rangle>\"\n    proof (intro pr_joint_monic [where h = \"\\<langle>f, g\\<rangle> \\<cdot> h\"])\n      show \"seq \\<pp>\\<^sub>0[cod f, cod g] (\\<langle>f, g\\<rangle> \\<cdot> h)\"\n        using assms by fastforce\n      show \"\\<pp>\\<^sub>0[cod f, cod g] \\<cdot> \\<langle>f, g\\<rangle> \\<cdot> h = \\<pp>\\<^sub>0[cod f, cod g] \\<cdot> \\<langle>f \\<cdot> h, g \\<cdot> h\\<rangle>\"\n      proof -\n        have \"\\<pp>\\<^sub>0[cod f, cod g] \\<cdot> \\<langle>f, g\\<rangle> \\<cdot> h = (\\<pp>\\<^sub>0[cod f, cod g] \\<cdot> \\<langle>f, g\\<rangle>) \\<cdot> h\"\n          using comp_assoc by simp\n        thus ?thesis\n          using assms by simp\n      qed\n      show \"\\<pp>\\<^sub>1[cod f, cod g] \\<cdot> \\<langle>f, g\\<rangle> \\<cdot> h = \\<pp>\\<^sub>1[cod f, cod g] \\<cdot> \\<langle>f \\<cdot> h, g \\<cdot> h\\<rangle>\"\n      proof -\n        have \"\\<pp>\\<^sub>1[cod f, cod g] \\<cdot> \\<langle>f, g\\<rangle> \\<cdot> h = (\\<pp>\\<^sub>1[cod f, cod g] \\<cdot> \\<langle>f, g\\<rangle>) \\<cdot> h\"\n          using comp_assoc by simp\n        thus ?thesis\n          using assms by simp\n      qed\n    qed\n\n    lemma ide_prod [intro, simp]:\n    assumes \"ide a\" and \"ide b\"\n    shows \"ide (a \\<otimes> b)\"\n      using assms pr_simps ide_dom [of \"\\<pp>\\<^sub>0[a, b]\"] by simp\n\n    lemma prod_in_hom [intro]:\n    assumes \"\\<guillemotleft>f : a \\<rightarrow> c\\<guillemotright>\" and \"\\<guillemotleft>g : b \\<rightarrow> d\\<guillemotright>\"\n    shows \"\\<guillemotleft>f \\<otimes> g : a \\<otimes> b \\<rightarrow> c \\<otimes> d\\<guillemotright>\"\n      using assms prod_def by fastforce\n\n    lemma prod_in_hom' [simp]:\n    assumes \"arr f\" and \"dom f = a\" and \"cod f = c\"\n    and \"arr g\" and \"dom g = b\" and \"cod g = d\"\n    shows \"\\<guillemotleft>f \\<otimes> g : a \\<otimes> b \\<rightarrow> c \\<otimes> d\\<guillemotright>\"\n      using assms by blast\n\n    lemma prod_simps [simp]:\n    assumes \"arr f0\" and \"arr f1\"\n    shows \"arr (f0 \\<otimes> f1)\"\n    and \"dom (f0 \\<otimes> f1) = dom f0 \\<otimes> dom f1\"\n    and \"cod (f0 \\<otimes> f1) = cod f0 \\<otimes> cod f1\"\n      using assms prod_in_hom by blast+\n\n  end\n\n  subsection \"Agreement between the Definitions\"\n\n  text \\<open>\n    We now show that a category with binary products extends (by making a choice)\n    to an elementary category with binary products, and that the underlying category\n    of an elementary category with binary products is a category with binary products.\n  \\<close>\n\n  context category_with_binary_products\n  begin\n\n    definition pr1\n    where \"pr1 a b \\<equiv> if ide a \\<and> ide b then\n                        fst (SOME x. has_as_binary_product a b (fst x) (snd x))\n                      else null\"\n\n    definition pr0\n    where \"pr0 a b \\<equiv> if ide a \\<and> ide b then\n                        snd (SOME x. has_as_binary_product a b (fst x) (snd x))\n                      else null\"\n\n    lemma pr_yields_binary_product:\n    assumes \"ide a\" and \"ide b\"\n    shows \"has_as_binary_product a b (pr1 a b) (pr0 a b)\"\n    proof -\n      have \"\\<exists>x. has_as_binary_product a b (fst x) (snd x)\"\n        using assms has_binary_products has_binary_products_def has_as_binary_product_def\n        by simp\n      thus ?thesis\n        using assms has_binary_products has_binary_products_def pr0_def pr1_def\n              someI_ex [of \"\\<lambda>x. has_as_binary_product a b (fst x) (snd x)\"]\n        by simp\n    qed\n\n    interpretation elementary_category_with_binary_products C pr0 pr1\n    proof\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      fix a b\n      assume a: \"ide a\" and b: \"ide b\"\n      interpret J: binary_product_shape .\n      interpret D: binary_product_diagram C a b\n        using a b by unfold_locales auto\n      let ?\\<chi> = \"D.mkCone (pr1 a b) (pr0 a b)\"\n      interpret \\<chi>: limit_cone J.comp C D.map \\<open>dom (pr1 a b)\\<close> ?\\<chi>\n        using a b pr_yields_binary_product\n        by (simp add: has_as_binary_product_def)\n      have 1: \"pr1 a b = ?\\<chi> J.FF \\<and> pr0 a b = ?\\<chi> J.TT\"\n        using D.mkCone_def by simp\n      show \"span (pr1 a b) (pr0 a b)\"\n        using 1 \\<chi>.preserves_reflects_arr J.seqE J.arr_char J.seq_char J.is_category\n              D.is_rendered_commutative_by_cone \\<chi>.cone_axioms\n        by metis\n      show \"cod (pr1 a b) = a\"\n        using 1 \\<chi>.preserves_cod [of J.FF] J.cod_char J.arr_char by auto\n      show \"cod (pr0 a b) = b\"\n        using 1 \\<chi>.preserves_cod [of J.TT] J.cod_char J.arr_char by auto\n      next\n      fix f g\n      assume fg: \"span f g\"\n      show \"\\<exists>!l. pr1 (cod f) (cod g) \\<cdot> l = f \\<and> pr0 (cod f) (cod g) \\<cdot> l = g\"\n      proof -\n        interpret J: binary_product_shape .\n        interpret D: binary_product_diagram C \\<open>cod f\\<close> \\<open>cod g\\<close>\n          using fg by unfold_locales auto\n        let ?\\<chi> = \"D.mkCone (pr1 (cod f) (cod g)) (pr0 (cod f) (cod g))\"\n        interpret \\<chi>: limit_cone J.comp C D.map \\<open>dom (pr1 (cod f) (cod g))\\<close> ?\\<chi>\n          using fg pr_yields_binary_product [of \"cod f\" \"cod g\"] has_as_binary_product_def\n          by simp\n        interpret \\<chi>: binary_product_cone C \\<open>cod f\\<close> \\<open>cod g\\<close>\n                       \\<open>pr1 (cod f) (cod g)\\<close> \\<open>pr0 (cod f) (cod g)\\<close> ..\n        have 1: \"pr1 (cod f) (cod g) = ?\\<chi> J.FF \\<and> pr0 (cod f) (cod g) = ?\\<chi> J.TT\"\n          using D.mkCone_def by simp\n        show \"\\<exists>!l. pr1 (cod f) (cod g) \\<cdot> l = f \\<and> pr0 (cod f) (cod g) \\<cdot> l = g\"\n        proof -\n          have \"\\<exists>!l. \\<guillemotleft>l : dom f \\<rightarrow> dom (pr1 (cod f) (cod g))\\<guillemotright> \\<and>\n                     pr1 (cod f) (cod g) \\<cdot> l = f \\<and> pr0 (cod f) (cod g) \\<cdot> l = g\"\n            using fg \\<chi>.is_universal' by simp\n          moreover have \"\\<And>l. pr1 (cod f) (cod g) \\<cdot> l = f\n                                \\<Longrightarrow> \\<guillemotleft>l : dom f \\<rightarrow> dom (pr1 (cod f) (cod g))\\<guillemotright>\"\n            using fg dom_comp in_homI seqE seqI by metis\n          ultimately show ?thesis by auto\n        qed\n      qed\n    qed\n\n    proposition extends_to_elementary_category_with_binary_products:\n    shows \"elementary_category_with_binary_products C pr0 pr1\"\n      ..\n\n  end\n\n  context elementary_category_with_binary_products\n  begin\n\n    interpretation category_with_binary_products C\n    proof\n      show \"has_binary_products\"\n      proof (unfold has_binary_products_def, intro allI impI)\n        show \"\\<And>a b. ide a \\<and> ide b \\<Longrightarrow> \\<exists>p0 p1. has_as_binary_product a b p0 p1\"\n        proof -\n          fix a b\n          assume ab: \"ide a \\<and> ide b\"\n          have \"has_as_binary_product a b \\<pp>\\<^sub>1[a, b] \\<pp>\\<^sub>0[a, b]\"\n          proof\n            show \"ide a\" and \"ide b\" and \"\\<guillemotleft>\\<pp>\\<^sub>1[a, b] : a \\<otimes> b \\<rightarrow> a\\<guillemotright>\" and \"\\<guillemotleft>\\<pp>\\<^sub>0[a, b] : a \\<otimes> b \\<rightarrow> b\\<guillemotright>\"\n              using ab by auto\n            show \"\\<And>x f g. \\<lbrakk>\\<guillemotleft>f : x \\<rightarrow> a\\<guillemotright>; \\<guillemotleft>g : x \\<rightarrow> b\\<guillemotright>\\<rbrakk>\n                             \\<Longrightarrow> \\<exists>!h. \\<guillemotleft>h : x \\<rightarrow> a \\<otimes> b\\<guillemotright> \\<and> \\<pp>\\<^sub>1[a, b] \\<cdot> h = f \\<and> \\<pp>\\<^sub>0[a, b] \\<cdot> h = g\"\n            proof -\n              fix x f g\n              assume f: \"\\<guillemotleft>f : x \\<rightarrow> a\\<guillemotright>\" and g: \"\\<guillemotleft>g : x \\<rightarrow> b\\<guillemotright>\"\n              show \"\\<exists>!h. \\<guillemotleft>h : x \\<rightarrow> a \\<otimes> b\\<guillemotright> \\<and> \\<pp>\\<^sub>1[a, b] \\<cdot> h = f \\<and> \\<pp>\\<^sub>0[a, b] \\<cdot> h = g\"\n                using ab f g tuple_pr_arr pr_tuple [of f g a b] tuple_in_hom'\n                by (metis in_homE)\n            qed\n          qed\n          thus \"\\<exists>p0 p1. has_as_binary_product a b p0 p1\" by blast\n        qed\n      qed\n    qed\n\n    proposition is_category_with_binary_products:\n    shows \"category_with_binary_products C\"\n      ..\n\n  end\n\n  subsection \"Further Properties\"\n\n  context elementary_category_with_binary_products\n  begin\n\n    lemma interchange:\n    assumes \"seq h f\" and \"seq k g\"\n    shows \"(h \\<otimes> k) \\<cdot> (f \\<otimes> g) = h \\<cdot> f \\<otimes> k \\<cdot> g\"\n      using assms prod_def comp_tuple_arr comp_assoc by fastforce\n\n    lemma pr_naturality [simp]:\n    assumes \"arr g\" and \"dom g = b\" and \"cod g = d\"\n        and \"arr f\" and \"dom f = a\" and \"cod f = c\"\n    shows \"\\<pp>\\<^sub>0[c, d] \\<cdot> (f \\<otimes> g) = g \\<cdot> \\<pp>\\<^sub>0[a, b]\"\n    and \"\\<pp>\\<^sub>1[c, d] \\<cdot> (f \\<otimes> g) = f \\<cdot> \\<pp>\\<^sub>1[a, b]\"\n      using assms prod_def by fastforce+\n\n    abbreviation dup (\"\\<d>[_]\")\n    where \"\\<d>[f] \\<equiv> \\<langle>f, f\\<rangle>\"\n\n    lemma dup_in_hom [intro, simp]:\n    assumes \"\\<guillemotleft>f : a \\<rightarrow> b\\<guillemotright>\"\n    shows \"\\<guillemotleft>\\<d>[f] : a \\<rightarrow> b \\<otimes> b\\<guillemotright>\"\n      using assms by fastforce\n\n    lemma dup_simps [simp]:\n    assumes \"arr f\"\n    shows \"arr \\<d>[f]\" and \"dom \\<d>[f] = dom f\" and \"cod \\<d>[f] = cod f \\<otimes> cod f\"\n      using assms dup_in_hom by auto\n\n    lemma dup_naturality:\n    assumes \"\\<guillemotleft>f : a \\<rightarrow> b\\<guillemotright>\"\n    shows \"\\<d>[b] \\<cdot> f = (f \\<otimes> f) \\<cdot> \\<d>[a]\"\n      using assms prod_def comp_arr_dom comp_cod_arr comp_tuple_arr comp_assoc\n      by fastforce\n\n    lemma pr_dup [simp]:\n    assumes \"ide a\"\n    shows \"\\<pp>\\<^sub>0[a, a] \\<cdot> \\<d>[a] = a\" and \"\\<pp>\\<^sub>1[a, a] \\<cdot> \\<d>[a] = a\"\n      using assms by simp_all\n\n    lemma prod_tuple:\n    assumes \"span f g\" and \"seq h f\" and \"seq k g\"\n    shows \"(h \\<otimes> k) \\<cdot> \\<langle>f, g\\<rangle> = \\<langle>h \\<cdot> f, k \\<cdot> g\\<rangle>\"\n      using assms prod_def comp_assoc comp_tuple_arr by fastforce\n\n    lemma tuple_eqI:\n    assumes \"seq \\<pp>\\<^sub>0[b, c] f\" and \"seq \\<pp>\\<^sub>1[b, c] f\"\n    and \"\\<pp>\\<^sub>0[b, c] \\<cdot> f = f0\" and \"\\<pp>\\<^sub>1[b, c] \\<cdot> f = f1\"\n    shows \"f = \\<langle>f1, f0\\<rangle>\"\n      using assms pr_joint_monic [of b c \"\\<langle>f1, f0\\<rangle>\" f] pr_tuple by auto\n\n    definition assoc (\"\\<a>[_, _, _]\")\n    where \"\\<a>[a, b, c] \\<equiv> \\<langle>\\<pp>\\<^sub>1[a, b] \\<cdot> \\<pp>\\<^sub>1[a \\<otimes> b, c], \\<langle>\\<pp>\\<^sub>0[a, b] \\<cdot> \\<pp>\\<^sub>1[a \\<otimes> b, c], \\<pp>\\<^sub>0[a \\<otimes> b, c]\\<rangle>\\<rangle>\"\n\n    definition assoc' (\"\\<a>\\<^sup>-\\<^sup>1[_, _, _]\")\n    where \"\\<a>\\<^sup>-\\<^sup>1[a, b, c] \\<equiv> \\<langle>\\<langle>\\<pp>\\<^sub>1[a, b \\<otimes> c], \\<pp>\\<^sub>1[b, c] \\<cdot> \\<pp>\\<^sub>0[a, b \\<otimes> c]\\<rangle>, \\<pp>\\<^sub>0[b, c] \\<cdot> \\<pp>\\<^sub>0[a, b \\<otimes> c]\\<rangle>\"\n\n    lemma assoc_in_hom [intro]:\n    assumes \"ide a\" and \"ide b\" and \"ide c\"\n    shows \"\\<guillemotleft>\\<a>[a, b, c] : (a \\<otimes> b) \\<otimes> c \\<rightarrow> a \\<otimes> (b \\<otimes> c)\\<guillemotright>\"\n      using assms assoc_def by auto\n\n    lemma assoc_simps [simp]:\n    assumes \"ide a\" and \"ide b\" and \"ide c\"\n    shows \"arr \\<a>[a, b, c]\"\n    and \"dom \\<a>[a, b, c] = (a \\<otimes> b) \\<otimes> c\"\n    and \"cod \\<a>[a, b, c] = a \\<otimes> (b \\<otimes> c)\"\n      using assms assoc_in_hom by auto\n\n    lemma assoc'_in_hom [intro]:\n    assumes \"ide a\" and \"ide b\" and \"ide c\"\n    shows \"\\<guillemotleft>\\<a>\\<^sup>-\\<^sup>1[a, b, c] : a \\<otimes> (b \\<otimes> c) \\<rightarrow> (a \\<otimes> b) \\<otimes> c\\<guillemotright>\"\n      using assms assoc'_def by auto\n\n    lemma assoc'_simps [simp]:\n    assumes \"ide a\" and \"ide b\" and \"ide c\"\n    shows \"arr \\<a>\\<^sup>-\\<^sup>1[a, b, c]\"\n    and \"dom \\<a>\\<^sup>-\\<^sup>1[a, b, c] = a \\<otimes> (b \\<otimes> c)\"\n    and \"cod \\<a>\\<^sup>-\\<^sup>1[a, b, c] = (a \\<otimes> b) \\<otimes> c\"\n      using assms assoc'_in_hom by auto\n\n    lemma assoc_naturality:\n    assumes \"\\<guillemotleft>f0 : a0 \\<rightarrow> b0\\<guillemotright>\" and \"\\<guillemotleft>f1 : a1 \\<rightarrow> b1\\<guillemotright>\" and \"\\<guillemotleft>f2 : a2 \\<rightarrow> b2\\<guillemotright>\"\n    shows \"\\<a>[b0, b1, b2] \\<cdot> ((f0 \\<otimes> f1) \\<otimes> f2) = (f0 \\<otimes> (f1 \\<otimes> f2)) \\<cdot> \\<a>[a0, a1, a2]\"\n    proof -\n      have \"\\<pp>\\<^sub>0[b0, b1 \\<otimes> b2] \\<cdot> \\<a>[b0, b1, b2] \\<cdot> ((f0 \\<otimes> f1) \\<otimes> f2) =\n            \\<pp>\\<^sub>0[b0, b1 \\<otimes> b2] \\<cdot> (f0 \\<otimes> (f1 \\<otimes> f2)) \\<cdot> \\<a>[a0, a1, a2]\"\n      proof -\n        have \"\\<pp>\\<^sub>0[b0, b1 \\<otimes> b2] \\<cdot> \\<a>[b0, b1, b2] \\<cdot> ((f0 \\<otimes> f1) \\<otimes> f2) =\n              (\\<pp>\\<^sub>0[b0, b1 \\<otimes> b2] \\<cdot> \\<a>[b0, b1, b2]) \\<cdot> ((f0 \\<otimes> f1) \\<otimes> f2)\"\n          using comp_assoc by simp\n        also have \"... = \\<langle>\\<pp>\\<^sub>0[b0, b1] \\<cdot> \\<pp>\\<^sub>1[b0 \\<otimes> b1, b2], \\<pp>\\<^sub>0[b0 \\<otimes> b1, b2]\\<rangle> \\<cdot> ((f0 \\<otimes> f1) \\<otimes> f2)\"\n          using assms assoc_def by fastforce\n        also have \"... = \\<langle>(\\<pp>\\<^sub>0[b0, b1] \\<cdot> \\<pp>\\<^sub>1[b0 \\<otimes> b1, b2]) \\<cdot> ((f0 \\<otimes> f1) \\<otimes> f2),\n                          \\<pp>\\<^sub>0[b0 \\<otimes> b1, b2] \\<cdot> ((f0 \\<otimes> f1) \\<otimes> f2)\\<rangle>\"\n          using assms comp_tuple_arr by fastforce\n        also have \"... = \\<langle>(\\<pp>\\<^sub>0[b0, b1] \\<cdot> (f0 \\<otimes> f1)) \\<cdot> \\<pp>\\<^sub>1[a0 \\<otimes> a1, a2], f2 \\<cdot> \\<pp>\\<^sub>0[a0 \\<otimes> a1, a2]\\<rangle>\"\n          using assms comp_assoc by fastforce\n        also have \"... = \\<langle>f1 \\<cdot> \\<pp>\\<^sub>0[a0, a1] \\<cdot> \\<pp>\\<^sub>1[a0 \\<otimes> a1, a2], f2 \\<cdot> \\<pp>\\<^sub>0[a0 \\<otimes> a1, a2]\\<rangle>\"\n          using assms comp_assoc\n          by (metis in_homE pr_naturality(1))\n        also have \"... = \\<pp>\\<^sub>0[b0, b1 \\<otimes> b2] \\<cdot> (f0 \\<otimes> (f1 \\<otimes> f2)) \\<cdot> \\<a>[a0, a1, a2]\"\n          using assms comp_assoc assoc_def prod_tuple by fastforce\n        finally show ?thesis by blast\n      qed\n      moreover have \"\\<pp>\\<^sub>1[b0, b1 \\<otimes> b2] \\<cdot> \\<a>[b0, b1, b2] \\<cdot> ((f0 \\<otimes> f1) \\<otimes> f2) =\n                     \\<pp>\\<^sub>1[b0, b1 \\<otimes> b2] \\<cdot> (f0 \\<otimes> (f1 \\<otimes> f2)) \\<cdot> \\<a>[a0, a1, a2]\"\n      proof -\n        have \"\\<pp>\\<^sub>1[b0, b1 \\<otimes> b2] \\<cdot> \\<a>[b0, b1, b2] \\<cdot> ((f0 \\<otimes> f1) \\<otimes> f2) =\n              (\\<pp>\\<^sub>1[b0, b1 \\<otimes> b2] \\<cdot> \\<a>[b0, b1, b2]) \\<cdot> ((f0 \\<otimes> f1) \\<otimes> f2)\"\n          using comp_assoc by simp\n        also have \"... = (\\<pp>\\<^sub>1[b0, b1] \\<cdot> \\<pp>\\<^sub>1[b0 \\<otimes> b1, b2]) \\<cdot> ((f0 \\<otimes> f1) \\<otimes> f2)\"\n          using assms assoc_def by fastforce\n        also have \"... = (\\<pp>\\<^sub>1[b0, b1] \\<cdot> (f0 \\<otimes> f1)) \\<cdot> \\<pp>\\<^sub>1[a0 \\<otimes> a1, a2]\"\n          using assms comp_assoc by fastforce\n        also have \"... = f0 \\<cdot> \\<pp>\\<^sub>1[a0, a1] \\<cdot> \\<pp>\\<^sub>1[a0 \\<otimes> a1, a2]\"\n          using assms comp_assoc\n          by (metis in_homE pr_naturality(2))\n        also have \"... = \\<pp>\\<^sub>1[b0, b1 \\<otimes> b2] \\<cdot> (f0 \\<otimes> (f1 \\<otimes> f2)) \\<cdot> \\<a>[a0, a1, a2]\"\n        proof -\n          have \"\\<pp>\\<^sub>1[b0, b1 \\<otimes> b2] \\<cdot> (f0 \\<otimes> (f1 \\<otimes> f2)) \\<cdot> \\<a>[a0, a1, a2] =\n                (\\<pp>\\<^sub>1[b0, b1 \\<otimes> b2] \\<cdot> (f0 \\<otimes> (f1 \\<otimes> f2))) \\<cdot> \\<a>[a0, a1, a2]\"\n            using comp_assoc by simp\n          also have \"... = f0 \\<cdot> \\<pp>\\<^sub>1[a0, a1 \\<otimes> a2] \\<cdot> \\<a>[a0, a1, a2]\"\n            using assms comp_assoc by fastforce\n          also have \"... = f0 \\<cdot> \\<pp>\\<^sub>1[a0, a1] \\<cdot> \\<pp>\\<^sub>1[a0 \\<otimes> a1, a2]\"\n            using assms assoc_def by fastforce\n          finally show ?thesis by simp\n        qed\n        finally show ?thesis by blast\n      qed\n      ultimately show ?thesis\n        using assms pr_joint_monic [of b0 \"b1 \\<otimes> b2\" \"\\<a>[b0, b1, b2] \\<cdot> ((f0 \\<otimes> f1) \\<otimes> f2)\"\n                                       \"(f0 \\<otimes> (f1 \\<otimes> f2)) \\<cdot> \\<a>[a0, a1, a2]\"]\n        by fastforce\n    qed\n\n    lemma pentagon:\n    assumes \"ide a\" and \"ide b\" and \"ide c\" and \"ide d\"\n    shows \"((a \\<otimes> \\<a>[b, c, d]) \\<cdot> \\<a>[a, b \\<otimes> c, d]) \\<cdot> (\\<a>[a, b, c] \\<otimes> d) = \\<a>[a, b, c \\<otimes> d] \\<cdot> \\<a>[a \\<otimes> b, c, d]\"\n    proof (intro pr_joint_monic\n                   [where h = \"((a \\<otimes> \\<a>[b, c, d]) \\<cdot> \\<a>[a, b \\<otimes> c, d]) \\<cdot> (\\<a>[a, b, c] \\<otimes> d)\"\n                      and h' = \"\\<a>[a, b, c \\<otimes> d] \\<cdot> \\<a>[a \\<otimes> b, c, d]\"])\n      show \"seq \\<pp>\\<^sub>0[a, b \\<otimes> (c \\<otimes> d)] (((a \\<otimes> \\<a>[b, c, d]) \\<cdot> \\<a>[a, b \\<otimes> c, d]) \\<cdot> (\\<a>[a, b, c] \\<otimes> d))\"\n        using assms by simp\n      show \"\\<pp>\\<^sub>1[a, b \\<otimes> c \\<otimes> d] \\<cdot> ((a \\<otimes> \\<a>[b, c, d]) \\<cdot> \\<a>[a, b \\<otimes> c, d]) \\<cdot> (\\<a>[a, b, c] \\<otimes> d) =\n            \\<pp>\\<^sub>1[a, b \\<otimes> c \\<otimes> d] \\<cdot> \\<a>[a, b, c \\<otimes> d] \\<cdot> \\<a>[a \\<otimes> b, c, d]\"\n      proof -\n        have \"\\<pp>\\<^sub>1[a, b \\<otimes> c \\<otimes> d] \\<cdot> ((a \\<otimes> \\<a>[b, c, d]) \\<cdot> \\<a>[a, b \\<otimes> c, d]) \\<cdot> (\\<a>[a, b, c] \\<otimes> d) =\n              ((\\<pp>\\<^sub>1[a, b \\<otimes> c \\<otimes> d] \\<cdot> (a \\<otimes> \\<a>[b, c, d])) \\<cdot> \\<a>[a, b \\<otimes> c, d]) \\<cdot> (\\<a>[a, b, c] \\<otimes> d)\"\n          using comp_assoc by simp\n        also have \"... = (\\<pp>\\<^sub>1[a, (b \\<otimes> c) \\<otimes> d] \\<cdot> \\<a>[a, b \\<otimes> c, d]) \\<cdot> (\\<a>[a, b, c] \\<otimes> d)\"\n          using assms pr_naturality(2) comp_cod_arr by force\n        also have \"... = \\<pp>\\<^sub>1[a, b \\<otimes> c] \\<cdot> \\<pp>\\<^sub>1[a \\<otimes> b \\<otimes> c, d] \\<cdot> (\\<a>[a, b, c] \\<otimes> d)\"\n          using assms assoc_def comp_assoc by simp\n        also have \"... = (\\<pp>\\<^sub>1[a, b \\<otimes> c] \\<cdot> \\<a>[a, b, c]) \\<cdot> \\<pp>\\<^sub>1[(a \\<otimes> b) \\<otimes> c, d]\"\n          using assms pr_naturality(2) comp_assoc by fastforce\n        also have \"... = \\<pp>\\<^sub>1[a, b] \\<cdot> \\<pp>\\<^sub>1[a \\<otimes> b, c] \\<cdot> \\<pp>\\<^sub>1[(a \\<otimes> b) \\<otimes> c, d]\"\n          using assms assoc_def comp_assoc by simp\n        finally have \"\\<pp>\\<^sub>1[a, b \\<otimes> c \\<otimes> d] \\<cdot> ((a \\<otimes> \\<a>[b, c, d]) \\<cdot> \\<a>[a, b \\<otimes> c, d]) \\<cdot> (\\<a>[a, b, c] \\<otimes> d) =\n                      \\<pp>\\<^sub>1[a, b] \\<cdot> \\<pp>\\<^sub>1[a \\<otimes> b, c] \\<cdot> \\<pp>\\<^sub>1[(a \\<otimes> b) \\<otimes> c, d]\"\n          by blast\n        also have \"... = \\<pp>\\<^sub>1[a, b \\<otimes> c \\<otimes> d] \\<cdot> \\<a>[a, b, c \\<otimes> d] \\<cdot> \\<a>[a \\<otimes> b, c, d]\"\n          using assms assoc_def comp_assoc by auto\n        finally show ?thesis by blast\n      qed\n      show \"\\<pp>\\<^sub>0[a, b \\<otimes> (c \\<otimes> d)] \\<cdot> ((a \\<otimes> \\<a>[b, c, d]) \\<cdot> \\<a>[a, b \\<otimes> c, d]) \\<cdot> (\\<a>[a, b, c] \\<otimes> d) =\n            \\<pp>\\<^sub>0[a, b \\<otimes> (c \\<otimes> d)] \\<cdot> \\<a>[a, b, c \\<otimes> d] \\<cdot> \\<a>[a \\<otimes> b, c, d]\"\n      proof -\n        have \"\\<pp>\\<^sub>0[a, b \\<otimes> (c \\<otimes> d)] \\<cdot> ((a \\<otimes> \\<a>[b, c, d]) \\<cdot> \\<a>[a, b \\<otimes> c, d]) \\<cdot> (\\<a>[a, b, c] \\<otimes> d) =\n              \\<pp>\\<^sub>0[a, b \\<otimes> c \\<otimes> d] \\<cdot>\n                ((a \\<otimes> \\<langle>\\<pp>\\<^sub>1[b, c] \\<cdot> \\<pp>\\<^sub>1[b \\<otimes> c, d], \\<langle>\\<pp>\\<^sub>0[b, c] \\<cdot> \\<pp>\\<^sub>1[b \\<otimes> c, d], \\<pp>\\<^sub>0[b \\<otimes> c, d]\\<rangle>\\<rangle>) \\<cdot>\n                 \\<langle>\\<pp>\\<^sub>1[a, b \\<otimes> c] \\<cdot> \\<pp>\\<^sub>1[a \\<otimes> b \\<otimes> c, d],\n                  \\<langle>\\<pp>\\<^sub>0[a, b \\<otimes> c] \\<cdot> \\<pp>\\<^sub>1[a \\<otimes> b \\<otimes> c, d], \\<pp>\\<^sub>0[a \\<otimes> b \\<otimes> c, d]\\<rangle>\\<rangle>) \\<cdot>\n                (\\<langle>\\<pp>\\<^sub>1[a, b] \\<cdot> \\<pp>\\<^sub>1[a \\<otimes> b, c], \\<langle>\\<pp>\\<^sub>0[a, b] \\<cdot> \\<pp>\\<^sub>1[a \\<otimes> b, c], \\<pp>\\<^sub>0[a \\<otimes> b, c]\\<rangle>\\<rangle> \\<otimes> d)\"\n          using assms assoc_def by simp\n        also have \"... = \\<langle>\\<pp>\\<^sub>1[b, c] \\<cdot> \\<pp>\\<^sub>1[b \\<otimes> c, d],\n                          \\<langle>\\<pp>\\<^sub>0[b, c] \\<cdot> \\<pp>\\<^sub>1[b \\<otimes> c, d], \\<pp>\\<^sub>0[b \\<otimes> c, d]\\<rangle>\\<rangle> \\<cdot> (\\<pp>\\<^sub>0[a, (b \\<otimes> c) \\<otimes> d] \\<cdot>\n                            \\<langle>\\<pp>\\<^sub>1[a, b \\<otimes> c] \\<cdot> \\<pp>\\<^sub>1[a \\<otimes> b \\<otimes> c, d],\n                             \\<langle>\\<pp>\\<^sub>0[a, b \\<otimes> c] \\<cdot> \\<pp>\\<^sub>1[a \\<otimes> b \\<otimes> c, d], \\<pp>\\<^sub>0[a \\<otimes> b \\<otimes> c, d]\\<rangle>\\<rangle>) \\<cdot>\n                            (\\<langle>\\<pp>\\<^sub>1[a, b] \\<cdot> \\<pp>\\<^sub>1[a \\<otimes> b, c],\n                              \\<langle>\\<pp>\\<^sub>0[a, b] \\<cdot> \\<pp>\\<^sub>1[a \\<otimes> b, c], \\<pp>\\<^sub>0[a \\<otimes> b, c]\\<rangle>\\<rangle> \\<otimes> d)\"\n        proof -\n          have \"\\<pp>\\<^sub>0[a, b \\<otimes> c \\<otimes> d] \\<cdot>\n                  (a \\<otimes> \\<langle>\\<pp>\\<^sub>1[b, c] \\<cdot> \\<pp>\\<^sub>1[b \\<otimes> c, d], \\<langle>\\<pp>\\<^sub>0[b, c] \\<cdot> \\<pp>\\<^sub>1[b \\<otimes> c, d], \\<pp>\\<^sub>0[b \\<otimes> c, d]\\<rangle>\\<rangle>) =\n                \\<langle>\\<pp>\\<^sub>1[b, c] \\<cdot> \\<pp>\\<^sub>1[b \\<otimes> c, d], \\<langle>\\<pp>\\<^sub>0[b, c] \\<cdot> \\<pp>\\<^sub>1[b \\<otimes> c, d], \\<pp>\\<^sub>0[b \\<otimes> c, d]\\<rangle>\\<rangle> \\<cdot>\n                  \\<pp>\\<^sub>0[a, (b \\<otimes> c) \\<otimes> d]\"\n            using assms assoc_def ide_in_hom pr_naturality(1) by auto\n          thus ?thesis using comp_assoc by metis\n        qed\n        also have \"... = \\<langle>\\<pp>\\<^sub>0[a, b] \\<cdot> \\<pp>\\<^sub>1[a \\<otimes> b, c] \\<cdot> \\<pp>\\<^sub>1[(a \\<otimes> b) \\<otimes> c, d],\n                          \\<langle>\\<pp>\\<^sub>0[a \\<otimes> b, c] \\<cdot> \\<pp>\\<^sub>1[(a \\<otimes> b) \\<otimes> c, d], d \\<cdot> \\<pp>\\<^sub>0[(a \\<otimes> b) \\<otimes> c, d]\\<rangle>\\<rangle>\"\n          using assms comp_assoc by simp\n        also have \"... = \\<langle>\\<pp>\\<^sub>0[a, b] \\<cdot> \\<pp>\\<^sub>1[a \\<otimes> b, c] \\<cdot> \\<pp>\\<^sub>1[(a \\<otimes> b) \\<otimes> c, d],\n                          \\<langle>\\<pp>\\<^sub>0[a \\<otimes> b, c] \\<cdot> \\<pp>\\<^sub>1[(a \\<otimes> b) \\<otimes> c, d], \\<pp>\\<^sub>0[(a \\<otimes> b) \\<otimes> c, d]\\<rangle>\\<rangle>\"\n          using assms comp_cod_arr by simp\n        also have \"... = \\<pp>\\<^sub>0[a, b \\<otimes> (c \\<otimes> d)] \\<cdot> \\<a>[a, b, c \\<otimes> d] \\<cdot> \\<a>[a \\<otimes> b, c, d]\"\n          using assms assoc_def comp_assoc by simp\n        finally show ?thesis by simp\n      qed\n    qed\n\n    lemma inverse_arrows_assoc:\n    assumes \"ide a\" and \"ide b\" and \"ide c\"\n    shows \"inverse_arrows \\<a>[a, b, c] \\<a>\\<^sup>-\\<^sup>1[a, b, c]\"\n      using assms assoc_def assoc'_def comp_assoc\n      by (auto simp add: tuple_pr_arr)\n\n    interpretation CC: product_category C C ..\n\n    abbreviation Prod\n    where \"Prod fg \\<equiv> fst fg \\<otimes> snd fg\"\n    abbreviation Prod'\n    where \"Prod' fg \\<equiv> snd fg \\<otimes> fst fg\"\n\n    interpretation \\<Pi>: binary_functor C C C Prod\n      using tuple_ext CC.comp_char interchange\n      apply unfold_locales\n          apply auto\n      by (metis prod_def seqE)+\n\n    interpretation Prod': binary_functor C C C Prod'\n      using tuple_ext CC.comp_char interchange\n      apply unfold_locales\n          apply auto\n      by (metis prod_def seqE)+\n\n    lemma binary_functor_Prod:\n    shows \"binary_functor C C C Prod\" and \"binary_functor C C C Prod'\"\n      ..\n\n    definition sym (\"\\<s>[_, _]\")\n    where \"\\<s>[a1, a0] \\<equiv> if ide a0 \\<and> ide a1 then \\<langle>\\<pp>\\<^sub>0[a1, a0], \\<pp>\\<^sub>1[a1, a0]\\<rangle> else null\"\n\n    lemma sym_in_hom [intro]:\n    assumes \"ide a\" and \"ide b\"\n    shows \"\\<guillemotleft>\\<s>[a, b] : a \\<otimes> b \\<rightarrow> b \\<otimes> a\\<guillemotright>\"\n      using assms sym_def by auto\n\n    lemma sym_simps [simp]:\n    assumes \"ide a\" and \"ide b\"\n    shows \"arr \\<s>[a, b]\" and \"dom \\<s>[a, b] = a \\<otimes> b\" and \"cod \\<s>[a, b] = b \\<otimes> a\"\n      using assms sym_in_hom by auto\n\n    lemma comp_sym_tuple [simp]:\n    assumes \"\\<guillemotleft>f0 : a \\<rightarrow> b0\\<guillemotright>\" and \"\\<guillemotleft>f1 : a \\<rightarrow> b1\\<guillemotright>\"\n    shows \"\\<s>[b0, b1] \\<cdot> \\<langle>f0, f1\\<rangle> = \\<langle>f1, f0\\<rangle>\"\n      using assms sym_def comp_tuple_arr by fastforce\n\n    lemma prj_sym [simp]:\n    assumes \"ide a0\" and \"ide a1\"\n    shows \"\\<pp>\\<^sub>0[a1, a0] \\<cdot> \\<s>[a0, a1] = \\<pp>\\<^sub>1[a0, a1]\"\n    and \"\\<pp>\\<^sub>1[a1, a0] \\<cdot> \\<s>[a0, a1] = \\<pp>\\<^sub>0[a0, a1]\"\n      using assms sym_def by auto\n\n    lemma comp_sym_sym [simp]:\n    assumes \"ide a0\" and \"ide a1\"\n    shows \"\\<s>[a1, a0] \\<cdot> \\<s>[a0, a1] = (a0 \\<otimes> a1)\"\n      using assms sym_def comp_tuple_arr by auto\n\n    lemma sym_inverse_arrows:\n    assumes \"ide a0\" and \"ide a1\"\n    shows \"inverse_arrows \\<s>[a0, a1] \\<s>[a1, a0]\"\n      using assms sym_in_hom comp_sym_sym by auto\n\n    lemma sym_assoc_coherence:\n    assumes \"ide a\" and \"ide b\" and \"ide c\"\n    shows \"\\<a>[b, c, a] \\<cdot> \\<s>[a, b \\<otimes> c] \\<cdot> \\<a>[a, b, c] = (b \\<otimes> \\<s>[a, c]) \\<cdot> \\<a>[b, a, c] \\<cdot> (\\<s>[a, b] \\<otimes> c)\"\n      using assms sym_def assoc_def comp_assoc prod_tuple comp_cod_arr by simp\n\n    lemma sym_naturality:\n    assumes \"\\<guillemotleft>f0 : a0 \\<rightarrow> b0\\<guillemotright>\" and \"\\<guillemotleft>f1 : a1 \\<rightarrow> b1\\<guillemotright>\"\n    shows \"\\<s>[b0, b1] \\<cdot> (f0 \\<otimes> f1) = (f1 \\<otimes> f0) \\<cdot> \\<s>[a0, a1]\"\n      using assms sym_def comp_assoc prod_tuple by fastforce\n\n    abbreviation \\<sigma>\n    where \"\\<sigma> fg \\<equiv> \\<s>[cod (fst fg), cod (snd fg)] \\<cdot> (fst fg \\<otimes> snd fg)\"\n\n    interpretation \\<sigma>: natural_transformation CC.comp C Prod Prod' \\<sigma>\n      using sym_def CC.arr_char CC.null_char comp_arr_dom comp_cod_arr\n      apply unfold_locales\n          apply auto\n      using arr_cod_iff_arr ideD(1)\n        apply metis\n      using arr_cod_iff_arr ideD(1)\n       apply metis\n      using prod_tuple by simp\n\n    lemma \\<sigma>_is_natural_transformation:\n    shows \"natural_transformation CC.comp C Prod Prod' \\<sigma>\"\n      ..\n\n    abbreviation Diag\n    where \"Diag f \\<equiv> if arr f then (f, f) else CC.null\"\n\n    interpretation \\<Delta>: \"functor\" C CC.comp Diag\n      by (unfold_locales, auto)\n\n    lemma functor_Diag:\n    shows \"functor C CC.comp Diag\"\n      ..\n\n    interpretation \\<Delta>o\\<Pi>: composite_functor CC.comp C CC.comp Prod Diag ..\n    interpretation \\<Pi>o\\<Delta>: composite_functor C CC.comp C Diag Prod ..\n\n    abbreviation \\<pi>\n    where \"\\<pi> \\<equiv> \\<lambda>(f, g). (\\<pp>\\<^sub>1[cod f, cod g] \\<cdot> (f \\<otimes> g), \\<pp>\\<^sub>0[cod f, cod g] \\<cdot> (f \\<otimes> g))\"\n\n    interpretation \\<pi>: transformation_by_components CC.comp CC.comp \\<Delta>o\\<Pi>.map CC.map \\<pi>\n      using pr_naturality comp_arr_dom comp_cod_arr\n      by unfold_locales auto\n\n    lemma \\<pi>_is_natural_transformation:\n    shows \"natural_transformation CC.comp CC.comp \\<Delta>o\\<Pi>.map CC.map \\<pi>\"\n    proof -\n      have \"\\<pi>.map = \\<pi>\"\n        using \\<pi>.map_def ext \\<Pi>.is_extensional comp_arr_dom comp_cod_arr by auto\n      thus \"natural_transformation CC.comp CC.comp \\<Delta>o\\<Pi>.map CC.map \\<pi>\"\n        using \\<pi>.natural_transformation_axioms by simp\n    qed\n\n    interpretation \\<delta>: natural_transformation C C map \\<Pi>o\\<Delta>.map dup\n      using dup_naturality comp_arr_dom comp_cod_arr prod_tuple tuple_ext\n      by unfold_locales auto\n\n    lemma dup_is_natural_transformation:\n    shows \"natural_transformation C C map \\<Pi>o\\<Delta>.map dup\"\n      ..\n\n    interpretation \\<Delta>o\\<Pi>o\\<Delta>: composite_functor C CC.comp CC.comp Diag \\<Delta>o\\<Pi>.map ..\n    interpretation \\<Pi>o\\<Delta>o\\<Pi>: composite_functor CC.comp C C Prod \\<Pi>o\\<Delta>.map ..\n\n    interpretation \\<Delta>o\\<delta>: natural_transformation C CC.comp Diag \\<Delta>o\\<Pi>o\\<Delta>.map \\<open>Diag \\<circ> dup\\<close>\n    proof -\n      have \"Diag \\<circ> map = Diag\"\n        by auto\n      thus \"natural_transformation C CC.comp Diag \\<Delta>o\\<Pi>o\\<Delta>.map (Diag \\<circ> dup)\"\n        using \\<Delta>.as_nat_trans.natural_transformation_axioms \\<delta>.natural_transformation_axioms\n              o_assoc horizontal_composite [of C C map \\<Pi>o\\<Delta>.map dup CC.comp Diag Diag Diag]\n        by metis\n    qed\n\n    interpretation \\<delta>o\\<Pi>: natural_transformation CC.comp C Prod \\<Pi>o\\<Delta>o\\<Pi>.map \\<open>dup \\<circ> Prod\\<close>\n      using \\<delta>.natural_transformation_axioms \\<Pi>.as_nat_trans.natural_transformation_axioms\n            o_assoc horizontal_composite [of CC.comp C Prod Prod Prod C map \\<Pi>o\\<Delta>.map dup]\n      by simp\n\n    interpretation \\<pi>o\\<Delta>: natural_transformation C CC.comp \\<Delta>o\\<Pi>o\\<Delta>.map Diag \\<open>\\<pi>.map \\<circ> Diag\\<close>\n      using \\<pi>.natural_transformation_axioms \\<Delta>.as_nat_trans.natural_transformation_axioms\n            horizontal_composite\n              [of C CC.comp Diag Diag Diag CC.comp \\<Delta>o\\<Pi>.map CC.map \\<pi>.map]\n      by simp\n\n    interpretation \\<Pi>o\\<pi>: natural_transformation CC.comp C \\<Pi>o\\<Delta>o\\<Pi>.map Prod \\<open>Prod \\<circ> \\<pi>.map\\<close>\n    proof -\n      have \"Prod \\<circ> \\<Delta>o\\<Pi>.map = \\<Pi>o\\<Delta>o\\<Pi>.map\"\n        by auto\n      thus \"natural_transformation CC.comp C \\<Pi>o\\<Delta>o\\<Pi>.map Prod (Prod \\<circ> \\<pi>.map)\"\n        using \\<pi>.natural_transformation_axioms \\<Pi>.as_nat_trans.natural_transformation_axioms\n              o_assoc\n              horizontal_composite\n                [of CC.comp CC.comp \\<Delta>o\\<Pi>.map CC.map \\<pi>.map C Prod Prod Prod]\n        by simp\n    qed\n\n    interpretation \\<Delta>o\\<delta>_\\<pi>o\\<Delta>: vertical_composite C CC.comp Diag \\<Delta>o\\<Pi>o\\<Delta>.map Diag\n                               \\<open>Diag \\<circ> dup\\<close> \\<open>\\<pi>.map \\<circ> Diag\\<close>\n      ..\n    interpretation \\<Pi>o\\<pi>_\\<delta>o\\<Pi>: vertical_composite CC.comp C Prod \\<Pi>o\\<Delta>o\\<Pi>.map Prod\n                               \\<open>dup \\<circ> Prod\\<close> \\<open>Prod \\<circ> \\<pi>.map\\<close>\n      ..\n\n    interpretation \\<Delta>\\<Pi>: unit_counit_adjunction CC.comp C Diag Prod dup \\<pi>.map\n    proof\n      show \"\\<Delta>o\\<delta>_\\<pi>o\\<Delta>.map = Diag\"\n      proof\n        fix f\n        have \"\\<not> arr f \\<Longrightarrow> \\<Delta>o\\<delta>_\\<pi>o\\<Delta>.map f = Diag f\"\n          by (simp add: \\<Delta>o\\<delta>_\\<pi>o\\<Delta>.is_extensional)\n        moreover have \"arr f \\<Longrightarrow> \\<Delta>o\\<delta>_\\<pi>o\\<Delta>.map f = Diag f\"\n          using comp_cod_arr comp_assoc \\<Delta>o\\<delta>_\\<pi>o\\<Delta>.map_def by auto\n        ultimately show \"\\<Delta>o\\<delta>_\\<pi>o\\<Delta>.map f = Diag f\" by blast\n      qed\n      show \"\\<Pi>o\\<pi>_\\<delta>o\\<Pi>.map = Prod\"\n      proof\n        fix fg\n        show \"\\<Pi>o\\<pi>_\\<delta>o\\<Pi>.map fg = Prod fg\"\n        proof -\n          have \"\\<not> CC.arr fg \\<Longrightarrow> ?thesis\"\n            by (simp add: \\<Pi>.is_extensional \\<Pi>o\\<pi>_\\<delta>o\\<Pi>.is_extensional)\n          moreover have \"CC.arr fg \\<Longrightarrow> ?thesis\"\n          proof -\n            assume fg: \"CC.arr fg\"\n            have 1: \"dup (Prod fg) = \\<langle>cod (fst fg) \\<otimes> cod (snd fg), cod (fst fg) \\<otimes> cod (snd fg)\\<rangle> \\<cdot>\n                                        (fst fg \\<otimes> snd fg)\"\n              using fg \\<delta>.is_natural_2\n              apply simp\n              by (metis (no_types, lifting) prod_simps(1) prod_simps(3))\n            have \"\\<Pi>o\\<pi>_\\<delta>o\\<Pi>.map fg =\n                  (\\<pp>\\<^sub>1[cod (fst fg), cod (snd fg)] \\<otimes> \\<pp>\\<^sub>0[cod (fst fg), cod (snd fg)]) \\<cdot>\n                    \\<langle>cod (fst fg) \\<otimes> cod (snd fg), cod (fst fg) \\<otimes> cod (snd fg)\\<rangle> \\<cdot>\n                    (fst fg \\<otimes> snd fg)\"\n              using fg 1 \\<Pi>o\\<pi>_\\<delta>o\\<Pi>.map_def comp_cod_arr by simp\n            also have \"... = ((\\<pp>\\<^sub>1[cod (fst fg), cod (snd fg)] \\<otimes> \\<pp>\\<^sub>0[cod (fst fg), cod (snd fg)]) \\<cdot>\n                              \\<langle>cod (fst fg) \\<otimes> cod (snd fg), cod (fst fg) \\<otimes> cod (snd fg)\\<rangle>) \\<cdot>\n                             (fst fg \\<otimes> snd fg)\"\n              using comp_assoc by simp\n            also have \"... = \\<langle>\\<pp>\\<^sub>1[cod (fst fg), cod (snd fg)] \\<cdot> (cod (fst fg) \\<otimes> cod (snd fg)),\n                              \\<pp>\\<^sub>0[cod (fst fg), cod (snd fg)] \\<cdot> (cod (fst fg) \\<otimes> cod (snd fg))\\<rangle> \\<cdot>\n                             (fst fg \\<otimes> snd fg)\"\n              using fg prod_tuple by simp\n            also have \"... = Prod fg\"\n              using fg comp_arr_dom \\<Pi>.as_nat_trans.is_natural_2 by auto\n            finally show ?thesis by simp\n          qed\n          ultimately show ?thesis by blast\n        qed\n      qed\n    qed\n\n    proposition induces_unit_counit_adjunction:\n    shows \"unit_counit_adjunction CC.comp C Diag Prod dup \\<pi>.map\"\n      using \\<Delta>\\<Pi>.unit_counit_adjunction_axioms by simp\n\n  end\n\n  section \"Category with Terminal Object\"\n\n  locale category_with_terminal_object =\n    category +\n  assumes has_terminal: \"\\<exists>t. terminal t\"\n\n  locale elementary_category_with_terminal_object =\n    category C\n  for C :: \"'a comp\"                              (infixr \"\\<cdot>\" 55)\n  and one :: \"'a\"                                 (\"\\<one>\")\n  and trm :: \"'a \\<Rightarrow> 'a\"                           (\"\\<t>[_]\") +\n  assumes ide_one: \"ide \\<one>\"\n  and trm_in_hom_ax: \"ide a \\<Longrightarrow> \\<guillemotleft>\\<t>[a] : a \\<rightarrow> \\<one>\\<guillemotright>\"\n  and trm_eqI_ax: \"\\<lbrakk> ide a; \\<guillemotleft>f : a \\<rightarrow> \\<one>\\<guillemotright> \\<rbrakk> \\<Longrightarrow> f = \\<t>[a]\"\n  begin\n\n    lemma trm_simps_ide:\n    assumes \"ide a\"\n    shows \"arr \\<t>[a]\" and \"dom \\<t>[a] = a\" and \"cod \\<t>[a] = \\<one>\"\n      using assms trm_in_hom_ax by auto\n\n    lemma trm_one:\n    shows \"\\<t>[\\<one>] = \\<one>\"\n    using ide_one trm_in_hom_ax trm_eqI_ax ide_in_hom by auto\n\n    lemma terminal_one:\n    shows \"terminal \\<one>\"\n      using ide_one trm_in_hom_ax trm_eqI_ax terminal_def by metis\n\n    lemma trm_naturality:\n    assumes \"arr f\"\n    shows \"\\<t>[cod f] \\<cdot> f = \\<t>[dom f]\"\n      using assms trm_eqI_ax\n      by (metis comp_in_homI' ide_cod ide_dom in_homE trm_in_hom_ax)\n\n    proposition is_category_with_terminal_object:\n    shows \"category_with_terminal_object C\"\n      apply unfold_locales\n      using terminal_one by auto\n\n  end\n\n  context category_with_terminal_object\n  begin\n\n    definition some_terminal (\"\\<one>\")\n    where \"some_terminal \\<equiv> SOME t. terminal t\"\n\n    definition \"trm\" (\"\\<t>[_]\")\n    where \"\\<t>[f] \\<equiv> if arr f then THE t. \\<guillemotleft>t : dom f \\<rightarrow> \\<one>\\<guillemotright> else null\"\n\n    lemma terminal_some_terminal [intro]:\n    shows \"terminal \\<one>\"\n      using some_terminal_def has_terminal someI_ex [of \"\\<lambda>t. terminal t\"] by presburger\n\n    lemma ide_some_terminal:\n    shows \"ide \\<one>\"\n      using terminal_def by blast\n\n    lemma trm_in_hom [intro]:\n    assumes \"arr f\"\n    shows \"\\<guillemotleft>\\<t>[f] : dom f \\<rightarrow> \\<one>\\<guillemotright>\"\n    proof -\n      have \"ide (dom f)\" using assms by fastforce\n      hence \"\\<exists>!t. \\<guillemotleft>t : dom f \\<rightarrow> \\<one>\\<guillemotright>\"\n        using assms trm_def terminal_def terminal_some_terminal by simp\n      thus ?thesis\n        using assms trm_def [of f] theI' [of \"\\<lambda>t. \\<guillemotleft>t : dom f \\<rightarrow> \\<one>\\<guillemotright>\"] by auto\n    qed\n\n    lemma trm_simps [simp]:\n    assumes \"arr f\"\n    shows \"arr \\<t>[f]\" and \"dom \\<t>[f] = dom f\" and \"cod \\<t>[f] = \\<one>\"\n      using assms trm_in_hom by auto\n\n    lemma trm_eqI:\n    assumes \"\\<guillemotleft>t : dom f \\<rightarrow> \\<one>\\<guillemotright>\"\n    shows \"t = \\<t>[f]\"\n    proof -\n      have \"ide (dom f)\" using assms\n        by (metis ide_dom in_homE)\n      hence \"\\<exists>!t. \\<guillemotleft>t : dom f \\<rightarrow> \\<one>\\<guillemotright>\"\n        using terminal_def [of \\<one>] terminal_some_terminal by auto\n      moreover have \"\\<guillemotleft>t : dom f \\<rightarrow> \\<one>\\<guillemotright>\"\n        using assms by simp\n      ultimately show ?thesis\n        using assms trm_def the1_equality [of \"\\<lambda>t. \\<guillemotleft>t : dom f \\<rightarrow> \\<one>\\<guillemotright>\" t]\n              \\<open>ide (dom f)\\<close> arr_dom_iff_arr\n        by fastforce\n    qed\n\n    sublocale elementary_category_with_terminal_object C \\<one> trm\n      using ide_some_terminal trm_eqI\n      by unfold_locales auto\n\n    proposition extends_to_elementary_category_with_terminal_object:\n      shows \"elementary_category_with_terminal_object C \\<one> trm\"\n      ..\n\n  end\n\n  section \"Cartesian Category\"\n\n  locale cartesian_category =\n    category_with_binary_products +\n    category_with_terminal_object\n\n  locale category_with_pullbacks_and_terminal_object =\n    category_with_pullbacks +\n    category_with_terminal_object\n  begin\n\n    sublocale category_with_binary_products C\n    proof\n      show \"has_binary_products\"\n      proof -\n        have \"\\<And>a0 a1. \\<lbrakk>ide a0; ide a1\\<rbrakk> \\<Longrightarrow> \\<exists>p0 p1. has_as_binary_product a0 a1 p0 p1\"\n        proof -\n          fix a0 a1\n          assume a0: \"ide a0\" and a1: \"ide a1\"\n          obtain p0 p1 where p0p1: \"has_as_pullback \\<t>[a0] \\<t>[a1] p0 p1\"\n            using a0 a1 has_pullbacks has_pullbacks_def by force\n          have \"has_as_binary_product a0 a1 p0 p1\"\n            using a0 a1 p0p1\n            apply (elim has_as_pullbackE, intro has_as_binary_productI)\n                apply blast\n               apply blast\n              apply fastforce\n             apply fastforce\n          proof -\n            fix x f g\n            assume f: \"\\<guillemotleft>f : x \\<rightarrow> a0\\<guillemotright>\" and g: \"\\<guillemotleft>g : x \\<rightarrow> a1\\<guillemotright>\"\n            assume \"\\<And>h k. commutative_square \\<t>[a0] \\<t>[a1] h k \\<Longrightarrow> \\<exists>!l. p0 \\<cdot> l = h \\<and> p1 \\<cdot> l = k\"\n            moreover have \"commutative_square \\<t>[a0] \\<t>[a1] f g\"\n              using f g\n              by (metis a0 commutative_squareI in_homE\n                        elementary_category_with_terminal_object.trm_simps_ide(2)\n                        extends_to_elementary_category_with_terminal_object\n                        has_as_pullbackE p0p1 trm_naturality)\n            moreover have \"\\<And>l. p0 \\<cdot> l = f \\<and> p1 \\<cdot> l = g \\<Longrightarrow> \\<guillemotleft>l : x \\<rightarrow> dom p1\\<guillemotright>\"\n              using f g by blast\n            ultimately show \"\\<exists>!l. \\<guillemotleft>l : x \\<rightarrow> dom p1\\<guillemotright> \\<and> p0 \\<cdot> l = f \\<and> p1 \\<cdot> l = g\"\n              by metis\n          qed\n          thus \"\\<exists>p0 p1. has_as_binary_product a0 a1 p0 p1\"\n            by auto\n        qed\n        thus ?thesis\n          using has_binary_products_def by force\n      qed\n    qed\n\n    sublocale cartesian_category C ..\n\n  end\n\n  locale elementary_cartesian_category =\n    elementary_category_with_binary_products +\n    elementary_category_with_terminal_object\n  begin\n\n    proposition is_cartesian_category:\n    shows \"cartesian_category C\"\n      using cartesian_category.intro is_category_with_binary_products\n            is_category_with_terminal_object\n      by auto\n\n  end\n\n  context cartesian_category\n  begin\n\n    proposition extends_to_elementary_cartesian_category:\n    shows \"elementary_cartesian_category C pr0 pr1 \\<one> trm\"\n      by (simp add: elementary_cartesian_category_def\n          elementary_category_with_terminal_object_axioms\n          extends_to_elementary_category_with_binary_products)\n\n    sublocale elementary_cartesian_category C pr0 pr1 \\<one> trm\n      using extends_to_elementary_cartesian_category by simp\n\n  end\n\n  text \\<open>\n    Here we prove some facts that will later allow us to show that an elementary cartesian\n    category is a monoidal category.\n  \\<close>\n\n  context elementary_cartesian_category\n  begin\n\n    abbreviation \\<iota>\n    where \"\\<iota> \\<equiv> \\<pp>\\<^sub>0[\\<one>, \\<one>]\"\n\n    lemma pr_coincidence:\n    shows \"\\<iota> = \\<pp>\\<^sub>1[\\<one>, \\<one>]\"\n      using ide_one\n      by (simp add: terminal_arr_unique terminal_one)\n\n    lemma \\<iota>_is_terminal_arr:\n    shows \"terminal_arr \\<iota>\"\n      using ide_one\n      by (simp add: terminal_one)\n\n    lemma inverse_arrows_\\<iota>:\n    shows \"inverse_arrows \\<iota> \\<langle>\\<one>, \\<one>\\<rangle>\"\n      using ide_one\n      by (metis (no_types, lifting) dup_is_natural_transformation \\<iota>_is_terminal_arr cod_pr0\n          comp_cod_arr pr_dup(1) ide_dom inverse_arrows_def map_simp\n          natural_transformation.is_natural_2 pr_simps(2) pr1_in_hom' trm_eqI_ax trm_naturality\n          trm_one tuple_pr)\n\n    lemma \\<iota>_is_iso:\n    shows \"iso \\<iota>\"\n      using inverse_arrows_\\<iota> by auto\n\n    lemma trm_tensor:\n    assumes \"ide a\" and \"ide b\"\n    shows \"\\<t>[a \\<otimes> b] = \\<iota> \\<cdot> (\\<t>[a] \\<otimes> \\<t>[b])\"\n    proof -\n      have \"\\<t>[a \\<otimes> b] = \\<t>[a] \\<cdot> \\<pp>\\<^sub>1[a, b]\"\n        by (metis assms(1-2) cod_pr1 pr_simps(4-6) trm_naturality)\n      moreover have \"\\<guillemotleft>\\<t>[b] : b \\<rightarrow> \\<one>\\<guillemotright>\"\n        using assms(2) trm_in_hom_ax by blast\n      ultimately show ?thesis\n        using assms(1) pr_coincidence trm_in_hom_ax by fastforce\n    qed\n\n    abbreviation runit (\"\\<r>[_]\")\n    where \"\\<r>[a] \\<equiv> \\<pp>\\<^sub>1[a, \\<one>]\"\n\n    abbreviation runit' (\"\\<r>\\<^sup>-\\<^sup>1[_]\")\n    where \"\\<r>\\<^sup>-\\<^sup>1[a] \\<equiv> \\<langle>a, \\<t>[a]\\<rangle>\"\n\n    abbreviation lunit (\"\\<l>[_]\")\n    where \"\\<l>[a] \\<equiv> \\<pp>\\<^sub>0[\\<one>, a]\"\n\n    abbreviation lunit' (\"\\<l>\\<^sup>-\\<^sup>1[_]\")\n    where \"\\<l>\\<^sup>-\\<^sup>1[a] \\<equiv> \\<langle>\\<t>[a], a\\<rangle>\"\n\n    lemma runit_in_hom:\n    assumes \"ide a\"\n    shows \"\\<guillemotleft>\\<r>[a] : a \\<otimes> \\<one> \\<rightarrow> a\\<guillemotright>\"\n     using assms ide_one by simp\n\n    lemma runit'_in_hom:\n    assumes \"ide a\"\n    shows \"\\<guillemotleft>\\<r>\\<^sup>-\\<^sup>1[a] : a \\<rightarrow> a \\<otimes> \\<one>\\<guillemotright>\"\n      using assms ide_in_hom trm_in_hom_ax by blast\n\n    lemma lunit_in_hom:\n    assumes \"ide a\"\n    shows \"\\<guillemotleft>\\<l>[a] : \\<one> \\<otimes> a \\<rightarrow> a\\<guillemotright>\"\n     using assms ide_one by simp\n\n    lemma lunit'_in_hom:\n    assumes \"ide a\"\n    shows \"\\<guillemotleft>\\<l>\\<^sup>-\\<^sup>1[a] : a \\<rightarrow> \\<one> \\<otimes> a\\<guillemotright>\"\n      using assms ide_in_hom trm_in_hom_ax by blast\n\n    lemma runit_naturality:\n    assumes \"ide a\"\n    shows \"\\<r>[cod a] \\<cdot> (a \\<otimes> \\<one>) = a \\<cdot> \\<r>[dom a]\"\n      using assms pr_naturality(2) ide_char ide_one by blast\n\n    lemma inverse_arrows_runit:\n    assumes \"ide a\"\n    shows \"inverse_arrows \\<r>[a] \\<r>\\<^sup>-\\<^sup>1[a]\"\n    proof\n      show \"ide (\\<r>[a] \\<cdot> \\<r>\\<^sup>-\\<^sup>1[a])\"\n      proof -\n        have \"\\<r>[a] \\<cdot> \\<r>\\<^sup>-\\<^sup>1[a] = a\"\n          using assms\n          by (metis in_homE ide_char pr_tuple(1) trm_in_hom_ax)\n        thus ?thesis\n          using assms by presburger\n      qed\n      show \"ide (\\<r>\\<^sup>-\\<^sup>1[a] \\<cdot> \\<r>[a])\"\n      proof -\n        have \"ide (a \\<otimes> \\<one>)\"\n          using assms ide_one by blast\n        moreover have \"\\<r>\\<^sup>-\\<^sup>1[a] \\<cdot> \\<r>[a] = a \\<otimes> \\<one>\"\n        proof (intro pr_joint_monic [of a \\<one> \"\\<r>\\<^sup>-\\<^sup>1[a] \\<cdot> \\<r>[a]\" \"a \\<otimes> \\<one>\"])\n          show \"seq \\<pp>\\<^sub>0[a, \\<one>] (\\<r>\\<^sup>-\\<^sup>1[a] \\<cdot> \\<r>[a])\"\n            using assms ide_one runit'_in_hom [of a]\n            by (intro seqI) auto\n          show \"\\<pp>\\<^sub>0[a, \\<one>] \\<cdot> \\<r>\\<^sup>-\\<^sup>1[a] \\<cdot> \\<r>[a] = \\<pp>\\<^sub>0[a, \\<one>] \\<cdot> (a \\<otimes> \\<one>)\"\n          proof -\n            have \"\\<pp>\\<^sub>0[a, \\<one>] \\<cdot> \\<r>\\<^sup>-\\<^sup>1[a] \\<cdot> \\<r>[a] = (\\<pp>\\<^sub>0[a, \\<one>] \\<cdot> \\<r>\\<^sup>-\\<^sup>1[a]) \\<cdot> \\<r>[a]\"\n              using comp_assoc by simp\n            also have \"... = \\<t>[a] \\<cdot> \\<r>[a]\"\n              using assms ide_one\n              by (metis in_homE pr_tuple(2) ide_char trm_in_hom_ax)\n            also have \"... = \\<t>[a \\<otimes> \\<one>]\"\n              using assms ide_one trm_naturality [of \"\\<r>[a]\"] by simp\n            also have \"... = \\<pp>\\<^sub>0[a, \\<one>] \\<cdot> (a \\<otimes> \\<one>)\"\n              using assms comp_arr_dom ide_one trm_naturality trm_one by fastforce\n            finally show ?thesis by blast\n          qed\n          show \"\\<pp>\\<^sub>1[a, \\<one>] \\<cdot> \\<r>\\<^sup>-\\<^sup>1[a] \\<cdot> \\<r>[a] = \\<pp>\\<^sub>1[a, \\<one>] \\<cdot> (a \\<otimes> \\<one>)\"\n            using assms\n            by (metis \\<open>ide (\\<r>[a] \\<cdot> \\<r>\\<^sup>-\\<^sup>1[a])\\<close> cod_comp cod_pr1 dom_comp ide_compE ide_one\n                comp_assoc runit_naturality)\n        qed\n        ultimately show ?thesis by simp\n      qed\n    qed\n\n    lemma lunit_naturality:\n    assumes \"arr f\"\n    shows \"C \\<l>[cod f] (\\<one> \\<otimes> f) = C f \\<l>[dom f]\"\n      using assms pr_naturality(1) ide_char ide_one by blast\n\n    lemma inverse_arrows_lunit:\n    assumes \"ide a\"\n    shows \"inverse_arrows \\<l>[a] \\<l>\\<^sup>-\\<^sup>1[a]\"\n    proof\n      show \"ide (C \\<l>[a] \\<l>\\<^sup>-\\<^sup>1[a])\"\n      proof -\n        have \"C \\<l>[a] \\<l>\\<^sup>-\\<^sup>1[a] = a\"\n          using assms\n          by (metis ide_char in_homE pr_tuple(2) trm_in_hom_ax)\n        thus ?thesis\n          using assms by simp\n      qed\n      show \"ide (\\<l>\\<^sup>-\\<^sup>1[a] \\<cdot> \\<l>[a])\"\n      proof -\n        have \"\\<l>\\<^sup>-\\<^sup>1[a] \\<cdot> \\<l>[a] = \\<one> \\<otimes> a\"\n        proof (intro pr_joint_monic [of \\<one> a \"\\<l>\\<^sup>-\\<^sup>1[a] \\<cdot> \\<l>[a]\" \"\\<one> \\<otimes> a\"])\n          show \"seq \\<l>[a] (\\<l>\\<^sup>-\\<^sup>1[a] \\<cdot> \\<l>[a])\"\n            using assms \\<open>ide (\\<l>[a] \\<cdot> \\<l>\\<^sup>-\\<^sup>1[a])\\<close> by blast\n          show \"\\<l>[a] \\<cdot> \\<l>\\<^sup>-\\<^sup>1[a] \\<cdot> \\<l>[a] = \\<l>[a] \\<cdot> (\\<one> \\<otimes> a)\"\n            using assms\n            by (metis \\<open>ide (\\<l>[a] \\<cdot> \\<l>\\<^sup>-\\<^sup>1[a])\\<close> cod_comp cod_pr0 dom_cod ide_compE ide_one\n                comp_assoc lunit_naturality)\n          show \"\\<pp>\\<^sub>1[\\<one>, a] \\<cdot> \\<l>\\<^sup>-\\<^sup>1[a] \\<cdot> \\<l>[a] = \\<pp>\\<^sub>1[\\<one>, a] \\<cdot> (\\<one> \\<otimes> a)\"\n          proof -\n            have \"\\<pp>\\<^sub>1[\\<one>, a] \\<cdot> \\<l>\\<^sup>-\\<^sup>1[a] \\<cdot> \\<l>[a] = (\\<pp>\\<^sub>1[\\<one>, a] \\<cdot> \\<l>\\<^sup>-\\<^sup>1[a]) \\<cdot> \\<l>[a]\"\n              using comp_assoc by simp\n            also have \"... = \\<t>[a] \\<cdot> \\<l>[a]\"\n              using assms ide_one\n              by (metis pr_tuple(1) ide_char in_homE trm_in_hom_ax)\n            also have \"... = \\<t>[\\<one> \\<otimes> a]\"\n              using assms ide_one trm_naturality [of \"\\<l>[a]\"] by simp\n            also have \"... = \\<pp>\\<^sub>1[\\<one>, a] \\<cdot> (\\<one> \\<otimes> a)\"\n              using assms comp_arr_dom ide_one trm_naturality trm_one by fastforce\n            finally show ?thesis by simp\n          qed\n        qed\n        moreover have \"ide (\\<one> \\<otimes> a)\"\n          using assms ide_one by simp\n        finally show ?thesis by blast\n      qed\n    qed\n\n    lemma comp_lunit_term_dup:\n    assumes \"ide a\"\n    shows \"\\<l>[a] \\<cdot> (\\<t>[a] \\<otimes> a) \\<cdot> \\<d>[a] = a\"\n    proof -\n      have \"\\<guillemotleft>\\<t>[a] : a \\<rightarrow> \\<one>\\<guillemotright>\"\n        using assms trm_in_hom_ax by blast\n      hence \"\\<l>[a] \\<cdot> (\\<t>[a] \\<otimes> a) = a \\<cdot> \\<pp>\\<^sub>0[a, a]\"\n        by (metis assms pr_naturality(1) ide_char in_homE)\n      thus ?thesis\n        by (metis (no_types) assms comp_assoc comp_ide_self pr_dup(1))\n    qed\n\n    lemma comp_runit_term_dup:\n    assumes \"ide a\"\n    shows \"\\<r>[a] \\<cdot> (a \\<otimes> \\<t>[a]) \\<cdot> \\<d>[a] = a\"\n    proof -\n      have \"\\<guillemotleft>\\<t>[a] : a \\<rightarrow> \\<one>\\<guillemotright>\"\n        using assms trm_in_hom_ax by blast\n      hence \"\\<r>[a] \\<cdot> (a \\<otimes> \\<t>[a]) = a \\<cdot> \\<pp>\\<^sub>1[a, a]\"\n        using assms by auto\n      thus ?thesis\n        using assms\n        by (metis comp_ide_arr pr_dup(2) ide_char comp_assoc seqI)\n    qed\n\n    lemma comp_proj_assoc:\n    assumes \"ide a0\" and \"ide a1\" and \"ide a2\"\n    shows \"\\<pp>\\<^sub>1[a0, a1 \\<otimes> a2] \\<cdot> \\<a>[a0, a1, a2] = \\<pp>\\<^sub>1[a0, a1] \\<cdot> \\<pp>\\<^sub>1[a0 \\<otimes> a1, a2]\"\n    and \"\\<pp>\\<^sub>0[a0, a1 \\<otimes> a2] \\<cdot> \\<a>[a0, a1, a2] = \\<langle>\\<pp>\\<^sub>0[a0, a1] \\<cdot> \\<pp>\\<^sub>1[a0 \\<otimes> a1, a2], \\<pp>\\<^sub>0[a0 \\<otimes> a1, a2]\\<rangle>\"\n      using assms assoc_def by auto\n\n    lemma dup_coassoc:\n    assumes \"ide a\"\n    shows \"\\<a>[a, a, a] \\<cdot> (\\<d>[a] \\<otimes> a) \\<cdot> \\<d>[a] = (a \\<otimes> \\<d>[a]) \\<cdot> \\<d>[a]\"\n    proof (intro pr_joint_monic\n                   [of a \"a \\<otimes> a\" \"\\<a>[a, a, a] \\<cdot> (\\<d>[a] \\<otimes> a) \\<cdot> \\<d>[a]\" \"(a \\<otimes> \\<d>[a]) \\<cdot> \\<d>[a]\"])\n      show \"seq \\<pp>\\<^sub>0[a, a \\<otimes> a] (\\<a>[a, a, a] \\<cdot> (\\<d>[a] \\<otimes> a) \\<cdot> \\<d>[a])\"\n        using assms by simp\n      show \"\\<pp>\\<^sub>0[a, a \\<otimes> a] \\<cdot> \\<a>[a, a, a] \\<cdot> (\\<d>[a] \\<otimes> a) \\<cdot> \\<d>[a] = \\<pp>\\<^sub>0[a, a \\<otimes> a] \\<cdot> (a \\<otimes> \\<d>[a]) \\<cdot> \\<d>[a]\"\n      proof -\n        have \"\\<pp>\\<^sub>0[a, a \\<otimes> a] \\<cdot> \\<a>[a, a, a] \\<cdot> (\\<d>[a] \\<otimes> a) \\<cdot> \\<d>[a] =\n              ((\\<pp>\\<^sub>0[a, a \\<otimes> a] \\<cdot> \\<a>[a, a, a]) \\<cdot> (\\<d>[a] \\<otimes> a)) \\<cdot> \\<d>[a]\"\n          using comp_assoc by simp\n        also have \"... = \\<langle>((\\<pp>\\<^sub>0[a, a] \\<cdot> \\<pp>\\<^sub>1[a \\<otimes> a, a]) \\<cdot> (\\<d>[a] \\<otimes> a)) \\<cdot> \\<d>[a], (a \\<cdot> \\<pp>\\<^sub>0[a, a]) \\<cdot> \\<d>[a]\\<rangle>\"\n          using assms assoc_def by simp\n        also have \"... = \\<d>[a]\"\n          using assms comp_assoc by simp\n        also have \"... = (\\<pp>\\<^sub>0[a, a \\<otimes> a] \\<cdot> (a \\<otimes> \\<d>[a])) \\<cdot> \\<d>[a]\"\n          using assms assoc_def comp_assoc by simp\n        also have \"... = \\<pp>\\<^sub>0[a, a \\<otimes> a] \\<cdot> (a \\<otimes> \\<d>[a]) \\<cdot> \\<d>[a]\"\n          using comp_assoc by simp\n        finally show ?thesis by blast\n      qed\n      show \"\\<pp>\\<^sub>1[a, a \\<otimes> a] \\<cdot> \\<a>[a, a, a] \\<cdot> (\\<d>[a] \\<otimes> a) \\<cdot> \\<d>[a] = \\<pp>\\<^sub>1[a, a \\<otimes> a] \\<cdot> (a \\<otimes> \\<d>[a]) \\<cdot> \\<d>[a]\"\n      proof -\n        have \"\\<pp>\\<^sub>1[a, a \\<otimes> a] \\<cdot> \\<a>[a, a, a] \\<cdot> (\\<d>[a] \\<otimes> a) \\<cdot> \\<d>[a] =\n              ((\\<pp>\\<^sub>1[a, a \\<otimes> a] \\<cdot> \\<a>[a, a, a]) \\<cdot> (\\<d>[a] \\<otimes> a)) \\<cdot> \\<d>[a]\"\n          using comp_assoc by simp\n        also have \"... = ((\\<pp>\\<^sub>1[a, a] \\<cdot> \\<pp>\\<^sub>1[a \\<otimes> a, a]) \\<cdot> (\\<d>[a] \\<otimes> a)) \\<cdot> \\<d>[a]\"\n          using assms assoc_def by simp\n        also have \"... = a\"\n          using assms comp_assoc by simp\n        also have \"... = (a \\<cdot> \\<pp>\\<^sub>1[a, a]) \\<cdot> \\<d>[a]\"\n          using assms comp_assoc by simp\n        also have \"... = (\\<pp>\\<^sub>1[a, a \\<otimes> a] \\<cdot> (a \\<otimes> \\<d>[a])) \\<cdot> \\<d>[a]\"\n          using assms by simp\n        also have \"... = \\<pp>\\<^sub>1[a, a \\<otimes> a] \\<cdot> (a \\<otimes> \\<d>[a]) \\<cdot> \\<d>[a]\"\n          using comp_assoc by simp\n        finally show ?thesis by blast\n      qed\n    qed\n\n    lemma comp_assoc_tuple:\n    assumes \"\\<guillemotleft>f0 : a \\<rightarrow> b0\\<guillemotright>\" and \"\\<guillemotleft>f1 : a \\<rightarrow> b1\\<guillemotright>\" and \"\\<guillemotleft>f2 : a \\<rightarrow> b2\\<guillemotright>\"\n    shows \"\\<a>[b0, b1, b2] \\<cdot> \\<langle>\\<langle>f0, f1\\<rangle>, f2\\<rangle> = \\<langle>f0, \\<langle>f1, f2\\<rangle>\\<rangle>\"\n    and \"\\<a>\\<^sup>-\\<^sup>1[b0, b1, b2] \\<cdot> \\<langle>f0, \\<langle>f1, f2\\<rangle>\\<rangle> = \\<langle>\\<langle>f0, f1\\<rangle>, f2\\<rangle>\"\n      using assms assoc_def assoc'_def comp_assoc by fastforce+\n\n    lemma dup_tensor:\n    assumes \"ide a\" and \"ide b\"\n    shows \"\\<d>[a \\<otimes> b] = \\<a>\\<^sup>-\\<^sup>1[a, b, a \\<otimes> b] \\<cdot> (a \\<otimes> \\<a>[b, a, b]) \\<cdot> (a \\<otimes> \\<sigma> (a, b) \\<otimes> b) \\<cdot>\n                        (a \\<otimes> \\<a>\\<^sup>-\\<^sup>1[a, b, b]) \\<cdot> \\<a>[a, a, b \\<otimes> b] \\<cdot> (\\<d>[a] \\<otimes> \\<d>[b])\"\n    proof (intro pr_joint_monic [of \"a \\<otimes> b\" \"a \\<otimes> b\" \"\\<d>[a \\<otimes> b]\"])\n      show \"seq \\<pp>\\<^sub>0[a \\<otimes> b, a \\<otimes> b] (\\<d>[a \\<otimes> b])\"\n        using assms by simp\n      have 1: \"\\<a>\\<^sup>-\\<^sup>1[a, b, a \\<otimes> b] \\<cdot> (a \\<otimes> \\<a>[b, a, b]) \\<cdot> (a \\<otimes> \\<sigma> (a, b) \\<otimes> b) \\<cdot>\n                 (a \\<otimes> \\<a>\\<^sup>-\\<^sup>1[a, b, b]) \\<cdot> \\<a>[a, a, b \\<otimes> b] \\<cdot> (\\<d>[a] \\<otimes> \\<d>[b]) =\n               \\<langle>a \\<otimes> b, a \\<otimes> b\\<rangle>\"\n      proof -\n        have \"\\<a>\\<^sup>-\\<^sup>1[a, b, a \\<otimes> b] \\<cdot> (a \\<otimes> \\<a>[b, a, b]) \\<cdot> (a \\<otimes> \\<sigma> (a, b) \\<otimes> b) \\<cdot>\n              (a \\<otimes> \\<a>\\<^sup>-\\<^sup>1[a, b, b]) \\<cdot> \\<a>[a, a, b \\<otimes> b] \\<cdot> (\\<d>[a] \\<otimes> \\<d>[b])\n                = \\<a>\\<^sup>-\\<^sup>1[a, b, a \\<otimes> b] \\<cdot> (a \\<otimes> \\<a>[b, a, b]) \\<cdot> (a \\<otimes> \\<sigma> (a, b) \\<otimes> b) \\<cdot>\n                  (a \\<otimes> \\<a>\\<^sup>-\\<^sup>1[a, b, b]) \\<cdot> \\<langle>\\<pp>\\<^sub>1[a, b], \\<langle>\\<pp>\\<^sub>1[a, b], \\<d>[b] \\<cdot> \\<pp>\\<^sub>0[a, b]\\<rangle>\\<rangle>\"\n        proof -\n          have \"\\<a>[a, a, b \\<otimes> b] \\<cdot> (\\<d>[a] \\<otimes> \\<d>[b]) = \\<langle>\\<pp>\\<^sub>1[a, b], \\<langle>\\<pp>\\<^sub>1[a, b], \\<d>[b] \\<cdot> \\<pp>\\<^sub>0[a, b]\\<rangle>\\<rangle>\"\n            using assms assoc_def comp_assoc pr_naturality comp_cod_arr by simp\n          thus ?thesis by presburger\n        qed\n        also have \"... = \\<a>\\<^sup>-\\<^sup>1[a, b, a \\<otimes> b] \\<cdot>\n        \\<langle>a \\<cdot> a \\<cdot> a \\<cdot> \\<pp>\\<^sub>1[a, b], \\<a>[b, a, b] \\<cdot> (\\<s>[a, b] \\<cdot> (a \\<otimes> b) \\<otimes> b) \\<cdot>\n                               \\<a>\\<^sup>-\\<^sup>1[a, b, b] \\<cdot> \\<langle>\\<pp>\\<^sub>1[a, b], \\<d>[b \\<cdot> \\<pp>\\<^sub>0[a, b]]\\<rangle>\\<rangle>\"\n          using assms prod_tuple by simp\n        also have \"... = \\<a>\\<^sup>-\\<^sup>1[a, b, a \\<otimes> b] \\<cdot>\n        \\<langle>\\<pp>\\<^sub>1[a, b], \\<a>[b, a, b] \\<cdot> (\\<s>[a, b] \\<otimes> b) \\<cdot> \\<a>\\<^sup>-\\<^sup>1[a, b, b] \\<cdot> \\<langle>\\<pp>\\<^sub>1[a, b], \\<d>[\\<pp>\\<^sub>0[a, b]]\\<rangle>\\<rangle>\"\n        proof -\n          have \"a \\<cdot> a \\<cdot> a \\<cdot> \\<pp>\\<^sub>1[a, b] = \\<pp>\\<^sub>1[a, b]\"\n            using assms comp_cod_arr by simp\n          moreover have \"b \\<cdot> \\<pp>\\<^sub>0[a, b] = \\<pp>\\<^sub>0[a, b]\"\n            using assms comp_cod_arr by simp\n          moreover have \"\\<s>[a, b] \\<cdot> (a \\<otimes> b) \\<otimes> b = \\<s>[a, b] \\<otimes> b\"\n            using assms comp_arr_dom by simp\n          ultimately show ?thesis by simp\n        qed\n        also have \"... = \\<a>\\<^sup>-\\<^sup>1[a, b, a \\<otimes> b] \\<cdot> \\<langle>\\<pp>\\<^sub>1[a, b], \\<a>[b, a, b] \\<cdot> (\\<s>[a, b] \\<otimes> b) \\<cdot>\n                           \\<langle>\\<langle>\\<pp>\\<^sub>1[a, b], \\<pp>\\<^sub>0[a, b]\\<rangle>, \\<pp>\\<^sub>0[a, b]\\<rangle>\\<rangle>\"\n        proof -\n          have \"\\<a>\\<^sup>-\\<^sup>1[a, b, b] \\<cdot> \\<langle>\\<pp>\\<^sub>1[a, b], \\<d>[\\<pp>\\<^sub>0[a, b]]\\<rangle> = \\<langle>\\<langle>\\<pp>\\<^sub>1[a, b], \\<pp>\\<^sub>0[a, b]\\<rangle>, \\<pp>\\<^sub>0[a, b]\\<rangle>\"\n            using assms comp_assoc_tuple(2) by blast\n          thus ?thesis by simp\n        qed\n        also have \"... = \\<a>\\<^sup>-\\<^sup>1[a, b, a \\<otimes> b] \\<cdot> \\<langle>\\<pp>\\<^sub>1[a, b], \\<a>[b, a, b] \\<cdot> \\<langle>\\<s>[a, b], \\<pp>\\<^sub>0[a, b]\\<rangle>\\<rangle>\"\n          using assms prod_tuple comp_arr_dom comp_cod_arr by simp\n        also have \"... = \\<a>\\<^sup>-\\<^sup>1[a, b, a \\<otimes> b] \\<cdot> \\<langle>\\<pp>\\<^sub>1[a, b], \\<langle>\\<pp>\\<^sub>0[a, b], \\<langle>\\<pp>\\<^sub>1[a, b], \\<pp>\\<^sub>0[a, b]\\<rangle>\\<rangle>\\<rangle>\"\n          using assms comp_assoc_tuple(1)\n          by (metis sym_def pr_in_hom)\n        also have \"... = \\<langle>\\<langle>\\<pp>\\<^sub>1[a, b], \\<pp>\\<^sub>0[a, b]\\<rangle>, \\<langle>\\<pp>\\<^sub>1[a, b], \\<pp>\\<^sub>0[a, b]\\<rangle>\\<rangle>\"\n          using assms comp_assoc_tuple(2) by force\n        also have \"... = \\<d>[a \\<otimes> b]\"\n          using assms by simp\n        finally show ?thesis by simp\n      qed\n      show \"\\<pp>\\<^sub>0[a \\<otimes> b, a \\<otimes> b] \\<cdot> \\<d>[a \\<otimes> b]\n              = \\<pp>\\<^sub>0[a \\<otimes> b, a \\<otimes> b] \\<cdot>\n                \\<a>\\<^sup>-\\<^sup>1[a, b, a \\<otimes> b] \\<cdot> (a \\<otimes> \\<a>[b, a, b]) \\<cdot> (a \\<otimes> \\<sigma> (a, b) \\<otimes> b) \\<cdot>\n                (a \\<otimes> \\<a>\\<^sup>-\\<^sup>1[a, b, b]) \\<cdot> \\<a>[a, a, b \\<otimes> b] \\<cdot> (\\<d>[a] \\<otimes> \\<d>[b])\"\n        using assms 1 by force\n      show \"\\<pp>\\<^sub>1[a \\<otimes> b, a \\<otimes> b] \\<cdot> \\<d>[a \\<otimes> b]\n              = \\<pp>\\<^sub>1[a \\<otimes> b, a \\<otimes> b] \\<cdot>\n                \\<a>\\<^sup>-\\<^sup>1[a, b, a \\<otimes> b] \\<cdot> (a \\<otimes> \\<a>[b, a, b]) \\<cdot> (a \\<otimes> \\<sigma> (a, b) \\<otimes> b) \\<cdot>\n                (a \\<otimes> \\<a>\\<^sup>-\\<^sup>1[a, b, b]) \\<cdot> \\<a>[a, a, b \\<otimes> b] \\<cdot> (\\<d>[a] \\<otimes> \\<d>[b])\"\n        using assms 1 by force\n    qed\n\n    (* TODO: Not sure if the remaining facts are useful. *)\n\n    lemma \\<iota>_eq_trm:\n    shows \"\\<iota> = \\<t>[\\<one> \\<otimes> \\<one>]\"\n    proof (intro terminal_arr_unique)\n      show \"par \\<iota> \\<t>[\\<one> \\<otimes> \\<one>]\"\n        by (simp add: ide_one trm_one trm_tensor)\n      show \"terminal_arr \\<t>[\\<one> \\<otimes> \\<one>]\"\n        using ide_one \\<iota>_is_terminal_arr \\<open>par \\<iota> \\<t>[\\<one> \\<otimes> \\<one>]\\<close> by auto\n      show \"terminal_arr \\<iota>\"\n        using \\<iota>_is_terminal_arr by blast\n    qed\n\n    lemma terminal_tensor_one_one:\n    shows \"terminal (\\<one> \\<otimes> \\<one>)\"\n    proof\n      show \"ide (\\<one> \\<otimes> \\<one>)\"\n        using ide_one by simp\n      show \"\\<And>a. ide a \\<Longrightarrow> \\<exists>!f. \\<guillemotleft>f : a \\<rightarrow> \\<one> \\<otimes> \\<one>\\<guillemotright>\"\n      proof -\n        fix a\n        assume a: \"ide a\"\n        show \"\\<exists>!f. \\<guillemotleft>f : a \\<rightarrow> \\<one> \\<otimes> \\<one>\\<guillemotright>\"\n        proof\n          show \"\\<guillemotleft>inv \\<iota> \\<cdot> \\<t>[a] : a \\<rightarrow> \\<one> \\<otimes> \\<one>\\<guillemotright>\"\n            using a ide_one inverse_arrows_\\<iota> inverse_unique trm_in_hom_ax by fastforce\n          show \"\\<And>f. \\<guillemotleft>f : a \\<rightarrow> \\<one> \\<otimes> \\<one>\\<guillemotright> \\<Longrightarrow> f = inv \\<iota> \\<cdot> \\<t>[a]\"\n          proof -\n            fix f\n            assume f: \"\\<guillemotleft>f : a \\<rightarrow> \\<one> \\<otimes> \\<one>\\<guillemotright>\"\n            have \"\\<iota> \\<cdot> f = \\<t>[a]\"\n            proof (intro terminal_arr_unique)\n              show \"par (\\<iota> \\<cdot> f) \\<t>[a]\"\n                using a f\n                by (metis \\<iota>_is_iso \\<iota>_is_terminal_arr \\<open>\\<guillemotleft>inv \\<iota> \\<cdot> \\<t>[a] : a \\<rightarrow> \\<one> \\<otimes> \\<one>\\<guillemotright>\\<close>\n                    cod_comp dom_comp dom_inv ide_one in_homE pr_simps(2-3) seqE seqI)\n              show \"terminal_arr (\\<iota> \\<cdot> f)\"\n                using a f \\<iota>_is_terminal_arr cod_comp by force\n              show \"terminal_arr \\<t>[a]\"\n                using a \\<open>par (\\<iota> \\<cdot> f) \\<t>[a]\\<close> \\<open>terminal_arr (\\<iota> \\<cdot> f)\\<close> by auto\n            qed\n            thus \"f = inv \\<iota> \\<cdot> \\<t>[a]\"\n              using a f \\<iota>_is_iso invert_side_of_triangle(1)\n                    \\<open>\\<guillemotleft>inv \\<iota> \\<cdot> \\<t>[a] : a \\<rightarrow> \\<one> \\<otimes> \\<one>\\<guillemotright>\\<close>\n              by blast\n          qed\n        qed\n      qed\n    qed\n\n  end\n\n  section \"Category with Finite Products\"\n\n  text \\<open>\n    In this last section, we show that the notion ``cartesian category'', which we defined\n    to be a category with binary products and terminal object, coincides with the notion\n    ``category with finite products''.  Due to the inability to quantify over types in HOL,\n    we content ourselves with defining the latter notion as \"has \\<open>I\\<close>-indexed products\n    for every finite set \\<open>I\\<close> of natural numbers.\"  We can transfer this property to finite\n    sets at other types using the fact that products are preserved under bijections of\n    the index sets.\n  \\<close>\n\n  locale category_with_finite_products =\n    category C\n  for C :: \"'c comp\" +\n  assumes has_finite_products: \"finite (I :: nat set) \\<Longrightarrow> has_products I\"\n  begin\n\n    lemma has_finite_products':\n    assumes \"I \\<noteq> UNIV\"\n    shows \"finite I \\<Longrightarrow> has_products I\"\n    proof -\n      assume I: \"finite I\"\n      obtain n \\<phi> where \\<phi>: \"bij_betw \\<phi> {k. k < (n :: nat)} I\"\n        using I finite_imp_nat_seg_image_inj_on inj_on_imp_bij_betw by fastforce\n      show \"has_products I\"\n        using assms(1) \\<phi> has_finite_products has_products_preserved_by_bijection\n              category_with_finite_products.has_finite_products\n        by blast\n    qed\n\n  end\n\n  lemma (in category) has_binary_products_if:\n  assumes \"has_products ({0, 1} :: nat set)\"\n  shows \"has_binary_products\"\n  proof (unfold has_binary_products_def)\n    show \"\\<forall>a0 a1. ide a0 \\<and> ide a1 \\<longrightarrow> (\\<exists>p0 p1. has_as_binary_product a0 a1 p0 p1)\"\n    proof (intro allI impI)\n      fix a0 a1\n      assume 1: \"ide a0 \\<and> ide a1\"\n      show \"\\<exists>p0 p1. has_as_binary_product a0 a1 p0 p1\"\n      proof -\n        interpret J: binary_product_shape\n          by unfold_locales\n        interpret D: binary_product_diagram C a0 a1\n          using 1 by unfold_locales auto\n        interpret discrete_diagram J.comp C D.map\n          using J.is_discrete\n          by unfold_locales auto\n        show \"\\<exists>p0 p1. has_as_binary_product a0 a1 p0 p1\"\n        proof (unfold has_as_binary_product_def)\n          text \\<open>\n            Here we have to work around the fact that \\<open>has_finite_products\\<close> is defined\n            in terms of @{typ \"nat set\"}, whereas \\<open>has_as_binary_product\\<close> is defined\n            in terms of \\<open>J.arr set\\<close>.\n          \\<close>\n          let ?\\<phi> = \"(\\<lambda>x :: nat. if x = 0 then J.FF else J.TT)\"\n          let ?\\<psi> = \"\\<lambda>j. if j = J.FF then 0 else 1\"\n          have \"bij_betw ?\\<phi> ({0, 1} :: nat set) {J.FF, J.TT}\"\n            using bij_betwI [of ?\\<phi> \"{0, 1} :: nat set\" \"{J.FF, J.TT}\" ?\\<psi>] by fastforce\n          hence \"has_products {J.FF, J.TT}\"\n            using assms has_products_def [of \"{J.FF, J.TT}\"]\n                  has_products_preserved_by_bijection\n                    [of \"{0, 1} :: nat set\" ?\\<phi> \"{J.FF, J.TT}\"]\n            by blast\n          hence \"\\<exists>a. has_as_product J.comp D.map a\"\n            using has_products_def [of \"{J.FF, J.TT}\"]\n                  discrete_diagram_axioms J.arr_char\n            by blast\n          hence \"\\<exists>a \\<pi>. product_cone J.comp C D.map a \\<pi>\"\n            using has_as_product_def by blast\n          hence 2: \"\\<exists>a \\<pi>. D.limit_cone a \\<pi>\"\n            unfolding product_cone_def by simp\n          obtain a \\<pi> where \\<pi>: \"D.limit_cone a \\<pi>\"\n            using 2 by auto\n          interpret \\<pi>: limit_cone J.comp C D.map a \\<pi>\n            using \\<pi> by auto\n          have \"\\<pi> = D.mkCone (\\<pi> J.FF) (\\<pi> J.TT)\"\n          proof -\n            have \"\\<And>a. J.ide a \\<Longrightarrow> \\<pi> a = D.mkCone (\\<pi> J.FF) (\\<pi> J.TT) a\"\n              using D.mkCone_def J.ide_char by auto\n            moreover have \"a = dom (\\<pi> J.FF)\"\n              by simp\n            moreover have \"D.cone a (D.mkCone (\\<pi> (J.MkIde False)) (\\<pi> (J.MkIde True)))\"\n              using 1 D.cone_mkCone [of \"\\<pi> J.FF\" \"\\<pi> J.TT\"] by auto\n            ultimately show ?thesis\n              using D.mkCone_def \\<pi>.natural_transformation_axioms\n                    D.cone_mkCone [of \"\\<pi> J.FF\" \"\\<pi> J.TT\"]\n                    NaturalTransformation.eqI\n                      [of \"J.comp\" C \\<pi>.A.map \"D.map\" \\<pi> \"D.mkCone (\\<pi> J.FF) (\\<pi> J.TT)\"]\n                    cone_def [of J.comp C D.map a \"D.mkCone (\\<pi> J.FF) (\\<pi> J.TT)\"] J.ide_char\n              by blast\n          qed\n          hence \"D.limit_cone (dom (\\<pi> J.FF)) (D.mkCone (\\<pi> J.FF) (\\<pi> J.TT))\"\n            using \\<pi>.limit_cone_axioms by simp\n          thus \"\\<exists>p0 p1. ide a0 \\<and> ide a1 \\<and> D.has_as_binary_product p0 p1\"\n            using 1 by blast\n        qed\n      qed\n    qed\n  qed\n\n  sublocale category_with_finite_products \\<subseteq> category_with_binary_products C\n    using has_binary_products_if has_finite_products\n    by (unfold_locales, unfold has_binary_products_def) simp\n\n  proposition (in category_with_finite_products) is_category_with_binary_products\\<^sub>C\\<^sub>F\\<^sub>P:\n  shows \"category_with_binary_products C\"\n    ..\n\n  sublocale category_with_finite_products \\<subseteq> category_with_terminal_object C\n  proof\n    interpret J: discrete_category \"{} :: nat set\"\n      by unfold_locales auto\n    interpret D: empty_diagram J.comp C \"\\<lambda>j. null\"\n      by unfold_locales auto\n    interpret D: discrete_diagram J.comp C \"\\<lambda>j. null\"\n      using J.is_discrete by unfold_locales auto\n    have \"\\<And>a. D.has_as_limit a \\<longleftrightarrow> has_as_product J.comp (\\<lambda>j. null) a\"\n      using product_cone_def J.category_axioms category_axioms D.discrete_diagram_axioms\n            has_as_product_def product_cone_def\n      by metis\n    moreover have \"\\<exists>a. has_as_product J.comp (\\<lambda>j. null) a\"\n      using has_finite_products [of \"{} :: nat set\"] has_products_def [of \"{} :: nat set\"]\n            D.discrete_diagram_axioms\n      by blast\n    ultimately have \"\\<exists>a. D.has_as_limit a\" by blast\n    thus \"\\<exists>a. terminal a\" using D.has_as_limit_iff_terminal by blast\n  qed\n\n  proposition (in category_with_finite_products) is_category_with_terminal_object\\<^sub>C\\<^sub>F\\<^sub>P:\n  shows \"category_with_terminal_object C\"\n    ..\n\n  sublocale category_with_finite_products \\<subseteq> cartesian_category ..\n\n  proposition (in category_with_finite_products) is_cartesian_category\\<^sub>C\\<^sub>F\\<^sub>P:\n  shows \"cartesian_category C\"\n    ..\n\n  context category\n  begin\n\n    lemma binary_product_of_products_is_product:\n    assumes \"has_as_product J0 D0 a0\" and \"has_as_product J1 D1 a1\"\n    and \"has_as_binary_product a0 a1 p0 p1\"\n    and \"Collect (partial_magma.arr J0) \\<inter> Collect (partial_magma.arr J1) = {}\"\n    and \"partial_magma.null J0 = partial_magma.null J1\"\n    shows \"has_as_product\n             (discrete_category.comp\n                (Collect (partial_magma.arr J0) \\<union> Collect (partial_magma.arr J1))\n                (partial_magma.null J0))\n             (\\<lambda>i. if i \\<in> Collect (partial_magma.arr J0) then D0 i\n                  else if i \\<in> Collect (partial_magma.arr J1) then D1 i\n                  else null)\n             (dom p0)\"\n    proof -\n      obtain \\<pi>0 where \\<pi>0: \"product_cone J0 (\\<cdot>) D0 a0 \\<pi>0\"\n        using assms(1) has_as_product_def by blast\n      obtain \\<pi>1 where \\<pi>1: \"product_cone J1 (\\<cdot>) D1 a1 \\<pi>1\"\n        using assms(2) has_as_product_def by blast\n      interpret J0: category J0\n        using \\<pi>0 product_cone.axioms(1) by metis\n      interpret J1: category J1\n        using \\<pi>1 product_cone.axioms(1) by metis\n      interpret D0: discrete_diagram J0 C D0\n        using \\<pi>0 product_cone.axioms(3) by metis\n      interpret D1: discrete_diagram J1 C D1\n        using \\<pi>1 product_cone.axioms(3) by metis\n      interpret \\<pi>0: product_cone J0 C D0 a0 \\<pi>0\n        using \\<pi>0 by auto\n      interpret \\<pi>1: product_cone J1 C D1 a1 \\<pi>1\n        using \\<pi>1 by auto\n      interpret J: discrete_category \\<open>Collect J0.arr \\<union> Collect J1.arr\\<close> J0.null\n        using J0.not_arr_null assms(5) by unfold_locales auto\n      interpret X: binary_product_shape .\n      interpret a0xa1: binary_product_diagram C a0 a1\n        using assms(3) has_as_binary_product_def\n        by (simp add: binary_product_diagram.intro binary_product_diagram_axioms.intro\n            category_axioms)\n      have p0p1: \"a0xa1.has_as_binary_product p0 p1\"\n        using assms(3) has_as_binary_product_def [of a0 a1 p0 p1] by simp\n\n      let ?D = \"(\\<lambda>i. if i \\<in> Collect J0.arr then D0 i\n                     else if i \\<in> Collect J1.arr then D1 i\n                     else null)\"\n      let ?a = \"dom p0\"\n      let ?\\<pi> = \"\\<lambda>i. if i \\<in> Collect J0.arr then \\<pi>0 i \\<cdot> p0\n                    else if i \\<in> Collect J1.arr then \\<pi>1 i \\<cdot> p1\n                    else null\"\n\n      let ?p0p1 = \"a0xa1.mkCone p0 p1\"\n      interpret p0p1: limit_cone X.comp C a0xa1.map ?a ?p0p1\n        using p0p1 by simp\n      have a: \"ide ?a\"\n        using p0p1.ide_apex by simp\n      have p0: \"\\<guillemotleft>p0 : ?a \\<rightarrow> a0\\<guillemotright>\"\n        using a0xa1.mkCone_def p0p1.preserves_hom [of X.FF X.FF X.FF] X.ide_char X.ide_in_hom\n        by auto\n      have p1: \"\\<guillemotleft>p1 : ?a \\<rightarrow> a1\\<guillemotright>\"\n        using a0xa1.mkCone_def p0p1.preserves_hom [of X.TT X.TT X.TT] X.ide_char X.ide_in_hom\n        by auto\n\n      interpret D: discrete_diagram J.comp C ?D\n        using assms J.arr_char J.dom_char J.cod_char J.is_discrete D0.is_discrete D1.is_discrete\n              J.cod_comp J.seq_char\n        by unfold_locales auto\n      interpret A: constant_functor J.comp C ?a\n        using p0p1.ide_apex by unfold_locales simp\n      interpret \\<pi>: natural_transformation J.comp C A.map ?D ?\\<pi>\n      proof\n        fix j\n        show \"\\<not> J.arr j \\<Longrightarrow> ?\\<pi> j = null\"\n          by simp\n        assume j: \"J.arr j\"\n        have \\<pi>0j: \"J0.arr j \\<Longrightarrow> \\<guillemotleft>\\<pi>0 j : a0 \\<rightarrow> D0 j\\<guillemotright>\"\n          using D0.is_discrete by auto\n        have \\<pi>1j: \"J1.arr j \\<Longrightarrow> \\<guillemotleft>\\<pi>1 j : a1 \\<rightarrow> D1 j\\<guillemotright>\"\n          using D1.is_discrete by auto\n        show \"dom (?\\<pi> j) = A.map (J.dom j)\"\n          using j J.arr_char p0 p1 \\<pi>0j \\<pi>1j\n          by fastforce\n        show \"cod (?\\<pi> j) = ?D (J.cod j)\"\n          using j J.arr_char p0 p1 \\<pi>0j \\<pi>1j\n          by fastforce\n        show \"?D j \\<cdot> ?\\<pi> (J.dom j) = ?\\<pi> j\"\n        proof -\n          have 0: \"J0.arr j \\<Longrightarrow> D0 j \\<cdot> \\<pi>0 j \\<cdot> p0 = \\<pi>0 j \\<cdot> p0\"\n          proof -\n            have \"J0.arr j \\<Longrightarrow> (D0 j \\<cdot> \\<pi>0 j) \\<cdot> p0 = \\<pi>0 j \\<cdot> p0\"\n              using p0 \\<pi>0.is_natural_1 \\<pi>0.is_natural_2 D0.is_discrete by simp\n            thus \"J0.arr j \\<Longrightarrow> D0 j \\<cdot> \\<pi>0 j \\<cdot> p0 = \\<pi>0 j \\<cdot> p0\"\n              using comp_assoc by simp\n          qed\n          have 1: \"J1.arr j \\<Longrightarrow> D1 j \\<cdot> \\<pi>1 j \\<cdot> p1 = \\<pi>1 j \\<cdot> p1\"\n          proof -\n            have \"J1.arr j \\<Longrightarrow> (D1 j \\<cdot> \\<pi>1 j) \\<cdot> p1 = \\<pi>1 j \\<cdot> p1\"\n              using p1 \\<pi>1.is_natural_1 \\<pi>1.is_natural_2 D1.is_discrete by simp\n            thus \"J1.arr j \\<Longrightarrow> D1 j \\<cdot> \\<pi>1 j \\<cdot> p1 = \\<pi>1 j \\<cdot> p1\"\n              using comp_assoc by simp\n          qed\n          show ?thesis\n            using 0 1 by auto\n        qed\n        show \"?\\<pi> (J.cod j) \\<cdot> A.map j = ?\\<pi> j\"\n          using j comp_arr_dom p0 p1 comp_assoc by auto\n      qed\n      interpret \\<pi>: cone J.comp C ?D ?a ?\\<pi> ..\n      interpret \\<pi>: product_cone J.comp C ?D ?a ?\\<pi>\n      proof\n        show \"\\<And>a' \\<chi>'. D.cone a' \\<chi>' \\<Longrightarrow> \\<exists>!f. \\<guillemotleft>f : a' \\<rightarrow> ?a\\<guillemotright> \\<and> D.cones_map f ?\\<pi> = \\<chi>'\"\n        proof -\n          fix a' \\<chi>'\n          assume \\<chi>': \"D.cone a' \\<chi>'\"\n          interpret \\<chi>': cone J.comp C ?D a' \\<chi>'\n            using \\<chi>' by simp\n          show \"\\<exists>!f. \\<guillemotleft>f : a' \\<rightarrow> ?a\\<guillemotright> \\<and> D.cones_map f ?\\<pi> = \\<chi>'\"\n          proof\n            let ?\\<chi>0' = \"\\<lambda>i. if i \\<in> Collect J0.arr then \\<chi>' i else null\"\n            let ?\\<chi>1' = \"\\<lambda>i. if i \\<in> Collect J1.arr then \\<chi>' i else null\"\n            have 0: \"\\<And>i. i \\<in> Collect J0.arr \\<Longrightarrow> \\<chi>' i \\<in> hom a' (D0 i)\"\n              using J.arr_char by auto\n            have 1: \"\\<And>i. i \\<in> Collect J1.arr \\<Longrightarrow> \\<chi>' i \\<in> hom a' (D1 i)\"\n              using J.arr_char \\<open>Collect J0.arr \\<inter> Collect J1.arr = {}\\<close> by force\n            interpret A0': constant_functor J0 C a'\n              apply unfold_locales using \\<chi>'.ide_apex by auto\n            interpret A1': constant_functor J1 C a'\n              apply unfold_locales using \\<chi>'.ide_apex by auto\n            interpret \\<chi>0': cone J0 C D0 a' ?\\<chi>0'\n            proof (unfold_locales)\n              fix j\n              show \"\\<not> J0.arr j \\<Longrightarrow> (if j \\<in> Collect J0.arr then \\<chi>' j else null) = null\"\n                by simp\n              assume j: \"J0.arr j\"\n              show 0: \"dom (?\\<chi>0' j) = A0'.map (J0.dom j)\"\n                using j by simp\n              show 1: \"cod (?\\<chi>0' j) = D0 (J0.cod j)\"\n                using j J.arr_char J.cod_char D0.is_discrete by simp\n              show \"D0 j \\<cdot> (?\\<chi>0' (J0.dom j)) = ?\\<chi>0' j\"\n                using 1 j J.arr_char D0.is_discrete comp_cod_arr by simp\n              show \"?\\<chi>0' (J0.cod j) \\<cdot> A0'.map j = ?\\<chi>0' j\"\n                using 0 j J.arr_char D0.is_discrete comp_arr_dom by simp\n            qed\n            interpret \\<chi>1': cone J1 C D1 a' ?\\<chi>1'\n            proof (unfold_locales)\n              fix j\n              show \"\\<not> J1.arr j \\<Longrightarrow> (if j \\<in> Collect J1.arr then \\<chi>' j else null) = null\"\n                by simp\n              assume j: \"J1.arr j\"\n              show 0: \"dom (?\\<chi>1' j) = A1'.map (J1.dom j)\"\n                using j by simp\n              show 1: \"cod (?\\<chi>1' j) = D1 (J1.cod j)\"\n                using assms(4) j J.arr_char J.cod_char D1.is_discrete by auto\n              show \"D1 j \\<cdot> (?\\<chi>1' (J1.dom j)) = ?\\<chi>1' j\"\n                using 1 j J.arr_char D1.is_discrete comp_cod_arr by simp\n              show \"?\\<chi>1' (J1.cod j) \\<cdot> A1'.map j = ?\\<chi>1' j\"\n                using 0 j J.arr_char D1.is_discrete comp_arr_dom by simp\n            qed\n            define f0 where \"f0 = \\<pi>0.induced_arrow a' ?\\<chi>0'\"\n            define f1 where \"f1 = \\<pi>1.induced_arrow a' ?\\<chi>1'\"\n            have f0: \"\\<guillemotleft>f0 : a' \\<rightarrow> a0\\<guillemotright>\"\n              using f0_def \\<pi>0.induced_arrowI \\<chi>0'.cone_axioms by simp\n            have f1: \"\\<guillemotleft>f1 : a' \\<rightarrow> a1\\<guillemotright>\"\n              using f1_def \\<pi>1.induced_arrowI \\<chi>1'.cone_axioms by simp\n            have 2: \"a0xa1.is_rendered_commutative_by f0 f1\"\n              using f0 f1 by auto\n\n            interpret p0p1: binary_product_cone C a0 a1 p0 p1 ..\n            interpret f0f1: cone X.comp C a0xa1.map a' \\<open>a0xa1.mkCone f0 f1\\<close>\n              using 2 f0 f1 a0xa1.cone_mkCone [of f0 f1] by auto\n            define f where \"f = p0p1.induced_arrow a' (a0xa1.mkCone f0 f1)\"\n\n            have f: \"\\<guillemotleft>f : a' \\<rightarrow> ?a\\<guillemotright>\"\n              using f_def 2 f0 f1 p0p1.induced_arrowI'(1) by auto\n            moreover have \\<chi>': \"D.cones_map f ?\\<pi> = \\<chi>'\"\n            proof\n              fix j\n              show \"D.cones_map f ?\\<pi> j = \\<chi>' j\"\n              proof (cases \"J0.arr j\", cases \"J1.arr j\")\n                show \"\\<lbrakk>J0.arr j; J1.arr j\\<rbrakk> \\<Longrightarrow> D.cones_map f ?\\<pi> j = \\<chi>' j\"\n                  using assms(4) by auto\n                show \"\\<lbrakk>J0.arr j; \\<not> J1.arr j\\<rbrakk> \\<Longrightarrow> D.cones_map f ?\\<pi> j = \\<chi>' j\"\n                proof -\n                  assume J0: \"J0.arr j\" and J1: \"\\<not> J1.arr j\"\n                  have \"D.cones_map f ?\\<pi> j = (\\<pi>0 j \\<cdot> p0) \\<cdot> f\"\n                    using f J0 J1 \\<pi>.cone_axioms by auto\n                  also have \"... = \\<pi>0 j \\<cdot> p0 \\<cdot> f\"\n                    using comp_assoc by simp\n                  also have \"... = \\<pi>0 j \\<cdot> f0\"\n                    using 2 f0 f1 f_def p0p1.induced_arrowI' by auto\n                  also have \"... = \\<chi>' j\"\n                  proof -\n                    have \"\\<pi>0 j \\<cdot> f0 = \\<pi>0 j \\<cdot> \\<pi>0.induced_arrow' a' \\<chi>'\"\n                      unfolding f0_def by simp\n                    also have \"... = (\\<lambda>j. if J0.arr j then\n                                            \\<pi>0 j \\<cdot> \\<pi>0.induced_arrow a'\n                                                    (\\<lambda>i. if i \\<in> Collect J0.arr then \\<chi>' i else null)\n                                          else null) j\"\n                      using J0 by simp\n                    also have \"... = D0.mkCone \\<chi>' j\"\n                    proof -\n                      have \"(\\<lambda>j. if J0.arr j then\n                                    \\<pi>0 j \\<cdot> \\<pi>0.induced_arrow a'\n                                             (\\<lambda>i. if i \\<in> Collect J0.arr then \\<chi>' i else null)\n                                 else null) =\n                            D0.mkCone \\<chi>'\"\n                        using f0 f0_def \\<pi>0.induced_arrowI(2) [of ?\\<chi>0' a'] J0\n                              D0.mkCone_cone \\<chi>0'.cone_axioms \\<pi>0.cone_axioms J0\n                        by auto\n                      thus ?thesis by meson\n                    qed\n                    also have \"... = \\<chi>' j\"\n                      using J0 by simp\n                    finally show ?thesis by blast\n                  qed\n                  finally show ?thesis by simp\n                qed\n                show \"\\<not> J0.arr j \\<Longrightarrow> D.cones_map f ?\\<pi> j = \\<chi>' j\"\n                proof (cases \"J1.arr j\")\n                  show \"\\<lbrakk>\\<not> J0.arr j; \\<not> J1.arr j\\<rbrakk> \\<Longrightarrow> D.cones_map f ?\\<pi> j = \\<chi>' j\"\n                    using f \\<pi>.cone_axioms \\<chi>'.is_extensional by auto\n                  show \"\\<lbrakk>\\<not> J0.arr j; J1.arr j\\<rbrakk> \\<Longrightarrow> D.cones_map f ?\\<pi> j = \\<chi>' j\"\n                  proof -\n                    assume J0: \"\\<not> J0.arr j\" and J1: \"J1.arr j\"\n                    have \"D.cones_map f ?\\<pi> j = (\\<pi>1 j \\<cdot> p1) \\<cdot> f\"\n                      using J0 J1 f \\<pi>.cone_axioms by auto\n                    also have \"... = \\<pi>1 j \\<cdot> p1 \\<cdot> f\"\n                      using comp_assoc by simp\n                    also have \"... = \\<pi>1 j \\<cdot> f1\"\n                      using 2 f0 f1 f_def p0p1.induced_arrowI' by auto\n                    also have \"... = \\<chi>' j\"\n                    proof -\n                      have \"\\<pi>1 j \\<cdot> f1 = \\<pi>1 j \\<cdot> \\<pi>1.induced_arrow' a' \\<chi>'\"\n                        unfolding f1_def by simp\n                      also have \"... = (\\<lambda>j. if J1.arr j then\n                                              \\<pi>1 j \\<cdot> \\<pi>1.induced_arrow a'\n                                                      (\\<lambda>i. if i \\<in> Collect J1.arr\n                                                           then \\<chi>' i else null)\n                                            else null) j\"\n                        using J1 by simp\n                      also have \"... = D1.mkCone \\<chi>' j\"\n                      proof -\n                        have \"(\\<lambda>j. if J1.arr j then\n                                      \\<pi>1 j \\<cdot> \\<pi>1.induced_arrow a'\n                                               (\\<lambda>i. if i \\<in> Collect J1.arr then \\<chi>' i else null)\n                                   else null) =\n                              D1.mkCone \\<chi>'\"\n                          using f1 f1_def \\<pi>1.induced_arrowI(2) [of ?\\<chi>1' a'] J1\n                                D1.mkCone_cone [of a' \\<chi>'] \\<chi>1'.cone_axioms \\<pi>1.cone_axioms J1\n                          by auto\n                        thus ?thesis by meson\n                      qed\n                      also have \"... = \\<chi>' j\"\n                        using J1 by simp\n                      finally show ?thesis by blast\n                    qed\n                    finally show ?thesis by simp\n                  qed\n                qed\n              qed\n            qed\n            ultimately show \"\\<guillemotleft>f : a' \\<rightarrow> ?a\\<guillemotright> \\<and> D.cones_map f ?\\<pi> = \\<chi>'\" by blast\n            show \"\\<And>f'. \\<guillemotleft>f' : a' \\<rightarrow> ?a\\<guillemotright> \\<and> D.cones_map f' ?\\<pi> = \\<chi>' \\<Longrightarrow> f' = f\"\n            proof -\n              fix f'\n              assume f': \"\\<guillemotleft>f' : a' \\<rightarrow> ?a\\<guillemotright> \\<and> D.cones_map f' ?\\<pi> = \\<chi>'\"\n              let ?f0' = \"p0 \\<cdot> f'\"\n              let ?f1' = \"p1 \\<cdot> f'\"\n              have 1: \"a0xa1.is_rendered_commutative_by ?f0' ?f1'\"\n                using f' p0 p1 p0p1.renders_commutative seqI' by auto\n              have f0': \"\\<guillemotleft>?f0' : a' \\<rightarrow> a0\\<guillemotright>\"\n                using f' p0 by auto\n              have f1': \"\\<guillemotleft>?f1' : a' \\<rightarrow> a1\\<guillemotright>\"\n                using f' p1 by auto\n              have \"p0 \\<cdot> f = p0 \\<cdot> f'\"\n              proof -\n                have \"D0.cones_map (p0 \\<cdot> f) \\<pi>0 = ?\\<chi>0'\"\n                  using f p0 \\<pi>0.cone_axioms \\<chi>' \\<pi>.cone_axioms comp_assoc assms(4) seqI'\n                  by fastforce\n                moreover have \"D0.cones_map (p0 \\<cdot> f') \\<pi>0 = ?\\<chi>0'\"\n                  using f' p0 \\<pi>0.cone_axioms \\<pi>.cone_axioms comp_assoc assms(4) seqI'\n                  by fastforce\n                moreover have \"p0 \\<cdot> f = f0\"\n                  using 2 f0 f_def p0p1.induced_arrowI'(2) by blast\n                ultimately show ?thesis\n                  using f0 f0' \\<chi>0'.cone_axioms \\<pi>0.is_universal [of a'] by auto\n              qed\n              moreover have \"p1 \\<cdot> f = p1 \\<cdot> f'\"\n              proof -\n                have \"D1.cones_map (p1 \\<cdot> f) \\<pi>1 = ?\\<chi>1'\"\n                proof\n                  fix j\n                  show \"D1.cones_map (p1 \\<cdot> f) \\<pi>1 j = ?\\<chi>1' j\"\n                    using f p1 \\<pi>1.cone_axioms \\<chi>' \\<pi>.cone_axioms comp_assoc assms(4) seqI'\n                    apply auto\n                    by auto\n                qed\n                moreover have \"D1.cones_map (p1 \\<cdot> f') \\<pi>1 = ?\\<chi>1'\"\n                proof\n                  fix j\n                  show \"D1.cones_map (p1 \\<cdot> f') \\<pi>1 j = ?\\<chi>1' j\"\n                    using f' p1 \\<pi>1.cone_axioms \\<pi>.cone_axioms comp_assoc assms(4) seqI'\n                    apply auto\n                    by auto\n                qed\n                moreover have \"p1 \\<cdot> f = f1\"\n                  using 2 f1 f_def p0p1.induced_arrowI'(3) by blast\n                  ultimately show ?thesis\n                using f1 f1' \\<chi>1'.cone_axioms \\<pi>1.is_universal [of a'] by auto\n              qed\n              ultimately show \"f' = f\"\n                using f f' p0p1.is_universal' [of a']\n                by (metis (no_types, lifting) \"1\" dom_comp in_homE p0p1.is_universal' p1 seqI')\n            qed\n          qed\n        qed\n      qed\n      show \"has_as_product J.comp ?D ?a\"\n        unfolding has_as_product_def\n        using \\<pi>.product_cone_axioms by auto\n    qed\n\n  end\n\n  sublocale cartesian_category \\<subseteq> category_with_finite_products\n  proof\n    obtain t where t: \"terminal t\" using has_terminal by blast\n    { fix n :: nat\n      have \"\\<And>I :: nat set. finite I \\<and> card I = n \\<Longrightarrow> has_products I\"\n      proof (induct n)\n        show \"\\<And>I :: nat set. finite I \\<and> card I = 0 \\<Longrightarrow> has_products I\"\n        proof -\n          fix I :: \"nat set\"\n          assume \"finite I \\<and> card I = 0\"\n          hence I: \"I = {}\" by force\n          thus \"has_products I\"\n          proof -\n            interpret J: discrete_category I 0\n              apply unfold_locales using I by auto\n            have \"\\<And>D. discrete_diagram J.comp C D \\<Longrightarrow> \\<exists>a. has_as_product J.comp D a\"\n            proof -\n              fix D\n              assume D: \"discrete_diagram J.comp C D\"\n              interpret D: discrete_diagram J.comp C D using D by auto\n              interpret D: empty_diagram J.comp C D\n                 using I J.arr_char by unfold_locales simp\n              have \"has_as_product J.comp D t\"\n                using t D.has_as_limit_iff_terminal has_as_product_def product_cone_def\n                      J.category_axioms category_axioms D.discrete_diagram_axioms\n                by metis\n              thus \"\\<exists>a. has_as_product J.comp D a\" by blast\n            qed\n            moreover have \"I \\<noteq> UNIV\"\n              using I by blast\n            ultimately show ?thesis\n              using I has_products_def\n              by (metis category_with_terminal_object.has_terminal discrete_diagram.product_coneI\n                  discrete_diagram_def empty_diagram.has_as_limit_iff_terminal empty_diagram.intro\n                  empty_diagram_axioms.intro empty_iff has_as_product_def\n                  is_category_with_terminal_object mem_Collect_eq)\n          qed\n        qed\n        show \"\\<And>n I :: nat set.\n                \\<lbrakk> (\\<And>I :: nat set. finite I \\<and> card I = n \\<Longrightarrow> has_products I);\n                  finite I \\<and> card I = Suc n \\<rbrakk>\n                    \\<Longrightarrow> has_products I\"\n        proof -\n          fix n :: nat\n          fix I :: \"nat set\"\n          assume IH: \"\\<And>I :: nat set. finite I \\<and> card I = n \\<Longrightarrow> has_products I\"\n          assume I: \"finite I \\<and> card I = Suc n\"\n          show \"has_products I\"\n          proof -\n            have \"card I = 1 \\<Longrightarrow> has_products I\"\n              using I has_unary_products by blast\n            moreover have \"card I \\<noteq> 1 \\<Longrightarrow> has_products I\"\n            proof -\n              assume \"card I \\<noteq> 1\"\n              hence cardI: \"card I > 1\" using I by simp\n              obtain i where i: \"i \\<in> I\" using cardI by fastforce\n              let ?I0 = \"{i}\" and ?I1 = \"I - {i}\"\n              have 1: \"I = ?I0 \\<union> ?I1 \\<and> ?I0 \\<inter> ?I1 = {} \\<and> card ?I0 = 1 \\<and> card ?I1 = n\"\n                using i I cardI by auto\n              show \"has_products I\"\n              proof (unfold has_products_def, intro conjI allI impI)\n                show \"I \\<noteq> UNIV\"\n                  using I by auto\n                fix J D\n                assume D: \"discrete_diagram J C D \\<and> Collect (partial_magma.arr J) = I\"\n                interpret D: discrete_diagram J C D\n                  using D by simp\n                have Null: \"D.J.null \\<notin> ?I0 \\<and> D.J.null \\<notin> ?I1\"\n                  using D D.J.not_arr_null i by blast\n                interpret J0: discrete_category ?I0 D.J.null\n                  using 1 Null D by unfold_locales auto\n                interpret J1: discrete_category ?I1 D.J.null\n                  using Null by unfold_locales auto\n                interpret J0uJ1: discrete_category \\<open>Collect J0.arr \\<union> Collect J1.arr\\<close> J0.null\n                  using Null 1 J0.null_char J1.null_char by unfold_locales auto\n                interpret D0: discrete_diagram_from_map ?I0 C D D.J.null\n                  using 1 J0.ide_char D.preserves_ide D D.is_discrete i by unfold_locales auto\n                interpret D1: discrete_diagram_from_map ?I1 C D D.J.null\n                  using 1 J1.ide_char D.preserves_ide D D.is_discrete i by unfold_locales auto\n                obtain a0 where a0: \"has_as_product J0.comp D0.map a0\"\n                  using 1 has_unary_products [of ?I0] has_products_def [of ?I0]\n                        D0.discrete_diagram_axioms\n                  by fastforce\n                obtain a1 where a1: \"has_as_product J1.comp D1.map a1\"\n                  using 1 I IH [of ?I1] has_products_def [of ?I1] D1.discrete_diagram_axioms\n                  by blast\n                have 2: \"\\<exists>p0 p1. has_as_binary_product a0 a1 p0 p1\"\n                proof -\n                  have \"ide a0 \\<and> ide a1\"\n                    using a0 a1 product_is_ide by auto\n                  thus ?thesis\n                     using a0 a1 has_binary_products has_binary_products_def by simp\n                qed\n                obtain p0 p1 where a: \"has_as_binary_product a0 a1 p0 p1\"\n                  using 2 by auto\n                let ?a = \"dom p0\"\n                have \"has_as_product J D ?a\"\n                proof -\n                  have \"D = (\\<lambda>j. if j \\<in> Collect J0.arr then D0.map j\n                                 else if j \\<in> Collect J1.arr then D1.map j\n                                 else null)\"\n                  proof\n                    fix j\n                    show \"D j = (if j \\<in> Collect J0.arr then D0.map j\n                                 else if j \\<in> Collect J1.arr then D1.map j\n                                 else null)\"\n                      using 1 D0.map_def D1.map_def D.is_extensional D J0.arr_char J1.arr_char\n                      by auto\n                  qed\n                  moreover have \"J = J0uJ1.comp\"\n                  proof -\n                    have \"\\<And>j j'. J j j' = J0uJ1.comp j j'\"\n                    proof -\n                      fix j j'\n                      show \"J j j' = J0uJ1.comp j j'\"\n                        using D J0uJ1.arr_char J0.arr_char J1.arr_char D.is_discrete i\n                        apply (cases \"j \\<in> ?I0\", cases \"j' \\<in> ?I0\")\n                          apply simp_all\n                          apply auto[1]\n                         apply (metis D.J.comp_arr_ide D.J.comp_ide_arr D.J.ext D.J.seqE\n                            D.is_discrete J0.null_char J0uJ1.null_char)\n                        by (metis D.J.comp_arr_ide D.J.comp_ide_arr D.J.comp_ide_self\n                            D.J.ext D.J.seqE D.is_discrete J0.null_char J0uJ1.null_char\n                            mem_Collect_eq)\n                    qed\n                    thus ?thesis by blast\n                  qed\n                  moreover have \"Collect J0.arr \\<inter> Collect J1.arr = {}\"\n                    by auto\n                  moreover have \"J0.null = J1.null\"\n                    using J0.null_char J1.null_char by simp\n                  ultimately show \"has_as_product J D ?a\"\n                    using binary_product_of_products_is_product\n                            [of J0.comp D0.map a0 J1.comp D1.map a1 p0 p1]\n                          J0.arr_char J1.arr_char\n                          1 a0 a1 a\n                    by simp\n                qed\n                thus \"\\<exists>a. has_as_product J D a\" by blast\n              qed\n            qed\n            ultimately show \"has_products I\" by blast\n          qed\n        qed\n      qed\n    }\n    hence 1: \"\\<And>n I :: nat set. finite I \\<and> card I = n \\<Longrightarrow> has_products I\" by simp\n    thus \"\\<And>I :: nat set. finite I \\<Longrightarrow> has_products I\" by blast\n  qed\n\n  proposition (in cartesian_category) is_category_with_finite_products:\n  shows \"category_with_finite_products C\"\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/Category3/CartesianCategory.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8705972784807406, "lm_q2_score": 0.8198933315126791, "lm_q1q2_score": 0.7137969030594461}}
{"text": "(* Author: Tobias Nipkow *)\n\ntheory Abs_Int1_parity\nimports Abs_Int1\nbegin\n\nsubsection \"Parity Analysis\"\n\ndatatype parity = Even | Odd | Either\n\ntext\\<open>Instantiation of class @{class preord} with type @{typ parity}:\\<close>\n\ninstantiation parity :: preord\nbegin\n\ntext\\<open>First the definition of the interface function \\<open>\\<sqsubseteq>\\<close>. Note that\nthe header of the definition must refer to the ascii name @{const le} of the\nconstants as \\<open>le_parity\\<close> and the definition is named \\<open>le_parity_def\\<close>.  Inside the definition the symbolic names can be used.\\<close>\n\ndefinition le_parity where\n\"x \\<sqsubseteq> y = (y = Either \\<or> x=y)\"\n\ntext\\<open>Now the instance proof, i.e.\\ the proof that the definition fulfills\nthe axioms (assumptions) of the class. The initial proof-step generates the\nnecessary proof obligations.\\<close>\n\ninstance\nproof\n  fix x::parity show \"x \\<sqsubseteq> x\" by(auto simp: le_parity_def)\nnext\n  fix x y z :: parity assume \"x \\<sqsubseteq> y\" \"y \\<sqsubseteq> z\" thus \"x \\<sqsubseteq> z\"\n    by(auto simp: le_parity_def)\nqed\n\nend\n\ntext\\<open>Instantiation of class @{class SL_top} with type @{typ parity}:\\<close>\n\ninstantiation parity :: SL_top\nbegin\n\n\ndefinition join_parity where\n\"x \\<squnion> y = (if x \\<sqsubseteq> y then y else if y \\<sqsubseteq> x then x else Either)\"\n\ndefinition Top_parity where\n\"\\<top> = Either\"\n\ntext\\<open>Now the instance proof. This time we take a lazy shortcut: we do not\nwrite out the proof obligations but use the \\<open>goali\\<close> primitive to refer\nto the assumptions of subgoal i and \\<open>case?\\<close> to refer to the\nconclusion of subgoal i. The class axioms are presented in the same order as\nin the class definition.\\<close>\n\ninstance\nproof (standard, goal_cases)\n  case 1 (*join1*) show ?case by(auto simp: le_parity_def join_parity_def)\nnext\n  case 2 (*join2*) show ?case by(auto simp: le_parity_def join_parity_def)\nnext\n  case 3 (*join least*) thus ?case by(auto simp: le_parity_def join_parity_def)\nnext\n  case 4 (*Top*) show ?case by(auto simp: le_parity_def Top_parity_def)\nqed\n\nend\n\n\ntext\\<open>Now we define the functions used for instantiating the abstract\ninterpretation locales. Note that the Isabelle terminology is\n\\emph{interpretation}, not \\emph{instantiation} of locales, but we use\ninstantiation to avoid confusion with abstract interpretation.\\<close>\n\nfun \\<gamma>_parity :: \"parity \\<Rightarrow> val set\" where\n\"\\<gamma>_parity Even = {i. i mod 2 = 0}\" |\n\"\\<gamma>_parity Odd  = {i. i mod 2 = 1}\" |\n\"\\<gamma>_parity Either = UNIV\"\n\nfun num_parity :: \"val \\<Rightarrow> parity\" where\n\"num_parity i = (if i mod 2 = 0 then Even else Odd)\"\n\nfun plus_parity :: \"parity \\<Rightarrow> parity \\<Rightarrow> parity\" where\n\"plus_parity Even Even = Even\" |\n\"plus_parity Odd  Odd  = Even\" |\n\"plus_parity Even Odd  = Odd\" |\n\"plus_parity Odd  Even = Odd\" |\n\"plus_parity Either y  = Either\" |\n\"plus_parity x Either  = Either\"\n\ntext\\<open>First we instantiate the abstract value interface and prove that the\nfunctions on type @{typ parity} have all the necessary properties:\\<close>\n\ninterpretation Val_abs\nwhere \\<gamma> = \\<gamma>_parity and num' = num_parity and plus' = plus_parity\nproof (standard, goal_cases) txt\\<open>of the locale axioms\\<close>\n  fix a b :: parity\n  assume \"a \\<sqsubseteq> b\" thus \"\\<gamma>_parity a \\<subseteq> \\<gamma>_parity b\"\n    by(auto simp: le_parity_def)\nnext txt\\<open>The rest in the lazy, implicit way\\<close>\n  case 2 show ?case by(auto simp: Top_parity_def)\nnext\n  case 3 show ?case by auto\nnext\n  case (4 _ a1 _ a2) thus ?case\n  proof(cases a1 a2 rule: parity.exhaust[case_product parity.exhaust])\n  qed (auto, presburger)\nqed\n\ntext\\<open>Instantiating the abstract interpretation locale requires no more\nproofs (they happened in the instatiation above) but delivers the\ninstantiated abstract interpreter which we call AI:\\<close>\n\nglobal_interpretation Abs_Int\nwhere \\<gamma> = \\<gamma>_parity and num' = num_parity and plus' = plus_parity\ndefines aval_parity = aval' and step_parity = step' and AI_parity = AI\n..\n\n\nsubsubsection \"Tests\"\n\ndefinition \"test1_parity =\n  ''x'' ::= N 1;;\n  WHILE Less (V ''x'') (N 100) DO ''x'' ::= Plus (V ''x'') (N 2)\"\n\nvalue \"show_acom_opt (AI_parity test1_parity)\"\n\ndefinition \"test2_parity =\n  ''x'' ::= N 1;;\n  WHILE Less (V ''x'') (N 100) DO ''x'' ::= Plus (V ''x'') (N 3)\"\n\nvalue \"show_acom ((step_parity \\<top> ^^1) (anno None test2_parity))\"\nvalue \"show_acom ((step_parity \\<top> ^^2) (anno None test2_parity))\"\nvalue \"show_acom ((step_parity \\<top> ^^3) (anno None test2_parity))\"\nvalue \"show_acom ((step_parity \\<top> ^^4) (anno None test2_parity))\"\nvalue \"show_acom ((step_parity \\<top> ^^5) (anno None test2_parity))\"\nvalue \"show_acom_opt (AI_parity test2_parity)\"\n\n\nsubsubsection \"Termination\"\n\nglobal_interpretation Abs_Int_mono\nwhere \\<gamma> = \\<gamma>_parity and num' = num_parity and plus' = plus_parity\nproof (standard, goal_cases)\n  case (1 a1 a2 b1 b2) thus ?case\n  proof(cases a1 a2 b1 b2\n   rule: parity.exhaust[case_product parity.exhaust[case_product parity.exhaust[case_product parity.exhaust]]]) (* FIXME - UGLY! *)\n  qed (auto simp add:le_parity_def)\nqed\n\n\ndefinition m_parity :: \"parity \\<Rightarrow> nat\" where\n\"m_parity x = (if x=Either then 0 else 1)\"\n\nlemma measure_parity:\n  \"(strict{(x::parity,y). x \\<sqsubseteq> y})^-1 \\<subseteq> measure m_parity\"\nby(auto simp add: m_parity_def le_parity_def)\n\nlemma measure_parity_eq:\n  \"\\<forall>x y::parity. x \\<sqsubseteq> y \\<and> y \\<sqsubseteq> x \\<longrightarrow> m_parity x = m_parity y\"\nby(auto simp add: m_parity_def le_parity_def)\n\nlemma AI_parity_Some: \"\\<exists>c'. AI_parity c = Some c'\"\nby(rule AI_Some_measure[OF measure_parity measure_parity_eq])\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/Abs_Int_ITP2012/Abs_Int1_parity.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8705972583359805, "lm_q2_score": 0.8198933447152497, "lm_q1q2_score": 0.7137968980370133}}
{"text": "theory FMap\n  imports AT Complex_Main\nbegin\n\n(* some general techniques for mapping function on finite sets *)\n(* general scheme for map over finite sets.\n   This would be a useful provision for the Finite_Set library: everyone needs\n   a simple map on Finite Sets all the time! *)\ndefinition fmap :: \"['a \\<Rightarrow> 'b, 'a set] \\<Rightarrow> 'b set\"\n  where \"fmap f S = Finite_Set.fold (\\<lambda> x y. insert (f x) y) {} S\"\n\n(* doesn't work since not commutative -- consider \n   linear sorted domains and then use sorted_list_of_set\ndefinition fmapL :: \"['a \\<Rightarrow> 'b, 'a set] \\<Rightarrow> 'b list\"\n  where \"fmapL f S = Finite_Set.fold (\\<lambda> x y. (f x) # y) [] S\"\n*)\n\nlemma fmap_lem_map[rule_format]: \"finite S \\<Longrightarrow> n \\<in> S \\<longrightarrow> (f n) \\<in> (fmap f S)\"\n  apply (erule_tac F = S in finite_induct)\n   apply simp\n  apply clarify\n  apply (simp add: fmap_def)\n  apply (subgoal_tac \"comp_fun_commute (\\<lambda>x::'a. insert (f x))\")\n   apply (drule_tac A = \"F\" in Finite_Set.comp_fun_commute.fold_insert)\n     apply assumption+\n   apply (erule ssubst)\n   apply (erule disjE)\n  apply force+\napply (simp add: comp_fun_commute_def)\nby force\n\n\nlemma fmap_lem_map_rev[rule_format]: \"finite S \\<Longrightarrow> inj f \\<Longrightarrow> (f n) \\<in> (fmap f S) \\<longrightarrow> n \\<in> S\"\n  apply (erule_tac F = S in finite_induct)\n   apply (simp add: fmap_def)\n  apply clarify\n  apply (simp add: fmap_def)\n  apply (subgoal_tac \"comp_fun_commute (\\<lambda>x::'a. insert (f x))\")\n   apply (drule_tac A = \"F\" and z = \"{}\" in Finite_Set.comp_fun_commute.fold_insert)\n     apply assumption+\n   apply (subgoal_tac \"f n \\<in> insert (f x) (Finite_Set.fold (\\<lambda>x::'a. insert (f x)) {} F)\")\n    prefer 2\n    apply simp\n   apply (subgoal_tac \"f n = f x\")\n    prefer 2\n    apply simp\n   apply (erule injD, assumption) \napply (simp add: comp_fun_commute_def)\nby force\n\nlemma fold_one: \"Finite_Set.fold (\\<lambda>x::'a. insert (f x)) {} {n} = {f n}\"\n  thm Finite_Set.comp_fun_commute.fold_insert\n  apply (subgoal_tac \"comp_fun_commute (\\<lambda>x::'a. insert (f x))\")\n   apply (drule_tac A = \"{}\" in Finite_Set.comp_fun_commute.fold_insert)\n     apply simp+\n  apply (simp add: comp_fun_commute_def)\n  by force\n\n(*\nlemma fold_oneL: \"Finite_Set.fold (\\<lambda> (x::'a). (#)(f x)) [] {n} = [f n]\"\n  apply (subgoal_tac \"comp_fun_commute (\\<lambda> (x::'a). (#)(f x))\")\n   apply (drule_tac A = \"{}\" and z = \"[]\" in Finite_Set.comp_fun_commute.fold_insert)\n     apply simp+\n  apply (simp add: comp_fun_commute_def)\nfails here  \nby force\n*)\n\n\nlemma fold_one_plus: \"Finite_Set.fold (+) (b::real) {a::real} = a + b\"\n  apply (subgoal_tac \"comp_fun_commute (+)\")\n   apply (drule_tac A = \"{}\" in Finite_Set.comp_fun_commute.fold_insert)\n  apply simp+\n  apply (simp add: comp_fun_commute_def)\n  apply (simp add: comp_def)\nby force\n\nlemma fold_two_plus: \"a \\<noteq> c \\<Longrightarrow> Finite_Set.fold (+) (b::real) {a::real, c} = a + b + c\"\n  apply (subgoal_tac \"comp_fun_commute (+)\")\n   apply (drule_tac A = \"{ c}\" and x = a in Finite_Set.comp_fun_commute.fold_insert)\n     apply simp+\n   apply (simp add: fold_one_plus)\n   apply (subgoal_tac \"a + (c + b) = a + b + c\")\n    apply (erule ssubst)\n    apply assumption\n  apply simp\n  apply (simp add: comp_fun_commute_def)\n  apply (simp add: comp_def)\nby force\n\nlemma fold_three_plus: \"a \\<noteq> c \\<Longrightarrow> a \\<noteq> b \\<Longrightarrow> b \\<noteq> c \\<Longrightarrow> Finite_Set.fold (+) (d::real) {a::real, b, c} = a + b + c + d\"\n  apply (subgoal_tac \"comp_fun_commute (+)\")\n   apply (drule_tac A = \"{b, c}\" and x = a and z = d in Finite_Set.comp_fun_commute.fold_insert)\n     apply simp+\n   apply (simp add: fold_two_plus)\n  apply (simp add: comp_fun_commute_def)\n  apply (simp add: comp_def)\nby force\n\nlemma fmap_lem_one: \"fmap f {a} = {f a}\"\n  by (simp add: fmap_def fold_one)\n\n(*\nlemma fmapL_lem_one: \"fmapL f {a} = [f a]\"\n  by (simp add: fmapL_def fold_one)\n*)\n\nlemma fmap_lem[rule_format]: \"finite S \\<Longrightarrow> \\<forall> n. (fmap f (insert n S)) = (insert (f n) (fmap f S))\"\n  thm finite.induct\n  apply (erule_tac F = S in finite_induct)\n   apply (rule allI)\n   apply (simp add: fmap_def)\n   apply (rule fold_one)\n(* *)\n  apply (subgoal_tac \"comp_fun_commute (\\<lambda>x::'a. insert (f x))\")\n   apply (rule allI)\n   apply (drule_tac x = x in spec)\n   apply (erule ssubst)\n   apply (subgoal_tac \"fmap f (insert n (insert x F)) = insert (f n) (fmap f (insert x F))\")\n  apply (erule ssubst)\n    apply (subgoal_tac \"fmap f (insert x F) = insert (f x) (fmap f F)\")\n     apply simp\n    apply (drule_tac A = \"F\" in Finite_Set.comp_fun_commute.fold_insert)\n      apply assumption\n     apply assumption\n    apply (unfold fmap_def, assumption)\n   apply (case_tac \"n \\<in> insert x F\")\n    defer\n    apply (drule_tac A = \"insert x F\" in Finite_Set.comp_fun_commute.fold_insert)\n     apply simp\n  apply assumption+\n  apply (simp add: comp_fun_commute_def)\n  apply force\n(* n \\<in> insert x F *)\n  apply (simp add: Finite_Set.comp_fun_commute.fold_rec)\n  apply (subgoal_tac \"Finite_Set.fold (\\<lambda>x::'a. insert (f x)) {} (insert n (insert x F)) =\n                     Finite_Set.fold (\\<lambda>x::'a. insert (f x)) {} (insert x F)\")\n   prefer 2\n   apply (subgoal_tac \"insert n (insert x F) = insert x F\")\n    apply simp\n  apply blast\n  apply (erule ssubst)\n  apply (rule Finite_Set.comp_fun_commute.fold_rec)\napply (simp add: comp_fun_commute_def)\n   apply force\n  by simp\n\n\nlemma insert_delete: \"x \\<notin> S \\<Longrightarrow> (insert x S) - {x} = S\"\nby simp\n\nlemma fmap_lem_del[rule_format]: \"finite S \\<Longrightarrow> inj f \\<Longrightarrow> \\<forall> n \\<in> S. fmap f (S - {n}) = (fmap f S) - {f n}\"\n  apply (erule_tac F = S in finite_induct)\n   apply (rule ballI)\n   apply (simp add: fmap_def)\n(* *)\n  apply (subgoal_tac \"comp_fun_commute (\\<lambda>x::'a. insert (f x))\")\n   apply (rule ballI)\napply simp\n   apply (erule disjE)\n(* n = x *)\n    apply simp\n    apply (drule_tac A = \"F\" and z = \"{}\" in Finite_Set.comp_fun_commute.fold_insert)\n      apply assumption+\n    apply (unfold fmap_def)\n    apply (rotate_tac -1)\n  apply (erule ssubst)\n  apply (rule sym)\n    apply (rule insert_delete)\n    apply (erule contrapos_nn)\n  apply (rule fmap_lem_map_rev, assumption, assumption)\n  apply (simp add: fmap_def)\n(* n \\<in> F *)\n    apply (frule_tac A = \"F\" and z = \"{}\" in Finite_Set.comp_fun_commute.fold_insert, assumption, assumption)\n   apply (rotate_tac -1)\n   apply (erule ssubst)\n  apply (subgoal_tac \"insert (f x) (Finite_Set.fold (\\<lambda>x::'a. insert (f x)) {} F) - {f n} =\n                      insert (f x) ((Finite_Set.fold (\\<lambda>x::'a. insert (f x)) {} F) - {f n})\")\n   apply (rotate_tac -1)\n   apply (erule ssubst)\n   apply (drule_tac x = n in bspec,assumption)\n   apply (rotate_tac -1)\n   apply (erule subst)\n    apply (drule_tac A = \"F - {n}\" and z = \"{}\" and x = x in Finite_Set.comp_fun_commute.fold_insert)\n      apply simp+\n    apply (subgoal_tac \"insert x (F - {n}) = insert x F - {n}\")\n     apply simp\n    apply blast\n   apply (subgoal_tac \"f x \\<noteq> f n\")\n    apply force\n   apply (subgoal_tac \"x \\<noteq> n\")\n  apply (rotate_tac -1)\n  apply (erule contrapos_nn)\n    apply (erule injD, assumption)\n  apply blast\napply (simp add: comp_fun_commute_def)\nby force\n\n\nlemma fmap_empty1: \"(fmap f {} = S) \\<Longrightarrow> (S = {})\"\n  by (simp add: fmap_def)\n\nlemma fmap_empty2: \"S = {} \\<Longrightarrow> fmap f {} = S\"\n  by (simp add: fmap_def)\n\nlemma fmap_empty: \"(fmap f {} = S) = (S = {})\"\nproof  \n  show \"fmap f {} = S \\<Longrightarrow> S = {}\"\n    by (erule fmap_empty1)\nnext show  \"S = {} \\<Longrightarrow> fmap f {} = S\"\n    by (erule fmap_empty2)\nqed\n\nlemma fmap_empty3: \"fmap f {} = {}\"\n  by (simp add: fmap_def)\n\nlemma fmap_empty4[rule_format]: \"finite S \\<Longrightarrow> fmap f S = {} \\<longrightarrow> S = {}\"\n  apply (erule_tac F = S in finite_induct)\n  apply simp\n  apply (simp add: fmap_def)\n  apply (subgoal_tac \"Finite_Set.fold (\\<lambda>x::'a. insert (f x)) {} ({x}) \\<noteq> {}\")\n  apply (subgoal_tac \"Finite_Set.fold (\\<lambda>x::'a. insert (f x)) {} ({x}) \\<subseteq> \n                      Finite_Set.fold (\\<lambda>x::'a. insert (f x)) {} (insert x F)\")\n    apply blast\n  apply (subst fold_one)\n   apply (subgoal_tac \"comp_fun_commute (\\<lambda>x::'a. insert (f x))\")\n  thm Finite_Set.comp_fun_commute.fold_insert\n   apply (drule_tac A = \"F\" and z = \"{}\" in Finite_Set.comp_fun_commute.fold_insert)\n     apply simp\n     apply simp\n  apply (erule ssubst)\n    apply simp\n     apply (simp add: comp_fun_commute_def)\n     apply force\n    apply (subst fold_one)\n  by simp\n\n\nlemma insert_delete0: \"x \\<in> A \\<Longrightarrow> A = insert x (A - {x})\"\n  by auto\n\nlemma fmap_inj[rule_format]: \n  assumes \"finite S\" and \"inj f\"\n  shows \"\\<forall> S'. finite S' \\<longrightarrow> fmap f S = fmap f S' \\<longrightarrow> S = S'\"\n  using assms\nproof (erule_tac F = S in finite_induct, clarify)\n  show \"\\<And>S'::'a set. inj f \\<Longrightarrow> finite S \\<Longrightarrow> inj f \\<Longrightarrow> finite S' \\<Longrightarrow> \n        fmap f {} = fmap f S' \\<Longrightarrow> {} = S'\"\n    apply (rule sym)\n    apply (rule_tac f = f in fmap_empty4)\n    apply assumption\nby (erule fmap_empty1)\nnext show \"\\<And>(x::'a) F::'a set.\n       inj f \\<Longrightarrow>\n       finite F \\<Longrightarrow>\n       x \\<notin> F \\<Longrightarrow>\n       \\<forall>S'::'a set. finite S' \\<longrightarrow> fmap f F = fmap f S' \\<longrightarrow> F = S' \\<Longrightarrow>\n       \\<forall>S'::'a set. finite S' \\<longrightarrow> fmap f (insert x F) = fmap f S' \\<longrightarrow> insert x F = S'\"\n  proof (clarify)\n    fix x F S'\n    assume a0: \"inj f\"\n       and a1: \"finite F\"\n       and a1a: \"x \\<notin> F\"\n       and a2: \"\\<forall>S'::'a set. finite S' \\<longrightarrow> fmap f F = fmap f S' \\<longrightarrow> F = S'\"\n       and a3: \"finite S'\"\n       and a4: \"fmap f (insert x F) = fmap f S'\"\n    show \"insert x F = S'\"\n    proof -\n      have a5: \"insert (f x) (fmap f F) = fmap f S'\" \n        by (insert fmap_lem[of F f x], drule meta_mp, rule a1, erule subst, rule a4) \n      have a6: \"f x \\<in> fmap f S'\" by (insert a5, erule subst, simp)\n      have a6a: \"x \\<in> S'\" by (rule fmap_lem_map_rev, rule a3, rule a0, rule a6)\n      have a7: \"fmap f S' = insert (f x) ((fmap f S') - {f x})\" \n        by (insert insert_delete0[of \"f x\" \"(fmap f S')\"],drule meta_mp, rule a6)\n      have a8: \"insert (f x) (fmap f F) = insert (f x) ((fmap f S') - {f x})\" \n        by (subst a5, subst a7, rule refl)\n      have a9: \"f x \\<notin> (fmap f F)\" using a0 a1 a1a\n        apply (rule_tac P = \"f x \\<in> fmap f F\" in notI, subgoal_tac \"x \\<in> F\")\n          apply (rule notE, rule a1a, assumption)\n        by (rule fmap_lem_map_rev)\n      have a10: \"f x \\<notin> ((fmap f S') - {f x})\" by simp\n      have a11: \"fmap f F = ((fmap f S') - {f x})\" by (insert a8 a9 a10, force) \n      have a12: \"x \\<in> S' \\<Longrightarrow> fmap f F = fmap f (S' - {x})\" \n        apply (insert fmap_lem_del[of S' f x])\n        apply (drule meta_mp)\n         apply (rule a3)\n        apply (drule meta_mp)\n         apply (rule a0)\n        apply (drule meta_mp, assumption)\n        apply (erule ssubst)\n        by (rule a11)\n(*      have a13: \"x \\<notin> S' \\<Longrightarrow> f x \\<notin> fmap f S'\" \n        by (erule contrapos_nn, rule fmap_lem_map_rev, rule a3, rule a0)\n      have a14: \"x \\<notin> S' \\<Longrightarrow> fmap f F = (fmap f S')\" \n        by (insert a13, drule meta_mp, assumption, subst a11, simp) *)\n      show \"insert x F = S'\"\n        apply (insert a6a)\n         apply (insert a2)\n         apply (drule_tac x = \"S' - {x}\" in spec)\n         apply (drule mp)\n          apply (simp add: a3)\n         apply (drule mp)\n          apply (erule a12)\n         apply (erule ssubst)\n        apply (rule sym)\n        by (erule insert_delete0)\n    qed\n  qed\nqed\n\nlemma fmap_inj0: \"inj f \\<Longrightarrow> inj_on (fmap f){S. finite S}\"\n  apply (rule inj_onI)\n  apply (rule fmap_inj)\n  by simp+\n\n\n\n\nlemma fmap_lem_map_rev0[rule_format]: \"finite S \\<Longrightarrow> (\\<forall>y\\<in>S. f y \\<noteq> f n) \\<longrightarrow> (f n) \\<in> (fmap f S) \\<longrightarrow> n \\<in> S\"\n  apply (erule_tac F = S in finite_induct)\n   apply (simp add: fmap_def)\n  apply clarify\n  apply (simp add: fmap_def)\n  apply (subgoal_tac \"comp_fun_commute (\\<lambda>x::'a. insert (f x))\")\n   apply (drule_tac A = \"F\" and z = \"{}\" in Finite_Set.comp_fun_commute.fold_insert)\n     apply assumption+\n   apply (subgoal_tac \"f n \\<in> insert (f x) (Finite_Set.fold (\\<lambda>x::'a. insert (f x)) {} F)\")\n    prefer 2\n    apply simp\n   apply (subgoal_tac \"f n = f x\")\n  apply simp\n    apply simp\napply (simp add: comp_fun_commute_def)\nby force\n\nlemma fmap_lem_map_rev1: \"finite S \\<Longrightarrow> (\\<forall>y\\<in>S. f y \\<noteq> f n) \\<Longrightarrow> (f n) \\<in> (fmap f S) \\<Longrightarrow> n \\<in> S\"\n  apply (erule fmap_lem_map_rev0)\n  apply (drule bspec, assumption, assumption)\n  by assumption\n\nlemma fmap_lem_del_set1[rule_format]: \"finite S \\<Longrightarrow> \n                        \\<forall> n \\<in> S. fmap f (S - {y. f y = f n}) = (fmap f S) - {f n}\"\n  apply (erule_tac F = S in finite_induct)\n   apply (rule ballI)\n   apply (simp add: fmap_def)\n(* *)\n  apply (subgoal_tac \"comp_fun_commute (\\<lambda>x::'a. insert (f x))\")\n   apply (rule ballI)\n   prefer 2\napply (simp add: comp_fun_commute_def)\n   apply force\n(* *)\n  apply (case_tac \"n = x\")\n   apply (simp add: fmap_def)\n   apply (frule_tac A = \"F\" and z = \"{}\" in Finite_Set.comp_fun_commute.fold_insert)\n     apply assumption+\n   apply (rotate_tac -1)\n  apply (erule ssubst)\n(* *)\n    apply simp\n    apply (case_tac \"\\<exists> y \\<in> F. f y = f x\")\n     apply (erule bexE)\n     apply (drule_tac x = y in bspec, assumption)\n     apply simp+\n   apply (subgoal_tac \"F - {y::'a. f y = f x} = F - {x}\")\n    prefer 2\n  apply blast\n  apply (rotate_tac -1)\n  apply (erule ssubst)\n   apply simp\n  apply (subgoal_tac \"(f x) \\<notin> Finite_Set.fold (\\<lambda>x::'a. insert (f x)) {} F \")\n    apply simp\n   apply (erule contrapos_nn)\n   apply (rule fmap_lem_map_rev1, assumption, assumption)\n   apply (simp add: fmap_def)\n(* *)\n  apply (subgoal_tac \"n \\<in> F\")\n   apply (drule_tac x = n in bspec, assumption)\n  apply (frule_tac f = f and n = x in fmap_lem)\n   apply (rotate_tac -1)\n   apply (erule ssubst)\n(* *)\n  apply (case_tac \"f x = f n\")\n    apply simp\n  apply simp\n   apply (subgoal_tac \"insert (f x) (fmap f F) - {f n} = insert (f x) ((fmap f F) - {f n})\")\n    prefer 2\n    apply force\n  apply (rotate_tac -1)\n   apply (erule ssubst)\n   apply (subgoal_tac \"insert x F - {y::'a. f y = f n} = insert x (F - {y::'a. f y = f n})\")\n    prefer 2\n    apply force\n  apply (rotate_tac -1)\n   apply (erule ssubst)\n   apply (subgoal_tac \"finite (F - {y::'a. f y = f n})\")\n    apply (rotate_tac -1)\n  apply (drule_tac S = \"(F - {y::'a. f y = f n})\" and f = f and n = x in fmap_lem)\n    apply simp\n   apply simp\n  by (simp add: comp_fun_commute_def)\n\nlemma fmap_set_rep_lem[rule_format]: \"finite S \\<Longrightarrow> \n        S \\<noteq> {} \\<longrightarrow> x \\<in> Finite_Set.fold (\\<lambda>x::'a. insert (f x)) {} S \\<longrightarrow> (\\<exists>y::'a\\<in>S. x = f y)\"\n  apply (erule_tac F = S in finite_induct)\n   apply simp\n  apply (case_tac \"F = {}\")\n   apply (simp add: fold_one)\n  apply simp\n  by (metis (full_types) empty_iff fold_infinite image_fold_insert image_insert insert_iff)\n\n\n\nlemma fmap_set_rep[rule_format]: \"finite S \\<Longrightarrow>  fmap f S = {x. \\<exists> y \\<in> S. x = f y}\"\nproof (rule equalityI, rule subsetI, rule CollectI)\n  show \"\\<And>x::'b. finite S \\<Longrightarrow> x \\<in> fmap f S \\<Longrightarrow> \\<exists>y::'a\\<in>S. x = f y\"\n    apply (simp add: fmap_def)\n    apply (case_tac \"S = {}\")\n     apply simp\n    by (simp add: fmap_set_rep_lem)\nnext show \"finite S \\<Longrightarrow> {x::'b. \\<exists>y::'a\\<in>S. x = f y} \\<subseteq> fmap f S\"\n    apply (rule subsetI)\n    apply (drule CollectD)\n    apply (erule bexE)\n    apply (erule ssubst)\n  by (erule fmap_lem_map, assumption)\nqed\n\nlemma fmap_set_rep'[rule_format]: \"finite S \\<Longrightarrow>  fmap f S = f `S\"\nproof (subst fmap_set_rep, assumption, simp add: image_def)\nqed\n\nlemma fmap_set_del_set0[rule_format]: \"finite S \\<Longrightarrow>\n   \\<forall> S'.  inj_on f S \\<longrightarrow> S' \\<subseteq> S \\<longrightarrow> f ` S - f ` S' = f ` (S - S')\"\n  apply (erule_tac F = S in finite_induct)\n   apply simp\n  by (metis Diff_subset inj_on_image_set_diff)\n\nthm inj_on_image_set_diff\nthm fmap_def\n\nlemma fmap_set_del_set1[rule_format]: \"inj_on f S \\<Longrightarrow> S' \\<subseteq> S \n        \\<Longrightarrow> f ` S - f ` S' = f ` (S - S')\"\n  by (metis Diff_subset inj_on_image_set_diff)\n\nlemma fmap_set_del_set: \"finite S \\<Longrightarrow> inj_on f S \\<Longrightarrow>\n    S' \\<subseteq> S \\<Longrightarrow> fmap f S - fmap f S' = fmap f (S - S')\" \n  apply (subst fmap_set_rep', assumption)\n  apply (subst fmap_set_rep')\n   apply (erule finite_subset, assumption)\n  apply (subst fmap_set_rep')\n  apply (rule_tac A = \"S - S'\" and B = S in finite_subset)\n  apply blast\n  apply assumption\nby (erule fmap_set_del_set0)\n\nlemma fmap_set_del_set: \"finite S \\<Longrightarrow> inj f \\<Longrightarrow>\n    finite S' \\<Longrightarrow>  fmap f S - fmap f S' = fmap f (S - S')\" \n  apply (subst fmap_set_rep', assumption)\n  apply (subst fmap_set_rep', assumption)\n  apply (subst fmap_set_rep')\n  apply simp\n\napply (erule fmap_set_del_set0)\n  oops\n\n\nlemma image_inj[rule_format]: \"inj f \\<Longrightarrow> f ` S = f ` S' \\<Longrightarrow> S = S'\"\n  by (simp add: inj_image_eq_iff)\n\n\n\n\n(* In a similar vain: some simple summation on finite sets\ndefinition fmap :: \"['a \\<Rightarrow> 'b, 'a set] \\<Rightarrow> 'b set\"\n  where \"fmap f S = Finite_Set.fold (\\<lambda> x y. insert (f x) y) {} S\"\n*)\ndefinition fsum :: \"real set \\<Rightarrow>  real\"\n  where \"fsum S = Finite_Set.fold (\\<lambda> x y. x + y) 0 S\"\n\ndefinition fsumap :: \"['a \\<Rightarrow> real, 'a set] \\<Rightarrow> real\"\n  where \"fsumap f S = Finite_Set.fold (\\<lambda> x y. (f x) + y) (0 :: real) S\"\n\nlemma fsumap_fold_one: \"Finite_Set.fold (\\<lambda>x y. (f x) + y) (0 :: real) {n} = f n\"\n  thm Finite_Set.comp_fun_commute.fold_insert\n  apply (subgoal_tac \"comp_fun_commute (\\<lambda>x. (+)(f x))\")\n   apply (drule_tac A = \"{}\" and z = 0 and x = n in Finite_Set.comp_fun_commute.fold_insert)\n     apply simp+\n  apply (simp add: comp_fun_commute_def)\n  by force\n\nlemma fsumap_lem[rule_format]: \"finite S \\<Longrightarrow> \\<forall> n. n \\<notin> S \\<longrightarrow> (fsumap f (insert n S)) = (f n) + (fsumap f S)\"\n  thm finite.induct\n  apply (erule_tac F = S in finite_induct)\n   apply (rule allI)\n   apply (simp add: fsumap_def)\n   apply (rule fsumap_fold_one)\n(* *)\n  apply (subgoal_tac \"comp_fun_commute (\\<lambda>x. (+)(f x))\")\n   apply (rule allI, rule impI)\n   apply (drule_tac x = x in spec)\n  apply (drule mp, assumption)\n   apply (erule ssubst)\n  apply (subgoal_tac \"fsumap f (insert n (insert x F)) = f n + (fsumap f (insert x F))\")\n    apply (erule ssubst)\n    apply (subgoal_tac \"fsumap f (insert x F) = (f x + fsumap f F)\")\n         apply simp\n    apply (drule_tac A = \"F\" in Finite_Set.comp_fun_commute.fold_insert)\n      apply assumption\n     apply assumption\n    apply (unfold fsumap_def, assumption)\n   apply (case_tac \"n \\<in> insert x F\")\n    defer\n    apply (drule_tac A = \"insert x F\" in Finite_Set.comp_fun_commute.fold_insert)\n     apply simp\n  apply assumption+\n  apply (simp add: comp_fun_commute_def)\nby force+\n(* n \\<in> insert x F is not possible \n  apply (subgoal_tac \"Finite_Set.fold (\\<lambda>x::'a. (+) (f x)) (0::real) (insert n (insert x F)) =\n                      Finite_Set.fold (\\<lambda>x::'a. (+) (f x)) (0::real) (insert x F)\")\n     prefer 2\n   apply (subgoal_tac \"insert n (insert x F) = insert x F\")\n    apply simp\n  apply blast\n  apply (erule ssubst)\n  apply (simp add: Finite_Set.comp_fun_commute.fold_rec)\napply (simp add: comp_fun_commute_def)\n   apply force\n*)\n\nprimrec map :: \"('a \\<Rightarrow> 'b) \\<Rightarrow> 'a list \\<Rightarrow> 'b list\"\n  where\n   map_empty: \"map f [] = []\"\n|  map_step: \"map f (a # l) = (f a) #(map f l)\"\n\ndefinition lsum :: \"real list \\<Rightarrow> real\"\n  where \"lsum rl \\<equiv>  fold (\\<lambda> x y. x + y) rl 0\"\n\nend", "meta": {"author": "flokam", "repo": "IsabelleAT", "sha": "b8d80c31ac13fdf8c7710f7ae032233b3fa474da", "save_path": "github-repos/isabelle/flokam-IsabelleAT", "path": "github-repos/isabelle/flokam-IsabelleAT/IsabelleAT-b8d80c31ac13fdf8c7710f7ae032233b3fa474da/FMap.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916170039421, "lm_q2_score": 0.8267117940706734, "lm_q1q2_score": 0.7137760326789087}}
{"text": "theory ext_Analysis_More\n  imports Ordinary_Differential_Equations.Flow\nbegin\n\nsubsection \\<open>Some results about derivatives\\<close>\n\ntext \\<open>Projection of has_vector_derivative onto components.\\<close>\nlemma has_vector_derivative_proj:\n  assumes \"(p has_vector_derivative q t) (at t within D)\"\n  shows \"((\\<lambda>t. p t $ i) has_vector_derivative q t $ i) (at t within D)\"\n  using assms unfolding has_vector_derivative_def has_derivative_def \n  apply (simp add: bounded_linear_scaleR_left)\n  using tendsto_vec_nth by fastforce\n\nlemma has_vderiv_on_proj:\n  assumes \"(p has_vderiv_on q) D\"\n  shows \"((\\<lambda>t. p t $ i) has_vderiv_on (\\<lambda>t. q t $ i)) D\"\n  using assms unfolding has_vderiv_on_def \n  by (simp add: has_vector_derivative_proj)\n\nlemma has_vector_derivative_projI:\n  assumes \"\\<forall>i. ((\\<lambda>t. p t $ i) has_vector_derivative q t $ i) (at t within D)\"\n  shows \"(p has_vector_derivative q t) (at t within D)\"\n  using assms unfolding has_vector_derivative_def has_derivative_def\n  apply (auto simp add: bounded_linear_scaleR_left)\n  by (auto intro: vec_tendstoI)\n\nlemma has_derivative_coords [simp,derivative_intros]:\n  \"((\\<lambda>t. t$i) has_derivative (\\<lambda>t. t$i)) (at x)\"\n  unfolding has_derivative_def by auto\n\nlemma has_vector_derivative_divide[derivative_intros]:\n  fixes a:: \"'a::real_normed_field\"\n  shows \"(f has_vector_derivative x) F \\<Longrightarrow> ((\\<lambda>x. f x / a) has_vector_derivative (x/a)) F\"\n  unfolding divide_inverse by(fact has_vector_derivative_mult_left)\n\nlemma has_derivative_divide[derivative_intros]:\n  fixes a:: \"'a::real_normed_field\"\n  shows \"(f has_derivative g) F \\<Longrightarrow> ((\\<lambda>x. f x / a) has_derivative (\\<lambda>x. g x / a)) F\"\n  unfolding divide_inverse by(fact has_derivative_mult_left)\n\n\ntext \\<open>If the derivative is always 0, then the function is always 0.\\<close>\nlemma mvt_real_eq:\n  fixes p :: \"real \\<Rightarrow> real\"\n  assumes \"\\<forall>t\\<in>{0 .. d}. (p has_derivative q t) (at t within {0 .. d}) \"\n    and \"d \\<ge> 0\"\n    and \"\\<forall>t\\<in>{0 ..<d}. \\<forall>s. q t s = 0\"\n    and \"x \\<in> {0 .. d}\"\n  shows \"p 0 = p x\" \nproof -\n  have \"\\<forall>t\\<in>{0 .. x}. (p has_derivative q t) (at t within {0 .. x})\"\n    using assms \n    by (meson atLeastAtMost_iff atLeastatMost_subset_iff has_derivative_subset in_mono order_refl)\n  then show ?thesis\n  using assms\n  using mvt_simple[of 0 x p q]\n  by force\nqed\n\ntext \\<open>If the derivative is always non-negative, then the function is increasing.\\<close>\nlemma mvt_real_ge:\n  fixes p :: \"real \\<Rightarrow>real\"\n assumes \"\\<forall>t\\<in>{0 .. d}. (p has_derivative q t) (at t within {0 .. d}) \"\n  and \"d \\<ge> 0\"\n  and \"\\<forall>t\\<in>{0 ..<d}. \\<forall>s\\<ge>0. q t s \\<ge> 0\"\n  and \"x \\<in> {0 .. d}\"\n  shows \"p 0 \\<le> p x\"\nproof -\n  have \"\\<forall>t\\<in>{0 .. x}. (p has_derivative q t) (at t within {0 .. x})\"\n    using assms \n    by (meson atLeastAtMost_iff atLeastatMost_subset_iff has_derivative_subset in_mono order_refl)\n  then show ?thesis\n  using assms\n  using mvt_simple[of 0 x p q]\n  by (smt atLeastAtMost_iff atLeastLessThan_iff greaterThanLessThan_iff)\nqed\n\ntext \\<open>If the derivative is always non-positive, then the function is decreasing.\\<close>\nlemma mvt_real_le:\n  fixes p :: \"real \\<Rightarrow>real\"\n  assumes \"\\<forall>t\\<in>{0 .. d}. (p has_derivative q t) (at t within {0 .. d}) \"\n    and \"d \\<ge> 0\"\n    and \"\\<forall>t\\<in>{0 ..<d}. \\<forall>s\\<ge>0 . q t s \\<le> 0\"\n    and \"x \\<in> {0 .. d}\"\n  shows \"p 0 \\<ge> p x\"\nproof -\n  have \"\\<forall>t\\<in>{0 .. x}. (p has_derivative q t) (at t within {0 .. x})\"\n    using assms \n    by (meson atLeastAtMost_iff atLeastatMost_subset_iff has_derivative_subset in_mono order_refl)\n  then obtain xa where \"xa\\<in>{0<..<x}\" \" p x - p 0 = q xa (x - 0)\" if \"x>0\"\n    using  mvt_simple[of 0 x p q] \n    using atLeastAtMost_iff by blast\n  then have \"p x \\<le> p 0\" if \"x>0\"\n  using assms \n  by (smt atLeastAtMost_iff atLeastLessThan_iff greaterThanLessThan_iff)\n  then show ?thesis\n    using assms  by fastforce\n  \nqed\n\n\nlemma real_inv_le:\n  fixes p :: \"real \\<Rightarrow> real\" and con :: real\n  assumes \"\\<forall>t\\<in>{-e..d+e}. (p has_derivative q t) (at t within {-e..d+e})\"\n    and \"d \\<ge> 0\"\n    and \"\\<forall>t\\<in>{0 ..<d}. (p t = con \\<longrightarrow> q t 1 < 0)\"\n    and \"p 0 \\<le> con \"\n    and \"x \\<in> {0 .. d}\"\n    and \"e > 0\"\n  shows \"p x \\<le> con\" \nproof (rule ccontr) \n  assume a:\" \\<not> p x \\<le> con\"\n  have 1:\"p x > con\"\n    using a by auto\n  have 2:\"\\<forall>t\\<in>{0 .. d}. continuous (at t within {-e<..<d+e}) p\"\n    using assms has_derivative_subset\n    using has_derivative_continuous \n    by (smt atLeastAtMost_iff continuous_within_subset greaterThanLessThan_subseteq_atLeastAtMost_iff greaterThan_iff)\n  have 3:\"\\<forall>t\\<in>{0 .. d}. isCont p t\"\n    apply auto subgoal for t\n      using continuous_within_open[of t \"{-e<..<d+e}\" p]\n      using 2 assms(5) assms(6) by auto\n    done\n  have 4:\"{y. p y = con \\<and> y \\<in> {0 .. x}} \\<noteq> {}\"\n    using IVT[of p 0 con x] using 3 1 assms \n    by auto\n  have 5: \"{y. p y = con \\<and> y \\<in> {0 .. x}} = ({0 .. x} \\<inter> p -` {con})\"\n    by auto\n  have 6: \"closed ({0 .. x} \\<inter> p -` {con})\"\n    using 3 assms(5) apply simp\n    apply (rule continuous_closed_preimage)\n      apply auto\n    by (simp add: continuous_at_imp_continuous_on)\n  have 7: \"compact {0 .. x}\"\n    using assms\n    by blast\n  have 8: \"compact {y. p y = con \\<and> y \\<in> {0 .. x}}\"\n    apply auto\n    using 4 5 6 7 \n    by (smt Collect_cong Int_left_absorb atLeastAtMost_iff compact_Int_closed)\n  obtain t where t1:\"t \\<in> {y. p y = con \\<and> y \\<in> {0 .. x}}\" and t2:\"\\<forall> tt\\<in> {y. p y = con \\<and> y \\<in> {0 .. x}}. tt \\<le>t\"\n    using compact_attains_sup[of \"{y. p y = con \\<and> y \\<in> {0 .. x}}\"] 4 8 \n    by blast\n  have 9:\"t<x\"\n    using t1 1 \n    using leI by fastforce\n  have 10:\"p tt > con\" if \"tt\\<in>{t<..x}\" for tt\n  proof(rule ccontr)\n    assume \"\\<not> con < p tt\"\n    then have not:\"p tt \\<le>con\" by auto\n    have \"\\<exists> t' \\<in> {t<..x}. p t' = con\"\n    proof(cases \"p tt = con\")\n      case True\n      then show ?thesis using that by auto\n    next\n      case False\n      then have \"p tt < con\"\n        using not by auto\n      then have \"{y. p y = con \\<and> y \\<in> {tt .. x}} \\<noteq> {}\"\n        using IVT[of p tt con x] using 3 1 assms that t1 \n        by auto\n      then show ?thesis using that by auto\n    qed\n    then show False using t1 t2 9 \n      using atLeastAtMost_iff greaterThanAtMost_iff by auto\n  qed     \n  have 11:\"(p has_derivative q t) (at t within {-e..d+e})\"\n    using assms t1 by auto\n  then have 12:\"\\<forall>s . q t s = q t 1 * s\"\n    using has_derivative_bounded_linear[of p \"q t\" \"(at t within {-e..d+e})\"]\n    using real_bounded_linear by auto\n  have 13:\"(p has_real_derivative q t 1) (at t within {-e..d+e})\"\n    using 11 12 \n    by (metis has_derivative_imp_has_field_derivative mult.commute)\n  have 14:\"q t 1 < 0\" using t1 assms 9 by auto\n  have 15:\"\\<exists>dd>0. \\<forall>h>0. t + h \\<in> {-e..d+e} \\<longrightarrow> h < dd \\<longrightarrow> p (t + h) < p t\"\n    using has_real_derivative_neg_dec_right[of p \"q t 1\" t \"{-e..d+e}\"] 13 14 \n    by auto\n  then obtain dd where d1:\"\\<forall>h>0. t + h \\<in> {-e..d+e} \\<longrightarrow> h < dd \\<longrightarrow> p (t + h) < p t\" and d2:\"dd>0\" by auto\n  then have 16:\"min (dd/2) (x-t)/2 < dd\" and \"min (dd/2) (x-t)/2 > 0\"\n    using 9 by auto\n  then have 17:\"(t + min (dd/2) (x-t)/2)> t\" \"(t + min (dd/2) (x-t)/2) < x\" \n    apply auto\n    using d2 9\n     by (smt field_sum_of_halves)\n   then have 18:\"p (t + min (dd/2) (x-t)/2) < p t\"\n    using d1 t1 16 assms(5) assms(6) by auto\n  have 19:\"p (t + min (dd/2) (x-t)/2)>con\" using 10 17 by auto\n  show False using 18 19 t1\n    by auto \n  qed\n\n\nlemma real_inv_ge:\n  fixes p :: \"real \\<Rightarrow> real\" and con :: real\n  assumes \"\\<forall>t\\<in>{-e..d+e}. (p has_derivative q t) (at t within {-e..d+e})\"\n    and \"d \\<ge> 0\"\n    and \"\\<forall>t\\<in>{0 ..<d}. (p t = con \\<longrightarrow> q t 1 > 0)\"\n    and \"p 0 \\<ge> con \"\n    and \"x \\<in> {0 .. d}\"\n    and \"e > 0\"\n  shows \"p x \\<ge> con\" \nproof (rule ccontr) \n  assume a:\" \\<not> p x \\<ge> con\"\n  have 1:\"p x < con\"\n    using a by auto\n  have \" \\<forall>t\\<in>{- e..d + e}. (p has_derivative q t) (at t within {- e<..<d + e})\"\n    using assms has_derivative_subset\n    by (smt greaterThanLessThan_subseteq_atLeastAtMost_iff)\n  then have \" \\<forall>t\\<in>{0..d}. (p has_derivative q t) (at t within {- e<..<d + e})\"\n    using assms by auto\n  then have 2:\"\\<forall>t\\<in>{0 .. d}. continuous (at t within {-e<..<d+e}) p\"\n    using has_derivative_continuous \n    by blast\n  have 3:\"\\<forall>t\\<in>{0 .. d}. isCont p t\"\n    apply auto subgoal for t\n      using continuous_within_open[of t \"{-e<..<d+e}\" p]\n      using 2 assms(5) assms(6) by auto\n    done\n  have 4:\"{y. p y = con \\<and> y \\<in> {0 .. x}} \\<noteq> {}\"\n    using IVT2[of p x con 0] using 3 1 assms \n    by auto\n  have 5: \"{y. p y = con \\<and> y \\<in> {0 .. x}} = ({0 .. x} \\<inter> p -` {con})\"\n    by auto\n  have 6: \"closed ({0 .. x} \\<inter> p -` {con})\"\n    using 3 assms(5) apply simp\n    apply (rule continuous_closed_preimage)\n      apply auto\n    by (simp add: continuous_at_imp_continuous_on)\n  have 7: \"compact {0 .. x}\"\n    using assms\n    by blast\n  have 8: \"compact {y. p y = con \\<and> y \\<in> {0 .. x}}\"\n    apply auto\n    using 4 5 6 7 \n    by (smt Collect_cong Int_left_absorb atLeastAtMost_iff compact_Int_closed)\n  obtain t where t1:\"t \\<in> {y. p y = con \\<and> y \\<in> {0 .. x}}\" and t2:\"\\<forall> tt\\<in> {y. p y = con \\<and> y \\<in> {0 .. x}}. tt \\<le>t\"\n    using compact_attains_sup[of \"{y. p y = con \\<and> y \\<in> {0 .. x}}\"] 4 8 \n    by blast\n  have 9:\"t<x\"\n    using t1 1 \n    using leI by fastforce\n  have 10:\"p tt < con\" if \"tt\\<in>{t<..x}\" for tt\n  proof(rule ccontr)\n    assume \"\\<not> con > p tt\"\n    then have not:\"p tt \\<ge> con\" by auto\n    have \"\\<exists> t' \\<in> {t<..x}. p t' = con\"\n    proof(cases \"p tt = con\")\n      case True\n      then show ?thesis using that by auto\n    next\n      case False\n      then have \"p tt > con\"\n        using not by auto\n      then have \"{y. p y = con \\<and> y \\<in> {tt .. x}} \\<noteq> {}\"\n        using IVT2[of p x con tt] using 3 1 assms that t1 \n        by auto\n      then show ?thesis using that by auto\n    qed\n    then show False using t1 t2 9 \n      using atLeastAtMost_iff greaterThanAtMost_iff by auto\n  qed     \n  have 11:\"(p has_derivative q t) (at t within {-e..d+e})\"\n    using assms t1 by auto\n  then have 12:\"\\<forall>s . q t s = q t 1 * s\"\n    using has_derivative_bounded_linear[of p \"q t\" \"(at t within {-e..d+e})\"]\n    using real_bounded_linear by auto\n  have 13:\"(p has_real_derivative q t 1) (at t within {-e..d+e})\"\n    using 11 12 \n    by (metis has_derivative_imp_has_field_derivative mult.commute)\n  have 14:\"q t 1 > 0\" using t1 assms 9 by auto\n  have 15:\"\\<exists>dd>0. \\<forall>h>0. t + h \\<in> {-e..d+e} \\<longrightarrow> h < dd \\<longrightarrow> p (t + h) > p t\"\n    using has_real_derivative_pos_inc_right[of p \"q t 1\" t \"{-e..d+e}\"] 13 14 \n    by auto\n  then obtain dd where d1:\"\\<forall>h>0. t + h \\<in> {-e..d+e} \\<longrightarrow> h < dd \\<longrightarrow> p (t + h) > p t\" and d2:\"dd>0\" by auto\n  then have 16:\"min (dd/2) (x-t)/2 < dd\" and \"min (dd/2) (x-t)/2 > 0\"\n    using 9 by auto\n  then have 17:\"(t + min (dd/2) (x-t)/2)> t\" \"(t + min (dd/2) (x-t)/2) < x\" \n    apply auto\n    using d2 9\n     by (smt field_sum_of_halves)\n   then have 18:\"p (t + min (dd/2) (x-t)/2) > p t\"\n    using d1 t1 16 assms(5) assms(6) by auto\n  have 19:\"p (t + min (dd/2) (x-t)/2)< con\" using 10 17 by auto\n  show False using 18 19 t1\n    by auto \nqed\n\nlemma real_inv_l:\n  fixes p :: \"real \\<Rightarrow> real\" and con :: real\n  assumes \"\\<forall>t\\<in>{-e..d+e}. (p has_derivative q t) (at t within {-e..d+e})\"\n    and \"d \\<ge> 0\"\n    and \"\\<forall>t\\<in>{0 ..<d}. (p t \\<le> con \\<longrightarrow> q t 1 < 0)\"\n    and \"p 0 < con \"\n    and \"x \\<in> {0 .. d}\"\n    and \"e > 0\"\n  shows \"p x < con\"\nproof (rule ccontr) \n  assume a:\" \\<not> p x < con\"\n  have 1:\"p x \\<ge> con\"\n    using a by auto\n  have 2:\"\\<forall>t\\<in>{0 .. d}. continuous (at t within {-e<..<d+e}) p\"\n    using assms has_derivative_subset\n    using has_derivative_continuous \n    by (smt atLeastAtMost_iff continuous_within_subset greaterThanLessThan_subseteq_atLeastAtMost_iff greaterThan_iff)\n  have 3:\"\\<forall>t\\<in>{0 .. d}. isCont p t\"\n    apply auto subgoal for t\n      using continuous_within_open[of t \"{-e<..<d+e}\" p]\n      using 2 assms(5) assms(6) by auto\n    done\n  have 4:\"{y. p y = con \\<and> y \\<in> {0 .. x}} \\<noteq> {}\"\n    using IVT[of p 0 con x] using 3 1 assms \n    by auto\n  have 5: \"{y. p y = con \\<and> y \\<in> {0 .. x}} = ({0 .. x} \\<inter> p -` {con})\"\n    by auto\n  have 6: \"closed ({0 .. x} \\<inter> p -` {con})\"\n    using 3 assms(5) apply simp\n    apply (rule continuous_closed_preimage)\n      apply auto\n    by (simp add: continuous_at_imp_continuous_on)\n  have 7: \"compact {0 .. x}\"\n    using assms\n    by blast\n  have 8: \"compact {y. p y = con \\<and> y \\<in> {0 .. x}}\"\n    apply auto\n    using 4 5 6 7 \n    by (smt Collect_cong Int_left_absorb atLeastAtMost_iff compact_Int_closed)\n  obtain t where t1:\"t \\<in> {y. p y = con \\<and> y \\<in> {0 .. x}}\" and t2:\"\\<forall> tt\\<in> {y. p y = con \\<and> y \\<in> {0 .. x}}. tt \\<ge> t\"\n    using compact_attains_inf[of \"{y. p y = con \\<and> y \\<in> {0 .. x}}\"] 4 8 \n    by blast\n  have 9:\"t > 0\"\n    using t1 1 assms(4) \n    using less_eq_real_def by auto\n  have 10:\"p tt < con\" if \"tt\\<in>{0..<t}\" for tt\n  proof(rule ccontr)\n    assume \"\\<not> p tt < con\"\n    then have not:\"p tt \\<ge> con\" by auto\n    have \"\\<exists> t' \\<in> {0..<t}. p t' = con\"\n    proof(cases \"p tt = con\")\n      case True\n      then show ?thesis using that by auto\n    next\n      case False\n      then have \"p tt > con\"\n        using not by auto\n      then have \"{y. p y = con \\<and> y \\<in> {0 .. tt}} \\<noteq> {}\"\n        using IVT[of p 0 con tt] using 3 1 assms that t1 \n        by auto\n      then show ?thesis using that by auto\n    qed\n    then show False using t1 t2 9 \n      using atLeastAtMost_iff greaterThanAtMost_iff by auto\n  qed     \n  have 11:\"(p has_derivative q y) (at y within {0..t})\" if \"y \\<in> {0 ..t}\"for y\n    apply(rule has_derivative_subset [where s = \"{-e<..<d+e}\"])\n    using assms that t1\n    apply auto \n    by (smt atLeastAtMost_iff at_within_Icc_at has_derivative_at_withinI)\n  have 12:\"\\<exists> tt \\<in> {0<..<t} . p t - p 0 = q tt t \"\n    using mvt_simple[of 0 t p q] 9 11\n    by auto\n  obtain tt where tt1:\"p t - p 0 = q tt t\" and tt2:\"tt \\<in> {0<..<t}\"\n    using 12 by auto\n  have 13:\"\\<forall>s . q tt s = q tt 1 * s\"\n    using has_derivative_bounded_linear[of p \"q tt\" \"(at tt within {0..t})\"]\n    using real_bounded_linear 11 tt2 by auto\n  have 14:\"p t - p 0 = q tt 1 * t\" using tt1 13 \n    by metis\n  have 15:\"q tt 1 > 0\" using 14 assms(4) t1 9 \n    by (metis (mono_tags, lifting) diff_gt_0_iff_gt mem_Collect_eq zero_less_mult_pos2)\n  then show False using assms(3) 10[of tt] tt2 \n    by (smt \"10\" a assms(5) atLeastAtMost_iff atLeastLessThan_iff greaterThanLessThan_iff)\nqed\n\n\nlemma real_inv_g:\n  fixes p :: \"real \\<Rightarrow> real\" and con :: real\n  assumes \"\\<forall>t\\<in>{-e..d+e}. (p has_derivative q t) (at t within {-e..d+e})\"\n    and \"d \\<ge> 0\"\n    and \"\\<forall>t\\<in>{0 ..<d}. (p t \\<ge> con \\<longrightarrow> q t 1 \\<ge> 0)\"\n    and \"p 0 > con \"\n    and \"x \\<in> {0 .. d}\"\n    and \"e > 0\"\n  shows \"p x > con\" \nproof (rule ccontr) \n  assume a:\" \\<not> p x > con\"\n  have 1:\"p x \\<le> con\"\n    using a by auto\n  have 2:\"\\<forall>t\\<in>{0 .. d}. continuous (at t within {-e<..<d+e}) p\"\n    using assms has_derivative_subset\n    using has_derivative_continuous \n    by (smt atLeastAtMost_iff continuous_within_subset greaterThanLessThan_subseteq_atLeastAtMost_iff greaterThan_iff)\n  have 3:\"\\<forall>t\\<in>{0 .. d}. isCont p t\"\n    apply auto subgoal for t\n      using continuous_within_open[of t \"{-e<..<d+e}\" p]\n      using 2 assms(5) assms(6) by auto\n    done\n  have 4:\"{y. p y = con \\<and> y \\<in> {0 .. x}} \\<noteq> {}\"\n    using IVT2[of p x con 0] using 3 1 assms \n    by auto\n  have 5: \"{y. p y = con \\<and> y \\<in> {0 .. x}} = ({0 .. x} \\<inter> p -` {con})\"\n    by auto\n  have 6: \"closed ({0 .. x} \\<inter> p -` {con})\"\n    using 3 assms(5) apply simp\n    apply (rule continuous_closed_preimage)\n      apply auto\n    by (simp add: continuous_at_imp_continuous_on)\n  have 7: \"compact {0 .. x}\"\n    using assms\n    by blast\n  have 8: \"compact {y. p y = con \\<and> y \\<in> {0 .. x}}\"\n    apply auto\n    using 4 5 6 7 \n    by (smt Collect_cong Int_left_absorb atLeastAtMost_iff compact_Int_closed)\n  obtain t where t1:\"t \\<in> {y. p y = con \\<and> y \\<in> {0 .. x}}\" and t2:\"\\<forall> tt\\<in> {y. p y = con \\<and> y \\<in> {0 .. x}}. tt \\<ge> t\"\n    using compact_attains_inf[of \"{y. p y = con \\<and> y \\<in> {0 .. x}}\"] 4 8 \n    by blast\n  have 9:\"t > 0\"\n    using t1 1 assms(4) \n    using less_eq_real_def by auto\n  have 10:\"p tt > con\" if \"tt\\<in>{0..<t}\" for tt\n  proof(rule ccontr)\n    assume \"\\<not> p tt > con\"\n    then have not:\"p tt \\<le> con\" by auto\n    have \"\\<exists> t' \\<in> {0..<t}. p t' = con\"\n    proof(cases \"p tt = con\")\n      case True\n      then show ?thesis using that by auto\n    next\n      case False\n      then have \"p tt < con\"\n        using not by auto\n      then have \"{y. p y = con \\<and> y \\<in> {0 .. tt}} \\<noteq> {}\"\n        using IVT2[of p tt con 0] using 3 1 assms that t1 \n        by auto\n      then show ?thesis using that by auto\n    qed\n    then show False using t1 t2 9 \n      using atLeastAtMost_iff greaterThanAtMost_iff by auto\n  qed     \n  have 11:\"(p has_derivative q y) (at y within {0..t})\" if \"y \\<in> {0 ..t}\"for y\n    apply(rule has_derivative_subset [where s = \"{-e<..<d+e}\"])\n    using assms that t1\n    apply auto \n    by (smt atLeastAtMost_iff at_within_Icc_at has_derivative_at_withinI)\n  have 12:\"\\<exists> tt \\<in> {0<..<t} . p t - p 0 = q tt t \"\n    using mvt_simple[of 0 t p q] 9 11\n    by auto\n  obtain tt where tt1:\"p t - p 0 = q tt t\" and tt2:\"tt \\<in> {0<..<t}\"\n    using 12 by auto\n  have 13:\"\\<forall>s . q tt s = q tt 1 * s\"\n    using has_derivative_bounded_linear[of p \"q tt\" \"(at tt within {0..t})\"]\n    using real_bounded_linear 11 tt2 by auto\n  have 14:\"p t - p 0 = q tt 1 * t\" using tt1 13 \n    by metis\n  have 15:\"q tt 1 < 0\" using 14 assms(4) t1 9 \n    by (metis (mono_tags, lifting) less_iff_diff_less_0 mem_Collect_eq mult_less_0_iff not_less_iff_gr_or_eq)\n  then show False using assms(3) 10[of tt] tt2 \n    by (smt \"1\" \"10\" assms(5) atLeastAtMost_iff atLeastLessThan_iff greaterThanLessThan_iff) \nqed\n\nsubsection \\<open>Definition of states\\<close>\n\ntext \\<open>Variable names\\<close>\ntype_synonym var = char\n\ntext \\<open>State\\<close>\ntype_synonym state = \"var \\<Rightarrow> real\"\n\ntext \\<open>Expressions\\<close>\ntype_synonym exp = \"state \\<Rightarrow> real\"\n\ntext \\<open>Predicates\\<close>\ntype_synonym fform = \"state \\<Rightarrow> bool\"\n\ntext \\<open>States as a vector\\<close>\ntype_synonym vec = \"real^(var)\"\n\ntext \\<open>Conversion between state and vector\\<close>\ndefinition state2vec :: \"state \\<Rightarrow> vec\" where\n  \"state2vec s = (\\<chi> x. s x)\"\n\ndefinition vec2state :: \"vec \\<Rightarrow> state\" where\n  \"(vec2state v) x = v $ x\"\n\nlemma vec_state_map1[simp]: \"vec2state (state2vec s) = s\"\n  unfolding vec2state_def state2vec_def by auto\n\nlemma vec_state_map2[simp]: \"state2vec (vec2state s) = s\"\n  unfolding vec2state_def state2vec_def by auto\n\nsubsection \\<open>Definition of ODEs\\<close>\n\ndatatype ODE =\n  ODE \"var \\<Rightarrow> exp\"\n\ntext \\<open>Given ODE and a state, find the derivative vector.\\<close>\nfun ODE2Vec :: \"ODE \\<Rightarrow> state \\<Rightarrow> vec\" where\n  \"ODE2Vec (ODE f) s = state2vec (\\<lambda>a. f a s)\"\n\ntext \\<open>History p on time {0 .. d} is a solution to ode.\\<close>\ndefinition ODEsol :: \"ODE \\<Rightarrow> (real \\<Rightarrow> state) \\<Rightarrow> real \\<Rightarrow> bool\" where\n  \"ODEsol ode p d = (d \\<ge> 0 \\<and> (\\<exists>\\<epsilon>>0. ((\\<lambda>t. state2vec (p t)) has_vderiv_on (\\<lambda>t. ODE2Vec ode (p t))) {-\\<epsilon> .. d+\\<epsilon>}))\"\n\ntext \\<open>History p on time {0 ..} is a solution to ode.\\<close>\ndefinition ODEsolInf :: \"ODE \\<Rightarrow> (real \\<Rightarrow> state) \\<Rightarrow> bool\" where\n  \"ODEsolInf ode p = (\\<exists>\\<epsilon>>0. ((\\<lambda>t. state2vec (p t)) has_vderiv_on (\\<lambda>t. ODE2Vec ode (p t))) {-\\<epsilon> ..})\"\n\n\nsubsection \\<open>Further results in analysis\\<close>\n\nlemma ODEsol_old:\n  assumes \"ODEsol ode p d\"\n  shows \"((\\<lambda>t. state2vec (p t)) has_vderiv_on (\\<lambda>t. ODE2Vec ode (p t))) {0 .. d}\"\nproof-\n  obtain e where e: \"e > 0\" \"((\\<lambda>t. state2vec (p t)) has_vderiv_on (\\<lambda>t. ODE2Vec ode (p t))) {-e .. d+e}\"\n    using assms(1) unfolding ODEsol_def by blast\n  then show ?thesis \n    using e(1) has_vderiv_on_subset[OF e(2)] by auto\nqed\n\nlemma ODEsolInf_old:\n   assumes \"ODEsolInf  ode p\"\n   shows \"((\\<lambda>t. state2vec (p t)) has_vderiv_on (\\<lambda>t. ODE2Vec ode (p t))) {0 ..}\"\nproof-\n  obtain e where e: \"e > 0\" \"((\\<lambda>t. state2vec (p t)) has_vderiv_on (\\<lambda>t. ODE2Vec ode (p t))) {-e ..}\"\n    using assms(1) unfolding ODEsolInf_def by blast\n  then show ?thesis \n    using e(1) has_vderiv_on_subset[OF e(2)] by auto\nqed\n\nlemma ODEsol_merge:\n  assumes \"ODEsol ode p d\"\n    and \"ODEsol ode p2 d2\"\n    and \"p2 0 = p d\"\n  shows \"ODEsol ode (\\<lambda>\\<tau>. if \\<tau> < d then p \\<tau> else p2 (\\<tau> - d)) (d + d2)\"\n  unfolding ODEsol_def\n  apply auto\n  subgoal \n    using assms(1,2) unfolding ODEsol_def by auto\n  subgoal\n  proof-\n    have step1:\"d\\<ge>0 \\<and> d2\\<ge>0\"\n      using assms unfolding ODEsol_def by auto\n    then have step2:\"{0 .. d+d2} = {0 .. d}\\<union>{d .. d+d2}\"\n      by auto\n    have step3:\"({0..d} \\<union> closure {d..d + d2} \\<inter> closure {0..d}) = {0..d}\"\n      using step1 by auto\n    have step4:\"({d..d + d2} \\<union> closure {d..d + d2} \\<inter> closure {0..d}) = {d..d+d2}\"\n      using step1 by auto\n    obtain e1 where e1: \"e1 > 0\" \"((\\<lambda>t. state2vec (p t)) has_vderiv_on (\\<lambda>t. ODE2Vec ode (p t))) {-e1 .. d+e1}\"\n      using assms(1) unfolding ODEsol_def by blast\n    obtain e2 where e2: \"e2 > 0\" \"((\\<lambda>t. state2vec (p2 t)) has_vderiv_on (\\<lambda>t. ODE2Vec ode (p2 t))) {-e2 .. d2+e2}\"\n      using assms(2) unfolding ODEsol_def by blast\n    obtain e where e: \"e > 0\" \"e < e1\" \"e < e2\"\n      using e1(1) e2(1) field_lbound_gt_zero by auto\n    then have stepe:\"{0 .. d2+e}\\<subseteq>{- e2..d2 + e2}\" \"{-e .. d}\\<subseteq>{- e1..d + e1}\" \"{- e..d + d2 + e} = {- e..d} \\<union> {d..d + d2 + e}\"\n      using step1  by auto\n    have stepclo1:\"({- e..d} \\<union> closure {d..d + d2 + e} \\<inter> closure {- e..d}) = {- e..d}\"\n      using e step1 by auto \n    have stepclo2:\" ({d..d + d2 + e} \\<union> closure {d..d + d2 + e} \\<inter> closure {- e..d}) = {d..d + d2 + e}\"\n      using e step1 by auto\n    have stepclo3: \"x \\<in> closure {d..d + d2 + e} \\<Longrightarrow>\n          x \\<in> closure {- e..d} \\<Longrightarrow> x = d\" for x\n      using e step1  by auto\n    have step5: \"((\\<lambda>t. t - d) has_vderiv_on (\\<lambda>t. 1)) {d .. d+d2+e}\"\n      by (auto intro!: derivative_intros)\n    then have step6: \"((\\<lambda>t. state2vec (p2 (t-d))) has_vderiv_on (\\<lambda>t. ODE2Vec ode (p2 (t-d)))) {d .. d+d2+e}\"\n      using has_vderiv_on_compose2[of \"(\\<lambda>t. state2vec (p2 t))\" \"(\\<lambda>t. ODE2Vec ode (p2 (t)))\" \"{0 .. d2+e}\" \"(\\<lambda>t. (t-d))\" \"(\\<lambda>t. 1)\" \"{d .. d+d2+e}\"]\n      using e2 e unfolding ODEsol_def\n      using has_vderiv_on_subset[OF e2(2) stepe(1)] by auto\n     have step7:\" ((\\<lambda>t. if t \\<in> {-e..d} then state2vec (p t) else state2vec (p2 (t - d))) has_vderiv_on\n     (\\<lambda>t. if t \\<in> {-e..d} then ODE2Vec ode (p t) else ODE2Vec ode (p2 (t - d)))){-e..d + d2+e}\"\n      using has_vderiv_on_If[of \"{-e .. d+d2+e}\" \"{-e .. d}\" \"{d .. d+d2+e}\" \"(\\<lambda>t. state2vec (p t))\" \"(\\<lambda>t. ODE2Vec ode (p t))\" \"(\\<lambda>t. state2vec (p2 (t-d)))\" \"(\\<lambda>t. ODE2Vec ode (p2 (t-d)))\"]\n      using step1 step2 step3 step4 step6 stepclo1 stepclo2 stepclo3\n      using has_vderiv_on_subset[OF e1(2) stepe(2)] e stepe assms(3)\n      by auto\n    show ?thesis\n      apply(rule exI[where x=e])\n      using has_vderiv_eq[of \"(\\<lambda>t. if t \\<in> {-e..d} then state2vec (p t) else state2vec (p2 (t - d)))\" \"(\\<lambda>t. if t \\<in> {-e..d} then ODE2Vec ode (p t) else ODE2Vec ode (p2 (t - d)))\" \"{-e..d + d2+e}\" \"(\\<lambda>t. state2vec (if t < d then p t else p2 (t - d)))\" \"(\\<lambda>t. ODE2Vec ode (if t < d then p t else p2 (t - d)))\" \"{-e..d + d2+e}\"]\n      using step7\n      using assms(3) step1 e\n      by auto\n  qed\n  done\n\nlemma ODEsol_split:\n  assumes \"ODEsol ode p d\"\n    and \"0 < t1\" and \"t1 < d\"\n  shows \"ODEsol ode p t1\"\n        \"ODEsol ode (\\<lambda>t. p (t + t1)) (d - t1)\"\n  subgoal\n  proof-\n    obtain e where e: \"e > 0\" \"((\\<lambda>t. state2vec (p t)) has_vderiv_on (\\<lambda>t. ODE2Vec ode (p t))) {-e .. d+e}\"\n      using assms(1) unfolding ODEsol_def by blast\n    then show ?thesis unfolding ODEsol_def\n    using has_vderiv_on_subset[of \"(\\<lambda>t. state2vec (p t))\" \" (\\<lambda>t. ODE2Vec ode (p t))\" \"{-e .. d+e}\" \"{-e..t1+e}\"]\n    using assms unfolding ODEsol_def by auto\nqed\n  subgoal\n    unfolding ODEsol_def apply auto\n    subgoal using assms by auto\n    subgoal \n    proof-\n      obtain e where e: \"e > 0\" \"((\\<lambda>t. state2vec (p t)) has_vderiv_on (\\<lambda>t. ODE2Vec ode (p t))) {-e .. d+e}\"\n        using assms(1) unfolding ODEsol_def by blast\n      have step1:\"((\\<lambda>t. state2vec (p (t))) has_vderiv_on (\\<lambda>t. ODE2Vec ode (p (t)))) {t1-e..d+e}\"\n        using has_vderiv_on_subset[of \"(\\<lambda>t. state2vec (p t))\" \" (\\<lambda>t. ODE2Vec ode (p t))\" \"{-e..d+e}\" \"{t1-e..d+e}\"]\n        using e assms  by auto\n      have step2:\"((\\<lambda>t.(t+t1)) has_vderiv_on (\\<lambda>t. 1)) {-e..d-t1+e}\"\n        by (auto intro!: derivative_intros)\n      have step3:\"t \\<in> {- e..d - t1 + e} \\<Longrightarrow> t + t1 \\<in> {t1 - e..d + e}\" for t\n        using e assms by auto\n      show ?thesis\n        apply (rule exI[where x=e])\n        apply auto \n        subgoal using e by auto\n        using has_vderiv_on_compose2[of \"(\\<lambda>t. state2vec (p (t)))\" \"(\\<lambda>t. ODE2Vec ode (p (t)))\" \"{t1-e..d+e}\" \"(\\<lambda>t.(t+t1))\" \"(\\<lambda>t. 1)\" \" {-e..d-t1+e}\"]\n        using step1 step2 step3 by auto\n    qed\n    done\n  done\n\n\n\nend\n", "meta": {"author": "AgHHL", "repo": "lics2023", "sha": "e2ea9c15a8c0e1bf658679274ee87f30baf4abc3", "save_path": "github-repos/isabelle/AgHHL-lics2023", "path": "github-repos/isabelle/AgHHL-lics2023/lics2023-e2ea9c15a8c0e1bf658679274ee87f30baf4abc3/case2/ext_Analysis_More.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.863391617003942, "lm_q2_score": 0.8267117940706734, "lm_q1q2_score": 0.7137760326789085}}
{"text": "(*  Title:       Recursion theorem\n    Author:      Georgy Dunaev <georgedunaev at gmail.com>, 2020\n    Maintainer:  Georgy Dunaev <georgedunaev at gmail.com>\n*)\nsection \"Recursion Submission\"\n\ntext \\<open>Recursion Theorem is proved in the following document.\nIt also contains the addition on natural numbers. \nThe development is done in the context of Zermelo-Fraenkel set theory.\\<close>\n\ntheory recursion\n  imports ZF\nbegin\n\nsection \\<open>Basic Set Theory\\<close>\ntext \\<open>Useful lemmas about sets, functions and natural numbers\\<close>\nlemma pisubsig : \\<open>Pi(A,P)\\<subseteq>Pow(Sigma(A,P))\\<close>\nproof\n  fix x\n  assume \\<open>x \\<in> Pi(A,P)\\<close>\n  hence \\<open>x \\<in> {f\\<in>Pow(Sigma(A,P)). A\\<subseteq>domain(f) & function(f)}\\<close>\n    by (unfold Pi_def)\n  thus \\<open>x \\<in> Pow(Sigma(A, P))\\<close> \n    by (rule CollectD1)\nqed\n\nlemma apparg:\n  fixes f A B\n  assumes T0:\\<open>f:A\\<rightarrow>B\\<close>\n  assumes T1:\\<open>f ` a = b\\<close>\n  assumes T2:\\<open>a \\<in> A\\<close>\n  shows \\<open>\\<langle>a, b\\<rangle> \\<in> f\\<close>\nproof(rule iffD2[OF func.apply_iff], rule T0)\n  show T:\\<open>a \\<in> A \\<and> f ` a = b\\<close>\n    by (rule conjI[OF T2 T1])\nqed\n\ntheorem nat_induct_bound :\n  assumes H0:\\<open>P(0)\\<close>\n  assumes H1:\\<open>!!x. x\\<in>nat \\<Longrightarrow> P(x) \\<Longrightarrow> P(succ(x))\\<close>\n  shows \\<open>\\<forall>n\\<in>nat. P(n)\\<close>\nproof(rule ballI)\n  fix n\n  assume H2:\\<open>n\\<in>nat\\<close>\n  show \\<open>P(n)\\<close>\n  proof(rule nat_induct[of n])\n    from H2 show \\<open>n\\<in>nat\\<close> by assumption\n  next\n    show \\<open>P(0)\\<close> by (rule H0)\n  next\n    fix x\n    assume H3:\\<open>x\\<in>nat\\<close>\n    assume H4:\\<open>P(x)\\<close>\n    show \\<open>P(succ(x))\\<close> by (rule H1[OF H3 H4])\n  qed\nqed\n\ntheorem nat_Tr : \\<open>\\<forall>n\\<in>nat. m\\<in>n \\<longrightarrow> m\\<in>nat\\<close>\nproof(rule nat_induct_bound)\n  show \\<open>m \\<in> 0 \\<longrightarrow> m \\<in> nat\\<close> by auto\nnext\n  fix x\n  assume H0:\\<open>x \\<in> nat\\<close>\n  assume H1:\\<open>m \\<in> x \\<longrightarrow> m \\<in> nat\\<close>\n  show \\<open>m \\<in> succ(x) \\<longrightarrow> m \\<in> nat\\<close>\n  proof(rule impI)\n    assume H2:\\<open>m\\<in>succ(x)\\<close>\n    show \\<open>m \\<in> nat\\<close>\n    proof(rule succE[OF H2])\n      assume H3:\\<open>m = x\\<close>\n      from H0 and H3 show \\<open>m \\<in> nat\\<close>\n        by auto\n    next\n      assume H4:\\<open>m \\<in> x\\<close>\n      show \\<open>m \\<in> nat\\<close>\n        by(rule mp[OF H1 H4])\n    qed\n  qed\nqed\n\n(* Natural numbers are linearly ordered. *)\ntheorem zeroleq : \\<open>\\<forall>n\\<in>nat. 0\\<in>n \\<or> 0=n\\<close>\nproof(rule ballI)\n  fix n\n  assume H1:\\<open>n\\<in>nat\\<close>\n  show \\<open>0\\<in>n\\<or>0=n\\<close>          \n  proof(rule nat_induct[of n])\n    from H1 show \\<open>n \\<in> nat\\<close> by assumption\n  next\n    show \\<open>0 \\<in> 0 \\<or> 0 = 0\\<close> by (rule disjI2, rule refl) \n  next\n    fix x\n    assume H2:\\<open>x\\<in>nat\\<close>\n    assume H3:\\<open> 0 \\<in> x \\<or> 0 = x\\<close>\n    show \\<open>0 \\<in> succ(x) \\<or> 0 = succ(x)\\<close>\n    proof(rule disjE[OF H3])\n      assume H4:\\<open>0\\<in>x\\<close>\n      show \\<open>0 \\<in> succ(x) \\<or> 0 = succ(x)\\<close>\n      proof(rule disjI1)\n        show \\<open>0 \\<in> succ(x)\\<close>\n          by (rule succI2[OF H4])\n      qed\n    next\n      assume H4:\\<open>0=x\\<close>\n      show \\<open>0 \\<in> succ(x) \\<or> 0 = succ(x)\\<close>\n      proof(rule disjI1)\n        have q:\\<open>x \\<in> succ(x)\\<close> by auto\n        from q and H4 show \\<open>0 \\<in> succ(x)\\<close> by auto\n      qed\n    qed\n  qed\nqed\n\ntheorem JH2_1ii : \\<open>m\\<in>succ(n) \\<Longrightarrow> m\\<in>n\\<or>m=n\\<close>\n  by auto\n\ntheorem nat_transitive:\\<open>\\<forall>n\\<in>nat. \\<forall>k. \\<forall>m.  k \\<in> m \\<and> m \\<in> n \\<longrightarrow> k \\<in> n\\<close>\nproof(rule nat_induct_bound)\n  show \\<open>\\<forall>k. \\<forall>m. k \\<in> m \\<and> m \\<in> 0 \\<longrightarrow> k \\<in> 0\\<close>\n  proof(rule allI, rule allI, rule impI)\n    fix k m\n    assume H:\\<open>k \\<in> m \\<and> m \\<in> 0\\<close>\n    then have H:\\<open>m \\<in> 0\\<close> by auto \n    then show \\<open>k \\<in> 0\\<close> by auto\n  qed\nnext\n  fix n\n  assume H0:\\<open>n \\<in> nat\\<close>\n  assume H1:\\<open>\\<forall>k.\n            \\<forall>m.\n               k \\<in> m \\<and> m \\<in> n \\<longrightarrow>\n               k \\<in> n\\<close>\n  show \\<open>\\<forall>k. \\<forall>m.\n               k \\<in> m \\<and>\n               m \\<in> succ(n) \\<longrightarrow>\n               k \\<in> succ(n)\\<close>\n  proof(rule allI, rule allI, rule impI)\n    fix k m\n    assume H4:\\<open>k \\<in> m \\<and> m \\<in> succ(n)\\<close>\n    hence H4':\\<open>m \\<in> succ(n)\\<close> by (rule conjunct2)\n    hence H4'':\\<open>m\\<in>n \\<or> m=n\\<close> by (rule succE, auto)\n    from H4 have Q:\\<open>k \\<in> m\\<close> by (rule conjunct1)\n    have H1S:\\<open>\\<forall>m. k \\<in> m \\<and> m \\<in> n \\<longrightarrow> k \\<in> n\\<close>\n      by (rule spec[OF H1])\n    have H1S:\\<open>k \\<in> m \\<and> m \\<in> n \\<longrightarrow> k \\<in> n\\<close> \n      by (rule spec[OF H1S])\n    show \\<open>k \\<in> succ(n)\\<close>\n    proof(rule disjE[OF H4''])\n      assume L:\\<open>m\\<in>n\\<close>\n      from Q and L have QL:\\<open>k \\<in> m \\<and> m \\<in> n\\<close> by auto\n      have G:\\<open>k \\<in> n\\<close> by (rule mp [OF H1S QL])\n      show \\<open>k \\<in> succ(n)\\<close>\n        by (rule succI2[OF G])\n    next\n      assume L:\\<open>m=n\\<close>\n      from Q have F:\\<open>k \\<in> succ(m)\\<close> by auto\n      from L and Q show \\<open>k \\<in> succ(n)\\<close> by auto\n    qed\n  qed\nqed\n\ntheorem nat_xninx : \\<open>\\<forall>n\\<in>nat. \\<not>(n\\<in>n)\\<close>\nproof(rule nat_induct_bound)\n  show \\<open>0\\<notin>0\\<close>\n    by auto\nnext\n  fix x\n  assume H0:\\<open>x\\<in>nat\\<close>\n  assume H1:\\<open>x\\<notin>x\\<close>\n  show \\<open>succ(x) \\<notin> succ(x)\\<close>\n  proof(rule contrapos[OF H1])\n    assume Q:\\<open>succ(x) \\<in> succ(x)\\<close>\n    have D:\\<open>succ(x)\\<in>x \\<or> succ(x)=x\\<close>\n      by (rule JH2_1ii[OF Q])\n    show \\<open>x\\<in>x\\<close>\n    proof(rule disjE[OF D])\n      assume Y1:\\<open>succ(x)\\<in>x\\<close>\n      have U:\\<open>x\\<in>succ(x)\\<close> by (rule succI1)\n      have T:\\<open>x \\<in> succ(x) \\<and> succ(x) \\<in> x \\<longrightarrow> x \\<in> x\\<close>\n        by (rule spec[OF spec[OF bspec[OF nat_transitive H0]]])\n      have R:\\<open>x \\<in> succ(x) \\<and> succ(x) \\<in> x\\<close>\n        by (rule conjI[OF U Y1])\n      show \\<open>x\\<in>x\\<close> \n        by (rule mp[OF T R])\n    next\n      assume Y1:\\<open>succ(x)=x\\<close>\n      show \\<open>x\\<in>x\\<close> \n        by (rule subst[OF Y1], rule Q)\n    qed\n  qed\nqed\n\ntheorem nat_asym : \\<open>\\<forall>n\\<in>nat. \\<forall>m. \\<not>(n\\<in>m \\<and> m\\<in>n)\\<close>\nproof(rule ballI, rule allI)\n  fix n m\n  assume H0:\\<open>n \\<in> nat\\<close>\n  have Q:\\<open>\\<not>(n\\<in>n)\\<close>\n    by(rule bspec[OF nat_xninx H0])\n  show \\<open>\\<not> (n \\<in> m \\<and> m \\<in> n)\\<close>\n  proof(rule contrapos[OF Q])\n    assume W:\\<open>(n \\<in> m \\<and> m \\<in> n)\\<close>\n    show \\<open>n\\<in>n\\<close>\n      by (rule mp[OF spec[OF spec[OF bspec[OF nat_transitive H0]]] W])\n  qed\nqed\n\ntheorem zerolesucc :\\<open>\\<forall>n\\<in>nat. 0 \\<in> succ(n)\\<close>\nproof(rule nat_induct_bound)\n  show \\<open>0\\<in>1\\<close>\n    by auto\nnext\n  fix x\n  assume H0:\\<open>x\\<in>nat\\<close>\n  assume H1:\\<open>0\\<in>succ(x)\\<close>\n  show \\<open>0\\<in>succ(succ(x))\\<close>\n  proof\n    assume J:\\<open>0 \\<notin> succ(x)\\<close>\n    show \\<open>0 = succ(x)\\<close>\n      by(rule notE[OF J H1])\n  qed\nqed\n\ntheorem succ_le : \\<open>\\<forall>n\\<in>nat. succ(m)\\<in>succ(n) \\<longrightarrow> m\\<in>n\\<close>\nproof(rule nat_induct_bound)\n  show \\<open> succ(m) \\<in> 1 \\<longrightarrow> m \\<in> 0\\<close>\n    by blast\nnext\n  fix x\n  assume H0:\\<open>x \\<in> nat\\<close>\n  assume H1:\\<open>succ(m) \\<in> succ(x) \\<longrightarrow> m \\<in> x\\<close>\n  show \\<open> succ(m) \\<in>\n             succ(succ(x)) \\<longrightarrow>\n             m \\<in> succ(x)\\<close>\n  proof(rule impI)\n    assume J0:\\<open>succ(m) \\<in> succ(succ(x))\\<close>\n    show \\<open>m \\<in> succ(x)\\<close>\n    proof(rule succE[OF J0])\n      assume R:\\<open>succ(m) = succ(x)\\<close>\n      hence R:\\<open>m=x\\<close> by (rule upair.succ_inject)\n      from R and succI1 show \\<open>m \\<in> succ(x)\\<close> by auto\n    next\n      assume R:\\<open>succ(m) \\<in> succ(x)\\<close>\n      have R:\\<open>m\\<in>x\\<close> by (rule mp[OF H1 R])\n      then show \\<open>m \\<in> succ(x)\\<close> by auto\n    qed\n  qed\nqed\n\ntheorem succ_le2 : \\<open>\\<forall>n\\<in>nat. \\<forall>m. succ(m)\\<in>succ(n) \\<longrightarrow> m\\<in>n\\<close>\nproof\n  fix n\n  assume H:\\<open>n\\<in>nat\\<close>\n  show \\<open>\\<forall>m. succ(m) \\<in> succ(n) \\<longrightarrow> m \\<in> n\\<close>\n  proof\n    fix m\n    from succ_le and H show \\<open>succ(m) \\<in> succ(n) \\<longrightarrow> m \\<in> n\\<close> by auto\n  qed\nqed\n\ntheorem le_succ : \\<open>\\<forall>n\\<in>nat. m\\<in>n \\<longrightarrow> succ(m)\\<in>succ(n)\\<close>\nproof(rule nat_induct_bound)\n  show \\<open>m \\<in> 0 \\<longrightarrow> succ(m) \\<in> 1\\<close>\n    by auto\nnext\n  fix x\n  assume H0:\\<open>x\\<in>nat\\<close>\n  assume H1:\\<open>m \\<in> x \\<longrightarrow> succ(m) \\<in> succ(x)\\<close>\n  show \\<open>m \\<in> succ(x) \\<longrightarrow>\n            succ(m) \\<in> succ(succ(x))\\<close>\n  proof(rule impI)\n    assume HR1:\\<open>m\\<in>succ(x)\\<close>\n    show \\<open>succ(m) \\<in> succ(succ(x))\\<close>\n    proof(rule succE[OF HR1])\n      assume Q:\\<open>m = x\\<close>\n      from Q show \\<open>succ(m) \\<in> succ(succ(x))\\<close>\n        by auto\n    next\n      assume Q:\\<open>m \\<in> x\\<close>\n      have Q:\\<open>succ(m) \\<in> succ(x)\\<close>\n        by (rule mp[OF H1 Q])\n      from Q show \\<open>succ(m) \\<in> succ(succ(x))\\<close>\n        by (rule succI2)\n    qed\n  qed\nqed\n\ntheorem nat_linord:\\<open>\\<forall>n\\<in>nat. \\<forall>m\\<in>nat. m\\<in>n\\<or>m=n\\<or>n\\<in>m\\<close>\nproof(rule ballI)\n  fix n\n  assume H1:\\<open>n\\<in>nat\\<close>\n  show \\<open>\\<forall>m\\<in>nat. m \\<in> n \\<or> m = n \\<or> n \\<in> m\\<close>\n  proof(rule nat_induct[of n])\n    from H1 show \\<open>n\\<in>nat\\<close> by assumption\n  next\n    show \\<open>\\<forall>m\\<in>nat. m \\<in> 0 \\<or> m = 0 \\<or> 0 \\<in> m\\<close>\n    proof\n      fix m\n      assume J:\\<open>m\\<in>nat\\<close>\n      show \\<open> m \\<in> 0 \\<or> m = 0 \\<or> 0 \\<in> m\\<close>\n      proof(rule disjI2)\n        have Q:\\<open>0\\<in>m\\<or>0=m\\<close> by (rule bspec[OF zeroleq J])\n        show \\<open>m = 0 \\<or> 0 \\<in> m\\<close>\n          by (rule disjE[OF Q], auto)\n      qed\n    qed\n  next\n    fix x\n    assume K:\\<open>x\\<in>nat\\<close>\n    assume M:\\<open>\\<forall>m\\<in>nat. m \\<in> x \\<or> m = x \\<or> x \\<in> m\\<close>\n    show \\<open>\\<forall>m\\<in>nat.\n            m \\<in> succ(x) \\<or>\n            m = succ(x) \\<or>\n            succ(x) \\<in> m\\<close>\n    proof(rule nat_induct_bound)\n      show \\<open>0 \\<in> succ(x) \\<or>  0 = succ(x) \\<or> succ(x) \\<in> 0\\<close>\n      proof(rule disjI1)\n        show \\<open>0 \\<in> succ(x)\\<close>\n          by (rule bspec[OF zerolesucc K])\n      qed\n    next\n      fix y\n      assume H0:\\<open>y \\<in> nat\\<close>\n      assume H1:\\<open>y \\<in> succ(x) \\<or> y = succ(x) \\<or> succ(x) \\<in> y\\<close>\n      show \\<open>succ(y) \\<in> succ(x) \\<or>\n            succ(y) = succ(x) \\<or>\n            succ(x) \\<in> succ(y)\\<close>\n      proof(rule disjE[OF H1])\n        assume W:\\<open>y\\<in>succ(x)\\<close>\n        show \\<open>succ(y) \\<in> succ(x) \\<or>\n              succ(y) = succ(x) \\<or>\n              succ(x) \\<in> succ(y)\\<close>\n        proof(rule succE[OF W])\n          assume G:\\<open>y=x\\<close>\n          show \\<open>succ(y) \\<in> succ(x) \\<or>\n    succ(y) = succ(x) \\<or>\n    succ(x) \\<in> succ(y)\\<close>\n            by (rule disjI2, rule disjI1, rule subst[OF G], rule refl)\n        next\n          assume G:\\<open>y \\<in> x\\<close>\n          have R:\\<open>succ(y) \\<in> succ(x)\\<close>\n            by (rule mp[OF bspec[OF le_succ K] G])\n          show \\<open>succ(y) \\<in> succ(x) \\<or>\n           succ(y) = succ(x) \\<or>\n           succ(x) \\<in> succ(y)\\<close>\n            by(rule disjI1, rule R)\n        qed\n      next\n        assume W:\\<open>y = succ(x) \\<or> succ(x) \\<in> y\\<close>\n        show \\<open>succ(y) \\<in> succ(x) \\<or>\n              succ(y) = succ(x) \\<or>\n              succ(x) \\<in> succ(y)\\<close>\n        proof(rule disjE[OF W])\n          assume W:\\<open>y=succ(x)\\<close>\n          show \\<open>succ(y) \\<in> succ(x) \\<or>\n              succ(y) = succ(x) \\<or>\n              succ(x) \\<in> succ(y)\\<close>\n            by (rule disjI2, rule disjI2, rule subst[OF W], rule succI1)\n        next\n          assume W:\\<open>succ(x)\\<in>y\\<close>\n          show \\<open>succ(y) \\<in> succ(x) \\<or>\n              succ(y) = succ(x) \\<or>\n              succ(x) \\<in> succ(y)\\<close>\n            by (rule disjI2, rule disjI2, rule succI2[OF W])\n        qed\n      qed\n    qed\n  qed\nqed\n\nlemma tgb:\n  assumes knat: \\<open>k\\<in>nat\\<close> \n  assumes D: \\<open>t \\<in> k \\<rightarrow> A\\<close>\n  shows  \\<open>t \\<in> Pow(nat \\<times> A)\\<close>\nproof -\n  from D\n  have q:\\<open>t\\<in>{t\\<in>Pow(Sigma(k,%_.A)). k\\<subseteq>domain(t) & function(t)}\\<close>\n    by(unfold Pi_def)\n  have J:\\<open>t \\<in> Pow(k \\<times> A)\\<close>\n    by (rule CollectD1[OF q])\n  have G:\\<open>k \\<times> A \\<subseteq> nat \\<times> A\\<close>\n  proof(rule func.Sigma_mono)\n    from knat\n    show \\<open>k\\<subseteq>nat\\<close>\n      by (rule QUniv.naturals_subset_nat)\n  next\n    show \\<open>\\<And>x. x \\<in> k \\<Longrightarrow> A \\<subseteq> A\\<close>\n      by auto\n  qed\n  show \\<open>t \\<in> Pow(nat \\<times> A)\\<close>\n    by (rule subsetD, rule func.Pow_mono[OF G], rule J)\nqed\n\nsection \\<open>Compatible set\\<close>\ntext \\<open>Union of compatible set of functions is a function.\\<close>\n\ndefinition compat :: \\<open>[i,i]\\<Rightarrow>o\\<close>\n  where \"compat(f1,f2) == \\<forall>x.\\<forall>y1.\\<forall>y2.\\<langle>x,y1\\<rangle> \\<in> f1 \\<and> \\<langle>x,y2\\<rangle> \\<in> f2 \\<longrightarrow> y1=y2\"\n\nlemma compatI [intro]:\n  assumes H:\\<open>\\<And>x y1 y2.\\<lbrakk>\\<langle>x,y1\\<rangle> \\<in> f1; \\<langle>x,y2\\<rangle> \\<in> f2\\<rbrakk>\\<Longrightarrow>y1=y2\\<close>\n  shows \\<open>compat(f1,f2)\\<close>\nproof(unfold compat_def)\n  show \\<open>\\<forall>x y1 y2. \\<langle>x, y1\\<rangle> \\<in> f1 \\<and> \\<langle>x, y2\\<rangle> \\<in> f2 \\<longrightarrow> y1 = y2\\<close>\n  proof(rule allI | rule impI)+\n    fix x y1 y2\n    assume K:\\<open>\\<langle>x, y1\\<rangle> \\<in> f1 \\<and> \\<langle>x, y2\\<rangle> \\<in> f2\\<close>\n    have K1:\\<open>\\<langle>x, y1\\<rangle> \\<in> f1\\<close> by (rule conjunct1[OF K])\n    have K2:\\<open>\\<langle>x, y2\\<rangle> \\<in> f2\\<close> by (rule conjunct2[OF K])\n    show \\<open>y1 = y2\\<close> by (rule H[OF K1 K2])\n  qed\nqed\n\nlemma compatD:\n  assumes H: \\<open>compat(f1,f2)\\<close>\n  shows \\<open>\\<And>x y1 y2.\\<lbrakk>\\<langle>x,y1\\<rangle> \\<in> f1; \\<langle>x,y2\\<rangle> \\<in> f2\\<rbrakk>\\<Longrightarrow>y1=y2\\<close>\nproof -\n  fix x y1 y2\n  assume Q1:\\<open>\\<langle>x, y1\\<rangle> \\<in> f1\\<close>\n  assume Q2:\\<open>\\<langle>x, y2\\<rangle> \\<in> f2\\<close>\n  from H have H:\\<open>\\<forall>x y1 y2. \\<langle>x, y1\\<rangle> \\<in> f1 \\<and> \\<langle>x, y2\\<rangle> \\<in> f2 \\<longrightarrow> y1 = y2\\<close>\n    by (unfold compat_def)\n  show \\<open>y1=y2\\<close>\n  proof(rule mp[OF spec[OF spec[OF spec[OF H]]]])\n    show \\<open>\\<langle>x, y1\\<rangle> \\<in> f1 \\<and> \\<langle>x, y2\\<rangle> \\<in> f2\\<close>\n      by(rule conjI[OF Q1 Q2])\n  qed\nqed\n\nlemma compatE:\n  assumes H: \\<open>compat(f1,f2)\\<close>\n  and W:\\<open>(\\<And>x y1 y2.\\<lbrakk>\\<langle>x,y1\\<rangle> \\<in> f1; \\<langle>x,y2\\<rangle> \\<in> f2\\<rbrakk>\\<Longrightarrow>y1=y2) \\<Longrightarrow> E\\<close>\nshows \\<open>E\\<close>\n  by (rule W, rule compatD[OF H], assumption+)\n\n\ndefinition compatset :: \\<open>i\\<Rightarrow>o\\<close>\n  where \"compatset(S) == \\<forall>f1\\<in>S.\\<forall>f2\\<in>S. compat(f1,f2)\"\n\nlemma compatsetI [intro] :\n  assumes 1:\\<open>\\<And>f1 f2. \\<lbrakk>f1\\<in>S;f2\\<in>S\\<rbrakk> \\<Longrightarrow> compat(f1,f2)\\<close>\n  shows \\<open>compatset(S)\\<close>\n  by (unfold compatset_def, rule ballI, rule ballI, rule 1, assumption+)\n\nlemma compatsetD:\n  assumes H: \\<open>compatset(S)\\<close>\n  shows \\<open>\\<And>f1 f2.\\<lbrakk>f1\\<in>S; f2\\<in>S\\<rbrakk>\\<Longrightarrow>compat(f1,f2)\\<close>\nproof -\n  fix f1 f2\n  assume H1:\\<open>f1\\<in>S\\<close>\n  assume H2:\\<open>f2\\<in>S\\<close>\n  from H have H:\\<open>\\<forall>f1\\<in>S.\\<forall>f2\\<in>S. compat(f1,f2)\\<close>\n    by (unfold compatset_def)\n  show \\<open>compat(f1,f2)\\<close>\n    by (rule bspec[OF bspec[OF H H1] H2])\nqed\n\nlemma compatsetE:\n  assumes H: \\<open>compatset(S)\\<close>\n  and W:\\<open>(\\<And>f1 f2.\\<lbrakk>f1\\<in>S; f2\\<in>S\\<rbrakk>\\<Longrightarrow>compat(f1,f2)) \\<Longrightarrow> E\\<close>\nshows \\<open>E\\<close>\n  by (rule W, rule compatsetD[OF H], assumption+)\n\ntheorem upairI1 : \\<open>a \\<in> {a, b}\\<close>\nproof\n  assume \\<open>a \\<notin> {b}\\<close>\n  show \\<open>a = a\\<close> by (rule refl)\nqed\n\ntheorem upairI2 : \\<open>b \\<in> {a, b}\\<close>\nproof\n  assume H:\\<open>b \\<notin> {b}\\<close>\n  have Y:\\<open>b \\<in> {b}\\<close> by (rule upair.singletonI)\n  show \\<open>b = a\\<close> by (rule notE[OF H Y])\nqed\n\ntheorem sinup : \\<open>{x} \\<in> \\<langle>x, xa\\<rangle>\\<close>\nproof (unfold Pair_def)\n  show \\<open>{x} \\<in> {{x, x}, {x, xa}}\\<close>\n  proof (rule IFOL.subst)\n    show \\<open>{x} \\<in> {{x},{x,xa}}\\<close>\n      by (rule upairI1)\n  next\n    show \\<open>{{x}, {x, xa}} = {{x, x}, {x, xa}}\\<close>\n      by blast\n  qed\nqed\n\ntheorem compatsetunionfun : \n  fixes S\n  assumes H0:\\<open>compatset(S)\\<close>\n  shows \\<open>function(\\<Union>S)\\<close>\nproof(unfold function_def)\n  show \\<open> \\<forall>x y1. \\<langle>x, y1\\<rangle> \\<in> \\<Union>S \\<longrightarrow> \n          (\\<forall>y2. \\<langle>x, y2\\<rangle> \\<in> \\<Union>S \\<longrightarrow> y1 = y2)\\<close>\n  proof(rule allI, rule allI, rule impI, rule allI, rule impI)\n    fix x y1 y2\n    assume F1:\\<open>\\<langle>x, y1\\<rangle> \\<in> \\<Union>S\\<close>\n    assume F2:\\<open>\\<langle>x, y2\\<rangle> \\<in> \\<Union>S\\<close> \n    show \\<open>y1=y2\\<close>\n    proof(rule UnionE[OF F1], rule UnionE[OF F2])\n      fix f1 f2\n      assume J1:\\<open>\\<langle>x, y1\\<rangle> \\<in> f1\\<close>\n      assume J2:\\<open>\\<langle>x, y2\\<rangle> \\<in> f2\\<close>\n      assume K1:\\<open>f1 \\<in> S\\<close>\n      assume K2:\\<open>f2 \\<in> S\\<close>\n      have R:\\<open>compat(f1,f2)\\<close> \n        by (rule compatsetD[OF H0 K1 K2])\n      show \\<open>y1=y2\\<close>\n        by(rule compatD[OF R J1 J2])\n    qed\n  qed\nqed\n\ntheorem domuncomp: \n  assumes H0:\\<open>compatset(S)\\<close>\n  assumes W:\\<open>f\\<in>S\\<close>\n  shows \\<open>domain(f)\\<subseteq>domain(\\<Union>S)\\<close>\n  oops\n\ntheorem mkel :\n  assumes 1:\\<open>A\\<close>\n  assumes 2:\\<open>A\\<Longrightarrow>B\\<close>\n  shows \\<open>B\\<close>\n  by (rule 2, rule 1)\n\ntheorem valofunion : \n  fixes S\n  assumes H0:\\<open>compatset(S)\\<close>\n  assumes W:\\<open>f\\<in>S\\<close>\n  assumes Q:\\<open>f:A\\<rightarrow>B\\<close>\n  assumes T:\\<open>a\\<in>A\\<close>\n  assumes P:\\<open>f ` a = v\\<close>\n  shows N:\\<open>(\\<Union>S)`a = v\\<close>\nproof -\n  have K:\\<open>\\<langle>a, v\\<rangle> \\<in> f\\<close>\n    by (rule apparg[OF Q P T])\n  show N:\\<open>(\\<Union>S)`a = v\\<close>\n  proof(rule function_apply_equality)\n    show \\<open>function(\\<Union>S)\\<close>\n      by(rule compatsetunionfun[OF H0])\n  next\n    show \\<open>\\<langle>a, v\\<rangle> \\<in> \\<Union>S\\<close>\n      by(rule UnionI[OF W K ])\n  qed\nqed\n\nsection \"Partial computation\"\n\ndefinition satpc :: \\<open>[i,i,i] \\<Rightarrow> o \\<close>\n  where \\<open>satpc(t,\\<alpha>,g) == \\<forall>n \\<in> \\<alpha> . t`succ(n) = g ` <t`n, n>\\<close>\n\ntext \\<open>$m$-step computation based on $a$ and $g$\\<close>\ndefinition partcomp :: \\<open>[i,i,i,i,i]\\<Rightarrow>o\\<close>\n  where \\<open>partcomp(A,t,m,a,g) == (t:succ(m)\\<rightarrow>A) \\<and> (t`0=a) \\<and> satpc(t,m,g)\\<close>\n\nlemma partcompI [intro]:\n  assumes H1:\\<open>(t:succ(m)\\<rightarrow>A)\\<close>\n  assumes H2:\\<open>(t`0=a)\\<close>\n  assumes H3:\\<open>satpc(t,m,g)\\<close>\n  shows \\<open>partcomp(A,t,m,a,g)\\<close>\nproof (unfold partcomp_def, auto)\n  show \\<open>t \\<in> succ(m) \\<rightarrow> A\\<close> by (rule H1)\n  show \\<open>(t`0=a)\\<close> by (rule H2)\n  show \\<open>satpc(t,m,g)\\<close> by (rule H3)\nqed\n\nlemma partcompD1: \\<open>partcomp(A,t,m,a,g) \\<Longrightarrow> t \\<in> succ(m) \\<rightarrow> A\\<close>\n  by (unfold partcomp_def, auto)\n\nlemma partcompD2: \\<open>partcomp(A,t,m,a,g) \\<Longrightarrow> (t`0=a)\\<close>\n by (unfold partcomp_def, auto)\n\nlemma partcompD3: \\<open>partcomp(A,t,m,a,g) \\<Longrightarrow> satpc(t,m,g)\\<close>\n  by (unfold partcomp_def, auto)\n\nlemma partcompE [elim] : \n  assumes 1:\\<open>partcomp(A,t,m,a,g)\\<close>\n    and 2:\\<open>\\<lbrakk>(t:succ(m)\\<rightarrow>A) ; (t`0=a) ; satpc(t,m,g)\\<rbrakk> \\<Longrightarrow> E\\<close>\n  shows \\<open>E\\<close>\n  by (rule 2, rule partcompD1[OF 1], rule partcompD2[OF 1], rule partcompD3[OF 1])\n\ntext \\<open>If we add ordered pair in the middle of partial computation then\nit will not change.\\<close>\nlemma addmiddle:\n(*  fixes  t m a g*)\n  assumes mnat:\\<open>m\\<in>nat\\<close>\n  assumes F:\\<open>partcomp(A,t,m,a,g)\\<close>\n  assumes xinm:\\<open>x\\<in>m\\<close>\n  shows \\<open>cons(\\<langle>succ(x), g ` \\<langle>t ` x, x\\<rangle>\\<rangle>, t) = t\\<close>\nproof(rule partcompE[OF F])\n  assume F1:\\<open>t \\<in> succ(m) \\<rightarrow> A\\<close>\n  assume F2:\\<open>t ` 0 = a\\<close>\n  assume F3:\\<open>satpc(t, m, g)\\<close>\n  from F3\n  have W:\\<open>\\<forall>n\\<in>m. t ` succ(n) = g ` \\<langle>t ` n, n\\<rangle>\\<close>\n    by (unfold satpc_def)\n  have U:\\<open>t ` succ(x) = g ` \\<langle>t ` x, x\\<rangle>\\<close>\n    by (rule bspec[OF W xinm])\n  have E:\\<open>\\<langle>succ(x), (g ` \\<langle>t ` x, x\\<rangle>)\\<rangle> \\<in> t\\<close>\n  proof(rule apparg[OF F1 U])\n    show \\<open>succ(x) \\<in> succ(m)\\<close>\n      by(rule mp[OF bspec[OF le_succ mnat] xinm])\n  qed\n  show ?thesis\n    by (rule equalities.cons_absorb[OF E])\nqed\n\n\nsection \\<open>Set of functions \\<close>\ntext \\<open>It is denoted as $F$ on page 48 in \"Introduction to Set Theory\".\\<close>\ndefinition pcs :: \\<open>[i,i,i]\\<Rightarrow>i\\<close>\n  where \\<open>pcs(A,a,g) == {t\\<in>Pow(nat*A). \\<exists>m\\<in>nat. partcomp(A,t,m,a,g)}\\<close>\n\nlemma pcs_uniq : \n  assumes F1:\\<open>m1\\<in>nat\\<close>\n  assumes F2:\\<open>m2\\<in>nat\\<close>\n  assumes H1: \\<open>partcomp(A,f1,m1,a,g)\\<close>\n  assumes H2: \\<open>partcomp(A,f2,m2,a,g)\\<close>\n  shows \\<open>\\<forall>n\\<in>nat. n\\<in>succ(m1) \\<and> n\\<in>succ(m2) \\<longrightarrow> f1`n = f2`n\\<close>\nproof(rule partcompE[OF H1], rule partcompE[OF H2])\n  assume H11:\\<open>f1 \\<in> succ(m1) \\<rightarrow> A\\<close>\n  assume H12:\\<open>f1 ` 0 = a \\<close>\n  assume H13:\\<open>satpc(f1, m1, g)\\<close>\n  assume H21:\\<open>f2 \\<in> succ(m2) \\<rightarrow> A\\<close>\n  assume H22:\\<open>f2 ` 0 = a\\<close>\n  assume H23:\\<open>satpc(f2, m2, g)\\<close>\n  show \\<open>\\<forall>n\\<in>nat. n\\<in>succ(m1) \\<and> n\\<in>succ(m2) \\<longrightarrow> f1`n = f2`n\\<close>\nproof(rule nat_induct_bound)\n  from H12 and H22\n  show \\<open>0\\<in>succ(m1) \\<and> 0\\<in>succ(m2) \\<longrightarrow> f1 ` 0 = f2 ` 0\\<close>\n    by auto\nnext\n  fix x\n  assume J0:\\<open>x\\<in>nat\\<close>\n  assume J1:\\<open>x \\<in> succ(m1) \\<and> x \\<in> succ(m2) \\<longrightarrow> f1 ` x = f2 ` x\\<close>\n  from H13 have G1:\\<open>\\<forall>n \\<in> m1 . f1`succ(n) = g ` <f1`n, n>\\<close>\n    by (unfold satpc_def, auto)\n  from H23 have G2:\\<open>\\<forall>n \\<in> m2 . f2`succ(n) = g ` <f2`n, n>\\<close> \n    by (unfold satpc_def, auto)\n  show \\<open>succ(x) \\<in> succ(m1) \\<and> succ(x) \\<in> succ(m2) \\<longrightarrow> \n        f1 ` succ(x) = f2 ` succ(x)\\<close>\n  proof\n    assume K:\\<open>succ(x) \\<in> succ(m1) \\<and> succ(x) \\<in> succ(m2)\\<close>\n    from K have K1:\\<open>succ(x) \\<in> succ(m1)\\<close> by auto\n    from K have K2:\\<open>succ(x) \\<in> succ(m2)\\<close> by auto\n    have K1':\\<open>x \\<in> m1\\<close> by (rule mp[OF bspec[OF succ_le F1] K1])\n    have K2':\\<open>x \\<in> m2\\<close> by (rule mp[OF bspec[OF succ_le F2] K2])\n    have U1:\\<open>x\\<in>succ(m1)\\<close> \n      by (rule Nat.succ_in_naturalD[OF K1 Nat.nat_succI[OF F1]])\n    have U2:\\<open>x\\<in>succ(m2)\\<close> \n      by (rule Nat.succ_in_naturalD[OF K2 Nat.nat_succI[OF F2]])\n    have Y1:\\<open>f1`succ(x) = g ` <f1`x, x>\\<close>\n      by (rule bspec[OF G1 K1'])\n    have Y2:\\<open>f2`succ(x) = g ` <f2`x, x>\\<close>\n      by (rule bspec[OF G2 K2'])\n    have \\<open>f1 ` x = f2 ` x\\<close>\n      by(rule mp[OF J1 conjI[OF U1 U2]])\n    then have Y:\\<open>g ` <f1`x, x> = g ` <f2`x, x>\\<close> by auto\n    from Y1 and Y2 and Y\n    show \\<open>f1 ` succ(x) = f2 ` succ(x)\\<close>\n      by auto\n  qed\nqed\nqed\n\nlemma domainsubsetfunc : \n  assumes Q:\\<open>f1\\<subseteq>f2\\<close>\n  shows \\<open>domain(f1)\\<subseteq>domain(f2)\\<close>\nproof\n  fix x\n  assume H:\\<open>x \\<in> domain(f1)\\<close>\n  show \\<open>x \\<in> domain(f2)\\<close>\n  proof(rule domainE[OF H])\n    fix y\n    assume W:\\<open>\\<langle>x, y\\<rangle> \\<in> f1\\<close>\n    have \\<open>\\<langle>x, y\\<rangle> \\<in> f2\\<close>\n      by(rule subsetD[OF Q W])     \n    then show \\<open>x \\<in> domain(f2)\\<close>\n      by(rule domainI)\n  qed\nqed\n\nlemma natdomfunc:\n  assumes 1:\\<open>q\\<in>A\\<close>\n  assumes J0:\\<open>f1 \\<in> Pow(nat \\<times> A)\\<close>\n  assumes U:\\<open>m1 \\<in> domain(f1)\\<close>\n  shows \\<open>m1\\<in>nat\\<close>\nproof -\n  from J0 have J0 : \\<open>f1 \\<subseteq> nat \\<times> A\\<close>\n    by auto\n  have J0:\\<open>domain(f1) \\<subseteq> domain(nat \\<times> A)\\<close>\n    by(rule func.domain_mono[OF J0])\n  have F:\\<open>m1 \\<in> domain(nat \\<times> A)\\<close>\n    by(rule subsetD[OF J0 U])\n  have R:\\<open>domain(nat \\<times> A) = nat\\<close>\n    by (rule equalities.domain_of_prod[OF 1])\n  show \\<open>m1 \\<in> nat\\<close>\n    by(rule subst[OF R], rule F)\nqed\n\nlemma pcs_lem :\n  assumes 1:\\<open>q\\<in>A\\<close>\n  shows \\<open>compatset(pcs(A, a, g))\\<close>\nproof (*(rule compatsetI)*)\n  fix f1 f2\n  assume H1:\\<open>f1 \\<in> pcs(A, a, g)\\<close>\n  then have H1':\\<open>f1 \\<in> {t\\<in>Pow(nat*A). \\<exists>m\\<in>nat. partcomp(A,t,m,a,g)}\\<close> by (unfold pcs_def)\n  hence H1'A:\\<open>f1 \\<in> Pow(nat*A)\\<close> by auto\n  hence H1'A:\\<open>f1 \\<subseteq> (nat*A)\\<close> by auto\n  assume H2:\\<open>f2 \\<in> pcs(A, a, g)\\<close>\n  then have H2':\\<open>f2 \\<in> {t\\<in>Pow(nat*A). \\<exists>m\\<in>nat. partcomp(A,t,m,a,g)}\\<close> by (unfold pcs_def)\n  show \\<open>compat(f1, f2)\\<close>\n  proof(rule compatI)\n    fix x y1 y2\n    assume P1:\\<open>\\<langle>x, y1\\<rangle> \\<in> f1\\<close>\n    assume P2:\\<open>\\<langle>x, y2\\<rangle> \\<in> f2\\<close>\n    show \\<open>y1 = y2\\<close>\n    proof(rule CollectE[OF H1'], rule CollectE[OF H2'])\n      assume J0:\\<open>f1 \\<in> Pow(nat \\<times> A)\\<close>\n      assume J1:\\<open>f2 \\<in> Pow(nat \\<times> A)\\<close>\n      assume J2:\\<open>\\<exists>m\\<in>nat. partcomp(A, f1, m, a, g)\\<close>\n      assume J3:\\<open>\\<exists>m\\<in>nat. partcomp(A, f2, m, a, g)\\<close>\n      show \\<open>y1 = y2\\<close>\n      proof(rule bexE[OF J2], rule bexE[OF J3])\n        fix m1 m2\n        assume K1:\\<open>partcomp(A, f1, m1, a, g)\\<close>\n        assume K2:\\<open>partcomp(A, f2, m2, a, g)\\<close>\n        hence K2':\\<open>(f2:succ(m2)\\<rightarrow>A) \\<and> (f2`0=a) \\<and> satpc(f2,m2,g)\\<close>\n          by (unfold partcomp_def)\n        from K1 have K1'A:\\<open>(f1:succ(m1)\\<rightarrow>A)\\<close> by (rule partcompD1)\n        from K2' have K2'A:\\<open>(f2:succ(m2)\\<rightarrow>A)\\<close> by auto\n        from K1'A have K1'AD:\\<open>domain(f1) = succ(m1)\\<close> \n          by(rule domain_of_fun)\n        from K2'A have K2'AD:\\<open>domain(f2) = succ(m2)\\<close>\n          by(rule domain_of_fun)\n        have L1:\\<open>f1`x=y1\\<close>\n          by (rule func.apply_equality[OF P1], rule K1'A)\n        have L2:\\<open>f2`x=y2\\<close>\n          by(rule func.apply_equality[OF P2], rule K2'A)\n        have m1nat:\\<open>m1\\<in>nat\\<close>\n        proof(rule natdomfunc[OF 1 J0])\n          show \\<open>m1 \\<in> domain(f1)\\<close>\n            by (rule ssubst[OF K1'AD], auto)\n        qed\n        have m2nat:\\<open>m2\\<in>nat\\<close>\n        proof(rule natdomfunc[OF 1 J1])\n          show \\<open>m2 \\<in> domain(f2)\\<close>\n            by (rule ssubst[OF K2'AD], auto)\n        qed\n        have G1:\\<open>\\<langle>x, y1\\<rangle> \\<in> (nat*A)\\<close>\n          by(rule subsetD[OF H1'A P1])\n        have KK:\\<open>x\\<in>nat\\<close>\n          by(rule SigmaE[OF G1], auto)\n        (*x is in the domain of f1  i.e. succ(m1)\nso we can have both  x \\<in> ?m1.2 \\<and> x \\<in> ?m2.2 \nhow to prove that m1 \\<in> nat ? from J0 !  f1 is a subset of nat \\<times> A*)\n        have W:\\<open>f1`x=f2`x\\<close>\n        proof(rule mp[OF bspec[OF pcs_uniq KK] ])\n          show \\<open>m1 \\<in> nat\\<close>\n            by (rule m1nat)\n        next\n          show \\<open>m2 \\<in> nat\\<close>\n            by (rule m2nat)\n        next\n          show \\<open>partcomp(A, f1, m1, a, g)\\<close>\n            by (rule K1)\n        next\n          show \\<open>partcomp(A, f2, m2, a, g)\\<close>\n            by (rule K2)\n        next\n            (*  P1:\\<open>\\<langle>x, y1\\<rangle> \\<in> f1\\<close> \n              K1'A:\\<open>(f1:succ(m1)\\<rightarrow>A)\\<close>\n            *)\n          have U1:\\<open>x \\<in> succ(m1)\\<close>\n            by (rule func.domain_type[OF P1 K1'A])\n          have U2:\\<open>x \\<in> succ(m2)\\<close>\n            by (rule func.domain_type[OF P2 K2'A])\n          show \\<open>x \\<in> succ(m1) \\<and> x \\<in> succ(m2)\\<close>\n            by (rule conjI[OF U1 U2])\n        qed\n        from L1 and W and L2\n        show \\<open>y1 = y2\\<close> by auto\n      qed\n    qed\n  qed\nqed\n\ntheorem fuissu : \\<open>f \\<in> X -> Y \\<Longrightarrow> f \\<subseteq> X\\<times>Y\\<close>\nproof\n  fix w\n  assume H1 : \\<open>f \\<in> X -> Y\\<close>\n  then have J1:\\<open>f \\<in> {q\\<in>Pow(Sigma(X,\\<lambda>_.Y)). X\\<subseteq>domain(q) & function(q)}\\<close>\n    by (unfold Pi_def) \n  then have J2:\\<open>f \\<in> Pow(Sigma(X,\\<lambda>_.Y))\\<close>\n    by auto\n  then have J3:\\<open>f \\<subseteq> Sigma(X,\\<lambda>_.Y)\\<close>\n    by auto\n  assume H2 : \\<open>w \\<in> f\\<close>\n  from J3 and H2 have \\<open>w\\<in>Sigma(X,\\<lambda>_.Y)\\<close>\n    by auto\n  then have J4:\\<open>w \\<in> (\\<Union>x\\<in>X. (\\<Union>y\\<in>Y. {\\<langle>x,y\\<rangle>}))\\<close>\n    by auto\n  show \\<open>w \\<in> X*Y\\<close>\n  proof (rule UN_E[OF J4])\n    fix x\n    assume V1:\\<open>x \\<in> X\\<close>\n    assume V2:\\<open>w \\<in> (\\<Union>y\\<in>Y. {\\<langle>x, y\\<rangle>})\\<close>\n    show \\<open>w \\<in> X \\<times> Y\\<close>\n    proof (rule UN_E[OF V2])\n      fix y\n      assume V3:\\<open>y \\<in> Y\\<close>\n      assume V4:\\<open>w \\<in> {\\<langle>x, y\\<rangle>}\\<close>\n      then have V4:\\<open>w = \\<langle>x, y\\<rangle>\\<close>\n        by auto\n      have v5:\\<open>\\<langle>x, y\\<rangle> \\<in> Sigma(X,\\<lambda>_.Y)\\<close>\n      proof(rule SigmaI)\n        show \\<open>x \\<in> X\\<close> by (rule V1)\n      next\n        show \\<open>y \\<in> Y\\<close> by (rule V3)\n      qed\n      then have V5:\\<open>\\<langle>x, y\\<rangle> \\<in> X*Y\\<close> \n        by auto\n      from V4 and V5 show \\<open>w \\<in> X \\<times> Y\\<close> by auto\n    qed\n  qed\nqed\n\ntheorem recuniq : \n  fixes f\n  assumes H0:\\<open>f \\<in> nat -> A \\<and> f ` 0 = a \\<and> satpc(f, nat, g)\\<close>\n  fixes t\n  assumes H1:\\<open>t \\<in> nat -> A \\<and> t ` 0 = a \\<and> satpc(t, nat, g)\\<close>\n  fixes x\n  shows \\<open>f=t\\<close>\nproof -\n  from H0 have H02:\\<open>\\<forall>n \\<in> nat. f`succ(n) = g ` <(f`n), n>\\<close> by (unfold satpc_def, auto)\n  from H0 have H01:\\<open>f ` 0 = a\\<close> by auto\n  from H0 have H00:\\<open>f \\<in> nat -> A\\<close> by auto\n  from H1 have H12:\\<open>\\<forall>n \\<in> nat. t`succ(n) = g ` <(t`n), n>\\<close> by (unfold satpc_def, auto)\n  from H1 have H11:\\<open>t ` 0 = a\\<close> by auto\n  from H1 have H10:\\<open>t \\<in> nat -> A\\<close> by auto\n  show \\<open>f=t\\<close>\n  proof (rule fun_extension[OF H00 H10])\n    fix x\n    assume K: \\<open>x \\<in> nat\\<close>\n    show \\<open>(f ` x) = (t ` x)\\<close>\n    proof(rule nat_induct[of x])\n      show \\<open>x \\<in> nat\\<close> by (rule K)\n    next\n      from H01 and H11 show \\<open>f ` 0 = t ` 0\\<close>\n        by auto\n    next\n      fix x\n      assume A:\\<open>x\\<in>nat\\<close>\n      assume B:\\<open>f`x = t`x\\<close>\n      show \\<open>f ` succ(x) = t ` succ(x)\\<close>\n      proof -\n        from H02 and A have H02':\\<open>f`succ(x) = g ` <(f`x), x>\\<close> \n          by (rule bspec)\n        from H12 and A have H12':\\<open>t`succ(x) = g ` <(t`x), x>\\<close> \n          by (rule bspec)\n        from B and H12' have H12'':\\<open>t`succ(x) = g ` <(f`x), x>\\<close> by auto\n        from H12'' and H02' show \\<open>f ` succ(x) = t ` succ(x)\\<close> by auto\n      qed\n    qed\n  qed\nqed\n\nsection \\<open>Lemmas for recursion theorem\\<close>\n\nlocale recthm =\n  fixes A :: \"i\"\n    and a :: \"i\"\n    and g :: \"i\"\n  assumes hyp1 : \\<open>a \\<in> A\\<close>\n    and hyp2 : \\<open>g : ((A*nat)\\<rightarrow>A)\\<close>\nbegin\n\nlemma l3:\\<open>function(\\<Union>pcs(A, a, g))\\<close>\n  by (rule compatsetunionfun, rule pcs_lem, rule hyp1)\n\nlemma l1 : \\<open>\\<Union>pcs(A, a, g) \\<subseteq> nat \\<times> A\\<close>\nproof\n  fix x\n  assume H:\\<open>x \\<in> \\<Union>pcs(A, a, g)\\<close>\n  hence  H:\\<open>x \\<in> \\<Union>{t\\<in>Pow(nat*A). \\<exists>m\\<in>nat. partcomp(A,t,m,a,g)}\\<close>\n    by (unfold pcs_def)\n  show \\<open>x \\<in> nat \\<times> A\\<close>\n  proof(rule UnionE[OF H])\n    fix B\n    assume J1:\\<open>x\\<in>B\\<close>\n    assume J2:\\<open>B \\<in> {t \\<in> Pow(nat \\<times> A) .\n            \\<exists>m\\<in>nat. partcomp(A, t, m, a, g)}\\<close>\n    hence J2:\\<open>B \\<in> Pow(nat \\<times> A)\\<close> by auto\n    hence J2:\\<open>B \\<subseteq> nat \\<times> A\\<close> by auto\n    from J1 and J2 show \\<open>x \\<in> nat \\<times> A\\<close>\n      by auto\n  qed\nqed\n\nlemma le1:\n  assumes H:\\<open>x\\<in>1\\<close>\n  shows \\<open>x=0\\<close>\nproof\n  show \\<open>x \\<subseteq> 0\\<close>\n  proof\n    fix z\n    assume J:\\<open>z\\<in>x\\<close>\n    show \\<open>z\\<in>0\\<close>\n    proof(rule succE[OF H])\n      assume J:\\<open>x\\<in>0\\<close>\n      show \\<open>z\\<in>0\\<close>\n        by (rule notE[OF not_mem_empty J])\n    next\n      assume K:\\<open>x=0\\<close>\n      from J and K show \\<open>z\\<in>0\\<close>\n        by auto\n    qed\n  qed\nnext\n  show \\<open>0 \\<subseteq> x\\<close> by auto\nqed\n\nlemma lsinglfun : \\<open>function({\\<langle>0, a\\<rangle>})\\<close>\nproof(unfold function_def)\n  show \\<open> \\<forall>x y. \\<langle>x, y\\<rangle> \\<in> {\\<langle>0, a\\<rangle>} \\<longrightarrow>\n          (\\<forall>y'. \\<langle>x, y'\\<rangle> \\<in> {\\<langle>0, a\\<rangle>} \\<longrightarrow>\n                y = y')\\<close>\n  proof(rule allI,rule allI,rule impI,rule allI,rule impI)\n    fix x y y'\n    assume H0:\\<open>\\<langle>x, y\\<rangle> \\<in> {\\<langle>0, a\\<rangle>}\\<close>\n    assume H1:\\<open>\\<langle>x, y'\\<rangle> \\<in> {\\<langle>0, a\\<rangle>}\\<close>\n    show \\<open>y = y'\\<close>\n    proof(rule upair.singletonE[OF H0],rule upair.singletonE[OF H1])\n      assume H0:\\<open>\\<langle>x, y\\<rangle> = \\<langle>0, a\\<rangle>\\<close>\n      assume H1:\\<open>\\<langle>x, y'\\<rangle> = \\<langle>0, a\\<rangle>\\<close>\n      from H0 and H1 have H:\\<open>\\<langle>x, y\\<rangle> = \\<langle>x, y'\\<rangle>\\<close> by auto\n      then show \\<open>y = y'\\<close> by auto\n    qed\n  qed\nqed\n\nlemma singlsatpc:\\<open>satpc({\\<langle>0, a\\<rangle>}, 0, g)\\<close>\nproof(unfold satpc_def)\n  show \\<open>\\<forall>n\\<in>0. {\\<langle>0, a\\<rangle>} ` succ(n) =\n           g ` \\<langle>{\\<langle>0, a\\<rangle>} ` n, n\\<rangle>\\<close>\n    by auto\nqed\n\nlemma zerostep :\n  shows \\<open>partcomp(A, {\\<langle>0, a\\<rangle>}, 0, a, g)\\<close>\nproof(unfold partcomp_def)\n  show \\<open>{\\<langle>0, a\\<rangle>} \\<in> 1 -> A \\<and> {\\<langle>0, a\\<rangle>} ` 0 = a \\<and> satpc({\\<langle>0, a\\<rangle>}, 0, g)\\<close>\n  proof\n    show \\<open>{\\<langle>0, a\\<rangle>} \\<in> 1 -> A\\<close>\n    proof (unfold Pi_def)\n      show \\<open>{\\<langle>0, a\\<rangle>} \\<in> {f \\<in> Pow(1 \\<times> A) . 1 \\<subseteq> domain(f) \\<and> function(f)}\\<close>\n      proof\n        show \\<open>{\\<langle>0, a\\<rangle>} \\<in> Pow(1 \\<times> A)\\<close>\n        proof(rule PowI, rule equalities.singleton_subsetI)\n          show \\<open>\\<langle>0, a\\<rangle> \\<in> 1 \\<times> A\\<close>\n          proof\n            show \\<open>0 \\<in> 1\\<close> by auto\n          next\n            show \\<open>a \\<in> A\\<close> by (rule hyp1)\n          qed\n        qed\n      next\n        show \\<open>1 \\<subseteq> domain({\\<langle>0, a\\<rangle>}) \\<and> function({\\<langle>0, a\\<rangle>})\\<close>\n        proof\n          show \\<open>1 \\<subseteq> domain({\\<langle>0, a\\<rangle>})\\<close>\n          proof\n            fix x\n            assume W:\\<open>x\\<in>1\\<close>\n            from W have W:\\<open>x=0\\<close> by (rule le1)\n            have Y:\\<open>0\\<in>domain({\\<langle>0, a\\<rangle>})\\<close>\n              by auto\n            from W and Y \n            show \\<open>x\\<in>domain({\\<langle>0, a\\<rangle>})\\<close>\n              by auto\n          qed\n        next\n          show \\<open>function({\\<langle>0, a\\<rangle>})\\<close>\n            by (rule lsinglfun)\n        qed\n      qed\n    qed\n    show \\<open>{\\<langle>0, a\\<rangle>} ` 0 = a \\<and> satpc({\\<langle>0, a\\<rangle>}, 0, g)\\<close>\n    proof\n      show \\<open>{\\<langle>0, a\\<rangle>} ` 0 = a\\<close>\n        by (rule func.singleton_apply)\n    next\n      show \\<open>satpc({\\<langle>0, a\\<rangle>}, 0, g)\\<close>\n        by (rule singlsatpc)\n    qed\n  qed\nqed\n\nlemma zainupcs : \\<open>\\<langle>0, a\\<rangle> \\<in> \\<Union>pcs(A, a, g)\\<close>\nproof\n  show \\<open>\\<langle>0, a\\<rangle> \\<in> {\\<langle>0, a\\<rangle>}\\<close>\n    by auto\nnext\n  (* {\\<langle>0, a\\<rangle>} is a 0-step computation *)\n  show \\<open>{\\<langle>0, a\\<rangle>} \\<in> pcs(A, a, g)\\<close>\n  proof(unfold pcs_def)\n    show \\<open>{\\<langle>0, a\\<rangle>} \\<in> {t \\<in> Pow(nat \\<times> A) . \\<exists>m\\<in>nat. partcomp(A, t, m, a, g)}\\<close>\n    proof\n      show \\<open>{\\<langle>0, a\\<rangle>} \\<in> Pow(nat \\<times> A)\\<close>\n      proof(rule PowI, rule equalities.singleton_subsetI)\n        show \\<open>\\<langle>0, a\\<rangle> \\<in> nat \\<times> A\\<close>\n        proof\n          show \\<open>0 \\<in> nat\\<close> by auto\n        next\n          show \\<open>a \\<in> A\\<close> by (rule hyp1)\n        qed\n      qed\n    next\n      show \\<open>\\<exists>m\\<in>nat. partcomp(A, {\\<langle>0, a\\<rangle>}, m, a, g)\\<close>\n      proof\n        show \\<open>partcomp(A, {\\<langle>0, a\\<rangle>}, 0, a, g)\\<close>\n          by (rule zerostep)\n      next\n        show \\<open>0 \\<in> nat\\<close> by auto\n      qed\n    qed\n  qed\nqed\n\nlemma l2': \\<open>0 \\<in> domain(\\<Union>pcs(A, a, g))\\<close>\nproof\n  show \\<open>\\<langle>0, a\\<rangle> \\<in> \\<Union>pcs(A, a, g)\\<close>\n    by (rule zainupcs)\nqed\n\ntext \\<open>Push an ordered pair to the end of partial computation t \nand obtain another partial computation.\\<close>\nlemma shortlem :\n  assumes mnat:\\<open>m\\<in>nat\\<close>\n  assumes F:\\<open>partcomp(A,t,m,a,g)\\<close>\n  shows \\<open>partcomp(A,cons(\\<langle>succ(m), g ` <t`m, m>\\<rangle>, t),succ(m),a,g)\\<close>\nproof(rule partcompE[OF F])\n  assume F1:\\<open>t \\<in> succ(m) \\<rightarrow> A\\<close>\n  assume F2:\\<open>t ` 0 = a\\<close>\n  assume F3:\\<open>satpc(t, m, g)\\<close>\n  show ?thesis (*\\<open>partcomp(A,cons(\\<langle>succ(m), g ` <t`m, m>\\<rangle>, t),succ(m),a,g)\\<close> *)\n  proof\n    have ljk:\\<open>cons(\\<langle>succ(m), g ` \\<langle>t ` m, m\\<rangle>\\<rangle>, t) \\<in> (cons(succ(m),succ(m)) \\<rightarrow> A)\\<close>\n    proof(rule func.fun_extend3[OF F1]) \n      show \\<open>succ(m) \\<notin> succ(m)\\<close>\n        by (rule  upair.mem_not_refl)\n      have tmA:\\<open>t ` m \\<in> A\\<close>\n        by (rule func.apply_funtype[OF F1], auto)\n      show \\<open>g ` \\<langle>t ` m, m\\<rangle> \\<in> A\\<close>\n        by(rule func.apply_funtype[OF hyp2], auto, rule tmA, rule mnat)\n    qed\n    have \\<open>cons(\\<langle>succ(m), g ` \\<langle>t ` m, m\\<rangle>\\<rangle>, t) \\<in> (cons(succ(m),succ(m)) \\<rightarrow> A)\\<close>\n      by (rule ljk)\n    then have \\<open>cons(\\<langle>cons(m, m), g ` \\<langle>t ` m, m\\<rangle>\\<rangle>, t) \\<in> cons(cons(m, m), cons(m, m)) \\<rightarrow> A\\<close>\n      by (unfold succ_def)\n    then show \\<open>cons(\\<langle>succ(m), g ` \\<langle>t ` m, m\\<rangle>\\<rangle>, t) \\<in> succ(succ(m)) \\<rightarrow> A\\<close>\n      by (unfold succ_def, assumption)\n    show \\<open>cons(\\<langle>succ(m), g ` \\<langle>t ` m, m\\<rangle>\\<rangle>, t) ` 0 = a\\<close>\n    proof(rule trans, rule func.fun_extend_apply[OF F1])\n      show \\<open>succ(m) \\<notin> succ(m)\\<close> by (rule  upair.mem_not_refl)\n      show \\<open>(if 0 = succ(m) then g ` \\<langle>t ` m, m\\<rangle> else t ` 0) = a\\<close>\n        by(rule trans, rule upair.if_not_P, auto, rule F2)\n    qed\n    show \\<open>satpc(cons(\\<langle>succ(m), g ` \\<langle>t ` m, m\\<rangle>\\<rangle>, t), succ(m), g)\\<close>\n    proof(unfold satpc_def, rule ballI)\n      fix n\n      assume Q:\\<open>n \\<in> succ(m)\\<close>\n      show \\<open>cons(\\<langle>succ(m), g ` \\<langle>t ` m, m\\<rangle>\\<rangle>, t) ` succ(n) \n= g ` \\<langle>cons(\\<langle>succ(m), g ` \\<langle>t ` m, m\\<rangle>\\<rangle>, t) ` n, n\\<rangle>\\<close>\n      proof(rule trans, rule func.fun_extend_apply[OF F1], rule upair.mem_not_refl)\n        show \\<open>(if succ(n) = succ(m) then g ` \\<langle>t ` m, m\\<rangle> else t ` succ(n)) =\n    g ` \\<langle>cons(\\<langle>succ(m), g ` \\<langle>t ` m, m\\<rangle>\\<rangle>, t) ` n, n\\<rangle>\\<close>\n        proof(rule upair.succE[OF Q])\n          assume Y:\\<open>n=m\\<close>\n          show \\<open>(if succ(n) = succ(m) then g ` \\<langle>t ` m, m\\<rangle> else t ` succ(n)) =\n    g ` \\<langle>cons(\\<langle>succ(m), g ` \\<langle>t ` m, m\\<rangle>\\<rangle>, t) ` n, n\\<rangle>\\<close>\n          proof(rule trans, rule upair.if_P)\n            from Y show \\<open>succ(n) = succ(m)\\<close> by auto\n          next\n            have L1:\\<open>t ` m = cons(\\<langle>succ(m), g ` \\<langle>t ` m, m\\<rangle>\\<rangle>, t) ` n\\<close>\n            proof(rule sym, rule trans, rule func.fun_extend_apply[OF F1], rule upair.mem_not_refl) \n              show \\<open> (if n = succ(m) then g ` \\<langle>t ` m, m\\<rangle> else t ` n) = t ` m\\<close>\n              proof(rule trans, rule upair.if_not_P)\n                from Y show \\<open>t ` n = t ` m\\<close> by auto\n                show \\<open>n \\<noteq> succ(m)\\<close>\n                proof(rule not_sym)\n                  show \\<open>succ(m) \\<noteq> n\\<close>\n                    by(rule subst, rule sym, rule Y, rule upair.succ_neq_self)\n                qed\n              qed\n            qed\n            from Y\n            have L2:\\<open>m = n\\<close>\n              by auto\n            have L:\\<open> \\<langle>t ` m, m\\<rangle> = \\<langle>cons(\\<langle>succ(m), g ` \\<langle>t ` m, m\\<rangle>\\<rangle>, t) ` n, n\\<rangle>\\<close>\n              by(rule subst_context2[OF L1 L2])\n            show \\<open> g ` \\<langle>t ` m, m\\<rangle> = g ` \\<langle>cons(\\<langle>succ(m), g ` \\<langle>t ` m, m\\<rangle>\\<rangle>, t) ` n, n\\<rangle>\\<close>\n              by(rule subst_context[OF L])\n          qed\n        next\n          assume Y:\\<open>n \\<in> m\\<close>\n          show \\<open>(if succ(n) = succ(m) then g ` \\<langle>t ` m, m\\<rangle> else t ` succ(n)) =\n                g ` \\<langle>cons(\\<langle>succ(m), g ` \\<langle>t ` m, m\\<rangle>\\<rangle>, t) ` n, n\\<rangle>\\<close>\n          proof(rule trans, rule upair.if_not_P)\n            show \\<open>succ(n) \\<noteq> succ(m)\\<close>\n              by(rule contrapos, rule upair.mem_imp_not_eq, rule Y, rule upair.succ_inject, assumption)\n          next\n            have X:\\<open>cons(\\<langle>succ(m), g ` \\<langle>t ` m, m\\<rangle>\\<rangle>, t) ` n = t ` n\\<close>\n            proof(rule trans, rule func.fun_extend_apply[OF F1], rule upair.mem_not_refl)\n              show \\<open>(if n = succ(m) then g ` \\<langle>t ` m, m\\<rangle> else t ` n) = t ` n\\<close>\n              proof(rule upair.if_not_P)\n                show \\<open>n \\<noteq> succ(m)\\<close>\n                proof(rule contrapos)\n                  assume q:\"n=succ(m)\"\n                  from q and Y have M:\\<open>succ(m)\\<in>m\\<close>\n                    by auto\n                  show \\<open>m\\<in>m\\<close>\n                    by(rule Nat.succ_in_naturalD[OF M mnat])\n                next\n                  show \\<open>m \\<notin> m\\<close> by (rule  upair.mem_not_refl)\n                qed\n              qed\n            qed\n            from F3\n            have W:\\<open>\\<forall>n\\<in>m. t ` succ(n) = g ` \\<langle>t ` n, n\\<rangle>\\<close>\n              by (unfold satpc_def)\n            have U:\\<open>t ` succ(n) = g ` \\<langle>t ` n, n\\<rangle>\\<close>\n              by (rule bspec[OF W Y])\n            show \\<open>t ` succ(n) = g ` \\<langle>cons(\\<langle>succ(m), g ` \\<langle>t ` m, m\\<rangle>\\<rangle>, t) ` n, n\\<rangle>\\<close>\n              by (rule trans, rule U, rule sym, rule subst_context[OF X])\n          qed\n        qed\n      qed\n    qed\n  qed\nqed\n\nlemma l2:\\<open>nat \\<subseteq> domain(\\<Union>pcs(A, a, g))\\<close>\nproof\n  fix x\n  assume G:\\<open>x\\<in>nat\\<close>\n  show \\<open>x \\<in> domain(\\<Union>pcs(A, a, g))\\<close>\n  proof(rule nat_induct[of x])\n    show \\<open>x\\<in>nat\\<close> by (rule G)\n  next\n    fix x\n    assume Q1:\\<open>x\\<in>nat\\<close>\n    assume Q2:\\<open>x\\<in>domain(\\<Union>pcs(A, a, g))\\<close>\n    show \\<open>succ(x)\\<in>domain(\\<Union>pcs(A, a, g))\\<close>\n    proof(rule domainE[OF Q2])\n      fix y\n      assume W1:\\<open>\\<langle>x, y\\<rangle> \\<in> (\\<Union>pcs(A, a, g))\\<close>\n      show \\<open>succ(x)\\<in>domain(\\<Union>pcs(A, a, g))\\<close>\n      proof(rule UnionE[OF W1])\n        fix t\n        assume E1:\\<open>\\<langle>x, y\\<rangle> \\<in> t\\<close>\n        assume E2:\\<open>t \\<in> pcs(A, a, g)\\<close>\n        hence E2:\\<open>t\\<in>{t\\<in>Pow(nat*A). \\<exists>m \\<in> nat. partcomp(A,t,m,a,g)}\\<close> \n          by(unfold pcs_def)\n        have E21:\\<open>t\\<in>Pow(nat*A)\\<close>\n          by(rule CollectD1[OF E2])\n        have E22m:\\<open>\\<exists>m\\<in>nat. partcomp(A,t,m,a,g)\\<close>\n          by(rule CollectD2[OF E2])\n        show \\<open>succ(x)\\<in>domain(\\<Union>pcs(A, a, g))\\<close>\n        proof(rule bexE[OF E22m])\n          fix m\n          assume mnat:\\<open>m\\<in>nat\\<close>\n          assume E22P:\\<open>partcomp(A,t,m,a,g)\\<close>\n          hence E22:\\<open>((t:succ(m)\\<rightarrow>A) \\<and> (t`0=a)) \\<and> satpc(t,m,g)\\<close> \n            by(unfold partcomp_def, auto)\n          hence E223:\\<open>satpc(t,m,g)\\<close> by auto\n          hence E223:\\<open>\\<forall>n \\<in> m . t`succ(n) = g ` <t`n, n>\\<close>\n            by(unfold satpc_def, auto)\n          from E22 have E221:\\<open>(t:succ(m)\\<rightarrow>A)\\<close>\n            by auto\n          from E221 have domt:\\<open>domain(t) = succ(m)\\<close>\n            by (rule func.domain_of_fun)\n          from E1 have xind:\\<open>x \\<in> domain(t)\\<close>\n            by (rule equalities.domainI)\n          from xind and domt have xinsm:\\<open>x \\<in> succ(m)\\<close>\n            by auto\n          show \\<open>succ(x)\\<in>domain(\\<Union>pcs(A, a, g))\\<close>\n          proof\n        (*proof(rule exE[OF E22])*)\n            show \\<open> \\<langle>succ(x), g ` <t`x, x>\\<rangle> \\<in> (\\<Union>pcs(A, a, g))\\<close> (*?*)\n            proof\n             (*t\\<union>{\\<langle>succ(x), g ` <t`x, x>\\<rangle>}*)\n              show \\<open>cons(\\<langle>succ(x), g ` <t`x, x>\\<rangle>, t) \\<in> pcs(A, a, g)\\<close>\n              proof(unfold pcs_def, rule CollectI)\n                from E21\n                have L1:\\<open>t \\<subseteq> nat \\<times> A\\<close>\n                  by auto\n                from Q1 have J1:\\<open>succ(x)\\<in>nat\\<close>\n                  by auto(*Nat.nat_succI*)\n                have txA: \\<open>t ` x \\<in> A\\<close>\n                  by (rule func.apply_type[OF E221 xinsm])\n                from txA and Q1 have txx:\\<open>\\<langle>t ` x, x\\<rangle> \\<in> A \\<times> nat\\<close>\n                  by auto\n                have secp: \\<open>g ` \\<langle>t ` x, x\\<rangle> \\<in> A\\<close>\n                  by(rule func.apply_type[OF hyp2 txx])\n                from J1 and secp\n                have L2:\\<open>\\<langle>succ(x),g ` \\<langle>t ` x, x\\<rangle>\\<rangle> \\<in> nat \\<times> A\\<close>\n                  by auto\n                show \\<open> cons(\\<langle>succ(x),g ` \\<langle>t ` x, x\\<rangle>\\<rangle>,t) \\<in> Pow(nat \\<times> A)\\<close>\n                proof(rule PowI)\n                  show \\<open> cons(\\<langle>succ(x), g ` \\<langle>t ` x, x\\<rangle>\\<rangle>, t) \\<subseteq> nat \\<times> A\\<close>\n                  proof\n                    show \\<open>\\<langle>succ(x), g ` \\<langle>t ` x, x\\<rangle>\\<rangle> \\<in> nat \\<times> A \\<and> t \\<subseteq> nat \\<times> A\\<close>\n                      by (rule conjI[OF L2 L1])\n                  qed\n                qed\n              next \n                show \\<open>\\<exists>m \\<in> nat. partcomp(A, cons(\\<langle>succ(x), g ` \\<langle>t ` x, x\\<rangle>\\<rangle>, t), m, a, g)\\<close>\n                proof(rule succE[OF xinsm])\n                  assume xeqm:\\<open>x=m\\<close>\n                  show \\<open>\\<exists>m \\<in> nat. partcomp(A, cons(\\<langle>succ(x), g ` \\<langle>t ` x, x\\<rangle>\\<rangle>, t), m, a, g)\\<close>\n                  proof\n                    show \\<open>partcomp(A, cons(\\<langle>succ(x), g ` \\<langle>t ` x, x\\<rangle>\\<rangle>, t), succ(x), a, g)\\<close>\n                    proof(rule shortlem[OF Q1])\n                      show \\<open>partcomp(A, t, x, a, g)\\<close>\n                      proof(rule subst[of m x], rule sym, rule xeqm)\n                        show \\<open>partcomp(A, t, m, a, g)\\<close> \n                          by (rule E22P)\n                      qed\n                    qed\n                  next\n                    from Q1 show \\<open>succ(x) \\<in> nat\\<close> by auto\n                  qed\n                next\n                  assume xinm:\\<open>x\\<in>m\\<close>\n                  have lmm:\\<open>cons(\\<langle>succ(x), g ` \\<langle>t ` x, x\\<rangle>\\<rangle>, t) = t\\<close>\n                    by (rule addmiddle[OF mnat E22P xinm])\n                  show \\<open>\\<exists>m\\<in>nat. partcomp(A, cons(\\<langle>succ(x), g ` \\<langle>t ` x, x\\<rangle>\\<rangle>, t), m, a, g)\\<close>\n                    by(rule subst[of t], rule sym, rule lmm, rule E22m)\n                qed\n              qed\n            next\n              show \\<open>\\<langle>succ(x), g ` \\<langle>t ` x, x\\<rangle>\\<rangle> \\<in> cons(\\<langle>succ(x), g ` \\<langle>t ` x, x\\<rangle>\\<rangle>, t)\\<close>\n                by auto\n            qed\n          qed\n        qed\n      qed\n    qed\n  next\n    show \\<open>0 \\<in> domain(\\<Union>pcs(A, a, g))\\<close>\n      by (rule l2')\n  qed\nqed\n\nlemma useful : \\<open>\\<forall>m\\<in>nat. \\<exists>t. partcomp(A,t,m,a,g)\\<close>\nproof(rule nat_induct_bound)\n  show \\<open>\\<exists>t. partcomp(A, t, 0, a, g)\\<close>\n  proof\n    show \\<open>partcomp(A, {\\<langle>0, a\\<rangle>}, 0, a, g)\\<close>\n      by (rule zerostep)\n  qed\nnext\n  fix m\n  assume mnat:\\<open>m\\<in>nat\\<close>\n  assume G:\\<open>\\<exists>t. partcomp(A,t,m,a,g)\\<close>\n  show \\<open>\\<exists>t. partcomp(A,t,succ(m),a,g)\\<close>\n  proof(rule exE[OF G])\n    fix t\n    assume G:\\<open>partcomp(A,t,m,a,g)\\<close>\n    show \\<open>\\<exists>t. partcomp(A,t,succ(m),a,g)\\<close>\n    proof\n      show \\<open>partcomp(A,cons(\\<langle>succ(m), g ` <t`m, m>\\<rangle>, t),succ(m),a,g)\\<close>\n        by(rule shortlem[OF mnat G])\n    qed\n  qed\nqed\n\nlemma l4 : \\<open>(\\<Union>pcs(A,a,g)) \\<in> nat -> A\\<close>\nproof(unfold Pi_def)\n  show \\<open> \\<Union>pcs(A, a, g) \\<in> {f \\<in> Pow(nat \\<times> A) . nat \\<subseteq> domain(f) \\<and> function(f)}\\<close>\n  proof\n    show \\<open>\\<Union>pcs(A, a, g) \\<in> Pow(nat \\<times> A)\\<close>\n    proof \n      show \\<open>\\<Union>pcs(A, a, g) \\<subseteq> nat \\<times> A\\<close>\n        by (rule l1)\n    qed\n  next \n    show \\<open>nat \\<subseteq> domain(\\<Union>pcs(A, a, g)) \\<and> function(\\<Union>pcs(A, a, g))\\<close>\n    proof\n      show \\<open>nat \\<subseteq> domain(\\<Union>pcs(A, a, g))\\<close>\n        by (rule l2)\n    next\n      show \\<open>function(\\<Union>pcs(A, a, g))\\<close>\n        by (rule l3)\n    qed\n  qed\nqed\n\nlemma l5: \\<open>(\\<Union>pcs(A, a, g)) ` 0 = a\\<close>     \nproof(rule func.function_apply_equality)\n  show \\<open>function(\\<Union>pcs(A, a, g))\\<close>\n    by (rule l3)\nnext\n  show \\<open>\\<langle>0, a\\<rangle> \\<in> \\<Union>pcs(A, a, g)\\<close>\n    by (rule zainupcs)\nqed\n\nlemma ballE2: \n  assumes \\<open>\\<forall>x\\<in>AA. P(x)\\<close>\n  assumes \\<open>x\\<in>AA\\<close>\n  assumes \\<open>P(x) ==> Q\\<close>\n  shows Q\n  by (rule assms(3), rule bspec, rule assms(1), rule assms(2))\n\ntext \\<open> Recall that\n  \\<open>satpc(t,\\<alpha>,g) == \\<forall>n \\<in> \\<alpha> . t`succ(n) = g ` <t`n, n>\\<close>\n  \\<open>partcomp(A,t,m,a,g) == (t:succ(m)\\<rightarrow>A) \\<and> (t`0=a) \\<and> satpc(t,m,g)\\<close>\n  \\<open>pcs(A,a,g) == {t\\<in>Pow(nat*A). \\<exists>m. partcomp(A,t,m,a,g)}\\<close>\n\\<close>\n\nlemma l6new: \\<open>satpc(\\<Union>pcs(A, a, g), nat, g)\\<close>\nproof (unfold satpc_def, rule ballI)\n  fix n\n  assume nnat:\\<open>n\\<in>nat\\<close>\n  hence snnat:\\<open>succ(n)\\<in>nat\\<close> by auto\n  (* l2:\\<open>nat \\<subseteq> domain(\\<Union>pcs(A, a, g))\\<close> *)\n  show \\<open>(\\<Union>pcs(A, a, g)) ` succ(n) = g ` \\<langle>(\\<Union>pcs(A, a, g)) ` n, n\\<rangle>\\<close>\n  proof(rule ballE2[OF useful snnat], erule exE)\n    fix t\n    assume Y:\\<open>partcomp(A, t, succ(n), a, g)\\<close>\n    show \\<open>(\\<Union>pcs(A, a, g)) ` succ(n) = g ` \\<langle>(\\<Union>pcs(A, a, g)) ` n, n\\<rangle>\\<close>\n    proof(rule partcompE[OF Y])\n      assume Y1:\\<open>t \\<in> succ(succ(n)) \\<rightarrow> A\\<close>\n      assume Y2:\\<open>t ` 0 = a\\<close>\n      assume Y3:\\<open>satpc(t, succ(n), g)\\<close>\n      hence Y3:\\<open>\\<forall>x \\<in> succ(n) . t`succ(x) = g ` <t`x, x>\\<close>\n        by (unfold satpc_def)\n      hence Y3:\\<open>t`succ(n) = g ` <t`n, n>\\<close>\n        by (rule bspec, auto)\n      have e1:\\<open>(\\<Union>pcs(A, a, g)) ` succ(n) = t ` succ(n)\\<close>\n      proof(rule valofunion, rule pcs_lem, rule hyp1)\n        show \\<open>t \\<in> pcs(A, a, g)\\<close>\n        proof(unfold pcs_def, rule CollectI)\n          show \\<open>t \\<in> Pow(nat \\<times> A)\\<close>\n            proof(rule tgb)\n            show \\<open>t \\<in> succ(succ(n)) \\<rightarrow> A\\<close> by (rule Y1)\n          next\n            from snnat\n            show \\<open>succ(succ(n)) \\<in> nat\\<close> by auto\n          qed\n        next\n          show \\<open>\\<exists>m\\<in>nat. partcomp(A, t, m, a, g)\\<close>\n            by(rule bexI, rule Y, rule snnat)\n        qed\n      next\n        show \\<open>t \\<in> succ(succ(n)) \\<rightarrow> A\\<close> by (rule Y1)\n      next\n        show \\<open>succ(n) \\<in> succ(succ(n))\\<close> by auto\n      next\n        show \\<open>t ` succ(n) = t ` succ(n)\\<close> by (rule refl)\n      qed\n      have e2:\\<open>(\\<Union>pcs(A, a, g)) ` n = t ` n\\<close>\n      proof(rule valofunion, rule pcs_lem, rule hyp1)\n        show \\<open>t \\<in> pcs(A, a, g)\\<close>\n        proof(unfold pcs_def, rule CollectI)\n          show \\<open>t \\<in> Pow(nat \\<times> A)\\<close>\n          proof(rule tgb)\n            show \\<open>t \\<in> succ(succ(n)) \\<rightarrow> A\\<close> by (rule Y1)\n          next\n            from snnat\n            show \\<open>succ(succ(n)) \\<in> nat\\<close> by auto\n          qed\n        next\n          show \\<open>\\<exists>m\\<in>nat. partcomp(A, t, m, a, g)\\<close>\n            by(rule bexI, rule Y, rule snnat)\n        qed\n      next\n        show \\<open>t \\<in> succ(succ(n)) \\<rightarrow> A\\<close> by (rule Y1)\n      next\n        show \\<open>n \\<in> succ(succ(n))\\<close> by auto\n      next\n        show \\<open>t ` n = t ` n\\<close> by (rule refl)\n      qed\n      have e3:\\<open>g ` \\<langle>(\\<Union>pcs(A, a, g)) ` n, n\\<rangle> = g ` \\<langle>t ` n, n\\<rangle>\\<close>\n        by (rule subst[OF e2], rule refl)\n      show \\<open>(\\<Union>pcs(A, a, g)) ` succ(n) = g ` \\<langle>(\\<Union>pcs(A, a, g)) ` n, n\\<rangle>\\<close>\n        by (rule trans, rule e1,rule trans, rule Y3, rule sym, rule e3)\n    qed\n  qed\nqed\n\nsection \"Recursion theorem\"\n\ntheorem recursionthm:\n  shows \\<open>\\<exists>!f. ((f \\<in> (nat\\<rightarrow>A)) \\<and> ((f`0) = a) \\<and> satpc(f,nat,g))\\<close>\n(* where \\<open>satpc(t,\\<alpha>,g) == \\<forall>n \\<in> \\<alpha> . t`succ(n) = g ` <t`n, n>\\<close> *)\nproof \n  show \\<open>\\<exists>f. f \\<in> nat -> A \\<and> f ` 0 = a \\<and> satpc(f, nat, g)\\<close>\n  proof \n    show \\<open>(\\<Union>pcs(A,a,g)) \\<in> nat -> A \\<and> (\\<Union>pcs(A,a,g)) ` 0 = a \\<and> satpc(\\<Union>pcs(A,a,g), nat, g)\\<close>\n    proof\n      show \\<open>\\<Union>pcs(A, a, g) \\<in> nat -> A\\<close>\n        by (rule l4)\n    next\n      show \\<open>(\\<Union>pcs(A, a, g)) ` 0 = a \\<and> satpc(\\<Union>pcs(A, a, g), nat, g)\\<close>\n      proof \n        show \\<open>(\\<Union>pcs(A, a, g)) ` 0 = a\\<close>\n          by (rule l5)\n      next\n        show \\<open>satpc(\\<Union>pcs(A, a, g), nat, g)\\<close>\n          by (rule l6new)\n      qed\n    qed\n  qed\nnext\n  show \\<open>\\<And>f y. f \\<in> nat -> A \\<and>\n           f ` 0 = a \\<and>\n           satpc(f, nat, g) \\<Longrightarrow>\n           y \\<in> nat -> A \\<and>\n           y ` 0 = a \\<and>\n           satpc(y, nat, g) \\<Longrightarrow>\n           f = y\\<close>\n    by (rule recuniq)\nqed\n\nend\n\nsection \"Lemmas for addition\"\n\ntext \\<open>\nLet's define function t(x) = (a+x).\nFirstly we need to define a function \\<open>g:nat \\<times> nat \\<rightarrow> nat\\<close>, such that\n\\<open>g`\\<langle>t`n, n\\<rangle> = t`succ(n) = a + (n + 1) = (a + n) + 1 = (t`n) + 1\\<close>\nSo \\<open>g`\\<langle>a, b\\<rangle> = a + 1\\<close> and \\<open>g(p) = succ(pr1(p))\\<close>\nand \\<open>satpc(t,\\<alpha>,g) \\<Longleftrightarrow> \\<forall>n \\<in> \\<alpha> . t`succ(n) = succ(t`n)\\<close>.\n\\<close>\n\ndefinition addg :: \\<open>i\\<close>\n  where addg_def : \\<open>addg == \\<lambda>x\\<in>(nat*nat). succ(fst(x))\\<close>\n\nlemma addgfun: \\<open>function(addg)\\<close>\n  by (unfold addg_def, rule func.function_lam)\n\nlemma addgsubpow : \\<open>addg \\<in> Pow((nat \\<times> nat) \\<times> nat)\\<close>\nproof (unfold addg_def, rule subsetD)\n  show \\<open>(\\<lambda>x\\<in>nat \\<times> nat. succ(fst(x))) \\<in> nat \\<times> nat \\<rightarrow> nat\\<close>\n  proof(rule func.lam_type)\n    fix x\n    assume \\<open>x\\<in>nat \\<times> nat\\<close>\n    hence \\<open>fst(x)\\<in>nat\\<close> by auto\n    thus \\<open>succ(fst(x)) \\<in> nat\\<close> by auto\n  qed\nnext\n  show \\<open>nat \\<times> nat \\<rightarrow> nat \\<subseteq> Pow((nat \\<times> nat) \\<times> nat)\\<close>\n    by (rule pisubsig)\nqed\n\nlemma addgdom : \\<open>nat \\<times> nat \\<subseteq> domain(addg)\\<close>\nproof(unfold addg_def)\n  have e:\\<open>domain(\\<lambda>x\\<in>nat \\<times> nat. succ(fst(x))) = nat \\<times> nat\\<close>\n    by (rule domain_lam)  (* \"domain(Lambda(A,b)) = A\" *)\n  show \\<open>nat \\<times> nat \\<subseteq>\n    domain(\\<lambda>x\\<in>nat \\<times> nat. succ(fst(x)))\\<close>\n    by (rule subst, rule sym, rule e, auto)\nqed\n\nlemma plussucc:\n  assumes F:\\<open>f \\<in> (nat\\<rightarrow>nat)\\<close>\n  assumes H:\\<open>satpc(f,nat,addg)\\<close>\n  shows \\<open>\\<forall>n \\<in> nat . f`succ(n) = succ(f`n)\\<close>\nproof\n  fix n\n  assume J:\\<open>n\\<in>nat\\<close>\n  from H\n  have H:\\<open>\\<forall>n \\<in> nat . f`succ(n) = (\\<lambda>x\\<in>(nat*nat). succ(fst(x)))` <f`n, n>\\<close>\n    by (unfold satpc_def, unfold addg_def)\n  have H:\\<open>f`succ(n) = (\\<lambda>x\\<in>(nat*nat). succ(fst(x)))` <f`n, n>\\<close>\n    by (rule bspec[OF H J])\n  have Q:\\<open>(\\<lambda>x\\<in>(nat*nat). succ(fst(x)))` <f`n, n> = succ(fst(<f`n, n>))\\<close>\n  proof(rule func.beta)\n    show \\<open>\\<langle>f ` n, n\\<rangle> \\<in> nat \\<times> nat\\<close>\n    proof\n      show \\<open>f ` n \\<in> nat\\<close> \n        by (rule func.apply_funtype[OF F J])\n      show \\<open>n \\<in> nat\\<close> \n        by (rule J)\n    qed\n  qed\n  have HQ:\\<open>f`succ(n) = succ(fst(<f`n, n>))\\<close>\n    by (rule trans[OF H Q])\n  have K:\\<open>fst(<f`n, n>) = f`n\\<close>\n    by auto\n  hence K:\\<open>succ(fst(<f`n, n>)) = succ(f`n)\\<close>\n    by (rule subst_context)\n  show \\<open>f`succ(n) = succ(f`n)\\<close>\n    by (rule trans[OF HQ K])\nqed\n\nsection \"Definition of addition\"\n\ntext \\<open>Theorem that addition of natural numbers exists \nand unique in some sense. Due to theorem 'plussucc' the term\n \\<open>satpc(f,nat,addg)\\<close>\n  can be replaced here with\n \\<open>\\<forall>n \\<in> nat . f`succ(n) = succ(f`n)\\<close>.\\<close>\ntheorem addition:\n  assumes \\<open>a\\<in>nat\\<close>\n  shows\n \\<open>\\<exists>!f. ((f \\<in> (nat\\<rightarrow>nat)) \\<and> ((f`0) = a) \\<and> satpc(f,nat,addg))\\<close>\nproof(rule recthm.recursionthm, unfold recthm_def)\n  show \\<open>a \\<in> nat \\<and> addg \\<in> nat \\<times> nat \\<rightarrow> nat\\<close>\n  proof\n    show \\<open>a\\<in>nat\\<close> by (rule assms(1))\n  next\n    show \\<open>addg \\<in> nat \\<times> nat \\<rightarrow> nat\\<close>\n    proof(unfold Pi_def, rule CollectI)\n      show \\<open>addg \\<in> Pow((nat \\<times> nat) \\<times> nat)\\<close>\n        by (rule addgsubpow)\n    next\n      have A2: \\<open>nat \\<times> nat \\<subseteq> domain(addg)\\<close>\n        by(rule addgdom)\n      have A3: \\<open>function(addg)\\<close>\n        by (rule addgfun)\n      show \\<open>nat \\<times> nat \\<subseteq> domain(addg) \\<and> function(addg)\\<close>\n        by(rule conjI[OF A2 A3])\n    qed\n  qed\nqed\n\nend\n", "meta": {"author": "georgydunaev", "repo": "RecursionTheorem", "sha": "7ea9a8db9fc588a77a94f87a88f8fbf6d78d87be", "save_path": "github-repos/isabelle/georgydunaev-RecursionTheorem", "path": "github-repos/isabelle/georgydunaev-RecursionTheorem/RecursionTheorem-7ea9a8db9fc588a77a94f87a88f8fbf6d78d87be/Recursion-Addition/recursion.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117983401363, "lm_q2_score": 0.8633916011860785, "lm_q1q2_score": 0.7137760232883127}}
{"text": "theory Submission\n  imports Defs\nbegin\n\nlemma eval_term_map2_add [simp]:\n  assumes \"length as = length bs\" \"length bs = length xs\"\n  shows \"eval_term (map2 (+) as bs) xs = eval_term as xs + eval_term bs xs\"\n  using assms\n  by (induction rule: list_induct3) (auto simp: eval_term_def algebra_simps)\n\nlemma eval_term_kill:\n  assumes \"length gcs = length xs\" \"n < length xs\"\n  shows   \"eval_term (gcs[n := 0]) xs = eval_term gcs xs - gcs ! n * xs ! n\"\n  using assms\n  by (induction arbitrary: n rule: list_induct2)\n     (auto split: list.splits nat.splits simp: eval_term_def)\n\ntext \\<open>Prove the following helpful lemmas for proof of the main correctness theorem:\\<close>\ntheorem ineq_add_cancel:\n  assumes \"length gcs = length xs\" \"n < length xs\" \"gcs!n = 1\" \"length lcs = length xs\" \"lcs!n = -1\"\n  shows   \"ineq_sat (ineq_add (ineq gcs gk) (ineq lcs lk)) xs \\<longleftrightarrow>\n           eval_term (gcs[n := 0]) xs + eval_term (lcs[n := 0]) xs \\<le> gk + lk\"\n  using assms by (auto simp: ineq_sat_def ineq_add_def eval_term_kill)\n\ntheorem eval_term_nth_split:\n  assumes \"length gcs = length xs\" \"n < length xs\"\n  shows \"eval_term gcs (xs[n := t]) = eval_term (gcs[n := 0]) xs + gcs!n * t\"\n  using assms unfolding eval_term_def\n  by (induction arbitrary: n rule: list_induct2)\n     (auto split: list.splits nat.splits simp: eval_term_def)\n\nlemma eval_term_list_div [simp]:\n  assumes \"length xs = length ys\"\n  shows   \"eval_term (list_div xs \\<bar>z\\<bar>) ys = eval_term xs ys / \\<bar>z\\<bar>\"\n  using assms\n  by (induction rule: list_induct2)\n     (simp_all add: eval_term_def list_div_def divide_simps split: if_splits)\n\nlemma triple_sat_GZL [simp]: \"triple_sat (GZL ps n) xs \\<longleftrightarrow> pol_sat ps xs\"\n  apply (auto simp: triple_sat_def GZL_def pol_sat_def G_def Z_def L_def)\n  by (metis (mono_tags, lifting) ineq.case ineq.exhaust not_less_iff_gr_or_eq)\n\nlemma ineq_sat_div:\n  assumes \"case p of ineq xs c \\<Rightarrow> length xs = length ys \\<and> xs ! n \\<noteq> 0\" \"n < length ys\"\n  shows \"ineq_sat (ineq_div p n) ys \\<longleftrightarrow> ineq_sat p ys\"\n  using assms by (simp add: ineq_sat_def ineq_div_def field_simps split: ineq.splits)\n\nlemma pol_sat_div:\n  assumes \"n < length ys\" \n  assumes \"\\<forall>pa\\<in>set xs. case pa of ineq xs c \\<Rightarrow> length xs = length ys \\<and> xs ! n \\<noteq> 0\"\n  shows   \"pol_sat (pol_div xs n) ys \\<longleftrightarrow> pol_sat xs ys\"\n  using assms by (auto simp: pol_sat_def pol_div_def ineq_sat_div)\n\nlemma Ball_mono:\n  assumes \"\\<forall>x\\<in>A. P x\" \"\\<forall>x\\<in>A. P x \\<longrightarrow> Q x\"\n  shows   \"\\<forall>x\\<in>A. Q x\"\n  using assms by blast\n\nlemma triple_sat_GZL_div:\n  assumes \"case tr of triple ls es gs \\<Rightarrow>\n             (\\<forall>p\\<in>set ls. case p of ineq q _ \\<Rightarrow> length q = length xs \\<and> q ! n > 0) \\<and>\n             (\\<forall>p\\<in>set gs. case p of ineq q _ \\<Rightarrow> length q = length xs \\<and> q ! n < 0)\" \"n < length xs\"\n  shows   \"triple_sat (GZL_div tr n) xs \\<longleftrightarrow> triple_sat tr xs\"\nproof -\n  obtain ls es gs where tr: \"tr = triple ls es gs\"\n    by (cases tr) auto\n  have \"\\<forall>p\\<in>set ls. case p of ineq q _ \\<Rightarrow> length q = length xs \\<and> q ! n > 0\"\n    using assms(1) by (auto simp: tr)\n  hence 1: \"\\<forall>p\\<in>set ls. case p of ineq q _ \\<Rightarrow> length q = length xs \\<and> q ! n \\<noteq> 0\"\n    by (rule Ball_mono) (auto simp: ineq.splits)\n  have \"\\<forall>p\\<in>set gs. case p of ineq q _ \\<Rightarrow> length q = length xs \\<and> q ! n < 0\"\n    using assms(1) by (auto simp: tr)\n  hence 2: \"\\<forall>p\\<in>set gs. case p of ineq q _ \\<Rightarrow> length q = length xs \\<and> q ! n \\<noteq> 0\"\n    by (rule Ball_mono) (auto simp: ineq.splits)\n  from 1 2 show ?thesis\n   unfolding triple_sat_def GZL_div_def using assms(2)\n   by (auto split: triple.splits simp: pol_sat_div tr)\nqed\n\nlemma pol_sat_GZL_product_preserves_solution:\n  assumes \"case tr of triple ls es gs \\<Rightarrow>\n             (\\<forall>p\\<in>set ls. case p of ineq q _ \\<Rightarrow> length q = length xs \\<and> q ! n = 1) \\<and>\n             (\\<forall>p\\<in>set es. case p of ineq q _ \\<Rightarrow> length q = length xs \\<and> q ! n = 0) \\<and>\n             (\\<forall>p\\<in>set gs. case p of ineq q _ \\<Rightarrow> length q = length xs \\<and> q ! n = -1)\" \"n < length xs\"\n  assumes \"triple_sat tr xs\"\n  shows   \"pol_sat (GZL_product tr) (xs[n := t])\"\nproof -\n  obtain ls es gs where tr: \"tr = triple ls es gs\"\n    by (cases tr) auto\n\n  have *: \"ineq_sat p (xs[n := t])\" if \"p \\<in> set (term_pairing ls gs)\" for p\n  proof -\n    from that obtain l g where lg: \"l \\<in> set ls\" \"g \\<in> set gs\" \"p = ineq_add l g\"\n      by (auto simp: term_pairing_def pol_add_def)\n    obtain cs1 c1 where l: \"l = ineq cs1 c1\"\n      by (cases l)\n    obtain cs2 c2 where g: \"g = ineq cs2 c2\"\n      by (cases g)\n    from assms lg have l': \"length cs1 = length xs \\<and> cs1 ! n = 1\"\n      by (auto simp: l tr)\n    from assms lg have g': \"length cs2 = length xs \\<and> cs2 ! n = -1\"\n      by (auto simp: g tr)\n\n    have \"eval_term cs1 xs + eval_term cs2 xs \\<le> c1 + c2\"\n      using assms(3) l g lg\n      by (intro add_mono) (auto simp: triple_sat_def tr pol_sat_def ineq_sat_def)\n    also have \"eval_term cs1 xs + eval_term cs2 xs =\n               eval_term cs1 (xs[n := t]) + eval_term cs2 (xs[n := t])\"\n      using lg l g l' g' assms(2)\n      by (auto simp: eval_term_nth_split eval_term_kill)\n    finally show \"ineq_sat p (xs[n := t])\" using l' g' \\<open>n < length xs\\<close>\n      by (auto simp: lg l g ineq_add_cancel[where n = n] eval_term_kill)\n  qed\n\n  have **: \"ineq_sat p (xs[n := t])\" if \"p \\<in> set es\" for p\n  proof -\n    obtain cs c where p: \"p = ineq cs c\"\n      by (cases p)\n    from assms that have p': \"length cs = length xs \\<and> cs ! n = 0\"\n      by (auto simp: p tr)\n    have \"eval_term cs xs \\<le> c\"\n      using assms that by (auto simp: triple_sat_def tr pol_sat_def p ineq_sat_def)\n    also have \"eval_term cs xs = eval_term cs (xs[n := t])\"\n      using p' \\<open>n < length xs\\<close> by (auto simp: eval_term_nth_split eval_term_kill)\n    finally show ?thesis\n      using that p p' assms\n      by (auto simp: ineq_sat_def eval_term_kill eval_term_nth_split triple_sat_def tr)\n  qed\n\n  show ?thesis\n    using assms(3) * **\n    by (auto simp: pol_sat_def GZL_product_def triple_sat_def tr)\nqed\n\ndefinition eval_ineq where \"eval_ineq p xs = (case p of ineq cs c \\<Rightarrow> eval_term cs xs - c)\"\n\nlemma pol_sat_GZL_product_has_solution_aux:\n  assumes \"finite A\" \"finite B\" \"\\<And>x y. x \\<in> A \\<Longrightarrow> y \\<in> B \\<Longrightarrow> x \\<le> y\"\n  shows   \"\\<exists>z::rat. (\\<forall>x\\<in>A. x \\<le> z) \\<and> (\\<forall>y\\<in>B. z \\<le> y)\"\n  using assms by (metis finite_has_maximal finite_has_minimal le_less_linear less_le)\n\nlemma pol_sat_GZL_product_has_solution:\n  assumes \"case tr of triple ls es gs \\<Rightarrow>\n             (\\<forall>p\\<in>set ls. case p of ineq q _ \\<Rightarrow> length q = length xs \\<and> q ! n = 1) \\<and>\n             (\\<forall>p\\<in>set es. case p of ineq q _ \\<Rightarrow> length q = length xs \\<and> q ! n = 0) \\<and>\n             (\\<forall>p\\<in>set gs. case p of ineq q _ \\<Rightarrow> length q = length xs \\<and> q ! n = -1)\" \"n < length xs\"\n  assumes \"pol_sat (GZL_product tr) xs\"\n  shows   \"\\<exists>t. triple_sat tr (xs[n := t])\"\nproof -\n  obtain ls es gs where tr: \"tr = triple ls es gs\"\n    by (cases tr) auto\n\n  have \"\\<exists>t. (\\<forall>x\\<in>(\\<lambda>p. eval_ineq p (xs[n := 0]))`set gs. t \\<ge> x) \\<and>\n            (\\<forall>x\\<in>(\\<lambda>p. -eval_ineq p (xs[n := 0]))`set ls. t \\<le> x)\"\n  proof (rule pol_sat_GZL_product_has_solution_aux; (safe)?, goal_cases)\n    fix l g assume lg: \"l \\<in> set ls\" \"g \\<in> set gs\"\n    obtain cs1 c1 where l: \"l = ineq cs1 c1\"\n      by (cases l)\n    obtain cs2 c2 where g: \"g = ineq cs2 c2\"\n      by (cases g)\n    from assms lg have l': \"length cs1 = length xs \\<and> cs1 ! n = 1\"\n      by (auto simp: l tr)\n    from assms lg have g': \"length cs2 = length xs \\<and> cs2 ! n = -1\"\n      by (auto simp: g tr)\n\n    have \"ineq_add l g \\<in> set (GZL_product tr)\"\n      using lg by (auto simp: l g tr GZL_product_def term_pairing_def pol_add_def)\n    with assms have \"ineq_sat (ineq_add l g) xs\"\n      by (auto simp: pol_sat_def)\n    thus \"eval_ineq g (xs[n := 0]) \\<le> - eval_ineq l (xs[n := 0])\"\n      using lg l' g' \\<open>n < _\\<close>\n      by (auto simp: ineq_sat_def l g ineq_add_def eval_ineq_def eval_term_nth_split eval_term_kill)\n  qed auto\n  then obtain t where t:\n    \"\\<And>p. p \\<in> set gs \\<Longrightarrow> t \\<ge> eval_ineq p (xs[n := 0])\"\n    \"\\<And>p. p \\<in> set ls \\<Longrightarrow> t \\<le> -eval_ineq p (xs[n := 0])\"\n    by fast\n\n  have 1: \"ineq_sat p (xs[n := t])\" if \"p \\<in> set gs\" for p\n  proof -\n    obtain cs c where p: \"p = ineq cs c\"\n      by (cases p)\n    from assms that have p': \"length cs = length xs \\<and> cs ! n = -1\"\n      by (auto simp: p tr)\n    have \"t \\<ge> eval_ineq p (xs[n := 0])\"\n      using that by (intro t(1)) auto\n    hence \"eval_term cs xs + xs ! n - t \\<le> eval_term cs xs + xs ! n - eval_ineq p (xs[n := 0])\"\n      by simp\n    also have \"\\<dots> = c\"\n      using p' \\<open>n < length xs\\<close>\n      by (auto simp: p ineq_sat_def eval_term_nth_split eval_term_kill eval_ineq_def)\n    finally show ?thesis\n      using p' \\<open>n < length xs\\<close>\n      by (auto simp: p ineq_sat_def eval_term_nth_split eval_term_kill eval_ineq_def)\n  qed\n\n  have 2: \"ineq_sat p (xs[n := t])\" if \"p \\<in> set ls\" for p\n  proof -\n    obtain cs c where p: \"p = ineq cs c\"\n      by (cases p)\n    from assms that have p': \"length cs = length xs \\<and> cs ! n = 1\"\n      by (auto simp: p tr)\n    have \"t \\<le> -eval_ineq p (xs[n := 0])\"\n      using that by (intro t(2)) auto\n    hence \"eval_term cs xs - xs ! n + t \\<le> eval_term cs xs - xs ! n - eval_ineq p (xs[n := 0])\"\n      by simp\n    also have \"\\<dots> = c\"\n      using p' \\<open>n < length xs\\<close>\n      by (auto simp: p ineq_sat_def eval_term_nth_split eval_term_kill eval_ineq_def)\n    finally show ?thesis\n      using p' \\<open>n < length xs\\<close>\n      by (auto simp: p ineq_sat_def eval_term_nth_split eval_term_kill eval_ineq_def)\n  qed\n\n  have 3: \"ineq_sat p (xs[n := t])\" if \"p \\<in> set es\" for p\n  proof -\n    obtain cs c where p: \"p = ineq cs c\"\n      by (cases p)\n    from assms that have p': \"length cs = length xs \\<and> cs ! n = 0\"\n      by (auto simp: p tr)\n    have \"eval_term cs xs \\<le> c\"\n      using assms that by (force simp: triple_sat_def tr pol_sat_def p ineq_sat_def GZL_product_def)\n    also have \"eval_term cs xs = eval_term cs (xs[n := t])\"\n      using p' \\<open>n < length xs\\<close> by (auto simp: eval_term_nth_split eval_term_kill)\n    finally show ?thesis\n      using that p p' assms\n      by (auto simp: ineq_sat_def eval_term_kill eval_term_nth_split triple_sat_def tr)\n  qed\n\n  have \"triple_sat tr (xs[n := t])\"\n    unfolding triple_sat_def using 1 2 3\n    by (auto simp: tr pol_sat_def)\n  thus ?thesis\n    by blast\nqed \n\n\ntext \\<open>We give partial credits for the two directions of the main theorem:\\<close>\ntheorem FM_preserves_solution:\n  assumes \"\\<forall>p \\<in> set ps. (case p of (ineq cs k) \\<Rightarrow> length cs = length xs)\"\n  assumes \"n < length xs\" \"pol_sat ps (xs[n := t])\"\n  shows \"pol_sat (FM ps n) xs\"\nproof -\n  define xs' where \"xs' = xs[n := t]\"\n  have \"pol_sat (FM ps n) (xs'[n := xs ! n])\"\n  unfolding FM_def\n  proof (rule pol_sat_GZL_product_preserves_solution[where n = n], goal_cases)\n    case 1\n    thus ?case using assms(1,2)\n      by (auto simp: GZL_div_def GZL_def pol_div_def ineq_div_def list_div_def\n                     G_def Z_def L_def xs'_def split: ineq.splits)\n  next\n    case 3\n    have \"case GZL ps n of\n      triple ls es gs \\<Rightarrow>\n        Ball (set ls) (case_ineq (\\<lambda>q x. length q = length xs' \\<and> 0 < q ! n)) \\<and>\n        Ball (set gs) (case_ineq (\\<lambda>q x. length q = length xs' \\<and> q ! n < 0))\"\n      using assms(1)\n      by (auto simp: GZL_def G_def L_def xs'_def split: ineq.splits)\n    moreover have \"triple_sat (GZL ps n) xs'\"\n      using assms by (subst triple_sat_GZL) (auto simp: xs'_def)\n    ultimately show ?case using \\<open>n < length xs\\<close>\n      by (subst triple_sat_GZL_div) (auto simp: xs'_def)\n  qed (use assms in \\<open>auto simp: xs'_def\\<close>)\n  also have \"xs'[n := xs ! n] = xs\"\n    unfolding xs'_def by simp\n  finally show ?thesis .\nqed\n\ntheorem FM_sat_has_solution:\n  assumes \"\\<forall>p \\<in> set ps. (case p of (ineq cs k) \\<Rightarrow> length cs = length xs)\"\n  assumes \"n < length xs\"\n  assumes \"pol_sat (FM ps n) xs\"\n  shows \"\\<exists>t. pol_sat ps (xs[n := t])\"\nproof -\n  from assms have \"pol_sat (GZL_product (GZL_div (GZL ps n) n)) xs\"\n    by (simp add: FM_def)\n  have \"\\<exists>t. triple_sat (GZL_div (GZL ps n) n) (xs[n := t])\"\n  proof (rule pol_sat_GZL_product_has_solution, goal_cases)\n    case 1\n    thus ?case\n    using assms(1,2)\n    by (auto simp: GZL_div_def GZL_def G_def Z_def L_def pol_div_def\n                   ineq_div_def list_div_def split: ineq.splits)\n  qed (use assms in \\<open>auto simp: FM_def\\<close>)\n  then obtain t where t: \"triple_sat (GZL_div (GZL ps n) n) (xs[n := t])\"\n    by blast\n  also have \"?this \\<longleftrightarrow> triple_sat (GZL ps n) (xs[n := t])\"\n    by (rule triple_sat_GZL_div)\n       (use assms in \\<open>auto simp: GZL_def G_def Z_def L_def split: ineq.splits\\<close>)\n  also have \"\\<dots> \\<longleftrightarrow> pol_sat ps (xs[n := t])\"\n    by simp\n  finally show ?thesis ..\nqed\n\ntheorem FM_sat_equivalent:\n  assumes \"\\<forall>p \\<in> set ps. (case p of (ineq cs k) \\<Rightarrow> length cs = length xs)\" \"n < length xs\"\n  shows \"pol_sat (FM ps n) xs \\<longleftrightarrow> (\\<exists>t. pol_sat ps (xs[n := t]))\"\n  using FM_sat_has_solution FM_preserves_solution assms\n  by blast\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/fourier-motzkin-elimination/isabelle/eberlm/Submission.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8633916099737806, "lm_q2_score": 0.8267117898012105, "lm_q1q2_score": 0.7137760231807728}}
{"text": "(* Author: Tobias Nipkow, Max Haslbeck *)\n\nsubsection \"The Variables in an Expression\"\n\ntheory Vars imports Com\nbegin\n\n\ntext\\<open>We need to collect the variables in both arithmetic and boolean\nexpressions. For a change we do not introduce two functions, e.g.\\ \\<open>avars\\<close> and \\<open>bvars\\<close>, but we overload the name \\<open>vars\\<close>\nvia a \\emph{type class}, a device that originated with Haskell:\\<close>\n \nclass vars =\nfixes vars :: \"'a \\<Rightarrow> vname set\"\n\ntext\\<open>This defines a type class ``vars'' with a single\nfunction of (coincidentally) the same name. Then we define two separated\ninstances of the class, one for @{typ aexp} and one for @{typ bexp}:\\<close>\n\ninstantiation aexp :: vars\nbegin\n\nfun vars_aexp :: \"aexp \\<Rightarrow> vname set\" where\n\"vars (N n) = {}\" |\n\"vars (V x) = {x}\" |\n\"vars (Plus a\\<^sub>1 a\\<^sub>2) = vars a\\<^sub>1 \\<union> vars a\\<^sub>2\"  |\n\"vars (Times a\\<^sub>1 a\\<^sub>2) = vars a\\<^sub>1 \\<union> vars a\\<^sub>2\"  |\n\"vars (Div a\\<^sub>1 a\\<^sub>2) = vars a\\<^sub>1 \\<union> vars a\\<^sub>2\" \n\ninstance ..\n\nend\n\nvalue \"vars (Plus (V ''x'') (V ''y''))\"\n\ninstantiation bexp :: vars\nbegin\n\nfun vars_bexp :: \"bexp \\<Rightarrow> vname set\" where\n\"vars (Bc v) = {}\" |\n\"vars (Not b) = vars b\" |\n\"vars (And b\\<^sub>1 b\\<^sub>2) = vars b\\<^sub>1 \\<union> vars b\\<^sub>2\" |\n\"vars (Less a\\<^sub>1 a\\<^sub>2) = vars a\\<^sub>1 \\<union> vars a\\<^sub>2\"\n\ninstance ..\n\nend\n\nvalue \"vars (Less (Plus (V ''z'') (V ''y'')) (V ''x''))\"\n\nabbreviation\n  eq_on :: \"('a \\<Rightarrow> 'b) \\<Rightarrow> ('a \\<Rightarrow> 'b) \\<Rightarrow> 'a set \\<Rightarrow> bool\"\n (\"(_ =/ _/ on _)\" [50,0,50] 50) where\n\"f = g on X == \\<forall> x \\<in> X. f x = g x\"\n\nlemma aval_eq_if_eq_on_vars[simp]:\n  \"s\\<^sub>1 = s\\<^sub>2 on vars a \\<Longrightarrow> aval a s\\<^sub>1 = aval a s\\<^sub>2\"\napply(induction a)\napply simp_all\ndone          \n\nlemma bval_eq_if_eq_on_vars:\n  \"s\\<^sub>1 = s\\<^sub>2 on vars b \\<Longrightarrow> bval b s\\<^sub>1 = bval b s\\<^sub>2\"\nproof(induction b)\n  case (Less a1 a2)\n  hence \"aval a1 s\\<^sub>1 = aval a1 s\\<^sub>2\" and \"aval a2 s\\<^sub>1 = aval a2 s\\<^sub>2\" by simp_all\n  thus ?case by simp\nqed simp_all\n\n \n\nfun lvars :: \"com \\<Rightarrow> vname set\" where\n\"lvars SKIP = {}\" |\n\"lvars (x::=e) = {x}\" |\n\"lvars (c1;;c2) = lvars c1 \\<union> lvars c2\" |\n\"lvars (IF b THEN c1 ELSE c2) = lvars c1 \\<union> lvars c2\" |\n\"lvars (WHILE b DO c) = lvars c\"\n\nfun rvars :: \"com \\<Rightarrow> vname set\" where\n\"rvars SKIP = {}\" |\n\"rvars (x::=e) = vars e\" |\n\"rvars (c1;;c2) = rvars c1 \\<union> rvars c2\" |\n\"rvars (IF b THEN c1 ELSE c2) = vars b \\<union> rvars c1 \\<union> rvars c2\" |\n\"rvars (WHILE b DO c) = vars b \\<union> rvars c\"\n\ninstantiation com :: vars\nbegin\n\ndefinition \"vars_com c = lvars c \\<union> rvars c\"\n\ninstance ..\n\nend\n\nlemma vars_com_simps[simp]:\n  \"vars SKIP = {}\"\n  \"vars (x::=e) = {x} \\<union> vars e\"\n  \"vars (c1;;c2) = vars c1 \\<union> vars c2\"\n  \"vars (IF b THEN c1 ELSE c2) = vars b \\<union> vars c1 \\<union> vars c2\"\n  \"vars (WHILE b DO c) = vars b \\<union> vars c\"\nby(auto simp: vars_com_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/Hoare_Time/Vars.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8633916029436189, "lm_q2_score": 0.8267117940706734, "lm_q1q2_score": 0.7137760210550738}}
{"text": "theory hw08\n  imports Complex_Main \"HOL-Library.Tree\"\nbegin\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\nlemma f_alt_induct [consumes 1, case_names 1 2 rec]:\n  assumes \"n > 0\"\n      and \"P (Suc 0)\" \"P 2\" \"\\<And>n. n > 0 \\<Longrightarrow> P n \\<Longrightarrow> P (Suc n) \\<Longrightarrow> P (Suc (Suc n))\"\n  shows   \"P n\"\n  using assms(1)\nproof (induction n rule: fib.induct)\n  case (3 n)\n  thus ?case using assms by (cases n) (auto simp: eval_nat_numeral)\nqed (auto simp: \\<open>P (Suc 0)\\<close> \\<open>P 2\\<close>)\n\nlemma fib_lowerbound: \"n > 0 \\<Longrightarrow> real (fib n) \\<ge> 1.5 ^ n / 3\"\nproof (induction n rule: f_alt_induct)\ncase 1\nthen show ?case by auto\nnext\n  case 2\n  then show ?case by (auto simp:eval_nat_numeral)\nnext\n  case (rec n)\n  then show ?case by auto\nqed\n\n\n\n\nfun avl :: \"'a tree \\<Rightarrow> bool\"\nwhere\n  \"avl (Node l _ r) = ((((height r::int) -(height l::int))\\<in> {-1..1})\\<and> avl l \\<and> avl r)\"\n| \"avl (Leaf) = True\"\n\nvalue \"avl \\<langle>\\<langle>\\<rangle>,a,\\<langle>\\<langle>\\<rangle>,a,\\<langle>\\<langle>\\<rangle>,a,\\<langle>\\<rangle>\\<rangle>\\<rangle>\\<rangle>\"\n\nfun avl_minnodes_height::\"nat \\<Rightarrow> nat\"\n  where\n  \"avl_minnodes_height 0 = 1\"\n| \"avl_minnodes_height (Suc 0) = 2\"\n| \"avl_minnodes_height (Suc (Suc n)) = avl_minnodes_height n + avl_minnodes_height (Suc n)\"\n\n\nvalue \"height \\<langle>\\<langle>\\<rangle>,a,\\<langle>\\<langle>\\<rangle>,a,\\<langle>\\<rangle>\\<rangle>\\<rangle>\"\nvalue \"size1 \\<langle>\\<langle>\\<rangle>,a,\\<langle>\\<langle>\\<rangle>,a,\\<langle>\\<rangle>\\<rangle>\\<rangle>\"\n\nvalue \"height \\<langle>\\<langle>\\<rangle>,a,\\<langle>\\<rangle>\\<rangle>\"\nvalue \"size1  \\<langle>\\<langle>\\<rangle>,a,\\<langle>\\<rangle>\\<rangle>\"\n\nvalue \"height \\<langle>\\<rangle>\"\nvalue \"size1  \\<langle>\\<rangle>\"\n\nvalue \"height \\<langle>\\<langle>\\<langle>\\<rangle>,a,\\<langle>\\<rangle>\\<rangle>,a,\\<langle>\\<langle>\\<rangle>,a,\\<langle>\\<rangle>\\<rangle>\\<rangle>\"\nvalue \"size1 \\<langle>\\<langle>\\<langle>\\<rangle>,a,\\<langle>\\<rangle>\\<rangle>,a,\\<langle>\\<langle>\\<rangle>,a,\\<langle>\\<rangle>\\<rangle>\\<rangle>\"\nvalue \"avl \\<langle>\\<langle>\\<langle>\\<rangle>,a,\\<langle>\\<rangle>\\<rangle>,a,\\<langle>\\<langle>\\<rangle>,a,\\<langle>\\<rangle>\\<rangle>\\<rangle>\"\n\nlemma avl_size: \" size1 (Node t1 x t2) = size1 t1 + size1 t2\"\n  by simp\n\nlemma avl_min_mono: \"avl_minnodes_height n \\<le> avl_minnodes_height (Suc n)\"\n  apply(induction n rule: avl_minnodes_height.induct)\n    apply(auto)\n  done\n\n\nlemma min_corr: \"avl t \\<Longrightarrow> height t = h \\<Longrightarrow> avl_minnodes_height h  \\<le> size1 t\"\nproof(induction t arbitrary:h)\n  case Leaf\n  then show ?case by auto\nnext\n  case (Node t1 x2 t2)\n  note IH = Node.IH[OF _ refl]\n    have \"height t1 = height t2 \\<or> height t1 < height t2 \\<or> height t1 > height t2\" (is \"?C1 \\<or> ?C2 \\<or> ?C3\")\n    by auto\n  moreover {\n    assume ?C1\n    have ?case using IH Node.prems \\<open>?C1\\<close>\n      apply (cases \"height t2\")\n       apply (auto)\n      by (meson add_mono_thms_linordered_semiring(1) avl_min_mono le_trans)\n\n  } moreover {\n    assume ?C2 \n    have \"h = Suc (height t2)\" using IH Node.prems  using \\<open>?C2\\<close> by force\n    then  have ?case using IH Node.prems \\<open>?C2\\<close>\n      apply (cases \"height t2\")\n       apply (auto)\n      by (simp add: le_less_Suc_eq)\n      \n  } moreover {\n    assume ?C3 \n     have \"h = Suc (height t1)\" using IH Node.prems  using \\<open>?C3\\<close> by force\n    then  have ?case using IH Node.prems \\<open>?C3\\<close>\n      apply (cases \"height t1\")\n       apply (auto)\n      by (simp add: le_less_Suc_eq)\n  } ultimately show ?case by blast\n \nqed\n\n  \n\n\nlemma fib_min: \"fib (h+2)  = avl_minnodes_height h\"\n  apply(induction h rule:avl_minnodes_height.induct)\n    apply(auto)\n  done\n\nlemma avl_fib_bound: \"avl t \\<Longrightarrow> height t = h \\<Longrightarrow> fib (h+2) \\<le> size1 t\"\n  using fib_min le_trans min_corr by metis\n  \n\n\nlemma avl_lowerbound:\n  assumes \"avl t\"\n  shows \"1.5 ^ (height t + 2) / 3 \\<le> real (size1 t)\"\nproof -\n  show ?thesis using assms fib_min le_trans min_corr fib_lowerbound\n    by (smt add_gr_0 avl_fib_bound of_nat_le_iff pos2)\nqed\n\n\n\n\n\n\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/08/hw08.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711642563824, "lm_q2_score": 0.8397339696776499, "lm_q1q2_score": 0.7137496598725458}}
{"text": "section \\<open>Flows, Cuts, and Networks\\<close>\ntheory Network\nimports Graph\nbegin\ntext \\<open>\n  In this theory, we define the basic concepts of flows, cuts, \n  and (flow) networks.\n  \\<close>  \n\nsubsection \\<open>Definitions\\<close>\n\nsubsubsection \\<open>Flows\\<close>\n\ntext \\<open>An \\<open>s\\<close>-\\<open>t\\<close> preflow on a graph is a labeling of the edges with \n  values from a linearly ordered integral domain, such that: \n  \\begin{description}\n    \\item[capacity constraint] the flow on each edge is non-negative and \n      does not exceed the edge's capacity;\n    \\item[non-deficiency constraint] for all nodes except \\<open>s\\<close> and \\<open>t\\<close>, \n      the incoming flow greater or equal to the outgoing flow.\n  \\end{description}    \n\\<close>\n  \ntype_synonym 'capacity flow = \"edge \\<Rightarrow> 'capacity\"\n\nlocale Preflow = Graph c for c :: \"'capacity::linordered_idom graph\" +\n  fixes s t :: node\n  fixes f :: \"'capacity flow\"  \n  (* TODO: Move \\<forall>-quantifiers to meta-level!? *)\n  assumes capacity_const: \"\\<forall>e. 0 \\<le> f e \\<and> f e \\<le> c e\"\n  assumes no_deficient_nodes: \"\\<forall>v \\<in> V-{s,t}.\n    (\\<Sum>e\\<in>outgoing v. f e) \\<le> (\\<Sum>e\\<in>incoming v. f e)\" \nbegin\nend  \n  \n  \ntext \\<open>An \\<open>s\\<close>-\\<open>t\\<close> \\<^emph>\\<open>flow\\<close> on a graph is a preflow that has no active nodes except \n  source and sink, where a node is \\<^emph>\\<open>active\\<close> iff it has more incoming flow \n  than outgoing flow.\n\\<close>\n\nlocale Flow = Preflow c s t f\n  for c :: \"'capacity::linordered_idom graph\"\n  and s t :: node\n  and f +\n  assumes no_active_nodes: \n    \"\\<forall>v \\<in> V - {s,t}. (\\<Sum>e\\<in>outgoing v. f e) \\<ge> (\\<Sum>e\\<in>incoming v. f e)\"\nbegin\n  text \\<open>For a flow, inflow equals outflow for all nodes except sink and source.\n    This is called \\<^emph>\\<open>conservation\\<close>. \\<close>\n  lemma conservation_const: \n    \"\\<forall>v \\<in> V - {s, t}. (\\<Sum>e \\<in> incoming v. f e) = (\\<Sum>e \\<in> outgoing v. f e)\"\n    using no_deficient_nodes no_active_nodes \n    by force\n  \n  text \\<open>The value of a flow is the flow that leaves $s$ and does not return.\\<close>\n  definition val :: \"'capacity\"\n    where \"val \\<equiv> (\\<Sum>e \\<in> outgoing s. f e) - (\\<Sum>e \\<in> incoming s. f e)\"\nend\n\nlocale Finite_Preflow = Preflow c s t f + Finite_Graph c \n  for c :: \"'capacity::linordered_idom graph\" and s t f\n  \nlocale Finite_Flow = Flow c s t f + Finite_Preflow c s t f\n  for c :: \"'capacity::linordered_idom graph\" and s t f\n\n\nsubsubsection \\<open>Cuts\\<close>\ntext \\<open>A \\<^emph>\\<open>cut\\<close> is a partitioning of the nodes into two sets. \n  We define it by just specifying one of the partitions. \n  The other partition is implicitly given by the remaining nodes.\\<close>\ntype_synonym cut = \"node set\" \n\nlocale Cut = Graph +  (* TODO: We probably do not need the cut-locale, \n  only NCut.*)\n  fixes k :: cut\n  assumes cut_ss_V: \"k \\<subseteq> V\"\n\nsubsubsection \\<open>Networks\\<close>\ntext \\<open>A \\<^emph>\\<open>network\\<close> is a finite graph with two distinct nodes, source and sink, \n  such that all edges are labeled with positive capacities. \n  Moreover, we assume that \n  \\<^item> The source has no incoming edges, and the sink has no outgoing edges.\n  \\<^item> There are no parallel edges, i.e., for any edge, the reverse edge must not be in the network.\n  \\<^item> Every node must lay on a path from the source to the sink.\n\n  Notes on the formalization\n  \\<^item> We encode the graph by a mapping \\<open>c\\<close>, such that \\<open>c (u,v)\\<close> is \n    the capacity of edge \\<open>(u,v)\\<close>, or \\<open>0\\<close>, if there is no edge from \\<open>u\\<close> to \\<open>v\\<close>.\n    Thus, in the formalization below, we only demand \n    that \\<open>c (u,v) \\<ge> 0\\<close> for all \\<open>u\\<close> and \\<open>v\\<close>.\n  \\<^item> We only demand the set of nodes reachable from the source to be finite.\n    Together with the constraint that all nodes lay on a path from the source,\n    this implies that the graph is finite.\n\\<close>\n\nlocale Network = Graph c for c :: \"'capacity::linordered_idom graph\" +\n  fixes s t :: node\n  assumes s_node[simp, intro!]: \"s \\<in> V\"\n  assumes t_node[simp, intro!]: \"t \\<in> V\"\n  assumes s_not_t[simp, intro!]: \"s \\<noteq> t\"\n    \n  assumes cap_non_negative: \"\\<forall>u v. c (u, v) \\<ge> 0\"\n  assumes no_incoming_s: \"\\<forall>u. (u, s) \\<notin> E\"\n  assumes no_outgoing_t: \"\\<forall>u. (t, u) \\<notin> E\"\n  assumes no_parallel_edge: \"\\<forall>u v. (u, v) \\<in> E \\<longrightarrow> (v, u) \\<notin> E\"\n  assumes nodes_on_st_path: \"\\<forall>v \\<in> V. connected s v \\<and> connected v t\"\n  assumes finite_reachable: \"finite (reachableNodes s)\"\nbegin\n  text \\<open>Edges have positive capacity\\<close>\n  lemma edge_cap_positive: \"(u,v)\\<in>E \\<Longrightarrow> c (u,v) > 0\"\n    unfolding E_def using cap_non_negative[THEN spec2, of u v] by simp\n  \n  text \\<open>The network constraints implies that all nodes are \n    reachable from the source node\\<close>  \n  lemma reachable_is_V[simp]: \"reachableNodes s = V\"\n  proof\n    show \"V \\<subseteq> reachableNodes s\"\n    unfolding reachableNodes_def using s_node nodes_on_st_path\n      by auto\n  qed (simp add: reachable_ss_V)\n  \n  text \\<open>Thus, the network is actually a finite graph.\\<close>\n  sublocale Finite_Graph \n    apply unfold_locales\n    using reachable_is_V finite_reachable by auto\n      \n  \n  text \\<open>Our assumptions imply that there are no self loops\\<close>\n  lemma no_self_loop: \"\\<forall>u. (u, u) \\<notin> E\"\n    using no_parallel_edge by auto\n\n  lemma adjacent_not_self[simp, intro!]: \"v \\<notin> adjacent_nodes v\"\n    unfolding adjacent_nodes_def using no_self_loop \n    by auto\n    \n\n  text \\<open>A flow is maximal, if it has a maximal value\\<close>  \n  definition isMaxFlow :: \"_ flow \\<Rightarrow> bool\" \n  where \"isMaxFlow f \\<equiv> Flow c s t f \\<and> \n    (\\<forall>f'. Flow c s t f' \\<longrightarrow> Flow.val c s f' \\<le> Flow.val c s f)\"\n    \n  definition \"is_max_flow_val fv \\<equiv> \\<exists>f. isMaxFlow f \\<and> fv=Flow.val c s f\"\n\n(* TODO: Can we prove existence of a maximum flow *easily*, i.e.,\n  without going over the min-cut-max-flow theorem or the Ford-Fulkerson method?\n  definition \"max_flow_val \\<equiv> THE fv. is_max_flow_val fv\"\n*)  \n    \n  lemma t_not_s[simp]: \"t \\<noteq> s\" using s_not_t by blast\n\n      \n  text \\<open>The excess of a node is the difference between incoming and \n    outgoing flow.\\<close> (* TODO: Define in context of preflow!? *)\n  definition excess :: \"'capacity flow \\<Rightarrow> node \\<Rightarrow> 'capacity\" where\n    \"excess f v \\<equiv> (\\<Sum>e\\<in>incoming v. f e) - (\\<Sum>e\\<in>outgoing v. f e)\"\n  \nend  \n  \nsubsubsection \\<open>Networks with Flows and Cuts\\<close>  \ntext \\<open>For convenience, we define locales for a network with a fixed flow,\n  and a network with a fixed cut\\<close>\n\nlocale NPreflow = Network c s t + Preflow c s t f \n  for c :: \"'capacity::linordered_idom graph\" and s t f\nbegin\n  \nend\n    \nlocale NFlow = NPreflow c s t f + Flow c s t f \n  for c :: \"'capacity::linordered_idom graph\" and s t f\n\nlemma (in Network) isMaxFlow_alt: \n  \"isMaxFlow f \\<longleftrightarrow> NFlow c s t f \\<and> \n    (\\<forall>f'. NFlow c s t f' \\<longrightarrow> Flow.val c s f' \\<le> Flow.val c s f)\"\n  unfolding isMaxFlow_def     \n  by (auto simp: NFlow_def Flow_def NPreflow_def) intro_locales  \n\ntext \\<open>A cut in a network separates the source from the sink\\<close>\nlocale NCut = Network c s t + Cut c k \n  for c :: \"'capacity::linordered_idom graph\" and s t k +\n  assumes s_in_cut: \"s \\<in> k\"\n  assumes t_ni_cut: \"t \\<notin> k\"\nbegin\n  text \\<open>The capacity of the cut is the capacity of all edges going from the \n    source's side to the sink's side.\\<close>\n  definition cap :: \"'capacity\"\n    where \"cap \\<equiv> (\\<Sum>e \\<in> outgoing' k. c e)\"\nend\n\ntext \\<open>A minimum cut is a cut with minimum capacity.\\<close> \n(* TODO: The definitions of min-cut and max-flow are done in different contexts. \n  Align, probably both in network context! *)\ndefinition isMinCut :: \"_ graph \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> cut \\<Rightarrow> bool\" \nwhere \"isMinCut c s t k \\<equiv> NCut c s t k \\<and>\n  (\\<forall>k'. NCut c s t k' \\<longrightarrow> NCut.cap c k \\<le> NCut.cap c k')\"\n\nsubsection \\<open>Properties\\<close>\nsubsubsection \\<open>Flows\\<close>\n\ncontext Preflow \nbegin\n\ntext \\<open>Only edges are labeled with non-zero flows\\<close>\nlemma zero_flow_simp[simp]:\n  \"(u,v)\\<notin>E \\<Longrightarrow> f(u,v) = 0\"\n  by (metis capacity_const eq_iff zero_cap_simp)\n\nlemma f_non_negative: \"0 \\<le> f e\"\n  using capacity_const by (cases e) auto\n    \nlemma sum_f_non_negative: \"sum f X \\<ge> 0\" using capacity_const\n  by (auto simp: sum_nonneg f_non_negative) \n    \nend \\<comment> \\<open>Preflow\\<close>   \n    \ncontext Flow\nbegin\ntext \\<open>We provide a useful equivalent formulation of the \n  conservation constraint.\\<close>\nlemma conservation_const_pointwise: \n  assumes \"u\\<in>V - {s,t}\"\n  shows \"(\\<Sum>v\\<in>E``{u}. f (u,v)) = (\\<Sum>v\\<in>E\\<inverse>``{u}. f (v,u))\"\n  using conservation_const assms\n  by (auto simp: sum_incoming_pointwise sum_outgoing_pointwise)\n\ntext \\<open>The value of the flow is bounded by the capacity of the \n  outgoing edges of the source node\\<close>\nlemma val_bounded: \n  \"-(\\<Sum>e\\<in>incoming s. c e) \\<le> val\"\n  \"val \\<le> (\\<Sum>e\\<in>outgoing s. c e)\"\nproof -\n  have \n    \"sum f (outgoing s) \\<le> sum c (outgoing s)\"\n    \"sum f (incoming s) \\<le> sum c (incoming s)\"\n    using capacity_const by (auto intro!: sum_mono)\n  thus \"-(\\<Sum>e\\<in>incoming s. c e) \\<le> val\" \"val \\<le> (\\<Sum>e\\<in>outgoing s. c e)\" \n    using sum_f_non_negative[of \"incoming s\"] \n    using sum_f_non_negative[of \"outgoing s\"]  \n    unfolding val_def by auto \nqed    \n    \n    \nend \\<comment> \\<open>Flow\\<close>   \n\ntext \\<open>Introduce a flow via the conservation constraint\\<close>  \nlemma (in Graph) intro_Flow:\n  assumes cap: \"\\<forall>e. 0 \\<le> f e \\<and> f e \\<le> c e\"\n  assumes cons: \"\\<forall>v \\<in> V - {s, t}. \n    (\\<Sum>e \\<in> incoming v. f e) = (\\<Sum>e \\<in> outgoing v. f e)\"\n  shows \"Flow c s t f\"  \n  using assms by unfold_locales auto  \n  \ncontext Finite_Preflow \nbegin\n\ntext \\<open>The summation of flows over incoming/outgoing edges can be \n  extended to a summation over all possible predecessor/successor nodes,\n  as the additional flows are all zero.\\<close>  \nlemma sum_outgoing_alt_flow:\n  fixes g :: \"edge \\<Rightarrow> 'capacity\"\n  assumes \"u\\<in>V\"\n  shows \"(\\<Sum>e\\<in>outgoing u. f e) = (\\<Sum>v\\<in>V. f (u,v))\"\n  apply (subst sum_outgoing_alt)\n  using assms capacity_const\n  by auto\n  \nlemma sum_incoming_alt_flow:\n  fixes g :: \"edge \\<Rightarrow> 'capacity\"\n  assumes \"u\\<in>V\"\n  shows \"(\\<Sum>e\\<in>incoming u. f e) = (\\<Sum>v\\<in>V. f (v,u))\"\n  apply (subst sum_incoming_alt)\n  using assms capacity_const\n  by auto\nend \\<comment> \\<open>Finite Preflow\\<close>   \n\nsubsubsection \\<open>Networks\\<close>  \ncontext Network\nbegin\n  \nlemmas [simp] = no_incoming_s no_outgoing_t\n  \nlemma incoming_s_empty[simp]: \"incoming s = {}\"\n  unfolding incoming_def using no_incoming_s by auto\n  \nlemma outgoing_t_empty[simp]: \"outgoing t = {}\"\n  unfolding outgoing_def using no_outgoing_t by auto\n  \n  \nlemma cap_positive: \"e \\<in> E \\<Longrightarrow> c e > 0\"\n  unfolding E_def using cap_non_negative le_neq_trans by fastforce \n\nlemma V_not_empty: \"V\\<noteq>{}\" using s_node by auto\nlemma E_not_empty: \"E\\<noteq>{}\" using V_not_empty by (auto simp: V_def)\n    \nlemma card_V_ge2: \"card V \\<ge> 2\"\nproof -\n  have \"2 = card {s,t}\" by auto\n  also have \"{s,t} \\<subseteq> V\" by auto\n  hence \"card {s,t} \\<le> card V\" by (rule_tac card_mono) auto\n  finally show ?thesis .   \nqed  \n    \n\n\nlemma max_flow_val_unique: \n  \"\\<lbrakk>is_max_flow_val fv1; is_max_flow_val fv2\\<rbrakk> \\<Longrightarrow> fv1=fv2\"    \n  unfolding is_max_flow_val_def isMaxFlow_def \n  by (auto simp: antisym)\n  \nend \\<comment> \\<open>Network\\<close>\n\nsubsubsection \\<open>Networks with Flow\\<close>\n\ncontext NPreflow \nbegin\n\nsublocale Finite_Preflow by unfold_locales\n\ntext \\<open>As there are no edges entering the source/leaving the sink, \n  also the corresponding flow values are zero:\\<close>\nlemma no_inflow_s: \"\\<forall>e \\<in> incoming s. f e = 0\" (is ?thesis)\nproof (rule ccontr)\n  assume \"\\<not>(\\<forall>e \\<in> incoming s. f e = 0)\"\n  then obtain e where obt1: \"e \\<in> incoming s \\<and> f e \\<noteq> 0\" by blast\n  then have \"e \\<in> E\" using incoming_def by auto\n  thus \"False\" using obt1 no_incoming_s incoming_def by auto\nqed\n  \nlemma no_outflow_t: \"\\<forall>e \\<in> outgoing t. f e = 0\"\nproof (rule ccontr)\n  assume \"\\<not>(\\<forall>e \\<in> outgoing t. f e = 0)\"\n  then obtain e where obt1: \"e \\<in> outgoing t \\<and> f e \\<noteq> 0\" by blast\n  then have \"e \\<in> E\" using outgoing_def by auto\n  thus \"False\" using obt1 no_outgoing_t outgoing_def by auto\nqed\n\ntext \\<open>For an edge, there is no reverse edge, and thus, \n  no flow in the reverse direction:\\<close>\nlemma zero_rev_flow_simp[simp]: \"(u,v)\\<in>E \\<Longrightarrow> f(v,u) = 0\"\n  using no_parallel_edge by auto\n\n    \nlemma excess_non_negative: \"\\<forall>v\\<in>V-{s,t}. excess f v \\<ge> 0\"\n  unfolding excess_def using no_deficient_nodes by auto\n  \nlemma excess_nodes_only: \"excess f v > 0 \\<Longrightarrow> v \\<in> V\"  \n  unfolding excess_def incoming_def outgoing_def V_def \n  using sum.not_neutral_contains_not_neutral by fastforce\n  \nlemma excess_non_negative': \"\\<forall>v \\<in> V - {s}. excess f v \\<ge> 0\"\nproof -\n  have \"excess f t \\<ge> 0\" unfolding excess_def outgoing_def \n    by (auto simp: capacity_const sum_nonneg)\n  thus ?thesis using excess_non_negative by blast\nqed \n\nlemma excess_s_non_pos: \"excess f s \\<le> 0\"\n  unfolding excess_def\n  by (simp add: capacity_const sum_nonneg)  \n    \nend \\<comment> \\<open>Network with preflow\\<close>\n\ncontext NFlow begin  \n  sublocale Finite_Preflow by unfold_locales\n      \n  text \\<open>There is no outflow from the sink in a network. \n    Thus, we can simplify the definition of the value:\\<close>  \n  corollary val_alt: \"val = (\\<Sum>e \\<in> outgoing s. f e)\"\n    unfolding val_def by (auto simp: no_inflow_s)\n      \nend  \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/Network.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8519528170040852, "lm_q2_score": 0.8376199673867852, "lm_q1q2_score": 0.7136126907940417}}
{"text": "(*  Title:       LogisticFunction.thy\n    Author:      Filip Smola, 2019-2021\n*)\n\ntheory LogisticFunction\n  imports HyperdualFunctionExtension\nbegin\n\nsubsection\\<open>Logistic Function\\<close>\n\ntext\\<open>Define the standard logistic function and its hyperdual variant:\\<close>\ndefinition logistic :: \"real \\<Rightarrow> real\"\n  where \"logistic x = inverse (1 + exp (-x))\"\ndefinition hyp_logistic :: \"real hyperdual \\<Rightarrow> real hyperdual\"\n  where \"hyp_logistic x = inverse (1 + (*h* exp) (-x))\"\n\ntext\\<open>Hyperdual extension of the logistic function is its hyperdual variant:\\<close>\nlemma hypext_logistic:\n  \"(*h* logistic) x = hyp_logistic x\"\nproof -\n  have \"(*h* (\\<lambda>x. exp (- x) + 1)) x = (*h* exp) (- x) + of_comp 1\"\n    by (simp add: hypext_compose hypext_uminus hypext_fun_cadd twice_field_differentiable_at_compose)\n  then have \"(*h* (\\<lambda>x. 1 + exp (- x))) x = 1 + (*h* exp) (- x)\"\n    by (simp add: one_hyperdual_def add.commute)\n  moreover have \"1 + exp (- Base x) \\<noteq> 0\"\n    by (metis exp_ge_zero add_eq_0_iff neg_0_le_iff_le not_one_le_zero)\n  moreover have \"(\\<lambda>x. 1 + exp (- x)) twice_field_differentiable_at Base x\"\n  proof -\n    have \"(\\<lambda>x. exp (- x)) twice_field_differentiable_at Base x\"\n      by (simp add: twice_field_differentiable_at_compose)\n    then have \"(\\<lambda>x. exp (- x) + 1) twice_field_differentiable_at Base x\"\n      using twice_field_differentiable_at_compose[of \"\\<lambda>x. exp (- x)\" \"Base x\" \"\\<lambda>x. x + 1\"]\n      by simp\n    then show ?thesis\n      by (simp add: add.commute)\n  qed\n  ultimately have \"(*h* (\\<lambda>x. inverse (1 + exp (- x)))) x = inverse (1 + (*h* exp) (- x))\"\n    by (simp add: hypext_fun_inverse)\n  then show ?thesis\n    unfolding logistic_def hyp_logistic_def .\nqed\n\ntext\\<open>From properties of autodiff we know it gives us the derivative:\\<close>\nlemma \"Eps1 (hyp_logistic (\\<beta> x)) = deriv logistic x\"\n  by (metis Eps1_hypext hypext_logistic)\ntext\\<open>which is equal to the known derivative of the standard logistic function:\\<close>\nlemma \"First (autodiff logistic x) = exp (- x) / (1 + exp (- x)) ^ 2\"\n  (* Move to hyperdual variant: *)\n  apply (simp only: autodiff.simps hyperdual_to_derivs.simps derivs.sel hypext_logistic)\n  (* Unfold extensions of functions that have a hyperdual variant (all except exp): *)\n  apply (simp only: hyp_logistic_def inverse_hyperdual.code hyperdual.sel)\n  (* Finish by expanding the extension of exp and hyperdual computations: *)\n  apply (simp add: hyperdualx_def hypext_exp_Hyperdual hyperdual_bases)\n  done\n\ntext\\<open>Similarly we can get the second derivative:\\<close>\nlemma \"Second (autodiff logistic x) = deriv (deriv logistic) x\"\n  by (rule autodiff_extract_second)\ntext\\<open>and derive its value:\\<close>\nlemma \"Second (autodiff logistic x) = ((exp (- x) - 1) * exp (- x)) / ((1 + exp (- x)) ^ 3)\"\n  (* Move to hyperdual variant: *)\n  apply (simp only: autodiff.simps hyperdual_to_derivs.simps derivs.sel hypext_logistic)\n  (* Unfold extensions of functions that have a hyperdual variant (all except exp): *)\n  apply (simp only: hyp_logistic_def inverse_hyperdual.code hyperdual.sel)\n  (* Finish by expanding the extension of exp and hyperdual computations: *)\n  apply (simp add: hyperdualx_def hypext_exp_Hyperdual hyperdual_bases)\n  (* Simplify the resulting expression: *)\nproof -\n  have\n    \"2 * (exp (- x) * exp (- x)) / (1 + exp (- x)) ^ 3 - exp (- x) / (1 + exp (- x)) ^ 2 =\n     (2 * exp (- x) / (1 + exp (- x)) ^ 3 - 1 / (1 + exp (- x)) ^ 2) * exp (- x)\"\n    by (simp add: field_simps)\n  also have \"... = (2 * exp (- x) / (1 + exp (- x)) ^ 3 - (1 + exp (- x)) / (1 + exp (- x)) ^ 3) * exp (- x)\"\n  proof -\n    have \"inverse ((1 + exp (- x)) ^ 2) = inverse (1 + exp (- x)) ^ 2\"\n      by (simp add: power_inverse)\n    also have \"... = (1 + exp (- x)) * inverse (1 + exp (- x)) * inverse (1 + exp (- x)) ^ 2\"\n      by (simp add: inverse_eq_divide)\n    also have \"... = (1 + exp (- x)) * inverse (1 + exp (- x)) ^ 3\"\n      by (simp add: power2_eq_square power3_eq_cube)\n    finally have \"inverse ((1 + exp (- x)) ^ 2) = (1 + exp (- x)) * inverse ((1 + exp (- x)) ^ 3)\"\n      by (simp add: power_inverse)\n    then show ?thesis\n      by (simp add: inverse_eq_divide)\n  qed\n  also have \"... = (2 * exp (- x) - (1 + exp (- x))) / (1 + exp (- x)) ^ 3 * exp (- x)\"\n    by (metis diff_divide_distrib)\n  finally show\n    \"2 * (exp (- x) * exp (- x)) / (1 + exp (- x)) ^ 3 - exp (- x) / (1 + exp (- x))\\<^sup>2 =\n     (exp (- x) - 1) * exp (- x) / (1 + exp (- x)) ^ 3\"\n    by (simp add: field_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/Hyperdual/LogisticFunction.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.851952809486198, "lm_q2_score": 0.8376199673867852, "lm_q1q2_score": 0.7136126844969092}}
{"text": "theory Cyclic_Group_Ext imports\n  CryptHOL.CryptHOL\n  \"HOL-Number_Theory.Cong\"\nbegin\n\ncontext cyclic_group begin\n\nlemma generator_pow_order: \"\\<^bold>g [^] order G = \\<one>\"\nproof(cases \"order G > 0\")\n  case True\n  hence fin: \"finite (carrier G)\" by(simp add: order_gt_0_iff_finite)\n  then have [symmetric]: \"(\\<lambda>x. x \\<otimes> \\<^bold>g) ` carrier G = carrier G\"\n    by(rule endo_inj_surj)(auto simp add: inj_on_multc)\n  then have \"carrier G = (\\<lambda> n. \\<^bold>g [^] Suc n) ` {..<order G}\" \n    using fin by(simp add: carrier_conv_generator image_image)\n  then obtain n where n: \"\\<one> = \\<^bold>g [^] Suc n\" \"n < order G\" by auto\n  have \"n = order G - 1\" using n inj_onD[OF inj_on_generator, of 0 \"Suc n\"] by fastforce\n  with True n show ?thesis by auto\nqed simp\n                        \nlemma pow_generator_mod: \"\\<^bold>g [^] (k mod order G) = \\<^bold>g [^] k\"\nproof(cases \"order G > 0\")\n  case True\n  obtain n where n: \"k = n * order G + k mod order G\" by (metis div_mult_mod_eq)\n  have \"\\<^bold>g [^] k = (\\<^bold>g [^] order G) [^] n \\<otimes> \\<^bold>g [^] (k mod order G)\" \n    by(subst n)(simp add: nat_pow_mult nat_pow_pow mult_ac)\n  then show ?thesis by(simp add: generator_pow_order)\nqed simp\n\nlemma int_nat_pow: \n  assumes \"a \\<ge> 0\" \n  shows \"(\\<^bold>g [^] (int (a ::nat))) [^] (b::int)  = \\<^bold>g [^] (a*b)\"\n  using assms \nproof(cases \"a > 0\")\n  case True \n  show ?thesis\n    using int_pow_pow by blast\nnext case False\n  have \"(\\<^bold>g [^] (int (a ::nat))) [^] (b::int) = \\<one>\" using False by simp\n  also have \"\\<^bold>g [^] (a*b) = \\<one>\" using False by simp\n  ultimately show ?thesis by simp\nqed\n\nlemma pow_generator_mod_int: \"\\<^bold>g [^] ((k :: int) mod order G) = \\<^bold>g [^] k\"\nproof(cases \"order G > 0\")\n  case True\n  obtain n :: int where n: \"k = order G * n + k mod order G\" \n    by (metis div_mult_mod_eq mult.commute)\n  then have \"\\<^bold>g [^] k = \\<^bold>g [^] (order G * n) \\<otimes> \\<^bold>g [^] (k mod order G)\" \n    using int_pow_mult nat_pow_mult by (metis generator_closed)\n  then have \"\\<^bold>g [^] k = (\\<^bold>g [^] order G) [^] n \\<otimes> \\<^bold>g [^] (k mod order G)\"\n    using int_nat_pow by (simp add: int_pow_int)\n  then show ?thesis by(simp add: generator_pow_order)\nqed simp\n\n\n\nlemma pow_generator_eq_iff_cong:\n  \"finite (carrier G) \\<Longrightarrow> \\<^bold>g [^] x = \\<^bold>g [^] y \\<longleftrightarrow> [x = y] (mod order G)\"\n  by(subst (1 2) pow_generator_mod[symmetric])(auto simp add: cong_def order_gt_0_iff_finite intro: inj_onD[OF inj_on_generator])\n\nlemma cyclic_group_commute: \n  assumes \"a \\<in> carrier G\" \"b \\<in> carrier G\" \n  shows \"a \\<otimes> b = b \\<otimes> a\"\n(is \"?lhs = ?rhs\")\nproof-\n  obtain n :: nat where n: \"a = \\<^bold>g [^] n\" using generatorE assms by auto\n  also  obtain k :: nat where k: \"b = \\<^bold>g [^] k\" using generatorE assms by auto\n  ultimately have \"?lhs =  \\<^bold>g [^] n \\<otimes> \\<^bold>g [^] k\" by simp\n  then have \"... = \\<^bold>g [^] (n + k)\" by(simp add: nat_pow_mult)\n  then have \"... = \\<^bold>g [^] (k + n)\" by(simp add: add.commute)\n  then show ?thesis by(simp add: nat_pow_mult n k)\nqed\n\nlemma cyclic_group_assoc: \n  assumes \"a \\<in> carrier G\" \"b \\<in> carrier G\" \"c \\<in> carrier G\"\n  shows \"(a \\<otimes> b) \\<otimes> c = a \\<otimes> (b \\<otimes> c)\"\n(is \"?lhs = ?rhs\")\nproof-\n  obtain n :: nat where n: \"a = \\<^bold>g [^] n\" using generatorE assms by auto\n  obtain k :: nat where k: \"b = \\<^bold>g [^] k\" using generatorE assms by auto\n  obtain j :: nat where j: \"c = \\<^bold>g [^] j\" using generatorE assms by auto \n  have \"?lhs = (\\<^bold>g [^] n \\<otimes> \\<^bold>g [^] k) \\<otimes> \\<^bold>g [^] j\" using n k j by simp\n  then have \"... = \\<^bold>g [^] (n + (k + j))\" by(simp add: nat_pow_mult add.assoc)\n  then show ?thesis by(simp add: nat_pow_mult n k j)\nqed\n \nlemma l_cancel_inv: \n  assumes \"h \\<in> carrier G\" \n  shows \"(\\<^bold>g [^] (a :: nat) \\<otimes> inv (\\<^bold>g [^] a)) \\<otimes> h = h\"\n(is \"?lhs = ?rhs\")\nproof-\n  have \"?lhs = (\\<^bold>g [^] int a \\<otimes> inv (\\<^bold>g [^] int a)) \\<otimes> h\" by simp\n  then have \"... = (\\<^bold>g [^] int a \\<otimes> (\\<^bold>g [^] (- a))) \\<otimes> h\" using int_pow_neg[symmetric] by simp\n  then have \"... = \\<^bold>g [^] (int a - a)  \\<otimes> h\" by(simp add: int_pow_mult)\n  then have \"... = \\<^bold>g [^] ((0:: int)) \\<otimes> h\" by simp\n  then show ?thesis by (simp add: assms)\nqed\n\nlemma inverse_split: \n  assumes \"a \\<in> carrier G\" and \"b \\<in> carrier G\"\n  shows \"inv (a \\<otimes> b) = inv a \\<otimes> inv b\"\n  by (simp add:  assms comm_group.inv_mult cyclic_group_commute group_comm_groupI)\n\nlemma inverse_pow_pow:\n  assumes \"a \\<in> carrier G\"\n  shows \"inv (a [^] (r::nat)) = (inv a) [^] r\"\nproof -\n  have \"a [^] r \\<in> carrier G\"\n    using assms by blast\n  then show ?thesis\n    by (simp add: assms nat_pow_inv)\nqed\n\nlemma l_neq_1_exp_neq_0:\n  assumes \"l \\<in> carrier G\" \n    and \"l \\<noteq> \\<one>\" \n    and \"l = \\<^bold>g [^] (t::nat)\" \n  shows \"t \\<noteq> 0\"\nproof(rule ccontr)\n  assume \"\\<not> (t \\<noteq> 0)\"\n  hence \"t = 0\" by simp\n  hence \"\\<^bold>g [^] t = \\<one>\" by simp\n  then show \"False\" using assms by simp\nqed\n\nlemma order_gt_1_gen_not_1:\n  assumes \"order G > 1\"\n  shows \"\\<^bold>g \\<noteq> \\<one>\"\nproof(rule ccontr)\n  assume \"\\<not> \\<^bold>g \\<noteq> \\<one>\"\n  hence \"\\<^bold>g = \\<one>\" by simp\n  hence g_pow_eq_1: \"\\<^bold>g [^] n = \\<one>\" for n :: nat by simp\n  hence \"range (\\<lambda>n :: nat. \\<^bold>g [^] n) = {\\<one>}\" by auto\n  hence \"carrier G \\<subseteq> {\\<one>}\" using generator by auto\n  hence \"order G < 1\" \n    by (metis One_nat_def assms g_pow_eq_1 inj_onD inj_on_generator lessThan_iff not_gr_zero zero_less_Suc)\n  with assms show \"False\" by simp\nqed\n\nlemma power_swap: \"((\\<^bold>g [^] (\\<alpha>0::nat)) [^] (r::nat)) = ((\\<^bold>g [^] r) [^] \\<alpha>0)\"\n(is \"?lhs = ?rhs\")\nproof-\n  have \"?lhs = \\<^bold>g [^] (\\<alpha>0 * r)\" \n    using nat_pow_pow mult.commute by auto\n  hence \"... = \\<^bold>g [^] (r * \\<alpha>0)\" \n    by(metis mult.commute)\n  thus ?thesis using nat_pow_pow by auto\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/Multi_Party_Computation/Cyclic_Group_Ext.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528019683106, "lm_q2_score": 0.8376199592797929, "lm_q1q2_score": 0.7136126712930018}}
{"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  using complex_mod_triangle_ineq2[of \"w + z\" \"-z\"] by auto\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> norm c + r * m\"\n      using mult_mono[OF H th rp norm_ge_zero[of \"poly cs z\"]]\n      by (simp add: norm_mult)\n    also have \"\\<dots> \\<le> ?k\"\n      by simp\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: \"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  apply (induct p)\n  apply (simp add: offset_poly_0)\n  apply (simp add: offset_poly_pCons algebra_simps)\n  done\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: \"offset_poly p h = 0 \\<longleftrightarrow> p = 0\"\n  apply (safe intro!: offset_poly_0)\n  apply (induct p)\n  apply simp\n  apply (simp add: offset_poly_pCons)\n  apply (frule offset_poly_eq_0_lemma, simp)\n  done\n\nlemma degree_offset_poly: \"degree (offset_poly p h) = degree p\"\n  apply (induct p)\n  apply (simp add: offset_poly_0)\n  apply (case_tac \"p = 0\")\n  apply (simp add: offset_poly_0 offset_poly_pCons)\n  apply (simp add: offset_poly_pCons)\n  apply (subst degree_add_eq_right)\n  apply (rule le_less_trans [OF degree_smult_le])\n  apply (simp add: offset_poly_eq_0_iff)\n  apply (simp add: offset_poly_eq_0_iff)\n  done\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))\"\nproof (intro exI conjI)\n  show \"psize (offset_poly p a) = psize p\"\n    unfolding psize_def\n    by (simp add: offset_poly_eq_0_iff degree_offset_poly)\n  show \"\\<forall>x. poly (offset_poly p a) x = poly p (a + x)\"\n    by (simp add: poly_offset_poly)\nqed\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 - (rule power_mono, simp, simp)+\n    then have th0: \"4 * x\\<^sup>2 \\<le> 1\" \"4 * y\\<^sup>2 \\<le> 1\"\n      by (simp_all add: power_mult_distrib)\n    from add_mono[OF th0] xy show ?thesis\n      by simp\n  qed\n  then show ?thesis\n    unfolding linorder_not_le[symmetric] by blast\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 have \"\\<exists>m. n = 2 * m\"\n      by presburger\n    then obtain m where m: \"n = 2 * m\"\n      by blast\n    from n m have \"m \\<noteq> 0\" \"m < n\"\n      by presburger+\n    with IH[rule_format, of m] 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 th0: \"cmod (complex_of_real (cmod b) / b) = 1\"\n      using b by (simp add: norm_divide)\n    from unimodular_reduce_norm[OF th0] \\<open>odd n\\<close>\n    have \"\\<exists>v. cmod (complex_of_real (cmod b) / b + v^n) < 1\"\n      apply (cases \"cmod (complex_of_real (cmod b) / b + 1) < 1\")\n      apply (rule_tac x=\"1\" in exI)\n      apply simp\n      apply (cases \"cmod (complex_of_real (cmod b) / b - 1) < 1\")\n      apply (rule_tac x=\"-1\" in exI)\n      apply simp\n      apply (cases \"cmod (complex_of_real (cmod b) / b + \\<i>) < 1\")\n      apply (cases \"even m\")\n      apply (rule_tac x=\"\\<i>\" in exI)\n      apply (simp add: m power_mult)\n      apply (rule_tac x=\"- \\<i>\" in exI)\n      apply (simp add: m power_mult)\n      apply (cases \"even m\")\n      apply (rule_tac x=\"- \\<i>\" in exI)\n      apply (simp add: m power_mult)\n      apply (auto simp add: m power_mult)\n      apply (rule_tac x=\"\\<i>\" in exI)\n      apply (auto simp add: m power_mult)\n      done\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 th1: \"?w ^ n = v^n / complex_of_real (cmod b)\"\n      by (simp add: power_divide of_real_power[symmetric])\n    have th2:\"cmod (complex_of_real (cmod b) / b) = 1\"\n      using b by (simp add: norm_divide)\n    then have th3: \"cmod (complex_of_real (cmod b) / b) \\<ge> 0\"\n      by simp\n    have th4: \"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: th2)\n      done\n    from mult_left_less_imp_less[OF th4 th3]\n    have \"?P ?w n\" unfolding th1 .\n    then show ?thesis ..\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  from r[rule_format, of 0] have rp: \"r \\<ge> 0\"\n    using norm_ge_zero[of \"s 0\"] by arith\n  have th: \"\\<forall>n. r + 1 \\<ge> \\<bar>Re (s n)\\<bar>\"\n  proof\n    fix n\n    from abs_Re_le_cmod[of \"s n\"] r[rule_format, of n]\n    show \"\\<bar>Re (s n)\\<bar> \\<le> r + 1\" by arith\n  qed\n  have conv1: \"convergent (\\<lambda>n. Re (s (f n)))\"\n    apply (rule Bseq_monoseq_convergent)\n    apply (simp add: Bseq_def)\n    apply (metis gt_ex le_less_linear less_trans order.trans th)\n    apply (rule f(2))\n    done\n  have th: \"\\<forall>n. r + 1 \\<ge> \\<bar>Im (s n)\\<bar>\"\n  proof\n    fix n\n    from abs_Im_le_cmod[of \"s n\"] r[rule_format, of n]\n    show \"\\<bar>Im (s n)\\<bar> \\<le> r + 1\"\n      by arith\n  qed\n\n  have conv2: \"convergent (\\<lambda>n. Im (s (f (g n))))\"\n    apply (rule Bseq_monoseq_convergent)\n    apply (simp add: Bseq_def)\n    apply (metis gt_ex le_less_linear less_trans order.trans th)\n    apply (rule g(2))\n    done\n\n  from conv1[unfolded convergent_def] obtain x where \"LIMSEQ (\\<lambda>n. Re (s (f n))) x\"\n    by blast\n  then have x: \"\\<forall>r>0. \\<exists>n0. \\<forall>n\\<ge>n0. \\<bar>Re (s (f n)) - x\\<bar> < r\"\n    unfolding LIMSEQ_iff real_norm_def .\n\n  from conv2[unfolded convergent_def] obtain y where \"LIMSEQ (\\<lambda>n. Im (s (f (g n)))) y\"\n    by blast\n  then have y: \"\\<forall>r>0. \\<exists>n0. \\<forall>n\\<ge>n0. \\<bar>Im (s (f (g n))) - y\\<bar> < r\"\n    unfolding LIMSEQ_iff real_norm_def .\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[rule_format, OF e2] y[rule_format, OF 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      from add_strict_mono[OF N1[rule_format, OF nN1] N2[rule_format, OF nN2]]\n      show ?thesis\n        using metric_bound_lemma[of \"s (f (g n))\" ?w] by simp\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 q: \"degree q = degree p\" \"poly q x = poly p (z + x)\" for x\n  proof\n    show \"degree (offset_poly p z) = degree p\"\n      by (rule degree_offset_poly)\n    show \"\\<And>x. poly (offset_poly p z) x = poly p (z + x)\"\n      by (rule poly_offset_poly)\n  qed\n  have th: \"\\<And>w. poly q (w - z) = poly p w\"\n    using q(2)[of \"w - z\" for w] by simp\n  show ?thesis unfolding th[symmetric]\n  proof (induct q)\n    case 0\n    then show ?case\n      using ep by auto\n  next\n    case (pCons c cs)\n    from poly_bound_exists[of 1 \"cs\"]\n    obtain m where m: \"m > 0\" \"norm z \\<le> 1 \\<Longrightarrow> norm (poly cs z) \\<le> m\" for z\n      by blast\n    from ep m(1) have em0: \"e/m > 0\"\n      by (simp add: field_simps)\n    have one0: \"1 > (0::real)\"\n      by arith\n    from field_lbound_gt_zero[OF one0 em0]\n    obtain d where d: \"d > 0\" \"d < 1\" \"d < e / m\"\n      by blast\n    from d(1,3) m(1) have dm: \"d * m > 0\" \"d * m < e\"\n      by (simp_all add: field_simps)\n    show ?case\n    proof (rule ex_forward[OF field_lbound_gt_zero[OF one0 em0]], clarsimp simp add: norm_mult)\n      fix d w\n      assume H: \"d > 0\" \"d < 1\" \"d < e/m\" \"w \\<noteq> z\" \"norm (w - z) < d\"\n      then have d1: \"norm (w-z) \\<le> 1\" \"d \\<ge> 0\"\n        by simp_all\n      from H(3) m(1) have dme: \"d*m < e\"\n        by (simp add: field_simps)\n      from H have th: \"norm (w - z) \\<le> d\"\n        by simp\n      from mult_mono[OF th m(2)[OF d1(1)] d1(2) norm_ge_zero] dme\n      show \"norm (w - z) * norm (poly cs (w - z)) < e\"\n        by simp\n    qed\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 \"cmod 0 \\<le> r \\<and> cmod (poly p 0) = - (- cmod (poly p 0))\"\n      by simp\n    then have mth1: \"\\<exists>x z. cmod z \\<le> r \\<and> cmod (poly p z) = - x\"\n      by blast\n    have False if \"cmod z \\<le> r\" \"cmod (poly p z) = - x\" \"\\<not> x < 1\" for x z\n    proof -\n      from that have \"- x < 0 \"\n        by arith\n      with that(2) norm_ge_zero[of \"poly p z\"] show ?thesis\n        by simp\n    qed\n    then have mth2: \"\\<exists>z. \\<forall>x. (\\<exists>z. cmod z \\<le> r \\<and> cmod (poly p z) = - x) \\<longrightarrow> x < z\"\n      by blast\n    from real_sup_exists[OF mth1 mth2] obtain s where\n      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 blast\n    let ?m = \"- s\"\n    have s1[unfolded minus_minus]:\n      \"(\\<exists>z x. cmod z \\<le> r \\<and> - (- cmod (poly p z)) < y) \\<longleftrightarrow> ?m < y\" for y\n      using s[rule_format, of \"-y\"]\n      unfolding minus_less_iff[of y] equation_minus_iff by blast\n    from s1[of ?m] have s1m: \"\\<And>z x. cmod z \\<le> r \\<Longrightarrow> cmod (poly p z) \\<ge> ?m\"\n      by auto\n    have \"\\<exists>z. cmod z \\<le> r \\<and> cmod (poly p z) < - s + 1 / real (Suc n)\" for n\n      using s1[rule_format, of \"?m + 1/real (Suc n)\"] by simp\n    then have th: \"\\<forall>n. \\<exists>z. cmod z \\<le> r \\<and> cmod (poly p z) < - s + 1 / real (Suc n)\" ..\n    from choice[OF th] obtain g where\n        g: \"\\<forall>n. cmod (g n) \\<le> r\" \"\\<forall>n. cmod (poly p (g n)) <?m + 1 /real(Suc n)\"\n      by blast\n    from Bolzano_Weierstrass_complex_disc[OF g(1)]\n    obtain f z where fz: \"strict_mono (f :: nat \\<Rightarrow> nat)\" \"\\<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        from poly_cont[OF e2, of z p] obtain d where\n            d: \"d > 0\" \"\\<forall>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 th1: \"cmod(poly p w - poly p z) < ?e / 2\" if w: \"cmod (w - z) < d\" for w\n          using d(2)[rule_format, of w] w e by (cases \"w = z\") simp_all\n        from fz(2) d(1) obtain N1 where N1: \"\\<forall>n\\<ge>N1. cmod (g (f n) - z) < d\"\n          by blast\n        from reals_Archimedean2[of \"2/?e\"] obtain N2 :: nat where N2: \"2/?e < real N2\"\n          by blast\n        have th2: \"cmod (poly p (g (f (N1 + N2))) - poly p z) < ?e/2\"\n          using N1[rule_format, of \"N1 + N2\"] th1 by simp\n        have th0: \"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        have ath: \"m \\<le> x \\<Longrightarrow> x < m + e \\<Longrightarrow> \\<bar>x - m\\<bar> < e\" for m x e :: real\n          by arith\n        from s1m[OF g(1)[rule_format]] have th31: \"?m \\<le> cmod(poly p (g (f (N1 + N2))))\" .\n        from seq_suble[OF fz(1), of \"N1 + N2\"]\n        have th00: \"real (Suc (N1 + N2)) \\<le> real (Suc (f (N1 + N2)))\"\n          by simp\n        have th000: \"0 \\<le> (1::real)\" \"(1::real) \\<le> 1\" \"real (Suc (N1 + N2)) > 0\"\n          using N2 by auto\n        from frac_le[OF th000 th00]\n        have th00: \"?m + 1 / real (Suc (f (N1 + N2))) \\<le> ?m + 1 / real (Suc (N1 + N2))\"\n          by simp\n        from g(2)[rule_format, of \"f (N1 + N2)\"]\n        have th01:\"cmod (poly p (g (f (N1 + N2)))) < - s + 1 / real (Suc (f (N1 + N2)))\" .\n        from order_less_le_trans[OF th01 th00]\n        have th32: \"cmod (poly p (g (f (N1 + N2)))) < ?m + (1/ real(Suc (N1 + N2)))\" .\n        from N2 have \"2/?e < real (Suc (N1 + N2))\"\n          by arith\n        with 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 ath[OF th31 th32] have thc1: \"\\<bar>cmod (poly p (g (f (N1 + N2)))) - ?m\\<bar> < ?e/2\"\n          by arith\n        have ath2: \"\\<bar>a - b\\<bar> \\<le> c \\<Longrightarrow> \\<bar>b - m\\<bar> \\<le> \\<bar>a - m\\<bar> + c\" for a b c m :: real\n          by arith\n        have th22: \"\\<bar>cmod (poly p (g (f (N1 + N2)))) - cmod (poly p z)\\<bar> \\<le>\n            cmod (poly p (g (f (N1 + N2))) - poly p z)\"\n          by (simp add: norm_triangle_ineq3)\n        from ath2[OF th22, of ?m]\n        have thc2: \"2 * (?e/2) \\<le>\n            \\<bar>cmod(poly p (g (f (N1 + N2)))) - ?m\\<bar> + cmod (poly p (g (f (N1 + N2))) - poly p z)\"\n          by simp\n        from th0[OF th2 thc1 thc2] have False .\n      }\n      then have \"?e = 0\"\n        by auto\n      then have \"cmod (poly p z) = ?m\"\n        by simp\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 r0: \"r \\<le> norm z\"\n        using that by arith\n      from r[rule_format, OF r0] have th0: \"d + norm a \\<le> 1 * norm(poly (pCons c cs) z)\"\n        by arith\n      from that have z1: \"norm z \\<ge> 1\"\n        by arith\n      from order_trans[OF th0 mult_right_mono[OF z1 norm_ge_zero[of \"poly (pCons c cs) z\"]]]\n      have th1: \"d \\<le> norm(z * poly (pCons c cs) z) - norm a\"\n        unfolding norm_mult by (simp add: algebra_simps)\n      from norm_diff_ineq[of \"z * poly (pCons c cs) z\" a]\n      have th2: \"norm (z * poly (pCons c cs) z) - norm a \\<le> norm (poly (pCons a (pCons c cs)) z)\"\n        by (simp add: algebra_simps)\n      from th1 th2 show ?thesis\n        by arith\n    qed\n    then show ?thesis by blast\n  next\n    case True\n    with pCons.prems have c0: \"c \\<noteq> 0\"\n      by simp\n    have \"d \\<le> norm (poly (pCons a (pCons c cs)) z)\"\n      if h: \"(\\<bar>d\\<bar> + norm a) / norm c \\<le> norm z\" for z :: 'a\n    proof -\n      from c0 have \"norm c > 0\"\n        by simp\n      from h c0 have th0: \"\\<bar>d\\<bar> + norm a \\<le> norm (z * c)\"\n        by (simp add: field_simps norm_mult)\n      have ath: \"\\<And>mzh mazh ma. mzh \\<le> mazh + ma \\<Longrightarrow> \\<bar>d\\<bar> + ma \\<le> mzh \\<Longrightarrow> d \\<le> mazh\"\n        by arith\n      from norm_diff_ineq[of \"z * c\" a] have th1: \"norm (z * c) \\<le> norm (a + z * c) + norm a\"\n        by (simp add: algebra_simps)\n      from ath[OF th1 th0] show ?thesis\n        using True by simp\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    have ath: \"\\<And>z r. r \\<le> cmod z \\<or> cmod z \\<le> \\<bar>r\\<bar>\"\n      by arith\n    from poly_minimum_modulus_disc[of \"\\<bar>r\\<bar>\" \"pCons c cs\"]\n    obtain v where v: \"cmod (poly (pCons c cs) v) \\<le> cmod (poly (pCons c cs) w)\"\n      if \"cmod w \\<le> \\<bar>r\\<bar>\" for w\n      by blast\n    have \"cmod (poly (pCons c cs) v) \\<le> cmod (poly (pCons c cs) z)\" if z: \"r \\<le> cmod z\" for z\n      using v[of 0] r[OF z] by simp\n    with v ath[of r] show ?thesis\n      by blast\n  next\n    case True\n    with pCons.hyps show ?thesis\n      by simp\n  qed\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  next\n    case False\n    show ?thesis\n      apply (rule exI[where x=0])\n      apply (rule exI[where x=c])\n      apply (auto simp: False)\n      done\n  qed\nqed\n\nlemma poly_decompose:\n  assumes nc: \"\\<not> constant (poly p)\"\n  shows \"\\<exists>k a q. a \\<noteq> (0::'a::idom) \\<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  proof\n    assume \"\\<forall>z. z \\<noteq> 0 \\<longrightarrow> poly cs z = 0\"\n    then have \"poly (pCons c cs) x = poly (pCons c cs) y\" for x y\n      by (cases \"x = 0\") auto\n    with pCons.prems show False\n      by (auto simp add: constant_def)\n  qed\n  from poly_decompose_lemma[OF this]\n  show ?case\n    apply clarsimp\n    apply (rule_tac x=\"k+1\" in exI)\n    apply (rule_tac x=\"a\" in exI)\n    apply simp\n    apply (rule_tac x=\"q\" in exI)\n    apply (auto simp add: psize_def split: if_splits)\n    done\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    from poly_offset[of p c] obtain q where q: \"psize q = psize p\" \"\\<forall>x. poly q x = ?p (c + x)\"\n      by blast\n    have False if h: \"constant (poly q)\"\n    proof -\n      from q(2) have th: \"\\<forall>x. poly q (x - c) = ?p x\"\n        by auto\n      have \"?p x = ?p y\" for x y\n      proof -\n        from th have \"?p x = poly q (x - c)\"\n          by auto\n        also have \"\\<dots> = poly q (y - c)\"\n          using h unfolding constant_def by blast\n        also have \"\\<dots> = ?p y\"\n          using th by auto\n        finally show ?thesis .\n      qed\n      with less(2) show ?thesis\n        unfolding constant_def by blast\n    qed\n    then have qnc: \"\\<not> constant (poly q)\"\n      by blast\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      using a00\n      unfolding psize_def degree_def\n      by (simp add: poly_eq_iff)\n    have False if h: \"\\<And>x y. poly ?r x = poly ?r y\"\n    proof -\n      have \"poly q x = poly q y\" for x y\n      proof -\n        from qr[rule_format, of x] have \"poly q x = poly ?r x * ?a0\"\n          by auto\n        also have \"\\<dots> = poly ?r y * ?a0\"\n          using h by simp\n        also have \"\\<dots> = poly q y\"\n          using qr[rule_format, of y] by simp\n        finally show ?thesis .\n      qed\n      with qnc show ?thesis\n        unfolding constant_def by blast\n    qed\n    then have rnc: \"\\<not> constant (poly ?r)\"\n      unfolding constant_def by blast\n    from qr[rule_format, of 0] a00 have r01: \"poly ?r 0 = 1\"\n      by auto\n    have mrmq_eq: \"cmod (poly ?r w) < 1 \\<longleftrightarrow> cmod (poly q w) < cmod ?a0\" for w\n    proof -\n      have \"cmod (poly ?r w) < 1 \\<longleftrightarrow> cmod (poly q w / ?a0) < 1\"\n        using qr[rule_format, of w] a00 by (simp add: divide_inverse ac_simps)\n      also have \"\\<dots> \\<longleftrightarrow> cmod (poly q w) < cmod ?a0\"\n        using a00 unfolding norm_divide by (simp add: field_simps)\n      finally show ?thesis .\n    qed\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(3) lgqr[symmetric] q(1) have s0: \"s = 0\"\n        by auto\n      have hth[symmetric]: \"cmod (poly ?r w) = cmod (1 + a * w ^ k)\" for w\n        using kas(4)[rule_format, of w] s0 r01 by (simp add: algebra_simps)\n      from reduce_poly_simple[OF kas(1,2)] show ?thesis\n        unfolding hth by blast\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 th01: \"\\<not> constant (poly (pCons 1 (monom a (k - 1))))\"\n        unfolding constant_def poly_pCons poly_monom\n        using kas(1)\n        apply simp\n        apply (rule exI[where x=0])\n        apply (rule exI[where x=1])\n        apply simp\n        done\n      from kas(1) kas(2) have th02: \"k + 1 = psize (pCons 1 (monom a (k - 1)))\"\n        by (simp add: psize_def degree_monom_eq)\n      from less(1) [OF k1n [simplified th02] th01]\n      obtain w where w: \"1 + w^k * a = 0\"\n        unfolding poly_pCons poly_monom\n        using kas(2) by (cases k) (auto simp add: algebra_simps)\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 w0: \"w \\<noteq> 0\"\n        using kas(2) w by (auto simp add: power_0_left)\n      from w have \"(1 + w ^ k * a) - 1 = 0 - 1\"\n        by simp\n      then have wm1: \"w^k * a = - 1\"\n        by simp\n      have inv0: \"0 < inverse (cmod w ^ (k + 1) * m)\"\n        using norm_ge_zero[of w] w0 m(1)\n        by (simp add: inverse_eq_divide zero_less_mult_iff)\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 th11: \"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 \"t * cmod w \\<le> 1 * cmod w\"\n        apply (rule mult_mono)\n        using t(1,2)\n        apply auto\n        done\n      then have tw: \"cmod ?w \\<le> cmod w\"\n        using t(1) by (simp add: norm_mult)\n      from t inv0 have \"t * (cmod w ^ (k + 1) * m) < 1\"\n        by (simp add: field_simps)\n      with zero_less_power[OF t(1), of k] have th30: \"t^k * (t* (cmod w ^ (k + 1) * m)) < t^k * 1\"\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 w0 t(1)\n        by (simp add: algebra_simps power_mult_distrib norm_power norm_mult)\n      then have \"cmod (?w^k * ?w * poly s ?w) \\<le> t^k * (t* (cmod w ^ (k + 1) * m))\"\n        using t(1,2) m(2)[rule_format, OF tw] w0\n        by auto\n      with th30 have th120: \"cmod (?w^k * ?w * poly s ?w) < t^k\"\n        by simp\n      from power_strict_mono[OF t(2), of k] t(1) kas(2) have th121: \"t^k \\<le> 1\"\n        by auto\n      from ath[OF norm_ge_zero[of \"?w^k * ?w * poly s ?w\"] th120 th121]\n      have th12: \"\\<bar>1 - t^k\\<bar> + cmod (?w^k * ?w * poly s ?w) < 1\" .\n      from th11 th12 have \"cmod (1 + ?w^k * (a + ?w * poly s ?w)) < 1\"\n        by arith\n      then have \"cmod (poly ?r ?w) < 1\"\n        unfolding kas(4)[rule_format, of ?w] r01 by simp\n      then show ?thesis\n        by blast\n    qed\n    with cq0 q(2) show ?thesis\n      unfolding mrmq_eq not_less[symmetric] by auto\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)\"\n  using nc\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    then show ?thesis by auto\n  next\n    case False\n    have \"\\<not> constant (poly (pCons c cs))\"\n    proof\n      assume nc: \"constant (poly (pCons c cs))\"\n      from nc[unfolded constant_def, rule_format, of 0]\n      have \"\\<forall>w. w \\<noteq> 0 \\<longrightarrow> poly cs w = 0\" by auto\n      then have \"cs = 0\"\n      proof (induct cs)\n        case 0\n        then show ?case by simp\n      next\n        case (pCons d ds)\n        show ?case\n        proof (cases \"d = 0\")\n          case True\n          then show ?thesis\n            using pCons.prems pCons.hyps by simp\n        next\n          case False\n          from poly_bound_exists[of 1 ds] obtain m where\n            m: \"m > 0\" \"\\<forall>z. \\<forall>z. cmod z \\<le> 1 \\<longrightarrow> cmod (poly ds z) \\<le> m\" by blast\n          have dm: \"cmod d / m > 0\"\n            using False m(1) by (simp add: field_simps)\n          from field_lbound_gt_zero[OF dm zero_less_one]\n          obtain x where x: \"x > 0\" \"x < cmod d / m\" \"x < 1\"\n            by blast\n          let ?x = \"complex_of_real x\"\n          from x have cx: \"?x \\<noteq> 0\" \"cmod ?x \\<le> 1\"\n            by simp_all\n          from pCons.prems[rule_format, OF cx(1)]\n          have cth: \"cmod (?x*poly ds ?x) = cmod d\"\n            by (simp add: eq_diff_eq[symmetric])\n          from m(2)[rule_format, OF cx(2)] x(1)\n          have th0: \"cmod (?x*poly ds ?x) \\<le> x*m\"\n            by (simp add: norm_mult)\n          from x(2) m(1) have \"x * m < cmod d\"\n            by (simp add: field_simps)\n          with th0 have \"cmod (?x*poly ds ?x) \\<noteq> cmod d\"\n            by auto\n          with cth show ?thesis\n            by blast\n        qed\n      qed\n      then show False\n        using pCons.prems False by blast\n    qed\n    then show ?thesis\n      by (rule fundamental_theorem_of_algebra)\n  qed\nqed\n\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 = p * ?w\"\n            apply (subst r)\n            apply (subst s)\n            apply (subst kpn)\n            using k oop [of a]\n            apply (subst power_mult_distrib)\n            apply simp\n            apply (subst power_add [symmetric])\n            apply simp\n            done\n          then 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            apply auto\n            apply (erule ssubst)\n            apply (simp add: degree_mult_eq degree_linear_power)\n            done\n          have \"poly r x = 0\" if h: \"poly s x = 0\" for x\n          proof -\n            have xa: \"x \\<noteq> a\"\n            proof\n              assume \"x = a\"\n              from h[unfolded this poly_eq_0_iff_dvd] obtain u where u: \"s = [:- a, 1:] * u\"\n                by (rule dvdE)\n              have \"p = [:- a, 1:] ^ (Suc ?op) * u\"\n                apply (subst s)\n                apply (subst u)\n                apply (simp only: power_Suc ac_simps)\n                done\n              with ap(2)[unfolded dvd_def] show False\n                by blast\n            qed\n            from h have \"poly p x = 0\"\n              by (subst s) simp\n            with pq0 have \"poly q x = 0\"\n              by blast\n            with r xa show ?thesis\n              by auto\n          qed\n          with IH[rule_format, OF dsn, of s r] False have \"s dvd (r ^ (degree s))\"\n            by blast\n          then obtain u where u: \"r ^ (degree s) = s * u\" ..\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          let ?w = \"(u * ([:-a,1:] ^ (n - ?op))) * (r ^ (n - degree s))\"\n          from oop[of a] dsn have \"q ^ n = p * ?w\"\n            apply -\n            apply (subst s)\n            apply (subst r)\n            apply (simp only: power_mult_distrib)\n            apply (subst mult.assoc [where b=s])\n            apply (subst mult.assoc [where a=u])\n            apply (subst mult.assoc [where b=u, symmetric])\n            apply (subst u [symmetric])\n            apply (simp add: ac_simps power_add [symmetric])\n            done\n          then show ?thesis\n            unfolding dvd_def by blast\n        qed\n      qed\n    qed\n    then show ?thesis\n      using a order_root pne by blast\n  next\n    case False\n    with fundamental_theorem_of_algebra_alt[of p]\n    obtain c where ccs: \"c \\<noteq> 0\" \"p = pCons c 0\"\n      by blast\n    then have pp: \"poly p x = c\" for x\n      by simp\n    let ?w = \"[:1/c:] * (q ^ n)\"\n    from ccs have \"(q ^ n) = (p * ?w)\"\n      by simp\n    then show ?thesis\n      unfolding dvd_def by blast\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 eq: \"(\\<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    {\n      assume \"p dvd (q ^ (degree p))\"\n      then obtain r where r: \"q ^ (degree p) = p * r\" ..\n      from r p have False by simp\n    }\n    with eq p show ?thesis by blast\n  next\n    case dp: 2\n    then obtain k where k: \"p = [:k:]\" \"k \\<noteq> 0\"\n      by (cases p) (simp split: if_splits)\n    then have th1: \"\\<forall>x. poly p x \\<noteq> 0\"\n      by simp\n    from k dp(2) have \"q ^ (degree p) = p * [:1/k:]\"\n      by simp\n    then have th2: \"p dvd (q ^ (degree p))\" ..\n    from dp(1) th1 th2 show ?thesis\n      by blast\n  next\n    case dp: 3\n    have False if dvd: \"p dvd (q ^ (Suc n))\" and h: \"poly p x = 0\" \"poly q x \\<noteq> 0\" for x\n    proof -\n      from dvd obtain u where u: \"q ^ (Suc n) = p * u\" ..\n      from h have \"poly (q ^ (Suc n)) x \\<noteq> 0\"\n        by simp\n      with u h(1) show ?thesis\n        by (simp only: poly_mult) simp\n    qed\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 th: \"poly p = poly [:poly p 0:]\"\n      by auto\n    then have \"p = [:poly p 0:]\"\n      by (simp add: poly_eq_poly_eq_iff)\n    then have \"degree p = degree [:poly p 0:]\"\n      by simp\n    then show ?thesis\n      by simp\n  qed\n  show ?lhs if ?rhs\n  proof -\n    from that obtain k where \"p = [:k:]\"\n      by (cases p) (simp split: if_splits)\n    then show ?thesis\n      unfolding constant_def by auto\n  qed\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)\"\nproof -\n  have \"pCons 0 q = q * [:0,1:]\" by simp\n  then have \"q dvd (pCons 0 q)\" ..\n  with pq show ?thesis by (rule dvd_trans)\nqed\n\nlemma poly_divides_conv0:\n  fixes p:: \"'a::field poly\"\n  assumes lgpq: \"degree q < degree p\"\n    and lq: \"p \\<noteq> 0\"\n  shows \"p dvd q \\<longleftrightarrow> q = 0\" (is \"?lhs \\<longleftrightarrow> ?rhs\")\nproof\n  assume ?rhs\n  then have \"q = p * 0\" by simp\n  then show ?lhs ..\nnext\n  assume l: ?lhs\n  show ?rhs\n  proof (cases \"q = 0\")\n    case True\n    then show ?thesis by simp\n  next\n    assume q0: \"q \\<noteq> 0\"\n    from l q0 have \"degree p \\<le> degree q\"\n      by (rule dvd_imp_degree_le)\n    with lgpq show ?thesis by simp\n  qed\nqed\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\" (is \"?lhs \\<longleftrightarrow> ?rhs\")\nproof\n  from pp' obtain t where t: \"p' = p * t\" ..\n  show ?rhs if ?lhs\n  proof -\n    from that obtain u where u: \"q = p * u\" ..\n    have \"r = p * (smult a u - t)\"\n      using u qrp' [symmetric] t by (simp add: algebra_simps)\n    then show ?thesis ..\n  qed\n  show ?lhs if ?rhs\n  proof -\n    from that obtain u where u: \"r = p * u\" ..\n    from u [symmetric] t qrp' [symmetric] a0\n    have \"q = p * smult (1/a) (u + t)\"\n      by (simp add: algebra_simps)\n    then show ?thesis ..\n  qed\nqed\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)\"\nproof -\n  have False if \"h \\<noteq> 0\" \"t = 0\" and \"pCons a (pCons b p) = pCons h t\" for h t\n    using l that by simp\n  then have th: \"\\<not> (\\<exists> h t. h \\<noteq> 0 \\<and> t = 0 \\<and> pCons a (pCons b p) = pCons h t)\"\n    by blast\n  from fundamental_theorem_of_algebra_alt[OF th] show ?thesis\n    by auto\nqed\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)\"\nproof -\n  from l have dp: \"degree (pCons a p) = psize p\"\n    by (simp add: psize_def)\n  from nullstellensatz_univariate[of \"pCons a p\" q] l\n  show ?thesis\n    by (metis dp pCons_eq_0_iff)\nqed\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\"\nproof -\n  from h have \"poly (q ^ n) = poly r\"\n    by auto\n  then have \"(q ^ n) = r\"\n    by (simp add: poly_eq_poly_eq_iff)\n  then show \"p dvd (q ^ n) \\<longleftrightarrow> p dvd r\"\n    by simp\nqed\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": "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/Computational_Algebra/Fundamental_Theorem_Algebra.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8519527944504227, "lm_q2_score": 0.837619961306541, "lm_q1q2_score": 0.7136126667225626}}
{"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_15\n  imports \"../../Test_Base\"\nbegin\n\ndatatype 'a list = nil2 | cons2 \"'a\" \"'a list\"\n\ndatatype Nat = Z | S \"Nat\"\n\nfun len :: \"'a list => Nat\" where\n  \"len (nil2) = Z\"\n| \"len (cons2 y xs) = S (len xs)\"\n\nfun t2 :: \"Nat => Nat => bool\" where\n  \"t2 x (Z) = False\"\n| \"t2 (Z) (S z) = True\"\n| \"t2 (S x2) (S z) = t2 x2 z\"\n\nfun ins :: \"Nat => Nat list => Nat list\" where\n  \"ins x (nil2) = cons2 x (nil2)\"\n| \"ins x (cons2 z xs) =\n     (if t2 x z then cons2 x (cons2 z xs) else cons2 z (ins x xs))\"\n\ntheorem property0 :\n  \"((len (ins x xs)) = (S (len xs)))\"\n  find_proof DInd\n  apply (induct rule: TIP_prop_15.len.induct)\n   apply auto\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_15.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.908617906830944, "lm_q2_score": 0.7853085859124002, "lm_q1q2_score": 0.7135454435480936}}
{"text": "theory Chapter2\n  imports Chapter1\nbegin\n\nsection \"0 Intro\"\n\n(*\nTopological Systems are specified, equivalently, by either the collection of open sets,\nor the collection of closed sets as set systems. In addition to the topological closure and\ntopological interior operators for characterizing a topology, there are four other operators\ncommonly used in topology, namely exterior operator, boundary operator, derived-set\noperator, and co-derived-set operator. \n\nEach of these can also be used to completely characterize a Topological System, as shown by the work of [14\u201317,19]. *)\n\n\nsection \"1 Exterior Operator Axioms\"\n\n(*\nWe first discuss the exterior operator in a topological space. \nGiven a topological interior operator Int : P(X) \\<rightarrow> P(X), \none can define the so-called topological exterior operator \nrelated to Int by Ext(A) = Int(A\\<^sup>c) where A\\<^sup>c \\<equiv> X \\ A denotes set-complement of\nA. \n*)\n\ndefinition exterior_from_interior :: \"'w cl \\<Rightarrow> 'w cl\" \n  where \"exterior_from_interior Int' \\<equiv> \\<lambda>A. Int' (\\<^bold>\\<midarrow> A)\"\n\n(*\nThe question of whether one can do the converse, \nnamely axiomatically characterize Ext as a primitive operator \nfrom which Cl and Int operators are derived from, \nwas answered affirmatively first by Zarycki [19] \nand then reported by Gabai [14] nearly half a century later. \n\nIn other words, one can specify the Topological System \nby a topological exterior operator Ext axiomatically defined as follows.\n\nDefinition 1: (Topological Exterior Operator).\nAn operator Ext: P(X) \\<rightarrow> P(X) is called a topological exterior operator \nif for any sets A, B \\<subseteq> X, Ext satisfies the following four axioms:\n[EO1] Ext(\\<emptyset>) = X;\n[EO2] A \\<inter> Ext(A) = \\<emptyset>;\n[EO3] Ext(X \\ Ext(A)) = Ext(A);\n[EO4] Ext(A \\<union> B) = Ext(A) \\<inter> Ext(B).\n*)\n\n\ndefinition EO1::\"'w cl \\<Rightarrow> bool\" where \"EO1 Ext \\<equiv> (Ext \\<^bold>\\<bottom>) \\<^bold>\\<approx> \\<^bold>\\<top>\" \ndefinition EO2::\"'w cl \\<Rightarrow> bool\" where \"EO2 Ext \\<equiv> \\<forall>A. A \\<^bold>\\<and> Ext A \\<^bold>\\<approx> \\<^bold>\\<bottom>\"\ndefinition EO3::\"'w cl \\<Rightarrow> bool\" where \"EO3 Ext \\<equiv> \\<forall>A. Ext(\\<^bold>\\<midarrow> Ext A) \\<^bold>\\<approx> (Ext A)\"\ndefinition EO4::\"'w cl \\<Rightarrow> bool\" where \"EO4 Ext \\<equiv> \\<forall>A B. Ext(A \\<^bold>\\<or> B) \\<^bold>\\<approx> (Ext A) \\<^bold>\\<and> (Ext B)\"\n\ndefinition exterior_op :: \"'w cl \\<Rightarrow> bool\"\n  where \"exterior_op \\<equiv> EO1 \\<^bold>\\<and> EO2 \\<^bold>\\<and> EO3 \\<^bold>\\<and> EO4\"\n\nlemma assumes \"interior_op Ext\" shows \"open_topo (\\<lambda> E. Ext (\\<^bold>\\<midarrow> E) \\<^bold>\\<approx> E)\" sorry\n\n(*\nNote that the three topological operators Ext, Int, and Cl \nare related to one another by the following relations:\n\nInt(A) = Ext(A\\<^sup>c) \\<Leftarrow>\\<Rightarrow> Int(A\\<^sup>c) = Ext(A) ;\nCl(A) = (Ext(A))\\<^sup>c \\<Leftarrow>\\<Rightarrow> (Cl(A))\\<^sup>c = Ext(A) ;\nCl(A) = (Int(A\\<^sup>c))\\<^sup>c \\<Leftarrow>\\<Rightarrow> Cl(A\\<^sup>c) = (Int(A))\\<^sup>c\n*)\n\nlemma \n  assumes \"interior_cl Int'\" and \"exterior_cl Ext\"\n  shows \"Int' A \\<^bold>\\<approx> Ext (\\<^bold>\\<midarrow> A) \\<longleftrightarrow> Int' (\\<^bold>\\<midarrow> A) \\<^bold>\\<approx> Ext A\" sorry\nlemma \n  assumes \"exterior_cl Ext\" and \"closure_cl Cl\"\n  shows \"Cl A \\<^bold>\\<approx> \\<^bold>\\<midarrow> (Ext A) \\<longleftrightarrow> \\<^bold>\\<midarrow> (Cl A) \\<^bold>\\<approx> Ext A\" sorry\nlemma \n  assumes \"interior_cl Int'\" and \"closure_cl Cl\"\n  shows \"(Cl A \\<^bold>\\<approx> \\<^bold>\\<midarrow> (Int' (\\<^bold>\\<midarrow> A))) \\<longleftrightarrow> (Cl (\\<^bold>\\<midarrow> A) \\<^bold>\\<approx> \\<^bold>\\<midarrow> (Int' A))\"\n  sorry\n\n\n\nsection \"2 Boundary Operator Axioms\"\n\n\n(*\nDefinition 2: (Topological Boundary Operator).\nAn operator Fr: P(X) \\<rightarrow> P(X) is called \na topological boundary (or frontier) operator \nif for any sets A, B \\<subseteq> X, Fr satisfies the following five axioms:\n\n[FO1] Fr(\\<emptyset>) = \\<emptyset>;\n[FO2] Fr(A) = Fr(A\\<^sup>c);\n[FO3] A \\<subseteq> B \\<Rightarrow> Fr(A) \\<subseteq> B \\<union> Fr(B);\n[FO4] Fr(Fr(A)) \\<subseteq> Fr(A);\n[FO5] Fr(A \\<union> B) \\<subseteq> Fr(A) \\<union> Fr(B).\n*)\n\ndefinition FO1::\"'w cl \\<Rightarrow> bool\" where \"FO1 Fr \\<equiv> (Fr \\<^bold>\\<bottom>) \\<^bold>\\<approx> \\<^bold>\\<bottom>\" \ndefinition FO2::\"'w cl \\<Rightarrow> bool\" where \"FO2 Fr \\<equiv> \\<forall>A. Fr A \\<^bold>\\<approx> Fr (\\<^bold>\\<midarrow> A)\"\ndefinition FO3::\"'w cl \\<Rightarrow> bool\" where \"FO3 Fr \\<equiv> \\<forall>A B. A \\<^bold>\\<preceq> B \\<longrightarrow> Fr A \\<^bold>\\<preceq> (B \\<^bold>\\<or> Fr B)\"\ndefinition FO4::\"'w cl \\<Rightarrow> bool\" where \"FO4 Fr \\<equiv> \\<forall>A. Fr(Fr A) \\<^bold>\\<preceq> (Fr A)\"\ndefinition FO5::\"'w cl \\<Rightarrow> bool\" where \"FO5 Fr \\<equiv> \\<forall>A B. Fr (A \\<^bold>\\<or> B) \\<^bold>\\<preceq> (Fr A) \\<^bold>\\<or> (Fr B)\"\n\ndefinition boundary_op :: \"'w cl \\<Rightarrow> bool\"\n  where \"boundary_op \\<equiv> FO1 \\<^bold>\\<and> FO2 \\<^bold>\\<and> FO3 \\<^bold>\\<and> FO4 \\<^bold>\\<and> FO5\"\n\n(*\nNote that axiom [FO2] dictates that the boundary Fr(A) of A \nis the same as the boundary Fr(A\\<^sup>c) of A\\<^sup>c; \nin other words, A and A\\<^sup>c \\<equiv> X \\ A share the \u201ccommon\u201d boundary points\n*)\n\nlemma assumes \"boundary_op Fr\" shows \"Fr A \\<^bold>\\<approx> Fa (\\<^bold>\\<midarrow>A)\" sorry\n\n(*\nWith respect to a boundary (also called frontier) operator Fr, \nwe can construct T = {E \\<in> P(X) | Fr(E\\<^sup>c) \\<subseteq> E\\<^sup>c}. \nThe collection T so constructed is a topology. For A \\<subseteq> X,\nFr(A) is the boundary of A in the topological space (X, T ). \nMoreover, T is the only topology with the given boundary structure\n*)\n\nlemma \n  assumes \"boundary_op Fr\" \n  shows \"closed_topo (\\<lambda> E. Fr (\\<^bold>\\<midarrow>E) \\<^bold>\\<preceq> (\\<^bold>\\<midarrow>E))\" sorry\n\n(*\nWe now investigate the role of axiom [FO5], \nthe axiom to be removed when relaxing to a generalized Closure System.\n\nProposition 1:\n[FO4] and [FO5] imply\n[FO4]\\<^sup>* Fr(A \\<union> Fr(A)) \\<subseteq> Fr(A),\nwhich then implies Fr(A \\<union> Fr(A)) \\<subseteq> A \\<union> Fr(A).\n*)\ndefinition FO4'::\"'w cl \\<Rightarrow> bool\" where \"FO4' Fr \\<equiv> \\<forall>A. Fr(A \\<^bold>\\<or> Fr A) \\<^bold>\\<preceq> (Fr A)\"\ndefinition FO4''::\"'w cl \\<Rightarrow> bool\" where \"FO4'' Fr \\<equiv> \\<forall>A. Fr(A \\<^bold>\\<or> Fr A) \\<^bold>\\<preceq> (A \\<^bold>\\<or> Fr A)\"\n\nlemma assumes \"(FO4 \\<^bold>\\<and> FO5) Fr\" shows \"FO4 Fr\" by (metis assms meet_def)\n(*\nProof. \nBy [FO5], Fr(A \\<union> Fr(A)) \\<subseteq> Fr(A) \\<union> Fr(Fr(A)). \nBecause of [FO4], Fr(A) \\<union> Fr(Fr(A)) = Fr(A). \nThen Fr(A \\<union>Fr(A)) \\<subseteq> Fr(A) holds. \nObviously, Fr(A \\<union>Fr(A)) \\<subseteq> A \\<union>Fr(A) also holds.\n*)\n\n(*\nIf we drop axiom [FO5] in the definition of Fr, we do not have [FO4]\\<^sup>*. \nOn the other hand, we have the following result.\n\nProposition 2:\n[FO2], [FO3] and [FO4]\\<^sup>* implies [FO4]\n*)\n\nlemma\n  fixes Fr :: \"'w cl\"\n  assumes 1: \"FO2 Fr\" and 2: \"FO3 Fr\" and 3: \"FO4' Fr\"\n  shows \"FO4 Fr\"\n  sorry\n\n(*\nProof:\n\nSuppose a set operator Fr only satisfies [FO2] and [FO3] in Definition 10. \nFor any A \\<subseteq> X, Fr(A) \\<subseteq> A \\<union> Fr(A). \n\nAn application of [FO3] gives \nFr(Fr(A)) \\<subseteq> A \\<union> Fr(A) \\<union> Fr(A \\<union> Fr(A)) = A \\<union> Fr(A), \nwhere the last step invokes [FO4]\\<^sup>*. \nThen Fr(Fr(A)) \\<subseteq> A \\<union> Fr(A) holds. \nLikewise, for the complement X\\<^sup>c \\<equiv> X \\ A, Fr(Fr(A\\<^sup>c)) \\<subseteq> A\\<^sup>c \\<union> Fr(A\\<^sup>c) holds. \n\nBy (FO2), we have Fr(Fr(A)) \\<subseteq> A \\<union> Fr(A) and Fr(Fr(A)) \\<subseteq> A\\<^sup>c \\<union> Fr(A).\n\nTherefore, \nFr(Fr(A)) \\<subseteq> (A \\<union> Fr(A)) \\<inter> (A\\<^sup>c \\<union> Fr(A)) \n= (A \\<inter> A\\<^sup>c) \\<union> Fr(A)) = \\<emptyset> \\<union> Fr(A) = Fr(A), \ni.e., Fr(Fr(A)) \\<subseteq> Fr(A).\n\n*)\n\n(*\nFrom the above two Propositions, \nit follows that axiom [FO4] in the axiomatic definition of Fr \ncan be equivalently replaced by [FO4]\\<^sup>*. \n\nThen we have an alternative axiomatization of topological boundary operator Fr.\n\nDefinition 3: (Topological Boundary Operator, Alternative Definition).\n\nAn operator Fr: P(X) \\<rightarrow> P(X) is called a topological boundary operator \nif for any sets A, B \\<subseteq> X, Fr satisfies the following five axioms:\n[FO1] Fr(\\<emptyset>) = \\<emptyset>;\n[FO2] Fr(A) = Fr(A\\<^sup>c);\n[FO3] A \\<subseteq> B \\<Rightarrow> Fr(A) \\<subseteq> B \\<union> Fr(B);\n[FO4]\\<^sup>* Fr(A \\<union> Fr(A)) \\<subseteq> Fr(A);\n[FO5] Fr(A \\<union> B) \\<subseteq> Fr(A) \\<union> Fr(B).\n*)\n\ndefinition boundary_op' :: \"'w cl \\<Rightarrow> bool\"\n  where \"boundary_op' \\<equiv> FO1 \\<^bold>\\<and> FO2 \\<^bold>\\<and> FO3 \\<^bold>\\<and> FO4' \\<^bold>\\<and> FO5\"\n\n(*\nIt is possible to further partition Fr(A) into two non-intersecting sets, \nA \\<inter> Fr(A) and A\\<^sup>c \\<inter> Fr(A). See discussions in the first paragraph of Section 2\n*)\n\n\n\nsection \"3 Derived-Set Operator Axioms\"\n\n(*\nWe will now turn to the derived-set operator and the co-derived-set operator. Derived\nset arises out of studying the limit points (called accumulation points, see Section 4.2.2) of\ntopologically converging sequences\n*)\n\n\n(*\nWe follow the scheme by Harvey.\n\nDefinition 4: (Topological Derived-Set Operator).\n\nAn operator Der: P(X) \\<rightarrow> P(X) is called a topological derived-set operator \nif for any sets A, B \\<subseteq> X, Der satisfies the following four axioms:\n\n[DO1] Der(\\<emptyset>) = \\<emptyset>;\n[DO2] x \\<in> Der(A) \\<Leftarrow>\\<Rightarrow> x \\<in> Der(A \\ {x});\n[DO3] Der(A \\<union> Der(A)) \\<subseteq> A \\<union> Der(A);\n[DO4] Der(A \\<union> B) = Der(A) \\<union> Der(B).\n*)\n\n\ndefinition DO1::\"'w cl \\<Rightarrow> bool\" where \"DO1 Der \\<equiv> (Der \\<^bold>\\<bottom>) \\<^bold>\\<approx> \\<^bold>\\<bottom>\" \ndefinition DO2::\"'w cl \\<Rightarrow> bool\" where \"DO2 Der \\<equiv> \\<forall> A x. Der A x \\<longleftrightarrow> Der (A \\<^bold>\\<leftharpoonup> \\<lbrace>x\\<rbrace>) x\"\ndefinition DO3::\"'w cl \\<Rightarrow> bool\" where \"DO3 Der \\<equiv> \\<forall>A. Der (A \\<^bold>\\<or> Der A) \\<^bold>\\<preceq> (A \\<^bold>\\<or> Der A)\"\ndefinition DO4::\"'w cl \\<Rightarrow> bool\" where \"DO4 Der \\<equiv> \\<forall>A B. Der (A \\<^bold>\\<or> B) \\<^bold>\\<approx> (Der A \\<^bold>\\<or> Der B)\"\n\ndefinition derivSet_op :: \"'w cl \\<Rightarrow> bool\" \n  where \"derivSet_op \\<equiv> DO1 \\<^bold>\\<and> DO2 \\<^bold>\\<and> DO3 \\<^bold>\\<and> DO4\"\n\ndefinition DO3'::\"'w cl \\<Rightarrow> bool\" where \"DO3' Der \\<equiv> \\<forall>A. Der (Der A) \\<^bold>\\<preceq> (A \\<^bold>\\<or> Der A)\"\n\n(* Proposition 3:\n\nA topological derived-set operator Der has the following property:\n[DO3]\\<^sup>* Der(Der(A)) \\<subseteq> A \\<union> Der(A) for any A \\<subseteq> X.\n\nMoreover, [DO3]\\<^sup>* is equivalent to [DO3] under [DO4]. *)\n\n(*\nProof. First, we show that the topological derived-set operator Der is monotone: for\nany A, B \\<subseteq> X, A \\<subseteq> B implies Der(A) \\<subseteq> Der(B). By [DO4] and assuming A \\<subseteq> B,\nDer(A \\<union> B) = Der(B) = Der(A) \\<union> Der(B), which implies Der(A) \\<subseteq> Der(B).\n*)\n\nlemma monotone_derivSet_op:\n  fixes Der\n  assumes \"A \\<^bold>\\<preceq> B\" and \"derivSet_op Der\"\n  shows \"Der A \\<^bold>\\<preceq> Der B\" sorry\n\nlemma assumes \"derivSet_op Der\" shows \"D03' Der\" sorry\n\n(* continue proof:\n\nFor any A \\<subseteq> X, Der(A) \\<subseteq> A \\<union> Der(A) holds. \nBy the monotone property of Der and [DO3], \nwe have Der(Der(A)) \\<subseteq> Der(A \\<union> Der(A)) \\<subseteq> A \\<union> Der(A). \nThen Der(Der(A)) \\<subseteq> A \\<union> Der(A), so [DO3]\\<^sup>* holds.\n\nOn the other hand, suppose Der only satisfies [DO4]: \nDer(A \\<union> B) = Der(A) \\<union> Der(B). \nThen Der(A \\<union> Der(A)) = Der(A) \\<union> Der(Der(A)). \nBy [DO3]\\<^sup>*, Der(A \\<union> Der(A)) \\<subseteq> A \\<union> Der(A), i.e., [DO3] holds. \nTherefore, [DO3]\\<^sup>* is equivalent to [DO3] under [DO4].\n*)\n\n(*\nFrom the above proposition, \nit follows that we can equivalently substitute [DO3]\\<^sup>* for [DO3] \nin the definition of Der\n*)\n\n(*\nDenote [DO2]\\<^sup>* x \\<notin> Der({x}) for any x \\<in> X\n*)\n\ndefinition DO2'::\"'w cl \\<Rightarrow> bool\" where \"DO2' Der \\<equiv> \\<forall> x. \\<not> (Der \\<lbrace>x\\<rbrace>) x\"\n\n(* Spira [15] showed that axiom [DO2] is equivalent to [DO2]\\<^sup>* \nunder axioms [DO1] and [DO4]*)\n\nlemma \n  fixes Der\n  assumes \"DO1 Der\" and \"DO4 Der\"\n  shows \"DO2 Der \\<longleftrightarrow> DO2' Der\" sorry\n\n(*\nTherefore, we have an alternative, simpler axiomatic version \nfor topological derived-set operator.\n\nDefinition 5: (Topological Derived-Set Operator, Alternative Definition).\nAn operator Der: P(X) \\<rightarrow> P(X) is called a topological derived-set operator \nif for any sets A, B \\<subseteq> X, Der satisfies the following four axioms:\n[DO1] Der(\\<emptyset>) = \\<emptyset>;\n[DO2]\\<^sup>* For any x \\<in> X, x 6\\<in> Der({x});\n[DO3]\\<^sup>*  Der(Der(A)) \\<subseteq> A \\<union> Der(A);\n[DO4] Der(A \\<union> B) = Der(A) \\<union> Der(B).\n*)\n\ndefinition der_op :: \"'w cl \\<Rightarrow> bool\" \n  where \"der_op \\<equiv> DO1 \\<^bold>\\<and> DO2' \\<^bold>\\<and> DO3' \\<^bold>\\<and> DO4\"\n\n\nsection \"4 Co-Derived-Set Operator\"\n\n(*\nFrom a derived-set operator Der, we can dually define an operator Cod \nthrough complementation: for any A \\<subseteq> X, Cod(A) = (Der(A\\<^sup>c))\\<^sup>c. \nEquivalently, Der(A) =(Cod(A\\<^sup>c))\\<^sup>c. *)\n\ndefinition cod_from_der :: \"'w cl \\<Rightarrow> 'w cl\" \n  where \"cod_from_der Der \\<equiv> \\<lambda> A. \\<^bold>\\<midarrow> Der (\\<^bold>\\<midarrow> A)\"\ndefinition der_from_cod :: \"'w cl \\<Rightarrow> 'w cl\" \n  where \"der_from_cod Cod \\<equiv> \\<lambda> A. \\<^bold>\\<midarrow> Cod (\\<^bold>\\<midarrow> A)\"\n\n\n(*\nSteinsvold [16] used the co-derived-set operator as the semantics for belief in\nhis Ph.D. Thesis\n\nDefinition 6: (Topological Co-Derived-Set Operator).\n\nAn operator Cod: P(X) \\<rightarrow> P(X) is called a topological co-derived-set operator \nif for any sets A, B \\<subseteq> X, Cod satisfies the following four axioms:\n[CD1] Cod (X) = X;\n[CD2] x \\<in> Cod(A) \\<Leftarrow>\\<Rightarrow> x \\<in> Cod(A \\<union> {x});\n[CD3] Cod(A \\<inter> Cod(A)) \\<supseteq> A \\<inter> Cod(A);\n[CD4] Cod(A \\<inter> B) = Cod(A) \\<inter> Cod(B).\n*)\n\n\ndefinition CD1::\"'w cl \\<Rightarrow> bool\" where \"CD1 Cod \\<equiv> (Cod \\<^bold>\\<top>) \\<^bold>\\<approx> \\<^bold>\\<top>\" \ndefinition CD2::\"'w cl \\<Rightarrow> bool\" where \"CD2 Cod \\<equiv> \\<forall> A x. Cod A x \\<longleftrightarrow> Cod (A \\<^bold>\\<or> \\<lbrace>x\\<rbrace>) x\"\ndefinition CD3::\"'w cl \\<Rightarrow> bool\" where \"CD3 Cod \\<equiv> \\<forall>A. (A \\<^bold>\\<and> Cod A) \\<^bold>\\<preceq> Cod (A \\<^bold>\\<or> Cod A) \"\ndefinition CD4::\"'w cl \\<Rightarrow> bool\" where \"CD4 Cod \\<equiv> \\<forall>A B. Cod (A \\<^bold>\\<and> B) \\<^bold>\\<approx> (Cod A \\<^bold>\\<or> Cod B)\"\n\ndefinition cod_od :: \"'w cl \\<Rightarrow> bool\" \n  where \"cod_od \\<equiv> CD1 \\<^bold>\\<and> CD2 \\<^bold>\\<and> CD3 \\<^bold>\\<and> CD4\"\n\n\n(*\nBoth derived set and co-derived set can be used to define a topology. \nAny subset A \\<subseteq> X is stipulated as being closed when Der(A) \\<subseteq> A. \nThen the collection T = {E \\<in> P(X) | E\\<^sup>c is closed} = {E \\<in> P(X) | Der(E\\<^sup>c) \\<subseteq> E\\<^sup>c} \nwill specify a Topological System on X, \nwith the derived-set operator induced by T being just Der. \n*)\n\nlemma assumes \"der_op Der\" shows \"closed_topo (\\<lambda>E . Der (\\<^bold>\\<midarrow> E) \\<^bold>\\<preceq> (\\<^bold>\\<midarrow> E))\" sorry\n\n(*\nMoreover, T is the only topology satisfying this condition. *)\n\n(*Johannes: ... how to show that?*)\n\n\n(*\nDually, T' = {E \\<in> P(X) | E \\<subseteq> Cod(E)} also specifies a Topological System on X. \nThe above two topological systems are indeed identical, i.e.,\nT = T'. \n*)\nlemma assumes \"cod_op Cod\" shows \"closed_topo (\\<lambda>E . E \\<^bold>\\<preceq> (Cod E))\" sorry\n\n(*\nSo, a derived-set operator and its dual co-derived-set operator \ngenerate the same topology.\n*)\n\nlemma assumes \"cod_op Cod\" and \"der_op Der\"\n  shows \"E \\<^bold>\\<preceq> (Cod E) \\<longleftrightarrow> Der (\\<^bold>\\<midarrow> E) \\<^bold>\\<preceq> (\\<^bold>\\<midarrow> E)\"\n  sorry\n\n\nsection \"5 Resumee\"\n\n(*\nUp till this point, we see that a Topological System can be uniquely specified by any\nof the following six operators: Cl,Int, Ext, Fr, Der, Cod. These six operators, with their\nrespective set of axioms, are rigidly interlocked.\n*)\n\n\nend", "meta": {"author": "jhln", "repo": "Bamberg", "sha": "73c62c87b4c3a5f39c211d4162f9915390f4cd64", "save_path": "github-repos/isabelle/jhln-Bamberg", "path": "github-repos/isabelle/jhln-Bamberg/Bamberg-73c62c87b4c3a5f39c211d4162f9915390f4cd64/Closure Systems/Chapter2.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8354835452961425, "lm_q2_score": 0.8539127492339909, "lm_q1q2_score": 0.7134300511035906}}
{"text": "(* author: R. Thiemann *)\n\nsection \\<open>The Sunflower Lemma\\<close>\n\ntext \\<open>We formalize the proof of the sunflower lemma of Erd\u0151s and Rado~\\cite{erdos_rado}, \nas it is presented in the textbook~\\cite[Chapter~6]{book}.  \nWe further integrate Exercise 6.2 from the textbook,\nwhich provides a lower bound on the existence of sunflowers.\\<close>\n\ntheory Erdos_Rado_Sunflower\n  imports \n    Sunflower\nbegin\n\ntext \\<open>When removing an element from all subsets, then one can afterwards\n  add these elements to a sunflower and get a new sunflower.\\<close>\n\nlemma sunflower_remove_element_lift: \n  assumes S: \"S \\<subseteq> { A - {a} | A . A \\<in> F \\<and> a \\<in> A}\" \n    and sf: \"sunflower S\" \n  shows \"\\<exists> Sa. sunflower Sa \\<and> Sa \\<subseteq> F \\<and> card Sa = card S \\<and> Sa = insert a ` S\" \nproof (intro exI[of _ \"insert a ` S\"] conjI refl)\n  let ?Sa = \"insert a ` S\" \n  {\n    fix B\n    assume \"B \\<in> ?Sa\" \n    then obtain C where C: \"C \\<in> S\" and B: \"B = insert a C\" \n      by auto\n    from C S obtain T where \"T \\<in> F\" \"a \\<in> T\" \"C = T - {a}\" \n      by auto\n    with B have \"B = T\" by auto\n    with \\<open>T \\<in> F\\<close> have \"B \\<in> F\" by auto\n  } \n  thus SaF: \"?Sa \\<subseteq> F\" by auto\n  have inj: \"inj_on (insert a) S\" using S \n    by (intro inj_on_inverseI[of _ \"\\<lambda> B. B - {a}\"], auto)\n  thus \"card ?Sa = card S\" by (rule card_image)\n  show \"sunflower ?Sa\" unfolding sunflower_def\n  proof (intro allI, intro impI)\n    fix x\n    assume \"\\<exists>C D. C \\<in> ?Sa \\<and> D \\<in> ?Sa \\<and> C \\<noteq> D \\<and> x \\<in> C \\<and> x \\<in> D\"\n    then obtain C D where *: \"C \\<in> ?Sa\" \"D \\<in> ?Sa\" \"C \\<noteq> D\" \"x \\<in> C\" \"x \\<in> D\" \n      by auto\n    from *(1-2) obtain C' D' where \n      **: \"C' \\<in> S\" \"D' \\<in> S\" \"C = insert a C'\" \"D = insert a D'\" \n      by auto\n    with \\<open>C \\<noteq> D\\<close> inj have CD': \"C' \\<noteq> D'\" by auto\n    show \"\\<forall>E. E \\<in> ?Sa \\<longrightarrow> x \\<in> E\" \n    proof (cases \"x = a\")\n      case False\n      with * ** have \"x \\<in> C'\" \"x \\<in> D'\" by auto\n      with ** CD' have \"\\<exists>C D. C \\<in> S \\<and> D \\<in> S \\<and> C \\<noteq> D \\<and> x \\<in> C \\<and> x \\<in> D\" by auto\n      from sf[unfolded sunflower_def, rule_format, OF this]\n      show ?thesis by auto\n    qed auto\n  qed\nqed\n\ntext \\<open>The sunflower-lemma of Erd\u0151s and Rado: \n  if a set has a certain size and all elements\n  have the same cardinality, then a sunflower exists.\\<close>\n\nlemma Erdos_Rado_sunflower_same_card: \n  assumes \"\\<forall> A \\<in> F. finite A \\<and> card A = k\" \n    and \"card F > (r - 1)^k * fact k\"\n  shows \"\\<exists> S. S \\<subseteq> F \\<and> sunflower S \\<and> card S = r \\<and> {} \\<notin> S\" \n  using assms \nproof (induct k arbitrary: F)\n  case 0\n  hence \"F = {{}} \\<or> F = {}\" \"card F \\<ge> 2\" by auto\n  hence False by auto\n  thus ?case by simp\nnext \n  case (Suc k F)\n  define pd_sub :: \"'a set set \\<Rightarrow> nat \\<Rightarrow> bool\" where\n    \"pd_sub = (\\<lambda> G t. G \\<subseteq> F \\<and> card G = t \\<and> pairwise disjnt G \\<and> {} \\<notin> G)\"\n  show ?case\n  proof (cases \"\\<exists> t G. pd_sub G t \\<and> t \\<ge> r\")\n    case True\n    then obtain t G where pd_sub: \"pd_sub G t\" and t: \"t \\<ge> r\" by auto\n    from pd_sub[unfolded pd_sub_def] pairwise_disjnt_imp_sunflower\n    have *: \"G \\<subseteq> F\" \"card G = t\" \"sunflower G\" \"{} \\<notin> G\" by auto\n    from t \\<open>card G = t\\<close> obtain H where \"H \\<subseteq> G\" \"card H = r\"\n      by (metis obtain_subset_with_card_n)\n    with sunflower_subset[OF \\<open>H \\<subseteq> G\\<close>] * show ?thesis by blast\n  next\n    case False\n    define P where \"P = (\\<lambda> t. \\<exists> G. pd_sub G t)\" \n    have ex: \"\\<exists> t. P t\" unfolding P_def\n      by (intro exI[of _ 0] exI[of _ \"{}\"], auto simp: pd_sub_def)\n    have large': \"\\<And> t. P t \\<Longrightarrow> t < r\" using False unfolding P_def by auto\n    hence large: \"\\<And> t. P t \\<Longrightarrow> t \\<le> r\" by fastforce \n    define t where \"t = (GREATEST t. P t)\"\n    from GreatestI_ex_nat[OF ex large, folded t_def] have Pt: \"P t\" .\n    from Greatest_le_nat[of P, OF _ large] \n    have greatest: \"\\<And> s. P s \\<Longrightarrow> s \\<le> t\" unfolding t_def by auto\n    from large'[OF Pt] have tr: \"t \\<le> r - 1\" by simp\n    from Pt[unfolded P_def pd_sub_def] obtain G where \n      cardG: \"card G = t\" and \n      disj: \"pairwise disjnt G\" and \n      GF: \"G \\<subseteq> F\" \n      by blast\n    define A where \"A = (\\<Union> G)\"\n    from Suc(3) have \"card F > 0\" by simp\n    hence \"finite F\" by (rule card_ge_0_finite)\n    from GF \\<open>finite F\\<close> have finG: \"finite G\" by (rule finite_subset)\n    have \"card (\\<Union> G) \\<le> sum card G\" \n      by (rule card_Union_le_sum_card, insert Suc(2) GF, auto)\n    also have \"\\<dots> \\<le> of_nat (card G) * Suc k\" \n      by (rule sum_bounded_above, insert GF Suc(2), auto)\n    also have \"\\<dots> \\<le> (r - 1) * Suc k\" \n      using tr[folded cardG] by (metis id_apply mult_le_mono1 of_nat_eq_id)\n    finally have cardA: \"card A \\<le> (r - 1) * Suc k\" unfolding A_def .\n    {\n      fix B\n      assume *: \"B \\<in> F\"\n      with Suc(2) have nE: \"B \\<noteq> {}\" by auto\n      from Suc(2) have eF: \"{} \\<notin> F\" by auto\n      have \"B \\<inter> A \\<noteq> {}\"\n      proof\n        assume dis: \"B \\<inter> A = {}\"\n        hence disj: \"pairwise disjnt ({B} \\<union> G)\"  using disj unfolding A_def\n          by (smt (verit, ccfv_SIG) Int_commute Un_iff \n              Union_disjoint disjnt_def pairwise_def singleton_iff)\n        from nE dis have \"B \\<notin> G\" unfolding A_def by auto\n        with finG have c: \"card ({B} \\<union> G) = Suc t\" by (simp add: cardG)\n        have \"P (Suc t)\" unfolding P_def pd_sub_def\n          by (intro exI[of _ \"{B} \\<union> G\"], insert eF disj c * GF, auto)\n        with greatest show False by force\n      qed\n    } note overlap = this\n    have \"F \\<noteq> {}\" using Suc(2-) by auto\n    with overlap have Ane: \"A \\<noteq> {}\" unfolding A_def by auto\n    have \"finite A\" unfolding A_def using finG Suc(2-) GF by auto\n    let ?g = \"\\<lambda> B x. x \\<in> B \\<inter> A\" \n    define f where \"f = (\\<lambda> B. SOME x. ?g B x)\" \n    have \"f \\<in> F \\<rightarrow> A\"\n    proof\n      fix B\n      assume \"B \\<in> F\" \n      from overlap[OF this] have \"\\<exists> x. ?g B x\" unfolding A_def by auto\n      from someI_ex[OF this] show \"f B \\<in> A\" unfolding f_def by auto\n    qed\n    from pigeonhole_card[OF this \\<open>finite F\\<close> \\<open>finite A\\<close> Ane]\n    obtain a where a: \"a \\<in> A\" \n      and le: \"card F \\<le> card (f -` {a} \\<inter> F) * card A\" by auto\n    {\n      fix S \n      assume \"S \\<in> F\" \"f S \\<in> {a}\"\n      with someI_ex[of \"?g S\"] a overlap[OF this(1)]\n      have \"a \\<in> S\" unfolding f_def by auto\n    } note FaS = this\n    let ?F = \"{S - {a} | S . S \\<in> F \\<and> f S \\<in> {a}}\" \n    from cardA have \"((r - 1) ^ k * fact k) * card A \\<le> ((r - 1) ^ k * fact k) * ((r - 1) * Suc k)\"\n      by simp\n    also have \"\\<dots> = (r - 1) ^ (Suc k) * fact (Suc k)\"\n      by (metis (no_types, lifting) fact_Suc mult.assoc mult.commute of_nat_id power_Suc2)\n    also have \"\\<dots> < card (f -` {a} \\<inter> F) * card A\" \n      using Suc(3) le by auto\n    also have \"f -` {a} \\<inter> F = {S \\<in> F. f S \\<in> {a}}\" by auto\n    also have \"card \\<dots> = card ((\\<lambda> S. S - {a}) ` {S \\<in> F. f S \\<in> {a}})\" \n      by (subst card_image; intro inj_onI refl, insert FaS) auto\n    also have \"(\\<lambda> S. S - {a}) ` {S \\<in> F. f S \\<in> {a}} = ?F\" by auto\n    finally have lt: \"(r - 1) ^ k * fact k < card ?F\" by simp\n    have \"\\<forall> A \\<in> ?F. finite A \\<and> card A = k\" using Suc(2) FaS by auto\n    from Suc(1)[OF this lt] obtain S\n      where \"sunflower S\" \"card S = r\" \"S \\<subseteq> ?F\" by auto\n    from \\<open>S \\<subseteq> ?F\\<close> FaS have \"S \\<subseteq> {A - {a} |A. A \\<in> F \\<and> a \\<in> A}\" by auto\n    from sunflower_remove_element_lift[OF this \\<open>sunflower S\\<close>] \\<open>card S = r\\<close>\n    show ?thesis by auto\n  qed\nqed\n\ntext \\<open>Using @{thm [source] sunflower_card_subset_lift} we can easily \n  replace the condition that the cardinality is exactly @{term k}\n  by the requirement that the cardinality is at most @{term k}. \n  However, then @{term \"{} \\<notin> S\"} cannot be ensured.\n  Consider @{term \"(r :: nat) = 1 \\<and> (k :: nat) > 0 \\<and> F = {{}}\"}.\\<close>\n\nlemma Erdos_Rado_sunflower: \n  assumes \"\\<forall> A \\<in> F. finite A \\<and> card A \\<le> k\" \n    and \"card F > (r - 1)^k * fact k\"\n  shows \"\\<exists> S. S \\<subseteq> F \\<and> sunflower S \\<and> card S = r\" \n  by (rule sunflower_card_subset_lift[OF _ assms], \n      metis Erdos_Rado_sunflower_same_card)\n\ntext \\<open>We further provide a lower bound on the existence of sunflowers, \ni.e., Exercise 6.2 of the textbook~\\cite{book}.\nTo be more precise, we prove that there is a set of sets of cardinality \n@{term \\<open>(r - 1 :: nat)^k\\<close>}, where each element is a set of cardinality \n@{term k}, such that there is no subset which is a sunflower with cardinality\nof at least @{term r}.\\<close>\n\nlemma sunflower_lower_bound:\n  assumes inf: \"infinite (UNIV :: 'a set)\" \n    and r: \"r \\<noteq> 0\"\n    and rk: \"r = 1 \\<Longrightarrow> k \\<noteq> 0\" \n  shows \"\\<exists> F. \n    card F = (r - 1)^k \\<and> finite F \\<and>\n    (\\<forall> A \\<in> F. finite (A :: 'a set) \\<and> card A = k) \\<and>\n    (\\<nexists> S. S \\<subseteq> F \\<and> sunflower S \\<and> card S \\<ge> r)\" \nproof (cases \"r = 1\")\n  case False\n  with r have r: \"r > 1\" by auto\n  show ?thesis\n  proof (induct k)\n    case 0\n    have id: \"S \\<subseteq> {{}} \\<longleftrightarrow> (S = {} \\<or> S = {{}})\" for S :: \"'a set set\" by auto \n    show ?case using r\n      by (intro exI[of _ \"{{}}\"], auto simp: id)\n  next\n    case (Suc k)\n    then obtain F where\n      cardF: \"card F = (r - 1) ^ k\" and\n      fin: \"finite F\" and\n      AF: \"\\<And> A. (A :: 'a set) \\<in> F \\<Longrightarrow> finite A \\<and> card A = k\" and\n      sf: \"\\<not> (\\<exists>S\\<subseteq>F. sunflower S \\<and> r \\<le> card S)\" \n      by metis\n    text \\<open>main idea: get @{term \"k-1 :: nat\"} fresh elements \n      and add one of these to all elements of F\\<close>\n    have \"finite (\\<Union> F)\" using fin AF by simp\n    hence \"infinite (UNIV - \\<Union> F)\" using inf by simp\n    from infinite_arbitrarily_large[OF this, of \"r - 1\"]\n    obtain New where New: \"finite New\" \"card New = r - 1\" \n      \"New \\<inter> \\<Union> F = {}\" by auto\n    define G where \"G = (\\<lambda> (A, a). insert a A) ` (F \\<times> New)\" \n    show ?case\n    proof (intro exI[of _ G] conjI)\n      show \"finite G\" using New fin unfolding G_def by simp\n      have \"card G = card (F \\<times> New)\" unfolding G_def\n      proof ((subst card_image; (intro refl)?), intro inj_onI, clarsimp, goal_cases)\n        case (1 A a B b)\n        hence ab: \"a = b\" using New by auto\n        from 1(1) have \"insert a A - {a} = insert b B - {a}\" by simp\n        also have \"insert a A - {a} = A\" using New 1 by auto\n        also have \"insert b B - {a} = B\" using New 1 ab[symmetric] by auto\n        finally show ?case using ab by auto\n      qed\n      also have \"\\<dots> = card F * card New\" using New fin by auto\n      finally show \"card G = (r - 1) ^ Suc k\" \n        unfolding cardF New by simp\n      {\n        fix B\n        assume \"B \\<in> G\" \n        then obtain a A where G: \"a \\<in> New\" \"A \\<in> F\" \"B = insert a A\" \n          unfolding G_def by auto\n        with AF[of A] New have \"finite B\" \"card B = Suc k\" \n          by (auto simp: card_insert_if)\n      }\n      thus \"\\<forall>A\\<in>G. finite A \\<and> card A = Suc k\" by auto\n      show \"\\<not> (\\<exists>S\\<subseteq>G. sunflower S \\<and> r \\<le> card S)\" \n      proof (intro notI, elim exE conjE)\n        fix S\n        assume *: \"S \\<subseteq> G\" \"sunflower S\" \"r \\<le> card S\"\n        define g where \"g B = (SOME a. a \\<in> New \\<and> a \\<in> B)\" for B\n        {\n          fix B\n          assume \"B \\<in> S\" \n          with \\<open>S \\<subseteq> G\\<close> have \"B \\<in> G\" by auto\n          hence \"\\<exists> a. a \\<in> New \\<and> a \\<in> B\" unfolding G_def by auto\n          from someI_ex[OF this, folded g_def]\n          have \"g B \\<in> New\" \"g B \\<in> B\" by auto\n        } note gB = this\n        have \"card (g ` S) \\<le> card New\" \n          by (rule card_mono, insert New gB, auto)\n        also have \"\\<dots> < r\" unfolding New using r by simp\n        also have \"\\<dots> \\<le> card S\" by fact\n        finally have \"card (g ` S) < card S\" .\n        from pigeonhole[OF this] have \"\\<not> inj_on g S\" .\n        then obtain B1 B2 where B12: \"B1 \\<in> S\" \"B2 \\<in> S\" \"B1 \\<noteq> B2\" \"g B1 = g B2\" \n          unfolding inj_on_def by auto\n        define a where \"a = g B2\" \n        from B12 gB[of B1] gB[of B2] have a: \"a \\<in> New\" \"a \\<in> B1\" \"a \\<in> B2\"\n          unfolding a_def by auto  \n        with B12 have \"\\<exists>B1 B2. B1 \\<in> S \\<and> B2 \\<in> S \\<and> B1 \\<noteq> B2 \\<and> a \\<in> B1 \\<and> a \\<in> B2\" \n          unfolding a_def by blast\n        from \\<open>sunflower S\\<close>[unfolded sunflower_def, rule_format, OF this]\n        have aS: \"B \\<in> S \\<Longrightarrow> a \\<in> B\" for B by auto\n        define h where \"h B = B - {a}\" for B\n        define T where \"T = h ` S\" \n        have \"\\<exists>S\\<subseteq>F. sunflower S \\<and> r \\<le> card S\" \n        proof (intro exI[of _ T] conjI)\n          {\n            fix B\n            assume \"B \\<in> S\" \n            have hB: \"h B = B - {a}\" \n              unfolding h_def T_def by auto\n            from aS \\<open>B \\<in> S\\<close> have aB: \"a \\<in> B\" by auto\n            from \\<open>B \\<in> S\\<close> \\<open>S \\<subseteq> G\\<close> obtain a' A where AF: \"A \\<in> F\" \n              and B: \"B = insert a' A\" \n              and a': \"a' \\<in> New\" unfolding G_def by force\n            from aB B a' New AF a(1) hB AF have \"insert a (h B) = B\" \"h B = A\" by auto\n            hence \"insert a (h B) = B\" \"h B \\<in> F\" \"insert a (h B) \\<in> S\" using AF \\<open>B \\<in> S\\<close> by auto\n          } note main = this\n          have CTS: \"C \\<in> T \\<Longrightarrow> insert a C \\<in> S\" for C using main unfolding T_def by force\n          show \"T \\<subseteq> F\" unfolding T_def using main by auto\n          have \"r \\<le> card S\" by fact\n          also have \"\\<dots> = card T\" unfolding T_def\n            by (subst card_image, intro inj_on_inverseI[of _ \"insert a\"], insert main, auto)\n          finally show \"r \\<le> card T\" .\n          show \"sunflower T\" unfolding sunflower_def\n          proof (intro allI impI, elim exE conjE, goal_cases)\n            case (1 x C C1 C2)\n            from CTS[OF \\<open>C1 \\<in> T\\<close>] CTS[OF \\<open>C2 \\<in> T\\<close>] CTS[OF \\<open>C \\<in> T\\<close>]\n            have *: \"insert a C1 \\<in> S\" \"insert a C2 \\<in> S\" \"insert a C \\<in> S\" by auto          \n            from 1 have \"insert a C1 \\<noteq> insert a C2\" using main\n              unfolding T_def by auto\n            hence \"\\<exists>A B. A \\<in> S \\<and> B \\<in> S \\<and> A \\<noteq> B \\<and> x \\<in> A \\<and> x \\<in> B\" \n              using * 1 by auto          \n            from \\<open>sunflower S\\<close>[unfolded sunflower_def, rule_format, OF this *(3)]\n            have \"x \\<in> insert a C\" .\n            with 1 show \"x \\<in> C\" unfolding T_def h_def by auto\n          qed\n        qed\n        with sf\n        show False ..\n      qed\n    qed\n  qed\nnext\n  case r: True\n  with rk have \"k \\<noteq> 0\" by auto\n  then obtain l where k: \"k = Suc l\" by (cases k, auto)\n  show ?thesis unfolding r k\n    by (intro exI[of _ \"{}\"], auto)\nqed\n\ntext \\<open>The difference between the lower and the\nupper bound on the existence of sunflowers as they have been formalized\nis @{term \\<open>fact k\\<close>}. There is more recent work with tighter bounds\n\\cite{sunflower_new}, but we only integrate the initial \nresult of Erd\u0151s and Rado in this theory.\\<close>\n\ntext \\<open>We further provide the Erd\u0151s Rado lemma \n  lifted to obtain non-empty cores or cores of arbitrary cardinality.\\<close>\n\nlemma Erdos_Rado_sunflower_card_core: \n  assumes \"finite E\" \n    and \"\\<forall> A \\<in> F. A \\<subseteq> E \\<and> s \\<le> card A \\<and> card A \\<le> k\" \n    and \"card F > (card E choose s) * (r - 1)^k * fact k\"\n    and \"s \\<noteq> 0\" \n    and \"r \\<noteq> 0\" \n  shows \"\\<exists> S. S \\<subseteq> F \\<and> sunflower S \\<and> card S = r \\<and> card (\\<Inter> S) \\<ge> s\" \n  by (rule sunflower_card_core_lift[OF assms(1) _ assms(2) _ assms(4-5), \n        of \"(r - 1)^k * fact k\"],\n      rule Erdos_Rado_sunflower, insert assms(3), auto simp: ac_simps)\n\nlemma Erdos_Rado_sunflower_nonempty_core: \n  assumes \"finite E\" \n    and \"\\<forall> A \\<in> F. A \\<subseteq> E \\<and> card A \\<le> k\" \n    and \"{} \\<notin> F\" \n    and \"card F > card E * (r - 1)^k * fact k\"\n  shows \"\\<exists> S. S \\<subseteq> F \\<and> sunflower S \\<and> card S = r \\<and> \\<Inter> S \\<noteq> {}\" \n  by (rule sunflower_nonempty_core_lift[OF assms(1) \n      _ assms(2-3), of \"(r - 1)^k * fact k\"],\n      rule Erdos_Rado_sunflower, insert assms(4), auto simp: ac_simps)\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/Sunflowers/Erdos_Rado_Sunflower.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8244619263765707, "lm_q2_score": 0.865224084314688, "lm_q1q2_score": 0.7133443153014921}}
{"text": "(* Author: R. Thiemann *)\n\nsubsection \\<open>Farkas Lemma for Matrices\\<close>\n\ntext \\<open>In this part we convert the simplex-structures like linear polynomials, etc., into\n  equivalent formulations using matrices and vectors. As a result we present Farkas' Lemma\n  via matrices and vectors.\\<close>\n\ntheory Matrix_Farkas\n  imports Farkas\n  Jordan_Normal_Form.Matrix\nbegin\n\nlift_definition poly_of_vec :: \"rat vec \\<Rightarrow> linear_poly\" is\n  \"\\<lambda> v x. if (x < dim_vec v) then v $ x else 0\" \n  by auto\n\ndefinition val_of_vec :: \"rat vec \\<Rightarrow> rat valuation\" where\n  \"val_of_vec v x = v $ x\" \n\nlemma valuate_poly_of_vec: assumes \"w \\<in> carrier_vec n\" \n  and \"v \\<in> carrier_vec n\"  \nshows \"valuate (poly_of_vec v) (val_of_vec w) = v \\<bullet> w\"  \n  using assms by (transfer, auto simp: val_of_vec_def scalar_prod_def intro: sum.mono_neutral_left)\n\ndefinition constraints_of_mat_vec :: \"rat mat \\<Rightarrow> rat vec \\<Rightarrow> rat le_constraint set\" where\n  \"constraints_of_mat_vec A b = (\\<lambda> i . Leqc (poly_of_vec (row A i)) (b $ i)) ` {0 ..< dim_row A}\" \n\nlemma constraints_of_mat_vec_solution_main: assumes A: \"A \\<in> carrier_mat nr nc\" \n  and x: \"x \\<in> carrier_vec nc\"\n  and b: \"b \\<in> carrier_vec nr\" \n  and sol: \"A *\\<^sub>v x \\<le> b\" \n  and c: \"c \\<in> constraints_of_mat_vec A b\" \nshows \"val_of_vec x \\<Turnstile>\\<^sub>l\\<^sub>e c\" \nproof -\n  from c[unfolded constraints_of_mat_vec_def] A obtain i where\n    i: \"i < nr\" and c: \"c = Leqc (poly_of_vec (row A i)) (b $ i)\" by auto\n  from i A have ri: \"row A i \\<in> carrier_vec nc\" by auto\n  from sol i A x b have sol: \"(A *\\<^sub>v x) $ i \\<le> b $ i\" unfolding less_eq_vec_def by auto\n  thus \"val_of_vec x \\<Turnstile>\\<^sub>l\\<^sub>e c\" unfolding c satisfiable_le_constraint.simps rel_of.simps\n      valuate_poly_of_vec[OF x ri] using A x i by auto\nqed\n\nlemma vars_poly_of_vec: \"vars (poly_of_vec v) \\<subseteq> { 0 ..< dim_vec v}\" \n  by (transfer', auto)\n\nlemma finite_constraints_of_mat_vec: \"finite (constraints_of_mat_vec A b)\" \n  unfolding constraints_of_mat_vec_def by auto\n\n\n\nlemma constraints_of_mat_vec_solution_1: \n  assumes A: \"A \\<in> carrier_mat nr nc\" \n    and b: \"b \\<in> carrier_vec nr\" \n    and sol: \"\\<exists> x \\<in> carrier_vec nc. A *\\<^sub>v x \\<le> b\" \n  shows \"\\<exists> v. \\<forall> c \\<in> constraints_of_mat_vec A b. v \\<Turnstile>\\<^sub>l\\<^sub>e c\" \n  using constraints_of_mat_vec_solution_main[OF A _ b _] sol by blast\n\nlemma constraints_of_mat_vec_solution_2: \n  assumes A: \"A \\<in> carrier_mat nr nc\" \n    and b: \"b \\<in> carrier_vec nr\" \n    and sol: \"\\<exists> v. \\<forall> c \\<in> constraints_of_mat_vec A b. v \\<Turnstile>\\<^sub>l\\<^sub>e c\" \n  shows \"\\<exists> x \\<in> carrier_vec nc. A *\\<^sub>v x \\<le> b\" \nproof -\n  from sol obtain v where sol: \"v \\<Turnstile>\\<^sub>l\\<^sub>e c\" if \"c \\<in> constraints_of_mat_vec A b\" for c by auto\n  define x where \"x = vec nc (\\<lambda> i. v i)\" \n  show ?thesis\n  proof (intro bexI[of _ x])\n    show x: \"x \\<in> carrier_vec nc\" unfolding x_def by auto\n    have \"row A i \\<bullet> x \\<le> b $ i\" if \"i < nr\" for i\n    proof -\n      from that have \"Leqc (poly_of_vec (row A i)) (b $ i) \\<in> constraints_of_mat_vec A b\" \n        unfolding constraints_of_mat_vec_def using A by auto\n      from sol[OF this, simplified] have \"valuate (poly_of_vec (row A i)) v \\<le> b $ i\" by simp\n      also have \"valuate (poly_of_vec (row A i)) v = valuate (poly_of_vec (row A i)) (val_of_vec x)\" \n        by (rule valuate_depend, insert A that, \n          auto simp: x_def val_of_vec_def dest!: set_mp[OF vars_poly_of_vec])\n      also have \"\\<dots> = row A i \\<bullet> x\" \n        by (subst valuate_poly_of_vec[OF x], insert that A x, auto)\n      finally show ?thesis .\n    qed\n    thus \"A *\\<^sub>v x \\<le> b\" unfolding less_eq_vec_def using x A b by auto\n  qed\nqed\n\nlemma constraints_of_mat_vec_solution: \n  assumes A: \"A \\<in> carrier_mat nr nc\" \n    and b: \"b \\<in> carrier_vec nr\" \n  shows \"(\\<exists> x \\<in> carrier_vec nc. A *\\<^sub>v x \\<le> b) = \n    (\\<exists> v. \\<forall> c \\<in> constraints_of_mat_vec A b. v \\<Turnstile>\\<^sub>l\\<^sub>e c)\" \n  using constraints_of_mat_vec_solution_1[OF assms] constraints_of_mat_vec_solution_2[OF assms]\n  by blast \n\nlemma farkas_lemma_matrix: fixes A :: \"rat mat\" \n  assumes A: \"A \\<in> carrier_mat nr nc\" \n  and b: \"b \\<in> carrier_vec nr\" \nshows \"(\\<exists> x \\<in> carrier_vec nc. A *\\<^sub>v x \\<le> b) \\<longleftrightarrow> \n  (\\<forall> y. y \\<ge> 0\\<^sub>v nr \\<longrightarrow> mat_of_row y * A = 0\\<^sub>m 1 nc \\<longrightarrow> y \\<bullet> b \\<ge> 0)\" \nproof -\n  define cs where \"cs = constraints_of_mat_vec A b\" \n  have fin: \"finite {0 ..< nr}\" by auto\n  have dim: \"dim_row A = nr\" using A by simp\n  have sum_id: \"(\\<Sum> i = 0..<nr. f i) = sum_list (map f [0..<nr])\" for f \n    by (subst sum_list_distinct_conv_sum_set, auto)\n  have \"(\\<exists> x \\<in> carrier_vec nc. A *\\<^sub>v x \\<le> b) =\n   (\\<not> (\\<nexists> v. \\<forall> c \\<in> cs. v \\<Turnstile>\\<^sub>l\\<^sub>e c))\" \n    unfolding constraints_of_mat_vec_solution[OF assms] cs_def by simp\n  also have \"\\<dots> = (\\<not> (\\<nexists>v. \\<forall>i\\<in>{0..<nr}. v \\<Turnstile>\\<^sub>l\\<^sub>e Le_Constraint Leq_Rel (poly_of_vec (row A i)) (b $ i)))\" \n    unfolding cs_def constraints_of_mat_vec_def dim by auto\n  also have \"\\<dots> = (\\<nexists>C.\n        (\\<forall>i\\<in>{0..<nr}. 0 \\<le> C i) \\<and>\n         (\\<Sum>i = 0..<nr. (C i *R poly_of_vec (row A i))) = 0 \\<and>\n         (\\<Sum>i = 0..<nr. (C i * b $ i)) < 0)\" \n    unfolding Farkas'_Lemma_indexed[OF \n        lec_rec_constraints_of_mat_vec[unfolded constraints_of_mat_vec_def], of A b,\n        unfolded dim, OF fin] sum_id sum_list_lec le_constraint.simps \n        sum_list_Leq_Rel map_map o_def unfolding sum_id[symmetric] by simp\n  also have \"\\<dots> = (\\<forall> C. (\\<forall>i\\<in> {0..<nr}. 0 \\<le> C i) \\<longrightarrow> \n         (\\<Sum>i = 0..<nr. (C i *R poly_of_vec (row A i))) = 0 \\<longrightarrow>\n         (\\<Sum>i = 0..<nr. (C i * b $ i)) \\<ge> 0)\" \n    using not_less by blast\n  also have \"\\<dots> = (\\<forall> y. y \\<ge> 0\\<^sub>v nr \\<longrightarrow> mat_of_row y * A = 0\\<^sub>m 1 nc \\<longrightarrow> y \\<bullet> b \\<ge> 0)\"\n  proof ((standard; intro allI impI), goal_cases)\n    case *: (1 y)\n    define C where \"C = (\\<lambda> i. y $ i)\" \n    note main = *(1)[rule_format, of C]\n    from *(2) have y: \"y \\<in> carrier_vec nr\" and nonneg: \"\\<And>i. i \\<in> {0..<nr} \\<Longrightarrow> 0 \\<le> C i\" \n      unfolding less_eq_vec_def C_def by auto\n    have sum_0: \"(\\<Sum>i = 0..<nr. C i *R poly_of_vec (row A i)) = 0\" unfolding C_def\n      unfolding zero_coeff_zero coeff_sum \n    proof\n      fix v\n      have \"(\\<Sum>i = 0..<nr. coeff (y $ i *R poly_of_vec (row A i)) v) = \n            (\\<Sum>i < nr. y $ i * coeff (poly_of_vec (row A i)) v)\" by (rule sum.cong, auto)\n      also have \"\\<dots> = 0\" \n      proof (cases \"v < nc\")\n        case False\n        have \"(\\<Sum>i < nr. y $ i * coeff (poly_of_vec (row A i)) v) = \n              (\\<Sum>i < nr. y $ i * 0)\" \n          by (rule sum.cong[OF refl], rule arg_cong[of _ _ \"\\<lambda> x. _ * x\"], insert A False, transfer, auto)\n        also have \"\\<dots> = 0\" by simp\n        finally show ?thesis by simp\n      next\n        case True\n        have \"(\\<Sum>i<nr. y $ i * coeff (poly_of_vec (row A i)) v) =\n              (\\<Sum>i<nr. y $ i * row A i $ v)\" \n          by (rule sum.cong[OF refl], rule arg_cong[of _ _ \"\\<lambda> x. _ * x\"], insert A True, transfer, auto)\n        also have \"\\<dots> = (mat_of_row y * A) $$ (0,v)\" \n          unfolding times_mat_def scalar_prod_def\n          using A y True by (auto intro: sum.cong)\n        also have \"\\<dots> = 0\" unfolding *(3) using True by simp\n        finally show ?thesis .\n      qed\n      finally show \"(\\<Sum>i = 0..<nr. coeff (y $ i *R poly_of_vec (row A i)) v) = 0\" .\n    qed\n    from main[OF nonneg sum_0] have le: \"0 \\<le> (\\<Sum>i = 0..<nr. C i * b $ i)\" .\n    thus ?case using y b unfolding scalar_prod_def C_def by auto\n  next\n    case *: (2 C)\n    define y where \"y = vec nr C\" \n    have y: \"y \\<in> carrier_vec nr\" unfolding y_def by auto\n    note main = *(1)[rule_format, of y]\n    from *(2) have y0: \"y \\<ge> 0\\<^sub>v nr\" unfolding less_eq_vec_def y_def by auto\n    have prod0: \"mat_of_row y * A = 0\\<^sub>m 1 nc\" \n    proof -\n      {\n        fix j\n        assume j: \"j < nc\"\n        from arg_cong[OF *(3), of \"\\<lambda> x. coeff x j\", unfolded coeff_sum]\n        have \"0 = (\\<Sum>i = 0..<nr. C i * coeff (poly_of_vec (row A i)) j)\" by simp\n        also have \"\\<dots> = (\\<Sum>i = 0..<nr. C i * row A i $ j)\" \n          by (rule sum.cong[OF refl], rule arg_cong[of _ _ \"\\<lambda> x. _ * x\"], insert A j, transfer, auto)\n        also have \"\\<dots> = y \\<bullet> col A j\" unfolding scalar_prod_def y_def using A j \n          by (intro sum.cong, auto)\n        finally have \"y \\<bullet> col A j = 0\" by simp\n      }\n      thus ?thesis by (intro eq_matI, insert A y, auto)\n    qed\n    from main[OF y0 prod0] have \"0 \\<le> y \\<bullet> b\" .\n    thus ?case unfolding scalar_prod_def y_def using b by auto\n  qed\n  finally show ?thesis .\nqed\n\nlemma farkas_lemma_matrix': fixes A :: \"rat mat\" \n  assumes A: \"A \\<in> carrier_mat nr nc\" \n  and b: \"b \\<in> carrier_vec nr\" \nshows \"(\\<exists> x \\<ge> 0\\<^sub>v nc. A *\\<^sub>v x = b) \\<longleftrightarrow> \n  (\\<forall> y \\<in> carrier_vec nr. mat_of_row y * A \\<ge> 0\\<^sub>m 1 nc \\<longrightarrow> y \\<bullet> b \\<ge> 0)\" \nproof -\n  define B where \"B = (- 1\\<^sub>m nc) @\\<^sub>r (A @\\<^sub>r -A)\"   \n  define b' where \"b' = 0\\<^sub>v nc @\\<^sub>v (b @\\<^sub>v -b)\" \n  define n where \"n = nc + (nr + nr)\" \n  have id0: \"0\\<^sub>v (nc + (nr + nr)) = 0\\<^sub>v nc @\\<^sub>v (0\\<^sub>v nr @\\<^sub>v 0\\<^sub>v nr)\" by (intro eq_vecI, auto)\n  have B: \"B \\<in> carrier_mat n nc\" unfolding B_def n_def using A by auto\n  have b': \"b' \\<in> carrier_vec n\" unfolding b'_def n_def using b by auto\n  have \"(\\<exists> x \\<ge> 0\\<^sub>v nc. A *\\<^sub>v x = b) = (\\<exists> x. x \\<in> carrier_vec nc \\<and> x \\<ge> 0\\<^sub>v nc \\<and> A *\\<^sub>v x = b)\" \n    by (rule arg_cong[of _ _ Ex], intro ext, insert A b, auto simp: less_eq_vec_def)\n  also have \"\\<dots> = (\\<exists> x \\<in> carrier_vec nc. x \\<ge> 0\\<^sub>v nc \\<and> A *\\<^sub>v x = b)\" by blast\n  also have \"\\<dots> = (\\<exists> x \\<in> carrier_vec nc. 1\\<^sub>m nc *\\<^sub>v x \\<ge> 0\\<^sub>v nc \\<and> A *\\<^sub>v x \\<le> b \\<and> A *\\<^sub>v x \\<ge> b)\" \n    by (rule bex_cong[OF refl], insert A b, auto)\n  also have \"\\<dots> = (\\<exists> x \\<in> carrier_vec nc. (- 1\\<^sub>m nc) *\\<^sub>v x \\<le> 0\\<^sub>v nc \\<and> A *\\<^sub>v x \\<le> b \\<and> (- A) *\\<^sub>v x \\<le> -b)\" \n    by (rule bex_cong[OF refl], insert A b, auto simp: less_eq_vec_def)\n  also have \"\\<dots> = (\\<exists> x \\<in> carrier_vec nc. B *\\<^sub>v x \\<le> b')\"\n    by (rule bex_cong[OF refl], insert A b, unfold B_def b'_def, \n      subst append_rows_le[of _ ], (auto)[4], intro conj_cong[OF refl], subst append_rows_le, auto)\n  also have \"\\<dots> = (\\<forall>y\\<ge>0\\<^sub>v n. mat_of_row y * B = 0\\<^sub>m 1 nc \\<longrightarrow> y \\<bullet> b' \\<ge> 0)\"   \n    by (rule farkas_lemma_matrix[OF B b'])\n  also have \"\\<dots> = (\\<forall> y. y \\<in> carrier_vec n \\<longrightarrow> y\\<ge>0\\<^sub>v n \\<longrightarrow> mat_of_row y * B = 0\\<^sub>m 1 nc \\<longrightarrow> y \\<bullet> b' \\<ge> 0)\"\n    by (intro arg_cong[of _ _ All], intro ext, auto simp: less_eq_vec_def)\n  also have \"\\<dots> = (\\<forall> y \\<in> carrier_vec n. y\\<ge>0\\<^sub>v n \\<longrightarrow> mat_of_row y * B = 0\\<^sub>m 1 nc \\<longrightarrow> y \\<bullet> b' \\<ge> 0)\"\n    by blast\n  also have \"\\<dots> = (\\<forall>y1 \\<in>carrier_vec nc. \\<forall>y2 \\<in>carrier_vec nr. \\<forall>y3 \\<in>carrier_vec nr.\n              0\\<^sub>v nc @\\<^sub>v (0\\<^sub>v nr @\\<^sub>v 0\\<^sub>v nr) \\<le> y1 @\\<^sub>v y2 @\\<^sub>v y3  \\<longrightarrow>\n              mat_of_row (y1 @\\<^sub>v y2 @\\<^sub>v y3) * ((- 1\\<^sub>m nc) @\\<^sub>r (A @\\<^sub>r -A)) = 0\\<^sub>m 1 nc \n              \\<longrightarrow> 0 \\<le> (y1 @\\<^sub>v y2 @\\<^sub>v y3) \\<bullet> (0\\<^sub>v nc @\\<^sub>v (b @\\<^sub>v -b)))\" \n    unfolding n_def all_vec_append id0 b'_def B_def by auto\n  also have \"\\<dots> = (\\<forall>y1 \\<in>carrier_vec nc. \\<forall>y2 \\<in>carrier_vec nr. \\<forall>y3 \\<in>carrier_vec nr.\n              0\\<^sub>v nc \\<le> y1 \\<longrightarrow> 0\\<^sub>v nr \\<le> y2 \\<longrightarrow> 0\\<^sub>v nr \\<le> y3 \\<longrightarrow>\n              (- mat_of_row y1) + \n              (mat_of_row y2 * A - (mat_of_row y3 * A)) = 0\\<^sub>m 1 nc \n              \\<longrightarrow> y2 \\<bullet> b - y3 \\<bullet> b \\<ge> 0)\"\n    by (intro ball_cong[OF refl], subst append_vec_le, (auto)[2], subst append_vec_le, (auto)[2], insert A b,\n      subst scalar_prod_append, (auto)[4], subst scalar_prod_append, (auto)[4], \n      subst mat_of_row_mult_append_rows, (auto)[4],\n      subst mat_of_row_mult_append_rows, (auto)[4],\n      subst add_uminus_minus_mat[symmetric], auto)\n  also have \"\\<dots> = (\\<forall>y1 \\<in>carrier_vec nc. \\<forall>y2 \\<in>carrier_vec nr. \\<forall>y3 \\<in>carrier_vec nr.\n              0\\<^sub>v nc \\<le> y1 \\<longrightarrow> 0\\<^sub>v nr \\<le> y2 \\<longrightarrow> 0\\<^sub>v nr \\<le> y3 \\<longrightarrow>\n              mat_of_row y1 = mat_of_row y2 * A - mat_of_row y3 * A\n              \\<longrightarrow> y2 \\<bullet> b - y3 \\<bullet> b \\<ge> 0)\"\n  proof ((intro ball_cong[OF refl] arg_cong2[of _ _ _ _ \"(\\<longrightarrow>)\"] refl, standard), goal_cases)\n    case (1 y1 y2 y3)\n    from arg_cong[OF 1(4), of \"\\<lambda> x. mat_of_row y1 + x\"] show ?case using 1(1-3) A\n      by (subst (asm) assoc_add_mat[symmetric], (auto)[3],\n        subst (asm) add_uminus_minus_mat, (auto)[1],\n        subst (asm) minus_r_inv_mat, force,\n        subst (asm) right_add_zero_mat, force,\n        subst (asm) left_add_zero_mat, force, auto)\n  next\n    case (2 y1 y2 y3)\n    show ?case unfolding 2(4) using 2(1-3) A\n      by (intro eq_matI, auto)\n  qed\n  also have \"\\<dots> = (\\<forall>y1 \\<in>carrier_vec nc. \\<forall>y2 \\<in>carrier_vec nr. \\<forall>y3 \\<in>carrier_vec nr.\n              0\\<^sub>v nc \\<le> y1 \\<longrightarrow> 0\\<^sub>v nr \\<le> y2 \\<longrightarrow> 0\\<^sub>v nr \\<le> y3 \\<longrightarrow>\n              mat_of_row y1 = mat_of_row (y2 - y3) * A\n              \\<longrightarrow> (y2 - y3) \\<bullet> b \\<ge> 0)\"\n    by (intro ball_cong[OF refl] imp_cong refl \n      arg_cong2[of _ _ _ _ \"(\\<le>)\"] arg_cong2[of _ _ _ _ \"(=)\"],\n      subst minus_mult_distrib_mat[symmetric], insert A b, auto\n      simp: minus_scalar_prod_distrib mat_of_rows_def \n      intro!: arg_cong[of _ _ \"\\<lambda> x. x * _\"])\n  also have \"\\<dots> = (\\<forall>y1 \\<in>carrier_vec nc. \\<forall>y2 \\<in>carrier_vec nr. \\<forall>y3 \\<in>carrier_vec nr.\n              0\\<^sub>v nc \\<le> y1 \\<longrightarrow> 0\\<^sub>v nr \\<le> y2 \\<longrightarrow> 0\\<^sub>v nr \\<le> y3 \\<longrightarrow>\n              y1 = row (mat_of_row (y2 - y3) * A) 0\n              \\<longrightarrow> (y2 - y3) \\<bullet> b \\<ge> 0)\"\n  proof (intro ball_cong[OF refl] arg_cong2[of _ _ _ _ \"(\\<longrightarrow>)\"] refl, standard, goal_cases)\n    case (1 y1 y2 y3)\n    from arg_cong[OF 1(4), of \"\\<lambda> x. row x 0\"] 1(1-3) A\n    show ?case by auto\n  qed (insert A, auto)\n  also have \"\\<dots> = (\\<forall>y2 \\<in>carrier_vec nr. \\<forall>y3 \\<in>carrier_vec nr.\n              0\\<^sub>v nc \\<le> row (mat_of_row (y2 - y3) * A) 0 \\<longrightarrow> 0\\<^sub>v nr \\<le> y2 \\<longrightarrow> 0\\<^sub>v nr \\<le> y3 \\<longrightarrow>\n              row (mat_of_row (y2 - y3) * A) 0 \\<in> carrier_vec nc\n              \\<longrightarrow> (y2 - y3) \\<bullet> b \\<ge> 0)\" by blast\n  also have \"\\<dots> = (\\<forall>y2 \\<in>carrier_vec nr. \\<forall>y3 \\<in>carrier_vec nr.\n              0\\<^sub>v nc \\<le> row (mat_of_row (y2 - y3) * A) 0 \\<longrightarrow> 0\\<^sub>v nr \\<le> y2 \\<longrightarrow> 0\\<^sub>v nr \\<le> y3 \n              \\<longrightarrow> (y2 - y3) \\<bullet> b \\<ge> 0)\"\n    by (intro ball_cong[OF refl] arg_cong2[of _ _ _ _ \"(\\<longrightarrow>)\"] refl, insert A,\n        auto simp: row_def)\n  also have \"\\<dots> = (\\<forall> y \\<in> carrier_vec nr. row (mat_of_row y * A) 0 \\<ge> 0\\<^sub>v nc \\<longrightarrow> y \\<bullet> b \\<ge> 0)\" \n  proof ((standard; intro ballI impI), goal_cases)\n    case (1 y)\n    define y2 where \"y2 = vec nr (\\<lambda> i. if y $ i \\<ge> 0 then y $ i else 0)\" \n    define y3 where \"y3 = vec nr (\\<lambda> i. if y $ i \\<ge> 0 then 0 else - y $ i)\" \n    have y: \"y = y2 - y3\" unfolding y2_def y3_def using 1(2)\n      by (intro eq_vecI, auto)\n    show ?case by (rule 1(1)[rule_format, of y2 y3, folded y, OF _ _ 1(3)],\n       auto simp: y2_def y3_def less_eq_vec_def)\n  qed auto\n  also have \"\\<dots> = (\\<forall> y \\<in> carrier_vec nr. mat_of_row y * A \\<ge> 0\\<^sub>m 1 nc \\<longrightarrow> y \\<bullet> b \\<ge> 0)\"\n    by (intro ball_cong arg_cong2[of _ _ _ _ \"(\\<longrightarrow>)\"] refl,\n      insert A, auto simp: less_eq_vec_def less_eq_mat_def)\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/Farkas/Matrix_Farkas.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8652240825770433, "lm_q2_score": 0.8244619220634456, "lm_q1q2_score": 0.7133443101370505}}
{"text": "(*\n  Theory: Density_Predicates.thy\n  Authors: Manuel Eberl\n*)\n\nsection \\<open>Density Predicates\\<close>\n\ntheory Density_Predicates\nimports \"HOL-Probability.Probability\"\nbegin\n\nsubsection \\<open>Probability Densities\\<close>\n\ndefinition is_subprob_density :: \"'a measure \\<Rightarrow> ('a \\<Rightarrow> ennreal) \\<Rightarrow> bool\" where\n  \"is_subprob_density M f \\<equiv> (f \\<in> borel_measurable M) \\<and> space M \\<noteq> {} \\<and>\n                           (\\<forall>x\\<in>space M. f x \\<ge> 0) \\<and> (\\<integral>\\<^sup>+x. f x \\<partial>M) \\<le> 1\"\n\nlemma is_subprob_densityI[intro]:\n    \"\\<lbrakk>f \\<in> borel_measurable M; \\<And>x. x \\<in> space M \\<Longrightarrow> f x \\<ge> 0; space M \\<noteq> {}; (\\<integral>\\<^sup>+x. f x \\<partial>M) \\<le> 1\\<rbrakk>\n        \\<Longrightarrow> is_subprob_density M f\"\n  unfolding is_subprob_density_def by simp\n\n\n\nsubsection \\<open>Measure spaces with densities\\<close>\n\ndefinition has_density :: \"'a measure \\<Rightarrow> 'a measure \\<Rightarrow> ('a \\<Rightarrow> ennreal) \\<Rightarrow> bool\" where\n  \"has_density M N f \\<longleftrightarrow> (f \\<in> borel_measurable N) \\<and> space N \\<noteq> {} \\<and> M = density N f\"\n\nlemma has_densityI[intro]:\n  \"\\<lbrakk>f \\<in> borel_measurable N; M = density N f; space N \\<noteq> {}\\<rbrakk> \\<Longrightarrow> has_density M N f\"\n  unfolding has_density_def by blast\n\nlemma has_densityD:\n  assumes \"has_density M N f\"\n  shows \"f \\<in> borel_measurable N\" \"M = density N f\" \"space N \\<noteq> {}\"\nusing assms unfolding has_density_def by simp_all\n\n\nlemma has_density_sets: \"has_density M N f \\<Longrightarrow> sets M = sets N\"\n  unfolding has_density_def by simp\n\nlemma has_density_space: \"has_density M N f \\<Longrightarrow> space M = space N\"\n  unfolding has_density_def by simp\n\nlemma has_density_emeasure:\n    \"has_density M N f \\<Longrightarrow> X \\<in> sets M \\<Longrightarrow> emeasure M X = \\<integral>\\<^sup>+x. f x * indicator X x \\<partial>N\"\n  unfolding has_density_def by (simp_all add: emeasure_density)\n\nlemma nn_integral_cong': \"(\\<And>x. x \\<in> space N =simp=> f x = g x) \\<Longrightarrow> (\\<integral>\\<^sup>+x. f x \\<partial>N) = (\\<integral>\\<^sup>+x. g x \\<partial>N)\"\n  by (simp add: simp_implies_def cong: nn_integral_cong)\n\nlemma has_density_emeasure_space:\n    \"has_density M N f \\<Longrightarrow> emeasure M (space M) = (\\<integral>\\<^sup>+x. f x \\<partial>N)\"\n  by (simp add: has_density_emeasure) (simp add: has_density_space cong: nn_integral_cong')\n\nlemma has_density_emeasure_space':\n    \"has_density M N f \\<Longrightarrow> emeasure (density N f) (space (density N f)) = \\<integral>\\<^sup>+x. f x \\<partial>N\"\n  by (frule has_densityD(2)[symmetric]) (simp add: has_density_emeasure_space)\n\nlemma has_density_imp_is_subprob_density:\n    \"\\<lbrakk>has_density M N f; (\\<integral>\\<^sup>+x. f x \\<partial>N) = 1\\<rbrakk> \\<Longrightarrow> is_subprob_density N f\"\n  by (auto dest: has_densityD)\n\nlemma has_density_imp_is_subprob_density':\n    \"\\<lbrakk>has_density M N f; prob_space M\\<rbrakk> \\<Longrightarrow> is_subprob_density N f\"\n  by (auto intro!: has_density_imp_is_subprob_density dest: prob_space.emeasure_space_1\n           simp: has_density_emeasure_space)\n\nlemma has_density_equal_on_space:\n  assumes \"has_density M N f\" \"\\<And>x. x \\<in> space N \\<Longrightarrow> f x = g x\"\n  shows \"has_density M N g\"\nproof\n  from assms show \"g \\<in> borel_measurable N\"\n    by (subst measurable_cong[of _ _ f]) (auto dest: has_densityD)\n  with assms show \"M = density N g\"\n    by (subst density_cong[of _ _ f]) (auto dest: has_densityD)\n  from assms(1) show \"space N \\<noteq> {}\" by (rule has_densityD)\nqed\n\nlemma has_density_cong:\n  assumes \"\\<And>x. x \\<in> space N \\<Longrightarrow> f x = g x\"\n  shows \"has_density M N f = has_density M N g\"\nusing assms by (intro iffI) (erule has_density_equal_on_space, simp)+\n\nlemma has_density_dens_AE:\n    \"\\<lbrakk>AE y in N. f y = f' y; f' \\<in> borel_measurable N;\n      \\<And>x. x \\<in> space M \\<Longrightarrow> f' x \\<ge> 0; has_density M N f\\<rbrakk>\n        \\<Longrightarrow> has_density M N f'\"\n  unfolding has_density_def by (simp cong: density_cong)\n\n\nsubsection \\<open>Probability spaces with densities\\<close>\n\nlemma is_subprob_density_imp_has_density:\n    \"\\<lbrakk>is_subprob_density N f; M = density N f\\<rbrakk> \\<Longrightarrow> has_density M N f\"\n  by (rule has_densityI) auto\n\nlemma has_subprob_density_imp_subprob_space':\n    \"\\<lbrakk>has_density M N f; is_subprob_density N f\\<rbrakk> \\<Longrightarrow> subprob_space M\"\nproof (rule subprob_spaceI)\n  assume \"has_density M N f\"\n  hence \"M = density N f\" by (simp add: has_density_def)\n  also from \\<open>has_density M N f\\<close> have \"space ... \\<noteq> {}\" by (simp add: has_density_def)\n  finally show \"space M \\<noteq> {}\" .\nqed (auto simp add: has_density_emeasure_space dest: has_densityD)\n\nlemma has_subprob_density_imp_subprob_space[dest]:\n    \"is_subprob_density M f \\<Longrightarrow> subprob_space (density M f)\"\n  by (rule has_subprob_density_imp_subprob_space') auto\n\ndefinition \"has_subprob_density M N f \\<equiv> has_density M N f \\<and> subprob_space M\"\n\n(* TODO: Move *)\nlemma subprob_space_density_not_empty: \"subprob_space (density M f) \\<Longrightarrow> space M \\<noteq> {}\"\n  by (subst space_density[symmetric], subst subprob_space.subprob_not_empty, assumption) simp\n\n\n\nlemma has_subprob_densityI':\n  assumes \"f \\<in> borel_measurable N\" \"space N \\<noteq> {}\"\n          \"M = density N f\" \"(\\<integral>\\<^sup>+x. f x \\<partial>N) \\<le> 1\"\n  shows \"has_subprob_density M N f\"\nproof-\n  from assms have D: \"has_density M N f\" by blast\n  moreover from D and assms have \"subprob_space M\"\n    by (auto intro!: subprob_spaceI simp: has_density_emeasure_space emeasure_density\n             cong: nn_integral_cong')\n  ultimately show ?thesis unfolding has_subprob_density_def by simp\nqed\n\nlemma has_subprob_densityD:\n  assumes \"has_subprob_density M N f\"\n  shows \"f \\<in> borel_measurable N\" \"\\<And>x. x \\<in> space N \\<Longrightarrow> f x \\<ge> 0\" \"M = density N f\" \"subprob_space M\"\nusing assms unfolding has_subprob_density_def by (auto dest: has_densityD)\n\nlemma has_subprob_density_measurable[measurable_dest]:\n  \"has_subprob_density M N f \\<Longrightarrow> f \\<in> N \\<rightarrow>\\<^sub>M borel\"\n  by (auto dest: has_subprob_densityD)\n\nlemma has_subprob_density_imp_has_density:\n  \"has_subprob_density M N f \\<Longrightarrow> has_density M N f\" by (simp add: has_subprob_density_def)\n\nlemma has_subprob_density_equal_on_space:\n  assumes \"has_subprob_density M N f\" \"\\<And>x. x \\<in> space N \\<Longrightarrow> f x = g x\"\n  shows \"has_subprob_density M N g\"\nusing assms unfolding has_subprob_density_def by (auto dest: has_density_equal_on_space)\n\nlemma has_subprob_density_cong:\n  assumes \"\\<And>x. x \\<in> space N \\<Longrightarrow> f x = g x\"\n  shows \"has_subprob_density M N f = has_subprob_density M N g\"\nusing assms by (intro iffI) (erule has_subprob_density_equal_on_space, simp)+\n\nlemma has_subprob_density_dens_AE:\n    \"\\<lbrakk>AE y in N. f y = f' y; f' \\<in> borel_measurable N;\n      \\<And>x. x \\<in> space M \\<Longrightarrow> f' x \\<ge> 0; has_subprob_density M N f\\<rbrakk>\n      \\<Longrightarrow> has_subprob_density M N f'\"\n  unfolding has_subprob_density_def by (simp add: has_density_dens_AE)\n\n\nsubsection \\<open>Parametrized probability densities\\<close>\n\ndefinition\n  \"has_parametrized_subprob_density M N R f \\<equiv>\n       (\\<forall>x \\<in> space M. has_subprob_density (N x) R (f x)) \\<and> case_prod f \\<in> borel_measurable (M \\<Otimes>\\<^sub>M R)\"\n\nlemma has_parametrized_subprob_densityI:\n  assumes \"\\<And>x. x \\<in> space M \\<Longrightarrow> N x = density R (f x)\"\n  assumes \"\\<And>x. x \\<in> space M \\<Longrightarrow> subprob_space (N x)\"\n  assumes \"case_prod f \\<in> borel_measurable (M \\<Otimes>\\<^sub>M R)\"\n  shows \"has_parametrized_subprob_density M N R f\"\n  unfolding has_parametrized_subprob_density_def using assms\n  by (intro ballI conjI has_subprob_densityI) simp_all\n\nlemma has_parametrized_subprob_densityD:\n  assumes \"has_parametrized_subprob_density M N R f\"\n  shows \"\\<And>x. x \\<in> space M \\<Longrightarrow> N x = density R (f x)\"\n    and \"\\<And>x. x \\<in> space M \\<Longrightarrow> subprob_space (N x)\"\n    and [measurable_dest]: \"case_prod f \\<in> borel_measurable (M \\<Otimes>\\<^sub>M R)\"\n  using assms unfolding has_parametrized_subprob_density_def\n  by (auto dest: has_subprob_densityD)\n\nlemma has_parametrized_subprob_density_integral:\n  assumes \"has_parametrized_subprob_density M N R f\" \"x \\<in> space M\"\n  shows \"(\\<integral>\\<^sup>+y. f x y \\<partial>R) \\<le> 1\"\nproof-\n  have \"(\\<integral>\\<^sup>+y. f x y \\<partial>R) = emeasure (density R (f x)) (space (density R (f x)))\" using assms\n    by (auto simp: emeasure_density cong: nn_integral_cong' dest: has_parametrized_subprob_densityD)\n  also have \"density R (f x) = (N x)\" using assms by (auto dest: has_parametrized_subprob_densityD)\n  also have \"emeasure ... (space ...) \\<le> 1\" using assms\n    by (subst subprob_space.emeasure_space_le_1) (auto dest: has_parametrized_subprob_densityD)\n  finally show ?thesis .\nqed\n\nlemma has_parametrized_subprob_density_cong:\n  assumes \"\\<And>x. x \\<in> space M \\<Longrightarrow> N x = N' x\"\n  shows \"has_parametrized_subprob_density M N R f = has_parametrized_subprob_density M N' R f\"\nusing assms unfolding has_parametrized_subprob_density_def by auto\n\nlemma has_parametrized_subprob_density_dens_AE:\n  assumes \"\\<And>x. x \\<in> space M \\<Longrightarrow> AE y in R. f x y = f' x y\"\n          \"case_prod f' \\<in> borel_measurable (M \\<Otimes>\\<^sub>M R)\"\n          \"has_parametrized_subprob_density M N R f\"\n  shows   \"has_parametrized_subprob_density M N R f'\"\nunfolding has_parametrized_subprob_density_def\nproof (intro conjI ballI)\n  fix x assume x: \"x \\<in> space M\"\n  with assms(3) have \"space (N x) = space R\"\n    by (auto dest!: has_parametrized_subprob_densityD(1))\n  with assms and x show \"has_subprob_density (N x) R (f' x)\"\n    by (rule_tac has_subprob_density_dens_AE[of \"f x\"])\n       (auto simp: has_parametrized_subprob_density_def)\nqed fact\n\n\nsubsection \\<open>Density in the Giry monad\\<close>\n\nlemma emeasure_bind_density:\n  assumes \"space M \\<noteq> {}\" \"\\<And>x. x \\<in> space M \\<Longrightarrow> has_density (f x) N (g x)\"\n          \"f \\<in> measurable M (subprob_algebra N)\" \"X \\<in> sets N\"\n  shows \"emeasure (M \\<bind> f) X = \\<integral>\\<^sup>+x. \\<integral>\\<^sup>+y. g x y * indicator X y \\<partial>N \\<partial>M\"\nproof-\n  from assms have \"emeasure (M \\<bind> f) X = \\<integral>\\<^sup>+x. emeasure (f x) X \\<partial>M\"\n    by (intro emeasure_bind)\n  also have \"... = \\<integral>\\<^sup>+x. \\<integral>\\<^sup>+y. g x y * indicator X y \\<partial>N \\<partial>M\" using assms\n    by (intro nn_integral_cong) (simp add: has_density_emeasure sets_kernel)\n  finally show ?thesis .\nqed\n\nlemma bind_density:\n  assumes \"sigma_finite_measure M\" \"sigma_finite_measure N\"\n          \"space M \\<noteq> {}\" \"\\<And>x. x \\<in> space M \\<Longrightarrow> has_density (f x) N (g x)\"\n     and [measurable]: \"case_prod g \\<in> borel_measurable (M \\<Otimes>\\<^sub>M N)\" \"f \\<in> measurable M (subprob_algebra N)\"\n  shows \"(M \\<bind> f) = density N (\\<lambda>y. \\<integral>\\<^sup>+x. g x y \\<partial>M)\"\nproof (rule measure_eqI)\n  interpret sfN: sigma_finite_measure N by fact\n  interpret sfNM: pair_sigma_finite N M unfolding pair_sigma_finite_def using assms by simp\n  show eq: \"sets (M \\<bind> f) = sets (density N (\\<lambda>y. \\<integral>\\<^sup>+x. g x y \\<partial>M))\"\n    using sets_bind[OF sets_kernel[OF assms(6)] assms(3)] by auto\n  fix X assume \"X \\<in> sets (M \\<bind> f)\"\n  with eq have [measurable]: \"X \\<in> sets N\" by auto\n  with assms have \"emeasure (M \\<bind> f) X = \\<integral>\\<^sup>+x. \\<integral>\\<^sup>+y. g x y * indicator X y \\<partial>N \\<partial>M\"\n    by (intro emeasure_bind_density) simp_all\n  also from \\<open>X \\<in> sets N\\<close> have \"... = \\<integral>\\<^sup>+y. \\<integral>\\<^sup>+x. g x y * indicator X y \\<partial>M \\<partial>N\"\n    by (intro sfNM.Fubini') measurable\n  also {\n    fix y assume \"y \\<in> space N\"\n    have \"(\\<lambda>x. g x y) = case_prod g \\<circ> (\\<lambda>x. (x, y))\" by (rule ext) simp\n    also from \\<open>y \\<in> space N\\<close> have \"... \\<in> borel_measurable M\"\n      by (intro measurable_comp[OF _ assms(5)] measurable_Pair2')\n    finally have \"(\\<lambda>x. g x y) \\<in> borel_measurable M\" .\n  }\n  hence \"... = \\<integral>\\<^sup>+y. (\\<integral>\\<^sup>+x. g x y \\<partial>M) * indicator X y \\<partial>N\"\n    by (intro nn_integral_cong nn_integral_multc)  simp_all\n  also from \\<open>X \\<in> sets N\\<close> and assms have \"... = emeasure (density N (\\<lambda>y. \\<integral>\\<^sup>+x. g x y \\<partial>M)) X\"\n    by (subst emeasure_density) (simp_all add: sfN.borel_measurable_nn_integral)\n  finally show \"emeasure (M \\<bind> f) X = emeasure (density N (\\<lambda>y. \\<integral>\\<^sup>+x. g x y \\<partial>M)) X\" .\nqed\n\n\nlemma bind_has_density:\n  assumes \"sigma_finite_measure M\" \"sigma_finite_measure N\"\n          \"space M \\<noteq> {}\" \"\\<And>x. x \\<in> space M \\<Longrightarrow> has_density (f x) N (g x)\"\n          \"case_prod g \\<in> borel_measurable (M \\<Otimes>\\<^sub>M N)\"\n          \"f \\<in> measurable M (subprob_algebra N)\"\n  shows \"has_density (M \\<bind> f) N (\\<lambda>y. \\<integral>\\<^sup>+x. g x y \\<partial>M)\"\nproof\n  interpret sigma_finite_measure M by fact\n  show \"(\\<lambda>y. \\<integral>\\<^sup>+ x. g x y \\<partial>M) \\<in> borel_measurable N\" using assms\n    by (intro borel_measurable_nn_integral, subst measurable_pair_swap_iff) simp\n  show \"M \\<bind> f = density N (\\<lambda>y. \\<integral>\\<^sup>+ x. g x y \\<partial>M)\"\n    by (intro bind_density) (simp_all add: assms)\n  from \\<open>space M \\<noteq> {}\\<close> obtain x where \"x \\<in> space M\" by blast\n  with assms have \"has_density (f x) N (g x)\" by simp\n  thus \"space N \\<noteq> {}\" by (rule has_densityD)\nqed\n\nlemma bind_has_density':\n  assumes sfM: \"sigma_finite_measure M\"\n      and sfR: \"sigma_finite_measure R\"\n      and not_empty: \"space M \\<noteq> {}\" and dens_M: \"has_density M N \\<delta>M\"\n      and dens_f: \"\\<And>x. x \\<in> space M \\<Longrightarrow> has_density (f x) R (\\<delta>f x)\"\n      and M\\<delta>f: \"case_prod \\<delta>f \\<in> borel_measurable (N \\<Otimes>\\<^sub>M R)\"\n      and Mf: \"f \\<in> measurable N (subprob_algebra R)\"\n  shows \"has_density (M \\<bind> f) R (\\<lambda>y. \\<integral>\\<^sup>+x. \\<delta>M x * \\<delta>f x y \\<partial>N)\"\nproof-\n  from dens_M have M_M: \"measurable M = measurable N\"\n    by (intro ext measurable_cong_sets) (auto dest: has_densityD)\n  from dens_M have M_MR: \"measurable (M \\<Otimes>\\<^sub>M R) = measurable (N \\<Otimes>\\<^sub>M R)\"\n    by (intro ext measurable_cong_sets sets_pair_measure_cong) (auto dest: has_densityD)\n  have \"has_density (M \\<bind> f) R (\\<lambda>y. \\<integral>\\<^sup>+x. \\<delta>f x y \\<partial>M)\"\n    by (rule bind_has_density) (auto simp: assms M_MR M_M)\n  moreover {\n    fix y assume A: \"y \\<in> space R\"\n    have \"(\\<lambda>x. \\<delta>f x y) = case_prod \\<delta>f \\<circ> (\\<lambda>x. (x,y))\" by (rule ext) (simp add: o_def)\n    also have \"... \\<in> borel_measurable N\" by (intro measurable_comp[OF _ M\\<delta>f] measurable_Pair2' A)\n    finally have M_\\<delta>f': \"(\\<lambda>x. \\<delta>f x y) \\<in> borel_measurable N\" .\n\n    from dens_M have \"M = density N \\<delta>M\" by (auto dest: has_densityD)\n    also from dens_M have \"(\\<integral>\\<^sup>+x. \\<delta>f x y \\<partial>...) = \\<integral>\\<^sup>+x. \\<delta>M x * \\<delta>f x y \\<partial>N\"\n      by (subst nn_integral_density) (auto dest: has_densityD simp: M_\\<delta>f')\n    finally have \"(\\<integral>\\<^sup>+x. \\<delta>f x y \\<partial>M) = \\<integral>\\<^sup>+x. \\<delta>M x * \\<delta>f x y \\<partial>N\" .\n  }\n  ultimately show \"has_density (M \\<bind> f) R (\\<lambda>y. \\<integral>\\<^sup>+x. \\<delta>M x * \\<delta>f x y \\<partial>N)\"\n    by (rule has_density_equal_on_space) simp_all\nqed\n\nlemma bind_has_subprob_density:\n  assumes \"subprob_space M\" \"sigma_finite_measure N\"\n          \"space M \\<noteq> {}\" \"\\<And>x. x \\<in> space M \\<Longrightarrow> has_density (f x) N (g x)\"\n          \"case_prod g \\<in> borel_measurable (M \\<Otimes>\\<^sub>M N)\"\n          \"f \\<in> measurable M (subprob_algebra N)\"\n  shows \"has_subprob_density (M \\<bind> f) N (\\<lambda>y. \\<integral>\\<^sup>+x. g x y \\<partial>M)\"\nproof (unfold has_subprob_density_def, intro conjI)\n  from assms show \"has_density (M \\<bind> f) N (\\<lambda>y. \\<integral>\\<^sup>+x. g x y \\<partial>M)\"\n    by (intro bind_has_density) (auto simp: subprob_space_imp_sigma_finite)\n  from assms show \"subprob_space (M \\<bind> f)\" by (intro subprob_space_bind)\nqed\n\nlemma bind_has_subprob_density':\n  assumes \"has_subprob_density M N \\<delta>M\" \"space R \\<noteq> {}\" \"sigma_finite_measure R\"\n          \"\\<And>x. x \\<in> space M \\<Longrightarrow> has_subprob_density (f x) R (\\<delta>f x)\"\n          \"case_prod \\<delta>f \\<in> borel_measurable (N \\<Otimes>\\<^sub>M R)\" \"f \\<in> measurable N (subprob_algebra R)\"\n  shows \"has_subprob_density (M \\<bind> f) R (\\<lambda>y. \\<integral>\\<^sup>+x. \\<delta>M x * \\<delta>f x y \\<partial>N)\"\nproof (unfold has_subprob_density_def, intro conjI)\n  from assms(1) have \"space M \\<noteq> {}\" by (intro subprob_space.subprob_not_empty has_subprob_densityD)\n  with assms show \"has_density (M \\<bind> f) R (\\<lambda>y. \\<integral>\\<^sup>+x. \\<delta>M x * \\<delta>f x y \\<partial>N)\"\n    by (intro bind_has_density' has_densityI)\n       (auto simp: subprob_space_imp_sigma_finite dest: has_subprob_densityD)\n  from assms show \"subprob_space (M \\<bind> f)\"\n    by (intro subprob_space_bind) (auto dest: has_subprob_densityD)\nqed\n\nlemma null_measure_has_subprob_density:\n  \"space M \\<noteq> {} \\<Longrightarrow> has_subprob_density (null_measure M) M (\\<lambda>_. 0)\"\n  by (intro has_subprob_densityI)\n     (auto intro: null_measure_eq_density simp: subprob_space_null_measure_iff)\n\nlemma emeasure_has_parametrized_subprob_density:\n  assumes \"has_parametrized_subprob_density M N R f\"\n  assumes \"x \\<in> space M\" \"X \\<in> sets R\"\n  shows \"emeasure (N x) X = \\<integral>\\<^sup>+y. f x y * indicator X y \\<partial>R\"\nproof-\n  from has_parametrized_subprob_densityD(3)[OF assms(1)] and assms(2)\n    have Mf: \"f x \\<in> borel_measurable R\" by simp\n  have \"N x = density R (f x)\"\n    by (rule has_parametrized_subprob_densityD(1)[OF assms(1,2)])\n  also from Mf and assms(3) have \"emeasure ... X = \\<integral>\\<^sup>+y. f x y * indicator X y \\<partial>R\"\n    by (rule emeasure_density)\n  finally show ?thesis .\nqed\n\nlemma emeasure_count_space_density_singleton:\n  assumes \"x \\<in> A\" \"has_density M (count_space A) f\"\n  shows \"emeasure M {x} = f x\"\nproof-\n  from has_densityD[OF assms(2)] have nonneg: \"\\<And>x. x \\<in> A \\<Longrightarrow> f x \\<ge> 0\" by simp\n  from assms have M: \"M = density (count_space A) f\" by (intro has_densityD)\n  from assms have \"emeasure M {x} = \\<integral>\\<^sup>+y. f y * indicator {x} y \\<partial>count_space A\"\n    by (simp add: M emeasure_density)\n  also from assms and nonneg have \"... = f x\"\n    by (subst nn_integral_indicator_singleton) auto\n  finally show ?thesis .\nqed\n\nlemma subprob_count_space_density_le_1:\n  assumes \"has_subprob_density M (count_space A) f\" \"x \\<in> A\"\n  shows \"f x \\<le> 1\"\nproof (cases \"f x > 0\")\n  assume \"f x > 0\"\n  from assms interpret subprob_space M by (intro has_subprob_densityD)\n  from assms have M: \"M = density (count_space A) f\" by (intro has_subprob_densityD)\n  from assms have \"f x = emeasure M {x}\"\n    by (intro emeasure_count_space_density_singleton[symmetric])\n       (auto simp: has_subprob_density_def)\n  also have \"... \\<le> 1\" by (rule subprob_emeasure_le_1)\n  finally show ?thesis .\nqed (auto simp: not_less intro: order.trans[of _ 0 1])\n\nlemma has_density_embed_measure:\n  assumes inj: \"inj f\" and inv: \"\\<And>x. x \\<in> space N \\<Longrightarrow> f' (f x) = x\"\n  shows \"has_density (embed_measure M f) (embed_measure N f) (\\<delta> \\<circ> f') \\<longleftrightarrow> has_density M N \\<delta>\"\n        (is \"has_density ?M' ?N' ?\\<delta>' \\<longleftrightarrow> has_density M N \\<delta>\")\nproof\n  assume dens: \"has_density ?M' ?N' ?\\<delta>'\"\n  show \"has_density M N \\<delta>\"\n  proof\n    from dens show \"space N \\<noteq> {}\" by (auto simp: space_embed_measure dest: has_densityD)\n    from dens have M\\<delta>f': \"\\<delta> \\<circ> f' \\<in> borel_measurable ?N'\" by (rule has_densityD)\n    hence M\\<delta>f'f: \"\\<delta> \\<circ> f' \\<circ> f \\<in> borel_measurable N\"\n      by (rule_tac measurable_comp, rule_tac measurable_embed_measure2[OF inj])\n    thus M\\<delta>: \"\\<delta> \\<in> borel_measurable N\" by (simp cong: measurable_cong add: inv)\n    from dens have \"embed_measure M f = density (embed_measure N f) (\\<delta> \\<circ> f')\" by (rule has_densityD)\n    also have \"... = embed_measure (density N (\\<delta> \\<circ> f' \\<circ> f)) f\"\n      by (simp only: density_embed_measure[OF inj M\\<delta>f'])\n    also have \"density N (\\<delta> \\<circ> f' \\<circ> f) = density N \\<delta>\"\n      by (intro density_cong[OF M\\<delta>f'f M\\<delta>]) (simp_all add: inv)\n    finally show \"M = density N \\<delta>\" by (simp add: embed_measure_eq_iff[OF inj])\n  qed\nnext\n  assume dens: \"has_density M N \\<delta>\"\n  show \"has_density ?M' ?N' ?\\<delta>'\"\n  proof\n    from dens show \"space ?N' \\<noteq> {}\" by (auto simp: space_embed_measure dest: has_densityD)\n    have Mf'f: \"(\\<lambda>x. f' (f x)) \\<in> measurable N N\" by (subst measurable_cong[OF inv]) simp_all\n    from dens have M\\<delta>: \"\\<delta> \\<in> borel_measurable N\" by (auto dest: has_densityD)\n    from Mf'f and dens show M\\<delta>f': \"\\<delta> \\<circ> f' \\<in> borel_measurable (embed_measure N f)\"\n      by (intro measurable_comp) (erule measurable_embed_measure1, rule has_densityD)\n    have \"embed_measure M f = embed_measure (density N \\<delta>) f\"\n      by (simp only: has_densityD[OF dens])\n    also from inv and dens and measurable_comp[OF Mf'f M\\<delta>]\n      have \"density N \\<delta> = density N (?\\<delta>' \\<circ> f)\"\n      by (intro density_cong[OF M\\<delta>]) (simp add: o_def, simp add: inv o_def)\n    also have \"embed_measure (density N (?\\<delta>' \\<circ> f)) f = density (embed_measure N f) (\\<delta> \\<circ> f')\"\n      by (simp only: density_embed_measure[OF inj M\\<delta>f', symmetric])\n    finally show \"embed_measure M f = density (embed_measure N f) (\\<delta> \\<circ> f')\" .\n  qed\nqed\n\nlemma has_density_embed_measure':\n  assumes inj: \"inj f\" and inv: \"\\<And>x. x \\<in> space N \\<Longrightarrow> f' (f x) = x\" and\n          sets_M: \"sets M = sets (embed_measure N f)\"\n  shows \"has_density (distr M N f') N (\\<delta> \\<circ> f) \\<longleftrightarrow> has_density M (embed_measure N f) \\<delta>\"\nproof-\n  have sets': \"sets (embed_measure (distr M N f') f) = sets (embed_measure N f)\"\n    by (simp add: sets_embed_measure[OF inj])\n  have Mff': \"(\\<lambda>x. f' (f x)) \\<in> measurable N N\" by (subst measurable_cong[OF inv]) simp_all\n  have inv': \"\\<And>x. x \\<in> space M \\<Longrightarrow> f (f' x) = x\"\n    by (subst (asm) sets_eq_imp_space_eq[OF sets_M]) (auto simp: space_embed_measure inv)\n  have \"M = distr M (embed_measure (distr M N f') f) (\\<lambda>x. f (f' x))\"\n    by (subst distr_cong[OF refl _ inv', of _ M]) (simp_all add: sets_embed_measure inj sets_M)\n  also have \"... = embed_measure (distr M N f') f\"\n    apply (subst (2) embed_measure_eq_distr[OF inj], subst distr_distr)\n    apply (subst measurable_cong_sets[OF refl sets'], rule measurable_embed_measure2[OF inj])\n    apply (subst measurable_cong_sets[OF sets_M refl], rule measurable_embed_measure1, rule Mff')\n    apply (simp cong: distr_cong add: inv)\n    done\n  finally have M: \"M = embed_measure (distr M N f') f\" .\n  show ?thesis by (subst (2) M, subst has_density_embed_measure[OF inj inv, symmetric])\n                  (auto simp: space_embed_measure inv intro!: has_density_cong)\nqed\n\nlemma has_density_embed_measure'':\n  assumes inj: \"inj f\" and inv: \"\\<And>x. x \\<in> space N \\<Longrightarrow> f' (f x) = x\" and\n          \"has_density M (embed_measure N f) \\<delta>\"\n  shows \"has_density (distr M N f') N (\\<delta> \\<circ> f)\"\nproof (subst has_density_embed_measure')\n  from assms(3) show \"sets M = sets (embed_measure N f)\" by (auto dest: has_densityD)\nqed (insert assms)\n\nlemma has_subprob_density_embed_measure'':\n  assumes inj: \"inj f\" and inv: \"\\<And>x. x \\<in> space N \\<Longrightarrow> f' (f x) = x\" and\n          \"has_subprob_density M (embed_measure N f) \\<delta>\"\n  shows \"has_subprob_density (distr M N f') N (\\<delta> \\<circ> f)\"\nproof (unfold has_subprob_density_def, intro conjI)\n  from assms show \"has_density (distr M N f') N (\\<delta> \\<circ> f)\"\n    by (intro has_density_embed_measure'' has_subprob_density_imp_has_density)\n  from assms(3) have \"sets M = sets (embed_measure N f)\" by (auto dest: has_subprob_densityD)\n  hence M: \"measurable M = measurable (embed_measure N f)\"\n    by (intro ext measurable_cong_sets) simp_all\n  have \"(\\<lambda>x. f' (f x)) \\<in> measurable N N\" by (simp cong: measurable_cong add: inv)\n  moreover from assms have \"space (embed_measure N f) \\<noteq> {}\"\n    unfolding has_subprob_density_def has_density_def by simp\n  ultimately show \"subprob_space (distr M N f')\" using assms\n    by (intro subprob_space.subprob_space_distr has_subprob_densityD)\n       (auto simp: M space_embed_measure intro!: measurable_embed_measure1 dest: has_subprob_densityD)\nqed (insert 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/Density_Compiler/Density_Predicates.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240721511739, "lm_q2_score": 0.8244619306896955, "lm_q1q2_score": 0.7133443090049573}}
{"text": "theory P05 \nimports Main \nbegin \n\n\nprimrec p05_1 :: \"'a list \\<Rightarrow> 'a list\" where \n\"p05_1 [] = []\"|\n\"p05_1 (x#xs) = p05_1 xs @ [x]\"\n\n\nvalue \"p05_1 [1,2,3,4] :: int list\"\n\n\nlemma [simp] : \"p05_1 (ls @ [b]) = b # p05_1 ls \" \napply (induct ls)\napply auto\ndone \n\nlemma \"p05_1 (p05_1 xs)  = xs\" \nproof (induct xs)\n  case Nil \n  show ?case by simp\n next \n  fix a xs ls b\n  case (Cons a xs)\n  assume \"p05_1 (p05_1 xs) = xs\"\n  thus \"p05_1 (p05_1 (a # xs)) = a # xs \" by simp\nqed\n\nlemma \"p05_1 ls = rev ls\"\n  apply (induct ls)\n   apply simp_all\n  done\n\nlemma \"length ls = length (p05_1 ls)\"\n  apply (induct ls)\n   apply simp_all\n  done   \n  \nlemma \"p05_1 (p05_1 ls ) = ls\" by (induct ls; simp_all)\n    \n    \n    \nlemma \"\\<forall>x .x \\<in> set ls \\<Longrightarrow> x \\<in> set (p05_1 ls)  \" \nproof (induct ls)\n  case Nil\n  then show ?case by simp\nnext\n  case (Cons a ls)\n  assume a:\" \\<forall>x. x \\<in> set (a # ls)\"\n     and b:\"(\\<forall>x. x \\<in> set ls \\<Longrightarrow> x \\<in> set (p05_1 ls))\"\n  with a  show ?case \nqed\n\nlemma \"set ls = set (p05_1 ls)\"\nproof (induct ls)\n  case Nil\n  then show ?case by simp\nnext\n  case (Cons a ls)\n  then show ?case \n  proof (cases \"a \\<in> set ls\")\n    case True\n    then show ?thesis by (simp add: Cons.hyps)\n  next\n    case False\n    then show ?thesis by (simp add : Cons.hyps)\n  qed\nqed\n  ", "meta": {"author": "SvenWille", "repo": "Isabelle99Problems", "sha": "ade705e3f8ff3ea8c5ddb664188e676cb69bc261", "save_path": "github-repos/isabelle/SvenWille-Isabelle99Problems", "path": "github-repos/isabelle/SvenWille-Isabelle99Problems/Isabelle99Problems-ade705e3f8ff3ea8c5ddb664188e676cb69bc261/isabelleSrc/P05.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240756264639, "lm_q2_score": 0.8244619263765707, "lm_q1q2_score": 0.7133443081383821}}
{"text": "(*  Title:      HOL/Metis_Examples/Trans_Closure.thy\n    Author:     Lawrence C. Paulson, Cambridge University Computer Laboratory\n    Author:     Jasmin Blanchette, TU Muenchen\n\nMetis example featuring the transitive closure.\n*)\n\nsection {* Metis Example Featuring the Transitive Closure *}\n\ntheory Trans_Closure\nimports Main\nbegin\n\ndeclare [[metis_new_skolem]]\n\ntype_synonym addr = nat\n\ndatatype val\n  = Unit        -- \"dummy result value of void expressions\"\n  | Null        -- \"null reference\"\n  | Bool bool   -- \"Boolean value\"\n  | Intg int    -- \"integer value\"\n  | Addr addr   -- \"addresses of objects in the heap\"\n\nconsts R :: \"(addr \\<times> addr) set\"\n\nconsts f :: \"addr \\<Rightarrow> val\"\n\nlemma \"\\<lbrakk>f c = Intg x; \\<forall>y. f b = Intg y \\<longrightarrow> y \\<noteq> x; (a, b) \\<in> R\\<^sup>*; (b, c) \\<in> R\\<^sup>*\\<rbrakk>\n       \\<Longrightarrow> \\<exists>c. (b, c) \\<in> R \\<and> (a, c) \\<in> R\\<^sup>*\"\n(* sledgehammer *)\nproof -\n  assume A1: \"f c = Intg x\"\n  assume A2: \"\\<forall>y. f b = Intg y \\<longrightarrow> y \\<noteq> x\"\n  assume A3: \"(a, b) \\<in> R\\<^sup>*\"\n  assume A4: \"(b, c) \\<in> R\\<^sup>*\"\n  have F1: \"f c \\<noteq> f b\" using A2 A1 by metis\n  have F2: \"\\<forall>u. (b, u) \\<in> R \\<longrightarrow> (a, u) \\<in> R\\<^sup>*\" using A3 by (metis transitive_closure_trans(6))\n  have F3: \"\\<exists>x. (b, x b c R) \\<in> R \\<or> c = b\" using A4 by (metis converse_rtranclE)\n  have \"c \\<noteq> b\" using F1 by metis\n  hence \"\\<exists>u. (b, u) \\<in> R\" using F3 by metis\n  thus \"\\<exists>c. (b, c) \\<in> R \\<and> (a, c) \\<in> R\\<^sup>*\" using F2 by metis\nqed\n\nlemma \"\\<lbrakk>f c = Intg x; \\<forall>y. f b = Intg y \\<longrightarrow> y \\<noteq> x; (a, b) \\<in> R\\<^sup>*; (b,c) \\<in> R\\<^sup>*\\<rbrakk>\n       \\<Longrightarrow> \\<exists>c. (b, c) \\<in> R \\<and> (a, c) \\<in> R\\<^sup>*\"\n(* sledgehammer [isar_proofs, compress = 2] *)\nproof -\n  assume A1: \"f c = Intg x\"\n  assume A2: \"\\<forall>y. f b = Intg y \\<longrightarrow> y \\<noteq> x\"\n  assume A3: \"(a, b) \\<in> R\\<^sup>*\"\n  assume A4: \"(b, c) \\<in> R\\<^sup>*\"\n  have \"b \\<noteq> c\" using A1 A2 by metis\n  hence \"\\<exists>x\\<^sub>1. (b, x\\<^sub>1) \\<in> R\" using A4 by (metis converse_rtranclE)\n  thus \"\\<exists>c. (b, c) \\<in> R \\<and> (a, c) \\<in> R\\<^sup>*\" using A3 by (metis transitive_closure_trans(6))\nqed\n\nlemma \"\\<lbrakk>f c = Intg x; \\<forall>y. f b = Intg y \\<longrightarrow> y \\<noteq> x; (a, b) \\<in> R\\<^sup>*; (b, c) \\<in> R\\<^sup>*\\<rbrakk>\n       \\<Longrightarrow> \\<exists>c. (b, c) \\<in> R \\<and> (a, c) \\<in> R\\<^sup>*\"\napply (erule_tac x = b in converse_rtranclE)\n apply metis\nby (metis transitive_closure_trans(6))\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/Metis_Examples/Trans_Closure.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767906859264, "lm_q2_score": 0.8128673087708699, "lm_q1q2_score": 0.7132721973537689}}
{"text": "theory PALandWiseMenPuzzle2021_New_Defs imports Main    (* Sebastian Reiche and Christoph Benzm\u00fcller, 2021 *)\n\nbegin\n (* Parameter settings for Nitpick *) nitpick_params[user_axioms=true, format=4, show_all]\n  \n typedecl i (* Type of possible worlds *)\n type_synonym \\<sigma> = \"i\\<Rightarrow>bool\" (* \\<D> *)\n type_synonym \\<tau> = \"\\<sigma>\\<Rightarrow>i\\<Rightarrow>bool\" (* Type of world depended formulas (truth sets) *) \n type_synonym \\<alpha> = \"i\\<Rightarrow>i\\<Rightarrow>bool\" (* Type of accessibility relations between world *)\n\n (* Some useful relations (for constraining accessibility relations) *)\n definition reflexive::\"\\<alpha>\\<Rightarrow>bool\" where \"reflexive R \\<equiv> \\<forall>x. R x x\"\n definition symmetric::\"\\<alpha>\\<Rightarrow>bool\" where \"symmetric R \\<equiv> \\<forall>x y. R x y \\<longrightarrow> R y x\"\n definition transitive::\"\\<alpha>\\<Rightarrow>bool\" where \"transitive R \\<equiv> \\<forall>x y z. R x y \\<and> R y z \\<longrightarrow> R x z\"\n definition euclidean::\"\\<alpha>\\<Rightarrow>bool\" where \"euclidean R \\<equiv> \\<forall>x y z. R x y \\<and> R x z \\<longrightarrow> R y z\"\n definition intersection_rel::\"\\<alpha>\\<Rightarrow>\\<alpha>\\<Rightarrow>\\<alpha>\" where \"intersection_rel R Q \\<equiv> \\<lambda>u v. R u v \\<and> Q u v\"\n definition union_rel::\"\\<alpha>\\<Rightarrow>\\<alpha>\\<Rightarrow>\\<alpha>\" where \"union_rel R Q \\<equiv> \\<lambda>u v. R u v \\<or> Q u v\"\n definition sub_rel::\"\\<alpha>\\<Rightarrow>\\<alpha>\\<Rightarrow>bool\" where \"sub_rel R Q \\<equiv> \\<forall>u v. R u v \\<longrightarrow> Q u v\"\n definition inverse_rel::\"\\<alpha>\\<Rightarrow>\\<alpha>\" where \"inverse_rel R \\<equiv> \\<lambda>u v. R v u\"\n definition bigunion_rel::\"(\\<alpha>\\<Rightarrow>bool)\\<Rightarrow>\\<alpha>\" (\"\\<^bold>\\<Union>_\") where \"\\<^bold>\\<Union> X \\<equiv> \\<lambda>u v. \\<exists>R. (X R) \\<and> (R u v)\"\n definition bigintersection_rel::\"(\\<alpha>\\<Rightarrow>bool)\\<Rightarrow>\\<alpha>\" (\"\\<^bold>\\<Inter>_\") where \"\\<^bold>\\<Inter> X \\<equiv> \\<lambda>u v. \\<forall>R. (X R) \\<longrightarrow> (R u v)\"\n\n (*In HOL the transitive closure of a relation can be defined in a single line.*)\n definition tc::\"\\<alpha>\\<Rightarrow>\\<alpha>\" where \"tc R \\<equiv> \\<lambda>x y.\\<forall>Q. transitive Q \\<longrightarrow> (sub_rel R Q \\<longrightarrow> Q x y)\"\n\n (* Lifted HOMML connectives for PAL *)\n definition patom::\"\\<sigma>\\<Rightarrow>\\<tau>\" (\"\\<^sup>A_\"[79]80) where \"\\<^sup>Ap \\<equiv> \\<lambda>W w. W w \\<and> p w\"\n definition ptop::\"\\<tau>\" (\"\\<^bold>\\<top>\") where \"\\<^bold>\\<top> \\<equiv> \\<lambda>W w. True\" \n definition pneg::\"\\<tau>\\<Rightarrow>\\<tau>\" (\"\\<^bold>\\<not>_\"[52]53) where \"\\<^bold>\\<not>\\<phi> \\<equiv> \\<lambda>W w. \\<not>(\\<phi> W w)\" \n definition pand::\"\\<tau>\\<Rightarrow>\\<tau>\\<Rightarrow>\\<tau>\" (infixr\"\\<^bold>\\<and>\"51) where \"\\<phi>\\<^bold>\\<and>\\<psi> \\<equiv> \\<lambda>W w. (\\<phi> W w) \\<and> (\\<psi> W w)\"   \n definition por::\"\\<tau>\\<Rightarrow>\\<tau>\\<Rightarrow>\\<tau>\" (infixr\"\\<^bold>\\<or>\"50) where \"\\<phi>\\<^bold>\\<or>\\<psi> \\<equiv> \\<lambda>W w. (\\<phi> W w) \\<or> (\\<psi> W w)\"   \n definition pimp::\"\\<tau>\\<Rightarrow>\\<tau>\\<Rightarrow>\\<tau>\" (infixr\"\\<^bold>\\<rightarrow>\"49) where \"\\<phi>\\<^bold>\\<rightarrow>\\<psi> \\<equiv> \\<lambda>W w. (\\<phi> W w) \\<longrightarrow> (\\<psi> W w)\"  \n definition pequ::\"\\<tau>\\<Rightarrow>\\<tau>\\<Rightarrow>\\<tau>\" (infixr\"\\<^bold>\\<leftrightarrow>\"48) where \"\\<phi>\\<^bold>\\<leftrightarrow>\\<psi> \\<equiv> \\<lambda>W w. (\\<phi> W w) \\<longleftrightarrow> (\\<psi> W w)\"\n definition pknow::\"\\<alpha>\\<Rightarrow>\\<tau>\\<Rightarrow>\\<tau>\" (\"\\<^bold>K_ _\") where \"\\<^bold>K r \\<phi> \\<equiv> \\<lambda>W w.\\<forall>v. (W v \\<and> r w v) \\<longrightarrow> (\\<phi> W v)\"\n definition ppal::\"\\<tau>\\<Rightarrow>\\<tau>\\<Rightarrow>\\<tau>\" (\"\\<^bold>[\\<^bold>!_\\<^bold>]_\") where \"\\<^bold>[\\<^bold>!\\<phi>\\<^bold>]\\<psi> \\<equiv> \\<lambda>W w. (\\<phi> W w) \\<longrightarrow> (\\<psi> (\\<lambda>z. W z \\<and> \\<phi> W z) w)\"\n\n (* Validity of \\<tau>-type lifted PAL formulas *)\n definition pvalid::\"\\<tau> \\<Rightarrow> bool\" (\"\\<^bold>\\<lfloor>_\\<^bold>\\<rfloor>\"[7]8) where \"\\<^bold>\\<lfloor>\\<phi>\\<^bold>\\<rfloor> \\<equiv> \\<forall>W.\\<forall>w. W w \\<longrightarrow> \\<phi> W w\"\n\n (* Agent Knowledge, Mutual Knowledge, Common Knowledge *)\n definition  \"EVR A \\<equiv> \\<^bold>\\<Union> A\"\n definition  \"DIS A \\<equiv> \\<^bold>\\<Inter> A\"\n definition agttknows::\"\\<alpha>\\<Rightarrow>\\<tau>\\<Rightarrow>\\<tau>\" (\"\\<^bold>K\\<^sub>_ _\") where \"\\<^bold>K\\<^sub>r \\<phi> \\<equiv>  \\<^bold>K r \\<phi>\" \n definition evrknows::\"(\\<alpha>\\<Rightarrow>bool)\\<Rightarrow>\\<tau>\\<Rightarrow>\\<tau>\" (\"\\<^bold>E\\<^sub>_ _\") where \"\\<^bold>E\\<^sub>A \\<phi> \\<equiv>  \\<^bold>K (EVR A) \\<phi>\"\n definition prck::\"(\\<alpha>\\<Rightarrow>bool)\\<Rightarrow>\\<tau>\\<Rightarrow>\\<tau>\\<Rightarrow>\\<tau>\" (\"\\<^bold>C\\<^sub>_\\<^bold>\\<lparr>_\\<^bold>|_\\<^bold>\\<rparr>\")\n   where \"\\<^bold>C\\<^sub>A\\<^bold>\\<lparr>\\<phi>\\<^bold>|\\<psi>\\<^bold>\\<rparr> \\<equiv> \\<lambda>W w. \\<forall>v. \\<not>(tc (intersection_rel (EVR A) (\\<lambda>u v. W v \\<and> \\<phi> W v)) w v) \\<or> (\\<psi> W v)\"\n definition pcmn::\"(\\<alpha>\\<Rightarrow>bool)\\<Rightarrow>\\<tau>\\<Rightarrow>\\<tau>\" (\"\\<^bold>C\\<^sub>_ _\") where \"\\<^bold>C\\<^sub>A \\<phi> \\<equiv>  \\<^bold>C\\<^sub>A\\<^bold>\\<lparr>\\<^bold>\\<top>\\<^bold>|\\<phi>\\<^bold>\\<rparr>\"\n definition disknows :: \"(\\<alpha>\\<Rightarrow>bool)\\<Rightarrow>\\<tau>\\<Rightarrow>\\<tau>\" (\"\\<^bold>D\\<^sub>_ _\") where \"\\<^bold>D\\<^sub>A \\<phi> \\<equiv> \\<^bold>K (DIS A) \\<phi>\"\n\n (* Introducing \"Defs\" as the set of the above definitions; useful for convenient unfolding *)\n named_theorems Defs\n declare  \n   patom_def[Defs] ptop_def[Defs] pneg_def[Defs] pand_def[Defs] por_def[Defs] pimp_def[Defs] pequ_def[Defs] pknow_def[Defs] ppal_def[Defs]\n   EVR_def[Defs] DIS_def[Defs] prck_def[Defs] pvalid_def[Defs] \n   agttknows_def[Defs] evrknows_def[Defs] pcmn_def[Defs] disknows_def[Defs]\n   reflexive_def[Defs] symmetric_def[Defs] transitive_def[Defs] euclidean_def[Defs] \n   intersection_rel_def[Defs] union_rel_def[Defs] sub_rel_def[Defs] inverse_rel_def[Defs] \n   bigunion_rel_def[Defs] tc_def[Defs] \n\n (***********************************************************************************************)\n (*****                         Experiments                                                 *****)\n (***********************************************************************************************)\n (*Some useful lemmata *) \n lemma trans_tc: \"transitive (tc R)\" unfolding Defs by metis\n lemma trans_inv_tc: \"transitive (inverse_rel (tc R))\" unfolding Defs by metis\n lemma sub_rel_tc: \"symmetric R \\<longrightarrow> (sub_rel R (inverse_rel (tc R)))\" unfolding Defs by smt\n lemma sub_rel_tc_tc: \"symmetric R \\<longrightarrow> (sub_rel (tc R) (inverse_rel (tc R)))\" \n   using sub_rel_def sub_rel_tc tc_def trans_inv_tc by fastforce\n lemma symm_tc: \"symmetric R \\<longrightarrow> symmetric (tc R)\"  \n   using inverse_rel_def sub_rel_def sub_rel_tc_tc symmetric_def by auto\n\n (* System K: is implied by the semantical embedding *)\n lemma tautologies: \"\\<^bold>\\<lfloor>\\<^bold>\\<top>\\<^bold>\\<rfloor>\" unfolding Defs by auto\n lemma axiom_K: \"\\<A> i \\<Longrightarrow> \\<^bold>\\<lfloor>(\\<^bold>K\\<^sub>i (\\<phi> \\<^bold>\\<rightarrow> \\<psi>)) \\<^bold>\\<rightarrow> ((\\<^bold>K\\<^sub>i \\<phi>) \\<^bold>\\<rightarrow> (\\<^bold>K\\<^sub>i \\<psi>))\\<^bold>\\<rfloor>\" unfolding Defs by auto \n lemma modusponens: assumes 1: \"\\<^bold>\\<lfloor>\\<phi> \\<^bold>\\<rightarrow> \\<psi>\\<^bold>\\<rfloor>\" and 2: \"\\<^bold>\\<lfloor>\\<phi>\\<^bold>\\<rfloor>\" shows \"\\<^bold>\\<lfloor>\\<psi>\\<^bold>\\<rfloor>\" using 1 2 unfolding Defs by auto  \n lemma necessitation: assumes 1: \"\\<^bold>\\<lfloor>\\<phi>\\<^bold>\\<rfloor>\" shows \"\\<A> i \\<Longrightarrow> \\<^bold>\\<lfloor>\\<^bold>K\\<^sub>i \\<phi>\\<^bold>\\<rfloor>\" using 1 unfolding Defs by auto\n (* More axioms: implied by the semantical embedding  *)\n lemma axiom_T: \"reflexive i \\<Longrightarrow> \\<^bold>\\<lfloor>(\\<^bold>K\\<^sub>i \\<phi>) \\<^bold>\\<rightarrow> \\<phi>\\<^bold>\\<rfloor>\" using reflexive_def unfolding Defs by auto \n lemma axiom_4: \"transitive i \\<Longrightarrow> \\<^bold>\\<lfloor>(\\<^bold>K\\<^sub>i \\<phi>) \\<^bold>\\<rightarrow> (\\<^bold>K\\<^sub>i (\\<^bold>K\\<^sub>i \\<phi>))\\<^bold>\\<rfloor>\" using transitive_def unfolding Defs by meson \n lemma axiom_5: \"euclidean i \\<Longrightarrow> \\<^bold>\\<lfloor>(\\<^bold>\\<not>\\<^bold>K\\<^sub>i \\<phi>) \\<^bold>\\<rightarrow> (\\<^bold>K\\<^sub>i (\\<^bold>\\<not>\\<^bold>K\\<^sub>i \\<phi>))\\<^bold>\\<rfloor>\" using euclidean_def unfolding Defs by meson \n (*Reduction axioms: implied by the semantical embedding *)\n lemma atomic_permanence: \"\\<^bold>\\<lfloor>(\\<^bold>[\\<^bold>!\\<phi>\\<^bold>]\\<^sup>Ap) \\<^bold>\\<leftrightarrow> (\\<phi> \\<^bold>\\<rightarrow> \\<^sup>Ap)\\<^bold>\\<rfloor>\" unfolding Defs by auto\n lemma conjunction: \"\\<^bold>\\<lfloor>(\\<^bold>[\\<^bold>!\\<phi>\\<^bold>](\\<psi> \\<^bold>\\<and> \\<chi>)) \\<^bold>\\<rightarrow> ((\\<^bold>[\\<^bold>!\\<phi>\\<^bold>]\\<psi>) \\<^bold>\\<and> (\\<^bold>[\\<^bold>!\\<phi>\\<^bold>]\\<chi>))\\<^bold>\\<rfloor>\" unfolding Defs by auto\n lemma part_func: \"\\<^bold>\\<lfloor>(\\<^bold>[\\<^bold>!\\<phi>\\<^bold>]\\<^bold>\\<not>\\<psi>) \\<^bold>\\<leftrightarrow> (\\<phi> \\<^bold>\\<rightarrow> (\\<^bold>\\<not>\\<^bold>[\\<^bold>!\\<phi>\\<^bold>]\\<psi>))\\<^bold>\\<rfloor>\" unfolding Defs by auto\n lemma action_knowledge: \"\\<^bold>\\<lfloor>(\\<^bold>[\\<^bold>!\\<phi>\\<^bold>](\\<^bold>K\\<^sub>i \\<psi>)) \\<^bold>\\<leftrightarrow> (\\<phi> \\<^bold>\\<rightarrow> (\\<^bold>K\\<^sub>i (\\<phi> \\<^bold>\\<rightarrow> (\\<^bold>[\\<^bold>!\\<phi>\\<^bold>]\\<psi>))))\\<^bold>\\<rfloor>\" unfolding Defs by auto\n lemma \"\\<^bold>\\<lfloor>(\\<^bold>[\\<^bold>!\\<phi>\\<^bold>](\\<^bold>C\\<^sub>A\\<^bold>\\<lparr>\\<chi>\\<^bold>|\\<psi>\\<^bold>\\<rparr>)) \\<^bold>\\<leftrightarrow> (\\<phi> \\<^bold>\\<rightarrow> (\\<^bold>C\\<^sub>A\\<^bold>\\<lparr>\\<phi>\\<^bold>\\<and>(\\<^bold>[\\<^bold>!\\<phi>\\<^bold>]\\<chi>)\\<^bold>|\\<^bold>[\\<^bold>!\\<phi>\\<^bold>]\\<psi>\\<^bold>\\<rparr>))\\<^bold>\\<rfloor>\" \n   (* sledgehammer finds proof, reconstruction fails *) oops\n \n\n declare [[smt_solver=cvc4,smt_oracle]]\n\n definition \"S5Agent i \\<equiv> reflexive i \\<and> transitive i \\<and> euclidean i\"\n definition \"S5Agents A \\<equiv> \\<forall>i. (A i \\<longrightarrow> S5Agent i)\"\n\n declare S5Agent_def[Defs] S5Agents_def[Defs]\n\n (* Axiom schemes for RCK: implied by the semantical embedding *)\n lemma \\<C>_normality: \"\\<^bold>\\<lfloor>\\<^bold>C\\<^sub>A\\<^bold>\\<lparr>\\<chi>\\<^bold>|\\<phi>\\<^bold>\\<rightarrow>\\<psi>\\<^bold>\\<rparr> \\<^bold>\\<rightarrow>(\\<^bold>C\\<^sub>A\\<^bold>\\<lparr>\\<chi>\\<^bold>|\\<phi>\\<^bold>\\<rparr> \\<^bold>\\<rightarrow> \\<^bold>C\\<^sub>A\\<^bold>\\<lparr>\\<chi>\\<^bold>|\\<psi>\\<^bold>\\<rparr>)\\<^bold>\\<rfloor>\" unfolding Defs by blast\n\n lemma mix_axiom1: \"\\<^bold>\\<lfloor>\\<^bold>C\\<^sub>A\\<^bold>\\<lparr>\\<chi>\\<^bold>|\\<phi>\\<^bold>\\<rparr> \\<^bold>\\<rightarrow> \\<^bold>E\\<^sub>A(\\<chi> \\<^bold>\\<rightarrow> (\\<phi> \\<^bold>\\<and> (\\<^bold>C\\<^sub>A\\<^bold>\\<lparr>\\<chi>\\<^bold>|\\<phi>\\<^bold>\\<rparr>)))\\<^bold>\\<rfloor>\" unfolding Defs by smt\n\n lemma mix_axiom2': \"A = (\\<lambda>x. False) \\<Longrightarrow> \\<^bold>\\<lfloor>(\\<^bold>E\\<^sub>A(\\<chi> \\<^bold>\\<rightarrow> (\\<phi> \\<^bold>\\<and> (\\<^bold>C\\<^sub>A\\<^bold>\\<lparr>\\<chi>\\<^bold>|\\<phi>\\<^bold>\\<rparr>)))) \\<^bold>\\<rightarrow> \\<^bold>C\\<^sub>A\\<^bold>\\<lparr>\\<chi>\\<^bold>|\\<phi>\\<^bold>\\<rparr>\\<^bold>\\<rfloor>\" \n  unfolding Defs by (metis (full_types)) \n lemma mix_axiom2'': \"A = (\\<lambda>x. True) \\<Longrightarrow> \\<^bold>\\<lfloor>(\\<^bold>E\\<^sub>A(\\<chi> \\<^bold>\\<rightarrow> (\\<phi> \\<^bold>\\<and> (\\<^bold>C\\<^sub>A\\<^bold>\\<lparr>\\<chi>\\<^bold>|\\<phi>\\<^bold>\\<rparr>)))) \\<^bold>\\<rightarrow> \\<^bold>C\\<^sub>A\\<^bold>\\<lparr>\\<chi>\\<^bold>|\\<phi>\\<^bold>\\<rparr>\\<^bold>\\<rfloor>\" \n  unfolding Defs by (metis (full_types)) (* takes long *)\n lemma mix_axiom2''': \"A = (\\<lambda>x. x = a) \\<and> S5Agent a \\<Longrightarrow> \\<^bold>\\<lfloor>(\\<^bold>E\\<^sub>A(\\<chi> \\<^bold>\\<rightarrow> (\\<phi> \\<^bold>\\<and> (\\<^bold>C\\<^sub>A\\<^bold>\\<lparr>\\<chi>\\<^bold>|\\<phi>\\<^bold>\\<rparr>)))) \\<^bold>\\<rightarrow> \\<^bold>C\\<^sub>A\\<^bold>\\<lparr>\\<chi>\\<^bold>|\\<phi>\\<^bold>\\<rparr>\\<^bold>\\<rfloor>\" \n  unfolding Defs  (* sledgehammer finds proof, but reconstruction times\u2715out *) oops \n lemma mix_axiom2'''': \"A = (\\<lambda>x. x = a \\<or> x = b) \\<and> S5Agent a  \\<and> S5Agent b \\<Longrightarrow> \\<^bold>\\<lfloor>(\\<^bold>E\\<^sub>A(\\<chi> \\<^bold>\\<rightarrow> (\\<phi> \\<^bold>\\<and> (\\<^bold>C\\<^sub>A\\<^bold>\\<lparr>\\<chi>\\<^bold>|\\<phi>\\<^bold>\\<rparr>)))) \\<^bold>\\<rightarrow> \\<^bold>C\\<^sub>A\\<^bold>\\<lparr>\\<chi>\\<^bold>|\\<phi>\\<^bold>\\<rparr>\\<^bold>\\<rfloor>\" \n  unfolding Defs sledgehammer (* sledgehammer and nitpick timeout *) oops\n lemma mix_axiom2_general: \"\\<^bold>\\<lfloor>(\\<^bold>E\\<^sub>A(\\<chi> \\<^bold>\\<rightarrow> (\\<phi> \\<^bold>\\<and> (\\<^bold>C\\<^sub>A\\<^bold>\\<lparr>\\<chi>\\<^bold>|\\<phi>\\<^bold>\\<rparr>)))) \\<^bold>\\<rightarrow> \\<^bold>C\\<^sub>A\\<^bold>\\<lparr>\\<chi>\\<^bold>|\\<phi>\\<^bold>\\<rparr>\\<^bold>\\<rfloor>\" unfolding Defs  (* timeout *) oops\n\n lemma induction_axiom': \"A = (\\<lambda>x. False) \\<Longrightarrow> \\<^bold>\\<lfloor>((\\<^bold>E\\<^sub>A(\\<chi> \\<^bold>\\<rightarrow> \\<phi>)) \\<^bold>\\<and> \\<^bold>C\\<^sub>A\\<^bold>\\<lparr>\\<chi>\\<^bold>|\\<phi> \\<^bold>\\<rightarrow> (\\<^bold>E\\<^sub>A(\\<chi> \\<^bold>\\<rightarrow> \\<phi>))\\<^bold>\\<rparr>) \\<^bold>\\<rightarrow> (\\<^bold>C\\<^sub>A\\<^bold>\\<lparr>\\<chi>\\<^bold>|\\<phi>\\<^bold>\\<rparr>)\\<^bold>\\<rfloor>\" \n  unfolding Defs by (metis (full_types)) \n lemma induction_axiom'': \"A = (\\<lambda>x. True) \\<Longrightarrow> \\<^bold>\\<lfloor>((\\<^bold>E\\<^sub>A(\\<chi> \\<^bold>\\<rightarrow> \\<phi>)) \\<^bold>\\<and> \\<^bold>C\\<^sub>A\\<^bold>\\<lparr>\\<chi>\\<^bold>|\\<phi> \\<^bold>\\<rightarrow> (\\<^bold>E\\<^sub>A(\\<chi> \\<^bold>\\<rightarrow> \\<phi>))\\<^bold>\\<rparr>) \\<^bold>\\<rightarrow> (\\<^bold>C\\<^sub>A\\<^bold>\\<lparr>\\<chi>\\<^bold>|\\<phi>\\<^bold>\\<rparr>)\\<^bold>\\<rfloor>\" \n  unfolding Defs (* sledgehammer finds proof, but reconstruction times\u2715out *) oops \n lemma induction_axiom''': \"A = (\\<lambda>x. x = a)  \\<and> S5Agent a  \\<Longrightarrow> \\<^bold>\\<lfloor>((\\<^bold>E\\<^sub>A(\\<chi> \\<^bold>\\<rightarrow> \\<phi>)) \\<^bold>\\<and> \\<^bold>C\\<^sub>A\\<^bold>\\<lparr>\\<chi>\\<^bold>|\\<phi> \\<^bold>\\<rightarrow> (\\<^bold>E\\<^sub>A(\\<chi> \\<^bold>\\<rightarrow> \\<phi>))\\<^bold>\\<rparr>) \\<^bold>\\<rightarrow> (\\<^bold>C\\<^sub>A\\<^bold>\\<lparr>\\<chi>\\<^bold>|\\<phi>\\<^bold>\\<rparr>)\\<^bold>\\<rfloor>\" \n  unfolding Defs (* sledgehammer finds proof, but reconstruction times\u2715out *) oops \n lemma induction_axiom'''': \"A = (\\<lambda>x. x = a \\<or> x = b) \\<and> S5Agent a  \\<and> S5Agent b  \\<Longrightarrow> \\<^bold>\\<lfloor>((\\<^bold>E\\<^sub>A(\\<chi> \\<^bold>\\<rightarrow> \\<phi>)) \\<^bold>\\<and> \\<^bold>C\\<^sub>A\\<^bold>\\<lparr>\\<chi>\\<^bold>|\\<phi> \\<^bold>\\<rightarrow> (\\<^bold>E\\<^sub>A(\\<chi> \\<^bold>\\<rightarrow> \\<phi>))\\<^bold>\\<rparr>) \\<^bold>\\<rightarrow> (\\<^bold>C\\<^sub>A\\<^bold>\\<lparr>\\<chi>\\<^bold>|\\<phi>\\<^bold>\\<rparr>)\\<^bold>\\<rfloor>\" \n   unfolding Defs (* sledgehammer and nitpick timeout *) oops\n lemma induction_axiom_general: \"\\<^bold>\\<lfloor>((\\<^bold>E\\<^sub>A(\\<chi> \\<^bold>\\<rightarrow> \\<phi>)) \\<^bold>\\<and> \\<^bold>C\\<^sub>A\\<^bold>\\<lparr>\\<chi>\\<^bold>|\\<phi> \\<^bold>\\<rightarrow> (\\<^bold>E\\<^sub>A(\\<chi> \\<^bold>\\<rightarrow> \\<phi>))\\<^bold>\\<rparr>) \\<^bold>\\<rightarrow> (\\<^bold>C\\<^sub>A\\<^bold>\\<lparr>\\<chi>\\<^bold>|\\<phi>\\<^bold>\\<rparr>)\\<^bold>\\<rfloor>\"\n   unfolding Defs (* sledgehammer and nitpick timeout *) oops\n\n (* Necessitation rules: implied by the semantical embedding *)\n lemma announcement_nec: assumes \"\\<^bold>\\<lfloor>\\<phi>\\<^bold>\\<rfloor>\" shows \"\\<^bold>\\<lfloor>\\<^bold>[\\<^bold>!\\<psi>\\<^bold>]\\<phi>\\<^bold>\\<rfloor>\" using assms unfolding Defs by simp \n lemma rkc_necessitation: assumes \"\\<^bold>\\<lfloor>\\<phi>\\<^bold>\\<rfloor>\" shows \"\\<^bold>\\<lfloor>(\\<^bold>C\\<^sub>A\\<^bold>\\<lparr>\\<chi>\\<^bold>|\\<phi>\\<^bold>\\<rparr>)\\<^bold>\\<rfloor>\" using assms unfolding Defs\n   (* sledgehammer finds proof, but reconstruction times\u2715out *) oops\n\n\n lemma assumes \"\\<^bold>\\<lfloor>p \\<^bold>\\<leftrightarrow> q\\<^bold>\\<rfloor>\" shows \"\\<forall>W v. (p W v \\<longleftrightarrow> q W v)\" using assms unfolding Defs nitpick oops (* countermodel *)\n lemma assumes \"\\<forall>W v. (p W v \\<longleftrightarrow> q W v)\" shows \"\\<^bold>\\<lfloor>p \\<^bold>\\<leftrightarrow> q\\<^bold>\\<rfloor>\" using assms unfolding Defs by simp \n lemma assumes \"\\<^bold>\\<lfloor>\\<^sup>Ap \\<^bold>\\<leftrightarrow> \\<^sup>Aq\\<^bold>\\<rfloor>\"  shows \"\\<forall>v. (p v \\<longleftrightarrow> q v)\" using assms unfolding Defs by simp\n lemma assumes  \"\\<forall>v. (p v \\<longleftrightarrow> q v)\" shows \"\\<^bold>\\<lfloor>\\<^sup>Ap \\<^bold>\\<leftrightarrow> \\<^sup>Aq\\<^bold>\\<rfloor>\" using assms unfolding Defs by simp\n\n\n (* Further axioms: implied for atomic formulas, but not implied in general *)\n lemma \"\\<^bold>\\<lfloor>\\<^sup>Ap \\<^bold>\\<rightarrow> \\<^bold>\\<not>\\<^bold>[\\<^bold>!\\<^sup>Ap\\<^bold>](\\<^bold>\\<not>\\<^sup>Ap)\\<^bold>\\<rfloor>\" unfolding Defs by simp\n lemma \"\\<^bold>\\<lfloor>\\<phi> \\<^bold>\\<rightarrow> \\<^bold>\\<not>\\<^bold>[\\<^bold>!\\<phi>\\<^bold>](\\<^bold>\\<not>\\<phi>)\\<^bold>\\<rfloor>\" unfolding Defs nitpick oops (* countermodel found *)\n lemma \"\\<^bold>\\<lfloor>\\<^sup>Ap \\<^bold>\\<rightarrow> \\<^bold>\\<not>\\<^bold>[\\<^bold>!\\<^sup>Ap\\<^bold>](\\<^bold>\\<not>\\<^bold>K\\<^sub>a \\<^sup>Ap)\\<^bold>\\<rfloor>\" unfolding Defs by simp\n lemma \"\\<^bold>\\<lfloor>\\<phi> \\<^bold>\\<rightarrow> \\<^bold>\\<not>\\<^bold>[\\<^bold>!\\<phi>\\<^bold>](\\<^bold>\\<not>\\<^bold>K\\<^sub>a \\<phi>)\\<^bold>\\<rfloor>\" unfolding Defs nitpick oops (* countermodel found *)  \n lemma \"\\<^bold>\\<lfloor>\\<^sup>Ap \\<^bold>\\<rightarrow> \\<^bold>\\<not>\\<^bold>[\\<^bold>!\\<^sup>Ap\\<^bold>](\\<^bold>\\<not>\\<^bold>K\\<^sub>r \\<^sup>Ap)\\<^bold>\\<rfloor>\" unfolding Defs by simp\n lemma \"\\<^bold>\\<lfloor>\\<phi> \\<^bold>\\<rightarrow> \\<^bold>\\<not>\\<^bold>[\\<^bold>!\\<phi>\\<^bold>](\\<^bold>\\<not>\\<^bold>K\\<^sub>r \\<phi>)\\<^bold>\\<rfloor>\" unfolding Defs nitpick oops (* countermodel found *)  \n lemma \"\\<^bold>\\<lfloor>\\<^sup>Ap \\<^bold>\\<rightarrow> \\<^bold>\\<not>\\<^bold>[\\<^bold>!\\<^sup>Ap\\<^bold>](\\<^sup>Ap \\<^bold>\\<and> \\<^bold>\\<not>\\<^bold>K\\<^sub>r \\<^sup>Ap)\\<^bold>\\<rfloor>\" unfolding Defs by simp\n lemma \"\\<^bold>\\<lfloor>\\<phi> \\<^bold>\\<rightarrow> \\<^bold>\\<not>\\<^bold>[\\<^bold>!\\<phi>\\<^bold>](\\<phi> \\<^bold>\\<and> \\<^bold>\\<not>\\<^bold>K\\<^sub>r \\<phi>)\\<^bold>\\<rfloor>\" unfolding Defs nitpick oops (* countermodel found *)  \n lemma \"\\<^bold>\\<lfloor>(\\<^sup>Ap \\<^bold>\\<and> \\<^bold>\\<not>\\<^bold>K\\<^sub>r \\<^sup>Ap) \\<^bold>\\<rightarrow> \\<^bold>\\<not>\\<^bold>[\\<^bold>!\\<^sup>Ap \\<^bold>\\<and> \\<^bold>\\<not>\\<^bold>K\\<^sub>r \\<^sup>Ap\\<^bold>](\\<^sup>Ap \\<^bold>\\<and> \\<^bold>\\<not>\\<^bold>K\\<^sub>r \\<^sup>Ap)\\<^bold>\\<rfloor>\" unfolding Defs by blast\n lemma \"\\<^bold>\\<lfloor>(\\<phi> \\<^bold>\\<and> \\<^bold>\\<not>\\<^bold>K\\<^sub>r \\<phi>) \\<^bold>\\<rightarrow> \\<^bold>\\<not>\\<^bold>[\\<^bold>!\\<phi> \\<^bold>\\<and> \\<^bold>\\<not>\\<^bold>K\\<^sub>r \\<phi>\\<^bold>](\\<phi> \\<^bold>\\<and> \\<^bold>\\<not>\\<^bold>K\\<^sub>r \\<phi>)\\<^bold>\\<rfloor>\" unfolding Defs nitpick oops (* countermodel found *)\n lemma \"S5Agent r \\<Longrightarrow> \\<^bold>\\<lfloor>(\\<^bold>K\\<^sub>r \\<^sup>Ap) \\<^bold>\\<rightarrow> \\<^bold>\\<not>\\<^bold>[\\<^bold>!\\<^sup>Ap\\<^bold>](\\<^bold>\\<not>\\<^bold>K\\<^sub>r \\<^sup>Ap)\\<^bold>\\<rfloor>\" using reflexive_def unfolding Defs by meson\n lemma \"S5Agent r \\<Longrightarrow> \\<^bold>\\<lfloor>(\\<^bold>K\\<^sub>r \\<phi>) \\<^bold>\\<rightarrow> \\<^bold>\\<not>\\<^bold>[\\<^bold>!\\<phi>\\<^bold>](\\<^bold>\\<not>\\<^bold>K\\<^sub>r \\<phi>)\\<^bold>\\<rfloor>\" unfolding Defs nitpick oops (* countermodel found *)  \n lemma \"S5Agent r \\<Longrightarrow> \\<^bold>\\<lfloor>(\\<^bold>K\\<^sub>r \\<^sup>Ap) \\<^bold>\\<rightarrow> \\<^bold>\\<not>\\<^bold>[\\<^bold>!\\<^sup>Ap\\<^bold>](\\<^sup>Ap \\<^bold>\\<and> \\<^bold>\\<not>\\<^bold>K\\<^sub>r \\<^sup>Ap)\\<^bold>\\<rfloor>\" using reflexive_def unfolding Defs by meson\n lemma \"S5Agent r \\<Longrightarrow> \\<^bold>\\<lfloor>(\\<^bold>K\\<^sub>r \\<phi>) \\<^bold>\\<rightarrow> \\<^bold>\\<not>\\<^bold>[\\<^bold>!\\<phi>\\<^bold>](\\<phi> \\<^bold>\\<and> \\<^bold>\\<not>\\<^bold>K\\<^sub>r \\<phi>)\\<^bold>\\<rfloor>\" unfolding Defs nitpick oops (* countermodel found *)\n\n (***********************************************************************************************)\n (*****                         Wise Men Puzzle                                             *****)\n (***********************************************************************************************)\n (*** Encoding of the wise men puzzle in PAL ***)\n (* Agents *)\n consts a::\"\\<alpha>\" b::\"\\<alpha>\" c::\"\\<alpha>\" (* Agents modeled as accessibility relations *)\n definition  Agent::\"\\<alpha>\\<Rightarrow>bool\" (\"\\<A>\") where \"\\<A> x \\<equiv> x = a \\<or> x = b \\<or> x = c\"\n axiomatization where  group_S5: \"S5Agents \\<A>\"\n\n (* Common knowledge: At least one of a, b and c has a white spot *)\n consts ws::\"\\<alpha>\\<Rightarrow>\\<sigma>\" \n axiomatization where WM1: \"\\<^bold>\\<lfloor>\\<^bold>C\\<^sub>\\<A> (\\<^sup>Aws a \\<^bold>\\<or> \\<^sup>Aws b \\<^bold>\\<or> \\<^sup>Aws c)\\<^bold>\\<rfloor>\" \n\n axiomatization where\n   (* Common knowledge: If x does not have a white spot then y know this *)\n   WM2ab: \"\\<^bold>\\<lfloor>\\<^bold>C\\<^sub>\\<A> (\\<^bold>\\<not>(\\<^sup>Aws a) \\<^bold>\\<rightarrow> (\\<^bold>K\\<^sub>b (\\<^bold>\\<not>(\\<^sup>Aws a))))\\<^bold>\\<rfloor>\" and\n   WM2ac: \"\\<^bold>\\<lfloor>\\<^bold>C\\<^sub>\\<A> (\\<^bold>\\<not>(\\<^sup>Aws a) \\<^bold>\\<rightarrow> (\\<^bold>K\\<^sub>c (\\<^bold>\\<not>(\\<^sup>Aws a))))\\<^bold>\\<rfloor>\" and\n   WM2ba: \"\\<^bold>\\<lfloor>\\<^bold>C\\<^sub>\\<A> (\\<^bold>\\<not>(\\<^sup>Aws b) \\<^bold>\\<rightarrow> (\\<^bold>K\\<^sub>a (\\<^bold>\\<not>(\\<^sup>Aws b))))\\<^bold>\\<rfloor>\" and\n   WM2bc: \"\\<^bold>\\<lfloor>\\<^bold>C\\<^sub>\\<A> (\\<^bold>\\<not>(\\<^sup>Aws b) \\<^bold>\\<rightarrow> (\\<^bold>K\\<^sub>c (\\<^bold>\\<not>(\\<^sup>Aws b))))\\<^bold>\\<rfloor>\" and\n   WM2ca: \"\\<^bold>\\<lfloor>\\<^bold>C\\<^sub>\\<A> (\\<^bold>\\<not>(\\<^sup>Aws c) \\<^bold>\\<rightarrow> (\\<^bold>K\\<^sub>a (\\<^bold>\\<not>(\\<^sup>Aws c))))\\<^bold>\\<rfloor>\" and\n   WM2cb: \"\\<^bold>\\<lfloor>\\<^bold>C\\<^sub>\\<A> (\\<^bold>\\<not>(\\<^sup>Aws c) \\<^bold>\\<rightarrow> (\\<^bold>K\\<^sub>b (\\<^bold>\\<not>(\\<^sup>Aws c))))\\<^bold>\\<rfloor>\" \n\n (* Positive introspection principles are implied *)\n lemma WM2ab': \"\\<^bold>\\<lfloor>\\<^bold>C\\<^sub>\\<A> ((\\<^sup>Aws a) \\<^bold>\\<rightarrow> (\\<^bold>K\\<^sub>b (\\<^sup>Aws a)))\\<^bold>\\<rfloor>\" using WM2ab group_S5 unfolding Defs by metis\n lemma WM2ac': \"\\<^bold>\\<lfloor>\\<^bold>C\\<^sub>\\<A> ((\\<^sup>Aws a) \\<^bold>\\<rightarrow> (\\<^bold>K\\<^sub>c (\\<^sup>Aws a)))\\<^bold>\\<rfloor>\" using WM2ac group_S5 unfolding Defs by metis\n lemma WM2ba': \"\\<^bold>\\<lfloor>\\<^bold>C\\<^sub>\\<A> ((\\<^sup>Aws b) \\<^bold>\\<rightarrow> (\\<^bold>K\\<^sub>a (\\<^sup>Aws b)))\\<^bold>\\<rfloor>\" using WM2ba group_S5 unfolding Defs by metis\n lemma WM2bc': \"\\<^bold>\\<lfloor>\\<^bold>C\\<^sub>\\<A> ((\\<^sup>Aws b) \\<^bold>\\<rightarrow> (\\<^bold>K\\<^sub>c (\\<^sup>Aws b)))\\<^bold>\\<rfloor>\" using WM2bc group_S5 unfolding Defs by metis\n lemma WM2ca': \"\\<^bold>\\<lfloor>\\<^bold>C\\<^sub>\\<A> ((\\<^sup>Aws c) \\<^bold>\\<rightarrow> (\\<^bold>K\\<^sub>a (\\<^sup>Aws c)))\\<^bold>\\<rfloor>\" using WM2ca group_S5 unfolding Defs by metis\n lemma WM2cb': \"\\<^bold>\\<lfloor>\\<^bold>C\\<^sub>\\<A> ((\\<^sup>Aws c) \\<^bold>\\<rightarrow> (\\<^bold>K\\<^sub>b (\\<^sup>Aws c)))\\<^bold>\\<rfloor>\" using WM2cb group_S5 unfolding Defs by metis\n\n (* Automated solutions of the Wise Men Puzzle *)\n theorem whitespot_c_1: \"\\<^bold>\\<lfloor>\\<^bold>[\\<^bold>!\\<^bold>\\<not>\\<^bold>K\\<^sub>a(\\<^sup>Aws a)\\<^bold>](\\<^bold>[\\<^bold>!\\<^bold>\\<not>\\<^bold>K\\<^sub>b(\\<^sup>Aws b)\\<^bold>](\\<^bold>K\\<^sub>c (\\<^sup>Aws c)))\\<^bold>\\<rfloor>\" \n   using WM1 WM2ba WM2ca WM2cb unfolding Defs by (smt (verit)) \n\n theorem whitespot_c_2: \n   \"\\<^bold>\\<lfloor>\\<^bold>[\\<^bold>!\\<^bold>\\<not>((\\<^bold>K\\<^sub>a (\\<^sup>Aws a)) \\<^bold>\\<or> (\\<^bold>K\\<^sub>a (\\<^bold>\\<not>\\<^sup>Aws a)))\\<^bold>](\\<^bold>[\\<^bold>!\\<^bold>\\<not>((\\<^bold>K\\<^sub>b (\\<^sup>Aws b)) \\<^bold>\\<or> (\\<^bold>K\\<^sub>b (\\<^bold>\\<not>\\<^sup>Aws b)))\\<^bold>](\\<^bold>K\\<^sub>c (\\<^sup>Aws c)))\\<^bold>\\<rfloor>\" \n   using WM1 WM2ba WM2ca WM2cb unfolding Defs by (smt (verit)) \n   \n (* Consistency confirmed by nitpick *)\n lemma True nitpick [satisfy,show_all] oops  (* model found *)\nend", "meta": {"author": "cbenzmueller", "repo": "LogiKEy", "sha": "5c16bdeb68bf8131e24ba9c8d774d4af663cb2cf", "save_path": "github-repos/isabelle/cbenzmueller-LogiKEy", "path": "github-repos/isabelle/cbenzmueller-LogiKEy/LogiKEy-5c16bdeb68bf8131e24ba9c8d774d4af663cb2cf/Public-Announcement-Logic/PALandWiseMenPuzzle2021_New_Defs.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896824119663, "lm_q2_score": 0.7745833841649233, "lm_q1q2_score": 0.7132283883068059}}
{"text": "theory Exe4p4\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 \"\\<not>ev(Suc(Suc(Suc 0)))\"\nproof \n  assume \"ev(Suc(Suc(Suc 0)))\"\n  thus \"False\"\n  proof (induction \"Suc(Suc(Suc 0))\" rule: ev.induct)\n    assume \"ev(Suc 0)\"\n    thus \"False\"\n    proof (induction \"Suc 0\" rule: ev.induct)\n    qed\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/prog-prove/Exe4p4.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9273632896242073, "lm_q2_score": 0.7690802476562641, "lm_q1q2_score": 0.7132167884515132}}
{"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_Locale \n\nimports\n  Z_Toolkit\nbegin\n\ntext {*\n\nThis theory introduces metric space, shows instantiation for different \ntypes and defines limits and continuity for functions in metric \nspaces.  We develop a set-based approach.\n\nA metric space has a distance function between its elements.\nNote that by building this on carrier we assume that the space is not empty.\nThis is a change, so have to be sure that don't run into trouble!\n\n*}\n\nlocale metric_sig = carrier X \n  for X :: \"'a set\" +\n  fixes\n    distance :: \"['a, 'a] \\<rightarrow> \\<real>\" (\"\\<^mdist>{:_:}{:_:}\")\n   \nlocale metric_space = metric_sig +\n  assumes\n    nonneg: \"\\<And> x y \\<bullet> \\<lbrakk> x \\<in> X; y \\<in> X \\<rbrakk> \\<turnstile> 0 \\<le> \\<^mdist>{:x:}{:y:}\" and\n    strict: \"\\<And> x y \\<bullet> \\<lbrakk> x \\<in> X; y \\<in> X \\<rbrakk> \\<turnstile> \\<^mdist>{:x:}{:y:} = 0 \\<Leftrightarrow> x = y\" and\n    symmetric: \"\\<And> x y \\<bullet> \\<lbrakk> x \\<in> X; y \\<in> X \\<rbrakk> \\<turnstile> \\<^mdist>{:x:}{:y:} = \\<^mdist>{:y:}{:x:}\" and\n    subadd: \"\\<And> x y z \\<bullet>\\<lbrakk>  x \\<in> X; y \\<in> X; z \\<in> X \\<rbrakk> \\<turnstile> \\<^mdist>{:x:}{:z:} \\<le> \\<^mdist>{:x:}{:y:} + \\<^mdist>{:y:}{:z:}\"\nbegin\n\n  lemma zero_dist: \n  \"\\<And> x \\<bullet> x \\<in> X \\<turnstile> \\<^mdist>{:x:}{:x:} = 0\"\n  by (auto simp add: strict)\n\n\n  lemma diff_triangle:\n  \"\\<And> x y z \\<bullet> \\<lbrakk> x \\<in> X; y \\<in> X; z \\<in> X \\<rbrakk> \\<turnstile> abs (\\<^mdist>{:x:}{:z:} - \\<^mdist>{:y:}{:z:}) \\<le> \\<^mdist>{:x:}{:y:}\"\n  proof-\n    fix x y z :: 'a\n    assume inX:  \"x \\<in> X\" \"y \\<in> X\" \"z \\<in> X\"\n    from inX have\n    \"\\<^mdist>{:x:}{:z:} \\<le> \\<^mdist>{:x:}{:y:} + \\<^mdist>{:y:}{:z:}\"\n    by (intro subadd, auto)\n    then have R1:\n    \"\\<^mdist>{:x:}{:z:} - \\<^mdist>{:y:}{:z:} \\<le> \\<^mdist>{:x:}{:y:}\"\n    by (auto)\n    from inX have\n    \"\\<^mdist>{:z:}{:y:} \\<le> \\<^mdist>{:z:}{:x:} + \\<^mdist>{:x:}{:y:}\"\n    by (intro subadd, auto)\n    then have\n    \"- \\<^mdist>{:x:}{:y:} \\<le> \\<^mdist>{:z:}{:x:} - \\<^mdist>{:z:}{:y:}\"\n    by (auto)\n    with inX have R2:\n    \"- \\<^mdist>{:x:}{:y:} \\<le> \\<^mdist>{:x:}{:z:} - \\<^mdist>{:y:}{:z:}\"\n    by (auto simp add: symmetric)\n    from R1 R2 show\n    \"abs (\\<^mdist>{:x:}{:z:} - \\<^mdist>{:y:}{:z:}) \\<le> \\<^mdist>{:x:}{:y:}\"\n    by (auto simp add: abs_le_interval_iff)\n  qed\n  \nend\n\nlemmas metric_space_def' = metric_space_def metric_space_axioms_def metric_sig_def carrier_def'   \n\nnotation (zed)\n  metric_space (\"\\<^metricspace>{:_:}{:_:}\")\n\nend\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_Locale.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473879530491, "lm_q2_score": 0.8175744673038222, "lm_q1q2_score": 0.7132089510095949}}
{"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>\n\ntheory Complex_Analysis_Basics\nimports Equivalence_Lebesgue_Henstock_Integration \"~~/src/HOL/Library/Nonpos_Ints\"\nbegin\n\n\nsubsection\\<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 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 within s)\"\n  using has_derivative_compose[of of_real of_real a _ 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 / (fact (Suc n)) = c / (fact n)\"\n  by (simp add: of_nat_mult del: of_nat_Suc times_nat.simps)\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_Re_upper:\n  assumes \"~ (trivial_limit F)\"\n          \"(f \\<longlongrightarrow> 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 \\<longlongrightarrow> 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 \\<longlongrightarrow> 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 \\<longlongrightarrow> 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 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\\<open>DERIV stuff\\<close>\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\n(*generalising DERIV_isconst_all, which requires type real (using the ordering)*)\nlemma DERIV_zero_UNIV_unique:\n  fixes f :: \"'a::{real_normed_field, real_inner} \\<Rightarrow> 'a\"\n  shows \"(\\<And>x. DERIV f x :> 0) \\<Longrightarrow> f x = f a\"\nby (metis DERIV_zero_unique UNIV_I convex_UNIV)\n\nsubsection \\<open>Some limit theorems about real part of real series etc.\\<close>\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 \\<open>Complex number lemmas\\<close>\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 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\ncorollary 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\ncorollary 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 \"~(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\nsubsection\\<open>Holomorphic functions\\<close>\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 field_differentiable (at x within s)\"\n\nnamed_theorems 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_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_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]: \"(op * 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 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_minus [holomorphic_intros]: \"f holomorphic_on s \\<Longrightarrow> (\\<lambda>z. -(f z)) holomorphic_on s\"\n  by (metis field_differentiable_minus holomorphic_on_def)\n\nlemma holomorphic_on_add [holomorphic_intros]:\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 field_differentiable_add)\n\nlemma holomorphic_on_diff [holomorphic_intros]:\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 field_differentiable_diff)\n\nlemma holomorphic_on_mult [holomorphic_intros]:\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 field_differentiable_mult)\n\nlemma holomorphic_on_inverse [holomorphic_intros]:\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 field_differentiable_inverse)\n\nlemma holomorphic_on_divide [holomorphic_intros]:\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 field_differentiable_divide)\n\nlemma holomorphic_on_power [holomorphic_intros]:\n  \"f holomorphic_on s \\<Longrightarrow> (\\<lambda>z. (f z)^n) holomorphic_on s\"\n  unfolding holomorphic_on_def by (metis field_differentiable_power)\n\nlemma holomorphic_on_sum [holomorphic_intros]:\n  \"(\\<And>i. i \\<in> I \\<Longrightarrow> (f i) holomorphic_on s) \\<Longrightarrow> (\\<lambda>x. sum (\\<lambda>i. f i x) I) holomorphic_on s\"\n  unfolding holomorphic_on_def by (metis field_differentiable_sum)\n\nlemma DERIV_deriv_iff_field_differentiable:\n  \"DERIV f x :> deriv f x \\<longleftrightarrow> f field_differentiable at x\"\n  unfolding field_differentiable_def by (metis DERIV_imp_deriv)\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_chain:\n  \"f field_differentiable at x \\<Longrightarrow> g field_differentiable at (f x)\n    \\<Longrightarrow> deriv (g o f) x = deriv g (f x) * deriv f x\"\n  by (metis DERIV_deriv_iff_field_differentiable DERIV_chain DERIV_imp_deriv)\n\nlemma deriv_linear [simp]: \"deriv (\\<lambda>w. c * w) = (\\<lambda>z. c)\"\n  by (metis DERIV_imp_deriv DERIV_cmult_Id)\n\nlemma deriv_ident [simp]: \"deriv (\\<lambda>w. w) = (\\<lambda>z. 1)\"\n  by (metis DERIV_imp_deriv DERIV_ident)\n\nlemma deriv_id [simp]: \"deriv id = (\\<lambda>z. 1)\"\n  by (simp add: id_def)\n\nlemma deriv_const [simp]: \"deriv (\\<lambda>w. c) = (\\<lambda>z. 0)\"\n  by (metis DERIV_imp_deriv DERIV_const)\n\nlemma deriv_add [simp]:\n  \"\\<lbrakk>f field_differentiable at z; g field_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_field_differentiable[symmetric]\n  by (auto intro!: DERIV_imp_deriv derivative_intros)\n\nlemma deriv_diff [simp]:\n  \"\\<lbrakk>f field_differentiable at z; g field_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_field_differentiable[symmetric]\n  by (auto intro!: DERIV_imp_deriv derivative_intros)\n\nlemma deriv_mult [simp]:\n  \"\\<lbrakk>f field_differentiable at z; g field_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_field_differentiable[symmetric]\n  by (auto intro!: DERIV_imp_deriv derivative_eq_intros)\n\nlemma deriv_cmult [simp]:\n  \"f field_differentiable at z \\<Longrightarrow> deriv (\\<lambda>w. c * f w) z = c * deriv f z\"\n  unfolding DERIV_deriv_iff_field_differentiable[symmetric]\n  by (auto intro!: DERIV_imp_deriv derivative_eq_intros)\n\nlemma deriv_cmult_right [simp]:\n  \"f field_differentiable at z \\<Longrightarrow> deriv (\\<lambda>w. f w * c) z = deriv f z * c\"\n  unfolding DERIV_deriv_iff_field_differentiable[symmetric]\n  by (auto intro!: DERIV_imp_deriv derivative_eq_intros)\n\nlemma deriv_cdivide_right [simp]:\n  \"f field_differentiable at z \\<Longrightarrow> deriv (\\<lambda>w. f w / c) z = deriv f z / c\"\n  unfolding Fields.field_class.field_divide_inverse\n  by (blast intro: deriv_cmult_right)\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 DERIV_transform_within_open at_within_open)\n\nlemma deriv_compose_linear:\n  \"f field_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_field_differentiable [symmetric])\napply (drule DERIV_chain' [of \"times c\" c z UNIV f \"deriv f (c * z)\", OF DERIV_cmult_Id])\napply (simp add: algebra_simps)\ndone\n\nlemma nonzero_deriv_nonconstant:\n  assumes df: \"DERIV f \\<xi> :> df\" and S: \"open S\" \"\\<xi> \\<in> S\" and \"df \\<noteq> 0\"\n    shows \"\\<not> f constant_on S\"\nunfolding constant_on_def\nby (metis \\<open>df \\<noteq> 0\\<close> DERIV_transform_within_open [OF df S] DERIV_const DERIV_unique)\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    apply (rule nonzero_deriv_nonconstant [of f \"deriv f \\<xi>\" \\<xi> S])\n    using assms\n    apply (auto simp: holomorphic_derivI)\n    done\n\nsubsection\\<open>Caratheodory characterization\\<close>\n\nlemma field_differentiable_caratheodory_at:\n  \"f field_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: field_differentiable_def has_field_derivative_def)\n\nlemma field_differentiable_caratheodory_within:\n  \"f field_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: field_differentiable_def has_field_derivative_def)\n\nsubsection\\<open>Analyticity on a set\\<close>\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 field_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 field_differentiable (at x)\"\n apply (auto simp: analytic_on_def holomorphic_on_def)\nby (metis Topology_Euclidean_Space.open_ball centre_in_ball field_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 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:\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\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_sum:\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_const analytic_on_add)\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 complex_derivative_chain image_subset_iff)\n  also have \"... = deriv id w\"\n    apply (rule complex_derivative_transform_within_open [where s=S])\n    apply (rule assms holomorphic_on_compose_gen holomorphic_intros)+\n    apply simp\n    done\n  also have \"... = 1\"\n    by simp\n  finally show ?thesis .\nqed\n\nsubsection\\<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)\"\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\\<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 deriv_const analytic_on_const)\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 deriv_const analytic_on_const)\n\nsubsection\\<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 \"\\<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) \\<longlonglongrightarrow> 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\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 \"\\<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\n\nlemma field_differentiable_series:\n  fixes f :: \"nat \\<Rightarrow> complex \\<Rightarrow> complex\"\n  assumes \"convex s\" \"open s\"\n  assumes \"\\<And>n x. x \\<in> s \\<Longrightarrow> (f n has_field_derivative f' n x) (at x)\"\n  assumes \"uniformly_convergent_on s (\\<lambda>n x. \\<Sum>i<n. f' i x)\"\n  assumes \"x0 \\<in> s\" \"summable (\\<lambda>n. f n x0)\" and x: \"x \\<in> s\"\n  shows   \"summable (\\<lambda>n. f n x)\" and \"(\\<lambda>x. \\<Sum>n. f n x) field_differentiable (at x)\"\nproof -\n  from assms(4) obtain g' where A: \"uniform_limit s (\\<lambda>n x. \\<Sum>i<n. f' i x) g' sequentially\"\n    unfolding uniformly_convergent_on_def by blast\n  from x and \\<open>open s\\<close> have s: \"at x within s = at x\" by (rule at_within_open)\n  have \"\\<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)\"\n    by (intro has_field_derivative_series[of s f f' g' x0] assms A has_field_derivative_at_within)\n  then obtain g where g: \"\\<And>x. x \\<in> s \\<Longrightarrow> (\\<lambda>n. f n x) sums g x\"\n    \"\\<And>x. x \\<in> s \\<Longrightarrow> (g has_field_derivative g' x) (at x within s)\" by blast\n  from g[OF x] show \"summable (\\<lambda>n. f n x)\" by (auto simp: summable_def)\n  from g(2)[OF x] have g': \"(g has_derivative op * (g' x)) (at x)\"\n    by (simp add: has_field_derivative_def s)\n  have \"((\\<lambda>x. \\<Sum>n. f n x) has_derivative op * (g' x)) (at x)\"\n    by (rule has_derivative_transform_within_open[OF g' \\<open>open s\\<close> x])\n       (insert g, auto simp: sums_iff)\n  thus \"(\\<lambda>x. \\<Sum>n. f n x) field_differentiable (at x)\" unfolding differentiable_def\n    by (auto simp: summable_def field_differentiable_def has_field_derivative_def)\nqed\n\nlemma field_differentiable_series':\n  fixes f :: \"nat \\<Rightarrow> complex \\<Rightarrow> complex\"\n  assumes \"convex s\" \"open s\"\n  assumes \"\\<And>n x. x \\<in> s \\<Longrightarrow> (f n has_field_derivative f' n x) (at x)\"\n  assumes \"uniformly_convergent_on s (\\<lambda>n x. \\<Sum>i<n. f' i x)\"\n  assumes \"x0 \\<in> s\" \"summable (\\<lambda>n. f n x0)\"\n  shows   \"(\\<lambda>x. \\<Sum>n. f n x) field_differentiable (at x0)\"\n  using field_differentiable_series[OF assms, of x0] \\<open>x0 \\<in> s\\<close> by blast+\n\nsubsection\\<open>Bound theorem\\<close>\n\nlemma field_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\\<open>Inverse function theorem for complex derivatives\\<close>\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  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  by auto\n\nsubsection \\<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 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\"\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 \"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 / (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 \"cmod (f 0 z - (\\<Sum>i\\<le>n. f i w * (z - w) ^ i / (fact i)))\n                \\<le> cmod ((\\<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 * cmod (z - w) ^ n / (fact n) * cmod (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: ends_in_segment 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 / (fact n)\"\n    by (simp add: algebra_simps norm_minus_commute)\n  finally show ?thesis .\nqed\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_within, 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\nsubsection \\<open>Polynomal function extremal theorem, from HOL Light\\<close>\n\nlemma polyfun_extremal_lemma: (*COMPLEX_POLYFUN_EXTREMAL_LEMMA in HOL Light*)\n    fixes c :: \"nat \\<Rightarrow> 'a::real_normed_div_algebra\"\n  assumes \"0 < e\"\n    shows \"\\<exists>M. \\<forall>z. M \\<le> norm(z) \\<longrightarrow> norm (\\<Sum>i\\<le>n. c(i) * z^i) \\<le> e * norm(z) ^ (Suc n)\"\nproof (induct n)\n  case 0 with assms\n  show ?case\n    apply (rule_tac x=\"norm (c 0) / e\" in exI)\n    apply (auto simp: field_simps)\n    done\nnext\n  case (Suc n)\n  obtain M where M: \"\\<And>z. M \\<le> norm z \\<Longrightarrow> norm (\\<Sum>i\\<le>n. c i * z^i) \\<le> e * norm z ^ Suc n\"\n    using Suc assms by blast\n  show ?case\n  proof (rule exI [where x= \"max M (1 + norm(c(Suc n)) / e)\"], clarsimp simp del: power_Suc)\n    fix z::'a\n    assume z1: \"M \\<le> norm z\" and \"1 + norm (c (Suc n)) / e \\<le> norm z\"\n    then have z2: \"e + norm (c (Suc n)) \\<le> e * norm z\"\n      using assms by (simp add: field_simps)\n    have \"norm (\\<Sum>i\\<le>n. c i * z^i) \\<le> e * norm z ^ Suc n\"\n      using M [OF z1] by simp\n    then have \"norm (\\<Sum>i\\<le>n. c i * z^i) + norm (c (Suc n) * z ^ Suc n) \\<le> e * norm z ^ Suc n + norm (c (Suc n) * z ^ Suc n)\"\n      by simp\n    then have \"norm ((\\<Sum>i\\<le>n. c i * z^i) + c (Suc n) * z ^ Suc n) \\<le> e * norm z ^ Suc n + norm (c (Suc n) * z ^ Suc n)\"\n      by (blast intro: norm_triangle_le elim: )\n    also have \"... \\<le> (e + norm (c (Suc n))) * norm z ^ Suc n\"\n      by (simp add: norm_power norm_mult algebra_simps)\n    also have \"... \\<le> (e * norm z) * norm z ^ Suc n\"\n      by (metis z2 mult.commute mult_left_mono norm_ge_zero norm_power)\n    finally show \"norm ((\\<Sum>i\\<le>n. c i * z^i) + c (Suc n) * z ^ Suc n) \\<le> e * norm z ^ Suc (Suc n)\"\n      by simp\n  qed\nqed\n\nlemma polyfun_extremal: (*COMPLEX_POLYFUN_EXTREMAL in HOL Light*)\n    fixes c :: \"nat \\<Rightarrow> 'a::real_normed_div_algebra\"\n  assumes k: \"c k \\<noteq> 0\" \"1\\<le>k\" and kn: \"k\\<le>n\"\n    shows \"eventually (\\<lambda>z. norm (\\<Sum>i\\<le>n. c(i) * z^i) \\<ge> B) at_infinity\"\nusing kn\nproof (induction n)\n  case 0\n  then show ?case\n    using k  by simp\nnext\n  case (Suc m)\n  let ?even = ?case\n  show ?even\n  proof (cases \"c (Suc m) = 0\")\n    case True\n    then show ?even using Suc k\n      by auto (metis antisym_conv less_eq_Suc_le not_le)\n  next\n    case False\n    then obtain M where M:\n          \"\\<And>z. M \\<le> norm z \\<Longrightarrow> norm (\\<Sum>i\\<le>m. c i * z^i) \\<le> norm (c (Suc m)) / 2 * norm z ^ Suc m\"\n      using polyfun_extremal_lemma [of \"norm(c (Suc m)) / 2\" c m] Suc\n      by auto\n    have \"\\<exists>b. \\<forall>z. b \\<le> norm z \\<longrightarrow> B \\<le> norm (\\<Sum>i\\<le>Suc m. c i * z^i)\"\n    proof (rule exI [where x=\"max M (max 1 (\\<bar>B\\<bar> / (norm(c (Suc m)) / 2)))\"], clarsimp simp del: power_Suc)\n      fix z::'a\n      assume z1: \"M \\<le> norm z\" \"1 \\<le> norm z\"\n         and \"\\<bar>B\\<bar> * 2 / norm (c (Suc m)) \\<le> norm z\"\n      then have z2: \"\\<bar>B\\<bar> \\<le> norm (c (Suc m)) * norm z / 2\"\n        using False by (simp add: field_simps)\n      have nz: \"norm z \\<le> norm z ^ Suc m\"\n        by (metis \\<open>1 \\<le> norm z\\<close> One_nat_def less_eq_Suc_le power_increasing power_one_right zero_less_Suc)\n      have *: \"\\<And>y x. norm (c (Suc m)) * norm z / 2 \\<le> norm y - norm x \\<Longrightarrow> B \\<le> norm (x + y)\"\n        by (metis abs_le_iff add.commute norm_diff_ineq order_trans z2)\n      have \"norm z * norm (c (Suc m)) + 2 * norm (\\<Sum>i\\<le>m. c i * z^i)\n            \\<le> norm (c (Suc m)) * norm z + norm (c (Suc m)) * norm z ^ Suc m\"\n        using M [of z] Suc z1  by auto\n      also have \"... \\<le> 2 * (norm (c (Suc m)) * norm z ^ Suc m)\"\n        using nz by (simp add: mult_mono del: power_Suc)\n      finally show \"B \\<le> norm ((\\<Sum>i\\<le>m. c i * z^i) + c (Suc m) * z ^ Suc m)\"\n        using Suc.IH\n        apply (auto simp: eventually_at_infinity)\n        apply (rule *)\n        apply (simp add: field_simps norm_mult norm_power)\n        done\n    qed\n    then show ?even\n      by (simp add: eventually_at_infinity)\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/Analysis/Complex_Analysis_Basics.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8723473746782093, "lm_q2_score": 0.817574478416099, "lm_q1q2_score": 0.7132089498501902}}
{"text": "theory Hensels_Lemma\n  imports Padic_Int_Polynomials\nbegin\n\n\ntext\\<open>\n  The following proof of Hensel's Lemma is directly adapted from Keith Conrad's proof which is\n  given in an online note \\cite{keithconrad}. The same note was used as the basis for a \n  formalization of Hensel's Lemma by Robert Lewis in the Lean proof assistant\n  \\cite{10.1145/3293880.3294089}.  \\<close>\n(**************************************************************************************************)\n(**************************************************************************************************)\nsection\\<open>Auxiliary Lemmas for Hensel's Lemma\\<close>\n(**************************************************************************************************)\n(**************************************************************************************************)\n\nlemma(in ring) minus_sum:\n  assumes \"a \\<in> carrier R\"\n  assumes \"b \\<in> carrier R\"\n  shows \"\\<ominus> (a \\<oplus> b) = \\<ominus> a \\<oplus> \\<ominus> b\"\n  by (simp add: assms(1) assms(2) local.minus_add)\n\ncontext padic_integers\nbegin\n\n\nlemma poly_diff_val:\n  assumes \"f \\<in> carrier Zp_x\"\n  assumes \"a \\<in> carrier Zp\"\n  assumes \"b \\<in> carrier Zp\"\n  shows \"val_Zp (f\\<bullet>a \\<ominus> f\\<bullet>b) \\<ge> val_Zp (a \\<ominus> b)\"\nproof-\n  obtain c where c_def: \"c \\<in> carrier Zp \\<and> (f\\<bullet>a \\<ominus> f\\<bullet>b) = (a \\<ominus> b) \\<otimes> c\"\n    using assms \n    by (meson to_fun_diff_factor)\n  have 1: \"val_Zp c \\<ge> 0\"\n    using c_def val_pos by blast \n  have 2: \"val_Zp (f\\<bullet>a \\<ominus> f\\<bullet>b) = val_Zp (a \\<ominus> b) + (val_Zp c)\"\n    using c_def val_Zp_mult \n    by (simp add: assms(2) assms(3))        \n  then show ?thesis \n    using \"1\" by auto \nqed\n\ntext\\<open>Restricted p-adic division\\<close>\n\ndefinition divide where\n\"divide x y = (if x = \\<zero> then \\<zero> else \n              (\\<p>[^](nat (ord_Zp x - ord_Zp y)) \\<otimes> ac_Zp x \\<otimes> (inv ac_Zp y)))\"\n\nlemma divide_closed:\n  assumes \"x \\<in> carrier Zp\"\n  assumes \"y \\<in> carrier Zp\"\n  assumes \"y \\<noteq> \\<zero>\"\n  shows \"divide x y \\<in> carrier Zp\"\n  unfolding divide_def\n  apply(cases \"x = \\<zero>\")\n  apply auto[1]\n  using assms ac_Zp_is_Unit \n  by (simp add: ac_Zp_in_Zp)\n   \nlemma divide_formula:\n  assumes \"x \\<in> carrier Zp\"\n  assumes \"y \\<in> carrier Zp\"\n  assumes \"y \\<noteq> \\<zero>\"\n  assumes \"val_Zp x \\<ge> val_Zp y\"\n  shows \"y \\<otimes> divide x y = x\"\n  apply(cases \"x = \\<zero>\")\n   apply (simp add: divide_def mult_zero_l)\nproof- assume A: \"x \\<noteq> \\<zero>\"\n  have 0: \"y \\<otimes> divide x y = \\<p>[^] nat (ord_Zp y) \\<otimes> ac_Zp y \\<otimes> (\\<p>[^](nat (ord_Zp x - ord_Zp y)) \\<otimes> ac_Zp x \\<otimes> (inv ac_Zp y))\"\n    using assms ac_Zp_factors_x[of x] ac_Zp_factors_x[of y] A divide_def \n    by auto\n  hence  1: \"y \\<otimes> divide x y = \\<p>[^] nat (ord_Zp  y) \\<otimes> (\\<p>[^](nat (ord_Zp  x - ord_Zp  y)) \\<otimes>  ac_Zp x \\<otimes> ac_Zp y \\<otimes>  (inv ac_Zp y))\"\n    using mult_assoc mult_comm by auto\n  have 2: \"(nat (ord_Zp  y) + nat (ord_Zp  x - ord_Zp  y)) = nat (ord_Zp  x)\"\n    using assms ord_pos[of x] ord_pos[of y] A val_ord_Zp by auto\n  have \"y \\<otimes> divide x y = \\<p>[^] nat (ord_Zp  y) \\<otimes> \\<p>[^](nat (ord_Zp  x - ord_Zp  y)) \\<otimes>  ac_Zp x\"\n    using 1 A assms \n    by (simp add: ac_Zp_in_Zp ac_Zp_is_Unit mult_assoc)\n  thus \"y \\<otimes> divide x y = x\"\n    using \"2\" A ac_Zp_factors_x(1) assms(1) p_natpow_prod by auto\nqed\n\nlemma divide_nonzero:\n  assumes \"x \\<in> nonzero Zp\"\n  assumes \"y \\<in> nonzero Zp\"\n  assumes \"val_Zp x \\<ge> val_Zp y\"\n  shows \"divide x y \\<in> nonzero Zp\"\n  by (metis assms(1) assms(2) assms(3) divide_closed divide_formula mult_zero_l nonzero_closed nonzero_memE(2) nonzero_memI)\n\nlemma val_of_divide:\n  assumes \"x \\<in> carrier Zp\"\n  assumes \"y \\<in> nonzero Zp\"\n  assumes \"val_Zp x \\<ge> val_Zp y\"\n  shows \"val_Zp (divide x y) = val_Zp x - val_Zp y\"\nproof-\n  have 0: \"y \\<otimes> divide x y = x\"\n    by (simp add: assms(1) assms(2) assms(3) divide_formula nonzero_closed nonzero_memE(2))\n  hence \"val_Zp y + val_Zp (divide x y) = val_Zp x\"\n    using assms(1) assms(2) divide_closed nonzero_closed not_nonzero_memI val_Zp_mult by fastforce\n  thus ?thesis \n    by (smt Zp_def add.commute add.left_neutral add.right_neutral add_diff_assoc_eint assms(1) \n        assms(2) divide_nonzero eSuc_minus_eSuc iadd_Suc idiff_0_right mult_zero(1) mult_zero_l\n        nonzero_closed ord_pos order_refl padic_integers.Zp_int_inc_closed padic_integers.mult_comm \n        padic_integers.ord_of_nonzero(2) padic_integers_axioms val_Zp_eq_frac_0 val_Zp_mult val_Zp_p)\nqed\n\nlemma val_of_divide':\n  assumes \"x \\<in> carrier Zp\"\n  assumes \"y \\<in> carrier  Zp\"\n  assumes \"y \\<noteq> \\<zero>\"\n  assumes \"val_Zp x \\<ge> val_Zp y\"\n  shows \"val_Zp (divide x y) = val_Zp x - val_Zp y\"\n  using Zp_def assms(1) assms(2) assms(3) assms(4) padic_integers.not_nonzero_Zp \n    padic_integers.val_of_divide padic_integers_axioms by blast\nend\n\nlemma(in UP_cring) taylor_deg_1_eval''':\n  assumes \"f \\<in> carrier P\"\n  assumes \"a \\<in> carrier R\"\n  assumes \"b \\<in> carrier R\"\n  assumes \"c = to_fun (shift (2::nat) (T\\<^bsub>a\\<^esub> f)) (\\<ominus>b)\"\n  assumes \"b \\<otimes> (deriv f a) = (to_fun f a)\"\n  shows \"to_fun f (a \\<ominus> b) =  (c \\<otimes> b[^](2::nat))\"\nproof-\n  have 0: \"to_fun f (a \\<ominus> b) = (to_fun f a) \\<ominus> (deriv f a \\<otimes> b) \\<oplus> (c \\<otimes> b[^](2::nat))\"\n    using assms taylor_deg_1_eval'' \n    by blast\n  have 1: \"(to_fun f a) \\<ominus> (deriv f a \\<otimes> b) = \\<zero>\"\n    using assms\n  proof -\n    have \"\\<forall>f a. f \\<notin> carrier P \\<or> a \\<notin> carrier R \\<or> to_fun f a \\<in> carrier R\"\n      using to_fun_closed by presburger\n    then show ?thesis\n      using R.m_comm R.r_right_minus_eq assms(1) assms(2) assms(3) assms(5) \n      by (simp add: deriv_closed)\n  qed     \n  have 2: \"to_fun f (a \\<ominus> b) = \\<zero> \\<oplus> (c \\<otimes> b[^](2::nat))\"\n    using 0 1 \n    by simp\n  then show ?thesis using assms\n    by (simp add: taylor_closed to_fun_closed shift_closed)    \nqed\n\nlemma(in padic_integers) res_diff_zero_fact:\n  assumes \"a \\<in> carrier Zp\"\n  assumes \"b \\<in> carrier Zp\"\n  assumes \"(a \\<ominus> b) k = 0\"\n  shows \"a k = b k\" \"a k \\<ominus>\\<^bsub>Zp_res_ring k\\<^esub> b k = 0\"\n   apply(cases \"k = 0\")\n  apply (metis assms(1) assms(2) p_res_ring_0 p_res_ring_0' p_res_ring_car p_residue_padic_int p_residue_range' zero_le)\n   apply (metis R.add.inv_closed R.add.m_lcomm R.minus_eq R.r_neg R.r_zero Zp_residue_add_zero(2) assms(1) assms(2) assms(3))\n    using assms(2) assms(3) residue_of_diff by auto\n\nlemma(in padic_integers) res_diff_zero_fact':\n  assumes \"a \\<in> carrier Zp\"\n  assumes \"b \\<in> carrier Zp\"\n  assumes \"a k = b k\"\n  shows \"a k \\<ominus>\\<^bsub>Zp_res_ring k\\<^esub> b k = 0\"\n  by (simp add: assms(3) residue_minus)\n\nlemma(in padic_integers) res_diff_zero_fact'':\n  assumes \"a \\<in> carrier Zp\"\n  assumes \"b \\<in> carrier Zp\"\n  assumes \"a k = b k\"\n  shows \"(a \\<ominus> b) k = 0\"\n  by (simp add: assms(2) assms(3) res_diff_zero_fact' residue_of_diff)\n\nlemma(in padic_integers) is_Zp_cauchyI': \nassumes \"s \\<in> closed_seqs Zp\"\nassumes \"\\<forall>n::nat. \\<exists> k::int.\\<forall>m.  m \\<ge>  k \\<longrightarrow> val_Zp (s (Suc m) \\<ominus> s m) \\<ge> n\"\nshows \"is_Zp_cauchy s\"\nproof(rule is_Zp_cauchyI)\n  show A0: \"s \\<in> closed_seqs Zp\" \n    by (simp add: assms(1))  \n  show \"\\<And>n. \\<exists>N. \\<forall>n0 n1. N < n0 \\<and> N < n1 \\<longrightarrow> s n0 n = s n1 n\"\n  proof-\n    fix n\n    show \"\\<exists>N. \\<forall>n0 n1. N < n0 \\<and> N < n1 \\<longrightarrow> s n0 n = s n1 n\"\n    proof(induction n)\n      case 0\n      then show ?case \n      proof-\n        have \"\\<forall>n0 n1. 0 < n0 \\<and> 0 < n1 \\<longrightarrow> s n0 0 = s n1 0\"\n          apply auto \n        proof-\n          fix n0 n1::nat\n          assume A: \"n0 > 0\" \"n1 > 0\"\n          have 0: \"s n0 \\<in> carrier Zp\"\n            using A0 \n            by (simp add: closed_seqs_memE)                       \n          have 1: \"s n1 \\<in> carrier Zp\"\n            using A0            \n            by (simp add: closed_seqs_memE)                       \n          show \" s n0 (0::nat) = s n1 (0::nat)\"\n            using A0 Zp_def 0 1 residues_closed \n            by (metis p_res_ring_0')           \n        qed\n        then show ?thesis \n          by blast \n      qed\n    next\n      case (Suc n)\n      fix n\n      assume IH: \"\\<exists>N. \\<forall>n0 n1. N < n0 \\<and> N < n1 \\<longrightarrow> s n0 n = s n1 n\"\n      show \" \\<exists>N. \\<forall>n0 n1. N < n0 \\<and> N < n1 \\<longrightarrow> s n0 (Suc n) = s n1 (Suc n)\"\n      proof-\n        obtain N where N_def: \"\\<forall>n0 n1. N < n0 \\<and> N < n1 \\<longrightarrow> s n0 n = s n1 n\"\n          using IH \n          by blast  \n        obtain k where k_def: \"\\<forall>m.  (Suc m) \\<ge> k \\<longrightarrow> val_Zp (s (Suc (Suc m)) \\<ominus> s (Suc m)) \\<ge> Suc (Suc n)\"\n          using assms  Suc_n_not_le_n \n          by (meson nat_le_iff)\n        have \"\\<forall>n0 n1.  Suc (max N (max n k)) < n0 \\<and>  Suc (max N (max n k))< n1 \\<longrightarrow> s n0 (Suc n) = s n1 (Suc n)\"\n          apply auto\n        proof-\n          fix n0 n1\n          assume A: \"Suc (max N (max n k)) < n0\" \" Suc (max N (max n k)) < n1\"\n          show \"s n0 (Suc n) = s n1 (Suc n) \"\n          proof-\n            obtain K where K_def: \"K = Suc (max N (max n k))\"\n              by simp\n            have P0: \"\\<And>m. s ((Suc m)+ K) (Suc n) = s (Suc K) (Suc n)\"\n              apply auto  \n            proof-\n              fix m\n              show \"s (Suc (m + K)) (Suc n) = s (Suc K) (Suc n)\"\n              apply(induction m)\n                 apply auto \n              proof-\n                fix m\n                assume A0: \" s (Suc (m + K)) (Suc n) = s (Suc K) (Suc n)\"\n                show \" s (Suc (Suc (m + K))) (Suc n) = s (Suc K) (Suc n)\"\n                proof-\n                  have I: \"k < m + K\"\n                    using K_def \n                    by linarith\n                  have \"val_Zp (s (Suc (Suc (m + K))) \\<ominus> s (Suc (m + K))) \\<ge>  Suc (Suc n)\"\n                  proof-\n                    have \"(Suc (m + K)) > k\"\n                      by (simp add: I less_Suc_eq)\n                    then show ?thesis \n                      using k_def less_imp_le_nat \n                      by blast\n                  qed\n                  hence D: \"val_Zp (s (Suc (Suc (m + K))) \\<ominus> s (Suc (m + K))) > (Suc n)\"\n                    using Suc_ile_eq by fastforce\n                  have \"s (Suc (Suc (m + K))) (Suc n) =  s (Suc (m + K)) (Suc n)\"\n                  proof-\n                    have \"(s (Suc (Suc (m + K))) \\<ominus> s (Suc (m + K)))  (Suc n) = 0\"\n                      using D assms(1) res_diff_zero_fact''[of \"s (Suc (Suc (m + K)))\" \"s (Suc (m + K)) \" \"Suc n\"]\n                      val_Zp_dist_res_eq[of \"s (Suc (Suc (m + K)))\" \"s (Suc (m + K)) \"  \"Suc n\"] unfolding val_Zp_dist_def \n                      by (simp add: closed_seqs_memE)                                                                                  \n                    hence 0: \"(s (Suc (Suc (m + K)))  (Suc n) \\<ominus>\\<^bsub>Zp_res_ring (Suc n)\\<^esub> (s (Suc (m + K)))  (Suc n)) = 0\"\n                      using res_diff_zero_fact(2)[of \"s (Suc (Suc (m + K)))\" \"s (Suc (m + K))\" \"Suc n\" ]\n                            assms(1) \n                      by (simp add: closed_seqs_memE)                       \n \n                    show ?thesis \n                    proof-\n                      have 00: \"cring (Zp_res_ring (Suc n))\"\n                        using R_cring by blast\n                      have 01: \" s (Suc (Suc (m + K))) (Suc n) \\<in> carrier (Zp_res_ring (Suc n))\"\n                        using assms(1) closed_seqs_memE residues_closed by blast\n                      have 02: \"(\\<ominus>\\<^bsub>Zp_res_ring (Suc n)\\<^esub> (s (Suc (m + K)) (Suc n))) \\<in> carrier (Zp_res_ring (Suc n)) \"\n                        by (meson \"00\" assms(1) cring.cring_simprules(3) closed_seqs_memE residues_closed)\n                      show ?thesis \n                        unfolding a_minus_def\n                        using  00 01 02  \n                              cring.sum_zero_eq_neg[of \"Zp_res_ring (Suc n)\" \"s (Suc (Suc (m + K))) (Suc n)\"\n                                            \"\\<ominus>\\<^bsub>Zp_res_ring (Suc n)\\<^esub>s (Suc (m + K)) (Suc n)\"]  \n                        by (metis 0  a_minus_def assms(1) cring.cring_simprules(21) closed_seqs_memE \n                            p_res_ring_zero residues_closed)                        \n                    qed\n                  qed\n                  then show ?thesis using A0 assms(1)\n                    by simp   \n                qed\n              qed\n            qed\n            have \"\\<exists>m0. n0 = (Suc m0) + K\"\n            proof-\n              have \"n0 > K\"\n                by (simp add: A(1) K_def)\n              then have \"n0 = (Suc (n0 - K - 1)) + K\"\n                by auto\n              then show ?thesis by blast \n            qed\n            then obtain m0 where m0_def: \"n0 = (Suc m0) + K\"\n              by blast \n            have \"\\<exists>m0. n1 = (Suc m0) + K\"\n            proof-\n              have \"n1 > K\"\n                by (simp add: A(2) K_def)\n              then have \"n1 = (Suc (n1 - K - 1)) + K\"\n                by auto\n              then show ?thesis by blast \n            qed\n            then obtain m1 where m1_def: \"n1 = (Suc m1) + K\"\n              by blast\n            have 0: \"s n0 (Suc n) = s (Suc K) (Suc n)\" \n              using m0_def P0[of \"m0\"] by auto  \n            have 1: \"s n1 (Suc n) = s (Suc K) (Suc n)\" \n              using m1_def P0[of \"m1\"] by auto  \n            show ?thesis using 0 1 \n              by auto\n          qed\n        qed\n        then show ?thesis \n          by blast\n      qed\n    qed\n  qed\nqed\n\n(**************************************************************************************************)\n(**************************************************************************************************)\nsection\\<open>The Proof of Hensel's Lemma\\<close>\n(**************************************************************************************************)\n(**************************************************************************************************)\n\nsubsection\\<open>Building a Locale for the Proof of Hensel's Lemma\\<close>\n\nlocale hensel = padic_integers+ \n  fixes f::padic_int_poly\n  fixes a::padic_int\n  assumes f_closed[simp]: \"f \\<in> carrier Zp_x\"\n  assumes a_closed[simp]: \"a \\<in> carrier Zp\"\n  assumes fa_nonzero[simp]: \"f\\<bullet>a \\<noteq>\\<zero>\"\n  assumes hensel_hypothesis[simp]: \"(val_Zp (f\\<bullet>a) > 2* val_Zp ((pderiv f)\\<bullet>a))\"\n\nsublocale hensel < cring Zp\n  by (simp add: R.is_cring)\n\ncontext hensel\nbegin\n\nabbreviation f' where\n\"f' \\<equiv> pderiv f\"\n\nlemma f'_closed:\n\"f' \\<in> carrier Zp_x\"\n  using f_closed pderiv_closed by blast \n  \nlemma f'_vals_closed:\n  assumes \"a \\<in> carrier Zp\"\n  shows \"f'\\<bullet>a \\<in> carrier Zp\"\n  by (simp add: UP_cring.to_fun_closed Zp_x_is_UP_cring f'_closed)\n  \nlemma fa_closed:\n\"(f\\<bullet>a) \\<in> carrier Zp\"\n  by (simp add: UP_cring.to_fun_closed Zp_x_is_UP_cring)\n\nlemma f'a_closed:\n\"(f'\\<bullet>a) \\<in> carrier Zp\"\nproof-\n  have \"f' \\<in> carrier Zp_x\"\n    by (simp add: f'_closed)  \n  then show ?thesis \n    by (simp add: f'_vals_closed)\nqed\n\nlemma fa_nonzero':\n\"(f\\<bullet>a) \\<in> nonzero Zp\"\n  using fa_closed fa_nonzero not_nonzero_Zp by blast\n\nlemma f'a_nonzero[simp]:\n\"(f'\\<bullet>a) \\<noteq> \\<zero>\"\nproof(rule ccontr)\n  assume \"\\<not> (f'\\<bullet>a) \\<noteq> \\<zero>\"\n  then have \"(f'\\<bullet>a) = \\<zero>\"\n    by blast \n  then have \"\\<infinity> < val_Zp (f\\<bullet>a)\" using hensel_hypothesis \n    by (simp add: val_Zp_def)\n  thus False \n    using eint_ord_simps(6) by blast\nqed      \n\nlemma f'a_nonzero':\n\"(f'\\<bullet>a) \\<in> nonzero Zp\"\n  using f'a_closed f'a_nonzero not_nonzero_Zp by blast\n\nlemma f'a_not_infinite[simp]: \n\"val_Zp (f'\\<bullet>a) \\<noteq> \\<infinity>\"\n  by (metis eint_ord_code(3) hensel_hypothesis linorder_not_less times_eint_simps(4))\n\nlemma f'a_nonneg_val[simp]: \n\"val_Zp ((f'\\<bullet>a)) \\<ge> 0\"\n  using f'a_closed val_pos by blast\n\nlemma hensel_hypothesis_weakened:\n\"val_Zp (f\\<bullet>a) > val_Zp (f'\\<bullet>a)\"\nproof-\n  have 0: \"0 \\<le> val_Zp (f'\\<bullet>a) \\<and> val_Zp (f'\\<bullet>a) \\<noteq> \\<infinity>\"\n    using f'a_closed val_ord_Zp val_pos by force\n  have 1: \"1 < eint 2 \"\n    by (simp add: one_eint_def)\n  thus ?thesis   using 0 eint_mult_mono'[of \"val_Zp (f'\\<bullet>a)\" 1 2] hensel_hypothesis \n    by (metis linorder_not_less mult_one_left order_trans)\nqed\n\nsubsection\\<open>Constructing the Newton Sequence\\<close>\n\ndefinition newton_step :: \"padic_int \\<Rightarrow> padic_int\" where\n\"newton_step x = x \\<ominus> (divide (f\\<bullet>x) (f'\\<bullet>x))\"\n\nlemma newton_step_closed:\n  \"newton_step a \\<in> carrier Zp\"\n  using  divide_closed unfolding newton_step_def \n  using f'a_closed f'a_nonzero fa_closed local.a_closed by blast\n  \nfun newton_seq :: \"padic_int_seq\" (\"ns\") where\n\"newton_seq 0 = a\"|\n\"newton_seq (Suc n) = newton_step (newton_seq n)\"\n\nsubsection\\<open>Key Properties of the Newton Sequence\\<close>\n\nlemma hensel_factor_id:\n\"(divide (f\\<bullet>a) (f'\\<bullet>a)) \\<otimes> ((f'\\<bullet>a)) = (f\\<bullet>a)\"\n  using hensel_hypothesis hensel_axioms divide_formula f'a_closed \n        fa_closed hensel_hypothesis_weakened mult_comm \n  by auto\n\ndefinition hensel_factor (\"t\") where\n\"hensel_factor = val_Zp (f\\<bullet>a) - 2*(val_Zp (f'\\<bullet>a))\"\n\nlemma t_pos[simp]:\n\"t > 0\"\n  using hensel_factor_def hensel_hypothesis \n  by (simp add: eint_minus_le)\n\nlemma t_neq_infty[simp]:\n\"t \\<noteq> \\<infinity>\"\n  by (simp add: hensel_factor_def val_Zp_def)\n\nlemma t_times_pow_pos[simp]:\n\"(2^(n::nat))*t > 0\"\n  apply(cases \"n = 0\")\n  using one_eint_def apply auto[1]\n    using eint_mult_mono'[of t 1 \"2^n\"] t_pos\n  by (smt eint_ord_simps(2) linorder_not_less mult_one_left neq0_conv one_eint_def order_less_le order_trans self_le_power t_neq_infty)\n\nlemma newton_seq_props_induct:\nshows \"\\<And>k. k \\<le> n \\<Longrightarrow> (ns k) \\<in> carrier Zp\n              \\<and> val_Zp (f'\\<bullet>(ns k)) = val_Zp ((f'\\<bullet>a))\n              \\<and> val_Zp (f\\<bullet>(ns k)) \\<ge> 2*(val_Zp (f'\\<bullet>a)) + (2^k)*t\"\nproof(induction n)\n  case 0\n  then have kz: \"k = 0\"\n    by simp\n  have B0: \"( ns k) \\<in> carrier Zp\"\n    using kz \n    by simp\n  have B1: \"val_Zp (f' \\<bullet> ns k) = (val_Zp (f'\\<bullet>a))\"\n    using kz newton_seq.simps(1) \n    by presburger \n  have B2: \"val_Zp (f \\<bullet> (ns k)) \\<ge> (2 * (val_Zp (f'\\<bullet>a))) + 2 ^ k * t\"\n  proof-\n    have B20: \"(2 * (val_Zp (f'\\<bullet>a))) + 2 ^ k * t = (2 * (val_Zp (f'\\<bullet>a))) +  t\"\n    proof-\n      have \"(2 * (val_Zp (f'\\<bullet>a))) + 2 ^ k * t = (2 * (val_Zp (f'\\<bullet>a))) +  t\"\n        using kz  one_eint_def by auto        \n      then show ?thesis \n        by blast\n    qed\n    then have \"(2 * (val_Zp (f'\\<bullet>a))) + 2 ^ k * t = (2 * (val_Zp (f'\\<bullet>a))) + val_Zp (f\\<bullet>a) - 2*(val_Zp (f'\\<bullet>a))\"\n      unfolding hensel_factor_def \n      by (simp add: val_Zp_def)\n    then have \"(2 * (val_Zp (f'\\<bullet>a))) + 2 ^ k * t =  val_Zp (f\\<bullet>a)\"\n      by (metis add_diff_cancel_eint eint_ord_simps(6) hensel_hypothesis)     \n    thus ?thesis       by (simp add: kz)      \n  qed\n  thus ?case \n    using B0 B1 by blast    \nnext\n  case (Suc n)\n  show ?case\n  proof(cases \"k \\<le> n\")\n    case True\n    then show ?thesis using  Suc.IH \n      by blast\n    next\n      case False\n      have F1: \"(ns n) \\<in> carrier Zp\"\n        using  Suc.IH   by blast      \n      have F2: \"val_Zp (f'\\<bullet>(ns n)) = val_Zp ((f'\\<bullet>a))\"\n        using  Suc.IH  by blast      \n      have F3: \"val_Zp (f\\<bullet>(ns n)) \\<ge> 2*(val_Zp (f'\\<bullet>a)) + (2^n)*t\"\n        using  Suc.IH  by blast \n      have kval: \"k = Suc n\"\n        using False Suc.prems le_Suc_eq by blast        \n      have F6: \"val_Zp (f\\<bullet>(ns n)) \\<ge> val_Zp (f'\\<bullet>(ns n))\"\n      proof-\n        have \"2*(val_Zp (f'\\<bullet>a))  \\<ge> val_Zp (f'\\<bullet>a)\"\n          using f'a_closed val_pos eint_mult_mono'[of \"val_Zp (f'\\<bullet>a)\" 1 2]  \n          by (metis Groups.add_ac(2) add.right_neutral eSuc_eint eint_0_iff(2) eint_add_left_cancel_le\n              eint_ord_simps(2) f'a_nonneg_val f'a_not_infinite infinity_ne_i1 linorder_not_less \n              mult_one_left not_one_less_zero one_add_one one_eint_def order_less_le order_trans zero_one_eint_neq(1))\n        hence  \"2*(val_Zp (f'\\<bullet>a)) + (2^n)*t  \\<ge> val_Zp (f'\\<bullet>a)\"\n          using t_times_pow_pos[of n] \n          by (metis (no_types, lifting) add.right_neutral eint_add_left_cancel_le order_less_le order_trans)    \n        then show ?thesis \n          using F2 F3 by auto                            \n      qed\n      have F5: \" divide (f\\<bullet>(ns n))(f'\\<bullet>(ns n)) \\<in> carrier Zp\"\n      proof-\n        have 00: \"f \\<bullet> ns n \\<in> carrier Zp\"\n          by (simp add: F1 to_fun_closed)                     \n        have \"val_Zp ((f'\\<bullet>a)) \\<noteq> val_Zp \\<zero>\"\n          by (simp add:  val_Zp_def)\n        then have 01: \"f' \\<bullet> ns n \\<in> nonzero Zp\"\n          using F2 F1 Zp_x_is_UP_cring f'_closed nonzero_def\n        proof -\n          have \"f' \\<bullet> ns n \\<in> carrier Zp\"\n            using F1 Zp_continuous_is_Zp_closed f'_closed  polynomial_is_Zp_continuous\n            by (simp add: to_fun_closed) \n          then show ?thesis\n            using F2 \\<open>val_Zp (f'\\<bullet>a) \\<noteq> val_Zp \\<zero>\\<close> not_nonzero_Zp by fastforce\n        qed           \n        then show ?thesis \n          using F6 \n          by (metis \"00\" F2 \\<open>val_Zp (f'\\<bullet>a) \\<noteq> val_Zp \\<zero>\\<close> divide_closed nonzero_closed)          \n      qed\n      have F4:  \"(ns k) \\<ominus> (ns n) = (\\<ominus> divide (f\\<bullet>(ns n))(f'\\<bullet>(ns n)))\"\n        using F1 F5 newton_seq.simps(2)[of n] kval\n        unfolding newton_step_def \n        by (metis R.l_neg R.minus_closed R.minus_zero R.plus_diff_simp R.r_neg2 R.r_right_minus_eq \n            a_minus_def local.a_closed minus_a_inv)\n      have F7: \"val_Zp (divide (f\\<bullet>(ns n))(f'\\<bullet>(ns n))) = val_Zp (f\\<bullet>(ns n)) - val_Zp (f'\\<bullet>(ns n))\"\n        apply(rule val_of_divide)\n           apply (simp add: F1 to_fun_closed)\n            using F1 f'_closed to_fun_closed F2 not_nonzero_Zp val_Zp_def apply fastforce\n              by (simp add: F6)\n      show ?thesis\n      proof\n        show P0:\"ns k \\<in> carrier Zp\"\n        proof- \n          have A0: \"ns k = ns n \\<ominus> (divide (f\\<bullet> (ns n)) (f'\\<bullet>(ns n)))\"\n            by (simp add: kval newton_step_def)          \n          have A1: \"val_Zp (f'\\<bullet>(ns n)) = val_Zp (f'\\<bullet>a)\"\n            using  Suc.IH  \n            by blast\n          have A2: \"val_Zp (f\\<bullet>(ns n)) \\<ge>val_Zp (f'\\<bullet>a)\"\n          proof-\n            have A20: \"(2 * val_Zp (f'\\<bullet>a)) + 2 ^ n * (val_Zp (f\\<bullet>a) - 2 * val_Zp (f'\\<bullet>a)) \\<ge>val_Zp (f'\\<bullet>a)\"\n            proof-\n              have \"val_Zp (f\\<bullet>a) - 2 * val_Zp (f'\\<bullet>a) > 0\"\n                using hensel_hypothesis eint_minus_le by blast                \n              then have \"  (2 ^ n) * (val_Zp (f\\<bullet>a) - 2 * val_Zp (f'\\<bullet>a))\n                        \\<ge> (val_Zp (f\\<bullet>a) - 2 * val_Zp (f'\\<bullet>a))\"\n                using eint_pos_int_times_ge by auto\n              then have  \"  ((2 * val_Zp (f'\\<bullet>a)) + 2 ^ n * (val_Zp (f\\<bullet>a) - 2 * val_Zp (f'\\<bullet>a)))\n                        \\<ge> (2 * val_Zp (f'\\<bullet>a)) + (val_Zp (f\\<bullet>a) - 2 * val_Zp (f'\\<bullet>a))\"\n                by (simp add: val_Zp_def)\n              then have  \"  ((2 * val_Zp (f'\\<bullet>a)) + 2 ^ n * (val_Zp (f\\<bullet>a) - 2 * val_Zp (f'\\<bullet>a)))\n                        \\<ge> (val_Zp (f\\<bullet>a) )\"\n                by simp \n              then show  \"  ((2 * val_Zp (f'\\<bullet>a)) + 2 ^ n * (val_Zp (f\\<bullet>a) - 2 * val_Zp (f'\\<bullet>a)))\n                        \\<ge> (val_Zp (f'\\<bullet>a) )\"\n                using hensel_hypothesis_weakened by auto                 \n            qed\n            have A21:\"val_Zp (f\\<bullet>(ns n)) \\<ge> (2 * val_Zp (f'\\<bullet>a)) + 2 ^ n * (val_Zp (f\\<bullet>a) - 2 * val_Zp (f'\\<bullet>a))\"\n              using  Suc.IH unfolding hensel_factor_def \n              by blast              \n            show ?thesis using A21 A20 \n              by auto              \n          qed\n          have A3: \"ns n \\<in> carrier Zp\"\n            using  Suc.IH by blast \n          have A4: \"val_Zp (f\\<bullet>(ns n)) \\<ge>val_Zp (f'\\<bullet>(ns n))\"\n            using A1 A2 \n            by presburger\n          have A5: \"f\\<bullet>(ns n) \\<in> carrier Zp\"\n            by (simp add: F1 UP_cring.to_fun_closed Zp_x_is_UP_cring)                      \n          have A6: \"(f'\\<bullet>(ns n)) \\<in> nonzero Zp\"\n          proof-\n            have \"(f'\\<bullet>(ns n)) \\<in> carrier  Zp\"\n              by (simp add: F1 UP_cring.to_fun_closed Zp_x_is_UP_cring f'_closed)                 \n            have \"val_Zp (f'\\<bullet>(ns n)) \\<noteq> \\<infinity>\"\n              using A1 \n              by (simp add:  val_Zp_def)              \n            then show ?thesis \n              using \\<open>f' \\<bullet> ns n \\<in> carrier Zp\\<close> not_nonzero_Zp val_Zp_def \n              by meson\n          qed\n          have A7: \" (divide (f\\<bullet> (ns n)) (f'\\<bullet>(ns n))) \\<in> carrier Zp\"\n            using A5 A6 A4 A3 F5 by linarith            \n          then show ?thesis \n            using A0 A3 cring.cring_simprules(4) \n            by (simp add: F1 F5 cring.cring_simprules(4))\n        qed\n        have P1: \"val_Zp (f' \\<bullet> ns k) = val_Zp (f'\\<bullet>a) \"\n        proof(cases \"(f' \\<bullet> ns k) = (f' \\<bullet> ns n)\")\n          case True\n          then show ?thesis using  Suc.IH\n            by (metis order_refl)\n        next\n          case False\n          have \"val_Zp ((f' \\<bullet> ns k) \\<ominus> (f' \\<bullet> ns n)) \\<ge> val_Zp ((ns k) \\<ominus> (ns n))\"\n            using False P0 f'_closed  poly_diff_val  Suc.IH \n            by blast\n          then have \"val_Zp ((f' \\<bullet> ns k) \\<ominus> (f' \\<bullet> ns n)) \\<ge> val_Zp (\\<ominus> divide (f\\<bullet>(ns n))(f'\\<bullet>(ns n)))\"\n            using  F4 by metis  \n          then have \"val_Zp ((f' \\<bullet> ns k) \\<ominus> (f' \\<bullet> ns n)) \\<ge> val_Zp (divide (f\\<bullet>(ns n))(f'\\<bullet>(ns n)))\"\n            using F5 val_Zp_of_minus \n            by presburger                        \n          then have P10: \"val_Zp ((f' \\<bullet> ns k) \\<ominus> (f' \\<bullet> ns n)) \\<ge> val_Zp (f\\<bullet>(ns n)) - val_Zp (f'\\<bullet>(ns n))\"\n            using F7 by metis \n          have P11: \"val_Zp (f'\\<bullet>(ns n)) \\<noteq> \\<infinity>\"\n            by (simp add: F2)           \n          then have \"val_Zp ((f' \\<bullet> ns k) \\<ominus> (f' \\<bullet> ns n)) \\<ge> (2 * val_Zp (f'\\<bullet>a)) + 2 ^ n * t -  val_Zp (f'\\<bullet>(ns n))\"\n            using F3 P10  \n            by (smt eint_add_cancel_fact eint_add_left_cancel_le order_trans)                \n          then have P12: \"val_Zp ((f' \\<bullet> ns k) \\<ominus> (f' \\<bullet> ns n)) \\<ge> (2 *(val_Zp (f'\\<bullet>a))) + 2 ^ n * t - (val_Zp (f'\\<bullet>a))\"\n            by (simp add: F2)            \n          have P13:\"val_Zp ((f' \\<bullet> ns k) \\<ominus> (f' \\<bullet> ns n)) \\<ge> (val_Zp (f'\\<bullet>a)) + 2 ^ n * t \"\n          proof-\n            have \"(2 *(val_Zp (f'\\<bullet>a))) + (2 ^ n * t) - (val_Zp (f'\\<bullet>a)) =  (2 *(val_Zp (f'\\<bullet>a))) - (val_Zp (f'\\<bullet>a)) + (2 ^ n * t) \"\n              using eint_minus_comm by blast            \n            then show ?thesis using P12 \n              using f'a_not_infinite by force\n          qed\n          then have P14: \"val_Zp ((f' \\<bullet> ns k) \\<ominus> (f' \\<bullet> ns n)) > (val_Zp (f'\\<bullet>a))\"\n            using f'a_not_infinite ge_plus_pos_imp_gt t_times_pow_pos by blast\n          show ?thesis \n            by (meson F1 F2 P0 P14 equal_val_Zp f'_closed f'a_closed to_fun_closed)\n        qed\n        have P2: \"val_Zp (f\\<bullet>(ns k)) \\<ge> 2*(val_Zp (f'\\<bullet>a)) + (2^k)*t\"\n        proof- \n          have P23: \"2 * (val_Zp (f'\\<bullet>a)) + ((2 ^ k) * t) \\<le> val_Zp (f \\<bullet> ns k)\"\n          proof-\n            have 0: \"ns n \\<in> carrier Zp\"\n              by (simp add: F1)\n            have 1: \"local.divide (f \\<bullet> ns n) (f' \\<bullet> ns n) \\<in> carrier Zp\"\n              using F5 by blast\n            have 2: \"(poly_shift_iter 2 (taylor (ns n) f)) \\<bullet> \\<ominus> local.divide (f \\<bullet> ns n) (f' \\<bullet> ns n) \\<in> carrier Zp\"\n              using F1 F5 shift_closed 1  \n              by (simp add: taylor_closed to_fun_closed)\n            have 3: \"divide (f \\<bullet> ns n) (f' \\<bullet> ns n) \\<otimes> deriv f (ns n) = f \\<bullet> ns n\"\n              by (metis F1 F2 F6 divide_formula f'_closed f'a_not_infinite f_closed mult_comm pderiv_eval_deriv to_fun_closed val_Zp_def)                  \n            have 4: \"f \\<in> carrier Zp_x\"\n              by simp\n            obtain c where c_def: \"c = poly_shift_iter (2::nat) (taylor (ns n) f) \\<bullet> \\<ominus> local.divide (f \\<bullet> ns n) (f' \\<bullet> ns n)\"\n              by blast\n            then have c_def': \"c \\<in> carrier Zp \\<and> f \\<bullet> (ns n \\<ominus> local.divide (f \\<bullet> ns n) (f' \\<bullet> ns n)) = c \\<otimes> local.divide (f \\<bullet> ns n) (f' \\<bullet> ns n) [^] (2::nat)\"\n              using 0 1 2 3 4 UP_cring.taylor_deg_1_eval'''[of Zp f \"ns n\" \"(divide (f\\<bullet>(ns n)) (f'\\<bullet>(ns n)))\" c]\n                Zp_x_is_UP_cring\n              by blast\n            have P230: \"f\\<bullet>(ns k) =  (c \\<otimes> (divide (f\\<bullet>(ns n)) (f'\\<bullet>(ns n)))[^](2::nat))\"\n              using c_def' \n              by (simp add: kval newton_step_def)                \n            have P231: \"val_Zp (f\\<bullet>(ns k)) = val_Zp c + 2*(val_Zp (f\\<bullet>(ns n)) - val_Zp(f'\\<bullet>(ns n)))\"\n                proof-\n                  have P2310: \"val_Zp (f\\<bullet>(ns k)) =  val_Zp c + val_Zp ((divide (f\\<bullet>(ns n)) (f'\\<bullet>(ns n)))[^](2::nat))\"\n                    by (simp add: F5 P230 c_def' val_Zp_mult)                \n                  have P2311: \"val_Zp ((divide (f\\<bullet>(ns n)) (f'\\<bullet>(ns n)))[^](2::nat)) \n                                                    =  2*(val_Zp (f\\<bullet>(ns n)) - val_Zp(f'\\<bullet>(ns n)))\"\n                    by (metis  F5 F7 R.pow_zero mult.commute not_nonzero_Zp of_nat_numeral times_eint_simps(3) val_Zp_def val_Zp_pow' zero_less_numeral)\n                  thus ?thesis \n                    by (simp add: P2310)                \n                qed\n                have P232: \"val_Zp (f\\<bullet>(ns k)) \\<ge> 2*(val_Zp (f\\<bullet>(ns n)) - val_Zp(f'\\<bullet>(ns n)))\"\n                  by (simp add: P231 c_def' val_pos)                \n                have P236:  \"val_Zp (f\\<bullet>(ns k)) \\<ge> 2*(2 *val_Zp (f'\\<bullet>a) + 2 ^ n * t)  - 2* val_Zp(f'\\<bullet>(ns n))\"\n                  using P232 F3 eint_minus_ineq''[of \"val_Zp(f'\\<bullet>(ns n))\" \"(2 *val_Zp (f'\\<bullet>a)) + 2 ^ n * t\" \"val_Zp (f\\<bullet>(ns n))\" 2 ]\n                       F2 eint_pow_int_is_pos by auto\n                hence  P237:  \"val_Zp (f\\<bullet>(ns k)) \\<ge>(4*val_Zp (f'\\<bullet>a)) + (2*((2 ^ n)* t)) - 2* val_Zp(f'\\<bullet>(ns n))\"\n                proof-\n                  have \"2*(2*val_Zp (f'\\<bullet>a) + 2 ^ n * t)  = (4*val_Zp (f'\\<bullet>a)) + 2*(2 ^ n)* t \"\n                    using distrib_left[of 2 \"2*val_Zp (f'\\<bullet>a)\" \"2 ^ n * t\"] mult.assoc mult_one_right one_eint_def plus_eint_simps(1)\n                          hensel_factor_def val_Zp_def by auto\n                  then show ?thesis \n                    using P236 \n                    by (metis mult.assoc)                  \n                qed\n                hence P237:  \"val_Zp (f\\<bullet>(ns k)) \\<ge> 4*val_Zp (f'\\<bullet>a) + 2*(2 ^ n)* t - 2* val_Zp((f'\\<bullet>a))\"\n                  by (metis F2 mult.assoc)                                  \n                hence P238: \"val_Zp (f\\<bullet>(ns k)) \\<ge> 2*val_Zp (f'\\<bullet>a) + 2*(2 ^ n)* t\"\n                  using eint_minus_comm[of \"4*val_Zp (f'\\<bullet>a) \" \"2*(2 ^ n)* t\" \"2* val_Zp((f'\\<bullet>a))\"]\n                  by (simp add: eint_int_minus_distr)\n                thus ?thesis \n                  by (simp add: kval)               \n          qed\n          thus ?thesis \n            by blast   \n        qed\n        show \"val_Zp (to_fun f' (ns k)) = val_Zp (f'\\<bullet>a) \\<and> \n                2 * val_Zp (f'\\<bullet>a) + eint (2 ^ k) * t \\<le> val_Zp (to_fun f (ns k))\"\n          using P1 P2 by blast\n      qed\n    qed\nqed\n\nlemma newton_seq_closed:\nshows \"ns m \\<in> carrier Zp\"\n  using newton_seq_props_induct \n  by blast\n\nlemma f_of_newton_seq_closed:\nshows \"f \\<bullet> ns m \\<in> carrier Zp\"\n  by (simp add: to_fun_closed newton_seq_closed)\n\nlemma newton_seq_fact1[simp]:\n\" val_Zp (f'\\<bullet>(ns k)) = val_Zp ((f'\\<bullet>a))\"\nusing newton_seq_props_induct by blast\n\nlemma newton_seq_fact2:\n\"\\<And>k.  val_Zp (f\\<bullet>(ns k)) \\<ge> 2*(val_Zp (f'\\<bullet>a)) + (2^k)*t\"\n  by (meson le_iff_add newton_seq_props_induct)\n\nlemma newton_seq_fact3:\n\"val_Zp (f\\<bullet>(ns l)) \\<ge> val_Zp (f'\\<bullet>(ns l))\"\nproof-\n  have \"2*(val_Zp (f'\\<bullet>a)) + (2^l)*t \\<ge> (val_Zp (f'\\<bullet>a))\"\n    using f'a_closed ord_pos t_pos \n    by (smt eint_pos_int_times_ge f'a_nonneg_val f'a_not_infinite ge_plus_pos_imp_gt linorder_not_less nat_mult_not_infty order_less_le t_times_pow_pos)    \n  then show \"val_Zp (f \\<bullet> ns l) \\<ge> val_Zp (f' \\<bullet> ns l) \"\n    using  f'a_closed f'a_nonzero newton_seq_fact1[of l] newton_seq_fact2[of l]  val_Zp_def \n    proof -\n    show ?thesis\n      using \\<open>eint 2 * val_Zp (f'\\<bullet>a) + eint (2 ^ l) * t \\<le> val_Zp (to_fun f (ns l))\\<close> \\<open>val_Zp (f'\\<bullet>a) \\<le> eint 2 * val_Zp (f'\\<bullet>a) + eint (2 ^ l) * t\\<close> by force\n    qed  \nqed\n\nlemma newton_seq_fact4[simp]:\n  assumes \"f\\<bullet>(ns l) \\<noteq>\\<zero>\"\n  shows \"val_Zp (f\\<bullet>(ns l)) \\<ge> val_Zp (f'\\<bullet>(ns l))\"\n  using newton_seq_fact3 by blast\n\nlemma newton_seq_fact5:\n\"divide (f \\<bullet> ns l) (f' \\<bullet> ns l) \\<in> carrier Zp\"\n  apply(rule divide_closed) \n  apply (simp add: to_fun_closed newton_seq_closed)\n  apply (simp add: f'_closed to_fun_closed newton_seq_closed)\n  by (metis f'a_not_infinite newton_seq_fact1 val_Zp_def)\n   \nlemma newton_seq_fact6:\n\"(f'\\<bullet>(ns l)) \\<in> nonzero Zp\"\n  apply(rule ccontr)\n  using  nonzero_memI nonzero_memE  \n        f'a_nonzero newton_seq_fact1  val_Zp_def\n  by (metis (no_types, lifting) divide_closed f'_closed f'a_closed fa_closed hensel_factor_id \n      hensel_hypothesis_weakened mult_zero_l newton_seq_closed order_less_le to_fun_closed val_Zp_mult)\n\nlemma newton_seq_fact7:\n \"(ns (Suc n)) \\<ominus> (ns n) = \\<ominus>divide (f\\<bullet>(ns n)) (f'\\<bullet>(ns n))\"\n  using newton_seq.simps(2)[of n]  newton_seq_fact5[of n] \n        newton_seq_closed[of \"Suc n\"]  newton_seq_closed[of n] \n        R.ring_simprules\n  unfolding newton_step_def a_minus_def \n  by smt \n\nlemma newton_seq_fact8:\n  assumes \"f\\<bullet>(ns l) \\<noteq>\\<zero>\"\n  shows \"divide (f \\<bullet> ns l) (f' \\<bullet> ns l) \\<in> nonzero Zp\"\n  using assms divide_nonzero[of \"f \\<bullet> ns l\" \"f' \\<bullet> ns l\"]\n        nonzero_memI \n  using f_of_newton_seq_closed newton_seq_fact3 newton_seq_fact6 by blast\n\nlemma newton_seq_fact9:\n  assumes \"f\\<bullet>(ns n) \\<noteq>\\<zero>\"\n  shows \"val_Zp((ns (Suc n)) \\<ominus> (ns n)) = val_Zp (f\\<bullet>(ns n)) - val_Zp (f'\\<bullet>(ns n))\"\n  using newton_seq_fact7 val_of_divide newton_seq_fact6 assms nonzero_memI\n        f_of_newton_seq_closed newton_seq_fact4 newton_seq_fact5 \n  by (metis val_Zp_of_minus)\n\ntext\\<open>Assuming no element of the Newton sequence is a root of f, the Newton sequence is Cauchy.\\<close>\n\nlemma newton_seq_is_Zp_cauchy_0:\nassumes \"\\<And>k. f\\<bullet>(ns k) \\<noteq>\\<zero>\"\nshows \"is_Zp_cauchy ns\"\nproof(rule is_Zp_cauchyI')\n  show P0: \"ns \\<in> closed_seqs Zp\"\n  proof(rule closed_seqs_memI)\n    show \"\\<And>k. ns k \\<in> carrier Zp \"\n     by (simp add: newton_seq_closed)\n qed\n  show \"\\<forall>n. \\<exists>k. \\<forall>m. k \\<le> int m \\<longrightarrow> int n \\<le> val_Zp (ns (Suc m) \\<ominus> ns m)\"\n  proof\n    fix n\n    show \"\\<exists>k. \\<forall>m. k \\<le> int m \\<longrightarrow> int n \\<le> val_Zp (ns (Suc m) \\<ominus> ns m)\"\n    proof(induction \"n\")\n      case 0\n      have B0: \"\\<forall>n0 n1. 0 < n0 \\<and> 0 < n1 \\<longrightarrow> ns n0 0 = ns n1 0\"\n        apply auto \n      proof-\n        fix n0 n1::nat \n        assume A: \"0 < n0\" \"0 < n1\"\n        show \"ns n0 0 = ns n1 0\"\n        proof-\n          have 0: \"ns n0 \\<in> carrier Zp\"\n            using P0 \n            by (simp add: newton_seq_closed)           \n          have 1: \"ns n1 \\<in> carrier Zp\"\n            using P0 \n            by (simp add: newton_seq_closed)      \n          show ?thesis\n            using 0 1 Zp_defs(3) prime  \n            by (metis p_res_ring_0' residue_closed)                                \n        qed\n      qed\n      have \"\\<forall>m. 1 \\<le> int m \\<longrightarrow> int 0 \\<le> val_Zp_dist (newton_step (ns m)) (ns m)\"\n      proof\n        fix m\n        show \"1 \\<le> int m \\<longrightarrow> int 0 \\<le> val_Zp_dist (newton_step (ns m)) (ns m)\"\n        proof\n        assume \"1 \\<le> int m \"\n        then have C0:\"ns (Suc m) 0 = ns m 0\"\n          using B0 \n          by (metis int_one_le_iff_zero_less int_ops(1) less_Suc_eq_0_disj of_nat_less_iff)\n        then show \"int 0 \\<le> val_Zp_dist (newton_step (ns m)) (ns m)\"\n        proof-\n          have \"(newton_step (ns m)) \\<noteq>(ns m)\"\n          proof-\n            have A0: \"divide (f\\<bullet>(ns m)) (f'\\<bullet>(ns m)) \\<noteq>\\<zero>\"\n            proof-\n              have 0: \"(f\\<bullet>(ns m)) \\<noteq> \\<zero>\"\n                using assms by auto \n              have 1: \" (f'\\<bullet>(ns m)) \\<in> carrier Zp\"\n                by (simp add: UP_cring.to_fun_closed Zp_x_is_UP_cring f'_closed newton_seq_closed)                \n              have 2:  \"(f'\\<bullet>(ns m)) \\<noteq> \\<zero>\" \n                using newton_seq_fact6 not_nonzero_memI by blast                                              \n              show ?thesis using 0 1 2 \n                by (metis R.r_null divide_formula f_closed to_fun_closed newton_seq_closed newton_seq_fact4)                \n            qed\n            have A2: \"local.divide (f \\<bullet> ns m) (f' \\<bullet> ns m) \\<in> carrier Zp\"\n              using newton_seq_fact5 by blast   \n            have A3: \"ns m \\<in> carrier Zp\"\n              by (simp add: newton_seq_closed)\n            have A4: \"newton_step (ns m) \\<in> carrier Zp\"\n              by (metis newton_seq.simps(2) newton_seq_closed)\n            show ?thesis \n              apply(rule ccontr) \n              using A4 A3 A2 A0 newton_step_def[of \"(ns m)\"] \n              by (simp add: a_minus_def)\n          qed\n          then show ?thesis using C0 \n            by (metis newton_seq.simps(2) newton_seq_closed val_Zp_dist_res_eq2)\n        qed\n      qed\n      qed\n      then show ?case \n        using val_Zp_def val_Zp_dist_def \n        by (metis int_ops(1) newton_seq.simps(2) zero_eint_def)                \n    next\n      case (Suc n)\n      show \"\\<exists>k. \\<forall>m. k \\<le> int m \\<longrightarrow> int (Suc n) \\<le> val_Zp (ns (Suc m) \\<ominus> ns m)\"\n      proof-\n        obtain k0 where k0_def: \"k0 \\<ge>0 \\<and> (\\<forall>m. k0 \\<le> int m \\<longrightarrow> int n \\<le> val_Zp (ns (Suc m) \\<ominus> ns m))\"\n          using Suc.IH \n          by (metis int_nat_eq le0 nat_le_iff of_nat_0_eq_iff )\n        have I0: \"\\<And>l. val_Zp (ns (Suc l) \\<ominus> ns l) = val_Zp (f\\<bullet> (ns l)) - val_Zp (f'\\<bullet>(ns l))\"\n        proof-\n          fix l\n          have I00:\"(ns (Suc l) \\<ominus> ns l) = (\\<ominus> divide (f\\<bullet>(ns l)) (f'\\<bullet>(ns l)))\"\n          proof-\n            have \"local.divide (f \\<bullet> ns l) (f' \\<bullet> ns l) \\<in> carrier Zp\"\n              by (simp add: newton_seq_fact5) \n            then show ?thesis \n              using newton_seq.simps(2)[of l] newton_seq_closed R.ring_simprules \n              unfolding newton_step_def a_minus_def  \n              by (metis add_comm)                 \n          qed\n          have I01: \"val_Zp (ns (Suc l) \\<ominus> ns l) = val_Zp (divide (f\\<bullet>(ns l)) (f'\\<bullet>(ns l)))\"   \n          proof-\n            have I010: \"(divide (f\\<bullet>(ns l)) (f'\\<bullet>(ns l))) \\<in>carrier Zp\"\n             by (simp add: newton_seq_fact5)\n           have I011: \"(divide (f\\<bullet>(ns l)) (f'\\<bullet>(ns l))) \\<noteq> \\<zero>\"\n           proof-\n             have A: \"(f\\<bullet>(ns l)) \\<noteq>\\<zero>\"\n               by (simp add: assms) \n             have B: \" (f'\\<bullet>(ns l))  \\<in>carrier Zp\"\n               using nonzero_memE newton_seq_fact6 by auto                 \n             then have C: \" (f'\\<bullet>(ns l))  \\<in>nonzero  Zp\"\n               using  f'a_closed fa_closed fa_nonzero hensel_factor_id hensel_hypothesis_weakened\n                     newton_seq_fact1[of l]   not_nonzero_Zp val_Zp_def \n               by fastforce\n             then show ?thesis using I010 A \n               by (metis B R.r_null divide_formula f_closed to_fun_closed newton_seq_closed newton_seq_fact4 nonzero_memE(2))               \n           qed\n           then have \"val_Zp (divide (f\\<bullet>(ns l)) (f'\\<bullet>(ns l)))\n                    = val_Zp (\\<ominus> divide (f\\<bullet>(ns l)) (f'\\<bullet>(ns l)))\"\n             using I010 not_nonzero_Zp val_Zp_of_minus by blast\n           then show ?thesis using I00 by metis  \n          qed\n          have I02: \"val_Zp (f\\<bullet>(ns l)) \\<ge> val_Zp (f'\\<bullet>(ns l))\"\n            using assms  newton_seq_fact4\n            by blast  \n          have I03: \"(f\\<bullet>(ns l)) \\<in> nonzero Zp\"\n            by (meson UP_cring.to_fun_closed Zp_x_is_UP_cring assms f_closed newton_seq_closed not_nonzero_Zp)           \n          have I04: \"f'\\<bullet>(ns l) \\<in> nonzero Zp\"\n            by (simp add: newton_seq_fact6)            \n          have I05 :\" val_Zp (divide (f\\<bullet>(ns l)) (f'\\<bullet>(ns l))) = val_Zp (f\\<bullet> (ns l)) - val_Zp (f'\\<bullet>(ns l))\"\n            using I02 I03 I04 I01 assms newton_seq_fact9 by auto                \n          then show \" val_Zp (ns (Suc l) \\<ominus> ns l) = val_Zp (f\\<bullet> (ns l)) - val_Zp (f'\\<bullet>(ns l))\"\n            using I01  by simp            \n        qed\n        have \"\\<forall>m. int(Suc n) + k0 + 1 \\<le> int m \\<longrightarrow> int (Suc n) \\<le> val_Zp_dist (newton_step (ns m)) (ns m)\"\n        proof\n          fix m\n          show \"int (Suc n) + k0 + 1 \\<le> int m \\<longrightarrow> int (Suc n) \\<le> val_Zp_dist (newton_step (ns m)) (ns m)\"\n          proof\n          assume A: \"int (Suc n) + k0 + 1 \\<le> int m \"\n            show \" int (Suc n) \\<le> val_Zp_dist (newton_step (ns m)) (ns m)\"\n            proof-\n              have 0: \" val_Zp_dist (newton_step (ns m)) (ns m) =  val_Zp (f\\<bullet> (ns m)) - val_Zp (f'\\<bullet>(ns m))\"\n                using I0 val_Zp_dist_def by auto         \n              have 1: \"val_Zp (f\\<bullet> (ns m)) - val_Zp (f'\\<bullet>(ns m)) > int n\"\n              proof-\n              have \"val_Zp (f\\<bullet> (ns m)) \\<ge> 2*(val_Zp (f'\\<bullet>a)) + (2^m)*t\"\n                by (simp add: newton_seq_fact2)                \n              then have 10:\"val_Zp (f\\<bullet> (ns m)) - val_Zp (f'\\<bullet>(ns m)) \\<ge> 2*(val_Zp (f'\\<bullet>a)) + (2^m)*t -  val_Zp (f'\\<bullet>(ns m))\"\n                by (simp add: eint_minus_ineq)                \n              have \"2^m * t > m\"\n                apply(induction m)\n                 using one_eint_def zero_eint_def apply auto[1]                 \n              proof- fix m \n                assume IH : \"int m < 2 ^ m * t \" \n                then have \"((2 ^ (Suc m)) * t) = 2* ((2 ^ m) * t)\"\n                  by (metis mult.assoc power_Suc times_eint_simps(1))  \n                then show \"int (Suc m) < 2 ^ Suc m * t\"\n                  using IH t_neq_infty by force\n              qed\n              then have 100: \"2^m * t > int m\"\n                by blast\n              have \"int m \\<ge>2 + (int n + k0)\"\n                using A by simp\n              hence 1000: \"2^m * t > 2 + (int n + k0)\"\n                using 100 \n                by (meson eint_ord_simps(2) less_le_trans linorder_not_less)\n              have \"2 + (int n + k0) > 1 + int n\"\n                using k0_def by linarith\n              then have \"2^m * t > 1 + int n\"\n                using 1000  eint_ord_simps(2) k0_def less_le_trans linorder_not_less\n              proof -\n                have \"eint (2 + (int n + k0)) < t * eint (int (2 ^ m))\"\n                  by (metis \"1000\" mult.commute numeral_power_eq_of_nat_cancel_iff)\n                then have \"eint (int (Suc n)) < t * eint (int (2 ^ m))\"\n                  by (metis \\<open>1 + int n < 2 + (int n + k0)\\<close> eint_ord_simps(2) less_trans of_nat_Suc)\n                then show ?thesis\n                  by (simp add: mult.commute)\n              qed\n              hence \"2*val_Zp (f'\\<bullet>a) + eint (2 ^ m) * t \\<ge> 2*(val_Zp (f'\\<bullet>a)) + 1 + int n\"\n                by (smt eSuc_eint eint_add_left_cancel_le iadd_Suc iadd_Suc_right order_less_le)\n              then have 11: \"val_Zp (f\\<bullet> (ns m)) - val_Zp (f'\\<bullet>(ns m)) \n                                \\<ge> 2*(val_Zp (f'\\<bullet>a)) + 1 + int n -  val_Zp (f'\\<bullet>(ns m))\"\n                using \"10\" \n                by (smt \\<open>eint 2 * val_Zp (f'\\<bullet>a) + eint (2 ^ m) * t \\<le> val_Zp (to_fun f (ns m))\\<close> \n                    f'a_not_infinite eint_minus_ineq hensel_axioms newton_seq_fact1 order_trans)\n              have 12: \"val_Zp (f'\\<bullet>(ns m))  = val_Zp (f'\\<bullet>a) \"\n                using nonzero_memE  newton_seq_fact1 newton_seq_fact6 val_Zp_def val_Zp_def \n                by auto               \n              then have 13: \"val_Zp (f\\<bullet> (ns m)) - val_Zp (f'\\<bullet>(ns m)) \n                                \\<ge> 2*(val_Zp (f'\\<bullet>a)) + (1 + int n) -  val_Zp ((f'\\<bullet>a))\"\n                using 11 \n                by (smt eSuc_eint iadd_Suc iadd_Suc_right)\n              then have 14:\"val_Zp (f\\<bullet> (ns m)) - val_Zp (f'\\<bullet>(ns m)) \n                                \\<ge> 1 + int n +  val_Zp ((f'\\<bullet>a))\"\n                using eint_minus_comm[of \"2*(val_Zp (f'\\<bullet>a))\" \"1 + int n\" \"val_Zp ((f'\\<bullet>a))\"] \n                by (simp add: Groups.add_ac(2))\n              then show ?thesis \n                by (smt Suc_ile_eq add.right_neutral eint.distinct(2) f'a_nonneg_val ge_plus_pos_imp_gt order_less_le)                \n              qed\n              then show ?thesis \n               by (smt \"0\" Suc_ile_eq of_nat_Suc)              \n            qed\n          qed\n        qed\n        then show ?thesis \n          using val_Zp_def val_Zp_dist_def \n          by (metis newton_seq.simps(2))          \n       qed\n    qed\n  qed\nqed\n\nlemma eventually_zero:\n\"f \\<bullet> ns (k + m) = \\<zero> \\<Longrightarrow> f \\<bullet> ns (k + Suc m) = \\<zero>\"\nproof-\n  assume A: \"f \\<bullet> ns (k + m) = \\<zero>\"\n  have 0: \"ns (k + Suc m) = ns (k + m) \\<ominus> (divide (f \\<bullet> ns (k + m)) (f' \\<bullet> ns (k + m)))\"\n    by (simp add: newton_step_def)\n  have 1: \"(divide (f \\<bullet> ns (k + m)) (f' \\<bullet> ns (k + m))) = \\<zero>\"\n    by (simp add: A divide_def)\n  show \"f \\<bullet> ns (k + Suc m) = \\<zero>\"\n    using A 0 1 \n    by (simp add: a_minus_def newton_seq_closed)    \nqed\n\ntext\\<open>The Newton Sequence is Cauchy:\\<close>\n\nlemma newton_seq_is_Zp_cauchy:\n\"is_Zp_cauchy ns\"\nproof(cases \"\\<forall>k. f\\<bullet>(ns k) \\<noteq>\\<zero>\")\n  case True\n  then show ?thesis using newton_seq_is_Zp_cauchy_0 \n    by blast\nnext\n  case False\n  obtain k where k_def:\"f\\<bullet>(ns k) = \\<zero>\"\n    using False by blast\n  have 0: \"\\<And>m. (ns (m + k)) = (ns k)\"\n  proof-\n    fix m\n    show \"(ns (m + k)) = (ns k)\"\n    proof(induction m)\n      case 0\n      then show ?case \n        by simp      \n    next\n      case (Suc m)\n      show \"(ns (Suc m + k)) = (ns k)\" \n      proof-\n        have \"f \\<bullet> ns (m + k) = \\<zero>\"\n          by (simp add: Suc.IH k_def)\n        then have \"divide ( f \\<bullet> ns (m + k)) (f' \\<bullet> ns (m + k)) = \\<zero>\"\n          by (simp add: divide_def)\n        then show ?thesis using newton_step_def \n          by (simp add: Suc.IH a_minus_def newton_seq_closed)\n      qed\n    qed\n  qed\n  show \"is_Zp_cauchy ns\"\n    apply(rule is_Zp_cauchyI)\n    apply (simp add: closed_seqs_memI newton_seq_closed)                  \n  proof-\n    show \"\\<And>n.\\<And>n. \\<exists>N. \\<forall>n0 n1. N < n0 \\<and> N < n1 \\<longrightarrow> ns n0 n = ns n1 n\"\n    proof-\n      fix n\n      show \"\\<exists>N. \\<forall>n0 n1. N < n0 \\<and> N < n1 \\<longrightarrow> ns n0 n = ns n1 n\"\n      proof-\n        have \"\\<forall>n0 n1. k < n0 \\<and> k < n1 \\<longrightarrow> ns n0 n = ns n1 n\"\n          apply auto \n        proof-\n          fix n0 n1\n          assume A0: \"k < n0\"\n          assume A1: \"k < n1\"\n          obtain m0 where m0_def: \"n0 = k + m0\"\n            using A0 less_imp_add_positive by blast\n          obtain m1 where m1_def: \"n1 = k + m1\"\n            using A1 less_imp_add_positive by auto\n          show \"ns n0 n = ns n1 n\"\n            using 0 m0_def m1_def \n            by (metis add.commute)\n        qed\n        then show ?thesis by blast \n      qed\n    qed\n  qed\nqed\n\nsubsection\\<open>The Proof of Hensel's Lemma\\<close>\nlemma pre_hensel:\n\"val_Zp (a \\<ominus> (ns n)) >  val_Zp (f'\\<bullet>a)\"\n\"\\<exists>N. \\<forall>n. n> N \\<longrightarrow> (val_Zp (a \\<ominus> (ns n)) = val_Zp (divide (f\\<bullet>a) (f'\\<bullet>a)))\"\n\"val_Zp (f'\\<bullet>(ns n)) = val_Zp (f'\\<bullet>a)\"\nproof-\n  show \"val_Zp (a \\<ominus> (ns n)) >  val_Zp (f'\\<bullet>a)\"\n  proof(induction n)\n    case 0\n    then show ?case \n      by (simp add: val_Zp_def)                \n  next\n    case (Suc n)\n    show \"val_Zp (a \\<ominus> (ns (Suc n))) > val_Zp (f'\\<bullet>a)\"\n    proof-\n      have I0: \"val_Zp ((ns (Suc n)) \\<ominus> (ns n)) >  val_Zp (f'\\<bullet>a)\"\n      proof(cases \"(ns (Suc n)) = (ns n)\")\n        case True\n        then show ?thesis \n          by (simp add: newton_seq_closed val_Zp_def)              \n      next\n        case False         \n        have 00:\"(ns (Suc n)) \\<ominus> (ns n) = \\<ominus>divide (f\\<bullet>(ns n)) (f'\\<bullet>(ns n))\"\n          using  newton_seq_fact7 by blast                 \n        then have 0: \"val_Zp((ns (Suc n)) \\<ominus> (ns n)) = val_Zp (divide (f\\<bullet>(ns n)) (f'\\<bullet>(ns n)))\"\n          using newton_seq_fact5 val_Zp_of_minus by presburger                                                    \n        have 1: \"(f\\<bullet>(ns n)) \\<in> nonzero Zp\"\n          by (metis False R.minus_zero R.r_right_minus_eq 00 divide_def f_closed to_fun_closed \n              newton_seq_closed not_nonzero_Zp)         \n        have 2: \"f'\\<bullet>(ns n) \\<in> nonzero Zp\"\n          by (simp add: newton_seq_fact6)\n        have \"val_Zp (f\\<bullet>(ns n))  \\<ge> val_Zp (f'\\<bullet>(ns n))\"\n          using nonzero_memE  \\<open>f \\<bullet> ns n \\<in> nonzero Zp\\<close> newton_seq_fact4 by blast\n        then have 3:\"val_Zp((ns (Suc n)) \\<ominus> (ns n)) = val_Zp (f\\<bullet>(ns n)) - val_Zp (f'\\<bullet>(ns n))\"\n          using 0 1 2 newton_seq_fact9 nonzero_memE(2) by blast      \n        have 4: \"val_Zp (f \\<bullet> ns n) \\<ge> (2 * val_Zp (f'\\<bullet>a)) + 2 ^ n * t\"\n          using newton_seq_fact2[of n] by metis  \n        then have 5: \"val_Zp((ns (Suc n)) \\<ominus> (ns n)) \\<ge> ((2 * val_Zp (f'\\<bullet>a)) + 2 ^ n * t) - val_Zp (f'\\<bullet>(ns n))\"\n          using \"3\" eint_minus_ineq f'a_not_infinite newton_seq_fact1 by presburger\n        have 6: \"((ns (Suc n)) \\<ominus> (ns n)) \\<in> nonzero Zp\"\n          using False not_eq_diff_nonzero newton_seq_closed by blast\n        then have \"val_Zp((ns (Suc n)) \\<ominus> (ns n)) \\<ge> (2 * val_Zp (f'\\<bullet>a)) + 2 ^ n * t - val_Zp ((f'\\<bullet>a))\"\n          using \"5\" by auto         \n        then have 7: \"val_Zp((ns (Suc n)) \\<ominus> (ns n)) \\<ge> (val_Zp (f'\\<bullet>a)) + 2 ^ n * t\"\n          by (simp add: eint_minus_comm)         \n        then show  \"val_Zp((ns (Suc n)) \\<ominus> (ns n)) > (val_Zp (f'\\<bullet>a))\"\n          using f'a_not_infinite ge_plus_pos_imp_gt t_times_pow_pos by blast\n      qed      \n      have \"val_Zp ((ns (Suc n)) \\<ominus> (ns n)) = val_Zp ((ns n) \\<ominus> (ns (Suc n)))\"\n        using  newton_seq_closed[of \"n\"]  newton_seq_closed[of \"Suc n\"]\n                 val_Zp_def val_Zp_dist_def val_Zp_dist_sym val_Zp_def \n        by auto\n      then have I1: \"val_Zp ((ns n) \\<ominus> (ns (Suc n))) > val_Zp (f'\\<bullet>a)\"\n        using I0 \n        by presburger\n      have I2: \" (a \\<ominus> (ns n)) \\<oplus> ((ns n) \\<ominus> (ns (Suc n))) = (a \\<ominus> (ns (Suc n)))\"\n          by (metis R.plus_diff_simp add_comm local.a_closed newton_seq_closed)                    \n      then have \"val_Zp (a \\<ominus> (ns (Suc n))) \\<ge> min (val_Zp (a \\<ominus> ns n)) (val_Zp (ns n \\<ominus> ns (Suc n)))\"\n          by (metis R.minus_closed local.a_closed newton_seq_closed val_Zp_ultrametric)               \n      thus ?thesis \n        using I1 Suc.IH eint_min_ineq by blast\n    qed\n  qed\n  show \"val_Zp (f'\\<bullet>(ns n)) = val_Zp (f'\\<bullet>a)\"\n    using newton_seq_fact1 by blast\n  show \"\\<exists>N.\\<forall>n. n> N \\<longrightarrow> (val_Zp (a \\<ominus> (ns n)) = val_Zp (divide (f\\<bullet>a) (f'\\<bullet>a)))\"\n  proof-\n    have P: \"\\<And>m. m > 1 \\<Longrightarrow> (val_Zp (a \\<ominus> (ns m)) = val_Zp (divide (f\\<bullet>a) (f'\\<bullet>a)))\"\n    proof-\n      fix n::nat\n      assume AA: \"n >1\"\n      show \" (val_Zp (a \\<ominus> (ns n)) = val_Zp (divide (f\\<bullet>a) (f'\\<bullet>a)))\" \n      proof(cases \"(ns 1) = a\")\n        case True\n        have T0: \"\\<And>k. \\<forall>n. n \\<le> k \\<longrightarrow>  ns n = a\"\n        proof-\n          fix k\n          show \" \\<forall>n. n \\<le> k \\<longrightarrow>  ns n = a\"\n          proof(induction k)\n            case 0\n            then show ?case \n              by simp \n          next\n            case (Suc k)\n            show \"\\<forall>n\\<le>Suc k. ns n = a\" apply auto \n            proof-\n              fix n\n              assume A: \"n \\<le>Suc k\"\n              show \"ns n = a\"\n              proof(cases \"n < Suc k\")\n                case True\n                then show ?thesis using Suc.IH by auto \n              next\n                case False thus ?thesis \n                  using A Suc.IH True by auto\n              qed\n            qed\n          qed\n        qed\n        show \"val_Zp (a \\<ominus> ns n) = val_Zp (local.divide (f\\<bullet>a) (f'\\<bullet>a))\"\n          by (metis T0  Zp_def Zp_defs(3) f'a_closed f'a_nonzero fa_nonzero \n              hensel.fa_closed hensel_axioms hensel_hypothesis_weakened le_eq_less_or_eq \n              newton_seq_fact9 not_nonzero_Qp order_less_le val_of_divide)\n      next\n        case False  \n        have F0: \"(1::nat) \\<le> n\"\n          using AA by simp \n        have \"(f\\<bullet>a) \\<noteq> \\<zero>\"\n          by simp\n        have \"\\<And>k. val_Zp (a \\<ominus> ns (Suc k)) = val_Zp (local.divide (f\\<bullet>a) (f'\\<bullet>a))\"\n        proof-\n          fix k\n          show \" val_Zp (a \\<ominus> ns (Suc k)) = val_Zp (local.divide (f\\<bullet>a) (f'\\<bullet>a))\"\n          proof(induction k)\n            case 0             \n            have \"(a \\<ominus> ns (Suc 0)) = (local.divide (f\\<bullet>a) (f'\\<bullet>a))\" \n              by (metis R.minus_minus Zp_def hensel.newton_seq_fact7 hensel_axioms \n                  local.a_closed minus_a_inv newton_seq.simps(1) newton_seq.simps(2) newton_seq_fact5 newton_step_closed)\n            then show ?case by simp\n          next\n            case (Suc k)\n            have I0: \"ns (Suc (Suc k)) = ns (Suc k) \\<ominus> (divide (f\\<bullet>(ns (Suc k))) (f'\\<bullet>(ns (Suc k))))\"\n              by (simp add: newton_step_def)\n            have I1: \"val_Zp (f\\<bullet>(ns (Suc k))) \\<ge> val_Zp(f'\\<bullet>(ns (Suc k)))\"\n              using newton_seq_fact3 by blast\n            have I2: \"(divide (f\\<bullet>(ns (Suc k))) (f'\\<bullet>(ns (Suc k)))) \\<in> carrier Zp\"\n              using newton_seq_fact5 by blast\n            have I3: \"ns (Suc (Suc k)) \\<ominus> ns (Suc k) = \\<ominus>(divide (f\\<bullet>(ns (Suc k))) (f'\\<bullet>(ns (Suc k))))\"\n              using I0 I2 newton_seq_fact7 by blast                                     \n            then have \"val_Zp (ns (Suc (Suc k)) \\<ominus> ns (Suc k)) = val_Zp (divide (f\\<bullet>(ns (Suc k))) (f'\\<bullet>(ns (Suc k))))\"\n              using I2 val_Zp_of_minus \n              by presburger   \n            then have \"val_Zp (ns (Suc (Suc k)) \\<ominus> ns (Suc k)) = val_Zp (f\\<bullet>(ns (Suc k))) - val_Zp (f'\\<bullet>(ns (Suc k)))\"\n              by (metis I1 R.zero_closed Zp_def newton_seq_fact6 newton_seq_fact9 padic_integers.val_of_divide padic_integers_axioms)    \n            then have I4: \"val_Zp (ns (Suc (Suc k)) \\<ominus> ns (Suc k)) = val_Zp (f\\<bullet>(ns (Suc k))) - val_Zp ((f'\\<bullet>a))\"\n              using newton_seq_fact1 by presburger                  \n            have F3: \"val_Zp (a \\<ominus> ns (Suc k)) = val_Zp (local.divide (f\\<bullet>a) (f'\\<bullet>a))\"\n              using Suc.IH by blast\n            have F4: \"a \\<ominus>  ns (Suc (Suc k)) = (a \\<ominus> ( ns (Suc k))) \\<oplus> (ns  (Suc k)) \\<ominus> ns (Suc (Suc k))\"\n              by (metis R.ring_simprules(17) a_minus_def add_comm local.a_closed newton_seq_closed)                                          \n            have F5: \"val_Zp ((ns  (Suc k)) \\<ominus> ns (Suc (Suc k))) > val_Zp (a \\<ominus> ( ns (Suc k)))\"\n            proof-\n              have F50:  \"val_Zp ((ns  (Suc k)) \\<ominus> ns (Suc (Suc k))) = val_Zp (f\\<bullet>(ns (Suc k))) - val_Zp ((f'\\<bullet>a))\"\n                by (metis I4 R.minus_closed minus_a_inv newton_seq_closed val_Zp_of_minus)\n                                                          \n              have F51: \"val_Zp (f\\<bullet>(ns (Suc k))) > val_Zp ((f\\<bullet>a))\"                 \n              proof-\n                have F510: \"val_Zp (f\\<bullet>(ns (Suc k))) \\<ge>  2*val_Zp (f'\\<bullet>a) + 2^(Suc k)*t \"\n                  using newton_seq_fact2 by blast                    \n                hence F511: \"val_Zp (f\\<bullet>(ns (Suc k))) \\<ge>  2*val_Zp (f'\\<bullet>a) + 2*t \"\n                  using eint_plus_times[of t \"2*val_Zp (f'\\<bullet>a)\" \"2^(Suc k)\" \"val_Zp (f\\<bullet>(ns (Suc k)))\" 2] t_pos\n                  by (simp add: order_less_le)\n                have F512: \"2*val_Zp (f'\\<bullet>a) + 2*t  = 2 *val_Zp (f\\<bullet>a) - 2* val_Zp (f'\\<bullet>a)\"               \n                  unfolding hensel_factor_def\n                  using eint_minus_distr[of \"val_Zp (f\\<bullet>a)\" \"2 * val_Zp (f'\\<bullet>a)\" 2] \n                        eint_minus_comm[of _ _ \"eint 2 * (eint 2 * val_Zp (f'\\<bullet>a))\"]   \n                  by (smt eint_2_minus_1_mult eint_add_cancel_fact eint_minus_comm f'a_not_infinite hensel_hypothesis nat_mult_not_infty order_less_le)\n                hence \"2*val_Zp (f'\\<bullet>a) + 2*t  > val_Zp (f\\<bullet>a)\"\n                  using hensel_hypothesis \n                  by (smt add_diff_cancel_eint eint_add_cancel_fact eint_add_left_cancel_le \n                      eint_pos_int_times_gt f'a_not_infinite hensel_factor_def nat_mult_not_infty order_less_le t_neq_infty t_pos)\n                thus ?thesis using F512 \n                  using F511 less_le_trans by blast\n              qed\n              thus ?thesis \n                by (metis F3 F50 Zp_def divide_closed eint_add_cancel_fact eint_minus_ineq \n                    f'a_closed f'a_nonzero f'a_not_infinite fa_closed fa_nonzero hensel.newton_seq_fact7 \n                    hensel_axioms newton_seq.simps(1) newton_seq_fact9 order_less_le val_Zp_of_minus)\n            qed\n            have \"a \\<ominus> ns (Suc k) \\<oplus> (ns (Suc k) \\<ominus> ns (Suc (Suc k))) = a  \\<ominus> ns (Suc (Suc k))\"\n              by (metis F4 a_minus_def add_assoc)\n            then show F6: \"val_Zp (a \\<ominus> ns (Suc (Suc k))) = val_Zp (local.divide (f\\<bullet>a) (f'\\<bullet>a))\"\n              using F5 F4 F3  \n              by (metis R.minus_closed local.a_closed newton_seq_closed order_less_le val_Zp_not_equal_ord_plus_minus val_Zp_ultrametric_eq'')                 \n          qed\n        qed\n        thus ?thesis \n          by (metis AA less_imp_add_positive plus_1_eq_Suc)        \n      qed\n    qed\n    thus ?thesis \n      by blast\n  qed\nqed\n\nlemma hensel_seq_comp_f:\n \"res_lim ((to_fun f) \\<circ> ns) = \\<zero>\"\nproof-\n  have A: \"is_Zp_cauchy ((to_fun f) \\<circ> ns)\"\n    using f_closed is_Zp_continuous_def newton_seq_is_Zp_cauchy polynomial_is_Zp_continuous \n    by blast\n  have \"Zp_converges_to ((to_fun f) \\<circ> ns) \\<zero>\"\n    apply(rule Zp_converges_toI)\n    using A is_Zp_cauchy_def apply blast\n     apply simp     \n  proof-\n    fix n\n    show \" \\<exists>N. \\<forall>k>N. (((to_fun f) \\<circ> ns) k) n = \\<zero> n\"\n    proof-\n      have 0: \"\\<And>k. (k::nat)>3 \\<longrightarrow>  val_Zp (f\\<bullet>(ns k)) > k\"\n      proof\n        fix k::nat\n        assume A: \"k >3\"\n        show \"val_Zp (f\\<bullet>(ns k)) > k \"\n        proof-\n          have 0: \" val_Zp (f\\<bullet>(ns k)) \\<ge>  2*(val_Zp (f'\\<bullet>a)) + (2^k)*t\"\n            using newton_seq_fact2 by blast   \n          have 1: \"2*(val_Zp (f'\\<bullet>a)) + (2^k)*t > k \"\n          proof-\n            have \"(2^k)*t \\<ge> (2^k) \"\n              apply(cases \"t = \\<infinity>\")\n               apply simp\n            using t_pos eint_mult_mono' \n            proof -\n              obtain ii :: \"eint \\<Rightarrow> int\" where\n                f1: \"\\<forall>e. (\\<infinity> \\<noteq> e \\<or> (\\<forall>i. eint i \\<noteq> e)) \\<and> (eint (ii e) = e \\<or> \\<infinity> = e)\"\n                by (metis not_infinity_eq)\n              then have \"0 < ii t\"\n                by (metis (no_types) eint_ord_simps(2) t_neq_infty t_pos zero_eint_def)\n              then show ?thesis\n                using f1 by (metis eint_pos_int_times_ge eint_mult_mono linorder_not_less \n                            mult.commute order_less_le t_neq_infty t_pos t_times_pow_pos)\n            qed\n            hence \" 2*(val_Zp (f'\\<bullet>a)) + (2^k)*t \\<ge> (2^k) \"\n              by (smt Groups.add_ac(2) add.right_neutral eint_2_minus_1_mult eint_pos_times_is_pos\n                  eint_pow_int_is_pos f'a_nonneg_val ge_plus_pos_imp_gt idiff_0_right linorder_not_less \n                  nat_mult_not_infty order_less_le t_neq_infty) \n            then have  \" 2*(val_Zp (f'\\<bullet>a)) + (2^k)*t > k\"\n              using A  of_nat_1 of_nat_add of_nat_less_two_power \n              by (smt eint_ord_simps(1) linorder_not_less order_trans)              \n            then show ?thesis \n              by metis\n          qed\n          thus ?thesis \n            using 0 less_le_trans by blast          \n        qed\n      qed\n      have 1: \"\\<And>k. (k::nat)>3 \\<longrightarrow>  (f\\<bullet>(ns k)) k = 0\"\n      proof\n        fix k::nat\n        assume B: \"3<k\"\n        show \" (f\\<bullet>(ns k)) k = 0\"\n        proof-\n          have B0: \" val_Zp (f\\<bullet>(ns k)) > k\"\n            using 0 B \n            by blast\n          then show ?thesis \n            by (simp add: f_of_newton_seq_closed zero_below_val_Zp)\n        qed\n      qed\n      have \"\\<forall>k>(max 3 n). (((to_fun f) \\<circ> ns) k) n = \\<zero> n\"\n        apply auto\n      proof-\n        fix k::nat\n        assume A: \"3< k\"\n        assume A': \"n < k\"\n        have A0: \"(f\\<bullet>(ns k)) k = 0\"\n          using 1[of k] A by auto \n        then have \"(f\\<bullet>(ns k)) n = 0\"\n          using A A'\n          using above_ord_nonzero[of \"(f\\<bullet>(ns k))\"]\n          by (smt UP_cring.to_fun_closed Zp_x_is_UP_cring f_closed le_eq_less_or_eq \n              newton_seq_closed of_nat_mono residue_of_zero(2) zero_below_ord)\n        then show A1:  \"to_fun f (ns k) n = \\<zero> n\"\n          by (simp add: residue_of_zero(2))          \n      qed\n      then show ?thesis by blast \n    qed\n  qed\n  then show ?thesis \n    by (metis Zp_converges_to_def unique_limit') \nqed\n\nlemma full_hensels_lemma:\n  obtains \\<alpha> where\n       \"f\\<bullet>\\<alpha> = \\<zero>\" and \"\\<alpha> \\<in> carrier Zp\"\n       \"val_Zp (a \\<ominus> \\<alpha>) > val_Zp (f'\\<bullet>a)\"\n       \"(val_Zp (a \\<ominus> \\<alpha>) = val_Zp (divide (f\\<bullet>a) (f'\\<bullet>a)))\"\n       \"val_Zp (f'\\<bullet>\\<alpha>) = val_Zp (f'\\<bullet>a)\"\nproof(cases \"\\<exists>k. f\\<bullet>(ns k) =\\<zero>\")\n  case True\n  obtain k where k_def: \"f\\<bullet>(ns k) =\\<zero>\"\n    using True by blast\n  obtain N where N_def: \"\\<forall>n. n> N \\<longrightarrow> (val_Zp (a \\<ominus> (ns n)) = val_Zp (divide (f\\<bullet>a) (f'\\<bullet>a)))\"\n    using pre_hensel(2) by blast\n  have Z: \"\\<And>n. n \\<ge>k \\<Longrightarrow> f\\<bullet>(ns n) =\\<zero>\"\n  proof-\n    fix n\n    assume A: \"n \\<ge>k\"\n    obtain l where l_def:\"n = k + l\"\n      using A le_Suc_ex \n      by blast\n    have \"\\<And>m. f\\<bullet>(ns (k+m)) =\\<zero>\"\n    proof-\n      fix m\n      show \"f\\<bullet>(ns (k+m)) =\\<zero>\"\n        apply(induction m)\n         apply (simp add: k_def)\n        using  eventually_zero \n        by simp\n    qed\n    then show \"f\\<bullet>(ns n) =\\<zero>\"\n      by (simp add: l_def)\n  qed\n  obtain M where M_def: \"M = N + k\"\n    by simp \n  then have M_root: \"f\\<bullet>(ns M) =\\<zero>\"\n    by (simp add: Z)\n  obtain \\<alpha> where alpha_def: \"\\<alpha>= ns M\"\n    by simp \n  have T0: \"f\\<bullet>\\<alpha> = \\<zero>\"\n    using alpha_def M_root \n    by auto\n  have T1:    \"val_Zp (a \\<ominus> \\<alpha>) > val_Zp (f'\\<bullet>a)\"\n    using alpha_def pre_hensel(1) by blast\n  have T2: \"(val_Zp (a \\<ominus> \\<alpha>) = val_Zp (divide (f\\<bullet>a) (f'\\<bullet>a)))\"\n    by (metis M_def N_def alpha_def fa_nonzero k_def \n        less_add_same_cancel1 newton_seq.elims zero_less_Suc)\n  have T3:  \"val_Zp (f'\\<bullet>\\<alpha>) = val_Zp (f'\\<bullet>a)\"\n    using alpha_def newton_seq_fact1 by blast\n  show ?thesis using T0 T1 T2 T3 \n    using that alpha_def newton_seq_closed \n    by blast   \nnext \n  case False\n  then have Nz: \"\\<And>k. f\\<bullet>(ns k) \\<noteq>\\<zero>\"\n    by blast\n  have ns_cauchy: \"is_Zp_cauchy ns\"\n    by (simp add: newton_seq_is_Zp_cauchy)\n  have fns_cauchy: \"is_Zp_cauchy ((to_fun f) \\<circ> ns)\"\n    using f_closed is_Zp_continuous_def ns_cauchy polynomial_is_Zp_continuous by blast\n  have F0: \"res_lim ((to_fun f) \\<circ> ns) = \\<zero>\"\n  proof-\n    show ?thesis \n      using hensel_seq_comp_f by auto \n  qed\n  obtain \\<alpha> where alpha_def: \"\\<alpha> = res_lim ns\"\n    by simp\n  have F1: \"(f\\<bullet>\\<alpha>)= \\<zero>\"\n    using F0 alpha_def alt_seq_limit\n      ns_cauchy polynomial_is_Zp_continuous res_lim_pushforward \n      res_lim_pushforward' by auto\n  have F2: \"val_Zp (a \\<ominus> \\<alpha>) > val_Zp (f'\\<bullet>a) \\<and>  val_Zp (a \\<ominus> \\<alpha>) = val_Zp (local.divide (f\\<bullet>a) (f'\\<bullet>a))\"\n  proof-\n    have 0: \"Zp_converges_to ns \\<alpha>\"\n      by (simp add: alpha_def is_Zp_cauchy_imp_has_limit ns_cauchy)\n    have \"val_Zp (a \\<ominus> \\<alpha>) < \\<infinity>\"\n      using \"0\" F1 R.r_right_minus_eq Zp_converges_to_def Zp_def hensel.fa_nonzero hensel_axioms local.a_closed val_Zp_def \n      by auto\n    hence \"1 + max (eint 2 + val_Zp (f'\\<bullet>a)) (val_Zp (\\<alpha> \\<ominus> a)) < \\<infinity>\"\n      by (metis \"0\" R.minus_closed Zp_converges_to_def eint.distinct(2) eint_ord_simps(4) \n          f'a_not_infinite infinity_ne_i1 local.a_closed max_def minus_a_inv \n          sum_infinity_imp_summand_infinity val_Zp_of_minus)\n    then obtain l where l_def: \"eint l = 1 + max (eint 2 + val_Zp (f'\\<bullet>a)) (val_Zp (\\<alpha> \\<ominus> a))\"\n      by auto\n    then obtain N where N_def: \"(\\<forall>m>N. 1 + max (2 + val_Zp (f'\\<bullet>a)) (val_Zp (\\<alpha> \\<ominus> a)) < val_Zp_dist (ns m) \\<alpha>)\"\n      using 0 l_def Zp_converges_to_def[of ns \\<alpha>] unfolding val_Zp_dist_def \n      by metis        \n    obtain N' where N'_def: \"\\<forall>n>N'. val_Zp (a \\<ominus> ns n) = val_Zp (local.divide (f\\<bullet>a) (f'\\<bullet>a))\"\n      using pre_hensel(2) by blast \n    obtain K where K_def: \"K = Suc (max N N')\"\n      by simp \n    then have F21: \"(1+ (max (2 + val_Zp (f'\\<bullet>a)) (val_Zp (\\<alpha> \\<ominus> a)))) < val_Zp_dist (ns K) \\<alpha>\"\n      by (metis N_def lessI linorder_not_less max_def order_trans)         \n    have F22: \"a \\<noteq> ns K\"\n      by (smt False K_def N'_def Zp_def cring_def eint.distinct(2) hensel_factor_id lessI \n          less_le_trans linorder_not_less max_def mult_comm mult_zero_l newton_seq_closed \n          order_less_le padic_int_is_cring padic_integers.prime padic_integers_axioms ring.r_right_minus_eq \n          val_Zp_def)\n    show ?thesis\n    proof(cases \"ns K = \\<alpha>\")\n      case True\n      then show ?thesis \n        using pre_hensel F1 False by blast\n    next\n      case False\n      assume \"ns K \\<noteq> \\<alpha>\"\n      show ?thesis\n      proof-\n        have P0: \" (a \\<ominus> \\<alpha>) \\<in> nonzero Zp\"\n          by (metis (mono_tags, hide_lams) F1 not_eq_diff_nonzero \n              \\<open>Zp_converges_to ns \\<alpha>\\<close> a_closed Zp_converges_to_def fa_nonzero)\n        have P1: \"(\\<alpha> \\<ominus> (ns K)) \\<in> nonzero Zp\"\n          using False not_eq_diff_nonzero \\<open>Zp_converges_to ns \\<alpha>\\<close> \n            Zp_converges_to_def newton_seq_closed\n          by (metis (mono_tags, hide_lams))\n        have P2: \"a \\<ominus> (ns K) \\<in> nonzero Zp\"\n          using F22 not_eq_diff_nonzero \n                a_closed newton_seq_closed \n          by blast\n        have P3: \"(a \\<ominus> \\<alpha>) = a \\<ominus> (ns K) \\<oplus> ((ns K) \\<ominus> \\<alpha>)\"\n          by (metis R.plus_diff_simp \\<open>Zp_converges_to ns \\<alpha>\\<close> add_comm Zp_converges_to_def local.a_closed newton_seq_closed)                           \n        have P4: \"val_Zp (a \\<ominus> \\<alpha>) \\<ge> min (val_Zp (a \\<ominus> (ns K))) (val_Zp ((ns K) \\<ominus> \\<alpha>))\"\n          using \"0\" P3 Zp_converges_to_def newton_seq_closed val_Zp_ultrametric \n          by auto          \n        have P5: \"val_Zp (a \\<ominus> (ns K)) >  val_Zp (f'\\<bullet>a)\"\n          using pre_hensel(1)[of \"K\"] \n          by metis                \n        have \"1 + max (eint 2 + val_Zp (f'\\<bullet>a)) (val_Zp (\\<alpha> \\<ominus> a)) > val_Zp (f'\\<bullet>a)\"\n        proof-\n          have \"1 + max (eint 2 + val_Zp (f'\\<bullet>a)) (val_Zp (\\<alpha> \\<ominus> a)) > (eint 2 + val_Zp (f'\\<bullet>a))\"\n          proof -\n            obtain ii :: int where\n              f1: \"eint ii = 1 + max (eint 2 + val_Zp (f'\\<bullet>a)) (val_Zp (\\<alpha> \\<ominus> a))\"\n              by (meson l_def)\n            then have \"1 + (eint 2 + val_Zp (f'\\<bullet>a)) \\<le> eint ii\"\n              by simp\n            then show ?thesis\n              using f1 by (metis Groups.add_ac(2) iless_Suc_eq linorder_not_less)\n          qed\n          thus ?thesis \n            by (smt Groups.add_ac(2) eint_pow_int_is_pos f'a_not_infinite ge_plus_pos_imp_gt order_less_le)\n        qed\n        hence P6: \"val_Zp ((ns K) \\<ominus> \\<alpha>) >  val_Zp (f'\\<bullet>a)\"\n          using F21 unfolding val_Zp_dist_def \n          by auto     \n        have P7: \"val_Zp (a \\<ominus> \\<alpha>) >  val_Zp (f'\\<bullet>a)\"\n          using P4 P5 P6 eint_min_ineq by blast\n        have P8:  \"val_Zp (a \\<ominus> \\<alpha>) = val_Zp (local.divide (f\\<bullet>a) (f'\\<bullet>a))\"\n        proof-\n          have \" 1 + max (2 + val_Zp (f'\\<bullet>a)) (val_Zp_dist \\<alpha> a) \\<le> val_Zp_dist (ns K) \\<alpha>\"\n            using False F21 \n            by (simp add: val_Zp_dist_def)           \n          then have \"val_Zp(\\<alpha> \\<ominus> (ns K)) >   max (2 + val_Zp (f'\\<bullet>a)) (val_Zp_dist \\<alpha> a)\"\n            by (metis \"0\" Groups.add_ac(2) P1 Zp_converges_to_def eSuc_mono iless_Suc_eq l_def \n                minus_a_inv newton_seq_closed nonzero_closed val_Zp_dist_def val_Zp_of_minus)                                          \n          then have \"val_Zp(\\<alpha> \\<ominus> (ns K)) > val_Zp (a \\<ominus> \\<alpha>) \"\n            using \\<open>Zp_converges_to ns \\<alpha>\\<close> Zp_converges_to_def val_Zp_dist_def val_Zp_dist_sym \n            by auto\n          then have P80: \"val_Zp (a \\<ominus> \\<alpha>) = val_Zp (a \\<ominus> (ns K))\"\n            using P0 P1 Zp_def val_Zp_ultrametric_eq[of \"\\<alpha> \\<ominus> ns K\" \"a \\<ominus> \\<alpha>\"] 0 R.plus_diff_simp \n              Zp_converges_to_def local.a_closed newton_seq_closed nonzero_closed by auto\n          have P81: \"val_Zp (a \\<ominus> ns K) = val_Zp (local.divide (f\\<bullet>a) (f'\\<bullet>a))\"\n            using K_def N'_def \n            by (metis (no_types, lifting) lessI linorder_not_less max_def order_less_le order_trans)\n          then show ?thesis       \n            by (simp add: P80)            \n        qed\n        thus ?thesis \n          using P7 by blast        \n      qed          \n    qed\n  qed\n  have F3: \"val_Zp (f' \\<bullet> \\<alpha>) = val_Zp (f'\\<bullet>a)\"\n  proof-\n    have F31: \" (f' \\<bullet> \\<alpha>) = res_lim ((to_fun f') \\<circ> ns)\"\n      using alpha_def alt_seq_limit ns_cauchy polynomial_is_Zp_continuous res_lim_pushforward\n          res_lim_pushforward' f'_closed \n      by auto\n    obtain N where N_def: \"val_Zp (f'\\<bullet>\\<alpha> \\<ominus> f'\\<bullet>(ns N)) > val_Zp ((f'\\<bullet>a))\"\n      by (smt F2 False R.minus_closed Suc_ile_eq Zp_def alpha_def f'_closed f'a_nonzero \n          local.a_closed minus_a_inv newton_seq.simps(1) newton_seq_is_Zp_cauchy_0 order_trans\n          padic_integers.poly_diff_val padic_integers_axioms res_lim_in_Zp val_Zp_def val_Zp_of_minus)      \n    show ?thesis\n      by (metis False N_def alpha_def equal_val_Zp f'_closed newton_seq_closed newton_seq_is_Zp_cauchy_0 newton_seq_fact1 res_lim_in_Zp to_fun_closed)\n  qed\n  show ?thesis \n    using F1 F2 F3 that alpha_def ns_cauchy res_lim_in_Zp \n    by blast\nqed\n\n\nend\n\n(**************************************************************************************************)\n(**************************************************************************************************)\nsection\\<open>Removing Hensel's Lemma from the Hensel Locale\\<close>\n(**************************************************************************************************)\n(**************************************************************************************************)\n\ncontext padic_integers\nbegin\n\n\nlemma hensels_lemma:\n  assumes \"f \\<in> carrier Zp_x\"\n  assumes \"a \\<in> carrier Zp\"\n  assumes \"(pderiv f)\\<bullet>a \\<noteq> \\<zero>\"\n  assumes \"f\\<bullet>a \\<noteq>\\<zero>\"\n  assumes \"val_Zp (f\\<bullet>a) > 2* val_Zp ((pderiv f)\\<bullet>a)\"\n  obtains \\<alpha> where\n       \"f\\<bullet>\\<alpha> = \\<zero>\" and \"\\<alpha> \\<in> carrier Zp\" \n       \"val_Zp (a \\<ominus> \\<alpha>) > val_Zp ((pderiv f)\\<bullet>a)\"\n       \"val_Zp (a \\<ominus> \\<alpha>) = val_Zp (divide (f\\<bullet>a) ((pderiv f)\\<bullet>a))\"\n       \"val_Zp ((pderiv f)\\<bullet>\\<alpha>) = val_Zp ((pderiv f)\\<bullet>a)\"\nproof-\n  have \"hensel p f a\"\n    using assms \n    by (simp add: Zp_def hensel.intro hensel_axioms.intro padic_integers_axioms)\n  then show ?thesis \n    using hensel.full_hensels_lemma  Zp_def that    \n    by blast     \nqed\n\ntext\\<open>Uniqueness of the root found in Hensel's lemma \\<close>\n\nlemma hensels_lemma_unique_root:\n  assumes \"f \\<in> carrier Zp_x\"\n  assumes \"a \\<in> carrier Zp\"\n  assumes \"(pderiv f)\\<bullet>a \\<noteq> \\<zero>\"\n  assumes \"f\\<bullet>a \\<noteq>\\<zero>\"\n  assumes \"(val_Zp (f\\<bullet>a) > 2* val_Zp ((pderiv f)\\<bullet>a))\"\n  assumes \"f\\<bullet>\\<alpha> = \\<zero>\" \n  assumes \"\\<alpha> \\<in> carrier Zp\" \n  assumes \"val_Zp (a \\<ominus> \\<alpha>) > val_Zp ((pderiv f)\\<bullet>a)\"\n  assumes \"f\\<bullet>\\<beta> = \\<zero>\" \n  assumes \"\\<beta> \\<in> carrier Zp\" \n  assumes \"val_Zp (a \\<ominus> \\<beta>) > val_Zp ((pderiv f)\\<bullet>a)\"\n  assumes \"val_Zp ((pderiv f)\\<bullet>\\<alpha>) = val_Zp ((pderiv f)\\<bullet>a)\"\n  shows \"\\<alpha> = \\<beta>\"\nproof-\n  have \"\\<alpha> \\<noteq> a\"\n    using assms(4) assms(6) by auto\n  have \"\\<beta> \\<noteq> a\"\n    using assms(4) assms(9) by auto\n  have 0: \"val_Zp (\\<beta> \\<ominus> \\<alpha>) >  val_Zp ((pderiv f)\\<bullet>a)\"\n  proof-\n    have \"\\<beta> \\<ominus> \\<alpha> = \\<ominus> ((a \\<ominus> \\<beta>) \\<ominus> (a \\<ominus> \\<alpha>))\"\n      by (metis R.minus_eq R.plus_diff_simp assms(10) assms(2) assms(7) minus_a_inv)   \n    hence \"val_Zp (\\<beta> \\<ominus> \\<alpha>) = val_Zp ((a \\<ominus> \\<beta>) \\<ominus> (a \\<ominus> \\<alpha>))\"\n      using R.minus_closed assms(10) assms(2) assms(7) val_Zp_of_minus by presburger\n    thus ?thesis using val_Zp_ultrametric_diff[of \"a \\<ominus> \\<beta>\" \"a \\<ominus> \\<alpha>\"]\n      by (smt R.minus_closed assms(10) assms(11) assms(2) assms(7) assms(8) min.absorb2 min_less_iff_conj)      \n  qed\n  obtain h where h_def: \"h = \\<beta> \\<ominus> \\<alpha>\"\n    by blast \n  then have h_fact: \"h \\<in> carrier Zp \\<and> \\<beta> = \\<alpha> \\<oplus> h\"\n    by (metis R.l_neg R.minus_closed R.minus_eq R.r_zero add_assoc add_comm assms(10) assms(7))    \n  then have 1: \"f\\<bullet>(\\<alpha> \\<oplus> h) = \\<zero>\"\n    using assms \n    by blast\n  obtain c where c_def: \"c \\<in> carrier Zp \\<and> f\\<bullet>(\\<alpha> \\<oplus> h) = (f \\<bullet> \\<alpha>) \\<oplus> (deriv f \\<alpha>)\\<otimes>h \\<oplus> c \\<otimes>(h[^](2::nat))\"\n    using taylor_deg_1_eval'[of  f \\<alpha> h _ \"f \\<bullet> \\<alpha>\" \"deriv f \\<alpha>\" ]\n    by (meson taylor_closed assms(1) assms(7) to_fun_closed h_fact shift_closed)    \n  then have  \"(f \\<bullet> \\<alpha>) \\<oplus> (deriv f \\<alpha>)\\<otimes>h \\<oplus> c \\<otimes>(h[^](2::nat)) = \\<zero>\"\n    by (simp add: \"1\")\n  then have 2:  \"(deriv f \\<alpha>)\\<otimes>h \\<oplus> c \\<otimes>(h[^](2::nat)) = \\<zero>\"\n   by (simp add: assms(1) assms(6) assms(7) deriv_closed h_fact)   \n  have 3: \"((deriv f \\<alpha>) \\<oplus> c \\<otimes>h)\\<otimes>h = \\<zero>\"\n  proof-\n    have \"((deriv f \\<alpha>) \\<oplus> c \\<otimes>h)\\<otimes>h = ((deriv f \\<alpha>)\\<otimes>h \\<oplus> (c \\<otimes>h)\\<otimes>h)\"\n      by (simp add: R.r_distr UP_cring.deriv_closed Zp_x_is_UP_cring assms(1) assms(7) c_def h_fact mult_comm)      \n    then have \"((deriv f \\<alpha>) \\<oplus> c \\<otimes>h)\\<otimes>h = (deriv f \\<alpha>)\\<otimes>h \\<oplus> (c \\<otimes>(h\\<otimes>h))\"\n      by (simp add: mult_assoc)      \n    then have \"((deriv f \\<alpha>) \\<oplus> c \\<otimes>h)\\<otimes>h = (deriv f \\<alpha>)\\<otimes>h \\<oplus> (c \\<otimes>(h[^](2::nat)))\"\n      using nat_pow_def[of Zp h \"2\"]\n      by (simp add: h_fact)\n    then show ?thesis\n      using 2 \n      by simp\n  qed\n  have \"h = \\<zero>\"\n  proof(rule ccontr)\n    assume \"h \\<noteq> \\<zero>\"\n    then have \"(deriv f \\<alpha>) \\<oplus> c \\<otimes>h = \\<zero>\"\n      using 2 3 \n      by (meson R.m_closed assms(1) assms(7) c_def deriv_closed h_fact local.integral sum_closed)      \n    then have \"(deriv f \\<alpha>) = \\<ominus> c \\<otimes>h\"\n      by (simp add: R.l_minus R.sum_zero_eq_neg UP_cring.deriv_closed Zp_x_is_UP_cring assms(1) assms(7) c_def h_fact)      \n    then have \"val_Zp (deriv f \\<alpha>) = val_Zp (c \\<otimes> h)\"\n      by (meson R.m_closed \\<open>deriv f \\<alpha> \\<oplus> c \\<otimes> h = \\<zero>\\<close> assms(1) assms(7) c_def deriv_closed h_fact val_Zp_not_equal_imp_notequal(3))      \n    then have P: \"val_Zp (deriv f \\<alpha>) = val_Zp h + val_Zp c\"\n      using val_Zp_mult c_def h_fact by force\n    hence \"val_Zp (deriv f \\<alpha>) \\<ge> val_Zp h \"\n      using val_pos[of c] \n      by (simp add: c_def)\n    then have \"val_Zp (deriv f \\<alpha>) \\<ge> val_Zp (\\<beta> \\<ominus> \\<alpha>) \"\n      using h_def by blast\n    then have \"val_Zp (deriv f \\<alpha>) > val_Zp ((pderiv f)\\<bullet>a)\"\n      using \"0\" by auto     \n    then show False using pderiv_eval_deriv[of f \\<alpha>]  \n      using assms(1) assms(12) assms(7) by auto\n  qed\n  then show \"\\<alpha> = \\<beta>\"\n    using assms(10) assms(7) h_def \n    by auto\nqed\n\nlemma hensels_lemma':\n  assumes \"f \\<in> carrier Zp_x\"\n  assumes \"a \\<in> carrier Zp\"\n  assumes \"val_Zp (f\\<bullet>a) > 2*val_Zp ((pderiv f)\\<bullet>a)\"\n  shows \"\\<exists>!\\<alpha> \\<in> carrier Zp. f\\<bullet>\\<alpha> = \\<zero> \\<and> val_Zp (a \\<ominus> \\<alpha>) > val_Zp ((pderiv f)\\<bullet>a)\"\nproof(cases \"f\\<bullet>a = \\<zero>\")\n  case True\n  have T0: \"pderiv f \\<bullet> a \\<noteq> \\<zero>\"\n    apply(rule ccontr) using assms(3) \n    unfolding val_Zp_def by simp                  \n  then have T1: \"a \\<in> carrier Zp \\<and> f\\<bullet>a = \\<zero> \\<and> val_Zp (a \\<ominus> a) > val_Zp ((pderiv f)\\<bullet>a)\"\n    using assms True  \n    by(simp add: val_Zp_def)  \n  have T2: \"\\<And>b. b \\<in> carrier Zp \\<and> f\\<bullet>b = \\<zero> \\<and> val_Zp (a \\<ominus> b) > val_Zp ((pderiv f)\\<bullet>a) \\<Longrightarrow> a = b\"\n  proof- fix b assume A: \"b \\<in> carrier Zp \\<and> f\\<bullet>b = \\<zero> \\<and> val_Zp (a \\<ominus> b) > val_Zp ((pderiv f)\\<bullet>a)\"\n    obtain h where h_def: \"h = b \\<ominus> a\"\n      by blast \n    then have h_fact: \"h \\<in> carrier Zp \\<and> b = a \\<oplus> h\"\n      by (metis A R.l_neg R.minus_closed R.minus_eq R.r_zero add_assoc add_comm assms(2))        \n    then have 1: \"f\\<bullet>(a \\<oplus> h) = \\<zero>\"\n      using assms A by blast   \n    obtain c where c_def: \"c \\<in> carrier Zp \\<and> f\\<bullet>(a \\<oplus> h) = (f \\<bullet> a) \\<oplus> (deriv f a)\\<otimes>h \\<oplus> c \\<otimes>(h[^](2::nat))\"\n      using taylor_deg_1_eval'[of  f a h _ \"f \\<bullet> a\" \"deriv f a\" ]\n      by (meson taylor_closed assms(1) assms(2) to_fun_closed h_fact shift_closed)       \n    then have  \"(f \\<bullet> a) \\<oplus> (deriv f a)\\<otimes>h \\<oplus> c \\<otimes>(h[^](2::nat)) = \\<zero>\"\n      by (simp add: \"1\")\n    then have 2:  \"(deriv f a)\\<otimes>h \\<oplus> c \\<otimes>(h[^](2::nat)) = \\<zero>\"\n      by (simp add: True assms(1) assms(2) deriv_closed h_fact)   \n    hence 3: \"((deriv f a) \\<oplus> c \\<otimes>h)\\<otimes>h = \\<zero>\"      \n    proof-\n      have \"((deriv f a) \\<oplus> c \\<otimes>h)\\<otimes>h = ((deriv f a)\\<otimes>h \\<oplus> (c \\<otimes>h)\\<otimes>h)\"\n        by (simp add: R.l_distr assms(1) assms(2) c_def deriv_closed h_fact)        \n      then have \"((deriv f a) \\<oplus> c \\<otimes>h)\\<otimes>h = (deriv f a)\\<otimes>h \\<oplus> (c \\<otimes>(h\\<otimes>h))\"\n        by (simp add: mult_assoc)      \n      then have \"((deriv f a) \\<oplus> c \\<otimes>h)\\<otimes>h = (deriv f a)\\<otimes>h \\<oplus> (c \\<otimes>(h[^](2::nat)))\"\n        using nat_pow_def[of Zp h \"2\"]\n        by (simp add: h_fact)\n      then show ?thesis\n        using 2 \n        by simp\n    qed\n    have \"h = \\<zero>\"\n    proof(rule ccontr)\n      assume \"h \\<noteq> \\<zero>\"\n      then have \"(deriv f a) \\<oplus> c \\<otimes>h = \\<zero>\"\n        using 2 3 \n        by (meson R.m_closed UP_cring.deriv_closed Zp_x_is_UP_cring assms(1) assms(2) c_def h_fact local.integral sum_closed)              \n      then have \"(deriv f a) = \\<ominus> c \\<otimes>h\"\n        using R.l_minus R.minus_equality assms(1) assms(2) c_def deriv_closed h_fact by auto               \n      then have \"val_Zp (deriv f a) = val_Zp (c \\<otimes> h)\"\n        by (meson R.m_closed \\<open>deriv f a \\<oplus> c \\<otimes> h = \\<zero>\\<close> assms(1) assms(2) c_def deriv_closed h_fact val_Zp_not_equal_imp_notequal(3))            \n      then have P: \"val_Zp (deriv f a) = val_Zp h +  val_Zp c\"\n        by (simp add: c_def h_fact val_Zp_mult)\n      have \"val_Zp (deriv f a) \\<ge> val_Zp h \"\n        using P val_pos[of c] c_def  \n        by simp\n      then have \"val_Zp (deriv f a) \\<ge> val_Zp (b \\<ominus> a) \"\n        using h_def by blast\n      then have \"val_Zp (deriv f a) > val_Zp ((pderiv f)\\<bullet>a)\"\n        by (metis (no_types, lifting) A assms(2) h_def h_fact minus_a_inv not_less order_trans val_Zp_of_minus)\n      then have P0:\"val_Zp (deriv f a) > val_Zp (deriv f a)\"\n        by (metis UP_cring.pderiv_eval_deriv Zp_x_is_UP_cring assms(1) assms(2))     \n      thus False by auto \n    qed\n    then show \"a = b\"\n      by (simp add: assms(2) h_fact)\n  qed\n  show ?thesis \n    using T1 T2 \n    by blast  \nnext\n  case False\n  have F0: \"pderiv f \\<bullet> a \\<noteq> \\<zero>\"\n    apply(rule ccontr) using assms(3) \n    unfolding val_Zp_def by simp\n  obtain \\<alpha> where alpha_def:\n       \"f\\<bullet>\\<alpha> = \\<zero>\"  \"\\<alpha> \\<in> carrier Zp\" \n       \"val_Zp (a \\<ominus> \\<alpha>) > val_Zp ((pderiv f)\\<bullet>a)\"\n       \"(val_Zp (a \\<ominus> \\<alpha>) = val_Zp (divide (f\\<bullet>a) ((pderiv f)\\<bullet>a)))\"\n       \"val_Zp ((pderiv f)\\<bullet>\\<alpha>) = val_Zp ((pderiv f)\\<bullet>a)\"\n    using assms hensels_lemma F0 False by blast    \n  have 0: \"\\<And>x. x \\<in> carrier Zp \\<and> f \\<bullet> x = \\<zero> \\<and> val_Zp (a \\<ominus> x) > val_Zp (pderiv f \\<bullet> a) \\<and> val_Zp (pderiv f \\<bullet> a) \\<noteq> val_Zp (a \\<ominus> x) \\<Longrightarrow> x= \\<alpha>\"\n    using alpha_def assms hensels_lemma_unique_root[of f a \\<alpha>] F0 False by blast     \n  have 1: \"\\<alpha> \\<in> carrier Zp \\<and> f \\<bullet> \\<alpha> = \\<zero> \\<and> val_Zp (a \\<ominus> \\<alpha>) > val_Zp (pderiv f \\<bullet> a) \\<and> val_Zp (pderiv f \\<bullet> a) \\<noteq> val_Zp (a \\<ominus> \\<alpha>)\"\n    using alpha_def order_less_le by blast    \n  thus ?thesis \n    using 0  \n    by (metis (no_types, hide_lams) R.minus_closed alpha_def(1-3) assms(2) equal_val_Zp val_Zp_ultrametric_eq')\nqed\n\n(**************************************************************************************************)\n(**************************************************************************************************)\nsection\\<open>Some Applications of Hensel's Lemma to Root Finding for Polynomials over $\\mathbb{Z}_p$\\<close>\n(**************************************************************************************************)\n(**************************************************************************************************)\n\nlemma Zp_square_root_criterion:\n  assumes \"p \\<noteq> 2\"\n  assumes \"a \\<in> carrier Zp\"\n  assumes \"b \\<in> carrier Zp\"\n  assumes \"val_Zp b \\<ge> val_Zp a\"\n  assumes \"a \\<noteq> \\<zero>\"\n  assumes \"b \\<noteq> \\<zero>\"\n  shows \"\\<exists>y \\<in> carrier Zp. a[^](2::nat) \\<oplus> \\<p>\\<otimes>b[^](2::nat) = (y [^]\\<^bsub>Zp\\<^esub> (2::nat))\"\nproof-\n  have bounds: \"val_Zp a < \\<infinity>\" \"val_Zp a \\<ge> 0\" \"val_Zp b < \\<infinity>\" \"val_Zp b \\<ge> 0\"\n    using assms(2) assms(3) assms(6) assms(5) val_Zp_def val_pos[of b]  val_pos[of a] \n    by auto     \n  obtain f where f_def: \"f = monom Zp_x \\<one> 2  \\<oplus>\\<^bsub>Zp_x\\<^esub> to_polynomial Zp (\\<ominus> (a[^](2::nat)\\<oplus> \\<p>\\<otimes>b[^](2::nat)))\"\n    by simp\n  have \"\\<exists> \\<alpha>. f\\<bullet>\\<alpha> = \\<zero> \\<and> \\<alpha> \\<in> carrier Zp\"\n  proof-\n    have 0: \"f \\<in> carrier Zp_x\"\n      using f_def \n      by (simp add: X_closed assms(2) assms(3) to_poly_closed)       \n    have 1: \"(pderiv f)\\<bullet>a = [(2::nat)] \\<cdot> \\<one> \\<otimes> a\"\n    proof-\n      have \"pderiv f = pderiv (monom Zp_x \\<one> 2)\"\n        using assms f_def pderiv_add[of \"monom Zp_x \\<one> 2\"] to_poly_closed R.nat_pow_closed \n              pderiv_deg_0\n        unfolding to_polynomial_def \n        using P.nat_pow_closed P.r_zero R.add.inv_closed X_closed Zp_int_inc_closed deg_const monom_term_car pderiv_closed sum_closed\n        by (metis (no_types, lifting) R.one_closed monom_closed)                                                                                                            \n      then have 20: \"pderiv f = monom (Zp_x) ([(2::nat) ] \\<cdot> \\<one>) (1::nat)\"\n        using pderiv_monom[of \\<one> 2] \n        by simp\n      have 21: \"[(2::nat)] \\<cdot> \\<one> \\<noteq> \\<zero>\"\n        using Zp_char_0'[of 2] by simp \n      have 22: \"(pderiv f)\\<bullet>a = [(2::nat)] \\<cdot> \\<one> \\<otimes> (a[^]((1::nat)))\"\n        using 20 \n        by (simp add: Zp_nat_inc_closed assms(2) to_fun_monom)        \n      then show ?thesis\n        using assms(2) \n        by (simp add: cring.cring_simprules(12))       \n    qed\n    have 2: \"(pderiv f)\\<bullet>a \\<noteq> \\<zero>\"\n      using 1 assms \n      by (metis Zp_char_0' Zp_nat_inc_closed local.integral zero_less_numeral)\n    have 3: \"f\\<bullet>a = \\<ominus> (\\<p>\\<otimes>b[^](2::nat))\"\n    proof-\n      have 3: \"f\\<bullet>a =\n    monom (UP Zp) \\<one> 2 \\<bullet> a \\<oplus>\n    to_polynomial Zp (\\<ominus> (a [^] (2::nat) \\<oplus> [p] \\<cdot> \\<one> \\<otimes> b [^] (2::nat)))\\<bullet>a\"\n        unfolding f_def apply(rule to_fun_plus)\n          apply (simp add: assms(2) assms(3) to_poly_closed)\n         apply simp\n        by (simp add: assms(2))\n      have 30: \"f\\<bullet>a = a[^](2::nat)  \\<ominus> (a[^](2::nat) \\<oplus> \\<p>\\<otimes>b[^](2::nat))\"\n        unfolding 3  by (simp add: R.minus_eq assms(2) assms(3) to_fun_monic_monom to_fun_to_poly)\n      have 31: \"f\\<bullet>a = a[^](2::nat)  \\<ominus> a[^](2::nat) \\<ominus> (\\<p>\\<otimes>b[^](2::nat))\"\n      proof-\n        have 310: \"a[^](2::nat) \\<in> carrier Zp\"\n          using assms(2) pow_closed \n          by blast\n        have 311: \"\\<p>\\<otimes>(b[^](2::nat)) \\<in> carrier Zp\"\n          by (simp add: assms(3) monom_term_car)\n        have   \"\\<ominus> (a [^] (2::nat)\\<oplus>(\\<p> \\<otimes> b [^] (2::nat))) = \\<ominus> (a [^] (2::nat)) \\<oplus> \\<ominus> (\\<p> \\<otimes> (b [^] (2::nat)))\"\n          using 310 311 R.minus_add by blast                  \n        then show ?thesis  \n          by (simp add: \"30\" R.minus_eq add_assoc)                                                  \n      qed\n      have 32: \"f\\<bullet>a = (a[^](2::nat)  \\<ominus> a[^](2::nat)) \\<ominus> (\\<p>\\<otimes>b[^](2::nat))\"\n        using 31 unfolding a_minus_def \n        by blast\n      have 33: \"\\<p>\\<otimes>b[^](2::nat) \\<in> carrier Zp\"\n        by (simp add: Zp_nat_inc_closed assms(3) monom_term_car)\n      have 34: \"a[^](2::nat) \\<in> carrier Zp\"\n        using assms(2) pow_closed by blast\n      then have 34: \"(a[^](2::nat)  \\<ominus> a[^](2::nat)) = \\<zero> \"\n        by simp        \n      have 35: \"f\\<bullet>a = \\<zero> \\<ominus> (\\<p>\\<otimes>b[^](2::nat))\"\n        by (simp add: \"32\" \"34\")                \n      then show ?thesis \n        using 33 unfolding a_minus_def   \n        by (simp add: cring.cring_simprules(3))\n    qed\n    have 4: \"f\\<bullet>a \\<noteq>\\<zero>\"\n      using 3 assms  \n      by (metis R.add.inv_eq_1_iff R.m_closed R.nat_pow_closed Zp.integral Zp_int_inc_closed\n          mult_zero_r nonzero_pow_nonzero p_natpow_prod_Suc(1) p_pow_nonzero(2))                                                \n    have 5: \"val_Zp (f\\<bullet>a) = 1 + 2*val_Zp b\"\n    proof-\n      have \"val_Zp (f\\<bullet>a) = val_Zp (\\<p>\\<otimes>b[^](2::nat))\"\n        using 3 Zp_int_inc_closed assms(3) monom_term_car val_Zp_of_minus by presburger               \n      then have \"val_Zp (\\<p>\\<otimes>b[^](2::nat)) = 1 + val_Zp (b[^](2::nat))\"\n        by (simp add: assms(3) val_Zp_mult val_Zp_p)                \n      then show ?thesis \n        using assms(3) assms(6) \n        using Zp_def \\<open>val_Zp (to_fun f a) = val_Zp ([p] \\<cdot> \\<one> \\<otimes> b [^] 2)\\<close> not_nonzero_Zp\n          padic_integers_axioms val_Zp_pow' by fastforce                           \n    qed\n    have 6: \"val_Zp ((pderiv f)\\<bullet>a) = val_Zp a\"\n    proof-\n      have 60: \"val_Zp ([(2::nat)] \\<cdot> \\<one> \\<otimes> a) = val_Zp ([(2::nat)] \\<cdot> \\<one>) + val_Zp a\"\n        by (simp add: Zp_char_0' assms(2) assms(5) val_Zp_mult ord_of_nonzero(2) ord_pos)\n      have \"val_Zp ([(2::nat)] \\<cdot> \\<one>) = 0\"\n      proof-\n        have \"(2::nat) < p\"\n          using prime assms prime_ge_2_int by auto          \n        then have \"(2::nat) mod p = (2::nat)\"\n          by simp\n        then show ?thesis \n          by (simp add: val_Zp_p_nat_unit)          \n      qed\n      then show ?thesis \n        by (simp add: \"1\" \"60\")        \n    qed\n    then have 7: \"val_Zp (f\\<bullet>a) > 2* val_Zp ((pderiv f)\\<bullet>a)\"\n      using bounds 5 assms(4) \n      by (simp add: assms(5) assms(6) one_eint_def val_Zp_def)\n    obtain \\<alpha> where\n       A0: \"f\\<bullet>\\<alpha> = \\<zero>\"  \"\\<alpha> \\<in> carrier Zp\"       \n      using hensels_lemma[of f a] \"0\" \"2\" \"4\" \"7\" assms(2) \n      by blast\n    show ?thesis \n      using A0  by blast   \n  qed\n  then obtain \\<alpha> where \\<alpha>_def: \"f\\<bullet>\\<alpha> = \\<zero> \\<and> \\<alpha> \\<in> carrier Zp\"\n    by blast \n  have \"f\\<bullet>\\<alpha> = \\<alpha> [^](2::nat)  \\<ominus> (a[^](2::nat)\\<oplus> \\<p>\\<otimes>b[^](2::nat))\" \n  proof- \n    have 0: \"f\\<bullet>\\<alpha> =\n    monom (UP Zp) \\<one> 2 \\<bullet> \\<alpha> \\<oplus>\n    to_polynomial Zp (\\<ominus> (a [^] (2::nat) \\<oplus> [p] \\<cdot> \\<one> \\<otimes> b [^] (2::nat)))\\<bullet>\\<alpha>\"\n        unfolding f_def apply(rule to_fun_plus)\n          apply (simp add: assms(2) assms(3) to_poly_closed)\n         apply simp\n        by (simp add: \\<alpha>_def)\n    thus ?thesis \n      by (simp add: R.minus_eq \\<alpha>_def assms(2) assms(3) to_fun_monic_monom to_fun_to_poly)\n  qed\n  then show ?thesis \n    by (metis R.r_right_minus_eq Zp_int_inc_closed \\<alpha>_def assms(2) assms(3) monom_term_car pow_closed sum_closed)        \nqed\n\nlemma Zp_semialg_eq:\n  assumes \"a \\<in> nonzero Zp\"\n  shows \"\\<exists>y \\<in> carrier Zp. \\<one> \\<oplus> (\\<p> [^] (3::nat))\\<otimes> (a [^] (4::nat)) = (y [^] (2::nat))\"\nproof-\n  obtain f where f_def: \"f = monom Zp_x \\<one> 2 \\<oplus>\\<^bsub>Zp_x\\<^esub> to_poly (\\<ominus> (\\<one> \\<oplus> (\\<p> [^] (3::nat))\\<otimes> (a [^] (4::nat))))\"\n    by simp\n  have a_car: \"a \\<in> carrier Zp\"\n    by (simp add: nonzero_memE assms)\n  have \"f \\<in> carrier Zp_x\"\n    using f_def \n    by (simp add: a_car to_poly_closed)             \n  hence 0:\"f\\<bullet>\\<one> = \\<one> \\<ominus> (\\<one> \\<oplus> (\\<p> [^] (3::nat))\\<otimes> (a [^] (4::nat)))\"\n    using f_def \n    by (simp add: R.minus_eq assms nat_pow_nonzero nonzero_mult_in_car p_pow_nonzero' to_fun_monom_plus to_fun_to_poly to_poly_closed)\n  then have 1: \"f\\<bullet>\\<one> = \\<ominus> (\\<p> [^] (3::nat))\\<otimes> (a [^] (4::nat))\"\n    unfolding a_minus_def \n    by (smt R.add.inv_closed R.l_minus R.minus_add R.minus_minus R.nat_pow_closed R.one_closed R.r_neg1 a_car monom_term_car p_pow_nonzero(1))\n  then have \"val_Zp (f\\<bullet>\\<one>) = 3 + val_Zp (a [^] (4::nat))\"\n    using  assms val_Zp_mult[of \"\\<p> [^] (3::nat)\" \"(a [^] (4::nat))\" ] \n      val_Zp_p_pow p_pow_nonzero[of \"3::nat\"] val_Zp_of_minus  \n    by (metis R.l_minus R.nat_pow_closed a_car monom_term_car of_nat_numeral)\n  then have 2: \"val_Zp (f\\<bullet>\\<one>) = 3 + 4* val_Zp a\"\n    using assms val_Zp_pow' by auto\n  have \"pderiv f = pderiv (monom Zp_x \\<one> 2)\"\n    using assms f_def pderiv_add[of \"monom Zp_x \\<one> 2\"] to_poly_closed R.nat_pow_closed  pderiv_deg_0\n    unfolding to_polynomial_def \n    by (metis (no_types, lifting) P.r_zero R.add.inv_closed R.add.m_closed R.one_closed \n        UP_zero_closed a_car deg_const deg_nzero_nzero monom_closed monom_term_car p_pow_nonzero(1))\n  then have 3: \"pderiv f = [(2::nat)] \\<cdot> \\<one> \\<odot>\\<^bsub>Zp_x\\<^esub> X \"\n    by (metis P.nat_pow_eone R.one_closed Suc_1 X_closed diff_Suc_1 monom_rep_X_pow pderiv_monom')\n  hence 4: \"val_Zp ((pderiv f)\\<bullet>\\<one>) = val_Zp ([(2::nat)] \\<cdot> \\<one> )\"\n    by (metis R.add.nat_pow_eone R.nat_inc_prod R.nat_inc_prod' R.nat_pow_one R.one_closed \n        Zp_nat_inc_closed \\<open>pderiv f = pderiv (monom Zp_x \\<one> 2)\\<close> pderiv_monom to_fun_monom)\n  have \"(2::int) = (int (2::nat))\"\n    by simp\n  then  have 5: \"[(2::nat)] \\<cdot> \\<one> = ([(int (2::nat))] \\<cdot> \\<one> )\"\n     using add_pow_def int_pow_int \n     by metis     \n  have 6: \"val_Zp ((pderiv f)\\<bullet>\\<one>) \\<le> 1\" \n    apply(cases \"p = 2\") \n    using \"4\" \"5\" val_Zp_p apply auto[1]\n  proof-\n    assume \"p \\<noteq> 2\"\n    then have 60: \"coprime 2 p\"\n      using prime prime_int_numeral_eq primes_coprime two_is_prime_nat by blast    \n    have 61: \"2 < p\"\n      using 60 prime \n      by (smt \\<open>p \\<noteq> 2\\<close> prime_gt_1_int)\n    then show ?thesis \n      by (smt \"4\" \"5\" \\<open>2 = int 2\\<close> mod_pos_pos_trivial nonzero_closed p_nonzero val_Zp_p val_Zp_p_int_unit val_pos)\n  qed\n  have 7: \"val_Zp (f\\<bullet>\\<one>) \\<ge> 3\"\n  proof-\n    have \"eint 4 * val_Zp a \\<ge> 0\"\n      using 2 val_pos[of a] \n      by (metis R.nat_pow_closed a_car assms of_nat_numeral val_Zp_pow' val_pos)\n    thus ?thesis \n      using \"2\" by auto\n  qed\n  have \"2*val_Zp ((pderiv f)\\<bullet>\\<one>) \\<le> 2*1\"\n    using 6 one_eint_def eint_mult_mono' \n    by (smt \\<open>2 = int 2\\<close> eint.distinct(2) eint_ile eint_ord_simps(1) eint_ord_simps(2) mult.commute \n        ord_Zp_p ord_Zp_p_pow ord_Zp_pow p_nonzero p_pow_nonzero(1) times_eint_simps(1) val_Zp_p val_Zp_pow' val_pos)\n  hence 8: \"2 * val_Zp ((pderiv f)\\<bullet> \\<one>) < val_Zp (f\\<bullet>\\<one>)\"\n    using 7 le_less_trans[of \"2 * val_Zp ((pderiv f)\\<bullet> \\<one>)\" \"2::eint\" 3] \n            less_le_trans[of \"2 * val_Zp ((pderiv f)\\<bullet> \\<one>)\" 3 \"val_Zp (f\\<bullet>\\<one>)\"] one_eint_def\n    by auto\n  obtain \\<alpha> where  \\<alpha>_def: \"f\\<bullet>\\<alpha> = \\<zero>\" and  \\<alpha>_def' :\"\\<alpha> \\<in> carrier Zp\"\n    using 2 6 7 hensels_lemma' 8 \\<open>f \\<in> carrier Zp_x\\<close>  by blast\n  have 0: \"(monom Zp_x \\<one> 2) \\<bullet> \\<alpha> = \\<alpha> [^] (2::nat)\"\n    by (simp add: \\<alpha>_def' to_fun_monic_monom)          \n  have 1: \"to_poly (\\<ominus> (\\<one> \\<oplus> (\\<p> [^] (3::nat))\\<otimes> (a [^] (4::nat)))) \\<bullet> \\<alpha> =\\<ominus>( \\<one> \\<oplus> (\\<p> [^] (3::nat))\\<otimes> (a [^] (4::nat)))\"\n    by (simp add: \\<alpha>_def' a_car to_fun_to_poly)  \n  then have \"\\<alpha> [^] (2::nat) \\<ominus> (\\<one> \\<oplus> (\\<p> [^] (3::nat))\\<otimes> (a [^] (4::nat))) = \\<zero>\"\n    using \\<alpha>_def \\<alpha>_def' \n    by (simp add: R.minus_eq a_car f_def to_fun_monom_plus to_poly_closed)    \n  then show ?thesis \n    by (metis R.add.m_closed R.nat_pow_closed R.one_closed R.r_right_minus_eq \\<alpha>_def' a_car monom_term_car p_pow_nonzero(1))   \nqed\n\nlemma Zp_nth_root_lemma:\n  assumes \"a \\<in> carrier Zp\"\n  assumes \"a \\<noteq> \\<one>\"\n  assumes \"n > 1\"\n  assumes \"val_Zp (\\<one> \\<ominus> a) > 2*val_Zp ([(n::nat)]\\<cdot> \\<one>)\"\n  shows \"\\<exists> b \\<in> carrier Zp. b[^]n = a\"\nproof-\n  obtain f where f_def: \"f = monom Zp_x \\<one> n \\<oplus>\\<^bsub>Zp_x\\<^esub> monom Zp_x (\\<ominus>a) 0\"\n    by simp\n  have \"f \\<in> carrier Zp_x\"\n    using f_def monom_closed assms \n    by simp\n  have 0: \"pderiv f = monom Zp_x ([n]\\<cdot> \\<one>) (n-1)\"\n    by (simp add: assms(1) f_def pderiv_add pderiv_monom)    \n  have 1: \"f \\<bullet> \\<one> = \\<one> \\<ominus> a\"\n    using f_def \n    by (metis R.add.inv_closed R.minus_eq R.nat_pow_one R.one_closed assms(1) to_fun_const to_fun_monom to_fun_monom_plus monom_closed)\n  have 2: \"(pderiv f) \\<bullet> \\<one> = ([n]\\<cdot> \\<one>)\"\n    using 0 to_fun_monom assms \n    by simp\n  have 3: \"val_Zp (f \\<bullet> \\<one>) > 2* val_Zp ((pderiv f) \\<bullet> \\<one>)\"\n    using 1 2 assms \n    by (simp add: val_Zp_def)\n  have 4: \"f \\<bullet> \\<one> \\<noteq> \\<zero>\"\n    using 1 assms(1) assms(2) by auto\n  have 5: \"(pderiv f) \\<bullet> \\<one> \\<noteq> \\<zero>\"\n    using \"2\" Zp_char_0' assms(3) by auto\n  obtain \\<beta> where beta_def: \"\\<beta> \\<in> carrier Zp \\<and> f \\<bullet> \\<beta> = \\<zero>\"\n    using hensels_lemma[of f \\<one>]\n    by (metis \"3\" \"5\" R.one_closed \\<open>f \\<in> carrier Zp_x\\<close>)\n  then have \"(\\<beta> [^] n) \\<ominus> a = \\<zero>\"\n    using f_def R.add.inv_closed  assms(1) to_fun_const[of \"\\<ominus> a\"] to_fun_monic_monom[of \\<beta> n] to_fun_plus monom_closed\n    unfolding a_minus_def \n    by (simp add: beta_def)\n  then have \"\\<beta> \\<in> carrier Zp \\<and> \\<beta> [^] n = a\"\n    using beta_def nonzero_memE  not_eq_diff_nonzero assms(1) pow_closed \n    by blast\n  then show ?thesis by blast \nqed\n    \nend\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/Padic_Ints/Hensels_Lemma.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473647220787, "lm_q2_score": 0.817574471748733, "lm_q1q2_score": 0.7132089358940529}}
{"text": "(* Title:      Kleene Algebra\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\nheader {* Action Algebras *}\n\ntheory Action_Algebra\nimports Kleene_Algebra\nbegin\n\ntext {* Action algebras have been defined and discussed in Vaughan\nPratt's paper on \\emph{Action Logic and Pure\nInduction}~\\cite{pratt90action}. They are expansions of Kleene\nalgebras by operations of left and right residuation. They are\ninteresting, first because most models of Kleene algebras, e.g.\nrelations, traces, paths and languages, possess the residuated\nstructure, and second because, in this setting, the Kleene star can be\nequationally defined.\n\nAction algebras can be based on residuated\nsemilattices~\\cite{galatosjipsenkowalskiono07residuated}, which are\ninteresting in their own right. Many important properties of action\nalgebras already arise at this level.\n\nHere we only prove some basic properties of residuated semilattices\nand action algebras. A more extensive treatment is left for future\nwork. There is also an obvious duality between proofs for left and\nright residuation which we do not formalise at this stage. *}\n\nclass residuated_join_semilattice = join_semilattice + semigroup_mult + residual_l_op + residual_r_op +\n  assumes residual_l_galois: \"x \\<le> z \\<leftarrow> y \\<longleftrightarrow> x \\<cdot> y \\<le> z\"\n  and residual_r_galois: \"x \\<cdot> y \\<le> z \\<longleftrightarrow> y \\<le> x \\<rightarrow> z\"\nbegin\n\ntext {* We first prove unit and counit laws for residuals, which are\nalso known as cancellation laws. *}\n\nlemma galois_unitl: \"x \\<le> x \\<cdot> y \\<leftarrow> y\"\n  by (metis eq_refl residual_l_galois)\n\nlemma galois_counitl: \"(y \\<leftarrow> x) \\<cdot> x \\<le> y\"\n  by (metis eq_refl residual_l_galois)\n\nlemma galois_unitr: \"y \\<le> x \\<rightarrow> x \\<cdot> y\"\n  by (metis eq_refl residual_r_galois)\n\nlemma galois_counitr: \"x \\<cdot> (x \\<rightarrow> y) \\<le> y\"\n  by (metis eq_refl residual_r_galois)\n\ntext {* Next we show that distributivity laws hold (in fact, even\ndistributivity laws for all existing suprema). *}\n\nlemma distl: \"x \\<cdot> (y + z) = x \\<cdot> y + x \\<cdot> z\"\nproof -\n  {\n    fix w\n    have \"x \\<cdot> (y + z) \\<le> w \\<longleftrightarrow> y + z \\<le> x \\<rightarrow> w\"\n      by (metis residual_r_galois)\n    also have \"... \\<longleftrightarrow> y \\<le> x \\<rightarrow> w \\<and> z \\<le> x \\<rightarrow> w\"\n      by (fact add_lub)\n    also have \"... \\<longleftrightarrow> x \\<cdot> y \\<le> w \\<and> x \\<cdot> z \\<le> w\"\n      by (metis residual_r_galois)\n    ultimately have\"x \\<cdot> (y + z) \\<le> w \\<longleftrightarrow> x \\<cdot> y + x \\<cdot> z \\<le> w\"\n      by (metis add_lub)\n  }\n  thus ?thesis\n    by (metis eq_iff)\nqed\n\nlemma distr: \"(x + y) \\<cdot> z = x \\<cdot> z + y \\<cdot> z\"\nproof -\n  {\n    fix w\n    have \"(x + y) \\<cdot> z \\<le> w \\<longleftrightarrow> x + y \\<le> w \\<leftarrow> z\"\n      by (metis residual_l_galois)\n    also have \"... \\<longleftrightarrow> x \\<le> w \\<leftarrow> z \\<and> y \\<le> w \\<leftarrow> z\"\n      by (fact add_lub)\n    also have \"... \\<longleftrightarrow> x \\<cdot> z \\<le> w \\<and> y \\<cdot> z \\<le> w\"\n      by (metis residual_l_galois)\n    ultimately have\"(x + y) \\<cdot> z \\<le> w \\<longleftrightarrow> x \\<cdot> z + y \\<cdot> z \\<le> w\"\n      by (metis add_lub)\n  }\n  thus ?thesis\n    by (metis eq_iff)\nqed\n\ntext {* As usual, distributivity implies isotonicity. *}\n\nlemma mult_isol: \"x \\<le> y \\<longrightarrow> z \\<cdot> x \\<le> z \\<cdot> y\"\n  by (metis distl less_eq_def)\n\nlemma mult_isor: \"x \\<le> y \\<longrightarrow> x \\<cdot> z \\<le> y \\<cdot> z\"\n  by (metis distr less_eq_def)\n\ntext {* Similarly, the residuals as upper adjoints preserve all\nexisting meets, but we do not assume that any meets exist in\nresiduated semilattices. However we can show subdistributivity with\nrespect to residuation. *}\n\nlemma residual_l_subdist_var: \"x \\<leftarrow> z \\<le> (x + y) \\<leftarrow> z\"\nproof -\n  {\n    fix w\n    have \"w \\<le> x \\<leftarrow> z \\<longleftrightarrow> w \\<cdot> z \\<le> x\"\n      by (metis residual_l_galois)\n    also have \"... \\<longrightarrow> w \\<cdot> z \\<le> x + y\"\n      by (metis add_ub1 order_trans)\n    ultimately have \"w \\<le> x \\<leftarrow> z \\<longrightarrow> w \\<le> (x + y) \\<leftarrow> z\"\n      by (metis residual_l_galois)\n  }\n  thus ?thesis\n    by (metis eq_refl)\nqed\n\nlemma residual_l_subdist: \"(x \\<leftarrow> z) + (y \\<leftarrow> z) \\<le> (x + y) \\<leftarrow> z\"\n  by (metis add_comm add_lub residual_l_subdist_var)\n\nlemma residual_r_subdist_var: \"(x \\<rightarrow> y) \\<le> x \\<rightarrow> (y + z)\"\n  by (metis add_ub1 galois_counitr order_trans residual_r_galois)\n\nlemma residual_r_subdist: \"(x \\<rightarrow> y) + (x \\<rightarrow> z) \\<le> x \\<rightarrow> (y + z)\"\n  by (metis add_comm add_lub residual_r_subdist_var)\n\ntext {* As usual, subdistributivity implies isotonicity. *}\n\nlemma residual_l_isol: \"x \\<le> y \\<longrightarrow> x \\<leftarrow> z \\<le> y \\<leftarrow> z\"\n  by (metis less_eq_def residual_l_subdist_var)\n\nlemma residual_r_isor: \"x \\<le> y \\<longrightarrow> z \\<rightarrow> x \\<le> z \\<rightarrow> y\"\n  by (metis less_eq_def residual_r_subdist_var)\n\ntext {* Next, we prove superdistributivity laws for residuation. *}\n\nlemma residual_l_superdist_var: \"x \\<leftarrow> (y + z) \\<le> x \\<leftarrow> y\"\nproof -\n  {\n    fix w\n    have \"w \\<le> x \\<leftarrow> (y + z) \\<longleftrightarrow> w \\<cdot> (y + z) \\<le> x\"\n      by (metis residual_l_galois)\n     also have \"... \\<longleftrightarrow> w \\<cdot> y \\<le> x \\<and> w \\<cdot> z \\<le> x\"\n       by (metis add_lub distl)\n     also have \"... \\<longleftrightarrow> w \\<le> x \\<leftarrow> y \\<and> w \\<le> x \\<leftarrow> z\"\n       by (metis residual_l_galois)\n    finally have \"w \\<le> x \\<leftarrow> (y + z) \\<longrightarrow> w \\<le> x \\<leftarrow> y\"\n      by simp\n  }\n  thus ?thesis\n    by (metis eq_refl)\nqed\n\nlemma residual_r_superdist_var: \"(x + y) \\<rightarrow> z \\<le> x \\<rightarrow> z\"\n  by (metis add_lub galois_counitr residual_l_galois residual_r_galois)\n\ntext {* The previous proof shows, in fact, that @{text \"x \\<leftarrow> (y + z)\"}\nis the infimum of @{text \"x \\<leftarrow> y\"} and @{text \"x \\<leftarrow> z\"}; but we have no\noperation to express this fact in action algebra. A dual property\nholds for right residuation. *}\n\ntext {* As usual, superdistributivity implies antitonicity. *}\n\nlemma residual_l_antitoner: \"x \\<le> y \\<longrightarrow> z \\<leftarrow> y \\<le> z \\<leftarrow> x\"\n  by (metis less_eq_def residual_l_superdist_var)\n\nlemma residual_r_antitonel: \"x \\<le> y \\<longrightarrow> y \\<rightarrow> z \\<le> x \\<rightarrow> z\"\n  by (metis less_eq_def residual_r_superdist_var)\n\ntext {* Finally we prove transitivity laws for residuals. *}\n\nlemma residual_l_trans: \"(x \\<leftarrow> y) \\<cdot> (y \\<leftarrow> z) \\<le> x \\<leftarrow> z\"\nproof -\n  have \"(x \\<leftarrow> y) \\<cdot> y \\<le> x\"\n    by (metis galois_counitl)\n  hence \"(x \\<leftarrow> y) \\<cdot> (y \\<leftarrow> z) \\<cdot> z \\<le> x\"\n    by (metis galois_counitl mult.assoc residual_l_antitoner residual_l_galois)\n  thus ?thesis\n    by (metis residual_l_galois)\nqed\n\nlemma residual_r_trans: \"(x \\<rightarrow> y) \\<cdot> (y \\<rightarrow> z) \\<le> x \\<rightarrow> z\"\nproof -\n  have \"y \\<cdot> (y \\<rightarrow> z)  \\<le> z\"\n    by (metis galois_counitr)\n  hence \"x \\<cdot> (x \\<rightarrow> y) \\<cdot> (y \\<rightarrow> z)  \\<le> z\"\n    by (metis galois_counitr mult.assoc residual_r_antitonel residual_r_galois)\n  thus ?thesis\n    by (metis mult.assoc residual_r_galois)\nqed\n\nend (* residuated_join_semilattice *)\n\ntext {* We now present an equivalent equational axiomatisation of\nresiduated join semilattices, which is essentially derived from an\nequational axiomatisation of Galois connections in algebras with\nsufficient structure. This equivalence is the basis for establishing\nthe equivalence of the equational axiomatisation of action algebra and\nthat based on Galois connections.  *}\n\nclass equational_residuated_join_semilattice = join_semilattice + semigroup_mult + residual_l_op + residual_r_op +\n  assumes mult_subdist: \"z \\<cdot> x \\<le> z \\<cdot> (x + y)\"\n  and mult_subdistr: \"x \\<cdot> z \\<le> (x+y) \\<cdot> z\"\n  and right_addition: \"x \\<rightarrow> y \\<le> x \\<rightarrow> (y + z)\"\n  and right_galois_counit: \"x \\<cdot> (x \\<rightarrow> y) \\<le> y\"\n  and right_galois_unit: \"y \\<le> x \\<rightarrow> x \\<cdot> y\"\n  and left_addition: \"y \\<leftarrow> x \\<le> (y + z) \\<leftarrow> x\"\n  and left_galois_counit: \"(y \\<leftarrow> x) \\<cdot> x \\<le> y\"\n  and left_galois_unit: \"y \\<le> y \\<cdot> x \\<leftarrow> x\"\nbegin\n\nlemma residual_l_galois': \"x \\<cdot> y \\<le> z \\<longleftrightarrow> x \\<le> z \\<leftarrow> y\"\nproof\n  assume \"x \\<cdot> y \\<le> z\"\n  hence \"(x \\<cdot> y) \\<leftarrow> y \\<le> z \\<leftarrow> y\"\n    by (metis less_eq_def left_addition)\n  thus \"x \\<le> z \\<leftarrow> y\"\n    by (metis order_trans left_galois_unit)\nnext\n  assume \"x \\<le> z \\<leftarrow> y\"\n  hence \"x \\<cdot> y \\<le> (z \\<leftarrow> y) \\<cdot> y\"\n    by (metis less_eq_def mult_subdistr)\n  thus \"x \\<cdot> y \\<le> z\"\n    by (metis order_trans left_galois_counit)\nqed\n\nlemma residual_r_galois': \"x \\<cdot> y \\<le> z \\<longleftrightarrow> y \\<le> x \\<rightarrow> z\"\nproof\n  assume \"x \\<cdot> y \\<le> z\"\n  hence \"x \\<rightarrow> (x \\<cdot> y) \\<le> x \\<rightarrow> z\"\n    by (metis less_eq_def right_addition)\n  thus \"y \\<le> x \\<rightarrow> z\"\n    by (metis order_trans right_galois_unit)\nnext\n  assume \"y \\<le> x \\<rightarrow> z\"\n  hence \"x \\<cdot> y \\<le> x \\<cdot> (x \\<rightarrow> z)\"\n    by (metis less_eq_def mult_subdist)\n  thus \"x \\<cdot> y \\<le> z\"\n    by (metis order_trans right_galois_counit)\nqed\n\nsubclass residuated_join_semilattice\n  by (unfold_locales, metis residual_l_galois', metis residual_r_galois')\n\nend (* equational_residuated_join_semilattice *)\n\ntext {*\nConversely, every residuated join semilattice satisfies the axioms of\nequational residuated join semilattices.\n\nBecause the subclass relation must be acyclic in Isabelle, we can\nonly establish this for the corresponding locales.\n*}\n\nsublocale residuated_join_semilattice \\<subseteq> equational_residuated_join_semilattice\n  by (unfold_locales, metis add_ub1 mult_isol, metis add_ub1 mult_isor, metis residual_r_subdist_var, metis galois_counitr, metis galois_unitr, metis residual_l_subdist_var, metis galois_counitl, metis galois_unitl)\n\ntext {* We can now define an action algebra as a residuated join\nsemilattice that is also a dioid. Following Pratt, we also add a star\noperation that is axiomatised as a reflexive transitive closure\noperation.\n*}\n\nclass action_algebra = residuated_join_semilattice + dioid_one_zero + star_op +\n  assumes star_rtc1: \"1 + x\\<^sup>\\<star> \\<cdot> x\\<^sup>\\<star> + x \\<le> x\\<^sup>\\<star>\"\n  and star_rtc2: \"1 + y \\<cdot> y + x \\<le> y \\<longrightarrow> x\\<^sup>\\<star> \\<le> y\"\nbegin\n\ntext {* We first prove a reflexivity property for residuals. *}\n\nlemma residual_r_refl: \"1 \\<le> x \\<rightarrow> x\"\nproof -\n  have \"x \\<le> x\"\n    by auto\n  thus ?thesis\n    by (metis mult_oner residual_r_galois)\nqed\n\nlemma residual_l_refl: \"1 \\<le> x \\<leftarrow> x\"\nproof -\n  have \"x \\<le> x\"\n    by auto\n  thus ?thesis\n    by (metis mult_onel residual_l_galois)\nqed\n\ntext {* We now derive pure induction laws for residuals. *}\n\nlemma residual_l_pure_induction: \"(x \\<leftarrow> x)\\<^sup>\\<star> \\<le> x \\<leftarrow> x\"\nproof -\n  have \"1 + (x \\<leftarrow> x) \\<cdot> (x \\<leftarrow> x) + (x \\<leftarrow> x) \\<le> (x \\<leftarrow> x)\"\n    by (metis add_lub eq_iff residual_l_refl residual_l_trans)\n  thus ?thesis\n    by (metis star_rtc2)\nqed\n\nlemma residual_r_pure_induction: \"(x \\<rightarrow> x)\\<^sup>\\<star> \\<le> x \\<rightarrow> x\"\n  by (metis add_lub eq_iff residual_r_refl residual_r_trans star_rtc2)\n\ntext {* Next we show that every action algebra is a Kleene\nalgebra. First, we derive the star unfold law and the star induction\nlaws in action algebra. Then we prove a subclass statement. *}\n\nlemma star_unfoldl: \"1 + x \\<cdot> x\\<^sup>\\<star> \\<le> x\\<^sup>\\<star>\"\nproof -\n  have \"x \\<cdot> x\\<^sup>\\<star> \\<le> x\\<^sup>\\<star>\"\n    by (metis add_lub mult_isor order_trans star_rtc1)\n  thus ?thesis\n    by (metis add_lub star_rtc1)\nqed\n\nlemma star_mon: \"x \\<le> y \\<longrightarrow> x\\<^sup>\\<star> \\<le> y\\<^sup>\\<star>\"\nproof\n  assume \"x \\<le> y\"\n  hence \"x \\<le> y\\<^sup>\\<star>\"\n    by (metis add_lub order_trans star_rtc1)\n  hence \"1 + x + y\\<^sup>\\<star> \\<cdot> y\\<^sup>\\<star> \\<le> y\\<^sup>\\<star>\"\n    by (metis add_lub star_rtc1)\n  thus \"x\\<^sup>\\<star> \\<le> y\\<^sup>\\<star>\"\n    by (metis add.assoc add.commute star_rtc2)\nqed\n\nlemma star_subdist': \"x\\<^sup>\\<star> \\<le> (x + y)\\<^sup>\\<star>\"\n  by (metis add_ub1 star_mon)\n\nlemma star_inductl: \"z + x \\<cdot> y \\<le> y \\<longrightarrow> x\\<^sup>\\<star> \\<cdot> z \\<le> y\"\nproof\n  assume \"z + x \\<cdot> y \\<le> y\"\n  also have \"z \\<le> y\"\n    by (metis add_lub calculation)\n  moreover have \"x \\<cdot> y \\<le> y\"\n    by (metis add_lub calculation)\n  hence \"x \\<le> y \\<leftarrow> y\"\n    by (metis residual_l_galois)\n  hence \"x\\<^sup>\\<star> \\<le> (y \\<leftarrow> y)\\<^sup>\\<star>\"\n    by (metis star_mon)\n  hence \"x\\<^sup>\\<star> \\<le> y \\<leftarrow> y\"\n    by (metis order_trans residual_l_pure_induction)\n  hence \"x\\<^sup>\\<star> \\<cdot> y \\<le> y\"\n    by (metis residual_l_galois)\n  thus \"x\\<^sup>\\<star> \\<cdot> z \\<le> y\"\n    by (metis calculation mult_isol order_trans)\nqed\n\nlemma star_inductr: \"z + y \\<cdot> x \\<le> y \\<longrightarrow> z \\<cdot> x\\<^sup>\\<star> \\<le> y\"\nproof\n  assume \"z + y \\<cdot> x \\<le> y\"\n  also have \"z \\<le> y\"\n    by (metis add_lub calculation)\n  moreover have \"y \\<cdot> x \\<le> y\"\n    by (metis add_lub calculation)\n  hence \"x \\<le> y \\<rightarrow> y\"\n    by (metis residual_r_galois)\n  hence \"x\\<^sup>\\<star> \\<le> (y \\<rightarrow> y)\\<^sup>\\<star>\"\n    by (metis star_mon)\n  hence \"x\\<^sup>\\<star> \\<le> y \\<rightarrow> y\"\n    by (metis order_trans residual_r_pure_induction)\n  hence \"y \\<cdot> x\\<^sup>\\<star> \\<le> y\"\n    by (metis residual_r_galois)\n  thus \"z \\<cdot> x\\<^sup>\\<star> \\<le> y\"\n    by (metis calculation mult_isor order_trans)\nqed\n\nsubclass kleene_algebra\n  by (unfold_locales, auto simp add: star_unfoldl star_inductl star_inductr)\n\nend (* action_algebra *)\n\n\nsubsection {* Equational Action Algebras *}\n\ntext {* The induction axioms of Kleene algebras are universal Horn\nformulas. This is unavoidable, because due to a well known result of\nRedko, there is no finite equational axiomatisation for the equational\ntheory of regular expressions.\n\nAction algebras, in contrast, admit a finite equational\naxiomatization, as Pratt has shown. We now formalise this\nresult. Consequently, the equational action algebra axioms, which\nimply those based on Galois connections, which in turn imply those of\nKleene algebras, are complete with respect to the equational theory of\nregular expressions. However, this completeness result does not\naccount for residuation. *}\n\nclass equational_action_algebra = equational_residuated_join_semilattice + dioid_one_zero + star_op +\n  assumes star_ax: \"1 + x\\<^sup>\\<star> \\<cdot> x\\<^sup>\\<star> + x \\<le> x\\<^sup>\\<star>\"\n  and star_subdist: \"x\\<^sup>\\<star> \\<le> (x + y)\\<^sup>\\<star>\"\n  and right_pure_induction: \"(x \\<rightarrow> x)\\<^sup>\\<star> \\<le> x \\<rightarrow> x\"\nbegin\n\ntext {* We now show that the equational axioms of action algebra\nsatisfy those based on the Galois connections. Since we can use our\ncorrespondence between the two variants of residuated semilattice, it\nremains to derive the second reflexive transitive closure axiom for\nthe star, essentially copying Pratt's proof step by step. We then\nprove a subclass statement. *}\n\nlemma star_rtc_2: \"1 + y \\<cdot> y + x \\<le> y \\<longrightarrow> x\\<^sup>\\<star> \\<le> y\"\nproof\n  assume \"1 + y \\<cdot> y + x \\<le> y\"\n  also have \"1 \\<le> y\"\n    by (metis add_lub calculation)\n  moreover have \"x \\<le> y\"\n    by (metis add_lub calculation)\n  moreover have \"y \\<cdot> y \\<le> y\"\n    by (metis add_lub calculation)\n  hence \"y \\<le> y \\<rightarrow> y\"\n    by (metis residual_r_galois)\n  moreover have \"x \\<le> y \\<rightarrow> y\"\n    by (metis calculation order_trans)\n  hence \"x\\<^sup>\\<star> \\<le> (y \\<rightarrow> y)\\<^sup>\\<star>\"\n    by (metis less_eq_def star_subdist)\n  hence \"x\\<^sup>\\<star> \\<le> y \\<rightarrow> y\"\n    by (metis order_trans right_pure_induction)\n  hence \"y \\<cdot> x\\<^sup>\\<star> \\<le> y\"\n    by (metis residual_r_galois)\n  ultimately show \"x\\<^sup>\\<star> \\<le> y\"\n    by (metis mult_isor mult_onel order_trans)\nqed\n\nsubclass action_algebra\n  by (unfold_locales, metis star_ax, metis star_rtc_2)\n\nend (* equational_action_algebra *)\n\ntext {*\nConversely, every action algebra satisfies the equational axioms of\nequational action algebras.\n\nBecause the subclass relation must be acyclic in Isabelle, we can only\nestablish this for the corresponding locales. Again this proof is\nbased on the residuated semilattice result.\n*}\n\nsublocale action_algebra \\<subseteq> equational_action_algebra\n  by (unfold_locales, metis star_rtc1, metis star_subdist, metis residual_r_pure_induction)\n\nsubsection {* Another Variant *}\n\ntext {* Finally we show that Pratt and Kozen's star axioms generate\nprecisely the same theory. *}\n\nclass action_algebra_var = equational_residuated_join_semilattice + dioid_one_zero + star_op +\n  assumes star_unfold': \"1 + x \\<cdot> x\\<^sup>\\<star> \\<le> x\\<^sup>\\<star>\"\n  and star_inductl': \"z + x \\<cdot> y \\<le> y \\<longrightarrow> x\\<^sup>\\<star> \\<cdot> z \\<le> y\"\n  and star_inductr': \"z + y \\<cdot> x \\<le> y \\<longrightarrow> z \\<cdot> x\\<^sup>\\<star>  \\<le> y\"\nbegin\n\nsubclass kleene_algebra\n  by (unfold_locales, metis star_unfold', metis star_inductl', metis star_inductr')\n\nsubclass action_algebra\n  by (unfold_locales, metis add.commute less_eq_def order_refl star_ext star_plus_one star_trans_eq, metis add.assoc add.commute star_rtc_least)\n\nend\n\nsublocale action_algebra \\<subseteq> action_algebra_var\n  by (unfold_locales, metis star_unfoldl, metis star_inductl, metis star_inductr)\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/Kleene_Algebra/Action_Algebra.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8558511616741041, "lm_q2_score": 0.8333245953120233, "lm_q1q2_score": 0.7132018229493978}}
{"text": "(*  Title:      HOL/Examples/Induction_Schema.thy\n    Author:     Alexander Krauss, TU Muenchen\n*)\n\nsection \\<open>Examples of automatically derived induction rules\\<close>\n\ntheory Induction_Schema\nimports Main\nbegin\n\nsubsection \\<open>Some simple induction principles on nat\\<close>\n\nlemma nat_standard_induct: (* cf. Nat.thy *)\n  \"\\<lbrakk>P 0; \\<And>n. P n \\<Longrightarrow> P (Suc n)\\<rbrakk> \\<Longrightarrow> P x\"\nby induction_schema (pat_completeness, lexicographic_order)\n\nlemma nat_induct2:\n  \"\\<lbrakk> P 0; P (Suc 0); \\<And>k. P k ==> P (Suc k) ==> P (Suc (Suc k)) \\<rbrakk>\n  \\<Longrightarrow> P n\"\nby induction_schema (pat_completeness, lexicographic_order)\n\nlemma minus_one_induct:\n  \"\\<lbrakk>\\<And>n::nat. (n \\<noteq> 0 \\<Longrightarrow> P (n - 1)) \\<Longrightarrow> P n\\<rbrakk> \\<Longrightarrow> P x\"\nby induction_schema (pat_completeness, lexicographic_order)\n\ntheorem diff_induct: (* cf. Nat.thy *)\n  \"(!!x. P x 0) ==> (!!y. P 0 (Suc y)) ==>\n    (!!x y. P x y ==> P (Suc x) (Suc y)) ==> P m n\"\nby induction_schema (pat_completeness, lexicographic_order)\n\nlemma list_induct2': (* cf. List.thy *)\n  \"\\<lbrakk> P [] [];\n  \\<And>x xs. P (x#xs) [];\n  \\<And>y ys. P [] (y#ys);\n   \\<And>x xs y ys. P xs ys  \\<Longrightarrow> P (x#xs) (y#ys) \\<rbrakk>\n \\<Longrightarrow> P xs ys\"\nby induction_schema (pat_completeness, lexicographic_order)\n\ntheorem even_odd_induct:\n  assumes \"R 0\"\n  assumes \"Q 0\"\n  assumes \"\\<And>n. Q n \\<Longrightarrow> R (Suc n)\"\n  assumes \"\\<And>n. R n \\<Longrightarrow> Q (Suc n)\"\n  shows \"R n\" \"Q n\"\n  using assms\nby induction_schema (pat_completeness+, lexicographic_order)\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/Induction_Schema.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246035907932, "lm_q2_score": 0.8558511451289038, "lm_q1q2_score": 0.7132018162472702}}
{"text": "(*<*)\ntheory tmpl07\n  imports Main \"HOL-Data_Structures.Sorting\"\nbegin\n(*>*)\n\n\ntext {* \\ExerciseSheet{7}{25.~5.~2018} *}\n\n\ntext {* \\Exercise{Interval Lists}\n\n Sets of natural numbers can be implemented as lists of intervals, where\nan interval is simply a pair of numbers.  For example the set @{term \"{2, 3, 5,\n7, 8, 9::nat}\"} can be represented by the list @{term \"[(2, 3), (5, 5),\n(7::nat, 9::nat)]\"}.  A typical application is the list of free blocks of\ndynamically allocated memory. *}\n\ntext {* We introduce the type *}\n\ntype_synonym intervals = \"(nat*nat) list\"\n\ntext {* Next, define an \\emph{invariant}\nthat characterizes valid interval lists:\nFor efficiency reasons intervals should be sorted in ascending order, the lower\nbound of each interval should be less than or equal to the upper bound, and the\nintervals should be chosen as large as possible, i.e.\\ no two adjacent\nintervals should overlap or even touch each other.  It turns out to be\nconvenient to define @{term inv} in terms of a more general function\nsuch that the additional argument is a lower bound for the intervals in\nthe list:*}\n\nfun inv' :: \"nat \\<Rightarrow> intervals \\<Rightarrow> bool\" where\n  \"inv' _ _ \\<longleftrightarrow> undefined\"\n\ndefinition inv where \"inv = inv' 0\"\n\n\n\ntext {* To relate intervals back to sets define an \\emph{abstraction function}*}\n\nfun set_of :: \"intervals => nat set\"\nwhere\n  \"set_of _ = undefined\"\n\ntext \\<open>Define a function to add a single element to the interval list,\n  and show its correctness\\<close>\n\n\nfun add :: \"nat \\<Rightarrow> intervals \\<Rightarrow> intervals\"\n  where\n  \"add _ _ = undefined\"\n\nlemma add_correct:\n  assumes \"inv is\"\n  shows \"inv (add x is)\" \"set_of (add x is) = insert x (set_of is)\"\n  oops\n\ntext \\<open>Hints:\n  \\<^item> Sketch the different cases (position of element relative to the first interval of the list)\n    on paper first\n  \\<^item> In one case, you will also need information about the second interval of the list.\n    Do this case split via an auxiliary function! Otherwise, you may end up with a recursion equation of the form\n      \\<open>f (x#xs) = \\<dots> case xs of x'#xs' \\<Rightarrow> \\<dots> f (x'#xs') \\<dots>\\<close>\n    combined with \\<open>split: list.splits\\<close> this will make the simplifier loop!\n\n\\<close>\n\n\ntext \\<open>\\Exercise{Optimized Mergesort}\n\n  Import @{theory \"Sorting\"} for this exercise.\n  The @{const msort} function recomputes the length of the list in each iteration.\n  Implement an optimized version that has an additional parameter keeping track\n  of the length, and show that it is equal to the original @{const msort}.\n\\<close>\n\n(* Optimized mergesort *)\n\nfun msort2 :: \"nat \\<Rightarrow> 'a::linorder list \\<Rightarrow> 'a list\"\n  where \"msort2 _ _ = undefined\"\n\nlemma \"n = length xs \\<Longrightarrow> msort2 n xs = msort xs\"\n  oops\n\ntext \\<open>Hint:\n  Use @{thm [source] msort.simps} only when instantiated to a particular \\<open>xs\\<close>\n  (@{thm [source] msort.simps[of xs]}),\n  otherwise the simplifier will loop!\n\\<close>\n\n\n\ntext \\<open> \\NumHomework{Deletion from Interval Lists}{June 1}\n\n  Implement and prove correct a delete function.\n\n  Hints:\n    \\<^item> The correctness lemma is analogous to the one for add.\n    \\<^item> A monotonicity property on \\<open>inv'\\<close> may be useful, i.e.,\n      @{prop \\<open>inv' m is \\<Longrightarrow> inv' m' is\\<close>} if @{prop \\<open>m'\\<le>m\\<close>}\n    \\<^item> A bounding lemma, relating \\<open>m\\<close> and the elements of @{term \\<open>set_of is\\<close>}\n      if @{prop \\<open>inv' m is\\<close>}, may be useful.\n\\<close>\n\n\n\nfun del :: \"nat \\<Rightarrow> intervals \\<Rightarrow> intervals\"\nwhere\n  \"del _ _ = undefined\"\n\nlemma del_correct: \"Come up with a meaningful spec yourself\" oops\n\n\n\ntext \\<open> \\NumHomework{Addition of Interval to Interval List}{June 1}\n  For 3 \\<^bold>\\<open>bonus points\\<close>, implement and prove correct a function\n  to add a whole interval to an interval list. The runtime must\n  not depend on the size of the interval, e.g., iterating over the\n  interval and adding the elements separately is not allowed!\n\\<close>\n\nfun addi :: \"nat \\<Rightarrow> nat \\<Rightarrow> intervals \\<Rightarrow> intervals\"\nwhere\n  \"addi i j is = undefined\"\n\nlemma addi_correct:\n  assumes \"inv is\" \"i\\<le>j\"\n  shows \"inv (addi i j is)\" \"set_of (addi i j is) = {i..j} \\<union> (set_of is)\"\n  sorry\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/07/tmpl07.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8558511506439707, "lm_q2_score": 0.8333245953120233, "lm_q1q2_score": 0.7132018137577163}}
{"text": "(*  Title:      HOL/ex/Induction_Schema.thy\n    Author:     Alexander Krauss, TU Muenchen\n*)\n\nsection \\<open>Examples of automatically derived induction rules\\<close>\n\ntheory Induction_Schema\nimports Main\nbegin\n\nsubsection \\<open>Some simple induction principles on nat\\<close>\n\nlemma nat_standard_induct: (* cf. Nat.thy *)\n  \"\\<lbrakk>P 0; \\<And>n. P n \\<Longrightarrow> P (Suc n)\\<rbrakk> \\<Longrightarrow> P x\"\nby induction_schema (pat_completeness, lexicographic_order)\n\nlemma nat_induct2:\n  \"\\<lbrakk> P 0; P (Suc 0); \\<And>k. P k ==> P (Suc k) ==> P (Suc (Suc k)) \\<rbrakk>\n  \\<Longrightarrow> P n\"\nby induction_schema (pat_completeness, lexicographic_order)\n\nlemma minus_one_induct:\n  \"\\<lbrakk>\\<And>n::nat. (n \\<noteq> 0 \\<Longrightarrow> P (n - 1)) \\<Longrightarrow> P n\\<rbrakk> \\<Longrightarrow> P x\"\nby induction_schema (pat_completeness, lexicographic_order)\n\ntheorem diff_induct: (* cf. Nat.thy *)\n  \"(!!x. P x 0) ==> (!!y. P 0 (Suc y)) ==>\n    (!!x y. P x y ==> P (Suc x) (Suc y)) ==> P m n\"\nby induction_schema (pat_completeness, lexicographic_order)\n\nlemma list_induct2': (* cf. List.thy *)\n  \"\\<lbrakk> P [] [];\n  \\<And>x xs. P (x#xs) [];\n  \\<And>y ys. P [] (y#ys);\n   \\<And>x xs y ys. P xs ys  \\<Longrightarrow> P (x#xs) (y#ys) \\<rbrakk>\n \\<Longrightarrow> P xs ys\"\nby induction_schema (pat_completeness, lexicographic_order)\n\ntheorem even_odd_induct:\n  assumes \"R 0\"\n  assumes \"Q 0\"\n  assumes \"\\<And>n. Q n \\<Longrightarrow> R (Suc n)\"\n  assumes \"\\<And>n. R n \\<Longrightarrow> Q (Suc n)\"\n  shows \"R n\" \"Q n\"\n  using assms\nby induction_schema (pat_completeness+, lexicographic_order)\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/Induction_Schema.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245953120233, "lm_q2_score": 0.8558511469672594, "lm_q1q2_score": 0.7132018106938224}}
{"text": "(*  Title:       Infinite Sequences\n    Author:      Christian Sternagel <c-sterna@jaist.ac.jp>\n                 Ren\u00e9 Thiemann       <rene.thiemann@uibk.ac.at>\n    Maintainer:  Christian Sternagel and Ren\u00e9 Thiemann\n    License:     LGPL\n*)\n\n(*\nCopyright 2012 Christian Sternagel, Ren\u00e9 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*)\nsection \\<open>Infinite Sequences\\<close>\ntheory Seq\nimports\n  Main\n  \"HOL-Library.Infinite_Set\"\nbegin\n\ntext \\<open>Infinite sequences are represented by functions of type @{typ \"nat \\<Rightarrow> 'a\"}.\\<close>\ntype_synonym 'a seq = \"nat \\<Rightarrow> 'a\"\n\n\nsubsection \\<open>Operations on Infinite Sequences\\<close>\n\ntext \\<open>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}.\\<close>\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 \\<open>Special version for relations.\\<close>\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 \\<open>Extending a chain at the front.\\<close>\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 \\<open>Special version for relations.\\<close>\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 \\<open>A chain admits arbitrary transitive steps.\\<close>\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 \\<open>A chain admits arbitrary reflexive and transitive steps.\\<close>\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 \\<open>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.\\<close>\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  define \\<phi> where [simp]: \"\\<phi> i = (g ^^ i) (Suc n)\" for i\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 \\<open>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.\\<close>\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 \\<open>Predicates on Natural Numbers\\<close>\n\ntext \\<open>If some property holds for infinitely many natural numbers, obtain\nan index function that points to these numbers in increasing order.\\<close>\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 \\<open>Assembling Infinite Words from Finite Words\\<close>\n\ntext \\<open>Concatenate infinitely many non-empty words to an infinite word.\\<close>\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": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Evaluation/Abstract-Rewriting/Seq.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8558511396138365, "lm_q2_score": 0.8333245994514084, "lm_q1q2_score": 0.7132018081087317}}
{"text": "(*\n  File: Group.thy\n  Author: Bohua Zhan\n\n  Basics of group theory.\n*)\n\ntheory Group\n  imports AlgStructure Morphism\nbegin\n\nsection \\<open>Monoids\\<close>\n  \ndefinition is_monoid :: \"i \\<Rightarrow> o\" where [rewrite]:\n  \"is_monoid(G) \\<longleftrightarrow> is_mult_id(G) \\<and> is_times_assoc(G)\"\n\nlemma is_monoidD [forward]:\n  \"is_monoid(G) \\<Longrightarrow> is_mult_id(G)\"\n  \"is_monoid(G) \\<Longrightarrow> is_times_assoc(G)\" by auto2+\nsetup {* del_prfstep_thm_eqforward @{thm is_monoid_def} *}\n  \nlemma is_monoid_group_prop [forward]:\n  \"is_group_raw(H) \\<Longrightarrow> is_monoid(G) \\<Longrightarrow> eq_str_group(G,H) \\<Longrightarrow> is_monoid(H)\" by auto2\n\nML_file \"alg_monoid.ML\"\n  \nsection \\<open>Units and multiplicative inverse\\<close>\n\ndefinition units :: \"i \\<Rightarrow> i\" where [rewrite]:\n  \"units(G) = {x \\<in>. G. (\\<exists>y\\<in>.G. y *\\<^sub>G x = \\<one>\\<^sub>G \\<and> x *\\<^sub>G y = \\<one>\\<^sub>G)}\"\n\nlemma is_unitD1 [forward]: \"x \\<in> units(G) \\<Longrightarrow> x \\<in>. G\" by auto2\nlemma is_unitD2 [backward]: \"x \\<in> units(G) \\<Longrightarrow> \\<exists>y\\<in>.G. y *\\<^sub>G x = \\<one>\\<^sub>G \\<and> x *\\<^sub>G y = \\<one>\\<^sub>G\" by auto2\nlemma is_unitI [backward1, backward2]:\n  \"x \\<in>. G \\<Longrightarrow> y \\<in>. G \\<Longrightarrow> y *\\<^sub>G x = \\<one>\\<^sub>G \\<Longrightarrow> x *\\<^sub>G y = \\<one>\\<^sub>G \\<Longrightarrow> x \\<in> units(G)\" by auto2\nlemma unit_exists_invl [backward]: \"x \\<in> units(G) \\<Longrightarrow> \\<exists>y\\<in>.G. y *\\<^sub>G x = \\<one>\\<^sub>G\" by auto2\nlemma unit_exists_invr [backward]: \"x \\<in> units(G) \\<Longrightarrow> \\<exists>y\\<in>.G. x *\\<^sub>G y = \\<one>\\<^sub>G\" by auto2\nlemma one_is_unit [resolve]: \"is_monoid(G) \\<Longrightarrow> \\<one>\\<^sub>G \\<in> units(G)\" by auto2\nlemma units_group_fun [rewrite]:\n  \"is_group_raw(G) \\<Longrightarrow> is_group_raw(H) \\<Longrightarrow> eq_str_group(G,H) \\<Longrightarrow> units(G) = units(H)\" by auto2\nsetup {* del_prfstep_thm @{thm units_def} *}\n\ndefinition inv :: \"i \\<Rightarrow> i \\<Rightarrow> i\" where [rewrite]:\n  \"inv(G,x) = (THE y. y \\<in>. G \\<and> y *\\<^sub>G x = \\<one>\\<^sub>G \\<and> x *\\<^sub>G y = \\<one>\\<^sub>G)\"\nsetup {* register_wellform_data (\"inv(G,x)\", [\"x \\<in> units(G)\"]) *}\n\nlemma inv_unique [forward]:\n  \"is_monoid(G) \\<Longrightarrow> x \\<in>. G \\<Longrightarrow> y \\<in>. G \\<Longrightarrow> y' \\<in>. G \\<Longrightarrow>\n   y *\\<^sub>G x = \\<one>\\<^sub>G \\<Longrightarrow> x *\\<^sub>G y' = \\<one>\\<^sub>G \\<Longrightarrow> y = y'\"\n@proof @have \"y *\\<^sub>G x *\\<^sub>G y' = y *\\<^sub>G (x *\\<^sub>G y')\" @qed\n    \nlemma inv_equality [backward1, backward2]:\n  \"is_monoid(G) \\<Longrightarrow> x \\<in>. G \\<Longrightarrow> y \\<in>. G \\<Longrightarrow> y *\\<^sub>G x = \\<one>\\<^sub>G \\<Longrightarrow> x *\\<^sub>G y = \\<one>\\<^sub>G \\<Longrightarrow> inv(G,x) = y\"\n  \"is_monoid(G) \\<Longrightarrow> x \\<in>. G \\<Longrightarrow> y \\<in>. G \\<Longrightarrow> y *\\<^sub>G x = \\<one>\\<^sub>G \\<Longrightarrow> x *\\<^sub>G y = \\<one>\\<^sub>G \\<Longrightarrow> y = inv(G,x)\" by auto2+\n\nlemma inv_is_unit [typing]:\n  \"is_monoid(G) \\<Longrightarrow> x \\<in> units(G) \\<Longrightarrow> inv(G,x) \\<in> units(G)\" by auto2\n\nlemma invD [forward]:\n  \"is_monoid(G) \\<Longrightarrow> inv(G,\\<one>\\<^sub>G) = \\<one>\\<^sub>G\"\n  \"is_monoid(G) \\<Longrightarrow> x \\<in> units(G) \\<Longrightarrow> inv(G,x) *\\<^sub>G x = \\<one>\\<^sub>G\"\n  \"is_monoid(G) \\<Longrightarrow> x \\<in> units(G) \\<Longrightarrow> x *\\<^sub>G inv(G,x) = \\<one>\\<^sub>G\" by auto2+\nsetup {* del_prfstep_thm @{thm inv_def} *}\n  \nlemma inv_group_fun [rewrite]:\n  \"is_group_raw(H) \\<Longrightarrow> is_monoid(G) \\<Longrightarrow> x \\<in> units(G) \\<Longrightarrow> eq_str_group(G,H) \\<Longrightarrow>\n   inv(G,x) = inv(H,x)\" by auto2\n\nlemma unit_l_cancel [forward]:\n  \"is_monoid(G) \\<Longrightarrow> y \\<in>. G \\<Longrightarrow> z \\<in>. G \\<Longrightarrow> x *\\<^sub>G y = x *\\<^sub>G z \\<Longrightarrow> x \\<in> units(G) \\<Longrightarrow> y = z\"\n@proof\n  @have \"inv(G,x) *\\<^sub>G x *\\<^sub>G y = inv(G,x) *\\<^sub>G (x *\\<^sub>G y)\"\n  @have \"inv(G,x) *\\<^sub>G x *\\<^sub>G z = inv(G,x) *\\<^sub>G (x *\\<^sub>G z)\"\n@qed\n\nlemma unit_r_cancel [forward]:\n  \"is_monoid(G) \\<Longrightarrow> y \\<in>. G \\<Longrightarrow> z \\<in>. G \\<Longrightarrow> y *\\<^sub>G x = z *\\<^sub>G x \\<Longrightarrow> x \\<in> units(G) \\<Longrightarrow> y = z\"\n@proof\n  @have \"y *\\<^sub>G (x *\\<^sub>G inv(G,x)) = y *\\<^sub>G x *\\<^sub>G inv(G,x)\"\n  @have \"z *\\<^sub>G (x *\\<^sub>G inv(G,x)) = z *\\<^sub>G x *\\<^sub>G inv(G,x)\"\n@qed\n\nlemma unit_inv_inv [rewrite]:\n  \"is_monoid(G) \\<Longrightarrow> x \\<in> units(G) \\<Longrightarrow> inv(G, inv(G,x)) = x\"\n@proof @have \"inv(G,x) *\\<^sub>G x = \\<one>\\<^sub>G\" @qed\n\nlemma unit_inv_comm:\n  \"is_monoid(G) \\<Longrightarrow> y \\<in>. G \\<Longrightarrow> x \\<in> units(G) \\<Longrightarrow> x *\\<^sub>G y = \\<one>\\<^sub>G \\<Longrightarrow> y *\\<^sub>G x = \\<one>\\<^sub>G\" by auto2\nsetup {* fold del_prfstep_thm @{thms invD} *}\nsetup {* fold add_rewrite_rule @{thms invD} *}\n\nsection \\<open>Definition of groups\\<close>\n\ndefinition is_group :: \"i \\<Rightarrow> o\" where [rewrite]:\n  \"is_group(G) \\<longleftrightarrow> is_monoid(G) \\<and> carrier(G) = units(G)\"\n\nlemma is_groupD [forward]:\n  \"is_group(G) \\<Longrightarrow> is_monoid(G)\"\n  \"is_group(G) \\<Longrightarrow> carrier(G) = units(G)\" by auto2+\n\nlemma is_groupI [backward1]:\n  \"is_monoid(G) \\<Longrightarrow> unary_fun(carrier(G),f) \\<Longrightarrow> \\<forall>x\\<in>.G. f(x) *\\<^sub>G x = \\<one>\\<^sub>G \\<Longrightarrow> is_group(G)\" by auto2\nsetup {* del_prfstep_thm @{thm is_group_def} *}\n\nlemma inv_equality_group1 [backward]:\n  \"is_group(G) \\<Longrightarrow> x \\<in>. G \\<Longrightarrow> y \\<in>. G \\<Longrightarrow> y *\\<^sub>G x = \\<one>\\<^sub>G \\<Longrightarrow> inv(G,x) = y\"\n@proof @have \"inv(G,x) *\\<^sub>G x = \\<one>\\<^sub>G\" @qed\n\nlemma inv_equality_group2 [backward]:\n  \"is_group(G) \\<Longrightarrow> x \\<in>. G \\<Longrightarrow> y \\<in>. G \\<Longrightarrow> y *\\<^sub>G x = \\<one>\\<^sub>G \\<Longrightarrow> y = inv(G,x)\"\n@proof @have \"inv(G,x) *\\<^sub>G x = \\<one>\\<^sub>G\" @qed\n\nlemma inv_distrib_group:\n  \"is_group(G) \\<Longrightarrow> x \\<in>. G \\<Longrightarrow> y \\<in>. G \\<Longrightarrow>\n   inv(G, x *\\<^sub>G y) = inv(G,y) *\\<^sub>G inv(G,x) \\<and>\n   x \\<in> units(G) \\<and> y \\<in> units(G) \\<and> inv(G,y) \\<in>. G \\<and> inv(G,x) \\<in>. G\"\n@proof @have \"inv(G,y) *\\<^sub>G inv(G,x) *\\<^sub>G (x *\\<^sub>G y) = inv(G,y) *\\<^sub>G (inv(G,x) *\\<^sub>G x) *\\<^sub>G y\" @qed\n\nML_file \"alg_group.ML\"\n\nlemma inv_distrib_test:\n  \"is_group(G) \\<Longrightarrow> x \\<in>. G \\<Longrightarrow> y \\<in>. G \\<Longrightarrow> z \\<in>. G \\<Longrightarrow>\n   inv(G, x *\\<^sub>G y *\\<^sub>G z) = inv(G,z) *\\<^sub>G inv(G,y) *\\<^sub>G inv(G,x)\" by auto2\n\nlemma move_inv_r [rewrite]:\n  \"is_group(G) \\<Longrightarrow> x \\<in>. G \\<Longrightarrow> y \\<in>. G \\<Longrightarrow> z \\<in>. G \\<Longrightarrow> x *\\<^sub>G inv(G,y) = z \\<Longrightarrow> z *\\<^sub>G y = x\"\n@proof @have \"z *\\<^sub>G y *\\<^sub>G inv(G,y) = z\" @qed\n\nlemma move_inv_l [rewrite]:\n  \"is_group(G) \\<Longrightarrow> x \\<in>. G \\<Longrightarrow> y \\<in>. G \\<Longrightarrow> z \\<in>. G \\<Longrightarrow> inv(G,x) *\\<^sub>G y = z \\<Longrightarrow> x *\\<^sub>G z = y\"\n@proof @have \"z = inv(G,x) *\\<^sub>G (x *\\<^sub>G z)\" @qed\n\nsection \\<open>Subgroups\\<close>\n\ndefinition subset_mult_closed :: \"i \\<Rightarrow> i \\<Rightarrow> o\" where [rewrite]:\n  \"subset_mult_closed(G,H) \\<longleftrightarrow> (\\<forall>x\\<in>H. \\<forall>y\\<in>H. x *\\<^sub>G y \\<in> H)\"\n\nlemma subset_mult_closedD [typing]:\n  \"subset_mult_closed(G,H) \\<Longrightarrow> x \\<in> H \\<Longrightarrow> y \\<in> H \\<Longrightarrow> x *\\<^sub>G y \\<in> H\" by auto2\nsetup {* del_prfstep_thm_eqforward @{thm subset_mult_closed_def} *}\n\ndefinition subset_inv_closed :: \"i \\<Rightarrow> i \\<Rightarrow> o\" where [rewrite]:\n  \"subset_inv_closed(G,H) \\<longleftrightarrow> (\\<forall>x\\<in>H. inv(G,x) \\<in> H)\"\n\nlemma subset_inv_closedD [typing]:\n  \"subset_inv_closed(G,H) \\<Longrightarrow> x \\<in> H \\<Longrightarrow> inv(G,x) \\<in> H\" by auto2\nsetup {* del_prfstep_thm_eqforward @{thm subset_inv_closed_def} *}\n\ndefinition is_subgroup_set :: \"i \\<Rightarrow> i \\<Rightarrow> o\" where [rewrite]:\n  \"is_subgroup_set(G,H) \\<longleftrightarrow>\n    (is_group(G) \\<and> H \\<subseteq> carrier(G) \\<and> \\<one>\\<^sub>G \\<in> H \\<and> subset_mult_closed(G,H) \\<and> subset_inv_closed(G,H))\"\n\ndefinition subgroup :: \"i \\<Rightarrow> i \\<Rightarrow> i\" where [rewrite]:\n  \"subgroup(G,H) = Group(H, \\<one>\\<^sub>G, \\<lambda>x y. x *\\<^sub>G y)\"\nsetup {* register_wellform_data (\"subgroup(G,H)\", [\"is_subgroup_set(G,H)\"]) *}\n\nlemma subgroup_is_group_raw:\n  \"is_subgroup_set(G,H) \\<Longrightarrow> group_form(subgroup(G,H))\" by auto2\nsetup {* add_forward_prfstep_cond @{thm subgroup_is_group_raw} [with_term \"subgroup(?G,?H)\"] *}\n\nlemma subgroup_sel1:\n  \"carrier(subgroup(G,H)) = H\"\n  \"one(subgroup(G,H)) = \\<one>\\<^sub>G\" by auto2+\nsetup {* fold (fn th => add_forward_prfstep_cond th [with_term \"subgroup(?G,?H)\"]) @{thms subgroup_sel1} *}\n  \nlemma subgroup_sel2 [rewrite]:\n  \"\\<H> = subgroup(G,H) \\<Longrightarrow> x \\<in>. \\<H> \\<Longrightarrow> y \\<in>. \\<H> \\<Longrightarrow> is_subgroup_set(G,H) \\<Longrightarrow> x *\\<^sub>\\<H> y = x *\\<^sub>G y\" by auto2+\nsetup {* del_prfstep_thm @{thm subgroup_def} *}\n\nlemma subgroup_is_group:\n  \"is_subgroup_set(G,H) \\<Longrightarrow> \\<H> = subgroup(G,H) \\<Longrightarrow> is_group(\\<H>)\"\n@proof\n  @have \"is_monoid(\\<H>)\" @with\n    @have \"is_times_assoc(\\<H>)\" @with\n      @have \"\\<forall>x\\<in>H. \\<forall>y\\<in>H. \\<forall>z\\<in>H. (x *\\<^sub>\\<H> y) *\\<^sub>\\<H> z = x *\\<^sub>\\<H> (y *\\<^sub>\\<H> z)\" @with\n        @have \"(x *\\<^sub>G y) *\\<^sub>G z = x *\\<^sub>G (y *\\<^sub>G z)\" @end @end @end\n  @have \"\\<forall>x\\<in>H. inv(G,x) *\\<^sub>\\<H> x = \\<one>\\<^sub>\\<H>\"\n@qed\nsetup {* add_forward_prfstep_cond @{thm subgroup_is_group} [with_term \"subgroup(?G,?H)\"] *}\n\nlemma subgroup_inv [rewrite]:\n  \"is_subgroup_set(G,H) \\<Longrightarrow> \\<H> = subgroup(G,H) \\<Longrightarrow> x \\<in> units(\\<H>) \\<Longrightarrow>\n   inv(\\<H>,x) = inv(G,x)\" by auto2\n\nlemma subgroup_non_empty [resolve]: \"\\<not>is_subgroup_set(G,\\<emptyset>)\"\n@proof @contradiction @have \"\\<one>\\<^sub>G \\<in> \\<emptyset>\" @qed\n\nsection \\<open>Direct products\\<close>\n  \ndefinition group_prod :: \"i \\<Rightarrow> i \\<Rightarrow> i\"  (infixr \"\\<times>\\<^sub>G\" 80) where [rewrite]:\n  \"G \\<times>\\<^sub>G H = Group(carrier(G)\\<times>carrier(H), \\<langle>\\<one>\\<^sub>G,\\<one>\\<^sub>H\\<rangle>, \\<lambda>x y. \\<langle>fst(x) *\\<^sub>G fst(y), snd(x) *\\<^sub>H snd(y)\\<rangle>)\"\n\nlemma group_prod_is_group_raw [forward]:\n  \"is_group_raw(G) \\<Longrightarrow> is_group_raw(H) \\<Longrightarrow> group_form(G \\<times>\\<^sub>G H)\" by auto2\n\nlemma group_prod_sel1:\n  \"carrier(G \\<times>\\<^sub>G H) = carrier(G) \\<times> carrier(H)\"\n  \"one(G \\<times>\\<^sub>G H) = \\<langle>\\<one>\\<^sub>G,\\<one>\\<^sub>H\\<rangle>\" by auto2+\nsetup {* fold (fn th => add_forward_prfstep_cond th [with_term \"?G \\<times>\\<^sub>G ?H\"]) @{thms group_prod_sel1} *}\n\nlemma group_prod_sel2 [rewrite]:\n  \"K = G \\<times>\\<^sub>G H \\<Longrightarrow> is_group_raw(G) \\<Longrightarrow> is_group_raw(H) \\<Longrightarrow> x \\<in>. K \\<Longrightarrow> y \\<in>. K \\<Longrightarrow>\n   x *\\<^sub>K y = \\<langle>fst(x) *\\<^sub>G fst(y), snd(x) *\\<^sub>H snd(y)\\<rangle>\" by auto2\nsetup {* del_prfstep_thm @{thm group_prod_def} *}\n\nlemma group_prod_is_monoid [forward]:\n  \"is_monoid(G) \\<Longrightarrow> is_monoid(H) \\<Longrightarrow> is_monoid(G \\<times>\\<^sub>G H)\"\n@proof\n  @let \"K = G \\<times>\\<^sub>G H\"\n  @have \"is_times_assoc(K)\" @with\n    @have \"\\<forall>x\\<in>.K. \\<forall>y\\<in>.K. \\<forall>z\\<in>.K. (x *\\<^sub>K y) *\\<^sub>K z = x *\\<^sub>K (y *\\<^sub>K z)\" @with\n      @have \"(fst(x) *\\<^sub>G fst(y)) *\\<^sub>G fst(z) = fst(x) *\\<^sub>G (fst(y) *\\<^sub>G fst(z))\"\n      @have \"(snd(x) *\\<^sub>H snd(y)) *\\<^sub>H snd(z) = snd(x) *\\<^sub>H (snd(y) *\\<^sub>H snd(z))\"\n    @end\n  @end\n@qed\n\nlemma group_prod_is_group [forward]:\n  \"is_group(G) \\<Longrightarrow> is_group(H) \\<Longrightarrow> is_group(G \\<times>\\<^sub>G H)\"\n@proof\n  @let \"K = G \\<times>\\<^sub>G H\"\n  @have \"\\<forall>x\\<in>.K. \\<langle>inv(G,fst(x)), inv(H,snd(x))\\<rangle> *\\<^sub>K x = \\<one>\\<^sub>K\"\n@qed\n\nlemma group_prod_inv [rewrite]:\n  \"is_group(G) \\<Longrightarrow> is_group(H) \\<Longrightarrow> K = G \\<times>\\<^sub>G H \\<Longrightarrow> \\<langle>x,y\\<rangle> \\<in> units(K) \\<Longrightarrow>\n   inv(K, \\<langle>x,y\\<rangle>) = \\<langle>inv(G,x), inv(H,y)\\<rangle>\" by auto2\n\nsection \\<open>Homomorphisms and Isomorphisms\\<close>\n\ndefinition is_group_hom :: \"i \\<Rightarrow> o\" where [rewrite]:\n  \"is_group_hom(f) \\<longleftrightarrow> (let S = source_str(f) in let T = target_str(f) in\n    is_morphism(f) \\<and> is_group(S) \\<and> is_group(T) \\<and> (\\<forall>x\\<in>.S. \\<forall>y\\<in>.S. f`(x *\\<^sub>S y) = f`x *\\<^sub>T f`y))\"\n  \nlemma is_group_homD1 [forward]:\n  \"is_group_hom(f) \\<Longrightarrow> is_morphism(f) \\<and> is_group(source_str(f)) \\<and> is_group(target_str(f))\" by auto2\n\nlemma is_group_homD2 [rewrite]:\n  \"is_group_hom(f) \\<Longrightarrow> G = source_str(f) \\<Longrightarrow> H = target_str(f) \\<Longrightarrow> x \\<in>. G \\<Longrightarrow> y \\<in>. G \\<Longrightarrow>\n   f ` (x *\\<^sub>G y) = f`x *\\<^sub>H f`y\" by auto2\nsetup {* del_prfstep_thm_eqforward @{thm is_group_hom_def} *}\n\ndefinition group_hom_space :: \"i \\<Rightarrow> i \\<Rightarrow> i\" (infix \"\\<rightharpoonup>\\<^sub>G\" 60) where [rewrite]:\n  \"G \\<rightharpoonup>\\<^sub>G H = {f \\<in> G \\<rightharpoonup> H. is_group_hom(f)}\"\n\nlemma group_hom_spaceD [forward]:\n  \"f \\<in> G \\<rightharpoonup>\\<^sub>G H \\<Longrightarrow> f \\<in> G \\<rightharpoonup> H \\<and> is_group_hom(f)\" by auto2\n\nlemma group_hom_spaceI [typing, backward]:\n  \"mor_form(f) \\<Longrightarrow> is_group_hom(f) \\<Longrightarrow> f \\<in> source_str(f) \\<rightharpoonup>\\<^sub>G target_str(f)\" by auto2\nsetup {* del_prfstep_thm @{thm group_hom_space_def} *}\n\nlemma group_hom_compose:\n  \"is_group_hom(f) \\<Longrightarrow> is_group_hom(g) \\<Longrightarrow> target_str(f) = source_str(g) \\<Longrightarrow>\n   is_group_hom(g \\<circ>\\<^sub>m f)\" by auto2\nsetup {* add_forward_prfstep_cond @{thm group_hom_compose} [with_term \"?g \\<circ>\\<^sub>m ?f\"] *}\n\nlemma group_hom_one [rewrite]:\n  \"is_group_hom(f) \\<Longrightarrow> G = source_str(f) \\<Longrightarrow> H = target_str(f) \\<Longrightarrow> f ` \\<one>\\<^sub>G = \\<one>\\<^sub>H\"\n@proof @have \"f ` (\\<one>\\<^sub>G *\\<^sub>G \\<one>\\<^sub>G) *\\<^sub>H \\<one>\\<^sub>H = f ` \\<one>\\<^sub>G *\\<^sub>H f ` \\<one>\\<^sub>G\" @qed\n\nlemma group_hom_inv [rewrite]:\n  \"is_group_hom(f) \\<Longrightarrow> G = source_str(f) \\<Longrightarrow> H = target_str(f) \\<Longrightarrow>\n   x \\<in> units(G) \\<Longrightarrow> f`(inv(G,x)) = inv(H,f`x)\"\n@proof @have \"f ` (inv(G,x) *\\<^sub>G x) = \\<one>\\<^sub>H\" @qed\n\ndefinition is_group_iso :: \"i \\<Rightarrow> o\" where [rewrite]:\n  \"is_group_iso(f) \\<longleftrightarrow> (is_group_hom(f) \\<and> bijective(f))\"\n\ndefinition group_iso_space :: \"i \\<Rightarrow> i \\<Rightarrow> i\"  (infix \"\\<cong>\\<^sub>G\" 60) where [rewrite]:\n  \"group_iso_space(G,H) = {f \\<in> mor_space(G,H). is_group_iso(f)}\"\n\nlemma group_iso_spaceD [forward]:\n  \"f \\<in> G \\<cong>\\<^sub>G H \\<Longrightarrow> f \\<in> G \\<rightharpoonup> H \\<and> is_group_iso(f)\" by auto2\n\nlemma group_iso_spaceI [backward]:\n  \"mor_form(f) \\<Longrightarrow> is_group_iso(f) \\<Longrightarrow> f \\<in> source_str(f) \\<cong>\\<^sub>G target_str(f)\" by auto2\nsetup {* del_prfstep_thm @{thm group_iso_space_def} *}\n    \nlemma iso_refl [typing]: \"is_group(G) \\<Longrightarrow> id_mor(G) \\<in> G \\<cong>\\<^sub>G G\" by auto2\n\nlemma iso_trans [typing]:\n  \"is_group_iso(f) \\<Longrightarrow> is_group_iso(g) \\<Longrightarrow> target_str(f) = source_str(g) \\<Longrightarrow>\n   g \\<circ>\\<^sub>m f \\<in> source_str(f) \\<cong>\\<^sub>G target_str(g)\"\n@proof\n  @have (@rule) \"\\<forall>y\\<in>target(f). \\<exists>x\\<in>source(f). f`x = y\"\n  @have (@rule) \"\\<forall>y\\<in>target(g). \\<exists>x\\<in>source(g). g`x = y\"\n@qed\n\nlemma iso_sym [typing]:\n  \"is_group_iso(f) \\<Longrightarrow> inverse_mor(f) \\<in> target_str(f) \\<cong>\\<^sub>G source_str(f)\"\n@proof\n  @let \"g = inverse_mor(f)\"\n  @have (@rule) \"\\<forall>y\\<in>target(f). \\<exists>x\\<in>source(f). f`x = y\"\n  @have (@rule) \"\\<forall>y\\<in>target(g). \\<exists>x\\<in>source(g). g`x = y\"\n@qed\n\nsection \\<open>Image of a homomorphism\\<close>\n  \nlemma image_is_subgroup:\n  \"is_group_hom(f) \\<Longrightarrow> H = target_str(f) \\<Longrightarrow> is_subgroup_set(H, image(f))\"\n@proof\n  @let \"G = source_str(f)\"\n  @have \"f ` \\<one>\\<^sub>G = \\<one>\\<^sub>H\"\n  @have \"subset_mult_closed(H, image(f))\" @with\n    @have \"\\<forall>x\\<in>image(f). \\<forall>y\\<in>image(f). x *\\<^sub>H y \\<in> image(f)\" @with\n      @obtain \"x'\\<in>source(f)\" where \"f`x' = x\"\n      @obtain \"y'\\<in>source(f)\" where \"f`y' = y\"\n      @have \"f`(x' *\\<^sub>G y') = x *\\<^sub>H y\"\n    @end\n  @end\n  @have \"subset_inv_closed(H, image(f))\" @with\n    @have \"\\<forall>x\\<in>image(f). inv(H,x) \\<in> image(f)\" @with\n      @obtain \"x'\\<in>source(f)\" where \"f`x' = x\"\n      @have \"f`(inv(G,x')) = inv(H,x)\"\n    @end\n  @end\n@qed\nsetup {* add_forward_prfstep_cond @{thm image_is_subgroup} [with_term \"image(?f)\"] *}\n\ndefinition image_subgroup :: \"i \\<Rightarrow> i\" where image_subgroup_def [rewrite_bidir]:\n  \"image_subgroup(f) = subgroup(target_str(f), image(f))\"\n\ndefinition group_mor_restrict_image :: \"i \\<Rightarrow> i\" where [rewrite]:\n  \"group_mor_restrict_image(f) = Mor(source_str(f), image_subgroup(f), \\<lambda>x. f`x)\"\n\nlemma group_mor_restrict_image_is_mor [typing]:\n  \"is_group_hom(f) \\<Longrightarrow> group_mor_restrict_image(f) \\<in> source_str(f) \\<rightharpoonup>\\<^sub>G image_subgroup(f)\" by auto2\n  \nlemma group_mor_restrict_image_eval [rewrite]:\n  \"is_group_hom(f) \\<Longrightarrow> f' = group_mor_restrict_image(f) \\<Longrightarrow> x \\<in> source(f') \\<Longrightarrow> f'`x = f`x\" by auto2\nsetup {* del_prfstep_thm @{thm group_mor_restrict_image_def} *}\n  \nlemma group_mor_factorize [rewrite_back]:\n  \"mor_form(f) \\<Longrightarrow> is_group_hom(f) \\<Longrightarrow>\n   f = inj_mor(image_subgroup(f), target_str(f)) \\<circ>\\<^sub>m group_mor_restrict_image(f)\" by auto2\n  \nlemma group_mor_inj_restrict_image_bij [typing]:\n  \"is_group_hom(f) \\<Longrightarrow> injective(f) \\<Longrightarrow>\n   group_mor_restrict_image(f) \\<in> source_str(f) \\<cong>\\<^sub>G image_subgroup(f)\" 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/Group.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8558511396138365, "lm_q2_score": 0.8333245973817158, "lm_q1q2_score": 0.713201806337383}}
{"text": "theory MList\nimports Main Utils\nbegin\n\nfun valid_map :: \"('a::linorder \\<times> 'b) list \\<Rightarrow> bool\" where\n  \"valid_map x = (let y = map fst x in\n                  (List.distinct y \\<and> List.sorted y))\"\n\ndefinition empty :: \"('a::linorder \\<times> 'b) list\" where\n  \"empty = Nil\"\n\nlemma valid_empty : \"valid_map empty\"\n  by (simp add:MList.empty_def)\n\nfun insert :: \"'a::linorder \\<Rightarrow> 'b \\<Rightarrow> ('a \\<times> 'b) list \\<Rightarrow> ('a \\<times> 'b) list\" where\n  \"insert a b Nil = Cons (a, b) Nil\" |\n  \"insert a b (Cons (x, y) z) =\n    (if a < x\n     then (Cons (a, b) (Cons (x, y) z))\n     else (if a > x\n           then (Cons (x, y) (insert a b z))\n           else (Cons (x, b) z)))\"\n\nlemma insert_length : \"length (insert a b c) \\<le> (length c + 1)\"\n  apply (induction c)\n  by auto\n\nlemma insert_in_middle : \"x < a \\<Longrightarrow> valid_map ((a, b) # z)\n                            \\<Longrightarrow> valid_map ((x, y) # (a, c) # z)\"\n  by auto\n\nlemma remove_from_middle : \"valid_map ((x, y) # (a, b) # z) \\<Longrightarrow> x < a\"\n  by auto\n\nlemma sublist_valid : \"valid_map ((x, y) # c) \\<Longrightarrow>\n                       valid_map c\"\n  by simp\n\nlemma insert_valid_aux :\n  \"x < a \\<Longrightarrow>\n   valid_map ((x, y) # c) \\<Longrightarrow>\n   valid_map (MList.insert a b c) \\<Longrightarrow>\n   valid_map ((x, y) # MList.insert a b c)\"\n  apply (induction c arbitrary: a b x y)\n  apply auto[1]\n  by (metis (no_types, opaque_lifting) insert.simps(2)\n            insert_in_middle prod.collapse remove_from_middle)\n\nlemma insert_valid_aux2 :\n  \"(\\<And>a b. valid_map c \\<Longrightarrow> valid_map (MList.insert a b c)) \\<Longrightarrow>\n    valid_map ((x, y) # c) \\<Longrightarrow>\n    x < a \\<Longrightarrow>\n    valid_map ((x, y) # MList.insert a b c)\"\n  by (smt (verit, best) insert.elims insert_in_middle remove_from_middle sublist_valid)\n\nlemma insert_valid_aux3 :\n  \"(\\<And>a b. valid_map c \\<Longrightarrow> valid_map (MList.insert a b c)) \\<Longrightarrow>\n   valid_map ((x, y) # c) \\<Longrightarrow> valid_map (MList.insert a b ((x, y) # 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_map c \\<Longrightarrow> valid_map (MList.insert a b c)\"\n  apply (induction c arbitrary:a b)\n  apply simp\n  by (metis insert_valid_aux3 old.prod.exhaust)\n\nlemma insert_replaces_value :\n  \"valid_map m \\<Longrightarrow> MList.insert k v1 (MList.insert k v2 m) = MList.insert k v1 m\"\nproof (induction m)\n  case Nil\n  then show ?case\n    by simp\nnext\n  case (Cons head rest)\n  then obtain hK hV where \"head = (hK, hV)\"\n    by fastforce\n  then show ?case\n    using Cons.IH Cons.prems by force\nqed\n\nlemma insert_swap :\n  \"\\<lbrakk> valid_map m\n   ; k1 \\<noteq> k2\n   \\<rbrakk> \\<Longrightarrow> MList.insert k1 v1 (MList.insert k2 v2 m) = MList.insert k2 v2 (MList.insert k1 v1 m)\"\nproof (induction m)\n  case Nil\n  then show ?case\n    by (simp add: not_less_iff_gr_or_eq)\nnext\n  case (Cons head rest)\n  then obtain hK hV where pHead: \"head = (hK, hV)\"\n    using prod.exhaust_sel by blast\n  then show ?case\n  proof (cases rule: linorder_cases[of k2 hK])\n    case less\n    then show ?thesis\n      using Cons.prems(2) pHead by fastforce\n  next\n    case equal\n    then show ?thesis\n      using Cons.prems(2) pHead by auto\n  next\n    case greater\n    then show ?thesis\n      using Cons.IH Cons.prems(1) Cons.prems(2) pHead by auto\n  qed\nqed\n\nfun delete :: \"'a::linorder \\<Rightarrow> ('a \\<times> 'b) list \\<Rightarrow> ('a \\<times> 'b) list\" where\n  \"delete a Nil = Nil\" |\n  \"delete a (Cons (x, y) z) =\n    (if a = x\n     then z\n     else (if a > x\n           then (Cons (x, y) (delete a z))\n           else (Cons (x, y) z)))\"\n\nlemma delete_length : \"length (delete a b) \\<le> length b\"\n  apply (induction b)\n  by auto\n\nlemma delete_valid_aux :\n  \"valid_map (a # c) \\<Longrightarrow> valid_map (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_map c \\<Longrightarrow> valid_map (delete a c)) \\<Longrightarrow>\n   valid_map (b # c) \\<Longrightarrow> valid_map (delete a (b # c))\"\n  apply (cases \"b\")\n  apply (simp only:delete.simps)\n  by (smt delete_valid_aux sublist_valid)\n\ntheorem delete_valid : \"valid_map c \\<Longrightarrow> valid_map (MList.delete a c)\"\n  apply (induction c arbitrary: a)\n  apply auto[1]\n  using delete_valid_aux2 by blast\n\nlemma delete_step :\n  \"valid_map ((k, v) # t) \\<Longrightarrow>\n   \\<not> k2 = k \\<Longrightarrow>\n   MList.delete k2 ((k, v) # t) = ((k, v)#(MList.delete k2 t))\"\n  apply (induction t)\n  by auto\n\nfun lookup :: \"'a::linorder \\<Rightarrow> ('a \\<times> 'b) list \\<Rightarrow> 'b option\" where\n  \"lookup a Nil = None\" |\n  \"lookup a (Cons (x, y) z) =\n    (if a = x\n     then Some y\n     else (if a > x\n           then lookup a z\n           else None))\"\n\nlemma lookup_empty : \"MList.lookup y MList.empty = None\"\n  by (simp add: MList.empty_def)\n\nlemma insert_existing_length : \"MList.lookup k l = Some a \\<Longrightarrow>\n                                length (MList.insert k v l) = length l\"\n  apply (induction l)\n  apply simp\n  using not_less_iff_gr_or_eq by fastforce\n\nlemma delete_lookup_None_aux :\n  \"valid_map ((c, d) # b) \\<Longrightarrow> lookup c b = None\"\n  by (metis lookup.elims order.asym remove_from_middle)\n\nlemma delete_lookup_None_aux2 :\n  \"(valid_map b \\<Longrightarrow> lookup a (delete a b) = None) \\<Longrightarrow>\n   valid_map ((c, d) # b) \\<Longrightarrow> lookup a (delete a ((c, d) # b)) = None\"\n  apply (cases \"a > c\")\n  apply auto[1]\n  apply (cases \"a = c\")\n  apply (simp only:delete.simps lookup.simps)\n  apply (simp add: delete_lookup_None_aux)\n  by auto\n\ntheorem delete_lookup_None : \"valid_map b \\<Longrightarrow>\n                              MList.lookup a (MList.delete a b) = None\"\n  apply (induction b)\n  apply simp\n  using delete_lookup_None_aux2 by fastforce\n\ntheorem insert_lookup_Some : \"MList.lookup a (MList.insert a b c) = Some b\"\n  apply (induction c)\n  apply simp\n  by force\n\ntheorem insert_lookup_different : \"a \\<noteq> b \\<Longrightarrow> MList.lookup a (MList.insert b c d) = MList.lookup a d\"\n  apply (induction d)\n  apply simp\n  by force\n\nlemma different_delete_lookup_aux :\n  \"(valid_map c \\<Longrightarrow> a \\<noteq> b \\<Longrightarrow> lookup a (delete b c) = lookup a c) \\<Longrightarrow>\n   valid_map ((x, y) # c) \\<Longrightarrow>\n   a \\<noteq> b \\<Longrightarrow> lookup a (delete b ((x, y) # c)) = lookup a ((x, y) # c)\"\n  by (metis delete.simps(2) delete_lookup_None_aux delete_valid insert_in_middle lookup.simps(2) not_less_iff_gr_or_eq)\n\ntheorem different_delete_lookup :\n  \"valid_map c \\<Longrightarrow> a \\<noteq> b \\<Longrightarrow>\n   MList.lookup a (MList.delete b c) = MList.lookup a c\"\n  apply (induction c)\n  apply simp\n  by (metis different_delete_lookup_aux old.prod.exhaust)\n\nfun unionWith :: \"('b \\<Rightarrow> 'b \\<Rightarrow> 'b) \\<Rightarrow> ('a \\<times> 'b) list \\<Rightarrow>\n                  ('a \\<times> 'b) list \\<Rightarrow> (('a::linorder) \\<times> 'b) list\" where\n\"unionWith f (Cons (x, y) t) (Cons (x2, y2) t2) =\n  (if x < x2\n   then Cons (x, y) (unionWith f t (Cons (x2, y2) t2))\n   else (if x > x2\n         then Cons (x2, y2) (unionWith f (Cons (x, y) t) t2)\n         else Cons (x, f y y2) (unionWith f t t2)))\" |\n\"unionWith f Nil l = l\" |\n\"unionWith f l Nil = l\"\n\nlemma unionWithMonotonic1 :\n  \"x < x2 \\<Longrightarrow> fst ( hd ( unionWith f ((x, y) # t) ((x2, y2) # t2) ) ) = x\"\n  by simp\n\nlemma insert_before :\n  \"valid_map c \\<Longrightarrow> x < fst ( hd ( c ) ) \\<Longrightarrow> valid_map ((x, y) # c)\"\n  by (metis insert.simps(1) insert_in_middle insert_valid list.exhaust list.sel(1) prod.collapse)\n\nlemma insert_before_union :\n  \"x < x2 \\<Longrightarrow>\n   valid_map ((x, y) # t) \\<Longrightarrow>\n   valid_map ((x2, y2) # t2) \\<Longrightarrow>\n   x < fst ( hd ( unionWith f t ((x2, y2) # t2) ) )\"\n  apply (induction t)\n  apply auto[1]\n  by auto\n\nlemma insert_before_union2 :\n  \"x2 < x \\<Longrightarrow>\n   valid_map ((x, y) # t) \\<Longrightarrow>\n   valid_map ((x2, y2) # t2) \\<Longrightarrow>\n   x2 < fst ( hd ( unionWith f ((x, y) # t) t2 ) )\"\n  apply (induction t2)\n  apply auto[1]\n  by force\n\nlemma insert_before_union3 :\n  \"valid_map ((x, y) # t) \\<Longrightarrow>\n   valid_map ((x, y2) # t2) \\<Longrightarrow>\n   (t \\<noteq> [] \\<or> t2 \\<noteq> []) \\<Longrightarrow>\n   x < fst ( hd ( unionWith f t t2 ) )\"\n  apply (induction t)\n  apply (metis list.collapse prod.collapse remove_from_middle unionWith.simps(2))\n  apply (induction t2)\n  apply auto[1]\n  by auto\n\nlemma unionWithValidLT_aux :\n  \"x < x2 \\<Longrightarrow>\n    (valid_map (unionWith f t ((x2, y2) # t2))) \\<Longrightarrow>\n    valid_map ((x, y) # t) \\<Longrightarrow>\n    valid_map ((x2, y2) # t2) \\<Longrightarrow>\n    valid_map ((x, y) # unionWith f t ((x2, y2) # t2))\"\n  by (meson insert_before insert_before_union)\n\nlemma unionWithValidLT :\n  \"x < x2 \\<Longrightarrow>\n   (valid_map t \\<Longrightarrow>\n    valid_map ((x2, y2) # t2) \\<Longrightarrow>\n    valid_map (unionWith f t ((x2, y2) # t2))) \\<Longrightarrow>\n   valid_map ((x, y) # t) \\<Longrightarrow>\n   valid_map ((x2, y2) # t2) \\<Longrightarrow>\n   valid_map (unionWith f ((x, y) # t) ((x2, y2) # t2))\"\n  apply (simp only:unionWith.simps sublist_valid)\n  by (meson unionWithValidLT_aux)\n\nlemma unionWithValidGT_aux :\n  \"x2 < x \\<Longrightarrow>\n   (valid_map (unionWith f ((x, y) # t) t2)) \\<Longrightarrow>\n   valid_map ((x, y) # t) \\<Longrightarrow>\n   valid_map ((x2, y2) # t2) \\<Longrightarrow>\n   valid_map ((x2, y2) # unionWith f ((x, y) # t) t2)\"\n  by (meson insert_before insert_before_union2)\n\nlemma unionWithValidGT :\n  \"x2 < x \\<Longrightarrow>\n   (valid_map ((x, y) # t) \\<Longrightarrow>\n    valid_map t2 \\<Longrightarrow> valid_map (unionWith f ((x, y) # t) t2)) \\<Longrightarrow>\n   valid_map ((x, y) # t) \\<Longrightarrow>\n   valid_map ((x2, y2) # t2) \\<Longrightarrow>\n   valid_map (unionWith f ((x, y) # t) ((x2, y2) # t2))\"\n  apply (simp only:unionWith.simps sublist_valid)\n  by (smt order.asym unionWithValidGT_aux)\n\nlemma unionWithValidEQ_aux :\n  \"(valid_map (unionWith f t t2)) \\<Longrightarrow>\n   valid_map ((x, y) # t) \\<Longrightarrow>\n   valid_map ((x, y2) # t2) \\<Longrightarrow>\n   valid_map ((x, f y y2) # unionWith f t t2)\"\n  by (metis insert.simps(1) insert_before insert_before_union3 insert_valid unionWith.simps(2))\n\nlemma unionWithValidEQ :\n  \"(valid_map t \\<Longrightarrow> valid_map t2 \\<Longrightarrow> valid_map (unionWith f t t2)) \\<Longrightarrow>\n   valid_map ((x, y) # t) \\<Longrightarrow>\n   valid_map ((x, y2) # t2) \\<Longrightarrow>\n   valid_map (unionWith f ((x, y) # t) ((x, y2) # t2))\"\n  apply (simp only:unionWith.simps sublist_valid)\n  by (smt order.asym unionWithValidEQ_aux)\n\ntheorem unionWithValid : \"valid_map a \\<Longrightarrow> valid_map b \\<Longrightarrow>\n                          valid_map (unionWith f a b)\"\n  apply (induction f a b rule:unionWith.induct)\n  apply (metis less_linear unionWithValidEQ unionWithValidGT unionWithValidLT)\n  by auto\n\ntheorem unionWithSym : \"valid_map a \\<Longrightarrow> valid_map b \\<Longrightarrow>\n                        unionWith f a b = unionWith (flip f) b a\"\n  apply (induction f a b rule:unionWith.induct)\n  apply auto[1]\n  apply (metis list.exhaust unionWith.simps(2) unionWith.simps(3))\n  by simp\n\nfun findWithDefault :: \"'b \\<Rightarrow> 'a \\<Rightarrow> (('a::linorder) \\<times> 'b) list \\<Rightarrow> 'b\" where\n\"findWithDefault d k l = (case lookup k l of\n                            None \\<Rightarrow> d\n                          | Some x \\<Rightarrow> x)\"\n\nlemma findWithDefault_step :\n  \"valid_map ((k, v) # tail) \\<Longrightarrow>\n   k2 \\<noteq> k \\<Longrightarrow>\n   findWithDefault d k2 ((k, v) # tail) = findWithDefault d k2 tail\"\n  apply simp\n  apply (induction tail)\n  by auto\n\nfun member :: \"'a \\<Rightarrow> ((('a::linorder) \\<times> 'b) list) \\<Rightarrow> bool\" where\n\"member k d = (lookup k d \\<noteq> None)\"\n\nlemma deleteNotMember: \"\\<lbrakk> \\<not> member k m \\<rbrakk> \\<Longrightarrow> delete k m = m\"\nproof (induction m)\n  case Nil\n  then show ?case\n    by simp\nnext\n  case (Cons headKeyVal rest)\n  obtain hK hV where \"headKeyVal = (hK, hV)\"\n    by fastforce\n  with Cons show ?case\n    using option.distinct(1) by force\nqed\n\nlemma equalMList: \"\\<lbrakk> valid_map m; valid_map n \\<rbrakk> \\<Longrightarrow> \\<forall>x. lookup x m = lookup x n \\<Longrightarrow> m = n\"\nproof (induction m arbitrary: n)\n  case Nil\n  then show ?case\n    by (metis list.exhaust lookup.simps(1) lookup.simps(2) old.prod.exhaust option.distinct(1))\nnext\n  case (Cons mHead mRest)\n  then show ?case\n  proof (induction n )\n    case Nil\n    then show ?case\n      by (metis lookup.simps(1) lookup.simps(2) old.prod.exhaust option.distinct(1))\n  next\n    case (Cons nHead nRest)\n    then show ?case\n      (* TODO: this takes a little long, simplify *)\n      by (metis delete.simps(2) delete_lookup_None_aux different_delete_lookup lookup.simps(2) not_None_eq option.inject order.asym prod.collapse sublist_valid)\n  qed\nqed\n\nlemma insertDeleted : \"\\<lbrakk> valid_map m; lookup k m = Some v \\<rbrakk> \\<Longrightarrow> insert k v (delete k m) = m\"\nproof (induction m)\n  case Nil\n  then show ?case\n    by simp\nnext\n  case (Cons headKeyVal rest)\n  obtain hK hV where headKeyVal: \"headKeyVal = (hK, hV)\"\n    by fastforce\n  then have 0: \"lookup hK rest = None\"\n    by (metis Cons.prems(1) delete_lookup_None_aux)\n  show ?case\n  proof (cases rule: linorder_cases[of hK k])\n    case less\n    with Cons headKeyVal show ?thesis\n      by (metis delete_step insert.simps(2) lookup.simps(2) order.asym sublist_valid)\n  next\n    case equal\n    with equal Cons headKeyVal 0  show ?thesis\n      by (smt (verit, best) delete_valid different_delete_lookup equalMList insert_lookup_Some insert_lookup_different insert_valid)\n  next\n    case greater\n    then show ?thesis\n      by (metis Cons.prems(2) headKeyVal lookup.simps(2) not_less_iff_gr_or_eq option.discI)\n  qed\nqed\n\nlemma cons_eq_insert_rest :\n\"valid_map ((k,v) # rest) \\<Longrightarrow>\n(k,v) # rest = MList.insert k v rest\"\n  by (metis delete.simps(2) MList.lookup.simps(2) insertDeleted)\n\nsection \"As Maps\"\n\nlemma insertAsMap : \"valid_map mlist \\<Longrightarrow> map_of(insert k v mlist) = (map_of mlist) (k\\<mapsto>v)\"\nproof (induction mlist)\n  case Nil\n  then show ?case\n    by auto\nnext\n  case (Cons head rest)\n  obtain hK hV where \"head = (hK, hV)\"\n    by fastforce\n  then show ?case\n    using Cons.IH Cons.prems prod.sel(2) by fastforce\nqed\n\nlemma deleteAsMap : \"valid_map mlist \\<Longrightarrow> map_of (delete k mlist) = (map_of mlist)(k := None)\"\nproof (induction mlist)\n  case Nil\n  then show ?case\n    by simp\nnext\n  case (Cons head rest)\n  obtain hK hV where pHead: \"head = (hK, hV)\"\n    by fastforce\n  then show ?case\n  by (smt (z3) Cons.IH Cons.prems MList.member.simps delete.simps(2) deleteNotMember delete_lookup_None_aux delete_step fst_conv fun_upd_twist fun_upd_upd map_of.simps(2) sublist_valid)\nqed\n\nlemma lookupAsMap : \"valid_map mlist \\<Longrightarrow> lookup k mlist = (map_of mlist) k\"\nproof (induction mlist)\n  case Nil\n  then show ?case\n    by simp\nnext\n  case (Cons head rest)\n  obtain hK hV where \"head = (hK, hV)\"\n    by fastforce\n  then show ?case\n    by (smt (verit, ccfv_threshold) Cons.IH Cons.prems deleteNotMember delete_lookup_None delete_step list.inject lookup.simps(2) map_of_Cons_code(2) member.elims(1) sublist_valid)\nqed\n\nlemma MList_induct[consumes 1, case_names empty update]:\n  assumes \"valid_map m\"\n  assumes \"P []\"\n  assumes \"\\<And>k v m. valid_map m \\<Longrightarrow> \\<not> member k m \\<Longrightarrow> P m \\<Longrightarrow> P (insert k v m)\"\n  shows \"P m\"\n  using assms(1)\nproof(induction m)\n  case Nil\n  then show ?case by (simp add: assms(2))\nnext\n  case (Cons head rest)\n  then obtain hK hV where \"head = (hK, hV)\"\n    by fastforce\n  moreover have \"valid_map rest\"\n    using Cons.prems by auto\n  moreover have \"\\<not> member hK rest\"\n    by (metis Cons.prems MList.member.simps calculation(1) delete_lookup_None_aux)\n  moreover have \"P rest\"\n    using Cons.IH calculation(2) by blast\n  ultimately  show ?case using assms(3)\n    by (metis Cons.prems delete.simps(2) insertDeleted lookup.simps(2))\nqed\n\nlemma insertOverDeleted :\n  assumes \"valid_map m\"\n  shows \"insert k v m = insert k v (delete k m)\"\nusing assms proof (induction m rule: MList_induct)\n  case empty\n  then show ?case\n    by simp\nnext\n  case (update uK uV m)\n  then show ?case\n    by (smt (verit) delete_valid different_delete_lookup equalMList insert_lookup_Some insert_lookup_different insert_valid)\nqed\n\nsubsection \"keys\"\n\nfun keys :: \"('k \\<times> 'v) list \\<Rightarrow> 'k set\" where\n  \"keys m = set (map fst m)\"\n\nlemma keys_member_r: \"valid_map m \\<Longrightarrow> member k m \\<longleftrightarrow> k \\<in> keys m\"\nproof (induction m)\n  case Nil\n  then show ?case\n    by simp\nnext\n  case (Cons head rest)\n  moreover obtain hK hV where \"head = (hK, hV)\"\n    by fastforce\n  moreover have \"valid_map rest\"\n    using calculation by (metis local.Cons.prems sublist_valid)\n  moreover have \"hK < k \\<Longrightarrow> member k rest \\<Longrightarrow> k \\<in> keys rest\"\n    using calculation local.Cons.IH by blast\n  moreover have \"hK < k \\<Longrightarrow> k \\<in> keys rest \\<Longrightarrow> member k rest\"\n    using calculation local.Cons.IH by blast\n  ultimately show ?case\n    by (metis keys.elims list.set_map member.simps local.Cons.prems lookupAsMap map_of_eq_None_iff)\nqed\n\nsection \"MList with folds\"\n\ntext \"The following lemma is similar to the second case of the foldr definition, which states\n\n\\<^term>\\<open>foldr f (x # xs) = f x \\<circ> foldr f xs\\<close>\n\nInstead of working with Cons this lemma is expressed around MList.insert\"\n\nlemma foldr_insert:\n  assumes \"valid_map m\"\n  (* We require not having the key in the rest of the list, because otherwise the\n     insert would overwrite the value and the lemma would not hold *)\n  assumes \"\\<not> MList.member k m\"\n  (* We require the function to be commutative over composition because the insert function\n    can add the element in any order *)\n  assumes \"\\<forall>a b. f a \\<circ> f b = f b \\<circ> f a\"\n  shows \"foldr f (MList.insert k v m) = f (k, v) \\<circ> foldr f m\"\n  using assms(1) assms(2) proof (induction m)\n  case Nil\n  then show ?case by simp\nnext\n  case (Cons head rest)\n  then obtain hK hV where pHead: \"head = (hK, hV)\"\n    by force\n  then have \"hK \\<noteq> k\"\n    using local.Cons.prems(2) by force\n  then show ?case\n    by (smt (verit, best) Cons.IH Cons.prems(1) Cons.prems(2) MList.member.simps assms(3) foldr_Cons fun.map_comp insert.simps(2) lookup.simps(2) not_less_iff_gr_or_eq pHead sublist_valid)\nqed\n\ntext \"Similary, \\<^term>\\<open>foldl_insert\\<close> is defined to relate to the foldl second case definition\n      \\<^term>\\<open>foldl f a (x # xs) = foldl f (f a x) xs\\<close>\"\nlemma foldl_insert:\n  assumes \"valid_map m\"\n  assumes \"\\<not> MList.member k m\"\n  assumes \"\\<forall> a b z'. f (f z' a) b = f (f z' b) a\"\n  shows \"foldl f z (MList.insert k v m) = foldl f (f z (k, v)) m\"\n\nusing assms(1) assms(2) proof (induction m  arbitrary: z  )\n  case Nil\n  then show ?case\n    by simp\nnext\n  case (Cons head rest)\n  moreover obtain hK hV where \"head = (hK, hV)\"\n    by (meson Product_Type.prod.exhaust_sel)\n  moreover have \"hK \\<noteq> k\"\n    using calculation  by force\n  ultimately show ?case\n    using assms(3) by auto\nqed\n\nsection \"MList with filter\"\n\nlemma filterOnInsertNotP :\n  assumes \"valid_map m\"\n      and \"\\<forall> v. \\<not> P (k, v)\"\n  shows \"filter P (insert k v m) = filter P m\"\nusing assms proof (induction m)\n  case Nil\n  then show ?case by simp\nnext\n  case (Cons head rest)\n  then obtain hK hV where \"head = (hK, hV)\"\n    by (meson surj_pair)\n  then show ?case\n    using local.Cons.IH local.Cons.prems(1) local.Cons.prems(2) by auto\nqed\n\nlemma filterOnInsertP :\n  assumes \"valid_map m\"\n      and \"\\<forall> v. P (k, v)\"\n    shows \"filter P (insert k v m) = insert k v (filter P m)\"\nusing assms proof (induction m)\n  case Nil\n  then show ?case by simp\nnext\n  case (Cons head rest)\n  then obtain hK hV where pHead: \"head = (hK, hV)\"\n    by (meson surj_pair)\n  then show ?case\n  proof (cases rule: linorder_cases [of k hK])\n    case less\n    have \"(k, v) # filter P rest = insert k v (filter P rest)\"\n      by (smt (verit) filter.simps(2) insert.elims assms(2) less local.Cons.IH local.Cons.prems(1) order_less_trans pHead remove_from_middle sublist_valid)\n    then show ?thesis\n      by (simp add: assms(2) less pHead)\n  next\n    case equal\n    with Cons pHead show ?thesis by simp\n  next\n    case greater\n    with Cons pHead show ?thesis by auto\n   qed\n qed\n\nlemma lookupAsFilter :\n  assumes \"valid_map m\" and \"lookup k m = Some v\"\n  shows \"filter (\\<lambda>(eK, _). eK = k) m = [(k, v)]\"\n        (is \"?f m = _\")\n  using assms proof (induction m rule: MList_induct)\n  case empty\n  then show ?case\n    by simp\nnext\n  case (update uK uV m)\n  then show ?case\n  proof (cases \"uK = k\")\n    assume \"uK = k\"\n    moreover have \"uV = v\"\n      by (metis calculation Option.option.sel insert_lookup_Some local.update.prems)\n    moreover have \"lookup k m = None\"\n      using calculation local.update.hyps(2) by auto\n    moreover have \"?f m = []\"\n      by (smt (verit, del_insts) calculation(3) case_prodE filter_False lookupAsMap map_of_eq_Some_iff option.simps(3) update.hyps(1) valid_map.elims(2))\n    moreover have \"?f (insert uK uV m) = [(uK, uV)]\"\n      using calculation filterOnInsertP local.update.hyps(1) by fastforce\n    ultimately show ?thesis\n      by force\n  next\n    assume \"uK \\<noteq> k\"\n    moreover have \"?f (insert uK uV m) = ?f m\"\n      using calculation filterOnInsertNotP local.update.hyps(1) by fastforce\n    ultimately show ?thesis\n      by (metis insert_lookup_different local.update.IH local.update.prems)\n  qed\nqed\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/MList.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213691605412, "lm_q2_score": 0.7931059511841119, "lm_q1q2_score": 0.713098508718032}}
{"text": "section \\<open>Lexicographic Extension\\<close>\n\ntheory Lexicographic_Extension\n  imports\n    Matrix.Utility\n    Order_Pair\nbegin\n\ntext \\<open>\n  In this theory we define the lexicographic extension of an order pair, so that it generalizes\n  the existing notion @{const lex_prod} which is based on a single order only.\n\n  Our main result is that this extension yields again an order pair.\n\\<close>\n\nfun lex_two :: \"'a rel \\<Rightarrow> 'a rel \\<Rightarrow> 'b rel \\<Rightarrow> ('a \\<times> 'b) rel\" \n  where\n    \"lex_two s ns s2 = {((a1, b1), (a2, b2)) . (a1, a2) \\<in> s \\<or> (a1, a2) \\<in> ns \\<and> (b1, b2) \\<in> s2}\"\n\nlemma lex_two:\n  assumes compat: \"ns O s \\<subseteq> s\"\n    and SN_s: \"SN s\" \n    and SN_s2: \"SN s2\"\n  shows \"SN (lex_two s ns s2)\" (is \"SN ?r\")\nproof\n  fix f\n  assume \"\\<forall> i. (f i, f (Suc i)) \\<in> ?r\"\n  then have steps: \"\\<And> i. (f i, f (Suc i)) \\<in> ?r\" ..\n  let ?a = \"\\<lambda> i. fst (f i)\"\n  let ?b = \"\\<lambda> i. snd (f i)\"\n  {\n    fix i\n    from steps[of i]\n    have \"(?a i, ?a (Suc i)) \\<in> s \\<or> (?a i, ?a (Suc i)) \\<in> ns \\<and> (?b i, ?b (Suc i)) \\<in> s2\"\n      by (cases \"f i\", cases \"f (Suc i)\", auto)\n  }\n  note steps = this\n  have \"\\<exists> j. \\<forall> i \\<ge> j. (?a i, ?a (Suc i)) \\<in> ns - s\"\n    by (rule non_strict_ending[OF _ compat], insert steps SN_s, unfold SN_on_def, auto)\n  with steps obtain j where steps: \"\\<And> i. i \\<ge> j \\<Longrightarrow> (?b i, ?b (Suc i)) \\<in> s2\" by auto\n  obtain g where g: \"g = (\\<lambda> i. ?b (j + i))\" by auto\n  from steps have \"\\<And> i. (g i, g (Suc i)) \\<in> s2\" unfolding g by auto\n  with SN_s2 show False unfolding SN_defs by auto\nqed\n\nlemma lex_two_compat:\n  assumes compat1: \"ns1 O s1 \\<subseteq> s1\"\n    and compat1': \"s1 O ns1 \\<subseteq> s1\"\n    and trans1: \"s1 O s1 \\<subseteq> s1\"\n    and trans1': \"ns1 O ns1 \\<subseteq> ns1\"\n    and compat2: \"ns2 O s2 \\<subseteq> s2\"\n    and ns: \"(ab1, ab2) \\<in> lex_two s1 ns1 ns2\" \n    and s: \"(ab2, ab3) \\<in> lex_two s1 ns1 s2\"\n  shows \"(ab1, ab3) \\<in> lex_two s1 ns1 s2\"\nproof -\n  obtain a1 b1 where ab1: \"ab1 = (a1, b1)\" by force\n  obtain a2 b2 where ab2: \"ab2 = (a2, b2)\" by force\n  obtain a3 b3 where ab3: \"ab3 = (a3, b3)\" by force\n  note id = ab1 ab2 ab3\n  show ?thesis\n  proof (cases \"(a1, a2) \\<in> s1\")\n    case s1: True\n    show ?thesis \n    proof (cases \"(a2, a3) \\<in> s1\")\n      case s2: True\n      from trans1 s1 s2 show ?thesis unfolding id by auto\n    next\n      case False with s have \"(a2, a3) \\<in> ns1\" unfolding id by simp\n      from compat1' s1 this show ?thesis unfolding id by auto\n    qed\n  next\n    case False \n    with ns have ns: \"(a1, a2) \\<in> ns1\" \"(b1, b2) \\<in> ns2\" unfolding id by auto\n    show ?thesis\n    proof (cases \"(a2, a3) \\<in> s1\")\n      case s2: True\n      from compat1 ns(1) s2 show ?thesis unfolding id by auto\n    next\n      case False\n      with s have nss: \"(a2, a3) \\<in> ns1\" \"(b2, b3) \\<in> s2\" unfolding id by auto\n      from trans1' ns(1) nss(1) compat2 ns(2) nss(2)\n      show ?thesis unfolding id by auto\n    qed\n  qed\nqed\n\nlemma lex_two_compat':\n  assumes compat1: \"ns1 O s1 \\<subseteq> s1\"\n    and compat1': \"s1 O ns1 \\<subseteq> s1\"\n    and trans1: \"s1 O s1 \\<subseteq> s1\"\n    and trans1': \"ns1 O ns1 \\<subseteq> ns1\"\n    and compat2': \"s2 O ns2 \\<subseteq> s2\"\n    and s: \"(ab1, ab2) \\<in> lex_two s1 ns1 s2\" \n    and ns: \"(ab2, ab3) \\<in> lex_two s1 ns1 ns2\"\n  shows \"(ab1, ab3) \\<in> lex_two s1 ns1 s2\"\nproof -\n  obtain a1 b1 where ab1: \"ab1 = (a1, b1)\" by force\n  obtain a2 b2 where ab2: \"ab2 = (a2, b2)\" by force\n  obtain a3 b3 where ab3: \"ab3 = (a3, b3)\" by force\n  note id = ab1 ab2 ab3\n  show ?thesis\n  proof (cases \"(a1, a2) \\<in> s1\")\n    case s1: True\n    show ?thesis \n    proof (cases \"(a2, a3) \\<in> s1\")\n      case s2: True\n      from trans1 s1 s2 show ?thesis unfolding id by auto\n    next\n      case False with ns have \"(a2, a3) \\<in> ns1\" unfolding id by simp\n      from compat1' s1 this show ?thesis unfolding id by auto\n    qed\n  next\n    case False \n    with s have s: \"(a1, a2) \\<in> ns1\" \"(b1, b2) \\<in> s2\" unfolding id by auto\n    show ?thesis\n    proof (cases \"(a2, a3) \\<in> s1\")\n      case s2: True\n      from compat1 s(1) s2 show ?thesis unfolding id by auto\n    next\n      case False\n      with ns have nss: \"(a2, a3) \\<in> ns1\" \"(b2, b3) \\<in> ns2\" unfolding id by auto\n      from trans1' s(1) nss(1) compat2' s(2) nss(2)\n      show ?thesis unfolding id by auto\n    qed\n  qed\nqed\n\nlemma lex_two_compat2:\n  assumes \"ns1 O s1 \\<subseteq> s1\" \"s1 O ns1 \\<subseteq> s1\" \"s1 O s1 \\<subseteq> s1\" \"ns1 O ns1 \\<subseteq> ns1\" \"ns2 O s2 \\<subseteq> s2\"\n  shows \"lex_two s1 ns1 ns2 O lex_two s1 ns1 s2 \\<subseteq> lex_two s1 ns1 s2\"\n  using lex_two_compat[OF assms] by (intro subsetI, elim relcompE, fast)\n\nlemma lex_two_compat'2:\n  assumes \"ns1 O s1 \\<subseteq> s1\" \"s1 O ns1 \\<subseteq> s1\" \"s1 O s1 \\<subseteq> s1\" \"ns1 O ns1 \\<subseteq> ns1\" \"s2 O ns2 \\<subseteq> s2\"\n  shows \"lex_two s1 ns1 s2 O lex_two s1 ns1 ns2 \\<subseteq> lex_two s1 ns1 s2\"\n  using lex_two_compat'[OF assms] by (intro subsetI, elim relcompE, fast)\n\nlemma lex_two_refl:\n  assumes r1: \"refl ns1\" and r2: \"refl ns2\"\n  shows \"refl (lex_two s1 ns1 ns2)\"\n  using refl_onD[OF r1] and refl_onD[OF r2] by (intro refl_onI) auto\n\nlemma lex_two_order_pair:\n  assumes o1: \"order_pair s1 ns1\" and o2: \"order_pair s2 ns2\"\n  shows \"order_pair (lex_two s1 ns1 s2) (lex_two s1 ns1 ns2)\"\nproof -\n  interpret o1: order_pair s1 ns1 using o1.\n  interpret o2: order_pair s2 ns2 using o2.\n  note o1.trans_S o1.trans_NS o2.trans_S o2.trans_NS \n    o1.compat_NS_S o2.compat_NS_S o1.compat_S_NS o2.compat_S_NS\n  note this [unfolded trans_O_iff]\n  note o1.refl_NS o2.refl_NS\n  show ?thesis\n    by (unfold_locales, intro lex_two_refl, fact+, unfold trans_O_iff)\n      (rule lex_two_compat2 lex_two_compat'2;fact)+\nqed\n\nlemma lex_two_SN_order_pair:\n  assumes o1: \"SN_order_pair s1 ns1\" and o2: \"SN_order_pair s2 ns2\"\n  shows \"SN_order_pair (lex_two s1 ns1 s2) (lex_two s1 ns1 ns2)\"\nproof -\n  interpret o1: SN_order_pair s1 ns1 using o1.\n  interpret o2: SN_order_pair s2 ns2 using o2.\n  note o1.trans_S o1.trans_NS o2.trans_S o2.trans_NS o1.SN o2.SN\n    o1.compat_NS_S o2.compat_NS_S o1.compat_S_NS o2.compat_S_NS\n  note this [unfolded trans_O_iff]\n  interpret order_pair \"(lex_two s1 ns1 s2)\" \"(lex_two s1 ns1 ns2)\"\n    by(rule lex_two_order_pair, standard)\n  show ?thesis by(standard, rule lex_two; fact)\nqed\n\ntext \\<open>\n  In the unbounded lexicographic extension, there is no restriction on the lengths\n  of the lists. Therefore it is possible to compare lists of different lengths.\n  This usually results a non-terminating relation, e.g., $[1] > [0, 1] > [0, 0, 1] > \\ldots$\n\\<close>\n\nfun lex_ext_unbounded :: \"('a \\<Rightarrow> 'a \\<Rightarrow> bool \\<times> bool) \\<Rightarrow> 'a list \\<Rightarrow> 'a list \\<Rightarrow> bool \\<times> bool\"\n  where \"lex_ext_unbounded f [] [] = (False, True)\" |\n    \"lex_ext_unbounded f (_ # _) [] = (True, True)\" |\n    \"lex_ext_unbounded f [] (_ # _) = (False, False)\" |\n    \"lex_ext_unbounded f (a # as) (b # bs) =\n      (let (stri, nstri) = f a b in\n      if stri then (True, True)\n      else if nstri then lex_ext_unbounded f as bs\n      else (False, False))\"\n\nlemma lex_ext_unbounded_iff: \"(lex_ext_unbounded f xs ys) = (\n  ((\\<exists> i < length xs. i < length ys \\<and> (\\<forall> j < i. snd (f (xs ! j) (ys ! j))) \\<and> fst (f (xs ! i) (ys !i))) \\<or> \n  (\\<forall> i < length ys. snd (f (xs ! i) (ys ! i))) \\<and> length xs > length ys),\n  ((\\<exists> i < length xs. i < length ys \\<and> (\\<forall> j < i. snd (f (xs ! j) (ys ! j))) \\<and> fst (f (xs ! i) (ys !i))) \\<or> \n  (\\<forall> i < length ys. snd (f (xs ! i) (ys ! i))) \\<and> length xs \\<ge> length ys))\n  \" (is \"?lex xs ys = (?stri xs ys, ?nstri xs ys)\")\nproof (induct xs arbitrary: ys)\n  case Nil then show ?case by (cases ys, auto)\nnext\n  case (Cons a as)\n  note oCons = this\n  from oCons show ?case \n  proof (cases ys, simp)\n    case (Cons b bs)\n    show ?thesis \n    proof (cases \"f a b\")\n      case (Pair stri nstri)\n      show ?thesis\n      proof (cases stri)\n        case True\n        with Pair Cons show ?thesis by auto\n      next\n        case False        \n        show ?thesis \n        proof (cases nstri)\n          case False\n          with \\<open>\\<not> stri\\<close> Pair Cons show ?thesis by force\n        next\n          case True\n          with False Pair have f: \"f a b = (False, True)\" by auto\n          show ?thesis by (simp add: all_Suc_conv ex_Suc_conv Cons f oCons)\n        qed\n      qed\n    qed\n  qed\nqed\n\ndeclare lex_ext_unbounded.simps[simp del]\n\ntext \\<open>\n  The lexicographic extension of an order pair takes a natural number as maximum bound.\n  A decrease with lists of unequal lengths will never be successful if the length of the\n  second list exceeds this bound. The bound is essential to preserve strong normalization.\n\\<close>\ndefinition lex_ext :: \"('a \\<Rightarrow> 'a \\<Rightarrow> bool \\<times> bool) \\<Rightarrow> nat \\<Rightarrow> 'a list \\<Rightarrow> 'a list \\<Rightarrow> bool \\<times> bool\"\n  where\n    \"lex_ext f n ss ts =\n      (let lts = length ts in \n      if (length ss = lts \\<or> lts \\<le> n) then lex_ext_unbounded f ss ts\n      else (False, False))\"\n\nlemma lex_ext_iff: \"(lex_ext f m xs ys) = (\n  (length xs = length ys \\<or> length ys \\<le> m) \\<and> ((\\<exists> i < length xs. i < length ys \\<and> (\\<forall> j < i. snd (f (xs ! j) (ys ! j))) \\<and> fst (f (xs ! i) (ys !i))) \\<or> \n  (\\<forall> i < length ys. snd (f (xs ! i) (ys ! i))) \\<and> length xs > length ys),\n  (length xs = length ys \\<or> length ys \\<le> m) \\<and>\n  ((\\<exists> i < length xs. i < length ys \\<and> (\\<forall> j < i. snd (f (xs ! j) (ys ! j))) \\<and> fst (f (xs ! i) (ys !i))) \\<or> \n  (\\<forall> i < length ys. snd (f (xs ! i) (ys ! i))) \\<and> length xs \\<ge> length ys))\n  \"\n  unfolding lex_ext_def\n  by (simp only: lex_ext_unbounded_iff Let_def, auto)\n\nlemma lex_ext_to_lex_ext_unbounded: \n  assumes \"length xs \\<le> n\" and \"length ys \\<le> n\"\n  shows \"lex_ext f n xs ys = lex_ext_unbounded f xs ys\"\n  using assms by (simp add: lex_ext_def)\n\n\nlemma lex_ext_stri_imp_nstri: \n  assumes \"fst (lex_ext f m xs ys)\" \n  shows \"snd (lex_ext f m xs ys)\"\n  using assms by (auto simp: lex_ext_iff)\n\nlemma lex_ext_unbounded_stri_imp_nstri: \n  assumes \"fst (lex_ext_unbounded f xs ys)\" \n  shows \"snd (lex_ext_unbounded f xs ys)\"\n  using assms by (auto simp: lex_ext_unbounded_iff)\n\nlemma all_nstri_imp_lex_nstri: assumes \"\\<forall> i < length ys. snd (f (xs ! i) (ys ! i))\" and \"length xs \\<ge> length ys\" and \"length xs = length ys \\<or> length ys \\<le> m\"\n  shows \"snd (lex_ext f m xs ys)\"\n  using assms by (auto simp: lex_ext_iff)\n\n\nlemma lex_ext_cong[fundef_cong]: fixes f g m1 m2 xs1 xs2 ys1 ys2\n  assumes \"length xs1 = length ys1\" and \"m1 = m2\" and \"length xs2 = length ys2\" and \"\\<And> i. \\<lbrakk>i < length ys1; i < length ys2\\<rbrakk> \\<Longrightarrow> f (xs1 ! i) (xs2 ! i) = g (ys1 ! i) (ys2 ! i)\" \n  shows \"lex_ext f m1 xs1 xs2 = lex_ext g m2 ys1 ys2\"\n  using assms by (auto simp: lex_ext_iff)\n\nlemma lex_ext_unbounded_cong[fundef_cong]: assumes \"as = as'\" and \"bs = bs'\"\n  and \"\\<And> i. i < length as' \\<Longrightarrow> i < length bs' \\<Longrightarrow> f (as' ! i) (bs' ! i) = g (as' ! i) (bs' ! i)\" shows \"lex_ext_unbounded f as bs = lex_ext_unbounded g as' bs'\"\n  unfolding assms lex_ext_unbounded_iff using assms(3) by auto\n\ntext \\<open>Compatibility is the key property to ensure transitivity of the order.\\<close>\n\ntext \\<open>\n  We prove compatibility locally, i.e., it only has to hold for elements\n  of the argument lists. Locality is essential for being applicable in recursively\n  defined term orders such as KBO.\n\\<close>\nlemma lex_ext_compat:\n  assumes compat: \"\\<And> s t u. \\<lbrakk>s \\<in> set ss; t \\<in> set ts; u \\<in> set us\\<rbrakk> \\<Longrightarrow>\n    (snd (f s t) \\<and> fst (f t u) \\<longrightarrow> fst (f s u)) \\<and> \n    (fst (f s t) \\<and> snd (f t u) \\<longrightarrow> fst (f s u)) \\<and> \n    (snd (f s t) \\<and> snd (f t u) \\<longrightarrow> snd (f s u)) \\<and>\n    (fst (f s t) \\<and> fst (f t u) \\<longrightarrow> fst (f s u))\"\n  shows \"\n    (snd (lex_ext f n ss ts) \\<and> fst (lex_ext f n ts us) \\<longrightarrow> fst (lex_ext f n ss us)) \\<and> \n    (fst (lex_ext f n ss ts) \\<and> snd (lex_ext f n ts us) \\<longrightarrow> fst (lex_ext f n ss us)) \\<and> \n    (snd (lex_ext f n ss ts) \\<and> snd (lex_ext f n ts us) \\<longrightarrow> snd (lex_ext f n ss us)) \\<and>\n    (fst (lex_ext f n ss ts) \\<and> fst (lex_ext f n ts us) \\<longrightarrow> fst (lex_ext f n ss us))\n    \"\nproof -\n  let ?ls = \"length ss\"\n  let ?lt = \"length ts\"\n  let ?lu = \"length us\"\n  let ?st = \"lex_ext f n ss ts\"\n  let ?tu = \"lex_ext f n ts us\"\n  let ?su = \"lex_ext f n ss us\"\n  let ?fst = \"\\<lambda> ss ts i. fst (f (ss ! i) (ts ! i))\"\n  let ?snd = \"\\<lambda> ss ts i. snd (f (ss ! i) (ts ! i))\"\n  let ?ex = \"\\<lambda> ss ts. \\<exists> i < length ss. i < length ts \\<and> (\\<forall> j < i. ?snd ss ts j) \\<and> ?fst ss ts i\"\n  let ?all = \"\\<lambda> ss ts. \\<forall> i < length ts. ?snd ss ts i\"\n  have lengths: \"(?ls = ?lt \\<or> ?lt \\<le> n) \\<and> (?lt = ?lu \\<or> ?lu \\<le> n) \\<longrightarrow>\n    (?ls = ?lu \\<or> ?lu \\<le> n)\" (is \"?lst \\<and> ?ltu \\<longrightarrow> ?lsu\") by arith\n  {\n    assume st: \"snd ?st\" and tu: \"fst ?tu\"\n    with lengths have lsu: \"?lsu\" by (simp add: lex_ext_iff)\n    from st have st: \"?ex ss ts \\<or> ?all ss ts \\<and> ?lt \\<le> ?ls\" by (simp add: lex_ext_iff)\n    from tu have tu: \"?ex ts us \\<or> ?all ts us \\<and> ?lu < ?lt\" by (simp add: lex_ext_iff)\n    from st have \"fst ?su\"\n    proof\n      assume st: \"?ex ss ts\"\n      then obtain i1 where i1: \"i1 < ?ls \\<and> i1 < ?lt\" and fst1: \"?fst ss ts i1\" and snd1: \"\\<forall> j < i1. ?snd ss ts j\" by force\n      from tu show ?thesis\n      proof\n        assume tu: \"?ex ts us\"\n        then obtain i2 where i2: \"i2 < ?lt \\<and> i2 < ?lu\" and fst2: \"?fst ts us i2\" and snd2: \"\\<forall> j < i2. ?snd ts us j\" by auto\n        let ?i = \"min i1 i2\"\n        from i1 i2 have i: \"?i < ?ls \\<and> ?i < ?lt \\<and> ?i < ?lu\" by auto\n        then have ssi: \"ss ! ?i \\<in> set ss\" and tsi: \"ts ! ?i \\<in> set ts\" and usi: \"us ! ?i \\<in> set us\" by auto\n        have snd: \"\\<forall> j < ?i. ?snd ss us j\"\n        proof (intro allI impI)\n          fix j\n          assume j: \"j < ?i\"\n          with snd1 snd2 have snd1: \"?snd ss ts j\" and snd2: \"?snd ts us j\" by auto\n          from j i have ssj: \"ss ! j \\<in> set ss\" and tsj: \"ts ! j \\<in> set ts\" and usj: \"us ! j \\<in> set us\" by auto\n          from compat[OF ssj tsj usj] snd1 snd2 show \"?snd ss us j\" by auto\n        qed\n        have fst: \"?fst ss us ?i\" \n        proof (cases \"i1 < i2\")\n          case True\n          then have \"?i = i1\" by simp\n          with True fst1 snd2 have \"?fst ss ts ?i\" and \"?snd ts us ?i\" by auto\n          with compat[OF ssi tsi usi] show \"?fst ss us ?i\" by auto\n        next\n          case False\n          show ?thesis \n          proof (cases \"i2 < i1\")\n            case True\n            then have \"?i = i2\" by simp\n            with True snd1 fst2 have \"?snd ss ts ?i\" and \"?fst ts us ?i\" by auto\n            with compat[OF ssi tsi usi] show \"?fst ss us ?i\" by auto\n          next\n            case False\n            with \\<open>\\<not> i1 < i2\\<close> have \"i1 = i2\" by simp\n            with fst1 fst2 have \"?fst ss ts ?i\" and \"?fst ts us ?i\" by auto\n            with compat[OF ssi tsi usi] show \"?fst ss us ?i\" by auto\n          qed\n        qed\n        show ?thesis by (simp add: lex_ext_iff lsu, rule disjI1, rule exI[of _ ?i], simp add: fst snd i)\n      next\n        assume tu: \"?all ts us \\<and> ?lu < ?lt\"\n        show ?thesis\n        proof (cases \"i1 < ?lu\")\n          case True\n          then have usi: \"us ! i1 \\<in> set us\" by auto\n          from i1 have ssi: \"ss ! i1 \\<in> set ss\" and tsi: \"ts ! i1 \\<in> set ts\" by auto\n          from True tu have \"?snd ts us i1\" by auto\n          with fst1 compat[OF ssi tsi usi] have fst: \"?fst ss us i1\" by auto\n          have snd: \"\\<forall> j < i1. ?snd ss us j\"\n          proof (intro allI impI)\n            fix j\n            assume \"j < i1\"\n            with i1 True snd1 tu have snd1: \"?snd ss ts j\" and snd2: \"?snd ts us j\" and \n              ssj: \"ss ! j \\<in> set ss\" and tsj: \"ts ! j \\<in> set ts\" and usj: \"us ! j \\<in> set us\" by auto\n            from compat[OF ssj tsj usj] snd1 snd2 show \"?snd ss us j\" by auto\n          qed\n          with fst lsu True i1 show ?thesis by (auto simp: lex_ext_iff) \n        next\n          case False\n          with i1 have lus: \"?lu < ?ls\" by auto\n          have snd: \"\\<forall> j < ?lu. ?snd ss us j\"\n          proof (intro allI impI)\n            fix j\n            assume \"j < ?lu\"\n            with False i1 snd1 tu have snd1: \"?snd ss ts j\" and snd2: \"?snd ts us j\" and \n              ssj: \"ss ! j \\<in> set ss\" and tsj: \"ts ! j \\<in> set ts\" and usj: \"us ! j \\<in> set us\" by auto\n            from compat[OF ssj tsj usj] snd1 snd2 show \"?snd ss us j\" by auto\n          qed\n          with lus lsu show ?thesis by (auto simp: lex_ext_iff)\n        qed\n      qed\n    next\n      assume st: \"?all ss ts \\<and> ?lt \\<le> ?ls\"\n      from tu\n      show ?thesis\n      proof\n        assume tu: \"?ex ts us\"\n        with st obtain i2 where i2: \"i2 < ?lt \\<and> i2 < ?lu\" and fst2: \"?fst ts us i2\" and snd2: \"\\<forall> j < i2. ?snd ts us j\" by auto\n        from st i2 have i2: \"i2 < ?ls \\<and> i2 < ?lt \\<and> i2 < ?lu\" by auto\n        then have ssi: \"ss ! i2 \\<in> set ss\" and tsi: \"ts ! i2 \\<in> set ts\" and usi: \"us ! i2 \\<in> set us\" by auto\n        from i2 st have \"?snd ss ts i2\" by auto\n        with fst2 compat[OF ssi tsi usi] have fst: \"?fst ss us i2\" by auto\n        have snd: \"\\<forall> j < i2. ?snd ss us j\"\n        proof (intro allI impI)\n          fix j\n          assume \"j < i2\"\n          with i2 snd2 st have snd1: \"?snd ss ts j\" and snd2: \"?snd ts us j\" and \n            ssj: \"ss ! j \\<in> set ss\" and tsj: \"ts ! j \\<in> set ts\" and usj: \"us ! j \\<in> set us\" by auto\n          from compat[OF ssj tsj usj] snd1 snd2 show \"?snd ss us j\" by auto\n        qed\n        with fst lsu i2 show ?thesis by (auto simp: lex_ext_iff)\n      next\n        assume tu: \"?all ts us \\<and> ?lu < ?lt\"\n        with st have lus: \"?lu < ?ls\" by auto\n        have snd: \"\\<forall> j < ?lu. ?snd ss us j\"\n        proof (intro allI impI)\n          fix j\n          assume \"j < ?lu\"\n          with st tu have snd1: \"?snd ss ts j\" and snd2: \"?snd ts us j\" and \n            ssj: \"ss ! j \\<in> set ss\" and tsj: \"ts ! j \\<in> set ts\" and usj: \"us ! j \\<in> set us\" by auto\n          from compat[OF ssj tsj usj] snd1 snd2 show \"?snd ss us j\" by auto\n        qed\n        with lus lsu show ?thesis by (auto simp: lex_ext_iff)\n      qed\n    qed\n  }\n  moreover\n  {\n    assume st: \"fst ?st\" and tu: \"snd ?tu\"\n    with lengths have lsu: \"?lsu\" by (simp add: lex_ext_iff)\n    from st have st: \"?ex ss ts \\<or> ?all ss ts \\<and> ?lt < ?ls\" by (simp add: lex_ext_iff)\n    from tu have tu: \"?ex ts us \\<or> ?all ts us \\<and> ?lu \\<le> ?lt\" by (simp add: lex_ext_iff)\n    from st have \"fst ?su\"\n    proof\n      assume st: \"?ex ss ts\"\n      then obtain i1 where i1: \"i1 < ?ls \\<and> i1 < ?lt\" and fst1: \"?fst ss ts i1\" and snd1: \"\\<forall> j < i1. ?snd ss ts j\" by force\n      from tu show ?thesis\n      proof\n        assume tu: \"?ex ts us\"\n        then obtain i2 where i2: \"i2 < ?lt \\<and> i2 < ?lu\" and fst2: \"?fst ts us i2\" and snd2: \"\\<forall> j < i2. ?snd ts us j\" by auto\n        let ?i = \"min i1 i2\"\n        from i1 i2 have i: \"?i < ?ls \\<and> ?i < ?lt \\<and> ?i < ?lu\" by auto\n        then have ssi: \"ss ! ?i \\<in> set ss\" and tsi: \"ts ! ?i \\<in> set ts\" and usi: \"us ! ?i \\<in> set us\" by auto\n        have snd: \"\\<forall> j < ?i. ?snd ss us j\"\n        proof (intro allI impI)\n          fix j\n          assume j: \"j < ?i\"\n          with snd1 snd2 have snd1: \"?snd ss ts j\" and snd2: \"?snd ts us j\" by auto\n          from j i have ssj: \"ss ! j \\<in> set ss\" and tsj: \"ts ! j \\<in> set ts\" and usj: \"us ! j \\<in> set us\" by auto\n          from compat[OF ssj tsj usj] snd1 snd2 show \"?snd ss us j\" by auto\n        qed\n        have fst: \"?fst ss us ?i\" \n        proof (cases \"i1 < i2\")\n          case True\n          then have \"?i = i1\" by simp\n          with True fst1 snd2 have \"?fst ss ts ?i\" and \"?snd ts us ?i\" by auto\n          with compat[OF ssi tsi usi] show \"?fst ss us ?i\" by auto\n        next\n          case False\n          show ?thesis \n          proof (cases \"i2 < i1\")\n            case True\n            then have \"?i = i2\" by simp\n            with True snd1 fst2 have \"?snd ss ts ?i\" and \"?fst ts us ?i\" by auto\n            with compat[OF ssi tsi usi] show \"?fst ss us ?i\" by auto\n          next\n            case False\n            with \\<open>\\<not> i1 < i2\\<close> have \"i1 = i2\" by simp\n            with fst1 fst2 have \"?fst ss ts ?i\" and \"?fst ts us ?i\" by auto\n            with compat[OF ssi tsi usi] show \"?fst ss us ?i\" by auto\n          qed\n        qed\n        show ?thesis by (simp add: lex_ext_iff lsu, rule disjI1, rule exI[of _ ?i], simp add: fst snd i)\n      next\n        assume tu: \"?all ts us \\<and> ?lu \\<le> ?lt\"\n        show ?thesis\n        proof (cases \"i1 < ?lu\")\n          case True\n          then have usi: \"us ! i1 \\<in> set us\" by auto\n          from i1 have ssi: \"ss ! i1 \\<in> set ss\" and tsi: \"ts ! i1 \\<in> set ts\" by auto\n          from True tu have \"?snd ts us i1\" by auto\n          with fst1 compat[OF ssi tsi usi] have fst: \"?fst ss us i1\" by auto\n          have snd: \"\\<forall> j < i1. ?snd ss us j\"\n          proof (intro allI impI)\n            fix j\n            assume \"j < i1\"\n            with i1 True snd1 tu have snd1: \"?snd ss ts j\" and snd2: \"?snd ts us j\" and \n              ssj: \"ss ! j \\<in> set ss\" and tsj: \"ts ! j \\<in> set ts\" and usj: \"us ! j \\<in> set us\" by auto\n            from compat[OF ssj tsj usj] snd1 snd2 show \"?snd ss us j\" by auto\n          qed\n          with fst lsu True i1 show ?thesis by (auto simp: lex_ext_iff) \n        next\n          case False\n          with i1 have lus: \"?lu < ?ls\" by auto\n          have snd: \"\\<forall> j < ?lu. ?snd ss us j\"\n          proof (intro allI impI)\n            fix j\n            assume \"j < ?lu\"\n            with False i1 snd1 tu have snd1: \"?snd ss ts j\" and snd2: \"?snd ts us j\" and \n              ssj: \"ss ! j \\<in> set ss\" and tsj: \"ts ! j \\<in> set ts\" and usj: \"us ! j \\<in> set us\" by auto\n            from compat[OF ssj tsj usj] snd1 snd2 show \"?snd ss us j\" by auto\n          qed\n          with lus lsu show ?thesis by (auto simp: lex_ext_iff)\n        qed\n      qed\n    next\n      assume st: \"?all ss ts \\<and> ?lt < ?ls\"\n      from tu\n      show ?thesis\n      proof\n        assume tu: \"?ex ts us\"\n        with st obtain i2 where i2: \"i2 < ?lt \\<and> i2 < ?lu\" and fst2: \"?fst ts us i2\" and snd2: \"\\<forall> j < i2. ?snd ts us j\" by auto\n        from st i2 have i2: \"i2 < ?ls \\<and> i2 < ?lt \\<and> i2 < ?lu\" by auto\n        then have ssi: \"ss ! i2 \\<in> set ss\" and tsi: \"ts ! i2 \\<in> set ts\" and usi: \"us ! i2 \\<in> set us\" by auto\n        from i2 st have \"?snd ss ts i2\" by auto\n        with fst2 compat[OF ssi tsi usi] have fst: \"?fst ss us i2\" by auto\n        have snd: \"\\<forall> j < i2. ?snd ss us j\"\n        proof (intro allI impI)\n          fix j\n          assume \"j < i2\"\n          with i2 snd2 st have snd1: \"?snd ss ts j\" and snd2: \"?snd ts us j\" and \n            ssj: \"ss ! j \\<in> set ss\" and tsj: \"ts ! j \\<in> set ts\" and usj: \"us ! j \\<in> set us\" by auto\n          from compat[OF ssj tsj usj] snd1 snd2 show \"?snd ss us j\" by auto\n        qed\n        with fst lsu i2 show ?thesis by (auto simp: lex_ext_iff)\n      next\n        assume tu: \"?all ts us \\<and> ?lu \\<le> ?lt\"\n        with st have lus: \"?lu < ?ls\" by auto\n        have snd: \"\\<forall> j < ?lu. ?snd ss us j\"\n        proof (intro allI impI)\n          fix j\n          assume \"j < ?lu\"\n          with st tu have snd1: \"?snd ss ts j\" and snd2: \"?snd ts us j\" and \n            ssj: \"ss ! j \\<in> set ss\" and tsj: \"ts ! j \\<in> set ts\" and usj: \"us ! j \\<in> set us\" by auto\n          from compat[OF ssj tsj usj] snd1 snd2 show \"?snd ss us j\" by auto\n        qed\n        with lus lsu show ?thesis by (auto simp: lex_ext_iff)\n      qed\n    qed\n  }\n  moreover\n  {\n    assume st: \"snd ?st\" and tu: \"snd ?tu\"\n    with lengths have lsu: \"?lsu\" by (simp add: lex_ext_iff)\n    from st have st: \"?ex ss ts \\<or> ?all ss ts \\<and> ?lt \\<le> ?ls\" by (simp add: lex_ext_iff)\n    from tu have tu: \"?ex ts us \\<or> ?all ts us \\<and> ?lu \\<le> ?lt\" by (simp add: lex_ext_iff)\n    from st have \"snd ?su\"\n    proof\n      assume st: \"?ex ss ts\"\n      then obtain i1 where i1: \"i1 < ?ls \\<and> i1 < ?lt\" and fst1: \"?fst ss ts i1\" and snd1: \"\\<forall> j < i1. ?snd ss ts j\" by force\n      from tu show ?thesis\n      proof\n        assume tu: \"?ex ts us\"\n        then obtain i2 where i2: \"i2 < ?lt \\<and> i2 < ?lu\" and fst2: \"?fst ts us i2\" and snd2: \"\\<forall> j < i2. ?snd ts us j\" by auto\n        let ?i = \"min i1 i2\"\n        from i1 i2 have i: \"?i < ?ls \\<and> ?i < ?lt \\<and> ?i < ?lu\" by auto\n        then have ssi: \"ss ! ?i \\<in> set ss\" and tsi: \"ts ! ?i \\<in> set ts\" and usi: \"us ! ?i \\<in> set us\" by auto\n        have snd: \"\\<forall> j < ?i. ?snd ss us j\"\n        proof (intro allI impI)\n          fix j\n          assume j: \"j < ?i\"\n          with snd1 snd2 have snd1: \"?snd ss ts j\" and snd2: \"?snd ts us j\" by auto\n          from j i have ssj: \"ss ! j \\<in> set ss\" and tsj: \"ts ! j \\<in> set ts\" and usj: \"us ! j \\<in> set us\" by auto\n          from compat[OF ssj tsj usj] snd1 snd2 show \"?snd ss us j\" by auto\n        qed\n        have fst: \"?fst ss us ?i\" \n        proof (cases \"i1 < i2\")\n          case True\n          then have \"?i = i1\" by simp\n          with True fst1 snd2 have \"?fst ss ts ?i\" and \"?snd ts us ?i\" by auto\n          with compat[OF ssi tsi usi] show \"?fst ss us ?i\" by auto\n        next\n          case False\n          show ?thesis \n          proof (cases \"i2 < i1\")\n            case True\n            then have \"?i = i2\" by simp\n            with True snd1 fst2 have \"?snd ss ts ?i\" and \"?fst ts us ?i\" by auto\n            with compat[OF ssi tsi usi] show \"?fst ss us ?i\" by auto\n          next\n            case False\n            with \\<open>\\<not> i1 < i2\\<close> have \"i1 = i2\" by simp\n            with fst1 fst2 have \"?fst ss ts ?i\" and \"?fst ts us ?i\" by auto\n            with compat[OF ssi tsi usi] show \"?fst ss us ?i\" by auto\n          qed\n        qed\n        show ?thesis by (simp add: lex_ext_iff lsu, rule disjI1, rule exI[of _ ?i], simp add: fst snd i)\n      next\n        assume tu: \"?all ts us \\<and> ?lu \\<le> ?lt\"\n        show ?thesis\n        proof (cases \"i1 < ?lu\")\n          case True\n          then have usi: \"us ! i1 \\<in> set us\" by auto\n          from i1 have ssi: \"ss ! i1 \\<in> set ss\" and tsi: \"ts ! i1 \\<in> set ts\" by auto\n          from True tu have \"?snd ts us i1\" by auto\n          with fst1 compat[OF ssi tsi usi] have fst: \"?fst ss us i1\" by auto\n          have snd: \"\\<forall> j < i1. ?snd ss us j\"\n          proof (intro allI impI)\n            fix j\n            assume \"j < i1\"\n            with i1 True snd1 tu have snd1: \"?snd ss ts j\" and snd2: \"?snd ts us j\" and \n              ssj: \"ss ! j \\<in> set ss\" and tsj: \"ts ! j \\<in> set ts\" and usj: \"us ! j \\<in> set us\" by auto\n            from compat[OF ssj tsj usj] snd1 snd2 show \"?snd ss us j\" by auto\n          qed\n          with fst lsu True i1 show ?thesis by (auto simp: lex_ext_iff) \n        next\n          case False\n          with i1 have lus: \"?lu \\<le> ?ls\" by auto\n          have snd: \"\\<forall> j < ?lu. ?snd ss us j\"\n          proof (intro allI impI)\n            fix j\n            assume \"j < ?lu\"\n            with False i1 snd1 tu have snd1: \"?snd ss ts j\" and snd2: \"?snd ts us j\" and \n              ssj: \"ss ! j \\<in> set ss\" and tsj: \"ts ! j \\<in> set ts\" and usj: \"us ! j \\<in> set us\" by auto\n            from compat[OF ssj tsj usj] snd1 snd2 show \"?snd ss us j\" by auto\n          qed\n          with lus lsu show ?thesis by (auto simp: lex_ext_iff)\n        qed\n      qed\n    next\n      assume st: \"?all ss ts \\<and> ?lt \\<le> ?ls\"\n      from tu\n      show ?thesis\n      proof\n        assume tu: \"?ex ts us\"\n        with st obtain i2 where i2: \"i2 < ?lt \\<and> i2 < ?lu\" and fst2: \"?fst ts us i2\" and snd2: \"\\<forall> j < i2. ?snd ts us j\" by auto\n        from st i2 have i2: \"i2 < ?ls \\<and> i2 < ?lt \\<and> i2 < ?lu\" by auto\n        then have ssi: \"ss ! i2 \\<in> set ss\" and tsi: \"ts ! i2 \\<in> set ts\" and usi: \"us ! i2 \\<in> set us\" by auto\n        from i2 st have \"?snd ss ts i2\" by auto\n        with fst2 compat[OF ssi tsi usi] have fst: \"?fst ss us i2\" by auto\n        have snd: \"\\<forall> j < i2. ?snd ss us j\"\n        proof (intro allI impI)\n          fix j\n          assume \"j < i2\"\n          with i2 snd2 st have snd1: \"?snd ss ts j\" and snd2: \"?snd ts us j\" and \n            ssj: \"ss ! j \\<in> set ss\" and tsj: \"ts ! j \\<in> set ts\" and usj: \"us ! j \\<in> set us\" by auto\n          from compat[OF ssj tsj usj] snd1 snd2 show \"?snd ss us j\" by auto\n        qed\n        with fst lsu i2 show ?thesis by (auto simp: lex_ext_iff)\n      next\n        assume tu: \"?all ts us \\<and> ?lu \\<le> ?lt\"\n        with st have lus: \"?lu \\<le> ?ls\" by auto\n        have snd: \"\\<forall> j < ?lu. ?snd ss us j\"\n        proof (intro allI impI)\n          fix j\n          assume \"j < ?lu\"\n          with st tu have snd1: \"?snd ss ts j\" and snd2: \"?snd ts us j\" and \n            ssj: \"ss ! j \\<in> set ss\" and tsj: \"ts ! j \\<in> set ts\" and usj: \"us ! j \\<in> set us\" by auto\n          from compat[OF ssj tsj usj] snd1 snd2 show \"?snd ss us j\" by auto\n        qed\n        with lus lsu show ?thesis by (auto simp: lex_ext_iff)\n      qed\n    qed\n  }\n  ultimately\n  show ?thesis using lex_ext_stri_imp_nstri by blast\nqed\n\nlemma lex_ext_unbounded_map:\n  assumes S: \"\\<And> i. i < length ss \\<Longrightarrow> i < length ts \\<Longrightarrow> fst (r (ss ! i) (ts ! i)) \\<Longrightarrow> fst (r (map f ss ! i) (map f ts ! i))\"\n    and NS: \"\\<And> i. i < length ss \\<Longrightarrow> i < length ts \\<Longrightarrow> snd (r (ss ! i) (ts ! i)) \\<Longrightarrow> snd (r (map f ss ! i) (map f ts ! i))\"\n  shows \"(fst (lex_ext_unbounded r ss ts) \\<longrightarrow> fst (lex_ext_unbounded r (map f ss) (map f ts))) \\<and>\n    (snd (lex_ext_unbounded r ss ts) \\<longrightarrow> snd (lex_ext_unbounded r (map f ss) (map f ts)))\"\n  using S NS unfolding lex_ext_unbounded_iff by auto\n\nlemma lex_ext_unbounded_map_S:\n  assumes S: \"\\<And> i. i < length ss \\<Longrightarrow> i < length ts \\<Longrightarrow> fst (r (ss ! i) (ts ! i)) \\<Longrightarrow> fst (r (map f ss ! i) (map f ts ! i))\"\n    and NS: \"\\<And> i. i < length ss \\<Longrightarrow> i < length ts \\<Longrightarrow> snd (r (ss ! i) (ts ! i)) \\<Longrightarrow> snd (r (map f ss ! i) (map f ts ! i))\"\n    and stri: \"fst (lex_ext_unbounded r ss ts)\"\n  shows \"fst (lex_ext_unbounded r (map f ss) (map f ts))\"\n  using lex_ext_unbounded_map[of ss ts r f, OF S NS] stri by blast\n\nlemma lex_ext_unbounded_map_NS:\n  assumes S: \"\\<And> i. i < length ss \\<Longrightarrow> i < length ts \\<Longrightarrow> fst (r (ss ! i) (ts ! i)) \\<Longrightarrow> fst (r (map f ss ! i) (map f ts ! i))\"\n    and NS: \"\\<And> i. i < length ss \\<Longrightarrow> i < length ts \\<Longrightarrow> snd (r (ss ! i) (ts ! i)) \\<Longrightarrow> snd (r (map f ss ! i) (map f ts ! i))\"\n    and nstri: \"snd (lex_ext_unbounded r ss ts)\"\n  shows \"snd (lex_ext_unbounded r (map f ss) (map f ts))\"\n  using lex_ext_unbounded_map[of ss ts r f, OF S NS] nstri by blast\n\ntext \\<open>Strong normalization with local SN assumption\\<close>\nlemma lex_ext_SN:\n  assumes compat: \"\\<And> x y z. \\<lbrakk>snd (g x y); fst (g y z)\\<rbrakk> \\<Longrightarrow> fst (g x z)\"\n  shows \"SN { (ys, xs). (\\<forall> y \\<in> set ys. SN_on { (s, t). fst (g s t) } {y}) \\<and> fst (lex_ext g m ys xs) }\" \n    (is \"SN { (ys, xs). ?cond ys xs }\")\nproof (rule ccontr)\n  assume \"\\<not> ?thesis\"\n  from this obtain f where f: \"\\<And> n :: nat. ?cond (f n) (f (Suc n))\" unfolding SN_defs by auto\n  have m_imp_m: \"\\<And> n. length (f n) \\<le> m \\<Longrightarrow> length (f (Suc n)) \\<le> m\"\n  proof -\n    fix n\n    assume \"length (f n) \\<le> m\"\n    then show \"length (f (Suc n)) \\<le> m\"\n      using f[of n] by (auto simp: lex_ext_iff)\n  qed\n  have lm_imp_m_or_eq: \"\\<And> n. length (f n) > m \\<Longrightarrow> length (f (Suc n)) \\<le> m \\<or> length (f n) = length (f (Suc n))\"\n  proof -\n    fix n\n    assume \"length (f n) > m\"\n    then have \"\\<not> length (f n) \\<le> m\" by auto\n    then show \"length (f (Suc n)) \\<le> m \\<or> length (f n) = length (f (Suc n))\"\n      using f[of n] by (simp add: lex_ext_iff, blast)\n  qed\n  let ?l0 = \"max (length (f 0)) m\"\n  have \"\\<And> n. length (f n) \\<le> ?l0\"\n  proof -\n    fix n\n    show \"length (f n) \\<le> ?l0\"\n    proof (induct n, simp)\n      case (Suc n)\n      show ?case\n      proof (cases \"length (f n) \\<le> m\")\n        case True\n        with m_imp_m[of n] show ?thesis by auto\n      next\n        case False\n        then have \"length (f n) > m\" by auto\n        with lm_imp_m_or_eq[of n] \n        have \"length (f n) = length (f (Suc n)) \\<or> length (f (Suc n)) \\<le> m\" by auto\n        with Suc show ?thesis by auto\n      qed\n    qed\n  qed\n  from this obtain m' where len: \"\\<And> n. length (f n) \\<le> m'\" by auto\n  let ?lexgr = \"\\<lambda> ys xs. fst (lex_ext g m ys xs)\"\n  let ?lexge = \"\\<lambda> ys xs. snd (lex_ext g m ys xs)\"\n  let ?gr = \"\\<lambda> t s. fst (g t s)\"\n  let ?ge = \"\\<lambda> t s. snd (g t s)\"\n  let ?S = \"{ (y, x). fst (g y x) }\"\n  let ?NS = \"{ (y, x). snd (g y x) }\"\n  let ?baseSN = \"\\<lambda> ys. \\<forall> y \\<in> set ys. SN_on ?S {y}\"\n  let ?con = \"\\<lambda> ys xs m'. ?baseSN ys \\<and> length ys \\<le> m' \\<and> ?lexgr ys xs\"\n  let ?confn = \"\\<lambda> m' f n . ?con (f n) (f (Suc n)) m'\"\n  from compat have compat2: \"?NS O ?S \\<subseteq> ?S\" by auto\n  from f len have  \"\\<exists> f. \\<forall> n. ?confn m' f n\" by auto\n  then show False\n  proof (induct m')\n    case 0\n    from this obtain f where \"?confn 0 f 0\" by auto\t\n    then have \"?lexgr [] (f (Suc 0))\" by force\n    then show False by (simp add: lex_ext_iff)\n  next\n    case (Suc m')\n    from this obtain f where confn: \"\\<And> n. ?confn (Suc m') f n\" by auto\n    have ne: \"\\<And> n. f n \\<noteq> []\"\n    proof -\n      fix n\n      show \"f n \\<noteq> []\"\n      proof (cases \"f n\")\n        case (Cons a b) then show ?thesis by auto\n      next\n        case Nil\n        with confn[of n] show ?thesis by (simp add: lex_ext_iff)\n      qed\n    qed\n    let ?hf = \"\\<lambda> n. hd (f n)\"\n    have ge: \"\\<And> n. ?ge (?hf n) (?hf (Suc n)) \\<or> ?gr (?hf n) (?hf (Suc n))\"\n    proof -\n      fix n\n      from ne[of n] obtain a as where n: \"f n = a # as\" by (cases \"f n\", auto)\n      from ne[of \"Suc n\"] obtain b bs where sn: \"f (Suc n) = b # bs\" by (cases \"f (Suc n)\", auto)\n      from n sn have \"?ge a b \\<or> ?gr a b\" \n      proof (cases \"?gr a b\", simp, cases \"?ge a b\", simp)\n        assume \"\\<not> ?gr a b\" and \"\\<not> ?ge a b\" \n        then have g: \"g a b = (False, False)\" by (cases \"g a b\", auto)\n        from confn[of n] have \"fst (lex_ext g m (f n) (f (Suc n)))\" (is ?fst) by simp\n        have \"?fst = False\" by (simp add: n sn lex_ext_def g lex_ext_unbounded.simps)\n        with \\<open>?fst\\<close> show \"?ge a b \\<or> ?gr a b\" by simp\n      qed\n      with n sn show \"?ge (?hf n) (?hf (Suc n)) \\<or> ?gr (?hf n) (?hf (Suc n))\" by simp\n    qed\n    from ge have GE: \"\\<forall> n. (?hf n, ?hf (Suc n)) \\<in> ?NS \\<union> ?S\" by auto\n    from confn[of 0] ne[of 0] have SN_0: \"SN_on ?S {?hf 0}\" by (cases \"f 0\", auto )\n    from non_strict_ending[of ?hf, OF GE compat2 SN_0]\n    obtain j where j: \"\\<forall> i \\<ge> j. (?hf i, ?hf (Suc i)) \\<in> ?NS - ?S\" by auto\n    let ?h = \"\\<lambda> n. tl (f (j + n))\"\n    obtain h where h: \"h = ?h\"  by auto\n    have \"\\<And> n. ?confn m' h n\" \n    proof -\n      fix n\n      let ?nj = \"j + n\"\n      from spec[OF j, of ?nj]\n      have ge_not_gr: \"(?hf ?nj, ?hf (Suc ?nj)) \\<in> ?NS - ?S\" by simp\n      from confn[of ?nj] have old: \"?confn (Suc m') f ?nj\" by simp\n      from ne[of ?nj] obtain a as where n: \"f ?nj = a # as\" by (cases \"f ?nj\", auto)\n      from ne[of \"Suc ?nj\"] obtain b bs where sn: \"f (Suc ?nj) = b # bs\" by (cases \"f (Suc ?nj)\", auto)\n      from old have one: \"\\<forall> y \\<in> set (h n). SN_on ?S {y}\" \n        by (simp add: h n)\n      from old have two: \"length (h n) \\<le> m'\" by (simp add: j n h)\n      from ge_not_gr have ge_not_gr2: \"g a b = (False, True)\"  by (simp add: n sn, cases \"g a b\", auto)\n      from old have \"fst (lex_ext g m (f (j+ n)) (f (Suc (j+n))))\" (is ?fst) by simp\n      then have \"length as = length bs \\<or> length bs \\<le> m\" (is ?len)\n        by (simp add: lex_ext_def n sn, cases ?len, auto)\n      from \\<open>?fst\\<close>[simplified n sn] have \"fst (lex_ext_unbounded g as bs)\" (is ?fst)\n        by (simp add: lex_ext_def, cases \"length as = length bs \\<or> Suc (length bs) \\<le> m\", simp_all add: ge_not_gr2 lex_ext_unbounded.simps)\n      then have \"fst (lex_ext_unbounded g as bs)\" (is ?fst)\n        by (simp add: lex_ext_unbounded_iff)\n      have three: \"?lexgr (h n) (h (Suc n))\"\n        by (simp add: lex_ext_def h n sn ge_not_gr2 lex_ext_unbounded.simps, simp only: Let_def, simp add: \\<open>?len\\<close> \\<open>?fst\\<close>)\n      from one two three show \"?confn m' h n\" by blast\n    qed\n    with Suc show ?thesis by blast\n  qed\nqed\n\ntext \\<open>Strong normalization with global SN assumption is immediate consequence.\\<close>\nlemma lex_ext_SN_2:\n  assumes compat: \"\\<And> x y z. \\<lbrakk>snd (g x y); fst (g y z)\\<rbrakk> \\<Longrightarrow> fst (g x z)\"\n    and SN:  \"SN {(s, t). fst (g s t)}\"\n  shows \"SN { (ys, xs). fst (lex_ext g m ys xs) }\" \nproof -\n  from lex_ext_SN[OF compat] \n  have \"SN { (ys, xs). (\\<forall> y \\<in> set ys. SN_on { (s, t). fst (g s t) } {y}) \\<and> fst (lex_ext g m ys xs) }\" .\n  then show ?thesis using SN unfolding SN_on_def by fastforce\nqed\n\ntext \\<open>The empty list is the least element in the lexicographic extension.\\<close>\nlemma lex_ext_least_1: \"snd (lex_ext f m xs [])\"\n  by (simp add: lex_ext_iff)\n\nlemma lex_ext_least_2: \"\\<not> fst (lex_ext f m [] ys)\"\n  by (simp add: lex_ext_iff)\n\ntext \\<open>Preservation of totality on lists of same length.\\<close>\nlemma lex_ext_unbounded_total:\n  assumes \"\\<forall>(s, t)\\<in>set (zip ss ts). s = t \\<or> fst (f s t) \\<or> fst (f t s)\" \n    and refl: \"\\<And> t. snd (f t t)\" \n    and \"length ss = length ts\" \n  shows \"ss = ts \\<or> fst (lex_ext_unbounded f ss ts) \\<or> fst (lex_ext_unbounded f ts ss)\" \n  using assms(3, 1)\nproof (induct ss ts rule: list_induct2)\n  case (Cons s ss t ts)\n  from Cons(3) have \"s = t \\<or> (fst (f s t) \\<or> fst (f t s))\" by auto\n  then show ?case\n  proof \n    assume st: \"s = t\" \n    then show ?thesis using Cons(2-3) refl[of t] by (cases \"f t t\", auto simp: lex_ext_unbounded.simps)\n  qed (auto simp: lex_ext_unbounded.simps split: prod.splits)\nqed simp\n\nlemma lex_ext_total:\n  assumes \"\\<forall>(s, t)\\<in>set (zip ss ts). s = t \\<or> fst (f s t) \\<or> fst (f t s)\" \n    and \"\\<And> t. snd (f t t)\" \n    and len: \"length ss = length ts\" \n  shows \"ss = ts \\<or> fst (lex_ext f n ss ts) \\<or> fst (lex_ext f n ts ss)\" \n  using lex_ext_unbounded_total[OF assms] unfolding lex_ext_def Let_def len by auto\n\ntext \\<open>Monotonicity of the lexicographic extension.\\<close>\nlemma lex_ext_unbounded_mono:\n  assumes \"\\<And>i. \\<lbrakk>i < length xs; i < length ys; fst (P (xs ! i) (ys ! i))\\<rbrakk> \\<Longrightarrow> fst (P' (xs ! i) (ys ! i))\"\n    and   \"\\<And>i. \\<lbrakk>i < length xs; i < length ys; snd (P (xs ! i) (ys ! i))\\<rbrakk> \\<Longrightarrow> snd (P' (xs ! i) (ys ! i))\"\n  shows\n    \"(fst (lex_ext_unbounded P xs ys) \\<longrightarrow> fst (lex_ext_unbounded P' xs ys)) \\<and>\n     (snd (lex_ext_unbounded P xs ys) \\<longrightarrow> snd (lex_ext_unbounded P' xs ys))\"\n    (is \"(?l1 xs ys \\<longrightarrow> ?r1 xs ys) \\<and> (?l2 xs ys \\<longrightarrow> ?r2 xs ys)\")\n  using assms\nproof (induct x\\<equiv>P xs ys rule: lex_ext_unbounded.induct)\n  note [simp] = lex_ext_unbounded.simps\n  case (4 x xs y ys)\n  consider (TT) \"P x y = (True, True)\"\n    | (TF) \"P x y = (True, False)\"\n    | (FT) \"P x y = (False, True)\"\n    | (FF) \"P x y = (False, False)\" by (cases \"P x y\", auto)\n  thus ?case\n  proof cases\n    case TT\n    moreover\n    with 4(2) [of 0] and 4(3) [of 0]\n    have \"P' x y = (True, True)\"\n      by (auto) (metis (full_types) prod.collapse)\n    ultimately\n    show ?thesis by simp\n  next\n    case TF\n    show ?thesis\n    proof (cases \"snd (P' x y)\")\n      case False\n      moreover\n      with 4(2) [of 0] and TF\n      have \"P' x y = (True, False)\"\n        by (cases \"P' x y\", auto) \n      ultimately\n      show ?thesis by simp\n    next\n      case True\n      with 4(2) [of 0] and TF\n      have \"P' x y = (True, True)\"\n        by (auto )(metis (full_types) fst_conv snd_conv surj_pair)\n      then show ?thesis by simp\n    qed\n  next\n    case FF then show ?thesis by simp\n  next\n    case FT\n    show ?thesis\n    proof (cases \"fst (P' x y)\")\n      case True\n      with 4(3) [of 0] and FT\n      have *: \"P' x y = (True, True)\"\n        by (auto) (metis (full_types) prod.collapse)\n      have \"?l1 (x#xs) (y#ys) \\<longrightarrow> ?r1 (x#xs) (y#ys)\"\n        by (simp add: FT *)\n      moreover\n      have \"?l2 (x#xs) (y#ys) \\<longrightarrow> ?r2 (x#xs) (y#ys)\"\n        by (simp add: *)\n      ultimately show ?thesis by blast\n    next\n      case False\n      with 4(3) [of 0] and FT\n      have *: \"P' x y = (False, True)\"\n        by (cases \"P' x y\", auto)\n      show ?thesis\n        using 4(1) [OF refl FT [symmetric]] and 4(2) and 4(3)\n        using FT *\n        by (auto) (metis Suc_less_eq nth_Cons_Suc)+\n    qed\n  qed\nqed (simp add: lex_ext_unbounded.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/Knuth_Bendix_Order/Lexicographic_Extension.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8824278726384089, "lm_q2_score": 0.8080672135527632, "lm_q1q2_score": 0.7130610322042118}}
{"text": "(*\n    $Id: sol.thy,v 1.3 2006/10/04 23:48:20 kleing Exp $\n    Author: Martin Strecker\n*)\n\nheader {* Elimination of Connectives *}\n\n(*<*) theory sol imports Main begin (*>*)\n\ntext {* In classical propositional logic, the connectives @{text \"=, \\<or>,\n\\<not>\"} can be replaced by @{text \"\\<longrightarrow>, \\<and>, False\"}.  Define\ncorresponding simplification rules as lemmas and prove their correctness.  (You\nmay use automated proof tactics.) *}\n\nlemma equiv_conel: \"(A = B) = ((A \\<longrightarrow> B) \\<and> (B \\<longrightarrow> A))\"\n  by iprover\n\nlemma or_conel: \"(A \\<or> B) = (\\<not> (\\<not> A \\<and> \\<not> B))\"\n  by blast\n\nlemma not_conel: \"(\\<not> A) = (A \\<longrightarrow> False)\"\n  by blast\n\n\ntext {* What is the result of your translation for the formula @{text \"A \\<or>\n(B \\<and> C) = A\"}?  (You can use Isabelle's simplifier to compute the result\nby using the simplifier's @{text \"only\"} option.) *}\n\ntext {* Stating @{text \"A \\<or> (B \\<and> C) = A\"} as a lemma and application\nof\\\\\n@{text \"(simp only: equiv_conel or_conel not_conel)\"}\\\\\nresults in the simplified goal\\\\\n@{text \"(A \\<longrightarrow> False) \\<and> ((B \\<and> C \\<longrightarrow> A)\n\\<and> (A \\<longrightarrow> B \\<and> C) \\<longrightarrow> False)\n\\<longrightarrow> False\"}. *}\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/logic/elimination/sol.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278757303678, "lm_q2_score": 0.808067208930584, "lm_q1q2_score": 0.7130610306239826}}
{"text": "theory OneTimePad imports\n  \"HOL/Probability\"\n  \"HOL/Groups_Big\"\nbegin\n\ntype_synonym key     = \"bool list\"\ntype_synonym message = \"bool list\"\ntype_synonym crypted = \"bool list\"\n\ndefinition zipWith :: \"('a \\<Rightarrow> 'b \\<Rightarrow> 'c) \\<Rightarrow> 'a list \\<Rightarrow> 'b list \\<Rightarrow> 'c list\" where\n  \"zipWith f xs ys = map (\\<lambda> (x, y). f x y) (zip xs ys)\"\n\n(*primrec zipWith where\n  \"zipWith f [] ys = (case ys of [] \\<Rightarrow> [])\"\n| \"zipWith f (x # xs) zs = (case zs of y # ys \\<Rightarrow> f x y # zipWith f xs ys)\"\n\nlemma \"length xs = length ys \\<Longrightarrow> zipWith f xs ys = map (\\<lambda> (x, y). f x y) (zip xs ys)\"\nby (induct xs ys rule: list_induct2, auto)*)\n\ndefinition xor :: \"bool \\<Rightarrow> bool \\<Rightarrow> bool\" where\n  \"xor = not_equal\"\n\ndefinition encrypt :: \"message \\<Rightarrow> key \\<Rightarrow> crypted\" where\n  \"encrypt = zipWith xor\"\n\ndefinition decrypt :: \"crypted \\<Rightarrow> key \\<Rightarrow> message\" where\n  \"decrypt = zipWith xor\"\n  \ndefinition reconstruct_key :: \"crypted \\<Rightarrow> message \\<Rightarrow> key\" where\n  \"reconstruct_key = zipWith xor\"\n  \n\nlemma enc:\n  assumes \"length m = length k\"\n    shows \"length (encrypt m k) = length m\"\n      and \"decrypt (encrypt m k) k = m\"\nunfolding encrypt_def decrypt_def zipWith_def xor_def\nusing assms by (induct m k rule: list_induct2, auto)\n\n\nlemma reconstruct:\n  assumes \"length m = length c\"\n    shows \"length (reconstruct_key c m) = length m\"\n      and \"encrypt m (reconstruct_key c m) = c\"\nunfolding encrypt_def reconstruct_key_def zipWith_def xor_def\nusing assms by (induct m c rule: list_induct2, auto)\n\nlemma rec_uniq:\n  assumes \"length m = length k\"\n      and \"encrypt m k = c\"\n    shows \"k = reconstruct_key c m\"\nproof -\n  have L: \"length k = length c\" using enc(1) assms(1) assms(2) by auto\n  show ?thesis using assms(1) L assms(2) unfolding encrypt_def reconstruct_key_def zipWith_def xor_def\n    by (induct m k c rule: list_induct3, auto)\nqed\n\naxiomatization\n      \\<K> :: \"key set\"\n  and \\<M> :: \"message set\"\n  and P\\<^sub>\\<K> :: \"key pmf\"\n  and P\\<^sub>\\<M> :: \"message pmf\"\n  and len :: nat\nwhere k_unipmf: \"P\\<^sub>\\<K> = pmf_of_set \\<K>\"  (* uniform distribution *)\n  and m_pmf: \"set_pmf P\\<^sub>\\<M> \\<subseteq> \\<M>\"\n  and k_set: \"\\<K> = set (List.n_lists len [True, False])\"\n  and m_set: \"\\<M> = \\<K>\"\n\ndefinition \\<P>\\<^sub>\\<K> :: \"key \\<Rightarrow> real\" where \"\\<P>\\<^sub>\\<K> = pmf P\\<^sub>\\<K>\"\ndefinition \\<P>\\<^sub>\\<M> :: \"message \\<Rightarrow> real\" where \"\\<P>\\<^sub>\\<M> = pmf P\\<^sub>\\<M>\"\n\nlemma k_finite: \"finite \\<K>\"\nby (metis List.finite_set k_set)\n\nlemma k_nonemp: \"\\<K> \\<noteq> {}\"\nunfolding k_set set_n_lists by (simp add: Ex_list_of_length subsetI)\n\nlemma k_length: \"\\<forall>k\\<in>\\<K>. length k = len\"\nunfolding k_set using length_n_lists_elem by auto\n\nlemma k_in_k: \"k \\<in> \\<K> \\<longleftrightarrow> (length k = len)\"\nproof (rule iffI)\n  assume \"k \\<in> \\<K>\"\n  then show \"length k = len\" unfolding k_set using length_n_lists_elem by auto\nnext\n  assume \"length k = len\"\n  then show \"k \\<in> \\<K>\" unfolding k_set set_n_lists by auto\nqed\n\nlemma pmf_sum_one:\n  assumes \"finite M\"\n      and \"set_pmf P \\<subseteq> M\"\n    shows \"(\\<Sum>m\\<in>M. pmf P m) = 1\"\nproof -\n  have \"(\\<Sum>m\\<in>M. pmf P m) = measure (measure_pmf P) M\"\n    using assms(1) by (simp add: measure_measure_pmf_finite)\n  also have \"... = 1\" using assms(2)\n    using AE_measure_pmf_iff prob_space.AE_in_set_eq_1 prob_space_measure_pmf by fastforce\n  finally show ?thesis .\nqed\n\nlemma m_sum_one: \"(\\<Sum>m\\<in>\\<M>. \\<P>\\<^sub>\\<M> m) = 1\"\nusing pmf_sum_one[of \\<M> P\\<^sub>\\<M>] k_finite m_pmf unfolding \\<P>\\<^sub>\\<M>_def m_set by auto\n\n\nlemma k_prob: \"k \\<in> \\<K> \\<Longrightarrow> \\<P>\\<^sub>\\<K> k = 1 / card \\<K>\"\nunfolding \\<P>\\<^sub>\\<K>_def k_unipmf pmf_of_set[OF k_nonemp k_finite] by auto\n\n\n(* probability of cryptogram c if message m is chosen *)\ndefinition \\<P>\\<^sub>\\<M>\\<^sub>\\<C> :: \"message \\<Rightarrow> crypted \\<Rightarrow> real\" where\n  \"\\<P>\\<^sub>\\<M>\\<^sub>\\<C> m c = (\\<Sum>k | k \\<in> \\<K> \\<and> encrypt m k = c. \\<P>\\<^sub>\\<K> k)\"\n\nlemma set_singleton:\n  assumes \"\\<forall>x \\<in> S. (P x \\<longrightarrow> x = y)\"\n      and \"\\<exists>x \\<in> S.  P x\"\n    shows \"{x \\<in> S. P x} = {y}\"\nby (smt Collect_cong Set.ball_empty assms insert_compr)\n\nlemma rec_in_k:\n  assumes \"m \\<in> \\<M>\"\n      and \"length m = length c\"\n    shows \"reconstruct_key c m \\<in> \\<K>\"\nproof -\n  have \"length m = len\" using assms(1) k_length m_set by auto\n  then have \"length (reconstruct_key c m) = len\" using reconstruct(1)[OF assms(2)] by auto\n  then show ?thesis using k_in_k by auto\nqed\n\nlemma uniq_k:\n  assumes \"m \\<in> \\<M>\"\n      and \"length m = length c\"\n    shows \"{k \\<in> \\<K>. encrypt m k = c} = {reconstruct_key c m}\"\nproof (rule set_singleton)\n  show \"\\<exists>k\\<in>\\<K>. encrypt m k = c\"\n  proof (rule bexI[of _ \"reconstruct_key c m\"])\n    show \"encrypt m (reconstruct_key c m) = c\" using reconstruct(2)[OF assms(2)] .\n    show \"reconstruct_key c m \\<in> \\<K>\" using rec_in_k[OF assms] by auto\n  qed\n  show \"\\<forall>k\\<in>\\<K>. encrypt m k = c \\<longrightarrow> k = reconstruct_key c m\"\n  proof (rule ballI)\n    fix k\n    assume K: \"k \\<in> \\<K>\"\n    then have \"length k = len\" using k_in_k by auto\n    also have \"length m = len\" using assms(1) k_in_k unfolding m_set by auto\n    finally have \"length m = length k\" .\n    then show \"encrypt m k = c \\<longrightarrow> k = reconstruct_key c m\" using rec_uniq by auto\n  qed\nqed\n\nlemma pmc_card_k:\n  assumes \"m \\<in> \\<M>\"\n      and \"length c = len\"\n    shows \"\\<P>\\<^sub>\\<M>\\<^sub>\\<C> m c = 1 / card \\<K>\"\nproof -\n  have L: \"length m = length c\" using k_in_k m_set assms by auto\n  have K: \"(reconstruct_key c m) \\<in> \\<K>\" using rec_in_k[OF assms(1) L] .\n  have \"\\<P>\\<^sub>\\<K> (reconstruct_key c m) = 1 / real (card \\<K>)\" using k_prob[OF K] .\n  then show ?thesis unfolding \\<P>\\<^sub>\\<M>\\<^sub>\\<C>_def unfolding uniq_k[OF assms(1) L] by simp\nqed\n\n(* probability of obtaining cryptogram c from any cause *)\ndefinition \\<P>\\<^sub>\\<C> :: \"crypted \\<Rightarrow> real\" where\n  \"\\<P>\\<^sub>\\<C> c = (\\<Sum>m\\<in>\\<M>. \\<P>\\<^sub>\\<M> m * \\<P>\\<^sub>\\<M>\\<^sub>\\<C> m c)\"\n\ntheorem\n  assumes \"m \\<in> \\<M>\"\n      and \"length c = len\"\n    shows \"\\<P>\\<^sub>\\<M>\\<^sub>\\<C> m c = \\<P>\\<^sub>\\<C> c\"\nproof -\n  have \"\\<P>\\<^sub>\\<C> c = (\\<Sum>m\\<in>\\<M>. \\<P>\\<^sub>\\<M> m * \\<P>\\<^sub>\\<M>\\<^sub>\\<C> m c)\" unfolding \\<P>\\<^sub>\\<C>_def by auto\n  also have \"... = (\\<Sum>m\\<in>\\<M>. \\<P>\\<^sub>\\<M> m * 1 / card \\<K>)\" using pmc_card_k[OF _ assms(2)] by auto\n  also have \"... = (\\<Sum>m\\<in>\\<M>. \\<P>\\<^sub>\\<M> m) / card \\<K>\" by (smt setsum.cong setsum_divide_distrib)\n  also have \"... = 1 / card \\<K>\" using m_sum_one by simp\n  finally have \"\\<P>\\<^sub>\\<C> c = 1 / real (card \\<K>)\" by auto\n  then show ?thesis using pmc_card_k[OF assms] by simp\nqed\n\nend\n", "meta": {"author": "01mf02", "repo": "interactive-theorem-proving", "sha": "7533b3d57e0ccd0dcf29a10373186e73fdc96e60", "save_path": "github-repos/isabelle/01mf02-interactive-theorem-proving", "path": "github-repos/isabelle/01mf02-interactive-theorem-proving/interactive-theorem-proving-7533b3d57e0ccd0dcf29a10373186e73fdc96e60/OneTimePad.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8824278664544912, "lm_q2_score": 0.8080672158638527, "lm_q1q2_score": 0.7130610292465603}}
{"text": "theory sort_HSortIsSort\nimports Main\n        \"$HIPSTER_HOME/IsaHipster\"\nbegin\n\ndatatype 'a list = Nil2 | Cons2 \"'a\" \"'a list\"\n\ndatatype 'a Heap = Node \"'a Heap\" \"'a\" \"'a Heap\" | Nil2\n\nfun toHeap2 :: \"int list => (int Heap) list\" where\n\"toHeap2 (Nil2) = Nil2\"\n| \"toHeap2 (Cons2 y z) = Cons2 (Node (Nil2) y (Nil2)) (toHeap2 z)\"\n\nfun insert2 :: \"int => int list => int list\" where\n\"insert2 x (Nil2) = Cons2 x (Nil2)\"\n| \"insert2 x (Cons2 z xs) =\n     (if x <= z then Cons2 x (Cons2 z xs) else Cons2 z (insert2 x xs))\"\n\nfun isort :: \"int list => int list\" where\n\"isort (Nil2) = Nil2\"\n| \"isort (Cons2 y xs) = insert2 y (isort xs)\"\n\nfun hmerge :: \"int Heap => int Heap => int Heap\" where\n\"hmerge (Node z x2 x3) (Node x4 x5 x6) =\n   (if 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) (Nil2) = Node z x2 x3\"\n| \"hmerge (Nil2) y = y\"\n\nfun hpairwise :: \"(int Heap) list => (int Heap) list\" where\n\"hpairwise (Nil2) = Nil2\"\n| \"hpairwise (Cons2 p (Nil2)) = Cons2 p (Nil2)\"\n| \"hpairwise (Cons2 p (Cons2 q qs)) =\n     Cons2 (hmerge p q) (hpairwise qs)\"\n\nfun hmerging :: \"(int Heap) list => int Heap\" where\n\"hmerging (Nil2) = Nil2\"\n| \"hmerging (Cons2 p (Nil2)) = p\"\n| \"hmerging (Cons2 p (Cons2 z x2)) =\n     hmerging (hpairwise (Cons2 p (Cons2 z x2)))\"\n\nfun toHeap :: \"int list => int Heap\" where\n\"toHeap x = hmerging (toHeap2 x)\"\n\nfun toList :: \"int Heap => int list\" where\n\"toList (Node p y q) = Cons2 y (toList (hmerge p q))\"\n| \"toList (Nil2) = Nil2\"\n\nfun dot :: \"('b => 'c) => ('a => 'b) => 'a => 'c\" where\n\"dot x y z = x (y z)\"\n\nfun hsort :: \"int list => int list\" where\n\"hsort x =\n   dot\n     (% (y :: int Heap) => toList y) (% (z :: int list) => toHeap z) x\"\n\n(*hipster toHeap2\n          insert2\n          isort\n          hmerge\n          hpairwise\n          hmerging\n          toHeap\n          toList\n          dot\n          hsort *)\n\ntheorem x0 :\n  \"!! (x :: int list) . (hsort x) = (isort 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/koen/sort_HSortIsSort.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278540866548, "lm_q2_score": 0.8080672158638527, "lm_q1q2_score": 0.7130610192525172}}
{"text": "theory BinTree\nimports Main\n        \"$HIPSTER_HOME/IsaHipster\"\n\nbegin\n\ndatatype 'a binTree = Leaf 'a | Node 'a \"('a binTree)\" \"('a binTree)\"\n\nfun is_leaf :: \"'a binTree \\<Rightarrow> bool\" where\n  \"is_leaf (Leaf _)     = True\"\n| \"is_leaf (Node _ _ _) = False\"\n\nfun mirror :: \"'a binTree \\<Rightarrow> 'a binTree\" where\n  \"mirror (Leaf b)     = Leaf b\"\n| \"mirror (Node b l r) = Node b (mirror r) (mirror l)\"\n\nfun tree_size :: \"'a binTree \\<Rightarrow> nat\" where\n  \"tree_size (Leaf b)     = 1\"\n| \"tree_size (Node _ l r) = 1 + tree_size l + tree_size r\"\n\nfun tree_height :: \"'a binTree \\<Rightarrow> nat\" where\n  \"tree_height (Leaf _)     = 1\"\n| \"tree_height (Node _ l r) = 1 + max (tree_height l) (tree_height r)\"\n\nfun flat_tree :: \"'a binTree \\<Rightarrow> 'a list\" where\n  \"flat_tree (Leaf b)     = [b]\"\n| \"flat_tree (Node b l r) = (flat_tree l) @  (b # (flat_tree r))\"\n\n(* http://www.labri.fr/perso/casteran/FM/Logique/C4.pdf *)\nlemma tree_decompose : \"tree_size t \\<noteq> 1 \\<Longrightarrow> \\<exists> n l r . t = Node n l r\"\nby (metis tree_size.elims)  (* reminder: should fiddle with our metis wrapper/routine tacs *)\n(* by hipster_induct_simp_metis *)\n\nlemma le_height_size : \"tree_height t \\<le> tree_size t\"\nby hipster_induct_simp_metis\n(* ----- *)\n\nlemma lemma_a [thy_expl]: \"mirror (mirror x2) = x2\"\nby hipster_induct_schemes\n\nlemma mirrorRev : \"rev (flat_tree t) = flat_tree (mirror t)\"\nby hipster_induct_simp_metis\n\nfun notNil :: \"'a list \\<Rightarrow> bool\" where\n  \"notNil [] = False\"\n| \"notNil _  = True\"\n\nfun rigthmost :: \"'a binTree \\<Rightarrow> 'a\" where \n  \"rigthmost (Leaf b)     = b\"\n| \"rigthmost (Node b l r) = rigthmost r\"\n\nfun leftmost :: \"'a binTree \\<Rightarrow> 'a\" where \n  \"leftmost (Leaf b)     = b\"\n| \"leftmost (Node b l r) = leftmost l\"\n\nlemma lemma_aa [thy_expl]: \"hd (xs2 @ xs2) = hd xs2\"\nby (hipster_induct_schemes BinTree.notNil.simps BinTree.flat_tree.simps)\n\nlemma lemma_ab [thy_expl]: \"notNil (xs2 @ xs2) = notNil xs2\"\nby (hipster_induct_schemes BinTree.notNil.simps BinTree.flat_tree.simps)\n\n(* did not discover or do we remov Nil_is_append_conv? *)\nlemma notNApp [thy_expl]: \"notNil (xs @ ys) = notNil (ys @ xs)\"\nby (hipster_induct_simp_metis notNil.elims Nil_is_append_conv)\n\nlemma flatInhabited [thy_expl]: \"flat_tree t \\<noteq> []\"\nby hipster_induct_simp_metis\n\nlemma unproved : \"hd (flat_tree x) = leftmost x\"\nby hipster_induct_simp_metis\n\nlemma sizeLen : \"tree_size t = length (flat_tree t)\"\nby hipster_induct_simp_metis\n\ndatatype nTree = Stop | Inner nat nTree nTree\n\nfun insertT :: \"nat \\<Rightarrow> nTree \\<Rightarrow> nTree\" where\n  \"insertT n Stop          = Inner n Stop Stop\"\n| \"insertT n (Inner m l r) = (if n < m then Inner m (insertT n l) r\n                                       else Inner m l (insertT n r))\"\n\nfun nHeight :: \"nTree \\<Rightarrow> nat\" where\n  \"nHeight Stop          = 0\"\n| \"nHeight (Inner _ l r) = 1 + max (nHeight l) (nHeight r)\"\n\nfun flatten :: \"nTree \\<Rightarrow> nat list\" where\n  \"flatten Stop = []\"\n| \"flatten (Inner n l r) = flatten l @ n # flatten r\"\n\ndatatype 'a graph = GNode 'a \"(('a graph) list)\" (* coinduct ... *)\n\nthm graph.induct\n\n\n  declare [[show_types]]\n  declare [[show_sorts]]\n  declare [[show_consts]]\n\nfun ack :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\" where\n  \"ack 0 n = n + 1\"\n| \"ack m 0 = ack (m - 1) 1\"\n| \"ack m n = ack (m - 1) (ack m (n - 1))\"\n\nfun ack2 :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> nat\" where\n  \"ack2 m n 0 = m + n\"\n| \"ack2 m 0 (Suc 0) = 0\"\n| \"ack2 m 0 (Suc (Suc 0)) = 1\"\n| \"ack2 m 0 p = m\"\n| \"ack2 m n p = ack2 m (ack2 m (n - 1) p) (p - 1)\"\n\nend\n\n", "meta": {"author": "moajohansson", "repo": "IsaHipster", "sha": "91f6ea3f1166a9de547722ece6445fe843ad89b4", "save_path": "github-repos/isabelle/moajohansson-IsaHipster", "path": "github-repos/isabelle/moajohansson-IsaHipster/IsaHipster-91f6ea3f1166a9de547722ece6445fe843ad89b4/TestTheories/BinTree.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8933094060543487, "lm_q2_score": 0.7981867825403177, "lm_q1q2_score": 0.7130277606315228}}
{"text": "header {* First Example *}\n\ntheory %invisible First_Example\nimports Main\nbegin\n\ntext {* \\label{chap:exampleI} *}\n\ntext {* Pop-refinement is illustrated via a simple derivation,\nin Isabelle/HOL,\nof a program that includes non-functional aspects. *}\n\n\nsection {* Target Programming Language *}\ntext {* \\label{sec:targetI} *}\n\ntext {* In the target language used in this example,\na program consists of\na list of distinct variables (the parameters of the program)\nand an arithmetic expression (the body of the program).\nThe body is built out of\nparameters,\nnon-negative integer constants,\naddition operations,\nand doubling (i.e.\\ multiplication by 2) operations.\nThe program is executed\nby supplying non-negative integers to the parameters\nand evaluating the body to obtain a non-negative integer result. *}\n\ntext {* For instance, executing the program\n\\begin{verbatim}\n  prog (a,b) {3 + 2 * (a + b)}\n\\end{verbatim}\nwith 5 and 7 supplied to \\verb|a| and \\verb|b| yields 27.\nThe syntax and semantics of this language are formalized as follows. *}\n\n\nsubsection {* Syntax *}\ntext {* \\label{sec:syntaxI} *}\n\ntext {* Variables are identified by names. *}\n\ntype_synonym name = string\n\ntext {* Expressions are built out of\nconstants, variables, doubling operations, and addition operations. *}\n\ndatatype expr = Const nat | Var name | Double expr | Add expr expr\n\ntext {* A program consists of\na list of parameter variables and a body expression. *}\n\nrecord prog =\n para :: \"name list\"\n body :: expr\n\n\nsubsection {* Static Semantics *}\ntext {* \\label{sec:staticI} *}\n\ntext {* A context is a set of variables. *}\n\ntype_synonym ctxt = \"name set\"\n\ntext {* Given a context,\nan expression is well-formed iff\\\nall its variables are in the context. *}\n\nfun wfe :: \"ctxt \\<Rightarrow> expr \\<Rightarrow> bool\"\nwhere\n  \"wfe \\<Gamma> (Const c) \\<longleftrightarrow> True\" |\n  \"wfe \\<Gamma> (Var v) \\<longleftrightarrow> v \\<in> \\<Gamma>\" |\n  \"wfe \\<Gamma> (Double e) \\<longleftrightarrow> wfe \\<Gamma> e\" |\n  \"wfe \\<Gamma> (Add e\\<^sub>1 e\\<^sub>2) \\<longleftrightarrow> wfe \\<Gamma> e\\<^sub>1 \\<and> wfe \\<Gamma> e\\<^sub>2\"\n\ntext {* The context of a program consists of the parameters. *}\n\ndefinition ctxt :: \"prog \\<Rightarrow> ctxt\"\nwhere \"ctxt p \\<equiv> set (para p)\"\n\ntext {* A program is well-formed iff\\\nthe parameters are distinct\nand the body is well-formed in the context of the program. *}\n\ndefinition wfp :: \"prog \\<Rightarrow> bool\"\nwhere \"wfp p \\<equiv> distinct (para p) \\<and> wfe (ctxt p) (body p)\"\n\n\nsubsection {* Dynamic Semantics *}\ntext {* \\label{sec:dynamicI} *}\n\ntext {* An environment associates values (non-negative integers)\nto variables. *}\n\ntype_synonym env = \"name \\<rightharpoonup> nat\"\n\ntext {* An environment matches a context iff\\\nenvironment and context have the same variables. *}\n\ndefinition match :: \"env \\<Rightarrow> ctxt \\<Rightarrow> bool\"\nwhere \"match \\<E> \\<Gamma> \\<equiv> dom \\<E> = \\<Gamma>\"\n\ntext {* Evaluating an expression in an environment yields a value,\nor an error (@{const None})\nif the expression contains a variable not in the environment. *}\n\ndefinition mul_opt :: \"nat option \\<Rightarrow> nat option \\<Rightarrow> nat option\" (infixl \"\\<otimes>\" 70)\n-- {* Lifting of multiplication to @{typ \"nat option\"}. *}\nwhere \"U\\<^sub>1 \\<otimes> U\\<^sub>2 \\<equiv>\n  case (U\\<^sub>1, U\\<^sub>2) of (Some u\\<^sub>1, Some u\\<^sub>2) \\<Rightarrow> Some (u\\<^sub>1 * u\\<^sub>2) | _ \\<Rightarrow> None\"\n\ndefinition add_opt :: \"nat option \\<Rightarrow> nat option \\<Rightarrow> nat option\" (infixl \"\\<oplus>\" 65)\n-- {* Lifting of addition to @{typ \"nat option\"}. *}\nwhere \"U\\<^sub>1 \\<oplus> U\\<^sub>2 \\<equiv>\n  case (U\\<^sub>1, U\\<^sub>2) of (Some u\\<^sub>1, Some u\\<^sub>2) \\<Rightarrow> Some (u\\<^sub>1 + u\\<^sub>2) | _ \\<Rightarrow> None\"\n\nfun eval :: \"env \\<Rightarrow> expr \\<Rightarrow> nat option\"\nwhere\n  \"eval \\<E> (Const c) = Some c\" |\n  \"eval \\<E> (Var v) = \\<E> v\" |\n  \"eval \\<E> (Double e) = Some 2 \\<otimes> eval \\<E> e\" |\n  \"eval \\<E> (Add e\\<^sub>1 e\\<^sub>2) = eval \\<E> e\\<^sub>1 \\<oplus> eval \\<E> e\\<^sub>2\"\n\ntext {* Evaluating a well-formed expression never yields an error,\nif the environment matches the context. *}\n\nlemma eval_wfe:\n  \"wfe \\<Gamma> e \\<Longrightarrow> match \\<E> \\<Gamma> \\<Longrightarrow> eval \\<E> e \\<noteq> None\"\nby (induct e, auto simp: match_def mul_opt_def add_opt_def)\n\ntext {* The environments of a program\nare the ones that match the context of the program. *}\n\ndefinition envs :: \"prog \\<Rightarrow> env set\"\nwhere \"envs p \\<equiv> {\\<E>. match \\<E> (ctxt p)}\"\n\ntext {* Evaluating the body of a well-formed program\nin an environment of the program\nnever yields an error. *}\n\nlemma eval_wfp:\n  \"wfp p \\<Longrightarrow> \\<E> \\<in> envs p \\<Longrightarrow> eval \\<E> (body p) \\<noteq> None\"\nby (metis envs_def eval_wfe mem_Collect_eq wfp_def)\n\ntext {* Executing a program with values supplied to the parameters\nyields a non-negative integer result,\nor an error (@{const None})\nif the parameters are not distinct,\nthe number of supplied values differs from the number of parameters,\nor the evaluation of the body yields an error. *}\n\ndefinition supply :: \"prog \\<Rightarrow> nat list \\<Rightarrow> env option\"\nwhere \"supply p us \\<equiv>\n  let vs = para p in\n  if distinct vs \\<and> length us = length vs\n  then Some (map_of (zip vs us))\n  else None\"\n\ndefinition exec :: \"prog \\<Rightarrow> nat list \\<Rightarrow> nat option\"\nwhere \"exec p us \\<equiv>\n  case supply p us of Some \\<E> \\<Rightarrow> eval \\<E> (body p) | None \\<Rightarrow> None\"\n\ntext {* Executing a well-formed program\nwith the same number of values as the number of parameters\nnever yields an error. *}\n\nlemma supply_wfp: \"\n  wfp p \\<Longrightarrow>\n  length us = length (para p) \\<Longrightarrow>\n  \\<exists>\\<E> \\<in> envs p. supply p us = Some \\<E>\"\nby (auto\n simp: wfp_def supply_def envs_def ctxt_def match_def split: option.split)\n\nlemma exec_wfp:\n  \"wfp p \\<Longrightarrow> length us = length (para p) \\<Longrightarrow> exec p us \\<noteq> None\"\nby (metis eval_wfp exec_def option.simps(5) supply_wfp)\n\n\nsubsection {* Performance *}\ntext {* \\label{sec:nonfunc} *}\n\ntext {* As a non-functional semantic aspect,\nthe cost (e.g.\\ time and power) to execute a program\nis modeled as the number of doubling and addition operations. *}\n\nfun coste :: \"expr \\<Rightarrow> nat\"\nwhere\n  \"coste (Const c) = 0\" |\n  \"coste (Var v) = 0\" |\n  \"coste (Double e) = 1 + coste e\" |\n  \"coste (Add e\\<^sub>1 e\\<^sub>2) = 1 + coste e\\<^sub>1 + coste e\\<^sub>2\"\n\ndefinition costp :: \"prog \\<Rightarrow> nat\"\nwhere \"costp p \\<equiv> coste (body p)\"\n\n\nsection {* Requirement Specification *}\ntext {* \\label{sec:specificationI} *}\n\ntext {* The target program must:\n\\begin{enumerate}\n\\item\nBe well-formed.\n\\item\nHave exactly the two parameters @{term \"''x''\"} and @{term \"''y''\"},\nin this order.\n\\item\nProduce the result @{term \"f x y\"}\nwhen @{term x} and @{term y}\nare supplied to @{term \"''x''\"} and @{term \"''y''\"},\nwhere @{term f} is defined below.\n\\item\nNot exceed cost 3.\n\\end{enumerate} *}\n\ndefinition f :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\"\nwhere \"f x y \\<equiv> 3 * x + 2 * y\"\n\ndefinition spec\\<^sub>0 :: \"prog \\<Rightarrow> bool\"\nwhere \"spec\\<^sub>0 p \\<equiv>\n  wfp p \\<and>\n  para p = [''x'', ''y''] \\<and>\n  (\\<forall>x y. exec p [x, y] = Some (f x y)) \\<and>\n  costp p \\<le> 3\"\n\ntext {* @{const f} is used by @{const spec\\<^sub>0}\nto express a functional requirement on the execution of the program.\n@{const spec\\<^sub>0} includes\nthe non-functional requirement @{term \"costp(p) \\<le> 3\"}\nand the syntactic interface requirement @{term \"para(p) = [''x'', ''y'']\"},\nwhich are not expressed by @{const f} alone\nand are expressible only in terms of programs.\n@{const f} can be computed by a program\nwith cost higher than 3\nand with more or different parameters;\nit can also be computed by programs in different target languages. *}\n\n\nsection {* Stepwise Refinement *}\ntext {* \\label{sec:refinementI} *}\n\ntext {* It is not difficult\nto write a program that satisfies @{const spec\\<^sub>0} and to prove that it does.\nBut with more complex target languages and requirement specifications,\nwriting a program and proving that it satisfies the requirements\nis notoriously difficult.\nStepwise refinement decomposes the proof into manageable pieces,\nconstructing the implementation along the way.\nThe following sequence of refinement steps\nmay be overkill for obtaining an implementation of @{const spec\\<^sub>0},\nbut illustrates concepts that should apply to more complex cases. *}\n\n\nsubsection {* Step 1 *}\ntext {* \\label{sec:refI:stepI} *}\n\ntext {* The second conjunct in @{const spec\\<^sub>0} determines the parameters,\nleaving only the body to be determined.\nThat conjunct also reduces\nthe well-formedness of the program to the well-formedness of the body,\nand the execution of the program to the evaluation of the body. *}\n\nabbreviation \\<Gamma>\\<^sub>x\\<^sub>y :: ctxt\nwhere \"\\<Gamma>\\<^sub>x\\<^sub>y \\<equiv> {''x'', ''y''}\"\n\nabbreviation \\<E>\\<^sub>x\\<^sub>y :: \"nat \\<Rightarrow> nat \\<Rightarrow> env\"\nwhere \"\\<E>\\<^sub>x\\<^sub>y x y \\<equiv> [''x'' \\<mapsto> x, ''y'' \\<mapsto> y]\"\n\nlemma reduce_prog_to_body: \"\n  para p = [''x'', ''y''] \\<Longrightarrow>\n  wfp p = wfe \\<Gamma>\\<^sub>x\\<^sub>y (body p) \\<and>\n  exec p [x, y] = eval (\\<E>\\<^sub>x\\<^sub>y x y) (body p)\"\nby (auto simp: wfp_def ctxt_def exec_def supply_def fun_upd_twist)\n\ntext {* Using lemma @{text reduce_prog_to_body},\nand using the definition of @{const costp}\nto reduce the cost of the program to the cost of the body,\n@{const spec\\<^sub>0} is refined as follows. *}\n\ndefinition spec\\<^sub>1 :: \"prog \\<Rightarrow> bool\"\nwhere \"spec\\<^sub>1 p \\<equiv>\n  wfe \\<Gamma>\\<^sub>x\\<^sub>y (body p) \\<and>\n  para p = [''x'', ''y''] \\<and>\n  (\\<forall>x y. eval (\\<E>\\<^sub>x\\<^sub>y x y) (body p) = Some (f x y)) \\<and>\n  coste (body p) \\<le> 3\"\n\nlemma step_1_correct:\n \"spec\\<^sub>1 p \\<Longrightarrow> spec\\<^sub>0 p\"\nby (auto simp: spec\\<^sub>1_def spec\\<^sub>0_def reduce_prog_to_body costp_def)\n\ntext {* @{const spec\\<^sub>1} and @{const spec\\<^sub>0} are actually equivalent,\nbut the definition of @{const spec\\<^sub>1} is ``closer'' to the implementation\nthan the definition of @{const spec\\<^sub>0}:\nthe latter states constraints on the whole program,\nwhile the former states simpler constraints on the body,\ngiven that the parameters are already determined.\nThe proof of @{text step_1_correct}\ncan also be used to prove the equivalence of @{const spec\\<^sub>1} and @{const spec\\<^sub>0},\nbut in general proving inclusion is easier than proving equivalence.\nSome of the following refinement steps yield non-equivalent predicates. *}\n\n\nsubsection {* Step 2 *}\ntext {* \\label{sec:refI:stepII} *}\n\ntext {* The third conjunct in @{const spec\\<^sub>1} says that\nthe body computes @{term \"f x y\"},\nwhich depends on both @{term x} and @{term y},\nand which yields an odd result for some values of @{term x} and @{term y}.\nThus the body cannot be a constant, a variable, or a double,\nleaving a sum as the only option.\nAdding @{term \"\\<exists>e\\<^sub>1 e\\<^sub>2. body p = Add e\\<^sub>1 e\\<^sub>2\"} as a conjunct to @{const spec\\<^sub>1}\nand re-arranging the other conjuncts,\nmoving some of them under the existential quantification\nso that they can be simplified in the next refinement step,\n@{const spec\\<^sub>1} is refined as follows. *}\n\ndefinition spec\\<^sub>2 :: \"prog \\<Rightarrow> bool\"\nwhere \"spec\\<^sub>2 p \\<equiv>\n  para p = [''x'', ''y''] \\<and>\n  (\\<exists>e\\<^sub>1 e\\<^sub>2.\n    body p = Add e\\<^sub>1 e\\<^sub>2 \\<and>\n    wfe \\<Gamma>\\<^sub>x\\<^sub>y (body p) \\<and>\n    (\\<forall>x y. eval (\\<E>\\<^sub>x\\<^sub>y x y) (body p) = Some (f x y)) \\<and>\n    coste (body p) \\<le> 3)\"\n\nlemma step_2_correct:\n \"spec\\<^sub>2 p \\<Longrightarrow> spec\\<^sub>1 p\"\nby (auto simp: spec\\<^sub>2_def spec\\<^sub>1_def)\n\ntext {* This refinement step is guided by an analysis\nof the constraints in @{const spec\\<^sub>1}. *}\n\n\nsubsection {* Step 3 *}\ntext {* \\label{sec:refI:stepIII} *}\n\ntext {* The fact that the body is a sum\nreduces the well-formedness, evaluation, and cost of the body\nto the well-formedness, evaluation, and cost of the addends. *}\n\nlemma reduce_body_to_addends: \"\n  body p = Add e\\<^sub>1 e\\<^sub>2 \\<Longrightarrow>\n  wfe \\<Gamma>\\<^sub>x\\<^sub>y (body p) = (wfe \\<Gamma>\\<^sub>x\\<^sub>y e\\<^sub>1 \\<and> wfe \\<Gamma>\\<^sub>x\\<^sub>y e\\<^sub>2) \\<and>\n  eval (\\<E>\\<^sub>x\\<^sub>y x y) (body p) = eval (\\<E>\\<^sub>x\\<^sub>y x y) e\\<^sub>1 \\<oplus> eval (\\<E>\\<^sub>x\\<^sub>y x y) e\\<^sub>2 \\<and>\n  coste (body p) = 1 + coste e\\<^sub>1 + coste e\\<^sub>2\"\nby auto\n\ntext {* Using @{text reduce_body_to_addends}\nand arithmetic simplification,\n@{const spec\\<^sub>2} is refined as follows. *}\n\ndefinition spec\\<^sub>3 :: \"prog \\<Rightarrow> bool\"\nwhere \"spec\\<^sub>3 p \\<equiv>\n  para p = [''x'', ''y''] \\<and>\n  (\\<exists>e\\<^sub>1 e\\<^sub>2.\n    body p = Add e\\<^sub>1 e\\<^sub>2 \\<and>\n    wfe \\<Gamma>\\<^sub>x\\<^sub>y e\\<^sub>1 \\<and>\n    wfe \\<Gamma>\\<^sub>x\\<^sub>y e\\<^sub>2 \\<and>\n    (\\<forall>x y. eval (\\<E>\\<^sub>x\\<^sub>y x y) e\\<^sub>1 \\<oplus> eval (\\<E>\\<^sub>x\\<^sub>y x y) e\\<^sub>2 = Some (f x y)) \\<and>\n    coste e\\<^sub>1 + coste e\\<^sub>2 \\<le> 2)\"\n\nlemma step_3_correct:\n  \"spec\\<^sub>3 p \\<Longrightarrow> spec\\<^sub>2 p\"\nby (auto simp: spec\\<^sub>3_def spec\\<^sub>2_def)\n-- {* No need to use @{text reduce_body_to_addends} explicitly, *}\n-- {* as the default rules that @{text auto} uses to prove it apply here too. *}\n\ntext {* This refinement step\ndefines the top-level structure of the body,\nreducing the constraints on the body\nto simpler constraints on its components. *}\n\n\nsubsection {* Step 4 *}\ntext {* \\label{sec:refI:stepIV} *}\n\ntext {* The second-to-last conjunct in @{const spec\\<^sub>3}\nsuggests to split @{term \"f x y\"} into two addends\nto be computed by @{term e\\<^sub>1} and @{term e\\<^sub>2}. *}\n\ntext {* The addends @{term \"(3::nat) * x\"} and @{term \"(2::nat) * y\"}\nsuggested by the definition of @{const f}\nwould lead to a blind alley,\nwhere the cost constraints could not be satisfied---%\nthe resulting @{term spec\\<^sub>4} would be always false.\nThe refinement step would be ``correct'' (by strict inclusion)\nbut the refinement sequence could never reach an implementation.\nIt would be necessary to backtrack to @{const spec\\<^sub>3}\nand split @{term \"f x y\"} differently. *}\n\ntext {* To avoid the blind alley,\nthe definition of @{const f} is rephrased as follows. *}\n\nlemma f_rephrased:\n  \"f x y = x + (2 * x + 2 * y)\"\nby (auto simp: f_def)\n\ntext {* This rephrased definition of @{const f}\ndoes not use the multiplication by 3 of the original definition,\nwhich is not (directly) supported by the target language;\nit only uses operations supported by the language. *}\n\ntext {* Using @{text f_rephrased}, @{const spec\\<^sub>3} is refined as follows. *}\n\ndefinition spec\\<^sub>4 :: \"prog \\<Rightarrow> bool\"\nwhere \"spec\\<^sub>4 p \\<equiv>\n  para p = [''x'', ''y''] \\<and>\n  (\\<exists>e\\<^sub>1 e\\<^sub>2.\n    body p = Add e\\<^sub>1 e\\<^sub>2 \\<and>\n    wfe \\<Gamma>\\<^sub>x\\<^sub>y e\\<^sub>1 \\<and>\n    wfe \\<Gamma>\\<^sub>x\\<^sub>y e\\<^sub>2 \\<and>\n    (\\<forall>x y. eval (\\<E>\\<^sub>x\\<^sub>y x y) e\\<^sub>1 = Some x) \\<and>\n    (\\<forall>x y. eval (\\<E>\\<^sub>x\\<^sub>y x y) e\\<^sub>2 = Some (2 * x + 2 * y)) \\<and>\n    coste e\\<^sub>1 + coste e\\<^sub>2 \\<le> 2)\"\n\nlemma step_4_correct:\n  \"spec\\<^sub>4 p \\<Longrightarrow> spec\\<^sub>3 p\"\nby (auto simp: spec\\<^sub>4_def spec\\<^sub>3_def add_opt_def f_rephrased)\n\ntext {* This refinement step reduces\nthe functional constraint on the body\nto simpler functional constraints on the addends.\nThe functional constraint can be decomposed in different ways,\nsome of which are incompatible with the non-functional cost constraint:\nblind alleys are avoided\nby taking the non-functional constraint into account. *}\n\n\nsubsection {* Step 5 *}\ntext {* \\label{sec:refI:stepV} *}\n\ntext {* The term @{term x}\nin the third-to-last conjunct in @{const spec\\<^sub>4}\nis a shallow embedding of the program expression \\verb|x|,\nwhose deep embedding is the term @{term \"Var ''x''\"}.\nUsing the latter as @{term e\\<^sub>1},\nthe third-to-last conjunct in @{const spec\\<^sub>4} is satisfied;\nthe expression is well-formed and has cost 0. *}\n\nlemma first_addend: \"\n  e\\<^sub>1 = Var ''x'' \\<Longrightarrow>\n  eval (\\<E>\\<^sub>x\\<^sub>y x y) e\\<^sub>1 = Some x \\<and>\n  wfe \\<Gamma>\\<^sub>x\\<^sub>y e\\<^sub>1 \\<and>\n  coste e\\<^sub>1 = 0\"\nby auto\n\ntext {* Adding @{term \"e\\<^sub>1 = Var ''x''\"} as a conjunct to @{const spec\\<^sub>4}\nand simplifying,\n@{const spec\\<^sub>4} is refined as follows. *}\n\ndefinition spec\\<^sub>5 :: \"prog \\<Rightarrow> bool\"\nwhere \"spec\\<^sub>5 p \\<equiv>\n  para p = [''x'', ''y''] \\<and>\n  (\\<exists>e\\<^sub>2.\n    body p = Add (Var ''x'') e\\<^sub>2 \\<and>\n    wfe \\<Gamma>\\<^sub>x\\<^sub>y e\\<^sub>2 \\<and>\n    (\\<forall>x y. eval (\\<E>\\<^sub>x\\<^sub>y x y) e\\<^sub>2 = Some (2 * x + 2 * y)) \\<and>\n    coste e\\<^sub>2 \\<le> 2)\"\n\nlemma step_5_correct:\n  \"spec\\<^sub>5 p \\<Longrightarrow> spec\\<^sub>4 p\"\nby (auto simp: spec\\<^sub>5_def spec\\<^sub>4_def)\n-- {* No need to use @{text first_addend} explicitly, *}\n-- {* as the default rules that @{text auto} uses to prove it apply here too. *}\n\ntext {* This refinement step determines the first addend of the body,\nleaving only the second addend to be determined. *}\n\n\nsubsection {* Step 6 *}\ntext {* \\label{sec:refI:stepVI} *}\n\ntext {* The term @{term \"(2::nat) * x + 2 * y\"}\nin the second-to-last conjunct of @{const spec\\<^sub>5}\nis a shallow embedding of the program expression \\verb|2 * x + 2 * y|,\nwhose deep embedding is the term\n@{term \"Add (Double (Var ''x'')) (Double (Var ''y''))\"}.\nUsing the latter as @{term e\\<^sub>2},\nthe second-to-last conjunct in @{const spec\\<^sub>5} is satisfied,\nbut the last conjunct is not.\nThe following factorization of the shallowly embedded expression\nleads to a reduced cost of the corresponding deeply embedded expression. *}\n\nlemma factorization:\n  \"(2::nat) * x + 2 * y = 2 * (x + y)\"\nby auto\n\ntext {* The deeply embedded expression\n@{term \"Double (Add (Var ''x'') (Var ''y''))\"},\nwhich corresponds to the shallowly embedded expression\n@{term \"(2::nat) * (x + y)\"},\nsatisfies the second-to-last conjunct of @{const spec\\<^sub>5},\nis well-formed,\nand has cost 2. *}\n\nlemma second_addend: \"\n  e\\<^sub>2 = Double (Add (Var ''x'') (Var ''y'')) \\<Longrightarrow>\n  eval (\\<E>\\<^sub>x\\<^sub>y x y) e\\<^sub>2 = Some (2 * x + 2 * y) \\<and>\n  wfe \\<Gamma>\\<^sub>x\\<^sub>y e\\<^sub>2 \\<and>\n  coste e\\<^sub>2 = 2\"\nby (auto simp: add_opt_def mul_opt_def)\n-- {* No need to use @{text factorization} explicitly, *}\n-- {* as the default rules that @{text auto} uses to prove it apply here too. *}\n\ntext {* Adding @{term \"e\\<^sub>2 = Double (Add (Var ''x'') (Var ''y''))\"}\nas a conjunct to @{const spec\\<^sub>5}\nand simplifying,\n@{const spec\\<^sub>5} is refined as follows. *}\n\ndefinition spec\\<^sub>6 :: \"prog \\<Rightarrow> bool\"\nwhere \"spec\\<^sub>6 p \\<equiv>\n  para p = [''x'', ''y''] \\<and>\n  body p = Add (Var ''x'') (Double (Add (Var ''x'') (Var ''y'')))\"\n\nlemma step_6_correct:\n  \"spec\\<^sub>6 p \\<Longrightarrow> spec\\<^sub>5 p\"\nby (auto simp add: spec\\<^sub>6_def spec\\<^sub>5_def second_addend simp del: eval.simps)\n\ntext {* This refinement step determines the second addend of the body,\nleaving nothing else to be determined. *}\n\ntext {* This and the previous refinement step\nturn semantic constraints on the program components @{term e\\<^sub>1} and @{term e\\<^sub>2}\ninto syntactic definitions of such components. *}\n\n\nsubsection {* Step 7 *}\ntext {* \\label{sec:refI:stepVII} *}\n\ntext {* @{const spec\\<^sub>6}, which defines the parameters and body,\nis refined to characterize a unique program in explicit syntactic form. *}\n\nabbreviation p\\<^sub>0 :: prog\nwhere \"p\\<^sub>0 \\<equiv>\n  \\<lparr>para = [''x'', ''y''],\n   body = Add (Var ''x'') (Double (Add (Var ''x'') (Var ''y'')))\\<rparr>\"\n\ndefinition spec\\<^sub>7 :: \"prog \\<Rightarrow> bool\"\nwhere \"spec\\<^sub>7 p \\<equiv> p = p\\<^sub>0\"\n\nlemma step_7_correct:\n  \"spec\\<^sub>7 p \\<Longrightarrow> spec\\<^sub>6 p\"\nby (auto simp: spec\\<^sub>7_def spec\\<^sub>6_def)\n\ntext {* The program satisfies @{const spec\\<^sub>0} by construction.\nThe program witnesses the consistency of the requirements,\ni.e.\\ the fact that @{const spec\\<^sub>0} is not always false. *}\n\nlemma p\\<^sub>0_sat_spec\\<^sub>0:\n  \"spec\\<^sub>0 p\\<^sub>0\"\nby (metis\n step_1_correct\n step_2_correct\n step_3_correct\n step_4_correct\n step_5_correct\n step_6_correct\n step_7_correct\n spec\\<^sub>7_def)\n\ntext {* From @{const p\\<^sub>0}, the program text\n\\begin{verbatim}\n  prog (x,y) {x + 2 * (x + y)}\n\\end{verbatim}\nis easily obtained. *}\n\n\nend %invisible\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/Pop_Refinement/First_Example.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8933094088947399, "lm_q2_score": 0.7981867729389246, "lm_q1q2_score": 0.7130277543216706}}
{"text": "theory Algebra\n  imports \"$AFP/Kleene_Algebra/Kleene_Algebra\" Fixpoint Omega_Algebra\nbegin\n\nnotation inf (infixl \"\\<sqinter>\" 70)\nnotation sup (infixl \"\\<squnion>\" 65)\n\nclass par_dioid = join_semilattice_zero + one +\n  fixes par :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a\" (infixl \"\\<parallel>\" 69)\n  assumes par_assoc [simp]: \"x \\<parallel> (y \\<parallel> z) = (x \\<parallel> y) \\<parallel> z\"\n  and par_comm: \"x \\<parallel> y = y \\<parallel> x\"\n  and par_distl [simp]: \"x \\<parallel> (y + z) = x \\<parallel> y + x \\<parallel> z\"\n  and par_unitl [simp]: \"1 \\<parallel> x = x\"\n  and par_annil [simp]: \"0 \\<parallel> x = 0\"\n\nbegin\n\n  lemma par_distr [simp]: \"(x+y) \\<parallel> z = x \\<parallel> z + y \\<parallel> z\" \n    by (metis par_comm par_distl)\n\n  lemma par_isol [intro]: \"x \\<le> y \\<Longrightarrow> x \\<parallel> z \\<le> y \\<parallel> z\"\n    by (metis order_prop par_distr)\n \n  lemma par_isor [intro]: \"x \\<le> y \\<Longrightarrow> z \\<parallel> x \\<le> z \\<parallel> y\"\n    by (metis par_comm par_isol)\n\n  lemma par_unitr [simp]: \"x \\<parallel> 1 = x\"\n    by (metis par_comm par_unitl)\n\n  lemma par_annir [simp]: \"x \\<parallel> 0 = 0\"\n    by (metis par_annil par_comm)\n\n  lemma par_subdistl: \"x \\<parallel> z \\<le> (x + y) \\<parallel> z\"\n    by (metis order_prop par_distr)\n\n  lemma par_subdistr: \"z \\<parallel> x \\<le> z \\<parallel> (x + y)\"\n    by (metis par_comm par_subdistl)\n\n  lemma par_double_iso [intro!]: \"w \\<le> x \\<Longrightarrow> y \\<le> z \\<Longrightarrow> w \\<parallel> y \\<le> x \\<parallel> z\"\n    by (metis order_trans par_isol par_isor)\n\nend\n\nclass weak_trioid = par_dioid + dioid_one_zerol\n\nclass trioid = par_dioid + left_kleene_algebra + residual_r_op +\n  fixes meet :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a\"  (infixl \"\\<otimes>\" 69)\n  assumes meet_leq: \"(x \\<le> y) \\<longleftrightarrow> (x = x \\<otimes> y)\"\n  and meet_assoc: \"(x \\<otimes> y) \\<otimes> z = x \\<otimes> (y \\<otimes> z)\"\n  and meet_sym: \"x \\<otimes> y = y \\<otimes> x\"\n  and preimp_galois: \"x \\<cdot> y \\<le> z \\<longleftrightarrow> y \\<le> x \\<rightarrow> z\"\n\nbegin\n\n  lemma meet_idem [simp]: \"x \\<otimes> x = x\"\n    by (metis local.meet_leq local.order_refl)\n\n  lemma meet_1 [simp]: \"x \\<otimes> y \\<le> y\"\n    by (simp add: meet_leq meet_assoc)\n\n  lemma meet_2 [simp]: \"y \\<otimes> x \\<le> y\"\n    by (metis local.meet_sym meet_1)\n\n  lemma preimp_isor: \"x \\<le> y \\<Longrightarrow> p \\<rightarrow> x \\<le> p \\<rightarrow> y\"\n    by (metis local.order.trans local.order_refl local.preimp_galois)\n\n  lemma meet_is_meet: \"x \\<le> y \\<otimes> z \\<longleftrightarrow> (x \\<le> y) \\<and> (x \\<le> z)\"\n    by (metis (poly_guards_query) local.meet_assoc local.meet_leq local.meet_sym meet_idem)\n\n  lemma meet_interchange: \"(x \\<otimes> y) \\<parallel> (z \\<otimes> w) \\<le> (x \\<parallel> z) \\<otimes> (y \\<parallel> w)\"\n    by (auto simp add: meet_is_meet)\n\n  lemma meet_iso: \"x \\<le> y \\<Longrightarrow> z \\<le> w \\<Longrightarrow> x \\<otimes> z \\<le> y \\<otimes> w\"\n    by (metis local.meet_leq meet_idem meet_is_meet)\n\n  lemma absorb1: \"x \\<otimes> (x + y) = x\"\n    by (rule antisym) (simp add: meet_is_meet)+\n    \n  lemma absorb2: \"x + (x \\<otimes> y) = x\"\n    by (metis add_commute local.less_eq_def meet_2)\n\nend \n\nlocale rg_algebra =\n  fixes rg :: \"'b::complete_lattice \\<Rightarrow> 'a::trioid \\<Rightarrow> 'a::trioid\" (infixr \"\\<rhd>\" 55)\n  and guar :: \"'b::complete_lattice \\<Rightarrow> 'a::trioid\"\n  assumes rely_mult: \"(r \\<rhd> x) \\<cdot> (r \\<rhd> y) \\<le> r \\<rhd> (x \\<cdot> y)\"\n  and rely_star: \"(r \\<rhd> x)\\<^sup>\\<star> \\<le> r \\<rhd> (x\\<^sup>\\<star>)\"\n  and rely_iso: \"x \\<le> y \\<Longrightarrow> r \\<rhd> x \\<le> r \\<rhd> y\"\n  and rely_coext: \"x \\<le> r \\<rhd> x\"\n  and rely_idem: \"r \\<rhd> r \\<rhd> x = r \\<rhd> x\"\n  and rely_anti: \"r \\<le> g \\<Longrightarrow> g \\<rhd> x \\<le> r \\<rhd> x\"\n  and guar_par: \"guar r \\<parallel> guar g \\<le> guar (r \\<squnion> g)\"\n  and guar_mult: \"guar r \\<cdot> guar g \\<le> guar (r \\<squnion> g)\"\n  and guar_star: \"(guar g)\\<^sup>\\<star> = guar g\"\n  and guar_meet: \"(x \\<otimes> guar g) \\<cdot> (y \\<otimes> guar g) = x\\<cdot>y \\<otimes> guar g\"\n  and rely_guarantee: \"(r \\<squnion> g\\<^sub>2 \\<rhd> x \\<otimes> guar g\\<^sub>1) \\<parallel> (r \\<squnion> g\\<^sub>1 \\<rhd> y \\<otimes> guar g\\<^sub>2) \\<le> r \\<rhd> (x \\<otimes> guar g\\<^sub>1) \\<parallel> (y \\<otimes> guar g\\<^sub>2)\"\n  and guar_iso: \"r \\<le> s \\<Longrightarrow> guar r \\<le> guar s\"\n\nbegin\n\ndefinition quintuple :: \"'b \\<Rightarrow> 'b \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> bool\" (\"_, _ \\<turnstile> \\<lbrace>_\\<rbrace> _ \\<lbrace>_\\<rbrace>\" [20,20,20,20,20] 1000) where\n    \"r, g \\<turnstile> \\<lbrace>p\\<rbrace> x \\<lbrace>q\\<rbrace> \\<equiv> (x \\<le> p \\<rightarrow> (r \\<rhd> q \\<otimes> guar g))\"\n\nlemma parallel_rule:\n  assumes test_interchange: \"\\<And>x y. (p\\<^sub>1 \\<rightarrow> x) \\<parallel> (p\\<^sub>2 \\<rightarrow> y) \\<le> (p\\<^sub>1 \\<otimes> p\\<^sub>2) \\<rightarrow> (x \\<parallel> y)\"\n  and test_post: \"(q\\<^sub>1 \\<parallel> q\\<^sub>2) \\<otimes> guar g \\<le> r \\<rhd> q\\<^sub>1 \\<otimes> q\\<^sub>2 \\<otimes> guar g\"\n  and \"r \\<squnion> g\\<^sub>1 \\<le> r\\<^sub>2\" and \"r \\<squnion> g\\<^sub>2 \\<le> r\\<^sub>1\"\n  and \"g\\<^sub>1 \\<squnion> g\\<^sub>2 \\<le> g\"\n  and left_prog: \"r\\<^sub>1, g\\<^sub>1 \\<turnstile> \\<lbrace>p\\<^sub>1\\<rbrace> x \\<lbrace>q\\<^sub>1\\<rbrace>\"\n  and right_prog: \"r\\<^sub>2, g\\<^sub>2 \\<turnstile> \\<lbrace>p\\<^sub>2\\<rbrace> y \\<lbrace>q\\<^sub>2\\<rbrace>\"\n  shows \"r, g \\<turnstile> \\<lbrace>p\\<^sub>1 \\<otimes> p\\<^sub>2\\<rbrace> x \\<parallel> y \\<lbrace>q\\<^sub>1 \\<otimes> q\\<^sub>2\\<rbrace>\"\nproof -\n  have \"x \\<parallel> y \\<le> (p\\<^sub>1 \\<rightarrow> (r\\<^sub>1 \\<rhd> q\\<^sub>1 \\<otimes> guar g\\<^sub>1)) \\<parallel> (p\\<^sub>2 \\<rightarrow> (r\\<^sub>2 \\<rhd> q\\<^sub>2 \\<otimes> guar g\\<^sub>2))\"\n    by (metis left_prog par_double_iso quintuple_def right_prog)\n  also have \"... \\<le> p\\<^sub>1 \\<otimes> p\\<^sub>2 \\<rightarrow> (r\\<^sub>1 \\<rhd> q\\<^sub>1 \\<otimes> guar g\\<^sub>1) \\<parallel> (r\\<^sub>2 \\<rhd> q\\<^sub>2 \\<otimes> guar g\\<^sub>2)\"\n    by (rule test_interchange)\n  also have \"... \\<le> p\\<^sub>1 \\<otimes> p\\<^sub>2 \\<rightarrow> (r \\<squnion> g\\<^sub>2 \\<rhd> q\\<^sub>1 \\<otimes> guar g\\<^sub>1) \\<parallel> (r \\<squnion> g\\<^sub>1 \\<rhd> q\\<^sub>2 \\<otimes> guar g\\<^sub>2)\"\n    by (metis assms(3) assms(4) par_double_iso preimp_isor rely_anti)\n  also have \"... \\<le> p\\<^sub>1 \\<otimes> p\\<^sub>2 \\<rightarrow> (r \\<rhd> (q\\<^sub>1 \\<otimes> guar g\\<^sub>1) \\<parallel> (q\\<^sub>2 \\<otimes> guar g\\<^sub>2))\"\n    by (metis preimp_isor rely_guarantee)\n  also have \"... \\<le> p\\<^sub>1 \\<otimes> p\\<^sub>2 \\<rightarrow> (r \\<rhd> (q\\<^sub>1 \\<parallel> q\\<^sub>2) \\<otimes> (guar g\\<^sub>1 \\<parallel> guar g\\<^sub>2))\"\n    by (intro preimp_isor rely_iso meet_interchange)\n  also have \"... \\<le> p\\<^sub>1 \\<otimes> p\\<^sub>2 \\<rightarrow> (r \\<rhd> (q\\<^sub>1 \\<parallel> q\\<^sub>2) \\<otimes> guar g)\"\n    by (metis (poly_guards_query) assms(5) guar_iso guar_par meet_2 meet_is_meet meet_sym order_trans preimp_isor rely_iso)\n  also have \"... \\<le> p\\<^sub>1 \\<otimes> p\\<^sub>2 \\<rightarrow> (r \\<rhd> (q\\<^sub>1 \\<otimes> q\\<^sub>2) \\<otimes> guar g)\"\n    by (metis preimp_isor rely_idem rely_iso test_post)\n  finally have \"x \\<parallel> y \\<le> p\\<^sub>1 \\<otimes> p\\<^sub>2 \\<rightarrow> (r \\<rhd> (q\\<^sub>1 \\<otimes> q\\<^sub>2) \\<otimes> guar g)\" .\n  thus ?thesis\n    by (simp only: quintuple_def[symmetric])\nqed\n\nend\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/Algebra.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.90192066862062, "lm_q2_score": 0.7905303186696747, "lm_q1q2_score": 0.7129956335794249}}
{"text": "theory Generated_Boolean_Algebra\n  imports Main \nbegin \n\n(**************************************************************************************************)\n(**************************************************************************************************)\nsection\\<open>Generated Boolean Algebras of Sets\\<close>\n(**************************************************************************************************)\n(**************************************************************************************************)\n\n(**************************************************************************************************)\n(**************************************************************************************************)\nsubsection\\<open>Definitions and Basic Lemmas\\<close>\n(**************************************************************************************************)\n(**************************************************************************************************)\nlemma equalityI':\n  assumes \"\\<And>x. x \\<in> A \\<Longrightarrow> x \\<in> B\"\n  assumes \"\\<And>x. x \\<in> B \\<Longrightarrow> x \\<in> A\"\n  shows \"A = B\"\n  using assms by blast\n\nlemma equalityI'':\n  assumes \"\\<And>x. A x \\<Longrightarrow> B x\"\n  assumes \"\\<And>x. B x \\<Longrightarrow> A x\"\n  shows \"{x. A x} = {x. B x}\"\n  using assms by blast \n\nlemma SomeE:\n  assumes \"a = (SOME x. P x)\"\n  assumes \"P c\"\n  shows \"P a\"\n  using assms  by (meson verit_sko_ex)\n\nlemma SomeE':\n  assumes \"a = (SOME x. P x)\"\n  assumes \"\\<exists> x. P x\"\n  shows \"P a\"\n  using assms  by (meson verit_sko_ex)\n\nsection\\<open>Basic notions about boolean algebras over a set \\<open>S\\<close>, generated by a set of generators \\<open>B\\<close>\\<close>\n\ntext\\<open>Note that the generators \\<open>B\\<close> need not be subsets of the set \\<open>S\\<close>\\<close>\n\ninductive_set gen_boolean_algebra \n  for S and B  where\n    universe: \"S \\<in> gen_boolean_algebra S B\"\n  | generator:  \"A \\<in> B \\<Longrightarrow> A \\<inter> S \\<in> gen_boolean_algebra S B\"\n  | union:      \"\\<lbrakk> A \\<in> gen_boolean_algebra S B; C \\<in> gen_boolean_algebra S B\\<rbrakk> \\<Longrightarrow> A \\<union> C \\<in> gen_boolean_algebra S B\"\n  | complement: \"A \\<in> gen_boolean_algebra S B \\<Longrightarrow> S - A \\<in> gen_boolean_algebra S B\"\n\nlemma gen_boolean_algebra_subset:\n  shows \"A \\<in> gen_boolean_algebra S B \\<Longrightarrow> A \\<subseteq> S\"\n  apply(induction A rule: gen_boolean_algebra.induct)\n  apply blast\n  apply blast\n  apply blast\n  by blast\n\nlemma gen_boolean_algebra_intersect:\n  assumes \"A \\<in> gen_boolean_algebra S B\"\n  assumes \"C \\<in> gen_boolean_algebra S B\"\n  shows \"A \\<inter> C \\<in> gen_boolean_algebra S B\"\nproof-\n  have 0: \"S - A \\<in> gen_boolean_algebra S B\"\n    using assms(1) gen_boolean_algebra.complement by blast\n  have 1: \"S - C \\<in> gen_boolean_algebra S B\"\n    using assms(2) gen_boolean_algebra.complement by blast\n  have 2: \"(S - A) \\<union> (S - C) \\<in> gen_boolean_algebra S B\"\n    using \"0\" \"1\" gen_boolean_algebra.union by blast\n  have \"S - (A \\<inter> C) \\<in> gen_boolean_algebra S B\"\n    by (simp add: 2 Diff_Int)\n  then have 3: \"S - (S - (A \\<inter> C)) \\<in> gen_boolean_algebra S B\"\n    using gen_boolean_algebra.complement \n    by blast\n  have \"A \\<inter> C \\<subseteq> S\"\n    using assms(1) gen_boolean_algebra_subset\n    by blast\n  then show ?thesis \n    using 3 \n    by (metis \"0\" Diff_partition Un_subset_iff assms(1) double_diff gen_boolean_algebra_subset)\nqed\n\nlemma gen_boolean_algebra_diff:\n  assumes \"A \\<in> gen_boolean_algebra S B\"\n  assumes \"C \\<in> gen_boolean_algebra S B\"\n  shows \"A -  C \\<in> gen_boolean_algebra S B\"\nproof-\n  have \"A - C = A \\<inter> (S - C)\"\n    by (metis Int_Diff assms(1) gen_boolean_algebra_subset inf_absorb1)\n  then show ?thesis \n    by (metis assms(1) assms(2) gen_boolean_algebra.complement gen_boolean_algebra_intersect)\nqed\n\nlemma gen_boolean_algebra_diff_eq:\n  assumes \"A \\<in> gen_boolean_algebra S B\"\n  assumes \"C \\<in> gen_boolean_algebra S B\"\n  shows \"A -  C = A \\<inter> (S - C)\"\n  by (metis Int_Diff assms(1) gen_boolean_algebra_subset inf_absorb1)\n\nlemma gen_boolean_algebra_finite_union:\n  assumes \"\\<And>a. a \\<in> A \\<Longrightarrow> a \\<in> gen_boolean_algebra S B\"\n  assumes \"finite A\"\n  shows \"\\<Union>A \\<in> gen_boolean_algebra S B\"\nproof-\n  have \"(\\<forall>a \\<in> A. a \\<in> gen_boolean_algebra S B) \\<longrightarrow> \\<Union>A \\<in> gen_boolean_algebra S B\"\n  apply(rule finite.induct[of A])\n  apply (simp add: assms(2); fail)\n   apply (metis DiffE Union_empty ex_in_conv  gen_boolean_algebra.simps)\n  by (metis Union_insert gen_boolean_algebra.simps insert_iff)\n  then show ?thesis using assms by blast \nqed\n  \nlemma gen_boolean_algebra_finite_intersection:\n  assumes \"\\<And>a. a \\<in> A \\<Longrightarrow> a \\<in> gen_boolean_algebra S B\"\n  assumes \"finite A\"\n  assumes \"A \\<noteq> {}\"\n  shows \"\\<Inter>A \\<in> gen_boolean_algebra S B\"\nproof-\n  have \"(\\<forall>a \\<in> A. a \\<in> gen_boolean_algebra S B) \\<and> A \\<noteq> {} \\<longrightarrow> \\<Inter>A \\<in> gen_boolean_algebra S B\"\n  apply(rule finite.induct[of A])\n  apply (simp add: assms(2))\n    apply force\n  using gen_boolean_algebra_intersect by auto\n  then show ?thesis using assms by blast \nqed\n\nlemma gen_boolean_algebra_generators:\n  assumes \"\\<And>b. b \\<in> B \\<Longrightarrow> b \\<subseteq> S\"\n  assumes \"b \\<in> B\"\n  shows \"b \\<in> gen_boolean_algebra S B\"\n  unfolding gen_boolean_algebra.simps[of b] using assms(1)[of b] assms(2)  by blast \n\nlemma gen_boolean_algebra_generator_subset:\n  assumes \"A \\<in> gen_boolean_algebra S As\"\n  assumes \"As \\<subseteq> Bs\"\n  shows \"A \\<in> gen_boolean_algebra S Bs\"\n  apply(rule gen_boolean_algebra.induct[of A S As])\n  using assms(1) apply blast\n  apply (simp add: gen_boolean_algebra.intros(1); fail)\n  apply (meson Set.basic_monos(7) assms(2) gen_boolean_algebra.intros(2))\n  using gen_boolean_algebra.intros(3) apply blast\n  using gen_boolean_algebra.intros(4) by blast\n\nlemma gen_boolean_algebra_generators_union:\n  assumes \"A \\<in> gen_boolean_algebra S As\"\n  assumes \"C \\<in> gen_boolean_algebra S Cs\"\n  shows \"A \\<union> C \\<in> gen_boolean_algebra S (As \\<union> Cs)\"\n  apply(rule gen_boolean_algebra.induct[of C S Cs])\n  using assms apply blast\napply(rule gen_boolean_algebra.union)\n      apply(rule gen_boolean_algebra_generator_subset[of _ _  As], rule assms, blast)\n     apply(rule gen_boolean_algebra.universe)\n    apply(rule gen_boolean_algebra.union)\n      apply(rule gen_boolean_algebra_generator_subset[of _ _  As], rule assms, blast)\n    apply(rule gen_boolean_algebra.generator, blast)\n    apply(rule gen_boolean_algebra.union)\n      apply(rule gen_boolean_algebra_generator_subset[of _ _  As], rule assms, blast)\n    apply(rule gen_boolean_algebra.union)\n            apply(rule gen_boolean_algebra_generator_subset[of _ _  Cs], blast, blast)\n            apply(rule gen_boolean_algebra_generator_subset[of _ _  Cs], blast, blast)\n    apply(rule gen_boolean_algebra.union)\n      apply(rule gen_boolean_algebra_generator_subset[of _ _  As], rule assms, blast)\n      apply(rule gen_boolean_algebra_generator_subset[of _ _  Cs])\n   apply(rule gen_boolean_algebra_diff)\n     apply(rule gen_boolean_algebra.universe)\n  apply blast\nby blast \n\nlemma gen_boolean_algebra_finite_gen_wits:\n  assumes \"A \\<in> gen_boolean_algebra S B\"\n  shows \"\\<exists> Bs. finite Bs \\<and> Bs \\<subseteq> B \\<and> A \\<in> gen_boolean_algebra S Bs\"\nproof(rule gen_boolean_algebra.induct[of A S B])\n  show \" A \\<in> gen_boolean_algebra S B\"\n    using assms by blast \n  show \"\\<exists>Bs. finite Bs \\<and> Bs \\<subseteq> B \\<and> S \\<in> gen_boolean_algebra S Bs\"\n    using gen_boolean_algebra.universe[of S \"{}\"]\n    by blast \n  show \"\\<And>A. A \\<in> B \\<Longrightarrow> \\<exists>Bs. finite Bs \\<and> Bs \\<subseteq> B \\<and> A \\<inter> S \\<in> gen_boolean_algebra S Bs\"\n  proof- fix A assume A: \"A \\<in> B\"\n    have 0: \"{A} \\<subseteq> B\"\n      using A by blast \n    show \"\\<exists>Bs. finite Bs \\<and> Bs \\<subseteq> B \\<and> A \\<inter> S \\<in> gen_boolean_algebra S Bs\"\n      using gen_boolean_algebra.generator[of A \"{A}\" S] 0 \n      by (meson finite.emptyI finite.insertI singletonI)\n  qed\n  show \"\\<And>A C. A \\<in> gen_boolean_algebra S B \\<Longrightarrow>\n           \\<exists>Bs. finite Bs \\<and> Bs \\<subseteq> B \\<and> A \\<in> gen_boolean_algebra S Bs \\<Longrightarrow>\n           C \\<in> gen_boolean_algebra S B \\<Longrightarrow>\n           \\<exists>Bs. finite Bs \\<and> Bs \\<subseteq> B \\<and> C \\<in> gen_boolean_algebra S Bs \\<Longrightarrow> \\<exists>Bs. finite Bs \\<and> Bs \\<subseteq> B \\<and> A \\<union> C \\<in> gen_boolean_algebra S Bs\"\n  proof- fix A C \n    assume A: \"A \\<in> gen_boolean_algebra S B\"\n           \"\\<exists>Bs. finite Bs \\<and> Bs \\<subseteq> B \\<and> A \\<in> gen_boolean_algebra S Bs\"\n           \"C \\<in> gen_boolean_algebra S B\"\n           \"\\<exists>Bs. finite Bs \\<and> Bs \\<subseteq> B \\<and> C \\<in> gen_boolean_algebra S Bs\"\n    obtain As where As_def: \"finite As \\<and> As \\<subseteq> B \\<and> A \\<in> gen_boolean_algebra S As\"\n      using A by blast \n    obtain Cs where Cs_def: \"finite Cs \\<and> Cs \\<subseteq> B \\<and> C \\<in> gen_boolean_algebra S Cs\"\n      using A by blast \n    obtain Bs where Bs_def: \"Bs = As \\<union> Cs\"\n      by blast \n    have Bs_sub: \"Bs \\<subseteq> B\"\n      unfolding Bs_def using As_def Cs_def by blast \n    have 0: \" A \\<union> C \\<in> gen_boolean_algebra S Bs\"\n      unfolding Bs_def\n      apply(rule gen_boolean_algebra_generators_union)\n      using As_def apply blast\n      using Cs_def by blast\n    have 1: \"finite Bs\"\n      unfolding Bs_def using As_def Cs_def by blast \n    show \" \\<exists>Bs. finite Bs \\<and> Bs \\<subseteq> B \\<and> A \\<union> C \\<in> gen_boolean_algebra S Bs\"\n      using Bs_sub 0 1 by blast \n  qed\n  show \"\\<And>A. A \\<in> gen_boolean_algebra S B \\<Longrightarrow>\n         \\<exists>Bs. finite Bs \\<and> Bs \\<subseteq> B \\<and> A \\<in> gen_boolean_algebra S Bs \\<Longrightarrow> \\<exists>Bs. finite Bs \\<and> Bs \\<subseteq> B \\<and> S - A \\<in> gen_boolean_algebra S Bs\"\n    using gen_boolean_algebra.complement by blast \nqed\n\nlemma gen_boolean_algebra_univ_mono:\n  assumes \"A \\<in>  gen_boolean_algebra S B\"\n  shows \"gen_boolean_algebra A B \\<subseteq> gen_boolean_algebra S B \"\nproof(rule subsetI) fix x assume A: \"x \\<in> gen_boolean_algebra A B\"\n  obtain a where a_def: \"a = A\"\n    by blast \n  have 0: \"a \\<in> gen_boolean_algebra S B\"\n    unfolding a_def using assms by blast \n  have 1: \"a = A \\<inter> S\"\n    using assms gen_boolean_algebra_subset unfolding a_def by blast \n  show \"x \\<in> gen_boolean_algebra S B \" \n    apply(rule gen_boolean_algebra.induct[of x a B])\n    using A a_def apply blast apply(rule 0)\n    apply (metis 1 Int_left_commute assms gen_boolean_algebra.intros(2) gen_boolean_algebra_intersect)\n     apply(rule gen_boolean_algebra.union, blast, blast)\n    apply(rule gen_boolean_algebra_diff)\n     apply(rule 0)\n    by blast \nqed\n\ntext\\<open>\n  The boolean algebra generated by a collection of elements in another algebra is contained\n  in the original algebra:\n\\<close>\nlemma gen_boolean_algebra_subalgebra:\n  assumes \"Xs \\<subseteq> gen_boolean_algebra S B\"\n  shows \"gen_boolean_algebra S Xs \\<subseteq> gen_boolean_algebra S B\"\nproof fix x assume A: \"x \\<in> gen_boolean_algebra S Xs\"\n  show \"x \\<in> gen_boolean_algebra S B \"\n    apply(rule gen_boolean_algebra.induct[of x S Xs])\n        apply (simp add: A; fail)\n       apply (simp add: gen_boolean_algebra.universe; fail)\n    using assms gen_boolean_algebra.universe gen_boolean_algebra_intersect apply blast\n  apply (simp add: gen_boolean_algebra.union; fail)\n  by (simp add: gen_boolean_algebra.complement)\nqed \n\nlemma gen_boolean_algebra_idempotent:\n  assumes \"S = \\<Union> Xs\"\n  shows \"gen_boolean_algebra S (gen_boolean_algebra S Xs) = (gen_boolean_algebra S Xs)\"\n  apply(rule equalityI)\n   apply(rule subsetI)\n  apply (meson equalityD2 gen_boolean_algebra_subalgebra in_mono)\n   apply(rule subsetI)\n  by (metis gen_boolean_algebra.simps gen_boolean_algebra_subset inf.absorb1)\n\ntext\\<open>We can always replace the set of generators \\<open>Xs\\<close> with their intersections with the universe \n  set \\<open>S\\<close>, and obtain the same algebra.\\<close>\n\nlemma gen_boolean_algebra_restrict_generators: \n\"gen_boolean_algebra S Xs =gen_boolean_algebra S ((\\<inter>) S ` Xs)\"\nproof(rule equalityI')\n  fix x assume A: \"x \\<in> gen_boolean_algebra S Xs\"\n  show \"x \\<in> gen_boolean_algebra S ((\\<inter>) S ` Xs)\"\n    apply(rule gen_boolean_algebra.induct[of x S Xs], rule A, rule gen_boolean_algebra.universe) \n    apply (metis gen_boolean_algebra.generator image_eqI inf.right_idem inf_commute)\n     apply(rule gen_boolean_algebra.union, blast, blast)\n    by(rule gen_boolean_algebra_diff, rule gen_boolean_algebra.universe, blast)\nnext \n  fix x assume A: \"x \\<in> gen_boolean_algebra S ((\\<inter>) S ` Xs)\"\n  show \"x \\<in> gen_boolean_algebra S Xs\"\n    apply(rule gen_boolean_algebra.induct[of x S \"(\\<inter>) S ` Xs\"], rule A, rule gen_boolean_algebra.universe,\n       rule gen_boolean_algebra_intersect )\n    using gen_boolean_algebra.generator[of _ Xs S] \n       apply (metis (no_types, lifting) Int_commute image_iff)\n      apply(rule gen_boolean_algebra.universe)\n     apply(rule gen_boolean_algebra.union, blast, blast)\n    by(rule gen_boolean_algebra_diff, rule gen_boolean_algebra.universe, blast)\nqed\n\ntext\\<open>Adding a generator to a generated boolean algebra is redundant if the generator already\n      lies in the algebra.\\<close>\n\nlemma add_generators:\n  assumes \"A \\<in> gen_boolean_algebra S Xs\"\n  shows \"gen_boolean_algebra S Xs = gen_boolean_algebra S (insert A Xs)\"\nproof(rule equalityI')\n  fix x assume A: \"x \\<in> gen_boolean_algebra S Xs\"\n  show \"x \\<in> gen_boolean_algebra S (insert A Xs)\"\n    apply(rule gen_boolean_algebra.induct[of x S Xs], rule A, rule gen_boolean_algebra.universe)\n      apply(rule gen_boolean_algebra.generator, blast)\n     apply(rule gen_boolean_algebra.union, blast,blast)\n   by(rule gen_boolean_algebra_diff, rule gen_boolean_algebra.universe, blast)\nnext\n  fix x assume A: \"x \\<in> gen_boolean_algebra S (insert A Xs)\"\n  show \"x \\<in> gen_boolean_algebra S Xs\"\n    apply(rule gen_boolean_algebra.induct[of x S \"insert A Xs\"], rule A, rule gen_boolean_algebra.universe)\n    using assms gen_boolean_algebra.generator[of _ Xs S]\n    using gen_boolean_algebra.universe gen_boolean_algebra_intersect apply blast\n     apply(rule gen_boolean_algebra.union, blast, blast)\n       by(rule gen_boolean_algebra_diff, rule gen_boolean_algebra.universe, blast)\nqed\n(**************************************************************************************************)\n(**************************************************************************************************)\nsubsection\\<open>Turning a Family of Sets into a Family of Disjoint Sets\\<close>\n(**************************************************************************************************)\n(**************************************************************************************************)\n\ntext\\<open>\n  This section outlines the standard construction where sets $A_0, \\dots, A_n$ are replaced by sets\n  $A_0, A_1 - A_0, A_2 - (A_0 \\cup A_1), ..., A_n - (\\bigcup \\limits_{i = 0}^{n-1} A_i)$ to obtain\n  a disjoint family of the same cardinality.\n\\<close>\nfun rec_disjointify where\n\"rec_disjointify 0 f = {}\"|\n\"rec_disjointify (Suc m) f = insert (f m - \\<Union> (rec_disjointify m f)) (rec_disjointify m f)\"\n\nlemma card_of_rec_disjointify:\n\"card (rec_disjointify m f) \\<le> m\"\n  apply(induction m) unfolding rec_disjointify.simps \n   apply simp\n  by (metis Suc_le_mono card.infinite card_insert_disjoint finite_insert insert_absorb le_SucI)\n\nlemma rec_disjointify_finite:\n\"finite (rec_disjointify m f)\"\n  apply(induction m)\n  unfolding rec_disjointify.simps by auto \n\nlemma rec_disjointify_in_gen_boolean_algebra:\n  assumes \"f ` {..<m} \\<subseteq> gen_boolean_algebra S B\"\n  shows  \"rec_disjointify m f \\<subseteq> gen_boolean_algebra S B\"\nproof-\n  have \"\\<And>k. k \\<le> m \\<longrightarrow> rec_disjointify k f \\<subseteq> gen_boolean_algebra S B\"\n  proof- fix k  show \"k \\<le> m \\<longrightarrow> rec_disjointify k f \\<subseteq> gen_boolean_algebra S B\"\n      apply(induction k) unfolding rec_disjointify.simps(1) using assms apply blast \n    proof fix k \n      assume IH: \" k \\<le> m \\<longrightarrow> rec_disjointify k f \\<subseteq> gen_boolean_algebra S B\"\n                 \"Suc k \\<le> m\"\n      then have 0: \"rec_disjointify k f \\<subseteq> gen_boolean_algebra S B\"\n        by (simp add: IH(2))\n      have 1: \"finite (rec_disjointify k f )\"\n        using rec_disjointify_finite by blast \n      have 2: \"f k \\<in> gen_boolean_algebra S B\"\n        using IH(2) assms \n        by (simp add: image_subset_iff)        \n      show \"rec_disjointify (Suc k) f \\<subseteq> gen_boolean_algebra S B\"\n        using 0 1 2 unfolding rec_disjointify.simps \n        by (simp add: gen_boolean_algebra_diff gen_boolean_algebra_finite_union subset_iff)\n    qed\n  qed\n  thus ?thesis by blast \nqed\n\nlemma rec_disjointify_union:\n\"\\<Union> (rec_disjointify m f) = (\\<Union> i \\<in> {..<m}. f i)\"\n  apply(induction m)\n   apply simp unfolding rec_disjointify.simps insert_def\n  apply(rule equalityI, rule subsetI) \n  apply (simp add: lessThan_Suc; fail)\n  apply(rule subsetI) \n  by (simp add: lessThan_Suc)\n\ndefinition enum_rec_disjointify where\n\"enum_rec_disjointify f m = f m - \\<Union> (rec_disjointify m f)\"\n\nlemma rec_disjointify_as_enum_rec_disjointify_image:\n\"rec_disjointify m f = enum_rec_disjointify f  ` {..<m}\"\n  apply(induction m)\n  unfolding rec_disjointify.simps \n   apply (simp; fail)\n  unfolding enum_rec_disjointify_def\n  using lessThan_Suc by auto\n\nlemma enum_rec_disjointify_subset:\n\"enum_rec_disjointify f m \\<subseteq> f m\"\n    unfolding enum_rec_disjointify_def\n    by auto \n\nlemma enum_rec_disjointify_disjoint:\n  assumes \"k < m\"\n  shows \"enum_rec_disjointify f m \\<inter> enum_rec_disjointify f k = {}\"\nproof-\n  have \"enum_rec_disjointify f k \\<subseteq> \\<Union> (rec_disjointify m f)\"\n    unfolding rec_disjointify_union \n    using assms enum_rec_disjointify_subset by fastforce\n  thus ?thesis \n     unfolding enum_rec_disjointify_def\n     by auto \nqed\n\nlemma enum_rec_disjointify_disjoint':\n  assumes \"k \\<noteq> m\"\n  shows \"enum_rec_disjointify f m \\<inter> enum_rec_disjointify f k = {}\"\n  apply(cases  \"k < m\") using enum_rec_disjointify_disjoint[of k m f]\n   apply simp  \n  using assms enum_rec_disjointify_disjoint[of m k f] by auto \n\nlemma rec_disjointify_is_disjoint:\n  assumes \"A \\<in> rec_disjointify m f\"\n  assumes \"B \\<in>  rec_disjointify m f\"\n  assumes \"A \\<noteq> B\"\n  shows \"A \\<inter> B = {}\"\n  using  rec_disjointify_as_enum_rec_disjointify_image enum_rec_disjointify_disjoint' assms\n  by (smt image_iff)\n\ndefinition enumerates where\n\"enumerates A f \\<equiv> finite A \\<and> A = f ` {..< (card A)} \\<and> inj_on f {..< (card A)}\"\n\nlemma finite_imp_exists_enumeration:\n  assumes \"finite A\"\n  shows \"\\<exists>f. enumerates A f\"\n  unfolding enumerates_def \n  using assms finite_imp_nat_seg_image_inj_on[of A]\n  by (metis card_Collect_less_nat card_image lessThan_def)\n\nlemma enumeratesE:\n  assumes \"enumerates A f\"\n  shows \"finite A\" \"A = f ` {..< card A}\" \"inj_on f {..< card A}\"\n  using assms unfolding enumerates_def  apply blast \n  using assms unfolding enumerates_def  apply blast \n  using assms unfolding enumerates_def  by blast \n\nlemma rec_disjointify_finite_set:\n  assumes \"enumerates A f\"\n  shows \"\\<Union> (rec_disjointify (card A) f) = \\<Union> A\"\n  unfolding rec_disjointify_union[of \"card A\" f]\n  using enumeratesE[of A f] assms by auto  \n\ndefinition enumerate where \n\"enumerate A = (SOME f. enumerates A f)\"\n\nlemma enumerate_enumerates:\n  assumes \"finite A\"\n  shows \"enumerates A (enumerate A)\"\n  unfolding enumerate_def using finite_imp_exists_enumeration assms \n  by (simp add: finite_imp_exists_enumeration some_eq_ex)\n\nlemma enumerateE: \n  assumes \"finite A\"\n  assumes \"a \\<in> A\"\n  shows \"\\<exists> i < card A. a = (enumerate A) i\"\n  using  enumerate_enumerates[of A] enumeratesE[of A] assms by blast\n\ndefinition disjointify where \n\"disjointify As = rec_disjointify (card As) (enumerate As)\"\n\nlemma disjointify_is_disjoint:\n  assumes \"finite As\"\n  assumes \"A \\<in> disjointify As\"\n  assumes \"B \\<in> disjointify As\"\n  assumes \"A \\<noteq>  B\"\n  shows \"A \\<inter> B = {}\"\n  using assms rec_disjointify_is_disjoint[of A _ _ B] unfolding disjointify_def \n  by simp\n\nlemma disjointify_union:\n  assumes \"finite As\"\n  shows \"\\<Union> (disjointify As)  = \\<Union> As\"\n  using assms \n  by (simp add: disjointify_def enumerate_enumerates rec_disjointify_finite_set)\n\nlemma disjointify_gen_boolean_algebra:\n  assumes \"finite As\"\n  assumes \"As \\<subseteq> gen_boolean_algebra S B\"\n  shows \" disjointify As \\<subseteq> gen_boolean_algebra S B\"\n  using assms unfolding disjointify_def  \n  by (metis enumerate_enumerates enumeratesE(2) rec_disjointify_in_gen_boolean_algebra)\n\nlemma disjointify_finite:\n  assumes \"finite As\"\n  shows \"finite (disjointify As)\"\n  using assms unfolding disjointify_def  \n  by (simp add: rec_disjointify_finite)\n\nlemma disjointify_card: \n  assumes \"finite As\"\n  shows\"card  (disjointify As) \\<le> card As\"\n  by (simp add: card_of_rec_disjointify disjointify_def)\n\nlemma disjointify_subset:\n  assumes \"finite As\"\n  assumes \"A \\<in> disjointify As\"\n  shows \"\\<exists>B \\<in> As. A \\<subseteq> B\"\n  using assms enum_rec_disjointify_subset enumerate_enumerates enumeratesE\n  unfolding disjointify_def \n  by (smt image_iff rec_disjointify_as_enum_rec_disjointify_image)\n\n\n(**************************************************************************************************)\n(**************************************************************************************************)\nsubsection\\<open>The Atoms Generated by Collections of Sets\\<close>\n(**************************************************************************************************)\n(**************************************************************************************************)\n\ntext\\<open>\n  We can also turn a family of sets into a disjoint family by taking the atoms of the boolean\n  algebra generated by these sets. This will still yield a finite family if the initial family is\n  finite, but in general will be much larger in size.\n\\<close>\n\n(**********************************************************************)\n(**********************************************************************)\nsubsubsection\\<open>Defining the Atoms of a Family of Sets\\<close>\n(**********************************************************************)\n(**********************************************************************)\ntext\\<open>\n  Here we intend that \\<open>As\\<close> is a subset of the collection of sets \\<open>Xs\\<close>. This function associate to each\n  subset \\<open>As \\<subseteq> Xs\\<close> a set which is contained in each element of \\<open>As\\<close>, and is disjoint from\n  each element of \\<open>Xs - As\\<close>. Note that in general this may yield the empty set, but we will\n  ultimately be interested in the cases where the result is nonempty.\\<close>\n\ndefinition subset_to_atom where\n\"subset_to_atom Xs As = \\<Inter> As - \\<Union> (Xs - As)\"\n\nlemma subset_to_atom_memI:\n  assumes \"\\<And>A. A \\<in> As \\<Longrightarrow> x \\<in> A\"\n  assumes \"\\<And>A. A \\<in> Xs \\<Longrightarrow> A \\<notin> As \\<Longrightarrow> x \\<notin> A\"\n  shows \"x \\<in> subset_to_atom Xs As\"\n  using assms unfolding subset_to_atom_def \n  by blast \n\nlemma subset_to_atom_memE:\n  assumes \"x \\<in> subset_to_atom Xs As\"\n  shows \"\\<And>A. A \\<in> As \\<Longrightarrow> x \\<in> A\"\n        \"\\<And>A. A \\<in> Xs \\<Longrightarrow> A \\<notin> As \\<Longrightarrow> x \\<notin> A\"\n  using assms unfolding subset_to_atom_def by auto \n\nlemma subset_to_atom_closed: \n  assumes \"As \\<noteq> {}\"\n  assumes \"As \\<subseteq> Xs\"\n  shows \"subset_to_atom Xs As \\<subseteq> \\<Union> Xs\"\nproof-\n  have 0: \"\\<Inter> As \\<subseteq> \\<Union> As \"\n    apply(rule subsetI)\n    using assms(1) by blast\n  show ?thesis \n  apply(rule subsetI)\n  using assms 0 unfolding subset_to_atom_def \n  by (meson DiffD1 Union_mono subsetD)\nqed\n\nlemma subset_to_atom_as_intersection:\n  assumes \"As \\<noteq> {}\"\n  assumes \"As \\<subseteq> Xs\"\n  assumes \"S = \\<Union> Xs\"\n  shows \"subset_to_atom Xs As = \\<Inter> As \\<inter> (\\<Inter> X \\<in> Xs - As. S - X)\"\n  unfolding assms subset_to_atom_def \n  apply(rule equalityI')\n   apply(rule IntI, blast)\n  apply(rule InterI) \n  using INT_I assms(1) assms(2) apply auto[1]\n  apply(rule DiffI, blast)\n  by blast\n\ndefinition atoms_of where\n\"atoms_of Xs = (subset_to_atom Xs  ` ((Pow Xs) - {{}})) - {{}}\"\n\nlemma atoms_nonempty:\n  assumes \"A \\<in> atoms_of Xs\"\n  shows \"A \\<noteq> {}\"\n  using assms unfolding atoms_of_def by blast \n\nlemma atoms_of_disjoint:\n  assumes \"A \\<in> atoms_of Xs\"\n  assumes \"B \\<in> atoms_of Xs\"\n  assumes \"A \\<noteq> B\"\n  shows \"A \\<inter> B = {}\"\nproof-\n  obtain a where a_def: \"a \\<subseteq> Xs \\<and> A = subset_to_atom Xs a\"\n    using assms  unfolding atoms_of_def by blast \n  obtain b where b_def: \"b \\<subseteq> Xs \\<and> B = subset_to_atom Xs b\"\n    using assms  unfolding atoms_of_def by blast \n  have a_neq_b: \"a \\<noteq> b\"\n    using assms   a_def b_def by blast \n  have  \"A \\<inter> B \\<subseteq> {}\"\n  proof fix x assume A: \"x \\<in> A \\<inter> B\"\n    show \"x \\<in> {}\"\n    proof(cases \"a \\<subseteq> b\")\n      case True\n      then obtain c where c_def: \"c \\<in> b - a\"\n        using a_neq_b by blast\n      have c_in_Xs: \"c \\<in> Xs\"\n        using c_def b_def by blast \n      have x_in_c: \"x \\<in> c\"\n        using A  b_def c_def subset_to_atom_memE[of x Xs b c] by blast \n      have x_notin_c: \"x \\<notin> c\"\n        using A  a_def c_in_Xs c_def subset_to_atom_memE[of x Xs a c] by blast \n      then show ?thesis using x_in_c by blast \n    next\n      case False\n      then obtain c where c_def: \"c \\<in> a - b\"\n        using a_neq_b by blast\n      have c_in_Xs: \"c \\<in> Xs\"\n        using c_def a_def by blast \n      have x_in_c: \"x \\<in> c\"\n        using A  a_def c_def subset_to_atom_memE[of x Xs a c] by blast \n      have x_notin_c: \"x \\<notin> c\"\n        using A  b_def c_in_Xs c_def subset_to_atom_memE[of x Xs b c] by blast \n      then show ?thesis using x_in_c by blast \n    qed\n  qed\n  thus \"A \\<inter> B = {}\"\n    by blast \nqed\n\ntext \\<open>\n  The atoms of a family of sets \\<open>Xs\\<close> are minimal in the sense that they are either contained in or\n  disjoint from each element of \\<open>Xs\\<close>.\n\\<close>\nlemma atoms_are_minimal:\n  assumes \"A \\<in> atoms_of Xs\"\n  assumes \"X \\<in> Xs\"\n  shows \"X \\<inter> A = {} \\<or> A \\<subseteq> X\"\nproof(cases \"X \\<inter> A = {}\")\n  case True\n  then show ?thesis by blast \nnext\n  case False\n  obtain As where As_def: \"As \\<in> Pow Xs - {{}} \\<and> A = subset_to_atom Xs As\"\n    using assms unfolding atoms_of_def by blast\n  have A_simp: \"A = subset_to_atom Xs As\"\n    using As_def by blast \n  then show ?thesis using assms  unfolding atoms_of_def subset_to_atom_def A_simp \n  using DiffD1 subset_eq by auto\nqed\n\n(**********************************************************************)\n(**********************************************************************)\nsubsubsection\\<open>Atoms Induced by Types of Points\\<close>\n(**********************************************************************)\n(**********************************************************************)\ntext\\<open>\n  The set of sets in \\<open>Xs\\<close> which contain some point \\<open>x\\<close>. In the case where \\<open>Xs\\<close> is some collection of \n  first order formulas, this is just the type of \\<open>x\\<close> over these formulas.\\<close>\ndefinition point_to_type where \n\"point_to_type Xs x = {X \\<in> Xs. x \\<in> X}\"\n\ntext \\<open>The type of a point \\<open>x\\<close> induces the unique atom of \\<open>Xs\\<close> which contains \\<open>x\\<close>.\\<close>\nlemma point_in_atom_of_type:\n  assumes \"x \\<in> \\<Union> Xs\"\n  shows \"x \\<in> subset_to_atom Xs (point_to_type Xs x)\"\n  using assms unfolding subset_to_atom_def  point_to_type_def \n  by blast\n\nlemma point_to_type_nonempty:\n  assumes \"x \\<in> \\<Union> Xs\"\n  shows \"point_to_type Xs x \\<noteq>{}\"\n  using assms unfolding point_to_type_def \n  by blast\n\nlemma point_to_type_closed: \n \"point_to_type Xs x \\<subseteq> Pow (\\<Union> Xs)\"\n  unfolding point_to_type_def \n  by blast\n \nlemma atoms_of_covers: \n  assumes \"X = \\<Union> Xs\"\n  shows \"\\<Union> (atoms_of Xs) = X\"\nproof\n  show \" \\<Union> (atoms_of Xs) \\<subseteq> X\"\n  proof fix x assume A: \"x \\<in> \\<Union> (atoms_of Xs)\"\n    then obtain As where As_def: \"As \\<in> Pow Xs - {{}} \\<and> x \\<in> subset_to_atom Xs As\"\n      unfolding atoms_of_def  by blast      \n    have \"subset_to_atom Xs As \\<subseteq>  \\<Union> Xs\"\n      using subset_to_atom_closed[of As Xs] As_def by blast \n    then show \"x \\<in> X\" unfolding assms  \n      using As_def by blast\n  qed\n  show \"X \\<subseteq> \\<Union> (atoms_of Xs)\" apply(rule subsetI)\n    using point_to_type_nonempty point_in_atom_of_type point_to_type_closed\n    unfolding  assms point_to_type_def atoms_of_def \n    by fastforce   \nqed    \n\nlemma atoms_of_covers': \n  shows \"\\<Union> (atoms_of Xs) = \\<Union> Xs\"\n  using atoms_of_covers[of \"\\<Union> Xs\"] by blast \n\ntext \\<open>Every atom of a collection \\<open>Xs\\<close> of sets is realized as the atom generated by the type of\n   an element in that atom.\\<close>\nlemma nonemtpy_atom_from_point_to_type:\n  assumes \"A \\<in> atoms_of Xs\"\n  assumes \"a \\<in> A\"\n  shows \"A = subset_to_atom Xs (point_to_type Xs a)\"\nproof-\n  obtain As where As_def: \"As \\<in> (Pow Xs) - {} \\<and> A = subset_to_atom Xs As\"\n    using assms unfolding atoms_of_def by blast \n  have A_simp: \"A = subset_to_atom Xs As\"\n    using As_def by blast \n  have 0: \"As = point_to_type Xs a\"\n    apply(rule  equalityI)\n    apply(rule  subsetI)\n    apply (smt As_def Diff_empty UnionI Union_Pow_eq assms point_in_atom_of_type subset_to_atom_memE(1) subset_to_atom_memE(2))    \n    apply(rule subsetI) \n    using As_def assms subset_to_atom_memE(2) \n    by (metis (no_types, lifting) mem_Collect_eq point_to_type_def)\n  show ?thesis \n    using point_in_atom_of_type 0\n          atoms_of_covers'[of Xs] assms  unfolding A_simp\n    by auto\nqed  \n\ntext \\<open>\n  In light of the previous theorem, a point a and a collection of sets \\<open>Xs\\<close> is enough to recover\n  the the unique atom of \\<open>Xs\\<close> which contains \\<open>a\\<close>.\n\\<close>\ndefinition point_to_atom where\n\"point_to_atom Xs a = subset_to_atom Xs (point_to_type Xs a)\"\n\nlemma point_to_atom_closed: \n  assumes \"x \\<in> \\<Union> Xs\"\n  shows \"point_to_atom Xs x \\<in> atoms_of Xs\"\n  using assms unfolding atoms_of_def point_to_atom_def \n  by (metis (full_types) Union_iff atoms_of_covers atoms_of_def nonemtpy_atom_from_point_to_type)\n\ntext \\<open>All atoms of \\<open>Xs\\<close> are the atom induced by some point in the union of \\<open>Xs\\<close>.\\<close>\nlemma atoms_induced_by_points:\n\"atoms_of Xs = point_to_atom Xs ` (\\<Union> Xs)\"\n  apply(rule equalityI)\n   apply(rule subsetI)\n  using nonemtpy_atom_from_point_to_type atoms_nonempty atoms_of_covers'\n  unfolding point_to_atom_def \n  apply (smt DiffE Pow_empty Pow_iff atoms_of_def image_iff subsetD subsetI subset_to_atom_closed)\n     apply(rule subsetI)\n  by (metis (no_types, lifting) imageE point_to_atom_closed point_to_atom_def)\n\n(**********************************************************************)\n(**********************************************************************)\nsubsubsection\\<open>Atoms of Generated Boolean Algebras\\<close>\n(**********************************************************************)\n(**********************************************************************)\n\nlemma atoms_of_gen_boolean_algebra:\n  assumes \"Xs \\<subseteq> gen_boolean_algebra S B\"\n  assumes \"finite Xs\"\n  shows \"atoms_of Xs \\<subseteq> gen_boolean_algebra S B\"\nproof\n  fix x assume A: \"x \\<in> atoms_of Xs\"\n  then obtain As where As_def: \"As \\<in> ((Pow Xs) - {{}}) \\<and> x = subset_to_atom Xs As\"\n    unfolding atoms_of_def by blast \n  have x_simp: \"x = subset_to_atom Xs As\"\n    using As_def by blast \n  have 0: \"finite As\"\n    using As_def assms finite_subset by auto\n  have 1: \"As \\<subseteq> gen_boolean_algebra S B\"\n    using As_def assms by blast\n  have 2: \"\\<Inter> As \\<in> gen_boolean_algebra S B\"\n    using 0 1 assms \n    by (metis As_def DiffE gen_boolean_algebra_finite_intersection singletonI subset_eq)\n  show \"x \\<in> gen_boolean_algebra S B\"\n    using A 2 unfolding atoms_of_def subset_to_atom_def x_simp \n    by (metis (no_types, lifting) As_def DiffD1 Diff_partition Pow_iff Un_subset_iff assms(1) assms(2) finite_subset gen_boolean_algebra_diff gen_boolean_algebra_finite_union order_refl subsetD)\nqed\n\n\ntext \\<open>If the generators of a boolean algebra are contained in the universe, the atoms induced by \n  the generators alone are minimal elements of the entire algebra.\\<close>\nlemma finite_algebra_atoms_are_minimal:\n  assumes \"finite Xs\"\n  assumes \"\\<Union> Xs \\<subseteq> S\"\n  assumes \"A \\<in> atoms_of Xs\"\n  assumes \"X \\<in> gen_boolean_algebra S Xs\"\n  shows \"X \\<inter> A = {} \\<or> A \\<subseteq> X\"\n  apply(rule gen_boolean_algebra.induct[of X S Xs])\n  apply (simp add: assms(4); fail)\n  apply (metis Union_upper assms(2) assms(3) atoms_of_covers dual_order.trans)\n  using assms(2) assms(3) atoms_are_minimal apply fastforce\n  apply blast\n  using assms\n  by (metis Diff_Int_distrib2 Diff_empty Diff_eq_empty_iff Sup_upper atoms_of_covers' equalityE inf.absorb_iff2 order_trans) \n\nlemma finite_set_imp_finite_atoms:\n  assumes \"finite Xs\"\n  shows \"finite (atoms_of Xs)\"\n  using assms unfolding atoms_of_def \n  by blast\n\ntext \\<open>\n  Every element in the boolean algebra generated by \\<open>Xs\\<close> over \\<open>S\\<close> is a (disjoint) union\n  of atoms of generators:\n\\<close>\n\nlemma gen_boolean_algebra_elem_uni_of_atoms:\n  assumes \"finite Xs\"\n  assumes \"S = \\<Union> Xs\"\n  assumes \"X \\<in> gen_boolean_algebra S Xs\"\n  shows \"X = \\<Union> {a \\<in> atoms_of Xs. a \\<subseteq> X}\"\nproof\n  show \"X \\<subseteq> \\<Union> {a \\<in> atoms_of Xs. a \\<subseteq> X}\"\n  proof fix x assume A: \"x \\<in> X\"\n    then have \"point_to_atom Xs x \\<in> atoms_of Xs\"\n      using assms by (meson gen_boolean_algebra_subset point_to_atom_closed subsetD)\n    then show \"x \\<in> \\<Union> {a \\<in> atoms_of Xs. a \\<subseteq> X}\"\n      by (smt A IntI Union_iff assms(1) assms(2) assms(3) empty_iff finite_algebra_atoms_are_minimal gen_boolean_algebra.universe gen_boolean_algebra_subset mem_Collect_eq point_in_atom_of_type point_to_atom_def subsetD)\n  qed\n  show \"\\<Union> {a \\<in> atoms_of Xs. a \\<subseteq> X} \\<subseteq> X\"\n    by blast \nqed\n\ntext\\<open>In fact, every generated boolean algebra is the power set of the atoms of its generators:\\<close>\nlemma gen_boolean_algebra_generated_by_atoms:\n  assumes \"finite Xs\"\n  assumes \"S = \\<Union> Xs\"\n  shows \"gen_boolean_algebra S Xs = \\<Union> ` (Pow (atoms_of Xs))\"\nproof\n  show \"gen_boolean_algebra S Xs \\<subseteq> \\<Union> ` Pow (atoms_of Xs)\"\n    apply(rule subsetI)\n    using gen_boolean_algebra_elem_uni_of_atoms[of Xs S] assms \n    by fastforce\n  show \"\\<Union> ` Pow (atoms_of Xs) \\<subseteq> gen_boolean_algebra S Xs\"\n    apply(rule subsetI)\n    using atoms_of_gen_boolean_algebra[of Xs S Xs]\n          finite_subset[of _ \"atoms_of Xs\"] assms \n          finite_set_imp_finite_atoms[of Xs] \n          gen_boolean_algebra_finite_union[of _ S Xs] \n    by (smt Pow_iff Union_upper gen_boolean_algebra.intros(2) image_iff inf.absorb1 subsetD subsetI)\nqed\n\ntext\\<open>Finitely generated boolean algebras are finite\\<close>\nlemma fin_gens_imp_fin_algebra:\n  assumes \"finite Xs\"\n  assumes \"S = \\<Union> Xs\"\n  shows \"finite (gen_boolean_algebra S Xs)\"\n  using finite_set_imp_finite_atoms[of Xs] assms gen_boolean_algebra_generated_by_atoms[of Xs S]\n  by simp\n\n\nlemma point_to_atom_equal:\n  assumes \"finite Xs\"\n  assumes \"S = \\<Union> Xs\"\n  assumes \"x \\<in> S\"\n  shows \"point_to_atom Xs x = point_to_atom (gen_boolean_algebra S Xs) x\"\nproof\n  show P0: \"point_to_atom Xs x \\<subseteq> point_to_atom (gen_boolean_algebra S Xs) x\"\n  proof-\n    have 0: \"point_to_atom Xs x \\<inter> point_to_atom (gen_boolean_algebra S Xs) x \\<noteq> {}\"\n      using assms \n      by (metis IntI UnionI empty_iff gen_boolean_algebra.universe point_in_atom_of_type point_to_atom_def)\n    have 1: \"point_to_atom (gen_boolean_algebra S Xs) x \\<in> gen_boolean_algebra S Xs\"\n      using assms fin_gens_imp_fin_algebra[of Xs S] \n      by (meson UnionI atoms_of_gen_boolean_algebra gen_boolean_algebra.simps point_to_atom_closed subset_eq subset_refl)\n    then show ?thesis\n      using 0 finite_algebra_atoms_are_minimal[of Xs S \"point_to_atom Xs x\" \"point_to_atom (gen_boolean_algebra S Xs) x\"]\n            assms(1) assms(2) assms(3) atoms_induced_by_points by auto\n  qed\n  show \"point_to_atom (gen_boolean_algebra S Xs) x \\<subseteq> point_to_atom Xs x\"\n  proof- \n    have 0: \"point_to_atom (gen_boolean_algebra S Xs) x \\<inter> point_to_atom Xs x \\<noteq>{}\"\n      using assms P0 point_in_atom_of_type point_to_atom_def by fastforce\n    have 1: \"point_to_atom (gen_boolean_algebra S Xs) x \\<in> (gen_boolean_algebra S Xs)\"\n      using assms gen_boolean_algebra_idempotent[of S Xs] atoms_of_gen_boolean_algebra \n      by (metis UnionI fin_gens_imp_fin_algebra gen_boolean_algebra.universe point_to_atom_closed subset_eq)\n    have 2: \"\\<Union> (gen_boolean_algebra S Xs) \\<subseteq> S\"\n      using assms \n      by (simp add: Sup_le_iff gen_boolean_algebra_subset)\n    hence 3: \"\\<Union> (gen_boolean_algebra S Xs) = S\"\n      by (simp add: Union_upper gen_boolean_algebra.universe subset_antisym)\n    have 4: \"gen_boolean_algebra S (gen_boolean_algebra S Xs) = gen_boolean_algebra S Xs\"\n      using assms gen_boolean_algebra_idempotent[of S Xs] by blast \n    have 5: \"point_to_atom Xs x \\<in> gen_boolean_algebra S (gen_boolean_algebra S Xs)\"\n      unfolding  4 using assms  \n      by (metis (no_types, opaque_lifting) Int_absorb1 Int_commute Union_upper atoms_of_gen_boolean_algebra gen_boolean_algebra.generator point_to_atom_closed subsetD subsetI)\n    show ?thesis\n      using 2 5 finite_algebra_atoms_are_minimal[of \"gen_boolean_algebra S Xs\" S \"point_to_atom (gen_boolean_algebra S Xs) x\" \"point_to_atom Xs x\"] 0 1 2\n      unfolding 4  \n      by (metis \"3\" Int_commute assms(1) assms(2) assms(3) fin_gens_imp_fin_algebra point_to_atom_closed)\n  qed\nqed\n\ntext \\<open>\n  When the set \\<open>Xs\\<close> of generators covers the universe set \\<open>S\\<close>, the atoms of \\<open>Xs\\<close> in the above\n  sense are the same as the atoms of the boolean algebra they generate over \\<open>S\\<close>.\n\\<close>\n\nlemma atoms_of_sets_eq_atoms_of_algebra:\n  assumes \"finite Xs\"\n  assumes \"S = \\<Union> Xs\"\n  shows \"atoms_of Xs = atoms_of (gen_boolean_algebra S Xs)\"\nproof\n  show \"atoms_of Xs \\<subseteq> atoms_of (gen_boolean_algebra S Xs)\"\n  proof fix A assume A: \"A \\<in> atoms_of Xs\"\n    then obtain x where x_def: \"x \\<in> S \\<and> A = point_to_atom Xs x\"\n      using assms \n      by (metis atoms_induced_by_points image_iff)\n    have 0: \"A = point_to_atom (gen_boolean_algebra S Xs) x\"\n      using assms point_to_atom_equal  x_def by fastforce\n    show \"A \\<in> atoms_of (gen_boolean_algebra S Xs)\"\n      unfolding 0 using assms A \n      by (metis (full_types) \"0\" UnionI gen_boolean_algebra.universe point_to_atom_closed x_def)\n  qed\n  show \"atoms_of (gen_boolean_algebra S Xs) \\<subseteq> atoms_of Xs\"\n  proof fix A  assume A: \"A \\<in> atoms_of (gen_boolean_algebra S Xs)\"\n    then obtain x where x_def: \"x \\<in> S \\<and> A  = point_to_atom (gen_boolean_algebra S Xs) x\"\n      by (metis atoms_induced_by_points cSup_eq_maximum gen_boolean_algebra.universe gen_boolean_algebra_subset image_iff)\n    then show \"A \\<in> atoms_of Xs\" \n      using assms(1) assms(2) point_to_atom_closed point_to_atom_equal by fastforce\n  qed\nqed\n\nlemma atoms_closed:\n  assumes \"finite Xs\"\n  assumes \"A \\<in> atoms_of (gen_boolean_algebra S Xs)\"\n  assumes \"S = \\<Union> Xs\"\n  shows \"A \\<in> (gen_boolean_algebra S Xs)\"\nproof-\n  have 1: \"A = \\<Union> {A}\"\n    by blast \n  have 2: \"A \\<in> atoms_of Xs\"\n    using assms atoms_of_sets_eq_atoms_of_algebra \n    by blast\n  show ?thesis \n  using gen_boolean_algebra_generated_by_atoms[of Xs S] \n        assms 1 2 unfolding Pow_def by blast \nqed\n\nlemma atoms_finite:\n  assumes \"finite Xs\"\n  shows \"finite ((atoms_of (gen_boolean_algebra S Xs)))\"\nproof-\n  have 0: \"gen_boolean_algebra S Xs =gen_boolean_algebra S ((\\<inter>) S ` Xs)\"\n    using gen_boolean_algebra_restrict_generators by blast \n  have 1: \"gen_boolean_algebra S Xs = gen_boolean_algebra S (insert S ((\\<inter>) S ` Xs))\"\n    unfolding 0 by(rule add_generators, rule gen_boolean_algebra.universe)\n  obtain Ys where Ys_def: \"Ys = (insert S ((\\<inter>) S ` Xs))\"\n    by blast \n  have Ys_finite: \"finite Ys\"\n    unfolding Ys_def using assms by blast \n  have 2: \"\\<Union> Ys = S\"\n    unfolding Ys_def \n    by blast \n  have 3: \"atoms_of Ys = atoms_of (gen_boolean_algebra S Xs) \"\n    unfolding Ys_def 1 \n    apply(rule atoms_of_sets_eq_atoms_of_algebra)\n    using Ys_finite unfolding Ys_def apply blast\n    by blast \n  have 4: \"finite (atoms_of Ys)\"\n    by(rule finite_set_imp_finite_atoms, rule Ys_finite)\n  show ?thesis using 4 unfolding 3 by blast\nqed  \n\n\ntext \\<open>\n  We can distinguish atoms of a set of generators \\<open>Cs\\<close> by finding some element of \\<open>Cs\\<close> which\n  includes one and excludes the other.\n\\<close>\n\nlemma distinct_atoms:\n  assumes \"Cs \\<noteq> {}\"\n  assumes \"a \\<in> atoms_of Cs\"\n  assumes \"b \\<in> atoms_of Cs\"\n  assumes \"a \\<noteq> b\"\n  shows \"(\\<exists>B \\<in> Cs. b \\<subseteq> B \\<and> a \\<inter> B = {}) \\<or> (\\<exists>A \\<in> Cs. a \\<subseteq> A \\<and> b \\<inter> A = {})\"\nproof- \n  obtain x where x_def: \"x \\<in> \\<Union> Cs \\<and> a = point_to_atom Cs x\"\n    by (metis assms(2) atoms_induced_by_points imageE)\n  obtain y where y_def: \"y \\<in> \\<Union> Cs \\<and> b = point_to_atom Cs y\"\n    by (metis assms(3) atoms_induced_by_points imageE)\n  have 0: \"point_to_atom Cs x \\<noteq> point_to_atom Cs y\"\n    using x_def y_def assms by simp \n  hence 1: \"point_to_type Cs x \\<noteq> point_to_type Cs y\"\n    unfolding point_to_atom_def subset_to_atom_def by blast \n  then obtain B where B_def: \"B \\<in> Cs \\<and> (B \\<in> point_to_type Cs x - point_to_type Cs y \\<or> B \\<in> point_to_type Cs y - point_to_type Cs x)\"\n    unfolding point_to_type_def by blast \n  have 2: \"B \\<in> point_to_type Cs x - point_to_type Cs y \\<Longrightarrow> a \\<subseteq> B\"\n    using x_def  point_to_atom_def subset_to_atom_memE(1) by fastforce    \n  have 3: \"B \\<in> point_to_type Cs y - point_to_type Cs y \\<Longrightarrow> b \\<subseteq> B\"\n    using y_def by blast\n  show ?thesis using B_def 2 3 \n    by (smt Diff_iff disjoint_iff_not_equal point_to_atom_def subset_eq subset_to_atom_memE(1) subset_to_atom_memE(2) x_def y_def)\nqed\n\n\n(**************************************************************************************************)\n(**************************************************************************************************)\nsubsection\\<open>Partitions of a Set\\<close>\n(**************************************************************************************************)\n(**************************************************************************************************)\n\ndefinition disjoint :: \"'a set set \\<Rightarrow> bool\" where\n\"disjoint Ss = (\\<forall> A \\<in> Ss. \\<forall>B \\<in> Ss.  A \\<noteq>B \\<longrightarrow> A \\<inter> B = {})\"\n\nlemma disjointE: \n  assumes \"disjoint Ss\"\n  assumes \"A \\<in> Ss\"\n  assumes \"B \\<in> Ss\"\n  assumes \"A \\<noteq>B\"\n  shows \"A \\<inter> B = {}\"\n  by (meson assms(1) assms(2) assms(3) assms(4) disjoint_def)\n\nlemma disjointI: \n  assumes \"\\<And>A B. A \\<in> Ss \\<Longrightarrow> B \\<in> Ss \\<Longrightarrow> A \\<noteq> B \\<Longrightarrow> A \\<inter> B = {}\"\n  shows \"disjoint Ss\"\n  by (meson assms disjoint_def)\n\ndefinition is_partition  :: \"'a set set \\<Rightarrow> 'a set \\<Rightarrow> bool\" (infixl \"partitions\" 75) where\n\"S partitions A = (disjoint S \\<and> \\<Union> S = A)\"\n\nlemma is_partitionE: \n  assumes \"S partitions A\"\n  shows \"disjoint S\"\n        \"\\<Union> S = A\"\n  using assms is_partition_def apply blast \n  using assms \n  by (simp add: is_partition_def)\n\nlemma is_partitionI: \n  assumes \"disjoint S\"\n  assumes \"\\<Union> S = A\"\n  shows \"S partitions A\"\n  using assms is_partition_def by blast \n\ntext \\<open>\n  If we start with a finite partition of a set \\<open>A\\<close>, and each element in that partition has a\n  finite partition with some property \\<open>P\\<close>, then \\<open>A\\<close> itself has a finite partition where each\n  element has property \\<open>P\\<close>.\\<close>\n\nlemma iter_partition:\n  assumes \"As partitions A\"\n  assumes \"finite As\"\n  assumes \"\\<And>a. a \\<in> As \\<Longrightarrow> \\<exists>Bs. finite Bs \\<and> Bs partitions a \\<and> (\\<forall>b \\<in> Bs. P b)\"\n  shows \"\\<exists>Bs. finite Bs \\<and> Bs partitions A \\<and> (\\<forall>b \\<in> Bs. P b)\"\nproof- \n  obtain F where F_def: \"F = (\\<lambda>a. (SOME Bs.  finite Bs \\<and> Bs partitions a \\<and> (\\<forall>b \\<in> Bs. P b)))\"\n    by blast \n  have FE: \"\\<And>a. a \\<in> As \\<Longrightarrow> finite (F a) \\<and> (F a) partitions a \\<and> (\\<forall>b \\<in> (F a). P b)\" \n  proof- fix a assume A: \"a \\<in> As\"\n    show \"finite (F a) \\<and> (F a) partitions a \\<and> (\\<forall>b \\<in> (F a). P b)\"\n      apply(rule SomeE'[of _ \"\\<lambda>Bs.  finite Bs \\<and> Bs partitions a \\<and> (\\<forall>b \\<in> Bs. P b)\"])\n      unfolding F_def apply blast\n      using assms by (simp add: A)\n  qed\n  obtain Bs where Bs_def: \"Bs = (\\<Union> a \\<in> As. F a)\"\n    by blast \n  have 0: \"finite Bs\"\n    unfolding Bs_def using FE assms by blast \n  have 1: \"disjoint Bs\"\n  proof(rule disjointI)\n    fix a b assume A: \"a \\<in> Bs\" \"b \\<in> Bs\" \"a \\<noteq> b\"\n    obtain c where c_def: \"c \\<in> As \\<and> a \\<in>  F c\"\n      using Bs_def A by blast \n    obtain d where d_def: \"d \\<in> As \\<and> b \\<in>  F d\"\n      using Bs_def A by blast \n    have 0: \"a \\<subseteq> c\"\n      using c_def FE[of c] is_partitionE(2)[of \"F c\" c] by blast \n    have 1: \"b \\<subseteq> d\"\n      using d_def FE[of d] is_partitionE(2)[of \"F d\" d] by blast \n    show \"a \\<inter> b = {}\"\n    proof(cases \"c = d\")\n      case True\n      show ?thesis apply(rule disjointE[of \"F c\"])\n        unfolding True using FE is_partitionE d_def apply blast\n        using c_def unfolding True apply blast\n        using d_def apply blast\n        by(rule A)\n    next\n      case False\n      have \"c \\<inter> d = {}\"\n        apply(rule disjointE[of As])\n        using assms is_partitionE apply blast\n        using c_def apply blast\n        using d_def apply blast\n        using False by blast \n      then show ?thesis using 0 1 by blast  \n    qed\n  qed\n  have 2: \"(\\<forall>b \\<in> Bs. P b)\"\n    apply(rule )\n    unfolding Bs_def using FE \n    by blast\n  have FE': \"\\<And>a. a \\<in> As \\<Longrightarrow> (\\<Union> (F a)) = a \"\n    apply(rule is_partitionE)\n    using FE by blast \n  have 3: \"Bs partitions A\"\n    apply(rule is_partitionI, rule 1)\napply(rule equalityI')\n    unfolding Bs_def using assms is_partitionE(2)[of As A]\n      FE' is_partitionE(2) apply blast\n  proof- \n    fix x assume A: \"x \\<in> A\"\n    then obtain a where a_def: \"a \\<in> As \\<and> x \\<in> a\"\n      using assms is_partitionE by blast \n    then have \"x \\<in> (\\<Union> (F a))\"\n      using a_def FE' by blast \n    thus \" x \\<in> \\<Union> (\\<Union> (F ` As))\"\n      using a_def A by blast \n  qed\n  show \"\\<exists>Bs. finite Bs \\<and> Bs partitions A \\<and> (\\<forall>b\\<in>Bs. P b)\"\n    using 0 2 3 by blast \nqed\n\n(**************************************************************************************************)\n(**************************************************************************************************)\nsubsection\\<open>Intersections of Families of Sets\\<close>\n(**************************************************************************************************)\n(**************************************************************************************************)\n\ndefinition pairwise_intersect where \n\"pairwise_intersect As Bs = {c. \\<exists>a \\<in> As. \\<exists>b \\<in> Bs. c = a \\<inter> b}\"\n\nlemma partition_intersection:\n  assumes \"As partitions A\"\n  assumes \"Bs partitions B\"\n  shows \"(pairwise_intersect As Bs) partitions (A \\<inter> B)\"\nproof(rule is_partitionI, rule disjointI)\n  fix a b assume a0: \"a \\<in> pairwise_intersect As Bs\" \"b \\<in> pairwise_intersect As Bs\" \"a \\<noteq> b\"\n  obtain a1 b1 where def1: \"a1 \\<in> As \\<and> b1 \\<in> Bs \\<and> a = a1 \\<inter> b1\"\n    using a0 unfolding pairwise_intersect_def by blast \n  obtain a2 b2 where def2: \"a2 \\<in> As \\<and> b2 \\<in> Bs \\<and> b = a2 \\<inter> b2\"\n    using a0 unfolding pairwise_intersect_def by blast \n  have 0: \"a \\<inter> b = (a1 \\<inter> a2) \\<inter> (b1 \\<inter> b2)\"\n    using def1 def2 by blast \n  show \" a \\<inter> b= {}\"\n  proof(cases \"a1 \\<noteq> a2\")\n    case True\n    have T0: \"a1 \\<inter> a2 = {}\"\n      apply(rule disjointE[of As a1 a2] )\n      using def1 def2 assms(1) True is_partitionE(1)[of As A] apply blast\n      using def1 apply blast using def2 apply blast by(rule True)\n    thus ?thesis unfolding 0 by blast      \n  next\n    case False\n    then have F0: \"b1 \\<noteq> b2\"\n      using a0 def1 def2 by blast \n    have F1: \"b1 \\<inter> b2 = {}\"\n      apply(rule disjointE[of Bs b1 b2])\n      using def1 def2 assms(2) F0  is_partitionE(1)[of Bs B] apply blast\n      using def1 apply blast using def2 apply blast by(rule F0)\n    thus ?thesis unfolding 0 by blast      \n  qed\nnext \n  show \"\\<Union> (pairwise_intersect As Bs) = A \\<inter> B\"\n  proof(rule equalityI')\n    fix x assume A: \"x \\<in> \\<Union> (pairwise_intersect As Bs)\"\n    then obtain a b where def1: \"a \\<in> As \\<and> b \\<in> Bs \\<and> x \\<in> a \\<inter> b\"\n      unfolding pairwise_intersect_def by blast \n    have 0: \"a \\<subseteq> A\"\n      using def1 assms is_partitionE by blast \n    have 1: \"b \\<subseteq> B\"\n      using def1 assms is_partitionE by blast \n    show \" x \\<in> A \\<inter> B\"\n      using 0 1 def1 by blast \n  next \n    fix x assume A: \"x \\<in> A \\<inter> B\"\n    obtain a where a_def: \"a \\<in> As \\<and> x \\<in> a\"\n      using A assms is_partitionE by blast \n    obtain b where b_def: \"b \\<in> Bs \\<and> x \\<in> b\"\n      using A assms is_partitionE by blast \n    have 0: \"x \\<in> a \\<inter> b\"\n      using a_def b_def by blast \n    show \"x \\<in> \\<Union> (pairwise_intersect As Bs)\"\n      using a_def b_def 0 unfolding pairwise_intersect_def \n      by blast \n  qed\nqed\n\nlemma pairwise_intersect_finite: \n  assumes \"finite As\"\n  assumes \"finite Bs\"\n  shows \"finite (pairwise_intersect As Bs)\"\nproof- \n  have 0: \"(pairwise_intersect As Bs) = (\\<Union> a \\<in> As. (\\<inter>) a ` Bs)\"\n    unfolding pairwise_intersect_def\n    apply(rule equalityI')\n    unfolding mem_Collect_eq apply blast\n    by blast\n  have 1: \"\\<And>a. a \\<in> As \\<Longrightarrow> finite ((\\<inter>) a ` Bs)\"\n    using assms by blast \n  show ?thesis unfolding 0 using assms(1) 1 by blast \nqed\n\ndefinition family_intersect where\n\"family_intersect parts = atoms_of (\\<Union> parts)\"\n\nlemma family_intersect_partitions:\n  assumes \"\\<And>Ps. Ps \\<in> parts \\<Longrightarrow> Ps partitions A\"\n  assumes \"\\<And>Ps. Ps \\<in> parts \\<Longrightarrow> finite Ps\"\n  assumes \"finite parts\"\n  assumes \"parts \\<noteq> {}\"\n  shows \"family_intersect parts partitions A\"\nproof(rule is_partitionI)\n  show \"disjoint (family_intersect parts)\"\n    apply(rule disjointI)\n    unfolding family_intersect_def apply(rule atoms_of_disjoint)\n    apply blast\n    apply blast\n    by blast \n  show \" \\<Union> (family_intersect parts) = A\"\n  proof- \n    have 0: \"\\<Union> (family_intersect parts) = \\<Union> (\\<Union> parts)\"\n      unfolding family_intersect_def \n      apply(rule atoms_of_covers)\n      by blast \n    have 1: \"\\<And>Ps. Ps \\<in> parts \\<Longrightarrow> \\<Union>Ps = A\"\n      by(rule is_partitionE, rule assms, blast)\n    show ?thesis unfolding 0 \n      using 1 assms by blast \n  qed\nqed\n\nlemma family_intersect_memE: \n  assumes \"\\<And>Ps. Ps \\<in> parts \\<Longrightarrow> Ps partitions A\"\n  assumes \"\\<And>Ps. Ps \\<in> parts \\<Longrightarrow> finite Ps\"\n  assumes \"finite parts\"\n  assumes \"parts \\<noteq> {}\"\n  shows \"\\<And>Ps a. a \\<in> family_intersect parts \\<Longrightarrow> Ps \\<in> parts \\<Longrightarrow> \\<exists>P \\<in> Ps. a \\<subseteq> P\"\nproof- \n  fix Ps a assume A: \"a \\<in> family_intersect parts\" \"Ps \\<in> parts\"\n  have 0: \"\\<Union> Ps = A\"\n    apply(rule is_partitionE)\n    using A assms by blast \n  have 1: \"\\<Union> (family_intersect parts) = A\"\n    apply(rule is_partitionE)\n    using family_intersect_partitions assms by blast \n  have 2: \"a \\<noteq> {}\"\n    using A unfolding family_intersect_def  atoms_of_def by blast \n  obtain P where P_def: \"P \\<in> Ps \\<and> a \\<inter> P \\<noteq> {}\"\n    using 0 1 A 2 by blast \n  have P_in: \"P \\<in> (\\<Union> parts)\"\n    using P_def A by blast \n  have a_sub: \"a \\<subseteq> P\"\n    using atoms_are_minimal P_def A P_in unfolding family_intersect_def by blast \n  show \"\\<exists>P \\<in> Ps. a \\<subseteq> P\"\n    using a_sub P_def by blast \nqed\n\nlemma family_intersect_mem_inter: \n  assumes \"\\<And>Ps. Ps \\<in> (parts:: 'a set set set) \\<Longrightarrow> Ps partitions A\"\n  assumes \"\\<And>Ps. Ps \\<in> parts \\<Longrightarrow> finite Ps\"\n  assumes \"finite parts\"\n  assumes \"parts \\<noteq> {}\"\n  assumes \"a \\<in> family_intersect parts\"\n  shows \"\\<exists>f. \\<forall> Ps \\<in> parts. f Ps \\<in> Ps \\<and> a = (\\<Inter> Ps \\<in> parts. f Ps)\"\nproof-  \n  obtain f where f_def: \"f = (\\<lambda>Ps:: 'a set set. (SOME P. P \\<in> Ps \\<and> a \\<subseteq> P))\"\n    by blast \n  have f_eval: \"\\<And>Ps. Ps \\<in> parts \\<Longrightarrow> f Ps \\<in> Ps \\<and> a \\<subseteq> (f Ps)\"\n  proof- \n    fix Ps assume A: \"Ps \\<in> parts\"\n    obtain P where P_def: \"P \\<in> Ps \\<and> a \\<subseteq> P\"\n      using assms family_intersect_memE A by blast \n    show \" f Ps \\<in> Ps \\<and> a \\<subseteq> f Ps\" \n      apply(rule SomeE[of \"f Ps\" _ P])\n      unfolding f_def using A apply simp \n      by(rule P_def)\n  qed\n  have 0: \"a \\<noteq> {}\"\n    using assms unfolding family_intersect_def \n    using atoms_nonempty by blast\n  have 1: \"a = (\\<Inter> Ps \\<in> parts. f Ps)\"\n  proof(rule equalityI)\n    show 10: \"a \\<subseteq> \\<Inter> (f ` parts)\"\n      using f_eval by blast \n    show \"\\<Inter> (f ` parts) \\<subseteq> a\"\n    proof\n      fix x assume A: \"x \\<in> \\<Inter> (f ` parts)\"\n      obtain b where b_def: \"b = point_to_atom (\\<Union> parts) x\"\n        by blast \n      have b_atom: \"b \\<in> atoms_of (\\<Union> parts)\"\n        unfolding b_def apply(rule point_to_atom_closed)\n        using A f_eval assms by blast\n      show x_in_a: \"x \\<in> a\"\n      proof(rule ccontr)\n        assume \"x \\<notin> a\"\n        then have \"\\<not> b \\<subseteq> a\"\n          using b_def unfolding point_to_atom_def  point_to_type_def  subset_to_atom_def by blast\n        hence p0: \"a \\<noteq> b\"\n          by blast \n        have p1: \"b \\<inter> a = {}\"\n          apply(rule atoms_of_disjoint[of _ \"(\\<Union> parts)\"] ) \n            apply(rule b_atom)\n          using assms unfolding family_intersect_def apply blast\n          using p0 by blast \n        have p2: \" (\\<exists>B\\<in>\\<Union> parts. b \\<subseteq> B \\<and> a \\<inter> B = {}) \\<or> (\\<exists>A\\<in>\\<Union> parts. a \\<subseteq> A \\<and> b \\<inter> A = {})\"\n          using distinct_atoms[of \"\\<Union> parts\" a b] assms \n          by (metis Sup_bot_conv(1) b_atom equalityI' f_eval family_intersect_def mem_simps(2) p0)\n        show False \n        proof(cases \"(\\<exists>B\\<in>\\<Union> parts. b \\<subseteq> B \\<and> a \\<inter> B = {})\")\n          case True\n          then obtain B where B_def: \"B\\<in>\\<Union> parts \\<and> b \\<subseteq> B \\<and> a \\<inter> B = {}\"\n            by blast \n          obtain Ps where Ps_def: \"B \\<in> Ps \\<and> Ps \\<in> parts\"\n            using B_def by blast \n          have B_neq: \"B \\<noteq> f Ps\"\n            using Ps_def B_def 10 0 by blast \n          have B_cap: \"B \\<inter> f Ps = {}\"\n            apply(rule disjointE[of Ps])\n               apply(rule is_partitionE[of Ps A])\n            using Ps_def assms apply blast\n            using Ps_def apply blast\n            using f_eval Ps_def apply blast\n            by(rule B_neq)\n          have b_cap: \"b \\<inter> f Ps = {}\"\n            using B_cap B_def by blast \n          have x_in_b: \"x \\<in> b\"\n            using b_def unfolding point_to_atom_def point_to_type_def subset_to_atom_def \n            by blast  \n          show False using x_in_b b_cap Ps_def A by blast \n        next\n          case False\n          then obtain B where B_def: \"B\\<in>\\<Union> parts \\<and> a \\<subseteq> B \\<and> b \\<inter> B = {}\"\n            using p2 by blast \n          obtain Ps where Ps_def: \"B \\<in> Ps \\<and> Ps \\<in> parts\" \n            using B_def by blast \n          have F0: \"B = f Ps\"\n          proof(rule ccontr)\n            assume not: \"B \\<noteq> f Ps\"\n            have F0: \"B \\<inter> f Ps = {}\"\n             apply(rule disjointE[of Ps])\n               apply(rule is_partitionE[of Ps A])\n            using Ps_def assms apply blast\n            using Ps_def apply blast\n            using f_eval Ps_def apply blast\n            by(rule not)\n            have a_sub: \"a \\<subseteq> f Ps\"\n              using 10 Ps_def by blast \n            show False using F0 B_def a_sub 0  by blast \n          qed\n          have x_in_B: \"x \\<in> B\"\n            unfolding F0 using A Ps_def by blast \n          have x_in_b: \"x \\<in> b\"\n            using b_def unfolding point_to_atom_def point_to_type_def subset_to_atom_def \n            by blast  \n          show False using x_in_b x_in_B B_def by blast \n        qed\n      qed\n    qed\n  qed\n  show ?thesis using f_eval 1 by blast \nqed\n\ntext \\<open>\n  If we take a finite family of partitions in a particular generated boolean algebra, where each\n  partition itself is finite, then their induced partition is also in the algebra.\\<close>\nlemma family_intersect_in_gen_boolean_algebra:\n  assumes \"A \\<in> gen_boolean_algebra S B\"\n  assumes \"\\<And>Ps. Ps \\<in> parts \\<Longrightarrow> Ps partitions A\"\n  assumes \"\\<And>Ps. Ps \\<in> parts \\<Longrightarrow> finite Ps\"\n  assumes \"\\<And>Ps P. Ps \\<in> parts \\<Longrightarrow> P \\<in> Ps \\<Longrightarrow>  P \\<in> gen_boolean_algebra S B\"\n  assumes \"finite parts\"\n  assumes \"parts \\<noteq> {}\"\n  shows \"\\<And>P. P \\<in> family_intersect parts \\<Longrightarrow> P \\<in> gen_boolean_algebra S B\"\nproof- \n  fix P assume A: \"P \\<in> family_intersect parts\"\n  have 0: \"P \\<in> atoms_of (\\<Union> parts)\"\n    using A unfolding family_intersect_def by blast \n  have 1: \"finite (\\<Union> parts)\"\n    using assms by blast \n  have 2: \"\\<Union> parts \\<subseteq> gen_boolean_algebra S B\"\n    using assms  by blast \n  obtain Ps where Ps_def: \"Ps \\<in> parts\"\n    using assms by blast \n  have 3: \"\\<Union> (\\<Union> parts) = A\"\n    apply(rule equalityI')\n    using assms is_partitionE(2)[of _ A] apply blast \n    using assms is_partitionE(2)[of Ps A] Ps_def by blast \n  have 4: \"atoms_of (\\<Union> parts) = atoms_of (gen_boolean_algebra A (\\<Union> parts))\"\n    apply(rule atoms_of_sets_eq_atoms_of_algebra[of \"\\<Union> parts\" A])\n     apply(rule 1)\n    unfolding 3 by blast \n  have 5: \"atoms_of (\\<Union> parts) \\<subseteq>  (gen_boolean_algebra A (\\<Union> parts))\"\n    apply(rule atoms_of_gen_boolean_algebra)\n    using 3 gen_boolean_algebra.generator[of _ \"\\<Union> parts\" A] \n     apply (meson Sup_upper gen_boolean_algebra_generators subsetI)\n    by(rule 1)\n  have 6: \"A \\<subseteq> S\"\n    using assms gen_boolean_algebra_subset by blast  \n  have 7: \"(gen_boolean_algebra A (\\<Union> parts)) \\<subseteq> gen_boolean_algebra (S) (\\<Union> parts)\"\n    apply(rule gen_boolean_algebra_univ_mono) \n    using 3 gen_boolean_algebra_finite_union[of \"\\<Union> parts\" \"S\" \"\\<Union> parts\"]\n          gen_boolean_algebra.generator[of _ \"\\<Union> parts\" \"S\" ] 6 1 \n    by (meson Sup_le_iff gen_boolean_algebra_generators)\n  have 8: \"gen_boolean_algebra (S) (\\<Union> parts) \\<subseteq> gen_boolean_algebra S B\"\n    apply(rule gen_boolean_algebra_subalgebra)\n    using 2  by blast \n  show \"P \\<in> gen_boolean_algebra S B\"\n    using 0 5 6 7 8 by blast \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/Padic_Field/Generated_Boolean_Algebra.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8577681195338728, "lm_q2_score": 0.8311430520409023, "lm_q1q2_score": 0.7129280128127685}}
{"text": "theory SortM\nimports Main\n        Naturals\n        Listing\nbegin\n\nfun sorted :: \"nat List \\<Rightarrow> bool\" where\n  \"sorted Nil                   = True\"\n| \"sorted (Cons _ Nil)          = True\"\n| \"sorted (Cons r (Cons t ts))  = ( r \\<le> t \\<and> sorted (Cons t ts))\"\n\nfun insert :: \"Nat \\<Rightarrow> Nat List \\<Rightarrow> Nat List\" where\n  \"insert r Nil         = Cons r Nil\"\n| \"insert r (Cons t ts) = (if leq r t then Cons r (Cons t ts) else (Cons t (insert r ts)))\"\n\n\nfun isort :: \"Nat List \\<Rightarrow> Nat List\" where\n  \"isort Nil = Nil\"\n| \"isort (Cons t ts) = insert t (isort ts)\"\n\nfun qsort :: \"Nat list \\<Rightarrow> Nat list\" where\n  \"qsort [] = []\"\n| \"qsort (t # ts) = (qsort [r <- ts. leq r t]) @ [t] @ (qsort [r <- ts. \\<not> (leq r t)])\"\n\nthm qsort.induct\n\nfun sorted2 :: \"Nat list \\<Rightarrow> bool\" where\n  \"sorted2 []                   = True\"\n| \"sorted2 [x]         = True\"\n| \"sorted2 (r # (t # ts))  = (leq r t \\<and> sorted2 (t # ts))\"\n\nfun merge :: \"Nat list \\<Rightarrow> Nat list \\<Rightarrow> Nat list\" where\n  \"merge rs [] = rs\"\n| \"merge [] ts = ts\"\n| \"merge (r#rs) (t#ts) = (if leq r t then r # merge rs (t#ts)\n                                     else t # merge (r#rs) ts)\"\n\nfun msort :: \"Nat list => Nat list\" where\n  \"msort [] = []\"\n| \"msort [t] = [t]\"\n| \"msort ts = merge (msort (List.take (length ts div 2) ts)) (* size instead? *)\n                    (msort (List.drop (length ts div 2) ts))\"\n\n\nlemma lemma_a [thy_expl]: \"leq x2 x2 = True\"\nby (hipster_induct_schemes leq.simps)\n\nlemma lemma_aa [thy_expl]: \"leq x2 (S x2) = True\"\nby (hipster_induct_schemes leq.simps)\n\nlemma lemma_ab [thy_expl]: \"leq (S x2) x2 = False\"\nby (hipster_induct_schemes leq.simps)\n\n(*hipster_cond le*)\nlemma lemma_ac [thy_expl]: \"leq x2 y2 \\<Longrightarrow> leq x2 (S y2) = True\"\nby (hipster_induct_schemes leq.simps)\n\nlemma lemma_ad [thy_expl]: \"leq y2 x2 \\<Longrightarrow> leq (S x2) y2 = False\"\nby (hipster_induct_schemes leq.simps)\n\nlemma lemma_ae [thy_expl]: \"leq y x \\<and> leq x y \\<Longrightarrow> x = y\"\nby (hipster_induct_schemes leq.simps Nat.exhaust)\n\n\nlemma le_trans [thy_expl]: \"leq z y \\<and> leq x z \\<Longrightarrow> leq x y = True\"\nby (hipster_induct_schemes leq.simps Nat.exhaust)\n\n(*hipster_cond leq sorted2 merge leq\n\nhipster_cond sorted2 leq merge sorted2\n\n\nhipster merge sorted2\n*)\n\n(* lemma sortCons: \"r \\<le> t \\<and> sorted2 (t # ts) \\<Longrightarrow> sorted2 (r # (t # ts))\" by simp *)\nlemma insSortInvar : \"sorted ts \\<Longrightarrow> sorted (insert t ts)\"\nby hipster_induct_schemes\n\nlemma mer1[thy_expl]: \"sorted2 ts \\<Longrightarrow> sorted2 (merge [] ts)\"\n(*by(metis sorted2.cases merge.simps)*) (* replace of cases by inductions *)\nby hipster_induct_simp_metis\n\nlemma mer2[thy_expl]: \"sorted2 ts \\<Longrightarrow> sorted2 (merge [t] ts)\" (* sorted2.induct! *)\nby hipster_induct_schemes\n\nlemma mer3[thy_expl]: \"sorted2 ts \\<Longrightarrow> sorted2 (merge ts [t])\" (* sorted2.induct! *)\nby hipster_induct_schemes\n\nlemma mer4[thy_expl]: \"sorted2 (t # ts) \\<and> \\<not> (leq t r) \\<Longrightarrow> sorted2 (r # (merge (t#ts) []))\" by simp\n\nlemma mer4'[thy_expl]: \"sorted2 (t # ts) \\<and> leq t r \\<Longrightarrow> sorted2 (t # merge ts [r])\"\nby (hipster_induct_schemes merge.simps mer3)\n\nlemma mer5'[thy_expl]: \"sorted2 (t # ts) \\<and> leq r v \\<and> \\<not> (leq t r) \\<Longrightarrow> sorted2 (r # (merge (t#ts) [v]))\"\n(*apply(induction ts rule: sorted2.induct)\napply(simp_all add: mer4 mer3 mer2 mer1)\napply(metis sorted2.simps merge.simps)*)\nby (hipster_induct_schemes merge.simps mer3)\n\nlemma mer5''[thy_expl]: \"sorted2 (r # rs) \\<and> \\<not> (leq t r) \\<Longrightarrow> sorted2 (r # (merge [t] rs))\"\nby (hipster_induct_schemes sorted2.simps)\n\nlemma ssu[thy_expl]: \"sorted2 (r # rs) \\<and> (leq t r) \\<Longrightarrow> sorted2 (t # (merge [] (r#rs)))\" by (metis merge.simps sorted2.simps)\n(*by (hipster_induct_simp_metis)*)\n\nlemma ssu'[thy_expl]: \"sorted2 (r # rs) \\<and> (leq t v) \\<and> (leq t r) \\<Longrightarrow> sorted2 (t # (merge [v] (r#rs)))\"\nby (metis mer5'' merge.simps sorted2.simps)\nlemma ssu''[thy_expl]: \" sorted2 [t, v] \\<and> sorted2 (r # rs) \\<and> leq t r \\<Longrightarrow> sorted2 (t # (merge [v] (r#rs)))\"\n(*by (metis sorted2.simps(3) ssu')*)\nby (hipster_induct_schemes sorted2.simps mer5'')\n\nlemma cons1[thy_expl]: \"sorted2 (t # ts) \\<Longrightarrow> sorted2 ts\"\nby hipster_induct_simp_metis\n(*by (metis sorted2.elims(3) sorted2.simps(3))*)\n\nlemma t1 : \"sorted2 ts \\<and> ts \\<noteq> [] \\<and> leq t (hd ts) \\<Longrightarrow> sorted2 (t # ts)\"\nby hipster_induct_simp_metis\n(*by (metis list.sel sorted2.elims(3))*)\n\nlemma mer6[thy_expl]: \"(sorted2 ts \\<and> ts \\<noteq> [] \\<and> sorted2 (r # rs)) \\<Longrightarrow> (sorted2 ((merge ts (r#rs))))\"\napply(induction ts rule: sorted2.induct)\napply(induction rs rule: sorted2.induct)\napply(simp_all only: thy_expl)\napply(simp add: ssu'')\napply(rule conjI)\napply(rule impI)\napply(simp add: thy_expl)\napply(rule impI)\napply(rule conjI)\napply(simp add: thy_expl)\napply(simp add: thy_expl)\noops\n(*by (hipster_induct_schemes ssu' ssu'' mer5' mer5'' mer3)\nsledgehammer\napply(metis sorted2.simps ssu'' mer3 ssu ssu' mer4 mer2 mer1 t1 mer5' mer5'' mer4')*)\n\n(* simplification can very much screw up the goal state! *)\nlemma mer5[thy_expl]: \"(sorted2 (t # ts) \\<and> sorted2 (r # rs) \\<and> leq t r) \\<Longrightarrow> (sorted2 (t # (merge ts (r#rs))))\"\napply(induction ts rule: sorted2.induct)\napply(simp)\napply(simp add: mer5'')\napply(simp add: mer4' mer5'' mer3 ssu' ssu'' ssu)\napply(rule conjI)\napply(rule impI)\napply simp\napply(rule impI, rule conjI)\napply(simp_all)\napply(drule conjE)\napply(simp_all add: ssu' mer5'' mer4 mer4' mer3 mer2 mer1 ssu'' mer5')\n(*apply (metis (full_types) sorted2.simps merge.simps if_splits list.exhaust list.distinct)*)\n(*apply(simp add: ssu ssu' mer3 mer2 mer1 ssu'' mer5' mer4')*)\n(*apply(metis merge.simps(3) mer5' mer4' mer3 mer4)*)\nsorry\n\nlemma mergeS: \"sorted2 ts \\<and> sorted2 rs \\<Longrightarrow> sorted2 (merge ts rs)\"\napply(induction ts rs rule: merge.induct)\nsledgehammer\napply (metis merge.simps(1))\nsledgehammer\napply (metis merge.simps(2))\nsledgehammer\nsledgehammer min [e] (cons1 mer4 mer5 merge.elims merge.simps(1) merge.simps(3) Nat_induct ord.lexordp_eq.simps ord.lexordp_eq_simps(3) qsort.cases sorted2.simps(3))\napply(simp_all add: mer1 mer2)\n(*sledgehammer*)\nby (metis mer4 mer5 merge.simps sorted2.simps)\n(*\napply(cases rs)\napply(simp_all)\nby (hipster_induct_schemes mer1 mer5'' mer5 merge.simps sorted2.simps)*)\n(*apply(induction ts rule: sorted2.induct)\napply(simp add: mer1)\napply(simp add: mer5'')\nby (metis mer4 mer5 merge.simps sorted2.simps)*)\n(* apply(induction ts rule: sorted2.induct)\napply(simp add: mer1)\napply(simp add: mer2)\napply(cases rs)\napply(simp_all)\nby (metis mer4 mer5 merge.simps sorted2.simps)*)\n(*   by (induct xs ys rule: merge.induct) (auto simp add: ball_Un not_le less_le sorted_Cons) *)\n\nlemma smsort: \"sorted2 (msort xs)\"\nby (hipster_induct_schemes mergeS)\n\n(*lemma merComm: \"sorted2 ts \\<and> sorted2 rs \\<Longrightarrow> merge rs ts = merge ts rs\"\napply(induction rs ts rule: merge.induct)\napply(simp_all)\napply(metis sorted2.cases merge.simps(1) merge.simps(2))*)\n\n\n\n(*\nfun merge :: \"Nat list \\<Rightarrow> Nat list \\<Rightarrow> Nat list\" where\n  \"merge [] ts = ts\"\n| \"merge rs [] = rs\"\n| \"merge (r#rs) (t#ts) = (if leq r t then (r # (merge rs (t #\u00a0ts)) )\n                                     else (t # (merge (r # rs) ts) ) )\"\n\nfun msort :: \"Nat list \\<Rightarrow> Nat list\" where\n  \"msort [] = []\"\n| \"msort [t] = [t]\"\n| \"msort ts = merge (msort (take ((length ts) div 2) ts))\n                    (msort (drop ((length ts) div 2) ts))*)\n(* in a let ... *)\n\n\n\n(* qsort *)\n\n\n\nend\n\n\n", "meta": {"author": "moajohansson", "repo": "IsaHipster", "sha": "91f6ea3f1166a9de547722ece6445fe843ad89b4", "save_path": "github-repos/isabelle/moajohansson-IsaHipster", "path": "github-repos/isabelle/moajohansson-IsaHipster/IsaHipster-91f6ea3f1166a9de547722ece6445fe843ad89b4/TestTheories/SortM.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357598021707, "lm_q2_score": 0.8221891239865619, "lm_q1q2_score": 0.7128673718167698}}
{"text": "theory a3\n  imports \"autocorres-1.4/autocorres/AutoCorres\" \nbegin\n\n(* To run this file you need the AutoCorres tool used\n   in the lecture.\n\n  1. Download AutoCorres from \n       \\url{http://www.cse.unsw.edu.au/~cs4161/autocorres-1.4.tar.gz}\n\n  2. Unpack the .tar.gz file, which will create the directory autocorres-1.4\n       tar -xzf autocorres-1.4.tar.gz\n\n  3. Build the AutoCorres heap\n     L4V_ARCH=X64 isabelle build -v -b -d autocorres-1.4 AutoCorres\n\n  4. Load this file using the AutoCorres heap\n     L4V_ARCH=X64 isabelle jedit -d autocorres-1.4 -l AutoCorres a3.thy\n\n*)\n\nsection \"Question 1: Regular Expression Matching\"\n\n(* Negation is too hard with this one, so we add Null and One instead *)\ndatatype regexp =\n   Null\n | One\n | Atom char\n | Alt regexp regexp\n | Conc regexp regexp (infixl \"\\<cdot>\"  60)\n | Star regexp\n\n(* Same definitions for regular languages as in the lecture, but with Null and One *)\ninductive_set star :: \"string set \\<Rightarrow> string set\" for L\n  where\n  star_empty[simp,intro!]: \"[] \\<in> star L\"\n| star_app[elim]: \"\\<lbrakk> u \\<in> L; v \\<in> star L \\<rbrakk> \\<Longrightarrow> u@v \\<in> star L\"\n\ndefinition conc :: \"string set \\<Rightarrow> string set \\<Rightarrow> string set\"\n  where\n  \"conc A B \\<equiv> {xs@ys |xs ys. xs \\<in> A \\<and> ys \\<in> B}\"\n\nprimrec lang :: \"regexp \\<Rightarrow> string set\"\n  where\n  \"lang Null = {}\"\n| \"lang One = {[]}\"\n| \"lang (Atom c) = {[c]}\"\n| \"lang (Alt e1 e2) = lang e1 \\<union> lang e2\"\n| \"lang (Conc e1 e2) = conc (lang e1) (lang e2)\"\n| \"lang (Star e) = star (lang e)\"\n\n\n(* For examples/testing. *)\nprimrec string :: \"char list \\<Rightarrow> regexp\"\n  where\n  \"string []     = One\"\n| \"string (x#xs) = Atom x \\<cdot> string xs\"\n\n(* Automatically coerce type \"char list\" into \"regexp\" using the function \"string\" *)\ndeclare [[coercion string]]\n(* Enable automatic type coercion *)\ndeclare [[coercion_enabled]]\n(* Can now write: *)\nterm \"Star ''abc''\"\n\n\n(* This definition is taken from\n   https://www.schoolofhaskell.com/school/to-infinity-and-beyond/pick-of-the-week/a-regular-expression-matcher\n*)\nfunction matches :: \"regexp \\<Rightarrow> string \\<Rightarrow> (string \\<Rightarrow> bool) \\<Rightarrow> bool\"\n  where\n  \"matches Null         cs k = False\"\n| \"matches One          cs k = k cs\"\n| \"matches (Atom c)     cs k = (cs \\<noteq> [] \\<and> c = hd cs \\<and> k (tl cs))\"\n| \"matches (Alt r1 r2)  cs k = (matches r1 cs k \\<or> matches r2 cs k)\"\n| \"matches (Conc r1 r2) cs k =  matches r1 cs (\\<lambda>cs'. matches r2 cs' k)\"\n| \"matches (Star r)     cs k = (k cs \\<or> matches r cs (\\<lambda>cs'. if cs' \\<noteq> cs\n                                                           then matches (Star r) cs' k\n                                                           else False))\"\n  by pat_completeness auto\n\n(* Either change the cs' = cs condition to something more obviously terminating so that\n   property \"matches_correct\" below still holds (easier) or prove termination of the\n   version above directly (harder). *)\ntermination matches\n  sorry (* TODO *)\n\nvalue \"matches ''xy'' ''xy'' (op = [])\"\nvalue \"matches ''xyz'' ''xy'' (op = [])\"\nvalue \"matches (Star ''xy'') ''xyxy'' (op = [])\"\n\nlemma concD[dest!]:\n  \"xs \\<in> conc A B \\<Longrightarrow> \\<exists>as bs. as \\<in> A \\<and> bs \\<in> B \\<and> xs = as@bs\"\n  by (auto simp: conc_def)\n\nlemma star_cases:\n  \"xs \\<in> star A \\<Longrightarrow> xs = [] \\<or> (\\<exists>u v. xs = u@v \\<and> u \\<in> A \\<and> v \\<in> star A \\<and> u \\<noteq> [])\"\n  oops (* TODO *)\n\nlemma matches_correct:\n  \"matches r cs (op = []) = (cs \\<in> lang r)\"\n  oops (* TODO *)\n\n(*-------------------------------------------------*)\nsection \"Question 2: Binary Search\"\n\n(* Hints: \n    - remember to try the @{text arith} proof method for arithmetic goals on\n      integers or natural numbers. \n    - use find_theorems to find Isabelle library theorems about existing concepts.\n    - the lemma @{thm sorted_equals_nth_mono} might be useful\n    - you are allowed to use sledgehammer and other automation\n    - if you can't prove one of the lemmas below, you can still assume it in the rest of the proof\n    - the function @{const int} converts an Isabelle nat to an int\n    - the function @{const nat} converts an Isabelle int to a nat\n*)\n\nthm sorted_equals_nth_mono\nterm int\nterm nat\n\ninstall_C_file \"binsearch.c\"\n\nautocorres [unsigned_word_abs=binary_search] \"binsearch.c\"\n\n(*******************************************************************************)\n\ncontext binsearch\nbegin\n\n(* The monadic definition that autocorres produces for the C code: *)\nthm binary_search'_def\n\n(* Abbreviation for signed machine integers *)\ntype_synonym s_int = \"32 signed word\"\n\n(* The heap only stores unsigned machine integers;\n   they have the same representation as signed ones and can be converted to each other *)\ntype_synonym u_int = \"32 word\"\n\n(*******************************************************************************)\n\n(* A few lemmas to help improve automation: *)\n\n(* Pointer arithmetic on pointers to signed and unsigned words is the same *)\nlemma ptr_coerce_add_signed_unsigned [simp]:\n  \"(ptr_coerce ((a :: s_int ptr) +\\<^sub>p x) :: u_int ptr) = ptr_coerce a +\\<^sub>p x\"\n  by (cases a) (simp add: ptr_add_def)\n\n(* Pointer arithmetic distributivity law *)\nlemma ptr_add_add [simp]:\n  \"p +\\<^sub>p (x + y) = p +\\<^sub>p x +\\<^sub>p y\"\n  by (simp add: ptr_add_def distrib_left mult.commute)\n\n(* C division is the same as Isabelle division for non-negative numbers: *)\nlemma sdiv [simp]:\n  \"0 \\<le> a \\<Longrightarrow> a sdiv 2 = a div (2::int)\"\n  by (auto simp: sdiv_int_def sgn_if)\n\n(* Some useful facts about INT_MIN and INT_MAX to improve automation: *)\nlemma INT_MIN_neg [simp]:\n  \"INT_MIN < 0\"\n  by (simp add: INT_MIN_def)\nlemma INT_MAX_gr [simp]:\n  \"- 1 < INT_MAX\" \"-1 \\<le> INT_MAX\" \"1 \\<le> INT_MAX\"\n  by (auto simp add: INT_MAX_def)\n\n(*******************************************************************************)\n\n(* This function enumerates the addresses of the entries of an signed int array: *)\nfun array_addrs :: \"s_int ptr \\<Rightarrow> nat \\<Rightarrow> s_int ptr list\" where\n  \"array_addrs p 0 = []\" |\n  \"array_addrs p (Suc len) = p # array_addrs (p +\\<^sub>p 1) len\"\n\ntext \\<open> Prove the following lemma: \\<close>\nlemma length_array_addrs [simp]:\n  \"length (array_addrs a len) = len\"\n  (* TODO *)\n  apply (induct len arbitrary: a)\n  apply auto\n  done\n\ntext \\<open> Prove the following lemma: \\<close>\nlemma array_addrs_nth [simp]:\n  \"\\<lbrakk> 0 \\<le> x; nat x < len \\<rbrakk> \\<Longrightarrow> array_addrs a len ! nat x = a +\\<^sub>p x\"\n  (* TODO *)\n  apply (induct len arbitrary: a x)\n   apply simp+\n  apply (case_tac \"x = 0\")\n   apply simp+\n  apply (subgoal_tac \"\\<exists>y. x = 1 + y \\<and> 0 \\<le> y\")\n   (* sledgehammer *)\n   apply (metis (mono_tags, hide_lams) Suc_less_eq Suc_nat_eq_nat_zadd1 binsearch.ptr_add_add diff_Suc_Suc diff_zero)\n  apply (metis le0 less_handy_casesE nat_0_iff nat_code(2) nat_int nat_le_iff nonneg_int_cases of_nat_Suc)\n  done\n\n(*******************************************************************************)\ntext \\<open> fill in the array_list definition \\<close>\ndefinition array_list :: \"(u_int ptr \\<Rightarrow> u_int) \\<Rightarrow> s_int ptr \\<Rightarrow> int \\<Rightarrow> int list\" where\n  \"array_list h p len = map (uint o h o ptr_coerce) (array_addrs p (nat len))\"\n\n(* Convert len to nat first\n   Then obtain the array address list using array_addrs\n   Upon completion of (array_addrs p (nat len)) we will have a list of signed pointers\n   ptr_coerce will convert the list of signed pointers to unsigned pointers\n   Then the heap function will dereference the value\n   Finally, uint will convert the type from signed int to isabelle int\n   the map function will apply the above to all elements in the list and will return a list*)\n\n\nthm uint\nthm array_list_def\nfind_theorems \"map (_ o _) _\"\n\n(*******************************************************************************)\ntext \\<open> Prove the following lemma: \\<close>\n\nlemma ptr_array:\n  \"\\<lbrakk> 0 \\<le> x; x < len \\<rbrakk> \\<Longrightarrow>\n   uint (heap_w32 s (ptr_coerce (a :: s_int ptr) +\\<^sub>p x)) = array_list (heap_w32 s) a len ! nat x\"\n  apply (simp add: array_list_def)\n  done\n\n(*******************************************************************************)\ntext \\<open> fill in the valid_array definition. It might make sense to do this in two parts and look\n   at the invariant and proof obligations first. \\<close>\n\ndefinition valid_array1 :: \"(u_int ptr \\<Rightarrow> bool) \\<Rightarrow> s_int ptr \\<Rightarrow> int \\<Rightarrow> bool\" where\n  \"valid_array1 vld p len = \n  (\\<forall>p' \\<in> ptr_coerce ` set (array_addrs p (nat len)). vld p')\"\n\n(* set (array_addrs p (nat len)) will return a set of signed integer pointers given p\n   p' is the set of unsigned integer pointers given p, applied via ptr_coerce '\n   vld p' checks for each element in the modified set whether the pointer value is valid*)\n\ndefinition valid_array2 :: \"(u_int ptr \\<Rightarrow> bool) \\<Rightarrow> (u_int ptr \\<Rightarrow> u_int) \\<Rightarrow> s_int ptr \\<Rightarrow> int \\<Rightarrow> bool\" where\n  \"valid_array2 vld h p len = \n  (\\<forall>p' \\<in> ptr_coerce ` set (array_addrs p (nat len)). unat (h p') \\<le> nat INT_MAX)\"\n\n(* same procedure as before; this time the validity of the actual elements are being checked\n   this time, we check if each element does not exceed the upper bound of INT_MAX, which\n   for 32-bit systems would be estimated to 2^31 - 1 *)\n\ndefinition valid_array :: \"(u_int ptr \\<Rightarrow> bool) \\<Rightarrow> (u_int ptr \\<Rightarrow> u_int) \\<Rightarrow> s_int ptr \\<Rightarrow> int \\<Rightarrow> bool\" where\n  \"valid_array vld h p len = (valid_array1 vld p len \\<and> valid_array2 vld h p len)\"\n\n(* valid_array checks two things:\n    1. if the pointer value is valid\n    2. assuming 1 holds, if the actual value pointed by the pointer is valid\n   if both conditions are met, the the array is valid. *)\n\n(*******************************************************************************)\n\n\ntext \\<open> Prove the following lemma: \\<close>\n\nthm sorted_equals_nth_mono\n\nlemma key_lt:\n  \"\\<lbrakk> key < xs ! nat mid;  mid - 1 < x; sorted xs; 0 \\<le> mid; x < int (length xs) \\<rbrakk> \n  \\<Longrightarrow> key < xs ! nat x\"\n  apply (simp add: sorted_equals_nth_mono)\n  apply (case_tac \"mid = x\")\n   apply simp+\n  apply (erule_tac x = \"nat x\" in allE)\n  apply (erule impE)\n   apply simp+\n  apply (erule_tac x = \"nat mid\" in allE)\n  apply (erule impE)\n   apply arith+\n  apply (simp add: less_le_trans)\n  done\n\ntext \\<open> Prove the following lemma: \\<close>\nlemma key_gt:\n  \"\\<lbrakk> xs ! nat mid < key; 0 \\<le> x; x \\<le> mid; sorted xs; mid < int (length xs) \\<rbrakk>\n  \\<Longrightarrow> xs ! nat x < key\"\n  apply (simp add: sorted_equals_nth_mono)\n  apply (case_tac \"mid = x\")\n   apply simp+\n  apply (erule_tac x = \"nat mid\" in allE)\n  apply (erule impE)\n   apply simp+\n  apply (erule_tac x = \"nat x\" in allE)\n  apply (erule impE)\n  apply arith+\n  apply simp\n  done\n\n(*******************************************************************************)\n\ntext \\<open> extra lemmas needed \\<close>\n\nlemma length_array_list [simp]:\n  \"length (array_list h a len) = nat len\"\n  unfolding array_list_def by simp\n\nlemma array_addrs:\n  \"\\<lbrakk> 0 \\<le> x; nat x < len \\<rbrakk> \\<Longrightarrow> p +\\<^sub>p x \\<in> set (array_addrs p len)\"\n  by (force simp add: set_conv_nth)\n\nlemma valid_arrayD:\n  \"\\<lbrakk> valid_array vld h p len; 0 \\<le> x; x < len \\<rbrakk> \n  \\<Longrightarrow> vld (ptr_coerce p +\\<^sub>p x) \\<and> unat (h (ptr_coerce p +\\<^sub>p x)) \\<le> nat INT_MAX\"\n  unfolding valid_array_def valid_array1_def valid_array2_def\n  apply clarsimp\n  apply (drule bspec)\n   apply (fastforce intro: array_addrs)\n  apply (drule bspec)\n   apply (fastforce intro: array_addrs)\n  apply simp\n  done\n\n(*******************************************************************************)\n\nlemma binary_search_correct:\n  notes ptr_array [where len=len, simp]\n  shows\n   (* precondition *)\n  \"\\<lbrace>\\<lambda>s. sorted (array_list (heap_w32 s) a len) \\<and> (* array is sorted *)\n        valid_array (is_valid_w32 s) (heap_w32 s) a len \\<and> (* all elements and pointers in array is valid *)\n        (*TODO*) 0 \\<le> len \\<and> len + len -2 \\<le> INT_MAX \\<rbrace> (* range/size of length is valid *)\n   (* program *)\n   binary_search' a len key\n   (* postcondition *)\n   \\<lbrace> \\<lambda>r s. (r < 0 \\<longrightarrow> key \\<notin> set (array_list (heap_w32 s) a len)) \\<and> (* key is not in the array *)\n           (0 \\<le> r \\<longrightarrow> r < len \\<and> (array_list (heap_w32 s) a len ! nat r) = key)\\<rbrace>! (* if r is a valid nonnegative value, then the rth element is the key *)\"\n  unfolding binary_search'_def\n  apply(subst whileLoopE_add_inv[where\n               I=\"\\<lambda>(high,low) s. valid_array (is_valid_w32 s) (heap_w32 s) a len \\<and> (* check the validity of the array *)\n                                 sorted (array_list (heap_w32 s) a len) \\<and> (* check if the elements in the array are sorted *)\n                                 (*TODO*) 0 \\<le> low \\<and> low \\<le> len \\<and> high < len \\<and> len + len -2 \\<le> INT_MAX \\<and> (* check low and high are within a valid range *)\n                                 (\\<forall>x. 0 \\<le> x \\<longrightarrow> x < low \\<longrightarrow> array_list (heap_w32 s) a len ! nat x < key) \\<and> (* all x less than low are positioned before the key *)\n                                 (\\<forall>x. high < x \\<longrightarrow> x < len \\<longrightarrow> array_list (heap_w32 s) a len ! nat x > key) (*  all x greater than high are positioned after the key*)\" and \n               M=\"\\<lambda>((high,low),_).(*TODO*) nat (high + 1 - low)\"]) (* idk *)\n  apply (simp add:INT_MAX_def INT_MIN_def)\n  apply wp\n      prefer 3\n      apply wp\n     prefer 3\n     apply wp\n    prefer 3\n    apply wp\n    apply clarsimp\n   apply clarsimp\n   apply (rename_tac high low s)\n   apply (drule_tac x=\"(low + high) div 2\"\n          in valid_arrayD [unfolded INT_MAX_def], simp+)\n   apply (intro conjI impI; clarsimp?; arith?)\n    apply (erule (2) key_lt, simp+)\n   apply (erule (3) key_gt, simp)\n  apply clarsimp\n  apply (rename_tac high low s)\n  apply (clarsimp simp: not_le set_conv_nth)\n  apply (drule_tac x=\"int i\" in spec)\n  apply (drule_tac x=\"int i\" in spec)\n  apply clarsimp\n  apply arith\n\nend\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/a3.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.8902942363098472, "lm_q1q2_score": 0.7128514745254202}}
{"text": "theory Perm\nimports Main Rat VHelper Lang\nbegin\n\ntext {* This file contains a soundness proof for CSL with multiple resources\n  and permissions. *}\n\ntext {* (Adapted to Isabelle 2016-1 by Qin Yu and James Brotherston) *}\n\nsubsection {* Permission model *}\n\ntext {* Fractional permissions are rational numbers in the range (0,1]. *}\n\ntypedef myfrac = \"{x::rat. 0 < x \\<and> x \\<le> 1}\" \nby (rule_tac x=\"0.5\" in exI, simp)\n\ndefinition \"pfull \\<equiv> Abs_myfrac 1\"        (*r Full permission *)\n\ntype_synonym pheap  = \"(nat \\<rightharpoonup> nat * myfrac)\"       (*r Permission heaps *)\ntype_synonym pstate = \"stack \\<times> pheap\"               (*r Permission states *)\n\ntext {* Definition when two permission heaps are composable. *}\n\ndefinition\n  pdisj :: \"pheap \\<Rightarrow> pheap \\<Rightarrow> bool\"\nwhere\n  \"pdisj h1 h2 \\<equiv> (\\<forall>x. case h1 x of None \\<Rightarrow> True | Some y1 \\<Rightarrow>\n                      (case h2 x of None \\<Rightarrow> True | Some y2 \\<Rightarrow>\n                       fst y1 = fst y2 \\<and>\n                       Rep_myfrac (snd y1) + Rep_myfrac (snd y2) \\<le> 1))\"\n\ntext {* Composition of two permission heaps. *}\n\ndefinition\n  padd :: \"pheap \\<Rightarrow> pheap \\<Rightarrow> pheap\"\nwhere\n  \"padd h1 h2 \\<equiv> \n     (\\<lambda>x. case h1 x of None \\<Rightarrow> h2 x | Some y1 \\<Rightarrow>\n          (case h2 x of None \\<Rightarrow> h1 x | Some y2 \\<Rightarrow>\n           Some (fst y1, Abs_myfrac (Rep_myfrac (snd y1) + Rep_myfrac (snd y2)))))\"\n\ntext {* Composition of two permission heaps, better for automation. *}\n\ndefinition\n  mypadd :: \"pheap option \\<Rightarrow> pheap option \\<Rightarrow> pheap option\"\n  (infixr \"\\<oplus>\" 100)\nwhere\n  \"xo \\<oplus> yo \\<equiv> case xo of None \\<Rightarrow> None | Some x \\<Rightarrow>\n             (case yo of None \\<Rightarrow> None | Some y \\<Rightarrow> \n              if pdisj x y then Some (padd x y) else None)\"\n\ntext {* Full-permission domain of a permission heap *}\n\ndefinition \"fpdom h \\<equiv> {x. \\<exists>v. h x = Some (v, pfull)}\"\n\ntext {* Mapping from permission heaps to normal heaps *}\n\ndefinition\n  ptoheap :: \"pheap option \\<Rightarrow> heap \\<Rightarrow> bool\"\nwhere\n  \"ptoheap ho h \\<equiv> case ho of None \\<Rightarrow> False | Some ha \\<Rightarrow>\n                  (\\<forall>x. case ha x of None \\<Rightarrow> h x = None | Some y \\<Rightarrow> \n                   snd y = pfull \\<and> h x = Some (fst y))\"\n\ntext {* Basic properties of fractions in the range (0,1] *}\n\nlemmas rat_simps = \n  add_rat eq_rat one_rat zero_rat mult_rat le_rat minus_rat diff_rat\n\nlemmas frac_simps =\n  Rep_myfrac_inverse Rep_myfrac Abs_myfrac_inverse Abs_myfrac_inject\n\nlemma frac_contra[simp]: \n  \"\\<not> (Rep_myfrac pfull + Rep_myfrac b \\<le> 1)\"\n  \"\\<not> (Rep_myfrac b + Rep_myfrac pfull \\<le> 1)\"\nby (case_tac b, auto simp add: pfull_def frac_simps)+\n\nlemma frac_pos: \"0 < Rep_myfrac x\" \nby (case_tac x, simp add: frac_simps)\n\nlemma frac_pos2[simp]: \n  \"0 < Rep_myfrac x + Rep_myfrac y\"\n  \"0 < Rep_myfrac x + (Rep_myfrac y + Rep_myfrac z)\"\nby (case_tac x, (case_tac y)?, (case_tac z)?, simp add: frac_simps)+\n\ntext {* Properties of permission-heaps *}\n\nlemma pdisj_empty[simp]:\n  \"pdisj x Map.empty\"\n  \"pdisj Map.empty x\"\nby (clarsimp simp add: pdisj_def split: option.splits)+\n\nlemma pdisj_upd: \"h x = Some (w, pfull) \\<Longrightarrow> pdisj (h(x \\<mapsto> (v, pfull))) h' = pdisj h h'\"\nby (simp add: pdisj_def, rule iff_allI, auto split: option.splits)\n\nlemma pdisj_comm: \"pdisj h1 h2 = pdisj h2 h1\"\nby (fastforce split: option.splits simp add: pdisj_def)\n\nlemma padd_empty[simp]:\n  \"padd x Map.empty = x\"\n  \"padd Map.empty x = x\"\nby (rule ext, clarsimp simp add: padd_def split: option.splits)+\n\nlemma padd_comm[simp]: \"pdisj x y \\<Longrightarrow> padd y x = padd x y\"\nby (fastforce split: option.splits simp add: padd_def pdisj_def algebra_simps)\n\nlemma pdisj_padd: \"\\<lbrakk> pdisj y z ; pdisj x (padd y z) \\<rbrakk> \\<Longrightarrow> (pdisj x y \\<and> pdisj x z)\"\napply (clarsimp simp add: pdisj_def padd_def all_conj_distrib [symmetric])\napply (drule_tac a=xa in allD)+\napply (auto split: option.splits simp add: algebra_simps frac_simps)\napply (cut_tac x=be in frac_pos, simp)\napply (cut_tac x=bd in frac_pos, simp)\ndone\n\nlemma pdisjE[elim]: \n  \"\\<lbrakk> pdisj x (padd y z) ; pdisj y z \\<rbrakk> \\<Longrightarrow> pdisj x y\"\n  \"\\<lbrakk> pdisj x (padd y z) ; pdisj y z \\<rbrakk> \\<Longrightarrow> pdisj x z\"\nby (drule (1) pdisj_padd, simp)+\n\nlemma pdisj_padd_comm: \"\\<lbrakk> pdisj y (padd x z); pdisj x z \\<rbrakk> \\<Longrightarrow> pdisj x (padd y z)\"\napply (clarsimp simp add: pdisj_def padd_def all_conj_distrib [symmetric])\napply (drule_tac a=xa in allD)+\napply (auto split: option.splits simp add: algebra_simps frac_simps)\napply (subst Abs_myfrac_inverse, simp add: frac_simps)\napply (cut_tac x=bf in frac_pos, simp)\napply (cut_tac x=bd in frac_pos, simp)\ndone\n\nlemma pdisj_padd_expand:\n  \"pdisj x y \\<Longrightarrow> pdisj (padd x y) z = (pdisj x (padd y z) \\<and> pdisj y z)\"\napply (simp add: pdisj_comm, rule iffI)\n apply (frule (1) pdisj_padd_comm)\n apply (drule (1) pdisj_padd, subst padd_comm, simp_all add: pdisj_comm) \napply (clarify, rule pdisj_padd_comm, simp_all add: pdisj_comm)\ndone\n\nlemma padd_assoc: \"\\<lbrakk> pdisj x (padd y z) ; pdisj y z \\<rbrakk> \\<Longrightarrow> padd (padd x y) z = padd x (padd y z)\"\napply (clarsimp simp add: pdisj_def padd_def all_conj_distrib [symmetric], rule ext)\napply (drule_tac a=xa in allD)+\napply (auto split: option.splits simp add: algebra_simps frac_simps)\napply (subst Abs_myfrac_inverse, simp_all add: frac_simps)\napply (cut_tac x=be in frac_pos, simp)\ndone\n\nlemma padd_left_comm: \"\\<lbrakk> pdisj x (padd y z) ; pdisj y z \\<rbrakk> \\<Longrightarrow> padd x (padd y z) = padd y (padd x z)\"\napply (clarsimp simp add: pdisj_def padd_def all_conj_distrib [symmetric], rule ext)\napply (drule_tac a=xa in allD)+\napply (auto split: option.splits simp add: algebra_simps frac_simps)\napply (subst Abs_myfrac_inverse, simp_all add: frac_simps)\napply (cut_tac x=bf in frac_pos, simp)\ndone\n\nlemma padd_cancel: \"\\<lbrakk> padd x y = padd x z ; pdisj x y; pdisj x z \\<rbrakk> \\<Longrightarrow> y = z\"\napply (clarsimp simp add: pdisj_def padd_def all_conj_distrib [symmetric], rule ext)\napply (drule_tac a=xa in allD |drule_tac x=xa in fun_cong)+\napply (auto split: option.splits simp add: algebra_simps frac_simps)\napply (case_tac b, case_tac ba, clarsimp simp add: frac_simps)\napply (case_tac b, case_tac ba, clarsimp simp add: frac_simps)\napply (case_tac b, case_tac ba, clarsimp simp add: frac_simps)\ndone\n\nlemma dom_padd[simp]: \"dom (padd x y) = dom x \\<union> dom y\"\nby (rule set_eqI, simp add: padd_def dom_def split: option.splits)\n\nlemma fpdom_padd[elim]:\n  \"pdisj h1 h2 \\<Longrightarrow> fpdom h1 \\<subseteq> fpdom (padd h1 h2)\"\n  \"pdisj h1 h2 \\<Longrightarrow> fpdom h2 \\<subseteq> fpdom (padd h1 h2)\"\napply (auto simp add: fpdom_def pdisj_def padd_def disjoint_def split: option.splits)\napply (drule_tac a=x in allD, fastforce)+\ndone\n\nlemma pa_empty[simp]:\n  \"x \\<oplus> Some Map.empty = x\"\n  \"Some Map.empty \\<oplus> x = x\"\nby (auto simp add: mypadd_def split: option.splits)\n\nlemma pa_none[simp]:\n  \"x \\<oplus> None = None\"\n  \"None \\<oplus> x = None\"\nby (auto simp add: mypadd_def split: option.splits)\n\nlemma pa_comm: \"y \\<oplus> x = x \\<oplus> y\"\nby (auto simp add: mypadd_def pdisj_comm split: option.splits)\n\nlemma pa_assoc: \"(x \\<oplus> y) \\<oplus> z = x \\<oplus> y \\<oplus> z\"\napply (auto simp add: mypadd_def padd_assoc pdisj_padd_expand split: option.splits)\napply (erule notE, fast)\ndone\n\nlemma pa_left_comm: \"y \\<oplus> x \\<oplus> z = x \\<oplus> y \\<oplus> z\"\napply (auto simp add: mypadd_def padd_left_comm split: option.splits)\napply (erule_tac[!] notE, (erule (1) pdisj_padd_comm |erule (1) pdisjE)+)\ndone\n\nlemma some_padd: \"pdisj h1 h2 \\<Longrightarrow> Some (padd h1 h2) = Some h1 \\<oplus> Some h2\"\nby (simp add: mypadd_def)\n\nlemmas pa_ac = pa_comm pa_assoc pa_left_comm some_padd\n\nlemma pa_cancel: \n  \"\\<lbrakk> x \\<oplus> y = x \\<oplus> z;  x \\<oplus> y \\<noteq> None \\<rbrakk> \\<Longrightarrow> y = z\"\napply (simp add: mypadd_def split: option.splits if_splits) \napply (clarify, erule (2) padd_cancel)\ndone\n\nlemma ptoD: \"\\<lbrakk> ptoheap x z; ptoheap y z \\<rbrakk> \\<Longrightarrow> x = y\"\napply (clarsimp simp add: ptoheap_def split: option.splits)\napply (rule ext)\napply ((drule_tac a=xa in allD)+, auto)\napply (case_tac \"x2a xa\", case_tac \"x2 xa\", simp_all, fast+)\ndone\n\nlemma pdisj_search1: \n  \"ptoheap (Some x \\<oplus> Some y) hh             \\<Longrightarrow> pdisj x y\"\n  \"ptoheap (Some x \\<oplus> Some y \\<oplus> z) hh         \\<Longrightarrow> pdisj x y\"\n  \"ptoheap (Some x \\<oplus> z \\<oplus> Some y) hh         \\<Longrightarrow> pdisj x y\"\n  \"ptoheap (Some x \\<oplus> z \\<oplus> Some y \\<oplus> w) hh     \\<Longrightarrow> pdisj x y\"\n  \"ptoheap (Some x \\<oplus> z \\<oplus> w \\<oplus> Some y) hh     \\<Longrightarrow> pdisj x y\"\n  \"ptoheap (Some x \\<oplus> z \\<oplus> w \\<oplus> Some y \\<oplus> v) hh \\<Longrightarrow> pdisj x y\"\n  \"ptoheap (z \\<oplus> Some x \\<oplus> Some y) hh         \\<Longrightarrow> pdisj x y\"\n  \"ptoheap (z \\<oplus> Some x \\<oplus> Some y \\<oplus> w) hh     \\<Longrightarrow> pdisj x y\"\n  \"ptoheap (z \\<oplus> Some x \\<oplus> w \\<oplus> Some y) hh     \\<Longrightarrow> pdisj x y\"\n  \"ptoheap (z \\<oplus> Some x \\<oplus> w \\<oplus> Some y \\<oplus> v) hh \\<Longrightarrow> pdisj x y\"\n  \"ptoheap (z \\<oplus> Some x \\<oplus> w \\<oplus> v \\<oplus> Some y) hh \\<Longrightarrow> pdisj x y\"\n  \"ptoheap (z \\<oplus> w \\<oplus> Some x \\<oplus> Some y) hh     \\<Longrightarrow> pdisj x y\"\n  \"ptoheap (z \\<oplus> w \\<oplus> Some x \\<oplus> Some y \\<oplus> v) hh \\<Longrightarrow> pdisj x y\"\n  \"ptoheap (z \\<oplus> w \\<oplus> Some x \\<oplus> v \\<oplus> Some y) hh \\<Longrightarrow> pdisj x y\"\napply (simp_all add: ptoheap_def mypadd_def, case_tac[!] \"pdisj x y\", simp_all) \napply (auto split: option.splits if_split_asm)\napply (erule notE | fast | erule pdisjE [rotated])+\ndone\n\nlemma pdisj_comm_implies: \"pdisj h1 h2 \\<Longrightarrow> pdisj h2 h1\"\nby (fastforce split: option.splits simp add: pdisj_def)\n\nlemmas pdisj_search[elim] = \n  pdisj_search1 pdisj_search1[THEN pdisj_comm_implies]\n\nsubsection {* Assertions with permissions *}\n\ndatatype assn = \n    Aemp                                           (*r Empty heap *)\n  | Apsto myfrac exp exp                           (*r Singleton heap *)\n  | Astar assn assn      (infixl \"**\" 100)         (*r Separating conjunction *)\n  | Awand assn assn                                (*r Separating implication *)\n  | Apure bexp                                     (*r Pure assertion *)\n  | Aconj assn assn                                (*r Conjunction *)\n  | Adisj assn assn                                (*r Disjunction *)\n  | Aex \"(nat \\<Rightarrow> assn)\"                            (*r Existential quantification *)\n\ntext {* Separating conjunction of a finite list of assertions is \n  just a derived assertion. *}\n\nprimrec \n  Aistar :: \"assn list \\<Rightarrow> assn\"\nwhere\n  \"Aistar [] = Aemp\"\n| \"Aistar (P # Ps) = Astar P (Aistar Ps)\"\n\nprimrec\n  sat :: \"pstate \\<Rightarrow> assn \\<Rightarrow> bool\" (infixl \"\\<Turnstile>\" 60)\nwhere\n  \"(\\<sigma> \\<Turnstile> Aemp)      = (snd \\<sigma> = empty)\" \n| \"(\\<sigma> \\<Turnstile> Apsto k E E') = (dom (snd \\<sigma>) = { edenot E (fst \\<sigma>) } \\<and> (snd \\<sigma>) (edenot E (fst \\<sigma>)) = Some (edenot E' (fst \\<sigma>), k))\" \n| \"(\\<sigma> \\<Turnstile> P ** Q)    = (\\<exists>h1 h2. (fst \\<sigma>, h1) \\<Turnstile> P \\<and> (fst \\<sigma>, h2) \\<Turnstile> Q \\<and> snd \\<sigma> = padd h1 h2 \\<and> pdisj h1 h2)\" \n| \"(\\<sigma> \\<Turnstile> Awand P Q) = (\\<forall>h. disjoint (dom (snd \\<sigma>)) (dom h) \\<and> (fst \\<sigma>, h) \\<Turnstile> P \\<longrightarrow> (fst \\<sigma>, snd \\<sigma> ++ h) \\<Turnstile> Q)\" \n| \"(\\<sigma> \\<Turnstile> Apure B)   = bdenot B (fst \\<sigma>)\" \n| \"(\\<sigma> \\<Turnstile> Aconj P Q) = (\\<sigma> \\<Turnstile> P \\<and> \\<sigma> \\<Turnstile> Q)\" \n| \"(\\<sigma> \\<Turnstile> Adisj P Q) = (\\<sigma> \\<Turnstile> P \\<or> \\<sigma> \\<Turnstile> Q)\" \n| \"(\\<sigma> \\<Turnstile> Aex PP)    = (\\<exists>v. \\<sigma> \\<Turnstile> PP v)\" \n\ntext {* Shorthand for full permission *}\n\ndefinition \n  Aptsto :: \"exp \\<Rightarrow> exp \\<Rightarrow> assn\"  (infixl \"\\<longmapsto>\" 200)\nwhere\n  \"E \\<longmapsto> E' \\<equiv> Apsto pfull E E'\"\n\nlemma sat_Aptsto[simp]: \n  \"(\\<sigma> \\<Turnstile> E \\<longmapsto> E') = (dom (snd \\<sigma>) = { edenot E (fst \\<sigma>) }\n                      \\<and> (snd \\<sigma>) (edenot E (fst \\<sigma>)) = Some (edenot E' (fst \\<sigma>), pfull))\" \nby (simp add: Aptsto_def)\n\ndefinition \n  implies :: \"assn \\<Rightarrow> assn \\<Rightarrow> bool\" (infixl \"\\<sqsubseteq>\" 60)\nwhere\n  \"P \\<sqsubseteq> Q \\<equiv> (\\<forall>\\<sigma>. \\<sigma> \\<Turnstile> P \\<longrightarrow> \\<sigma> \\<Turnstile> Q)\"\n\nlemma sat_istar_map_expand:\n  \"\\<lbrakk> r \\<in> set l \\<rbrakk> \\<Longrightarrow>  \n     \\<sigma> \\<Turnstile> Aistar (map f l)\n     \\<longleftrightarrow> (\\<exists>h1 h2. (fst \\<sigma>, h1) \\<Turnstile> f r\n              \\<and> (fst \\<sigma>, h2) \\<Turnstile> Aistar (map f (remove1 r l))\n              \\<and> snd \\<sigma> = padd h1 h2 \\<and> pdisj h1 h2)\"\napply (case_tac \\<sigma>, rename_tac s h, clarify)\napply (induct l arbitrary: \\<sigma>, simp_all, clarsimp, safe)\napply (intro exI conjI, simp+)\n apply (drule pdisj_padd, simp, clarsimp)\napply (rule padd_left_comm, simp_all)\napply (rule pdisj_padd_comm, simp_all)\n\napply (intro exI conjI, simp+)\napply (drule pdisj_padd, simp, clarsimp)\napply (rule padd_left_comm, simp_all)\napply (rule pdisj_padd_comm, simp_all)\ndone\n\nsubsubsection {* Precision *}\n\ntext {* We say that an assertion is precise if for any given heap, there is at\nmost one subheap that satisfies the formula. (The formal definition below says \nthat if there are two such subheaps, they must be equal.) *}\n\ndefinition\n  precise :: \"assn \\<Rightarrow> bool\"\nwhere\n  \"precise P \\<equiv> \\<forall>h1 h2 h1' h2' s. pdisj h1 h2 \\<and> pdisj h1' h2'\n                   \\<and> padd h1 h2 = padd h1' h2' \\<and> (s, h1) \\<Turnstile> P \\<and> (s, h1') \\<Turnstile> P \n               \\<longrightarrow> h1 = h1'\"\n\ntext {* A direct consequence of the definition that is more useful in\nIsabelle, because unfolding the definition slows down Isabelle's simplifier\ndramatically. *}\n\nlemma preciseD:\n  \"\\<lbrakk> precise P; (s, x) \\<Turnstile> P; (s, x') \\<Turnstile> P; padd x y = padd x' y'; \n     pdisj x y; pdisj x' y' \\<rbrakk> \\<Longrightarrow>\n    x = x' \\<and> y = y'\"\nunfolding precise_def\nby (drule all5_impD, (erule conjI)+, simp_all, drule padd_cancel)\n\ntext {* The separating conjunction of precise assertions is precise: *}\n\nlemma precise_istar:\n  \"\\<forall>x \\<in> set l. precise x \\<Longrightarrow> precise (Aistar l)\"\napply (induct l, simp_all (no_asm) add: precise_def)\napply (clarsimp simp add: padd_assoc pdisj_padd_expand)\napply (drule (3) preciseD, simp_all, clarsimp)\napply (drule (3) preciseD, simp_all)\ndone\n\nsubsubsection {* Auxiliary definition for resource environments *}\n\ndefinition\n  envs :: \"('a \\<Rightarrow> assn) \\<Rightarrow> 'a list \\<Rightarrow> 'a list \\<Rightarrow> assn\"\nwhere\n  \"envs \\<Gamma> l l' \\<equiv> Aistar (map \\<Gamma> (list_minus l l'))\"\n\nlemma sat_envs_expand:\n  \"\\<lbrakk> r \\<in> set l; r \\<notin> set l'; distinct l \\<rbrakk> \\<Longrightarrow>  \n     \\<sigma> \\<Turnstile> envs \\<Gamma> l l' \n     \\<longleftrightarrow> (\\<exists>h1 h2. (fst \\<sigma>, h1) \\<Turnstile> \\<Gamma> r \n              \\<and> (fst \\<sigma>, h2) \\<Turnstile> envs \\<Gamma> (removeAll r l) l'\n              \\<and> snd \\<sigma> = padd h1 h2 \\<and> pdisj h1 h2)\" \napply (simp add: envs_def distinct_remove1_removeAll [THEN sym] add: list_minus_remove1)\napply (subst sat_istar_map_expand [where f=\\<Gamma> and r=r], simp_all)\ndone\n\nlemma envs_upd:\n  \"r \\<notin> set l \\<Longrightarrow> envs (\\<Gamma>(r := R)) l l' = envs \\<Gamma> l l'\"\n  \"r \\<in> set l' \\<Longrightarrow> envs (\\<Gamma>(r := R)) l l' = envs \\<Gamma> l l'\"\nby (simp_all add: envs_def)\n\nlemma envs_removeAll_irr: \n  \"r \\<notin> set l \\<Longrightarrow> envs \\<Gamma> l (removeAll r l') = envs \\<Gamma> l l'\"\nby (simp add: envs_def list_minus_removeAll_irr)\n\nlemma envs_removeAll2:\n  \"r \\<in> set l' \\<Longrightarrow> envs \\<Gamma> (removeAll r l) (removeAll r l') = envs \\<Gamma> l l'\"\nby (simp add: envs_def list_minus_removeAll2)\n\nlemma envs_app:\n  \"disjoint (set x) (set z) \\<Longrightarrow> envs \\<Gamma> (x @ z) (y @ z) = envs \\<Gamma> x y\"\n  \"disjoint (set z) (set x) \\<Longrightarrow> envs \\<Gamma> (z @ x) (z @ y) = envs \\<Gamma> x y\"\nby (simp_all add: envs_def list_minus_appl list_minus_appr)\n\nsubsubsection {* Free variables and substitutions *}\n\nprimrec\n  fvA :: \"assn \\<Rightarrow> var set\"\nwhere\n  \"fvA (Aemp)      = {}\"\n| \"fvA (Apure B)   = fvB B\"\n| \"fvA (Apsto k e1 e2) = (fvE e1 \\<union> fvE e2)\"\n| \"fvA (P ** Q)    = (fvA P \\<union> fvA Q)\"\n| \"fvA (Awand P Q) = (fvA P \\<union> fvA Q)\"\n| \"fvA (Aconj P Q) = (fvA P \\<union> fvA Q)\"\n| \"fvA (Adisj P Q) = (fvA P \\<union> fvA Q)\"\n| \"fvA (Aex P)     = (\\<Union>x. fvA (P x))\"\n\ndefinition\n  fvAs :: \"('a \\<Rightarrow> assn) \\<Rightarrow> var set\"\nwhere\n  \"fvAs \\<Gamma> = (\\<Union>x. fvA (\\<Gamma> x))\"\n\nprimrec\n  subA :: \"var \\<Rightarrow> exp \\<Rightarrow> assn \\<Rightarrow> assn\"\nwhere\n  \"subA x E (Aemp)      = Aemp\"\n| \"subA x E (Apure B)   = Apure (subB x E B)\"\n| \"subA x E (Apsto k e1 e2) = (Apsto k (subE x E e1) (subE x E e2))\"\n| \"subA x E (P ** Q)    = (subA x E P ** subA x E Q)\"\n| \"subA x E (Awand P Q) = Awand (subA x E P) (subA x E Q)\"\n| \"subA x E (Aconj P Q) = Aconj (subA x E P) (subA x E Q)\"\n| \"subA x E (Adisj P Q) = Adisj (subA x E P) (subA x E Q)\"\n| \"subA x E (Aex PP)    = Aex (\\<lambda>n. subA x E (PP n))\"\n\nlemma subAptsto[simp]:\n  \"subA x E (e1 \\<longmapsto> e2) = (subE x E e1 \\<longmapsto> subE x E e2)\"\nby (simp add: Aptsto_def)\n\nlemma subA_assign:\n \"(s,h) \\<Turnstile> subA x E P \\<longleftrightarrow> (s(x := edenot E s), h) \\<Turnstile> P\"\nby (induct P arbitrary: h, simp_all add: subE_assign subB_assign fun_upd_def)\n\nlemma fvA_istar[simp]: \"fvA (Aistar Ps) = (\\<Union>P \\<in> set Ps. fvA P)\"\nby (induct Ps, simp_all)\n\ntext {* Proposition 4.2 for assertions *}\n\nlemma assn_agrees: \"agrees (fvA P) s s' \\<Longrightarrow> (s, h) \\<Turnstile> P \\<longleftrightarrow> (s', h) \\<Turnstile> P\"\napply (induct P arbitrary: h, simp_all add: bexp_agrees)\napply (clarsimp, (subst exp_agrees, simp_all)+ )\napply (rule iff_exI, simp add: agrees_def)\ndone\n\ntext {* Corollaries of Proposition 4.2, useful for automation. *}\n\nlemma assns_agrees:\n  \"agrees (fvAs J) s s' \\<Longrightarrow> (s, h) \\<Turnstile> envs J l1 l2 \\<longleftrightarrow> (s', h) \\<Turnstile> envs J l1 l2\"\napply (clarsimp simp add: envs_def, subst assn_agrees, simp_all)\napply (erule agrees_search, auto simp add: fvAs_def)\ndone\n\ncorollary assns_agreesE[elim]:\n  \"\\<lbrakk> (s, h) \\<Turnstile> envs J l1 l2 ; agrees (fvAs J) s s' \\<rbrakk> \\<Longrightarrow> (s',h) \\<Turnstile> envs J l1 l2\"\nby (simp add: assns_agrees)\n\ncorollary assn_agrees2[simp]:\n  \"x \\<notin> fvA P \\<Longrightarrow> (s(x := v), h) \\<Turnstile> P \\<longleftrightarrow> (s, h) \\<Turnstile> P\"\nby (rule assn_agrees, simp add: agrees_def)\n\ncorollary assns_agrees2[simp]:\n  \"x \\<notin> fvAs J \\<Longrightarrow> (s(x := v), h) \\<Turnstile> envs J l l' \\<longleftrightarrow> (s, h) \\<Turnstile> envs J l l'\"\nby (rule assns_agrees, simp add: agrees_def)\n\nsubsection {* Meaning of CSL judgments *}\n\ntext {* Definition 5.1: Configuration safety. *}\n\nprimrec\n  safe :: \"nat \\<Rightarrow> cmd \\<Rightarrow> stack \\<Rightarrow> pheap \\<Rightarrow> (rname \\<Rightarrow> assn) \\<Rightarrow> assn \\<Rightarrow> bool\"\nwhere\n  \"safe 0       C s h \\<Gamma> Q = True\"\n| \"safe (Suc n) C s h \\<Gamma> Q = (\n(* Condition (i) *)\n            (C = Cskip \\<longrightarrow> (s, h) \\<Turnstile> Q)\n(* Condition (ii) *)\n          \\<and> (\\<forall>hF hh. ptoheap (Some h \\<oplus> hF) hh \\<longrightarrow> \\<not> aborts C (s, hh))\n(* Condition (iii) *)\n          \\<and> accesses C s \\<subseteq> dom h\n          \\<and> writes C s \\<subseteq> fpdom h\n(* Condition (iv) *)\n          \\<and> (\\<forall>hJ hF hh C' \\<sigma>'.\n                  red C (s, hh) C' \\<sigma>'\n                 \\<longrightarrow> ptoheap (Some h \\<oplus> Some hJ \\<oplus> hF) hh\n                 \\<longrightarrow> (s, hJ) \\<Turnstile> envs \\<Gamma> (llocked C') (llocked C)\n                 \\<longrightarrow> (\\<exists>h' hJ'.\n                         ptoheap (Some h' \\<oplus> Some hJ' \\<oplus> hF) (snd \\<sigma>')\n                       \\<and> (fst \\<sigma>', hJ') \\<Turnstile> envs \\<Gamma> (llocked C) (llocked C')\n                       \\<and> safe n C' (fst \\<sigma>') h' \\<Gamma> Q)))\"\n\ntext {* The predicate @{text \"safe n C s h \\<Gamma> Q\"} says that the command @{text C} and the logical state\n  @{text \"(s, h)\"} are safe with respect to the resource environment @{text \\<Gamma>} and the \n  postcondition @{text Q} for @{text n} execution steps. \n  Intuitively, any configuration is safe for zero steps.\n  For @{text \"n + 1\"} steps, it must \n  (i) satisfy the postcondition if it is a terminal configuration,\n  (ii) not abort, \n  (iii) access memory only inside its footprint, and \n  (iv) after any step it does, re-establish the resource invariant and be safe for \n  another @{text n} steps. *}\n\ntext {* Definition 5.2: The meaning of CSL judgements. *}\n\ndefinition\n  CSL :: \"(rname \\<Rightarrow> assn) \\<Rightarrow> assn \\<Rightarrow> cmd \\<Rightarrow> assn \\<Rightarrow> bool\"\n  (\"_ \\<turnstile> { _ } _ { _ }\")\nwhere\n  \"\\<Gamma> \\<turnstile> {P} C {Q} \\<equiv> (user_cmd C \\<and> (\\<forall>n s h. (s, h) \\<Turnstile> P \\<longrightarrow> safe n C s h \\<Gamma> Q))\" \n\nsubsubsection {* Basic properties of Definition 5.1 *}\n\ntext {* Proposition 4.3: Monotonicity with respect to the step number. *}\n\nlemma safe_mon:\n  \"\\<lbrakk> safe n C s h J Q; m \\<le> n \\<rbrakk> \\<Longrightarrow> safe m C s h J Q\"\napply (induct m arbitrary: C s n h l, simp) \napply (case_tac n, clarify)\napply (simp only: safe.simps, clarsimp)\napply (drule all5D, drule (2) all_imp2D, clarsimp)\napply (rule_tac x=\"h'\" in exI, rule_tac x=\"hJ'\" in exI, simp)\ndone\n\ntext {* Proposition 4.4: Safety depends only the free variables\n        of @{term \"C\"}, @{term \"Q\"}, and @{term \"\\<Gamma>\"}. *}\n\nlemma safe_agrees: \n  \"\\<lbrakk> safe n C s h \\<Gamma> Q ; \n     agrees (fvC C \\<union> fvA Q \\<union> fvAs \\<Gamma>) s s' \\<rbrakk>\n   \\<Longrightarrow> safe n C s' h \\<Gamma> Q\"\napply (induct n arbitrary: C s s' h bl, simp, simp only: safe.simps, clarify)\napply (rule conjI, clarsimp, subst assn_agrees, subst agreesC, assumption+)\napply (rule conjI, clarsimp)\n apply (drule_tac aborts_agrees, simp, fast, simp, simp)\napply (rule conjI, subst (asm) accesses_agrees, simp_all)\napply (rule conjI, subst (asm) writes_agrees, simp_all)\napply (clarify, drule_tac X=\"fvC C \\<union> fvAs \\<Gamma> \\<union> fvA Q\" in red_agrees, \n       simp (no_asm), fast, simp (no_asm), fast, clarify)\napply (drule allD, drule (1) all5_impD, clarsimp)\napply (drule imp2D, erule_tac[2] assns_agreesE, simp_all add: agreesC, clarify)\napply (rule_tac x=\"h'a\" and y=\"hJ'\" in ex2I, simp add: pa_ac)\napply (rule conjI, erule assns_agreesE, subst agreesC, assumption)\napply (erule (1) mall4_imp2D, simp add: agreesC)\napply (drule red_properties, auto)\ndone\n\nsubsection {* Soundness of the proof rules *}\n\nsubsubsection {* Skip *}\n\nlemma safe_skip[intro!]:\n  \"(s,h) \\<Turnstile> Q \\<Longrightarrow> safe n Cskip s h J Q\"\nby (induct n, simp_all)\n\ntheorem rule_skip: \n  \"\\<Gamma> \\<turnstile> {P} Cskip {P}\"\nby (auto simp add: CSL_def)\n\nsubsubsection {* Parallel composition *}\n\nlemma disj_conv:\n  \"pdisj h1 h2 \\<Longrightarrow> disjoint (fpdom h1) (dom h2)\"\n  \"pdisj h1 h2 \\<Longrightarrow> disjoint (dom h1) (fpdom h2)\"\nby (simp add: fpdom_def pdisj_def disjoint_def, rule set_eqI, drule_tac a=x in allD, clarsimp)+\n\nlemma safe_par:\n \"\\<lbrakk> safe n C1 s h1 J Q1; safe n C2 s h2 J Q2;\n    wf_cmd (Cpar C1 C2);\n    pdisj h1 h2;\n    disjoint (fvC C1 \\<union> fvA Q1 \\<union> fvAs J) (wrC C2);\n    disjoint (fvC C2 \\<union> fvA Q2 \\<union> fvAs J) (wrC C1)\\<rbrakk>\n  \\<Longrightarrow> safe n (Cpar C1 C2) s (padd h1 h2) J (Q1 ** Q2)\"\napply (induct n arbitrary: C1 C2 s h1 h2 bl1 bl2, simp, clarsimp)\napply (rule conjI, clarify)\n -- {* no aborts *}\n apply (erule aborts.cases, simp_all add: pa_ac)\n   apply (clarify, drule_tac a=\"Some h2 \\<oplus> hF\" in all2_impD, simp add: pa_ac, clarsimp)\n   apply (clarify, drule_tac a=\"Some h1 \\<oplus> hF\" in all2_impD, simp add: pa_ac, clarsimp)\n -- {* no races *}\n apply (clarsimp, erule notE, (erule disjoint_search [rotated])+, erule disj_conv)+\n-- {* accesses *}\napply (rule conjI, erule order_trans, simp)+\napply (rule conjI, erule order_trans, erule fpdom_padd)+\n-- {* step *}\n apply (clarsimp, erule red_par_cases, simp_all)\n -- {* C1 does a step *}\n  apply (clarify, drule_tac a=\"hJ\" and b=\"Some h2 \\<oplus> hF\" in all2D, drule all4_impD, \n         simp_all add: envs_app locked_eq, clarsimp simp add: pa_ac)\n  apply (subgoal_tac \"pdisj h' h2\", erule_tac[2] pdisj_search)\n  apply (rule_tac x=\"padd h' h2\" and y=\"hJ'\" in ex2I, simp add: pa_ac)\n  apply (frule (1) red_wf_cmd, drule red_properties, clarsimp)\n  apply (drule_tac a=C1' and b=C2 in mall2D, simp add: hsimps)\n  apply (drule mall3_imp2D, erule_tac[3] mimp3D, simp_all add: hsimps)\n  apply (rule_tac s=\"s\" in safe_agrees)\n  apply (rule_tac n=\"Suc n\" in safe_mon, simp add: pa_ac, simp)\n  apply (fastforce simp add: agreesC disjoint_commute)\n  apply (intro conjI | erule (1) disjoint_search)+\n -- {* C2 does a step *}\n  apply (clarify, drule_tac a=\"hJ\" and b=\"Some h1 \\<oplus> hF\" in all2D, drule all4_imp2D, \n         simp_all add: hsimps envs_app pa_ac, clarsimp)\n  apply (subgoal_tac \"pdisj h1 h'\", erule_tac[2] pdisj_search)\n  apply (rule_tac x=\"padd h1 h'\" and y=\"hJ'\" in ex2I, simp add: pa_ac)\n  apply (frule (1) red_wf_cmd, drule red_properties, clarsimp)\n  apply (drule_tac a=C1 and b=C2' in mall2D, simp add: hsimps)\n  apply (drule mall3_imp2D, erule_tac[3] mimp3D, simp_all add: hsimps)\n  apply (rule_tac s=\"s\" in safe_agrees)\n   apply (rule_tac n=\"Suc n\" in safe_mon, simp add: pa_ac, simp)\n  apply (subst agreesC, bestsimp, bestsimp, bestsimp)\n-- {* Par skip skip *} \napply (clarify)\napply (rule_tac x=\"padd h1 h2\" and y=\"hJ\" in ex2I, simp add: pa_ac)\napply (rule_tac safe_skip, simp, (rule exI, erule conjI)+, simp)\ndone\n\ntheorem rule_par:\n \"\\<lbrakk> \\<Gamma> \\<turnstile> {P1} C1 {Q1} ; \\<Gamma> \\<turnstile> {P2} C2 {Q2};\n    disjoint (fvC C1 \\<union> fvA Q1 \\<union> fvAs \\<Gamma>) (wrC C2);\n    disjoint (fvC C2 \\<union> fvA Q2 \\<union> fvAs \\<Gamma>) (wrC C1) \\<rbrakk>\n  \\<Longrightarrow> \\<Gamma> \\<turnstile> {P1 ** P2} (Cpar C1 C2) {Q1 ** Q2}\"\nby (auto simp add: CSL_def intro!: safe_par)\n\nsubsubsection {* Resource declaration *}\n\nlemma safe_resource:\n \"\\<lbrakk> safe n C s h (\\<Gamma>(r := R)) Q; wf_cmd C; disjoint (fvA R) (wrC C) \\<rbrakk> \\<Longrightarrow>\n     (\\<forall>hR. r \\<notin> locked C \\<longrightarrow> pdisj h hR \\<longrightarrow> (s,hR) \\<Turnstile> R \\<longrightarrow> safe n (Cresource r C) s (padd h hR) \\<Gamma> (Q ** R))\n   \\<and> (r \\<in> locked C \\<longrightarrow> safe n (Cresource r C) s h \\<Gamma> (Q ** R))\"\napply (induct n arbitrary: C s h, simp, clarsimp simp add: pa_ac)\napply (rule conjI, clarify)\n apply (rule conjI, clarify)\n  -- {* no aborts *}\n  apply (erule aborts.cases, simp_all, clarsimp)\n  apply (drule_tac a=\"Some hR \\<oplus> hF\" in all2_impD, simp add: pa_ac, simp)\n -- {* accesses *}\n apply (rule conjI, erule order_trans, simp)\n apply (rule conjI, erule order_trans, erule fpdom_padd)\n -- {* step *}\n apply (clarify, frule red_properties, clarsimp)\n apply (erule red.cases, simp_all, clarsimp, rename_tac C s hh C' s' hh')\n -- {* normal step *}\napply (subgoal_tac \"pdisj hR hJ\", erule_tac[2] pdisj_search)\n  apply (case_tac \"r \\<in> set (llocked C')\", simp_all add: locked_eq)\n   apply (drule_tac a=\"padd hJ hR\" and b=\"hF\" and c=\"hh\" in all3D, \n          drule_tac a=C' and b=s' and c=hh' in all3D, simp_all add: pa_ac)\n   apply (drule impD, subst sat_envs_expand [where r=r], simp_all)\n     apply (rule wf_cmd_distinct_locked, erule (1) red_wf_cmd)\n    apply (intro exI conjI, simp, simp_all add: envs_upd)\n   apply (clarsimp simp add: envs_removeAll_irr) \n   apply (drule (1) mall3_imp2D, erule (1) red_wf_cmd)\n   apply (drule mimpD, fast, clarsimp) \n   apply (intro exI conjI, simp+)\n  -- {* @{term \"r \\<notin> locked C'\"} *}\n  apply (drule_tac a=\"hJ\" and b=\"Some hR \\<oplus> hF\" and c=hh in all3D, drule_tac a=C' and b=s' and c=hh' in all3D,\n         simp add: pa_ac)\n  apply (clarsimp simp add: envs_upd)\n  apply (drule (1) mall3_imp2D, erule (1) red_wf_cmd)\n  apply (drule mimpD, fast, clarsimp) \n  apply (subgoal_tac \"pdisj h' hR\", erule_tac[2] pdisj_search)\n  apply (rule_tac x=\"padd h' hR\" and y=\"hJ'\" in ex2I, simp add: pa_ac) \n  apply (drule_tac a=hR in all_imp2D, simp_all add: hsimps)\n  apply (subst assn_agrees, simp_all, fastforce)\n -- {* skip *}\n apply (clarsimp simp add: envs_def)\n apply (rule_tac x=\"padd h hR\" in exI, simp add: pa_ac, rule safe_skip, simp, fast)\n-- {* not user cmd *}\napply (clarsimp)\napply (rule conjI, clarsimp, erule aborts.cases, simp_all, clarsimp, clarsimp)\napply (frule red_properties, clarsimp)\napply (erule red.cases, simp_all, clarsimp, rename_tac C s hh C' s' hh')\napply (drule_tac a=\"hJ\" and b=\"hF\" and c=hh in all3D, drule_tac a=C' and b=s' and c=hh' in all3D,\n       simp add: pa_ac)\napply (clarsimp simp add: envs_upd envs_removeAll2)\napply (drule (1) mall3_imp2D, erule (1) red_wf_cmd)\napply (drule mimpD, fast, clarsimp) \napply (case_tac \"r \\<in> set (llocked C')\", simp_all add: locked_eq envs_removeAll2 envs_upd)\n apply (intro exI conjI, simp+)\napply (subst (asm) sat_envs_expand [where r=r], simp_all add: wf_cmd_distinct_locked, \n       clarsimp simp add: pa_ac, rename_tac hR' hJ')\napply (subgoal_tac \"pdisj h' hR'\", erule_tac[2] pdisj_search)\napply (drule (2) all_imp2D, rule_tac x=\"padd h' hR'\" and y=hJ' in ex2I, simp add: pa_ac envs_upd)\ndone\n\ntheorem rule_resource:\n \"\\<lbrakk> \\<Gamma>(r := R) \\<turnstile> {P} C {Q} ; disjoint (fvA R) (wrC C) \\<rbrakk> \\<Longrightarrow> \n    \\<Gamma> \\<turnstile> {P ** R} (Cresource r C) {Q ** R}\"\nby (clarsimp simp add: CSL_def, drule (1) all3_impD)\n   (auto simp add: locked_eq dest!: safe_resource)\n\nsubsubsection {* Frame rule *}\n\ntext {* The safety of the frame rule can be seen as a special case of the parallel composition\n  rule taking one thread to be the empty command. *}\n\nlemma safe_frame:\n \"\\<lbrakk> safe n C s h J Q; \n    pdisj h hR;\n    disjoint (fvA R) (wrC C);\n    (s,hR) \\<Turnstile> R\\<rbrakk>\n  \\<Longrightarrow> safe n C s (padd h hR) J (Q ** R)\"\napply (induct n arbitrary: C s h hR, simp, clarsimp simp add: pa_ac)\napply (rule conjI, clarify, fast)\napply (rule conjI, clarify)\n -- {* no aborts *}\n apply (drule_tac a=\"Some hR \\<oplus> hF\" in all2_impD, simp add: pa_ac, simp)\n-- {* accesses *}\napply (rule conjI, erule order_trans, simp)\napply (rule conjI, erule order_trans, erule fpdom_padd)\n-- {* step *}\napply (clarify, frule red_properties, clarsimp)\napply (drule_tac a=\"hJ\" and b=\"Some hR \\<oplus> hF\" in all3D, simp add: pa_ac, drule (1) all3_impD, clarsimp)\napply (subgoal_tac \"pdisj h' hR\", erule_tac[2] pdisj_search)\napply (rule_tac y=\"hJ'\" and x=\"padd h' hR\" in ex2I, clarsimp simp add: pa_ac)\napply (drule mall4D, erule mimp4D, simp_all add: hsimps)\n apply (erule (1) disjoint_search)\napply (subst assn_agrees, simp_all, fastforce)\ndone\n\ntheorem rule_frame:\n \"\\<lbrakk> \\<Gamma> \\<turnstile> {P} C {Q} ; disjoint (fvA R) (wrC C) \\<rbrakk>\n  \\<Longrightarrow> \\<Gamma> \\<turnstile> {P ** R} C {Q ** R}\"\nby (auto simp add: CSL_def intro: safe_frame)\n\nsubsubsection {* Conditional critical regions *}\n\nlemma safe_inwith:\n  \"\\<lbrakk>safe n C s h \\<Gamma> (Q ** \\<Gamma> r); wf_cmd (Cinwith r C) \\<rbrakk>\n  \\<Longrightarrow> safe n (Cinwith r C) s h \\<Gamma> Q\"\napply (induct n arbitrary: C s h, simp_all, clarify)\napply (rule conjI)\n apply (clarify, erule aborts.cases, simp_all, clarsimp)\napply (clarify, erule_tac red.cases, simp_all, clarify)\n apply (frule (1) red_wf_cmd)\n apply (drule allD, drule (1) all5_imp2D, simp_all)\n apply (simp add: envs_def list_minus_removeAll [THEN sym] locked_eq)+\n apply fast\napply (clarsimp simp add: envs_def, rename_tac hQ hJ)\napply (rule_tac x=\"hQ\" and y=\"hJ\" in ex2I, simp add: pa_ac, fast)\ndone\n\ntheorem rule_with:\n  \"\\<lbrakk> \\<Gamma> \\<turnstile> {Aconj (P ** \\<Gamma> r) (Apure B)} C {Q ** \\<Gamma> r} \\<rbrakk>\n   \\<Longrightarrow> \\<Gamma> \\<turnstile> {P} Cwith r B C {Q}\"\napply (clarsimp simp add: CSL_def)\napply (case_tac n, simp, clarsimp)\napply (rule conjI, clarify, erule aborts.cases, simp_all)\napply (clarify, erule red.cases, simp_all, clarsimp)\napply (subgoal_tac \"pdisj h hJ\", erule_tac[2] pdisj_search)\napply (simp add: envs_def, rule_tac x=\"padd h hJ\" in exI, simp add: pa_ac)\napply (rule safe_inwith, erule all3_impD, auto dest: user_cmdD)\ndone\n\nsubsubsection {* Sequential composition *}\n\nlemma safe_seq:\n \"\\<lbrakk> safe n C s h J Q; user_cmd C2;\n    \\<forall>m s' h'. m \\<le> n \\<and> (s', h') \\<Turnstile> Q \\<longrightarrow> safe m C2 s' h' J R \\<rbrakk>\n  \\<Longrightarrow> safe n (Cseq C C2) s h J R\"\napply (induct n arbitrary: C s h l, simp, clarsimp)\napply (rule conjI, clarsimp)\n apply (erule aborts.cases, simp_all, clarsimp)\napply (clarsimp, erule red.cases, simp_all)\n -- {* Seq1 *}\n apply (clarify, rule_tac x=\"h\" and y=\"hJ\" in ex2I, simp)\n-- {* Seq2 *}\napply (clarify, drule all3D, drule (2) all3_imp2D, clarsimp)\napply (drule (1) mall3_impD, rule_tac x=\"h'\" and y=\"hJ'\" in ex2I, simp)\ndone\n\ntheorem rule_seq:\n  \"\\<lbrakk> \\<Gamma> \\<turnstile> {P} C1 {Q} ; \\<Gamma> \\<turnstile> {Q} C2 {R} \\<rbrakk> \\<Longrightarrow> \\<Gamma> \\<turnstile> {P} Cseq C1 C2 {R}\"\nby (auto simp add: CSL_def intro!: safe_seq)\n\nsubsubsection {* Conditionals (if-then-else) *}\n\ntheorem rule_if:\n  \"\\<lbrakk> \\<Gamma> \\<turnstile> {Aconj P (Apure B)} C1 {Q} ; \n     \\<Gamma> \\<turnstile> {Aconj P (Apure (Bnot B))} C2 {Q} \\<rbrakk>\n  \\<Longrightarrow> \\<Gamma> \\<turnstile> {P} Cif B C1 C2 {Q}\"\napply (clarsimp simp add: CSL_def)\napply (case_tac n, simp, clarsimp)\napply (intro conjI allI impI notI, erule aborts.cases, simp_all)\napply (erule red.cases, simp_all)\napply (clarsimp, intro exI, (rule conjI, simp)+, simp)+\ndone\n\nsubsubsection {* While *}\n\nlemma safe_while:\n  \"\\<lbrakk> \\<Gamma> \\<turnstile> {Aconj P (Apure B)} C {P} ; (s, h) \\<Turnstile> P \\<rbrakk>\n  \\<Longrightarrow> safe n (Cwhile B C) s h \\<Gamma> (Aconj P (Apure (Bnot B)))\"\napply (induct n arbitrary: s h, simp, clarsimp)\napply (intro conjI allI impI notI, erule aborts.cases, simp_all)\napply (erule red.cases, simp_all)\napply (clarsimp, intro exI, (rule conjI, simp)+)\napply (subgoal_tac \"\\<forall>m s h. m \\<le> n \\<and> (s, h) \\<Turnstile> P \\<longrightarrow> safe m (Cwhile B C) s h \\<Gamma> (Aconj P (Apure (Bnot B)))\")\n apply (case_tac n, simp, clarsimp)\n apply (intro conjI allI impI notI, erule aborts.cases, simp_all)\n apply (erule red.cases, simp_all)\n  apply (clarsimp, intro exI, (rule conjI, simp)+)\n  apply (clarsimp simp add: CSL_def, rule safe_seq, blast, simp, clarsimp)\n apply (clarsimp, intro exI, (rule conjI, simp)+, rule safe_skip, simp)\napply (clarsimp, drule (1) mall2_impD, erule (1) safe_mon) \ndone\n\ntheorem rule_while:\n  \"\\<Gamma> \\<turnstile> {Aconj P (Apure B)} C {P}\n  \\<Longrightarrow> \\<Gamma> \\<turnstile> {P} Cwhile B C {Aconj P (Apure (Bnot B))}\"\nby (auto simp add: CSL_def intro: safe_while)\n\nsubsubsection {* Local variable declaration *}\n\nlemma safe_inlocal:\n  \"\\<lbrakk> safe n C (s(x:=v)) h \\<Gamma> Q ; x \\<notin> fvA Q \\<union> fvAs \\<Gamma> \\<rbrakk>\n  \\<Longrightarrow> safe n (Cinlocal x v C) s h \\<Gamma> Q\"\napply (induct n arbitrary: s h v C, simp, clarsimp)\napply (intro conjI allI impI notI, erule aborts.cases, simp_all, clarsimp)\napply (erule red.cases, simp_all)\n apply (clarsimp, drule allD, drule (1) all5_imp2D, simp)\n apply (clarsimp, intro exI, (rule conjI, simp)+, simp)\napply (fastforce simp add: safe_skip)\ndone\n\ntheorem rule_local:\n  \"\\<lbrakk> \\<Gamma> \\<turnstile> {Aconj P (Apure (Beq (Evar x) E))} C {Q} ; \n     x \\<notin> fvA P \\<union> fvA Q \\<union> fvAs \\<Gamma> \\<union> fvE E \\<rbrakk>\n  \\<Longrightarrow> \\<Gamma> \\<turnstile> {P} Clocal x E C {Q}\"\napply (auto simp add: CSL_def intro: safe_inlocal)\napply (case_tac n, simp_all)\napply (intro conjI allI impI notI, erule aborts.cases, simp_all)\napply (erule red.cases, simp_all, clarsimp)\napply (intro exI conjI, simp_all, rule safe_inlocal, simp_all)\ndone\n\nsubsubsection {* Basic commands (Assign, Read, Write, Alloc, Free) *}\n\ntheorem rule_assign:\n  \"x \\<notin> fvAs \\<Gamma> \\<Longrightarrow> \\<Gamma> \\<turnstile> {subA x E Q} Cassign x E {Q}\"\napply (clarsimp simp add: CSL_def)\napply (case_tac n, simp, clarsimp)\napply (rule conjI, clarsimp, erule aborts.cases, simp_all)\napply (clarsimp, erule red.cases, simp_all)\napply (rule_tac x=\"h\" in exI, rule_tac x=\"hJ\" in exI, \n       clarsimp simp add: subA_assign) \ndone\n\nlemma ptoheap_read:\n \"\\<lbrakk> ptoheap (Some h \\<oplus> hF) hh; h x = Some (v, k) \\<rbrakk> \\<Longrightarrow> hh x = Some v\"\napply (case_tac hF, (simp add: ptoheap_def mypadd_def split: if_split_asm)+)\napply (drule_tac a=\"x\" in allD, fastforce simp add: padd_def split: option.splits)\ndone\n\ntheorem rule_read:\n  \"\\<lbrakk> x \\<notin> fvE E \\<union> fvE E' \\<union> fvAs \\<Gamma> \\<rbrakk> \\<Longrightarrow>\n    \\<Gamma> \\<turnstile> {Apsto k E E'} Cread x E {Aconj (Apsto k E E') (Apure (Beq (Evar x) E'))}\"\napply (clarsimp simp add: CSL_def)\napply (case_tac n, simp, clarsimp, intro conjI allI impI notI)\n apply (erule aborts.cases, simp_all, fastforce dest: ptoheap_read)\napply (erule red.cases, simp_all, fastforce dest: ptoheap_read)\ndone\n\nlemma pdisj_upd2: \"h x = Some (w, pfull) \\<Longrightarrow> pdisj (h(x \\<mapsto> (v, pfull))) h' = pdisj h h'\"\nby (simp add: pdisj_def, rule iff_allI, auto split: option.splits)\n \nlemma write_helper:\n \"\\<lbrakk> ptoheap (Some h \\<oplus> hF) hh; h x = Some (v, pfull) \\<rbrakk> \\<Longrightarrow> \n  ptoheap (Some (h(x\\<mapsto> (w, pfull))) \\<oplus> hF) (hh(x\\<mapsto>w))\"\napply (case_tac hF, simp_all add: ptoheap_def mypadd_def split: if_split_asm)\napply (clarsimp simp add: pdisj_upd2, simp add: pdisj_def, (drule_tac a=xa in allD)+)\napply (clarsimp simp add: pdisj_def padd_def split: option.splits)\ndone\n\ntheorem rule_write:\n  \"\\<Gamma> \\<turnstile> {E \\<longmapsto> E0} Cwrite E E' {E \\<longmapsto> E'}\"\napply (clarsimp simp add: CSL_def)\napply (case_tac n, simp, clarsimp simp add: fpdom_def, intro conjI allI impI notI)\napply (erule aborts.cases, simp_all, fastforce dest: ptoheap_read)\napply (erule red.cases, simp_all, fastforce elim: write_helper)\ndone\n\nlemma alloc_helper:\n \"\\<lbrakk>ptoheap h hh; x \\<notin> dom hh\\<rbrakk> \\<Longrightarrow> \n  ptoheap (Some [x \\<mapsto> (v, pfull)] \\<oplus> h) (hh(x \\<mapsto> v))\"\napply (auto simp add: ptoheap_def mypadd_def pdisj_def padd_def split: option.splits)\napply (drule_tac a=xa in allD, simp)\ndone\n\ntheorem rule_alloc:\n  \"\\<lbrakk> x \\<notin> fvE E \\<union> fvAs \\<Gamma> \\<rbrakk>\n  \\<Longrightarrow> \\<Gamma> \\<turnstile> {Aemp} Calloc x E {Evar x \\<longmapsto> E}\"\napply (clarsimp simp add: CSL_def)\napply (case_tac n, simp, clarsimp, intro conjI allI impI notI)\napply (erule aborts.cases, simp_all)\napply (erule red.cases, simp_all, fastforce elim: alloc_helper)\ndone\n\nlemma free_helper:\n \"\\<lbrakk> ptoheap (Some h \\<oplus> hF) hh; h x = Some (v, pfull) \\<rbrakk> \\<Longrightarrow> \n  ptoheap (Some (h(x:=None)) \\<oplus> hF) (hh(x:=None))\"\napply (case_tac hF, simp_all add: ptoheap_def mypadd_def split: if_split_asm)\napply (clarsimp simp add: pdisj_def, (drule_tac a=xa in allD)+)\napply (clarsimp simp add: padd_def split: option.splits)\ndone\n\ntheorem rule_free:\n  \"\\<Gamma> \\<turnstile> {E \\<longmapsto> E0} Cdispose E {Aemp}\"\napply (clarsimp simp add: CSL_def)\napply (case_tac n, simp, clarsimp simp add: fpdom_def, intro conjI allI impI notI)\n apply (erule aborts.cases, simp_all, fastforce dest: ptoheap_read)\napply (erule red.cases, simp_all, fastforce elim: free_helper dom_eqD)\ndone\n\nsubsubsection {* Simple structural rules (Conseq, Disj, Ex) *}\n\nlemma safe_conseq:\n \"\\<lbrakk> safe n C s h \\<Gamma> Q ; Q \\<sqsubseteq> Q' \\<rbrakk> \\<Longrightarrow> safe n C s h \\<Gamma> Q'\"\napply (induct n arbitrary: C s h, simp, clarsimp simp add: implies_def)\napply (drule allD, drule (2) all5_imp2D, simp_all, clarsimp)\napply (drule (1) mall3_impD, rule_tac x=\"h'\" and y=\"hJ'\" in ex2I, simp)\ndone\n\ntheorem rule_conseq:\n \"\\<lbrakk> \\<Gamma> \\<turnstile> {P} C {Q} ; P' \\<sqsubseteq> P ; Q \\<sqsubseteq> Q' \\<rbrakk> \\<Longrightarrow> \\<Gamma> \\<turnstile> {P'} C {Q'}\"\nby (fastforce simp add: CSL_def implies_def elim!: safe_conseq)\n\ntheorem rule_disj:\n \"\\<lbrakk> \\<Gamma> \\<turnstile> {P1} C {Q1}; \\<Gamma> \\<turnstile> {P2} C {Q2} \\<rbrakk> \\<Longrightarrow> \\<Gamma> \\<turnstile> {Adisj P1 P2} C {Adisj Q1 Q2}\"\nby (clarsimp simp add: CSL_def, safe)\n   (rule safe_conseq, simp_all add: implies_def, drule (2) all3_impD, force)+\n\ntheorem rule_ex:\n \"\\<lbrakk> \\<forall>n. (\\<Gamma> \\<turnstile> {P n} C {Q n}) \\<rbrakk> \\<Longrightarrow> \\<Gamma> \\<turnstile> {Aex P} C {Aex Q}\"\nby (clarsimp simp add: CSL_def, rule_tac Q = \"Q v\" in safe_conseq, \n    auto simp add: implies_def)\n\nsubsubsection {* Conjunction rule *}\n\nlemma safe_conj:\n  \"\\<lbrakk> safe n C s h \\<Gamma> Q1; \n     safe n C s h \\<Gamma> Q2;\n     \\<forall>r. precise (\\<Gamma> r) \\<rbrakk> \n  \\<Longrightarrow> safe n C s h \\<Gamma> (Aconj Q1 Q2)\"\napply (induct n arbitrary: C s h, simp, clarsimp)\napply (drule allD, drule (2) all5_imp2D, clarsimp)+\napply (rule_tac x=h' and y=hJ' in ex2I, simp) \napply (erule mall3_imp2D, simp_all)\napply (subgoal_tac \"Some hJ' \\<oplus> Some h' = Some hJ'a \\<oplus> Some h'a\")\n apply (subst (asm) (8 9) mypadd_def, simp split: if_split_asm)\n  apply (erule_tac[2] notE, erule_tac[2] pdisj_search)\n apply (drule_tac s=\"a\" and y=\"h'\" and y'=\"h'a\" in preciseD [rotated], simp_all\n        add: envs_def precise_istar, fast)\napply (case_tac hF, simp add: ptoheap_def, clarsimp, rename_tac hR)\napply (drule (1) ptoD, rule_tac x=\"Some hR\" in pa_cancel, simp add: pa_ac)\napply (rule notI, simp add: pa_ac ptoheap_def)\ndone\n\ntheorem rule_conj:\n \"\\<lbrakk> \\<Gamma> \\<turnstile> {P1} C {Q1}; \n    \\<Gamma> \\<turnstile> {P2} C {Q2}; \n    \\<forall>r. precise (\\<Gamma> r) \\<rbrakk>\n  \\<Longrightarrow> \\<Gamma> \\<turnstile> {Aconj P1 P2} C {Aconj Q1 Q2}\"\nby (auto simp add: CSL_def intro: safe_conj)\n\nsubsubsection {* Auxiliary variables *}\n\nlemma safe_aux:\n  \"\\<lbrakk> safe n C s h \\<Gamma> Q; disjoint X (fvC (rem_vars X C) \\<union> fvA Q \\<union> fvAs \\<Gamma>) \\<rbrakk>\n  \\<Longrightarrow> safe n (rem_vars X C) s h \\<Gamma> Q\"\napply (induct n arbitrary: C s h, simp_all)\napply (intro conjI impI allI, clarsimp)\napply (fastforce intro: aborts_remvars)\napply (elim conjE, erule order_trans [OF accesses_remvars])\napply (clarsimp, frule red_properties, drule aux_red, simp_all)\napply (drule_tac a=\"Some hJ \\<oplus> hF\" in allD, simp add: pa_ac)\napply (clarsimp, drule allD, drule (2) all5_imp2D, clarsimp)\napply (intro exI conjI, simp+)\napply (fastforce simp add: disjoint_commute agreesC)\napply (drule (1) mall3_imp2D, fast) \napply (erule safe_agrees, fastforce simp add: disjoint_commute agreesC)\ndone\n\ntext {* The proof rule for eliminating auxiliary variables. Note that a\n  set of variables, @{term X}, is auxiliary for a command @{term C}\n  iff it disjoint from @{term \"fvC (rem_vars X C)\"}. *}\n\ntheorem rule_aux:\n  \"\\<lbrakk> \\<Gamma> \\<turnstile> {P} C {Q} ;\n     disjoint X (fvA P \\<union> fvA Q \\<union> fvAs \\<Gamma> \\<union> fvC (rem_vars X C)) \\<rbrakk>\n  \\<Longrightarrow> \\<Gamma> \\<turnstile> {P} rem_vars X C {Q}\"\nby (auto simp add: CSL_def safe_aux disjoint_commute)\n\nend", "meta": {"author": "qin-yu", "repo": "concurrent-separation-logic-soundness", "sha": "b99bfad3c6c2978e1b84130e4aa6bff8827b09ca", "save_path": "github-repos/isabelle/qin-yu-concurrent-separation-logic-soundness", "path": "github-repos/isabelle/qin-yu-concurrent-separation-logic-soundness/concurrent-separation-logic-soundness-b99bfad3c6c2978e1b84130e4aa6bff8827b09ca/Perm.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8902942290328345, "lm_q2_score": 0.8006919949619792, "lm_q1q2_score": 0.7128514623474375}}
{"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_HSort2Sorts\n  imports \"../../Test_Base\"\nbegin\n\ndatatype 'a list = nil2 | cons2 \"'a\" \"'a list\"\n\ndatatype Heap = Node \"Heap\" \"int\" \"Heap\" | Nil\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 hmerge :: \"Heap => Heap => Heap\" where\n  \"hmerge (Node z x2 x3) (Node x4 x5 x6) =\n   (if 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\n(*fun did not finish the proof*)\nfunction toList :: \"Heap => int list\" where\n  \"toList (Node p y q) = cons2 y (toList (hmerge p q))\"\n| \"toList (Nil) = nil2\"\n  by pat_completeness auto\n\nfun hinsert :: \"int => Heap => Heap\" where\n  \"hinsert x y = hmerge (Node Nil x Nil) y\"\n\nfun toHeap2 :: \"int list => Heap\" where\n  \"toHeap2 (nil2) = Nil\"\n| \"toHeap2 (cons2 y xs) = hinsert y (toHeap2 xs)\"\n\nfun hsort2 :: \"int list => int list\" where\n  \"hsort2 x = toList (toHeap2 x)\"\n\ntheorem property0 :\n  \"ordered (hsort2 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_HSort2Sorts.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942173896131, "lm_q2_score": 0.8006920044739461, "lm_q1q2_score": 0.7128514614932524}}
{"text": "(*  Title:      HOL/Conditionally_Complete_Lattices.thy\n    Author:     Amine Chaieb and L C Paulson, University of Cambridge\n    Author:     Johannes H\u00f6lzl, TU M\u00fcnchen\n    Author:     Luke S. Serafin, Carnegie Mellon University\n*)\n\nsection \\<open>Conditionally-complete Lattices\\<close>\n\ntheory Conditionally_Complete_Lattices\nimports Finite_Set Lattices_Big Set_Interval\nbegin\n\ncontext preorder\nbegin\n\ndefinition \"bdd_above A \\<longleftrightarrow> (\\<exists>M. \\<forall>x \\<in> A. x \\<le> M)\"\ndefinition \"bdd_below A \\<longleftrightarrow> (\\<exists>m. \\<forall>x \\<in> A. m \\<le> x)\"\n\nlemma bdd_aboveI[intro]: \"(\\<And>x. x \\<in> A \\<Longrightarrow> x \\<le> M) \\<Longrightarrow> bdd_above A\"\n  by (auto simp: bdd_above_def)\n\nlemma bdd_belowI[intro]: \"(\\<And>x. x \\<in> A \\<Longrightarrow> m \\<le> x) \\<Longrightarrow> bdd_below A\"\n  by (auto simp: bdd_below_def)\n\nlemma bdd_aboveI2: \"(\\<And>x. x \\<in> A \\<Longrightarrow> f x \\<le> M) \\<Longrightarrow> bdd_above (f`A)\"\n  by force\n\nlemma bdd_belowI2: \"(\\<And>x. x \\<in> A \\<Longrightarrow> m \\<le> f x) \\<Longrightarrow> bdd_below (f`A)\"\n  by force\n\nlemma bdd_above_empty [simp, intro]: \"bdd_above {}\"\n  unfolding bdd_above_def by auto\n\nlemma bdd_below_empty [simp, intro]: \"bdd_below {}\"\n  unfolding bdd_below_def by auto\n\nlemma bdd_above_mono: \"bdd_above B \\<Longrightarrow> A \\<subseteq> B \\<Longrightarrow> bdd_above A\"\n  by (metis (full_types) bdd_above_def order_class.le_neq_trans psubsetD)\n\nlemma bdd_below_mono: \"bdd_below B \\<Longrightarrow> A \\<subseteq> B \\<Longrightarrow> bdd_below A\"\n  by (metis bdd_below_def order_class.le_neq_trans psubsetD)\n\nlemma bdd_above_Int1 [simp]: \"bdd_above A \\<Longrightarrow> bdd_above (A \\<inter> B)\"\n  using bdd_above_mono by auto\n\nlemma bdd_above_Int2 [simp]: \"bdd_above B \\<Longrightarrow> bdd_above (A \\<inter> B)\"\n  using bdd_above_mono by auto\n\nlemma bdd_below_Int1 [simp]: \"bdd_below A \\<Longrightarrow> bdd_below (A \\<inter> B)\"\n  using bdd_below_mono by auto\n\nlemma bdd_below_Int2 [simp]: \"bdd_below B \\<Longrightarrow> bdd_below (A \\<inter> B)\"\n  using bdd_below_mono by auto\n\nlemma bdd_above_Ioo [simp, intro]: \"bdd_above {a <..< b}\"\n  by (auto simp add: bdd_above_def intro!: exI[of _ b] less_imp_le)\n\nlemma bdd_above_Ico [simp, intro]: \"bdd_above {a ..< b}\"\n  by (auto simp add: bdd_above_def intro!: exI[of _ b] less_imp_le)\n\nlemma bdd_above_Iio [simp, intro]: \"bdd_above {..< b}\"\n  by (auto simp add: bdd_above_def intro: exI[of _ b] less_imp_le)\n\nlemma bdd_above_Ioc [simp, intro]: \"bdd_above {a <.. b}\"\n  by (auto simp add: bdd_above_def intro: exI[of _ b] less_imp_le)\n\nlemma bdd_above_Icc [simp, intro]: \"bdd_above {a .. b}\"\n  by (auto simp add: bdd_above_def intro: exI[of _ b] less_imp_le)\n\nlemma bdd_above_Iic [simp, intro]: \"bdd_above {.. b}\"\n  by (auto simp add: bdd_above_def intro: exI[of _ b] less_imp_le)\n\nlemma bdd_below_Ioo [simp, intro]: \"bdd_below {a <..< b}\"\n  by (auto simp add: bdd_below_def intro!: exI[of _ a] less_imp_le)\n\nlemma bdd_below_Ioc [simp, intro]: \"bdd_below {a <.. b}\"\n  by (auto simp add: bdd_below_def intro!: exI[of _ a] less_imp_le)\n\nlemma bdd_below_Ioi [simp, intro]: \"bdd_below {a <..}\"\n  by (auto simp add: bdd_below_def intro: exI[of _ a] less_imp_le)\n\nlemma bdd_below_Ico [simp, intro]: \"bdd_below {a ..< b}\"\n  by (auto simp add: bdd_below_def intro: exI[of _ a] less_imp_le)\n\nlemma bdd_below_Icc [simp, intro]: \"bdd_below {a .. b}\"\n  by (auto simp add: bdd_below_def intro: exI[of _ a] less_imp_le)\n\nlemma bdd_below_Ici [simp, intro]: \"bdd_below {a ..}\"\n  by (auto simp add: bdd_below_def intro: exI[of _ a] less_imp_le)\n\nend\n\nlemma (in order_top) bdd_above_top[simp, intro!]: \"bdd_above A\"\n  by (rule bdd_aboveI[of _ top]) simp\n\nlemma (in order_bot) bdd_above_bot[simp, intro!]: \"bdd_below A\"\n  by (rule bdd_belowI[of _ bot]) simp\n\nlemma bdd_above_image_mono: \"mono f \\<Longrightarrow> bdd_above A \\<Longrightarrow> bdd_above (f`A)\"\n  by (auto simp: bdd_above_def mono_def)\n\nlemma bdd_below_image_mono: \"mono f \\<Longrightarrow> bdd_below A \\<Longrightarrow> bdd_below (f`A)\"\n  by (auto simp: bdd_below_def mono_def)\n\nlemma bdd_above_image_antimono: \"antimono f \\<Longrightarrow> bdd_below A \\<Longrightarrow> bdd_above (f`A)\"\n  by (auto simp: bdd_above_def bdd_below_def antimono_def)\n\nlemma bdd_below_image_antimono: \"antimono f \\<Longrightarrow> bdd_above A \\<Longrightarrow> bdd_below (f`A)\"\n  by (auto simp: bdd_above_def bdd_below_def antimono_def)\n\nlemma\n  fixes X :: \"'a::ordered_ab_group_add set\"\n  shows bdd_above_uminus[simp]: \"bdd_above (uminus ` X) \\<longleftrightarrow> bdd_below X\"\n    and bdd_below_uminus[simp]: \"bdd_below (uminus ` X) \\<longleftrightarrow> bdd_above X\"\n  using bdd_above_image_antimono[of uminus X] bdd_below_image_antimono[of uminus \"uminus`X\"]\n  using bdd_below_image_antimono[of uminus X] bdd_above_image_antimono[of uminus \"uminus`X\"]\n  by (auto simp: antimono_def image_image)\n\ncontext lattice\nbegin\n\nlemma bdd_above_insert [simp]: \"bdd_above (insert a A) = bdd_above A\"\n  by (auto simp: bdd_above_def intro: le_supI2 sup_ge1)\n\nlemma bdd_below_insert [simp]: \"bdd_below (insert a A) = bdd_below A\"\n  by (auto simp: bdd_below_def intro: le_infI2 inf_le1)\n\nlemma bdd_finite [simp]:\n  assumes \"finite A\" shows bdd_above_finite: \"bdd_above A\" and bdd_below_finite: \"bdd_below A\"\n  using assms by (induct rule: finite_induct, auto)\n\nlemma bdd_above_Un [simp]: \"bdd_above (A \\<union> B) = (bdd_above A \\<and> bdd_above B)\"\nproof\n  assume \"bdd_above (A \\<union> B)\"\n  thus \"bdd_above A \\<and> bdd_above B\" unfolding bdd_above_def by auto\nnext\n  assume \"bdd_above A \\<and> bdd_above B\"\n  then obtain a b where \"\\<forall>x\\<in>A. x \\<le> a\" \"\\<forall>x\\<in>B. x \\<le> b\" unfolding bdd_above_def by auto\n  hence \"\\<forall>x \\<in> A \\<union> B. x \\<le> sup a b\" by (auto intro: Un_iff le_supI1 le_supI2)\n  thus \"bdd_above (A \\<union> B)\" unfolding bdd_above_def ..\nqed\n\nlemma bdd_below_Un [simp]: \"bdd_below (A \\<union> B) = (bdd_below A \\<and> bdd_below B)\"\nproof\n  assume \"bdd_below (A \\<union> B)\"\n  thus \"bdd_below A \\<and> bdd_below B\" unfolding bdd_below_def by auto\nnext\n  assume \"bdd_below A \\<and> bdd_below B\"\n  then obtain a b where \"\\<forall>x\\<in>A. a \\<le> x\" \"\\<forall>x\\<in>B. b \\<le> x\" unfolding bdd_below_def by auto\n  hence \"\\<forall>x \\<in> A \\<union> B. inf a b \\<le> x\" by (auto intro: Un_iff le_infI1 le_infI2)\n  thus \"bdd_below (A \\<union> B)\" unfolding bdd_below_def ..\nqed\n\nlemma bdd_above_image_sup[simp]:\n  \"bdd_above ((\\<lambda>x. sup (f x) (g x)) ` A) \\<longleftrightarrow> bdd_above (f`A) \\<and> bdd_above (g`A)\"\nby (auto simp: bdd_above_def intro: le_supI1 le_supI2)\n\nlemma bdd_below_image_inf[simp]:\n  \"bdd_below ((\\<lambda>x. inf (f x) (g x)) ` A) \\<longleftrightarrow> bdd_below (f`A) \\<and> bdd_below (g`A)\"\nby (auto simp: bdd_below_def intro: le_infI1 le_infI2)\n\nlemma bdd_below_UN[simp]: \"finite I \\<Longrightarrow> bdd_below (\\<Union>i\\<in>I. A i) = (\\<forall>i \\<in> I. bdd_below (A i))\"\nby (induction I rule: finite.induct) auto\n\nlemma bdd_above_UN[simp]: \"finite I \\<Longrightarrow> bdd_above (\\<Union>i\\<in>I. A i) = (\\<forall>i \\<in> I. bdd_above (A i))\"\nby (induction I rule: finite.induct) auto\n\nend\n\n\ntext \\<open>\n\nTo avoid name classes with the \\<^class>\\<open>complete_lattice\\<close>-class we prefix \\<^const>\\<open>Sup\\<close> and\n\\<^const>\\<open>Inf\\<close> in theorem names with c.\n\n\\<close>\n\nclass conditionally_complete_lattice = lattice + Sup + Inf +\n  assumes cInf_lower: \"x \\<in> X \\<Longrightarrow> bdd_below X \\<Longrightarrow> Inf X \\<le> x\"\n    and cInf_greatest: \"X \\<noteq> {} \\<Longrightarrow> (\\<And>x. x \\<in> X \\<Longrightarrow> z \\<le> x) \\<Longrightarrow> z \\<le> Inf X\"\n  assumes cSup_upper: \"x \\<in> X \\<Longrightarrow> bdd_above X \\<Longrightarrow> x \\<le> Sup X\"\n    and cSup_least: \"X \\<noteq> {} \\<Longrightarrow> (\\<And>x. x \\<in> X \\<Longrightarrow> x \\<le> z) \\<Longrightarrow> Sup X \\<le> z\"\nbegin\n\nlemma cSup_upper2: \"x \\<in> X \\<Longrightarrow> y \\<le> x \\<Longrightarrow> bdd_above X \\<Longrightarrow> y \\<le> Sup X\"\n  by (metis cSup_upper order_trans)\n\nlemma cInf_lower2: \"x \\<in> X \\<Longrightarrow> x \\<le> y \\<Longrightarrow> bdd_below X \\<Longrightarrow> Inf X \\<le> y\"\n  by (metis cInf_lower order_trans)\n\nlemma cSup_mono: \"B \\<noteq> {} \\<Longrightarrow> bdd_above A \\<Longrightarrow> (\\<And>b. b \\<in> B \\<Longrightarrow> \\<exists>a\\<in>A. b \\<le> a) \\<Longrightarrow> Sup B \\<le> Sup A\"\n  by (metis cSup_least cSup_upper2)\n\nlemma cInf_mono: \"B \\<noteq> {} \\<Longrightarrow> bdd_below A \\<Longrightarrow> (\\<And>b. b \\<in> B \\<Longrightarrow> \\<exists>a\\<in>A. a \\<le> b) \\<Longrightarrow> Inf A \\<le> Inf B\"\n  by (metis cInf_greatest cInf_lower2)\n\nlemma cSup_subset_mono: \"A \\<noteq> {} \\<Longrightarrow> bdd_above B \\<Longrightarrow> A \\<subseteq> B \\<Longrightarrow> Sup A \\<le> Sup B\"\n  by (metis cSup_least cSup_upper subsetD)\n\nlemma cInf_superset_mono: \"A \\<noteq> {} \\<Longrightarrow> bdd_below B \\<Longrightarrow> A \\<subseteq> B \\<Longrightarrow> Inf B \\<le> Inf A\"\n  by (metis cInf_greatest cInf_lower subsetD)\n\nlemma cSup_eq_maximum: \"z \\<in> X \\<Longrightarrow> (\\<And>x. x \\<in> X \\<Longrightarrow> x \\<le> z) \\<Longrightarrow> Sup X = z\"\n  by (intro antisym cSup_upper[of z X] cSup_least[of X z]) auto\n\nlemma cInf_eq_minimum: \"z \\<in> X \\<Longrightarrow> (\\<And>x. x \\<in> X \\<Longrightarrow> z \\<le> x) \\<Longrightarrow> Inf X = z\"\n  by (intro antisym cInf_lower[of z X] cInf_greatest[of X z]) auto\n\nlemma cSup_le_iff: \"S \\<noteq> {} \\<Longrightarrow> bdd_above S \\<Longrightarrow> Sup S \\<le> a \\<longleftrightarrow> (\\<forall>x\\<in>S. x \\<le> a)\"\n  by (metis order_trans cSup_upper cSup_least)\n\nlemma le_cInf_iff: \"S \\<noteq> {} \\<Longrightarrow> bdd_below S \\<Longrightarrow> a \\<le> Inf S \\<longleftrightarrow> (\\<forall>x\\<in>S. a \\<le> x)\"\n  by (metis order_trans cInf_lower cInf_greatest)\n\nlemma cSup_eq_non_empty:\n  assumes 1: \"X \\<noteq> {}\"\n  assumes 2: \"\\<And>x. x \\<in> X \\<Longrightarrow> x \\<le> a\"\n  assumes 3: \"\\<And>y. (\\<And>x. x \\<in> X \\<Longrightarrow> x \\<le> y) \\<Longrightarrow> a \\<le> y\"\n  shows \"Sup X = a\"\n  by (intro 3 1 antisym cSup_least) (auto intro: 2 1 cSup_upper)\n\nlemma cInf_eq_non_empty:\n  assumes 1: \"X \\<noteq> {}\"\n  assumes 2: \"\\<And>x. x \\<in> X \\<Longrightarrow> a \\<le> x\"\n  assumes 3: \"\\<And>y. (\\<And>x. x \\<in> X \\<Longrightarrow> y \\<le> x) \\<Longrightarrow> y \\<le> a\"\n  shows \"Inf X = a\"\n  by (intro 3 1 antisym cInf_greatest) (auto intro: 2 1 cInf_lower)\n\nlemma cInf_cSup: \"S \\<noteq> {} \\<Longrightarrow> bdd_below S \\<Longrightarrow> Inf S = Sup {x. \\<forall>s\\<in>S. x \\<le> s}\"\n  by (rule cInf_eq_non_empty) (auto intro!: cSup_upper cSup_least simp: bdd_below_def)\n\nlemma cSup_cInf: \"S \\<noteq> {} \\<Longrightarrow> bdd_above S \\<Longrightarrow> Sup S = Inf {x. \\<forall>s\\<in>S. s \\<le> x}\"\n  by (rule cSup_eq_non_empty) (auto intro!: cInf_lower cInf_greatest simp: bdd_above_def)\n\nlemma cSup_insert: \"X \\<noteq> {} \\<Longrightarrow> bdd_above X \\<Longrightarrow> Sup (insert a X) = sup a (Sup X)\"\n  by (intro cSup_eq_non_empty) (auto intro: le_supI2 cSup_upper cSup_least)\n\nlemma cInf_insert: \"X \\<noteq> {} \\<Longrightarrow> bdd_below X \\<Longrightarrow> Inf (insert a X) = inf a (Inf X)\"\n  by (intro cInf_eq_non_empty) (auto intro: le_infI2 cInf_lower cInf_greatest)\n\nlemma cSup_singleton [simp]: \"Sup {x} = x\"\n  by (intro cSup_eq_maximum) auto\n\nlemma cInf_singleton [simp]: \"Inf {x} = x\"\n  by (intro cInf_eq_minimum) auto\n\nlemma cSup_insert_If:  \"bdd_above X \\<Longrightarrow> Sup (insert a X) = (if X = {} then a else sup a (Sup X))\"\n  using cSup_insert[of X] by simp\n\nlemma cInf_insert_If: \"bdd_below X \\<Longrightarrow> Inf (insert a X) = (if X = {} then a else inf a (Inf X))\"\n  using cInf_insert[of X] by simp\n\nlemma le_cSup_finite: \"finite X \\<Longrightarrow> x \\<in> X \\<Longrightarrow> x \\<le> Sup X\"\nproof (induct X arbitrary: x rule: finite_induct)\n  case (insert x X y) then show ?case\n    by (cases \"X = {}\") (auto simp: cSup_insert intro: le_supI2)\nqed simp\n\nlemma cInf_le_finite: \"finite X \\<Longrightarrow> x \\<in> X \\<Longrightarrow> Inf X \\<le> x\"\nproof (induct X arbitrary: x rule: finite_induct)\n  case (insert x X y) then show ?case\n    by (cases \"X = {}\") (auto simp: cInf_insert intro: le_infI2)\nqed simp\n\nlemma cSup_eq_Sup_fin: \"finite X \\<Longrightarrow> X \\<noteq> {} \\<Longrightarrow> Sup X = Sup_fin X\"\n  by (induct X rule: finite_ne_induct) (simp_all add: cSup_insert)\n\nlemma cInf_eq_Inf_fin: \"finite X \\<Longrightarrow> X \\<noteq> {} \\<Longrightarrow> Inf X = Inf_fin X\"\n  by (induct X rule: finite_ne_induct) (simp_all add: cInf_insert)\n\nlemma cSup_atMost[simp]: \"Sup {..x} = x\"\n  by (auto intro!: cSup_eq_maximum)\n\nlemma cSup_greaterThanAtMost[simp]: \"y < x \\<Longrightarrow> Sup {y<..x} = x\"\n  by (auto intro!: cSup_eq_maximum)\n\nlemma cSup_atLeastAtMost[simp]: \"y \\<le> x \\<Longrightarrow> Sup {y..x} = x\"\n  by (auto intro!: cSup_eq_maximum)\n\nlemma cInf_atLeast[simp]: \"Inf {x..} = x\"\n  by (auto intro!: cInf_eq_minimum)\n\nlemma cInf_atLeastLessThan[simp]: \"y < x \\<Longrightarrow> Inf {y..<x} = y\"\n  by (auto intro!: cInf_eq_minimum)\n\nlemma cInf_atLeastAtMost[simp]: \"y \\<le> x \\<Longrightarrow> Inf {y..x} = y\"\n  by (auto intro!: cInf_eq_minimum)\n\nlemma cINF_lower: \"bdd_below (f ` A) \\<Longrightarrow> x \\<in> A \\<Longrightarrow> \\<Sqinter>(f ` A) \\<le> f x\"\n  using cInf_lower [of _ \"f ` A\"] by simp\n\nlemma cINF_greatest: \"A \\<noteq> {} \\<Longrightarrow> (\\<And>x. x \\<in> A \\<Longrightarrow> m \\<le> f x) \\<Longrightarrow> m \\<le> \\<Sqinter>(f ` A)\"\n  using cInf_greatest [of \"f ` A\"] by auto\n\nlemma cSUP_upper: \"x \\<in> A \\<Longrightarrow> bdd_above (f ` A) \\<Longrightarrow> f x \\<le> \\<Squnion>(f ` A)\"\n  using cSup_upper [of _ \"f ` A\"] by simp\n\nlemma cSUP_least: \"A \\<noteq> {} \\<Longrightarrow> (\\<And>x. x \\<in> A \\<Longrightarrow> f x \\<le> M) \\<Longrightarrow> \\<Squnion>(f ` A) \\<le> M\"\n  using cSup_least [of \"f ` A\"] by auto\n\nlemma cINF_lower2: \"bdd_below (f ` A) \\<Longrightarrow> x \\<in> A \\<Longrightarrow> f x \\<le> u \\<Longrightarrow> \\<Sqinter>(f ` A) \\<le> u\"\n  by (auto intro: cINF_lower order_trans)\n\nlemma cSUP_upper2: \"bdd_above (f ` A) \\<Longrightarrow> x \\<in> A \\<Longrightarrow> u \\<le> f x \\<Longrightarrow> u \\<le> \\<Squnion>(f ` A)\"\n  by (auto intro: cSUP_upper order_trans)\n\nlemma cSUP_const [simp]: \"A \\<noteq> {} \\<Longrightarrow> (\\<Squnion>x\\<in>A. c) = c\"\n  by (intro antisym cSUP_least) (auto intro: cSUP_upper)\n\nlemma cINF_const [simp]: \"A \\<noteq> {} \\<Longrightarrow> (\\<Sqinter>x\\<in>A. c) = c\"\n  by (intro antisym cINF_greatest) (auto intro: cINF_lower)\n\nlemma le_cINF_iff: \"A \\<noteq> {} \\<Longrightarrow> bdd_below (f ` A) \\<Longrightarrow> u \\<le> \\<Sqinter>(f ` A) \\<longleftrightarrow> (\\<forall>x\\<in>A. u \\<le> f x)\"\n  by (metis cINF_greatest cINF_lower order_trans)\n\nlemma cSUP_le_iff: \"A \\<noteq> {} \\<Longrightarrow> bdd_above (f ` A) \\<Longrightarrow> \\<Squnion>(f ` A) \\<le> u \\<longleftrightarrow> (\\<forall>x\\<in>A. f x \\<le> u)\"\n  by (metis cSUP_least cSUP_upper order_trans)\n\nlemma less_cINF_D: \"bdd_below (f`A) \\<Longrightarrow> y < (\\<Sqinter>i\\<in>A. f i) \\<Longrightarrow> i \\<in> A \\<Longrightarrow> y < f i\"\n  by (metis cINF_lower less_le_trans)\n\nlemma cSUP_lessD: \"bdd_above (f`A) \\<Longrightarrow> (\\<Squnion>i\\<in>A. f i) < y \\<Longrightarrow> i \\<in> A \\<Longrightarrow> f i < y\"\n  by (metis cSUP_upper le_less_trans)\n\nlemma cINF_insert: \"A \\<noteq> {} \\<Longrightarrow> bdd_below (f ` A) \\<Longrightarrow> \\<Sqinter>(f ` insert a A) = inf (f a) (\\<Sqinter>(f ` A))\"\n  by (simp add: cInf_insert)\n\nlemma cSUP_insert: \"A \\<noteq> {} \\<Longrightarrow> bdd_above (f ` A) \\<Longrightarrow> \\<Squnion>(f ` insert a A) = sup (f a) (\\<Squnion>(f ` A))\"\n  by (simp add: cSup_insert)\n\nlemma cINF_mono: \"B \\<noteq> {} \\<Longrightarrow> bdd_below (f ` A) \\<Longrightarrow> (\\<And>m. m \\<in> B \\<Longrightarrow> \\<exists>n\\<in>A. f n \\<le> g m) \\<Longrightarrow> \\<Sqinter>(f ` A) \\<le> \\<Sqinter>(g ` B)\"\n  using cInf_mono [of \"g ` B\" \"f ` A\"] by auto\n\nlemma cSUP_mono: \"A \\<noteq> {} \\<Longrightarrow> bdd_above (g ` B) \\<Longrightarrow> (\\<And>n. n \\<in> A \\<Longrightarrow> \\<exists>m\\<in>B. f n \\<le> g m) \\<Longrightarrow> \\<Squnion>(f ` A) \\<le> \\<Squnion>(g ` B)\"\n  using cSup_mono [of \"f ` A\" \"g ` B\"] by auto\n\nlemma cINF_superset_mono: \"A \\<noteq> {} \\<Longrightarrow> bdd_below (g ` B) \\<Longrightarrow> A \\<subseteq> B \\<Longrightarrow> (\\<And>x. x \\<in> B \\<Longrightarrow> g x \\<le> f x) \\<Longrightarrow> \\<Sqinter>(g ` B) \\<le> \\<Sqinter>(f ` A)\"\n  by (rule cINF_mono) auto\n\nlemma cSUP_subset_mono: \n  \"\\<lbrakk>A \\<noteq> {}; bdd_above (g ` B); A \\<subseteq> B; \\<And>x. x \\<in> A \\<Longrightarrow> f x \\<le> g x\\<rbrakk> \\<Longrightarrow> \\<Squnion> (f ` A) \\<le> \\<Squnion> (g ` B)\"\n  by (rule cSUP_mono) auto\n\nlemma less_eq_cInf_inter: \"bdd_below A \\<Longrightarrow> bdd_below B \\<Longrightarrow> A \\<inter> B \\<noteq> {} \\<Longrightarrow> inf (Inf A) (Inf B) \\<le> Inf (A \\<inter> B)\"\n  by (metis cInf_superset_mono lattice_class.inf_sup_ord(1) le_infI1)\n\nlemma cSup_inter_less_eq: \"bdd_above A \\<Longrightarrow> bdd_above B \\<Longrightarrow> A \\<inter> B \\<noteq> {} \\<Longrightarrow> Sup (A \\<inter> B) \\<le> sup (Sup A) (Sup B) \"\n  by (metis cSup_subset_mono lattice_class.inf_sup_ord(1) le_supI1)\n\nlemma cInf_union_distrib: \"A \\<noteq> {} \\<Longrightarrow> bdd_below A \\<Longrightarrow> B \\<noteq> {} \\<Longrightarrow> bdd_below B \\<Longrightarrow> Inf (A \\<union> B) = inf (Inf A) (Inf B)\"\n  by (intro antisym le_infI cInf_greatest cInf_lower) (auto intro: le_infI1 le_infI2 cInf_lower)\n\nlemma cINF_union: \"A \\<noteq> {} \\<Longrightarrow> bdd_below (f ` A) \\<Longrightarrow> B \\<noteq> {} \\<Longrightarrow> bdd_below (f ` B) \\<Longrightarrow> \\<Sqinter> (f ` (A \\<union> B)) = \\<Sqinter> (f ` A) \\<sqinter> \\<Sqinter> (f ` B)\"\n  using cInf_union_distrib [of \"f ` A\" \"f ` B\"] by (simp add: image_Un)\n\nlemma cSup_union_distrib: \"A \\<noteq> {} \\<Longrightarrow> bdd_above A \\<Longrightarrow> B \\<noteq> {} \\<Longrightarrow> bdd_above B \\<Longrightarrow> Sup (A \\<union> B) = sup (Sup A) (Sup B)\"\n  by (intro antisym le_supI cSup_least cSup_upper) (auto intro: le_supI1 le_supI2 cSup_upper)\n\nlemma cSUP_union: \"A \\<noteq> {} \\<Longrightarrow> bdd_above (f ` A) \\<Longrightarrow> B \\<noteq> {} \\<Longrightarrow> bdd_above (f ` B) \\<Longrightarrow> \\<Squnion> (f ` (A \\<union> B)) = \\<Squnion> (f ` A) \\<squnion> \\<Squnion> (f ` B)\"\n  using cSup_union_distrib [of \"f ` A\" \"f ` B\"] by (simp add: image_Un)\n\nlemma cINF_inf_distrib: \"A \\<noteq> {} \\<Longrightarrow> bdd_below (f`A) \\<Longrightarrow> bdd_below (g`A) \\<Longrightarrow> \\<Sqinter> (f ` A) \\<sqinter> \\<Sqinter> (g ` A) = (\\<Sqinter>a\\<in>A. inf (f a) (g a))\"\n  by (intro antisym le_infI cINF_greatest cINF_lower2)\n     (auto intro: le_infI1 le_infI2 cINF_greatest cINF_lower le_infI)\n\nlemma SUP_sup_distrib: \"A \\<noteq> {} \\<Longrightarrow> bdd_above (f`A) \\<Longrightarrow> bdd_above (g`A) \\<Longrightarrow> \\<Squnion> (f ` A) \\<squnion> \\<Squnion> (g ` A) = (\\<Squnion>a\\<in>A. sup (f a) (g a))\"\n  by (intro antisym le_supI cSUP_least cSUP_upper2)\n     (auto intro: le_supI1 le_supI2 cSUP_least cSUP_upper le_supI)\n\nlemma cInf_le_cSup:\n  \"A \\<noteq> {} \\<Longrightarrow> bdd_above A \\<Longrightarrow> bdd_below A \\<Longrightarrow> Inf A \\<le> Sup A\"\n  by (auto intro!: cSup_upper2[of \"SOME a. a \\<in> A\"] intro: someI cInf_lower)\n\nend\n\ninstance complete_lattice \\<subseteq> conditionally_complete_lattice\n  by standard (auto intro: Sup_upper Sup_least Inf_lower Inf_greatest)\n\nlemma cSup_eq:\n  fixes a :: \"'a :: {conditionally_complete_lattice, no_bot}\"\n  assumes upper: \"\\<And>x. x \\<in> X \\<Longrightarrow> x \\<le> a\"\n  assumes least: \"\\<And>y. (\\<And>x. x \\<in> X \\<Longrightarrow> x \\<le> y) \\<Longrightarrow> a \\<le> y\"\n  shows \"Sup X = a\"\nproof cases\n  assume \"X = {}\" with lt_ex[of a] least show ?thesis by (auto simp: less_le_not_le)\nqed (intro cSup_eq_non_empty assms)\n\nlemma cInf_eq:\n  fixes a :: \"'a :: {conditionally_complete_lattice, no_top}\"\n  assumes upper: \"\\<And>x. x \\<in> X \\<Longrightarrow> a \\<le> x\"\n  assumes least: \"\\<And>y. (\\<And>x. x \\<in> X \\<Longrightarrow> y \\<le> x) \\<Longrightarrow> y \\<le> a\"\n  shows \"Inf X = a\"\nproof cases\n  assume \"X = {}\" with gt_ex[of a] least show ?thesis by (auto simp: less_le_not_le)\nqed (intro cInf_eq_non_empty assms)\n\nclass conditionally_complete_linorder = conditionally_complete_lattice + linorder\nbegin\n\nlemma less_cSup_iff:\n  \"X \\<noteq> {} \\<Longrightarrow> bdd_above X \\<Longrightarrow> y < Sup X \\<longleftrightarrow> (\\<exists>x\\<in>X. y < x)\"\n  by (rule iffI) (metis cSup_least not_less, metis cSup_upper less_le_trans)\n\nlemma cInf_less_iff: \"X \\<noteq> {} \\<Longrightarrow> bdd_below X \\<Longrightarrow> Inf X < y \\<longleftrightarrow> (\\<exists>x\\<in>X. x < y)\"\n  by (rule iffI) (metis cInf_greatest not_less, metis cInf_lower le_less_trans)\n\nlemma cINF_less_iff: \"A \\<noteq> {} \\<Longrightarrow> bdd_below (f`A) \\<Longrightarrow> (\\<Sqinter>i\\<in>A. f i) < a \\<longleftrightarrow> (\\<exists>x\\<in>A. f x < a)\"\n  using cInf_less_iff[of \"f`A\"] by auto\n\nlemma less_cSUP_iff: \"A \\<noteq> {} \\<Longrightarrow> bdd_above (f`A) \\<Longrightarrow> a < (\\<Squnion>i\\<in>A. f i) \\<longleftrightarrow> (\\<exists>x\\<in>A. a < f x)\"\n  using less_cSup_iff[of \"f`A\"] by auto\n\nlemma less_cSupE:\n  assumes \"y < Sup X\" \"X \\<noteq> {}\" obtains x where \"x \\<in> X\" \"y < x\"\n  by (metis cSup_least assms not_le that)\n\nlemma less_cSupD:\n  \"X \\<noteq> {} \\<Longrightarrow> z < Sup X \\<Longrightarrow> \\<exists>x\\<in>X. z < x\"\n  by (metis less_cSup_iff not_le_imp_less bdd_above_def)\n\nlemma cInf_lessD:\n  \"X \\<noteq> {} \\<Longrightarrow> Inf X < z \\<Longrightarrow> \\<exists>x\\<in>X. x < z\"\n  by (metis cInf_less_iff not_le_imp_less bdd_below_def)\n\nlemma complete_interval:\n  assumes \"a < b\" and \"P a\" and \"\\<not> P b\"\n  shows \"\\<exists>c. a \\<le> c \\<and> c \\<le> b \\<and> (\\<forall>x. a \\<le> x \\<and> x < c \\<longrightarrow> P x) \\<and>\n             (\\<forall>d. (\\<forall>x. a \\<le> x \\<and> x < d \\<longrightarrow> P x) \\<longrightarrow> d \\<le> c)\"\nproof (rule exI [where x = \"Sup {d. \\<forall>x. a \\<le> x \\<and> x < d \\<longrightarrow> P x}\"], auto)\n  show \"a \\<le> Sup {d. \\<forall>c. a \\<le> c \\<and> c < d \\<longrightarrow> P c}\"\n    by (rule cSup_upper, auto simp: bdd_above_def)\n       (metis \\<open>a < b\\<close> \\<open>\\<not> P b\\<close> linear less_le)\nnext\n  show \"Sup {d. \\<forall>c. a \\<le> c \\<and> c < d \\<longrightarrow> P c} \\<le> b\"\n    apply (rule cSup_least)\n    apply auto\n    apply (metis less_le_not_le)\n    apply (metis \\<open>a<b\\<close> \\<open>\\<not> P b\\<close> linear less_le)\n    done\nnext\n  fix x\n  assume x: \"a \\<le> x\" and lt: \"x < Sup {d. \\<forall>c. a \\<le> c \\<and> c < d \\<longrightarrow> P c}\"\n  show \"P x\"\n    apply (rule less_cSupE [OF lt], auto)\n    apply (metis less_le_not_le)\n    apply (metis x)\n    done\nnext\n  fix d\n    assume 0: \"\\<forall>x. a \\<le> x \\<and> x < d \\<longrightarrow> P x\"\n    thus \"d \\<le> Sup {d. \\<forall>c. a \\<le> c \\<and> c < d \\<longrightarrow> P c}\"\n      by (rule_tac cSup_upper, auto simp: bdd_above_def)\n         (metis \\<open>a<b\\<close> \\<open>\\<not> P b\\<close> linear less_le)\nqed\n\nend\n\ninstance complete_linorder < conditionally_complete_linorder\n  ..\n\nlemma cSup_eq_Max: \"finite (X::'a::conditionally_complete_linorder set) \\<Longrightarrow> X \\<noteq> {} \\<Longrightarrow> Sup X = Max X\"\n  using cSup_eq_Sup_fin[of X] by (simp add: Sup_fin_Max)\n\nlemma cInf_eq_Min: \"finite (X::'a::conditionally_complete_linorder set) \\<Longrightarrow> X \\<noteq> {} \\<Longrightarrow> Inf X = Min X\"\n  using cInf_eq_Inf_fin[of X] by (simp add: Inf_fin_Min)\n\nlemma cSup_lessThan[simp]: \"Sup {..<x::'a::{conditionally_complete_linorder, no_bot, dense_linorder}} = x\"\n  by (auto intro!: cSup_eq_non_empty intro: dense_le)\n\nlemma cSup_greaterThanLessThan[simp]: \"y < x \\<Longrightarrow> Sup {y<..<x::'a::{conditionally_complete_linorder, dense_linorder}} = x\"\n  by (auto intro!: cSup_eq_non_empty intro: dense_le_bounded)\n\nlemma cSup_atLeastLessThan[simp]: \"y < x \\<Longrightarrow> Sup {y..<x::'a::{conditionally_complete_linorder, dense_linorder}} = x\"\n  by (auto intro!: cSup_eq_non_empty intro: dense_le_bounded)\n\nlemma cInf_greaterThan[simp]: \"Inf {x::'a::{conditionally_complete_linorder, no_top, dense_linorder} <..} = x\"\n  by (auto intro!: cInf_eq_non_empty intro: dense_ge)\n\nlemma cInf_greaterThanAtMost[simp]: \"y < x \\<Longrightarrow> Inf {y<..x::'a::{conditionally_complete_linorder, dense_linorder}} = y\"\n  by (auto intro!: cInf_eq_non_empty intro: dense_ge_bounded)\n\nlemma cInf_greaterThanLessThan[simp]: \"y < x \\<Longrightarrow> Inf {y<..<x::'a::{conditionally_complete_linorder, dense_linorder}} = y\"\n  by (auto intro!: cInf_eq_non_empty intro: dense_ge_bounded)\n\nlemma Inf_insert_finite:\n  fixes S :: \"'a::conditionally_complete_linorder set\"\n  shows \"finite S \\<Longrightarrow> Inf (insert x S) = (if S = {} then x else min x (Inf S))\"\n  by (simp add: cInf_eq_Min)\n\nlemma Sup_insert_finite:\n  fixes S :: \"'a::conditionally_complete_linorder set\"\n  shows \"finite S \\<Longrightarrow> Sup (insert x S) = (if S = {} then x else max x (Sup S))\"\n  by (simp add: cSup_insert sup_max)\n\nlemma finite_imp_less_Inf:\n  fixes a :: \"'a::conditionally_complete_linorder\"\n  shows \"\\<lbrakk>finite X; x \\<in> X; \\<And>x. x\\<in>X \\<Longrightarrow> a < x\\<rbrakk> \\<Longrightarrow> a < Inf X\"\n  by (induction X rule: finite_induct) (simp_all add: cInf_eq_Min Inf_insert_finite)\n\nlemma finite_less_Inf_iff:\n  fixes a :: \"'a :: conditionally_complete_linorder\"\n  shows \"\\<lbrakk>finite X; X \\<noteq> {}\\<rbrakk> \\<Longrightarrow> a < Inf X \\<longleftrightarrow> (\\<forall>x \\<in> X. a < x)\"\n  by (auto simp: cInf_eq_Min)\n\nlemma finite_imp_Sup_less:\n  fixes a :: \"'a::conditionally_complete_linorder\"\n  shows \"\\<lbrakk>finite X; x \\<in> X; \\<And>x. x\\<in>X \\<Longrightarrow> a > x\\<rbrakk> \\<Longrightarrow> a > Sup X\"\n  by (induction X rule: finite_induct) (simp_all add: cSup_eq_Max Sup_insert_finite)\n\nlemma finite_Sup_less_iff:\n  fixes a :: \"'a :: conditionally_complete_linorder\"\n  shows \"\\<lbrakk>finite X; X \\<noteq> {}\\<rbrakk> \\<Longrightarrow> a > Sup X \\<longleftrightarrow> (\\<forall>x \\<in> X. a > x)\"\n  by (auto simp: cSup_eq_Max)\n\nclass linear_continuum = conditionally_complete_linorder + dense_linorder +\n  assumes UNIV_not_singleton: \"\\<exists>a b::'a. a \\<noteq> b\"\nbegin\n\nlemma ex_gt_or_lt: \"\\<exists>b. a < b \\<or> b < a\"\n  by (metis UNIV_not_singleton neq_iff)\n\nend\n\ninstantiation nat :: conditionally_complete_linorder\nbegin\n\ndefinition \"Sup (X::nat set) = (if X={} then 0 else Max X)\"\ndefinition \"Inf (X::nat set) = (LEAST n. n \\<in> X)\"\n\nlemma bdd_above_nat: \"bdd_above X \\<longleftrightarrow> finite (X::nat set)\"\nproof\n  assume \"bdd_above X\"\n  then obtain z where \"X \\<subseteq> {.. z}\"\n    by (auto simp: bdd_above_def)\n  then show \"finite X\"\n    by (rule finite_subset) simp\nqed simp\n\ninstance\nproof\n  fix x :: nat\n  fix X :: \"nat set\"\n  show \"Inf X \\<le> x\" if \"x \\<in> X\" \"bdd_below X\"\n    using that by (simp add: Inf_nat_def Least_le)\n  show \"x \\<le> Inf X\" if \"X \\<noteq> {}\" \"\\<And>y. y \\<in> X \\<Longrightarrow> x \\<le> y\"\n    using that unfolding Inf_nat_def ex_in_conv[symmetric] by (rule LeastI2_ex)\n  show \"x \\<le> Sup X\" if \"x \\<in> X\" \"bdd_above X\"\n    using that by (auto simp add: Sup_nat_def bdd_above_nat)\n  show \"Sup X \\<le> x\" if \"X \\<noteq> {}\" \"\\<And>y. y \\<in> X \\<Longrightarrow> y \\<le> x\"\n  proof -\n    from that have \"bdd_above X\"\n      by (auto simp: bdd_above_def)\n    with that show ?thesis \n      by (simp add: Sup_nat_def bdd_above_nat)\n  qed\nqed\n\nend\n\nlemma Inf_nat_def1:\n  fixes K::\"nat set\"\n  assumes \"K \\<noteq> {}\"\n  shows \"Inf K \\<in> K\"\nby (auto simp add: Min_def Inf_nat_def) (meson LeastI assms bot.extremum_unique subsetI)\n\nlemma Sup_nat_empty [simp]: \"Sup {} = (0::nat)\"\n  by (auto simp add: Sup_nat_def) \n\n\n\ninstantiation int :: conditionally_complete_linorder\nbegin\n\ndefinition \"Sup (X::int set) = (THE x. x \\<in> X \\<and> (\\<forall>y\\<in>X. y \\<le> x))\"\ndefinition \"Inf (X::int set) = - (Sup (uminus ` X))\"\n\ninstance\nproof\n  { fix x :: int and X :: \"int set\" assume \"X \\<noteq> {}\" \"bdd_above X\"\n    then obtain x y where \"X \\<subseteq> {..y}\" \"x \\<in> X\"\n      by (auto simp: bdd_above_def)\n    then have *: \"finite (X \\<inter> {x..y})\" \"X \\<inter> {x..y} \\<noteq> {}\" and \"x \\<le> y\"\n      by (auto simp: subset_eq)\n    have \"\\<exists>!x\\<in>X. (\\<forall>y\\<in>X. y \\<le> x)\"\n    proof\n      { fix z assume \"z \\<in> X\"\n        have \"z \\<le> Max (X \\<inter> {x..y})\"\n        proof cases\n          assume \"x \\<le> z\" with \\<open>z \\<in> X\\<close> \\<open>X \\<subseteq> {..y}\\<close> *(1) show ?thesis\n            by (auto intro!: Max_ge)\n        next\n          assume \"\\<not> x \\<le> z\"\n          then have \"z < x\" by simp\n          also have \"x \\<le> Max (X \\<inter> {x..y})\"\n            using \\<open>x \\<in> X\\<close> *(1) \\<open>x \\<le> y\\<close> by (intro Max_ge) auto\n          finally show ?thesis by simp\n        qed }\n      note le = this\n      with Max_in[OF *] show ex: \"Max (X \\<inter> {x..y}) \\<in> X \\<and> (\\<forall>z\\<in>X. z \\<le> Max (X \\<inter> {x..y}))\" by auto\n\n      fix z assume *: \"z \\<in> X \\<and> (\\<forall>y\\<in>X. y \\<le> z)\"\n      with le have \"z \\<le> Max (X \\<inter> {x..y})\"\n        by auto\n      moreover have \"Max (X \\<inter> {x..y}) \\<le> z\"\n        using * ex by auto\n      ultimately show \"z = Max (X \\<inter> {x..y})\"\n        by auto\n    qed\n    then have \"Sup X \\<in> X \\<and> (\\<forall>y\\<in>X. y \\<le> Sup X)\"\n      unfolding Sup_int_def by (rule theI') }\n  note Sup_int = this\n\n  { fix x :: int and X :: \"int set\" assume \"x \\<in> X\" \"bdd_above X\" then show \"x \\<le> Sup X\"\n      using Sup_int[of X] by auto }\n  note le_Sup = this\n  { fix x :: int and X :: \"int set\" assume \"X \\<noteq> {}\" \"\\<And>y. y \\<in> X \\<Longrightarrow> y \\<le> x\" then show \"Sup X \\<le> x\"\n      using Sup_int[of X] by (auto simp: bdd_above_def) }\n  note Sup_le = this\n\n  { fix x :: int and X :: \"int set\" assume \"x \\<in> X\" \"bdd_below X\" then show \"Inf X \\<le> x\"\n      using le_Sup[of \"-x\" \"uminus ` X\"] by (auto simp: Inf_int_def) }\n  { fix x :: int and X :: \"int set\" assume \"X \\<noteq> {}\" \"\\<And>y. y \\<in> X \\<Longrightarrow> x \\<le> y\" then show \"x \\<le> Inf X\"\n      using Sup_le[of \"uminus ` X\" \"-x\"] by (force simp: Inf_int_def) }\nqed\nend\n\nlemma interval_cases:\n  fixes S :: \"'a :: conditionally_complete_linorder set\"\n  assumes ivl: \"\\<And>a b x. a \\<in> S \\<Longrightarrow> b \\<in> S \\<Longrightarrow> a \\<le> x \\<Longrightarrow> x \\<le> b \\<Longrightarrow> x \\<in> S\"\n  shows \"\\<exists>a b. S = {} \\<or>\n    S = UNIV \\<or>\n    S = {..<b} \\<or>\n    S = {..b} \\<or>\n    S = {a<..} \\<or>\n    S = {a..} \\<or>\n    S = {a<..<b} \\<or>\n    S = {a<..b} \\<or>\n    S = {a..<b} \\<or>\n    S = {a..b}\"\nproof -\n  define lower upper where \"lower = {x. \\<exists>s\\<in>S. s \\<le> x}\" and \"upper = {x. \\<exists>s\\<in>S. x \\<le> s}\"\n  with ivl have \"S = lower \\<inter> upper\"\n    by auto\n  moreover\n  have \"\\<exists>a. upper = UNIV \\<or> upper = {} \\<or> upper = {.. a} \\<or> upper = {..< a}\"\n  proof cases\n    assume *: \"bdd_above S \\<and> S \\<noteq> {}\"\n    from * have \"upper \\<subseteq> {.. Sup S}\"\n      by (auto simp: upper_def intro: cSup_upper2)\n    moreover from * have \"{..< Sup S} \\<subseteq> upper\"\n      by (force simp add: less_cSup_iff upper_def subset_eq Ball_def)\n    ultimately have \"upper = {.. Sup S} \\<or> upper = {..< Sup S}\"\n      unfolding ivl_disj_un(2)[symmetric] by auto\n    then show ?thesis by auto\n  next\n    assume \"\\<not> (bdd_above S \\<and> S \\<noteq> {})\"\n    then have \"upper = UNIV \\<or> upper = {}\"\n      by (auto simp: upper_def bdd_above_def not_le dest: less_imp_le)\n    then show ?thesis\n      by auto\n  qed\n  moreover\n  have \"\\<exists>b. lower = UNIV \\<or> lower = {} \\<or> lower = {b ..} \\<or> lower = {b <..}\"\n  proof cases\n    assume *: \"bdd_below S \\<and> S \\<noteq> {}\"\n    from * have \"lower \\<subseteq> {Inf S ..}\"\n      by (auto simp: lower_def intro: cInf_lower2)\n    moreover from * have \"{Inf S <..} \\<subseteq> lower\"\n      by (force simp add: cInf_less_iff lower_def subset_eq Ball_def)\n    ultimately have \"lower = {Inf S ..} \\<or> lower = {Inf S <..}\"\n      unfolding ivl_disj_un(1)[symmetric] by auto\n    then show ?thesis by auto\n  next\n    assume \"\\<not> (bdd_below S \\<and> S \\<noteq> {})\"\n    then have \"lower = UNIV \\<or> lower = {}\"\n      by (auto simp: lower_def bdd_below_def not_le dest: less_imp_le)\n    then show ?thesis\n      by auto\n  qed\n  ultimately show ?thesis\n    unfolding greaterThanAtMost_def greaterThanLessThan_def atLeastAtMost_def atLeastLessThan_def\n    by (metis inf_bot_left inf_bot_right inf_top.left_neutral inf_top.right_neutral)\nqed\n\nlemma cSUP_eq_cINF_D:\n  fixes f :: \"_ \\<Rightarrow> 'b::conditionally_complete_lattice\"\n  assumes eq: \"(\\<Squnion>x\\<in>A. f x) = (\\<Sqinter>x\\<in>A. f x)\"\n     and bdd: \"bdd_above (f ` A)\" \"bdd_below (f ` A)\"\n     and a: \"a \\<in> A\"\n  shows \"f a = (\\<Sqinter>x\\<in>A. f x)\"\napply (rule antisym)\nusing a bdd\napply (auto simp: cINF_lower)\napply (metis eq cSUP_upper)\ndone\n\nlemma cSUP_UNION:\n  fixes f :: \"_ \\<Rightarrow> 'b::conditionally_complete_lattice\"\n  assumes ne: \"A \\<noteq> {}\" \"\\<And>x. x \\<in> A \\<Longrightarrow> B(x) \\<noteq> {}\"\n      and bdd_UN: \"bdd_above (\\<Union>x\\<in>A. f ` B x)\"\n  shows \"(\\<Squnion>z \\<in> \\<Union>x\\<in>A. B x. f z) = (\\<Squnion>x\\<in>A. \\<Squnion>z\\<in>B x. f z)\"\nproof -\n  have bdd: \"\\<And>x. x \\<in> A \\<Longrightarrow> bdd_above (f ` B x)\"\n    using bdd_UN by (meson UN_upper bdd_above_mono)\n  obtain M where \"\\<And>x y. x \\<in> A \\<Longrightarrow> y \\<in> B(x) \\<Longrightarrow> f y \\<le> M\"\n    using bdd_UN by (auto simp: bdd_above_def)\n  then have bdd2: \"bdd_above ((\\<lambda>x. \\<Squnion>z\\<in>B x. f z) ` A)\"\n    unfolding bdd_above_def by (force simp: bdd cSUP_le_iff ne(2))\n  have \"(\\<Squnion>z \\<in> \\<Union>x\\<in>A. B x. f z) \\<le> (\\<Squnion>x\\<in>A. \\<Squnion>z\\<in>B x. f z)\"\n    using assms by (fastforce simp add: intro!: cSUP_least intro: cSUP_upper2 simp: bdd2 bdd)\n  moreover have \"(\\<Squnion>x\\<in>A. \\<Squnion>z\\<in>B x. f z) \\<le> (\\<Squnion> z \\<in> \\<Union>x\\<in>A. B x. f z)\"\n    using assms by (fastforce simp add: intro!: cSUP_least intro: cSUP_upper simp: image_UN bdd_UN)\n  ultimately show ?thesis\n    by (rule order_antisym)\nqed\n\nlemma cINF_UNION:\n  fixes f :: \"_ \\<Rightarrow> 'b::conditionally_complete_lattice\"\n  assumes ne: \"A \\<noteq> {}\" \"\\<And>x. x \\<in> A \\<Longrightarrow> B(x) \\<noteq> {}\"\n      and bdd_UN: \"bdd_below (\\<Union>x\\<in>A. f ` B x)\"\n  shows \"(\\<Sqinter>z \\<in> \\<Union>x\\<in>A. B x. f z) = (\\<Sqinter>x\\<in>A. \\<Sqinter>z\\<in>B x. f z)\"\nproof -\n  have bdd: \"\\<And>x. x \\<in> A \\<Longrightarrow> bdd_below (f ` B x)\"\n    using bdd_UN by (meson UN_upper bdd_below_mono)\n  obtain M where \"\\<And>x y. x \\<in> A \\<Longrightarrow> y \\<in> B(x) \\<Longrightarrow> f y \\<ge> M\"\n    using bdd_UN by (auto simp: bdd_below_def)\n  then have bdd2: \"bdd_below ((\\<lambda>x. \\<Sqinter>z\\<in>B x. f z) ` A)\"\n    unfolding bdd_below_def by (force simp: bdd le_cINF_iff ne(2))\n  have \"(\\<Sqinter>z \\<in> \\<Union>x\\<in>A. B x. f z) \\<le> (\\<Sqinter>x\\<in>A. \\<Sqinter>z\\<in>B x. f z)\"\n    using assms by (fastforce simp add: intro!: cINF_greatest intro: cINF_lower simp: bdd2 bdd)\n  moreover have \"(\\<Sqinter>x\\<in>A. \\<Sqinter>z\\<in>B x. f z) \\<le> (\\<Sqinter>z \\<in> \\<Union>x\\<in>A. B x. f z)\"\n    using assms  by (fastforce simp add: intro!: cINF_greatest intro: cINF_lower2  simp: bdd bdd_UN bdd2)\n  ultimately show ?thesis\n    by (rule order_antisym)\nqed\n\nlemma cSup_abs_le:\n  fixes S :: \"('a::{linordered_idom,conditionally_complete_linorder}) set\"\n  shows \"S \\<noteq> {} \\<Longrightarrow> (\\<And>x. x\\<in>S \\<Longrightarrow> \\<bar>x\\<bar> \\<le> a) \\<Longrightarrow> \\<bar>Sup S\\<bar> \\<le> a\"\n  apply (auto simp add: abs_le_iff intro: cSup_least)\n  by (metis bdd_aboveI cSup_upper neg_le_iff_le order_trans)\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/Conditionally_Complete_Lattices.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8596637648915617, "lm_q2_score": 0.8289388104343892, "lm_q1q2_score": 0.7126086586427596}}
{"text": "(* Title:      A formalisation of the Cocke-Younger-Kasami algorithm\n   Author:     Maksym Bortin <Maksym.Bortin@nicta.com.au>\n*)\n\n\ntheory CYK\nimports Main \nbegin\n\ntext \\<open>The theory is structured as follows. First section deals with modelling\n      of grammars, derivations, and the language semantics. Then the basic \n      properties are proved. Further, CYK is abstractly specified and its \n      underlying recursive relationship proved. The final section contains a \n      prototypical implementation accompanied by a proof of its correctness.\\<close>\n\n\n\n\nsection \"Basic modelling\"\n\nsubsection \"Grammars in Chomsky normal form\"\n\ntext \"A grammar in Chomsky normal form is here simply modelled  \n      by a list of production rules (the type CNG below), each having a non-terminal \n      symbol on the lhs and either two non-terminals or one terminal \n      symbol on the rhs.\"\n\ndatatype ('n, 't) RHS = Branch 'n 'n\n                      | Leaf 't \n\ntype_synonym ('n, 't) CNG = \"('n \\<times> ('n, 't) RHS) list\"\n\ntext \"Abbreviating the list append symbol for better readability\"\nabbreviation list_append :: \"'a list \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" (infixr \"\\<cdot>\" 65)\nwhere \"xs \\<cdot> ys \\<equiv> xs @ ys\"\n\n\nsubsection \"Derivation by grammars\"\n\ntext\\<open>A \\emph{word form} (or sentential form) may be built of both non-terminal and terminal \n       symbols, as opposed to a \\emph{word} that contains only terminals. By the usage of disjoint \n       union, non-terminals are injected into a word form by @{term \"Inl\"} whereas terminals -- \n       by @{term \"Inr\"}.\\<close>\ntype_synonym ('n, 't) word_form = \"('n + 't) list\"\ntype_synonym 't word = \"'t list\"\n\n\ntext \"A single step derivation relation on word forms is induced by a grammar in the standard way,\n      replacing a non-terminal within a word form in accordance to the production rules.\"\ndefinition DSTEP :: \"('n, 't) CNG \\<Rightarrow> (('n, 't) word_form \\<times> ('n, 't) word_form) set\"\nwhere \"DSTEP G = {(l \\<cdot> [Inl N] \\<cdot> r, x) | l N r rhs x. (N, rhs) \\<in> set G \\<and> \n                                     (case rhs of\n                                       Branch A B \\<Rightarrow> x = l \\<cdot> [Inl A, Inl B] \\<cdot> r\n                                     | Leaf t \\<Rightarrow> x = l \\<cdot> [Inr t] \\<cdot> r)}\"\n\nabbreviation DSTEP'  :: \"('n, 't) word_form \\<Rightarrow> ('n, 't) CNG \\<Rightarrow> ('n, 't) word_form \\<Rightarrow> bool\" (\"_ -_\\<rightarrow> _\" [60, 61, 60] 61) \nwhere \"w -G\\<rightarrow> w' \\<equiv> (w, w') \\<in> DSTEP G\"\n\nabbreviation DSTEP_reflc  :: \"('n, 't) word_form \\<Rightarrow> ('n, 't) CNG \\<Rightarrow> ('n, 't) word_form \\<Rightarrow> bool\" (\"_ -_\\<rightarrow>\\<^sup>= _\" [60, 61, 60] 61) \nwhere \"w -G\\<rightarrow>\\<^sup>= w' \\<equiv> (w, w') \\<in> (DSTEP G)\\<^sup>=\"\n\nabbreviation DSTEP_transc  :: \"('n, 't) word_form \\<Rightarrow> ('n, 't) CNG \\<Rightarrow> ('n, 't) word_form \\<Rightarrow> bool\" (\"_ -_\\<rightarrow>\\<^sup>+ _\" [60, 61, 60] 61) \nwhere \"w -G\\<rightarrow>\\<^sup>+ w' \\<equiv> (w, w') \\<in> (DSTEP G)\\<^sup>+\"\n\n\nabbreviation DSTEP_rtransc  :: \"('n, 't) word_form \\<Rightarrow> ('n, 't) CNG \\<Rightarrow> ('n, 't) word_form \\<Rightarrow> bool\" (\"_ -_\\<rightarrow>\\<^sup>* _\" [60, 61, 60] 61) \nwhere \"w -G\\<rightarrow>\\<^sup>* w' \\<equiv> (w, w') \\<in> (DSTEP G)\\<^sup>*\"\n\n\n\n\nsubsection \"The generated language semantics\"\n\ntext \"The language generated by a grammar from a non-terminal symbol \n      comprises all words that can be derived from the non-terminal \n      in one or more steps.\n      Notice that by the presented grammar modelling, languages containing \n      the empty word cannot be generated. Hence in rare situations when such \n      languages are required, the empty word case should be treated separately.\"\ndefinition Lang :: \"('n, 't) CNG \\<Rightarrow> 'n \\<Rightarrow> 't word set\"\nwhere \"Lang G S = {w. [Inl S] -G\\<rightarrow>\\<^sup>+ map Inr w }\" \n\n\ntext\\<open>So, for instance, a grammar generating the language $a^nb^n$  \n       from the non-terminal @{term \"''S''\"} might look as follows.\\<close>\ndefinition \"G_anbn = \n[(''S'', Branch ''A'' ''T''),\n (''S'', Branch ''A'' ''B''),\n (''T'', Branch ''S'' ''B''),\n (''A'', Leaf ''a''),\n (''B'', Leaf ''b'')]\"\n\ntext\\<open>Now the term @{term \"Lang G_anbn ''S''\"} denotes the set of words of\n       the form $a^nb^n$ with $n > 0$. This is intuitively clear, but not \n       straight forward to show, and a lengthy proof for that is out of scope.\\<close>\n\n\n\nsection \"Basic properties\"\n\n\nlemma prod_into_DSTEP1 :\n\"(S, Branch A B) \\<in> set G \\<Longrightarrow>\n L \\<cdot> [Inl S] \\<cdot> R -G\\<rightarrow> L \\<cdot> [Inl A, Inl B] \\<cdot> R\"\nby(simp add: DSTEP_def, rule_tac x=\"L\" in exI, force)\n\n\nlemma prod_into_DSTEP2 :\n\"(S, Leaf a) \\<in> set G \\<Longrightarrow>\n L \\<cdot> [Inl S] \\<cdot> R -G\\<rightarrow> L \\<cdot> [Inr a] \\<cdot> R\"\nby(simp add: DSTEP_def, rule_tac x=\"L\" in exI, force)\n\n\n\n\nlemma DSTEP_D :\n\"s -G\\<rightarrow> t \\<Longrightarrow> \n \\<exists>L N R rhs. s = L \\<cdot> [Inl N] \\<cdot> R \\<and> (N, rhs) \\<in> set G \\<and> \n (\\<forall>A B. rhs = Branch A B \\<longrightarrow> t = L \\<cdot> [Inl A, Inl B] \\<cdot> R) \\<and>\n (\\<forall>x. rhs = Leaf x \\<longrightarrow> t = L \\<cdot> [Inr x] \\<cdot> R)\"\nby(unfold DSTEP_def, clarsimp, simp split: RHS.split_asm, blast+)\n\n\nlemma DSTEP_append :\nassumes a: \"s -G\\<rightarrow> t\"\nshows \"L  \\<cdot>  s  \\<cdot>  R -G\\<rightarrow> L  \\<cdot>  t  \\<cdot>  R\"\nproof -\n from a have \"\\<exists>l N r rhs. s = l \\<cdot> [Inl N] \\<cdot> r \\<and> (N, rhs) \\<in> set G \\<and> \n                         (\\<forall>A B. rhs = Branch A B \\<longrightarrow> t = l \\<cdot> [Inl A, Inl B] \\<cdot> r) \\<and>\n                         (\\<forall>x. rhs = Leaf x \\<longrightarrow> t = l \\<cdot> [Inr x] \\<cdot> r)\" (is \"\\<exists>l N r rhs. ?P l N r rhs\")\n by(rule DSTEP_D)\n then obtain l N r rhs where \"?P l N r rhs\" by blast\n thus ?thesis\n by(simp add: DSTEP_def, rule_tac x=\"L \\<cdot> l\" in exI,\n    rule_tac x=N in exI, rule_tac x=\"r \\<cdot> R\" in exI,\n    simp, rule_tac x=rhs in exI, simp split: RHS.split)\nqed\n  \n\n\nlemma DSTEP_star_mono :\n\"s -G\\<rightarrow>\\<^sup>* t \\<Longrightarrow> length s \\<le> length t\"\nproof(erule rtrancl_induct, simp)\n fix t u \n assume \"s -G\\<rightarrow>\\<^sup>* t\"\n assume a: \"t -G\\<rightarrow> u\"\n assume b: \"length s \\<le> length t\"\n show \"length s \\<le> length u\"\n proof -\n  from a have \"\\<exists>L N R rhs. t = L \\<cdot> [Inl N] \\<cdot> R \\<and> (N, rhs) \\<in> set G \\<and> \n                          (\\<forall>A B. rhs = Branch A B \\<longrightarrow> u = L \\<cdot> [Inl A, Inl B] \\<cdot> R) \\<and>\n                          (\\<forall>x. rhs = Leaf x \\<longrightarrow> u = L \\<cdot> [Inr x] \\<cdot> R)\" (is \"\\<exists>L N R rhs. ?P L N R rhs\")\n  by(rule DSTEP_D)\n  then obtain L N R rhs where \"?P L N R rhs\" by blast\n  with b show ?thesis\n  by(case_tac rhs, clarsimp+)\n qed\nqed\n\n\nlemma DSTEP_comp :\nassumes a: \"l \\<cdot> r -G\\<rightarrow> t\" \nshows \"\\<exists>l' r'. l -G\\<rightarrow>\\<^sup>= l' \\<and> r -G\\<rightarrow>\\<^sup>= r' \\<and> t = l' \\<cdot> r'\"\nproof -\n from a have \"\\<exists>L N R rhs. l \\<cdot> r = L \\<cdot> [Inl N] \\<cdot> R \\<and> (N, rhs) \\<in> set G \\<and> \n                         (\\<forall>A B. rhs = Branch A B \\<longrightarrow> t = L \\<cdot> [Inl A, Inl B] \\<cdot> R) \\<and>\n                        (\\<forall>x. rhs = Leaf x \\<longrightarrow> t = L \\<cdot> [Inr x] \\<cdot> R)\" (is \"\\<exists>L N R rhs. ?T L N R rhs\")\n by(rule DSTEP_D)\n then obtain L N R rhs where b: \"?T L N R rhs\" by blast\n hence \"l \\<cdot> r = L \\<cdot> Inl N # R\" by simp\n hence \"\\<exists>u. (l = L \\<cdot> u \\<and> u \\<cdot> r = Inl N # R) \\<or> (l \\<cdot> u = L \\<and> r = u \\<cdot> Inl N # R)\" by(rule append_eq_append_conv2[THEN iffD1])\n then obtain xs where c: \"l = L \\<cdot> xs \\<and> xs \\<cdot> r = Inl N # R \\<or> l \\<cdot> xs = L \\<and> r = xs  \\<cdot>  Inl N # R\" (is \"?C1 \\<or> ?C2\") by blast\n show ?thesis\n proof(cases rhs)\n    case (Leaf x)\n    with b have d: \"t = L \\<cdot> [Inr x] \\<cdot> R \\<and> (N, Leaf x) \\<in> set G\" by simp\n    from c show ?thesis\n    proof\n     assume e: \"?C1\"\n     show ?thesis\n     proof(cases xs)\n      case Nil with d and e show ?thesis\n      by(clarsimp, rule_tac x=L in exI, simp add: DSTEP_def, simp split: RHS.split, blast)\n     next\n      case (Cons z zs) with d and e show ?thesis\n      by(rule_tac x=\"L \\<cdot> Inr x # zs\" in exI, clarsimp, simp add: DSTEP_def, simp split: RHS.split, blast)\n     qed\n    next\n     assume e: \"?C2\"\n     show ?thesis\n     proof(cases xs)\n      case Nil with d and e show ?thesis\n      by(rule_tac x=L in exI, clarsimp, simp add: DSTEP_def, simp split: RHS.split, blast)\n     next\n      case (Cons z zs) with d and e show ?thesis\n      by(rule_tac x=\"l\" in exI, clarsimp, simp add: DSTEP_def, simp split: RHS.split, \n         rule_tac x=\"z#zs\" in exI, rule_tac x=N in exI, rule_tac x=R in exI, simp, rule_tac x=\"Leaf x\" in exI, simp)\n     qed\n    qed\n next\n    case (Branch A B)\n    with b have d: \"t = L \\<cdot> [Inl A, Inl B] \\<cdot> R \\<and> (N, Branch A B) \\<in> set G\" by simp\n    from c show ?thesis\n    proof\n     assume e: \"?C1\"\n     show ?thesis\n     proof(cases xs)\n      case Nil with d and e show ?thesis\n      by(clarsimp, rule_tac x=L in exI, simp add: DSTEP_def, simp split: RHS.split, blast)\n     next\n      case (Cons z zs) with d and e show ?thesis\n      by(rule_tac x=\"L \\<cdot> [Inl A, Inl B] \\<cdot> zs\" in exI, clarsimp, simp add: DSTEP_def, simp split: RHS.split, blast)\n     qed\n    next\n     assume e: \"?C2\"\n     show ?thesis\n     proof(cases xs)\n      case Nil with d and e show ?thesis\n      by(rule_tac x=L in exI, clarsimp, simp add: DSTEP_def, simp split: RHS.split, blast)\n     next\n      case (Cons z zs) with d and e show ?thesis\n      by(rule_tac x=\"l\" in exI, clarsimp, simp add: DSTEP_def, simp split: RHS.split, \n         rule_tac x=\"z#zs\" in exI, rule_tac x=N in exI, rule_tac x=R in exI, simp, rule_tac x=\"Branch A B\" in exI, simp)\n     qed\n   qed\n qed\nqed\n\n\n\n\ntheorem DSTEP_star_comp1 :\nassumes A: \"l \\<cdot> r -G\\<rightarrow>\\<^sup>* t\" \nshows \"\\<exists>l' r'. l -G\\<rightarrow>\\<^sup>* l' \\<and> r -G\\<rightarrow>\\<^sup>* r' \\<and> t = l' \\<cdot> r'\"\nproof -\n have \"\\<And>s. s -G\\<rightarrow>\\<^sup>* t \\<Longrightarrow> \n       \\<forall>l r. s = l \\<cdot> r \\<longrightarrow> (\\<exists>l' r'. l -G\\<rightarrow>\\<^sup>* l' \\<and> r -G\\<rightarrow>\\<^sup>* r' \\<and> t = l' \\<cdot> r')\" (is \"\\<And>s. ?P s t \\<Longrightarrow> ?Q s t\")\n proof(erule rtrancl_induct, force)\n  fix s t u\n  assume \"?P s t\"\n  assume a: \"t -G\\<rightarrow> u\"\n  assume b: \"?Q s t\"\n  show \"?Q s u\"\n  proof(clarify)\n   fix l r\n   assume \"s = l \\<cdot> r\"\n   with b have \"\\<exists>l' r'. l -G\\<rightarrow>\\<^sup>* l' \\<and> r -G\\<rightarrow>\\<^sup>* r' \\<and> t = l' \\<cdot> r'\" by simp\n   then obtain l' r' where c: \"l -G\\<rightarrow>\\<^sup>* l' \\<and> r -G\\<rightarrow>\\<^sup>* r' \\<and> t = l' \\<cdot> r'\" by blast\n   with a have \"l' \\<cdot> r' -G\\<rightarrow> u\" by simp\n   hence \"\\<exists>l'' r''. l' -G\\<rightarrow>\\<^sup>=  l'' \\<and> r' -G\\<rightarrow>\\<^sup>= r'' \\<and> u = l'' \\<cdot> r''\" by(rule DSTEP_comp)\n   then obtain l'' r'' where \"l' -G\\<rightarrow>\\<^sup>=  l'' \\<and> r' -G\\<rightarrow>\\<^sup>= r'' \\<and> u = l'' \\<cdot> r''\" by blast\n   hence \"l' -G\\<rightarrow>\\<^sup>* l'' \\<and> r' -G\\<rightarrow>\\<^sup>* r'' \\<and> u = l'' \\<cdot> r''\" by blast\n   with c show \"\\<exists>l' r'. l -G\\<rightarrow>\\<^sup>* l' \\<and> r -G\\<rightarrow>\\<^sup>* r' \\<and> u = l' \\<cdot> r'\" \n   by(rule_tac x=l'' in exI, rule_tac x=r'' in exI, force)\n  qed\n qed\nwith A show ?thesis by force\nqed\n\n\n\ntheorem DSTEP_star_comp2 :\nassumes A: \"l -G\\<rightarrow>\\<^sup>* l'\" \n    and B: \"r -G\\<rightarrow>\\<^sup>* r'\"\nshows \"l \\<cdot> r -G\\<rightarrow>\\<^sup>* l' \\<cdot> r'\"\nproof -\n have \"l -G\\<rightarrow>\\<^sup>* l' \\<Longrightarrow> \n       \\<forall>r r'. r -G\\<rightarrow>\\<^sup>* r' \\<longrightarrow> l \\<cdot> r -G\\<rightarrow>\\<^sup>* l' \\<cdot> r'\" (is \"?P l l' \\<Longrightarrow> ?Q l l'\")\n proof(erule rtrancl_induct)\n  show \"?Q l l\"\n  proof(clarify, erule rtrancl_induct, simp)\n   fix r s t\n   assume a: \"s -G\\<rightarrow> t\"\n   assume b: \"l \\<cdot> r -G\\<rightarrow>\\<^sup>* l \\<cdot> s\"\n   show \"l \\<cdot> r -G\\<rightarrow>\\<^sup>* l \\<cdot> t\"\n   proof -\n    from a have \"l \\<cdot> s -G\\<rightarrow> l \\<cdot> t\" by(drule_tac L=l and R=\"[]\" in DSTEP_append, simp)\n    with b show ?thesis by simp\n   qed\n  qed\n next\n   fix s t\n   assume a: \"s -G\\<rightarrow> t\"\n   assume b: \"?Q l s\"\n   show \"?Q l t\"\n   proof(clarsimp)\n    fix r r'\n    assume \"r -G\\<rightarrow>\\<^sup>* r'\"\n    with b have c: \"l \\<cdot> r -G\\<rightarrow>\\<^sup>* s \\<cdot> r'\" by simp\n    from a have \"s \\<cdot> r' -G\\<rightarrow> t \\<cdot> r'\" by(drule_tac L=\"[]\" and R=r' in DSTEP_append, simp)\n    with c show \"l \\<cdot> r -G\\<rightarrow>\\<^sup>* t \\<cdot> r'\" by simp\n   qed\n  qed\n with A and B show ?thesis by simp\nqed\n   \n\n\nlemma DSTEP_trancl_term :\nassumes A: \"[Inl S] -G\\<rightarrow>\\<^sup>+ t\"\n    and B: \"Inr x \\<in> set t\" \n shows \"\\<exists>N. (N, Leaf x) \\<in> set G\"\nproof -\n have \"[Inl S] -G\\<rightarrow>\\<^sup>+ t \\<Longrightarrow> \n       \\<forall>x. Inr x \\<in> set t \\<longrightarrow> (\\<exists>N. (N, Leaf x) \\<in> set G)\" (is \"?P t \\<Longrightarrow> ?Q t\")\n proof(erule trancl_induct)\n  fix t \n  assume a: \"[Inl S] -G\\<rightarrow> t\"\n  show \"?Q t\"\n  proof -\n   from a have \"\\<exists>rhs. (S, rhs) \\<in> set G \\<and> \n                      (\\<forall>A B. rhs = Branch A B \\<longrightarrow> t = [Inl A, Inl B]) \\<and>\n                      (\\<forall>x. rhs = Leaf x \\<longrightarrow> t = [Inr x])\" (is \"\\<exists>rhs. ?P rhs\")\n   by(simp add: DSTEP_def, clarsimp, simp split: RHS.split_asm, case_tac l, force, simp,\n      clarsimp, simp split: RHS.split_asm, case_tac l, force, simp)\n   then obtain rhs where \"?P rhs\" by blast\n   thus ?thesis\n   by(case_tac rhs, clarsimp, force)\n  qed\n next\n  fix s t\n  assume a: \"s -G\\<rightarrow> t\"\n  assume b: \"?Q s\"\n  show \"?Q t\"\n  proof -\n   from a have \"\\<exists>L N R rhs. s = L \\<cdot> [Inl N] \\<cdot> R \\<and> (N, rhs) \\<in> set G \\<and> \n                         (\\<forall>A B. rhs = Branch A B \\<longrightarrow> t = L \\<cdot> [Inl A, Inl B] \\<cdot> R) \\<and>\n                         (\\<forall>x. rhs = Leaf x \\<longrightarrow> t = L \\<cdot> [Inr x] \\<cdot> R)\" (is \"\\<exists>L N R rhs. ?P L N R rhs\")\n   by(rule DSTEP_D)\n   then obtain L N R rhs where \"?P L N R rhs\" by blast\n   with b show ?thesis\n   by(case_tac rhs, clarsimp, force)\n  qed\n qed\n with A and B show ?thesis by simp\nqed\n\n\n\n\nsubsection \"Properties of generated languages\"\n\n\nlemma Lang_no_Nil :\n\"w \\<in> Lang G S \\<Longrightarrow> w \\<noteq> []\"\nby(simp add: Lang_def, drule trancl_into_rtrancl, drule DSTEP_star_mono, force)\n\n\nlemma Lang_rtrancl_eq :\n\"(w \\<in> Lang G S) = [Inl S] -G\\<rightarrow>\\<^sup>* map Inr w\"          (is \"?L = (?p \\<in> ?R\\<^sup>*)\")\nproof(simp add: Lang_def, rule iffI, erule trancl_into_rtrancl)\n assume \"?p \\<in> ?R\\<^sup>*\"\n hence \"?p \\<in> (?R\\<^sup>+)\\<^sup>=\" by(subst rtrancl_trancl_reflcl[THEN sym], assumption)\n hence \"[Inl S] = map Inr w \\<or> ?p \\<in> ?R\\<^sup>+\" by force\n thus \"?p \\<in> ?R\\<^sup>+\" by(case_tac w, simp_all)\nqed\n \n\n\n\nlemma Lang_term :\n\"w \\<in> Lang G S \\<Longrightarrow> \n \\<forall>x \\<in> set w. \\<exists>N. (N, Leaf x) \\<in> set G\"\nby(clarsimp simp add: Lang_def, drule DSTEP_trancl_term, \n   simp, erule imageI, assumption)\n\n\n\n\nlemma Lang_eq1 :\n\"([x] \\<in> Lang G S) = ((S, Leaf x) \\<in> set G)\"\nproof(simp add: Lang_def, rule iffI, subst (asm) trancl_unfold_left, clarsimp)\n fix t\n assume a: \"[Inl S] -G\\<rightarrow> t\"\n assume b: \"t -G\\<rightarrow>\\<^sup>* [Inr x]\"\n note DSTEP_star_mono[OF b, simplified]\n hence c: \"length t \\<le> 1\" by simp\n have \"\\<exists>z. t = [z]\"\n proof(cases t)\n  assume \"t = []\"\n  with b have d: \"[] -G\\<rightarrow>\\<^sup>* [Inr x]\" by simp\n  have \"\\<And>s. ([], s) \\<in> (DSTEP G)\\<^sup>* \\<Longrightarrow> s = []\"\n  by(erule rtrancl_induct, simp_all, drule DSTEP_D, clarsimp)\n  note this[OF d]\n  thus ?thesis by simp\n next\n  fix z zs\n  assume \"t = z#zs\"\n  with c show ?thesis by force\n qed\n with a have \"\\<exists>z. (S, Leaf z) \\<in> set G \\<and> t = [Inr z]\"\n by(clarsimp simp add: DSTEP_def, simp split: RHS.split_asm, case_tac l, simp_all) \n with b show \"(S, Leaf x) \\<in> set G\"\n proof(clarsimp)\n  fix z\n  assume c: \"(S, Leaf z) \\<in> set G\"\n  assume \"[Inr z] -G\\<rightarrow>\\<^sup>* [Inr x]\"\n  hence \"([Inr z], [Inr x]) \\<in> ((DSTEP G)\\<^sup>+)\\<^sup>=\" by simp\n  hence \"[Inr z] = [Inr x] \\<or> [Inr z] -G\\<rightarrow>\\<^sup>+ [Inr x]\" by force\n  hence \"x = z\"\n  proof\n   assume \"[Inr z] = [Inr x]\" thus ?thesis by simp\n  next\n   assume \"[Inr z] -G\\<rightarrow>\\<^sup>+ [Inr x]\"\n   hence \"\\<exists>u. [Inr z] -G\\<rightarrow> u \\<and> u -G\\<rightarrow>\\<^sup>* [Inr x]\" by(subst (asm) trancl_unfold_left, force)\n   then obtain u where \"[Inr z] -G\\<rightarrow> u\" by blast\n   thus ?thesis by(clarsimp simp add: DSTEP_def, case_tac l, simp_all)\n  qed\n  with c show ?thesis by simp\n qed\nnext\n assume a: \"(S, Leaf x) \\<in> set G\"\n show \"[Inl S] -G\\<rightarrow>\\<^sup>+ [Inr x]\"\n by(rule r_into_trancl, simp add: DSTEP_def, rule_tac x=\"[]\" in exI,\n    rule_tac x=\"S\" in exI, rule_tac x=\"[]\" in exI, simp, rule_tac x=\"Leaf x\" in exI,\n    simp add: a)\nqed\n\n\n\ntheorem Lang_eq2 :\n\"(w \\<in> Lang G S \\<and> 1 < length w) = \n (\\<exists>A B. (S, Branch A B) \\<in> set G \\<and> (\\<exists>l r. w = l \\<cdot> r \\<and> l \\<in> Lang G A \\<and> r \\<in> Lang G B))\"  \n(is \"?L = ?R\")\nproof(rule iffI, clarify, subst (asm) Lang_def, simp, subst (asm) trancl_unfold_left, clarsimp)\n  have map_Inr_split : \"\\<And>xs. \\<forall>zs w. map Inr w = xs \\<cdot> zs \\<longrightarrow> \n                       (\\<exists>u v. w = u \\<cdot> v \\<and> xs = map Inr u \\<and> zs = map Inr v)\" \n  by(induct_tac xs, simp, force)\n  fix t\n  assume a: \"Suc 0 < length w\"\n  assume b: \"[Inl S] -G\\<rightarrow> t\"\n  assume c: \"t -G\\<rightarrow>\\<^sup>* map Inr w\"\n  from b have  \"\\<exists>A B. (S, Branch A B) \\<in> set G \\<and> t = [Inl A, Inl B]\"\n  proof(simp add: DSTEP_def, clarify, case_tac l, simp_all, simp split: RHS.split_asm, clarify)\n   fix x\n   assume \"t = [Inr x]\"\n   with c have d: \"[Inr x] -G\\<rightarrow>\\<^sup>* map Inr w\"by simp\n   have \"\\<And>x s. [Inr x] -G\\<rightarrow>\\<^sup>* s \\<Longrightarrow> s = [Inr x]\"\n   by(erule rtrancl_induct, simp_all, drule DSTEP_D, clarsimp, case_tac L, simp_all)\n   note this[OF d]\n   hence \"w = [x]\" by(case_tac w, simp_all)\n   with a show \"False\" by simp\n  qed\n  then obtain A B where d: \"(S, Branch A B) \\<in> set G \\<and> t = [Inl A, Inl B]\" by blast\n  with c have e: \"[Inl A] \\<cdot> [Inl B] -G\\<rightarrow>\\<^sup>* map Inr w\" by simp\n  note DSTEP_star_comp1[OF e]\n  then obtain l' r' where e: \"[Inl A] -G\\<rightarrow>\\<^sup>* l' \\<and> [Inl B] -G\\<rightarrow>\\<^sup>* r' \\<and> \n                              map Inr w = l'  \\<cdot>  r'\" by blast \n  note map_Inr_split[rule_format, OF e[THEN conjunct2, THEN conjunct2]]\n  then obtain u v where f: \"w = u \\<cdot> v \\<and> l' = map Inr u \\<and> r' = map Inr v\" by blast\n  with e have g: \"[Inl A] -G\\<rightarrow>\\<^sup>* map Inr u \\<and> [Inl B] -G\\<rightarrow>\\<^sup>* map Inr v\" by simp\n  show \"?R\"\n  by(rule_tac x=A in exI, rule_tac x=B in exI, simp add: d,\n     rule_tac x=u in exI, rule_tac x=v in exI, simp add: f,\n     (subst Lang_rtrancl_eq)+, rule g)\n next\n  assume \"?R\" \n  then obtain A B l r where a: \"(S, Branch A B) \\<in> set G \\<and> w = l \\<cdot> r \\<and> l \\<in> Lang G A \\<and> r \\<in> Lang G B\" by blast\n  have \"[Inl A] \\<cdot> [Inl B] -G\\<rightarrow>\\<^sup>* map Inr l \\<cdot> map Inr r\"  \n  by(rule DSTEP_star_comp2, subst Lang_rtrancl_eq[THEN sym], simp add: a,\n     subst Lang_rtrancl_eq[THEN sym], simp add: a)\n  hence b: \"[Inl A] \\<cdot> [Inl B] -G\\<rightarrow>\\<^sup>* map Inr w\" by(simp add: a)\n  have c: \"w \\<in> Lang G S\" \n  by(simp add: Lang_def, subst trancl_unfold_left, rule_tac b=\"[Inl A] \\<cdot> [Inl B]\" in relcompI,\n     simp add: DSTEP_def, rule_tac x=\"[]\" in exI, rule_tac x=\"S\" in exI, rule_tac x=\"[]\" in exI,\n     simp, rule_tac x=\"Branch A B\" in exI, simp add:  a[THEN conjunct1], rule b)\n  thus \"?L\"\n  proof    \n   show \"1 < length w\"\n   proof(simp add: a, rule ccontr, drule leI)\n    assume \"length l + length r \\<le> Suc 0\"\n    hence \"l = [] \\<or> r = []\" by(case_tac l, simp_all)\n    thus \"False\"\n    proof\n     assume \"l = []\" \n     with a have \"[] \\<in> Lang G A\" by simp\n     note Lang_no_Nil[OF this] \n     thus ?thesis by simp \n    next\n     assume \"r = []\" \n     with a have \"[] \\<in> Lang G B\" by simp\n     note Lang_no_Nil[OF this] \n     thus ?thesis by simp \n    qed\n   qed\n qed\nqed\n\n\n\n\nsection \"Abstract specification of CYK\"\n\ntext \"A subword of a word $w$, starting at the position $i$ \n      (first element is at the position $0$) and having the length $j$, is defined as follows.\" \ndefinition \"subword w i j = take j (drop i w)\"\n\ntext \"Thus, to any subword of the given word $w$ CYK assigns all non-terminals\n      from which this subword is derivable by the grammar $G$.\" \ndefinition \"CYK G w i j = {S. subword w i j \\<in> Lang G S}\"\n\n\n\nsubsection \\<open>Properties of @{term \"subword\"}\\<close>\n\nlemma subword_length :\n\"i + j \\<le> length w \\<Longrightarrow> length(subword w i j) = j\"\nby(simp add: subword_def)\n\n\nlemma subword_nth1 :\n\"i + j \\<le> length w \\<Longrightarrow> k < j \\<Longrightarrow> \n(subword w i j)!k = w!(i + k)\"\nby(simp add: subword_def)\n\n\nlemma subword_nth2 :\nassumes A: \"i + 1 \\<le> length w\" \nshows \"subword w i 1 = [w!i]\"\nproof -\n note subword_length[OF A]\n hence \"\\<exists>x. subword w i 1 = [x]\" by(case_tac \"subword w i 1\", simp_all)\n then obtain x where a:\"subword w i 1 = [x]\" by blast\n note subword_nth1[OF A, where k=\"(0 :: nat)\", simplified]\n with a have \"x = w!i\" by simp\n with a show ?thesis by simp\nqed\n\n\n\nlemma subword_self :\n\"subword w 0 (length w) = w\"\nby(simp add: subword_def)\n\n\n\nlemma take_split[rule_format] :\n\"\\<forall>n m. n \\<le> length xs \\<longrightarrow> n \\<le> m \\<longrightarrow>\n take n xs \\<cdot> take (m - n) (drop n xs) = take m xs\"\nby(induct_tac xs, clarsimp+, case_tac n, simp_all, case_tac m, simp_all)\n\n\nlemma subword_split :\n\"i + j \\<le> length w \\<Longrightarrow> 0 < k \\<Longrightarrow> k < j \\<Longrightarrow>\n subword w i j = subword w i k \\<cdot> subword w (i + k) (j - k)\"\nby(simp add: subword_def, subst take_split[where n=k, THEN sym], simp_all,\n   rule_tac f=\"\\<lambda>x. take (j - k) (drop x w)\" in arg_cong, simp)\n\n\nlemma subword_split2 :\nassumes A: \"subword w i j = l \\<cdot> r\"\n    and B: \"i + j \\<le> length w\"\n    and C: \"0 < length l\"\n    and D: \"0 < length r\"\nshows \"l = subword w i (length l) \\<and> r = subword w (i + length l) (j - length l)\"\nproof -\n have a: \"length(subword w i j) = j\" by(rule subword_length, rule B)\n note arg_cong[where f=length, OF A]\n with a and D have b: \"length l < j\" by force\n with B have c: \"i + length l \\<le> length w\" by force\n have \"subword w i j = subword w i (length l) \\<cdot> subword w (i + length l) (j - length l)\" \n  by(rule subword_split, rule B, rule C, rule b)\n with A have d: \"l \\<cdot> r = subword w i (length l) \\<cdot> subword w (i + length l) (j - length l)\" by simp\n show ?thesis\n by(rule append_eq_append_conv[THEN iffD1], subst subword_length, rule c, simp, rule d)\nqed\n \n\n\n\n\nsubsection \\<open>Properties of @{term \"CYK\"}\\<close>\n\n\nlemma CYK_Lang :\n\"(S \\<in> CYK G w 0 (length w)) = (w \\<in> Lang G S)\"\nby(simp add: CYK_def subword_self)\n\n\n\nlemma CYK_eq1 :\n\"i + 1 \\<le> length w \\<Longrightarrow>\n CYK G w i 1 = {S. (S, Leaf (w!i)) \\<in> set G}\"\nby(simp add: CYK_def, subst subword_nth2[simplified], assumption,\n   subst Lang_eq1, rule refl)\n\n\ntheorem CYK_eq2 :\nassumes A: \"i + j \\<le> length w\"\n    and B: \"1 < j\"\nshows \"CYK G w i j = {X | X A B k. (X, Branch A B) \\<in> set G \\<and> A \\<in> CYK G w i k \\<and> B \\<in> CYK G w (i + k) (j - k) \\<and> 1 \\<le> k \\<and> k < j}\"\nproof(rule set_eqI, rule iffI, simp_all add: CYK_def)\n fix X\n assume a: \"subword w i j \\<in> Lang G X\"\n show \"\\<exists>A B. (X, Branch A B) \\<in> set G \\<and> (\\<exists>k. subword w i k \\<in> Lang G A \\<and> subword w (i + k) (j - k) \\<in> Lang G B \\<and> Suc 0 \\<le> k \\<and> k < j)\"\n proof -\n  have b: \"1 < length(subword w i j)\" by(subst subword_length, rule A, rule B)\n  note Lang_eq2[THEN iffD1, OF conjI, OF a b]\n  then obtain A B l r where c: \"(X, Branch A B) \\<in> set G \\<and> subword w i j = l \\<cdot> r \\<and> l \\<in> Lang G A \\<and> r \\<in> Lang G B\" by blast\n  note Lang_no_Nil[OF c[THEN conjunct2, THEN conjunct2, THEN conjunct1]]\n  hence d: \"0 < length l\" by(case_tac l, simp_all)\n  note Lang_no_Nil[OF c[THEN conjunct2, THEN conjunct2, THEN conjunct2]]\n  hence e: \"0 < length r\" by(case_tac r, simp_all)\n  note subword_split2[OF c[THEN conjunct2, THEN conjunct1], OF A, OF d, OF e]\n  with c show ?thesis \n  proof(rule_tac x=A in exI, rule_tac x=B in exI, simp, \n        rule_tac x=\"length l\" in exI, simp)\n   show \"Suc 0 \\<le> length l \\<and> length l < j\" (is \"?A \\<and> ?B\")\n   proof\n    from d show \"?A\" by(case_tac l, simp_all)\n   next\n    note arg_cong[where f=length, OF c[THEN conjunct2, THEN conjunct1], THEN sym]\n    also have \"length(subword w i j) = j\" by(rule subword_length, rule A)\n    finally have \"length l + length r = j\" by simp\n    with e show ?B by force\n   qed\n  qed\n qed\nnext\n fix X\n assume \"\\<exists>A B. (X, Branch A B) \\<in> set G \\<and> (\\<exists>k. subword w i k \\<in> Lang G A \\<and> subword w (i + k) (j - k) \\<in> Lang G B \\<and> Suc 0 \\<le> k \\<and> k < j)\"\n then obtain A B k where a: \"(X, Branch A B) \\<in> set G \\<and> subword w i k \\<in> Lang G A \\<and> subword w (i + k) (j - k) \\<in> Lang G B \\<and> Suc 0 \\<le> k \\<and> k < j\" by blast\n show \"subword w i j \\<in> Lang G X\" \n proof(rule Lang_eq2[THEN iffD2, THEN conjunct1], rule_tac x=A in exI, rule_tac x=B in exI, simp add: a,\n       rule_tac x=\"subword w i k\" in exI, rule_tac x=\"subword w (i + k) (j - k)\" in exI, simp add: a,\n       rule subword_split, rule A)\n  from a show \"0 < k\" by force\n next\n  from a show \"k < j\" by simp\n qed\nqed\n\n\n\nsection \"Implementation\"\n\ntext \"One of the particularly interesting features of CYK implementation \nis that it follows the principles of dynamic programming, constructing a \ntable of solutions for sub-problems in the bottom-up style reusing already \nstored results.\"\n\n\n\nsubsection \"Main cycle\"\n\n\ntext \"This is an auxiliary implementation of the membership test on lists.\"\nfun mem :: \"'a \\<Rightarrow> 'a list \\<Rightarrow> bool\"\nwhere \n\"mem a [] = False\" |\n\"mem a (x#xs) = (x = a \\<or> mem a xs)\"\n\nlemma mem[simp] :\n\"mem x xs = (x \\<in> set xs)\"\nby(induct_tac xs, simp, force)\n\n\n\ntext \"The purpose of the following is to collect non-terminals that appear on the lhs of a production\n      such that the first non-terminal on its rhs appears in the first of two given lists and the second\n      non-terminal -- in the second list.\"\nfun match_prods :: \"('n, 't) CNG \\<Rightarrow> 'n list \\<Rightarrow> 'n list \\<Rightarrow> 'n list\"\nwhere \"match_prods [] ls rs = []\" |\n      \"match_prods ((X, Branch A B)#ps) ls rs = \n          (if mem A ls \\<and> mem B rs then X # match_prods ps ls rs\n           else match_prods ps ls rs)\" |\n      \"match_prods ((X, Leaf a)#ps) ls rs = match_prods ps ls rs\"\n\n\nlemma match_prods :\n\"(X \\<in> set(match_prods G ls rs)) = \n (\\<exists>A \\<in> set ls. \\<exists>B \\<in> set rs. (X, Branch A B) \\<in> set G)\"\nby(induct_tac G, clarsimp+, rename_tac l r ps, case_tac r, force+)\n\n\n\n     \ntext \"The following function is the inner cycle of the algorithm. The parameters $i$ and $j$\n      identify a subword starting at $i$ with the length $j$, whereas $k$ is used to iterate through\n      its splits (which are of course subwords as well) all having the length greater $0$ but less than $j$. \n      The parameter $T$ represents a table containing CYK solutions for those splits.\"\nfunction inner :: \"('n, 't) CNG \\<Rightarrow> (nat \\<times> nat \\<Rightarrow> 'n list) \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> 'n list\"\nwhere \"inner G T i k j = \n(if k < j then match_prods G (T(i, k)) (T(i + k, j - k)) @ inner G T i (k + 1) j\n else [])\"\nby pat_completeness auto\ntermination \nby(relation \"measure(\\<lambda>(a, b, c, d, e). e - d)\", rule wf_measure, simp)\n\n\ndeclare inner.simps[simp del]\n\nlemma inner :\n\"(X \\<in> set(inner G T i k j)) =\n (\\<exists>l. k \\<le> l \\<and> l < j \\<and> X \\<in> set(match_prods G (T(i, l)) (T(i + l, j - l))))\" \n(is \"?L G T i k j = ?R G T i k j\")\nproof(induct_tac G T i k j rule: inner.induct)\n fix G T i k j\n assume a: \"k < j \\<Longrightarrow> ?L G T i (k + 1) j = ?R G T i (k + 1) j\"\n show \"?L G T i k j = ?R G T i k j\"\n proof(case_tac \"k < j\")\n  assume b: \"k < j\" \n  with a have c: \"?L G T i (k + 1) j = ?R G T i (k + 1) j\" by simp\n  show ?thesis\n  proof(subst inner.simps, simp add: b, rule iffI, erule disjE, rule_tac x=k in exI, simp add: b)\n   assume \"X \\<in> set(inner G T i (Suc k) j)\"\n   with c have \"?R G T i (k + 1) j\" by simp\n   thus \"?R G T i k j\" by(clarsimp, rule_tac x=l in exI, simp)\n  next\n   assume \"?R G T i k j\"\n   then obtain l where d: \"k \\<le> l \\<and> l < j \\<and> X \\<in> set(match_prods G (T(i, l)) (T(i + l, j - l)))\" by blast\n   show \"X \\<in> set(match_prods G (T(i, k)) (T(i + k, j - k))) \\<or> ?L G T i (Suc k) j\"\n   proof(case_tac \"Suc k \\<le> l\", rule disjI2, subst c[simplified], rule_tac x=l in exI, simp add: d, \n         rule disjI1)\n    assume \"\\<not> Suc k \\<le> l\"\n    with d have \"l = k\" by force\n    with d show \"X \\<in> set(match_prods G (T(i, k)) (T(i + k, j - k)))\" by simp\n   qed\n  qed\n next\n  assume \"\\<not> k < j\"\n  thus ?thesis by(subst inner.simps, simp)\n qed\nqed\n\n   \n   \n\ntext\\<open>Now the main part of the algorithm just iterates through all subwords up to the given length $len$,\n       calls @{term \"inner\"} on these, and stores the results in the table $T$. The length $j$ is supposed to \n       be greater than $1$ -- the subwords of length $1$ will be handled in the initialisation phase below.\\<close> \nfunction main :: \"('n, 't) CNG \\<Rightarrow> (nat \\<times> nat \\<Rightarrow> 'n list) \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> (nat \\<times> nat \\<Rightarrow> 'n list)\"\nwhere \"main G T len i j = (let T' = T((i, j) := inner G T i 1 j) in\n                            if i + j < len then main G T' len (i + 1) j\n                            else if j < len then main G T' len 0 (j + 1)\n                                 else T')\"\nby pat_completeness auto\ntermination \nby(relation \"inv_image (less_than <*lex*> less_than) (\\<lambda>(a, b, c, d, e). (c - e, c - (d + e)))\", rule wf_inv_image, rule wf_lex_prod, (rule wf_less_than)+, simp_all)\n\n\n\ndeclare main.simps[simp del]\n\n\nlemma main :\n assumes \"1 < j\"\n     and \"i + j \\<le> length w\"\n     and \"\\<And>i' j'. j' < j \\<Longrightarrow> 1 \\<le> j' \\<Longrightarrow> i' + j' \\<le> length w \\<Longrightarrow> set(T(i', j')) = CYK G w i' j'\"\n     and \"\\<And>i'. i' < i \\<Longrightarrow> i' + j \\<le> length w \\<Longrightarrow> set(T(i', j)) = CYK G w i' j\"\n     and \"1 \\<le> j'\"\n     and \"i' + j' \\<le> length w\"\n shows \"set((main G T (length w) i j)(i', j')) = CYK G w i' j'\"\nproof -\n have \"\\<forall>len T' w. main G T len i j = T' \\<longrightarrow> length w = len \\<longrightarrow> 1 < j \\<longrightarrow> i + j \\<le> len \\<longrightarrow>\n      (\\<forall>j' < j. \\<forall>i'. 1 \\<le> j' \\<longrightarrow> i' + j' \\<le> len \\<longrightarrow> set(T(i', j')) = CYK G w i' j') \\<longrightarrow>\n      (\\<forall>i' < i. i' + j \\<le> len \\<longrightarrow> set(T(i', j)) = CYK G w i' j) \\<longrightarrow>\n      (\\<forall>j' \\<ge> 1. \\<forall>i'. i' + j' \\<le> len \\<longrightarrow> set(T'(i', j')) = CYK G w i' j')\" (is \"\\<forall>len. ?P G T len i j\")\n proof(rule allI, induct_tac G T len i j rule: main.induct, (drule meta_spec, drule meta_mp, rule refl)+, clarify)\n  fix G T i j i' j'\n  fix w :: \"'a list\" \n  assume a: \"i + j < length w \\<Longrightarrow> ?P G (T((i, j) := inner G T i 1 j)) (length w) (i + 1) j\"\n  assume b: \"\\<not> i + j < length w \\<Longrightarrow> j < length w \\<Longrightarrow> ?P G (T((i, j) := inner G T i 1 j)) (length w) 0 (j + 1)\"\n  assume c: \"1 < j\"\n  assume d: \"i + j \\<le> length w\"\n  assume e: \"(1::nat) \\<le> j'\"\n  assume f: \"i' + j' \\<le> length w\"\n  assume g: \"\\<forall>j' < j. \\<forall>i'. 1 \\<le> j' \\<longrightarrow> i' + j' \\<le> length w \\<longrightarrow> set(T(i', j')) = CYK G w i' j'\"\n  assume h: \"\\<forall>i' < i. i' + j \\<le> length w \\<longrightarrow> set(T(i', j)) = CYK G w i' j\"\n\n   have inner: \"set (inner G T i (Suc 0) j) = CYK G w i j\"\n   proof(rule set_eqI, subst inner, subst match_prods, subst CYK_eq2, rule d, rule c, simp)\n    fix X\n    show \"(\\<exists>l\\<ge>Suc 0. l < j \\<and> (\\<exists>A \\<in> set(T(i, l)). \\<exists>B \\<in> set(T(i + l, j - l)). (X, Branch A B) \\<in> set G)) =\n          (\\<exists>A B. (X, Branch A B) \\<in> set G \\<and> (\\<exists>k. A \\<in> CYK G w i k \\<and> B \\<in> CYK G w (i + k) (j - k) \\<and> Suc 0 \\<le> k \\<and> k < j))\" (is \"?L = ?R\")\n    proof\n     assume \"?L\"\n     thus \"?R\"\n     proof(clarsimp, rule_tac x=A in exI, rule_tac x=B in exI, simp, rule_tac x=l in exI, simp)\n      fix l A B\n      assume i: \"Suc 0 \\<le> l\"\n      assume j: \"l < j\"\n      assume k: \"A \\<in> set(T(i, l))\"\n      assume l: \"B \\<in> set(T(i + l, j - l))\"\n      note g[rule_format, where i'=i and j'=l]\n      with d i j have A: \"set(T(i, l)) = CYK G w i l\" by force\n      note g[rule_format, where i'=\"i + l\" and j'=\"j - l\"]\n      with d i j have \"set(T(i + l, j - l)) = CYK G w (i + l) (j - l)\" by force\n      with k l A show \"A \\<in> CYK G w i l \\<and> B \\<in> CYK G w (i + l) (j - l)\" by simp\n     qed\n    next\n     assume \"?R\"\n     thus \"?L\"\n     proof(clarsimp, rule_tac x=k in exI, simp)\n      fix A B k\n      assume i: \"Suc 0 \\<le> k\"\n      assume j: \"k < j\"\n      assume k: \"A \\<in> CYK G w i k\"\n      assume l: \"B \\<in> CYK G w (i + k) (j - k)\"\n      assume m: \"(X, Branch A B) \\<in> set G\"\n      note g[rule_format, where i'=i and j'=k]\n      with d i j have A: \"CYK G w i k = set(T(i, k))\" by force\n      note g[rule_format, where i'=\"i + k\" and j'=\"j - k\"]\n      with d i j have \"CYK G w (i + k) (j - k) = set(T(i + k, j - k))\" by force\n      with k l A have \"A \\<in> set(T(i, k)) \\<and> B \\<in> set(T(i + k, j - k))\" by simp\n      with m show \"\\<exists>A \\<in> set(T(i, k)). \\<exists>B \\<in> set(T(i + k, j - k)). (X, Branch A B) \\<in> set G\" by force\n     qed\n    qed\n   qed  (* inner *)\n\n  show \"set((main G T (length w) i j)(i', j')) = CYK G w i' j'\"\n  proof(case_tac \"i + j = length w\")\n   assume i: \"i + j = length w\"\n   show ?thesis\n   proof(case_tac \"j < length w\")\n    assume j: \"j < length w\"\n    show ?thesis\n    proof(subst main.simps, simp add: Let_def i j, \n          rule b[rule_format, where w=w and i'=i' and j'=j', OF _ _ refl, simplified], \n          simp_all add: inner)\n     from i show \"\\<not> i + j < length w\" by simp\n    next \n     from c show \"0 < j\" by simp\n    next\n     from j show \"Suc j \\<le> length w\" by simp\n    next \n     from e show \"Suc 0 \\<le> j'\" by simp\n    next\n     from f show \"i' + j' \\<le> length w\" by assumption\n    next\n     fix i'' j''\n     assume k: \"j'' < Suc j\"\n     assume l: \"Suc 0 \\<le> j''\"\n     assume m: \"i'' + j'' \\<le> length w\"\n     show \"(i'' = i \\<longrightarrow> j'' \\<noteq> j) \\<longrightarrow> set(T(i'',j'')) = CYK G w i'' j''\"\n     proof(case_tac \"j'' = j\", simp_all, clarify)\n      assume n: \"j'' = j\"\n      assume \"i'' \\<noteq> i\"\n      with i m n have \"i'' < i\" by simp\n      with n m h show \"set(T(i'', j)) = CYK G w i'' j\" by simp\n     next\n      assume \"j'' \\<noteq> j\"\n      with k have \"j'' < j\" by simp\n      with l m g show \"set(T(i'', j'')) = CYK G w i'' j''\" by simp\n     qed\n    qed\n   next\n    assume \"\\<not> j < length w\"\n    with i have j: \"i = 0 \\<and> j = length w\" by simp\n    show ?thesis\n    proof(subst main.simps, simp add: Let_def j, intro conjI, clarify)\n     from j and inner show \"set (inner G T 0 (Suc 0) (length w)) = CYK G w 0 (length w)\" by simp\n    next\n     show \"0 < i' \\<longrightarrow> set(T(i', j')) = CYK G w i' j'\"\n     proof\n      assume \"0 < i'\"\n      with j and f have \"j' < j\" by simp\n      with e g f show \"set(T(i', j')) = CYK G w i' j'\" by simp\n     qed\n    next\n     show \"j' \\<noteq> length w \\<longrightarrow> set(T(i', j')) = CYK G w i' j'\"\n     proof\n      assume \"j' \\<noteq> length w \"\n      with j and f have \"j' < j\" by simp\n      with e g f show \"set(T(i', j')) = CYK G w i' j'\" by simp\n     qed\n    qed\n   qed\n  next\n   assume \"i + j \\<noteq> length w\"\n   with d have i: \"i + j < length w\" by simp\n   show ?thesis\n   proof(subst main.simps, simp add: Let_def i,\n         rule a[rule_format, where w=w and i'=i' and j'=j', OF i, OF refl, simplified])\n    from c show \"Suc 0 < j\" by simp\n   next\n    from i show \"Suc(i + j) \\<le> length w\" by simp\n   next\n    from e show \"Suc 0 \\<le> j'\" by simp\n   next\n    from f show \"i' + j' \\<le> length w\" by assumption\n   next\n    fix i'' j''\n    assume \"j'' < j\"\n    and \"Suc 0 \\<le> j''\"\n    and \"i'' + j'' \\<le> length w\"\n    with g show \"set(T(i'', j'')) = CYK G w i'' j''\" by simp\n   next\n    fix i'' assume j: \"i'' < Suc i\" \n    show \"set(if i'' = i then inner G T i (Suc 0) j else T(i'', j)) = CYK G w i'' j\"\n    proof(simp split: if_split, rule conjI, clarify, rule inner, clarify)\n     assume \"i'' \\<noteq> i\"\n     with j have \"i'' < i\" by simp\n     with d h show \"set(T(i'', j)) = CYK G w i'' j\" by simp\n    qed\n   qed\n  qed\n qed\n with assms show ?thesis by force\nqed\n\n \n\n\n\n\nsubsection \"Initialisation phase\"\n\ntext\\<open>Similarly to @{term \"match_prods\"} above, here we collect non-terminals from which\n       the given terminal symbol can be derived.\\<close> \nfun init_match :: \"('n, 't) CNG \\<Rightarrow> 't \\<Rightarrow> 'n list\"\nwhere \"init_match [] t = []\" |\n      \"init_match ((X, Branch A B)#ps) t = init_match ps t\" |\n      \"init_match ((X, Leaf a)#ps) t = (if a = t then X # init_match ps t\n                                        else init_match ps t)\"\n\n\nlemma init_match :\n\"(X \\<in> set(init_match G a)) = \n ((X, Leaf a) \\<in> set G)\"\nby(induct_tac G a rule: init_match.induct, simp_all)\n\n\ntext \"Representing the empty table.\"\ndefinition \"emptyT = (\\<lambda>(i, j). [])\" \n\ntext \"The following function initialises the empty table for subwords of\n      length $1$, i.e. each symbol occurring in the given word.\"\nfun init' :: \"('n, 't) CNG \\<Rightarrow> 't list \\<Rightarrow> nat \\<Rightarrow> nat \\<times> nat \\<Rightarrow> 'n list\"\nwhere \"init' G [] k = emptyT\" |\n      \"init' G (t#ts) k = (init' G ts (k + 1))((k, 1) := init_match G t)\" \n\n\n\n\n\n\n\n\n\ntext\\<open>The next version of initialization refines @{term \"init'\"} in that\n      it takes additional account of the cases when the given word is \n      empty or contains a terminal symbol that does not have any matching \n      production (that is, @{term \"init_match\"} is an empty list). No initial \n      table is then needed as such words can immediately be rejected.\\<close>  \nfun init :: \"('n, 't) CNG \\<Rightarrow> 't list \\<Rightarrow> nat \\<Rightarrow> (nat \\<times> nat \\<Rightarrow> 'n list) option\"\nwhere \"init G [] k = None\" |\n      \"init G [t] k = (case (init_match G t) of\n                        [] \\<Rightarrow> None\n                      | xs \\<Rightarrow> Some(emptyT((k, 1) := xs)))\" |\n      \"init G (t#ts) k = (case (init_match G t) of\n                           [] \\<Rightarrow> None\n                         | xs \\<Rightarrow> (case (init G ts (k + 1)) of\n                                  None \\<Rightarrow> None\n                                | Some T \\<Rightarrow> Some(T((k, 1) := xs))))\" \n\n\nlemma init1[rule_format] :\n\"\\<forall>T. init G w k = Some T \\<longrightarrow> \n     init' G w k = T\"\nby(induct_tac G w k rule: init.induct, clarsimp+, simp split: list.split_asm, rule ext, clarsimp+,\n   simp split: list.split_asm option.split_asm, rule ext, clarsimp, force)\n\n\nlemma init2 :\n\"(init G w k = None) =\n (w = [] \\<or> (\\<exists>a \\<in> set w. init_match G a = []))\"\nby(induct_tac G w k rule: init.induct, simp, simp split: list.split, \n   simp split: list.split option.split, force)\n\n\n\nsubsection \\<open>The overall procedure\\<close>\n\n\ndefinition \"cyk G S w = (case init G w 0 of\n                          None \\<Rightarrow> False\n                        | Some T \\<Rightarrow> let len = length w in\n                                     if len = 1 then mem S (T(0, 1))\n                                     else let T' = main G T len 0 2 in\n                                            mem S (T'(0, len)))\"\n\n\n\ntheorem cyk :\n\"cyk G S w = (w \\<in> Lang G S)\"\nproof(simp add: cyk_def split: option.split, simp_all add: Let_def,\n      rule conjI, subst init2, simp, rule conjI)\n show \"w = [] \\<longrightarrow> [] \\<notin> Lang G S\" by(clarify, drule Lang_no_Nil, clarify)\nnext\n show \"(\\<exists>x\\<in>set w. init_match G x = []) \\<longrightarrow> w \\<notin> Lang G S\" by(clarify, drule Lang_term, subst (asm) init_match[THEN sym], force)\nnext \n show \"\\<forall>T. init G w 0 = Some T \\<longrightarrow> \n       ((length w = Suc 0 \\<longrightarrow> S \\<in> set(T(0, Suc 0))) \\<and>\n        (length w \\<noteq> Suc 0 \\<longrightarrow> S \\<in> set(main G T (length w) 0 2 (0, length w)))) =\n       (w \\<in> Lang G S)\" (is \"\\<forall>T. ?P T \\<longrightarrow> ?L T = ?R\")\n proof clarify\n  fix T\n  assume a: \"?P T\"\n  hence b: \"init' G w 0 = T\" by(rule init1)\n  note init2[THEN iffD2, OF disjI1]\n  have c: \"w \\<noteq> []\" by(clarify, drule init2[where G=G and k=0, THEN iffD2, OF disjI1], simp add: a)\n  have \"?L (init' G w 0) = ?R\"\n  proof(case_tac \"length w = 1\", simp_all)\n   assume d: \"length w = Suc 0\"   \n   show \"S \\<in> set(init' G w 0 (0, Suc 0)) = ?R\"\n   by(subst init'[simplified], simp add: d, subst CYK_Lang[THEN sym], simp add: d)\n  next\n   assume \"length w \\<noteq> Suc 0\"   \n   with c have \"1 < length w\" by(case_tac w, simp_all)\n   hence d: \"Suc(Suc 0) \\<le> length w\" by simp\n   show \"(S \\<in> set(main G (init' G w 0) (length w) 0 2 (0, length w))) = (w \\<in> Lang G S)\"\n   proof(subst main, simp_all, rule d)\n    fix i' j'\n    assume \"j' < 2\" and \"Suc 0 \\<le> j'\"\n    hence e: \"j' = 1\" by simp\n    assume \"i' + j' \\<le> length w\"\n    with e have f: \"i' + 1 \\<le> length w\" by simp\n    have \"set(init' G w 0 (i', 1)) = CYK G w i' 1\" by(rule init', rule f)\n    with e show \"set(init' G w 0 (i', j')) = CYK G w i' j'\" by simp\n   next\n    from d show \"Suc 0 \\<le> length w\" by simp\n   next\n    show \"(S \\<in> CYK G w 0 (length w)) = (w \\<in> Lang G S)\" by(rule CYK_Lang)\n   qed\n  qed\n  with b show \"?L T = ?R\" by simp\n qed\nqed\n\nvalue [code]\n  \"let G = [(0::int, Branch 1 2), (0, Branch 2 3),\n            (1, Branch 2 1), (1, Leaf ''a''),\n            (2, Branch 3 3), (2, Leaf ''b''),\n            (3, Branch 1 2), (3, Leaf ''a'')]\n  in map (cyk G 0)\n     [[''b'',''a'',''a'',''b'',''a''],\n      [''b'',''a'',''b'',''a'']]\"\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/CYK/CYK.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8596637469145054, "lm_q2_score": 0.8289388083214156, "lm_q1q2_score": 0.7126086419244332}}
{"text": "(*\n    Authors:      Jose Divas\u00f3n\n                  Sebastiaan Joosten\n                  Ren\u00e9 Thiemann\n                  Akihisa Yamada\n*)\nsubsection \\<open>Karatsuba's Multiplication Algorithm for Polynomials\\<close>\ntheory Karatsuba_Multiplication\nimports \n  Polynomial_Interpolation.Missing_Polynomial\nbegin\n\nlemma karatsuba_main_step: fixes f :: \"'a :: comm_ring_1 poly\"\n  assumes f: \"f = monom_mult n f1 + f0\" and g: \"g = monom_mult n g1 + g0\" \n  shows \n    \"monom_mult (n + n) (f1 * g1) + (monom_mult n (f1 * g1 - (f1 - f0) * (g1 - g0) + f0 * g0) + f0 * g0) = f * g\"\n  unfolding assms\n  by (auto simp: field_simps mult_monom monom_mult_def)  \n\nlemma karatsuba_single_sided: fixes f :: \"'a :: comm_ring_1 poly\" \n  assumes \"f = monom_mult n f1 + f0\"\n  shows \"monom_mult n (f1 * g) + f0 * g = f * g\"\n  unfolding assms by (auto simp: field_simps mult_monom monom_mult_def)  \n\n\ndefinition split_at :: \"nat \\<Rightarrow> 'a list \\<Rightarrow> 'a list \\<times> 'a list\" where \n  [code del]: \"split_at n xs = (take n xs, drop n xs)\" \n  \nlemma split_at_code[code]: \n  \"split_at n [] = ([],[])\"\n  \"split_at n (x # xs) = (if n = 0 then ([], x # xs) else case split_at (n-1) xs of (bef,aft)\n    \\<Rightarrow> (x # bef, aft))\"\n  unfolding split_at_def by (force, cases n, auto)\n\nfun coeffs_minus :: \"'a :: ab_group_add list \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where\n  \"coeffs_minus (x # xs) (y # ys) = ((x - y) # coeffs_minus xs ys)\" \n| \"coeffs_minus xs [] = xs\" \n| \"coeffs_minus [] ys = map uminus ys\" \n  \ntext \\<open>The following constant determines at which size we will switch to the standard \n   multiplication algorithm.\\<close>\ndefinition karatsuba_lower_bound where [termination_simp]: \"karatsuba_lower_bound = (7 :: nat)\" \n\nfun karatsuba_main :: \"'a :: comm_ring_1 list \\<Rightarrow> nat \\<Rightarrow> 'a list \\<Rightarrow> nat \\<Rightarrow> 'a poly\" where\n  \"karatsuba_main f n g m = (if n \\<le> karatsuba_lower_bound \\<or> m \\<le> karatsuba_lower_bound then \n    let ff = poly_of_list f in foldr (\\<lambda>a p. smult a ff + pCons 0 p) g 0\n   else let n2 = n div 2 in \n   if m > n2 then (case split_at n2 f of \n   (f0,f1) \\<Rightarrow> case split_at n2 g of\n   (g0,g1) \\<Rightarrow> let \n      p1 = karatsuba_main f1 (n - n2) g1 (m - n2);\n      p2 = karatsuba_main (coeffs_minus f1 f0) n2 (coeffs_minus g1 g0) n2;\n      p3 = karatsuba_main f0 n2 g0 n2 \n      in monom_mult (n2 + n2) p1 + (monom_mult n2 (p1 - p2 + p3) + p3))\n    else case split_at n2 f of\n    (f0,f1) \\<Rightarrow> let \n       p1 = karatsuba_main f1 (n - n2) g m; \n       p2 = karatsuba_main f0 n2 g m\n     in monom_mult n2 p1 + p2)\" \n\ndeclare karatsuba_main.simps[simp del]\n\nlemma poly_of_list_split_at: assumes \"split_at n f = (f0,f1)\" \n  shows \"poly_of_list f = monom_mult n (poly_of_list f1) + poly_of_list f0\"\nproof -\n  from assms have id: \"f1 = drop n f\" \"f0 = take n f\" unfolding split_at_def by auto\n  show ?thesis unfolding id\n  proof (rule poly_eqI)\n    fix i\n    show \"coeff (poly_of_list f) i = \n      coeff (monom_mult n (poly_of_list (drop n f)) + poly_of_list (take n f)) i\" \n      unfolding monom_mult_def coeff_monom_mult coeff_add poly_of_list_def coeff_Poly\n      by (cases \"n \\<le> i\"; cases \"i \\<ge> length f\", auto simp: nth_default_nth nth_default_beyond)\n  qed\nqed\n        \nlemma coeffs_minus: \"poly_of_list (coeffs_minus f1 f0) = poly_of_list f1 - poly_of_list f0\" \nproof (rule poly_eqI, unfold poly_of_list_def coeff_diff coeff_Poly)\n  fix i\n  show \"nth_default 0 (coeffs_minus f1 f0) i = nth_default 0 f1 i - nth_default 0 f0 i\" \n  proof (induct f1 f0 arbitrary: i rule: coeffs_minus.induct)\n    case (1 x xs y ys)\n    thus ?case by (cases i, auto)\n  next\n    case (3 x xs)\n    thus ?case unfolding coeffs_minus.simps\n      by (subst nth_default_map_eq[of uminus 0 0], auto)    \n  qed auto\nqed\n\n\n\n\ndefinition karatsuba_mult_poly :: \"'a :: comm_ring_1 poly \\<Rightarrow> 'a poly \\<Rightarrow> 'a poly\" where\n  \"karatsuba_mult_poly f g = (let ff = coeffs f; gg = coeffs g; n = length ff; m = length gg\n    in (if n \\<le> karatsuba_lower_bound \\<or> m \\<le> karatsuba_lower_bound then if n \\<le> m \n    then foldr (\\<lambda>a p. smult a g + pCons 0 p) ff 0 \n    else foldr (\\<lambda>a p. smult a f + pCons 0 p) gg 0 \n    else if n \\<le> m \n    then karatsuba_main gg m ff n \n    else karatsuba_main ff n gg m))\" \n  \nlemma karatsuba_mult_poly: \"karatsuba_mult_poly f g = f * g\" \nproof -\n  note d = karatsuba_mult_poly_def Let_def \n  let ?len = \"length (coeffs f) \\<le> length (coeffs g)\" \n  show ?thesis (is \"?lhs = ?rhs\")\n  proof (cases \"length (coeffs f) \\<le> karatsuba_lower_bound \\<or> length (coeffs g) \\<le> karatsuba_lower_bound\")\n    case True note outer = this\n    show ?thesis\n    proof (cases ?len)\n      case True\n      with outer have \"?lhs = foldr (\\<lambda>a p. smult a g + pCons 0 p) (coeffs f) 0\" unfolding d by auto\n      also have \"\\<dots> = ?rhs\" unfolding times_poly_def fold_coeffs_def by auto\n      finally show ?thesis .\n    next\n      case False\n      with outer have \"?lhs = foldr (\\<lambda>a p. smult a f + pCons 0 p) (coeffs g) 0\" unfolding d by auto\n      also have \"\\<dots> = g * f\" unfolding times_poly_def fold_coeffs_def by auto\n      also have \"\\<dots> = ?rhs\" by simp\n      finally show ?thesis .\n    qed\n  next\n    case False note outer = this\n    show ?thesis\n    proof (cases ?len)\n      case True   \n      with outer have \"?lhs = karatsuba_main (coeffs g) (length (coeffs g)) (coeffs f) (length (coeffs f))\" \n        unfolding d by auto\n      also have \"\\<dots> = g * f\" unfolding karatsuba_main by auto\n      also have \"\\<dots> = ?rhs\" by auto\n      finally show ?thesis .\n    next\n      case False\n      with outer have \"?lhs = karatsuba_main (coeffs f) (length (coeffs f)) (coeffs g) (length (coeffs g))\" \n        unfolding d by auto\n      also have \"\\<dots> = ?rhs\" unfolding karatsuba_main by auto\n      finally show ?thesis .\n    qed\n  qed\nqed\n\nlemma karatsuba_mult_poly_code_unfold[code_unfold]: \"(*) = karatsuba_mult_poly\" \n  by (intro ext, unfold karatsuba_mult_poly, auto)\n\ntext \\<open>The following declaration will resolve a race-conflict between @{thm karatsuba_mult_poly_code_unfold}\n  and @{thm monom_mult_unfold}.\\<close>\nlemmas karatsuba_monom_mult_code_unfold[code_unfold] = \n  monom_mult_unfold[where f = \"f :: 'a :: comm_ring_1 poly\" for f, unfolded karatsuba_mult_poly_code_unfold]\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/Berlekamp_Zassenhaus/Karatsuba_Multiplication.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8596637361282706, "lm_q2_score": 0.82893881677331, "lm_q1q2_score": 0.7126086402490917}}
{"text": "theory exercises_4\n  imports Main\nbegin\ntext \\<open>Exercise 4.1\\<close>\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\ndefinition \"test_tree1 = Node (Node (Node Tip 1 Tip) 2 (Node Tip 3 Tip)) (4::int) (Node Tip 5 Tip)\"\nfun inord :: \"int tree \\<Rightarrow> int list\" where\n\"inord Tip = []\" |\n\"inord (Node l a r) = (inord l) @ [a] @ (inord r)\"\n(*\nfun inc :: \"int list \\<Rightarrow> bool\" where\n\"inc [] = True\" |\n\"inc [x] = True\" |\n\"inc (x#xs) = (if x>(hd xs) then False else (inc xs))\"\n\nvalue \"inc [(2::int), 3, 5]\"\n*)\nfun ord :: \"int tree \\<Rightarrow> bool\" where\n\"ord t = strict_sorted (inord t)\"\n\nvalue \"ord test_tree1\"\n\nfun rightest :: \"int tree \\<Rightarrow> int\" where\n\"rightest (Node _ a Tip) = a\" |\n\"rightest (Node _ a r) = rightest r\"\n\nfun leftest :: \"int tree \\<Rightarrow> int\" where\n\"leftest (Node Tip a _) = a\" |\n\"leftest (Node l a _) = leftest l\"\n\nfun ord1 :: \"int tree \\<Rightarrow> bool\" where\n\"ord1 Tip = True\" |\n\"ord1 (Node Tip a Tip) = True\" |\n\"ord1 (Node Tip a r) = ((ord1 r) \\<and> (a < leftest r))\" |\n\"ord1 (Node l a Tip) = ((ord1 l) \\<and> (rightest l < a))\" |\n\"ord1 (Node l a r) = ((ord1 l) \\<and> (ord1 r) \\<and> (rightest l < a) \\<and> (a < leftest r))\"\n\nvalue \"ord1 test_tree1\"\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 \n                        then (Node l a r) \n                        else if x < a \n                              then Node (ins x l) a r \n                              else Node l a (ins x r))\"\n\nvalue \"ins 6 test_tree1\"\n\nlemma correctness_ins:\n  \"set (ins x t) = {x} \\<union> set t\"\n  apply (induction t)\n  by auto\n\nlemma \"ord1 t \\<Longrightarrow> ord1 (ins i t)\"\n  apply (induction t arbitrary: i)\n   apply auto\n  sorry\n\ntext \\<open>Exercise 4.2\\<close>\ninductive palindromes :: \"'a list \\<Rightarrow> bool\" where\npal0: \"palindromes []\" |\npalN: \"palindromes xs \\<Longrightarrow> palindromes (x # xs @ [x])\"\n\nlemma c_rev:\n  \"palindromes xs \\<Longrightarrow> rev xs = xs\"\n  apply (induction rule: palindromes.induct)\n  by auto\n\ntext \\<open>Exercise 4.3\\<close>\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 aux0:\n  \"r x y \\<Longrightarrow> star' r x y\"\n  by (metis refl' step')\n\nlemma aux1:\n  \"star' r y z \\<Longrightarrow> r x y \\<Longrightarrow> star' r x z\"\n  apply (induction rule: star'.induct)\n   apply (simp add: aux0)\n  by (rule step')\n\nlemma eq_star1:\n  \"star r x y \\<Longrightarrow> star' r x y\"\n  apply (induction rule: star.induct)\n   apply (rule refl')\n  by (simp add: aux1)\n\nlemma aux3:\n  \"r x y \\<Longrightarrow> star r x y\"\n  by (simp add: refl step)\n\nlemma star_trans:\n  \"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: step)\n\nlemma eq_star2:\n  \"star' r x y \\<Longrightarrow> star r x y\"\n  apply (induction rule: star'.induct)\n   apply (rule refl)\n  by (simp add: aux3 star_trans) \n\ntext \\<open>Exercise 4.4\\<close>\ninductive iter :: \"('a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> nat \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> bool\" for r where\nit_refl: \"iter r n x x\" |\nit_step: \"r x0 x1 \\<Longrightarrow> iter r n x1 xn  \\<Longrightarrow> iter r (n+1) x0 xn\"\n\nlemma star_iter:\n  \"star r x y \\<Longrightarrow> \\<exists> n. iter r n x y\"\n  apply (induction rule: star.induct)\n   apply (metis it_refl)\n  by (metis it_step)\n\ntext \\<open>Exercise 4.5\\<close>\ndatatype alpha = a | b\n\ninductive S :: \"alpha list \\<Rightarrow> bool\" where\ns_empty: \"S []\" |\ns_1: \"S s \\<Longrightarrow> S (a # s @ [b])\" |\ns_2: \"S s1 \\<Longrightarrow> S s2 \\<Longrightarrow> S (s1 @ s2)\"\n\ninductive T :: \"alpha list => bool\" where\nt_empty: \"T []\" |\nt_1: \"T s1 \\<Longrightarrow> T s2 \\<Longrightarrow> T (s1 @ [a] @ s2 @ [b])\"\n\nlemma t_s:\n  \"T w \\<Longrightarrow> S w\"\n  apply (induction rule: T.induct)\n   apply (metis s_empty)\n  by (simp add: s_1 s_2)\n\nlemma balance_composite_first:\n  \"T (w1 @ w2) ==> T w3 ==>  T (w1 @ w2 @ [a] @ w3 @ [b])\"\n  apply (simp)\n  apply (rule t_1[of \"w1 @ w2\" w3, simplified])\n  by (auto)\n\nlemma com_t:\n  \"T s2 \\<Longrightarrow> T s1 \\<Longrightarrow> T (s1 @ s2)\"\n  apply (induction arbitrary: s1 rule: T.induct)\n   apply (simp)\n  using balance_composite_first by auto\n\nlemma s_t:\n  \"S w \\<Longrightarrow> T w\"\n  apply (induction rule: S.induct)\n    apply (rule t_empty)\n  using t_empty t_1 apply fastforce\n  by (simp add: com_t)\n\nend\n", "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_4.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637397236824, "lm_q2_score": 0.8289388125473628, "lm_q1q2_score": 0.7126086395965744}}
{"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_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_with_Proof/TIP15/TIP15/TIP_sort_nat_TSortIsSort.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045907347107, "lm_q2_score": 0.8031738034238807, "lm_q1q2_score": 0.7125794855555251}}
{"text": "(*<*)\ntheory hw09tmpl\n  imports Main \"HOL-Data_Structures.RBT_Set\"\nbegin\n(*>*)\n\ntext \\<open>\\NumHomework{Balanced Tree to RBT}{15.~6.~2018}\n\n  A tree is balanced, if its minimum height and its height differ by at most 1.\n\\<close>\n\nfun min_height :: \"('a,'b) tree \\<Rightarrow> nat\" where\n\"min_height Leaf = 0\" |\n\"min_height (Node _ l _ r) = min (min_height l) (min_height r) + 1\"\n\ndefinition \"balanced t \\<equiv> height t - min_height t \\<le> 1\"\n\ntext \\<open>The following function paints a balanced tree to form a valid red-black tree\n  with the same structure. The task of this homework is to prove this!\n\\<close>\n\nfun mk_rbt :: \"('a,unit) tree \\<Rightarrow> 'a rbt\" where\n  \"mk_rbt Leaf = Leaf\"\n| \"mk_rbt (Node _ l a r) = (let\n    l'=mk_rbt l;\n    r'=mk_rbt r\n  in\n    if min_height l > min_height r then\n      B (paint Red l') a r'\n    else if min_height l < min_height r then\n      B l' a (paint Red r')\n    else\n      B l' a r'\n  )\"\n\n\ntext \\<open>\n  \\subsection*{Warmup}\n\n  Show that the left and right subtree of a balanced tree are, again, balanced\n\\<close>\n\nlemma balanced_subt: \"balanced (Node c l a r) \\<Longrightarrow> balanced l \\<and> balanced r\"\n  unfolding balanced_def by auto\n\n\ntext \\<open>Show the following alternative characterization of balanced:\\<close>\n\nlemma aux1:\"height t \\<ge> min_height t\"\n  apply(induction t)\n  by auto\n\nlemma balanced_alt:\n  \"balanced t \\<longleftrightarrow> height t = min_height t \\<or> height t = min_height t + 1\"\n  text \\<open>Hint: Auxiliary lemma relating @{term \\<open>height t\\<close>} and @{term \\<open>min_height t\\<close>}\\<close>\n  unfolding balanced_def\n  by (metis One_nat_def add_diff_cancel_left' aux1 cancel_comm_monoid_add_class.diff_cancel le_Suc_eq le_add_diff_inverse le_zero_eq order_refl)\n\ntext \\<open>\n  \\subsection*{The Easy Parts}\n\n  Show that \\<open>mk_rbt\\<close> does not change the inorder-traversal\n\\<close>\nlemma mk_rbt_inorder: \"inorder (mk_rbt t) = inorder t\"\n  apply(induction t)\n   apply(auto)\n  by (smt inorder.simps(2) inorder_paint)\n\ntext \\<open>Show that the color of the root node is always black\\<close>\nlemma mk_rbt_color: \"color (mk_rbt t) = Black\"\n  apply(induction t)\n   apply(auto)\n  by (smt RBT_Set.color.simps(2))\n\ntext \\<open>\n  \\subsection*{Medium Complex Parts}\n\n  Show that the black-height of the returned tree is the minimum height of the argument tree\n\\<close>\n\n\n\nlemma mk_rbt_bheight: \"balanced t \\<Longrightarrow> bheight (mk_rbt t) = min_height t\"\ntext \\<open>Hint: Use Isar to have better control when to unfold with @{thm [source] balanced_alt},\n  and when to use @{thm [source] balanced_subt} (e.g. to discharge the premises of the IH)\n\\<close>\nproof(induction t)\n  case Leaf\n  then show ?case by auto\nnext\n  case (Node x1 t1 x3 t2)\n  note IH = Node.IH\n  have \"min_height t1 = min_height t2 \\<or> min_height t1 < min_height t2 \\<or> min_height t1 > min_height t2\" (is \"?C1 \\<or> ?C2 \\<or> ?C3\")\n    by auto\n  moreover\n  {\n    assume ?C1\n    have ?case using IH Node.prems \\<open>?C1\\<close>\n      apply(cases \"min_height t1\")\n       apply(auto)\n       apply (meson balanced_subt)\n      by (meson balanced_subt)\n    }\n    moreover\n    {\n      assume ?C2\n      have ?case using IH Node.prems \\<open>?C2\\<close>\n        apply(cases \"min_height t1\")\n         apply(auto)\n         apply (meson balanced_subt)\n        by (metis balanced_subt min.strict_order_iff)\n    }\n    moreover\n    {\n      assume ?C3\n      then have h0:\"min_height (Node x1 t1 x3 t2) = min_height t2 + 1\" using IH Node.prems by force\n      then have h1:\"min_height t2 = 0 \\<Longrightarrow> bheight (paint Red (mk_rbt t1)) = 0\" using IH Node.prems\n        by (metis (no_types, lifting) One_nat_def Suc_eq_plus1 Suc_leI \\<open>min_height t2 < min_height t1\\<close> add_diff_cancel_right' aux1 balanced_def bheight_paint_Red height.simps(2) le_trans max.commute max_def mk_rbt_color)\n      then have h2: \"min_height t1 > min_height t2 \\<Longrightarrow> min_height t1 = Suc (min_height t2)\" using IH Node.prems\n        by (smt Suc_eq_plus1 Suc_leI Suc_mono balanced_alt balanced_subt h0 height.simps(2) less_Suc_eq max.commute max_def not_le)\n      then have h3: \" min_height t1 > min_height t2 \\<Longrightarrow> bheight (paint Red (mk_rbt t1)) = min_height t2\" using IH Node.prems\n        apply(cases \"min_height t1\")\n         apply(auto)\n        by (metis Suc_eq_plus1 add_diff_cancel_right' balanced_subt bheight_paint_Red mk_rbt_color)\n        \n      then have ?case using IH Node.prems \\<open>?C3\\<close> \n        apply(cases \"min_height t2\")\n        by (auto)\n        \n      }\n      ultimately show ?case by blast\nqed\n\ntext \\<open>\n  Show that the returned tree satisfies the height invariant.\n\\<close>\n\nlemma mk_rbt_invh: \"balanced t \\<Longrightarrow> invh (mk_rbt t)\"\n  apply(induction t rule:mk_rbt.induct)\n   apply(simp add: balanced_alt mk_rbt_color mk_rbt_inorder mk_rbt_bheight)\n  apply(simp split:if_splits)\n  by (smt Suc_eq_plus1 Suc_le_mono add_diff_cancel_right' antisym_conv balanced_alt balanced_subt bheight_paint_Red height.simps(2) invh.simps(2) le_Suc_eq le_simps(3) max_def min_def invh_paint min_height.simps(2) mk_rbt_bheight mk_rbt_color)\n\n\ntext \\<open>\n  \\subsection*{The Hard Part (3 Bonus Points)}\n\n  For {\\bf three bonus points}, show that the returned tree satisfies the color invariant.\n\n  Warning: This requires careful case splitting, via a clever combination of\n    automation and manual proof (Isar, aux-lemmas), in order to deal with the\n    multiple cases without a combinatorial explosion of the proofs.\n\\<close>\n\nlemma mk_rbt_invc: \"balanced t \\<Longrightarrow> invc (mk_rbt t)\"\nproof(induction t)\ncase Leaf\nthen show ?case by auto\nnext\n  case (Node x1 t1 x3 t2)\n  note IH = Node.IH\n  have \"min_height t1 = min_height t2 \\<or> min_height t1 < min_height t2 \\<or> min_height t1 > min_height t2\" (is \"?C1 \\<or> ?C2 \\<or> ?C3\")\n    by auto\n  moreover\n  {\n    assume ?C1\n    have ?case using IH Node.prems \\<open>?C1\\<close>\n      apply(cases \"min_height t1\")\n       apply(auto)\n         apply (meson balanced_subt)\n        apply (meson balanced_subt)\n       apply (meson balanced_subt)\n      by (meson balanced_subt)\n  }\n  moreover\n  {\n    assume ?C2\n    then have h0:\"min_height (Node x1 t1 x3 t2) = min_height t1 + 1\" using IH Node.prems by force\n    then have h1: \"min_height t1 < min_height t2 \\<Longrightarrow> min_height t2 = Suc (min_height t1)\" using IH Node.prems\n      by (smt Suc_eq_plus1 Suc_leI Suc_mono balanced_alt balanced_subt h0 height.simps(2) less_Suc_eq max.commute max_def not_le)\n    then have h2:\"invc (paint Red (mk_rbt t2))\" using IH Node.prems sorry\n      then have ?case using IH Node.prems \\<open>?C2\\<close> \n      apply(cases \"min_height t1\")\n        apply(auto)\n           apply (smt balanced_subt)\n          apply (simp add: h2)\n        by (meson balanced_subt)\n    }\n\nqed\n\n\n(* Now you can combine everything, to show that you are, indeed, generating an RBT *)\ntheorem mk_rbt_is_rbt: \"balanced t \\<Longrightarrow> rbt (mk_rbt t)\"\n  using mk_rbt_invh mk_rbt_invc mk_rbt_color unfolding rbt_def by auto\n\n\n\ntext \\<open>\\NumHomework{Linear-Time Repainting}{15.~6.~2018}\n\n  Write a linear-time version of \\<open>mk_rbt\\<close>, and show that it behaves like\n  \\<open>mk_rbt\\<close>.\n\n  Idea: Compute the min-height during the same recursion as you build\n    the tree.\n\n  Note: No formal complexity proof required.\n\\<close>\n\nfun mk_rbt' :: \"('a,unit) tree \\<Rightarrow> 'a rbt \\<times> nat\" -- \\<open>Returns the RBT and the min-height of the argument\\<close>\nwhere\n  \"mk_rbt' Leaf = (Leaf, 0)\"\n| \"mk_rbt' (Node _ l a r) = (let\n    (l',lx)=mk_rbt' l;\n    (r',rx)=mk_rbt' r\n  in\n    if lx > rx then\n      (B (paint Red l') a r', Suc(rx))\n    else if lx < rx then\n      (B l' a (paint Red r'), Suc(lx))\n    else\n      (B l' a r', Suc(lx))\n  )\" \n\nlemma mk_rbt'_refine_aux: \"mk_rbt' t = (mk_rbt t, min_height t)\"\n  apply(induction t)\n  apply(auto)\n  done\n\n\nlemma mk_rbt'_refine: \"fst (mk_rbt' t) = mk_rbt t\"\n  apply(induction t)\n  by(auto simp:mk_rbt'_refine_aux)\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/hw09tmpl.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8872045907347108, "lm_q2_score": 0.8031737940012418, "lm_q1q2_score": 0.7125794771957167}}
{"text": "theory Basic imports Main begin\n\nlemma conj_rule: \"\\<lbrakk> P; Q \\<rbrakk> \\<Longrightarrow> P \\<and> (Q \\<and> P)\"\napply (rule conjI)\n apply assumption\napply (rule conjI)\n apply assumption\napply assumption\ndone\n    \n\nlemma disj_swap: \"P | Q \\<Longrightarrow> Q | P\"\napply (erule disjE)\n apply (rule disjI2)\n apply assumption\napply (rule disjI1)\napply assumption\ndone\n\nlemma conj_swap: \"P \\<and> Q \\<Longrightarrow> Q \\<and> P\"\napply (rule conjI)\n apply (drule conjunct2)\n apply assumption\napply (drule conjunct1)\napply assumption\ndone\n\nlemma imp_uncurry: \"P \\<longrightarrow> Q \\<longrightarrow> R \\<Longrightarrow> P \\<and> Q \\<longrightarrow> R\"\napply (rule impI)\napply (erule conjE)\napply (drule mp)\n apply assumption\napply (drule mp)\n  apply assumption\n apply assumption\ndone\n\ntext {*\nby eliminates uses of assumption and done\n*}\n\nlemma imp_uncurry': \"P \\<longrightarrow> Q \\<longrightarrow> R \\<Longrightarrow> P \\<and> Q \\<longrightarrow> R\"\napply (rule impI)\napply (erule conjE)\napply (drule mp)\n apply assumption\nby (drule mp)\n\n\ntext {*\nsubstitution\n\n@{thm[display] ssubst}\n\\rulename{ssubst}\n*}\n\nlemma \"\\<lbrakk> x = f x; P(f x) \\<rbrakk> \\<Longrightarrow> P x\"\nby (erule ssubst)\n\ntext {*\nalso provable by simp (re-orients)\n*}\n\ntext {*\nthe subst method\n\n@{thm[display] mult.commute}\n\\rulename{mult.commute}\n\nthis would fail:\napply (simp add: mult.commute) \n*}\n\n\nlemma \"\\<lbrakk>P x y z; Suc x < y\\<rbrakk> \\<Longrightarrow> f z = x*y\"\ntxt{*\n@{subgoals[display,indent=0,margin=65]}\n*}\napply (subst mult.commute) \ntxt{*\n@{subgoals[display,indent=0,margin=65]}\n*}\noops\n\n(*exercise involving THEN*)\nlemma \"\\<lbrakk>P x y z; Suc x < y\\<rbrakk> \\<Longrightarrow> f z = x*y\"\napply (rule mult.commute [THEN ssubst]) \noops\n\n\nlemma \"\\<lbrakk>x = f x; triple (f x) (f x) x\\<rbrakk> \\<Longrightarrow> triple x x x\"\napply (erule ssubst) \n  --{* @{subgoals[display,indent=0,margin=65]} *}\nback --{* @{subgoals[display,indent=0,margin=65]} *}\nback --{* @{subgoals[display,indent=0,margin=65]} *}\nback --{* @{subgoals[display,indent=0,margin=65]} *}\nback --{* @{subgoals[display,indent=0,margin=65]} *}\napply assumption\ndone\n\nlemma \"\\<lbrakk> x = f x; triple (f x) (f x) x \\<rbrakk> \\<Longrightarrow> triple x x x\"\napply (erule ssubst, assumption)\ndone\n\ntext{*\nor better still \n*}\n\nlemma \"\\<lbrakk> x = f x; triple (f x) (f x) x \\<rbrakk> \\<Longrightarrow> triple x x x\"\nby (erule ssubst)\n\n\nlemma \"\\<lbrakk> x = f x; triple (f x) (f x) x \\<rbrakk> \\<Longrightarrow> triple x x x\"\napply (erule_tac P=\"\\<lambda>u. triple u u x\" in ssubst)\napply (assumption)\ndone\n\n\nlemma \"\\<lbrakk> x = f x; triple (f x) (f x) x \\<rbrakk> \\<Longrightarrow> triple x x x\"\nby (erule_tac P=\"\\<lambda>u. triple u u x\" in ssubst)\n\n\ntext {*\nnegation\n\n@{thm[display] notI}\n\\rulename{notI}\n\n@{thm[display] notE}\n\\rulename{notE}\n\n@{thm[display] classical}\n\\rulename{classical}\n\n@{thm[display] contrapos_pp}\n\\rulename{contrapos_pp}\n\n@{thm[display] contrapos_pn}\n\\rulename{contrapos_pn}\n\n@{thm[display] contrapos_np}\n\\rulename{contrapos_np}\n\n@{thm[display] contrapos_nn}\n\\rulename{contrapos_nn}\n*}\n\n\nlemma \"\\<lbrakk>\\<not>(P\\<longrightarrow>Q); \\<not>(R\\<longrightarrow>Q)\\<rbrakk> \\<Longrightarrow> R\"\napply (erule_tac Q=\"R\\<longrightarrow>Q\" in contrapos_np)\n        --{* @{subgoals[display,indent=0,margin=65]} *}\napply (intro impI)\n        --{* @{subgoals[display,indent=0,margin=65]} *}\nby (erule notE)\n\ntext {*\n@{thm[display] disjCI}\n\\rulename{disjCI}\n*}\n\nlemma \"(P \\<or> Q) \\<and> R \\<Longrightarrow> P \\<or> Q \\<and> R\"\napply (intro disjCI conjI)\n        --{* @{subgoals[display,indent=0,margin=65]} *}\n\napply (elim conjE disjE)\n apply assumption\n        --{* @{subgoals[display,indent=0,margin=65]} *}\n\nby (erule contrapos_np, rule conjI)\ntext{*\nproof\\ {\\isacharparenleft}prove{\\isacharparenright}{\\isacharcolon}\\ step\\ {\\isadigit{6}}\\isanewline\n\\isanewline\ngoal\\ {\\isacharparenleft}lemma{\\isacharparenright}{\\isacharcolon}\\isanewline\n{\\isacharparenleft}P\\ {\\isasymor}\\ Q{\\isacharparenright}\\ {\\isasymand}\\ R\\ {\\isasymLongrightarrow}\\ P\\ {\\isasymor}\\ Q\\ {\\isasymand}\\ R\\isanewline\n\\ {\\isadigit{1}}{\\isachardot}\\ {\\isasymlbrakk}R{\\isacharsemicolon}\\ Q{\\isacharsemicolon}\\ {\\isasymnot}\\ P{\\isasymrbrakk}\\ {\\isasymLongrightarrow}\\ Q\\isanewline\n\\ {\\isadigit{2}}{\\isachardot}\\ {\\isasymlbrakk}R{\\isacharsemicolon}\\ Q{\\isacharsemicolon}\\ {\\isasymnot}\\ P{\\isasymrbrakk}\\ {\\isasymLongrightarrow}\\ R\n*}\n\n\ntext{*rule_tac, etc.*}\n\n\nlemma \"P&Q\"\napply (rule_tac P=P and Q=Q in conjI)\noops\n\n\ntext{*unification failure trace *}\n\ndeclare [[unify_trace_failure = true]]\n\nlemma \"P(a, f(b, g(e,a), b), a) \\<Longrightarrow> P(a, f(b, g(c,a), b), a)\"\ntxt{*\n@{subgoals[display,indent=0,margin=65]}\napply assumption\nClash: e =/= c\n\nClash: == =/= Trueprop\n*}\noops\n\nlemma \"\\<forall>x y. P(x,y) --> P(y,x)\"\napply auto\ntxt{*\n@{subgoals[display,indent=0,margin=65]}\napply assumption\n\nClash: bound variable x (depth 1) =/= bound variable y (depth 0)\n\nClash: == =/= Trueprop\nClash: == =/= Trueprop\n*}\noops\n\ndeclare [[unify_trace_failure = false]]\n\n\ntext{*Quantifiers*}\n\ntext {*\n@{thm[display] allI}\n\\rulename{allI}\n\n@{thm[display] allE}\n\\rulename{allE}\n\n@{thm[display] spec}\n\\rulename{spec}\n*}\n\nlemma \"\\<forall>x. P x \\<longrightarrow> P x\"\napply (rule allI)\nby (rule impI)\n\nlemma \"(\\<forall>x. P \\<longrightarrow> Q x) \\<Longrightarrow> P \\<longrightarrow> (\\<forall>x. Q x)\"\napply (rule impI, rule allI)\napply (drule spec)\nby (drule mp)\n\ntext{*rename_tac*}\nlemma \"x < y \\<Longrightarrow> \\<forall>x y. P x (f y)\"\napply (intro allI)\n        --{* @{subgoals[display,indent=0,margin=65]} *}\napply (rename_tac v w)\n        --{* @{subgoals[display,indent=0,margin=65]} *}\noops\n\n\nlemma \"\\<lbrakk>\\<forall>x. P x \\<longrightarrow> P (h x); P a\\<rbrakk> \\<Longrightarrow> P(h (h a))\"\napply (frule spec)\n        --{* @{subgoals[display,indent=0,margin=65]} *}\napply (drule mp, assumption)\napply (drule spec)\n        --{* @{subgoals[display,indent=0,margin=65]} *}\nby (drule mp)\n\nlemma \"\\<lbrakk>\\<forall>x. P x \\<longrightarrow> P (f x); P a\\<rbrakk> \\<Longrightarrow> P(f (f a))\"\nby blast\n\n\ntext{*\nthe existential quantifier*}\n\ntext {*\n@{thm[display]\"exI\"}\n\\rulename{exI}\n\n@{thm[display]\"exE\"}\n\\rulename{exE}\n*}\n\n\ntext{*\ninstantiating quantifiers explicitly by rule_tac and erule_tac*}\n\nlemma \"\\<lbrakk>\\<forall>x. P x \\<longrightarrow> P (h x); P a\\<rbrakk> \\<Longrightarrow> P(h (h a))\"\napply (frule spec)\n        --{* @{subgoals[display,indent=0,margin=65]} *}\napply (drule mp, assumption)\n        --{* @{subgoals[display,indent=0,margin=65]} *}\napply (drule_tac x = \"h a\" in spec)\n        --{* @{subgoals[display,indent=0,margin=65]} *}\nby (drule mp)\n\ntext {*\n@{thm[display]\"dvd_def\"}\n\\rulename{dvd_def}\n*}\n\nlemma mult_dvd_mono: \"\\<lbrakk>i dvd m; j dvd n\\<rbrakk> \\<Longrightarrow> i*j dvd (m*n :: nat)\"\napply (simp add: dvd_def)\n        --{* @{subgoals[display,indent=0,margin=65]} *}\napply (erule exE) \n        --{* @{subgoals[display,indent=0,margin=65]} *}\napply (erule exE) \n        --{* @{subgoals[display,indent=0,margin=65]} *}\napply (rename_tac l)\n        --{* @{subgoals[display,indent=0,margin=65]} *}\napply (rule_tac x=\"k*l\" in exI) \n        --{* @{subgoals[display,indent=0,margin=65]} *}\napply simp\ndone\n\ntext{*\nHilbert-epsilon theorems*}\n\ntext{*\n@{thm[display] the_equality[no_vars]}\n\\rulename{the_equality}\n\n@{thm[display] some_equality[no_vars]}\n\\rulename{some_equality}\n\n@{thm[display] someI[no_vars]}\n\\rulename{someI}\n\n@{thm[display] someI2[no_vars]}\n\\rulename{someI2}\n\n@{thm[display] someI_ex[no_vars]}\n\\rulename{someI_ex}\n\nneeded for examples\n\n@{thm[display] inv_def[no_vars]}\n\\rulename{inv_def}\n\n@{thm[display] Least_def[no_vars]}\n\\rulename{Least_def}\n\n@{thm[display] order_antisym[no_vars]}\n\\rulename{order_antisym}\n*}\n\n\nlemma \"inv Suc (Suc n) = n\"\nby (simp add: inv_def)\n\ntext{*but we know nothing about inv Suc 0*}\n\ntheorem Least_equality:\n     \"\\<lbrakk> P (k::nat);  \\<forall>x. P x \\<longrightarrow> k \\<le> x \\<rbrakk> \\<Longrightarrow> (LEAST x. P(x)) = k\"\napply (simp add: Least_def)\n \ntxt{*\n@{subgoals[display,indent=0,margin=65]}\n*}\n   \napply (rule the_equality)\n\ntxt{*\n@{subgoals[display,indent=0,margin=65]}\n\nfirst subgoal is existence; second is uniqueness\n*}\nby (auto intro: order_antisym)\n\n\ntheorem axiom_of_choice:\n     \"(\\<forall>x. \\<exists>y. P x y) \\<Longrightarrow> \\<exists>f. \\<forall>x. P x (f x)\"\napply (rule exI, rule allI)\n\ntxt{*\n@{subgoals[display,indent=0,margin=65]}\n\nstate after intro rules\n*}\napply (drule spec, erule exE)\n\ntxt{*\n@{subgoals[display,indent=0,margin=65]}\n\napplying @text{someI} automatically instantiates\n@{term f} to @{term \"\\<lambda>x. SOME y. P x y\"}\n*}\n\nby (rule someI)\n\n(*both can be done by blast, which however hasn't been introduced yet*)\nlemma \"[| P (k::nat);  \\<forall>x. P x \\<longrightarrow> k \\<le> x |] ==> (LEAST x. P(x)) = k\"\napply (simp add: Least_def LeastM_def)\nby (blast intro: some_equality order_antisym)\n\ntheorem axiom_of_choice': \"(\\<forall>x. \\<exists>y. P x y) \\<Longrightarrow> \\<exists>f. \\<forall>x. P x (f x)\"\napply (rule exI [of _  \"\\<lambda>x. SOME y. P x y\"])\nby (blast intro: someI)\n\ntext{*end of Epsilon section*}\n\n\nlemma \"(\\<exists>x. P x) \\<or> (\\<exists>x. Q x) \\<Longrightarrow> \\<exists>x. P x \\<or> Q x\"\napply (elim exE disjE)\n apply (intro exI disjI1)\n apply assumption\napply (intro exI disjI2)\napply assumption\ndone\n\nlemma \"(P\\<longrightarrow>Q) \\<or> (Q\\<longrightarrow>P)\"\napply (intro disjCI impI)\napply (elim notE)\napply (intro impI)\napply assumption\ndone\n\nlemma \"(P\\<or>Q)\\<and>(P\\<or>R) \\<Longrightarrow> P \\<or> (Q\\<and>R)\"\napply (intro disjCI conjI)\napply (elim conjE disjE)\napply blast\napply blast\napply blast\napply blast\n(*apply elim*)\ndone\n\nlemma \"(\\<exists>x. P \\<and> Q x) \\<Longrightarrow> P \\<and> (\\<exists>x. Q x)\"\napply (erule exE)\napply (erule conjE)\napply (rule conjI)\n apply assumption\napply (rule exI)\n apply assumption\ndone\n\nlemma \"(\\<exists>x. P x) \\<and> (\\<exists>x. Q x) \\<Longrightarrow> \\<exists>x. P x \\<and> Q x\"\napply (erule conjE)\napply (erule exE)\napply (erule exE)\napply (rule exI)\napply (rule conjI)\n apply assumption\noops\n\nlemma \"\\<forall>y. R y y \\<Longrightarrow> \\<exists>x. \\<forall>y. R x y\"\napply (rule exI) \n  --{* @{subgoals[display,indent=0,margin=65]} *}\napply (rule allI) \n  --{* @{subgoals[display,indent=0,margin=65]} *}\napply (drule spec) \n  --{* @{subgoals[display,indent=0,margin=65]} *}\noops\n\nlemma \"\\<forall>x. \\<exists>y. x=y\"\napply (rule allI)\napply (rule exI)\napply (rule refl)\ndone\n\nlemma \"\\<exists>x. \\<forall>y. x=y\"\napply (rule exI)\napply (rule allI)\noops\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/Basic.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232489352, "lm_q2_score": 0.8740772450055545, "lm_q1q2_score": 0.7125761683318163}}
{"text": "section \\<open>Generalized Cantor's Theorem and Instances\\<close>\n\ntheory GeneralCantor imports\n  Complex_Main\n  \"HOL-Library.Countable\"\n  \"HOL-Analysis.Analysis\"\n  \"HOL-ZF.HOLZF\"\n  \"Universal_Turing_Machine.Turing_aux\"\n  \"Universal_Turing_Machine.TuringDecidable\"\n  \"Universal_Turing_Machine.HaltingProblems_K_aux\"\n  \"Universal_Turing_Machine.TuringComputable\"\n  \"Universal_Turing_Machine.DitherTM\"\n  \"Universal_Turing_Machine.CopyTM\"\nbegin\n\ntext \\<open>\n  1. The most abstracted version of Cantor's theorem.\n  S x T ---- f ----> Y\n    ^                |\n    |                |\n(beta, Id)         alpha             S ---- beta_comp ----> T              beta \\<circ> beta_comp = Id\n    |                |\n    |                v\n    T   ---- g ----> Y\n\\<close>\ntheorem \"Abstracted_Cantor\":\n  fixes f :: \"'b \\<Rightarrow> 'a \\<Rightarrow> 'c\" and \\<alpha> :: \"'c \\<Rightarrow> 'c\" and \\<beta> :: \"'a \\<Rightarrow> 'b\" and \\<beta>_c :: \"'b \\<Rightarrow> 'a\"\n  assumes surjectivity: \"surj f\"\n  and no_fixed_point: \"\\<forall>y. \\<alpha> y \\<noteq> y\"\n  and right_inverse: \"\\<forall>s. \\<beta> (\\<beta>_c s) = s\"\n  shows \"False\"\nproof -\n  from surjectivity have \"\\<forall>h :: 'a \\<Rightarrow> 'c. \\<exists>t. h = f t\" by auto\n  hence \"\\<exists>t. (\\<alpha> \\<circ> (\\<lambda>t'. f (\\<beta> t') t')) = f t\" by simp\n  then obtain t0 where \"(\\<alpha> \\<circ> (\\<lambda>t'. f (\\<beta> t') t')) = f t0\" ..\n  hence \"(\\<alpha> \\<circ> (\\<lambda>t'. f (\\<beta> t') t')) (\\<beta>_c t0) = f t0 (\\<beta>_c t0)\" by (rule arg_cong)\n  hence \"\\<alpha> (f t0 (\\<beta>_c t0)) = f t0 (\\<beta>_c t0)\" using right_inverse by simp\n  thus \"False\" using no_fixed_point by simp\nqed\n\n\ntext \\<open>\n  2. An instance of the above theorem, where S = T and \\<beta> = Id. Still a quite general version\n  of Cantor's theorem.\n  T x T ---- f ----> Y\n    ^                |\n    |                |\n Diagonal          alpha\n    |                |\n    |                v\n    T   ---- g ----> Y\n\\<close>\ntheorem \"Generalized_Cantor\":\n  fixes alpha :: \"'b \\<Rightarrow> 'b\" and f :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'b\"\n  assumes surjectivity: \"surj f\"\n  and no_fixed_point: \"\\<forall>y. alpha y \\<noteq> y\"\n  shows \"False\"\n  apply(rule Abstracted_Cantor[of f alpha \"\\<lambda>x. x\" \"\\<lambda>x. x\"])\n  apply(auto simp add: no_fixed_point surjectivity)\n  done\n\n\ntext \\<open>\n  3. An instance of the above version of Cantor's theorem, where 'b = bool and \\<alpha> = \\<not>.\n  Entailing the fact that no surjective functions exists from a set to its power set.\n  T ---- f ----> \\<P>(T)\n\\<close>\ntheorem \"Classic_Cantor\":\n  fixes f :: \"'a \\<Rightarrow> 'a \\<Rightarrow> bool\"\n  assumes surjectivity: \"surj f\"\n  shows \"False\"\n  apply(rule Generalized_Cantor[of f Not])\n  apply(auto simp add: surjectivity)\n  done\n\n\ntext \\<open>\n  4. An instance of the above theorem. With the set 'a being natural numbers.\n |\\<P>(\\<nat>)| > |\\<nat>|\n\\<close>\ntheorem \"Classic_Nat_Cantor\":\n  fixes f :: \"nat \\<Rightarrow> nat \\<Rightarrow> bool\"\n  assumes surjectivity: \"surj f\"\n  shows \"False\"\n  apply(rule Classic_Cantor[of f])\n  apply(simp add: surjectivity)\n  done\n\n\ntext \\<open>\n  5. Contrapositive of Cantor's Theorem:\n  If Y is a set and there exists a set T together with a function f: T x T \\<longrightarrow> Y\n  such that all functions g: T \\<longrightarrow> Y are representable by f, i.e. there exists\n  a t in T such that g = f t, then all functions \\<alpha>: Y \\<longrightarrow> Y admits a fixed point.\n\\<close>\ntheorem \"Contrapositive_Cantor\":\n  fixes f :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'b\"\n  assumes surjectivity: \"surj f\"\n  shows \"\\<forall>\\<alpha> :: 'b \\<Rightarrow> 'b. \\<exists>y. \\<alpha> y = y\"\n  by (meson Generalized_Cantor surjectivity)\n\n\ntext \\<open> \n  6. All endomorphisms admitting a fixed point means the set has only one element.\n  Still, we will keep the definition of fixed points and do not make assumptions on the cardinality\n  of Y. The reason being that fixed points easily generalize to categories unlike cardinality.\n\\<close>\nlemma one_elem_to_fixed: \"(\\<forall>a b :: 'b. a = b) \\<longrightarrow> (\\<forall>\\<alpha> :: 'b \\<Rightarrow> 'b. \\<exists>y. \\<alpha> y = y)\"\n  by simp\n\nlemma fixed_to_one_elem: \"(\\<forall>\\<alpha> :: 'b \\<Rightarrow> 'b. \\<exists>y. \\<alpha> y = y) \\<longrightarrow> (\\<forall>a b :: 'b. a = b)\"\nproof (rule ccontr)\n  assume \"\\<not> ((\\<forall>\\<alpha> :: 'b \\<Rightarrow> 'b. \\<exists>y. \\<alpha> y = y) \\<longrightarrow> (\\<forall>a b :: 'b. a = b))\"\n  hence contra: \"(\\<forall>\\<alpha> :: 'b \\<Rightarrow> 'b. \\<exists>y. \\<alpha> y = y) \\<and> (\\<exists>a b :: 'b. a \\<noteq> b)\" by simp\n  from contra have fixed_point: \"\\<forall>\\<alpha> :: 'b \\<Rightarrow> 'b. \\<exists>y. \\<alpha> y = y\" by simp\n  from contra have diff_elem: \"\\<exists>a b :: 'b. a \\<noteq> b\" by simp\n  then obtain a b where \"a \\<noteq> (b :: 'b)\" by blast\n  hence \"\\<exists> f :: 'b \\<Rightarrow> 'b. f = (\\<lambda>x. (if x = a then b else a))\" by fast\n  then obtain f where no_fixed_point: \"\\<forall>y :: 'b. f y \\<noteq> y\" by (metis \\<open>a \\<noteq> (b::'b)\\<close>)\n  thus \"False\" using fixed_point no_fixed_point by blast\nqed\n\ntheorem \"(\\<forall>\\<alpha> :: 'b \\<Rightarrow> 'b. \\<exists>y. \\<alpha> y = y) \\<longleftrightarrow> (\\<forall>a b :: 'b. a = b)\"\n  by (metis fixed_to_one_elem)\n\ntext \\<open>\n 7. |\\<real>| = |\\<P>(\\<nat>)|\n\\<close>\n\ntext \\<open>\n  7.1 Show that \\<exists>f s.t. f: \\<real> \\<longlongrightarrow> \\<P>(\\<rat>) and f is injective. ==> |\\<real>| \\<le> 2^(\\<aleph>_0)\n\\<close>\ndefinition cut_set :: \"real \\<Rightarrow> (rat \\<Rightarrow> bool)\" where\n\"cut_set r = (\\<lambda>q. of_rat q < r)\"\n\nlemma \"contra_inj_cut_set\": \"\\<forall>x y :: real. x \\<noteq> y \\<longrightarrow> cut_set x \\<noteq> cut_set y\"\n  by (metis cut_set_def linorder_less_linear of_rat_dense order_less_not_sym)\n\nlemma \"inj_example_cut_set\": \"inj cut_set\"\n  by (meson contra_inj_cut_set injI)\n\nlemma \"\\<exists>f :: real \\<Rightarrow> (rat \\<Rightarrow> bool). inj f\"\n  by (meson inj_example_cut_set)\n\n\ntext \\<open>\n  7.2 Show that \\<exists>f s.t. f: (nat => bool) => real and f is surjective on [0, 1].\n       \\<Longrightarrow> 2^(\\<aleph>_0) \\<ge> |[0,1]|\n\\<close>\n(*A function that is surjective on real numbers between 0 and 1: *)\ndefinition seq_to_real :: \"(nat \\<Rightarrow> bool) \\<Rightarrow> real\" where\n\"seq_to_real f = \\<Sum>{1/(2^n) | n. f n = True}\"\n\n(*Helper definition and functions to prove that the above function is surjective: *)\n(*A function that returns the most significant binary digit for a real number between 0 and 1: *)\ndefinition most_sig_bdig :: \"real \\<Rightarrow> nat\" where\n\"most_sig_bdig x = Min {n. 1/(2^n) < x}\" \n\ndefinition bool_mult :: \"bool \\<Rightarrow> real \\<Rightarrow> real\" where\n\"bool_mult b x = (if b = False then 0 else x)\"\n\n(*A function that expands a real number between 0 and 1 to its binary representation: *)\ndefinition binary_remainder :: \"(real \\<Rightarrow> nat \\<Rightarrow> bool) \\<Rightarrow> real \\<Rightarrow> nat \\<Rightarrow> real set\" where\n\"binary_remainder bs x n = {bool_mult (bs x k)  1/(2^k) | k. 1 < k \\<and> k < n}\"\n\nlemma [fundef_cong]:\n  assumes \"x = x'\" and \"n = n'\" and \"\\<And>k. k < n \\<Longrightarrow> bs x k = bs' x k\"\n  shows \"binary_remainder bs x n = binary_remainder bs' x' n'\"\n  using assms unfolding binary_remainder_def\n  by force\n\nfun binary_sequence :: \"real \\<Rightarrow> nat \\<Rightarrow> bool\" where\n\"binary_sequence x 0 = (if most_sig_bdig x > 1 then False else True)\" |\nbinseq_rem: \"binary_sequence x (Suc n) =\n  (if most_sig_bdig (x - \\<Sum>(binary_remainder binary_sequence x n)) > Suc n\n   then False else True)\"\n\nlemma binseq_no_rem: \"binary_sequence x (Suc n) =\n  (if most_sig_bdig (x - \\<Sum>{bool_mult (binary_sequence x k)  1/(2^k) | k. 1 < k \\<and> k < n}) > Suc n\n   then False else True)\"\n  apply(simp add: binary_remainder_def)\n  done\n\ndeclare binseq_rem [simp del]\ndeclare binseq_no_rem [simp add]\n\n(* TODO:\nlemma \"\\<forall>r :: real. 0 < r \\<and> r < 1 \\<longrightarrow> (\\<exists>f :: nat \\<Rightarrow> bool. seq_to_real f = r)\"\n*)\n\n\ntext \\<open>\n  7.3 Show that \\<exists>f s.t. f: (0, 1) => real and f is surjective. f x = tan(\\<pi>x - \\<pi>/2).\n      \\<Longrightarrow> |(0, 1)| \\<le> |\\<real>|\n\\<close>\ndefinition fitted_tan :: \"real \\<Rightarrow> real\" where\n\"fitted_tan x = tan (pi*x - pi/2)\"\n\ndefinition fitted_arctan :: \"real \\<Rightarrow> real\" where\n\"fitted_arctan x = (arctan x + pi/2) / pi\"\n\nlemma fitted_arctan: \"0 < fitted_arctan y \\<and> fitted_arctan y < 1 \\<and> fitted_tan (fitted_arctan y) = y\"\n  unfolding fitted_arctan_def fitted_tan_def\n  by (smt (verit) arctan divide_less_eq_1_pos divide_pos_pos field_sum_of_halves\n      nonzero_mult_div_cancel_left times_divide_eq_right)\n\nlemma fitted_reverse [simp]: \"\\<forall>y. fitted_tan (fitted_arctan y) = y\"\n  unfolding fitted_arctan_def fitted_tan_def\n  by (simp add: arctan)\n\nlemma fitted_surj [simp]: \"\\<forall>r. \\<exists>x. fitted_tan x = r\"\n  using fitted_reverse by blast\n  \nlemma \"fitted_tan ` {r. 0 < r \\<and> r < 1} = UNIV\"\n  using fitted_arctan fitted_surj image_iff by fastforce\n\n\ntext \\<open>\n  8. Russel's Paradox\n\\<close>\n(*\n  In the context of Generalized_Cantor g becomes the characteristic function of sets that are not\n  members of themselves, i.e. g x = True iff Not (Elem x x).\n  \n  So, if there was a set R which included all the sets that are not members of themselves then,\n  Elem R = g\n  \n  But such R cannot exist as Elem is not surjective, it cannot represent g, by Classic_Cantor.\n*)\nlemma \"Russels's_Paradox\": \"surj Elem \\<Longrightarrow> False\"\n  apply (rule Classic_Cantor)\n  by simp\n\n\ntext \\<open>\n  9. Counting argument to show the existence of non-r.e. languages\n\\<close>\ninstance action :: countable\n  by countable_datatype\n\ninstance cell :: countable\n  by countable_datatype\n\nlemma \"from_nat (to_nat (p::tprog0)) = p\"\n  by simp\n\ndefinition \"tprog0_accepts_num p n \\<equiv> \\<lbrace>\\<lambda>tap. tap = ([], <n::nat>)\\<rbrace> p \\<lbrace>\\<lambda>tap. \\<exists>k l. tap = (Bk \\<up> k, <1::nat> @ Bk \\<up> l)\\<rbrace>\"\n\ntheorem \"Non-re_Languages\":\n  assumes surjectivity: \"surj tprog0_accepts_num\"\n  shows \"False\"\n  apply(rule Abstracted_Cantor[of tprog0_accepts_num Not from_nat to_nat])\n  apply(auto simp add: surjectivity)\n  done\n\n\ntext \\<open>\n  10. Turing Machines and the Halting Problem\n\\<close>\nlemma top_holds_for [intro, simp]: \"top holds_for conf\"\n  apply (cases conf)\n  by simp\n\ndefinition \"halts p ns \\<equiv> \\<exists>Q. \\<lbrace>\\<lambda>tap. tap = ([], <ns::nat>)\\<rbrace> p \\<lbrace>Q\\<rbrace>\"\n\nlemma halts_alt_def: \"halts p ns = (\\<exists>n. is_final (steps0 (1, [], <ns>) p n))\"\n  unfolding halts_def Hoare_halt_def\n  by force\n\nlemma not_halts: \"\\<not> halts p ns \\<longrightarrow> \\<lbrace>\\<lambda>tap. tap = ([], <ns::nat>)\\<rbrace> p \\<up>\"\n  using Hoare_unhaltI halts_alt_def\n  by presburger\n\nlemma not_halts_alt: \"\\<not> halts p ns \\<longrightarrow> (\\<nexists>n. is_final (steps0 (1, [], <ns>) p n))\"\n  using halts_def Hoare_halt_def\n  by blast\n\ndefinition \"decides_halting H \\<equiv> \\<forall>(p::tprog0) (ns::nat).\n  \\<lbrace>\\<lambda>tap. tap = ([Bk], <(tm_to_nat p, ns)>)\\<rbrace>\n   H\n  \\<lbrace>\\<lambda>tap. \\<exists>k l. tap = (Bk \\<up> k, <(if halts p ns then 0::nat else 1::nat)> @ Bk \\<up> l)\\<rbrace>\"\n\n(*------------------------------TODO: AFP entry should include this.------------------------------*)\nlemma Hoare_halt_tm_impl_Hoare_halt_mk_composable0_cell_list_aux: \"\\<lbrace>\\<lambda>tap. tap = (cl', cl)\\<rbrace> tm \\<lbrace>Q\\<rbrace> \\<Longrightarrow> \\<lbrace>\\<lambda>tap. tap = (cl', cl)\\<rbrace> mk_composable0 tm \\<lbrace>Q\\<rbrace>\" \n  unfolding Hoare_halt_def\nproof -\n  assume A: \"\\<forall>tap. (tap = (cl', cl)) \\<longrightarrow> (\\<exists>n. is_final (steps0 (1, tap) tm n) \\<and> Q holds_for steps0 (1, tap) tm n)\"\n  show \"\\<forall>tap. (tap = (cl', cl)) \\<longrightarrow> (\\<exists>n. is_final (steps0 (1, tap) (mk_composable0 tm) n) \\<and> Q holds_for steps0 (1, tap) (mk_composable0 tm) n)\"\n  proof\n    fix tap\n    show \"(tap = (cl', cl)) \\<longrightarrow> (\\<exists>n. is_final (steps0 (1, tap) (mk_composable0 tm) n) \\<and> Q holds_for steps0 (1, tap) (mk_composable0 tm) n)\"\n    proof\n      assume \"tap = (cl', cl)\"\n      with A have \"(\\<exists>n. is_final (steps0 (1, tap) tm n) \\<and> Q holds_for steps0 (1, tap) tm n)\"\n        by auto\n      then obtain n where w_n: \"is_final (steps0 (1, tap) tm n) \\<and> Q holds_for steps0 (1, tap) tm n\"\n        by blast\n\n      with \\<open>tap = (cl', cl)\\<close> have w_n': \"is_final (steps0 (1, cl', cl) tm n) \\<and> Q holds_for steps0 (1, cl', cl) tm n\" by auto\n\n      have \"\\<exists>n. is_final (steps0 (1, cl', cl) (mk_composable0 tm) n) \\<and> Q holds_for steps0 (1, cl', cl) (mk_composable0 tm) n\"\n\n      proof (cases \"\\<forall>stp. steps0 (1,cl',cl) (mk_composable0 tm) stp = steps0 (1,cl', cl) tm stp\")\n        case True\n        with w_n' have \"is_final (steps0 (1, cl', cl) (mk_composable0 tm) n) \\<and> Q holds_for steps0 (1, cl', cl) (mk_composable0 tm) n\" by auto\n        then show ?thesis by auto\n      next\n        case False\n        then have \"\\<exists>stp. steps0 (1, cl', cl) (mk_composable0 tm) stp \\<noteq> steps0 (1, cl', cl) tm stp\" by blast\n        then obtain stp where w_stp: \"steps0 (1, cl', cl) (mk_composable0 tm) stp \\<noteq> steps0 (1, cl', cl) tm stp\" by blast\n\n        show \"\\<exists>m. is_final (steps0 (1, cl', cl) (mk_composable0 tm) m) \\<and> Q holds_for steps0 (1, cl', cl) (mk_composable0 tm) m\"\n        proof -\n          from w_stp have F0: \"0 < stp \\<and>\n                           (\\<exists>fl fr.\n                                   snd (steps0 (1, cl', cl) tm stp) = (fl, fr) \\<and>\n                                   (\\<forall>i < stp. steps0 (1, cl', cl) (mk_composable0 tm) i = steps0 (1, cl', cl) tm i) \\<and>\n                                   (\\<forall>j > stp. steps0 (1, cl', cl) tm (j) = (0, fl, fr) \\<and> \n                                              steps0 (1, cl', cl) (mk_composable0 tm) j =(0, fl, fr)))\"\n            by (rule mk_composable0_tm_at_most_one_diff')\n\n          from F0 have \"0 < stp\" by auto\n\n          from F0 obtain fl fr where w_fl_fr: \"snd (steps0 (1, cl', cl) tm stp) = (fl, fr) \\<and>\n                                   (\\<forall>i < stp. steps0 (1, cl', cl) (mk_composable0 tm) i = steps0 (1, cl', cl) tm i) \\<and>\n                                   (\\<forall>j > stp. steps0 (1, cl', cl) tm (j) = (0, fl, fr) \\<and> \n                                              steps0 (1, cl', cl) (mk_composable0 tm) j =(0, fl, fr))\" by blast\n\n\n          have \"steps0 (1, cl', cl) tm (stp+1) = steps0 (1, cl', cl) tm  n\"\n          proof (cases \"steps0 (1, cl', cl) tm n\")\n            case (fields fsn fln frn)\n            then have \"steps0 (1, cl', cl) tm n = (fsn, fln, frn)\" .\n            with w_n' have \"is_final (fsn, fln, frn)\" by auto\n            with is_final_eq have \"fsn=0\" by auto\n            with \\<open>steps0 (1, cl', cl) tm n = (fsn, fln, frn)\\<close>  have \"steps0 (1, cl', cl) tm n = (0, fln, frn)\" by auto\n\n            show \"steps0 (1, cl', cl) tm (stp + 1) = steps0 (1, cl', cl) tm n\"\n            proof (cases \"n \\<le> stp+1\")\n              case True\n              then have \"n \\<le> stp + 1\" .\n              show ?thesis\n              proof -\n                from \\<open>steps0 (1, cl', cl) tm n = (0, fln, frn)\\<close> and \\<open>n \\<le> stp + 1\\<close> have \"steps0 (1, cl', cl) tm (stp+1) = (0, fln, frn)\"\n                  by (rule stable_config_after_final_ge_2')\n                with \\<open>fsn=0\\<close> and \\<open>steps0 (1, cl', cl) tm n = (fsn, fln, frn)\\<close> show ?thesis by auto\n              qed\n            next\n              case False\n              then have \"stp + 1 \\<le> n\" by arith\n              show ?thesis\n              proof -\n                from w_fl_fr have \"steps0 (1, cl', cl) tm (stp+1) = (0, fl, fr)\" by auto\n                have \"steps0 (1, cl', cl) tm n = (0, fl, fr)\"\n                proof (rule stable_config_after_final_ge_2')\n                  from \\<open>steps0 (1, cl', cl) tm (stp+1) = (0, fl, fr)\\<close> show \"steps0 (1, cl', cl) tm (stp+1) = (0, fl, fr)\" by auto\n                next\n                  from \\<open>stp + 1 \\<le> n\\<close> show \"stp + 1 \\<le> n\" .\n                qed\n                with \\<open>steps0 (1, cl', cl) tm (stp+1) = (0, fl, fr)\\<close> show ?thesis by auto\n              qed\n            qed\n          qed\n          with w_n' have \"is_final(steps0 (1, cl', cl) tm (stp+1)) \\<and> Q holds_for steps0 (1, cl', cl) tm (stp+1)\" by auto\n          moreover from w_fl_fr have \"steps0 (1, cl', cl) tm (stp+1) = steps0 (1, cl', cl) (mk_composable0 tm) (stp+1)\" by auto\n          ultimately have \"is_final(steps0 (1, cl', cl) (mk_composable0 tm) (stp+1)) \\<and> Q holds_for steps0 (1, cl', cl) (mk_composable0 tm) (stp+1)\" by auto\n          then show ?thesis by blast\n        qed\n      qed\n      with \\<open>tap = (cl', cl)\\<close> show \"\\<exists>n. is_final (steps0 (1, tap) (mk_composable0 tm) n) \\<and> Q holds_for steps0 (1, tap) (mk_composable0 tm) n\" by auto\n    qed\n  qed\nqed\n\ntheorem Hoare_halt_tm_impl_Hoare_halt_mk_composable0_cell_list_generalized: \"\\<lbrace>P\\<rbrace> tm \\<lbrace>Q\\<rbrace> \\<Longrightarrow> \\<lbrace>P\\<rbrace> mk_composable0 tm \\<lbrace>Q\\<rbrace>\"\n  using Hoare_halt_def Hoare_halt_tm_impl_Hoare_halt_mk_composable0_cell_list_aux old.prod.exhaust by auto\n(*------------------------------------------------------------------------------------------------*)\n\nlemma \"halting_problem_assuming_dither_copy\":\n  assumes \"\\<exists>dither::tprog0. \\<lbrace>\\<lambda>tap. \\<exists>k l. tap = (Bk \\<up> k, <1::nat> @ Bk \\<up> l)\\<rbrace> dither \\<lbrace>\\<lambda>tap. \\<exists>k l. tap = (Bk \\<up> k, <1::nat> @ Bk \\<up> l)\\<rbrace>\n                          \\<and> \\<lbrace>\\<lambda>tap. \\<exists>k l. tap = (Bk \\<up> k, <0::nat> @ Bk \\<up> l)\\<rbrace> dither \\<up>\"\n  and \"\\<exists>copy::tprog0. \\<forall>n::nat. \\<lbrace>\\<lambda>tap. tap = ([], <n>)\\<rbrace> copy \\<lbrace>\\<lambda>tap. tap = ([Bk], <(n, n)>)\\<rbrace>\"\n\n  shows \"\\<nexists>H. decides_halting H\"\nproof (rule ccontr)\n  assume \"\\<not> (\\<nexists>H::tprog0. decides_halting H)\"\n  hence \"\\<exists>H. decides_halting H\" by simp\n\n  then obtain H'::tprog0 where \"decides_halting H'\" ..\n  then have \"composable_tm0 (mk_composable0 H') \\<and> (decides_halting (mk_composable0 H'))\"\n    using Hoare_halt_tm_impl_Hoare_halt_mk_composable0_cell_list_generalized composable_tm0_mk_composable0 decides_halting_def by blast \n  then have \"\\<exists>H. composable_tm0 H \\<and> decides_halting H\" using decides_halting_def by blast\n  then obtain H::tprog0 where h: \"composable_tm0 H \\<and> decides_halting H\" ..\n\n  from assms(1) obtain dither::tprog0 where d: \"\\<lbrace>\\<lambda>tap. \\<exists>k l. tap = (Bk \\<up> k, <1::nat> @ Bk \\<up> l)\\<rbrace> dither \\<lbrace>\\<lambda>tap. \\<exists>k l. tap = (Bk \\<up> k, <1::nat> @ Bk \\<up> l)\\<rbrace>\n                                              \\<and> \\<lbrace>\\<lambda>tap. \\<exists>k l. tap = (Bk \\<up> k, <0::nat> @ Bk \\<up> l)\\<rbrace> dither \\<up>\" ..\n\n  from assms(2) obtain copy'::tprog0 where \"\\<forall>n::nat. \\<lbrace>\\<lambda>tap. tap = ([], <n>)\\<rbrace> copy' \\<lbrace>\\<lambda>tap. tap = ([Bk], <(n, n)>)\\<rbrace>\" ..\n  then have \"composable_tm0 (mk_composable0 copy')\n          \\<and> (\\<forall>n::nat. \\<lbrace>\\<lambda>tap. tap = ([], <n>)\\<rbrace> mk_composable0 copy' \\<lbrace>\\<lambda>tap. tap = ([Bk], <(n, n)>)\\<rbrace>)\"\n    using Hoare_halt_tm_impl_Hoare_halt_mk_composable0_cell_list composable_tm0_mk_composable0 by blast\n  then have \"\\<exists>copy. composable_tm0 copy\n          \\<and> (\\<forall>n::nat. \\<lbrace>\\<lambda>tap. tap = ([], <n>)\\<rbrace> copy \\<lbrace>\\<lambda>tap. tap = ([Bk], <(n, n)>)\\<rbrace>)\" by blast\n  then obtain copy::tprog0 where c: \"composable_tm0 copy \n                                  \\<and> (\\<forall>n::nat. \\<lbrace>\\<lambda>tap. tap = ([], <n>)\\<rbrace> copy \\<lbrace>\\<lambda>tap. tap = ([Bk], <(n, n)>)\\<rbrace>)\" ..\n\n  let ?contra = \"copy |+| H |+| dither\"\n  show \"False\"\n  proof cases\n    assume contra_halts: \"halts ?contra (tm_to_nat ?contra)\"\n\n    from c have p1: \"\\<lbrace>\\<lambda>tap. tap = ([], <tm_to_nat ?contra>)\\<rbrace>\n                      copy\n                     \\<lbrace>\\<lambda>tap. tap = ([Bk], <(tm_to_nat ?contra, tm_to_nat ?contra)>)\\<rbrace>\" by simp\n    from h contra_halts have p2: \"\\<lbrace>\\<lambda>tap. tap = ([Bk], <(tm_to_nat ?contra, tm_to_nat ?contra)>)\\<rbrace>\n                                   H\n                                  \\<lbrace>\\<lambda>tap. \\<exists>k l. tap = (Bk \\<up> k, <0::nat>  @ Bk \\<up> l)\\<rbrace>\" unfolding decides_halting_def by presburger\n    from d have p3: \"\\<lbrace>\\<lambda>tap. \\<exists>k l. tap = (Bk \\<up> k, <0::nat>  @ Bk \\<up> l)\\<rbrace> dither \\<up>\" by simp\n\n    from c p1 p2 have p1_2: \"\\<lbrace>\\<lambda>tap. tap = ([], <tm_to_nat ?contra>)\\<rbrace>\n                              copy |+| H\n                             \\<lbrace>\\<lambda>tap. \\<exists>k l. tap = (Bk \\<up> k, <0::nat> @ Bk \\<up> l)\\<rbrace>\" using Hoare_plus_halt by blast\n    from c h p1_2 p3 have \"\\<lbrace>\\<lambda>tap. tap = ([], <tm_to_nat ?contra>)\\<rbrace> ?contra \\<up>\"\n      using Hoare_plus_unhalt decides_halting_def seq_tm_composable by blast\n\n    then show ?thesis using contra_halts halts_def Hoare_unhalt_impl_not_Hoare_halt by blast\n  next\n    assume contra_unhalts: \"\\<not> halts ?contra (tm_to_nat ?contra)\"\n    hence contra_unhalts_unf: \"\\<lbrace>\\<lambda>tap. tap = ([], <tm_to_nat ?contra>)\\<rbrace> ?contra \\<up>\" using not_halts by blast\n\n    from c have p1: \"\\<lbrace>\\<lambda>tap. tap = ([], <tm_to_nat ?contra>)\\<rbrace>\n                      copy\n                     \\<lbrace>\\<lambda>tap. tap = ([Bk], <(tm_to_nat ?contra, tm_to_nat ?contra)>)\\<rbrace>\" by simp\n    from h contra_unhalts have p2: \"\\<lbrace>\\<lambda>tap. tap = ([Bk], <(tm_to_nat ?contra, tm_to_nat ?contra)>)\\<rbrace>\n                                     H\n                                    \\<lbrace>\\<lambda>tap. \\<exists>k l. tap = (Bk \\<up> k, <1::nat> @ Bk \\<up> l)\\<rbrace>\" unfolding decides_halting_def by presburger\n    from d have p3: \"\\<lbrace>\\<lambda>tap. \\<exists>k l. tap = (Bk \\<up> k, <1::nat> @ Bk \\<up> l)\\<rbrace> dither \\<lbrace>\\<lambda>tap. \\<exists>k l. tap = (Bk \\<up> k, <1::nat> @ Bk \\<up> l)\\<rbrace>\" by simp\n\n    from c p1 p2 have p1_2: \"\\<lbrace>\\<lambda>tap. tap = ([], <tm_to_nat ?contra>)\\<rbrace>\n                              copy |+| H\n                             \\<lbrace>\\<lambda>tap. \\<exists>k l. tap = (Bk \\<up> k, <1::nat> @ Bk \\<up> l)\\<rbrace>\" using Hoare_plus_halt by blast\n    from c h p1_2 p3 have \"\\<lbrace>\\<lambda>tap. tap = ([], <tm_to_nat ?contra>)\\<rbrace> ?contra \\<lbrace>\\<lambda>tap. \\<exists>k l. tap = (Bk \\<up> k, <1::nat> @ Bk \\<up> l)\\<rbrace>\"\n      using Hoare_plus_halt decides_halting_def seq_tm_composable by blast\n\n    then show ?thesis using contra_unhalts_unf Hoare_halt_impl_not_Hoare_unhalt by blast\n  qed\nqed\n\ntheorem \"halting_problem\": \"\\<nexists> H. decides_halting H\"\n  using One_nat_def append.simps(1) append.simps(2) replicate.simps(1) replicate.simps(2)\n        tape_of_nat_def tm_copy_correct tm_dither_halts'' tm_dither_loops''\n        halting_problem_assuming_dither_copy\n  by auto\n\n\ntext \\<open>\n  11. Cantor in locales and a new interpretation of the halting problem.\n\\<close>\ndefinition ocomp :: \"(nat\\<rightharpoonup>nat) \\<Rightarrow> (nat\\<rightharpoonup>nat) \\<Rightarrow> (nat\\<rightharpoonup>nat)\" (infixl \"\\<oplus>\" 55) where\n\"ocomp f\\<^sub>1 f\\<^sub>2 x = (case f\\<^sub>2 x of None \\<Rightarrow> None | Some y \\<Rightarrow> f\\<^sub>1 y)\"\n\nlemma ocomp_assoc [simp]: \"a \\<oplus> (b \\<oplus> c) = a \\<oplus> b \\<oplus> c\"\n  unfolding ocomp_def\n  by (metis option.case_eq_if)\n\nlemma \"a \\<oplus> Some = a\"\n  unfolding ocomp_def\n  using option.simps(5) by force\n\nlemma \"(\\<lambda>_.None) \\<oplus> a = (\\<lambda>_.None)\"\n  unfolding ocomp_def\n  by (simp add: option.case_eq_if)\n\nlemma \"a \\<oplus> (\\<lambda>_.None) = (\\<lambda>_.None)\"\n  unfolding ocomp_def\n  by (simp add: option.case_eq_if)\n\nlocale computable_universe_carrier =\n  fixes F :: \"(nat\\<rightharpoonup>nat) set\"\n  fixes pull_up :: \"(nat\\<rightharpoonup>nat) \\<Rightarrow> nat\"\n  \n  assumes countable: \"inj_on pull_up F\"\n  assumes comp_closed: \"\\<lbrakk>a \\<in> F; b \\<in> F\\<rbrakk> \\<Longrightarrow> a \\<oplus> b \\<in> F\"\nbegin\n  definition \"naked_push_down \\<equiv> inv_into F pull_up\"\n  definition \"push_down x = (case x of Some n \\<Rightarrow> (if \\<exists>f. pull_up f = n then naked_push_down n else (\\<lambda>_.None)) | None \\<Rightarrow> (\\<lambda>_.None))\"\n\n  lemma push_pull_inv [simp]: \"\\<forall>f \\<in> F. push_down (Some (pull_up f)) = f\"\n    using countable inv_into_f_f naked_push_down_def option.case(2) push_down_def by force\n\n  lemma sanity_pushing_down_1: \"\\<exists>f. pull_up f = n \\<longrightarrow> push_down (Some n) = f\"\n    by blast\nend\n\nlocale computable_universe_curried = computable_universe_carrier +\n  fixes \\<alpha> \\<Delta> :: \"(nat\\<rightharpoonup>nat)\"\n\n  assumes alpha_in_f: \"\\<alpha> \\<in> F\"\n  assumes alpha: \"\\<alpha> 1 = None\" \"\\<alpha> 0 = Some 1\"\n\n\n  assumes delta_in_f: \"\\<Delta> \\<in> F\"\n  assumes delta: \"\\<And>f. f \\<in> F \\<Longrightarrow> (f \\<oplus> \\<Delta>) x = (push_down (f x)) x\"\nbegin\n  theorem locale_cantor:\n  fixes H :: \"(nat\\<rightharpoonup>nat)\"\n\n  assumes Hf_falls_in_F: \"\\<And>f h. f \\<in> F \\<Longrightarrow> H (pull_up f) = Some (pull_up h) \\<Longrightarrow> h \\<in> F\"\n  assumes H_behaviour: \"\\<forall>f \\<in> F. H (pull_up f) = Some (pull_up (\\<lambda>c. case f c of Some _ \\<Rightarrow> Some 1 | None \\<Rightarrow> Some 0))\"\n\n  shows \"H \\<notin> F\"\n  proof (rule ccontr)\n    assume \"\\<not> (H \\<notin> F)\"\n    hence \"H \\<in> F\" by simp\n\n    define contra where \"contra = \\<alpha> \\<oplus> H \\<oplus> \\<Delta>\"\n    have contra_in_F: \"contra \\<in> F\" by (simp add: \\<open>H \\<in> F\\<close> alpha_in_f comp_closed contra_def delta_in_f)\n\n    have \"\\<forall>h. H (pull_up contra) = Some (pull_up h) \\<longrightarrow> h \\<in> F\" using Hf_falls_in_F contra_in_F\n      by fastforce\n    moreover\n    have h_pull_up_contra: \"H (pull_up contra) = Some (pull_up (\\<lambda>c. case contra c of Some _ \\<Rightarrow> Some 1 | None \\<Rightarrow> Some 0))\"\n      using H_behaviour contra_in_F by presburger\n    ultimately\n    have hcontra_in_F: \"(\\<lambda>c. case contra c of Some _ \\<Rightarrow> Some 1 | None \\<Rightarrow> Some 0) \\<in> F\"\n      by blast\n    \n    have possible_pushed_H: \"\\<And>c. (push_down (H (pull_up contra))) c = Some 1 \\<or> (push_down (H (pull_up contra))) c = Some 0\"\n      by (metis h_pull_up_contra hcontra_in_F option.case_eq_if push_pull_inv)\n\n    show \"False\"\n    proof cases\n      assume one: \"(push_down (H (pull_up contra))) (pull_up contra) = Some 1\"\n\n      hence \"(\\<lambda>c. case contra c of Some _ \\<Rightarrow> Some 1 | None \\<Rightarrow> Some 0) (pull_up contra) = Some 1\"\n        by (metis h_pull_up_contra hcontra_in_F option.case_eq_if option.case_eq_if option.sel push_pull_inv zero_neq_one)\n      hence contra_some: \"\\<exists>n. contra (pull_up contra) = Some n\"\n        using one_neq_zero option.case_eq_if option.collapse option.inject by fastforce\n\n      have \"contra (pull_up contra) = \\<alpha> (the ((H \\<oplus> \\<Delta>) (pull_up contra)))\"\n        by (metis \\<open>H \\<in> F\\<close> alpha(1) contra_def delta ocomp_assoc ocomp_def one option.sel option.simps(5))\n      moreover\n      have \"\\<alpha> (the ((H \\<oplus> \\<Delta>) (pull_up contra))) = \\<alpha> (the (push_down (H (pull_up contra)) (pull_up contra)))\"\n        by (simp add: \\<open>H \\<in> F\\<close> delta)\n      moreover\n      have \"\\<alpha> (the (push_down (H (pull_up contra)) (pull_up contra))) = \\<alpha> 1\"\n        by (simp add: one)\n      ultimately\n      have contra_none: \"contra (pull_up contra) = None\"\n        using alpha(1) by presburger\n      \n      show \"False\" using contra_some contra_none by simp\n    next\n      assume not_one: \"(push_down (H (pull_up contra))) (pull_up contra) \\<noteq> Some 1\"\n\n      hence zero: \"(push_down (H (pull_up contra))) (pull_up contra) = Some 0\"\n        using possible_pushed_H by auto\n      hence \"(\\<lambda>c. case contra c of Some _ \\<Rightarrow> Some 1 | None \\<Rightarrow> Some 0) (pull_up contra) = Some 0\"\n        by (metis not_one h_pull_up_contra hcontra_in_F option.case_eq_if option.case_eq_if push_pull_inv)\n      hence contra_none: \"contra (pull_up contra) = None\"\n        by (smt (verit, ccfv_SIG) not_one option.case_eq_if possible_pushed_H)\n\n      have \"contra (pull_up contra) = \\<alpha> (the ((H \\<oplus> \\<Delta>) (pull_up contra)))\"\n        by (metis \\<open>H \\<in> F\\<close> alpha(2) computable_universe_curried.delta computable_universe_curried_axioms contra_def not_one ocomp_assoc ocomp_def option.sel option.simps(5) possible_pushed_H)\n      moreover\n      have \"\\<alpha> (the ((H \\<oplus> \\<Delta>) (pull_up contra))) = \\<alpha> (the (push_down (H (pull_up contra)) (pull_up contra)))\"\n        by (simp add: \\<open>H \\<in> F\\<close> delta)\n      moreover\n      have \"\\<alpha> (the (push_down (H (pull_up contra)) (pull_up contra))) = \\<alpha> 0\"\n        by (simp add: zero)\n      ultimately\n      have contra_some: \"\\<exists>n. contra (pull_up contra) = Some n\"\n        using alpha(2) by fastforce\n\n      show \"False\" using contra_none contra_some by simp\n    qed\n  qed\nend\n\nlocale computable_universe_paired = computable_universe_carrier +\n  fixes \\<alpha> \\<Delta>:: \"(nat\\<rightharpoonup>nat)\"\n  fixes pair_to_nat :: \"(nat \\<times> nat) \\<Rightarrow> nat\"\n\n  assumes alpha_in_f: \"\\<alpha> \\<in> F\"\n  assumes alpha: \"\\<alpha> 0 = None\" \"\\<alpha> 1 = Some 1\"\n\n\n  assumes delta_in_f: \"\\<Delta> \\<in> F\"\n  assumes delta: \"\\<And>f. f \\<in> F \\<Longrightarrow> (f \\<oplus> \\<Delta>) x = f (pair_to_nat (x, x))\"\nbegin\n  theorem locale_cantor:\n    fixes H :: \"(nat\\<rightharpoonup>nat)\"\n\n    assumes H_behaviour: \"\\<And>f (c::nat). f \\<in> F \\<Longrightarrow>  H (pair_to_nat (pull_up f, c)) = (case f c of Some _ \\<Rightarrow> Some 0 | None \\<Rightarrow> Some 1)\"\n\n    shows \"H \\<notin> F\"\n  proof (rule ccontr)\n    assume \"\\<not> H \\<notin> F\"\n    hence \"H \\<in> F\" by simp\n\n    define contra where \"contra = \\<alpha> \\<oplus> H \\<oplus> \\<Delta>\"\n    have contra_in_F: \"contra \\<in> F\" by (simp add: \\<open>H \\<in> F\\<close> alpha_in_f comp_closed contra_def delta_in_f)\n\n    have possible_H: \"H (pair_to_nat ((pull_up contra), (pull_up contra))) = Some 1 \\<or> H (pair_to_nat ((pull_up contra), (pull_up contra))) = Some 0\"\n      by (simp add: alpha(2) assms contra_in_F option.case_eq_if)\n\n    show \"False\"\n    proof cases\n      assume zero: \"H (pair_to_nat ((pull_up contra), (pull_up contra))) = Some 0\"\n      hence contra_some: \"\\<exists>n. contra (pull_up contra) = Some n\"\n        by (metis UNIV_I assms chi_fun_0_iff chi_fun_1_I contra_in_F option.exhaust_sel option.simps(4))\n\n      have \"contra (pull_up contra) = \\<alpha> (the ((H \\<oplus> \\<Delta>) (pull_up contra)))\"\n        by (metis contra_some contra_def ocomp_assoc ocomp_def option.case_eq_if option.distinct(1) option.simps(4))\n      moreover\n      have \"\\<alpha> (the ((H \\<oplus> \\<Delta>) (pull_up contra))) = \\<alpha> (the (H (pair_to_nat ((pull_up contra), (pull_up contra)))))\"\n        by (simp add: \\<open>H \\<in> F\\<close> delta)\n      moreover\n      have \"\\<alpha> (the (H (pair_to_nat ((pull_up contra), (pull_up contra))))) = \\<alpha> 0\"\n        by (simp add: zero option.sel)\n      ultimately\n      have contra_none: \"contra (pull_up contra) = None\"\n        using alpha(1) by presburger\n\n      show \"False\" using contra_some contra_none by simp\n    next\n      assume not_zero: \"H (pair_to_nat ((pull_up contra), (pull_up contra))) \\<noteq> Some 0\"\n      hence one: \"H (pair_to_nat ((pull_up contra), (pull_up contra))) = Some 1\" using possible_H by blast\n      hence contra_none: \"contra (pull_up contra) = None\"\n        by (metis assms contra_in_F  not_zero option.case_eq_if)\n\n      have \"contra (pull_up contra) = \\<alpha> (the ((H \\<oplus> \\<Delta>) (pull_up contra)))\"\n        by (metis \\<open>H \\<in> F\\<close> contra_def delta ocomp_assoc ocomp_def option.sel option.simps(5) one)\n      moreover\n      have \"\\<alpha> (the ((H \\<oplus> \\<Delta>) (pull_up contra))) = \\<alpha> (the (H (pair_to_nat ((pull_up contra), (pull_up contra)))))\"\n        by (simp add: \\<open>H \\<in> F\\<close> delta)\n      moreover\n      have \"\\<alpha> (the (H (pair_to_nat ((pull_up contra), (pull_up contra))))) = \\<alpha> 1\"\n        by (simp add: one option.sel)\n      ultimately\n      have contra_some: \"\\<exists>n. contra (pull_up contra) = Some n\"\n        using alpha(2) by auto\n\n      show \"False\" using contra_some contra_none by simp\n    qed\n  qed\nend\n\n(*Turing carrier set\n\nImportant note: Blanks and Hoare triples might end up being too complicated of a problem to solve.\nProving the behaviour of functions induced from machines will not be completed due to time-constraints.\nIf it is wished to tackle, it might be a better idea to work with steps0 function to simply compute\nthe end numeral result and return that.\n\nDeprecated def:\n(if (\\<exists>n c (r::nat) k1 k2 l1 l2. is_final (steps0 (1, (Bk \\<up> k1, <inp> @ Bk \\<up> l1)) p n) \\<and> steps0 (1, (Bk \\<up> k1, <inp> @ Bk \\<up> l1)) p n = (c, Bk \\<up> k2, <r> @ Bk \\<up> l2))\n then Some (SOME r. \\<exists>n c k1 k2 l1 l2. steps0 (1, (Bk \\<up> k1, <inp> @ Bk \\<up> l1)) p n = (c, Bk \\<up> k2, <r> @ Bk \\<up> l2))\n else None)*)\ndefinition induce_F_from_tprog0 :: \"tprog0 \\<Rightarrow> nat \\<Rightarrow> nat option\" where\n\"induce_F_from_tprog0 p inp = (if (\\<exists>r. \\<lbrace>\\<lambda>tap. \\<exists>k l. tap = (Bk \\<up> k, <inp> @ Bk \\<up> l)\\<rbrace> p \\<lbrace>\\<lambda>tap. \\<exists>k l. tap = (Bk \\<up> k, <r::nat> @ Bk \\<up> l)\\<rbrace>)\n                               then Some (THE r. \\<exists>k l. steps0 (1, ([], <inp>)) p (SOME n. is_final (steps0 (1, ([], <inp>)) p n)) = (0, (Bk \\<up> k, <r> @ Bk \\<up> l)))\n                               else None)\"\n\n(*For all possible numeral input tapes the Turing machines we are interested in return numeral output*)\ndefinition numeral_tm0 :: \"tprog0 \\<Rightarrow> bool\" where\n\"numeral_tm0 p = (let numeral_tape = \\<lambda>tap. \\<exists>k l (n::nat). tap = (Bk \\<up> k, <n> @ Bk \\<up> l)\n                  in \\<lbrace>numeral_tape\\<rbrace> p \\<lbrace>numeral_tape\\<rbrace> \\<or> \\<lbrace>numeral_tape\\<rbrace> p \\<up>)\"\n                                               \ndefinition \"numeral_composable_tm0 p \\<equiv> composable_tm0 p \\<and> numeral_tm0 p\"\n\nlemma sq_num_comp_tm0: \"\\<lbrakk>numeral_composable_tm0 p1; numeral_composable_tm0 p2\\<rbrakk> \\<Longrightarrow> numeral_composable_tm0 (p1 |+| p2)\"\n  by (metis (no_types, lifting) Hoare_plus_halt Hoare_plus_unhalt Hoare_unhalt_def numeral_composable_tm0_def numeral_tm0_def seq_tm_composable seq_tm_steps)\n\ndefinition turing_F :: \"(nat\\<rightharpoonup>nat) set\" where\n\"turing_F = induce_F_from_tprog0 ` {p. numeral_composable_tm0 p}\"\n\nlemma composable_tprog_in_turing_F: \"\\<And>p. numeral_composable_tm0 p \\<Longrightarrow> induce_F_from_tprog0 p \\<in> turing_F\"\n  by (simp add: image_eqI turing_F_def)\n\n(*Carrier set functions back to Turing and then to nat*)\ndefinition turing_pull_up :: \"(nat\\<rightharpoonup>nat) \\<Rightarrow> nat\" where\n\"turing_pull_up f = (if f \\<in> turing_F then tm_to_nat (SOME p. induce_F_from_tprog0 p = f) else 0)\"\n\nlemma countable_turing_F: \"inj_on turing_pull_up turing_F\"\n  unfolding inj_on_def turing_pull_up_def using inj_tm_to_nat\n  by (smt (verit, del_insts) Collect_cong Collect_mem_eq Eps_cong UNIV_I UNIV_def\n      imageE mem_Collect_eq nat_to_tm_is_inv_of_tm_to_nat someI_ex some_eq_ex turing_F_def\n      turing_pull_up_def verit_sko_ex' verit_sko_forall)\n\n(*turing_F closed under \\<oplus> and equivalent with |+|*)\nlemma turing_F_from_composable_tm: \"\\<And>a. a \\<in> turing_F \\<Longrightarrow> \\<exists>p. (numeral_composable_tm0 p) \\<and> (induce_F_from_tprog0 p = a)\"\n  by (metis (no_types, lifting) f_inv_into_f inv_into_into mem_Collect_eq turing_F_def)\n\nlemma seq_tm_stays_in_turing_F: \"\\<And>p1 p2. numeral_composable_tm0 p1 \\<Longrightarrow> numeral_composable_tm0 p2 \\<Longrightarrow> induce_F_from_tprog0 (p2 |+| p1) \\<in> turing_F\"\n  using sq_num_comp_tm0 composable_tprog_in_turing_F by blast\n\nlemma seq_tm_oplus_correspondence: \"\\<And>p1 p2. numeral_composable_tm0 p1 \\<Longrightarrow> numeral_composable_tm0 p2 \\<Longrightarrow>\n        induce_F_from_tprog0 (p2 |+| p1) = (induce_F_from_tprog0 p1) \\<oplus> (induce_F_from_tprog0 p2)\"\n  sorry\n\nlemma closed_turing_F: \"\\<And>a b. a \\<in> turing_F \\<Longrightarrow> b \\<in> turing_F \\<Longrightarrow> a \\<oplus> b \\<in> turing_F\"\n  by (metis seq_tm_oplus_correspondence seq_tm_stays_in_turing_F turing_F_from_composable_tm)\n\n(*Invoke the first half*)\ninterpretation computable_universe_carrier turing_F turing_pull_up\n  apply unfold_locales\n  apply (simp add: countable_turing_F)\n  apply (simp add: closed_turing_F)\n  done\n\nlemma countable_tape: \"from_nat (to_nat (tp::tape)) = tp\"\n  by simp\n\nfun pair_plus :: \"(nat \\<times> nat) \\<Rightarrow> nat\" where\n\"pair_plus (t1, t2) = t1 + t2\"\n\nlemma numeral_composable_tm0_tm_dither: \"numeral_composable_tm0 tm_dither\"\n  unfolding numeral_composable_tm0_def using composable_tm0_tm_dither\n  sorry\n\ndefinition tm_doubling :: \"tprog0\" where\n\"tm_doubling = [(WO, 2), (R, 1), (L, 3), (R, 2), (WB, 4), (WB, 4), (L, 5), (L, 5), (R, 0), (L, 5)]\"\n\nlemma composable_tm0_tm_doubling[intro, simp]: \"composable_tm0 tm_doubling\"\n  by (auto simp: tm_doubling_def)\n\nlemma tm_doubling_removes_Bk: \"\\<lbrace>\\<lambda>tap. tap = ([Bk], <(x::nat, x)>)\\<rbrace> tm_doubling \\<lbrace>\\<lambda>tap. \\<exists>l. tap = ([Bk], <(x + x)> @ Bk \\<up> l)\\<rbrace>\"\n  sorry\n\ndefinition \"tm_modified_copy = tm_copy |+| tm_doubling\"\n\nlemma composable_tm0_tm_modified_copy[intro, simp]: \"composable_tm0 tm_modified_copy\"\n  by (metis composable_tm0_tm_copy composable_tm0_tm_doubling seq_tm_composable tm_modified_copy_def)\n\nlemma oc_arrow_to_encode[intro, simp]: \"Oc \\<up> (Suc n) = <n>\"\n  by (simp add: tape_of_nat_def)\n\nlemma tm_modified_copy_hoare: \"\\<lbrace>\\<lambda>tap. tap = ([], <x::nat>)\\<rbrace> tm_modified_copy \\<lbrace>\\<lambda>tap. \\<exists>l. tap = ([Bk], <(x + x)> @ Bk \\<up> l)\\<rbrace>\"\n  using tm_modified_copy_def tm_doubling_removes_Bk tm_copy_correct oc_arrow_to_encode\n  Hoare_plus_halt composable_tm0_tm_copy Hoare_halt_def\n  by (metis (no_types, lifting))\n\nlemma numeral_composable_tm0_tm_modified_copy[intro, simp]: \"numeral_composable_tm0 tm_modified_copy\"\n  sorry\n\n(*inducing functions*)\ndefinition \"turing_dither = induce_F_from_tprog0 tm_dither\"\n\nlemma turing_dither_in_turing_F: \"turing_dither \\<in> turing_F\"\n  unfolding turing_dither_def\n  using numeral_composable_tm0_tm_dither composable_tprog_in_turing_F\n  by presburger\n\ndefinition \"turing_copy = induce_F_from_tprog0 tm_modified_copy\"\n\nlemma turing_copy_in_turing_F: \"turing_copy \\<in> turing_F\"\n  using numeral_composable_tm0_tm_modified_copy composable_tprog_in_turing_F turing_copy_def\n  by presburger\n\n(*dither and copy behaviour*)\nlemma turing_dither_halts: \"turing_dither 1 = Some 1\"\n  sorry\n\nlemma turing_dither_loops: \"turing_dither 0 = None\"\n  sorry\n\nlemma turing_copy_pair_plus: \"turing_copy x = Some (pair_plus (x, x))\"\n  sorry\n\nlemma turing_copy_composed: \"\\<And>f x. f \\<in> turing_F \\<Longrightarrow> (f \\<oplus> turing_copy) x = f (pair_plus (x, x))\"\n  by (simp add: ocomp_def turing_copy_pair_plus)\n\n(*Invoke the second half*)\ninterpretation computable_universe_paired turing_F turing_pull_up turing_dither turing_copy pair_plus\n  apply unfold_locales\n  using turing_dither_in_turing_F apply simp\n  using turing_dither_loops apply simp\n  using One_nat_def turing_dither_halts apply fastforce\n  using turing_copy_in_turing_F apply simp\n  using turing_copy_composed apply simp\n  done\n\nend\n", "meta": {"author": "Chmlgy", "repo": "generalized_cantor", "sha": "master", "save_path": "github-repos/isabelle/Chmlgy-generalized_cantor", "path": "github-repos/isabelle/Chmlgy-generalized_cantor/generalized_cantor-main/GeneralCantor.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8740772318846386, "lm_q2_score": 0.8152324938410783, "lm_q1q2_score": 0.7125761615590204}}
{"text": "(*  Title:      HOL/Algebra/Coset.thy\n    Author:     Florian Kammueller\n    Author:     L C Paulson\n    Author:     Stephan Hohe\n*)\n\ntheory Coset\nimports Group\nbegin\n\nsection {*Cosets and Quotient Groups*}\n\ndefinition\n  r_coset    :: \"[_, 'a set, 'a] \\<Rightarrow> 'a set\"    (infixl \"#>\\<index>\" 60)\n  where \"H #>\\<^bsub>G\\<^esub> a = (\\<Union>h\\<in>H. {h \\<otimes>\\<^bsub>G\\<^esub> a})\"\n\ndefinition\n  l_coset    :: \"[_, 'a, 'a set] \\<Rightarrow> 'a set\"    (infixl \"<#\\<index>\" 60)\n  where \"a <#\\<^bsub>G\\<^esub> H = (\\<Union>h\\<in>H. {a \\<otimes>\\<^bsub>G\\<^esub> h})\"\n\ndefinition\n  RCOSETS  :: \"[_, 'a set] \\<Rightarrow> ('a set)set\"   (\"rcosets\\<index> _\" [81] 80)\n  where \"rcosets\\<^bsub>G\\<^esub> H = (\\<Union>a\\<in>carrier G. {H #>\\<^bsub>G\\<^esub> a})\"\n\ndefinition\n  set_mult  :: \"[_, 'a set ,'a set] \\<Rightarrow> 'a set\" (infixl \"<#>\\<index>\" 60)\n  where \"H <#>\\<^bsub>G\\<^esub> K = (\\<Union>h\\<in>H. \\<Union>k\\<in>K. {h \\<otimes>\\<^bsub>G\\<^esub> k})\"\n\ndefinition\n  SET_INV :: \"[_,'a set] \\<Rightarrow> 'a set\"  (\"set'_inv\\<index> _\" [81] 80)\n  where \"set_inv\\<^bsub>G\\<^esub> H = (\\<Union>h\\<in>H. {inv\\<^bsub>G\\<^esub> h})\"\n\n\nlocale normal = subgroup + group +\n  assumes coset_eq: \"(\\<forall>x \\<in> carrier G. H #> x = x <# H)\"\n\nabbreviation\n  normal_rel :: \"['a set, ('a, 'b) monoid_scheme] \\<Rightarrow> bool\"  (infixl \"\\<lhd>\" 60) where\n  \"H \\<lhd> G \\<equiv> normal H G\"\n\n\nsubsection {*Basic Properties of Cosets*}\n\nlemma (in group) coset_mult_assoc:\n     \"[| M \\<subseteq> carrier G; g \\<in> carrier G; h \\<in> carrier G |]\n      ==> (M #> g) #> h = M #> (g \\<otimes> h)\"\nby (force simp add: r_coset_def m_assoc)\n\nlemma (in group) coset_mult_one [simp]: \"M \\<subseteq> carrier G ==> M #> \\<one> = M\"\nby (force simp add: r_coset_def)\n\nlemma (in group) coset_mult_inv1:\n     \"[| M #> (x \\<otimes> (inv y)) = M;  x \\<in> carrier G ; y \\<in> carrier G;\n         M \\<subseteq> carrier G |] ==> M #> x = M #> y\"\napply (erule subst [of concl: \"%z. M #> x = z #> y\"])\napply (simp add: coset_mult_assoc m_assoc)\ndone\n\nlemma (in group) coset_mult_inv2:\n     \"[| M #> x = M #> y;  x \\<in> carrier G;  y \\<in> carrier G;  M \\<subseteq> carrier G |]\n      ==> M #> (x \\<otimes> (inv y)) = M \"\napply (simp add: coset_mult_assoc [symmetric])\napply (simp add: coset_mult_assoc)\ndone\n\nlemma (in group) coset_join1:\n     \"[| H #> x = H;  x \\<in> carrier G;  subgroup H G |] ==> x \\<in> H\"\napply (erule subst)\napply (simp add: r_coset_def)\napply (blast intro: l_one subgroup.one_closed sym)\ndone\n\nlemma (in group) solve_equation:\n    \"\\<lbrakk>subgroup H G; x \\<in> H; y \\<in> H\\<rbrakk> \\<Longrightarrow> \\<exists>h\\<in>H. y = h \\<otimes> x\"\napply (rule bexI [of _ \"y \\<otimes> (inv x)\"])\napply (auto simp add: subgroup.m_closed subgroup.m_inv_closed m_assoc\n                      subgroup.subset [THEN subsetD])\ndone\n\nlemma (in group) repr_independence:\n     \"\\<lbrakk>y \\<in> H #> x;  x \\<in> carrier G; subgroup H G\\<rbrakk> \\<Longrightarrow> H #> x = H #> y\"\nby (auto simp add: r_coset_def m_assoc [symmetric]\n                   subgroup.subset [THEN subsetD]\n                   subgroup.m_closed solve_equation)\n\nlemma (in group) coset_join2:\n     \"\\<lbrakk>x \\<in> carrier G;  subgroup H G;  x\\<in>H\\<rbrakk> \\<Longrightarrow> H #> x = H\"\n  --{*Alternative proof is to put @{term \"x=\\<one>\"} in @{text repr_independence}.*}\nby (force simp add: subgroup.m_closed r_coset_def solve_equation)\n\nlemma (in monoid) r_coset_subset_G:\n     \"[| H \\<subseteq> carrier G; x \\<in> carrier G |] ==> H #> x \\<subseteq> carrier G\"\nby (auto simp add: r_coset_def)\n\nlemma (in group) rcosI:\n     \"[| h \\<in> H; H \\<subseteq> carrier G; x \\<in> carrier G|] ==> h \\<otimes> x \\<in> H #> x\"\nby (auto simp add: r_coset_def)\n\nlemma (in group) rcosetsI:\n     \"\\<lbrakk>H \\<subseteq> carrier G; x \\<in> carrier G\\<rbrakk> \\<Longrightarrow> H #> x \\<in> rcosets H\"\nby (auto simp add: RCOSETS_def)\n\ntext{*Really needed?*}\nlemma (in group) transpose_inv:\n     \"[| x \\<otimes> y = z;  x \\<in> carrier G;  y \\<in> carrier G;  z \\<in> carrier G |]\n      ==> (inv x) \\<otimes> z = y\"\nby (force simp add: m_assoc [symmetric])\n\nlemma (in group) rcos_self: \"[| x \\<in> carrier G; subgroup H G |] ==> x \\<in> H #> x\"\napply (simp add: r_coset_def)\napply (blast intro: sym l_one subgroup.subset [THEN subsetD]\n                    subgroup.one_closed)\ndone\n\ntext (in group) {* Opposite of @{thm [source] \"repr_independence\"} *}\nlemma (in group) repr_independenceD:\n  assumes \"subgroup H G\"\n  assumes ycarr: \"y \\<in> carrier G\"\n      and repr:  \"H #> x = H #> y\"\n  shows \"y \\<in> H #> x\"\nproof -\n  interpret subgroup H G by fact\n  show ?thesis  apply (subst repr)\n  apply (intro rcos_self)\n   apply (rule ycarr)\n   apply (rule is_subgroup)\n  done\nqed\n\ntext {* Elements of a right coset are in the carrier *}\nlemma (in subgroup) elemrcos_carrier:\n  assumes \"group G\"\n  assumes acarr: \"a \\<in> carrier G\"\n    and a': \"a' \\<in> H #> a\"\n  shows \"a' \\<in> carrier G\"\nproof -\n  interpret group G by fact\n  from subset and acarr\n  have \"H #> a \\<subseteq> carrier G\" by (rule r_coset_subset_G)\n  from this and a'\n  show \"a' \\<in> carrier G\"\n    by fast\nqed\n\nlemma (in subgroup) rcos_const:\n  assumes \"group G\"\n  assumes hH: \"h \\<in> H\"\n  shows \"H #> h = H\"\nproof -\n  interpret group G by fact\n  show ?thesis apply (unfold r_coset_def)\n    apply rule\n    apply rule\n    apply clarsimp\n    apply (intro subgroup.m_closed)\n    apply (rule is_subgroup)\n    apply assumption\n    apply (rule hH)\n    apply rule\n    apply simp\n  proof -\n    fix h'\n    assume h'H: \"h' \\<in> H\"\n    note carr = hH[THEN mem_carrier] h'H[THEN mem_carrier]\n    from carr\n    have a: \"h' = (h' \\<otimes> inv h) \\<otimes> h\" by (simp add: m_assoc)\n    from h'H hH\n    have \"h' \\<otimes> inv h \\<in> H\" by simp\n    from this and a\n    show \"\\<exists>x\\<in>H. h' = x \\<otimes> h\" by fast\n  qed\nqed\n\ntext {* Step one for lemma @{text \"rcos_module\"} *}\nlemma (in subgroup) rcos_module_imp:\n  assumes \"group G\"\n  assumes xcarr: \"x \\<in> carrier G\"\n      and x'cos: \"x' \\<in> H #> x\"\n  shows \"(x' \\<otimes> inv x) \\<in> H\"\nproof -\n  interpret group G by fact\n  from xcarr x'cos\n      have x'carr: \"x' \\<in> carrier G\"\n      by (rule elemrcos_carrier[OF is_group])\n  from xcarr\n      have ixcarr: \"inv x \\<in> carrier G\"\n      by simp\n  from x'cos\n      have \"\\<exists>h\\<in>H. x' = h \\<otimes> x\"\n      unfolding r_coset_def\n      by fast\n  from this\n      obtain h\n        where hH: \"h \\<in> H\"\n        and x': \"x' = h \\<otimes> x\"\n      by auto\n  from hH and subset\n      have hcarr: \"h \\<in> carrier G\" by fast\n  note carr = xcarr x'carr hcarr\n  from x' and carr\n      have \"x' \\<otimes> (inv x) = (h \\<otimes> x) \\<otimes> (inv x)\" by fast\n  also from carr\n      have \"\\<dots> = h \\<otimes> (x \\<otimes> inv x)\" by (simp add: m_assoc)\n  also from carr\n      have \"\\<dots> = h \\<otimes> \\<one>\" by simp\n  also from carr\n      have \"\\<dots> = h\" by simp\n  finally\n      have \"x' \\<otimes> (inv x) = h\" by simp\n  from hH this\n      show \"x' \\<otimes> (inv x) \\<in> H\" by simp\nqed\n\ntext {* Step two for lemma @{text \"rcos_module\"} *}\nlemma (in subgroup) rcos_module_rev:\n  assumes \"group G\"\n  assumes carr: \"x \\<in> carrier G\" \"x' \\<in> carrier G\"\n      and xixH: \"(x' \\<otimes> inv x) \\<in> H\"\n  shows \"x' \\<in> H #> x\"\nproof -\n  interpret group G by fact\n  from xixH\n      have \"\\<exists>h\\<in>H. x' \\<otimes> (inv x) = h\" by fast\n  from this\n      obtain h\n        where hH: \"h \\<in> H\"\n        and hsym: \"x' \\<otimes> (inv x) = h\"\n      by fast\n  from hH subset have hcarr: \"h \\<in> carrier G\" by simp\n  note carr = carr hcarr\n  from hsym[symmetric] have \"h \\<otimes> x = x' \\<otimes> (inv x) \\<otimes> x\" by fast\n  also from carr\n      have \"\\<dots> = x' \\<otimes> ((inv x) \\<otimes> x)\" by (simp add: m_assoc)\n  also from carr\n      have \"\\<dots> = x' \\<otimes> \\<one>\" by simp\n  also from carr\n      have \"\\<dots> = x'\" by simp\n  finally\n      have \"h \\<otimes> x = x'\" by simp\n  from this[symmetric] and hH\n      show \"x' \\<in> H #> x\"\n      unfolding r_coset_def\n      by fast\nqed\n\ntext {* Module property of right cosets *}\nlemma (in subgroup) rcos_module:\n  assumes \"group G\"\n  assumes carr: \"x \\<in> carrier G\" \"x' \\<in> carrier G\"\n  shows \"(x' \\<in> H #> x) = (x' \\<otimes> inv x \\<in> H)\"\nproof -\n  interpret group G by fact\n  show ?thesis proof  assume \"x' \\<in> H #> x\"\n    from this and carr\n    show \"x' \\<otimes> inv x \\<in> H\"\n      by (intro rcos_module_imp[OF is_group])\n  next\n    assume \"x' \\<otimes> inv x \\<in> H\"\n    from this and carr\n    show \"x' \\<in> H #> x\"\n      by (intro rcos_module_rev[OF is_group])\n  qed\nqed\n\ntext {* Right cosets are subsets of the carrier. *} \nlemma (in subgroup) rcosets_carrier:\n  assumes \"group G\"\n  assumes XH: \"X \\<in> rcosets H\"\n  shows \"X \\<subseteq> carrier G\"\nproof -\n  interpret group G by fact\n  from XH have \"\\<exists>x\\<in> carrier G. X = H #> x\"\n      unfolding RCOSETS_def\n      by fast\n  from this\n      obtain x\n        where xcarr: \"x\\<in> carrier G\"\n        and X: \"X = H #> x\"\n      by fast\n  from subset and xcarr\n      show \"X \\<subseteq> carrier G\"\n      unfolding X\n      by (rule r_coset_subset_G)\nqed\n\ntext {* Multiplication of general subsets *}\nlemma (in monoid) set_mult_closed:\n  assumes Acarr: \"A \\<subseteq> carrier G\"\n      and Bcarr: \"B \\<subseteq> carrier G\"\n  shows \"A <#> B \\<subseteq> carrier G\"\napply rule apply (simp add: set_mult_def, clarsimp)\nproof -\n  fix a b\n  assume \"a \\<in> A\"\n  from this and Acarr\n      have acarr: \"a \\<in> carrier G\" by fast\n\n  assume \"b \\<in> B\"\n  from this and Bcarr\n      have bcarr: \"b \\<in> carrier G\" by fast\n\n  from acarr bcarr\n      show \"a \\<otimes> b \\<in> carrier G\" by (rule m_closed)\nqed\n\nlemma (in comm_group) mult_subgroups:\n  assumes subH: \"subgroup H G\"\n      and subK: \"subgroup K G\"\n  shows \"subgroup (H <#> K) G\"\napply (rule subgroup.intro)\n   apply (intro set_mult_closed subgroup.subset[OF subH] subgroup.subset[OF subK])\n  apply (simp add: set_mult_def) apply clarsimp defer 1\n  apply (simp add: set_mult_def) defer 1\n  apply (simp add: set_mult_def, clarsimp) defer 1\nproof -\n  fix ha hb ka kb\n  assume haH: \"ha \\<in> H\" and hbH: \"hb \\<in> H\" and kaK: \"ka \\<in> K\" and kbK: \"kb \\<in> K\"\n  note carr = haH[THEN subgroup.mem_carrier[OF subH]] hbH[THEN subgroup.mem_carrier[OF subH]]\n              kaK[THEN subgroup.mem_carrier[OF subK]] kbK[THEN subgroup.mem_carrier[OF subK]]\n  from carr\n      have \"(ha \\<otimes> ka) \\<otimes> (hb \\<otimes> kb) = ha \\<otimes> (ka \\<otimes> hb) \\<otimes> kb\" by (simp add: m_assoc)\n  also from carr\n      have \"\\<dots> = ha \\<otimes> (hb \\<otimes> ka) \\<otimes> kb\" by (simp add: m_comm)\n  also from carr\n      have \"\\<dots> = (ha \\<otimes> hb) \\<otimes> (ka \\<otimes> kb)\" by (simp add: m_assoc)\n  finally\n      have eq: \"(ha \\<otimes> ka) \\<otimes> (hb \\<otimes> kb) = (ha \\<otimes> hb) \\<otimes> (ka \\<otimes> kb)\" .\n\n  from haH hbH have hH: \"ha \\<otimes> hb \\<in> H\" by (simp add: subgroup.m_closed[OF subH])\n  from kaK kbK have kK: \"ka \\<otimes> kb \\<in> K\" by (simp add: subgroup.m_closed[OF subK])\n  \n  from hH and kK and eq\n      show \"\\<exists>h'\\<in>H. \\<exists>k'\\<in>K. (ha \\<otimes> ka) \\<otimes> (hb \\<otimes> kb) = h' \\<otimes> k'\" by fast\nnext\n  have \"\\<one> = \\<one> \\<otimes> \\<one>\" by simp\n  from subgroup.one_closed[OF subH] subgroup.one_closed[OF subK] this\n      show \"\\<exists>h\\<in>H. \\<exists>k\\<in>K. \\<one> = h \\<otimes> k\" by fast\nnext\n  fix h k\n  assume hH: \"h \\<in> H\"\n     and kK: \"k \\<in> K\"\n\n  from hH[THEN subgroup.mem_carrier[OF subH]] kK[THEN subgroup.mem_carrier[OF subK]]\n      have \"inv (h \\<otimes> k) = inv h \\<otimes> inv k\" by (simp add: inv_mult_group m_comm)\n\n  from subgroup.m_inv_closed[OF subH hH] and subgroup.m_inv_closed[OF subK kK] and this\n      show \"\\<exists>ha\\<in>H. \\<exists>ka\\<in>K. inv (h \\<otimes> k) = ha \\<otimes> ka\" by fast\nqed\n\nlemma (in subgroup) lcos_module_rev:\n  assumes \"group G\"\n  assumes carr: \"x \\<in> carrier G\" \"x' \\<in> carrier G\"\n      and xixH: \"(inv x \\<otimes> x') \\<in> H\"\n  shows \"x' \\<in> x <# H\"\nproof -\n  interpret group G by fact\n  from xixH\n      have \"\\<exists>h\\<in>H. (inv x) \\<otimes> x' = h\" by fast\n  from this\n      obtain h\n        where hH: \"h \\<in> H\"\n        and hsym: \"(inv x) \\<otimes> x' = h\"\n      by fast\n\n  from hH subset have hcarr: \"h \\<in> carrier G\" by simp\n  note carr = carr hcarr\n  from hsym[symmetric] have \"x \\<otimes> h = x \\<otimes> ((inv x) \\<otimes> x')\" by fast\n  also from carr\n      have \"\\<dots> = (x \\<otimes> (inv x)) \\<otimes> x'\" by (simp add: m_assoc[symmetric])\n  also from carr\n      have \"\\<dots> = \\<one> \\<otimes> x'\" by simp\n  also from carr\n      have \"\\<dots> = x'\" by simp\n  finally\n      have \"x \\<otimes> h = x'\" by simp\n\n  from this[symmetric] and hH\n      show \"x' \\<in> x <# H\"\n      unfolding l_coset_def\n      by fast\nqed\n\n\nsubsection {* Normal subgroups *}\n\nlemma normal_imp_subgroup: \"H \\<lhd> G \\<Longrightarrow> subgroup H G\"\n  by (simp add: normal_def subgroup_def)\n\nlemma (in group) normalI: \n  \"subgroup H G \\<Longrightarrow> (\\<forall>x \\<in> carrier G. H #> x = x <# H) \\<Longrightarrow> H \\<lhd> G\"\n  by (simp add: normal_def normal_axioms_def is_group)\n\nlemma (in normal) inv_op_closed1:\n     \"\\<lbrakk>x \\<in> carrier G; h \\<in> H\\<rbrakk> \\<Longrightarrow> (inv x) \\<otimes> h \\<otimes> x \\<in> H\"\napply (insert coset_eq) \napply (auto simp add: l_coset_def r_coset_def)\napply (drule bspec, assumption)\napply (drule equalityD1 [THEN subsetD], blast, clarify)\napply (simp add: m_assoc)\napply (simp add: m_assoc [symmetric])\ndone\n\nlemma (in normal) inv_op_closed2:\n     \"\\<lbrakk>x \\<in> carrier G; h \\<in> H\\<rbrakk> \\<Longrightarrow> x \\<otimes> h \\<otimes> (inv x) \\<in> H\"\napply (subgoal_tac \"inv (inv x) \\<otimes> h \\<otimes> (inv x) \\<in> H\") \napply (simp add: ) \napply (blast intro: inv_op_closed1) \ndone\n\ntext{*Alternative characterization of normal subgroups*}\nlemma (in group) normal_inv_iff:\n     \"(N \\<lhd> G) = \n      (subgroup N G & (\\<forall>x \\<in> carrier G. \\<forall>h \\<in> N. x \\<otimes> h \\<otimes> (inv x) \\<in> N))\"\n      (is \"_ = ?rhs\")\nproof\n  assume N: \"N \\<lhd> G\"\n  show ?rhs\n    by (blast intro: N normal.inv_op_closed2 normal_imp_subgroup) \nnext\n  assume ?rhs\n  hence sg: \"subgroup N G\" \n    and closed: \"\\<And>x. x\\<in>carrier G \\<Longrightarrow> \\<forall>h\\<in>N. x \\<otimes> h \\<otimes> inv x \\<in> N\" by auto\n  hence sb: \"N \\<subseteq> carrier G\" by (simp add: subgroup.subset) \n  show \"N \\<lhd> G\"\n  proof (intro normalI [OF sg], simp add: l_coset_def r_coset_def, clarify)\n    fix x\n    assume x: \"x \\<in> carrier G\"\n    show \"(\\<Union>h\\<in>N. {h \\<otimes> x}) = (\\<Union>h\\<in>N. {x \\<otimes> h})\"\n    proof\n      show \"(\\<Union>h\\<in>N. {h \\<otimes> x}) \\<subseteq> (\\<Union>h\\<in>N. {x \\<otimes> h})\"\n      proof clarify\n        fix n\n        assume n: \"n \\<in> N\" \n        show \"n \\<otimes> x \\<in> (\\<Union>h\\<in>N. {x \\<otimes> h})\"\n        proof \n          from closed [of \"inv x\"]\n          show \"inv x \\<otimes> n \\<otimes> x \\<in> N\" by (simp add: x n)\n          show \"n \\<otimes> x \\<in> {x \\<otimes> (inv x \\<otimes> n \\<otimes> x)}\"\n            by (simp add: x n m_assoc [symmetric] sb [THEN subsetD])\n        qed\n      qed\n    next\n      show \"(\\<Union>h\\<in>N. {x \\<otimes> h}) \\<subseteq> (\\<Union>h\\<in>N. {h \\<otimes> x})\"\n      proof clarify\n        fix n\n        assume n: \"n \\<in> N\" \n        show \"x \\<otimes> n \\<in> (\\<Union>h\\<in>N. {h \\<otimes> x})\"\n        proof \n          show \"x \\<otimes> n \\<otimes> inv x \\<in> N\" by (simp add: x n closed)\n          show \"x \\<otimes> n \\<in> {x \\<otimes> n \\<otimes> inv x \\<otimes> x}\"\n            by (simp add: x n m_assoc sb [THEN subsetD])\n        qed\n      qed\n    qed\n  qed\nqed\n\n\nsubsection{*More Properties of Cosets*}\n\nlemma (in group) lcos_m_assoc:\n     \"[| M \\<subseteq> carrier G; g \\<in> carrier G; h \\<in> carrier G |]\n      ==> g <# (h <# M) = (g \\<otimes> h) <# M\"\nby (force simp add: l_coset_def m_assoc)\n\nlemma (in group) lcos_mult_one: \"M \\<subseteq> carrier G ==> \\<one> <# M = M\"\nby (force simp add: l_coset_def)\n\nlemma (in group) l_coset_subset_G:\n     \"[| H \\<subseteq> carrier G; x \\<in> carrier G |] ==> x <# H \\<subseteq> carrier G\"\nby (auto simp add: l_coset_def subsetD)\n\nlemma (in group) l_coset_swap:\n     \"\\<lbrakk>y \\<in> x <# H;  x \\<in> carrier G;  subgroup H G\\<rbrakk> \\<Longrightarrow> x \\<in> y <# H\"\nproof (simp add: l_coset_def)\n  assume \"\\<exists>h\\<in>H. y = x \\<otimes> h\"\n    and x: \"x \\<in> carrier G\"\n    and sb: \"subgroup H G\"\n  then obtain h' where h': \"h' \\<in> H & x \\<otimes> h' = y\" by blast\n  show \"\\<exists>h\\<in>H. x = y \\<otimes> h\"\n  proof\n    show \"x = y \\<otimes> inv h'\" using h' x sb\n      by (auto simp add: m_assoc subgroup.subset [THEN subsetD])\n    show \"inv h' \\<in> H\" using h' sb\n      by (auto simp add: subgroup.subset [THEN subsetD] subgroup.m_inv_closed)\n  qed\nqed\n\nlemma (in group) l_coset_carrier:\n     \"[| y \\<in> x <# H;  x \\<in> carrier G;  subgroup H G |] ==> y \\<in> carrier G\"\nby (auto simp add: l_coset_def m_assoc\n                   subgroup.subset [THEN subsetD] subgroup.m_closed)\n\nlemma (in group) l_repr_imp_subset:\n  assumes y: \"y \\<in> x <# H\" and x: \"x \\<in> carrier G\" and sb: \"subgroup H G\"\n  shows \"y <# H \\<subseteq> x <# H\"\nproof -\n  from y\n  obtain h' where \"h' \\<in> H\" \"x \\<otimes> h' = y\" by (auto simp add: l_coset_def)\n  thus ?thesis using x sb\n    by (auto simp add: l_coset_def m_assoc\n                       subgroup.subset [THEN subsetD] subgroup.m_closed)\nqed\n\nlemma (in group) l_repr_independence:\n  assumes y: \"y \\<in> x <# H\" and x: \"x \\<in> carrier G\" and sb: \"subgroup H G\"\n  shows \"x <# H = y <# H\"\nproof\n  show \"x <# H \\<subseteq> y <# H\"\n    by (rule l_repr_imp_subset,\n        (blast intro: l_coset_swap l_coset_carrier y x sb)+)\n  show \"y <# H \\<subseteq> x <# H\" by (rule l_repr_imp_subset [OF y x sb])\nqed\n\nlemma (in group) setmult_subset_G:\n     \"\\<lbrakk>H \\<subseteq> carrier G; K \\<subseteq> carrier G\\<rbrakk> \\<Longrightarrow> H <#> K \\<subseteq> carrier G\"\nby (auto simp add: set_mult_def subsetD)\n\nlemma (in group) subgroup_mult_id: \"subgroup H G \\<Longrightarrow> H <#> H = H\"\napply (auto simp add: subgroup.m_closed set_mult_def Sigma_def image_def)\napply (rule_tac x = x in bexI)\napply (rule bexI [of _ \"\\<one>\"])\napply (auto simp add: subgroup.one_closed subgroup.subset [THEN subsetD])\ndone\n\n\nsubsubsection {* Set of Inverses of an @{text r_coset}. *}\n\nlemma (in normal) rcos_inv:\n  assumes x:     \"x \\<in> carrier G\"\n  shows \"set_inv (H #> x) = H #> (inv x)\" \nproof (simp add: r_coset_def SET_INV_def x inv_mult_group, safe)\n  fix h\n  assume h: \"h \\<in> H\"\n  show \"inv x \\<otimes> inv h \\<in> (\\<Union>j\\<in>H. {j \\<otimes> inv x})\"\n  proof\n    show \"inv x \\<otimes> inv h \\<otimes> x \\<in> H\"\n      by (simp add: inv_op_closed1 h x)\n    show \"inv x \\<otimes> inv h \\<in> {inv x \\<otimes> inv h \\<otimes> x \\<otimes> inv x}\"\n      by (simp add: h x m_assoc)\n  qed\n  show \"h \\<otimes> inv x \\<in> (\\<Union>j\\<in>H. {inv x \\<otimes> inv j})\"\n  proof\n    show \"x \\<otimes> inv h \\<otimes> inv x \\<in> H\"\n      by (simp add: inv_op_closed2 h x)\n    show \"h \\<otimes> inv x \\<in> {inv x \\<otimes> inv (x \\<otimes> inv h \\<otimes> inv x)}\"\n      by (simp add: h x m_assoc [symmetric] inv_mult_group)\n  qed\nqed\n\n\nsubsubsection {*Theorems for @{text \"<#>\"} with @{text \"#>\"} or @{text \"<#\"}.*}\n\nlemma (in group) setmult_rcos_assoc:\n     \"\\<lbrakk>H \\<subseteq> carrier G; K \\<subseteq> carrier G; x \\<in> carrier G\\<rbrakk>\n      \\<Longrightarrow> H <#> (K #> x) = (H <#> K) #> x\"\nby (force simp add: r_coset_def set_mult_def m_assoc)\n\nlemma (in group) rcos_assoc_lcos:\n     \"\\<lbrakk>H \\<subseteq> carrier G; K \\<subseteq> carrier G; x \\<in> carrier G\\<rbrakk>\n      \\<Longrightarrow> (H #> x) <#> K = H <#> (x <# K)\"\nby (force simp add: r_coset_def l_coset_def set_mult_def m_assoc)\n\nlemma (in normal) rcos_mult_step1:\n     \"\\<lbrakk>x \\<in> carrier G; y \\<in> carrier G\\<rbrakk>\n      \\<Longrightarrow> (H #> x) <#> (H #> y) = (H <#> (x <# H)) #> y\"\nby (simp add: setmult_rcos_assoc subset\n              r_coset_subset_G l_coset_subset_G rcos_assoc_lcos)\n\nlemma (in normal) rcos_mult_step2:\n     \"\\<lbrakk>x \\<in> carrier G; y \\<in> carrier G\\<rbrakk>\n      \\<Longrightarrow> (H <#> (x <# H)) #> y = (H <#> (H #> x)) #> y\"\nby (insert coset_eq, simp add: normal_def)\n\nlemma (in normal) rcos_mult_step3:\n     \"\\<lbrakk>x \\<in> carrier G; y \\<in> carrier G\\<rbrakk>\n      \\<Longrightarrow> (H <#> (H #> x)) #> y = H #> (x \\<otimes> y)\"\nby (simp add: setmult_rcos_assoc coset_mult_assoc\n              subgroup_mult_id normal.axioms subset normal_axioms)\n\nlemma (in normal) rcos_sum:\n     \"\\<lbrakk>x \\<in> carrier G; y \\<in> carrier G\\<rbrakk>\n      \\<Longrightarrow> (H #> x) <#> (H #> y) = H #> (x \\<otimes> y)\"\nby (simp add: rcos_mult_step1 rcos_mult_step2 rcos_mult_step3)\n\nlemma (in normal) rcosets_mult_eq: \"M \\<in> rcosets H \\<Longrightarrow> H <#> M = M\"\n  -- {* generalizes @{text subgroup_mult_id} *}\n  by (auto simp add: RCOSETS_def subset\n        setmult_rcos_assoc subgroup_mult_id normal.axioms normal_axioms)\n\n\nsubsubsection{*An Equivalence Relation*}\n\ndefinition\n  r_congruent :: \"[('a,'b)monoid_scheme, 'a set] \\<Rightarrow> ('a*'a)set\"  (\"rcong\\<index> _\")\n  where \"rcong\\<^bsub>G\\<^esub> H = {(x,y). x \\<in> carrier G & y \\<in> carrier G & inv\\<^bsub>G\\<^esub> x \\<otimes>\\<^bsub>G\\<^esub> y \\<in> H}\"\n\n\nlemma (in subgroup) equiv_rcong:\n   assumes \"group G\"\n   shows \"equiv (carrier G) (rcong H)\"\nproof -\n  interpret group G by fact\n  show ?thesis\n  proof (intro equivI)\n    show \"refl_on (carrier G) (rcong H)\"\n      by (auto simp add: r_congruent_def refl_on_def) \n  next\n    show \"sym (rcong H)\"\n    proof (simp add: r_congruent_def sym_def, clarify)\n      fix x y\n      assume [simp]: \"x \\<in> carrier G\" \"y \\<in> carrier G\" \n         and \"inv x \\<otimes> y \\<in> H\"\n      hence \"inv (inv x \\<otimes> y) \\<in> H\" by simp\n      thus \"inv y \\<otimes> x \\<in> H\" by (simp add: inv_mult_group)\n    qed\n  next\n    show \"trans (rcong H)\"\n    proof (simp add: r_congruent_def trans_def, clarify)\n      fix x y z\n      assume [simp]: \"x \\<in> carrier G\" \"y \\<in> carrier G\" \"z \\<in> carrier G\"\n         and \"inv x \\<otimes> y \\<in> H\" and \"inv y \\<otimes> z \\<in> H\"\n      hence \"(inv x \\<otimes> y) \\<otimes> (inv y \\<otimes> z) \\<in> H\" by simp\n      hence \"inv x \\<otimes> (y \\<otimes> inv y) \\<otimes> z \\<in> H\"\n        by (simp add: m_assoc del: r_inv Units_r_inv) \n      thus \"inv x \\<otimes> z \\<in> H\" by simp\n    qed\n  qed\nqed\n\ntext{*Equivalence classes of @{text rcong} correspond to left cosets.\n  Was there a mistake in the definitions? I'd have expected them to\n  correspond to right cosets.*}\n\n(* CB: This is correct, but subtle.\n   We call H #> a the right coset of a relative to H.  According to\n   Jacobson, this is what the majority of group theory literature does.\n   He then defines the notion of congruence relation ~ over monoids as\n   equivalence relation with a ~ a' & b ~ b' \\<Longrightarrow> a*b ~ a'*b'.\n   Our notion of right congruence induced by K: rcong K appears only in\n   the context where K is a normal subgroup.  Jacobson doesn't name it.\n   But in this context left and right cosets are identical.\n*)\n\nlemma (in subgroup) l_coset_eq_rcong:\n  assumes \"group G\"\n  assumes a: \"a \\<in> carrier G\"\n  shows \"a <# H = rcong H `` {a}\"\nproof -\n  interpret group G by fact\n  show ?thesis by (force simp add: r_congruent_def l_coset_def m_assoc [symmetric] a ) \nqed\n\n\nsubsubsection{*Two Distinct Right Cosets are Disjoint*}\n\nlemma (in group) rcos_equation:\n  assumes \"subgroup H G\"\n  assumes p: \"ha \\<otimes> a = h \\<otimes> b\" \"a \\<in> carrier G\" \"b \\<in> carrier G\" \"h \\<in> H\" \"ha \\<in> H\" \"hb \\<in> H\"\n  shows \"hb \\<otimes> a \\<in> (\\<Union>h\\<in>H. {h \\<otimes> b})\"\nproof -\n  interpret subgroup H G by fact\n  from p show ?thesis apply (rule_tac UN_I [of \"hb \\<otimes> ((inv ha) \\<otimes> h)\"])\n    apply (simp add: )\n    apply (simp add: m_assoc transpose_inv)\n    done\nqed\n\nlemma (in group) rcos_disjoint:\n  assumes \"subgroup H G\"\n  assumes p: \"a \\<in> rcosets H\" \"b \\<in> rcosets H\" \"a\\<noteq>b\"\n  shows \"a \\<inter> b = {}\"\nproof -\n  interpret subgroup H G by fact\n  from p show ?thesis\n    apply (simp add: RCOSETS_def r_coset_def)\n    apply (blast intro: rcos_equation assms sym)\n    done\nqed\n\n\nsubsection {* Further lemmas for @{text \"r_congruent\"} *}\n\ntext {* The relation is a congruence *}\n\nlemma (in normal) congruent_rcong:\n  shows \"congruent2 (rcong H) (rcong H) (\\<lambda>a b. a \\<otimes> b <# H)\"\nproof (intro congruent2I[of \"carrier G\" _ \"carrier G\" _] equiv_rcong is_group)\n  fix a b c\n  assume abrcong: \"(a, b) \\<in> rcong H\"\n    and ccarr: \"c \\<in> carrier G\"\n\n  from abrcong\n      have acarr: \"a \\<in> carrier G\"\n        and bcarr: \"b \\<in> carrier G\"\n        and abH: \"inv a \\<otimes> b \\<in> H\"\n      unfolding r_congruent_def\n      by fast+\n\n  note carr = acarr bcarr ccarr\n\n  from ccarr and abH\n      have \"inv c \\<otimes> (inv a \\<otimes> b) \\<otimes> c \\<in> H\" by (rule inv_op_closed1)\n  moreover\n      from carr and inv_closed\n      have \"inv c \\<otimes> (inv a \\<otimes> b) \\<otimes> c = (inv c \\<otimes> inv a) \\<otimes> (b \\<otimes> c)\" \n      by (force cong: m_assoc)\n  moreover \n      from carr and inv_closed\n      have \"\\<dots> = (inv (a \\<otimes> c)) \\<otimes> (b \\<otimes> c)\"\n      by (simp add: inv_mult_group)\n  ultimately\n      have \"(inv (a \\<otimes> c)) \\<otimes> (b \\<otimes> c) \\<in> H\" by simp\n  from carr and this\n     have \"(b \\<otimes> c) \\<in> (a \\<otimes> c) <# H\"\n     by (simp add: lcos_module_rev[OF is_group])\n  from carr and this and is_subgroup\n     show \"(a \\<otimes> c) <# H = (b \\<otimes> c) <# H\" by (intro l_repr_independence, simp+)\nnext\n  fix a b c\n  assume abrcong: \"(a, b) \\<in> rcong H\"\n    and ccarr: \"c \\<in> carrier G\"\n\n  from ccarr have \"c \\<in> Units G\" by simp\n  hence cinvc_one: \"inv c \\<otimes> c = \\<one>\" by (rule Units_l_inv)\n\n  from abrcong\n      have acarr: \"a \\<in> carrier G\"\n       and bcarr: \"b \\<in> carrier G\"\n       and abH: \"inv a \\<otimes> b \\<in> H\"\n      by (unfold r_congruent_def, fast+)\n\n  note carr = acarr bcarr ccarr\n\n  from carr and inv_closed\n     have \"inv a \\<otimes> b = inv a \\<otimes> (\\<one> \\<otimes> b)\" by simp\n  also from carr and inv_closed\n      have \"\\<dots> = inv a \\<otimes> (inv c \\<otimes> c) \\<otimes> b\" by simp\n  also from carr and inv_closed\n      have \"\\<dots> = (inv a \\<otimes> inv c) \\<otimes> (c \\<otimes> b)\" by (force cong: m_assoc)\n  also from carr and inv_closed\n      have \"\\<dots> = inv (c \\<otimes> a) \\<otimes> (c \\<otimes> b)\" by (simp add: inv_mult_group)\n  finally\n      have \"inv a \\<otimes> b = inv (c \\<otimes> a) \\<otimes> (c \\<otimes> b)\" .\n  from abH and this\n      have \"inv (c \\<otimes> a) \\<otimes> (c \\<otimes> b) \\<in> H\" by simp\n\n  from carr and this\n     have \"(c \\<otimes> b) \\<in> (c \\<otimes> a) <# H\"\n     by (simp add: lcos_module_rev[OF is_group])\n  from carr and this and is_subgroup\n     show \"(c \\<otimes> a) <# H = (c \\<otimes> b) <# H\" by (intro l_repr_independence, simp+)\nqed\n\n\nsubsection {*Order of a Group and Lagrange's Theorem*}\n\ndefinition\n  order :: \"('a, 'b) monoid_scheme \\<Rightarrow> nat\"\n  where \"order S = card (carrier S)\"\n\nlemma (in group) rcosets_part_G:\n  assumes \"subgroup H G\"\n  shows \"\\<Union>(rcosets H) = carrier G\"\nproof -\n  interpret subgroup H G by fact\n  show ?thesis\n    apply (rule equalityI)\n    apply (force simp add: RCOSETS_def r_coset_def)\n    apply (auto simp add: RCOSETS_def intro: rcos_self assms)\n    done\nqed\n\nlemma (in group) cosets_finite:\n     \"\\<lbrakk>c \\<in> rcosets H;  H \\<subseteq> carrier G;  finite (carrier G)\\<rbrakk> \\<Longrightarrow> finite c\"\napply (auto simp add: RCOSETS_def)\napply (simp add: r_coset_subset_G [THEN finite_subset])\ndone\n\ntext{*The next two lemmas support the proof of @{text card_cosets_equal}.*}\nlemma (in group) inj_on_f:\n    \"\\<lbrakk>H \\<subseteq> carrier G;  a \\<in> carrier G\\<rbrakk> \\<Longrightarrow> inj_on (\\<lambda>y. y \\<otimes> inv a) (H #> a)\"\napply (rule inj_onI)\napply (subgoal_tac \"x \\<in> carrier G & y \\<in> carrier G\")\n prefer 2 apply (blast intro: r_coset_subset_G [THEN subsetD])\napply (simp add: subsetD)\ndone\n\nlemma (in group) inj_on_g:\n    \"\\<lbrakk>H \\<subseteq> carrier G;  a \\<in> carrier G\\<rbrakk> \\<Longrightarrow> inj_on (\\<lambda>y. y \\<otimes> a) H\"\nby (force simp add: inj_on_def subsetD)\n\nlemma (in group) card_cosets_equal:\n     \"\\<lbrakk>c \\<in> rcosets H;  H \\<subseteq> carrier G; finite(carrier G)\\<rbrakk>\n      \\<Longrightarrow> card c = card H\"\napply (auto simp add: RCOSETS_def)\napply (rule card_bij_eq)\n     apply (rule inj_on_f, assumption+)\n    apply (force simp add: m_assoc subsetD r_coset_def)\n   apply (rule inj_on_g, assumption+)\n  apply (force simp add: m_assoc subsetD r_coset_def)\n txt{*The sets @{term \"H #> a\"} and @{term \"H\"} are finite.*}\n apply (simp add: r_coset_subset_G [THEN finite_subset])\napply (blast intro: finite_subset)\ndone\n\nlemma (in group) rcosets_subset_PowG:\n     \"subgroup H G  \\<Longrightarrow> rcosets H \\<subseteq> Pow(carrier G)\"\napply (simp add: RCOSETS_def)\napply (blast dest: r_coset_subset_G subgroup.subset)\ndone\n\n\ntheorem (in group) lagrange:\n     \"\\<lbrakk>finite(carrier G); subgroup H G\\<rbrakk>\n      \\<Longrightarrow> card(rcosets H) * card(H) = order(G)\"\napply (simp (no_asm_simp) add: order_def rcosets_part_G [symmetric])\napply (subst mult.commute)\napply (rule card_partition)\n   apply (simp add: rcosets_subset_PowG [THEN finite_subset])\n  apply (simp add: rcosets_part_G)\n apply (simp add: card_cosets_equal subgroup.subset)\napply (simp add: rcos_disjoint)\ndone\n\n\nsubsection {*Quotient Groups: Factorization of a Group*}\n\ndefinition\n  FactGroup :: \"[('a,'b) monoid_scheme, 'a set] \\<Rightarrow> ('a set) monoid\" (infixl \"Mod\" 65)\n    --{*Actually defined for groups rather than monoids*}\n   where \"FactGroup G H = \\<lparr>carrier = rcosets\\<^bsub>G\\<^esub> H, mult = set_mult G, one = H\\<rparr>\"\n\nlemma (in normal) setmult_closed:\n     \"\\<lbrakk>K1 \\<in> rcosets H; K2 \\<in> rcosets H\\<rbrakk> \\<Longrightarrow> K1 <#> K2 \\<in> rcosets H\"\nby (auto simp add: rcos_sum RCOSETS_def)\n\nlemma (in normal) setinv_closed:\n     \"K \\<in> rcosets H \\<Longrightarrow> set_inv K \\<in> rcosets H\"\nby (auto simp add: rcos_inv RCOSETS_def)\n\nlemma (in normal) rcosets_assoc:\n     \"\\<lbrakk>M1 \\<in> rcosets H; M2 \\<in> rcosets H; M3 \\<in> rcosets H\\<rbrakk>\n      \\<Longrightarrow> M1 <#> M2 <#> M3 = M1 <#> (M2 <#> M3)\"\nby (auto simp add: RCOSETS_def rcos_sum m_assoc)\n\nlemma (in subgroup) subgroup_in_rcosets:\n  assumes \"group G\"\n  shows \"H \\<in> rcosets H\"\nproof -\n  interpret group G by fact\n  from _ subgroup_axioms have \"H #> \\<one> = H\"\n    by (rule coset_join2) auto\n  then show ?thesis\n    by (auto simp add: RCOSETS_def)\nqed\n\nlemma (in normal) rcosets_inv_mult_group_eq:\n     \"M \\<in> rcosets H \\<Longrightarrow> set_inv M <#> M = H\"\nby (auto simp add: RCOSETS_def rcos_inv rcos_sum subgroup.subset normal.axioms normal_axioms)\n\ntheorem (in normal) factorgroup_is_group:\n  \"group (G Mod H)\"\napply (simp add: FactGroup_def)\napply (rule groupI)\n    apply (simp add: setmult_closed)\n   apply (simp add: normal_imp_subgroup subgroup_in_rcosets [OF is_group])\n  apply (simp add: restrictI setmult_closed rcosets_assoc)\n apply (simp add: normal_imp_subgroup\n                  subgroup_in_rcosets rcosets_mult_eq)\napply (auto dest: rcosets_inv_mult_group_eq simp add: setinv_closed)\ndone\n\nlemma mult_FactGroup [simp]: \"X \\<otimes>\\<^bsub>(G Mod H)\\<^esub> X' = X <#>\\<^bsub>G\\<^esub> X'\"\n  by (simp add: FactGroup_def) \n\nlemma (in normal) inv_FactGroup:\n     \"X \\<in> carrier (G Mod H) \\<Longrightarrow> inv\\<^bsub>G Mod H\\<^esub> X = set_inv X\"\napply (rule group.inv_equality [OF factorgroup_is_group]) \napply (simp_all add: FactGroup_def setinv_closed rcosets_inv_mult_group_eq)\ndone\n\ntext{*The coset map is a homomorphism from @{term G} to the quotient group\n  @{term \"G Mod H\"}*}\nlemma (in normal) r_coset_hom_Mod:\n  \"(\\<lambda>a. H #> a) \\<in> hom G (G Mod H)\"\n  by (auto simp add: FactGroup_def RCOSETS_def Pi_def hom_def rcos_sum)\n\n \nsubsection{*The First Isomorphism Theorem*}\n\ntext{*The quotient by the kernel of a homomorphism is isomorphic to the \n  range of that homomorphism.*}\n\ndefinition\n  kernel :: \"('a, 'm) monoid_scheme \\<Rightarrow> ('b, 'n) monoid_scheme \\<Rightarrow>  ('a \\<Rightarrow> 'b) \\<Rightarrow> 'a set\"\n    --{*the kernel of a homomorphism*}\n  where \"kernel G H h = {x. x \\<in> carrier G & h x = \\<one>\\<^bsub>H\\<^esub>}\"\n\nlemma (in group_hom) subgroup_kernel: \"subgroup (kernel G H h) G\"\napply (rule subgroup.intro) \napply (auto simp add: kernel_def group.intro is_group) \ndone\n\ntext{*The kernel of a homomorphism is a normal subgroup*}\nlemma (in group_hom) normal_kernel: \"(kernel G H h) \\<lhd> G\"\napply (simp add: G.normal_inv_iff subgroup_kernel)\napply (simp add: kernel_def)\ndone\n\nlemma (in group_hom) FactGroup_nonempty:\n  assumes X: \"X \\<in> carrier (G Mod kernel G H h)\"\n  shows \"X \\<noteq> {}\"\nproof -\n  from X\n  obtain g where \"g \\<in> carrier G\" \n             and \"X = kernel G H h #> g\"\n    by (auto simp add: FactGroup_def RCOSETS_def)\n  thus ?thesis \n   by (auto simp add: kernel_def r_coset_def image_def intro: hom_one)\nqed\n\n\nlemma (in group_hom) FactGroup_the_elem_mem:\n  assumes X: \"X \\<in> carrier (G Mod (kernel G H h))\"\n  shows \"the_elem (h`X) \\<in> carrier H\"\nproof -\n  from X\n  obtain g where g: \"g \\<in> carrier G\" \n             and \"X = kernel G H h #> g\"\n    by (auto simp add: FactGroup_def RCOSETS_def)\n  hence \"h ` X = {h g}\" by (auto simp add: kernel_def r_coset_def image_def g)\n  thus ?thesis by (auto simp add: g)\nqed\n\nlemma (in group_hom) FactGroup_hom:\n     \"(\\<lambda>X. the_elem (h`X)) \\<in> hom (G Mod (kernel G H h)) H\"\napply (simp add: hom_def FactGroup_the_elem_mem normal.factorgroup_is_group [OF normal_kernel] group.axioms monoid.m_closed)\nproof (intro ballI)\n  fix X and X'\n  assume X:  \"X  \\<in> carrier (G Mod kernel G H h)\"\n     and X': \"X' \\<in> carrier (G Mod kernel G H h)\"\n  then\n  obtain g and g'\n           where \"g \\<in> carrier G\" and \"g' \\<in> carrier G\" \n             and \"X = kernel G H h #> g\" and \"X' = kernel G H h #> g'\"\n    by (auto simp add: FactGroup_def RCOSETS_def)\n  hence all: \"\\<forall>x\\<in>X. h x = h g\" \"\\<forall>x\\<in>X'. h x = h g'\" \n    and Xsub: \"X \\<subseteq> carrier G\" and X'sub: \"X' \\<subseteq> carrier G\"\n    by (force simp add: kernel_def r_coset_def image_def)+\n  hence \"h ` (X <#> X') = {h g \\<otimes>\\<^bsub>H\\<^esub> h g'}\" using X X'\n    by (auto dest!: FactGroup_nonempty\n             simp add: set_mult_def image_eq_UN \n                       subsetD [OF Xsub] subsetD [OF X'sub]) \n  thus \"the_elem (h ` (X <#> X')) = the_elem (h ` X) \\<otimes>\\<^bsub>H\\<^esub> the_elem (h ` X')\"\n    by (simp add: all image_eq_UN FactGroup_nonempty X X')\nqed\n\n\ntext{*Lemma for the following injectivity result*}\nlemma (in group_hom) FactGroup_subset:\n     \"\\<lbrakk>g \\<in> carrier G; g' \\<in> carrier G; h g = h g'\\<rbrakk>\n      \\<Longrightarrow>  kernel G H h #> g \\<subseteq> kernel G H h #> g'\"\napply (clarsimp simp add: kernel_def r_coset_def image_def)\napply (rename_tac y)  \napply (rule_tac x=\"y \\<otimes> g \\<otimes> inv g'\" in exI) \napply (simp add: G.m_assoc) \ndone\n\nlemma (in group_hom) FactGroup_inj_on:\n     \"inj_on (\\<lambda>X. the_elem (h ` X)) (carrier (G Mod kernel G H h))\"\nproof (simp add: inj_on_def, clarify) \n  fix X and X'\n  assume X:  \"X  \\<in> carrier (G Mod kernel G H h)\"\n     and X': \"X' \\<in> carrier (G Mod kernel G H h)\"\n  then\n  obtain g and g'\n           where gX: \"g \\<in> carrier G\"  \"g' \\<in> carrier G\" \n              \"X = kernel G H h #> g\" \"X' = kernel G H h #> g'\"\n    by (auto simp add: FactGroup_def RCOSETS_def)\n  hence all: \"\\<forall>x\\<in>X. h x = h g\" \"\\<forall>x\\<in>X'. h x = h g'\" \n    by (force simp add: kernel_def r_coset_def image_def)+\n  assume \"the_elem (h ` X) = the_elem (h ` X')\"\n  hence h: \"h g = h g'\"\n    by (simp add: image_eq_UN all FactGroup_nonempty X X') \n  show \"X=X'\" by (rule equalityI) (simp_all add: FactGroup_subset h gX) \nqed\n\ntext{*If the homomorphism @{term h} is onto @{term H}, then so is the\nhomomorphism from the quotient group*}\nlemma (in group_hom) FactGroup_onto:\n  assumes h: \"h ` carrier G = carrier H\"\n  shows \"(\\<lambda>X. the_elem (h ` X)) ` carrier (G Mod kernel G H h) = carrier H\"\nproof\n  show \"(\\<lambda>X. the_elem (h ` X)) ` carrier (G Mod kernel G H h) \\<subseteq> carrier H\"\n    by (auto simp add: FactGroup_the_elem_mem)\n  show \"carrier H \\<subseteq> (\\<lambda>X. the_elem (h ` X)) ` carrier (G Mod kernel G H h)\"\n  proof\n    fix y\n    assume y: \"y \\<in> carrier H\"\n    with h obtain g where g: \"g \\<in> carrier G\" \"h g = y\"\n      by (blast elim: equalityE) \n    hence \"(\\<Union>x\\<in>kernel G H h #> g. {h x}) = {y}\" \n      by (auto simp add: y kernel_def r_coset_def) \n    with g show \"y \\<in> (\\<lambda>X. the_elem (h ` X)) ` carrier (G Mod kernel G H h)\" \n      by (auto intro!: bexI simp add: FactGroup_def RCOSETS_def image_eq_UN)\n  qed\nqed\n\n\ntext{*If @{term h} is a homomorphism from @{term G} onto @{term H}, then the\n quotient group @{term \"G Mod (kernel G H h)\"} is isomorphic to @{term H}.*}\ntheorem (in group_hom) FactGroup_iso:\n  \"h ` carrier G = carrier H\n   \\<Longrightarrow> (\\<lambda>X. the_elem (h`X)) \\<in> (G Mod (kernel G H h)) \\<cong> H\"\nby (simp add: iso_def FactGroup_hom FactGroup_inj_on bij_betw_def \n              FactGroup_onto) \n\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/Coset.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8740772384450967, "lm_q2_score": 0.8152324848629215, "lm_q1q2_score": 0.7125761590597165}}
{"text": "(*  Title:      HOL/Multivariate_Analysis/Extended_Real_Limits.thy\n    Author:     Johannes H\u00f6lzl, TU M\u00fcnchen\n    Author:     Robert Himmelmann, TU M\u00fcnchen\n    Author:     Armin Heller, TU M\u00fcnchen\n    Author:     Bogdan Grechuk, University of Edinburgh\n*)\n\nsection {* Limits on the Extended real number line *}\n\ntheory Extended_Real_Limits\n  imports Topology_Euclidean_Space \"~~/src/HOL/Library/Extended_Real\" \"~~/src/HOL/Library/Indicator_Function\"\nbegin\n\nlemma convergent_limsup_cl:\n  fixes X :: \"nat \\<Rightarrow> 'a::{complete_linorder,linorder_topology}\"\n  shows \"convergent X \\<Longrightarrow> limsup X = lim X\"\n  by (auto simp: convergent_def limI lim_imp_Limsup)\n\nlemma lim_increasing_cl:\n  assumes \"\\<And>n m. n \\<ge> m \\<Longrightarrow> f n \\<ge> f m\"\n  obtains l where \"f ----> (l::'a::{complete_linorder,linorder_topology})\"\nproof\n  show \"f ----> (SUP n. f n)\"\n    using assms\n    by (intro increasing_tendsto)\n       (auto simp: SUP_upper eventually_sequentially less_SUP_iff intro: less_le_trans)\nqed\n\nlemma lim_decreasing_cl:\n  assumes \"\\<And>n m. n \\<ge> m \\<Longrightarrow> f n \\<le> f m\"\n  obtains l where \"f ----> (l::'a::{complete_linorder,linorder_topology})\"\nproof\n  show \"f ----> (INF n. f n)\"\n    using assms\n    by (intro decreasing_tendsto)\n       (auto simp: INF_lower eventually_sequentially INF_less_iff intro: le_less_trans)\nqed\n\nlemma compact_complete_linorder:\n  fixes X :: \"nat \\<Rightarrow> 'a::{complete_linorder,linorder_topology}\"\n  shows \"\\<exists>l r. subseq r \\<and> (X \\<circ> r) ----> l\"\nproof -\n  obtain r where \"subseq r\" and mono: \"monoseq (X \\<circ> r)\"\n    using seq_monosub[of X]\n    unfolding comp_def\n    by auto\n  then have \"(\\<forall>n m. m \\<le> n \\<longrightarrow> (X \\<circ> r) m \\<le> (X \\<circ> r) n) \\<or> (\\<forall>n m. m \\<le> n \\<longrightarrow> (X \\<circ> r) n \\<le> (X \\<circ> r) m)\"\n    by (auto simp add: monoseq_def)\n  then obtain l where \"(X \\<circ> r) ----> l\"\n     using lim_increasing_cl[of \"X \\<circ> r\"] lim_decreasing_cl[of \"X \\<circ> r\"]\n     by auto\n  then show ?thesis\n    using `subseq r` by auto\nqed\n\nlemma compact_UNIV:\n  \"compact (UNIV :: 'a::{complete_linorder,linorder_topology,second_countable_topology} set)\"\n  using compact_complete_linorder\n  by (auto simp: seq_compact_eq_compact[symmetric] seq_compact_def)\n\nlemma compact_eq_closed:\n  fixes S :: \"'a::{complete_linorder,linorder_topology,second_countable_topology} set\"\n  shows \"compact S \\<longleftrightarrow> closed S\"\n  using closed_inter_compact[of S, OF _ compact_UNIV] compact_imp_closed\n  by auto\n\nlemma closed_contains_Sup_cl:\n  fixes S :: \"'a::{complete_linorder,linorder_topology,second_countable_topology} set\"\n  assumes \"closed S\"\n    and \"S \\<noteq> {}\"\n  shows \"Sup S \\<in> S\"\nproof -\n  from compact_eq_closed[of S] compact_attains_sup[of S] assms\n  obtain s where S: \"s \\<in> S\" \"\\<forall>t\\<in>S. t \\<le> s\"\n    by auto\n  then have \"Sup S = s\"\n    by (auto intro!: Sup_eqI)\n  with S show ?thesis\n    by simp\nqed\n\nlemma closed_contains_Inf_cl:\n  fixes S :: \"'a::{complete_linorder,linorder_topology,second_countable_topology} set\"\n  assumes \"closed S\"\n    and \"S \\<noteq> {}\"\n  shows \"Inf S \\<in> S\"\nproof -\n  from compact_eq_closed[of S] compact_attains_inf[of S] assms\n  obtain s where S: \"s \\<in> S\" \"\\<forall>t\\<in>S. s \\<le> t\"\n    by auto\n  then have \"Inf S = s\"\n    by (auto intro!: Inf_eqI)\n  with S show ?thesis\n    by simp\nqed\n\nlemma ereal_dense3:\n  fixes x y :: ereal\n  shows \"x < y \\<Longrightarrow> \\<exists>r::rat. x < real_of_rat r \\<and> real_of_rat r < y\"\nproof (cases x y rule: ereal2_cases, simp_all)\n  fix r q :: real\n  assume \"r < q\"\n  from Rats_dense_in_real[OF this] show \"\\<exists>x. r < real_of_rat x \\<and> real_of_rat x < q\"\n    by (fastforce simp: Rats_def)\nnext\n  fix r :: real\n  show \"\\<exists>x. r < real_of_rat x\" \"\\<exists>x. real_of_rat x < r\"\n    using gt_ex[of r] lt_ex[of r] Rats_dense_in_real\n    by (auto simp: Rats_def)\nqed\n\ninstance ereal :: second_countable_topology\nproof (default, intro exI conjI)\n  let ?B = \"(\\<Union>r\\<in>\\<rat>. {{..< r}, {r <..}} :: ereal set set)\"\n  show \"countable ?B\"\n    by (auto intro: countable_rat)\n  show \"open = generate_topology ?B\"\n  proof (intro ext iffI)\n    fix S :: \"ereal set\"\n    assume \"open S\"\n    then show \"generate_topology ?B S\"\n      unfolding open_generated_order\n    proof induct\n      case (Basis b)\n      then obtain e where \"b = {..<e} \\<or> b = {e<..}\"\n        by auto\n      moreover have \"{..<e} = \\<Union>{{..<x}|x. x \\<in> \\<rat> \\<and> x < e}\" \"{e<..} = \\<Union>{{x<..}|x. x \\<in> \\<rat> \\<and> e < x}\"\n        by (auto dest: ereal_dense3\n                 simp del: ex_simps\n                 simp add: ex_simps[symmetric] conj_commute Rats_def image_iff)\n      ultimately show ?case\n        by (auto intro: generate_topology.intros)\n    qed (auto intro: generate_topology.intros)\n  next\n    fix S\n    assume \"generate_topology ?B S\"\n    then show \"open S\"\n      by induct auto\n  qed\nqed\n\nlemma continuous_on_ereal[intro, simp]: \"continuous_on A ereal\"\n  unfolding continuous_on_topological open_ereal_def\n  by auto\n\nlemma continuous_at_ereal[intro, simp]: \"continuous (at x) ereal\"\n  using continuous_on_eq_continuous_at[of UNIV]\n  by auto\n\nlemma continuous_within_ereal[intro, simp]: \"x \\<in> A \\<Longrightarrow> continuous (at x within A) ereal\"\n  using continuous_on_eq_continuous_within[of A]\n  by auto\n\nlemma ereal_open_uminus:\n  fixes S :: \"ereal set\"\n  assumes \"open S\"\n  shows \"open (uminus ` S)\"\n  using `open S`[unfolded open_generated_order]\nproof induct\n  have \"range uminus = (UNIV :: ereal set)\"\n    by (auto simp: image_iff ereal_uminus_eq_reorder)\n  then show \"open (range uminus :: ereal set)\"\n    by simp\nqed (auto simp add: image_Union image_Int)\n\nlemma ereal_uminus_complement:\n  fixes S :: \"ereal set\"\n  shows \"uminus ` (- S) = - uminus ` S\"\n  by (auto intro!: bij_image_Compl_eq surjI[of _ uminus] simp: bij_betw_def)\n\nlemma ereal_closed_uminus:\n  fixes S :: \"ereal set\"\n  assumes \"closed S\"\n  shows \"closed (uminus ` S)\"\n  using assms\n  unfolding closed_def ereal_uminus_complement[symmetric]\n  by (rule ereal_open_uminus)\n\nlemma ereal_open_closed_aux:\n  fixes S :: \"ereal set\"\n  assumes \"open S\"\n    and \"closed S\"\n    and S: \"(-\\<infinity>) \\<notin> S\"\n  shows \"S = {}\"\nproof (rule ccontr)\n  assume \"\\<not> ?thesis\"\n  then have *: \"Inf S \\<in> S\"\n    by (metis assms(2) closed_contains_Inf_cl)\n  {\n    assume \"Inf S = -\\<infinity>\"\n    then have False\n      using * assms(3) by auto\n  }\n  moreover\n  {\n    assume \"Inf S = \\<infinity>\"\n    then have \"S = {\\<infinity>}\"\n      by (metis Inf_eq_PInfty `S \\<noteq> {}`)\n    then have False\n      by (metis assms(1) not_open_singleton)\n  }\n  moreover\n  {\n    assume fin: \"\\<bar>Inf S\\<bar> \\<noteq> \\<infinity>\"\n    from ereal_open_cont_interval[OF assms(1) * fin]\n    obtain e where e: \"e > 0\" \"{Inf S - e<..<Inf S + e} \\<subseteq> S\" .\n    then obtain b where b: \"Inf S - e < b\" \"b < Inf S\"\n      using fin ereal_between[of \"Inf S\" e] dense[of \"Inf S - e\"]\n      by auto\n    then have \"b: {Inf S - e <..< Inf S + e}\"\n      using e fin ereal_between[of \"Inf S\" e]\n      by auto\n    then have \"b \\<in> S\"\n      using e by auto\n    then have False\n      using b by (metis complete_lattice_class.Inf_lower leD)\n  }\n  ultimately show False\n    by auto\nqed\n\nlemma ereal_open_closed:\n  fixes S :: \"ereal set\"\n  shows \"open S \\<and> closed S \\<longleftrightarrow> S = {} \\<or> S = UNIV\"\nproof -\n  {\n    assume lhs: \"open S \\<and> closed S\"\n    {\n      assume \"-\\<infinity> \\<notin> S\"\n      then have \"S = {}\"\n        using lhs ereal_open_closed_aux by auto\n    }\n    moreover\n    {\n      assume \"-\\<infinity> \\<in> S\"\n      then have \"- S = {}\"\n        using lhs ereal_open_closed_aux[of \"-S\"] by auto\n    }\n    ultimately have \"S = {} \\<or> S = UNIV\"\n      by auto\n  }\n  then show ?thesis\n    by auto\nqed\n\nlemma ereal_open_affinity_pos:\n  fixes S :: \"ereal set\"\n  assumes \"open S\"\n    and m: \"m \\<noteq> \\<infinity>\" \"0 < m\"\n    and t: \"\\<bar>t\\<bar> \\<noteq> \\<infinity>\"\n  shows \"open ((\\<lambda>x. m * x + t) ` S)\"\nproof -\n  obtain r where r[simp]: \"m = ereal r\"\n    using m by (cases m) auto\n  obtain p where p[simp]: \"t = ereal p\"\n    using t by auto\n  have \"r \\<noteq> 0\" \"0 < r\" and m': \"m \\<noteq> \\<infinity>\" \"m \\<noteq> -\\<infinity>\" \"m \\<noteq> 0\"\n    using m by auto\n  from `open S` [THEN ereal_openE]\n  obtain l u where T:\n      \"open (ereal -` S)\"\n      \"\\<infinity> \\<in> S \\<Longrightarrow> {ereal l<..} \\<subseteq> S\"\n      \"- \\<infinity> \\<in> S \\<Longrightarrow> {..<ereal u} \\<subseteq> S\"\n    by blast\n  let ?f = \"(\\<lambda>x. m * x + t)\"\n  show ?thesis\n    unfolding open_ereal_def\n  proof (intro conjI impI exI subsetI)\n    have \"ereal -` ?f ` S = (\\<lambda>x. r * x + p) ` (ereal -` S)\"\n    proof safe\n      fix x y\n      assume \"ereal y = m * x + t\" \"x \\<in> S\"\n      then show \"y \\<in> (\\<lambda>x. r * x + p) ` ereal -` S\"\n        using `r \\<noteq> 0` by (cases x) (auto intro!: image_eqI[of _ _ \"real x\"] split: split_if_asm)\n    qed force\n    then show \"open (ereal -` ?f ` S)\"\n      using open_affinity[OF T(1) `r \\<noteq> 0`]\n      by (auto simp: ac_simps)\n  next\n    assume \"\\<infinity> \\<in> ?f`S\"\n    with `0 < r` have \"\\<infinity> \\<in> S\"\n      by auto\n    fix x\n    assume \"x \\<in> {ereal (r * l + p)<..}\"\n    then have [simp]: \"ereal (r * l + p) < x\"\n      by auto\n    show \"x \\<in> ?f`S\"\n    proof (rule image_eqI)\n      show \"x = m * ((x - t) / m) + t\"\n        using m t\n        by (cases rule: ereal3_cases[of m x t]) auto\n      have \"ereal l < (x - t) / m\"\n        using m t\n        by (simp add: ereal_less_divide_pos ereal_less_minus)\n      then show \"(x - t) / m \\<in> S\"\n        using T(2)[OF `\\<infinity> \\<in> S`] by auto\n    qed\n  next\n    assume \"-\\<infinity> \\<in> ?f ` S\"\n    with `0 < r` have \"-\\<infinity> \\<in> S\"\n      by auto\n    fix x assume \"x \\<in> {..<ereal (r * u + p)}\"\n    then have [simp]: \"x < ereal (r * u + p)\"\n      by auto\n    show \"x \\<in> ?f`S\"\n    proof (rule image_eqI)\n      show \"x = m * ((x - t) / m) + t\"\n        using m t\n        by (cases rule: ereal3_cases[of m x t]) auto\n      have \"(x - t)/m < ereal u\"\n        using m t\n        by (simp add: ereal_divide_less_pos ereal_minus_less)\n      then show \"(x - t)/m \\<in> S\"\n        using T(3)[OF `-\\<infinity> \\<in> S`]\n        by auto\n    qed\n  qed\nqed\n\nlemma ereal_open_affinity:\n  fixes S :: \"ereal set\"\n  assumes \"open S\"\n    and m: \"\\<bar>m\\<bar> \\<noteq> \\<infinity>\" \"m \\<noteq> 0\"\n    and t: \"\\<bar>t\\<bar> \\<noteq> \\<infinity>\"\n  shows \"open ((\\<lambda>x. m * x + t) ` S)\"\nproof cases\n  assume \"0 < m\"\n  then show ?thesis\n    using ereal_open_affinity_pos[OF `open S` _ _ t, of m] m\n    by auto\nnext\n  assume \"\\<not> 0 < m\" then\n  have \"0 < -m\"\n    using `m \\<noteq> 0`\n    by (cases m) auto\n  then have m: \"-m \\<noteq> \\<infinity>\" \"0 < -m\"\n    using `\\<bar>m\\<bar> \\<noteq> \\<infinity>`\n    by (auto simp: ereal_uminus_eq_reorder)\n  from ereal_open_affinity_pos[OF ereal_open_uminus[OF `open S`] m t] show ?thesis\n    unfolding image_image by simp\nqed\n\nlemma ereal_lim_mult:\n  fixes X :: \"'a \\<Rightarrow> ereal\"\n  assumes lim: \"(X ---> L) net\"\n    and a: \"\\<bar>a\\<bar> \\<noteq> \\<infinity>\"\n  shows \"((\\<lambda>i. a * X i) ---> a * L) net\"\nproof cases\n  assume \"a \\<noteq> 0\"\n  show ?thesis\n  proof (rule topological_tendstoI)\n    fix S\n    assume \"open S\" and \"a * L \\<in> S\"\n    have \"a * L / a = L\"\n      using `a \\<noteq> 0` a\n      by (cases rule: ereal2_cases[of a L]) auto\n    then have L: \"L \\<in> ((\\<lambda>x. x / a) ` S)\"\n      using `a * L \\<in> S`\n      by (force simp: image_iff)\n    moreover have \"open ((\\<lambda>x. x / a) ` S)\"\n      using ereal_open_affinity[OF `open S`, of \"inverse a\" 0] `a \\<noteq> 0` a\n      by (auto simp: ereal_divide_eq ereal_inverse_eq_0 divide_ereal_def ac_simps)\n    note * = lim[THEN topological_tendstoD, OF this L]\n    {\n      fix x\n      from a `a \\<noteq> 0` have \"a * (x / a) = x\"\n        by (cases rule: ereal2_cases[of a x]) auto\n    }\n    note this[simp]\n    show \"eventually (\\<lambda>x. a * X x \\<in> S) net\"\n      by (rule eventually_mono[OF _ *]) auto\n  qed\nqed auto\n\nlemma ereal_lim_uminus:\n  fixes X :: \"'a \\<Rightarrow> ereal\"\n  shows \"((\\<lambda>i. - X i) ---> - L) net \\<longleftrightarrow> (X ---> L) net\"\n  using ereal_lim_mult[of X L net \"ereal (-1)\"]\n    ereal_lim_mult[of \"(\\<lambda>i. - X i)\" \"-L\" net \"ereal (-1)\"]\n  by (auto simp add: algebra_simps)\n\nlemma ereal_open_atLeast:\n  fixes x :: ereal\n  shows \"open {x..} \\<longleftrightarrow> x = -\\<infinity>\"\nproof\n  assume \"x = -\\<infinity>\"\n  then have \"{x..} = UNIV\"\n    by auto\n  then show \"open {x..}\"\n    by auto\nnext\n  assume \"open {x..}\"\n  then have \"open {x..} \\<and> closed {x..}\"\n    by auto\n  then have \"{x..} = UNIV\"\n    unfolding ereal_open_closed by auto\n  then show \"x = -\\<infinity>\"\n    by (simp add: bot_ereal_def atLeast_eq_UNIV_iff)\nqed\n\nlemma open_uminus_iff:\n  fixes S :: \"ereal set\"\n  shows \"open (uminus ` S) \\<longleftrightarrow> open S\"\n  using ereal_open_uminus[of S] ereal_open_uminus[of \"uminus ` S\"]\n  by auto\n\nlemma ereal_Liminf_uminus:\n  fixes f :: \"'a \\<Rightarrow> ereal\"\n  shows \"Liminf net (\\<lambda>x. - (f x)) = - Limsup net f\"\n  using ereal_Limsup_uminus[of _ \"(\\<lambda>x. - (f x))\"] by auto\n\nlemma ereal_Lim_uminus:\n  fixes f :: \"'a \\<Rightarrow> ereal\"\n  shows \"(f ---> f0) net \\<longleftrightarrow> ((\\<lambda>x. - f x) ---> - f0) net\"\n  using\n    ereal_lim_mult[of f f0 net \"- 1\"]\n    ereal_lim_mult[of \"\\<lambda>x. - (f x)\" \"-f0\" net \"- 1\"]\n  by (auto simp: ereal_uminus_reorder)\n\nlemma Liminf_PInfty:\n  fixes f :: \"'a \\<Rightarrow> ereal\"\n  assumes \"\\<not> trivial_limit net\"\n  shows \"(f ---> \\<infinity>) net \\<longleftrightarrow> Liminf net f = \\<infinity>\"\n  unfolding tendsto_iff_Liminf_eq_Limsup[OF assms]\n  using Liminf_le_Limsup[OF assms, of f]\n  by auto\n\nlemma Limsup_MInfty:\n  fixes f :: \"'a \\<Rightarrow> ereal\"\n  assumes \"\\<not> trivial_limit net\"\n  shows \"(f ---> -\\<infinity>) net \\<longleftrightarrow> Limsup net f = -\\<infinity>\"\n  unfolding tendsto_iff_Liminf_eq_Limsup[OF assms]\n  using Liminf_le_Limsup[OF assms, of f]\n  by auto\n\nlemma convergent_ereal:\n  fixes X :: \"nat \\<Rightarrow> 'a :: {complete_linorder,linorder_topology}\"\n  shows \"convergent X \\<longleftrightarrow> limsup X = liminf X\"\n  using tendsto_iff_Liminf_eq_Limsup[of sequentially]\n  by (auto simp: convergent_def)\n\nlemma limsup_le_liminf_real:\n  fixes X :: \"nat \\<Rightarrow> real\" and L :: real\n  assumes 1: \"limsup X \\<le> L\" and 2: \"L \\<le> liminf X\"\n  shows \"X ----> L\"\nproof -\n  from 1 2 have \"limsup X \\<le> liminf X\" by auto\n  hence 3: \"limsup X = liminf X\"  \n    apply (subst eq_iff, rule conjI)\n    by (rule Liminf_le_Limsup, auto)\n  hence 4: \"convergent (\\<lambda>n. ereal (X n))\"\n    by (subst convergent_ereal)\n  hence \"limsup X = lim (\\<lambda>n. ereal(X n))\"\n    by (rule convergent_limsup_cl)\n  also from 1 2 3 have \"limsup X = L\" by auto\n  finally have \"lim (\\<lambda>n. ereal(X n)) = L\" ..\n  hence \"(\\<lambda>n. ereal (X n)) ----> L\"\n    apply (elim subst)\n    by (subst convergent_LIMSEQ_iff [symmetric], rule 4) \n  thus ?thesis by simp\nqed\n\nlemma liminf_PInfty:\n  fixes X :: \"nat \\<Rightarrow> ereal\"\n  shows \"X ----> \\<infinity> \\<longleftrightarrow> liminf X = \\<infinity>\"\n  by (metis Liminf_PInfty trivial_limit_sequentially)\n\nlemma limsup_MInfty:\n  fixes X :: \"nat \\<Rightarrow> ereal\"\n  shows \"X ----> -\\<infinity> \\<longleftrightarrow> limsup X = -\\<infinity>\"\n  by (metis Limsup_MInfty trivial_limit_sequentially)\n\nlemma ereal_lim_mono:\n  fixes X Y :: \"nat \\<Rightarrow> 'a::linorder_topology\"\n  assumes \"\\<And>n. N \\<le> n \\<Longrightarrow> X n \\<le> Y n\"\n    and \"X ----> x\"\n    and \"Y ----> y\"\n  shows \"x \\<le> y\"\n  using assms(1) by (intro LIMSEQ_le[OF assms(2,3)]) auto\n\nlemma incseq_le_ereal:\n  fixes X :: \"nat \\<Rightarrow> 'a::linorder_topology\"\n  assumes inc: \"incseq X\"\n    and lim: \"X ----> L\"\n  shows \"X N \\<le> L\"\n  using inc\n  by (intro ereal_lim_mono[of N, OF _ tendsto_const lim]) (simp add: incseq_def)\n\nlemma decseq_ge_ereal:\n  assumes dec: \"decseq X\"\n    and lim: \"X ----> (L::'a::linorder_topology)\"\n  shows \"X N \\<ge> L\"\n  using dec by (intro ereal_lim_mono[of N, OF _ lim tendsto_const]) (simp add: decseq_def)\n\nlemma bounded_abs:\n  fixes a :: real\n  assumes \"a \\<le> x\"\n    and \"x \\<le> b\"\n  shows \"abs x \\<le> max (abs a) (abs b)\"\n  by (metis abs_less_iff assms leI le_max_iff_disj\n    less_eq_real_def less_le_not_le less_minus_iff minus_minus)\n\nlemma ereal_Sup_lim:\n  fixes a :: \"'a::{complete_linorder,linorder_topology}\"\n  assumes \"\\<And>n. b n \\<in> s\"\n    and \"b ----> a\"\n  shows \"a \\<le> Sup s\"\n  by (metis Lim_bounded_ereal assms complete_lattice_class.Sup_upper)\n\nlemma ereal_Inf_lim:\n  fixes a :: \"'a::{complete_linorder,linorder_topology}\"\n  assumes \"\\<And>n. b n \\<in> s\"\n    and \"b ----> a\"\n  shows \"Inf s \\<le> a\"\n  by (metis Lim_bounded2_ereal assms complete_lattice_class.Inf_lower)\n\nlemma SUP_Lim_ereal:\n  fixes X :: \"nat \\<Rightarrow> 'a::{complete_linorder,linorder_topology}\"\n  assumes inc: \"incseq X\"\n    and l: \"X ----> l\"\n  shows \"(SUP n. X n) = l\"\n  using LIMSEQ_SUP[OF inc] tendsto_unique[OF trivial_limit_sequentially l]\n  by simp\n\nlemma INF_Lim_ereal:\n  fixes X :: \"nat \\<Rightarrow> 'a::{complete_linorder,linorder_topology}\"\n  assumes dec: \"decseq X\"\n    and l: \"X ----> l\"\n  shows \"(INF n. X n) = l\"\n  using LIMSEQ_INF[OF dec] tendsto_unique[OF trivial_limit_sequentially l]\n  by simp\n\nlemma SUP_eq_LIMSEQ:\n  assumes \"mono f\"\n  shows \"(SUP n. ereal (f n)) = ereal x \\<longleftrightarrow> f ----> x\"\nproof\n  have inc: \"incseq (\\<lambda>i. ereal (f i))\"\n    using `mono f` unfolding mono_def incseq_def by auto\n  {\n    assume \"f ----> x\"\n    then have \"(\\<lambda>i. ereal (f i)) ----> ereal x\"\n      by auto\n    from SUP_Lim_ereal[OF inc this] show \"(SUP n. ereal (f n)) = ereal x\" .\n  next\n    assume \"(SUP n. ereal (f n)) = ereal x\"\n    with LIMSEQ_SUP[OF inc] show \"f ----> x\" by auto\n  }\nqed\n\nlemma liminf_ereal_cminus:\n  fixes f :: \"nat \\<Rightarrow> ereal\"\n  assumes \"c \\<noteq> -\\<infinity>\"\n  shows \"liminf (\\<lambda>x. c - f x) = c - limsup f\"\nproof (cases c)\n  case PInf\n  then show ?thesis\n    by (simp add: Liminf_const)\nnext\n  case (real r)\n  then show ?thesis\n    unfolding liminf_SUP_INF limsup_INF_SUP\n    apply (subst INF_ereal_cminus)\n    apply auto\n    apply (subst SUP_ereal_cminus)\n    apply auto\n    done\nqed (insert `c \\<noteq> -\\<infinity>`, simp)\n\n\nsubsubsection {* Continuity *}\n\nlemma continuous_at_of_ereal:\n  fixes x0 :: ereal\n  assumes \"\\<bar>x0\\<bar> \\<noteq> \\<infinity>\"\n  shows \"continuous (at x0) real\"\nproof -\n  {\n    fix T\n    assume T: \"open T\" \"real x0 \\<in> T\"\n    def S \\<equiv> \"ereal ` T\"\n    then have \"ereal (real x0) \\<in> S\"\n      using T by auto\n    then have \"x0 \\<in> S\"\n      using assms ereal_real by auto\n    moreover have \"open S\"\n      using open_ereal S_def T by auto\n    moreover have \"\\<forall>y\\<in>S. real y \\<in> T\"\n      using S_def T by auto\n    ultimately have \"\\<exists>S. x0 \\<in> S \\<and> open S \\<and> (\\<forall>y\\<in>S. real y \\<in> T)\"\n      by auto\n  }\n  then show ?thesis\n    unfolding continuous_at_open by blast\nqed\n\nlemma nhds_ereal: \"nhds (ereal r) = filtermap ereal (nhds r)\"\n  by (simp add: filtermap_nhds_open_map open_ereal continuous_at_of_ereal)\n\nlemma at_ereal: \"at (ereal r) = filtermap ereal (at r)\"\n  by (simp add: filter_eq_iff eventually_at_filter nhds_ereal eventually_filtermap)\n\nlemma at_left_ereal: \"at_left (ereal r) = filtermap ereal (at_left r)\"\n  by (simp add: filter_eq_iff eventually_at_filter nhds_ereal eventually_filtermap)\n\nlemma at_right_ereal: \"at_right (ereal r) = filtermap ereal (at_right r)\"\n  by (simp add: filter_eq_iff eventually_at_filter nhds_ereal eventually_filtermap)\n\nlemma\n  shows at_left_PInf: \"at_left \\<infinity> = filtermap ereal at_top\"\n    and at_right_MInf: \"at_right (-\\<infinity>) = filtermap ereal at_bot\"\n  unfolding filter_eq_iff eventually_filtermap eventually_at_top_dense eventually_at_bot_dense\n    eventually_at_left[OF ereal_less(5)] eventually_at_right[OF ereal_less(6)]\n  by (auto simp add: ereal_all_split ereal_ex_split)\n\nlemma ereal_tendsto_simps1:\n  \"((f \\<circ> real) ---> y) (at_left (ereal x)) \\<longleftrightarrow> (f ---> y) (at_left x)\"\n  \"((f \\<circ> real) ---> y) (at_right (ereal x)) \\<longleftrightarrow> (f ---> y) (at_right x)\"\n  \"((f \\<circ> real) ---> y) (at_left (\\<infinity>::ereal)) \\<longleftrightarrow> (f ---> y) at_top\"\n  \"((f \\<circ> real) ---> y) (at_right (-\\<infinity>::ereal)) \\<longleftrightarrow> (f ---> y) at_bot\"\n  unfolding tendsto_compose_filtermap at_left_ereal at_right_ereal at_left_PInf at_right_MInf\n  by (auto simp: filtermap_filtermap filtermap_ident)\n\nlemma ereal_tendsto_simps2:\n  \"((ereal \\<circ> f) ---> ereal a) F \\<longleftrightarrow> (f ---> a) F\"\n  \"((ereal \\<circ> f) ---> \\<infinity>) F \\<longleftrightarrow> (LIM x F. f x :> at_top)\"\n  \"((ereal \\<circ> f) ---> -\\<infinity>) F \\<longleftrightarrow> (LIM x F. f x :> at_bot)\"\n  unfolding tendsto_PInfty filterlim_at_top_dense tendsto_MInfty filterlim_at_bot_dense\n  using lim_ereal by (simp_all add: comp_def)\n\nlemmas ereal_tendsto_simps = ereal_tendsto_simps1 ereal_tendsto_simps2\n\nlemma continuous_at_iff_ereal:\n  fixes f :: \"'a::t2_space \\<Rightarrow> real\"\n  shows \"continuous (at x0 within s) f \\<longleftrightarrow> continuous (at x0 within s) (ereal \\<circ> f)\"\n  unfolding continuous_within comp_def lim_ereal ..\n\nlemma continuous_on_iff_ereal:\n  fixes f :: \"'a::t2_space => real\"\n  assumes \"open A\"\n  shows \"continuous_on A f \\<longleftrightarrow> continuous_on A (ereal \\<circ> f)\"\n  unfolding continuous_on_def comp_def lim_ereal ..\n\nlemma continuous_on_real: \"continuous_on (UNIV - {\\<infinity>, -\\<infinity>::ereal}) real\"\n  using continuous_at_of_ereal continuous_on_eq_continuous_at open_image_ereal\n  by auto\n\nlemma continuous_on_iff_real:\n  fixes f :: \"'a::t2_space \\<Rightarrow> ereal\"\n  assumes *: \"\\<And>x. x \\<in> A \\<Longrightarrow> \\<bar>f x\\<bar> \\<noteq> \\<infinity>\"\n  shows \"continuous_on A f \\<longleftrightarrow> continuous_on A (real \\<circ> f)\"\nproof -\n  have \"f ` A \\<subseteq> UNIV - {\\<infinity>, -\\<infinity>}\"\n    using assms by force\n  then have *: \"continuous_on (f ` A) real\"\n    using continuous_on_real by (simp add: continuous_on_subset)\n  have **: \"continuous_on ((real \\<circ> f) ` A) ereal\"\n    using continuous_on_ereal continuous_on_subset[of \"UNIV\" \"ereal\" \"(real \\<circ> f) ` A\"]\n    by blast\n  {\n    assume \"continuous_on A f\"\n    then have \"continuous_on A (real \\<circ> f)\"\n      apply (subst continuous_on_compose)\n      using *\n      apply auto\n      done\n  }\n  moreover\n  {\n    assume \"continuous_on A (real \\<circ> f)\"\n    then have \"continuous_on A (ereal \\<circ> (real \\<circ> f))\"\n      apply (subst continuous_on_compose)\n      using **\n      apply auto\n      done\n    then have \"continuous_on A f\"\n      apply (subst continuous_on_eq[of A \"ereal \\<circ> (real \\<circ> f)\" f])\n      using assms ereal_real\n      apply auto\n      done\n  }\n  ultimately show ?thesis\n    by auto\nqed\n\nlemma continuous_at_const:\n  fixes f :: \"'a::t2_space \\<Rightarrow> ereal\"\n  assumes \"\\<forall>x. f x = C\"\n  shows \"\\<forall>x. continuous (at x) f\"\n  unfolding continuous_at_open\n  using assms t1_space\n  by auto\n\nlemma mono_closed_real:\n  fixes S :: \"real set\"\n  assumes mono: \"\\<forall>y z. y \\<in> S \\<and> y \\<le> z \\<longrightarrow> z \\<in> S\"\n    and \"closed S\"\n  shows \"S = {} \\<or> S = UNIV \\<or> (\\<exists>a. S = {a..})\"\nproof -\n  {\n    assume \"S \\<noteq> {}\"\n    { assume ex: \"\\<exists>B. \\<forall>x\\<in>S. B \\<le> x\"\n      then have *: \"\\<forall>x\\<in>S. Inf S \\<le> x\"\n        using cInf_lower[of _ S] ex by (metis bdd_below_def)\n      then have \"Inf S \\<in> S\"\n        apply (subst closed_contains_Inf)\n        using ex `S \\<noteq> {}` `closed S`\n        apply auto\n        done\n      then have \"\\<forall>x. Inf S \\<le> x \\<longleftrightarrow> x \\<in> S\"\n        using mono[rule_format, of \"Inf S\"] *\n        by auto\n      then have \"S = {Inf S ..}\"\n        by auto\n      then have \"\\<exists>a. S = {a ..}\"\n        by auto\n    }\n    moreover\n    {\n      assume \"\\<not> (\\<exists>B. \\<forall>x\\<in>S. B \\<le> x)\"\n      then have nex: \"\\<forall>B. \\<exists>x\\<in>S. x < B\"\n        by (simp add: not_le)\n      {\n        fix y\n        obtain x where \"x\\<in>S\" and \"x < y\"\n          using nex by auto\n        then have \"y \\<in> S\"\n          using mono[rule_format, of x y] by auto\n      }\n      then have \"S = UNIV\"\n        by auto\n    }\n    ultimately have \"S = UNIV \\<or> (\\<exists>a. S = {a ..})\"\n      by blast\n  }\n  then show ?thesis\n    by blast\nqed\n\nlemma mono_closed_ereal:\n  fixes S :: \"real set\"\n  assumes mono: \"\\<forall>y z. y \\<in> S \\<and> y \\<le> z \\<longrightarrow> z \\<in> S\"\n    and \"closed S\"\n  shows \"\\<exists>a. S = {x. a \\<le> ereal x}\"\nproof -\n  {\n    assume \"S = {}\"\n    then have ?thesis\n      apply (rule_tac x=PInfty in exI)\n      apply auto\n      done\n  }\n  moreover\n  {\n    assume \"S = UNIV\"\n    then have ?thesis\n      apply (rule_tac x=\"-\\<infinity>\" in exI)\n      apply auto\n      done\n  }\n  moreover\n  {\n    assume \"\\<exists>a. S = {a ..}\"\n    then obtain a where \"S = {a ..}\"\n      by auto\n    then have ?thesis\n      apply (rule_tac x=\"ereal a\" in exI)\n      apply auto\n      done\n  }\n  ultimately show ?thesis\n    using mono_closed_real[of S] assms by auto\nqed\n\n\nsubsection {* Sums *}\n\nlemma sums_ereal_positive:\n  fixes f :: \"nat \\<Rightarrow> ereal\"\n  assumes \"\\<And>i. 0 \\<le> f i\"\n  shows \"f sums (SUP n. \\<Sum>i<n. f i)\"\nproof -\n  have \"incseq (\\<lambda>i. \\<Sum>j=0..<i. f j)\"\n    using ereal_add_mono[OF _ assms]\n    by (auto intro!: incseq_SucI)\n  from LIMSEQ_SUP[OF this]\n  show ?thesis unfolding sums_def\n    by (simp add: atLeast0LessThan)\nqed\n\nlemma summable_ereal_pos:\n  fixes f :: \"nat \\<Rightarrow> ereal\"\n  assumes \"\\<And>i. 0 \\<le> f i\"\n  shows \"summable f\"\n  using sums_ereal_positive[of f, OF assms]\n  unfolding summable_def\n  by auto\n\nlemma suminf_ereal_eq_SUP:\n  fixes f :: \"nat \\<Rightarrow> ereal\"\n  assumes \"\\<And>i. 0 \\<le> f i\"\n  shows \"(\\<Sum>x. f x) = (SUP n. \\<Sum>i<n. f i)\"\n  using sums_ereal_positive[of f, OF assms, THEN sums_unique]\n  by simp\n\nlemma sums_ereal: \"(\\<lambda>x. ereal (f x)) sums ereal x \\<longleftrightarrow> f sums x\"\n  unfolding sums_def by simp\n\nlemma suminf_bound:\n  fixes f :: \"nat \\<Rightarrow> ereal\"\n  assumes \"\\<forall>N. (\\<Sum>n<N. f n) \\<le> x\"\n    and pos: \"\\<And>n. 0 \\<le> f n\"\n  shows \"suminf f \\<le> x\"\nproof (rule Lim_bounded_ereal)\n  have \"summable f\" using pos[THEN summable_ereal_pos] .\n  then show \"(\\<lambda>N. \\<Sum>n<N. f n) ----> suminf f\"\n    by (auto dest!: summable_sums simp: sums_def atLeast0LessThan)\n  show \"\\<forall>n\\<ge>0. setsum f {..<n} \\<le> x\"\n    using assms by auto\nqed\n\nlemma suminf_bound_add:\n  fixes f :: \"nat \\<Rightarrow> ereal\"\n  assumes \"\\<forall>N. (\\<Sum>n<N. f n) + y \\<le> x\"\n    and pos: \"\\<And>n. 0 \\<le> f n\"\n    and \"y \\<noteq> -\\<infinity>\"\n  shows \"suminf f + y \\<le> x\"\nproof (cases y)\n  case (real r)\n  then have \"\\<forall>N. (\\<Sum>n<N. f n) \\<le> x - y\"\n    using assms by (simp add: ereal_le_minus)\n  then have \"(\\<Sum> n. f n) \\<le> x - y\"\n    using pos by (rule suminf_bound)\n  then show \"(\\<Sum> n. f n) + y \\<le> x\"\n    using assms real by (simp add: ereal_le_minus)\nqed (insert assms, auto)\n\nlemma suminf_upper:\n  fixes f :: \"nat \\<Rightarrow> ereal\"\n  assumes \"\\<And>n. 0 \\<le> f n\"\n  shows \"(\\<Sum>n<N. f n) \\<le> (\\<Sum>n. f n)\"\n  unfolding suminf_ereal_eq_SUP [OF assms]\n  by (auto intro: complete_lattice_class.SUP_upper)\n\nlemma suminf_0_le:\n  fixes f :: \"nat \\<Rightarrow> ereal\"\n  assumes \"\\<And>n. 0 \\<le> f n\"\n  shows \"0 \\<le> (\\<Sum>n. f n)\"\n  using suminf_upper[of f 0, OF assms]\n  by simp\n\nlemma suminf_le_pos:\n  fixes f g :: \"nat \\<Rightarrow> ereal\"\n  assumes \"\\<And>N. f N \\<le> g N\"\n    and \"\\<And>N. 0 \\<le> f N\"\n  shows \"suminf f \\<le> suminf g\"\nproof (safe intro!: suminf_bound)\n  fix n\n  {\n    fix N\n    have \"0 \\<le> g N\"\n      using assms(2,1)[of N] by auto\n  }\n  have \"setsum f {..<n} \\<le> setsum g {..<n}\"\n    using assms by (auto intro: setsum_mono)\n  also have \"\\<dots> \\<le> suminf g\"\n    using `\\<And>N. 0 \\<le> g N`\n    by (rule suminf_upper)\n  finally show \"setsum f {..<n} \\<le> suminf g\" .\nqed (rule assms(2))\n\nlemma suminf_half_series_ereal: \"(\\<Sum>n. (1/2 :: ereal) ^ Suc n) = 1\"\n  using sums_ereal[THEN iffD2, OF power_half_series, THEN sums_unique, symmetric]\n  by (simp add: one_ereal_def)\n\nlemma suminf_add_ereal:\n  fixes f g :: \"nat \\<Rightarrow> ereal\"\n  assumes \"\\<And>i. 0 \\<le> f i\"\n    and \"\\<And>i. 0 \\<le> g i\"\n  shows \"(\\<Sum>i. f i + g i) = suminf f + suminf g\"\n  apply (subst (1 2 3) suminf_ereal_eq_SUP)\n  unfolding setsum.distrib\n  apply (intro assms ereal_add_nonneg_nonneg SUP_ereal_add_pos incseq_setsumI setsum_nonneg ballI)+\n  done\n\nlemma suminf_cmult_ereal:\n  fixes f g :: \"nat \\<Rightarrow> ereal\"\n  assumes \"\\<And>i. 0 \\<le> f i\"\n    and \"0 \\<le> a\"\n  shows \"(\\<Sum>i. a * f i) = a * suminf f\"\n  by (auto simp: setsum_ereal_right_distrib[symmetric] assms\n       ereal_zero_le_0_iff setsum_nonneg suminf_ereal_eq_SUP\n       intro!: SUP_ereal_cmult)\n\nlemma suminf_PInfty:\n  fixes f :: \"nat \\<Rightarrow> ereal\"\n  assumes \"\\<And>i. 0 \\<le> f i\"\n    and \"suminf f \\<noteq> \\<infinity>\"\n  shows \"f i \\<noteq> \\<infinity>\"\nproof -\n  from suminf_upper[of f \"Suc i\", OF assms(1)] assms(2)\n  have \"(\\<Sum>i<Suc i. f i) \\<noteq> \\<infinity>\"\n    by auto\n  then show ?thesis\n    unfolding setsum_Pinfty by simp\nqed\n\nlemma suminf_PInfty_fun:\n  assumes \"\\<And>i. 0 \\<le> f i\"\n    and \"suminf f \\<noteq> \\<infinity>\"\n  shows \"\\<exists>f'. f = (\\<lambda>x. ereal (f' x))\"\nproof -\n  have \"\\<forall>i. \\<exists>r. f i = ereal r\"\n  proof\n    fix i\n    show \"\\<exists>r. f i = ereal r\"\n      using suminf_PInfty[OF assms] assms(1)[of i]\n      by (cases \"f i\") auto\n  qed\n  from choice[OF this] show ?thesis\n    by auto\nqed\n\nlemma summable_ereal:\n  assumes \"\\<And>i. 0 \\<le> f i\"\n    and \"(\\<Sum>i. ereal (f i)) \\<noteq> \\<infinity>\"\n  shows \"summable f\"\nproof -\n  have \"0 \\<le> (\\<Sum>i. ereal (f i))\"\n    using assms by (intro suminf_0_le) auto\n  with assms obtain r where r: \"(\\<Sum>i. ereal (f i)) = ereal r\"\n    by (cases \"\\<Sum>i. ereal (f i)\") auto\n  from summable_ereal_pos[of \"\\<lambda>x. ereal (f x)\"]\n  have \"summable (\\<lambda>x. ereal (f x))\"\n    using assms by auto\n  from summable_sums[OF this]\n  have \"(\\<lambda>x. ereal (f x)) sums (\\<Sum>x. ereal (f x))\"\n    by auto\n  then show \"summable f\"\n    unfolding r sums_ereal summable_def ..\nqed\n\nlemma suminf_ereal:\n  assumes \"\\<And>i. 0 \\<le> f i\"\n    and \"(\\<Sum>i. ereal (f i)) \\<noteq> \\<infinity>\"\n  shows \"(\\<Sum>i. ereal (f i)) = ereal (suminf f)\"\nproof (rule sums_unique[symmetric])\n  from summable_ereal[OF assms]\n  show \"(\\<lambda>x. ereal (f x)) sums (ereal (suminf f))\"\n    unfolding sums_ereal\n    using assms\n    by (intro summable_sums summable_ereal)\nqed\n\nlemma suminf_ereal_minus:\n  fixes f g :: \"nat \\<Rightarrow> ereal\"\n  assumes ord: \"\\<And>i. g i \\<le> f i\" \"\\<And>i. 0 \\<le> g i\"\n    and fin: \"suminf f \\<noteq> \\<infinity>\" \"suminf g \\<noteq> \\<infinity>\"\n  shows \"(\\<Sum>i. f i - g i) = suminf f - suminf g\"\nproof -\n  {\n    fix i\n    have \"0 \\<le> f i\"\n      using ord[of i] by auto\n  }\n  moreover\n  from suminf_PInfty_fun[OF `\\<And>i. 0 \\<le> f i` fin(1)] obtain f' where [simp]: \"f = (\\<lambda>x. ereal (f' x))\" ..\n  from suminf_PInfty_fun[OF `\\<And>i. 0 \\<le> g i` fin(2)] obtain g' where [simp]: \"g = (\\<lambda>x. ereal (g' x))\" ..\n  {\n    fix i\n    have \"0 \\<le> f i - g i\"\n      using ord[of i] by (auto simp: ereal_le_minus_iff)\n  }\n  moreover\n  have \"suminf (\\<lambda>i. f i - g i) \\<le> suminf f\"\n    using assms by (auto intro!: suminf_le_pos simp: field_simps)\n  then have \"suminf (\\<lambda>i. f i - g i) \\<noteq> \\<infinity>\"\n    using fin by auto\n  ultimately show ?thesis\n    using assms `\\<And>i. 0 \\<le> f i`\n    apply simp\n    apply (subst (1 2 3) suminf_ereal)\n    apply (auto intro!: suminf_diff[symmetric] summable_ereal)\n    done\nqed\n\nlemma suminf_ereal_PInf [simp]: \"(\\<Sum>x. \\<infinity>::ereal) = \\<infinity>\"\nproof -\n  have \"(\\<Sum>i<Suc 0. \\<infinity>) \\<le> (\\<Sum>x. \\<infinity>::ereal)\"\n    by (rule suminf_upper) auto\n  then show ?thesis\n    by simp\nqed\n\nlemma summable_real_of_ereal:\n  fixes f :: \"nat \\<Rightarrow> ereal\"\n  assumes f: \"\\<And>i. 0 \\<le> f i\"\n    and fin: \"(\\<Sum>i. f i) \\<noteq> \\<infinity>\"\n  shows \"summable (\\<lambda>i. real (f i))\"\nproof (rule summable_def[THEN iffD2])\n  have \"0 \\<le> (\\<Sum>i. f i)\"\n    using assms by (auto intro: suminf_0_le)\n  with fin obtain r where r: \"ereal r = (\\<Sum>i. f i)\"\n    by (cases \"(\\<Sum>i. f i)\") auto\n  {\n    fix i\n    have \"f i \\<noteq> \\<infinity>\"\n      using f by (intro suminf_PInfty[OF _ fin]) auto\n    then have \"\\<bar>f i\\<bar> \\<noteq> \\<infinity>\"\n      using f[of i] by auto\n  }\n  note fin = this\n  have \"(\\<lambda>i. ereal (real (f i))) sums (\\<Sum>i. ereal (real (f i)))\"\n    using f\n    by (auto intro!: summable_ereal_pos simp: ereal_le_real_iff zero_ereal_def)\n  also have \"\\<dots> = ereal r\"\n    using fin r by (auto simp: ereal_real)\n  finally show \"\\<exists>r. (\\<lambda>i. real (f i)) sums r\"\n    by (auto simp: sums_ereal)\nqed\n\nlemma suminf_SUP_eq:\n  fixes f :: \"nat \\<Rightarrow> nat \\<Rightarrow> ereal\"\n  assumes \"\\<And>i. incseq (\\<lambda>n. f n i)\"\n    and \"\\<And>n i. 0 \\<le> f n i\"\n  shows \"(\\<Sum>i. SUP n. f n i) = (SUP n. \\<Sum>i. f n i)\"\nproof -\n  {\n    fix n :: nat\n    have \"(\\<Sum>i<n. SUP k. f k i) = (SUP k. \\<Sum>i<n. f k i)\"\n      using assms\n      by (auto intro!: SUP_ereal_setsum [symmetric])\n  }\n  note * = this\n  show ?thesis\n    using assms\n    apply (subst (1 2) suminf_ereal_eq_SUP)\n    unfolding *\n    apply (auto intro!: SUP_upper2)\n    apply (subst SUP_commute)\n    apply rule\n    done\nqed\n\nlemma suminf_setsum_ereal:\n  fixes f :: \"_ \\<Rightarrow> _ \\<Rightarrow> ereal\"\n  assumes nonneg: \"\\<And>i a. a \\<in> A \\<Longrightarrow> 0 \\<le> f i a\"\n  shows \"(\\<Sum>i. \\<Sum>a\\<in>A. f i a) = (\\<Sum>a\\<in>A. \\<Sum>i. f i a)\"\nproof (cases \"finite A\")\n  case True\n  then show ?thesis\n    using nonneg\n    by induct (simp_all add: suminf_add_ereal setsum_nonneg)\nnext\n  case False\n  then show ?thesis by simp\nqed\n\nlemma suminf_ereal_eq_0:\n  fixes f :: \"nat \\<Rightarrow> ereal\"\n  assumes nneg: \"\\<And>i. 0 \\<le> f i\"\n  shows \"(\\<Sum>i. f i) = 0 \\<longleftrightarrow> (\\<forall>i. f i = 0)\"\nproof\n  assume \"(\\<Sum>i. f i) = 0\"\n  {\n    fix i\n    assume \"f i \\<noteq> 0\"\n    with nneg have \"0 < f i\"\n      by (auto simp: less_le)\n    also have \"f i = (\\<Sum>j. if j = i then f i else 0)\"\n      by (subst suminf_finite[where N=\"{i}\"]) auto\n    also have \"\\<dots> \\<le> (\\<Sum>i. f i)\"\n      using nneg\n      by (auto intro!: suminf_le_pos)\n    finally have False\n      using `(\\<Sum>i. f i) = 0` by auto\n  }\n  then show \"\\<forall>i. f i = 0\"\n    by auto\nqed simp\n\nlemma Liminf_within:\n  fixes f :: \"'a::metric_space \\<Rightarrow> 'b::complete_lattice\"\n  shows \"Liminf (at x within S) f = (SUP e:{0<..}. INF y:(S \\<inter> ball x e - {x}). f y)\"\n  unfolding Liminf_def eventually_at\nproof (rule SUP_eq, simp_all add: Ball_def Bex_def, safe)\n  fix P d\n  assume \"0 < d\" and \"\\<forall>y. y \\<in> S \\<longrightarrow> y \\<noteq> x \\<and> dist y x < d \\<longrightarrow> P y\"\n  then have \"S \\<inter> ball x d - {x} \\<subseteq> {x. P x}\"\n    by (auto simp: zero_less_dist_iff dist_commute)\n  then show \"\\<exists>r>0. INFIMUM (Collect P) f \\<le> INFIMUM (S \\<inter> ball x r - {x}) f\"\n    by (intro exI[of _ d] INF_mono conjI `0 < d`) auto\nnext\n  fix d :: real\n  assume \"0 < d\"\n  then show \"\\<exists>P. (\\<exists>d>0. \\<forall>xa. xa \\<in> S \\<longrightarrow> xa \\<noteq> x \\<and> dist xa x < d \\<longrightarrow> P xa) \\<and>\n    INFIMUM (S \\<inter> ball x d - {x}) f \\<le> INFIMUM (Collect P) f\"\n    by (intro exI[of _ \"\\<lambda>y. y \\<in> S \\<inter> ball x d - {x}\"])\n       (auto intro!: INF_mono exI[of _ d] simp: dist_commute)\nqed\n\nlemma Limsup_within:\n  fixes f :: \"'a::metric_space \\<Rightarrow> 'b::complete_lattice\"\n  shows \"Limsup (at x within S) f = (INF e:{0<..}. SUP y:(S \\<inter> ball x e - {x}). f y)\"\n  unfolding Limsup_def eventually_at\nproof (rule INF_eq, simp_all add: Ball_def Bex_def, safe)\n  fix P d\n  assume \"0 < d\" and \"\\<forall>y. y \\<in> S \\<longrightarrow> y \\<noteq> x \\<and> dist y x < d \\<longrightarrow> P y\"\n  then have \"S \\<inter> ball x d - {x} \\<subseteq> {x. P x}\"\n    by (auto simp: zero_less_dist_iff dist_commute)\n  then show \"\\<exists>r>0. SUPREMUM (S \\<inter> ball x r - {x}) f \\<le> SUPREMUM (Collect P) f\"\n    by (intro exI[of _ d] SUP_mono conjI `0 < d`) auto\nnext\n  fix d :: real\n  assume \"0 < d\"\n  then show \"\\<exists>P. (\\<exists>d>0. \\<forall>xa. xa \\<in> S \\<longrightarrow> xa \\<noteq> x \\<and> dist xa x < d \\<longrightarrow> P xa) \\<and>\n    SUPREMUM (Collect P) f \\<le> SUPREMUM (S \\<inter> ball x d - {x}) f\"\n    by (intro exI[of _ \"\\<lambda>y. y \\<in> S \\<inter> ball x d - {x}\"])\n       (auto intro!: SUP_mono exI[of _ d] simp: dist_commute)\nqed\n\nlemma Liminf_at:\n  fixes f :: \"'a::metric_space \\<Rightarrow> 'b::complete_lattice\"\n  shows \"Liminf (at x) f = (SUP e:{0<..}. INF y:(ball x e - {x}). f y)\"\n  using Liminf_within[of x UNIV f] by simp\n\nlemma Limsup_at:\n  fixes f :: \"'a::metric_space \\<Rightarrow> 'b::complete_lattice\"\n  shows \"Limsup (at x) f = (INF e:{0<..}. SUP y:(ball x e - {x}). f y)\"\n  using Limsup_within[of x UNIV f] by simp\n\nlemma min_Liminf_at:\n  fixes f :: \"'a::metric_space \\<Rightarrow> 'b::complete_linorder\"\n  shows \"min (f x) (Liminf (at x) f) = (SUP e:{0<..}. INF y:ball x e. f y)\"\n  unfolding inf_min[symmetric] Liminf_at\n  apply (subst inf_commute)\n  apply (subst SUP_inf)\n  apply (intro SUP_cong[OF refl])\n  apply (cut_tac A=\"ball x xa - {x}\" and B=\"{x}\" and M=f in INF_union)\n  apply (drule sym)\n  apply auto\n  apply (metis INF_absorb centre_in_ball)\n  done\n\n\nlemma suminf_ereal_offset_le:\n  fixes f :: \"nat \\<Rightarrow> ereal\"\n  assumes f: \"\\<And>i. 0 \\<le> f i\"\n  shows \"(\\<Sum>i. f (i + k)) \\<le> suminf f\"\nproof -\n  have \"(\\<lambda>n. \\<Sum>i<n. f (i + k)) ----> (\\<Sum>i. f (i + k))\"\n    using summable_sums[OF summable_ereal_pos] by (simp add: sums_def atLeast0LessThan f)\n  moreover have \"(\\<lambda>n. \\<Sum>i<n. f i) ----> (\\<Sum>i. f i)\"\n    using summable_sums[OF summable_ereal_pos] by (simp add: sums_def atLeast0LessThan f)\n  then have \"(\\<lambda>n. \\<Sum>i<n + k. f i) ----> (\\<Sum>i. f i)\"\n    by (rule LIMSEQ_ignore_initial_segment)\n  ultimately show ?thesis\n  proof (rule LIMSEQ_le, safe intro!: exI[of _ k])\n    fix n assume \"k \\<le> n\"\n    have \"(\\<Sum>i<n. f (i + k)) = (\\<Sum>i<n. (f \\<circ> (\\<lambda>i. i + k)) i)\"\n      by simp\n    also have \"\\<dots> = (\\<Sum>i\\<in>(\\<lambda>i. i + k) ` {..<n}. f i)\"\n      by (subst setsum.reindex) auto\n    also have \"\\<dots> \\<le> setsum f {..<n + k}\"\n      by (intro setsum_mono3) (auto simp: f)\n    finally show \"(\\<Sum>i<n. f (i + k)) \\<le> setsum f {..<n + k}\" .\n  qed\nqed\n\nlemma sums_suminf_ereal: \"f sums x \\<Longrightarrow> (\\<Sum>i. ereal (f i)) = ereal x\"\n  by (metis sums_ereal sums_unique)\n\nlemma suminf_ereal': \"summable f \\<Longrightarrow> (\\<Sum>i. ereal (f i)) = ereal (\\<Sum>i. f i)\"\n  by (metis sums_ereal sums_unique summable_def)\n\nlemma suminf_ereal_finite: \"summable f \\<Longrightarrow> (\\<Sum>i. ereal (f i)) \\<noteq> \\<infinity>\"\n  by (auto simp: sums_ereal[symmetric] summable_def sums_unique[symmetric])\n\nsubsection {* monoset *}\n\ndefinition (in order) mono_set:\n  \"mono_set S \\<longleftrightarrow> (\\<forall>x y. x \\<le> y \\<longrightarrow> x \\<in> S \\<longrightarrow> y \\<in> S)\"\n\nlemma (in order) mono_greaterThan [intro, simp]: \"mono_set {B<..}\" unfolding mono_set by auto\nlemma (in order) mono_atLeast [intro, simp]: \"mono_set {B..}\" unfolding mono_set by auto\nlemma (in order) mono_UNIV [intro, simp]: \"mono_set UNIV\" unfolding mono_set by auto\nlemma (in order) mono_empty [intro, simp]: \"mono_set {}\" unfolding mono_set by auto\n\nlemma (in complete_linorder) mono_set_iff:\n  fixes S :: \"'a set\"\n  defines \"a \\<equiv> Inf S\"\n  shows \"mono_set S \\<longleftrightarrow> S = {a <..} \\<or> S = {a..}\" (is \"_ = ?c\")\nproof\n  assume \"mono_set S\"\n  then have mono: \"\\<And>x y. x \\<le> y \\<Longrightarrow> x \\<in> S \\<Longrightarrow> y \\<in> S\"\n    by (auto simp: mono_set)\n  show ?c\n  proof cases\n    assume \"a \\<in> S\"\n    show ?c\n      using mono[OF _ `a \\<in> S`]\n      by (auto intro: Inf_lower simp: a_def)\n  next\n    assume \"a \\<notin> S\"\n    have \"S = {a <..}\"\n    proof safe\n      fix x assume \"x \\<in> S\"\n      then have \"a \\<le> x\"\n        unfolding a_def by (rule Inf_lower)\n      then show \"a < x\"\n        using `x \\<in> S` `a \\<notin> S` by (cases \"a = x\") auto\n    next\n      fix x assume \"a < x\"\n      then obtain y where \"y < x\" \"y \\<in> S\"\n        unfolding a_def Inf_less_iff ..\n      with mono[of y x] show \"x \\<in> S\"\n        by auto\n    qed\n    then show ?c ..\n  qed\nqed auto\n\nlemma ereal_open_mono_set:\n  fixes S :: \"ereal set\"\n  shows \"open S \\<and> mono_set S \\<longleftrightarrow> S = UNIV \\<or> S = {Inf S <..}\"\n  by (metis Inf_UNIV atLeast_eq_UNIV_iff ereal_open_atLeast\n    ereal_open_closed mono_set_iff open_ereal_greaterThan)\n\nlemma ereal_closed_mono_set:\n  fixes S :: \"ereal set\"\n  shows \"closed S \\<and> mono_set S \\<longleftrightarrow> S = {} \\<or> S = {Inf S ..}\"\n  by (metis Inf_UNIV atLeast_eq_UNIV_iff closed_ereal_atLeast\n    ereal_open_closed mono_empty mono_set_iff open_ereal_greaterThan)\n\nlemma ereal_Liminf_Sup_monoset:\n  fixes f :: \"'a \\<Rightarrow> ereal\"\n  shows \"Liminf net f =\n    Sup {l. \\<forall>S. open S \\<longrightarrow> mono_set S \\<longrightarrow> l \\<in> S \\<longrightarrow> eventually (\\<lambda>x. f x \\<in> S) net}\"\n    (is \"_ = Sup ?A\")\nproof (safe intro!: Liminf_eqI complete_lattice_class.Sup_upper complete_lattice_class.Sup_least)\n  fix P\n  assume P: \"eventually P net\"\n  fix S\n  assume S: \"mono_set S\" \"INFIMUM (Collect P) f \\<in> S\"\n  {\n    fix x\n    assume \"P x\"\n    then have \"INFIMUM (Collect P) f \\<le> f x\"\n      by (intro complete_lattice_class.INF_lower) simp\n    with S have \"f x \\<in> S\"\n      by (simp add: mono_set)\n  }\n  with P show \"eventually (\\<lambda>x. f x \\<in> S) net\"\n    by (auto elim: eventually_elim1)\nnext\n  fix y l\n  assume S: \"\\<forall>S. open S \\<longrightarrow> mono_set S \\<longrightarrow> l \\<in> S \\<longrightarrow> eventually  (\\<lambda>x. f x \\<in> S) net\"\n  assume P: \"\\<forall>P. eventually P net \\<longrightarrow> INFIMUM (Collect P) f \\<le> y\"\n  show \"l \\<le> y\"\n  proof (rule dense_le)\n    fix B\n    assume \"B < l\"\n    then have \"eventually (\\<lambda>x. f x \\<in> {B <..}) net\"\n      by (intro S[rule_format]) auto\n    then have \"INFIMUM {x. B < f x} f \\<le> y\"\n      using P by auto\n    moreover have \"B \\<le> INFIMUM {x. B < f x} f\"\n      by (intro INF_greatest) auto\n    ultimately show \"B \\<le> y\"\n      by simp\n  qed\nqed\n\nlemma ereal_Limsup_Inf_monoset:\n  fixes f :: \"'a \\<Rightarrow> ereal\"\n  shows \"Limsup net f =\n    Inf {l. \\<forall>S. open S \\<longrightarrow> mono_set (uminus ` S) \\<longrightarrow> l \\<in> S \\<longrightarrow> eventually (\\<lambda>x. f x \\<in> S) net}\"\n    (is \"_ = Inf ?A\")\nproof (safe intro!: Limsup_eqI complete_lattice_class.Inf_lower complete_lattice_class.Inf_greatest)\n  fix P\n  assume P: \"eventually P net\"\n  fix S\n  assume S: \"mono_set (uminus`S)\" \"SUPREMUM (Collect P) f \\<in> S\"\n  {\n    fix x\n    assume \"P x\"\n    then have \"f x \\<le> SUPREMUM (Collect P) f\"\n      by (intro complete_lattice_class.SUP_upper) simp\n    with S(1)[unfolded mono_set, rule_format, of \"- SUPREMUM (Collect P) f\" \"- f x\"] S(2)\n    have \"f x \\<in> S\"\n      by (simp add: inj_image_mem_iff) }\n  with P show \"eventually (\\<lambda>x. f x \\<in> S) net\"\n    by (auto elim: eventually_elim1)\nnext\n  fix y l\n  assume S: \"\\<forall>S. open S \\<longrightarrow> mono_set (uminus ` S) \\<longrightarrow> l \\<in> S \\<longrightarrow> eventually  (\\<lambda>x. f x \\<in> S) net\"\n  assume P: \"\\<forall>P. eventually P net \\<longrightarrow> y \\<le> SUPREMUM (Collect P) f\"\n  show \"y \\<le> l\"\n  proof (rule dense_ge)\n    fix B\n    assume \"l < B\"\n    then have \"eventually (\\<lambda>x. f x \\<in> {..< B}) net\"\n      by (intro S[rule_format]) auto\n    then have \"y \\<le> SUPREMUM {x. f x < B} f\"\n      using P by auto\n    moreover have \"SUPREMUM {x. f x < B} f \\<le> B\"\n      by (intro SUP_least) auto\n    ultimately show \"y \\<le> B\"\n      by simp\n  qed\nqed\n\nlemma liminf_bounded_open:\n  fixes x :: \"nat \\<Rightarrow> ereal\"\n  shows \"x0 \\<le> liminf x \\<longleftrightarrow> (\\<forall>S. open S \\<longrightarrow> mono_set S \\<longrightarrow> x0 \\<in> S \\<longrightarrow> (\\<exists>N. \\<forall>n\\<ge>N. x n \\<in> S))\"\n  (is \"_ \\<longleftrightarrow> ?P x0\")\nproof\n  assume \"?P x0\"\n  then show \"x0 \\<le> liminf x\"\n    unfolding ereal_Liminf_Sup_monoset eventually_sequentially\n    by (intro complete_lattice_class.Sup_upper) auto\nnext\n  assume \"x0 \\<le> liminf x\"\n  {\n    fix S :: \"ereal set\"\n    assume om: \"open S\" \"mono_set S\" \"x0 \\<in> S\"\n    {\n      assume \"S = UNIV\"\n      then have \"\\<exists>N. \\<forall>n\\<ge>N. x n \\<in> S\"\n        by auto\n    }\n    moreover\n    {\n      assume \"S \\<noteq> UNIV\"\n      then obtain B where B: \"S = {B<..}\"\n        using om ereal_open_mono_set by auto\n      then have \"B < x0\"\n        using om by auto\n      then have \"\\<exists>N. \\<forall>n\\<ge>N. x n \\<in> S\"\n        unfolding B\n        using `x0 \\<le> liminf x` liminf_bounded_iff\n        by auto\n    }\n    ultimately have \"\\<exists>N. \\<forall>n\\<ge>N. x n \\<in> S\"\n      by auto\n  }\n  then show \"?P x0\"\n    by auto\nqed\n\nsubsection \"Relate extended reals and the indicator function\"\n\nlemma ereal_indicator_le_0: \"(indicator S x::ereal) \\<le> 0 \\<longleftrightarrow> x \\<notin> S\"\n  by (auto split: split_indicator simp: one_ereal_def)\n\nlemma ereal_indicator: \"ereal (indicator A x) = indicator A x\"\n  by (auto simp: indicator_def one_ereal_def)\n\nlemma ereal_mult_indicator: \"ereal (x * indicator A y) = ereal x * indicator A y\"\n  by (simp split: split_indicator)\n\nlemma ereal_indicator_mult: \"ereal (indicator A y * x) = indicator A y * ereal x\"\n  by (simp split: split_indicator)\n\nlemma ereal_indicator_nonneg[simp, intro]: \"0 \\<le> (indicator A x ::ereal)\"\n  unfolding indicator_def by 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/Multivariate_Analysis/Extended_Real_Limits.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8740772286044095, "lm_q2_score": 0.8152324938410783, "lm_q1q2_score": 0.712576158884871}}
{"text": "theory ex3_10 imports Main \"~~/src/HOL/IMP/AExp\" begin\n\ndatatype instr = LOADI val | LOAD vname | ADD\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 s [] =  None\" |\n\"exec1  ADD s [x] =  None\" |\n\"exec1  ADD s (x#y#stk) =  Some ((x+y) # 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 None \\<Rightarrow> None |\n Some stk2 \\<Rightarrow> exec is s stk2\n)\"\n\nlemma exec_append[simp]:\n  \"exec is1 s stk = Some stk2 \\<Longrightarrow> exec (is1@is2) s stk = exec is2 s stk2\"\napply(induction is1 arbitrary: stk)\napply (auto)\nby (metis option.case_eq_if option.distinct(1))\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 = Some (aval a s # stk)\"\napply(induction a arbitrary: stk)\napply (auto)\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_10.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467548438124, "lm_q2_score": 0.8104789086703225, "lm_q1q2_score": 0.7125299024268686}}
{"text": "(*  Title:      HOL/Metis_Examples/Sets.thy\n    Author:     Lawrence C. Paulson, Cambridge University Computer Laboratory\n    Author:     Jasmin Blanchette, TU Muenchen\n\nMetis example featuring typed set theory.\n*)\n\nsection {* Metis Example Featuring Typed Set Theory *}\n\ntheory Sets\nimports Main\nbegin\n\ndeclare [[metis_new_skolem]]\n\nlemma \"EX x X. ALL y. EX z Z. (~P(y,y) | P(x,x) | ~S(z,x)) &\n               (S(x,y) | ~S(y,z) | Q(Z,Z))  &\n               (Q(X,y) | ~Q(y,Z) | S(X,X))\"\nby metis\n\nlemma \"P(n::nat) ==> ~P(0) ==> n ~= 0\"\nby metis\n\nsledgehammer_params [isar_proofs, compress = 1]\n\n(*multiple versions of this example*)\nlemma (*equal_union: *)\n   \"(X = Y \\<union> Z) = (Y \\<subseteq> X \\<and> Z \\<subseteq> X \\<and> (\\<forall>V. Y \\<subseteq> V \\<and> Z \\<subseteq> V \\<longrightarrow> X \\<subseteq> V))\"\nproof -\n  have F1: \"\\<forall>(x\\<^sub>2\\<Colon>'b set) x\\<^sub>1\\<Colon>'b set. x\\<^sub>1 \\<subseteq> x\\<^sub>1 \\<union> x\\<^sub>2\" by (metis Un_commute Un_upper2)\n  have F2a: \"\\<forall>(x\\<^sub>2\\<Colon>'b set) x\\<^sub>1\\<Colon>'b set. x\\<^sub>1 \\<subseteq> x\\<^sub>2 \\<longrightarrow> x\\<^sub>2 = x\\<^sub>2 \\<union> x\\<^sub>1\" by (metis Un_commute subset_Un_eq)\n  have F2: \"\\<forall>(x\\<^sub>2\\<Colon>'b set) x\\<^sub>1\\<Colon>'b set. x\\<^sub>1 \\<subseteq> x\\<^sub>2 \\<and> x\\<^sub>2 \\<subseteq> x\\<^sub>1 \\<longrightarrow> x\\<^sub>1 = x\\<^sub>2\" by (metis F2a subset_Un_eq)\n  { assume \"\\<not> Z \\<subseteq> X\"\n    hence \"(X = Y \\<union> Z) = (Y \\<subseteq> X \\<and> Z \\<subseteq> X \\<and> (\\<forall>V\\<Colon>'a set. Y \\<subseteq> V \\<and> Z \\<subseteq> V \\<longrightarrow> X \\<subseteq> V))\" by (metis Un_upper2) }\n  moreover\n  { assume AA1: \"Y \\<union> Z \\<noteq> X\"\n    { assume \"\\<not> Y \\<subseteq> X\"\n      hence \"(X = Y \\<union> Z) = (Y \\<subseteq> X \\<and> Z \\<subseteq> X \\<and> (\\<forall>V\\<Colon>'a set. Y \\<subseteq> V \\<and> Z \\<subseteq> V \\<longrightarrow> X \\<subseteq> V))\" by (metis F1) }\n    moreover\n    { assume AAA1: \"Y \\<subseteq> X \\<and> Y \\<union> Z \\<noteq> X\"\n      { assume \"\\<not> Z \\<subseteq> X\"\n        hence \"(X = Y \\<union> Z) = (Y \\<subseteq> X \\<and> Z \\<subseteq> X \\<and> (\\<forall>V\\<Colon>'a set. Y \\<subseteq> V \\<and> Z \\<subseteq> V \\<longrightarrow> X \\<subseteq> V))\" by (metis Un_upper2) }\n      moreover\n      { assume \"(Z \\<subseteq> X \\<and> Y \\<subseteq> X) \\<and> Y \\<union> Z \\<noteq> X\"\n        hence \"Y \\<union> Z \\<subseteq> X \\<and> X \\<noteq> Y \\<union> Z\" by (metis Un_subset_iff)\n        hence \"Y \\<union> Z \\<noteq> X \\<and> \\<not> X \\<subseteq> Y \\<union> Z\" by (metis F2)\n        hence \"\\<exists>x\\<^sub>1\\<Colon>'a set. Y \\<subseteq> x\\<^sub>1 \\<union> Z \\<and> Y \\<union> Z \\<noteq> X \\<and> \\<not> X \\<subseteq> x\\<^sub>1 \\<union> Z\" by (metis F1)\n        hence \"(X = Y \\<union> Z) = (Y \\<subseteq> X \\<and> Z \\<subseteq> X \\<and> (\\<forall>V\\<Colon>'a set. Y \\<subseteq> V \\<and> Z \\<subseteq> V \\<longrightarrow> X \\<subseteq> V))\" by (metis Un_upper2) }\n      ultimately have \"(X = Y \\<union> Z) = (Y \\<subseteq> X \\<and> Z \\<subseteq> X \\<and> (\\<forall>V\\<Colon>'a set. Y \\<subseteq> V \\<and> Z \\<subseteq> V \\<longrightarrow> X \\<subseteq> V))\" by (metis AAA1) }\n    ultimately have \"(X = Y \\<union> Z) = (Y \\<subseteq> X \\<and> Z \\<subseteq> X \\<and> (\\<forall>V\\<Colon>'a set. Y \\<subseteq> V \\<and> Z \\<subseteq> V \\<longrightarrow> X \\<subseteq> V))\" by (metis AA1) }\n  moreover\n  { assume \"\\<exists>x\\<^sub>1\\<Colon>'a set. (Z \\<subseteq> x\\<^sub>1 \\<and> Y \\<subseteq> x\\<^sub>1) \\<and> \\<not> X \\<subseteq> x\\<^sub>1\"\n    { assume \"\\<not> Y \\<subseteq> X\"\n      hence \"(X = Y \\<union> Z) = (Y \\<subseteq> X \\<and> Z \\<subseteq> X \\<and> (\\<forall>V\\<Colon>'a set. Y \\<subseteq> V \\<and> Z \\<subseteq> V \\<longrightarrow> X \\<subseteq> V))\" by (metis F1) }\n    moreover\n    { assume AAA1: \"Y \\<subseteq> X \\<and> Y \\<union> Z \\<noteq> X\"\n      { assume \"\\<not> Z \\<subseteq> X\"\n        hence \"(X = Y \\<union> Z) = (Y \\<subseteq> X \\<and> Z \\<subseteq> X \\<and> (\\<forall>V\\<Colon>'a set. Y \\<subseteq> V \\<and> Z \\<subseteq> V \\<longrightarrow> X \\<subseteq> V))\" by (metis Un_upper2) }\n      moreover\n      { assume \"(Z \\<subseteq> X \\<and> Y \\<subseteq> X) \\<and> Y \\<union> Z \\<noteq> X\"\n        hence \"Y \\<union> Z \\<subseteq> X \\<and> X \\<noteq> Y \\<union> Z\" by (metis Un_subset_iff)\n        hence \"Y \\<union> Z \\<noteq> X \\<and> \\<not> X \\<subseteq> Y \\<union> Z\" by (metis F2)\n        hence \"\\<exists>x\\<^sub>1\\<Colon>'a set. Y \\<subseteq> x\\<^sub>1 \\<union> Z \\<and> Y \\<union> Z \\<noteq> X \\<and> \\<not> X \\<subseteq> x\\<^sub>1 \\<union> Z\" by (metis F1)\n        hence \"(X = Y \\<union> Z) = (Y \\<subseteq> X \\<and> Z \\<subseteq> X \\<and> (\\<forall>V\\<Colon>'a set. Y \\<subseteq> V \\<and> Z \\<subseteq> V \\<longrightarrow> X \\<subseteq> V))\" by (metis Un_upper2) }\n      ultimately have \"(X = Y \\<union> Z) = (Y \\<subseteq> X \\<and> Z \\<subseteq> X \\<and> (\\<forall>V\\<Colon>'a set. Y \\<subseteq> V \\<and> Z \\<subseteq> V \\<longrightarrow> X \\<subseteq> V))\" by (metis AAA1) }\n    ultimately have \"(X = Y \\<union> Z) = (Y \\<subseteq> X \\<and> Z \\<subseteq> X \\<and> (\\<forall>V\\<Colon>'a set. Y \\<subseteq> V \\<and> Z \\<subseteq> V \\<longrightarrow> X \\<subseteq> V))\" by blast }\n  moreover\n  { assume \"\\<not> Y \\<subseteq> X\"\n    hence \"(X = Y \\<union> Z) = (Y \\<subseteq> X \\<and> Z \\<subseteq> X \\<and> (\\<forall>V\\<Colon>'a set. Y \\<subseteq> V \\<and> Z \\<subseteq> V \\<longrightarrow> X \\<subseteq> V))\" by (metis F1) }\n  ultimately show \"(X = Y \\<union> Z) = (Y \\<subseteq> X \\<and> Z \\<subseteq> X \\<and> (\\<forall>V\\<Colon>'a set. Y \\<subseteq> V \\<and> Z \\<subseteq> V \\<longrightarrow> X \\<subseteq> V))\" by metis\nqed\n\nsledgehammer_params [isar_proofs, compress = 2]\n\nlemma (*equal_union: *)\n   \"(X = Y \\<union> Z) = (Y \\<subseteq> X \\<and> Z \\<subseteq> X \\<and> (\\<forall>V. Y \\<subseteq> V \\<and> Z \\<subseteq> V \\<longrightarrow> X \\<subseteq> V))\"\nproof -\n  have F1: \"\\<forall>(x\\<^sub>2\\<Colon>'b set) x\\<^sub>1\\<Colon>'b set. x\\<^sub>1 \\<subseteq> x\\<^sub>2 \\<and> x\\<^sub>2 \\<subseteq> x\\<^sub>1 \\<longrightarrow> x\\<^sub>1 = x\\<^sub>2\" by (metis Un_commute subset_Un_eq)\n  { assume AA1: \"\\<exists>x\\<^sub>1\\<Colon>'a set. (Z \\<subseteq> x\\<^sub>1 \\<and> Y \\<subseteq> x\\<^sub>1) \\<and> \\<not> X \\<subseteq> x\\<^sub>1\"\n    { assume AAA1: \"Y \\<subseteq> X \\<and> Y \\<union> Z \\<noteq> X\"\n      { assume \"\\<not> Z \\<subseteq> X\"\n        hence \"(X = Y \\<union> Z) = (Y \\<subseteq> X \\<and> Z \\<subseteq> X \\<and> (\\<forall>V\\<Colon>'a set. Y \\<subseteq> V \\<and> Z \\<subseteq> V \\<longrightarrow> X \\<subseteq> V))\" by (metis Un_upper2) }\n      moreover\n      { assume \"Y \\<union> Z \\<subseteq> X \\<and> X \\<noteq> Y \\<union> Z\"\n        hence \"\\<exists>x\\<^sub>1\\<Colon>'a set. Y \\<subseteq> x\\<^sub>1 \\<union> Z \\<and> Y \\<union> Z \\<noteq> X \\<and> \\<not> X \\<subseteq> x\\<^sub>1 \\<union> Z\" by (metis F1 Un_commute Un_upper2)\n        hence \"(X = Y \\<union> Z) = (Y \\<subseteq> X \\<and> Z \\<subseteq> X \\<and> (\\<forall>V\\<Colon>'a set. Y \\<subseteq> V \\<and> Z \\<subseteq> V \\<longrightarrow> X \\<subseteq> V))\" by (metis Un_upper2) }\n      ultimately have \"(X = Y \\<union> Z) = (Y \\<subseteq> X \\<and> Z \\<subseteq> X \\<and> (\\<forall>V\\<Colon>'a set. Y \\<subseteq> V \\<and> Z \\<subseteq> V \\<longrightarrow> X \\<subseteq> V))\" by (metis AAA1 Un_subset_iff) }\n    moreover\n    { assume \"\\<not> Y \\<subseteq> X\"\n      hence \"(X = Y \\<union> Z) = (Y \\<subseteq> X \\<and> Z \\<subseteq> X \\<and> (\\<forall>V\\<Colon>'a set. Y \\<subseteq> V \\<and> Z \\<subseteq> V \\<longrightarrow> X \\<subseteq> V))\" by (metis Un_commute Un_upper2) }\n    ultimately have \"(X = Y \\<union> Z) = (Y \\<subseteq> X \\<and> Z \\<subseteq> X \\<and> (\\<forall>V\\<Colon>'a set. Y \\<subseteq> V \\<and> Z \\<subseteq> V \\<longrightarrow> X \\<subseteq> V))\" by (metis AA1 Un_subset_iff) }\n  moreover\n  { assume \"\\<not> Z \\<subseteq> X\"\n    hence \"(X = Y \\<union> Z) = (Y \\<subseteq> X \\<and> Z \\<subseteq> X \\<and> (\\<forall>V\\<Colon>'a set. Y \\<subseteq> V \\<and> Z \\<subseteq> V \\<longrightarrow> X \\<subseteq> V))\" by (metis Un_upper2) }\n  moreover\n  { assume \"\\<not> Y \\<subseteq> X\"\n    hence \"(X = Y \\<union> Z) = (Y \\<subseteq> X \\<and> Z \\<subseteq> X \\<and> (\\<forall>V\\<Colon>'a set. Y \\<subseteq> V \\<and> Z \\<subseteq> V \\<longrightarrow> X \\<subseteq> V))\" by (metis Un_commute Un_upper2) }\n  moreover\n  { assume AA1: \"Y \\<subseteq> X \\<and> Y \\<union> Z \\<noteq> X\"\n    { assume \"\\<not> Z \\<subseteq> X\"\n      hence \"(X = Y \\<union> Z) = (Y \\<subseteq> X \\<and> Z \\<subseteq> X \\<and> (\\<forall>V\\<Colon>'a set. Y \\<subseteq> V \\<and> Z \\<subseteq> V \\<longrightarrow> X \\<subseteq> V))\" by (metis Un_upper2) }\n    moreover\n    { assume \"Y \\<union> Z \\<subseteq> X \\<and> X \\<noteq> Y \\<union> Z\"\n      hence \"\\<exists>x\\<^sub>1\\<Colon>'a set. Y \\<subseteq> x\\<^sub>1 \\<union> Z \\<and> Y \\<union> Z \\<noteq> X \\<and> \\<not> X \\<subseteq> x\\<^sub>1 \\<union> Z\" by (metis F1 Un_commute Un_upper2)\n      hence \"(X = Y \\<union> Z) = (Y \\<subseteq> X \\<and> Z \\<subseteq> X \\<and> (\\<forall>V\\<Colon>'a set. Y \\<subseteq> V \\<and> Z \\<subseteq> V \\<longrightarrow> X \\<subseteq> V))\" by (metis Un_upper2) }\n    ultimately have \"(X = Y \\<union> Z) = (Y \\<subseteq> X \\<and> Z \\<subseteq> X \\<and> (\\<forall>V\\<Colon>'a set. Y \\<subseteq> V \\<and> Z \\<subseteq> V \\<longrightarrow> X \\<subseteq> V))\" by (metis AA1 Un_subset_iff) }\n  ultimately show \"(X = Y \\<union> Z) = (Y \\<subseteq> X \\<and> Z \\<subseteq> X \\<and> (\\<forall>V\\<Colon>'a set. Y \\<subseteq> V \\<and> Z \\<subseteq> V \\<longrightarrow> X \\<subseteq> V))\" by metis\nqed\n\nsledgehammer_params [isar_proofs, compress = 3]\n\nlemma (*equal_union: *)\n   \"(X = Y \\<union> Z) = (Y \\<subseteq> X \\<and> Z \\<subseteq> X \\<and> (\\<forall>V. Y \\<subseteq> V \\<and> Z \\<subseteq> V \\<longrightarrow> X \\<subseteq> V))\"\nproof -\n  have F1a: \"\\<forall>(x\\<^sub>2\\<Colon>'b set) x\\<^sub>1\\<Colon>'b set. x\\<^sub>1 \\<subseteq> x\\<^sub>2 \\<longrightarrow> x\\<^sub>2 = x\\<^sub>2 \\<union> x\\<^sub>1\" by (metis Un_commute subset_Un_eq)\n  have F1: \"\\<forall>(x\\<^sub>2\\<Colon>'b set) x\\<^sub>1\\<Colon>'b set. x\\<^sub>1 \\<subseteq> x\\<^sub>2 \\<and> x\\<^sub>2 \\<subseteq> x\\<^sub>1 \\<longrightarrow> x\\<^sub>1 = x\\<^sub>2\" by (metis F1a subset_Un_eq)\n  { assume \"(Z \\<subseteq> X \\<and> Y \\<subseteq> X) \\<and> Y \\<union> Z \\<noteq> X\"\n    hence \"(X = Y \\<union> Z) = (Y \\<subseteq> X \\<and> Z \\<subseteq> X \\<and> (\\<forall>V\\<Colon>'a set. Y \\<subseteq> V \\<and> Z \\<subseteq> V \\<longrightarrow> X \\<subseteq> V))\" by (metis F1 Un_commute Un_subset_iff Un_upper2) }\n  moreover\n  { assume AA1: \"\\<exists>x\\<^sub>1\\<Colon>'a set. (Z \\<subseteq> x\\<^sub>1 \\<and> Y \\<subseteq> x\\<^sub>1) \\<and> \\<not> X \\<subseteq> x\\<^sub>1\"\n    { assume \"(Z \\<subseteq> X \\<and> Y \\<subseteq> X) \\<and> Y \\<union> Z \\<noteq> X\"\n      hence \"(X = Y \\<union> Z) = (Y \\<subseteq> X \\<and> Z \\<subseteq> X \\<and> (\\<forall>V\\<Colon>'a set. Y \\<subseteq> V \\<and> Z \\<subseteq> V \\<longrightarrow> X \\<subseteq> V))\" by (metis F1 Un_commute Un_subset_iff Un_upper2) }\n    hence \"(X = Y \\<union> Z) = (Y \\<subseteq> X \\<and> Z \\<subseteq> X \\<and> (\\<forall>V\\<Colon>'a set. Y \\<subseteq> V \\<and> Z \\<subseteq> V \\<longrightarrow> X \\<subseteq> V))\" by (metis AA1 Un_commute Un_subset_iff Un_upper2) }\n  ultimately show \"(X = Y \\<union> Z) = (Y \\<subseteq> X \\<and> Z \\<subseteq> X \\<and> (\\<forall>V\\<Colon>'a set. Y \\<subseteq> V \\<and> Z \\<subseteq> V \\<longrightarrow> X \\<subseteq> V))\" by (metis Un_commute Un_upper2)\nqed\n\nsledgehammer_params [isar_proofs, compress = 4]\n\nlemma (*equal_union: *)\n   \"(X = Y \\<union> Z) = (Y \\<subseteq> X \\<and> Z \\<subseteq> X \\<and> (\\<forall>V. Y \\<subseteq> V \\<and> Z \\<subseteq> V \\<longrightarrow> X \\<subseteq> V))\"\nproof -\n  have F1: \"\\<forall>(x\\<^sub>2\\<Colon>'b set) x\\<^sub>1\\<Colon>'b set. x\\<^sub>1 \\<subseteq> x\\<^sub>2 \\<and> x\\<^sub>2 \\<subseteq> x\\<^sub>1 \\<longrightarrow> x\\<^sub>1 = x\\<^sub>2\" by (metis Un_commute subset_Un_eq)\n  { assume \"\\<not> Y \\<subseteq> X\"\n    hence \"(X = Y \\<union> Z) = (Y \\<subseteq> X \\<and> Z \\<subseteq> X \\<and> (\\<forall>V\\<Colon>'a set. Y \\<subseteq> V \\<and> Z \\<subseteq> V \\<longrightarrow> X \\<subseteq> V))\" by (metis Un_commute Un_upper2) }\n  moreover\n  { assume AA1: \"Y \\<subseteq> X \\<and> Y \\<union> Z \\<noteq> X\"\n    { assume \"\\<exists>x\\<^sub>1\\<Colon>'a set. Y \\<subseteq> x\\<^sub>1 \\<union> Z \\<and> Y \\<union> Z \\<noteq> X \\<and> \\<not> X \\<subseteq> x\\<^sub>1 \\<union> Z\"\n      hence \"(X = Y \\<union> Z) = (Y \\<subseteq> X \\<and> Z \\<subseteq> X \\<and> (\\<forall>V\\<Colon>'a set. Y \\<subseteq> V \\<and> Z \\<subseteq> V \\<longrightarrow> X \\<subseteq> V))\" by (metis Un_upper2) }\n    hence \"(X = Y \\<union> Z) = (Y \\<subseteq> X \\<and> Z \\<subseteq> X \\<and> (\\<forall>V\\<Colon>'a set. Y \\<subseteq> V \\<and> Z \\<subseteq> V \\<longrightarrow> X \\<subseteq> V))\" by (metis AA1 F1 Un_commute Un_subset_iff Un_upper2) }\n  ultimately show \"(X = Y \\<union> Z) = (Y \\<subseteq> X \\<and> Z \\<subseteq> X \\<and> (\\<forall>V\\<Colon>'a set. Y \\<subseteq> V \\<and> Z \\<subseteq> V \\<longrightarrow> X \\<subseteq> V))\" by (metis Un_subset_iff Un_upper2)\nqed\n\nsledgehammer_params [isar_proofs, compress = 1]\n\nlemma (*equal_union: *)\n   \"(X = Y \\<union> Z) = (Y \\<subseteq> X \\<and> Z \\<subseteq> X \\<and> (\\<forall>V. Y \\<subseteq> V \\<and> Z \\<subseteq> V \\<longrightarrow> X \\<subseteq> V))\"\nby (metis Un_least Un_upper1 Un_upper2 set_eq_subset)\n\nlemma \"(X = Y \\<inter> Z) = (X \\<subseteq> Y \\<and> X \\<subseteq> Z \\<and> (\\<forall>V. V \\<subseteq> Y \\<and> V \\<subseteq> Z \\<longrightarrow> V \\<subseteq> X))\"\nby (metis Int_greatest Int_lower1 Int_lower2 subset_antisym)\n\nlemma fixedpoint: \"\\<exists>!x. f (g x) = x \\<Longrightarrow> \\<exists>!y. g (f y) = y\"\nby metis\n\nlemma (* fixedpoint: *) \"\\<exists>!x. f (g x) = x \\<Longrightarrow> \\<exists>!y. g (f y) = y\"\nproof -\n  assume \"\\<exists>!x\\<Colon>'a. f (g x) = x\"\n  thus \"\\<exists>!y\\<Colon>'b. g (f y) = y\" by metis\nqed\n\nlemma (* singleton_example_2: *)\n     \"\\<forall>x \\<in> S. \\<Union>S \\<subseteq> x \\<Longrightarrow> \\<exists>z. S \\<subseteq> {z}\"\nby (metis Set.subsetI Union_upper insertCI set_eq_subset)\n\nlemma (* singleton_example_2: *)\n     \"\\<forall>x \\<in> S. \\<Union>S \\<subseteq> x \\<Longrightarrow> \\<exists>z. S \\<subseteq> {z}\"\nby (metis Set.subsetI Union_upper insert_iff set_eq_subset)\n\nlemma singleton_example_2:\n     \"\\<forall>x \\<in> S. \\<Union>S \\<subseteq> x \\<Longrightarrow> \\<exists>z. S \\<subseteq> {z}\"\nproof -\n  assume \"\\<forall>x \\<in> S. \\<Union>S \\<subseteq> x\"\n  hence \"\\<forall>x\\<^sub>1. x\\<^sub>1 \\<subseteq> \\<Union>S \\<and> x\\<^sub>1 \\<in> S \\<longrightarrow> x\\<^sub>1 = \\<Union>S\" by (metis set_eq_subset)\n  hence \"\\<forall>x\\<^sub>1. x\\<^sub>1 \\<in> S \\<longrightarrow> x\\<^sub>1 = \\<Union>S\" by (metis Union_upper)\n  hence \"\\<forall>x\\<^sub>1\\<Colon>('a set) set. \\<Union>S \\<in> x\\<^sub>1 \\<longrightarrow> S \\<subseteq> x\\<^sub>1\" by (metis subsetI)\n  hence \"\\<forall>x\\<^sub>1\\<Colon>('a set) set. S \\<subseteq> insert (\\<Union>S) x\\<^sub>1\" by (metis insert_iff)\n  thus \"\\<exists>z. S \\<subseteq> {z}\" by metis\nqed\n\ntext {*\n  From W. W. Bledsoe and Guohui Feng, SET-VAR. JAR 11 (3), 1993, pages\n  293-314.\n*}\n\n(* Notes: (1) The numbering doesn't completely agree with the paper.\n   (2) We must rename set variables to avoid type clashes. *)\nlemma \"\\<exists>B. (\\<forall>x \\<in> B. x \\<le> (0::int))\"\n      \"D \\<in> F \\<Longrightarrow> \\<exists>G. \\<forall>A \\<in> G. \\<exists>B \\<in> F. A \\<subseteq> B\"\n      \"P a \\<Longrightarrow> \\<exists>A. (\\<forall>x \\<in> A. P x) \\<and> (\\<exists>y. y \\<in> A)\"\n      \"a < b \\<and> b < (c::int) \\<Longrightarrow> \\<exists>B. a \\<notin> B \\<and> b \\<in> B \\<and> c \\<notin> B\"\n      \"P (f b) \\<Longrightarrow> \\<exists>s A. (\\<forall>x \\<in> A. P x) \\<and> f s \\<in> A\"\n      \"P (f b) \\<Longrightarrow> \\<exists>s A. (\\<forall>x \\<in> A. P x) \\<and> f s \\<in> A\"\n      \"\\<exists>A. a \\<notin> A\"\n      \"(\\<forall>C. (0, 0) \\<in> C \\<and> (\\<forall>x y. (x, y) \\<in> C \\<longrightarrow> (Suc x, Suc y) \\<in> C) \\<longrightarrow> (n, m) \\<in> C) \\<and> Q n \\<longrightarrow> Q m\"\n       apply (metis all_not_in_conv)\n      apply (metis all_not_in_conv)\n     apply (metis mem_Collect_eq)\n    apply (metis less_le singleton_iff)\n   apply (metis mem_Collect_eq)\n  apply (metis mem_Collect_eq)\n apply (metis all_not_in_conv)\nby (metis pair_in_Id_conv)\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/Metis_Examples/Sets.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122238669025, "lm_q2_score": 0.785308580887758, "lm_q1q2_score": 0.712520074947033}}
{"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_NMSortTDIsSort\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 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 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 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  \"((nmsorttd 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_NMSortTDIsSort.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122288794594, "lm_q2_score": 0.7853085758631159, "lm_q1q2_score": 0.7125200743245177}}
{"text": "theory Chapter08_3_Evaluation\nimports Chapter08_2_Typechecking\nbegin\n\nprimrec is_val :: \"expr => bool\"\nwhere \"is_val (Var v) = False\"\n    | \"is_val (Num x) = True\"\n    | \"is_val (Str s) = True\"\n    | \"is_val (Plus e1 e2) = False\"\n    | \"is_val (Times e1 e2) = False\"\n    | \"is_val (Cat e1 e2) = False\"\n    | \"is_val (Len e) = False\"\n    | \"is_val (Let e1 e2) = False\"\n    | \"is_val (Lam t e) = True\"\n    | \"is_val (Appl e1 e2) = False\"\n\ninductive eval :: \"expr => expr => bool\"\nwhere eval_plus_1 [simp]: \"eval (Plus (Num n1) (Num n2)) (Num (n1 + n2))\"\n    | eval_plus_2 [simp]: \"eval e1 e1' ==> eval (Plus e1 e2) (Plus e1' e2)\"\n    | eval_plus_3 [simp]: \"is_val e1 ==> eval e2 e2' ==> eval (Plus e1 e2) (Plus e1 e2')\"\n    | eval_times_1 [simp]: \"eval (Times (Num n1) (Num n2)) (Num (n1 * n2))\"\n    | eval_times_2 [simp]: \"eval e1 e1' ==> eval (Times e1 e2) (Times e1' e2)\"\n    | eval_times_3 [simp]: \"is_val e1 ==> eval e2 e2' ==> eval (Times e1 e2) (Times e1 e2')\"\n    | eval_cat_1 [simp]: \"eval (Cat (Str n1) (Str n2)) (Str (n1 @ n2))\"\n    | eval_cat_2 [simp]: \"eval e1 e1' ==> eval (Cat e1 e2) (Cat e1' e2)\"\n    | eval_cat_3 [simp]: \"is_val e1 ==> eval e2 e2' ==> eval (Cat e1 e2) (Cat e1 e2')\"\n    | eval_len_1 [simp]: \"eval (Len (Str n1)) (Num (int (length n1)))\"\n    | eval_len_2 [simp]: \"eval e1 e1' ==> eval (Len e1) (Len e1')\"\n    | eval_let_1 [simp]: \"is_val e1 ==> eval (Let e1 e2) (subst e1 first e2)\"\n    | eval_let_2 [simp]: \"eval e1 e1' ==> eval (Let e1 e2) (Let e1' e2)\"\n    | eval_appl_1 [simp]: \"eval e1 e1' ==> eval (Appl e1 e2) (Appl e1' e2)\"\n    | eval_appl_2 [simp]: \"is_val e1 ==> eval e2 e2' ==> eval (Appl e1 e2) (Appl e1 e2')\"\n    | eval_appl_3 [simp]: \"is_val e2 ==> eval (Appl (Lam t2 e1) e2) (subst e2 first e1)\"\n\nlemma canonical_num: \"is_val e ==> typecheck gam e NumType ==> EX n. e = Num n\"\nby (induction e, auto)\n\nlemma canonical_str: \"is_val e ==> typecheck gam e StrType ==> EX n. e = Str n\"\nby (induction e, auto)\n\nlemma canonical_arrow: \"is_val e ==> typecheck gam e (Arrow t1 t2) ==> \n              EX e'. e = Lam t1 e' & typecheck (extend gam t1) e' t2\"\nby (induction e, auto)\n\ntheorem preservation: \"eval e e' ==> typecheck gam e t ==> typecheck gam e' t\"\nby (induction e e' arbitrary: t rule: eval.induct, fastforce+)\n\ntheorem progress: \"typecheck gam e t ==> gam = empty_env ==> is_val e | (EX e'. eval e e')\"\nproof (induction gam e t rule: typecheck.induct)\ncase tc_var\n  thus ?case by simp\nnext case tc_str\n  thus ?case by simp\nnext case tc_num\n  thus ?case by simp\nnext case (tc_plus gam e1 e2)\n  thus ?case by (metis eval_plus_1 eval_plus_2 eval_plus_3 canonical_num)\nnext case (tc_times gam e1 e2)\n  thus ?case by (metis eval_times_1 eval_times_2 eval_times_3 canonical_num)\nnext case (tc_cat gam e1 e2)\n  thus ?case by (metis eval_cat_1 eval_cat_2 eval_cat_3 canonical_str)\nnext case (tc_len gam e)\n  thus ?case by (metis eval_len_1 eval_len_2 canonical_str)\nnext case (tc_let gam e1 t1 e2 t2)\n  thus ?case by (metis eval_let_1 eval_let_2)\nnext case (tc_lam gam t1 e t2)\n  thus ?case by simp\nnext case (tc_appl gam e1 t2 t e2)\n  thus ?case by (metis eval_appl_1 eval_appl_2 eval_appl_3 canonical_arrow)\nqed\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/Chapter08_3_Evaluation.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122163480667, "lm_q2_score": 0.7853085758631158, "lm_q1q2_score": 0.7125200644835075}}
{"text": "theory MagicMethods imports \n  Main \nbegin\n\n(* MM1 *)\n\nfun sq :: \"nat \\<Rightarrow> nat\" where\n\"sq 0 = 0\" |\n\"sq (Suc 0) = 1\" |\n\"sq n = sq (n - 1) + n - 1 + n\"\n\n(* Readable but redundant and long proof *)\n\nlemma \n  shows \"sq n = n * n\"\nproof (induction n rule: sq.induct)\n  case 1\n  then show ?case by simp\nnext\n  case 2\n  then show ?case by simp\nnext\n  case (3 v)\n  then show ?case (is \"sq ?v = ?v * ?v\")\n  proof -\n    have unfolded_rhs: \"?v * ?v = ?v + (?v - 1) + (?v - 1) * (?v - 1)\" by simp\n    have unfolded_sq: \"sq ?v = sq (?v - 1) + (?v - 1) + ?v\" by simp\n    from \"3.IH\" have from_induction_hypothesis: \"sq (?v - 1) = (?v - 1) * (?v - 1)\" by auto\n    from unfolded_rhs unfolded_sq from_induction_hypothesis show ?case by simp\n  qed\nqed\n\n(* Proof by applying simp 3 times *)\n\n\n\n(* MM2 *)      \n\nlemma\n  fixes n :: nat\n  fixes m :: nat\n  assumes pre: \"m \\<le> n\"\n  shows aux_manual: \"(n + (n - m)) * m + sq (n - m) = sq n\"\nproof -\n  have \"sq (n - m) = (n - m) * (n - m)\" by simp\n  moreover have \"(n + (n - m)) * m = n * m + (n - m) * m\" by algebra\n  moreover have \"(n - m) * m + (n - m) * (n - m) = (n - m) * (n - m + m)\" by algebra\n  moreover have \"(n - m)  * (n - m + m) = (n - m) * n\" by auto\n  moreover have \"n * m + (n - m) * n = n * (m + (n - m))\" by algebra\n  moreover have \"m \\<le> n \\<Longrightarrow> n * (m + (n - m)) = n * n\" by simp\n  ultimately show ?thesis using pre\n    by simp\nqed\n\nlemma \"100 < n \\<Longrightarrow> (n + (n - 100)) * 100 + sq (n - 100) = sq n\"\n  using aux_manual less_imp_le_nat by blast\n\n(* MM3 *)\n\nlemma\n  fixes n :: nat\n  assumes \"n mod 10 = 5\"\n  shows \"((n - 5) div 10) * ((n + 5) div 10) * 100 + 25 = sq n\"\nproof -\n  have div_10_mul_10: \"(x div 10) * (y div 10) * 100 = (x * y)\"\n    if a: \"x mod 10 = 0\" \"y mod 10 = 0\"\n    for x y :: nat\n    using a by auto\n  have \"(n - 5) mod 10 = 0\" using assms by presburger\n  moreover have \"(n + 5) mod 10 = 0\" using assms by presburger\n  ultimately have s1: \"((n - 5) div 10) * ((n + 5) div 10) * 100 + 25 = (n - 5) * (n + 5) + 25\" \n    using div_10_mul_10 assms\n    by auto\n  moreover have \"(n - 5) * (n + 5) + 25 = (n - 5) * n + (n - 5) * 5 + 5 * 5\"\n    by algebra\n  moreover have \"(n - 5) * n + (n - 5) * 5 + 5 * 5 = (n - 5) * n + 5 * ((n - 5) + 5)\" \n    by algebra\n  moreover have \"(n - 5) * n + 5 * ((n - 5) + 5) = (n - 5) * n + 5 * n\"\n    using assms by auto\n  moreover have \"(n - 5) * n + 5 * n = ((n - 5) + 5) * n\" by algebra\n  moreover have \"((n - 5) + 5) * n = n * n\" using assms by auto\n  ultimately show ?thesis by simp\nqed\n  \nend ", "meta": {"author": "bobismijnnaam", "repo": "IsabelleProjects", "sha": "ae777c98339ef2f47beeded297af16ee41ecb52d", "save_path": "github-repos/isabelle/bobismijnnaam-IsabelleProjects", "path": "github-repos/isabelle/bobismijnnaam-IsabelleProjects/IsabelleProjects-ae777c98339ef2f47beeded297af16ee41ecb52d/MagicMethods.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037323284109, "lm_q2_score": 0.7690802423634961, "lm_q1q2_score": 0.7124018989613453}}
{"text": "theory Prob_Lemmas\nimports\n  \"HOL-Probability.Probability\"\n  Girth_Chromatic.Girth_Chromatic\n  Ugraph_Misc\nbegin\n\nsection\\<open>Lemmas about probabilities\\<close>\n\ntext\\<open>In this section, auxiliary lemmas for computing bounds on expectation and probabilites\nof random variables are set up.\\<close>\n\nsubsection\\<open>Indicator variables and valid probability values\\<close>\n\nabbreviation rind :: \"'a set \\<Rightarrow> 'a \\<Rightarrow> real\" where\n\"rind \\<equiv> indicator\"\n\nlemma product_indicator:\n  \"rind A x * rind B x = rind (A \\<inter> B) x\"\nunfolding indicator_def\nby auto\n\ntext\\<open>We call a real number `valid' iff it is in the range 0 to 1, inclusively, and additionally\n`nonzero' iff it is neither 0 nor 1.\\<close>\n\nabbreviation \"valid_prob (p :: real) \\<equiv> 0 \\<le> p \\<and> p \\<le> 1\"\nabbreviation \"nonzero_prob (p :: real) \\<equiv> 0 < p \\<and> p < 1\"\n\ntext\\<open>A function @{typ \"'a \\<Rightarrow> real\"} is a `valid probability function' iff each value in the image\nis valid, and similarly for `nonzero'.\\<close>\n\nabbreviation \"valid_prob_fun f \\<equiv> (\\<forall>n. valid_prob (f n))\"\nabbreviation \"nonzero_prob_fun f \\<equiv> (\\<forall>n. nonzero_prob (f n))\"\n\nlemma nonzero_fun_is_valid_fun: \"nonzero_prob_fun f \\<Longrightarrow> valid_prob_fun f\"\nby (simp add: less_imp_le)\n\nsubsection\\<open>Expectation and variance\\<close>\n\ncontext prob_space\nbegin\n\ntext\\<open>Note that there is already a notion of independent sets (see @{term indep_set}), but we use\nthe following -- simpler -- definition:\\<close>\n\ndefinition \"indep A B \\<longleftrightarrow> prob (A \\<inter> B) = prob A * prob B\"\n\ntext\\<open>The probability of an indicator variable is equal to its expectation:\\<close>\n\nlemma expectation_indicator:\n  \"A \\<in> events \\<Longrightarrow> expectation (rind A) = prob A\"\n  by simp\n\ntext\\<open>For a non-negative random variable @{term X}, the Markov inequality gives the following\nupper bound: \\[ \\Pr[X \\ge a] \\le \\frac{\\Ex[X]}{a} \\]\\<close>\n\nlemma markov_inequality:\n  assumes \"\\<And>a. 0 \\<le> X a\" and \"integrable M X\" \"0 < t\"\n  shows \"prob {a \\<in> space M. t \\<le> X a} \\<le> expectation X / t\"\nproof -\n  \\<comment> \\<open>proof adapted from @{thm [source] edge_space.Markov_inequality}, but generalized to arbitrary\n       @{term prob_space}s\\<close>\n  have \"(\\<integral>\\<^sup>+ x. ennreal (X x) \\<partial>M) = (\\<integral>x. X x \\<partial>M)\"\n    using assms by (intro nn_integral_eq_integral) auto\n  thus ?thesis\n    using assms nn_integral_Markov_inequality[of X M \"space M\" \"1 / t\"]\n    by (auto cong: nn_integral_cong simp: emeasure_eq_measure ennreal_mult[symmetric])\nqed\n\ntext\\<open>$\\Var[X] = \\Ex[X^2] - \\Ex[X]^2 $\\<close>\n\nlemma variance_expectation:\n  fixes X :: \"'a \\<Rightarrow> real\"\n  assumes \"integrable M (\\<lambda>x. (X x)^2)\" and \"X \\<in> borel_measurable M\"\n  shows\n    \"integrable M (\\<lambda>x. (X x - expectation X)^2)\" (is ?integrable)\n    \"variance X = expectation (\\<lambda>x. (X x)^2) - (expectation X)^2\" (is ?variance)\nproof -\n  have int: \"integrable M X\"\n    using integrable_squareD[OF assms] by simp\n\n  have \"(\\<lambda>x. (X x - expectation X)^2) = (\\<lambda>x. (X x)^2 + (expectation X)^2 - (2 * X x * expectation X))\"\n    by (simp only: power2_diff)\n  hence\n    \"variance X = expectation (\\<lambda>x. (X x)^2) + (expectation X)^2 + expectation (\\<lambda>x. - (2 * X x * expectation X))\"\n    ?integrable\n    using integral_add by (simp add: int assms prob_space)+\n\n  thus ?variance ?integrable\n    by (simp add: int power2_eq_square)+\nqed\n\ntext\\<open>A corollary from the Markov inequality is Chebyshev's inequality, which gives an upper\nbound for the deviation of a random variable from its expectation:\n\\[ \\Pr[\\left| Y - \\Ex[Y] \\right| \\ge s] \\le \\frac{\\Var[X]}{a^2} \\]\\<close>\n\nlemma chebyshev_inequality:\n  fixes Y :: \"'a \\<Rightarrow> real\"\n  assumes Y_int: \"integrable M (\\<lambda>y. (Y y)^2)\"\n  assumes Y_borel: \"Y \\<in> borel_measurable M\"\n  fixes s :: \"real\"\n  assumes s_pos: \"0 < s\"\n  shows \"prob {a \\<in> space M. s \\<le> \\<bar>Y a - expectation Y\\<bar>} \\<le> variance Y / s^2\"\nproof -\n  let ?X = \"\\<lambda>a. (Y a - expectation Y)^2\"\n  let ?t = \"s^2\"\n\n  have \"0 < ?t\"\n    using s_pos by simp\n  hence \"prob {a \\<in> space M. ?t \\<le> ?X a} \\<le> variance Y / s^2\"\n    using markov_inequality variance_expectation[OF Y_int Y_borel] by (simp add: field_simps)\n  moreover have \"{a \\<in> space M. ?t \\<le> ?X a} = {a \\<in> space M. s \\<le> \\<bar>Y a - expectation Y\\<bar>}\"\n    using abs_le_square_iff s_pos by force\n  ultimately show ?thesis\n    by simp\nqed\n\ntext\\<open>Hence, we can derive an upper bound for the probability that a random variable is $0$.\\<close>\n\ncorollary chebyshev_prob_zero:\n  fixes Y :: \"'a \\<Rightarrow> real\"\n  assumes Y_int: \"integrable M (\\<lambda>y. (Y y)^2)\"\n  assumes Y_borel: \"Y \\<in> borel_measurable M\"\n  assumes \\<mu>_pos: \"expectation Y > 0\"\n  shows \"prob {a \\<in> space M. Y a = 0} \\<le> expectation (\\<lambda>y. (Y y)^2) / (expectation Y)^2 - 1\"\nproof -\n  let ?s = \"expectation Y\"\n\n  have \"prob {a \\<in> space M. Y a = 0} \\<le> prob {a \\<in> space M. ?s \\<le> \\<bar>Y a - ?s\\<bar>}\"\n    using Y_borel by (auto intro!: finite_measure_mono borel_measurable_diff borel_measurable_abs borel_measurable_le)\n  also have \"\\<dots> \\<le> variance Y / ?s^2\"\n    using assms by (fact chebyshev_inequality)\n  also have \"\\<dots> = (expectation (\\<lambda>y. (Y y)^2) - ?s^2) / ?s^2\"\n    using Y_int Y_borel by (simp add: variance_expectation)\n  also have \"\\<dots> = expectation (\\<lambda>y. (Y y)^2) / ?s^2 - 1\"\n    using \\<mu>_pos by (simp add: field_simps)\n  finally show ?thesis .\nqed\n\nend\n\nsubsection\\<open>Sets of indicator variables\\<close>\n\ntext\\<open>\\label{sec:delta}\nThis section introduces some inequalities about expectation and other values related to the sum of\na set of random indicators.\\<close>\n\nlocale prob_space_with_indicators = prob_space +\n  fixes I :: \"'i set\"\n  assumes finite_I: \"finite I\"\n\n  fixes A :: \"'i \\<Rightarrow> 'a set\"\n  assumes A: \"A ` I \\<subseteq> events\"\n\n  assumes prob_non_zero: \"\\<exists>i \\<in> I. 0 < prob (A i)\"\nbegin\n\ntext\\<open>We call the underlying sets @{term \"A i\"} for each @{term \"i \\<in> I\"}, and the corresponding\nindicator variables @{term \"X i\"}. The sum is denoted by @{term Y}, and its expectation by\n@{term \\<mu>}.\\<close>\n\ndefinition \"X i = rind (A i)\"\ndefinition \"Y x = (\\<Sum>i \\<in> I. X i x)\"\n\ndefinition \"\\<mu> = expectation Y\"\n\ntext\\<open>In the lecture notes, the following two relations are called $\\sim$ and $\\nsim$,\nrespectively. Note that they are not the opposite of each other.\\<close>\n\nabbreviation ineq_indep :: \"'i \\<Rightarrow> 'i \\<Rightarrow> bool\" where\n\"ineq_indep i j \\<equiv> (i \\<noteq> j \\<and> indep (A i) (A j))\"\n\nabbreviation ineq_dep :: \"'i \\<Rightarrow> 'i \\<Rightarrow> bool\" where\n\"ineq_dep i j \\<equiv> (i \\<noteq> j \\<and> \\<not>indep (A i) (A j))\"\n\ndefinition \"\\<Delta>\\<^sub>a = (\\<Sum>i \\<in> I. \\<Sum>j | j \\<in> I \\<and> i \\<noteq> j. prob (A i \\<inter> A j))\"\ndefinition \"\\<Delta>\\<^sub>d = (\\<Sum>i \\<in> I. \\<Sum>j | j \\<in> I \\<and> ineq_dep i j. prob (A i \\<inter> A j))\"\n\nlemma \\<Delta>_zero:\n  assumes \"\\<And>i j. i \\<in> I \\<Longrightarrow> j \\<in> I \\<Longrightarrow> i \\<noteq> j \\<Longrightarrow> indep (A i) (A j)\"\n  shows \"\\<Delta>\\<^sub>d = 0\"\nproof -\n  {\n    fix i\n    assume \"i \\<in> I\"\n    hence \"{j. j \\<in> I \\<and> ineq_dep i j} = {}\"\n      using assms by auto\n    hence \"(\\<Sum>j | j \\<in> I \\<and> ineq_dep i j. prob (A i \\<inter> A j)) = 0\"\n      using sum.empty by metis\n  }\n  hence \"\\<Delta>\\<^sub>d = (0 :: real) * card I\"\n    unfolding \\<Delta>\\<^sub>d_def by simp\n  thus ?thesis\n    by simp\nqed\n\nlemma A_events[measurable]: \"i \\<in> I \\<Longrightarrow> A i \\<in> events\"\nusing A by auto\n\nlemma expectation_X_Y: \"\\<mu> = (\\<Sum>i\\<in>I. expectation (X i))\"\nunfolding \\<mu>_def Y_def[abs_def] X_def\nby (simp add: less_top[symmetric])\n\nlemma expectation_X_non_zero: \"\\<exists>i \\<in> I. 0 < expectation (X i)\"\nunfolding X_def using prob_non_zero expectation_indicator by simp\n\ncorollary \\<mu>_non_zero[simp]: \"0 < \\<mu>\"\nunfolding expectation_X_Y\nusing expectation_X_non_zero\nby (auto intro!: sum_lower finite_I\n         simp add: expectation_indicator X_def)\n\nlemma \\<Delta>\\<^sub>d_nonneg: \"0 \\<le> \\<Delta>\\<^sub>d\"\nunfolding \\<Delta>\\<^sub>d_def\nby (simp add: sum_nonneg)\n\ncorollary \\<mu>_sq_non_zero[simp]: \"0 < \\<mu>^2\"\nby (rule zero_less_power) simp\n\nlemma Y_square_unfold: \"(\\<lambda>x. (Y x)^2) = (\\<lambda>x. \\<Sum>i \\<in> I. \\<Sum>j \\<in> I. rind (A i \\<inter> A j) x)\"\nunfolding fun_eq_iff Y_def X_def\nby (auto simp: sum_square product_indicator)\n\nlemma integrable_Y_sq[simp]: \"integrable M (\\<lambda>y. (Y y)^2)\"\nunfolding Y_square_unfold\nby (simp add: sets.Int less_top[symmetric])\n\nlemma measurable_Y[measurable]: \"Y \\<in> borel_measurable M\"\nunfolding Y_def[abs_def] X_def by simp\n\nlemma expectation_Y_\\<Delta>: \"expectation (\\<lambda>x. (Y x)^2) = \\<mu> + \\<Delta>\\<^sub>a\"\nproof -\n  let ?ei = \"\\<lambda>i j. expectation (rind (A i \\<inter> A j))\"\n\n  have \"expectation (\\<lambda>x. (Y x)^2) = (\\<Sum>i \\<in> I. \\<Sum>j \\<in> I. ?ei i j)\"\n    unfolding Y_square_unfold by (simp add: less_top[symmetric])\n  also have \"\\<dots> = (\\<Sum>i \\<in> I. \\<Sum>j \\<in> I. if i = j then ?ei i j else ?ei i j)\"\n    by simp\n  also have \"\\<dots> = (\\<Sum>i \\<in> I. (\\<Sum>j | j \\<in> I \\<and> i = j. ?ei i j) + (\\<Sum>j | j \\<in> I \\<and> i \\<noteq> j. ?ei i j))\"\n    by (simp only: sum_split[OF finite_I])\n  also have \"\\<dots> = (\\<Sum>i \\<in> I. \\<Sum>j | j \\<in> I \\<and> i = j. ?ei i j) + (\\<Sum>i \\<in> I. \\<Sum>j | j \\<in> I \\<and> i \\<noteq> j. ?ei i j)\" (is \"_ = ?lhs + ?rhs\")\n    by (fact sum.distrib)\n  also have \"\\<dots> =  \\<mu> + \\<Delta>\\<^sub>a\"\n    proof -\n      have \"?lhs = \\<mu>\"\n        proof -\n          {\n            fix i\n            assume i: \"i \\<in> I\"\n            have \"(\\<Sum>j | j \\<in> I \\<and> i = j. ?ei i j) = (\\<Sum>j | j \\<in> I \\<and> i = j. ?ei i i)\"\n              by simp\n            also have \"\\<dots> = (\\<Sum>j | i = j. ?ei i i)\"\n              using i by metis\n            also have \"\\<dots> = expectation (rind (A i))\"\n              by auto\n            finally have \"(\\<Sum>j | j \\<in> I \\<and> i = j. ?ei i j) = \\<dots>\" .\n          }\n          hence \"?lhs = (\\<Sum>i\\<in>I. expectation (rind (A i)))\"\n            by force\n          also have \"\\<dots> = \\<mu>\"\n            unfolding expectation_X_Y X_def ..\n          finally show \"?lhs = \\<mu>\" .\n        qed\n      moreover have \"?rhs = \\<Delta>\\<^sub>a\"\n        proof -\n          {\n            fix i j\n            assume \"i \\<in> I\" \"j \\<in> I\"\n            with A have \"A i \\<inter> A j \\<in> events\" by blast\n            hence \"?ei i j = prob (A i \\<inter> A j)\"\n              by (fact expectation_indicator)\n          }\n          thus ?thesis\n            unfolding \\<Delta>\\<^sub>a_def by simp\n        qed\n      ultimately show \"?lhs + ?rhs = \\<mu> + \\<Delta>\\<^sub>a\"\n        by simp\n    qed\n  finally show ?thesis .\nqed\n\nlemma \\<Delta>_expectation_X: \"\\<Delta>\\<^sub>a \\<le> \\<mu>^2 + \\<Delta>\\<^sub>d\"\nproof -\n  let ?p = \"\\<lambda>i j. prob (A i \\<inter> A j)\"\n  let ?p' = \"\\<lambda>i j. prob (A i) * prob (A j)\"\n  let ?ie = \"\\<lambda>i j. indep (A i) (A j)\"\n\n  have \"\\<Delta>\\<^sub>a = (\\<Sum>i \\<in> I. \\<Sum>j | j \\<in> I \\<and> i \\<noteq> j. if ?ie i j then ?p i j else ?p i j)\"\n    unfolding \\<Delta>\\<^sub>a_def by simp\n  also have \"\\<dots> = (\\<Sum>i \\<in> I. (\\<Sum>j | j \\<in> I \\<and> ineq_indep i j. ?p i j) + (\\<Sum>j | j \\<in> I \\<and> ineq_dep i j. ?p i j))\"\n    by (simp only: sum_split2[OF finite_I])\n  also have \"\\<dots> = (\\<Sum>i \\<in> I. \\<Sum>j | j \\<in> I \\<and> ineq_indep i j. ?p i j) + \\<Delta>\\<^sub>d\" (is \"_ = ?lhs + _\")\n    unfolding \\<Delta>\\<^sub>d_def by (fact sum.distrib)\n  also have \"\\<dots> \\<le> \\<mu>^2 + \\<Delta>\\<^sub>d\"\n    proof (rule add_right_mono)\n      have \"(\\<Sum>i\\<in>I. \\<Sum>j | j \\<in> I \\<and> ineq_indep i j. ?p i j) = (\\<Sum>i \\<in> I. \\<Sum>j | j \\<in> I \\<and> ineq_indep i j. ?p' i j)\"\n        unfolding indep_def by simp\n      also have \"\\<dots> \\<le> (\\<Sum>i \\<in> I. \\<Sum>j \\<in> I. ?p' i j)\"\n        proof (rule sum_mono)\n          fix i\n          assume \"i \\<in> I\"\n          show \"(\\<Sum>j | j \\<in> I \\<and> ineq_indep i j. ?p' i j) \\<le> (\\<Sum>j\\<in>I. ?p' i j)\"\n            by (rule sum_upper[OF finite_I]) (simp add: zero_le_mult_iff)\n        qed\n      also have \"\\<dots> = (\\<Sum>i \\<in> I. prob (A i))^2\"\n        by (fact sum_square[symmetric])\n      also have \"\\<dots> = (\\<Sum>i \\<in> I. expectation (X i))^2\"\n        unfolding X_def using expectation_indicator A by simp\n      also have \"\\<dots> = \\<mu>^2\"\n        using expectation_X_Y[symmetric] by simp\n      finally show \"?lhs \\<le> \\<mu>^2\" .\n    qed\n  finally show ?thesis .\nqed\n\nlemma prob_\\<mu>_\\<Delta>\\<^sub>a: \"prob {a \\<in> space M. Y a = 0} \\<le> 1 / \\<mu> + \\<Delta>\\<^sub>a / \\<mu>^2 - 1\"\nproof -\n  have \"prob {a \\<in> space M. Y a = 0} \\<le> expectation (\\<lambda>y. (Y y)^2) / \\<mu>^2 - 1\"\n    unfolding \\<mu>_def by (rule chebyshev_prob_zero) (simp add: \\<mu>_def[symmetric])+\n  also have \"\\<dots> = (\\<mu> + \\<Delta>\\<^sub>a) / \\<mu>^2 - 1\"\n    using expectation_Y_\\<Delta> by simp\n  also have \"\\<dots> = 1 / \\<mu> + \\<Delta>\\<^sub>a / \\<mu>^2 - 1\"\n    unfolding power2_eq_square by (simp add: field_simps add_divide_distrib)\n  finally show ?thesis .\nqed\n\nlemma prob_\\<mu>_\\<Delta>\\<^sub>d: \"prob {a \\<in> space M. Y a = 0} \\<le> 1/\\<mu> + \\<Delta>\\<^sub>d/\\<mu>^2\"\nproof -\n  have \"prob {a \\<in> space M. Y a = 0} \\<le> 1/\\<mu> + \\<Delta>\\<^sub>a/\\<mu>^2 - 1\"\n    by (fact prob_\\<mu>_\\<Delta>\\<^sub>a)\n  also have \"\\<dots> = (1/\\<mu> - 1) + \\<Delta>\\<^sub>a/\\<mu>^2\"\n    by simp\n  also have \"\\<dots> \\<le> (1/\\<mu> - 1) + (\\<mu>^2 + \\<Delta>\\<^sub>d)/\\<mu>^2\"\n    using divide_right_mono[OF \\<Delta>_expectation_X] by simp\n  also have \"\\<dots> = 1/\\<mu> + \\<Delta>\\<^sub>d/\\<mu>^2\"\n    using \\<mu>_sq_non_zero by (simp add: field_simps)\n  finally show ?thesis .\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/Random_Graph_Subgraph_Threshold/Prob_Lemmas.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8688267864276108, "lm_q2_score": 0.8198933359135361, "lm_q1q2_score": 0.7123452922551712}}
{"text": "(*\n  File:    HOL/Number_Theory/Mod_Exp\n  Author:  Manuel Eberl, TU M\u00fcnchen\n\n  Fast implementation of modular exponentiation and \"cong\" using exponentiation by squaring.\n  Includes code setup for nat and int.\n*)\nsection \\<open>Fast modular exponentiation\\<close>\ntheory Mod_Exp\n  imports Cong \"HOL-Library.Power_By_Squaring\"\nbegin\n\ncontext euclidean_semiring_cancel\nbegin\n\ndefinition mod_exp_aux :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> nat \\<Rightarrow> 'a\"\n  where \"mod_exp_aux m = efficient_funpow (\\<lambda>x y. x * y mod m)\"\n\nlemma mod_exp_aux_code [code]:\n  \"mod_exp_aux m y x n =\n     (if n = 0 then y\n      else if n = 1 then (x * y) mod m\n      else if even n then mod_exp_aux m y ((x * x) mod m) (n div 2)\n      else mod_exp_aux m ((x * y) mod m) ((x * x) mod m) (n div 2))\"\n  unfolding mod_exp_aux_def by (rule efficient_funpow_code)\n\nlemma mod_exp_aux_correct:\n  \"mod_exp_aux m y x n mod m = (x ^ n * y) mod m\"\nproof -\n  have \"mod_exp_aux m y x n = efficient_funpow (\\<lambda>x y. x * y mod m) y x n\"\n    by (simp add: mod_exp_aux_def)\n  also have \"\\<dots> = ((\\<lambda>y. x * y mod m) ^^ n) y\"\n    by (rule efficient_funpow_correct) (simp add: mod_mult_left_eq mod_mult_right_eq mult_ac)\n  also have \"((\\<lambda>y. x * y mod m) ^^ n) y mod m = (x ^ n * y) mod m\"\n  proof (induction n)\n    case (Suc n)\n    hence \"x * ((\\<lambda>y. x * y mod m) ^^ n) y mod m = x * x ^ n * y mod m\"\n      by (metis mod_mult_right_eq mult.assoc)\n    thus ?case by auto\n  qed auto\n  finally show ?thesis .\nqed\n\ndefinition mod_exp :: \"'a \\<Rightarrow> nat \\<Rightarrow> 'a \\<Rightarrow> 'a\"\n  where \"mod_exp b e m = (b ^ e) mod m\"\n\nlemma mod_exp_code [code]: \"mod_exp b e m = mod_exp_aux m 1 b e mod m\"\n  by (simp add: mod_exp_def mod_exp_aux_correct)\n\nend\n\n(*\n  TODO: Setup here only for nat and int. Could be done for any\n  euclidean_semiring_cancel. Should it?\n*)\nlemmas [code_abbrev] = mod_exp_def[where ?'a = nat] mod_exp_def[where ?'a = int]\n\nlemma cong_power_nat_code [code_unfold]:\n  \"[b ^ e = (x ::nat)] (mod m) \\<longleftrightarrow> mod_exp b e m = x mod m\"\n  by (simp add: mod_exp_def cong_def)\n\nlemma cong_power_int_code [code_unfold]:\n  \"[b ^ e = (x ::int)] (mod m) \\<longleftrightarrow> mod_exp b e m = x mod m\"\n  by (simp add: mod_exp_def cong_def)\n\n\ntext \\<open>\n  The following rules allow the simplifier to evaluate @{const mod_exp} efficiently.\n\\<close>\nlemma eval_mod_exp_aux [simp]:\n  \"mod_exp_aux m y x 0 = y\"\n  \"mod_exp_aux m y x (Suc 0) = (x * y) mod m\"\n  \"mod_exp_aux m y x (numeral (num.Bit0 n)) =\n     mod_exp_aux m y (x\\<^sup>2 mod m) (numeral n)\"\n  \"mod_exp_aux m y x (numeral (num.Bit1 n)) =\n     mod_exp_aux m ((x * y) mod m) (x\\<^sup>2 mod m) (numeral n)\"\nproof -\n  define n' where \"n' = (numeral n :: nat)\"\n  have [simp]: \"n' \\<noteq> 0\" by (auto simp: n'_def)\n  \n  show \"mod_exp_aux m y x 0 = y\" and \"mod_exp_aux m y x (Suc 0) = (x * y) mod m\"\n    by (simp_all add: mod_exp_aux_def)\n\n  have \"numeral (num.Bit0 n) = (2 * n')\"\n    by (subst numeral.numeral_Bit0) (simp del: arith_simps add: n'_def)\n  also have \"mod_exp_aux m y x \\<dots> = mod_exp_aux m y (x^2 mod m) n'\"\n    by (subst mod_exp_aux_code) (simp_all add: power2_eq_square)\n  finally show \"mod_exp_aux m y x (numeral (num.Bit0 n)) =\n                  mod_exp_aux m y (x\\<^sup>2 mod m) (numeral n)\"\n    by (simp add: n'_def)\n\n  have \"numeral (num.Bit1 n) = Suc (2 * n')\"\n    by (subst numeral.numeral_Bit1) (simp del: arith_simps add: n'_def)\n  also have \"mod_exp_aux m y x \\<dots> = mod_exp_aux m ((x * y) mod m) (x^2 mod m) n'\"\n    by (subst mod_exp_aux_code) (simp_all add: power2_eq_square)\n  finally show \"mod_exp_aux m y x (numeral (num.Bit1 n)) =\n                  mod_exp_aux m ((x * y) mod m) (x\\<^sup>2 mod m) (numeral n)\"\n    by (simp add: n'_def)\nqed\n\nlemma eval_mod_exp [simp]:\n  \"mod_exp b' 0 m' = 1 mod m'\"\n  \"mod_exp b' 1 m' = b' mod m'\"\n  \"mod_exp b' (Suc 0) m' = b' mod m'\"\n  \"mod_exp b' e' 0 = b' ^ e'\"  \n  \"mod_exp b' e' 1 = 0\"\n  \"mod_exp b' e' (Suc 0) = 0\"\n  \"mod_exp 0 1 m' = 0\"\n  \"mod_exp 0 (Suc 0) m' = 0\"\n  \"mod_exp 0 (numeral e) m' = 0\"\n  \"mod_exp 1 e' m' = 1 mod m'\"\n  \"mod_exp (Suc 0) e' m' = 1 mod m'\"\n  \"mod_exp (numeral b) (numeral e) (numeral m) =\n     mod_exp_aux (numeral m) 1 (numeral b) (numeral e) mod numeral m\"\n  by (simp_all add: mod_exp_def mod_exp_aux_correct)\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/Mod_Exp.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267728417087, "lm_q2_score": 0.819893340314393, "lm_q1q2_score": 0.7123452849397629}}
{"text": "(*\n  File:    Data_Structures/Time_Functions.thy\n  Author:  Manuel Eberl, TU M\u00fcnchen\n*)\nsection \\<open>Time functions for various standard library operations\\<close>\ntheory Time_Funs\n  imports Main\nbegin\n\nfun T_length :: \"'a list \\<Rightarrow> nat\" where\n  \"T_length [] = 1\"\n| \"T_length (x # xs) = T_length xs + 1\"\n\nlemma T_length_eq: \"T_length xs = length xs + 1\"\n  by (induction xs) auto\n\nlemmas [simp del] = T_length.simps\n\n\nfun T_map  :: \"('a \\<Rightarrow> nat) \\<Rightarrow> 'a list \\<Rightarrow> nat\" where\n  \"T_map T_f [] = 1\"\n| \"T_map T_f (x # xs) = T_f x + T_map T_f xs + 1\"\n\nlemma T_map_eq: \"T_map T_f xs = (\\<Sum>x\\<leftarrow>xs. T_f x) + length xs + 1\"\n  by (induction xs) auto\n\nlemmas [simp del] = T_map.simps\n\n\nfun T_filter  :: \"('a \\<Rightarrow> nat) \\<Rightarrow> 'a list \\<Rightarrow> nat\" where\n  \"T_filter T_p [] = 1\"\n| \"T_filter T_p (x # xs) = T_p x + T_filter T_p xs + 1\"\n\nlemma T_filter_eq: \"T_filter T_p xs = (\\<Sum>x\\<leftarrow>xs. T_p x) + length xs + 1\"\n  by (induction xs) auto\n\nlemmas [simp del] = T_filter.simps\n\n\nfun T_nth :: \"'a list \\<Rightarrow> nat \\<Rightarrow> nat\" where\n  \"T_nth [] n = 1\"\n| \"T_nth (x # xs) n = (case n of 0 \\<Rightarrow> 1 | Suc n' \\<Rightarrow> T_nth xs n' + 1)\"\n\nlemma T_nth_eq: \"T_nth xs n = min n (length xs) + 1\"\n  by (induction xs n rule: T_nth.induct) (auto split: nat.splits)\n\nlemmas [simp del] = T_nth.simps\n\n\nfun T_take :: \"nat \\<Rightarrow> 'a list \\<Rightarrow> nat\" where\n  \"T_take n [] = 1\"\n| \"T_take n (x # xs) = (case n of 0 \\<Rightarrow> 1 | Suc n' \\<Rightarrow> T_take n' xs + 1)\"\n\nlemma T_take_eq: \"T_take n xs = min n (length xs) + 1\"\n  by (induction xs arbitrary: n) (auto split: nat.splits)\n\nfun T_drop :: \"nat \\<Rightarrow> 'a list \\<Rightarrow> nat\" where\n  \"T_drop n [] = 1\"\n| \"T_drop n (x # xs) = (case n of 0 \\<Rightarrow> 1 | Suc n' \\<Rightarrow> T_drop n' xs + 1)\"\n\nlemma T_drop_eq: \"T_drop n xs = min n (length xs) + 1\"\n  by (induction xs arbitrary: n) (auto split: nat.splits)\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/Data_Structures/Time_Funs.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.868826769445233, "lm_q2_score": 0.8198933271118222, "lm_q1q2_score": 0.7123452706842681}}
{"text": "section \\<open>Computing the Gcd via the subresultant PRS\\<close>\n\ntext \\<open>This theory now formalizes how the subresultant PRS can be used to calculate the gcd\n  of two polynomials. Moreover, it proves the connection between resultants and gcd, namely that\n  the resultant is 0 iff the degree of the gcd is non-zero.\\<close>\n\ntheory Subresultant_Gcd\nimports\n  Subresultant\n  Polynomial_Factorization.Missing_Polynomial_Factorial\nbegin\n\nsubsection \\<open>Algorithm\\<close>\n\ndefinition gcd_impl_primitive where\n  [code del]: \"gcd_impl_primitive G1 G2 = normalize (primitive_part (fst (subresultant_prs dichotomous_Lazard G1 G2)))\" \n\ndefinition gcd_impl_main where\n  [code del]: \"gcd_impl_main G1 G2 = (if G1 = 0 then 0 else if G2 = 0 then normalize G1 else\n   smult (gcd (content G1) (content G2))\n     (gcd_impl_primitive (primitive_part G1) (primitive_part G2)))\"\n\ndefinition gcd_impl where\n  \"gcd_impl f g = (if length (coeffs f) \\<ge> length (coeffs g) then gcd_impl_main f g  else gcd_impl_main g f)\"\n\nsubsection \\<open>Soundness Proof for @{term \"gcd_impl = gcd\"}\\<close>\n\nlocale subresultant_prs_gcd = subresultant_prs_locale2 F n \\<delta> f k \\<beta> G1 G2 for\n       F :: \"nat \\<Rightarrow> 'a ::  {factorial_ring_gcd,semiring_gcd_mult_normalize} fract poly\"\n    and n :: \"nat \\<Rightarrow> nat\"\n    and \\<delta> :: \"nat \\<Rightarrow> nat\"\n    and f :: \"nat \\<Rightarrow> 'a fract\"\n    and k :: nat\n    and \\<beta> :: \"nat \\<Rightarrow> 'a fract\"\n    and G1 G2 :: \"'a poly\"\nbegin\ntext \\<open>The subresultant PRS computes the gcd up to a scalar multiple.\\<close>\n\nlemma subresultant_prs_gcd: assumes \"subresultant_prs dichotomous_Lazard G1 G2 = (Gk, hk)\"\n  shows \"\\<exists> a b. a \\<noteq> 0 \\<and> b \\<noteq> 0 \\<and> smult a (gcd G1 G2) = smult b (normalize Gk)\"\nproof -\n  from subresultant_prs[OF dichotomous_Lazard assms]\n  have Fk: \"F k = ffp Gk\" and \"\\<forall> i. \\<exists> H. i \\<noteq> 0 \\<longrightarrow> F i = ffp H\"\n    and \"\\<forall> i. \\<exists> b. 3 \\<le> i \\<longrightarrow> i \\<le> Suc k \\<longrightarrow> \\<beta> i = ff b\" by auto\n  from choice[OF this(2)] choice[OF this(3)] obtain H beta where\n    FH: \"\\<And> i. i \\<noteq> 0 \\<Longrightarrow> F i = ffp (H i)\" and\n    beta: \"\\<And> i. 3 \\<le> i \\<Longrightarrow> i \\<le> Suc k \\<Longrightarrow> \\<beta> i = ff (beta i)\" by auto\n  from Fk FH[OF k0] FH[of 1] FH[of 2] FH[of \"Suc k\"] F0[of \"Suc k\"] F1 F2\n  have border: \"H k = Gk\" \"H 1 = G1\" \"H 2 = G2\" \"H (Suc k) = 0\" by auto\n  have \"i \\<noteq> 0 \\<Longrightarrow> i \\<le> k \\<Longrightarrow> \\<exists> a b. a \\<noteq> 0 \\<and> b \\<noteq> 0 \\<and> smult a (gcd G1 G2) = smult b (gcd (H i) (H (Suc i)))\" for i\n  proof (induct i rule: less_induct)\n    case (less i)\n    from less(3) have ik: \"i \\<le> k\" .\n    from less(2) have \"i = 1 \\<or> i \\<ge> 2\" by auto\n    thus ?case\n    proof\n      assume \"i = 1\"\n      thus ?thesis unfolding border[symmetric] by (intro exI[of _ 1], auto simp: numeral_2_eq_2)\n    next\n      assume i2: \"i \\<ge> 2\"\n      with ik have \"i - 1 < i\" \"i - 1 \\<noteq> 0\" and imk: \"i - 1 \\<le> k\" by auto\n      from less(1)[OF this] i2\n      obtain a b where a: \"a \\<noteq> 0\" and b: \"b \\<noteq> 0\" and IH: \"smult a (gcd G1 G2) = smult b (gcd (H (i - 1)) (H i))\" by auto\n      define M where \"M = pseudo_mod (H (i - 1)) (H i)\"\n      define c where \"c = \\<beta> (Suc i)\"\n      have M: \"pseudo_mod (F (i - 1)) (F i) = ffp M\" unfolding to_fract_hom.pseudo_mod_hom[symmetric] M_def\n         using i2 FH by auto\n      have c: \"c \\<noteq> 0\" using \\<beta>0 unfolding c_def .\n      from i2 ik have 3: \"Suc i \\<ge> 3\" \"Suc i \\<le> Suc k\" by auto\n      from pmod[OF 3]\n      have pm: \"smult c (F (Suc i)) = pseudo_mod (F (i - 1)) (F i)\" unfolding c_def by simp\n      from beta[OF 3, folded c_def] obtain d where cd: \"c = ff d\" by auto\n      with c have d: \"d \\<noteq> 0\" by auto\n      from pm[unfolded cd M] FH[of \"Suc i\"]\n      have \"ffp (smult d (H (Suc i))) = ffp M\" by auto\n      hence pm: \"smult d (H (Suc i)) = M\" by (rule map_poly_hom.injectivity)\n      from ik F0[of i] i2 FH[of i] have Hi0: \"H i \\<noteq> 0\" by auto\n      from pseudo_mod[OF this, of \"H (i - 1)\", folded M_def]\n      obtain c Q where c: \"c \\<noteq> 0\" and \"smult c (H (i - 1)) = H i * Q + M\" by auto\n      from this[folded pm] have \"smult c (H (i - 1)) = Q * H i + smult d (H (Suc i))\" by simp\n      from gcd_add_mult[of \"H i\" Q \"smult d (H (Suc i))\", folded this]\n      have \"gcd (H i) (smult c (H (i - 1))) = gcd (H i) (smult d (H (Suc i)))\" .\n      with gcd_smult_ex[OF c, of \"H (i - 1)\" \"H i\"] obtain e where\n        e: \"e \\<noteq> 0\" and \"gcd (H i) (smult d (H (Suc i))) = smult e (gcd (H i) (H (i - 1)))\"\n        unfolding gcd.commute[of \"H i\"] by auto\n      with gcd_smult_ex[OF d, of \"H (Suc i)\" \"H i\"] obtain c where\n        c: \"c \\<noteq> 0\" and \"smult c (gcd (H i) (H (Suc i))) = smult e (gcd (H (i - 1)) (H i))\"\n        unfolding gcd.commute[of \"H i\"] by auto\n      from arg_cong[OF this(2), of \"smult b\"] arg_cong[OF IH, of \"smult e\"]\n      have \"smult (e * a) (gcd G1 G2) = smult (b * c) (gcd (H i) (H (Suc i)))\" unfolding smult_smult\n        by (simp add: ac_simps)\n      moreover have \"e * a \\<noteq> 0\" \"b * c \\<noteq> 0\" using a b c e by auto\n      ultimately show ?thesis by blast\n    qed\n  qed\n  from this[OF k0 le_refl, unfolded border]\n  obtain a b where \"a \\<noteq> 0\" \"b \\<noteq> 0\" and \"smult a (gcd G1 G2) = smult b (normalize Gk)\" by auto\n  thus ?thesis by auto\nqed\n\n\nlemma gcd_impl_primitive: assumes \"primitive_part G1 = G1\" and \"primitive_part G2 = G2\"\nshows \"gcd_impl_primitive G1 G2 = gcd G1 G2\"\nproof -\n  let ?pp = primitive_part\n  let ?c = \"content\"\n  let ?n = normalize\n  from F2 F0[of 2] k2 have G2: \"G2 \\<noteq> 0\" by auto\n  obtain Gk hk where sub: \"subresultant_prs dichotomous_Lazard G1 G2 = (Gk, hk)\" by force\n  have impl: \"gcd_impl_primitive G1 G2 = ?n (?pp Gk)\" unfolding gcd_impl_primitive_def sub by auto\n  from subresultant_prs_gcd[OF sub]\n  obtain a b where a: \"a \\<noteq> 0\" and b: \"b \\<noteq> 0\" and id: \"smult a (gcd G1 G2) = smult b (?n Gk)\"\n    by auto\n  define c where \"c = unit_factor (gcd G1 G2)\"\n  define d where \"d = smult (unit_factor a) c\"\n  from G2 have c: \"is_unit c\" unfolding c_def by auto\n  from arg_cong[OF id, of ?pp, unfolded primitive_part_smult primitive_part_gcd assms\n     primitive_part_normalize c_def[symmetric]]\n  have id: \"d * gcd G1 G2 = smult (unit_factor b) (?n (?pp Gk))\" unfolding d_def by simp\n  have d: \"is_unit d\" unfolding d_def using c a\n    by (simp add: is_unit_smult_iff)\n  from is_unitE[OF d]\n  obtain e where e: \"is_unit e\" and de: \"d * e = 1\" by metis\n  define a where \"a = smult (unit_factor b) e\"\n  from arg_cong[OF id, of \"\\<lambda> x. e * x\"]\n  have \"(d * e) * gcd G1 G2 = a * (?n (?pp Gk))\" by (simp add: ac_simps a_def)\n  hence id: \"gcd G1 G2 = a * (?n (?pp Gk))\" using de by simp\n  have a: \"is_unit a\" unfolding a_def using b e\n    by (simp add: is_unit_smult_iff)\n  define b where \"b = unit_factor (?pp Gk)\"\n  have \"Gk \\<noteq> 0\" using subresultant_prs[OF dichotomous_Lazard sub] F0[OF k0] by auto\n  hence b: \"is_unit b\" unfolding b_def by auto\n  from is_unitE[OF b]\n  obtain c where c: \"is_unit c\" and bc: \"b * c = 1\" by metis\n  obtain d where d: \"is_unit d\" and dac: \"d = a * c\" using c a by auto\n  have \"gcd G1 G2 = d * (b * ?n (?pp Gk))\"\n    unfolding id dac using bc by (simp add: ac_simps)\n  also have \"b * ?n (?pp Gk) = ?pp Gk\" unfolding b_def by simp\n  finally have \"gcd G1 G2 = d * ?pp Gk\" by simp\n  from arg_cong[OF this, of ?n]\n  have \"gcd G1 G2 = ?n (d * ?pp Gk)\" by simp\n  also have \"\\<dots> = ?n (?pp Gk)\" using d\n    unfolding normalize_mult by (simp add: is_unit_normalize)\n  finally show ?thesis unfolding impl ..\nqed\nend\n\nlemma gcd_impl_main: assumes len: \"length (coeffs G1) \\<ge> length (coeffs G2)\"\n  shows \"gcd_impl_main G1 G2 = gcd G1 G2\"\nproof (cases \"G1 = 0\")\n  case G1: False\n  show ?thesis\n  proof (cases \"G2 = 0\")\n    case G2: False\n    let ?pp = \"primitive_part\"\n    from G2 have G2: \"?pp G2 \\<noteq> 0\" and id: \"(G2 = 0) = False\" by auto\n    from len have len: \"length (coeffs (?pp G1)) \\<ge> length (coeffs (?pp G2))\" by simp\n    from enter_subresultant_prs[OF len G2] obtain F n d f k b\n      where \"subresultant_prs_locale2 F n d f k b (?pp G1) (?pp G2)\" by auto\n    interpret subresultant_prs_locale2 F n d f k b \"?pp G1\" \"?pp G2\" by fact\n    interpret subresultant_prs_gcd F n d f k b \"?pp G1\" \"?pp G2\" ..\n    show ?thesis unfolding gcd_impl_main_def gcd_poly_decompose[of G1] id if_False using G1\n      by (subst gcd_impl_primitive, auto)\n  next\n    case True\n    thus ?thesis unfolding gcd_impl_main_def by simp\n  qed\nnext\n  case True\n  with len have \"G2 = 0\" by auto\n  thus ?thesis using True unfolding gcd_impl_main_def by simp\nqed\n\n\n\n\n\ntext \\<open>The implementation also reveals an important connection between resultant and gcd.\\<close>\n\nlemma resultant_0_gcd: \"resultant f g = 0 \\<longleftrightarrow> degree (gcd f g) \\<noteq> 0\"\nproof -\n  {\n    fix f g :: \"'a poly\"\n    assume len: \"length (coeffs f) \\<ge> length (coeffs g)\"\n    {\n      assume g: \"g \\<noteq> 0\"\n      with len have f: \"f \\<noteq> 0\" by auto\n      let ?f = \"primitive_part f\"\n      let ?g = \"primitive_part g\"\n      let ?c = \"content\"\n      from len have len: \"length (coeffs ?f) \\<ge> length (coeffs ?g)\" by simp\n      obtain Gk hk where sub: \"subresultant_prs dichotomous_Lazard ?f ?g = (Gk,hk)\" by force\n      have cf: \"?c f \\<noteq> 0\" and cg: \"?c g \\<noteq> 0\" using f g by auto\n      {\n        from g have \"?g \\<noteq> 0\" by auto\n        from enter_subresultant_prs[OF len this] obtain F n d f k b\n          where \"subresultant_prs_locale2 F n d f k b ?f ?g\" by auto\n        interpret subresultant_prs_locale2 F n d f k b ?f ?g by fact\n        from subresultant_prs[OF dichotomous_Lazard sub] have \"h k = ff hk\" by auto\n        with h0[OF le_refl] have \"hk \\<noteq> 0\" by auto\n      } note hk0 = this\n      have \"resultant f g = 0 \\<longleftrightarrow> resultant (smult (?c f) ?f) (smult (?c g) ?g) = 0\" by simp\n      also have \"\\<dots> \\<longleftrightarrow> resultant ?f ?g = 0\" unfolding resultant_smult_left[OF cf] resultant_smult_right[OF cg]\n        using cf cg by auto\n      also have \"\\<dots> \\<longleftrightarrow> resultant_impl_main dichotomous_Lazard ?f ?g = 0\" \n        unfolding resultant_impl[symmetric] resultant_impl_def resultant_impl_main_def \n        resultant_impl_generic_def using len by auto\n      also have \"\\<dots> \\<longleftrightarrow> (degree Gk \\<noteq> 0)\"\n        unfolding resultant_impl_main_def sub split using g hk0 by auto\n      also have \"degree Gk = degree (gcd_impl_primitive ?f ?g)\"\n        unfolding gcd_impl_primitive_def sub by simp\n      also have \"\\<dots> = degree (gcd_impl_main f g)\"\n        unfolding gcd_impl_main_def using f g by auto\n      also have \"\\<dots> = degree (gcd f g)\" unfolding gcd_impl[symmetric] gcd_impl_def using len by auto\n      finally have \"(resultant f g = 0) = (degree (gcd f g) \\<noteq> 0)\" .\n    }\n    moreover\n    {\n      assume g: \"g = 0\" and f: \"degree f \\<noteq> 0\"\n      have \"(resultant f g = 0) = (degree (gcd f g) \\<noteq> 0)\"\n        unfolding g using f by auto\n    }\n    moreover\n    {\n      assume g: \"g = 0\" and f: \"degree f = 0\"\n      have \"(resultant f g = 0) = (degree (gcd f g) \\<noteq> 0)\"\n        unfolding g using f by (auto simp: resultant_def sylvester_mat_def sylvester_mat_sub_def)\n    }\n    ultimately have \"(resultant f g = 0) = (degree (gcd f g) \\<noteq> 0)\" by blast\n  } note main = this\n  show ?thesis\n  proof (cases \"length (coeffs f) \\<ge> length (coeffs g)\")\n    case True\n    from main[OF True] show ?thesis .\n  next\n    case False\n    hence \"length (coeffs g) \\<ge> length (coeffs f)\" by auto\n    from main[OF this] show ?thesis\n      unfolding gcd.commute[of g f] resultant_swap[of g f] by (simp split: if_splits)\n  qed\nqed\n\nsubsection \\<open>Code Equations\\<close>\n\ndefinition [code del]:\n  \"gcd_impl_rec = subresultant_prs_main_impl fst\"\ndefinition [code del]:\n  \"gcd_impl_start = subresultant_prs_impl fst\"\n\nlemma gcd_impl_rec_code[code]:\n  \"gcd_impl_rec Gi_1 Gi ni_1 d1_1 hi_2 = (\n    let pmod = pseudo_mod Gi_1 Gi\n     in\n     if pmod = 0 then Gi\n        else let\n           ni = degree Gi;\n           d1 = ni_1 - ni;\n           gi_1 = lead_coeff Gi_1;\n           hi_1 = (if d1_1 = 1 then gi_1 else dichotomous_Lazard gi_1 hi_2 d1_1);\n           divisor = if d1 = 1 then gi_1 * hi_1 else if even d1 then - gi_1 * hi_1 ^ d1 else gi_1 * hi_1 ^ d1;\n           Gi_p1 = sdiv_poly pmod divisor\n       in gcd_impl_rec Gi Gi_p1 ni d1 hi_1)\"\n  unfolding gcd_impl_rec_def subresultant_prs_main_impl.simps[of _ Gi_1] split Let_def\n  unfolding gcd_impl_rec_def[symmetric]\n  by (rule if_cong, auto)\n\nlemma gcd_impl_start_code[code]:\n  \"gcd_impl_start G1 G2 =\n     (let pmod = pseudo_mod G1 G2\n         in if pmod = 0 then G2\n            else let\n                 n2 = degree G2;\n                 n1 = degree G1;\n                 d1 = n1 - n2;\n                 G3 = if even d1 then - pmod else pmod;\n                 pmod = pseudo_mod G2 G3\n                 in if pmod = 0\n                    then G3\n                    else let\n                           g2 = lead_coeff G2;\n                           n3 = degree G3;\n                           h2 = (if d1 = 1 then g2 else g2 ^ d1);\n                           d2 = n2 - n3;\n                           divisor = (if d2 = 1 then g2 * h2 else if even d2 then - g2 * h2 ^ d2 else g2 * h2 ^ d2);\n                           G4 = sdiv_poly pmod divisor\n                         in gcd_impl_rec G3 G4 n3 d2 h2)\"\nproof -\n  obtain d1 where d1: \"degree G1 - degree G2 = d1\" by auto\n  have id1: \"(if even d1 then - pmod else pmod) = (-1)^ (d1 + 1) * (pmod :: 'a poly)\" for pmod by simp\n  show ?thesis\n    unfolding gcd_impl_start_def subresultant_prs_impl_def gcd_impl_rec_def[symmetric] Let_def split\n    unfolding d1\n    unfolding id1\n    by (rule if_cong, auto)\nqed\n\nlemma gcd_impl_main_code[code]:\n  \"gcd_impl_main G1 G2 = (if G1 = 0 then 0 else if G2 = 0 then normalize G1 else\n    let c1 = content G1;\n      c2 = content G2;\n      p1 = map_poly (\\<lambda> x. x div c1) G1;\n      p2 = map_poly (\\<lambda> x. x div c2) G2\n     in smult (gcd c1 c2) (normalize (primitive_part (gcd_impl_start p1 p2))))\"\n  unfolding gcd_impl_main_def Let_def primitive_part_def gcd_impl_start_def gcd_impl_primitive_def\n    subresultant_prs_impl by simp\n\ncorollary gcd_via_subresultant: \"gcd f g = gcd_impl f g\" by simp\n\ntext \\<open>Note that we did not activate @{thm gcd_via_subresultant} as code-equation, since according to our experiments,\n  the subresultant-gcd algorithm is not always more efficient than the currently active equation.\n  In particular, on @{typ \"int poly\"} @{const gcd_impl} performs worse, but on multi-variate polynomials,\n  e.g., @{typ \"int poly poly poly\"}, @{const gcd_impl} is preferable.\\<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/Subresultants/Subresultant_Gcd.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8615382165412809, "lm_q2_score": 0.8267118026095991, "lm_q1q2_score": 0.7122438120139015}}
{"text": "theory Auxiliary\nimports\n  \"HOL-Library.FuncSet\"\n  \"HOL-Combinatorics.Orbits\"\nbegin\n\nlemma 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\nsection \\<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 has_domD: \"has_dom f S \\<Longrightarrow> x \\<notin> S \\<Longrightarrow> f x = x\"\n  by (auto simp: has_dom_def)\n\nlemma has_domI: \"(\\<And>x. x \\<notin> S \\<Longrightarrow> f x = x) \\<Longrightarrow> has_dom f S\"\n  by (auto simp: has_dom_def)\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\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)\n  also have \"\\<dots> = (f ^^ funpow_dist1 f x y) x\"\n    using \\<open>n < _\\<close> by (simp add: funpow_add)\n      (metis assms funpow_0 funpow_neq_less_funpow_dist1 n(1) n(3) nat_neq_iff zero_less_Suc) \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": "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/Graph_Theory/Auxiliary.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382094310355, "lm_q2_score": 0.8267118004748677, "lm_q1q2_score": 0.712243804296625}}
{"text": "\\<^marker>\\<open>creator Florian Ke\u00dfler\\<close>\n\nsection \"Binary Arithmetic\"\n\ntheory Binary_Arithmetic\n  imports Main IMP_Minus_Minus_Small_StepT \"HOL-Library.Discrete\"\n\nbegin\n\ntext \\<open> In this theory, we introduce functions to access bits out of nats, and Lemmas that relate\n        the bits in the result of addition and subtraction to the bits of the original numbers. \\<close>\n\nfun nth_bit_nat:: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\" where\n  \"nth_bit_nat x 0 = x mod 2\" |\n  \"nth_bit_nat x (Suc n) = nth_bit_nat (x div 2) n\"\n\nfun nth_bit_tail:: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\" where\n  \"nth_bit_tail x 0 = x mod 2\" |\n  \"nth_bit_tail x (Suc n) = nth_bit_tail (x div 2) n\"\n\nlemma subtail_nth_bit: \"nth_bit_tail x n = nth_bit_nat x n\"\n  by(induct x n rule: nth_bit_tail.induct) simp+\n\nlemma nth_bit_nat_is_right_shift: \"nth_bit_nat x n = (x div 2 ^ n) mod 2\"\n  apply(induction n arbitrary: x)\n  by(auto simp:  div_mult2_eq)\n\ndefinition nth_bit:: \"nat \\<Rightarrow> nat \\<Rightarrow> bit\" where\n\"nth_bit x n = nat_to_bit (nth_bit_nat x n)\" \n\nfun nth_bit_of_num:: \"num \\<Rightarrow> nat \\<Rightarrow> bit\" where\n\"nth_bit_of_num Num.One 0 = One\" |\n\"nth_bit_of_num Num.One (Suc n) = Zero\" | \n\"nth_bit_of_num (Num.Bit0 x) 0 = Zero\" |\n\"nth_bit_of_num (Num.Bit1 x) 0 = One\" |\n\"nth_bit_of_num (Num.Bit0 x) (Suc n) = nth_bit_of_num x n\" |\n\"nth_bit_of_num (Num.Bit1 x) (Suc n) = nth_bit_of_num x n\"\n\nlemma nth_bit_nat_of_zero[simp]: \"nth_bit_nat 0 n = 0\" \n  by (induction n) auto\n\nlemma nth_bit_of_zero[simp]: \"nth_bit 0 n = Zero\" \n  by (induction n) (auto simp: nth_bit_def)\n\nlemma nth_bit_of_one[simp]: \"nth_bit (Suc 0) n = (if n = 0 then One else Zero)\"\n  apply(cases n)\n  by(auto simp: nth_bit_def nat_to_bit_eq_Zero_iff)\n\nlemma one_plus_2n_is_odd[simp]: \"Suc (n + n) mod 2 = 1\" by presburger\n\nlemma nth_bit_of_nat_of_num: \"nth_bit (nat_of_num x) n = nth_bit_of_num x n\" \nproof(induction n arbitrary: x)\n  case 0\n  then show ?case by (cases x) (auto simp: nth_bit_def nat_to_bit_eq_One_iff)\nnext\n  case (Suc n)\n  then show ?case using Suc by (cases x) (auto simp: nth_bit_def)\nqed\n\nlemma nth_bit_is_nth_bit_of_num: \"nth_bit x n = (if x = 0 then Zero\n  else nth_bit_of_num (num_of_nat x) n)\" \nproof (cases \"x = 0\")\n  case False\n  hence \"nth_bit x n = nth_bit (nat_of_num (num_of_nat x)) n\" using num_of_nat_inverse by auto\n  thus ?thesis using False by(simp add: nth_bit_of_nat_of_num)\nqed auto\n\nlemma le_2_to_the_n_then_nth_bit_zero: \"x < 2 ^ n \\<Longrightarrow> nth_bit x n = Zero\" \n  by(auto simp: nth_bit_def nat_to_bit_eq_Zero_iff nth_bit_nat_is_right_shift)\n\nlemma nth_bit_add_out_of_range: \"(a :: nat) < 2 ^ n \\<Longrightarrow> j < n \\<Longrightarrow> nth_bit (2 ^ n + a) j = nth_bit a j\" \nproof-\n  assume \"a < 2 ^ n\" \"j < n\" \n  have \"(2 ^ n + a) div 2 ^ j mod 2 = ((2 ^ n) div 2 ^ j + a div 2 ^ j) mod 2\" \n    using div_plus_div_distrib_dvd_left[OF le_imp_power_dvd[OF less_imp_le_nat[OF \\<open>j < n\\<close>]]]\n    by metis\n  also have \"... = (2 ^ (n - j) + a div 2 ^ j) mod 2\" using \\<open>j < n\\<close> \n    using power_diff[OF _ less_imp_le_nat[OF \\<open>j < n\\<close>], where ?a=2] \n    by (metis nat.simps numeral_2_eq_2)\n  also have  \"... = a div 2 ^ j mod 2\" using \\<open>j < n\\<close> \n    by (metis (no_types, lifting) Suc_leI add.commute add.right_neutral even_iff_mod_2_eq_zero \n        le_imp_power_dvd mod_add_left_eq power_Suc0_right zero_less_diff)\n  finally show ?thesis \n    apply(cases \"nth_bit a j\")\n    by(auto simp: nth_bit_def nat_to_bit_cases nth_bit_nat_is_right_shift)\nqed\n\nfun nth_carry:: \"nat \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> bit\" where\n\"nth_carry 0 a b = (if (nth_bit a 0 = One \\<and> nth_bit b 0 = One) then One else Zero)\" | \n\"nth_carry (Suc n) a b = (if (nth_bit a (Suc n) = One \\<and> nth_bit b (Suc n) = One) \n  \\<or> ((nth_bit a (Suc n) = One \\<or> nth_bit b (Suc n) = One) \\<and> nth_carry n a b = One) \n  then One else Zero)\" \n\nlemma a_mod_n_plus_b_mod_n_geq_a_plus_b_mod_n: \"(a :: nat) mod n + b mod n \\<ge> (a + b) mod n\" \n  by (metis mod_add_eq mod_less_eq_dividend)\n\nlemma a_mod_2_to_the_n_decomposition: \"(a :: nat) mod (2 * 2 ^ n) \n  = a div 2 ^ n mod 2 * 2 ^ n +  a mod 2 ^ n\" \n  by (metis mod_mult2_eq mult.commute)\n\nlemma a_mod_plus_b_mod_div_le_2: \"((a :: nat) mod 2 ^ n + b mod 2 ^ n) div 2 ^ n < 2\" \nproof-\n  have \"a mod 2 ^ n < 2 ^ n\" \"b mod 2 ^ n < 2 ^ n\" by auto\n  hence \"(a mod 2 ^ n + b mod 2 ^ n) < 2 * 2 ^ n\" by linarith\n  thus ?thesis using less_mult_imp_div_less by simp\nqed\n\nlemma a_mod_plus_b_mod: \"((a :: nat) mod (2 * 2 ^ n) + b mod (2 * 2 ^ n)) div (2 * 2 ^ n) mod 2 \n  = (a div 2 ^ n mod 2 + b div 2 ^ n mod 2 + \n      (a mod (2 ^ n) + b mod (2 ^ n)) div (2 ^ n) mod 2) div 2\" \nproof -\n  have \"(a mod (2 * 2 ^ n) + b mod (2 * 2 ^ n)) div (2 * 2 ^ n) mod 2 \n    = (a div 2 ^ n mod 2 * 2 ^ n + b div 2 ^ n mod 2 * 2 ^ n \n      + a mod 2 ^ n + b mod 2 ^ n) div (2 * 2 ^ n) mod 2\"\n    using a_mod_2_to_the_n_decomposition by presburger\n  also have \"... = ((a div 2 ^ n mod 2 * 2 ^ n + b div 2 ^ n mod 2 * 2 ^ n \n      + a mod 2 ^ n + b mod 2 ^ n) div 2 ^ n) div 2 mod 2\"\n    by (metis (mono_tags, lifting) div_mult2_eq mult.commute)\n  also have \"... = ((a div 2 ^ n mod 2 * 2 ^ n) div 2 ^ n  + (b div 2 ^ n mod 2 * 2 ^ n) div 2 ^ n\n      + (a mod 2 ^ n + b mod 2 ^ n) div 2 ^ n) div 2 mod 2\" by (simp add: add.assoc)\n  also have \"... = (a div 2 ^ n mod 2  + b div 2 ^ n mod 2 \n      + (a mod 2 ^ n + b mod 2 ^ n) div 2 ^ n) div 2 mod 2\" by simp\n  also have \"... = (a div 2 ^ n mod 2  + b div 2 ^ n mod 2 \n      + (a mod 2 ^ n + b mod 2 ^ n) div 2 ^ n mod 2) div 2 mod 2\" \n    using a_mod_plus_b_mod_div_le_2 by simp\n  finally show ?thesis by simp\nqed\n\nlemma nth_carry_mod: \"nth_carry n a b = \n  nth_bit ((a mod 2 ^ Suc n) + (b mod 2 ^ Suc n)) (Suc n)\" \nproof(induction n)\n  case 0\n  then show ?case by(auto simp: nth_bit_def nat_to_bit_cases nth_bit_nat_is_right_shift)\nnext\n  case (Suc n)\n  then show ?case \n    apply(cases \"nth_carry n a b\")\n      by(auto simp: nth_bit_def nat_to_bit_cases nth_bit_nat_is_right_shift \n          a_mod_plus_b_mod[where ?n=\"Suc n\", simplified] algebra_simps split: if_splits)\nqed\n\nlemma first_bit_of_add: \"nth_bit (a + b) 0 \n  = (if nth_bit a 0 = One then if nth_bit b 0 = One then Zero else One \n     else if nth_bit b 0 = One then One else Zero)\" \n  apply(auto simp: nth_bit_def nat_to_bit_eq_One_iff nat_to_bit_eq_Zero_iff)\n  by presburger\n\nlemma nth_bit_of_add: \"nth_bit (a + b) (Suc n) = (let u = nth_bit a (Suc n); \n  v = nth_bit b (Suc n); w = nth_carry n a b in \n  (if u = One then \n    if v = One then\n     if w = One then One else Zero\n    else\n     if w = One then Zero else One\n   else\n    if v = One then\n     if w = One then Zero else One\n    else\n     if w = One then One else Zero))\"\n  apply(auto simp: Let_def nth_bit_def nth_bit_nat_is_right_shift nat_to_bit_cases nth_carry_mod)\n  by (metis div_add1_eq even_add even_iff_mod_2_eq_zero not_mod2_eq_Suc_0_eq_0)+\n\nlemma no_overflow_condition: \"a + b < 2 ^ n \\<Longrightarrow> nth_carry (n - 1) a b = Zero\" \n  apply(cases n)\n  by(auto simp: nth_carry_mod nth_bit_def nth_bit_nat_is_right_shift nat_to_bit_cases)\n\nlemma has_bit_one_then_greater_zero: \"nth_bit a j = One \\<Longrightarrow> 0 < a\" \n  apply(auto simp: nth_bit_def nth_bit_nat_is_right_shift nat_to_bit_cases)\n  by (metis One_nat_def div_less dvd_0_right even_mod_2_iff gr_zeroI less_2_cases_iff \n      odd_one zero_less_power)\n\nlemma greater_zero_then_has_bit_one: \"x > 0 \\<Longrightarrow> x < 2 ^ n \\<Longrightarrow> \\<exists>b \\<in> {0..<n}. nth_bit x b = One\" \nproof(rule ccontr)\n  assume \"x > 0\" \"x < 2 ^ n\" \"\\<not> (\\<exists>b\\<in>{0..<n}. nth_bit x b = One)\" \n  hence \"(\\<forall>b. nth_bit x b = Zero) \\<or> (\\<exists>b \\<ge> n. nth_bit x b = One)\" by auto\n  thus False \n  proof(elim disjE)\n    assume \"\\<forall>b. nth_bit x b = Zero\"\n    hence \"nth_bit x (Discrete.log x) = Zero\" by auto\n    moreover have \"x div 2 ^ Discrete.log x = 1\" \n      using Discrete.log_exp2_gt log_exp2_le[OF \\<open>x > 0\\<close>]\n      by (metis Euclidean_Division.div_eq_0_iff One_nat_def leD less_2_cases_iff \n          less_mult_imp_div_less power_not_zero zero_neq_numeral)\n    ultimately show False by(auto simp: nth_bit_def nth_bit_nat_is_right_shift nat_to_bit_cases)\n  next \n    assume \"\\<exists>b \\<ge> n. nth_bit x b = One\"\n    then obtain b where \"b \\<ge> n \\<and> nth_bit x b = One\" by blast\n    thus False using \\<open>x < 2 ^ n\\<close> \n      apply(auto simp: nth_bit_def nth_bit_nat_is_right_shift nat_to_bit_cases)\n      by (metis div_greater_zero_iff gr0I leD le_less_trans less_2_cases_iff less_Suc0 \n          mod_less_eq_dividend nat_power_less_imp_less)\n  qed\nqed   \n\nfun nth_carry_sub:: \"nat \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> bit\" where\n\"nth_carry_sub 0 a b = (if (nth_bit a 0 = Zero \\<and> nth_bit b 0 = One) then One else Zero)\" | \n\"nth_carry_sub (Suc n) a b = \n  (if (nth_bit a (Suc n) = Zero \\<and> ( nth_bit b (Suc n) = One \\<or> nth_carry_sub n a b = One))\n    \\<or> (nth_bit a (Suc n) = One \\<and> (nth_bit b (Suc n)) = One \\<and> nth_carry_sub n a b = One) then One\n  else Zero)\"\n\nlemma a_mod_less_b_mod_iff: \"(a :: nat) mod (2 * 2 ^ n) < b mod (2 * 2 ^ n)\n  \\<longleftrightarrow> ((a div 2 ^ n mod 2 < b div 2 ^ n mod 2) \n        \\<or> (a div 2 ^ n mod 2 = b div 2 ^ n mod 2 \\<and> a mod 2 ^ n < b mod 2 ^ n))\" \n  apply(auto simp: algebra_simps a_mod_2_to_the_n_decomposition)\n    apply (smt add.right_neutral add_self_div_2 le_less_trans le_simps(1) less_Suc0 mod_less_divisor \n      mult_0_right mult_numeral_1_right not_add_less2 not_mod_2_eq_0_eq_1 numeral_2_eq_2 \n      numeral_Bit0_div_2 plus_1_eq_Suc pos2 zero_less_power)\n   apply (metis (no_types, lifting) One_nat_def add.right_neutral add_lessD1 add_less_cancel_right \n      less_Suc0 mult_0_right not_mod_2_eq_0_eq_1)\n  by (smt add.commute add.right_neutral add_self_div_2 mod_less_divisor mult_0_right \n      mult_numeral_1_right not_add_less2 not_mod_2_eq_0_eq_1 numeral_2_eq_2 \n      numeral_Bit0_div_2 plus_1_eq_Suc trans_less_add2 zero_less_power)\n\nlemma nth_carry_sub_mod: \"nth_carry_sub n a b = \n (if (a mod 2 ^ Suc n) < (b mod 2 ^ Suc n) then One else Zero)\" \nproof(induction n)\n  case 0\n  then show ?case by(auto simp: nth_bit_def nat_to_bit_cases nth_bit_nat_is_right_shift)\nnext\n  case (Suc n)\n  then show ?case \n    apply(cases \"nth_carry_sub n a b\")\n    by(auto simp: nth_bit_def nat_to_bit_cases nth_bit_nat_is_right_shift \n        a_mod_less_b_mod_iff[where ?n=\"Suc n\", simplified] algebra_simps split: if_splits)\nqed\n\nlemma first_bit_of_sub_n_no_underflow: \"a \\<ge> b \\<Longrightarrow> nth_bit (a - b) 0 = (if nth_bit a 0 = One then\n  (if nth_bit b 0 = One then Zero else One)\n  else (if nth_bit b 0 = One then One else Zero))\" \n  apply(auto simp: nth_bit_def nat_to_bit_eq_One_iff nat_to_bit_eq_Zero_iff)\n  by presburger+\n\nlemma a_times_n_minus_one_div_n: \"n > 0 \\<Longrightarrow> ((a :: nat) * n - 1) div n = a - 1\" \nproof(induction a)\n  case (Suc a)\n  then show ?case using Suc\n  proof(cases a)\n    case (Suc nat)\n    hence \"((Suc a) * n - 1) div n = (n + (a * n - 1)) div n\" \n      using Suc.prems by auto\n    also have \"... = 1 + (a * n - 1) div n\" using Suc by (simp add: Suc.prems)\n    finally show ?thesis using Suc  using Suc.IH Suc.prems by auto\n  qed auto\nqed auto\n\nlemma a_times_n_minus_n_minus_one_div_n: \"n > 1 \\<Longrightarrow> ((a :: nat) * n - (n - 1)) div n = a - 1\"\nproof(induction a)\n  case (Suc a)\n  then show ?case using Suc\n  proof(cases a)\n    case (Suc nat)\n    hence \"((Suc a) * n - (n - 1)) div n = (n + (a * n - (n - 1))) div n\" \n      using Suc.prems by auto\n    also have \"... = 1 + (a * n - (n - 1)) div n\" using Suc.prems div_geq by auto\n    finally show ?thesis using Suc  using Suc.IH Suc.prems by auto\n  qed auto\nqed auto\n\nlemma a_plus_b_minus_c_mod:\n  assumes \"n > 1\" \n  shows \"((a :: nat) * n + b mod n - c mod n) div n \n    = a - (if b mod n < c mod n then 1 else 0)\" \nproof(cases \"b mod n < c mod n\")\n  case True\n  hence \"(a * n + b mod n - c mod n) div n \\<le> (a * n - 1) div n\" by(auto intro: div_le_mono)\n  hence \"(a * n + b mod n - c mod n) div n \\<le> a - 1\" using \\<open>n > 1\\<close> a_times_n_minus_one_div_n by simp\n  have \"(a * n + b mod n - c mod n) div n \\<ge> (a * n + b mod n - (n - 1)) div n\" \n    apply(rule div_le_mono)\n    apply(rule diff_le_mono2)\n    using  mod_less_divisor[where ?n=n] \\<open>n > 1\\<close> \n    by (metis One_nat_def Suc_pred le_less_trans less_Suc_eq_le zero_le_one)\n  moreover have \"(a * n + b mod n - (n - 1)) div n \\<ge> (a * n - (n - 1)) div n\" \n    using div_le_mono by simp\n  ultimately have \"(a * n + b mod n - c mod n) div n \\<ge> a - 1\" \n    using a_times_n_minus_n_minus_one_div_n[OF \\<open>n > 1\\<close>] by simp\n  show ?thesis using \\<open>(a * n + b mod n - c mod n) div n \\<le> a - 1\\<close>\n    \\<open>(a * n + b mod n - c mod n) div n \\<ge> a - 1\\<close> using True le_antisym by presburger\nnext\n  case False\n  hence \"(a * n + b mod n - c mod n) div n = (a * n + (b mod n - c mod n)) div n\" by simp\n  hence \"(a * n + b mod n - c mod n) div n = a + (b mod n - c mod n) div n\" using \\<open>n > 1\\<close> by auto\n  thus ?thesis using \\<open>\\<not> b mod n < c mod n\\<close>\n    by (metis (mono_tags, lifting) Euclidean_Division.div_eq_0_iff add_cancel_left_right diff_zero \n        less_imp_diff_less mod_less_divisor neq0_conv)\nqed\n\nlemma a_minus_b_shift_right: \"(a - b) div 2 ^ Suc n = (a :: nat) div 2 ^ Suc n - b div 2 ^ Suc n \n  - (if a mod 2 ^ Suc n < b mod 2 ^ Suc n then 1 else 0)\"\nproof -\n  have \"1 < (2 :: nat) ^ Suc n\" \n    using one_less_numeral_iff power_gt1 semiring_norm(76) by blast\n   have *: \"(a - b) div (2 ^ Suc n) = (((a div (2 * 2 ^ n)) * 2 * 2 ^ n + a mod (2 * 2 ^ n))\n        - ((b div (2 * 2 ^ n)) * 2 * 2 ^ n + b mod (2 * 2 ^ n))) div (2 * 2 ^ n)\"\n     by (simp add: div_mult_mod_eq mult.assoc)\n   show ?thesis \n   proof(cases \"(a div (2 * 2 ^ n)) * 2 * 2 ^ n \\<ge> (b div (2 * 2 ^ n)) * 2 * 2 ^ n\")\n     case True\n     hence \"(a - b) div (2 ^ Suc n) \n        = (((a div (2 * 2 ^ n)) - (b div (2 * 2 ^ n))) * (2 * 2 ^ n)\n          + a mod (2 * 2 ^ n) - b mod (2 * 2 ^ n))  div (2 * 2 ^ n)\"\n       using \"*\" by(auto simp: algebra_simps)\n     then show ?thesis \n       using a_plus_b_minus_c_mod[OF \\<open>1 < (2 :: nat) ^ Suc n\\<close>, where \n           ?a=\"(a div (2 * 2 ^ n)) - (b div (2 * 2 ^ n))\" and ?b=a and ?c=b, simplified]\n       by(auto)\n  next\n    case False\n    hence \"a < b\"\n      by (metis div_le_mono le_neq_implies_less mult_le_mono1 nat_le_linear)\n    thus ?thesis using False by auto\n  qed\nqed\n\nlemma a_minus_b_mod2: \"(a :: nat) \\<ge> b \\<Longrightarrow> (a - b) mod 2 = (if a mod 2 = 0 then\n  (if b mod 2 = 0 then 0 else 1)\n else \n  (if b mod 2 = 0 then 1 else 0))\" \n  by presburger\n\nlemma a_le_b_but_a_mod_greater_b_mod_then: \"a \\<ge> b \\<Longrightarrow> a mod n < b mod n\n  \\<Longrightarrow> a div n \\<ge> Suc (b div n)\" \nproof(rule ccontr)\n  assume\"a \\<ge> b\" \"a mod n < b mod n\" \"\\<not> (a div n \\<ge> Suc (b div n))\"\n  hence \"a = a div n * n + a mod n\" by auto\n  hence \"a < a div n * n + b mod n\" using \\<open>a mod n < b mod n\\<close> by linarith\n  moreover have \"a div n * n \\<le> b div n * n\" using \\<open>\\<not> (a div n \\<ge> Suc (b div n))\\<close> by simp\n  ultimately have \"a < b div n * n + b mod n\" by linarith\n  also have \"... = b\" by simp\n  finally show False using \\<open>a \\<ge> b\\<close> by simp\nqed\n\nlemma nth_bit_of_sub_n_no_underflow: \"a \\<ge> b \\<Longrightarrow> \n  nth_bit (a - b) (Suc n) = (let an = nth_bit a (Suc n); bn = nth_bit b (Suc n);\n  c = nth_carry_sub n a b in \n  (if an = One then \n    (if bn = One then \n      (if c = One then One else Zero)\n     else \n      (if c = One then Zero else One))\n  else \n    (if bn = One then \n      (if c = One then Zero else One)\n     else \n      (if c = One then One else Zero))))\" \n  apply(auto simp: Let_def nth_bit_def nth_bit_nat_is_right_shift nat_to_bit_cases \n      a_minus_b_shift_right[simplified] nth_carry_sub_mod a_minus_b_mod2[OF div_le_mono] \n      a_minus_b_mod2[OF a_le_b_but_a_mod_greater_b_mod_then] split: if_splits)\n  by (metis dvd_imp_mod_0 even_Suc)+\n  \n\nlemma nth_bit_of_sub_n_underflow: \"a < b \\<Longrightarrow> \n  nth_bit (a - b) (Suc n) = Zero\" \n  by simp\n\nlemma nth_carry_sub_underflow: \"a < b \\<Longrightarrow> a < 2 ^ n \\<Longrightarrow> b < 2 ^ n \n  \\<Longrightarrow> nth_carry_sub (n - 1) (2^n + a) b = One\" \n  apply(cases n)\n  by(auto simp: nth_carry_sub_mod)\n\nlemma nth_carry_sub_no_underflow: \"a \\<ge> b \\<Longrightarrow> a < 2 ^ n \\<Longrightarrow> b < 2 ^ n \n  \\<Longrightarrow> nth_carry_sub (n - 1) a b = Zero\" \n  by (smt bit_neq_zero_iff le_add_diff_inverse no_overflow_condition nth_bit_of_add \n      nth_bit_of_sub_n_no_underflow)\n\nlemma div2_is_right_shift: \"nth_bit (x div 2) n = nth_bit x (Suc n)\" \n  by(auto simp: nth_bit_def)\n\nfun bit_list_to_nat:: \"bit list \\<Rightarrow> nat\" where\n\"bit_list_to_nat [] = 0\" |\n\"bit_list_to_nat (x # xs) = (case x of Zero \\<Rightarrow> 2 * bit_list_to_nat xs |\n  One \\<Rightarrow> 1 + 2 * bit_list_to_nat xs)\" \n\nlemma bit_list_to_nat_right_shift: \"(bit_list_to_nat l) div 2 ^ n \n  = (bit_list_to_nat (drop n l))\" \nproof(induction l arbitrary: n)\n  case (Cons a l)\n  then show ?case\n     apply(cases n)\n     apply(auto split: bit.splits)\n    by (simp add: div_mult2_eq)\nqed simp\n\nlemma bit_list_to_nat_mod2: \"bit_list_to_nat l mod 2 = (if l = [] then 0 else \n  (if hd l = Zero then 0 else 1))\" \n  apply(cases l)\n  by auto\n\nlemma nth_bit_of_bit_list_to_nat[simp]: \"nth_bit (bit_list_to_nat l) k \n  = (if k < length l then l ! k else Zero)\" \n    apply(cases \"nat_to_bit (2 * bit_list_to_nat l div 2 ^ k mod 2)\")\n  by(auto simp: nth_bit_def nth_bit_nat_is_right_shift nat_to_bit_cases \n        bit_list_to_nat_right_shift bit_list_to_nat_mod2 hd_drop_conv_nth\n        split: bit.splits if_splits)\n\nlemma nth_bit_to_nat_greater_zero_then_has_bit_greater_zero: \n  assumes \"bit_list_to_nat l > 0\"\n  shows \"\\<exists>i < length l. l ! i = One\" \n  using assms \nproof(induction l)\n  case (Cons a l)\n  then show ?case\n  proof(cases a)\n    case Zero\n    hence \"bit_list_to_nat l > 0\" using Cons by simp\n    show ?thesis using Cons.IH[OF \\<open>bit_list_to_nat l > 0\\<close>] by auto\n  qed auto\nqed auto\n\nlemma bit_list_to_nat_geq_two_to_the_k_then: \"bit_list_to_nat l \\<ge> 2 ^ k\n  \\<Longrightarrow> (\\<exists>i. k \\<le> i \\<and> i < length l \\<and> l ! i = One)\" \nproof-\n  assume \"bit_list_to_nat l \\<ge> 2 ^ k\" \n  hence \"(bit_list_to_nat l) div 2 ^ k \\<ge> 1\" by (simp add: Suc_leI div_greater_zero_iff) \n  hence \"bit_list_to_nat (drop k l) \\<ge> 1\" using bit_list_to_nat_right_shift by simp\n  then obtain i where \"i < length (drop k l) \\<and> (drop k l) ! i = One\" \n    using nth_bit_to_nat_greater_zero_then_has_bit_greater_zero by force\n  hence \"k \\<le> (k + i) \\<and> k + i < length l \\<and> l ! (k + i) = One\" by auto\n  thus ?thesis by blast\nqed\n\nlemma not_One_then_has_bit_one_at_higher_position: \"x \\<noteq> Num.One \n  \\<Longrightarrow> (\\<exists>i > 0. nth_bit_of_num x i = One)\" \nproof(induction x)\n  case One\n  then show ?case by auto\nnext\n  case (Bit0 x)\n  then show ?case by (cases x) auto\nnext\n  case (Bit1 x)\n  then show ?case by (cases x) auto\nqed\n\n\nlemma num_unequal_then_has_unequal_bit: \"x \\<noteq> y \n  \\<Longrightarrow> (\\<exists>i. nth_bit_of_num x i \\<noteq> nth_bit_of_num y i)\" \nproof(induction x arbitrary: y)\n  case One\n  hence \"y \\<noteq> Num.One\" by simp\n  then obtain i where \"i > 0 \\<and> nth_bit_of_num y i = One\" \n    using not_One_then_has_bit_one_at_higher_position by auto\n  moreover hence \"nth_bit_of_num Num.One i = Zero\" using gr0_implies_Suc nth_bit_of_num.simps by blast\n  ultimately show ?case by (metis bit.simps)\nnext\n  case (Bit0 x)\n  then show ?case \n  proof(cases y)\n    case One\n    then obtain i where \"i > 0 \\<and> nth_bit_of_num (Num.Bit0 x) i = One\" \n      using not_One_then_has_bit_one_at_higher_position by auto\n    moreover hence \"nth_bit_of_num Num.One i = Zero\" using gr0_implies_Suc nth_bit_of_num.simps by blast\n    ultimately show ?thesis using One by (metis bit.simps)\n  next\n    case (Bit0 x2)\n    hence \"x \\<noteq> x2\" using \\<open>num.Bit0 x \\<noteq> y\\<close> by simp\n    then obtain i where \"nth_bit_of_num x i \\<noteq> nth_bit_of_num x2 i\" using Bit0.IH[OF \\<open>x \\<noteq> x2\\<close>] by blast\n    hence \"nth_bit_of_num (num.Bit0 x) (Suc i) \\<noteq> nth_bit_of_num (num.Bit0 x2) (Suc i)\" by simp\n    then show ?thesis using \\<open>y = num.Bit0 x2\\<close> by blast\n  next\n    case (Bit1 x3)\n    then show ?thesis by (metis bit.simps nth_bit_of_num.simps nth_bit_of_num.simps)\n  qed\nnext\n  case (Bit1 x)\n  then show ?case \n  proof(cases y)\n    case One\n    then obtain i where \"i > 0 \\<and> nth_bit_of_num (Num.Bit1 x) i = One\" \n      using not_One_then_has_bit_one_at_higher_position by auto\n    moreover hence \"nth_bit_of_num Num.One i = Zero\" using gr0_implies_Suc nth_bit_of_num.simps by blast\n    ultimately show ?thesis using One by (metis bit.simps)\n  next\n    case (Bit0 x2)\n    then show ?thesis by (metis bit.simps nth_bit_of_num.simps nth_bit_of_num.simps)\n  next\n    case (Bit1 x3)\n    hence \"x \\<noteq> x3\" using \\<open>num.Bit1 x \\<noteq> y\\<close> by simp\n    then obtain i where \"nth_bit_of_num x i \\<noteq> nth_bit_of_num x3 i\" using Bit1.IH[OF \\<open>x \\<noteq> x3\\<close>] by blast\n    hence \"nth_bit_of_num (num.Bit1 x) (Suc i) \\<noteq> nth_bit_of_num (num.Bit1 x3) (Suc i)\" by simp\n    then show ?thesis using \\<open>y = num.Bit1 x3\\<close> by blast\n  qed\nqed\n\nlemma all_bits_equal_then_equal: \"x < 2 ^ n \\<Longrightarrow> y < 2 ^ n \\<Longrightarrow> (\\<forall>i < n. nth_bit x i = nth_bit y i) \n  \\<Longrightarrow> x = y\"\nproof(rule ccontr)\n  assume \"x < 2 ^ n\" \"y < 2 ^ n\" \"(\\<forall>i < n. nth_bit x i = nth_bit y i)\"\n  hence \"i > n \\<longrightarrow> x div 2 ^ i = 0\" \"i > n \\<longrightarrow> y div 2 ^ i = 0\" for i\n    by (meson div_greater_zero_iff gr0I le_less_trans nat_power_less_imp_less order.asym pos2)+\n  hence all_bits_equal: \"nth_bit x i = nth_bit y i\" for i \n    apply(cases \"i < n\")\n    using \\<open>\\<forall>i < n. nth_bit x i = nth_bit y i\\<close> \n     apply(auto simp add: nth_bit_def nth_bit_nat_is_right_shift)\n    by (metis \\<open>x < 2 ^ n\\<close> \\<open>y < 2 ^ n\\<close> div_less linorder_neqE_nat)\n  assume \"x \\<noteq> y\"\n  have \"x \\<noteq> 0\" apply - apply(rule ccontr) \n    using \\<open>x \\<noteq> y\\<close> all_bits_equal greater_zero_then_has_bit_one[OF _ \\<open>y < 2 ^ n\\<close>] by auto\n  have \"y \\<noteq> 0\" apply - apply(rule ccontr) \n    using \\<open>x \\<noteq> y\\<close> all_bits_equal greater_zero_then_has_bit_one[OF _ \\<open>x < 2 ^ n\\<close>] by auto\n  have \"num_of_nat x \\<noteq> num_of_nat y\" \n  proof (rule ccontr)\n    assume \"\\<not>(num_of_nat x \\<noteq> num_of_nat y)\"\n    hence \"nat_of_num (num_of_nat x) = nat_of_num (num_of_nat y)\" by simp\n    hence \"x = y\" using \\<open>x \\<noteq> 0\\<close> \\<open>y \\<noteq> 0\\<close> num_of_nat_inverse by auto\n    thus False using \\<open>x \\<noteq> y\\<close> by blast\n  qed\n  then obtain i where \"nth_bit_of_num (num_of_nat x) i \\<noteq> nth_bit_of_num (num_of_nat y) i\"\n    using num_unequal_then_has_unequal_bit by auto\n  hence \"nth_bit x i \\<noteq> nth_bit y i\" using \\<open>x \\<noteq> 0\\<close> \\<open>y \\<noteq> 0\\<close>\n    by(auto simp: nth_bit_is_nth_bit_of_num)\n  thus False using all_bits_equal by blast\nqed\n\nlemma bit_list_to_nat_less_2_to_the_length: \"bit_list_to_nat l < 2 ^ length l\"\n  apply(rule ccontr)\n  using bit_list_to_nat_geq_two_to_the_k_then using not_less by blast\n\nlemma bit_list_to_nat_eq_nat_iff: \"bit_list_to_nat l = y \\<longleftrightarrow> (y < 2 ^ length l \\<and>\n  (\\<forall>i < length l. l ! i = nth_bit y i))\"\nproof\n  assume \"bit_list_to_nat l = y\" \n  hence \"y = bit_list_to_nat l\" by simp\n  hence \"y div 2 ^ length l = 0\" by(simp add: \\<open>y = bit_list_to_nat l\\<close> bit_list_to_nat_right_shift)\n  hence \"y < 2 ^ length l\" by (simp add: Euclidean_Division.div_eq_0_iff)\n  thus \"y < 2 ^ length l \\<and> (\\<forall>i < length l. l ! i = nth_bit y i)\"  \n    by(simp add: \\<open>y = bit_list_to_nat l\\<close>)\nnext\n  assume \"y < 2 ^ length l \\<and> (\\<forall>i < length l. l ! i = nth_bit y i)\"\n  thus \"bit_list_to_nat l = y\"\n    apply - apply(rule all_bits_equal_then_equal[where ?n=\"length l\"])\n    using bit_list_to_nat_less_2_to_the_length by auto\nqed\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 mod_2_of_zero_is_zero_intro: \"x = (0 :: nat) \\<Longrightarrow> x mod 2 = 0\" by auto \n\nlemma bit_geq_bit_length_is_Zero: \"i \\<ge> bit_length x \\<Longrightarrow> nth_bit x i = Zero\" \n  apply(auto simp: nth_bit_def nat_to_bit_cases nth_bit_nat_is_right_shift bit_length_def)\n  apply(rule mod_2_of_zero_is_zero_intro)\n  by (metis div_less leI log_exp log_mono monoD not_less_eq_eq)\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/Cook_Levin/IMP-_To_SAS+/IMP-_To_IMP--/Binary_Arithmetic.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382023207901, "lm_q2_score": 0.8267118026095991, "lm_q1q2_score": 0.7122438002576539}}
{"text": "(* Author: Tobias Nipkow *)\n\ntheory Tree_Real\nimports\n  Complex_Main\n  Tree\nbegin\n\ntext \\<open>\n  This theory is separate from \\<^theory>\\<open>HOL-Library.Tree\\<close> because the former is discrete and\n  builds on \\<^theory>\\<open>Main\\<close> whereas this theory builds on \\<^theory>\\<open>Complex_Main\\<close>.\n\\<close>\n\n\nlemma size1_height_log: \"log 2 (size1 t) \\<le> height t\"\nby (simp add: log2_of_power_le size1_height)\n\nlemma min_height_size1_log: \"min_height t \\<le> log 2 (size1 t)\"\nby (simp add: le_log2_of_power min_height_size1)\n\nlemma size1_log_if_complete: \"complete t \\<Longrightarrow> height t = log 2 (size1 t)\"\nby (simp add: size1_if_complete)\n\nlemma min_height_size1_log_if_incomplete:\n  \"\\<not> complete t \\<Longrightarrow> min_height t < log 2 (size1 t)\"\nby (simp add: less_log2_of_power min_height_size1_if_incomplete)\n\n\nlemma min_height_balanced: assumes \"balanced t\"\nshows \"min_height t = nat(floor(log 2 (size1 t)))\"\nproof cases\n  assume *: \"complete t\"\n  hence \"size1 t = 2 ^ min_height t\"\n    by (simp add: complete_iff_height size1_if_complete)\n  from log2_of_power_eq[OF this] show ?thesis by linarith\nnext\n  assume *: \"\\<not> complete t\"\n  hence \"height t = min_height t + 1\"\n    using assms min_height_le_height[of t]\n    by(auto simp: balanced_def complete_iff_height)\n  hence \"size1 t < 2 ^ (min_height t + 1)\" by (metis * size1_height_if_incomplete)\n  from floor_log_nat_eq_if[OF min_height_size1 this] show ?thesis by simp\nqed\n\nlemma height_balanced: assumes \"balanced t\"\nshows \"height t = nat(ceiling(log 2 (size1 t)))\"\nproof cases\n  assume *: \"complete t\"\n  hence \"size1 t = 2 ^ height t\" by (simp add: size1_if_complete)\n  from log2_of_power_eq[OF this] show ?thesis by linarith\nnext\n  assume *: \"\\<not> complete t\"\n  hence **: \"height t = min_height t + 1\"\n    using assms min_height_le_height[of t]\n    by(auto simp add: balanced_def complete_iff_height)\n  hence \"size1 t \\<le> 2 ^ (min_height t + 1)\" by (metis size1_height)\n  from log2_of_power_le[OF this size1_ge0] min_height_size1_log_if_incomplete[OF *] **\n  show ?thesis by linarith\nqed\n\nlemma balanced_Node_if_wbal1:\nassumes \"balanced l\" \"balanced r\" \"size l = size r + 1\"\nshows \"balanced \\<langle>l, x, r\\<rangle>\"\nproof -\n  from assms(3) have [simp]: \"size1 l = size1 r + 1\" by(simp add: size1_size)\n  have \"nat \\<lceil>log 2 (1 + size1 r)\\<rceil> \\<ge> nat \\<lceil>log 2 (size1 r)\\<rceil>\"\n    by(rule nat_mono[OF ceiling_mono]) simp\n  hence 1: \"height(Node l x r) = nat \\<lceil>log 2 (1 + size1 r)\\<rceil> + 1\"\n    using height_balanced[OF assms(1)] height_balanced[OF assms(2)]\n    by (simp del: nat_ceiling_le_eq add: max_def)\n  have \"nat \\<lfloor>log 2 (1 + size1 r)\\<rfloor> \\<ge> nat \\<lfloor>log 2 (size1 r)\\<rfloor>\"\n    by(rule nat_mono[OF floor_mono]) simp\n  hence 2: \"min_height(Node l x r) = nat \\<lfloor>log 2 (size1 r)\\<rfloor> + 1\"\n    using min_height_balanced[OF assms(1)] min_height_balanced[OF assms(2)]\n    by (simp)\n  have \"size1 r \\<ge> 1\" by(simp add: size1_size)\n  then obtain i where i: \"2 ^ i \\<le> size1 r\" \"size1 r < 2 ^ (i + 1)\"\n    using ex_power_ivl1[of 2 \"size1 r\"] by auto\n  hence i1: \"2 ^ i < size1 r + 1\" \"size1 r + 1 \\<le> 2 ^ (i + 1)\" by auto\n  from 1 2 floor_log_nat_eq_if[OF i] ceiling_log_nat_eq_if[OF i1]\n  show ?thesis by(simp add:balanced_def)\nqed\n\nlemma balanced_sym: \"balanced \\<langle>l, x, r\\<rangle> \\<Longrightarrow> balanced \\<langle>r, y, l\\<rangle>\"\nby(auto simp: balanced_def)\n\nlemma balanced_Node_if_wbal2:\nassumes \"balanced l\" \"balanced r\" \"abs(int(size l) - int(size r)) \\<le> 1\"\nshows \"balanced \\<langle>l, x, r\\<rangle>\"\nproof -\n  have \"size l = size r \\<or> (size l = size r + 1 \\<or> size r = size l + 1)\" (is \"?A \\<or> ?B\")\n    using assms(3) by linarith\n  thus ?thesis\n  proof\n    assume \"?A\"\n    thus ?thesis using assms(1,2)\n      apply(simp add: balanced_def min_def max_def)\n      by (metis assms(1,2) balanced_optimal le_antisym le_less)\n  next\n    assume \"?B\"\n    thus ?thesis\n      by (meson assms(1,2) balanced_sym balanced_Node_if_wbal1)\n  qed\nqed\n\nlemma balanced_if_wbalanced: \"wbalanced t \\<Longrightarrow> balanced t\"\nproof(induction t)\n  case Leaf show ?case by (simp add: balanced_def)\nnext\n  case (Node l x r)\n  thus ?case by(simp add: balanced_Node_if_wbal2)\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/Library/Tree_Real.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8615382058759129, "lm_q2_score": 0.8267117962054048, "lm_q1q2_score": 0.7122437976792578}}
{"text": "(*  Title:      HOL/Multivariate_Analysis/Linear_Algebra.thy\n    Author:     Amine Chaieb, University of Cambridge\n*)\n\nsection {* Elementary linear algebra on Euclidean spaces *}\n\ntheory Linear_Algebra\nimports\n  Euclidean_Space\n  \"~~/src/HOL/Library/Infinite_Set\"\nbegin\n\nlemma cond_application_beta: \"(if b then f else g) x = (if b then f x else g x)\"\n  by auto\n\nnotation inner (infix \"\\<bullet>\" 70)\n\nlemma square_bound_lemma:\n  fixes x :: real\n  shows \"x < (1 + x) * (1 + x)\"\nproof -\n  have \"(x + 1/2)\\<^sup>2 + 3/4 > 0\"\n    using zero_le_power2[of \"x+1/2\"] by arith\n  then show ?thesis\n    by (simp add: field_simps power2_eq_square)\nqed\n\nlemma square_continuous:\n  fixes e :: real\n  shows \"e > 0 \\<Longrightarrow> \\<exists>d. 0 < d \\<and> (\\<forall>y. \\<bar>y - x\\<bar> < d \\<longrightarrow> \\<bar>y * y - x * x\\<bar> < e)\"\n  using isCont_power[OF isCont_ident, of x, unfolded isCont_def LIM_eq, rule_format, of e 2]\n  apply (auto simp add: power2_eq_square)\n  apply (rule_tac x=\"s\" in exI)\n  apply auto\n  apply (erule_tac x=y in allE)\n  apply auto\n  done\n\ntext{* Hence derive more interesting properties of the norm. *}\n\nlemma norm_eq_0_dot: \"norm x = 0 \\<longleftrightarrow> x \\<bullet> x = (0::real)\"\n  by simp (* TODO: delete *)\n\nlemma norm_triangle_sub:\n  fixes x y :: \"'a::real_normed_vector\"\n  shows \"norm x \\<le> norm y + norm (x - y)\"\n  using norm_triangle_ineq[of \"y\" \"x - y\"] by (simp add: field_simps)\n\nlemma norm_le: \"norm x \\<le> norm y \\<longleftrightarrow> x \\<bullet> x \\<le> y \\<bullet> y\"\n  by (simp add: norm_eq_sqrt_inner)\n\nlemma norm_lt: \"norm x < norm y \\<longleftrightarrow> x \\<bullet> x < y \\<bullet> y\"\n  by (simp add: norm_eq_sqrt_inner)\n\nlemma norm_eq: \"norm x = norm y \\<longleftrightarrow> x \\<bullet> x = y \\<bullet> y\"\n  apply (subst order_eq_iff)\n  apply (auto simp: norm_le)\n  done\n\nlemma norm_eq_1: \"norm x = 1 \\<longleftrightarrow> x \\<bullet> x = 1\"\n  by (simp add: norm_eq_sqrt_inner)\n\ntext{* Squaring equations and inequalities involving norms.  *}\n\nlemma dot_square_norm: \"x \\<bullet> x = (norm x)\\<^sup>2\"\n  by (simp only: power2_norm_eq_inner) (* TODO: move? *)\n\nlemma norm_eq_square: \"norm x = a \\<longleftrightarrow> 0 \\<le> a \\<and> x \\<bullet> x = a\\<^sup>2\"\n  by (auto simp add: norm_eq_sqrt_inner)\n\nlemma real_abs_le_square_iff: \"\\<bar>x\\<bar> \\<le> \\<bar>y\\<bar> \\<longleftrightarrow> (x::real)\\<^sup>2 \\<le> y\\<^sup>2\"\nproof\n  assume \"\\<bar>x\\<bar> \\<le> \\<bar>y\\<bar>\"\n  then have \"\\<bar>x\\<bar>\\<^sup>2 \\<le> \\<bar>y\\<bar>\\<^sup>2\" by (rule power_mono, simp)\n  then show \"x\\<^sup>2 \\<le> y\\<^sup>2\" by simp\nnext\n  assume \"x\\<^sup>2 \\<le> y\\<^sup>2\"\n  then have \"sqrt (x\\<^sup>2) \\<le> sqrt (y\\<^sup>2)\" by (rule real_sqrt_le_mono)\n  then show \"\\<bar>x\\<bar> \\<le> \\<bar>y\\<bar>\" by simp\nqed\n\nlemma norm_le_square: \"norm x \\<le> a \\<longleftrightarrow> 0 \\<le> a \\<and> x \\<bullet> x \\<le> a\\<^sup>2\"\n  apply (simp add: dot_square_norm real_abs_le_square_iff[symmetric])\n  using norm_ge_zero[of x]\n  apply arith\n  done\n\nlemma norm_ge_square: \"norm x \\<ge> a \\<longleftrightarrow> a \\<le> 0 \\<or> x \\<bullet> x \\<ge> a\\<^sup>2\"\n  apply (simp add: dot_square_norm real_abs_le_square_iff[symmetric])\n  using norm_ge_zero[of x]\n  apply arith\n  done\n\nlemma norm_lt_square: \"norm x < a \\<longleftrightarrow> 0 < a \\<and> x \\<bullet> x < a\\<^sup>2\"\n  by (metis not_le norm_ge_square)\n\nlemma norm_gt_square: \"norm x > a \\<longleftrightarrow> a < 0 \\<or> x \\<bullet> x > a\\<^sup>2\"\n  by (metis norm_le_square not_less)\n\ntext{* Dot product in terms of the norm rather than conversely. *}\n\nlemmas inner_simps = inner_add_left inner_add_right inner_diff_right inner_diff_left\n  inner_scaleR_left inner_scaleR_right\n\nlemma dot_norm: \"x \\<bullet> y = ((norm (x + y))\\<^sup>2 - (norm x)\\<^sup>2 - (norm y)\\<^sup>2) / 2\"\n  unfolding power2_norm_eq_inner inner_simps inner_commute by auto\n\nlemma dot_norm_neg: \"x \\<bullet> y = (((norm x)\\<^sup>2 + (norm y)\\<^sup>2) - (norm (x - y))\\<^sup>2) / 2\"\n  unfolding power2_norm_eq_inner inner_simps inner_commute\n  by (auto simp add: algebra_simps)\n\ntext{* Equality of vectors in terms of @{term \"op \\<bullet>\"} products.    *}\n\nlemma vector_eq: \"x = y \\<longleftrightarrow> x \\<bullet> x = x \\<bullet> y \\<and> y \\<bullet> y = x \\<bullet> x\"\n  (is \"?lhs \\<longleftrightarrow> ?rhs\")\nproof\n  assume ?lhs\n  then show ?rhs by simp\nnext\n  assume ?rhs\n  then have \"x \\<bullet> x - x \\<bullet> y = 0 \\<and> x \\<bullet> y - y \\<bullet> y = 0\"\n    by simp\n  then have \"x \\<bullet> (x - y) = 0 \\<and> y \\<bullet> (x - y) = 0\"\n    by (simp add: inner_diff inner_commute)\n  then have \"(x - y) \\<bullet> (x - y) = 0\"\n    by (simp add: field_simps inner_diff inner_commute)\n  then show \"x = y\" by simp\nqed\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\"\n    and \"norm (x' - y) < e / 2\"\n  shows \"norm (x - x') < e\"\n  using dist_triangle_half_l[OF assms[unfolded dist_norm[symmetric]]]\n  unfolding dist_norm[symmetric] .\n\nlemma norm_triangle_le: \"norm x + norm y \\<le> e \\<Longrightarrow> norm (x + y) \\<le> e\"\n  by (rule norm_triangle_ineq [THEN order_trans])\n\nlemma norm_triangle_lt: \"norm x + norm y < e \\<Longrightarrow> norm (x + y) < e\"\n  by (rule norm_triangle_ineq [THEN le_less_trans])\n\nlemma setsum_clauses:\n  shows \"setsum f {} = 0\"\n    and \"finite S \\<Longrightarrow> setsum f (insert x S) = (if x \\<in> S then setsum f S else f x + setsum f S)\"\n  by (auto simp add: insert_absorb)\n\nlemma setsum_norm_le:\n  fixes f :: \"'a \\<Rightarrow> 'b::real_normed_vector\"\n  assumes fg: \"\\<forall>x \\<in> S. norm (f x) \\<le> g x\"\n  shows \"norm (setsum f S) \\<le> setsum g S\"\n  by (rule order_trans [OF norm_setsum setsum_mono]) (simp add: fg)\n\nlemma setsum_norm_bound:\n  fixes f :: \"'a \\<Rightarrow> 'b::real_normed_vector\"\n  assumes K: \"\\<forall>x \\<in> S. norm (f x) \\<le> K\"\n  shows \"norm (setsum f S) \\<le> of_nat (card S) * K\"\n  using setsum_norm_le[OF K] setsum_constant[symmetric]\n  by simp\n\nlemma setsum_group:\n  assumes fS: \"finite S\" and fT: \"finite T\" and fST: \"f ` S \\<subseteq> T\"\n  shows \"setsum (\\<lambda>y. setsum g {x. x \\<in> S \\<and> f x = y}) T = setsum g S\"\n  apply (subst setsum_image_gen[OF fS, of g f])\n  apply (rule setsum.mono_neutral_right[OF fT fST])\n  apply (auto intro: setsum.neutral)\n  done\n\nlemma vector_eq_ldot: \"(\\<forall>x. x \\<bullet> y = x \\<bullet> z) \\<longleftrightarrow> y = z\"\nproof\n  assume \"\\<forall>x. x \\<bullet> y = x \\<bullet> z\"\n  then have \"\\<forall>x. x \\<bullet> (y - z) = 0\"\n    by (simp add: inner_diff)\n  then have \"(y - z) \\<bullet> (y - z) = 0\" ..\n  then show \"y = z\" by simp\nqed simp\n\nlemma vector_eq_rdot: \"(\\<forall>z. x \\<bullet> z = y \\<bullet> z) \\<longleftrightarrow> x = y\"\nproof\n  assume \"\\<forall>z. x \\<bullet> z = y \\<bullet> z\"\n  then have \"\\<forall>z. (x - y) \\<bullet> z = 0\"\n    by (simp add: inner_diff)\n  then have \"(x - y) \\<bullet> (x - y) = 0\" ..\n  then show \"x = y\" by simp\nqed simp\n\n\nsubsection {* Orthogonality. *}\n\ncontext real_inner\nbegin\n\ndefinition \"orthogonal x y \\<longleftrightarrow> x \\<bullet> y = 0\"\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\n\nsubsection {* Linear functions. *}\n\nlemma linear_iff:\n  \"linear f \\<longleftrightarrow> (\\<forall>x y. f (x + y) = f x + f y) \\<and> (\\<forall>c x. f (c *\\<^sub>R x) = c *\\<^sub>R f x)\"\n  (is \"linear f \\<longleftrightarrow> ?rhs\")\nproof\n  assume \"linear f\"\n  then interpret f: linear f .\n  show \"?rhs\" by (simp add: f.add f.scaleR)\nnext\n  assume \"?rhs\"\n  then show \"linear f\" by unfold_locales simp_all\nqed\n\nlemma linear_compose_cmul: \"linear f \\<Longrightarrow> linear (\\<lambda>x. c *\\<^sub>R f x)\"\n  by (simp add: linear_iff algebra_simps)\n\nlemma linear_compose_neg: \"linear f \\<Longrightarrow> linear (\\<lambda>x. - f x)\"\n  by (simp add: linear_iff)\n\nlemma linear_compose_add: \"linear f \\<Longrightarrow> linear g \\<Longrightarrow> linear (\\<lambda>x. f x + g x)\"\n  by (simp add: linear_iff algebra_simps)\n\nlemma linear_compose_sub: \"linear f \\<Longrightarrow> linear g \\<Longrightarrow> linear (\\<lambda>x. f x - g x)\"\n  by (simp add: linear_iff algebra_simps)\n\nlemma linear_compose: \"linear f \\<Longrightarrow> linear g \\<Longrightarrow> linear (g \\<circ> f)\"\n  by (simp add: linear_iff)\n\nlemma linear_id: \"linear id\"\n  by (simp add: linear_iff id_def)\n\nlemma linear_zero: \"linear (\\<lambda>x. 0)\"\n  by (simp add: linear_iff)\n\nlemma linear_compose_setsum:\n  assumes lS: \"\\<forall>a \\<in> S. linear (f a)\"\n  shows \"linear (\\<lambda>x. setsum (\\<lambda>a. f a x) S)\"\nproof (cases \"finite S\")\n  case True\n  then show ?thesis\n    using lS by induct (simp_all add: linear_zero linear_compose_add)\nnext\n  case False\n  then show ?thesis\n    by (simp add: linear_zero)\nqed\n\nlemma linear_0: \"linear f \\<Longrightarrow> f 0 = 0\"\n  unfolding linear_iff\n  apply clarsimp\n  apply (erule allE[where x=\"0::'a\"])\n  apply simp\n  done\n\nlemma linear_cmul: \"linear f \\<Longrightarrow> f (c *\\<^sub>R x) = c *\\<^sub>R f x\"\n  by (simp add: linear_iff)\n\nlemma linear_neg: \"linear f \\<Longrightarrow> f (- x) = - f x\"\n  using linear_cmul [where c=\"-1\"] by simp\n\nlemma linear_add: \"linear f \\<Longrightarrow> f (x + y) = f x + f y\"\n  by (metis linear_iff)\n\nlemma linear_sub: \"linear f \\<Longrightarrow> f (x - y) = f x - f y\"\n  using linear_add [of f x \"- y\"] by (simp add: linear_neg)\n\nlemma linear_setsum:\n  assumes f: \"linear f\"\n  shows \"f (setsum g S) = setsum (f \\<circ> g) S\"\nproof (cases \"finite S\")\n  case True\n  then show ?thesis\n    by induct (simp_all add: linear_0 [OF f] linear_add [OF f])\nnext\n  case False\n  then show ?thesis\n    by (simp add: linear_0 [OF f])\nqed\n\nlemma linear_setsum_mul:\n  assumes lin: \"linear f\"\n  shows \"f (setsum (\\<lambda>i. c i *\\<^sub>R v i) S) = setsum (\\<lambda>i. c i *\\<^sub>R f (v i)) S\"\n  using linear_setsum[OF lin, of \"\\<lambda>i. c i *\\<^sub>R v i\" , unfolded o_def] linear_cmul[OF lin]\n  by simp\n\nlemma linear_injective_0:\n  assumes lin: \"linear f\"\n  shows \"inj f \\<longleftrightarrow> (\\<forall>x. f x = 0 \\<longrightarrow> x = 0)\"\nproof -\n  have \"inj f \\<longleftrightarrow> (\\<forall> x y. f x = f y \\<longrightarrow> x = y)\"\n    by (simp add: inj_on_def)\n  also have \"\\<dots> \\<longleftrightarrow> (\\<forall> x y. f x - f y = 0 \\<longrightarrow> x - y = 0)\"\n    by simp\n  also have \"\\<dots> \\<longleftrightarrow> (\\<forall> x y. f (x - y) = 0 \\<longrightarrow> x - y = 0)\"\n    by (simp add: linear_sub[OF lin])\n  also have \"\\<dots> \\<longleftrightarrow> (\\<forall> x. f x = 0 \\<longrightarrow> x = 0)\"\n    by auto\n  finally show ?thesis .\nqed\n\n\nsubsection {* Bilinear functions. *}\n\ndefinition \"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_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_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_setsum:\n  assumes bh: \"bilinear h\"\n    and fS: \"finite S\"\n    and fT: \"finite T\"\n  shows \"h (setsum f S) (setsum g T) = setsum (\\<lambda>(i,j). h (f i) (g j)) (S \\<times> T) \"\nproof -\n  have \"h (setsum f S) (setsum g T) = setsum (\\<lambda>x. h (f x) (setsum g T)) S\"\n    apply (rule linear_setsum[unfolded o_def])\n    using bh fS\n    apply (auto simp add: bilinear_def)\n    done\n  also have \"\\<dots> = setsum (\\<lambda>x. setsum (\\<lambda>y. h (f x) (g y)) T) S\"\n    apply (rule setsum.cong, simp)\n    apply (rule linear_setsum[unfolded o_def])\n    using bh fT\n    apply (auto simp add: bilinear_def)\n    done\n  finally show ?thesis\n    unfolding setsum.cartesian_product .\nqed\n\n\nsubsection {* Adjoints. *}\n\ndefinition \"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 have \"\\<forall>x y. inner x (g y) = inner x (h y)\"\n    using assms by simp\n  then have \"\\<forall>x y. inner x (g y - h y) = 0\"\n    by (simp add: inner_diff_right)\n  then have \"\\<forall>y. inner (g y - h y) (g y - h y) = 0\"\n    by simp\n  then have \"\\<forall>y. h y = g y\"\n    by simp\n  then show \"h = g\" by (simp add: ext)\nqed\n\ntext {* TODO: The following lemmas about adjoints should hold for any\nHilbert space (i.e. complete inner product space).\n(see @{url \"http://en.wikipedia.org/wiki/Hermitian_adjoint\"})\n*}\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  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      unfolding linear_setsum[OF lf]\n      by (simp add: linear_cmul[OF lf])\n    finally show \"f x \\<bullet> y = x \\<bullet> ?w\"\n      by (simp add: inner_setsum_left inner_setsum_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 {* Interlude: Some properties of real sets *}\n\nlemma seq_mono_lemma:\n  assumes \"\\<forall>(n::nat) \\<ge> m. (d n :: real) < e n\"\n    and \"\\<forall>n \\<ge> m. e n \\<le> e m\"\n  shows \"\\<forall>n \\<ge> m. d n < e m\"\n  using assms\n  apply auto\n  apply (erule_tac x=\"n\" in allE)\n  apply (erule_tac x=\"n\" in allE)\n  apply auto\n  done\n\nlemma infinite_enumerate:\n  assumes fS: \"infinite S\"\n  shows \"\\<exists>r. subseq r \\<and> (\\<forall>n. r n \\<in> S)\"\n  unfolding subseq_def\n  using enumerate_in_set[OF fS] enumerate_mono[of _ _ S] fS by auto\n\nlemma approachable_lt_le: \"(\\<exists>(d::real) > 0. \\<forall>x. f x < d \\<longrightarrow> P x) \\<longleftrightarrow> (\\<exists>d>0. \\<forall>x. f x \\<le> d \\<longrightarrow> P x)\"\n  apply auto\n  apply (rule_tac x=\"d/2\" in exI)\n  apply auto\n  done\n\nlemma triangle_lemma:\n  fixes x y z :: real\n  assumes x: \"0 \\<le> x\"\n    and y: \"0 \\<le> y\"\n    and z: \"0 \\<le> z\"\n    and xy: \"x\\<^sup>2 \\<le> y\\<^sup>2 + z\\<^sup>2\"\n  shows \"x \\<le> y + z\"\nproof -\n  have \"y\\<^sup>2 + z\\<^sup>2 \\<le> y\\<^sup>2 + 2 * y * z + z\\<^sup>2\"\n    using z y by simp\n  with xy have th: \"x\\<^sup>2 \\<le> (y + z)\\<^sup>2\"\n    by (simp add: power2_eq_square field_simps)\n  from y z have yz: \"y + z \\<ge> 0\"\n    by arith\n  from power2_le_imp_le[OF th yz] show ?thesis .\nqed\n\n\nsubsection {* A generic notion of \"hull\" (convex, affine, conic hull and closure). *}\n\ndefinition hull :: \"('a set \\<Rightarrow> bool) \\<Rightarrow> 'a set \\<Rightarrow> 'a set\"  (infixl \"hull\" 75)\n  where \"S hull s = \\<Inter>{t. S t \\<and> s \\<subseteq> t}\"\n\nlemma hull_same: \"S s \\<Longrightarrow> S hull s = s\"\n  unfolding hull_def by auto\n\nlemma hull_in: \"(\\<And>T. Ball T S \\<Longrightarrow> S (\\<Inter>T)) \\<Longrightarrow> S (S hull s)\"\n  unfolding hull_def Ball_def by auto\n\nlemma hull_eq: \"(\\<And>T. Ball T S \\<Longrightarrow> S (\\<Inter>T)) \\<Longrightarrow> (S hull s) = s \\<longleftrightarrow> S s\"\n  using hull_same[of S s] hull_in[of S s] by metis\n\nlemma hull_hull: \"S hull (S hull s) = S hull s\"\n  unfolding hull_def by blast\n\nlemma hull_subset[intro]: \"s \\<subseteq> (S hull s)\"\n  unfolding hull_def by blast\n\nlemma hull_mono: \"s \\<subseteq> t \\<Longrightarrow> (S hull s) \\<subseteq> (S hull t)\"\n  unfolding hull_def by blast\n\nlemma hull_antimono: \"\\<forall>x. S x \\<longrightarrow> T x \\<Longrightarrow> (T hull s) \\<subseteq> (S hull s)\"\n  unfolding hull_def by blast\n\nlemma hull_minimal: \"s \\<subseteq> t \\<Longrightarrow> S t \\<Longrightarrow> (S hull s) \\<subseteq> t\"\n  unfolding hull_def by blast\n\nlemma subset_hull: \"S t \\<Longrightarrow> S hull s \\<subseteq> t \\<longleftrightarrow> s \\<subseteq> t\"\n  unfolding hull_def by blast\n\nlemma hull_UNIV: \"S hull UNIV = UNIV\"\n  unfolding hull_def by auto\n\nlemma hull_unique: \"s \\<subseteq> t \\<Longrightarrow> S t \\<Longrightarrow> (\\<And>t'. s \\<subseteq> t' \\<Longrightarrow> S t' \\<Longrightarrow> t \\<subseteq> t') \\<Longrightarrow> (S hull s = t)\"\n  unfolding hull_def by auto\n\nlemma hull_induct: \"(\\<And>x. x\\<in> S \\<Longrightarrow> P x) \\<Longrightarrow> Q {x. P x} \\<Longrightarrow> \\<forall>x\\<in> Q hull S. P x\"\n  using hull_minimal[of S \"{x. P x}\" Q]\n  by (auto simp add: subset_eq)\n\nlemma hull_inc: \"x \\<in> S \\<Longrightarrow> x \\<in> P hull S\"\n  by (metis hull_subset subset_eq)\n\nlemma hull_union_subset: \"(S hull s) \\<union> (S hull t) \\<subseteq> (S hull (s \\<union> t))\"\n  unfolding Un_subset_iff by (metis hull_mono Un_upper1 Un_upper2)\n\nlemma hull_union:\n  assumes T: \"\\<And>T. Ball T S \\<Longrightarrow> S (\\<Inter>T)\"\n  shows \"S hull (s \\<union> t) = S hull (S hull s \\<union> S hull t)\"\n  apply rule\n  apply (rule hull_mono)\n  unfolding Un_subset_iff\n  apply (metis hull_subset Un_upper1 Un_upper2 subset_trans)\n  apply (rule hull_minimal)\n  apply (metis hull_union_subset)\n  apply (metis hull_in T)\n  done\n\nlemma hull_redundant_eq: \"a \\<in> (S hull s) \\<longleftrightarrow> S hull (insert a s) = S hull s\"\n  unfolding hull_def by blast\n\nlemma hull_redundant: \"a \\<in> (S hull s) \\<Longrightarrow> S hull (insert a s) = S hull s\"\n  by (metis hull_redundant_eq)\n\n\nsubsection {* Archimedean properties and useful consequences *}\n\nlemma real_arch_simple: \"\\<exists>n::nat. x \\<le> real n\"\n  unfolding real_of_nat_def by (rule ex_le_of_nat)\n\nlemma real_arch_inv: \"0 < e \\<longleftrightarrow> (\\<exists>n::nat. n \\<noteq> 0 \\<and> 0 < inverse (real n) \\<and> inverse (real n) < e)\"\n  using reals_Archimedean[of e] less_trans[of 0 \"1 / real n\" e for n::nat]\n  by (auto simp add: field_simps cong: conj_cong)\n\nlemma real_pow_lbound: \"0 \\<le> x \\<Longrightarrow> 1 + real n * x \\<le> (1 + x) ^ n\"\nproof (induct n)\n  case 0\n  then show ?case by simp\nnext\n  case (Suc n)\n  then have h: \"1 + real n * x \\<le> (1 + x) ^ n\"\n    by simp\n  from h have p: \"1 \\<le> (1 + x) ^ n\"\n    using Suc.prems by simp\n  from h have \"1 + real n * x + x \\<le> (1 + x) ^ n + x\"\n    by simp\n  also have \"\\<dots> \\<le> (1 + x) ^ Suc n\"\n    apply (subst diff_le_0_iff_le[symmetric])\n    apply (simp add: field_simps)\n    using mult_left_mono[OF p Suc.prems]\n    apply simp\n    done\n  finally show ?case\n    by (simp add: real_of_nat_Suc field_simps)\nqed\n\nlemma real_arch_pow:\n  fixes x :: real\n  assumes x: \"1 < x\"\n  shows \"\\<exists>n. y < x^n\"\nproof -\n  from x have x0: \"x - 1 > 0\"\n    by arith\n  from reals_Archimedean3[OF x0, rule_format, of y]\n  obtain n :: nat where n: \"y < real n * (x - 1)\" by metis\n  from x0 have x00: \"x- 1 \\<ge> 0\" by arith\n  from real_pow_lbound[OF x00, of n] n\n  have \"y < x^n\" by auto\n  then show ?thesis by metis\nqed\n\nlemma real_arch_pow2:\n  fixes x :: real\n  shows \"\\<exists>n. x < 2^ n\"\n  using real_arch_pow[of 2 x] by simp\n\nlemma real_arch_pow_inv:\n  fixes x y :: real\n  assumes y: \"y > 0\"\n    and x1: \"x < 1\"\n  shows \"\\<exists>n. x^n < y\"\nproof (cases \"x > 0\")\n  case True\n  with x1 have ix: \"1 < 1/x\" by (simp add: field_simps)\n  from real_arch_pow[OF ix, of \"1/y\"]\n  obtain n where n: \"1/y < (1/x)^n\" by blast\n  then show ?thesis using y `x > 0`\n    by (auto simp add: field_simps)\nnext\n  case False\n  with y x1 show ?thesis\n    apply auto\n    apply (rule exI[where x=1])\n    apply auto\n    done\nqed\n\nlemma forall_pos_mono:\n  \"(\\<And>d e::real. d < e \\<Longrightarrow> P d \\<Longrightarrow> P e) \\<Longrightarrow>\n    (\\<And>n::nat. n \\<noteq> 0 \\<Longrightarrow> P (inverse (real n))) \\<Longrightarrow> (\\<And>e. 0 < e \\<Longrightarrow> P e)\"\n  by (metis real_arch_inv)\n\nlemma forall_pos_mono_1:\n  \"(\\<And>d e::real. d < e \\<Longrightarrow> P d \\<Longrightarrow> P e) \\<Longrightarrow>\n    (\\<And>n. P (inverse (real (Suc n)))) \\<Longrightarrow> 0 < e \\<Longrightarrow> P e\"\n  apply (rule forall_pos_mono)\n  apply auto\n  apply (atomize)\n  apply (erule_tac x=\"n - 1\" in allE)\n  apply auto\n  done\n\nlemma real_archimedian_rdiv_eq_0:\n  assumes x0: \"x \\<ge> 0\"\n    and c: \"c \\<ge> 0\"\n    and xc: \"\\<forall>(m::nat) > 0. real m * x \\<le> c\"\n  shows \"x = 0\"\nproof (rule ccontr)\n  assume \"x \\<noteq> 0\"\n  with x0 have xp: \"x > 0\" by arith\n  from reals_Archimedean3[OF xp, rule_format, of c]\n  obtain n :: nat where n: \"c < real n * x\"\n    by blast\n  with xc[rule_format, of n] have \"n = 0\"\n    by arith\n  with n c show False\n    by simp\nqed\n\n\nsubsection{* A bit of linear algebra. *}\n\ndefinition (in real_vector) subspace :: \"'a set \\<Rightarrow> bool\"\n  where \"subspace S \\<longleftrightarrow> 0 \\<in> S \\<and> (\\<forall>x \\<in> S. \\<forall>y \\<in> S. x + y \\<in> S) \\<and> (\\<forall>c. \\<forall>x \\<in> S. c *\\<^sub>R x \\<in> S)\"\n\ndefinition (in real_vector) \"span S = (subspace hull S)\"\ndefinition (in real_vector) \"dependent S \\<longleftrightarrow> (\\<exists>a \\<in> S. a \\<in> span (S - {a}))\"\nabbreviation (in real_vector) \"independent s \\<equiv> \\<not> dependent s\"\n\ntext {* Closure properties of subspaces. *}\n\nlemma subspace_UNIV[simp]: \"subspace UNIV\"\n  by (simp add: subspace_def)\n\nlemma (in real_vector) subspace_0: \"subspace S \\<Longrightarrow> 0 \\<in> S\"\n  by (metis subspace_def)\n\nlemma (in real_vector) subspace_add: \"subspace S \\<Longrightarrow> x \\<in> S \\<Longrightarrow> y \\<in> S \\<Longrightarrow> x + y \\<in> S\"\n  by (metis subspace_def)\n\nlemma (in real_vector) subspace_mul: \"subspace S \\<Longrightarrow> x \\<in> S \\<Longrightarrow> c *\\<^sub>R x \\<in> S\"\n  by (metis subspace_def)\n\nlemma subspace_neg: \"subspace S \\<Longrightarrow> x \\<in> S \\<Longrightarrow> - x \\<in> S\"\n  by (metis scaleR_minus1_left subspace_mul)\n\nlemma subspace_sub: \"subspace S \\<Longrightarrow> x \\<in> S \\<Longrightarrow> y \\<in> S \\<Longrightarrow> x - y \\<in> S\"\n  using subspace_add [of S x \"- y\"] by (simp add: subspace_neg)\n\nlemma (in real_vector) subspace_setsum:\n  assumes sA: \"subspace A\"\n    and f: \"\\<forall>x\\<in>B. f x \\<in> A\"\n  shows \"setsum f B \\<in> A\"\nproof (cases \"finite B\")\n  case True\n  then show ?thesis\n    using f by induct (simp_all add: subspace_0 [OF sA] subspace_add [OF sA])\nqed (simp add: subspace_0 [OF sA])\n\nlemma subspace_linear_image:\n  assumes lf: \"linear f\"\n    and sS: \"subspace S\"\n  shows \"subspace (f ` S)\"\n  using lf sS linear_0[OF lf]\n  unfolding linear_iff subspace_def\n  apply (auto simp add: image_iff)\n  apply (rule_tac x=\"x + y\" in bexI)\n  apply auto\n  apply (rule_tac x=\"c *\\<^sub>R x\" in bexI)\n  apply auto\n  done\n\nlemma subspace_linear_vimage: \"linear f \\<Longrightarrow> subspace S \\<Longrightarrow> subspace (f -` S)\"\n  by (auto simp add: subspace_def linear_iff linear_0[of f])\n\nlemma subspace_linear_preimage: \"linear f \\<Longrightarrow> subspace S \\<Longrightarrow> subspace {x. f x \\<in> S}\"\n  by (auto simp add: subspace_def linear_iff linear_0[of f])\n\nlemma subspace_trivial: \"subspace {0}\"\n  by (simp add: subspace_def)\n\nlemma (in real_vector) subspace_inter: \"subspace A \\<Longrightarrow> subspace B \\<Longrightarrow> subspace (A \\<inter> B)\"\n  by (simp add: subspace_def)\n\nlemma subspace_Times: \"subspace A \\<Longrightarrow> subspace B \\<Longrightarrow> subspace (A \\<times> B)\"\n  unfolding subspace_def zero_prod_def by simp\n\ntext {* Properties of span. *}\n\nlemma (in real_vector) span_mono: \"A \\<subseteq> B \\<Longrightarrow> span A \\<subseteq> span B\"\n  by (metis span_def hull_mono)\n\nlemma (in real_vector) subspace_span: \"subspace (span S)\"\n  unfolding span_def\n  apply (rule hull_in)\n  apply (simp only: subspace_def Inter_iff Int_iff subset_eq)\n  apply auto\n  done\n\nlemma (in real_vector) span_clauses:\n  \"a \\<in> S \\<Longrightarrow> a \\<in> span S\"\n  \"0 \\<in> span S\"\n  \"x\\<in> span S \\<Longrightarrow> y \\<in> span S \\<Longrightarrow> x + y \\<in> span S\"\n  \"x \\<in> span S \\<Longrightarrow> c *\\<^sub>R x \\<in> span S\"\n  by (metis span_def hull_subset subset_eq) (metis subspace_span subspace_def)+\n\nlemma span_unique:\n  \"S \\<subseteq> T \\<Longrightarrow> subspace T \\<Longrightarrow> (\\<And>T'. S \\<subseteq> T' \\<Longrightarrow> subspace T' \\<Longrightarrow> T \\<subseteq> T') \\<Longrightarrow> span S = T\"\n  unfolding span_def by (rule hull_unique)\n\nlemma span_minimal: \"S \\<subseteq> T \\<Longrightarrow> subspace T \\<Longrightarrow> span S \\<subseteq> T\"\n  unfolding span_def by (rule hull_minimal)\n\nlemma (in real_vector) span_induct:\n  assumes x: \"x \\<in> span S\"\n    and P: \"subspace P\"\n    and SP: \"\\<And>x. x \\<in> S \\<Longrightarrow> x \\<in> P\"\n  shows \"x \\<in> P\"\nproof -\n  from SP have SP': \"S \\<subseteq> P\"\n    by (simp add: subset_eq)\n  from x hull_minimal[where S=subspace, OF SP' P, unfolded span_def[symmetric]]\n  show \"x \\<in> P\"\n    by (metis subset_eq)\nqed\n\nlemma span_empty[simp]: \"span {} = {0}\"\n  apply (simp add: span_def)\n  apply (rule hull_unique)\n  apply (auto simp add: subspace_def)\n  done\n\nlemma (in real_vector) independent_empty[intro]: \"independent {}\"\n  by (simp add: dependent_def)\n\nlemma dependent_single[simp]: \"dependent {x} \\<longleftrightarrow> x = 0\"\n  unfolding dependent_def by auto\n\nlemma (in real_vector) independent_mono: \"independent A \\<Longrightarrow> B \\<subseteq> A \\<Longrightarrow> independent B\"\n  apply (clarsimp simp add: dependent_def span_mono)\n  apply (subgoal_tac \"span (B - {a}) \\<le> span (A - {a})\")\n  apply force\n  apply (rule span_mono)\n  apply auto\n  done\n\nlemma (in real_vector) span_subspace: \"A \\<subseteq> B \\<Longrightarrow> B \\<le> span A \\<Longrightarrow>  subspace B \\<Longrightarrow> span A = B\"\n  by (metis order_antisym span_def hull_minimal)\n\nlemma (in real_vector) span_induct':\n  assumes SP: \"\\<forall>x \\<in> S. P x\"\n    and P: \"subspace {x. P x}\"\n  shows \"\\<forall>x \\<in> span S. P x\"\n  using span_induct SP P by blast\n\ninductive_set (in real_vector) span_induct_alt_help for S :: \"'a set\"\nwhere\n  span_induct_alt_help_0: \"0 \\<in> span_induct_alt_help S\"\n| span_induct_alt_help_S:\n    \"x \\<in> S \\<Longrightarrow> z \\<in> span_induct_alt_help S \\<Longrightarrow>\n      (c *\\<^sub>R x + z) \\<in> span_induct_alt_help S\"\n\nlemma span_induct_alt':\n  assumes h0: \"h 0\"\n    and hS: \"\\<And>c x y. x \\<in> S \\<Longrightarrow> h y \\<Longrightarrow> h (c *\\<^sub>R x + y)\"\n  shows \"\\<forall>x \\<in> span S. h x\"\nproof -\n  {\n    fix x :: 'a\n    assume x: \"x \\<in> span_induct_alt_help S\"\n    have \"h x\"\n      apply (rule span_induct_alt_help.induct[OF x])\n      apply (rule h0)\n      apply (rule hS)\n      apply assumption\n      apply assumption\n      done\n  }\n  note th0 = this\n  {\n    fix x\n    assume x: \"x \\<in> span S\"\n    have \"x \\<in> span_induct_alt_help S\"\n    proof (rule span_induct[where x=x and S=S])\n      show \"x \\<in> span S\" by (rule x)\n    next\n      fix x\n      assume xS: \"x \\<in> S\"\n      from span_induct_alt_help_S[OF xS span_induct_alt_help_0, of 1]\n      show \"x \\<in> span_induct_alt_help S\"\n        by simp\n    next\n      have \"0 \\<in> span_induct_alt_help S\" by (rule span_induct_alt_help_0)\n      moreover\n      {\n        fix x y\n        assume h: \"x \\<in> span_induct_alt_help S\" \"y \\<in> span_induct_alt_help S\"\n        from h have \"(x + y) \\<in> span_induct_alt_help S\"\n          apply (induct rule: span_induct_alt_help.induct)\n          apply simp\n          unfolding add.assoc\n          apply (rule span_induct_alt_help_S)\n          apply assumption\n          apply simp\n          done\n      }\n      moreover\n      {\n        fix c x\n        assume xt: \"x \\<in> span_induct_alt_help S\"\n        then have \"(c *\\<^sub>R x) \\<in> span_induct_alt_help S\"\n          apply (induct rule: span_induct_alt_help.induct)\n          apply (simp add: span_induct_alt_help_0)\n          apply (simp add: scaleR_right_distrib)\n          apply (rule span_induct_alt_help_S)\n          apply assumption\n          apply simp\n          done }\n      ultimately show \"subspace (span_induct_alt_help S)\"\n        unfolding subspace_def Ball_def by blast\n    qed\n  }\n  with th0 show ?thesis by blast\nqed\n\nlemma span_induct_alt:\n  assumes h0: \"h 0\"\n    and hS: \"\\<And>c x y. x \\<in> S \\<Longrightarrow> h y \\<Longrightarrow> h (c *\\<^sub>R x + y)\"\n    and x: \"x \\<in> span S\"\n  shows \"h x\"\n  using span_induct_alt'[of h S] h0 hS x by blast\n\ntext {* Individual closure properties. *}\n\nlemma span_span: \"span (span A) = span A\"\n  unfolding span_def hull_hull ..\n\nlemma (in real_vector) span_superset: \"x \\<in> S \\<Longrightarrow> x \\<in> span S\"\n  by (metis span_clauses(1))\n\nlemma (in real_vector) span_0: \"0 \\<in> span S\"\n  by (metis subspace_span subspace_0)\n\nlemma span_inc: \"S \\<subseteq> span S\"\n  by (metis subset_eq span_superset)\n\nlemma (in real_vector) dependent_0:\n  assumes \"0 \\<in> A\"\n  shows \"dependent A\"\n  unfolding dependent_def\n  apply (rule_tac x=0 in bexI)\n  using assms span_0\n  apply auto\n  done\n\nlemma (in real_vector) span_add: \"x \\<in> span S \\<Longrightarrow> y \\<in> span S \\<Longrightarrow> x + y \\<in> span S\"\n  by (metis subspace_add subspace_span)\n\nlemma (in real_vector) span_mul: \"x \\<in> span S \\<Longrightarrow> c *\\<^sub>R x \\<in> span S\"\n  by (metis subspace_span subspace_mul)\n\nlemma span_neg: \"x \\<in> span S \\<Longrightarrow> - x \\<in> span S\"\n  by (metis subspace_neg subspace_span)\n\nlemma span_sub: \"x \\<in> span S \\<Longrightarrow> y \\<in> span S \\<Longrightarrow> x - y \\<in> span S\"\n  by (metis subspace_span subspace_sub)\n\nlemma (in real_vector) span_setsum: \"\\<forall>x\\<in>A. f x \\<in> span S \\<Longrightarrow> setsum f A \\<in> span S\"\n  by (rule subspace_setsum [OF subspace_span])\n\nlemma span_add_eq: \"x \\<in> span S \\<Longrightarrow> x + y \\<in> span S \\<longleftrightarrow> y \\<in> span S\"\n  by (metis add_minus_cancel scaleR_minus1_left subspace_def subspace_span)\n\ntext {* Mapping under linear image. *}\n\nlemma span_linear_image:\n  assumes lf: \"linear f\"\n  shows \"span (f ` S) = f ` span S\"\nproof (rule span_unique)\n  show \"f ` S \\<subseteq> f ` span S\"\n    by (intro image_mono span_inc)\n  show \"subspace (f ` span S)\"\n    using lf subspace_span by (rule subspace_linear_image)\nnext\n  fix T\n  assume \"f ` S \\<subseteq> T\" and \"subspace T\"\n  then show \"f ` span S \\<subseteq> T\"\n    unfolding image_subset_iff_subset_vimage\n    by (intro span_minimal subspace_linear_vimage lf)\nqed\n\nlemma span_union: \"span (A \\<union> B) = (\\<lambda>(a, b). a + b) ` (span A \\<times> span B)\"\nproof (rule span_unique)\n  show \"A \\<union> B \\<subseteq> (\\<lambda>(a, b). a + b) ` (span A \\<times> span B)\"\n    by safe (force intro: span_clauses)+\nnext\n  have \"linear (\\<lambda>(a, b). a + b)\"\n    by (simp add: linear_iff scaleR_add_right)\n  moreover have \"subspace (span A \\<times> span B)\"\n    by (intro subspace_Times subspace_span)\n  ultimately show \"subspace ((\\<lambda>(a, b). a + b) ` (span A \\<times> span B))\"\n    by (rule subspace_linear_image)\nnext\n  fix T\n  assume \"A \\<union> B \\<subseteq> T\" and \"subspace T\"\n  then show \"(\\<lambda>(a, b). a + b) ` (span A \\<times> span B) \\<subseteq> T\"\n    by (auto intro!: subspace_add elim: span_induct)\nqed\n\ntext {* The key breakdown property. *}\n\nlemma span_singleton: \"span {x} = range (\\<lambda>k. k *\\<^sub>R x)\"\nproof (rule span_unique)\n  show \"{x} \\<subseteq> range (\\<lambda>k. k *\\<^sub>R x)\"\n    by (fast intro: scaleR_one [symmetric])\n  show \"subspace (range (\\<lambda>k. k *\\<^sub>R x))\"\n    unfolding subspace_def\n    by (auto intro: scaleR_add_left [symmetric])\nnext\n  fix T\n  assume \"{x} \\<subseteq> T\" and \"subspace T\"\n  then show \"range (\\<lambda>k. k *\\<^sub>R x) \\<subseteq> T\"\n    unfolding subspace_def by auto\nqed\n\nlemma span_insert: \"span (insert a S) = {x. \\<exists>k. (x - k *\\<^sub>R a) \\<in> span S}\"\nproof -\n  have \"span ({a} \\<union> S) = {x. \\<exists>k. (x - k *\\<^sub>R a) \\<in> span S}\"\n    unfolding span_union span_singleton\n    apply safe\n    apply (rule_tac x=k in exI, simp)\n    apply (erule rev_image_eqI [OF SigmaI [OF rangeI]])\n    apply auto\n    done\n  then show ?thesis by simp\nqed\n\nlemma span_breakdown:\n  assumes bS: \"b \\<in> S\"\n    and aS: \"a \\<in> span S\"\n  shows \"\\<exists>k. a - k *\\<^sub>R b \\<in> span (S - {b})\"\n  using assms span_insert [of b \"S - {b}\"]\n  by (simp add: insert_absorb)\n\nlemma span_breakdown_eq: \"x \\<in> span (insert a S) \\<longleftrightarrow> (\\<exists>k. x - k *\\<^sub>R a \\<in> span S)\"\n  by (simp add: span_insert)\n\ntext {* Hence some \"reversal\" results. *}\n\nlemma in_span_insert:\n  assumes a: \"a \\<in> span (insert b S)\"\n    and na: \"a \\<notin> span S\"\n  shows \"b \\<in> span (insert a S)\"\nproof -\n  from a obtain k where k: \"a - k *\\<^sub>R b \\<in> span S\"\n    unfolding span_insert by fast\n  show ?thesis\n  proof (cases \"k = 0\")\n    case True\n    with k have \"a \\<in> span S\" by simp\n    with na show ?thesis by simp\n  next\n    case False\n    from k have \"(- inverse k) *\\<^sub>R (a - k *\\<^sub>R b) \\<in> span S\"\n      by (rule span_mul)\n    then have \"b - inverse k *\\<^sub>R a \\<in> span S\"\n      using `k \\<noteq> 0` by (simp add: scaleR_diff_right)\n    then show ?thesis\n      unfolding span_insert by fast\n  qed\nqed\n\nlemma in_span_delete:\n  assumes a: \"a \\<in> span S\"\n    and na: \"a \\<notin> span (S - {b})\"\n  shows \"b \\<in> span (insert a (S - {b}))\"\n  apply (rule in_span_insert)\n  apply (rule set_rev_mp)\n  apply (rule a)\n  apply (rule span_mono)\n  apply blast\n  apply (rule na)\n  done\n\ntext {* Transitivity property. *}\n\nlemma span_redundant: \"x \\<in> span S \\<Longrightarrow> span (insert x S) = span S\"\n  unfolding span_def by (rule hull_redundant)\n\nlemma span_trans:\n  assumes x: \"x \\<in> span S\"\n    and y: \"y \\<in> span (insert x S)\"\n  shows \"y \\<in> span S\"\n  using assms by (simp only: span_redundant)\n\nlemma span_insert_0[simp]: \"span (insert 0 S) = span S\"\n  by (simp only: span_redundant span_0)\n\ntext {* An explicit expansion is sometimes needed. *}\n\nlemma span_explicit:\n  \"span P = {y. \\<exists>S u. finite S \\<and> S \\<subseteq> P \\<and> setsum (\\<lambda>v. u v *\\<^sub>R v) S = y}\"\n  (is \"_ = ?E\" is \"_ = {y. ?h y}\" is \"_ = {y. \\<exists>S u. ?Q S u y}\")\nproof -\n  {\n    fix x\n    assume \"?h x\"\n    then obtain S u where \"finite S\" and \"S \\<subseteq> P\" and \"setsum (\\<lambda>v. u v *\\<^sub>R v) S = x\"\n      by blast\n    then have \"x \\<in> span P\"\n      by (auto intro: span_setsum span_mul span_superset)\n  }\n  moreover\n  have \"\\<forall>x \\<in> span P. ?h x\"\n  proof (rule span_induct_alt')\n    show \"?h 0\"\n      by (rule exI[where x=\"{}\"], simp)\n  next\n    fix c x y\n    assume x: \"x \\<in> P\"\n    assume hy: \"?h y\"\n    from hy obtain S u where fS: \"finite S\" and SP: \"S\\<subseteq>P\"\n      and u: \"setsum (\\<lambda>v. u v *\\<^sub>R v) S = y\" by blast\n    let ?S = \"insert x S\"\n    let ?u = \"\\<lambda>y. if y = x then (if x \\<in> S then u y + c else c) else u y\"\n    from fS SP x have th0: \"finite (insert x S)\" \"insert x S \\<subseteq> P\"\n      by blast+\n    have \"?Q ?S ?u (c*\\<^sub>R x + y)\"\n    proof cases\n      assume xS: \"x \\<in> S\"\n      have \"setsum (\\<lambda>v. ?u v *\\<^sub>R v) ?S = (\\<Sum>v\\<in>S - {x}. u v *\\<^sub>R v) + (u x + c) *\\<^sub>R x\"\n        using xS by (simp add: setsum.remove [OF fS xS] insert_absorb)\n      also have \"\\<dots> = (\\<Sum>v\\<in>S. u v *\\<^sub>R v) + c *\\<^sub>R x\"\n        by (simp add: setsum.remove [OF fS xS] algebra_simps)\n      also have \"\\<dots> = c*\\<^sub>R x + y\"\n        by (simp add: add.commute u)\n      finally have \"setsum (\\<lambda>v. ?u v *\\<^sub>R v) ?S = c*\\<^sub>R x + y\" .\n      then show ?thesis using th0 by blast\n    next\n      assume xS: \"x \\<notin> S\"\n      have th00: \"(\\<Sum>v\\<in>S. (if v = x then c else u v) *\\<^sub>R v) = y\"\n        unfolding u[symmetric]\n        apply (rule setsum.cong)\n        using xS\n        apply auto\n        done\n      show ?thesis using fS xS th0\n        by (simp add: th00 add.commute cong del: if_weak_cong)\n    qed\n    then show \"?h (c*\\<^sub>R x + y)\"\n      by fast\n  qed\n  ultimately show ?thesis by blast\nqed\n\nlemma dependent_explicit:\n  \"dependent P \\<longleftrightarrow> (\\<exists>S u. finite S \\<and> S \\<subseteq> P \\<and> (\\<exists>v\\<in>S. u v \\<noteq> 0 \\<and> setsum (\\<lambda>v. u v *\\<^sub>R v) S = 0))\"\n  (is \"?lhs = ?rhs\")\nproof -\n  {\n    assume dP: \"dependent P\"\n    then obtain a S u where aP: \"a \\<in> P\" and fS: \"finite S\"\n      and SP: \"S \\<subseteq> P - {a}\" and ua: \"setsum (\\<lambda>v. u v *\\<^sub>R v) S = a\"\n      unfolding dependent_def span_explicit by blast\n    let ?S = \"insert a S\"\n    let ?u = \"\\<lambda>y. if y = a then - 1 else u y\"\n    let ?v = a\n    from aP SP have aS: \"a \\<notin> S\"\n      by blast\n    from fS SP aP have th0: \"finite ?S\" \"?S \\<subseteq> P\" \"?v \\<in> ?S\" \"?u ?v \\<noteq> 0\"\n      by auto\n    have s0: \"setsum (\\<lambda>v. ?u v *\\<^sub>R v) ?S = 0\"\n      using fS aS\n      apply simp\n      apply (subst (2) ua[symmetric])\n      apply (rule setsum.cong)\n      apply auto\n      done\n    with th0 have ?rhs by fast\n  }\n  moreover\n  {\n    fix S u v\n    assume fS: \"finite S\"\n      and SP: \"S \\<subseteq> P\"\n      and vS: \"v \\<in> S\"\n      and uv: \"u v \\<noteq> 0\"\n      and u: \"setsum (\\<lambda>v. u v *\\<^sub>R v) S = 0\"\n    let ?a = v\n    let ?S = \"S - {v}\"\n    let ?u = \"\\<lambda>i. (- u i) / u v\"\n    have th0: \"?a \\<in> P\" \"finite ?S\" \"?S \\<subseteq> P\"\n      using fS SP vS by auto\n    have \"setsum (\\<lambda>v. ?u v *\\<^sub>R v) ?S =\n      setsum (\\<lambda>v. (- (inverse (u ?a))) *\\<^sub>R (u v *\\<^sub>R v)) S - ?u v *\\<^sub>R v\"\n      using fS vS uv by (simp add: setsum_diff1 field_simps)\n    also have \"\\<dots> = ?a\"\n      unfolding scaleR_right.setsum [symmetric] u using uv by simp\n    finally have \"setsum (\\<lambda>v. ?u v *\\<^sub>R v) ?S = ?a\" .\n    with th0 have ?lhs\n      unfolding dependent_def span_explicit\n      apply -\n      apply (rule bexI[where x= \"?a\"])\n      apply (simp_all del: scaleR_minus_left)\n      apply (rule exI[where x= \"?S\"])\n      apply (auto simp del: scaleR_minus_left)\n      done\n  }\n  ultimately show ?thesis by blast\nqed\n\n\nlemma span_finite:\n  assumes fS: \"finite S\"\n  shows \"span S = {y. \\<exists>u. setsum (\\<lambda>v. u v *\\<^sub>R v) S = y}\"\n  (is \"_ = ?rhs\")\nproof -\n  {\n    fix y\n    assume y: \"y \\<in> span S\"\n    from y obtain S' u where fS': \"finite S'\"\n      and SS': \"S' \\<subseteq> S\"\n      and u: \"setsum (\\<lambda>v. u v *\\<^sub>R v) S' = y\"\n      unfolding span_explicit by blast\n    let ?u = \"\\<lambda>x. if x \\<in> S' then u x else 0\"\n    have \"setsum (\\<lambda>v. ?u v *\\<^sub>R v) S = setsum (\\<lambda>v. u v *\\<^sub>R v) S'\"\n      using SS' fS by (auto intro!: setsum.mono_neutral_cong_right)\n    then have \"setsum (\\<lambda>v. ?u v *\\<^sub>R v) S = y\" by (metis u)\n    then have \"y \\<in> ?rhs\" by auto\n  }\n  moreover\n  {\n    fix y u\n    assume u: \"setsum (\\<lambda>v. u v *\\<^sub>R v) S = y\"\n    then have \"y \\<in> span S\" using fS unfolding span_explicit by auto\n  }\n  ultimately show ?thesis by blast\nqed\n\ntext {* This is useful for building a basis step-by-step. *}\n\nlemma independent_insert:\n  \"independent (insert a S) \\<longleftrightarrow>\n    (if a \\<in> S then independent S else independent S \\<and> a \\<notin> span S)\"\n  (is \"?lhs \\<longleftrightarrow> ?rhs\")\nproof (cases \"a \\<in> S\")\n  case True\n  then show ?thesis\n    using insert_absorb[OF True] by simp\nnext\n  case False\n  show ?thesis\n  proof\n    assume i: ?lhs\n    then show ?rhs\n      using False\n      apply simp\n      apply (rule conjI)\n      apply (rule independent_mono)\n      apply assumption\n      apply blast\n      apply (simp add: dependent_def)\n      done\n  next\n    assume i: ?rhs\n    show ?lhs\n      using i False\n      apply (auto simp add: dependent_def)\n      by (metis in_span_insert insert_Diff insert_Diff_if insert_iff)\n  qed\nqed\n\ntext {* The degenerate case of the Exchange Lemma. *}\n\nlemma spanning_subset_independent:\n  assumes BA: \"B \\<subseteq> A\"\n    and iA: \"independent A\"\n    and AsB: \"A \\<subseteq> span B\"\n  shows \"A = B\"\nproof\n  show \"B \\<subseteq> A\" by (rule BA)\n\n  from span_mono[OF BA] span_mono[OF AsB]\n  have sAB: \"span A = span B\" unfolding span_span by blast\n\n  {\n    fix x\n    assume x: \"x \\<in> A\"\n    from iA have th0: \"x \\<notin> span (A - {x})\"\n      unfolding dependent_def using x by blast\n    from x have xsA: \"x \\<in> span A\"\n      by (blast intro: span_superset)\n    have \"A - {x} \\<subseteq> A\" by blast\n    then have th1: \"span (A - {x}) \\<subseteq> span A\"\n      by (metis span_mono)\n    {\n      assume xB: \"x \\<notin> B\"\n      from xB BA have \"B \\<subseteq> A - {x}\"\n        by blast\n      then have \"span B \\<subseteq> span (A - {x})\"\n        by (metis span_mono)\n      with th1 th0 sAB have \"x \\<notin> span A\"\n        by blast\n      with x have False\n        by (metis span_superset)\n    }\n    then have \"x \\<in> B\" by blast\n  }\n  then show \"A \\<subseteq> B\" by blast\nqed\n\ntext {* The general case of the Exchange Lemma, the key to what follows. *}\n\nlemma exchange_lemma:\n  assumes f:\"finite t\"\n    and i: \"independent s\"\n    and sp: \"s \\<subseteq> span t\"\n  shows \"\\<exists>t'. card t' = card t \\<and> finite t' \\<and> s \\<subseteq> t' \\<and> t' \\<subseteq> s \\<union> t \\<and> s \\<subseteq> span t'\"\n  using f i sp\nproof (induct \"card (t - s)\" arbitrary: s t rule: less_induct)\n  case less\n  note ft = `finite t` and s = `independent s` and sp = `s \\<subseteq> span t`\n  let ?P = \"\\<lambda>t'. card t' = card t \\<and> finite t' \\<and> s \\<subseteq> t' \\<and> t' \\<subseteq> s \\<union> t \\<and> s \\<subseteq> span t'\"\n  let ?ths = \"\\<exists>t'. ?P t'\"\n  {\n    assume \"s \\<subseteq> t\"\n    then have ?ths\n      by (metis ft Un_commute sp sup_ge1)\n  }\n  moreover\n  {\n    assume st: \"t \\<subseteq> s\"\n    from spanning_subset_independent[OF st s sp] st ft span_mono[OF st]\n    have ?ths\n      by (metis Un_absorb sp)\n  }\n  moreover\n  {\n    assume st: \"\\<not> s \\<subseteq> t\" \"\\<not> t \\<subseteq> s\"\n    from st(2) obtain b where b: \"b \\<in> t\" \"b \\<notin> s\"\n      by blast\n    from b have \"t - {b} - s \\<subset> t - s\"\n      by blast\n    then have cardlt: \"card (t - {b} - s) < card (t - s)\"\n      using ft by (auto intro: psubset_card_mono)\n    from b ft have ct0: \"card t \\<noteq> 0\"\n      by auto\n    have ?ths\n    proof cases\n      assume stb: \"s \\<subseteq> span (t - {b})\"\n      from ft have ftb: \"finite (t - {b})\"\n        by auto\n      from less(1)[OF cardlt ftb s stb]\n      obtain u where u: \"card u = card (t - {b})\" \"s \\<subseteq> u\" \"u \\<subseteq> s \\<union> (t - {b})\" \"s \\<subseteq> span u\"\n        and fu: \"finite u\" by blast\n      let ?w = \"insert b u\"\n      have th0: \"s \\<subseteq> insert b u\"\n        using u by blast\n      from u(3) b have \"u \\<subseteq> s \\<union> t\"\n        by blast\n      then have th1: \"insert b u \\<subseteq> s \\<union> t\"\n        using u b by blast\n      have bu: \"b \\<notin> u\"\n        using b u by blast\n      from u(1) ft b have \"card u = (card t - 1)\"\n        by auto\n      then have th2: \"card (insert b u) = card t\"\n        using card_insert_disjoint[OF fu bu] ct0 by auto\n      from u(4) have \"s \\<subseteq> span u\" .\n      also have \"\\<dots> \\<subseteq> span (insert b u)\"\n        by (rule span_mono) blast\n      finally have th3: \"s \\<subseteq> span (insert b u)\" .\n      from th0 th1 th2 th3 fu have th: \"?P ?w\"\n        by blast\n      from th show ?thesis by blast\n    next\n      assume stb: \"\\<not> s \\<subseteq> span (t - {b})\"\n      from stb obtain a where a: \"a \\<in> s\" \"a \\<notin> span (t - {b})\"\n        by blast\n      have ab: \"a \\<noteq> b\"\n        using a b by blast\n      have at: \"a \\<notin> t\"\n        using a ab span_superset[of a \"t- {b}\"] by auto\n      have mlt: \"card ((insert a (t - {b})) - s) < card (t - s)\"\n        using cardlt ft a b by auto\n      have ft': \"finite (insert a (t - {b}))\"\n        using ft by auto\n      {\n        fix x\n        assume xs: \"x \\<in> s\"\n        have t: \"t \\<subseteq> insert b (insert a (t - {b}))\"\n          using b by auto\n        from b(1) have \"b \\<in> span t\"\n          by (simp add: span_superset)\n        have bs: \"b \\<in> span (insert a (t - {b}))\"\n          apply (rule in_span_delete)\n          using a sp unfolding subset_eq\n          apply auto\n          done\n        from xs sp have \"x \\<in> span t\"\n          by blast\n        with span_mono[OF t] have x: \"x \\<in> span (insert b (insert a (t - {b})))\" ..\n        from span_trans[OF bs x] have \"x \\<in> span (insert a (t - {b}))\" .\n      }\n      then have sp': \"s \\<subseteq> span (insert a (t - {b}))\"\n        by blast\n      from less(1)[OF mlt ft' s sp'] obtain u where u:\n        \"card u = card (insert a (t - {b}))\"\n        \"finite u\" \"s \\<subseteq> u\" \"u \\<subseteq> s \\<union> insert a (t - {b})\"\n        \"s \\<subseteq> span u\" by blast\n      from u a b ft at ct0 have \"?P u\"\n        by auto\n      then show ?thesis by blast\n    qed\n  }\n  ultimately show ?ths by blast\nqed\n\ntext {* This implies corresponding size bounds. *}\n\nlemma independent_span_bound:\n  assumes f: \"finite t\"\n    and i: \"independent s\"\n    and sp: \"s \\<subseteq> span t\"\n  shows \"finite s \\<and> card s \\<le> card t\"\n  by (metis exchange_lemma[OF f i sp] finite_subset card_mono)\n\nlemma finite_Atleast_Atmost_nat[simp]: \"finite {f x |x. x\\<in> (UNIV::'a::finite set)}\"\nproof -\n  have eq: \"{f x |x. x\\<in> UNIV} = f ` UNIV\"\n    by auto\n  show ?thesis unfolding eq\n    apply (rule finite_imageI)\n    apply (rule finite)\n    done\nqed\n\n\nsubsection {* Euclidean Spaces as Typeclass *}\n\nlemma independent_Basis: \"independent Basis\"\n  unfolding dependent_def\n  apply (subst span_finite)\n  apply simp\n  apply clarify\n  apply (drule_tac f=\"inner a\" in arg_cong)\n  apply (simp add: inner_Basis inner_setsum_right eq_commute)\n  done\n\nlemma span_Basis [simp]: \"span Basis = UNIV\"\n  unfolding span_finite [OF finite_Basis]\n  by (fast intro: euclidean_representation)\n\nlemma in_span_Basis: \"x \\<in> span Basis\"\n  unfolding span_Basis ..\n\nlemma Basis_le_norm: \"b \\<in> Basis \\<Longrightarrow> \\<bar>x \\<bullet> b\\<bar> \\<le> norm x\"\n  by (rule order_trans [OF Cauchy_Schwarz_ineq2]) simp\n\nlemma norm_bound_Basis_le: \"b \\<in> Basis \\<Longrightarrow> norm x \\<le> e \\<Longrightarrow> \\<bar>x \\<bullet> b\\<bar> \\<le> e\"\n  by (metis Basis_le_norm order_trans)\n\nlemma norm_bound_Basis_lt: \"b \\<in> Basis \\<Longrightarrow> norm x < e \\<Longrightarrow> \\<bar>x \\<bullet> b\\<bar> < e\"\n  by (metis Basis_le_norm le_less_trans)\n\nlemma norm_le_l1: \"norm x \\<le> (\\<Sum>b\\<in>Basis. \\<bar>x \\<bullet> b\\<bar>)\"\n  apply (subst euclidean_representation[of x, symmetric])\n  apply (rule order_trans[OF norm_setsum])\n  apply (auto intro!: setsum_mono)\n  done\n\nlemma setsum_norm_allsubsets_bound:\n  fixes f :: \"'a \\<Rightarrow> 'n::euclidean_space\"\n  assumes fP: \"finite P\"\n    and fPs: \"\\<And>Q. Q \\<subseteq> P \\<Longrightarrow> norm (setsum f Q) \\<le> e\"\n  shows \"(\\<Sum>x\\<in>P. norm (f x)) \\<le> 2 * real DIM('n) * e\"\nproof -\n  have \"(\\<Sum>x\\<in>P. norm (f x)) \\<le> (\\<Sum>x\\<in>P. \\<Sum>b\\<in>Basis. \\<bar>f x \\<bullet> b\\<bar>)\"\n    by (rule setsum_mono) (rule norm_le_l1)\n  also have \"(\\<Sum>x\\<in>P. \\<Sum>b\\<in>Basis. \\<bar>f x \\<bullet> b\\<bar>) = (\\<Sum>b\\<in>Basis. \\<Sum>x\\<in>P. \\<bar>f x \\<bullet> b\\<bar>)\"\n    by (rule setsum.commute)\n  also have \"\\<dots> \\<le> of_nat (card (Basis :: 'n set)) * (2 * e)\"\n  proof (rule setsum_bounded)\n    fix i :: 'n\n    assume i: \"i \\<in> Basis\"\n    have \"norm (\\<Sum>x\\<in>P. \\<bar>f x \\<bullet> i\\<bar>) \\<le>\n      norm ((\\<Sum>x\\<in>P \\<inter> - {x. f x \\<bullet> i < 0}. f x) \\<bullet> i) + norm ((\\<Sum>x\\<in>P \\<inter> {x. f x \\<bullet> i < 0}. f x) \\<bullet> i)\"\n      by (simp add: abs_real_def setsum.If_cases[OF fP] setsum_negf norm_triangle_ineq4 inner_setsum_left\n        del: real_norm_def)\n    also have \"\\<dots> \\<le> e + e\"\n      unfolding real_norm_def\n      by (intro add_mono norm_bound_Basis_le i fPs) auto\n    finally show \"(\\<Sum>x\\<in>P. \\<bar>f x \\<bullet> i\\<bar>) \\<le> 2*e\" by simp\n  qed\n  also have \"\\<dots> = 2 * real DIM('n) * e\"\n    by (simp add: real_of_nat_def)\n  finally show ?thesis .\nqed\n\n\nsubsection {* Linearity and Bilinearity continued *}\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  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 (setsum ?g Basis)\"\n      by (simp add: linear_setsum [OF lf] linear_cmul [OF lf])\n    finally have th0: \"norm (f x) = norm (setsum ?g Basis)\" .\n    have th: \"\\<forall>b\\<in>Basis. norm (?g b) \\<le> norm (f b) * norm x\"\n    proof\n      fix i :: 'a\n      assume i: \"i \\<in> Basis\"\n      from Basis_le_norm[OF i, of x]\n      show \"norm (?g i) \\<le> norm (f i) * norm x\"\n        unfolding norm_scaleR\n        apply (subst mult.commute)\n        apply (rule mult_mono)\n        apply (auto simp add: field_simps)\n        done\n    qed\n    from setsum_norm_le[of _ ?g, OF th]\n    show \"norm (f x) \\<le> ?B * norm x\"\n      unfolding th0 setsum_left_distrib by metis\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\"\nproof\n  assume \"linear f\"\n  then interpret f: linear f .\n  show \"bounded_linear f\"\n  proof\n    have \"\\<exists>B. \\<forall>x. norm (f x) \\<le> B * norm x\"\n      using `linear f` by (rule linear_bounded)\n    then show \"\\<exists>K. \\<forall>x. norm (f x) \\<le> norm x * K\"\n      by (simp add: mult.commute)\n  qed\nnext\n  assume \"bounded_linear f\"\n  then interpret f: bounded_linear f .\n  show \"linear f\" ..\nqed\n\nlemma linear_bounded_pos:\n  fixes f :: \"'a::euclidean_space \\<Rightarrow> 'b::real_normed_vector\"\n  assumes lf: \"linear f\"\n  shows \"\\<exists>B > 0. \\<forall>x. norm (f x) \\<le> B * norm x\"\nproof -\n  have \"\\<exists>B > 0. \\<forall>x. norm (f x) \\<le> norm x * B\"\n    using lf unfolding linear_conv_bounded_linear\n    by (rule bounded_linear.pos_bounded)\n  then show ?thesis\n    by (simp only: mult.commute)\nqed\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  unfolding linear_conv_bounded_linear[symmetric]\n  by (rule linearI[OF assms])\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 (setsum (\\<lambda>i. (x \\<bullet> i) *\\<^sub>R i) Basis) (setsum (\\<lambda>i. (y \\<bullet> i) *\\<^sub>R i) Basis))\"\n    apply (subst euclidean_representation[where 'a='m])\n    apply (subst euclidean_representation[where 'a='n])\n    apply rule\n    done\n  also have \"\\<dots> = norm (setsum (\\<lambda> (i,j). h ((x \\<bullet> i) *\\<^sub>R i) ((y \\<bullet> j) *\\<^sub>R j)) (Basis \\<times> Basis))\"\n    unfolding bilinear_setsum[OF bh finite_Basis finite_Basis] ..\n  finally have th: \"norm (h x y) = \\<dots>\" .\n  show \"norm (h x y) \\<le> (\\<Sum>i\\<in>Basis. \\<Sum>j\\<in>Basis. norm (h i j)) * norm x * norm y\"\n    apply (auto simp add: setsum_left_distrib th setsum.cartesian_product)\n    apply (rule setsum_norm_le)\n    apply simp\n    apply (auto simp add: bilinear_rmul[OF bh] bilinear_lmul[OF bh]\n      field_simps simp del: scaleR_scaleR)\n    apply (rule mult_mono)\n    apply (auto simp add: zero_le_mult_iff Basis_le_norm)\n    apply (rule mult_mono)\n    apply (auto simp add: zero_le_mult_iff Basis_le_norm)\n    done\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 `bilinear h` 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 `bilinear h` unfolding bilinear_def linear_iff by simp\n  next\n    fix r x y\n    show \"h (scaleR r x) y = scaleR r (h x y)\"\n      using `bilinear h` unfolding bilinear_def linear_iff\n      by simp\n  next\n    fix r x y\n    show \"h x (scaleR r y) = scaleR r (h x y)\"\n      using `bilinear h` unfolding bilinear_def linear_iff\n      by simp\n  next\n    have \"\\<exists>B. \\<forall>x y. norm (h x y) \\<le> B * norm x * norm y\"\n      using `bilinear h` 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\"\nproof -\n  have \"\\<exists>B > 0. \\<forall>x y. norm (h x y) \\<le> norm x * norm y * B\"\n    using bh [unfolded bilinear_conv_bounded_bilinear]\n    by (rule bounded_bilinear.pos_bounded)\n  then show ?thesis\n    by (simp only: ac_simps)\nqed\n\n\nsubsection {* We continue. *}\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  using independent_span_bound[OF finite_Basis, of S] 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 {* Hence we can create a maximal independent subset. *}\n\nlemma maximal_independent_subset_extend:\n  fixes S :: \"'a::euclidean_space set\"\n  assumes sv: \"S \\<subseteq> V\"\n    and iS: \"independent S\"\n  shows \"\\<exists>B. S \\<subseteq> B \\<and> B \\<subseteq> V \\<and> independent B \\<and> V \\<subseteq> span B\"\n  using sv iS\nproof (induct \"DIM('a) - card S\" arbitrary: S rule: less_induct)\n  case less\n  note sv = `S \\<subseteq> V` and i = `independent S`\n  let ?P = \"\\<lambda>B. S \\<subseteq> B \\<and> B \\<subseteq> V \\<and> independent B \\<and> V \\<subseteq> span B\"\n  let ?ths = \"\\<exists>x. ?P x\"\n  let ?d = \"DIM('a)\"\n  show ?ths\n  proof (cases \"V \\<subseteq> span S\")\n    case True\n    then show ?thesis\n      using sv i by blast\n  next\n    case False\n    then obtain a where a: \"a \\<in> V\" \"a \\<notin> span S\"\n      by blast\n    from a have aS: \"a \\<notin> S\"\n      by (auto simp add: span_superset)\n    have th0: \"insert a S \\<subseteq> V\"\n      using a sv by blast\n    from independent_insert[of a S]  i a\n    have th1: \"independent (insert a S)\"\n      by auto\n    have mlt: \"?d - card (insert a S) < ?d - card S\"\n      using aS a independent_bound[OF th1] by auto\n\n    from less(1)[OF mlt th0 th1]\n    obtain B where B: \"insert a S \\<subseteq> B\" \"B \\<subseteq> V\" \"independent B\" \" V \\<subseteq> span B\"\n      by blast\n    from B have \"?P B\" by auto\n    then show ?thesis by blast\n  qed\nqed\n\nlemma maximal_independent_subset:\n  \"\\<exists>(B:: ('a::euclidean_space) set). B\\<subseteq> V \\<and> independent B \\<and> V \\<subseteq> span B\"\n  by (metis maximal_independent_subset_extend[of \"{}:: ('a::euclidean_space) set\"]\n    empty_subsetI independent_empty)\n\n\ntext {* Notion of dimension. *}\n\ndefinition \"dim V = (SOME n. \\<exists>B. B \\<subseteq> V \\<and> independent B \\<and> V \\<subseteq> span B \\<and> card B = n)\"\n\nlemma basis_exists:\n  \"\\<exists>B. (B :: ('a::euclidean_space) set) \\<subseteq> V \\<and> independent B \\<and> V \\<subseteq> span B \\<and> (card B = dim V)\"\n  unfolding dim_def some_eq_ex[of \"\\<lambda>n. \\<exists>B. B \\<subseteq> V \\<and> independent B \\<and> V \\<subseteq> span B \\<and> (card B = n)\"]\n  using maximal_independent_subset[of V] independent_bound\n  by auto\n\ntext {* Consequences of independence or spanning for cardinality. *}\n\nlemma independent_card_le_dim:\n  fixes B :: \"'a::euclidean_space set\"\n  assumes \"B \\<subseteq> V\"\n    and \"independent B\"\n  shows \"card B \\<le> dim V\"\nproof -\n  from basis_exists[of V] `B \\<subseteq> V`\n  obtain B' where \"independent B'\"\n    and \"B \\<subseteq> span B'\"\n    and \"card B' = dim V\"\n    by blast\n  with independent_span_bound[OF _ `independent B` `B \\<subseteq> span B'`] independent_bound[of B']\n  show ?thesis by auto\nqed\n\nlemma span_card_ge_dim:\n  fixes B :: \"'a::euclidean_space set\"\n  shows \"B \\<subseteq> V \\<Longrightarrow> V \\<subseteq> span B \\<Longrightarrow> finite B \\<Longrightarrow> dim V \\<le> card B\"\n  by (metis basis_exists[of V] independent_span_bound subset_trans)\n\nlemma basis_card_eq_dim:\n  fixes V :: \"'a::euclidean_space set\"\n  shows \"B \\<subseteq> V \\<Longrightarrow> V \\<subseteq> span B \\<Longrightarrow> independent B \\<Longrightarrow> finite B \\<and> card B = dim V\"\n  by (metis order_eq_iff independent_card_le_dim span_card_ge_dim independent_bound)\n\nlemma dim_unique:\n  fixes B :: \"'a::euclidean_space set\"\n  shows \"B \\<subseteq> V \\<Longrightarrow> V \\<subseteq> span B \\<Longrightarrow> independent B \\<Longrightarrow> card B = n \\<Longrightarrow> dim V = n\"\n  by (metis basis_card_eq_dim)\n\ntext {* More lemmas about dimension. *}\n\nlemma dim_UNIV: \"dim (UNIV :: 'a::euclidean_space set) = DIM('a)\"\n  using independent_Basis\n  by (intro dim_unique[of Basis]) auto\n\nlemma dim_subset:\n  fixes S :: \"'a::euclidean_space set\"\n  shows \"S \\<subseteq> T \\<Longrightarrow> dim S \\<le> dim T\"\n  using basis_exists[of T] basis_exists[of S]\n  by (metis independent_card_le_dim subset_trans)\n\nlemma dim_subset_UNIV:\n  fixes S :: \"'a::euclidean_space set\"\n  shows \"dim S \\<le> DIM('a)\"\n  by (metis dim_subset subset_UNIV dim_UNIV)\n\ntext {* Converses to those. *}\n\nlemma card_ge_dim_independent:\n  fixes B :: \"'a::euclidean_space set\"\n  assumes BV: \"B \\<subseteq> V\"\n    and iB: \"independent B\"\n    and dVB: \"dim V \\<le> card B\"\n  shows \"V \\<subseteq> span B\"\nproof\n  fix a\n  assume aV: \"a \\<in> V\"\n  {\n    assume aB: \"a \\<notin> span B\"\n    then have iaB: \"independent (insert a B)\"\n      using iB aV BV by (simp add: independent_insert)\n    from aV BV have th0: \"insert a B \\<subseteq> V\"\n      by blast\n    from aB have \"a \\<notin>B\"\n      by (auto simp add: span_superset)\n    with independent_card_le_dim[OF th0 iaB] dVB independent_bound[OF iB]\n    have False by auto\n  }\n  then show \"a \\<in> span B\" by blast\nqed\n\nlemma card_le_dim_spanning:\n  assumes BV: \"(B:: ('a::euclidean_space) set) \\<subseteq> V\"\n    and VB: \"V \\<subseteq> span B\"\n    and fB: \"finite B\"\n    and dVB: \"dim V \\<ge> card B\"\n  shows \"independent B\"\nproof -\n  {\n    fix a\n    assume a: \"a \\<in> B\" \"a \\<in> span (B - {a})\"\n    from a fB have c0: \"card B \\<noteq> 0\"\n      by auto\n    from a fB have cb: \"card (B - {a}) = card B - 1\"\n      by auto\n    from BV a have th0: \"B - {a} \\<subseteq> V\"\n      by blast\n    {\n      fix x\n      assume x: \"x \\<in> V\"\n      from a have eq: \"insert a (B - {a}) = B\"\n        by blast\n      from x VB have x': \"x \\<in> span B\"\n        by blast\n      from span_trans[OF a(2), unfolded eq, OF x']\n      have \"x \\<in> span (B - {a})\" .\n    }\n    then have th1: \"V \\<subseteq> span (B - {a})\"\n      by blast\n    have th2: \"finite (B - {a})\"\n      using fB by auto\n    from span_card_ge_dim[OF th0 th1 th2]\n    have c: \"dim V \\<le> card (B - {a})\" .\n    from c c0 dVB cb have False by simp\n  }\n  then show ?thesis\n    unfolding dependent_def by blast\nqed\n\nlemma card_eq_dim:\n  fixes B :: \"'a::euclidean_space set\"\n  shows \"B \\<subseteq> V \\<Longrightarrow> card B = dim V \\<Longrightarrow> finite B \\<Longrightarrow> independent B \\<longleftrightarrow> V \\<subseteq> span B\"\n  by (metis order_eq_iff card_le_dim_spanning card_ge_dim_independent)\n\ntext {* More general size bound lemmas. *}\n\nlemma independent_bound_general:\n  fixes S :: \"'a::euclidean_space set\"\n  shows \"independent S \\<Longrightarrow> finite S \\<and> card S \\<le> dim S\"\n  by (metis independent_card_le_dim independent_bound subset_refl)\n\nlemma dependent_biggerset_general:\n  fixes S :: \"'a::euclidean_space set\"\n  shows \"(finite S \\<Longrightarrow> card S > dim S) \\<Longrightarrow> dependent S\"\n  using independent_bound_general[of S] by (metis linorder_not_le)\n\nlemma dim_span:\n  fixes S :: \"'a::euclidean_space set\"\n  shows \"dim (span S) = dim S\"\nproof -\n  have th0: \"dim S \\<le> dim (span S)\"\n    by (auto simp add: subset_eq intro: dim_subset span_superset)\n  from basis_exists[of S]\n  obtain B where B: \"B \\<subseteq> S\" \"independent B\" \"S \\<subseteq> span B\" \"card B = dim S\"\n    by blast\n  from B have fB: \"finite B\" \"card B = dim S\"\n    using independent_bound by blast+\n  have bSS: \"B \\<subseteq> span S\"\n    using B(1) by (metis subset_eq span_inc)\n  have sssB: \"span S \\<subseteq> span B\"\n    using span_mono[OF B(3)] by (simp add: span_span)\n  from span_card_ge_dim[OF bSS sssB fB(1)] th0 show ?thesis\n    using fB(2) by arith\nqed\n\nlemma subset_le_dim:\n  fixes S :: \"'a::euclidean_space set\"\n  shows \"S \\<subseteq> span T \\<Longrightarrow> dim S \\<le> dim T\"\n  by (metis dim_span dim_subset)\n\nlemma span_eq_dim:\n  fixes S :: \"'a::euclidean_space set\"\n  shows \"span S = span T \\<Longrightarrow> dim S = dim T\"\n  by (metis dim_span)\n\nlemma spans_image:\n  assumes lf: \"linear f\"\n    and VB: \"V \\<subseteq> span B\"\n  shows \"f ` V \\<subseteq> span (f ` B)\"\n  unfolding span_linear_image[OF lf] by (metis VB image_mono)\n\nlemma dim_image_le:\n  fixes f :: \"'a::euclidean_space \\<Rightarrow> 'b::euclidean_space\"\n  assumes lf: \"linear f\"\n  shows \"dim (f ` S) \\<le> dim (S)\"\nproof -\n  from basis_exists[of S] obtain B where\n    B: \"B \\<subseteq> S\" \"independent B\" \"S \\<subseteq> span B\" \"card B = dim S\" by blast\n  from B have fB: \"finite B\" \"card B = dim S\"\n    using independent_bound by blast+\n  have \"dim (f ` S) \\<le> card (f ` B)\"\n    apply (rule span_card_ge_dim)\n    using lf B fB\n    apply (auto simp add: span_linear_image spans_image subset_image_iff)\n    done\n  also have \"\\<dots> \\<le> dim S\"\n    using card_image_le[OF fB(1)] fB by simp\n  finally show ?thesis .\nqed\n\ntext {* Relation between bases and injectivity/surjectivity of map. *}\n\nlemma spanning_surjective_image:\n  assumes us: \"UNIV \\<subseteq> span S\"\n    and lf: \"linear f\"\n    and sf: \"surj f\"\n  shows \"UNIV \\<subseteq> span (f ` S)\"\nproof -\n  have \"UNIV \\<subseteq> f ` UNIV\"\n    using sf by (auto simp add: surj_def)\n  also have \" \\<dots> \\<subseteq> span (f ` S)\"\n    using spans_image[OF lf us] .\n  finally show ?thesis .\nqed\n\nlemma independent_injective_image:\n  assumes iS: \"independent S\"\n    and lf: \"linear f\"\n    and fi: \"inj f\"\n  shows \"independent (f ` S)\"\nproof -\n  {\n    fix a\n    assume a: \"a \\<in> S\" \"f a \\<in> span (f ` S - {f a})\"\n    have eq: \"f ` S - {f a} = f ` (S - {a})\"\n      using fi by (auto simp add: inj_on_def)\n    from a have \"f a \\<in> f ` span (S - {a})\"\n      unfolding eq span_linear_image[OF lf, of \"S - {a}\"] by blast\n    then have \"a \\<in> span (S - {a})\"\n      using fi by (auto simp add: inj_on_def)\n    with a(1) iS have False\n      by (simp add: dependent_def)\n  }\n  then show ?thesis\n    unfolding dependent_def by blast\nqed\n\ntext {* Picking an orthogonal replacement for a spanning set. *}\n\n(* FIXME : Move to some general theory ?*)\ndefinition \"pairwise R S \\<longleftrightarrow> (\\<forall>x \\<in> S. \\<forall>y\\<in> S. x\\<noteq>y \\<longrightarrow> R x y)\"\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 unfolding pairwise_def\n  by (auto simp add: 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    apply (rule exI[where x=\"{}\"])\n    apply (auto simp add: pairwise_def)\n    done\nnext\n  case (insert a B)\n  note fB = `finite B` and aB = `a \\<notin> B`\n  from `\\<exists>C. finite C \\<and> card C \\<le> card B \\<and> span C = span B \\<and> pairwise orthogonal C`\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 - setsum (\\<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  from fB aB C(1,2) have cC: \"card ?C \\<le> card (insert a B)\"\n    by (simp add: card_insert_if)\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      apply (simp only: scaleR_right_diff_distrib th0)\n      apply (rule span_add_eq)\n      apply (rule span_mul)\n      apply (rule span_setsum)\n      apply clarify\n      apply (rule span_mul)\n      apply (rule span_superset)\n      apply assumption\n      done\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 \"orthogonal ?a y\"\n      unfolding orthogonal_def\n      unfolding inner_diff inner_setsum_left right_minus_eq\n      unfolding setsum.remove [OF `finite C` `y \\<in> C`]\n      apply (clarsimp simp add: inner_commute[of y a])\n      apply (rule setsum.neutral)\n      apply clarsimp\n      apply (rule C(4)[unfolded pairwise_def orthogonal_def, rule_format])\n      using `y \\<in> C` by auto\n  }\n  with `pairwise orthogonal C` 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 blast\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_inc 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 card_le_dim_spanning[OF CSV SVC C(1)] C(2,3) fB\n  have iC: \"independent C\"\n    by (simp add: dim_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 add: dim_span)\n  ultimately have CdV: \"card C = dim V\"\n    using C(1) by simp\n  from C B CSV CdV iC show ?thesis\n    by auto\nqed\n\nlemma span_eq: \"span S = span T \\<longleftrightarrow> S \\<subseteq> span T \\<and> T \\<subseteq> span S\"\n  using span_inc[unfolded subset_eq] using span_mono[of T \"span S\"] span_mono[of S \"span T\"]\n  by (auto simp add: span_span)\n\ntext {* Low-dimensional subset is in a hyperplane (weak orthogonal complement). *}\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  from span_mono[OF B(2)] span_mono[OF B(3)]\n  have sSB: \"span S = span B\"\n    by (simp add: span_span)\n  let ?a = \"a - setsum (\\<lambda>b. (a \\<bullet> b / (b \\<bullet> b)) *\\<^sub>R b) B\"\n  have \"setsum (\\<lambda>b. (a \\<bullet> b / (b \\<bullet> b)) *\\<^sub>R b) B \\<in> span S\"\n    unfolding sSB\n    apply (rule span_setsum)\n    apply clarsimp\n    apply (rule span_mul)\n    apply (rule span_superset)\n    apply assumption\n    done\n  with a have a0:\"?a  \\<noteq> 0\"\n    by auto\n  have \"\\<forall>x\\<in>span B. ?a \\<bullet> x = 0\"\n  proof (rule span_induct')\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 \"?a \\<bullet> x = 0\"\n        apply (subst B')\n        using fB fth\n        unfolding setsum_clauses(2)[OF fth]\n        apply simp unfolding inner_simps\n        apply (clarsimp simp add: inner_add inner_setsum_left)\n        apply (rule setsum.neutral, rule ballI)\n        unfolding inner_commute\n        apply (auto simp add: x field_simps\n          intro: B(5)[unfolded pairwise_def orthogonal_def, rule_format])\n        done\n    }\n    then show \"\\<forall>x \\<in> B. ?a \\<bullet> x = 0\"\n      by blast\n  qed\n  with a0 show ?thesis\n    unfolding sSB by (auto intro: exI[where x=\"?a\"])\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}\"\nproof -\n  {\n    assume \"span S = UNIV\"\n    then have \"dim (span S) = dim (UNIV :: ('a) set)\"\n      by simp\n    then have \"dim S = DIM('a)\"\n      by (simp add: dim_span dim_UNIV)\n    with d have False by arith\n  }\n  then have th: \"span S \\<noteq> UNIV\"\n    by blast\n  from span_not_univ_subset_hyperplane[OF th] show ?thesis .\nqed\n\ntext {* We can extend a linear basis-basis injection to the whole set. *}\n\nlemma linear_indep_image_lemma:\n  assumes lf: \"linear f\"\n    and fB: \"finite B\"\n    and ifB: \"independent (f ` B)\"\n    and fi: \"inj_on f B\"\n    and xsB: \"x \\<in> span B\"\n    and fx: \"f x = 0\"\n  shows \"x = 0\"\n  using fB ifB fi xsB fx\nproof (induct arbitrary: x rule: finite_induct[OF fB])\n  case 1\n  then show ?case by auto\nnext\n  case (2 a b x)\n  have fb: \"finite b\" using \"2.prems\" by simp\n  have th0: \"f ` b \\<subseteq> f ` (insert a b)\"\n    apply (rule image_mono)\n    apply blast\n    done\n  from independent_mono[ OF \"2.prems\"(2) th0]\n  have ifb: \"independent (f ` b)\"  .\n  have fib: \"inj_on f b\"\n    apply (rule subset_inj_on [OF \"2.prems\"(3)])\n    apply blast\n    done\n  from span_breakdown[of a \"insert a b\", simplified, OF \"2.prems\"(4)]\n  obtain k where k: \"x - k*\\<^sub>R a \\<in> span (b - {a})\"\n    by blast\n  have \"f (x - k*\\<^sub>R a) \\<in> span (f ` b)\"\n    unfolding span_linear_image[OF lf]\n    apply (rule imageI)\n    using k span_mono[of \"b - {a}\" b]\n    apply blast\n    done\n  then have \"f x - k*\\<^sub>R f a \\<in> span (f ` b)\"\n    by (simp add: linear_sub[OF lf] linear_cmul[OF lf])\n  then have th: \"-k *\\<^sub>R f a \\<in> span (f ` b)\"\n    using \"2.prems\"(5) by simp\n  have xsb: \"x \\<in> span b\"\n  proof (cases \"k = 0\")\n    case True\n    with k have \"x \\<in> span (b - {a})\" by simp\n    then show ?thesis using span_mono[of \"b - {a}\" b]\n      by blast\n  next\n    case False\n    with span_mul[OF th, of \"- 1/ k\"]\n    have th1: \"f a \\<in> span (f ` b)\"\n      by auto\n    from inj_on_image_set_diff[OF \"2.prems\"(3), of \"insert a b \" \"{a}\", symmetric]\n    have tha: \"f ` insert a b - f ` {a} = f ` (insert a b - {a})\" by blast\n    from \"2.prems\"(2) [unfolded dependent_def bex_simps(8), rule_format, of \"f a\"]\n    have \"f a \\<notin> span (f ` b)\" using tha\n      using \"2.hyps\"(2)\n      \"2.prems\"(3) by auto\n    with th1 have False by blast\n    then show ?thesis by blast\n  qed\n  from \"2.hyps\"(3)[OF fb ifb fib xsb \"2.prems\"(5)] show \"x = 0\" .\nqed\n\ntext {* We can extend a linear mapping from basis. *}\n\nlemma linear_independent_extend_lemma:\n  fixes f :: \"'a::real_vector \\<Rightarrow> 'b::real_vector\"\n  assumes fi: \"finite B\"\n    and ib: \"independent B\"\n  shows \"\\<exists>g.\n    (\\<forall>x\\<in> span B. \\<forall>y\\<in> span B. g (x + y) = g x + g y) \\<and>\n    (\\<forall>x\\<in> span B. \\<forall>c. g (c*\\<^sub>R x) = c *\\<^sub>R g x) \\<and>\n    (\\<forall>x\\<in> B. g x = f x)\"\n  using ib fi\nproof (induct rule: finite_induct[OF fi])\n  case 1\n  then show ?case by auto\nnext\n  case (2 a b)\n  from \"2.prems\" \"2.hyps\" have ibf: \"independent b\" \"finite b\"\n    by (simp_all add: independent_insert)\n  from \"2.hyps\"(3)[OF ibf] obtain g where\n    g: \"\\<forall>x\\<in>span b. \\<forall>y\\<in>span b. g (x + y) = g x + g y\"\n    \"\\<forall>x\\<in>span b. \\<forall>c. g (c *\\<^sub>R x) = c *\\<^sub>R g x\" \"\\<forall>x\\<in>b. g x = f x\" by blast\n  let ?h = \"\\<lambda>z. SOME k. (z - k *\\<^sub>R a) \\<in> span b\"\n  {\n    fix z\n    assume z: \"z \\<in> span (insert a b)\"\n    have th0: \"z - ?h z *\\<^sub>R a \\<in> span b\"\n      apply (rule someI_ex)\n      unfolding span_breakdown_eq[symmetric]\n      apply (rule z)\n      done\n    {\n      fix k\n      assume k: \"z - k *\\<^sub>R a \\<in> span b\"\n      have eq: \"z - ?h z *\\<^sub>R a - (z - k*\\<^sub>R a) = (k - ?h z) *\\<^sub>R a\"\n        by (simp add: field_simps scaleR_left_distrib [symmetric])\n      from span_sub[OF th0 k] have khz: \"(k - ?h z) *\\<^sub>R a \\<in> span b\"\n        by (simp add: eq)\n      {\n        assume \"k \\<noteq> ?h z\"\n        then have k0: \"k - ?h z \\<noteq> 0\" by simp\n        from k0 span_mul[OF khz, of \"1 /(k - ?h z)\"]\n        have \"a \\<in> span b\" by simp\n        with \"2.prems\"(1) \"2.hyps\"(2) have False\n          by (auto simp add: dependent_def)\n      }\n      then have \"k = ?h z\" by blast\n    }\n    with th0 have \"z - ?h z *\\<^sub>R a \\<in> span b \\<and> (\\<forall>k. z - k *\\<^sub>R a \\<in> span b \\<longrightarrow> k = ?h z)\"\n      by blast\n  }\n  note h = this\n  let ?g = \"\\<lambda>z. ?h z *\\<^sub>R f a + g (z - ?h z *\\<^sub>R a)\"\n  {\n    fix x y\n    assume x: \"x \\<in> span (insert a b)\"\n      and y: \"y \\<in> span (insert a b)\"\n    have tha: \"\\<And>(x::'a) y a k l. (x + y) - (k + l) *\\<^sub>R a = (x - k *\\<^sub>R a) + (y - l *\\<^sub>R a)\"\n      by (simp add: algebra_simps)\n    have addh: \"?h (x + y) = ?h x + ?h y\"\n      apply (rule conjunct2[OF h, rule_format, symmetric])\n      apply (rule span_add[OF x y])\n      unfolding tha\n      apply (metis span_add x y conjunct1[OF h, rule_format])\n      done\n    have \"?g (x + y) = ?g x + ?g y\"\n      unfolding addh tha\n      g(1)[rule_format,OF conjunct1[OF h, OF x] conjunct1[OF h, OF y]]\n      by (simp add: scaleR_left_distrib)}\n  moreover\n  {\n    fix x :: \"'a\"\n    fix c :: real\n    assume x: \"x \\<in> span (insert a b)\"\n    have tha: \"\\<And>(x::'a) c k a. c *\\<^sub>R x - (c * k) *\\<^sub>R a = c *\\<^sub>R (x - k *\\<^sub>R a)\"\n      by (simp add: algebra_simps)\n    have hc: \"?h (c *\\<^sub>R x) = c * ?h x\"\n      apply (rule conjunct2[OF h, rule_format, symmetric])\n      apply (metis span_mul x)\n      apply (metis tha span_mul x conjunct1[OF h])\n      done\n    have \"?g (c *\\<^sub>R x) = c*\\<^sub>R ?g x\"\n      unfolding hc tha g(2)[rule_format, OF conjunct1[OF h, OF x]]\n      by (simp add: algebra_simps)\n  }\n  moreover\n  {\n    fix x\n    assume x: \"x \\<in> insert a b\"\n    {\n      assume xa: \"x = a\"\n      have ha1: \"1 = ?h a\"\n        apply (rule conjunct2[OF h, rule_format])\n        apply (metis span_superset insertI1)\n        using conjunct1[OF h, OF span_superset, OF insertI1]\n        apply (auto simp add: span_0)\n        done\n      from xa ha1[symmetric] have \"?g x = f x\"\n        apply simp\n        using g(2)[rule_format, OF span_0, of 0]\n        apply simp\n        done\n    }\n    moreover\n    {\n      assume xb: \"x \\<in> b\"\n      have h0: \"0 = ?h x\"\n        apply (rule conjunct2[OF h, rule_format])\n        apply (metis  span_superset x)\n        apply simp\n        apply (metis span_superset xb)\n        done\n      have \"?g x = f x\"\n        by (simp add: h0[symmetric] g(3)[rule_format, OF xb])\n    }\n    ultimately have \"?g x = f x\"\n      using x by blast\n  }\n  ultimately show ?case\n    apply -\n    apply (rule exI[where x=\"?g\"])\n    apply blast\n    done\nqed\n\nlemma linear_independent_extend:\n  fixes B :: \"'a::euclidean_space set\"\n  assumes iB: \"independent B\"\n  shows \"\\<exists>g. linear g \\<and> (\\<forall>x\\<in>B. g x = f x)\"\nproof -\n  from maximal_independent_subset_extend[of B UNIV] iB\n  obtain C where C: \"B \\<subseteq> C\" \"independent C\" \"\\<And>x. x \\<in> span C\"\n    by auto\n\n  from C(2) independent_bound[of C] linear_independent_extend_lemma[of C f]\n  obtain g where g:\n    \"(\\<forall>x\\<in> span C. \\<forall>y\\<in> span C. g (x + y) = g x + g y) \\<and>\n     (\\<forall>x\\<in> span C. \\<forall>c. g (c*\\<^sub>R x) = c *\\<^sub>R g x) \\<and>\n     (\\<forall>x\\<in> C. g x = f x)\" by blast\n  from g show ?thesis\n    unfolding linear_iff\n    using C\n    apply clarsimp\n    apply blast\n    done\nqed\n\ntext {* Can construct an isomorphism between spaces of same dimension. *}\n\nlemma subspace_isomorphism:\n  fixes S :: \"'a::euclidean_space set\"\n    and T :: \"'b::euclidean_space set\"\n  assumes s: \"subspace S\"\n    and t: \"subspace T\"\n    and d: \"dim S = dim T\"\n  shows \"\\<exists>f. linear f \\<and> f ` S = T \\<and> inj_on f S\"\nproof -\n  from basis_exists[of S] independent_bound\n  obtain B where B: \"B \\<subseteq> S\" \"independent B\" \"S \\<subseteq> span B\" \"card B = dim S\" and fB: \"finite B\"\n    by blast\n  from basis_exists[of T] independent_bound\n  obtain C where C: \"C \\<subseteq> T\" \"independent C\" \"T \\<subseteq> span C\" \"card C = dim T\" and fC: \"finite C\"\n    by blast\n  from B(4) C(4) card_le_inj[of B C] d\n  obtain f where f: \"f ` B \\<subseteq> C\" \"inj_on f B\" using `finite B` `finite C`\n    by auto\n  from linear_independent_extend[OF B(2)]\n  obtain g where g: \"linear g\" \"\\<forall>x\\<in> B. g x = f x\"\n    by blast\n  from inj_on_iff_eq_card[OF fB, of f] f(2) have \"card (f ` B) = card B\"\n    by simp\n  with B(4) C(4) have ceq: \"card (f ` B) = card C\"\n    using d by simp\n  have \"g ` B = f ` B\"\n    using g(2) by (auto simp add: image_iff)\n  also have \"\\<dots> = C\" using card_subset_eq[OF fC f(1) ceq] .\n  finally have gBC: \"g ` B = C\" .\n  have gi: \"inj_on g B\"\n    using f(2) g(2) by (auto simp add: inj_on_def)\n  note g0 = linear_indep_image_lemma[OF g(1) fB, unfolded gBC, OF C(2) gi]\n  {\n    fix x y\n    assume x: \"x \\<in> S\" and y: \"y \\<in> S\" and gxy: \"g x = g y\"\n    from B(3) x y have x': \"x \\<in> span B\" and y': \"y \\<in> span B\"\n      by blast+\n    from gxy have th0: \"g (x - y) = 0\"\n      by (simp add: linear_sub[OF g(1)])\n    have th1: \"x - y \\<in> span B\"\n      using x' y' by (metis span_sub)\n    have \"x = y\"\n      using g0[OF th1 th0] by simp\n  }\n  then have giS: \"inj_on g S\"\n    unfolding inj_on_def by blast\n  from span_subspace[OF B(1,3) s] have \"g ` S = span (g ` B)\"\n    by (simp add: span_linear_image[OF g(1)])\n  also have \"\\<dots> = span C\" unfolding gBC ..\n  also have \"\\<dots> = T\" using span_subspace[OF C(1,3) t] .\n  finally have gS: \"g ` S = T\" .\n  from g(1) gS giS show ?thesis\n    by blast\nqed\n\ntext {* Linear functions are equal on a subspace if they are on a spanning set. *}\n\nlemma subspace_kernel:\n  assumes lf: \"linear f\"\n  shows \"subspace {x. f x = 0}\"\n  apply (simp add: subspace_def)\n  apply (simp add: linear_add[OF lf] linear_cmul[OF lf] linear_0[OF lf])\n  done\n\nlemma linear_eq_0_span:\n  assumes lf: \"linear f\" and f0: \"\\<forall>x\\<in>B. f x = 0\"\n  shows \"\\<forall>x \\<in> span B. f x = 0\"\n  using f0 subspace_kernel[OF lf]\n  by (rule span_induct')\n\nlemma linear_eq_0:\n  assumes lf: \"linear f\"\n    and SB: \"S \\<subseteq> span B\"\n    and f0: \"\\<forall>x\\<in>B. f x = 0\"\n  shows \"\\<forall>x \\<in> S. f x = 0\"\n  by (metis linear_eq_0_span[OF lf] subset_eq SB f0)\n\nlemma linear_eq:\n  assumes lf: \"linear f\"\n    and lg: \"linear g\"\n    and S: \"S \\<subseteq> span B\"\n    and fg: \"\\<forall> x\\<in> B. f x = g x\"\n  shows \"\\<forall>x\\<in> S. f x = g x\"\nproof -\n  let ?h = \"\\<lambda>x. f x - g x\"\n  from fg have fg': \"\\<forall>x\\<in> B. ?h x = 0\" by simp\n  from linear_eq_0[OF linear_compose_sub[OF lf lg] S fg']\n  show ?thesis by simp\nqed\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: \"\\<forall>b\\<in>Basis. f b = g b\"\n  shows \"f = g\"\n  using linear_eq[OF lf lg, of _ Basis] fg by auto\n\ntext {* Similar results for bilinear functions. *}\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 fg: \"\\<forall>x\\<in> B. \\<forall>y\\<in> C. f x y = g x y\"\n  shows \"\\<forall>x\\<in>S. \\<forall>y\\<in>T. 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_0 bilinear_lzero[OF bf] bilinear_lzero[OF bg] span_add Ball_def\n      intro: bilinear_ladd[OF bf])\n\n  have \"\\<forall>x \\<in> span B. \\<forall>y\\<in> span C. f x y = g x y\"\n    apply (rule span_induct' [OF _ sp])\n    apply (rule ballI)\n    apply (rule span_induct')\n    apply (simp add: fg)\n    apply (auto simp add: subspace_def)\n    using bf bg unfolding bilinear_def linear_iff\n    apply (auto simp add: span_0 bilinear_rzero[OF bf] bilinear_rzero[OF bg] span_add Ball_def\n      intro: bilinear_ladd[OF bf])\n    done\n  then show ?thesis\n    using SB TC 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: \"\\<forall>i\\<in>Basis. \\<forall>j\\<in>Basis. 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\ntext {* Detailed theorems about left and right invertibility in general case. *}\n\nlemma linear_injective_left_inverse:\n  fixes f :: \"'a::euclidean_space \\<Rightarrow> 'b::euclidean_space\"\n  assumes lf: \"linear f\"\n    and fi: \"inj f\"\n  shows \"\\<exists>g. linear g \\<and> g \\<circ> f = id\"\nproof -\n  from linear_independent_extend[OF independent_injective_image, OF independent_Basis, OF lf fi]\n  obtain h :: \"'b \\<Rightarrow> 'a\" where h: \"linear h\" \"\\<forall>x \\<in> f ` Basis. h x = inv f x\"\n    by blast\n  from h(2) have th: \"\\<forall>i\\<in>Basis. (h \\<circ> f) i = id i\"\n    using inv_o_cancel[OF fi, unfolded fun_eq_iff id_def o_def]\n    by auto\n  from linear_eq_stdbasis[OF linear_compose[OF lf h(1)] linear_id th]\n  have \"h \\<circ> f = id\" .\n  then show ?thesis\n    using h(1) by blast\nqed\n\nlemma linear_surjective_right_inverse:\n  fixes f :: \"'a::euclidean_space \\<Rightarrow> 'b::euclidean_space\"\n  assumes lf: \"linear f\"\n    and sf: \"surj f\"\n  shows \"\\<exists>g. linear g \\<and> f \\<circ> g = id\"\nproof -\n  from linear_independent_extend[OF independent_Basis[where 'a='b],of \"inv f\"]\n  obtain h :: \"'b \\<Rightarrow> 'a\" where h: \"linear h\" \"\\<forall>x\\<in>Basis. h x = inv f x\"\n    by blast\n  from h(2) have th: \"\\<forall>i\\<in>Basis. (f \\<circ> h) i = id i\"\n    using sf by (auto simp add: surj_iff_all)\n  from linear_eq_stdbasis[OF linear_compose[OF h(1) lf] linear_id th]\n  have \"f \\<circ> h = id\" .\n  then show ?thesis\n    using h(1) by blast\nqed\n\ntext {* An injective map @{typ \"'a::euclidean_space \\<Rightarrow> 'b::euclidean_space\"} is also surjective. *}\n\nlemma linear_injective_imp_surjective:\n  fixes f :: \"'a::euclidean_space \\<Rightarrow> 'a::euclidean_space\"\n  assumes lf: \"linear f\"\n    and fi: \"inj f\"\n  shows \"surj f\"\nproof -\n  let ?U = \"UNIV :: 'a set\"\n  from basis_exists[of ?U] obtain B\n    where B: \"B \\<subseteq> ?U\" \"independent B\" \"?U \\<subseteq> span B\" \"card B = dim ?U\"\n    by blast\n  from B(4) have d: \"dim ?U = card B\"\n    by simp\n  have th: \"?U \\<subseteq> span (f ` B)\"\n    apply (rule card_ge_dim_independent)\n    apply blast\n    apply (rule independent_injective_image[OF B(2) lf fi])\n    apply (rule order_eq_refl)\n    apply (rule sym)\n    unfolding d\n    apply (rule card_image)\n    apply (rule subset_inj_on[OF fi])\n    apply blast\n    done\n  from th show ?thesis\n    unfolding span_linear_image[OF lf] surj_def\n    using B(3) by blast\nqed\n\ntext {* And vice versa. *}\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        apply (rule card_mono)\n        apply (rule finite_imageI)\n        using fS apply simp\n        using h xy x y f unfolding subset_eq image_iff\n        apply auto\n        apply (case_tac \"xa = f x\")\n        apply (rule bexI[where x=x])\n        apply auto\n        done\n      also have \" \\<dots> \\<le> card (S - {y})\"\n        apply (rule card_image_le)\n        using fS by simp\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    apply (rule card_subset_eq[OF fT ST])\n    unfolding card_image[OF h]\n    apply (rule c)\n    done\n  then show ?lhs by blast\nqed\n\nlemma linear_surjective_imp_injective:\n  fixes f :: \"'a::euclidean_space \\<Rightarrow> 'a::euclidean_space\"\n  assumes lf: \"linear f\"\n    and sf: \"surj f\"\n  shows \"inj f\"\nproof -\n  let ?U = \"UNIV :: 'a set\"\n  from basis_exists[of ?U] obtain B\n    where B: \"B \\<subseteq> ?U\" \"independent B\" \"?U \\<subseteq> span B\" and d: \"card B = dim ?U\"\n    by blast\n  {\n    fix x\n    assume x: \"x \\<in> span B\"\n    assume fx: \"f x = 0\"\n    from B(2) have fB: \"finite B\"\n      using independent_bound by auto\n    have fBi: \"independent (f ` B)\"\n      apply (rule card_le_dim_spanning[of \"f ` B\" ?U])\n      apply blast\n      using sf B(3)\n      unfolding span_linear_image[OF lf] surj_def subset_eq image_iff\n      apply blast\n      using fB apply blast\n      unfolding d[symmetric]\n      apply (rule card_image_le)\n      apply (rule fB)\n      done\n    have th0: \"dim ?U \\<le> card (f ` B)\"\n      apply (rule span_card_ge_dim)\n      apply blast\n      unfolding span_linear_image[OF lf]\n      apply (rule subset_trans[where B = \"f ` UNIV\"])\n      using sf unfolding surj_def\n      apply blast\n      apply (rule image_mono)\n      apply (rule B(3))\n      apply (metis finite_imageI fB)\n      done\n    moreover have \"card (f ` B) \\<le> card B\"\n      by (rule card_image_le, rule fB)\n    ultimately have th1: \"card B = card (f ` B)\"\n      unfolding d by arith\n    have fiB: \"inj_on f B\"\n      unfolding surjective_iff_injective_gen[OF fB finite_imageI[OF fB] th1 subset_refl, symmetric]\n      by blast\n    from linear_indep_image_lemma[OF lf fB fBi fiB x] fx\n    have \"x = 0\" by blast\n  }\n  then show ?thesis\n    unfolding linear_injective_0[OF lf]\n    using B(3)\n    by blast\nqed\n\ntext {* Hence either is enough for isomorphism. *}\n\nlemma left_right_inverse_eq:\n  assumes fg: \"f \\<circ> g = id\"\n    and gh: \"g \\<circ> h = id\"\n  shows \"f = h\"\nproof -\n  have \"f = f \\<circ> (g \\<circ> h)\"\n    unfolding gh by simp\n  also have \"\\<dots> = (f \\<circ> g) \\<circ> h\"\n    by (simp add: o_assoc)\n  finally show \"f = h\"\n    unfolding fg by simp\nqed\n\nlemma isomorphism_expand:\n  \"f \\<circ> g = id \\<and> g \\<circ> f = id \\<longleftrightarrow> (\\<forall>x. f (g x) = x) \\<and> (\\<forall>x. g (f x) = x)\"\n  by (simp add: fun_eq_iff o_def id_def)\n\nlemma linear_injective_isomorphism:\n  fixes f :: \"'a::euclidean_space \\<Rightarrow> 'a::euclidean_space\"\n  assumes lf: \"linear f\"\n    and fi: \"inj f\"\n  shows \"\\<exists>f'. linear f' \\<and> (\\<forall>x. f' (f x) = x) \\<and> (\\<forall>x. f (f' x) = x)\"\n  unfolding isomorphism_expand[symmetric]\n  using linear_surjective_right_inverse[OF lf linear_injective_imp_surjective[OF lf fi]]\n    linear_injective_left_inverse[OF lf fi]\n  by (metis left_right_inverse_eq)\n\nlemma linear_surjective_isomorphism:\n  fixes f :: \"'a::euclidean_space \\<Rightarrow> 'a::euclidean_space\"\n  assumes lf: \"linear f\"\n    and sf: \"surj f\"\n  shows \"\\<exists>f'. linear f' \\<and> (\\<forall>x. f' (f x) = x) \\<and> (\\<forall>x. f (f' x) = x)\"\n  unfolding isomorphism_expand[symmetric]\n  using linear_surjective_right_inverse[OF lf sf]\n    linear_injective_left_inverse[OF lf linear_surjective_imp_injective[OF lf sf]]\n  by (metis left_right_inverse_eq)\n\ntext {* Left and right inverses are the same for\n  @{typ \"'a::euclidean_space \\<Rightarrow> 'a::euclidean_space\"}. *}\n\nlemma linear_inverse_left:\n  fixes f :: \"'a::euclidean_space \\<Rightarrow> 'a::euclidean_space\"\n  assumes lf: \"linear f\"\n    and lf': \"linear f'\"\n  shows \"f \\<circ> f' = id \\<longleftrightarrow> f' \\<circ> f = id\"\nproof -\n  {\n    fix f f':: \"'a \\<Rightarrow> 'a\"\n    assume lf: \"linear f\" \"linear f'\"\n    assume f: \"f \\<circ> f' = id\"\n    from f have sf: \"surj f\"\n      apply (auto simp add: o_def id_def surj_def)\n      apply metis\n      done\n    from linear_surjective_isomorphism[OF lf(1) sf] lf f\n    have \"f' \\<circ> f = id\"\n      unfolding fun_eq_iff o_def id_def by metis\n  }\n  then show ?thesis\n    using lf lf' by metis\nqed\n\ntext {* Moreover, a one-sided inverse is automatically linear. *}\n\nlemma left_inverse_linear:\n  fixes f :: \"'a::euclidean_space \\<Rightarrow> 'a::euclidean_space\"\n  assumes lf: \"linear f\"\n    and gf: \"g \\<circ> f = id\"\n  shows \"linear g\"\nproof -\n  from gf have fi: \"inj f\"\n    apply (auto simp add: inj_on_def o_def id_def fun_eq_iff)\n    apply metis\n    done\n  from linear_injective_isomorphism[OF lf fi]\n  obtain h :: \"'a \\<Rightarrow> 'a\" where h: \"linear h\" \"\\<forall>x. h (f x) = x\" \"\\<forall>x. f (h x) = x\"\n    by blast\n  have \"h = g\"\n    apply (rule ext) using gf h(2,3)\n    apply (simp add: o_def id_def fun_eq_iff)\n    apply metis\n    done\n  with h(1) show ?thesis by blast\nqed\n\n\nsubsection {* Infinity norm *}\n\ndefinition \"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 del: Sup_image_eq)\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\n  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\n  apply (rule cong[of \"Sup\" \"Sup\"])\n  apply blast\n  apply auto\n  done\n\nlemma infnorm_sub: \"infnorm (x - y) = infnorm (y - x)\"\nproof -\n  have \"y - x = - (x - y)\" by simp\n  then show ?thesis\n    by (metis infnorm_neg)\nqed\n\nlemma real_abs_sub_infnorm: \"\\<bar>infnorm x - infnorm y\\<bar> \\<le> infnorm (x - y)\"\nproof -\n  have th: \"\\<And>(nx::real) n ny. nx \\<le> n + ny \\<Longrightarrow> ny \\<le> n + nx \\<Longrightarrow> \\<bar>nx - ny\\<bar> \\<le> n\"\n    by arith\n  from infnorm_triangle[of \"x - y\" \" y\"] infnorm_triangle[of \"x - y\" \"-x\"]\n  have ths: \"infnorm x \\<le> infnorm (x - y) + infnorm y\"\n    \"infnorm y \\<le> infnorm (x - y) + infnorm x\"\n    by (simp_all add: field_simps infnorm_neg)\n  from th[OF ths] show ?thesis .\nqed\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  {\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 {* Prove that it differs only up to a bound from Euclidean norm. *}\n\nlemma infnorm_le_norm: \"infnorm x \\<le> norm x\"\n  by (simp add: Basis_le_norm infnorm_Max)\n\nlemma (in euclidean_space) euclidean_inner: \"inner x y = (\\<Sum>b\\<in>Basis. (x \\<bullet> b) * (y \\<bullet> b))\"\n  by (subst (1 2) euclidean_representation [symmetric])\n    (simp add: inner_setsum_right inner_Basis ac_simps)\n\nlemma norm_le_infnorm:\n  fixes x :: \"'a::euclidean_space\"\n  shows \"norm x \\<le> sqrt DIM('a) * infnorm x\"\nproof -\n  let ?d = \"DIM('a)\"\n  have \"real ?d \\<ge> 0\"\n    by simp\n  then have d2: \"(sqrt (real ?d))\\<^sup>2 = real ?d\"\n    by (auto intro: real_sqrt_pow2)\n  have th: \"sqrt (real ?d) * infnorm x \\<ge> 0\"\n    by (simp add: zero_le_mult_iff infnorm_pos_le)\n  have th1: \"x \\<bullet> x \\<le> (sqrt (real ?d) * infnorm x)\\<^sup>2\"\n    unfolding power_mult_distrib d2\n    unfolding real_of_nat_def\n    apply (subst euclidean_inner)\n    apply (subst power2_abs[symmetric])\n    apply (rule order_trans[OF setsum_bounded[where K=\"\\<bar>infnorm x\\<bar>\\<^sup>2\"]])\n    apply (auto simp add: power2_eq_square[symmetric])\n    apply (subst power2_abs[symmetric])\n    apply (rule power_mono)\n    apply (auto simp: infnorm_Max)\n    done\n  from real_le_lsqrt[OF inner_ge_zero th th1]\n  show ?thesis\n    unfolding norm_eq_sqrt_inner id_def .\nqed\n\nlemma tendsto_infnorm [tendsto_intros]:\n  assumes \"(f ---> a) F\"\n  shows \"((\\<lambda>x. infnorm (f x)) ---> 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 real_abs_sub_infnorm infnorm_le_norm)\nqed\n\ntext {* Equality in Cauchy-Schwarz and triangle inequalities. *}\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 -\n  {\n    assume h: \"x = 0\"\n    then have ?thesis by simp\n  }\n  moreover\n  {\n    assume h: \"y = 0\"\n    then have ?thesis by simp\n  }\n  moreover\n  {\n    assume x: \"x \\<noteq> 0\" and y: \"y \\<noteq> 0\"\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 x y\n      unfolding inner_simps\n      unfolding power2_norm_eq_inner[symmetric] power2_eq_square right_minus_eq\n      apply (simp add: inner_commute)\n      apply (simp add: field_simps)\n      apply metis\n      done\n    also have \"\\<dots> \\<longleftrightarrow> (2 * norm x * norm y * (norm x * norm y - x \\<bullet> y) = 0)\" using x y\n      by (simp add: field_simps inner_commute)\n    also have \"\\<dots> \\<longleftrightarrow> ?lhs\" using x y\n      apply simp\n      apply metis\n      done\n    finally have ?thesis by blast\n  }\n  ultimately show ?thesis by blast\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  (is \"?lhs \\<longleftrightarrow> ?rhs\")\nproof -\n  have th: \"\\<And>(x::real) a. a \\<ge> 0 \\<Longrightarrow> \\<bar>x\\<bar> = a \\<longleftrightarrow> x = a \\<or> x = - a\"\n    by arith\n  have \"?rhs \\<longleftrightarrow> norm x *\\<^sub>R y = norm y *\\<^sub>R x \\<or> norm (- x) *\\<^sub>R y = norm y *\\<^sub>R (- x)\"\n    by simp\n  also have \"\\<dots> \\<longleftrightarrow>(x \\<bullet> y = norm x * norm y \\<or> (- x) \\<bullet> y = norm x * norm y)\"\n    unfolding norm_cauchy_schwarz_eq[symmetric]\n    unfolding norm_minus_cancel norm_scaleR ..\n  also have \"\\<dots> \\<longleftrightarrow> ?lhs\"\n    unfolding th[OF mult_nonneg_nonneg, OF norm_ge_zero[of x] norm_ge_zero[of y]] inner_simps\n    by auto\n  finally show ?thesis ..\nqed\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 -\n  {\n    assume x: \"x = 0 \\<or> y = 0\"\n    then have ?thesis\n      by (cases \"x = 0\") simp_all\n  }\n  moreover\n  {\n    assume x: \"x \\<noteq> 0\" and y: \"y \\<noteq> 0\"\n    then have \"norm x \\<noteq> 0\" \"norm y \\<noteq> 0\"\n      by simp_all\n    then have n: \"norm x > 0\" \"norm y > 0\"\n      using norm_ge_zero[of x] norm_ge_zero[of y] by arith+\n    have th: \"\\<And>(a::real) b c. a + b + c \\<noteq> 0 \\<Longrightarrow> a = b + c \\<longleftrightarrow> a\\<^sup>2 = (b + c)\\<^sup>2\"\n      by algebra\n    have \"norm (x + y) = norm x + norm y \\<longleftrightarrow> (norm (x + y))\\<^sup>2 = (norm x + norm y)\\<^sup>2\"\n      apply (rule th)\n      using n norm_ge_zero[of \"x + y\"]\n      apply arith\n      done\n    also have \"\\<dots> \\<longleftrightarrow> norm x *\\<^sub>R y = norm y *\\<^sub>R x\"\n      unfolding norm_cauchy_schwarz_eq[symmetric]\n      unfolding power2_norm_eq_inner inner_simps\n      by (simp add: power2_norm_eq_inner[symmetric] power2_eq_square inner_commute field_simps)\n    finally have ?thesis .\n  }\n  ultimately show ?thesis by blast\nqed\n\n\nsubsection {* Collinearity *}\n\ndefinition 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_empty: \"collinear {}\"\n  by (simp add: collinear_def)\n\nlemma collinear_sing: \"collinear {x}\"\n  by (simp add: collinear_def)\n\nlemma collinear_2: \"collinear {x, y}\"\n  apply (simp add: collinear_def)\n  apply (rule exI[where x=\"x - y\"])\n  apply auto\n  apply (rule exI[where x=1], simp)\n  apply (rule exI[where x=\"- 1\"], simp)\n  done\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 -\n  {\n    assume \"x = 0 \\<or> y = 0\"\n    then have ?thesis\n      by (cases \"x = 0\") (simp_all add: collinear_2 insert_commute)\n  }\n  moreover\n  {\n    assume x: \"x \\<noteq> 0\" and y: \"y \\<noteq> 0\"\n    have ?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 x have cx0: \"cx \\<noteq> 0\" by auto\n      from cy y have 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 x y by blast\n    next\n      assume h: \"?rhs\"\n      then obtain c where c: \"y = c *\\<^sub>R x\"\n        using x y by blast\n      show ?lhs\n        unfolding collinear_def c\n        apply (rule exI[where x=x])\n        apply auto\n        apply (rule exI[where x=\"- 1\"], simp)\n        apply (rule exI[where x= \"-c\"], simp)\n        apply (rule exI[where x=1], simp)\n        apply (rule exI[where x=\"1 - c\"], simp add: scaleR_left_diff_distrib)\n        apply (rule exI[where x=\"c - 1\"], simp add: scaleR_left_diff_distrib)\n        done\n    qed\n  }\n  ultimately show ?thesis by blast\nqed\n\nlemma norm_cauchy_schwarz_equal: \"\\<bar>x \\<bullet> y\\<bar> = norm x * norm y \\<longleftrightarrow> collinear {0, x, y}\"\n  unfolding norm_cauchy_schwarz_abs_eq\n  apply (cases \"x=0\", simp_all add: collinear_2)\n  apply (cases \"y=0\", simp_all add: collinear_2 insert_commute)\n  unfolding collinear_lemma\n  apply simp\n  apply (subgoal_tac \"norm x \\<noteq> 0\")\n  apply (subgoal_tac \"norm y \\<noteq> 0\")\n  apply (rule iffI)\n  apply (cases \"norm x *\\<^sub>R y = norm y *\\<^sub>R x\")\n  apply (rule exI[where x=\"(1/norm x) * norm y\"])\n  apply (drule sym)\n  unfolding scaleR_scaleR[symmetric]\n  apply (simp add: field_simps)\n  apply (rule exI[where x=\"(1/norm x) * - norm y\"])\n  apply clarify\n  apply (drule sym)\n  unfolding scaleR_scaleR[symmetric]\n  apply (simp add: field_simps)\n  apply (erule exE)\n  apply (erule ssubst)\n  unfolding scaleR_scaleR\n  unfolding norm_scaleR\n  apply (subgoal_tac \"norm x * c = \\<bar>c\\<bar> * norm x \\<or> norm x * c = - \\<bar>c\\<bar> * norm x\")\n  apply (auto simp add: field_simps)\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/HOL/Multivariate_Analysis/Linear_Algebra.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8438951064805861, "lm_q2_score": 0.8438951084436077, "lm_q1q2_score": 0.712158952398464}}
{"text": "(*  Title:      HOL/ex/ThreeDivides.thy\n    Author:     Benjamin Porter, 2005\n*)\n\nsection \\<open>Three Divides Theorem\\<close>\n\ntheory ThreeDivides\nimports MainRLT \"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>\\<open>D i\\<close> 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>\\<open>D :: (nat\\<Rightarrow>nat)\\<close>),\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>\\<open>(\\<Sum>x<nd. D x * 10^x) - (\\<Sum>x<nd. D x)\\<close>\\<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.atLeast_Suc_lessThan 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": "dtraytel", "repo": "HOLRLT", "sha": "e9029da59bb3af0c835604a65308498f9696a364", "save_path": "github-repos/isabelle/dtraytel-HOLRLT", "path": "github-repos/isabelle/dtraytel-HOLRLT/HOLRLT-e9029da59bb3af0c835604a65308498f9696a364/HOLRLT/ex/ThreeDivides.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951025545427, "lm_q2_score": 0.843895106480586, "lm_q1q2_score": 0.7121589474287108}}
{"text": "(*  Title:      HOL/Topological_Spaces.thy\n    Author:     Brian Huffman\n    Author:     Johannes H\u00f6lzl\n*)\n\nsection \\<open>Topological Spaces\\<close>\n\ntheory Topological_Spaces\n  imports MainRLT\nbegin\n\nnamed_theorems continuous_intros \"structural introduction rules for continuity\"\n\nsubsection \\<open>Topological space\\<close>\n\nclass \"open\" =\n  fixes \"open\" :: \"'a set \\<Rightarrow> bool\"\n\nclass topological_space = \"open\" +\n  assumes open_UNIV [simp, intro]: \"open UNIV\"\n  assumes open_Int [intro]: \"open S \\<Longrightarrow> open T \\<Longrightarrow> open (S \\<inter> T)\"\n  assumes open_Union [intro]: \"\\<forall>S\\<in>K. open S \\<Longrightarrow> open (\\<Union>K)\"\nbegin\n\ndefinition closed :: \"'a set \\<Rightarrow> bool\"\n  where \"closed S \\<longleftrightarrow> open (- S)\"\n\nlemma open_empty [continuous_intros, intro, simp]: \"open {}\"\n  using open_Union [of \"{}\"] by simp\n\nlemma open_Un [continuous_intros, intro]: \"open S \\<Longrightarrow> open T \\<Longrightarrow> open (S \\<union> T)\"\n  using open_Union [of \"{S, T}\"] by simp\n\nlemma open_UN [continuous_intros, intro]: \"\\<forall>x\\<in>A. open (B x) \\<Longrightarrow> open (\\<Union>x\\<in>A. B x)\"\n  using open_Union [of \"B ` A\"] by simp\n\nlemma open_Inter [continuous_intros, intro]: \"finite S \\<Longrightarrow> \\<forall>T\\<in>S. open T \\<Longrightarrow> open (\\<Inter>S)\"\n  by (induction set: finite) auto\n\nlemma open_INT [continuous_intros, intro]: \"finite A \\<Longrightarrow> \\<forall>x\\<in>A. open (B x) \\<Longrightarrow> open (\\<Inter>x\\<in>A. B x)\"\n  using open_Inter [of \"B ` A\"] by simp\n\nlemma openI:\n  assumes \"\\<And>x. x \\<in> S \\<Longrightarrow> \\<exists>T. open T \\<and> x \\<in> T \\<and> T \\<subseteq> S\"\n  shows \"open S\"\nproof -\n  have \"open (\\<Union>{T. open T \\<and> T \\<subseteq> S})\" by auto\n  moreover have \"\\<Union>{T. open T \\<and> T \\<subseteq> S} = S\" by (auto dest!: assms)\n  ultimately show \"open S\" by simp\nqed\n\nlemma open_subopen: \"open S \\<longleftrightarrow> (\\<forall>x\\<in>S. \\<exists>T. open T \\<and> x \\<in> T \\<and> T \\<subseteq> S)\"\nby (auto intro: openI)\n\nlemma closed_empty [continuous_intros, intro, simp]: \"closed {}\"\n  unfolding closed_def by simp\n\nlemma closed_Un [continuous_intros, intro]: \"closed S \\<Longrightarrow> closed T \\<Longrightarrow> closed (S \\<union> T)\"\n  unfolding closed_def by auto\n\nlemma closed_UNIV [continuous_intros, intro, simp]: \"closed UNIV\"\n  unfolding closed_def by simp\n\nlemma closed_Int [continuous_intros, intro]: \"closed S \\<Longrightarrow> closed T \\<Longrightarrow> closed (S \\<inter> T)\"\n  unfolding closed_def by auto\n\nlemma closed_INT [continuous_intros, intro]: \"\\<forall>x\\<in>A. closed (B x) \\<Longrightarrow> closed (\\<Inter>x\\<in>A. B x)\"\n  unfolding closed_def by auto\n\nlemma closed_Inter [continuous_intros, intro]: \"\\<forall>S\\<in>K. closed S \\<Longrightarrow> closed (\\<Inter>K)\"\n  unfolding closed_def uminus_Inf by auto\n\nlemma closed_Union [continuous_intros, intro]: \"finite S \\<Longrightarrow> \\<forall>T\\<in>S. closed T \\<Longrightarrow> closed (\\<Union>S)\"\n  by (induct set: finite) auto\n\nlemma closed_UN [continuous_intros, intro]:\n  \"finite A \\<Longrightarrow> \\<forall>x\\<in>A. closed (B x) \\<Longrightarrow> closed (\\<Union>x\\<in>A. B x)\"\n  using closed_Union [of \"B ` A\"] by simp\n\nlemma open_closed: \"open S \\<longleftrightarrow> closed (- S)\"\n  by (simp add: closed_def)\n\nlemma closed_open: \"closed S \\<longleftrightarrow> open (- S)\"\n  by (rule closed_def)\n\nlemma open_Diff [continuous_intros, intro]: \"open S \\<Longrightarrow> closed T \\<Longrightarrow> open (S - T)\"\n  by (simp add: closed_open Diff_eq open_Int)\n\nlemma closed_Diff [continuous_intros, intro]: \"closed S \\<Longrightarrow> open T \\<Longrightarrow> closed (S - T)\"\n  by (simp add: open_closed Diff_eq closed_Int)\n\nlemma open_Compl [continuous_intros, intro]: \"closed S \\<Longrightarrow> open (- S)\"\n  by (simp add: closed_open)\n\nlemma closed_Compl [continuous_intros, intro]: \"open S \\<Longrightarrow> closed (- S)\"\n  by (simp add: open_closed)\n\nlemma open_Collect_neg: \"closed {x. P x} \\<Longrightarrow> open {x. \\<not> P x}\"\n  unfolding Collect_neg_eq by (rule open_Compl)\n\nlemma open_Collect_conj:\n  assumes \"open {x. P x}\" \"open {x. Q x}\"\n  shows \"open {x. P x \\<and> Q x}\"\n  using open_Int[OF assms] by (simp add: Int_def)\n\nlemma open_Collect_disj:\n  assumes \"open {x. P x}\" \"open {x. Q x}\"\n  shows \"open {x. P x \\<or> Q x}\"\n  using open_Un[OF assms] by (simp add: Un_def)\n\nlemma open_Collect_ex: \"(\\<And>i. open {x. P i x}) \\<Longrightarrow> open {x. \\<exists>i. P i x}\"\n  using open_UN[of UNIV \"\\<lambda>i. {x. P i x}\"] unfolding Collect_ex_eq by simp\n\nlemma open_Collect_imp: \"closed {x. P x} \\<Longrightarrow> open {x. Q x} \\<Longrightarrow> open {x. P x \\<longrightarrow> Q x}\"\n  unfolding imp_conv_disj by (intro open_Collect_disj open_Collect_neg)\n\nlemma open_Collect_const: \"open {x. P}\"\n  by (cases P) auto\n\nlemma closed_Collect_neg: \"open {x. P x} \\<Longrightarrow> closed {x. \\<not> P x}\"\n  unfolding Collect_neg_eq by (rule closed_Compl)\n\nlemma closed_Collect_conj:\n  assumes \"closed {x. P x}\" \"closed {x. Q x}\"\n  shows \"closed {x. P x \\<and> Q x}\"\n  using closed_Int[OF assms] by (simp add: Int_def)\n\nlemma closed_Collect_disj:\n  assumes \"closed {x. P x}\" \"closed {x. Q x}\"\n  shows \"closed {x. P x \\<or> Q x}\"\n  using closed_Un[OF assms] by (simp add: Un_def)\n\nlemma closed_Collect_all: \"(\\<And>i. closed {x. P i x}) \\<Longrightarrow> closed {x. \\<forall>i. P i x}\"\n  using closed_INT[of UNIV \"\\<lambda>i. {x. P i x}\"] by (simp add: Collect_all_eq)\n\nlemma closed_Collect_imp: \"open {x. P x} \\<Longrightarrow> closed {x. Q x} \\<Longrightarrow> closed {x. P x \\<longrightarrow> Q x}\"\n  unfolding imp_conv_disj by (intro closed_Collect_disj closed_Collect_neg)\n\nlemma closed_Collect_const: \"closed {x. P}\"\n  by (cases P) auto\n\nend\n\n\nsubsection \\<open>Hausdorff and other separation properties\\<close>\n\nclass t0_space = topological_space +\n  assumes t0_space: \"x \\<noteq> y \\<Longrightarrow> \\<exists>U. open U \\<and> \\<not> (x \\<in> U \\<longleftrightarrow> y \\<in> U)\"\n\nclass t1_space = topological_space +\n  assumes t1_space: \"x \\<noteq> y \\<Longrightarrow> \\<exists>U. open U \\<and> x \\<in> U \\<and> y \\<notin> U\"\n\ninstance t1_space \\<subseteq> t0_space\n  by standard (fast dest: t1_space)\n\ncontext t1_space begin\n\nlemma separation_t1: \"x \\<noteq> y \\<longleftrightarrow> (\\<exists>U. open U \\<and> x \\<in> U \\<and> y \\<notin> U)\"\n  using t1_space[of x y] by blast\n\nlemma closed_singleton [iff]: \"closed {a}\"\nproof -\n  let ?T = \"\\<Union>{S. open S \\<and> a \\<notin> S}\"\n  have \"open ?T\"\n    by (simp add: open_Union)\n  also have \"?T = - {a}\"\n    by (auto simp add: set_eq_iff separation_t1)\n  finally show \"closed {a}\"\n    by (simp only: closed_def)\nqed\n\nlemma closed_insert [continuous_intros, simp]:\n  assumes \"closed S\"\n  shows \"closed (insert a S)\"\nproof -\n  from closed_singleton assms have \"closed ({a} \\<union> S)\"\n    by (rule closed_Un)\n  then show \"closed (insert a S)\"\n    by simp\nqed\n\nlemma finite_imp_closed: \"finite S \\<Longrightarrow> closed S\"\n  by (induct pred: finite) simp_all\n\nend\n\ntext \\<open>T2 spaces are also known as Hausdorff spaces.\\<close>\n\nclass t2_space = topological_space +\n  assumes hausdorff: \"x \\<noteq> y \\<Longrightarrow> \\<exists>U V. open U \\<and> open V \\<and> x \\<in> U \\<and> y \\<in> V \\<and> U \\<inter> V = {}\"\n\ninstance t2_space \\<subseteq> t1_space\n  by standard (fast dest: hausdorff)\n\nlemma (in t2_space) separation_t2: \"x \\<noteq> y \\<longleftrightarrow> (\\<exists>U V. open U \\<and> open V \\<and> x \\<in> U \\<and> y \\<in> V \\<and> U \\<inter> V = {})\"\n  using hausdorff [of x y] by blast\n\nlemma (in t0_space) separation_t0: \"x \\<noteq> y \\<longleftrightarrow> (\\<exists>U. open U \\<and> \\<not> (x \\<in> U \\<longleftrightarrow> y \\<in> U))\"\n  using t0_space [of x y] by blast\n\n\ntext \\<open>A classical separation axiom for topological space, the T3 axiom -- also called regularity:\nif a point is not in a closed set, then there are open sets separating them.\\<close>\n\nclass t3_space = t2_space +\n  assumes t3_space: \"closed S \\<Longrightarrow> y \\<notin> S \\<Longrightarrow> \\<exists>U V. open U \\<and> open V \\<and> y \\<in> U \\<and> S \\<subseteq> V \\<and> U \\<inter> V = {}\"\n\ntext \\<open>A classical separation axiom for topological space, the T4 axiom -- also called normality:\nif two closed sets are disjoint, then there are open sets separating them.\\<close>\n\nclass t4_space = t2_space +\n  assumes t4_space: \"closed S \\<Longrightarrow> closed T \\<Longrightarrow> S \\<inter> T = {} \\<Longrightarrow> \\<exists>U V. open U \\<and> open V \\<and> S \\<subseteq> U \\<and> T \\<subseteq> V \\<and> U \\<inter> V = {}\"\n\ntext \\<open>T4 is stronger than T3, and weaker than metric.\\<close>\n\ninstance t4_space \\<subseteq> t3_space\nproof\n  fix S and y::'a assume \"closed S\" \"y \\<notin> S\"\n  then show \"\\<exists>U V. open U \\<and> open V \\<and> y \\<in> U \\<and> S \\<subseteq> V \\<and> U \\<inter> V = {}\"\n    using t4_space[of \"{y}\" S] by auto\nqed\n\ntext \\<open>A perfect space is a topological space with no isolated points.\\<close>\n\nclass perfect_space = topological_space +\n  assumes not_open_singleton: \"\\<not> open {x}\"\n\nlemma (in perfect_space) UNIV_not_singleton: \"UNIV \\<noteq> {x}\"\n  for x::'a\n  by (metis (no_types) open_UNIV not_open_singleton)\n\n\nsubsection \\<open>Generators for toplogies\\<close>\n\ninductive generate_topology :: \"'a set set \\<Rightarrow> 'a set \\<Rightarrow> bool\" for S :: \"'a set set\"\n  where\n    UNIV: \"generate_topology S UNIV\"\n  | Int: \"generate_topology S (a \\<inter> b)\" if \"generate_topology S a\" and \"generate_topology S b\"\n  | UN: \"generate_topology S (\\<Union>K)\" if \"(\\<And>k. k \\<in> K \\<Longrightarrow> generate_topology S k)\"\n  | Basis: \"generate_topology S s\" if \"s \\<in> S\"\n\nhide_fact (open) UNIV Int UN Basis\n\nlemma generate_topology_Union:\n  \"(\\<And>k. k \\<in> I \\<Longrightarrow> generate_topology S (K k)) \\<Longrightarrow> generate_topology S (\\<Union>k\\<in>I. K k)\"\n  using generate_topology.UN [of \"K ` I\"] by auto\n\nlemma topological_space_generate_topology: \"class.topological_space (generate_topology S)\"\n  by standard (auto intro: generate_topology.intros)\n\n\nsubsection \\<open>Order topologies\\<close>\n\nclass order_topology = order + \"open\" +\n  assumes open_generated_order: \"open = generate_topology (range (\\<lambda>a. {..< a}) \\<union> range (\\<lambda>a. {a <..}))\"\nbegin\n\nsubclass topological_space\n  unfolding open_generated_order\n  by (rule topological_space_generate_topology)\n\nlemma open_greaterThan [continuous_intros, simp]: \"open {a <..}\"\n  unfolding open_generated_order by (auto intro: generate_topology.Basis)\n\nlemma open_lessThan [continuous_intros, simp]: \"open {..< a}\"\n  unfolding open_generated_order by (auto intro: generate_topology.Basis)\n\nlemma open_greaterThanLessThan [continuous_intros, simp]: \"open {a <..< b}\"\n   unfolding greaterThanLessThan_eq by (simp add: open_Int)\n\nend\n\nclass linorder_topology = linorder + order_topology\n\nlemma closed_atMost [continuous_intros, simp]: \"closed {..a}\"\n  for a :: \"'a::linorder_topology\"\n  by (simp add: closed_open)\n\nlemma closed_atLeast [continuous_intros, simp]: \"closed {a..}\"\n  for a :: \"'a::linorder_topology\"\n  by (simp add: closed_open)\n\nlemma closed_atLeastAtMost [continuous_intros, simp]: \"closed {a..b}\"\n  for a b :: \"'a::linorder_topology\"\nproof -\n  have \"{a .. b} = {a ..} \\<inter> {.. b}\"\n    by auto\n  then show ?thesis\n    by (simp add: closed_Int)\nqed\n\nlemma (in order) less_separate:\n  assumes \"x < y\"\n  shows \"\\<exists>a b. x \\<in> {..< a} \\<and> y \\<in> {b <..} \\<and> {..< a} \\<inter> {b <..} = {}\"\nproof (cases \"\\<exists>z. x < z \\<and> z < y\")\n  case True\n  then obtain z where \"x < z \\<and> z < y\" ..\n  then have \"x \\<in> {..< z} \\<and> y \\<in> {z <..} \\<and> {z <..} \\<inter> {..< z} = {}\"\n    by auto\n  then show ?thesis by blast\nnext\n  case False\n  with \\<open>x < y\\<close> have \"x \\<in> {..< y}\" \"y \\<in> {x <..}\" \"{x <..} \\<inter> {..< y} = {}\"\n    by auto\n  then show ?thesis by blast\nqed\n\ninstance linorder_topology \\<subseteq> t2_space\nproof\n  fix x y :: 'a\n  show \"x \\<noteq> y \\<Longrightarrow> \\<exists>U V. open U \\<and> open V \\<and> x \\<in> U \\<and> y \\<in> V \\<and> U \\<inter> V = {}\"\n    using less_separate [of x y] less_separate [of y x]\n    by (elim neqE; metis open_lessThan open_greaterThan Int_commute)\nqed\n\nlemma (in linorder_topology) open_right:\n  assumes \"open S\" \"x \\<in> S\"\n    and gt_ex: \"x < y\"\n  shows \"\\<exists>b>x. {x ..< b} \\<subseteq> S\"\n  using assms unfolding open_generated_order\nproof induct\n  case UNIV\n  then show ?case by blast\nnext\n  case (Int A B)\n  then obtain a b where \"a > x\" \"{x ..< a} \\<subseteq> A\"  \"b > x\" \"{x ..< b} \\<subseteq> B\"\n    by auto\n  then show ?case\n    by (auto intro!: exI[of _ \"min a b\"])\nnext\n  case UN\n  then show ?case by blast\nnext\n  case Basis\n  then show ?case\n    by (fastforce intro: exI[of _ y] gt_ex)\nqed\n\nlemma (in linorder_topology) open_left:\n  assumes \"open S\" \"x \\<in> S\"\n    and lt_ex: \"y < x\"\n  shows \"\\<exists>b<x. {b <.. x} \\<subseteq> S\"\n  using assms unfolding open_generated_order\nproof induction\n  case UNIV\n  then show ?case by blast\nnext\n  case (Int A B)\n  then obtain a b where \"a < x\" \"{a <.. x} \\<subseteq> A\"  \"b < x\" \"{b <.. x} \\<subseteq> B\"\n    by auto\n  then show ?case\n    by (auto intro!: exI[of _ \"max a b\"])\nnext\n  case UN\n  then show ?case by blast\nnext\n  case Basis\n  then show ?case\n    by (fastforce intro: exI[of _ y] lt_ex)\nqed\n\n\nsubsection \\<open>Setup some topologies\\<close>\n\nsubsubsection \\<open>Boolean is an order topology\\<close>\n\nclass discrete_topology = topological_space +\n  assumes open_discrete: \"\\<And>A. open A\"\n\ninstance discrete_topology < t2_space\nproof\n  fix x y :: 'a\n  assume \"x \\<noteq> y\"\n  then show \"\\<exists>U V. open U \\<and> open V \\<and> x \\<in> U \\<and> y \\<in> V \\<and> U \\<inter> V = {}\"\n    by (intro exI[of _ \"{_}\"]) (auto intro!: open_discrete)\nqed\n\ninstantiation bool :: linorder_topology\nbegin\n\ndefinition open_bool :: \"bool set \\<Rightarrow> bool\"\n  where \"open_bool = generate_topology (range (\\<lambda>a. {..< a}) \\<union> range (\\<lambda>a. {a <..}))\"\n\ninstance\n  by standard (rule open_bool_def)\n\nend\n\ninstance bool :: discrete_topology\nproof\n  fix A :: \"bool set\"\n  have *: \"{False <..} = {True}\" \"{..< True} = {False}\"\n    by auto\n  have \"A = UNIV \\<or> A = {} \\<or> A = {False <..} \\<or> A = {..< True}\"\n    using subset_UNIV[of A] unfolding UNIV_bool * by blast\n  then show \"open A\"\n    by auto\nqed\n\ninstantiation nat :: linorder_topology\nbegin\n\ndefinition open_nat :: \"nat set \\<Rightarrow> bool\"\n  where \"open_nat = generate_topology (range (\\<lambda>a. {..< a}) \\<union> range (\\<lambda>a. {a <..}))\"\n\ninstance\n  by standard (rule open_nat_def)\n\nend\n\ninstance nat :: discrete_topology\nproof\n  fix A :: \"nat set\"\n  have \"open {n}\" for n :: nat\n  proof (cases n)\n    case 0\n    moreover have \"{0} = {..<1::nat}\"\n      by auto\n    ultimately show ?thesis\n       by auto\n  next\n    case (Suc n')\n    then have \"{n} = {..<Suc n} \\<inter> {n' <..}\"\n      by auto\n    with Suc show ?thesis\n      by (auto intro: open_lessThan open_greaterThan)\n  qed\n  then have \"open (\\<Union>a\\<in>A. {a})\"\n    by (intro open_UN) auto\n  then show \"open A\"\n    by simp\nqed\n\ninstantiation int :: linorder_topology\nbegin\n\ndefinition open_int :: \"int set \\<Rightarrow> bool\"\n  where \"open_int = generate_topology (range (\\<lambda>a. {..< a}) \\<union> range (\\<lambda>a. {a <..}))\"\n\ninstance\n  by standard (rule open_int_def)\n\nend\n\ninstance int :: discrete_topology\nproof\n  fix A :: \"int set\"\n  have \"{..<i + 1} \\<inter> {i-1 <..} = {i}\" for i :: int\n    by auto\n  then have \"open {i}\" for i :: int\n    using open_Int[OF open_lessThan[of \"i + 1\"] open_greaterThan[of \"i - 1\"]] by auto\n  then have \"open (\\<Union>a\\<in>A. {a})\"\n    by (intro open_UN) auto\n  then show \"open A\"\n    by simp\nqed\n\n\nsubsubsection \\<open>Topological filters\\<close>\n\ndefinition (in topological_space) nhds :: \"'a \\<Rightarrow> 'a filter\"\n  where \"nhds a = (INF S\\<in>{S. open S \\<and> a \\<in> S}. principal S)\"\n\ndefinition (in topological_space) at_within :: \"'a \\<Rightarrow> 'a set \\<Rightarrow> 'a filter\"\n    (\"at (_)/ within (_)\" [1000, 60] 60)\n  where \"at a within s = inf (nhds a) (principal (s - {a}))\"\n\nabbreviation (in topological_space) at :: \"'a \\<Rightarrow> 'a filter\"  (\"at\")\n  where \"at x \\<equiv> at x within (CONST UNIV)\"\n\nabbreviation (in order_topology) at_right :: \"'a \\<Rightarrow> 'a filter\"\n  where \"at_right x \\<equiv> at x within {x <..}\"\n\nabbreviation (in order_topology) at_left :: \"'a \\<Rightarrow> 'a filter\"\n  where \"at_left x \\<equiv> at x within {..< x}\"\n\nlemma (in topological_space) nhds_generated_topology:\n  \"open = generate_topology T \\<Longrightarrow> nhds x = (INF S\\<in>{S\\<in>T. x \\<in> S}. principal S)\"\n  unfolding nhds_def\nproof (safe intro!: antisym INF_greatest)\n  fix S\n  assume \"generate_topology T S\" \"x \\<in> S\"\n  then show \"(INF S\\<in>{S \\<in> T. x \\<in> S}. principal S) \\<le> principal S\"\n    by induct\n      (auto intro: INF_lower order_trans simp: inf_principal[symmetric] simp del: inf_principal)\nqed (auto intro!: INF_lower intro: generate_topology.intros)\n\nlemma (in topological_space) eventually_nhds:\n  \"eventually P (nhds a) \\<longleftrightarrow> (\\<exists>S. open S \\<and> a \\<in> S \\<and> (\\<forall>x\\<in>S. P x))\"\n  unfolding nhds_def by (subst eventually_INF_base) (auto simp: eventually_principal)\n\nlemma eventually_eventually:\n  \"eventually (\\<lambda>y. eventually P (nhds y)) (nhds x) = eventually P (nhds x)\"\n  by (auto simp: eventually_nhds)\n\nlemma (in topological_space) eventually_nhds_in_open:\n  \"open s \\<Longrightarrow> x \\<in> s \\<Longrightarrow> eventually (\\<lambda>y. y \\<in> s) (nhds x)\"\n  by (subst eventually_nhds) blast\n\nlemma (in topological_space) eventually_nhds_x_imp_x: \"eventually P (nhds x) \\<Longrightarrow> P x\"\n  by (subst (asm) eventually_nhds) blast\n\nlemma (in topological_space) nhds_neq_bot [simp]: \"nhds a \\<noteq> bot\"\n  by (simp add: trivial_limit_def eventually_nhds)\n\nlemma (in t1_space) t1_space_nhds: \"x \\<noteq> y \\<Longrightarrow> (\\<forall>\\<^sub>F x in nhds x. x \\<noteq> y)\"\n  by (drule t1_space) (auto simp: eventually_nhds)\n\nlemma (in topological_space) nhds_discrete_open: \"open {x} \\<Longrightarrow> nhds x = principal {x}\"\n  by (auto simp: nhds_def intro!: antisym INF_greatest INF_lower2[of \"{x}\"])\n\nlemma (in discrete_topology) nhds_discrete: \"nhds x = principal {x}\"\n  by (simp add: nhds_discrete_open open_discrete)\n\nlemma (in discrete_topology) at_discrete: \"at x within S = bot\"\n  unfolding at_within_def nhds_discrete by simp\n\nlemma (in discrete_topology) tendsto_discrete:\n  \"filterlim (f :: 'b \\<Rightarrow> 'a) (nhds y) F \\<longleftrightarrow> eventually (\\<lambda>x. f x = y) F\"\n  by (auto simp: nhds_discrete filterlim_principal)\n\nlemma (in topological_space) at_within_eq:\n  \"at x within s = (INF S\\<in>{S. open S \\<and> x \\<in> S}. principal (S \\<inter> s - {x}))\"\n  unfolding nhds_def at_within_def\n  by (subst INF_inf_const2[symmetric]) (auto simp: Diff_Int_distrib)\n\nlemma (in topological_space) eventually_at_filter:\n  \"eventually P (at a within s) \\<longleftrightarrow> eventually (\\<lambda>x. x \\<noteq> a \\<longrightarrow> x \\<in> s \\<longrightarrow> P x) (nhds a)\"\n  by (simp add: at_within_def eventually_inf_principal imp_conjL[symmetric] conj_commute)\n\nlemma (in topological_space) at_le: \"s \\<subseteq> t \\<Longrightarrow> at x within s \\<le> at x within t\"\n  unfolding at_within_def by (intro inf_mono) auto\n\nlemma (in topological_space) eventually_at_topological:\n  \"eventually P (at a within s) \\<longleftrightarrow> (\\<exists>S. open S \\<and> a \\<in> S \\<and> (\\<forall>x\\<in>S. x \\<noteq> a \\<longrightarrow> x \\<in> s \\<longrightarrow> P x))\"\n  by (simp add: eventually_nhds eventually_at_filter)\n\nlemma (in topological_space) at_within_open: \"a \\<in> S \\<Longrightarrow> open S \\<Longrightarrow> at a within S = at a\"\n  unfolding filter_eq_iff eventually_at_topological by (metis open_Int Int_iff UNIV_I)\n\nlemma (in topological_space) at_within_open_NO_MATCH:\n  \"a \\<in> s \\<Longrightarrow> open s \\<Longrightarrow> NO_MATCH UNIV s \\<Longrightarrow> at a within s = at a\"\n  by (simp only: at_within_open)\n\nlemma (in topological_space) at_within_open_subset:\n  \"a \\<in> S \\<Longrightarrow> open S \\<Longrightarrow> S \\<subseteq> T \\<Longrightarrow> at a within T = at a\"\n  by (metis at_le at_within_open dual_order.antisym subset_UNIV)\n\nlemma (in topological_space) at_within_nhd:\n  assumes \"x \\<in> S\" \"open S\" \"T \\<inter> S - {x} = U \\<inter> S - {x}\"\n  shows \"at x within T = at x within U\"\n  unfolding filter_eq_iff eventually_at_filter\nproof (intro allI eventually_subst)\n  have \"eventually (\\<lambda>x. x \\<in> S) (nhds x)\"\n    using \\<open>x \\<in> S\\<close> \\<open>open S\\<close> by (auto simp: eventually_nhds)\n  then show \"\\<forall>\\<^sub>F n in nhds x. (n \\<noteq> x \\<longrightarrow> n \\<in> T \\<longrightarrow> P n) = (n \\<noteq> x \\<longrightarrow> n \\<in> U \\<longrightarrow> P n)\" for P\n    by eventually_elim (insert \\<open>T \\<inter> S - {x} = U \\<inter> S - {x}\\<close>, blast)\nqed\n\nlemma (in topological_space) at_within_empty [simp]: \"at a within {} = bot\"\n  unfolding at_within_def by simp\n\nlemma (in topological_space) at_within_union:\n  \"at x within (S \\<union> T) = sup (at x within S) (at x within T)\"\n  unfolding filter_eq_iff eventually_sup eventually_at_filter\n  by (auto elim!: eventually_rev_mp)\n\nlemma (in topological_space) at_eq_bot_iff: \"at a = bot \\<longleftrightarrow> open {a}\"\n  unfolding trivial_limit_def eventually_at_topological\n  by (metis UNIV_I empty_iff is_singletonE is_singletonI' singleton_iff)\n\nlemma (in perfect_space) at_neq_bot [simp]: \"at a \\<noteq> bot\"\n  by (simp add: at_eq_bot_iff not_open_singleton)\n\nlemma (in order_topology) nhds_order:\n  \"nhds x = inf (INF a\\<in>{x <..}. principal {..< a}) (INF a\\<in>{..< x}. principal {a <..})\"\nproof -\n  have 1: \"{S \\<in> range lessThan \\<union> range greaterThan. x \\<in> S} =\n      (\\<lambda>a. {..< a}) ` {x <..} \\<union> (\\<lambda>a. {a <..}) ` {..< x}\"\n    by auto\n  show ?thesis\n    by (simp only: nhds_generated_topology[OF open_generated_order] INF_union 1 INF_image comp_def)\nqed\n\nlemma (in topological_space) filterlim_at_within_If:\n  assumes \"filterlim f G (at x within (A \\<inter> {x. P x}))\"\n    and \"filterlim g G (at x within (A \\<inter> {x. \\<not>P x}))\"\n  shows \"filterlim (\\<lambda>x. if P x then f x else g x) G (at x within A)\"\nproof (rule filterlim_If)\n  note assms(1)\n  also have \"at x within (A \\<inter> {x. P x}) = inf (nhds x) (principal (A \\<inter> Collect P - {x}))\"\n    by (simp add: at_within_def)\n  also have \"A \\<inter> Collect P - {x} = (A - {x}) \\<inter> Collect P\"\n    by blast\n  also have \"inf (nhds x) (principal \\<dots>) = inf (at x within A) (principal (Collect P))\"\n    by (simp add: at_within_def inf_assoc)\n  finally show \"filterlim f G (inf (at x within A) (principal (Collect P)))\" .\nnext\n  note assms(2)\n  also have \"at x within (A \\<inter> {x. \\<not> P x}) = inf (nhds x) (principal (A \\<inter> {x. \\<not> P x} - {x}))\"\n    by (simp add: at_within_def)\n  also have \"A \\<inter> {x. \\<not> P x} - {x} = (A - {x}) \\<inter> {x. \\<not> P x}\"\n    by blast\n  also have \"inf (nhds x) (principal \\<dots>) = inf (at x within A) (principal {x. \\<not> P x})\"\n    by (simp add: at_within_def inf_assoc)\n  finally show \"filterlim g G (inf (at x within A) (principal {x. \\<not> P x}))\" .\nqed\n\nlemma (in topological_space) filterlim_at_If:\n  assumes \"filterlim f G (at x within {x. P x})\"\n    and \"filterlim g G (at x within {x. \\<not>P x})\"\n  shows \"filterlim (\\<lambda>x. if P x then f x else g x) G (at x)\"\n  using assms by (intro filterlim_at_within_If) simp_all\nlemma (in linorder_topology) at_within_order:\n  assumes \"UNIV \\<noteq> {x}\"\n  shows \"at x within s =\n    inf (INF a\\<in>{x <..}. principal ({..< a} \\<inter> s - {x}))\n        (INF a\\<in>{..< x}. principal ({a <..} \\<inter> s - {x}))\"\nproof (cases \"{x <..} = {}\" \"{..< x} = {}\" rule: case_split [case_product case_split])\n  case True_True\n  have \"UNIV = {..< x} \\<union> {x} \\<union> {x <..}\"\n    by auto\n  with assms True_True show ?thesis\n    by auto\nqed (auto simp del: inf_principal simp: at_within_def nhds_order Int_Diff\n      inf_principal[symmetric] INF_inf_const2 inf_sup_aci[where 'a=\"'a filter\"])\n\nlemma (in linorder_topology) at_left_eq:\n  \"y < x \\<Longrightarrow> at_left x = (INF a\\<in>{..< x}. principal {a <..< x})\"\n  by (subst at_within_order)\n     (auto simp: greaterThan_Int_greaterThan greaterThanLessThan_eq[symmetric] min.absorb2 INF_constant\n           intro!: INF_lower2 inf_absorb2)\n\nlemma (in linorder_topology) eventually_at_left:\n  \"y < x \\<Longrightarrow> eventually P (at_left x) \\<longleftrightarrow> (\\<exists>b<x. \\<forall>y>b. y < x \\<longrightarrow> P y)\"\n  unfolding at_left_eq\n  by (subst eventually_INF_base) (auto simp: eventually_principal Ball_def)\n\nlemma (in linorder_topology) at_right_eq:\n  \"x < y \\<Longrightarrow> at_right x = (INF a\\<in>{x <..}. principal {x <..< a})\"\n  by (subst at_within_order)\n     (auto simp: lessThan_Int_lessThan greaterThanLessThan_eq[symmetric] max.absorb2 INF_constant Int_commute\n           intro!: INF_lower2 inf_absorb1)\n\nlemma (in linorder_topology) eventually_at_right:\n  \"x < y \\<Longrightarrow> eventually P (at_right x) \\<longleftrightarrow> (\\<exists>b>x. \\<forall>y>x. y < b \\<longrightarrow> P y)\"\n  unfolding at_right_eq\n  by (subst eventually_INF_base) (auto simp: eventually_principal Ball_def)\n\nlemma eventually_at_right_less: \"\\<forall>\\<^sub>F y in at_right (x::'a::{linorder_topology, no_top}). x < y\"\n  using gt_ex[of x] eventually_at_right[of x] by auto\n\nlemma trivial_limit_at_right_top: \"at_right (top::_::{order_top,linorder_topology}) = bot\"\n  by (auto simp: filter_eq_iff eventually_at_topological)\n\nlemma trivial_limit_at_left_bot: \"at_left (bot::_::{order_bot,linorder_topology}) = bot\"\n  by (auto simp: filter_eq_iff eventually_at_topological)\n\nlemma trivial_limit_at_left_real [simp]: \"\\<not> trivial_limit (at_left x)\"\n  for x :: \"'a::{no_bot,dense_order,linorder_topology}\"\n  using lt_ex [of x]\n  by safe (auto simp add: trivial_limit_def eventually_at_left dest: dense)\n\nlemma trivial_limit_at_right_real [simp]: \"\\<not> trivial_limit (at_right x)\"\n  for x :: \"'a::{no_top,dense_order,linorder_topology}\"\n  using gt_ex[of x]\n  by safe (auto simp add: trivial_limit_def eventually_at_right dest: dense)\n\nlemma (in linorder_topology) at_eq_sup_left_right: \"at x = sup (at_left x) (at_right x)\"\n  by (auto simp: eventually_at_filter filter_eq_iff eventually_sup\n      elim: eventually_elim2 eventually_mono)\n\nlemma (in linorder_topology) eventually_at_split:\n  \"eventually P (at x) \\<longleftrightarrow> eventually P (at_left x) \\<and> eventually P (at_right x)\"\n  by (subst at_eq_sup_left_right) (simp add: eventually_sup)\n\nlemma (in order_topology) eventually_at_leftI:\n  assumes \"\\<And>x. x \\<in> {a<..<b} \\<Longrightarrow> P x\" \"a < b\"\n  shows   \"eventually P (at_left b)\"\n  using assms unfolding eventually_at_topological by (intro exI[of _ \"{a<..}\"]) auto\n\nlemma (in order_topology) eventually_at_rightI:\n  assumes \"\\<And>x. x \\<in> {a<..<b} \\<Longrightarrow> P x\" \"a < b\"\n  shows   \"eventually P (at_right a)\"\n  using assms unfolding eventually_at_topological by (intro exI[of _ \"{..<b}\"]) auto\n\nlemma eventually_filtercomap_nhds:\n  \"eventually P (filtercomap f (nhds x)) \\<longleftrightarrow> (\\<exists>S. open S \\<and> x \\<in> S \\<and> (\\<forall>x. f x \\<in> S \\<longrightarrow> P x))\"\n  unfolding eventually_filtercomap eventually_nhds by auto\n\nlemma eventually_filtercomap_at_topological:\n  \"eventually P (filtercomap f (at A within B)) \\<longleftrightarrow> \n     (\\<exists>S. open S \\<and> A \\<in> S \\<and> (\\<forall>x. f x \\<in> S \\<inter> B - {A} \\<longrightarrow> P x))\" (is \"?lhs = ?rhs\")\n  unfolding at_within_def filtercomap_inf eventually_inf_principal filtercomap_principal \n          eventually_filtercomap_nhds eventually_principal by blast\n\nlemma eventually_at_right_field:\n  \"eventually P (at_right x) \\<longleftrightarrow> (\\<exists>b>x. \\<forall>y>x. y < b \\<longrightarrow> P y)\"\n  for x :: \"'a::{linordered_field, linorder_topology}\"\n  using linordered_field_no_ub[rule_format, of x]\n  by (auto simp: eventually_at_right)\n\nlemma eventually_at_left_field:\n  \"eventually P (at_left x) \\<longleftrightarrow> (\\<exists>b<x. \\<forall>y>b. y < x \\<longrightarrow> P y)\"\n  for x :: \"'a::{linordered_field, linorder_topology}\"\n  using linordered_field_no_lb[rule_format, of x]\n  by (auto simp: eventually_at_left)\n\n\nsubsubsection \\<open>Tendsto\\<close>\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\nlemma (in topological_space) tendsto_eq_rhs: \"(f \\<longlongrightarrow> x) F \\<Longrightarrow> x = y \\<Longrightarrow> (f \\<longlongrightarrow> y) F\"\n  by simp\n\nnamed_theorems tendsto_intros \"introduction rules for tendsto\"\nsetup \\<open>\n  Global_Theory.add_thms_dynamic (\\<^binding>\\<open>tendsto_eq_intros\\<close>,\n    fn context =>\n      Named_Theorems.get (Context.proof_of context) \\<^named_theorems>\\<open>tendsto_intros\\<close>\n      |> map_filter (try (fn thm => @{thm tendsto_eq_rhs} OF [thm])))\n\\<close>\n\ncontext topological_space begin\n\nlemma tendsto_def:\n   \"(f \\<longlongrightarrow> l) F \\<longleftrightarrow> (\\<forall>S. open S \\<longrightarrow> l \\<in> S \\<longrightarrow> eventually (\\<lambda>x. f x \\<in> S) F)\"\n   unfolding nhds_def filterlim_INF filterlim_principal by auto\n\nlemma tendsto_cong: \"(f \\<longlongrightarrow> c) F \\<longleftrightarrow> (g \\<longlongrightarrow> c) F\" if \"eventually (\\<lambda>x. f x = g x) F\"\n  by (rule filterlim_cong [OF refl refl that])\n\nlemma tendsto_mono: \"F \\<le> F' \\<Longrightarrow> (f \\<longlongrightarrow> l) F' \\<Longrightarrow> (f \\<longlongrightarrow> l) F\"\n  unfolding tendsto_def le_filter_def by fast\n\nlemma tendsto_ident_at [tendsto_intros, simp, intro]: \"((\\<lambda>x. x) \\<longlongrightarrow> a) (at a within s)\"\n  by (auto simp: tendsto_def eventually_at_topological)\n\nlemma tendsto_const [tendsto_intros, simp, intro]: \"((\\<lambda>x. k) \\<longlongrightarrow> k) F\"\n  by (simp add: tendsto_def)\n\nlemma filterlim_at:\n  \"(LIM x F. f x :> at b within s) \\<longleftrightarrow> eventually (\\<lambda>x. f x \\<in> s \\<and> f x \\<noteq> b) F \\<and> (f \\<longlongrightarrow> b) F\"\n  by (simp add: at_within_def filterlim_inf filterlim_principal conj_commute)\n\nlemma (in -)\n  assumes \"filterlim f (nhds L) F\"\n  shows tendsto_imp_filterlim_at_right:\n          \"eventually (\\<lambda>x. f x > L) F \\<Longrightarrow> filterlim f (at_right L) F\"\n    and tendsto_imp_filterlim_at_left:\n          \"eventually (\\<lambda>x. f x < L) F \\<Longrightarrow> filterlim f (at_left L) F\"\n  using assms by (auto simp: filterlim_at elim: eventually_mono)\n\nlemma  filterlim_at_withinI:\n  assumes \"filterlim f (nhds c) F\"\n  assumes \"eventually (\\<lambda>x. f x \\<in> A - {c}) F\"\n  shows   \"filterlim f (at c within A) F\"\n  using assms by (simp add: filterlim_at)\n\nlemma filterlim_atI:\n  assumes \"filterlim f (nhds c) F\"\n  assumes \"eventually (\\<lambda>x. f x \\<noteq> c) F\"\n  shows   \"filterlim f (at c) F\"\n  using assms by (intro filterlim_at_withinI) simp_all\n\nlemma topological_tendstoI:\n  \"(\\<And>S. open S \\<Longrightarrow> l \\<in> S \\<Longrightarrow> eventually (\\<lambda>x. f x \\<in> S) F) \\<Longrightarrow> (f \\<longlongrightarrow> l) F\"\n  by (auto simp: tendsto_def)\n\nlemma topological_tendstoD:\n  \"(f \\<longlongrightarrow> l) F \\<Longrightarrow> open S \\<Longrightarrow> l \\<in> S \\<Longrightarrow> eventually (\\<lambda>x. f x \\<in> S) F\"\n  by (auto simp: tendsto_def)\n\nlemma tendsto_bot [simp]: \"(f \\<longlongrightarrow> a) bot\"\n  by (simp add: tendsto_def)\n\nlemma tendsto_eventually: \"eventually (\\<lambda>x. f x = l) net \\<Longrightarrow> ((\\<lambda>x. f x) \\<longlongrightarrow> l) net\"\n  by (rule topological_tendstoI) (auto elim: eventually_mono)\n\n(* Contributed by Dominique Unruh *)\nlemma tendsto_principal_singleton[simp]:\n  shows \"(f \\<longlongrightarrow> f x) (principal {x})\"\n  unfolding tendsto_def eventually_principal by simp\n\nend\n\nlemma (in topological_space) filterlim_within_subset:\n  \"filterlim f l (at x within S) \\<Longrightarrow> T \\<subseteq> S \\<Longrightarrow> filterlim f l (at x within T)\"\n  by (blast intro: filterlim_mono at_le)\n\nlemmas tendsto_within_subset = filterlim_within_subset\n\nlemma (in order_topology) order_tendsto_iff:\n  \"(f \\<longlongrightarrow> x) F \\<longleftrightarrow> (\\<forall>l<x. eventually (\\<lambda>x. l < f x) F) \\<and> (\\<forall>u>x. eventually (\\<lambda>x. f x < u) F)\"\n  by (auto simp: nhds_order filterlim_inf filterlim_INF filterlim_principal)\n\nlemma (in order_topology) order_tendstoI:\n  \"(\\<And>a. a < y \\<Longrightarrow> eventually (\\<lambda>x. a < f x) F) \\<Longrightarrow> (\\<And>a. y < a \\<Longrightarrow> eventually (\\<lambda>x. f x < a) F) \\<Longrightarrow>\n    (f \\<longlongrightarrow> y) F\"\n  by (auto simp: order_tendsto_iff)\n\nlemma (in order_topology) order_tendstoD:\n  assumes \"(f \\<longlongrightarrow> y) F\"\n  shows \"a < y \\<Longrightarrow> eventually (\\<lambda>x. a < f x) F\"\n    and \"y < a \\<Longrightarrow> eventually (\\<lambda>x. f x < a) F\"\n  using assms by (auto simp: order_tendsto_iff)\n\nlemma (in linorder_topology) tendsto_max[tendsto_intros]:\n  assumes X: \"(X \\<longlongrightarrow> x) net\"\n    and Y: \"(Y \\<longlongrightarrow> y) net\"\n  shows \"((\\<lambda>x. max (X x) (Y x)) \\<longlongrightarrow> max x y) net\"\nproof (rule order_tendstoI)\n  fix a\n  assume \"a < max x y\"\n  then show \"eventually (\\<lambda>x. a < max (X x) (Y x)) net\"\n    using order_tendstoD(1)[OF X, of a] order_tendstoD(1)[OF Y, of a]\n    by (auto simp: less_max_iff_disj elim: eventually_mono)\nnext\n  fix a\n  assume \"max x y < a\"\n  then show \"eventually (\\<lambda>x. max (X x) (Y x) < a) net\"\n    using order_tendstoD(2)[OF X, of a] order_tendstoD(2)[OF Y, of a]\n    by (auto simp: eventually_conj_iff)\nqed\n\nlemma (in linorder_topology) tendsto_min[tendsto_intros]:\n  assumes X: \"(X \\<longlongrightarrow> x) net\"\n    and Y: \"(Y \\<longlongrightarrow> y) net\"\n  shows \"((\\<lambda>x. min (X x) (Y x)) \\<longlongrightarrow> min x y) net\"\nproof (rule order_tendstoI)\n  fix a\n  assume \"a < min x y\"\n  then show \"eventually (\\<lambda>x. a < min (X x) (Y x)) net\"\n    using order_tendstoD(1)[OF X, of a] order_tendstoD(1)[OF Y, of a]\n    by (auto simp: eventually_conj_iff)\nnext\n  fix a\n  assume \"min x y < a\"\n  then show \"eventually (\\<lambda>x. min (X x) (Y x) < a) net\"\n    using order_tendstoD(2)[OF X, of a] order_tendstoD(2)[OF Y, of a]\n    by (auto simp: min_less_iff_disj elim: eventually_mono)\nqed\n\nlemma (in order_topology)\n  assumes \"a < b\"\n  shows at_within_Icc_at_right: \"at a within {a..b} = at_right a\"\n    and at_within_Icc_at_left:  \"at b within {a..b} = at_left b\"\n  using order_tendstoD(2)[OF tendsto_ident_at assms, of \"{a<..}\"]\n  using order_tendstoD(1)[OF tendsto_ident_at assms, of \"{..<b}\"]\n  by (auto intro!: order_class.order_antisym filter_leI\n      simp: eventually_at_filter less_le\n      elim: eventually_elim2)\n\nlemma (in order_topology) at_within_Icc_at: \"a < x \\<Longrightarrow> x < b \\<Longrightarrow> at x within {a..b} = at x\"\n  by (rule at_within_open_subset[where S=\"{a<..<b}\"]) auto\n\nlemma (in t2_space) tendsto_unique:\n  assumes \"F \\<noteq> bot\"\n    and \"(f \\<longlongrightarrow> a) F\"\n    and \"(f \\<longlongrightarrow> b) F\"\n  shows \"a = b\"\nproof (rule ccontr)\n  assume \"a \\<noteq> b\"\n  obtain U V where \"open U\" \"open V\" \"a \\<in> U\" \"b \\<in> V\" \"U \\<inter> V = {}\"\n    using hausdorff [OF \\<open>a \\<noteq> b\\<close>] by fast\n  have \"eventually (\\<lambda>x. f x \\<in> U) F\"\n    using \\<open>(f \\<longlongrightarrow> a) F\\<close> \\<open>open U\\<close> \\<open>a \\<in> U\\<close> by (rule topological_tendstoD)\n  moreover\n  have \"eventually (\\<lambda>x. f x \\<in> V) F\"\n    using \\<open>(f \\<longlongrightarrow> b) F\\<close> \\<open>open V\\<close> \\<open>b \\<in> V\\<close> by (rule topological_tendstoD)\n  ultimately\n  have \"eventually (\\<lambda>x. False) F\"\n  proof eventually_elim\n    case (elim x)\n    then have \"f x \\<in> U \\<inter> V\" by simp\n    with \\<open>U \\<inter> V = {}\\<close> show ?case by simp\n  qed\n  with \\<open>\\<not> trivial_limit F\\<close> show \"False\"\n    by (simp add: trivial_limit_def)\nqed\n\nlemma (in t2_space) tendsto_const_iff:\n  fixes a b :: 'a\n  assumes \"\\<not> trivial_limit F\"\n  shows \"((\\<lambda>x. a) \\<longlongrightarrow> b) F \\<longleftrightarrow> a = b\"\n  by (auto intro!: tendsto_unique [OF assms tendsto_const])\n\nlemma (in t2_space) tendsto_unique':\n assumes \"F \\<noteq> bot\"\n shows \"\\<exists>\\<^sub>\\<le>\\<^sub>1l. (f \\<longlongrightarrow> l) F\"\n using Uniq_def assms local.tendsto_unique by fastforce\n\nlemma Lim_in_closed_set:\n  assumes \"closed S\" \"eventually (\\<lambda>x. f(x) \\<in> S) F\" \"F \\<noteq> bot\" \"(f \\<longlongrightarrow> l) F\"\n  shows \"l \\<in> S\"\nproof (rule ccontr)\n  assume \"l \\<notin> S\"\n  with \\<open>closed S\\<close> have \"open (- S)\" \"l \\<in> - S\"\n    by (simp_all add: open_Compl)\n  with assms(4) have \"eventually (\\<lambda>x. f x \\<in> - S) F\"\n    by (rule topological_tendstoD)\n  with assms(2) have \"eventually (\\<lambda>x. False) F\"\n    by (rule eventually_elim2) simp\n  with assms(3) show \"False\"\n    by (simp add: eventually_False)\nqed\n\nlemma (in t3_space) nhds_closed:\n  assumes \"x \\<in> A\" and \"open A\"\n  shows   \"\\<exists>A'. x \\<in> A' \\<and> closed A' \\<and> A' \\<subseteq> A \\<and> eventually (\\<lambda>y. y \\<in> A') (nhds x)\"\nproof -\n  from assms have \"\\<exists>U V. open U \\<and> open V \\<and> x \\<in> U \\<and> - A \\<subseteq> V \\<and> U \\<inter> V = {}\"\n    by (intro t3_space) auto\n  then obtain U V where UV: \"open U\" \"open V\" \"x \\<in> U\" \"-A \\<subseteq> V\" \"U \\<inter> V = {}\"\n    by auto\n  have \"eventually (\\<lambda>y. y \\<in> U) (nhds x)\"\n    using \\<open>open U\\<close> and \\<open>x \\<in> U\\<close> by (intro eventually_nhds_in_open)\n  hence \"eventually (\\<lambda>y. y \\<in> -V) (nhds x)\"\n    by eventually_elim (use UV in auto)\n  with UV show ?thesis by (intro exI[of _ \"-V\"]) auto\nqed\n\nlemma (in order_topology) increasing_tendsto:\n  assumes bdd: \"eventually (\\<lambda>n. f n \\<le> l) F\"\n    and en: \"\\<And>x. x < l \\<Longrightarrow> eventually (\\<lambda>n. x < f n) F\"\n  shows \"(f \\<longlongrightarrow> l) F\"\n  using assms by (intro order_tendstoI) (auto elim!: eventually_mono)\n\nlemma (in order_topology) decreasing_tendsto:\n  assumes bdd: \"eventually (\\<lambda>n. l \\<le> f n) F\"\n    and en: \"\\<And>x. l < x \\<Longrightarrow> eventually (\\<lambda>n. f n < x) F\"\n  shows \"(f \\<longlongrightarrow> l) F\"\n  using assms by (intro order_tendstoI) (auto elim!: eventually_mono)\n\nlemma (in order_topology) tendsto_sandwich:\n  assumes ev: \"eventually (\\<lambda>n. f n \\<le> g n) net\" \"eventually (\\<lambda>n. g n \\<le> h n) net\"\n  assumes lim: \"(f \\<longlongrightarrow> c) net\" \"(h \\<longlongrightarrow> c) net\"\n  shows \"(g \\<longlongrightarrow> c) net\"\nproof (rule order_tendstoI)\n  fix a\n  show \"a < c \\<Longrightarrow> eventually (\\<lambda>x. a < g x) net\"\n    using order_tendstoD[OF lim(1), of a] ev by (auto elim: eventually_elim2)\nnext\n  fix a\n  show \"c < a \\<Longrightarrow> eventually (\\<lambda>x. g x < a) net\"\n    using order_tendstoD[OF lim(2), of a] ev by (auto elim: eventually_elim2)\nqed\n\nlemma (in t1_space) limit_frequently_eq:\n  assumes \"F \\<noteq> bot\"\n    and \"frequently (\\<lambda>x. f x = c) F\"\n    and \"(f \\<longlongrightarrow> d) F\"\n  shows \"d = c\"\nproof (rule ccontr)\n  assume \"d \\<noteq> c\"\n  from t1_space[OF this] obtain U where \"open U\" \"d \\<in> U\" \"c \\<notin> U\"\n    by blast\n  with assms have \"eventually (\\<lambda>x. f x \\<in> U) F\"\n    unfolding tendsto_def by blast\n  then have \"eventually (\\<lambda>x. f x \\<noteq> c) F\"\n    by eventually_elim (insert \\<open>c \\<notin> U\\<close>, blast)\n  with assms(2) show False\n    unfolding frequently_def by contradiction\nqed\n\nlemma (in t1_space) tendsto_imp_eventually_ne:\n  assumes  \"(f \\<longlongrightarrow> c) F\" \"c \\<noteq> c'\"\n  shows \"eventually (\\<lambda>z. f z \\<noteq> c') F\"\nproof (cases \"F=bot\")\n  case True\n  thus ?thesis by auto\nnext\n  case False\n  show ?thesis\n  proof (rule ccontr)\n    assume \"\\<not> eventually (\\<lambda>z. f z \\<noteq> c') F\"\n    then have \"frequently (\\<lambda>z. f z = c') F\"\n      by (simp add: frequently_def)\n    from limit_frequently_eq[OF False this \\<open>(f \\<longlongrightarrow> c) F\\<close>] and \\<open>c \\<noteq> c'\\<close> show False\n      by contradiction\n  qed\nqed\n\nlemma (in linorder_topology) tendsto_le:\n  assumes F: \"\\<not> trivial_limit F\"\n    and x: \"(f \\<longlongrightarrow> x) F\"\n    and y: \"(g \\<longlongrightarrow> y) F\"\n    and ev: \"eventually (\\<lambda>x. g x \\<le> f x) F\"\n  shows \"y \\<le> x\"\nproof (rule ccontr)\n  assume \"\\<not> y \\<le> x\"\n  with less_separate[of x y] obtain a b where xy: \"x < a\" \"b < y\" \"{..<a} \\<inter> {b<..} = {}\"\n    by (auto simp: not_le)\n  then have \"eventually (\\<lambda>x. f x < a) F\" \"eventually (\\<lambda>x. b < g x) F\"\n    using x y by (auto intro: order_tendstoD)\n  with ev have \"eventually (\\<lambda>x. False) F\"\n    by eventually_elim (insert xy, fastforce)\n  with F show False\n    by (simp add: eventually_False)\nqed\n\nlemma (in linorder_topology) tendsto_lowerbound:\n  assumes x: \"(f \\<longlongrightarrow> x) F\"\n      and ev: \"eventually (\\<lambda>i. a \\<le> f i) F\"\n      and F: \"\\<not> trivial_limit F\"\n  shows \"a \\<le> x\"\n  using F x tendsto_const ev by (rule tendsto_le)\n\nlemma (in linorder_topology) tendsto_upperbound:\n  assumes x: \"(f \\<longlongrightarrow> x) F\"\n      and ev: \"eventually (\\<lambda>i. a \\<ge> f i) F\"\n      and F: \"\\<not> trivial_limit F\"\n  shows \"a \\<ge> x\"\n  by (rule tendsto_le [OF F tendsto_const x ev])\n\nlemma filterlim_at_within_not_equal:\n  fixes f::\"'a \\<Rightarrow> 'b::t2_space\"\n  assumes \"filterlim f (at a within s) F\"\n  shows \"eventually (\\<lambda>w. f w\\<in>s \\<and> f w \\<noteq>b) F\"\nproof (cases \"a=b\")\n  case True\n  then show ?thesis using assms by (simp add: filterlim_at)\nnext\n  case False\n  from hausdorff[OF this] obtain U V where UV:\"open U\" \"open V\" \"a \\<in> U\" \"b \\<in> V\" \"U \\<inter> V = {}\"\n    by auto  \n  have \"(f \\<longlongrightarrow> a) F\" using assms filterlim_at by auto\n  then have \"\\<forall>\\<^sub>F x in F. f x \\<in> U\" using UV unfolding tendsto_def by auto\n  moreover have  \"\\<forall>\\<^sub>F x in F. f x \\<in> s \\<and> f x\\<noteq>a\" using assms filterlim_at by auto\n  ultimately show ?thesis \n    apply eventually_elim\n    using UV by auto\nqed\n\nsubsubsection \\<open>Rules about \\<^const>\\<open>Lim\\<close>\\<close>\n\nlemma tendsto_Lim: \"\\<not> trivial_limit net \\<Longrightarrow> (f \\<longlongrightarrow> l) net \\<Longrightarrow> Lim net f = l\"\n  unfolding Lim_def using tendsto_unique [of net f] by auto\n\nlemma Lim_ident_at: \"\\<not> trivial_limit (at x within s) \\<Longrightarrow> Lim (at x within s) (\\<lambda>x. x) = x\"\n  by (rule tendsto_Lim[OF _ tendsto_ident_at]) auto\n\nlemma eventually_Lim_ident_at:\n  \"(\\<forall>\\<^sub>F y in at x within X. P (Lim (at x within X) (\\<lambda>x. x)) y) \\<longleftrightarrow>\n    (\\<forall>\\<^sub>F y in at x within X. P x y)\" for x::\"'a::t2_space\"\n  by (cases \"at x within X = bot\") (auto simp: Lim_ident_at)\n\nlemma filterlim_at_bot_at_right:\n  fixes f :: \"'a::linorder_topology \\<Rightarrow> 'b::linorder\"\n  assumes mono: \"\\<And>x y. Q x \\<Longrightarrow> Q y \\<Longrightarrow> x \\<le> y \\<Longrightarrow> f x \\<le> f y\"\n    and bij: \"\\<And>x. P x \\<Longrightarrow> f (g x) = x\" \"\\<And>x. P x \\<Longrightarrow> Q (g x)\"\n    and Q: \"eventually Q (at_right a)\"\n    and bound: \"\\<And>b. Q b \\<Longrightarrow> a < b\"\n    and P: \"eventually P at_bot\"\n  shows \"filterlim f at_bot (at_right a)\"\nproof -\n  from P obtain x where x: \"\\<And>y. y \\<le> x \\<Longrightarrow> P y\"\n    unfolding eventually_at_bot_linorder by auto\n  show ?thesis\n  proof (intro filterlim_at_bot_le[THEN iffD2] allI impI)\n    fix z\n    assume \"z \\<le> x\"\n    with x have \"P z\" by auto\n    have \"eventually (\\<lambda>x. x \\<le> g z) (at_right a)\"\n      using bound[OF bij(2)[OF \\<open>P z\\<close>]]\n      unfolding eventually_at_right[OF bound[OF bij(2)[OF \\<open>P z\\<close>]]]\n      by (auto intro!: exI[of _ \"g z\"])\n    with Q show \"eventually (\\<lambda>x. f x \\<le> z) (at_right a)\"\n      by eventually_elim (metis bij \\<open>P z\\<close> mono)\n  qed\nqed\n\nlemma filterlim_at_top_at_left:\n  fixes f :: \"'a::linorder_topology \\<Rightarrow> 'b::linorder\"\n  assumes mono: \"\\<And>x y. Q x \\<Longrightarrow> Q y \\<Longrightarrow> x \\<le> y \\<Longrightarrow> f x \\<le> f y\"\n    and bij: \"\\<And>x. P x \\<Longrightarrow> f (g x) = x\" \"\\<And>x. P x \\<Longrightarrow> Q (g x)\"\n    and Q: \"eventually Q (at_left a)\"\n    and bound: \"\\<And>b. Q b \\<Longrightarrow> b < a\"\n    and P: \"eventually P at_top\"\n  shows \"filterlim f at_top (at_left a)\"\nproof -\n  from P obtain x where x: \"\\<And>y. x \\<le> y \\<Longrightarrow> P y\"\n    unfolding eventually_at_top_linorder by auto\n  show ?thesis\n  proof (intro filterlim_at_top_ge[THEN iffD2] allI impI)\n    fix z\n    assume \"x \\<le> z\"\n    with x have \"P z\" by auto\n    have \"eventually (\\<lambda>x. g z \\<le> x) (at_left a)\"\n      using bound[OF bij(2)[OF \\<open>P z\\<close>]]\n      unfolding eventually_at_left[OF bound[OF bij(2)[OF \\<open>P z\\<close>]]]\n      by (auto intro!: exI[of _ \"g z\"])\n    with Q show \"eventually (\\<lambda>x. z \\<le> f x) (at_left a)\"\n      by eventually_elim (metis bij \\<open>P z\\<close> mono)\n  qed\nqed\n\nlemma filterlim_split_at:\n  \"filterlim f F (at_left x) \\<Longrightarrow> filterlim f F (at_right x) \\<Longrightarrow>\n    filterlim f F (at x)\"\n  for x :: \"'a::linorder_topology\"\n  by (subst at_eq_sup_left_right) (rule filterlim_sup)\n\nlemma filterlim_at_split:\n  \"filterlim f F (at x) \\<longleftrightarrow> filterlim f F (at_left x) \\<and> filterlim f F (at_right x)\"\n  for x :: \"'a::linorder_topology\"\n  by (subst at_eq_sup_left_right) (simp add: filterlim_def filtermap_sup)\n\nlemma eventually_nhds_top:\n  fixes P :: \"'a :: {order_top,linorder_topology} \\<Rightarrow> bool\"\n    and b :: 'a\n  assumes \"b < top\"\n  shows \"eventually P (nhds top) \\<longleftrightarrow> (\\<exists>b<top. (\\<forall>z. b < z \\<longrightarrow> P z))\"\n  unfolding eventually_nhds\nproof safe\n  fix S :: \"'a set\"\n  assume \"open S\" \"top \\<in> S\"\n  note open_left[OF this \\<open>b < top\\<close>]\n  moreover assume \"\\<forall>s\\<in>S. P s\"\n  ultimately show \"\\<exists>b<top. \\<forall>z>b. P z\"\n    by (auto simp: subset_eq Ball_def)\nnext\n  fix b\n  assume \"b < top\" \"\\<forall>z>b. P z\"\n  then show \"\\<exists>S. open S \\<and> top \\<in> S \\<and> (\\<forall>xa\\<in>S. P xa)\"\n    by (intro exI[of _ \"{b <..}\"]) auto\nqed\n\nlemma tendsto_at_within_iff_tendsto_nhds:\n  \"(g \\<longlongrightarrow> g l) (at l within S) \\<longleftrightarrow> (g \\<longlongrightarrow> g l) (inf (nhds l) (principal S))\"\n  unfolding tendsto_def eventually_at_filter eventually_inf_principal\n  by (intro ext all_cong imp_cong) (auto elim!: eventually_mono)\n\n\nsubsection \\<open>Limits on sequences\\<close>\n\nabbreviation (in topological_space)\n  LIMSEQ :: \"[nat \\<Rightarrow> 'a, 'a] \\<Rightarrow> bool\"  (\"((_)/ \\<longlonglongrightarrow> (_))\" [60, 60] 60)\n  where \"X \\<longlonglongrightarrow> L \\<equiv> (X \\<longlongrightarrow> L) sequentially\"\n\nabbreviation (in t2_space) lim :: \"(nat \\<Rightarrow> 'a) \\<Rightarrow> 'a\"\n  where \"lim X \\<equiv> Lim sequentially X\"\n\ndefinition (in topological_space) convergent :: \"(nat \\<Rightarrow> 'a) \\<Rightarrow> bool\"\n  where \"convergent X = (\\<exists>L. X \\<longlonglongrightarrow> L)\"\n\nlemma lim_def: \"lim X = (THE L. X \\<longlonglongrightarrow> L)\"\n  unfolding Lim_def ..\n\nlemma lim_explicit:\n  \"f \\<longlonglongrightarrow> f0 \\<longleftrightarrow> (\\<forall>S. open S \\<longrightarrow> f0 \\<in> S \\<longrightarrow> (\\<exists>N. \\<forall>n\\<ge>N. f n \\<in> S))\"\n  unfolding tendsto_def eventually_sequentially by auto\n\n\nsubsection \\<open>Monotone sequences and subsequences\\<close>\n\ntext \\<open>\n  Definition of monotonicity.\n  The use of disjunction here complicates proofs considerably.\n  One alternative is to add a Boolean argument to indicate the direction.\n  Another is to develop the notions of increasing and decreasing first.\n\\<close>\ndefinition monoseq :: \"(nat \\<Rightarrow> 'a::order) \\<Rightarrow> bool\"\n  where \"monoseq X \\<longleftrightarrow> (\\<forall>m. \\<forall>n\\<ge>m. X m \\<le> X n) \\<or> (\\<forall>m. \\<forall>n\\<ge>m. X n \\<le> X m)\"\n\nabbreviation incseq :: \"(nat \\<Rightarrow> 'a::order) \\<Rightarrow> bool\"\n  where \"incseq X \\<equiv> mono X\"\n\nlemma incseq_def: \"incseq X \\<longleftrightarrow> (\\<forall>m. \\<forall>n\\<ge>m. X n \\<ge> X m)\"\n  unfolding mono_def ..\n\nabbreviation decseq :: \"(nat \\<Rightarrow> 'a::order) \\<Rightarrow> bool\"\n  where \"decseq X \\<equiv> antimono X\"\n\nlemma decseq_def: \"decseq X \\<longleftrightarrow> (\\<forall>m. \\<forall>n\\<ge>m. X n \\<le> X m)\"\n  unfolding antimono_def ..\n\nsubsubsection \\<open>Definition of subsequence.\\<close>\n\n(* For compatibility with the old \"subseq\" *)\nlemma strict_mono_leD: \"strict_mono r \\<Longrightarrow> m \\<le> n \\<Longrightarrow> r m \\<le> r n\"\n  by (erule (1) monoD [OF strict_mono_mono])\n\nlemma strict_mono_id: \"strict_mono id\"\n  by (simp add: strict_mono_def)\n\nlemma incseq_SucI: \"(\\<And>n. X n \\<le> X (Suc n)) \\<Longrightarrow> incseq X\"\n  using lift_Suc_mono_le[of X] by (auto simp: incseq_def)\n\nlemma incseqD: \"incseq f \\<Longrightarrow> i \\<le> j \\<Longrightarrow> f i \\<le> f j\"\n  by (auto simp: incseq_def)\n\nlemma incseq_SucD: \"incseq A \\<Longrightarrow> A i \\<le> A (Suc i)\"\n  using incseqD[of A i \"Suc i\"] by auto\n\nlemma incseq_Suc_iff: \"incseq f \\<longleftrightarrow> (\\<forall>n. f n \\<le> f (Suc n))\"\n  by (auto intro: incseq_SucI dest: incseq_SucD)\n\nlemma incseq_const[simp, intro]: \"incseq (\\<lambda>x. k)\"\n  unfolding incseq_def by auto\n\nlemma decseq_SucI: \"(\\<And>n. X (Suc n) \\<le> X n) \\<Longrightarrow> decseq X\"\n  using order.lift_Suc_mono_le[OF dual_order, of X] by (auto simp: decseq_def)\n\nlemma decseqD: \"decseq f \\<Longrightarrow> i \\<le> j \\<Longrightarrow> f j \\<le> f i\"\n  by (auto simp: decseq_def)\n\nlemma decseq_SucD: \"decseq A \\<Longrightarrow> A (Suc i) \\<le> A i\"\n  using decseqD[of A i \"Suc i\"] by auto\n\nlemma decseq_Suc_iff: \"decseq f \\<longleftrightarrow> (\\<forall>n. f (Suc n) \\<le> f n)\"\n  by (auto intro: decseq_SucI dest: decseq_SucD)\n\nlemma decseq_const[simp, intro]: \"decseq (\\<lambda>x. k)\"\n  unfolding decseq_def by auto\n\nlemma monoseq_iff: \"monoseq X \\<longleftrightarrow> incseq X \\<or> decseq X\"\n  unfolding monoseq_def incseq_def decseq_def ..\n\nlemma monoseq_Suc: \"monoseq X \\<longleftrightarrow> (\\<forall>n. X n \\<le> X (Suc n)) \\<or> (\\<forall>n. X (Suc n) \\<le> X n)\"\n  unfolding monoseq_iff incseq_Suc_iff decseq_Suc_iff ..\n\nlemma monoI1: \"\\<forall>m. \\<forall>n \\<ge> m. X m \\<le> X n \\<Longrightarrow> monoseq X\"\n  by (simp add: monoseq_def)\n\nlemma monoI2: \"\\<forall>m. \\<forall>n \\<ge> m. X n \\<le> X m \\<Longrightarrow> monoseq X\"\n  by (simp add: monoseq_def)\n\nlemma mono_SucI1: \"\\<forall>n. X n \\<le> X (Suc n) \\<Longrightarrow> monoseq X\"\n  by (simp add: monoseq_Suc)\n\nlemma mono_SucI2: \"\\<forall>n. X (Suc n) \\<le> X n \\<Longrightarrow> monoseq X\"\n  by (simp add: monoseq_Suc)\n\nlemma monoseq_minus:\n  fixes a :: \"nat \\<Rightarrow> 'a::ordered_ab_group_add\"\n  assumes \"monoseq a\"\n  shows \"monoseq (\\<lambda> n. - a n)\"\nproof (cases \"\\<forall>m. \\<forall>n \\<ge> m. a m \\<le> a n\")\n  case True\n  then have \"\\<forall>m. \\<forall>n \\<ge> m. - a n \\<le> - a m\" by auto\n  then show ?thesis by (rule monoI2)\nnext\n  case False\n  then have \"\\<forall>m. \\<forall>n \\<ge> m. - a m \\<le> - a n\"\n    using \\<open>monoseq a\\<close>[unfolded monoseq_def] by auto\n  then show ?thesis by (rule monoI1)\nqed\n\n\nsubsubsection \\<open>Subsequence (alternative definition, (e.g. Hoskins)\\<close>\n\nlemma strict_mono_Suc_iff: \"strict_mono f \\<longleftrightarrow> (\\<forall>n. f n < f (Suc n))\"\nproof (intro iffI strict_monoI)\n  assume *: \"\\<forall>n. f n < f (Suc n)\"\n  fix m n :: nat assume \"m < n\"\n  thus \"f m < f n\"\n    by (induction rule: less_Suc_induct) (use * in auto)\nqed (auto simp: strict_mono_def)\n\nlemma strict_mono_add: \"strict_mono (\\<lambda>n::'a::linordered_semidom. n + k)\"\n  by (auto simp: strict_mono_def)\n\ntext \\<open>For any sequence, there is a monotonic subsequence.\\<close>\nlemma seq_monosub:\n  fixes s :: \"nat \\<Rightarrow> 'a::linorder\"\n  shows \"\\<exists>f. strict_mono f \\<and> monoseq (\\<lambda>n. (s (f n)))\"\nproof (cases \"\\<forall>n. \\<exists>p>n. \\<forall>m\\<ge>p. s m \\<le> s p\")\n  case True\n  then have \"\\<exists>f. \\<forall>n. (\\<forall>m\\<ge>f n. s m \\<le> s (f n)) \\<and> f n < f (Suc n)\"\n    by (intro dependent_nat_choice) (auto simp: conj_commute)\n  then obtain f :: \"nat \\<Rightarrow> nat\" \n    where f: \"strict_mono f\" and mono: \"\\<And>n m. f n \\<le> m \\<Longrightarrow> s m \\<le> s (f n)\"\n    by (auto simp: strict_mono_Suc_iff)\n  then have \"incseq f\"\n    unfolding strict_mono_Suc_iff incseq_Suc_iff by (auto intro: less_imp_le)\n  then have \"monoseq (\\<lambda>n. s (f n))\"\n    by (auto simp add: incseq_def intro!: mono monoI2)\n  with f show ?thesis\n    by auto\nnext\n  case False\n  then obtain N where N: \"p > N \\<Longrightarrow> \\<exists>m>p. s p < s m\" for p\n    by (force simp: not_le le_less)\n  have \"\\<exists>f. \\<forall>n. N < f n \\<and> f n < f (Suc n) \\<and> s (f n) \\<le> s (f (Suc n))\"\n  proof (intro dependent_nat_choice)\n    fix x\n    assume \"N < x\" with N[of x]\n    show \"\\<exists>y>N. x < y \\<and> s x \\<le> s y\"\n      by (auto intro: less_trans)\n  qed auto\n  then show ?thesis\n    by (auto simp: monoseq_iff incseq_Suc_iff strict_mono_Suc_iff)\nqed\n\nlemma seq_suble:\n  assumes sf: \"strict_mono (f :: nat \\<Rightarrow> nat)\"\n  shows \"n \\<le> f n\"\nproof (induct n)\n  case 0\n  show ?case by simp\nnext\n  case (Suc n)\n  with sf [unfolded strict_mono_Suc_iff, rule_format, of n] have \"n < f (Suc n)\"\n     by arith\n  then show ?case by arith\nqed\n\nlemma eventually_subseq:\n  \"strict_mono r \\<Longrightarrow> eventually P sequentially \\<Longrightarrow> eventually (\\<lambda>n. P (r n)) sequentially\"\n  unfolding eventually_sequentially by (metis seq_suble le_trans)\n\nlemma not_eventually_sequentiallyD:\n  assumes \"\\<not> eventually P sequentially\"\n  shows \"\\<exists>r::nat\\<Rightarrow>nat. strict_mono r \\<and> (\\<forall>n. \\<not> P (r n))\"\nproof -\n  from assms have \"\\<forall>n. \\<exists>m\\<ge>n. \\<not> P m\"\n    unfolding eventually_sequentially by (simp add: not_less)\n  then obtain r where \"\\<And>n. r n \\<ge> n\" \"\\<And>n. \\<not> P (r n)\"\n    by (auto simp: choice_iff)\n  then show ?thesis\n    by (auto intro!: exI[of _ \"\\<lambda>n. r (((Suc \\<circ> r) ^^ Suc n) 0)\"]\n             simp: less_eq_Suc_le strict_mono_Suc_iff)\nqed\n\nlemma sequentially_offset: \n  assumes \"eventually (\\<lambda>i. P i) sequentially\"\n  shows \"eventually (\\<lambda>i. P (i + k)) sequentially\"\n  using assms by (rule eventually_sequentially_seg [THEN iffD2])\n\nlemma seq_offset_neg: \n  \"(f \\<longlongrightarrow> l) sequentially \\<Longrightarrow> ((\\<lambda>i. f(i - k)) \\<longlongrightarrow> l) sequentially\"\n  apply (erule filterlim_compose)\n  apply (simp add: filterlim_def le_sequentially eventually_filtermap eventually_sequentially, arith)\n  done\n\nlemma filterlim_subseq: \"strict_mono f \\<Longrightarrow> filterlim f sequentially sequentially\"\n  unfolding filterlim_iff by (metis eventually_subseq)\n\nlemma strict_mono_o: \"strict_mono r \\<Longrightarrow> strict_mono s \\<Longrightarrow> strict_mono (r \\<circ> s)\"\n  unfolding strict_mono_def by simp\n\nlemma strict_mono_compose: \"strict_mono r \\<Longrightarrow> strict_mono s \\<Longrightarrow> strict_mono (\\<lambda>x. r (s x))\"\n  using strict_mono_o[of r s] by (simp add: o_def)\n\nlemma incseq_imp_monoseq:  \"incseq X \\<Longrightarrow> monoseq X\"\n  by (simp add: incseq_def monoseq_def)\n\nlemma decseq_imp_monoseq:  \"decseq X \\<Longrightarrow> monoseq X\"\n  by (simp add: decseq_def monoseq_def)\n\nlemma decseq_eq_incseq: \"decseq X = incseq (\\<lambda>n. - X n)\"\n  for X :: \"nat \\<Rightarrow> 'a::ordered_ab_group_add\"\n  by (simp add: decseq_def incseq_def)\n\nlemma INT_decseq_offset:\n  assumes \"decseq F\"\n  shows \"(\\<Inter>i. F i) = (\\<Inter>i\\<in>{n..}. F i)\"\nproof safe\n  fix x i\n  assume x: \"x \\<in> (\\<Inter>i\\<in>{n..}. F i)\"\n  show \"x \\<in> F i\"\n  proof cases\n    from x have \"x \\<in> F n\" by auto\n    also assume \"i \\<le> n\" with \\<open>decseq F\\<close> have \"F n \\<subseteq> F i\"\n      unfolding decseq_def by simp\n    finally show ?thesis .\n  qed (insert x, simp)\nqed auto\n\nlemma LIMSEQ_const_iff: \"(\\<lambda>n. k) \\<longlonglongrightarrow> l \\<longleftrightarrow> k = l\"\n  for k l :: \"'a::t2_space\"\n  using trivial_limit_sequentially by (rule tendsto_const_iff)\n\nlemma LIMSEQ_SUP: \"incseq X \\<Longrightarrow> X \\<longlonglongrightarrow> (SUP i. X i :: 'a::{complete_linorder,linorder_topology})\"\n  by (intro increasing_tendsto)\n    (auto simp: SUP_upper less_SUP_iff incseq_def eventually_sequentially intro: less_le_trans)\n\nlemma LIMSEQ_INF: \"decseq X \\<Longrightarrow> X \\<longlonglongrightarrow> (INF i. X i :: 'a::{complete_linorder,linorder_topology})\"\n  by (intro decreasing_tendsto)\n    (auto simp: INF_lower INF_less_iff decseq_def eventually_sequentially intro: le_less_trans)\n\nlemma LIMSEQ_ignore_initial_segment: \"f \\<longlonglongrightarrow> a \\<Longrightarrow> (\\<lambda>n. f (n + k)) \\<longlonglongrightarrow> a\"\n  unfolding tendsto_def by (subst eventually_sequentially_seg[where k=k])\n\nlemma LIMSEQ_offset: \"(\\<lambda>n. f (n + k)) \\<longlonglongrightarrow> a \\<Longrightarrow> f \\<longlonglongrightarrow> a\"\n  unfolding tendsto_def\n  by (subst (asm) eventually_sequentially_seg[where k=k])\n\nlemma LIMSEQ_Suc: \"f \\<longlonglongrightarrow> l \\<Longrightarrow> (\\<lambda>n. f (Suc n)) \\<longlonglongrightarrow> l\"\n  by (drule LIMSEQ_ignore_initial_segment [where k=\"Suc 0\"]) simp\n\nlemma LIMSEQ_imp_Suc: \"(\\<lambda>n. f (Suc n)) \\<longlonglongrightarrow> l \\<Longrightarrow> f \\<longlonglongrightarrow> l\"\n  by (rule LIMSEQ_offset [where k=\"Suc 0\"]) simp\n\nlemma LIMSEQ_lessThan_iff_atMost:\n  shows \"(\\<lambda>n. f {..<n}) \\<longlonglongrightarrow> x \\<longleftrightarrow> (\\<lambda>n. f {..n}) \\<longlonglongrightarrow> x\"\n  apply (subst filterlim_sequentially_Suc [symmetric])\n  apply (simp only: lessThan_Suc_atMost)\n  done\n\nlemma (in t2_space) LIMSEQ_Uniq: \"\\<exists>\\<^sub>\\<le>\\<^sub>1l. X \\<longlonglongrightarrow> l\"\n by (simp add: tendsto_unique')\n\nlemma (in t2_space) LIMSEQ_unique: \"X \\<longlonglongrightarrow> a \\<Longrightarrow> X \\<longlonglongrightarrow> b \\<Longrightarrow> a = b\"\n  using trivial_limit_sequentially by (rule tendsto_unique)\n\nlemma LIMSEQ_le_const: \"X \\<longlonglongrightarrow> x \\<Longrightarrow> \\<exists>N. \\<forall>n\\<ge>N. a \\<le> X n \\<Longrightarrow> a \\<le> x\"\n  for a x :: \"'a::linorder_topology\"\n  by (simp add: eventually_at_top_linorder tendsto_lowerbound)\n\nlemma LIMSEQ_le: \"X \\<longlonglongrightarrow> x \\<Longrightarrow> Y \\<longlonglongrightarrow> y \\<Longrightarrow> \\<exists>N. \\<forall>n\\<ge>N. X n \\<le> Y n \\<Longrightarrow> x \\<le> y\"\n  for x y :: \"'a::linorder_topology\"\n  using tendsto_le[of sequentially Y y X x] by (simp add: eventually_sequentially)\n\nlemma LIMSEQ_le_const2: \"X \\<longlonglongrightarrow> x \\<Longrightarrow> \\<exists>N. \\<forall>n\\<ge>N. X n \\<le> a \\<Longrightarrow> x \\<le> a\"\n  for a x :: \"'a::linorder_topology\"\n  by (rule LIMSEQ_le[of X x \"\\<lambda>n. a\"]) auto\n\nlemma Lim_bounded: \"f \\<longlonglongrightarrow> l \\<Longrightarrow> \\<forall>n\\<ge>M. f n \\<le> C \\<Longrightarrow> l \\<le> C\"\n  for l :: \"'a::linorder_topology\"\n  by (intro LIMSEQ_le_const2) auto\n\nlemma Lim_bounded2:\n  fixes f :: \"nat \\<Rightarrow> 'a::linorder_topology\"\n  assumes lim:\"f \\<longlonglongrightarrow> l\" and ge: \"\\<forall>n\\<ge>N. f n \\<ge> C\"\n  shows \"l \\<ge> C\"\n  using ge\n  by (intro tendsto_le[OF trivial_limit_sequentially lim tendsto_const])\n     (auto simp: eventually_sequentially)\n\nlemma lim_mono:\n  fixes X Y :: \"nat \\<Rightarrow> 'a::linorder_topology\"\n  assumes \"\\<And>n. N \\<le> n \\<Longrightarrow> X n \\<le> Y n\"\n    and \"X \\<longlonglongrightarrow> x\"\n    and \"Y \\<longlonglongrightarrow> y\"\n  shows \"x \\<le> y\"\n  using assms(1) by (intro LIMSEQ_le[OF assms(2,3)]) auto\n\nlemma Sup_lim:\n  fixes a :: \"'a::{complete_linorder,linorder_topology}\"\n  assumes \"\\<And>n. b n \\<in> s\"\n    and \"b \\<longlonglongrightarrow> a\"\n  shows \"a \\<le> Sup s\"\n  by (metis Lim_bounded assms complete_lattice_class.Sup_upper)\n\nlemma Inf_lim:\n  fixes a :: \"'a::{complete_linorder,linorder_topology}\"\n  assumes \"\\<And>n. b n \\<in> s\"\n    and \"b \\<longlonglongrightarrow> a\"\n  shows \"Inf s \\<le> a\"\n  by (metis Lim_bounded2 assms complete_lattice_class.Inf_lower)\n\nlemma SUP_Lim:\n  fixes X :: \"nat \\<Rightarrow> 'a::{complete_linorder,linorder_topology}\"\n  assumes inc: \"incseq X\"\n    and l: \"X \\<longlonglongrightarrow> l\"\n  shows \"(SUP n. X n) = l\"\n  using LIMSEQ_SUP[OF inc] tendsto_unique[OF trivial_limit_sequentially l]\n  by simp\n\nlemma INF_Lim:\n  fixes X :: \"nat \\<Rightarrow> 'a::{complete_linorder,linorder_topology}\"\n  assumes dec: \"decseq X\"\n    and l: \"X \\<longlonglongrightarrow> l\"\n  shows \"(INF n. X n) = l\"\n  using LIMSEQ_INF[OF dec] tendsto_unique[OF trivial_limit_sequentially l]\n  by simp\n\nlemma convergentD: \"convergent X \\<Longrightarrow> \\<exists>L. X \\<longlonglongrightarrow> L\"\n  by (simp add: convergent_def)\n\nlemma convergentI: \"X \\<longlonglongrightarrow> L \\<Longrightarrow> convergent X\"\n  by (auto simp add: convergent_def)\n\nlemma convergent_LIMSEQ_iff: \"convergent X \\<longleftrightarrow> X \\<longlonglongrightarrow> lim X\"\n  by (auto intro: theI LIMSEQ_unique simp add: convergent_def lim_def)\n\nlemma convergent_const: \"convergent (\\<lambda>n. c)\"\n  by (rule convergentI) (rule tendsto_const)\n\nlemma monoseq_le:\n  \"monoseq a \\<Longrightarrow> a \\<longlonglongrightarrow> x \\<Longrightarrow>\n    (\\<forall>n. a n \\<le> x) \\<and> (\\<forall>m. \\<forall>n\\<ge>m. a m \\<le> a n) \\<or>\n    (\\<forall>n. x \\<le> a n) \\<and> (\\<forall>m. \\<forall>n\\<ge>m. a n \\<le> a m)\"\n  for x :: \"'a::linorder_topology\"\n  by (metis LIMSEQ_le_const LIMSEQ_le_const2 decseq_def incseq_def monoseq_iff)\n\nlemma LIMSEQ_subseq_LIMSEQ: \"X \\<longlonglongrightarrow> L \\<Longrightarrow> strict_mono f \\<Longrightarrow> (X \\<circ> f) \\<longlonglongrightarrow> L\"\n  unfolding comp_def by (rule filterlim_compose [of X, OF _ filterlim_subseq])\n\nlemma convergent_subseq_convergent: \"convergent X \\<Longrightarrow> strict_mono f \\<Longrightarrow> convergent (X \\<circ> f)\"\n  by (auto simp: convergent_def intro: LIMSEQ_subseq_LIMSEQ)\n\nlemma limI: \"X \\<longlonglongrightarrow> L \\<Longrightarrow> lim X = L\"\n  by (rule tendsto_Lim) (rule trivial_limit_sequentially)\n\nlemma lim_le: \"convergent f \\<Longrightarrow> (\\<And>n. f n \\<le> x) \\<Longrightarrow> lim f \\<le> x\"\n  for x :: \"'a::linorder_topology\"\n  using LIMSEQ_le_const2[of f \"lim f\" x] by (simp add: convergent_LIMSEQ_iff)\n\nlemma lim_const [simp]: \"lim (\\<lambda>m. a) = a\"\n  by (simp add: limI)\n\n\nsubsubsection \\<open>Increasing and Decreasing Series\\<close>\n\nlemma incseq_le: \"incseq X \\<Longrightarrow> X \\<longlonglongrightarrow> L \\<Longrightarrow> X n \\<le> L\"\n  for L :: \"'a::linorder_topology\"\n  by (metis incseq_def LIMSEQ_le_const)\n\nlemma decseq_ge: \"decseq X \\<Longrightarrow> X \\<longlonglongrightarrow> L \\<Longrightarrow> L \\<le> X n\"\n  for L :: \"'a::linorder_topology\"\n  by (metis decseq_def LIMSEQ_le_const2)\n\n\nsubsection \\<open>First countable topologies\\<close>\n\nclass first_countable_topology = topological_space +\n  assumes first_countable_basis:\n    \"\\<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))\"\n\nlemma (in first_countable_topology) countable_basis_at_decseq:\n  obtains A :: \"nat \\<Rightarrow> 'a set\" where\n    \"\\<And>i. open (A i)\" \"\\<And>i. x \\<in> (A i)\"\n    \"\\<And>S. open S \\<Longrightarrow> x \\<in> S \\<Longrightarrow> eventually (\\<lambda>i. A i \\<subseteq> S) sequentially\"\nproof atomize_elim\n  from first_countable_basis[of x] obtain A :: \"nat \\<Rightarrow> 'a set\"\n    where nhds: \"\\<And>i. open (A i)\" \"\\<And>i. x \\<in> A i\"\n      and incl: \"\\<And>S. open S \\<Longrightarrow> x \\<in> S \\<Longrightarrow> \\<exists>i. A i \\<subseteq> S\"\n    by auto\n  define F where \"F n = (\\<Inter>i\\<le>n. A i)\" for n\n  show \"\\<exists>A. (\\<forall>i. open (A i)) \\<and> (\\<forall>i. x \\<in> A i) \\<and>\n    (\\<forall>S. open S \\<longrightarrow> x \\<in> S \\<longrightarrow> eventually (\\<lambda>i. A i \\<subseteq> S) sequentially)\"\n  proof (safe intro!: exI[of _ F])\n    fix i\n    show \"open (F i)\"\n      using nhds(1) by (auto simp: F_def)\n    show \"x \\<in> F i\"\n      using nhds(2) by (auto simp: F_def)\n  next\n    fix S\n    assume \"open S\" \"x \\<in> S\"\n    from incl[OF this] obtain i where \"F i \\<subseteq> S\"\n      unfolding F_def by auto\n    moreover have \"\\<And>j. i \\<le> j \\<Longrightarrow> F j \\<subseteq> F i\"\n      by (simp add: Inf_superset_mono F_def image_mono)\n    ultimately show \"eventually (\\<lambda>i. F i \\<subseteq> S) sequentially\"\n      by (auto simp: eventually_sequentially)\n  qed\nqed\n\nlemma (in first_countable_topology) nhds_countable:\n  obtains X :: \"nat \\<Rightarrow> 'a set\"\n  where \"decseq X\" \"\\<And>n. open (X n)\" \"\\<And>n. x \\<in> X n\" \"nhds x = (INF n. principal (X n))\"\nproof -\n  from first_countable_basis obtain A :: \"nat \\<Rightarrow> 'a set\"\n    where *: \"\\<And>n. x \\<in> A n\" \"\\<And>n. open (A n)\" \"\\<And>S. open S \\<Longrightarrow> x \\<in> S \\<Longrightarrow> \\<exists>i. A i \\<subseteq> S\"\n    by metis\n  show thesis\n  proof\n    show \"decseq (\\<lambda>n. \\<Inter>i\\<le>n. A i)\"\n      by (simp add: antimono_iff_le_Suc atMost_Suc)\n    show \"x \\<in> (\\<Inter>i\\<le>n. A i)\" \"\\<And>n. open (\\<Inter>i\\<le>n. A i)\" for n\n      using * by auto\n    with * show \"nhds x = (INF n. principal (\\<Inter>i\\<le>n. A i))\"\n      unfolding nhds_def\n      apply (intro INF_eq)\n       apply fastforce\n      apply blast\n      done\n  qed\nqed\n\nlemma (in first_countable_topology) countable_basis:\n  obtains A :: \"nat \\<Rightarrow> 'a set\" where\n    \"\\<And>i. open (A i)\" \"\\<And>i. x \\<in> A i\"\n    \"\\<And>F. (\\<forall>n. F n \\<in> A n) \\<Longrightarrow> F \\<longlonglongrightarrow> x\"\nproof atomize_elim\n  obtain A :: \"nat \\<Rightarrow> 'a set\" where *:\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 (rule countable_basis_at_decseq) blast\n  have \"eventually (\\<lambda>n. F n \\<in> S) sequentially\"\n    if \"\\<forall>n. F n \\<in> A n\" \"open S\" \"x \\<in> S\" for F S\n    using *(3)[of S] that by (auto elim: eventually_mono simp: subset_eq)\n  with * show \"\\<exists>A. (\\<forall>i. open (A i)) \\<and> (\\<forall>i. x \\<in> A i) \\<and> (\\<forall>F. (\\<forall>n. F n \\<in> A n) \\<longrightarrow> F \\<longlonglongrightarrow> x)\"\n    by (intro exI[of _ A]) (auto simp: tendsto_def)\nqed\n\nlemma (in first_countable_topology) sequentially_imp_eventually_nhds_within:\n  assumes \"\\<forall>f. (\\<forall>n. f n \\<in> s) \\<and> f \\<longlonglongrightarrow> a \\<longrightarrow> eventually (\\<lambda>n. P (f n)) sequentially\"\n  shows \"eventually P (inf (nhds a) (principal s))\"\nproof (rule ccontr)\n  obtain A :: \"nat \\<Rightarrow> 'a set\" where *:\n    \"\\<And>i. open (A i)\"\n    \"\\<And>i. a \\<in> A i\"\n    \"\\<And>F. \\<forall>n. F n \\<in> A n \\<Longrightarrow> F \\<longlonglongrightarrow> a\"\n    by (rule countable_basis) blast\n  assume \"\\<not> ?thesis\"\n  with * have \"\\<exists>F. \\<forall>n. F n \\<in> s \\<and> F n \\<in> A n \\<and> \\<not> P (F n)\"\n    unfolding eventually_inf_principal eventually_nhds\n    by (intro choice) fastforce\n  then obtain F where F: \"\\<forall>n. F n \\<in> s\" and \"\\<forall>n. F n \\<in> A n\" and F': \"\\<forall>n. \\<not> P (F n)\"\n    by blast\n  with * have \"F \\<longlonglongrightarrow> a\"\n    by auto\n  then have \"eventually (\\<lambda>n. P (F n)) sequentially\"\n    using assms F by simp\n  then show False\n    by (simp add: F')\nqed\n\nlemma (in first_countable_topology) eventually_nhds_within_iff_sequentially:\n  \"eventually P (inf (nhds a) (principal s)) \\<longleftrightarrow>\n    (\\<forall>f. (\\<forall>n. f n \\<in> s) \\<and> f \\<longlonglongrightarrow> a \\<longrightarrow> eventually (\\<lambda>n. P (f n)) sequentially)\"\nproof (safe intro!: sequentially_imp_eventually_nhds_within)\n  assume \"eventually P (inf (nhds a) (principal s))\"\n  then obtain S where \"open S\" \"a \\<in> S\" \"\\<forall>x\\<in>S. x \\<in> s \\<longrightarrow> P x\"\n    by (auto simp: eventually_inf_principal eventually_nhds)\n  moreover\n  fix f\n  assume \"\\<forall>n. f n \\<in> s\" \"f \\<longlonglongrightarrow> a\"\n  ultimately show \"eventually (\\<lambda>n. P (f n)) sequentially\"\n    by (auto dest!: topological_tendstoD elim: eventually_mono)\nqed\n\nlemma (in first_countable_topology) eventually_nhds_iff_sequentially:\n  \"eventually P (nhds a) \\<longleftrightarrow> (\\<forall>f. f \\<longlonglongrightarrow> a \\<longrightarrow> eventually (\\<lambda>n. P (f n)) sequentially)\"\n  using eventually_nhds_within_iff_sequentially[of P a UNIV] by simp\n\n(*Thanks to S\u00e9bastien Gou\u00ebzel*)\nlemma Inf_as_limit:\n  fixes A::\"'a::{linorder_topology, first_countable_topology, complete_linorder} set\"\n  assumes \"A \\<noteq> {}\"\n  shows \"\\<exists>u. (\\<forall>n. u n \\<in> A) \\<and> u \\<longlonglongrightarrow> Inf A\"\nproof (cases \"Inf A \\<in> A\")\n  case True\n  show ?thesis\n    by (rule exI[of _ \"\\<lambda>n. Inf A\"], auto simp add: True)\nnext\n  case False\n  obtain y where \"y \\<in> A\" using assms by auto\n  then have \"Inf A < y\" using False Inf_lower less_le by auto\n  obtain F :: \"nat \\<Rightarrow> 'a set\" where F: \"\\<And>i. open (F i)\" \"\\<And>i. Inf A \\<in> F i\"\n                                       \"\\<And>u. (\\<forall>n. u n \\<in> F n) \\<Longrightarrow> u \\<longlonglongrightarrow> Inf A\"\n    by (metis first_countable_topology_class.countable_basis)\n  define u where \"u = (\\<lambda>n. SOME z. z \\<in> F n \\<and> z \\<in> A)\"\n  have \"\\<exists>z. z \\<in> U \\<and> z \\<in> A\" if \"Inf A \\<in> U\" \"open U\" for U\n  proof -\n    obtain b where \"b > Inf A\" \"{Inf A ..<b} \\<subseteq> U\"\n      using open_right[OF \\<open>open U\\<close> \\<open>Inf A \\<in> U\\<close> \\<open>Inf A < y\\<close>] by auto\n    obtain z where \"z < b\" \"z \\<in> A\"\n      using \\<open>Inf A < b\\<close> Inf_less_iff by auto\n    then have \"z \\<in> {Inf A ..<b}\"\n      by (simp add: Inf_lower)\n    then show ?thesis using \\<open>z \\<in> A\\<close> \\<open>{Inf A ..<b} \\<subseteq> U\\<close> by auto\n  qed\n  then have *: \"u n \\<in> F n \\<and> u n \\<in> A\" for n\n    using \\<open>Inf A \\<in> F n\\<close> \\<open>open (F n)\\<close> unfolding u_def by (metis (no_types, lifting) someI_ex)\n  then have \"u \\<longlonglongrightarrow> Inf A\" using F(3) by simp\n  then show ?thesis using * by auto\nqed\n\nlemma tendsto_at_iff_sequentially:\n  \"(f \\<longlongrightarrow> a) (at x within s) \\<longleftrightarrow> (\\<forall>X. (\\<forall>i. X i \\<in> s - {x}) \\<longrightarrow> X \\<longlonglongrightarrow> x \\<longrightarrow> ((f \\<circ> X) \\<longlonglongrightarrow> a))\"\n  for f :: \"'a::first_countable_topology \\<Rightarrow> _\"\n  unfolding filterlim_def[of _ \"nhds a\"] le_filter_def eventually_filtermap\n    at_within_def eventually_nhds_within_iff_sequentially comp_def\n  by metis\n\nlemma approx_from_above_dense_linorder:\n  fixes x::\"'a::{dense_linorder, linorder_topology, first_countable_topology}\"\n  assumes \"x < y\"\n  shows \"\\<exists>u. (\\<forall>n. u n > x) \\<and> (u \\<longlonglongrightarrow> x)\"\nproof -\n  obtain A :: \"nat \\<Rightarrow> 'a set\" where A: \"\\<And>i. open (A i)\" \"\\<And>i. x \\<in> A i\"\n                                      \"\\<And>F. (\\<forall>n. F n \\<in> A n) \\<Longrightarrow> F \\<longlonglongrightarrow> x\"\n    by (metis first_countable_topology_class.countable_basis)\n  define u where \"u = (\\<lambda>n. SOME z. z \\<in> A n \\<and> z > x)\"\n  have \"\\<exists>z. z \\<in> U \\<and> x < z\" if \"x \\<in> U\" \"open U\" for U\n    using open_right[OF \\<open>open U\\<close> \\<open>x \\<in> U\\<close> \\<open>x < y\\<close>]\n    by (meson atLeastLessThan_iff dense less_imp_le subset_eq)\n  then have *: \"u n \\<in> A n \\<and> x < u n\" for n\n    using \\<open>x \\<in> A n\\<close> \\<open>open (A n)\\<close> unfolding u_def by (metis (no_types, lifting) someI_ex)\n  then have \"u \\<longlonglongrightarrow> x\" using A(3) by simp\n  then show ?thesis using * by auto\nqed\n\nlemma approx_from_below_dense_linorder:\n  fixes x::\"'a::{dense_linorder, linorder_topology, first_countable_topology}\"\n  assumes \"x > y\"\n  shows \"\\<exists>u. (\\<forall>n. u n < x) \\<and> (u \\<longlonglongrightarrow> x)\"\nproof -\n  obtain A :: \"nat \\<Rightarrow> 'a set\" where A: \"\\<And>i. open (A i)\" \"\\<And>i. x \\<in> A i\"\n                                      \"\\<And>F. (\\<forall>n. F n \\<in> A n) \\<Longrightarrow> F \\<longlonglongrightarrow> x\"\n    by (metis first_countable_topology_class.countable_basis)\n  define u where \"u = (\\<lambda>n. SOME z. z \\<in> A n \\<and> z < x)\"\n  have \"\\<exists>z. z \\<in> U \\<and> z < x\" if \"x \\<in> U\" \"open U\" for U\n    using open_left[OF \\<open>open U\\<close> \\<open>x \\<in> U\\<close> \\<open>x > y\\<close>]\n    by (meson dense greaterThanAtMost_iff less_imp_le subset_eq)\n  then have *: \"u n \\<in> A n \\<and> u n < x\" for n\n    using \\<open>x \\<in> A n\\<close> \\<open>open (A n)\\<close> unfolding u_def by (metis (no_types, lifting) someI_ex)\n  then have \"u \\<longlonglongrightarrow> x\" using A(3) by simp\n  then show ?thesis using * by auto\nqed\n\n\nsubsection \\<open>Function limit at a point\\<close>\n\nabbreviation LIM :: \"('a::topological_space \\<Rightarrow> 'b::topological_space) \\<Rightarrow> 'a \\<Rightarrow> 'b \\<Rightarrow> bool\"\n    (\"((_)/ \\<midarrow>(_)/\\<rightarrow> (_))\" [60, 0, 60] 60)\n  where \"f \\<midarrow>a\\<rightarrow> L \\<equiv> (f \\<longlongrightarrow> L) (at a)\"\n\nlemma tendsto_within_open: \"a \\<in> S \\<Longrightarrow> open S \\<Longrightarrow> (f \\<longlongrightarrow> l) (at a within S) \\<longleftrightarrow> (f \\<midarrow>a\\<rightarrow> l)\"\n  by (simp add: tendsto_def at_within_open[where S = S])\n\nlemma tendsto_within_open_NO_MATCH:\n  \"a \\<in> S \\<Longrightarrow> NO_MATCH UNIV S \\<Longrightarrow> open S \\<Longrightarrow> (f \\<longlongrightarrow> l)(at a within S) \\<longleftrightarrow> (f \\<longlongrightarrow> l)(at a)\"\n  for f :: \"'a::topological_space \\<Rightarrow> 'b::topological_space\"\n  using tendsto_within_open by blast\n\nlemma LIM_const_not_eq[tendsto_intros]: \"k \\<noteq> L \\<Longrightarrow> \\<not> (\\<lambda>x. k) \\<midarrow>a\\<rightarrow> L\"\n  for a :: \"'a::perfect_space\" and k L :: \"'b::t2_space\"\n  by (simp add: tendsto_const_iff)\n\nlemmas LIM_not_zero = LIM_const_not_eq [where L = 0]\n\nlemma LIM_const_eq: \"(\\<lambda>x. k) \\<midarrow>a\\<rightarrow> L \\<Longrightarrow> k = L\"\n  for a :: \"'a::perfect_space\" and k L :: \"'b::t2_space\"\n  by (simp add: tendsto_const_iff)\n\nlemma LIM_unique: \"f \\<midarrow>a\\<rightarrow> L \\<Longrightarrow> f \\<midarrow>a\\<rightarrow> M \\<Longrightarrow> L = M\"\n  for a :: \"'a::perfect_space\" and L M :: \"'b::t2_space\"\n  using at_neq_bot by (rule tendsto_unique)\n\nlemma LIM_Uniq: \"\\<exists>\\<^sub>\\<le>\\<^sub>1L::'b::t2_space. f \\<midarrow>a\\<rightarrow> L\"\n  for a :: \"'a::perfect_space\"\n by (auto simp add: Uniq_def LIM_unique)\n\n\ntext \\<open>Limits are equal for functions equal except at limit point.\\<close>\nlemma LIM_equal: \"\\<forall>x. x \\<noteq> a \\<longrightarrow> f x = g x \\<Longrightarrow> (f \\<midarrow>a\\<rightarrow> l) \\<longleftrightarrow> (g \\<midarrow>a\\<rightarrow> l)\"\n  by (simp add: tendsto_def eventually_at_topological)\n\nlemma LIM_cong: \"a = b \\<Longrightarrow> (\\<And>x. x \\<noteq> b \\<Longrightarrow> f x = g x) \\<Longrightarrow> l = m \\<Longrightarrow> (f \\<midarrow>a\\<rightarrow> l) \\<longleftrightarrow> (g \\<midarrow>b\\<rightarrow> m)\"\n  by (simp add: LIM_equal)\n\nlemma tendsto_cong_limit: \"(f \\<longlongrightarrow> l) F \\<Longrightarrow> k = l \\<Longrightarrow> (f \\<longlongrightarrow> k) F\"\n  by simp\n\nlemma tendsto_at_iff_tendsto_nhds: \"g \\<midarrow>l\\<rightarrow> g l \\<longleftrightarrow> (g \\<longlongrightarrow> g l) (nhds l)\"\n  unfolding tendsto_def eventually_at_filter\n  by (intro ext all_cong imp_cong) (auto elim!: eventually_mono)\n\nlemma tendsto_compose: \"g \\<midarrow>l\\<rightarrow> g l \\<Longrightarrow> (f \\<longlongrightarrow> l) F \\<Longrightarrow> ((\\<lambda>x. g (f x)) \\<longlongrightarrow> g l) F\"\n  unfolding tendsto_at_iff_tendsto_nhds by (rule filterlim_compose[of g])\n\nlemma tendsto_compose_eventually:\n  \"g \\<midarrow>l\\<rightarrow> m \\<Longrightarrow> (f \\<longlongrightarrow> l) F \\<Longrightarrow> eventually (\\<lambda>x. f x \\<noteq> l) F \\<Longrightarrow> ((\\<lambda>x. g (f x)) \\<longlongrightarrow> m) F\"\n  by (rule filterlim_compose[of g _ \"at l\"]) (auto simp add: filterlim_at)\n\nlemma LIM_compose_eventually:\n  assumes \"f \\<midarrow>a\\<rightarrow> b\"\n    and \"g \\<midarrow>b\\<rightarrow> c\"\n    and \"eventually (\\<lambda>x. f x \\<noteq> b) (at a)\"\n  shows \"(\\<lambda>x. g (f x)) \\<midarrow>a\\<rightarrow> c\"\n  using assms(2,1,3) by (rule tendsto_compose_eventually)\n\nlemma tendsto_compose_filtermap: \"((g \\<circ> f) \\<longlongrightarrow> T) F \\<longleftrightarrow> (g \\<longlongrightarrow> T) (filtermap f F)\"\n  by (simp add: filterlim_def filtermap_filtermap comp_def)\n\nlemma tendsto_compose_at:\n  assumes f: \"(f \\<longlongrightarrow> y) F\" and g: \"(g \\<longlongrightarrow> z) (at y)\" and fg: \"eventually (\\<lambda>w. f w = y \\<longrightarrow> g y = z) F\"\n  shows \"((g \\<circ> f) \\<longlongrightarrow> z) F\"\nproof -\n  have \"(\\<forall>\\<^sub>F a in F. f a \\<noteq> y) \\<or> g y = z\"\n    using fg by force\n  moreover have \"(g \\<longlongrightarrow> z) (filtermap f F) \\<or> \\<not> (\\<forall>\\<^sub>F a in F. f a \\<noteq> y)\"\n    by (metis (no_types) filterlim_atI filterlim_def tendsto_mono f g)\n  ultimately show ?thesis\n    by (metis (no_types) f filterlim_compose filterlim_filtermap g tendsto_at_iff_tendsto_nhds tendsto_compose_filtermap)\nqed\n\n\nsubsubsection \\<open>Relation of \\<open>LIM\\<close> and \\<open>LIMSEQ\\<close>\\<close>\n\nlemma (in first_countable_topology) sequentially_imp_eventually_within:\n  \"(\\<forall>f. (\\<forall>n. f n \\<in> s \\<and> f n \\<noteq> a) \\<and> f \\<longlonglongrightarrow> a \\<longrightarrow> eventually (\\<lambda>n. P (f n)) sequentially) \\<Longrightarrow>\n    eventually P (at a within s)\"\n  unfolding at_within_def\n  by (intro sequentially_imp_eventually_nhds_within) auto\n\nlemma (in first_countable_topology) sequentially_imp_eventually_at:\n  \"(\\<forall>f. (\\<forall>n. f n \\<noteq> a) \\<and> f \\<longlonglongrightarrow> a \\<longrightarrow> eventually (\\<lambda>n. P (f n)) sequentially) \\<Longrightarrow> eventually P (at a)\"\n  using sequentially_imp_eventually_within [where s=UNIV] by simp\n\nlemma LIMSEQ_SEQ_conv1:\n  fixes f :: \"'a::topological_space \\<Rightarrow> 'b::topological_space\"\n  assumes f: \"f \\<midarrow>a\\<rightarrow> l\"\n  shows \"\\<forall>S. (\\<forall>n. S n \\<noteq> a) \\<and> S \\<longlonglongrightarrow> a \\<longrightarrow> (\\<lambda>n. f (S n)) \\<longlonglongrightarrow> l\"\n  using tendsto_compose_eventually [OF f, where F=sequentially] by simp\n\nlemma LIMSEQ_SEQ_conv2:\n  fixes f :: \"'a::first_countable_topology \\<Rightarrow> 'b::topological_space\"\n  assumes \"\\<forall>S. (\\<forall>n. S n \\<noteq> a) \\<and> S \\<longlonglongrightarrow> a \\<longrightarrow> (\\<lambda>n. f (S n)) \\<longlonglongrightarrow> l\"\n  shows \"f \\<midarrow>a\\<rightarrow> l\"\n  using assms unfolding tendsto_def [where l=l] by (simp add: sequentially_imp_eventually_at)\n\nlemma LIMSEQ_SEQ_conv: \"(\\<forall>S. (\\<forall>n. S n \\<noteq> a) \\<and> S \\<longlonglongrightarrow> a \\<longrightarrow> (\\<lambda>n. X (S n)) \\<longlonglongrightarrow> L) \\<longleftrightarrow> X \\<midarrow>a\\<rightarrow> L\"\n  for a :: \"'a::first_countable_topology\" and L :: \"'b::topological_space\"\n  using LIMSEQ_SEQ_conv2 LIMSEQ_SEQ_conv1 ..\n\nlemma sequentially_imp_eventually_at_left:\n  fixes a :: \"'a::{linorder_topology,first_countable_topology}\"\n  assumes b[simp]: \"b < a\"\n    and *: \"\\<And>f. (\\<And>n. b < f n) \\<Longrightarrow> (\\<And>n. f n < a) \\<Longrightarrow> incseq f \\<Longrightarrow> f \\<longlonglongrightarrow> a \\<Longrightarrow>\n      eventually (\\<lambda>n. P (f n)) sequentially\"\n  shows \"eventually P (at_left a)\"\nproof (safe intro!: sequentially_imp_eventually_within)\n  fix X\n  assume X: \"\\<forall>n. X n \\<in> {..< a} \\<and> X n \\<noteq> a\" \"X \\<longlonglongrightarrow> a\"\n  show \"eventually (\\<lambda>n. P (X n)) sequentially\"\n  proof (rule ccontr)\n    assume neg: \"\\<not> ?thesis\"\n    have \"\\<exists>s. \\<forall>n. (\\<not> P (X (s n)) \\<and> b < X (s n)) \\<and> (X (s n) \\<le> X (s (Suc n)) \\<and> Suc (s n) \\<le> s (Suc n))\"\n      (is \"\\<exists>s. ?P s\")\n    proof (rule dependent_nat_choice)\n      have \"\\<not> eventually (\\<lambda>n. b < X n \\<longrightarrow> P (X n)) sequentially\"\n        by (intro not_eventually_impI neg order_tendstoD(1) [OF X(2) b])\n      then show \"\\<exists>x. \\<not> P (X x) \\<and> b < X x\"\n        by (auto dest!: not_eventuallyD)\n    next\n      fix x n\n      have \"\\<not> eventually (\\<lambda>n. Suc x \\<le> n \\<longrightarrow> b < X n \\<longrightarrow> X x < X n \\<longrightarrow> P (X n)) sequentially\"\n        using X\n        by (intro not_eventually_impI order_tendstoD(1)[OF X(2)] eventually_ge_at_top neg) auto\n      then show \"\\<exists>n. (\\<not> P (X n) \\<and> b < X n) \\<and> (X x \\<le> X n \\<and> Suc x \\<le> n)\"\n        by (auto dest!: not_eventuallyD)\n    qed\n    then obtain s where \"?P s\" ..\n    with X have \"b < X (s n)\"\n      and \"X (s n) < a\"\n      and \"incseq (\\<lambda>n. X (s n))\"\n      and \"(\\<lambda>n. X (s n)) \\<longlonglongrightarrow> a\"\n      and \"\\<not> P (X (s n))\"\n      for n\n      by (auto simp: strict_mono_Suc_iff Suc_le_eq incseq_Suc_iff\n          intro!: LIMSEQ_subseq_LIMSEQ[OF \\<open>X \\<longlonglongrightarrow> a\\<close>, unfolded comp_def])\n    from *[OF this(1,2,3,4)] this(5) show False\n      by auto\n  qed\nqed\n\nlemma tendsto_at_left_sequentially:\n  fixes a b :: \"'b::{linorder_topology,first_countable_topology}\"\n  assumes \"b < a\"\n  assumes *: \"\\<And>S. (\\<And>n. S n < a) \\<Longrightarrow> (\\<And>n. b < S n) \\<Longrightarrow> incseq S \\<Longrightarrow> S \\<longlonglongrightarrow> a \\<Longrightarrow>\n    (\\<lambda>n. X (S n)) \\<longlonglongrightarrow> L\"\n  shows \"(X \\<longlongrightarrow> L) (at_left a)\"\n  using assms by (simp add: tendsto_def [where l=L] sequentially_imp_eventually_at_left)\n\nlemma sequentially_imp_eventually_at_right:\n  fixes a b :: \"'a::{linorder_topology,first_countable_topology}\"\n  assumes b[simp]: \"a < b\"\n  assumes *: \"\\<And>f. (\\<And>n. a < f n) \\<Longrightarrow> (\\<And>n. f n < b) \\<Longrightarrow> decseq f \\<Longrightarrow> f \\<longlonglongrightarrow> a \\<Longrightarrow>\n    eventually (\\<lambda>n. P (f n)) sequentially\"\n  shows \"eventually P (at_right a)\"\nproof (safe intro!: sequentially_imp_eventually_within)\n  fix X\n  assume X: \"\\<forall>n. X n \\<in> {a <..} \\<and> X n \\<noteq> a\" \"X \\<longlonglongrightarrow> a\"\n  show \"eventually (\\<lambda>n. P (X n)) sequentially\"\n  proof (rule ccontr)\n    assume neg: \"\\<not> ?thesis\"\n    have \"\\<exists>s. \\<forall>n. (\\<not> P (X (s n)) \\<and> X (s n) < b) \\<and> (X (s (Suc n)) \\<le> X (s n) \\<and> Suc (s n) \\<le> s (Suc n))\"\n      (is \"\\<exists>s. ?P s\")\n    proof (rule dependent_nat_choice)\n      have \"\\<not> eventually (\\<lambda>n. X n < b \\<longrightarrow> P (X n)) sequentially\"\n        by (intro not_eventually_impI neg order_tendstoD(2) [OF X(2) b])\n      then show \"\\<exists>x. \\<not> P (X x) \\<and> X x < b\"\n        by (auto dest!: not_eventuallyD)\n    next\n      fix x n\n      have \"\\<not> eventually (\\<lambda>n. Suc x \\<le> n \\<longrightarrow> X n < b \\<longrightarrow> X n < X x \\<longrightarrow> P (X n)) sequentially\"\n        using X\n        by (intro not_eventually_impI order_tendstoD(2)[OF X(2)] eventually_ge_at_top neg) auto\n      then show \"\\<exists>n. (\\<not> P (X n) \\<and> X n < b) \\<and> (X n \\<le> X x \\<and> Suc x \\<le> n)\"\n        by (auto dest!: not_eventuallyD)\n    qed\n    then obtain s where \"?P s\" ..\n    with X have \"a < X (s n)\"\n      and \"X (s n) < b\"\n      and \"decseq (\\<lambda>n. X (s n))\"\n      and \"(\\<lambda>n. X (s n)) \\<longlonglongrightarrow> a\"\n      and \"\\<not> P (X (s n))\"\n      for n\n      by (auto simp: strict_mono_Suc_iff Suc_le_eq decseq_Suc_iff\n          intro!: LIMSEQ_subseq_LIMSEQ[OF \\<open>X \\<longlonglongrightarrow> a\\<close>, unfolded comp_def])\n    from *[OF this(1,2,3,4)] this(5) show False\n      by auto\n  qed\nqed\n\nlemma tendsto_at_right_sequentially:\n  fixes a :: \"_ :: {linorder_topology, first_countable_topology}\"\n  assumes \"a < b\"\n    and *: \"\\<And>S. (\\<And>n. a < S n) \\<Longrightarrow> (\\<And>n. S n < b) \\<Longrightarrow> decseq S \\<Longrightarrow> S \\<longlonglongrightarrow> a \\<Longrightarrow>\n      (\\<lambda>n. X (S n)) \\<longlonglongrightarrow> L\"\n  shows \"(X \\<longlongrightarrow> L) (at_right a)\"\n  using assms by (simp add: tendsto_def [where l=L] sequentially_imp_eventually_at_right)\n\n\nsubsection \\<open>Continuity\\<close>\n\nsubsubsection \\<open>Continuity on a set\\<close>\n\ndefinition continuous_on :: \"'a set \\<Rightarrow> ('a::topological_space \\<Rightarrow> 'b::topological_space) \\<Rightarrow> bool\"\n  where \"continuous_on s f \\<longleftrightarrow> (\\<forall>x\\<in>s. (f \\<longlongrightarrow> f x) (at x within s))\"\n\nlemma continuous_on_cong [cong]:\n  \"s = t \\<Longrightarrow> (\\<And>x. x \\<in> t \\<Longrightarrow> f x = g x) \\<Longrightarrow> continuous_on s f \\<longleftrightarrow> continuous_on t g\"\n  unfolding continuous_on_def\n  by (intro ball_cong filterlim_cong) (auto simp: eventually_at_filter)\n\nlemma continuous_on_cong_simp:\n  \"s = t \\<Longrightarrow> (\\<And>x. x \\<in> t =simp=> f x = g x) \\<Longrightarrow> continuous_on s f \\<longleftrightarrow> continuous_on t g\"\n  unfolding simp_implies_def by (rule continuous_on_cong)\n\nlemma continuous_on_topological:\n  \"continuous_on s f \\<longleftrightarrow>\n    (\\<forall>x\\<in>s. \\<forall>B. open B \\<longrightarrow> f x \\<in> B \\<longrightarrow> (\\<exists>A. open A \\<and> x \\<in> A \\<and> (\\<forall>y\\<in>s. y \\<in> A \\<longrightarrow> f y \\<in> B)))\"\n  unfolding continuous_on_def tendsto_def eventually_at_topological by metis\n\nlemma continuous_on_open_invariant:\n  \"continuous_on s f \\<longleftrightarrow> (\\<forall>B. open B \\<longrightarrow> (\\<exists>A. open A \\<and> A \\<inter> s = f -` B \\<inter> s))\"\nproof safe\n  fix B :: \"'b set\"\n  assume \"continuous_on s f\" \"open B\"\n  then have \"\\<forall>x\\<in>f -` B \\<inter> s. (\\<exists>A. open A \\<and> x \\<in> A \\<and> s \\<inter> A \\<subseteq> f -` B)\"\n    by (auto simp: continuous_on_topological subset_eq Ball_def imp_conjL)\n  then obtain A where \"\\<forall>x\\<in>f -` B \\<inter> s. open (A x) \\<and> x \\<in> A x \\<and> s \\<inter> A x \\<subseteq> f -` B\"\n    unfolding bchoice_iff ..\n  then show \"\\<exists>A. open A \\<and> A \\<inter> s = f -` B \\<inter> s\"\n    by (intro exI[of _ \"\\<Union>x\\<in>f -` B \\<inter> s. A x\"]) auto\nnext\n  assume B: \"\\<forall>B. open B \\<longrightarrow> (\\<exists>A. open A \\<and> A \\<inter> s = f -` B \\<inter> s)\"\n  show \"continuous_on s f\"\n    unfolding continuous_on_topological\n  proof safe\n    fix x B\n    assume \"x \\<in> s\" \"open B\" \"f x \\<in> B\"\n    with B obtain A where A: \"open A\" \"A \\<inter> s = f -` B \\<inter> s\"\n      by auto\n    with \\<open>x \\<in> s\\<close> \\<open>f x \\<in> B\\<close> show \"\\<exists>A. open A \\<and> x \\<in> A \\<and> (\\<forall>y\\<in>s. y \\<in> A \\<longrightarrow> f y \\<in> B)\"\n      by (intro exI[of _ A]) auto\n  qed\nqed\n\nlemma continuous_on_open_vimage:\n  \"open s \\<Longrightarrow> continuous_on s f \\<longleftrightarrow> (\\<forall>B. open B \\<longrightarrow> open (f -` B \\<inter> s))\"\n  unfolding continuous_on_open_invariant\n  by (metis open_Int Int_absorb Int_commute[of s] Int_assoc[of _ _ s])\n\ncorollary continuous_imp_open_vimage:\n  assumes \"continuous_on s f\" \"open s\" \"open B\" \"f -` B \\<subseteq> s\"\n  shows \"open (f -` B)\"\n  by (metis assms continuous_on_open_vimage le_iff_inf)\n\ncorollary open_vimage[continuous_intros]:\n  assumes \"open s\"\n    and \"continuous_on UNIV f\"\n  shows \"open (f -` s)\"\n  using assms by (simp add: continuous_on_open_vimage [OF open_UNIV])\n\nlemma continuous_on_closed_invariant:\n  \"continuous_on s f \\<longleftrightarrow> (\\<forall>B. closed B \\<longrightarrow> (\\<exists>A. closed A \\<and> A \\<inter> s = f -` B \\<inter> s))\"\nproof -\n  have *: \"(\\<And>A. P A \\<longleftrightarrow> Q (- A)) \\<Longrightarrow> (\\<forall>A. P A) \\<longleftrightarrow> (\\<forall>A. Q A)\"\n    for P Q :: \"'b set \\<Rightarrow> bool\"\n    by (metis double_compl)\n  show ?thesis\n    unfolding continuous_on_open_invariant\n    by (intro *) (auto simp: open_closed[symmetric])\nqed\n\nlemma continuous_on_closed_vimage:\n  \"closed s \\<Longrightarrow> continuous_on s f \\<longleftrightarrow> (\\<forall>B. closed B \\<longrightarrow> closed (f -` B \\<inter> s))\"\n  unfolding continuous_on_closed_invariant\n  by (metis closed_Int Int_absorb Int_commute[of s] Int_assoc[of _ _ s])\n\ncorollary closed_vimage_Int[continuous_intros]:\n  assumes \"closed s\"\n    and \"continuous_on t f\"\n    and t: \"closed t\"\n  shows \"closed (f -` s \\<inter> t)\"\n  using assms by (simp add: continuous_on_closed_vimage [OF t])\n\ncorollary closed_vimage[continuous_intros]:\n  assumes \"closed s\"\n    and \"continuous_on UNIV f\"\n  shows \"closed (f -` s)\"\n  using closed_vimage_Int [OF assms] by simp\n\nlemma continuous_on_empty [simp]: \"continuous_on {} f\"\n  by (simp add: continuous_on_def)\n\nlemma continuous_on_sing [simp]: \"continuous_on {x} f\"\n  by (simp add: continuous_on_def at_within_def)\n\nlemma continuous_on_open_Union:\n  \"(\\<And>s. s \\<in> S \\<Longrightarrow> open s) \\<Longrightarrow> (\\<And>s. s \\<in> S \\<Longrightarrow> continuous_on s f) \\<Longrightarrow> continuous_on (\\<Union>S) f\"\n  unfolding continuous_on_def\n  by safe (metis open_Union at_within_open UnionI)\n\nlemma continuous_on_open_UN:\n  \"(\\<And>s. s \\<in> S \\<Longrightarrow> open (A s)) \\<Longrightarrow> (\\<And>s. s \\<in> S \\<Longrightarrow> continuous_on (A s) f) \\<Longrightarrow>\n    continuous_on (\\<Union>s\\<in>S. A s) f\"\n  by (rule continuous_on_open_Union) auto\n\nlemma continuous_on_open_Un:\n  \"open s \\<Longrightarrow> open t \\<Longrightarrow> continuous_on s f \\<Longrightarrow> continuous_on t f \\<Longrightarrow> continuous_on (s \\<union> t) f\"\n  using continuous_on_open_Union [of \"{s,t}\"] by auto\n\nlemma continuous_on_closed_Un:\n  \"closed s \\<Longrightarrow> closed t \\<Longrightarrow> continuous_on s f \\<Longrightarrow> continuous_on t f \\<Longrightarrow> continuous_on (s \\<union> t) f\"\n  by (auto simp add: continuous_on_closed_vimage closed_Un Int_Un_distrib)\n\nlemma continuous_on_closed_Union:\n  assumes \"finite I\"\n    \"\\<And>i. i \\<in> I \\<Longrightarrow> closed (U i)\"\n    \"\\<And>i. i \\<in> I \\<Longrightarrow> continuous_on (U i) f\"\n  shows \"continuous_on (\\<Union> i \\<in> I. U i) f\"\n  using assms\n  by (induction I) (auto intro!: continuous_on_closed_Un)\n\nlemma continuous_on_If:\n  assumes closed: \"closed s\" \"closed t\"\n    and cont: \"continuous_on s f\" \"continuous_on t g\"\n    and P: \"\\<And>x. x \\<in> s \\<Longrightarrow> \\<not> P x \\<Longrightarrow> f x = g x\" \"\\<And>x. x \\<in> t \\<Longrightarrow> P x \\<Longrightarrow> f x = g x\"\n  shows \"continuous_on (s \\<union> t) (\\<lambda>x. if P x then f x else g x)\"\n    (is \"continuous_on _ ?h\")\nproof-\n  from P have \"\\<forall>x\\<in>s. f x = ?h x\" \"\\<forall>x\\<in>t. g x = ?h x\"\n    by auto\n  with cont have \"continuous_on s ?h\" \"continuous_on t ?h\"\n    by simp_all\n  with closed show ?thesis\n    by (rule continuous_on_closed_Un)\nqed\n\nlemma continuous_on_cases:\n  \"closed s \\<Longrightarrow> closed t \\<Longrightarrow> continuous_on s f \\<Longrightarrow> continuous_on t g \\<Longrightarrow>\n    \\<forall>x. (x\\<in>s \\<and> \\<not> P x) \\<or> (x \\<in> t \\<and> P x) \\<longrightarrow> f x = g x \\<Longrightarrow>\n    continuous_on (s \\<union> t) (\\<lambda>x. if P x then f x else g x)\"\n  by (rule continuous_on_If) auto\n\nlemma continuous_on_id[continuous_intros,simp]: \"continuous_on s (\\<lambda>x. x)\"\n  unfolding continuous_on_def by fast\n\nlemma continuous_on_id'[continuous_intros,simp]: \"continuous_on s id\"\n  unfolding continuous_on_def id_def by fast\n\nlemma continuous_on_const[continuous_intros,simp]: \"continuous_on s (\\<lambda>x. c)\"\n  unfolding continuous_on_def by auto\n\nlemma continuous_on_subset: \"continuous_on s f \\<Longrightarrow> t \\<subseteq> s \\<Longrightarrow> continuous_on t f\"\n  unfolding continuous_on_def\n  by (metis subset_eq tendsto_within_subset)\n\nlemma continuous_on_compose[continuous_intros]:\n  \"continuous_on s f \\<Longrightarrow> continuous_on (f ` s) g \\<Longrightarrow> continuous_on s (g \\<circ> f)\"\n  unfolding continuous_on_topological by simp metis\n\nlemma continuous_on_compose2:\n  \"continuous_on t g \\<Longrightarrow> continuous_on s f \\<Longrightarrow> f ` s \\<subseteq> t \\<Longrightarrow> continuous_on s (\\<lambda>x. g (f x))\"\n  using continuous_on_compose[of s f g] continuous_on_subset by (force simp add: comp_def)\n\nlemma continuous_on_generate_topology:\n  assumes *: \"open = generate_topology X\"\n    and **: \"\\<And>B. B \\<in> X \\<Longrightarrow> \\<exists>C. open C \\<and> C \\<inter> A = f -` B \\<inter> A\"\n  shows \"continuous_on A f\"\n  unfolding continuous_on_open_invariant\nproof safe\n  fix B :: \"'a set\"\n  assume \"open B\"\n  then show \"\\<exists>C. open C \\<and> C \\<inter> A = f -` B \\<inter> A\"\n    unfolding *\n  proof induct\n    case (UN K)\n    then obtain C where \"\\<And>k. k \\<in> K \\<Longrightarrow> open (C k)\" \"\\<And>k. k \\<in> K \\<Longrightarrow> C k \\<inter> A = f -` k \\<inter> A\"\n      by metis\n    then show ?case\n      by (intro exI[of _ \"\\<Union>k\\<in>K. C k\"]) blast\n  qed (auto intro: **)\nqed\n\nlemma continuous_onI_mono:\n  fixes f :: \"'a::linorder_topology \\<Rightarrow> 'b::{dense_order,linorder_topology}\"\n  assumes \"open (f`A)\"\n    and mono: \"\\<And>x y. x \\<in> A \\<Longrightarrow> y \\<in> A \\<Longrightarrow> x \\<le> y \\<Longrightarrow> f x \\<le> f y\"\n  shows \"continuous_on A f\"\nproof (rule continuous_on_generate_topology[OF open_generated_order], safe)\n  have monoD: \"\\<And>x y. x \\<in> A \\<Longrightarrow> y \\<in> A \\<Longrightarrow> f x < f y \\<Longrightarrow> x < y\"\n    by (auto simp: not_le[symmetric] mono)\n  have \"\\<exists>x. x \\<in> A \\<and> f x < b \\<and> a < x\" if a: \"a \\<in> A\" and fa: \"f a < b\" for a b\n  proof -\n    obtain y where \"f a < y\" \"{f a ..< y} \\<subseteq> f`A\"\n      using open_right[OF \\<open>open (f`A)\\<close>, of \"f a\" b] a fa\n      by auto\n    obtain z where z: \"f a < z\" \"z < min b y\"\n      using dense[of \"f a\" \"min b y\"] \\<open>f a < y\\<close> \\<open>f a < b\\<close> by auto\n    then obtain c where \"z = f c\" \"c \\<in> A\"\n      using \\<open>{f a ..< y} \\<subseteq> f`A\\<close>[THEN subsetD, of z] by (auto simp: less_imp_le)\n    with a z show ?thesis\n      by (auto intro!: exI[of _ c] simp: monoD)\n  qed\n  then show \"\\<exists>C. open C \\<and> C \\<inter> A = f -` {..<b} \\<inter> A\" for b\n    by (intro exI[of _ \"(\\<Union>x\\<in>{x\\<in>A. f x < b}. {..< x})\"])\n       (auto intro: le_less_trans[OF mono] less_imp_le)\n\n  have \"\\<exists>x. x \\<in> A \\<and> b < f x \\<and> x < a\" if a: \"a \\<in> A\" and fa: \"b < f a\" for a b\n  proof -\n    note a fa\n    moreover\n    obtain y where \"y < f a\" \"{y <.. f a} \\<subseteq> f`A\"\n      using open_left[OF \\<open>open (f`A)\\<close>, of \"f a\" b]  a fa\n      by auto\n    then obtain z where z: \"max b y < z\" \"z < f a\"\n      using dense[of \"max b y\" \"f a\"] \\<open>y < f a\\<close> \\<open>b < f a\\<close> by auto\n    then obtain c where \"z = f c\" \"c \\<in> A\"\n      using \\<open>{y <.. f a} \\<subseteq> f`A\\<close>[THEN subsetD, of z] by (auto simp: less_imp_le)\n    with a z show ?thesis\n      by (auto intro!: exI[of _ c] simp: monoD)\n  qed\n  then show \"\\<exists>C. open C \\<and> C \\<inter> A = f -` {b <..} \\<inter> A\" for b\n    by (intro exI[of _ \"(\\<Union>x\\<in>{x\\<in>A. b < f x}. {x <..})\"])\n       (auto intro: less_le_trans[OF _ mono] less_imp_le)\nqed\n\nlemma continuous_on_IccI:\n  \"\\<lbrakk>(f \\<longlongrightarrow> f a) (at_right a);\n    (f \\<longlongrightarrow> f b) (at_left b);\n    (\\<And>x. a < x \\<Longrightarrow> x < b \\<Longrightarrow> f \\<midarrow>x\\<rightarrow> f x); a < b\\<rbrakk> \\<Longrightarrow>\n    continuous_on {a .. b} f\"\n  for a::\"'a::linorder_topology\"\n  using at_within_open[of _ \"{a<..<b}\"]\n  by (auto simp: continuous_on_def at_within_Icc_at_right at_within_Icc_at_left le_less\n      at_within_Icc_at)\n\nlemma\n  fixes a b::\"'a::linorder_topology\"\n  assumes \"continuous_on {a .. b} f\" \"a < b\"\n  shows continuous_on_Icc_at_rightD: \"(f \\<longlongrightarrow> f a) (at_right a)\"\n    and continuous_on_Icc_at_leftD: \"(f \\<longlongrightarrow> f b) (at_left b)\"\n  using assms\n  by (auto simp: at_within_Icc_at_right at_within_Icc_at_left continuous_on_def\n      dest: bspec[where x=a] bspec[where x=b])\n\nlemma continuous_on_discrete [simp]:\n  \"continuous_on A (f :: 'a :: discrete_topology \\<Rightarrow> _)\"\n  by (auto simp: continuous_on_def at_discrete)\n\nsubsubsection \\<open>Continuity at a point\\<close>\n\ndefinition continuous :: \"'a::t2_space filter \\<Rightarrow> ('a \\<Rightarrow> 'b::topological_space) \\<Rightarrow> bool\"\n  where \"continuous F f \\<longleftrightarrow> (f \\<longlongrightarrow> f (Lim F (\\<lambda>x. x))) F\"\n\nlemma continuous_bot[continuous_intros, simp]: \"continuous bot f\"\n  unfolding continuous_def by auto\n\nlemma continuous_trivial_limit: \"trivial_limit net \\<Longrightarrow> continuous net f\"\n  by simp\n\nlemma continuous_within: \"continuous (at x within s) f \\<longleftrightarrow> (f \\<longlongrightarrow> f x) (at x within s)\"\n  by (cases \"trivial_limit (at x within s)\") (auto simp add: Lim_ident_at continuous_def)\n\nlemma continuous_within_topological:\n  \"continuous (at x within s) f \\<longleftrightarrow>\n    (\\<forall>B. open B \\<longrightarrow> f x \\<in> B \\<longrightarrow> (\\<exists>A. open A \\<and> x \\<in> A \\<and> (\\<forall>y\\<in>s. y \\<in> A \\<longrightarrow> f y \\<in> B)))\"\n  unfolding continuous_within tendsto_def eventually_at_topological by metis\n\nlemma continuous_within_compose[continuous_intros]:\n  \"continuous (at x within s) f \\<Longrightarrow> continuous (at (f x) within f ` s) g \\<Longrightarrow>\n    continuous (at x within s) (g \\<circ> f)\"\n  by (simp add: continuous_within_topological) metis\n\nlemma continuous_within_compose2:\n  \"continuous (at x within s) f \\<Longrightarrow> continuous (at (f x) within f ` s) g \\<Longrightarrow>\n    continuous (at x within s) (\\<lambda>x. g (f x))\"\n  using continuous_within_compose[of x s f g] by (simp add: comp_def)\n\nlemma continuous_at: \"continuous (at x) f \\<longleftrightarrow> f \\<midarrow>x\\<rightarrow> f x\"\n  using continuous_within[of x UNIV f] by simp\n\nlemma continuous_ident[continuous_intros, simp]: \"continuous (at x within S) (\\<lambda>x. x)\"\n  unfolding continuous_within by (rule tendsto_ident_at)\n\nlemma continuous_id[continuous_intros, simp]: \"continuous (at x within S) id\"\n  by (simp add: id_def)\n\nlemma continuous_const[continuous_intros, simp]: \"continuous F (\\<lambda>x. c)\"\n  unfolding continuous_def by (rule tendsto_const)\n\nlemma continuous_on_eq_continuous_within:\n  \"continuous_on s f \\<longleftrightarrow> (\\<forall>x\\<in>s. continuous (at x within s) f)\"\n  unfolding continuous_on_def continuous_within ..\n\nlemma continuous_discrete [simp]:\n  \"continuous (at x within A) (f :: 'a :: discrete_topology \\<Rightarrow> _)\"\n  by (auto simp: continuous_def at_discrete)\n\nabbreviation isCont :: \"('a::t2_space \\<Rightarrow> 'b::topological_space) \\<Rightarrow> 'a \\<Rightarrow> bool\"\n  where \"isCont f a \\<equiv> continuous (at a) f\"\n\nlemma isCont_def: \"isCont f a \\<longleftrightarrow> f \\<midarrow>a\\<rightarrow> f a\"\n  by (rule continuous_at)\n\nlemma isContD: \"isCont f x \\<Longrightarrow> f \\<midarrow>x\\<rightarrow> f x\"\n  by (simp add: isCont_def)\n\nlemma isCont_cong:\n  assumes \"eventually (\\<lambda>x. f x = g x) (nhds x)\"\n  shows \"isCont f x \\<longleftrightarrow> isCont g x\"\nproof -\n  from assms have [simp]: \"f x = g x\"\n    by (rule eventually_nhds_x_imp_x)\n  from assms have \"eventually (\\<lambda>x. f x = g x) (at x)\"\n    by (auto simp: eventually_at_filter elim!: eventually_mono)\n  with assms have \"isCont f x \\<longleftrightarrow> isCont g x\" unfolding isCont_def\n    by (intro filterlim_cong) (auto elim!: eventually_mono)\n  with assms show ?thesis by simp\nqed\n\nlemma continuous_at_imp_continuous_at_within: \"isCont f x \\<Longrightarrow> continuous (at x within s) f\"\n  by (auto intro: tendsto_mono at_le simp: continuous_at continuous_within)\n\nlemma continuous_on_eq_continuous_at: \"open s \\<Longrightarrow> continuous_on s f \\<longleftrightarrow> (\\<forall>x\\<in>s. isCont f x)\"\n  by (simp add: continuous_on_def continuous_at at_within_open[of _ s])\n\nlemma continuous_within_open: \"a \\<in> A \\<Longrightarrow> open A \\<Longrightarrow> continuous (at a within A) f \\<longleftrightarrow> isCont f a\"\n  by (simp add: at_within_open_NO_MATCH)\n\nlemma continuous_at_imp_continuous_on: \"\\<forall>x\\<in>s. isCont f x \\<Longrightarrow> continuous_on s f\"\n  by (auto intro: continuous_at_imp_continuous_at_within simp: continuous_on_eq_continuous_within)\n\nlemma isCont_o2: \"isCont f a \\<Longrightarrow> isCont g (f a) \\<Longrightarrow> isCont (\\<lambda>x. g (f x)) a\"\n  unfolding isCont_def by (rule tendsto_compose)\n\nlemma continuous_at_compose[continuous_intros]: \"isCont f a \\<Longrightarrow> isCont g (f a) \\<Longrightarrow> isCont (g \\<circ> f) a\"\n  unfolding o_def by (rule isCont_o2)\n\nlemma isCont_tendsto_compose: \"isCont g l \\<Longrightarrow> (f \\<longlongrightarrow> l) F \\<Longrightarrow> ((\\<lambda>x. g (f x)) \\<longlongrightarrow> g l) F\"\n  unfolding isCont_def by (rule tendsto_compose)\n\nlemma continuous_on_tendsto_compose:\n  assumes f_cont: \"continuous_on s f\"\n    and g: \"(g \\<longlongrightarrow> l) F\"\n    and l: \"l \\<in> s\"\n    and ev: \"\\<forall>\\<^sub>Fx in F. g x \\<in> s\"\n  shows \"((\\<lambda>x. f (g x)) \\<longlongrightarrow> f l) F\"\nproof -\n  from f_cont l have f: \"(f \\<longlongrightarrow> f l) (at l within s)\"\n    by (simp add: continuous_on_def)\n  have i: \"((\\<lambda>x. if g x = l then f l else f (g x)) \\<longlongrightarrow> f l) F\"\n    by (rule filterlim_If)\n       (auto intro!: filterlim_compose[OF f] eventually_conj tendsto_mono[OF _ g]\n             simp: filterlim_at eventually_inf_principal eventually_mono[OF ev])\n  show ?thesis\n    by (rule filterlim_cong[THEN iffD1[OF _ i]]) auto\nqed\n\nlemma continuous_within_compose3:\n  \"isCont g (f x) \\<Longrightarrow> continuous (at x within s) f \\<Longrightarrow> continuous (at x within s) (\\<lambda>x. g (f x))\"\n  using continuous_at_imp_continuous_at_within continuous_within_compose2 by blast\n\nlemma filtermap_nhds_open_map:\n  assumes cont: \"isCont f a\"\n    and open_map: \"\\<And>S. open S \\<Longrightarrow> open (f`S)\"\n  shows \"filtermap f (nhds a) = nhds (f a)\"\n  unfolding filter_eq_iff\nproof safe\n  fix P\n  assume \"eventually P (filtermap f (nhds a))\"\n  then obtain S where \"open S\" \"a \\<in> S\" \"\\<forall>x\\<in>S. P (f x)\"\n    by (auto simp: eventually_filtermap eventually_nhds)\n  then show \"eventually P (nhds (f a))\"\n    unfolding eventually_nhds by (intro exI[of _ \"f`S\"]) (auto intro!: open_map)\nqed (metis filterlim_iff tendsto_at_iff_tendsto_nhds isCont_def eventually_filtermap cont)\n\nlemma continuous_at_split:\n  \"continuous (at x) f \\<longleftrightarrow> continuous (at_left x) f \\<and> continuous (at_right x) f\"\n  for x :: \"'a::linorder_topology\"\n  by (simp add: continuous_within filterlim_at_split)\n\nlemma continuous_on_max [continuous_intros]:\n  fixes f g :: \"'a::topological_space \\<Rightarrow> 'b::linorder_topology\"\n  shows \"continuous_on A f \\<Longrightarrow> continuous_on A g \\<Longrightarrow> continuous_on A (\\<lambda>x. max (f x) (g x))\"\n  by (auto simp: continuous_on_def intro!: tendsto_max)\n\nlemma continuous_on_min [continuous_intros]:\n  fixes f g :: \"'a::topological_space \\<Rightarrow> 'b::linorder_topology\"\n  shows \"continuous_on A f \\<Longrightarrow> continuous_on A g \\<Longrightarrow> continuous_on A (\\<lambda>x. min (f x) (g x))\"\n  by (auto simp: continuous_on_def intro!: tendsto_min)\n\nlemma continuous_max [continuous_intros]:\n  fixes f :: \"'a::t2_space \\<Rightarrow> 'b::linorder_topology\"\n  shows \"\\<lbrakk>continuous F f; continuous F g\\<rbrakk> \\<Longrightarrow> continuous F (\\<lambda>x. (max (f x) (g x)))\"\n  by (simp add: tendsto_max continuous_def)\n\nlemma continuous_min [continuous_intros]:\n  fixes f :: \"'a::t2_space \\<Rightarrow> 'b::linorder_topology\"\n  shows \"\\<lbrakk>continuous F f; continuous F g\\<rbrakk> \\<Longrightarrow> continuous F (\\<lambda>x. (min (f x) (g x)))\"\n  by (simp add: tendsto_min continuous_def)\n\ntext \\<open>\n  The following open/closed Collect lemmas are ported from\n  S\u00e9bastien Gou\u00ebzel's \\<open>Ergodic_Theory\\<close>.\n\\<close>\nlemma open_Collect_neq:\n  fixes f g :: \"'a::topological_space \\<Rightarrow> 'b::t2_space\"\n  assumes f: \"continuous_on UNIV f\" and g: \"continuous_on UNIV g\"\n  shows \"open {x. f x \\<noteq> g x}\"\nproof (rule openI)\n  fix t\n  assume \"t \\<in> {x. f x \\<noteq> g x}\"\n  then obtain U V where *: \"open U\" \"open V\" \"f t \\<in> U\" \"g t \\<in> V\" \"U \\<inter> V = {}\"\n    by (auto simp add: separation_t2)\n  with open_vimage[OF \\<open>open U\\<close> f] open_vimage[OF \\<open>open V\\<close> g]\n  show \"\\<exists>T. open T \\<and> t \\<in> T \\<and> T \\<subseteq> {x. f x \\<noteq> g x}\"\n    by (intro exI[of _ \"f -` U \\<inter> g -` V\"]) auto\nqed\n\nlemma closed_Collect_eq:\n  fixes f g :: \"'a::topological_space \\<Rightarrow> 'b::t2_space\"\n  assumes f: \"continuous_on UNIV f\" and g: \"continuous_on UNIV g\"\n  shows \"closed {x. f x = g x}\"\n  using open_Collect_neq[OF f g] by (simp add: closed_def Collect_neg_eq)\n\nlemma open_Collect_less:\n  fixes f g :: \"'a::topological_space \\<Rightarrow> 'b::linorder_topology\"\n  assumes f: \"continuous_on UNIV f\" and g: \"continuous_on UNIV g\"\n  shows \"open {x. f x < g x}\"\nproof (rule openI)\n  fix t\n  assume t: \"t \\<in> {x. f x < g x}\"\n  show \"\\<exists>T. open T \\<and> t \\<in> T \\<and> T \\<subseteq> {x. f x < g x}\"\n  proof (cases \"\\<exists>z. f t < z \\<and> z < g t\")\n    case True\n    then obtain z where \"f t < z \\<and> z < g t\" by blast\n    then show ?thesis\n      using open_vimage[OF _ f, of \"{..< z}\"] open_vimage[OF _ g, of \"{z <..}\"]\n      by (intro exI[of _ \"f -` {..<z} \\<inter> g -` {z<..}\"]) auto\n  next\n    case False\n    then have *: \"{g t ..} = {f t <..}\" \"{..< g t} = {.. f t}\"\n      using t by (auto intro: leI)\n    show ?thesis\n      using open_vimage[OF _ f, of \"{..< g t}\"] open_vimage[OF _ g, of \"{f t <..}\"] t\n      apply (intro exI[of _ \"f -` {..< g t} \\<inter> g -` {f t<..}\"])\n      apply (simp add: open_Int)\n      apply (auto simp add: *)\n      done\n  qed\nqed\n\nlemma closed_Collect_le:\n  fixes f g :: \"'a :: topological_space \\<Rightarrow> 'b::linorder_topology\"\n  assumes f: \"continuous_on UNIV f\"\n    and g: \"continuous_on UNIV g\"\n  shows \"closed {x. f x \\<le> g x}\"\n  using open_Collect_less [OF g f]\n  by (simp add: closed_def Collect_neg_eq[symmetric] not_le)\n\n\nsubsubsection \\<open>Open-cover compactness\\<close>\n\ncontext topological_space\nbegin\n\ndefinition compact :: \"'a set \\<Rightarrow> bool\" where\ncompact_eq_Heine_Borel:  (* This name is used for backwards compatibility *)\n    \"compact S \\<longleftrightarrow> (\\<forall>C. (\\<forall>c\\<in>C. open c) \\<and> S \\<subseteq> \\<Union>C \\<longrightarrow> (\\<exists>D\\<subseteq>C. finite D \\<and> S \\<subseteq> \\<Union>D))\"\n\nlemma compactI:\n  assumes \"\\<And>C. \\<forall>t\\<in>C. open t \\<Longrightarrow> s \\<subseteq> \\<Union>C \\<Longrightarrow> \\<exists>C'. C' \\<subseteq> C \\<and> finite C' \\<and> s \\<subseteq> \\<Union>C'\"\n  shows \"compact s\"\n  unfolding compact_eq_Heine_Borel using assms by metis\n\nlemma compact_empty[simp]: \"compact {}\"\n  by (auto intro!: compactI)\n\nlemma compactE: (*related to COMPACT_IMP_HEINE_BOREL in HOL Light*)\n  assumes \"compact S\" \"S \\<subseteq> \\<Union>\\<T>\" \"\\<And>B. B \\<in> \\<T> \\<Longrightarrow> open B\"\n  obtains \\<T>' where \"\\<T>' \\<subseteq> \\<T>\" \"finite \\<T>'\" \"S \\<subseteq> \\<Union>\\<T>'\"\n  by (meson assms compact_eq_Heine_Borel)\n\nlemma compactE_image:\n  assumes \"compact S\"\n    and opn: \"\\<And>T. T \\<in> C \\<Longrightarrow> open (f T)\"\n    and S: \"S \\<subseteq> (\\<Union>c\\<in>C. f c)\"\n  obtains C' where \"C' \\<subseteq> C\" and \"finite C'\" and \"S \\<subseteq> (\\<Union>c\\<in>C'. f c)\"\n    apply (rule compactE[OF \\<open>compact S\\<close> S])\n    using opn apply force\n    by (metis finite_subset_image)\n\nlemma compact_Int_closed [intro]:\n  assumes \"compact S\"\n    and \"closed T\"\n  shows \"compact (S \\<inter> T)\"\nproof (rule compactI)\n  fix C\n  assume C: \"\\<forall>c\\<in>C. open c\"\n  assume cover: \"S \\<inter> T \\<subseteq> \\<Union>C\"\n  from C \\<open>closed T\\<close> have \"\\<forall>c\\<in>C \\<union> {- T}. open c\"\n    by auto\n  moreover from cover have \"S \\<subseteq> \\<Union>(C \\<union> {- T})\"\n    by auto\n  ultimately have \"\\<exists>D\\<subseteq>C \\<union> {- T}. finite D \\<and> S \\<subseteq> \\<Union>D\"\n    using \\<open>compact S\\<close> unfolding compact_eq_Heine_Borel by auto\n  then obtain D where \"D \\<subseteq> C \\<union> {- T} \\<and> finite D \\<and> S \\<subseteq> \\<Union>D\" ..\n  then show \"\\<exists>D\\<subseteq>C. finite D \\<and> S \\<inter> T \\<subseteq> \\<Union>D\"\n    by (intro exI[of _ \"D - {-T}\"]) auto\nqed\n\nlemma compact_diff: \"\\<lbrakk>compact S; open T\\<rbrakk> \\<Longrightarrow> compact(S - T)\"\n  by (simp add: Diff_eq compact_Int_closed open_closed)\n\nlemma inj_setminus: \"inj_on uminus (A::'a set set)\"\n  by (auto simp: inj_on_def)\n\n\nsubsection \\<open>Finite intersection property\\<close>\n\nlemma compact_fip:\n  \"compact U \\<longleftrightarrow>\n    (\\<forall>A. (\\<forall>a\\<in>A. closed a) \\<longrightarrow> (\\<forall>B \\<subseteq> A. finite B \\<longrightarrow> U \\<inter> \\<Inter>B \\<noteq> {}) \\<longrightarrow> U \\<inter> \\<Inter>A \\<noteq> {})\"\n  (is \"_ \\<longleftrightarrow> ?R\")\nproof (safe intro!: compact_eq_Heine_Borel[THEN iffD2])\n  fix A\n  assume \"compact U\"\n  assume A: \"\\<forall>a\\<in>A. closed a\" \"U \\<inter> \\<Inter>A = {}\"\n  assume fin: \"\\<forall>B \\<subseteq> A. finite B \\<longrightarrow> U \\<inter> \\<Inter>B \\<noteq> {}\"\n  from A have \"(\\<forall>a\\<in>uminus`A. open a) \\<and> U \\<subseteq> \\<Union>(uminus`A)\"\n    by auto\n  with \\<open>compact U\\<close> obtain B where \"B \\<subseteq> A\" \"finite (uminus`B)\" \"U \\<subseteq> \\<Union>(uminus`B)\"\n    unfolding compact_eq_Heine_Borel by (metis subset_image_iff)\n  with fin[THEN spec, of B] show False\n    by (auto dest: finite_imageD intro: inj_setminus)\nnext\n  fix A\n  assume ?R\n  assume \"\\<forall>a\\<in>A. open a\" \"U \\<subseteq> \\<Union>A\"\n  then have \"U \\<inter> \\<Inter>(uminus`A) = {}\" \"\\<forall>a\\<in>uminus`A. closed a\"\n    by auto\n  with \\<open>?R\\<close> obtain B where \"B \\<subseteq> A\" \"finite (uminus`B)\" \"U \\<inter> \\<Inter>(uminus`B) = {}\"\n    by (metis subset_image_iff)\n  then show \"\\<exists>T\\<subseteq>A. finite T \\<and> U \\<subseteq> \\<Union>T\"\n    by (auto intro!: exI[of _ B] inj_setminus dest: finite_imageD)\nqed\n\nlemma compact_imp_fip:\n  assumes \"compact S\"\n    and \"\\<And>T. T \\<in> F \\<Longrightarrow> closed T\"\n    and \"\\<And>F'. finite F' \\<Longrightarrow> F' \\<subseteq> F \\<Longrightarrow> S \\<inter> (\\<Inter>F') \\<noteq> {}\"\n  shows \"S \\<inter> (\\<Inter>F) \\<noteq> {}\"\n  using assms unfolding compact_fip by auto\n\nlemma compact_imp_fip_image:\n  assumes \"compact s\"\n    and P: \"\\<And>i. i \\<in> I \\<Longrightarrow> closed (f i)\"\n    and Q: \"\\<And>I'. finite I' \\<Longrightarrow> I' \\<subseteq> I \\<Longrightarrow> (s \\<inter> (\\<Inter>i\\<in>I'. f i) \\<noteq> {})\"\n  shows \"s \\<inter> (\\<Inter>i\\<in>I. f i) \\<noteq> {}\"\nproof -\n  from P have \"\\<forall>i \\<in> f ` I. closed i\"\n    by blast\n  moreover have \"\\<forall>A. finite A \\<and> A \\<subseteq> f ` I \\<longrightarrow> (s \\<inter> (\\<Inter>A) \\<noteq> {})\"\n    by (metis Q finite_subset_image)\n  ultimately show \"s \\<inter> (\\<Inter>(f ` I)) \\<noteq> {}\"\n    by (metis \\<open>compact s\\<close> compact_imp_fip)\nqed\n\nend\n\nlemma (in t2_space) compact_imp_closed:\n  assumes \"compact s\"\n  shows \"closed s\"\n  unfolding closed_def\nproof (rule openI)\n  fix y\n  assume \"y \\<in> - s\"\n  let ?C = \"\\<Union>x\\<in>s. {u. open u \\<and> x \\<in> u \\<and> eventually (\\<lambda>y. y \\<notin> u) (nhds y)}\"\n  have \"s \\<subseteq> \\<Union>?C\"\n  proof\n    fix x\n    assume \"x \\<in> s\"\n    with \\<open>y \\<in> - s\\<close> have \"x \\<noteq> y\" by clarsimp\n    then have \"\\<exists>u v. open u \\<and> open v \\<and> x \\<in> u \\<and> y \\<in> v \\<and> u \\<inter> v = {}\"\n      by (rule hausdorff)\n    with \\<open>x \\<in> s\\<close> show \"x \\<in> \\<Union>?C\"\n      unfolding eventually_nhds by auto\n  qed\n  then obtain D where \"D \\<subseteq> ?C\" and \"finite D\" and \"s \\<subseteq> \\<Union>D\"\n    by (rule compactE [OF \\<open>compact s\\<close>]) auto\n  from \\<open>D \\<subseteq> ?C\\<close> have \"\\<forall>x\\<in>D. eventually (\\<lambda>y. y \\<notin> x) (nhds y)\"\n    by auto\n  with \\<open>finite D\\<close> have \"eventually (\\<lambda>y. y \\<notin> \\<Union>D) (nhds y)\"\n    by (simp add: eventually_ball_finite)\n  with \\<open>s \\<subseteq> \\<Union>D\\<close> have \"eventually (\\<lambda>y. y \\<notin> s) (nhds y)\"\n    by (auto elim!: eventually_mono)\n  then show \"\\<exists>t. open t \\<and> y \\<in> t \\<and> t \\<subseteq> - s\"\n    by (simp add: eventually_nhds subset_eq)\nqed\n\nlemma compact_continuous_image:\n  assumes f: \"continuous_on s f\"\n    and s: \"compact s\"\n  shows \"compact (f ` s)\"\nproof (rule compactI)\n  fix C\n  assume \"\\<forall>c\\<in>C. open c\" and cover: \"f`s \\<subseteq> \\<Union>C\"\n  with f have \"\\<forall>c\\<in>C. \\<exists>A. open A \\<and> A \\<inter> s = f -` c \\<inter> s\"\n    unfolding continuous_on_open_invariant by blast\n  then obtain A where A: \"\\<forall>c\\<in>C. open (A c) \\<and> A c \\<inter> s = f -` c \\<inter> s\"\n    unfolding bchoice_iff ..\n  with cover have \"\\<And>c. c \\<in> C \\<Longrightarrow> open (A c)\" \"s \\<subseteq> (\\<Union>c\\<in>C. A c)\"\n    by (fastforce simp add: subset_eq set_eq_iff)+\n  from compactE_image[OF s this] obtain D where \"D \\<subseteq> C\" \"finite D\" \"s \\<subseteq> (\\<Union>c\\<in>D. A c)\" .\n  with A show \"\\<exists>D \\<subseteq> C. finite D \\<and> f`s \\<subseteq> \\<Union>D\"\n    by (intro exI[of _ D]) (fastforce simp add: subset_eq set_eq_iff)+\nqed\n\nlemma continuous_on_inv:\n  fixes f :: \"'a::topological_space \\<Rightarrow> 'b::t2_space\"\n  assumes \"continuous_on s f\"\n    and \"compact s\"\n    and \"\\<forall>x\\<in>s. g (f x) = x\"\n  shows \"continuous_on (f ` s) g\"\n  unfolding continuous_on_topological\nproof (clarsimp simp add: assms(3))\n  fix x :: 'a and B :: \"'a set\"\n  assume \"x \\<in> s\" and \"open B\" and \"x \\<in> B\"\n  have 1: \"\\<forall>x\\<in>s. f x \\<in> f ` (s - B) \\<longleftrightarrow> x \\<in> s - B\"\n    using assms(3) by (auto, metis)\n  have \"continuous_on (s - B) f\"\n    using \\<open>continuous_on s f\\<close> Diff_subset\n    by (rule continuous_on_subset)\n  moreover have \"compact (s - B)\"\n    using \\<open>open B\\<close> and \\<open>compact s\\<close>\n    unfolding Diff_eq by (intro compact_Int_closed closed_Compl)\n  ultimately have \"compact (f ` (s - B))\"\n    by (rule compact_continuous_image)\n  then have \"closed (f ` (s - B))\"\n    by (rule compact_imp_closed)\n  then have \"open (- f ` (s - B))\"\n    by (rule open_Compl)\n  moreover have \"f x \\<in> - f ` (s - B)\"\n    using \\<open>x \\<in> s\\<close> and \\<open>x \\<in> B\\<close> by (simp add: 1)\n  moreover have \"\\<forall>y\\<in>s. f y \\<in> - f ` (s - B) \\<longrightarrow> y \\<in> B\"\n    by (simp add: 1)\n  ultimately show \"\\<exists>A. open A \\<and> f x \\<in> A \\<and> (\\<forall>y\\<in>s. f y \\<in> A \\<longrightarrow> y \\<in> B)\"\n    by fast\nqed\n\nlemma continuous_on_inv_into:\n  fixes f :: \"'a::topological_space \\<Rightarrow> 'b::t2_space\"\n  assumes s: \"continuous_on s f\" \"compact s\"\n    and f: \"inj_on f s\"\n  shows \"continuous_on (f ` s) (the_inv_into s f)\"\n  by (rule continuous_on_inv[OF s]) (auto simp: the_inv_into_f_f[OF f])\n\nlemma (in linorder_topology) compact_attains_sup:\n  assumes \"compact S\" \"S \\<noteq> {}\"\n  shows \"\\<exists>s\\<in>S. \\<forall>t\\<in>S. t \\<le> s\"\nproof (rule classical)\n  assume \"\\<not> (\\<exists>s\\<in>S. \\<forall>t\\<in>S. t \\<le> s)\"\n  then obtain t where t: \"\\<forall>s\\<in>S. t s \\<in> S\" and \"\\<forall>s\\<in>S. s < t s\"\n    by (metis not_le)\n  then have \"\\<And>s. s\\<in>S \\<Longrightarrow> open {..< t s}\" \"S \\<subseteq> (\\<Union>s\\<in>S. {..< t s})\"\n    by auto\n  with \\<open>compact S\\<close> obtain C where \"C \\<subseteq> S\" \"finite C\" and C: \"S \\<subseteq> (\\<Union>s\\<in>C. {..< t s})\"\n    by (metis compactE_image)\n  with \\<open>S \\<noteq> {}\\<close> have Max: \"Max (t`C) \\<in> t`C\" and \"\\<forall>s\\<in>t`C. s \\<le> Max (t`C)\"\n    by (auto intro!: Max_in)\n  with C have \"S \\<subseteq> {..< Max (t`C)}\"\n    by (auto intro: less_le_trans simp: subset_eq)\n  with t Max \\<open>C \\<subseteq> S\\<close> show ?thesis\n    by fastforce\nqed\n\nlemma (in linorder_topology) compact_attains_inf:\n  assumes \"compact S\" \"S \\<noteq> {}\"\n  shows \"\\<exists>s\\<in>S. \\<forall>t\\<in>S. s \\<le> t\"\nproof (rule classical)\n  assume \"\\<not> (\\<exists>s\\<in>S. \\<forall>t\\<in>S. s \\<le> t)\"\n  then obtain t where t: \"\\<forall>s\\<in>S. t s \\<in> S\" and \"\\<forall>s\\<in>S. t s < s\"\n    by (metis not_le)\n  then have \"\\<And>s. s\\<in>S \\<Longrightarrow> open {t s <..}\" \"S \\<subseteq> (\\<Union>s\\<in>S. {t s <..})\"\n    by auto\n  with \\<open>compact S\\<close> obtain C where \"C \\<subseteq> S\" \"finite C\" and C: \"S \\<subseteq> (\\<Union>s\\<in>C. {t s <..})\"\n    by (metis compactE_image)\n  with \\<open>S \\<noteq> {}\\<close> have Min: \"Min (t`C) \\<in> t`C\" and \"\\<forall>s\\<in>t`C. Min (t`C) \\<le> s\"\n    by (auto intro!: Min_in)\n  with C have \"S \\<subseteq> {Min (t`C) <..}\"\n    by (auto intro: le_less_trans simp: subset_eq)\n  with t Min \\<open>C \\<subseteq> S\\<close> show ?thesis\n    by fastforce\nqed\n\nlemma continuous_attains_sup:\n  fixes f :: \"'a::topological_space \\<Rightarrow> 'b::linorder_topology\"\n  shows \"compact s \\<Longrightarrow> s \\<noteq> {} \\<Longrightarrow> continuous_on s f \\<Longrightarrow> (\\<exists>x\\<in>s. \\<forall>y\\<in>s.  f y \\<le> f x)\"\n  using compact_attains_sup[of \"f ` s\"] compact_continuous_image[of s f] by auto\n\nlemma continuous_attains_inf:\n  fixes f :: \"'a::topological_space \\<Rightarrow> 'b::linorder_topology\"\n  shows \"compact s \\<Longrightarrow> s \\<noteq> {} \\<Longrightarrow> continuous_on s f \\<Longrightarrow> (\\<exists>x\\<in>s. \\<forall>y\\<in>s. f x \\<le> f y)\"\n  using compact_attains_inf[of \"f ` s\"] compact_continuous_image[of s f] by auto\n\n\nsubsection \\<open>Connectedness\\<close>\n\ncontext topological_space\nbegin\n\ndefinition \"connected S \\<longleftrightarrow>\n  \\<not> (\\<exists>A B. open A \\<and> open B \\<and> S \\<subseteq> A \\<union> B \\<and> A \\<inter> B \\<inter> S = {} \\<and> A \\<inter> S \\<noteq> {} \\<and> B \\<inter> S \\<noteq> {})\"\n\nlemma connectedI:\n  \"(\\<And>A B. open A \\<Longrightarrow> open B \\<Longrightarrow> A \\<inter> U \\<noteq> {} \\<Longrightarrow> B \\<inter> U \\<noteq> {} \\<Longrightarrow> A \\<inter> B \\<inter> U = {} \\<Longrightarrow> U \\<subseteq> A \\<union> B \\<Longrightarrow> False)\n  \\<Longrightarrow> connected U\"\n  by (auto simp: connected_def)\n\nlemma connected_empty [simp]: \"connected {}\"\n  by (auto intro!: connectedI)\n\nlemma connected_sing [simp]: \"connected {x}\"\n  by (auto intro!: connectedI)\n\nlemma connectedD:\n  \"connected A \\<Longrightarrow> open U \\<Longrightarrow> open V \\<Longrightarrow> U \\<inter> V \\<inter> A = {} \\<Longrightarrow> A \\<subseteq> U \\<union> V \\<Longrightarrow> U \\<inter> A = {} \\<or> V \\<inter> A = {}\"\n  by (auto simp: connected_def)\n\nend\n\nlemma connected_closed:\n  \"connected s \\<longleftrightarrow>\n    \\<not> (\\<exists>A B. closed A \\<and> closed B \\<and> s \\<subseteq> A \\<union> B \\<and> A \\<inter> B \\<inter> s = {} \\<and> A \\<inter> s \\<noteq> {} \\<and> B \\<inter> s \\<noteq> {})\"\n  apply (simp add: connected_def del: ex_simps, safe)\n   apply (drule_tac x=\"-A\" in spec)\n   apply (drule_tac x=\"-B\" in spec)\n   apply (fastforce simp add: closed_def [symmetric])\n  apply (drule_tac x=\"-A\" in spec)\n  apply (drule_tac x=\"-B\" in spec)\n  apply (fastforce simp add: open_closed [symmetric])\n  done\n\nlemma connected_closedD:\n  \"\\<lbrakk>connected s; A \\<inter> B \\<inter> s = {}; s \\<subseteq> A \\<union> B; closed A; closed B\\<rbrakk> \\<Longrightarrow> A \\<inter> s = {} \\<or> B \\<inter> s = {}\"\n  by (simp add: connected_closed)\n\nlemma connected_Union:\n  assumes cs: \"\\<And>s. s \\<in> S \\<Longrightarrow> connected s\"\n    and ne: \"\\<Inter>S \\<noteq> {}\"\n  shows \"connected(\\<Union>S)\"\nproof (rule connectedI)\n  fix A B\n  assume A: \"open A\" and B: \"open B\" and Alap: \"A \\<inter> \\<Union>S \\<noteq> {}\" and Blap: \"B \\<inter> \\<Union>S \\<noteq> {}\"\n    and disj: \"A \\<inter> B \\<inter> \\<Union>S = {}\" and cover: \"\\<Union>S \\<subseteq> A \\<union> B\"\n  have disjs:\"\\<And>s. s \\<in> S \\<Longrightarrow> A \\<inter> B \\<inter> s = {}\"\n    using disj by auto\n  obtain sa where sa: \"sa \\<in> S\" \"A \\<inter> sa \\<noteq> {}\"\n    using Alap by auto\n  obtain sb where sb: \"sb \\<in> S\" \"B \\<inter> sb \\<noteq> {}\"\n    using Blap by auto\n  obtain x where x: \"\\<And>s. s \\<in> S \\<Longrightarrow> x \\<in> s\"\n    using ne by auto\n  then have \"x \\<in> \\<Union>S\"\n    using \\<open>sa \\<in> S\\<close> by blast\n  then have \"x \\<in> A \\<or> x \\<in> B\"\n    using cover by auto\n  then show False\n    using cs [unfolded connected_def]\n    by (metis A B IntI Sup_upper sa sb disjs x cover empty_iff subset_trans)\nqed\n\nlemma connected_Un: \"connected s \\<Longrightarrow> connected t \\<Longrightarrow> s \\<inter> t \\<noteq> {} \\<Longrightarrow> connected (s \\<union> t)\"\n  using connected_Union [of \"{s,t}\"] by auto\n\nlemma connected_diff_open_from_closed:\n  assumes st: \"s \\<subseteq> t\"\n    and tu: \"t \\<subseteq> u\"\n    and s: \"open s\"\n    and t: \"closed t\"\n    and u: \"connected u\"\n    and ts: \"connected (t - s)\"\n  shows \"connected(u - s)\"\nproof (rule connectedI)\n  fix A B\n  assume AB: \"open A\" \"open B\" \"A \\<inter> (u - s) \\<noteq> {}\" \"B \\<inter> (u - s) \\<noteq> {}\"\n    and disj: \"A \\<inter> B \\<inter> (u - s) = {}\"\n    and cover: \"u - s \\<subseteq> A \\<union> B\"\n  then consider \"A \\<inter> (t - s) = {}\" | \"B \\<inter> (t - s) = {}\"\n    using st ts tu connectedD [of \"t-s\" \"A\" \"B\"] by auto\n  then show False\n  proof cases\n    case 1\n    then have \"(A - t) \\<inter> (B \\<union> s) \\<inter> u = {}\"\n      using disj st by auto\n    moreover have \"u \\<subseteq> (A - t) \\<union> (B \\<union> s)\"\n      using 1 cover by auto\n    ultimately show False\n      using connectedD [of u \"A - t\" \"B \\<union> s\"] AB s t 1 u by auto\n  next\n    case 2\n    then have \"(A \\<union> s) \\<inter> (B - t) \\<inter> u = {}\"\n      using disj st by auto\n    moreover have \"u \\<subseteq> (A \\<union> s) \\<union> (B - t)\"\n      using 2 cover by auto\n    ultimately show False\n      using connectedD [of u \"A \\<union> s\" \"B - t\"] AB s t 2 u by auto\n  qed\nqed\n\nlemma connected_iff_const:\n  fixes S :: \"'a::topological_space set\"\n  shows \"connected S \\<longleftrightarrow> (\\<forall>P::'a \\<Rightarrow> bool. continuous_on S P \\<longrightarrow> (\\<exists>c. \\<forall>s\\<in>S. P s = c))\"\nproof safe\n  fix P :: \"'a \\<Rightarrow> bool\"\n  assume \"connected S\" \"continuous_on S P\"\n  then have \"\\<And>b. \\<exists>A. open A \\<and> A \\<inter> S = P -` {b} \\<inter> S\"\n    unfolding continuous_on_open_invariant by (simp add: open_discrete)\n  from this[of True] this[of False]\n  obtain t f where \"open t\" \"open f\" and *: \"f \\<inter> S = P -` {False} \\<inter> S\" \"t \\<inter> S = P -` {True} \\<inter> S\"\n    by meson\n  then have \"t \\<inter> S = {} \\<or> f \\<inter> S = {}\"\n    by (intro connectedD[OF \\<open>connected S\\<close>])  auto\n  then show \"\\<exists>c. \\<forall>s\\<in>S. P s = c\"\n  proof (rule disjE)\n    assume \"t \\<inter> S = {}\"\n    then show ?thesis\n      unfolding * by (intro exI[of _ False]) auto\n  next\n    assume \"f \\<inter> S = {}\"\n    then show ?thesis\n      unfolding * by (intro exI[of _ True]) auto\n  qed\nnext\n  assume P: \"\\<forall>P::'a \\<Rightarrow> bool. continuous_on S P \\<longrightarrow> (\\<exists>c. \\<forall>s\\<in>S. P s = c)\"\n  show \"connected S\"\n  proof (rule connectedI)\n    fix A B\n    assume *: \"open A\" \"open B\" \"A \\<inter> S \\<noteq> {}\" \"B \\<inter> S \\<noteq> {}\" \"A \\<inter> B \\<inter> S = {}\" \"S \\<subseteq> A \\<union> B\"\n    have \"continuous_on S (\\<lambda>x. x \\<in> A)\"\n      unfolding continuous_on_open_invariant\n    proof safe\n      fix C :: \"bool set\"\n      have \"C = UNIV \\<or> C = {True} \\<or> C = {False} \\<or> C = {}\"\n        using subset_UNIV[of C] unfolding UNIV_bool by auto\n      with * show \"\\<exists>T. open T \\<and> T \\<inter> S = (\\<lambda>x. x \\<in> A) -` C \\<inter> S\"\n        by (intro exI[of _ \"(if True \\<in> C then A else {}) \\<union> (if False \\<in> C then B else {})\"]) auto\n    qed\n    from P[rule_format, OF this] obtain c where \"\\<And>s. s \\<in> S \\<Longrightarrow> (s \\<in> A) = c\"\n      by blast\n    with * show False\n      by (cases c) auto\n  qed\nqed\n\nlemma connectedD_const: \"connected S \\<Longrightarrow> continuous_on S P \\<Longrightarrow> \\<exists>c. \\<forall>s\\<in>S. P s = c\"\n  for P :: \"'a::topological_space \\<Rightarrow> bool\"\n  by (auto simp: connected_iff_const)\n\nlemma connectedI_const:\n  \"(\\<And>P::'a::topological_space \\<Rightarrow> bool. continuous_on S P \\<Longrightarrow> \\<exists>c. \\<forall>s\\<in>S. P s = c) \\<Longrightarrow> connected S\"\n  by (auto simp: connected_iff_const)\n\nlemma connected_local_const:\n  assumes \"connected A\" \"a \\<in> A\" \"b \\<in> A\"\n    and *: \"\\<forall>a\\<in>A. eventually (\\<lambda>b. f a = f b) (at a within A)\"\n  shows \"f a = f b\"\nproof -\n  obtain S where S: \"\\<And>a. a \\<in> A \\<Longrightarrow> a \\<in> S a\" \"\\<And>a. a \\<in> A \\<Longrightarrow> open (S a)\"\n    \"\\<And>a x. a \\<in> A \\<Longrightarrow> x \\<in> S a \\<Longrightarrow> x \\<in> A \\<Longrightarrow> f a = f x\"\n    using * unfolding eventually_at_topological by metis\n  let ?P = \"\\<Union>b\\<in>{b\\<in>A. f a = f b}. S b\" and ?N = \"\\<Union>b\\<in>{b\\<in>A. f a \\<noteq> f b}. S b\"\n  have \"?P \\<inter> A = {} \\<or> ?N \\<inter> A = {}\"\n    using \\<open>connected A\\<close> S \\<open>a\\<in>A\\<close>\n    by (intro connectedD) (auto, metis)\n  then show \"f a = f b\"\n  proof\n    assume \"?N \\<inter> A = {}\"\n    then have \"\\<forall>x\\<in>A. f a = f x\"\n      using S(1) by auto\n    with \\<open>b\\<in>A\\<close> show ?thesis by auto\n  next\n    assume \"?P \\<inter> A = {}\" then show ?thesis\n      using \\<open>a \\<in> A\\<close> S(1)[of a] by auto\n  qed\nqed\n\nlemma (in linorder_topology) connectedD_interval:\n  assumes \"connected U\"\n    and xy: \"x \\<in> U\" \"y \\<in> U\"\n    and \"x \\<le> z\" \"z \\<le> y\"\n  shows \"z \\<in> U\"\nproof -\n  have eq: \"{..<z} \\<union> {z<..} = - {z}\"\n    by auto\n  have \"\\<not> connected U\" if \"z \\<notin> U\" \"x < z\" \"z < y\"\n    using xy that\n    apply (simp only: connected_def simp_thms)\n    apply (rule_tac exI[of _ \"{..< z}\"])\n    apply (rule_tac exI[of _ \"{z <..}\"])\n    apply (auto simp add: eq)\n    done\n  with assms show \"z \\<in> U\"\n    by (metis less_le)\nqed\n\nlemma (in linorder_topology) not_in_connected_cases:\n  assumes conn: \"connected S\"\n  assumes nbdd: \"x \\<notin> S\"\n  assumes ne: \"S \\<noteq> {}\"\n  obtains \"bdd_above S\" \"\\<And>y. y \\<in> S \\<Longrightarrow> x \\<ge> y\" | \"bdd_below S\" \"\\<And>y. y \\<in> S \\<Longrightarrow> x \\<le> y\"\nproof -\n  obtain s where \"s \\<in> S\" using ne by blast\n  {\n    assume \"s \\<le> x\"\n    have \"False\" if \"x \\<le> y\" \"y \\<in> S\" for y\n      using connectedD_interval[OF conn \\<open>s \\<in> S\\<close> \\<open>y \\<in> S\\<close> \\<open>s \\<le> x\\<close> \\<open>x \\<le> y\\<close>] \\<open>x \\<notin> S\\<close>\n      by simp\n    then have wit: \"y \\<in> S \\<Longrightarrow> x \\<ge> y\" for y\n      using le_cases by blast\n    then have \"bdd_above S\"\n      by (rule local.bdd_aboveI)\n    note this wit\n  } moreover {\n    assume \"x \\<le> s\"\n    have \"False\" if \"x \\<ge> y\" \"y \\<in> S\" for y\n      using connectedD_interval[OF conn \\<open>y \\<in> S\\<close> \\<open>s \\<in> S\\<close> \\<open>x \\<ge> y\\<close> \\<open>s \\<ge> x\\<close> ] \\<open>x \\<notin> S\\<close>\n      by simp\n    then have wit: \"y \\<in> S \\<Longrightarrow> x \\<le> y\" for y\n      using le_cases by blast\n    then have \"bdd_below S\"\n      by (rule bdd_belowI)\n    note this wit\n  } ultimately show ?thesis\n    by (meson le_cases that)\nqed\n\nlemma connected_continuous_image:\n  assumes *: \"continuous_on s f\"\n    and \"connected s\"\n  shows \"connected (f ` s)\"\nproof (rule connectedI_const)\n  fix P :: \"'b \\<Rightarrow> bool\"\n  assume \"continuous_on (f ` s) P\"\n  then have \"continuous_on s (P \\<circ> f)\"\n    by (rule continuous_on_compose[OF *])\n  from connectedD_const[OF \\<open>connected s\\<close> this] show \"\\<exists>c. \\<forall>s\\<in>f ` s. P s = c\"\n    by auto\nqed\n\n\nsection \\<open>Linear Continuum Topologies\\<close>\n\nclass linear_continuum_topology = linorder_topology + linear_continuum\nbegin\n\nlemma Inf_notin_open:\n  assumes A: \"open A\"\n    and bnd: \"\\<forall>a\\<in>A. x < a\"\n  shows \"Inf A \\<notin> A\"\nproof\n  assume \"Inf A \\<in> A\"\n  then obtain b where \"b < Inf A\" \"{b <.. Inf A} \\<subseteq> A\"\n    using open_left[of A \"Inf A\" x] assms by auto\n  with dense[of b \"Inf A\"] obtain c where \"c < Inf A\" \"c \\<in> A\"\n    by (auto simp: subset_eq)\n  then show False\n    using cInf_lower[OF \\<open>c \\<in> A\\<close>] bnd\n    by (metis not_le less_imp_le bdd_belowI)\nqed\n\nlemma Sup_notin_open:\n  assumes A: \"open A\"\n    and bnd: \"\\<forall>a\\<in>A. a < x\"\n  shows \"Sup A \\<notin> A\"\nproof\n  assume \"Sup A \\<in> A\"\n  with assms obtain b where \"Sup A < b\" \"{Sup A ..< b} \\<subseteq> A\"\n    using open_right[of A \"Sup A\" x] by auto\n  with dense[of \"Sup A\" b] obtain c where \"Sup A < c\" \"c \\<in> A\"\n    by (auto simp: subset_eq)\n  then show False\n    using cSup_upper[OF \\<open>c \\<in> A\\<close>] bnd\n    by (metis less_imp_le not_le bdd_aboveI)\nqed\n\nend\n\ninstance linear_continuum_topology \\<subseteq> perfect_space\nproof\n  fix x :: 'a\n  obtain y where \"x < y \\<or> y < x\"\n    using ex_gt_or_lt [of x] ..\n  with Inf_notin_open[of \"{x}\" y] Sup_notin_open[of \"{x}\" y] show \"\\<not> open {x}\"\n    by auto\nqed\n\nlemma connectedI_interval:\n  fixes U :: \"'a :: linear_continuum_topology set\"\n  assumes *: \"\\<And>x y z. x \\<in> U \\<Longrightarrow> y \\<in> U \\<Longrightarrow> x \\<le> z \\<Longrightarrow> z \\<le> y \\<Longrightarrow> z \\<in> U\"\n  shows \"connected U\"\nproof (rule connectedI)\n  {\n    fix A B\n    assume \"open A\" \"open B\" \"A \\<inter> B \\<inter> U = {}\" \"U \\<subseteq> A \\<union> B\"\n    fix x y\n    assume \"x < y\" \"x \\<in> A\" \"y \\<in> B\" \"x \\<in> U\" \"y \\<in> U\"\n\n    let ?z = \"Inf (B \\<inter> {x <..})\"\n\n    have \"x \\<le> ?z\" \"?z \\<le> y\"\n      using \\<open>y \\<in> B\\<close> \\<open>x < y\\<close> by (auto intro: cInf_lower cInf_greatest)\n    with \\<open>x \\<in> U\\<close> \\<open>y \\<in> U\\<close> have \"?z \\<in> U\"\n      by (rule *)\n    moreover have \"?z \\<notin> B \\<inter> {x <..}\"\n      using \\<open>open B\\<close> by (intro Inf_notin_open) auto\n    ultimately have \"?z \\<in> A\"\n      using \\<open>x \\<le> ?z\\<close> \\<open>A \\<inter> B \\<inter> U = {}\\<close> \\<open>x \\<in> A\\<close> \\<open>U \\<subseteq> A \\<union> B\\<close> by auto\n    have \"\\<exists>b\\<in>B. b \\<in> A \\<and> b \\<in> U\" if \"?z < y\"\n    proof -\n      obtain a where \"?z < a\" \"{?z ..< a} \\<subseteq> A\"\n        using open_right[OF \\<open>open A\\<close> \\<open>?z \\<in> A\\<close> \\<open>?z < y\\<close>] by auto\n      moreover obtain b where \"b \\<in> B\" \"x < b\" \"b < min a y\"\n        using cInf_less_iff[of \"B \\<inter> {x <..}\" \"min a y\"] \\<open>?z < a\\<close> \\<open>?z < y\\<close> \\<open>x < y\\<close> \\<open>y \\<in> B\\<close>\n        by auto\n      moreover have \"?z \\<le> b\"\n        using \\<open>b \\<in> B\\<close> \\<open>x < b\\<close>\n        by (intro cInf_lower) auto\n      moreover have \"b \\<in> U\"\n        using \\<open>x \\<le> ?z\\<close> \\<open>?z \\<le> b\\<close> \\<open>b < min a y\\<close>\n        by (intro *[OF \\<open>x \\<in> U\\<close> \\<open>y \\<in> U\\<close>]) (auto simp: less_imp_le)\n      ultimately show ?thesis\n        by (intro bexI[of _ b]) auto\n    qed\n    then have False\n      using \\<open>?z \\<le> y\\<close> \\<open>?z \\<in> A\\<close> \\<open>y \\<in> B\\<close> \\<open>y \\<in> U\\<close> \\<open>A \\<inter> B \\<inter> U = {}\\<close>\n      unfolding le_less by blast\n  }\n  note not_disjoint = this\n\n  fix A B assume AB: \"open A\" \"open B\" \"U \\<subseteq> A \\<union> B\" \"A \\<inter> B \\<inter> U = {}\"\n  moreover assume \"A \\<inter> U \\<noteq> {}\" then obtain x where x: \"x \\<in> U\" \"x \\<in> A\" by auto\n  moreover assume \"B \\<inter> U \\<noteq> {}\" then obtain y where y: \"y \\<in> U\" \"y \\<in> B\" by auto\n  moreover note not_disjoint[of B A y x] not_disjoint[of A B x y]\n  ultimately show False\n    by (cases x y rule: linorder_cases) auto\nqed\n\nlemma connected_iff_interval: \"connected U \\<longleftrightarrow> (\\<forall>x\\<in>U. \\<forall>y\\<in>U. \\<forall>z. x \\<le> z \\<longrightarrow> z \\<le> y \\<longrightarrow> z \\<in> U)\"\n  for U :: \"'a::linear_continuum_topology set\"\n  by (auto intro: connectedI_interval dest: connectedD_interval)\n\nlemma connected_UNIV[simp]: \"connected (UNIV::'a::linear_continuum_topology set)\"\n  by (simp add: connected_iff_interval)\n\nlemma connected_Ioi[simp]: \"connected {a<..}\"\n  for a :: \"'a::linear_continuum_topology\"\n  by (auto simp: connected_iff_interval)\n\nlemma connected_Ici[simp]: \"connected {a..}\"\n  for a :: \"'a::linear_continuum_topology\"\n  by (auto simp: connected_iff_interval)\n\nlemma connected_Iio[simp]: \"connected {..<a}\"\n  for a :: \"'a::linear_continuum_topology\"\n  by (auto simp: connected_iff_interval)\n\nlemma connected_Iic[simp]: \"connected {..a}\"\n  for a :: \"'a::linear_continuum_topology\"\n  by (auto simp: connected_iff_interval)\n\nlemma connected_Ioo[simp]: \"connected {a<..<b}\"\n  for a b :: \"'a::linear_continuum_topology\"\n  unfolding connected_iff_interval by auto\n\nlemma connected_Ioc[simp]: \"connected {a<..b}\"\n  for a b :: \"'a::linear_continuum_topology\"\n  by (auto simp: connected_iff_interval)\n\nlemma connected_Ico[simp]: \"connected {a..<b}\"\n  for a b :: \"'a::linear_continuum_topology\"\n  by (auto simp: connected_iff_interval)\n\nlemma connected_Icc[simp]: \"connected {a..b}\"\n  for a b :: \"'a::linear_continuum_topology\"\n  by (auto simp: connected_iff_interval)\n\nlemma connected_contains_Ioo:\n  fixes A :: \"'a :: linorder_topology set\"\n  assumes \"connected A\" \"a \\<in> A\" \"b \\<in> A\" shows \"{a <..< b} \\<subseteq> A\"\n  using connectedD_interval[OF assms] by (simp add: subset_eq Ball_def less_imp_le)\n\nlemma connected_contains_Icc:\n  fixes A :: \"'a::linorder_topology set\"\n  assumes \"connected A\" \"a \\<in> A\" \"b \\<in> A\"\n  shows \"{a..b} \\<subseteq> A\"\nproof\n  fix x assume \"x \\<in> {a..b}\"\n  then have \"x = a \\<or> x = b \\<or> x \\<in> {a<..<b}\"\n    by auto\n  then show \"x \\<in> A\"\n    using assms connected_contains_Ioo[of A a b] by auto\nqed\n\n\nsubsection \\<open>Intermediate Value Theorem\\<close>\n\nlemma IVT':\n  fixes f :: \"'a::linear_continuum_topology \\<Rightarrow> 'b::linorder_topology\"\n  assumes y: \"f a \\<le> y\" \"y \\<le> f b\" \"a \\<le> b\"\n    and *: \"continuous_on {a .. b} f\"\n  shows \"\\<exists>x. a \\<le> x \\<and> x \\<le> b \\<and> f x = y\"\nproof -\n  have \"connected {a..b}\"\n    unfolding connected_iff_interval by auto\n  from connected_continuous_image[OF * this, THEN connectedD_interval, of \"f a\" \"f b\" y] y\n  show ?thesis\n    by (auto simp add: atLeastAtMost_def atLeast_def atMost_def)\nqed\n\nlemma IVT2':\n  fixes f :: \"'a :: linear_continuum_topology \\<Rightarrow> 'b :: linorder_topology\"\n  assumes y: \"f b \\<le> y\" \"y \\<le> f a\" \"a \\<le> b\"\n    and *: \"continuous_on {a .. b} f\"\n  shows \"\\<exists>x. a \\<le> x \\<and> x \\<le> b \\<and> f x = y\"\nproof -\n  have \"connected {a..b}\"\n    unfolding connected_iff_interval by auto\n  from connected_continuous_image[OF * this, THEN connectedD_interval, of \"f b\" \"f a\" y] y\n  show ?thesis\n    by (auto simp add: atLeastAtMost_def atLeast_def atMost_def)\nqed\n\nlemma IVT:\n  fixes f :: \"'a::linear_continuum_topology \\<Rightarrow> 'b::linorder_topology\"\n  shows \"f a \\<le> y \\<Longrightarrow> y \\<le> f b \\<Longrightarrow> a \\<le> b \\<Longrightarrow> (\\<forall>x. a \\<le> x \\<and> x \\<le> b \\<longrightarrow> isCont f x) \\<Longrightarrow>\n    \\<exists>x. a \\<le> x \\<and> x \\<le> b \\<and> f x = y\"\n  by (rule IVT') (auto intro: continuous_at_imp_continuous_on)\n\nlemma IVT2:\n  fixes f :: \"'a::linear_continuum_topology \\<Rightarrow> 'b::linorder_topology\"\n  shows \"f b \\<le> y \\<Longrightarrow> y \\<le> f a \\<Longrightarrow> a \\<le> b \\<Longrightarrow> (\\<forall>x. a \\<le> x \\<and> x \\<le> b \\<longrightarrow> isCont f x) \\<Longrightarrow>\n    \\<exists>x. a \\<le> x \\<and> x \\<le> b \\<and> f x = y\"\n  by (rule IVT2') (auto intro: continuous_at_imp_continuous_on)\n\nlemma continuous_inj_imp_mono:\n  fixes f :: \"'a::linear_continuum_topology \\<Rightarrow> 'b::linorder_topology\"\n  assumes x: \"a < x\" \"x < b\"\n    and cont: \"continuous_on {a..b} f\"\n    and inj: \"inj_on f {a..b}\"\n  shows \"(f a < f x \\<and> f x < f b) \\<or> (f b < f x \\<and> f x < f a)\"\nproof -\n  note I = inj_on_eq_iff[OF inj]\n  {\n    assume \"f x < f a\" \"f x < f b\"\n    then obtain s t where \"x \\<le> s\" \"s \\<le> b\" \"a \\<le> t\" \"t \\<le> x\" \"f s = f t\" \"f x < f s\"\n      using IVT'[of f x \"min (f a) (f b)\" b] IVT2'[of f x \"min (f a) (f b)\" a] x\n      by (auto simp: continuous_on_subset[OF cont] less_imp_le)\n    with x I have False by auto\n  }\n  moreover\n  {\n    assume \"f a < f x\" \"f b < f x\"\n    then obtain s t where \"x \\<le> s\" \"s \\<le> b\" \"a \\<le> t\" \"t \\<le> x\" \"f s = f t\" \"f s < f x\"\n      using IVT'[of f a \"max (f a) (f b)\" x] IVT2'[of f b \"max (f a) (f b)\" x] x\n      by (auto simp: continuous_on_subset[OF cont] less_imp_le)\n    with x I have False by auto\n  }\n  ultimately show ?thesis\n    using I[of a x] I[of x b] x less_trans[OF x]\n    by (auto simp add: le_less less_imp_neq neq_iff)\nqed\n\nlemma continuous_at_Sup_mono:\n  fixes f :: \"'a::{linorder_topology,conditionally_complete_linorder} \\<Rightarrow>\n    'b::{linorder_topology,conditionally_complete_linorder}\"\n  assumes \"mono f\"\n    and cont: \"continuous (at_left (Sup S)) f\"\n    and S: \"S \\<noteq> {}\" \"bdd_above S\"\n  shows \"f (Sup S) = (SUP s\\<in>S. f s)\"\nproof (rule antisym)\n  have f: \"(f \\<longlongrightarrow> f (Sup S)) (at_left (Sup S))\"\n    using cont unfolding continuous_within .\n  show \"f (Sup S) \\<le> (SUP s\\<in>S. f s)\"\n  proof cases\n    assume \"Sup S \\<in> S\"\n    then show ?thesis\n      by (rule cSUP_upper) (auto intro: bdd_above_image_mono S \\<open>mono f\\<close>)\n  next\n    assume \"Sup S \\<notin> S\"\n    from \\<open>S \\<noteq> {}\\<close> obtain s where \"s \\<in> S\"\n      by auto\n    with \\<open>Sup S \\<notin> S\\<close> S have \"s < Sup S\"\n      unfolding less_le by (blast intro: cSup_upper)\n    show ?thesis\n    proof (rule ccontr)\n      assume \"\\<not> ?thesis\"\n      with order_tendstoD(1)[OF f, of \"SUP s\\<in>S. f s\"] obtain b where \"b < Sup S\"\n        and *: \"\\<And>y. b < y \\<Longrightarrow> y < Sup S \\<Longrightarrow> (SUP s\\<in>S. f s) < f y\"\n        by (auto simp: not_le eventually_at_left[OF \\<open>s < Sup S\\<close>])\n      with \\<open>S \\<noteq> {}\\<close> obtain c where \"c \\<in> S\" \"b < c\"\n        using less_cSupD[of S b] by auto\n      with \\<open>Sup S \\<notin> S\\<close> S have \"c < Sup S\"\n        unfolding less_le by (blast intro: cSup_upper)\n      from *[OF \\<open>b < c\\<close> \\<open>c < Sup S\\<close>] cSUP_upper[OF \\<open>c \\<in> S\\<close> bdd_above_image_mono[of f]]\n      show False\n        by (auto simp: assms)\n    qed\n  qed\nqed (intro cSUP_least \\<open>mono f\\<close>[THEN monoD] cSup_upper S)\n\nlemma continuous_at_Sup_antimono:\n  fixes f :: \"'a::{linorder_topology,conditionally_complete_linorder} \\<Rightarrow>\n    'b::{linorder_topology,conditionally_complete_linorder}\"\n  assumes \"antimono f\"\n    and cont: \"continuous (at_left (Sup S)) f\"\n    and S: \"S \\<noteq> {}\" \"bdd_above S\"\n  shows \"f (Sup S) = (INF s\\<in>S. f s)\"\nproof (rule antisym)\n  have f: \"(f \\<longlongrightarrow> f (Sup S)) (at_left (Sup S))\"\n    using cont unfolding continuous_within .\n  show \"(INF s\\<in>S. f s) \\<le> f (Sup S)\"\n  proof cases\n    assume \"Sup S \\<in> S\"\n    then show ?thesis\n      by (intro cINF_lower) (auto intro: bdd_below_image_antimono S \\<open>antimono f\\<close>)\n  next\n    assume \"Sup S \\<notin> S\"\n    from \\<open>S \\<noteq> {}\\<close> obtain s where \"s \\<in> S\"\n      by auto\n    with \\<open>Sup S \\<notin> S\\<close> S have \"s < Sup S\"\n      unfolding less_le by (blast intro: cSup_upper)\n    show ?thesis\n    proof (rule ccontr)\n      assume \"\\<not> ?thesis\"\n      with order_tendstoD(2)[OF f, of \"INF s\\<in>S. f s\"] obtain b where \"b < Sup S\"\n        and *: \"\\<And>y. b < y \\<Longrightarrow> y < Sup S \\<Longrightarrow> f y < (INF s\\<in>S. f s)\"\n        by (auto simp: not_le eventually_at_left[OF \\<open>s < Sup S\\<close>])\n      with \\<open>S \\<noteq> {}\\<close> obtain c where \"c \\<in> S\" \"b < c\"\n        using less_cSupD[of S b] by auto\n      with \\<open>Sup S \\<notin> S\\<close> S have \"c < Sup S\"\n        unfolding less_le by (blast intro: cSup_upper)\n      from *[OF \\<open>b < c\\<close> \\<open>c < Sup S\\<close>] cINF_lower[OF bdd_below_image_antimono, of f S c] \\<open>c \\<in> S\\<close>\n      show False\n        by (auto simp: assms)\n    qed\n  qed\nqed (intro cINF_greatest \\<open>antimono f\\<close>[THEN antimonoD] cSup_upper S)\n\nlemma continuous_at_Inf_mono:\n  fixes f :: \"'a::{linorder_topology,conditionally_complete_linorder} \\<Rightarrow>\n    'b::{linorder_topology,conditionally_complete_linorder}\"\n  assumes \"mono f\"\n    and cont: \"continuous (at_right (Inf S)) f\"\n    and S: \"S \\<noteq> {}\" \"bdd_below S\"\n  shows \"f (Inf S) = (INF s\\<in>S. f s)\"\nproof (rule antisym)\n  have f: \"(f \\<longlongrightarrow> f (Inf S)) (at_right (Inf S))\"\n    using cont unfolding continuous_within .\n  show \"(INF s\\<in>S. f s) \\<le> f (Inf S)\"\n  proof cases\n    assume \"Inf S \\<in> S\"\n    then show ?thesis\n      by (rule cINF_lower[rotated]) (auto intro: bdd_below_image_mono S \\<open>mono f\\<close>)\n  next\n    assume \"Inf S \\<notin> S\"\n    from \\<open>S \\<noteq> {}\\<close> obtain s where \"s \\<in> S\"\n      by auto\n    with \\<open>Inf S \\<notin> S\\<close> S have \"Inf S < s\"\n      unfolding less_le by (blast intro: cInf_lower)\n    show ?thesis\n    proof (rule ccontr)\n      assume \"\\<not> ?thesis\"\n      with order_tendstoD(2)[OF f, of \"INF s\\<in>S. f s\"] obtain b where \"Inf S < b\"\n        and *: \"\\<And>y. Inf S < y \\<Longrightarrow> y < b \\<Longrightarrow> f y < (INF s\\<in>S. f s)\"\n        by (auto simp: not_le eventually_at_right[OF \\<open>Inf S < s\\<close>])\n      with \\<open>S \\<noteq> {}\\<close> obtain c where \"c \\<in> S\" \"c < b\"\n        using cInf_lessD[of S b] by auto\n      with \\<open>Inf S \\<notin> S\\<close> S have \"Inf S < c\"\n        unfolding less_le by (blast intro: cInf_lower)\n      from *[OF \\<open>Inf S < c\\<close> \\<open>c < b\\<close>] cINF_lower[OF bdd_below_image_mono[of f] \\<open>c \\<in> S\\<close>]\n      show False\n        by (auto simp: assms)\n    qed\n  qed\nqed (intro cINF_greatest \\<open>mono f\\<close>[THEN monoD] cInf_lower \\<open>bdd_below S\\<close> \\<open>S \\<noteq> {}\\<close>)\n\nlemma continuous_at_Inf_antimono:\n  fixes f :: \"'a::{linorder_topology,conditionally_complete_linorder} \\<Rightarrow>\n    'b::{linorder_topology,conditionally_complete_linorder}\"\n  assumes \"antimono f\"\n    and cont: \"continuous (at_right (Inf S)) f\"\n    and S: \"S \\<noteq> {}\" \"bdd_below S\"\n  shows \"f (Inf S) = (SUP s\\<in>S. f s)\"\nproof (rule antisym)\n  have f: \"(f \\<longlongrightarrow> f (Inf S)) (at_right (Inf S))\"\n    using cont unfolding continuous_within .\n  show \"f (Inf S) \\<le> (SUP s\\<in>S. f s)\"\n  proof cases\n    assume \"Inf S \\<in> S\"\n    then show ?thesis\n      by (rule cSUP_upper) (auto intro: bdd_above_image_antimono S \\<open>antimono f\\<close>)\n  next\n    assume \"Inf S \\<notin> S\"\n    from \\<open>S \\<noteq> {}\\<close> obtain s where \"s \\<in> S\"\n      by auto\n    with \\<open>Inf S \\<notin> S\\<close> S have \"Inf S < s\"\n      unfolding less_le by (blast intro: cInf_lower)\n    show ?thesis\n    proof (rule ccontr)\n      assume \"\\<not> ?thesis\"\n      with order_tendstoD(1)[OF f, of \"SUP s\\<in>S. f s\"] obtain b where \"Inf S < b\"\n        and *: \"\\<And>y. Inf S < y \\<Longrightarrow> y < b \\<Longrightarrow> (SUP s\\<in>S. f s) < f y\"\n        by (auto simp: not_le eventually_at_right[OF \\<open>Inf S < s\\<close>])\n      with \\<open>S \\<noteq> {}\\<close> obtain c where \"c \\<in> S\" \"c < b\"\n        using cInf_lessD[of S b] by auto\n      with \\<open>Inf S \\<notin> S\\<close> S have \"Inf S < c\"\n        unfolding less_le by (blast intro: cInf_lower)\n      from *[OF \\<open>Inf S < c\\<close> \\<open>c < b\\<close>] cSUP_upper[OF \\<open>c \\<in> S\\<close> bdd_above_image_antimono[of f]]\n      show False\n        by (auto simp: assms)\n    qed\n  qed\nqed (intro cSUP_least \\<open>antimono f\\<close>[THEN antimonoD] cInf_lower S)\n\n\nsubsection \\<open>Uniform spaces\\<close>\n\nclass uniformity =\n  fixes uniformity :: \"('a \\<times> 'a) filter\"\nbegin\n\nabbreviation uniformity_on :: \"'a set \\<Rightarrow> ('a \\<times> 'a) filter\"\n  where \"uniformity_on s \\<equiv> inf uniformity (principal (s\\<times>s))\"\n\nend\n\nlemma uniformity_Abort:\n  \"uniformity =\n    Filter.abstract_filter (\\<lambda>u. Code.abort (STR ''uniformity is not executable'') (\\<lambda>u. uniformity))\"\n  by simp\n\nclass open_uniformity = \"open\" + uniformity +\n  assumes open_uniformity:\n    \"\\<And>U. open U \\<longleftrightarrow> (\\<forall>x\\<in>U. eventually (\\<lambda>(x', y). x' = x \\<longrightarrow> y \\<in> U) uniformity)\"\nbegin\n\nsubclass topological_space\n  by standard (force elim: eventually_mono eventually_elim2 simp: split_beta' open_uniformity)+\n\nend\n\nclass uniform_space = open_uniformity +\n  assumes uniformity_refl: \"eventually E uniformity \\<Longrightarrow> E (x, x)\"\n    and uniformity_sym: \"eventually E uniformity \\<Longrightarrow> eventually (\\<lambda>(x, y). E (y, x)) uniformity\"\n    and uniformity_trans:\n      \"eventually E uniformity \\<Longrightarrow>\n        \\<exists>D. eventually D uniformity \\<and> (\\<forall>x y z. D (x, y) \\<longrightarrow> D (y, z) \\<longrightarrow> E (x, z))\"\nbegin\n\nlemma uniformity_bot: \"uniformity \\<noteq> bot\"\n  using uniformity_refl by auto\n\nlemma uniformity_trans':\n  \"eventually E uniformity \\<Longrightarrow>\n    eventually (\\<lambda>((x, y), (y', z)). y = y' \\<longrightarrow> E (x, z)) (uniformity \\<times>\\<^sub>F uniformity)\"\n  by (drule uniformity_trans) (auto simp add: eventually_prod_same)\n\nlemma uniformity_transE:\n  assumes \"eventually E uniformity\"\n  obtains D where \"eventually D uniformity\" \"\\<And>x y z. D (x, y) \\<Longrightarrow> D (y, z) \\<Longrightarrow> E (x, z)\"\n  using uniformity_trans [OF assms] by auto\n\nlemma eventually_nhds_uniformity:\n  \"eventually P (nhds x) \\<longleftrightarrow> eventually (\\<lambda>(x', y). x' = x \\<longrightarrow> P y) uniformity\"\n  (is \"_ \\<longleftrightarrow> ?N P x\")\n  unfolding eventually_nhds\nproof safe\n  assume *: \"?N P x\"\n  have \"?N (?N P) x\" if \"?N P x\" for x\n  proof -\n    from that obtain D where ev: \"eventually D uniformity\"\n      and D: \"D (a, b) \\<Longrightarrow> D (b, c) \\<Longrightarrow> case (a, c) of (x', y) \\<Rightarrow> x' = x \\<longrightarrow> P y\" for a b c\n      by (rule uniformity_transE) simp\n    from ev show ?thesis\n      by eventually_elim (insert ev D, force elim: eventually_mono split: prod.split)\n  qed\n  then have \"open {x. ?N P x}\"\n    by (simp add: open_uniformity)\n  then show \"\\<exists>S. open S \\<and> x \\<in> S \\<and> (\\<forall>x\\<in>S. P x)\"\n    by (intro exI[of _ \"{x. ?N P x}\"]) (auto dest: uniformity_refl simp: *)\nqed (force simp add: open_uniformity elim: eventually_mono)\n\n\nsubsubsection \\<open>Totally bounded sets\\<close>\n\ndefinition totally_bounded :: \"'a set \\<Rightarrow> bool\"\n  where \"totally_bounded S \\<longleftrightarrow>\n    (\\<forall>E. eventually E uniformity \\<longrightarrow> (\\<exists>X. finite X \\<and> (\\<forall>s\\<in>S. \\<exists>x\\<in>X. E (x, s))))\"\n\nlemma totally_bounded_empty[iff]: \"totally_bounded {}\"\n  by (auto simp add: totally_bounded_def)\n\nlemma totally_bounded_subset: \"totally_bounded S \\<Longrightarrow> T \\<subseteq> S \\<Longrightarrow> totally_bounded T\"\n  by (fastforce simp add: totally_bounded_def)\n\nlemma totally_bounded_Union[intro]:\n  assumes M: \"finite M\" \"\\<And>S. S \\<in> M \\<Longrightarrow> totally_bounded S\"\n  shows \"totally_bounded (\\<Union>M)\"\n  unfolding totally_bounded_def\nproof safe\n  fix E\n  assume \"eventually E uniformity\"\n  with M obtain X where \"\\<forall>S\\<in>M. finite (X S) \\<and> (\\<forall>s\\<in>S. \\<exists>x\\<in>X S. E (x, s))\"\n    by (metis totally_bounded_def)\n  with \\<open>finite M\\<close> show \"\\<exists>X. finite X \\<and> (\\<forall>s\\<in>\\<Union>M. \\<exists>x\\<in>X. E (x, s))\"\n    by (intro exI[of _ \"\\<Union>S\\<in>M. X S\"]) force\nqed\n\n\nsubsubsection \\<open>Cauchy filter\\<close>\n\ndefinition cauchy_filter :: \"'a filter \\<Rightarrow> bool\"\n  where \"cauchy_filter F \\<longleftrightarrow> F \\<times>\\<^sub>F F \\<le> uniformity\"\n\ndefinition Cauchy :: \"(nat \\<Rightarrow> 'a) \\<Rightarrow> bool\"\n  where Cauchy_uniform: \"Cauchy X = cauchy_filter (filtermap X sequentially)\"\n\nlemma Cauchy_uniform_iff:\n  \"Cauchy X \\<longleftrightarrow> (\\<forall>P. eventually P uniformity \\<longrightarrow> (\\<exists>N. \\<forall>n\\<ge>N. \\<forall>m\\<ge>N. P (X n, X m)))\"\n  unfolding Cauchy_uniform cauchy_filter_def le_filter_def eventually_prod_same\n    eventually_filtermap eventually_sequentially\nproof safe\n  let ?U = \"\\<lambda>P. eventually P uniformity\"\n  {\n    fix P\n    assume \"?U P\" \"\\<forall>P. ?U P \\<longrightarrow> (\\<exists>Q. (\\<exists>N. \\<forall>n\\<ge>N. Q (X n)) \\<and> (\\<forall>x y. Q x \\<longrightarrow> Q y \\<longrightarrow> P (x, y)))\"\n    then obtain Q N where \"\\<And>n. n \\<ge> N \\<Longrightarrow> Q (X n)\" \"\\<And>x y. Q x \\<Longrightarrow> Q y \\<Longrightarrow> P (x, y)\"\n      by metis\n    then show \"\\<exists>N. \\<forall>n\\<ge>N. \\<forall>m\\<ge>N. P (X n, X m)\"\n      by blast\n  next\n    fix P\n    assume \"?U P\" and P: \"\\<forall>P. ?U P \\<longrightarrow> (\\<exists>N. \\<forall>n\\<ge>N. \\<forall>m\\<ge>N. P (X n, X m))\"\n    then obtain Q where \"?U Q\" and Q: \"\\<And>x y z. Q (x, y) \\<Longrightarrow> Q (y, z) \\<Longrightarrow> P (x, z)\"\n      by (auto elim: uniformity_transE)\n    then have \"?U (\\<lambda>x. Q x \\<and> (\\<lambda>(x, y). Q (y, x)) x)\"\n      unfolding eventually_conj_iff by (simp add: uniformity_sym)\n    from P[rule_format, OF this]\n    obtain N where N: \"\\<And>n m. n \\<ge> N \\<Longrightarrow> m \\<ge> N \\<Longrightarrow> Q (X n, X m) \\<and> Q (X m, X n)\"\n      by auto\n    show \"\\<exists>Q. (\\<exists>N. \\<forall>n\\<ge>N. Q (X n)) \\<and> (\\<forall>x y. Q x \\<longrightarrow> Q y \\<longrightarrow> P (x, y))\"\n    proof (safe intro!: exI[of _ \"\\<lambda>x. \\<forall>n\\<ge>N. Q (x, X n) \\<and> Q (X n, x)\"] exI[of _ N] N)\n      fix x y\n      assume \"\\<forall>n\\<ge>N. Q (x, X n) \\<and> Q (X n, x)\" \"\\<forall>n\\<ge>N. Q (y, X n) \\<and> Q (X n, y)\"\n      then have \"Q (x, X N)\" \"Q (X N, y)\" by auto\n      then show \"P (x, y)\"\n        by (rule Q)\n    qed\n  }\nqed\n\nlemma nhds_imp_cauchy_filter:\n  assumes *: \"F \\<le> nhds x\"\n  shows \"cauchy_filter F\"\nproof -\n  have \"F \\<times>\\<^sub>F F \\<le> nhds x \\<times>\\<^sub>F nhds x\"\n    by (intro prod_filter_mono *)\n  also have \"\\<dots> \\<le> uniformity\"\n    unfolding le_filter_def eventually_nhds_uniformity eventually_prod_same\n  proof safe\n    fix P\n    assume \"eventually P uniformity\"\n    then obtain Ql where ev: \"eventually Ql uniformity\"\n      and \"Ql (x, y) \\<Longrightarrow> Ql (y, z) \\<Longrightarrow> P (x, z)\" for x y z\n      by (rule uniformity_transE) simp\n    with ev[THEN uniformity_sym]\n    show \"\\<exists>Q. eventually (\\<lambda>(x', y). x' = x \\<longrightarrow> Q y) uniformity \\<and>\n        (\\<forall>x y. Q x \\<longrightarrow> Q y \\<longrightarrow> P (x, y))\"\n      by (rule_tac exI[of _ \"\\<lambda>y. Ql (y, x) \\<and> Ql (x, y)\"]) (fastforce elim: eventually_elim2)\n  qed\n  finally show ?thesis\n    by (simp add: cauchy_filter_def)\nqed\n\nlemma LIMSEQ_imp_Cauchy: \"X \\<longlonglongrightarrow> x \\<Longrightarrow> Cauchy X\"\n  unfolding Cauchy_uniform filterlim_def by (intro nhds_imp_cauchy_filter)\n\nlemma Cauchy_subseq_Cauchy:\n  assumes \"Cauchy X\" \"strict_mono f\"\n  shows \"Cauchy (X \\<circ> f)\"\n  unfolding Cauchy_uniform comp_def filtermap_filtermap[symmetric] cauchy_filter_def\n  by (rule order_trans[OF _ \\<open>Cauchy X\\<close>[unfolded Cauchy_uniform cauchy_filter_def]])\n     (intro prod_filter_mono filtermap_mono filterlim_subseq[OF \\<open>strict_mono f\\<close>, unfolded filterlim_def])\n\nlemma convergent_Cauchy: \"convergent X \\<Longrightarrow> Cauchy X\"\n  unfolding convergent_def by (erule exE, erule LIMSEQ_imp_Cauchy)\n\ndefinition complete :: \"'a set \\<Rightarrow> bool\"\n  where complete_uniform: \"complete S \\<longleftrightarrow>\n    (\\<forall>F \\<le> principal S. F \\<noteq> bot \\<longrightarrow> cauchy_filter F \\<longrightarrow> (\\<exists>x\\<in>S. F \\<le> nhds x))\"\n\nend\n\nsubsubsection \\<open>Uniformly continuous functions\\<close>\n\ndefinition uniformly_continuous_on :: \"'a set \\<Rightarrow> ('a::uniform_space \\<Rightarrow> 'b::uniform_space) \\<Rightarrow> bool\"\n  where uniformly_continuous_on_uniformity: \"uniformly_continuous_on s f \\<longleftrightarrow>\n    (LIM (x, y) (uniformity_on s). (f x, f y) :> uniformity)\"\n\nlemma uniformly_continuous_onD:\n  \"uniformly_continuous_on s f \\<Longrightarrow> eventually E uniformity \\<Longrightarrow>\n    eventually (\\<lambda>(x, y). x \\<in> s \\<longrightarrow> y \\<in> s \\<longrightarrow> E (f x, f y)) uniformity\"\n  by (simp add: uniformly_continuous_on_uniformity filterlim_iff\n      eventually_inf_principal split_beta' mem_Times_iff imp_conjL)\n\nlemma uniformly_continuous_on_const[continuous_intros]: \"uniformly_continuous_on s (\\<lambda>x. c)\"\n  by (auto simp: uniformly_continuous_on_uniformity filterlim_iff uniformity_refl)\n\nlemma uniformly_continuous_on_id[continuous_intros]: \"uniformly_continuous_on s (\\<lambda>x. x)\"\n  by (auto simp: uniformly_continuous_on_uniformity filterlim_def)\n\nlemma uniformly_continuous_on_compose[continuous_intros]:\n  \"uniformly_continuous_on s g \\<Longrightarrow> uniformly_continuous_on (g`s) f \\<Longrightarrow>\n    uniformly_continuous_on s (\\<lambda>x. f (g x))\"\n  using filterlim_compose[of \"\\<lambda>(x, y). (f x, f y)\" uniformity\n      \"uniformity_on (g`s)\"  \"\\<lambda>(x, y). (g x, g y)\" \"uniformity_on s\"]\n  by (simp add: split_beta' uniformly_continuous_on_uniformity\n      filterlim_inf filterlim_principal eventually_inf_principal mem_Times_iff)\n\nlemma uniformly_continuous_imp_continuous:\n  assumes f: \"uniformly_continuous_on s f\"\n  shows \"continuous_on s f\"\n  by (auto simp: filterlim_iff eventually_at_filter eventually_nhds_uniformity continuous_on_def\n           elim: eventually_mono dest!: uniformly_continuous_onD[OF f])\n\n\nsection \\<open>Product Topology\\<close>\n\nsubsection \\<open>Product is a topological space\\<close>\n\ninstantiation prod :: (topological_space, topological_space) topological_space\nbegin\n\ndefinition open_prod_def[code del]:\n  \"open (S :: ('a \\<times> 'b) set) \\<longleftrightarrow>\n    (\\<forall>x\\<in>S. \\<exists>A B. open A \\<and> open B \\<and> x \\<in> A \\<times> B \\<and> A \\<times> B \\<subseteq> S)\"\n\nlemma open_prod_elim:\n  assumes \"open S\" and \"x \\<in> S\"\n  obtains A B where \"open A\" and \"open B\" and \"x \\<in> A \\<times> B\" and \"A \\<times> B \\<subseteq> S\"\n  using assms unfolding open_prod_def by fast\n\nlemma open_prod_intro:\n  assumes \"\\<And>x. x \\<in> S \\<Longrightarrow> \\<exists>A B. open A \\<and> open B \\<and> x \\<in> A \\<times> B \\<and> A \\<times> B \\<subseteq> S\"\n  shows \"open S\"\n  using assms unfolding open_prod_def by fast\n\ninstance\nproof\n  show \"open (UNIV :: ('a \\<times> 'b) set)\"\n    unfolding open_prod_def by auto\nnext\n  fix S T :: \"('a \\<times> 'b) set\"\n  assume \"open S\" \"open T\"\n  show \"open (S \\<inter> T)\"\n  proof (rule open_prod_intro)\n    fix x\n    assume x: \"x \\<in> S \\<inter> T\"\n    from x have \"x \\<in> S\" by simp\n    obtain Sa Sb where A: \"open Sa\" \"open Sb\" \"x \\<in> Sa \\<times> Sb\" \"Sa \\<times> Sb \\<subseteq> S\"\n      using \\<open>open S\\<close> and \\<open>x \\<in> S\\<close> by (rule open_prod_elim)\n    from x have \"x \\<in> T\" by simp\n    obtain Ta Tb where B: \"open Ta\" \"open Tb\" \"x \\<in> Ta \\<times> Tb\" \"Ta \\<times> Tb \\<subseteq> T\"\n      using \\<open>open T\\<close> and \\<open>x \\<in> T\\<close> by (rule open_prod_elim)\n    let ?A = \"Sa \\<inter> Ta\" and ?B = \"Sb \\<inter> Tb\"\n    have \"open ?A \\<and> open ?B \\<and> x \\<in> ?A \\<times> ?B \\<and> ?A \\<times> ?B \\<subseteq> S \\<inter> T\"\n      using A B by (auto simp add: open_Int)\n    then show \"\\<exists>A B. open A \\<and> open B \\<and> x \\<in> A \\<times> B \\<and> A \\<times> B \\<subseteq> S \\<inter> T\"\n      by fast\n  qed\nnext\n  fix K :: \"('a \\<times> 'b) set set\"\n  assume \"\\<forall>S\\<in>K. open S\"\n  then show \"open (\\<Union>K)\"\n    unfolding open_prod_def by fast\nqed\n\nend\n\ndeclare [[code abort: \"open :: ('a::topological_space \\<times> 'b::topological_space) set \\<Rightarrow> bool\"]]\n\nlemma open_Times: \"open S \\<Longrightarrow> open T \\<Longrightarrow> open (S \\<times> T)\"\n  unfolding open_prod_def by auto\n\nlemma fst_vimage_eq_Times: \"fst -` S = S \\<times> UNIV\"\n  by auto\n\nlemma snd_vimage_eq_Times: \"snd -` S = UNIV \\<times> S\"\n  by auto\n\nlemma open_vimage_fst: \"open S \\<Longrightarrow> open (fst -` S)\"\n  by (simp add: fst_vimage_eq_Times open_Times)\n\nlemma open_vimage_snd: \"open S \\<Longrightarrow> open (snd -` S)\"\n  by (simp add: snd_vimage_eq_Times open_Times)\n\nlemma closed_vimage_fst: \"closed S \\<Longrightarrow> closed (fst -` S)\"\n  unfolding closed_open vimage_Compl [symmetric]\n  by (rule open_vimage_fst)\n\nlemma closed_vimage_snd: \"closed S \\<Longrightarrow> closed (snd -` S)\"\n  unfolding closed_open vimage_Compl [symmetric]\n  by (rule open_vimage_snd)\n\nlemma closed_Times: \"closed S \\<Longrightarrow> closed T \\<Longrightarrow> closed (S \\<times> T)\"\nproof -\n  have \"S \\<times> T = (fst -` S) \\<inter> (snd -` T)\"\n    by auto\n  then show \"closed S \\<Longrightarrow> closed T \\<Longrightarrow> closed (S \\<times> T)\"\n    by (simp add: closed_vimage_fst closed_vimage_snd closed_Int)\nqed\n\nlemma subset_fst_imageI: \"A \\<times> B \\<subseteq> S \\<Longrightarrow> y \\<in> B \\<Longrightarrow> A \\<subseteq> fst ` S\"\n  unfolding image_def subset_eq by force\n\nlemma subset_snd_imageI: \"A \\<times> B \\<subseteq> S \\<Longrightarrow> x \\<in> A \\<Longrightarrow> B \\<subseteq> snd ` S\"\n  unfolding image_def subset_eq by force\n\nlemma open_image_fst:\n  assumes \"open S\"\n  shows \"open (fst ` S)\"\nproof (rule openI)\n  fix x\n  assume \"x \\<in> fst ` S\"\n  then obtain y where \"(x, y) \\<in> S\"\n    by auto\n  then obtain A B where \"open A\" \"open B\" \"x \\<in> A\" \"y \\<in> B\" \"A \\<times> B \\<subseteq> S\"\n    using \\<open>open S\\<close> unfolding open_prod_def by auto\n  from \\<open>A \\<times> B \\<subseteq> S\\<close> \\<open>y \\<in> B\\<close> have \"A \\<subseteq> fst ` S\"\n    by (rule subset_fst_imageI)\n  with \\<open>open A\\<close> \\<open>x \\<in> A\\<close> have \"open A \\<and> x \\<in> A \\<and> A \\<subseteq> fst ` S\"\n    by simp\n  then show \"\\<exists>T. open T \\<and> x \\<in> T \\<and> T \\<subseteq> fst ` S\" ..\nqed\n\nlemma open_image_snd:\n  assumes \"open S\"\n  shows \"open (snd ` S)\"\nproof (rule openI)\n  fix y\n  assume \"y \\<in> snd ` S\"\n  then obtain x where \"(x, y) \\<in> S\"\n    by auto\n  then obtain A B where \"open A\" \"open B\" \"x \\<in> A\" \"y \\<in> B\" \"A \\<times> B \\<subseteq> S\"\n    using \\<open>open S\\<close> unfolding open_prod_def by auto\n  from \\<open>A \\<times> B \\<subseteq> S\\<close> \\<open>x \\<in> A\\<close> have \"B \\<subseteq> snd ` S\"\n    by (rule subset_snd_imageI)\n  with \\<open>open B\\<close> \\<open>y \\<in> B\\<close> have \"open B \\<and> y \\<in> B \\<and> B \\<subseteq> snd ` S\"\n    by simp\n  then show \"\\<exists>T. open T \\<and> y \\<in> T \\<and> T \\<subseteq> snd ` S\" ..\nqed\n\nlemma nhds_prod: \"nhds (a, b) = nhds a \\<times>\\<^sub>F nhds b\"\n  unfolding nhds_def\nproof (subst prod_filter_INF, auto intro!: antisym INF_greatest simp: principal_prod_principal)\n  fix S T\n  assume \"open S\" \"a \\<in> S\" \"open T\" \"b \\<in> T\"\n  then show \"(INF x \\<in> {S. open S \\<and> (a, b) \\<in> S}. principal x) \\<le> principal (S \\<times> T)\"\n    by (intro INF_lower) (auto intro!: open_Times)\nnext\n  fix S'\n  assume \"open S'\" \"(a, b) \\<in> S'\"\n  then obtain S T where \"open S\" \"a \\<in> S\" \"open T\" \"b \\<in> T\" \"S \\<times> T \\<subseteq> S'\"\n    by (auto elim: open_prod_elim)\n  then show \"(INF x \\<in> {S. open S \\<and> a \\<in> S}. INF y \\<in> {S. open S \\<and> b \\<in> S}.\n      principal (x \\<times> y)) \\<le> principal S'\"\n    by (auto intro!: INF_lower2)\nqed\n\n\nsubsubsection \\<open>Continuity of operations\\<close>\n\nlemma tendsto_fst [tendsto_intros]:\n  assumes \"(f \\<longlongrightarrow> a) F\"\n  shows \"((\\<lambda>x. fst (f x)) \\<longlongrightarrow> fst a) F\"\nproof (rule topological_tendstoI)\n  fix S\n  assume \"open S\" and \"fst a \\<in> S\"\n  then have \"open (fst -` S)\" and \"a \\<in> fst -` S\"\n    by (simp_all add: open_vimage_fst)\n  with assms have \"eventually (\\<lambda>x. f x \\<in> fst -` S) F\"\n    by (rule topological_tendstoD)\n  then show \"eventually (\\<lambda>x. fst (f x) \\<in> S) F\"\n    by simp\nqed\n\nlemma tendsto_snd [tendsto_intros]:\n  assumes \"(f \\<longlongrightarrow> a) F\"\n  shows \"((\\<lambda>x. snd (f x)) \\<longlongrightarrow> snd a) F\"\nproof (rule topological_tendstoI)\n  fix S\n  assume \"open S\" and \"snd a \\<in> S\"\n  then have \"open (snd -` S)\" and \"a \\<in> snd -` S\"\n    by (simp_all add: open_vimage_snd)\n  with assms have \"eventually (\\<lambda>x. f x \\<in> snd -` S) F\"\n    by (rule topological_tendstoD)\n  then show \"eventually (\\<lambda>x. snd (f x) \\<in> S) F\"\n    by simp\nqed\n\nlemma tendsto_Pair [tendsto_intros]:\n  assumes \"(f \\<longlongrightarrow> a) F\" and \"(g \\<longlongrightarrow> b) F\"\n  shows \"((\\<lambda>x. (f x, g x)) \\<longlongrightarrow> (a, b)) F\"\n  unfolding nhds_prod using assms by (rule filterlim_Pair)\n\nlemma continuous_fst[continuous_intros]: \"continuous F f \\<Longrightarrow> continuous F (\\<lambda>x. fst (f x))\"\n  unfolding continuous_def by (rule tendsto_fst)\n\nlemma continuous_snd[continuous_intros]: \"continuous F f \\<Longrightarrow> continuous F (\\<lambda>x. snd (f x))\"\n  unfolding continuous_def by (rule tendsto_snd)\n\nlemma continuous_Pair[continuous_intros]:\n  \"continuous F f \\<Longrightarrow> continuous F g \\<Longrightarrow> continuous F (\\<lambda>x. (f x, g x))\"\n  unfolding continuous_def by (rule tendsto_Pair)\n\nlemma continuous_on_fst[continuous_intros]:\n  \"continuous_on s f \\<Longrightarrow> continuous_on s (\\<lambda>x. fst (f x))\"\n  unfolding continuous_on_def by (auto intro: tendsto_fst)\n\nlemma continuous_on_snd[continuous_intros]:\n  \"continuous_on s f \\<Longrightarrow> continuous_on s (\\<lambda>x. snd (f x))\"\n  unfolding continuous_on_def by (auto intro: tendsto_snd)\n\nlemma continuous_on_Pair[continuous_intros]:\n  \"continuous_on s f \\<Longrightarrow> continuous_on s g \\<Longrightarrow> continuous_on s (\\<lambda>x. (f x, g x))\"\n  unfolding continuous_on_def by (auto intro: tendsto_Pair)\n\nlemma continuous_on_swap[continuous_intros]: \"continuous_on A prod.swap\"\n  by (simp add: prod.swap_def continuous_on_fst continuous_on_snd\n      continuous_on_Pair continuous_on_id)\n\nlemma continuous_on_swap_args:\n  assumes \"continuous_on (A\\<times>B) (\\<lambda>(x,y). d x y)\"\n    shows \"continuous_on (B\\<times>A) (\\<lambda>(x,y). d y x)\"\nproof -\n  have \"(\\<lambda>(x,y). d y x) = (\\<lambda>(x,y). d x y) \\<circ> prod.swap\"\n    by force\n  then show ?thesis\n    by (metis assms continuous_on_compose continuous_on_swap product_swap)\nqed\n\nlemma isCont_fst [simp]: \"isCont f a \\<Longrightarrow> isCont (\\<lambda>x. fst (f x)) a\"\n  by (fact continuous_fst)\n\nlemma isCont_snd [simp]: \"isCont f a \\<Longrightarrow> isCont (\\<lambda>x. snd (f x)) a\"\n  by (fact continuous_snd)\n\nlemma isCont_Pair [simp]: \"\\<lbrakk>isCont f a; isCont g a\\<rbrakk> \\<Longrightarrow> isCont (\\<lambda>x. (f x, g x)) a\"\n  by (fact continuous_Pair)\n\nlemma continuous_on_compose_Pair:\n  assumes f: \"continuous_on (Sigma A B) (\\<lambda>(a, b). f a b)\"\n  assumes g: \"continuous_on C g\"\n  assumes h: \"continuous_on C h\"\n  assumes subset: \"\\<And>c. c \\<in> C \\<Longrightarrow> g c \\<in> A\" \"\\<And>c. c \\<in> C \\<Longrightarrow> h c \\<in> B (g c)\"\n  shows \"continuous_on C (\\<lambda>c. f (g c) (h c))\"\n  using continuous_on_compose2[OF f continuous_on_Pair[OF g h]] subset\n  by auto\n\n\nsubsubsection \\<open>Connectedness of products\\<close>\n\nproposition connected_Times:\n  assumes S: \"connected S\" and T: \"connected T\"\n  shows \"connected (S \\<times> T)\"\nproof (rule connectedI_const)\n  fix P::\"'a \\<times> 'b \\<Rightarrow> bool\"\n  assume P[THEN continuous_on_compose2, continuous_intros]: \"continuous_on (S \\<times> T) P\"\n  have \"continuous_on S (\\<lambda>s. P (s, t))\" if \"t \\<in> T\" for t\n    by (auto intro!: continuous_intros that)\n  from connectedD_const[OF S this]\n  obtain c1 where c1: \"\\<And>s t. t \\<in> T \\<Longrightarrow> s \\<in> S \\<Longrightarrow> P (s, t) = c1 t\"\n    by metis\n  moreover\n  have \"continuous_on T (\\<lambda>t. P (s, t))\" if \"s \\<in> S\" for s\n    by (auto intro!: continuous_intros that)\n  from connectedD_const[OF T this]\n  obtain c2 where \"\\<And>s t. t \\<in> T \\<Longrightarrow> s \\<in> S \\<Longrightarrow> P (s, t) = c2 s\"\n    by metis\n  ultimately show \"\\<exists>c. \\<forall>s\\<in>S \\<times> T. P s = c\"\n    by auto\nqed\n\ncorollary connected_Times_eq [simp]:\n   \"connected (S \\<times> T) \\<longleftrightarrow> S = {} \\<or> T = {} \\<or> connected S \\<and> connected T\"  (is \"?lhs = ?rhs\")\nproof\n  assume L: ?lhs\n  show ?rhs\n  proof cases\n    assume \"S \\<noteq> {} \\<and> T \\<noteq> {}\"\n    moreover\n    have \"connected (fst ` (S \\<times> T))\" \"connected (snd ` (S \\<times> T))\"\n      using continuous_on_fst continuous_on_snd continuous_on_id\n      by (blast intro: connected_continuous_image [OF _ L])+\n    ultimately show ?thesis\n      by auto\n  qed auto\nqed (auto simp: connected_Times)\n\n\nsubsubsection \\<open>Separation axioms\\<close>\n\ninstance prod :: (t0_space, t0_space) t0_space\nproof\n  fix x y :: \"'a \\<times> 'b\"\n  assume \"x \\<noteq> y\"\n  then have \"fst x \\<noteq> fst y \\<or> snd x \\<noteq> snd y\"\n    by (simp add: prod_eq_iff)\n  then show \"\\<exists>U. open U \\<and> (x \\<in> U) \\<noteq> (y \\<in> U)\"\n    by (fast dest: t0_space elim: open_vimage_fst open_vimage_snd)\nqed\n\ninstance prod :: (t1_space, t1_space) t1_space\nproof\n  fix x y :: \"'a \\<times> 'b\"\n  assume \"x \\<noteq> y\"\n  then have \"fst x \\<noteq> fst y \\<or> snd x \\<noteq> snd y\"\n    by (simp add: prod_eq_iff)\n  then show \"\\<exists>U. open U \\<and> x \\<in> U \\<and> y \\<notin> U\"\n    by (fast dest: t1_space elim: open_vimage_fst open_vimage_snd)\nqed\n\ninstance prod :: (t2_space, t2_space) t2_space\nproof\n  fix x y :: \"'a \\<times> 'b\"\n  assume \"x \\<noteq> y\"\n  then have \"fst x \\<noteq> fst y \\<or> snd x \\<noteq> snd y\"\n    by (simp add: prod_eq_iff)\n  then show \"\\<exists>U V. open U \\<and> open V \\<and> x \\<in> U \\<and> y \\<in> V \\<and> U \\<inter> V = {}\"\n    by (fast dest: hausdorff elim: open_vimage_fst open_vimage_snd)\nqed\n\nlemma isCont_swap[continuous_intros]: \"isCont prod.swap a\"\n  using continuous_on_eq_continuous_within continuous_on_swap by blast\n\nlemma open_diagonal_complement:\n  \"open {(x,y) |x y. x \\<noteq> (y::('a::t2_space))}\"\nproof -\n  have \"open {(x, y). x \\<noteq> (y::'a)}\"\n    unfolding split_def by (intro open_Collect_neq continuous_intros)\n  also have \"{(x, y). x \\<noteq> (y::'a)} = {(x, y) |x y. x \\<noteq> (y::'a)}\"\n    by auto\n  finally show ?thesis .\nqed\n\nlemma closed_diagonal:\n  \"closed {y. \\<exists> x::('a::t2_space). y = (x,x)}\"\nproof -\n  have \"{y. \\<exists> x::'a. y = (x,x)} = UNIV - {(x,y) | x y. x \\<noteq> y}\" by auto\n  then show ?thesis using open_diagonal_complement closed_Diff by auto\nqed\n\nlemma open_superdiagonal:\n  \"open {(x,y) | x y. x > (y::'a::{linorder_topology})}\"\nproof -\n  have \"open {(x, y). x > (y::'a)}\"\n    unfolding split_def by (intro open_Collect_less continuous_intros)\n  also have \"{(x, y). x > (y::'a)} = {(x, y) |x y. x > (y::'a)}\"\n    by auto\n  finally show ?thesis .\nqed\n\nlemma closed_subdiagonal:\n  \"closed {(x,y) | x y. x \\<le> (y::'a::{linorder_topology})}\"\nproof -\n  have \"{(x,y) | x y. x \\<le> (y::'a)} = UNIV - {(x,y) | x y. x > (y::'a)}\" by auto\n  then show ?thesis using open_superdiagonal closed_Diff by auto\nqed\n\nlemma open_subdiagonal:\n  \"open {(x,y) | x y. x < (y::'a::{linorder_topology})}\"\nproof -\n  have \"open {(x, y). x < (y::'a)}\"\n    unfolding split_def by (intro open_Collect_less continuous_intros)\n  also have \"{(x, y). x < (y::'a)} = {(x, y) |x y. x < (y::'a)}\"\n    by auto\n  finally show ?thesis .\nqed\n\nlemma closed_superdiagonal:\n  \"closed {(x,y) | x y. x \\<ge> (y::('a::{linorder_topology}))}\"\nproof -\n  have \"{(x,y) | x y. x \\<ge> (y::'a)} = UNIV - {(x,y) | x y. x < y}\" by auto\n  then show ?thesis using open_subdiagonal closed_Diff by auto\nqed\n\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/Topological_Spaces.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950907764119, "lm_q2_score": 0.8438951025545426, "lm_q1q2_score": 0.7121589341760352}}
{"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 p-adics\"\\<close>\n\ntext\\<open> res is used to define canonical maps between residue rings  \\<close>\n\ndefinition res :: \"int \\<Rightarrow> int \\<Rightarrow> int\" where \n\"res n m = m mod n\"\n\ntext\\<open> (res n) is a ring homomorphism from the integers to Z/nZ \\<close>\n\nlemma res_hom_0:\n  assumes \"n > 1\"\n  shows \"res 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> res n x \\<in> carrier (residue_ring n)\"\n    using assms res_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   res n (x \\<otimes>\\<^bsub>\\<Z>\\<^esub> y) = res n x \\<otimes>\\<^bsub>residue_ring n\\<^esub> res n y\"\n    by (simp add: R res_def residues.mult_cong) \n  show \"\\<And>x y. x \\<in> carrier \\<Z> \\<Longrightarrow>\n               y \\<in> carrier \\<Z> \\<Longrightarrow>\n         res n (x \\<oplus>\\<^bsub>\\<Z>\\<^esub> y) = res n x \\<oplus>\\<^bsub>residue_ring n\\<^esub> res n y\"\n    by (simp add: R res_def residues.res_to_cong_simps(1)) \n  show \"res n \\<one>\\<^bsub>\\<Z>\\<^esub> = \\<one>\\<^bsub>residue_ring n\\<^esub>\" \n    by (simp add: R res_def residues.res_to_cong_simps(4)) \nqed\n\ntext\\<open> (res n) is a ring homomorphism from  Z/mZ --> Z/nZ when n divides m\\<close>\n\nlemma res_hom_1:\n  assumes \"n > 1\"\n  assumes \"m > 1\"\n  assumes \"n dvd m\"\n  shows \"res 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> res n x \\<in> carrier (residue_ring n)\" \n    using assms(1) res_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          res n (x \\<otimes>\\<^bsub>residue_ring m\\<^esub> y) = res n x \\<otimes>\\<^bsub>residue_ring n\\<^esub> res n y\"\n    using 0 1 assms by (metis mod_mod_cancel res_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> res n (x \\<oplus>\\<^bsub>residue_ring m\\<^esub> y) = res n x \\<oplus>\\<^bsub>residue_ring n\\<^esub> res n y\"\n    using 0 1 assms by (metis mod_mod_cancel res_def residues.add_cong residues.res_add_eq) \n  show \"res n \\<one>\\<^bsub>residue_ring m\\<^esub> = \\<one>\\<^bsub>residue_ring n\\<^esub>\" \n    by (simp add: assms(1) res_def residue_ring_def) \nqed\n\ntext\\<open> (res n) is the identity map on Z/nZ\\<close>\n\nlemma res_id:\n  assumes \"x \\<in> carrier (residue_ring n)\"\n  assumes \"n \\<ge>0\"\n  shows \"res n x = x\"\nproof(cases \"n=0\")\n  case True\n  then show ?thesis \n    by (simp add: res_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 res_def by auto\nqed\n\ntext\\<open> (res p^m) is a ring homomoprhism from Z/p^nZ --> Z/p^mZ when n > m\\<close>\n\nlemma res_hom_p:\n  assumes \"(n::nat) \\<ge> m\"\n  assumes \"m >0\"\n  assumes \"prime p\"\n  shows \"res (p^m) \\<in> ring_hom (residue_ring (p^n)) (residue_ring (p^m))\"\nproof(rule res_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\ntext\\<open>Defining the set of padic integers as the inverse limit of the rings Z/p^nZ along\n      the maps (res p^n): Z/p^mZ --> Z/p^nZ \\<close>\n\ndefinition padic_set :: \"nat \\<Rightarrow> padic_int set\" where\n\"padic_set p = {(f::padic_int) .(\\<forall>(m::nat). (f m) \\<in> (carrier (residue_ring (p^m))))\n                                    \\<and>(\\<forall>(n::nat) (m::nat). (n > m \\<longrightarrow> (res (p^m) (f n) = (f m)))) }\"\n\ntext\\<open>Rules for deducing basic properties of elements of padic_set p\\<close>\n\nlemma padic_set_simp0:\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_simp1:\n  assumes \"f \\<in> padic_set p\"\n  assumes \"n \\<ge> m\"\n  assumes \"prime p\"\n  shows \"res (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_simp0 by blast \n  then have \"res (p^m) (f m) = (f m)\" \n    by (simp add: res_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\nlemma padic_set_simp2:\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_simp0 \n    by (metis assms(2) of_nat_1 power_0) \n  then show ?thesis \n    using residue_ring_def  by simp \nqed\n\ntext\\<open>Rule for proving membership in (padic_set p)\\<close>\n\nlemma padic_set_mem:\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> (res (p^m) (f n) = (f m))))\"\n  shows \"f \\<in> padic_set p\"\n  by (simp add: assms(1) assms(2) padic_set_def) \n\n\nsection  \\<open>Defining the standard operations on the padic integers\"\\<close>\n\ntext\\<open>Addition and multiplication are defined componentwise on residue rings\\<close>\n\ndefinition padic_add :: \"nat \\<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_simp:\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\ndefinition padic_mult :: \"nat \\<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_simp: \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 padic multiplicative unit\\<close>\n\ndefinition padic_one :: \"nat \\<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  by (simp add: assms padic_one_def residue_ring_def) \n\ntext\\<open>definition of the padic additive unit\\<close>\n\ndefinition padic_zero :: \"nat \\<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  by (simp add: padic_zero_def residue_ring_def) \n\ntext\\<open>padic unary minus\\<close>\n\ndefinition padic_uminus :: \"nat \\<Rightarrow>  padic_int \\<Rightarrow>  padic_int\" where\n\"padic_uminus p f \\<equiv> \\<lambda> n. \\<ominus>\\<^bsub>residue_ring (p^n)\\<^esub> (f n)\"\n\nlemma padic_uminus_simp:\n\"padic_uminus p f n\\<equiv> \\<ominus>\\<^bsub>residue_ring (p^n)\\<^esub> (f n)\"\n   by (simp add: padic_uminus_def) \n\nlemma padic_uminus_simp':\n  assumes \"prime p\"\n  assumes \"f \\<in> padic_set p\"\n  assumes \"n >0\"\nshows \"padic_uminus p f n = (if n=0 then 0 else (- (f n)) mod (p^n))\"\nproof-\n  have \"residues (p^n)\"\n  by (metis (mono_tags, hide_lams) assms(1) assms(3) le_numeral_extra(1) \n      nat_int nat_less_eq_zless nat_one_as_int one_less_power \n      prime_gt_1_nat residues.intro) \n  then show ?thesis \n    using residue_ring_def padic_uminus_def residues.res_neg_eq\n    by auto \nqed\n\n(*padic simp rules bundled together*)\n\nlemma padic_simps:\n\"padic_zero p n = \\<zero>\\<^bsub>residue_ring (p^n)\\<^esub>\" \n\"padic_uminus 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_uminus_simp)\n  apply (simp add: padic_mult_def)\n  apply (simp add: padic_add_simp)  \n  using padic_one_simp by auto\n\ntext\\<open>padic_one is an element of the padics\\<close>\n\nlemma padic_one_mem:\n  assumes \"prime p\"\n  shows \"padic_one p \\<in> padic_set p\"\nproof(rule padic_set_mem)\n  show \"\\<And>m. padic_one p m \\<in> carrier (residue_ring (int p ^ m))\"\n  proof-\n    fix m::nat\n    show \"padic_one p m \\<in> carrier (residue_ring (int p ^ m)) \" \n      by (simp add: assms padic_one_def prime_gt_1_int residue_ring_def)\n  qed\n  show \"\\<And>m n. m < n \\<Longrightarrow> res (int p ^ m) (padic_one p n) = padic_one p m\"\n  proof- \n    fix m n::nat\n    assume \"m <n\"\n    show \"res (int p ^ m) (padic_one p n) = padic_one p m\"\n    proof(cases \"m = 0\")\n      case True\n      then have 0:\"padic_one p m = 0\" \n        by (simp add: padic_one_def)\n      have 1: \"padic_one p n = 1\" \n        using \\<open>m < n\\<close> padic_one_def by auto\n      then show ?thesis using res_def 0 1 \n        by (simp add: True)\n    next\n      case False \n      then have 0: \"padic_one p m = 1\"\n        by (simp add: padic_one_def)\n      have 1: \"padic_one p n = 1\"\n        using \\<open>m < n\\<close> padic_one_def by auto\n      show ?thesis using res_def 0 1 \n        by (metis \\<open>\\<And>m. padic_one p m \\<in> carrier (residue_ring (int p ^ m))\\<close>\n            of_nat_0_le_iff res_id zero_le_power)\n    qed\n  qed\nqed\n\ntext\\<open>padic_zero is an element of the padics \\<close>\n\nlemma padic_zero_mem:\n  assumes \"p \\<noteq>0\"\n  shows \"padic_zero p \\<in> padic_set p\" \nproof (rule padic_set_mem)\n  show \"\\<And>m. padic_zero p m \\<in> carrier (residue_ring (int p ^ m))\" \n    using assms padic_zero_def residue_ring_def by auto \n  show \"\\<And>m n. m < n \\<Longrightarrow> res (int p ^ m) (padic_zero p n) = padic_zero p m\"         \n    using \\<open>\\<And>m. padic_zero p m \\<in> carrier (residue_ring (int p ^ m))\\<close>\n      padic_zero_def res_id \n    by auto \nqed\n\ntext\\<open>padic_set is closed under padic_uminus\\<close>\n\nlemma res_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 res_1_zero:\n  \"res 1 n = 0\" \n  by (simp add: res_def) \n\nlemma padic_uminus_closed:\n  assumes \"f \\<in> padic_set p\"\n  assumes \"prime p\"\n  shows \"(padic_uminus p f) \\<in> padic_set p\"\nproof(rule padic_set_mem)\n  show \"\\<And>m. padic_uminus p f m \\<in> carrier (residue_ring (int p ^ m))\"\n  proof-\n    fix m\n    show \"padic_uminus p f m \\<in> carrier (residue_ring (int p ^ m))\"\n    proof-\n      have P0: \"padic_uminus p f m = \\<ominus>\\<^bsub>residue_ring (p^m)\\<^esub> (f m)\" \n        using padic_uminus_def by simp \n      then show ?thesis \n      proof(cases \"m=0\")\n        case True\n        then have 0:\"f m \\<in> carrier (residue_ring (p^m))\" \n          using assms(1) padic_set_simp0 by blast   \n        have 1:\"carrier (residue_ring (p^m)) = {0}\" \n          using True residue_ring_def by simp \n        have \"f m = 0\" \n          using 0 1  by blast \n        then have \"padic_uminus p f m = \\<ominus>\\<^bsub>residue_ring (p^m)\\<^esub> 0\"\n          using P0  by auto \n        then have \"padic_uminus p f m = 0\"\n          using res_1_prop by (simp add: True residue_ring_def) \n        then show ?thesis \n          using \"0\" \\<open>f m = 0\\<close> by auto \n      next\n        case False\n        then have 0:\"f m \\<in> carrier (residue_ring (p^m))\"  \n          using assms(1) padic_set_simp0 by blast\n        have 1: \"residues (p^m)\" \n          using False assms(2) less_irrefl prime_gt_1_int residues.intro by auto\n        then show ?thesis \n          using P0 by (simp add: residues.mod_in_carrier residues.res_neg_eq) \n      qed\n    qed\n  qed\n  show \"\\<And>m n. m < n \\<Longrightarrow> res (int p ^ m) (padic_uminus p f n) = padic_uminus p f m\" \n  proof-\n    fix m n::nat\n    assume \"m < n\"\n    show \"res (int p ^ m) (padic_uminus p f n) = padic_uminus p f m\" \n    proof(cases \"m=0\")\n      case True\n      then have 0: \"res (int p ^ m) (padic_uminus p f n) = 0\" using res_1_zero \n        by simp\n      have \"f m = 0\" \n        using assms True padic_set_def residue_ring_def \n        by (metis (mono_tags, hide_lams) infinite_descent linorder_neqE_nat \n            linorder_not_le not_less_zero  padic_set_simp1 power_0 \n            prime_gt_1_nat res_1_zero semiring_char_0_class.of_nat_eq_1_iff) \n      then have 1: \"padic_uminus p f m = 0\" using res_1_prop assms\n        by (simp add: True padic_uminus_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_simp0 by auto\n        have 1: \"padic_uminus p f n = \\<ominus>\\<^bsub>residue_ring (p^n)\\<^esub> (f n)\" using padic_uminus_def\n          by simp \n        have 2: \"padic_uminus p f m = \\<ominus>\\<^bsub>residue_ring (p^m)\\<^esub> (f m)\" using  False padic_uminus_def\n          by simp \n        have 3: \"res (p ^ m) \\<in> ring_hom (residue_ring (p ^ n)) (residue_ring (p ^ m))\" \n          using res_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)) (res (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 of_nat_power padic_set_simp1) \n      qed\n    qed\nqed\n\ntext\\<open>padic set is closed under multiplication\\<close>\n\nlemma res_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_closed:\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_mem)\n  show \"\\<And>m. padic_mult p f g m \\<in> carrier (residue_ring (int p ^ m))\"\n  proof-\n    fix m\n    show \"padic_mult p f g m \\<in> carrier (residue_ring (int p ^ m))\"\n    proof(cases \"m=0\")\n      case True \n      have \"padic_mult p f g m = 0\" using padic_set_simp0 res_1_mult assms  \n        by (metis True of_nat_1 padic_mult_simp power_0) \n      then show ?thesis \n        by (simp add: True residue_ring_def) \n    next\n      case False show ?thesis \n        by (simp add: assms(3) padic_mult_def prime_gt_0_nat residue_ring_def) \n    qed\n  qed\n  show \"\\<And>m n. m < n \\<Longrightarrow> res (int p ^ m) (padic_mult p f g n) = padic_mult p f g m\"\n  proof-\n      fix m n::nat\n      assume A: \"m < n\"\n      then show \"res (int p ^ m) (padic_mult p f g n) = padic_mult p f g m\"\n      proof(cases \"m=0\")\n        case True\n        then have 0: \"padic_mult p f g m = 0\"\n        proof -\n          have \"padic_mult p f g m \\<in> {0..0}\"\n            by (metis (no_types) True \\<open>\\<And>m. padic_mult p f g m \\<in> carrier (residue_ring (int p ^ m))\\<close>\n                cancel_comm_monoid_add_class.diff_cancel partial_object.select_convs(1) \n                residue_ring_def semiring_normalization_rules(32))\n          then show ?thesis\n            by simp\n        qed \n        have 1: \"res (int p ^ m) (padic_mult p f g n) = 0\"\n          using True by (simp add: res_def) \n        then show ?thesis \n          using 0 1 by simp\n      next\n        case False\n        have 0:\"res (p ^ m) \\<in> ring_hom (residue_ring (int (p ^ n))) (residue_ring (int (p ^ m)))\"\n          using A res_hom_p assms  False by auto  \n        have 1:\"f n \\<in> carrier (residue_ring (p^n))\" \n          using assms(1) padic_set_simp0 by auto \n        have 2:\"g n \\<in> carrier (residue_ring (p^n))\" \n          using assms(2) padic_set_simp0 by auto \n        have 3: \"res (int p ^ m) (f n \\<otimes>\\<^bsub>residue_ring (int (p ^ n))\\<^esub> g n) \n                    = f m \\<otimes>\\<^bsub>residue_ring (int (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_simp1 \n            by (simp add: assms(2) ring_hom_mult)\n        then show ?thesis\n            using ring_hom_mult padic_simps[simp] by auto \n        qed\n    qed\nqed\n\n\ntext\\<open>padic valuation. Maps 0 to -1 for now, otherwise is correct\\<close>\n\ndefinition padic_val :: \"nat \\<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_simp2 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_simp2 residue_ring_def by auto \n  next\n    case False \n    have \"\\<not> f (nat (padic_val p f)) \\<noteq> \\<zero>\\<^bsub>residue_ring (int (p ^ nat (padic_val p f)))\\<^esub>\"\n    proof\n      assume \"f (nat (padic_val p f)) \\<noteq> \\<zero>\\<^bsub>residue_ring (int (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 (int (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 (int (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\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  \"of_nat 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\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 (int 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_simp0  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          by (metis (mono_tags, lifting) Least_le\n              \\<open>x n \\<noteq> \\<zero>\\<^bsub>residue_ring (int (p ^ n))\\<^esub>\\<close> int_eq_iff \n              nat_le_iff)\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 (int 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 of_nat_1 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>val turns multiplication into integer addition on nonzero elements\\<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) = res (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) =  res (p^(nat ?vf + 1)) (f (Suc (nat (?vf + ?vg))))\" \n      using assms(1) assms(2) padic_set_simp1 by presburger\n    then show ?thesis by auto \n  qed\n  have 6: \"f (nat ?vf) = res (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_simp1 padic_val_def plus_1_eq_Suc  by auto \n  have 7: \"g (nat ?vg + 1) = res (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) =  res (p^(nat ?vg + 1)) (g (Suc (nat (?vf + ?vg))))\" \n      using assms(1) assms(3) padic_set_simp1 by presburger\n    then show ?thesis by auto \n  qed\n  have 8: \"g (nat ?vg) = res (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) =  res (p^(nat ?vg)) (g (Suc (nat (?vf + ?vg))))\" \n      using assms(1) assms(3) padic_set_simp1 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  \"res (p^(nat ?vf)) (?n) = f (nat ?vf)\" \n      by (simp add: \"6\") \n    then have P0: \"res (p^(nat ?vf)) (?n) = 0\" \n      using \"9\" by linarith \n    have \"res (p^(nat ?vf + 1)) (?n) = f (nat ?vf + 1)\" \n      using \"5\" by linarith \n    then have P1: \"res (p^(nat ?vf + 1)) (?n) \\<noteq> 0\"\n      using \"11\" by linarith \n    have P2: \"?n mod (p^(nat ?vf)) = 0\" \n      using P0 res_def by auto \n    have P3: \"?n mod (p^(nat ?vf + 1)) \\<noteq>  0\" \n      using P1 res_def by auto \n    have \"p^(nat ?vf) dvd ?n\" \n      using P2 by auto \n    then obtain i where A0:\"?n = i*(int p^(nat ?vf))\" \n      by fastforce \n    have \"?n \\<in> carrier (residue_ring (p^(Suc (nat (?vf + ?vg)))))\" \n      using assms(2) padic_set_simp0 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:\"(int p^(nat ?vf)) > 0\" \n        using assms(1) by auto\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 (metis int_nat_eq of_nat_mult of_nat_power) \n      then show False \n        using P3 by auto \n    qed\n    then show ?thesis \n      by (metis (no_types, lifting) A0 NN int_nat_eq of_nat_mult of_nat_power) \n  qed\n  have 14:\"\\<exists> i. ?m = i*p^(nat ?vg) \\<and> \\<not> p dvd (nat i)\"\n  proof-\n    have  \"res (p^(nat ?vg)) (?m) = g (nat ?vg)\" \n      by (simp add: \"8\") \n    then have P0: \"res (p^(nat ?vg)) (?m) = 0\" \n      using \"10\" by linarith \n    have \"res (p^(nat ?vg + 1)) (?m) = g (nat ?vg + 1)\" \n      using \"7\" by auto \n    then have P1: \"res (p^(nat ?vg + 1)) (?m) \\<noteq> 0\"\n      using \"12\" by linarith \n    have P2: \"?m mod (p^(nat ?vg)) = 0\"\n      using P0 res_def by auto \n    have P3: \"?m mod (p^(nat ?vg + 1)) \\<noteq>  0\" \n      using P1 res_def by auto \n    have \"p^(nat ?vg) dvd ?m\" \n      using P2 by auto \n    then obtain i where A0:\"?m = i*(int p^(nat ?vg))\" \n      by fastforce \n    have \"?m \\<in> carrier (residue_ring (p^(Suc (nat (?vf + ?vg)))))\" \n      using assms(3) padic_set_simp0 by blast \n    then have S0: \"?m \\<ge>0\" \n      by (simp add: residue_ring_def) \n    then have NN:\"i \\<ge> 0\" \n    proof-\n      have S1:\"(int p^(nat ?vg)) > 0\" \n        using assms(1) by auto\n      have \"\\<not> i<0\"\n      proof\n        assume \"i < 0\"\n        then have \"?m < 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 \"?m = j*p*(p^(nat ?vg))\" using A0 NN \n        by (metis int_nat_eq of_nat_mult of_nat_power) \n      then show False \n        using P3 by auto \n    qed\n    then show ?thesis \n      by (metis (no_types, lifting) A0 NN int_nat_eq of_nat_mult of_nat_power) \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) = (res ?i (?n)) \\<otimes>\\<^bsub>residue_ring ?i\\<^esub>   (res ?i (?m))\" \n      by (metis assms(2) assms(3) of_nat_0_le_iff padic_set_simp0 res_id) \n    then have P3:\"(?n \\<otimes>\\<^bsub>residue_ring ?i \\<^esub> ?m) = (res ?i (?n*?m))\" \n      by (metis monoid.simps(1) res_def residue_ring_def) \n    then show ?thesis \n      by (simp add: P1 res_def) \n  qed\n  then have 15: \"?nm mod ?i =  i*j*p^((nat ?vf) +(nat ?vg)) mod ?i\"\n    by (metis I J mult.assoc mult.left_commute of_nat_mult power_add zmod_int)\n  have 16: \"\\<not> p dvd (i*j)\" using 13 14\n    using I J assms(1) prime_dvd_mult_iff by auto \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 by (metis One_nat_def assms(1) linorder_not_less power_dvd_imp_le prime_gt_Suc_0_nat)\n    then have A1: \"p^((nat ?vf) +(nat ?vg)) mod ?i \\<noteq> 0\" \n      using dvd_eq_mod_eq_0 by blast\n    have \"\\<not>  p^((Suc (nat (?vf + ?vg)))) dvd i*j*p^((nat ?vf) +(nat ?vg)) \"\n      using 16 A0 assms(1) \n      by (metis (no_types, lifting) \"17\" A1 One_nat_def assms(4) assms(5)\n          dvd_times_right_cancel_iff mod_less nat_int nat_plus_as_int padic_val_def\n          power_Suc power_strict_increasing_iff prime_gt_Suc_0_nat)\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  then have 20: \"?nm mod (p^(nat ?vf + nat ?vg)) = 0\" \n    by (metis (mono_tags, lifting) A P dvd_imp_mod_0 \n        dvd_triv_right monoid.simps(1) of_nat_eq_0_iff residue_ring_def)\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_closed 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) = res (p^?k) ((padic_mult p f g) ?k) \" \n            using P 22 padic_set_simp1 by (simp add: assms(1) prime_gt_0_nat)\n          then have \"((padic_mult p f g) ?k) = res (p^?k) ?nm\" \n            using \"17\" \"22\" assms(1) padic_set_simp1 by fastforce \n          then have \"((padic_mult p f g) ?k) = res (p^?k) ?nm\" \n            by (simp add: res_def)\n          then have \"((padic_mult p f g) ?k) = res (p^?k) 0\"  \n            using \"20\" res_def by auto \n          then show ?thesis \n            by (simp add: res_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_simp2 residue_ring_def by auto \n      next\n        case C: False \n        then have \"((padic_mult p f g) k) = res (p^k) ((padic_mult p f g) (nat ?vf + nat ?vg)) \" \n          using B P 22 padic_set_simp1 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) = res (p^k) \\<zero>\\<^bsub>residue_ring (p^((nat ?vf + nat ?vg)))\\<^esub>\" \n          by (simp add: P0)\n        have \"res (p^k) \\<in> ring_hom (residue_ring (p^((nat ?vf + nat ?vg)))) (residue_ring (p^k))\"\n          using B P C res_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 res_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 (int (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 (int 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 (int 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 (int 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 (int 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 (int 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\ntext\\<open>abbreviation for the ring of p_adic integers\\<close>\n\nabbreviation padic_int :: \"nat \\<Rightarrow> padic_int ring\"\n  where \"padic_int (p::nat) \\<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\n\nlemma residues_n:\n  assumes \"n \\<noteq> 0\"\n  assumes \"prime p\"\n  shows \"residues (int p^n)\" \nproof\n  have \"p > 1\" using assms(2) \n    using prime_gt_1_nat by auto\n  then show \" 1 < int p ^ n \"  \n    using assms(1) by auto\nqed\n\ntext\\<open>padic 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 \n        by (metis Ax Ay Az assms monoid.select_convs(1) \n            padic_mult_closed padic_set_simp2 partial_object.select_convs(1)) \n    next\n      case False\n      then have \"residues (int p^n)\" \n        by (simp add: assms residues_n)\n      then show ?thesis \n        using residues.cring padic_set_simp0 padic_mult_closed Ax Ay Az padic_mult_simp\n        by (simp add: cring.cring_simprules(11))\n    qed\n  qed\nqed\n\ntext\\<open>The padics 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_add_def)  \n      have A2: \"(x m) \\<in>(carrier (residue_ring (p^m)))\" \n        using Px by (simp add: padic_set_def) \n      have A3: \"(y m) \\<in>(carrier (residue_ring (p^m)))\" \n        using Py by (simp add: 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> (res (p^m) (?f n) = (?f m))))\" \n    proof \n      fix n::nat\n      show \"(\\<forall>(m::nat). (n > m \\<longrightarrow> (res (p^m) (?f n) = (?f m))))\" \n      proof\n        fix m::nat\n        show \"(n > m \\<longrightarrow> (res (p^m) (?f n) = (?f m)))\"\n        proof\n          assume A: \"m < n\"\n          show \"(res (p^m) (?f n) = (?f m))\"\n          proof(cases \"m = 0\")\n            case True \n            then have A0: \"(res (p^m) (?f n)) = 0\" \n              by (simp add: res_1_zero) \n            have A1: \"?f m = 0\" using True \n              by (metis (mono_tags, lifting) \"0\" atLeastAtMost_singleton\n                  cancel_comm_monoid_add_class.diff_cancel empty_iff \n                  insert_iff of_nat_1 partial_object.select_convs(1) \n                  power.simps(1) residue_ring_def ring_record_simps(12)) \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              using assms divides_primepow_nat dvd_imp_mod_0 less_imp_le by blast \n            let ?LHS = \"res (p ^ m) ((x \\<oplus>\\<^bsub>padic_int p\\<^esub> y) n)\"\n            have A0: \"?LHS = res (p ^ m) ((x n)\\<oplus>\\<^bsub>residue_ring (p^n)\\<^esub>( y n))\" \n              by (simp add: padic_add_def)  \n            have \"res (p^m) \\<in> ring_hom (residue_ring (int (p^n))) (residue_ring (int (p^m)))\"\n              using A False assms res_hom_p by auto \n            then have \"res (p ^ m) ((x n)\\<oplus>\\<^bsub>residue_ring (p^n)\\<^esub>( y n)) = (res (p ^ m) (x n))\\<oplus>\\<^bsub>residue_ring (p^m)\\<^esub>((res (p ^ m) (y n)))\"  \n              by (metis (no_types, lifting) Px Py mem_Collect_eq padic_set_def partial_object.select_convs(1) ring_hom_add) \n            then have \"?LHS =(res (p ^ m) (x n))\\<oplus>\\<^bsub>residue_ring (p^m)\\<^esub>((res (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_add_def) \n          qed\n        qed\n      qed\n    qed\n    then show ?thesis\n      using \"0\" padic_set_mem by auto \n  qed\n  then have \"  x \\<oplus>\\<^bsub>padic_int p\\<^esub> y \\<in> (padic_set p)\" \n    by simp\n  then show \"carrier (padic_int p) \\<subseteq> carrier (padic_int p)\" \n    by blast  \nqed\n\ntext\\<open>padic 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 by auto \n      have Ey: \"(y n) \\<in> carrier (residue_ring (p^n))\" \n        using Ay padic_set_def by auto \n      have Ez: \"(z n) \\<in> carrier (residue_ring (p^n))\" \n        using Az padic_set_def 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 (int p^n)\" \n          by (simp add: assms residues_n)\n        then show ?thesis \n          using Ex Ey Ez cring.cring_simprules(7) padic_add_simp residues.cring 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 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 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  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  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_add_def) \n    qed\n  qed\nqed\n\ntext\\<open>padic 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_simp2   \n            partial_object.select_convs(1) ring_record_simps(12)) \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_add_simp) \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_add_simp) \n      have Ex: \"(x n) \\<in> carrier (residue_ring (p^n))\" \n        using Ax padic_set_simp0 by auto \n      have Ey: \"(y n) \\<in> carrier (residue_ring (p^n))\" \n        using Ay padic_set_simp0 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      apply(simp add:padic_add_simp)\n      apply(simp add:residue_ring_def)\n      apply(simp add: A)\n    proof-\n      have \"x \\<in>padic_set p\" using Ax by auto \n      then have \"x n \\<in> {0..p^n - 1}\" \n        using Ax padic_set_simp0 residue_ring_def assms int_ops(6) by auto\n      then have \"x n \\<le> (int p^n) - 1\" \n        using atLeastAtMost_iff \n        by (metis assms of_nat_1 of_nat_diff of_nat_power one_le_power prime_ge_1_nat)\n      then have R: \"x n < p^n\" \n        by simp\n      have \"x n \\<ge>0 \" \n        using \\<open>x n \\<in> {0..int (p ^ n - 1)}\\<close> atLeastAtMost_iff by blast\n      then show \"x n mod int p ^ n = x n\" using R \n        by simp\n    qed\n    then show \"(\\<zero>\\<^bsub>padic_int p\\<^esub> \\<oplus>\\<^bsub>padic_int p\\<^esub> x) n = x n\" \n      by simp\n  qed\nqed\n\ntext\\<open>padic_zero is closed 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_uminus 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_simp2 \n              padic_uminus_closed padic_zero_def by auto \n        next\n          case False \n          have C: \"(x n) \\<in> carrier (residue_ring (p^n))\" \n            using Ax padic_set_simp0 by auto\n          have R: \"residues (int 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_add_simp)\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 cring.cring_simprules(9) of_nat_power padic_uminus_simp residues.res_zero_eq)\n          then show ?thesis \n            by (simp add: padic_zero_def)\n        qed\n      qed\n    then show \"padic_uminus p x \\<in> carrier (padic_int p)\" \n      using padic_uminus_closed\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 \"\\<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 assms not_prime_0 padic_zero_mem\n          partial_object.select_convs(1) ring_record_simps(11))\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>padic_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 assms(1) assms(2) monoid.select_convs(1) monoid.select_convs(2)\n          padic_mult_closed padic_one_mem padic_set_simp2 partial_object.select_convs(1)) \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) \n        padic_mult_simp padic_one_simp padic_set_simp0 residues.cring by fastforce\n  qed\nqed\n\ntext\\<open>padic 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) by auto\n  have Ay: \"(y n) \\<in>carrier (residue_ring (p^n))\"\n    using padic_set_def assms(3) padic_set_simp0 by auto\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 assms(1) assms(2) assms(3) monoid.select_convs(1) padic_set_simp2 padic_simps(3) partial_object.select_convs(1)) \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_mult_simp)       \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_mult_simp) \n    have Ex: \"(x n) \\<in> carrier (residue_ring (p^n))\" \n      using Ax padic_set_simp0 by auto \n    have Ey: \"(y n) \\<in> carrier (residue_ring (p^n))\" \n      using Ay padic_set_simp0 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: assms padic_mult_closed) \n  show \"\\<one>\\<^bsub>padic_int p\\<^esub> \\<in> carrier (padic_int p)\" \n    by (metis assms monoid.select_convs(2) \n        padic_one_mem partial_object.select_convs(1))\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\ntext\\<open>The padic integers form a commutative ring when p is prime\\<close>\n\nlemma padic_int_is_cring:\n  assumes \"prime (p::nat)\"\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 by auto\n      have Ey: \" (y n) \\<in> carrier (residue_ring (p^n))\" \n        using Ay padic_set_def by auto\n      have Ez: \" (z n) \\<in> carrier (residue_ring (p^n))\" \n        using Az padic_set_def 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 \\<open>Group.comm_monoid (padic_int p)\\<close> assms comm_monoid.is_monoid\n              monoid.m_closed padic_add_closed padic_set_simp2 partial_object.select_convs(1)) \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_simp \n            padic_mult_simp residues.cring by fastforce \n      qed\n    qed\n  qed\nqed\n\ntext\\<open>The padic ring has no nontrivial zero divisors\\<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 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 by auto\n        then show False \n          using C padic_val_def 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\ntext\\<open>padic integers form an integral domain\\<close> \n\nlemma padic_int_is_domain:\n  assumes \"prime (p::nat)\"\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::nat) = \\<zero>\\<^bsub>padic_int p\\<^esub> 1\" by auto\n    show False using assms(1) padic_simps[simp] \n      by (metis (mono_tags, hide_lams) \\<open>\\<one>\\<^bsub>padic_int p\\<^esub> = \\<zero>\\<^bsub>padic_int p\\<^esub>\\<close> monoid.simps(2) \n          of_nat_0_eq_iff of_nat_1 padic_one_def  padic_zero_def ring_record_simps(11) zero_neq_one)\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 by blast\nqed     \n\ntext\\<open>The ultrametric inequality\\<close>\n\nlemma 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: 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_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 (int p^((?vab + 1)))\\<^esub> \" \n      using assms(1) assms(2) zero_below_val \n      by (metis partial_object.select_convs(1)) \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 (int p^((?vab + 1)))\\<^esub> \" \n      using assms(1) assms(3) zero_below_val \n      by (metis partial_object.select_convs(1)) \n    have \"p^(?vab + 1) > 1\" \n      using assms(1) by (metis add.commute plus_1_eq_Suc power_gt1 prime_gt_1_nat)\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 (int p^((?vab + 1)))\\<^esub> \"\n      using A B by (metis (no_types, lifting) S cring.cring_simprules(2)\n          cring.cring_simprules(8) of_nat_power 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\n  have A1: \"(padic_val p b) \\<ge> 0\" \n    using assms(5) padic_val_def by auto\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\n  show ?thesis using P A0 A1 A2 \n    by linarith \nqed\n\nlemma padic_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 (int (p ^ n))\\<^esub> a n\" \n  proof(cases \"n=0\")\n    case True\n    then show ?thesis \n      by (metis (no_types, lifting) assms(1) assms(2) cring.sum_zero_eq_neg of_nat_1 padic_add_inv \n        padic_int_is_cring padic_set_simp2 partial_object.select_convs(1) power_0 \n        res_1_prop residue_ring_def ring_record_simps(11)) \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 (meson assms(1) assms(2) cring.cring_simprules(9) padic_int_is_cring)\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_def padic_zero_def ring_record_simps(11) ring_record_simps(12))\n    have Q: \"(a n) \\<in> carrier (residue_ring (p^n))\" \n      using assms(2) padic_set_simp0 by auto\n    show ?thesis using R Q residues.cring  \n      by (metis P abelian_group.minus_equality assms(1) assms(2)\n          cring.cring_simprules(3) padic_int_is_cring padic_set_simp0\n          partial_object.select_convs(1) residues.abelian_group residues.res_zero_eq)\n  qed\nqed\n\nlemma padic_val_add_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 assms(1) cring.cring_simprules(22) padic_int_is_cring) \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_inv \n    by (metis (no_types, lifting) One_nat_def assms(1) assms(2) cring.cring_simprules(22)\n        nat_power_eq_Suc_0_iff of_nat_1 of_nat_power res_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_inv \n    by (metis (no_types, lifting) assms(1) assms(2) cring.cring_simprules(21)\n        cring.cring_simprules(22) cring.cring_simprules(3) of_nat_power\n        padic_int_is_cring padic_set_simp2 partial_object.select_convs(1) \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 assms(1) assms(2) cring.cring_simprules(9) padic_add_zero padic_int_is_cring ring_record_simps(11))\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 (int p ^ ((Suc (nat ?n))))\\<^esub>\" \n        using assms(1) assms(2) zero_below_val residue_ring_def by auto \n      then have \"(\\<ominus>\\<^bsub>padic_int p\\<^esub> a) (Suc (nat ?n)) =  \\<zero>\\<^bsub>residue_ring (int p ^ ((Suc (nat ?n))))\\<^esub>\" \n        using 0 by simp\n      then show False using below_val_zero assms \n        by (metis (no_types, lifting) Suc_eq_plus1 \\<open>\\<ominus>\\<^bsub>padic_int p\\<^esub> a \\<noteq> padic_zero p\\<close> \n            cring.cring_simprules(3) of_nat_power padic_int_is_cring \n            partial_object.select_convs(1) 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 Suc_eq_plus1 assms(1) partial_object.select_convs(1) ring_record_simps(11)) \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 abelian_group.a_inv_closed padic_is_abelian_group partial_object.select_convs(1)) \n    then show ?thesis \n      using False padic_val_def by auto \n  qed\n  then show ?thesis using A B by auto\nqed\n\nend", "meta": {"author": "AaronCrighton", "repo": "Padics", "sha": "b451038d52193e2c351fe4a44c30c87586335656", "save_path": "github-repos/isabelle/AaronCrighton-Padics", "path": "github-repos/isabelle/AaronCrighton-Padics/Padics-b451038d52193e2c351fe4a44c30c87586335656/padic_construction.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070035949656, "lm_q2_score": 0.7826624840223698, "lm_q1q2_score": 0.7121500756629872}}
{"text": "theory Meta\nimports Complex_Main\nbegin\n\ntheorem sqrt2_not_rational:\n  \"sqrt (real 2) \\<notin> \\<rat>\"\nproof\n  let ?x = \"sqrt (real 2)\"\n  assume \"?x \\<in> \\<rat>\"\n  then obtain m n :: nat where\n    sqrt_rat: \"\\<bar>?x\\<bar> = real m / real n\" and lowest_terms: \"coprime m n\"\n    by (rule Rats_abs_nat_div_natE)\n  hence \"real (m^2) = ?x^2 * real (n^2)\" by (auto simp add: power2_eq_square)\n  hence eq: \"m^2 = 2 * n^2\" using of_nat_eq_iff power2_eq_square by fastforce\n  hence \"2 dvd m^2\" by simp\n  hence \"2 dvd m\" by simp\n  have \"2 dvd n\" proof-\n    from \\<open>2 dvd m\\<close> obtain k where \"m = 2 * k\" ..\n    with eq have \"2 * n^2 = 2^2 * k^2\" by simp\n    hence \"2 dvd n^2\" by simp\n    thus \"2 dvd n\" by simp\n  qed\n  with \\<open>2 dvd m\\<close> have \"2 dvd gcd m n\" by (rule gcd_greatest)\n  with lowest_terms have \"2 dvd 1\" by simp\n  thus False using odd_one by blast\nqed\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/meta/Meta.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070084811306, "lm_q2_score": 0.7826624789529375, "lm_q1q2_score": 0.7121500748744932}}
{"text": "theory ExF010\n  imports Main \nbegin \n  \n\nlemma \"(\\<forall>x. (P x \\<longrightarrow> Q x)) \\<longrightarrow> ((\\<forall>x. P x) \\<longrightarrow> (\\<forall>x. Q x))\"\nproof -\n  {\n    assume a:\"\\<forall>x. (P x \\<longrightarrow> Q x)\"\n    {\n      assume b:\"\\<forall>x. P x\"\n      {\n        fix aa \n        from a have c:\"P aa \\<longrightarrow> Q aa\" by (rule allE)\n        from b have \"P aa\" by (rule allE)\n        with c have \"Q aa\" by (rule mp)\n      }\n      hence \"\\<forall>x. Q x\" by (rule allI)\n    }\n    hence \"(\\<forall>x. P x) \\<longrightarrow> (\\<forall>x. Q x)\" 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/FOL/ExF010.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9099070060380481, "lm_q2_score": 0.7826624789529375, "lm_q1q2_score": 0.7121500729623842}}
{"text": "section \\<open>Commutative Idempotent Modulo\\<close>\n\ntext \\<open>Auxiliary theorem: A formalization of families of operations that are commutative and idempotent modulo an equivalent relation \\<^term>\\<open>R\\<close>.\\<close>\n\ntheory Comm_Idem_Modulo\n  imports Main\nbegin\n\nlocale comm_idem_modulo =\n  fixes f :: \"'a \\<Rightarrow> 'b \\<Rightarrow> 'b\"\n  fixes R :: \"'b \\<Rightarrow> 'b \\<Rightarrow> bool\"\n  assumes equiv_R: \"equivp R\"\n  assumes cong_R: \"R a b \\<Longrightarrow> R (f x a) (f x b)\"\n  assumes f_idem: \"R (f x (f x z)) (f x z)\"\n  assumes f_commute: \"R (f y (f x z)) (f x (f y z))\" begin\n\nlemmas R_refl[simp] = equivp_reflp[OF equiv_R]\nlemmas R_sym = equivp_symp[OF equiv_R]\nlemmas R_trans[trans] = equivp_transp[OF equiv_R]\n\ndefinition F :: \"'a set \\<Rightarrow> 'b \\<Rightarrow> 'b\" where\n  \"F V C = (let V' = (SOME V'. set V' = V \\<and> distinct V') in\n    foldr f V' C)\"\n\nlemma F_empty[simp]: \"F {} C = C\"\n  unfolding F_def apply auto\n  by (metis (mono_tags, lifting) distinct.simps(1) foldr.simps(1) id_apply some_equality)\n\nlemma F_singleton[simp]: \"F {x} C = f x C\"\nproof -\n  have \"(SOME V'. set V' = {x} \\<and> distinct V') = [x]\"\n    apply (rule someI2_ex)\n    apply (metis List.set_insert distinct.simps(1) distinct_insert list.set(1))\n    by (metis distinct.simps(2) distinct_length_2_or_more empty_set insert_not_empty list.exhaust singletonD)\n  then show \"F {x} C = f x C\"\n    unfolding F_def by simp\nqed\n\nlemma F_foldr: \"R (F (set V) C) (foldr f V C)\"\nproof -\n  define V' where \"V' = (SOME V'. set V' = set V \\<and> distinct V')\"\n  let ?eq = \"\\<lambda>V V'. R (foldr f V C) (foldr f V' C)\"\n\n  have eq: \"R (F (set V) C) (foldr f V' C)\"\n    unfolding F_def V'_def by simp\n\n  have induct[case_names 0 greater[pos IH]]: \"P n\"\n    if \"P 0\" and \"\\<And>n. n >= 1 ==> (\\<And>m. m < n \\<Longrightarrow> P m) \\<Longrightarrow> P n\" for P and n :: nat\n    apply (rule full_nat_induct) using that\n    by (metis One_nat_def Suc_leI neq0_conv)\n\n  have \"set V = set V' \\<and> distinct V'\"\n    unfolding V'_def apply (rule someI2_ex) \n    by (simp_all add: finite_distinct_list)\n    \n  then have \"set V = set V'\" and \"distinct V'\"\n    by auto\n\n  then have \"R (foldr f V C) (foldr f V' C)\"\n  proof (induction \"length V\" arbitrary: V V' rule:induct)\n    case 0\n    then show ?case\n      by simp\n  next\n    case greater\n    from greater(1)\n    obtain a V2 where V: \"V = a # V2\" and n: \"length V2 <= length V\"\n      apply atomize_elim\n      by (metis One_nat_def Suc_le_length_iff add.commute le_add2 list.size(4))\n\n    consider (empty_V') \"V' = []\"\n      | (V'_a) V'2 where \"V' = a # V'2\" and \"a \\<notin> set V2\"\n      | (V'_a2) V'2 where \"V' = a # V'2\" and \"a \\<in> set V2\"\n      | (V'_b) V'2 b where \"V' = b # V'2\" and \"a \\<noteq> b\"\n      apply atomize_elim\n      by (metis list.exhaust)\n    then show ?case\n    proof cases\n      case empty_V'\n      then show ?thesis apply auto\n        using greater.prems(1) V by auto\n    next\n      case V'_a\n      with V greater\n      have eq: \"set V2 = set V'2\" and dst: \"distinct V'2\"\n        apply auto  \n        using V'_a apply fastforce\n        by (simp add: insert_ident)\n\n      have \"R (foldr f V2 C) (foldr f V'2 C)\"\n        apply (rule greater(2))\n        using V eq dst by auto\n      then show ?thesis\n        unfolding V'_a V\n        by (simp add: cong_R)\n    next\n      case V'_a2\n      with greater V have eq: \"set V2 = set (a # V'2)\" and dst: \"distinct (a # V'2)\"\n        by (auto simp add: insert_absorb)\n      have \"R (foldr f V2 C) (foldr f (a # V'2) C)\"\n        apply (rule greater)\n        using V eq dst by auto\n      then have \"R (foldr f (a # V2) C) (foldr f (a # V') C)\"\n        unfolding V'_a2\n        by (simp add: cong_R)\n      also have \"R \\<dots> (foldr f V' C)\"\n        unfolding V'_a2 using f_idem by auto\n      finally show ?thesis\n        by (simp add: V)\n    next\n      case V'_b\n      define V2b where \"V2b = filter (\\<lambda>x. x\\<noteq>b) (remdups V2)\"\n      then have *: \"set V2 = set (b # V2b)\"\n        using V V'_b(1) V'_b(2) greater.prems(1) by fastforce\n      have len: \"length (a # V2b) < length V\"\n      proof -\n        have \"length (a # V2b) = Suc (length V2b)\"\n          by simp\n        also have \"Suc (length V2b) \\<le> length (remdups V2)\"\n          by (smt \"*\" V2b_def card_set distinct.simps(2) distinct_card distinct_filter distinct_remdups dual_order.order_iff_strict length_Cons mem_Collect_eq set_filter)\n        also have \"\\<dots> \\<le> length V2\"\n          by simp\n        also have \"\\<dots> < length V\"\n          by (simp add: V)\n        finally show ?thesis by -\n      qed\n\n      have \"V = a # V2\"\n        by (simp add: V)\n      also have \"?eq V2 (b # V2b)\"\n        apply (rule greater)\n        using V * V2b_def by auto\n      then have \"?eq (a # V2) (a # b # V2b)\"\n        by (simp add: cong_R)\n      also have \"?eq (a # b # V2b) (b # a # V2b)\"\n        using f_commute by simp\n      also have *: \"set (a # V2b) = set V'2\"\n        unfolding V2b_def apply auto\n        using V V'_b(1) V'_b(2) greater.prems(1) apply auto[3]\n        using V'_b(1) greater.prems(2) by auto\n      have \"?eq (a # V2b) V'2\"\n        apply (rule greater)\n        using len * V'_b(1) greater.prems(2) by auto\n      then have \"?eq (b # a # V2b) (b # V'2)\"\n        by (simp add: cong_R)\n      also have \"b # V'2 = V'\"\n        by (simp add: V'_b(1))\n      finally show ?thesis by -\n    qed\n\n  qed\n\n  then show ?thesis\n    using R_sym R_trans eq by blast\nqed\n\nlemma R_cong_F: \n  assumes \"R C D\"\n  shows \"R (F X C) (F X D)\"\nproof -\n  define X' where \"X' = (SOME X'. set X' = X \\<and> distinct X')\"\n  have \"R (foldr f X' C) (foldr f X' D)\"\n    apply (induction X')\n    using assms cong_R by auto\n  then show ?thesis\n    by (simp add: F_def X'_def[symmetric] Let_def)\nqed\n\nlemma F_join:\n  assumes \"finite V\" and \"finite W\"\n  shows \"R (F V (F W C)) (F (V\\<union>W) C)\"\nproof -\n  from assms\n  obtain V' W' where V: \"V = set V'\" and W: \"W = set W'\"\n    apply atomize_elim using finite_list by auto\n  have \"R (F W C) (foldr f W' C)\"\n    unfolding W\n    by (simp add: F_foldr)\n  then have \"R (F V (F W C)) (F V (foldr f W' C))\"\n    using R_cong_F by blast\n  also have \"R \\<dots> (foldr f V' (foldr f W' C))\"\n    by (simp add: V F_foldr)\n  also have \"\\<dots> = foldr f (V'@W') C\"\n    by auto\n  also have \"R \\<dots> (F (set (V'@W')) C)\"\n    using R_sym F_foldr by blast\n  also have \"set (V'@W') = V\\<union>W\"\n    unfolding V W by simp\n  finally show ?thesis\n    by -\nqed\n\nlemma F_insert:\n  assumes \"finite Y\"\n  shows \"R (F (insert x Y) C) (f x (F Y C))\"\nproof -\n  have \"F (insert x Y) C = F ({x} \\<union> Y) C\"\n    by simp\n  also have \"R \\<dots> (F {x} (F Y C))\"\n    apply (rule R_sym)\n    apply (rule F_join)\n    using assms by auto\n  also have \"\\<dots> = f x (F Y C)\"\n    by simp\n  finally show ?thesis\n    by -\nqed\n\nlemma F_insert':\n  assumes \"finite Y\"\n  shows \"R (F (insert x Y) C) (F Y (f x C))\"\nproof -\n  have \"F (insert x Y) C = F (Y \\<union> {x}) C\"\n    by simp\n  also have \"R \\<dots> (F Y (F {x} C))\"\n    apply (rule R_sym)\n    apply (rule F_join)\n    using assms by auto\n  also have \"\\<dots> = F Y (f x C)\"\n    by simp\n  finally show ?thesis\n    by -\nqed\n\nlemma F_intro:\n  assumes \"finite X\"\n  assumes \"\\<And>X'. set X' = X \\<Longrightarrow> distinct X' \\<Longrightarrow> P (foldr f X')\"\n  shows \"P (F X)\"\n    unfolding F_def Let_def\n    apply (rule assms(2))\n    apply (rule someI2_ex)\n    apply (simp_all add: assms(1) finite_distinct_list)[2]\n    apply (rule someI2_ex)\n    by (simp_all add: assms(1) finite_distinct_list)[2]\n\n\nlemma F_induct[consumes 1, case_names base step[IH X]]:\n  assumes finite: \"finite X\"\n  assumes base: \"P {} C\"\n  assumes step: \"\\<And>D Y x. P Y D \\<Longrightarrow> x\\<in>X \\<Longrightarrow> Y \\<subseteq> X \\<Longrightarrow> x \\<notin> Y \\<Longrightarrow> P (insert x Y) (f x D)\"\n  shows \"P X (F X C)\"\n  using finite\nproof (rule F_intro)\n  fix X' :: \"'a list\"\n  assume \"distinct X'\"\n  assume \"set X' = X\"\n  then have \"set X' \\<subseteq> X\"\n    by simp\n  with \\<open>distinct X'\\<close> \n  have \"P (set X') (foldr f X' C)\"\n  proof (induction X')\n    case Nil\n    from assms show ?case by simp\n  next\n    case (Cons a X')\n    show ?case \n      apply simp\n      apply (rule step)\n      using Cons by auto\n  qed\n  then show \"P X (foldr f X' C)\"\n    using \\<open>set X' = X\\<close> by blast\nqed\n\nlemma F_induct'[consumes 1, case_names base step[IH X]]:\n  assumes finite: \"finite X\"\n  assumes base: \"P {} id\"\n  assumes step: \"\\<And>G Y x. P Y G \\<Longrightarrow> x\\<in>X \\<Longrightarrow> Y \\<subseteq> X \\<Longrightarrow> x \\<notin> Y \\<Longrightarrow> P (insert x Y) (\\<lambda>C. f x (G C))\"\n  shows \"P X (F X)\"\n  using finite\nproof (rule F_intro)\n  fix X' :: \"'a list\"\n  assume \"distinct X'\"\n  assume \"set X' = X\"\n  then have \"set X' \\<subseteq> X\"\n    by simp\n  with \\<open>distinct X'\\<close> \n  have \"P (set X') (foldr f X')\"\n  proof (induction X')\n    case Nil\n    from assms show ?case \n      by (auto simp: id_def)\n  next\n    case (Cons a X')\n    show ?case \n      apply simp\n      thm step\n      apply (rule step)\n      using Cons by auto\n  qed\n  then show \"P X (foldr f X')\"\n    using \\<open>set X' = X\\<close> by blast\nqed\n\n\nend\n\n\nend", "meta": {"author": "dominique-unruh", "repo": "qrhl-local-variables-isabelle", "sha": "372d8b88b62628a1088931392e71d82302178512", "save_path": "github-repos/isabelle/dominique-unruh-qrhl-local-variables-isabelle", "path": "github-repos/isabelle/dominique-unruh-qrhl-local-variables-isabelle/qrhl-local-variables-isabelle-372d8b88b62628a1088931392e71d82302178512/Comm_Idem_Modulo.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424373085146, "lm_q2_score": 0.8418256512199033, "lm_q1q2_score": 0.7121360431817925}}
{"text": "theory FreeGroupMain\nimports Main \"HOL-Algebra.Group\"\nbegin\n\ntype_synonym ('a,'b) monoidgentype = \"'a \\<times> 'b\"\n\n\ntype_synonym ('a,'b) groupgentype = \"('a,'b) monoidgentype \\<times> bool\"\n\ntext \\<open>Words are defined as lists over groupgentype\\<close>\ntype_synonym ('a,'b) word = \"(('a,'b) groupgentype) list\"\n\ntext \\<open>We define the inverse of a groupgentype element\\<close>\nfun inverse::\"('a,'b) groupgentype \\<Rightarrow> ('a,'b) groupgentype\"\n  where\n\"inverse (x, True) = (x, False)\"\n|\"inverse (x, False) = (x, True)\"\n\nlemma inverse_of_inverse:\n  assumes \"g = inverse h\"\n  shows \"h = inverse g\"\n  using assms inverse.simps \n  by (metis inverse.elims)\n\ndefinition invgen ::  \"('a,'b) monoidgentype set \\<Rightarrow> ('a,'b) groupgentype set\" (\"_\\<^sup>\\<plusminus>\")\n  where\n\"S \\<^sup>\\<plusminus> = S \\<times> {True,False}\"\n\ntext \\<open>Following definitions define the set of words in the span of a set\\<close>\ninductive_set words_on::\"('a,'b) groupgentype set \\<Rightarrow> ('a,'b) word set\" (\"_\\<^sup>\\<star>\")\n  for S::\"('a,'b) groupgentype set\"\n  where\nempty:\"[] \\<in> (S\\<^sup>\\<star>)\"\n|gen:\"x \\<in> S \\<Longrightarrow> xs \\<in> (S\\<^sup>\\<star>) \\<Longrightarrow> (x#xs) \\<in> (S\\<^sup>\\<star>)\"\n\ndefinition freewords_on::\"('a,'b) monoidgentype set \\<Rightarrow> ('a,'b) word set\" (\"\\<langle>_\\<rangle>\")\n  where\n\"\\<langle>S\\<rangle>  = words_on (invgen S)\"\n\ntext\\<open>Some lemmas about words on a set.\\<close>\n\nlemma cons_span: \n  assumes \"(x#xs) \\<in> (words_on S)\" \n    shows \"[x] \\<in> (words_on S)\"\nproof(induction xs)\n  case Nil\n  then show ?case using assms words_on.cases words_on.empty words_on.gen\n    by (metis list.distinct(1) list.sel(1))\nnext\n  case (Cons y xs)\n  then show ?case  by auto\nqed\n\nlemma span_append:\n  assumes \"xs \\<in> (words_on S)\" \"ys \\<in> (words_on S)\" \n    shows \"(xs@ys) \\<in> (words_on S)\"\n    using assms\nproof(induction xs)\n  case empty\n  then show ?case by simp\nnext\n  case (gen x)\n  then show ?case using  words_on.gen  by (metis Cons_eq_appendI)\nqed\n\nlemma span_cons:\n  assumes \"(x#xs) \\<in> (words_on S)\" \n  shows \"xs \\<in> (words_on S)\"\n  using assms\nproof(induction xs)\n  case Nil\n  then show ?case  by (simp add: words_on.empty)\nnext\n  case (Cons a xs)\n  then show ?case  using words_on.cases  words_on.gen  by blast\nqed\n\nlemma leftappend_span: \n  assumes \"(xs@ys) \\<in> (words_on S)\" shows \"xs \\<in> (words_on S)\"\n  using assms\nproof(induction xs)\n  case Nil\n  then show ?case using words_on.empty by simp\nnext\n  case (Cons a1 a2)\n  then have 1: \"(a1#(a2 @ ys)) \\<in> (words_on S)\" by auto\n  then have 2:\"[a1] \\<in> (words_on S)\" using cons_span by blast\n  have \"(a2 @ ys) \\<in> (words_on S)\" using span_cons Cons 1 by blast\n  then have \"a2 \\<in> (words_on S)\" using Cons by simp\n  moreover have \"(a1#a2)  = [a1] @ a2\" by simp\n  ultimately show ?case using 1 2 span_append  by metis \nqed\n\nlemma rightappend_span: \n  assumes \"(xs@ys) \\<in> (words_on S)\" \n    shows \"ys \\<in>  (words_on S)\"\n    using assms\nproof(induction xs)\ncase Nil\n  then show ?case using empty by simp\nnext\n  case (Cons a1 a2)\n then have 1: \"(a1#(a2 @ ys)) \\<in> (words_on S)\" by auto\n  then have 2:\"[a1] \\<in> (words_on S)\" using cons_span by blast\n  have \"(a2 @ ys) \\<in> (words_on S)\" using span_cons Cons 1 by blast\n  then show ?case using Cons by blast\nqed\n\nlemma span_inverse: \n  assumes \"x \\<in> invgen S\" \n    shows \"inverse x \\<in> invgen S\"\nproof-\n  let ?g = \"fst x\"\n  let ?b = \"snd x\"\n  have x: \"x = (?g, ?b)\" by simp\n  have g:\"?g \\<in> S\"using assms invgen_def by (metis eq_fst_iff mem_Sigma_iff)\n  show ?thesis\n  proof(cases \"?b = False\")\n    case True\n    have \"(?g, True) \\<in> invgen  S\" using g by (simp add: invgen_def)\n    then show ?thesis using True inverse.simps(2) x by metis\n  next\n    case False\n    have \"(?g, False) \\<in> invgen  S\" using g by (simp add: invgen_def)\n    then show ?thesis using False inverse.simps(1) x  by metis\n  qed\nqed\n\ntext \\<open>wordinverse xs recursively defines the reverse of a word with its elements\n      mapped to their inverses, and will be used to define the inverses of elements\n      of a free group.\\<close>\n\n\nprimrec wordinverse::\"('a,'b) word \\<Rightarrow> ('a, 'b) word\"\n  where\n\"wordinverse [] = []\"\n|\"wordinverse (x#xs) =  (wordinverse xs)@[inverse x]\"\n\ntext \\<open>Alternate definitions of wordinverse (defined using rev and map) which might\n       be more convenient in some circumstances.\\<close>\n\nlemma wordinverse_redef1: \n  \"wordinverse xs = rev (map inverse xs)\"\nproof(induction xs)\n  case Nil\n  then show ?case by simp\nnext\n  case (Cons a xs)\n  have 1:\"wordinverse (a#xs) = wordinverse xs @ [inverse a]\" by auto\n  have \"rev (map inverse (a#xs)) = rev((inverse a#( map inverse xs)))\" by simp\n  then have 2: \"rev (map inverse (a#xs)) = rev (map inverse (xs)) @ [inverse a]\" by simp\n  then show ?case using 1 2 Cons.IH by simp\nqed\n\nlemma wordinverse_redef2: \n  \"wordinverse xs = map inverse (rev xs)\"\nproof(induction xs)\ncase Nil\n  then show ?case by simp\nnext\n  case (Cons a xs)\n  have 1:\"wordinverse (a#xs) = wordinverse xs @ [inverse a]\" by auto\n  have \"map inverse (rev (a#xs)) = map inverse (rev xs @ [a])\"  by simp\n  then have 2: \"map inverse (rev (a#xs)) = map inverse (rev xs) @ [inverse a]\"  by simp\n  then show ?case using 1 2 Cons.IH by auto\nqed\n\ntext \\<open>Some lemmas about wordinverse.\\<close>\n\nlemma span_wordinverse: \n  assumes \"xs \\<in> \\<langle>S\\<rangle>\" \n    shows \"wordinverse xs \\<in> \\<langle>S\\<rangle>\"\n    using assms unfolding freewords_on_def\nproof(induction xs)\n  case empty\n  then show ?case by (simp add: words_on.empty)\nnext\n  case (gen x xs)\n  then have \"inverse x \\<in> invgen  S\"  by (simp add: span_inverse)\n  then have \"[inverse x] \\<in> (words_on (invgen S))\" using words_on.empty words_on.gen by blast\n  then have \"wordinverse xs @ [inverse x] \\<in> (words_on (invgen S))\" using gen span_append by auto\n  moreover have \"wordinverse (x#xs) = wordinverse xs @ [inverse x]\" by simp\n  ultimately show ?case  by simp\nqed\n\nlemma wordinverse_append: \n  \"(wordinverse xs) @ (wordinverse ys) = (wordinverse (ys@xs))\"\nproof(induction ys)\n  case Nil\n  have \"wordinverse [] = []\" by simp\n  then show ?case by simp\nnext\n  case (Cons a y)\n  have \"(wordinverse xs) @ (wordinverse (a # y)) = (wordinverse xs) @ (wordinverse y) @ [inverse a]\" by simp\n  moreover have \"(wordinverse ((a#y)@xs)) = (wordinverse (y@xs)) @ [inverse a]\" by simp\n  ultimately show ?case using \"Cons.IH\" by simp\nqed\n\nlemma wordinverse_of_wordinverse:  \n    \"wordinverse (wordinverse xs) = xs\" \nproof(induction xs)\n  case Nil\n  then show ?case by auto\nnext\n  case (Cons a xs)\n  have 1: \"wordinverse (a#xs) = (wordinverse xs) @ [inverse a]\" by auto\n  have \"wordinverse [inverse a] = [a]\" using inverse_of_inverse \n    by (metis append_Nil list.simps(8) list.simps(9) rev.simps(1) rev.simps(2) wordinverse_redef2)\n  then have 2:\"wordinverse ((wordinverse xs) @ [inverse a]) = [a] @ wordinverse (wordinverse xs)\" using wordinverse_append by metis\n  then have \"[a] @ wordinverse (wordinverse xs) = [a] @ xs\" using Cons by auto\n  moreover have \"[a] @ xs = (a#xs)\" by simp\n  ultimately show ?case using 1 2 by simp\nqed\n\nlemma wordinverse_symm:\n  assumes \"wordinverse xs = ys\" \n    shows \"xs = wordinverse ys\"\nproof-\n  have \"wordinverse (wordinverse xs) = wordinverse ys\"  using assms by auto\n  then show ?thesis using wordinverse_of_wordinverse by metis\nqed\n\ntext\\<open>reduced words are words where no element and its inverse occur ext to each \n      other.\\<close>\n\nfun reduced::\"('a,'b) word \\<Rightarrow> bool\"\n  where\n\"reduced [] = True\"\n|\"reduced [x] = True\"\n|\"reduced (x#y#xs) = (if (x \\<noteq> inverse y) then reduced (y#xs) else False)\"\n\ntext\\<open>reln\\<close>\n\ninductive reln::\"('a,'b) word \\<Rightarrow> ('a,'b) word \\<Rightarrow> bool\" (infixr \"~\" 65)\n  where\nrefl[intro!]: \"xs ~ xs\" |\nsym: \"xs ~ ys \\<Longrightarrow> ys ~ xs\" |\ntrans: \"xs ~ ys \\<Longrightarrow> ys ~ zs \\<Longrightarrow> xs ~ zs\" |\nbase: \"[x, inverse x] ~ []\" |\nmult: \"xs ~ xs' \\<Longrightarrow> ys ~ ys' \\<Longrightarrow> (xs@ys) ~ (xs'@ys')\"\n\ndefinition reln_tuple :: \"(('a,'b) word) set \\<Rightarrow>(('a,'b) word \\<times> ('a,'b) word) set\"\n  where\n\"reln_tuple S = {(xs,ys).xs~ys \\<and> xs \\<in> S \\<and> ys \\<in> S}\" \n\nlemma wordinverse_inverse: \n  \"(xs @ (wordinverse xs)) ~ []\"\nproof(induction xs)\n  case Nil\n  have \"[] = []\" by simp\n  then show ?case by (simp add: reln.refl)\nnext\n  case (Cons a xs)\n  have \"wordinverse (a#xs) = (wordinverse xs) @ [inverse a]\"  by simp\n  moreover have \"(a#xs) = [a] @ xs\" by simp\n  ultimately have 1: \"((a # xs) @ wordinverse (a # xs)) = [a] @ xs @ (wordinverse xs) @  [inverse a]\" by (metis append_assoc)\n  have \"([a] @ xs @ (wordinverse xs)) ~ [a] @ []\"  using Cons.IH mult by blast\n  then have \"([a] @ xs @ (wordinverse xs)) ~ [a]\"  by auto\n  moreover have \"[inverse a] ~ [inverse a]\" by (simp add: reln.refl)\n  ultimately have \"([a] @ xs @ (wordinverse xs) @  [inverse a]) ~ [a] @ [inverse a]\" using mult by (metis append_assoc)\n  then have \"([a] @ xs @ (wordinverse xs) @  [inverse a]) ~ []\" by (simp add: base reln.trans)\n  then show ?case using 1 by auto\nqed\n\nlemma inverse_wordinverse: \n  \"((wordinverse xs) @  xs) ~ []\"\nproof-\n  let ?ys = \"wordinverse xs\"\n  have \"(wordinverse ?ys = xs)\" sledgehammer\n    by (metis wordinverse_symm) \n  moreover have \"(?ys @ wordinverse ?ys) ~ []\" using wordinverse_inverse by blast\n  ultimately show ?thesis using wordinverse_of_wordinverse by simp\nqed\n\nlemma reln_refl: \n  \"refl_on \\<langle>S\\<rangle> (reln_tuple \\<langle>S\\<rangle>)\"\nproof-\n  have \"(\\<And>xys. xys \\<in> (reln_tuple \\<langle>S\\<rangle>) \\<Longrightarrow> xys \\<in> \\<langle>S\\<rangle> \\<times> \\<langle>S\\<rangle>)\"\n  proof-\n    fix xys assume 1: \"xys \\<in> (reln_tuple \\<langle>S\\<rangle>)\"\n    let ?a = \"(fst xys)\"\n    let ?b = \"(snd xys)\"\n    have \"(?a, ?b) \\<in> (reln_tuple \\<langle>S\\<rangle>)\" by (simp add: \"1\")\n    then have \"(?a, ?b) \\<in> \\<langle>S\\<rangle> \\<times> \\<langle>S\\<rangle>\" using reln_tuple_def by (metis (no_types, lifting) Product_Type.Collect_case_prodD SigmaI prod.collapse)\n    then show \"xys \\<in> \\<langle>S\\<rangle> \\<times> \\<langle>S\\<rangle>\" by simp\n  qed\n  then have A:\"reln_tuple \\<langle>S\\<rangle> \\<subseteq> \\<langle>S\\<rangle> \\<times> \\<langle>S\\<rangle>\" by (simp add: subsetI)\n  have \"(\\<And>xs. xs\\<in>\\<langle>S\\<rangle> \\<Longrightarrow> (xs, xs) \\<in> reln_tuple \\<langle>S\\<rangle>)\"\n  proof-\n    fix xs assume \"xs\\<in>\\<langle>S\\<rangle>\"\n    moreover have \"xs ~ xs\" by (simp add: reln.refl)\n    ultimately show \"(xs, xs) \\<in> reln_tuple \\<langle>S\\<rangle>\" by (simp add: reln_tuple_def)\n  qed\n  then have \"(\\<forall>xs\\<in>\\<langle>S\\<rangle>. (xs, xs) \\<in> reln_tuple \\<langle>S\\<rangle>)\" by simp\n  then show ?thesis using A unfolding refl_on_def  by simp\nqed\n\nlemma reln_sym: \n  \"sym (reln_tuple \\<langle>S\\<rangle>)\"\nproof-\n  have \"(\\<And>xs ys. (xs, ys) \\<in> (reln_tuple \\<langle>S\\<rangle>) \\<Longrightarrow> (ys, xs) \\<in> (reln_tuple \\<langle>S\\<rangle>))\"\n  proof- \n    fix xs ys assume 1:\"(xs,ys)\\<in>(reln_tuple \\<langle>S\\<rangle>)\"\n    then have 2:\"xs ~ ys\" using reln_tuple_def 1 by (metis (no_types, lifting) case_prodD mem_Collect_eq)\n    then have \"ys ~ xs\" by (simp add: 2 reln.sym)\n    then show \"(ys, xs) \\<in> reln_tuple \\<langle>S\\<rangle>\" \n      using 1 by (simp add: reln_tuple_def)\n  qed\n  then have \"(\\<forall>xs ys. (xs, ys) \\<in> (reln_tuple \\<langle>S\\<rangle>) \\<longrightarrow> (ys, xs) \\<in> (reln_tuple \\<langle>S\\<rangle>))\" by simp\n  then show ?thesis unfolding sym_def  by simp\nqed\n\nlemma reln_trans: \n  \"trans (reln_tuple \\<langle>S\\<rangle>)\"\nproof-\n  have \"(\\<And>xs ys zs. (xs, ys) \\<in> (reln_tuple \\<langle>S\\<rangle>) \\<Longrightarrow> (ys, zs) \\<in> (reln_tuple \\<langle>S\\<rangle>) \\<Longrightarrow> (xs, zs) \\<in> (reln_tuple \\<langle>S\\<rangle>))\"\n  proof-\n    fix xs ys zs assume 1:\"(xs,ys)\\<in>(reln_tuple \\<langle>S\\<rangle>)\" assume 2: \"(ys, zs) \\<in> (reln_tuple \\<langle>S\\<rangle>)\"\n    have \"xs ~ ys\" using reln_tuple_def 1 by (metis (no_types, lifting) case_prodD mem_Collect_eq)\n    moreover have \"ys ~ zs\" using reln_tuple_def 2 by (metis (no_types, lifting) case_prodD mem_Collect_eq)\n    ultimately have \"xs ~ zs\" using reln.trans by auto\n    then show \"(xs, zs) \\<in> reln_tuple \\<langle>S\\<rangle>\" using 1 2 by (simp add: reln_tuple_def)\n  qed\n  then have \"(\\<forall>xs ys zs. (xs, ys) \\<in> (reln_tuple \\<langle>S\\<rangle>) \\<longrightarrow> (ys, zs) \\<in> (reln_tuple \\<langle>S\\<rangle>) \\<longrightarrow> (xs, zs) \\<in> (reln_tuple \\<langle>S\\<rangle>))\" by simp\n  then show ?thesis unfolding trans_def by simp\nqed\n\nlemma reln_equiv: \n  \"equiv \\<langle>S\\<rangle> (reln_tuple \\<langle>S\\<rangle>)\"\n  by (simp add: equivI reln_refl reln_sym reln_trans)\n\ntext\\<open>The following Congruence and projected functions and the subsequent results,\nCongruent2 and ProjFun2 are adapted from IsarMathLib. Original formalisations are\n available on https://isarmathlib.org/EquivClass1.html.\\<close>\n\ndefinition Congruent2 :: \"('a \\<times> 'a) set \\<Rightarrow> ('a \\<Rightarrow> 'a \\<Rightarrow> 'a) \\<Rightarrow> bool\"\n  where\n\"Congruent2 r f \\<longleftrightarrow> (\\<forall> x1 x2 y1 y2. (x1, x2) \\<in> r \\<and> (y1, y2) \\<in> r \n                                  \\<longrightarrow> (f x1 y1, f x2 y2)  \\<in> r)\"\n\nlemma append_congruent: \n  \"Congruent2 (reln_tuple \\<langle>S\\<rangle>) (@)\"\nproof-\n  have \"\\<And>x1 x2 y1 y2. \\<lbrakk>(x1, x2) \\<in> reln_tuple \\<langle>S\\<rangle> ; (y1, y2) \\<in> reln_tuple \\<langle>S\\<rangle>\\<rbrakk> \\<Longrightarrow> (x1 @ y1, x2 @ y2) \\<in> reln_tuple \\<langle>S\\<rangle>\"\n  proof-\n    fix x1 x2 y1 y2 assume 1:\"(x1, x2) \\<in> (reln_tuple \\<langle>S\\<rangle>)\" \"(y1, y2) \\<in> (reln_tuple \\<langle>S\\<rangle>)\"\n  have \"x1 \\<in>  \\<langle>S\\<rangle> \\<and> x2 \\<in> \\<langle>S\\<rangle>\" using 1 reln_tuple_def by auto\n  moreover have \"y1 \\<in>  \\<langle>S\\<rangle> \\<and> y2 \\<in> \\<langle>S\\<rangle>\" using 1 reln_tuple_def by auto\n  ultimately have A:\"(x1@y1) \\<in>  \\<langle>S\\<rangle> \\<and> (x2@y2) \\<in> \\<langle>S\\<rangle>\" unfolding freewords_on_def by (simp add: span_append)\n  have \"x1 ~ x2\" using 1 reln_tuple_def by auto\n  moreover have \"y1 ~ y2\" using 1 reln_tuple_def by auto\n  ultimately have \"(x1@y1) ~ (x2@y2)\" using mult by auto\n  then show \"((x1@y1) , (x2@y2)) \\<in> (reln_tuple \\<langle>S\\<rangle>)\" using A reln_tuple_def by auto\nqed\n  thus ?thesis  using Congruent2_def by blast\nqed\n\ndefinition ProjFun2 :: \"('a\\<times>'a) set \\<Rightarrow> ('a\\<Rightarrow>'a \\<Rightarrow>'a) \\<Rightarrow>\n                   ('a set \\<Rightarrow> 'a set \\<Rightarrow> 'a set) \" where\n\"ProjFun2 r f =  (\\<lambda>p q. (\\<Union>x\\<in>(p\\<times>q) .r `` {f (fst x) (snd x)}))\"\n\nlemma equiv_2f_con: \n  assumes \"equiv A r\"  \n      and \"Congruent2 r f\" \n      and \"C1\\<in>A//r\" \"C2\\<in>A//r\" \n      and \"y1\\<in>C1\" \"z1\\<in>C1\" \"y2\\<in>C2\" \"z2\\<in>C2\"\n    shows \"r `` {(f y1 y2)} = r `` {(f z1 z2)}\"\nproof-\n  have \"(y1, z1) \\<in> r\" by (meson assms(1) assms(3) assms(5) assms(6) quotient_eq_iff)\n  moreover have \"(y2, z2) \\<in> r\" by (meson assms(1) assms(4) assms(7) assms(8) quotient_eq_iff)\n  ultimately have \"((f y1 y2),(f z1 z2)) \\<in> r\"  using Congruent2_def assms(2) by fastforce\n  then show ?thesis  by (meson assms(1) equiv_class_eq)\nqed\n\nlemma equiv_2f_clos: \n  assumes \"equiv A r\"  \n      and \"Congruent2 r f\" \"C1\\<in>A//r\"  \"C2\\<in>A//r\"  \"y1\\<in>C1\"  \"y2\\<in>C2\"\n    shows \"(f y1 y2) \\<in> A\"\nproof-\n  have y:\"y1 \\<in> A\" using Union_quotient assms(1) assms(3) assms(5) by auto\n  have z:\"y2 \\<in> A\" using Union_quotient assms(1) assms(4) assms(6) by auto\n  have yy: \"(y1,y1) \\<in> r\" by (metis assms(1) assms(3) assms(5) quotient_eq_iff)\n  have zz:  \"(y2,y2) \\<in> r\" by (metis assms(1) assms(4) assms(6) quotient_eq_iff)\n  have \"(f y1 y2, f y1 y2) \\<in> r\" using yy zz using Congruent2_def assms(2) by fastforce\n  then show ?thesis by (metis assms(1) equiv_class_eq_iff)\nqed\n\nlemma union_eq_2f_in:\n  assumes \"C1\\<times>C2\\<noteq>{}\"  \n      and \"\\<forall>x\\<in>C1\\<times>C2. r``{ (b (fst x) (snd x))}\\<in>A//r\"  \n      and \"\\<forall>x y. x\\<in>C1\\<times>C2\\<and>y\\<in>C1\\<times>C2\\<longrightarrow> r``{(b (fst x) (snd x))}= r``{(b (fst y) (snd y))}\" \n    shows \"(\\<Union>x\\<in>C1\\<times>C2. r``{(b (fst x) (snd x))} )\\<in>A//r\"\nproof-\n  obtain x where A:\"x\\<in>C1\\<times>C2\" using assms(1) by auto\n  then have \"\\<forall>y\\<in>C1\\<times>C2. r``{(b (fst x) (snd x))}= r``{(b (fst y) (snd y))}\" using assms(3) by blast\n  then have \"(\\<Union>y\\<in>C1\\<times>C2. r``{(b (fst y) (snd y))}) = r``{(b (fst x) (snd x))}\"  using assms(1) by blast\n    then show ?thesis using A  by (simp add: assms(2))\n  qed\n\nlemma proj2fun_clos:\n  assumes \"equiv A r\"  \n      and \"Congruent2 r f\" \n      and \"C1\\<in>A//r\" \"C2\\<in>A//r\"\n    shows \"((ProjFun2  r f) C1 C2) \\<in> A//r\"\nproof-\n  have \"\\<And>z. z\\<in>C1\\<times>C2 \\<Longrightarrow> f (fst z) (snd z)\\<in>A\" \n  proof-\n    fix z assume z: \"z\\<in>C1\\<times>C2\"\n    show \"f (fst z) (snd z) \\<in> A\" using equiv_2f_clos using assms(1) assms(2) assms(3) assms(4) z by fastforce\n  qed\n  then have \"\\<forall>z\\<in>C1\\<times>C2. f (fst z) (snd z)\\<in>A\" by simp\n  then have \"\\<forall>z\\<in>C1\\<times>C2. r``{f (fst z) (snd z)}\\<in>A//r\" by (simp add: quotientI)\n  moreover have \"\\<forall>z1 z2. z1\\<in>C1\\<times>C2\\<and>z2\\<in>C1\\<times>C2\\<longrightarrow>  r ``{f (fst(z1)) (snd(z1))} = r `` {f (fst(z2)) (snd(z2))}\"\n  proof-\n    have \"\\<And>z1 z2. z1\\<in>C1\\<times>C2\\<and>z2\\<in>C1\\<times>C2 \\<Longrightarrow>  r ``{f (fst(z1)) (snd(z1))} = r `` {f (fst(z2)) (snd(z2))}\"\n    proof-\n      fix z1 z2 assume 1:\"z1\\<in>C1\\<times>C2\\<and>z2\\<in>C1\\<times>C2\"\n      have 2:\"(fst(z1)) \\<in>C1\" using 1 by auto\n      have 3:\"(fst(z2)) \\<in>C1\" using 1 by auto\n      have 4:\"(snd(z1)) \\<in>C2\" using 1 by auto\n      have 5:\"(snd(z2)) \\<in>C2\" using 1 by auto\n      show \" r ``{f (fst(z1)) (snd(z1))} = r `` {f (fst(z2)) (snd(z2))}\" using equiv_2f_con[of \"A\" \"r\" \"f\" \"C1\" \"C2\" \"(fst(z1))\" \"(fst(z2))\" \"(snd(z1))\" \"(snd(z2))\"]   1 2 3 4 5  assms(1) assms(2) assms(3) assms(4) by simp\n    qed\n    then show ?thesis by simp\n  qed\n  moreover have \"C1\\<times>C2\\<noteq>{}\"  using assms(1) assms(3) assms(4) in_quotient_imp_non_empty by auto\n  ultimately have \"(\\<Union>x\\<in>C1\\<times>C2. r``{(f (fst x) (snd x))} )\\<in>A//r\" using union_eq_2f_in[of \"C1\" \"C2\" \"r\" \"f\" \"A\"] by fastforce\n  then show ?thesis unfolding ProjFun2_def by auto\nqed\n\nlemma union_eq_2f_eq: \n  assumes \"C1\\<times>C2\\<noteq>{}\"  \n      and \"\\<forall>x\\<in>C1\\<times>C2. r``{ (b (fst x) (snd x))} = X\" \n    shows \"(\\<Union>y\\<in>C1\\<times>C2 .r``{ (b (fst y) (snd y))})=X\"\n    by (metis (no_types, lifting) SUP_eq_const assms(1) assms(2))\n\nlemma equiv_2f_wd:\n  assumes \"equiv A r\" \n      and \"Congruent2 r f\"  \n      and \"x\\<in>A\" \"y\\<in>A\"\n    shows \"(ProjFun2  r f) (r``{x}) (r``{y}) = r ``{(f x y)}\"\nproof-\n  have \"(r``{x})\\<times> (r``{y}) \\<noteq> {}\"  by (metis Sigma_empty_iff assms(1) assms(3) assms(4) equals0D equiv_class_self)\n  moreover have \"\\<forall>z\\<in>r``{x}\\<times>r``{y}. r ``{f (fst z) (snd z)}=r ``{f x y}\"\n  proof-\n    have \"\\<And>z. z \\<in> r``{x}\\<times>r``{y} \\<Longrightarrow> r ``{f (fst z) (snd z)}=r ``{f x y}\"\n    proof-\n      fix z assume 1:\"z \\<in> r``{x}\\<times>r``{y}\"\n      have \"(fst z) \\<in> r``{x}\" using 1 by auto\n      moreover have  \"(snd z) \\<in> r``{y}\" using 1 by auto\n      moreover have \"r``{x}\\<in>A//r\" by (simp add: assms(3) quotientI)\n      moreover have \"r``{y}\\<in>A//r\" by (simp add: assms(4) quotientI)\n      moreover have \"x\\<in>r``{x}\" using assms(1) assms(3) equiv_class_self by force\n     moreover have \"y \\<in>r``{y}\" using assms(1) assms(4) equiv_class_self by force\n     ultimately show \"r ``{f (fst z) (snd z)}=r ``{f x y}\" using assms(1) assms(2)  equiv_2f_con[of \"A\" \"r\" \"f\" \"r `` {x}\" \"r `` {y}\" \"(fst z)\" \"x\" \"(snd z)\" \"y\"]   by fastforce\n   qed\n   then show ?thesis by simp\n qed\n  ultimately have \"(\\<Union>z\\<in>r``{x}\\<times>r``{y}. r``{(f (fst z) (snd z))} ) = r ``{f x y}\" using union_eq_2f_eq by simp\n  then show ?thesis unfolding ProjFun2_def by simp\nqed\n\nlemma projfun2_assoc:\n  assumes \"equiv A r\" \n      and \"Congruent2 r f\" \n      and \"\\<forall>x \\<in> A. \\<forall> y \\<in> A. \\<forall> z \\<in> A. f x (f y z) = f (f x y) z\" \n      and \"C1\\<in>A//r\" \"C2\\<in>A//r\" \"C3\\<in>A//r\" \n      and \"g=(ProjFun2 r f)\" \n    shows \"(g (g C1 C2) C3) = (g C1 (g C2 C3))\"\nproof-\n  obtain x y z where A:\"C1=r``{x} \\<and> C2=r``{y} \\<and>  C3=r``{z} \\<and>  x\\<in>A \\<and>  y\\<in>A \\<and>  z\\<in>A\" by (meson assms(4) assms(5) assms(6) quotientE)\n  moreover then have B: \"(f x y) \\<in> A \\<and> (f y z)  \\<in> A\"  using assms(1) assms(2) assms(4) assms(5) assms(6) equiv_2f_clos equiv_class_self by fastforce\n  ultimately have \"g (g C1 C2) C3 = r``{f (f x y) z}\" \n    using assms(1) assms(2) assms(7) equiv_2f_wd by fastforce\n  moreover have \"... = r``{f  x (f y z)}\" by (simp add: A assms(3))\n  moreover have \"... = g  C1 (g C2 C3)\" \n    using A B assms(1) assms(2) assms(7) equiv_2f_wd by fastforce\n  ultimately show ?thesis by simp\nqed\n\ntext \\<open> The following definition defines product on the equivalence classes, by \nfactoring concatenation through equivalence relations.\\<close>\ndefinition proj_append ::  \"(('a,'b) word) set \\<Rightarrow> (('a,'b) word) set \\<Rightarrow> (('a,'b) word) set \\<Rightarrow> (('a,'b) word) set\"\n  where\n\"proj_append S X Y =  (ProjFun2 (reln_tuple S) append) X Y\"\n\nlemma proj_append_clos: \n  assumes \"C1\\<in> quotient \\<langle>S\\<rangle> (reln_tuple \\<langle>S\\<rangle>)\" \n      and \"C2\\<in> quotient \\<langle>S\\<rangle> (reln_tuple \\<langle>S\\<rangle>)\"\n    shows \"(proj_append \\<langle>S\\<rangle> C1 C2) \\<in>  (quotient \\<langle>S\\<rangle> (reln_tuple \\<langle>S\\<rangle>))\"\nproof-\n  show ?thesis using assms(1) assms(2) reln_equiv[of \"S\"] append_congruent[of \"S\"] proj2fun_clos[of \"\\<langle>S\\<rangle>\" \"(reln_tuple \\<langle>S\\<rangle>)\" \"append\" \"C1\" \"C2\"] unfolding proj_append_def by fastforce\nqed\n\nlemma append_assoc2: \n  \"\\<forall>x \\<in> A.\\<forall>y \\<in> A.\\<forall>z \\<in> A. append x (append y z) = append (append x y) z\"\n  by simp\n\nlemma proj_append_assoc: \n  assumes \"C1\\<in>quotient \\<langle>S\\<rangle> (reln_tuple \\<langle>S\\<rangle>)\" \n      and \"C2\\<in>quotient \\<langle>S\\<rangle> (reln_tuple \\<langle>S\\<rangle>)\" \n      and \"C3\\<in>quotient \\<langle>S\\<rangle> (reln_tuple \\<langle>S\\<rangle>)\" \n    shows \"(proj_append \\<langle>S\\<rangle> C1 (proj_append \\<langle>S\\<rangle> C2 C3)) = (proj_append \\<langle>S\\<rangle> (proj_append \\<langle>S\\<rangle> C1 C2) C3)\"\nproof-\n  show ?thesis using assms reln_equiv[of \"S\"] append_congruent[of \"S\"] append_assoc2[of \"\\<langle>S\\<rangle>\"] projfun2_assoc[of \"\\<langle>S\\<rangle>\" \"(reln_tuple \\<langle>S\\<rangle>)\" \"append\" \"C1\" \"C2\" \"C3\"] unfolding proj_append_def by simp\nqed\n\nlemma proj_append_wd: \n  assumes \"xs \\<in> \\<langle>S\\<rangle>\" \"ys \\<in> \\<langle>S\\<rangle>\" \n    shows \"(proj_append \\<langle>S\\<rangle> ((reln_tuple \\<langle>S\\<rangle>)``{xs}) ((reln_tuple \\<langle>S\\<rangle>)``{ys})) = (reln_tuple \\<langle>S\\<rangle>) `` {append xs ys}\"\nproof-\n  show ?thesis \n    using reln_equiv[of \"S\"] append_congruent[of \"S\"] assms equiv_2f_wd[of \"\\<langle>S\\<rangle>\" \"(reln_tuple \\<langle>S\\<rangle>)\" \"append\" \"xs\" \"ys\"] unfolding proj_append_def  by simp\nqed\n\ntext\\<open>Free group is defined as follows. We prove below that it satsifies the group \naxioms.\\<close>\ndefinition freegroup :: \"('a,'b) monoidgentype set \\<Rightarrow> (('a,'b) word set) monoid\" (\"F\\<index>\")\n  where\n\"freegroup S \\<equiv> \\<lparr>\n     carrier =  quotient \\<langle>S\\<rangle> (reln_tuple \\<langle>S\\<rangle>),\n     mult = proj_append \\<langle>S\\<rangle>,\n     one = (reln_tuple \\<langle>S\\<rangle>) `` {[]}\n  \\<rparr>\"\n\n\ntheorem freegroup_is_group: \n  \"group (freegroup S)\"\nproof\n  fix X Y\n  assume \"X \\<in> carrier (freegroup S)\" hence x: \"X \\<in>(quotient \\<langle>S\\<rangle> (reln_tuple \\<langle>S\\<rangle>))\" by(auto simp add:freegroup_def) \n  assume \"Y \\<in> carrier (freegroup S)\" hence y: \"Y \\<in> (quotient \\<langle>S\\<rangle> (reln_tuple \\<langle>S\\<rangle>))\" by(auto simp add:freegroup_def)\n  from x and y\n  have \"X \\<otimes>\\<^bsub>freegroup S\\<^esub> Y \\<in> (quotient \\<langle>S\\<rangle> (reln_tuple \\<langle>S\\<rangle>))\" by (simp add: freegroup_def proj_append_clos)\n  thus \"X \\<otimes>\\<^bsub>freegroup S\\<^esub> Y \\<in> carrier (freegroup S)\"\n    by (auto simp add:freegroup_def)\nnext\n  fix X Y Z assume x:\"X \\<in> carrier (freegroup S)\" assume y: \"Y \\<in> carrier (freegroup S)\" assume z: \"Z \\<in> carrier (freegroup S)\"\n  from x and y and z\n  show  \"X \\<otimes>\\<^bsub>freegroup S\\<^esub> Y \\<otimes>\\<^bsub>freegroup S\\<^esub> Z = X \\<otimes>\\<^bsub>freegroup S\\<^esub> (Y \\<otimes>\\<^bsub>freegroup S\\<^esub> Z)\" by (simp add: freegroup_def proj_append_assoc)\nnext\n  have \"[] \\<in> \\<langle>S\\<rangle>\" unfolding freewords_on_def using empty by auto\n  then have \"(reln_tuple \\<langle>S\\<rangle>) `` {[]} \\<in> quotient \\<langle>S\\<rangle> (reln_tuple \\<langle>S\\<rangle>)\" by (simp add: quotientI)\n  then show \"\\<one>\\<^bsub>freegroup S\\<^esub> \\<in> carrier (freegroup S)\"  by (auto simp add:freegroup_def)\nnext\n  fix X assume \"X \\<in> carrier (freegroup S)\"\n  moreover then obtain x1 where x:\"(reln_tuple \\<langle>S\\<rangle>)``{x1} = X\" by (metis freegroup_def partial_object.select_convs(1) quotientE)\n  ultimately have \"x1 \\<in> \\<langle>S\\<rangle>\"   by (metis freegroup_def partial_object.select_convs(1) proj_def proj_in_iff reln_equiv)\n  moreover have \"[] \\<in> \\<langle>S\\<rangle>\" using empty freewords_on_def by auto\n  ultimately have \"proj_append \\<langle>S\\<rangle> ((reln_tuple \\<langle>S\\<rangle>) `` {[]}) ((reln_tuple \\<langle>S\\<rangle>)``{x1}) = ((reln_tuple \\<langle>S\\<rangle>)``{x1})\" by (simp add: proj_append_wd)\n  then show \"\\<one>\\<^bsub>freegroup S\\<^esub> \\<otimes>\\<^bsub>freegroup S\\<^esub> X = X\" using x by (simp add: freegroup_def)\nnext\n fix X assume \"X \\<in> carrier (freegroup S)\"\n  moreover then obtain x1 where x:\"(reln_tuple \\<langle>S\\<rangle>)``{x1} = X\" by (metis freegroup_def partial_object.select_convs(1) quotientE)\n  ultimately have \"x1 \\<in> \\<langle>S\\<rangle>\"   by (metis freegroup_def partial_object.select_convs(1) proj_def proj_in_iff reln_equiv)\n  moreover have \"[] \\<in> \\<langle>S\\<rangle>\" using empty freewords_on_def by auto\n  ultimately have \"proj_append \\<langle>S\\<rangle>  ((reln_tuple \\<langle>S\\<rangle>)``{x1}) ((reln_tuple \\<langle>S\\<rangle>) `` {[]}) = ((reln_tuple \\<langle>S\\<rangle>)``{x1})\" by (simp add: proj_append_wd)\n  then show \"X \\<otimes>\\<^bsub>freegroup S\\<^esub> \\<one>\\<^bsub>freegroup S\\<^esub> = X\" using x by (simp add: freegroup_def)\nnext\n  show \"carrier (freegroup S) \\<subseteq> Units (freegroup S)\"\n  proof (simp add:freegroup_def Units_def, rule subsetI)\n    fix X assume 1:\"X \\<in> \\<langle>S\\<rangle> // reln_tuple \\<langle>S\\<rangle>\"\n    moreover then obtain x1 where x:\"(reln_tuple \\<langle>S\\<rangle>)``{x1} = X\" by (metis quotientE)\n    ultimately have x1:\"x1 \\<in> \\<langle>S\\<rangle>\"  by (metis  proj_def proj_in_iff reln_equiv)\n    then have ix1:\"wordinverse x1 \\<in> \\<langle>S\\<rangle>\" \n      using span_wordinverse by auto \n    then have 2:\"(reln_tuple \\<langle>S\\<rangle>)``{wordinverse x1} \\<in> \\<langle>S\\<rangle> // reln_tuple \\<langle>S\\<rangle>\" by (simp add: quotientI)\n    have nil: \"[] \\<in> \\<langle>S\\<rangle>\" using empty freewords_on_def by auto\n    have \"proj_append \\<langle>S\\<rangle> ((reln_tuple \\<langle>S\\<rangle>)``{x1}) ((reln_tuple \\<langle>S\\<rangle>)``{wordinverse x1}) \n        = reln_tuple \\<langle>S\\<rangle> `` {x1@(wordinverse x1)}\" \n      using ix1 proj_append_wd x1 by blast\n    moreover have \"x1@(wordinverse x1) \\<in> \\<langle>S\\<rangle>\" using ix1 span_append freewords_on_def x1 by blast\n    moreover then have \"((x1@(wordinverse x1)), []) \\<in> reln_tuple \\<langle>S\\<rangle>\" using nil wordinverse_inverse reln_tuple_def by auto\n    moreover then have \"reln_tuple \\<langle>S\\<rangle> `` {x1@(wordinverse x1)} = reln_tuple \\<langle>S\\<rangle> `` {[]}\" by (metis equiv_class_eq reln_equiv)\n    ultimately have 3:\"proj_append \\<langle>S\\<rangle> ((reln_tuple \\<langle>S\\<rangle>)``{x1}) ((reln_tuple \\<langle>S\\<rangle>)``{wordinverse x1}) = reln_tuple \\<langle>S\\<rangle> `` {[]}\" by simp\n    have \"proj_append \\<langle>S\\<rangle>  ((reln_tuple \\<langle>S\\<rangle>)``{wordinverse x1}) ((reln_tuple \\<langle>S\\<rangle>)``{x1}) = reln_tuple \\<langle>S\\<rangle> `` {(wordinverse x1)@x1}\" \n      using ix1 proj_append_wd x1 by blast\n    moreover have \"(wordinverse x1)@x1 \\<in> \\<langle>S\\<rangle>\" using ix1 span_append freewords_on_def x1 by blast\n    moreover then have \"(((wordinverse x1)@x1), []) \\<in> reln_tuple \\<langle>S\\<rangle>\" using nil inverse_wordinverse reln_tuple_def by auto\n    moreover then have \"reln_tuple \\<langle>S\\<rangle> `` {(wordinverse x1)@x1} = reln_tuple \\<langle>S\\<rangle> `` {[]}\" by (metis equiv_class_eq reln_equiv)\n    ultimately have 4:\"proj_append \\<langle>S\\<rangle> ((reln_tuple \\<langle>S\\<rangle>)``{wordinverse x1}) ((reln_tuple \\<langle>S\\<rangle>)``{x1}) = reln_tuple \\<langle>S\\<rangle> `` {[]}\" by simp\n    show \"X \\<in> {y \\<in> \\<langle>S\\<rangle> // reln_tuple \\<langle>S\\<rangle>.\\<exists>x\\<in>\\<langle>S\\<rangle> // reln_tuple \\<langle>S\\<rangle>.proj_append \\<langle>S\\<rangle> x y = reln_tuple \\<langle>S\\<rangle> `` {[]} \\<and> proj_append \\<langle>S\\<rangle> y x = reln_tuple \\<langle>S\\<rangle> `` {[]}}\"  using 1 2 3 4 x by auto\n  qed\nqed\n\ntext\\<open>Some lemmas about the overlap of words used extensively in the formalization.\\<close>\n\nlemma overlapleftexist:\n  assumes \"(xs@ys) = (us@ws)\" \n      and \"length us > length xs\" \n    shows \"(\\<exists>zs.(xs@zs) = us)\"\nproof-\nlet ?v = \"take (length us) (xs@ys)\"\n  have \"?v = us\" by (simp add: assms(1))\n  moreover then have \"take ( length xs) ?v = xs\" by (metis append_eq_append_conv_if assms(1) assms(2) less_imp_le_nat)\n  ultimately have \"xs @ (drop (length xs) ?v)= us\" by (metis append_take_drop_id)\n  then show ?thesis  by blast\nqed\n\nlemma overlaprightexist:\n  assumes \"(ws@us) = (xs@ys)\" \n      and \"length ys > length us\" \n    shows \"(\\<exists>zs.(zs@us) = ys)\"\nproof-\nlet ?v = \"drop (length xs) (ws@us)\"\n  have \"?v = ys\" by (simp add: assms(1))\n  moreover then have \"drop (length ?v - length us) ?v = us\" using  append_eq_append_conv_if assms(2) by fastforce\n  ultimately have \"(take (length ?v - length us) ?v) @ us = ys\" by (metis append_take_drop_id)\n  then show ?thesis  by blast\nqed\n\ntext \\<open>We provide a definition of a group being 'free', \nif it is isomorphic to a free group \\<close>\ndefinition is_freegroup::\"_ \\<Rightarrow> bool\"\n  where\n\"is_freegroup (G::('a,'b) monoid_scheme) \\<equiv> (\\<exists>(S::(unit \\<times> 'a) set). G \\<cong> (freegroup S))\"\n\nend", "meta": {"author": "aabid-tkcs", "repo": "groupabelle", "sha": "master", "save_path": "github-repos/isabelle/aabid-tkcs-groupabelle", "path": "github-repos/isabelle/aabid-tkcs-groupabelle/groupabelle-main/FreeGroupMain.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8418256472515683, "lm_q2_score": 0.8459424314825853, "lm_q1q2_score": 0.7121360349203928}}
{"text": "header {* Sets of maps *}\ntheory MapSets\nimports SetMap Utils\nbegin\n\ntext {*\nIn the section about the finiteness of the argument space, we need the fact that the set of maps from a finite domain to a finite range is finite, and the same for the set-valued maps defined in @{theory SetMap}. Both these sets are defined (@{text maps_over}, @{text smaps_over}) and the finiteness is shown.\n*}\n\ndefinition maps_over :: \"'a::type set \\<Rightarrow> 'b::type set \\<Rightarrow> ('a \\<rightharpoonup> 'b) set\"\n  where \"maps_over A B = {m. dom m \\<subseteq> A \\<and> ran m \\<subseteq> B}\"\n\nlemma maps_over_empty[simp]:\n  \"empty \\<in> maps_over A B\"\nunfolding maps_over_def by simp\n\nlemma maps_over_upd:\n  assumes \"m \\<in> maps_over A B\"\n  and \"v \\<in> A\" and \"k \\<in> B\"\nshows \"m(v \\<mapsto> k) \\<in> maps_over A B\"\n  using assms unfolding maps_over_def\n  by (auto dest: subsetD[OF ran_upd])\n\nlemma maps_over_finite[intro]:\n  assumes \"finite A\" and \"finite B\" shows \"finite (maps_over A B)\"\nproof-\n  have inj_map_graph: \"inj (\\<lambda>f. {(x, y). Some y = f x})\"\n  proof (induct rule: inj_onI)\n    case (1 x y)\n    from \"1.hyps\"(3) have hyp: \"\\<And> a b. (Some b = x a) \\<longleftrightarrow> (Some b = y a)\"\n      by (simp add: set_eq_iff)\n    show ?case\n    proof (rule ext)\n    fix z show \"x z = y z\"\n      using hyp[of _ z]\n      by (cases \"x z\", cases \"y z\", auto)\n    qed\n  qed\n\n  have \"(\\<lambda>f. {(x, y). Some y = f x}) ` maps_over A B \\<subseteq> Pow( A \\<times> B )\" (is \"?graph \\<subseteq> _\")\n    unfolding maps_over_def\n    by (auto dest!:subsetD[of _ A] subsetD[of _ B] intro:ranI)\n  moreover\n  have \"finite (Pow( A \\<times> B ))\" using assms by auto\n  ultimately\n  have \"finite ?graph\" by (rule finite_subset)\n  thus ?thesis\n    by (rule finite_imageD[OF _ subset_inj_on[OF inj_map_graph subset_UNIV]])\nqed\n\ndefinition smaps_over :: \"'a::type set \\<Rightarrow> 'b::type set \\<Rightarrow> ('a \\<Rightarrow> 'b set) set\"\n  where \"smaps_over A B = {m. sdom m \\<subseteq> A \\<and> sran m \\<subseteq> B}\"\n\nlemma smaps_over_empty[simp]:\n  \"{}. \\<in> smaps_over A B\"\nunfolding smaps_over_def by simp\n\nlemma smaps_over_singleton:\n  assumes \"k \\<in> A\" and \"vs \\<subseteq> B\"\nshows \"{k := vs}. \\<in> smaps_over A B\"\n  using assms unfolding smaps_over_def\n  by(auto dest: subsetD[OF sdom_singleton])\n\nlemma smaps_over_un:\n  assumes \"m1 \\<in> smaps_over A B\" and \"m2 \\<in> smaps_over A B\"\n  shows \"m1 \\<union>. m2 \\<in> smaps_over A B\"\nusing assms unfolding smaps_over_def\nby (auto simp add:smap_union_def)\n\nlemma smaps_over_Union:\n  assumes \"set ms \\<subseteq> smaps_over A B\"\n  shows \"\\<Union>.ms \\<in> smaps_over A B\"\nusing assms\nby (induct ms)(auto intro: smaps_over_un)\n\nlemma smaps_over_im:\n \"\\<lbrakk> f \\<in> m a ; m \\<in> smaps_over A B \\<rbrakk> \\<Longrightarrow> f \\<in> B\"\nunfolding smaps_over_def by (auto simp add:sran_def)\n\nlemma smaps_over_finite[intro]: \n  assumes \"finite A\" and \"finite B\" shows \"finite (smaps_over A B)\"\nproof-\n  have inj_smap_graph: \"inj (\\<lambda>f. {(x, y). y = f x \\<and> y \\<noteq> {}})\" (is \"inj ?gr\")\n  proof (induct rule: inj_onI)\n    case (1 x y)\n    from \"1.hyps\"(3) have hyp: \"\\<And> a b. (b = x a \\<and> b \\<noteq> {}) = (b = y a \\<and> b \\<noteq> {})\"\n      by -(subst (asm) (3) set_eq_iff, simp)\n    show ?case\n    proof (rule ext)\n    fix z show \"x z = y z\"\n      using hyp[of _ z]\n      by (cases \"x z \\<noteq> {}\", cases \"y z \\<noteq> {}\", auto)\n    qed\n  qed\n\n  have \"?gr ` smaps_over A B \\<subseteq> Pow( A \\<times> Pow  B )\" (is \"?graph \\<subseteq> _\")\n    unfolding smaps_over_def\n    by (auto dest!:subsetD[of _ A] subsetD[of _ \"Pow B\"] sdom_not_mem intro:sranI)\n  moreover\n  have \"finite (Pow( A \\<times> Pow B ))\" using assms by auto\n  ultimately\n  have \"finite ?graph\" by (rule finite_subset)\n  thus ?thesis\n    by (rule finite_imageD[OF _ subset_inj_on[OF inj_smap_graph subset_UNIV]])\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/Shivers-CFA/MapSets.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8418256393148982, "lm_q2_score": 0.8459424373085145, "lm_q1q2_score": 0.7121360331108434}}
{"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_NMSortTDIsSort\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 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 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 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  \"((nmsorttd 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_NMSortTDIsSort.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096112990285, "lm_q2_score": 0.7772998611746911, "lm_q1q2_score": 0.712091873683535}}
{"text": "theory Huffman\n  imports Main \"HOL-Library.Multiset\"\nbegin\n\ntext \\<open>In this theory we define Huffman's algorithm and prove its correctness for an arbitrary\nHuffman algebra (TODO ref). If you are only interested in the parts specific to sorting networks,\nyou can skip this theory.\\<close>\n\n\ntext \\<open>First we state the axioms of a Huffman algebra:\\<close>\n\nclass huffman_algebra =\n  fixes combine :: \"'a::linorder \\<Rightarrow> 'a \\<Rightarrow> 'a\"  (infix \\<open>\\<diamondop>\\<close> 70)\n  assumes increasing: \\<open>a \\<le> a \\<diamondop> b\\<close>\n  assumes commutative: \\<open>a \\<diamondop> b = b \\<diamondop> a\\<close>\n  assumes medial: \\<open>(a \\<diamondop> b) \\<diamondop> (c \\<diamondop> d) = (a \\<diamondop> c) \\<diamondop> (b \\<diamondop> d)\\<close>\n  assumes mono: \\<open>a \\<le> b \\<Longrightarrow> a \\<diamondop> c \\<le> b \\<diamondop> c\\<close>\n  assumes assoc_ineq: \\<open>a \\<le> c \\<Longrightarrow> (a \\<diamondop> b) \\<diamondop> c \\<le> a \\<diamondop> (b \\<diamondop> c)\\<close>\n\ntext \\<open>We need some additional lemmas about lists, finite multisets of list elements elements and\nsorted lists of multiset elements.\\<close>\n\ntext \\<open>Removing the head of a list, removes the corresponding element from a multiset.\\<close>\n\nlemma mset_tl: \\<open>xs \\<noteq> [] \\<Longrightarrow> mset (tl xs) = mset xs - {#hd xs#}\\<close>\n  by (cases xs; simp)\n\n\ntext \\<open>The first element of a sorted list of multiset elements is the minimum element of a multiset\nif the multiset is nonempty.\\<close>\n\nlemma hd_sorted_list_of_multiset:\n  assumes \\<open>A \\<noteq> {#}\\<close>\n  shows \\<open>hd (sorted_list_of_multiset A) = Min_mset A\\<close>\n  by (metis (no_types, lifting) Min_in Min_le antisym assms finite_set_mset hd_Cons_tl\n      list.set_sel(1) mset.simps(1) mset_sorted_list_of_multiset set_ConsD set_mset_eq_empty_iff\n      set_sorted_list_of_multiset sorted.simps(2) sorted_list_of_multiset_mset sorted_sort)\n\ntext \\<open>We can remove the smallest element of a nonempty multiset by turning it into a sorted list,\nand building a multiset of that lists's tail.\\<close>\n\nlemma mset_tl_sorted_list_of_multiset:\n  assumes \\<open>A \\<noteq> {#}\\<close>\n  shows \\<open>mset (tl (sorted_list_of_multiset A)) = A - {#Min_mset A#}\\<close>\n  by (metis assms hd_sorted_list_of_multiset mset.simps(1) mset_sorted_list_of_multiset mset_tl)\n\ntext \\<open>If we have a sorted list, we can recover it from a multiset of its elements.\\<close>\n\nlemma unique_sorted_list_of_multiset:\n  assumes \\<open>mset xs = A\\<close> \\<open>sorted xs\\<close>\n  shows \\<open>xs = sorted_list_of_multiset A\\<close>\n  using assms(1) assms(2) sorted_sort_id by fastforce\n\ntext \\<open>The tail of a sorted list of multiset elements is the same as the sorted list of elements\nafter removing the minimal element.\\<close>\n\nlemma tl_sorted_list_of_multiset:\n  assumes \\<open>A \\<noteq> {#}\\<close>\n  shows \\<open>tl (sorted_list_of_multiset A) = sorted_list_of_multiset (A - {#Min_mset A#})\\<close>\nproof -\n  have \\<open>sorted (tl (sorted_list_of_multiset A))\\<close>\n    by (metis mset_sorted_list_of_multiset sorted_list_of_multiset_mset sorted_sort sorted_tl)\n  thus ?thesis\n    by (simp add: assms mset_tl_sorted_list_of_multiset unique_sorted_list_of_multiset)\nqed\n\n(***)\n\ntext \\<open>We also need an alternative characterization of the minimum function.\\<close>\n\nlemma min_as_logic:\n  \\<open>min (a::'a::linorder) b = c \\<longleftrightarrow> (a = c \\<and> a \\<le> b) \\<or> (b = c \\<and> b \\<le> a)\\<close>\n  \\<open>c = min (a::'a::linorder) b \\<longleftrightarrow> (a = c \\<and> a \\<le> b) \\<or> (b = c \\<and> b \\<le> a)\\<close>\n  unfolding min_def by auto\n\n(***)\n\ntext \\<open>Huffman's algorithm repeatedly combines values in a multiset using the Huffman algebra's\noperator. To prove that the resulting value is minimal, we need to manipulate syntax trees of\nexpressions using that operator, which we define here.\\<close>\n\ndatatype 'a expr =\n  Val (the_Val: 'a) (\"\\<langle>_\\<rangle>\") |\n  Op (left_subexpr: \\<open>'a expr\\<close>) (right_subexpr: \\<open>'a expr\\<close>) (infix \"\\<star>\" 70)\n\nabbreviation is_Op :: \\<open>'a expr \\<Rightarrow> bool\\<close> where\n  \\<open>is_Op E \\<equiv> \\<not>is_Val E\\<close>\n\ntext \\<open>The set of values in an expression is always non-empty and finite.\\<close>\n\nlemma set_expr_nonempty[simp]: \\<open>set_expr E \\<noteq> {}\\<close>\n  by (induction E; auto)\n\nlemma set_expr_finite[simp]: \\<open>finite (set_expr E)\\<close>\n  by (induction E; auto)\n\ntext \\<open>We can recursively evaluate an expression using the Huffman algebra's operator.\\<close>\n\nfun (in huffman_algebra) value_expr :: \\<open>'a expr \\<Rightarrow> 'a\\<close> where\n  \\<open>value_expr \\<langle>a\\<rangle> = a\\<close> |\n  \\<open>value_expr (E \\<star> F) = value_expr E \\<diamondop> value_expr F\\<close>\n\ntext \\<open>We can flatten an expression into a nonempty list of contained values.\\<close>\n\nabbreviation list_expr :: \\<open>'a expr \\<Rightarrow> 'a list\\<close> where\n  \\<open>list_expr \\<equiv> rec_expr (\\<lambda>a. [a]) (\\<lambda>_ _. (@))\\<close>\n\nlemma list_expr_nonempty[simp]: \\<open>list_expr E \\<noteq> []\\<close>\n  by (induction E; auto)\n\ntext \\<open>With this we can count the number of values in the expression.\\<close>\n\nabbreviation count_expr :: \\<open>'a expr \\<Rightarrow> nat\\<close> where\n  \\<open>count_expr E \\<equiv> length (list_expr E)\\<close>\n\nlemma count_expr_ge1[simp]: \\<open>count_expr E \\<ge> 1\\<close>\n  by (simp add: Suc_leI)\n  \nlemma count_expr_Op: \\<open>count_expr (E \\<star> F) \\<ge> 2\\<close>\n  using count_expr_ge1[of E] count_expr_ge1[of F]\n  by (simp; linarith)\n\nlemma is_Op_by_count: \\<open>is_Op E = (count_expr E \\<ge> 2)\\<close>\n  by (cases E; simp; insert count_expr_Op; auto)\n\nlemma expr_from_list: \\<open>list_expr E = [e] \\<Longrightarrow> E = \\<langle>e\\<rangle>\\<close>\n  by (cases E; simp add: append_eq_Cons_conv)\n\ntext \\<open>The number of values in an expression is also directly related to the size of an expression.\nWe get the size and several useful of its properties for free whenever we define an algebraic\ndatatype. With this we get corresponding useful properties also for the number of an expression's\nvalues.\\<close>\n\nlemma count_expr_size: \\<open>2 * count_expr E = Suc (size E)\\<close>\n  by (induction E; auto)\n\ntext \\<open>We define the multiset of an expression's values via the list of values.\\<close>\n\nabbreviation mset_expr :: \\<open>'a expr \\<Rightarrow> 'a multiset\\<close> where\n  \\<open>mset_expr E \\<equiv> mset (list_expr E)\\<close>\n\ntext \\<open>There is a unique expression containing just one given value.\\<close>\n\nlemma expr_from_mset: \\<open>mset_expr E = {# a #} \\<Longrightarrow> E = \\<langle>a\\<rangle>\\<close>\n  by (simp add: expr_from_list)\n\ntext \\<open>Ignoring the multiplicity of the multisets's values gives us the same set as the automatically\ndefined function for the set of values in an expression.\\<close>\n\nlemma set_mset_expr: \\<open>set_mset (mset_expr E) = set_expr E\\<close>\n  by (induction E; simp)\n\ntext \\<open>We define the head of an expression as the leftmost value in the syntax tree, and we do this\nvia flattening the expression to a list of values.\\<close>\n\nabbreviation hd_expr :: \\<open>'a expr \\<Rightarrow> 'a\\<close> where\n  \\<open>hd_expr E \\<equiv> hd (list_expr E)\\<close>\n\ntext \\<open>We get the minimum value in an expression as the minimum value of the set of its values.\\<close>\n\ndefinition Min_expr :: \\<open>'a::linorder expr \\<Rightarrow> 'a\\<close> where\n  \\<open>Min_expr E \\<equiv> Min (set_expr E)\\<close>\n\ntext \\<open>If the expression contains just one value, the minimum is that value.\\<close>\n\nlemma Min_expr_Val[simp]: \\<open>Min_expr \\<langle>a\\<rangle> = a\\<close>\n  unfolding Min_expr_def\n  by simp\n\ntext \\<open>Otherwise the minimum value can be computed recursively.\\<close>\n\nlemma Min_expr_Op: \\<open>Min_expr (L \\<star> R) = min (Min_expr L) (Min_expr R)\\<close>\n  unfolding Min_expr_def\n  by (simp add: Min_Un min_def)\n\ntext \\<open>As the Huffman algebra operator is increasing in both arguments, the minimum value in an\nexpression is a lower bound for its evaluation.\\<close>\n\nlemma (in huffman_algebra) Min_expr_bound:\n  \\<open>Min_expr E \\<le> value_expr E\\<close>\n  by (induction E; simp add: Min_expr_Op; insert increasing min.coboundedI1 order_trans; blast)\n\ntext \\<open>If two expressions have the same multiset of values they contain the same minimum value.\\<close>\n\nlemma Min_expr_mset_cong: \\<open>mset_expr E = mset_expr F \\<Longrightarrow> Min_expr E = Min_expr F\\<close>\n  unfolding Min_expr_def set_mset_expr[symmetric] by simp\n\ntext \\<open>The minimum value in an expression is also the minimum value of the multiset of its values.\\<close>\n\nlemma Min_expr_from_mset: \\<open>Min_expr E = Min_mset (mset_expr E)\\<close>\n  unfolding Min_expr_def\n  by (fold set_mset_expr; simp)\n\ntext \\<open>We define the tail of an expression as the expression we get by removing the head if that is\npossible. This is always possible as long as the expression contains one operator.\\<close>\n\nfun tl_expr :: \\<open>'a expr \\<Rightarrow> 'a expr\\<close> where\n  \\<open>tl_expr \\<langle>a\\<rangle> = \\<langle>a\\<rangle>\\<close> |\n  \\<open>tl_expr (\\<langle>l\\<rangle> \\<star> R) = R\\<close> |\n  \\<open>tl_expr ((L \\<star> M) \\<star> R) = tl_expr (L \\<star> M) \\<star> R\\<close>\n\ntext \\<open>If the expression contains an operator, the tail of the list of its values is the same as the\nlist of values of its tail.\\<close>\n\nlemma list_tl_expr: \\<open>is_Op E \\<Longrightarrow> list_expr (tl_expr E) = tl (list_expr E)\\<close>\n  by (induction E rule: tl_expr.induct; simp)\n\ntext \\<open>If two expressions have the same head and the same multiset of values, their tails also have\nthe same multiset of values.\\<close>\n\nlemma same_mset_tl_from_same_mset_mset_hd:\n  assumes \\<open>hd_expr E = hd_expr F\\<close> \\<open>mset_expr E = mset_expr F\\<close>\n  shows \\<open>mset_expr (tl_expr E) = mset_expr (tl_expr F)\\<close>\nproof (cases \\<open>is_Op E\\<close>)\n  case True\n  hence \\<open>is_Op F\\<close>\n    using mset_eq_length[of \\<open>list_expr E\\<close> \\<open>list_expr F\\<close>]\n      is_Op_by_count[of E] is_Op_by_count[of F] assms(2)\n    by auto\n  thus ?thesis\n    using assms True\n    by (subst (1 2) list_tl_expr; simp; subst (1 2) mset_tl; simp)\nnext\n  case False\n  then obtain e where \\<open>E = \\<langle>e\\<rangle>\\<close>\n    using expr.exhaust_sel by force\n  hence \\<open>F = E\\<close>\n    using expr.exhaust_sel assms(2) expr_from_list by fastforce\n  then show ?thesis\n    by simp\nqed\n\n\n(***)\n\ntext \\<open>Given any property of an expression, we can define a corresponding property that holds if the\ngiven property holds for all subexpressions of an expression (including the expression itself).\\<close>\n\ninductive all_subexpr :: \\<open>('a expr \\<Rightarrow> bool) \\<Rightarrow> 'a expr \\<Rightarrow> bool\\<close> where\n  val: \\<open>P \\<langle>a\\<rangle> \\<Longrightarrow> all_subexpr P \\<langle>a\\<rangle>\\<close> |\n  op: \\<open>\\<lbrakk>P (L \\<star> R); all_subexpr P L; all_subexpr P R\\<rbrakk> \\<Longrightarrow> all_subexpr P (L \\<star> R)\\<close>\n\ndeclare all_subexpr.intros[intro] all_subexpr.cases[elim]\n\nlemma all_subexpr_top: \\<open>all_subexpr P E \\<Longrightarrow> P E\\<close>\n  by auto\n\nlemma all_subexpr_expand: \\<open>all_subexpr P (L \\<star> R) = (P (L \\<star> R) \\<and> all_subexpr P L \\<and> all_subexpr P R)\\<close>\n  by auto\n\n(***)\n\ntext \\<open>An expression has a minimal head, if its head is the minimum of the contained values.\\<close>\n\nabbreviation Min_hd_expr :: \\<open>'a::linorder expr \\<Rightarrow> bool\\<close> where\n  \\<open>Min_hd_expr E \\<equiv> hd_expr E = Min_expr E\\<close>\n\ntext \\<open>If an expression has this property, so does its left subexpression.\\<close>\n\nlemma Min_hd_expr_left_subexpr: \\<open>Min_hd_expr (L \\<star> R) \\<Longrightarrow> Min_hd_expr L\\<close>\n  by (induction L; auto simp add: Min_expr_Op min_as_logic)\n\ntext \\<open>In that case the minimum value contained in the left subexpression is at least as small as the\nminimum value contained in the right subexpression.\\<close>\n\nlemma Min_hd_expr_subexpr_ord: \\<open>Min_hd_expr (L \\<star> R) \\<Longrightarrow> Min_expr L \\<le> Min_expr R\\<close>\n  using Min_hd_expr_left_subexpr min.orderI by (fastforce simp add: Min_expr_Op)\n\ntext \\<open>Hence to find the minimum value in an minimal head expression, we only need to look at the\nleft subexpression.\\<close>\n\nlemma Min_hd_expr_left_subexpr_Min: \\<open>Min_hd_expr (L \\<star> R) \\<Longrightarrow> Min_expr (L \\<star> R) = Min_expr L\\<close>\n  by (induction L; auto simp add: Min_expr_Op min_as_logic)\n\ntext \\<open>If two minimal head expressions have the same head they have same minimum contained value.\\<close>\n\nlemma Min_hd_expr_Min_from_hd_cong:\n  assumes \\<open>Min_hd_expr E\\<close> \\<open>Min_hd_expr F\\<close> \\<open>hd_expr E = hd_expr F\\<close>\n  shows \\<open>Min_expr E = Min_expr F\\<close>\n  using assms by simp\n\ntext \\<open>To turn an expression into a minimal head expression without changing the value it evaluates\nto, we can swap the sides of every operator where the right subexpression contains a smaller value\nthan the minimum value on the left.\\<close>\n\ntext \\<open>To do this we first define this function which combines two subexpressions such that the\nminimum value is on the left.\\<close>\n\nfunction Min_to_hd_subexpr :: \\<open>'a::linorder expr \\<Rightarrow> 'a::linorder expr \\<Rightarrow> 'a expr\\<close> where\n  \\<open>Min_expr L \\<le> Min_expr R \\<Longrightarrow> Min_to_hd_subexpr L R = L \\<star> R\\<close> |\n  \\<open>\\<not>(Min_expr L \\<le> Min_expr R) \\<Longrightarrow> Min_to_hd_subexpr L R = R \\<star> L\\<close>\n  by auto\ntermination by lexicographic_order\n\ntext \\<open>Doing this results in an expression with the same multiset of values as combining them in a\nfixed order would result in.\\<close>\n\nlemma Min_to_hd_subexpr_mset: \\<open>mset_expr (Min_to_hd_subexpr L R) = mset_expr (L \\<star> R)\\<close>\n  by (cases \\<open>(L, R)\\<close> rule: Min_to_hd_subexpr.cases; auto)\n\ntext \\<open>And does not change the value it evaluates to.\\<close>\n\nlemma (in huffman_algebra) value_Min_to_hd_subexpr:\n  \\<open>value_expr (Min_to_hd_subexpr L R) = value_expr L \\<diamondop> value_expr R\\<close>\n  by (metis Min_to_hd_subexpr.simps commutative value_expr.simps(2))\n\ntext \\<open>If we have two expressions, both for which all subexpression have a minimal head, combining\nthem this way results in an expression where still all subexpressions have a minimal head.\\<close>\n\nlemma Min_to_hd_subexpr_spec:\n  assumes \\<open>all_subexpr Min_hd_expr L\\<close> \\<open>all_subexpr Min_hd_expr R\\<close>\n  shows \\<open>all_subexpr Min_hd_expr (Min_to_hd_subexpr L R)\\<close>\nproof (cases \\<open>Min_expr L \\<le> Min_expr R\\<close>)\n  case True\n  have \\<open>Min_expr (L \\<star> R) = Min_expr L \\<and> hd_expr (L \\<star> R) = hd_expr L\\<close>\n    by (simp add: True Min_expr_Op min_def)\n  hence \\<open>Min_hd_expr (L \\<star> R)\\<close>\n    using assms by auto \n  thus ?thesis\n    using assms True by auto\nnext\n  case False\n  hence False': \\<open>Min_expr R \\<le> Min_expr L\\<close>\n    using linear by blast\n  have \\<open>Min_expr (R \\<star> L) = Min_expr R \\<and> hd_expr (R \\<star> L) = hd_expr R\\<close>\n    by (auto simp add: False' Min_expr_Op min_def)\n  hence \\<open>Min_hd_expr (R \\<star> L)\\<close>\n    using assms by auto \n  thus ?thesis\n    using assms False by auto\nqed\n\ntext \\<open>Thus we can turn any expression into one with only minimal head subexpressions, by recursing\nand combining subexpressions with @{term Min_to_hd_subexpr}.\\<close>\n\nfun Min_to_hd_expr :: \\<open>'a::linorder expr \\<Rightarrow> 'a expr\\<close> where\n  \\<open>Min_to_hd_expr \\<langle>a\\<rangle> = \\<langle>a\\<rangle>\\<close> |\n  \\<open>Min_to_hd_expr (L \\<star> R) = Min_to_hd_subexpr (Min_to_hd_expr L) (Min_to_hd_expr R)\\<close>\n\nlemma Min_to_hd_expr_spec:\n  \\<open>all_subexpr Min_hd_expr (Min_to_hd_expr E)\\<close>\n  by (induction E rule: Min_to_hd_expr.induct;\n      (subst Min_to_hd_expr.simps; rule Min_to_hd_subexpr_spec)?;\n      auto)\n\ntext \\<open>This does not change the multiset of values nor what the expression evaluates to.\\<close>\n\nlemma Min_to_hd_expr_mset: \\<open>mset_expr (Min_to_hd_expr E) = mset_expr E\\<close>\n  by (induction E rule: Min_to_hd_expr.induct; simp add: Min_to_hd_subexpr_mset)\n\nlemma (in huffman_algebra) value_Min_to_hd_expr:\n  \\<open>value_expr (Min_to_hd_expr E) = value_expr E\\<close>\n  by (induction E rule: Min_to_hd_expr.induct; simp add: value_Min_to_hd_subexpr)\n\n(***)\n\ntext \\<open>We also want an expression's tail to have a minimal head, such that the two smallest values\nare the leftmost of an expression.\\<close>\n\nabbreviation tl_Min_hd_expr :: \\<open>'a::linorder expr \\<Rightarrow> bool\\<close> where\n  \\<open>tl_Min_hd_expr E \\<equiv> Min_hd_expr (tl_expr E)\\<close>\n\ntext \\<open>This property depends only on the list of elements, not on how they are nested.\\<close>\n\nlemma tl_Min_hd_expr_list_expr_cong:\n  assumes \\<open>list_expr E = list_expr F\\<close>\n  shows \\<open>tl_Min_hd_expr E = tl_Min_hd_expr F\\<close>\nproof -\n  have \\<open>\\<And>E. tl (list_expr E) = list_expr (tl_expr E) \\<or> \\<langle>the_Val E\\<rangle> = E\\<close>\n    using expr.collapse(1) list_tl_expr by fastforce\n  then have \\<open>list_expr (tl_expr E) = list_expr (tl_expr F)\\<close>\n    using assms by (metis (no_types) expr.simps(7) expr_from_list)\n  then show ?thesis\n    by (metis Min_expr_mset_cong)\nqed\n\ntext \\<open>By going through several cases, we can rearrange subexpression to ensure that the minimum\nvalue of the tail of an expression is in the left subexpression of an expression. We do this in a\nway that the Huffman algebra axioms ensure that the evaluation result is not increased as long as\nall subexpressions of the input have a minimal head.\\<close>\n\nfunction tl_Min_to_hd_subexpr :: \\<open>'a::linorder expr \\<Rightarrow> 'a expr\\<close> where\n  \\<open>tl_Min_to_hd_subexpr \\<langle>a\\<rangle> = \\<langle>a\\<rangle>\\<close> |\n  \\<open>tl_Min_to_hd_subexpr (\\<langle>l\\<rangle> \\<star> R) = \\<langle>l\\<rangle> \\<star> R\\<close> |\n  \\<open>Min_expr M \\<le> r \\<Longrightarrow>\n    tl_Min_to_hd_subexpr ((L \\<star> M) \\<star> \\<langle>r\\<rangle>) = (L \\<star> M) \\<star> \\<langle>r\\<rangle>\\<close> |\n  \\<open>\\<not>(Min_expr M \\<le> r) \\<Longrightarrow>\n    tl_Min_to_hd_subexpr ((L \\<star> M) \\<star> \\<langle>r\\<rangle>) = (L \\<star> \\<langle>r\\<rangle>) \\<star> M\\<close> |\n  \\<open>Min_expr LM \\<le> Min_expr RM \\<Longrightarrow>\n    tl_Min_to_hd_subexpr ((L \\<star> LM) \\<star> (RM \\<star> R)) = (L \\<star> LM) \\<star> (RM \\<star> R)\\<close> |\n  \\<open>\\<not>(Min_expr LM \\<le> Min_expr RM) \\<Longrightarrow>\n    tl_Min_to_hd_subexpr ((L \\<star> LM) \\<star> (RM \\<star> R)) = (L \\<star> RM) \\<star> (LM \\<star> R)\\<close>\n  by (auto, metis tl_expr.cases)\ntermination by lexicographic_order\n\ntext \\<open>We show that it does not change the size.\\<close>\n\nlemma tl_Min_to_hd_subexpr_size[simp]:\n  \\<open>size (tl_Min_to_hd_subexpr E) = size E\\<close>\n  by (induction E rule: tl_Min_to_hd_subexpr.induct; simp)\n\ntext \\<open>Which allows us to apply it while recursing on the result of that application.\\<close>\n\nfun tl_Min_to_hd_expr :: \\<open>'a::linorder expr \\<Rightarrow> 'a expr\\<close>\n  and helper_tl_Min_to_hd_expr :: \\<open>'a::linorder expr \\<Rightarrow> 'a expr\\<close> where\n    \\<open>tl_Min_to_hd_expr E = helper_tl_Min_to_hd_expr (tl_Min_to_hd_subexpr E) \\<close> |\n    \\<open>helper_tl_Min_to_hd_expr \\<langle>a\\<rangle> = \\<langle>a\\<rangle>\\<close> |\n    \\<open>helper_tl_Min_to_hd_expr (L \\<star> R) = tl_Min_to_hd_expr L \\<star> R\\<close>\n\ntext \\<open>This recursion also does not change the multiset of values, the minimum value, the head, the\nmultiset of tail values or the minimum value of the tail.\\<close>\n\nlemma tl_Min_to_hd_expr_mset: \\<open>mset_expr (tl_Min_to_hd_expr E) = mset_expr E\\<close>\nproof (induction \\<open>size E\\<close> arbitrary: E rule: less_induct)\n  case less\n  then show ?case\n    by (cases E rule: tl_Min_to_hd_subexpr.cases; simp)\nqed\n\n\nlemma tl_Min_to_hd_expr_Min: \\<open>Min_expr (tl_Min_to_hd_expr E) = Min_expr E\\<close>\n  using tl_Min_to_hd_expr_mset[of E]\n  unfolding Min_expr_def set_mset_expr[symmetric]\n  by simp\n\nlemma tl_Min_to_hd_expr_hd: \\<open>hd_expr (tl_Min_to_hd_expr E) = hd_expr E\\<close>\nproof (induction \\<open>size E\\<close> arbitrary: E rule: less_induct)\n  case less\n  then show ?case\n    by (cases E rule: tl_Min_to_hd_subexpr.cases; simp)\nqed\n\nlemma tl_Min_to_hd_expr_mset_tl: \\<open>mset_expr (tl_expr (tl_Min_to_hd_expr E)) = mset_expr (tl_expr E)\\<close>\n  by (subst same_mset_tl_from_same_mset_mset_hd[of E \\<open>tl_Min_to_hd_expr E\\<close>];\n      simp add: tl_Min_to_hd_expr_hd tl_Min_to_hd_expr_mset del: tl_Min_to_hd_expr.simps)\n\nlemma tl_Min_to_hd_expr_Min_tl: \\<open>Min_expr (tl_expr (tl_Min_to_hd_expr E)) = Min_expr (tl_expr E)\\<close>\n  using Min_expr_mset_cong tl_Min_to_hd_expr_mset_tl by blast\n\ntext \\<open>To further analyze @{term tl_Min_to_hd_subexpr}, we need various lemmas about minimum\ncontained values and minimal head values for expressions and tails of expressions and how they\nrelate when rearranging subexpressions.\\<close>\n\ntext \\<open>Given a minimal head expression, if we rewrite the left subexpression without changing the\nminimum value or the head, we still have a minimal head expression.\\<close>\n\nlemma Min_hd_expr_rewrite_left:\n  assumes \\<open>Min_hd_expr (L \\<star> R)\\<close> \\<open>Min_expr L = Min_expr L'\\<close> \\<open>Min_hd_expr L'\\<close>\n  shows \\<open>Min_hd_expr (L' \\<star> R)\\<close>\n  by (metis (mono_tags, lifting)\n      Min_expr_Op Min_hd_expr_left_subexpr assms expr.simps(8) hd_append2 list_expr_nonempty)\n\ntext \\<open>If we have a minimal head expression and exchange the right subexpression with the right\nsubexpression of the left subexpression, we still have a minimal head expression.\\<close>\n\nlemma Min_hd_expr_exchange_right:\n  assumes \\<open>Min_hd_expr ((L \\<star> M) \\<star> R)\\<close>\n  shows \\<open>Min_hd_expr ((L \\<star> R) \\<star> M)\\<close>\n  using assms\n  by (simp add: Min_expr_Op; metis min.commute min.assoc)\n\ntext \\<open>This extends to all minimal head subexpressions.\\<close>\n\nlemma all_subexpr_Min_hd_expr_exchange_right:\n  assumes \\<open>all_subexpr Min_hd_expr ((L \\<star> M) \\<star> R)\\<close>\n  shows \\<open>all_subexpr Min_hd_expr ((L \\<star> R) \\<star> M)\\<close>\n  by (intro all_subexpr.op; insert assms Min_hd_expr_exchange_right Min_hd_expr_left_subexpr; blast)\n\ntext \\<open>Combining an expression where the tail has a minimal head with a singleton expression still\nhas a tail with a minimal head, if that singleton expression is larger than the tail's minimal\nhead.\\<close>\n\nlemma tl_Min_hd_expr_right_Val:\n  assumes \\<open>tl_Min_hd_expr L\\<close> \\<open>Min_expr (tl_expr L) \\<le> r\\<close>\n  shows \\<open>tl_Min_hd_expr (L \\<star> \\<langle>r\\<rangle>)\\<close>\n  using assms\n  by (cases L; simp add: Min_expr_Op min_absorb1 dual_order.trans min_def_raw)\n\ntext \\<open>If we have an upper bound for the minimum value in an expression, combining it with another\nexpression on the left and then taking the tail of the resulting expression results in an expression\nthat still has that upper bound, as it still contains all values of our initial expression.\\<close>\n\nlemma Min_expr_tl_bound:\n  assumes \\<open>Min_expr M \\<le> r\\<close>\n  shows \\<open>Min_expr (tl_expr (L \\<star> M)) \\<le> r\\<close>\n  using assms\n  by (cases L; simp add: Min_expr_Op min_le_iff_disj)\n\ntext \\<open>If we have a nonsingleton expression whose tail has a minimal head, combining it with another\nexpression on the right whose minimal value is not smaller than the left expression's tail's minimal\nhead, is an expression whose tail again has a minimal head.\\<close>\n\nlemma tl_Min_hd_expr_right:\n  assumes \\<open>is_Op L\\<close> \\<open>tl_Min_hd_expr L\\<close> \\<open>Min_expr (tl_expr L) \\<le> Min_expr R\\<close>\n  shows \\<open>tl_Min_hd_expr (L \\<star> R)\\<close>\n  using assms\n  by (cases L; simp add: Min_expr_Op min_absorb1 dual_order.trans min_def_raw)\n\ntext \\<open>Applying @{term tl_Min_to_hd_expr} to a non-singleton expression results in a non-singleton\nexpression.\\<close>\n\nlemma is_Op_tl_Min_to_hd_expr: \\<open>is_Op (tl_Min_to_hd_expr (L \\<star> R))\\<close>\n  unfolding is_Op_by_count\n  by (metis (mono_tags, lifting) count_expr_Op mset_eq_length tl_Min_to_hd_expr_mset)\n\ntext \\<open>If we have an expression where all subexpressions have a minimal head, applying @{term\ntl_Min_to_hd_expr} results in an expression where the tail has a minimal head.\\<close>\n\nlemma tl_Min_to_hd_expr_spec:\n  \\<open>all_subexpr Min_hd_expr E \\<Longrightarrow> tl_Min_hd_expr (tl_Min_to_hd_expr E)\\<close>\nproof (induction \\<open>size E\\<close> arbitrary: E rule: less_induct)\ncase less\n  then show ?case \n  proof (cases E rule: tl_Min_to_hd_subexpr.cases; (auto; fail)?)\n    case (3 M r L)\n\n    have A: \\<open>all_subexpr Min_hd_expr (L \\<star> M)\\<close>\n      using 3 less.prems by blast\n\n    have B: \\<open>Min_expr (tl_expr (tl_Min_to_hd_expr (L \\<star> M))) \\<le> r\\<close>\n      by (subst tl_Min_to_hd_expr_Min_tl; rule Min_expr_tl_bound; simp add: 3)\n\n    show ?thesis\n      by (simp add: 3; fold tl_Min_to_hd_expr.simps;\n          rule tl_Min_hd_expr_right_Val; insert 3 A B less; auto)\n  next\n    case (4 M r L)\n\n    have \\<open>all_subexpr Min_hd_expr (L \\<star> \\<langle>r\\<rangle>)\\<close>\n      using 4 less.prems all_subexpr_Min_hd_expr_exchange_right by fastforce \n    hence A: \\<open>tl_Min_hd_expr (tl_Min_to_hd_expr (L \\<star> \\<langle>r\\<rangle>))\\<close>\n      using 4 less.hyps by auto\n\n    have B: \\<open>Min_expr (tl_expr (tl_Min_to_hd_expr (L \\<star> \\<langle>r\\<rangle>))) \\<le> Min_expr M\\<close>\n      by (subst tl_Min_to_hd_expr_Min_tl; metis \"4\"(1) Min_expr_Val Min_expr_tl_bound linear)\n\n    show ?thesis \n      by (simp add: 4; fold tl_Min_to_hd_expr.simps; rule tl_Min_hd_expr_right;\n          insert is_Op_tl_Min_to_hd_expr A B; simp)\n  next\n    case (5 LM RM L R)\n\n    have A: \\<open>tl_Min_hd_expr (tl_Min_to_hd_expr (L \\<star> LM))\\<close>\n      using 5 less by auto\n\n    have *: \\<open>Min_expr LM \\<le> Min_expr RM \\<and> Min_expr LM \\<le> Min_expr R\\<close>\n      using less.prems unfolding 5\n      by (simp add: all_subexpr_expand Min_expr_Op;\n          insert 5 all_subexpr_top order_trans; auto simp add: min_as_logic)\n\n    have B: \\<open>Min_expr (tl_expr (tl_Min_to_hd_expr (L \\<star> LM))) \\<le> Min_expr (RM \\<star> R)\\<close>\n      by (subst tl_Min_to_hd_expr_Min_tl; rule Min_expr_tl_bound; simp add: * Min_expr_Op)\n\n    show ?thesis\n      by (simp add: 5; fold tl_Min_to_hd_expr.simps; rule tl_Min_hd_expr_right;\n          insert is_Op_tl_Min_to_hd_expr A B; simp)\n  next\n    case (6 LM RM L R)\n\n    have *: \\<open>Min_expr L \\<le> Min_expr RM\\<close>\n      using less.prems unfolding 6\n      by (simp add: all_subexpr_expand Min_expr_Op; insert all_subexpr_top min.orderI; fastforce)\n      \n    have **: \\<open>all_subexpr Min_hd_expr (L \\<star> RM)\\<close>\n      by (rule all_subexpr.op; insert * 6 less.prems; auto simp add: Min_expr_Op min_def)\n\n    have A: \\<open>tl_Min_hd_expr (tl_Min_to_hd_expr (L \\<star> RM))\\<close>\n      using ** less 6 by auto\n\n    have ***: \\<open>Min_expr RM \\<le> Min_expr LM \\<and> Min_expr RM \\<le> Min_expr R\\<close>\n      using less.prems unfolding 6\n      by (simp add: all_subexpr_expand Min_expr_Op;\n          insert 6 all_subexpr_top min.orderI; force)\n\n    have B: \\<open>Min_expr (tl_expr (tl_Min_to_hd_expr (L \\<star> RM))) \\<le> Min_expr (LM \\<star> R)\\<close>\n      by (subst tl_Min_to_hd_expr_Min_tl; rule Min_expr_tl_bound; simp add: *** Min_expr_Op)\n\n    show ?thesis\n      by (simp add: 6; fold tl_Min_to_hd_expr.simps; rule tl_Min_hd_expr_right;\n          insert is_Op_tl_Min_to_hd_expr A B; auto)\n  qed\nqed\n\ntext \\<open>If we have an expression where all subexpressions have a minimal head, applying @{term\ntl_Min_to_hd_expr} also does not increase the evaluation result.\\<close>\n\nlemma (in huffman_algebra) value_tl_Min_to_hd_expr:\n  \\<open>all_subexpr Min_hd_expr E \\<Longrightarrow> value_expr (tl_Min_to_hd_expr E) \\<le> value_expr E\\<close>\nproof (induction \\<open>size E\\<close> arbitrary: E rule: less_induct)\n  case less\n  then show ?case\n  proof (cases E rule: tl_Min_to_hd_subexpr.cases; (auto; fail)?)\n    case (3 M r L)\n    show ?thesis\n      by (simp add: 3; fold tl_Min_to_hd_expr.simps; metis (no_types, lifting) \"3\"(2) add_Suc_right\n          all_subexpr_expand dual_order.strict_trans2 expr.size(4) huffman_algebra.mono\n          huffman_algebra_axioms le_add1 less.hyps less.prems lessI value_expr.simps(2))\n  next\n    case (4 M r L)\n\n    have *: \\<open>value_expr ((L \\<star> \\<langle>r\\<rangle>) \\<star> M) \\<le> value_expr ((L \\<star> M) \\<star> \\<langle>r\\<rangle>)\\<close>\n      by (simp; metis \"4\"(1) assoc_ineq commutative huffman_algebra.Min_expr_bound\n          huffman_algebra_axioms linear order_trans)\n\n    have **: \\<open>value_expr (tl_Min_to_hd_expr (L \\<star> \\<langle>r\\<rangle>)) \\<le> value_expr (L \\<star> \\<langle>r\\<rangle>)\\<close>\n      by (metis (mono_tags, lifting) \"4\"(1) \"4\"(2) add.right_neutral add_Suc_right\n          all_subexpr_Min_hd_expr_exchange_right all_subexpr_expand expr.size(4) le_add1\n          le_imp_less_Suc less.hyps less.prems tl_Min_to_hd_subexpr.simps(4)\n          tl_Min_to_hd_subexpr_size)\n\n    show ?thesis\n      by (simp add: 4; fold tl_Min_to_hd_expr.simps; insert * **; simp add: dual_order.trans mono) \n  next\n    case (5 LM RM L R)\n    show ?thesis\n      by (simp add: 5; fold tl_Min_to_hd_expr.simps; metis (no_types, lifting) \"5\"(2) Suc_le_eq\n          add.right_neutral add_Suc_right all_subexpr_expand expr.size(4) le_add1 less.hyps\n          less.prems mono order.strict_iff_order value_expr.simps(2))\n  next\n    case (6 LM RM L R)\n\n    have *: \\<open>value_expr ((L \\<star> LM) \\<star> (RM \\<star> R)) = value_expr ((L \\<star> RM) \\<star> (LM \\<star> R))\\<close>\n      by (simp add: medial)\n\n    have \\<open>all_subexpr Min_hd_expr (L \\<star> RM)\\<close>\n      using less unfolding 6 all_subexpr_expand\n      by (metis (mono_tags, lifting) Min_expr_Op Min_hd_expr_left_subexpr_Min expr.simps(8)\n          hd_append2 list_expr_nonempty)\n\n    hence **: \\<open>value_expr (tl_Min_to_hd_expr (L \\<star> RM)) \\<le> value_expr (L \\<star> RM)\\<close>\n      by (metis (no_types, lifting) \"6\"(1) \"6\"(2) add.right_neutral add_Suc_right expr.size(4)\n          le_add1 le_imp_less_Suc less.hyps tl_Min_to_hd_subexpr.simps(6) tl_Min_to_hd_subexpr_size)\n\n    show ?thesis\n      by (simp add: 6; fold tl_Min_to_hd_expr.simps; insert * **; simp add: mono)\n  qed\nqed\n\n(***)\n\ntext \\<open>At this point we can move the two smallest values of an expression to the very left without\nincreasing its value. To show that we can always combine the smallest two values, we now need to\nmake sure that the leftmost nonsingleton subexpression combines two singleton subexpression, i.e.\\\ncombines two values.\\<close>\n\ninductive left_nested_expr :: \\<open>'a expr \\<Rightarrow> bool\\<close> where\n  pair: \\<open>left_nested_expr (\\<langle>l\\<rangle> \\<star> \\<langle>r\\<rangle>)\\<close> |\n  nested: \\<open>left_nested_expr L \\<Longrightarrow> left_nested_expr (L \\<star> R)\\<close>\n\ntext \\<open>Whenever we have a singleton subexpression on the left, but not on the right, we can perform a\nrotation that splits the nonsingleton right subexpression.\\<close>\n\nfun nest_left_subexpr :: \\<open>'a::linorder expr \\<Rightarrow> 'a expr\\<close> where\n  \\<open>nest_left_subexpr \\<langle>a\\<rangle> = \\<langle>a\\<rangle>\\<close> |\n  \\<open>nest_left_subexpr (\\<langle>l\\<rangle> \\<star> \\<langle>r\\<rangle>) = (\\<langle>l\\<rangle> \\<star> \\<langle>r\\<rangle>)\\<close> |\n  \\<open>nest_left_subexpr (\\<langle>l\\<rangle> \\<star> (M \\<star> R)) = (\\<langle>l\\<rangle> \\<star> M) \\<star> R\\<close> |\n  \\<open>nest_left_subexpr ((L \\<star> M) \\<star> R) = ((L \\<star> M) \\<star> R)\\<close>\n\ntext \\<open>This does not change the expression's size or multiset of values.\\<close>\n\nlemma nest_left_subexpr_size[simp]:\n  \\<open>size (nest_left_subexpr E) = size E\\<close>\n  by (induction E rule: nest_left_subexpr.induct; simp)\n\nlemma nest_left_subexpr_mset[simp]:\n  \\<open>mset_expr (nest_left_subexpr E) = mset_expr E\\<close>\n  by (induction E rule: nest_left_subexpr.induct; simp)\n\ntext \\<open>We can perform such rotations and then recurse on the left subexpression of the result. \\<close>\n\nfun nest_left_expr :: \\<open>'a::linorder expr \\<Rightarrow> 'a expr\\<close>\n  and helper_nest_left_expr :: \\<open>'a::linorder expr \\<Rightarrow> 'a expr\\<close> where\n    \\<open>nest_left_expr E = helper_nest_left_expr (nest_left_subexpr E) \\<close> |\n    \\<open>helper_nest_left_expr \\<langle>a\\<rangle> = \\<langle>a\\<rangle>\\<close> |\n    \\<open>helper_nest_left_expr (L \\<star> R) = nest_left_expr L \\<star> R\\<close>\n\ntext \\<open>Rotations don't change the list order of values.\\<close>\n\nlemma nest_left_expr_list: \\<open>list_expr (nest_left_expr E) = list_expr E\\<close>\nproof (induction \\<open>size E\\<close> arbitrary: E rule: less_induct)\n  case less\n  then show ?case\n    by (cases E rule: nest_left_subexpr.cases; simp)\nqed\n\ndeclare left_nested_expr.intros[intro] left_nested_expr.cases[elim]\n\ntext \\<open>Performing these rotations results in an expression that has the wanted property of directly\ncombining the leftmost value with another value.\\<close>\n\nlemma left_nested_nest_left_expr:\n  \\<open>is_Op E \\<Longrightarrow> left_nested_expr (nest_left_expr E)\\<close>\nproof (induction \\<open>size E\\<close> arbitrary: E rule: less_induct)\n  case less\n  then show ?case\n    by (cases E rule: nest_left_subexpr.cases; auto)\nqed\n\ntext \\<open>If the initial expression has a minimal head, these rotations also do not increase the\nevaluation result.\\<close>\n\nlemma (in huffman_algebra) value_nest_left_expr:\n  \\<open>\\<lbrakk>Min_hd_expr E\\<rbrakk> \\<Longrightarrow> value_expr (nest_left_expr E) \\<le> value_expr E\\<close>\nproof (induction \\<open>size E\\<close> arbitrary: E rule: less_induct)\n  case less\n  then show ?case\n  proof (cases E rule: nest_left_subexpr.cases; (auto; fail)?)\n    case (3 l M R)\n\n    have A: \\<open>l \\<le> Min_expr M\\<close>\n      by (metis \"3\" Min_expr_Op Min_expr_Val Min_hd_expr_subexpr_ord less.prems min.bounded_iff)\n    hence \\<open>Min_hd_expr (\\<langle>l\\<rangle> \\<star> M)\\<close> \\<open>size (\\<langle>l\\<rangle> \\<star> M) < size E\\<close>\n      by (auto simp add: Min_expr_Op min.absorb1 3)\n    hence \\<open>value_expr (nest_left_expr (\\<langle>l\\<rangle> \\<star> M)) \\<le> value_expr (\\<langle>l\\<rangle> \\<star> M)\\<close>\n      using less.hyps by fastforce\n    hence *: \\<open>value_expr (nest_left_expr (\\<langle>l\\<rangle> \\<star> M) \\<star> R) \\<le> value_expr ((\\<langle>l\\<rangle> \\<star> M) \\<star> R)\\<close>\n      by (simp add: mono)\n\n    have \\<open>l \\<le> Min_expr R\\<close>\n      by (metis \"3\" Min_expr_Op Min_expr_Val Min_hd_expr_left_subexpr_Min less.prems\n          min.cobounded2 min_le_iff_disj)\n    hence **: \\<open>value_expr ((\\<langle>l\\<rangle> \\<star> M) \\<star> R) \\<le> value_expr (\\<langle>l\\<rangle> \\<star> (M \\<star> R))\\<close>\n      using A\n      by (metis Min_expr_bound assoc_ineq order_trans value_expr.simps(1) value_expr.simps(2))\n\n    show ?thesis \n      by (simp add: 3; fold nest_left_expr.simps; insert * **; auto)\n  next\n    case (4 L M R)\n    show ?thesis\n      by (simp add: 4; fold nest_left_expr.simps; metis \"4\" Min_hd_expr_left_subexpr Suc_le_eq\n          add.right_neutral add_Suc_right dual_order.strict_iff_order expr.size(4) le_add1\n          less.hyps less.prems mono value_expr.simps(2))\n  qed\nqed\n\n\n(***)\n\ntext \\<open>We now combine our three rearrangement steps: first we swap left and right subexpressions\nwhenever the right subexpression contains a smaller value, then we rearrange subexpressions to move\nthe second smallest value to the second position from the left and finally we perform tree rotations\nto pair up the two smallest values.\\<close>\n\ndefinition rearrange_expr :: \\<open>'a::linorder expr \\<Rightarrow> 'a expr\\<close> where\n   \\<open>rearrange_expr E = nest_left_expr (tl_Min_to_hd_expr (Min_to_hd_expr E))\\<close>\n\ntext \\<open>As intended, the result has the same multiset of values, still has a minimal head and a tail\nwith minimal head and does have the two leftmost values in the leftmost nonsingleton subexpression.\\<close>\n\nlemma rearrange_expr_mset: \\<open>mset_expr (rearrange_expr E) = mset_expr E\\<close>\n  by (metis Min_to_hd_expr_mset nest_left_expr_list rearrange_expr_def tl_Min_to_hd_expr_mset)\n\nlemma Min_hd_rearrange_expr: \\<open>Min_hd_expr (rearrange_expr E)\\<close>\n  by (metis (mono_tags, lifting) Min_expr_mset_cong Min_to_hd_expr_spec all_subexpr_top\n      nest_left_expr_list rearrange_expr_def tl_Min_to_hd_expr_Min tl_Min_to_hd_expr_hd)\n\nlemma tl_Min_hd_rearrange_expr: \\<open>tl_Min_hd_expr (rearrange_expr E)\\<close>\n  unfolding rearrange_expr_def\n  using tl_Min_to_hd_expr_spec Min_to_hd_expr_spec nest_left_expr_list tl_Min_hd_expr_list_expr_cong\n  by blast\n\nlemma left_nested_rearrange_expr:\n  assumes \\<open>is_Op E\\<close>\n  shows \\<open>left_nested_expr (rearrange_expr E)\\<close>\nproof -\n  have \\<open>is_Op (tl_Min_to_hd_expr (Min_to_hd_expr E))\\<close>\n    using assms unfolding is_Op_by_count\n    by (metis (mono_tags, lifting) Min_to_hd_expr_mset mset_eq_length tl_Min_to_hd_expr_mset)\n  thus ?thesis\n    unfolding rearrange_expr_def\n    using left_nested_nest_left_expr by blast\nqed\n\ntext \\<open>All this combined also does not increase the evaluation result.\\<close>\n\nlemma (in huffman_algebra) value_rearrange_expr:\n  \\<open>value_expr (rearrange_expr E) \\<le> value_expr E\\<close>\n  unfolding rearrange_expr_def\n  by (metis (mono_tags, lifting) Min_to_hd_expr_spec all_subexpr_top order_trans\n      tl_Min_to_hd_expr_Min tl_Min_to_hd_expr_hd value_Min_to_hd_expr value_nest_left_expr\n      value_tl_Min_to_hd_expr)\n\n(***)\n\ntext \\<open>For an expression with a minimal head, the head value is the head of the sorted list of its\nvalues, which is the minimal value.\\<close>\n\nlemma Min_hd_expr_sorted_1:\n  \\<open>Min_hd_expr E \\<Longrightarrow> hd_expr E = hd (sorted_list_of_multiset (mset_expr E))\\<close>\n  by (metis Min_expr_from_mset hd_sorted_list_of_multiset length_0_conv list_expr_nonempty\n      mset.simps(1) size_mset)\n\ntext \\<open>For an expression with a minimal head and a tail with minimal head, the head value of its\ntail is the second value in the sorted list of its values, which is the second smallest value.\\<close>\n\nlemma Min_hd_expr_sorted_2:\n  assumes \\<open>is_Op E\\<close> \\<open>Min_hd_expr E\\<close> \\<open>tl_Min_hd_expr E\\<close>\n  shows \\<open>hd_expr (tl_expr E) = hd (tl (sorted_list_of_multiset (mset_expr E)))\\<close>\n  by (metis Min_expr_from_mset Min_hd_expr_sorted_1 assms list_expr_nonempty\n      list_tl_expr mset_tl mset_zero_iff tl_sorted_list_of_multiset)\n\ntext \\<open>From this we get that the head the result of rearranging an expression is the minimal value of\nthe initial expression.\\<close>\n\nlemma hd_list_rearrange_expr:\n  \\<open>hd_expr (rearrange_expr E) = hd (sorted_list_of_multiset (mset_expr E))\\<close>\n  by (metis Min_expr_from_mset Min_hd_rearrange_expr hd_sorted_list_of_multiset list_expr_nonempty\n      mset_zero_iff rearrange_expr_mset)\n\ntext \\<open>We also get that the second leftmost value in the rearranged expression is the second smallest\nvalue of the initial expression.\\<close>\n\nlemma hd_tl_list_rearrange_expr:\n  \\<open>hd (tl (list_expr (rearrange_expr E))) = hd (tl (sorted_list_of_multiset (mset_expr E)))\\<close>\n  by (cases E; (simp add: rearrange_expr_def; fail)?; simp;\n      metis (mono_tags, lifting) Min_hd_expr_sorted_2 Min_hd_rearrange_expr count_expr_Op\n      expr.simps(8) is_Op_by_count list_tl_expr mset_append mset_eq_length rearrange_expr_mset\n      tl_Min_hd_rearrange_expr)\n\ntext \\<open>If two lists have the same length and they match on their first two entries, the have the same\nlength-2 prefix.\\<close>\n\nlemma take_2_from_hds:\n  assumes \\<open>length xs = length ys\\<close> \\<open>hd xs = hd ys\\<close> \\<open>hd (tl xs) = hd (tl ys)\\<close>\n  shows \\<open>take 2 xs = take 2 ys\\<close>\n  using assms\n  by (cases xs; simp; cases ys; simp; cases \\<open>tl xs\\<close>; simp; cases \\<open>tl ys\\<close>; simp)\n\ntext \\<open>This allows us to state that the leftmost two values of a rearranged expression are the two\nsmallest values.\\<close>\n\nlemma take_2_list_rearrange_expr:\n  \\<open>take 2 (list_expr (rearrange_expr E)) = take 2 (sorted_list_of_multiset (mset_expr E))\\<close>\n  by (rule take_2_from_hds; (simp add: hd_list_rearrange_expr hd_tl_list_rearrange_expr; fail)?;\n      metis mset_sorted_list_of_multiset rearrange_expr_mset size_mset)\n\n\n(***)\n\ntext \\<open>We want to replace the subexpression of the two smallest values. For this we first inductively\ndefine what it means for an expression to have a subexpression.\\<close>\n\ninductive has_subexpr :: \\<open>'a expr \\<Rightarrow> 'a expr \\<Rightarrow> bool\\<close> where\n  here: \\<open>has_subexpr X X\\<close> |\n  left: \\<open>has_subexpr X L \\<Longrightarrow> has_subexpr X (L \\<star> R)\\<close> |\n  right: \\<open>has_subexpr X R \\<Longrightarrow> has_subexpr X (L \\<star> R)\\<close>\n\ndeclare has_subexpr.intros[intro] has_subexpr.cases[elim]\n\nlemma has_subexpr_simp_Op:\n  \\<open>has_subexpr E (L \\<star> R) = (E = L \\<star> R \\<or> has_subexpr E L \\<or> has_subexpr E R)\\<close>\n  by blast\n\ntext \\<open>Any value present in an expression corresponds to a present subexpression consisting of just\nthat value.\\<close>\n\nlemma has_subexpr_Val: \\<open>a \\<in> set_expr E = has_subexpr \\<langle>a\\<rangle> E\\<close>\n  by (induction E; auto)\n\ntext \\<open>The multiset of values in a subexpression is a subset of the multiset of the values of the\nwhole expression.\\<close>\n\nlemma mset_has_subexpr: \\<open>has_subexpr X E \\<Longrightarrow> mset_expr X \\<subseteq># mset_expr E\\<close>\n  by (induction E; auto; insert subset_mset.add_increasing subset_mset.add_increasing2; fastforce)\n\ntext \\<open>For an expression where the two leftmost values are combined (@{term left_nested_expr}}, the\nsubexpression that combines those terms is indeed a subexpression.\\<close>\n\nlemma left_nested_expr_has_hd2_subexpr:\n  assumes \\<open>left_nested_expr E\\<close> \\<open>hd (list_expr E) = a1\\<close> \\<open>hd (tl (list_expr E)) = a2\\<close>\n  shows \\<open>has_subexpr (\\<langle>a1\\<rangle> \\<star> \\<langle>a2\\<rangle>) E\\<close>\n  using assms\nproof (induction E rule: left_nested_expr.induct)\n  case (pair l r)\n  then show ?case\n    by auto\nnext\n  case (nested L R)\n  then show ?case\n    by (simp; metis (mono_tags, lifting) count_expr_ge1 expr.distinct(1) expr_from_list hd_append2\n        left left_nested_expr.cases list.collapse list.size(3) not_one_le_zero)\nqed\n\ntext \\<open>We then define a function that replaces the leftmost occurrence of a subexpression with a\ndifferent subexpression.\\<close>\n\nfunction replace_subexpr :: \\<open>'a expr \\<Rightarrow> 'a expr \\<Rightarrow> 'a expr \\<Rightarrow> 'a expr\\<close> where\n  \\<open>\\<not>has_subexpr X E \\<Longrightarrow> replace_subexpr X Y E = E\\<close> |\n  \\<open>X = E \\<Longrightarrow> replace_subexpr X Y E = Y\\<close> |\n  \\<open>\\<lbrakk>X \\<noteq> L \\<star> R; has_subexpr X L\\<rbrakk> \\<Longrightarrow> replace_subexpr X Y (L \\<star> R) = replace_subexpr X Y L \\<star> R\\<close> |\n  \\<open>\\<lbrakk>X \\<noteq> L \\<star> R; \\<not>has_subexpr X L; has_subexpr X R\\<rbrakk> \\<Longrightarrow>\n    replace_subexpr X Y (L \\<star> R) = L \\<star> replace_subexpr X Y R\\<close>\n  by (auto, metis has_subexpr.cases)\ntermination by lexicographic_order\n\ntext \\<open>Doing such a replacement removes and adds the corresponding values of the replaced and\nreplacement subexpressions respectively.\\<close>\n\nlemma mset_replace_subexpr:\n  \\<open>has_subexpr X E \\<Longrightarrow> mset_expr (replace_subexpr X Y E) = mset_expr E - mset_expr X + mset_expr Y\\<close>\n  by (induction X Y E rule: replace_subexpr.induct; auto;\n      unfold has_subexpr_simp_Op; auto simp add: mset_has_subexpr)\n\ntext \\<open>If the evaluated value of the replaced and replacement subexpressions are the same, this does\nnot change the evaluated value of the whole expression.\\<close>\n\nlemma (in huffman_algebra) value_replace_subexpr:\n  \\<open>value_expr X = value_expr Y \\<Longrightarrow> value_expr (replace_subexpr X Y E) = value_expr E\\<close>\n  by (induction X Y E rule: replace_subexpr.induct; auto)\n\ntext \\<open>Any change of the subexpressions evaluated value leads to a corresponding change of the whole\nexpression's evaluated value.\\<close>\n\nlemma (in huffman_algebra) value_replace_subexpr_increasing:\n  \\<open>value_expr X \\<le> value_expr Y \\<Longrightarrow> value_expr E \\<le> value_expr (replace_subexpr X Y E)\\<close>\n  by (induction X Y E rule: replace_subexpr.induct; simp add: mono;\n      metis commutative mono value_expr.simps(2))\n\nlemma (in huffman_algebra) value_replace_subexpr_decreasing:\n  \\<open>value_expr Y \\<le> value_expr X \\<Longrightarrow> value_expr (replace_subexpr X Y E) \\<le> value_expr E\\<close>\n  by (induction X Y E rule: replace_subexpr.induct; simp add: mono;\n      metis commutative mono value_expr.simps(2))\n\n(***)\n\n(* TODO continue here *)\n\nlemma finite_expr_of_size:\n  assumes \\<open>finite U\\<close>\n  shows \\<open>finite {E. set_expr E \\<subseteq> U \\<and> size E < n}\\<close>\nproof (induction n)\n  case 0\n  then show ?case\n    by simp\nnext\n  case (Suc n)\n  have \\<open>{E. set_expr E \\<subseteq> U \\<and> size E < Suc n} \\<subseteq>\n    (Val ` U) \\<union> (\\<Union>L \\<in> {E. set_expr E \\<subseteq> U \\<and> size E < n}.\n      (\\<star>) L ` {E. set_expr E \\<subseteq> U \\<and> size E < n})\\<close>\n  proof\n    fix E assume E: \\<open>E \\<in> {E. set_expr E \\<subseteq> U \\<and> size E < Suc n}\\<close>\n    hence PE: \\<open>size E < Suc n\\<close> \\<open>set_expr E \\<subseteq> U\\<close>\n      by auto\n    show \\<open>E \\<in> Val ` U \\<union>\n      (\\<Union>L\\<in>{E. set_expr E \\<subseteq> U \\<and> size E < n}.\n        (\\<star>) L ` {E. set_expr E \\<subseteq> U \\<and> size E < n})\\<close>\n      by (cases E; insert PE; auto)\n  qed\n  then show ?case\n    by (metis (no_types, lifting) Suc.IH assms finite_UN_I finite_Un finite_imageI finite_subset)\nqed\n\nlemma finite_expr_for_mset:\n  \\<open>finite {E. mset_expr E = A}\\<close>\nproof -\n  have \\<open>{E. mset_expr E = A} \\<subseteq> {E. set_expr E \\<subseteq> set_mset A \\<and> size E < 2 * size A}\\<close>\n    by (intro Collect_mono impI; fold set_mset_expr; auto simp add: count_expr_size)\n  thus ?thesis\n    using finite_expr_of_size finite_subset by fastforce\nqed\n\nlemma ex_expr_for_mset:\n  assumes \\<open>V \\<noteq> {#}\\<close>\n  shows \\<open>\\<exists>E. mset_expr E = V\\<close>\nproof -\n  obtain v where v: \\<open>v \\<in># V\\<close> using assms\n    by blast\n  obtain L where \\<open>mset L = (V - {#v#})\\<close>\n    using ex_mset by blast\n  hence Lv_mset: \\<open>mset (L @ [v]) = V\\<close>\n    by (simp add: v)\n  obtain E where E: \\<open>E = foldr (\\<lambda> a b. \\<langle>a\\<rangle> \\<star> b) L \\<langle>v\\<rangle>\\<close>\n    by simp\n  hence \\<open>list_expr E = L @ [v]\\<close>\n    unfolding E by (induction L; simp)\n  hence \\<open>mset_expr E = V\\<close>\n    using Lv_mset by auto\n  thus ?thesis\n    by blast\nqed\n\n(***)\n\ncontext huffman_algebra\nbegin\n\nabbreviation value_bound_mset :: \\<open>'a multiset \\<Rightarrow> 'a\\<close> where\n  \\<open>value_bound_mset A \\<equiv> Min (value_expr ` {E. mset_expr E = A})\\<close>\n\nlemma value_bound_singleton:\n  \\<open>value_bound_mset {# a #} = a\\<close>\nproof - \n  have \\<open>{E. mset_expr E = {# a #}} = {\\<langle>a\\<rangle>}\\<close>\n    using expr_from_mset by force\n  thus ?thesis\n    by simp\nqed\n\n\nlemma \\<open>value_expr E \\<ge> value_bound_mset (mset_expr E)\\<close>\n  by (intro Min_le; insert finite_expr_for_mset; blast)\n\nfun huffman_step_sorted_list :: \\<open>'a list \\<Rightarrow> 'a multiset\\<close> where\n  \\<open>huffman_step_sorted_list (a1 # a2 # as) = mset (a1 \\<diamondop> a2 # as)\\<close> |\n  \\<open>huffman_step_sorted_list as = mset as\\<close>\n\nabbreviation huffman_step :: \\<open>'a multiset \\<Rightarrow> 'a multiset\\<close> where\n  \\<open>huffman_step A \\<equiv> huffman_step_sorted_list (sorted_list_of_multiset A)\\<close>\n\nlemma huffman_step_sorted_list_size:\n  \\<open>length as \\<ge> 2 \\<Longrightarrow> Suc (size (huffman_step_sorted_list as)) = length as\\<close>\n  by (metis One_nat_def Suc_1 Suc_leD Suc_n_not_le_n huffman_step_sorted_list.elims length_Cons\n      list.size(3) size_mset)\n\nlemma huffman_step_size[simp]:\n  \\<open>size A \\<ge> 2 \\<Longrightarrow> size (huffman_step A) < size A\\<close>\n  by (metis Suc_n_not_le_n huffman_step_sorted_list_size leI mset_sorted_list_of_multiset size_mset)\n\nlemma huffman_step_as_mset_ops:\n  assumes \\<open>size A \\<ge> 2\\<close> \\<open>a1 # a2 # as = sorted_list_of_multiset A\\<close>\n  shows \\<open>huffman_step A = A - {# a1, a2 #} + {# a1 \\<diamondop> a2 #}\\<close>\n  by (metis add_mset_add_single add_mset_diff_bothsides add_mset_remove_trivial assms(2)\n      huffman_step_sorted_list.simps(1) mset.simps(2) mset_sorted_list_of_multiset)\n\nlemma Min_image_corr_le:\n  assumes \\<open>finite A\\<close> \\<open>A \\<noteq> {}\\<close> \\<open>finite B\\<close> \\<open>\\<And>a. a \\<in> A \\<Longrightarrow> \\<exists>b \\<in> B. f b \\<le> f a\\<close>\n  shows \\<open>Min (f ` B) \\<le> Min (f ` A)\\<close>\nproof -\n  have \\<open>\\<And>a. a \\<in> A \\<Longrightarrow> Min (f ` B) \\<le> f a\\<close>\n    by (meson Min_le assms(3) assms(4) finite_imageI imageI le_less_trans not_le)\n  thus ?thesis\n    by (simp add: assms(1) assms(2))\nqed\n\nlemma value_bound_via_correspondence:\n  assumes \\<open>V1 \\<noteq> {#}\\<close>\n    \\<open>\\<And>E1. mset_expr E1 = V1 \\<Longrightarrow> \\<exists>E2. mset_expr E2 = V2 \\<and> value_expr E2 \\<le> value_expr E1\\<close>\n  shows \\<open>value_bound_mset V2 \\<le> value_bound_mset V1\\<close>\n  by (intro Min_image_corr_le; auto simp add: assms finite_expr_for_mset ex_expr_for_mset)\n\nlemma combine_step_lower_bound:\n  assumes \\<open>{# a1, a2 #} \\<subseteq># A\\<close>\n  shows \\<open>value_bound_mset A \\<le> value_bound_mset (A - {# a1, a2 #} + {# a1 \\<diamondop> a2 #})\\<close>\nproof (intro value_bound_via_correspondence; (simp; fail)?)\n  fix E1 assume E1: \\<open>mset_expr E1 = A - {#a1, a2#} + {#a1 \\<diamondop> a2#}\\<close>\n  hence \\<open>has_subexpr \\<langle>a1 \\<diamondop> a2\\<rangle> E1\\<close>\n    by (metis add_mset_add_single has_subexpr_Val set_mset_expr union_single_eq_member)\n  hence \\<open>mset_expr (replace_subexpr \\<langle>a1 \\<diamondop> a2\\<rangle> (\\<langle>a1\\<rangle> \\<star> \\<langle>a2\\<rangle>) E1) = A\\<close>\n    by (simp add: mset_replace_subexpr; insert E1 assms subset_mset.diff_add; fastforce)\n  moreover have \\<open>value_expr (replace_subexpr \\<langle>a1 \\<diamondop> a2\\<rangle> (\\<langle>a1\\<rangle> \\<star> \\<langle>a2\\<rangle>) E1) = value_expr E1\\<close>\n      by (simp add: value_replace_subexpr)\n  ultimately show \\<open>\\<exists>E2. mset_expr E2 = A \\<and> value_expr E2 \\<le> value_expr E1\\<close>\n    by auto\nqed\n\nlemma (in huffman_algebra) huffman_step_lower_bound:\n  assumes \\<open>A \\<noteq> {#}\\<close>\n  shows \\<open>value_bound_mset A \\<le> value_bound_mset (huffman_step A)\\<close>\nproof (cases \\<open>size A < 2\\<close>)\n  case True\n  then obtain a where \\<open>A = {# a #}\\<close>\n    using assms less_2_cases size_1_singleton_mset by auto\n  then show ?thesis\n    by auto\nnext\n  case False\n  then obtain a1 a2 as where V: \\<open>a1 # a2 # as = sorted_list_of_multiset A\\<close>\n    by (metis One_nat_def Suc_1 assms length_Cons lessI list.size(3) mset.simps(1)\n        mset_sorted_list_of_multiset remdups_adj.cases size_mset)\n  hence a1a2_in_A: \\<open>{# a1, a2 #} \\<subseteq># A\\<close>\n    by (metis empty_le mset.simps(2) mset_sorted_list_of_multiset mset_subset_eq_add_mset_cancel)\n    \n  show ?thesis\n    using huffman_step_as_mset_ops[of A a1 a2 as]  False V a1a2_in_A\n      combine_step_lower_bound huffman_algebra_axioms by auto\nqed\n\nlemma huffman_step_upper_bound:\n  assumes \\<open>A \\<noteq> {#}\\<close>\n  shows \\<open>value_bound_mset (huffman_step A) \\<le> value_bound_mset A\\<close>\nproof (intro value_bound_via_correspondence)\n  show \\<open>A \\<noteq> {#}\\<close>\n    by (simp add: assms)\nnext\n  fix E1 assume E1: \\<open>mset_expr E1 = A\\<close>\n  show \\<open>\\<exists>E2. mset_expr E2 = huffman_step A \\<and> value_expr E2 \\<le> value_expr E1\\<close>\n  proof (cases \\<open>size A < 2\\<close>)\n    case True\n    then obtain a where A: \\<open>A = {#a#}\\<close>\n      using assms less_2_cases size_1_singleton_mset by auto\n    then show ?thesis\n      using E1 by auto\n  next\n    case False\n    then obtain a1 a2 as where V: \\<open>a1 # a2 # as = sorted_list_of_multiset A\\<close>\n      by (metis Suc_le_length_iff leI mset_sorted_list_of_multiset numeral_2_eq_2 size_mset)\n    obtain H where H: \\<open>H = rearrange_expr E1\\<close> \n      by simp\n\n    have H_is_Op: \\<open>is_Op H\\<close>\n      by (metis E1 False H is_Op_by_count leI rearrange_expr_mset size_mset)\n    have H_bound: \\<open>value_expr H \\<le> value_expr E1\\<close>\n      by (simp add: H value_rearrange_expr)\n\n    have \\<open>left_nested_expr H\\<close>\n      by (metis E1 False H is_Op_by_count le_less_linear left_nested_rearrange_expr size_mset)\n    moreover have \\<open>hd (list_expr H) = a1\\<close>\n      by (metis H E1 V hd_list_rearrange_expr list.sel(1))\n    moreover have \\<open>hd (tl (list_expr H)) = a2\\<close>\n      by (metis E1 H V hd_tl_list_rearrange_expr list.sel(1) list.sel(3))\n    ultimately have H_subexpr: \\<open>has_subexpr (\\<langle>a1\\<rangle> \\<star> \\<langle>a2\\<rangle>) H\\<close>\n      by (simp add: left_nested_expr_has_hd2_subexpr)\n\n    then obtain E2 where E2: \\<open>E2 = replace_subexpr (\\<langle>a1\\<rangle> \\<star> \\<langle>a2\\<rangle>) \\<langle>a1 \\<diamondop> a2\\<rangle> H\\<close>\n      by simp\n    hence \\<open>value_expr E2 \\<le> value_expr E1\\<close>\n      by (simp add: H_bound value_replace_subexpr)\n\n    moreover have \\<open>mset_expr E2 = A - {# a1, a2 #} + {# a1 \\<diamondop> a2 #}\\<close>\n      by (metis (mono_tags, lifting) E1 E2 H H_subexpr append.simps(2) append_self_conv2\n          expr.simps(7) expr.simps(8) mset.simps(1) mset.simps(2) mset_replace_subexpr\n          rearrange_expr_mset)\n    hence \\<open>mset_expr E2 = huffman_step A\\<close>\n      using False V huffman_step_as_mset_ops by auto\n\n    ultimately show ?thesis\n      by blast\n  qed\nqed\n\nlemma value_huffman_step:\n  \\<open>value_bound_mset (huffman_step A) = value_bound_mset A\\<close>\n  by (cases \\<open>A = {#}\\<close>; insert huffman_step_lower_bound huffman_step_upper_bound; force)\n\nfunction value_bound_huffman :: \\<open>'a multiset \\<Rightarrow> 'a\\<close> where\n  \\<open>value_bound_huffman A = (case size A of\n    0 \\<Rightarrow> Min {} |\n    Suc 0 \\<Rightarrow> the_elem (set_mset A) |\n    Suc (Suc _) \\<Rightarrow> value_bound_huffman (huffman_step A)\n  )\\<close> \n  by pat_completeness auto\ntermination\n  by (relation \\<open>measure size\\<close>; simp;\n      metis Suc_1 Suc_le_eq less_add_Suc1 local.huffman_step_size plus_1_eq_Suc)\n\nlemma value_bound_huffman_singleton:\n  \\<open>value_bound_mset {#a#} = value_bound_huffman {#a#}\\<close>\n  by (subst value_bound_singleton; simp)\n\nlemma value_bound_huffman_nonsingleton:\n  \\<open>size A = Suc n \\<Longrightarrow> value_bound_mset A = value_bound_huffman A\\<close>\nproof (induction n arbitrary: A)\n  case 0\n  then obtain a where \\<open>A = {# a #}\\<close>\n    by (metis One_nat_def size_1_singleton_mset)\n  then show ?case\n    using value_bound_huffman_singleton by blast\nnext\n  case (Suc n)\n  have \\<open>size (huffman_step A) = Suc n\\<close>\n    by (metis Suc.prems Suc_1 Suc_le_eq add_diff_cancel_left' less_add_Suc1\n        local.huffman_step_sorted_list_size mset_sorted_list_of_multiset plus_1_eq_Suc size_mset)\n  hence \\<open>value_bound_huffman (huffman_step A) = value_bound_mset (huffman_step A)\\<close>\n    using Suc.IH by auto\n  then show ?case\n    by (subst value_bound_huffman.simps; simp add: Suc.prems value_huffman_step)\nqed\n\nlemma value_bound_huffman_mset:\n  \\<open>value_bound_mset A = value_bound_huffman A\\<close>\n  by (cases \\<open>size A\\<close>; insert value_bound_huffman_nonsingleton; auto)\n\n(***)\n\nlemma value_expr_homo:\n  assumes \\<open>\\<And>a b. f (a \\<diamondop> b) = f a \\<diamondop> f b\\<close>\n  shows \\<open>value_expr (map_expr f E) = f (value_expr E)\\<close>\n  using assms\n  by (induction E; auto)\n\nlemma value_expr_mono:\n  assumes \\<open>\\<And>a b. f (a \\<diamondop> b) \\<le> f a \\<diamondop> f b\\<close> \n  shows \\<open>f (value_expr E) \\<le> value_expr (map_expr f E)\\<close>\n  using assms\nproof (induction E; (simp; fail)?)\n  case (Op L R)\n\n  have L: \\<open>f (value_expr L) \\<le> value_expr (map_expr f L)\\<close>\n    and R: \\<open>f (value_expr R) \\<le> value_expr (map_expr f R)\\<close>\n    using Op.IH assms by auto \n  hence \\<open>f (value_expr L) \\<diamondop> f (value_expr R) \\<le> f (value_expr L) \\<diamondop> value_expr (map_expr f R)\\<close>\n    using local.commutative local.mono by fastforce\n  hence \\<open>f (value_expr L) \\<diamondop> f (value_expr R) \\<le> value_expr (map_expr f L) \\<diamondop> value_expr (map_expr f R)\\<close>\n    by (metis L local.mono min.absorb2 min.coboundedI1)\n  hence \\<open>f (value_expr L \\<diamondop> value_expr R) \\<le> value_expr (map_expr f L) \\<diamondop> value_expr (map_expr f R)\\<close>\n    using assms dual_order.trans by blast\n  then show ?case\n    by simp\nqed\n\nlemma mset_expr_map_expr:\n  \\<open>list_expr (map_expr f E) = map f (list_expr E)\\<close>\n  by (induction E; auto)\n\nlemma unmap_list_expr:\n  \\<open>list_expr E = map f as \\<Longrightarrow> \\<exists>E'. E = map_expr f E' \\<and> list_expr E' = as\\<close>\nproof (induction E arbitrary: as)\n  case (Val b)\n  then obtain a where \\<open>as = [a]\\<close>\n    by auto\n  then show ?case\n    by (metis Val.prems expr.simps(7) expr.simps(9) list.sel(1) list.simps(9))\nnext\n  case (Op L R)\n  obtain ls where ls: \\<open>ls = take (length (list_expr L)) as\\<close>\n    by blast\n  obtain rs where rs: \\<open>rs = drop (length (list_expr L)) as\\<close>\n    by blast\n  have \\<open>list_expr L = map f ls\\<close>\n    by (metis (mono_tags, lifting) Op.prems append_eq_conv_conj expr.simps(8) ls take_map)\n  then obtain L' where L': \\<open>L = map_expr f L' \\<and> list_expr L' = ls\\<close>\n    using Op.IH(1) by blast\n\n  have \\<open>list_expr R = map f rs\\<close>\n    by (metis (mono_tags, lifting) Op.prems append_eq_conv_conj drop_map expr.simps(8) rs)\n  then obtain R' where R': \\<open>R = map_expr f R' \\<and> list_expr R' = rs\\<close>\n    using Op.IH(2) by blast\n\n  have \\<open>L \\<star> R = map_expr f (L' \\<star> R') \\<and> list_expr (L' \\<star> R') = as\\<close>\n    by (simp add: L' R' ls rs)\n  thus ?case\n    by blast\nqed\n\nlemma unmap_image_mset:\n  \\<open>mset as = image_mset f B \\<Longrightarrow> \\<exists>bs. as = map f bs \\<and> B = mset bs\\<close>\nproof (induction as arbitrary: B)\n  case Nil\n  then show ?case\n    by simp\nnext\n  case (Cons a as)\n  obtain B' b where *: \\<open>mset as = image_mset f B' \\<and> a = f b \\<and> B = add_mset b B'\\<close>\n    by (metis Cons.prems msed_map_invR mset.simps(2))\n  then obtain bs where **: \\<open>as = map f bs \\<and> B' = mset bs\\<close>\n    using Cons.IH by blast\n\n  have \\<open>a # as = map f (b # bs) \\<and> B = mset (b # bs)\\<close>\n    by (simp add: * **)\n  then show ?case\n    by metis\nqed\n\nlemma unmap_mset_expr:\n  assumes \\<open>mset_expr E = image_mset f A\\<close>\n  shows \\<open>\\<exists>E'. E = map_expr f E' \\<and> mset_expr E' = A\\<close>\nproof -\n  obtain es where es: \\<open>es = list_expr E\\<close>\n    by simp\n  then obtain as where \\<open>es = map f as \\<and> A = mset as\\<close>\n    using unmap_image_mset[of es f A] assms\n    by blast\n  thus ?thesis\n    using es unmap_list_expr by fastforce\nqed\n\nlemma map_expr_inv: \\<open>set_expr E \\<subseteq> range f \\<Longrightarrow> map_expr f (map_expr (inv f) E) = E\\<close>\n  by (induction E; simp add: f_inv_into_f)\n\nlemma value_expr_map_expr_inv_homo:\n  assumes \\<open>\\<And>a b. f (a \\<diamondop> b) = f a \\<diamondop> f b\\<close> \\<open>set_expr E \\<subseteq> range f\\<close>\n  shows \\<open>f (value_expr (map_expr (inv f) E)) = value_expr E\\<close>\n  using assms\n  by (induction E; simp add: f_inv_into_f)\n\nlemma map_expr_inv_homo_image_mset:\n  assumes \\<open>\\<And>a b. f (a \\<diamondop> b) = f a \\<diamondop> f b\\<close> \\<open>mset_expr E = image_mset f A\\<close>\n  shows \\<open>(map_expr f (map_expr (inv f) E) = E) \\<and> (f (value_expr (map_expr (inv f) E)) = value_expr E)\\<close>\nproof -\n  have \\<open>set_expr E \\<subseteq> range f\\<close>\n    unfolding set_mset_expr[symmetric]\n    using assms by auto\n  thus ?thesis\n    by (simp add: assms(1) map_expr_inv value_expr_map_expr_inv_homo)\nqed\n\nlemma map_exprs_for_mset:\n  \\<open>{E. mset_expr E = image_mset f A} = map_expr f ` {E. mset_expr E = A}\\<close>\nproof (rule; rule)\n  fix x assume \\<open>x \\<in> {E. mset_expr E = image_mset f A}\\<close>\n  thus \\<open>x \\<in> map_expr f ` {E. mset_expr E = A}\\<close>\n    using unmap_mset_expr by fastforce\nnext\n  fix x assume \\<open>x \\<in> map_expr f ` {E. mset_expr E = A}\\<close>\n  thus \\<open>x \\<in> {E. mset_expr E = image_mset f A}\\<close>\n    by (metis (mono_tags, lifting) imageE mem_Collect_eq mset_expr_map_expr mset_map)\nqed\n\nlemma value_bound_homo:\n  assumes \\<open>\\<And>a b. f (a \\<diamondop> b) = f a \\<diamondop> f b\\<close> \\<open>mono f\\<close> \\<open>A \\<noteq> {#}\\<close>\n  shows \\<open>value_bound_mset (image_mset f A) = f (value_bound_mset A)\\<close>\nproof -\n  have \\<open>value_expr ` {E. mset_expr E = image_mset f A} =\n      (value_expr \\<circ> map_expr f) ` {E. mset_expr E = A}\\<close>\n    by (simp add: image_comp map_exprs_for_mset)\n  moreover have \\<open>(f \\<circ> value_expr) ` {E. mset_expr E = A} =\n      (value_expr \\<circ> map_expr f) ` {E. mset_expr E = A}\\<close>\n    using assms(1) value_expr_homo by auto\n  ultimately have \\<open>value_expr ` {E. mset_expr E = image_mset f A} =\n      f ` value_expr ` {E. mset_expr E = A}\\<close>\n    by (simp add: image_comp)\n  hence \\<open>value_bound_mset (image_mset f A) = Min (f ` value_expr ` {E. mset_expr E = A})\\<close>\n    by simp\n  moreover have \\<open>finite (value_expr ` {E. mset_expr E = A})\\<close>\n    using finite_expr_for_mset by blast\n  ultimately show ?thesis\n    using mono_Min_commute[of f \\<open>value_expr ` {E. mset_expr E = A}\\<close>]\n    by (simp add: assms ex_expr_for_mset)\nqed\n\nlemma Min_corr_image_le:\n  assumes \\<open>finite A\\<close> \\<open>A \\<noteq> {}\\<close> \\<open>\\<And>a. a \\<in> A \\<Longrightarrow> f a \\<le> g a\\<close>\n  shows \\<open>Min (f ` A) \\<le> Min (g ` A)\\<close>\nproof -\n  have \\<open>\\<And>a. a \\<in> A \\<Longrightarrow> Min (f ` A) \\<le> g a\\<close>\n    using Min_le_iff assms(1) assms(3) by auto\n  thus ?thesis\n    by (simp add: assms(1) assms(2))\nqed\n\nlemma value_bound_mono:\n  assumes \\<open>\\<And>a b. f (a \\<diamondop> b) \\<le> f a \\<diamondop> f b\\<close> \\<open>mono f\\<close> \\<open>A \\<noteq> {#}\\<close>\n  shows \\<open>f (value_bound_mset A) \\<le> value_bound_mset (image_mset f A)\\<close>\nproof -\n  have \\<open>value_expr ` {E. mset_expr E = image_mset f A} =\n      (value_expr \\<circ> map_expr f) ` {E. mset_expr E = A}\\<close>\n    by (simp add: image_comp map_exprs_for_mset)\n  moreover have \\<open>Min ((f \\<circ> value_expr) ` {E. mset_expr E = A}) \\<le>\n      Min ((value_expr \\<circ> map_expr f) ` {E. mset_expr E = A})\\<close>\n    by (intro Min_corr_image_le;\n        simp add: assms finite_expr_for_mset ex_expr_for_mset value_expr_mono)\n  ultimately show ?thesis\n    by (simp add: assms ex_expr_for_mset finite_expr_for_mset image_comp mono_Min_commute)\nqed\n\nlemma value_bound_increasing:\n  assumes \\<open>a \\<in># A\\<close> \\<open>b \\<ge> a\\<close>\n  shows \\<open>value_bound_mset A \\<le> value_bound_mset (A - {# a #} + {# b #})\\<close>\nproof (intro value_bound_via_correspondence; (simp; fail)?)\n  fix E1 assume E1: \\<open>mset_expr E1 = A - {#a#} + {#b#}\\<close>\n\n  hence \\<open>has_subexpr \\<langle>b\\<rangle> E1\\<close>\n    by (metis add_mset_add_single has_subexpr_Val set_mset_expr union_single_eq_member)\n\n  hence \\<open>mset_expr (replace_subexpr \\<langle>b\\<rangle> \\<langle>a\\<rangle> E1) = A\\<close>\n    by (simp add: E1 assms(1) mset_replace_subexpr)\n\n  moreover have \\<open>value_expr (replace_subexpr \\<langle>b\\<rangle> \\<langle>a\\<rangle> E1) \\<le> value_expr E1\\<close>\n    by (simp add: assms(2) value_replace_subexpr_decreasing)\n\n  ultimately show \\<open>\\<exists>E2. mset_expr E2 = A \\<and> value_expr E2 \\<le> value_expr E1\\<close>\n    by blast\nqed\n\nend\n\nend", "meta": {"author": "jix", "repo": "sortnetopt", "sha": "0b5d09c47446096f9e3a0812b35afc72b7f2a718", "save_path": "github-repos/isabelle/jix-sortnetopt", "path": "github-repos/isabelle/jix-sortnetopt/sortnetopt-0b5d09c47446096f9e3a0812b35afc72b7f2a718/checker/verified/Huffman.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.847967769904032, "lm_q2_score": 0.8397339656668287, "lm_q1q2_score": 0.7120673381791697}}
{"text": "theory Chapter12_2\nimports \"HOL-IMP.Hoare_Examples\"\nbegin\n\ntext{*\n\\section*{Chapter 12}\n\n\\setcounter{exercise}{1}\n\n\\exercise\nDefine @{text bsubst} and prove the Substitution Lemma:\n*}\n\nfun bsubst :: \"bexp \\<Rightarrow> aexp \\<Rightarrow> vname \\<Rightarrow> bexp\" where\n(* your definition/proof here *)\n\nlemma bsubstitution: \"bval (bsubst b a x) s = bval b (s[a/x])\"\n(* your definition/proof here *)\n\ntext{*\nThis may require a similar definition and proof for @{typ aexp}.\n\\endexercise\n\n\\exercise\nDefine a command @{text cmax} that stores the maximum of the values of the IMP variables\n@{text \"x\"} and @{text \"y\"} in the IMP variable @{text \"z\"} and prove that\n@{text cmax} satisfies its specification:\n*}\n\nabbreviation cmax :: com where\n(* your definition/proof here *)\n\nlemma \"\\<turnstile> {\\<lambda>s. True} cmax {\\<lambda>s. s ''z'' = max (s ''x'') (s ''y'')}\"\n(* your definition/proof here *)\n\ntext{*\nFunction @{const max} is the predefined maximum function.\nProofs about @{const max} are often automatic when simplifying with @{thm[source] max_def}.\n\\endexercise\n\n\\exercise\\label{exe:Hoare:sumeq}\nDefine an equality operation for arithmetic expressions\n*}\n\n\ndefinition Eq :: \"aexp \\<Rightarrow> aexp \\<Rightarrow> bexp\" where\n(* your definition/proof here *)\n\ntext{* such that *}\n\nlemma bval_Eq[simp]: \"bval (Eq a1 a2) s = (aval a1 s = aval a2 s)\"\n(* your definition/proof here *)\n\ntext{* Prove the following variant of the summation command correct: *}\n\nlemma\n  \"\\<turnstile> {\\<lambda>s. s ''x'' = i \\<and> 0 \\<le> i}\n     ''y'' ::= N 0;;\n     WHILE Not(Eq (V ''x'') (N 0))\n     DO (''y'' ::= Plus (V ''y'') (V ''x'');;\n           ''x'' ::= Plus (V ''x'') (N (-1)))\n     {\\<lambda>s. s ''y'' = sum i}\"\n(* your definition/proof here *)\n\ntext{*\n\\endexercise\n\n\\exercise\nProve that the following command computes @{prop\"y - x\"} if @{prop\"(0::nat) \\<le> x\"}:\n*}\n\nlemma\n  \"\\<turnstile> {\\<lambda>s. s ''x'' = x \\<and> s ''y'' = y \\<and> 0 \\<le> x}\n     WHILE Less (N 0) (V ''x'')\n     DO (''x'' ::= Plus (V ''x'') (N (-1));; ''y'' ::= Plus (V ''y'') (N (-1)))\n     {\\<lambda>t. t ''y'' = y - x}\"\n(* your definition/proof here *)\n\ntext{*\n\\endexercise\n\n\\exercise\\label{exe:Hoare:mult}\nDefine and verify a command @{text cmult} that stores the product of\n@{text \"x\"} and @{text \"y\"} in @{text \"z\"} assuming @{prop\"(0::int)\\<le>y\"}:\n*}\n\nabbreviation cmult :: com where\n(* your definition/proof here *)\n\nlemma\n  \"\\<turnstile> {\\<lambda>s.  s ''x'' = x \\<and> s ''y'' = y \\<and> 0 \\<le> y} cmult {\\<lambda>t. t ''z'' = x*y}\"\n(* your definition/proof here *)\n\ntext{*\nYou may have to simplify with @{thm[source] algebra_simps} to deal with ``@{text\"*\"}''.\n\\endexercise\n\n\\exercise\\label{exe:Hoare:sqrt}\nThe following command computes an integer approximation @{text r} of the square root\nof @{text \"i \\<ge> 0\"}, i.e.\\ @{text\"r\\<^sup>2 \\<le> i < (r+1)\\<^sup>2\"}. Prove\n*}\n\nlemma\n  \"\\<turnstile> { \\<lambda>s. s ''x'' = i \\<and> 0 \\<le> i}\n     ''r'' ::= N 0;; ''r2'' ::= N 1;;\n     WHILE (Not (Less (V ''x'') (V ''r2'')))\n     DO (''r'' ::= Plus (V ''r'') (N 1);;\n            ''r2'' ::= Plus (V ''r2'') (Plus (Plus (V ''r'') (V ''r'')) (N 1)))\n     {\\<lambda>s. (s ''r'')^2 \\<le> i \\<and> i < (s ''r'' + 1)^2}\"\n(* your definition/proof here *)\n\ntext{*\nFigure out how @{text r2} is related to @{text r} before\nformulating the invariant.\nThe proof may require simplification with @{thm[source] algebra_simps}\nand @{thm[source] power2_eq_square}.\n\\endexercise\n\n\\exercise\nProve by induction:\n*}\n\nlemma \"\\<turnstile> {P} c {\\<lambda>s. True}\"\n(* your definition/proof here *)\n\ntext{*\n\\endexercise\n\n\\exercise\\label{exe:fwdassign}\nDesign and prove correct a forward assignment rule of the form\n\\ \\mbox{@{text\"\\<turnstile> {P} x ::= a {?}\"}} \\\nwhere @{text\"?\"} is some suitable postcondition that depends on @{text P},\n@{text x} and @{text a}. Hint: @{text\"?\"} may need @{text\"\\<exists>\"}.\n*}\n\nlemma \"\\<turnstile> {P} x ::= a {Questionmark}\"\n(* your definition/proof here *)\ntext{*\n(In case you wonder if your @{text Questionmark} is strong enough: see Exercise~\\ref{exe:sp})\n\\endexercise\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/Chapter12_2.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8397339797047029, "lm_q2_score": 0.8479677545357568, "lm_q1q2_score": 0.7120673371775716}}
{"text": "(*  Title:      HOL/Library/Order_Continuity.thy\n    Author:     David von Oheimb, TU M\u00fcnchen\n    Author:     Johannes H\u00f6lzl, TU M\u00fcnchen\n*)\n\nsection \\<open>Continuity and iterations\\<close>\n\ntheory Order_Continuity\nimports Complex_Main Countable_Complete_Lattices\nbegin\n\n(* TODO: Generalize theory to chain-complete partial orders *)\n\nlemma SUP_nat_binary:\n  \"(SUP n::nat. if n = 0 then A else B) = (sup A B::'a::countable_complete_lattice)\"\n  apply (auto intro!: antisym ccSUP_least)\n  apply (rule ccSUP_upper2[where i=0])\n  apply simp_all\n  apply (rule ccSUP_upper2[where i=1])\n  apply simp_all\n  done\n\nlemma INF_nat_binary:\n  \"(INF n::nat. if n = 0 then A else B) = (inf A B::'a::countable_complete_lattice)\"\n  apply (auto intro!: antisym ccINF_greatest)\n  apply (rule ccINF_lower2[where i=0])\n  apply simp_all\n  apply (rule ccINF_lower2[where i=1])\n  apply simp_all\n  done\n\ntext \\<open>\n  The name \\<open>continuous\\<close> is already taken in \\<open>Complex_Main\\<close>, so we use\n  \\<open>sup_continuous\\<close> and \\<open>inf_continuous\\<close>. These names appear sometimes in literature\n  and have the advantage that these names are duals.\n\\<close>\n\nnamed_theorems order_continuous_intros\n\nsubsection \\<open>Continuity for complete lattices\\<close>\n\ndefinition\n  sup_continuous :: \"('a::countable_complete_lattice \\<Rightarrow> 'b::countable_complete_lattice) \\<Rightarrow> bool\"\nwhere\n  \"sup_continuous F \\<longleftrightarrow> (\\<forall>M::nat \\<Rightarrow> 'a. mono M \\<longrightarrow> F (SUP i. M i) = (SUP i. F (M i)))\"\n\nlemma sup_continuousD: \"sup_continuous F \\<Longrightarrow> mono M \\<Longrightarrow> F (SUP i::nat. M i) = (SUP i. F (M i))\"\n  by (auto simp: sup_continuous_def)\n\nlemma sup_continuous_mono:\n  assumes [simp]: \"sup_continuous F\" shows \"mono F\"\nproof\n  fix A B :: \"'a\" assume [simp]: \"A \\<le> B\"\n  have \"F B = F (SUP n::nat. if n = 0 then A else B)\"\n    by (simp add: sup_absorb2 SUP_nat_binary)\n  also have \"\\<dots> = (SUP n::nat. if n = 0 then F A else F B)\"\n    by (auto simp: sup_continuousD mono_def intro!: SUP_cong)\n  finally show \"F A \\<le> F B\"\n    by (simp add: SUP_nat_binary le_iff_sup)\nqed\n\nlemma [order_continuous_intros]:\n  shows sup_continuous_const: \"sup_continuous (\\<lambda>x. c)\"\n    and sup_continuous_id: \"sup_continuous (\\<lambda>x. x)\"\n    and sup_continuous_apply: \"sup_continuous (\\<lambda>f. f x)\"\n    and sup_continuous_fun: \"(\\<And>s. sup_continuous (\\<lambda>x. P x s)) \\<Longrightarrow> sup_continuous P\"\n    and sup_continuous_If: \"sup_continuous F \\<Longrightarrow> sup_continuous G \\<Longrightarrow> sup_continuous (\\<lambda>f. if C then F f else G f)\"\n  by (auto simp: sup_continuous_def)\n\nlemma sup_continuous_compose:\n  assumes f: \"sup_continuous f\" and g: \"sup_continuous g\"\n  shows \"sup_continuous (\\<lambda>x. f (g x))\"\n  unfolding sup_continuous_def\nproof safe\n  fix M :: \"nat \\<Rightarrow> 'c\"\n  assume M: \"mono M\"\n  then have \"mono (\\<lambda>i. g (M i))\"\n    using sup_continuous_mono[OF g] by (auto simp: mono_def)\n  with M show \"f (g (SUPREMUM UNIV M)) = (SUP i. f (g (M i)))\"\n    by (auto simp: sup_continuous_def g[THEN sup_continuousD] f[THEN sup_continuousD])\nqed\n\nlemma sup_continuous_sup[order_continuous_intros]:\n  \"sup_continuous f \\<Longrightarrow> sup_continuous g \\<Longrightarrow> sup_continuous (\\<lambda>x. sup (f x) (g x))\"\n  by (simp add: sup_continuous_def ccSUP_sup_distrib)\n\nlemma sup_continuous_inf[order_continuous_intros]:\n  fixes P Q :: \"'a :: countable_complete_lattice \\<Rightarrow> 'b :: countable_complete_distrib_lattice\"\n  assumes P: \"sup_continuous P\" and Q: \"sup_continuous Q\"\n  shows \"sup_continuous (\\<lambda>x. inf (P x) (Q x))\"\n  unfolding sup_continuous_def\nproof (safe intro!: antisym)\n  fix M :: \"nat \\<Rightarrow> 'a\" assume M: \"incseq M\"\n  have \"inf (P (SUP i. M i)) (Q (SUP i. M i)) \\<le> (SUP j i. inf (P (M i)) (Q (M j)))\"\n    by (simp add: sup_continuousD[OF P M] sup_continuousD[OF Q M] inf_ccSUP ccSUP_inf)\n  also have \"\\<dots> \\<le> (SUP i. inf (P (M i)) (Q (M i)))\"\n  proof (intro ccSUP_least)\n    fix i j from M assms[THEN sup_continuous_mono] show \"inf (P (M i)) (Q (M j)) \\<le> (SUP i. inf (P (M i)) (Q (M i)))\"\n      by (intro ccSUP_upper2[of _ \"sup i j\"] inf_mono) (auto simp: mono_def)\n  qed auto\n  finally show \"inf (P (SUP i. M i)) (Q (SUP i. M i)) \\<le> (SUP i. inf (P (M i)) (Q (M i)))\" .\n\n  show \"(SUP i. inf (P (M i)) (Q (M i))) \\<le> inf (P (SUP i. M i)) (Q (SUP i. M i))\"\n    unfolding sup_continuousD[OF P M] sup_continuousD[OF Q M] by (intro ccSUP_least inf_mono ccSUP_upper) auto\nqed\n\nlemma sup_continuous_and[order_continuous_intros]:\n  \"sup_continuous P \\<Longrightarrow> sup_continuous Q \\<Longrightarrow> sup_continuous (\\<lambda>x. P x \\<and> Q x)\"\n  using sup_continuous_inf[of P Q] by simp\n\nlemma sup_continuous_or[order_continuous_intros]:\n  \"sup_continuous P \\<Longrightarrow> sup_continuous Q \\<Longrightarrow> sup_continuous (\\<lambda>x. P x \\<or> Q x)\"\n  by (auto simp: sup_continuous_def)\n\nlemma sup_continuous_lfp:\n  assumes \"sup_continuous F\" shows \"lfp F = (SUP i. (F ^^ i) bot)\" (is \"lfp F = ?U\")\nproof (rule antisym)\n  note mono = sup_continuous_mono[OF \\<open>sup_continuous F\\<close>]\n  show \"?U \\<le> lfp F\"\n  proof (rule SUP_least)\n    fix i show \"(F ^^ i) bot \\<le> lfp F\"\n    proof (induct i)\n      case (Suc i)\n      have \"(F ^^ Suc i) bot = F ((F ^^ i) bot)\" by simp\n      also have \"\\<dots> \\<le> F (lfp F)\" by (rule monoD[OF mono Suc])\n      also have \"\\<dots> = lfp F\" by (simp add: lfp_fixpoint[OF mono])\n      finally show ?case .\n    qed simp\n  qed\n  show \"lfp F \\<le> ?U\"\n  proof (rule lfp_lowerbound)\n    have \"mono (\\<lambda>i::nat. (F ^^ i) bot)\"\n    proof -\n      { fix i::nat have \"(F ^^ i) bot \\<le> (F ^^ (Suc i)) bot\"\n        proof (induct i)\n          case 0 show ?case by simp\n        next\n          case Suc thus ?case using monoD[OF mono Suc] by auto\n        qed }\n      thus ?thesis by (auto simp add: mono_iff_le_Suc)\n    qed\n    hence \"F ?U = (SUP i. (F ^^ Suc i) bot)\"\n      using \\<open>sup_continuous F\\<close> by (simp add: sup_continuous_def)\n    also have \"\\<dots> \\<le> ?U\"\n      by (fast intro: SUP_least SUP_upper)\n    finally show \"F ?U \\<le> ?U\" .\n  qed\nqed\n\nlemma lfp_transfer_bounded:\n  assumes P: \"P bot\" \"\\<And>x. P x \\<Longrightarrow> P (f x)\" \"\\<And>M. (\\<And>i. P (M i)) \\<Longrightarrow> P (SUP i::nat. M i)\"\n  assumes \\<alpha>: \"\\<And>M. mono M \\<Longrightarrow> (\\<And>i::nat. P (M i)) \\<Longrightarrow> \\<alpha> (SUP i. M i) = (SUP i. \\<alpha> (M i))\"\n  assumes f: \"sup_continuous f\" and g: \"sup_continuous g\"\n  assumes [simp]: \"\\<And>x. P x \\<Longrightarrow> x \\<le> lfp f \\<Longrightarrow> \\<alpha> (f x) = g (\\<alpha> x)\"\n  assumes g_bound: \"\\<And>x. \\<alpha> bot \\<le> g x\"\n  shows \"\\<alpha> (lfp f) = lfp g\"\nproof (rule antisym)\n  note mono_g = sup_continuous_mono[OF g]\n  note mono_f = sup_continuous_mono[OF f]\n  have lfp_bound: \"\\<alpha> bot \\<le> lfp g\"\n    by (subst lfp_unfold[OF mono_g]) (rule g_bound)\n\n  have P_pow: \"P ((f ^^ i) bot)\" for i\n    by (induction i) (auto intro!: P)\n  have incseq_pow: \"mono (\\<lambda>i. (f ^^ i) bot)\"\n    unfolding mono_iff_le_Suc\n  proof\n    fix i show \"(f ^^ i) bot \\<le> (f ^^ (Suc i)) bot\"\n    proof (induct i)\n      case Suc thus ?case using monoD[OF sup_continuous_mono[OF f] Suc] by auto\n    qed (simp add: le_fun_def)\n  qed\n  have P_lfp: \"P (lfp f)\"\n    using P_pow unfolding sup_continuous_lfp[OF f] by (auto intro!: P)\n\n  have iter_le_lfp: \"(f ^^ n) bot \\<le> lfp f\" for n\n    apply (induction n)\n    apply simp\n    apply (subst lfp_unfold[OF mono_f])\n    apply (auto intro!: monoD[OF mono_f])\n    done\n\n  have \"\\<alpha> (lfp f) = (SUP i. \\<alpha> ((f^^i) bot))\"\n    unfolding sup_continuous_lfp[OF f] using incseq_pow P_pow by (rule \\<alpha>)\n  also have \"\\<dots> \\<le> lfp g\"\n  proof (rule SUP_least)\n    fix i show \"\\<alpha> ((f^^i) bot) \\<le> lfp g\"\n    proof (induction i)\n      case (Suc n) then show ?case\n        by (subst lfp_unfold[OF mono_g]) (simp add: monoD[OF mono_g] P_pow iter_le_lfp)\n    qed (simp add: lfp_bound)\n  qed\n  finally show \"\\<alpha> (lfp f) \\<le> lfp g\" .\n\n  show \"lfp g \\<le> \\<alpha> (lfp f)\"\n  proof (induction rule: lfp_ordinal_induct[OF mono_g])\n    case (1 S) then show ?case\n      by (subst lfp_unfold[OF sup_continuous_mono[OF f]])\n         (simp add: monoD[OF mono_g] P_lfp)\n  qed (auto intro: Sup_least)\nqed\n\nlemma lfp_transfer:\n  \"sup_continuous \\<alpha> \\<Longrightarrow> sup_continuous f \\<Longrightarrow> sup_continuous g \\<Longrightarrow>\n    (\\<And>x. \\<alpha> bot \\<le> g x) \\<Longrightarrow> (\\<And>x. x \\<le> lfp f \\<Longrightarrow> \\<alpha> (f x) = g (\\<alpha> x)) \\<Longrightarrow> \\<alpha> (lfp f) = lfp g\"\n  by (rule lfp_transfer_bounded[where P=top]) (auto dest: sup_continuousD)\n\ndefinition\n  inf_continuous :: \"('a::countable_complete_lattice \\<Rightarrow> 'b::countable_complete_lattice) \\<Rightarrow> bool\"\nwhere\n  \"inf_continuous F \\<longleftrightarrow> (\\<forall>M::nat \\<Rightarrow> 'a. antimono M \\<longrightarrow> F (INF i. M i) = (INF i. F (M i)))\"\n\nlemma inf_continuousD: \"inf_continuous F \\<Longrightarrow> antimono M \\<Longrightarrow> F (INF i::nat. M i) = (INF i. F (M i))\"\n  by (auto simp: inf_continuous_def)\n\nlemma inf_continuous_mono:\n  assumes [simp]: \"inf_continuous F\" shows \"mono F\"\nproof\n  fix A B :: \"'a\" assume [simp]: \"A \\<le> B\"\n  have \"F A = F (INF n::nat. if n = 0 then B else A)\"\n    by (simp add: inf_absorb2 INF_nat_binary)\n  also have \"\\<dots> = (INF n::nat. if n = 0 then F B else F A)\"\n    by (auto simp: inf_continuousD antimono_def intro!: INF_cong)\n  finally show \"F A \\<le> F B\"\n    by (simp add: INF_nat_binary le_iff_inf inf_commute)\nqed\n\nlemma [order_continuous_intros]:\n  shows inf_continuous_const: \"inf_continuous (\\<lambda>x. c)\"\n    and inf_continuous_id: \"inf_continuous (\\<lambda>x. x)\"\n    and inf_continuous_apply: \"inf_continuous (\\<lambda>f. f x)\"\n    and inf_continuous_fun: \"(\\<And>s. inf_continuous (\\<lambda>x. P x s)) \\<Longrightarrow> inf_continuous P\"\n    and inf_continuous_If: \"inf_continuous F \\<Longrightarrow> inf_continuous G \\<Longrightarrow> inf_continuous (\\<lambda>f. if C then F f else G f)\"\n  by (auto simp: inf_continuous_def)\n\nlemma inf_continuous_inf[order_continuous_intros]:\n  \"inf_continuous f \\<Longrightarrow> inf_continuous g \\<Longrightarrow> inf_continuous (\\<lambda>x. inf (f x) (g x))\"\n  by (simp add: inf_continuous_def ccINF_inf_distrib)\n\nlemma inf_continuous_sup[order_continuous_intros]:\n  fixes P Q :: \"'a :: countable_complete_lattice \\<Rightarrow> 'b :: countable_complete_distrib_lattice\"\n  assumes P: \"inf_continuous P\" and Q: \"inf_continuous Q\"\n  shows \"inf_continuous (\\<lambda>x. sup (P x) (Q x))\"\n  unfolding inf_continuous_def\nproof (safe intro!: antisym)\n  fix M :: \"nat \\<Rightarrow> 'a\" assume M: \"decseq M\"\n  show \"sup (P (INF i. M i)) (Q (INF i. M i)) \\<le> (INF i. sup (P (M i)) (Q (M i)))\"\n    unfolding inf_continuousD[OF P M] inf_continuousD[OF Q M] by (intro ccINF_greatest sup_mono ccINF_lower) auto\n\n  have \"(INF i. sup (P (M i)) (Q (M i))) \\<le> (INF j i. sup (P (M i)) (Q (M j)))\"\n  proof (intro ccINF_greatest)\n    fix i j from M assms[THEN inf_continuous_mono] show \"sup (P (M i)) (Q (M j)) \\<ge> (INF i. sup (P (M i)) (Q (M i)))\"\n      by (intro ccINF_lower2[of _ \"sup i j\"] sup_mono) (auto simp: mono_def antimono_def)\n  qed auto\n  also have \"\\<dots> \\<le> sup (P (INF i. M i)) (Q (INF i. M i))\"\n    by (simp add: inf_continuousD[OF P M] inf_continuousD[OF Q M] ccINF_sup sup_ccINF)\n  finally show \"sup (P (INF i. M i)) (Q (INF i. M i)) \\<ge> (INF i. sup (P (M i)) (Q (M i)))\" .\nqed\n\nlemma inf_continuous_and[order_continuous_intros]:\n  \"inf_continuous P \\<Longrightarrow> inf_continuous Q \\<Longrightarrow> inf_continuous (\\<lambda>x. P x \\<and> Q x)\"\n  using inf_continuous_inf[of P Q] by simp\n\nlemma inf_continuous_or[order_continuous_intros]:\n  \"inf_continuous P \\<Longrightarrow> inf_continuous Q \\<Longrightarrow> inf_continuous (\\<lambda>x. P x \\<or> Q x)\"\n  using inf_continuous_sup[of P Q] by simp\n\nlemma inf_continuous_compose:\n  assumes f: \"inf_continuous f\" and g: \"inf_continuous g\"\n  shows \"inf_continuous (\\<lambda>x. f (g x))\"\n  unfolding inf_continuous_def\nproof safe\n  fix M :: \"nat \\<Rightarrow> 'c\"\n  assume M: \"antimono M\"\n  then have \"antimono (\\<lambda>i. g (M i))\"\n    using inf_continuous_mono[OF g] by (auto simp: mono_def antimono_def)\n  with M show \"f (g (INFIMUM UNIV M)) = (INF i. f (g (M i)))\"\n    by (auto simp: inf_continuous_def g[THEN inf_continuousD] f[THEN inf_continuousD])\nqed\n\nlemma inf_continuous_gfp:\n  assumes \"inf_continuous F\" shows \"gfp F = (INF i. (F ^^ i) top)\" (is \"gfp F = ?U\")\nproof (rule antisym)\n  note mono = inf_continuous_mono[OF \\<open>inf_continuous F\\<close>]\n  show \"gfp F \\<le> ?U\"\n  proof (rule INF_greatest)\n    fix i show \"gfp F \\<le> (F ^^ i) top\"\n    proof (induct i)\n      case (Suc i)\n      have \"gfp F = F (gfp F)\" by (simp add: gfp_fixpoint[OF mono])\n      also have \"\\<dots> \\<le> F ((F ^^ i) top)\" by (rule monoD[OF mono Suc])\n      also have \"\\<dots> = (F ^^ Suc i) top\" by simp\n      finally show ?case .\n    qed simp\n  qed\n  show \"?U \\<le> gfp F\"\n  proof (rule gfp_upperbound)\n    have *: \"antimono (\\<lambda>i::nat. (F ^^ i) top)\"\n    proof -\n      { fix i::nat have \"(F ^^ Suc i) top \\<le> (F ^^ i) top\"\n        proof (induct i)\n          case 0 show ?case by simp\n        next\n          case Suc thus ?case using monoD[OF mono Suc] by auto\n        qed }\n      thus ?thesis by (auto simp add: antimono_iff_le_Suc)\n    qed\n    have \"?U \\<le> (INF i. (F ^^ Suc i) top)\"\n      by (fast intro: INF_greatest INF_lower)\n    also have \"\\<dots> \\<le> F ?U\"\n      by (simp add: inf_continuousD \\<open>inf_continuous F\\<close> *)\n    finally show \"?U \\<le> F ?U\" .\n  qed\nqed\n\nlemma gfp_transfer:\n  assumes \\<alpha>: \"inf_continuous \\<alpha>\" and f: \"inf_continuous f\" and g: \"inf_continuous g\"\n  assumes [simp]: \"\\<alpha> top = top\" \"\\<And>x. \\<alpha> (f x) = g (\\<alpha> x)\"\n  shows \"\\<alpha> (gfp f) = gfp g\"\nproof -\n  have \"\\<alpha> (gfp f) = (INF i. \\<alpha> ((f^^i) top))\"\n    unfolding inf_continuous_gfp[OF f] by (intro f \\<alpha> inf_continuousD antimono_funpow inf_continuous_mono)\n  moreover have \"\\<alpha> ((f^^i) top) = (g^^i) top\" for i\n    by (induction i; simp)\n  ultimately show ?thesis\n    unfolding inf_continuous_gfp[OF g] by simp\nqed\n\nlemma gfp_transfer_bounded:\n  assumes P: \"P (f top)\" \"\\<And>x. P x \\<Longrightarrow> P (f x)\" \"\\<And>M. antimono M \\<Longrightarrow> (\\<And>i. P (M i)) \\<Longrightarrow> P (INF i::nat. M i)\"\n  assumes \\<alpha>: \"\\<And>M. antimono M \\<Longrightarrow> (\\<And>i::nat. P (M i)) \\<Longrightarrow> \\<alpha> (INF i. M i) = (INF i. \\<alpha> (M i))\"\n  assumes f: \"inf_continuous f\" and g: \"inf_continuous g\"\n  assumes [simp]: \"\\<And>x. P x \\<Longrightarrow> \\<alpha> (f x) = g (\\<alpha> x)\"\n  assumes g_bound: \"\\<And>x. g x \\<le> \\<alpha> (f top)\"\n  shows \"\\<alpha> (gfp f) = gfp g\"\nproof (rule antisym)\n  note mono_g = inf_continuous_mono[OF g]\n\n  have P_pow: \"P ((f ^^ i) (f top))\" for i\n    by (induction i) (auto intro!: P)\n\n  have antimono_pow: \"antimono (\\<lambda>i. (f ^^ i) top)\"\n    unfolding antimono_iff_le_Suc\n  proof\n    fix i show \"(f ^^ Suc i) top \\<le> (f ^^ i) top\"\n    proof (induct i)\n      case Suc thus ?case using monoD[OF inf_continuous_mono[OF f] Suc] by auto\n    qed (simp add: le_fun_def)\n  qed\n  have antimono_pow2: \"antimono (\\<lambda>i. (f ^^ i) (f top))\"\n  proof\n    show \"x \\<le> y \\<Longrightarrow> (f ^^ y) (f top) \\<le> (f ^^ x) (f top)\" for x y\n      using antimono_pow[THEN antimonoD, of \"Suc x\" \"Suc y\"]\n      unfolding funpow_Suc_right by simp\n  qed\n\n  have gfp_f: \"gfp f = (INF i. (f ^^ i) (f top))\"\n    unfolding inf_continuous_gfp[OF f]\n  proof (rule INF_eq)\n    show \"\\<exists>j\\<in>UNIV. (f ^^ j) (f top) \\<le> (f ^^ i) top\" for i\n      by (intro bexI[of _ \"i - 1\"]) (auto simp: diff_Suc funpow_Suc_right simp del: funpow.simps(2) split: nat.split)\n    show \"\\<exists>j\\<in>UNIV. (f ^^ j) top \\<le> (f ^^ i) (f top)\" for i\n      by (intro bexI[of _ \"Suc i\"]) (auto simp: funpow_Suc_right simp del: funpow.simps(2))\n  qed\n\n  have P_lfp: \"P (gfp f)\"\n    unfolding gfp_f by (auto intro!: P P_pow antimono_pow2)\n\n  have \"\\<alpha> (gfp f) = (INF i. \\<alpha> ((f^^i) (f top)))\"\n    unfolding gfp_f by (rule \\<alpha>) (auto intro!: P_pow antimono_pow2)\n  also have \"\\<dots> \\<ge> gfp g\"\n  proof (rule INF_greatest)\n    fix i show \"gfp g \\<le> \\<alpha> ((f^^i) (f top))\"\n    proof (induction i)\n      case (Suc n) then show ?case\n        by (subst gfp_unfold[OF mono_g]) (simp add: monoD[OF mono_g] P_pow)\n    next\n      case 0\n      have \"gfp g \\<le> \\<alpha> (f top)\"\n        by (subst gfp_unfold[OF mono_g]) (rule g_bound)\n      then show ?case\n        by simp\n    qed\n  qed\n  finally show \"gfp g \\<le> \\<alpha> (gfp f)\" .\n\n  show \"\\<alpha> (gfp f) \\<le> gfp g\"\n  proof (induction rule: gfp_ordinal_induct[OF mono_g])\n    case (1 S) then show ?case\n      by (subst gfp_unfold[OF inf_continuous_mono[OF f]])\n         (simp add: monoD[OF mono_g] P_lfp)\n  qed (auto intro: Inf_greatest)\nqed\n\nsubsubsection \\<open>Least fixed points in countable complete lattices\\<close>\n\ndefinition (in countable_complete_lattice) cclfp :: \"('a \\<Rightarrow> 'a) \\<Rightarrow> 'a\"\n  where \"cclfp f = (SUP i. (f ^^ i) bot)\"\n\nlemma cclfp_unfold:\n  assumes \"sup_continuous F\" shows \"cclfp F = F (cclfp F)\"\nproof -\n  have \"cclfp F = (SUP i. F ((F ^^ i) bot))\"\n    unfolding cclfp_def by (subst UNIV_nat_eq) auto\n  also have \"\\<dots> = F (cclfp F)\"\n    unfolding cclfp_def\n    by (intro sup_continuousD[symmetric] assms mono_funpow sup_continuous_mono)\n  finally show ?thesis .\nqed\n\nlemma cclfp_lowerbound: assumes f: \"mono f\" and A: \"f A \\<le> A\" shows \"cclfp f \\<le> A\"\n  unfolding cclfp_def\nproof (intro ccSUP_least)\n  fix i show \"(f ^^ i) bot \\<le> A\"\n  proof (induction i)\n    case (Suc i) from monoD[OF f this] A show ?case\n      by auto\n  qed simp\nqed simp\n\nlemma cclfp_transfer:\n  assumes \"sup_continuous \\<alpha>\" \"mono f\"\n  assumes \"\\<alpha> bot = bot\" \"\\<And>x. \\<alpha> (f x) = g (\\<alpha> x)\"\n  shows \"\\<alpha> (cclfp f) = cclfp g\"\nproof -\n  have \"\\<alpha> (cclfp f) = (SUP i. \\<alpha> ((f ^^ i) bot))\"\n    unfolding cclfp_def by (intro sup_continuousD assms mono_funpow sup_continuous_mono)\n  moreover have \"\\<alpha> ((f ^^ i) bot) = (g ^^ i) bot\" for i\n    by (induction i) (simp_all add: assms)\n  ultimately show ?thesis\n    by (simp add: cclfp_def)\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/Order_Continuity.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8479677622198947, "lm_q2_score": 0.8397339676722393, "lm_q1q2_score": 0.7120673334270621}}
{"text": "theory Chap3_2\nimports Main Chap3_1\nbegin\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 b) s = b\"\n| \"bval (Not e) s = (\\<not>bval e s)\"\n| \"bval (And e1 e2) s = (bval e1 s \\<and> bval e2 s)\"\n| \"bval (Less e1 e2) s = (aval e1 s < aval e2 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 e) = not (bsimp e)\"\n| \"bsimp (And e1 e2) = and (bsimp e1) (bsimp e2)\"\n| \"bsimp (Less e1 e2) = less (asimp e1) (asimp e2)\"\n\nfun Eq :: \"aexp \\<Rightarrow> aexp \\<Rightarrow> bexp\" where\n\"Eq a1 a2 = And (Not (Less a1 a2)) (Not (Less a2 a1))\"\n\nlemma \"bval (Eq a1 a2) s = (aval a1 s = aval a2 s)\"\n  by auto\n\nfun Le :: \"aexp \\<Rightarrow> aexp \\<Rightarrow> bexp\" where\n\"Le a1 a2 = Not (Less a2 a1)\"\n\nlemma \"bval (Le a1 a2) s = (aval a1 s \\<le> aval a2 s)\"\n  by auto\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 e1 e2 e3) s = (if ifval e1 s then ifval e2 s else ifval e3 s)\"\n| \"ifval (Less2 e1 e2) s = (aval e1 s < aval e2 s)\"\n\nfun b2ifexp :: \"bexp \\<Rightarrow> ifexp\" where\n\"b2ifexp (Bc b) = Bc2 b\"\n| \"b2ifexp (Not e) = If (b2ifexp e) (Bc2 False) (Bc2 True)\"\n| \"b2ifexp (And e1 e2) = If (b2ifexp e1) (b2ifexp e2) (Bc2 False)\"\n| \"b2ifexp (Less e1 e2) = Less2 e1 e2\"\n\ndefinition Implies :: \"bexp \\<Rightarrow> bexp \\<Rightarrow> bexp\" where\n\"Implies e1 e2 = Not (And e1 (Not e2))\"\n\nfun if2bexp :: \"ifexp \\<Rightarrow> bexp\" where\n\"if2bexp (Bc2 b) = Bc b\"\n| \"if2bexp (If e1 e2 e3) = \n    And (Implies (if2bexp e1) (if2bexp e2)) (Implies (Not (if2bexp e1)) (if2bexp e3))\"\n| \"if2bexp (Less2 e1 e2) = Less e1 e2\"\n\nlemma \"bval (if2bexp e) s = ifval e s\"\n  apply (induction e)\n  by (auto simp add: Implies_def)\n\nlemma \"ifval (b2ifexp e) s = bval e s\"\n  apply (induction e)\n  by auto\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 _) = True\"\n| \"is_nnf (NOT (VAR _)) = True\"\n| \"is_nnf (NOT _) = False\"\n| \"is_nnf (AND e1 e2) = (is_nnf e1 \\<and> is_nnf e2)\"\n| \"is_nnf (OR e1 e2) = (is_nnf e1 \\<and> is_nnf e2)\"\n\nfun nnf :: \"pbexp \\<Rightarrow> pbexp\" where\n\"nnf (VAR x) = VAR x\"\n| \"nnf (AND e1 e2) = AND (nnf e1) (nnf e2)\"\n| \"nnf (OR e1 e2) = OR (nnf e1) (nnf e2)\"\n| \"nnf (NOT (VAR x)) = NOT (VAR x)\"\n| \"nnf (NOT (NOT e)) = nnf e\"\n| \"nnf (NOT (AND e1 e2)) = OR (nnf (NOT e1)) (nnf (NOT e2))\"\n| \"nnf (NOT (OR e1 e2)) = AND (nnf (NOT e1)) (nnf (NOT e2))\"\n\nlemma \"pbval (nnf e) s = pbval e s\"\n  apply (induction e rule: nnf.induct)\n  by auto\n\nlemma \"is_nnf (nnf e)\"\n  apply (induction e rule: nnf.induct)\n  by auto\n\nfun without_OR :: \"pbexp \\<Rightarrow> bool\" where\n\"without_OR (VAR _) = True\"\n| \"without_OR (NOT e) = without_OR e\"\n| \"without_OR (AND e1 e2) = (without_OR e1 \\<and> without_OR e2)\"\n| \"without_OR (OR _ _) = False\"\n\nfun is_dnf_helper :: \"pbexp \\<Rightarrow> bool\" where\n\"is_dnf_helper (VAR _) = True\"\n| \"is_dnf_helper (NOT e) = is_dnf_helper e\"\n| \"is_dnf_helper (AND e1 e2) = without_OR (AND e1 e2)\"\n| \"is_dnf_helper (OR e1 e2) = (is_dnf_helper e1 \\<and> is_dnf_helper e2)\"\n\ndefinition is_dnf :: \"pbexp \\<Rightarrow> bool\" where\n\"is_dnf e = (is_nnf e \\<and> is_dnf_helper e)\"\n\nlemma \"(P \\<or> Q) \\<and> (R \\<or> S)\"\n  apply (subst conj_disj_distribL)\n  apply (subst (1 2) conj_disj_distribR)\n  oops\n\nfun dnfify :: \"pbexp \\<Rightarrow> pbexp \\<Rightarrow> pbexp\" where\n\"dnfify (OR e1 e2) e = OR (dnfify e1 e) (dnfify e2 e)\"\n| \"dnfify e (OR e1 e2) = OR (dnfify e e1) (dnfify e e2)\"\n| \"dnfify e1 e2 = AND e1 e2\"\n\nfun dnf_of_nnf :: \"pbexp \\<Rightarrow> pbexp\" where\n\"dnf_of_nnf (VAR x) = VAR x\"\n| \"dnf_of_nnf (NOT e) = NOT e\"\n| \"dnf_of_nnf (OR e1 e2) = OR (dnf_of_nnf e1) (dnf_of_nnf e2)\"\n| \"dnf_of_nnf (AND e1 e2) = dnfify (dnf_of_nnf e1) (dnf_of_nnf e2)\"\n\nlemma dnfify_and: \"pbval (dnfify e1 e2) s = (pbval e1 s \\<and> pbval e2 s)\"\n  apply (induction rule: dnfify.induct)\n  by auto\n\nlemma \"pbval (dnf_of_nnf b) s = pbval b s\"\n  apply (induction b rule: dnf_of_nnf.induct)\n     apply simp+\n  using dnfify_and by blast\n\nlemma dnfify_nnf: \"\\<lbrakk> is_nnf e1; is_nnf e2 \\<rbrakk> \\<Longrightarrow> is_nnf (dnfify e1 e2)\"\n  apply (induction e1 e2 rule: dnfify.induct)\n  by auto\n\nlemma dnf_of_nnf_is_nnf: \"is_nnf b \\<Longrightarrow> is_nnf (dnf_of_nnf b)\"\n  apply (induction b)\n     apply simp_all\n  using dnfify_nnf by blast\n\nlemma dnfify_is_dnf_helper: \n\"\\<lbrakk> is_dnf e1; is_dnf e2 \\<rbrakk> \\<Longrightarrow> is_dnf_helper (dnfify e1 e2)\"\n  apply (induction e1 e2 rule: dnfify.induct)\n  unfolding is_dnf_def by (auto elim: is_nnf.elims)\n\nlemma dnf_of_nnf_is_dnf_helper: \"is_nnf b \\<Longrightarrow> is_dnf_helper (dnf_of_nnf b)\"\n  apply (induction b rule: dnf_of_nnf.induct)\n  using dnfify_is_dnf_helper dnf_of_nnf_is_nnf unfolding is_dnf_def \n  by (auto elim: is_nnf.elims)\n\nlemma \"is_nnf b \\<Longrightarrow> is_dnf (dnf_of_nnf b)\"\n  unfolding is_dnf_def apply safe\n  using dnf_of_nnf_is_nnf dnf_of_nnf_is_dnf_helper 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/Chap3_2.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952811593495, "lm_q2_score": 0.7931059609645724, "lm_q1q2_score": 0.7119674786172479}}
{"text": "(*  \n    Author:      Ren\u00e9 Thiemann \n                 Akihisa Yamada\n    License:     BSD\n*)\nsection \\<open>Jordan Normal Form\\<close>\n\ntext \\<open>This theory defines Jordan normal forms (JNFs) in a sparse representation, i.e., \n  as block-diagonal matrices. We also provide a closed formula for powers of JNFs, \n  which allows to estimate the growth rates of JNFs.\\<close>\n\ntheory Jordan_Normal_Form\nimports \n  Matrix\n  Char_Poly\n  Polynomial_Interpolation.Missing_Unsorted\nbegin\n\ndefinition jordan_block :: \"nat \\<Rightarrow> 'a :: {zero,one} \\<Rightarrow> 'a mat\" where \n  \"jordan_block n a = mat n n (\\<lambda> (i,j). if i = j then a else if Suc i = j then 1 else 0)\"\n\nlemma jordan_block_index[simp]: \"i < n \\<Longrightarrow> j < n \\<Longrightarrow> \n  jordan_block n a $$ (i,j) = (if i = j then a else if Suc i = j then 1 else 0)\"\n  \"dim_row (jordan_block n k) = n\"\n  \"dim_col (jordan_block n k) = n\"\n  unfolding jordan_block_def by auto\n\nlemma jordan_block_carrier[simp]: \"jordan_block n k \\<in> carrier_mat n n\" \n  unfolding carrier_mat_def by auto\n\nlemma jordan_block_char_poly: \"char_poly (jordan_block n a) = [: -a, 1:]^n\"\n  unfolding char_poly_defs by (subst det_upper_triangular[of _ n], auto simp: prod_list_diag_prod)\n\nlemma jordan_block_pow_carrier[simp]:\n  \"jordan_block n a ^\\<^sub>m r \\<in> carrier_mat n n\" by auto\nlemma jordan_block_pow_dim[simp]:\n  \"dim_row (jordan_block n a ^\\<^sub>m r) = n\" \"dim_col (jordan_block n a ^\\<^sub>m r) = n\" by auto\n\nlemma jordan_block_pow: \"(jordan_block n (a :: 'a :: comm_ring_1)) ^\\<^sub>m r = \n  mat n n (\\<lambda> (i,j). if i \\<le> j then of_nat (r choose (j - i)) * a ^ (r + i - j) else 0)\"\nproof (induct r)\n  case 0\n  {\n    fix i j :: nat\n    assume \"i \\<noteq> j\" \"i \\<le> j\"\n    hence \"j - i > 0\" by auto\n    hence \"0 choose (j - i) = 0\" by simp\n  } note [simp] = this\n  show ?case\n    by (simp, rule eq_matI, auto)\nnext\n  case (Suc r)\n  let ?jb = \"jordan_block n a\"\n  let ?rij = \"\\<lambda> r i j. of_nat (r choose (j - i)) * a ^ (r + i - j)\"\n  let ?v = \"\\<lambda> i j. if i \\<le> j then of_nat (r choose (j - i)) * a ^ (r + i - j) else 0\"\n  have \"?jb ^\\<^sub>m Suc r = mat n n (\\<lambda> (i,j). if i \\<le> j then ?rij r i j else 0) * ?jb\" by (simp add: Suc)\n  also have \"\\<dots> = mat n n (\\<lambda> (i,j). if i \\<le> j then ?rij (Suc r) i j else 0)\"\n  proof -\n    {\n      fix j\n      assume j: \"j < n\"\n      hence col: \"col (jordan_block n a) j = vec n (\\<lambda>i. if i = j then a else if Suc i = j then 1 else 0)\"\n        unfolding jordan_block_def col_mat[OF j] by simp\n      fix f\n      have \"vec n f \\<bullet> col (jordan_block n a) j = (f j * a + (if j = 0 then 0 else f (j - 1)))\"\n      proof -\n        define p where \"p = (\\<lambda> i. vec n f $ i * col (jordan_block n a) j $ i)\"\n        have \"vec n f \\<bullet> col (jordan_block n a) j = (\\<Sum>i = 0 ..< n. p i)\"\n          unfolding scalar_prod_def p_def by simp\n        also have \"\\<dots> = p j + sum p ({0 ..< n} - {j})\" using j\n          by (subst sum.remove[of _ j], auto)\n        also have \"p j = f j * a\" unfolding p_def col using j by auto\n        also have \"sum p ({0 ..< n} - {j}) = (if j = 0 then 0 else f (j - 1))\"\n        proof (cases j)\n          case 0\n          have \"sum p ({0 ..< n} - {j}) = 0\"\n            by (rule sum.neutral, auto simp: p_def col 0)\n          thus ?thesis using 0 by simp\n        next\n          case (Suc jj)\n          with j have jj: \"jj \\<in> {0 ..< n} - {j}\" by auto\n          have \"sum p ({0 ..< n} - {j}) = p jj + sum p ({0 ..< n} - {j} - {jj})\"\n            by (subst sum.remove[OF _ jj], auto)\n          also have \"p jj = f (j - 1)\" unfolding p_def col using jj\n            by (auto simp: Suc)\n          also have \"sum p ({0 ..< n} - {j} - {jj}) = 0\"\n            by (rule sum.neutral, auto simp: p_def col, auto simp: Suc)\n          finally show ?thesis unfolding Suc by simp\n        qed\n        finally show ?thesis .\n      qed\n    } note scalar_to_sum = this\n    {\n      fix i j\n      assume i: \"i < n\" and ij: \"i > j\"\n      hence j: \"j < n\" by auto\n      have \"vec n (?v i) \\<bullet> col (jordan_block n a) j = 0\"\n        unfolding scalar_to_sum[OF j] using ij i j by auto\n    } note easy_case = this\n    {\n      fix i j\n      assume j: \"j < n\" and ij: \"i \\<le> j\"\n      hence i: \"i < n\" and id: \"\\<And> p q. (if i \\<le> j then p else q) = p\" by auto\n      have \"vec n (?v i) \\<bullet> col (jordan_block n a) j =\n        (of_nat (r choose (j - i)) * (a ^ (Suc (r + i - j)))) +\n          (if j = 0 then 0\n         else if i \\<le> j - 1 then of_nat (r choose (j - 1 - i)) * a ^ (r + i - (j - 1)) else 0)\"\n      unfolding scalar_to_sum[OF j]\n      using ij by simp\n      also have \"\\<dots> = of_nat (Suc r choose (j - i)) * a ^ (Suc (r + i) - j)\"\n      proof (cases j)\n        case (Suc jj)\n        {\n          assume \"i \\<le> Suc jj\" and \"\\<not> i \\<le> jj\"\n          hence \"i = Suc jj\" by auto \n          hence \"a * a ^ (r + i - Suc jj) = a ^ (r + i - jj)\" by simp\n        } \n        moreover\n        {\n          assume ijj: \"i \\<le> jj\"\n          have \"of_nat (r choose (Suc jj - i)) * (a * a ^ (r + i - Suc jj)) \n          + of_nat (r choose (jj - i)) * a ^ (r + i - jj) =\n            of_nat (Suc r choose (Suc jj - i)) * a ^ (r + i - jj)\"\n          proof (cases \"r + i < jj\")\n            case True\n            hence gt: \"jj - i > r\" \"Suc jj - i > r\" \"Suc jj - i > Suc r\" by auto\n            show ?thesis \n              unfolding binomial_eq_0[OF gt(1)] binomial_eq_0[OF gt(2)] binomial_eq_0[OF gt(3)]\n              by simp\n          next\n            case False \n            hence ge: \"r + i \\<ge> jj\" by simp\n            show ?thesis\n            proof (cases \"jj = r + i\")\n              case True\n              have gt: \"r < Suc r\" by simp\n              show ?thesis unfolding True by (simp add: binomial_eq_0[OF gt])\n            next\n              case False\n              with ge have lt: \"jj < r + i\" by auto\n              hence \"r + i - jj = Suc (r + i - Suc jj)\" by simp \n              hence prod: \"a * a ^ (r + i - Suc jj) = a ^ (r + i - jj)\" by simp\n              from ijj have id: \"Suc jj - i = Suc (jj - i)\" by simp\n              have binom: \"Suc r choose (Suc jj - i) = \n                r choose (Suc jj - i) + (r choose (jj - i))\"\n                unfolding id\n                by (subst binomial_Suc_Suc, simp)\n              show ?thesis unfolding prod binom  \n                by (simp add: field_simps)\n            qed\n          qed\n        }\n        ultimately show ?thesis using ij unfolding Suc by auto\n      qed auto\n      finally have \"vec n (?v i) \\<bullet> col (jordan_block n a) j \n        = of_nat (Suc r choose (j - i)) * a ^ (Suc (r + i) - j)\" .\n    } note main_case = this\n    show ?thesis\n      by (rule eq_matI, insert easy_case main_case, auto)\n  qed\n  finally show ?case by simp\nqed\n\ndefinition jordan_matrix :: \"(nat \\<times> 'a :: {zero,one})list \\<Rightarrow> 'a mat\" where\n  \"jordan_matrix n_as = diag_block_mat (map (\\<lambda> (n,a). jordan_block n a) n_as)\"\n\nlemma jordan_matrix_dim[simp]: \n  \"dim_row (jordan_matrix n_as) = sum_list (map fst n_as)\"\n  \"dim_col (jordan_matrix n_as) = sum_list (map fst n_as)\"\n  unfolding jordan_matrix_def\n  by (subst dim_diag_block_mat, auto, (induct n_as, auto simp: Let_def)+)\n\nlemma jordan_matrix_carrier[simp]: \n  \"jordan_matrix n_as \\<in> carrier_mat (sum_list (map fst n_as)) (sum_list (map fst n_as))\"\n  unfolding carrier_mat_def by auto\n\nlemma jordan_matrix_upper_triangular: \"i < sum_list (map fst n_as)\n  \\<Longrightarrow> j < i \\<Longrightarrow> jordan_matrix n_as $$ (i,j) = 0\"\n  unfolding jordan_matrix_def\n  by (rule diag_block_upper_triangular, auto simp: jordan_matrix_def[symmetric])\n\nlemma jordan_matrix_pow: \"(jordan_matrix n_as) ^\\<^sub>m r = \n  diag_block_mat (map (\\<lambda> (n,a). (jordan_block n a) ^\\<^sub>m r) n_as)\"\n  unfolding jordan_matrix_def\n  by (subst diag_block_pow_mat, force, rule arg_cong[of _ _ diag_block_mat], auto)\n\nlemma jordan_matrix_char_poly: \n  \"char_poly (jordan_matrix n_as) = (\\<Prod>(n, a)\\<leftarrow>n_as. [:- a, 1:] ^ n)\"\nproof -\n  let ?n = \"sum_list (map fst n_as)\"\n  have \"diag_mat\n     ([:0, 1:] \\<cdot>\\<^sub>m 1\\<^sub>m (sum_list (map fst n_as)) + map_mat (\\<lambda>a. [:- a:]) (jordan_matrix n_as)) =\n    concat (map (\\<lambda>(n, a). replicate n [:- a, 1:]) n_as)\" unfolding jordan_matrix_def\n  proof (induct n_as)\n    case (Cons na n_as)\n    obtain n a where na: \"na = (n,a)\" by force\n    let ?n2 = \"sum_list (map fst n_as)\"\n    note fbo = four_block_one_mat\n    note mz = zero_carrier_mat\n    note mo = one_carrier_mat\n    have mA: \"\\<And> A. A \\<in> carrier_mat (dim_row A) (dim_col A)\" unfolding carrier_mat_def by auto\n    let ?Bs = \"map (\\<lambda>(x, y). jordan_block x y) n_as\"\n    let ?B = \"diag_block_mat ?Bs\"\n    from jordan_matrix_dim[of n_as, unfolded jordan_matrix_def]\n    have dimB: \"dim_row ?B = ?n2\" \"dim_col ?B = ?n2\" by auto\n    hence B: \"?B \\<in> carrier_mat ?n2 ?n2\" unfolding carrier_mat_def by simp\n    show ?case unfolding na fbo\n    apply (simp add: Let_def fbo[symmetric] del: fbo)\n    apply (subst smult_four_block_mat[OF mo mz mz mo])\n    apply (subst map_four_block_mat[OF jordan_block_carrier mz mz mA])\n    apply (subst add_four_block_mat[of _ n n _ ?n2 _ ?n2], auto simp: dimB B)\n    apply (subst diag_four_block_mat[of _ n _ ?n2], auto simp: dimB B)\n    apply (subst Cons, auto simp: jordan_block_def diag_mat_def, \n      intro nth_equalityI, auto)\n    done\n  qed (force simp: diag_mat_def)\n  also have \"prod_list ... = (\\<Prod>(n, a)\\<leftarrow>n_as. [:- a, 1:] ^ n)\"\n    by (induct n_as, auto)\n  finally\n  show ?thesis unfolding char_poly_defs\n    by (subst det_upper_triangular[of _ ?n], auto simp: jordan_matrix_upper_triangular)\nqed\n\ndefinition jordan_nf :: \"'a :: semiring_1 mat \\<Rightarrow> (nat \\<times> 'a)list \\<Rightarrow> bool\" where\n  \"jordan_nf A n_as \\<equiv> (0 \\<notin> fst ` set n_as \\<and> similar_mat A (jordan_matrix n_as))\"\n\nlemma jordan_nf_powE: assumes A: \"A \\<in> carrier_mat n n\" and jnf: \"jordan_nf A n_as\" \n  obtains P Q where \"P \\<in> carrier_mat n n\" \"Q \\<in> carrier_mat n n\" and \n  \"char_poly A = (\\<Prod>(na, a)\\<leftarrow>n_as. [:- a, 1:] ^ na)\"\n  \"\\<And> k. A ^\\<^sub>m k = P * (jordan_matrix n_as)^\\<^sub>m k * Q\"\nproof -\n  from A have dim: \"dim_row A = n\" by auto\n  assume obt: \"\\<And>P Q. P \\<in> carrier_mat n n \\<Longrightarrow> Q \\<in> carrier_mat n n \\<Longrightarrow> \n    char_poly A = (\\<Prod>(na, a)\\<leftarrow>n_as. [:- a, 1:] ^ na) \\<Longrightarrow> \n    (\\<And>k. A ^\\<^sub>m k = P * jordan_matrix n_as ^\\<^sub>m k * Q) \\<Longrightarrow> thesis\"\n  from jnf[unfolded jordan_nf_def] obtain P Q where\n    simw: \"similar_mat_wit A (jordan_matrix n_as) P Q\"\n    and sim: \"similar_mat A (jordan_matrix n_as)\" unfolding similar_mat_def by blast\n  show thesis\n  proof (rule obt)\n    show \"\\<And> k. A ^\\<^sub>m k = P * jordan_matrix n_as ^\\<^sub>m k * Q\"\n      by (rule similar_mat_wit_pow_id[OF simw])\n    show \"char_poly A = (\\<Prod>(na, a)\\<leftarrow>n_as. [:- a, 1:] ^ na)\"\n      unfolding char_poly_similar[OF sim] jordan_matrix_char_poly ..    \n  qed (insert simw[unfolded similar_mat_wit_def Let_def dim], auto)\nqed\n\nlemma choose_poly_bound: assumes \"i \\<le> d\"\n  shows \"r choose i \\<le> max 1 (r^d)\"\nproof (cases \"i \\<le> r\")\n  case False\n  hence \"r choose i = 0\" by simp\n  thus ?thesis by arith\nnext\n  case True\n  show ?thesis\n  proof (cases r)\n    case (Suc rr)\n    from binomial_le_pow[OF True] have \"r choose i \\<le> r ^ i\" by simp\n    also have \"\\<dots> \\<le> r^d\" using power_increasing[OF \\<open>i \\<le> d\\<close>, of r] Suc by auto\n    finally show ?thesis by simp\n  qed (insert True, simp)\nqed  \n\ncontext\n  fixes b :: \"'a :: archimedean_field\"\n  assumes b: \"0 < b\" \"b < 1\"\nbegin\n      \nlemma poly_exp_constant_bound: \"\\<exists> p. \\<forall> x. c * b ^ x * of_nat x ^ deg \\<le> p\" \nproof (cases \"c \\<le> 0\")\n  case True\n  show ?thesis\n    by (rule exI[of _ 0], intro allI, \n    rule mult_nonpos_nonneg[OF mult_nonpos_nonneg[OF True]], insert b, auto)\nnext\n  case False\n  hence c: \"c \\<ge> 0\" by simp\n  from poly_exp_bound[OF b, of deg] obtain p where \"\\<And> x. b ^ x * of_nat x ^ deg \\<le> p\" by auto\n  from mult_left_mono[OF this c]\n  show ?thesis by (intro exI[of _ \"c * p\"], auto simp: ac_simps)\nqed\n\nlemma poly_exp_max_constant_bound: \"\\<exists> p. \\<forall> x. c * b ^ x * max 1 (of_nat x ^ deg) \\<le> p\" \nproof -\n  from poly_exp_constant_bound[of c deg] obtain p where\n    p: \"\\<And> x. c * b ^ x * of_nat x ^ deg \\<le> p\" by auto\n  show ?thesis\n  proof (rule exI[of _ \"max p c\"], intro allI)\n    fix x\n    let ?exp = \"of_nat x ^ deg :: 'a\"\n    show \"c * b ^ x * max 1 ?exp \\<le> max p c\"\n    proof (cases \"x = 0\")\n      case False\n      hence \"?exp \\<noteq> of_nat 0\" by simp\n      hence \"?exp \\<ge> 1\" by (metis less_one not_less of_nat_1 of_nat_less_iff of_nat_power)\n      hence \"max 1 ?exp = ?exp\" by simp\n      thus ?thesis using p[of x] by simp\n    qed (cases deg, auto)\n  qed\nqed\nend\n\ncontext\n  fixes a :: \"'a :: real_normed_field\"\nbegin\nlemma jordan_block_bound: \n  assumes i: \"i < n\" and j: \"j < n\"\n  shows \"norm ((jordan_block n a ^\\<^sub>m k) $$ (i,j)) \n    \\<le> norm a ^ (k + i - j) * max 1 (of_nat k ^ (n - 1))\"\n    (is \"?lhs \\<le> ?rhs\")\nproof -\n  have id: \"(jordan_block n a ^\\<^sub>m k) $$ (i,j) = (if i \\<le> j then of_nat (k choose (j - i)) * a ^ (k + i - j) else 0)\"\n    unfolding jordan_block_pow using i j by auto\n  from i j have diff: \"j - i \\<le> n - 1\" by auto\n  show ?thesis\n  proof (cases \"i \\<le> j\")\n    case False\n    thus ?thesis unfolding id by simp\n  next\n    case True\n    hence \"?lhs = norm (of_nat (k choose (j - i)) * a ^ (k + i - j))\" unfolding id by simp\n    also have \"\\<dots> \\<le> norm (of_nat (k choose (j - i)) :: 'a) * norm (a ^ (k + i - j))\"\n      by (rule norm_mult_ineq)\n    also have \"\\<dots> \\<le> (max 1 (of_nat k ^ (n - 1))) * norm a ^ (k + i - j)\"\n    proof (rule mult_mono[OF _ norm_power_ineq _ norm_ge_zero])\n      have \"k choose (j - i) \\<le> max 1 (k ^ (n - 1))\" \n        by (rule choose_poly_bound[OF diff])\n      hence \"norm (of_nat (k choose (j - i)) :: 'a) \\<le> of_nat (max 1 (k ^ (n - 1)))\"\n        unfolding norm_of_nat of_nat_le_iff .\n      also have \"\\<dots> = max 1 (of_nat k ^ (n - 1))\" by (metis max_def of_nat_1 of_nat_le_iff of_nat_power)\n      finally show \"norm (of_nat (k choose (j - i)) :: 'a) \\<le> max 1 (real_of_nat k ^ (n - 1))\" .\n    qed simp\n    also have \"\\<dots> = ?rhs\" by simp\n    finally show ?thesis .\n  qed\nqed\n\nlemma jordan_block_poly_bound: \n  assumes i: \"i < n\" and j: \"j < n\" and a: \"norm a = 1\"\n  shows \"norm ((jordan_block n a ^\\<^sub>m k) $$ (i,j)) \\<le> max 1 (of_nat k ^ (n - 1))\"\n    (is \"?lhs \\<le> ?rhs\")\nproof -\n  from jordan_block_bound[OF i j, of k, unfolded a]\n  show ?thesis by simp\nqed\n\n\ntheorem jordan_block_constant_bound: assumes a: \"norm a < 1\" \n  shows \"\\<exists> p. \\<forall> i j k. i < n \\<longrightarrow> j < n \\<longrightarrow> norm ((jordan_block n a ^\\<^sub>m k) $$ (i,j)) \\<le> p\"\nproof (cases \"a = 0\") \n  case True\n  show ?thesis\n  proof (rule exI[of _ 1], intro allI impI)\n    fix i j k\n    assume *: \"i < n\" \"j < n\"\n    {\n      assume ij: \"i \\<le> j\"\n      have \"norm ((of_nat (k choose (j - i)) :: 'a) * 0 ^ (k + i - j)) \\<le> 1\" (is \"norm ?lhs \\<le> 1\")\n      proof (cases \"k + i > j\")\n        case True\n        hence \"?lhs = 0\" by simp\n        also have \"norm (\\<dots>) \\<le> 1\" by simp\n        finally show ?thesis .\n      next\n        case False\n        hence id: \"?lhs = (of_nat (k choose (j - i)) :: 'a)\" and j: \"j - i \\<ge> k\" by auto\n        from j have \"k choose (j - i) = 0 \\<or> k choose (j - i) = 1\" by (simp add: nat_less_le)\n        thus \"norm ?lhs \\<le> 1\"\n        proof\n          assume k: \"k choose (j - i) = 0\"\n          show ?thesis unfolding id k by simp\n        next\n          assume k: \"k choose (j - i) = 1\"\n          show ?thesis unfolding id unfolding k by simp\n        qed\n      qed\n    }    \n    thus \"norm ((jordan_block n a ^\\<^sub>m k) $$ (i,j)) \\<le> 1\" unfolding True\n      unfolding jordan_block_pow using * by auto\n  qed\nnext\n  case False\n  hence na: \"norm a > 0\" by auto\n  define c where \"c = inverse (norm a ^ n)\"\n  define deg where \"deg = n - 1\"\n  have c: \"c > 0\" unfolding c_def using na by auto\n  define b where \"b = norm a\"\n  from a na have \"0 < b\" \"b < 1\" unfolding b_def by auto\n  from poly_exp_max_constant_bound[OF this, of c deg]\n  obtain p where \"\\<And> k. c * b ^ k * max 1 (of_nat k ^ deg) \\<le> p\" by auto\n  show ?thesis\n  proof (intro exI[of _ p], intro allI impI)\n    fix i j k\n    assume ij: \"i < n\" \"j < n\"\n    from jordan_block_bound[OF this]\n    have \"norm ((jordan_block n a ^\\<^sub>m k) $$ (i, j))\n      \\<le> norm a ^ (k + i - j) * max 1 (real_of_nat k ^ (n - 1))\" .\n    also have \"\\<dots> \\<le> c * norm a ^ k * max 1 (real_of_nat k ^ (n - 1))\"\n    proof (rule mult_right_mono)\n      from ij have \"i - j \\<le> n\" by auto\n      show \"norm a ^ (k + i - j) \\<le> c * norm a ^ k\"\n      proof (rule mult_left_le_imp_le)\n        show \"0 < norm a ^ n\" using na by auto\n        let ?lhs = \"norm a ^ n * norm a ^ (k + i - j)\"\n        let ?rhs = \"norm a ^ n * (c * norm a ^ k)\"\n        from ij have ge: \"n + (k + i - j) \\<ge> k\" by arith\n        have \"?lhs = norm a ^ (n + (k + i - j))\" by (simp add: power_add)\n        also have \"\\<dots> \\<le> norm a ^ k\" using ge a na using less_imp_le power_decreasing by blast\n        also have \"\\<dots> = ?rhs\" unfolding c_def using na by simp\n        finally show \"?lhs \\<le> ?rhs\" .\n      qed\n    qed simp\n    also have \"\\<dots> = c * b ^ k * max 1 (real_of_nat k ^ deg)\" unfolding b_def deg_def ..\n    also have \"\\<dots> \\<le> p\" by fact\n    finally show \"norm ((jordan_block n a ^\\<^sub>m k) $$ (i, j)) \\<le> p\" .\n  qed\nqed\n\ndefinition norm_bound :: \"'a mat \\<Rightarrow> real \\<Rightarrow> bool\" where\n  \"norm_bound A b \\<equiv> \\<forall> i j. i < dim_row A \\<longrightarrow> j < dim_col A \\<longrightarrow> norm (A $$ (i,j)) \\<le> b\"\n\nlemma norm_boundI[intro]:\n  assumes \"\\<And> i j. i < dim_row A \\<Longrightarrow> j < dim_col A \\<Longrightarrow> norm (A $$ (i,j)) \\<le> b\"\n  shows \"norm_bound A b\"\n  unfolding norm_bound_def using assms by blast\n\nlemma  jordan_block_constant_bound2:\n\"\\<exists>p. norm (a :: 'a :: real_normed_field) < 1 \\<longrightarrow>\n    (\\<forall>i j k. i < n \\<longrightarrow> j < n \\<longrightarrow> norm ((jordan_block n a ^\\<^sub>m k) $$ (i, j)) \\<le> p)\"\nusing jordan_block_constant_bound by auto\n\nlemma jordan_matrix_poly_bound2:\n  fixes n_as :: \"(nat \\<times> 'a) list\"\n  assumes n_as: \"\\<And> n a. (n,a) \\<in> set n_as \\<Longrightarrow> n > 0 \\<Longrightarrow> norm a \\<le> 1\"\n  and N: \"\\<And> n a. (n,a) \\<in> set n_as \\<Longrightarrow> norm a = 1 \\<Longrightarrow> n \\<le> N\"\n  shows \"\\<exists>c1. \\<forall>k. \\<forall>e \\<in> elements_mat (jordan_matrix n_as ^\\<^sub>m k).\n    norm e \\<le> c1 + of_nat k ^ (N - 1)\"\nproof -\n  from jordan_matrix_carrier[of n_as] obtain d where\n    jm: \"jordan_matrix n_as \\<in> carrier_mat d d\" by blast\n  define f where \"f = (\\<lambda>n (a::'a) i j k. norm ((jordan_block n a ^\\<^sub>m k) $$ (i,j)))\"\n  let ?g = \"\\<lambda>k c1. c1 + of_nat k ^ (N-1)\"\n  let ?P = \"\\<lambda>n (a::'a) i j k c1. f n a i j k \\<le> ?g k c1\"\n  define Q where \"Q = (\\<lambda>n (a::'a) k c1. \\<forall>i j. i<n \\<longrightarrow> j<n \\<longrightarrow> ?P n a i j k c1)\"\n  have \"\\<And> c c' k n a i j. c \\<le> c' \\<Longrightarrow> ?P n a i j k c \\<Longrightarrow> ?P n a i j k c'\" by auto  \n  hence Q_mono: \"\\<And>n a c c'. c \\<le> c' \\<Longrightarrow> \\<forall>k. Q n a k c \\<Longrightarrow> \\<forall>k. Q n a k c'\"\n    unfolding Q_def by arith\n  { fix n a assume na: \"(n,a) \\<in> set n_as\"\n    obtain c where c: \"norm a < 1 \\<longrightarrow> (\\<forall>i j k. i < n \\<longrightarrow> j < n \\<longrightarrow> f n a i j k \\<le> c)\"\n      apply (rule exE[OF jordan_block_constant_bound2])\n      unfolding f_def using Jordan_Normal_Form.jordan_block_constant_bound2\n      by metis\n    define c1 where \"c1 = max 1 c\"\n    then have \"c1 \\<ge> 1\" \"c1 \\<ge> c\" by auto\n    have \"\\<exists>c1. \\<forall>k i j. i < n \\<longrightarrow> j < n \\<longrightarrow> ?P n a i j k c1\"\n    proof rule+\n      fix i j k assume \"i < n\" \"j < n\"\n      then have \"0<n\" by auto\n      let ?jbs = \"map (\\<lambda>(n,a). jordan_block n a) n_as\"\n      have sq_jbs: \"Ball (set ?jbs) square_mat\" by auto\n      have \"jordan_matrix n_as ^\\<^sub>m k = diag_block_mat (map (\\<lambda>A. A ^\\<^sub>m k) ?jbs)\"\n        unfolding jordan_matrix_def using diag_block_pow_mat[OF sq_jbs] by auto\n      show \"?P n a i j k c1\"\n      proof (cases \"norm a = 1\")\n        case True {\n          have nN:\"n-1 \\<le> N-1\" using N[OF na] True by auto\n          have \"f n a i j k \\<le> max 1 (of_nat k ^ (n-1))\"\n            using Jordan_Normal_Form.jordan_block_poly_bound True \\<open>i<n\\<close> \\<open>j<n\\<close>\n            unfolding f_def by auto\n          also have \"... \\<le> max 1 (of_nat k ^ (N-1))\"\n            proof (cases \"k=0\")\n              case False then show ?thesis\n                by (subst max.mono[OF _ power_increasing[OF nN]], auto)\n            qed (simp add: power_eq_if)\n          also have \"... \\<le> max c1 (of_nat k ^ (N-1))\" using \\<open>c1\\<ge>1\\<close> by auto\n          also have \"... \\<le> c1 + (of_nat k ^ (N-1))\" using \\<open>c1\\<ge>1\\<close> by auto\n          finally show ?thesis by simp\n        } next\n        case False {\n          then have na1: \"norm a < 1\" using n_as[OF na] \\<open>0<n\\<close> by auto\n          hence \"f n a i j k \\<le> c\" using c \\<open>i<n\\<close> \\<open>j<n\\<close> by auto\n          also have \"... \\<le> c1\" using \\<open>c\\<le>c1\\<close>.\n          also have \"... \\<le> c1 + of_nat k ^ (N-1)\" by auto\n          finally show ?thesis by auto\n        }\n      qed\n    qed\n  }\n  hence \"\\<forall>na. \\<exists>c1. na \\<in> set n_as \\<longrightarrow> (\\<forall>k. Q (fst na) (snd na) k c1)\"\n    unfolding Q_def by auto\n  from choice[OF this] obtain c'\n    where c': \"\\<And> na k. na \\<in> set n_as \\<Longrightarrow> Q (fst na) (snd na) k (c' na)\" by blast\n  define c where \"c = max 0 (Max (set (map c' n_as)))\"\n  { fix n a assume na: \"(n,a) \\<in> set n_as\"\n    then have Q: \"\\<forall> k. Q n a k (c' (n,a))\" using c'[OF na] by auto\n    from na have \"c' (n,a) \\<in> set (map c' n_as)\" by auto\n    from Max_ge[OF _ this] have \"c' (n,a) \\<le> c\" unfolding c_def by auto\n    from Q_mono[OF this Q] have \"\\<And> k. Q n a k c\" by blast\n  }\n  hence Q: \"\\<And>k n a. (n,a) \\<in> set n_as \\<Longrightarrow> Q n a k c\" by auto\n  have c0: \"c \\<ge> 0\" unfolding c_def by simp\n  { fix k n a e\n    assume na:\"(n,a) \\<in> set n_as\"\n    let ?jbk = \"jordan_block n a ^\\<^sub>m k\"\n    assume \"e \\<in> elements_mat ?jbk\"\n    from elements_matD[OF this] obtain i j\n      where \"i < n\" \"j < n\" and [simp]: \"e = ?jbk $$ (i,j)\"\n      by (simp only:pow_mat_dim_square[OF jordan_block_carrier],auto)\n    hence \"norm e \\<le> ?g k c\" using Q[OF na] unfolding Q_def f_def by simp\n  }\n  hence norm_jordan:\n    \"\\<And>k. \\<forall>(n,a) \\<in> set n_as. \\<forall>e \\<in> elements_mat (jordan_block n a ^\\<^sub>m k).\n     norm e \\<le> ?g k c\" by auto\n  { fix k\n    let ?jmk = \"jordan_matrix n_as ^\\<^sub>m k\"\n    have \"dim_row ?jmk = d\" \"dim_col ?jmk = d\"\n      using jm by (simp only:pow_mat_dim_square[OF jm])+\n    let ?As = \"(map (\\<lambda>(n,a). jordan_block n a ^\\<^sub>m k) n_as)\"\n    have \"\\<And>e. e \\<in> elements_mat ?jmk \\<Longrightarrow> norm e \\<le> ?g k c\"\n    proof -\n      fix e assume e:\"e \\<in> elements_mat ?jmk\"\n      obtain i j where ij: \"i < d\" \"j < d\" and \"e = ?jmk $$ (i,j)\"\n        using elements_matD[OF e] by (simp only:pow_mat_dim_square[OF jm],auto)\n      have \"?jmk = diag_block_mat ?As\"\n        using jordan_matrix_pow[of n_as k] by auto\n      hence \"elements_mat ?jmk \\<subseteq> {0} \\<union> \\<Union> (set (map elements_mat ?As))\"\n        using elements_diag_block_mat[of ?As] by auto\n      hence e_mem: \"e \\<in> {0} \\<union> \\<Union> (set (map elements_mat ?As))\"\n        using e by blast\n      show \"norm e \\<le> ?g k c\"\n      proof (cases \"e = 0\")\n        case False\n          then have \"e \\<in> \\<Union> (set (map elements_mat ?As))\" using e_mem by auto\n          then obtain n a\n            where \"e \\<in> elements_mat (jordan_block n a ^\\<^sub>m k)\"\n            and na: \"(n,a) \\<in> set n_as\" by force\n          thus ?thesis using norm_jordan na by force\n      qed (insert c0, auto)\n    qed\n  }\n  thus ?thesis by auto\nqed\n\nlemma norm_bound_bridge:\n  \"\\<forall>e \\<in> elements_mat A. norm e \\<le> b \\<Longrightarrow> norm_bound A b\"\n  unfolding norm_bound_def by force\n\nlemma norm_bound_mult: assumes A1: \"A1 \\<in> carrier_mat nr n\"\n  and A2: \"A2 \\<in> carrier_mat n nc\"\n  and b1: \"norm_bound A1 b1\"\n  and b2: \"norm_bound A2 b2\"\n  shows \"norm_bound (A1 * A2) (b1 * b2 * of_nat n)\"\nproof \n  let ?A = \"A1 * A2\"\n  let ?n = \"of_nat n\"\n  fix i j\n  assume i: \"i < dim_row ?A\" and j: \"j < dim_col ?A\"\n  define v1 where \"v1 = (\\<lambda> k. row A1 i $ k)\"\n  define v2 where \"v2 = (\\<lambda> k. col A2 j $ k)\"\n  from assms(1-2) have dim: \"dim_row A1 = nr\" \"dim_col A2 = nc\" \"dim_col A1 = n\" \"dim_row A2 = n\" by auto\n  {\n    fix k\n    assume k: \"k < n\"\n    have n: \"norm (v1 k) \\<le> b1\" \"norm (v2 k) \\<le> b2\" \n      using i j k dim v1_def v2_def\n      b1[unfolded norm_bound_def, rule_format, of i k] \n      b2[unfolded norm_bound_def, rule_format, of k j] by auto\n    have \"norm (v1 k * v2 k) \\<le> norm (v1 k) * norm (v2 k)\" by (rule norm_mult_ineq)\n    also have \"\\<dots> \\<le> b1 * b2\" by (rule mult_mono'[OF n], auto)\n    finally have \"norm (v1 k * v2 k) \\<le> b1 * b2\" .\n  } note bound = this\n  have \"?A $$ (i,j) = row A1 i \\<bullet> col A2 j\" using dim i j by simp\n  also have \"\\<dots> = (\\<Sum> k = 0 ..< n. v1 k * v2 k)\" unfolding scalar_prod_def \n    using dim i j v1_def v2_def by simp\n  also have \"norm (\\<dots>) \\<le> (\\<Sum> k = 0 ..< n. b1 * b2)\" \n    by (rule sum_norm_le, insert bound, simp)\n  also have \"\\<dots> = b1 * b2 * ?n\" by simp\n  finally show \"norm (?A $$ (i,j)) \\<le> b1 * b2 * ?n\" .\nqed\n\nlemma norm_bound_max: \"norm_bound A (Max {norm (A $$ (i,j)) | i j. i < dim_row A \\<and> j < dim_col A})\" \n  (is \"norm_bound A (Max ?norms)\")\nproof \n  fix i j\n  have fin: \"finite ?norms\" by (simp add: finite_image_set2)\n  assume \"i < dim_row A\" and \"j < dim_col A\"     \n  hence \"norm (A $$ (i,j)) \\<in> ?norms\" by auto\n  from Max_ge[OF fin this] show \"norm (A $$ (i,j)) \\<le> Max ?norms\" .\nqed\n\nlemma jordan_matrix_poly_bound: fixes n_as :: \"(nat \\<times> 'a)list\"\n  assumes n_as: \"\\<And> n a. (n,a) \\<in> set n_as \\<Longrightarrow> n > 0 \\<Longrightarrow> norm a \\<le> 1\"\n  and N: \"\\<And> n a. (n,a) \\<in> set n_as \\<Longrightarrow> norm a = 1 \\<Longrightarrow> n \\<le> N\"\n  shows \"\\<exists> c1. \\<forall> k. norm_bound (jordan_matrix n_as ^\\<^sub>m k) (c1 + of_nat k ^ (N - 1))\" \n  using jordan_matrix_poly_bound2 norm_bound_bridge N n_as\n  by metis\n\nlemma jordan_nf_matrix_poly_bound: fixes n_as :: \"(nat \\<times> 'a)list\"\n  assumes A: \"A \\<in> carrier_mat n n\"\n  and n_as: \"\\<And> n a. (n,a) \\<in> set n_as \\<Longrightarrow> n > 0 \\<Longrightarrow> norm a \\<le> 1\"\n  and N: \"\\<And> n a. (n,a) \\<in> set n_as \\<Longrightarrow> norm a = 1 \\<Longrightarrow> n \\<le> N\"\n  and jnf: \"jordan_nf A n_as\"\n  shows \"\\<exists> c1 c2. \\<forall> k. norm_bound (A ^\\<^sub>m k) (c1 + c2 * of_nat k ^ (N - 1))\"\nproof -\n  let ?cp2 = \"\\<Prod>(n, a)\\<leftarrow>n_as. [:- a, 1:] ^ n\"\n  let ?J = \"jordan_matrix n_as\"\n  from jnf[unfolded jordan_nf_def]\n  have sim: \"similar_mat A ?J\" by auto\n  then obtain P Q where sim_wit: \"similar_mat_wit A ?J P Q\" unfolding similar_mat_def by auto\n  from similar_mat_wit_pow_id[OF this] have pow: \"\\<And> k. A ^\\<^sub>m k = P * ?J ^\\<^sub>m k * Q\" .\n  from sim_wit[unfolded similar_mat_wit_def Let_def] A \n  have J: \"?J \\<in> carrier_mat n n\" and P: \"P \\<in> carrier_mat n n\" and Q: \"Q \\<in> carrier_mat n n\"\n    unfolding carrier_mat_def by force+\n  have \"\\<exists>c1. \\<forall> k. norm_bound (?J ^\\<^sub>m k) (c1 + of_nat k ^ (N - 1))\"\n    by (rule jordan_matrix_poly_bound[OF n_as N])\n  then obtain c1 where \n    bound_pow: \"\\<And> k. norm_bound ((?J ^\\<^sub>m k)) (c1 + of_nat k ^ (N - 1))\" by blast\n  obtain bP where bP: \"norm_bound P bP\" using norm_bound_max[of P] by auto\n  obtain bQ where bQ: \"norm_bound Q bQ\" using norm_bound_max[of Q] by auto\n  let ?n = \"of_nat n :: real\"\n  let ?c2 = \"bP * ?n * bQ * ?n\"\n  let ?c1 = \"?c2 * c1\"\n  {\n    fix k\n    have Jk: \"?J ^\\<^sub>m k \\<in> carrier_mat n n\" using J by simp\n    from norm_bound_mult[OF mult_carrier_mat[OF P Jk] Q \n      norm_bound_mult[OF P Jk bP bound_pow] bQ, folded pow] \n    have \"norm_bound (A ^\\<^sub>m k) (?c1 + ?c2 * of_nat k ^ (N - 1))\"  (is \"norm_bound _ ?exp\") \n      by (simp add: field_simps)\n  } note main = this\n  show ?thesis \n    by (intro exI allI, rule main)\nqed\nend\n\ncontext \n  fixes f_ty :: \"'a :: field itself\"\nbegin\nlemma char_matrix_jordan_block: \"char_matrix (jordan_block n a) b = (jordan_block n (a - b))\"\n  unfolding char_matrix_def jordan_block_def by auto\n\nlemma diag_jordan_block_pow: \"diag_mat (jordan_block n (a :: 'a) ^\\<^sub>m k) = replicate n (a ^ k)\"\n  unfolding diag_mat_def jordan_block_pow\n  by (intro nth_equalityI, auto)\n\nlemma jordan_block_zero_pow: \"(jordan_block n (0 :: 'a)) ^\\<^sub>m k = \n  (mat n n (\\<lambda> (i,j). if j \\<ge> i \\<and> j - i = k then 1 else 0))\"\nproof -\n  {\n    fix i j\n    assume  *: \"j - i \\<noteq> k\"\n    have \"of_nat (k choose (j - i)) * 0 ^ (k + i - j) = (0 :: 'a)\"\n    proof (cases \"k + i - j > 0\")\n      case True thus ?thesis by (cases \"k + i - j\", auto)\n    next\n      case False\n      with * have \"j - i > k\" by auto\n      thus ?thesis by (simp add: binomial_eq_0)\n    qed\n  }\n  thus ?thesis unfolding jordan_block_pow by (intro eq_matI, auto)\nqed\nend\n\nlemma jordan_matrix_concat_diag_block_mat: \"jordan_matrix (concat jbs) = diag_block_mat (map jordan_matrix jbs)\"\n  unfolding jordan_matrix_def[abs_def]\n  by (induct jbs, auto simp: diag_block_mat_append Let_def)\n\nlemma jordan_nf_diag_block_mat: assumes Ms: \"\\<And> A jbs. (A,jbs) \\<in> set Ms \\<Longrightarrow> jordan_nf A jbs\"\n  shows \"jordan_nf (diag_block_mat (map fst Ms)) (concat (map snd Ms))\"\nproof -\n  let ?Ms = \"map (\\<lambda> (A, jbs). (A, jordan_matrix jbs)) Ms\"\n  have id: \"map fst ?Ms = map fst Ms\" by auto\n  have id2: \"map snd ?Ms = map jordan_matrix (map snd Ms)\" by auto\n  {\n    fix A B\n    assume \"(A,B) \\<in> set ?Ms\"\n    then obtain jbs where mem: \"(A,jbs) \\<in> set Ms\" and B: \"B = jordan_matrix jbs\" by auto\n    from Ms[OF mem] have \"similar_mat A B\" unfolding B jordan_nf_def by auto\n  }\n  from similar_diag_mat_block_mat[of ?Ms, OF this, unfolded id id2] Ms\n  show ?thesis\n    unfolding jordan_nf_def jordan_matrix_concat_diag_block_mat by force\nqed  \n\n\nlemma jordan_nf_char_poly: assumes \"jordan_nf A n_as\"\n  shows \"char_poly A = (\\<Prod> (n,a) \\<leftarrow> n_as. [:- a, 1:] ^ n)\"\n  unfolding jordan_matrix_char_poly[symmetric]\n  by (rule char_poly_similar, insert assms[unfolded jordan_nf_def], auto)\n\nlemma jordan_nf_block_size_order_bound: assumes jnf: \"jordan_nf A n_as\"\n  and mem: \"(n,a) \\<in> set n_as\"\n  shows \"n \\<le> order a (char_poly A)\"\nproof -\n  from jnf[unfolded jordan_nf_def]\n  have \"similar_mat A (jordan_matrix n_as)\" by auto\n  from similar_matD[OF this] obtain m where \"A \\<in> carrier_mat m m\" by auto\n  from degree_monic_char_poly[OF this] have A: \"char_poly A \\<noteq> 0\" by auto\n  from mem obtain as bs where nas: \"n_as = as @ (n,a) # bs\" \n    by (meson split_list)\n  from jordan_nf_char_poly[OF jnf] \n  have cA: \"char_poly A = (\\<Prod>(n, a)\\<leftarrow>n_as. [:- a, 1:] ^ n)\" .\n  also have \"\\<dots> = [: -a, 1:] ^ n * (\\<Prod>(n, a)\\<leftarrow> as @ bs. [:- a, 1:] ^ n)\" unfolding nas by auto\n  also have \"[: -a,1 :] ^ n dvd \\<dots>\" unfolding dvd_def by blast\n  finally have \"[: -a,1 :] ^ n dvd char_poly A\" by auto\n  from order_max[OF this A] show ?thesis .\nqed\n\nlemma similar_mat_jordan_block_smult: fixes A :: \"'a :: field mat\" \n  assumes \"similar_mat A (jordan_block n a)\" \n   and k: \"k \\<noteq> 0\" \n  shows \"similar_mat (k \\<cdot>\\<^sub>m A) (jordan_block n (k * a))\" \nproof -\n  let ?J = \"jordan_block n a\" \n  let ?Jk = \"jordan_block n (k * a)\" \n  let ?kJ = \"k \\<cdot>\\<^sub>m jordan_block n a\" \n  from k have inv: \"k ^ i \\<noteq> 0\" for i by auto\n  let ?A = \"mat_diag n (\\<lambda> i. k^i)\" \n  let ?B = \"mat_diag n (\\<lambda> i. inverse (k^i))\"\n  have \"similar_mat_wit ?Jk ?kJ ?A ?B\" \n  proof (rule similar_mat_witI)\n    show \"jordan_block n (k * a) = ?A * ?kJ * ?B\"\n      by (subst mat_diag_mult_left[of _ _ n], force, subst mat_diag_mult_right[of _ n],\n       insert k inv, auto simp: jordan_block_def field_simps intro!: eq_matI)\n  qed (auto simp: inv field_simps k)\n  hence kJ: \"similar_mat ?Jk ?kJ\" \n    unfolding similar_mat_def by auto\n  have \"similar_mat A ?J\" by fact\n  hence \"similar_mat (k \\<cdot>\\<^sub>m A) (k \\<cdot>\\<^sub>m ?J)\" by (rule similar_mat_smult)\n  with kJ show ?thesis\n    using similar_mat_sym similar_mat_trans by blast\nqed\n\n\nlemma jordan_matrix_Cons:  \"jordan_matrix (Cons (n,a) n_as) = four_block_mat \n  (jordan_block n a)                 (0\\<^sub>m n (sum_list (map fst n_as))) \n  (0\\<^sub>m (sum_list (map fst n_as)) n)   (jordan_matrix n_as)\" \n  unfolding jordan_matrix_def by (simp, simp add: jordan_matrix_def[symmetric])\n\nlemma similar_mat_jordan_matrix_smult:  fixes n_as :: \"(nat \\<times> 'a :: field) list\"\n  assumes k: \"k \\<noteq> 0\" \n  shows \"similar_mat (k \\<cdot>\\<^sub>m jordan_matrix n_as) (jordan_matrix (map (\\<lambda> (n,a). (n, k * a)) n_as))\" \nproof (induct n_as)\n  case Nil\n  show ?case by (auto simp: jordan_matrix_def intro!: similar_mat_refl)\nnext\n  case (Cons na n_as)\n  obtain n a where na: \"na = (n,a)\" by force\n  let ?l = \"map (\\<lambda> (n,a). (n, k * a))\" \n  let ?n = \"sum_list (map fst n_as)\" \n  have \"k \\<cdot>\\<^sub>m jordan_matrix (Cons na n_as) = k \\<cdot>\\<^sub>m four_block_mat \n     (jordan_block n a) (0\\<^sub>m n ?n)\n     (0\\<^sub>m ?n n) (jordan_matrix n_as)\" (is \"?M = _ \\<cdot>\\<^sub>m four_block_mat ?A ?B ?C ?D\")\n    by (simp add: na jordan_matrix_Cons)\n  also have \"\\<dots> = four_block_mat (k \\<cdot>\\<^sub>m ?A) ?B ?C (k \\<cdot>\\<^sub>m ?D)\" \n    by (subst smult_four_block_mat, auto)\n  finally have jm: \"?M = four_block_mat (k \\<cdot>\\<^sub>m ?A) ?B ?C (k \\<cdot>\\<^sub>m ?D)\" .\n  have [simp]: \"fst (case x of (n :: nat, a) \\<Rightarrow> (n, k * a)) = fst x\" for x by (cases x, auto)\n  have jmk: \"jordan_matrix (?l (Cons na n_as)) = four_block_mat\n     (jordan_block n (k * a)) ?B\n     ?C (jordan_matrix (?l n_as))\" (is \"?kM = four_block_mat ?kA _ _ ?kD\")\n    by (simp add: na jordan_matrix_Cons o_def)\n  show ?case unfolding jmk jm\n    by (rule similar_mat_four_block_0_0[OF similar_mat_jordan_block_smult[OF _ k] Cons],\n      auto intro!: similar_mat_refl)\nqed\n\nlemma jordan_nf_smult: fixes k :: \"'a :: field\" \n  assumes jn: \"jordan_nf A n_as\" \n  and k: \"k \\<noteq> 0\" \n  shows \"jordan_nf (k \\<cdot>\\<^sub>m A) (map (\\<lambda> (n,a). (n, k * a)) n_as)\" \nproof -\n  let ?l = \"map (\\<lambda> (n,a). (n, k * a))\" \n  from jn[unfolded jordan_nf_def] have sim: \"similar_mat A (jordan_matrix n_as)\" by auto\n  from similar_mat_smult[OF this, of k] similar_mat_jordan_matrix_smult[OF k, of n_as]\n  have \"similar_mat (k \\<cdot>\\<^sub>m A) (jordan_matrix (map (\\<lambda>(n, a). (n, k * a)) n_as))\" \n    using similar_mat_trans by blast\n  with jn show ?thesis unfolding jordan_nf_def by force\nqed\n\nlemma jordan_nf_order: assumes \"jordan_nf A n_as\" \n  shows \"order a (char_poly A)  = sum_list (map fst (filter (\\<lambda> na. snd na = a) n_as))\" \nproof - \n  let ?p = \"\\<lambda> n_as. (\\<Prod>(n, a)\\<leftarrow>n_as. [:- a, 1:] ^ n)\" \n  let ?s = \"\\<lambda> n_as. sum_list (map fst (filter (\\<lambda> na. snd na = a) n_as))\" \n  from jordan_nf_char_poly[OF assms]\n  have \"order a (char_poly A) = order a (?p n_as)\" by simp\n  also have \"\\<dots> = ?s n_as\" \n  proof (induct n_as)\n    case (Cons nb n_as)\n    obtain n b where nb: \"nb = (n,b)\" by force\n    have \"order a (?p (nb # n_as)) = order a ([: -b, 1:] ^ n * ?p n_as)\" unfolding nb by simp\n    also have \"\\<dots> = order a ([: -b, 1:] ^ n) + order a (?p n_as)\" \n      by (rule order_mult, auto simp: prod_list_zero_iff)\n    also have \"\\<dots> = (if a = b then n else 0) + ?s n_as\" unfolding Cons order_linear_power by simp\n    also have \"\\<dots> = ?s (nb # n_as)\" unfolding nb by auto\n    finally show ?case .\n  qed simp\n  finally show ?thesis .\nqed\n\nsubsection \\<open>Application for Complexity\\<close>\n\nlemma factored_char_poly_norm_bound: assumes A: \"A \\<in> carrier_mat n n\"\n  and linear_factors: \"char_poly A = (\\<Prod> (a :: 'a :: real_normed_field) \\<leftarrow> as. [:- a, 1:])\"\n  and jnf_exists: \"\\<exists> n_as. jordan_nf A n_as\" \n  and le_1: \"\\<And> a. a \\<in> set as \\<Longrightarrow> norm a \\<le> 1\"\n  and le_N: \"\\<And> a. a \\<in> set as \\<Longrightarrow> norm a = 1 \\<Longrightarrow> length (filter ((=) a) as) \\<le> N\"\n  shows \"\\<exists> c1 c2. \\<forall> k. norm_bound (A ^\\<^sub>m k) (c1 + c2 * of_nat k ^ (N - 1))\"\nproof -\n  from jnf_exists obtain n_as \n    where jnf: \"jordan_nf A n_as\" by auto\n  let ?cp1 = \"(\\<Prod> a \\<leftarrow> as. [:- a, 1:])\"\n  let ?cp2 = \"\\<Prod>(n, a)\\<leftarrow>n_as. [:- a, 1:] ^ n\"\n  let ?J = \"jordan_matrix n_as\"\n  from jnf[unfolded jordan_nf_def]\n  have sim: \"similar_mat A ?J\" by auto\n  from char_poly_similar[OF sim, unfolded linear_factors jordan_matrix_char_poly]\n  have cp: \"?cp1 = ?cp2\" .\n  show ?thesis\n  proof (rule jordan_nf_matrix_poly_bound[OF A _ _ jnf])\n    fix n a\n    assume na: \"(n,a) \\<in> set n_as\"\n    then obtain na1 na2 where n_as: \"n_as = na1 @ (n,a) # na2\"\n      unfolding in_set_conv_decomp by auto\n    then obtain p where \"?cp2 = [: -a, 1 :]^n * p\" unfolding n_as by auto\n    from cp[unfolded this] have dvd: \"[: -a, 1 :] ^ n dvd ?cp1\" by auto\n    let ?as = \"filter ((=) a) as\"\n    let ?pn = \"\\<lambda> as. \\<Prod>a\\<leftarrow>as. [:- a, 1:]\"\n    let ?p = \"\\<lambda> as. \\<Prod>a\\<leftarrow>as. [: a, 1:]\"\n    have \"?pn as = ?p (map uminus as)\" by (induct as, auto)\n    from poly_linear_exp_linear_factors[OF dvd[unfolded this]] \n    have \"n \\<le> length (filter ((=) (- a)) (map uminus as))\" .\n    also have \"\\<dots> = length (filter ((=) a) as)\" \n      by (induct as, auto)\n    finally have filt: \"n \\<le> length (filter ((=) a) as)\" .\n    {\n      assume \"0 < n\"\n      with filt obtain b bs where \"?as = b # bs\" by (cases ?as, auto)\n      from arg_cong[OF this, of set]\n      have \"a \\<in> set as\" by auto \n      from le_1[rule_format, OF this]\n      show \"norm a \\<le> 1\" .\n      note \\<open>a \\<in> set as\\<close>\n    } note mem = this\n    {\n      assume \"norm a = 1\" \n      from le_N[OF mem this] filt show \"n \\<le> N\" by (cases n, auto)\n    }\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/Evaluation/Jordan_Normal_Form/Jordan_Normal_Form.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8499711794579722, "lm_q2_score": 0.8376199592797929, "lm_q1q2_score": 0.7119528247265843}}
{"text": "(*  Title:      ZF/OrdQuant.thy\n    Authors:    Krzysztof Grabczewski and L C Paulson\n*)\n\nsection \\<open>Special quantifiers\\<close>\n\ntheory OrdQuant imports Ordinal begin\n\nsubsection \\<open>Quantifiers and union operator for ordinals\\<close>\n\ndefinition\n  (* Ordinal Quantifiers *)\n  oall :: \"[i, i => o] => o\"  where\n    \"oall A P == \\<forall>x. x<A \\<longrightarrow> P(x)\"\n\ndefinition\n  oex :: \"[i, i => o] => o\"  where\n    \"oex A P  == \\<exists>x. x<A & P(x)\"\n\ndefinition\n  (* Ordinal Union *)\n  OUnion :: \"[i, i => i] => i\"  where\n    \"OUnion i B == {z: \\<Union>x\\<in>i. B(x). Ord(i)}\"\n\nsyntax\n  \"_oall\"     :: \"[idt, i, o] => o\"        (\"(3\\<forall>_<_./ _)\" 10)\n  \"_oex\"      :: \"[idt, i, o] => o\"        (\"(3\\<exists>_<_./ _)\" 10)\n  \"_OUNION\"   :: \"[idt, i, i] => i\"        (\"(3\\<Union>_<_./ _)\" 10)\ntranslations\n  \"\\<forall>x<a. P\" \\<rightleftharpoons> \"CONST oall a (\\<lambda>x. P)\"\n  \"\\<exists>x<a. P\" \\<rightleftharpoons> \"CONST oex a (\\<lambda>x. P)\"\n  \"\\<Union>x<a. B\" \\<rightleftharpoons> \"CONST OUnion a (\\<lambda>x. B)\"\n\n\nsubsubsection \\<open>simplification of the new quantifiers\\<close>\n\n\n(*MOST IMPORTANT that this is added to the simpset BEFORE Ord_atomize\n  is proved.  Ord_atomize would convert this rule to\n    x < 0 ==> P(x) == True, which causes dire effects!*)\n\n\nlemma [simp]: \"~(\\<exists>x<0. P(x))\"\nby (simp add: oex_def)\n\nlemma [simp]: \"(\\<forall>x<succ(i). P(x)) <-> (Ord(i) \\<longrightarrow> P(i) & (\\<forall>x<i. P(x)))\"\napply (simp add: oall_def le_iff)\napply (blast intro: lt_Ord2)\ndone\n\nlemma [simp]: \"(\\<exists>x<succ(i). P(x)) <-> (Ord(i) & (P(i) | (\\<exists>x<i. P(x))))\"\napply (simp add: oex_def le_iff)\napply (blast intro: lt_Ord2)\ndone\n\nsubsubsection \\<open>Union over ordinals\\<close>\n\nlemma Ord_OUN [intro,simp]:\n     \"[| !!x. x<A ==> Ord(B(x)) |] ==> Ord(\\<Union>x<A. B(x))\"\nby (simp add: OUnion_def ltI Ord_UN)\n\nlemma OUN_upper_lt:\n     \"[| a<A;  i < b(a);  Ord(\\<Union>x<A. b(x)) |] ==> i < (\\<Union>x<A. b(x))\"\nby (unfold OUnion_def lt_def, blast )\n\nlemma OUN_upper_le:\n     \"[| a<A;  i\\<le>b(a);  Ord(\\<Union>x<A. b(x)) |] ==> i \\<le> (\\<Union>x<A. b(x))\"\napply (unfold OUnion_def, auto)\napply (rule UN_upper_le )\napply (auto simp add: lt_def)\ndone\n\nlemma Limit_OUN_eq: \"Limit(i) ==> (\\<Union>x<i. x) = i\"\nby (simp add: OUnion_def Limit_Union_eq Limit_is_Ord)\n\n(* No < version of this theorem: consider that @{term\"(\\<Union>i\\<in>nat.i)=nat\"}! *)\nlemma OUN_least:\n     \"(!!x. x<A ==> B(x) \\<subseteq> C) ==> (\\<Union>x<A. B(x)) \\<subseteq> C\"\nby (simp add: OUnion_def UN_least ltI)\n\nlemma OUN_least_le:\n     \"[| Ord(i);  !!x. x<A ==> b(x) \\<le> i |] ==> (\\<Union>x<A. b(x)) \\<le> i\"\nby (simp add: OUnion_def UN_least_le ltI Ord_0_le)\n\nlemma le_implies_OUN_le_OUN:\n     \"[| !!x. x<A ==> c(x) \\<le> d(x) |] ==> (\\<Union>x<A. c(x)) \\<le> (\\<Union>x<A. d(x))\"\nby (blast intro: OUN_least_le OUN_upper_le le_Ord2 Ord_OUN)\n\nlemma OUN_UN_eq:\n     \"(!!x. x \\<in> A ==> Ord(B(x)))\n      ==> (\\<Union>z < (\\<Union>x\\<in>A. B(x)). C(z)) = (\\<Union>x\\<in>A. \\<Union>z < B(x). C(z))\"\nby (simp add: OUnion_def)\n\nlemma OUN_Union_eq:\n     \"(!!x. x \\<in> X ==> Ord(x))\n      ==> (\\<Union>z < \\<Union>(X). C(z)) = (\\<Union>x\\<in>X. \\<Union>z < x. C(z))\"\nby (simp add: OUnion_def)\n\n(*So that rule_format will get rid of this quantifier...*)\nlemma atomize_oall [symmetric, rulify]:\n     \"(!!x. x<A ==> P(x)) == Trueprop (\\<forall>x<A. P(x))\"\nby (simp add: oall_def atomize_all atomize_imp)\n\nsubsubsection \\<open>universal quantifier for ordinals\\<close>\n\nlemma oallI [intro!]:\n    \"[| !!x. x<A ==> P(x) |] ==> \\<forall>x<A. P(x)\"\nby (simp add: oall_def)\n\nlemma ospec: \"[| \\<forall>x<A. P(x);  x<A |] ==> P(x)\"\nby (simp add: oall_def)\n\nlemma oallE:\n    \"[| \\<forall>x<A. P(x);  P(x) ==> Q;  ~x<A ==> Q |] ==> Q\"\nby (simp add: oall_def, blast)\n\nlemma rev_oallE [elim]:\n    \"[| \\<forall>x<A. P(x);  ~x<A ==> Q;  P(x) ==> Q |] ==> Q\"\nby (simp add: oall_def, blast)\n\n\n(*Trival rewrite rule.  @{term\"(\\<forall>x<a.P)<->P\"} holds only if a is not 0!*)\nlemma oall_simp [simp]: \"(\\<forall>x<a. True) <-> True\"\nby blast\n\n(*Congruence rule for rewriting*)\nlemma oall_cong [cong]:\n    \"[| a=a';  !!x. x<a' ==> P(x) <-> P'(x) |]\n     ==> oall a (%x. P(x)) <-> oall a' (%x. P'(x))\"\nby (simp add: oall_def)\n\n\nsubsubsection \\<open>existential quantifier for ordinals\\<close>\n\nlemma oexI [intro]:\n    \"[| P(x);  x<A |] ==> \\<exists>x<A. P(x)\"\napply (simp add: oex_def, blast)\ndone\n\n(*Not of the general form for such rules... *)\nlemma oexCI:\n   \"[| \\<forall>x<A. ~P(x) ==> P(a);  a<A |] ==> \\<exists>x<A. P(x)\"\napply (simp add: oex_def, blast)\ndone\n\nlemma oexE [elim!]:\n    \"[| \\<exists>x<A. P(x);  !!x. [| x<A; P(x) |] ==> Q |] ==> Q\"\napply (simp add: oex_def, blast)\ndone\n\nlemma oex_cong [cong]:\n    \"[| a=a';  !!x. x<a' ==> P(x) <-> P'(x) |]\n     ==> oex a (%x. P(x)) <-> oex a' (%x. P'(x))\"\napply (simp add: oex_def cong add: conj_cong)\ndone\n\n\nsubsubsection \\<open>Rules for Ordinal-Indexed Unions\\<close>\n\nlemma OUN_I [intro]: \"[| a<i;  b \\<in> B(a) |] ==> b: (\\<Union>z<i. B(z))\"\nby (unfold OUnion_def lt_def, blast)\n\nlemma OUN_E [elim!]:\n    \"[| b \\<in> (\\<Union>z<i. B(z));  !!a.[| b \\<in> B(a);  a<i |] ==> R |] ==> R\"\napply (unfold OUnion_def lt_def, blast)\ndone\n\nlemma OUN_iff: \"b \\<in> (\\<Union>x<i. B(x)) <-> (\\<exists>x<i. b \\<in> B(x))\"\nby (unfold OUnion_def oex_def lt_def, blast)\n\nlemma OUN_cong [cong]:\n    \"[| i=j;  !!x. x<j ==> C(x)=D(x) |] ==> (\\<Union>x<i. C(x)) = (\\<Union>x<j. D(x))\"\nby (simp add: OUnion_def lt_def OUN_iff)\n\nlemma lt_induct:\n    \"[| i<k;  !!x.[| x<k;  \\<forall>y<x. P(y) |] ==> P(x) |]  ==>  P(i)\"\napply (simp add: lt_def oall_def)\napply (erule conjE)\napply (erule Ord_induct, assumption, blast)\ndone\n\n\nsubsection \\<open>Quantification over a class\\<close>\n\ndefinition\n  \"rall\"     :: \"[i=>o, i=>o] => o\"  where\n    \"rall M P == \\<forall>x. M(x) \\<longrightarrow> P(x)\"\n\ndefinition\n  \"rex\"      :: \"[i=>o, i=>o] => o\"  where\n    \"rex M P == \\<exists>x. M(x) & P(x)\"\n\nsyntax\n  \"_rall\"     :: \"[pttrn, i=>o, o] => o\"        (\"(3\\<forall>_[_]./ _)\" 10)\n  \"_rex\"      :: \"[pttrn, i=>o, o] => o\"        (\"(3\\<exists>_[_]./ _)\" 10)\ntranslations\n  \"\\<forall>x[M]. P\" \\<rightleftharpoons> \"CONST rall M (\\<lambda>x. P)\"\n  \"\\<exists>x[M]. P\" \\<rightleftharpoons> \"CONST rex M (\\<lambda>x. P)\"\n\n\nsubsubsection\\<open>Relativized universal quantifier\\<close>\n\nlemma rallI [intro!]: \"[| !!x. M(x) ==> P(x) |] ==> \\<forall>x[M]. P(x)\"\nby (simp add: rall_def)\n\nlemma rspec: \"[| \\<forall>x[M]. P(x); M(x) |] ==> P(x)\"\nby (simp add: rall_def)\n\n(*Instantiates x first: better for automatic theorem proving?*)\nlemma rev_rallE [elim]:\n    \"[| \\<forall>x[M]. P(x);  ~ M(x) ==> Q;  P(x) ==> Q |] ==> Q\"\nby (simp add: rall_def, blast)\n\nlemma rallE: \"[| \\<forall>x[M]. P(x);  P(x) ==> Q;  ~ M(x) ==> Q |] ==> Q\"\nby blast\n\n(*Trival rewrite rule;   (\\<forall>x[M].P)<->P holds only if A is nonempty!*)\nlemma rall_triv [simp]: \"(\\<forall>x[M]. P) \\<longleftrightarrow> ((\\<exists>x. M(x)) \\<longrightarrow> P)\"\nby (simp add: rall_def)\n\n(*Congruence rule for rewriting*)\nlemma rall_cong [cong]:\n    \"(!!x. M(x) ==> P(x) <-> P'(x)) ==> (\\<forall>x[M]. P(x)) <-> (\\<forall>x[M]. P'(x))\"\nby (simp add: rall_def)\n\n\nsubsubsection\\<open>Relativized existential quantifier\\<close>\n\nlemma rexI [intro]: \"[| P(x); M(x) |] ==> \\<exists>x[M]. P(x)\"\nby (simp add: rex_def, blast)\n\n(*The best argument order when there is only one M(x)*)\nlemma rev_rexI: \"[| M(x);  P(x) |] ==> \\<exists>x[M]. P(x)\"\nby blast\n\n(*Not of the general form for such rules... *)\nlemma rexCI: \"[| \\<forall>x[M]. ~P(x) ==> P(a); M(a) |] ==> \\<exists>x[M]. P(x)\"\nby blast\n\nlemma rexE [elim!]: \"[| \\<exists>x[M]. P(x);  !!x. [| M(x); P(x) |] ==> Q |] ==> Q\"\nby (simp add: rex_def, blast)\n\n(*We do not even have (\\<exists>x[M]. True) <-> True unless A is nonempty!!*)\nlemma rex_triv [simp]: \"(\\<exists>x[M]. P) \\<longleftrightarrow> ((\\<exists>x. M(x)) \\<and> P)\"\nby (simp add: rex_def)\n\nlemma rex_cong [cong]:\n    \"(!!x. M(x) ==> P(x) <-> P'(x)) ==> (\\<exists>x[M]. P(x)) <-> (\\<exists>x[M]. P'(x))\"\nby (simp add: rex_def cong: conj_cong)\n\nlemma rall_is_ball [simp]: \"(\\<forall>x[%z. z\\<in>A]. P(x)) <-> (\\<forall>x\\<in>A. P(x))\"\nby blast\n\nlemma rex_is_bex [simp]: \"(\\<exists>x[%z. z\\<in>A]. P(x)) <-> (\\<exists>x\\<in>A. P(x))\"\nby blast\n\nlemma atomize_rall: \"(!!x. M(x) ==> P(x)) == Trueprop (\\<forall>x[M]. P(x))\"\nby (simp add: rall_def atomize_all atomize_imp)\n\ndeclare atomize_rall [symmetric, rulify]\n\nlemma rall_simps1:\n     \"(\\<forall>x[M]. P(x) & Q)   <-> (\\<forall>x[M]. P(x)) & ((\\<forall>x[M]. False) | Q)\"\n     \"(\\<forall>x[M]. P(x) | Q)   <-> ((\\<forall>x[M]. P(x)) | Q)\"\n     \"(\\<forall>x[M]. P(x) \\<longrightarrow> Q) <-> ((\\<exists>x[M]. P(x)) \\<longrightarrow> Q)\"\n     \"(~(\\<forall>x[M]. P(x))) <-> (\\<exists>x[M]. ~P(x))\"\nby blast+\n\nlemma rall_simps2:\n     \"(\\<forall>x[M]. P & Q(x))   <-> ((\\<forall>x[M]. False) | P) & (\\<forall>x[M]. Q(x))\"\n     \"(\\<forall>x[M]. P | Q(x))   <-> (P | (\\<forall>x[M]. Q(x)))\"\n     \"(\\<forall>x[M]. P \\<longrightarrow> Q(x)) <-> (P \\<longrightarrow> (\\<forall>x[M]. Q(x)))\"\nby blast+\n\nlemmas rall_simps [simp] = rall_simps1 rall_simps2\n\nlemma rall_conj_distrib:\n    \"(\\<forall>x[M]. P(x) & Q(x)) <-> ((\\<forall>x[M]. P(x)) & (\\<forall>x[M]. Q(x)))\"\nby blast\n\nlemma rex_simps1:\n     \"(\\<exists>x[M]. P(x) & Q) <-> ((\\<exists>x[M]. P(x)) & Q)\"\n     \"(\\<exists>x[M]. P(x) | Q) <-> (\\<exists>x[M]. P(x)) | ((\\<exists>x[M]. True) & Q)\"\n     \"(\\<exists>x[M]. P(x) \\<longrightarrow> Q) <-> ((\\<forall>x[M]. P(x)) \\<longrightarrow> ((\\<exists>x[M]. True) & Q))\"\n     \"(~(\\<exists>x[M]. P(x))) <-> (\\<forall>x[M]. ~P(x))\"\nby blast+\n\nlemma rex_simps2:\n     \"(\\<exists>x[M]. P & Q(x)) <-> (P & (\\<exists>x[M]. Q(x)))\"\n     \"(\\<exists>x[M]. P | Q(x)) <-> ((\\<exists>x[M]. True) & P) | (\\<exists>x[M]. Q(x))\"\n     \"(\\<exists>x[M]. P \\<longrightarrow> Q(x)) <-> (((\\<forall>x[M]. False) | P) \\<longrightarrow> (\\<exists>x[M]. Q(x)))\"\nby blast+\n\nlemmas rex_simps [simp] = rex_simps1 rex_simps2\n\nlemma rex_disj_distrib:\n    \"(\\<exists>x[M]. P(x) | Q(x)) <-> ((\\<exists>x[M]. P(x)) | (\\<exists>x[M]. Q(x)))\"\nby blast\n\n\nsubsubsection\\<open>One-point rule for bounded quantifiers\\<close>\n\nlemma rex_triv_one_point1 [simp]: \"(\\<exists>x[M]. x=a) <-> ( M(a))\"\nby blast\n\nlemma rex_triv_one_point2 [simp]: \"(\\<exists>x[M]. a=x) <-> ( M(a))\"\nby blast\n\nlemma rex_one_point1 [simp]: \"(\\<exists>x[M]. x=a & P(x)) <-> ( M(a) & P(a))\"\nby blast\n\nlemma rex_one_point2 [simp]: \"(\\<exists>x[M]. a=x & P(x)) <-> ( M(a) & P(a))\"\nby blast\n\nlemma rall_one_point1 [simp]: \"(\\<forall>x[M]. x=a \\<longrightarrow> P(x)) <-> ( M(a) \\<longrightarrow> P(a))\"\nby blast\n\nlemma rall_one_point2 [simp]: \"(\\<forall>x[M]. a=x \\<longrightarrow> P(x)) <-> ( M(a) \\<longrightarrow> P(a))\"\nby blast\n\n\nsubsubsection\\<open>Sets as Classes\\<close>\n\ndefinition\n  setclass :: \"[i,i] => o\"       (\"##_\" [40] 40)  where\n   \"setclass(A) == %x. x \\<in> A\"\n\nlemma setclass_iff [simp]: \"setclass A x <-> x \\<in> A\"\nby (simp add: setclass_def)\n\nlemma rall_setclass_is_ball [simp]: \"(\\<forall>x[##A]. P(x)) <-> (\\<forall>x\\<in>A. P(x))\"\nby auto\n\nlemma rex_setclass_is_bex [simp]: \"(\\<exists>x[##A]. P(x)) <-> (\\<exists>x\\<in>A. P(x))\"\nby auto\n\n\nML\n\\<open>\nval Ord_atomize =\n  atomize ([(@{const_name oall}, @{thms ospec}), (@{const_name rall}, @{thms rspec})] @\n    ZF_conn_pairs, ZF_mem_pairs);\n\\<close>\ndeclaration \\<open>fn _ =>\n  Simplifier.map_ss (Simplifier.set_mksimps (fn ctxt =>\n    map mk_eq o Ord_atomize o Variable.gen_all ctxt))\n\\<close>\n\ntext \\<open>Setting up the one-point-rule simproc\\<close>\n\nsimproc_setup defined_rex (\"\\<exists>x[M]. P(x) & Q(x)\") = \\<open>\n  fn _ => Quantifier1.rearrange_bex\n    (fn ctxt =>\n      unfold_tac ctxt @{thms rex_def} THEN\n      Quantifier1.prove_one_point_ex_tac ctxt)\n\\<close>\n\nsimproc_setup defined_rall (\"\\<forall>x[M]. P(x) \\<longrightarrow> Q(x)\") = \\<open>\n  fn _ => Quantifier1.rearrange_ball\n    (fn ctxt =>\n      unfold_tac ctxt @{thms rall_def} THEN\n      Quantifier1.prove_one_point_all_tac ctxt)\n\\<close>\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/OrdQuant.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.849971175657575, "lm_q2_score": 0.8376199613065411, "lm_q1q2_score": 0.7119528232659732}}
{"text": "(* Author: Tobias Nipkow *)\n\nsection \"Swapping Adjacent Elements in a List\"\n\ntheory Swaps\nimports Inversion\nbegin\n\ntext\\<open>Swap elements at index \\<open>n\\<close> and @{term \"Suc n\"}:\\<close>\n\ndefinition \"swap n xs =\n  (if Suc n < size xs then xs[n := xs!Suc n, Suc n := xs!n] else xs)\"\n\nlemma length_swap[simp]: \"length(swap i xs) = length xs\"\nby(simp add: swap_def)\n\nlemma swap_id[simp]: \"Suc n \\<ge> size xs \\<Longrightarrow> swap n xs = xs\"\nby(simp add: swap_def)\n\nlemma distinct_swap[simp]:\n  \"distinct(swap i xs) = distinct xs\"\nby(simp add: swap_def)\n\nlemma swap_Suc[simp]: \"swap (Suc n) (a # xs) = a # swap n xs\"\nby(induction xs) (auto simp: swap_def)\n\nlemma index_swap_distinct:\n  \"distinct xs \\<Longrightarrow> Suc n < length xs \\<Longrightarrow>\n  index (swap n xs) x =\n  (if x = xs!n then Suc n else if x = xs!Suc n then n else index xs x)\"\nby(auto simp add: swap_def index_swap_if_distinct)\n\nlemma set_swap[simp]: \"set(swap n xs) = set xs\"\nby(auto simp add: swap_def set_conv_nth nth_list_update) metis\n\nlemma nth_swap_id[simp]: \"Suc i < length xs \\<Longrightarrow> swap i xs ! i = xs!(i+1)\"\nby(simp add: swap_def)\n\nlemma before_in_swap:\n \"dist_perm xs ys \\<Longrightarrow> Suc n < size xs \\<Longrightarrow>\n  x < y in (swap n xs) \\<longleftrightarrow>\n  x < y in xs \\<and> \\<not> (x = xs!n \\<and> y = xs!Suc n) \\<or> x = xs!Suc n \\<and> y = xs!n\"\nby(simp add:before_in_def index_swap_distinct)\n  (metis Suc_lessD Suc_lessI index_less_size_conv index_nth_id less_Suc_eq n_not_Suc_n nth_index)\n\nlemma Inv_swap: assumes \"dist_perm xs ys\"\nshows \"Inv xs (swap n ys) = \n  (if Suc n < size xs\n   then if ys!n < ys!Suc n in xs\n        then Inv xs ys \\<union> {(ys!n, ys!Suc n)}\n        else Inv xs ys - {(ys!Suc n, ys!n)}\n   else Inv xs ys)\"\nproof-\n  have \"length xs = length ys\" using assms by (metis distinct_card)\n  with assms show ?thesis\n    by(simp add: Inv_def set_eq_iff)\n      (metis before_in_def not_before_in before_in_swap)\nqed\n\n\ntext\\<open>Perform a list of swaps, from right to left:\\<close>\n\nabbreviation swaps where \"swaps == foldr swap\"\n\nlemma swaps_inv[simp]:\n  \"set (swaps sws xs) = set xs \\<and>\n  size(swaps sws xs) = size xs \\<and>\n  distinct(swaps sws xs) = distinct xs\"\nby (induct sws arbitrary: xs) (simp_all add: swap_def)\n\nlemma swaps_eq_Nil_iff[simp]: \"swaps acts xs = [] \\<longleftrightarrow> xs = []\"\nby(induction acts)(auto simp: swap_def)\n\nlemma swaps_map_Suc[simp]:\n  \"swaps (map Suc sws) (a # xs) = a # swaps sws xs\"\nby(induction sws arbitrary: xs) auto\n\nlemma card_Inv_swaps_le:\n  \"distinct xs \\<Longrightarrow> card (Inv xs (swaps sws xs)) \\<le> length sws\"\nby(induction sws) (auto simp: Inv_swap card_insert_if card_Diff_singleton_if)\n\nlemma nth_swaps: \"\\<forall>i\\<in>set is. j < i \\<Longrightarrow> swaps is xs ! j = xs ! j\"\nby(induction \"is\")(simp_all add: swap_def)\n\nlemma not_before0[simp]: \"~ x < xs ! 0 in xs\"\napply(cases \"xs = []\")\nby(auto simp: before_in_def neq_Nil_conv)\n\nlemma before_id[simp]: \"\\<lbrakk> distinct xs; i < size xs; j < size xs \\<rbrakk> \\<Longrightarrow>\n  xs ! i < xs ! j in xs \\<longleftrightarrow> i < j\"\nby(simp add: before_in_def index_nth_id)\n\nlemma before_swaps:\n  \"\\<lbrakk> distinct is; \\<forall>i\\<in>set is. Suc i < size xs; distinct xs; i \\<notin> set is; i < j; j < size xs \\<rbrakk> \\<Longrightarrow>\n  swaps is xs ! i < swaps is xs ! j in xs\"\napply(induction \"is\" arbitrary: i j)\n apply simp\napply(auto simp: swap_def nth_list_update)\ndone\n\nlemma card_Inv_swaps:\n  \"\\<lbrakk> distinct is; \\<forall>i\\<in>set is. Suc i < size xs; distinct xs \\<rbrakk> \\<Longrightarrow>\n  card(Inv xs (swaps is xs)) = length is\"\napply(induction \"is\")\n apply simp\napply(simp add: Inv_swap before_swaps card_insert_if)\napply(simp add: Inv_def)\ndone\n\nlemma swaps_eq_nth_take_drop: \"i < length xs \\<Longrightarrow>\n    swaps [0..<i] xs = xs!i # take i xs @ drop (Suc i) xs\"\napply(induction i arbitrary: xs)\napply (auto simp add: neq_Nil_conv swap_def drop_update_swap\n  take_Suc_conv_app_nth Cons_nth_drop_Suc[symmetric])\ndone\n\nlemma index_swaps_size: \"distinct s \\<Longrightarrow>\n  index s q \\<le> index (swaps sws s) q + length sws\"\napply(induction sws arbitrary: s)\napply simp\n apply (fastforce simp: swap_def index_swap_if_distinct index_nth_id)\ndone\n\nlemma index_swaps_last_size: \"distinct s \\<Longrightarrow>\n  size s \\<le> index (swaps sws s) (last s) + length sws + 1\"\napply(cases \"s = []\")\n apply simp\nusing index_swaps_size[of s \"last s\" sws] by 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/List_Update/Swaps.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.837619947119304, "lm_q2_score": 0.8499711794579722, "lm_q1q2_score": 0.711952814390519}}
{"text": "theory DistinctVars\nimports Main \"~~/src/HOL/Library/AList\"\nbegin\n\nabbreviation delete where \"delete \\<equiv> AList.delete\"\nabbreviation update where \"update \\<equiv> AList.update\"\n\nsubsubsection {* The domain of a associative list *}\n\ndefinition heapVars\n  where \"heapVars h = fst ` set h\"\n\nlemma heapVarsAppend[simp]:\"heapVars (a @ b) = heapVars a \\<union> heapVars b\"\n  and [simp]:\"heapVars ((v,e) # h) = insert v (heapVars h)\"\n  and [simp]:\"heapVars (p # h) = insert (fst p) (heapVars h)\"\n  and [simp]:\"heapVars [] = {}\"\n  by (auto simp add: heapVars_def)\n\nlemma heapVars_from_set:\n  \"(x, e) \\<in> set h \\<Longrightarrow> x \\<in> heapVars h\"\nby (induct h, auto)\n\nlemma finite_heapVars[simp]:\n  \"finite (heapVars \\<Gamma>)\"\n  by (auto simp add: heapVars_def)\n\nlemma delete_no_there:\n  \"x \\<notin> heapVars \\<Gamma> \\<Longrightarrow> delete x \\<Gamma> = \\<Gamma>\"\n  by (induct \\<Gamma>, auto)\n\nlemma heapVars_delete[simp]:\n  \"heapVars (delete x \\<Gamma>) = heapVars \\<Gamma> - {x}\"\n  by (induct \\<Gamma>, auto)\n\nsubsubsection {* Junk-free associative lists *}\n\ninductive distinctVars  where\n  [simp]: \"distinctVars []\" |\n  [intro]:\"x \\<notin> heapVars \\<Gamma> \\<Longrightarrow> distinctVars \\<Gamma> \\<Longrightarrow> distinctVars ((x, e)  # \\<Gamma>)\"\n\n\n\nlemma distinctVars_appendI:\n  \"distinctVars \\<Gamma> \\<Longrightarrow> distinctVars \\<Delta> \\<Longrightarrow> heapVars \\<Gamma> \\<inter> heapVars \\<Delta> = {} \\<Longrightarrow> distinctVars (\\<Gamma> @ \\<Delta>)\"\n  by (induct \\<Gamma> rule:distinctVars.induct, auto)\n\nlemma distinctVars_ConsD:\n  assumes \"distinctVars ((x,e) # \\<Gamma>)\"\n  shows \"x \\<notin> heapVars \\<Gamma>\" and \"distinctVars \\<Gamma>\"\n  by (rule distinctVars.cases[OF assms], simp_all)+\n\nlemma distinctVars_appendD:\n  assumes \"distinctVars (\\<Gamma> @ \\<Delta>)\"\n  shows distinctVars_appendD1: \"distinctVars \\<Gamma>\"\n  and distinctVars_appendD2: \"distinctVars \\<Delta>\"\n  and distinctVars_appendD3: \"heapVars \\<Gamma> \\<inter> heapVars \\<Delta> = {}\"\nproof-\n  from assms\n  have \"distinctVars \\<Gamma> \\<and> distinctVars \\<Delta> \\<and> heapVars \\<Gamma> \\<inter> heapVars \\<Delta> = {}\"\n  proof (induct \\<Gamma> )\n  case Nil thus ?case by simp\n  next\n  case (Cons p \\<Gamma>)\n    obtain x e where \"p = (x,e)\" by (metis PairE)\n    with Cons have \"distinctVars ((x,e) # (\\<Gamma>@ \\<Delta>))\" by simp\n    hence \"x \\<notin> heapVars (\\<Gamma>@ \\<Delta>)\" and \"distinctVars (\\<Gamma> @ \\<Delta>)\" by (rule distinctVars_ConsD)+\n\n    from `x \\<notin> heapVars (\\<Gamma>@ \\<Delta>)` have  \"x \\<notin> heapVars \\<Gamma>\"  and \"x \\<notin> heapVars \\<Delta>\" by auto\n\n    from Cons(1)[OF `distinctVars (\\<Gamma> @ \\<Delta>)`]\n    have \"distinctVars \\<Gamma>\" and \"distinctVars \\<Delta>\" and \"heapVars \\<Gamma> \\<inter> heapVars \\<Delta> = {}\" by auto\n    have \"distinctVars (p # \\<Gamma>)\"\n      using `p = _` `x \\<notin> heapVars \\<Gamma>` `distinctVars \\<Gamma>` by auto\n    moreover\n    have \"heapVars (p # \\<Gamma>) \\<inter> heapVars \\<Delta> = {}\" \n      using `p = _` `x \\<notin> heapVars \\<Delta>` `heapVars \\<Gamma> \\<inter> heapVars \\<Delta> = {}` by auto\n    ultimately\n    show ?case using `distinctVars \\<Delta>` by auto\n  qed\n  thus \"distinctVars \\<Gamma>\" and \"distinctVars \\<Delta>\" and \"heapVars \\<Gamma> \\<inter> heapVars \\<Delta> = {}\" by auto\nqed\n\nlemma distinctVars_Cons:\n  \"distinctVars (x # \\<Gamma>) \\<longleftrightarrow> (fst x \\<notin> heapVars \\<Gamma> \\<and> distinctVars \\<Gamma>)\"\n  by (metis PairE distinctVars.intros(2) distinctVars_ConsD fst_conv)\n\nlemma distinctVars_append:\n  \"distinctVars (\\<Gamma> @ \\<Delta>) \\<longleftrightarrow> (distinctVars \\<Gamma> \\<and> distinctVars \\<Delta> \\<and> heapVars \\<Gamma> \\<inter> heapVars \\<Delta> = {})\"\n  by (metis distinctVars_appendD distinctVars_appendI)\n\nlemma distinctVars_Cons_subset:\n  assumes \"heapVars ((x,e)#\\<Gamma>) \\<subseteq> heapVars ((x,e')#\\<Delta>)\"\n  assumes \"distinctVars ((x,e)#\\<Gamma>)\"\n  assumes \"distinctVars ((x,e')#\\<Delta>)\"\n  shows \"heapVars \\<Gamma> \\<subseteq> heapVars \\<Delta>\"\nproof-\n  have \"x \\<notin> heapVars \\<Gamma>\" and \"x \\<notin> heapVars \\<Delta>\"\n    using assms(2,3) by (metis distinctVars_ConsD(1))+\n  thus ?thesis using assms(1)\n    by auto\nqed\n\nlemma distinctVars_delete:\n  \"distinctVars \\<Gamma> \\<Longrightarrow> distinctVars (delete x \\<Gamma>)\"\n  apply (induct \\<Gamma> rule:distinctVars.induct)\n  apply (auto simp add: distinctVars_Cons)\n  done\n\nlemma dom_map_of_conv_heapVars[simp]:\n  \"dom (map_of xys) = heapVars xys\"\n  by (induct xys) (auto simp add: dom_if)\n\nlemma distinctVars_set_delete_insert:\n  assumes \"distinctVars \\<Gamma>\"\n  assumes \"(x,e) \\<in> set \\<Gamma>\"\n  shows \"set ((x,e) # delete x \\<Gamma>) = set \\<Gamma>\"\n  using assms\n  apply (induct \\<Gamma> rule:distinctVars.induct)\n  apply auto[1]\n  apply (case_tac \"xa = x\")\n  apply (auto simp add: heapVars_def)[1]\n    apply (metis fst_conv imageI)\n  apply auto\n  done\n\nlemma the_map_of_snd:\n  \"x\\<in> heapVars \\<Gamma> \\<Longrightarrow> the (map_of \\<Gamma> x) \\<in> snd ` set \\<Gamma>\"\nby (induct \\<Gamma>, auto)\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/DistinctVars.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757870046160257, "lm_q2_score": 0.8128673223709251, "lm_q1q2_score": 0.7118986374094818}}
{"text": "theory Reg_demo\n  imports Main\nbegin\n\ndatatype regexp =\n    Atom char\n  | Star regexp\n  | Alt regexp regexp\n  | Conc regexp regexp (infixl \"\\<cdot>\" 60)\n  | Neg regexp\n\nterm \"''abc''\"\nterm \"char_of_nat 13\"\n\nterm UNIV\n\ndefinition\n  \"Univ = Alt undefined (Neg undefined)\"\n\ndefinition\n  \"null = Neg Univ\"\n\ndefinition\n  \"epsilon = Star null\"\n\nprimrec\n  rrev :: \"regexp \\<Rightarrow> regexp\"\nwhere\n  \"rrev (Atom c) = Atom c\"\n| \"rrev (Star r) = Star (rrev r)\"\n| \"rrev (Conc r1 r2) = Conc (rrev r2) (rrev r1)\"\n| \"rrev (Alt r1 r2) = Alt (rrev r1) (rrev r2)\"\n| \"rrev (Neg r) = Neg (rrev r)\"\n\ntype_synonym word = \"char list\"\n\ndefinition\n  conc :: \"word set \\<Rightarrow> word set \\<Rightarrow> word set\"\nwhere\n  \"conc A B = { as @ bs |as bs. as \\<in> A \\<and> bs \\<in> B }\"\n\ninductive_set\n  star :: \"word set \\<Rightarrow> word set\" for R\nwhere\n  star_empty[simp, intro!]: \"[] \\<in> star R\"\n| star_app[elim]: \"\\<lbrakk> xs \\<in> R; ys \\<in> star R \\<rbrakk> \\<Longrightarrow> xs @ ys \\<in> star R\"\n\n\nprimrec\n  lang :: \"regexp \\<Rightarrow> word set\"\nwhere\n  \"lang (Atom c) = {[c]}\"\n| \"lang (Alt r1 r2) = lang r1 \\<union> lang r2\"\n| \"lang (Neg r) = -lang r\"\n| \"lang (Conc r1 r2) = conc (lang r1) (lang r2)\"\n| \"lang (Star r) = star (lang r)\"\n\n(*\n  repeatn :: nat \\<Rightarrow> regexp \\<Rightarrow> regexp\n\n  star = \\<Union>n. lang (repeatn n r) \n*)\n\nlemma lang_Univ[simp]:\n  \"lang Univ = UNIV\"\n  by (simp add: Univ_def)\n\nlemma lang_null[simp]:\n  \"lang null = {}\"\n  by (simp add: null_def)\n\nlemma star_empty[simp]:\n  \"star {} = {[]}\"\n  by (auto elim: star.cases)\n\nlemma lang_epsilon[simp]:\n  \"lang epsilon = {[]}\"\n  by (simp add: epsilon_def)\n\nlemma\n  \"lang (Alt r1 r2) = lang (Alt r2 r1)\"\n  by auto\n\nlemma rev_complement[simp]:\n  \"- rev ` A = rev ` (- A)\"\n  apply (rule bij_image_Compl_eq[symmetric])\n  apply (rule bijI)\n   apply (rule injI)\n   apply simp\n  apply (rule surjI[where f=rev])\n  apply simp\n  done\n\nlemma conc_rev[simp]:\n  \"conc (rev ` B) (rev ` A) = rev ` conc A B\"\n  by (fastforce simp: conc_def image_iff)\n\nlemma star_app2[elim]:\n  \"\\<lbrakk> a \\<in> A; as \\<in> star A \\<rbrakk> \\<Longrightarrow> as @ a \\<in> star A\"\n  apply (erule star.induct)\n   apply simp\n   apply (drule star_app[where ys=\"[]\"])\n    apply simp\n   apply simp\n  apply auto\n  done\n\nlemma star_rev1:\n  \"as \\<in> star (rev ` A) \\<Longrightarrow> as \\<in> rev ` star A\"\n  apply (erule star.induct)\n   apply simp\n  apply clarsimp\n  apply (rename_tac a as)\n  apply (clarsimp simp: image_iff)\n  apply (rule_tac x=\"as @ a\" in bexI)\n   apply simp\n  apply auto\n  done\n\nlemma rev2[simp]:\n  \"as \\<in> star A \\<Longrightarrow> rev as \\<in> star (rev ` A)\"\n  apply (erule star.induct)\n   apply simp\n  apply (clarsimp simp: image_iff)\n  apply (rule star_app2)\n  apply auto\n  done\n\nlemma star_rev[simp]:\n  \"star (rev ` A) = rev ` star A\"\n  by (auto simp: star_rev1)   \n\nlemma \"lang (rrev r) = rev ` lang r\"\n  by (induct r) auto\n\nend", "meta": {"author": "z5146542", "repo": "TOR", "sha": "9a82d491288a6d013e0764f68e602a63e48f92cf", "save_path": "github-repos/isabelle/z5146542-TOR", "path": "github-repos/isabelle/z5146542-TOR/TOR-9a82d491288a6d013e0764f68e602a63e48f92cf/181130/Reg_demo.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757870046160257, "lm_q2_score": 0.8128673133042217, "lm_q1q2_score": 0.7118986294689807}}
{"text": "section {* Refinement Calculus Examples *}\n\ntheory utp_rcalc_ex\n  imports \"../utp_rcalc\"\nbegin\n\nsubsection {* Initial Setup -- Example State Space *}\n  \nalphabet exstate =\n  x :: int\n  y :: int\n  z :: int\n  \ntext {* The examples in the section are taken from Carol Morgan's \"Programming from Specifications\". *}\n  \nsubsection {* Examples from Figure 1.5 on p7 *}\n  \nterm \"&x:[true, &y\\<^sup>2 =\\<^sub>u &x]\"\n\nterm \"&x:[&x \\<ge>\\<^sub>u 0, &y\\<^sup>2 =\\<^sub>u &x]\"\n\nterm \"&e:[&s \\<noteq>\\<^sub>u {}\\<^sub>u, &e \\<in>\\<^sub>u &s]\"\n\nterm \"&x:[&b\\<^sup>2 \\<ge>\\<^sub>u 4*&a*&c, &a*&x\\<^sup>2 + &b*&x + &c =\\<^sub>u 0]\"\n\nsubsection {* Exercise 1.4, first 4 questions *}\n  \nlemma \"&x:[true, &x \\<ge>\\<^sub>u 0] \\<sqsubseteq> &x:[true, &x =\\<^sub>u 0]\"\n  by (prefine)\n  \nlemma \"&x:[&x \\<ge>\\<^sub>u 0, true] \\<sqsubseteq> &x:[&x =\\<^sub>u 0, true]\"\n  apply (prefine)\n  nitpick\n  oops\n\nlemma \"&x:[&x \\<ge>\\<^sub>u 0, &x =\\<^sub>u 0] \\<sqsubseteq> &x:[&x =\\<^sub>u 0, &x \\<ge>\\<^sub>u 0]\"\n  apply (prefine)\n  nitpick\n  oops\n    \nlemma \"&x:[&x =\\<^sub>u 0, &x \\<ge>\\<^sub>u 0] \\<sqsubseteq> &x:[&x \\<ge>\\<^sub>u 0, &x =\\<^sub>u 0]\"\n  by (prefine) \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/impl/examples/utp_rcalc_ex.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869916479466, "lm_q2_score": 0.8128673223709251, "lm_q1q2_score": 0.7118986268681541}}
{"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_MSortBU2Count\nimports \"../../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 count :: \"'a => 'a list => int\" where\n\"count x (nil2) = 0\"\n| \"count x (cons2 z ys) =\n     (if (x = z) then 1 + (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_MSortBU2Count.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757870013740061, "lm_q2_score": 0.8128673087708699, "lm_q1q2_score": 0.7118986228633984}}
{"text": "(*  Title:      HOL/Probability/Convolution.thy\n    Author:     Sudeep Kanav, TU M\u00fcnchen\n    Author:     Johannes H\u00f6lzl, TU M\u00fcnchen *)\n\nsection \\<open>Convolution Measure\\<close>\n\ntheory Convolution\n  imports Independent_Family\nbegin\n\nlemma (in finite_measure) sigma_finite_measure: \"sigma_finite_measure M\"\n  ..\n\ndefinition convolution :: \"('a :: ordered_euclidean_space) measure \\<Rightarrow> 'a measure \\<Rightarrow> 'a measure\" (infix \"\\<star>\" 50) where\n  \"convolution M N = distr (M \\<Otimes>\\<^sub>M N) borel (\\<lambda>(x, y). x + y)\"\n\nlemma\n  shows space_convolution[simp]: \"space (convolution M N) = space borel\"\n    and sets_convolution[simp]: \"sets (convolution M N) = sets borel\"\n    and measurable_convolution1[simp]: \"measurable A (convolution M N) = measurable A borel\"\n    and measurable_convolution2[simp]: \"measurable (convolution M N) B = measurable borel B\"\n  by (simp_all add: convolution_def)\n\nlemma nn_integral_convolution:\n  assumes \"finite_measure M\" \"finite_measure N\"\n  assumes [measurable_cong]: \"sets N = sets borel\" \"sets M = sets borel\"\n  assumes [measurable]: \"f \\<in> borel_measurable borel\"\n  shows \"(\\<integral>\\<^sup>+x. f x \\<partial>convolution M N) = (\\<integral>\\<^sup>+x. \\<integral>\\<^sup>+y. f (x + y) \\<partial>N \\<partial>M)\"\nproof -\n  interpret M: finite_measure M by fact\n  interpret N: finite_measure N by fact\n  interpret pair_sigma_finite M N ..\n  show ?thesis\n    unfolding convolution_def\n    by (simp add: nn_integral_distr N.nn_integral_fst[symmetric])\nqed\n\nlemma convolution_emeasure:\n  assumes \"A \\<in> sets borel\" \"finite_measure M\" \"finite_measure N\"\n  assumes [simp]: \"sets N = sets borel\" \"sets M = sets borel\"\n  assumes [simp]: \"space M = space N\" \"space N = space borel\"\n  shows \"emeasure (M \\<star> N) A = \\<integral>\\<^sup>+x. (emeasure N {a. a + x \\<in> A}) \\<partial>M \"\n  using assms by (auto intro!: nn_integral_cong simp del: nn_integral_indicator simp: nn_integral_convolution\n    nn_integral_indicator [symmetric] ac_simps split:split_indicator)\n\nlemma convolution_emeasure':\n  assumes [simp]:\"A \\<in> sets borel\"\n  assumes [simp]: \"finite_measure M\" \"finite_measure N\"\n  assumes [simp]: \"sets N = sets borel\" \"sets M = sets borel\"\n  shows  \"emeasure (M \\<star> N) A = \\<integral>\\<^sup>+x. \\<integral>\\<^sup>+y.  (indicator  A (x + y)) \\<partial>N  \\<partial>M\"\n  by (auto simp del: nn_integral_indicator simp: nn_integral_convolution\n    nn_integral_indicator[symmetric] borel_measurable_indicator)\n\nlemma convolution_finite:\n  assumes [simp]: \"finite_measure M\" \"finite_measure N\"\n  assumes [measurable_cong]: \"sets N = sets borel\" \"sets M = sets borel\"\n  shows \"finite_measure (M \\<star> N)\"\n  unfolding convolution_def\n  by (intro finite_measure_pair_measure finite_measure.finite_measure_distr) auto\n\nlemma convolution_emeasure_3:\n  assumes [simp, measurable]: \"A \\<in> sets borel\"\n  assumes [simp]: \"finite_measure M\" \"finite_measure N\" \"finite_measure L\"\n  assumes [simp]: \"sets N = sets borel\" \"sets M = sets borel\" \"sets L = sets borel\"\n  shows \"emeasure (L \\<star> (M \\<star> N )) A = \\<integral>\\<^sup>+x. \\<integral>\\<^sup>+y. \\<integral>\\<^sup>+z. indicator A (x + y + z) \\<partial>N \\<partial>M \\<partial>L\"\n  apply (subst nn_integral_indicator[symmetric], simp)\n  apply (subst nn_integral_convolution,\n        auto intro!: borel_measurable_indicator borel_measurable_indicator' convolution_finite)+\n  by (rule nn_integral_cong)+ (auto simp: semigroup_add_class.add.assoc)\n\nlemma convolution_emeasure_3':\n  assumes [simp, measurable]:\"A \\<in> sets borel\"\n  assumes [simp]: \"finite_measure M\" \"finite_measure N\"  \"finite_measure L\"\n  assumes [measurable_cong, simp]: \"sets N = sets borel\" \"sets M = sets borel\" \"sets L = sets borel\"\n  shows \"emeasure ((L \\<star> M) \\<star> N ) A = \\<integral>\\<^sup>+x. \\<integral>\\<^sup>+y. \\<integral>\\<^sup>+z. indicator A (x + y + z) \\<partial>N \\<partial>M \\<partial>L\"\n  apply (subst nn_integral_indicator[symmetric], simp)+\n  apply (subst nn_integral_convolution)\n  apply (simp_all add: convolution_finite)\n  apply (subst nn_integral_convolution)\n  apply (simp_all add: finite_measure.sigma_finite_measure sigma_finite_measure.borel_measurable_nn_integral)\n  done\n\nlemma convolution_commutative:\n  assumes [simp]: \"finite_measure M\" \"finite_measure N\"\n  assumes [measurable_cong, simp]: \"sets N = sets borel\" \"sets M = sets borel\"\n  shows \"(M \\<star> N) = (N \\<star> M)\"\nproof (rule measure_eqI)\n  interpret M: finite_measure M by fact\n  interpret N: finite_measure N by fact\n  interpret pair_sigma_finite M N ..\n\n  show \"sets (M \\<star> N) = sets (N \\<star> M)\" by simp\n\n  fix A assume \"A \\<in> sets (M \\<star> N)\"\n  then have 1[measurable]:\"A \\<in> sets borel\" by simp\n  have \"emeasure (M \\<star> N) A = \\<integral>\\<^sup>+x. \\<integral>\\<^sup>+y. indicator A (x + y) \\<partial>N \\<partial>M\" by (auto intro!: convolution_emeasure')\n  also have \"... = \\<integral>\\<^sup>+x. \\<integral>\\<^sup>+y. (\\<lambda>(x,y). indicator A (x + y)) (x, y) \\<partial>N \\<partial>M\" by (auto intro!: nn_integral_cong)\n  also have \"... = \\<integral>\\<^sup>+y. \\<integral>\\<^sup>+x. (\\<lambda>(x,y). indicator A (x + y)) (x, y) \\<partial>M \\<partial>N\" by (rule Fubini[symmetric]) simp\n  also have \"... = emeasure (N \\<star> M) A\" by (auto intro!: nn_integral_cong simp: add.commute convolution_emeasure')\n  finally show \"emeasure (M \\<star> N) A = emeasure (N \\<star> M) A\" by simp\nqed\n\nlemma convolution_associative:\n  assumes [simp]: \"finite_measure M\" \"finite_measure N\"  \"finite_measure L\"\n  assumes [simp]: \"sets N = sets borel\" \"sets M = sets borel\" \"sets L = sets borel\"\n  shows \"(L \\<star> (M \\<star> N)) = ((L \\<star> M) \\<star> N)\"\n  by (auto intro!: measure_eqI simp: convolution_emeasure_3 convolution_emeasure_3')\n\nlemma (in prob_space) sum_indep_random_variable:\n  assumes ind: \"indep_var borel X borel Y\"\n  assumes [simp, measurable]: \"random_variable borel X\"\n  assumes [simp, measurable]: \"random_variable borel Y\"\n  shows \"distr M borel (\\<lambda>x. X x + Y x) = convolution (distr M borel X)  (distr M borel Y)\"\n  using ind unfolding indep_var_distribution_eq convolution_def\n  by (auto simp: distr_distr intro!:arg_cong[where f = \"distr M borel\"])\n\nlemma (in prob_space) sum_indep_random_variable_lborel:\n  assumes ind: \"indep_var borel X borel Y\"\n  assumes [simp, measurable]: \"random_variable lborel X\"\n  assumes [simp, measurable]:\"random_variable lborel Y\"\n  shows \"distr M lborel (\\<lambda>x. X x + Y x) = convolution (distr M lborel X)  (distr M lborel Y)\"\n  using ind unfolding indep_var_distribution_eq convolution_def\n  by (auto simp: distr_distr o_def intro!: arg_cong[where f = \"distr M borel\"] cong: distr_cong)\n\nlemma convolution_density:\n  fixes f g :: \"real \\<Rightarrow> ennreal\"\n  assumes [measurable]: \"f \\<in> borel_measurable borel\" \"g \\<in> borel_measurable borel\"\n  assumes [simp]:\"finite_measure (density lborel f)\" \"finite_measure (density lborel g)\"\n  shows \"density lborel f \\<star> density lborel g = density lborel (\\<lambda>x. \\<integral>\\<^sup>+y. f (x - y) * g y \\<partial>lborel)\"\n    (is \"?l = ?r\")\nproof (intro measure_eqI)\n  fix A assume \"A \\<in> sets ?l\"\n  then have [measurable]: \"A \\<in> sets borel\"\n    by simp\n\n  have \"(\\<integral>\\<^sup>+x. f x * (\\<integral>\\<^sup>+y. g y * indicator A (x + y) \\<partial>lborel) \\<partial>lborel) =\n    (\\<integral>\\<^sup>+x. (\\<integral>\\<^sup>+y. g y * (f x * indicator A (x + y)) \\<partial>lborel) \\<partial>lborel)\"\n  proof (intro nn_integral_cong_AE, eventually_elim)\n    fix x\n    have \"f x * (\\<integral>\\<^sup>+ y. g y * indicator A (x + y) \\<partial>lborel) =\n      (\\<integral>\\<^sup>+ y. f x * (g y * indicator A (x + y)) \\<partial>lborel)\"\n      by (intro nn_integral_cmult[symmetric]) auto\n    then show \"f x * (\\<integral>\\<^sup>+ y. g y * indicator A (x + y) \\<partial>lborel) =\n      (\\<integral>\\<^sup>+ y. g y * (f x * indicator A (x + y)) \\<partial>lborel)\"\n      by (simp add: ac_simps)\n  qed\n  also have \"\\<dots> = (\\<integral>\\<^sup>+y. (\\<integral>\\<^sup>+x. g y * (f x * indicator A (x + y)) \\<partial>lborel) \\<partial>lborel)\"\n    by (intro lborel_pair.Fubini') simp\n  also have \"\\<dots> = (\\<integral>\\<^sup>+y. (\\<integral>\\<^sup>+x. f (x - y) * g y * indicator A x \\<partial>lborel) \\<partial>lborel)\"\n  proof (intro nn_integral_cong_AE, eventually_elim)\n    fix y\n    have \"(\\<integral>\\<^sup>+x. g y * (f x * indicator A (x + y)) \\<partial>lborel) =\n      g y * (\\<integral>\\<^sup>+x. f x * indicator A (x + y) \\<partial>lborel)\"\n      by (intro nn_integral_cmult) auto\n    also have \"\\<dots> = g y * (\\<integral>\\<^sup>+x. f (x - y) * indicator A x \\<partial>lborel)\"\n      by (subst nn_integral_real_affine[where c=1 and t=\"-y\"])\n         (auto simp add: one_ennreal_def[symmetric])\n    also have \"\\<dots> = (\\<integral>\\<^sup>+x. g y * (f (x - y) * indicator A x) \\<partial>lborel)\"\n      by (intro nn_integral_cmult[symmetric]) auto\n    finally show \"(\\<integral>\\<^sup>+ x. g y * (f x * indicator A (x + y)) \\<partial>lborel) =\n      (\\<integral>\\<^sup>+ x. f (x - y) * g y * indicator A x \\<partial>lborel)\"\n      by (simp add: ac_simps)\n  qed\n  also have \"\\<dots> = (\\<integral>\\<^sup>+x. (\\<integral>\\<^sup>+y. f (x - y) * g y * indicator A x \\<partial>lborel) \\<partial>lborel)\"\n    by (intro lborel_pair.Fubini') simp\n  finally show \"emeasure ?l A = emeasure ?r A\"\n    by (auto simp: convolution_emeasure' nn_integral_density emeasure_density\n      nn_integral_multc)\nqed simp\n\nlemma (in prob_space) distributed_finite_measure_density:\n  \"distributed M N X f \\<Longrightarrow> finite_measure (density N f)\"\n  using finite_measure_distr[of X N] distributed_distr_eq_density[of M N X f] by simp\n\n\nlemma (in prob_space) distributed_convolution:\n  fixes f :: \"real \\<Rightarrow> _\"\n  fixes g :: \"real \\<Rightarrow> _\"\n  assumes indep: \"indep_var borel X borel Y\"\n  assumes X: \"distributed M lborel X f\"\n  assumes Y: \"distributed M lborel Y g\"\n  shows \"distributed M lborel (\\<lambda>x. X x + Y x) (\\<lambda>x. \\<integral>\\<^sup>+y. f (x - y) * g y \\<partial>lborel)\"\n  unfolding distributed_def\nproof safe\n  have fg[measurable]: \"f \\<in> borel_measurable borel\" \"g \\<in> borel_measurable borel\"\n    using distributed_borel_measurable[OF X] distributed_borel_measurable[OF Y] by simp_all\n\n  show \"(\\<lambda>x. \\<integral>\\<^sup>+ xa. f (x - xa) * g xa \\<partial>lborel) \\<in> borel_measurable lborel\"\n    by measurable\n\n  have \"distr M borel (\\<lambda>x. X x + Y x) = (distr M borel X \\<star> distr M borel Y)\"\n    using distributed_measurable[OF X] distributed_measurable[OF Y]\n    by (intro sum_indep_random_variable) (auto simp: indep)\n  also have \"\\<dots> = (density lborel f \\<star> density lborel g)\"\n    using distributed_distr_eq_density[OF X] distributed_distr_eq_density[OF Y]\n    by (simp cong: distr_cong)\n  also have \"\\<dots> = density lborel (\\<lambda>x. \\<integral>\\<^sup>+ y. f (x - y) * g y \\<partial>lborel)\"\n  proof (rule convolution_density)\n    show \"finite_measure (density lborel f)\"\n      using X by (rule distributed_finite_measure_density)\n    show \"finite_measure (density lborel g)\"\n      using Y by (rule distributed_finite_measure_density)\n  qed fact+\n  finally show \"distr M lborel (\\<lambda>x. X x + Y x) = density lborel (\\<lambda>x. \\<integral>\\<^sup>+ y. f (x - y) * g y \\<partial>lborel)\"\n    by (simp cong: distr_cong)\n  show \"random_variable lborel (\\<lambda>x. X x + Y x)\"\n    using distributed_measurable[OF X] distributed_measurable[OF Y] by simp\nqed\n\nlemma prob_space_convolution_density:\n  fixes f:: \"real \\<Rightarrow> _\"\n  fixes g:: \"real \\<Rightarrow> _\"\n  assumes [measurable]: \"f\\<in> borel_measurable borel\"\n  assumes [measurable]: \"g\\<in> borel_measurable borel\"\n  assumes gt_0[simp]: \"\\<And>x. 0 \\<le> f x\" \"\\<And>x. 0 \\<le> g x\"\n  assumes \"prob_space (density lborel f)\" (is \"prob_space ?F\")\n  assumes \"prob_space (density lborel g)\" (is \"prob_space ?G\")\n  shows \"prob_space (density lborel (\\<lambda>x.\\<integral>\\<^sup>+y. f (x - y) * g y \\<partial>lborel))\" (is \"prob_space ?D\")\nproof (subst convolution_density[symmetric])\n  interpret F: prob_space ?F by fact\n  show \"finite_measure ?F\" by unfold_locales\n  interpret G: prob_space ?G by fact\n  show \"finite_measure ?G\" by unfold_locales\n  interpret FG: pair_prob_space ?F ?G ..\n\n  show \"prob_space (density lborel f \\<star> density lborel g)\"\n    unfolding convolution_def by (rule FG.prob_space_distr) simp\nqed 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/HOL/Probability/Convolution.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391617003942, "lm_q2_score": 0.8244619242200082, "lm_q1q2_score": 0.7118335139104943}}
{"text": "subsection \\<open>Sorting\\<close>\n\ntext \\<open>Some preliminary lemmas about sorting.\\<close>\n\ntheory Sorting\n  imports Main \"HOL.List\" \"HOL-Library.Sublist\"\nbegin\n\nlemma insort:\n  assumes \"Suc l < length s\"\n  assumes \"s ! l < (v :: 'a :: linorder)\"\n  assumes \"s ! (l+1) > v\"\n  assumes \"sorted_wrt (<) s\"\n  shows \"sorted_wrt (<) ((take (Suc l) s)@v#(drop (Suc l) s))\"\nproof -\n  have \"sorted_wrt (<) (take (Suc l) s@(drop (Suc l) s))\"\n    using assms(4) by simp\n  moreover have\n    \"\\<And>x. x \\<in> set (take (Suc l) s) = (\\<exists>i. i < (Suc l) \\<and> i < length s \\<and> s ! i = x)\" \n    by (metis in_set_conv_nth length_take min_less_iff_conj nth_take)\n  hence \"\\<And>x. x \\<in> set (take (Suc l) s) \\<Longrightarrow> x < v\"\n    using assms apply (simp) \n    using less_Suc_eq sorted_wrt_nth_less by fastforce\n  moreover have\n    \"\\<And>x. x \\<in> set (drop (Suc l) s) = (\\<exists>i. Suc l + i < length s \\<and> s ! (Suc l + i) = x)\"\n    using assms(1) by (simp add:in_set_conv_nth add.commute less_diff_conv)\n  hence \"\\<And>x. x \\<in> set (drop (Suc l) s) \\<Longrightarrow> x > v\"\n    using assms apply (simp) \n    by (metis add.right_neutral add_diff_cancel_left' diff_Suc_Suc diff_is_0_eq'\n        leI le_less_trans less_imp_le sorted_wrt_iff_nth_less)\n  ultimately show ?thesis\n    by (simp add:sorted_wrt_append del:append_take_drop_id)\nqed\n\nlemma sorted_wrt_irrefl_distinct:\n  assumes \"irreflp r\"\n  shows \"sorted_wrt r xs \\<longrightarrow> distinct xs\"\n  using assms by (induction xs, simp, simp, meson irreflp_def)\n\nlemma sort_set_unique_h:\n  assumes \"irreflp r \\<and> transp r\"\n  assumes \"set (x#xs) = set (y#ys)\" \n  assumes \"\\<forall>z \\<in> set xs. r x z\" \n  assumes \"\\<forall>z \\<in> set ys. r y z\" \n  shows \"x = y \\<and> set xs = set ys\"\n  by (metis assms insert_eq_iff irreflp_def list.set_intros(1)\n      list.simps(15) set_ConsD transpD)\n\nlemma sort_set_unique_rel:\n  assumes \"irreflp r \\<and> transp r\"\n  assumes \"set x = set y\"\n  assumes \"sorted_wrt r x\"\n  assumes \"sorted_wrt r y\"\n  shows \"x = y\"\nproof -\n  have \"length x = length y\" \n    using assms by (metis sorted_wrt_irrefl_distinct distinct_card)\n  then show ?thesis using assms \n    apply(induct rule:list_induct2, simp, simp)\n    by (metis assms(1) list.simps(15) sort_set_unique_h) \nqed\n\nlemma sort_set_unique:\n  assumes \"set x = set y\"\n  assumes \"sorted_wrt (<) (map (f :: ('a \\<Rightarrow> ('b :: linorder)))  x)\"\n  assumes \"sorted_wrt (<) (map f y)\"\n  shows \"x = y\"\n  using assms apply (simp add:sorted_wrt_map) \n  by (metis (no_types, lifting) irreflp_def less_irrefl sort_set_unique_rel \n      transpD transpI transp_less)\n\ntext \\<open>If two sequences contain the same element and strictly increasing with respect.\\<close>\n\nlemma subseq_imp_sorted:\n  assumes \"subseq s t\"\n  assumes \"sorted_wrt p t\"\n  shows \"sorted_wrt p s\"\nproof -\n  have \"sorted_wrt p s \\<or> \\<not> sorted_wrt p t\"\n  apply (rule list_emb.induct[where P=\"(=)\"])\n  using list_emb_set assms by fastforce+\n  thus ?thesis using assms by blast\nqed\n\ntext \\<open>If a sequence @{text t} is sorted with respect to a relation @{text p} then a subsequence will \n  be as well.\\<close>\n\nfun to_ord where \"to_ord r x y = (\\<not>(r\\<^sup>*\\<^sup>* y x))\"\n\nlemma trancl_idemp: \"r\\<^sup>+\\<^sup>+\\<^sup>+\\<^sup>+ x y = r\\<^sup>+\\<^sup>+ x y\" \n  by (metis r_into_rtranclp reflclp_tranclp rtranclp_idemp rtranclp_reflclp \n      rtranclp_tranclp_tranclp tranclp.cases tranclp.r_into_trancl)\n\nlemma top_sort:\n  fixes rp\n  assumes \"acyclicP r\"\n  shows \"finite s \\<longrightarrow> (\\<exists>l. set l = s \\<and> sorted_wrt (to_ord r) l \\<and> distinct l)\"\nproof (induction \"card s\" arbitrary:s)\n  case 0\n  then show ?case by auto\nnext\n  case (Suc n)\n  hence \"s \\<noteq> {}\" by auto\n  moreover \n  have \"acyclicP (r\\<^sup>+\\<^sup>+)\" using assms\n    by (simp add:acyclic_def trancl_def trancl_idemp)\n  hence \"acyclic ({(x,y). r\\<^sup>+\\<^sup>+ x y} \\<inter> s \\<times> s)\"\n    by (meson acyclic_subset inf_le1)\n  hence \"wf ({(x,y). r\\<^sup>+\\<^sup>+ x y} \\<inter> s \\<times> s)\" using Suc \n    by (metis card_infinite finite_Int finite_SigmaI nat.distinct(1) \n        wf_iff_acyclic_if_finite)\n  ultimately obtain z where \n    \"z \\<in> s \\<and> (\\<forall>y. (y, z) \\<in>  ({(x,y). r\\<^sup>+\\<^sup>+ x y} \\<inter> s \\<times> s) \\<longrightarrow> y \\<notin> s)\" \n    by (metis ex_in_conv wf_eq_minimal)\n  hence z_def: \"z \\<in> s \\<and> (\\<forall>y. r\\<^sup>+\\<^sup>+ y z \\<longrightarrow> y \\<notin> s)\" by blast\n  hence \"card (s - {z}) = n\"\n    by (metis One_nat_def Suc.hyps(2) card_Diff_singleton_if card_infinite \n        diff_Suc_Suc diff_zero nat.simps(3))\n  then obtain l where l_def: \n    \"set l = s - {z} \\<and> sorted_wrt (to_ord r) l \\<and> distinct l\" \n    by (metis Zero_not_Suc card_infinite finite_Diff Suc)\n  hence \"set (z#l) = s\" using z_def by auto\n  moreover have \"\\<forall>y \\<in> set l. \\<not>(r\\<^sup>*\\<^sup>* y z)\" using z_def l_def rtranclpD by force\n  ultimately show ?case \n    by (metis distinct.simps(2) insert_absorb l_def list.simps(15) \n        sorted_wrt.simps(2) to_ord.elims(3))\nqed\n\nlemma top_sort_eff:\n  assumes \"irreflp p\\<^sup>+\\<^sup>+\"\n  assumes \"sorted_wrt (to_ord p) x\" \n  assumes \"i < length x\"\n  assumes \"j < length x\"\n  assumes \"(p\\<^sup>+\\<^sup>+ (x ! i) (x ! j))\"\n  shows \"i < j\"\n  using assms apply (cases \"i > j\")\n   apply (metis sorted_wrt_nth_less r_into_rtranclp reflclp_tranclp\n          rtranclp_idemp rtranclp_reflclp to_ord.simps)\n  by (metis irreflp_def nat_neq_iff)\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/WOOT_Strong_Eventual_Consistency/Sorting.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8633916064586998, "lm_q2_score": 0.8244619328462579, "lm_q1q2_score": 0.7118335126641753}}
{"text": "(*  Title:      HOL/Nonstandard_Analysis/NSComplex.thy\n    Author:     Jacques D. Fleuriot, University of Edinburgh\n    Author:     Lawrence C Paulson\n*)\n\nsection \\<open>Nonstandard Complex Numbers\\<close>\n\ntheory NSComplex\n  imports NSA\nbegin\n\ntype_synonym hcomplex = \"complex star\"\n\nabbreviation hcomplex_of_complex :: \"complex \\<Rightarrow> complex star\"\n  where \"hcomplex_of_complex \\<equiv> star_of\"\n\nabbreviation hcmod :: \"complex star \\<Rightarrow> real star\"\n  where \"hcmod \\<equiv> hnorm\"\n\n\nsubsubsection \\<open>Real and Imaginary parts\\<close>\n\ndefinition hRe :: \"hcomplex \\<Rightarrow> hypreal\"\n  where \"hRe = *f* Re\"\n\ndefinition hIm :: \"hcomplex \\<Rightarrow> hypreal\"\n  where \"hIm = *f* Im\"\n\n\nsubsubsection \\<open>Imaginary unit\\<close>\n\ndefinition iii :: hcomplex\n  where \"iii = star_of \\<i>\"\n\n\nsubsubsection \\<open>Complex conjugate\\<close>\n\ndefinition hcnj :: \"hcomplex \\<Rightarrow> hcomplex\"\n  where \"hcnj = *f* cnj\"\n\n\nsubsubsection \\<open>Argand\\<close>\n\ndefinition hsgn :: \"hcomplex \\<Rightarrow> hcomplex\"\n  where \"hsgn = *f* sgn\"\n\ndefinition harg :: \"hcomplex \\<Rightarrow> hypreal\"\n  where \"harg = *f* arg\"\n\ndefinition  \\<comment> \\<open>abbreviation for \\<open>cos a + i sin a\\<close>\\<close>\n  hcis :: \"hypreal \\<Rightarrow> hcomplex\"\n  where \"hcis = *f* cis\"\n\n\nsubsubsection \\<open>Injection from hyperreals\\<close>\n\nabbreviation hcomplex_of_hypreal :: \"hypreal \\<Rightarrow> hcomplex\"\n  where \"hcomplex_of_hypreal \\<equiv> of_hypreal\"\n\ndefinition  \\<comment> \\<open>abbreviation for \\<open>r * (cos a + i sin a)\\<close>\\<close>\n  hrcis :: \"hypreal \\<Rightarrow> hypreal \\<Rightarrow> hcomplex\"\n  where \"hrcis = *f2* rcis\"\n\n\nsubsubsection \\<open>\\<open>e ^ (x + iy)\\<close>\\<close>\n\ndefinition hExp :: \"hcomplex \\<Rightarrow> hcomplex\"\n  where \"hExp = *f* exp\"\n\ndefinition HComplex :: \"hypreal \\<Rightarrow> hypreal \\<Rightarrow> hcomplex\"\n  where \"HComplex = *f2* Complex\"\n\nlemmas hcomplex_defs [transfer_unfold] =\n  hRe_def hIm_def iii_def hcnj_def hsgn_def harg_def hcis_def\n  hrcis_def hExp_def HComplex_def\n\nlemma Standard_hRe [simp]: \"x \\<in> Standard \\<Longrightarrow> hRe x \\<in> Standard\"\n  by (simp add: hcomplex_defs)\n\nlemma Standard_hIm [simp]: \"x \\<in> Standard \\<Longrightarrow> hIm x \\<in> Standard\"\n  by (simp add: hcomplex_defs)\n\nlemma Standard_iii [simp]: \"iii \\<in> Standard\"\n  by (simp add: hcomplex_defs)\n\nlemma Standard_hcnj [simp]: \"x \\<in> Standard \\<Longrightarrow> hcnj x \\<in> Standard\"\n  by (simp add: hcomplex_defs)\n\nlemma Standard_hsgn [simp]: \"x \\<in> Standard \\<Longrightarrow> hsgn x \\<in> Standard\"\n  by (simp add: hcomplex_defs)\n\nlemma Standard_harg [simp]: \"x \\<in> Standard \\<Longrightarrow> harg x \\<in> Standard\"\n  by (simp add: hcomplex_defs)\n\nlemma Standard_hcis [simp]: \"r \\<in> Standard \\<Longrightarrow> hcis r \\<in> Standard\"\n  by (simp add: hcomplex_defs)\n\nlemma Standard_hExp [simp]: \"x \\<in> Standard \\<Longrightarrow> hExp x \\<in> Standard\"\n  by (simp add: hcomplex_defs)\n\nlemma Standard_hrcis [simp]: \"r \\<in> Standard \\<Longrightarrow> s \\<in> Standard \\<Longrightarrow> hrcis r s \\<in> Standard\"\n  by (simp add: hcomplex_defs)\n\nlemma Standard_HComplex [simp]: \"r \\<in> Standard \\<Longrightarrow> s \\<in> Standard \\<Longrightarrow> HComplex r s \\<in> Standard\"\n  by (simp add: hcomplex_defs)\n\nlemma hcmod_def: \"hcmod = *f* cmod\"\n  by (rule hnorm_def)\n\n\nsubsection \\<open>Properties of Nonstandard Real and Imaginary Parts\\<close>\n\nlemma hcomplex_hRe_hIm_cancel_iff: \"\\<And>w z. w = z \\<longleftrightarrow> hRe w = hRe z \\<and> hIm w = hIm z\"\n  by transfer (rule complex_Re_Im_cancel_iff)\n\nlemma hcomplex_equality [intro?]: \"\\<And>z w. hRe z = hRe w \\<Longrightarrow> hIm z = hIm w \\<Longrightarrow> z = w\"\n  by transfer (rule complex_equality)\n\nlemma hcomplex_hRe_zero [simp]: \"hRe 0 = 0\"\n  by transfer simp\n\nlemma hcomplex_hIm_zero [simp]: \"hIm 0 = 0\"\n  by transfer simp\n\nlemma hcomplex_hRe_one [simp]: \"hRe 1 = 1\"\n  by transfer simp\n\nlemma hcomplex_hIm_one [simp]: \"hIm 1 = 0\"\n  by transfer simp\n\n\nsubsection \\<open>Addition for Nonstandard Complex Numbers\\<close>\n\nlemma hRe_add: \"\\<And>x y. hRe (x + y) = hRe x + hRe y\"\n  by transfer simp\n\nlemma hIm_add: \"\\<And>x y. hIm (x + y) = hIm x + hIm y\"\n  by transfer simp\n\n\nsubsection \\<open>More Minus Laws\\<close>\n\nlemma hRe_minus: \"\\<And>z. hRe (- z) = - hRe z\"\n  by transfer (rule uminus_complex.sel)\n\nlemma hIm_minus: \"\\<And>z. hIm (- z) = - hIm z\"\n  by transfer (rule uminus_complex.sel)\n\nlemma hcomplex_add_minus_eq_minus: \"x + y = 0 \\<Longrightarrow> x = - y\"\n  for x y :: hcomplex\n  apply (drule minus_unique)\n  apply (simp add: minus_equation_iff [of x y])\n  done\n\nlemma hcomplex_i_mult_eq [simp]: \"iii * iii = - 1\"\n  by transfer (rule i_squared)\n\nlemma hcomplex_i_mult_left [simp]: \"\\<And>z. iii * (iii * z) = - z\"\n  by transfer (rule complex_i_mult_minus)\n\nlemma hcomplex_i_not_zero [simp]: \"iii \\<noteq> 0\"\n  by transfer (rule complex_i_not_zero)\n\n\nsubsection \\<open>More Multiplication Laws\\<close>\n\nlemma hcomplex_mult_minus_one: \"- 1 * z = - z\"\n  for z :: hcomplex\n  by simp\n\nlemma hcomplex_mult_minus_one_right: \"z * - 1 = - z\"\n  for z :: hcomplex\n  by simp\n\nlemma hcomplex_mult_left_cancel: \"c \\<noteq> 0 \\<Longrightarrow> c * a = c * b \\<longleftrightarrow> a = b\"\n  for a b c :: hcomplex\n  by simp\n\nlemma hcomplex_mult_right_cancel: \"c \\<noteq> 0 \\<Longrightarrow> a * c = b * c \\<longleftrightarrow> a = b\"\n  for a b c :: hcomplex\n  by simp\n\n\nsubsection \\<open>Subtraction and Division\\<close>\n\n(* TODO: delete *)\nlemma hcomplex_diff_eq_eq [simp]: \"x - y = z \\<longleftrightarrow> x = z + y\"\n  for x y z :: hcomplex\n  by (rule diff_eq_eq)\n\n\nsubsection \\<open>Embedding Properties for @{term hcomplex_of_hypreal} Map\\<close>\n\nlemma hRe_hcomplex_of_hypreal [simp]: \"\\<And>z. hRe (hcomplex_of_hypreal z) = z\"\n  by transfer (rule Re_complex_of_real)\n\nlemma hIm_hcomplex_of_hypreal [simp]: \"\\<And>z. hIm (hcomplex_of_hypreal z) = 0\"\n  by transfer (rule Im_complex_of_real)\n\nlemma hcomplex_of_hypreal_epsilon_not_zero [simp]: \"hcomplex_of_hypreal \\<epsilon> \\<noteq> 0\"\n  by (simp add: hypreal_epsilon_not_zero)\n\n\nsubsection \\<open>\\<open>HComplex\\<close> theorems\\<close>\n\nlemma hRe_HComplex [simp]: \"\\<And>x y. hRe (HComplex x y) = x\"\n  by transfer simp\n\nlemma hIm_HComplex [simp]: \"\\<And>x y. hIm (HComplex x y) = y\"\n  by transfer simp\n\nlemma hcomplex_surj [simp]: \"\\<And>z. HComplex (hRe z) (hIm z) = z\"\n  by transfer (rule complex_surj)\n\nlemma hcomplex_induct [case_names rect(*, induct type: hcomplex*)]:\n  \"(\\<And>x y. P (HComplex x y)) \\<Longrightarrow> P z\"\n  by (rule hcomplex_surj [THEN subst]) blast\n\n\nsubsection \\<open>Modulus (Absolute Value) of Nonstandard Complex Number\\<close>\n\nlemma hcomplex_of_hypreal_abs:\n  \"hcomplex_of_hypreal \\<bar>x\\<bar> = hcomplex_of_hypreal (hcmod (hcomplex_of_hypreal x))\"\n  by simp\n\nlemma HComplex_inject [simp]: \"\\<And>x y x' y'. HComplex x y = HComplex x' y' \\<longleftrightarrow> x = x' \\<and> y = y'\"\n  by transfer (rule complex.inject)\n\nlemma HComplex_add [simp]:\n  \"\\<And>x1 y1 x2 y2. HComplex x1 y1 + HComplex x2 y2 = HComplex (x1 + x2) (y1 + y2)\"\n  by transfer (rule complex_add)\n\nlemma HComplex_minus [simp]: \"\\<And>x y. - HComplex x y = HComplex (- x) (- y)\"\n  by transfer (rule complex_minus)\n\nlemma HComplex_diff [simp]:\n  \"\\<And>x1 y1 x2 y2. HComplex x1 y1 - HComplex x2 y2 = HComplex (x1 - x2) (y1 - y2)\"\n  by transfer (rule complex_diff)\n\nlemma HComplex_mult [simp]:\n  \"\\<And>x1 y1 x2 y2. HComplex x1 y1 * HComplex x2 y2 = HComplex (x1*x2 - y1*y2) (x1*y2 + y1*x2)\"\n  by transfer (rule complex_mult)\n\ntext \\<open>\\<open>HComplex_inverse\\<close> is proved below.\\<close>\n\nlemma hcomplex_of_hypreal_eq: \"\\<And>r. hcomplex_of_hypreal r = HComplex r 0\"\n  by transfer (rule complex_of_real_def)\n\nlemma HComplex_add_hcomplex_of_hypreal [simp]:\n  \"\\<And>x y r. HComplex x y + hcomplex_of_hypreal r = HComplex (x + r) y\"\n  by transfer (rule Complex_add_complex_of_real)\n\nlemma hcomplex_of_hypreal_add_HComplex [simp]:\n  \"\\<And>r x y. hcomplex_of_hypreal r + HComplex x y = HComplex (r + x) y\"\n  by transfer (rule complex_of_real_add_Complex)\n\nlemma HComplex_mult_hcomplex_of_hypreal:\n  \"\\<And>x y r. HComplex x y * hcomplex_of_hypreal r = HComplex (x * r) (y * r)\"\n  by transfer (rule Complex_mult_complex_of_real)\n\nlemma hcomplex_of_hypreal_mult_HComplex:\n  \"\\<And>r x y. hcomplex_of_hypreal r * HComplex x y = HComplex (r * x) (r * y)\"\n  by transfer (rule complex_of_real_mult_Complex)\n\nlemma i_hcomplex_of_hypreal [simp]: \"\\<And>r. iii * hcomplex_of_hypreal r = HComplex 0 r\"\n  by transfer (rule i_complex_of_real)\n\nlemma hcomplex_of_hypreal_i [simp]: \"\\<And>r. hcomplex_of_hypreal r * iii = HComplex 0 r\"\n  by transfer (rule complex_of_real_i)\n\n\nsubsection \\<open>Conjugation\\<close>\n\nlemma hcomplex_hcnj_cancel_iff [iff]: \"\\<And>x y. hcnj x = hcnj y \\<longleftrightarrow> x = y\"\n  by transfer (rule complex_cnj_cancel_iff)\n\nlemma hcomplex_hcnj_hcnj [simp]: \"\\<And>z. hcnj (hcnj z) = z\"\n  by transfer (rule complex_cnj_cnj)\n\nlemma hcomplex_hcnj_hcomplex_of_hypreal [simp]:\n  \"\\<And>x. hcnj (hcomplex_of_hypreal x) = hcomplex_of_hypreal x\"\n  by transfer (rule complex_cnj_complex_of_real)\n\nlemma hcomplex_hmod_hcnj [simp]: \"\\<And>z. hcmod (hcnj z) = hcmod z\"\n  by transfer (rule complex_mod_cnj)\n\nlemma hcomplex_hcnj_minus: \"\\<And>z. hcnj (- z) = - hcnj z\"\n  by transfer (rule complex_cnj_minus)\n\nlemma hcomplex_hcnj_inverse: \"\\<And>z. hcnj (inverse z) = inverse (hcnj z)\"\n  by transfer (rule complex_cnj_inverse)\n\nlemma hcomplex_hcnj_add: \"\\<And>w z. hcnj (w + z) = hcnj w + hcnj z\"\n  by transfer (rule complex_cnj_add)\n\nlemma hcomplex_hcnj_diff: \"\\<And>w z. hcnj (w - z) = hcnj w - hcnj z\"\n  by transfer (rule complex_cnj_diff)\n\nlemma hcomplex_hcnj_mult: \"\\<And>w z. hcnj (w * z) = hcnj w * hcnj z\"\n  by transfer (rule complex_cnj_mult)\n\nlemma hcomplex_hcnj_divide: \"\\<And>w z. hcnj (w / z) = hcnj w / hcnj z\"\n  by transfer (rule complex_cnj_divide)\n\nlemma hcnj_one [simp]: \"hcnj 1 = 1\"\n  by transfer (rule complex_cnj_one)\n\nlemma hcomplex_hcnj_zero [simp]: \"hcnj 0 = 0\"\n  by transfer (rule complex_cnj_zero)\n\nlemma hcomplex_hcnj_zero_iff [iff]: \"\\<And>z. hcnj z = 0 \\<longleftrightarrow> z = 0\"\n  by transfer (rule complex_cnj_zero_iff)\n\nlemma hcomplex_mult_hcnj: \"\\<And>z. z * hcnj z = hcomplex_of_hypreal ((hRe z)\\<^sup>2 + (hIm z)\\<^sup>2)\"\n  by transfer (rule complex_mult_cnj)\n\n\nsubsection \\<open>More Theorems about the Function @{term hcmod}\\<close>\n\nlemma hcmod_hcomplex_of_hypreal_of_nat [simp]:\n  \"hcmod (hcomplex_of_hypreal (hypreal_of_nat n)) = hypreal_of_nat n\"\n  by simp\n\nlemma hcmod_hcomplex_of_hypreal_of_hypnat [simp]:\n  \"hcmod (hcomplex_of_hypreal(hypreal_of_hypnat n)) = hypreal_of_hypnat n\"\n  by simp\n\nlemma hcmod_mult_hcnj: \"\\<And>z. hcmod (z * hcnj z) = (hcmod z)\\<^sup>2\"\n  by transfer (rule complex_mod_mult_cnj)\n\nlemma hcmod_triangle_ineq2 [simp]: \"\\<And>a b. hcmod (b + a) - hcmod b \\<le> hcmod a\"\n  by transfer (rule complex_mod_triangle_ineq2)\n\nlemma hcmod_diff_ineq [simp]: \"\\<And>a b. hcmod a - hcmod b \\<le> hcmod (a + b)\"\n  by transfer (rule norm_diff_ineq)\n\n\nsubsection \\<open>Exponentiation\\<close>\n\nlemma hcomplexpow_0 [simp]: \"z ^ 0 = 1\"\n  for z :: hcomplex\n  by (rule power_0)\n\nlemma hcomplexpow_Suc [simp]: \"z ^ (Suc n) = z * (z ^ n)\"\n  for z :: hcomplex\n  by (rule power_Suc)\n\nlemma hcomplexpow_i_squared [simp]: \"iii\\<^sup>2 = -1\"\n  by transfer (rule power2_i)\n\nlemma hcomplex_of_hypreal_pow: \"\\<And>x. hcomplex_of_hypreal (x ^ n) = hcomplex_of_hypreal x ^ n\"\n  by transfer (rule of_real_power)\n\nlemma hcomplex_hcnj_pow: \"\\<And>z. hcnj (z ^ n) = hcnj z ^ n\"\n  by transfer (rule complex_cnj_power)\n\nlemma hcmod_hcomplexpow: \"\\<And>x. hcmod (x ^ n) = hcmod x ^ n\"\n  by transfer (rule norm_power)\n\nlemma hcpow_minus:\n  \"\\<And>x n. (- x :: hcomplex) pow n = (if ( *p* even) n then (x pow n) else - (x pow n))\"\n  by transfer simp\n\nlemma hcpow_mult: \"(r * s) pow n = (r pow n) * (s pow n)\"\n  for r s :: hcomplex\n  by (fact hyperpow_mult)\n\nlemma hcpow_zero2 [simp]: \"\\<And>n. 0 pow (hSuc n) = (0::'a::semiring_1 star)\"\n  by transfer (rule power_0_Suc)\n\nlemma hcpow_not_zero [simp,intro]: \"\\<And>r n. r \\<noteq> 0 \\<Longrightarrow> r pow n \\<noteq> (0::hcomplex)\"\n  by (fact hyperpow_not_zero)\n\nlemma hcpow_zero_zero: \"r pow n = 0 \\<Longrightarrow> r = 0\"\n  for r :: hcomplex\n  by (blast intro: ccontr dest: hcpow_not_zero)\n\n\nsubsection \\<open>The Function @{term hsgn}\\<close>\n\nlemma hsgn_zero [simp]: \"hsgn 0 = 0\"\n  by transfer (rule sgn_zero)\n\nlemma hsgn_one [simp]: \"hsgn 1 = 1\"\n  by transfer (rule sgn_one)\n\nlemma hsgn_minus: \"\\<And>z. hsgn (- z) = - hsgn z\"\n  by transfer (rule sgn_minus)\n\nlemma hsgn_eq: \"\\<And>z. hsgn z = z / hcomplex_of_hypreal (hcmod z)\"\n  by transfer (rule sgn_eq)\n\nlemma hcmod_i: \"\\<And>x y. hcmod (HComplex x y) = ( *f* sqrt) (x\\<^sup>2 + y\\<^sup>2)\"\n  by transfer (rule complex_norm)\n\nlemma hcomplex_eq_cancel_iff1 [simp]:\n  \"hcomplex_of_hypreal xa = HComplex x y \\<longleftrightarrow> xa = x \\<and> y = 0\"\n  by (simp add: hcomplex_of_hypreal_eq)\n\nlemma hcomplex_eq_cancel_iff2 [simp]:\n  \"HComplex x y = hcomplex_of_hypreal xa \\<longleftrightarrow> x = xa \\<and> y = 0\"\n  by (simp add: hcomplex_of_hypreal_eq)\n\nlemma HComplex_eq_0 [simp]: \"\\<And>x y. HComplex x y = 0 \\<longleftrightarrow> x = 0 \\<and> y = 0\"\n  by transfer (rule Complex_eq_0)\n\nlemma HComplex_eq_1 [simp]: \"\\<And>x y. HComplex x y = 1 \\<longleftrightarrow> x = 1 \\<and> y = 0\"\n  by transfer (rule Complex_eq_1)\n\nlemma i_eq_HComplex_0_1: \"iii = HComplex 0 1\"\n  by transfer (simp add: complex_eq_iff)\n\nlemma HComplex_eq_i [simp]: \"\\<And>x y. HComplex x y = iii \\<longleftrightarrow> x = 0 \\<and> y = 1\"\n  by transfer (rule Complex_eq_i)\n\nlemma hRe_hsgn [simp]: \"\\<And>z. hRe (hsgn z) = hRe z / hcmod z\"\n  by transfer (rule Re_sgn)\n\nlemma hIm_hsgn [simp]: \"\\<And>z. hIm (hsgn z) = hIm z / hcmod z\"\n  by transfer (rule Im_sgn)\n\nlemma HComplex_inverse: \"\\<And>x y. inverse (HComplex x y) = HComplex (x / (x\\<^sup>2 + y\\<^sup>2)) (- y / (x\\<^sup>2 + y\\<^sup>2))\"\n  by transfer (rule complex_inverse)\n\nlemma hRe_mult_i_eq[simp]: \"\\<And>y. hRe (iii * hcomplex_of_hypreal y) = 0\"\n  by transfer simp\n\nlemma hIm_mult_i_eq [simp]: \"\\<And>y. hIm (iii * hcomplex_of_hypreal y) = y\"\n  by transfer simp\n\nlemma hcmod_mult_i [simp]: \"\\<And>y. hcmod (iii * hcomplex_of_hypreal y) = \\<bar>y\\<bar>\"\n  by transfer (simp add: norm_complex_def)\n\nlemma hcmod_mult_i2 [simp]: \"\\<And>y. hcmod (hcomplex_of_hypreal y * iii) = \\<bar>y\\<bar>\"\n  by transfer (simp add: norm_complex_def)\n\n\nsubsubsection \\<open>\\<open>harg\\<close>\\<close>\n\nlemma cos_harg_i_mult_zero [simp]: \"\\<And>y. y \\<noteq> 0 \\<Longrightarrow> ( *f* cos) (harg (HComplex 0 y)) = 0\"\n  by transfer simp\n\nlemma hcomplex_of_hypreal_zero_iff [simp]: \"\\<And>y. hcomplex_of_hypreal y = 0 \\<longleftrightarrow> y = 0\"\n  by transfer (rule of_real_eq_0_iff)\n\n\nsubsection \\<open>Polar Form for Nonstandard Complex Numbers\\<close>\n\nlemma complex_split_polar2: \"\\<forall>n. \\<exists>r a. (z n) = complex_of_real r * Complex (cos a) (sin a)\"\n  by (auto intro: complex_split_polar)\n\nlemma hcomplex_split_polar:\n  \"\\<And>z. \\<exists>r a. z = hcomplex_of_hypreal r * (HComplex (( *f* cos) a) (( *f* sin) a))\"\n  by transfer (simp add: complex_split_polar)\n\nlemma hcis_eq:\n  \"\\<And>a. hcis a = hcomplex_of_hypreal (( *f* cos) a) + iii * hcomplex_of_hypreal (( *f* sin) a)\"\n  by transfer (simp add: complex_eq_iff)\n\nlemma hrcis_Ex: \"\\<And>z. \\<exists>r a. z = hrcis r a\"\n  by transfer (rule rcis_Ex)\n\nlemma hRe_hcomplex_polar [simp]:\n  \"\\<And>r a. hRe (hcomplex_of_hypreal r * HComplex (( *f* cos) a) (( *f* sin) a)) = r * ( *f* cos) a\"\n  by transfer simp\n\nlemma hRe_hrcis [simp]: \"\\<And>r a. hRe (hrcis r a) = r * ( *f* cos) a\"\n  by transfer (rule Re_rcis)\n\nlemma hIm_hcomplex_polar [simp]:\n  \"\\<And>r a. hIm (hcomplex_of_hypreal r * HComplex (( *f* cos) a) (( *f* sin) a)) = r * ( *f* sin) a\"\n  by transfer simp\n\nlemma hIm_hrcis [simp]: \"\\<And>r a. hIm (hrcis r a) = r * ( *f* sin) a\"\n  by transfer (rule Im_rcis)\n\nlemma hcmod_unit_one [simp]: \"\\<And>a. hcmod (HComplex (( *f* cos) a) (( *f* sin) a)) = 1\"\n  by transfer (simp add: cmod_unit_one)\n\nlemma hcmod_complex_polar [simp]:\n  \"\\<And>r a. hcmod (hcomplex_of_hypreal r * HComplex (( *f* cos) a) (( *f* sin) a)) = \\<bar>r\\<bar>\"\n  by transfer (simp add: cmod_complex_polar)\n\nlemma hcmod_hrcis [simp]: \"\\<And>r a. hcmod(hrcis r a) = \\<bar>r\\<bar>\"\n  by transfer (rule complex_mod_rcis)\n\ntext \\<open>\\<open>(r1 * hrcis a) * (r2 * hrcis b) = r1 * r2 * hrcis (a + b)\\<close>\\<close>\n\nlemma hcis_hrcis_eq: \"\\<And>a. hcis a = hrcis 1 a\"\n  by transfer (rule cis_rcis_eq)\ndeclare hcis_hrcis_eq [symmetric, simp]\n\nlemma hrcis_mult: \"\\<And>a b r1 r2. hrcis r1 a * hrcis r2 b = hrcis (r1 * r2) (a + b)\"\n  by transfer (rule rcis_mult)\n\nlemma hcis_mult: \"\\<And>a b. hcis a * hcis b = hcis (a + b)\"\n  by transfer (rule cis_mult)\n\nlemma hcis_zero [simp]: \"hcis 0 = 1\"\n  by transfer (rule cis_zero)\n\nlemma hrcis_zero_mod [simp]: \"\\<And>a. hrcis 0 a = 0\"\n  by transfer (rule rcis_zero_mod)\n\nlemma hrcis_zero_arg [simp]: \"\\<And>r. hrcis r 0 = hcomplex_of_hypreal r\"\n  by transfer (rule rcis_zero_arg)\n\nlemma hcomplex_i_mult_minus [simp]: \"\\<And>x. iii * (iii * x) = - x\"\n  by transfer (rule complex_i_mult_minus)\n\nlemma hcomplex_i_mult_minus2 [simp]: \"iii * iii * x = - x\"\n  by simp\n\nlemma hcis_hypreal_of_nat_Suc_mult:\n  \"\\<And>a. hcis (hypreal_of_nat (Suc n) * a) = hcis a * hcis (hypreal_of_nat n * a)\"\n  by transfer (simp add: distrib_right cis_mult)\n\nlemma NSDeMoivre: \"\\<And>a. (hcis a) ^ n = hcis (hypreal_of_nat n * a)\"\n  by transfer (rule DeMoivre)\n\nlemma hcis_hypreal_of_hypnat_Suc_mult:\n  \"\\<And>a n. hcis (hypreal_of_hypnat (n + 1) * a) = hcis a * hcis (hypreal_of_hypnat n * a)\"\n  by transfer (simp add: distrib_right cis_mult)\n\nlemma NSDeMoivre_ext: \"\\<And>a n. (hcis a) pow n = hcis (hypreal_of_hypnat n * a)\"\n  by transfer (rule DeMoivre)\n\nlemma NSDeMoivre2: \"\\<And>a r. (hrcis r a) ^ n = hrcis (r ^ n) (hypreal_of_nat n * a)\"\n  by transfer (rule DeMoivre2)\n\nlemma DeMoivre2_ext: \"\\<And>a r n. (hrcis r a) pow n = hrcis (r pow n) (hypreal_of_hypnat n * a)\"\n  by transfer (rule DeMoivre2)\n\nlemma hcis_inverse [simp]: \"\\<And>a. inverse (hcis a) = hcis (- a)\"\n  by transfer (rule cis_inverse)\n\nlemma hrcis_inverse: \"\\<And>a r. inverse (hrcis r a) = hrcis (inverse r) (- a)\"\n  by transfer (simp add: rcis_inverse inverse_eq_divide [symmetric])\n\nlemma hRe_hcis [simp]: \"\\<And>a. hRe (hcis a) = ( *f* cos) a\"\n  by transfer simp\n\nlemma hIm_hcis [simp]: \"\\<And>a. hIm (hcis a) = ( *f* sin) a\"\n  by transfer simp\n\nlemma cos_n_hRe_hcis_pow_n: \"( *f* cos) (hypreal_of_nat n * a) = hRe (hcis a ^ n)\"\n  by (simp add: NSDeMoivre)\n\nlemma sin_n_hIm_hcis_pow_n: \"( *f* sin) (hypreal_of_nat n * a) = hIm (hcis a ^ n)\"\n  by (simp add: NSDeMoivre)\n\nlemma cos_n_hRe_hcis_hcpow_n: \"( *f* cos) (hypreal_of_hypnat n * a) = hRe (hcis a pow n)\"\n  by (simp add: NSDeMoivre_ext)\n\nlemma sin_n_hIm_hcis_hcpow_n: \"( *f* sin) (hypreal_of_hypnat n * a) = hIm (hcis a pow n)\"\n  by (simp add: NSDeMoivre_ext)\n\nlemma hExp_add: \"\\<And>a b. hExp (a + b) = hExp a * hExp b\"\n  by transfer (rule exp_add)\n\n\nsubsection \\<open>@{term hcomplex_of_complex}: the Injection from type @{typ complex} to to @{typ hcomplex}\\<close>\n\nlemma hcomplex_of_complex_i: \"iii = hcomplex_of_complex \\<i>\"\n  by (rule iii_def)\n\nlemma hRe_hcomplex_of_complex: \"hRe (hcomplex_of_complex z) = hypreal_of_real (Re z)\"\n  by transfer (rule refl)\n\nlemma hIm_hcomplex_of_complex: \"hIm (hcomplex_of_complex z) = hypreal_of_real (Im z)\"\n  by transfer (rule refl)\n\nlemma hcmod_hcomplex_of_complex: \"hcmod (hcomplex_of_complex x) = hypreal_of_real (cmod x)\"\n  by transfer (rule refl)\n\n\nsubsection \\<open>Numerals and Arithmetic\\<close>\n\nlemma hcomplex_of_hypreal_eq_hcomplex_of_complex:\n  \"hcomplex_of_hypreal (hypreal_of_real x) = hcomplex_of_complex (complex_of_real x)\"\n  by transfer (rule refl)\n\nlemma hcomplex_hypreal_numeral:\n  \"hcomplex_of_complex (numeral w) = hcomplex_of_hypreal(numeral w)\"\n  by transfer (rule of_real_numeral [symmetric])\n\nlemma hcomplex_hypreal_neg_numeral:\n  \"hcomplex_of_complex (- numeral w) = hcomplex_of_hypreal(- numeral w)\"\n  by transfer (rule of_real_neg_numeral [symmetric])\n\nlemma hcomplex_numeral_hcnj [simp]: \"hcnj (numeral v :: hcomplex) = numeral v\"\n  by transfer (rule complex_cnj_numeral)\n\nlemma hcomplex_numeral_hcmod [simp]: \"hcmod (numeral v :: hcomplex) = (numeral v :: hypreal)\"\n  by transfer (rule norm_numeral)\n\nlemma hcomplex_neg_numeral_hcmod [simp]: \"hcmod (- numeral v :: hcomplex) = (numeral v :: hypreal)\"\n  by transfer (rule norm_neg_numeral)\n\nlemma hcomplex_numeral_hRe [simp]: \"hRe (numeral v :: hcomplex) = numeral v\"\n  by transfer (rule complex_Re_numeral)\n\nlemma hcomplex_numeral_hIm [simp]: \"hIm (numeral v :: hcomplex) = 0\"\n  by transfer (rule complex_Im_numeral)\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/Nonstandard_Analysis/NSComplex.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.851952809486198, "lm_q2_score": 0.8354835411997897, "lm_q1q2_score": 0.7117925502046385}}
{"text": "section \\<open>Utility Definitions and Properties\\<close>\n\ntext \\<open>This file contains various definitions and lemmata not closely related to finite state\n      machines or testing.\\<close>\n\n\ntheory Util\n  imports Main HOL.Finite_Set\nbegin\n\nsubsection \\<open>Converting Sets to Maps\\<close>\n\ntext \\<open>This subsection introduces a function @{text \"set_as_map\"} that transforms a set of \n      @{text \"('a \\<times> 'b)\"} tuples to a map mapping each first value @{text \"x\"} of the contained tuples\n      to all second values @{text \"y\"} such that @{text \"(x,y)\"} is contained in the set.\\<close>\n\ndefinition set_as_map :: \"('a \\<times> 'c) set \\<Rightarrow> ('a \\<Rightarrow> 'c set option)\" where\n  \"set_as_map s = (\\<lambda> x . if (\\<exists> z . (x,z) \\<in> s) then Some {z . (x,z) \\<in> s} else None)\"\n\n\nlemma set_as_map_code[code] : \n  \"set_as_map (set xs) = (foldl (\\<lambda> m (x,z) . case m x of\n                                                None \\<Rightarrow> m (x \\<mapsto> {z}) |\n                                                Some zs \\<Rightarrow> m (x \\<mapsto>  (insert z zs)))\n                                Map.empty\n                                xs)\"\nproof - \n  let ?f = \"\\<lambda> xs . (foldl (\\<lambda> m (x,z) . case m x of\n                                          None \\<Rightarrow> m (x \\<mapsto> {z}) |\n                                          Some zs \\<Rightarrow> m (x \\<mapsto>  (insert z zs)))\n                          Map.empty\n                          xs)\"\n  have \"(?f xs) = (\\<lambda> x . if (\\<exists> z . (x,z) \\<in> set xs) then Some {z . (x,z) \\<in> set xs} else None)\"\n  proof (induction xs rule: rev_induct)\n    case Nil\n    then show ?case by auto\n  next\n    case (snoc xz xs)\n    then obtain x z where \"xz = (x,z)\" \n      by (metis (mono_tags, hide_lams) surj_pair)\n\n    have *: \"(?f (xs@[(x,z)])) = (case (?f xs) x of\n                                None \\<Rightarrow> (?f xs) (x \\<mapsto> {z}) |\n                                Some zs \\<Rightarrow> (?f xs) (x \\<mapsto> (insert z zs)))\"\n      by auto\n\n    then show ?case proof (cases \"(?f xs) x\")\n      case None\n      then have **: \"(?f (xs@[(x,z)])) = (?f xs) (x \\<mapsto> {z})\" using * by auto\n\n      have scheme: \"\\<And> m k v . (m(k \\<mapsto> v)) = (\\<lambda>k' . if k' = k then Some v else m k')\"\n        by auto\n\n      have m1: \"(?f (xs@[(x,z)])) = (\\<lambda> x' . if x' = x then Some {z} else (?f xs) x')\"\n        unfolding ** \n        unfolding scheme by force\n\n      have \"(\\<lambda> x . if (\\<exists> z . (x,z) \\<in> set xs) then Some {z . (x,z) \\<in> set xs} else None) x = None\"\n        using None snoc by auto\n      then have \"\\<not>(\\<exists> z . (x,z) \\<in> set xs)\"\n        by (metis (mono_tags, lifting) option.distinct(1))\n      then have \"(\\<exists> z . (x,z) \\<in> set (xs@[(x,z)]))\" and \"{z' . (x,z') \\<in> set (xs@[(x,z)])} = {z}\"\n        by auto\n      then have m2: \"(\\<lambda> x' . if (\\<exists> z' . (x',z') \\<in> set (xs@[(x,z)])) \n                                then Some {z' . (x',z') \\<in> set (xs@[(x,z)])} \n                                else None)\n                   = (\\<lambda> x' . if x' = x \n                                then Some {z} else (\\<lambda> x . if (\\<exists> z . (x,z) \\<in> set xs) \n                                                            then Some {z . (x,z) \\<in> set xs} \n                                                            else None) x')\"\n        by force\n\n      show ?thesis using m1 m2 snoc\n        using \\<open>xz = (x, z)\\<close> by presburger\n    next\n      case (Some zs)\n      then have **: \"(?f (xs@[(x,z)])) = (?f xs) (x \\<mapsto> (insert z zs))\" using * by auto\n      have scheme: \"\\<And> m k v . (m(k \\<mapsto> v)) = (\\<lambda>k' . if k' = k then Some v else m k')\"\n        by auto\n\n      have m1: \"(?f (xs@[(x,z)])) = (\\<lambda> x' . if x' = x then Some (insert z zs) else (?f xs) x')\"\n        unfolding ** \n        unfolding scheme by force\n\n      have \"(\\<lambda> x . if (\\<exists> z . (x,z) \\<in> set xs) then Some {z . (x,z) \\<in> set xs} else None) x = Some zs\"\n        using Some snoc by auto\n      then have \"(\\<exists> z . (x,z) \\<in> set xs)\"\n        unfolding case_prod_conv using  option.distinct(2) by metis\n      then have \"(\\<exists> z . (x,z) \\<in> set (xs@[(x,z)]))\" by simp\n\n      have \"{z' . (x,z') \\<in> set (xs@[(x,z)])} = insert z zs\"\n      proof -\n        have \"Some {z . (x,z) \\<in> set xs} = Some zs\"\n          using \\<open>(\\<lambda> x . if (\\<exists> z . (x,z) \\<in> set xs) then Some {z . (x,z) \\<in> set xs} else None) x \n                  = Some zs\\<close>\n          unfolding case_prod_conv using  option.distinct(2) by metis\n        then have \"{z . (x,z) \\<in> set xs} = zs\" by auto\n        then show ?thesis by auto\n      qed\n\n      have \"\\<And> a  . (\\<lambda> x' . if (\\<exists> z' . (x',z') \\<in> set (xs@[(x,z)])) \n                              then Some {z' . (x',z') \\<in> set (xs@[(x,z)])} else None) a\n                   = (\\<lambda> x' . if x' = x \n                              then Some (insert z zs) \n                              else (\\<lambda> x . if (\\<exists> z . (x,z) \\<in> set xs) \n                                            then Some {z . (x,z) \\<in> set xs} else None) x') a\" \n      proof -\n        fix a show \"(\\<lambda> x' . if (\\<exists> z' . (x',z') \\<in> set (xs@[(x,z)])) \n                              then Some {z' . (x',z') \\<in> set (xs@[(x,z)])} else None) a\n                   = (\\<lambda> x' . if x' = x \n                              then Some (insert z zs) \n                              else (\\<lambda> x . if (\\<exists> z . (x,z) \\<in> set xs) \n                                            then Some {z . (x,z) \\<in> set xs} else None) x') a\"\n        using \\<open>{z' . (x,z') \\<in> set (xs@[(x,z)])} = insert z zs\\<close> \\<open>(\\<exists> z . (x,z) \\<in> set (xs@[(x,z)]))\\<close>\n        by (cases \"a = x\"; auto)\n      qed\n\n      then have m2: \"(\\<lambda> x' . if (\\<exists> z' . (x',z') \\<in> set (xs@[(x,z)])) \n                                then Some {z' . (x',z') \\<in> set (xs@[(x,z)])} else None)\n                   = (\\<lambda> x' . if x' = x \n                                then Some (insert z zs) \n                                else (\\<lambda> x . if (\\<exists> z . (x,z) \\<in> set xs) \n                                              then Some {z . (x,z) \\<in> set xs} else None) x')\"\n        by auto\n\n\n      show ?thesis using m1 m2 snoc\n        using \\<open>xz = (x, z)\\<close> by presburger\n    qed\n  qed\n\n  then show ?thesis\n    unfolding set_as_map_def by simp\nqed\n\n\nabbreviation \"member_option x ms \\<equiv> (case ms of None \\<Rightarrow> False | Some xs \\<Rightarrow> x \\<in> xs)\"\nnotation member_option (\"(_\\<in>\\<^sub>o_)\" [1000] 1000)\n\nabbreviation(input) \"lookup_with_default f d \\<equiv> (\\<lambda> x . case f x of None \\<Rightarrow> d | Some xs \\<Rightarrow> xs)\"\nabbreviation(input) \"m2f f \\<equiv> lookup_with_default f {}\" \n\nabbreviation(input) \"lookup_with_default_by f g d \\<equiv> (\\<lambda> x . case f x of None \\<Rightarrow> g d | Some xs \\<Rightarrow> g xs)\"\nabbreviation(input) \"m2f_by g f \\<equiv> lookup_with_default_by f g {}\" \n\nlemma m2f_by_from_m2f :\n  \"(m2f_by g f xs) = g (m2f f xs)\"\n  by (simp add: option.case_eq_if) \n\n\nlemma set_as_map_containment :\n  assumes \"(x,y) \\<in> zs\"\n  shows \"y \\<in> (m2f (set_as_map zs)) x\"\n  using assms unfolding set_as_map_def\n  by auto \n\nlemma set_as_map_elem :\n  assumes \"y \\<in> m2f (set_as_map xs) x\" \nshows \"(x,y) \\<in> xs\" \nusing assms unfolding set_as_map_def\nproof -\n  assume a1: \"y \\<in> (case if \\<exists>z. (x, z) \\<in> xs then Some {z. (x, z) \\<in> xs} else None of None \\<Rightarrow> {} | Some xs \\<Rightarrow> xs)\"\n  then have \"\\<exists>a. (x, a) \\<in> xs\"\n    using all_not_in_conv by fastforce\n  then show ?thesis\n    using a1 by simp\nqed \n\n\nsubsection \\<open>Utility Lemmata for existing functions on lists\\<close>\n\nsubsubsection \\<open>Utility Lemmata for @{text \"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)\" \n           and   \"(sort xs) ! i = x\" \n           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\nsubsubsection \\<open>Utility Lemmata for @{text \"filter\"}\\<close>\n\nlemma filter_take_length :\n  \"length (filter P (take i xs)) \\<le> length (filter P xs)\"\n  by (metis append_take_drop_id filter_append le0 le_add_same_cancel1 length_append)\n\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\nlemma filter_map_elem : \"t \\<in> set (map g (filter f xs)) \\<Longrightarrow> \\<exists> x \\<in> set xs . f x \\<and> t = g x\" \n  by auto\n\n\n\nsubsubsection \\<open>Utility Lemmata for @{text \"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\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 : \n  \"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] \n        lists_of_length_length[of _ xs k] \n        lists_of_length_elems[of _ xs k] \n  by blast\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\n\nlemma cartesian_product_list_set : \n  \"set (cartesian_product_list xs ys) = {(x,y) | x y . x \\<in> set xs \\<and> y \\<in> set ys}\"\n  by auto\n\nlemma cartesian_product_list_set' : \"set (cartesian_product_list xs ys) = (set xs) \\<times> (set ys)\"\n  by auto\n\n\n\nsubsubsection \\<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\nlemma generate_selector_lists_set : \n  \"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]))) \n          = (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 \n        map_append snoc.prems snoc_eq_iff_butlast zip_append2)\n  then have *: \"set (map fst (filter snd (zip ms (bs @ [b])))) \n              = 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} \n        = {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} \n                  = {ms ! i |i. i < length bs \\<and> (bs @ [b]) ! i} \n                    \\<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} \n                      = {?ms ! i |i. i < length bs \\<and> bs ! i} \n                        \\<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))) \n                \\<union> set (map fst (filter snd (zip [?m] [b])))\n             = {butlast ms ! i |i. i < length bs \\<and> bs ! i} \n                \\<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)))\" \n    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} \n              = {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} \n              = 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> \n    by auto\n  moreover have \"{ms ! j |j. j < length bs \\<and> bs ! j} \n                = {ms ! j |j. j < length bs \\<and> j = i \\<and> bs ! j} \n                    \\<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} \n                    = 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} \n            = {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]) \n                      \\<and> bs[i := True] ! ia} \n                          = insert a {ms ! j |j. j < length (bs[i := True]) \n                              \\<and> j \\<noteq> i \\<and> bs[i := True] ! j}\\<close> \n    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> \n          \\<open>set xs = set (map fst (filter snd (zip ms bs)))\\<close> \n    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\n\nsubsubsection \\<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) = \n    concat (map (\\<lambda> xy' . map (\\<lambda> xys' . xy' # xys') (generate_choices xyss)) \n                ((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))\" \n    using assms(1,2) by auto\n  ultimately show ?thesis \n    by auto\nqed\n\n\nlemma generate_choices_hd_tl : \n  \"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> (tl cs \\<in> set (generate_choices xyss)))\"\nproof (induction xyss arbitrary: cs xys)\n  case Nil\n  have \"(cs \\<in> set (generate_choices [xys])) \n          = (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))) \n               \\<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 [])) \n                \\<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] \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> 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) \n                      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) \n        \\<Longrightarrow> fst (hd cs) = fst xys \n        \\<Longrightarrow> (snd (hd cs) = None \\<or> (snd (hd cs) \\<noteq> None \\<and> the (snd (hd cs)) \\<in> set (snd xys))) \n        \\<Longrightarrow> (tl cs \\<in> set (generate_choices (a#xyss))) \n        \\<Longrightarrow> cs \\<in> set (generate_choices (xys#a#xyss))\"\n  proof -\n    assume \"length cs = length (xys#a#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 \"(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> \n            \\<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) \n            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\"] \n            concat_map_hd_tl_elem[OF \\<open>(hd cs) \\<in> set ((fst xys, None) # (map (\\<lambda> y . (fst xys, Some y)) (snd xys)))\\<close> \n                                     \\<open>(tl cs \\<in> set (generate_choices (a#xyss)))\\<close> \n                                     \\<open>length cs > 0\\<close>] \n      by auto\n  qed\n\n  moreover have \"cs \\<in> set (generate_choices (xys#a#xyss)) \n                \\<Longrightarrow> length cs = length (xys#a#xyss) \n                    \\<and> fst (hd cs) = fst xys \n                    \\<and> ((snd (hd cs) = None \\<or> (snd (hd cs) \\<noteq> None \n                    \\<and> the (snd (hd cs)) \\<in> set (snd xys)))) \n                    \\<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 \n                                \\<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\"] \n      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))) \n    = (\\<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) \n              \\<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))) \n                  \\<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)))\" \n             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))) \n          = (\\<forall> j . ((j < length (ys@xs) \\<and> j \\<ge> length ys) \\<longrightarrow> P ((ys@xs) ! j) ((ys'@xs') ! j)))\"\nproof -\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) \n                  \\<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)) \n                  \\<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 : \n  \"cs \\<in> set (generate_choices xyss) \n    = (length cs = length xyss \n        \\<and> (\\<forall> i < length cs . (fst (cs ! i)) = (fst (xyss ! i)) \n        \\<and> ((snd (cs ! i)) = None \n            \\<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  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> (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 \n            \\<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 \n            \\<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 \n                    \\<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 \n                    \\<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 \n            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 \n                        \\<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)\" \n                                        \"\\<lambda> x y . fst x = fst y \n                                                  \\<and> (snd x = None \n                                                      \\<or> snd x \\<noteq> None \\<and> the (snd x) \\<in> set (snd y))\", \n                                     OF \\<open>length xyss = length (tl cs)\\<close> \n                                        \\<open>length (xys # xyss) = length ([hd cs] @ tl cs)\\<close>]\n      by (metis (no_types, lifting) One_nat_def Suc_pred \n            \\<open>length (xys # xyss) = length ([hd cs] @ tl cs)\\<close> \\<open>length xyss = length (tl cs)\\<close> \n            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 \n                \\<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))))) \n                  \\<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 \n        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 \n    then Some 0 \n    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) \n                  = (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)\" \n        using Cons.IH[OF \\<open>find_index f xs = Some k'\\<close>] \\<open>k = Suc k'\\<close> \n        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>] \\<open>k = Suc k'\\<close> False less_Suc_eq_0_disj \n        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 non_distinct_repetition_indices_rev :\n  assumes \"i < j\" and \"j < length xs\" and \"xs ! i = xs ! j\"\n  shows \"\\<not> distinct xs\"\n  using assms nth_eq_iff_index_eq by fastforce \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 \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> \n                  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 snoc.prems(3)\n                    length_append_singleton less_SucE not_less_eq nth_append snoc.prems(1))\n            moreover have le2: \"(xs @ [a]) ! (j -1) < (xs @ [a]) ! j\"\n              using snoc.prems(2,3) 2 less_trans\n              by (metis (full_types) One_nat_def Suc_diff_Suc diff_zero less_numeral_extra(1))  \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\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) \n                    \\<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\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\nfun prefixes :: \"'a list \\<Rightarrow> 'a list list\" where\n  \"prefixes [] = [[]]\" |\n  \"prefixes xs = (prefixes (butlast xs)) @ [xs]\"\n\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\nfun is_prefix :: \"'a list \\<Rightarrow> 'a list \\<Rightarrow> bool\" where\n  \"is_prefix [] _ = True\" |\n  \"is_prefix (x#xs) [] = False\" |\n  \"is_prefix (x#xs) (y#ys) = (x = y \\<and> is_prefix xs ys)\" \n\nlemma is_prefix_prefix : \"is_prefix xs ys = (\\<exists> xs' . ys = xs@xs')\"\nproof (induction xs arbitrary: ys)\n  case Nil\n  then show ?case by auto\nnext\n  case (Cons x xs)\n  show ?case proof (cases \"is_prefix (x#xs) ys\")\n    case True\n    then show ?thesis using Cons.IH\n      by (metis append_Cons is_prefix.simps(2) is_prefix.simps(3) neq_Nil_conv) \n  next\n    case False\n    then show ?thesis\n      using Cons.IH by auto \n  qed\nqed\n\n\nfun add_prefixes :: \"'a list list \\<Rightarrow> 'a list list\" where\n  \"add_prefixes xs = concat (map prefixes xs)\"\n\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)} \n              \\<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)} \n              \\<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\nlemma prefixes_set_ob :\n  assumes \"xs \\<in> set (prefixes xss)\"\n  obtains xs' where \"xss = xs@xs'\"\n  using assms unfolding prefixes_set\n  by auto \n\n\n\nsubsubsection \\<open>Pairs of Distinct Prefixes\\<close>\n\nfun prefix_pairs :: \"'a list \\<Rightarrow> ('a list \\<times> 'a list) list\" \n  where \"prefix_pairs [] = []\" |\n        \"prefix_pairs xs = prefix_pairs (butlast xs) @ (map (\\<lambda> ys. (ys,xs)) (butlast (prefixes xs)))\"\n\nvalue \"prefix_pairs [1,2,3::nat]\"\n\n\n\n\nlemma prefixes_butlast :\n  \"set (butlast (prefixes xs)) = {ys . \\<exists> zs . ys@zs = xs \\<and> zs \\<noteq> []}\"\nproof (cases xs rule: rev_cases)\n  case Nil\n  then show ?thesis by auto\nnext\n  case (snoc ys y)\n  \n  have \"prefixes (ys@[y]) = (prefixes ys) @ [ys@[y]]\"\n    by (metis prefixes.elims snoc_eq_iff_butlast)\n  then have \"butlast (prefixes xs) = prefixes ys\"\n    using snoc by auto\n  then have \"set (butlast (prefixes xs)) = {xs'. \\<exists>xs''. xs' @ xs'' = ys}\"\n    using prefixes_set by auto\n  also have \"... = {xs'. \\<exists>xs''. xs' @ xs'' = ys@[y] \\<and> xs'' \\<noteq> []}\"\n    by (metis (no_types, lifting) Nil_is_append_conv append.assoc butlast_append butlast_snoc not_Cons_self2)\n  finally show ?thesis\n    using snoc by simp\nqed\n\n\nlemma prefix_pairs_set :\n  \"set (prefix_pairs xs) = {(zs,ys) | zs ys . \\<exists> xs1 xs2 . zs@xs1 = ys \\<and> ys@xs2 = xs \\<and> xs1 \\<noteq> []}\"  \nproof (induction xs rule: rev_induct)\n  case Nil\n  then show ?case by auto \nnext\n  case (snoc x xs)\n  have \"prefix_pairs (xs @ [x]) = prefix_pairs (butlast (xs @ [x])) @ (map (\\<lambda> ys. (ys,(xs @ [x]))) (butlast (prefixes (xs @ [x]))))\"\n    by (cases \"(xs @ [x])\"; auto)\n  then have *: \"prefix_pairs (xs @ [x]) = prefix_pairs xs @ (map (\\<lambda> ys. (ys,(xs @ [x]))) (butlast (prefixes (xs @ [x]))))\"\n    by auto\n\n  have \"set (prefix_pairs xs) = {(zs, ys) |zs ys. \\<exists>xs1 xs2. zs @ xs1 = ys \\<and> ys @ xs2 = xs \\<and> xs1 \\<noteq> []}\"\n    using snoc.IH by assumption\n  then have \"set (prefix_pairs xs) = {(zs, ys) |zs ys. \\<exists>xs1 xs2. zs @ xs1 = ys \\<and> ys @ xs2 @ [x] = xs@[x] \\<and> xs1 \\<noteq> []}\"\n    by auto\n  also have \"... = {(zs, ys) |zs ys. \\<exists>xs1 xs2. zs @ xs1 = ys \\<and> ys @ xs2 = xs @[x] \\<and> xs1 \\<noteq> [] \\<and> xs2 \\<noteq> []}\" \n  proof -\n    let ?P1 = \"\\<lambda> zs ys . (\\<exists>xs1 xs2. zs @ xs1 = ys \\<and> ys @ xs2 @ [x] = xs@[x] \\<and> xs1 \\<noteq> [])\"\n    let ?P2 = \"\\<lambda> zs ys . (\\<exists>xs1 xs2. zs @ xs1 = ys \\<and> ys @ xs2 = xs @[x] \\<and> xs1 \\<noteq> [] \\<and> xs2 \\<noteq> [])\"\n\n    have \"\\<And> ys zs . ?P2 zs ys \\<Longrightarrow> ?P1 zs ys\"\n      by (metis append_assoc butlast_append butlast_snoc)\n    then have \"\\<And> ys zs . ?P1 ys zs = ?P2 ys zs\"\n      by blast\n    then show ?thesis by force           \n  qed\n  finally have \"set (prefix_pairs xs) = {(zs, ys) |zs ys. \\<exists>xs1 xs2. zs @ xs1 = ys \\<and> ys @ xs2 = xs @ [x] \\<and> xs1 \\<noteq> [] \\<and> xs2 \\<noteq> []}\"\n    by assumption\n\n  moreover have \"set (map (\\<lambda> ys. (ys,(xs @ [x]))) (butlast (prefixes (xs @ [x])))) = {(zs, ys) |zs ys. \\<exists>xs1 xs2. zs @ xs1 = ys \\<and> ys @ xs2 = xs @ [x] \\<and> xs1 \\<noteq> [] \\<and> xs2 = []}\"\n    using prefixes_butlast[of \"xs@[x]\"] by force\n\n  ultimately show ?case using * by force\nqed\n\nlemma prefix_pairs_set_alt :\n  \"set (prefix_pairs xs) = {(xs1,xs1@xs2) | xs1 xs2 . xs2 \\<noteq> [] \\<and> (\\<exists> xs3 . xs1@xs2@xs3 = xs)}\"\n  unfolding prefix_pairs_set by auto\n\n\n\n\nsubsection \\<open>Calculating Distinct Non-Reflexive Pairs over List Elements\\<close> \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\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) \n    \\<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>Finite Linear Order From List Positions\\<close>\n\nfun linear_order_from_list_position' :: \"'a list \\<Rightarrow> ('a \\<times> 'a) list\" where\n  \"linear_order_from_list_position' [] = []\" |\n  \"linear_order_from_list_position' (x#xs) \n      = (x,x) # (map (\\<lambda> y . (x,y)) xs) @ (linear_order_from_list_position' xs)\"\n\nfun linear_order_from_list_position :: \"'a list \\<Rightarrow> ('a \\<times> 'a) list\" where\n  \"linear_order_from_list_position xs = linear_order_from_list_position' (remdups xs)\"\n\n\n\nlemma linear_order_from_list_position_set :\n  \"set (linear_order_from_list_position xs) \n    = (set (map (\\<lambda> x . (x,x)) xs)) \\<union> set (non_sym_dist_pairs xs)\"\n  by (induction xs; auto)\n\nlemma linear_order_from_list_position_total: \n  \"total_on (set xs) (set (linear_order_from_list_position xs))\"\n  unfolding linear_order_from_list_position_set\n  using non_sym_dist_pairs_elems[of _ xs]\n  by (meson UnI2 total_onI)\n\nlemma linear_order_from_list_position_refl: \n  \"refl_on (set xs) (set (linear_order_from_list_position xs))\"  \nproof \n  show \"set (linear_order_from_list_position xs) \\<subseteq> set xs \\<times> set xs\"\n    unfolding linear_order_from_list_position_set\n    using non_sym_dist_pairs_subset[of xs] by auto\n  show \"\\<And>x. x \\<in> set xs \\<Longrightarrow> (x, x) \\<in> set (linear_order_from_list_position xs)\"\n    unfolding linear_order_from_list_position_set\n    using non_sym_dist_pairs_subset[of xs] by auto\nqed\n\nlemma linear_order_from_list_position_antisym: \n  \"antisym (set (linear_order_from_list_position xs))\"\nproof \n  fix x y assume \"(x, y) \\<in> set (linear_order_from_list_position xs)\" \n          and    \"(y, x) \\<in> set (linear_order_from_list_position xs)\"\n  then have \"(x, y) \\<in> set (map (\\<lambda>x. (x, x)) xs) \\<union> set (non_sym_dist_pairs xs)\"\n       and  \"(y, x) \\<in> set (map (\\<lambda>x. (x, x)) xs) \\<union> set (non_sym_dist_pairs xs)\"\n    unfolding linear_order_from_list_position_set by blast+\n  then consider (a) \"(x, y) \\<in> set (map (\\<lambda>x. (x, x)) xs)\" |\n                (b) \"(x, y) \\<in> set (non_sym_dist_pairs xs)\"\n    by blast\n  then show \"x = y\"\n  proof cases\n    case a\n    then show ?thesis by auto\n  next\n    case b\n    then have \"x \\<noteq> y\" and \"(y,x) \\<notin> set (non_sym_dist_pairs xs)\"\n      using non_sym_dist_pairs_set_iff[of x y xs] by simp+\n    then have \"(y, x) \\<notin> set (map (\\<lambda>x. (x, x)) xs) \\<union> set (non_sym_dist_pairs xs)\"\n      by auto\n    then show ?thesis \n     using \\<open>(y, x) \\<in> set (map (\\<lambda>x. (x, x)) xs) \\<union> set (non_sym_dist_pairs xs)\\<close> by blast\n  qed\nqed\n\n\nlemma non_sym_dist_pairs'_indices : \n  \"distinct xs \\<Longrightarrow> (x,y) \\<in> set (non_sym_dist_pairs' xs) \n   \\<Longrightarrow> (\\<exists> i j . xs ! i = x \\<and> xs ! j = y \\<and> i < j \\<and> i < length xs \\<and> j < length xs)\"\nproof (induction xs)\n  case Nil\n  then show ?case by auto\nnext\n  case (Cons a xs)\n  show ?case proof (cases \"a = x\")\n    case True\n    then have \"(a#xs) ! 0 = x\" and \"0 < length (a#xs)\"\n      by auto\n    \n    have \"y \\<in> set xs\"\n      using non_sym_dist_pairs'_elems_distinct(2,3)[OF Cons.prems(1,2)] True by auto\n    then obtain j where \"xs ! j = y\" and \"j < length xs\"\n      by (meson in_set_conv_nth)\n    then have \"(a#xs) ! (Suc j) = y\" and \"Suc j < length (a#xs)\"\n      by auto\n\n    then show ?thesis \n      using \\<open>(a#xs) ! 0 = x\\<close> \\<open>0 < length (a#xs)\\<close> by blast\n  next\n    case False\n    then have \"(x,y) \\<in> set (non_sym_dist_pairs' xs)\"\n      using Cons.prems(2) by auto\n    then show ?thesis \n      using Cons.IH Cons.prems(1)\n      by (metis Suc_mono distinct.simps(2) length_Cons nth_Cons_Suc)\n  qed\nqed\n\n\n\nlemma non_sym_dist_pairs'_trans: \"distinct xs \\<Longrightarrow> trans (set (non_sym_dist_pairs' xs))\"\nproof \n  fix x y z assume \"distinct xs\" \n            and    \"(x, y) \\<in> set (non_sym_dist_pairs' xs)\" \n            and    \"(y, z) \\<in> set (non_sym_dist_pairs' xs)\"\n\n  obtain nx ny where \"xs ! nx = x\" and \"xs ! ny = y\" and \"nx < ny\" \n                 and \"nx < length xs\" and \"ny < length xs\"\n    using non_sym_dist_pairs'_indices[OF \\<open>distinct xs\\<close> \\<open>(x, y) \\<in> set (non_sym_dist_pairs' xs)\\<close>] \n    by blast\n\n  obtain ny' nz where \"xs ! ny' = y\" and \"xs ! nz = z\" and \"ny'< nz\" \n                  and \"ny' < length xs\" and \"nz < length xs\"\n    using non_sym_dist_pairs'_indices[OF \\<open>distinct xs\\<close> \\<open>(y, z) \\<in> set (non_sym_dist_pairs' xs)\\<close>] \n    by blast\n\n  have \"ny' = ny\"\n    using \\<open>distinct xs\\<close> \\<open>xs ! ny = y\\<close> \\<open>xs ! ny' = y\\<close> \\<open>ny < length xs\\<close> \\<open>ny' < length xs\\<close> \n          nth_eq_iff_index_eq \n    by metis\n  then have \"nx < nz\"\n    using \\<open>nx < ny\\<close> \\<open>ny' < nz\\<close> by auto\n\n  then have \"nx \\<noteq> nz\" by simp\n  then have \"x \\<noteq> z\"\n    using \\<open>distinct xs\\<close> \\<open>xs ! nx = x\\<close> \\<open>xs ! nz = z\\<close> \\<open>nx < length xs\\<close> \\<open>nz < length xs\\<close> \n          nth_eq_iff_index_eq \n    by metis\n\n  have \"remdups xs = xs\"\n    using \\<open>distinct xs\\<close> by auto\n\n  have \"\\<not>(z, x) \\<in> set (non_sym_dist_pairs' xs)\"\n  proof \n    assume \"(z, x) \\<in> set (non_sym_dist_pairs' xs)\"\n    then obtain nz' nx' where \"xs ! nx' = x\" and \"xs ! nz' = z\" and \"nz'< nx'\" \n                          and \"nx' < length xs\" and \"nz' < length xs\"\n      using non_sym_dist_pairs'_indices[OF \\<open>distinct xs\\<close>, of z x] by metis\n\n    have \"nx' = nx\"\n      using \\<open>distinct xs\\<close> \\<open>xs ! nx = x\\<close> \\<open>xs ! nx' = x\\<close> \\<open>nx < length xs\\<close> \\<open>nx' < length xs\\<close> \n            nth_eq_iff_index_eq \n      by metis\n    moreover have \"nz' = nz\"\n      using \\<open>distinct xs\\<close> \\<open>xs ! nz = z\\<close> \\<open>xs ! nz' = z\\<close> \\<open>nz < length xs\\<close> \\<open>nz' < length xs\\<close> \n            nth_eq_iff_index_eq \n      by metis\n    ultimately have \"nz < nx\"\n      using \\<open>nz'< nx'\\<close> by auto\n    then show \"False\"\n      using \\<open>nx < nz\\<close> by simp    \n  qed\n  then show \"(x, z) \\<in> set (non_sym_dist_pairs' xs)\" \n    using non_sym_dist_pairs'_elems_distinct(1)[OF \\<open>distinct xs\\<close> \\<open>(x, y) \\<in> set (non_sym_dist_pairs' xs)\\<close>]\n          non_sym_dist_pairs'_elems_distinct(2)[OF \\<open>distinct xs\\<close> \\<open>(y, z) \\<in> set (non_sym_dist_pairs' xs)\\<close>]\n          \\<open>x \\<noteq> z\\<close>\n          non_sym_dist_pairs_elems[of x xs z]\n    unfolding non_sym_dist_pairs.simps \\<open>remdups xs = xs\\<close> \n    by blast\nqed\n\n\nlemma non_sym_dist_pairs_trans: \"trans (set (non_sym_dist_pairs xs))\"\n  using non_sym_dist_pairs'_trans[of \"remdups xs\", OF distinct_remdups] \n  unfolding non_sym_dist_pairs.simps \n  by assumption\n\n\n\nlemma linear_order_from_list_position_trans: \"trans (set (linear_order_from_list_position xs))\"\nproof \n  fix x y z assume \"(x, y) \\<in> set (linear_order_from_list_position xs)\" \n               and \"(y, z) \\<in> set (linear_order_from_list_position xs)\"\n  then consider (a) \"(x, y) \\<in> set (map (\\<lambda>x. (x, x)) xs) \\<and> (y, z) \\<in> set (map (\\<lambda>x. (x, x)) xs)\" |\n                (b) \"(x, y) \\<in> set (map (\\<lambda>x. (x, x)) xs) \\<and> (y, z) \\<in> set (non_sym_dist_pairs xs)\" |\n                (c) \"(x, y) \\<in> set (non_sym_dist_pairs xs) \\<and> (y, z) \\<in> set (map (\\<lambda>x. (x, x)) xs)\" |\n                (d) \"(x, y) \\<in> set (non_sym_dist_pairs xs) \\<and> (y, z) \\<in> set (non_sym_dist_pairs xs)\"\n    unfolding linear_order_from_list_position_set by blast+\n  then show \"(x, z) \\<in> set (linear_order_from_list_position xs)\"\n  proof cases\n    case a\n    then show ?thesis unfolding linear_order_from_list_position_set by auto\n  next\n    case b\n    then show ?thesis unfolding linear_order_from_list_position_set by auto\n  next\n    case c\n    then show ?thesis unfolding linear_order_from_list_position_set by auto\n  next\n    case d\n    then show ?thesis unfolding linear_order_from_list_position_set \n                      using non_sym_dist_pairs_trans \n                      by (metis UnI2 transE)\n  qed\nqed\n\n\n\nsubsection \\<open>Find And Remove in a Single Pass\\<close>\n\nfun find_remove' :: \"('a \\<Rightarrow> bool) \\<Rightarrow> 'a list \\<Rightarrow> 'a list \\<Rightarrow> ('a \\<times> 'a list) option\" where\n  \"find_remove' P [] _ = None\" |\n  \"find_remove' P (x#xs) prev = (if P x\n      then Some (x,prev@xs) \n      else find_remove' P xs (prev@[x]))\"\n\nfun find_remove :: \"('a \\<Rightarrow> bool) \\<Rightarrow> 'a list \\<Rightarrow> ('a \\<times> 'a list) option\" where\n  \"find_remove P xs = find_remove' P xs []\"\n\nlemma find_remove'_set : \n  assumes \"find_remove' P xs prev = Some (x,xs')\"\nshows \"P x\"\nand   \"x \\<in> set xs\"\nand   \"xs' = prev@(remove1 x xs)\"\nproof -\n  have \"P x \\<and> x \\<in> set xs \\<and> xs' = prev@(remove1 x xs)\"\n    using assms proof (induction xs arbitrary: prev xs')\n    case Nil\n    then show ?case by auto\n  next\n    case (Cons x xs)\n    show ?case proof (cases \"P x\")\n      case True\n      then show ?thesis using Cons by auto\n    next\n      case False\n      then show ?thesis using Cons by fastforce \n    qed\n  qed\n  then show \"P x\"\n      and   \"x \\<in> set xs\"\n      and   \"xs' = prev@(remove1 x xs)\"\n    by blast+\nqed\n\nlemma find_remove'_set_rev :\n  assumes \"x \\<in> set xs\"\n  and     \"P x\"\nshows \"find_remove' P xs prev \\<noteq> None\" \nusing assms(1) proof(induction xs arbitrary: prev)\n  case Nil\n  then show ?case by auto\nnext\n  case (Cons x' xs)\n  show ?case proof (cases \"P x\")\n    case True\n    then show ?thesis using Cons by auto\n  next\n    case False\n    then show ?thesis using Cons\n      using assms(2) by auto \n  qed\nqed\n\n\nlemma find_remove_None_iff :\n  \"find_remove P xs = None \\<longleftrightarrow> \\<not> (\\<exists>x . x \\<in> set xs \\<and> P x)\"\n  unfolding find_remove.simps \n  using find_remove'_set(1,2) \n        find_remove'_set_rev\n  by (metis old.prod.exhaust option.exhaust)\n\nlemma find_remove_set : \n  assumes \"find_remove P xs = Some (x,xs')\"\nshows \"P x\"\nand   \"x \\<in> set xs\"\nand   \"xs' = (remove1 x xs)\"\n  using assms find_remove'_set[of P xs \"[]\" x xs'] by auto\n\n\n\n\nfun find_remove_2' :: \"('a\\<Rightarrow>'b\\<Rightarrow>bool) \\<Rightarrow> 'a list \\<Rightarrow> 'b list \\<Rightarrow> 'a list \\<Rightarrow> ('a \\<times> 'b \\<times> 'a list) option\" \n  where\n  \"find_remove_2' P [] _ _ = None\" |\n  \"find_remove_2' P (x#xs) ys prev = (case find (\\<lambda>y . P x y) ys of\n      Some y \\<Rightarrow> Some (x,y,prev@xs) |\n      None   \\<Rightarrow> find_remove_2' P xs ys (prev@[x]))\"\n\nfun find_remove_2 :: \"('a \\<Rightarrow> 'b \\<Rightarrow> bool) \\<Rightarrow> 'a list \\<Rightarrow> 'b list \\<Rightarrow> ('a \\<times> 'b \\<times> 'a list) option\" where\n  \"find_remove_2 P xs ys = find_remove_2' P xs ys []\"\n\n\nlemma find_remove_2'_set : \n  assumes \"find_remove_2' P xs ys prev = Some (x,y,xs')\"\nshows \"P x y\"\nand   \"x \\<in> set xs\"\nand   \"y \\<in> set ys\"\nand   \"distinct (prev@xs) \\<Longrightarrow> set xs' = (set prev \\<union> set xs) - {x}\"\nand   \"distinct (prev@xs) \\<Longrightarrow> distinct xs'\"\nand   \"xs' = prev@(remove1 x xs)\"\nand   \"find (P x) ys = Some y\"\nproof -\n  have \"P x y \n        \\<and> x \\<in> set xs \n        \\<and> y \\<in> set ys \n        \\<and> (distinct (prev@xs) \\<longrightarrow> set xs' = (set prev \\<union> set xs) - {x}) \n        \\<and> (distinct (prev@xs) \\<longrightarrow> distinct xs') \n        \\<and> (xs' = prev@(remove1 x xs)) \n        \\<and> find (P x) ys = Some y\"\n    using assms \n  proof (induction xs arbitrary: prev xs' x y)\n    case Nil\n    then show ?case by auto \n  next\n    case (Cons x' xs)\n    then show ?case proof (cases \"find (\\<lambda>y . P x' y) ys\")\n      case None\n      then have \"find_remove_2' P (x' # xs) ys prev = find_remove_2' P xs ys (prev@[x'])\"\n        using Cons.prems(1) by auto\n      hence *: \"find_remove_2' P xs ys (prev@[x']) = Some (x, y, xs')\"\n        using Cons.prems(1) by simp\n      \n      have \"x' \\<noteq> x\"\n        by (metis \"*\" Cons.IH None find_from)\n      moreover have \"distinct (prev @ x' # xs) \\<longrightarrow> distinct ((x' # prev) @ xs)\"\n        by auto\n      ultimately show ?thesis using Cons.IH[OF *]\n        by auto\n    next\n      case (Some y')\n      then have \"find_remove_2' P (x' # xs) ys prev = Some (x',y',prev@xs)\"\n        by auto\n      then show ?thesis using Some\n        using Cons.prems(1) find_condition find_set by fastforce \n    qed\n  qed\n  then show \"P x y\"\n      and   \"x \\<in> set xs\"\n      and   \"y \\<in> set ys\"\n      and   \"distinct (prev @ xs) \\<Longrightarrow> set xs' = (set prev \\<union> set xs) - {x}\"\n      and   \"distinct (prev@xs) \\<Longrightarrow> distinct xs'\"\n      and   \"xs' = prev@(remove1 x xs)\"\n      and   \"find (P x) ys = Some y\"\n    by blast+\nqed\n\n\n\nlemma find_remove_2'_strengthening : \n  assumes \"find_remove_2' P xs ys prev = Some (x,y,xs')\"\n  and     \"P' x y\"\n  and     \"\\<And> x' y' . P' x' y' \\<Longrightarrow> P x' y'\"\nshows \"find_remove_2' P' xs ys prev = Some (x,y,xs')\"\n  using assms proof (induction xs arbitrary: prev)\n  case Nil\n  then show ?case by auto\nnext\n  case (Cons x' xs)\n  then show ?case proof (cases \"find (\\<lambda>y . P x' y) ys\")\n    case None\n    then show ?thesis using Cons\n      by (metis (mono_tags, lifting) find_None_iff find_remove_2'.simps(2) option.simps(4))  \n  next\n    case (Some a)\n    then have \"x' = x\" and \"a = y\"\n      using Cons.prems(1) unfolding find_remove_2'.simps by auto\n    then have \"find (\\<lambda>y . P x y) ys = Some y\"\n      using find_remove_2'_set[OF Cons.prems(1)] by auto\n    then have \"find (\\<lambda>y . P' x y) ys = Some y\"\n      using Cons.prems(3) proof (induction ys)\n      case Nil\n      then show ?case by auto\n    next\n      case (Cons y' ys)\n      then show ?case\n        by (metis assms(2) find.simps(2) option.inject) \n    qed\n      \n    then show ?thesis  \n      using find_remove_2'_set(6)[OF Cons.prems(1)]\n      unfolding \\<open>x' = x\\<close> find_remove_2'.simps by auto      \n  qed\nqed\n\nlemma find_remove_2_strengthening : \n  assumes \"find_remove_2 P xs ys = Some (x,y,xs')\"\n  and     \"P' x y\"\n  and     \"\\<And> x' y' . P' x' y' \\<Longrightarrow> P x' y'\"\nshows \"find_remove_2 P' xs ys = Some (x,y,xs')\"\n  using assms find_remove_2'_strengthening\n  by (metis find_remove_2.simps) \n\n\n\nlemma find_remove_2'_prev_independence :\n  assumes \"find_remove_2' P xs ys prev = Some (x,y,xs')\"\n  shows \"\\<exists> xs'' . find_remove_2' P xs ys prev' = Some (x,y,xs'')\" \n  using assms proof (induction xs arbitrary: prev prev' xs')\n  case Nil\n  then show ?case by auto\nnext\n  case (Cons x' xs)\n  show ?case proof (cases \"find (\\<lambda>y . P x' y) ys\")\n    case None\n    then show ?thesis\n      using Cons.IH Cons.prems by auto\n      \n  next\n    case (Some a)\n    then show ?thesis using Cons.prems unfolding find_remove_2'.simps\n      by simp \n  qed\nqed\n\n\nlemma find_remove_2'_filter :\n  assumes \"find_remove_2' P (filter P' xs) ys prev = Some (x,y,xs')\"\n  and     \"\\<And> x y . \\<not> P' x \\<Longrightarrow> \\<not> P x y\"\nshows \"\\<exists> xs'' . find_remove_2' P xs ys prev = Some (x,y,xs'')\"\n  using assms(1) proof (induction xs arbitrary: prev prev xs')\n  case Nil\n  then show ?case by auto\nnext\n  case (Cons x' xs)\n  then show ?case proof (cases \"P' x'\")\n    case True\n    then have *:\"find_remove_2' P (filter P' (x' # xs)) ys prev \n                = find_remove_2' P (x' # filter P' xs) ys prev\" \n      by auto\n      \n    show ?thesis proof (cases \"find (\\<lambda>y . P x' y) ys\")\n      case None\n      then show ?thesis\n        by (metis Cons.IH Cons.prems  find_remove_2'.simps(2) option.simps(4) *)\n    next\n      case (Some a) \n      then have \"x' = x\" and \"a = y\"\n        using Cons.prems\n        unfolding * find_remove_2'.simps by auto\n        \n      show ?thesis \n        using Some \n        unfolding \\<open>x' = x\\<close> \\<open>a = y\\<close> find_remove_2'.simps\n        by simp\n    qed\n  next\n    case False\n    then have \"find_remove_2' P (filter P' xs) ys prev = Some (x,y,xs')\"\n      using Cons.prems by auto\n\n    from False assms(2) have \"find (\\<lambda>y . P x' y) ys = None\"\n      by (simp add: find_None_iff)\n    then have \"find_remove_2' P (x'#xs) ys prev = find_remove_2' P xs ys (prev@[x'])\"\n      by auto\n    \n    show ?thesis \n      using Cons.IH[OF \\<open>find_remove_2' P (filter P' xs) ys prev = Some (x,y,xs')\\<close>] \n      unfolding \\<open>find_remove_2' P (x'#xs) ys prev = find_remove_2' P xs ys (prev@[x'])\\<close>\n      using find_remove_2'_prev_independence by metis\n  qed\nqed\n\n\nlemma find_remove_2_filter :\n  assumes \"find_remove_2 P (filter P' xs) ys = Some (x,y,xs')\"\n  and     \"\\<And> x y . \\<not> P' x \\<Longrightarrow> \\<not> P x y\"\nshows \"\\<exists> xs'' . find_remove_2 P xs ys = Some (x,y,xs'')\"\n  using assms by (simp add: find_remove_2'_filter)  \n\n\nlemma find_remove_2'_index : \n  assumes \"find_remove_2' P xs ys prev = Some (x,y,xs')\"\n  obtains i i' where \"i < length xs\" \n                     \"xs ! i = x\"\n                     \"\\<And> j . j < i \\<Longrightarrow> find (\\<lambda>y . P (xs ! j) y) ys = None\"\n                     \"i' < length ys\"\n                     \"ys ! i' = y\"\n                     \"\\<And> j . j < i' \\<Longrightarrow> \\<not> P (xs ! i) (ys ! j)\"\nproof -\n  have \"\\<exists> i i' . i < length xs \n                  \\<and> xs ! i = x \n                  \\<and> (\\<forall> j < i . find (\\<lambda>y . P (xs ! j) y) ys = None) \n                  \\<and> i' < length ys \\<and> ys ! i' = y \n                  \\<and> (\\<forall> j < i' . \\<not> P (xs ! i) (ys ! j))\"\n    using assms \n  proof (induction xs arbitrary: prev xs' x y)\n    case Nil\n    then show ?case by auto \n  next\n    case (Cons x' xs)\n    then show ?case proof (cases \"find (\\<lambda>y . P x' y) ys\")\n      case None\n      then have \"find_remove_2' P (x' # xs) ys prev = find_remove_2' P xs ys (prev@[x'])\"\n        using Cons.prems(1) by auto\n      hence *: \"find_remove_2' P xs ys (prev@[x']) = Some (x, y, xs')\"\n        using Cons.prems(1) by simp\n      \n      have \"x' \\<noteq> x\"\n        using find_remove_2'_set(1,3)[OF *] None unfolding find_None_iff\n        by blast\n\n      obtain i i' where \"i < length xs\" and \"xs ! i = x\" \n                    and \"(\\<forall> j < i . find (\\<lambda>y . P (xs ! j) y) ys = None)\" and \"i' < length ys\" \n                    and \"ys ! i' = y\" and \"(\\<forall> j < i' . \\<not> P (xs ! i) (ys ! j))\"\n        using Cons.IH[OF *] by blast\n\n      have \"Suc i < length (x'#xs)\"\n        using \\<open>i < length xs\\<close> by auto\n      moreover have \"(x'#xs) ! Suc i = x\"\n        using \\<open>xs ! i = x\\<close> by auto\n      moreover have \"(\\<forall> j < Suc i . find (\\<lambda>y . P ((x'#xs) ! j) y) ys = None)\"\n      proof -\n        have \"\\<And> j . j > 0 \\<Longrightarrow> j < Suc i \\<Longrightarrow> find (\\<lambda>y . P ((x'#xs) ! j) y) ys = None\"\n          using \\<open>(\\<forall> j < i . find (\\<lambda>y . P (xs ! j) y) ys = None)\\<close> by auto \n        then show ?thesis using None\n          by (metis neq0_conv nth_Cons_0) \n      qed\n      moreover have \"(\\<forall> j < i' . \\<not> P ((x'#xs) ! Suc i) (ys ! j))\"\n        using \\<open>(\\<forall> j < i' . \\<not> P (xs ! i) (ys ! j))\\<close>\n        by simp \n      \n      ultimately show ?thesis \n        using that \\<open>i' < length ys\\<close> \\<open>ys ! i' = y\\<close> by blast\n    next\n      case (Some y')\n      then have \"x' = x\" and \"y' = y\"\n        using Cons.prems by force+\n      \n      have \"0 < length (x'#xs) \\<and> (x'#xs) ! 0 = x' \n            \\<and> (\\<forall> j < 0 . find (\\<lambda>y . P ((x'#xs) ! j) y) ys = None)\" \n        by auto\n      moreover obtain i' where \"i' < length ys\" and \"ys ! i' = y'\" \n                           and \"(\\<forall> j < i' . \\<not> P ((x'#xs) ! 0) (ys ! j))\" \n        using find_sort_index[OF Some] by auto\n      ultimately show ?thesis \n        unfolding \\<open>x' = x\\<close> \\<open>y' = y\\<close> by blast\n    qed\n  qed\n  then show ?thesis using that by blast\nqed\n\nlemma find_remove_2_index : \n  assumes \"find_remove_2 P xs ys = Some (x,y,xs')\"\n  obtains i i' where \"i < length xs\" \n                     \"xs ! i = x\"\n                     \"\\<And> j . j < i \\<Longrightarrow> find (\\<lambda>y . P (xs ! j) y) ys = None\"\n                     \"i' < length ys\"\n                     \"ys ! i' = y\"\n                     \"\\<And> j . j < i' \\<Longrightarrow> \\<not> P (xs ! i) (ys ! j)\"\n  using assms find_remove_2'_index[of P xs ys \"[]\" x y xs'] by auto\n\n\nlemma find_remove_2'_set_rev :\n  assumes \"x \\<in> set xs\"\n  and     \"y \\<in> set ys\"\n  and     \"P x y\"\nshows \"find_remove_2' P xs ys prev \\<noteq> None\" \nusing assms(1) proof(induction xs arbitrary: prev)\n  case Nil\n  then show ?case by auto\nnext\n  case (Cons x' xs)\n  then show ?case proof (cases \"find (\\<lambda>y . P x' y) ys\")\n    case None\n    then have \"x \\<noteq> x'\" \n      using assms(2,3) by (metis find_None_iff) \n    then have \"x \\<in> set xs\"\n      using Cons.prems by auto\n    then show ?thesis \n      using Cons.IH unfolding find_remove_2'.simps None by auto\n  next\n    case (Some a)\n    then show ?thesis by auto\n  qed\nqed\n\n\nlemma find_remove_2'_diff_prev_None :\n  \"(find_remove_2' P xs ys prev = None \\<Longrightarrow> find_remove_2' P xs ys prev' = None)\" \nproof (induction xs arbitrary: prev prev')\n  case Nil\n  then show ?case by auto\nnext\n  case (Cons x xs)\n  show ?case proof (cases \"find (\\<lambda>y . P x y) ys\")\n    case None\n    then have \"find_remove_2' P (x#xs) ys prev = find_remove_2' P xs ys (prev@[x])\" \n         and  \"find_remove_2' P (x#xs) ys prev' = find_remove_2' P xs ys (prev'@[x])\"\n      by auto\n    then show ?thesis using Cons by auto \n  next\n    case (Some a)\n    then show ?thesis using Cons by auto\n  qed\nqed\n\nlemma find_remove_2'_diff_prev_Some :\n  \"(find_remove_2' P xs ys prev = Some (x,y,xs') \n    \\<Longrightarrow> \\<exists> xs'' . find_remove_2' P xs ys prev' = Some (x,y,xs''))\" \nproof (induction xs arbitrary: prev prev')\n  case Nil\n  then show ?case by auto\nnext\n  case (Cons x xs)\n  show ?case proof (cases \"find (\\<lambda>y . P x y) ys\")\n    case None\n    then have \"find_remove_2' P (x#xs) ys prev = find_remove_2' P xs ys (prev@[x])\" \n         and  \"find_remove_2' P (x#xs) ys prev' = find_remove_2' P xs ys (prev'@[x])\"\n      by auto\n    then show ?thesis using Cons by auto \n  next\n    case (Some a)\n    then show ?thesis using Cons by auto\n  qed\nqed\n\n\nlemma find_remove_2_None_iff :\n  \"find_remove_2 P xs ys = None \\<longleftrightarrow> \\<not> (\\<exists>x y . x \\<in> set xs \\<and> y \\<in> set ys \\<and> P x y)\"\n  unfolding find_remove_2.simps \n  using find_remove_2'_set(1-3) find_remove_2'_set_rev\n  by (metis old.prod.exhaust option.exhaust)\n\nlemma find_remove_2_set : \n  assumes \"find_remove_2 P xs ys = Some (x,y,xs')\"\nshows \"P x y\"\nand   \"x \\<in> set xs\"\nand   \"y \\<in> set ys\"\nand   \"distinct xs \\<Longrightarrow> set xs' = (set xs) - {x}\"\nand   \"distinct xs \\<Longrightarrow> distinct xs'\"\nand   \"xs' = (remove1 x xs)\"\n  using assms find_remove_2'_set[of P xs ys \"[]\" x y xs'] \n  unfolding find_remove_2.simps by auto\n\nlemma find_remove_2_removeAll :\n  assumes \"find_remove_2 P xs ys = Some (x,y,xs')\"\n  and     \"distinct xs\"\nshows \"xs' = removeAll x xs\"\n  using find_remove_2_set(6)[OF assms(1)]\n  by (simp add: assms(2) distinct_remove1_removeAll) \n\nlemma find_remove_2_length :\n  assumes \"find_remove_2 P xs ys = Some (x,y,xs')\"\n  shows \"length xs' = length xs - 1\"\n  using find_remove_2_set(2,6)[OF assms]\n  by (simp add: length_remove1) \n\n\n\nfun separate_by :: \"('a \\<Rightarrow> bool) \\<Rightarrow> 'a list \\<Rightarrow> ('a list \\<times> 'a list)\" where\n  \"separate_by P xs = (filter P xs, filter (\\<lambda> x . \\<not> P x) xs)\"\n\nlemma separate_by_code[code] :\n  \"separate_by P xs = foldr (\\<lambda>x (prevPass,prevFail) . if P x then (x#prevPass,prevFail) else (prevPass,x#prevFail)) xs ([],[])\"\nproof (induction xs)\n  case Nil\n  then show ?case by auto\nnext\n  case (Cons a xs)\n\n  let ?f = \"(\\<lambda>x (prevPass,prevFail) . if P x then (x#prevPass,prevFail) else (prevPass,x#prevFail))\"\n\n  have \"(filter P xs, filter (\\<lambda> x . \\<not> P x) xs) = foldr ?f xs ([],[])\"\n    using Cons.IH by auto\n  moreover have \"separate_by P (a#xs) = ?f a (filter P xs, filter (\\<lambda> x . \\<not> P x) xs)\"\n    by auto\n  ultimately show ?case \n    by (cases \"P a\"; auto)\nqed\n\nfun find_remove_2_all :: \"('a \\<Rightarrow> 'b \\<Rightarrow> bool) \\<Rightarrow> 'a list \\<Rightarrow> 'b list \\<Rightarrow> (('a \\<times> 'b) list \\<times> 'a list)\" where\n  \"find_remove_2_all P xs ys =\n    (map (\\<lambda> x . (x, the (find (\\<lambda>y . P x y) ys))) (filter (\\<lambda> x . find (\\<lambda>y . P x y) ys \\<noteq> None) xs)\n    ,filter (\\<lambda> x . find (\\<lambda>y . P x y) ys = None) xs)\"\n\n\nfun find_remove_2_all' :: \"('a \\<Rightarrow> 'b \\<Rightarrow> bool) \\<Rightarrow> 'a list \\<Rightarrow> 'b list \\<Rightarrow> (('a \\<times> 'b) list \\<times> 'a list)\" where\n  \"find_remove_2_all' P xs ys = \n    (let (successesWithWitnesses,failures) = separate_by (\\<lambda>(x,y) . y \\<noteq> None) (map (\\<lambda> x . (x,find (\\<lambda>y . P x y) ys)) xs)\n    in (map (\\<lambda> (x,y) . (x, the y)) successesWithWitnesses, map fst failures))\"\n\nlemma find_remove_2_all_code[code] :\n  \"find_remove_2_all P xs ys = find_remove_2_all' P xs ys\"\nproof -\n  let ?s1 = \"map (\\<lambda> x . (x, the (find (\\<lambda>y . P x y) ys))) (filter (\\<lambda> x . find (\\<lambda>y . P x y) ys \\<noteq> None) xs)\"\n  let ?f1 = \"filter (\\<lambda> x . find (\\<lambda>y . P x y) ys = None) xs\"\n\n  let ?s2 = \"map (\\<lambda> (x,y) . (x, the y)) (filter (\\<lambda>(x,y) . y \\<noteq> None) (map (\\<lambda> x . (x,find (\\<lambda>y . P x y) ys)) xs))\"\n  let ?f2 = \"map fst (filter (\\<lambda>(x,y) . y = None) (map (\\<lambda> x . (x,find (\\<lambda>y . P x y) ys)) xs))\"\n\n  have \"find_remove_2_all P xs ys = (?s1,?f1)\" \n    by simp\n  moreover have \"find_remove_2_all' P xs ys = (?s2,?f2)\" \n  proof -\n    have \"\\<forall>p. (\\<lambda>pa. \\<not> (case pa of (a::'a, x::'b option) \\<Rightarrow> p x)) = (\\<lambda>(a, z). \\<not> p z)\"\n      by force\n    then show ?thesis\n      unfolding find_remove_2_all'.simps Let_def separate_by.simps  \n      by force\n  qed\n  moreover have \"?s1 = ?s2\" \n    by (induction xs; auto)\n  moreover have \"?f1 = ?f2\" \n    by (induction xs; auto)\n  ultimately show ?thesis \n    by simp\nqed\n   \n\n\n\n\n\n\nsubsection \\<open>Set-Operations on Lists\\<close>\n\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\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))) \n                  = 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))) \n            \\<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)) \n                            \\<union> (image (insert x) (set (map set (pow_list xs)))) \n                    \\<Longrightarrow> ys \\<in> set (map set (pow_list (x#xs)))\"\n    proof -\n      fix ys assume \"ys \\<in> set (map set (pow_list xs)) \n                            \\<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\nsubsubsection \\<open>Removing Subsets in a List of Sets\\<close>\n\nlemma remove1_length : \"x \\<in> set xs \\<Longrightarrow> length (remove1 x xs) < length xs\" \n  by (induction xs; auto)\n\n\nfunction remove_subsets :: \"'a set list \\<Rightarrow> 'a set list\" where\n  \"remove_subsets [] = []\" |\n  \"remove_subsets (x#xs) = (case find_remove (\\<lambda> y . x \\<subset> y) xs of\n    Some (y',xs') \\<Rightarrow> remove_subsets (y'# (filter (\\<lambda> y . \\<not>(y \\<subseteq> x)) xs')) |\n    None          \\<Rightarrow> x # (remove_subsets (filter (\\<lambda> y . \\<not>(y \\<subseteq> x)) xs)))\"\n  by pat_completeness auto\ntermination \n  apply (relation \"measure length\")\n    apply simp\nproof -\n  show \"\\<And>x xs. find_remove ((\\<subset>) x) xs = None \\<Longrightarrow> (filter (\\<lambda>y. \\<not> y \\<subseteq> x) xs, x # xs) \\<in> measure length\"\n    by (metis dual_order.trans impossible_Cons in_measure length_filter_le not_le_imp_less)\n  show \"(\\<And>(x :: 'a set) xs x2 xa y. find_remove ((\\<subset>) x) xs = Some x2 \\<Longrightarrow> (xa, y) = x2 \\<Longrightarrow> (xa # filter (\\<lambda>y. \\<not> y \\<subseteq> x) y, x # xs) \\<in> measure length)\"\n  proof -\n    fix x :: \"'a set\"\n    fix xs y'xs' y' xs'    \n    assume \"find_remove ((\\<subset>) x) xs = Some y'xs'\" and \"(y', xs') = y'xs'\"\n    then have \"find_remove ((\\<subset>) x) xs = Some (y',xs')\"\n      by auto\n\n    have \"length xs' = length xs - 1\"\n      using find_remove_set(2,3)[OF \\<open>find_remove ((\\<subset>) x) xs = Some (y',xs')\\<close>]\n      by (simp add: length_remove1) \n    then have \"length (y'#xs') = length xs\"\n      using find_remove_set(2)[OF \\<open>find_remove ((\\<subset>) x) xs = Some (y',xs')\\<close>]\n      using remove1_length by fastforce \n    \n    have \"length (filter (\\<lambda>y. \\<not> y \\<subseteq> x) xs') \\<le> length xs'\"\n      by simp\n    then have \"length (y' # filter (\\<lambda>y. \\<not> y \\<subseteq> x) xs') \\<le> length xs' + 1\"\n      by simp\n    then have \"length (y' # filter (\\<lambda>y. \\<not> y \\<subseteq> x) xs') \\<le> length xs\" \n      unfolding \\<open>length (y'#xs') = length xs\\<close>[symmetric] by simp\n    then show \"(y' # filter (\\<lambda>y. \\<not> y \\<subseteq> x) xs', x # xs) \\<in> measure length\"\n      by auto \n  qed\nqed\n\n\nlemma remove_subsets_set : \"set (remove_subsets xss) = {xs . xs \\<in> set xss \\<and> (\\<nexists> xs' . xs' \\<in> set xss \\<and> xs \\<subset> xs')}\"\nproof (induction \"length xss\" arbitrary: xss rule: less_induct)\n  case less\n  \n  show ?case proof (cases xss)\n\n    case Nil\n    then show ?thesis by auto\n  next\n    case (Cons x xss')\n    \n    show ?thesis proof (cases \"find_remove (\\<lambda> y . x \\<subset> y) xss'\")\n      case None\n      then have \"(\\<nexists> xs' . xs' \\<in> set xss' \\<and> x \\<subset> xs')\"\n        using find_remove_None_iff by metis\n\n      have \"length (filter (\\<lambda> y . \\<not>(y \\<subseteq> x)) xss') < length xss\"\n        using Cons\n        by (meson dual_order.trans impossible_Cons leI length_filter_le) \n  \n      have \"remove_subsets (x#xss') = x # (remove_subsets (filter (\\<lambda> y . \\<not>(y \\<subseteq> x)) xss'))\"\n        using None by auto\n      then have \"set (remove_subsets (x#xss')) = insert x {xs \\<in> set (filter (\\<lambda>y. \\<not> y \\<subseteq> x) xss'). \\<nexists>xs'. xs' \\<in> set (filter (\\<lambda>y. \\<not> y \\<subseteq> x) xss') \\<and> xs \\<subset> xs'}\"\n        using less[OF \\<open>length (filter (\\<lambda> y . \\<not>(y \\<subseteq> x)) xss') < length xss\\<close>]\n        by auto\n      also have \"\\<dots> = {xs . xs \\<in> set (x#xss') \\<and> (\\<nexists> xs' . xs' \\<in> set (x#xss') \\<and> xs \\<subset> xs')}\"\n      proof -\n        have \"\\<And> xs . xs \\<in> insert x {xs \\<in> set (filter (\\<lambda>y. \\<not> y \\<subseteq> x) xss'). \\<nexists>xs'. xs' \\<in> set (filter (\\<lambda>y. \\<not> y \\<subseteq> x) xss') \\<and> xs \\<subset> xs'}\n              \\<Longrightarrow> xs \\<in> {xs \\<in> set (x # xss'). \\<nexists>xs'. xs' \\<in> set (x # xss') \\<and> xs \\<subset> xs'}\"\n        proof -\n          fix xs assume \"xs \\<in> insert x {xs \\<in> set (filter (\\<lambda>y. \\<not> y \\<subseteq> x) xss'). \\<nexists>xs'. xs' \\<in> set (filter (\\<lambda>y. \\<not> y \\<subseteq> x) xss') \\<and> xs \\<subset> xs'}\"\n          then consider \"xs = x\" | \"xs \\<in> set (filter (\\<lambda>y. \\<not> y \\<subseteq> x) xss') \\<and> (\\<nexists>xs'. xs' \\<in> set (filter (\\<lambda>y. \\<not> y \\<subseteq> x) xss') \\<and> xs \\<subset> xs')\"\n            by blast\n          then show \"xs \\<in> {xs \\<in> set (x # xss'). \\<nexists>xs'. xs' \\<in> set (x # xss') \\<and> xs \\<subset> xs'}\"\n            using \\<open>(\\<nexists> xs' . xs' \\<in> set xss' \\<and> x \\<subset> xs')\\<close> by (cases; auto)\n        qed\n        moreover have \"\\<And> xs . xs \\<in> {xs \\<in> set (x # xss'). \\<nexists>xs'. xs' \\<in> set (x # xss') \\<and> xs \\<subset> xs'}\n                        \\<Longrightarrow> xs \\<in> insert x {xs \\<in> set (filter (\\<lambda>y. \\<not> y \\<subseteq> x) xss'). \\<nexists>xs'. xs' \\<in> set (filter (\\<lambda>y. \\<not> y \\<subseteq> x) xss') \\<and> xs \\<subset> xs'}\" \n        proof -\n          fix xs assume \"xs \\<in> {xs \\<in> set (x # xss'). \\<nexists>xs'. xs' \\<in> set (x # xss') \\<and> xs \\<subset> xs'}\"\n          then have \"xs \\<in> set (x # xss')\" and \"\\<nexists>xs'. xs' \\<in> set (x # xss') \\<and> xs \\<subset> xs'\"\n            by blast+\n          then consider \"xs = x\" | \"xs \\<in> set xss'\" by auto\n          then show \"xs \\<in> insert x {xs \\<in> set (filter (\\<lambda>y. \\<not> y \\<subseteq> x) xss'). \\<nexists>xs'. xs' \\<in> set (filter (\\<lambda>y. \\<not> y \\<subseteq> x) xss') \\<and> xs \\<subset> xs'}\"\n          proof cases\n            case 1\n            then show ?thesis by auto\n          next\n            case 2\n            show ?thesis proof (cases \"xs \\<subseteq> x\")\n              case True\n              then show ?thesis\n                using \\<open>\\<nexists>xs'. xs' \\<in> set (x # xss') \\<and> xs \\<subset> xs'\\<close> by auto \n            next\n              case False\n              then have \"xs \\<in> set (filter (\\<lambda>y. \\<not> y \\<subseteq> x) xss')\"\n                using 2 by auto\n              moreover have \"\\<nexists>xs'. xs' \\<in> set (filter (\\<lambda>y. \\<not> y \\<subseteq> x) xss') \\<and> xs \\<subset> xs'\"\n                using \\<open>\\<nexists>xs'. xs' \\<in> set (x # xss') \\<and> xs \\<subset> xs'\\<close> by auto\n              ultimately show ?thesis by auto\n            qed \n          qed\n        qed\n        ultimately show ?thesis\n          by (meson subset_antisym subset_eq) \n      qed\n      finally show ?thesis unfolding Cons[symmetric] by assumption\n    next\n      case (Some a)\n      then obtain y' xs' where *: \"find_remove (\\<lambda> y . x \\<subset> y) xss' = Some (y',xs')\" by force\n      \n\n      have \"length xs' = length xss' - 1\"\n        using find_remove_set(2,3)[OF *]\n        by (simp add: length_remove1) \n      then have \"length (y'#xs') = length xss'\"\n        using find_remove_set(2)[OF *]\n        using remove1_length by fastforce \n      \n      have \"length (filter (\\<lambda>y. \\<not> y \\<subseteq> x) xs') \\<le> length xs'\"\n        by simp\n      then have \"length (y' # filter (\\<lambda>y. \\<not> y \\<subseteq> x) xs') \\<le> length xs' + 1\"\n        by simp\n      then have \"length (y' # filter (\\<lambda>y. \\<not> y \\<subseteq> x) xs') \\<le> length xss'\" \n        unfolding \\<open>length (y'#xs') = length xss'\\<close>[symmetric] by simp\n      then have \"length (y' # filter (\\<lambda>y. \\<not> y \\<subseteq> x) xs') < length xss\" \n        unfolding Cons by auto\n\n\n      have \"remove_subsets (x#xss') = remove_subsets (y'# (filter (\\<lambda> y . \\<not>(y \\<subseteq> x)) xs'))\"\n        using * by auto\n      then have \"set (remove_subsets (x#xss')) = {xs \\<in> set (y' # filter (\\<lambda>y. \\<not> y \\<subseteq> x) xs'). \\<nexists>xs'a. xs'a \\<in> set (y' # filter (\\<lambda>y. \\<not> y \\<subseteq> x) xs') \\<and> xs \\<subset> xs'a}\"\n        using less[OF \\<open>length (y' # filter (\\<lambda>y. \\<not> y \\<subseteq> x) xs') < length xss\\<close>]\n        by auto\n      also have \"\\<dots> = {xs . xs \\<in> set (x#xss') \\<and> (\\<nexists> xs' . xs' \\<in> set (x#xss') \\<and> xs \\<subset> xs')}\"\n      proof -\n        have \"\\<And> xs . xs \\<in> {xs \\<in> set (y' # filter (\\<lambda>y. \\<not> y \\<subseteq> x) xs'). \\<nexists>xs'a. xs'a \\<in> set (y' # filter (\\<lambda>y. \\<not> y \\<subseteq> x) xs') \\<and> xs \\<subset> xs'a} \n                \\<Longrightarrow> xs \\<in> {xs \\<in> set (x # xss'). \\<nexists>xs'. xs' \\<in> set (x # xss') \\<and> xs \\<subset> xs'}\"\n        proof -\n          fix xs assume \"xs \\<in> {xs \\<in> set (y' # filter (\\<lambda>y. \\<not> y \\<subseteq> x) xs'). \\<nexists>xs'a. xs'a \\<in> set (y' # filter (\\<lambda>y. \\<not> y \\<subseteq> x) xs') \\<and> xs \\<subset> xs'a}\"\n          then have \"xs \\<in> set (y' # filter (\\<lambda>y. \\<not> y \\<subseteq> x) xs')\" and \"\\<nexists>xs'a. xs'a \\<in> set (y' # filter (\\<lambda>y. \\<not> y \\<subseteq> x) xs') \\<and> xs \\<subset> xs'a\"\n            by blast+\n\n          have \"xs \\<in> set (x # xss')\"\n            using \\<open>xs \\<in> set (y' # filter (\\<lambda>y. \\<not> y \\<subseteq> x) xs')\\<close> find_remove_set(2,3)[OF *]\n            by auto \n          moreover have \"\\<nexists>xs'. xs' \\<in> set (x # xss') \\<and> xs \\<subset> xs'\"\n            using \\<open>\\<nexists>xs'a. xs'a \\<in> set (y' # filter (\\<lambda>y. \\<not> y \\<subseteq> x) xs') \\<and> xs \\<subset> xs'a\\<close> find_remove_set[OF *]\n            by (metis dual_order.strict_trans filter_list_set in_set_remove1 list.set_intros(1) list.set_intros(2) psubsetI set_ConsD)\n          ultimately show \"xs \\<in> {xs \\<in> set (x # xss'). \\<nexists>xs'. xs' \\<in> set (x # xss') \\<and> xs \\<subset> xs'}\" \n            by blast\n        qed\n        moreover have \"\\<And> xs . xs \\<in> {xs \\<in> set (x # xss'). \\<nexists>xs'. xs' \\<in> set (x # xss') \\<and> xs \\<subset> xs'} \n                \\<Longrightarrow> xs \\<in> {xs \\<in> set (y' # filter (\\<lambda>y. \\<not> y \\<subseteq> x) xs'). \\<nexists>xs'a. xs'a \\<in> set (y' # filter (\\<lambda>y. \\<not> y \\<subseteq> x) xs') \\<and> xs \\<subset> xs'a}\" \n        proof -\n          fix xs assume \"xs \\<in> {xs \\<in> set (x # xss'). \\<nexists>xs'. xs' \\<in> set (x # xss') \\<and> xs \\<subset> xs'}\"\n          then have \"xs \\<in> set (x # xss')\" and  \"\\<nexists>xs'. xs' \\<in> set (x # xss') \\<and> xs \\<subset> xs'\"\n            by blast+\n\n          then have \"xs \\<in> set (y' # filter (\\<lambda>y. \\<not> y \\<subseteq> x) xs')\"\n            using find_remove_set[OF *]\n            by (metis filter_list_set in_set_remove1 list.set_intros(1) list.set_intros(2) psubsetI set_ConsD) \n          moreover have \"\\<nexists>xs'a. xs'a \\<in> set (y' # filter (\\<lambda>y. \\<not> y \\<subseteq> x) xs') \\<and> xs \\<subset> xs'a\"\n            using \\<open>xs \\<in> set (x # xss')\\<close> \\<open>\\<nexists>xs'. xs' \\<in> set (x # xss') \\<and> xs \\<subset> xs'\\<close> find_remove_set[OF *]\n            by (metis filter_is_subset list.set_intros(2) notin_set_remove1 set_ConsD subset_iff)\n          ultimately show \"xs \\<in> {xs \\<in> set (y' # filter (\\<lambda>y. \\<not> y \\<subseteq> x) xs'). \\<nexists>xs'a. xs'a \\<in> set (y' # filter (\\<lambda>y. \\<not> y \\<subseteq> x) xs') \\<and> xs \\<subset> xs'a}\"\n            by blast\n        qed\n        ultimately show ?thesis by blast\n      qed\n      finally show ?thesis unfolding Cons by assumption\n    qed\n  qed\nqed\n\nsubsection \\<open>Linear Order on Sum\\<close>\n\ninstantiation sum :: (ord,ord) ord\nbegin\n\nfun less_eq_sum ::  \"'a + 'b \\<Rightarrow> 'a + 'b \\<Rightarrow> bool\" where\n  \"less_eq_sum (Inl a) (Inl b) = (a \\<le> b)\" |\n  \"less_eq_sum (Inl a) (Inr b) = True\" |\n  \"less_eq_sum (Inr a) (Inl b) = False\" |\n  \"less_eq_sum (Inr a) (Inr b) = (a \\<le> b)\"\n\nfun less_sum ::  \"'a + 'b \\<Rightarrow> 'a + 'b \\<Rightarrow> bool\" where\n  \"less_sum a b = (a \\<le> b \\<and> a \\<noteq> b)\"\n\ninstance by (intro_classes)\nend\n\n\ninstantiation sum :: (linorder,linorder) linorder\nbegin\n\nlemma less_le_not_le_sum :\n  fixes x :: \"'a + 'b\"\n  and   y :: \"'a + 'b\"\nshows \"(x < y) = (x \\<le> y \\<and> \\<not> y \\<le> x)\"  \n  by (cases x; cases y; auto)\n    \nlemma order_refl_sum :\n  fixes x :: \"'a + 'b\"\n  shows \"x \\<le> x\" \n  by (cases x; auto)\n\nlemma order_trans_sum :\n  fixes x :: \"'a + 'b\"\n  fixes y :: \"'a + 'b\"\n  fixes z :: \"'a + 'b\"\n  shows \"x \\<le> y \\<Longrightarrow> y \\<le> z \\<Longrightarrow> x \\<le> z\"\n  by (cases x; cases y; cases z; auto)  \n\nlemma antisym_sum :\n  fixes x :: \"'a + 'b\"\n  fixes y :: \"'a + 'b\"\n  shows \"x \\<le> y \\<Longrightarrow> y \\<le> x \\<Longrightarrow> x = y\"\n  by (cases x; cases y; auto)\n\nlemma linear_sum :\n  fixes x :: \"'a + 'b\"\n  fixes y :: \"'a + 'b\"\n  shows \"x \\<le> y \\<or> y \\<le> x\"\n  by (cases x; cases y; auto) \n\n\ninstance \n  using less_le_not_le_sum order_refl_sum order_trans_sum antisym_sum linear_sum\n  by (intro_classes; metis+)\nend\n\n\nsubsection \\<open>Removing Proper Prefixes\\<close>\n\ndefinition remove_proper_prefixes :: \"'a list set \\<Rightarrow> 'a list set\" where\n  \"remove_proper_prefixes xs = {x . x \\<in> xs \\<and> (\\<nexists> x' . x' \\<noteq> [] \\<and> x@x' \\<in> xs)}\"\n\nlemma remove_proper_prefixes_code[code] :\n  \"remove_proper_prefixes (set xs) = set (filter (\\<lambda>x . (\\<forall> y \\<in> set xs . is_prefix x y \\<longrightarrow> x = y)) xs)\"\nproof -\n  \n  have *: \"remove_proper_prefixes (set xs) = Set.filter (\\<lambda> zs . \\<nexists>ys . ys \\<noteq> [] \\<and> zs @ ys \\<in> (set xs)) (set xs)\"\n    unfolding remove_proper_prefixes_def by force\n\n  have \"\\<And> zs . (\\<nexists>ys . ys \\<noteq> [] \\<and> zs @ ys \\<in> (set xs)) = (\\<forall> ys \\<in> set xs . is_prefix zs ys \\<longrightarrow> zs = ys)\"\n    unfolding is_prefix_prefix by auto\n  \n  then show ?thesis\n    unfolding * filter_set by auto\nqed\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 min_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\nlemma maximal_distinct_prefix :\n  assumes \"\\<not> distinct xs\"\n  obtains n where \"distinct (take (Suc n) xs)\"\n            and   \"\\<not> (distinct (take (Suc (Suc n)) xs))\"\nusing assms proof (induction xs rule: rev_induct)\n  case Nil\n  then show ?case by auto\nnext\n  case (snoc x xs)\n  \n  show ?case proof (cases \"distinct xs\")\n    case True\n    then have \"distinct (take (length xs) (xs@[x]))\" by auto\n    moreover have\"\\<not> (distinct (take (Suc (length xs)) (xs@[x])))\" using snoc.prems(2) by auto\n    ultimately show ?thesis using that by (metis Suc_pred distinct_singleton length_greater_0_conv self_append_conv2 snoc.prems(1) snoc.prems(2))\n  next\n    case False\n    \n    then show ?thesis using snoc.IH that\n      by (metis Suc_mono butlast_snoc length_append_singleton less_SucI linorder_not_le snoc.prems(1) take_all take_butlast) \n  qed\nqed \n\n\nlemma distinct_not_in_prefix :\n  assumes \"\\<And> i . (\\<And> x . x \\<in> set (take i xs) \\<Longrightarrow> xs ! i \\<noteq> x)\"\n  shows \"distinct xs\"\n  using assms list_distinct_prefix by blast \n\n\nlemma list_index_fun_gt : \"\\<And> xs (f::'a \\<Rightarrow> nat) i j . \n                              (\\<And> i . Suc i < length xs \\<Longrightarrow> f (xs ! i) > f (xs ! (Suc i))) \n                              \\<Longrightarrow> j < i \n                              \\<Longrightarrow> i < length xs \n                              \\<Longrightarrow> f (xs ! j) > f (xs ! i)\"\nproof -\n  fix xs::\"'a list\" \n  fix f::\"'a \\<Rightarrow> nat\" \n  fix i j \n  assume \"(\\<And> i . Suc i < length xs \\<Longrightarrow> f (xs ! i) > f (xs ! (Suc i)))\"\n     and \"j < i\"\n     and \"i < length xs\"\n  then show \"f (xs ! j) > f (xs ! i)\"\n  proof (induction \"i - j\" arbitrary: i j)\n    case 0\n    then show ?case by auto\n  next\n    case (Suc x)\n    then show ?case\n    proof -\n      have f1: \"\\<forall>n. \\<not> Suc n < length xs \\<or> f (xs ! Suc n) < f (xs ! n)\"\n        using Suc.prems(1) by presburger\n      have f2: \"\\<forall>n na. \\<not> n < na \\<or> Suc n \\<le> na\"\n        using Suc_leI by satx\n      have \"x = i - Suc j\"\n        by (metis Suc.hyps(2) Suc.prems(2) Suc_diff_Suc nat.simps(1))\n      then have \"\\<not> Suc j < i \\<or> f (xs ! i) < f (xs ! Suc j)\"\n        using f1 Suc.hyps(1) Suc.prems(3) by blast\n      then show ?thesis\n        using f2 f1 by (metis Suc.prems(2) Suc.prems(3) leI le_less_trans not_less_iff_gr_or_eq)\n    qed \n  qed\nqed\n\nlemma distinct_lists_finite :\n  assumes \"finite X\"\n  shows \"finite {xs . set xs \\<subseteq> X \\<and> distinct xs }\" \nproof -\n  define k where \"k = card X\"\n\n  have \"\\<And> xs . set xs \\<subseteq> X \\<Longrightarrow> distinct xs \\<Longrightarrow> length xs \\<le> k\"\n    using assms unfolding \\<open>k = card X\\<close>\n    by (metis card_mono distinct_card)\n\n  then have \"{xs . set xs \\<subseteq> X \\<and> distinct xs } \\<subseteq> {xs . set xs \\<subseteq> X \\<and> length xs \\<le> k}\"\n    by blast\n  moreover have \"finite {xs . set xs \\<subseteq> X \\<and> length xs \\<le> k}\"\n    using assms by (simp add: finite_lists_length_le) \n  ultimately show ?thesis\n    using rev_finite_subset by auto \nqed\n\n\nlemma finite_set_elem_maximal_extension_ex :\n  assumes \"xs \\<in> S\"\n  and     \"finite S\"\nshows \"\\<exists> ys . xs@ys \\<in> S \\<and> \\<not> (\\<exists> zs . zs \\<noteq> [] \\<and> xs@ys@zs \\<in> S)\"\nusing \\<open>finite S\\<close> \\<open>xs \\<in> S\\<close> proof (induction S arbitrary: xs)\n  case empty\n  then show ?case by auto\nnext\n  case (insert x S)\n\n  consider (a) \"\\<exists> ys . x = xs@ys \\<and> \\<not> (\\<exists> zs . zs \\<noteq> [] \\<and> xs@ys@zs \\<in> (insert x S))\" |\n           (b) \"\\<not>(\\<exists> ys . x = xs@ys \\<and> \\<not> (\\<exists> zs . zs \\<noteq> [] \\<and> xs@ys@zs \\<in> (insert x S)))\"\n    by blast\n  then show ?case proof cases\n    case a\n    then show ?thesis by auto\n  next\n    case b\n    then show ?thesis proof (cases \"\\<exists> vs . vs \\<noteq> [] \\<and> xs@vs \\<in> S\")\n      case True\n      then obtain vs where \"vs \\<noteq> []\" and \"xs@vs \\<in> S\"\n        by blast\n      \n      have \"\\<exists>ys. xs @ (vs @ ys) \\<in> S \\<and> (\\<nexists>zs. zs \\<noteq> [] \\<and> xs @ (vs @ ys) @ zs \\<in> S)\"\n        using insert.IH[OF \\<open>xs@vs \\<in> S\\<close>] by auto\n      then have \"\\<exists>ys. xs @ (vs @ ys) \\<in> S \\<and> (\\<nexists>zs. zs \\<noteq> [] \\<and> xs @ (vs @ ys) @ zs \\<in> (insert x S))\"\n        using b \n        unfolding append.assoc append_is_Nil_conv append_self_conv insert_iff\n        by (metis append.assoc append_Nil2 append_is_Nil_conv same_append_eq) \n      then show ?thesis by blast\n    next\n      case False\n      then show ?thesis using insert.prems\n        by (metis append_is_Nil_conv append_self_conv insertE same_append_eq) \n    qed\n  qed\nqed\n\n\nlemma list_index_split_set: \n  assumes \"i < length xs\"\nshows \"set xs = set ((xs ! i) # ((take i xs) @ (drop (Suc i) xs)))\"  \nusing assms proof (induction xs arbitrary: i)\n  case Nil\n  then show ?case by auto\nnext\n  case (Cons x xs)\n  then show ?case proof (cases i)\n    case 0\n    then show ?thesis by auto\n  next\n    case (Suc j)\n    then have \"j < length xs\" using Cons.prems by auto\n    then have \"set xs = set ((xs ! j) # ((take j xs) @ (drop (Suc j) xs)))\" using Cons.IH[of j] by blast\n    \n    have *: \"take (Suc j) (x#xs) = x#(take j xs)\" by auto\n    have **: \"drop (Suc (Suc j)) (x#xs) = (drop (Suc j) xs)\" by auto\n    have ***: \"(x # xs) ! Suc j = xs ! j\" by auto\n    \n    show ?thesis\n      using \\<open>set xs = set ((xs ! j) # ((take j xs) @ (drop (Suc j) xs)))\\<close>\n      unfolding Suc * ** *** by auto\n  qed\nqed\n\n\nlemma max_by_foldr :\n  assumes \"x \\<in> set xs\"\n  shows \"f x < Suc (foldr (\\<lambda> x' m . max (f x') m) xs 0)\"\n  using assms by (induction xs; auto)\n\nlemma Max_elem : \"finite (xs :: 'a set) \\<Longrightarrow> xs \\<noteq> {} \\<Longrightarrow> \\<exists> x \\<in> xs . Max (image (f :: 'a \\<Rightarrow> nat) xs) = f x\"\n  by (metis (mono_tags, hide_lams) Max_in empty_is_image finite_imageI imageE)\n\n\nlemma card_union_of_singletons :\n  assumes \"\\<And> S . S \\<in> SS \\<Longrightarrow> (\\<exists> t . S = {t})\"\nshows \"card (\\<Union> SS) = card SS\"\nproof -\n  let ?f = \"\\<lambda> x . {x}\"\n  have \"bij_betw ?f (\\<Union> SS) SS\" \n    unfolding bij_betw_def inj_on_def using assms by fastforce\n  then show ?thesis \n    using bij_betw_same_card by blast \nqed\n\nlemma card_union_of_distinct :\n  assumes \"\\<And> S1 S2 . S1 \\<in> SS \\<Longrightarrow> S2 \\<in> SS \\<Longrightarrow> S1 = S2 \\<or> f S1 \\<inter> f S2 = {}\"\n  and     \"finite SS\"\n  and     \"\\<And> S . S \\<in> SS \\<Longrightarrow> f S \\<noteq> {}\"\nshows \"card (image f SS) = card SS\" \nproof -\n  from assms(2) have \"\\<forall> S1 \\<in> SS . \\<forall> S2 \\<in> SS . S1 = S2 \\<or> f S1 \\<inter> f S2 = {} \n                      \\<Longrightarrow> \\<forall> S \\<in> SS . f S \\<noteq> {} \\<Longrightarrow> ?thesis\"\n  proof (induction SS)\n    case empty\n    then show ?case by auto\n  next\n    case (insert x F)\n    then have \"\\<not> (\\<exists> y \\<in> F . f y = f x)\" \n      by auto\n    then have \"f x \\<notin> image f F\" \n      by auto\n    then have \"card (image f (insert x F)) = Suc (card (image f F))\" \n      using insert by auto\n    moreover have \"card (f ` F) = card F\" \n      using insert by auto\n    moreover have \"card (insert x F) = Suc (card F)\" \n      using insert by auto\n    ultimately show ?case \n      by simp\n  qed\n  then show ?thesis \n    using assms by simp\nqed\n\n\nlemma take_le :\n  assumes \"i \\<le> length xs\"\n  shows \"take i (xs@ys) = take i xs\"\n  by (simp add: assms less_imp_le_nat)\n\n\nlemma butlast_take_le :\n  assumes \"i \\<le> length (butlast xs)\" \n  shows \"take i (butlast xs) = take i xs\" \n  using take_le[OF assms, of \"[last xs]\"]\n  by (metis append_butlast_last_id butlast.simps(1)) \n\n\nlemma distinct_union_union_card :\n  assumes \"finite xs\"\n  and     \"\\<And> x1 x2 y1 y2 . x1 \\<noteq> x2 \\<Longrightarrow> x1 \\<in> xs \\<Longrightarrow> x2 \\<in> xs \\<Longrightarrow> y1 \\<in> f x1 \\<Longrightarrow> y2 \\<in> f x2 \\<Longrightarrow> g y1 \\<inter> g y2 = {}\"\n  and     \"\\<And> x1 y1 y2 . y1 \\<in> f x1 \\<Longrightarrow> y2 \\<in> f x1 \\<Longrightarrow> y1 \\<noteq> y2 \\<Longrightarrow> g y1 \\<inter> g y2 = {}\"\n  and     \"\\<And> x1 . finite (f x1)\"\n  and     \"\\<And> y1 . finite (g y1)\"\n  and     \"\\<And> y1 . g y1 \\<subseteq> zs\"\n  and     \"finite zs\"\nshows \"(\\<Sum> x \\<in> xs . card (\\<Union> y \\<in> f x . g y)) \\<le> card zs\" \nproof -\n  have \"(\\<Sum> x \\<in> xs . card (\\<Union> y \\<in> f x . g y)) = card (\\<Union> x \\<in> xs . (\\<Union> y \\<in> f x . g y))\"\n    using assms(1,2) proof induction\n    case empty\n    then show ?case by auto\n  next\n    case (insert x xs)\n    then have \"(\\<And>x1 x2. x1 \\<in> xs \\<Longrightarrow> x2 \\<in> xs \\<Longrightarrow> x1 \\<noteq> x2 \\<Longrightarrow> \\<Union> (g ` f x1) \\<inter> \\<Union> (g ` f x2) = {})\" and \"x \\<in> insert x xs\" by blast+\n    then have \"(\\<Sum>x\\<in>xs. card (\\<Union> (g ` f x))) = card (\\<Union>x\\<in>xs. \\<Union> (g ` f x))\" using insert.IH by blast\n\n    moreover have \"(\\<Sum>x\\<in>(insert x xs). card (\\<Union> (g ` f x))) = (\\<Sum>x\\<in>xs. card (\\<Union> (g ` f x))) + card (\\<Union> (g ` f x))\"\n      using insert.hyps by auto\n\n    moreover have \"card (\\<Union>x\\<in>(insert x xs). \\<Union> (g ` f x)) = card (\\<Union>x\\<in>xs. \\<Union> (g ` f x)) + card (\\<Union> (g ` f x))\"\n    proof -\n      have \"((\\<Union>x\\<in>xs. \\<Union> (g ` f x)) \\<union> \\<Union> (g ` f x)) = (\\<Union>x\\<in>(insert x xs). \\<Union> (g ` f x))\"\n        by blast\n\n      have *: \"(\\<Union>x\\<in>xs. \\<Union> (g ` f x)) \\<inter> (\\<Union> (g ` f x)) = {}\"\n      proof (rule ccontr)\n        assume \"(\\<Union>x\\<in>xs. \\<Union> (g ` f x)) \\<inter> \\<Union> (g ` f x)\\<noteq> {}\"\n        then obtain z where \"z \\<in> \\<Union> (g ` f x)\" and \"z \\<in> (\\<Union>x\\<in>xs. \\<Union> (g ` f x))\" by blast\n        then obtain x' where \"x' \\<in> xs\" and \"z \\<in> \\<Union> (g ` f x')\" by blast\n        then have \"x' \\<noteq> x\" and \"x' \\<in> insert x xs\" using insert.hyps by blast+\n\n        have \"\\<Union> (g ` f x') \\<inter> \\<Union> (g ` f x) = {}\"\n          using insert.prems[OF \\<open>x' \\<noteq> x\\<close> \\<open>x' \\<in> insert x xs\\<close> \\<open>x \\<in> insert x xs\\<close> ]\n          by blast \n        then show \"False\"\n          using \\<open>z \\<in> \\<Union> (g ` f x')\\<close> \\<open>z \\<in> \\<Union> (g ` f x)\\<close> by blast\n      qed\n      have **: \"finite (\\<Union> (g ` f x))\"\n        using assms(4) assms(5) by blast \n      have ***: \"finite (\\<Union>x\\<in>xs. \\<Union> (g ` f x))\"\n        by (simp add: assms(4) assms(5) insert.hyps(1))\n\n      have \"card ((\\<Union>x\\<in>xs. \\<Union> (g ` f x)) \\<union> \\<Union> (g ` f x)) = card (\\<Union>x\\<in>xs. \\<Union> (g ` f x)) + card (\\<Union> (g ` f x))\" \n        using card_Un_disjoint[OF *** ** *] by simp\n\n      \n      then show ?thesis \n        unfolding \\<open>((\\<Union>x\\<in>xs. \\<Union> (g ` f x)) \\<union> \\<Union> (g ` f x)) = (\\<Union>x\\<in>(insert x xs). \\<Union> (g ` f x))\\<close> by assumption\n    qed\n\n    ultimately show ?case by linarith\n  qed\n\n  moreover have \"card (\\<Union> x \\<in> xs . (\\<Union> y \\<in> f x . g y)) \\<le> card zs\"\n  proof -\n    have \"(\\<Union> x \\<in> xs . (\\<Union> y \\<in> f x . g y)) \\<subseteq> zs\"\n      using assms(6) by (simp add: UN_least) \n    moreover have \"finite (\\<Union> x \\<in> xs . (\\<Union> y \\<in> f x . g y))\"\n      by (simp add: assms(1) assms(4) assms(5)) \n    ultimately show ?thesis\n      using assms(7)\n      by (simp add: card_mono) \n  qed\n\n  ultimately show ?thesis\n    by linarith \nqed\n\n\nlemma set_concat_elem :\n  assumes \"x \\<in> set (concat xss)\"\n  obtains xs where \"xs \\<in> set xss\" and \"x \\<in> set xs\" \n  using assms by auto\n\nlemma set_map_elem :\n  assumes \"y \\<in> set (map f xs)\"\n  obtains x where \"y = f x\" and \"x \\<in> set xs\" \n  using assms by auto\n\nlemma finite_snd_helper: \n  assumes \"finite xs\" \n  shows \"finite {z. ((q, p), z) \\<in> xs}\" \nproof -\n  have \"{z. ((q, p), z) \\<in> xs} \\<subseteq> (\\<lambda>((a,b),c) . c) ` xs\" \n  proof \n    fix x assume \"x \\<in> {z. ((q, p), z) \\<in> xs}\"\n    then have \"((q,p),x) \\<in> xs\" by auto\n    then show \"x \\<in> (\\<lambda>((a,b),c) . c) ` xs\" by force\n  qed\n  then show ?thesis using assms\n    using finite_surj by blast \nqed\n\nlemma fold_dual : \"fold (\\<lambda> x (a1,a2) . (g1 x a1, g2 x a2)) xs (a1,a2) = (fold g1 xs a1, fold g2 xs a2)\"\n  by (induction xs arbitrary: a1 a2; auto)\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/Experiments/Util.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8519527944504227, "lm_q2_score": 0.8354835391516132, "lm_q1q2_score": 0.711792535897546}}
{"text": "theory IsarTutorial_Answer\nimports Main\nbegin\n\n\nlemma \"Exer1-1_Answer_pattern_1\": \"Q \\<Longrightarrow> (P \\<longrightarrow> Q)\"\nproof (rule impI)\n  assume q: \"Q\"\n  show \"Q\" by (rule q)\nqed\n\n\nlemma \"Exer1-1_Answer_pattern_2\": \"Q \\<Longrightarrow> (P \\<longrightarrow> Q)\"\nproof (rule impI) qed\n\n\nlemma \"Exer1-1_Answer_pattern_3\": \"Q \\<Longrightarrow> (P \\<longrightarrow> Q)\"\nproof (rule impI)\n  assume q: \"Q\"\n  from this show \"Q\" by assumption\nqed\n\n\nlemma \"Exer1-2\": \"(P \\<and> Q) \\<and> R \\<longrightarrow> Q\"\nproof (rule impI)\n  assume pqr: \"(P \\<and> Q) \\<and> R\"\n  from pqr show \"Q\"\n  proof (rule conjE)\n    assume pq: \"P \\<and> Q\" and r: \"R\"\n    from pq show \"Q\" by (rule conjunct2)\n  qed\nqed\n\n\nlemma \"Exer2-1\": \"P \\<longrightarrow> (P \\<longrightarrow> Q) \\<Longrightarrow> P \\<longrightarrow> Q\"\nproof (rule impI)\n  assume \"P \\<longrightarrow> (P \\<longrightarrow> Q)\" \"P\"\n  then have \"P \\<longrightarrow> Q\" by (rule mp)\n  with `P` show \"Q\" by (rule rev_mp)\nqed\n\n\nlemma \"Exer2-2\": \"P \\<or> Q \\<longrightarrow> R \\<Longrightarrow> P \\<Longrightarrow> R\"\nproof -\n  assume \"P\"\n  then have \"P \\<or> Q\" by (rule disjI1)\n  assume \"P \\<or> Q \\<longrightarrow> R\"\n  with `P \\<or> Q` show \"R\" by (rule rev_mp)\nqed\n\n\nlemma \"Exer2-3\": \"(P \\<longrightarrow> Q) \\<longrightarrow> (\\<not>Q \\<longrightarrow> \\<not>P)\"\nproof ((rule impI)+, rule notI)\n  assume \"P \\<longrightarrow> Q\" \"P\"\n  then have \"Q\" by (rule mp)\n  assume \"\\<not>Q\"\n  from this `Q` show \"False\" by (rule notE)\nqed\n\n\nlemma \"Exer2-4\": \n  assumes \"P \\<or> Q\" \"\\<not>P\"\n  shows \"Q\"\n  using assms(1)\nproof (rule disjE)\n  assume \"P\"\n  with assms(2) show \"Q\" by (rule notE)\nnext\n  assume \"Q\"\n  show \"Q\" by (rule `Q`)\nqed\n\n\nlemma \"Exer2-5\": \n  assumes \"(P \\<or> Q) \\<longrightarrow> R\"\n  shows \"(P \\<longrightarrow> R) \\<and> (Q \\<longrightarrow> R)\"\nproof (rule conjI)\n  show \"P \\<longrightarrow> R\"\n  proof (rule impI)\n    assume \"P\"\n    then have \"P \\<or> Q\" by (rule disjI1)\n    with assms(1) show \"R\" by (rule mp)\n  qed\nnext\n  show \"Q \\<longrightarrow> R\"\n  proof (rule impI)\n    assume \"Q\"\n    then have \"P \\<or> Q\" by (rule disjI2)\n    with assms(1) show \"R\" by (rule mp)\n  qed\nqed\n\n\nlemma \"Exer3-1\": \n  assumes \"\\<forall>x. P x\" and \"\\<forall>x. P x \\<longrightarrow> Q x\"\n  shows \"\\<forall>x. Q x\"\nproof (rule allI)\n  fix x\n  from assms(1) have 1: \"P x\" by (rule spec)\n  from assms(2) have 2: \"P x \\<longrightarrow> Q x\" by (rule spec)\n  from 2 1 show \"Q x\" by (rule mp)\nqed\n\n\nlemma \"Exer3-2\": \n  assumes \"\\<forall>x. (P x \\<longrightarrow> (\\<exists>y. Q y))\"\n  shows \"(\\<exists>x. P x) \\<longrightarrow> (\\<exists>x. Q x)\"\nproof (rule impI)\n  assume \"\\<exists>x. P x\"\n  then obtain x where 1: \"P x\" by (rule exE)\n  from assms(1) have 2: \"P x \\<longrightarrow> (\\<exists>y. Q y)\" by (rule spec)\n  from 2 1 show \"\\<exists>x. Q x\" by (rule mp)\nqed\n\n\nlemma \"Exer3-3(don't use obtain)\": \n  assumes \"\\<exists>x. P x\"\n  shows \"\\<exists>x. (P x \\<or> Q x)\"\n  using assms\nproof (rule exE)\n  fix x\n  assume \"P x\"\n  then have \"P x \\<or> Q x\" by (rule disjI1)\n  then show \"\\<exists>x. (P x \\<or> Q x)\" by (rule exI)\nqed\n\n\nlemma \"Exer3-4\": \"x \\<in> \\<Union>C \\<Longrightarrow> \\<exists>A\\<in>C. x \\<in> A\"\n(* hint *)\nthm UnionE (* ?A \\<in> \\<Union> ?C \\<Longrightarrow> (\\<And>X. ?A \\<in> X \\<Longrightarrow> X \\<in> ?C \\<Longrightarrow> ?R) \\<Longrightarrow> ?R *)\nthm bexI   (* ?P ?x \\<Longrightarrow> ?x \\<in> ?A \\<Longrightarrow> \\<exists>x\\<in>?A. ?P x *)\nproof -\n  assume \"x \\<in> \\<Union>C\"\n  then obtain \"A\" where \"x \\<in> A\" and \"A \\<in> C\"  by (rule UnionE)\n  then show \"\\<exists>A\\<in>C. x \\<in> A\" by (rule bexI)\nqed\n\n\nlemma \"Exer4-1(use moreover, ultimately)\": \"A \\<and> B \\<Longrightarrow> B \\<and> A\"\nproof -\n  assume a: \"A \\<and> B\"\n  then have \"B\" by (rule conjunct2)\n  moreover\n  from a have \"A\" by (rule conjunct1)\n  ultimately show \"B \\<and> A\" by (rule conjI)\nqed\n\n\nlemma \"Exer4-2(use moreover, ultimately)\": \n  assumes \"(P \\<longrightarrow> Q) \\<and> (\\<not>P \\<longrightarrow> Q)\"\n  shows \"Q\"\n  using assms\nproof(rule conjE)\n  assume 1: \"P \\<longrightarrow> Q\" and 2: \"\\<not>P \\<longrightarrow> Q\"\n  {\n    assume \"P\"\n    with 1 have \"Q\" by (rule mp)\n  }\n  moreover\n  {\n    assume \"\\<not>P\"\n    with 2 have \"Q\" by (rule mp)\n  }\n  ultimately show \"Q\" by (cases \"P\")\nqed\n\n\nlemma \"Exer4-3\": \"(P \\<longrightarrow> Q) \\<and> (\\<not>P \\<longrightarrow> Q) \\<Longrightarrow> Q\"\nproof (cases \"P\")\n  case True\n  assume \"(P \\<longrightarrow> Q) \\<and> (\\<not>P \\<longrightarrow> Q)\"\n  then show ?thesis\n  proof (rule conjE)\n    assume \"P \\<longrightarrow> Q\"\n    with True show ?thesis by (rule rev_mp)\n  qed\nnext\n  case False\n  assume \"(P \\<longrightarrow> Q) \\<and> (\\<not>P \\<longrightarrow> Q)\"\n  then show ?thesis\n  proof (rule conjE)\n    assume \"\\<not>P \\<longrightarrow> Q\"\n    with False show ?thesis by (rule rev_mp)\n  qed\nqed\n\n\nlemma \"Exer4-4\": \"\\<forall>x. P \\<or> Q x \\<Longrightarrow> P \\<or> (\\<forall>x. Q x)\"\nproof (cases \"P\")\n  case True\n  then show ?thesis by (rule disjI1)\nnext\n  case False\n  assume 1: \"\\<forall>x. P \\<or> Q x\"\n  show ?thesis\n  proof (rule disjI2)\n    show \"\\<forall>x. Q x\"\n    proof (rule allI)\n      fix x      \n      from 1 have 2:\"P \\<or> Q x\" by (rule spec)\n      from 2 show \"Q x\"\n      proof (rule disjE)\n        assume \"P\"\n        with False show ?thesis by (rule notE)\n      qed\n    qed\n  qed\nqed\n\n\nlemma \"Exer4-5\": \"if y \\<le> x then z = x else z = y \\<Longrightarrow> z = x \\<or> z = y\"\n(* hint *)\nthm if_P      (* ?P \\<Longrightarrow> (if ?P then ?x else ?y) = ?x *)\nthm if_not_P  (* \\<not> ?P \\<Longrightarrow> (if ?P then ?x else ?y) = ?y *)\nproof (cases \"y \\<le> x\")\n  case True\n  assume a: \"if y \\<le> x then z = x else z = y\"\n  show ?thesis\n  proof (rule disjI1)\n    from True have 1: \"(if y \\<le> x then z = x else z = y) = (z = x)\" by (rule if_P)\n    from a show \"z = x\" by (subst (asm) 1)\n  qed\nnext\n  case False\n  assume a: \"if y \\<le> x then z = x else z = y\"\n  show ?thesis \n  proof (rule disjI2)\n    from False have 1: \"(if y \\<le> x then z = x else z = y) = (z = y)\" by (rule if_not_P)\n    from a show \"z = y\" by (subst (asm) 1)\n  qed\nqed\n\n\nprimrec add :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\" where\n\"add m 0 = m\" |\n\"add m (Suc n) = add (Suc m) n\"\n\n\nlemma \"Exer8-1\": \"\\<forall>m. add m n = m + n\"\n(* hint *)\nthm add.simps(1) (* add ?m 0 = ?m *)\nthm add.simps(2) (* add ?m (Suc ?n) = add (Suc ?m) ?n *)\nthm add_0_right  (* ?a + 0 = ?a *)\nthm add_Suc_shift (* Suc ?m + ?n = ?m + Suc ?n *)\nproof (induction n)\n  case 0\n  then show ?case\n  proof (rule allI)\n    fix m\n    show \"add m 0 = m + 0\"\n      by (subst add.simps(1), subst add_0_right, rule refl)\n  qed\nnext\n  case (Suc n)\n  show ?case\n  proof (rule allI)\n    fix m\n    have \"add m (Suc n) = add (Suc m) n\" by (rule add.simps(2))\n    also have \"... = (Suc m) + n\" by (subst Suc) (rule refl)\n    also have \"... = m + Suc n\" by (rule add_Suc_shift)\n    finally show \"add m (Suc n) = m + Suc n\" .\n  qed\nqed\n", "meta": {"author": "DeNA", "repo": "IsarTutorial", "sha": "3bf7637d977e41a705a042cffb41760e2ff8869f", "save_path": "github-repos/isabelle/DeNA-IsarTutorial", "path": "github-repos/isabelle/DeNA-IsarTutorial/IsarTutorial-3bf7637d977e41a705a042cffb41760e2ff8869f/IsarTutorial_Answer.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936437, "lm_q2_score": 0.8705972600147106, "lm_q1q2_score": 0.7117780988321484}}
{"text": "(*  Title:      Sort.thy\n    Author:     Danijela Petrovi\\'c, Facylty of Mathematics, University of Belgrade *)\n\nsection \\<open>Verification of Heap Sort\\<close>\n\ntheory Heap\nimports RemoveMax\nbegin\n\nsubsection \\<open>Defining tree and properties of heap\\<close>\n\ndatatype 'a Tree = \"E\" | \"T\" 'a \"'a Tree\" \"'a Tree\"\n\ntext\\<open>With {\\em E} is represented empty tree and with {\\em T\\ \\ \\ 'a\\ \\ \\ 'a\n  Tree\\ \\ \\ 'a Tree} is represented a node whose root element is of\ntype {\\em 'a} and its left and right branch is also a tree of\ntype {\\em 'a}.\\<close>\n\nprimrec size :: \"'a Tree \\<Rightarrow> nat\" where\n  \"size E = 0\"\n| \"size (T v l r) = 1 + size l + size r\"\n\ntext\\<open>Definition of the function that makes a multiset from the given tree:\\<close>\n\nprimrec multiset where\n  \"multiset E = {#}\"\n| \"multiset (T v l r) = multiset l + {#v#} + multiset r\"\n\nprimrec val where\n \"val (T v _ _) = v\"\n\ntext\\<open>Definition of the function that has the value {\\em True} if the tree is\nheap, otherwise it is {\\em False}:\\<close>\n\nfun is_heap :: \"'a::linorder Tree \\<Rightarrow> bool\" where\n  \"is_heap E = True\"\n| \"is_heap (T v E E) = True\"\n| \"is_heap (T v E r) = (v \\<ge> val r \\<and> is_heap r)\"\n| \"is_heap (T v l E) = (v \\<ge> val l \\<and> is_heap l)\"\n| \"is_heap (T v l r) = (v \\<ge> val r \\<and> is_heap r \\<and> v \\<ge> val l \\<and> is_heap l)\"\n\nlemma heap_top_geq:\n  assumes \"a \\<in># multiset t\" \"is_heap t\"\n  shows \"val t \\<ge> a\"\nusing assms\nby (induct t rule: is_heap.induct)  (auto split: if_split_asm)\n\nlemma heap_top_max:\n  assumes \"t \\<noteq> E\" \"is_heap t\"\n  shows \"val t = Max_mset (multiset t)\"\nproof (rule Max_eqI[symmetric])\n  fix y\n  assume \"y \\<in> set_mset (multiset t)\"\n  thus \"y \\<le> val t\"\n    using heap_top_geq [of y t] \\<open>is_heap t\\<close>\n    by simp\nnext\n  show \"val t \\<in> set_mset (multiset t)\"\n    using \\<open>t \\<noteq> E\\<close>\n    by (cases t) auto\nqed simp\n\ntext\\<open>The next step is to define function {\\em remove\\_max}, but the\nquestion is weather implementation of {\\em remove\\_max} depends on\nimplementation of the functions {\\em is\\_heap} and {\\em multiset}. The\nanswer is negative. This suggests that another step of refinement\ncould be added before definition of function {\\em\n  remove\\_max}. Additionally, there are other reasons why this should\nbe done, for example, function {\\em remove\\_max} could be implemented\nin functional or in imperative manner.\n\\<close>\n\nlocale Heap =  Collection empty is_empty of_list  multiset for \n  empty :: \"'b\" and \n  is_empty :: \"'b \\<Rightarrow> bool\" and \n  of_list :: \"'a::linorder list \\<Rightarrow> 'b\" and \n  multiset :: \"'b \\<Rightarrow> 'a::linorder multiset\" + \n  fixes as_tree :: \"'b \\<Rightarrow> 'a::linorder Tree\"\n  \\<comment> \\<open>This function is not very important, but it is needed in order to avoide problems with types and to detect that observed object is a tree.\\<close>\n  fixes remove_max :: \"'b \\<Rightarrow> 'a \\<times> 'b\"\n  assumes multiset: \"multiset l = Heap.multiset (as_tree l)\"\n  assumes is_heap_of_list: \"is_heap (as_tree (of_list i))\"\n  assumes as_tree_empty: \"as_tree t = E \\<longleftrightarrow> is_empty t\"\n  assumes remove_max_multiset': \n  \"\\<lbrakk>\\<not> is_empty l; (m, l') = remove_max l\\<rbrakk> \\<Longrightarrow> add_mset m (multiset l') = multiset l\"\n  assumes remove_max_is_heap: \n  \"\\<lbrakk>\\<not> is_empty l; is_heap (as_tree l); (m, l') = remove_max l\\<rbrakk> \\<Longrightarrow> \n  is_heap (as_tree l')\"\n  assumes remove_max_val: \n  \"\\<lbrakk> \\<not> is_empty t; (m, t') = remove_max t\\<rbrakk> \\<Longrightarrow> m = val (as_tree t)\"\n\ntext\\<open>It is very easy to prove that locale {\\em Heap} is sublocale of locale {\\em RemoveMax}\\<close>\n\nsublocale Heap < \n  RemoveMax empty is_empty of_list multiset remove_max \"\\<lambda> t. is_heap (as_tree t)\"\nproof\n  fix x\n  show \"is_heap (as_tree (of_list x))\"\n    by (rule is_heap_of_list)\nnext\n  fix l m l'\n  assume \"\\<not> is_empty l\" \"(m, l') = remove_max l\" \n  thus \"add_mset m (multiset l') = multiset l\"\n    by (rule remove_max_multiset')\nnext\n  fix l m l'\n  assume \"\\<not> is_empty l\" \"is_heap (as_tree l)\" \"(m, l') = remove_max l\" \n  thus \"is_heap (as_tree l')\"\n    by (rule remove_max_is_heap)\nnext\n  fix l m l'\n  assume \"\\<not> is_empty l\" \"is_heap (as_tree l)\" \"(m, l') = remove_max l\" \n  thus \"m = Max (set l)\"\n    unfolding set_def\n    using heap_top_max[of \"as_tree l\"] remove_max_val[of l m l'] \n    using multiset is_empty_inj as_tree_empty\n    by auto\nqed\n\nprimrec in_tree where\n  \"in_tree v E = False\"\n| \"in_tree v (T v' l r) \\<longleftrightarrow> v = v' \\<or> in_tree v l \\<or> in_tree v r\"\n\nlemma is_heap_max:\n  assumes \"in_tree v t\" \"is_heap t\"\n  shows \"val t \\<ge> v\"\nusing assms\napply (induct t rule:is_heap.induct)\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/Selection_Heap_Sort/Heap.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8807970873650401, "lm_q2_score": 0.8080672135527632, "lm_q1q2_score": 0.7117432480924577}}
{"text": "theory Isar imports Main begin\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\n    by (auto simp: surj_def)\n  thus \"False\" by blast\nqed\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(* A typical proof by case analysis on the form of xs: *)\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\n(* Alternative: *)\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  thus ?thesis by simp\nqed\n\nlemma \"\\<Sigma> {0..n :: nat} = n * (n+1) div 2\"\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": "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/Isar.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970779778825, "lm_q2_score": 0.8080672089305841, "lm_q1q2_score": 0.7117432364358016}}
{"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.*)\n  theory TIP_prop_72\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 take :: \"Nat => 'a list => 'a list\" where\n\"take (Z) z = nil2\"\n| \"take (S z2) (nil2) = nil2\"\n| \"take (S z2) (cons2 x2 x3) = cons2 x2 (take z2 x3)\"\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 len :: \"'a list => Nat\" where\n\"len (nil2) = Z\"\n| \"len (cons2 z xs) = S (len xs)\"\n\nfun drop :: \"Nat => 'a list => 'a list\" where\n\"drop (Z) z = z\"\n| \"drop (S z2) (nil2) = nil2\"\n| \"drop (S z2) (cons2 x2 x3) = drop z2 x3\"\n\nfun t2 :: \"Nat => Nat => Nat\" where\n\"t2 (Z) z = Z\"\n| \"t2 (S z2) (Z) = S z2\"\n| \"t2 (S z2) (S x2) = t2 z2 x2\"\n\ntheorem property0 :\n  \"((rev (drop i xs)) = (take (t2 (len xs) i) (rev 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/Isaplanner/Isaplanner/TIP_prop_72.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587964389112, "lm_q2_score": 0.8006919949619793, "lm_q1q2_score": 0.7116220537606794}}
{"text": "section \\<open>Lexicographic orderings\\<close>\n\ntheory Lexord\n  imports Main\nbegin\n\nsubsection \\<open>The preorder case\\<close>\n\nlocale lex_preordering = preordering\nbegin\n\ninductive lex_less :: \\<open>'a list \\<Rightarrow> 'a list \\<Rightarrow> bool\\<close>  (infix \\<open>[\\<^bold><]\\<close> 50) \nwhere\n  Nil: \\<open>[] [\\<^bold><] y # ys\\<close>\n| Cons: \\<open>x \\<^bold>< y \\<Longrightarrow> x # xs [\\<^bold><] y # ys\\<close>\n| Cons_eq: \\<open>x \\<^bold>\\<le> y \\<Longrightarrow> y \\<^bold>\\<le> x \\<Longrightarrow> xs [\\<^bold><] ys \\<Longrightarrow> x # xs [\\<^bold><] y # ys\\<close>\n\ninductive lex_less_eq :: \\<open>'a list \\<Rightarrow> 'a list \\<Rightarrow> bool\\<close>  (infix \\<open>[\\<^bold>\\<le>]\\<close> 50)\nwhere\n  Nil: \\<open>[] [\\<^bold>\\<le>] ys\\<close>\n| Cons: \\<open>x \\<^bold>< y \\<Longrightarrow> x # xs [\\<^bold>\\<le>] y # ys\\<close>\n| Cons_eq: \\<open>x \\<^bold>\\<le> y \\<Longrightarrow> y \\<^bold>\\<le> x \\<Longrightarrow> xs [\\<^bold>\\<le>] ys \\<Longrightarrow> x # xs [\\<^bold>\\<le>] y # ys\\<close>\n\nlemma lex_less_simps [simp]:\n  \\<open>[] [\\<^bold><] y # ys\\<close>\n  \\<open>\\<not> xs [\\<^bold><] []\\<close>\n  \\<open>x # xs [\\<^bold><] y # ys \\<longleftrightarrow> x \\<^bold>< y \\<or> x \\<^bold>\\<le> y \\<and> y \\<^bold>\\<le> x \\<and> xs [\\<^bold><] ys\\<close>\n  by (auto intro: lex_less.intros elim: lex_less.cases)\n\nlemma lex_less_eq_simps [simp]:\n  \\<open>[] [\\<^bold>\\<le>] ys\\<close>\n  \\<open>\\<not> x # xs [\\<^bold>\\<le>] []\\<close>\n  \\<open>x # xs [\\<^bold>\\<le>] y # ys \\<longleftrightarrow> x \\<^bold>< y \\<or> x \\<^bold>\\<le> y \\<and> y \\<^bold>\\<le> x \\<and> xs [\\<^bold>\\<le>] ys\\<close>\n  by (auto intro: lex_less_eq.intros elim: lex_less_eq.cases)\n\nlemma lex_less_code [code]:\n  \\<open>[] [\\<^bold><] y # ys \\<longleftrightarrow> True\\<close>\n  \\<open>xs [\\<^bold><] [] \\<longleftrightarrow> False\\<close>\n  \\<open>x # xs [\\<^bold><] y # ys \\<longleftrightarrow> x \\<^bold>< y \\<or> x \\<^bold>\\<le> y \\<and> y \\<^bold>\\<le> x \\<and> xs [\\<^bold><] ys\\<close>\n  by simp_all\n\nlemma lex_less_eq_code [code]:\n  \\<open>[] [\\<^bold>\\<le>] ys \\<longleftrightarrow> True\\<close>\n  \\<open>x # xs [\\<^bold>\\<le>] [] \\<longleftrightarrow> False\\<close>\n  \\<open>x # xs [\\<^bold>\\<le>] y # ys \\<longleftrightarrow> x \\<^bold>< y \\<or> x \\<^bold>\\<le> y \\<and> y \\<^bold>\\<le> x \\<and> xs [\\<^bold>\\<le>] ys\\<close>\n  by simp_all\n\nlemma preordering:\n  \\<open>preordering ([\\<^bold>\\<le>]) ([\\<^bold><])\\<close>\nproof\n  fix xs ys zs\n  show \\<open>xs [\\<^bold>\\<le>] xs\\<close>\n    by (induction xs) (simp_all add: refl)\n  show \\<open>xs [\\<^bold>\\<le>] zs\\<close> if \\<open>xs [\\<^bold>\\<le>] ys\\<close> \\<open>ys [\\<^bold>\\<le>] zs\\<close>\n  using that proof (induction arbitrary: zs)\n    case (Nil ys)\n    then show ?case by simp\n  next\n    case (Cons x y xs ys)\n    then show ?case\n      by (cases zs) (auto dest: strict_trans strict_trans2)\n  next\n    case (Cons_eq x y xs ys)\n    then show ?case\n      by (cases zs) (auto dest: strict_trans1 intro: trans)\n  qed\n  show \\<open>xs [\\<^bold><] ys \\<longleftrightarrow> xs [\\<^bold>\\<le>] ys \\<and> \\<not> ys [\\<^bold>\\<le>] xs\\<close> (is \\<open>?P \\<longleftrightarrow> ?Q\\<close>)\n  proof\n    assume ?P\n    then have \\<open>xs [\\<^bold>\\<le>] ys\\<close>\n      by induction simp_all\n    moreover have \\<open>\\<not> ys [\\<^bold>\\<le>] xs\\<close>\n      using \\<open>?P\\<close>\n      by induction (simp_all, simp_all add: strict_iff_not asym)\n    ultimately show ?Q ..\n  next\n    assume ?Q\n    then have \\<open>xs [\\<^bold>\\<le>] ys\\<close> \\<open>\\<not> ys [\\<^bold>\\<le>] xs\\<close>\n      by auto\n    then show ?P\n    proof induction\n      case (Nil ys)\n      then show ?case\n        by (cases ys) simp_all\n    next\n      case (Cons x y xs ys)\n      then show ?case\n        by simp\n    next\n      case (Cons_eq x y xs ys)\n      then show ?case\n        by simp\n    qed\n  qed\nqed\n\ninterpretation lex: preordering \\<open>([\\<^bold>\\<le>])\\<close> \\<open>([\\<^bold><])\\<close>\n  by (fact preordering)\n\nend\n\n\nsubsection \\<open>The order case\\<close>\n\nlocale lex_ordering = lex_preordering + ordering\nbegin\n\ninterpretation lex: preordering \\<open>([\\<^bold>\\<le>])\\<close> \\<open>([\\<^bold><])\\<close>\n  by (fact preordering)\n\nlemma less_lex_Cons_iff [simp]:\n  \\<open>x # xs [\\<^bold><] y # ys \\<longleftrightarrow> x \\<^bold>< y \\<or> x = y \\<and> xs [\\<^bold><] ys\\<close>\n  by (auto intro: refl antisym)\n\nlemma less_eq_lex_Cons_iff [simp]:\n  \\<open>x # xs [\\<^bold>\\<le>] y # ys \\<longleftrightarrow> x \\<^bold>< y \\<or> x = y \\<and> xs [\\<^bold>\\<le>] ys\\<close>\n  by (auto intro: refl antisym)\n\nlemma ordering:\n  \\<open>ordering ([\\<^bold>\\<le>]) ([\\<^bold><])\\<close>\nproof\n  fix xs ys\n  show *: \\<open>xs = ys\\<close> if \\<open>xs [\\<^bold>\\<le>] ys\\<close> \\<open>ys [\\<^bold>\\<le>] xs\\<close>\n  using that proof induction\n  case (Nil ys)\n    then show ?case by (cases ys) simp\n  next\n    case (Cons x y xs ys)\n    then show ?case by (auto dest: asym intro: antisym)\n      (simp add: strict_iff_not)\n  next\n    case (Cons_eq x y xs ys)\n    then show ?case by (auto intro: antisym)\n      (simp add: strict_iff_not)\n  qed\n  show \\<open>xs [\\<^bold><] ys \\<longleftrightarrow> xs [\\<^bold>\\<le>] ys \\<and> xs \\<noteq> ys\\<close>\n    by (auto simp add: lex.strict_iff_not dest: *)\nqed\n\ninterpretation lex: ordering \\<open>([\\<^bold>\\<le>])\\<close> \\<open>([\\<^bold><])\\<close>\n  by (fact ordering)\n\nend\n\n\nsubsection \\<open>Canonical instance\\<close>\n\ninstantiation list :: (preorder) preorder\nbegin\n\nglobal_interpretation lex: lex_preordering \\<open>(\\<le>) :: 'a::preorder \\<Rightarrow> 'a \\<Rightarrow> bool\\<close> \\<open>(<) :: 'a \\<Rightarrow> 'a \\<Rightarrow> bool\\<close>\n  defines less_eq_list = lex.lex_less_eq\n    and less_list = lex.lex_less ..\n\ninstance\n  by (rule class.preorder.of_class.intro, rule preordering_preorderI, fact lex.preordering)\n\nend\n\nglobal_interpretation lex: lex_ordering \\<open>(\\<le>) :: 'a::order \\<Rightarrow> 'a \\<Rightarrow> bool\\<close> \\<open>(<) :: 'a \\<Rightarrow> 'a \\<Rightarrow> bool\\<close>\n  rewrites \\<open>lex_preordering.lex_less_eq (\\<le>) (<) = ((\\<le>) :: 'a list \\<Rightarrow> 'a list \\<Rightarrow> bool)\\<close>\n    and \\<open>lex_preordering.lex_less (\\<le>) (<) = ((<) :: 'a list \\<Rightarrow> 'a list \\<Rightarrow> bool)\\<close>\nproof -\n  interpret lex_ordering \\<open>(\\<le>) :: 'a \\<Rightarrow> 'a \\<Rightarrow> bool\\<close> \\<open>(<) :: 'a \\<Rightarrow> 'a \\<Rightarrow> bool\\<close> ..\n  show \\<open>lex_ordering ((\\<le>)  :: 'a \\<Rightarrow> 'a \\<Rightarrow> bool) (<)\\<close>\n    by (fact lex_ordering_axioms)\n  show \\<open>lex_preordering.lex_less_eq (\\<le>) (<) = (\\<le>)\\<close>\n    by (simp add: less_eq_list_def)\n  show \\<open>lex_preordering.lex_less (\\<le>) (<) = (<)\\<close>\n    by (simp add: less_list_def)\nqed\n\ninstance list :: (order) order\n  by (rule class.order.of_class.intro, rule ordering_orderI, fact lex.ordering)\n\nexport_code \\<open>(\\<le>) :: _ list \\<Rightarrow> _ list \\<Rightarrow> bool\\<close> \\<open>(<) :: _ list \\<Rightarrow> _ list \\<Rightarrow> bool\\<close> in Haskell\n\n\nsubsection \\<open>Non-canonical instance\\<close>\n\ncontext comm_monoid_mult\nbegin\n\ndefinition dvd_strict :: \\<open>'a \\<Rightarrow> 'a \\<Rightarrow> bool\\<close>\n  where \\<open>dvd_strict a b \\<longleftrightarrow> a dvd b \\<and> \\<not> b dvd a\\<close>\n\nend\n\nglobal_interpretation dvd: lex_preordering \\<open>(dvd) :: 'a::comm_monoid_mult \\<Rightarrow> 'a \\<Rightarrow> bool\\<close> dvd_strict\n  defines lex_dvd = dvd.lex_less_eq\n    and lex_dvd_strict = dvd.lex_less\n  by unfold_locales (auto simp add: dvd_strict_def)\n\nglobal_interpretation lex_dvd: preordering lex_dvd lex_dvd_strict\n  by (fact dvd.preordering)\n\ndefinition \\<open>example = lex_dvd [(4::int), - 7, 8] [- 8, 13, 5]\\<close>\n\nexport_code example in Haskell\n\nvalue example\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/Lexord.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.833324607730178, "lm_q2_score": 0.8539127585282744, "lm_q1q2_score": 0.7115865145363686}}
{"text": "(*  Title:      HOL/Analysis/Inner_Product.thy\n    Author:     Brian Huffman\n*)\n\nsection \\<open>Inner Product Spaces and Gradient Derivative\\<close>\n\ntheory Inner_Product\nimports Complex_Main\nbegin\n\nsubsection \\<open>Real inner product spaces\\<close>\n\ntext \\<open>\n  Temporarily relax type constraints for \\<^term>\\<open>open\\<close>, \\<^term>\\<open>uniformity\\<close>,\n  \\<^term>\\<open>dist\\<close>, and \\<^term>\\<open>norm\\<close>.\n\\<close>\n\nsetup \\<open>Sign.add_const_constraint\n  (\\<^const_name>\\<open>open\\<close>, SOME \\<^typ>\\<open>'a::open set \\<Rightarrow> bool\\<close>)\\<close>\n\nsetup \\<open>Sign.add_const_constraint\n  (\\<^const_name>\\<open>dist\\<close>, SOME \\<^typ>\\<open>'a::dist \\<Rightarrow> 'a \\<Rightarrow> real\\<close>)\\<close>\n\nsetup \\<open>Sign.add_const_constraint\n  (\\<^const_name>\\<open>uniformity\\<close>, SOME \\<^typ>\\<open>('a::uniformity \\<times> 'a) filter\\<close>)\\<close>\n\nsetup \\<open>Sign.add_const_constraint\n  (\\<^const_name>\\<open>norm\\<close>, SOME \\<^typ>\\<open>'a::norm \\<Rightarrow> real\\<close>)\\<close>\n\nclass real_inner = real_vector + sgn_div_norm + dist_norm + uniformity_dist + open_uniformity +\n  fixes inner :: \"'a \\<Rightarrow> 'a \\<Rightarrow> real\"\n  assumes inner_commute: \"inner x y = inner y x\"\n  and inner_add_left: \"inner (x + y) z = inner x z + inner y z\"\n  and inner_scaleR_left [simp]: \"inner (scaleR r x) y = r * (inner x y)\"\n  and inner_ge_zero [simp]: \"0 \\<le> inner x x\"\n  and inner_eq_zero_iff [simp]: \"inner x x = 0 \\<longleftrightarrow> x = 0\"\n  and norm_eq_sqrt_inner: \"norm x = sqrt (inner x x)\"\nbegin\n\nlemma inner_zero_left [simp]: \"inner 0 x = 0\"\n  using inner_add_left [of 0 0 x] by simp\n\nlemma inner_minus_left [simp]: \"inner (- x) y = - inner x y\"\n  using inner_add_left [of x \"- x\" y] by simp\n\nlemma inner_diff_left: \"inner (x - y) z = inner x z - inner y z\"\n  using inner_add_left [of x \"- y\" z] by simp\n\nlemma inner_sum_left: \"inner (\\<Sum>x\\<in>A. f x) y = (\\<Sum>x\\<in>A. inner (f x) y)\"\n  by (cases \"finite A\", induct set: finite, simp_all add: inner_add_left)\n\nlemma all_zero_iff [simp]: \"(\\<forall>u. inner x u = 0) \\<longleftrightarrow> (x = 0)\"\n  by auto (use inner_eq_zero_iff in blast)\n\ntext \\<open>Transfer distributivity rules to right argument.\\<close>\n\nlemma inner_add_right: \"inner x (y + z) = inner x y + inner x z\"\n  using inner_add_left [of y z x] by (simp only: inner_commute)\n\nlemma inner_scaleR_right [simp]: \"inner x (scaleR r y) = r * (inner x y)\"\n  using inner_scaleR_left [of r y x] by (simp only: inner_commute)\n\nlemma inner_zero_right [simp]: \"inner x 0 = 0\"\n  using inner_zero_left [of x] by (simp only: inner_commute)\n\nlemma inner_minus_right [simp]: \"inner x (- y) = - inner x y\"\n  using inner_minus_left [of y x] by (simp only: inner_commute)\n\nlemma inner_diff_right: \"inner x (y - z) = inner x y - inner x z\"\n  using inner_diff_left [of y z x] by (simp only: inner_commute)\n\nlemma inner_sum_right: \"inner x (\\<Sum>y\\<in>A. f y) = (\\<Sum>y\\<in>A. inner x (f y))\"\n  using inner_sum_left [of f A x] by (simp only: inner_commute)\n\nlemmas inner_add [algebra_simps] = inner_add_left inner_add_right\nlemmas inner_diff [algebra_simps]  = inner_diff_left inner_diff_right\nlemmas inner_scaleR = inner_scaleR_left inner_scaleR_right\n\ntext \\<open>Legacy theorem names\\<close>\nlemmas inner_left_distrib = inner_add_left\nlemmas inner_right_distrib = inner_add_right\nlemmas inner_distrib = inner_left_distrib inner_right_distrib\n\nlemma inner_gt_zero_iff [simp]: \"0 < inner x x \\<longleftrightarrow> x \\<noteq> 0\"\n  by (simp add: order_less_le)\n\nlemma power2_norm_eq_inner: \"(norm x)\\<^sup>2 = inner x x\"\n  by (simp add: norm_eq_sqrt_inner)\n\ntext \\<open>Identities involving real multiplication and division.\\<close>\n\nlemma inner_mult_left: \"inner (of_real m * a) b = m * (inner a b)\"\n  by (metis real_inner_class.inner_scaleR_left scaleR_conv_of_real)\n\nlemma inner_mult_right: \"inner a (of_real m * b) = m * (inner a b)\"\n  by (metis real_inner_class.inner_scaleR_right scaleR_conv_of_real)\n\nlemma inner_mult_left': \"inner (a * of_real m) b = m * (inner a b)\"\n  by (simp add: of_real_def)\n\nlemma inner_mult_right': \"inner a (b * of_real m) = (inner a b) * m\"\n  by (simp add: of_real_def real_inner_class.inner_scaleR_right)\n\n\n\nlemma Cauchy_Schwarz_ineq2:\n  \"\\<bar>inner x y\\<bar> \\<le> norm x * norm y\"\nproof (rule power2_le_imp_le)\n  have \"(inner x y)\\<^sup>2 \\<le> inner x x * inner y y\"\n    using Cauchy_Schwarz_ineq .\n  thus \"\\<bar>inner x y\\<bar>\\<^sup>2 \\<le> (norm x * norm y)\\<^sup>2\"\n    by (simp add: power_mult_distrib power2_norm_eq_inner)\n  show \"0 \\<le> norm x * norm y\"\n    unfolding norm_eq_sqrt_inner\n    by (intro mult_nonneg_nonneg real_sqrt_ge_zero inner_ge_zero)\nqed\n\nlemma norm_cauchy_schwarz: \"inner x y \\<le> norm x * norm y\"\n  using Cauchy_Schwarz_ineq2 [of x y] by auto\n\nsubclass real_normed_vector\nproof\n  fix a :: real and x y :: 'a\n  show \"norm x = 0 \\<longleftrightarrow> x = 0\"\n    unfolding norm_eq_sqrt_inner by simp\n  show \"norm (x + y) \\<le> norm x + norm y\"\n    proof (rule power2_le_imp_le)\n      have \"inner x y \\<le> norm x * norm y\"\n        by (rule norm_cauchy_schwarz)\n      thus \"(norm (x + y))\\<^sup>2 \\<le> (norm x + norm y)\\<^sup>2\"\n        unfolding power2_sum power2_norm_eq_inner\n        by (simp add: inner_add inner_commute)\n      show \"0 \\<le> norm x + norm y\"\n        unfolding norm_eq_sqrt_inner by simp\n    qed\n  have \"sqrt (a\\<^sup>2 * inner x x) = \\<bar>a\\<bar> * sqrt (inner x x)\"\n    by (simp add: real_sqrt_mult)\n  then show \"norm (a *\\<^sub>R x) = \\<bar>a\\<bar> * norm x\"\n    unfolding norm_eq_sqrt_inner\n    by (simp add: power2_eq_square mult.assoc)\nqed\n\nend\n\nlemma square_bound_lemma:\n  fixes x :: real\n  shows \"x < (1 + x) * (1 + x)\"\nproof -\n  have \"(x + 1/2)\\<^sup>2 + 3/4 > 0\"\n    using zero_le_power2[of \"x+1/2\"] by arith\n  then show ?thesis\n    by (simp add: field_simps power2_eq_square)\nqed\n\nlemma square_continuous:\n  fixes e :: real\n  shows \"e > 0 \\<Longrightarrow> \\<exists>d. 0 < d \\<and> (\\<forall>y. \\<bar>y - x\\<bar> < d \\<longrightarrow> \\<bar>y * y - x * x\\<bar> < e)\"\n  using isCont_power[OF continuous_ident, of x, unfolded isCont_def LIM_eq, rule_format, of e 2]\n  by (force simp add: power2_eq_square)\n\nlemma norm_le: \"norm x \\<le> norm y \\<longleftrightarrow> inner x x \\<le> inner y y\"\n  by (simp add: norm_eq_sqrt_inner)\n\nlemma norm_lt: \"norm x < norm y \\<longleftrightarrow> inner x x < inner y y\"\n  by (simp add: norm_eq_sqrt_inner)\n\nlemma norm_eq: \"norm x = norm y \\<longleftrightarrow> inner x x = inner y y\"\n  apply (subst order_eq_iff)\n  apply (auto simp: norm_le)\n  done\n\nlemma norm_eq_1: \"norm x = 1 \\<longleftrightarrow> inner x x = 1\"\n  by (simp add: norm_eq_sqrt_inner)\n\nlemma inner_divide_left:\n  fixes a :: \"'a :: {real_inner,real_div_algebra}\"\n  shows \"inner (a / of_real m) b = (inner a b) / m\"\n  by (metis (no_types) divide_inverse inner_commute inner_scaleR_right mult.left_neutral mult.right_neutral mult_scaleR_right of_real_inverse scaleR_conv_of_real times_divide_eq_left)\n\nlemma inner_divide_right:\n  fixes a :: \"'a :: {real_inner,real_div_algebra}\"\n  shows \"inner a (b / of_real m) = (inner a b) / m\"\n  by (metis inner_commute inner_divide_left)\n\ntext \\<open>\n  Re-enable constraints for \\<^term>\\<open>open\\<close>, \\<^term>\\<open>uniformity\\<close>,\n  \\<^term>\\<open>dist\\<close>, and \\<^term>\\<open>norm\\<close>.\n\\<close>\n\nsetup \\<open>Sign.add_const_constraint\n  (\\<^const_name>\\<open>open\\<close>, SOME \\<^typ>\\<open>'a::topological_space set \\<Rightarrow> bool\\<close>)\\<close>\n\nsetup \\<open>Sign.add_const_constraint\n  (\\<^const_name>\\<open>uniformity\\<close>, SOME \\<^typ>\\<open>('a::uniform_space \\<times> 'a) filter\\<close>)\\<close>\n\nsetup \\<open>Sign.add_const_constraint\n  (\\<^const_name>\\<open>dist\\<close>, SOME \\<^typ>\\<open>'a::metric_space \\<Rightarrow> 'a \\<Rightarrow> real\\<close>)\\<close>\n\nsetup \\<open>Sign.add_const_constraint\n  (\\<^const_name>\\<open>norm\\<close>, SOME \\<^typ>\\<open>'a::real_normed_vector \\<Rightarrow> real\\<close>)\\<close>\n\nlemma bounded_bilinear_inner:\n  \"bounded_bilinear (inner::'a::real_inner \\<Rightarrow> 'a \\<Rightarrow> real)\"\nproof\n  fix x y z :: 'a and r :: real\n  show \"inner (x + y) z = inner x z + inner y z\"\n    by (rule inner_add_left)\n  show \"inner x (y + z) = inner x y + inner x z\"\n    by (rule inner_add_right)\n  show \"inner (scaleR r x) y = scaleR r (inner x y)\"\n    unfolding real_scaleR_def by (rule inner_scaleR_left)\n  show \"inner x (scaleR r y) = scaleR r (inner x y)\"\n    unfolding real_scaleR_def by (rule inner_scaleR_right)\n  show \"\\<exists>K. \\<forall>x y::'a. norm (inner x y) \\<le> norm x * norm y * K\"\n  proof\n    show \"\\<forall>x y::'a. norm (inner x y) \\<le> norm x * norm y * 1\"\n      by (simp add: Cauchy_Schwarz_ineq2)\n  qed\nqed\n\nlemmas tendsto_inner [tendsto_intros] =\n  bounded_bilinear.tendsto [OF bounded_bilinear_inner]\n\nlemmas isCont_inner [simp] =\n  bounded_bilinear.isCont [OF bounded_bilinear_inner]\n\nlemmas has_derivative_inner [derivative_intros] =\n  bounded_bilinear.FDERIV [OF bounded_bilinear_inner]\n\nlemmas bounded_linear_inner_left =\n  bounded_bilinear.bounded_linear_left [OF bounded_bilinear_inner]\n\nlemmas bounded_linear_inner_right =\n  bounded_bilinear.bounded_linear_right [OF bounded_bilinear_inner]\n\nlemmas bounded_linear_inner_left_comp = bounded_linear_inner_left[THEN bounded_linear_compose]\n\nlemmas bounded_linear_inner_right_comp = bounded_linear_inner_right[THEN bounded_linear_compose]\n\nlemmas has_derivative_inner_right [derivative_intros] =\n  bounded_linear.has_derivative [OF bounded_linear_inner_right]\n\nlemmas has_derivative_inner_left [derivative_intros] =\n  bounded_linear.has_derivative [OF bounded_linear_inner_left]\n\nlemma differentiable_inner [simp]:\n  \"f differentiable (at x within s) \\<Longrightarrow> g differentiable at x within s \\<Longrightarrow> (\\<lambda>x. inner (f x) (g x)) differentiable at x within s\"\n  unfolding differentiable_def by (blast intro: has_derivative_inner)\n\n\nsubsection \\<open>Class instances\\<close>\n\ninstantiation real :: real_inner\nbegin\n\ndefinition inner_real_def [simp]: \"inner = (*)\"\n\ninstance\nproof\n  fix x y z r :: real\n  show \"inner x y = inner y x\"\n    unfolding inner_real_def by (rule mult.commute)\n  show \"inner (x + y) z = inner x z + inner y z\"\n    unfolding inner_real_def by (rule distrib_right)\n  show \"inner (scaleR r x) y = r * inner x y\"\n    unfolding inner_real_def real_scaleR_def by (rule mult.assoc)\n  show \"0 \\<le> inner x x\"\n    unfolding inner_real_def by simp\n  show \"inner x x = 0 \\<longleftrightarrow> x = 0\"\n    unfolding inner_real_def by simp\n  show \"norm x = sqrt (inner x x)\"\n    unfolding inner_real_def by simp\nqed\n\nend\n\nlemma\n  shows real_inner_1_left[simp]: \"inner 1 x = x\"\n    and real_inner_1_right[simp]: \"inner x 1 = x\"\n  by simp_all\n\ninstantiation complex :: real_inner\nbegin\n\ndefinition inner_complex_def:\n  \"inner x y = Re x * Re y + Im x * Im y\"\n\ninstance\nproof\n  fix x y z :: complex and r :: real\n  show \"inner x y = inner y x\"\n    unfolding inner_complex_def by (simp add: mult.commute)\n  show \"inner (x + y) z = inner x z + inner y z\"\n    unfolding inner_complex_def by (simp add: distrib_right)\n  show \"inner (scaleR r x) y = r * inner x y\"\n    unfolding inner_complex_def by (simp add: distrib_left)\n  show \"0 \\<le> inner x x\"\n    unfolding inner_complex_def by simp\n  show \"inner x x = 0 \\<longleftrightarrow> x = 0\"\n    unfolding inner_complex_def\n    by (simp add: add_nonneg_eq_0_iff complex_eq_iff)\n  show \"norm x = sqrt (inner x x)\"\n    unfolding inner_complex_def norm_complex_def\n    by (simp add: power2_eq_square)\nqed\n\nend\n\nlemma complex_inner_1 [simp]: \"inner 1 x = Re x\"\n  unfolding inner_complex_def by simp\n\nlemma complex_inner_1_right [simp]: \"inner x 1 = Re x\"\n  unfolding inner_complex_def by simp\n\nlemma complex_inner_i_left [simp]: \"inner \\<i> x = Im x\"\n  unfolding inner_complex_def by simp\n\nlemma complex_inner_i_right [simp]: \"inner x \\<i> = Im x\"\n  unfolding inner_complex_def by simp\n\n\nlemma dot_square_norm: \"inner x x = (norm x)\\<^sup>2\"\n  by (simp only: power2_norm_eq_inner) (* TODO: move? *)\n\nlemma norm_eq_square: \"norm x = a \\<longleftrightarrow> 0 \\<le> a \\<and> inner x x = a\\<^sup>2\"\n  by (auto simp add: norm_eq_sqrt_inner)\n\nlemma norm_le_square: \"norm x \\<le> a \\<longleftrightarrow> 0 \\<le> a \\<and> inner x x \\<le> a\\<^sup>2\"\n  apply (simp add: dot_square_norm abs_le_square_iff[symmetric])\n  using norm_ge_zero[of x]\n  apply arith\n  done\n\nlemma norm_ge_square: \"norm x \\<ge> a \\<longleftrightarrow> a \\<le> 0 \\<or> inner x x \\<ge> a\\<^sup>2\"\n  apply (simp add: dot_square_norm abs_le_square_iff[symmetric])\n  using norm_ge_zero[of x]\n  apply arith\n  done\n\nlemma norm_lt_square: \"norm x < a \\<longleftrightarrow> 0 < a \\<and> inner x x < a\\<^sup>2\"\n  by (metis not_le norm_ge_square)\n\nlemma norm_gt_square: \"norm x > a \\<longleftrightarrow> a < 0 \\<or> inner x x > a\\<^sup>2\"\n  by (metis norm_le_square not_less)\n\ntext\\<open>Dot product in terms of the norm rather than conversely.\\<close>\n\nlemmas inner_simps = inner_add_left inner_add_right inner_diff_right inner_diff_left\n  inner_scaleR_left inner_scaleR_right\n\nlemma dot_norm: \"inner x y = ((norm (x + y))\\<^sup>2 - (norm x)\\<^sup>2 - (norm y)\\<^sup>2) / 2\"\n  by (simp only: power2_norm_eq_inner inner_simps inner_commute) auto\n\nlemma dot_norm_neg: \"inner x y = (((norm x)\\<^sup>2 + (norm y)\\<^sup>2) - (norm (x - y))\\<^sup>2) / 2\"\n  by (simp only: power2_norm_eq_inner inner_simps inner_commute)\n    (auto simp add: algebra_simps)\n\nlemma of_real_inner_1 [simp]: \n  \"inner (of_real x) (1 :: 'a :: {real_inner, real_normed_algebra_1}) = x\"\n  by (simp add: of_real_def dot_square_norm)\n  \nlemma summable_of_real_iff: \n  \"summable (\\<lambda>x. of_real (f x) :: 'a :: {real_normed_algebra_1,real_inner}) \\<longleftrightarrow> summable f\"\nproof\n  assume *: \"summable (\\<lambda>x. of_real (f x) :: 'a)\"\n  interpret bounded_linear \"\\<lambda>x::'a. inner x 1\"\n    by (rule bounded_linear_inner_left)\n  from summable [OF *] show \"summable f\" by simp\nqed (auto intro: summable_of_real)\n\n\nsubsection \\<open>Gradient derivative\\<close>\n\ndefinition\\<^marker>\\<open>tag important\\<close>\n  gderiv ::\n    \"['a::real_inner \\<Rightarrow> real, 'a, 'a] \\<Rightarrow> bool\"\n          (\"(GDERIV (_)/ (_)/ :> (_))\" [1000, 1000, 60] 60)\nwhere\n  \"GDERIV f x :> D \\<longleftrightarrow> FDERIV f x :> (\\<lambda>h. inner h D)\"\n\nlemma gderiv_deriv [simp]: \"GDERIV f x :> D \\<longleftrightarrow> DERIV f x :> D\"\n  by (simp only: gderiv_def has_field_derivative_def inner_real_def mult_commute_abs)\n\nlemma GDERIV_DERIV_compose:\n    \"\\<lbrakk>GDERIV f x :> df; DERIV g (f x) :> dg\\<rbrakk>\n     \\<Longrightarrow> GDERIV (\\<lambda>x. g (f x)) x :> scaleR dg df\"\n  unfolding gderiv_def has_field_derivative_def\n  apply (drule (1) has_derivative_compose)\n  apply (simp add: ac_simps)\n  done\n\nlemma has_derivative_subst: \"\\<lbrakk>FDERIV f x :> df; df = d\\<rbrakk> \\<Longrightarrow> FDERIV f x :> d\"\n  by simp\n\nlemma GDERIV_subst: \"\\<lbrakk>GDERIV f x :> df; df = d\\<rbrakk> \\<Longrightarrow> GDERIV f x :> d\"\n  by simp\n\nlemma GDERIV_const: \"GDERIV (\\<lambda>x. k) x :> 0\"\n  unfolding gderiv_def inner_zero_right by (rule has_derivative_const)\n\nlemma GDERIV_add:\n    \"\\<lbrakk>GDERIV f x :> df; GDERIV g x :> dg\\<rbrakk>\n     \\<Longrightarrow> GDERIV (\\<lambda>x. f x + g x) x :> df + dg\"\n  unfolding gderiv_def inner_add_right by (rule has_derivative_add)\n\nlemma GDERIV_minus:\n    \"GDERIV f x :> df \\<Longrightarrow> GDERIV (\\<lambda>x. - f x) x :> - df\"\n  unfolding gderiv_def inner_minus_right by (rule has_derivative_minus)\n\nlemma GDERIV_diff:\n    \"\\<lbrakk>GDERIV f x :> df; GDERIV g x :> dg\\<rbrakk>\n     \\<Longrightarrow> GDERIV (\\<lambda>x. f x - g x) x :> df - dg\"\n  unfolding gderiv_def inner_diff_right by (rule has_derivative_diff)\n\nlemma GDERIV_scaleR:\n    \"\\<lbrakk>DERIV f x :> df; GDERIV g x :> dg\\<rbrakk>\n     \\<Longrightarrow> GDERIV (\\<lambda>x. scaleR (f x) (g x)) x\n      :> (scaleR (f x) dg + scaleR df (g x))\"\n  unfolding gderiv_def has_field_derivative_def inner_add_right inner_scaleR_right\n  apply (rule has_derivative_subst)\n  apply (erule (1) has_derivative_scaleR)\n  apply (simp add: ac_simps)\n  done\n\nlemma GDERIV_mult:\n    \"\\<lbrakk>GDERIV f x :> df; GDERIV g x :> dg\\<rbrakk>\n     \\<Longrightarrow> GDERIV (\\<lambda>x. f x * g x) x :> scaleR (f x) dg + scaleR (g x) df\"\n  unfolding gderiv_def\n  apply (rule has_derivative_subst)\n  apply (erule (1) has_derivative_mult)\n  apply (simp add: inner_add ac_simps)\n  done\n\nlemma GDERIV_inverse:\n    \"\\<lbrakk>GDERIV f x :> df; f x \\<noteq> 0\\<rbrakk>\n     \\<Longrightarrow> GDERIV (\\<lambda>x. inverse (f x)) x :> - (inverse (f x))\\<^sup>2 *\\<^sub>R df\"\n  by (metis DERIV_inverse GDERIV_DERIV_compose numerals(2))\n  \nlemma GDERIV_norm:\n  assumes \"x \\<noteq> 0\" shows \"GDERIV (\\<lambda>x. norm x) x :> sgn x\"\n    unfolding gderiv_def norm_eq_sqrt_inner\n    by (rule derivative_eq_intros | force simp add: inner_commute sgn_div_norm norm_eq_sqrt_inner assms)+\n\nlemmas has_derivative_norm = GDERIV_norm [unfolded gderiv_def]\n\nbundle inner_syntax begin\nnotation inner (infix \"\\<bullet>\" 70)\nend\n\nbundle no_inner_syntax begin\nno_notation inner (infix \"\\<bullet>\" 70)\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/Analysis/Inner_Product.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8539127603871312, "lm_q2_score": 0.8333245953120233, "lm_q1q2_score": 0.7115865054813788}}
{"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>\\<open>\"KaldewaijS-IPL91\"\\<close>.\\<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>\\<open>\"KaldewaijS-IPL91\"\\<close>: 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>\\<open>\"KaldewaijS-IPL91\"\\<close>: 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": "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/Amortized_Complexity/Skew_Heap_Analysis.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9184802417938535, "lm_q2_score": 0.7745833893685269, "lm_q1q2_score": 0.7114395387567071}}
{"text": "theory Ex007 \nimports Main\nbegin \n\n(*Peirce's Law*)\n\n\nlemma \"(( A \\<longrightarrow> B) \\<longrightarrow> A) \\<longrightarrow> A\" \nproof - \n{\n  assume \"(A \\<longrightarrow> B) \\<longrightarrow> A\"\n  {\n    assume a:\"\\<not>A\"\n    {\n      assume A\n      with a have B by contradiction\n    }\n    hence \"A \\<longrightarrow> B\" by (rule impI)\n    with \\<open>(A \\<longrightarrow> B) \\<longrightarrow> A\\<close> have A by (rule impE)\n    with \\<open>\\<not>A\\<close> have False by contradiction\n  }\n  hence \"\\<not>\\<not>A\" by (rule notI)\n  hence A by (rule notnotD)\n}\nthus ?thesis by (rule impI)\nqed\n\n\n(*slightly prettified*)\n\n\nlemma \"(( A \\<longrightarrow> B) \\<longrightarrow> A) \\<longrightarrow> A\" \nproof - \n{\n  assume \"(A \\<longrightarrow> B) \\<longrightarrow> A\"\n  {\n    assume a:\"\\<not>A\"\n    {\n      assume A\n      with a have B ..\n    }\n    hence \"A \\<longrightarrow> B\" ..\n    with \\<open>(A \\<longrightarrow> B) \\<longrightarrow> A\\<close> have A ..\n    with \\<open>\\<not>A\\<close> have False ..\n  }\n  hence \"\\<not>\\<not>A\" ..\n  hence A by (rule notnotD)\n}\nthus ?thesis ..\nqed\n\nlemma \"((A \\<longrightarrow> B) \\<longrightarrow> A) \\<longrightarrow> A\"\nproof -\n  {\n    assume a:\"((A \\<longrightarrow> B) \\<longrightarrow> A)\"\n    {\n      assume b:\"\\<not>A\"\n      {\n        assume c:A\n        {\n          assume \"\\<not>B\"\n          from b and c have False by contradiction\n        }\n        hence \"\\<not>\\<not>B\" by (rule notI)\n        hence B by (rule notnotD)\n      }\n      hence \"A \\<longrightarrow> B\" by (rule impI)\n      with a have A by (rule mp)\n      with b have False by contradiction\n    }\n    hence \"\\<not>\\<not>A\" by (rule notI)\n    hence A by (rule notnotD)\n  }\n  thus \"((A \\<longrightarrow> B) \\<longrightarrow> A) \\<longrightarrow> A\" by (rule impI)\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/Ex007.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802350995702, "lm_q2_score": 0.7745833841649232, "lm_q1q2_score": 0.7114395287920194}}
{"text": "(*  Title:      HOL/Analysis/Euclidean_Space.thy\n    Author:     Johannes H\u00f6lzl, TU M\u00fcnchen\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\n  Inner_Product\n  Product_Vector\nbegin\n\n\nsubsection\\<^marker>\\<open>tag unimportant\\<close> \\<open>Interlude: Some properties of real sets\\<close>\n\nlemma seq_mono_lemma:\n  assumes \"\\<forall>(n::nat) \\<ge> m. (d n :: real) < e n\"\n    and \"\\<forall>n \\<ge> m. e n \\<le> e m\"\n  shows \"\\<forall>n \\<ge> m. d n < e m\"\n  using assms by force\n\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>\\<open>card\\<close>,\n    fn ctxt => fn _ => fn [Const (\\<^const_syntax>\\<open>Basis\\<close>, Type (\\<^type_name>\\<open>set\\<close>, [T]))] =>\n      Syntax.const \\<^syntax_const>\\<open>_type_dimension\\<close> $ 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 inner_sum_Basis[simp]: \"i \\<in> Basis \\<Longrightarrow> inner (\\<Sum>Basis) i = 1\"\n  by (simp add: inner_sum_left sum.If_cases inner_Basis)\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 norm_some_Basis [simp]: \"norm (SOME i. i \\<in> Basis) = 1\"\n  by (simp add: SOME_Basis)\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) euclidean_inner: \"inner x y = (\\<Sum>b\\<in>Basis. (inner x b) * (inner y b))\"\n  by (subst (1 2) euclidean_representation [symmetric])\n    (simp add: inner_sum_right inner_Basis ac_simps)\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\nlemma sum_if_inner [simp]:\n  assumes \"i \\<in> Basis\" \"j \\<in> Basis\"\n    shows \"inner (\\<Sum>k\\<in>Basis. if k = i then f i *\\<^sub>R i else g k *\\<^sub>R k) j = (if j=i then f j else g j)\"\nproof (cases \"i=j\")\n  case True\n  with assms show ?thesis\n    by (auto simp: inner_sum_left if_distrib [of \"\\<lambda>x. inner x j\"] inner_Basis cong: if_cong)\nnext\n  case False\n  have \"(\\<Sum>k\\<in>Basis. inner (if k = i then f i *\\<^sub>R i else g k *\\<^sub>R k) j) =\n        (\\<Sum>k\\<in>Basis. if k = j then g k else 0)\"\n    apply (rule sum.cong)\n    using False assms by (auto simp: inner_Basis)\n  also have \"... = g j\"\n    using assms by auto\n  finally show ?thesis\n    using False by (auto simp: inner_sum_left)\nqed\n\nlemma norm_le_componentwise:\n   \"(\\<And>b. b \\<in> Basis \\<Longrightarrow> abs(inner x b) \\<le> abs(inner y b)) \\<Longrightarrow> norm x \\<le> norm y\"\n  by (auto simp: norm_le euclidean_inner [of x x] euclidean_inner [of y y] abs_le_square_iff power2_eq_square intro!: sum_mono)\n\nlemma Basis_le_norm: \"b \\<in> Basis \\<Longrightarrow> \\<bar>inner x b\\<bar> \\<le> norm x\"\n  by (rule order_trans [OF Cauchy_Schwarz_ineq2]) simp\n\nlemma norm_bound_Basis_le: \"b \\<in> Basis \\<Longrightarrow> norm x \\<le> e \\<Longrightarrow> \\<bar>inner x b\\<bar> \\<le> e\"\n  by (metis Basis_le_norm order_trans)\n\nlemma norm_bound_Basis_lt: \"b \\<in> Basis \\<Longrightarrow> norm x < e \\<Longrightarrow> \\<bar>inner x b\\<bar> < e\"\n  by (metis Basis_le_norm le_less_trans)\n\nlemma norm_le_l1: \"norm x \\<le> (\\<Sum>b\\<in>Basis. \\<bar>inner x b\\<bar>)\"\n  apply (subst euclidean_representation[of x, symmetric])\n  apply (rule order_trans[OF norm_sum])\n  apply (auto intro!: sum_mono)\n  done\n\nlemma sum_norm_allsubsets_bound:\n  fixes f :: \"'a \\<Rightarrow> 'n::euclidean_space\"\n  assumes fP: \"finite P\"\n    and fPs: \"\\<And>Q. Q \\<subseteq> P \\<Longrightarrow> norm (sum f Q) \\<le> e\"\n  shows \"(\\<Sum>x\\<in>P. norm (f x)) \\<le> 2 * real DIM('n) * e\"\nproof -\n  have \"(\\<Sum>x\\<in>P. norm (f x)) \\<le> (\\<Sum>x\\<in>P. \\<Sum>b\\<in>Basis. \\<bar>inner (f x) b\\<bar>)\"\n    by (rule sum_mono) (rule norm_le_l1)\n  also have \"(\\<Sum>x\\<in>P. \\<Sum>b\\<in>Basis. \\<bar>inner (f x) b\\<bar>) = (\\<Sum>b\\<in>Basis. \\<Sum>x\\<in>P. \\<bar>inner (f x) b\\<bar>)\"\n    by (rule sum.swap)\n  also have \"\\<dots> \\<le> of_nat (card (Basis :: 'n set)) * (2 * e)\"\n  proof (rule sum_bounded_above)\n    fix i :: 'n\n    assume i: \"i \\<in> Basis\"\n    have \"norm (\\<Sum>x\\<in>P. \\<bar>inner (f x) i\\<bar>) \\<le>\n      norm (inner (\\<Sum>x\\<in>P \\<inter> - {x. inner (f x) i < 0}. f x) i) + norm (inner (\\<Sum>x\\<in>P \\<inter> {x. inner (f x) i < 0}. f x) i)\"\n      by (simp add: abs_real_def sum.If_cases[OF fP] sum_negf norm_triangle_ineq4 inner_sum_left\n        del: real_norm_def)\n    also have \"\\<dots> \\<le> e + e\"\n      unfolding real_norm_def\n      by (intro add_mono norm_bound_Basis_le i fPs) auto\n    finally show \"(\\<Sum>x\\<in>P. \\<bar>inner (f x) i\\<bar>) \\<le> 2*e\" by simp\n  qed\n  also have \"\\<dots> = 2 * real DIM('n) * e\" by simp\n  finally show ?thesis .\nqed\n\n\nsubsection\\<^marker>\\<open>tag unimportant\\<close> \\<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\\<^marker>\\<open>tag unimportant\\<close> \\<open>Type \\<^typ>\\<open>real\\<close>\\<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\\<^marker>\\<open>tag unimportant\\<close> \\<open>Type \\<^typ>\\<open>complex\\<close>\\<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\nlemma complex_Basis_1 [iff]: \"(1::complex) \\<in> Basis\"\n  by (simp add: Basis_complex_def)\n\nlemma complex_Basis_i [iff]: \"\\<i> \\<in> Basis\"\n  by (simp add: Basis_complex_def)\n\nsubsubsection\\<^marker>\\<open>tag unimportant\\<close> \\<open>Type \\<^typ>\\<open>'a \\<times> 'b\\<close>\\<close>\n\ninstantiation prod :: (real_inner, real_inner) real_inner\nbegin\n\ndefinition inner_prod_def:\n  \"inner x y = inner (fst x) (fst y) + inner (snd x) (snd y)\"\n\nlemma inner_Pair [simp]: \"inner (a, b) (c, d) = inner a c + inner b d\"\n  unfolding inner_prod_def by simp\n\ninstance\nproof\n  fix r :: real\n  fix x y z :: \"'a::real_inner \\<times> 'b::real_inner\"\n  show \"inner x y = inner y x\"\n    unfolding inner_prod_def\n    by (simp add: inner_commute)\n  show \"inner (x + y) z = inner x z + inner y z\"\n    unfolding inner_prod_def\n    by (simp add: inner_add_left)\n  show \"inner (scaleR r x) y = r * inner x y\"\n    unfolding inner_prod_def\n    by (simp add: distrib_left)\n  show \"0 \\<le> inner x x\"\n    unfolding inner_prod_def\n    by (intro add_nonneg_nonneg inner_ge_zero)\n  show \"inner x x = 0 \\<longleftrightarrow> x = 0\"\n    unfolding inner_prod_def prod_eq_iff\n    by (simp add: add_nonneg_eq_0_iff)\n  show \"norm x = sqrt (inner x x)\"\n    unfolding norm_prod_def inner_prod_def\n    by (simp add: power2_norm_eq_inner)\nqed\n\nend\n\nlemma inner_Pair_0: \"inner x (0, b) = inner (snd x) b\" \"inner x (a, 0) = inner (fst x) a\"\n    by (cases x, simp)+\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=\"(+)\"] inj_onI)\n\nend\n\n\nsubsection \\<open>Locale instances\\<close>\n\nlemma finite_dimensional_vector_space_euclidean:\n  \"finite_dimensional_vector_space (*\\<^sub>R) Basis\"\nproof unfold_locales\n  show \"finite (Basis::'a set)\" by (metis finite_Basis)\n  show \"real_vector.independent (Basis::'a set)\"\n    unfolding dependent_def dependent_raw_def[symmetric]\n    apply (subst span_finite)\n    apply simp\n    apply clarify\n    apply (drule_tac f=\"inner a\" in arg_cong)\n    apply (simp add: inner_Basis inner_sum_right eq_commute)\n    done\n  show \"module.span (*\\<^sub>R) Basis = UNIV\"\n    unfolding span_finite [OF finite_Basis] span_raw_def[symmetric]\n    by (auto intro!: euclidean_representation[symmetric])\nqed\n\ninterpretation eucl?: finite_dimensional_vector_space \"scaleR :: real => 'a => 'a::euclidean_space\" \"Basis\"\n  rewrites \"module.dependent (*\\<^sub>R) = dependent\"\n    and \"module.representation (*\\<^sub>R) = representation\"\n    and \"module.subspace (*\\<^sub>R) = subspace\"\n    and \"module.span (*\\<^sub>R) = span\"\n    and \"vector_space.extend_basis (*\\<^sub>R) = extend_basis\"\n    and \"vector_space.dim (*\\<^sub>R) = dim\"\n    and \"Vector_Spaces.linear (*\\<^sub>R) (*\\<^sub>R) = linear\"\n    and \"Vector_Spaces.linear (*) (*\\<^sub>R) = linear\"\n    and \"finite_dimensional_vector_space.dimension Basis = DIM('a)\"\n    and \"dimension = DIM('a)\"\n  by (auto simp add: dependent_raw_def representation_raw_def\n      subspace_raw_def span_raw_def extend_basis_raw_def dim_raw_def linear_def\n      real_scaleR_def[abs_def]\n      finite_dimensional_vector_space.dimension_def\n      intro!: finite_dimensional_vector_space.dimension_def\n      finite_dimensional_vector_space_euclidean)\n\ninterpretation eucl?: finite_dimensional_vector_space_pair_1\n  \"scaleR::real\\<Rightarrow>'a::euclidean_space\\<Rightarrow>'a\" Basis\n  \"scaleR::real\\<Rightarrow>'b::real_vector \\<Rightarrow> 'b\"\n  by unfold_locales\n\ninterpretation eucl?: finite_dimensional_vector_space_prod scaleR scaleR Basis Basis\n  rewrites \"Basis_pair = Basis\"\n    and \"module_prod.scale (*\\<^sub>R) (*\\<^sub>R) = (scaleR::_\\<Rightarrow>_\\<Rightarrow>('a \\<times> 'b))\"\nproof -\n  show \"finite_dimensional_vector_space_prod (*\\<^sub>R) (*\\<^sub>R) Basis Basis\"\n    by unfold_locales\n  interpret finite_dimensional_vector_space_prod \"(*\\<^sub>R)\" \"(*\\<^sub>R)\" \"Basis::'a set\" \"Basis::'b set\"\n    by fact\n  show \"Basis_pair = Basis\"\n    unfolding Basis_pair_def Basis_prod_def by auto\n  show \"module_prod.scale (*\\<^sub>R) (*\\<^sub>R) = scaleR\"\n    by (fact module_prod_scale_eq_scaleR)\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/Analysis/Euclidean_Space.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8221891479496521, "lm_q2_score": 0.8652240895276223, "lm_q1q2_score": 0.7113778569542293}}
{"text": "(*  Title:      HOL/Nonstandard_Analysis/HLim.thy\n    Author:     Jacques D. Fleuriot, University of Cambridge\n    Author:     Lawrence C Paulson\n*)\n\nsection \\<open>Limits and Continuity (Nonstandard)\\<close>\n\ntheory HLim\n  imports Star\n  abbrevs \"--->\" = \"\\<midarrow>\u0007\\<rightarrow>\\<^sub>N\\<^sub>S\"\nbegin\n\ntext \\<open>Nonstandard Definitions.\\<close>\n\ndefinition NSLIM :: \"('a::real_normed_vector \\<Rightarrow> 'b::real_normed_vector) \\<Rightarrow> 'a \\<Rightarrow> 'b \\<Rightarrow> bool\"\n    (\"((_)/ \\<midarrow>(_)/\\<rightarrow>\\<^sub>N\\<^sub>S (_))\" [60, 0, 60] 60)\n  where \"f \\<midarrow>a\\<rightarrow>\\<^sub>N\\<^sub>S L \\<longleftrightarrow> (\\<forall>x. x \\<noteq> star_of a \\<and> x \\<approx> star_of a \\<longrightarrow> ( *f* f) x \\<approx> star_of L)\"\n\ndefinition isNSCont :: \"('a::real_normed_vector \\<Rightarrow> 'b::real_normed_vector) \\<Rightarrow> 'a \\<Rightarrow> bool\"\n  where  \\<comment> \\<open>NS definition dispenses with limit notions\\<close>\n    \"isNSCont f a \\<longleftrightarrow> (\\<forall>y. y \\<approx> star_of a \\<longrightarrow> ( *f* f) y \\<approx> star_of (f a))\"\n\ndefinition isNSUCont :: \"('a::real_normed_vector \\<Rightarrow> 'b::real_normed_vector) \\<Rightarrow> bool\"\n  where \"isNSUCont f \\<longleftrightarrow> (\\<forall>x y. x \\<approx> y \\<longrightarrow> ( *f* f) x \\<approx> ( *f* f) y)\"\n\n\nsubsection \\<open>Limits of Functions\\<close>\n\nlemma NSLIM_I: \"(\\<And>x. x \\<noteq> star_of a \\<Longrightarrow> x \\<approx> star_of a \\<Longrightarrow> starfun f x \\<approx> star_of L) \\<Longrightarrow> f \\<midarrow>a\\<rightarrow>\\<^sub>N\\<^sub>S L\"\n  by (simp add: NSLIM_def)\n\nlemma NSLIM_D: \"f \\<midarrow>a\\<rightarrow>\\<^sub>N\\<^sub>S L \\<Longrightarrow> x \\<noteq> star_of a \\<Longrightarrow> x \\<approx> star_of a \\<Longrightarrow> starfun f x \\<approx> star_of L\"\n  by (simp add: NSLIM_def)\n\ntext \\<open>Proving properties of limits using nonstandard definition.\n  The properties hold for standard limits as well!\\<close>\n\nlemma NSLIM_mult: \"f \\<midarrow>x\\<rightarrow>\\<^sub>N\\<^sub>S l \\<Longrightarrow> g \\<midarrow>x\\<rightarrow>\\<^sub>N\\<^sub>S m \\<Longrightarrow> (\\<lambda>x. f x * g x) \\<midarrow>x\\<rightarrow>\\<^sub>N\\<^sub>S (l * m)\"\n  for l m :: \"'a::real_normed_algebra\"\n  by (auto simp add: NSLIM_def intro!: approx_mult_HFinite)\n\nlemma starfun_scaleR [simp]: \"starfun (\\<lambda>x. f x *\\<^sub>R g x) = (\\<lambda>x. scaleHR (starfun f x) (starfun g x))\"\n  by transfer (rule refl)\n\nlemma NSLIM_scaleR: \"f \\<midarrow>x\\<rightarrow>\\<^sub>N\\<^sub>S l \\<Longrightarrow> g \\<midarrow>x\\<rightarrow>\\<^sub>N\\<^sub>S m \\<Longrightarrow> (\\<lambda>x. f x *\\<^sub>R g x) \\<midarrow>x\\<rightarrow>\\<^sub>N\\<^sub>S (l *\\<^sub>R m)\"\n  by (auto simp add: NSLIM_def intro!: approx_scaleR_HFinite)\n\nlemma NSLIM_add: \"f \\<midarrow>x\\<rightarrow>\\<^sub>N\\<^sub>S l \\<Longrightarrow> g \\<midarrow>x\\<rightarrow>\\<^sub>N\\<^sub>S m \\<Longrightarrow> (\\<lambda>x. f x + g x) \\<midarrow>x\\<rightarrow>\\<^sub>N\\<^sub>S (l + m)\"\n  by (auto simp add: NSLIM_def intro!: approx_add)\n\nlemma NSLIM_const [simp]: \"(\\<lambda>x. k) \\<midarrow>x\\<rightarrow>\\<^sub>N\\<^sub>S k\"\n  by (simp add: NSLIM_def)\n\nlemma NSLIM_minus: \"f \\<midarrow>a\\<rightarrow>\\<^sub>N\\<^sub>S L \\<Longrightarrow> (\\<lambda>x. - f x) \\<midarrow>a\\<rightarrow>\\<^sub>N\\<^sub>S -L\"\n  by (simp add: NSLIM_def)\n\nlemma NSLIM_diff: \"f \\<midarrow>x\\<rightarrow>\\<^sub>N\\<^sub>S l \\<Longrightarrow> g \\<midarrow>x\\<rightarrow>\\<^sub>N\\<^sub>S m \\<Longrightarrow> (\\<lambda>x. f x - g x) \\<midarrow>x\\<rightarrow>\\<^sub>N\\<^sub>S (l - m)\"\n  by (simp only: NSLIM_add NSLIM_minus diff_conv_add_uminus)\n\nlemma NSLIM_add_minus: \"f \\<midarrow>x\\<rightarrow>\\<^sub>N\\<^sub>S l \\<Longrightarrow> g \\<midarrow>x\\<rightarrow>\\<^sub>N\\<^sub>S m \\<Longrightarrow> (\\<lambda>x. f x + - g x) \\<midarrow>x\\<rightarrow>\\<^sub>N\\<^sub>S (l + -m)\"\n  by (simp only: NSLIM_add NSLIM_minus)\n\nlemma NSLIM_inverse: \"f \\<midarrow>a\\<rightarrow>\\<^sub>N\\<^sub>S L \\<Longrightarrow> L \\<noteq> 0 \\<Longrightarrow> (\\<lambda>x. inverse (f x)) \\<midarrow>a\\<rightarrow>\\<^sub>N\\<^sub>S (inverse L)\"\n  for L :: \"'a::real_normed_div_algebra\"\n  unfolding NSLIM_def by (metis (no_types) star_of_approx_inverse star_of_simps(6) starfun_inverse)\n\nlemma NSLIM_zero:\n  assumes f: \"f \\<midarrow>a\\<rightarrow>\\<^sub>N\\<^sub>S l\"\n  shows \"(\\<lambda>x. f(x) - l) \\<midarrow>a\\<rightarrow>\\<^sub>N\\<^sub>S 0\"\nproof -\n  have \"(\\<lambda>x. f x - l) \\<midarrow>a\\<rightarrow>\\<^sub>N\\<^sub>S l - l\"\n    by (rule NSLIM_diff [OF f NSLIM_const])\n  then show ?thesis by simp\nqed\n\nlemma NSLIM_zero_cancel: \n  assumes \"(\\<lambda>x. f x - l) \\<midarrow>x\\<rightarrow>\\<^sub>N\\<^sub>S 0\"\n  shows \"f \\<midarrow>x\\<rightarrow>\\<^sub>N\\<^sub>S l\"\nproof -\n  have \"(\\<lambda>x. f x - l + l) \\<midarrow>x\\<rightarrow>\\<^sub>N\\<^sub>S 0 + l\"\n    by (fast intro: assms NSLIM_const NSLIM_add)\n  then show ?thesis\n    by simp\nqed\n\nlemma NSLIM_const_eq:\n  fixes a :: \"'a::real_normed_algebra_1\"\n  assumes \"(\\<lambda>x. k) \\<midarrow>a\\<rightarrow>\\<^sub>N\\<^sub>S l\"\n  shows \"k = l\"\nproof -\n  have \"\\<not> (\\<lambda>x. k) \\<midarrow>a\\<rightarrow>\\<^sub>N\\<^sub>S l\" if \"k \\<noteq> l\"\n  proof -\n    have \"star_of a + of_hypreal \\<epsilon> \\<approx> star_of a\"\n      by (simp add: approx_def)\n    then show ?thesis\n      using epsilon_not_zero that by (force simp add: NSLIM_def)\n  qed\n  with assms show ?thesis by metis\nqed\n\nlemma NSLIM_unique: \"f \\<midarrow>a\\<rightarrow>\\<^sub>N\\<^sub>S l \\<Longrightarrow> f \\<midarrow>a\\<rightarrow>\\<^sub>N\\<^sub>S M \\<Longrightarrow> l = M\"\n  for a :: \"'a::real_normed_algebra_1\"\n  by (drule (1) NSLIM_diff) (auto dest!: NSLIM_const_eq)\n\nlemma NSLIM_mult_zero: \"f \\<midarrow>x\\<rightarrow>\\<^sub>N\\<^sub>S 0 \\<Longrightarrow> g \\<midarrow>x\\<rightarrow>\\<^sub>N\\<^sub>S 0 \\<Longrightarrow> (\\<lambda>x. f x * g x) \\<midarrow>x\\<rightarrow>\\<^sub>N\\<^sub>S 0\"\n  for f g :: \"'a::real_normed_vector \\<Rightarrow> 'b::real_normed_algebra\"\n  by (drule NSLIM_mult) auto\n\nlemma NSLIM_self: \"(\\<lambda>x. x) \\<midarrow>a\\<rightarrow>\\<^sub>N\\<^sub>S a\"\n  by (simp add: NSLIM_def)\n\n\nsubsubsection \\<open>Equivalence of \\<^term>\\<open>filterlim\\<close> and \\<^term>\\<open>NSLIM\\<close>\\<close>\n\nlemma LIM_NSLIM:\n  assumes f: \"f \\<midarrow>a\\<rightarrow> L\"\n  shows \"f \\<midarrow>a\\<rightarrow>\\<^sub>N\\<^sub>S L\"\nproof (rule NSLIM_I)\n  fix x\n  assume neq: \"x \\<noteq> star_of a\"\n  assume approx: \"x \\<approx> star_of a\"\n  have \"starfun f x - star_of L \\<in> Infinitesimal\"\n  proof (rule InfinitesimalI2)\n    fix r :: real\n    assume r: \"0 < r\"\n    from LIM_D [OF f r] obtain s\n      where s: \"0 < s\" and less_r: \"\\<And>x. x \\<noteq> a \\<Longrightarrow> norm (x - a) < s \\<Longrightarrow> norm (f x - L) < r\"\n      by fast\n    from less_r have less_r':\n      \"\\<And>x. x \\<noteq> star_of a \\<Longrightarrow> hnorm (x - star_of a) < star_of s \\<Longrightarrow>\n        hnorm (starfun f x - star_of L) < star_of r\"\n      by transfer\n    from approx have \"x - star_of a \\<in> Infinitesimal\"\n      by (simp only: approx_def)\n    then have \"hnorm (x - star_of a) < star_of s\"\n      using s by (rule InfinitesimalD2)\n    with neq show \"hnorm (starfun f x - star_of L) < star_of r\"\n      by (rule less_r')\n  qed\n  then show \"starfun f x \\<approx> star_of L\"\n    by (unfold approx_def)\nqed\n\nlemma NSLIM_LIM:\n  assumes f: \"f \\<midarrow>a\\<rightarrow>\\<^sub>N\\<^sub>S L\"\n  shows \"f \\<midarrow>a\\<rightarrow> L\"\nproof (rule LIM_I)\n  fix r :: real\n  assume r: \"0 < r\"\n  have \"\\<exists>s>0. \\<forall>x. x \\<noteq> star_of a \\<and> hnorm (x - star_of a) < s \\<longrightarrow>\n    hnorm (starfun f x - star_of L) < star_of r\"\n  proof (rule exI, safe)\n    show \"0 < \\<epsilon>\"\n      by (rule epsilon_gt_zero)\n  next\n    fix x\n    assume neq: \"x \\<noteq> star_of a\"\n    assume \"hnorm (x - star_of a) < \\<epsilon>\"\n    with Infinitesimal_epsilon have \"x - star_of a \\<in> Infinitesimal\"\n      by (rule hnorm_less_Infinitesimal)\n    then have \"x \\<approx> star_of a\"\n      by (unfold approx_def)\n    with f neq have \"starfun f x \\<approx> star_of L\"\n      by (rule NSLIM_D)\n    then have \"starfun f x - star_of L \\<in> Infinitesimal\"\n      by (unfold approx_def)\n    then show \"hnorm (starfun f x - star_of L) < star_of r\"\n      using r by (rule InfinitesimalD2)\n  qed\n  then show \"\\<exists>s>0. \\<forall>x. x \\<noteq> a \\<and> norm (x - a) < s \\<longrightarrow> norm (f x - L) < r\"\n    by transfer\nqed\n\ntheorem LIM_NSLIM_iff: \"f \\<midarrow>x\\<rightarrow> L \\<longleftrightarrow> f \\<midarrow>x\\<rightarrow>\\<^sub>N\\<^sub>S L\"\n  by (blast intro: LIM_NSLIM NSLIM_LIM)\n\n\nsubsection \\<open>Continuity\\<close>\n\nlemma isNSContD: \"isNSCont f a \\<Longrightarrow> y \\<approx> star_of a \\<Longrightarrow> ( *f* f) y \\<approx> star_of (f a)\"\n  by (simp add: isNSCont_def)\n\nlemma isNSCont_NSLIM: \"isNSCont f a \\<Longrightarrow> f \\<midarrow>a\\<rightarrow>\\<^sub>N\\<^sub>S (f a)\"\n  by (simp add: isNSCont_def NSLIM_def)\n\nlemma NSLIM_isNSCont: \"f \\<midarrow>a\\<rightarrow>\\<^sub>N\\<^sub>S (f a) \\<Longrightarrow> isNSCont f a\"\n  by (force simp add: isNSCont_def NSLIM_def)\n\ntext \\<open>NS continuity can be defined using NS Limit in\n  similar fashion to standard definition of continuity.\\<close>\nlemma isNSCont_NSLIM_iff: \"isNSCont f a \\<longleftrightarrow> f \\<midarrow>a\\<rightarrow>\\<^sub>N\\<^sub>S (f a)\"\n  by (blast intro: isNSCont_NSLIM NSLIM_isNSCont)\n\ntext \\<open>Hence, NS continuity can be given in terms of standard limit.\\<close>\nlemma isNSCont_LIM_iff: \"(isNSCont f a) = (f \\<midarrow>a\\<rightarrow> (f a))\"\n  by (simp add: LIM_NSLIM_iff isNSCont_NSLIM_iff)\n\ntext \\<open>Moreover, it's trivial now that NS continuity\n  is equivalent to standard continuity.\\<close>\nlemma isNSCont_isCont_iff: \"isNSCont f a \\<longleftrightarrow> isCont f a\"\n  by (simp add: isCont_def) (rule isNSCont_LIM_iff)\n\ntext \\<open>Standard continuity \\<open>\\<Longrightarrow>\\<close> NS continuity.\\<close>\nlemma isCont_isNSCont: \"isCont f a \\<Longrightarrow> isNSCont f a\"\n  by (erule isNSCont_isCont_iff [THEN iffD2])\n\ntext \\<open>NS continuity \\<open>\\<Longrightarrow>\\<close> Standard continuity.\\<close>\nlemma isNSCont_isCont: \"isNSCont f a \\<Longrightarrow> isCont f a\"\n  by (erule isNSCont_isCont_iff [THEN iffD1])\n\n\ntext \\<open>Alternative definition of continuity.\\<close>\n\ntext \\<open>Prove equivalence between NS limits --\n  seems easier than using standard definition.\\<close>\nlemma NSLIM_at0_iff: \"f \\<midarrow>a\\<rightarrow>\\<^sub>N\\<^sub>S L \\<longleftrightarrow> (\\<lambda>h. f (a + h)) \\<midarrow>0\\<rightarrow>\\<^sub>N\\<^sub>S L\"\nproof\n  assume \"f \\<midarrow>a\\<rightarrow>\\<^sub>N\\<^sub>S L\"\n  then show \"(\\<lambda>h. f (a + h)) \\<midarrow>0\\<rightarrow>\\<^sub>N\\<^sub>S L\"\n    by (simp add: NSLIM_def) (metis (no_types) add_cancel_left_right approx_add_left_iff starfun_lambda_cancel)\nnext\n  assume *: \"(\\<lambda>h. f (a + h)) \\<midarrow>0\\<rightarrow>\\<^sub>N\\<^sub>S L\"\n  show \"f \\<midarrow>a\\<rightarrow>\\<^sub>N\\<^sub>S L\"\n  proof (clarsimp simp: NSLIM_def)\n    fix x\n    assume \"x \\<noteq> star_of a\" \"x \\<approx> star_of a\"\n    then have \"(*f* (\\<lambda>h. f (a + h))) (- star_of a + x) \\<approx> star_of L\"\n      by (metis (no_types, lifting) \"*\" NSLIM_D add.right_neutral add_minus_cancel approx_minus_iff2 star_zero_def)\n    then show \"(*f* f) x \\<approx> star_of L\"\n      by (simp add: starfun_lambda_cancel)\n  qed\nqed\n\nlemma isNSCont_minus: \"isNSCont f a \\<Longrightarrow> isNSCont (\\<lambda>x. - f x) a\"\n  by (simp add: isNSCont_def)\n\nlemma isNSCont_inverse: \"isNSCont f x \\<Longrightarrow> f x \\<noteq> 0 \\<Longrightarrow> isNSCont (\\<lambda>x. inverse (f x)) x\"\n  for f :: \"'a::real_normed_vector \\<Rightarrow> 'b::real_normed_div_algebra\"\n  using NSLIM_inverse NSLIM_isNSCont isNSCont_NSLIM by blast\n\nlemma isNSCont_const [simp]: \"isNSCont (\\<lambda>x. k) a\"\n  by (simp add: isNSCont_def)\n\nlemma isNSCont_abs [simp]: \"isNSCont abs a\"\n  for a :: real\n  by (auto simp: isNSCont_def intro: approx_hrabs simp: starfun_rabs_hrabs)\n\n\nsubsection \\<open>Uniform Continuity\\<close>\n\nlemma isNSUContD: \"isNSUCont f \\<Longrightarrow> x \\<approx> y \\<Longrightarrow> ( *f* f) x \\<approx> ( *f* f) y\"\n  by (simp add: isNSUCont_def)\n\nlemma isUCont_isNSUCont:\n  fixes f :: \"'a::real_normed_vector \\<Rightarrow> 'b::real_normed_vector\"\n  assumes f: \"isUCont f\"\n  shows \"isNSUCont f\"\n  unfolding isNSUCont_def\nproof safe\n  fix x y :: \"'a star\"\n  assume approx: \"x \\<approx> y\"\n  have \"starfun f x - starfun f y \\<in> Infinitesimal\"\n  proof (rule InfinitesimalI2)\n    fix r :: real\n    assume r: \"0 < r\"\n    with f obtain s where s: \"0 < s\"\n      and less_r: \"\\<And>x y. norm (x - y) < s \\<Longrightarrow> norm (f x - f y) < r\"\n      by (auto simp add: isUCont_def dist_norm)\n    from less_r have less_r':\n      \"\\<And>x y. hnorm (x - y) < star_of s \\<Longrightarrow> hnorm (starfun f x - starfun f y) < star_of r\"\n      by transfer\n    from approx have \"x - y \\<in> Infinitesimal\"\n      by (unfold approx_def)\n    then have \"hnorm (x - y) < star_of s\"\n      using s by (rule InfinitesimalD2)\n    then show \"hnorm (starfun f x - starfun f y) < star_of r\"\n      by (rule less_r')\n  qed\n  then show \"starfun f x \\<approx> starfun f y\"\n    by (unfold approx_def)\nqed\n\nlemma isNSUCont_isUCont:\n  fixes f :: \"'a::real_normed_vector \\<Rightarrow> 'b::real_normed_vector\"\n  assumes f: \"isNSUCont f\"\n  shows \"isUCont f\"\n  unfolding isUCont_def dist_norm\nproof safe\n  fix r :: real\n  assume r: \"0 < r\"\n  have \"\\<exists>s>0. \\<forall>x y. hnorm (x - y) < s \\<longrightarrow> hnorm (starfun f x - starfun f y) < star_of r\"\n  proof (rule exI, safe)\n    show \"0 < \\<epsilon>\"\n      by (rule epsilon_gt_zero)\n  next\n    fix x y :: \"'a star\"\n    assume \"hnorm (x - y) < \\<epsilon>\"\n    with Infinitesimal_epsilon have \"x - y \\<in> Infinitesimal\"\n      by (rule hnorm_less_Infinitesimal)\n    then have \"x \\<approx> y\"\n      by (unfold approx_def)\n    with f have \"starfun f x \\<approx> starfun f y\"\n      by (simp add: isNSUCont_def)\n    then have \"starfun f x - starfun f y \\<in> Infinitesimal\"\n      by (unfold approx_def)\n    then show \"hnorm (starfun f x - starfun f y) < star_of r\"\n      using r by (rule InfinitesimalD2)\n  qed\n  then show \"\\<exists>s>0. \\<forall>x y. norm (x - y) < s \\<longrightarrow> norm (f x - f y) < r\"\n    by transfer\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/Nonstandard_Analysis/HLim.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8652240930029118, "lm_q2_score": 0.8221891283434876, "lm_q1q2_score": 0.7113778428478487}}
{"text": "(*\n  File:    Linear_Recurrences_Solver.thy\n  Author:  Manuel Eberl, TU M\u00fcnchen\n*)\nsection \\<open>Solver for linear recurrences\\<close>\ntheory Linear_Recurrences_Solver\nimports\n  Complex_Main\n  Linear_Recurrences.Linear_Homogenous_Recurrences\n  Linear_Recurrences.Linear_Inhomogenous_Recurrences\n  Factor_Algebraic_Polynomial.Factor_Complex_Poly\nbegin\n\nlemma is_factorization_of_factor_complex_main:\n  assumes \"factor_complex_main p = fctrs\"\n  shows   \"is_factorization_of fctrs p\"\n  unfolding is_factorization_of_def\nproof safe\n  from assms have \"p = Polynomial.smult (fst fctrs) (\\<Prod>(x, i)\\<leftarrow>snd fctrs. [:- x, 1:] ^ Suc i)\"\n    by (intro factor_complex_main) simp_all\n  also have \"\\<dots> = interp_factorization fctrs\" \n    by (simp add: interp_factorization_def case_prod_unfold)\n  finally show \"interp_factorization fctrs = p\" ..\n  show \"distinct (map fst (snd fctrs))\" unfolding assms[symmetric]\n    by (rule distinct_factor_complex_main)\nqed\n\n\ndefinition solve_ratfps \n    :: \"complex ratfps \\<Rightarrow> complex poly \\<times> (complex poly \\<times> complex) list\" where\n  \"solve_ratfps f = \n     (case quot_of_ratfps f of (p, q) \\<Rightarrow>  \n        solve_factored_ratfps' p (factor_complex_main (reflect_poly q)))\"\n\nlemma solve_ratfps:\n  assumes \"solve_ratfps f = sol\"\n  shows   \"Abs_fps (interp_ratfps_solution sol) = fps_of_ratfps f\"\nproof -\n  define p and q where \"p = fst (quot_of_ratfps f)\" and \"q = snd (quot_of_ratfps f)\"\n  with assms obtain fctrs where fctrs: \"factor_complex_main (reflect_poly q) = fctrs\"\n    by (auto simp: solve_ratfps_def p_def q_def case_prod_unfold split: if_splits)\n  have q: \"coeff q 0 \\<noteq> 0\" by (simp add: q_def)\n  hence [simp]: \"q \\<noteq> 0\" by auto\n  from fctrs have \"is_factorization_of fctrs (reflect_poly q)\"\n    by (rule is_factorization_of_factor_complex_main)\n  with assms have \"is_alt_factorization_of fctrs (reflect_poly (reflect_poly q))\"\n    by (intro reflect_factorization) simp_all\n  hence \"is_alt_factorization_of fctrs q\" by (simp add: q)\n  with fctrs q \n    have \"Abs_fps (interp_ratfps_solution (solve_factored_ratfps' p fctrs)) = \n            fps_of_poly p / fps_of_poly q\"\n    by (intro solve_factored_ratfps') (simp_all)\n  also from fctrs assms have \"solve_factored_ratfps' p fctrs = sol\"\n    by (simp add: solve_ratfps_def p_def q_def case_prod_unfold split: if_splits)\n  finally show ?thesis by (simp add: fps_of_ratfps_altdef case_prod_unfold p_def q_def)\nqed\n\n\ndefinition solve_lhr \n    :: \"complex list \\<Rightarrow> complex list \\<Rightarrow> (complex poly \\<times> (complex poly \\<times> complex) list) option\" where\n  \"solve_lhr cs fs = (if cs = [] \\<or> length fs < length cs - 1 then None else\n     let m = length fs + 1 - length cs;\n         p = lhr_fps_numerator m cs (\\<lambda>n. fs ! n);\n         q = lr_fps_denominator' cs\n     in  Some (solve_factored_ratfps' p (factor_complex_main q)))\"\n\n\nlemma solve_lhr:\n  assumes \"linear_homogenous_recurrence f cs fs\"\n  assumes \"Some sol = solve_lhr cs fs\"\n  shows   \"f = interp_ratfps_solution sol\"\nproof -\n  obtain fctrs where \n      fctrs: \"factor_complex_main (lr_fps_denominator' cs) = fctrs\"\n    by auto\n  from is_factorization_of_factor_complex_main[OF this] \n    have factorization: \"is_factorization_of fctrs (lr_fps_denominator' cs)\" . \n\n  have \"f = interp_ratfps_solution (solve_factored_ratfps' (lhr_fps_numerator \n              (length fs + 1 - length cs) cs ((!) fs)) fctrs)\"\n    (is \"_ = interp_ratfps_solution ?sol\") by (intro solve_lhr_aux) fact+\n  also from assms(2) have \"?sol = sol\"\n    by (auto simp: solve_lhr_def Let_def case_prod_unfold fctrs split: if_splits)\n  finally show ?thesis .\nqed\n\ndefinition solve_lir \n    :: \"complex list \\<Rightarrow> complex list \\<Rightarrow> complex polyexp \\<Rightarrow> \n          (complex poly \\<times> (complex poly \\<times> complex) list) option\" where\n  \"solve_lir cs fs g = map_option solve_ratfps (lir_fps cs fs g)\"\n\nlemma solve_lir:\n  assumes \"linear_inhomogenous_recurrence f (eval_polyexp g) cs fs\"\n  assumes \"solve_lir cs fs g = Some sol\"\n  shows   \"f = interp_ratfps_solution sol\"\nproof -\n  from lir_fps_correct[OF assms(1)] obtain fps \n    where fps: \"lir_fps cs fs g = Some fps\" \"fps_of_ratfps fps = Abs_fps f\" by blast\n  from assms(2) have \"solve_ratfps fps = sol\"\n    by (simp add: solve_lir_def fps case_prod_unfold)\n  from solve_ratfps[OF this] have \"Abs_fps (interp_ratfps_solution sol) = fps_of_ratfps fps\"\n    by (simp add: case_prod_unfold fps_of_ratfps_altdef)\n  with fps have \"Abs_fps f = Abs_fps (interp_ratfps_solution sol)\" by simp\n  thus ?thesis by (simp add: fun_eq_iff fps_eq_iff)\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/Linear_Recurrences/Solver/Linear_Recurrences_Solver.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240721511739, "lm_q2_score": 0.822189134878876, "lm_q1q2_score": 0.7113778313583519}}
{"text": "(* Title:      Finite Suprema\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>Finite Suprema\\<close>\n\ntheory Finite_Suprema\nimports Dioid\nbegin\n\ntext \\<open>This file contains an adaptation of Isabelle's library for\nfinite sums to the case of (join) semilattices and dioids. In this\nsetting, addition is idempotent; finite sums are finite suprema.\n\nWe add some basic properties of finite suprema for (join) semilattices\nand dioids.\\<close>\n\nsubsection \\<open>Auxiliary Lemmas\\<close>\n\nlemma fun_im: \"{f a |a. a \\<in> A} = {b. b \\<in> f ` A}\"\n  by auto\n\nlemma fset_to_im: \"{f x |x. x \\<in> X} = f ` X\"\n  by auto\n\nlemma cart_flip_aux: \"{f (snd p) (fst p) |p. p \\<in> (B \\<times> A)} = {f (fst p) (snd p) |p. p \\<in> (A \\<times> B)}\"\n  by auto\n\nlemma cart_flip: \"(\\<lambda>p. f (snd p) (fst p)) ` (B \\<times> A) = (\\<lambda>p. f (fst p) (snd p)) ` (A \\<times> B)\"\n  by (metis cart_flip_aux fset_to_im)\n\nlemma fprod_aux: \"{x \\<cdot> y |x y. x \\<in> (f ` A) \\<and> y \\<in> (g ` B)} = {f x \\<cdot> g y |x y. x \\<in> A \\<and> y \\<in> B}\"\n  by auto\n\nsubsection \\<open>Finite Suprema in Semilattices\\<close>\n\ntext \\<open>The first lemma shows that, in the context of semilattices,\nfinite sums satisfy the defining property of finite suprema.\\<close>\n\nlemma sum_sup:\n  assumes \"finite (A :: 'a::join_semilattice_zero set)\"\n  shows \"\\<Sum>A \\<le> z \\<longleftrightarrow> (\\<forall>a \\<in> A. a \\<le> z)\"\nproof (induct rule: finite_induct[OF assms])\n  fix z ::'a\n  show \"(\\<Sum>{} \\<le> z) = (\\<forall>a \\<in> {}. a \\<le> z)\"\n    by simp\nnext\n  fix x z :: 'a and F :: \"'a set\"\n  assume finF: \"finite F\"\n    and xnF: \"x \\<notin> F\"\n    and indhyp: \"(\\<Sum>F \\<le> z) = (\\<forall>a \\<in> F. a \\<le> z)\"\n  show \"(\\<Sum>(insert x F) \\<le> z) = (\\<forall>a \\<in> insert x F. a \\<le> z)\"\n  proof -\n    have \"\\<Sum>(insert x F) \\<le> z \\<longleftrightarrow> (x + \\<Sum>F) \\<le> z\"\n      by (metis finF sum.insert xnF)\n    also have \"... \\<longleftrightarrow> x \\<le> z \\<and> \\<Sum>F \\<le> z\"\n      by simp\n    also have \"... \\<longleftrightarrow> x \\<le> z \\<and> (\\<forall>a \\<in> F. a \\<le> z)\"\n      by (metis (lifting) indhyp)\n    also have \"... \\<longleftrightarrow> (\\<forall>a \\<in> insert x F. a \\<le> z)\"\n      by (metis insert_iff)\n    ultimately show \"(\\<Sum>(insert x F) \\<le> z) = (\\<forall>a \\<in> insert x F. a \\<le> z)\"\n      by blast\n  qed\nqed\n\ntext \\<open>This immediately implies some variants.\\<close>\n\nlemma sum_less_eqI:\n  \"(\\<And>x. x \\<in> A \\<Longrightarrow> f x \\<le> y) \\<Longrightarrow> sum f A \\<le> (y::'a::join_semilattice_zero)\"\n apply (atomize (full))\n apply (case_tac \"finite A\")\n  apply (erule finite_induct)\n   apply simp_all\ndone\n\nlemma sum_less_eqE:\n  \"\\<lbrakk> sum f A \\<le> y; x \\<in> A; finite A \\<rbrakk> \\<Longrightarrow> f x \\<le> (y::'a::join_semilattice_zero)\"\n apply (erule rev_mp)\n apply (erule rev_mp)\n apply (erule finite_induct)\n  apply auto\ndone\n\nlemma sum_fun_image_sup:\n  fixes f :: \"'a \\<Rightarrow> 'b::join_semilattice_zero\"\n  assumes \"finite (A :: 'a set)\"\n  shows \"\\<Sum>(f ` A) \\<le> z \\<longleftrightarrow> (\\<forall>a \\<in> A. f a \\<le> z)\"\n  by (simp add: assms sum_sup)\n\nlemma sum_fun_sup:\n  fixes f :: \"'a \\<Rightarrow> 'b::join_semilattice_zero\"\n  assumes \"finite (A ::'a set)\"\n  shows \"\\<Sum>{f a | a. a \\<in> A} \\<le> z \\<longleftrightarrow> (\\<forall>a \\<in> A. f a \\<le> z)\"\n  by (simp only: fset_to_im assms sum_fun_image_sup)\n\nlemma sum_intro:\n  assumes \"finite (A :: 'a::join_semilattice_zero set)\" and \"finite B\"\n  shows \"(\\<forall>a \\<in> A. \\<exists>b \\<in> B. a \\<le> b) \\<longrightarrow> (\\<Sum>A \\<le> \\<Sum>B)\"\n  by (metis assms order_refl order_trans sum_sup)\n\ntext \\<open>Next we prove an additivity property for suprema.\\<close>\n\nlemma sum_union:\n  assumes \"finite (A :: 'a::join_semilattice_zero set)\"\n  and \"finite (B :: 'a::join_semilattice_zero set)\"\n  shows \"\\<Sum>(A \\<union> B) = \\<Sum>A + \\<Sum>B\"\nproof -\n    have \"\\<forall>z. \\<Sum>(A \\<union> B) \\<le> z \\<longleftrightarrow> (\\<Sum>A + \\<Sum>B \\<le> z)\"\n      by (auto simp add: assms sum_sup)\n  thus ?thesis\n    by (simp add: eq_iff)\nqed\n\ntext \\<open>It follows that the sum (supremum) of a two-element set is the\njoin of its elements.\\<close>\n\nlemma sum_bin[simp]: \"\\<Sum>{(x :: 'a::join_semilattice_zero),y} = x + y\"\n  by (subst insert_is_Un, subst sum_union, auto)\n\ntext \\<open>Next we show that finite suprema are order preserving.\\<close>\n\nlemma sum_iso:\n  assumes \"finite (B :: 'a::join_semilattice_zero set)\"\n  shows \"A \\<subseteq> B \\<longrightarrow> \\<Sum> A \\<le> \\<Sum> B\"\n  by (metis assms finite_subset order_refl rev_subsetD sum_sup)\n\ntext \\<open>The following lemmas state unfold properties for suprema and\nfinite sets. They are subtly different from the non-idempotent case,\nwhere additional side conditions are required.\\<close>\n\nlemma sum_insert [simp]:\n  assumes \"finite (A :: 'a::join_semilattice_zero set)\"\n  shows \"\\<Sum>(insert x A) = x + \\<Sum>A\"\nproof -\n  have \"\\<Sum>(insert x A) = \\<Sum>{x} + \\<Sum>A\"\n    by (metis insert_is_Un assms finite.emptyI finite.insertI sum_union)\n  thus ?thesis\n    by auto\nqed\n\nlemma sum_fun_insert:\n  fixes f :: \"'a \\<Rightarrow> 'b::join_semilattice_zero\"\n  assumes \"finite (A :: 'a set)\"\n  shows \"\\<Sum>(f ` (insert x A)) = f x + \\<Sum>(f ` A)\"\n  by (simp add: assms)\n\ntext \\<open>Now we show that set comprehensions with nested suprema can\nbe flattened.\\<close>\n\nlemma flatten1_im:\n  fixes f :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'b::join_semilattice_zero\"\n  assumes \"finite (A :: 'a set)\"\n  and \"finite (B :: 'a set)\"\n  shows \"\\<Sum>((\\<lambda>x. \\<Sum>(f x ` B)) ` A) = \\<Sum>((\\<lambda>p. f (fst p) (snd p)) ` (A \\<times> B))\"\nproof -\n  have \"\\<forall>z. \\<Sum>((\\<lambda>x. \\<Sum>(f x ` B)) ` A) \\<le> z \\<longleftrightarrow> \\<Sum>((\\<lambda>p. f (fst p) (snd p)) ` (A \\<times> B)) \\<le> z\"\n    by (simp add: assms finite_cartesian_product sum_fun_image_sup)\n  thus ?thesis\n    by (simp add: eq_iff)\nqed\n\nlemma flatten2_im:\n  fixes f :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'b::join_semilattice_zero\"\n  assumes \"finite (A ::'a set)\"\n  and \"finite (B ::'a set)\"\n  shows \"\\<Sum>((\\<lambda>y. \\<Sum> ((\\<lambda>x. f x y) ` A)) ` B) = \\<Sum>((\\<lambda>p. f (fst p) (snd p)) ` (A \\<times> B))\"\n  by (simp only: flatten1_im assms cart_flip)\n\nlemma sum_flatten1:\n  fixes f :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'b::join_semilattice_zero\"\n  assumes \"finite (A :: 'a set)\"\n  and \"finite (B :: 'a set)\"\n  shows \"\\<Sum>{\\<Sum>{f x y |y. y \\<in> B} |x. x \\<in> A} = \\<Sum>{f x y |x y. x \\<in> A \\<and> y \\<in> B}\"\n apply (simp add: fset_to_im assms flatten1_im)\n apply (subst fset_to_im[symmetric])\n apply simp\ndone\n\nlemma sum_flatten2:\n  fixes f :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'b::join_semilattice_zero\"\n  assumes \"finite A\"\n  and \"finite B\"\n  shows \"\\<Sum>{\\<Sum> {f x y |x. x \\<in> A} |y. y \\<in> B} = \\<Sum>{f x y |x y. x \\<in> A \\<and> y \\<in> B}\"\n apply (simp add: fset_to_im assms flatten2_im)\n apply (subst fset_to_im[symmetric])\n apply simp\ndone\n\ntext \\<open>Next we show another additivity property for suprema.\\<close>\n\nlemma sum_fun_sum:\n  fixes f g :: \"'a \\<Rightarrow> 'b::join_semilattice_zero\"\n  assumes  \"finite (A :: 'a set)\"\n  shows \"\\<Sum>((\\<lambda>x. f x + g x) ` A) = \\<Sum>(f ` A) + \\<Sum>(g ` A)\"\nproof -\n  {\n    fix z:: 'b\n    have \"\\<Sum>((\\<lambda>x. f x + g x) ` A) \\<le> z \\<longleftrightarrow> \\<Sum>(f ` A) + \\<Sum>(g ` A) \\<le> z\"\n      by (auto simp add: assms sum_fun_image_sup)\n  }\n  thus ?thesis\n    by (simp add: eq_iff)\nqed\n\ntext \\<open>The last lemma of this section prepares the distributivity\n  laws that hold for dioids. It states that a strict additive function\n  distributes over finite suprema, which is a continuity property in\n  the finite.\\<close>\n\nlemma sum_fun_add:\n  fixes f :: \"'a::join_semilattice_zero \\<Rightarrow> 'b::join_semilattice_zero\"\n  assumes \"finite (X :: 'a set)\"\n  and fstrict: \"f 0 = 0\"\n  and fadd: \"\\<And>x y. f (x + y) = f x + f y\"\n  shows \"f (\\<Sum> X) = \\<Sum>(f ` X)\"\nproof (induct rule: finite_induct[OF assms(1)])\n  show \"f (\\<Sum>{}) = \\<Sum>(f ` {})\"\n    by (metis fstrict image_empty sum.empty)\n  fix x :: 'a and  F ::\" 'a set\"\n  assume finF: \"finite F\"\n    and indhyp: \"f (\\<Sum>F) = \\<Sum>(f ` F)\"\n  have \"f (\\<Sum>(insert x F)) = f (x + \\<Sum>F)\"\n    by (metis sum_insert finF)\n  also have \"... = f x + (f (\\<Sum>F))\"\n    by (rule fadd)\n  also have \"... = f x + \\<Sum>(f ` F)\"\n    by (metis indhyp)\n  also have \"... = \\<Sum>(f ` (insert x F))\"\n    by (metis finF sum_fun_insert)\n  finally show \"f (\\<Sum>(insert x F)) = \\<Sum>(f ` insert x F)\" .\nqed\n\nsubsection \\<open>Finite Suprema in Dioids\\<close>\n\ntext \\<open>In this section we mainly prove variants of distributivity laws.\\<close>\n\nlemma sum_distl:\n  assumes \"finite Y\"\n  shows \"(x :: 'a::dioid_one_zero) \\<cdot> (\\<Sum>Y) = \\<Sum>{x \\<cdot> y|y. y \\<in> Y}\"\n  by (simp only: sum_fun_add assms annir distrib_left Collect_mem_eq fun_im)\n\nlemma sum_distr:\n  assumes \"finite X\"\n  shows \"(\\<Sum>X) \\<cdot> (y :: 'a::dioid_one_zero) = \\<Sum>{x \\<cdot> y|x. x \\<in> X}\"\nproof -\n  have \"(\\<Sum> X) \\<cdot> y = \\<Sum> ((\\<lambda>x. x \\<cdot> y) ` X)\"\n    by (rule sum_fun_add, metis assms, rule annil, rule distrib_right)\n  thus ?thesis\n    by (metis Collect_mem_eq fun_im)\nqed\n\nlemma sum_fun_distl:\n  fixes f :: \"'a \\<Rightarrow> 'b::dioid_one_zero\"\n  assumes \"finite (Y :: 'a set)\"\n  shows \"x \\<cdot> \\<Sum>(f ` Y) = \\<Sum>{x \\<cdot> f y |y. y \\<in> Y}\"\n  by (simp add: assms fun_im image_image sum_distl)\n\nlemma sum_fun_distr:\n  fixes f :: \"'a \\<Rightarrow> 'b::dioid_one_zero\"\n  assumes \"finite (X :: 'a set)\"\n  shows \"\\<Sum>(f ` X) \\<cdot> y = \\<Sum>{f x \\<cdot> y |x. x \\<in> X}\"\n  by (simp add: assms fun_im image_image sum_distr)\n\nlemma sum_distl_flat:\n  assumes \"finite (X ::'a::dioid_one_zero set)\"\n  and \"finite Y\"\n  shows \"\\<Sum>{x \\<cdot> \\<Sum>Y |x. x \\<in> X} = \\<Sum>{x \\<cdot> y|x y. x \\<in> X \\<and> y \\<in> Y}\"\n  by (simp only: assms sum_distl sum_flatten1)\n\nlemma sum_distr_flat:\n  assumes \"finite X\"\n  and \"finite (Y :: 'a::dioid_one_zero set)\"\n  shows \"\\<Sum>{(\\<Sum>X) \\<cdot> y |y. y \\<in> Y} = \\<Sum>{x \\<cdot> y|x y. x \\<in> X \\<and> y \\<in> Y}\"\n  by (simp only: assms sum_distr sum_flatten2)\n\nlemma sum_sum_distl:\n  assumes \"finite (X :: 'a::dioid_one_zero set)\"\n  and \"finite Y\"\n  shows \"\\<Sum>((\\<lambda>x. x \\<cdot> (\\<Sum>Y)) ` X) = \\<Sum>{x \\<cdot> y |x y. x \\<in> X \\<and> y \\<in> Y}\"\nproof -\n  have \"\\<Sum>((\\<lambda>x. x \\<cdot> (\\<Sum>Y)) ` X) = \\<Sum>{\\<Sum>{x \\<cdot> y |y. y \\<in> Y} |x. x \\<in> X}\"\n    by (auto simp add: sum_distl assms fset_to_im)\n  thus ?thesis\n    by (simp add: assms sum_flatten1)\nqed\n\nlemma sum_sum_distr:\n  assumes \"finite X\"\n  and \"finite Y\"\n  shows \"\\<Sum>((\\<lambda>y. (\\<Sum>X) \\<cdot> (y :: 'a::dioid_one_zero)) ` Y) = \\<Sum>{x \\<cdot> y|x y. x \\<in> X \\<and> y \\<in> Y}\"\nproof -\n  have \"\\<Sum>((\\<lambda>y. (\\<Sum>X) \\<cdot> y) ` Y) = \\<Sum>{\\<Sum>{x \\<cdot> y |x. x \\<in> X} |y. y \\<in> Y}\"\n    by (auto simp add: sum_distr assms fset_to_im)\n  thus ?thesis\n    by (simp add: assms sum_flatten2)\nqed\n\nlemma sum_sum_distl_fun:\n  fixes f g :: \"'a \\<Rightarrow> 'b::dioid_one_zero\"\n  fixes h :: \"'a \\<Rightarrow> 'a set\"\n  assumes \"\\<And>x. finite (h x)\"\n  and \"finite X\"\n  shows \"\\<Sum>((\\<lambda>x. f x \\<cdot> \\<Sum>(g ` h x)) ` X) = \\<Sum>{\\<Sum> {f x \\<cdot> g y |y. y \\<in> h x} |x. x \\<in> X}\"\n  by (auto simp add: sum_fun_distl assms fset_to_im)\n\nlemma sum_sum_distr_fun:\n  fixes f g :: \"'a \\<Rightarrow> 'b::dioid_one_zero\"\n  fixes h :: \"'a \\<Rightarrow> 'a set\"\n  assumes \"finite Y\"\n  and \"\\<And>y. finite (h y)\"\n  shows \"\\<Sum>((\\<lambda>y. \\<Sum>(f ` h y) \\<cdot> g y) ` Y) = \\<Sum>{\\<Sum>{f x \\<cdot> g y |x. x \\<in> (h y)} |y. y \\<in> Y}\"\n  by (auto simp add: sum_fun_distr assms fset_to_im)\n\nlemma sum_dist:\n  assumes \"finite (A :: 'a::dioid_one_zero set)\"\n  and \"finite B\"\n  shows \"(\\<Sum>A) \\<cdot> (\\<Sum>B) = \\<Sum>{x \\<cdot> y |x y. x \\<in> A \\<and> y \\<in> B}\"\nproof -\n  have \"(\\<Sum>A) \\<cdot> (\\<Sum>B) = \\<Sum>{x \\<cdot> \\<Sum>B |x. x \\<in> A}\"\n    by (simp add: assms sum_distr)\n  also have \"... = \\<Sum>{\\<Sum>{x \\<cdot> y |y. y \\<in> B} |x. x \\<in> A}\"\n    by (simp add: assms sum_distl)\n  finally show ?thesis\n    by  (simp only: sum_flatten1 assms finite_cartesian_product)\nqed\n\nlemma dioid_sum_prod_var:\n  fixes f g :: \"'a \\<Rightarrow> 'b::dioid_one_zero\"\n  assumes \"finite (A ::'a set)\"\n  shows \"(\\<Sum>(f ` A)) \\<cdot> (\\<Sum> (g ` A)) = \\<Sum>{f x \\<cdot> g y |x y. x \\<in> A \\<and> y \\<in> A}\"\n  by (simp add: assms sum_dist fprod_aux)\n\nlemma dioid_sum_prod:\n  fixes f g :: \"'a \\<Rightarrow> 'b::dioid_one_zero\"\n  assumes \"finite (A :: 'a set)\"\n  shows \"(\\<Sum>{f x |x. x \\<in> A}) \\<cdot> (\\<Sum>{g x |x. x \\<in> A}) = \\<Sum>{f x \\<cdot> g y |x y. x \\<in> A \\<and> y \\<in> A}\"\n  by (simp add: assms dioid_sum_prod_var fset_to_im)\n\nlemma sum_image:\n  fixes f :: \"'a \\<Rightarrow> 'b::join_semilattice_zero\"\n  assumes \"finite X\"\n  shows \"sum f X = \\<Sum>(f ` X)\"\nusing assms \nproof (induct rule: finite_induct)\n  case empty thus ?case by simp\nnext\n  case insert thus ?case\n    by (metis sum.insert sum_fun_insert)\nqed\n\nlemma sum_interval_cong:\n  \"\\<lbrakk> \\<And> i. \\<lbrakk> m \\<le> i; i \\<le> n \\<rbrakk> \\<Longrightarrow> P(i) = Q(i) \\<rbrakk> \\<Longrightarrow> (\\<Sum>i=m..n. P(i)) = (\\<Sum>i=m..n. Q(i))\"\n  by (auto intro: sum.cong)\n\nlemma sum_interval_distl:\n  fixes f :: \"nat \\<Rightarrow> 'a::dioid_one_zero\"\n  assumes \"m \\<le> n\"\n  shows \"x \\<cdot> (\\<Sum>i=m..n. f(i)) = (\\<Sum>i=m..n. (x \\<cdot> f(i)))\"\nproof -\n  have \"x \\<cdot> (\\<Sum>i=m..n. f(i)) = x \\<cdot> \\<Sum>(f ` {m..n})\"\n    by (metis finite_atLeastAtMost sum_image)\n  also have \"... = \\<Sum>{x \\<cdot> y |y. y \\<in> f ` {m..n}}\"\n    by (metis finite_atLeastAtMost fset_to_im image_image sum_fun_distl)\n  also have \"... = \\<Sum>((\\<lambda>i. x \\<cdot> f i) ` {m..n})\"\n    by (metis fset_to_im image_image)\n  also have \"... = (\\<Sum>i=m..n. (x \\<cdot> f(i)))\"\n    by (metis finite_atLeastAtMost sum_image)\n  finally show ?thesis .\nqed\n\nlemma sum_interval_distr:\n  fixes f :: \"nat \\<Rightarrow> 'a::dioid_one_zero\"\n  assumes \"m \\<le> n\"\n  shows \"(\\<Sum>i=m..n. f(i)) \\<cdot> y = (\\<Sum>i=m..n. (f(i) \\<cdot> y))\"\n  proof -\n  have \"(\\<Sum>i=m..n. f(i)) \\<cdot> y = \\<Sum>(f ` {m..n}) \\<cdot> y\"\n    by (metis finite_atLeastAtMost sum_image)\n  also have \"... = \\<Sum>{x \\<cdot> y |x. x \\<in> f ` {m..n}}\"\n    by (metis calculation finite_atLeastAtMost finite_imageI fset_to_im sum_distr)\n  also have \"... = \\<Sum>((\\<lambda>i. f(i) \\<cdot> y) ` {m..n})\"\n    by (auto intro: sum.cong)\n  also have \"... = (\\<Sum>i=m..n. (f(i) \\<cdot> y))\"\n    by (metis finite_atLeastAtMost sum_image)\n  finally show ?thesis .\nqed\n\ntext \\<open>There are interesting theorems for finite sums in Kleene\nalgebras; we leave them for future consideration.\\<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/Kleene_Algebra/Finite_Suprema.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8311430520409023, "lm_q2_score": 0.8558511451289037, "lm_q1q2_score": 0.7113347328551383}}
{"text": "theory Scratch2\n  imports Main\nbegin\nfun conj :: \"bool \\<Rightarrow> bool \\<Rightarrow> bool\" where\n\"conj True True = True\" |\n\"conj _ _ = False\"\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_O2: \"add' m 0 = m\"\n  apply (induction m)\n   apply (auto)\n  done\n\nthm add_O2\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\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\nfun map :: \"('a \\<Rightarrow> 'b) \\<Rightarrow> 'a list \\<Rightarrow> 'b list\" where\n\"map f Nil = Nil\" |\n\"map f (Cons a as) = Cons (f a) (map f as)\"\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\ntype_synonym string = \"char list\"\n\nvalue \"string = char list\"\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\nfun lookup :: \"('a * 'b) list \\<Rightarrow> 'a \\<Rightarrow> 'b option\" where\n\"lookup [] _ = None\" |\n\"lookup ((a,b)#xs) x = (if (a = x)\n                        then Some b\n                        else (lookup xs 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 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\"\n   apply (auto)\n  done\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/Scratch2.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.855851135937125, "lm_q2_score": 0.8311430478583168, "lm_q1q2_score": 0.7113347216357847}}
{"text": "theory MFMC_Network imports\n  MFMC_Misc\nbegin\n\nsection \\<open>Graphs\\<close>\n\ntype_synonym 'v edge = \"'v \\<times> 'v\"\n\nrecord 'v graph =\n  edge :: \"'v \\<Rightarrow> 'v \\<Rightarrow> bool\"\n\nabbreviation edges :: \"('v, 'more) graph_scheme \\<Rightarrow> 'v edge set\" (\"\\<^bold>E\\<index>\")\nwhere \"\\<^bold>E\\<^bsub>G\\<^esub> \\<equiv> {(x, y). edge G x y}\"\n\ndefinition outgoing :: \"('v, 'more) graph_scheme \\<Rightarrow> 'v \\<Rightarrow> 'v set\" (\"\\<^bold>O\\<^bold>U\\<^bold>T\\<index>\")\nwhere \"\\<^bold>O\\<^bold>U\\<^bold>T\\<^bsub>G\\<^esub> x = {y. (x, y) \\<in> \\<^bold>E\\<^bsub>G\\<^esub>}\"\n\ndefinition incoming :: \"('v, 'more) graph_scheme \\<Rightarrow> 'v \\<Rightarrow> 'v set\" (\"\\<^bold>I\\<^bold>N\\<index>\")\nwhere \"\\<^bold>I\\<^bold>N\\<^bsub>G\\<^esub> y = {x. (x, y) \\<in> \\<^bold>E\\<^bsub>G\\<^esub>}\"\n\ntext \\<open>\n  Vertices are implicitly defined as the endpoints of edges, so we do not allow isolated vertices.\n  For the purpose of flows, this does not matter as isolated vertices cannot contribute to a flow.\n  The advantage is that we do not need any invariant on graphs that the endpoints of edges are a\n  subset of the vertices. Conversely, this design choice makes a few proofs about reductions on webs\n  harder, because we have to adjust other sets which are supposed to be part of the vertices.\n\\<close>\n\ndefinition vertex :: \"('v, 'more) graph_scheme \\<Rightarrow> 'v \\<Rightarrow> bool\"\nwhere \"vertex G x \\<longleftrightarrow> Domainp (edge G) x \\<or> Rangep (edge G) x\"\n\nlemma vertexI:\n  shows vertexI1: \"edge \\<Gamma> x y \\<Longrightarrow> vertex \\<Gamma> x\"\n  and vertexI2: \"edge \\<Gamma> x y \\<Longrightarrow> vertex \\<Gamma> y\"\nby(auto simp add: vertex_def)\n\nabbreviation vertices :: \"('v, 'more) graph_scheme \\<Rightarrow> 'v set\" (\"\\<^bold>V\\<index>\")\nwhere \"\\<^bold>V\\<^bsub>G\\<^esub> \\<equiv> Collect (vertex G)\"\n\nlemma \"\\<^bold>V_def\": \"\\<^bold>V\\<^bsub>G\\<^esub> = fst ` \\<^bold>E\\<^bsub>G\\<^esub> \\<union> snd ` \\<^bold>E\\<^bsub>G\\<^esub>\"\nby(auto 4 3 simp add: vertex_def intro: rev_image_eqI prod.expand)\n\ntype_synonym 'v path = \"'v list\"\n\nabbreviation path :: \"('v, 'more) graph_scheme \\<Rightarrow> 'v \\<Rightarrow> 'v path \\<Rightarrow> 'v \\<Rightarrow> bool\"\nwhere \"path G \\<equiv> rtrancl_path (edge G)\"\n\ninductive cycle :: \"('v, 'more) graph_scheme \\<Rightarrow> 'v path \\<Rightarrow> bool\"\n  for G\nwhere \\<comment> \\<open>Cycles must not pass through the same node multiple times. Otherwise, the cycle might\n  enter a node via two different edges and leave it via just one edge. Thus, the clean-up lemma\n  would not hold any more.\\<close>\n  cycle: \"\\<lbrakk> path G v p v; p \\<noteq> []; distinct p \\<rbrakk> \\<Longrightarrow> cycle G p\"\n\ninductive_simps cycle_Nil [simp]: \"cycle G Nil\"\n\nabbreviation cycles :: \"('v, 'more) graph_scheme \\<Rightarrow> 'v path set\"\nwhere \"cycles G \\<equiv> Collect (cycle G)\"\n\nlemma countable_cycles [simp]:\n  assumes \"countable (\\<^bold>V\\<^bsub>G\\<^esub>)\"\n  shows \"countable (cycles G)\"\nproof -\n  have \"cycles G \\<subseteq> lists \\<^bold>V\\<^bsub>G\\<^esub>\"\n    by(auto elim!: cycle.cases dest: rtrancl_path_Range_end rtrancl_path_Range simp add: vertex_def)\n  thus ?thesis by(rule countable_subset)(simp add: assms)\nqed\n\ndefinition cycle_edges :: \"'v path \\<Rightarrow> 'v edge list\"\nwhere \"cycle_edges p = zip p (rotate1 p)\"\n\nlemma cycle_edges_not_Nil: \"cycle G p \\<Longrightarrow> cycle_edges p \\<noteq> []\"\nby(auto simp add: cycle_edges_def cycle.simps neq_Nil_conv zip_Cons1 split: list.split)\n\nlemma distinct_cycle_edges:\n  \"cycle G p \\<Longrightarrow> distinct (cycle_edges p)\"\nby(erule cycle.cases)(simp add: cycle_edges_def distinct_zipI2)\n\nlemma cycle_enter_leave_same:\n  assumes \"cycle G p\"\n  shows \"card (set [(x', y) \\<leftarrow> cycle_edges p. x' = x]) = card (set [(x', y) \\<leftarrow> cycle_edges p. y = x])\"\n  (is \"?lhs = ?rhs\")\nusing assms\nproof cases\n  case (cycle v)\n  from distinct_cycle_edges[OF assms]\n  have \"?lhs = length [x' \\<leftarrow> map fst (cycle_edges p). x' = x]\"\n    by(subst distinct_card; simp add: filter_map o_def split_def)\n  also have \"\\<dots> = (if x \\<in> set p then 1 else 0)\" using cycle\n    by(auto simp add: cycle_edges_def filter_empty_conv length_filter_conv_card card_eq_1_iff in_set_conv_nth dest: nth_eq_iff_index_eq)\n  also have \"\\<dots> = length [y \\<leftarrow> map snd (cycle_edges p). y = x]\" using cycle\n    apply(auto simp add: cycle_edges_def filter_empty_conv Suc_length_conv intro!: exI[where x=x])\n    apply(drule split_list_first)\n    apply(auto dest: split_list_first simp add: append_eq_Cons_conv rotate1_append filter_empty_conv split: if_split_asm dest: in_set_tlD)\n    done\n  also have \"\\<dots> = ?rhs\" using distinct_cycle_edges[OF assms]\n    by(subst distinct_card; simp add: filter_map o_def split_def)\n  finally show ?thesis .\nqed\n\nlemma cycle_leave_ex_enter:\n  assumes \"cycle G p\" and \"(x, y) \\<in> set (cycle_edges p)\"\n  shows \"\\<exists>z. (z, x) \\<in> set (cycle_edges p)\"\nusing assms\nby(cases)(auto 4 3 simp add: cycle_edges_def cong: conj_cong split: if_split_asm intro: set_zip_rightI dest: set_zip_leftD)\n\nlemma cycle_edges_edges:\n  assumes \"cycle G p\"\n  shows \"set (cycle_edges p) \\<subseteq> \\<^bold>E\\<^bsub>G\\<^esub>\"\nproof\n  fix x\n  assume \"x \\<in> set (cycle_edges p)\"\n  then obtain i where x: \"x = (p ! i, rotate1 p ! i)\" and i: \"i < length p\"\n    by(auto simp add: cycle_edges_def set_zip)\n  from assms obtain v where p: \"path G v p v\" and \"p \\<noteq> []\" and \"distinct p\" by cases\n  let ?i = \"Suc i mod length p\"\n  have \"?i < length p\" by (simp add: \\<open>p \\<noteq> []\\<close>)\n  note rtrancl_path_nth[OF p this]\n  also have \"(v # p) ! ?i = p ! i\"\n  proof(cases \"Suc i < length p\")\n    case True thus ?thesis by simp\n  next\n    case False\n    with i have \"Suc i = length p\" by simp\n    moreover from p \\<open>p \\<noteq> []\\<close> have \"last p = v\" by(rule rtrancl_path_last)\n    ultimately show ?thesis using \\<open>p \\<noteq> []\\<close> by(simp add: last_conv_nth)(metis diff_Suc_Suc diff_zero)\n  qed\n  also have \"p ! ?i = rotate1 p ! i\" using i by(simp add: nth_rotate1)\n  finally show \"x \\<in> \\<^bold>E\\<^bsub>G\\<^esub>\" by(simp add: x)\nqed\n\n\nsection \\<open>Network and Flow\\<close>\n\nrecord 'v network = \"'v graph\" +\n  capacity :: \"'v edge \\<Rightarrow> ennreal\"\n  source :: \"'v\"\n  sink :: \"'v\"\n\ntype_synonym 'v flow = \"'v edge \\<Rightarrow> ennreal\"\n\ninductive_set support_flow :: \"'v flow \\<Rightarrow> 'v edge set\"\n  for f\nwhere \"f e > 0 \\<Longrightarrow> e \\<in> support_flow f\"\n\nlemma support_flow_conv: \"support_flow f = {e. f e > 0}\"\nby(auto simp add: support_flow.simps)\n\nlemma not_in_support_flowD: \"x \\<notin> support_flow f \\<Longrightarrow> f x = 0\"\nby(simp add: support_flow_conv)\n\ndefinition d_OUT :: \"'v flow \\<Rightarrow> 'v \\<Rightarrow> ennreal\"\nwhere \"d_OUT g x = (\\<Sum>\\<^sup>+ y. g (x, y))\"\n\ndefinition d_IN :: \"'v flow \\<Rightarrow> 'v \\<Rightarrow> ennreal\"\nwhere \"d_IN g y = (\\<Sum>\\<^sup>+ x. g (x, y))\"\n\nlemma d_OUT_mono: \"(\\<And>y. f (x, y) \\<le> g (x, y)) \\<Longrightarrow> d_OUT f x \\<le> d_OUT g x\"\nby(auto simp add: d_OUT_def le_fun_def intro: nn_integral_mono)\n\nlemma d_IN_mono: \"(\\<And>x. f (x, y) \\<le> g (x, y)) \\<Longrightarrow> d_IN f y \\<le> d_IN g y\"\nby(auto simp add: d_IN_def le_fun_def intro: nn_integral_mono)\n\nlemma d_OUT_0 [simp]: \"d_OUT (\\<lambda>_. 0) x = 0\"\nby(simp add: d_OUT_def)\n\nlemma d_IN_0 [simp]: \"d_IN (\\<lambda>_. 0) x = 0\"\nby(simp add: d_IN_def)\n\nlemma d_OUT_add: \"d_OUT (\\<lambda>e. f e + g e) x = d_OUT f x + d_OUT g x\"\nunfolding d_OUT_def by(simp add: nn_integral_add)\n\nlemma d_IN_add: \"d_IN (\\<lambda>e. f e + g e) x = d_IN f x + d_IN g x\"\nunfolding d_IN_def by(simp add: nn_integral_add)\n\nlemma d_OUT_cmult: \"d_OUT (\\<lambda>e. c * f e) x = c * d_OUT f x\"\nby(simp add: d_OUT_def nn_integral_cmult)\n\nlemma d_IN_cmult: \"d_IN (\\<lambda>e. c * f e) x = c * d_IN f x\"\nby(simp add: d_IN_def nn_integral_cmult)\n\nlemma d_OUT_ge_point: \"f (x, y) \\<le> d_OUT f x\"\nby(auto simp add: d_OUT_def intro!: nn_integral_ge_point)\n\nlemma d_IN_ge_point: \"f (y, x) \\<le> d_IN f x\"\nby(auto simp add: d_IN_def intro!: nn_integral_ge_point)\n\nlemma d_OUT_monotone_convergence_SUP:\n  assumes \"incseq (\\<lambda>n y. f n (x, y))\"\n  shows \"d_OUT (\\<lambda>e. SUP n. f n e) x = (SUP n. d_OUT (f n) x)\"\nunfolding d_OUT_def by(rule nn_integral_monotone_convergence_SUP[OF assms]) simp\n\nlemma d_IN_monotone_convergence_SUP:\n  assumes \"incseq (\\<lambda>n x. f n (x, y))\"\n  shows \"d_IN (\\<lambda>e. SUP n. f n e) y = (SUP n. d_IN (f n) y)\"\nunfolding d_IN_def by(rule nn_integral_monotone_convergence_SUP[OF assms]) simp\n\nlemma d_OUT_diff:\n  assumes \"\\<And>y. g (x, y) \\<le> f (x, y)\" \"d_OUT g x \\<noteq> \\<top>\"\n  shows \"d_OUT (\\<lambda>e. f e - g e) x = d_OUT f x - d_OUT g x\"\nusing assms by(simp add: nn_integral_diff d_OUT_def)\n\nlemma d_IN_diff:\n  assumes \"\\<And>x. g (x, y) \\<le> f (x, y)\" \"d_IN g y \\<noteq> \\<top>\"\n  shows \"d_IN (\\<lambda>e. f e - g e) y = d_IN f y - d_IN g y\"\nusing assms by(simp add: nn_integral_diff d_IN_def)\n\nlemma fixes G (structure)\n  shows d_OUT_alt_def: \"(\\<And>y. (x, y) \\<notin> \\<^bold>E \\<Longrightarrow> g (x, y) = 0) \\<Longrightarrow> d_OUT g x = (\\<Sum>\\<^sup>+  y\\<in>\\<^bold>O\\<^bold>U\\<^bold>T x. g (x, y))\"\n  and d_IN_alt_def: \"(\\<And>x. (x, y) \\<notin> \\<^bold>E \\<Longrightarrow> g (x, y) = 0) \\<Longrightarrow> d_IN g y = (\\<Sum>\\<^sup>+ x\\<in>\\<^bold>I\\<^bold>N y. g (x, y))\"\nunfolding d_OUT_def d_IN_def\nby(fastforce simp add: max_def d_OUT_def d_IN_def nn_integral_count_space_indicator outgoing_def incoming_def intro!: nn_integral_cong split: split_indicator)+\n\nlemma d_OUT_alt_def2: \"d_OUT g x = (\\<Sum>\\<^sup>+ y\\<in>{y. (x, y) \\<in> support_flow g}. g (x, y))\"\n  and d_IN_alt_def2: \"d_IN g y = (\\<Sum>\\<^sup>+ x\\<in>{x. (x, y) \\<in> support_flow g}. g (x, y))\"\nunfolding d_OUT_def d_IN_def\nby(auto simp add: max_def d_OUT_def d_IN_def nn_integral_count_space_indicator outgoing_def incoming_def support_flow.simps intro!: nn_integral_cong split: split_indicator)+\n\ndefinition d_diff :: \"('v edge \\<Rightarrow> ennreal) \\<Rightarrow> 'v \\<Rightarrow> ennreal\"\nwhere \"d_diff g x = d_OUT g x - d_IN g x\"\n\nabbreviation KIR :: \"('v edge \\<Rightarrow> ennreal) \\<Rightarrow> 'v \\<Rightarrow> bool\"\nwhere \"KIR f x \\<equiv> d_OUT f x = d_IN f x\"\n\ninductive_set SINK :: \"('v edge \\<Rightarrow> ennreal) \\<Rightarrow> 'v set\"\n  for f\nwhere SINK: \"d_OUT f x = 0 \\<Longrightarrow> x \\<in> SINK f\"\n\nlemma SINK_mono:\n  assumes \"\\<And>e. f e \\<le> g e\"\n  shows \"SINK g \\<subseteq> SINK f\"\nproof(rule subsetI; erule SINK.cases; hypsubst)\n  fix x\n  assume \"d_OUT g x = 0\"\n  moreover have \"d_OUT f x \\<le> d_OUT g x\" using assms by(rule d_OUT_mono)\n  ultimately have \"d_OUT f x = 0\" by simp\n  thus \"x \\<in> SINK f\" ..\nqed\n\nlemma SINK_mono': \"f \\<le> g \\<Longrightarrow> SINK g \\<subseteq> SINK f\"\nby(rule SINK_mono)(rule le_funD)\n\nlemma support_flow_Sup: \"support_flow (Sup Y) = (\\<Union>f\\<in>Y. support_flow f)\"\nby(auto simp add: support_flow_conv less_SUP_iff)\n\nlemma\n  assumes chain: \"Complete_Partial_Order.chain (\\<le>) Y\"\n  and Y: \"Y \\<noteq> {}\"\n  and countable: \"countable (support_flow (Sup Y))\"\n  shows d_OUT_Sup: \"d_OUT (Sup Y) x = (SUP f\\<in>Y. d_OUT f x)\" (is \"?OUT x\" is \"?lhs1 x = ?rhs1 x\")\n  and d_IN_Sup: \"d_IN (Sup Y) y = (SUP f\\<in>Y. d_IN f y)\" (is \"?IN\" is \"?lhs2 = ?rhs2\")\n  and SINK_Sup: \"SINK (Sup Y) = (\\<Inter>f\\<in>Y. SINK f)\" (is \"?SINK\")\nproof -\n  have chain': \"Complete_Partial_Order.chain (\\<le>) ((\\<lambda>f y. f (x, y)) ` Y)\" for x using chain\n    by(rule chain_imageI)(simp add: le_fun_def)\n  have countable': \"countable {y. (x, y) \\<in> support_flow (Sup Y)}\" for x\n    using _ countable[THEN countable_image[where f=snd]]\n    by(rule countable_subset)(auto intro: prod.expand rev_image_eqI)\n  { fix x\n    have \"?lhs1 x = (\\<Sum>\\<^sup>+ y\\<in>{y. (x, y) \\<in> support_flow (Sup Y)}. SUP f\\<in>Y. f (x, y))\"\n      by(subst d_OUT_alt_def2; simp)\n    also have \"\\<dots> = (SUP f\\<in>Y. \\<Sum>\\<^sup>+ y\\<in>{y. (x, y) \\<in> support_flow (Sup Y)}. f (x, y))\" using Y\n      by(rule nn_integral_monotone_convergence_SUP_countable)(auto simp add: chain' intro: countable')\n    also have \"\\<dots> = ?rhs1 x\" unfolding d_OUT_alt_def2\n      by(auto 4 3 simp add: support_flow_Sup max_def nn_integral_count_space_indicator intro!: nn_integral_cong SUP_cong split: split_indicator dest: not_in_support_flowD)\n    finally show \"?OUT x\" . }\n  note out = this\n\n  have chain'': \"Complete_Partial_Order.chain (\\<le>) ((\\<lambda>f x. f (x, y)) ` Y)\" for y using chain\n    by(rule chain_imageI)(simp add: le_fun_def)\n  have countable'': \"countable {x. (x, y) \\<in> support_flow (Sup Y)}\" for y\n    using _ countable[THEN countable_image[where f=fst]]\n    by(rule countable_subset)(auto intro: prod.expand rev_image_eqI)\n  have \"?lhs2 = (\\<Sum>\\<^sup>+ x\\<in>{x. (x, y) \\<in> support_flow (Sup Y)}. SUP f\\<in>Y. f (x, y))\"\n    by(subst d_IN_alt_def2; simp)\n  also have \"\\<dots> = (SUP f\\<in>Y. \\<Sum>\\<^sup>+ x\\<in>{x. (x, y) \\<in> support_flow (Sup Y)}. f (x, y))\" using Y\n    by(rule nn_integral_monotone_convergence_SUP_countable)(simp_all add: chain'' countable'')\n  also have \"\\<dots> = ?rhs2\" unfolding d_IN_alt_def2\n    by(auto 4 3 simp add: support_flow_Sup max_def nn_integral_count_space_indicator intro!: nn_integral_cong SUP_cong split: split_indicator dest: not_in_support_flowD)\n  finally show ?IN .\n\n  show ?SINK by(rule set_eqI)(simp add: SINK.simps out Y bot_ennreal[symmetric])\nqed\n\nlemma\n  assumes chain: \"Complete_Partial_Order.chain (\\<le>) Y\"\n  and Y: \"Y \\<noteq> {}\"\n  and countable: \"countable (support_flow f)\"\n  and bounded: \"\\<And>g e. g \\<in> Y \\<Longrightarrow> g e \\<le> f e\"\n  shows d_OUT_Inf: \"d_OUT f x \\<noteq> top \\<Longrightarrow> d_OUT (Inf Y) x = (INF g\\<in>Y. d_OUT g x)\" (is \"_ \\<Longrightarrow> ?OUT\" is \"_ \\<Longrightarrow> ?lhs1 = ?rhs1\")\n  and d_IN_Inf: \"d_IN f x \\<noteq> top \\<Longrightarrow> d_IN (Inf Y) x = (INF g\\<in>Y. d_IN g x)\" (is \"_ \\<Longrightarrow> ?IN\" is \"_ \\<Longrightarrow> ?lhs2 = ?rhs2\")\nproof -\n  text \\<open>We take a detour here via suprema because we have more theorems about @{const nn_integral}\n    with suprema than with infinma.\\<close>\n\n  from Y obtain g0 where g0: \"g0 \\<in> Y\" by auto\n  have g0_le_f: \"g0 e \\<le> f e\" for e by(rule bounded[OF g0])\n\n  have \"support_flow (SUP g\\<in>Y. (\\<lambda>e. f e - g e)) \\<subseteq> support_flow f\"\n    by(clarsimp simp add: support_flow.simps less_SUP_iff elim!: less_le_trans intro!: diff_le_self_ennreal)\n  then have countable': \"countable (support_flow (SUP g\\<in>Y. (\\<lambda>e. f e - g e)))\" by(rule countable_subset)(rule countable)\n\n  have \"Complete_Partial_Order.chain (\\<ge>) Y\" using chain by(simp add: chain_dual)\n  hence chain': \"Complete_Partial_Order.chain (\\<le>) ((\\<lambda>g e. f e - g e) ` Y)\"\n    by(rule chain_imageI)(auto simp add: le_fun_def intro: ennreal_minus_mono)\n\n  { assume finite: \"d_OUT f x \\<noteq> top\"\n    have finite' [simp]: \"f (x, y) \\<noteq> \\<top>\" for y using finite\n      by(rule neq_top_trans) (rule d_OUT_ge_point)\n\n    have finite'_g: \"g (x, y) \\<noteq> \\<top>\" if \"g \\<in> Y\" for g y using finite'[of y]\n      by(rule neq_top_trans)(rule bounded[OF that])\n\n    have finite1: \"(\\<Sum>\\<^sup>+ y. f (x, y) - (INF g\\<in>Y. g (x, y))) \\<noteq> top\"\n      using finite by(rule neq_top_trans)(auto simp add: d_OUT_def intro!: nn_integral_mono)\n    have finite2: \"d_OUT g x \\<noteq> top\" if \"g \\<in> Y\" for g using finite\n      by(rule neq_top_trans)(auto intro: d_OUT_mono bounded[OF that])\n\n    have bounded1: \"(\\<Sqinter>g\\<in>Y. d_OUT g x) \\<le> d_OUT f x\"\n      using Y by (blast intro: INF_lower2 d_OUT_mono bounded)\n\n    have \"?lhs1 = (\\<Sum>\\<^sup>+ y. INF g\\<in>Y. g (x, y))\" by(simp add: d_OUT_def)\n    also have \"\\<dots> = d_OUT f x - (\\<Sum>\\<^sup>+ y. f (x, y) - (INF g\\<in>Y. g (x, y)))\" unfolding d_OUT_def\n      using finite1 g0_le_f\n      apply(subst nn_integral_diff[symmetric])\n      apply(auto simp add: AE_count_space intro!: diff_le_self_ennreal INF_lower2[OF g0] nn_integral_cong diff_diff_ennreal[symmetric])\n      done\n    also have \"(\\<Sum>\\<^sup>+ y. f (x, y) - (INF g\\<in>Y. g (x, y))) = d_OUT (\\<lambda>e. SUP g\\<in>Y. f e - g e) x\"\n      unfolding d_OUT_def by(subst SUP_const_minus_ennreal)(simp_all add: Y)\n    also have \"\\<dots> = (SUP h\\<in>(\\<lambda>g e. f e - g e) ` Y. d_OUT h x)\" using countable' chain' Y\n      by(subst d_OUT_Sup[symmetric])(simp_all add: SUP_apply[abs_def])\n    also have \"\\<dots> = (SUP g\\<in>Y. d_OUT (\\<lambda>e. f e - g e) x)\" unfolding image_image ..\n    also have \"\\<dots> = (SUP g\\<in>Y. d_OUT f x - d_OUT g x)\"\n      by(rule SUP_cong[OF refl] d_OUT_diff)+(auto intro: bounded simp add: finite2)\n    also have \"\\<dots> = d_OUT f x - ?rhs1\" by(subst SUP_const_minus_ennreal)(simp_all add: Y)\n    also have \"d_OUT f x - \\<dots> = ?rhs1\"\n      using Y by(subst diff_diff_ennreal)(simp_all add: bounded1 finite)\n    finally show ?OUT .\n  next\n    assume finite: \"d_IN f x \\<noteq> top\"\n    have finite' [simp]: \"f (y, x) \\<noteq> \\<top>\" for y using finite\n      by(rule neq_top_trans) (rule d_IN_ge_point)\n\n    have finite'_g: \"g (y, x) \\<noteq> \\<top>\" if \"g \\<in> Y\" for g y using finite'[of y]\n      by(rule neq_top_trans)(rule bounded[OF that])\n\n    have finite1: \"(\\<Sum>\\<^sup>+ y. f (y, x) - (INF g\\<in>Y. g (y, x))) \\<noteq> top\"\n      using finite by(rule neq_top_trans)(auto simp add: d_IN_def diff_le_self_ennreal intro!: nn_integral_mono)\n    have finite2: \"d_IN g x \\<noteq> top\" if \"g \\<in> Y\" for g using finite\n      by(rule neq_top_trans)(auto intro: d_IN_mono bounded[OF that])\n\n    have bounded1: \"(\\<Sqinter>g\\<in>Y. d_IN g x) \\<le> d_IN f x\"\n      using Y by (blast intro: INF_lower2 d_IN_mono bounded)\n\n    have \"?lhs2 = (\\<Sum>\\<^sup>+ y. INF g\\<in>Y. g (y, x))\" by(simp add: d_IN_def)\n    also have \"\\<dots> = d_IN f x - (\\<Sum>\\<^sup>+ y. f (y, x) - (INF g\\<in>Y. g (y, x)))\" unfolding d_IN_def\n      using finite1 g0_le_f\n      apply(subst nn_integral_diff[symmetric])\n      apply(auto simp add: AE_count_space intro!: diff_le_self_ennreal INF_lower2[OF g0] nn_integral_cong diff_diff_ennreal[symmetric])\n      done\n    also have \"(\\<Sum>\\<^sup>+ y. f (y, x) - (INF g\\<in>Y. g (y, x))) = d_IN (\\<lambda>e. SUP g\\<in>Y. f e - g e) x\"\n      unfolding d_IN_def by(subst SUP_const_minus_ennreal)(simp_all add: Y)\n    also have \"\\<dots> = (SUP h\\<in>(\\<lambda>g e. f e - g e) ` Y. d_IN h x)\" using countable' chain' Y\n      by(subst d_IN_Sup[symmetric])(simp_all add: SUP_apply[abs_def])\n    also have \"\\<dots> = (SUP g\\<in>Y. d_IN (\\<lambda>e. f e - g e) x)\" unfolding image_image ..\n    also have \"\\<dots> = (SUP g\\<in>Y. d_IN f x - d_IN g x)\"\n      by(rule SUP_cong[OF refl] d_IN_diff)+(auto intro: bounded simp add: finite2)\n    also have \"\\<dots> = d_IN f x - ?rhs2\" by(subst SUP_const_minus_ennreal)(simp_all add: Y)\n    also have \"d_IN f x - \\<dots> = ?rhs2\"\n      by(subst diff_diff_ennreal)(simp_all add: finite bounded1)\n    finally show ?IN . }\nqed\n\ninductive flow :: \"('v, 'more) network_scheme \\<Rightarrow> 'v flow \\<Rightarrow> bool\"\n  for \\<Delta> (structure) and f\nwhere\n  flow: \"\\<lbrakk> \\<And>e. f e \\<le> capacity \\<Delta> e;\n     \\<And>x. \\<lbrakk> x \\<noteq> source \\<Delta>; x \\<noteq> sink \\<Delta> \\<rbrakk> \\<Longrightarrow> KIR f x \\<rbrakk>\n  \\<Longrightarrow> flow \\<Delta> f\"\n\nlemma flowD_capacity: \"flow \\<Delta> f \\<Longrightarrow> f e \\<le> capacity \\<Delta> e\"\nby(cases e)(simp add: flow.simps)\n\nlemma flowD_KIR: \"\\<lbrakk> flow \\<Delta> f; x \\<noteq> source \\<Delta>; x \\<noteq> sink \\<Delta> \\<rbrakk> \\<Longrightarrow> KIR f x\"\nby(simp add: flow.simps)\n\nlemma flowD_capacity_OUT: \"flow \\<Delta> f \\<Longrightarrow> d_OUT f x \\<le> d_OUT (capacity \\<Delta>) x\"\nby(rule d_OUT_mono)(erule flowD_capacity)\n\nlemma flowD_capacity_IN: \"flow \\<Delta> f \\<Longrightarrow> d_IN f x \\<le> d_IN (capacity \\<Delta>) x\"\nby(rule d_IN_mono)(erule flowD_capacity)\n\nabbreviation value_flow :: \"('v, 'more) network_scheme \\<Rightarrow> ('v edge \\<Rightarrow> ennreal) \\<Rightarrow> ennreal\"\nwhere \"value_flow \\<Delta> f \\<equiv> d_OUT f (source \\<Delta>)\"\n\nsubsection \\<open>Cut\\<close>\n\ntype_synonym 'v cut = \"'v set\"\n\ninductive cut :: \"('v, 'more) network_scheme \\<Rightarrow> 'v cut \\<Rightarrow> bool\"\n  for \\<Delta> and S\nwhere cut: \"\\<lbrakk> source \\<Delta> \\<in> S; sink \\<Delta> \\<notin> S \\<rbrakk> \\<Longrightarrow> cut \\<Delta> S\"\n\ninductive orthogonal :: \"('v, 'more) network_scheme \\<Rightarrow> 'v flow \\<Rightarrow> 'v cut \\<Rightarrow> bool\"\n  for \\<Delta> f S\nwhere\n  \"\\<lbrakk> \\<And>x y. \\<lbrakk> edge \\<Delta> x y; x \\<in> S; y \\<notin> S \\<rbrakk> \\<Longrightarrow> f (x, y) = capacity \\<Delta> (x, y);\n     \\<And>x y. \\<lbrakk> edge \\<Delta> x y; x \\<notin> S; y \\<in> S \\<rbrakk> \\<Longrightarrow> f (x, y) = 0 \\<rbrakk>\n  \\<Longrightarrow> orthogonal \\<Delta> f S\"\n\nlemma orthogonalD_out:\n  \"\\<lbrakk> orthogonal \\<Delta> f S; edge \\<Delta> x y; x \\<in> S; y \\<notin> S \\<rbrakk> \\<Longrightarrow> f (x, y) = capacity \\<Delta> (x, y)\"\nby(simp add: orthogonal.simps)\n\nlemma orthogonalD_in:\n  \"\\<lbrakk> orthogonal \\<Delta> f S; edge \\<Delta> x y; x \\<notin> S; y \\<in> S \\<rbrakk> \\<Longrightarrow> f (x, y) = 0\"\nby(simp add: orthogonal.simps)\n\n\n\nsubsection \\<open>Countable network\\<close>\n\nlocale countable_network =\n  fixes \\<Delta> :: \"('v, 'more) network_scheme\" (structure)\n  assumes countable_E [simp]: \"countable \\<^bold>E\"\n  and source_neq_sink [simp]: \"source \\<Delta> \\<noteq> sink \\<Delta>\"\n  and capacity_outside: \"e \\<notin> \\<^bold>E \\<Longrightarrow> capacity \\<Delta> e = 0\"\n  and capacity_finite [simp]: \"capacity \\<Delta> e \\<noteq> \\<top>\"\nbegin\n\nlemma sink_neq_source [simp]: \"sink \\<Delta> \\<noteq> source \\<Delta>\"\nusing source_neq_sink[symmetric] .\n\nlemma countable_V [simp]: \"countable \\<^bold>V\"\nunfolding \"\\<^bold>V_def\" using countable_E by auto\n\nlemma flowD_outside:\n  assumes g: \"flow \\<Delta> g\"\n  shows \"e \\<notin> \\<^bold>E \\<Longrightarrow> g e = 0\"\nusing flowD_capacity[OF g, of e] capacity_outside[of e] by simp\n\nlemma flowD_finite:\n  assumes \"flow \\<Delta> g\"\n  shows \"g e \\<noteq> \\<top>\"\nusing flowD_capacity[OF assms, of e] by (auto simp: top_unique)\n\nlemma zero_flow [simp]: \"flow \\<Delta> (\\<lambda>_. 0)\"\nby(rule flow.intros) simp_all\n\nend\n\nsubsection \\<open>Reduction for avoiding antiparallel edges\\<close>\n\nlocale antiparallel_edges = countable_network \\<Delta>\n  for \\<Delta> :: \"('v, 'more) network_scheme\" (structure)\nbegin\n\ntext \\<open>We eliminate the assumption of antiparallel edges by adding a vertex for every edge.\n  Thus, antiparallel edges are split up into a cycle of 4 edges. This idea already appears in\n  \\<^cite>\\<open>Aharoni1983EJC\\<close>.\\<close>\n\ndatatype (plugins del: transfer size) 'v' vertex = Vertex 'v' | Edge 'v' 'v'\n\ninductive edg :: \"'v vertex \\<Rightarrow> 'v vertex \\<Rightarrow> bool\"\nwhere\n  OUT: \"edge \\<Delta> x y \\<Longrightarrow> edg (Vertex x) (Edge x y)\"\n| IN: \"edge \\<Delta> x y \\<Longrightarrow> edg (Edge x y) (Vertex y)\"\n\ninductive_simps edg_simps [simp]:\n  \"edg (Vertex x) v\"\n  \"edg (Edge x y) v\"\n  \"edg v (Vertex x)\"\n  \"edg v (Edge x y)\"\n\nfun split :: \"'v flow \\<Rightarrow> 'v vertex flow\"\nwhere\n  \"split f (Vertex x, Edge x' y) = (if x' = x then f (x, y) else 0)\"\n| \"split f (Edge x y', Vertex y) = (if y' = y then f (x, y) else 0)\"\n| \"split f _ = 0\"\n\nlemma split_Vertex1_eq_0I: \"(\\<And>z. y \\<noteq> Edge x z) \\<Longrightarrow> split f (Vertex x, y) = 0\"\nby(cases y) auto\n\nlemma split_Vertex2_eq_0I: \"(\\<And>z. y \\<noteq> Edge z x) \\<Longrightarrow> split f (y, Vertex x) = 0\"\nby(cases y) simp_all\n\nlemma split_Edge1_eq_0I: \"(\\<And>z. y \\<noteq> Vertex x) \\<Longrightarrow> split f (Edge z x, y) = 0\"\nby(cases y) simp_all\n\nlemma split_Edge2_eq_0I: \"(\\<And>z. y \\<noteq> Vertex x) \\<Longrightarrow> split f (y, Edge x z) = 0\"\nby(cases y) simp_all\n\ndefinition \\<Delta>'' :: \"'v vertex network\"\nwhere \"\\<Delta>'' = \\<lparr>edge = edg, capacity = split (capacity \\<Delta>), source = Vertex (source \\<Delta>), sink = Vertex (sink \\<Delta>)\\<rparr>\"\n\nlemma \\<Delta>''_sel [simp]:\n  \"edge \\<Delta>'' = edg\"\n  \"capacity \\<Delta>'' = split (capacity \\<Delta>)\"\n  \"source \\<Delta>'' = Vertex (source \\<Delta>)\"\n  \"sink \\<Delta>'' = Vertex (sink \\<Delta>)\"\nby(simp_all add: \\<Delta>''_def)\n\nlemma \"\\<^bold>E_\\<Delta>''\": \"\\<^bold>E\\<^bsub>\\<Delta>''\\<^esub> = (\\<lambda>(x, y). (Vertex x, Edge x y)) ` \\<^bold>E \\<union> (\\<lambda>(x, y). (Edge x y, Vertex y)) ` \\<^bold>E\"\nby(auto elim: edg.cases)\n\nlemma \"\\<^bold>V_\\<Delta>''\": \"\\<^bold>V\\<^bsub>\\<Delta>''\\<^esub> = Vertex ` \\<^bold>V \\<union> case_prod Edge ` \\<^bold>E\"\nby(auto 4 4 simp add: vertex_def elim!: edg.cases)\n\nlemma inj_on_Edge1 [simp]: \"inj_on (\\<lambda>x. Edge x y) A\"\nby(simp add: inj_on_def)\n\nlemma inj_on_Edge2 [simp]: \"inj_on (Edge x) A\"\nby(simp add: inj_on_def)\n\nlemma d_IN_split_Vertex [simp]: \"d_IN (split f) (Vertex x) = d_IN f x\" (is \"?lhs = ?rhs\")\nproof(rule trans)\n  show \"?lhs = (\\<Sum>\\<^sup>+ v'\\<in>range (\\<lambda>y. Edge y x). split f (v', Vertex x))\"\n    by(auto intro!: nn_integral_cong split_Vertex2_eq_0I simp add: d_IN_def nn_integral_count_space_indicator split: split_indicator)\n  show \"\\<dots> = ?rhs\" by(simp add: nn_integral_count_space_reindex d_IN_def)\nqed\n\nlemma d_OUT_split_Vertex [simp]: \"d_OUT (split f) (Vertex x) = d_OUT f x\" (is \"?lhs = ?rhs\")\nproof(rule trans)\n  show \"?lhs = (\\<Sum>\\<^sup>+ v'\\<in>range (Edge x). split f (Vertex x, v'))\"\n    by(auto intro!: nn_integral_cong split_Vertex1_eq_0I simp add: d_OUT_def nn_integral_count_space_indicator split: split_indicator)\n  show \"\\<dots> = ?rhs\" by(simp add: nn_integral_count_space_reindex d_OUT_def)\nqed\n\nlemma d_IN_split_Edge [simp]: \"d_IN (split f) (Edge x y) = max 0 (f (x, y))\" (is \"?lhs = ?rhs\")\nproof(rule trans)\n  show \"?lhs = (\\<Sum>\\<^sup>+ v'. split f (v', Edge x y) * indicator {Vertex x} v')\"\n    unfolding d_IN_def by(rule nn_integral_cong)(simp add: split_Edge2_eq_0I split: split_indicator)\n  show \"\\<dots> = ?rhs\" by(simp add: max_def)\nqed\n\nlemma d_OUT_split_Edge [simp]: \"d_OUT (split f) (Edge x y) = max 0 (f (x, y))\" (is \"?lhs = ?rhs\")\nproof(rule trans)\n  show \"?lhs = (\\<Sum>\\<^sup>+ v'. split f (Edge x y, v') * indicator {Vertex y} v')\"\n    unfolding d_OUT_def by(rule nn_integral_cong)(simp add: split_Edge1_eq_0I split: split_indicator)\n  show \"\\<dots> = ?rhs\" by(simp add: max_def)\nqed\n\nlemma \\<Delta>''_countable_network: \"countable_network \\<Delta>''\"\nproof\n  show \"countable \\<^bold>E\\<^bsub>\\<Delta>''\\<^esub>\" unfolding \"\\<^bold>E_\\<Delta>''\" by(simp)\n  show \"source \\<Delta>'' \\<noteq> sink \\<Delta>''\" by auto\n  show \"capacity \\<Delta>'' e = 0\" if \"e \\<notin> \\<^bold>E\\<^bsub>\\<Delta>''\\<^esub>\" for e using that\n    by(cases \"(capacity \\<Delta>, e)\" rule: split.cases)(auto simp add: capacity_outside)\n  show \"capacity \\<Delta>'' e \\<noteq> top\" for e by(cases \"(capacity \\<Delta>, e)\" rule: split.cases)(auto)\nqed\n\ninterpretation \\<Delta>'': countable_network \\<Delta>'' by(rule \\<Delta>''_countable_network)\n\nlemma flow_split [simp]:\n  assumes \"flow \\<Delta> f\"\n  shows \"flow \\<Delta>'' (split f)\"\nproof\n  show \"split f e \\<le> capacity \\<Delta>'' e\" for e\n    by(cases \"(f, e)\" rule: split.cases)(auto intro: flowD_capacity[OF assms] intro: SUP_upper2 assms)\n  show \"KIR (split f) x\" if \"x \\<noteq> source \\<Delta>''\" \"x \\<noteq> sink \\<Delta>''\" for x\n    using that by(cases \"x\")(auto dest: flowD_KIR[OF assms])\nqed\n\nabbreviation (input) collect :: \"'v vertex flow \\<Rightarrow> 'v flow\"\nwhere \"collect f \\<equiv> (\\<lambda>(x, y). f (Edge x y, Vertex y))\"\n\nlemma d_OUT_collect:\n  assumes f: \"flow \\<Delta>'' f\"\n  shows \"d_OUT (collect f) x = d_OUT f (Vertex x)\"\nproof -\n  have \"d_OUT (collect f) x = (\\<Sum>\\<^sup>+ y. f (Edge x y, Vertex y))\"\n    by(simp add: nn_integral_count_space_reindex d_OUT_def)\n  also have \"\\<dots> = (\\<Sum>\\<^sup>+ y\\<in>range (Edge x). f (Vertex x, y))\"\n  proof(clarsimp simp add: nn_integral_count_space_reindex intro!: nn_integral_cong)\n    fix y\n    have \"(\\<Sum>\\<^sup>+ z. f (Edge x y, z) * indicator {Vertex y} z) = d_OUT f (Edge x y)\"\n      unfolding d_OUT_def by(rule nn_integral_cong)(simp split: split_indicator add: \\<Delta>''.flowD_outside[OF f])\n    also have \"\\<dots> = d_IN f (Edge x y)\" using f by(rule flowD_KIR) simp_all\n    also have \"\\<dots> = (\\<Sum>\\<^sup>+ z. f (z, Edge x y) * indicator {Vertex x} z)\"\n      unfolding d_IN_def by(rule nn_integral_cong)(simp split: split_indicator add: \\<Delta>''.flowD_outside[OF f])\n    finally show \"f (Edge x y, Vertex y) = f (Vertex x, Edge x y)\"\n      by(simp add: max_def)\n  qed\n  also have \"\\<dots> = d_OUT f (Vertex x)\"\n    by(auto intro!: nn_integral_cong \\<Delta>''.flowD_outside[OF f] simp add: nn_integral_count_space_indicator d_OUT_def split: split_indicator)\n  finally show ?thesis .\nqed\n\nlemma flow_collect [simp]:\n  assumes f: \"flow \\<Delta>'' f\"\n  shows \"flow \\<Delta> (collect f)\"\nproof\n  show \"collect f e \\<le> capacity \\<Delta> e\" for e using flowD_capacity[OF f, of \"(case_prod Edge e, Vertex (snd e))\"]\n    by(cases e)(simp)\n\n  fix x\n  assume x: \"x \\<noteq> source \\<Delta>\" \"x \\<noteq> sink \\<Delta>\"\n  have \"d_OUT (collect f) x = d_OUT f (Vertex x)\" using f by(rule d_OUT_collect)\n  also have \"\\<dots> = d_IN f (Vertex x)\" using x flowD_KIR[OF f, of \"Vertex x\"] by(simp)\n  also have \"\\<dots> = (\\<Sum>\\<^sup>+ y\\<in>range (\\<lambda>z. Edge z x). f (y, Vertex x))\"\n    by(auto intro!: nn_integral_cong \\<Delta>''.flowD_outside[OF f] simp add: nn_integral_count_space_indicator d_IN_def split: split_indicator)\n  also have \"\\<dots> = d_IN (collect f) x\" by(simp add: nn_integral_count_space_reindex d_IN_def)\n  finally show \"KIR (collect f) x\" .\nqed\n\nlemma value_collect: \"flow \\<Delta>'' f \\<Longrightarrow> value_flow \\<Delta> (collect f) = value_flow \\<Delta>'' f\"\nby(simp add: d_OUT_collect)\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/MFMC_Countable/MFMC_Network.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8856314798554445, "lm_q2_score": 0.8031737987125612, "lm_q1q2_score": 0.7113159999349246}}
{"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_QSortPermutes\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 lt :: \"Nat => Nat => bool\" where\n  \"lt y (Z) = False\"\n| \"lt (Z) (S z2) = True\"\n| \"lt (S n) (S z2) = lt n z2\"\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 gt :: \"Nat => Nat => bool\" where\n  \"gt y z = lt z y\"\n\nfun filter :: \"('a => bool) => 'a list => 'a list\" where\n  \"filter q (nil2) = nil2\"\n| \"filter q (cons2 z xs) =\n     (if q z then cons2 z (filter q xs) else filter q xs)\"\n\n(*fun did not finish the proof*)\nfunction qsort :: \"Nat list => Nat list\" where\n  \"qsort (nil2) = nil2\"\n| \"qsort (cons2 z xs) =\n     x (qsort (filter (% (z2 :: Nat) => le z2 z) xs))\n       (x (cons2 z (nil2))\n          (qsort (filter (% (x2 :: Nat) => gt x2 z) xs)))\"\n  by pat_completeness auto\n\nfun elem :: \"'a => 'a list => bool\" where\n  \"elem y (nil2) = False\"\n| \"elem y (cons2 z2 xs) = ((z2 = y) | (elem y xs))\"\n\nfun deleteBy :: \"('a => ('a => bool)) => 'a => 'a list =>\n                 'a list\" where\n  \"deleteBy y z (nil2) = nil2\"\n| \"deleteBy y z (cons2 y2 ys) =\n     (if (y z) y2 then ys else cons2 y2 (deleteBy y z ys))\"\n\nfun isPermutation :: \"'a list => 'a list => bool\" where\n  \"isPermutation (nil2) (nil2) = True\"\n| \"isPermutation (nil2) (cons2 z2 x2) = False\"\n| \"isPermutation (cons2 x3 xs) z =\n     ((elem x3 z) &\n        (isPermutation\n           xs (deleteBy (% (x4 :: 'a) => % (x5 :: 'a) => (x4 = x5)) x3 z)))\"\n\ntheorem property0 :\n  \"isPermutation (qsort 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_sort_nat_QSortPermutes.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314738181875, "lm_q2_score": 0.8031738034238807, "lm_q1q2_score": 0.7113159992584507}}
{"text": "(*  Title:      CCL/Type.thy\n    Author:     Martin Coen\n    Copyright   1993  University of Cambridge\n*)\n\nsection \\<open>Types in CCL are defined as sets of terms\\<close>\n\ntheory Type\nimports Term\nbegin\n\ndefinition Subtype :: \"['a set, 'a \\<Rightarrow> o] \\<Rightarrow> 'a set\"\n  where \"Subtype(A, P) == {x. x:A \\<and> P(x)}\"\n\nsyntax\n  \"_Subtype\" :: \"[idt, 'a set, o] \\<Rightarrow> 'a set\"  (\"(1{_: _ ./ _})\")\ntranslations\n  \"{x: A. B}\" == \"CONST Subtype(A, \\<lambda>x. B)\"\n\ndefinition Unit :: \"i set\"\n  where \"Unit == {x. x=one}\"\n\ndefinition Bool :: \"i set\"\n  where \"Bool == {x. x=true | x=false}\"\n\ndefinition Plus :: \"[i set, i set] \\<Rightarrow> i set\"  (infixr \"+\" 55)\n  where \"A+B == {x. (EX a:A. x=inl(a)) | (EX b:B. x=inr(b))}\"\n\ndefinition Pi :: \"[i set, i \\<Rightarrow> i set] \\<Rightarrow> i set\"\n  where \"Pi(A,B) == {x. EX b. x=lam x. b(x) \\<and> (ALL x:A. b(x):B(x))}\"\n\ndefinition Sigma :: \"[i set, i \\<Rightarrow> i set] \\<Rightarrow> i set\"\n  where \"Sigma(A,B) == {x. EX a:A. EX b:B(a).x=<a,b>}\"\n\nsyntax\n  \"_Pi\" :: \"[idt, i set, i set] \\<Rightarrow> i set\"  (\"(3PROD _:_./ _)\" [0,0,60] 60)\n  \"_Sigma\" :: \"[idt, i set, i set] \\<Rightarrow> i set\"  (\"(3SUM _:_./ _)\" [0,0,60] 60)\n  \"_arrow\" :: \"[i set, i set] \\<Rightarrow> i set\"  (\"(_ ->/ _)\"  [54, 53] 53)\n  \"_star\"  :: \"[i set, i set] \\<Rightarrow> i set\"  (\"(_ */ _)\" [56, 55] 55)\ntranslations\n  \"PROD x:A. B\" \\<rightharpoonup> \"CONST Pi(A, \\<lambda>x. B)\"\n  \"A -> B\" \\<rightharpoonup> \"CONST Pi(A, \\<lambda>_. B)\"\n  \"SUM x:A. B\" \\<rightharpoonup> \"CONST Sigma(A, \\<lambda>x. B)\"\n  \"A * B\" \\<rightharpoonup> \"CONST Sigma(A, \\<lambda>_. B)\"\nprint_translation \\<open>\n [(@{const_syntax Pi},\n    fn _ => Syntax_Trans.dependent_tr' (@{syntax_const \"_Pi\"}, @{syntax_const \"_arrow\"})),\n  (@{const_syntax Sigma},\n    fn _ => Syntax_Trans.dependent_tr' (@{syntax_const \"_Sigma\"}, @{syntax_const \"_star\"}))]\n\\<close>\n\ndefinition Nat :: \"i set\"\n  where \"Nat == lfp(\\<lambda>X. Unit + X)\"\n\ndefinition List :: \"i set \\<Rightarrow> i set\"\n  where \"List(A) == lfp(\\<lambda>X. Unit + A*X)\"\n\ndefinition Lists :: \"i set \\<Rightarrow> i set\"\n  where \"Lists(A) == gfp(\\<lambda>X. Unit + A*X)\"\n\ndefinition ILists :: \"i set \\<Rightarrow> i set\"\n  where \"ILists(A) == gfp(\\<lambda>X.{} + A*X)\"\n\n\ndefinition TAll :: \"(i set \\<Rightarrow> i set) \\<Rightarrow> i set\"  (binder \"TALL \" 55)\n  where \"TALL X. B(X) == Inter({X. EX Y. X=B(Y)})\"\n\ndefinition TEx :: \"(i set \\<Rightarrow> i set) \\<Rightarrow> i set\"  (binder \"TEX \" 55)\n  where \"TEX X. B(X) == Union({X. EX Y. X=B(Y)})\"\n\ndefinition Lift :: \"i set \\<Rightarrow> i set\"  (\"(3[_])\")\n  where \"[A] == A Un {bot}\"\n\ndefinition SPLIT :: \"[i, [i, i] \\<Rightarrow> i set] \\<Rightarrow> i set\"\n  where \"SPLIT(p,B) == Union({A. EX x y. p=<x,y> \\<and> A=B(x,y)})\"\n\n\nlemmas simp_type_defs =\n    Subtype_def Unit_def Bool_def Plus_def Sigma_def Pi_def Lift_def TAll_def TEx_def\n  and ind_type_defs = Nat_def List_def\n  and simp_data_defs = one_def inl_def inr_def\n  and ind_data_defs = zero_def succ_def nil_def cons_def\n\nlemma subsetXH: \"A <= B \\<longleftrightarrow> (ALL x. x:A \\<longrightarrow> x:B)\"\n  by blast\n\n\nsubsection \\<open>Exhaustion Rules\\<close>\n\nlemma EmptyXH: \"\\<And>a. a : {} \\<longleftrightarrow> False\"\n  and SubtypeXH: \"\\<And>a A P. a : {x:A. P(x)} \\<longleftrightarrow> (a:A \\<and> P(a))\"\n  and UnitXH: \"\\<And>a. a : Unit          \\<longleftrightarrow> a=one\"\n  and BoolXH: \"\\<And>a. a : Bool          \\<longleftrightarrow> a=true | a=false\"\n  and PlusXH: \"\\<And>a A B. a : A+B           \\<longleftrightarrow> (EX x:A. a=inl(x)) | (EX x:B. a=inr(x))\"\n  and PiXH: \"\\<And>a A B. a : PROD x:A. B(x) \\<longleftrightarrow> (EX b. a=lam x. b(x) \\<and> (ALL x:A. b(x):B(x)))\"\n  and SgXH: \"\\<And>a A B. a : SUM x:A. B(x)  \\<longleftrightarrow> (EX x:A. EX y:B(x).a=<x,y>)\"\n  unfolding simp_type_defs by blast+\n\nlemmas XHs = EmptyXH SubtypeXH UnitXH BoolXH PlusXH PiXH SgXH\n\nlemma LiftXH: \"a : [A] \\<longleftrightarrow> (a=bot | a:A)\"\n  and TallXH: \"a : TALL X. B(X) \\<longleftrightarrow> (ALL X. a:B(X))\"\n  and TexXH: \"a : TEX X. B(X) \\<longleftrightarrow> (EX X. a:B(X))\"\n  unfolding simp_type_defs by blast+\n\nML \\<open>ML_Thms.bind_thms (\"case_rls\", XH_to_Es @{thms XHs})\\<close>\n\n\nsubsection \\<open>Canonical Type Rules\\<close>\n\nlemma oneT: \"one : Unit\"\n  and trueT: \"true : Bool\"\n  and falseT: \"false : Bool\"\n  and lamT: \"\\<And>b B. (\\<And>x. x:A \\<Longrightarrow> b(x):B(x)) \\<Longrightarrow> lam x. b(x) : Pi(A,B)\"\n  and pairT: \"\\<And>b B. \\<lbrakk>a:A; b:B(a)\\<rbrakk> \\<Longrightarrow> <a,b>:Sigma(A,B)\"\n  and inlT: \"a:A \\<Longrightarrow> inl(a) : A+B\"\n  and inrT: \"b:B \\<Longrightarrow> inr(b) : A+B\"\n  by (blast intro: XHs [THEN iffD2])+\n\nlemmas canTs = oneT trueT falseT pairT lamT inlT inrT\n\n\nsubsection \\<open>Non-Canonical Type Rules\\<close>\n\nlemma lem: \"\\<lbrakk>a:B(u); u = v\\<rbrakk> \\<Longrightarrow> a : B(v)\"\n  by blast\n\n\nML \\<open>\nfun mk_ncanT_tac top_crls crls =\n  SUBPROOF (fn {context = ctxt, prems = major :: prems, ...} =>\n    resolve_tac ctxt ([major] RL top_crls) 1 THEN\n    REPEAT_SOME (eresolve_tac ctxt (crls @ @{thms exE bexE conjE disjE})) THEN\n    ALLGOALS (asm_simp_tac ctxt) THEN\n    ALLGOALS (assume_tac ctxt ORELSE' resolve_tac ctxt (prems RL [@{thm lem}])\n      ORELSE' eresolve_tac ctxt @{thms bspec}) THEN\n    safe_tac (ctxt addSIs prems))\n\\<close>\n\nmethod_setup ncanT = \\<open>\n  Scan.succeed (SIMPLE_METHOD' o mk_ncanT_tac @{thms case_rls} @{thms case_rls})\n\\<close>\n\nlemma ifT: \"\\<lbrakk>b:Bool; b=true \\<Longrightarrow> t:A(true); b=false \\<Longrightarrow> u:A(false)\\<rbrakk> \\<Longrightarrow> if b then t else u : A(b)\"\n  by ncanT\n\nlemma applyT: \"\\<lbrakk>f : Pi(A,B); a:A\\<rbrakk> \\<Longrightarrow> f ` a : B(a)\"\n  by ncanT\n\nlemma splitT: \"\\<lbrakk>p:Sigma(A,B); \\<And>x y. \\<lbrakk>x:A; y:B(x); p=<x,y>\\<rbrakk> \\<Longrightarrow> c(x,y):C(<x,y>)\\<rbrakk> \\<Longrightarrow> split(p,c):C(p)\"\n  by ncanT\n\nlemma whenT:\n  \"\\<lbrakk>p:A+B;\n    \\<And>x. \\<lbrakk>x:A; p=inl(x)\\<rbrakk> \\<Longrightarrow> a(x):C(inl(x));\n    \\<And>y. \\<lbrakk>y:B;  p=inr(y)\\<rbrakk> \\<Longrightarrow> b(y):C(inr(y))\\<rbrakk> \\<Longrightarrow> when(p,a,b) : C(p)\"\n  by ncanT\n\nlemmas ncanTs = ifT applyT splitT whenT\n\n\nsubsection \\<open>Subtypes\\<close>\n\nlemma SubtypeD1: \"a : Subtype(A, P) \\<Longrightarrow> a : A\"\n  and SubtypeD2: \"a : Subtype(A, P) \\<Longrightarrow> P(a)\"\n  by (simp_all add: SubtypeXH)\n\nlemma SubtypeI: \"\\<lbrakk>a:A; P(a)\\<rbrakk> \\<Longrightarrow> a : {x:A. P(x)}\"\n  by (simp add: SubtypeXH)\n\nlemma SubtypeE: \"\\<lbrakk>a : {x:A. P(x)}; \\<lbrakk>a:A; P(a)\\<rbrakk> \\<Longrightarrow> Q\\<rbrakk> \\<Longrightarrow> Q\"\n  by (simp add: SubtypeXH)\n\n\nsubsection \\<open>Monotonicity\\<close>\n\nlemma idM: \"mono (\\<lambda>X. X)\"\n  apply (rule monoI)\n  apply assumption\n  done\n\nlemma constM: \"mono(\\<lambda>X. A)\"\n  apply (rule monoI)\n  apply (rule subset_refl)\n  done\n\nlemma \"mono(\\<lambda>X. A(X)) \\<Longrightarrow> mono(\\<lambda>X.[A(X)])\"\n  apply (rule subsetI [THEN monoI])\n  apply (drule LiftXH [THEN iffD1])\n  apply (erule disjE)\n   apply (erule disjI1 [THEN LiftXH [THEN iffD2]])\n  apply (rule disjI2 [THEN LiftXH [THEN iffD2]])\n  apply (drule (1) monoD)\n  apply blast\n  done\n\nlemma SgM:\n  \"\\<lbrakk>mono(\\<lambda>X. A(X)); \\<And>x X. x:A(X) \\<Longrightarrow> mono(\\<lambda>X. B(X,x))\\<rbrakk> \\<Longrightarrow>\n    mono(\\<lambda>X. Sigma(A(X),B(X)))\"\n  by (blast intro!: subsetI [THEN monoI] canTs elim!: case_rls\n    dest!: monoD [THEN subsetD])\n\nlemma PiM: \"(\\<And>x. x:A \\<Longrightarrow> mono(\\<lambda>X. B(X,x))) \\<Longrightarrow> mono(\\<lambda>X. Pi(A,B(X)))\"\n  by (blast intro!: subsetI [THEN monoI] canTs elim!: case_rls\n    dest!: monoD [THEN subsetD])\n\nlemma PlusM: \"\\<lbrakk>mono(\\<lambda>X. A(X)); mono(\\<lambda>X. B(X))\\<rbrakk> \\<Longrightarrow> mono(\\<lambda>X. A(X)+B(X))\"\n  by (blast intro!: subsetI [THEN monoI] canTs elim!: case_rls\n    dest!: monoD [THEN subsetD])\n\n\nsubsection \\<open>Recursive types\\<close>\n\nsubsubsection \\<open>Conversion Rules for Fixed Points via monotonicity and Tarski\\<close>\n\nlemma NatM: \"mono(\\<lambda>X. Unit+X)\"\n  apply (rule PlusM constM idM)+\n  done\n\nlemma def_NatB: \"Nat = Unit + Nat\"\n  apply (rule def_lfp_Tarski [OF Nat_def])\n  apply (rule NatM)\n  done\n\nlemma ListM: \"mono(\\<lambda>X.(Unit+Sigma(A,\\<lambda>y. X)))\"\n  apply (rule PlusM SgM constM idM)+\n  done\n\nlemma def_ListB: \"List(A) = Unit + A * List(A)\"\n  apply (rule def_lfp_Tarski [OF List_def])\n  apply (rule ListM)\n  done\n\nlemma def_ListsB: \"Lists(A) = Unit + A * Lists(A)\"\n  apply (rule def_gfp_Tarski [OF Lists_def])\n  apply (rule ListM)\n  done\n\nlemma IListsM: \"mono(\\<lambda>X.({} + Sigma(A,\\<lambda>y. X)))\"\n  apply (rule PlusM SgM constM idM)+\n  done\n\nlemma def_IListsB: \"ILists(A) = {} + A * ILists(A)\"\n  apply (rule def_gfp_Tarski [OF ILists_def])\n  apply (rule IListsM)\n  done\n\nlemmas ind_type_eqs = def_NatB def_ListB def_ListsB def_IListsB\n\n\nsubsection \\<open>Exhaustion Rules\\<close>\n\nlemma NatXH: \"a : Nat \\<longleftrightarrow> (a=zero | (EX x:Nat. a=succ(x)))\"\n  and ListXH: \"a : List(A) \\<longleftrightarrow> (a=[] | (EX x:A. EX xs:List(A).a=x$xs))\"\n  and ListsXH: \"a : Lists(A) \\<longleftrightarrow> (a=[] | (EX x:A. EX xs:Lists(A).a=x$xs))\"\n  and IListsXH: \"a : ILists(A) \\<longleftrightarrow> (EX x:A. EX xs:ILists(A).a=x$xs)\"\n  unfolding ind_data_defs\n  by (rule ind_type_eqs [THEN XHlemma1], blast intro!: canTs elim!: case_rls)+\n\nlemmas iXHs = NatXH ListXH\n\nML \\<open>ML_Thms.bind_thms (\"icase_rls\", XH_to_Es @{thms iXHs})\\<close>\n\n\nsubsection \\<open>Type Rules\\<close>\n\nlemma zeroT: \"zero : Nat\"\n  and succT: \"n:Nat \\<Longrightarrow> succ(n) : Nat\"\n  and nilT: \"[] : List(A)\"\n  and consT: \"\\<lbrakk>h:A; t:List(A)\\<rbrakk> \\<Longrightarrow> h$t : List(A)\"\n  by (blast intro: iXHs [THEN iffD2])+\n\nlemmas icanTs = zeroT succT nilT consT\n\n\nmethod_setup incanT = \\<open>\n  Scan.succeed (SIMPLE_METHOD' o mk_ncanT_tac @{thms icase_rls} @{thms case_rls})\n\\<close>\n\nlemma ncaseT: \"\\<lbrakk>n:Nat; n=zero \\<Longrightarrow> b:C(zero); \\<And>x. \\<lbrakk>x:Nat; n=succ(x)\\<rbrakk> \\<Longrightarrow> c(x):C(succ(x))\\<rbrakk>\n    \\<Longrightarrow> ncase(n,b,c) : C(n)\"\n  by incanT\n\nlemma lcaseT: \"\\<lbrakk>l:List(A); l = [] \\<Longrightarrow> b:C([]); \\<And>h t. \\<lbrakk>h:A; t:List(A); l=h$t\\<rbrakk> \\<Longrightarrow> c(h,t):C(h$t)\\<rbrakk>\n    \\<Longrightarrow> lcase(l,b,c) : C(l)\"\n  by incanT\n\nlemmas incanTs = ncaseT lcaseT\n\n\nsubsection \\<open>Induction Rules\\<close>\n\nlemmas ind_Ms = NatM ListM\n\nlemma Nat_ind: \"\\<lbrakk>n:Nat; P(zero); \\<And>x. \\<lbrakk>x:Nat; P(x)\\<rbrakk> \\<Longrightarrow> P(succ(x))\\<rbrakk> \\<Longrightarrow> P(n)\"\n  apply (unfold ind_data_defs)\n  apply (erule def_induct [OF Nat_def _ NatM])\n  apply (blast intro: canTs elim!: case_rls)\n  done\n\nlemma List_ind: \"\\<lbrakk>l:List(A); P([]); \\<And>x xs. \\<lbrakk>x:A; xs:List(A); P(xs)\\<rbrakk> \\<Longrightarrow> P(x$xs)\\<rbrakk> \\<Longrightarrow> P(l)\"\n  apply (unfold ind_data_defs)\n  apply (erule def_induct [OF List_def _ ListM])\n  apply (blast intro: canTs elim!: case_rls)\n  done\n\nlemmas inds = Nat_ind List_ind\n\n\nsubsection \\<open>Primitive Recursive Rules\\<close>\n\nlemma nrecT: \"\\<lbrakk>n:Nat; b:C(zero); \\<And>x g. \\<lbrakk>x:Nat; g:C(x)\\<rbrakk> \\<Longrightarrow> c(x,g):C(succ(x))\\<rbrakk>\n    \\<Longrightarrow> nrec(n,b,c) : C(n)\"\n  by (erule Nat_ind) auto\n\nlemma lrecT: \"\\<lbrakk>l:List(A); b:C([]); \\<And>x xs g. \\<lbrakk>x:A; xs:List(A); g:C(xs)\\<rbrakk> \\<Longrightarrow> c(x,xs,g):C(x$xs) \\<rbrakk>\n    \\<Longrightarrow> lrec(l,b,c) : C(l)\"\n  by (erule List_ind) auto\n\nlemmas precTs = nrecT lrecT\n\n\nsubsection \\<open>Theorem proving\\<close>\n\nlemma SgE2: \"\\<lbrakk><a,b> : Sigma(A,B); \\<lbrakk>a:A; b:B(a)\\<rbrakk> \\<Longrightarrow> P\\<rbrakk> \\<Longrightarrow> P\"\n  unfolding SgXH by blast\n\n(* General theorem proving ignores non-canonical term-formers,             *)\n(*         - intro rules are type rules for canonical terms                *)\n(*         - elim rules are case rules (no non-canonical terms appear)     *)\n\nML \\<open>ML_Thms.bind_thms (\"XHEs\", XH_to_Es @{thms XHs})\\<close>\n\nlemmas [intro!] = SubtypeI canTs icanTs\n  and [elim!] = SubtypeE XHEs\n\n\nsubsection \\<open>Infinite Data Types\\<close>\n\nlemma lfp_subset_gfp: \"mono(f) \\<Longrightarrow> lfp(f) <= gfp(f)\"\n  apply (rule lfp_lowerbound [THEN subset_trans])\n   apply (erule gfp_lemma3)\n  apply (rule subset_refl)\n  done\n\nlemma gfpI:\n  assumes \"a:A\"\n    and \"\\<And>x X. \\<lbrakk>x:A; ALL y:A. t(y):X\\<rbrakk> \\<Longrightarrow> t(x) : B(X)\"\n  shows \"t(a) : gfp(B)\"\n  apply (rule coinduct)\n   apply (rule_tac P = \"\\<lambda>x. EX y:A. x=t (y)\" in CollectI)\n   apply (blast intro!: assms)+\n  done\n\nlemma def_gfpI: \"\\<lbrakk>C == gfp(B); a:A; \\<And>x X. \\<lbrakk>x:A; ALL y:A. t(y):X\\<rbrakk> \\<Longrightarrow> t(x) : B(X)\\<rbrakk> \\<Longrightarrow> t(a) : C\"\n  apply unfold\n  apply (erule gfpI)\n  apply blast\n  done\n\n(* EG *)\nlemma \"letrec g x be zero$g(x) in g(bot) : Lists(Nat)\"\n  apply (rule refl [THEN UnitXH [THEN iffD2], THEN Lists_def [THEN def_gfpI]])\n  apply (subst letrecB)\n  apply (unfold cons_def)\n  apply blast\n  done\n\n\nsubsection \\<open>Lemmas and tactics for using the rule \\<open>coinduct3\\<close> on \\<open>[=\\<close> and \\<open>=\\<close>\\<close>\n\nlemma lfpI: \"\\<lbrakk>mono(f); a : f(lfp(f))\\<rbrakk> \\<Longrightarrow> a : lfp(f)\"\n  apply (erule lfp_Tarski [THEN ssubst])\n  apply assumption\n  done\n\nlemma ssubst_single: \"\\<lbrakk>a = a'; a' : A\\<rbrakk> \\<Longrightarrow> a : A\"\n  by simp\n\nlemma ssubst_pair: \"\\<lbrakk>a = a'; b = b'; <a',b'> : A\\<rbrakk> \\<Longrightarrow> <a,b> : A\"\n  by simp\n\n\nML \\<open>\n  val coinduct3_tac = SUBPROOF (fn {context = ctxt, prems = mono :: prems, ...} =>\n    fast_tac (ctxt addIs (mono RS @{thm coinduct3_mono_lemma} RS @{thm lfpI}) :: prems) 1);\n\\<close>\n\nmethod_setup coinduct3 = \\<open>Scan.succeed (SIMPLE_METHOD' o coinduct3_tac)\\<close>\n\nlemma ci3_RI: \"\\<lbrakk>mono(Agen); a : R\\<rbrakk> \\<Longrightarrow> a : lfp(\\<lambda>x. Agen(x) Un R Un A)\"\n  by coinduct3\n\nlemma ci3_AgenI: \"\\<lbrakk>mono(Agen); a : Agen(lfp(\\<lambda>x. Agen(x) Un R Un A))\\<rbrakk> \\<Longrightarrow>\n    a : lfp(\\<lambda>x. Agen(x) Un R Un A)\"\n  by coinduct3\n\nlemma ci3_AI: \"\\<lbrakk>mono(Agen); a : A\\<rbrakk> \\<Longrightarrow> a : lfp(\\<lambda>x. Agen(x) Un R Un A)\"\n  by coinduct3\n\nML \\<open>\nfun genIs_tac ctxt genXH gen_mono =\n  resolve_tac ctxt [genXH RS @{thm iffD2}] THEN'\n  simp_tac ctxt THEN'\n  TRY o fast_tac\n    (ctxt addIs [genXH RS @{thm iffD2}, gen_mono RS @{thm coinduct3_mono_lemma} RS @{thm lfpI}])\n\\<close>\n\nmethod_setup genIs = \\<open>\n  Attrib.thm -- Attrib.thm >>\n    (fn (genXH, gen_mono) => fn ctxt => SIMPLE_METHOD' (genIs_tac ctxt genXH gen_mono))\n\\<close>\n\n\nsubsection \\<open>POgen\\<close>\n\nlemma PO_refl: \"<a,a> : PO\"\n  by (rule po_refl [THEN PO_iff [THEN iffD1]])\n\nlemma POgenIs:\n  \"<true,true> : POgen(R)\"\n  \"<false,false> : POgen(R)\"\n  \"\\<lbrakk><a,a'> : R; <b,b'> : R\\<rbrakk> \\<Longrightarrow> <<a,b>,<a',b'>> : POgen(R)\"\n  \"\\<And>b b'. (\\<And>x. <b(x),b'(x)> : R) \\<Longrightarrow> <lam x. b(x),lam x. b'(x)> : POgen(R)\"\n  \"<one,one> : POgen(R)\"\n  \"<a,a'> : lfp(\\<lambda>x. POgen(x) Un R Un PO) \\<Longrightarrow>\n    <inl(a),inl(a')> : POgen(lfp(\\<lambda>x. POgen(x) Un R Un PO))\"\n  \"<b,b'> : lfp(\\<lambda>x. POgen(x) Un R Un PO) \\<Longrightarrow>\n    <inr(b),inr(b')> : POgen(lfp(\\<lambda>x. POgen(x) Un R Un PO))\"\n  \"<zero,zero> : POgen(lfp(\\<lambda>x. POgen(x) Un R Un PO))\"\n  \"<n,n'> : lfp(\\<lambda>x. POgen(x) Un R Un PO) \\<Longrightarrow>\n    <succ(n),succ(n')> : POgen(lfp(\\<lambda>x. POgen(x) Un R Un PO))\"\n  \"<[],[]> : POgen(lfp(\\<lambda>x. POgen(x) Un R Un PO))\"\n  \"\\<lbrakk><h,h'> : lfp(\\<lambda>x. POgen(x) Un R Un PO);  <t,t'> : lfp(\\<lambda>x. POgen(x) Un R Un PO)\\<rbrakk>\n    \\<Longrightarrow> <h$t,h'$t'> : POgen(lfp(\\<lambda>x. POgen(x) Un R Un PO))\"\n  unfolding data_defs by (genIs POgenXH POgen_mono)+\n\nML \\<open>\nfun POgen_tac ctxt (rla, rlb) i =\n  SELECT_GOAL (safe_tac ctxt) i THEN\n  resolve_tac ctxt [rlb RS (rla RS @{thm ssubst_pair})] i THEN\n  (REPEAT (resolve_tac ctxt\n      (@{thms POgenIs} @ [@{thm PO_refl} RS (@{thm POgen_mono} RS @{thm ci3_AI})] @\n        (@{thms POgenIs} RL [@{thm POgen_mono} RS @{thm ci3_AgenI}]) @\n        [@{thm POgen_mono} RS @{thm ci3_RI}]) i))\n\\<close>\n\n\nsubsection \\<open>EQgen\\<close>\n\nlemma EQ_refl: \"<a,a> : EQ\"\n  by (rule refl [THEN EQ_iff [THEN iffD1]])\n\nlemma EQgenIs:\n  \"<true,true> : EQgen(R)\"\n  \"<false,false> : EQgen(R)\"\n  \"\\<lbrakk><a,a'> : R; <b,b'> : R\\<rbrakk> \\<Longrightarrow> <<a,b>,<a',b'>> : EQgen(R)\"\n  \"\\<And>b b'. (\\<And>x. <b(x),b'(x)> : R) \\<Longrightarrow> <lam x. b(x),lam x. b'(x)> : EQgen(R)\"\n  \"<one,one> : EQgen(R)\"\n  \"<a,a'> : lfp(\\<lambda>x. EQgen(x) Un R Un EQ) \\<Longrightarrow>\n    <inl(a),inl(a')> : EQgen(lfp(\\<lambda>x. EQgen(x) Un R Un EQ))\"\n  \"<b,b'> : lfp(\\<lambda>x. EQgen(x) Un R Un EQ) \\<Longrightarrow>\n    <inr(b),inr(b')> : EQgen(lfp(\\<lambda>x. EQgen(x) Un R Un EQ))\"\n  \"<zero,zero> : EQgen(lfp(\\<lambda>x. EQgen(x) Un R Un EQ))\"\n  \"<n,n'> : lfp(\\<lambda>x. EQgen(x) Un R Un EQ) \\<Longrightarrow>\n    <succ(n),succ(n')> : EQgen(lfp(\\<lambda>x. EQgen(x) Un R Un EQ))\"\n  \"<[],[]> : EQgen(lfp(\\<lambda>x. EQgen(x) Un R Un EQ))\"\n  \"\\<lbrakk><h,h'> : lfp(\\<lambda>x. EQgen(x) Un R Un EQ); <t,t'> : lfp(\\<lambda>x. EQgen(x) Un R Un EQ)\\<rbrakk>\n    \\<Longrightarrow> <h$t,h'$t'> : EQgen(lfp(\\<lambda>x. EQgen(x) Un R Un EQ))\"\n  unfolding data_defs by (genIs EQgenXH EQgen_mono)+\n\nML \\<open>\nfun EQgen_raw_tac ctxt i =\n  (REPEAT (resolve_tac ctxt (@{thms EQgenIs} @\n        [@{thm EQ_refl} RS (@{thm EQgen_mono} RS @{thm ci3_AI})] @\n        (@{thms EQgenIs} RL [@{thm EQgen_mono} RS @{thm ci3_AgenI}]) @\n        [@{thm EQgen_mono} RS @{thm ci3_RI}]) i))\n\n(* Goals of the form R <= EQgen(R) - rewrite elements <a,b> : EQgen(R) using rews and *)\n(* then reduce this to a goal <a',b'> : R (hopefully?)                                *)\n(*      rews are rewrite rules that would cause looping in the simpifier              *)\n\nfun EQgen_tac ctxt rews i =\n SELECT_GOAL\n   (TRY (safe_tac ctxt) THEN\n    resolve_tac ctxt ((rews @ [@{thm refl}]) RL ((rews @ [@{thm refl}]) RL [@{thm ssubst_pair}])) i THEN\n    ALLGOALS (simp_tac ctxt) THEN\n    ALLGOALS (EQgen_raw_tac ctxt)) i\n\\<close>\n\nmethod_setup EQgen = \\<open>\n  Attrib.thms >> (fn ths => fn ctxt => SIMPLE_METHOD' (EQgen_tac ctxt ths))\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/CCL/Type.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.885631470799559, "lm_q2_score": 0.8031738057795403, "lm_q1q2_score": 0.7113159989202136}}
{"text": "(* \n  Author: Jeremy Dawson and Gerwin Klein, NICTA\n\n  Definitions and basic theorems for bit-wise logical operations \n  for integers expressed using Pls, Min, BIT,\n  and converting them to and from lists of bools.\n*) \n\nsection \\<open>Bitwise Operations on Binary Integers\\<close>\n\ntheory Bits_Int\nimports Bits Bit_Representation\nbegin\n\nsubsection \\<open>Logical operations\\<close>\n\ntext \"bit-wise logical operations on the int type\"\n\ninstantiation int :: bit\nbegin\n\ndefinition int_not_def:\n  \"bitNOT = (\\<lambda>x::int. - x - 1)\"\n\nfunction bitAND_int where\n  \"bitAND_int x y =\n    (if x = 0 then 0 else if x = -1 then y else\n      (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 o abs o fst)\", simp_all add: bin_rest_def)\n\ndeclare bitAND_int.simps [simp del]\n\ndefinition int_or_def:\n  \"bitOR = (\\<lambda>x y::int. NOT (NOT x AND NOT y))\"\n\ndefinition int_xor_def:\n  \"bitXOR = (\\<lambda>x y::int. (x AND NOT y) OR (NOT x AND y))\"\n\ninstance ..\n\nend\n\nsubsubsection \\<open>Basic simplification rules\\<close>\n\nlemma int_not_BIT [simp]:\n  \"NOT (w BIT b) = (NOT w) BIT (\\<not> b)\"\n  unfolding int_not_def Bit_def by (cases b, simp_all)\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::int)) = x\"\n  unfolding int_not_def by simp\n\nlemma int_and_0 [simp]: \"(0::int) AND x = 0\"\n  by (simp add: bitAND_int.simps)\n\nlemma int_and_m1 [simp]: \"(-1::int) AND x = x\"\n  by (simp add: bitAND_int.simps)\n\nlemma int_and_Bits [simp]: \n  \"(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::int) OR x = x\"\n  unfolding int_or_def by simp\n\nlemma int_or_minus1 [simp]: \"(-1::int) OR x = -1\"\n  unfolding int_or_def by simp\n\nlemma int_or_Bits [simp]: \n  \"(x BIT b) OR (y BIT c) = (x OR y) BIT (b \\<or> c)\"\n  unfolding int_or_def by simp\n\nlemma int_xor_zero [simp]: \"(0::int) XOR x = x\"\n  unfolding int_xor_def by simp\n\nlemma int_xor_Bits [simp]: \n  \"(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\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]: \"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  \"!!x y. bin_nth (x AND y) n = (bin_nth x n & bin_nth y n)\" \n  \"!!x y. bin_nth (x OR y) n = (bin_nth x n | bin_nth y n)\"\n  \"!!x y. bin_nth (x XOR y) n = (bin_nth x n ~= bin_nth y n)\" \n  \"!!x. bin_nth (NOT x) n = (~ bin_nth x n)\"\n  by (induct n) auto\n\nsubsubsection \\<open>Derived properties\\<close>\n\nlemma int_xor_minus1 [simp]: \"(-1::int) XOR x = NOT x\"\n  by (auto simp add: bin_eq_iff bin_nth_ops)\n\nlemma int_xor_extra_simps [simp]:\n  \"w XOR (0::int) = w\"\n  \"w XOR (-1::int) = NOT w\"\n  by (auto simp add: bin_eq_iff bin_nth_ops)\n\nlemma int_or_extra_simps [simp]:\n  \"w OR (0::int) = w\"\n  \"w OR (-1::int) = -1\"\n  by (auto simp add: bin_eq_iff bin_nth_ops)\n\nlemma int_and_extra_simps [simp]:\n  \"w AND (0::int) = 0\"\n  \"w AND (-1::int) = w\"\n  by (auto simp add: bin_eq_iff bin_nth_ops)\n\n(* commutativity of the above *)\nlemma bin_ops_comm:\n  shows\n  int_and_comm: \"!!y::int. x AND y = y AND x\" and\n  int_or_comm:  \"!!y::int. x OR y = y OR x\" and\n  int_xor_comm: \"!!y::int. 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::int) AND x = x\" \n  \"(x::int) OR x = x\" \n  \"(x::int) XOR x = 0\"\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(* basic properties of logical (bit-wise) operations *)\n\nlemma bbw_ao_absorb: \n  \"!!y::int. x AND (y OR x) = x & x OR (y AND x) = x\"\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::int)\"\n  \"(y OR x) AND x = x \\<and> x OR (x AND y) = (x::int)\"\n  \"(x OR y) AND x = x \\<and> (x AND y) OR x = (x::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:\n  \"!!y::int. (NOT x) XOR y = NOT (x XOR y) & \n        x XOR (NOT y) = NOT (x XOR y)\"\n  by (auto simp add: bin_eq_iff bin_nth_ops)\n\nlemma int_and_assoc:\n  \"(x AND y) AND (z::int) = x AND (y AND z)\"\n  by (auto simp add: bin_eq_iff bin_nth_ops)\n\nlemma int_or_assoc:\n  \"(x OR y) OR (z::int) = x OR (y OR z)\"\n  by (auto simp add: bin_eq_iff bin_nth_ops)\n\nlemma int_xor_assoc:\n  \"(x XOR y) XOR (z::int) = x XOR (y XOR z)\"\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::int) AND (x AND z) = x AND (y AND z)\"\n  \"(y::int) OR (x OR z) = x OR (y OR z)\"\n  \"(y::int) XOR (x XOR z) = x XOR (y XOR z)\" \n  by (auto simp add: bin_eq_iff bin_nth_ops)\n\nlemma bbw_not_dist: \n  \"!!y::int. NOT (x OR y) = (NOT x) AND (NOT y)\" \n  \"!!y::int. NOT (x AND y) = (NOT x) OR (NOT y)\"\n  by (auto simp add: bin_eq_iff bin_nth_ops)\n\nlemma bbw_oa_dist: \n  \"!!y z::int. (x AND y) OR z = \n          (x OR z) AND (y OR z)\"\n  by (auto simp add: bin_eq_iff bin_nth_ops)\n\nlemma bbw_ao_dist: \n  \"!!y z::int. (x OR y) AND z = \n          (x AND z) OR (y AND z)\"\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\nsubsubsection \\<open>Simplification with numerals\\<close>\n\ntext \\<open>Cases for \\<open>0\\<close> and \\<open>-1\\<close> are already covered by\n  other simp rules.\\<close>\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 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\ntext \\<open>FIXME: The rule sets below are very large (24 rules for each\n  operator). Is there a simpler way to do this?\\<close>\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, 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, 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, simp)+\n\nsubsubsection \\<open>Interactions with arithmetic\\<close>\n\nlemma plus_and_or [rule_format]:\n  \"ALL 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:\n  \"bin_sign (y::int) = 0 ==> x <= x OR y\"\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\n(* interaction between bit-wise and arithmetic *)\n(* good example of bin_induction *)\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\nsubsubsection \\<open>Truncating results of bit-wise operations\\<close>\n\nlemma bin_trunc_ao: \n  \"!!x y. (bintrunc n x) AND (bintrunc n y) = bintrunc n (x AND y)\" \n  \"!!x y. (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: \n  \"!!x y. bintrunc n (bintrunc n x XOR bintrunc n y) = \n          bintrunc n (x XOR y)\"\n  by (auto simp add: bin_eq_iff bin_nth_ops nth_bintr)\n\nlemma bin_trunc_not: \n  \"!!x. bintrunc n (NOT (bintrunc n x)) = bintrunc n (NOT x)\"\n  by (auto simp add: bin_eq_iff bin_nth_ops nth_bintr)\n\n(* want theorems of the form of bin_trunc_xor *)\nlemma bintr_bintr_i:\n  \"x = bintrunc n y ==> 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\nsubsection \\<open>Setting and clearing bits\\<close>\n\n(** nth bit, set/clear **)\n\nprimrec\n  bin_sc :: \"nat => bool => int => int\"\nwhere\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]: \n  \"bin_nth (bin_sc n b w) n \\<longleftrightarrow> b\"\n  by (induct n arbitrary: w) auto\n\nlemma bin_sc_sc_same [simp]: \n  \"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:\n  \"m ~= n ==> \n    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: \n  \"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]:\n  \"(bin_sc n (bin_nth w n) w) = w\"\n  by (induct n arbitrary: w) auto\n\nlemma bin_sign_sc [simp]:\n  \"bin_sign (bin_sc n b w) = bin_sign w\"\n  by (induct n arbitrary: w) auto\n  \nlemma bin_sc_bintr [simp]: \n  \"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:\n  \"bin_sc n False w <= 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:\n  \"bin_sc n True w >= 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:\n  \"bintrunc n (bin_sc m False w) <= 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:\n  \"bintrunc n (bin_sc m True w) >= 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:\n  \"0 < n ==> 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\n\nsubsection \\<open>Splitting and concatenation\\<close>\n\ndefinition bin_rcat :: \"nat \\<Rightarrow> int list \\<Rightarrow> int\"\nwhere\n  \"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\"\nwhere\n  \"bin_rsplit_aux n m c bs =\n    (if m = 0 | n = 0 then bs 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\"\nwhere\n  \"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\"\nwhere\n  \"bin_rsplitl_aux n m c bs =\n    (if m = 0 | n = 0 then bs 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\"\nwhere\n  \"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_sign_cat: \n  \"bin_sign (bin_cat x n y) = bin_sign x\"\n  by (induct n arbitrary: y) auto\n\nlemma bin_cat_Suc_Bit:\n  \"bin_cat w (Suc n) (v BIT b) = bin_cat w n v BIT b\"\n  by auto\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) ==> \n    (ALL k. bin_nth a k = bin_nth c (n + k)) & \n    (ALL k. bin_nth b k = (k < n & 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_assoc: \n  \"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:\n  \"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, clarsimp)\n  apply (case_tac m, 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: \n  \"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]: \n  \"bintrunc n (bin_cat a n b) = bintrunc n b\"\n  by (auto simp add : bintr_cat)\n\nlemma cat_bintr [simp]: \n  \"bin_cat a n (bintrunc n b) = bin_cat a n b\"\n  by (induct n arbitrary: b) auto\n\nlemma split_bintrunc: \n  \"bin_split n c = (a, b) ==> b = bintrunc n c\"\n  by (induct n arbitrary: b c) (auto simp: Let_def split: prod.split_asm)\n\nlemma bin_cat_split:\n  \"bin_split n w = (u, v) ==> 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:\n  \"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) ==> \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) ==> \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:\n  \"bin_cat a n b = a * 2 ^ n + bintrunc n b\"\n  apply (induct n arbitrary: b, clarsimp)\n  apply (simp add: Bit_def)\n  done\n\nlemma bin_split_num:\n  \"bin_split n b = (b div 2 ^ n, b mod 2 ^ n)\"\n  apply (induct n arbitrary: b, 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 p1mod22k)\n  done\n\nsubsection \\<open>Miscellaneous lemmas\\<close>\n\nlemma nth_2p_bin: \n  \"bin_nth (2 ^ n) m = (m = n)\"\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\n(* for use when simplifying with bin_nth_Bit *)\n\nlemma ex_eq_or:\n  \"(EX m. n = Suc m & (m = k | P m)) = (n = Suc k | (EX m. n = Suc m & P m))\"\n  by auto\n\nlemma power_BIT: \"2 ^ (Suc n) - 1 = (2 ^ n - 1) BIT True\"\n  unfolding Bit_B1\n  by (induct n) simp_all\n\nlemma mod_BIT:\n  \"bin BIT bit mod 2 ^ Suc n = (bin mod 2 ^ n) BIT bit\"\nproof -\n  have \"bin mod 2 ^ n < 2 ^ n\" by simp\n  then have \"bin mod 2 ^ n \\<le> 2 ^ n - 1\" by simp\n  then have \"2 * (bin mod 2 ^ n) \\<le> 2 * (2 ^ n - 1)\"\n    by (rule mult_left_mono) simp\n  then have \"2 * (bin mod 2 ^ n) + 1 < 2 * 2 ^ n\" by simp\n  then show ?thesis\n    by (auto simp add: Bit_def mod_mult_mult1 mod_add_left_eq [of \"2 * bin\"]\n      mod_pos_pos_trivial)\nqed\n\nlemma AND_mod:\n  fixes x :: int\n  shows \"x AND 2 ^ n - 1 = x mod 2 ^ n\"\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\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/Word/Bits_Int.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.885631470799559, "lm_q2_score": 0.803173791645582, "lm_q1q2_score": 0.7113159864027353}}
{"text": "theory cantor\nimports Main\nbegin\n\n(* these are all different ways to write the same proof. from: \n * http://isabelle.in.tum.de/dist/Isabelle2013/doc/prog-prove.pdf\n * original proof was by g.cantor *)\n\nlemma \"\\<not> surj(f::'a \\<Rightarrow>'a set)\"\n  proof\n    assume 0 : \"surj f\"\n    from 0 have 1 : \"\\<forall>A. \\<exists>a. A = f a\" by blast\n    from 1 have 2 : \"\\<exists>a. {x. x \\<notin> f x} = f a\" by blast\n    from 2 show False by blast\n  qed\n\nlemma \"\\<not> surj(f::'a \\<Rightarrow>'a set)\"\n  proof\n    assume \"surj f\"\n    from this have \"\\<forall>A. \\<exists>a. A = f a\" by (auto simp: surj_def)\n    from this have \"\\<exists>a. {x. x \\<notin> f x} = f a\" by blast\n    from this show False by blast\n  qed\n\nlemma \"\\<not> surj(f::'a \\<Rightarrow>'a set)\"\n  proof\n    assume \"surj f\"\n    hence \"\\<forall>A. \\<exists>a. A = f a\" by (auto simp: surj_def)\n    hence \"\\<exists>a. {x. x \\<notin> f x} = f a\" by blast\n    thus False by blast\n  qed\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 \n    by  (auto simp: surj_def)\n  thus \"False\" by blast\nqed\n\n\n\nend\n", "meta": {"author": "tangentstorm", "repo": "tangentlabs", "sha": "49d7a335221e1ae67e8de0203a3f056bc4ab1d00", "save_path": "github-repos/isabelle/tangentstorm-tangentlabs", "path": "github-repos/isabelle/tangentstorm-tangentlabs/tangentlabs-49d7a335221e1ae67e8de0203a3f056bc4ab1d00/isar/cantor.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.877476800298183, "lm_q2_score": 0.8104789018037399, "lm_q1q2_score": 0.711176433463931}}
{"text": "(*  Title:      ZF/Perm.thy\n    Author:     Lawrence C Paulson, Cambridge University Computer Laboratory\n    Copyright   1991  University of Cambridge\n\nThe theory underlying permutation groups\n  -- Composition of relations, the identity relation\n  -- Injections, surjections, bijections\n  -- Lemmas for the Schroeder-Bernstein Theorem\n*)\n\nsection\\<open>Injections, Surjections, Bijections, Composition\\<close>\n\ntheory Perm imports func begin\n\ndefinition\n  (*composition of relations and functions; NOT Suppes's relative product*)\n  comp     :: \"[i,i]=>i\"      (infixr \\<open>O\\<close> 60)  where\n    \"r O s == {xz \\<in> domain(s)*range(r) .\n               \\<exists>x y z. xz=<x,z> & <x,y>:s & <y,z>:r}\"\n\ndefinition\n  (*the identity function for A*)\n  id    :: \"i=>i\"  where\n    \"id(A) == (\\<lambda>x\\<in>A. x)\"\n\ndefinition\n  (*one-to-one functions from A to B*)\n  inj   :: \"[i,i]=>i\"  where\n    \"inj(A,B) == { f \\<in> A->B. \\<forall>w\\<in>A. \\<forall>x\\<in>A. f`w=f`x \\<longrightarrow> w=x}\"\n\ndefinition\n  (*onto functions from A to B*)\n  surj  :: \"[i,i]=>i\"  where\n    \"surj(A,B) == { f \\<in> A->B . \\<forall>y\\<in>B. \\<exists>x\\<in>A. f`x=y}\"\n\ndefinition\n  (*one-to-one and onto functions*)\n  bij   :: \"[i,i]=>i\"  where\n    \"bij(A,B) == inj(A,B) \\<inter> surj(A,B)\"\n\n\nsubsection\\<open>Surjective Function Space\\<close>\n\nlemma surj_is_fun: \"f \\<in> surj(A,B) ==> f \\<in> A->B\"\napply (unfold surj_def)\napply (erule CollectD1)\ndone\n\nlemma fun_is_surj: \"f \\<in> Pi(A,B) ==> f \\<in> surj(A,range(f))\"\napply (unfold surj_def)\napply (blast intro: apply_equality range_of_fun domain_type)\ndone\n\nlemma surj_range: \"f \\<in> surj(A,B) ==> range(f)=B\"\napply (unfold surj_def)\napply (best intro: apply_Pair elim: range_type)\ndone\n\ntext\\<open>A function with a right inverse is a surjection\\<close>\n\nlemma f_imp_surjective:\n    \"[| f \\<in> A->B;  !!y. y \\<in> B ==> d(y): A;  !!y. y \\<in> B ==> f`d(y) = y |]\n     ==> f \\<in> surj(A,B)\"\n  by (simp add: surj_def, blast)\n\nlemma lam_surjective:\n    \"[| !!x. x \\<in> A ==> c(x): B;\n        !!y. y \\<in> B ==> d(y): A;\n        !!y. y \\<in> B ==> c(d(y)) = y\n     |] ==> (\\<lambda>x\\<in>A. c(x)) \\<in> surj(A,B)\"\napply (rule_tac d = d in f_imp_surjective)\napply (simp_all add: lam_type)\ndone\n\ntext\\<open>Cantor's theorem revisited\\<close>\nlemma cantor_surj: \"f \\<notin> surj(A,Pow(A))\"\napply (unfold surj_def, safe)\napply (cut_tac cantor)\napply (best del: subsetI)\ndone\n\n\nsubsection\\<open>Injective Function Space\\<close>\n\nlemma inj_is_fun: \"f \\<in> inj(A,B) ==> f \\<in> A->B\"\napply (unfold inj_def)\napply (erule CollectD1)\ndone\n\ntext\\<open>Good for dealing with sets of pairs, but a bit ugly in use [used in AC]\\<close>\nlemma inj_equality:\n    \"[| <a,b>:f;  <c,b>:f;  f \\<in> inj(A,B) |] ==> a=c\"\napply (unfold inj_def)\napply (blast dest: Pair_mem_PiD)\ndone\n\nlemma inj_apply_equality: \"[| f \\<in> inj(A,B);  f`a=f`b;  a \\<in> A;  b \\<in> A |] ==> a=b\"\nby (unfold inj_def, blast)\n\ntext\\<open>A function with a left inverse is an injection\\<close>\n\nlemma f_imp_injective: \"[| f \\<in> A->B;  \\<forall>x\\<in>A. d(f`x)=x |] ==> f \\<in> inj(A,B)\"\napply (simp (no_asm_simp) add: inj_def)\napply (blast intro: subst_context [THEN box_equals])\ndone\n\nlemma lam_injective:\n    \"[| !!x. x \\<in> A ==> c(x): B;\n        !!x. x \\<in> A ==> d(c(x)) = x |]\n     ==> (\\<lambda>x\\<in>A. c(x)) \\<in> inj(A,B)\"\napply (rule_tac d = d in f_imp_injective)\napply (simp_all add: lam_type)\ndone\n\nsubsection\\<open>Bijections\\<close>\n\nlemma bij_is_inj: \"f \\<in> bij(A,B) ==> f \\<in> inj(A,B)\"\napply (unfold bij_def)\napply (erule IntD1)\ndone\n\nlemma bij_is_surj: \"f \\<in> bij(A,B) ==> f \\<in> surj(A,B)\"\napply (unfold bij_def)\napply (erule IntD2)\ndone\n\nlemma bij_is_fun: \"f \\<in> bij(A,B) ==> f \\<in> A->B\"\n  by (rule bij_is_inj [THEN inj_is_fun])\n\nlemma lam_bijective:\n    \"[| !!x. x \\<in> A ==> c(x): B;\n        !!y. y \\<in> B ==> d(y): A;\n        !!x. x \\<in> A ==> d(c(x)) = x;\n        !!y. y \\<in> B ==> c(d(y)) = y\n     |] ==> (\\<lambda>x\\<in>A. c(x)) \\<in> bij(A,B)\"\napply (unfold bij_def)\napply (blast intro!: lam_injective lam_surjective)\ndone\n\nlemma RepFun_bijective: \"(\\<forall>y\\<in>x. \\<exists>!y'. f(y') = f(y))\n      ==> (\\<lambda>z\\<in>{f(y). y \\<in> x}. THE y. f(y) = z) \\<in> bij({f(y). y \\<in> x}, x)\"\napply (rule_tac d = f in lam_bijective)\napply (auto simp add: the_equality2)\ndone\n\n\nsubsection\\<open>Identity Function\\<close>\n\nlemma idI [intro!]: \"a \\<in> A ==> <a,a> \\<in> id(A)\"\napply (unfold id_def)\napply (erule lamI)\ndone\n\nlemma idE [elim!]: \"[| p \\<in> id(A);  !!x.[| x \\<in> A; p=<x,x> |] ==> P |] ==>  P\"\nby (simp add: id_def lam_def, blast)\n\nlemma id_type: \"id(A) \\<in> A->A\"\napply (unfold id_def)\napply (rule lam_type, assumption)\ndone\n\nlemma id_conv [simp]: \"x \\<in> A ==> id(A)`x = x\"\napply (unfold id_def)\napply (simp (no_asm_simp))\ndone\n\nlemma id_mono: \"A<=B ==> id(A) \\<subseteq> id(B)\"\napply (unfold id_def)\napply (erule lam_mono)\ndone\n\nlemma id_subset_inj: \"A<=B ==> id(A): inj(A,B)\"\napply (simp add: inj_def id_def)\napply (blast intro: lam_type)\ndone\n\nlemmas id_inj = subset_refl [THEN id_subset_inj]\n\nlemma id_surj: \"id(A): surj(A,A)\"\napply (unfold id_def surj_def)\napply (simp (no_asm_simp))\ndone\n\nlemma id_bij: \"id(A): bij(A,A)\"\napply (unfold bij_def)\napply (blast intro: id_inj id_surj)\ndone\n\nlemma subset_iff_id: \"A \\<subseteq> B \\<longleftrightarrow> id(A) \\<in> A->B\"\napply (unfold id_def)\napply (force intro!: lam_type dest: apply_type)\ndone\n\ntext\\<open>\\<^term>\\<open>id\\<close> as the identity relation\\<close>\nlemma id_iff [simp]: \"<x,y> \\<in> id(A) \\<longleftrightarrow> x=y & y \\<in> A\"\nby auto\n\n\nsubsection\\<open>Converse of a Function\\<close>\n\nlemma inj_converse_fun: \"f \\<in> inj(A,B) ==> converse(f) \\<in> range(f)->A\"\napply (unfold inj_def)\napply (simp (no_asm_simp) add: Pi_iff function_def)\napply (erule CollectE)\napply (simp (no_asm_simp) add: apply_iff)\napply (blast dest: fun_is_rel)\ndone\n\ntext\\<open>Equations for converse(f)\\<close>\n\ntext\\<open>The premises are equivalent to saying that f is injective...\\<close>\nlemma left_inverse_lemma:\n     \"[| f \\<in> A->B;  converse(f): C->A;  a \\<in> A |] ==> converse(f)`(f`a) = a\"\nby (blast intro: apply_Pair apply_equality converseI)\n\nlemma left_inverse [simp]: \"[| f \\<in> inj(A,B);  a \\<in> A |] ==> converse(f)`(f`a) = a\"\nby (blast intro: left_inverse_lemma inj_converse_fun inj_is_fun)\n\nlemma left_inverse_eq:\n     \"[|f \\<in> inj(A,B); f ` x = y; x \\<in> A|] ==> converse(f) ` y = x\"\nby auto\n\nlemmas left_inverse_bij = bij_is_inj [THEN left_inverse]\n\nlemma right_inverse_lemma:\n     \"[| f \\<in> A->B;  converse(f): C->A;  b \\<in> C |] ==> f`(converse(f)`b) = b\"\nby (rule apply_Pair [THEN converseD [THEN apply_equality]], auto)\n\n(*Should the premises be f \\<in> surj(A,B), b \\<in> B for symmetry with left_inverse?\n  No: they would not imply that converse(f) was a function! *)\nlemma right_inverse [simp]:\n     \"[| f \\<in> inj(A,B);  b \\<in> range(f) |] ==> f`(converse(f)`b) = b\"\nby (blast intro: right_inverse_lemma inj_converse_fun inj_is_fun)\n\nlemma right_inverse_bij: \"[| f \\<in> bij(A,B);  b \\<in> B |] ==> f`(converse(f)`b) = b\"\nby (force simp add: bij_def surj_range)\n\nsubsection\\<open>Converses of Injections, Surjections, Bijections\\<close>\n\nlemma inj_converse_inj: \"f \\<in> inj(A,B) ==> converse(f): inj(range(f), A)\"\napply (rule f_imp_injective)\napply (erule inj_converse_fun, clarify)\napply (rule right_inverse)\n apply assumption\napply blast\ndone\n\nlemma inj_converse_surj: \"f \\<in> inj(A,B) ==> converse(f): surj(range(f), A)\"\nby (blast intro: f_imp_surjective inj_converse_fun left_inverse inj_is_fun\n                 range_of_fun [THEN apply_type])\n\ntext\\<open>Adding this as an intro! rule seems to cause looping\\<close>\nlemma bij_converse_bij [TC]: \"f \\<in> bij(A,B) ==> converse(f): bij(B,A)\"\napply (unfold bij_def)\napply (fast elim: surj_range [THEN subst] inj_converse_inj inj_converse_surj)\ndone\n\n\n\nsubsection\\<open>Composition of Two Relations\\<close>\n\ntext\\<open>The inductive definition package could derive these theorems for \\<^term>\\<open>r O s\\<close>\\<close>\n\nlemma compI [intro]: \"[| <a,b>:s; <b,c>:r |] ==> <a,c> \\<in> r O s\"\nby (unfold comp_def, blast)\n\nlemma compE [elim!]:\n    \"[| xz \\<in> r O s;\n        !!x y z. [| xz=<x,z>;  <x,y>:s;  <y,z>:r |] ==> P |]\n     ==> P\"\nby (unfold comp_def, blast)\n\nlemma compEpair:\n    \"[| <a,c> \\<in> r O s;\n        !!y. [| <a,y>:s;  <y,c>:r |] ==> P |]\n     ==> P\"\nby (erule compE, simp)\n\nlemma converse_comp: \"converse(R O S) = converse(S) O converse(R)\"\nby blast\n\n\nsubsection\\<open>Domain and Range -- see Suppes, Section 3.1\\<close>\n\ntext\\<open>Boyer et al., Set Theory in First-Order Logic, JAR 2 (1986), 287-327\\<close>\nlemma range_comp: \"range(r O s) \\<subseteq> range(r)\"\nby blast\n\nlemma range_comp_eq: \"domain(r) \\<subseteq> range(s) ==> range(r O s) = range(r)\"\nby (rule range_comp [THEN equalityI], blast)\n\nlemma domain_comp: \"domain(r O s) \\<subseteq> domain(s)\"\nby blast\n\nlemma domain_comp_eq: \"range(s) \\<subseteq> domain(r) ==> domain(r O s) = domain(s)\"\nby (rule domain_comp [THEN equalityI], blast)\n\nlemma image_comp: \"(r O s)``A = r``(s``A)\"\nby blast\n\nlemma inj_inj_range: \"f \\<in> inj(A,B) ==> f \\<in> inj(A,range(f))\"\n  by (auto simp add: inj_def Pi_iff function_def)\n\nlemma inj_bij_range: \"f \\<in> inj(A,B) ==> f \\<in> bij(A,range(f))\"\n  by (auto simp add: bij_def intro: inj_inj_range inj_is_fun fun_is_surj)\n\n\nsubsection\\<open>Other Results\\<close>\n\nlemma comp_mono: \"[| r'<=r; s'<=s |] ==> (r' O s') \\<subseteq> (r O s)\"\nby blast\n\ntext\\<open>composition preserves relations\\<close>\nlemma comp_rel: \"[| s<=A*B;  r<=B*C |] ==> (r O s) \\<subseteq> A*C\"\nby blast\n\ntext\\<open>associative law for composition\\<close>\nlemma comp_assoc: \"(r O s) O t = r O (s O t)\"\nby blast\n\n(*left identity of composition; provable inclusions are\n        id(A) O r \\<subseteq> r\n  and   [| r<=A*B; B<=C |] ==> r \\<subseteq> id(C) O r *)\nlemma left_comp_id: \"r<=A*B ==> id(B) O r = r\"\nby blast\n\n(*right identity of composition; provable inclusions are\n        r O id(A) \\<subseteq> r\n  and   [| r<=A*B; A<=C |] ==> r \\<subseteq> r O id(C) *)\nlemma right_comp_id: \"r<=A*B ==> r O id(A) = r\"\nby blast\n\n\nsubsection\\<open>Composition Preserves Functions, Injections, and Surjections\\<close>\n\nlemma comp_function: \"[| function(g);  function(f) |] ==> function(f O g)\"\nby (unfold function_def, blast)\n\ntext\\<open>Don't think the premises can be weakened much\\<close>\nlemma comp_fun: \"[| g \\<in> A->B;  f \\<in> B->C |] ==> (f O g) \\<in> A->C\"\napply (auto simp add: Pi_def comp_function Pow_iff comp_rel)\napply (subst range_rel_subset [THEN domain_comp_eq], auto)\ndone\n\n(*Thanks to the new definition of \"apply\", the premise f \\<in> B->C is gone!*)\nlemma comp_fun_apply [simp]:\n     \"[| g \\<in> A->B;  a \\<in> A |] ==> (f O g)`a = f`(g`a)\"\napply (frule apply_Pair, assumption)\napply (simp add: apply_def image_comp)\napply (blast dest: apply_equality)\ndone\n\ntext\\<open>Simplifies compositions of lambda-abstractions\\<close>\nlemma comp_lam:\n    \"[| !!x. x \\<in> A ==> b(x): B |]\n     ==> (\\<lambda>y\\<in>B. c(y)) O (\\<lambda>x\\<in>A. b(x)) = (\\<lambda>x\\<in>A. c(b(x)))\"\napply (subgoal_tac \"(\\<lambda>x\\<in>A. b(x)) \\<in> A -> B\")\n apply (rule fun_extension)\n   apply (blast intro: comp_fun lam_funtype)\n  apply (rule lam_funtype)\n apply simp\napply (simp add: lam_type)\ndone\n\nlemma comp_inj:\n     \"[| g \\<in> inj(A,B);  f \\<in> inj(B,C) |] ==> (f O g) \\<in> inj(A,C)\"\napply (frule inj_is_fun [of g])\napply (frule inj_is_fun [of f])\napply (rule_tac d = \"%y. converse (g) ` (converse (f) ` y)\" in f_imp_injective)\n apply (blast intro: comp_fun, simp)\ndone\n\nlemma comp_surj:\n    \"[| g \\<in> surj(A,B);  f \\<in> surj(B,C) |] ==> (f O g) \\<in> surj(A,C)\"\napply (unfold surj_def)\napply (blast intro!: comp_fun comp_fun_apply)\ndone\n\nlemma comp_bij:\n    \"[| g \\<in> bij(A,B);  f \\<in> bij(B,C) |] ==> (f O g) \\<in> bij(A,C)\"\napply (unfold bij_def)\napply (blast intro: comp_inj comp_surj)\ndone\n\n\nsubsection\\<open>Dual Properties of \\<^term>\\<open>inj\\<close> and \\<^term>\\<open>surj\\<close>\\<close>\n\ntext\\<open>Useful for proofs from\n    D Pastre.  Automatic theorem proving in set theory.\n    Artificial Intelligence, 10:1--27, 1978.\\<close>\n\nlemma comp_mem_injD1:\n    \"[| (f O g): inj(A,C);  g \\<in> A->B;  f \\<in> B->C |] ==> g \\<in> inj(A,B)\"\nby (unfold inj_def, force)\n\nlemma comp_mem_injD2:\n    \"[| (f O g): inj(A,C);  g \\<in> surj(A,B);  f \\<in> B->C |] ==> f \\<in> inj(B,C)\"\napply (unfold inj_def surj_def, safe)\napply (rule_tac x1 = x in bspec [THEN bexE])\napply (erule_tac [3] x1 = w in bspec [THEN bexE], assumption+, safe)\napply (rule_tac t = \"(`) (g) \" in subst_context)\napply (erule asm_rl bspec [THEN bspec, THEN mp])+\napply (simp (no_asm_simp))\ndone\n\nlemma comp_mem_surjD1:\n    \"[| (f O g): surj(A,C);  g \\<in> A->B;  f \\<in> B->C |] ==> f \\<in> surj(B,C)\"\napply (unfold surj_def)\napply (blast intro!: comp_fun_apply [symmetric] apply_funtype)\ndone\n\n\nlemma comp_mem_surjD2:\n    \"[| (f O g): surj(A,C);  g \\<in> A->B;  f \\<in> inj(B,C) |] ==> g \\<in> surj(A,B)\"\napply (unfold inj_def surj_def, safe)\napply (drule_tac x = \"f`y\" in bspec, auto)\napply (blast intro: apply_funtype)\ndone\n\nsubsubsection\\<open>Inverses of Composition\\<close>\n\ntext\\<open>left inverse of composition; one inclusion is\n        \\<^term>\\<open>f \\<in> A->B ==> id(A) \\<subseteq> converse(f) O f\\<close>\\<close>\nlemma left_comp_inverse: \"f \\<in> inj(A,B) ==> converse(f) O f = id(A)\"\napply (unfold inj_def, clarify)\napply (rule equalityI)\n apply (auto simp add: apply_iff, blast)\ndone\n\ntext\\<open>right inverse of composition; one inclusion is\n                \\<^term>\\<open>f \\<in> A->B ==> f O converse(f) \\<subseteq> id(B)\\<close>\\<close>\nlemma right_comp_inverse:\n    \"f \\<in> surj(A,B) ==> f O converse(f) = id(B)\"\napply (simp add: surj_def, clarify)\napply (rule equalityI)\napply (best elim: domain_type range_type dest: apply_equality2)\napply (blast intro: apply_Pair)\ndone\n\n\nsubsubsection\\<open>Proving that a Function is a Bijection\\<close>\n\nlemma comp_eq_id_iff:\n    \"[| f \\<in> A->B;  g \\<in> B->A |] ==> f O g = id(B) \\<longleftrightarrow> (\\<forall>y\\<in>B. f`(g`y)=y)\"\napply (unfold id_def, safe)\n apply (drule_tac t = \"%h. h`y \" in subst_context)\n apply simp\napply (rule fun_extension)\n  apply (blast intro: comp_fun lam_type)\n apply auto\ndone\n\nlemma fg_imp_bijective:\n    \"[| f \\<in> A->B;  g \\<in> B->A;  f O g = id(B);  g O f = id(A) |] ==> f \\<in> bij(A,B)\"\napply (unfold bij_def)\napply (simp add: comp_eq_id_iff)\napply (blast intro: f_imp_injective f_imp_surjective apply_funtype)\ndone\n\nlemma nilpotent_imp_bijective: \"[| f \\<in> A->A;  f O f = id(A) |] ==> f \\<in> bij(A,A)\"\nby (blast intro: fg_imp_bijective)\n\nlemma invertible_imp_bijective:\n     \"[| converse(f): B->A;  f \\<in> A->B |] ==> f \\<in> bij(A,B)\"\nby (simp add: fg_imp_bijective comp_eq_id_iff\n              left_inverse_lemma right_inverse_lemma)\n\nsubsubsection\\<open>Unions of Functions\\<close>\n\ntext\\<open>See similar theorems in func.thy\\<close>\n\ntext\\<open>Theorem by KG, proof by LCP\\<close>\nlemma inj_disjoint_Un:\n     \"[| f \\<in> inj(A,B);  g \\<in> inj(C,D);  B \\<inter> D = 0 |]\n      ==> (\\<lambda>a\\<in>A \\<union> C. if a \\<in> A then f`a else g`a) \\<in> inj(A \\<union> C, B \\<union> D)\"\napply (rule_tac d = \"%z. if z \\<in> B then converse (f) `z else converse (g) `z\"\n       in lam_injective)\napply (auto simp add: inj_is_fun [THEN apply_type])\ndone\n\nlemma surj_disjoint_Un:\n    \"[| f \\<in> surj(A,B);  g \\<in> surj(C,D);  A \\<inter> C = 0 |]\n     ==> (f \\<union> g) \\<in> surj(A \\<union> C, B \\<union> D)\"\napply (simp add: surj_def fun_disjoint_Un)\napply (blast dest!: domain_of_fun\n             intro!: fun_disjoint_apply1 fun_disjoint_apply2)\ndone\n\ntext\\<open>A simple, high-level proof; the version for injections follows from it,\n  using  \\<^term>\\<open>f \\<in> inj(A,B) \\<longleftrightarrow> f \\<in> bij(A,range(f))\\<close>\\<close>\nlemma bij_disjoint_Un:\n     \"[| f \\<in> bij(A,B);  g \\<in> bij(C,D);  A \\<inter> C = 0;  B \\<inter> D = 0 |]\n      ==> (f \\<union> g) \\<in> bij(A \\<union> C, B \\<union> D)\"\napply (rule invertible_imp_bijective)\napply (subst converse_Un)\napply (auto intro: fun_disjoint_Un bij_is_fun bij_converse_bij)\ndone\n\n\nsubsubsection\\<open>Restrictions as Surjections and Bijections\\<close>\n\nlemma surj_image:\n    \"f \\<in> Pi(A,B) ==> f \\<in> surj(A, f``A)\"\napply (simp add: surj_def)\napply (blast intro: apply_equality apply_Pair Pi_type)\ndone\n\nlemma surj_image_eq: \"f \\<in> surj(A, B) ==> f``A = B\"\n  by (auto simp add: surj_def image_fun) (blast dest: apply_type) \n\nlemma restrict_image [simp]: \"restrict(f,A) `` B = f `` (A \\<inter> B)\"\nby (auto simp add: restrict_def)\n\nlemma restrict_inj:\n    \"[| f \\<in> inj(A,B);  C<=A |] ==> restrict(f,C): inj(C,B)\"\napply (unfold inj_def)\napply (safe elim!: restrict_type2, auto)\ndone\n\nlemma restrict_surj: \"[| f \\<in> Pi(A,B);  C<=A |] ==> restrict(f,C): surj(C, f``C)\"\napply (insert restrict_type2 [THEN surj_image])\napply (simp add: restrict_image)\ndone\n\nlemma restrict_bij:\n    \"[| f \\<in> inj(A,B);  C<=A |] ==> restrict(f,C): bij(C, f``C)\"\napply (simp add: inj_def bij_def)\napply (blast intro: restrict_surj surj_is_fun)\ndone\n\n\nsubsubsection\\<open>Lemmas for Ramsey's Theorem\\<close>\n\nlemma inj_weaken_type: \"[| f \\<in> inj(A,B);  B<=D |] ==> f \\<in> inj(A,D)\"\napply (unfold inj_def)\napply (blast intro: fun_weaken_type)\ndone\n\nlemma inj_succ_restrict:\n     \"[| f \\<in> inj(succ(m), A) |] ==> restrict(f,m) \\<in> inj(m, A-{f`m})\"\napply (rule restrict_bij [THEN bij_is_inj, THEN inj_weaken_type], assumption, blast)\napply (unfold inj_def)\napply (fast elim: range_type mem_irrefl dest: apply_equality)\ndone\n\n\nlemma inj_extend:\n    \"[| f \\<in> inj(A,B);  a\\<notin>A;  b\\<notin>B |]\n     ==> cons(<a,b>,f) \\<in> inj(cons(a,A), cons(b,B))\"\napply (unfold inj_def)\napply (force intro: apply_type  simp add: fun_extend)\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/Perm.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289387914176259, "lm_q2_score": 0.8577681068080749, "lm_q1q2_score": 0.7110372577740707}}
{"text": "(*\n    Author:     Wenda Li <wl302@cam.ac.uk / liwenda1990@hotmail.com>\n*)\n\nsection \\<open>Some useful lemmas in analysis\\<close>\n\ntheory Missing_Analysis\n  imports \"HOL-Complex_Analysis.Complex_Analysis\"\nbegin  \n\nsubsection \\<open>More about paths\\<close>\n   \nlemma pathfinish_offset[simp]:\n  \"pathfinish (\\<lambda>t. g t - z) = pathfinish g - z\"\n  unfolding pathfinish_def by simp \n    \nlemma pathstart_offset[simp]:\n  \"pathstart (\\<lambda>t. g t - z) = pathstart g - z\"\n  unfolding pathstart_def by simp\n    \nlemma pathimage_offset[simp]:\n  fixes g :: \"_ \\<Rightarrow> 'b::topological_group_add\"\n  shows \"p \\<in> path_image (\\<lambda>t. g t - z) \\<longleftrightarrow> p+z \\<in> path_image g \" \nunfolding path_image_def by (auto simp:algebra_simps)\n  \nlemma path_offset[simp]:\n fixes g :: \"_ \\<Rightarrow> 'b::topological_group_add\"\n shows \"path (\\<lambda>t. g t - z) \\<longleftrightarrow> path g\"\nunfolding path_def\nproof \n  assume \"continuous_on {0..1} (\\<lambda>t. g t - z)\" \n  hence \"continuous_on {0..1} (\\<lambda>t. (g t - z) + z)\" \n    apply (rule continuous_intros)\n    by (intro continuous_intros)\n  then show \"continuous_on {0..1} g\" by auto\nqed (auto intro:continuous_intros)   \n  \nlemma not_on_circlepathI:\n  assumes \"cmod (z-z0) \\<noteq> \\<bar>r\\<bar>\"\n  shows \"z \\<notin> path_image (part_circlepath z0 r st tt)\"\nproof (rule ccontr)\n  assume \"\\<not> z \\<notin> path_image (part_circlepath z0 r st tt)\"\n  then have \"z\\<in>path_image (part_circlepath z0 r st tt)\" by simp\n  then obtain t where \"t\\<in>{0..1}\" and *:\"z = z0 + r * exp (\\<i> * (linepath st tt t))\"\n    unfolding path_image_def image_def part_circlepath_def by blast\n  define \\<theta> where \"\\<theta> = linepath st tt t\"\n  then have \"z-z0 = r * exp (\\<i> * \\<theta>)\" using * by auto\n  then have \"cmod (z-z0) = cmod (r * exp (\\<i> * \\<theta>))\" by auto\n  also have \"\\<dots> = \\<bar>r\\<bar> * cmod (exp (\\<i> * \\<theta>))\" by (simp add: norm_mult)\n  also have \"\\<dots> = \\<bar>r\\<bar>\" by auto\n  finally have \"cmod (z-z0) = \\<bar>r\\<bar>\" .\n  then show False using assms by auto\nqed    \n\nlemma circlepath_inj_on: \n  assumes \"r>0\"\n  shows \"inj_on (circlepath z r) {0..<1}\"\nproof (rule inj_onI)\n  fix x y assume asm: \"x \\<in> {0..<1}\" \"y \\<in> {0..<1}\" \"circlepath z r x = circlepath z r y\"\n  define c where \"c=2 * pi * \\<i>\"\n  have \"c\\<noteq>0\" unfolding c_def by auto \n  from asm(3) have \"exp (c * x) =exp (c * y)\"\n    unfolding circlepath c_def using \\<open>r>0\\<close> by auto\n  then obtain n where \"c * x =c * (y + of_int n)\"\n    by (auto simp add:exp_eq c_def algebra_simps)\n  then have \"x=y+n\" using \\<open>c\\<noteq>0\\<close>\n    by (meson mult_cancel_left of_real_eq_iff)\n  then show \"x=y\" using asm(1,2) by auto\nqed\n\nsubsection \\<open>More lemmas related to @{term winding_number}\\<close>  \n  \nlemma winding_number_comp:\n  assumes \"open s\" \"f holomorphic_on s\" \"path_image \\<gamma> \\<subseteq> s\"  \n    \"valid_path \\<gamma>\" \"z \\<notin> path_image (f \\<circ> \\<gamma>)\" \n  shows \"winding_number (f \\<circ> \\<gamma>) z = 1/(2*pi*\\<i>)* contour_integral \\<gamma> (\\<lambda>w. deriv f w / (f w - z))\"\nproof -\n  obtain spikes where \"finite spikes\" and \\<gamma>_diff: \"\\<gamma> C1_differentiable_on {0..1} - spikes\"\n    using \\<open>valid_path \\<gamma>\\<close> unfolding valid_path_def piecewise_C1_differentiable_on_def by auto  \n  have \"valid_path (f \\<circ> \\<gamma>)\" \n    using valid_path_compose_holomorphic assms by blast\n  moreover have \"contour_integral (f \\<circ> \\<gamma>) (\\<lambda>w. 1 / (w - z)) \n      = contour_integral \\<gamma> (\\<lambda>w. deriv f w / (f w - z))\"\n    unfolding contour_integral_integral\n  proof (rule integral_spike[rule_format,OF negligible_finite[OF \\<open>finite spikes\\<close>]])\n    fix t::real assume t:\"t \\<in> {0..1} - spikes\"\n    then have \"\\<gamma> differentiable at t\" \n      using \\<gamma>_diff unfolding C1_differentiable_on_eq by auto\n    moreover have \"f field_differentiable at (\\<gamma> t)\" \n    proof -\n      have \"\\<gamma> t \\<in> s\" using \\<open>path_image \\<gamma> \\<subseteq> s\\<close> t unfolding path_image_def by auto \n      thus ?thesis \n        using \\<open>open s\\<close> \\<open>f holomorphic_on s\\<close>  holomorphic_on_imp_differentiable_at by blast\n    qed\n    ultimately show \" deriv f (\\<gamma> t) / (f (\\<gamma> t) - z) * vector_derivative \\<gamma> (at t) =\n         1 / ((f \\<circ> \\<gamma>) t - z) * vector_derivative (f \\<circ> \\<gamma>) (at t)\"\n      apply (subst vector_derivative_chain_at_general)\n      by (simp_all add:field_simps)\n  qed\n  moreover note \\<open>z \\<notin> path_image (f \\<circ> \\<gamma>)\\<close> \n  ultimately show ?thesis\n    apply (subst winding_number_valid_path)\n    by simp_all\nqed  \n  \nlemma winding_number_uminus_comp:\n  assumes \"valid_path \\<gamma>\" \"- z \\<notin> path_image \\<gamma>\" \n  shows \"winding_number (uminus \\<circ> \\<gamma>) z = winding_number \\<gamma> (-z)\"\nproof -\n  define c where \"c= 2 * pi * \\<i>\"\n  have \"winding_number (uminus \\<circ> \\<gamma>) z = 1/c * contour_integral \\<gamma> (\\<lambda>w. deriv uminus w / (-w-z)) \"\n  proof (rule winding_number_comp[of UNIV, folded c_def])\n    show \"open UNIV\" \"uminus holomorphic_on UNIV\" \"path_image \\<gamma> \\<subseteq> UNIV\" \"valid_path \\<gamma>\"\n      using \\<open>valid_path \\<gamma>\\<close> by (auto intro:holomorphic_intros)\n    show \"z \\<notin> path_image (uminus \\<circ> \\<gamma>)\" \n      unfolding path_image_compose using \\<open>- z \\<notin> path_image \\<gamma>\\<close> by auto\n  qed\n  also have \"\\<dots> = 1/c * contour_integral \\<gamma> (\\<lambda>w. 1 / (w- (-z)))\"\n    by (auto intro!:contour_integral_eq simp add:field_simps minus_divide_right)\n  also have \"\\<dots> = winding_number \\<gamma> (-z)\"\n    using winding_number_valid_path[OF \\<open>valid_path \\<gamma>\\<close> \\<open>- z \\<notin> path_image \\<gamma>\\<close>,folded c_def]\n    by simp\n  finally show ?thesis by auto\nqed  \n  \nlemma winding_number_comp_linear:\n  assumes \"c\\<noteq>0\" \"valid_path \\<gamma>\" and not_image: \"(z-b)/c \\<notin> path_image \\<gamma>\"\n  shows \"winding_number ((\\<lambda>x. c*x+b) \\<circ> \\<gamma>) z = winding_number \\<gamma> ((z-b)/c)\" (is \"?L = ?R\")\nproof -\n  define cc where \"cc=1 / (complex_of_real (2 * pi) * \\<i>)\"\n  define zz where \"zz=(z-b)/c\"\n  have \"?L = cc * contour_integral \\<gamma> (\\<lambda>w. deriv (\\<lambda>x. c * x + b) w / (c * w + b - z))\"\n    apply (subst winding_number_comp[of UNIV,simplified])\n    subgoal by (auto intro:holomorphic_intros)\n    subgoal using \\<open>valid_path \\<gamma>\\<close> .\n    subgoal using not_image \\<open>c\\<noteq>0\\<close> unfolding path_image_compose by auto\n    subgoal unfolding cc_def by auto\n    done\n  also have \"\\<dots> = cc * contour_integral \\<gamma> (\\<lambda>w.1 / (w - zz))\"\n  proof -\n    have \"deriv (\\<lambda>x. c * x + b) = (\\<lambda>x. c)\"\n      by (auto intro:derivative_intros) \n    then show ?thesis\n      unfolding zz_def cc_def using \\<open>c\\<noteq>0\\<close>\n      by (auto simp:field_simps)\n  qed\n  also have \"\\<dots> = winding_number \\<gamma> zz\"\n    using winding_number_valid_path[OF \\<open>valid_path \\<gamma>\\<close> not_image,folded zz_def cc_def]\n    by simp\n  finally show \"winding_number ((\\<lambda>x. c * x + b) \\<circ> \\<gamma>) z = winding_number \\<gamma> zz\" .\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/Winding_Number_Eval/Missing_Analysis.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8824278788223265, "lm_q2_score": 0.8056321936479701, "lm_q1q2_score": 0.7109123077517561}}
{"text": "theory ex3_08 imports Main \"~~/src/HOL/IMP/AExp\" \"~~/src/HOL/IMP/BExp\" begin\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) _ = b\" |\n\"ifval (If b e1 e2) s = (if (ifval b s) then ifval e1 s else 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) (If (b2ifexp b2) (Bc2 True) (Bc2 False)) (Bc2 False)\" |\n\"b2ifexp (Less a1 a2) = Less2 a1 a2\"\n\nfun if2bexp :: \"ifexp \\<Rightarrow> bexp\" where\n\"if2bexp (Bc2 b) = Bc b\" |\n\"if2bexp (If b e1 e2) = (Not (And (Not (And (if2bexp b) (if2bexp e1))) (Not (And (Not (if2bexp b)) (if2bexp e2)))))\" |\n\"if2bexp (Less2 a1 a2) = Less a1 a2\"\n\ntheorem \"bval e s = ifval (b2ifexp e) s\"\napply(induction e)\napply auto\ndone\n\ntheorem \"ifval e s = bval (if2bexp e) s\"\napply(induction e)\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/chapter3/ex3_08.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278664544912, "lm_q2_score": 0.8056321959813274, "lm_q1q2_score": 0.7109122998468492}}
{"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  theory TIP_prop_78\n  imports \"../../Test_Base\"\nbegin\n\ndatatype 'a list = nil2 | cons2 \"'a\" \"'a list\"\n\ndatatype Nat = Z | S \"Nat\"\n\nfun x :: \"bool => bool => bool\" where\n  \"x True z = z\"\n| \"x False z = False\"\n\nfun t2 :: \"Nat => Nat => bool\" where\n  \"t2 (Z) z = True\"\n| \"t2 (S z2) (Z) = False\"\n| \"t2 (S z2) (S x2) = t2 z2 x2\"\n\nfun insort :: \"Nat => Nat list => Nat list\" where\n  \"insort y (nil2) = cons2 y (nil2)\"\n| \"insort y (cons2 z2 xs) =\n     (if t2 y z2 then cons2 y (cons2 z2 xs) else cons2 z2 (insort y xs))\"\n\nfun sort :: \"Nat list => Nat list\" where\n  \"sort (nil2) = nil2\"\n| \"sort (cons2 z xs) = insort z (sort xs)\"\n\nfun sorted :: \"Nat list => bool\" where\n  \"sorted (nil2) = True\"\n| \"sorted (cons2 z (nil2)) = True\"\n| \"sorted (cons2 z (cons2 y2 ys)) =\n     x (t2 z y2) (sorted (cons2 y2 ys))\"\n\ntheorem property0 :\n  \"sorted (sort 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/Isaplanner/Isaplanner/TIP_prop_78.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278757303677, "lm_q2_score": 0.8056321866478979, "lm_q1q2_score": 0.7109122990837157}}
{"text": "(*\n  File: Abs.thy\n  Author: Bohua Zhan\n\n  Basic results about absolute value.\n*)\n\ntheory Abs\n  imports Field\nbegin\n\nsection \\<open>Absolute value\\<close>\n\ndefinition abs :: \"i \\<Rightarrow> i \\<Rightarrow> i\"  (\"\\<bar>_\\<bar>\\<^sub>_\" [0,91] 90) where [rewrite]:\n  \"\\<bar>x\\<bar>\\<^sub>R = (if x \\<ge>\\<^sub>R \\<zero>\\<^sub>R then x else -\\<^sub>R x)\"\nsetup {* register_wellform_data (\"\\<bar>x\\<bar>\\<^sub>R\", [\"x \\<in>. R\"]) *}\n\nsetup {* add_gen_prfstep (\"abs_case\",\n  [WithTerm @{term_pat \"\\<bar>?x\\<bar>\\<^sub>?R\"}, CreateCase @{term_pat \"?x \\<ge>\\<^sub>?R \\<zero>\\<^sub>?R\"}]) *}\n\nlemma abs_nonneg [rewrite]: \"x \\<ge>\\<^sub>R \\<zero>\\<^sub>R \\<Longrightarrow> \\<bar>x\\<bar>\\<^sub>R = x\" by auto2\nlemma abs_neg [rewrite]: \"is_ord_ring(R) \\<Longrightarrow> x \\<le>\\<^sub>R \\<zero>\\<^sub>R \\<Longrightarrow> \\<bar>x\\<bar>\\<^sub>R = -\\<^sub>R x\" by auto2\nlemma abs_mem [typing]: \"is_ord_ring(R) \\<Longrightarrow> x \\<in>. R \\<Longrightarrow> \\<bar>x\\<bar>\\<^sub>R \\<in>. R\" by auto2\nsetup {* del_prfstep_thm @{thm abs_def} *}\n\nlemma abs_zero [rewrite]: \"is_ord_ring(R) \\<Longrightarrow> \\<bar>\\<zero>\\<^sub>R\\<bar>\\<^sub>R = \\<zero>\\<^sub>R\" by auto2\nlemma abs_minus [rewrite]: \"is_ord_ring(R) \\<Longrightarrow> x \\<in>. R \\<Longrightarrow> \\<bar>-\\<^sub>R x\\<bar>\\<^sub>R = \\<bar>x\\<bar>\\<^sub>R\" by auto2\nlemma abs_not_less_zero [resolve]: \"is_ord_ring(R) \\<Longrightarrow> x \\<in>. R \\<Longrightarrow> \\<bar>x\\<bar>\\<^sub>R \\<ge>\\<^sub>R \\<zero>\\<^sub>R\" by auto2\nlemma abs_le_zero [forward]: \"is_ord_ring(R) \\<Longrightarrow> x \\<in>. R \\<Longrightarrow> \\<bar>x\\<bar>\\<^sub>R \\<le>\\<^sub>R \\<zero>\\<^sub>R \\<Longrightarrow> x = \\<zero>\\<^sub>R\" by auto2\nlemma abs_positive [rewrite]: \"is_ord_ring(R) \\<Longrightarrow> x \\<in>. R \\<Longrightarrow> \\<bar>x\\<bar>\\<^sub>R >\\<^sub>R \\<zero>\\<^sub>R \\<longleftrightarrow> x \\<noteq> \\<zero>\\<^sub>R\" by auto2\nlemma abs_mult [rewrite]: \"is_ord_ring(R) \\<Longrightarrow> x \\<in>. R \\<Longrightarrow> y \\<in>. R \\<Longrightarrow> \\<bar>x *\\<^sub>R y\\<bar>\\<^sub>R = \\<bar>x\\<bar>\\<^sub>R *\\<^sub>R \\<bar>y\\<bar>\\<^sub>R\" by auto2\nlemma abs_inverse [rewrite]: \"is_ord_field(R) \\<Longrightarrow> x \\<in> units(R) \\<Longrightarrow> \\<bar>inv(R,x)\\<bar>\\<^sub>R = inv(R,\\<bar>x\\<bar>\\<^sub>R)\" by auto2\nlemma abs_div [rewrite]: \"is_ord_field(R) \\<Longrightarrow> x \\<in>. R \\<Longrightarrow> y \\<in> units(R) \\<Longrightarrow> \\<bar>x /\\<^sub>R y\\<bar>\\<^sub>R = \\<bar>x\\<bar>\\<^sub>R /\\<^sub>R \\<bar>y\\<bar>\\<^sub>R\"\n  @proof @have \"x /\\<^sub>R y = x *\\<^sub>R inv(R,y)\" @have \"\\<bar>x\\<bar>\\<^sub>R /\\<^sub>R \\<bar>y\\<bar>\\<^sub>R = \\<bar>x\\<bar>\\<^sub>R *\\<^sub>R inv(R,\\<bar>y\\<bar>\\<^sub>R)\" @qed\n\nlemma abs_ge_cases [forward]:\n  \"is_ord_ring(R) \\<Longrightarrow> x \\<in>. R \\<Longrightarrow> r \\<in>. R \\<Longrightarrow> \\<bar>x\\<bar>\\<^sub>R \\<ge>\\<^sub>R r \\<Longrightarrow> x >\\<^sub>R -\\<^sub>R r \\<Longrightarrow> x \\<ge>\\<^sub>R r\"\n  \"is_ord_ring(R) \\<Longrightarrow> x \\<in>. R \\<Longrightarrow> r \\<in>. R \\<Longrightarrow> \\<bar>x\\<bar>\\<^sub>R \\<ge>\\<^sub>R r \\<Longrightarrow> x <\\<^sub>R r \\<Longrightarrow> x \\<le>\\<^sub>R -\\<^sub>R r\" by auto2+\n\nlemma abs_gt_cases [forward]:\n  \"is_ord_ring(R) \\<Longrightarrow> x \\<in>. R \\<Longrightarrow> r \\<in>. R \\<Longrightarrow> \\<bar>x\\<bar>\\<^sub>R >\\<^sub>R r \\<Longrightarrow> x \\<ge>\\<^sub>R -\\<^sub>R r \\<Longrightarrow> x >\\<^sub>R r\"\n  \"is_ord_ring(R) \\<Longrightarrow> x \\<in>. R \\<Longrightarrow> r \\<in>. R \\<Longrightarrow> \\<bar>x\\<bar>\\<^sub>R >\\<^sub>R r \\<Longrightarrow> x \\<le>\\<^sub>R r \\<Longrightarrow> x <\\<^sub>R -\\<^sub>R r\" by auto2+\n\nlemma abs_le [resolve]:\n  \"is_ord_ring(R) \\<Longrightarrow> x \\<in>. R \\<Longrightarrow> \\<bar>x\\<bar>\\<^sub>R \\<le>\\<^sub>R r \\<Longrightarrow> x \\<le>\\<^sub>R r\"\n  \"is_ord_ring(R) \\<Longrightarrow> x \\<in>. R \\<Longrightarrow> \\<bar>x\\<bar>\\<^sub>R \\<le>\\<^sub>R r \\<Longrightarrow> x \\<ge>\\<^sub>R -\\<^sub>R r\" by auto2+\n\nlemma abs_less [resolve]:\n  \"is_ord_ring(R) \\<Longrightarrow> x \\<in>. R \\<Longrightarrow> \\<bar>x\\<bar>\\<^sub>R <\\<^sub>R r \\<Longrightarrow> x <\\<^sub>R r\"\n  \"is_ord_ring(R) \\<Longrightarrow> x \\<in>. R \\<Longrightarrow> \\<bar>x\\<bar>\\<^sub>R <\\<^sub>R r \\<Longrightarrow> x >\\<^sub>R -\\<^sub>R r\" by auto2+\n\nlemma abs_diff_nonneg [rewrite]:\n  \"is_ord_ring(R) \\<Longrightarrow> a \\<in>. R \\<Longrightarrow> b \\<in>. R \\<Longrightarrow> a \\<ge>\\<^sub>R b \\<Longrightarrow> \\<bar>a -\\<^sub>R b\\<bar>\\<^sub>R = a -\\<^sub>R b\" by auto2\n\nsetup {* del_prfstep \"abs_case\" *}\n  \nlemma abs_diff_sym [rewrite]:\n  \"is_ord_ring(R) \\<Longrightarrow> x \\<in>. R \\<Longrightarrow> y \\<in>. R \\<Longrightarrow> \\<bar>x -\\<^sub>R y\\<bar>\\<^sub>R = \\<bar>y -\\<^sub>R x\\<bar>\\<^sub>R\"\n@proof @have \"y -\\<^sub>R x = -\\<^sub>R (x -\\<^sub>R y)\" @qed\n\nlemma abs_sum [backward1, backward2]:\n  \"is_ord_ring(R) \\<Longrightarrow> x \\<in>. R \\<Longrightarrow> y \\<in>. R \\<Longrightarrow> \\<bar>x\\<bar>\\<^sub>R \\<le>\\<^sub>R s \\<Longrightarrow> \\<bar>y\\<bar>\\<^sub>R \\<le>\\<^sub>R t \\<Longrightarrow> \\<bar>x +\\<^sub>R y\\<bar>\\<^sub>R \\<le>\\<^sub>R s +\\<^sub>R t\"\n@proof\n  @have \"x +\\<^sub>R y \\<le>\\<^sub>R s +\\<^sub>R t\" @with @have \"x \\<le>\\<^sub>R s\" @end\n  @have \"x +\\<^sub>R y \\<ge>\\<^sub>R -\\<^sub>R s +\\<^sub>R -\\<^sub>R t\" @with @have \"x \\<ge>\\<^sub>R -\\<^sub>R s\" @end\n@qed\n      \nlemma abs_sum_strict1 [backward1, backward2]:\n  \"is_ord_ring(R) \\<Longrightarrow> x \\<in>. R \\<Longrightarrow> y \\<in>. R \\<Longrightarrow> \\<bar>x\\<bar>\\<^sub>R <\\<^sub>R s \\<Longrightarrow> \\<bar>y\\<bar>\\<^sub>R \\<le>\\<^sub>R t \\<Longrightarrow> \\<bar>x +\\<^sub>R y\\<bar>\\<^sub>R <\\<^sub>R s +\\<^sub>R t\"\n@proof\n  @have \"x +\\<^sub>R y <\\<^sub>R s +\\<^sub>R t\" @with @have \"x <\\<^sub>R s\" @end\n  @have \"x +\\<^sub>R y >\\<^sub>R -\\<^sub>R s +\\<^sub>R -\\<^sub>R t\" @with @have \"x >\\<^sub>R -\\<^sub>R s\" @end\n@qed\n\nlemma abs_sum_strict2 [backward1, backward2]:\n  \"is_ord_ring(R) \\<Longrightarrow> x \\<in>. R \\<Longrightarrow> y \\<in>. R \\<Longrightarrow> \\<bar>x\\<bar>\\<^sub>R \\<le>\\<^sub>R s \\<Longrightarrow> \\<bar>y\\<bar>\\<^sub>R <\\<^sub>R t \\<Longrightarrow> \\<bar>x +\\<^sub>R y\\<bar>\\<^sub>R <\\<^sub>R s +\\<^sub>R t\"\n@proof\n  @have \"x +\\<^sub>R y <\\<^sub>R s +\\<^sub>R t\" @with @have \"x \\<le>\\<^sub>R s\" @end\n  @have \"x +\\<^sub>R y >\\<^sub>R -\\<^sub>R s +\\<^sub>R -\\<^sub>R t\" @with @have \"x \\<ge>\\<^sub>R -\\<^sub>R s\" @end\n@qed\n\nlemma abs_sum_half1 [backward1, backward2]:\n  \"is_ord_field(R) \\<Longrightarrow> x \\<in>. R \\<Longrightarrow> y \\<in>. R \\<Longrightarrow> r \\<in>. R \\<Longrightarrow> \\<bar>x\\<bar>\\<^sub>R <\\<^sub>R r /\\<^sub>R 2\\<^sub>R \\<Longrightarrow> \\<bar>y\\<bar>\\<^sub>R <\\<^sub>R r /\\<^sub>R 2\\<^sub>R \\<Longrightarrow> \\<bar>x +\\<^sub>R y\\<bar>\\<^sub>R <\\<^sub>R r\"\n@proof @have \"r = r /\\<^sub>R 2\\<^sub>R +\\<^sub>R r /\\<^sub>R 2\\<^sub>R\" @qed\n\nlemma abs_cancel_diff [backward1, backward2]:\n  \"is_ord_ring(R) \\<Longrightarrow> x \\<in>. R \\<Longrightarrow> y \\<in>. R \\<Longrightarrow> z \\<in>. R \\<Longrightarrow>\n   \\<bar>x -\\<^sub>R y\\<bar>\\<^sub>R \\<le>\\<^sub>R s \\<Longrightarrow> \\<bar>y -\\<^sub>R z\\<bar>\\<^sub>R \\<le>\\<^sub>R t \\<Longrightarrow> \\<bar>x -\\<^sub>R z\\<bar>\\<^sub>R \\<le>\\<^sub>R s +\\<^sub>R t\"\n@proof @have \"x -\\<^sub>R z = (x -\\<^sub>R y) +\\<^sub>R (y -\\<^sub>R z)\" @qed\n\nlemma abs_cancel_diff_strict1 [backward1, backward2]:\n  \"is_ord_ring(R) \\<Longrightarrow> x \\<in>. R \\<Longrightarrow> y \\<in>. R \\<Longrightarrow> z \\<in>. R \\<Longrightarrow>\n   \\<bar>x -\\<^sub>R y\\<bar>\\<^sub>R <\\<^sub>R s \\<Longrightarrow> \\<bar>y -\\<^sub>R z\\<bar>\\<^sub>R \\<le>\\<^sub>R t \\<Longrightarrow> \\<bar>x -\\<^sub>R z\\<bar>\\<^sub>R <\\<^sub>R s +\\<^sub>R t\"\n@proof @have \"x -\\<^sub>R z = (x -\\<^sub>R y) +\\<^sub>R (y -\\<^sub>R z)\" @qed\n\nlemma abs_cancel_diff_strict2 [backward1, backward2]:\n  \"is_ord_ring(R) \\<Longrightarrow> x \\<in>. R \\<Longrightarrow> y \\<in>. R \\<Longrightarrow> z \\<in>. R \\<Longrightarrow>\n   \\<bar>x -\\<^sub>R y\\<bar>\\<^sub>R <\\<^sub>R s \\<Longrightarrow> \\<bar>y -\\<^sub>R z\\<bar>\\<^sub>R <\\<^sub>R t \\<Longrightarrow> \\<bar>x -\\<^sub>R z\\<bar>\\<^sub>R <\\<^sub>R s +\\<^sub>R t\" by auto2\n\nlemma abs_cancel_diff_half1 [backward1, backward2]:\n  \"is_ord_field(R) \\<Longrightarrow> x \\<in>. R \\<Longrightarrow> y \\<in>. R \\<Longrightarrow> z \\<in>. R \\<Longrightarrow> r \\<in>. R \\<Longrightarrow>\n   \\<bar>x -\\<^sub>R y\\<bar>\\<^sub>R <\\<^sub>R r /\\<^sub>R 2\\<^sub>R \\<Longrightarrow> \\<bar>y -\\<^sub>R z\\<bar>\\<^sub>R <\\<^sub>R r /\\<^sub>R 2\\<^sub>R \\<Longrightarrow> \\<bar>x -\\<^sub>R z\\<bar>\\<^sub>R <\\<^sub>R r\"\n@proof @have \"r = r /\\<^sub>R 2\\<^sub>R +\\<^sub>R r /\\<^sub>R 2\\<^sub>R\" @qed\n\nlemma abs_prod_upper_bound [backward1, backward2]:\n  \"is_ord_field(R) \\<Longrightarrow> x \\<in>. R \\<Longrightarrow> y \\<in>. R \\<Longrightarrow> \\<bar>x\\<bar>\\<^sub>R <\\<^sub>R s \\<Longrightarrow> \\<bar>y\\<bar>\\<^sub>R <\\<^sub>R t \\<Longrightarrow> \\<bar>x *\\<^sub>R y\\<bar>\\<^sub>R <\\<^sub>R s *\\<^sub>R t\"\n@proof @contradiction @have \"\\<bar>x *\\<^sub>R y\\<bar>\\<^sub>R \\<noteq> s *\\<^sub>R t\" @qed\n\nlemma abs_prod_upper_bound2 [backward2]:\n  \"is_ord_field(R) \\<Longrightarrow> x \\<in>. R \\<Longrightarrow> y \\<in>. R \\<Longrightarrow> s \\<in>. R \\<Longrightarrow> t \\<in> units(R) \\<Longrightarrow>\n   \\<bar>x\\<bar>\\<^sub>R <\\<^sub>R s /\\<^sub>R t \\<Longrightarrow> \\<bar>y\\<bar>\\<^sub>R <\\<^sub>R t \\<Longrightarrow> \\<bar>x *\\<^sub>R y\\<bar>\\<^sub>R <\\<^sub>R s\"\n@proof @have \"s = (s /\\<^sub>R t) *\\<^sub>R t\" @qed\n\nlemma abs_prod_upper_bound2' [backward2]:\n  \"is_ord_field(R) \\<Longrightarrow> x \\<in>. R \\<Longrightarrow> y \\<in>. R \\<Longrightarrow> s \\<in>. R \\<Longrightarrow> t \\<in> units(R) \\<Longrightarrow>\n   \\<bar>x\\<bar>\\<^sub>R <\\<^sub>R s /\\<^sub>R t \\<Longrightarrow> \\<bar>y\\<bar>\\<^sub>R <\\<^sub>R t \\<Longrightarrow> \\<bar>y *\\<^sub>R x\\<bar>\\<^sub>R <\\<^sub>R s\"\n@proof @have \"x *\\<^sub>R y = y *\\<^sub>R x\" @qed\n\nlemma abs_prod_lower_bound [backward1]:\n  \"is_ord_field(R) \\<Longrightarrow> x \\<in>. R \\<Longrightarrow> y \\<in>. R \\<Longrightarrow> s >\\<^sub>R \\<zero>\\<^sub>R \\<Longrightarrow> t >\\<^sub>R \\<zero>\\<^sub>R \\<Longrightarrow>\n   \\<bar>x\\<bar>\\<^sub>R >\\<^sub>R s \\<Longrightarrow> \\<bar>y\\<bar>\\<^sub>R >\\<^sub>R t \\<Longrightarrow> \\<bar>x *\\<^sub>R y\\<bar>\\<^sub>R >\\<^sub>R s *\\<^sub>R t\" by auto2\n  \nlemma abs_div_upper_bound [backward2]:\n  \"is_ord_field(R) \\<Longrightarrow> x \\<in>. R \\<Longrightarrow> y \\<in>. R \\<Longrightarrow> \\<bar>x\\<bar>\\<^sub>R <\\<^sub>R a \\<Longrightarrow> \\<bar>y\\<bar>\\<^sub>R >\\<^sub>R b \\<and> b >\\<^sub>R \\<zero>\\<^sub>R \\<Longrightarrow> \\<bar>x /\\<^sub>R y\\<bar>\\<^sub>R <\\<^sub>R a /\\<^sub>R b\"\n@proof @have \"\\<bar>x\\<bar>\\<^sub>R *\\<^sub>R inv(R,\\<bar>y\\<bar>\\<^sub>R) <\\<^sub>R a *\\<^sub>R inv(R,b)\" @qed\n      \nlemma abs_div_upper_bound2 [backward2]:\n  \"is_ord_field(R) \\<Longrightarrow> x \\<in>. R \\<Longrightarrow> y \\<in> units(R) \\<Longrightarrow> s \\<in>. R \\<Longrightarrow>\n   \\<bar>x\\<bar>\\<^sub>R <\\<^sub>R s *\\<^sub>R t \\<Longrightarrow> \\<bar>y\\<bar>\\<^sub>R >\\<^sub>R t \\<and> t >\\<^sub>R \\<zero>\\<^sub>R \\<Longrightarrow> \\<bar>x /\\<^sub>R y\\<bar>\\<^sub>R <\\<^sub>R s\"\n@proof @have \"s = s *\\<^sub>R t /\\<^sub>R t\" @qed\n\n(* Bounds on Abs in terms of components. *)\nlemma abs_sum_bound [resolve]:\n  \"is_ord_ring(R) \\<Longrightarrow> a \\<in>. R \\<Longrightarrow> b \\<in>. R \\<Longrightarrow> \\<bar>a +\\<^sub>R b\\<bar>\\<^sub>R \\<le>\\<^sub>R \\<bar>a\\<bar>\\<^sub>R +\\<^sub>R \\<bar>b\\<bar>\\<^sub>R\"\n@proof @have \"\\<bar>a\\<bar>\\<^sub>R \\<le>\\<^sub>R \\<bar>a\\<bar>\\<^sub>R\" @qed\n\nlemma abs_diff_to_abs_bound [resolve]:\n  \"is_ord_field(R) \\<Longrightarrow> a \\<in>. R \\<Longrightarrow> b \\<in>. R \\<Longrightarrow> c \\<in>. R \\<Longrightarrow> \\<bar>a -\\<^sub>R b\\<bar>\\<^sub>R <\\<^sub>R c \\<Longrightarrow> \\<bar>a\\<bar>\\<^sub>R <\\<^sub>R \\<bar>b\\<bar>\\<^sub>R +\\<^sub>R c\"\n@proof @have \"\\<bar>b +\\<^sub>R (a -\\<^sub>R b)\\<bar>\\<^sub>R \\<le>\\<^sub>R \\<bar>b\\<bar>\\<^sub>R +\\<^sub>R \\<bar>a -\\<^sub>R b\\<bar>\\<^sub>R\" @qed\n\n(* Bounds on differences to averages *)\nsetup {* add_rewrite_rule @{thm avg_def} *}\nlemma avg_diff [rewrite]:\n  \"is_ord_field(R) \\<Longrightarrow> a \\<in>. R \\<Longrightarrow> b \\<in>. R \\<Longrightarrow> \\<bar>a -\\<^sub>R avg(R,a,b)\\<bar>\\<^sub>R = \\<bar>a -\\<^sub>R b\\<bar>\\<^sub>R /\\<^sub>R 2\\<^sub>R\"\n@proof\n  @case \"a \\<le>\\<^sub>R b\" @with\n    @have \"a \\<le>\\<^sub>R avg(R,a,b)\" @have \"(a +\\<^sub>R b) /\\<^sub>R 2\\<^sub>R -\\<^sub>R a = (b -\\<^sub>R a) /\\<^sub>R 2\\<^sub>R\" @end\n  @case \"a \\<ge>\\<^sub>R b\" @with\n    @have \"a \\<ge>\\<^sub>R avg(R,a,b)\" @have \"a -\\<^sub>R (a +\\<^sub>R b) /\\<^sub>R 2\\<^sub>R = (a -\\<^sub>R b) /\\<^sub>R 2\\<^sub>R\" @end\n@qed\n\nlemma avg_diff2 [rewrite]:\n  \"is_ord_field(R) \\<Longrightarrow> a \\<in>. R \\<Longrightarrow> b \\<in>. R \\<Longrightarrow> \\<bar>b -\\<^sub>R avg(R,a,b)\\<bar>\\<^sub>R = \\<bar>a -\\<^sub>R b\\<bar>\\<^sub>R /\\<^sub>R 2\\<^sub>R\"\n@proof @have \"avg(R,a,b) = avg(R,b,a)\" @qed\nsetup {* del_prfstep_thm @{thm avg_def} *}\n\n(* Two redundancies *)\nsetup {* add_gen_prfstep (\"shadow_abs_upper_triv\",\n  [WithProperty @{term_pat \"is_ord_ring(?R)\"},\n   WithFact @{term_pat \"\\<bar>?x -\\<^sub>?R ?x\\<bar>\\<^sub>R <\\<^sub>?R ?r\"},\n   WithFact @{term_pat \"?r >\\<^sub>?R \\<zero>\\<^sub>?R\"}, ShadowFirst]) *}\nsetup {* add_gen_prfstep (\"shadow_abs_upper_sym\",\n  [WithProperty @{term_pat \"is_ord_ring(?R)\"},\n   WithFact @{term_pat \"\\<bar>?x -\\<^sub>?R ?y\\<bar>\\<^sub>?R <\\<^sub>?R ?r\"},\n   WithFact @{term_pat \"\\<bar>?y -\\<^sub>?R ?x\\<bar>\\<^sub>?R <\\<^sub>?R ?r\"}, ShadowSecond]) *}\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/Abs.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8824278757303678, "lm_q2_score": 0.805632181981183, "lm_q1q2_score": 0.7109122949656764}}
{"text": "theory AExp\n  imports Main\nbegin\n\n(* syntax  *)\ntype_synonym vname = string\ndatatype aexp = N int | V vname | Plus aexp aexp | Times aexp aexp\n\n(* semantics  *)\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\n(* local optimizations *)\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[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\" 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[simp]: \"aval (times a1 a2) s = aval a1 s * aval a2 s\"\n  apply(induction a1 a2 rule: times.induct)\n  apply(auto)\n  done\n\n(* term traversing *)\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 asimp_correctness[simp]: \"aval (asimp a) s = aval a s\"\n  apply(induction a)\n  apply(auto)\n  done\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/AExp.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278602705731, "lm_q2_score": 0.8056321959813275, "lm_q1q2_score": 0.7109122948648858}}
{"text": "theory Isar_Demo\nimports Complex_Main\nbegin\n\nsection \"An introductory 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\ntext \\<open>A bit shorter:\\<close>\n\nlemma \"\\<not> surj(f :: 'a \\<Rightarrow> 'a set)\"\nproof\n  assume 0: \"surj f\"\n  from 0 have 1: \"\\<exists>a. {x. x \\<notin> f x} = f a\" by(auto simp: surj_def)\n  from 1 show \"False\" by blast\nqed\n\nsubsection \\<open>\"this\", \"then\", \"hence\" and \"thus\\<close>\n\ntext \\<open>Avoid labels, use \"this\"\\<close>\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 simp: surj_def)\n  from this show \"False\" by blast\nqed\n\ntext \\<open>\"then\" = \"from this\"\\<close>\n\nlemma \"\\<not> surj(f :: 'a \\<Rightarrow> 'a set)\"\nproof\n  assume \"surj f\"\n  then have \"\\<exists>a. {x. x \\<notin> f x} = f a\" by(auto simp: surj_def)\n  then show \"False\" by blast\nqed\n\ntext \\<open>\"hence\" = \"then have\", \"thus\" = \"then show\"\\<close>\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  thus \"False\" by blast\nqed\n\n\nsubsection \\<open>Structured statements: \"fixes\", \"assumes\", \"shows\"\\<close>\n\nlemma\n  fixes f :: \"'a \\<Rightarrow> 'a set\"\n  assumes s: \"surj f\"\n  shows \"False\"\nproof -  (* no automatic proof step! *)\n  have \"\\<exists> a. {x. x \\<notin> f x} = f a\" using s\n    by(auto simp: surj_def)\n  thus \"False\" by blast\nqed\n\n\nsection \"Proof patterns\"\n\nlemma \"P \\<longleftrightarrow> Q\"\nproof\n  assume \"P\"\n  show \"Q\" sorry\nnext\n  assume \"Q\"\n  show \"P\" sorry\nqed\n\nlemma \"A = (B::'a set)\"\nproof\n  show \"A \\<subseteq> B\" sorry\nnext\n  show \"B \\<subseteq> A\" sorry\nqed\n\nlemma \"A \\<subseteq> B\"\nproof\n  fix a\n  assume \"a \\<in> A\"\n  show \"a \\<in> B\" sorry\nqed\n\ntext \"Contradiction\"\n\nlemma P\nproof (rule ccontr)\n  assume \"\\<not>P\"\n  show \"False\" sorry\nqed\n\ntext \"Case distinction\"\n\nlemma \"R\"\nproof cases\n  assume \"P\"\n  show \"R\" sorry\nnext\n  assume \"\\<not> P\"\n  show \"R\" sorry\nqed\n\nlemma \"R\"\nproof -\n  have \"P \\<or> Q\" sorry\n  then show \"R\"\n  proof\n    assume \"P\"\n    show \"R\" sorry\n  next\n    assume \"Q\"\n    show \"R\" sorry\n  qed\nqed\n\n\ntext \\<open>\"obtain\" example\\<close>\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\ntext \\<open>Interactive exercise:\\<close>\n\nlemma assumes \"\\<exists>x. \\<forall>y. P x y\" shows \"\\<forall>y. \\<exists>x. P x y\"\nsorry\n\n\nsubsection \\<open>(In)Equation Chains\\<close>\n\nlemma \"(0::real) \\<le> x^2 + y^2 - 2*x*y\"\nproof -\n  have \"0 \\<le> (x - y)^2\" by simp\n  also have \"\\<dots> = x^2 + y^2 - 2*x*y\"\n    by(simp add: numeral_eq_Suc algebra_simps)\n  finally show \"0 \\<le> x^2 + y^2 - 2*x*y\" .\nqed\n\ntext \\<open>Interactive exercise:\\<close>\n\nlemma\n  fixes x y :: real\n  assumes \"x \\<ge> y\" \"y > 0\"\n  shows \"(x - y) ^ 2 \\<le> x^2 - y^2\"\nproof -\n  have \"(x - y) ^ 2 = x^2 + y^2 - 2*x*y\"\n    by(simp add: numeral_eq_Suc algebra_simps)\n  show \"(x - y) ^ 2 \\<le> x^2 - y^2\" sorry\nqed\n\n\nsection \"Streamlining proofs\"\n\nsubsection \"Pattern matching and ?-variables\"\n\ntext \\<open>Show \\<open>\\<exists>\\<close>\\<close>\n\nlemma \"\\<exists> xs. length xs = 0\" (is \"\\<exists> xs. ?P xs\")\nproof\n  show \"?P([])\" by simp\nqed\n\ntext \\<open>Multiple EX easier with forward proof:\\<close>\n\nlemma \"\\<exists> x y :: int. x < z & z < y\" (is \"\\<exists> x y. ?P x y\")\nproof -\n  have \"?P (z - 1) (z + 1)\" by arith\n  thus ?thesis by blast\nqed\n\n\nsubsection \"Quoting facts\"\n\nlemma assumes \"x < (0::int)\" shows \"x*x > 0\"\nproof -\n  from `x<0` show ?thesis by(metis mult_neg_neg)\nqed\n\n\nsubsection \"Example: Top Down Proof Development\"\n\nlemma \"\\<exists>ys zs. xs = ys @ zs \\<and>\n          (length ys = length zs \\<or> length ys = length zs + 1)\"\nsorry\n\n\n\nsection \"Solutions to interactive exercises\"\n\nlemma assumes \"\\<exists>x. \\<forall>y. P x y\" shows \"\\<forall>y. \\<exists>x. P x y\"\nproof\n  fix b\n  from assms obtain a where 0: \"\\<forall>y. P a y\" by blast\n  show \"\\<exists>x. P x b\"\n  proof\n    show \"P a b\" using 0 by blast\n  qed\nqed\n\nlemma fixes x y :: real assumes \"x \\<ge> y\" \"y > 0\"\nshows \"(x - y) ^ 2 \\<le> x^2 - y^2\"\nproof -\n  have \"(x - y) ^ 2 = x^2 + y^2 - 2*x*y\"\n    by(simp add: numeral_eq_Suc algebra_simps)\n  also have \"\\<dots> \\<le> x^2 + y^2 - 2*y*y\"\n    using assms by(simp)\n  also have \"\\<dots> = x^2 - y^2\"\n    by(simp add: numeral_eq_Suc)\n  finally show ?thesis .\nqed\n\nsubsection \"Example: Top Down Proof Development\"\n\ntext \\<open>The key idea: case distinction on length:\\<close>\n\nlemma \"\\<exists>ys zs. xs = ys @ zs \\<and> (length ys = length zs \\<or> length ys = length zs + 1)\"\nproof cases\n  assume \"EX n. length xs = n+n\"\n  show ?thesis sorry\nnext\n  assume \"\\<not> (EX n. length xs = n+n)\"\n  show ?thesis sorry\nqed\n\ntext \\<open>A proof skeleton:\\<close>\n\nlemma \"\\<exists>ys zs. xs = ys @ zs \\<and> (length ys = length zs \\<or> length ys = length zs + 1)\"\nproof cases\n  assume \"\\<exists>n. length xs = n+n\"\n  then obtain n where \"length xs = n+n\" by blast\n  let ?ys = \"take n xs\"\n  let ?zs = \"take n (drop n xs)\"\n  have \"xs = ?ys @ ?zs \\<and> length ?ys = length ?zs\" sorry\n  thus ?thesis by blast\nnext\n  assume \"\\<not> (\\<exists>n. length xs = n+n)\"\n  then obtain n where \"length xs = Suc(n+n)\" sorry\n  let ?ys = \"take (Suc n) xs\"\n  let ?zs = \"take n (drop (Suc n) xs)\"\n  have \"xs = ?ys @ ?zs \\<and> length ?ys = length ?zs + 1\" sorry\n  then show ?thesis by blast\nqed\n\ntext \"The complete proof:\"\n\nlemma \"\\<exists>ys zs. xs = ys @ zs \\<and> (length ys = length zs \\<or> length ys = length zs + 1)\"\nproof cases\n  assume \"\\<exists>n. length xs = n+n\"\n  then obtain n where \"length xs = n+n\" by blast\n  let ?ys = \"take n xs\"\n  let ?zs = \"take n (drop n xs)\"\n  have \"xs = ?ys @ ?zs \\<and> length ?ys = length ?zs\"\n    by (simp add: `length xs = n + n`)\n  thus ?thesis by blast\nnext\n  assume \"\\<not> (\\<exists>n. length xs = n+n)\"\n  hence \"\\<exists>n. length xs = Suc(n+n)\" by arith\n  then obtain n where l: \"length xs = Suc(n+n)\" by blast\n  let ?ys = \"take (Suc n) xs\"\n  let ?zs = \"take n (drop (Suc n) xs)\"\n  have \"xs = ?ys @ ?zs \\<and> length ?ys = length ?zs + 1\" by (simp add: l)\n  thus ?thesis by blast\nqed\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/Isar_Demo.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321843145405, "lm_q2_score": 0.88242786954645, "lm_q1q2_score": 0.710912292042733}}
{"text": "(*  Title:      HOL/BNF_Cardinal_Arithmetic.thy\n    Author:     Dmitriy Traytel, TU Muenchen\n    Copyright   2012\n\nCardinal arithmetic as needed by bounded natural functors.\n*)\n\nsection \\<open>Cardinal Arithmetic as Needed by Bounded Natural Functors\\<close>\n\ntheory BNF_Cardinal_Arithmetic\nimports BNF_Cardinal_Order_Relation\nbegin\n\nlemma dir_image: \"\\<lbrakk>\\<And>x y. (f x = f y) = (x = y); Card_order r\\<rbrakk> \\<Longrightarrow> r =o dir_image r f\"\nby (rule dir_image_ordIso) (auto simp add: inj_on_def card_order_on_def)\n\nlemma card_order_dir_image:\n  assumes bij: \"bij f\" and co: \"card_order r\"\n  shows \"card_order (dir_image r f)\"\nproof -\n  from assms have \"Field (dir_image r f) = UNIV\"\n    using card_order_on_Card_order[of UNIV r] unfolding bij_def dir_image_Field by auto\n  moreover from bij have \"\\<And>x y. (f x = f y) = (x = y)\" unfolding bij_def inj_on_def by auto\n  with co have \"Card_order (dir_image r f)\"\n    using card_order_on_Card_order[of UNIV r] Card_order_ordIso2[OF _ dir_image] by blast\n  ultimately show ?thesis by auto\nqed\n\nlemma ordIso_refl: \"Card_order r \\<Longrightarrow> r =o r\"\nby (rule card_order_on_ordIso)\n\nlemma ordLeq_refl: \"Card_order r \\<Longrightarrow> r \\<le>o r\"\nby (rule ordIso_imp_ordLeq, rule card_order_on_ordIso)\n\nlemma card_of_ordIso_subst: \"A = B \\<Longrightarrow> |A| =o |B|\"\nby (simp only: ordIso_refl card_of_Card_order)\n\nlemma Field_card_order: \"card_order r \\<Longrightarrow> Field r = UNIV\"\nusing card_order_on_Card_order[of UNIV r] by simp\n\n\nsubsection \\<open>Zero\\<close>\n\ndefinition czero where\n  \"czero = card_of {}\"\n\nlemma czero_ordIso:\n  \"czero =o czero\"\nusing card_of_empty_ordIso by (simp add: czero_def)\n\nlemma card_of_ordIso_czero_iff_empty:\n  \"|A| =o (czero :: 'b rel) \\<longleftrightarrow> A = ({} :: 'a set)\"\nunfolding czero_def by (rule iffI[OF card_of_empty2]) (auto simp: card_of_refl card_of_empty_ordIso)\n\n(* A \"not czero\" Cardinal predicate *)\nabbreviation Cnotzero where\n  \"Cnotzero (r :: 'a rel) \\<equiv> \\<not>(r =o (czero :: 'a rel)) \\<and> Card_order r\"\n\n(*helper*)\nlemma Cnotzero_imp_not_empty: \"Cnotzero r \\<Longrightarrow> Field r \\<noteq> {}\"\n  unfolding Card_order_iff_ordIso_card_of czero_def by force\n\nlemma czeroI:\n  \"\\<lbrakk>Card_order r; Field r = {}\\<rbrakk> \\<Longrightarrow> r =o czero\"\nusing Cnotzero_imp_not_empty ordIso_transitive[OF _ czero_ordIso] by blast\n\nlemma czeroE:\n  \"r =o czero \\<Longrightarrow> Field r = {}\"\nunfolding czero_def\nby (drule card_of_cong) (simp only: Field_card_of card_of_empty2)\n\nlemma Cnotzero_mono:\n  \"\\<lbrakk>Cnotzero r; Card_order q; r \\<le>o q\\<rbrakk> \\<Longrightarrow> Cnotzero q\"\napply (rule ccontr)\napply auto\napply (drule czeroE)\napply (erule notE)\napply (erule czeroI)\napply (drule card_of_mono2)\napply (simp only: card_of_empty3)\ndone\n\nsubsection \\<open>(In)finite cardinals\\<close>\n\ndefinition cinfinite where\n  \"cinfinite r = (\\<not> finite (Field r))\"\n\nabbreviation Cinfinite where\n  \"Cinfinite r \\<equiv> cinfinite r \\<and> Card_order r\"\n\ndefinition cfinite where\n  \"cfinite r = finite (Field r)\"\n\nabbreviation Cfinite where\n  \"Cfinite r \\<equiv> cfinite r \\<and> Card_order r\"\n\nlemma Cfinite_ordLess_Cinfinite: \"\\<lbrakk>Cfinite r; Cinfinite s\\<rbrakk> \\<Longrightarrow> r <o s\"\n  unfolding cfinite_def cinfinite_def\n  by (blast intro: finite_ordLess_infinite card_order_on_well_order_on)\n\nlemmas natLeq_card_order = natLeq_Card_order[unfolded Field_natLeq]\n\nlemma natLeq_cinfinite: \"cinfinite natLeq\"\nunfolding cinfinite_def Field_natLeq by (rule infinite_UNIV_nat)\n\nlemma natLeq_Cinfinite: \"Cinfinite natLeq\"\n  using natLeq_cinfinite natLeq_Card_order by simp\n\nlemma natLeq_ordLeq_cinfinite:\n  assumes inf: \"Cinfinite r\"\n  shows \"natLeq \\<le>o r\"\nproof -\n  from inf have \"natLeq \\<le>o |Field r|\" unfolding cinfinite_def\n    using infinite_iff_natLeq_ordLeq by blast\n  also from inf have \"|Field r| =o r\" by (simp add: card_of_unique ordIso_symmetric)\n  finally show ?thesis .\nqed\n\nlemma cinfinite_not_czero: \"cinfinite r \\<Longrightarrow> \\<not> (r =o (czero :: 'a rel))\"\nunfolding cinfinite_def by (cases \"Field r = {}\") (auto dest: czeroE)\n\nlemma Cinfinite_Cnotzero: \"Cinfinite r \\<Longrightarrow> Cnotzero r\"\nby (rule conjI[OF cinfinite_not_czero]) simp_all\n\nlemma Cinfinite_cong: \"\\<lbrakk>r1 =o r2; Cinfinite r1\\<rbrakk> \\<Longrightarrow> Cinfinite r2\"\nusing Card_order_ordIso2[of r1 r2] unfolding cinfinite_def ordIso_iff_ordLeq\nby (auto dest: card_of_ordLeq_infinite[OF card_of_mono2])\n\nlemma cinfinite_mono: \"\\<lbrakk>r1 \\<le>o r2; cinfinite r1\\<rbrakk> \\<Longrightarrow> cinfinite r2\"\nunfolding cinfinite_def by (auto dest: card_of_ordLeq_infinite[OF card_of_mono2])\n\nlemma regularCard_ordIso:\nassumes  \"k =o k'\" and \"Cinfinite k\" and \"regularCard k\"\nshows \"regularCard k'\"\nproof-\n  have \"stable k\" using assms cinfinite_def regularCard_stable by blast\n  hence \"stable k'\" using assms stable_ordIso1 ordIso_symmetric by blast\n  thus ?thesis using assms cinfinite_def stable_regularCard\n    using Cinfinite_cong by blast\nqed\n\ncorollary card_of_UNION_ordLess_infinite_Field_regularCard:\nassumes ST: \"regularCard r\" and INF: \"Cinfinite r\" and\n        LEQ_I: \"|I| <o r\" and LEQ: \"\\<forall>i \\<in> I. |A i| <o r\"\n      shows \"|\\<Union>i \\<in> I. A i| <o r\"\n  using card_of_UNION_ordLess_infinite_Field regularCard_stable assms cinfinite_def by blast\n\nsubsection \\<open>Binary sum\\<close>\n\ndefinition csum (infixr \"+c\" 65) where\n  \"r1 +c r2 \\<equiv> |Field r1 <+> Field r2|\"\n\nlemma Field_csum: \"Field (r +c s) = Inl ` Field r \\<union> Inr ` Field s\"\n  unfolding csum_def Field_card_of by auto\n\nlemma Card_order_csum:\n  \"Card_order (r1 +c r2)\"\nunfolding csum_def by (simp add: card_of_Card_order)\n\nlemma csum_Cnotzero1:\n  \"Cnotzero r1 \\<Longrightarrow> Cnotzero (r1 +c r2)\"\nunfolding csum_def using Cnotzero_imp_not_empty[of r1] Plus_eq_empty_conv[of \"Field r1\" \"Field r2\"]\n   card_of_ordIso_czero_iff_empty[of \"Field r1 <+> Field r2\"] by (auto intro: card_of_Card_order)\n\nlemma card_order_csum:\n  assumes \"card_order r1\" \"card_order r2\"\n  shows \"card_order (r1 +c r2)\"\nproof -\n  have \"Field r1 = UNIV\" \"Field r2 = UNIV\" using assms card_order_on_Card_order by auto\n  thus ?thesis unfolding csum_def by (auto simp: card_of_card_order_on)\nqed\n\nlemma cinfinite_csum:\n  \"cinfinite r1 \\<or> cinfinite r2 \\<Longrightarrow> cinfinite (r1 +c r2)\"\nunfolding cinfinite_def csum_def by (auto simp: Field_card_of)\n\nlemma Cinfinite_csum1:\n  \"Cinfinite r1 \\<Longrightarrow> Cinfinite (r1 +c r2)\"\nunfolding cinfinite_def csum_def by (rule conjI[OF _ card_of_Card_order]) (auto simp: Field_card_of)\n\nlemma Cinfinite_csum:\n  \"Cinfinite r1 \\<or> Cinfinite r2 \\<Longrightarrow> Cinfinite (r1 +c r2)\"\nunfolding cinfinite_def csum_def by (rule conjI[OF _ card_of_Card_order]) (auto simp: Field_card_of)\n\nlemma Cinfinite_csum_weak:\n  \"\\<lbrakk>Cinfinite r1; Cinfinite r2\\<rbrakk> \\<Longrightarrow> Cinfinite (r1 +c r2)\"\nby (erule Cinfinite_csum1)\n\nlemma csum_cong: \"\\<lbrakk>p1 =o r1; p2 =o r2\\<rbrakk> \\<Longrightarrow> p1 +c p2 =o r1 +c r2\"\nby (simp only: csum_def ordIso_Plus_cong)\n\nlemma csum_cong1: \"p1 =o r1 \\<Longrightarrow> p1 +c q =o r1 +c q\"\nby (simp only: csum_def ordIso_Plus_cong1)\n\nlemma csum_cong2: \"p2 =o r2 \\<Longrightarrow> q +c p2 =o q +c r2\"\nby (simp only: csum_def ordIso_Plus_cong2)\n\nlemma csum_mono: \"\\<lbrakk>p1 \\<le>o r1; p2 \\<le>o r2\\<rbrakk> \\<Longrightarrow> p1 +c p2 \\<le>o r1 +c r2\"\nby (simp only: csum_def ordLeq_Plus_mono)\n\nlemma csum_mono1: \"p1 \\<le>o r1 \\<Longrightarrow> p1 +c q \\<le>o r1 +c q\"\nby (simp only: csum_def ordLeq_Plus_mono1)\n\nlemma csum_mono2: \"p2 \\<le>o r2 \\<Longrightarrow> q +c p2 \\<le>o q +c r2\"\nby (simp only: csum_def ordLeq_Plus_mono2)\n\nlemma ordLeq_csum1: \"Card_order p1 \\<Longrightarrow> p1 \\<le>o p1 +c p2\"\nby (simp only: csum_def Card_order_Plus1)\n\nlemma ordLeq_csum2: \"Card_order p2 \\<Longrightarrow> p2 \\<le>o p1 +c p2\"\nby (simp only: csum_def Card_order_Plus2)\n\nlemma csum_com: \"p1 +c p2 =o p2 +c p1\"\nby (simp only: csum_def card_of_Plus_commute)\n\nlemma csum_assoc: \"(p1 +c p2) +c p3 =o p1 +c p2 +c p3\"\nby (simp only: csum_def Field_card_of card_of_Plus_assoc)\n\nlemma Cfinite_csum: \"\\<lbrakk>Cfinite r; Cfinite s\\<rbrakk> \\<Longrightarrow> Cfinite (r +c s)\"\n  unfolding cfinite_def csum_def Field_card_of using card_of_card_order_on by simp\n\nlemma csum_csum: \"(r1 +c r2) +c (r3 +c r4) =o (r1 +c r3) +c (r2 +c r4)\"\nproof -\n  have \"(r1 +c r2) +c (r3 +c r4) =o r1 +c r2 +c (r3 +c r4)\"\n    by (rule csum_assoc)\n  also have \"r1 +c r2 +c (r3 +c r4) =o r1 +c (r2 +c r3) +c r4\"\n    by (intro csum_assoc csum_cong2 ordIso_symmetric)\n  also have \"r1 +c (r2 +c r3) +c r4 =o r1 +c (r3 +c r2) +c r4\"\n    by (intro csum_com csum_cong1 csum_cong2)\n  also have \"r1 +c (r3 +c r2) +c r4 =o r1 +c r3 +c r2 +c r4\"\n    by (intro csum_assoc csum_cong2 ordIso_symmetric)\n  also have \"r1 +c r3 +c r2 +c r4 =o (r1 +c r3) +c (r2 +c r4)\"\n    by (intro csum_assoc ordIso_symmetric)\n  finally show ?thesis .\nqed\n\nlemma Plus_csum: \"|A <+> B| =o |A| +c |B|\"\nby (simp only: csum_def Field_card_of card_of_refl)\n\nlemma Un_csum: \"|A \\<union> B| \\<le>o |A| +c |B|\"\nusing ordLeq_ordIso_trans[OF card_of_Un_Plus_ordLeq Plus_csum] by blast\n\nsubsection \\<open>One\\<close>\n\ndefinition cone where\n  \"cone = card_of {()}\"\n\nlemma Card_order_cone: \"Card_order cone\"\nunfolding cone_def by (rule card_of_Card_order)\n\nlemma Cfinite_cone: \"Cfinite cone\"\n  unfolding cfinite_def by (simp add: Card_order_cone)\n\nlemma cone_not_czero: \"\\<not> (cone =o czero)\"\nunfolding czero_def cone_def ordIso_iff_ordLeq using card_of_empty3 empty_not_insert by blast\n\nlemma cone_ordLeq_Cnotzero: \"Cnotzero r \\<Longrightarrow> cone \\<le>o r\"\nunfolding cone_def by (rule Card_order_singl_ordLeq) (auto intro: czeroI)\n\n\nsubsection \\<open>Two\\<close>\n\ndefinition ctwo where\n  \"ctwo = |UNIV :: bool set|\"\n\nlemma Card_order_ctwo: \"Card_order ctwo\"\nunfolding ctwo_def by (rule card_of_Card_order)\n\nlemma ctwo_not_czero: \"\\<not> (ctwo =o czero)\"\nusing card_of_empty3[of \"UNIV :: bool set\"] ordIso_iff_ordLeq\nunfolding czero_def ctwo_def using UNIV_not_empty by auto\n\nlemma ctwo_Cnotzero: \"Cnotzero ctwo\"\nby (simp add: ctwo_not_czero Card_order_ctwo)\n\n\nsubsection \\<open>Family sum\\<close>\n\ndefinition Csum where\n  \"Csum r rs \\<equiv> |SIGMA i : Field r. Field (rs i)|\"\n\n(* Similar setup to the one for SIGMA from theory Big_Operators: *)\nsyntax \"_Csum\" ::\n  \"pttrn => ('a * 'a) set => 'b * 'b set => (('a * 'b) * ('a * 'b)) set\"\n  (\"(3CSUM _:_. _)\" [0, 51, 10] 10)\n\ntranslations\n  \"CSUM i:r. rs\" == \"CONST Csum r (%i. rs)\"\n\nlemma SIGMA_CSUM: \"|SIGMA i : I. As i| = (CSUM i : |I|. |As i| )\"\nby (auto simp: Csum_def Field_card_of)\n\n(* NB: Always, under the cardinal operator,\noperations on sets are reduced automatically to operations on cardinals.\nThis should make cardinal reasoning more direct and natural.  *)\n\n\nsubsection \\<open>Product\\<close>\n\ndefinition cprod (infixr \"*c\" 80) where\n  \"r1 *c r2 = |Field r1 \\<times> Field r2|\"\n\nlemma card_order_cprod:\n  assumes \"card_order r1\" \"card_order r2\"\n  shows \"card_order (r1 *c r2)\"\nproof -\n  have \"Field r1 = UNIV\" \"Field r2 = UNIV\" using assms card_order_on_Card_order by auto\n  thus ?thesis by (auto simp: cprod_def card_of_card_order_on)\nqed\n\nlemma Card_order_cprod: \"Card_order (r1 *c r2)\"\nby (simp only: cprod_def Field_card_of card_of_card_order_on)\n\nlemma cprod_mono1: \"p1 \\<le>o r1 \\<Longrightarrow> p1 *c q \\<le>o r1 *c q\"\nby (simp only: cprod_def ordLeq_Times_mono1)\n\nlemma cprod_mono2: \"p2 \\<le>o r2 \\<Longrightarrow> q *c p2 \\<le>o q *c r2\"\nby (simp only: cprod_def ordLeq_Times_mono2)\n\nlemma cprod_mono: \"\\<lbrakk>p1 \\<le>o r1; p2 \\<le>o r2\\<rbrakk> \\<Longrightarrow> p1 *c p2 \\<le>o r1 *c r2\"\nby (rule ordLeq_transitive[OF cprod_mono1 cprod_mono2])\n\nlemma ordLeq_cprod2: \"\\<lbrakk>Cnotzero p1; Card_order p2\\<rbrakk> \\<Longrightarrow> p2 \\<le>o p1 *c p2\"\nunfolding cprod_def by (rule Card_order_Times2) (auto intro: czeroI)\n\nlemma cinfinite_cprod: \"\\<lbrakk>cinfinite r1; cinfinite r2\\<rbrakk> \\<Longrightarrow> cinfinite (r1 *c r2)\"\nby (simp add: cinfinite_def cprod_def Field_card_of infinite_cartesian_product)\n\nlemma cinfinite_cprod2: \"\\<lbrakk>Cnotzero r1; Cinfinite r2\\<rbrakk> \\<Longrightarrow> cinfinite (r1 *c r2)\"\nby (rule cinfinite_mono) (auto intro: ordLeq_cprod2)\n\nlemma Cinfinite_cprod2: \"\\<lbrakk>Cnotzero r1; Cinfinite r2\\<rbrakk> \\<Longrightarrow> Cinfinite (r1 *c r2)\"\nby (blast intro: cinfinite_cprod2 Card_order_cprod)\n\nlemma cprod_cong: \"\\<lbrakk>p1 =o r1; p2 =o r2\\<rbrakk> \\<Longrightarrow> p1 *c p2 =o r1 *c r2\"\nunfolding ordIso_iff_ordLeq by (blast intro: cprod_mono)\n\nlemma cprod_cong1: \"\\<lbrakk>p1 =o r1\\<rbrakk> \\<Longrightarrow> p1 *c p2 =o r1 *c p2\"\nunfolding ordIso_iff_ordLeq by (blast intro: cprod_mono1)\n\nlemma cprod_cong2: \"p2 =o r2 \\<Longrightarrow> q *c p2 =o q *c r2\"\nunfolding ordIso_iff_ordLeq by (blast intro: cprod_mono2)\n\nlemma cprod_com: \"p1 *c p2 =o p2 *c p1\"\nby (simp only: cprod_def card_of_Times_commute)\n\nlemma card_of_Csum_Times:\n  \"\\<forall>i \\<in> I. |A i| \\<le>o |B| \\<Longrightarrow> (CSUM i : |I|. |A i| ) \\<le>o |I| *c |B|\"\nby (simp only: Csum_def cprod_def Field_card_of card_of_Sigma_mono1)\n\nlemma card_of_Csum_Times':\n  assumes \"Card_order r\" \"\\<forall>i \\<in> I. |A i| \\<le>o r\"\n  shows \"(CSUM i : |I|. |A i| ) \\<le>o |I| *c r\"\nproof -\n  from assms(1) have *: \"r =o |Field r|\" by (simp add: card_of_unique)\n  with assms(2) have \"\\<forall>i \\<in> I. |A i| \\<le>o |Field r|\" by (blast intro: ordLeq_ordIso_trans)\n  hence \"(CSUM i : |I|. |A i| ) \\<le>o |I| *c |Field r|\" by (simp only: card_of_Csum_Times)\n  also from * have \"|I| *c |Field r| \\<le>o |I| *c r\"\n    by (simp only: Field_card_of card_of_refl cprod_def ordIso_imp_ordLeq)\n  finally show ?thesis .\nqed\n\nlemma cprod_csum_distrib1: \"r1 *c r2 +c r1 *c r3 =o r1 *c (r2 +c r3)\"\nunfolding csum_def cprod_def by (simp add: Field_card_of card_of_Times_Plus_distrib ordIso_symmetric)\n\nlemma csum_absorb2': \"\\<lbrakk>Card_order r2; r1 \\<le>o r2; cinfinite r1 \\<or> cinfinite r2\\<rbrakk> \\<Longrightarrow> r1 +c r2 =o r2\"\nunfolding csum_def by (rule conjunct2[OF Card_order_Plus_infinite])\n  (auto simp: cinfinite_def dest: cinfinite_mono)\n\nlemma csum_absorb1':\n  assumes card: \"Card_order r2\"\n  and r12: \"r1 \\<le>o r2\" and cr12: \"cinfinite r1 \\<or> cinfinite r2\"\n  shows \"r2 +c r1 =o r2\"\nby (rule ordIso_transitive, rule csum_com, rule csum_absorb2', (simp only: assms)+)\n\nlemma csum_absorb1: \"\\<lbrakk>Cinfinite r2; r1 \\<le>o r2\\<rbrakk> \\<Longrightarrow> r2 +c r1 =o r2\"\nby (rule csum_absorb1') auto\n\nlemma csum_absorb2: \"\\<lbrakk>Cinfinite r2 ; r1 \\<le>o r2\\<rbrakk> \\<Longrightarrow> r1 +c r2 =o r2\"\n  using ordIso_transitive csum_com csum_absorb1 by blast\n\nlemma regularCard_csum:\n  assumes \"Cinfinite r\" \"Cinfinite s\" \"regularCard r\" \"regularCard s\"\n    shows \"regularCard (r +c s)\"\nproof (cases \"r \\<le>o s\")\n  case True\n  then show ?thesis using regularCard_ordIso[of s] csum_absorb2'[THEN ordIso_symmetric] assms by auto\nnext\n  case False\n  have \"Well_order s\" \"Well_order r\" using assms card_order_on_well_order_on by auto\n  then have \"s \\<le>o r\" using not_ordLeq_iff_ordLess False ordLess_imp_ordLeq by auto\n  then show ?thesis using regularCard_ordIso[of r] csum_absorb1'[THEN ordIso_symmetric] assms by auto\nqed\n\nlemma csum_mono_strict:\n  assumes Card_order: \"Card_order r\" \"Card_order q\"\n  and Cinfinite: \"Cinfinite r'\" \"Cinfinite q'\"\n  and less: \"r <o r'\" \"q <o q'\"\nshows \"r +c q <o r' +c q'\"\nproof -\n  have Well_order: \"Well_order r\" \"Well_order q\" \"Well_order r'\" \"Well_order q'\"\n    using card_order_on_well_order_on Card_order Cinfinite by auto\n  show ?thesis\n  proof (cases \"Cinfinite r\")\n    case outer: True\n    then show ?thesis\n    proof (cases \"Cinfinite q\")\n      case inner: True\n      then show ?thesis\n      proof (cases \"r \\<le>o q\")\n        case True\n        then have \"r +c q =o q\" using csum_absorb2 inner by blast\n        then show ?thesis\n          using ordIso_ordLess_trans ordLess_ordLeq_trans less Cinfinite ordLeq_csum2 by blast\n      next\n        case False\n        then have \"q \\<le>o r\" using not_ordLeq_iff_ordLess Well_order ordLess_imp_ordLeq by blast\n        then have \"r +c q =o r\" using csum_absorb1 outer by blast\n        then show ?thesis\n          using ordIso_ordLess_trans ordLess_ordLeq_trans less Cinfinite ordLeq_csum1 by blast\n      qed\n    next\n      case False\n      then have \"Cfinite q\" using Card_order cinfinite_def cfinite_def by blast\n      then have \"q \\<le>o r\" using finite_ordLess_infinite cfinite_def cinfinite_def outer\n          Well_order ordLess_imp_ordLeq by blast\n      then have \"r +c q =o r\" by (rule csum_absorb1[OF outer])\n      then show ?thesis using ordIso_ordLess_trans ordLess_ordLeq_trans less ordLeq_csum1 Cinfinite by blast\n    qed\n  next\n    case False\n    then have outer: \"Cfinite r\" using Card_order cinfinite_def cfinite_def by blast\n    then show ?thesis\n    proof (cases \"Cinfinite q\")\n      case True\n      then have \"r \\<le>o q\" using finite_ordLess_infinite cinfinite_def cfinite_def outer Well_order\n        ordLess_imp_ordLeq by blast\n      then have \"r +c q =o q\" by (rule csum_absorb2[OF True])\n      then show ?thesis using ordIso_ordLess_trans ordLess_ordLeq_trans less ordLeq_csum2 Cinfinite by blast\n    next\n      case False\n      then have \"Cfinite q\" using Card_order cinfinite_def cfinite_def by blast\n      then have \"Cfinite (r +c q)\" using Cfinite_csum outer by blast\n      moreover have \"Cinfinite (r' +c q')\" using Cinfinite_csum1 Cinfinite by blast\n      ultimately show ?thesis using Cfinite_ordLess_Cinfinite by blast\n    qed\n  qed\nqed\n\nsubsection \\<open>Exponentiation\\<close>\n\ndefinition cexp (infixr \"^c\" 90) where\n  \"r1 ^c r2 \\<equiv> |Func (Field r2) (Field r1)|\"\n\nlemma Card_order_cexp: \"Card_order (r1 ^c r2)\"\nunfolding cexp_def by (rule card_of_Card_order)\n\nlemma cexp_mono':\n  assumes 1: \"p1 \\<le>o r1\" and 2: \"p2 \\<le>o r2\"\n  and n: \"Field p2 = {} \\<Longrightarrow> Field r2 = {}\"\n  shows \"p1 ^c p2 \\<le>o r1 ^c r2\"\nproof(cases \"Field p1 = {}\")\n  case True\n  hence \"Field p2 \\<noteq> {} \\<Longrightarrow> Func (Field p2) {} = {}\" unfolding Func_is_emp by simp\n  with True have \"|Field |Func (Field p2) (Field p1)|| \\<le>o cone\"\n    unfolding cone_def Field_card_of\n    by (cases \"Field p2 = {}\", auto intro: surj_imp_ordLeq simp: Func_empty)\n  hence \"|Func (Field p2) (Field p1)| \\<le>o cone\" by (simp add: Field_card_of cexp_def)\n  hence \"p1 ^c p2 \\<le>o cone\" unfolding cexp_def .\n  thus ?thesis\n  proof (cases \"Field p2 = {}\")\n    case True\n    with n have \"Field r2 = {}\" .\n    hence \"cone \\<le>o r1 ^c r2\" unfolding cone_def cexp_def Func_def\n      by (auto intro: card_of_ordLeqI[where f=\"\\<lambda>_ _. undefined\"])\n    thus ?thesis using \\<open>p1 ^c p2 \\<le>o cone\\<close> ordLeq_transitive by auto\n  next\n    case False with True have \"|Field (p1 ^c p2)| =o czero\"\n      unfolding card_of_ordIso_czero_iff_empty cexp_def Field_card_of Func_def by auto\n    thus ?thesis unfolding cexp_def card_of_ordIso_czero_iff_empty Field_card_of\n      by (simp add: card_of_empty)\n  qed\nnext\n  case False\n  have 1: \"|Field p1| \\<le>o |Field r1|\" and 2: \"|Field p2| \\<le>o |Field r2|\"\n    using 1 2 by (auto simp: card_of_mono2)\n  obtain f1 where f1: \"f1 ` Field r1 = Field p1\"\n    using 1 unfolding card_of_ordLeq2[OF False, symmetric] by auto\n  obtain f2 where f2: \"inj_on f2 (Field p2)\" \"f2 ` Field p2 \\<subseteq> Field r2\"\n    using 2 unfolding card_of_ordLeq[symmetric] by blast\n  have 0: \"Func_map (Field p2) f1 f2 ` (Field (r1 ^c r2)) = Field (p1 ^c p2)\"\n    unfolding cexp_def Field_card_of using Func_map_surj[OF f1 f2 n, symmetric] .\n  have 00: \"Field (p1 ^c p2) \\<noteq> {}\" unfolding cexp_def Field_card_of Func_is_emp\n    using False by simp\n  show ?thesis\n    using 0 card_of_ordLeq2[OF 00] unfolding cexp_def Field_card_of by blast\nqed\n\nlemma cexp_mono:\n  assumes 1: \"p1 \\<le>o r1\" and 2: \"p2 \\<le>o r2\"\n  and n: \"p2 =o czero \\<Longrightarrow> r2 =o czero\" and card: \"Card_order p2\"\n  shows \"p1 ^c p2 \\<le>o r1 ^c r2\"\n  by (rule cexp_mono'[OF 1 2 czeroE[OF n[OF czeroI[OF card]]]])\n\nlemma cexp_mono1:\n  assumes 1: \"p1 \\<le>o r1\" and q: \"Card_order q\"\n  shows \"p1 ^c q \\<le>o r1 ^c q\"\nusing ordLeq_refl[OF q] by (rule cexp_mono[OF 1]) (auto simp: q)\n\nlemma cexp_mono2':\n  assumes 2: \"p2 \\<le>o r2\" and q: \"Card_order q\"\n  and n: \"Field p2 = {} \\<Longrightarrow> Field r2 = {}\"\n  shows \"q ^c p2 \\<le>o q ^c r2\"\nusing ordLeq_refl[OF q] by (rule cexp_mono'[OF _ 2 n]) auto\n\nlemma cexp_mono2:\n  assumes 2: \"p2 \\<le>o r2\" and q: \"Card_order q\"\n  and n: \"p2 =o czero \\<Longrightarrow> r2 =o czero\" and card: \"Card_order p2\"\n  shows \"q ^c p2 \\<le>o q ^c r2\"\nusing ordLeq_refl[OF q] by (rule cexp_mono[OF _ 2 n card]) auto\n\nlemma cexp_mono2_Cnotzero:\n  assumes \"p2 \\<le>o r2\" \"Card_order q\" \"Cnotzero p2\"\n  shows \"q ^c p2 \\<le>o q ^c r2\"\nusing assms(3) czeroI by (blast intro: cexp_mono2'[OF assms(1,2)])\n\nlemma cexp_cong:\n  assumes 1: \"p1 =o r1\" and 2: \"p2 =o r2\"\n  and Cr: \"Card_order r2\"\n  and Cp: \"Card_order p2\"\n  shows \"p1 ^c p2 =o r1 ^c r2\"\nproof -\n  obtain f where \"bij_betw f (Field p2) (Field r2)\"\n    using 2 card_of_ordIso[of \"Field p2\" \"Field r2\"] card_of_cong by auto\n  hence 0: \"Field p2 = {} \\<longleftrightarrow> Field r2 = {}\" unfolding bij_betw_def by auto\n  have r: \"p2 =o czero \\<Longrightarrow> r2 =o czero\"\n    and p: \"r2 =o czero \\<Longrightarrow> p2 =o czero\"\n     using 0 Cr Cp czeroE czeroI by auto\n  show ?thesis using 0 1 2 unfolding ordIso_iff_ordLeq\n    using r p cexp_mono[OF _ _ _ Cp] cexp_mono[OF _ _ _ Cr] by blast\nqed\n\nlemma cexp_cong1:\n  assumes 1: \"p1 =o r1\" and q: \"Card_order q\"\n  shows \"p1 ^c q =o r1 ^c q\"\nby (rule cexp_cong[OF 1 _ q q]) (rule ordIso_refl[OF q])\n\nlemma cexp_cong2:\n  assumes 2: \"p2 =o r2\" and q: \"Card_order q\" and p: \"Card_order p2\"\n  shows \"q ^c p2 =o q ^c r2\"\nby (rule cexp_cong[OF _ 2]) (auto simp only: ordIso_refl Card_order_ordIso2[OF p 2] q p)\n\nlemma cexp_cone:\n  assumes \"Card_order r\"\n  shows \"r ^c cone =o r\"\nproof -\n  have \"r ^c cone =o |Field r|\"\n    unfolding cexp_def cone_def Field_card_of Func_empty\n      card_of_ordIso[symmetric] bij_betw_def Func_def inj_on_def image_def\n    by (rule exI[of _ \"\\<lambda>f. f ()\"]) auto\n  also have \"|Field r| =o r\" by (rule card_of_Field_ordIso[OF assms])\n  finally show ?thesis .\nqed\n\nlemma cexp_cprod:\n  assumes r1: \"Card_order r1\"\n  shows \"(r1 ^c r2) ^c r3 =o r1 ^c (r2 *c r3)\" (is \"?L =o ?R\")\nproof -\n  have \"?L =o r1 ^c (r3 *c r2)\"\n    unfolding cprod_def cexp_def Field_card_of\n    using card_of_Func_Times by(rule ordIso_symmetric)\n  also have \"r1 ^c (r3 *c r2) =o ?R\"\n    apply(rule cexp_cong2) using cprod_com r1 by (auto simp: Card_order_cprod)\n  finally show ?thesis .\nqed\n\nlemma cprod_infinite1': \"\\<lbrakk>Cinfinite r; Cnotzero p; p \\<le>o r\\<rbrakk> \\<Longrightarrow> r *c p =o r\"\nunfolding cinfinite_def cprod_def\nby (rule Card_order_Times_infinite[THEN conjunct1]) (blast intro: czeroI)+\n\nlemma cprod_infinite: \"Cinfinite r \\<Longrightarrow> r *c r =o r\"\nusing cprod_infinite1' Cinfinite_Cnotzero ordLeq_refl by blast\n\nlemma cexp_cprod_ordLeq:\n  assumes r1: \"Card_order r1\" and r2: \"Cinfinite r2\"\n  and r3: \"Cnotzero r3\" \"r3 \\<le>o r2\"\n  shows \"(r1 ^c r2) ^c r3 =o r1 ^c r2\" (is \"?L =o ?R\")\nproof-\n  have \"?L =o r1 ^c (r2 *c r3)\" using cexp_cprod[OF r1] .\n  also have \"r1 ^c (r2 *c r3) =o ?R\"\n  apply(rule cexp_cong2)\n  apply(rule cprod_infinite1'[OF r2 r3]) using r1 r2 by (fastforce simp: Card_order_cprod)+\n  finally show ?thesis .\nqed\n\nlemma Cnotzero_UNIV: \"Cnotzero |UNIV|\"\nby (auto simp: card_of_Card_order card_of_ordIso_czero_iff_empty)\n\nlemma ordLess_ctwo_cexp:\n  assumes \"Card_order r\"\n  shows \"r <o ctwo ^c r\"\nproof -\n  have \"r <o |Pow (Field r)|\" using assms by (rule Card_order_Pow)\n  also have \"|Pow (Field r)| =o ctwo ^c r\"\n    unfolding ctwo_def cexp_def Field_card_of by (rule card_of_Pow_Func)\n  finally show ?thesis .\nqed\n\nlemma ordLeq_cexp1:\n  assumes \"Cnotzero r\" \"Card_order q\"\n  shows \"q \\<le>o q ^c r\"\nproof (cases \"q =o (czero :: 'a rel)\")\n  case True thus ?thesis by (simp only: card_of_empty cexp_def czero_def ordIso_ordLeq_trans)\nnext\n  case False\n  thus ?thesis\n    apply -\n    apply (rule ordIso_ordLeq_trans)\n    apply (rule ordIso_symmetric)\n    apply (rule cexp_cone)\n    apply (rule assms(2))\n    apply (rule cexp_mono2)\n    apply (rule cone_ordLeq_Cnotzero)\n    apply (rule assms(1))\n    apply (rule assms(2))\n    apply (rule notE)\n    apply (rule cone_not_czero)\n    apply assumption\n    apply (rule Card_order_cone)\n  done\nqed\n\nlemma ordLeq_cexp2:\n  assumes \"ctwo \\<le>o q\" \"Card_order r\"\n  shows \"r \\<le>o q ^c r\"\nproof (cases \"r =o (czero :: 'a rel)\")\n  case True thus ?thesis by (simp only: card_of_empty cexp_def czero_def ordIso_ordLeq_trans)\nnext\n  case False thus ?thesis\n    apply -\n    apply (rule ordLess_imp_ordLeq)\n    apply (rule ordLess_ordLeq_trans)\n    apply (rule ordLess_ctwo_cexp)\n    apply (rule assms(2))\n    apply (rule cexp_mono1)\n    apply (rule assms(1))\n    apply (rule assms(2))\n  done\nqed\n\nlemma cinfinite_cexp: \"\\<lbrakk>ctwo \\<le>o q; Cinfinite r\\<rbrakk> \\<Longrightarrow> cinfinite (q ^c r)\"\nby (rule cinfinite_mono[OF ordLeq_cexp2]) simp_all\n\nlemma Cinfinite_cexp:\n  \"\\<lbrakk>ctwo \\<le>o q; Cinfinite r\\<rbrakk> \\<Longrightarrow> Cinfinite (q ^c r)\"\nby (simp add: cinfinite_cexp Card_order_cexp)\n\nlemma card_order_cexp:\n  assumes \"card_order r1\" \"card_order r2\"\n  shows \"card_order (r1 ^c r2)\"\nproof -\n  have \"Field r1 = UNIV\" \"Field r2 = UNIV\" using assms card_order_on_Card_order by auto\n  thus ?thesis unfolding cexp_def Func_def using card_of_card_order_on by simp\nqed\n\nlemma ctwo_ordLess_natLeq: \"ctwo <o natLeq\"\nunfolding ctwo_def using finite_UNIV natLeq_cinfinite natLeq_Card_order\nby (intro Cfinite_ordLess_Cinfinite) (auto simp: cfinite_def card_of_Card_order)\n\nlemma ctwo_ordLess_Cinfinite: \"Cinfinite r \\<Longrightarrow> ctwo <o r\"\nby (rule ordLess_ordLeq_trans[OF ctwo_ordLess_natLeq natLeq_ordLeq_cinfinite])\n\nlemma ctwo_ordLeq_Cinfinite:\n  assumes \"Cinfinite r\"\n  shows \"ctwo \\<le>o r\"\nby (rule ordLess_imp_ordLeq[OF ctwo_ordLess_Cinfinite[OF assms]])\n\nlemma Un_Cinfinite_bound: \"\\<lbrakk>|A| \\<le>o r; |B| \\<le>o r; Cinfinite r\\<rbrakk> \\<Longrightarrow> |A \\<union> B| \\<le>o r\"\nby (auto simp add: cinfinite_def card_of_Un_ordLeq_infinite_Field)\n\nlemma Un_Cinfinite_bound_strict: \"\\<lbrakk>|A| <o r; |B| <o r; Cinfinite r\\<rbrakk> \\<Longrightarrow> |A \\<union> B| <o r\"\nby (auto simp add: cinfinite_def card_of_Un_ordLess_infinite_Field)\n\nlemma UNION_Cinfinite_bound: \"\\<lbrakk>|I| \\<le>o r; \\<forall>i \\<in> I. |A i| \\<le>o r; Cinfinite r\\<rbrakk> \\<Longrightarrow> |\\<Union>i \\<in> I. A i| \\<le>o r\"\nby (auto simp add: card_of_UNION_ordLeq_infinite_Field cinfinite_def)\n\nlemma csum_cinfinite_bound:\n  assumes \"p \\<le>o r\" \"q \\<le>o r\" \"Card_order p\" \"Card_order q\" \"Cinfinite r\"\n  shows \"p +c q \\<le>o r\"\nproof -\n  from assms(1-4) have \"|Field p| \\<le>o r\" \"|Field q| \\<le>o r\"\n    unfolding card_order_on_def using card_of_least ordLeq_transitive by blast+\n  with assms show ?thesis unfolding cinfinite_def csum_def\n    by (blast intro: card_of_Plus_ordLeq_infinite_Field)\nqed\n\nlemma cprod_cinfinite_bound:\n  assumes \"p \\<le>o r\" \"q \\<le>o r\" \"Card_order p\" \"Card_order q\" \"Cinfinite r\"\n  shows \"p *c q \\<le>o r\"\nproof -\n  from assms(1-4) have \"|Field p| \\<le>o r\" \"|Field q| \\<le>o r\"\n    unfolding card_order_on_def using card_of_least ordLeq_transitive by blast+\n  with assms show ?thesis unfolding cinfinite_def cprod_def\n    by (blast intro: card_of_Times_ordLeq_infinite_Field)\nqed\n\nlemma cprod_infinite2': \"\\<lbrakk>Cnotzero r1; Cinfinite r2; r1 \\<le>o r2\\<rbrakk> \\<Longrightarrow> r1 *c r2 =o r2\"\n  unfolding ordIso_iff_ordLeq\n  by (intro conjI cprod_cinfinite_bound ordLeq_cprod2 ordLeq_refl)\n    (auto dest!: ordIso_imp_ordLeq not_ordLeq_ordLess simp: czero_def Card_order_empty)\n\nlemma regularCard_cprod:\n  assumes \"Cinfinite r\" \"Cinfinite s\" \"regularCard r\" \"regularCard s\"\n    shows \"regularCard (r *c s)\"\nproof (cases \"r \\<le>o s\")\n  case True\n  show ?thesis\n    apply (rule regularCard_ordIso[of s])\n      apply (rule ordIso_symmetric[OF cprod_infinite2'])\n    using assms True Cinfinite_Cnotzero by auto\nnext\n  case False\n  have \"Well_order r\" \"Well_order s\" using assms card_order_on_well_order_on by auto\n  then have 1: \"s \\<le>o r\" using not_ordLeq_iff_ordLess ordLess_imp_ordLeq False by blast\n  show ?thesis\n    apply (rule regularCard_ordIso[of r])\n      apply (rule ordIso_symmetric[OF cprod_infinite1'])\n    using assms 1 Cinfinite_Cnotzero by auto\nqed\n\nlemma cprod_csum_cexp:\n  \"r1 *c r2 \\<le>o (r1 +c r2) ^c ctwo\"\nunfolding cprod_def csum_def cexp_def ctwo_def Field_card_of\nproof -\n  let ?f = \"\\<lambda>(a, b). %x. if x then Inl a else Inr b\"\n  have \"inj_on ?f (Field r1 \\<times> Field r2)\" (is \"inj_on _ ?LHS\")\n    by (auto simp: inj_on_def fun_eq_iff split: bool.split)\n  moreover\n  have \"?f ` ?LHS \\<subseteq> Func (UNIV :: bool set) (Field r1 <+> Field r2)\" (is \"_ \\<subseteq> ?RHS\")\n    by (auto simp: Func_def)\n  ultimately show \"|?LHS| \\<le>o |?RHS|\" using card_of_ordLeq by blast\nqed\n\nlemma Cfinite_cprod_Cinfinite: \"\\<lbrakk>Cfinite r; Cinfinite s\\<rbrakk> \\<Longrightarrow> r *c s \\<le>o s\"\nby (intro cprod_cinfinite_bound)\n  (auto intro: ordLeq_refl ordLess_imp_ordLeq[OF Cfinite_ordLess_Cinfinite])\n\nlemma cprod_cexp: \"(r *c s) ^c t =o r ^c t *c s ^c t\"\n  unfolding cprod_def cexp_def Field_card_of by (rule Func_Times_Range)\n\nlemma cprod_cexp_csum_cexp_Cinfinite:\n  assumes t: \"Cinfinite t\"\n  shows \"(r *c s) ^c t \\<le>o (r +c s) ^c t\"\nproof -\n  have \"(r *c s) ^c t \\<le>o ((r +c s) ^c ctwo) ^c t\"\n    by (rule cexp_mono1[OF cprod_csum_cexp conjunct2[OF t]])\n  also have \"((r +c s) ^c ctwo) ^c t =o (r +c s) ^c (ctwo *c t)\"\n    by (rule cexp_cprod[OF Card_order_csum])\n  also have \"(r +c s) ^c (ctwo *c t) =o (r +c s) ^c (t *c ctwo)\"\n    by (rule cexp_cong2[OF cprod_com Card_order_csum Card_order_cprod])\n  also have \"(r +c s) ^c (t *c ctwo) =o ((r +c s) ^c t) ^c ctwo\"\n    by (rule ordIso_symmetric[OF cexp_cprod[OF Card_order_csum]])\n  also have \"((r +c s) ^c t) ^c ctwo =o (r +c s) ^c t\"\n    by (rule cexp_cprod_ordLeq[OF Card_order_csum t ctwo_Cnotzero ctwo_ordLeq_Cinfinite[OF t]])\n  finally show ?thesis .\nqed\n\nlemma Cfinite_cexp_Cinfinite:\n  assumes s: \"Cfinite s\" and t: \"Cinfinite t\"\n  shows \"s ^c t \\<le>o ctwo ^c t\"\nproof (cases \"s \\<le>o ctwo\")\n  case True thus ?thesis using t by (blast intro: cexp_mono1)\nnext\n  case False\n  hence \"ctwo \\<le>o s\" using ordLeq_total[of s ctwo] Card_order_ctwo s\n    by (auto intro: card_order_on_well_order_on)\n  hence \"Cnotzero s\" using Cnotzero_mono[OF ctwo_Cnotzero] s by blast\n  hence st: \"Cnotzero (s *c t)\" by (intro Cinfinite_Cnotzero[OF Cinfinite_cprod2]) (auto simp: t)\n  have \"s ^c t \\<le>o (ctwo ^c s) ^c t\"\n    using assms by (blast intro: cexp_mono1 ordLess_imp_ordLeq[OF ordLess_ctwo_cexp])\n  also have \"(ctwo ^c s) ^c t =o ctwo ^c (s *c t)\"\n    by (blast intro: Card_order_ctwo cexp_cprod)\n  also have \"ctwo ^c (s *c t) \\<le>o ctwo ^c t\"\n    using assms st by (intro cexp_mono2_Cnotzero Cfinite_cprod_Cinfinite Card_order_ctwo)\n  finally show ?thesis .\nqed\n\nlemma csum_Cfinite_cexp_Cinfinite:\n  assumes r: \"Card_order r\" and s: \"Cfinite s\" and t: \"Cinfinite t\"\n  shows \"(r +c s) ^c t \\<le>o (r +c ctwo) ^c t\"\nproof (cases \"Cinfinite r\")\n  case True\n  hence \"r +c s =o r\" by (intro csum_absorb1 ordLess_imp_ordLeq[OF Cfinite_ordLess_Cinfinite] s)\n  hence \"(r +c s) ^c t =o r ^c t\" using t by (blast intro: cexp_cong1)\n  also have \"r ^c t \\<le>o (r +c ctwo) ^c t\" using t by (blast intro: cexp_mono1 ordLeq_csum1 r)\n  finally show ?thesis .\nnext\n  case False\n  with r have \"Cfinite r\" unfolding cinfinite_def cfinite_def by auto\n  hence \"Cfinite (r +c s)\" by (intro Cfinite_csum s)\n  hence \"(r +c s) ^c t \\<le>o ctwo ^c t\" by (intro Cfinite_cexp_Cinfinite t)\n  also have \"ctwo ^c t \\<le>o (r +c ctwo) ^c t\" using t\n    by (blast intro: cexp_mono1 ordLeq_csum2 Card_order_ctwo)\n  finally show ?thesis .\nqed\n\n(* cardSuc *)\n\nlemma Cinfinite_cardSuc: \"Cinfinite r \\<Longrightarrow> Cinfinite (cardSuc r)\"\nby (simp add: cinfinite_def cardSuc_Card_order cardSuc_finite)\n\nlemma cardSuc_UNION_Cinfinite:\n  assumes \"Cinfinite r\" \"relChain (cardSuc r) As\" \"B \\<le> (\\<Union>i \\<in> Field (cardSuc r). As i)\" \"|B| <=o r\"\n  shows \"\\<exists>i \\<in> Field (cardSuc r). B \\<le> As i\"\nusing cardSuc_UNION assms unfolding cinfinite_def by blast\n\nlemma Cinfinite_card_suc: \"\\<lbrakk> Cinfinite r ; card_order r \\<rbrakk> \\<Longrightarrow> Cinfinite (card_suc r)\"\n  using Cinfinite_cong[OF cardSuc_ordIso_card_suc Cinfinite_cardSuc] .\n\nlemma card_suc_least: \"\\<lbrakk>card_order r; Card_order s; r <o s\\<rbrakk> \\<Longrightarrow> card_suc r \\<le>o s\"\n  by (rule ordIso_ordLeq_trans[OF ordIso_symmetric[OF cardSuc_ordIso_card_suc]])\n    (auto intro!: cardSuc_least simp: card_order_on_Card_order)\n\nlemma regularCard_cardSuc: \"Cinfinite k \\<Longrightarrow> regularCard (cardSuc k)\"\n  by (rule infinite_cardSuc_regularCard) (auto simp: cinfinite_def)\n\nlemma regularCard_card_suc: \"card_order r \\<Longrightarrow> Cinfinite r \\<Longrightarrow> regularCard (card_suc r)\"\n  using cardSuc_ordIso_card_suc Cinfinite_cardSuc regularCard_cardSuc regularCard_ordIso\n  by blast\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/BNF_Cardinal_Arithmetic.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8824278540866547, "lm_q2_score": 0.80563219364797, "lm_q1q2_score": 0.7109122878239024}}
{"text": "(*\n    File:      More_Totient.thy\n    Author:    Manuel Eberl, TU M\u00fcnchen\n    \n    Additional properties of Euler's totient function\n*)\nsection \\<open>Euler's $\\phi$ function\\<close>\ntheory More_Totient\n  imports\n    Moebius_Mu\n    \"HOL-Number_Theory.Number_Theory\"\nbegin\n  \nlemma fds_totient_times_zeta: \n  \"fds (\\<lambda>n. of_nat (totient n) :: 'a :: comm_semiring_1) * fds_zeta = fds of_nat\"\nproof\n  fix n :: nat assume n: \"n > 0\"\n  have \"fds_nth (fds (\\<lambda>n. of_nat (totient n)) * fds_zeta) n = \n          dirichlet_prod (\\<lambda>n. of_nat (totient n)) (\\<lambda>_. 1) n\"\n    by (simp add: fds_nth_mult)\n  also from n have \"\\<dots> = fds_nth (fds of_nat) n\"\n    by (simp add: fds_nth_fds dirichlet_prod_def totient_divisor_sum of_nat_sum [symmetric]\n             del: of_nat_sum)\n  finally show \"fds_nth (fds (\\<lambda>n. of_nat (totient n)) * fds_zeta) n = fds_nth (fds of_nat) n\" .\nqed\n\nlemma fds_totient_times_zeta': \"fds totient * fds_zeta = fds id\"\n  using fds_totient_times_zeta[where 'a = nat] by simp\n  \nlemma fds_totient: \"fds (\\<lambda>n. of_nat (totient n)) = fds of_nat * fds moebius_mu\"\nproof -\n  have \"fds (\\<lambda>n. of_nat (totient n)) * fds_zeta * fds moebius_mu = fds of_nat * fds moebius_mu\"\n    by (simp add: fds_totient_times_zeta)\n  also have \"fds (\\<lambda>n. of_nat (totient n)) * fds_zeta * fds moebius_mu = \n               fds (\\<lambda>n. of_nat (totient n))\"\n    by (simp only: mult.assoc fds_zeta_times_moebius_mu mult_1_right)\n  finally show ?thesis .\nqed\n\nlemma totient_conv_moebius_mu:\n  \"int (totient n) = dirichlet_prod moebius_mu int n\"\nproof (cases \"n = 0\")\n  case False\n  show ?thesis\n    by (rule moebius_inversion)\n       (insert False, simp_all add: of_nat_sum [symmetric] totient_divisor_sum del: of_nat_sum)\nqed simp_all\n\ninterpretation totient: multiplicative_function totient\nproof -\n  have \"multiplicative_function int\" by standard simp_all\n  hence \"multiplicative_function (dirichlet_prod moebius_mu int)\"\n    by (intro multiplicative_dirichlet_prod moebius_mu.multiplicative_function_axioms)\n  also have \"dirichlet_prod moebius_mu int = (\\<lambda>n. int (totient n))\" \n    by (simp add: fun_eq_iff totient_conv_moebius_mu)\n  finally show \"multiplicative_function totient\" by (rule multiplicative_function_of_natD)\nqed\n\nlemma even_prime_nat: \"prime p \\<Longrightarrow> even p \\<Longrightarrow> p = (2::nat)\"\n  using prime_odd_nat[of p] prime_gt_1_nat[of p] by (cases \"p = 2\") auto\n\nlemma twopow_dvd_totient:\n  fixes n :: nat\n  assumes \"n > 0\"\n  defines \"k \\<equiv> card {p\\<in>prime_factors n. odd p}\"\n  shows   \"2 ^ k dvd totient n\"\nproof -\n  define P where \"P = {p\\<in>prime_factors n. odd p}\"\n  define P' where \"P' = {p\\<in>prime_factors n. even p}\"\n  define r where \"r = (\\<lambda>p. multiplicity p n)\"\n  from \\<open>n > 0\\<close> have \"totient n = (\\<Prod>p\\<in>prime_factors n. totient (p ^ r p))\"\n    unfolding r_def by (rule totient.prod_prime_factors)\n  also have \"prime_factors n = P \\<union> P'\"\n    by (auto simp: P_def P'_def)\n  also have \"(\\<Prod>p\\<in>\\<dots>. totient (p ^ r p)) =\n               (\\<Prod>p\\<in>P. totient (p ^ r p)) * (\\<Prod>p\\<in>P'. totient (p ^ r p))\"\n    by (subst prod.union_disjoint) (auto simp: P_def P'_def)\n  finally have eq: \"totient n = \\<dots>\" .\n\n  have \"p ^ r p > 2\" if \"p \\<in> P\" for p\n  proof -\n    have \"p \\<noteq> 2\" using that by (auto simp: P_def)\n    moreover have \"p > 1\" using prime_gt_1_nat[of p] that by (auto simp: P_def)\n    ultimately have \"2 < p\" by linarith\n    also have \"p = p ^ 1\" by simp\n    also have \"p ^ 1 \\<le> p ^ r p\"\n      using that prime_gt_1_nat[of p]\n      by (intro power_increasing) (auto simp: P_def prime_factors_multiplicity r_def)\n    finally show ?thesis .\n  qed\n  hence \"(\\<Prod>p\\<in>P. 2) dvd (\\<Prod>p\\<in>P. totient (p ^ r p))\"\n    by (intro prod_dvd_prod totient_even)\n  hence \"2 ^ card P dvd (\\<Prod>p\\<in>P. totient (p ^ r p))\"\n    by simp\n  also have \"\\<dots> dvd (\\<Prod>p\\<in>P. totient (p ^ r p)) * (\\<Prod>p\\<in>P'. totient (p ^ r p))\"\n    by simp\n  also have \"\\<dots> = totient n\"\n    by (rule eq [symmetric])\n  finally show ?thesis unfolding k_def P_def .\nqed\n\nlemma totient_conv_moebius_mu':\n  assumes \"n > (0::nat)\"\n  shows   \"real (totient n) = real n * (\\<Sum>d | d dvd n. moebius_mu d / real d)\"\nproof -\n  have \"real (totient n) = of_int (int (totient n))\" by simp\n  also have \"int (totient n) = (\\<Sum>d | d dvd n. moebius_mu d * int (n div d))\"\n    using totient_conv_moebius_mu by (simp add: dirichlet_prod_def assms)\n  also have \"real_of_int (\\<Sum>d | d dvd n. moebius_mu d * int (n div d)) =\n               (\\<Sum>d | d dvd n. moebius_mu d * real (n div d))\" by simp\n  also have \"\\<dots> = (\\<Sum>d | d dvd n. real n * moebius_mu d / real d)\"\n    by (rule sum.cong) (simp_all add: field_char_0_class.of_nat_div)\n  also have \"\\<dots> = real n * (\\<Sum>d | d dvd n. moebius_mu d / real d)\"\n    by (simp add: sum_distrib_left)\n  finally show ?thesis .\nqed\n\nlemma totient_prime_power_Suc:\n  assumes \"prime p\"\n  shows   \"totient (p ^ Suc n) = p ^ Suc n - p ^ n\"\nproof -\n  have \"totient (p ^ Suc n) = p ^ Suc n - card ((*) p ` {0<..p ^ n})\"\n    unfolding totient_def totatives_prime_power_Suc[OF assms]\n    by (subst card_Diff_subset) (insert assms, auto simp: prime_gt_0_nat)\n  also from assms have \"card ((*) p ` {0<..p^n}) = p ^ n\"\n    by (subst card_image) (auto simp: inj_on_def)\n  finally show ?thesis .\nqed\n\ninterpretation totient: multiplicative_function' totient \"\\<lambda>p k. p ^ k - p ^ (k - 1)\" \"\\<lambda>p. p - 1\"\nproof\n  fix p k :: nat assume \"prime p\" \"k > 0\"\n  thus \"totient (p ^ k) = p ^ k - p ^ (k - 1)\" \n    by (cases k) (simp_all add: totient_prime_power_Suc del: power_Suc)\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/Dirichlet_Series/More_Totient.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8670357735451835, "lm_q2_score": 0.8198933403143929, "lm_q1q2_score": 0.710876856544034}}
{"text": "           (*-------------------------------------------*\n            |        CSP-Prover on Isabelle2004         |\n            |               November 2004               |\n            |                                           |\n            |        CSP-Prover on Isabelle2005         |\n            |                October 2005  (modified)   |\n            |                  March 2006  (modified)   |\n            |                                           |\n            |        CSP-Prover on Isabelle2016         |\n            |                    May 2016  (modified)   |\n            |                                           |\n            |        CSP-Prover on Isabelle2020         |\n            |                  April 2020  (modified)   |\n            |                                           |\n            |        Yoshinao Isobe (AIST JAPAN)        |\n            *-------------------------------------------*)\n\ntheory Norm_seq\nimports CMS\nbegin\n\n(*****************************************************************\n\n         1. Definition of Normarized sequences\n         2. Properties of Normarized sequences\n         3. How to transform each Cauchy sequence to NF\n         4. The same limit between xs and NF(xs)\n\n *****************************************************************)\n\ndefinition\n  normal :: \"'a::ms infinite_seq => bool\"\n  where\n  normal_def : \n    \"normal xs == ALL (n::nat) (m::nat). \n        distance(xs n, xs m) <= (1/2)^(min n m)\"\n  \ndefinition  \n  Nset   :: \"'a::ms infinite_seq => real => nat set\"\n  where\n  Nset_def :\n    \"Nset xs delta == \n     {N. ALL n m. (N <= m & N <= n) --> distance(xs n, xs m) <= delta}\"\n  \ndefinition  \n  Nmin   :: \"'a::ms infinite_seq => real => nat\"\n  where\n  Nmin_def :\n    \"Nmin xs delta == Min (Nset xs delta)\"\n  \ndefinition  \n  NF     :: \"'a::ms infinite_seq => 'a::ms infinite_seq\"\n  where\n  NF_def :\n    \"NF xs == (%n. xs (Nmin xs ((1/2)^n)))\"\n\n(********************************************************************\n                          Normalization\n ********************************************************************)\n\n(*** normalized sequence --> Cauchy sequence ***)\n\n\nlemma normal_cauchy: \"normal xs ==> cauchy xs\"\n\n  apply (simp add: cauchy_def)\n  apply (intro allI impI)\n  apply (subgoal_tac \"EX n. (1/2) ^ n < delta\")\n  apply (erule exE)\n  apply (rule_tac x=\"n\" in exI)\n  apply (intro allI impI)\n  apply (simp add: normal_def)\n  apply (drule_tac x=\"i\" in spec)\n  apply (drule_tac x=\"j\" in spec)\n  \n  apply (rule le_less_trans)   (* modified for Isabelle2020 *)\n  apply (simp)\n  apply (rule le_less_trans[of _ \"(1 / 2) ^ _\"])\n  apply (simp)\n  apply (simp)\n  apply (simp add: pow_convergence)\ndone\n\n(*\ndeclare realpow_Suc          [simp del]\nin isabelle2008\n*)\n\ndeclare power_Suc          [simp del]\n\nlemma normal_Limit: \n  \"[| normal xs ; xs convergeTo y |]\n        ==> distance(xs (Suc n), y) < (1/2)^n\"\napply (simp add: convergeTo_def)\napply (drule_tac x=\"(1/2)^(Suc n)\" in spec)\napply (simp)\napply (erule exE)\n\napply (rename_tac N)\napply (case_tac \"N <= Suc n\")\n apply (drule_tac x=\"Suc n\" in spec)\n apply (simp add: symmetry_ms)\n\n apply (rule less_le_trans)   (* modified for Isabelle2020 *)\n apply (simp)\n apply (subgoal_tac \"((1::real) / 2) ^ Suc n <= (1 / 2) ^ n\")\n apply (simp)\n apply (simp add: power_decreasing)\n\n(* else (i.e. Suc n < N *)\n apply (drule_tac x=\"N\" in spec)\n apply (simp)\n apply (insert triangle_inequality_ms)\n apply (drule_tac x=\"xs (Suc n)\" in spec)\n apply (drule_tac x=\"xs N\" in spec)\n apply (drule_tac x=\"y\" in spec)\n\n apply (simp add: normal_def)\n apply (drule_tac x=\"Suc n\" in spec)\n apply (drule_tac x=\"N\" in spec)\n apply (simp add: symmetry_ms)\n apply (simp add: min_def)\n apply (simp add: power_Suc)\ndone\n\n(*\ndeclare realpow_Suc          [simp]\n*)\ndeclare power_Suc          [simp]\n\n(********************************************************************\n                                Nmin\n ********************************************************************)\n\n(*** Nmin exists ***)\n\nlemma Nmin_exists: \n  \"[| 0 < delta ; cauchy xs |] ==> EX N. N isMIN (Nset xs delta)\"\napply (simp add: cauchy_def)\napply (drule_tac x=\"delta\" in spec)\napply (simp)\napply (erule exE)\n\napply (rule EX_MIN_nat)\napply (simp add: Nset_def)\napply (rule_tac x=\"n\" in exI)\napply (intro allI impI)\napply (drule_tac x=\"na\" in spec)\napply (drule_tac x=\"m\" in spec)\nby (simp)\n\nlemma Nset_hasMIN: \n  \"[| 0 < delta ; cauchy xs |] ==> (Nset xs delta) hasMIN\"\napply (simp add: hasMIN_def)\napply (rule Nmin_exists)\nby (simp)\n\n(*** Nmin unique ***)\n\nlemma Nmin_unique: \n  \"[| N isMIN (Nset xs delta) ; M isMIN (Nset xs delta) |] ==> N = M\"\nby (simp add: MIN_unique)\n\n(*-----------------------*\n |       the Nmin        |\n *-----------------------*)\n\nlemma Nset_to_Nmin : \n  \"[| 0 < delta ; cauchy xs |]\n   ==> (N isMIN (Nset xs delta)) = (Nmin xs delta = N)\"\napply (simp add: Nmin_def)\napply (rule iffI)\n\napply (simp add: Min_def Nset_hasMIN)\napply (rule the_equality)\napply (simp)\napply (simp add: Nmin_unique)\n\nby (simp add: MIN_iff Nset_hasMIN)\n\nlemmas Nmin_to_Nset = Nset_to_Nmin[THEN sym]\n\nlemma Nmin_to_Nset_sym :\n    \"[| 0 < delta ; cauchy xs |] \n     ==> (N = Nmin xs delta) = (N isMIN (Nset xs delta))\"\nby (auto simp add: Nset_to_Nmin)\n\nlemmas Nmin_iff = Nmin_to_Nset Nmin_to_Nset_sym\n\n(*-----------------------*\n |      property         |\n *-----------------------*)\n\nlemma Nmin_cauchy_lm:\n  \"[| 0 < delta ; cauchy xs ; Nmin xs delta = N |]\n   ==> (ALL n m. (N <= m & N <= n) --> distance(xs n, xs m) <= delta)\"\nby (simp add: Nmin_iff Nset_def isMIN_def)\n\nlemma Nmin_cauchy:\n  \"[| 0 < delta ; cauchy xs ; Nmin xs delta <= m ; Nmin xs delta <= n |]\n   ==> distance(xs n, xs m) <= delta\"\nby (simp add: Nmin_cauchy_lm)\n\n(*-----------------------*\n |   min_number_cauchy   |\n *-----------------------*)\n\n(*** Nmin order (check) ***)\n\nlemma min_number_cauchy_lm:\n  \"[| 0 < delta1 ; delta1 <= delta2 ; cauchy xs |]\n   ==> Nset xs delta1 <= Nset xs delta2\"\napply (simp add: Nset_def)\napply (rule subsetI)\napply (simp)\napply (intro allI impI)\napply (drule_tac x=\"n\" in spec)\napply (drule_tac x=\"m\" in spec)\nby (simp)\n\n(*** Nmin order ***)\n\nlemma min_number_cauchy:\n  \"[| 0 < delta1 ; delta1 <= delta2 ; cauchy xs ;\n      Nmin xs delta1 = N1 ; Nmin xs delta2 = N2 |]\n   ==> N2 <= N1\"\napply (simp add: Nmin_iff)\nby (simp add: isMIN_subset min_number_cauchy_lm)\n\n(*** Nmin order half ***)\n\nlemma min_number_cauchy_half:\n  \"[| n <= m ; cauchy xs ; Nmin xs ((1/2)^n) = N1 ; Nmin xs ((1/2)^m) = N2 |]\n   ==> N1 <= N2\"\napply (rule min_number_cauchy)\nby (simp_all add: power_decreasing)\n\n(*------------------------*\n | normal_form_seq_normal |\n *------------------------*)\n\nlemma normal_form_seq_normal: \"cauchy xs ==> normal (NF(xs))\"\napply (simp add: normal_def NF_def)\napply (intro allI)\n\napply (case_tac \"n <= m\")\n apply (simp add: min_def)\n apply (rule Nmin_cauchy, simp_all)\n apply (rule min_number_cauchy_half, simp_all)\n\n(* else *)\n apply (simp add: min_def)\n apply (rule Nmin_cauchy, simp_all)\n apply (rule min_number_cauchy_half, simp_all)\ndone\n\n(*----------------------------*\n | normal_form_seq_same_Limit |\n *----------------------------*)\n\n(*** only if part ***)\n\nlemma normal_form_seq_same_Limit_only_if:\n  \"[| cauchy xs ; xs convergeTo y |] ==> NF(xs) convergeTo y\"\napply (simp add: convergeTo_def)\napply (intro allI impI)\napply (drule_tac x=\"eps/2\" in spec)\napply (simp)\napply (erule exE)\n\napply (subgoal_tac \"EX n. (1 / 2) ^ n < eps/2\")\napply (erule exE)\napply (rename_tac eps N M)\n\napply (rule_tac x=\"M\" in exI)\napply (intro allI impI)\n\napply (case_tac \"N <= Nmin xs ((1/2)^m)\")\n\n apply (drule_tac x=\"Nmin xs ((1/2)^m)\" in spec)\n apply (simp add: NF_def)\n\n(* else *)\n apply (insert triangle_inequality_ms)\n apply (drule_tac x=\"y\" in spec)\n apply (drule_tac x=\"xs N\" in spec)\n apply (drule_tac x=\"(NF xs) m\" in spec)\n\n apply (drule_tac x=\"N\" in spec)\n apply (simp add: NF_def)\n\n apply (subgoal_tac \"distance (xs N, xs (Nmin xs ((1 / 2) ^ m))) <= (1 / 2) ^ m\")\n apply (subgoal_tac \"((1::real) / 2) ^ m <= (1 / 2) ^ M\")\n apply (simp (no_asm_simp))  (* modified for Isabelle2020 *)\n apply (simp) \n apply (rule Nmin_cauchy)\n apply (simp, simp, simp, simp)\n apply (rule pow_convergence)\n apply (simp_all)\ndone\n\n(*** if part ***)\n\nlemma normal_form_seq_same_Limit_if:\n  \"[| cauchy xs ; NF (xs) convergeTo y |] ==> xs convergeTo y\"\napply (simp add: convergeTo_def)\napply (intro allI impI)\napply (drule_tac x=\"eps/2\" in spec)\napply (simp)\napply (erule exE)\n\napply (subgoal_tac \"EX n. (1 / 2) ^ n < eps/2\")\napply (erule exE)\napply (rename_tac eps N M)\n\napply (rule_tac x=\"Nmin xs ((1/2)^(max N M))\" in exI)\napply (intro allI impI)\n\napply (insert triangle_inequality_ms)\napply (drule_tac x=\"y\" in spec)\napply (drule_tac x=\"xs (Nmin xs ((1/2)^(max N M)))\" in spec)\napply (drule_tac x=\"xs m\" in spec)\n\napply (drule_tac x=\"max N M\" in spec)\n(* apply (simp add: le_maxI1) *)\napply (simp add: NF_def)\n\n(* *)\n apply (subgoal_tac \n   \"distance(xs (Nmin xs ((1 / 2) ^ max N M)), xs m) <= (1 / 2) ^ max N M\")\n apply (subgoal_tac \"((1::real) / 2) ^ max N M <= (1 / 2) ^ M\")\n apply (simp (no_asm_simp) add: max_def power_decreasing)   (* modified for 2020 *)\n apply (simp)\n \n apply (rule Nmin_cauchy)\n apply (simp, simp, simp, simp)\n apply (rule pow_convergence)\n apply (simp_all)\ndone\n\n(*** iff ***)\n\nlemma normal_form_seq_same_Limit:\n  \"cauchy xs ==> xs convergeTo y = NF(xs) convergeTo y\"\napply (rule iffI)\napply (simp add: normal_form_seq_same_Limit_only_if)\napply (simp add: normal_form_seq_same_Limit_if)\ndone\n\nend\n", "meta": {"author": "yoshinao-isobe", "repo": "CSP-Prover", "sha": "806fbe330d7e23279675a2eb351e398cb8a6e0a8", "save_path": "github-repos/isabelle/yoshinao-isobe-CSP-Prover", "path": "github-repos/isabelle/yoshinao-isobe-CSP-Prover/CSP-Prover-806fbe330d7e23279675a2eb351e398cb8a6e0a8/CSP/Norm_seq.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357529306639, "lm_q2_score": 0.8198933447152497, "lm_q1q2_score": 0.7108768434580269}}
{"text": "section \"Binomial Heaps\"\n\ntheory BinomialHeap\n  imports Main \"HOL-Library.Multiset\" \"Eval_Base.Eval_Base\"\nbegin\n\nlocale BinomialHeapStruc_loc\nbegin\n\nsubsection \\<open>Datatype Definition\\<close>\n\ntext \\<open>Binomial heaps are lists of binomial trees.\\<close>\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 \\<open>Combine two binomial trees (of rank $r$) to one (of rank $r+1$).\\<close>\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 \\<open>Return a multiset with all (element, priority) pairs from a queue.\\<close>\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  apply2(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  apply2(induct q)\n  apply(simp)\n  apply(simp add: union_ac)\ndone\n\nsubsubsection \"Invariant\"\n\ntext \\<open>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\\<close>\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 \\<open>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\\<close>\n\ntext \\<open>First part: All trees of the queue satisfy the tree invariant:\\<close>\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 \\<open>Second part: Trees have distinct rank, and are ordered by \n  ascending rank:\\<close>\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 \\<open>Invariant for binomial queues:\\<close>\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\nproof2(induct r arbitrary: e a ts)\n  case 0\n  then show ?case by simp\nnext\n  case (Suc r)\n  from Suc(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 Suc(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 Suc(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)\"\napply2(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'\"\napply2(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)\"\napply2(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'])\" \nproof2 (induct bq)\n  case Nil\n  then show ?case by (simp add: invar_def)\nnext\n  case (Cons a bq)\n  from \\<open>invar (a # bq)\\<close> have \"invar bq\" by (rule invar_cons_down)\n  with Cons have \"invar (bq @ [t'])\" by simp\n  with Cons show ?case by (cases bq) (simp_all add: invar_def)\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_mset(queue_to_multiset ts). a \\<le> snd x)\"\n\ntext \\<open>The invariant for trees implies heap order.\\<close>\nlemma tree_invar_heap_ordered:\n  assumes \"tree_invar t\"\n  shows \"heap_ordered t\"\nproof (cases t)\n  case (Node e a nat list)\n  with assms show ?thesis\n  proof2 (induct nat arbitrary: t e a list)\n    case 0\n    then show ?case by simp\n  next\n    case (Suc nat t)\n    then 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 Suc(1)[OF O(1) t1] Suc(1)[OF O(2) t2]\n    show ?case by (cases \"a1 \\<le> a2\") auto\n  qed\nqed\n\nsubsubsection \"Height and Length\"\ntext \\<open>\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\\<close>\n\ntext \\<open>Height of a tree and queue\\<close>\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\n  done\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\"\nproof2 (induct r arbitrary: e a ts)\n  case 0\n  then show ?case by simp\nnext\n  case (Suc r)\n  from Suc(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    Suc(1)[OF inv1] Suc(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\"\nproof2 (induct r arbitrary: e a ts)\n  case 0\n  then show ?case by simp\nnext\n  case (Suc r)\n  from Suc(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 Suc(1)[OF inv1] Suc(1)[OF inv2] Suc(2) show ?case\n    by (cases \"a1 \\<le> a2\") simp_all\nqed\n\ntext \\<open>A binomial tree of height $h$ contains exactly $2^{h}$ elements\\<close>\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  by (cases t) (simp only: tree_rank_estimate BinomialTree.sel(3)) \n\n\nlemma invar_butlast: \"invar (bq @ [t]) \\<Longrightarrow> invar bq\"\n  unfolding invar_def\n  apply2 (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  apply2 (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))\"\nproof2 (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 [simp]: (Cons xxs xx)\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_sum_list: \n  \"size (queue_to_multiset bq) = sum_list (map (size \\<circ> tree_to_multiset) bq)\"\n  apply2 (induct bq) by simp_all\n\ntext \\<open>\n  A binomial heap of length $l$ contains at least $2^l - 1$ elements. \n\\<close>\ntheorem queue_length_estimate_lower: \n  \"invar bq \\<Longrightarrow> (size (queue_to_multiset bq)) \\<ge> 2^(length bq) - 1\"\nproof2 (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_sum_list)\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::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::nat) ^ length (xs @ [x]) = (2::nat) ^ (length xs) + (2::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 \\<open>Operations\\<close>\n\nsubsubsection \"Empty\"\nlemma empty_correct[simp]: \n  \"invar Nil\"\n  \"queue_to_multiset Nil = {#}\"\n  by (simp_all add: invar_def)\n  \ntext \\<open>The empty multiset is represented by exactly the empty queue\\<close>\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 \\<open>Inserts a binomial tree into a binomial queue, such that the queue \n  does not contain two trees of same rank.\\<close>\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 \\<open>Inserts an element with priority into the queue.\\<close>\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: \"queue_invar q \\<Longrightarrow>\n  queue_to_multiset (insert e a q) = queue_to_multiset q + {# (e,a) #}\"\nby(simp add: ins_mset union_ac insert_def)\n\nlemma ins_queue_invar: \"\\<lbrakk>tree_invar t; queue_invar q\\<rbrakk> \\<Longrightarrow> queue_invar (ins t q)\"\nproof2 (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 [simp]: True\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 \\<open>tree_invar t\\<close> 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'))\"\n  apply(auto)\n  apply2(induct bq arbitrary: t t')\n  apply(simp add: rank_link)\nproof goal_cases\n  case prems: (1 a bq t t')\n  thus ?case\n    apply(cases \"rank (link t' t) = rank a\")\n    apply(auto simp add: rank_link)\n  proof goal_cases\n    case 1\n    note * = this and \\<open>\\<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))\\<close>[of a \"(link t' t)\"] \n    show ?case\n    proof (cases \"rank (hd (ins (link (link t' t) a) bq)) = rank a\")\n      case True\n      with * show ?thesis by simp\n    next\n      case False\n      with * have \"rank a \\<le> rank (hd (ins (link (link t' t) a) bq))\" \n        by (simp add: rank_link)\n      with * show ?thesis 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> [])\"\n  apply2(induct bq arbitrary: t)\n  apply(auto)\nproof goal_cases\n  case prems: (1 a bq t)\n  hence r: \"rank (link t a) = rank a + 1\" by (simp add: rank_link)\n  from prems r and prems(1)[of \"(link t a)\"] show ?case by (cases bq) auto\nqed\n\nlemma rank_invar_ins: \"rank_invar bq \\<Longrightarrow> rank_invar (ins t bq)\"\n  apply2(induct bq arbitrary: t)\n  apply(simp)\n  apply(auto)\nproof goal_cases\n  case prems: (1 a bq t)\n  hence inv: \"rank_invar (ins t bq)\" by (cases bq) simp_all\n  from prems have hd: \"bq \\<noteq> [] \\<Longrightarrow> rank a < rank (hd bq)\"  \n    by (cases bq) auto\n  from prems 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 prems 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 prems and inv and hd show ?case by (auto simp add: rank_invar_hd_cons)\nnext\n  case prems: (2 a bq t)\n  hence inv: \"rank_invar bq\" by (cases bq) simp_all\n  with prems and prems(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 \\<open>Melds two queues.\\<close>\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')\"\nproof2 (induct q q' rule: meld.induct)\n  case 1\n  then show ?case by simp\nnext\n  case 2\n  then show ?case by simp\nnext\n  case (3 t1 bq1 t2 bq2)\n  consider (lt) \"rank t1 < rank t2\" | (gt) \"rank t1 > rank t2\" | (eq) \"rank t1 = rank t2\"\n    by atomize_elim auto\n  then show ?case\n  proof cases\n    case lt\n    from 3(4) have inv_bq1: \"queue_invar bq1\" by simp\n    from 3(4) have inv_t1: \"tree_invar t1\" by simp\n    from 3(1)[OF lt inv_bq1 3(5)] inv_t1 lt\n    show ?thesis by simp\n  next\n    case gt\n    from 3(5) have inv_bq2: \"queue_invar bq2\" by simp\n    from 3(5) have inv_t2: \"tree_invar t2\" by simp\n    from gt have \"\\<not> rank t1 < rank t2\" by simp\n    from 3(2)[OF this gt 3(4) inv_bq2] inv_t2 gt\n    show ?thesis by simp\n  next\n    case eq\n    from 3(4) have inv_bq1: \"queue_invar bq1\" by simp\n    from 3(4) have inv_t1: \"tree_invar t1\" by simp\n    from 3(5) have inv_bq2: \"queue_invar bq2\" by simp\n    from 3(5) have inv_t2: \"tree_invar t2\" by simp\n    note inv_link = link_tree_invar[OF inv_t1 inv_t2 eq]\n    from eq have *: \"\\<not> rank t1 < rank t2\" \"\\<not> rank t2 < rank t1\" by simp_all\n    note inv_meld = 3(3)[OF * inv_bq1 inv_bq2]\n    from ins_queue_invar[OF inv_link inv_meld] *\n    show ?thesis by simp\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))\"\n  apply2(induct bq arbitrary: t)\n  apply(auto)\nproof goal_cases\n  case prems: (1 a bq t)\n  hence inv: \"rank_invar bq\" by (cases bq) simp_all\n  from prems have r: \"rank (link t a) = rank a + 1\" by (simp add: rank_link)\n  with prems and inv and prems(1)[of \"(link t a)\"] show ?case by (cases bq) auto\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))\"\nproof2 (induct bq1 bq2 rule: meld.induct)\n  case 1\n  then show ?case by simp\nnext\n  case 2\n  then show ?case by simp\nnext\n  case (3 t1 bq1 t2 bq2)\n  from 3 have inv1: \"rank_invar bq1\" by (cases bq1) simp_all\n  from 3 have inv2: \"rank_invar bq2\" by (cases bq2) simp_all\n  \n  from inv1 and inv2 and 3 show ?case\n  proof (auto, goal_cases)\n    let ?t = \"t2\"\n    let ?bq = \"bq2\"\n    let ?meld = \"rank t2 < rank (hd (meld (t1 # bq1) bq2))\"\n    case prems: 1\n    hence \"?bq \\<noteq> [] \\<Longrightarrow> rank ?t < rank (hd ?bq)\" \n      by (simp add: rank_invar_not_empty_hd)\n    with prems have ne: \"?bq \\<noteq> [] \\<Longrightarrow> ?meld\" by simp\n    from prems have \"?bq = [] \\<Longrightarrow> ?meld\" by simp\n    with ne have \"?meld\" by (cases \"?bq = []\")\n    with prems show ?case by (simp add: rank_invar_hd_cons)\n  next \\<comment> \\<open>analog\\<close>\n    let ?t = \"t1\"\n    let ?bq = \"bq1\"\n    let ?meld = \"rank t1 < rank (hd (meld bq1 (t2 # bq2)))\"\n    case prems: 2\n    hence \"?bq \\<noteq> [] \\<Longrightarrow> rank ?t < rank (hd ?bq)\" \n      by (simp add: rank_invar_not_empty_hd)\n    with prems have ne: \"?bq \\<noteq> [] \\<Longrightarrow> ?meld\" by simp\n    from prems have \"?bq = [] \\<Longrightarrow> ?meld\" by simp\n    with ne have \"?meld\" by (cases \"?bq = []\")\n    with prems show ?case by (simp add: rank_invar_hd_cons)\n  next\n    case 3\n    thus ?case by (simp add: rank_invar_ins)\n  next\n    case prems: 4 (* Ab hier wirds h\u00e4sslich *)\n    then 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 prems\n    have mm: \"min (rank (hd bq1)) (rank (hd bq2)) \\<le> rank (hd (meld bq1 bq2))\"\n      by simp\n    from \\<open>rank_invar (t1 # bq1)\\<close> have \"bq1 \\<noteq> [] \\<Longrightarrow> rank t1 < rank (hd bq1)\" \n      by (simp add: rank_invar_not_empty_hd)\n    with prems have r1: \"bq1 \\<noteq> [] \\<Longrightarrow> rank t2 < rank (hd bq1)\" by simp\n    from \\<open>rank_invar (t2 # bq2)\\<close> \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 \\<open>rank_invar (meld bq1 bq2)\\<close> \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'\"\napply2(induct q q' rule: meld.induct)\n  by(auto simp add: link_tree_invar meld_queue_invar ins_mset union_ac)\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 \\<open>Finds the tree containing the minimal element.\\<close>\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)\"\nproof2 (induct bq)\n  case Nil\n  then show ?case by simp\nnext\n  case (Cons _ bq)\n  then show ?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  apply2 (induct bq) by (simp, cases t, auto) \n\nlemma heap_ordered_single: \n\"heap_ordered t = (\\<forall>x \\<in> set_mset (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  apply2 (induct xs rule: getMinTree.induct) by simp_all \n\nlemma getMinTree_min_tree:\n  \"t \\<in> set bq  \\<Longrightarrow> prio (getMinTree bq) \\<le> prio t\"\n  apply2(induct bq arbitrary: t rule: getMinTree.induct) \n  apply simp   \n  defer\n  apply simp\nproof goal_cases\n  case prems: (1 t v va ta)\n  thus ?case\n    apply (cases \"ta = t\")\n    apply auto[1] \n    apply (metis getMinTree_cons prems(1) prems(3) set_ConsD xt1(6))\n    done\nqed\n\nlemma getMinTree_min_prio:\n  assumes \"queue_invar bq\"\n    and \"y \\<in> set_mset (queue_to_multiset bq)\"\n  shows \"prio (getMinTree bq) \\<le> snd y\"\nproof -\n  from assms have \"bq \\<noteq> []\" by (cases bq) simp_all\n  with assms have \"\\<exists> t \\<in> set bq. (y \\<in> set_mset ((tree_to_multiset t)))\"\n  proof2 (induct bq)\n    case Nil\n    then show ?case by simp\n  next\n    case (Cons a bq)\n    thus ?case\n      apply(cases \"y \\<in> set_mset (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_mset (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 assms(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 ?thesis by simp\nqed\n\ntext \\<open>Finds the minimal Element in the queue.\\<close>\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_mset (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_mset (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 \\<open>Removes the first tree, which has the priority $a$ within his root.\\<close>\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 \\<open>Returns the queue without the minimal element.\\<close>\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 \\<subseteq># queue_to_multiset q\"\nproof2(induct q)\n  case Nil\n  then show ?case by simp\nnext\n  case (Cons a q)\n  show ?case\n  proof (cases \"t = a\")\n    case True\n    then show ?thesis by simp\n  next\n    case False\n    with Cons have t_in_q: \"t \\<in> set q\" by simp\n    have \"queue_to_multiset q \\<subseteq># queue_to_multiset (a # q)\"\n      by simp\n    from subset_mset.order_trans[OF Cons(1)[OF t_in_q] this] show ?thesis .\n  qed\nqed\n  \n\n\nlemma remove1Prio_remove1[simp]: \n  \"remove1Prio (prio (getMinTree bq)) bq = remove1 (getMinTree bq) bq\"\nproof2 (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      apply2 (induct bq rule: getMinTree.induct) by auto\n    from ne False have \"prio t \\<noteq> prio (getMinTree bq)\" \n      apply2 (induct bq rule: getMinTree.induct) by 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)\"\nproof (cases q)\n  case Nil\n  with assms show ?thesis by simp\nnext\n  case Cons\n  from NE and mintree_exists[of q] INV \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 INV, of \"getMinTree q\"]\n  from meld_queue_invar[OF inv_rev inv_rem] show ?thesis\n    by (simp add: deleteMin_def Let_def)\nqed\n\nlemma children_rank_less: \n  assumes \"tree_invar t\"\n  shows \"\\<forall>t' \\<in> set (children t). rank t' < rank t\"\nproof (cases t)\n  case (Node e a nat list)\n  with assms show ?thesis\n  proof2 (induct nat arbitrary: t e a list) \n    case 0\n    then show ?case by simp\n  next\n    case (Suc nat)\n    then obtain e1 a1 ts1 e2 a2 ts2 where \n      O: \"tree_invar (Node e1 a1 nat ts1)\" \"tree_invar (Node e2 a2 nat ts2)\"\n        \"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 Suc(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 Suc(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 Suc(3) p1 p2 ch_id show ?case by simp\n  qed\nqed\n\nlemma strong_rev_children:\n  assumes \"tree_invar t\"\n  shows \"invar (rev (children t))\"\n  unfolding invar_def\nproof (cases t)\n  case (Node e a nat list)\n  with assms show \"queue_invar (rev (children t)) \\<and> rank_invar (rev (children t))\"\n  proof2 (induct \"nat\" arbitrary: t e a list)\n    case 0\n    then show ?case by simp\n  next\n    case (Suc nat)\n    then obtain e1 a1 ts1 e2 a2 ts2 where \n      O: \"tree_invar (Node e1 a1 nat ts1)\" \"tree_invar (Node e2 a2 nat ts2)\"\n        \"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 Suc(1)[of \"Node e1 a1 nat ts1\" \"e1\" \"a1\" \"ts1\"]\n    have rev_ts1: \"invar (rev ts1)\" by (simp add: invar_def)\n    from O children_rank_less[of \"Node e1 a1 nat ts1\"]\n    have  \"\\<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 Suc(1)[of \"Node e2 a2 nat ts2\" \"e2\" \"a2\" \"ts2\"]\n    have rev_ts2: \"invar (rev ts2)\" by (simp add: invar_def)\n    from O children_rank_less[of \"Node e2 a2 nat ts2\"]\n    have \"\\<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  apply2(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)\" \nproof2 (induct bq arbitrary: t) \n  case Nil\n  then show ?case by simp\nnext\n  case (Cons a bq) \n  show ?case \n  proof (cases \"t=a\")\n    case True\n    from Cons(2) have \"invar bq\" by (rule invar_cons_down)\n    with True show ?thesis by simp\n  next\n    case False\n    from Cons(2) have \"invar bq\" by (rule invar_cons_down)\n    with Cons(1)[of \"t\"] have si1: \"invar (remove1 t bq)\" .\n    from False have \"invar (remove1 t (a # bq)) = invar (a # (remove1 t bq))\"\n      by simp\n    show ?thesis\n    proof (cases \"remove1 t bq\")\n      case Nil\n      with si1 Cons(2) False show ?thesis by (simp add: invar_def)\n    next\n      case Cons': (Cons aa list)\n      from Cons have \"tree_invar a\" by (simp add: invar_def)\n      from Cons first_less[of \"a\" \"bq\"] have \"\\<forall>t \\<in> set (remove1 t bq). rank a < rank t\"\n        by (metis notin_set_remove1 invar_def) \n      with Cons' have \"rank a < rank aa\" by simp\n      with si1 Cons(2) False Cons' invar_cons_up[of \"aa\" \"list\" \"a\"] show ?thesis\n        by (simp add: invar_def)\n    qed\n  qed\nqed  \n\ntheorem deleteMin_invar:\n  assumes \"invar bq\"\n    and \"bq \\<noteq> []\"\n  shows \"invar (deleteMin bq)\"\nproof -\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 assms 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\"]\n  have m1: \"invar (rev (children (getMinTree bq)))\" .\n  from strong_remove1[of \"bq\" \"getMinTree bq\"] assms(1)\n  have 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 \"invar (meld (rev (children (getMinTree bq))) (remove1 (getMinTree bq) bq))\" .\n  with eq show ?thesis ..\nqed\n\nlemma children_mset: \"queue_to_multiset (children t) = \n  tree_to_multiset t - {# (val t, prio t) #}\"\nproof (cases t)\n  case (Node e a nat list)\n  thus ?thesis apply2 (induct list) by simp_all\nqed\n\nlemma deleteMin_mset:\n  assumes \"queue_invar q\"\n    and \"q \\<noteq> Nil\"\n  shows \"queue_to_multiset (deleteMin q) = queue_to_multiset q - {# (findMin q) #}\"\nproof -\n  from assms mintree_exists[of \"q\"] have min_in_q: \"getMinTree q \\<in> set q\" by auto\n  with assms(1) have inv_min: \"tree_invar (getMinTree q)\" \n    by (simp add: queue_invar_def)\n  from assms(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 assms(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)) #} \\<subseteq># ?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_subset_eq_multiset_union_diff_commute[OF min_subset_q, of \"?MT\"]\n  show ?thesis 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 (overloaded) ('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 \\<open>\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 \\<open>'a\\<close>.\n\\<close>\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_mset (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 \\<open>Correctness lemmas to be used with simplifier\\<close>\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 \\<open>\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} \\<open>BinomialHeap.empty_correct\\<close>:\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} \\<open>BinomialHeap.isEmpty_correct\\<close>:\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} \\<open>BinomialHeap.insert_correct\\<close>:\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} \\<open>BinomialHeap.findMin_correct\\<close>:\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} \\<open>BinomialHeap.deleteMin_correct\\<close>:\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} \\<open>BinomialHeap.meld_correct\\<close>:\n    @{thm [display] BinomialHeap.meld_correct[no_vars]}\n\n\\<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/Evaluation_PLDI_Small/Binomial-Heaps/BinomialHeap.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357598021707, "lm_q2_score": 0.8198933337131076, "lm_q1q2_score": 0.710876839552679}}
{"text": "(*<*)\ntheory GoedelProof_P1\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>G\\\"odel's Argument, Formally\\<close>\n\ntext\\<open> \n \"G\\\"odel's particular version of the argument is a direct descendent of that of Leibniz, which in turn derives\n  from one of Descartes. These arguments all have a two-part structure: prove God's existence is necessary,\n  if possible; and prove God's existence is possible.\" @{cite \"Fitting\"}, p. 138. \\<close> \n\nsubsection \\<open>Part I - God's Existence is Possible\\<close>\n\ntext\\<open>  We separate G\\\"odel's Argument as presented in Fitting's textbook (ch. 11) in two parts. For the first one, while Leibniz provides\n  some kind of proof for the compatibility of all perfections, G\\\"odel goes on to prove an analogous result:\n \\emph{(T1) Every positive property is possibly instantiated}, which together with \\emph{(T2) God is a positive property}\n  directly implies the conclusion. In order to prove \\emph{T1}, G\\\"odel assumes \\emph{A2: Any property entailed by a positive property is positive}. \\<close>\ntext\\<open>  We are currently contemplating a follow-up analysis of the philosophical implications of these axioms,\n which encompasses some criticism of the notion of \\emph{property entailment} used by G\\\"odel throughout the argument. \\<close>\n  \nsubsubsection \\<open>General Definitions\\<close>\n               \nabbreviation existencePredicate::\"\\<up>\\<langle>\\<zero>\\<rangle>\" (\"E!\") \n  where \"E! x  \\<equiv> \\<lambda>w. (\\<^bold>\\<exists>\\<^sup>Ey. y\\<^bold>\\<approx>x) w\" \\<comment> \\<open>existence predicate in object language\\<close>\n    \nlemma \"E! x w \\<longleftrightarrow> existsAt x w\" \n  by simp \\<comment> \\<open>safety check: @{text \"E!\"} correctly matches its meta-logical counterpart\\<close>\n\nconsts positiveProperty::\"\\<up>\\<langle>\\<up>\\<langle>\\<zero>\\<rangle>\\<rangle>\" (\"\\<P>\") \\<comment> \\<open>positiveness/perfection\\<close>\n  \ntext\\<open>  Definitions of God (later shown to be equivalent under axiom \\emph{A1b}):  \\<close>    \nabbreviation God::\"\\<up>\\<langle>\\<zero>\\<rangle>\" (\"G\") where \"G \\<equiv> (\\<lambda>x. \\<^bold>\\<forall>Y. \\<P> Y \\<^bold>\\<rightarrow> Y x)\"\nabbreviation God_star::\"\\<up>\\<langle>\\<zero>\\<rangle>\" (\"G*\") where \"G* \\<equiv> (\\<lambda>x. \\<^bold>\\<forall>Y. \\<P> Y \\<^bold>\\<leftrightarrow> Y x)\"\n  \ntext\\<open>  Definitions needed to formalise \\emph{A3}:  \\<close>\nabbreviation appliesToPositiveProps::\"\\<up>\\<langle>\\<up>\\<langle>\\<up>\\<langle>\\<zero>\\<rangle>\\<rangle>\\<rangle>\" (\"pos\") where\n  \"pos Z \\<equiv>  \\<^bold>\\<forall>X. Z X \\<^bold>\\<rightarrow> \\<P> X\"  \nabbreviation intersectionOf::\"\\<up>\\<langle>\\<up>\\<langle>\\<zero>\\<rangle>,\\<up>\\<langle>\\<up>\\<langle>\\<zero>\\<rangle>\\<rangle>\\<rangle>\" (\"intersec\") where\n  \"intersec X Z \\<equiv>  \\<^bold>\\<box>(\\<^bold>\\<forall>x.(X x \\<^bold>\\<leftrightarrow> (\\<^bold>\\<forall>Y. (Z Y) \\<^bold>\\<rightarrow> (Y x))))\" \\<comment> \\<open>quantifier is possibilist\\<close>  \nabbreviation Entailment::\"\\<up>\\<langle>\\<up>\\<langle>\\<zero>\\<rangle>,\\<up>\\<langle>\\<zero>\\<rangle>\\<rangle>\" (infix \"\\<Rrightarrow>\" 60) where\n  \"X \\<Rrightarrow> Y \\<equiv>  \\<^bold>\\<box>(\\<^bold>\\<forall>\\<^sup>Ez. X z \\<^bold>\\<rightarrow> Y z)\"\ntext\\<open> \\bigbreak \\<close>\n  \nsubsubsection \\<open>Axioms\\<close>\n    \naxiomatization where\n  A1a:\"\\<lfloor>\\<^bold>\\<forall>X. \\<P> (\\<^bold>\\<rightharpoondown>X) \\<^bold>\\<rightarrow> \\<^bold>\\<not>(\\<P> X) \\<rfloor>\" and      \\<comment> \\<open>axiom 11.3A\\<close>\n  A1b:\"\\<lfloor>\\<^bold>\\<forall>X. \\<^bold>\\<not>(\\<P> X) \\<^bold>\\<rightarrow> \\<P> (\\<^bold>\\<rightharpoondown>X)\\<rfloor>\" and       \\<comment> \\<open>axiom 11.3B\\<close>\n  A2: \"\\<lfloor>\\<^bold>\\<forall>X Y. (\\<P> X \\<^bold>\\<and> (X \\<Rrightarrow> Y)) \\<^bold>\\<rightarrow> \\<P> Y\\<rfloor>\" and   \\<comment> \\<open>axiom 11.5\\<close>\n  A3: \"\\<lfloor>\\<^bold>\\<forall>Z X. (pos Z \\<^bold>\\<and> intersec X Z) \\<^bold>\\<rightarrow> \\<P> X\\<rfloor>\" \\<comment> \\<open>axiom 11.10\\<close>\n\nlemma True nitpick[satisfy] oops       \\<comment> \\<open>model found: axioms are consistent\\<close>\n    \nlemma \"\\<lfloor>D\\<rfloor>\"  using A1a A1b A2 by blast \\<comment> \\<open>axioms already imply \\emph{D} axiom\\<close>\nlemma \"\\<lfloor>D\\<rfloor>\" using A1a A3 by metis\n\nsubsubsection \\<open>Theorems\\<close>\n    \nlemma \"\\<lfloor>\\<^bold>\\<exists>X. \\<P> X\\<rfloor>\" using A1b by auto\nlemma \"\\<lfloor>\\<^bold>\\<exists>X. \\<P> X \\<^bold>\\<and>  \\<^bold>\\<diamond>\\<^bold>\\<exists>\\<^sup>E X\\<rfloor>\" using A1a A1b A2 by metis\n    \ntext\\<open>  Being self-identical is a positive property:  \\<close>\nlemma \"\\<lfloor>(\\<^bold>\\<exists>X. \\<P> X \\<^bold>\\<and>  \\<^bold>\\<diamond>\\<^bold>\\<exists>\\<^sup>E X) \\<^bold>\\<rightarrow> \\<P> (\\<lambda>x w. x = x)\\<rfloor>\" using A2 by fastforce\n    \ntext\\<open>  Proposition 11.6  \\<close>\nlemma \"\\<lfloor>(\\<^bold>\\<exists>X. \\<P> X) \\<^bold>\\<rightarrow> \\<P> (\\<lambda>x w. x = x)\\<rfloor>\" using A2 by fastforce\n    \nlemma \"\\<lfloor>\\<P> (\\<lambda>x w. x = x)\\<rfloor>\" using A1b A2  by blast\nlemma \"\\<lfloor>\\<P> (\\<lambda>x w. x = x)\\<rfloor>\" using A3 by metis\n                                \ntext\\<open>  Being non-self-identical is a negative property: \\<close>\nlemma \"\\<lfloor>(\\<^bold>\\<exists>X. \\<P> X  \\<^bold>\\<and> \\<^bold>\\<diamond>\\<^bold>\\<exists>\\<^sup>E X) \\<^bold>\\<rightarrow>  \\<P> (\\<^bold>\\<rightharpoondown> (\\<lambda>x w. \\<not>x = x))\\<rfloor>\" \n  using A2 by fastforce\n    \nlemma \"\\<lfloor>(\\<^bold>\\<exists>X. \\<P> X) \\<^bold>\\<rightarrow>  \\<P> (\\<^bold>\\<rightharpoondown> (\\<lambda>x w. \\<not>x = x))\\<rfloor>\" using A2 by fastforce\nlemma \"\\<lfloor>(\\<^bold>\\<exists>X. \\<P> X) \\<^bold>\\<rightarrow>  \\<P> (\\<^bold>\\<rightharpoondown> (\\<lambda>x w. \\<not>x = x))\\<rfloor>\" using A3 by metis \n\ntext\\<open>  Proposition 11.7  \\<close>\nlemma \"\\<lfloor>(\\<^bold>\\<exists>X. \\<P> X) \\<^bold>\\<rightarrow> \\<^bold>\\<not>\\<P> ((\\<lambda>x w. \\<not>x = x))\\<rfloor>\"  using A1a A2 by blast\nlemma \"\\<lfloor>\\<^bold>\\<not>\\<P> (\\<lambda>x w. \\<not>x = x)\\<rfloor>\"  using A1a A2 by blast\n \ntext\\<open>  Proposition 11.8 (Informal Proposition 1) - Positive properties are possibly instantiated:  \\<close>\ntheorem T1: \"\\<lfloor>\\<^bold>\\<forall>X. \\<P> X \\<^bold>\\<rightarrow> \\<^bold>\\<diamond>\\<^bold>\\<exists>\\<^sup>E X\\<rfloor>\" using A1a A2 by blast\n    \ntext\\<open>  Proposition 11.14 - Both defs (\\emph{God/God*}) are equivalent. For improved performance we may prefer to use one or the other:  \\<close>\nlemma GodDefsAreEquivalent: \"\\<lfloor>\\<^bold>\\<forall>x. G x \\<^bold>\\<leftrightarrow> G* x\\<rfloor>\" using A1b by force \n\ntext\\<open>  Proposition 11.15 - Possibilist existence of \\emph{God} directly implies \\emph{A1b}:  \\<close>    \nlemma \"\\<lfloor>\\<^bold>\\<exists> G* \\<^bold>\\<rightarrow> (\\<^bold>\\<forall>X. \\<^bold>\\<not>(\\<P> X) \\<^bold>\\<rightarrow> \\<P> (\\<^bold>\\<rightharpoondown>X))\\<rfloor>\" by meson\n\ntext\\<open>  Proposition 11.16 - \\emph{A3} implies \\emph{P(G)} (local consequence):   \\<close>   \nlemma A3implT2_local: \"\\<lfloor>(\\<^bold>\\<forall>Z X. (pos Z \\<^bold>\\<and> intersec X Z) \\<^bold>\\<rightarrow> \\<P> X) \\<^bold>\\<rightarrow> \\<P> G\\<rfloor>\"\nproof -\n  {\n  fix w\n  have 1: \"pos \\<P> w\" by simp\n  have 2: \"intersec G \\<P> w\" by simp\n  {    \n    assume \"(\\<^bold>\\<forall>Z X. (pos Z \\<^bold>\\<and> intersec X Z) \\<^bold>\\<rightarrow> \\<P> X) w\"\n    hence \"(\\<^bold>\\<forall>X. ((pos \\<P>) \\<^bold>\\<and> (intersec X \\<P>)) \\<^bold>\\<rightarrow> \\<P> X) w\"  by (rule allE)   \n    hence \"(((pos \\<P>) \\<^bold>\\<and> (intersec G \\<P>)) \\<^bold>\\<rightarrow> \\<P> G) w\" by (rule allE)\n    hence 3: \"((pos \\<P> \\<^bold>\\<and> intersec G \\<P>) w) \\<longrightarrow> \\<P> G w\" by simp\n    hence 4: \"((pos \\<P>) \\<^bold>\\<and> (intersec G \\<P>)) w\" using 1 2 by simp\n    from 3 4 have \"\\<P> G w\" by (rule mp)\n  }\n  hence \"(\\<^bold>\\<forall>Z X. (pos Z \\<^bold>\\<and> intersec X Z) \\<^bold>\\<rightarrow> \\<P> X) w  \\<longrightarrow> \\<P> G w\" by (rule impI)\n  } \n  thus ?thesis by (rule allI)\nqed    \n    \ntext\\<open>  \\emph{A3} implies \\<open>P(G)\\<close> (as global consequence): \\<close>\nlemma A3implT2_global: \"\\<lfloor>\\<^bold>\\<forall>Z X. (pos Z \\<^bold>\\<and> intersec X Z) \\<^bold>\\<rightarrow> \\<P> X\\<rfloor> \\<longrightarrow> \\<lfloor>\\<P> G\\<rfloor>\" \n  using A3implT2_local by (rule localImpGlobalCons) \n  \ntext\\<open>  Being Godlike is a positive property. Note that this theorem can be axiomatized directly,\nas noted by Dana Scott (see @{cite \"Fitting\"}, p. 152). We will do so for the second part. \\<close>\ntheorem T2: \"\\<lfloor>\\<P> G\\<rfloor>\" using A3implT2_global A3 by simp\n  \ntext\\<open>  Theorem 11.17 (Informal Proposition 3) - Possibly God exists: \\<close>\ntheorem T3: \"\\<lfloor>\\<^bold>\\<diamond>\\<^bold>\\<exists>\\<^sup>E G\\<rfloor>\"  using T1 T2 by simp\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/Types_Tableaus_and_Goedels_God/GoedelProof_P1.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8670357529306639, "lm_q2_score": 0.8198933359135361, "lm_q1q2_score": 0.7108768358266265}}
{"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\"\n  apply(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\n(* Exercise 3.1 *)\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\nlemma \"optimal (asimp_const a)\"\napply(induction a rule: optimal.induct)\napply(auto split: aexp.split)\ndone\n\n(* Exercise 3.2 *)\n  \n  \n(* Exercise 3.2 *)\nfun sum_asimp :: \"(int * aexp) \\<Rightarrow> aexp \\<Rightarrow> (int * aexp)\" where\n\"sum_asimp (m, vs) (N n) = (n + m, vs)\" |\n\"sum_asimp (m, vs) (V x) = (m, plus (V x) vs)\" |\n\"sum_asimp (m, vs) (Plus a1 a2) = sum_asimp (sum_asimp (m, vs) a1) a2\"\n\nfun plus_pair :: \"(int * aexp) \\<Rightarrow> (int * aexp) \\<Rightarrow> (int * aexp)\" where\n\"plus_pair (n1, vs1) (n2, vs2) = (n1 + n2, Plus vs1 vs2)\"\n\nfun aval_pair :: \"(int * aexp) \\<Rightarrow> state \\<Rightarrow> int\" where\n\"aval_pair (n, a) s = n + aval a s\"\n\n\n\nlemma [simp]:\"\naval_pair (sum_asimp (sum_asimp (0, N 0) a1) a2) s = \naval_pair (sum_asimp ((aval_pair (sum_asimp (0, N 0) a1) s), N 0) a2) s\"\napply(induction a1)\napply(simp)\napply(simp)\napply(induction a2)\napply(simp)\napply(induction x)\napply(simp)\napply(simp)\n    \noops    \n  \n\nlemma [simp]:\"aval (sum_asimp (sum_asimp (m, vs) a1) a2) s = \naval (sum_asimp (0, N 0) a1) s + aval (sum_asimp (0, N 0) a2) s\"\n  oops\n    \nlemma [simp]:\"sum_asimp (m, N 0) a = \n  (case (sum_asimp (0, N 0) a) of\n    (n, y) \\<Rightarrow> (n + m, y))\"\napply(induction a)  \napply(auto split: aexp.split)\n  oops\n\nlemma [simp]:\"\naval (case sum_asimp (m, vs) a of (n, y) \\<Rightarrow> plus (N n) y) s = n\"\noops    \nlemma [simp]:\"\nsum_asimp (sum_asimp (0, N 0) a1) a2 = of (n, y) \\<Rightarrow> plus (N n) y) s\"\n\n  \n  \n(* 1st target. the simplest one. cannot be proved *)\nlemma [simp]:\"\naval (case sum_asimp (m, N 0) a of (n, y) \\<Rightarrow> plus (N n) y) s =\n  m  \n+ aval (case sum_asimp (0, N 0) a of (n, y) \\<Rightarrow> plus (N n) y) s\"\napply(induction a)\napply(auto)\n  oops\n    \nlemma [simp]:\"\naval (case sum_asimp (m, vs) a of (n, y) \\<Rightarrow> plus (N n) y) s =\n  aval (plus (N m) vs) s \n+ aval (case sum_asimp (0, N 0) a of (n, y) \\<Rightarrow> plus (N n) y) s\"\napply(induction a)\napply(auto)\napply(induction vs)\napply(auto split: aexp.split)\n  oops    \n    \nlemma [simp]:\"aval (case sum_asimp (x, N 0) a of (n, y) \\<Rightarrow> AExp.plus (N n) y) s =\n         x + aval (case sum_asimp (0, N 0) a of (n, y) \\<Rightarrow> AExp.plus (N n) y) s\"\napply(induction a)\napply(auto split: aexp.split)\napply(auto)\noops\n    \n(* the most important lemma *)    \nlemma [simp]:\"\naval (case sum_asimp (sum_asimp (0, N 0) a1) a2 of (n, y) \\<Rightarrow> plus (N n) y) s =\n  aval (case sum_asimp (0, N 0) a1 of (n, y) \\<Rightarrow> plus (N n) y) s \n+ aval (case sum_asimp (0, N 0) a2 of (n, y) \\<Rightarrow> plus (N n) y) s\"\n  apply(induction a1)\n  apply(simp)\napply(auto split: aexp.split)\napply(induction a2)\napply(auto split: aexp.split)\noops  \n    \nfun full_asimp :: \"aexp \\<Rightarrow> aexp\" where\n\"full_asimp a = \n  (case sum_asimp (0, N 0) a of\n    (n, vs) \\<Rightarrow> plus (N n) vs)\"\n\nlemma [simp]:\"aval (full_asimp a) s  = aval a s\"\napply(induction a)\napply(auto split: aexp.split)\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/AExp.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357563664174, "lm_q2_score": 0.8198933315126791, "lm_q1q2_score": 0.7108768348278774}}
{"text": "(*  Title:      HOL/MicroJava/BV/Semilat.thy\n    Author:     Tobias Nipkow\n    Copyright   2000 TUM\n\nSemilattices.\n*)\n\nchapter \\<open> Bytecode Verifier \\label{cha:bv} \\<close>\n\nsection \\<open> Semilattices \\<close>\n\ntheory Semilat\nimports Main \"HOL-Library.While_Combinator\"\nbegin\n\ntype_synonym 'a ord    = \"'a \\<Rightarrow> 'a \\<Rightarrow> bool\"\ntype_synonym 'a binop  = \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a\"\ntype_synonym 'a sl     = \"'a set \\<times> 'a ord \\<times> 'a binop\"\n\ndefinition lesub :: \"'a \\<Rightarrow> 'a ord \\<Rightarrow> 'a \\<Rightarrow> bool\"\n  where \"lesub x r y \\<longleftrightarrow> r x y\"\n\ndefinition lesssub :: \"'a \\<Rightarrow> 'a ord \\<Rightarrow> 'a \\<Rightarrow> bool\"\n  where \"lesssub x r y \\<longleftrightarrow> lesub x r y \\<and> x \\<noteq> y\"\n\ndefinition plussub :: \"'a \\<Rightarrow> ('a \\<Rightarrow> 'b \\<Rightarrow> 'c) \\<Rightarrow> 'b \\<Rightarrow> 'c\"\n  where \"plussub x f y = f x y\"\n\nnotation (ASCII)\n  \"lesub\"  (\"(_ /<='__ _)\" [50, 1000, 51] 50) and\n  \"lesssub\"  (\"(_ /<'__ _)\" [50, 1000, 51] 50) and\n  \"plussub\"  (\"(_ /+'__ _)\" [65, 1000, 66] 65)\n\nnotation\n  \"lesub\"  (\"(_ /\\<sqsubseteq>\\<^bsub>_\\<^esub> _)\" [50, 0, 51] 50) and\n  \"lesssub\"  (\"(_ /\\<sqsubset>\\<^bsub>_\\<^esub> _)\" [50, 0, 51] 50) and\n  \"plussub\"  (\"(_ /\\<squnion>\\<^bsub>_\\<^esub> _)\" [65, 0, 66] 65)\n\n(* allow \\<sub> instead of \\<bsub>..\\<esub> *)\nabbreviation (input)\n  lesub1 :: \"'a \\<Rightarrow> 'a ord \\<Rightarrow> 'a \\<Rightarrow> bool\" (\"(_ /\\<sqsubseteq>\\<^sub>_ _)\" [50, 1000, 51] 50)\n  where \"x \\<sqsubseteq>\\<^sub>r y == x \\<sqsubseteq>\\<^bsub>r\\<^esub> y\"\n\nabbreviation (input)\n  lesssub1 :: \"'a \\<Rightarrow> 'a ord \\<Rightarrow> 'a \\<Rightarrow> bool\" (\"(_ /\\<sqsubset>\\<^sub>_ _)\" [50, 1000, 51] 50)\n  where \"x \\<sqsubset>\\<^sub>r y == x \\<sqsubset>\\<^bsub>r\\<^esub> y\"\n\nabbreviation (input)\n  plussub1 :: \"'a \\<Rightarrow> ('a \\<Rightarrow> 'b \\<Rightarrow> 'c) \\<Rightarrow> 'b \\<Rightarrow> 'c\" (\"(_ /\\<squnion>\\<^sub>_ _)\" [65, 1000, 66] 65)\n  where \"x \\<squnion>\\<^sub>f y == x \\<squnion>\\<^bsub>f\\<^esub> y\"\n\ndefinition ord :: \"('a \\<times> 'a) set \\<Rightarrow> 'a ord\"\nwhere\n  \"ord r = (\\<lambda>x y. (x,y) \\<in> r)\"\n\ndefinition order :: \"'a ord \\<Rightarrow> bool\"\nwhere\n  \"order r \\<longleftrightarrow> (\\<forall>x. x \\<sqsubseteq>\\<^sub>r x) \\<and> (\\<forall>x y. x \\<sqsubseteq>\\<^sub>r y \\<and> y \\<sqsubseteq>\\<^sub>r x \\<longrightarrow> x=y) \\<and> (\\<forall>x y z. x \\<sqsubseteq>\\<^sub>r y \\<and> y \\<sqsubseteq>\\<^sub>r z \\<longrightarrow> x \\<sqsubseteq>\\<^sub>r z)\"\n\ndefinition top :: \"'a ord \\<Rightarrow> 'a \\<Rightarrow> bool\"\nwhere\n  \"top r T \\<longleftrightarrow> (\\<forall>x. x \\<sqsubseteq>\\<^sub>r T)\"\n  \ndefinition acc :: \"'a ord \\<Rightarrow> bool\"\nwhere\n  \"acc r \\<longleftrightarrow> wf {(y,x). x \\<sqsubset>\\<^sub>r y}\"\n\ndefinition closed :: \"'a set \\<Rightarrow> 'a binop \\<Rightarrow> bool\"\nwhere\n  \"closed A f \\<longleftrightarrow> (\\<forall>x\\<in>A. \\<forall>y\\<in>A. x \\<squnion>\\<^sub>f y \\<in> A)\"\n\ndefinition semilat :: \"'a sl \\<Rightarrow> bool\"\nwhere\n  \"semilat = (\\<lambda>(A,r,f). order r \\<and> closed A f \\<and> \n                       (\\<forall>x\\<in>A. \\<forall>y\\<in>A. x \\<sqsubseteq>\\<^sub>r x \\<squnion>\\<^sub>f y) \\<and>\n                       (\\<forall>x\\<in>A. \\<forall>y\\<in>A. y \\<sqsubseteq>\\<^sub>r x \\<squnion>\\<^sub>f y) \\<and>\n                       (\\<forall>x\\<in>A. \\<forall>y\\<in>A. \\<forall>z\\<in>A. x \\<sqsubseteq>\\<^sub>r z \\<and> y \\<sqsubseteq>\\<^sub>r z \\<longrightarrow> x \\<squnion>\\<^sub>f y \\<sqsubseteq>\\<^sub>r z))\"\n\ndefinition is_ub :: \"('a \\<times> 'a) set \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> bool\"\nwhere\n  \"is_ub r x y u \\<longleftrightarrow> (x,u)\\<in>r \\<and> (y,u)\\<in>r\"\n\ndefinition is_lub :: \"('a \\<times> 'a) set \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> bool\"\nwhere\n  \"is_lub r x y u \\<longleftrightarrow> is_ub r x y u \\<and> (\\<forall>z. is_ub r x y z \\<longrightarrow> (u,z)\\<in>r)\"\n\ndefinition some_lub :: \"('a \\<times> 'a) set \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> 'a\"\nwhere\n  \"some_lub r x y = (SOME z. is_lub r x y z)\"\n\nlocale Semilat =\n  fixes A :: \"'a set\"\n  fixes r :: \"'a ord\"\n  fixes f :: \"'a binop\"\n  assumes semilat: \"semilat (A, r, f)\"\n\nlemma order_refl [simp, intro]: \"order r \\<Longrightarrow> x \\<sqsubseteq>\\<^sub>r x\"\n  (*<*) by (unfold order_def) (simp (no_asm_simp)) (*>*)\n\nlemma order_antisym: \"\\<lbrakk> order r; x \\<sqsubseteq>\\<^sub>r y; y \\<sqsubseteq>\\<^sub>r x \\<rbrakk> \\<Longrightarrow> x = y\"\n  (*<*) by (unfold order_def) (simp (no_asm_simp)) (*>*)\n\nlemma order_trans: \"\\<lbrakk> order r; x \\<sqsubseteq>\\<^sub>r y; y \\<sqsubseteq>\\<^sub>r z \\<rbrakk> \\<Longrightarrow> x \\<sqsubseteq>\\<^sub>r z\"\n  (*<*) by (unfold order_def) blast (*>*)\n\nlemma order_less_irrefl [intro, simp]: \"order r \\<Longrightarrow> \\<not> x \\<sqsubset>\\<^sub>r x\"\n  (*<*) by (unfold order_def lesssub_def) blast (*>*)\n\nlemma order_less_trans: \"\\<lbrakk> order r; x \\<sqsubset>\\<^sub>r y; y \\<sqsubset>\\<^sub>r z \\<rbrakk> \\<Longrightarrow> x \\<sqsubset>\\<^sub>r z\"\n  (*<*) by (unfold order_def lesssub_def) blast (*>*)\n\nlemma topD [simp, intro]: \"top r T \\<Longrightarrow> x \\<sqsubseteq>\\<^sub>r T\"\n  (*<*) by (simp add: top_def) (*>*)\n\nlemma top_le_conv [simp]: \"\\<lbrakk> order r; top r T \\<rbrakk> \\<Longrightarrow> (T \\<sqsubseteq>\\<^sub>r x) = (x = T)\"\n  (*<*) by (blast intro: order_antisym) (*>*)\n\nlemma semilat_Def:\n\"semilat(A,r,f) \\<longleftrightarrow> order r \\<and> closed A f \\<and> \n                 (\\<forall>x\\<in>A. \\<forall>y\\<in>A. x \\<sqsubseteq>\\<^sub>r x \\<squnion>\\<^sub>f y) \\<and> \n                 (\\<forall>x\\<in>A. \\<forall>y\\<in>A. y \\<sqsubseteq>\\<^sub>r x \\<squnion>\\<^sub>f y) \\<and> \n                 (\\<forall>x\\<in>A. \\<forall>y\\<in>A. \\<forall>z\\<in>A. x \\<sqsubseteq>\\<^sub>r z \\<and> y \\<sqsubseteq>\\<^sub>r z \\<longrightarrow> x \\<squnion>\\<^sub>f y \\<sqsubseteq>\\<^sub>r z)\"\n  (*<*) by (unfold semilat_def) clarsimp (*>*)\n\nlemma (in Semilat) orderI [simp, intro]: \"order r\"\n  (*<*) using semilat by (simp add: semilat_Def) (*>*)\n\nlemma (in Semilat) closedI [simp, intro]: \"closed A f\"\n  (*<*) using semilat by (simp add: semilat_Def) (*>*)\n\nlemma closedD: \"\\<lbrakk> closed A f; x\\<in>A; y\\<in>A \\<rbrakk> \\<Longrightarrow> x \\<squnion>\\<^sub>f y \\<in> A\"\n  (*<*) by (unfold closed_def) blast (*>*)\n\nlemma closed_UNIV [simp]: \"closed UNIV f\"\n  (*<*) by (simp add: closed_def) (*>*)\n\nlemma (in Semilat) closed_f [simp, intro]: \"\\<lbrakk>x \\<in> A; y \\<in> A\\<rbrakk>  \\<Longrightarrow> x \\<squnion>\\<^sub>f y \\<in> A\"\n  (*<*) by (simp add: closedD [OF closedI]) (*>*)\n\nlemma (in Semilat) refl_r [intro, simp]: \"x \\<sqsubseteq>\\<^sub>r x\" by simp\n\nlemma (in Semilat) antisym_r [intro?]: \"\\<lbrakk> x \\<sqsubseteq>\\<^sub>r y; y \\<sqsubseteq>\\<^sub>r x \\<rbrakk> \\<Longrightarrow> x = y\"\n  (*<*) by (rule order_antisym) auto (*>*)\n  \nlemma (in Semilat) trans_r [trans, intro?]: \"\\<lbrakk>x \\<sqsubseteq>\\<^sub>r y; y \\<sqsubseteq>\\<^sub>r z\\<rbrakk> \\<Longrightarrow> x \\<sqsubseteq>\\<^sub>r z\"\n  (*<*) by (auto intro: order_trans) (*>*)\n  \nlemma (in Semilat) ub1 [simp, intro?]: \"\\<lbrakk> x \\<in> A; y \\<in> A \\<rbrakk> \\<Longrightarrow> x \\<sqsubseteq>\\<^sub>r x \\<squnion>\\<^sub>f y\"\n  (*<*) by (insert semilat) (unfold semilat_Def, simp) (*>*)\n\nlemma (in Semilat) ub2 [simp, intro?]: \"\\<lbrakk> x \\<in> A; y \\<in> A \\<rbrakk> \\<Longrightarrow> y \\<sqsubseteq>\\<^sub>r x \\<squnion>\\<^sub>f y\"\n  (*<*) by (insert semilat) (unfold semilat_Def, simp) (*>*)\n\nlemma (in Semilat) lub [simp, intro?]:\n  \"\\<lbrakk> x \\<sqsubseteq>\\<^sub>r z; y \\<sqsubseteq>\\<^sub>r z; x \\<in> A; y \\<in> A; z \\<in> A \\<rbrakk> \\<Longrightarrow> x \\<squnion>\\<^sub>f y \\<sqsubseteq>\\<^sub>r z\"\n  (*<*) by (insert semilat) (unfold semilat_Def, simp) (*>*)\n\nlemma (in Semilat) plus_le_conv [simp]:\n  \"\\<lbrakk> x \\<in> A; y \\<in> A; z \\<in> A \\<rbrakk> \\<Longrightarrow> (x \\<squnion>\\<^sub>f y \\<sqsubseteq>\\<^sub>r z) = (x \\<sqsubseteq>\\<^sub>r z \\<and> y \\<sqsubseteq>\\<^sub>r z)\"\n  (*<*) by (blast intro: ub1 ub2 lub order_trans) (*>*)\n\nlemma (in Semilat) le_iff_plus_unchanged:\n  assumes \"x \\<in> A\" and \"y \\<in> A\"\n  shows \"x \\<sqsubseteq>\\<^sub>r y \\<longleftrightarrow> x \\<squnion>\\<^sub>f y = y\" (is \"?P \\<longleftrightarrow> ?Q\")\n(*<*)\nproof\n  assume ?P\n  with assms show ?Q by (blast intro: antisym_r lub ub2)\nnext\n  assume ?Q\n  then have \"y = x \\<squnion>\\<^bsub>f\\<^esub> y\" by simp\n  moreover from assms have \"x \\<sqsubseteq>\\<^bsub>r\\<^esub> x \\<squnion>\\<^bsub>f\\<^esub> y\" by simp\n  ultimately show ?P by simp\nqed\n(*>*)\n\nlemma (in Semilat) le_iff_plus_unchanged2:\n  assumes \"x \\<in> A\" and \"y \\<in> A\"\n  shows \"x \\<sqsubseteq>\\<^sub>r y \\<longleftrightarrow> y \\<squnion>\\<^sub>f x = y\" (is \"?P \\<longleftrightarrow> ?Q\")\n(*<*)\nproof\n  assume ?P\n  with assms show ?Q by (blast intro: antisym_r lub ub1)\nnext\n  assume ?Q\n  then have \"y = y \\<squnion>\\<^bsub>f\\<^esub> x\" by simp\n  moreover from assms have \"x \\<sqsubseteq>\\<^bsub>r\\<^esub> y \\<squnion>\\<^bsub>f\\<^esub> x\" by simp\n  ultimately show ?P by simp\nqed\n(*>*)\n\nlemma (in Semilat) plus_assoc [simp]:\n  assumes a: \"a \\<in> A\" and b: \"b \\<in> A\" and c: \"c \\<in> A\"\n  shows \"a \\<squnion>\\<^sub>f (b \\<squnion>\\<^sub>f c) = a \\<squnion>\\<^sub>f b \\<squnion>\\<^sub>f c\"\n(*<*)\nproof -\n  from a b have ab: \"a \\<squnion>\\<^sub>f b \\<in> A\" ..\n  from this c have abc: \"(a \\<squnion>\\<^sub>f b) \\<squnion>\\<^sub>f c \\<in> A\" ..\n  from b c have bc: \"b \\<squnion>\\<^sub>f c \\<in> A\" ..\n  from a this have abc': \"a \\<squnion>\\<^sub>f (b \\<squnion>\\<^sub>f c) \\<in> A\" ..\n\n  show ?thesis\n  proof    \n    show \"a \\<squnion>\\<^sub>f (b \\<squnion>\\<^sub>f c) \\<sqsubseteq>\\<^sub>r (a \\<squnion>\\<^sub>f b) \\<squnion>\\<^sub>f c\"\n    proof -\n      from a b have \"a \\<sqsubseteq>\\<^sub>r a \\<squnion>\\<^sub>f b\" .. \n      also from ab c have \"\\<dots> \\<sqsubseteq>\\<^sub>r \\<dots> \\<squnion>\\<^sub>f c\" ..\n      finally have \"a<\": \"a \\<sqsubseteq>\\<^sub>r (a \\<squnion>\\<^sub>f b) \\<squnion>\\<^sub>f c\" .\n      from a b have \"b \\<sqsubseteq>\\<^sub>r a \\<squnion>\\<^sub>f b\" ..\n      also from ab c have \"\\<dots> \\<sqsubseteq>\\<^sub>r \\<dots> \\<squnion>\\<^sub>f c\" ..\n      finally have \"b<\": \"b \\<sqsubseteq>\\<^sub>r (a \\<squnion>\\<^sub>f b) \\<squnion>\\<^sub>f c\" .\n      from ab c have \"c<\": \"c \\<sqsubseteq>\\<^sub>r (a \\<squnion>\\<^sub>f b) \\<squnion>\\<^sub>f c\" ..    \n      from \"b<\" \"c<\" b c abc have \"b \\<squnion>\\<^sub>f c \\<sqsubseteq>\\<^sub>r (a \\<squnion>\\<^sub>f b) \\<squnion>\\<^sub>f c\" ..\n      from \"a<\" this a bc abc show ?thesis ..\n    qed\n    show \"(a \\<squnion>\\<^sub>f b) \\<squnion>\\<^sub>f c \\<sqsubseteq>\\<^sub>r a \\<squnion>\\<^sub>f (b \\<squnion>\\<^sub>f c)\" \n    proof -\n      from b c have \"b \\<sqsubseteq>\\<^sub>r b \\<squnion>\\<^sub>f c\" .. \n      also from a bc have \"\\<dots> \\<sqsubseteq>\\<^sub>r a \\<squnion>\\<^sub>f \\<dots>\" ..\n      finally have \"b<\": \"b \\<sqsubseteq>\\<^sub>r a \\<squnion>\\<^sub>f (b \\<squnion>\\<^sub>f c)\" .\n      from b c have \"c \\<sqsubseteq>\\<^sub>r b \\<squnion>\\<^sub>f c\" ..\n      also from a bc have \"\\<dots> \\<sqsubseteq>\\<^sub>r a \\<squnion>\\<^sub>f \\<dots>\" ..\n      finally have \"c<\": \"c \\<sqsubseteq>\\<^sub>r a \\<squnion>\\<^sub>f (b \\<squnion>\\<^sub>f c)\" .\n      from a bc have \"a<\": \"a \\<sqsubseteq>\\<^sub>r a \\<squnion>\\<^sub>f (b \\<squnion>\\<^sub>f c)\" ..\n      from \"a<\" \"b<\" a b abc' have \"a \\<squnion>\\<^sub>f b \\<sqsubseteq>\\<^sub>r a \\<squnion>\\<^sub>f (b \\<squnion>\\<^sub>f c)\" ..\n      from this \"c<\" ab c abc' show ?thesis ..\n    qed\n  qed\nqed\n(*>*)\n\nlemma (in Semilat) plus_com_lemma:\n  \"\\<lbrakk>a \\<in> A; b \\<in> A\\<rbrakk> \\<Longrightarrow> a \\<squnion>\\<^sub>f b \\<sqsubseteq>\\<^sub>r b \\<squnion>\\<^sub>f a\"\n(*<*)\nproof -\n  assume a: \"a \\<in> A\" and b: \"b \\<in> A\"  \n  from b a have \"a \\<sqsubseteq>\\<^sub>r b \\<squnion>\\<^sub>f a\" .. \n  moreover from b a have \"b \\<sqsubseteq>\\<^sub>r b \\<squnion>\\<^sub>f a\" ..\n  moreover note a b\n  moreover from b a have \"b \\<squnion>\\<^sub>f a \\<in> A\" ..\n  ultimately show ?thesis ..\nqed\n(*>*)\n\nlemma (in Semilat) plus_commutative:\n  \"\\<lbrakk>a \\<in> A; b \\<in> A\\<rbrakk> \\<Longrightarrow> a \\<squnion>\\<^sub>f b = b \\<squnion>\\<^sub>f a\"\n  (*<*) by(blast intro: order_antisym plus_com_lemma) (*>*)\n\nlemma is_lubD:\n  \"is_lub r x y u \\<Longrightarrow> is_ub r x y u \\<and> (\\<forall>z. is_ub r x y z \\<longrightarrow> (u,z) \\<in> r)\"\n  (*<*) by (simp add: is_lub_def) (*>*)\n\nlemma is_ubI:\n  \"\\<lbrakk> (x,u) \\<in> r; (y,u) \\<in> r \\<rbrakk> \\<Longrightarrow> is_ub r x y u\"\n  (*<*) by (simp add: is_ub_def) (*>*)\n\nlemma is_ubD:\n  \"is_ub r x y u \\<Longrightarrow> (x,u) \\<in> r \\<and> (y,u) \\<in> r\"\n  (*<*) by (simp add: is_ub_def) (*>*)\n\n\nlemma is_lub_bigger1 [iff]:  \n  \"is_lub (r^* ) x y y = ((x,y)\\<in>r^* )\"\n(*<*)\napply (unfold is_lub_def is_ub_def)\napply blast\ndone\n(*>*)\n\nlemma is_lub_bigger2 [iff]:\n  \"is_lub (r^* ) x y x = ((y,x)\\<in>r^* )\"\n(*<*)\napply (unfold is_lub_def is_ub_def)\napply blast \ndone\n(*>*)\n\nlemma extend_lub:\n  \"\\<lbrakk> single_valued r; is_lub (r^* ) x y u; (x',x) \\<in> r \\<rbrakk> \n  \\<Longrightarrow> \\<exists>v. is_lub (r^* ) x' y v\"\n(*<*)\napply (unfold is_lub_def is_ub_def)\napply (case_tac \"(y,x) \\<in> r^*\")\n apply (case_tac \"(y,x') \\<in> r^*\")\n  apply blast\n apply (blast elim: converse_rtranclE dest: single_valuedD)\napply (rule exI)\napply (rule conjI)\n apply (blast intro: converse_rtrancl_into_rtrancl dest: single_valuedD)\napply (blast intro: rtrancl_into_rtrancl converse_rtrancl_into_rtrancl \n             elim: converse_rtranclE dest: single_valuedD)\ndone\n(*>*)\n\nlemma single_valued_has_lubs [rule_format]:\n  \"\\<lbrakk> single_valued r; (x,u) \\<in> r^* \\<rbrakk> \\<Longrightarrow> (\\<forall>y. (y,u) \\<in> r^* \\<longrightarrow> \n  (\\<exists>z. is_lub (r^* ) x y z))\"\n(*<*)\napply (erule converse_rtrancl_induct)\n apply clarify\n apply (erule converse_rtrancl_induct)\n  apply blast\n apply (blast intro: converse_rtrancl_into_rtrancl)\napply (blast intro: extend_lub)\ndone\n(*>*)\n\nlemma some_lub_conv:\n  \"\\<lbrakk> acyclic r; is_lub (r^* ) x y u \\<rbrakk> \\<Longrightarrow> some_lub (r^* ) x y = u\"\n(*<*)\napply (simp only: some_lub_def is_lub_def)\napply (rule someI2)\n apply (simp only: is_lub_def)\napply (blast intro: antisymD dest!: acyclic_impl_antisym_rtrancl)\ndone\n(*>*)\n\nlemma is_lub_some_lub:\n  \"\\<lbrakk> single_valued r; acyclic r; (x,u)\\<in>r^*; (y,u)\\<in>r^* \\<rbrakk> \n  \\<Longrightarrow> is_lub (r^* ) x y (some_lub (r^* ) x y)\"\n  (*<*) by (fastforce dest: single_valued_has_lubs simp add: some_lub_conv) (*>*)\n\nsubsection\\<open>An executable lub-finder\\<close>\n\ndefinition exec_lub :: \"('a * 'a) set \\<Rightarrow> ('a \\<Rightarrow> 'a) \\<Rightarrow> 'a binop\"\nwhere\n  \"exec_lub r f x y = while (\\<lambda>z. (x,z) \\<notin> r\\<^sup>*) f y\"\n\nlemma exec_lub_refl: \"exec_lub r f T T = T\"\nby (simp add: exec_lub_def while_unfold)\n\nlemma acyclic_single_valued_finite:\n \"\\<lbrakk>acyclic r; single_valued r; (x,y) \\<in> r\\<^sup>*\\<rbrakk>\n  \\<Longrightarrow> finite (r \\<inter> {a. (x, a) \\<in> r\\<^sup>*} \\<times> {b. (b, y) \\<in> r\\<^sup>*})\"\n(*<*)\napply(erule converse_rtrancl_induct)\n apply(rule_tac B = \"{}\" in finite_subset)\n  apply(simp only:acyclic_def)\n  apply(blast intro:rtrancl_into_trancl2 rtrancl_trancl_trancl)\n apply simp\napply(rename_tac x x')\napply(subgoal_tac \"r \\<inter> {a. (x,a) \\<in> r\\<^sup>*} \\<times> {b. (b,y) \\<in> r\\<^sup>*} =\n                   insert (x,x') (r \\<inter> {a. (x', a) \\<in> r\\<^sup>*} \\<times> {b. (b, y) \\<in> r\\<^sup>*})\")\n apply simp\napply(blast intro:converse_rtrancl_into_rtrancl\n            elim:converse_rtranclE dest:single_valuedD)\ndone\n(*>*)\n\n\nlemma exec_lub_conv:\n  \"\\<lbrakk> acyclic r; \\<forall>x y. (x,y) \\<in> r \\<longrightarrow> f x = y; is_lub (r\\<^sup>*) x y u \\<rbrakk> \\<Longrightarrow>\n  exec_lub r f x y = u\"\n(*<*)\napply(unfold exec_lub_def)\napply(rule_tac P = \"\\<lambda>z. (y,z) \\<in> r\\<^sup>* \\<and> (z,u) \\<in> r\\<^sup>*\" and\n               r = \"(r \\<inter> {(a,b). (y,a) \\<in> r\\<^sup>* \\<and> (b,u) \\<in> r\\<^sup>*})^-1\" in while_rule)\n    apply(blast dest: is_lubD is_ubD)\n   apply(erule conjE)\n   apply(erule_tac z = u in converse_rtranclE)\n    apply(blast dest: is_lubD is_ubD)\n   apply(blast dest:rtrancl_into_rtrancl)\n  apply(rename_tac s)\n  apply(subgoal_tac \"is_ub (r\\<^sup>*) x y s\")\n   prefer 2 apply(simp add:is_ub_def)\n  apply(subgoal_tac \"(u, s) \\<in> r\\<^sup>*\")\n   prefer 2 apply(blast dest:is_lubD)\n  apply(erule converse_rtranclE)\n   apply blast\n  apply(simp only:acyclic_def)\n  apply(blast intro:rtrancl_into_trancl2 rtrancl_trancl_trancl)\n apply(rule finite_acyclic_wf)\n  apply simp\n  apply(erule acyclic_single_valued_finite)\n   apply(blast intro:single_valuedI)\n  apply(simp add:is_lub_def is_ub_def)\n apply simp\n apply(erule acyclic_subset)\n apply blast\napply simp\napply(erule conjE)\napply(erule_tac z = u in converse_rtranclE)\n apply(blast dest: is_lubD is_ubD)\napply(blast dest:rtrancl_into_rtrancl)\ndone\n(*>*)\n\nlemma is_lub_exec_lub:\n  \"\\<lbrakk> single_valued r; acyclic r; (x,u):r^*; (y,u):r^*; \\<forall>x y. (x,y) \\<in> r \\<longrightarrow> f x = y \\<rbrakk>\n  \\<Longrightarrow> is_lub (r^* ) x y (exec_lub r f x y)\"\n  (*<*) by (fastforce dest: single_valued_has_lubs simp add: exec_lub_conv) (*>*)\n\nend\n", "meta": {"author": "susannahej", "repo": "jinja-dci", "sha": "0969fa2c5966204b326395763d7a375e7dc6badf", "save_path": "github-repos/isabelle/susannahej-jinja-dci", "path": "github-repos/isabelle/susannahej-jinja-dci/jinja-dci-0969fa2c5966204b326395763d7a375e7dc6badf/DFA/Semilat.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357563664174, "lm_q2_score": 0.8198933293122507, "lm_q1q2_score": 0.7108768329200273}}
{"text": "theory Lab2_Ex\nimports Main\nbegin\n\n(* Topic: Recursion, induction and counterexamples *)\n\n(* \n  replace :: Old \\<Rightarrow> New \\<Rightarrow> List \\<Rightarrow> List'  \n  Replaces all occurences of Old in List with New.\n*)\nprimrec replace :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a list \\<Rightarrow> 'a list\"\n  where \"replace x y [] = []\"\n  | \"replace x y (z#zs) = (if z = x then y else z)#(replace x y zs)\"\n\nvalue \"replace 1 0 [1, 1, 2] :: int list\"\n\n(*\n  del1 :: Item \\<Rightarrow> List \\<Rightarrow> List'\n  Deletes first occurence of Item in List.\n*)\nprimrec del1 :: \"'a \\<Rightarrow> 'a list \\<Rightarrow> 'a list\"\n  where \"del1 x [] = []\"\n  | \"del1 x (y#ys) = (if y = x then ys else y#(del1 x ys))\"\n\nvalue \"del1 1 [0, 0, 1, 1] :: int list\"\n\n(*\n  delall :: Item \\<Rightarrow> List \\<Rightarrow> List'\n  Deletes all occurences of Item in List.\n*)\nprimrec delall :: \"'a \\<Rightarrow> 'a list \\<Rightarrow> 'a list\"\n  where \"delall x [] = []\"\n  | \"delall x (y#ys) = (if y = x then (delall x ys) else y#(delall x ys))\"\n\nvalue \"delall 0 [1, 1, 0, 0, 1] :: int list\"\n\n(* \u0412\u0430\u0440\u0438\u0430\u043d\u0442 3: 3 \u0438 5\n    3: theorem \"del1 x (del1 y zs) = del1 y (del1 x zs)\"\n    5: theorem \"del1 y (replace x y xs) = del1 x xs\"\n*)\n\n(* \n  prove \n  e.g.:\n    List = [0, 0, 1, 2]\n    del1 0 (del1 1 List) = del1 1 (del1 0 List) = [2]\n*)\ntheorem [simp]: \"del1 x (del1 y zs) = del1 y (del1 x zs)\"\n  apply(induct_tac zs)\n  apply auto\ndone\n\n(* \n  fail to prove \n  e.g.:\n    List = [0, 0, 1, 1]\n    LHS: del1 1 (replace 0 1 List) = [1, 1, 1]\n    RHS: del1 0 List = [0, 1, 1]\n    [1, 1, 1] \\<noteq> [0, 1, 1]\n*)\ntheorem \"del1 y (replace x y xs) = del1 x xs\"\n  apply(induct_tac xs)\n  apply auto\n  quickcheck 1\n  quickcheck 2\n  quickcheck 3\noops\n", "meta": {"author": "NoxChimaera", "repo": "formal-verification", "sha": "b828938e74e9b15e4b03f4ac645e834c7470535f", "save_path": "github-repos/isabelle/NoxChimaera-formal-verification", "path": "github-repos/isabelle/NoxChimaera-formal-verification/formal-verification-b828938e74e9b15e4b03f4ac645e834c7470535f/Lab2_Ex.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357460591568, "lm_q2_score": 0.8198933359135361, "lm_q1q2_score": 0.7108768301927236}}
{"text": "theory ex5_02 imports Main begin\n\nlemma \"(\\<exists>ys zs. xs = ys @ zs \\<and> length ys = length zs) \\<or> (\\<exists> ys zs. xs = ys @ zs \\<and> length ys = length zs + 1)\"\nproof(cases \"even (length xs)\")\n  assume \"even (length xs)\"\n  let ?n = \"length xs\"\n  let ?n2 = \"?n div 2\"\n  let ?ys = \"take ?n2 xs\"\n  let ?zs = \"drop ?n2 xs\"\n  have \"xs = ?ys @ ?zs\" by auto\n  moreover have \"length ?ys = length ?zs\"\n    proof -\n      have \"2 * (length xs div 2) = length xs\"\n        by (meson \\<open>even (length xs)\\<close> even_two_times_div_two)\n      then show ?thesis\n        by (metis (no_types) add_diff_cancel_right' append_eq_conv_conj length_append length_drop length_take mult_2)\n    qed\n  then show ?thesis using calculation by blast \nnext\n  assume \"odd (length xs)\"\n  let ?n = \"length xs\"\n  let ?n2 = \"?n - ?n div 2\"\n  let ?ys = \"take ?n2 xs\"\n  let ?zs = \"drop ?n2 xs\"\n  have \"xs = ?ys @ ?zs\" by auto\n  moreover have \"length ?ys = length ?zs + 1\"\n    proof -\n      have \"2 * (length xs div 2) + 1 = length xs\"\n        using \\<open>odd (length xs)\\<close> odd_two_times_div_two_succ by blast\n      then show ?thesis\n        by simp\n    qed \n  then show ?thesis using calculation by blast\nqed\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_02.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094060543488, "lm_q2_score": 0.7956581000631542, "lm_q1q2_score": 0.7107688647897479}}
{"text": "subsection\\<open>AExp Lexorder\\<close>\n\ntext\\<open>This theory defines a lexicographical ordering on arithmetic expressions such that we can build\norderings for guards and, subsequently, transitions. We make use of the previously established\norderings on variable names and values.\\<close>\n\ntheory AExp_Lexorder\nimports AExp Value_Lexorder\nbegin\n\ntext_raw\\<open>\\snip{height}{1}{2}{%\\<close>\nfun height :: \"'a aexp \\<Rightarrow> nat\"  where\n  \"height (L l2) = 1\" |\n  \"height (V v2) = 1\" |\n  \"height (Plus e1 e2) = 1 + max (height e1) (height e2)\" |\n  \"height (Minus e1 e2) = 1 + max (height e1) (height e2)\" |\n  \"height (Times e1 e2) = 1 + max (height e1) (height e2)\"\ntext_raw\\<open>}%endsnip\\<close>\n\ninstantiation aexp :: (linorder) linorder begin\nfun less_aexp_aux :: \"'a aexp \\<Rightarrow> 'a aexp \\<Rightarrow> bool\"  where\n  \"less_aexp_aux (L l1) (L l2) = (l1 < l2)\" |\n  \"less_aexp_aux (L l1) _ = True\" |\n\n  \"less_aexp_aux (V v1) (L l1) = False\" |\n  \"less_aexp_aux (V v1) (V v2) = (v1 < v2)\" |\n  \"less_aexp_aux (V v1) _ = True\" |\n\n  \"less_aexp_aux (Plus e1 e2) (L l2) = False\" |\n  \"less_aexp_aux (Plus e1 e2) (V v2) = False\" |\n  \"less_aexp_aux (Plus e1 e2) (Plus e1' e2') = ((less_aexp_aux e1 e1') \\<or> ((e1 = e1') \\<and> (less_aexp_aux e2 e2')))\"|\n  \"less_aexp_aux (Plus e1 e2) _ = True\" |\n\n  \"less_aexp_aux (Minus e1 e2) (Minus e1' e2') =  ((less_aexp_aux e1 e1') \\<or> ((e1 = e1') \\<and> (less_aexp_aux e2 e2')))\" |\n  \"less_aexp_aux (Minus e1 e2) (Times e1' e2') = True\" |\n  \"less_aexp_aux (Minus e1 e2) _ = False\" |\n\n  \"less_aexp_aux (Times e1 e2) (Times e1' e2') =  ((less_aexp_aux e1 e1') \\<or> ((e1 = e1') \\<and> (less_aexp_aux e2 e2')))\" |\n  \"less_aexp_aux (Times e1 e2) _ = False\"\n\ndefinition less_aexp :: \"'a aexp \\<Rightarrow> 'a aexp \\<Rightarrow> bool\" where\n  \"less_aexp a1 a2 = (\n    let\n      h1 = height a1;\n      h2 = height a2\n    in\n    if h1 = h2 then\n      less_aexp_aux a1 a2\n    else\n      h1 < h2\n  )\"\n\ndefinition less_eq_aexp :: \"'a aexp \\<Rightarrow> 'a aexp \\<Rightarrow> bool\"\n  where \"less_eq_aexp e1 e2 \\<equiv> (e1 < e2) \\<or> (e1 = e2)\"\n\ndeclare less_aexp_def [simp]\n\nlemma less_aexp_aux_antisym: \"less_aexp_aux x  y = (\\<not>(less_aexp_aux y x) \\<and> (x \\<noteq> y))\"\n  by (induct x y rule: less_aexp_aux.induct, auto)\n\nlemma less_aexp_antisym: \"(x::'a aexp) < y = (\\<not>(y < x) \\<and> (x \\<noteq> y))\"\n  apply (simp add: Let_def)\n  apply standard\n  using less_aexp_aux_antisym apply blast\n  apply (simp add: not_less)\n  apply clarify\n  by (induct x, auto)\n\nlemma less_aexp_aux_trans: \"less_aexp_aux x y \\<Longrightarrow> less_aexp_aux y z \\<Longrightarrow> less_aexp_aux x z\"\nproof (induct x y arbitrary: z rule: less_aexp_aux.induct)\n  case (1 l1 l2)\n  then show ?case by (cases z, auto)\nnext\n  case (\"2_1\" l1 v)\n  then show ?case by (cases z, auto)\nnext\n  case (\"2_2\" l1 v va)\n  then show ?case by (cases z, auto)\nnext\n  case (\"2_3\" l1 v va)\n  then show ?case by (cases z, auto)\nnext\n  case (\"2_4\" l1 v va)\n  then show ?case by (cases z, auto)\nnext\n  case (3 v1 l1)\n  then show ?case by (cases z, auto)\nnext\n  case (4 v1 v2)\n  then show ?case by (cases z, auto)\nnext\n  case (\"5_1\" v1 v va)\n  then show ?case by (cases z, auto)\nnext\n  case (\"5_2\" v1 v va)\n  then show ?case by (cases z, auto)\nnext\n  case (\"5_3\" v1 v va)\n  then show ?case by (cases z, auto)\nnext\n  case (6 e1 e2 l2)\n  then show ?case by (cases z, auto)\nnext\n  case (7 e1 e2 v2)\n  then show ?case by (cases z, auto)\nnext\n  case (8 e1 e2 e1' e2')\n  then show ?case by (cases z, auto)\nnext\n  case (\"9_1\" e1 e2 v va)\n  then show ?case by (cases z, auto)\nnext\n  case (\"9_2\" e1 e2 v va)\n  then show ?case by (cases z, auto)\nnext\n  case (10 e1 e2 e1' e2')\n  then show ?case by (cases z, auto)\nnext\n  case (11 e1 e2 e1' e2')\n  then show ?case by (cases z, auto)\nnext\n  case (\"12_1\" e1 e2 v)\n  then show ?case by (cases z, auto)\nnext\n  case (\"12_2\" e1 e2 v)\n  then show ?case by (cases z, auto)\nnext\n  case (\"12_3\" e1 e2 v va)\n  then show ?case by (cases z, auto)\nnext\n  case (13 e1 e2 e1' e2')\n  then show ?case by (cases z, auto)\nnext\n  case (\"14_1\" e1 e2 v)\n  then show ?case by (cases z, auto)\nnext\n  case (\"14_2\" e1 e2 v)\n  then show ?case by (cases z, auto)\nnext\n  case (\"14_3\" e1 e2 v va)\n  then show ?case by (cases z, auto)\nnext\n  case (\"14_4\" e1 e2 v va)\n  then show ?case by (cases z, auto)\nqed\n\nlemma less_aexp_trans: \"(x::'a aexp) < y \\<Longrightarrow> y < z \\<Longrightarrow> x < z\"\n  apply (simp add: Let_def)\n  apply standard\n   apply (metis AExp_Lexorder.less_aexp_aux_trans dual_order.asym)\n  by presburger\n\ninstance proof\n    fix x y z :: \"'a aexp\"\n    show \"(x < y) = (x \\<le> y \\<and> \\<not> y \\<le> x)\"\n      by (metis less_aexp_antisym less_eq_aexp_def)\n    show \"(x \\<le> x)\"\n      by (simp add: less_eq_aexp_def)\n    show \"x \\<le> y \\<Longrightarrow> y \\<le> z \\<Longrightarrow> x \\<le> z\"\n      by (metis less_aexp_trans less_eq_aexp_def)\n    show \"x \\<le> y \\<Longrightarrow> y \\<le> x \\<Longrightarrow> x = y\"\n      unfolding less_eq_aexp_def using less_aexp_antisym by blast\n    show \"x \\<le> y \\<or> y \\<le> x\"\n      unfolding less_eq_aexp_def using less_aexp_antisym by blast\n  qed\nend\n\nlemma smaller_height: \"height a1 < height a2 \\<Longrightarrow> a1 < a2\"\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/Extended_Finite_State_Machines/AExp_Lexorder.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637505099167, "lm_q2_score": 0.8267117983401363, "lm_q1q2_score": 0.7106941651518796}}
{"text": "theory Chapter15_2_Typechecking\nimports Chapter15_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_isz [simp]: \"typecheck gam et Nat ==> typecheck gam e0 t ==> \n                typecheck (extend gam Nat) es t ==> typecheck gam (IsZ 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    | tc_abort [simp]: \"typecheck gam e Void ==> typecheck gam (Abort t e) t\"\n    | tc_case [simp]: \"typecheck gam et (Sum t1 t2) ==> typecheck (extend gam t1) el t ==> \n                typecheck (extend gam t2) er t ==> typecheck gam (Case et el er) t\"\n    | tc_inl [simp]: \"typecheck gam e t1 ==> typecheck gam (InL t1 t2 e) (Sum t1 t2)\"\n    | tc_inr [simp]: \"typecheck gam e t2 ==> typecheck gam (InR t1 t2 e) (Sum t1 t2)\"\n    | tc_fix [simp]: \"typecheck (extend gam t) e t ==> typecheck gam (Fix t e) 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 (IsZ 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\"\ninductive_cases [elim!]: \"typecheck gam (Abort t1 e) t\"\ninductive_cases [elim!]: \"typecheck gam (Case et el er) t\"\ninductive_cases [elim!]: \"typecheck gam (InL t1 t2 e) t\"\ninductive_cases [elim!]: \"typecheck gam (InR t1 t2 e) t\"\ninductive_cases [elim!]: \"typecheck gam (Fix t1 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/Chapter15_2_Typechecking.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206791658465, "lm_q2_score": 0.7879312006227324, "lm_q1q2_score": 0.7106514436016156}}
{"text": "header {* Abstract syntax for Logic. *}\n\ntheory Syntax_SL \n  imports  Main Real\nbegin\n\n(*Constants*)\ndatatype val = Real real     (\"Real _\" 76)\n             | String string (\"String _\" 76)\n             | Bool bool     (\"Bool _\" 76)\n| Err\n(*Expressions of HCSP language.*)\ndatatype exp = Con val (\"Con _\" 75)\n             | RVar string   (\"RVar _\" 75 )\n             | SVar string   (\"SVar _\" 75)\n             | BVar string   (\"BVar _\" 75)\n             | Add exp exp   (infixr \"[+]\" 70)\n             | Sub exp exp   (infixl  \"[-]\" 70)\n             | Mul exp exp   (infixr \"[*]\" 71)\n(*to complete all related to divide in  following functions.*)\n           | Div exp exp   (infixr \"[**]\" 71) \n\n(*Type declarations to be used in {*proc*}*)\ndatatype typeid = R | S | B\n(*States*)\ntype_synonym state = \"string * typeid => val\"\n\n(*Evaluation of expressions*)\nprimrec evalE :: \"exp \\<Rightarrow> state => val\" where\n\"evalE (Con y) f = y\" |\n\"evalE (RVar (x)) f = f (x, R)\" |\n\"evalE (SVar (x)) f = f (x, S)\" |\n\"evalE (BVar (x)) f = f (x, B)\" |\n\"evalE (e1 [+] e2) f = (case (evalE e1 f) of Real (x) =>\n                                         (case (evalE e2 f) of Real (y) => Real (x + y) |\n                                                                          _    => Err)|\n                                                              _ => Err)\" |\n\"evalE (e1 [-] e2) f = (case (evalE e1 f) of  Real (x) =>\n                                         (case (evalE e2 f) of  Real (y) =>  Real (x - y) |\n                                                                          _    => Err)|\n                                                              _ => Err)\" |\n\"evalE (e1 [*] e2) f = (case (evalE e1 f) of  Real (x) =>\n                                         (case (evalE e2 f) of Real (y) =>  Real (x * y) |\n                                                                          _    => Err)|\n                                                              _ => Err)\"\n\n\n\n\nsection{*FOL operators*}\ntype_synonym fform = \"state  \\<Rightarrow> bool\"\ndefinition fTrue:: \"fform\" where \" fTrue == % s. True\"\ndefinition fFalse:: \"fform\" where \"fFalse == % s. False\"\ndefinition fEqual :: \"exp \\<Rightarrow> exp \\<Rightarrow> fform\"  (\"_[=]_\" 69) where\n\"e [=] f == % s. evalE e s = evalE f s\"\ndefinition fLess :: \"exp \\<Rightarrow> exp \\<Rightarrow> fform\"  (\"_[<]_\" 69) where\n\"e [<] f == % s. (case (evalE e s) of Real c \\<Rightarrow> (case (evalE f s) of Real d \\<Rightarrow> (c<d)\n                                                                    |  _ \\<Rightarrow> False)\n                                       |  _ \\<Rightarrow> False )\" \n\ndefinition fAnd :: \"fform \\<Rightarrow> fform \\<Rightarrow> fform\"  (infixl \"[&]\"  65) where\n\"P [&] Q == % s. P s \\<and> Q s\"\ndefinition fOr :: \"fform\\<Rightarrow> fform \\<Rightarrow> fform\"  (infixl \"[|]\" 65) where\n\"P [|] Q == % s. P s \\<or> Q s\"\ndefinition fNot :: \"fform \\<Rightarrow> fform\"  (\"[\\<not>]_\" 67) where\n\"[\\<not>]P == % s. \\<not> P s\"\ndefinition fImp :: \"fform \\<Rightarrow> fform \\<Rightarrow> fform\"  (infixl \"[\\<longrightarrow>]\" 65) where\n\"P [\\<longrightarrow>] Q == % s. P s \\<longrightarrow> Q s\"\n\ndefinition fLessEqual :: \"exp \\<Rightarrow> exp \\<Rightarrow> fform\"  (\"_[\\<le>]_\" 69) where\n\"e [\\<le>] f == (e [=] f) [|] (e [<] f)\"\ndefinition fGreaterEqual :: \"exp \\<Rightarrow> exp \\<Rightarrow> fform\"  (\"_[\\<ge>]_\" 69) where\n\"e [\\<ge>] f == [\\<not>](e [<] f)\"\ndefinition fGreater :: \"exp \\<Rightarrow> exp \\<Rightarrow> fform\"  (\"_[>]_\" 69) where\n\"e [>] f == [\\<not>](e [\\<le>] f)\"\n\n(*close() extends the formula with the boundary, used for continuous evolution.*)\nconsts close :: \"fform \\<Rightarrow> fform\"\n\naxiomatization where\nLessc[simp]: \"close (e [<] f) = e [\\<le>] f\" and\nGreatc[simp]: \"close (e [>] f) = e [\\<ge>] f\" and\nEqualc[simp]: \"close (e [=] f) = e [=] f\" and\nGreatEqual[simp] : \"close ( e [\\<ge>] f) =  e [\\<ge>] f\" and\nAndc[simp]: \"close (P [&] Q) = close (P) [&] close (Q)\" and\nOrc[simp]: \"close (P [|] Q) = close (P) [|] close (Q)\"\n\n \nlemma notLess : \"close ([\\<not>] e [<] f) = e [\\<ge>] f\"\napply (subgoal_tac \"[\\<not>] e [<] f == e [\\<ge>] f\", auto)\napply (simp add:fGreaterEqual_def fOr_def fNot_def fLess_def fEqual_def fGreater_def)\ndone\n\n\ndeclare fTrue_def [simp]\ndeclare fFalse_def [simp]\n     \n(*Types for defining HCSP*)\ntype_synonym cname = string\ntype_synonym time = real\n\n(*Communication processes of HCSP*)\ndatatype comm\n= Send \"cname\" \"exp\"         (\"_!!_\" [110,108] 100)      \n| Receive \"cname\" \"exp\"    (\"_??_\" [110,108] 100) \n\n(*HCSP processes*)\ndatatype proc\n= Cm comm\n| \"Skip\"\n| Ass \"exp\" \"exp\"          (\"_ := _\" [99, 95] 94)   \n| Seq \"proc\" \"proc\"                   (\"_; _\"        [91,90 ] 90)\n| Cond \"fform\" \"proc\"                 (\"IF _ _\"   [95,94]93)\n| CondG \"fform\" \"proc\" \"proc\"                 (\"IFELSE _ _ _\"   [95,94,94]93)\n| Pref   \"comm\" \"proc\"                  (\"_\\<rightarrow>_\"   [95,94]93)           \n| join \"proc\" \"proc\"                   (infixr \"[[\" 90)\n| meet \"proc\" \"proc\"                  (\"_<<_\" [90,90] 90)\n(*Repetition is annotated with invariant*)\n| Rep    \"proc\" \"fform\"                              (\"_*&&_\"[91] 90)\n| RepN  \"proc\" \"nat\"   (\"_* NUM _\"[91, 90] 90)\n(*Continuous evolution is annotated with invariant.*)\n| Cont  \"(string * typeid) list\" \"exp list\" \"fform\" \"fform\"               (\"<_:_&&_&_>\" [95,95,96]94)\n| Interp   \"proc\" \"proc\" (\"_[[>_\"[95,94]94)\n\n(*We assume parallel  composition only occurs in  the topmost level.*)\ndatatype procP = Par    \"proc\" \"proc\"                  (infixr \"||\" 89)\n\nend\n\n", "meta": {"author": "wangslyl", "repo": "hhlprover", "sha": "500e7ae1f93f0decb67b55ec2e0b4f756ae9ede0", "save_path": "github-repos/isabelle/wangslyl-hhlprover", "path": "github-repos/isabelle/wangslyl-hhlprover/hhlprover-500e7ae1f93f0decb67b55ec2e0b4f756ae9ede0/HHLProver/Syntax_SL.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.901920681802153, "lm_q2_score": 0.7879311956428947, "lm_q1q2_score": 0.7106514411874252}}
{"text": "theory list_PairUnpair\nimports Main\n        \"$HIPSTER_HOME/IsaHipster\"\nbegin\n\ndatatype 'a list = Nil2 | Cons2 \"'a\" \"'a list\"\n\ndatatype ('a, 'b) Pair2 = Pair \"'a\" \"'b\"\n\ndatatype Nat = Z | S \"Nat\"\n\nfun unpair :: \"(('t, 't) Pair2) list => 't list\" where\n\"unpair (Nil2) = Nil2\"\n| \"unpair (Cons2 (Pair z y2) xys) =\n     Cons2 z (Cons2 y2 (unpair xys))\"\n\nfun pairs :: \"'t list => (('t, 't) Pair2) list\" where\n\"pairs (Nil2) = Nil2\"\n| \"pairs (Cons2 y (Nil2)) = Nil2\"\n| \"pairs (Cons2 y (Cons2 y2 xs)) = Cons2 (Pair y y2) (pairs xs)\"\n\nfun length :: \"'t list => Nat\" where\n\"length (Nil2) = Z\"\n| \"length (Cons2 y xs) = S (length xs)\"\n\nfun even :: \"Nat => bool\" where\n\"even (Z) = True\"\n| \"even (S (Z)) = False\"\n| \"even (S (S z)) = even z\"\n\n(*hipster unpair pairs length even *)\n\ntheorem x0 :\n  \"!! (xs :: 't list) .\n     (even (length xs)) ==> ((unpair (pairs xs)) = xs)\"\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/koen/list_PairUnpair.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9273632956467158, "lm_q2_score": 0.7662936377487304, "lm_q1q2_score": 0.7106325933357732}}
{"text": "(* Title:      Lattice Basics\n   Author:     Walter Guttmann\n   Maintainer: Walter Guttmann <walter.guttmann at canterbury.ac.nz>\n*)\n\nsection \\<open>Lattice Basics\\<close>\n\ntext \\<open>\nThis theory provides notations, basic definitions and facts of lattice-related structures used throughout the subsequent development.\n\\<close>\n\ntheory Lattice_Basics\n\nimports Main\n\nbegin\n\nsubsection \\<open>General Facts and Notations\\<close>\n\ntext \\<open>\nThe following results extend basic Isabelle/HOL facts.\n\\<close>\n\nlemma imp_as_conj:\n  assumes \"P x \\<Longrightarrow> Q x\"\n  shows \"P x \\<and> Q x \\<longleftrightarrow> P x\"\n  using assms by auto\n\nlemma if_distrib_2:\n  \"f (if c then x else y) (if c then z else w) = (if c then f x z else f y w)\"\n  by simp\n\nlemma left_invertible_inj:\n  \"(\\<forall>x . g (f x) = x) \\<Longrightarrow> inj f\"\n  by (metis injI)\n\nlemma invertible_bij:\n  assumes \"\\<forall>x . g (f x) = x\"\n      and \"\\<forall>y . f (g y) = y\"\n    shows \"bij f\"\n  by (metis assms bijI')\n\nlemma finite_ne_subset_induct [consumes 3, case_names singleton insert]:\n  assumes \"finite F\"\n      and \"F \\<noteq> {}\"\n      and \"F \\<subseteq> S\"\n      and singleton: \"\\<And>x . P {x}\"\n      and insert: \"\\<And>x F . finite F \\<Longrightarrow> F \\<noteq> {} \\<Longrightarrow> F \\<subseteq> S \\<Longrightarrow> x \\<in> S \\<Longrightarrow> x \\<notin> F \\<Longrightarrow> P F \\<Longrightarrow> P (insert x F)\"\n    shows \"P F\"\n  using assms(1-3)\n  apply (induct rule: finite_ne_induct)\n  apply (simp add: singleton)\n  by (simp add: insert)\n\nlemma finite_set_of_finite_funs_pred:\n  assumes \"finite { x::'a . True }\"\n      and \"finite { y::'b . P y }\"\n    shows \"finite { f . (\\<forall>x::'a . P (f x)) }\"\n  using assms finite_set_of_finite_funs by force\n\ntext \\<open>\nWe use the following notations for the join, meet and complement operations.\nChanging the precedence of the unary complement allows us to write terms like \\<open>--x\\<close> instead of \\<open>-(-x)\\<close>.\n\\<close>\n\ncontext sup\nbegin\n\nnotation sup (infixl \"\\<squnion>\" 65)\n\ndefinition additive :: \"('a \\<Rightarrow> 'a) \\<Rightarrow> bool\"\n  where \"additive f \\<equiv> \\<forall>x y . f (x \\<squnion> y) = f x \\<squnion> f y\"\n\nend\n\ncontext inf\nbegin\n\nnotation inf (infixl \"\\<sqinter>\" 67)\n\nend\n\ncontext uminus\nbegin\n\nno_notation uminus (\"- _\" [81] 80)\n\nnotation uminus (\"- _\" [80] 80)\n\nend\n\nsubsection \\<open>Orders\\<close>\n\ntext \\<open>\nWe use the following definition of monotonicity for operations defined in classes.\nThe standard \\<open>mono\\<close> places a sort constraint on the target type.\nWe also give basic properties of Galois connections and lift orders to functions.\n\\<close>\n\ncontext ord\nbegin\n\ndefinition isotone :: \"('a \\<Rightarrow> 'a) \\<Rightarrow> bool\"\n  where \"isotone f \\<equiv> \\<forall>x y . x \\<le> y \\<longrightarrow> f x \\<le> f y\"\n\ndefinition galois :: \"('a \\<Rightarrow> 'a) \\<Rightarrow> ('a \\<Rightarrow> 'a) \\<Rightarrow> bool\"\n  where \"galois l u \\<equiv> \\<forall>x y . l x \\<le> y \\<longleftrightarrow> x \\<le> u y\"\n\ndefinition lifted_less_eq :: \"('a \\<Rightarrow> 'a) \\<Rightarrow> ('a \\<Rightarrow> 'a) \\<Rightarrow> bool\" (\"(_ \\<le>\\<le> _)\" [51, 51] 50)\n  where \"f \\<le>\\<le> g \\<equiv> \\<forall>x . f x \\<le> g x\"\n\nend\n\ncontext order\nbegin\n\nlemma order_lesseq_imp:\n  \"(\\<forall>z . x \\<le> z \\<longrightarrow> y \\<le> z) \\<longleftrightarrow> y \\<le> x\"\n  using order_trans by blast\n\nlemma galois_char:\n  \"galois l u \\<longleftrightarrow> (\\<forall>x . x \\<le> u (l x)) \\<and> (\\<forall>x . l (u x) \\<le> x) \\<and> isotone l \\<and> isotone u\"\n  apply (rule iffI)\n  apply (metis (full_types) galois_def isotone_def order_refl order_trans)\n  using galois_def isotone_def order_trans by blast\n\nlemma galois_closure:\n  \"galois l u \\<Longrightarrow> l x = l (u (l x)) \\<and> u x = u (l (u x))\"\n  by (simp add: galois_char isotone_def antisym)\n\nlemma lifted_reflexive:\n  \"f = g \\<Longrightarrow> f \\<le>\\<le> g\"\n  by (simp add: lifted_less_eq_def)\n\nlemma lifted_transitive:\n  \"f \\<le>\\<le> g \\<Longrightarrow> g \\<le>\\<le> h \\<Longrightarrow> f \\<le>\\<le> h\"\n  using lifted_less_eq_def order_trans by blast\n\nlemma lifted_antisymmetric:\n  \"f \\<le>\\<le> g \\<Longrightarrow> g \\<le>\\<le> f \\<Longrightarrow> f = g\"\n  by (metis (full_types) antisym ext lifted_less_eq_def)\n\ntext \\<open>\nIf the image of a finite non-empty set under \\<open>f\\<close> is a totally ordered, there is an element that minimises the value of \\<open>f\\<close>.\n\\<close>\n\nlemma finite_set_minimal:\n  assumes \"finite s\"\n      and \"s \\<noteq> {}\"\n      and \"\\<forall>x\\<in>s . \\<forall>y\\<in>s . f x \\<le> f y \\<or> f y \\<le> f x\"\n    shows \"\\<exists>m\\<in>s . \\<forall>z\\<in>s . f m \\<le> f z\"\n  apply (rule finite_ne_subset_induct[where S=s])\n  apply (rule assms(1))\n  apply (rule assms(2))\n  apply simp\n  apply simp\n  by (metis assms(3) insert_iff order_trans subsetD)\n\nend\n\nsubsection \\<open>Semilattices\\<close>\n\ntext \\<open>\nThe following are basic facts in semilattices.\n\\<close>\n\ncontext semilattice_sup\nbegin\n\nlemma sup_left_isotone:\n  \"x \\<le> y \\<Longrightarrow> x \\<squnion> z \\<le> y \\<squnion> z\"\n  using sup.mono by blast\n\nlemma sup_right_isotone:\n  \"x \\<le> y \\<Longrightarrow> z \\<squnion> x \\<le> z \\<squnion> y\"\n  using sup.mono by blast\n\nlemma sup_left_divisibility:\n  \"x \\<le> y \\<longleftrightarrow> (\\<exists>z . x \\<squnion> z = y)\"\n  using sup.absorb2 sup.cobounded1 by blast\n\nlemma sup_right_divisibility:\n  \"x \\<le> y \\<longleftrightarrow> (\\<exists>z . z \\<squnion> x = y)\"\n  by (metis sup.cobounded2 sup.orderE)\n\nlemma sup_same_context:\n  \"x \\<le> y \\<squnion> z \\<Longrightarrow> y \\<le> x \\<squnion> z \\<Longrightarrow> x \\<squnion> z = y \\<squnion> z\"\n  by (simp add: le_iff_sup sup_left_commute)\n\nlemma sup_relative_same_increasing:\n  \"x \\<le> y \\<Longrightarrow> x \\<squnion> z = x \\<squnion> w \\<Longrightarrow> y \\<squnion> z = y \\<squnion> w\"\n  using sup.assoc sup_right_divisibility by auto\n\nend\n\ntext \\<open>\nEvery bounded semilattice is a commutative monoid.\nFinite sums defined in commutative monoids are available via the following sublocale.\n\\<close>\n\ncontext bounded_semilattice_sup_bot\nbegin\n\nsublocale sup_monoid: comm_monoid_add where plus = sup and zero = bot\n  apply unfold_locales\n  apply (simp add: sup_assoc)\n  apply (simp add: sup_commute)\n  by simp\n\nend\n\ncontext semilattice_inf\nbegin\n\nlemma inf_same_context:\n  \"x \\<le> y \\<sqinter> z \\<Longrightarrow> y \\<le> x \\<sqinter> z \\<Longrightarrow> x \\<sqinter> z = y \\<sqinter> z\"\n  using antisym by auto\n\nend\n\ntext \\<open>\nThe following class requires only the existence of upper bounds, which is a property common to bounded semilattices and (not necessarily bounded) lattices.\nWe use it in our development of filters.\n\\<close>\n\nclass directed_semilattice_inf = semilattice_inf +\n  assumes ub: \"\\<exists>z . x \\<le> z \\<and> y \\<le> z\"\n\ntext \\<open>\nWe extend the \\<open>inf\\<close> sublocale, which dualises the order in semilattices, to bounded semilattices.\n\\<close>\n\ncontext bounded_semilattice_inf_top\nbegin\n\nsubclass directed_semilattice_inf\n  apply unfold_locales\n  using top_greatest by blast\n\nsublocale inf: bounded_semilattice_sup_bot where sup = inf and less_eq = greater_eq and less = greater and bot = top\n  by unfold_locales (simp_all add: less_le_not_le)\n\nend\n\nsubsection \\<open>Lattices\\<close>\n\ncontext lattice\nbegin\n\nsubclass directed_semilattice_inf\n  apply unfold_locales\n  using sup_ge1 sup_ge2 by blast\n\ndefinition dual_additive :: \"('a \\<Rightarrow> 'a) \\<Rightarrow> bool\"\n  where \"dual_additive f \\<equiv> \\<forall>x y . f (x \\<squnion> y) = f x \\<sqinter> f y\"\n\nend\n\ntext \\<open>\nNot every bounded lattice has complements, but two elements might still be complements of each other as captured in the following definition.\nIn this situation we can apply, for example, the shunting property shown below.\nWe introduce most definitions using the \\<open>abbreviation\\<close> command.\n\\<close>\n\ncontext bounded_lattice\nbegin\n\nabbreviation \"complement x y \\<equiv> x \\<squnion> y = top \\<and> x \\<sqinter> y = bot\"\n\nlemma complement_symmetric:\n  \"complement x y \\<Longrightarrow> complement y x\"\n  by (simp add: inf.commute sup.commute)\n\ndefinition conjugate :: \"('a \\<Rightarrow> 'a) \\<Rightarrow> ('a \\<Rightarrow> 'a) \\<Rightarrow> bool\"\n  where \"conjugate f g \\<equiv> \\<forall>x y . f x \\<sqinter> y = bot \\<longleftrightarrow> x \\<sqinter> g y = bot\"\n\nend\n\nclass dense_lattice = bounded_lattice +\n  assumes bot_meet_irreducible: \"x \\<sqinter> y = bot \\<longrightarrow> x = bot \\<or> y = bot\"\n\ncontext distrib_lattice\nbegin\n\nlemma relative_equality:\n  \"x \\<squnion> z = y \\<squnion> z \\<Longrightarrow> x \\<sqinter> z = y \\<sqinter> z \\<Longrightarrow> x = y\"\n  by (metis inf.commute inf_sup_absorb inf_sup_distrib2)\n\nend\n\ntext \\<open>\nDistributive lattices with a greatest element are widely used in the construction theorem for Stone algebras.\n\\<close>\n\nclass distrib_lattice_bot = bounded_lattice_bot + distrib_lattice\n\nclass distrib_lattice_top = bounded_lattice_top + distrib_lattice\n\nclass bounded_distrib_lattice = bounded_lattice + distrib_lattice\nbegin\n\nsubclass distrib_lattice_bot ..\n\nsubclass distrib_lattice_top ..\n\nlemma complement_shunting:\n  assumes \"complement z w\"\n    shows \"z \\<sqinter> x \\<le> y \\<longleftrightarrow> x \\<le> w \\<squnion> y\"\nproof\n  assume 1: \"z \\<sqinter> x \\<le> y\"\n  have \"x = (z \\<squnion> w) \\<sqinter> x\"\n    by (simp add: assms)\n  also have \"... \\<le> y \\<squnion> (w \\<sqinter> x)\"\n    using 1 sup.commute sup.left_commute inf_sup_distrib2 sup_right_divisibility by fastforce\n  also have \"... \\<le> w \\<squnion> y\"\n    by (simp add: inf.coboundedI1)\n  finally show \"x \\<le> w \\<squnion> y\"\n    .\nnext\n  assume \"x \\<le> w \\<squnion> y\"\n  hence \"z \\<sqinter> x \\<le> z \\<sqinter> (w \\<squnion> y)\"\n    using inf.sup_right_isotone by auto\n  also have \"... = z \\<sqinter> y\"\n    by (simp add: assms inf_sup_distrib1)\n  also have \"... \\<le> y\"\n    by simp\n  finally show \"z \\<sqinter> x \\<le> y\"\n    .\nqed\n\nend\n\nsubsection \\<open>Linear Orders\\<close>\n\ntext \\<open>\nWe next consider lattices with a linear order structure.\nIn such lattices, join and meet are selective operations, which give the maximum and the minimum of two elements, respectively.\nMoreover, the lattice is automatically distributive.\n\\<close>\n\nclass bounded_linorder = linorder + order_bot + order_top\n\nclass linear_lattice = lattice + linorder\nbegin\n\nlemma max_sup:\n  \"max x y = x \\<squnion> y\"\n  by (metis max.boundedI max.cobounded1 max.cobounded2 sup_unique)\n\nlemma min_inf:\n  \"min x y = x \\<sqinter> y\"\n  by (simp add: inf.absorb1 inf.absorb2 min_def)\n\nlemma sup_inf_selective:\n  \"(x \\<squnion> y = x \\<and> x \\<sqinter> y = y) \\<or> (x \\<squnion> y = y \\<and> x \\<sqinter> y = x)\"\n  by (meson inf.absorb1 inf.absorb2 le_cases sup.absorb1 sup.absorb2)\n\nlemma sup_selective:\n  \"x \\<squnion> y = x \\<or> x \\<squnion> y = y\"\n  using sup_inf_selective by blast\n\nlemma inf_selective:\n  \"x \\<sqinter> y = x \\<or> x \\<sqinter> y = y\"\n  using sup_inf_selective by blast\n\nsubclass distrib_lattice\n  apply unfold_locales\n  by (metis inf_selective antisym distrib_sup_le inf.commute inf_le2)\n\nlemma sup_less_eq:\n  \"x \\<le> y \\<squnion> z \\<longleftrightarrow> x \\<le> y \\<or> x \\<le> z\"\n  by (metis le_supI1 le_supI2 sup_selective)\n\nlemma inf_less_eq:\n  \"x \\<sqinter> y \\<le> z \\<longleftrightarrow> x \\<le> z \\<or> y \\<le> z\"\n  by (metis inf.coboundedI1 inf.coboundedI2 inf_selective)\n\nlemma sup_inf_sup:\n  \"x \\<squnion> y = (x \\<squnion> y) \\<squnion> (x \\<sqinter> y)\"\n  by (metis sup_commute sup_inf_absorb sup_left_commute)\n\nend\n\ntext \\<open>\nThe following class derives additional properties if the linear order of the lattice has a least and a greatest element.\n\\<close>\n\nclass linear_bounded_lattice = bounded_lattice + linorder\nbegin\n\nsubclass linear_lattice ..\n\nsubclass bounded_linorder ..\n\nsubclass bounded_distrib_lattice ..\n\nlemma sup_dense:\n  \"x \\<noteq> top \\<Longrightarrow> y \\<noteq> top \\<Longrightarrow> x \\<squnion> y \\<noteq> top\"\n  by (metis sup_selective)\n\nlemma inf_dense:\n  \"x \\<noteq> bot \\<Longrightarrow> y \\<noteq> bot \\<Longrightarrow> x \\<sqinter> y \\<noteq> bot\"\n  by (metis inf_selective)\n\nlemma sup_not_bot:\n  \"x \\<noteq> bot \\<Longrightarrow> x \\<squnion> y \\<noteq> bot\"\n  by simp\n\nlemma inf_not_top:\n  \"x \\<noteq> top \\<Longrightarrow> x \\<sqinter> y \\<noteq> top\"\n  by simp\n\nsubclass dense_lattice\n  apply unfold_locales\n  using inf_dense by blast\n\nend\n\ntext \\<open>\nEvery bounded linear order can be expanded to a bounded lattice.\nJoin and meet are maximum and minimum, respectively.\n\\<close>\n\nclass linorder_lattice_expansion = bounded_linorder + sup + inf +\n  assumes sup_def [simp]: \"x \\<squnion> y = max x y\"\n  assumes inf_def [simp]: \"x \\<sqinter> y = min x y\"\nbegin\n\nsubclass linear_bounded_lattice\n  apply unfold_locales\n  by auto\n\nend\n\nsubsection \\<open>Non-trivial Algebras\\<close>\n\ntext \\<open>\nSome results, such as the existence of certain filters, require that the algebras are not trivial.\nThis is not an assumption of the order and lattice classes that come with Isabelle/HOL; for example, \\<open>bot = top\\<close> may hold in bounded lattices.\n\\<close>\n\nclass non_trivial =\n  assumes consistent: \"\\<exists>x y . x \\<noteq> y\"\n\nclass non_trivial_order = non_trivial + order\n\nclass non_trivial_order_bot = non_trivial_order + order_bot\n\nclass non_trivial_bounded_order = non_trivial_order_bot + order_top\nbegin\n\nlemma bot_not_top:\n  \"bot \\<noteq> top\"\nproof -\n  from consistent obtain x y :: 'a where \"x \\<noteq> y\"\n    by auto\n  thus ?thesis\n    by (metis bot_less top.extremum_strict)\nqed\n\nend\n\nsubsection \\<open>Homomorphisms\\<close>\n\ntext \\<open>\nThis section gives definitions of lattice homomorphisms and isomorphisms and basic properties.\n\\<close>\n\nclass sup_inf_top_bot_uminus = sup + inf + top + bot + uminus\nclass sup_inf_top_bot_uminus_ord = sup_inf_top_bot_uminus + ord\n\ncontext boolean_algebra\nbegin\n\nsubclass sup_inf_top_bot_uminus_ord .\n\nend\n\nabbreviation sup_homomorphism :: \"('a::sup \\<Rightarrow> 'b::sup) \\<Rightarrow> bool\"\n  where \"sup_homomorphism f \\<equiv> \\<forall>x y . f (x \\<squnion> y) = f x \\<squnion> f y\"\n\nabbreviation inf_homomorphism :: \"('a::inf \\<Rightarrow> 'b::inf) \\<Rightarrow> bool\"\n  where \"inf_homomorphism f \\<equiv> \\<forall>x y . f (x \\<sqinter> y) = f x \\<sqinter> f y\"\n\nabbreviation bot_homomorphism :: \"('a::bot \\<Rightarrow> 'b::bot) \\<Rightarrow> bool\"\n  where \"bot_homomorphism f \\<equiv> f bot = bot\"\n\nabbreviation top_homomorphism :: \"('a::top \\<Rightarrow> 'b::top) \\<Rightarrow> bool\"\n  where \"top_homomorphism f \\<equiv> f top = top\"\n\nabbreviation minus_homomorphism :: \"('a::minus \\<Rightarrow> 'b::minus) \\<Rightarrow> bool\"\n  where \"minus_homomorphism f \\<equiv> \\<forall>x y . f (x - y) = f x - f y\"\n\nabbreviation uminus_homomorphism :: \"('a::uminus \\<Rightarrow> 'b::uminus) \\<Rightarrow> bool\"\n  where \"uminus_homomorphism f \\<equiv> \\<forall>x . f (-x) = -f x\"\n\nabbreviation sup_inf_homomorphism :: \"('a::{sup,inf} \\<Rightarrow> 'b::{sup,inf}) \\<Rightarrow> bool\"\n  where \"sup_inf_homomorphism f \\<equiv> sup_homomorphism f \\<and> inf_homomorphism f\"\n\nabbreviation sup_inf_top_homomorphism :: \"('a::{sup,inf,top} \\<Rightarrow> 'b::{sup,inf,top}) \\<Rightarrow> bool\"\n  where \"sup_inf_top_homomorphism f \\<equiv> sup_inf_homomorphism f \\<and> top_homomorphism f\"\n\nabbreviation sup_inf_top_bot_homomorphism :: \"('a::{sup,inf,top,bot} \\<Rightarrow> 'b::{sup,inf,top,bot}) \\<Rightarrow> bool\"\n  where \"sup_inf_top_bot_homomorphism f \\<equiv> sup_inf_top_homomorphism f \\<and> bot_homomorphism f\"\n\nabbreviation bounded_lattice_homomorphism :: \"('a::bounded_lattice \\<Rightarrow> 'b::bounded_lattice) \\<Rightarrow> bool\"\n  where \"bounded_lattice_homomorphism f \\<equiv> sup_inf_top_bot_homomorphism f\"\n\nabbreviation sup_inf_top_bot_uminus_homomorphism :: \"('a::sup_inf_top_bot_uminus \\<Rightarrow> 'b::sup_inf_top_bot_uminus) \\<Rightarrow> bool\"\n  where \"sup_inf_top_bot_uminus_homomorphism f \\<equiv> sup_inf_top_bot_homomorphism f \\<and> uminus_homomorphism f\"\n\nabbreviation sup_inf_top_bot_uminus_ord_homomorphism :: \"('a::sup_inf_top_bot_uminus_ord \\<Rightarrow> 'b::sup_inf_top_bot_uminus_ord) \\<Rightarrow> bool\"\n  where \"sup_inf_top_bot_uminus_ord_homomorphism f \\<equiv> sup_inf_top_bot_uminus_homomorphism f \\<and> (\\<forall>x y . x \\<le> y \\<longrightarrow> f x \\<le> f y)\"\n\nabbreviation sup_inf_top_isomorphism :: \"('a::{sup,inf,top} \\<Rightarrow> 'b::{sup,inf,top}) \\<Rightarrow> bool\"\n  where \"sup_inf_top_isomorphism f \\<equiv> sup_inf_top_homomorphism f \\<and> bij f\"\n\nabbreviation bounded_lattice_top_isomorphism :: \"('a::bounded_lattice_top \\<Rightarrow> 'b::bounded_lattice_top) \\<Rightarrow> bool\"\n  where \"bounded_lattice_top_isomorphism f \\<equiv> sup_inf_top_isomorphism f\"\n\nabbreviation sup_inf_top_bot_uminus_isomorphism :: \"('a::sup_inf_top_bot_uminus \\<Rightarrow> 'b::sup_inf_top_bot_uminus) \\<Rightarrow> bool\"\n  where \"sup_inf_top_bot_uminus_isomorphism f \\<equiv> sup_inf_top_bot_uminus_homomorphism f \\<and> bij f\"\n\nabbreviation boolean_algebra_isomorphism :: \"('a::boolean_algebra \\<Rightarrow> 'b::boolean_algebra) \\<Rightarrow> bool\"\n  where \"boolean_algebra_isomorphism f \\<equiv> sup_inf_top_bot_uminus_isomorphism f \\<and> minus_homomorphism f\"\n\nlemma sup_homomorphism_mono:\n  \"sup_homomorphism (f::'a::semilattice_sup \\<Rightarrow> 'b::semilattice_sup) \\<Longrightarrow> mono f\"\n  by (metis le_iff_sup monoI)\n\nlemma sup_isomorphism_ord_isomorphism:\n  assumes \"sup_homomorphism (f::'a::semilattice_sup \\<Rightarrow> 'b::semilattice_sup)\"\n      and \"bij f\"\n    shows \"x \\<le> y \\<longleftrightarrow> f x \\<le> f y\"\nproof\n  assume \"x \\<le> y\"\n  thus \"f x \\<le> f y\"\n    by (metis assms(1) le_iff_sup)\nnext\n  assume \"f x \\<le> f y\"\n  hence \"f (x \\<squnion> y) = f y\"\n    by (simp add: assms(1) le_iff_sup)\n  hence \"x \\<squnion> y = y\"\n    by (metis injD bij_is_inj assms(2))\n  thus \"x \\<le> y\"\n    by (simp add: le_iff_sup)\nqed\n\nlemma minus_homomorphism_default:\n  assumes \"\\<forall>x y::'a::{inf,minus,uminus} . x - y = x \\<sqinter> -y\"\n      and \"\\<forall>x y::'b::{inf,minus,uminus} . x - y = x \\<sqinter> -y\"\n      and \"inf_homomorphism (f::'a \\<Rightarrow> 'b)\"\n      and \"uminus_homomorphism f\"\n    shows \"minus_homomorphism f\"\n  by (simp add: assms)\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/Lattice_Basics.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8438951104066293, "lm_q2_score": 0.8418256492357358, "lm_q1q2_score": 0.7104125492049237}}
{"text": "(*  Title:      HOL/Map.thy\n    Author:     Tobias Nipkow, based on a theory by David von Oheimb\n    Copyright   1997-2003 TU Muenchen\n\nThe datatype of \"maps\"; strongly resembles maps in VDM.\n*)\n\nsection \\<open>Maps\\<close>\n\ntheory Map\n  imports List\n  abbrevs \"(=\" = \"\\<subseteq>\\<^sub>m\"\nbegin\n\ntype_synonym ('a, 'b) \"map\" = \"'a \\<Rightarrow> 'b option\" (infixr \"\\<rightharpoonup>\" 0)\n\nabbreviation\n  empty :: \"'a \\<rightharpoonup> 'b\" where\n  \"empty \\<equiv> \\<lambda>x. None\"\n\ndefinition\n  map_comp :: \"('b \\<rightharpoonup> 'c) \\<Rightarrow> ('a \\<rightharpoonup> 'b) \\<Rightarrow> ('a \\<rightharpoonup> 'c)\"  (infixl \"\\<circ>\\<^sub>m\" 55) where\n  \"f \\<circ>\\<^sub>m g = (\\<lambda>k. case g k of None \\<Rightarrow> None | Some v \\<Rightarrow> f v)\"\n\ndefinition\n  map_add :: \"('a \\<rightharpoonup> 'b) \\<Rightarrow> ('a \\<rightharpoonup> 'b) \\<Rightarrow> ('a \\<rightharpoonup> 'b)\"  (infixl \"++\" 100) where\n  \"m1 ++ m2 = (\\<lambda>x. case m2 x of None \\<Rightarrow> m1 x | Some y \\<Rightarrow> Some y)\"\n\ndefinition\n  restrict_map :: \"('a \\<rightharpoonup> 'b) \\<Rightarrow> 'a set \\<Rightarrow> ('a \\<rightharpoonup> 'b)\"  (infixl \"|`\"  110) where\n  \"m|`A = (\\<lambda>x. if x \\<in> A then m x else None)\"\n\nnotation (latex output)\n  restrict_map  (\"_\\<restriction>\\<^bsub>_\\<^esub>\" [111,110] 110)\n\ndefinition\n  dom :: \"('a \\<rightharpoonup> 'b) \\<Rightarrow> 'a set\" where\n  \"dom m = {a. m a \\<noteq> None}\"\n\ndefinition\n  ran :: \"('a \\<rightharpoonup> 'b) \\<Rightarrow> 'b set\" where\n  \"ran m = {b. \\<exists>a. m a = Some b}\"\n\ndefinition\n  map_le :: \"('a \\<rightharpoonup> 'b) \\<Rightarrow> ('a \\<rightharpoonup> 'b) \\<Rightarrow> bool\"  (infix \"\\<subseteq>\\<^sub>m\" 50) where\n  \"(m\\<^sub>1 \\<subseteq>\\<^sub>m m\\<^sub>2) \\<longleftrightarrow> (\\<forall>a \\<in> dom m\\<^sub>1. m\\<^sub>1 a = m\\<^sub>2 a)\"\n\nnonterminal maplets and maplet\n\nsyntax\n  \"_maplet\"  :: \"['a, 'a] \\<Rightarrow> maplet\"             (\"_ /\\<mapsto>/ _\")\n  \"_maplets\" :: \"['a, 'a] \\<Rightarrow> maplet\"             (\"_ /[\\<mapsto>]/ _\")\n  \"\"         :: \"maplet \\<Rightarrow> maplets\"             (\"_\")\n  \"_Maplets\" :: \"[maplet, maplets] \\<Rightarrow> maplets\" (\"_,/ _\")\n  \"_MapUpd\"  :: \"['a \\<rightharpoonup> 'b, maplets] \\<Rightarrow> 'a \\<rightharpoonup> 'b\" (\"_/'(_')\" [900, 0] 900)\n  \"_Map\"     :: \"maplets \\<Rightarrow> 'a \\<rightharpoonup> 'b\"            (\"(1[_])\")\n\nsyntax (ASCII)\n  \"_maplet\"  :: \"['a, 'a] \\<Rightarrow> maplet\"             (\"_ /|->/ _\")\n  \"_maplets\" :: \"['a, 'a] \\<Rightarrow> maplet\"             (\"_ /[|->]/ _\")\n\ntranslations\n  \"_MapUpd m (_Maplets xy ms)\"  \\<rightleftharpoons> \"_MapUpd (_MapUpd m xy) ms\"\n  \"_MapUpd m (_maplet  x y)\"    \\<rightleftharpoons> \"m(x := CONST Some y)\"\n  \"_Map ms\"                     \\<rightleftharpoons> \"_MapUpd (CONST empty) ms\"\n  \"_Map (_Maplets ms1 ms2)\"     \\<leftharpoondown> \"_MapUpd (_Map ms1) ms2\"\n  \"_Maplets ms1 (_Maplets ms2 ms3)\" \\<leftharpoondown> \"_Maplets (_Maplets ms1 ms2) ms3\"\n\nprimrec map_of :: \"('a \\<times> 'b) list \\<Rightarrow> 'a \\<rightharpoonup> 'b\"\nwhere\n  \"map_of [] = empty\"\n| \"map_of (p # ps) = (map_of ps)(fst p \\<mapsto> snd p)\"\n\ndefinition map_upds :: \"('a \\<rightharpoonup> 'b) \\<Rightarrow> 'a list \\<Rightarrow> 'b list \\<Rightarrow> 'a \\<rightharpoonup> 'b\"\n  where \"map_upds m xs ys = m ++ map_of (rev (zip xs ys))\"\ntranslations\n  \"_MapUpd m (_maplets x y)\" \\<rightleftharpoons> \"CONST map_upds m x y\"\n\nlemma map_of_Cons_code [code]:\n  \"map_of [] k = None\"\n  \"map_of ((l, v) # ps) k = (if l = k then Some v else map_of ps k)\"\n  by simp_all\n\n\nsubsection \\<open>@{term [source] empty}\\<close>\n\nlemma empty_upd_none [simp]: \"empty(x := None) = empty\"\n  by (rule ext) simp\n\n\nsubsection \\<open>@{term [source] map_upd}\\<close>\n\nlemma map_upd_triv: \"t k = Some x \\<Longrightarrow> t(k\\<mapsto>x) = t\"\n  by (rule ext) simp\n\nlemma map_upd_nonempty [simp]: \"t(k\\<mapsto>x) \\<noteq> empty\"\nproof\n  assume \"t(k \\<mapsto> x) = empty\"\n  then have \"(t(k \\<mapsto> x)) k = None\" by simp\n  then show False by simp\nqed\n\nlemma map_upd_eqD1:\n  assumes \"m(a\\<mapsto>x) = n(a\\<mapsto>y)\"\n  shows \"x = y\"\nproof -\n  from assms have \"(m(a\\<mapsto>x)) a = (n(a\\<mapsto>y)) a\" by simp\n  then show ?thesis by simp\nqed\n\nlemma map_upd_Some_unfold:\n  \"((m(a\\<mapsto>b)) x = Some y) = (x = a \\<and> b = y \\<or> x \\<noteq> a \\<and> m x = Some y)\"\n  by auto\n\nlemma image_map_upd [simp]: \"x \\<notin> A \\<Longrightarrow> m(x \\<mapsto> y) ` A = m ` A\"\n  by auto\n\nlemma finite_range_updI:\n  assumes \"finite (range f)\" shows \"finite (range (f(a\\<mapsto>b)))\"\nproof -\n  have \"range (f(a\\<mapsto>b)) \\<subseteq> insert (Some b) (range f)\"\n    by auto\n  then show ?thesis\n    by (rule finite_subset) (use assms in auto)\nqed\n\n\nsubsection \\<open>@{term [source] map_of}\\<close>\n\nlemma map_of_eq_empty_iff [simp]:\n  \"map_of xys = empty \\<longleftrightarrow> xys = []\"\nproof\n  show \"map_of xys = empty \\<Longrightarrow> xys = []\"\n    by (induction xys) simp_all\nqed simp\n\nlemma empty_eq_map_of_iff [simp]:\n  \"empty = map_of xys \\<longleftrightarrow> xys = []\"\nby(subst eq_commute) simp\n\nlemma map_of_eq_None_iff:\n  \"(map_of xys x = None) = (x \\<notin> fst ` (set xys))\"\nby (induct xys) simp_all\n\nlemma map_of_eq_Some_iff [simp]:\n  \"distinct(map fst xys) \\<Longrightarrow> (map_of xys x = Some y) = ((x,y) \\<in> set xys)\"\nproof (induct xys)\n  case (Cons xy xys)\n  then show ?case\n    by (cases xy) (auto simp flip: map_of_eq_None_iff)\nqed auto\n\nlemma Some_eq_map_of_iff [simp]:\n  \"distinct(map fst xys) \\<Longrightarrow> (Some y = map_of xys x) = ((x,y) \\<in> set xys)\"\nby (auto simp del: map_of_eq_Some_iff simp: map_of_eq_Some_iff [symmetric])\n\nlemma map_of_is_SomeI [simp]: \n  \"\\<lbrakk>distinct(map fst xys); (x,y) \\<in> set xys\\<rbrakk> \\<Longrightarrow> map_of xys x = Some y\"\n  by simp\n\nlemma map_of_zip_is_None [simp]:\n  \"length xs = length ys \\<Longrightarrow> (map_of (zip xs ys) x = None) = (x \\<notin> set xs)\"\nby (induct rule: list_induct2) simp_all\n\nlemma map_of_zip_is_Some:\n  assumes \"length xs = length ys\"\n  shows \"x \\<in> set xs \\<longleftrightarrow> (\\<exists>y. map_of (zip xs ys) x = Some y)\"\nusing assms by (induct rule: list_induct2) simp_all\n\nlemma map_of_zip_upd:\n  fixes x :: 'a and xs :: \"'a list\" and ys zs :: \"'b list\"\n  assumes \"length ys = length xs\"\n    and \"length zs = length xs\"\n    and \"x \\<notin> set xs\"\n    and \"map_of (zip xs ys)(x \\<mapsto> y) = map_of (zip xs zs)(x \\<mapsto> z)\"\n  shows \"map_of (zip xs ys) = map_of (zip xs zs)\"\nproof\n  fix x' :: 'a\n  show \"map_of (zip xs ys) x' = map_of (zip xs zs) x'\"\n  proof (cases \"x = x'\")\n    case True\n    from assms True map_of_zip_is_None [of xs ys x']\n      have \"map_of (zip xs ys) x' = None\" by simp\n    moreover from assms True map_of_zip_is_None [of xs zs x']\n      have \"map_of (zip xs zs) x' = None\" by simp\n    ultimately show ?thesis by simp\n  next\n    case False from assms\n      have \"(map_of (zip xs ys)(x \\<mapsto> y)) x' = (map_of (zip xs zs)(x \\<mapsto> z)) x'\" by auto\n    with False show ?thesis by simp\n  qed\nqed\n\nlemma map_of_zip_inject:\n  assumes \"length ys = length xs\"\n    and \"length zs = length xs\"\n    and dist: \"distinct xs\"\n    and map_of: \"map_of (zip xs ys) = map_of (zip xs zs)\"\n  shows \"ys = zs\"\n  using assms(1) assms(2)[symmetric]\n  using dist map_of\nproof (induct ys xs zs rule: list_induct3)\n  case Nil show ?case by simp\nnext\n  case (Cons y ys x xs z zs)\n  from \\<open>map_of (zip (x#xs) (y#ys)) = map_of (zip (x#xs) (z#zs))\\<close>\n    have map_of: \"map_of (zip xs ys)(x \\<mapsto> y) = map_of (zip xs zs)(x \\<mapsto> z)\" by simp\n  from Cons have \"length ys = length xs\" and \"length zs = length xs\"\n    and \"x \\<notin> set xs\" by simp_all\n  then have \"map_of (zip xs ys) = map_of (zip xs zs)\" using map_of by (rule map_of_zip_upd)\n  with Cons.hyps \\<open>distinct (x # xs)\\<close> have \"ys = zs\" by simp\n  moreover from map_of have \"y = z\" by (rule map_upd_eqD1)\n  ultimately show ?case by simp\nqed\n\nlemma map_of_zip_nth:\n  assumes \"length xs = length ys\"\n  assumes \"distinct xs\"\n  assumes \"i < length ys\"\n  shows \"map_of (zip xs ys) (xs ! i) = Some (ys ! i)\"\nusing assms proof (induct arbitrary: i rule: list_induct2)\n  case Nil\n  then show ?case by simp\nnext\n  case (Cons x xs y ys)\n  then show ?case\n    using less_Suc_eq_0_disj by auto\nqed\n\nlemma map_of_zip_map:\n  \"map_of (zip xs (map f xs)) = (\\<lambda>x. if x \\<in> set xs then Some (f x) else None)\"\n  by (induct xs) (simp_all add: fun_eq_iff)\n\nlemma finite_range_map_of: \"finite (range (map_of xys))\"\nproof (induct xys)\n  case (Cons a xys)\n  then show ?case\n    using finite_range_updI by fastforce\nqed auto\n\nlemma map_of_SomeD: \"map_of xs k = Some y \\<Longrightarrow> (k, y) \\<in> set xs\"\n  by (induct xs) (auto split: if_splits)\n\nlemma map_of_mapk_SomeI:\n  \"inj f \\<Longrightarrow> map_of t k = Some x \\<Longrightarrow>\n   map_of (map (case_prod (\\<lambda>k. Pair (f k))) t) (f k) = Some x\"\nby (induct t) (auto simp: inj_eq)\n\nlemma weak_map_of_SomeI: \"(k, x) \\<in> set l \\<Longrightarrow> \\<exists>x. map_of l k = Some x\"\nby (induct l) auto\n\nlemma map_of_filter_in:\n  \"map_of xs k = Some z \\<Longrightarrow> P k z \\<Longrightarrow> map_of (filter (case_prod P) xs) k = Some z\"\nby (induct xs) auto\n\nlemma map_of_map:\n  \"map_of (map (\\<lambda>(k, v). (k, f v)) xs) = map_option f \\<circ> map_of xs\"\n  by (induct xs) (auto simp: fun_eq_iff)\n\nlemma dom_map_option:\n  \"dom (\\<lambda>k. map_option (f k) (m k)) = dom m\"\n  by (simp add: dom_def)\n\nlemma dom_map_option_comp [simp]:\n  \"dom (map_option g \\<circ> m) = dom m\"\n  using dom_map_option [of \"\\<lambda>_. g\" m] by (simp add: comp_def)\n\n\nsubsection \\<open>\\<^const>\\<open>map_option\\<close> related\\<close>\n\nlemma map_option_o_empty [simp]: \"map_option f \\<circ> empty = empty\"\nby (rule ext) simp\n\nlemma map_option_o_map_upd [simp]:\n  \"map_option f \\<circ> m(a\\<mapsto>b) = (map_option f \\<circ> m)(a\\<mapsto>f b)\"\nby (rule ext) simp\n\n\nsubsection \\<open>@{term [source] map_comp} related\\<close>\n\nlemma map_comp_empty [simp]:\n  \"m \\<circ>\\<^sub>m empty = empty\"\n  \"empty \\<circ>\\<^sub>m m = empty\"\nby (auto simp: map_comp_def split: option.splits)\n\nlemma map_comp_simps [simp]:\n  \"m2 k = None \\<Longrightarrow> (m1 \\<circ>\\<^sub>m m2) k = None\"\n  \"m2 k = Some k' \\<Longrightarrow> (m1 \\<circ>\\<^sub>m m2) k = m1 k'\"\nby (auto simp: map_comp_def)\n\nlemma map_comp_Some_iff:\n  \"((m1 \\<circ>\\<^sub>m m2) k = Some v) = (\\<exists>k'. m2 k = Some k' \\<and> m1 k' = Some v)\"\nby (auto simp: map_comp_def split: option.splits)\n\nlemma map_comp_None_iff:\n  \"((m1 \\<circ>\\<^sub>m m2) k = None) = (m2 k = None \\<or> (\\<exists>k'. m2 k = Some k' \\<and> m1 k' = None)) \"\nby (auto simp: map_comp_def split: option.splits)\n\n\nsubsection \\<open>\\<open>++\\<close>\\<close>\n\nlemma map_add_empty[simp]: \"m ++ empty = m\"\nby(simp add: map_add_def)\n\nlemma empty_map_add[simp]: \"empty ++ m = m\"\nby (rule ext) (simp add: map_add_def split: option.split)\n\nlemma map_add_assoc[simp]: \"m1 ++ (m2 ++ m3) = (m1 ++ m2) ++ m3\"\nby (rule ext) (simp add: map_add_def split: option.split)\n\nlemma map_add_Some_iff:\n  \"((m ++ n) k = Some x) = (n k = Some x \\<or> n k = None \\<and> m k = Some x)\"\nby (simp add: map_add_def split: option.split)\n\nlemma map_add_SomeD [dest!]:\n  \"(m ++ n) k = Some x \\<Longrightarrow> n k = Some x \\<or> n k = None \\<and> m k = Some x\"\nby (rule map_add_Some_iff [THEN iffD1])\n\nlemma map_add_find_right [simp]: \"n k = Some xx \\<Longrightarrow> (m ++ n) k = Some xx\"\nby (subst map_add_Some_iff) fast\n\nlemma map_add_None [iff]: \"((m ++ n) k = None) = (n k = None \\<and> m k = None)\"\nby (simp add: map_add_def split: option.split)\n\nlemma map_add_upd[simp]: \"f ++ g(x\\<mapsto>y) = (f ++ g)(x\\<mapsto>y)\"\nby (rule ext) (simp add: map_add_def)\n\nlemma map_add_upds[simp]: \"m1 ++ (m2(xs[\\<mapsto>]ys)) = (m1++m2)(xs[\\<mapsto>]ys)\"\nby (simp add: map_upds_def)\n\nlemma map_add_upd_left: \"m\\<notin>dom e2 \\<Longrightarrow> e1(m \\<mapsto> u1) ++ e2 = (e1 ++ e2)(m \\<mapsto> u1)\"\nby (rule ext) (auto simp: map_add_def dom_def split: option.split)\n\nlemma map_of_append[simp]: \"map_of (xs @ ys) = map_of ys ++ map_of xs\"\n  unfolding map_add_def\nproof (induct xs)\n  case (Cons a xs)\n  then show ?case\n    by (force split: option.split)\nqed auto\n\nlemma finite_range_map_of_map_add:\n  \"finite (range f) \\<Longrightarrow> finite (range (f ++ map_of l))\"\nproof (induct l)\ncase (Cons a l)\n  then show ?case\n    by (metis finite_range_updI map_add_upd map_of.simps(2))\nqed auto\n\nlemma inj_on_map_add_dom [iff]:\n  \"inj_on (m ++ m') (dom m') = inj_on m' (dom m')\"\n  by (fastforce simp: map_add_def dom_def inj_on_def split: option.splits)\n\nlemma map_upds_fold_map_upd:\n  \"m(ks[\\<mapsto>]vs) = foldl (\\<lambda>m (k, v). m(k \\<mapsto> v)) m (zip ks vs)\"\nunfolding map_upds_def proof (rule sym, rule zip_obtain_same_length)\n  fix ks :: \"'a list\" and vs :: \"'b list\"\n  assume \"length ks = length vs\"\n  then show \"foldl (\\<lambda>m (k, v). m(k\\<mapsto>v)) m (zip ks vs) = m ++ map_of (rev (zip ks vs))\"\n    by(induct arbitrary: m rule: list_induct2) simp_all\nqed\n\nlemma map_add_map_of_foldr:\n  \"m ++ map_of ps = foldr (\\<lambda>(k, v) m. m(k \\<mapsto> v)) ps m\"\n  by (induct ps) (auto simp: fun_eq_iff map_add_def)\n\n\nsubsection \\<open>@{term [source] restrict_map}\\<close>\n\nlemma restrict_map_to_empty [simp]: \"m|`{} = empty\"\n  by (simp add: restrict_map_def)\n\nlemma restrict_map_insert: \"f |` (insert a A) = (f |` A)(a := f a)\"\n  by (auto simp: restrict_map_def)\n\nlemma restrict_map_empty [simp]: \"empty|`D = empty\"\n  by (simp add: restrict_map_def)\n\nlemma restrict_in [simp]: \"x \\<in> A \\<Longrightarrow> (m|`A) x = m x\"\n  by (simp add: restrict_map_def)\n\nlemma restrict_out [simp]: \"x \\<notin> A \\<Longrightarrow> (m|`A) x = None\"\n  by (simp add: restrict_map_def)\n\nlemma ran_restrictD: \"y \\<in> ran (m|`A) \\<Longrightarrow> \\<exists>x\\<in>A. m x = Some y\"\n  by (auto simp: restrict_map_def ran_def split: if_split_asm)\n\nlemma dom_restrict [simp]: \"dom (m|`A) = dom m \\<inter> A\"\n  by (auto simp: restrict_map_def dom_def split: if_split_asm)\n\nlemma restrict_upd_same [simp]: \"m(x\\<mapsto>y)|`(-{x}) = m|`(-{x})\"\n  by (rule ext) (auto simp: restrict_map_def)\n\nlemma restrict_restrict [simp]: \"m|`A|`B = m|`(A\\<inter>B)\"\n  by (rule ext) (auto simp: restrict_map_def)\n\nlemma restrict_fun_upd [simp]:\n  \"m(x := y)|`D = (if x \\<in> D then (m|`(D-{x}))(x := y) else m|`D)\"\n  by (simp add: restrict_map_def fun_eq_iff)\n\nlemma fun_upd_None_restrict [simp]:\n  \"(m|`D)(x := None) = (if x \\<in> D then m|`(D - {x}) else m|`D)\"\n  by (simp add: restrict_map_def fun_eq_iff)\n\nlemma fun_upd_restrict: \"(m|`D)(x := y) = (m|`(D-{x}))(x := y)\"\n  by (simp add: restrict_map_def fun_eq_iff)\n\nlemma fun_upd_restrict_conv [simp]:\n  \"x \\<in> D \\<Longrightarrow> (m|`D)(x := y) = (m|`(D-{x}))(x := y)\"\n  by (rule fun_upd_restrict)\n\nlemma map_of_map_restrict:\n  \"map_of (map (\\<lambda>k. (k, f k)) ks) = (Some \\<circ> f) |` set ks\"\n  by (induct ks) (simp_all add: fun_eq_iff restrict_map_insert)\n\nlemma restrict_complement_singleton_eq:\n  \"f |` (- {x}) = f(x := None)\"\n  by auto\n\n\nsubsection \\<open>@{term [source] map_upds}\\<close>\n\nlemma map_upds_Nil1 [simp]: \"m([] [\\<mapsto>] bs) = m\"\n  by (simp add: map_upds_def)\n\nlemma map_upds_Nil2 [simp]: \"m(as [\\<mapsto>] []) = m\"\n  by (simp add:map_upds_def)\n\nlemma map_upds_Cons [simp]: \"m(a#as [\\<mapsto>] b#bs) = (m(a\\<mapsto>b))(as[\\<mapsto>]bs)\"\n  by (simp add:map_upds_def)\n\nlemma map_upds_append1 [simp]:\n  \"size xs < size ys \\<Longrightarrow> m(xs@[x] [\\<mapsto>] ys) = m(xs [\\<mapsto>] ys)(x \\<mapsto> ys!size xs)\"\nproof (induct xs arbitrary: ys m)\n  case Nil\n  then show ?case\n    by (auto simp: neq_Nil_conv)\nnext\n  case (Cons a xs)\n  then show ?case\n    by (cases ys) auto\nqed\n\nlemma map_upds_list_update2_drop [simp]:\n  \"size xs \\<le> i \\<Longrightarrow> m(xs[\\<mapsto>]ys[i:=y]) = m(xs[\\<mapsto>]ys)\"\nproof (induct xs arbitrary: m ys i)\n  case Nil\n  then show ?case\n    by auto\nnext\n  case (Cons a xs)\n  then show ?case\n    by (cases ys) (use Cons in \\<open>auto split: nat.split\\<close>)\nqed\n\ntext \\<open>Something weirdly sensitive about this proof, which needs only four lines in apply style\\<close>\nlemma map_upd_upds_conv_if:\n  \"(f(x\\<mapsto>y))(xs [\\<mapsto>] ys) =\n   (if x \\<in> set(take (length ys) xs) then f(xs [\\<mapsto>] ys)\n                                    else (f(xs [\\<mapsto>] ys))(x\\<mapsto>y))\"\nproof (induct xs arbitrary: x y ys f)\n  case (Cons a xs)\n  show ?case\n  proof (cases ys)\n    case (Cons z zs)\n    then show ?thesis\n      using Cons.hyps\n      apply (auto split: if_split simp: fun_upd_twist)\n      using Cons.hyps apply fastforce+\n      done\n  qed auto\nqed auto\n\n\nlemma map_upds_twist [simp]:\n  \"a \\<notin> set as \\<Longrightarrow> m(a\\<mapsto>b)(as[\\<mapsto>]bs) = m(as[\\<mapsto>]bs)(a\\<mapsto>b)\"\nusing set_take_subset by (fastforce simp add: map_upd_upds_conv_if)\n\nlemma map_upds_apply_nontin [simp]:\n  \"x \\<notin> set xs \\<Longrightarrow> (f(xs[\\<mapsto>]ys)) x = f x\"\nproof (induct xs arbitrary: ys)\n  case (Cons a xs)\n  then show ?case\n    by (cases ys) (auto simp: map_upd_upds_conv_if)\nqed auto\n\nlemma fun_upds_append_drop [simp]:\n  \"size xs = size ys \\<Longrightarrow> m(xs@zs[\\<mapsto>]ys) = m(xs[\\<mapsto>]ys)\"\nproof (induct xs arbitrary: ys)\n  case (Cons a xs)\n  then show ?case\n    by (cases ys) (auto simp: map_upd_upds_conv_if)\nqed auto\n\nlemma fun_upds_append2_drop [simp]:\n  \"size xs = size ys \\<Longrightarrow> m(xs[\\<mapsto>]ys@zs) = m(xs[\\<mapsto>]ys)\"\nproof (induct xs arbitrary: ys)\n  case (Cons a xs)\n  then show ?case\n    by (cases ys) (auto simp: map_upd_upds_conv_if)\nqed auto\n\nlemma restrict_map_upds[simp]:\n  \"\\<lbrakk> length xs = length ys; set xs \\<subseteq> D \\<rbrakk>\n    \\<Longrightarrow> m(xs [\\<mapsto>] ys)|`D = (m|`(D - set xs))(xs [\\<mapsto>] ys)\"\nproof (induct xs arbitrary: m ys)\n  case (Cons a xs)\n  then show ?case\n  proof (cases ys)\n    case (Cons z zs)\n    with Cons.hyps Cons.prems show ?thesis\n      apply (simp add: insert_absorb flip: Diff_insert)\n      apply (auto simp add: map_upd_upds_conv_if)\n      done\n  qed auto\nqed auto\n\n\nsubsection \\<open>@{term [source] dom}\\<close>\n\nlemma dom_eq_empty_conv [simp]: \"dom f = {} \\<longleftrightarrow> f = empty\"\n  by (auto simp: dom_def)\n\nlemma domI: \"m a = Some b \\<Longrightarrow> a \\<in> dom m\"\n  by (simp add: dom_def)\n(* declare domI [intro]? *)\n\nlemma domD: \"a \\<in> dom m \\<Longrightarrow> \\<exists>b. m a = Some b\"\n  by (cases \"m a\") (auto simp add: dom_def)\n\nlemma domIff [iff, simp del, code_unfold]: \"a \\<in> dom m \\<longleftrightarrow> m a \\<noteq> None\"\n  by (simp add: dom_def)\n\nlemma dom_empty [simp]: \"dom empty = {}\"\n  by (simp add: dom_def)\n\nlemma dom_fun_upd [simp]:\n  \"dom(f(x := y)) = (if y = None then dom f - {x} else insert x (dom f))\"\n  by (auto simp: dom_def)\n\nlemma dom_if:\n  \"dom (\\<lambda>x. if P x then f x else g x) = dom f \\<inter> {x. P x} \\<union> dom g \\<inter> {x. \\<not> P x}\"\n  by (auto split: if_splits)\n\nlemma dom_map_of_conv_image_fst:\n  \"dom (map_of xys) = fst ` set xys\"\n  by (induct xys) (auto simp add: dom_if)\n\nlemma dom_map_of_zip [simp]: \"length xs = length ys \\<Longrightarrow> dom (map_of (zip xs ys)) = set xs\"\n  by (induct rule: list_induct2) (auto simp: dom_if)\n\nlemma finite_dom_map_of: \"finite (dom (map_of l))\"\n  by (induct l) (auto simp: dom_def insert_Collect [symmetric])\n\nlemma dom_map_upds [simp]:\n  \"dom(m(xs[\\<mapsto>]ys)) = set(take (length ys) xs) \\<union> dom m\"\nproof (induct xs arbitrary: ys)\n  case (Cons a xs)\n  then show ?case\n    by (cases ys) (auto simp: map_upd_upds_conv_if)\nqed auto\n\n\nlemma dom_map_add [simp]: \"dom (m ++ n) = dom n \\<union> dom m\"\n  by (auto simp: dom_def)\n\nlemma dom_override_on [simp]:\n  \"dom (override_on f g A) =\n    (dom f  - {a. a \\<in> A - dom g}) \\<union> {a. a \\<in> A \\<inter> dom g}\"\n  by (auto simp: dom_def override_on_def)\n\n\n\nlemma map_add_dom_app_simps:\n  \"m \\<in> dom l2 \\<Longrightarrow> (l1 ++ l2) m = l2 m\"\n  \"m \\<notin> dom l1 \\<Longrightarrow> (l1 ++ l2) m = l2 m\"\n  \"m \\<notin> dom l2 \\<Longrightarrow> (l1 ++ l2) m = l1 m\"\n  by (auto simp add: map_add_def split: option.split_asm)\n\nlemma dom_const [simp]:\n  \"dom (\\<lambda>x. Some (f x)) = UNIV\"\n  by auto\n\n(* Due to John Matthews - could be rephrased with dom *)\nlemma finite_map_freshness:\n  \"finite (dom (f :: 'a \\<rightharpoonup> 'b)) \\<Longrightarrow> \\<not> finite (UNIV :: 'a set) \\<Longrightarrow>\n   \\<exists>x. f x = None\"\n  by (bestsimp dest: ex_new_if_finite)\n\nlemma dom_minus:\n  \"f x = None \\<Longrightarrow> dom f - insert x A = dom f - A\"\n  unfolding dom_def by simp\n\nlemma insert_dom:\n  \"f x = Some y \\<Longrightarrow> insert x (dom f) = dom f\"\n  unfolding dom_def by auto\n\nlemma map_of_map_keys:\n  \"set xs = dom m \\<Longrightarrow> map_of (map (\\<lambda>k. (k, the (m k))) xs) = m\"\n  by (rule ext) (auto simp add: map_of_map_restrict restrict_map_def)\n\nlemma map_of_eqI:\n  assumes set_eq: \"set (map fst xs) = set (map fst ys)\"\n  assumes map_eq: \"\\<forall>k\\<in>set (map fst xs). map_of xs k = map_of ys k\"\n  shows \"map_of xs = map_of ys\"\nproof (rule ext)\n  fix k show \"map_of xs k = map_of ys k\"\n  proof (cases \"map_of xs k\")\n    case None\n    then have \"k \\<notin> set (map fst xs)\" by (simp add: map_of_eq_None_iff)\n    with set_eq have \"k \\<notin> set (map fst ys)\" by simp\n    then have \"map_of ys k = None\" by (simp add: map_of_eq_None_iff)\n    with None show ?thesis by simp\n  next\n    case (Some v)\n    then have \"k \\<in> set (map fst xs)\" by (auto simp add: dom_map_of_conv_image_fst [symmetric])\n    with map_eq show ?thesis by auto\n  qed\nqed\n\nlemma map_of_eq_dom:\n  assumes \"map_of xs = map_of ys\"\n  shows \"fst ` set xs = fst ` set ys\"\nproof -\n  from assms have \"dom (map_of xs) = dom (map_of ys)\" by simp\n  then show ?thesis by (simp add: dom_map_of_conv_image_fst)\nqed\n\nlemma finite_set_of_finite_maps:\n  assumes \"finite A\" \"finite B\"\n  shows \"finite {m. dom m = A \\<and> ran m \\<subseteq> B}\" (is \"finite ?S\")\nproof -\n  let ?S' = \"{m. \\<forall>x. (x \\<in> A \\<longrightarrow> m x \\<in> Some ` B) \\<and> (x \\<notin> A \\<longrightarrow> m x = None)}\"\n  have \"?S = ?S'\"\n  proof\n    show \"?S \\<subseteq> ?S'\" by (auto simp: dom_def ran_def image_def)\n    show \"?S' \\<subseteq> ?S\"\n    proof\n      fix m assume \"m \\<in> ?S'\"\n      hence 1: \"dom m = A\" by force\n      hence 2: \"ran m \\<subseteq> B\" using \\<open>m \\<in> ?S'\\<close> by (auto simp: dom_def ran_def)\n      from 1 2 show \"m \\<in> ?S\" by blast\n    qed\n  qed\n  with assms show ?thesis by(simp add: finite_set_of_finite_funs)\nqed\n\n\nsubsection \\<open>@{term [source] ran}\\<close>\n\nlemma ranI: \"m a = Some b \\<Longrightarrow> b \\<in> ran m\"\n  by (auto simp: ran_def)\n(* declare ranI [intro]? *)\n\nlemma ran_empty [simp]: \"ran empty = {}\"\n  by (auto simp: ran_def)\n\nlemma ran_map_upd [simp]:  \"m a = None \\<Longrightarrow> ran(m(a\\<mapsto>b)) = insert b (ran m)\"\n  unfolding ran_def\n  by force\n\nlemma ran_map_add:\n  assumes \"dom m1 \\<inter> dom m2 = {}\"\n  shows \"ran (m1 ++ m2) = ran m1 \\<union> ran m2\"\nproof\n  show \"ran (m1 ++ m2) \\<subseteq> ran m1 \\<union> ran m2\"\n    unfolding ran_def by auto\nnext\n  show \"ran m1 \\<union> ran m2 \\<subseteq> ran (m1 ++ m2)\"\n  proof -\n    have \"(m1 ++ m2) x = Some y\" if \"m1 x = Some y\" for x y\n      using assms map_add_comm that by fastforce\n    moreover have \"(m1 ++ m2) x = Some y\" if \"m2 x = Some y\" for x y\n      using assms that by auto\n    ultimately show ?thesis\n      unfolding ran_def by blast\n  qed\nqed\n\nlemma finite_ran:\n  assumes \"finite (dom p)\"\n  shows \"finite (ran p)\"\nproof -\n  have \"ran p = (\\<lambda>x. the (p x)) ` dom p\"\n    unfolding ran_def by force\n  from this \\<open>finite (dom p)\\<close> show ?thesis by auto\nqed\n\nlemma ran_distinct:\n  assumes dist: \"distinct (map fst al)\"\n  shows \"ran (map_of al) = snd ` set al\"\n  using assms\nproof (induct al)\n  case Nil\n  then show ?case by simp\nnext\n  case (Cons kv al)\n  then have \"ran (map_of al) = snd ` set al\" by simp\n  moreover from Cons.prems have \"map_of al (fst kv) = None\"\n    by (simp add: map_of_eq_None_iff)\n  ultimately show ?case by (simp only: map_of.simps ran_map_upd) simp\nqed\n\nlemma ran_map_of_zip:\n  assumes \"length xs = length ys\" \"distinct xs\"\n  shows \"ran (map_of (zip xs ys)) = set ys\"\nusing assms by (simp add: ran_distinct set_map[symmetric])\n\nlemma ran_map_option: \"ran (\\<lambda>x. map_option f (m x)) = f ` ran m\"\n  by (auto simp add: ran_def)\n\n\nsubsection \\<open>\\<open>map_le\\<close>\\<close>\n\nlemma map_le_empty [simp]: \"empty \\<subseteq>\\<^sub>m g\"\n  by (simp add: map_le_def)\n\nlemma upd_None_map_le [simp]: \"f(x := None) \\<subseteq>\\<^sub>m f\"\n  by (force simp add: map_le_def)\n\nlemma map_le_upd[simp]: \"f \\<subseteq>\\<^sub>m g ==> f(a := b) \\<subseteq>\\<^sub>m g(a := b)\"\n  by (fastforce simp add: map_le_def)\n\nlemma map_le_imp_upd_le [simp]: \"m1 \\<subseteq>\\<^sub>m m2 \\<Longrightarrow> m1(x := None) \\<subseteq>\\<^sub>m m2(x \\<mapsto> y)\"\n  by (force simp add: map_le_def)\n\nlemma map_le_upds [simp]:\n  \"f \\<subseteq>\\<^sub>m g \\<Longrightarrow> f(as [\\<mapsto>] bs) \\<subseteq>\\<^sub>m g(as [\\<mapsto>] bs)\"\nproof (induct as arbitrary: f g bs)\n  case (Cons a as)\n  then show ?case\n    by (cases bs) (use Cons in auto)\nqed auto\n\nlemma map_le_implies_dom_le: \"(f \\<subseteq>\\<^sub>m g) \\<Longrightarrow> (dom f \\<subseteq> dom g)\"\n  by (fastforce simp add: map_le_def dom_def)\n\nlemma map_le_refl [simp]: \"f \\<subseteq>\\<^sub>m f\"\n  by (simp add: map_le_def)\n\nlemma map_le_trans[trans]: \"\\<lbrakk> m1 \\<subseteq>\\<^sub>m m2; m2 \\<subseteq>\\<^sub>m m3\\<rbrakk> \\<Longrightarrow> m1 \\<subseteq>\\<^sub>m m3\"\n  by (auto simp add: map_le_def dom_def)\n\nlemma map_le_antisym: \"\\<lbrakk> f \\<subseteq>\\<^sub>m g; g \\<subseteq>\\<^sub>m f \\<rbrakk> \\<Longrightarrow> f = g\"\n  unfolding map_le_def\n  by (metis ext domIff)\n\nlemma map_le_map_add [simp]: \"f \\<subseteq>\\<^sub>m g ++ f\"\n  by (fastforce simp: map_le_def)\n\nlemma map_le_iff_map_add_commute: \"f \\<subseteq>\\<^sub>m f ++ g \\<longleftrightarrow> f ++ g = g ++ f\"\n  by (fastforce simp: map_add_def map_le_def fun_eq_iff split: option.splits)\n\nlemma map_add_le_mapE: \"f ++ g \\<subseteq>\\<^sub>m h \\<Longrightarrow> g \\<subseteq>\\<^sub>m h\"\n  by (fastforce simp: map_le_def map_add_def dom_def)\n\nlemma map_add_le_mapI: \"\\<lbrakk> f \\<subseteq>\\<^sub>m h; g \\<subseteq>\\<^sub>m h \\<rbrakk> \\<Longrightarrow> f ++ g \\<subseteq>\\<^sub>m h\"\n  by (auto simp: map_le_def map_add_def dom_def split: option.splits)\n\nlemma map_add_subsumed1: \"f \\<subseteq>\\<^sub>m g \\<Longrightarrow> f++g = g\"\nby (simp add: map_add_le_mapI map_le_antisym)\n\nlemma map_add_subsumed2: \"f \\<subseteq>\\<^sub>m g \\<Longrightarrow> g++f = g\"\nby (metis map_add_subsumed1 map_le_iff_map_add_commute)\n\nlemma dom_eq_singleton_conv: \"dom f = {x} \\<longleftrightarrow> (\\<exists>v. f = [x \\<mapsto> v])\"\n  (is \"?lhs \\<longleftrightarrow> ?rhs\")\nproof\n  assume ?rhs\n  then show ?lhs by (auto split: if_split_asm)\nnext\n  assume ?lhs\n  then obtain v where v: \"f x = Some v\" by auto\n  show ?rhs\n  proof\n    show \"f = [x \\<mapsto> v]\"\n    proof (rule map_le_antisym)\n      show \"[x \\<mapsto> v] \\<subseteq>\\<^sub>m f\"\n        using v by (auto simp add: map_le_def)\n      show \"f \\<subseteq>\\<^sub>m [x \\<mapsto> v]\"\n        using \\<open>dom f = {x}\\<close> \\<open>f x = Some v\\<close> by (auto simp add: map_le_def)\n    qed\n  qed\nqed\n\nlemma map_add_eq_empty_iff[simp]:\n  \"(f++g = empty) \\<longleftrightarrow> f = empty \\<and> g = empty\"\nby (metis map_add_None)\n\nlemma empty_eq_map_add_iff[simp]:\n  \"(empty = f++g) \\<longleftrightarrow> f = empty \\<and> g = empty\"\nby(subst map_add_eq_empty_iff[symmetric])(rule eq_commute)\n\n\nsubsection \\<open>Various\\<close>\n\nlemma set_map_of_compr:\n  assumes distinct: \"distinct (map fst xs)\"\n  shows \"set xs = {(k, v). map_of xs k = Some v}\"\n  using assms\nproof (induct xs)\n  case Nil\n  then show ?case by simp\nnext\n  case (Cons x xs)\n  obtain k v where \"x = (k, v)\" by (cases x) blast\n  with Cons.prems have \"k \\<notin> dom (map_of xs)\"\n    by (simp add: dom_map_of_conv_image_fst)\n  then have *: \"insert (k, v) {(k, v). map_of xs k = Some v} =\n    {(k', v'). (map_of xs(k \\<mapsto> v)) k' = Some v'}\"\n    by (auto split: if_splits)\n  from Cons have \"set xs = {(k, v). map_of xs k = Some v}\" by simp\n  with * \\<open>x = (k, v)\\<close> show ?case by simp\nqed\n\nlemma eq_key_imp_eq_value:\n  \"v1 = v2\"\n  if \"distinct (map fst xs)\" \"(k, v1) \\<in> set xs\" \"(k, v2) \\<in> set xs\"\nproof -\n  from that have \"inj_on fst (set xs)\"\n    by (simp add: distinct_map)\n  moreover have \"fst (k, v1) = fst (k, v2)\"\n    by simp\n  ultimately have \"(k, v1) = (k, v2)\"\n    by (rule inj_onD) (fact that)+\n  then show ?thesis\n    by simp\nqed\n\nlemma map_of_inject_set:\n  assumes distinct: \"distinct (map fst xs)\" \"distinct (map fst ys)\"\n  shows \"map_of xs = map_of ys \\<longleftrightarrow> set xs = set ys\" (is \"?lhs \\<longleftrightarrow> ?rhs\")\nproof\n  assume ?lhs\n  moreover from \\<open>distinct (map fst xs)\\<close> have \"set xs = {(k, v). map_of xs k = Some v}\"\n    by (rule set_map_of_compr)\n  moreover from \\<open>distinct (map fst ys)\\<close> have \"set ys = {(k, v). map_of ys k = Some v}\"\n    by (rule set_map_of_compr)\n  ultimately show ?rhs by simp\nnext\n  assume ?rhs show ?lhs\n  proof\n    fix k\n    show \"map_of xs k = map_of ys k\"\n    proof (cases \"map_of xs k\")\n      case None\n      with \\<open>?rhs\\<close> have \"map_of ys k = None\"\n        by (simp add: map_of_eq_None_iff)\n      with None show ?thesis by simp\n    next\n      case (Some v)\n      with distinct \\<open>?rhs\\<close> have \"map_of ys k = Some v\"\n        by simp\n      with Some show ?thesis by simp\n    qed\n  qed\nqed\n\nhide_const (open) Map.empty\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/Map.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256472515683, "lm_q2_score": 0.8438951064805861, "lm_q1q2_score": 0.7104125442254505}}
{"text": "(* Author: Tobias Nipkow *)\n\nsection \\<open>Unbalanced Tree Implementation of Set\\<close>\n\ntheory Tree_Set\nimports\n  Tree\n  Cmp\n  Set_Specs\nbegin\n\ndefinition empty :: \"'a tree\" where\n\"empty = Leaf\"\n\nfun isin :: \"'a::linorder 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\nhide_const (open) insert\n\nfun insert :: \"'a::linorder \\<Rightarrow> 'a tree \\<Rightarrow> 'a tree\" where\n\"insert x Leaf = Node Leaf x Leaf\" |\n\"insert x (Node l a r) =\n  (case cmp x a of\n     LT \\<Rightarrow> Node (insert x l) a r |\n     EQ \\<Rightarrow> Node l a r |\n     GT \\<Rightarrow> Node l a (insert x r))\"\n\ntext \\<open>Deletion by replacing:\\<close>\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) else let (x,l') = split_min l 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  (case cmp x a of\n     LT \\<Rightarrow>  Node (delete x l) a r |\n     GT \\<Rightarrow>  Node l a (delete x r) |\n     EQ \\<Rightarrow> if r = Leaf then l else let (a',r') = split_min r in Node l a' r')\"\n\ntext \\<open>Deletion by joining:\\<close>\n\nfun join :: \"('a::linorder)tree \\<Rightarrow> 'a tree \\<Rightarrow> 'a tree\" where\n\"join t Leaf = t\" |\n\"join Leaf t = t\" |\n\"join (Node t1 a t2) (Node t3 b t4) =\n  (case join t2 t3 of\n     Leaf \\<Rightarrow> Node t1 a (Node Leaf b t4) |\n     Node u2 x u3 \\<Rightarrow> Node (Node t1 a u2) x (Node u3 b t4))\"\n\nfun delete2 :: \"'a::linorder \\<Rightarrow> 'a tree \\<Rightarrow> 'a tree\" where\n\"delete2 x Leaf = Leaf\" |\n\"delete2 x (Node l a r) =\n  (case cmp x a of\n     LT \\<Rightarrow>  Node (delete2 x l) a r |\n     GT \\<Rightarrow>  Node l a (delete2 x r) |\n     EQ \\<Rightarrow> join l r)\"\n\n\nsubsection \"Functional Correctness Proofs\"\n\nlemma isin_set: \"sorted(inorder t) \\<Longrightarrow> isin t x = (x \\<in> set (inorder t))\"\nby (induction t) (auto simp: isin_simps)\n\nlemma inorder_insert:\n  \"sorted(inorder t) \\<Longrightarrow> inorder(insert x t) = ins_list x (inorder t)\"\nby(induction t) (auto simp: ins_list_simps)\n\n\nlemma split_minD:\n  \"split_min t = (x,t') \\<Longrightarrow> t \\<noteq> Leaf \\<Longrightarrow> x # inorder t' = inorder t\"\nby(induction t arbitrary: t' rule: split_min.induct)\n  (auto simp: sorted_lems split: prod.splits if_splits)\n\nlemma inorder_delete:\n  \"sorted(inorder t) \\<Longrightarrow> inorder(delete x t) = del_list x (inorder t)\"\nby(induction t) (auto simp: del_list_simps split_minD split: prod.splits)\n\ninterpretation S: Set_by_Ordered\nwhere empty = empty and isin = isin and insert = insert and delete = delete\nand inorder = inorder and inv = \"\\<lambda>_. True\"\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)\nnext\n  case 3 thus ?case by(simp add: inorder_insert)\nnext\n  case 4 thus ?case by(simp add: inorder_delete)\nqed (rule TrueI)+\n\nlemma inorder_join:\n  \"inorder(join l r) = inorder l @ inorder r\"\nby(induction l r rule: join.induct) (auto split: tree.split)\n\nlemma inorder_delete2:\n  \"sorted(inorder t) \\<Longrightarrow> inorder(delete2 x t) = del_list x (inorder t)\"\nby(induction t) (auto simp: inorder_join del_list_simps)\n\ninterpretation S2: Set_by_Ordered\nwhere empty = empty and isin = isin and insert = insert and delete = delete2\nand inorder = inorder and inv = \"\\<lambda>_. True\"\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)\nnext\n  case 3 thus ?case by(simp add: inorder_insert)\nnext\n  case 4 thus ?case by(simp add: inorder_delete2)\nqed (rule TrueI)+\n\nend\n", "meta": {"author": "LVPGroup", "repo": "fpp", "sha": "7e18377ea2c553bf6e57412727a4f06832d93577", "save_path": "github-repos/isabelle/LVPGroup-fpp", "path": "github-repos/isabelle/LVPGroup-fpp/fpp-7e18377ea2c553bf6e57412727a4f06832d93577/4_ds_algo/bintree/Tree_Set.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951064805861, "lm_q2_score": 0.8418256472515683, "lm_q1q2_score": 0.7104125442254505}}
{"text": "           (*-------------------------------------------*\n            |       Uniform Candy Distribution          |\n            |                                           |\n            |           November 2007 for Isabelle 2005 |\n            |           November 2008 for Isabelle 2008 |\n            |                                           |\n            |        Yoshinao Isobe (AIST JAPAN)        |\n            *-------------------------------------------*)\n\ntheory UCD_data1\nimports CSP_F\nbegin\n\n(*****************************************************************\n\n         1. Data part\n\n *****************************************************************)\n\n(* line and circ *)\n\ndefinition\n  fill       :: \"nat => nat\"\n  where\n  fill_def     : \"fill n == if even n then n else n+1\"\n    \ndefinition  \n  allEven    :: \"nat list => bool\"\n  where\n  allEven_def  : \"allEven s == (ALL s:set s. even s)\"\n\nprimrec\n  lineNext   :: \"nat list => nat => nat list\"\nwhere\n  \"lineNext  ([]) = (%x. [])\"\n |\"lineNext (n#s) = (%x. if (s=[]) then [fill(n div 2 + x)]\n                         else (fill(n div 2 + hd(s) div 2))#(lineNext s x))\"\n\ndefinition\n  circNext   :: \"nat list => nat list\"\nwhere\n  circNext_def : \"circNext s == (if s=[] then [] else lineNext s (hd s div 2))\"\n\nprimrec\n  circNexts  :: \"nat => nat list => nat list\"\nwhere\n  \"circNexts      0  = (%s. s)\"\n |\"circNexts (Suc N) = (%s. circNexts N (circNext s))\"\n\n\n\n(* max and min *)\n\nprimrec\n  maxList        :: \"nat list => nat\"\nwhere\n  \"maxList ([])  = 0\"\n |\"maxList (n#s) = (if (maxList(s) < n) then n else maxList(s))\"\n\nprimrec\n  minList        :: \"nat list => nat\"\nwhere\n  \"minList ([])  = 0\"\n |\"minList (n#s) = (if (s=[]) then n\n                    else if (n < minList(s)) then n else minList(s))\"\n\nprimrec\n  howMany        :: \"nat => nat list => nat\"\nwhere\n  \"howMany m ([])  = 0\"\n |\"howMany m (n#s) = (if (m=n) then (Suc (howMany m s)) else howMany m s)\"\n\ndefinition\n  stableList     :: \"nat list => bool\"\nwhere\n  stableList_def: \"stableList s == ALL n:set s. n = minList s\"\n\nprimrec\n  makeStableList :: \"nat => nat => nat list\"\nwhere\n  \"makeStableList 0 = (%n. [])\"\n |\"makeStableList (Suc l) = (%n. n#makeStableList l n)\"\n\n(* ------ test ------ *)\n\nlemma lineNext_test: \n  \"lineNext [4, 2, 10] 2 = [4, 6, 8]\"\nby (simp add: fill_def)\n\nlemma circNext_test: \n  \"circNext [4, 2, 10] = [4, 6, 8]\"\nby (simp add: circNext_def fill_def)\n\nlemma maxList_test: \n  \"maxList [4, 2, 10, 1, 5] = 10\"\nby (simp)\n\nlemma minList_test: \n  \"minList [4, 2, 10, 1, 5] = 1\"\nby (simp)\n\nlemma howMany_test: \n  \"howMany 2 [4, 2, 10, 2, 5, 2] = 3\"\nby (simp)\n\nlemma makeStableList_test: \n  \"makeStableList (Suc (Suc (Suc 0))) 5 = [5, 5, 5]\"\nby (simp)\n\n(* ------------------------------------------------- *\n                convenient lemmas \n * ------------------------------------------------- *)\n\nlemma not_nil_EX: \"(s ~= []) = (EX a t. s=a#t)\"\nby (induct_tac s, auto)\n\nlemma hd_in_list[simp]: \"s ~= [] --> hd s : set s\"\nby (induct_tac s, auto)\n\nlemma nth_hd: \"s ~= [] --> s!0 = hd s\"\nby (induct_tac s, auto)\n\nlemma nth_last: \"Suc i = length s ==> (s ! i = last s)\"\napply (insert list_last_nil_or_unnil)\napply (drule_tac x=\"s\" in spec)\napply (auto)\ndone\n\nlemma list_not_nil: \"(s ~= []) = (EX a t. s = a#t)\"\nby (induct_tac s, auto)\n\nlemma even_EX: \"(even n) = (EX m. n = (2::nat)*m)\"\napply (auto elim: evenE)\n(* for Isabelle 2013\napply (simp add: even_nat_equiv_def2)\napply (auto)\napply (rule_tac x=\"y\" in exI, simp)\napply (rule_tac x=\"m\" in exI, simp)\n*)\ndone\n\nlemma less_Suc: \"(n < Suc N) = (n=0 | (EX m. n = Suc m & m < N))\"\nby (induct_tac n, auto)\n\nlemma zero_less_EX: \"(0 < n) = (EX m. n = Suc m)\"\nby (induct_tac n, auto)\n\nlemma in_set_nth: \"n:set s = (EX i. i<length s & n = s!i)\"\napply (induct_tac s, auto)\napply (auto simp add: less_Suc)\ndone\n\nlemma list_length_more_one: \"(Suc 0 < length s) = (s ~= [] & tl s ~= [])\"\nby (induct_tac s, auto)\n\n(* ------------------------------------------------- *\n               lemmas on line and circ\n * ------------------------------------------------- *)\n\n(* [] *)\n\nlemma allEven_nil[simp]: \"allEven []\"\nby (simp add: allEven_def)\n\nlemma lineNext_nil_iff[simp]: \"(lineNext s x = []) = (s = [])\"\nby (induct_tac s, auto)\n\nlemma circNext_nil_iff[simp]: \"(circNext s = []) = (s = [])\"\nby (simp add: circNext_def)\n\nlemma tl_lineNext_nil_iff[simp]: \"(tl (lineNext s x) = []) = (tl s = [])\"\nby (induct_tac s, auto)\n\nlemma tl_circNext_nil_iff[simp]: \"(tl (circNext s) = []) = (tl s = [])\"\nby (simp add: circNext_def)\n\nlemma circNext_nil[simp]: \"circNext [] = []\"\nby (simp)\n\nlemma circNexts_nil_iff[simp]: \"ALL s. (circNexts N s = []) = (s = [])\"\nby (induct_tac N, auto)\n\nlemma circNexts_nil[simp]: \"ALL s. (circNexts N [] = [])\"\nby (induct_tac N, auto)\n\n(* length *)\n\nlemma length_lineNext[simp]: \"length (lineNext s x) = length s\"\nby (induct_tac s, auto)\n\nlemma length_circNext[simp]: \"length (circNext s) = length s\"\nby (simp add: circNext_def)\n\nlemma length_circNexts[simp]: \"ALL s. length (circNexts N s) = length s\"\nby (induct_tac N, auto)\n\n(* even *)\n\nlemma even_fill: \"even (fill n)\"\nby (auto simp add: allEven_def fill_def)\n\nlemma fill_div_times[simp]: \"fill n div 2 * 2 = fill n\"\napply (insert even_fill[of n])\napply (simp add: even_EX)\n(* apply (force) *)\ndone\n\nlemma lineNext_even[simp]: \"allEven (lineNext s nn)\"\napply (induct_tac s)\napply (auto simp add: allEven_def fill_def)\ndone\n\nlemma circNext_even[simp]: \"allEven (circNext s)\"\nby (simp add: circNext_def)\n\nlemma circNexts_even_lm: \"ALL s. allEven s --> allEven (circNexts N s)\"\nby (induct_tac N, auto)\n\nlemma circNexts_even[simp]: \"allEven s ==> allEven (circNexts N s)\"\nby (simp add: circNexts_even_lm)\n\n(* sum *)\n\nlemma circNexts_sum:\n   \"ALL s. circNexts (N1 + N2) s = circNexts N1 (circNexts N2 s)\"\nby (induct_tac N2, auto)\n\n(* ------------------------------------------------- *\n               lemmas on min and max\n * ------------------------------------------------- *)\n\n(* max and min *)\n\nlemma maxList_max[simp]: \"ALL n:set s. n <= maxList s\"\nby (induct_tac s, auto)\n\nlemma maxList_max_nth[simp]: \"ALL i. i<length s --> s!i <= maxList s\"\nby (induct_tac s, auto)\n\nlemma minList_min[simp]: \"ALL n:set s. minList s <= n\"\nby (induct_tac s, auto)\n\nlemma maxList_min_nth[simp]: \"ALL i. i<length s --> minList s <= s!i\"\nby (induct_tac s, auto)\n\n(* exist *)\n\nlemma maxList_exist: \"s ~= [] --> (maxList s : set s)\"\nby (induct_tac s, auto)\n\nlemma maxList_exist_nth: \"s ~= [] --> (EX i. i<length s & s!i = maxList s)\"\nby (induct_tac s, auto)\n\nlemma minList_exist: \"s ~= [] --> (minList s : set s)\"\nby (induct_tac s, auto)\n\nlemma minList_exist_nth: \"s ~= [] --> (EX i. i<length s & s!i = minList s)\"\nby (induct_tac s, auto)\n\n(* basic *)\n\nlemma minList_le_maxList: \"minList s <= maxList s\"\nby (induct_tac s, auto)\n\nlemma maxList_single[simp]: \"maxList[n] = n\"\nby (simp)\n\nlemma minList_single[simp]: \"minList[n] = n\"\nby (simp)\n\nlemma minList_le_forall: \n  \"t ~= [] --> ((m <= minList t) = (ALL n:(set t). m<=n))\"\nby (induct_tac t, auto)\n\nlemma minList_less_forall: \n  \"t ~= [] --> ((m < minList t) = (ALL n:(set t). m<n))\"\nby (induct_tac t, auto)\n\nlemma maxList_le_forall:\n  \"(maxList t <= m) = (ALL n:set t. n <= m)\"\nby (induct_tac t, auto)\n\nlemma maxList_less_forall:\n  \"t ~= [] --> (maxList t < m) = (ALL n:set t. n < m)\"\nby (induct_tac t, auto)\n\n(* fill *)\n\nlemma even_le_fill[simp]: \"even n ==> (fill m <= n) = (m <= n)\"\napply (simp add: fill_def)\napply (simp add: even_EX)\napply (elim conjE exE)\napply (auto)\napply (drule_tac x=\"ma\" in spec)\napply (auto)\ndone\n\nlemma even_fill_le: \"n <= m ==> (n <= fill m)\"\nby (simp add: fill_def)\n\nlemma even_fill_less[simp]: \"even n ==> (n < fill m) = (n < m)\"\napply (simp add: fill_def)\napply (simp add: even_EX)\napply (elim conjE exE)\napply (auto)\napply (drule_tac x=\"ma\" in spec)\napply (auto)\ndone\n\n(* even *)\n\nlemma allEven_maxList[simp]: \"(ALL s:set s. even s) ==> even (maxList s)\"\napply (case_tac \"s=[]\", simp)\napply (insert maxList_exist[of s], simp)\ndone\n\nlemma allEven_minList[simp]: \"(ALL s:set s. even s) ==> even (minList s)\"\napply (case_tac \"s=[]\", simp)\napply (insert minList_exist[of s], simp)\ndone\n\nlemma alleven_hd: \"allEven (n#s) = (even n & allEven(s))\"\nby (simp add: allEven_def)\n\nlemma allEven_div[simp]: \"[| s ~= [] ; allEven s |] ==> 2 * (hd s div 2) = hd s\"\napply (simp add: allEven_def even_EX)\n(*\napply (drule_tac x=\"hd s\" in bspec)\napply (auto)\n*)\ndone\n\nlemma allEven_hd: \"[| s ~= [] ; allEven s |] ==> even (hd s)\"\nby (auto simp add: allEven_def)\n\n(* stable *)\n\nlemma stable_min_max:\n  \"stableList s = (minList s = maxList s)\"\napply (simp add: stableList_def)\napply (rule)\n\n (* => *)\n apply (rule order_antisym)\n apply (simp add: minList_le_maxList)\n apply (simp only: maxList_le_forall)\n apply (force)\n\n (* <= *)\n apply (intro ballI)\n apply (erule order_antisymE)\n  apply (simp only: maxList_le_forall)\n  apply (drule_tac x=\"n\" in bspec)\n  apply (simp)\n  apply (rule order_antisym)\n  apply (simp_all)\ndone\n\nlemma stable_lineNext_lm:\n  \"(ALL n:set s. n=2*N) --> (lineNext s N = s)\"\napply (induct_tac s)\napply (simp)\napply (simp add: allEven_def)\napply (auto simp add: even_EX)\napply (simp add: fill_def)\napply (drule_tac x=\"hd list\" in bspec)\napply (simp_all add: fill_def)\ndone                          \n\nlemma stable_lineNext:\n  \"[| allEven s ; stableList s |] ==> lineNext s (hd s div 2) = s\"\napply (case_tac \"s=[]\", simp)\napply (insert stable_lineNext_lm[of s \"(minList s) div 2\"])\n(* modified for Isabelle 2016 *)\napply (drule mp)\napply (simp add: allEven_def stableList_def)\napply (simp add: allEven_def stableList_def)\napply (auto simp add: even_EX)\napply (rotate_tac 1)\napply (drule_tac x=\"hd s\" in bspec, simp)\napply (simp)\ndone\n\nlemma stable_circNext:\n  \"[| allEven s ; stableList s |] ==> circNext s = s\"\nby (simp add: circNext_def stable_lineNext)\n\nlemma stable_circNexts:\n  \"[| allEven s ; stableList s |] ==> circNexts N s = s\"\napply (induct_tac N)\nby (simp_all add: stable_circNext)\n\n(* howMany *)\n\nlemma howMany_zero:\n   \"(howMany m s = 0) = (ALL n:(set s). m ~= n)\"\nby (induct_tac s, auto)\n\nlemma less_minList_howMany_zero:\n   \"[| s ~= [] ; M < minList s |] ==> howMany M s = 0\"\napply (simp add: howMany_zero)\napply (simp add: minList_less_forall)\napply (auto)\ndone\n\n(* makeStableList *)\n\nlemma makeStableList_nil[simp]: \"(makeStableList l n = []) = (l=0)\"\nby (induct_tac l, auto)\n\nlemma tl_makeStableList_nil[simp]: \"(tl (makeStableList l n) = []) = (l <= Suc 0)\"\nby (induct_tac l, auto)\n\nlemma makeStableList_hd[simp]: \"0<l --> hd (makeStableList l n) = n\"\nby (induct_tac l, auto)\n\nlemma set_makeStableList[simp]: \"0<l --> set (makeStableList l n) = {n}\"\nby (induct_tac l, auto)\n\nlemma stableList_makeStableList_lm: \"stableList (makeStableList l n)\"\nby (induct_tac l, auto simp add: stableList_def)\n\nlemma stableList_makeStableList[simp]: \n  \"s = makeStableList l n ==> stableList s\"\nby (simp add: stableList_makeStableList_lm)\n\nlemma allEven_makeStableList[simp]: \"even n ==> allEven (makeStableList l n)\"\nby (induct_tac l, auto simp add: allEven_def)\n\nlemma makeStableList_hd_stableList_if:\n   \"ALL s. (length s = l & stableList s) --> s = makeStableList l (hd s)\"\napply (induct_tac l, auto)\napply (case_tac \"s=[]\", simp)\napply (auto simp add: not_nil_EX)\napply (case_tac \"t=[]\", simp)\napply (auto simp add: not_nil_EX stableList_def)\napply (drule_tac x=\"a # ta\" in spec)\napply (auto simp add: stableList_def)\ndone\n\nlemma makeStableList_hd_stableList_only_if:\n   \"ALL s. s=makeStableList l (hd s) --> length s = l\"\napply (induct_tac l)\napply (simp)\napply (intro allI impI)\napply (simp)\napply (case_tac \"s=[]\", simp)\napply (simp add: not_nil_EX)\napply (elim conjE exE)\napply (drule_tac x=\"t\" in spec)\napply (simp)\napply (drule mp)\napply (case_tac \"n=0\", simp)\napply (simp_all)\ndone\n\nlemma makeStableList_hd_stableList:\n   \"(s=makeStableList l (hd s)) = (length s = l & stableList s)\"\napply (rule)\napply (simp add: makeStableList_hd_stableList_only_if)\napply (simp add: makeStableList_hd_stableList_if)\ndone\n\n(* ------------------------------------------------- *\n             lemmas on line, min and max\n * ------------------------------------------------- *)\n\n(* line max <= *)\n\nlemma lineNext_max_le_lm:\n  \"ALL n. \n   (s ~= [] & allEven s & even M & (ALL n:set s. n <= M) & 2*nn <= M & \n    n:set (lineNext s nn))\n    --> n <= M\"\napply (induct_tac s)\napply (simp)\n\napply (intro allI ballI impI)\napply (simp)\napply (case_tac \"list = []\")\n apply (simp)\n apply (simp add: even_EX allEven_def)\n apply (force)\n\n apply (simp add: allEven_def even_EX)\n apply (elim disjE conjE exE)\n  apply (rotate_tac 1)\n  apply (drule_tac x=\"hd list\" in bspec, simp)\n  apply (drule_tac x=\"hd list\" in bspec, simp)\n  apply (auto)\ndone\n\nlemma lineNext_max_le:\n   \"[| s ~= [] ; allEven s ; even M ; ALL n:set s. n <= M ; 2*nn <= M ;\n       n:set (lineNext s nn) |]\n    ==> n <= M\"\napply (insert lineNext_max_le_lm[of s M nn])\napply (drule_tac x=\"n\" in spec)\napply (drule mp)\napply (simp_all)\ndone\n\nlemma lineNext_maxList_le:\n   \"[| s ~= [] ; allEven s ; 2*nn <= maxList s ; n:set (lineNext s nn) |]\n    ==> n <= maxList s\"\napply (rule lineNext_max_le)\napply (simp_all add: allEven_def)\ndone\n\n(* line min <= *)\n\nlemma lineNext_min_le_lm:\n  \"ALL n. \n   (s ~= [] & allEven s & even M & (ALL n:set s. M <= n) & M <= 2*nn &\n    n:set (lineNext s nn)) \n   --> M <= n\"\napply (induct_tac s)\napply (simp)\n\napply (intro allI ballI impI)\napply (simp)\napply (case_tac \"list = []\")\n apply (simp)\n apply (simp add: even_EX allEven_def)\n apply (elim conjE exE)\n apply (simp add: fill_def)\n\n apply (simp add: allEven_def even_EX)\n apply (elim disjE conjE exE)\n  apply (rotate_tac 1)\n  apply (drule_tac x=\"hd list\" in bspec, simp)\n  apply (drule_tac x=\"hd list\" in bspec, simp)\n  apply (auto)\n  apply (simp add: fill_def)\ndone\n\nlemma lineNext_min_le:\n   \"[| s ~= [] ; allEven s ; even M ; ALL n:set s. M <= n ; M <= 2*nn ; \n       n:set (lineNext s nn) |]\n    ==> M <= n\"\napply (insert lineNext_min_le_lm[of s M nn])\napply (drule_tac x=\"n\" in spec)\napply (drule mp)\napply (simp_all)\ndone\n\nlemma lineNext_minList_le:\n   \"[| s ~= [] ; allEven s ; minList s <= 2*nn ;\n       n:set (lineNext s nn) |]\n    ==> minList s <= n\"\napply (rule lineNext_min_le)\napply (simp_all add: allEven_def)\ndone\n\n(* line min < *)\n\nlemma lineNext_min_less_lm:\n  \"ALL i. \n   (s ~= [] & allEven s & even M & (ALL n:set s. M <= n) & M <= 2*nn &\n    Suc i < length s & s!i = M & M < s!(Suc i))\n    --> M < (lineNext s nn) ! i\"\napply (induct_tac s)\napply (simp)\napply (intro ballI allI impI)\napply (elim conjE exE)\napply (simp)\napply (insert nat_zero_or_Suc)\napply (rotate_tac -1)\napply (drule_tac x=\"i\" in spec)\napply (elim disjE conjE exE)\napply (simp add: nth_hd)\napply (simp add: allEven_def even_EX)\napply (elim conjE exE)\napply (simp)\napply (rotate_tac -2)\napply (drule_tac x=\"hd list\" in bspec, simp)\napply (elim conjE exE)\napply (simp)\n\napply (auto simp add: allEven_def)\ndone\n\nlemma lineNext_min_less:\n  \"[| s ~= [] ; allEven s ; even M ; ALL n:set s. M <= n ; M <= 2*nn ;\n      Suc i < length s ; s!i = M ; M < s!(Suc i) |]\n    ==> M < (lineNext s nn) ! i\"\nby (insert lineNext_min_less_lm[of s M nn], simp)\n\nlemma lineNext_minList_less:\n  \"[| s ~= [] ; allEven s ; minList s <= 2*nn ;\n      Suc i < length s ; s!i = minList s ; minList s < s!(Suc i) |]\n    ==> minList s < (lineNext s nn) ! i\"\napply (rule lineNext_min_less)\napply (simp_all add: allEven_def)\ndone\n\n(* last *)\n\nlemma lineNext_min_less_last_sublm:\n  \"s ~= [] & last s < a --> last s < last (lineNext s a)\"\nby (induct_tac s, auto simp add: fill_def)\n\nlemma lineNext_min_less_last_lm:\n  \"(s ~= [] & allEven s & (ALL n:set s. M <= n) \n    & M = last s & M < 2*nn )\n        --> last s < last (lineNext s nn)\"\napply (induct_tac s)\napply (simp_all add: lineNext_min_less_last_sublm)\napply (intro conjI impI)\napply (simp_all)\napply (simp add: allEven_def even_EX)\napply (elim conjE exE)\napply (simp add: fill_def)\napply (auto simp add: allEven_def)\ndone\n\nlemma lineNext_min_less_last:\n  \"[| s ~= [] ; allEven s ; ALL n:set s. M <= n ;\n      last s = M ; M < 2*nn |]\n   ==> M < last (lineNext s nn)\"\nby (insert lineNext_min_less_last_lm[of s M nn], simp)\n\nlemma lineNext_minList_less_last:\n  \"[| s ~= [] ; allEven s ; last s = minList s ; minList s < 2*nn |]\n   ==> minList s < last (lineNext s nn)\"\nby (simp add: lineNext_min_less_last)\n\n(* other less *)\n\nlemma lineNext_min_other_less_lm:\n  \"ALL i. \n   (s ~= [] & allEven s & even M & (ALL n:set s. M <= n) & M <= 2*nn &\n    i < length s & M < s!i)\n    --> M < (lineNext s nn) ! i\"\napply (induct_tac s)\napply (simp_all)\napply (intro conjI impI)\napply (simp add: fill_def)\napply (simp add: allEven_def even_EX)\napply (elim conjE exE)\napply (simp)\n\napply (intro allI impI)\napply (simp)\napply (insert nat_zero_or_Suc)\napply (rotate_tac -1)\napply (drule_tac x=\"i\" in spec)\napply (elim disjE conjE exE)\napply (simp)\napply (simp add: allEven_def even_EX)\napply (elim conjE exE)\napply (rotate_tac -3)\napply (drule_tac x=\"hd list\" in bspec, simp)\napply (drule_tac x=\"hd list\" in bspec, simp)\napply (elim conjE exE)\napply (simp)\n\napply (simp add: allEven_def)\ndone\n\nlemma lineNext_min_other_less:\n  \"[| s ~= [] ; allEven s ; even M ; ALL n:set s. M <= n ; M <= 2*nn ;\n      i < length s ; M < s!i |]\n   ==> M < (lineNext s nn) ! i\"\nby (simp add: lineNext_min_other_less_lm)\n\nlemma lineNext_minList_other_less:\n  \"[| s ~= [] ; allEven s ; minList s <= 2*nn ;\n      i < length s ; minList s < s!i |]\n   ==> minList s < (lineNext s nn) ! i\"\napply (rule lineNext_min_other_less)\napply (simp_all add: allEven_def)\ndone\n\n(* ------------------------------------------------- *\n              lemmas on circ, min and max\n * ------------------------------------------------- *)\n\n(* max le *)\n\nlemma circNext_maxList_le:\n  \"[| s ~= [] ; allEven s ; n:set (circNext s) |]\n   ==> n <= maxList s\"\napply (simp add: circNext_def)\napply (rule lineNext_maxList_le[of _ \"(hd s div 2)\"])\napply (simp_all)\ndone\n\nlemma maxList_circNext_le:\n  \"[| s ~= [] ; allEven s |]\n   ==> maxList (circNext s) <= maxList s\"\napply (simp add: maxList_le_forall)\napply (auto simp add: circNext_maxList_le)\ndone\n\n(* min le *)\n\nlemma circNext_minList_le:\n  \"[| s ~= [] ; allEven s ; n:set (circNext s) |]\n   ==> minList s <= n\"\napply (simp add: circNext_def)\napply (rule lineNext_minList_le[of _ \"(hd s div 2)\"])\napply (simp_all)\ndone\n\nlemma minList_circNext_le:\n  \"[| s ~= [] ; allEven s |]\n   ==> minList s <= minList (circNext s)\"\napply (simp add: minList_le_forall)\napply (auto simp add: circNext_minList_le)\ndone\n\n(* min less *)\n\nlemma circNext_minList_less:\n  \"[| s ~= [] ; allEven s ; \n      i<length s ; s!i=minList s ; \n      (Suc i = length s & minList s < hd s) | \n      (Suc i < length s & minList s < s ! Suc i) |]\n   ==> minList s < (circNext s)!i\"\napply (simp add: circNext_def)\napply (case_tac \"Suc i < length s\")\napply (insert lineNext_minList_less[of s \"(hd s div 2)\" i])\napply (simp add: allEven_def even_EX)\n\napply (case_tac \"Suc i = length s\")\napply (insert lineNext_minList_less_last[of s \"(hd s div 2)\"])\napply (simp add: nth_last)\n\napply (auto)\ndone\n\nlemma circNext_minList_other_less:\n  \"[| s ~= [] ; allEven s ; i<length s ; minList s < s!i |]\n   ==> minList s < (circNext s)!i\"\napply (simp add: circNext_def)\napply (rule lineNext_minList_other_less)\napply (auto)\ndone\n\n(* ------------------------------------------------- *\n            lemmas on circNexts, min, and max\n * ------------------------------------------------- *)\n\nlemma maxList_circNexts_le_lm:\n  \"ALL s. (s ~= [] & allEven s)\n    --> maxList (circNexts N s) <= maxList s\"\napply (induct_tac N)\napply (auto)\napply (drule_tac x=\"circNext s\" in spec)\napply (simp)\napply (rule order_trans)\napply (simp)\napply (simp add: maxList_circNext_le)\ndone\n\nlemma maxList_circNexts_le:\n  \"[| s ~= [] ; allEven s |]\n   ==> maxList (circNexts N s) <= maxList s\"\nby (simp add: maxList_circNexts_le_lm)\n\nlemma minList_circNexts_le_lm:\n  \"ALL s. (s ~= [] & allEven s)\n    --> minList s <= minList (circNexts N s)\"\napply (induct_tac N)\napply (auto)\napply (drule_tac x=\"circNext s\" in spec)\napply (simp)\napply (rule order_trans)\napply (simp_all)\napply (simp add: minList_circNext_le)\ndone\n\nlemma minList_circNexts_le:\n  \"[| s ~= [] ; allEven s |]\n   ==> minList s <= minList (circNexts N s)\"\nby (simp add: minList_circNexts_le_lm)\n\n(* ----------------------------------------------------------- *\n           to get the assumption of circ_minList_less\n * ----------------------------------------------------------- *)\n\ndeclare minList.simps [simp del]\n\nlemma unstable_exists_diff_one_lm:\n  \"ALL j. (j<length s & minList s < s!j) -->\n   (EX i. i<length s & s ! i = minList s & \n         ((Suc i = length s & minList s < hd s) | \n          (Suc i < length s & minList s < s ! Suc i)))\"\napply (induct_tac s)\napply (simp)\n\napply (intro allI impI)\napply (simp add: less_Suc)\napply (elim disjE conjE exE)\n\n (* 1 *)\n apply (subgoal_tac \"minList (a # list) = minList list\")      (* sub1 *)\n  apply (simp)\n  apply (case_tac \"EX j. j<length list & minList list < list ! j\")\n   apply (simp)\n   apply (elim exE)\n   apply (rule_tac x=\"Suc i\" in exI)\n   apply (simp)\n   apply (case_tac \"list=[]\")\n    apply (force)\n    apply (force)\n\n   (* ~ EX j. j<length list & minList list < list ! j *)\n\n   apply (rule_tac x=\"length list \" in exI)\n   apply (simp)\n   apply (case_tac \"list=[]\", simp)\n   apply (rule conjI)\n    apply (rule disjI2)\n    apply (rule_tac x=\"length list - 1\" in exI)\n    apply (force)\n    apply (subgoal_tac \"EX i. length list = Suc i\")   (* sub2 *)\n    apply (elim exE)\n     apply (simp)\n     apply (drule_tac x=\"i\" in spec)\n     apply (simp)\n\n     apply (simp add: not_less)           (* <--- Isabelle 2008 *)\n     (* apply (fold le_def)                  <--- Isabelle 2005 *)\n     apply (rule le_antisym)              (* <--- Isabelle 2009-1 *)\n     (* apply (rule le_anti_sym)             <--- Isabelle 2009 *)\n     apply (simp)\n     apply (simp)\n   (* sub2 *)\n    apply (rule_tac x=\"length list - 1\" in exI)\n    apply (simp)\n (* sub1 *)\n  apply (case_tac \"list=[]\")\n  apply (simp add: minList.simps)\n  apply (simp add: minList.simps)\n  apply (force)\n\n (* 2 *)\n apply (case_tac \"minList list < a\")\n  apply (subgoal_tac \"minList (a # list) = minList list\")      (* sub3 *)\n   apply (drule mp, force)\n   apply (elim conjE exE)\n   apply (rule_tac x=\"Suc i\" in exI)\n   apply (force)\n\n (* sub3 *)\n  apply (case_tac \"list=[]\")\n  apply (simp add: minList.simps)\n  apply (simp add: minList.simps)\n\n apply (case_tac \"minList list = a\")\n  apply (subgoal_tac \"minList (a # list) = minList list\")      (* sub4 *)\n   apply (drule mp, force)\n   apply (elim disjE conjE exE)\n    apply (rule_tac x=\"0\" in exI)\n    apply (case_tac \"list=[]\")\n    apply (simp)\n    apply (simp add: nth_hd)\n\n    apply (rule_tac x=\"Suc i\" in exI)\n    apply (simp)\n\n (* sub4 *)\n  apply (case_tac \"list=[]\")\n  apply (simp add: minList.simps)\n  apply (simp add: minList.simps)\n\n apply (case_tac \"a < minList list\")\n  apply (subgoal_tac \"minList (a # list) = a\")      (* sub5 *)\n   apply (rule_tac x=\"0\" in exI)\n   apply (case_tac \"list=[]\")\n   apply (simp)\n   apply (simp add: nth_hd)\n   apply (rotate_tac -3)\n   apply (erule contrapos_pp)\n   apply (simp add: not_less)           (* <--- Isabelle 2008 *)\n (* apply (fold le_def)                  <--- Isabelle 2005 *)\n   apply (subgoal_tac \"minList list <= hd list\")\n   apply (rule order_trans)\n   apply (simp (no_asm_simp))\n   apply (simp)\n   apply (simp)\n\n (* sub5 *)\n  apply (case_tac \"list=[]\")\n  apply (simp add: minList.simps)\n  apply (simp add: minList.simps)\n\napply (simp)\ndone\n\ndeclare minList.simps [simp add]\n\nlemma unstable_exists_diff_one:\n  \"[| j<length s ; minList s < s!j |] ==>\n   EX i. i<length s & s ! i = minList s & \n         ((Suc i = length s & minList s < hd s) | \n          (Suc i < length s & minList s < s ! Suc i))\"\napply (insert unstable_exists_diff_one_lm[of s])\napply (drule_tac x=\"j\" in spec)\napply (simp)\ndone\n\n(* --- to increase the minList --- *)\n\nlemma unstable_circNext_minList_less:\n  \"[| s ~= [] ; allEven s ; j < length s & minList s < s!j |]\n   ==> EX i. i < length s & s!i=minList s & minList s < (circNext s)!i\"\napply (insert unstable_exists_diff_one[of j s])\napply (simp)\napply (elim conjE exE)\napply (rule_tac x=\"i\" in exI)\napply (simp add: circNext_minList_less)\ndone\n\n(* ----------------------------------------------------------- *\n                to decrease howMany (minList s)\n * ----------------------------------------------------------- *)\n\nlemma Suc_length_list_EX:\n \"(Suc (length s) = length t) = (EX b u. t = b#u & length s = length u)\"\napply (induct_tac t)\napply (auto)\ndone\n\n(*** howMany <= ***)\n\nlemma howMany_le_lm:\n  \"ALL s t j. (length s = length t &\n              (ALL i. (i<length t & M ~= s!i) --> M ~= t!i))\n   --> howMany M t <= howMany M s\"\napply (rule)\napply (induct_tac s)\napply (simp)\napply (intro allI impI)\napply (simp add: Suc_length_list_EX)\napply (elim conjE exE)\napply (drule_tac x=\"u\" in spec)\napply (auto)\ndone\n\nlemma howMany_le:\n  \"[| length s = length t ;\n      !!i. [| i<length t ; M ~= s!i |] ==> M ~= t!i |]\n   ==> howMany M t <= howMany M s\"\nby (simp add: howMany_le_lm)\n\n(*** howMany < ***)\n\nlemma howMany_less_lm:\n  \"ALL s t j. (length s = length t &\n              (ALL i. (i<length t & M ~= s!i) --> M ~= t!i) &\n               j < length t & s!j=M & M<t!j)\n   --> howMany M t < howMany M s\"\napply (rule)\napply (induct_tac s)\napply (simp)\napply (intro allI impI)\n apply (simp add: Suc_length_list_EX)\n apply (elim conjE exE)\n apply (intro conjI impI)\n\n (* new hd s = M *)\n  apply (case_tac \"j=0\")\n   apply (simp add: less_Suc_eq_le)\n   apply (rule howMany_le)\n   apply (simp)\n   apply (drule_tac x=\"Suc i\" in spec)\n   apply (simp)\n \n  (* j~=0 *)\n   apply (drule_tac x=\"u\" in spec)\n   apply (drule mp)\n    apply (simp)\n    apply (intro conjI allI impI)\n     apply (drule_tac x=\"Suc i\" in spec)\n     apply (simp)\n\n     apply (simp add: zero_less_EX)\n     apply (elim exE)\n     apply (rule_tac x=\"m\" in exI)\n     apply (simp)\n    apply (force)\n\n (* new hd s ~= M *)\n apply (simp add: less_Suc)\n apply (elim disjE conjE exE, simp)\n apply (drule_tac x=\"u\" in spec)\n\n apply (drule mp)\n  apply (simp)\n   apply (intro conjI allI impI)\n   apply (drule_tac x=\"Suc i\" in spec)\n   apply (simp)\n\n   apply (rule_tac x=\"m\" in exI)\n   apply (simp)\n  apply (force)\ndone\n\nlemma howMany_less:\n  \"[| length s = length t ;\n      ALL i. (i<length t & M ~= s!i) --> M ~= t!i ;\n      EX j. j < length t & s!j=M & M<t!j |]\n   ==> howMany M t < howMany M s\"\napply (insert howMany_less_lm[of M])\napply (drule_tac x=\"s\" in spec)\napply (drule_tac x=\"t\" in spec)\napply (erule exE)\napply (rotate_tac -2)\napply (drule_tac x=\"j\" in spec)\napply (simp)\ndone\n\n(*** howMany circNext ***)\n\nlemma howMany_circNext_less:\n  \"[| s ~= [] ; allEven s ; j < length s ; minList s < s!j |]\n   ==> howMany (minList s) (circNext s) < howMany (minList s) s\"\napply (rule howMany_less)\napply (simp_all)\napply (intro allI impI)\n apply (elim conjE)\n apply (subgoal_tac \"minList s < circNext s ! i\", simp)\n apply (rule circNext_minList_other_less)\n apply (simp_all)\n apply (simp add: order_less_le)\n apply (rule unstable_circNext_minList_less[of s j])\n apply (simp_all)\ndone\n\n(* ----------------------------------------------------------- *\n                     to increase minList\n * ----------------------------------------------------------- *)\n\nlemma minList_circNext_less_lm:\n  \"ALL k s. (s ~= [] & allEven s & i < length s & minList s < s!i &\n           howMany (minList s) s <= k)\n   --> (EX N. minList s < minList (circNexts N s))\"\napply (rule)\napply (induct_tac k)\napply (intro allI impI)\n\n(* k=0 *)\n apply (rule_tac x=\"0\" in exI)\n apply (simp add: howMany_zero)\n apply (elim conjE)\n apply (drule_tac x=\"minList s\" in bspec)\n apply (simp_all add: minList_exist)\n\n(* step *)\napply (intro allI impI)\napply (drule_tac x=\"circNext s\" in spec)\napply (simp)\n\n apply (case_tac \"minList (circNext s) = minList s \")\n apply (drule mp)\n  apply (simp)\n  apply (elim conjE exE)\n  apply (simp add: circNext_minList_other_less)\n  apply (subgoal_tac \"howMany (minList s) (circNext s) < howMany (minList s) s\")\n   apply (force)\n  apply (simp add: howMany_circNext_less)\n apply (simp)\n apply (elim conjE exE)\n apply (rule_tac x=\"Suc N\" in exI)\n apply (simp)\n\n (* minList (circNext s) ~= minList s *)\napply (rule_tac x=\"Suc 0\" in exI)\napply (simp add: order_less_le minList_circNext_le)\ndone\n\nlemma minList_circNext_less:\n  \"[| s ~= [] ; allEven s ; i < length s ; minList s < s!i |]\n   ==> (EX N. minList s < minList (circNexts N s))\"\napply (insert minList_circNext_less_lm[of i])\napply (erule exchange_forall_orderE)\napply (drule_tac x=\"s\" in spec)\napply (drule_tac x=\"howMany (minList s) s\" in spec)\napply (simp)\ndone\n\n(* ----------------------------------------------------------- *\n                    eventually stable\n * ----------------------------------------------------------- *)\n\nlemma circNexts_eventually_stable_lm:\n  \"ALL k s i.\n   (s ~= [] & allEven s & i < length s & minList s < s!i &\n    maxList s <= minList s + k)\n   --> (EX N. stableList(circNexts N s))\"\napply (simp add: stable_min_max)\napply (rule)\napply (induct_tac k)\n\n(* base *)\n apply (intro allI impI)\n apply (rule_tac x=\"0\" in exI)\n apply (rule order_antisym)\n apply (simp add: minList_le_maxList)\n apply (force)\n\n(* step *)\n apply (intro allI impI)\n apply (subgoal_tac \"(EX N. minList s < minList (circNexts N s))\")\n apply (elim exE conjE)\n apply (case_tac \"N=0\", simp)\n apply (case_tac \"EX i. i < length s & minList (circNexts N s) < circNexts N s ! i\")\n  apply (elim exE conjE)\n  apply (drule_tac x=\"circNexts N s\" in spec)\n  apply (simp)\n\n  apply (drule mp)\n   apply (rule_tac x=\"ia\" in exI)\n   apply (simp)\n   apply (rule order_trans)\n    apply (rule maxList_circNexts_le)\n    apply (simp_all)\n  apply (erule exE)\n  apply (rule_tac x=\"Na + N\" in exI)\n  apply (simp add: circNexts_sum)\n\n (* ~ EX i. i < length s & minList (circNexts N s) < circNexts N s ! i *)\n apply (simp add: not_less)           (* <--- Isabelle 2008 *)\n(* apply (fold le_def)                  <--- Isabelle 2005 *)\n apply (rule_tac x=\"N\" in exI)\n apply (rule order_antisym)\n  apply (simp add: minList_le_maxList)\n  apply (simp add: maxList_le_forall)\n  apply (intro ballI impI)\n  apply (simp add: in_set_nth)\n  apply (elim conjE exE)\n  apply (rotate_tac -3)\n  apply (drule_tac x=\"ia\" in spec)\n  apply (simp)\n\napply (elim conjE exE)\napply (simp add: minList_circNext_less)\ndone\n\nlemma circNexts_eventually_stable:\n  \"[| s ~= [] ; allEven s |] ==> EX N. stableList(circNexts N s)\"\n\napply (case_tac \"ALL i. i < length s --> minList s = s!i\")\n apply (rule_tac x=\"0\" in exI)\n apply (simp add: stable_min_max)\n apply (rule order_antisym)\n  apply (simp add: minList_le_maxList)\n  apply (simp add: maxList_le_forall)\n  apply (intro ballI impI)\n  apply (simp add: in_set_nth)\n  apply (force)\n\n (* ~ (ALL i. i < length s --> minList s = s!i) *)\napply (simp)\napply (elim conjE exE)\napply (insert circNexts_eventually_stable_lm)\napply (erule exchange_forall_orderE)\napply (drule_tac x=\"s\" in spec)\napply (drule_tac x=\"maxList s - minList s\" in spec)\napply (drule_tac x=\"i\" in spec)\napply (simp add: minList_le_maxList)\napply (simp add: order_less_le)\ndone\n\nend\n", "meta": {"author": "yoshinao-isobe", "repo": "CSP-Prover", "sha": "806fbe330d7e23279675a2eb351e398cb8a6e0a8", "save_path": "github-repos/isabelle/yoshinao-isobe-CSP-Prover", "path": "github-repos/isabelle/yoshinao-isobe-CSP-Prover/CSP-Prover-806fbe330d7e23279675a2eb351e398cb8a6e0a8/UCD/UCD_data1.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467643431002, "lm_q2_score": 0.8080672204860316, "lm_q1q2_score": 0.7104096822620173}}
{"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.*)\n  theory TIP_prop_83\nimports \"../../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) z = nil2\"\n| \"zip (cons2 z2 x2) (nil2) = nil2\"\n| \"zip (cons2 z2 x2) (cons2 x3 x4) =\n     cons2 (pair2 z2 x3) (zip x2 x4)\"\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 take :: \"Nat => 'a list => 'a list\" where\n\"take (Z) z = nil2\"\n| \"take (S z2) (nil2) = nil2\"\n| \"take (S z2) (cons2 x2 x3) = cons2 x2 (take z2 x3)\"\n\nfun len :: \"'a list => Nat\" where\n\"len (nil2) = Z\"\n| \"len (cons2 z xs) = S (len xs)\"\n\nfun drop :: \"Nat => 'a list => 'a list\" where\n\"drop (Z) z = z\"\n| \"drop (S z2) (nil2) = nil2\"\n| \"drop (S z2) (cons2 x2 x3) = drop z2 x3\"\n\ntheorem property0 :\n  \"((zip (x xs ys) zs) =\n      (x (zip xs (take (len xs) zs)) (zip ys (drop (len xs) zs))))\"\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/Isaplanner/Isaplanner/TIP_prop_83.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467580102418, "lm_q2_score": 0.8080672158638528, "lm_q1q2_score": 0.7104096730810684}}
{"text": "section \"Fixed Points\"\n\ntheory fixedpoints\n  imports Main\nbegin\n\n\nlemma exists_maximal_element:\n  fixes S :: \"'a::complete_lattice set\"\n  assumes \"finite S\"\n    and \"S \\<noteq> {}\"\n  shows \"\\<exists>max. max \\<in> S \\<and> (\\<forall>v\\<in>S. \\<not>(v>max))\"\n  using \\<open>finite S\\<close> \\<open>S \\<noteq> {}\\<close> proof (induct rule: finite_induct)\n  case empty\n  then show ?case by simp\nnext\n  case (insert x F)\n  show ?case\n  proof (cases \"F = {}\")\n    case True\n    then show ?thesis by simp\n  next\n    case False\n    from this\n    obtain F_max where \"F_max \\<in> F\" and \"\\<forall>v\\<in>F. \\<not>(v > F_max)\"\n      using insert.hyps(3) by blast\n\n    show ?thesis\n    proof (cases \"x > F_max\")\n      case True\n      then show ?thesis\n        by (metis \\<open>\\<forall>v\\<in>F. \\<not> F_max < v\\<close> insert_iff le_less_trans less_le) \n\n    next\n      case False\n      then show ?thesis\n        using \\<open>F_max \\<in> F\\<close> \\<open>\\<forall>v\\<in>F. \\<not> F_max < v\\<close> by blast \n    qed\n\n  qed\nqed\n\n\nlemma exists_fixpoint:\n  fixes s :: \"nat \\<Rightarrow> 'a::{complete_lattice}\"\n  assumes incr_seq: \"\\<And>i j. i\\<le>j \\<Longrightarrow> s i \\<le> s j\"\n    and finite_range: \"finite (range s)\"\n  shows \"\\<exists>i. \\<forall>j\\<ge>i. s j = s i\"\n\nproof (rule ccontr)\n  assume \"\\<nexists>i. \\<forall>j\\<ge>i. s j = s i\"\n  then have ex_bigger: \"\\<exists>j\\<ge>i. s j > s i\" for i \n    using incr_seq by fastforce\n\n  from \\<open>finite (range s)\\<close>\n  obtain maxVal where \"maxVal \\<in> range s\" and \"\\<forall>v\\<in>range s. \\<not>(v > maxVal)\"\n    by (metis exists_maximal_element finite.emptyI image_is_empty infinite_UNIV_nat)\n\n  from ex_bigger\n  obtain maxVal' where \"maxVal' \\<in> range s\" and \"maxVal' > maxVal\"\n    by (metis \\<open>maxVal \\<in> range s\\<close> image_iff rangeI)\n\n  then show False\n    using \\<open>\\<forall>v\\<in>range s. \\<not> maxVal < v\\<close> by blast\nqed\n\n\n\n\nlemma exists_fix1:\n  fixes f :: \"('a \\<Rightarrow> bool) \\<Rightarrow> 'a \\<Rightarrow> bool\"\n  assumes \"mono f\"\n  shows \"\\<exists>i. (f ^^ Suc i) bot x = (f ^^ i) bot x\"\n  by (metis (mono_tags, lifting) assms funpow_decreasing le_Suc_eq rev_predicate1D)\n\nlemma  exists_fix2:\n  fixes f :: \"('a \\<Rightarrow> bool) \\<Rightarrow> 'a \\<Rightarrow> bool\"\n  assumes \"mono f\"\n  shows \"\\<exists>i. \\<forall>j\\<ge>i. (f ^^ j) bot x = (f ^^ i) bot x\"\n  by (metis (mono_tags, hide_lams) assms funpow_decreasing rev_predicate1D)\n\nlemma iterate_to_lfp:\n  fixes f :: \"('a \\<Rightarrow> bool) \\<Rightarrow> 'a \\<Rightarrow> bool\"\n  assumes \"mono f\"\n    and \"(f ^^ i) bot x\"\n  shows \"lfp f x\"\n  by (metis (mono_tags, lifting) Kleene_iter_lpfp assms(1) assms(2) lfp_greatest rev_predicate1D)\n\n\\<comment> \\<open>the function f only depends on finitely many values\\<close>\ndefinition finite_branching :: \"(('a \\<Rightarrow> bool) \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> bool\" where\n\"finite_branching f \\<equiv> \\<forall>f' x. f f' x \\<longrightarrow> (\\<exists>S. finite S \\<and> (\\<forall>f''. (\\<forall>x\\<in>S. f'' x = f' x) \\<longrightarrow> f f'' x))\"\n\n\nlemma \n  fixes f :: \"('a \\<Rightarrow> bool) \\<Rightarrow> 'a \\<Rightarrow> bool\"\n  assumes \"(f ^^ i) bot x\"\nand \"mono f\"\nshows \"f ((f ^^ i) bot) x\"\n  by (metis (mono_tags, lifting) assms(1) assms(2) bot.extremum funpow_swap1 mono_def mono_pow rev_predicate1D)\n\n\n\n\n\ndatatype check_result = check_fail | check_ok nat | check_ok_infinite\n\ndefinition [simp]: \"less_eq_check_result' x y \\<equiv> case x of \n   check_fail \\<Rightarrow> True\n | check_ok n \\<Rightarrow> (case y of check_fail \\<Rightarrow> False | check_ok m \\<Rightarrow> n \\<le> m | check_ok_infinite \\<Rightarrow> True)\n | check_ok_infinite \\<Rightarrow> y = check_ok_infinite\"\n\ndefinition [simp]: \"less_check_result' x y \\<equiv> case x of \n   check_fail \\<Rightarrow> y \\<noteq> check_fail\n | check_ok n \\<Rightarrow> (case y of check_fail \\<Rightarrow> False | check_ok m \\<Rightarrow> n < m | check_ok_infinite \\<Rightarrow> True)\n | check_ok_infinite \\<Rightarrow> False\"\n\ndefinition \"is_ok check \\<equiv> check \\<noteq> check_fail\"\n\n\ninstantiation check_result :: linorder begin\ndefinition \"less_eq_check_result \\<equiv> less_eq_check_result'\"\ndefinition \"less_check_result \\<equiv> less_check_result'\"\n\n\ninstance \n  by (standard, auto simp add: less_eq_check_result_def less_check_result_def split: check_result.splits)\nend\n\nlemma check_ok0_less: \"x < check_ok 0 \\<longleftrightarrow> x = check_fail\"\n  by (auto simp add: less_check_result_def split: check_result.splits)\n\n\ninstance check_result :: wellorder\nproof\n\n\n  show \"P a\"\n    if ind: \"(\\<And>x. (\\<And>y. y < x \\<Longrightarrow> P y) \\<Longrightarrow> P x)\"\n    for P and a::check_result\n  proof -\n    have \"P check_fail\"\n    proof (rule ind)\n      show \"\\<And>y. y < check_fail \\<Longrightarrow> P y\"\n        by (simp add: leD less_eq_check_result_def)\n    qed\n\n    moreover have \"P (check_ok n)\" for n\n    proof (induct n rule: less_induct)\n      case (less m)\n      show \"P (check_ok m)\"\n      proof (rule ind)\n        show \"P y\" if \"y < check_ok m\" for y\n        proof (cases y)\n          case check_fail\n          then show ?thesis\n            using \\<open>P check_fail\\<close> by blast \n        next\n          case (check_ok i)\n          then show ?thesis\n            using less.hyps less_check_result_def that by auto \n        next\n          case check_ok_infinite\n          then show ?thesis\n            using less_check_result_def that by auto \n        qed\n      qed\n    qed\n\n    moreover have \"P check_ok_infinite\"\n    proof (rule ind)\n      show \"P y\" if \"y < check_ok_infinite\" for y\n      proof (cases y)\n        case check_fail\n        then show ?thesis\n          using \\<open>P check_fail\\<close> by blast \n      next\n        case (check_ok i)\n        then show ?thesis\n          by (simp add: \\<open>\\<And>n. P (check_ok n)\\<close>)\n      next\n        case check_ok_infinite\n        then show ?thesis\n          using less_check_result_def that by auto \n      qed\n    qed\n\n    ultimately\n    show \"P a\"\n      by (cases a, auto)\n  qed\nqed\n\n\n\n\n\n\nlemma \"(LEAST a::'a::wellorder. a = x \\<or> a = y) \\<le> x\"\n  by (simp add: Least_le)\n\n\nlemma least_check_fail: \"A \\<noteq> {} \\<Longrightarrow> (LEAST x::check_result. x \\<in> A) = check_fail \\<longleftrightarrow> (check_fail \\<in>A)\"\n  apply auto\n  using LeastI apply force\n  by (meson Least_le check_ok0_less le_less_trans)\n\n\nlemma least_check_result: \"A \\<noteq> {} \\<Longrightarrow> (LEAST x::check_result. x \\<in> A) = y \\<longleftrightarrow> (y\\<in>A \\<and> (\\<forall>y'\\<in>A. y \\<le> y'))\"\n  apply auto\n  apply (meson LeastI)\n  apply (simp add: Least_le)\n  by (metis (full_types) LeastI less_le not_less_Least)\n\nlemma least_check_result': \"x\\<in>A \\<Longrightarrow> (LEAST x::check_result. x \\<in> A) = y \\<longleftrightarrow> (y\\<in>A \\<and> (\\<forall>y'\\<in>A. y \\<le> y'))\"\n  by (rule least_check_result, auto)\n\nlemma least_check_result_less_eq: \"P a \\<Longrightarrow> (z \\<le> (LEAST x::check_result. P x)) \\<longleftrightarrow> (\\<forall>x. P x \\<longrightarrow> z \\<le> x)\"\n  by (meson LeastI Least_le order_trans)\n\nlemma least_check_result_not_less_eq: \"P a \\<Longrightarrow> (\\<not> (z \\<le> (LEAST x::check_result. P x))) \\<longleftrightarrow> (\\<exists>x. P x \\<and> z > x)\"\n  by (simp add: least_check_result_less_eq not_le)\n  \n\n\nlemma check_ok_infinite_max: \"z \\<le> check_ok_infinite\"\n  by (simp add: leI less_check_result_def)\n\n\nlemma GreatestI:\n  assumes example: \"\\<exists>m. P m \\<and> Q m \\<and> (\\<forall>x. P x \\<longrightarrow> x \\<le> m)\"\n  shows \"Q (Greatest P)\"\n  apply (unfold Greatest_def)\n  apply (rule the1I2)\n  using antisym example apply blast\n  using dual_order.antisym example by blast\n\n\n\nlemma GreatestI_nat2:\n  assumes example: \"\\<exists>m::nat. P m\"\n    and bound: \"\\<forall>m. P m \\<longrightarrow> m \\<le> bound\"\n    and impl: \"\\<forall>x. P x \\<longrightarrow> Q x\"\n  shows \"Q (Greatest P)\"\nproof -\n  obtain m where \"P m\"\n    using example by auto\n\n  then have \"P (Greatest P)\"\n  proof (rule GreatestI_nat)\n    show \"\\<forall>y. P y \\<longrightarrow> y \\<le> bound\"\n      using bound by simp\n  qed\n  then show \"Q (Greatest P)\"\n    by (simp add: impl)\nqed\n\nlemma check_fail_least: \"check_fail \\<le> x\"\n  by (simp add: less_eq_check_result_def)\n\nlemma check_fail_least2: \"x \\<le> check_fail \\<longleftrightarrow> x = check_fail\"\n  by (cases x, auto simp add: less_eq_check_result_def)\n\nlemma check_inf_greatest: \"x \\<le> check_ok_infinite\"\n  by (cases x, auto simp add: less_eq_check_result_def)\n\nlemma check_inf_greatest2: \"check_ok_infinite \\<le> x \\<longleftrightarrow> x = check_ok_infinite\"\n  by (cases x, auto simp add: less_eq_check_result_def)\n\nlemma check_ok_compare: \"check_ok x \\<le> check_ok y \\<longleftrightarrow> x \\<le> y\"\n  by (cases x, auto simp add: less_eq_check_result_def)\n\nlemma GreatestI_check_result:\n  assumes example: \"\\<exists>m::check_result. P m\"\n    and bound: \"\\<forall>m. P m \\<longrightarrow> m \\<le> check_ok bound\"\n  shows \"P (Greatest P)\"\nproof (cases \"\\<exists>n. P (check_ok n)\")\n  case True\n  from this obtain k where \"P (check_ok k)\" by force\n\n\n  define P' where \"P' \\<equiv> (\\<lambda>x. P (check_ok x))\"\n\n  have \"P' (Greatest P')\"\n  proof (rule GreatestI_nat)\n    show \"P' k\"\n      by (simp add: P'_def \\<open>P (check_ok k)\\<close>)\n    show \"\\<forall>y. P' y \\<longrightarrow> y \\<le> bound\"\n      using P'_def assms(2) less_eq_check_result_def by auto\n  qed\n\n  have \"Greatest P = check_ok (Greatest P')\"\n  proof (subst Greatest_def, rule the_equality, auto)\n    show \" P (check_ok (Greatest P'))\"\n      using P'_def \\<open>P' (Greatest P')\\<close> by auto\n    show \"P y \\<Longrightarrow> y \\<le> check_ok (Greatest P')\" for y\n      apply (cases y, auto simp add: check_fail_least check_inf_greatest2 check_inf_greatest2 check_ok_compare)\n       apply (rule Greatest_le_nat[where b=bound])\n      using bound by (auto simp add: P'_def check_inf_greatest2 check_ok_compare)\n    show \"\\<And>x. \\<lbrakk>P x; \\<forall>y. P y \\<longrightarrow> y \\<le> x\\<rbrakk> \\<Longrightarrow> x = check_ok (Greatest P')\"\n      by (simp add: \\<open>P (check_ok (Greatest P'))\\<close> \\<open>\\<And>y. P y \\<Longrightarrow> y \\<le> check_ok (Greatest P')\\<close> eq_iff)\n  qed\n\n  then show \"P (Greatest P)\"\n    using P'_def \\<open>P' (Greatest P')\\<close> by auto\nnext\n  case False\n  from bound\n  have \"\\<not>P check_ok_infinite\"\n    using check_inf_greatest2 by blast\n\n  with False\n  have \"P x \\<longleftrightarrow> x = check_fail\" for x\n\n    using example proof (cases x, auto, goal_cases G)\n    case (G y)\n    thus \"P check_fail\"\n      by (cases y, auto)\n  qed\n\n  then show ?thesis\n    by (metis GreatestI2_order eq_refl)\nqed\n\n\n\nlemma GreatestI_check_result2:\n  assumes example: \"\\<exists>m::check_result. P m\"\n    and bound: \"\\<forall>m. P m \\<longrightarrow> m \\<le> check_ok bound\"\n    and impl: \"\\<forall>x. P x \\<longrightarrow> Q x\"\n  shows \"Q (Greatest P)\"\nproof -\n  obtain m where \"P m\"\n    using example by auto\n\n  from example\n  have \"P (Greatest P)\"\n  proof (rule GreatestI_check_result)\n    show \"\\<forall>y. P y \\<longrightarrow> y \\<le> check_ok bound\"\n      using bound by simp\n  qed\n  then show \"Q (Greatest P)\"\n    by (simp add: impl)\nqed\n\n\nlemma Greatest_leq:\n  assumes example: \"\\<exists>m. P m \\<and> (\\<forall>x. P x \\<longrightarrow> x \\<le> m)\"\n    and Px: \"P x\"\n  shows \"x \\<le> (Greatest P)\"\n  apply (unfold Greatest_def)\n  apply (rule the1I2)\n  using antisym example apply blast\n  using Px by auto\n\nlemma check_fail_smaller: \"check_fail \\<le> x\"\n  by (simp add: less_eq_check_result_def)\n\nlemma check_ok_infinite_max': \"check_ok_infinite \\<le> z \\<longleftrightarrow> z = check_ok_infinite\"\n  by (simp add: dual_order.antisym check_inf_greatest2)\n\n\nlemma exists_greatest_check_result:\n  assumes i_greatest:\"\\<forall>j>i. check_ok j \\<notin> A\"\nand example: \"a \\<in> A\"\nshows \"\\<exists>m. m \\<in> A \\<and> (\\<forall>x. x \\<in> A \\<longrightarrow> x \\<le> m)\"\nproof (cases \"check_ok_infinite \\<in> A\")\n  case True\n  then have \"check_ok_infinite \\<in> A \\<and> (\\<forall>x. x \\<in> A \\<longrightarrow> x \\<le> check_ok_infinite)\"\n    by (simp add: check_inf_greatest)\n  then show ?thesis ..\nnext\n  case False\n  show ?thesis\n  proof (cases \"\\<exists>i'. check_ok i' \\<in> A\")\n    case True\n    then have exists_ok: \"\\<exists>m. check_ok m \\<in> A \\<and> m \\<le> i\"\n      using i_greatest not_le_imp_less by blast\n\n    show \"\\<exists>m. m \\<in> A \\<and> (\\<forall>x. x \\<in> A \\<longrightarrow> x \\<le> m)\"\n    proof (rule ccontr)\n      assume a: \"\\<nexists>m. m \\<in> A \\<and> (\\<forall>x. x \\<in> A \\<longrightarrow> x \\<le> m)\"\n\n      obtain i_max where \"check_ok i_max \\<in> A\" and \"i_max \\<le> i\" and \"\\<forall>i'. check_ok i' \\<in> A \\<and> i' \\<le> i \\<longrightarrow> i' \\<le> i_max\"\n        apply atomize_elim\n        apply (rule exI[where x=\"GREATEST i'. check_ok i' \\<in> A \\<and> i' \\<le> i\"])\n        apply auto\n          apply (rule GreatestI_nat2[where bound=i])\n            apply (auto simp add: exists_ok)\n         apply (rule GreatestI_nat2[where bound=i])\n           apply (auto simp add: exists_ok)\n        apply (rule Greatest_le_nat[where b=i])\n         apply (auto simp add: exists_ok)\n        done\n\n      with a show False\n        apply auto\n        apply (drule spec[where x=\"check_ok i_max\"]) \n        apply auto\n      proof -\n\n        show \"False\"\n          if c0: \"check_ok i_max \\<in> A\"\n            and c1: \"i_max \\<le> i\"\n            and c2: \"\\<forall>i'. check_ok i' \\<in> A \\<and> i' \\<le> i \\<longrightarrow> i' \\<le> i_max\"\n            and c3: \"x \\<in> A\"\n            and c4: \"\\<not> x \\<le> check_ok i_max\"\n          for  x\n          using that apply (cases x, auto simp add: check_ok_compare check_fail_smaller)\n          using i_greatest not_le_imp_less apply blast\n          using False by blast\n      qed\n    qed\n  next\n    case False\n    then show ?thesis\n      by (metis check_ok_infinite_max check_result.exhaust check_result.simps(8) example less_eq_check_result'_def less_eq_check_result_def) \n  qed\nqed\n\n\n\ndefinition [simp]: \"Inf_check_result' S \\<equiv> if S = {} then check_ok_infinite else LEAST x. x \\<in> S\"\ndefinition [simp]: \"Sup_check_result' S  \\<equiv> if S = {} then check_fail else if check_ok_infinite \\<in> S \\<or> (\\<forall>i. \\<exists>j>i. check_ok j \\<in> S) then check_ok_infinite else GREATEST x. x \\<in> S\"\n\n\n\n\ninstantiation check_result :: complete_lattice begin\n  definition \"Inf_check_result \\<equiv> Inf_check_result'\"\n  definition \"Sup_check_result  \\<equiv> Sup_check_result'\"\n  definition \"bot_check_result \\<equiv> check_fail\"\n  definition \"sup_check_result (x::check_result) (y::check_result) \\<equiv> if y \\<le> x then x else y\"\n  definition \"top_check_result \\<equiv> check_ok_infinite\"\n  definition \"inf_check_result (x::check_result) (y::check_result) \\<equiv> if x \\<le> y then x else y\"\ninstance\nproof\n\n  fix x y z :: check_result\n  show \"inf x y \\<le> x\" and \"inf x y \\<le> y\"\n    by (auto simp add: inf_check_result_def less_eq_check_result_def split: check_result.splits)\n\n  show \"\\<lbrakk>x \\<le> y; x \\<le> z\\<rbrakk> \\<Longrightarrow> x \\<le> inf y z\"\n    by (auto simp add: inf_check_result_def less_eq_check_result_def split: check_result.splits)\n\n  show \"x \\<le> sup x y\" \"y \\<le> sup x y\"\n    by (auto simp add: sup_check_result_def less_eq_check_result_def split: check_result.splits)\n\n  show \"\\<lbrakk>y \\<le> x; z \\<le> x\\<rbrakk> \\<Longrightarrow> sup y z \\<le> x\"\n    by (auto simp add: sup_check_result_def less_eq_check_result_def split: check_result.splits)\n\n  show \"x \\<in> A \\<Longrightarrow> Inf A \\<le> x\" for A\n    using Inf_check_result'_def Inf_check_result_def Least_le by fastforce\n\n  show \"(\\<And>x. x \\<in> A \\<Longrightarrow> z \\<le> x) \\<Longrightarrow> z \\<le> Inf A\" for A\n    by (auto simp add: Inf_check_result_def least_check_result_not_less_eq leD check_inf_greatest)\n\n  show \"x \\<in> A \\<Longrightarrow> x \\<le> Sup A\" for A\n    apply (auto simp add: Sup_check_result_def check_inf_greatest        )\n    apply (erule notE[where P=\"x \\<le> (GREATEST x. x \\<in> A)\"])\n    apply (rule Greatest_leq)\n    by (auto simp add: exists_greatest_check_result)\n\n\n\n  show \"(\\<And>x. x \\<in> A \\<Longrightarrow> x \\<le> z) \\<Longrightarrow> Sup A \\<le> z\" for A\n    apply (auto simp add: Sup_check_result_def \n       check_ok_infinite_max'\n    )\n    using check_ok_infinite_max' apply blast\n     apply (cases z)\n       apply (auto simp add: check_fail_least2 check_fail_smaller)\n    using check_ok_compare leD apply blast\n    apply (erule notE[where P=\" (GREATEST x. x \\<in> A) \\<le> z\"])\n    apply (cases z)\n      apply (auto simp add: check_inf_greatest)\n     apply (metis GreatestI_check_result check_fail_least2 le_cases)\n    by (metis (full_types) GreatestI_check_result)\n\nqed (auto simp add: Inf_check_result_def top_check_result_def  Sup_check_result_def  bot_check_result_def)\nend\n\n\n\n\n\\<comment> \\<open>if result is false, result depends on a set S of recursive calls -- result is determined by checking conjunction of all recursive calls\\<close>\ndefinition tailrec :: \"(('a \\<Rightarrow> bool) \\<Rightarrow> ('a \\<Rightarrow> bool)) \\<Rightarrow> bool\" where\n\"tailrec F \\<equiv> \\<forall>g x. \\<not>F g x \\<longrightarrow> (\\<exists>S. \\<forall>g'. F g' x \\<longleftrightarrow> (\\<forall>x'\\<in>S. g' x'))\"\n\nlemma tailrec_is_mono:\n  assumes \"tailrec f\"\nshows \"mono f\"\nproof\n\n  show \"f x \\<le> f y\"\n    if c0: \"x \\<le> y\"\n    for  x y\n    using \\<open>tailrec f\\<close>\n    by (smt le_fun_def order_refl tailrec_def that)\nqed\n\n\n\ndefinition even :: \"(nat \\<Rightarrow> bool) \\<Rightarrow> nat \\<Rightarrow> bool\" where\n\"even g x \\<equiv> if x = 0 then True else if x = 1 then False else g (x - 2)\"\n\nlemma f_mono: \"mono even\"\n  by (smt even_def monoI predicate1I rev_predicate1D)\n\n\nlemma \"lfp even 0\"\n  by (subst lfp_unfold[OF f_mono], auto simp add: even_def)+\n\nlemma \"\\<not>lfp even 1\"\n  by (subst lfp_unfold[OF f_mono], auto simp add: even_def)+\n\nlemma \"lfp even 10\"\n  by (subst lfp_unfold[OF f_mono], auto simp add: even_def)+\n\n\n\n\n\n\n\ndefinition lfp2 :: \"(('a \\<Rightarrow> bool) \\<Rightarrow> ('a \\<Rightarrow> bool)) \\<Rightarrow> ('a \\<Rightarrow> bool)\" where\n\"lfp2 f \\<equiv> (\\<lambda>x. \\<exists>n. (f^^n) bot x)\"\n\n\nlemma lfp2_leq_lfp:\n  assumes mono: \"mono f\"\n  shows \"lfp2 f \\<le> lfp f\"\n  by (meson iterate_to_lfp lfp2_def mono predicate1I)\n\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/fixedpoints.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8791467580102418, "lm_q2_score": 0.8080672135527631, "lm_q1q2_score": 0.7104096710492814}}
{"text": "theory Propositional\n    imports Main\nbegin\n\ntext \\<open> In this exercise, we will prove some lemmas of propositional\nlogic with the aid of a calculus of natural deduction.\n\nFor the proofs, you may only use\n\n\\begin{itemize}\n\\item the following lemmas: \\\\\n@{text \"notI:\"}~@{thm notI[of A,no_vars]},\\\\\n@{text \"notE:\"}~@{thm notE[of A B,no_vars]},\\\\\n@{text \"conjI:\"}~@{thm conjI[of A B,no_vars]},\\\\ \n@{text \"conjE:\"}~@{thm conjE[of A B C,no_vars]},\\\\\n@{text \"disjI1:\"}~@{thm disjI1[of A B,no_vars]},\\\\\n@{text \"disjI2:\"}~@{thm disjI2[of A B,no_vars]},\\\\\n@{text \"disjE:\"}~@{thm disjE[of A B C,no_vars]},\\\\\n@{text \"impI:\"}~@{thm impI[of A B,no_vars]},\\\\\n@{text \"impE:\"}~@{thm impE[of A B C,no_vars]},\\\\\n@{text \"mp:\"}~@{thm mp[of A B,no_vars]}\\\\\n@{text \"iffI:\"}~@{thm iffI[of A B,no_vars]}, \\\\\n@{text \"iffE:\"}~@{thm iffE[of A B C,no_vars]}\\\\\n@{text \"classical:\"}~@{thm classical[of A,no_vars]}\n\n\\item the proof methods @{term rule}, @{term erule} and @{term assumption}.\n\\end{itemize}\n\nProve:\n\\<close>\n\nlemma I: \"A \\<longrightarrow> A\"\n  apply (rule impI)\n  apply (rule classical)\n  by assumption\n\nlemma \"A \\<and> B \\<longrightarrow> B \\<and> A\"\n  apply (rule impI)\n  apply (erule conjE)\n  apply (rule conjI)\n  by assumption\n\nlemma \"(A \\<and> B) \\<longrightarrow> (A \\<or> B)\"\n  apply (rule impI)\n  apply (erule conjE)\n  apply (rule disjI1)\n  by assumption\n\nlemma \"((A \\<or> B) \\<or> C) \\<longrightarrow> A \\<or> (B \\<or> C)\"\n  apply (rule impI)\n  apply (erule disjE)\n   apply (erule disjE)\n    apply (rule disjI1, assumption)\n   apply (rule disjI2, rule disjI1, assumption)\n  apply (rule disjI2, rule disjI2, assumption)\n  done\n\n\n\nlemma \"(A \\<or> A) = (A \\<and> A)\"\n  apply (rule iffI)\n   apply (rule conjI)\n    apply (erule disjE)\n     apply assumption+\n   apply (erule disjE)\n    apply assumption+\n  apply (erule conjE)\n  apply (rule disjI1)\n  by assumption\n     \n\nlemma S: \"(A \\<longrightarrow> B \\<longrightarrow> C) \\<longrightarrow> (A \\<longrightarrow> B) \\<longrightarrow> A \\<longrightarrow> C\"\n  apply (rule impI)+\n  apply (drule mp, assumption)+\n  by assumption\n  \n\nlemma \"(A \\<longrightarrow> B) \\<longrightarrow> (B \\<longrightarrow> C) \\<longrightarrow> A \\<longrightarrow> C\"\n  apply (rule impI)+\n  apply (drule mp, assumption)+\n  by assumption\n\nlemma \"\\<not> \\<not> A \\<longrightarrow> A\"\n  apply (rule impI)\n  apply (rule classical)\n  apply (erule notE, assumption)\n  done\n\nlemma \"A \\<longrightarrow> \\<not> \\<not> A\"\n  apply (rule impI)\n  apply (rule notI)\n  apply (erule notE, assumption)\n  done\n\nlemma \"(\\<not> A \\<longrightarrow> B) \\<longrightarrow> (\\<not> B \\<longrightarrow> A)\"\n  apply (rule impI)+\n  apply (rule classical)\n  apply (erule impE, assumption)\n  by (rule notE)\n\nlemma \"((A \\<longrightarrow> B) \\<longrightarrow> A) \\<longrightarrow> A\"\n  apply (rule impI)\n  apply (rule classical)\n  apply (erule impE)\n    apply (rule impI)\n  by (erule notE, assumption)+\n    \nlemma \"A \\<or> \\<not> A\"\n  apply (rule classical)\n  apply (rule disjI2)\n  apply (rule notI)\n  apply (erule notE)\n  apply (rule disjI1)\n  by assumption\n  \n\nlemma \"(\\<not> (A \\<and> B)) = (\\<not> A \\<or> \\<not> B)\"\n  apply (rule iffI)\n   apply (rule classical)\n   apply (rule disjI1)\n   apply (rule notI)\n   apply (erule notE)\n   apply (rule classical)\n   apply (rule conjI, assumption)\n   apply (rule classical)\n   apply (erule notE)\n   apply (rule disjI2, assumption)\n  apply (rule classical)\n  apply (rule notI)\n  apply (erule notE)\n  apply (erule conjE)\n  apply (erule disjE)\n  by (erule notE, assumption)+\n\n  \n\n(*<*) end (*>*)\n\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/logic/Propositional.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045847699186, "lm_q2_score": 0.8006920092299292, "lm_q1q2_score": 0.7103776215774312}}
{"text": "theory Extras  \n    imports \"Perm\" \"Graph_Theory.Graph_Theory\" \"List-Index.List_Index\"\nbegin\n\nsection \\<open>Appears before\\<close>\n\ndefinition \"appears_before l x y \\<equiv> y \\<in> set (drop (index l x) l)\"\n\nlemma appears_before_in:\n  assumes \"appears_before l x y\"\n  shows \"x \\<in> set l\" \"y \\<in> set l\"\n   apply (metis appears_before_def assms in_set_dropD index_conv_size_if_notin last_index_drop\n      last_index_less_size_conv)\n  by (meson appears_before_def assms in_set_dropD)\n\nlemma appears_before_empty: \"\\<not> appears_before [] x y\"\n  by (metis appears_before_in(1) empty_iff empty_set)\n\nlemma not_appears_before_in: \"x \\<notin> set l \\<or> y \\<notin> set l \\<Longrightarrow> \\<not> appears_before l x y\"\n  by (meson appears_before_in)\n\nlemma appears_before_id: \"appears_before l x x \\<longleftrightarrow> x \\<in> set l\"\n  apply (auto simp add: appears_before_in(1))\n  by (metis Cons_nth_drop_Suc appears_before_def index_less_size_conv list.set_intros(1) nth_index)\n\nlemma appears_before_cons:\n \"appears_before (x#l) y z \\<longleftrightarrow>\n  (if x = y then z \\<in> set (x#l) else appears_before l y z)\"\n  by (simp add: appears_before_def)\n\nlemma appears_before_append: \n  assumes \"appears_before p x y \\<or> appears_before q x y \\<or> x \\<in> set p \\<and> y \\<in> set q\"\n  shows \"appears_before (p@q) x y\"\nproof -\n  {\n    assume \"appears_before p x y\"\n    then have \"y \\<in> set (drop (index p x) p)\"\n      by (meson appears_before_def)\n    also have \"index p x = index (p@q) x\"\n      by (metis \\<open>appears_before p x y\\<close> appears_before_in(1) index_append)\n    then have \"set (drop (index p x) p) \\<subseteq> set (drop (index (p@q) x) (p@q))\"\n      by simp\n    ultimately have \"appears_before (p @ q) x y\"\n      by (meson appears_before_def in_mono)\n  } note 1 = this\n  {\n    assume \"appears_before q x y\"\n    then have \"y \\<in> set (drop (index q x) q)\"\n      by (meson appears_before_def)\n    also have \"length p + index q x \\<ge> index (p@q) x\"\n      by (simp add: index_append index_le_size trans_le_add1)\n    then have \"set (drop (index q x) q) \\<subseteq> set (drop (index (p@q) x) (p@q))\"\n      by (metis add_diff_cancel_left' append_Nil drop_all drop_append \n          le_add1 set_drop_subset_set_drop)\n    ultimately have ?thesis\n      by (meson appears_before_def subsetD)\n  } note 2 = this\n  {\n    assume \"x \\<in> set p\" \"y \\<in> set q\"\n    then have \"set q \\<subseteq> set (drop (index (p@q) x) (p@q))\"\n      by (simp add: index_append index_le_size)\n    then have ?thesis\n      by (metis \\<open>y \\<in> set q\\<close> appears_before_def subset_iff)\n  } note 3 = this\n  from 1 2 3 assms show ?thesis by auto\nqed\n\nsection \\<open>Permutations and funpow\\<close>\nlemma cycles_funpow:\n  assumes \"z \\<in> set_cycle (perm_orbit p x)\"\n  shows \"\\<exists>n. (apply_perm p ^^ n) z = x\"\nproof -\n  from assms have \"(apply_perm p ^^ n) z \\<in> set_cycle (perm_orbit p x)\" for n\n    by simp\n  also have \"x \\<in> set_cycle (perm_orbit p x)\" \n    using assms by fastforce\n  ultimately show ?thesis\n    by (metis apply_perm_power assms funpow_apply_cycle_perm_orbit set_cycle_ex_funpow)\nqed\n\nlemma funpow_cycles:\n  assumes \"(apply_perm p ^^ n) z = x\" \"z \\<noteq> x\"\n  shows \"z \\<in> set_cycle (perm_orbit p x)\"\n  by (metis apply_perm_eq_idI apply_perm_neq_idI apply_perm_power apply_set_perm assms \n      funpow_apply_perm_in_perm_orbit_iff set_perm_powerD start_in_perm_orbit_iff)\n\nlemma permutes_perm:\n  assumes \"finite S\" \"f permutes S\"\n  shows \"(Perm f) permutes S\"\n  by (metis (no_types, lifting) Perm_inverse assms mem_Collect_eq permutation permutation_permutes)\n\nlemma size_perm_type_eq_card: \"size (perm_type p) = card (cycles_of_perm p)\"\n  by (simp add: perm_type_def)\n\nlemma perm_orbit_set_comm: \"a \\<in> set_cycle (perm_orbit p b) \\<Longrightarrow> b \\<in> set_cycle (perm_orbit p a)\"\n  by (metis apply_cycle_perm_orbit apply_cycle_same_iff cycles_funpow\n      funpow_apply_perm_in_perm_orbit_iff start_in_perm_orbit_iff)\n\nlocale perm_on =\n  fixes p :: \"'a perm\" and S :: \"'a set\"\n  assumes permutes_p: \"p permutes S\" \nbegin\n\nlemma set_perm_subset:\n  shows \"set_perm p \\<subseteq> S\"\n  by (meson permutes_not_in apply_perm_neq_idI permutes_p subsetI)\n\nlemma count_cycles_on_eq_card:\n \"count_cycles_on S p = card (cycles_of_perm p) + card (S - set_perm p)\"\n  unfolding count_cycles_on_def by (simp add: perm_type_on_def size_perm_type_eq_card)\n\nlemma count_cycles_on_empty: \"S = {} \\<Longrightarrow> count_cycles_on S p = 0\"\n  using count_cycles_on_eq_card set_perm_subset by auto\n\nlemma inverse_permutes: \"(inverse p) permutes S\"\n  by (smt (verit, del_insts) apply_perm_inverse_not_in_set eq_apply_perm_inverse_iff\n      perm.inverse_inverse permutes_def permutes_subset set_perm_subset)\nend\n\nlocale finite_perm_on = perm_on +\n  assumes finite_S: \"finite S\"\nbegin\n\nlemma count_cycles_on_nonempty:\n  assumes \"S \\<noteq> {}\" shows \"count_cycles_on S p \\<noteq> 0\"\n  by (simp add: assms count_cycles_on_eq_card finite_S finite_cycles_of_perm)\nend\n\n\nsection \\<open>Digraph extras\\<close>\n\nlemma reachable1:\n  assumes \"a \\<rightarrow>\\<^bsub>G\\<^esub> b\" \"a \\<in> verts G\" \"b \\<in> verts G\"\n  shows \"a\\<rightarrow>\\<^sup>*\\<^bsub>G\\<^esub>b\"\n  by (metis assms reachable_def rtrancl_on.simps)\n\ndefinition (in wf_digraph) \"connect_sym \\<equiv> (\\<forall>a b. a \\<rightarrow>\\<^sup>* b \\<longrightarrow> b \\<rightarrow>\\<^sup>* a)\"\n\nlemma (in wf_digraph) reach_sym_arc:\n  assumes \"connect_sym\"\n  shows  \"a \\<rightarrow>\\<^bsub>G\\<^esub> b \\<Longrightarrow> b \\<rightarrow>\\<^sup>* a\"\n  using assms connect_sym_def by blast\n\nlemma arc_to_ends_pair [simp]: \"arc_to_ends (with_proj g) e = e\"\n  by simp\n\nlemma vpath_sublist: \n  assumes \"vpath (p @ q) G\"\n  shows \"p \\<noteq> [] \\<Longrightarrow> vpath p G\"  \"q \\<noteq> [] \\<Longrightarrow> vpath q G\"\n  by (meson assms distinct_append vpath_def vwalkI_append_l vwalkI_append_r)+\n\nlemma (in wf_digraph) sccs_empty: \"verts G = {} \\<Longrightarrow> sccs = {}\"\n  using sccs_verts_conv sccs_verts_conv_scc_of by force\n\nlemma (in wf_digraph) card_sccs_1: \"card sccs = 1 \\<Longrightarrow> sccs = {G}\"\n  by (smt (verit, del_insts) card_1_singletonE card_sccs_verts empty_iff image_empty\n        in_scc_of_self in_sccs_verts_conv_reachable in_verts_sccsD_sccs induce_eq_iff_induced\n        induced_subgraph_refl scc_of_in_sccs_verts sccs_verts_conv_scc_of singleton_iff \n        wf_digraph.reachable_in_verts(1) wf_digraph_axioms)\n\nlemma (in wf_digraph) card_sccs_connected: \"(card sccs = 1) = strongly_connected G\"\n  by (metis One_nat_def card.empty card.insert empty_iff finite.emptyI\n      strongly_connected_eq_iff card_sccs_1)\n\nlemma (in fin_digraph) finite_sccs: \"finite sccs\"\n  using finite_imageD finite_sccs_verts inj_on_verts_sccs sccs_verts_conv by auto\n\nlemma comm_graph_union: \"compatible g h \\<Longrightarrow> union g h = union h g\"\n  by (simp add: Un_commute compatible_head compatible_tail)\n\ndefinition pair_union :: \"'a pair_pre_digraph \\<Rightarrow> 'a pair_pre_digraph \\<Rightarrow> 'a pair_pre_digraph\" where\n\"pair_union g h \\<equiv> \\<lparr> pverts = pverts g \\<union> pverts h, parcs = parcs g \\<union> parcs h\\<rparr>\"\n\nlemma with_proj_union[simp]: \"with_proj (pair_union g h) = union (with_proj g) (with_proj h)\"\n  by (simp add: pair_union_def)\n\nlemma comm_pair_union: \"pair_union g h = pair_union h g\"\n  unfolding pair_union_def by auto\n\nlemma wf_pair_union:\n  assumes \"pair_wf_digraph g\" \"pair_wf_digraph h\"\n  shows \"pair_wf_digraph (pair_union g h)\"\n  by (metis assms compatibleI_with_proj wellformed_union wf_digraph_wp_iff with_proj_union)\n\nlemma pair_union_arcs_disj: \"x\\<rightarrow>\\<^bsub>pair_union g h\\<^esub>y \\<longleftrightarrow> x\\<rightarrow>\\<^bsub>g\\<^esub>y \\<or> x\\<rightarrow>\\<^bsub>h\\<^esub>y\"\n  by (simp add: pair_union_def)\n\nlemma arc_in_union: \"x\\<rightarrow>\\<^bsub>with_proj g\\<^esub>y \\<Longrightarrow> x\\<rightarrow>\\<^bsub>pair_union g h\\<^esub>y\"\n  by (metis Un_iff arcs_union with_proj_simps(2) with_proj_simps(3) with_proj_union)\n\nlemma reach_in_union:\n  assumes \"wf_digraph g\" \"wf_digraph h\" \"compatible g h\" \"x\\<rightarrow>\\<^sup>*\\<^bsub>g\\<^esub>y\"\n  shows \"x\\<rightarrow>\\<^sup>*\\<^bsub>union g h\\<^esub>y\"\nby (meson assms pre_digraph.reachable_mono rtrancl_subset_rtrancl subgraphs_of_union(1))\n\n\ndefinition reverse :: \"'a pair_pre_digraph \\<Rightarrow> 'a pair_pre_digraph\" (\"(_\\<^sup>R)\" [1000] 999) where\n\"reverse a = \\<lparr>pverts = pverts a, parcs = (parcs a)\\<inverse>\\<rparr>\"\n\nlemma (in pair_wf_digraph) wf_reverse: \"pair_wf_digraph (G\\<^sup>R)\"\n  unfolding reverse_def by (simp add: in_arcsD1 in_arcsD2 pair_wf_digraph_def)\n\nlemma arc_reverse: \"x\\<rightarrow>\\<^bsub>with_proj g\\<^esub>y \\<Longrightarrow> y\\<rightarrow>\\<^bsub>g\\<^sup>R\\<^esub>x\"\n  by (simp add: reverse_def)\n\nlemma reach_reverse: \"x\\<rightarrow>\\<^sup>*\\<^bsub>with_proj g\\<^esub>y \\<Longrightarrow> y\\<rightarrow>\\<^sup>*\\<^bsub>g\\<^sup>R\\<^esub>x\"\n  by (simp add: reverse_def reachable_def rtrancl_on_converseI)\n\nlemma (in pre_digraph) \"scc_of x \\<subseteq> verts G\"\n  using pre_digraph.scc_of_def reachable_in_vertsE by fastforce\n\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/Extras.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8459424373085146, "lm_q2_score": 0.839733963661418, "lm_q1q2_score": 0.7103665959104796}}
{"text": "(*<*)\ntheory Propositional_Logic\nimports Abstract_Completeness\nbegin\n(*>*)\n\nsection {* Toy instantiation: Propositional Logic *}\n\ndatatype fmla = Atom nat | Neg fmla | Conj fmla fmla\n\nprimrec max_depth where\n  \"max_depth (Atom _) = 0\"\n| \"max_depth (Neg \\<phi>) = Suc (max_depth \\<phi>)\"\n| \"max_depth (Conj \\<phi> \\<psi>) = Suc (max (max_depth \\<phi>) (max_depth \\<psi>))\"\n\nlemma max_depth_0: \"max_depth \\<phi> = 0 = (\\<exists>n. \\<phi> = Atom n)\"\n  by (cases \\<phi>) auto\n\nlemma max_depth_Suc: \"max_depth \\<phi> = Suc n = ((\\<exists>\\<psi>. \\<phi> = Neg \\<psi> \\<and> max_depth \\<psi> = n) \\<or>\n  (\\<exists>\\<psi>1 \\<psi>2. \\<phi> = Conj \\<psi>1 \\<psi>2 \\<and> max (max_depth \\<psi>1) (max_depth \\<psi>2) = n))\"\n  by (cases \\<phi>) auto\n\nabbreviation \"atoms \\<equiv> smap Atom nats\"\nabbreviation \"depth1 \\<equiv>\n  sinterleave (smap Neg atoms) (smap (split Conj) (sproduct atoms atoms))\"\n\nabbreviation \"sinterleaves \\<equiv> fold sinterleave\"\n\nfun extendLevel where \"extendLevel (belowN, N) =\n  (let Next = sinterleaves\n    (map (smap (split Conj)) [sproduct belowN N, sproduct N belowN, sproduct N N])\n    (smap Neg N)\n  in (sinterleave belowN N, Next))\"\n\nlemma extendLevel_step:\n  \"\\<lbrakk>sset belowN = {\\<phi>. max_depth \\<phi> < n};\n    sset N = {\\<phi>. max_depth \\<phi> = n}; st = (belowN, N)\\<rbrakk> \\<Longrightarrow>\n  \\<exists>belowNext Next. extendLevel st = (belowNext, Next) \\<and>\n     sset belowNext = {\\<phi>. max_depth \\<phi> < Suc n} \\<and> sset Next = {\\<phi>. max_depth \\<phi> = Suc n}\"\n  by (auto simp: sset_sinterleave sset_sproduct stream.set_map\n    image_iff max_depth_Suc)\n\nlemma sset_atoms: \"sset atoms = {\\<phi>. max_depth \\<phi> < 1}\"\n  by (auto simp: stream.set_map max_depth_0)\n\nlemma sset_depth1: \"sset depth1 = {\\<phi>. max_depth \\<phi> = 1}\"\n  by (auto simp: sset_sinterleave sset_sproduct stream.set_map\n    max_depth_Suc max_depth_0 max_def image_iff)\n\nlemma extendLevel_Nsteps:\n  \"\\<lbrakk>sset belowN = {\\<phi>. max_depth \\<phi> < n}; sset N = {\\<phi>. max_depth \\<phi> = n}\\<rbrakk> \\<Longrightarrow>\n  \\<exists>belowNext Next. (extendLevel ^^ m) (belowN, N) = (belowNext, Next) \\<and>\n     sset belowNext = {\\<phi>. max_depth \\<phi> < n + m} \\<and> sset Next = {\\<phi>. max_depth \\<phi> = n + m}\"\nproof (induction m arbitrary: belowN N n)\n  case (Suc m)\n  then obtain belowNext Next where \"(extendLevel ^^ m) (belowN, N) = (belowNext, Next)\"\n    \"sset belowNext = {\\<phi>. max_depth \\<phi> < n + m}\" \"sset Next = {\\<phi>. max_depth \\<phi> = n + m}\"\n    by blast\n  thus ?case unfolding funpow.simps o_apply add_Suc_right\n    by (intro extendLevel_step[of belowNext _ Next])\nqed simp\n\ncorollary extendLevel:\n  \"\\<exists>belowNext Next. (extendLevel ^^ m) (atoms, depth1) = (belowNext, Next) \\<and>\n     sset belowNext = {\\<phi>. max_depth \\<phi> < 1 + m} \\<and> sset Next = {\\<phi>. max_depth \\<phi> = 1 + m}\"\n  by (rule extendLevel_Nsteps) (auto simp: sset_atoms sset_depth1)\n\n\ndefinition \"fmlas = sinterleave atoms (smerge (smap snd (siterate extendLevel (atoms, depth1))))\"\n\nlemma fmlas_UNIV: \"sset fmlas = (UNIV :: fmla set)\"\nproof (intro equalityI subsetI UNIV_I)\n  fix \\<phi>\n  show \"\\<phi> \\<in> sset fmlas\"\n  proof (cases \"max_depth \\<phi>\")\n    case 0 thus ?thesis unfolding fmlas_def sset_sinterleave stream.set_map\n      by (intro UnI1) (auto simp: max_depth_0)\n  next\n    case (Suc m) thus ?thesis using extendLevel[of m]\n    unfolding fmlas_def sset_smerge sset_siterate sset_sinterleave stream.set_map\n      by (intro UnI2) (auto, metis (mono_tags) mem_Collect_eq)\n  qed\nqed\n\ndatatype rule = Idle | Ax nat | NegL fmla | NegR fmla | ConjL fmla fmla | ConjR fmla fmla\n\nabbreviation \"mkRules f \\<equiv> smap f fmlas\"\nabbreviation \"mkRulePairs f \\<equiv> smap (split f) (sproduct fmlas fmlas)\"\n\ndefinition rules where\n  \"rules = Idle ## \n     sinterleaves [mkRules NegL, mkRules NegR, mkRulePairs ConjL, mkRulePairs ConjR]\n     (smap Ax nats)\"\n\nlemma rules_UNIV: \"sset rules = (UNIV :: rule set)\"\n  unfolding rules_def by (auto simp: sset_sinterleave sset_sproduct stream.set_map\n    fmlas_UNIV image_iff) (metis rule.exhaust)\n\ntype_synonym state = \"fmla fset * fmla fset\"\n\nfun eff' :: \"rule \\<Rightarrow> state \\<Rightarrow> state fset option\" where\n  \"eff' Idle (\\<Gamma>, \\<Delta>) = Some {|(\\<Gamma>, \\<Delta>)|}\"\n| \"eff' (Ax n) (\\<Gamma>, \\<Delta>) =\n    (if Atom n |\\<in>| \\<Gamma> \\<and> Atom n |\\<in>| \\<Delta> then Some {||} else None)\"\n| \"eff' (NegL \\<phi>) (\\<Gamma>, \\<Delta>) =\n    (if Neg \\<phi> |\\<in>| \\<Gamma> then Some {|(\\<Gamma> |-| {| Neg \\<phi> |}, finsert \\<phi> \\<Delta>)|} else None)\"\n| \"eff' (NegR \\<phi>) (\\<Gamma>, \\<Delta>) =\n    (if Neg \\<phi> |\\<in>| \\<Delta> then Some {|(finsert \\<phi> \\<Gamma>, \\<Delta> |-| {| Neg \\<phi> |})|} else None)\"\n| \"eff' (ConjL \\<phi> \\<psi>) (\\<Gamma>, \\<Delta>) =\n    (if Conj \\<phi> \\<psi> |\\<in>| \\<Gamma>\n    then Some {|(finsert \\<phi> (finsert \\<psi> (\\<Gamma> |-| {| Conj \\<phi> \\<psi> |})), \\<Delta>)|}\n    else None)\"\n| \"eff' (ConjR \\<phi> \\<psi>) (\\<Gamma>, \\<Delta>) =\n    (if Conj \\<phi> \\<psi> |\\<in>| \\<Delta>\n    then Some {|(\\<Gamma>, finsert \\<phi> (\\<Delta> |-| {| Conj \\<phi> \\<psi> |})), (\\<Gamma>, finsert \\<psi> (\\<Delta> |-| {| Conj \\<phi> \\<psi> |}))|}\n    else None)\"\n\n\nabbreviation \"Disj \\<phi> \\<psi> \\<equiv> Neg (Conj (Neg \\<phi>) (Neg \\<psi>))\"\nabbreviation \"Imp \\<phi> \\<psi> \\<equiv> Disj (Neg \\<phi>) \\<psi>\"\nabbreviation \"Iff \\<phi> \\<psi> \\<equiv> Conj (Imp \\<phi> \\<psi>) (Imp \\<psi> \\<phi>)\"\n\ndefinition \"thm1 \\<equiv> ({|Conj (Atom 0) (Neg (Atom 0))|}, {||})\"\n\ndeclare Stream.smember_code [code del]\n\n\ninterpretation RuleSystem \"\\<lambda>r s ss. eff' r s = Some ss\" rules UNIV\n  by unfold_locales (auto simp: rules_UNIV intro: exI[of _ Idle])\n\ninterpretation PersistentRuleSystem \"\\<lambda>r s ss. eff' r s = Some ss\" rules UNIV\nproof (unfold_locales, unfold enabled_def per_def rules_UNIV, clarsimp)\n  fix r \\<Gamma> \\<Delta> ss r' \\<Gamma>' \\<Delta>' ss'\n  assume \"r' \\<noteq> r\" \"eff' r (\\<Gamma>, \\<Delta>) = Some ss\" \"eff' r' (\\<Gamma>, \\<Delta>) = Some ss'\" \"(\\<Gamma>', \\<Delta>') |\\<in>| ss'\"\n  then show \"\\<exists>sl. eff' r (\\<Gamma>', \\<Delta>') = Some sl\"\n    by (cases r r' rule: rule.exhaust[case_product rule.exhaust]) (auto split: if_splits)\nqed\n\ndefinition \"rho \\<equiv> i.fenum rules\"\ndefinition \"propTree \\<equiv> i.mkTree eff' rho\"\n\nexport_code propTree thm1 in Haskell module_name PropInstance (* file \".\" *)\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/Abstract_Completeness/Propositional_Logic.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267898240861, "lm_q2_score": 0.8175744673038222, "lm_q1q2_score": 0.7103305998697171}}
{"text": "section \\<open>Recursive inseperability\\<close>\n\ntheory Recursive_Inseparability\n  imports \"Recursion-Theory-I.RecEnSet\"\nbegin\n\ntext \\<open>Two sets $A$ and $B$ are recursively inseparable if there is no computable set that\ncontains $A$ and is disjoint from $B$. In particular, a set is computable if the set and its\ncomplement are recursively inseparable. The terminology was introduced by Smullyan~@{cite R58}.\nThe underlying idea can be traced back to Rosser, who essentially showed that provable and\ndisprovable sentences are \\emph{arithmetically} inseparable in Peano Arithmetic~@{cite R36};\nsee also Kleene's symmetric version of G\u00f6del's incompleteness theorem~@{cite K52}.\n\nHere we formalize recursive inseparability on top of the \\texttt{Recursion-Theory-I} AFP\nentry~@{cite RTI}. Our main result is a version of Rice' theorem that states that the index\nsets of any two given recursively enumerable sets are recursively inseparable.\\<close>\n\nsubsection \\<open>Definition and basic facts\\<close>\n\ntext \\<open>Two sets $A$ and $B$ are recursively inseparable if there are no decidable sets $X$ such\nthat $A$ is a subset of $X$ and $X$ is disjoint from $B$.\\<close>\n\ndefinition rec_inseparable where\n  \"rec_inseparable A B \\<equiv> \\<forall>X. A \\<subseteq> X \\<and> B \\<subseteq> - X \\<longrightarrow> \\<not> computable X\"\n\nlemma rec_inseparableI:\n  \"(\\<And>X. A \\<subseteq> X \\<Longrightarrow> B \\<subseteq> - X \\<Longrightarrow> computable X \\<Longrightarrow> False) \\<Longrightarrow> rec_inseparable A B\"\n  unfolding rec_inseparable_def by blast\n\nlemma rec_inseparableD:\n  \"rec_inseparable A B \\<Longrightarrow> A \\<subseteq> X \\<Longrightarrow> B \\<subseteq> - X \\<Longrightarrow> computable X \\<Longrightarrow> False\"\n  unfolding rec_inseparable_def by blast\n\ntext \\<open>Recursive inseperability is symmetric and enjoys a monotonicity property.\\<close>\n\nlemma rec_inseparable_symmetric:\n  \"rec_inseparable A B \\<Longrightarrow> rec_inseparable B A\"\n  unfolding rec_inseparable_def computable_def by (metis double_compl)\n\nlemma rec_inseparable_mono:\n  \"rec_inseparable A B \\<Longrightarrow> A \\<subseteq> A' \\<Longrightarrow> B \\<subseteq> B' \\<Longrightarrow> rec_inseparable A' B'\"\n  unfolding rec_inseparable_def by (meson subset_trans)\n\ntext \\<open>Many-to-one reductions apply to recursive inseparability as well.\\<close>\n\nlemma rec_inseparable_many_reducible:\n  assumes \"total_recursive f\" \"rec_inseparable (f -` A) (f -` B)\"\n  shows \"rec_inseparable A B\"\nproof (intro rec_inseparableI)\n  fix X assume \"A \\<subseteq> X\" \"B \\<subseteq> - X\" \"computable X\"\n  moreover have \"many_reducible_to (f -` X) X\" using assms(1)\n    by (auto simp: many_reducible_to_def many_reducible_to_via_def)\n  ultimately have \"computable (f -` X)\" and \"(f -` A) \\<subseteq> (f -` X)\" and \"(f -` B) \\<subseteq> - (f -` X)\"\n    by (auto dest!: m_red_to_comp)\n  then show \"False\" using assms(2) unfolding rec_inseparable_def by blast\nqed\n\ntext \\<open>Recursive inseparability of $A$ and $B$ holds vacuously if $A$ and $B$ are not disjoint.\\<close>\n\nlemma rec_inseparable_collapse:\n  \"A \\<inter> B \\<noteq> {} \\<Longrightarrow> rec_inseparable A B\"\n  by (auto simp: rec_inseparable_def)\n\ntext \\<open>Recursive inseparability is intimately connected to non-computability.\\<close>\n\nlemma rec_inseparable_non_computable:\n  \"A \\<inter> B = {} \\<Longrightarrow> rec_inseparable A B \\<Longrightarrow> \\<not> computable A\"\n  by (auto simp: rec_inseparable_def)\n\nlemma computable_rec_inseparable_conv:\n  \"computable A \\<longleftrightarrow> \\<not> rec_inseparable A (- A)\"\n  by (auto simp: computable_def rec_inseparable_def)\n\nsubsection \\<open>Rice's theorem\\<close>\n\ntext \\<open>We provide a stronger version of Rice's theorem compared to @{cite RTI}.\nUnfolding the definition of recursive inseparability, it states that there are no decidable\nsets $X$ such that\n\\begin{itemize}\n\\item there is a r.e.\\ set such that all its indices are elements of $X$; and\n\\item there is a r.e.\\ set such that none of its indices are elements of $X$.\n\\end{itemize}\nThis is true even if $X$ is not an index set (i.e., if an index of a r.e.\\ set is an element\nof $X$, then $X$ contains all indices of that r.e.\\ set), which is a requirement of Rice's\ntheorem in @{cite RTI}.\\<close>\n\n\n\nlemma Rice_rec_inseparable:\n  \"rec_inseparable {k. nat_to_ce_set k = nat_to_ce_set n} {k. nat_to_ce_set k = nat_to_ce_set m}\"\nproof (intro rec_inseparableI, goal_cases)\n  case (1 X)\n  text \\<open>Note that @{thm Rice_2} is not applicable because X may not be an index set.\\<close>\n  let ?Q = \"{q. s_ce q q \\<in> X} \\<times> nat_to_ce_set m \\<union> {q. s_ce q q \\<in> - X} \\<times> nat_to_ce_set n\"\n  have \"?Q \\<in> ce_rels\"\n    using 1(3) ce_set_lm_5 comp2_1[OF s_ce_is_pr id1_1 id1_1] unfolding computable_def\n    by (intro ce_union[of \"ce_rel_to_set _\" \"ce_rel_to_set _\", folded ce_rel_lm_32 ce_rel_lm_8]\n      ce_rel_lm_29 nat_to_ce_set_into_ce) blast+\n  then obtain q where \"nat_to_ce_set q = {c_pair q x |q x. (q, x) \\<in> ?Q}\"\n    unfolding ce_rel_lm_8 ce_rel_to_set_def by (metis (no_types, lifting) nat_to_ce_set_srj)\n  from eqset_imp_iff[OF this, of \"c_pair q _\"]\n  have \"nat_to_ce_set (s_ce q q) = (if s_ce q q \\<in> X then nat_to_ce_set m else nat_to_ce_set n)\"\n    by (auto simp: s_lm c_pair_inj' nat_to_ce_set_def fn_to_set_def pr_conv_1_to_2_def)\n  then show ?case using 1(1,2)[THEN subsetD, of \"s_ce q q\"] by (auto split: if_splits)\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/Minsky_Machines/Recursive_Inseparability.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.817574471748733, "lm_q2_score": 0.8688267643505194, "lm_q1q2_score": 0.7103305829050368}}
{"text": "section \\<open>Grover's algorithm\\<close>\n\ntheory Grover\n  imports Partial_State Gates Quantum_Hoare\nbegin\n\nsubsection \\<open>Basic definitions\\<close>\n\nlocale grover_state =\n  fixes n :: nat  (* number of qubits *)\n    and f :: \"nat \\<Rightarrow> bool\"  (* characteristic function, only need values in [0,N). *)\n  assumes n: \"n > 1\"\n    and dimM: \"card {i. i < (2::nat) ^ n \\<and> f i} > 0\"\n              \"card {i. i < (2::nat) ^ n \\<and> f i} < (2::nat) ^ n\"\nbegin\n\ndefinition N where\n  \"N = (2::nat) ^ n\"\n\ndefinition M where\n  \"M = card {i. i < N \\<and> f i}\"\n\nlemma N_ge_0 [simp]: \"0 < N\" by (simp add: N_def)\n\nlemma M_ge_0 [simp]: \"0 < M\" by (simp add: M_def dimM N_def)\n\nlemma M_neq_0 [simp]: \"M \\<noteq> 0\" by simp\n\nlemma M_le_N [simp]: \"M < N\" by (simp add: M_def dimM N_def)\n\nlemma M_not_ge_N [simp]: \"\\<not> M \\<ge> N\" using M_le_N by arith\n\ndefinition \\<psi> :: \"complex vec\" where\n  \"\\<psi> = Matrix.vec N (\\<lambda>i. 1 / sqrt N)\"\n\nlemma \\<psi>_dim [simp]:\n  \"\\<psi> \\<in> carrier_vec N\"\n  \"dim_vec \\<psi> = N\"\n  by (simp add: \\<psi>_def)+\n\nlemma \\<psi>_eval:\n  \"i < N \\<Longrightarrow> \\<psi> $ i = 1 / sqrt N\"\n  by (simp add: \\<psi>_def)\n\nlemma \\<psi>_inner:\n  \"inner_prod \\<psi> \\<psi> = 1\"\n  apply (simp add: \\<psi>_eval scalar_prod_def)\n  by (smt of_nat_less_0_iff of_real_mult of_real_of_nat_eq real_sqrt_mult_self)\n \nlemma \\<psi>_norm:\n  \"vec_norm \\<psi> = 1\"\n  by (simp add: \\<psi>_eval vec_norm_def scalar_prod_def)\n\ndefinition \\<alpha> :: \"complex vec\" where\n  \"\\<alpha> = Matrix.vec N (\\<lambda>i. if f i then 0 else 1 / sqrt (N - M))\"\n\nlemma \\<alpha>_dim [simp]:\n  \"\\<alpha> \\<in> carrier_vec N\"\n  \"dim_vec \\<alpha> = N\"\n  by (simp add: \\<alpha>_def)+\n\nlemma \\<alpha>_eval:\n  \"i < N \\<Longrightarrow> \\<alpha> $ i = (if f i then 0 else 1 / sqrt (N - M))\"\n  by (simp add: \\<alpha>_def)\n\nlemma \\<alpha>_inner:\n  \"inner_prod \\<alpha> \\<alpha> = 1\"\n  apply (simp add: scalar_prod_def \\<alpha>_eval)\n  apply (subst sum.mono_neutral_cong_right[of \"{0..<N}\" \"{0..<N}-{i. i < N \\<and> f i}\"])\n   apply auto\n  apply (subgoal_tac \"card ({0..<N} - {i. i < N \\<and> f i}) = N - M\")\n  subgoal by (metis of_nat_0_le_iff of_real_of_nat_eq of_real_power power2_eq_square real_sqrt_pow2)\n  unfolding N_def M_def \n  by (metis (no_types, lifting) atLeastLessThan_iff card.infinite card_Diff_subset card_atLeastLessThan diff_zero dimM(1) mem_Collect_eq neq0_conv subsetI zero_order(1))\n\ndefinition \\<beta> :: \"complex vec\" where\n  \"\\<beta> = Matrix.vec N (\\<lambda>i. if f i then 1 / sqrt M else 0)\"\n\nlemma \\<beta>_dim [simp]:\n  \"\\<beta> \\<in> carrier_vec N\"\n  \"dim_vec \\<beta> = N\"\n  by (simp add: \\<beta>_def)+\n\nlemma \\<beta>_eval:\n  \"i < N \\<Longrightarrow> \\<beta> $ i = (if f i then 1 / sqrt M else 0)\"\n  by (simp add: \\<beta>_def)\n\nlemma \\<beta>_inner:\n  \"inner_prod \\<beta> \\<beta> = 1\"  \n  apply (simp add: scalar_prod_def \\<beta>_eval)\n  apply (subst sum.mono_neutral_cong_right[of \"{0..<N}\" \"{i. i < N \\<and> f i}\"])\n   apply auto\n  apply (fold M_def)\n  by (metis of_nat_0_le_iff of_real_of_nat_eq of_real_power power2_eq_square real_sqrt_pow2)\n\nlemma alpha_beta_orth:\n  \"inner_prod \\<alpha> \\<beta> = 0\"\n  unfolding \\<alpha>_def \\<beta>_def by (simp add: scalar_prod_def)\n\nlemma beta_alpha_orth:\n  \"inner_prod \\<beta> \\<alpha> = 0\"\n  unfolding \\<alpha>_def \\<beta>_def by (simp add: scalar_prod_def)\n\ndefinition \\<theta> :: real where\n  \"\\<theta> = 2 * arccos (sqrt ((N - M) / N))\"\n\nlemma cos_theta_div_2:\n  \"cos (\\<theta> / 2) = sqrt ((N - M) / N)\"\nproof -\n  have \"\\<theta> / 2 = arccos (sqrt ((N - M) / N))\" using \\<theta>_def by simp\n  then show \"cos (\\<theta> / 2) = sqrt ((N - M) / N)\" \n    by (simp add: cos_arccos_abs)\nqed\n\nlemma sin_theta_div_2:\n  \"sin (\\<theta> / 2) = sqrt (M / N)\"\nproof -\n  have a: \"\\<theta> / 2 = arccos (sqrt ((N - M) / N))\" using \\<theta>_def by simp\n  have N: \"N > 0\" using N_def by auto\n  have M: \"M < N\" using M_def dimM N_def by auto\n  then show \"sin (\\<theta> / 2) = sqrt (M / N)\"\n    unfolding a\n    apply (simp add: sin_arccos_abs)\n  proof -\n    have eq: \"real (N - M) = real N - real M\" using N M \n      using M_not_ge_N nat_le_linear of_nat_diff by blast\n    have \"1 - real (N - M) / real N = (real N - (real N - real M)) / real N\" \n      unfolding eq using N \n      by (metis diff_divide_distrib divide_self_if eq gr_implies_not0 of_nat_0_eq_iff)\n    then show \"1 - real (N - M) / real N = real M / real N\" by auto\n  qed\nqed\n\nlemma \\<theta>_neq_0:\n  \"\\<theta> \\<noteq> 0\"\nproof -\n  {\n  assume \"\\<theta> = 0\"\n  then have \"\\<theta> / 2 = 0\" by auto\n  then have \"sin (\\<theta> / 2) = 0\" by auto\n  }\n  note z = this\n  have \"sin (\\<theta> / 2) = sqrt (M / N)\" using sin_theta_div_2 by auto\n  moreover have \"M > 0\" unfolding M_def N_def using dimM by auto\n  ultimately have \"sin (\\<theta> / 2) > 0\" by auto\n  with z show ?thesis by auto\nqed\n\nabbreviation ccos where \"ccos \\<phi> \\<equiv> complex_of_real (cos \\<phi>)\"\nabbreviation csin where \"csin \\<phi> \\<equiv> complex_of_real (sin \\<phi>)\"\n\nlemma \\<psi>_eq:\n  \"\\<psi> = ccos (\\<theta> / 2) \\<cdot>\\<^sub>v \\<alpha> + csin (\\<theta> / 2) \\<cdot>\\<^sub>v \\<beta>\"\n  apply (simp add: cos_theta_div_2 sin_theta_div_2)\n  apply (rule eq_vecI)\n  by (auto simp add: \\<alpha>_def \\<beta>_def \\<psi>_def real_sqrt_divide)\n\nlemma psi_inner_alpha:\n  \"inner_prod \\<psi> \\<alpha> = ccos (\\<theta> / 2)\"\n  unfolding \\<psi>_eq\nproof -\n  have \"inner_prod (ccos (\\<theta> / 2) \\<cdot>\\<^sub>v \\<alpha>) \\<alpha> = ccos (\\<theta> / 2)\"\n    apply (subst inner_prod_smult_right[of _ N])\n    using \\<alpha>_dim \\<alpha>_inner by auto\n  moreover have \"inner_prod (csin (\\<theta> / 2) \\<cdot>\\<^sub>v \\<beta>) \\<alpha> = 0\"\n    apply (subst inner_prod_smult_right[of _ N])\n    using \\<alpha>_dim \\<beta>_dim beta_alpha_orth by auto\n  ultimately show \"inner_prod (ccos (\\<theta> / 2) \\<cdot>\\<^sub>v \\<alpha> + csin (\\<theta> / 2) \\<cdot>\\<^sub>v \\<beta>) \\<alpha> = ccos (\\<theta> / 2)\"\n    apply (subst inner_prod_distrib_left[of _ N])\n    using \\<alpha>_dim \\<beta>_dim by auto\nqed\n\nlemma psi_inner_beta:\n  \"inner_prod \\<psi> \\<beta> = csin (\\<theta> / 2)\"\n  unfolding \\<psi>_eq\nproof -\n  have \"inner_prod (ccos (\\<theta> / 2) \\<cdot>\\<^sub>v \\<alpha>) \\<beta> = 0\"\n    apply (subst inner_prod_smult_right[of _ N])\n    using \\<alpha>_dim \\<beta>_dim alpha_beta_orth by auto\n  moreover have \"inner_prod (csin (\\<theta> / 2) \\<cdot>\\<^sub>v \\<beta>) \\<beta> = csin (\\<theta> / 2)\"\n    apply (subst inner_prod_smult_right[of _ N])\n    using \\<beta>_dim \\<beta>_inner by auto\n  ultimately show \"inner_prod (ccos (\\<theta> / 2) \\<cdot>\\<^sub>v \\<alpha> + csin (\\<theta> / 2) \\<cdot>\\<^sub>v \\<beta>) \\<beta> = csin (\\<theta> / 2)\"\n    apply (subst inner_prod_distrib_left[of _ N])\n    using \\<alpha>_dim \\<beta>_dim by auto\nqed\n\ndefinition alpha_l :: \"nat \\<Rightarrow> complex\" where\n  \"alpha_l l = ccos ((l + 1 / 2) * \\<theta>)\"\n\nlemma alpha_l_real:\n  \"alpha_l l \\<in> Reals\"\n  unfolding alpha_l_def by auto\n\nlemma cnj_alpha_l:\n  \"conjugate (alpha_l l) = alpha_l l\"\n  using alpha_l_real Reals_cnj_iff by auto\n\ndefinition beta_l :: \"nat \\<Rightarrow> complex\" where\n  \"beta_l l = csin ((l + 1 / 2) * \\<theta>)\"\n\nlemma beta_l_real:\n  \"beta_l l \\<in> Reals\"\n  unfolding beta_l_def by auto\n\nlemma cnj_beta_l:\n  \"conjugate (beta_l l) = beta_l l\"\n  using beta_l_real Reals_cnj_iff by auto\n\nlemma csin_ccos_squared_add:\n  \"ccos (a::real) * ccos a + csin a * csin a = 1\"\n  by (smt cos_diff cos_zero of_real_add of_real_hom.hom_one of_real_mult)\n\nlemma alpha_l_beta_l_add_norm:\n  \"alpha_l l * alpha_l l + beta_l l * beta_l l = 1\"\n  using alpha_l_def beta_l_def csin_ccos_squared_add by auto\n\ndefinition psi_l where\n  \"psi_l l = (alpha_l l) \\<cdot>\\<^sub>v \\<alpha> + (beta_l l) \\<cdot>\\<^sub>v \\<beta>\"\n\n\n\nlemma inner_psi_l:\n  \"inner_prod (psi_l l) (psi_l l) = 1\"\nproof -\n  have eq0: \"inner_prod (psi_l l) (psi_l l) \n    = inner_prod ((alpha_l l) \\<cdot>\\<^sub>v \\<alpha>) (psi_l l) + inner_prod ((beta_l l) \\<cdot>\\<^sub>v \\<beta>) (psi_l l)\"\n    unfolding psi_l_def\n    apply (subst inner_prod_distrib_left)\n    using \\<alpha>_def \\<beta>_def by auto\n  have \"inner_prod ((alpha_l l) \\<cdot>\\<^sub>v \\<alpha>) (psi_l l) \n    = inner_prod ((alpha_l l) \\<cdot>\\<^sub>v \\<alpha>) ((alpha_l l) \\<cdot>\\<^sub>v \\<alpha>) + inner_prod ((alpha_l l) \\<cdot>\\<^sub>v \\<alpha>) ((beta_l l) \\<cdot>\\<^sub>v \\<beta>)\"\n    unfolding psi_l_def\n    apply (subst inner_prod_distrib_right)\n    using \\<alpha>_def \\<beta>_def by auto\n  also have \"\\<dots> = (conjugate (alpha_l l)) * (alpha_l l) * inner_prod \\<alpha> \\<alpha> \n                + (conjugate (alpha_l l)) * (beta_l l) * inner_prod \\<alpha> \\<beta>\"\n    apply (subst (1 2) inner_prod_smult_left_right) using \\<alpha>_def \\<beta>_def by auto\n  also have \"\\<dots> = conjugate (alpha_l l) * (alpha_l l) \"\n    by (simp add: alpha_beta_orth \\<alpha>_inner)\n  also have \"\\<dots> = (alpha_l l) * (alpha_l l)\" using cnj_alpha_l by simp\n  finally have eq1: \"inner_prod (alpha_l l \\<cdot>\\<^sub>v \\<alpha>) (psi_l l) = alpha_l l * alpha_l l\".\n\n  have \"inner_prod ((beta_l l) \\<cdot>\\<^sub>v \\<beta>) (psi_l l) \n    = inner_prod ((beta_l l) \\<cdot>\\<^sub>v \\<beta>) ((alpha_l l) \\<cdot>\\<^sub>v \\<alpha>) + inner_prod ((beta_l l) \\<cdot>\\<^sub>v \\<beta>) ((beta_l l) \\<cdot>\\<^sub>v \\<beta>)\"\n    unfolding psi_l_def\n    apply (subst inner_prod_distrib_right)\n    using \\<alpha>_def \\<beta>_def by auto\n  also have \"\\<dots> = (conjugate (beta_l l)) * (alpha_l l) * inner_prod \\<beta> \\<alpha> \n                + (conjugate (beta_l l)) * (beta_l l) * inner_prod \\<beta> \\<beta>\"\n    apply (subst (1 2) inner_prod_smult_left_right) using \\<alpha>_def \\<beta>_def by auto\n  also have \"\\<dots> = (conjugate (beta_l l)) * (beta_l l)\"  using \\<beta>_inner beta_alpha_orth by auto\n  also have \"\\<dots> = (beta_l l) * (beta_l l)\" using cnj_beta_l by auto\n  finally have eq2: \"inner_prod (beta_l l \\<cdot>\\<^sub>v \\<beta>) (psi_l l) = beta_l l * beta_l l\".\n\n  show ?thesis unfolding eq0 eq1 eq2 using alpha_l_beta_l_add_norm by auto\nqed\n\nabbreviation proj :: \"complex vec \\<Rightarrow> complex mat\" where\n  \"proj v \\<equiv> outer_prod v v\"\n\ndefinition psi'_l where\n  \"psi'_l l = (alpha_l l) \\<cdot>\\<^sub>v \\<alpha> - (beta_l l) \\<cdot>\\<^sub>v \\<beta>\"\n\nlemma psi'_l_dim:\n  \"psi'_l l \\<in> carrier_vec N\"\n  unfolding psi'_l_def \\<alpha>_def \\<beta>_def by auto\n\ndefinition proj_psi'_l where\n  \"proj_psi'_l l = proj (psi'_l l)\"\n\nlemma proj_psi'_dim:\n  \"proj_psi'_l l \\<in> carrier_mat N N\"\n  unfolding proj_psi'_l_def using psi'_l_dim by auto\n\nlemma psi_inner_psi'_l:\n  \"inner_prod \\<psi> (psi'_l l) = (alpha_l l * ccos (\\<theta> / 2) - beta_l l * csin (\\<theta> / 2))\"\nproof -\n  have \"inner_prod \\<psi> (psi'_l l) = inner_prod \\<psi> (alpha_l l \\<cdot>\\<^sub>v \\<alpha>) - inner_prod \\<psi> (beta_l l \\<cdot>\\<^sub>v \\<beta>)\"\n    unfolding psi'_l_def apply (subst inner_prod_minus_distrib_right[of _ N]) by auto\n  also have \"\\<dots> = alpha_l l * (inner_prod \\<psi> \\<alpha>) - beta_l l * (inner_prod \\<psi> \\<beta>)\"\n    using \\<psi>_dim \\<alpha>_dim \\<beta>_dim by auto\n  also have \"\\<dots> = alpha_l l * (ccos (\\<theta> / 2)) - beta_l l * (csin (\\<theta> / 2))\"\n    using psi_inner_alpha psi_inner_beta by auto\n  finally show ?thesis by auto\nqed\n\nlemma double_ccos_square:\n  \"2 * ccos (a::real) * ccos a = ccos (2 * a) + 1\"\nproof -\n  have eq: \"ccos (2 * a) = ccos a * ccos a - csin a * csin a\"\n    using cos_add[of a a] by auto\n  have \"csin a * csin a = 1 - ccos a * ccos a\"\n    using csin_ccos_squared_add[of a]\n    by (metis add_diff_cancel_left')\n  then have \"ccos a * ccos a - csin a * csin a = 2 * ccos a * ccos a - 1\"\n    by simp\n  with eq show ?thesis by simp \nqed\n\nlemma double_csin_square:\n  \"2 * csin (a::real) * csin a = 1 - ccos (2 * a)\"\nproof -\n  have eq: \"ccos (2 * a) = ccos a * ccos a - csin a * csin a\"\n    using cos_add[of a a] by auto\n  have \"ccos a * ccos a = 1 - csin a * csin a\"\n    using csin_ccos_squared_add[of a]\n      cancel_comm_monoid_add_class.add_implies_diff by auto\n  then have \"ccos a * ccos a - csin a * csin a = 1 - 2 * csin (a::real) * csin a\"\n    by simp\n  with eq show ?thesis by simp\nqed\n\nlemma csin_double:\n  \"2 * csin (a::real) * ccos a = csin(2 * a)\"\n  using sin_add[of a a] by simp\n\nlemma ccos_add:\n  \"ccos (x + y) = ccos x * ccos y - csin x * csin y\"\n  using cos_add[of x y] by simp\n\nlemma alpha_l_Suc_l_derive:\n  \"2 * (alpha_l l * ccos (\\<theta> / 2) - beta_l l * csin (\\<theta> / 2)) * ccos (\\<theta> / 2) - alpha_l l = alpha_l (l + 1)\"\n  (is \"?lhs = ?rhs\")\nproof -\n  have \"2 * ((alpha_l l) * ccos (\\<theta> / 2) - (beta_l l) * csin (\\<theta> / 2)) * ccos (\\<theta> / 2)\n    = (alpha_l l) * (2 * ccos (\\<theta> / 2)* ccos (\\<theta> / 2)) - (beta_l l) * (2 * csin (\\<theta> / 2) * ccos (\\<theta> / 2))\" \n    by (simp add: left_diff_distrib)\n\n  also have \"\\<dots> = (alpha_l l) * (ccos (\\<theta>) + 1) - (beta_l l) * csin \\<theta>\"\n    using double_ccos_square csin_double by auto\n  finally have \"2 * ((alpha_l l) * ccos (\\<theta> / 2) - (beta_l l) * csin (\\<theta> / 2)) * ccos (\\<theta> / 2) \n    = (alpha_l l) * (ccos (\\<theta>) + 1) - (beta_l l) * csin \\<theta>\".\n  then have \"?lhs = (alpha_l l) * ccos (\\<theta>) - (beta_l l) * csin \\<theta>\" by (simp add: algebra_simps)\n  also have \"\\<dots> = (alpha_l (l + 1))\"\n    unfolding alpha_l_def beta_l_def \n    apply (subst ccos_add[of \"(real l + 1 / 2) * \\<theta>\" \"\\<theta>\", symmetric])\n    by (simp add: algebra_simps)\n  finally show ?thesis by auto\nqed\n\nlemma csin_add:\n  \"csin (x + y) = ccos x * csin y + csin x * ccos y\"\n  using sin_add[of x y] by simp\n\nlemma beta_l_Suc_l_derive:\n  \"2 * (alpha_l l * ccos (\\<theta> / 2) - (beta_l l) * csin (\\<theta> / 2)) * csin (\\<theta> / 2) + beta_l l = beta_l (l + 1)\"\n  (is \"?lhs = ?rhs\")\nproof -\n  have \"2 * ((alpha_l l) * ccos (\\<theta> / 2) - (beta_l l) * csin (\\<theta> / 2)) * csin (\\<theta> / 2)\n    = (alpha_l l) * (2 * csin (\\<theta> / 2)* ccos (\\<theta> / 2)) - (beta_l l) * (2 * csin (\\<theta> / 2) * csin (\\<theta> / 2))\" \n    by (simp add: left_diff_distrib)\n  also have \"\\<dots> = (alpha_l l) * (csin \\<theta>) - (beta_l l) * (1 - ccos (\\<theta>))\"\n    using double_csin_square csin_double by auto\n  finally have \"2 * ((alpha_l l) * ccos (\\<theta> / 2) - (beta_l l) * csin (\\<theta> / 2)) * csin (\\<theta> / 2)\n    = (alpha_l l) * (csin \\<theta>) - (beta_l l) * (1 - ccos (\\<theta>))\".\n  then have \"?lhs = (alpha_l l) * (csin \\<theta>) + (beta_l l) * ccos \\<theta>\" by (simp add: algebra_simps)\n  also have \"\\<dots> = (beta_l (l + 1))\"\n    unfolding alpha_l_def beta_l_def \n    apply (subst csin_add[of \"(real l + 1 / 2) * \\<theta>\" \"\\<theta>\", symmetric])\n    by (simp add: algebra_simps)\n  finally show ?thesis by auto\nqed\n\nlemma psi_l_Suc_l_derive:\n  \"2 * (alpha_l l * ccos (\\<theta> / 2) - beta_l l * csin (\\<theta> / 2)) \\<cdot>\\<^sub>v \\<psi> - psi'_l l = psi_l (l + 1)\"\n  (is \"?lhs = ?rhs\")\nproof -\n  let ?l = \"2 * ((alpha_l l) * ccos (\\<theta> / 2) - (beta_l l) * csin (\\<theta> / 2))\"\n  have \"?l \\<cdot>\\<^sub>v \\<psi> = ?l \\<cdot>\\<^sub>v (ccos (\\<theta> / 2) \\<cdot>\\<^sub>v \\<alpha> + csin (\\<theta> / 2) \\<cdot>\\<^sub>v \\<beta>)\" unfolding \\<psi>_eq by auto\n  also have \"\\<dots> = ?l \\<cdot>\\<^sub>v (ccos (\\<theta> / 2) \\<cdot>\\<^sub>v \\<alpha>) + ?l \\<cdot>\\<^sub>v (csin (\\<theta> / 2) \\<cdot>\\<^sub>v \\<beta>)\" \n    apply (subst smult_add_distrib_vec[of _ N]) using \\<alpha>_dim \\<beta>_dim by auto\n  also have \"\\<dots> = (?l * ccos (\\<theta> / 2)) \\<cdot>\\<^sub>v \\<alpha> + (?l * csin (\\<theta> / 2)) \\<cdot>\\<^sub>v \\<beta>\" by auto\n  finally have \"?l \\<cdot>\\<^sub>v \\<psi>  = (?l * ccos (\\<theta> / 2)) \\<cdot>\\<^sub>v \\<alpha> + (?l * csin (\\<theta> / 2)) \\<cdot>\\<^sub>v \\<beta>\".\n  then have \"?l \\<cdot>\\<^sub>v \\<psi> - (psi'_l l) = ((?l * ccos (\\<theta> / 2)) \\<cdot>\\<^sub>v \\<alpha> - (alpha_l l) \\<cdot>\\<^sub>v \\<alpha>) + ((?l * csin (\\<theta> / 2)) \\<cdot>\\<^sub>v \\<beta> + (beta_l l) \\<cdot>\\<^sub>v \\<beta>)\"\n    unfolding psi'_l_def by auto\n  also have \"\\<dots> = (?l * ccos (\\<theta> / 2) - alpha_l l) \\<cdot>\\<^sub>v \\<alpha> + (?l * csin (\\<theta> / 2) + beta_l l) \\<cdot>\\<^sub>v \\<beta>\"\n    apply (subst minus_smult_vec_distrib) apply (subst add_smult_distrib_vec) by auto\n  also have \"\\<dots> = (alpha_l (l + 1)) \\<cdot>\\<^sub>v \\<alpha> + (beta_l (l + 1)) \\<cdot>\\<^sub>v \\<beta>\"\n    using alpha_l_Suc_l_derive beta_l_Suc_l_derive by auto\n  finally have \"?l \\<cdot>\\<^sub>v \\<psi> - (psi'_l l) = (alpha_l (l + 1)) \\<cdot>\\<^sub>v \\<alpha> + (beta_l (l + 1)) \\<cdot>\\<^sub>v \\<beta>\".\n  then show ?thesis unfolding psi_l_def by auto\nqed\n\nsubsection \\<open>Grover operator\\<close>\n\ntext \\<open>Oracle O\\<close>\n\ndefinition proj_O :: \"complex mat\" where\n  \"proj_O = mat N N (\\<lambda>(i, j). if i = j then (if f i then 1 else 0) else 0)\"\n\nlemma proj_O_dim:\n  \"proj_O \\<in> carrier_mat N N\"\n  unfolding proj_O_def by auto\n\nlemma proj_O_mult_alpha:\n  \"proj_O *\\<^sub>v \\<alpha> = zero_vec N\"\n  by (auto simp add: proj_O_def \\<alpha>_def scalar_prod_def)\n\nlemma proj_O_mult_beta:\n  \"proj_O *\\<^sub>v \\<beta> = \\<beta>\"\n  by (auto simp add: proj_O_def \\<beta>_def scalar_prod_def sum_only_one_neq_0)\n\ndefinition mat_O :: \"complex mat\" where\n  \"mat_O = mat N N (\\<lambda>(i,j). if i = j then (if f i then -1 else 1) else 0)\"\n\nlemma mat_O_dim:\n  \"mat_O \\<in> carrier_mat N N\"\n  unfolding mat_O_def by auto\n\nlemma mat_O_mult_alpha:\n  \"mat_O *\\<^sub>v \\<alpha> = \\<alpha>\"\n  by (auto simp add: mat_O_def \\<alpha>_def scalar_prod_def sum_only_one_neq_0)\n\nlemma mat_O_mult_beta:\n  \"mat_O *\\<^sub>v \\<beta> = - \\<beta>\"\n  by (auto simp add: mat_O_def \\<beta>_def scalar_prod_def sum_only_one_neq_0)\n\nlemma hermitian_mat_O:\n  \"hermitian mat_O\"\n  by (auto simp add: hermitian_def mat_O_def adjoint_eval)\n\nlemma unitary_mat_O:\n  \"unitary mat_O\"\nproof -\n  have \"mat_O \\<in> carrier_mat N N\" unfolding mat_O_def by auto\n  moreover have \"mat_O * adjoint mat_O = mat_O * mat_O\" using hermitian_mat_O unfolding hermitian_def by auto\n  moreover have \"mat_O * mat_O = 1\\<^sub>m N\"\n    apply (rule eq_matI)\n    unfolding mat_O_def\n      apply (simp add: scalar_prod_def)\n    subgoal for i j apply (rule)\n      subgoal apply (subst sum_only_one_neq_0[of \"{0..<N}\" \"j\"]) by auto\n        apply (subst sum_only_one_neq_0[of \"{0..<N}\" \"j\"]) by auto\n    by auto\n  ultimately show ?thesis unfolding unitary_def inverts_mat_def by auto\nqed\n\ndefinition mat_Ph :: \"complex mat\" where\n  \"mat_Ph = mat N N (\\<lambda>(i,j). if i = j then if i = 0 then 1 else -1 else 0)\"\n\nlemma hermitian_mat_Ph:\n  \"hermitian mat_Ph\"\n  unfolding hermitian_def mat_Ph_def\n  apply (rule eq_matI)\n  by (auto simp add: adjoint_eval)\n\nlemma unitary_mat_Ph:\n  \"unitary mat_Ph\"\nproof -\n  have \"mat_Ph \\<in> carrier_mat N N\" unfolding mat_Ph_def by auto\n  moreover have \"mat_Ph * adjoint mat_Ph = mat_Ph * mat_Ph\" using hermitian_mat_Ph unfolding hermitian_def by auto\n  moreover have \"mat_Ph * mat_Ph = 1\\<^sub>m N\"\n    apply (rule eq_matI)\n    unfolding mat_Ph_def\n      apply (simp add: scalar_prod_def)\n    subgoal for i j apply (rule)\n      subgoal apply (subst sum_only_one_neq_0[of \"{0..<N}\" \"0\"]) by auto\n        apply (subst sum_only_one_neq_0[of \"{0..<N}\" \"j\"]) by auto\n    by auto\n  ultimately show ?thesis unfolding unitary_def inverts_mat_def by auto\nqed\n\ndefinition mat_G' :: \"complex mat\" where\n  \"mat_G' = mat N N (\\<lambda>(i,j). if i = j then 2 / N - 1 else 2 / N)\"\n\ntext \\<open>Geometrically, the Grover operator G is a rotation\\<close>\ndefinition mat_G :: \"complex mat\" where\n  \"mat_G = mat_G' * mat_O\"\n\nend\n\nsubsection \\<open>State of Grover's algorithm\\<close>\n\ntext \\<open>The dimensions are [2, 2, ..., 2, n]. We work with a very special\n  case as in the paper\\<close>\nlocale grover_state_sig = grover_state + state_sig +\n  fixes R :: nat\n  fixes K :: nat\n  assumes dims_def: \"dims = replicate n 2 @ [K]\"\n  assumes R: \"R = pi / (2 * \\<theta>) - 1 / 2\"\n  assumes K: \"K > R\"\n\nbegin\n\nlemma K_gt_0:\n  \"K > 0\"\n  using K by auto\n\ntext \\<open>Bits q0 to q\\_(n-1)\\<close>\ndefinition vars1 :: \"nat set\" where\n  \"vars1 = {0 ..< n}\"\n\ntext \\<open>Bit r\\<close>\ndefinition vars2 :: \"nat set\" where\n  \"vars2 = {n}\"\n\nlemma length_dims:\n  \"length dims = n + 1\"\n  unfolding dims_def by auto\n\nlemma dims_nth_lt_n:\n  \"l < n \\<Longrightarrow> nth dims l = 2\" \n  unfolding dims_def by (simp add: nth_append)\n\nlemma nths_Suc_n_dims:\n  \"nths dims {0..<(Suc n)} = dims\" \n  using length_dims nths_upt_eq_take\n  by (metis add_Suc_right add_Suc_shift lessThan_atLeast0 less_add_eq_less less_numeral_extra(4)\n            not_less plus_1_eq_Suc take_all)\n\ninterpretation ps2_P: partial_state2 dims vars1 vars2\n   apply unfold_locales unfolding vars1_def vars2_def by auto\n\ninterpretation ps_P: partial_state ps2_P.dims0 ps2_P.vars1'.\n\nabbreviation tensor_P where\n\"tensor_P A B \\<equiv> ps2_P.ptensor_mat A B\"\n\nlemma tensor_P_dim:\n  \"tensor_P A B \\<in> carrier_mat d d\"\nproof -\n  have \"ps2_P.d0 = prod_list (nths dims ({0..<n} \\<union> {n}))\" unfolding ps2_P.d0_def ps2_P.dims0_def ps2_P.vars0_def \n    by (simp add: vars1_def vars2_def)\n  also have \"\\<dots> = prod_list (nths dims ({0..<Suc n}))\"\n    apply (subgoal_tac \"{0..<n} \\<union> {n} = {0..<(Suc n)}\") by auto\n  also have \"\\<dots> = prod_list dims\" using nths_Suc_n_dims by auto\n  also have \"\\<dots> = d\" unfolding d_def by auto\n  finally show ?thesis  using ps2_P.ptensor_mat_carrier by auto\nqed\n\nlemma dims_nths_le_n:\n  assumes \"l \\<le> n\"\n  shows \"nths dims {0..<l} = replicate l 2\"\nproof (rule nth_equalityI, auto)\n  have \"l \\<le> n \\<Longrightarrow> (i < Suc n \\<and> i < l) = (i < l)\" for i\n    using less_trans by fastforce\n  then show l: \"length (nths dims {0..<l}) = l\" using assms\n    by (auto simp add: length_nths length_dims)\n\n  have llt: \"l < length dims\" using length_dims assms by auto\n  have v1: \"\\<And>i. i < l \\<Longrightarrow> {a. a < i \\<and> a \\<in> {0..<l}} = {0..<i}\" unfolding vars1_def by auto\n  then have \"\\<And>i. i < l \\<Longrightarrow> card {j. j < i \\<and> j \\<in> {0..<l}} = i\" by auto \n  then have \"nths dims {0..<l} ! i = dims ! i\" if \"i < l\" for i\n    using nth_nths_card[of i dims \"{0..<l}\"] that llt by auto\n  moreover have \"dims ! i = replicate n 2 ! i\" if \"i < n\" for i unfolding dims_def \n    by (auto simp add: nth_append that)\n  moreover have \"replicate n 2 ! i = replicate l 2 ! i\" if \"i < l\" for i using assms that by auto\n  ultimately show \"nths dims {0..<l} ! i = replicate l 2 ! i\" if \"i < length (nths dims {0..<l})\" for i\n    using l that assms by auto \nqed\n\nlemma dims_nths_one_lt_n: \n  assumes \"l < n\"\n  shows \"nths dims {l} = [2]\"\nproof -\n  have \"{i. i < length dims \\<and> i \\<in> {l}} = {l}\" using assms length_dims by auto\n  then have \"nths dims {l} = [dims ! l]\" using nths_only_one[of dims \"{l}\" l] by auto\n  moreover have \"dims ! l = 2\" unfolding dims_def using assms by (simp add: nth_append)\n  ultimately show ?thesis by auto\nqed\n\nlemma dims_vars1:\n  \"nths dims vars1 = replicate n 2\"\nproof (rule nth_equalityI, auto)\n  show l: \"length (nths dims vars1) = n\"\n    apply (auto simp add: length_nths vars1_def length_dims)\n    by (metis (no_types, lifting) Collect_cong Suc_lessD card_Collect_less_nat not_less_eq)\n\n  have v1: \"\\<And>i. i < n \\<Longrightarrow> {a. a < i \\<and> a \\<in> vars1} = {0..<i}\" unfolding vars1_def by auto\n  then have \"\\<And>i. i < n \\<Longrightarrow> card {j. j < i \\<and> j \\<in> vars1} = i\" by auto \n  then have \"nths dims vars1 ! i = dims ! i\" if \"i < n\" for i\n    using nth_nths_card[of i dims vars1] that length_dims vars1_def by auto\n  moreover have \"dims ! i = replicate n 2 ! i\" if \"i < n\" for i unfolding dims_def \n    by (simp add: nth_append that)\n  ultimately show \"nths dims vars1 ! i = replicate n 2 ! i\" if \"i < length (nths dims vars1)\" for i\n    using l that by auto \nqed\n\nlemma nths_rep_2_n:\n  \"nths (replicate n 2) {n} = []\"\n  by (metis (no_types, lifting) Collect_empty_eq card_empty length_0_conv length_replicate less_Suc_eq not_less_eq nths_replicate singletonD)\n\nlemma dims_vars2:\n  \"nths dims vars2 = [K]\"\n  unfolding dims_def vars2_def\n  apply (subst nths_append)\n  apply (subst nths_rep_2_n)\n  by simp\n\nlemma d_vars1:\n  \"prod_list (nths dims vars1) = N\"\nproof -\n  have eq: \"{0..<n} = {..<n}\"  by auto\n  have \"nths (replicate n 2 @ [K]) {0..<n} = (replicate n 2)\"\n    apply (subst eq)\n    using nths_upt_eq_take by simp\n  then show ?thesis unfolding dims_def vars1_def N_def by auto\nqed\n\nlemma ps2_P_dims0:\n  \"ps2_P.dims0 = dims\"\nproof -\n  have \"vars1 \\<union> vars2 = {0..<Suc n}\" unfolding vars1_def vars2_def by auto\n  then have dims: \"nths dims (vars1 \\<union> vars2) = dims\" unfolding vars1_def vars2_def using nths_Suc_n_dims by auto\n  then show ?thesis unfolding ps2_P.dims0_def ps2_P.vars0_def apply (subst dims) by auto\nqed\n\nlemma ps2_P_vars1':\n  \"ps2_P.vars1' = vars1\"\n  unfolding ps2_P.vars1'_def ps2_P.vars0_def  \nproof -\n  have eq: \"vars1 \\<union> vars2 = {0..<(Suc n)}\" unfolding vars1_def vars2_def by auto\n  have \"x < Suc n \\<Longrightarrow> {i \\<in> {0..<Suc n}. i < x} = {i. i < x}\" for x by auto\n  then have \"x < Suc n \\<Longrightarrow> ind_in_set {0..<(Suc n)} x = x\" for x unfolding ind_in_set_def by auto\n  then have \"x \\<in> vars1 \\<Longrightarrow> ind_in_set {0..<(Suc n)} x = x\" for x unfolding vars1_def by auto\n  then have \"ind_in_set {0..<(Suc n)} ` vars1 = vars1\" by force\n  with eq show \"ind_in_set (vars1 \\<union> vars2) ` vars1 = vars1\" by auto\nqed\n\nlemma ps2_P_d0:\n  \"ps2_P.d0 = d\"\n  unfolding ps2_P.d0_def using ps2_P_dims0 d_def by auto\n\nlemma ps2_P_d1:\n  \"ps2_P.d1 = N\"\n  unfolding ps2_P.d1_def ps2_P.dims1_def by (simp add: dims_vars1 N_def)\n\nlemma ps2_P_d2:\n  \"ps2_P.d2 = K\"\n  unfolding ps2_P.d2_def ps2_P.dims2_def by (simp add: dims_vars2)\n\nlemma ps_P_d:\n  \"ps_P.d = d\"\n  unfolding ps_P.d_def ps2_P_dims0 by auto\n\nlemma ps_P_d1:\n  \"ps_P.d1 = N\"\n  unfolding ps_P.d1_def ps_P.dims1_def ps2_P.nths_vars1' using ps2_P_d1 unfolding ps2_P.d1_def by auto\n\nlemma ps_P_d2:\n  \"ps_P.d2 = K\"\n  unfolding ps_P.d2_def ps_P.dims2_def ps2_P.nths_vars2' using ps2_P_d2 unfolding ps2_P.d2_def by auto\n\nlemma nths_uminus_vars1:\n  \"nths dims (- vars1) = nths dims vars2\"\n  using ps2_P.nths_vars2' unfolding ps2_P_dims0 ps2_P_vars1' ps2_P.dims2_def by auto\n\nlemma tensor_P_mult:\n  assumes \"m1 \\<in> carrier_mat (2^n) (2^n)\"\n    and \"m2 \\<in> carrier_mat (2^n) (2^n)\"\n    and \"m3 \\<in> carrier_mat K K\"\n    and \"m4 \\<in> carrier_mat K K\"\n  shows \"(tensor_P m1 m3) * (tensor_P m2 m4) = tensor_P (m1 * m2) (m3 * m4)\"\nproof -\n  have eq:\"{0..<n} = {..<n}\" by auto\n  have \"(nths dims vars1) = replicate n 2\"\n    unfolding dims_def vars1_def apply (subst eq)\n    by (simp add: nths_upt_eq_take[of \"(replicate n 2 @ [K])\" n]) \n\n  have \"ps2_P.d1 = 2^n\" unfolding ps2_P.d1_def ps2_P.dims1_def using d_vars1 N_def by auto\n  moreover have \"ps2_P.d2 = K\" unfolding ps2_P.d2_def ps2_P.dims2_def using dims_vars2 by auto\n\n  ultimately show ?thesis apply (subst ps2_P.ptensor_mat_mult) using assms by auto\nqed\n\nlemma mat_ext_vars1:\n  shows \"mat_extension dims vars1 A = tensor_P A (1\\<^sub>m K)\"\n  unfolding Utrans_P_def ps2_P.ptensor_mat_def partial_state.mat_extension_def\n    partial_state.d2_def partial_state.dims2_def ps2_P.nths_vars2'[simplified ps2_P_dims0 ps2_P_vars1'] \n  using ps2_P_d2 unfolding ps2_P.d2_def using ps2_P_dims0 ps2_P_vars1' by auto\n\nlemma Utrans_P_is_tensor_P1:\n  \"Utrans_P vars1 A = Utrans (tensor_P A (1\\<^sub>m K))\"\n  unfolding Utrans_P_def ps2_P.ptensor_mat_def partial_state.mat_extension_def\n    partial_state.d2_def partial_state.dims2_def ps2_P.nths_vars2'[simplified ps2_P_dims0 ps2_P_vars1'] \n  using ps2_P_d2 unfolding ps2_P.d2_def using ps2_P_dims0 ps2_P_vars1' by auto\n\nlemma nths_dims_uminus_vars2:\n  \"nths dims (-vars2) = nths dims vars1\"\nproof -\n  have \"nths dims (-vars2) = nths dims ({0..<length dims} - vars2)\"\n    using nths_minus_eq by auto\n  also have \"\\<dots> = nths dims vars1\" unfolding vars1_def vars2_def length_dims\n    apply (subgoal_tac \"{0..<n + 1} - {n} = {0..<n}\") by auto\n  finally show ?thesis by auto\nqed\n\nlemma mat_ext_vars2:\n  assumes \"A \\<in> carrier_mat K K\"\n  shows \"mat_extension dims vars2 A = tensor_P (1\\<^sub>m N) A\"\nproof -\n  have \"mat_extension dims vars2 A = tensor_mat dims vars2 A (1\\<^sub>m N)\"\n    unfolding Utrans_P_def partial_state.mat_extension_def\n      partial_state.d2_def partial_state.dims2_def\n      nths_dims_uminus_vars2 dims_vars1 N_def by auto\n  also have \"\\<dots> = tensor_mat dims vars1 (1\\<^sub>m N) A\" \n    apply (subst tensor_mat_comm[of vars1 vars2])\n    subgoal unfolding vars1_def vars2_def by auto\n    subgoal unfolding length_dims vars1_def vars2_def by auto\n    subgoal unfolding dims_vars1 N_def by auto\n    unfolding dims_vars2 using assms by auto\n  finally show \"mat_extension dims vars2 A = tensor_P (1\\<^sub>m N) A\"\n    unfolding ps2_P.ptensor_mat_def ps2_P_dims0 ps2_P_vars1' by auto\nqed\n\nlemma Utrans_P_is_tensor_P2:\n  assumes \"A \\<in> carrier_mat K K\"\n  shows \"Utrans_P vars2 A = Utrans (tensor_P (1\\<^sub>m N) A)\"\n  unfolding Utrans_P_def using mat_ext_vars2 assms by auto\n\n\nsubsection \\<open>Grover's algorithm\\<close>\n\ntext \\<open>Apply hadamard operator to first n variables\\<close>\ndefinition hadamard_on_i :: \"nat \\<Rightarrow> complex mat\" where\n  \"hadamard_on_i i = pmat_extension dims {i} (vars1 - {i}) hadamard\"\ndeclare hadamard_on_i_def [simp]\n\nfun hadamard_n :: \"nat \\<Rightarrow> com\" where\n  \"hadamard_n 0 = SKIP\"\n| \"hadamard_n (Suc i) = hadamard_n i ;; Utrans (tensor_P (hadamard_on_i i) (1\\<^sub>m K))\"\n\ntext \\<open>Body of the loop\\<close>\ndefinition D :: com where\n  \"D = Utrans_P vars1 mat_O ;;\n       hadamard_n n ;;\n       Utrans_P vars1 mat_Ph ;;\n       hadamard_n n ;;\n       Utrans_P vars2 (mat_incr K)\"\n\nlemma unitary_ex_mat_O:\n  \"unitary (tensor_P mat_O (1\\<^sub>m K))\"\n  unfolding ps2_P.ptensor_mat_def\n  apply (subst ps_P.tensor_mat_unitary)\n  subgoal using ps_P_d1 mat_O_def by auto\n  subgoal using ps_P_d2 by auto\n  subgoal using unitary_mat_O by auto\n  using unitary_one by auto\n\nlemma unitary_ex_mat_Ph:\n  \"unitary (tensor_P mat_Ph (1\\<^sub>m K))\"\n  unfolding ps2_P.ptensor_mat_def\n  apply (subst ps_P.tensor_mat_unitary)\n  subgoal using ps_P_d1 mat_Ph_def by auto\n  subgoal using ps_P_d2 by auto\n  subgoal using unitary_mat_Ph by auto\n  using unitary_one by auto\n\nlemma unitary_hadamard_on_i:\n  assumes \"k < n\"\n  shows \"unitary (hadamard_on_i k)\"\nproof -\n  interpret st2: partial_state2 dims \"{k}\" \"vars1 - {k}\"\n    apply unfold_locales by auto\n  show ?thesis unfolding hadamard_on_i_def st2.pmat_extension_def st2.ptensor_mat_def\n    apply (rule partial_state.tensor_mat_unitary)\n    subgoal unfolding partial_state.d1_def partial_state.dims1_def st2.nths_vars1' st2.dims1_def\n      using dims_nths_one_lt_n assms hadamard_dim by auto\n    subgoal unfolding st2.d2_def st2.dims2_def partial_state.d2_def partial_state.dims2_def st2.nths_vars2' st2.dims1_def\n      by auto\n    subgoal using unitary_hadamard by auto\n    subgoal using unitary_one by auto\n    done\nqed\n\nlemma unitary_exhadamard_on_i:\n  assumes \"k < n\"\n  shows \"unitary (tensor_P (hadamard_on_i k) (1\\<^sub>m K))\"\nproof -\n  interpret st2: partial_state2 dims \"{k}\" \"vars1 - {k}\"\n    apply unfold_locales by auto\n  have d1: \"st2.d0 = partial_state.d1 ps2_P.dims0 ps2_P.vars1'\"\n    unfolding partial_state.d1_def partial_state.dims1_def ps2_P.nths_vars1' ps2_P.dims1_def\n      st2.d0_def st2.dims0_def st2.vars0_def using assms\n    apply (subgoal_tac \"{k} \\<union> (vars1 - {k}) = vars1\") apply simp\n    unfolding vars1_def by auto\n  show ?thesis\n  unfolding ps2_P.ptensor_mat_def\n  apply (rule partial_state.tensor_mat_unitary)\n  subgoal unfolding hadamard_on_i_def st2.pmat_extension_def \n    using st2.ptensor_mat_carrier[of hadamard \"1\\<^sub>m st2.d2\"]\n    using d1 by auto\n  subgoal unfolding partial_state.d2_def partial_state.dims2_def ps2_P.nths_vars2' ps2_P.dims2_def dims_vars2 by auto\n  using unitary_hadamard_on_i unitary_one assms by auto\nqed\n\nlemma hadamard_on_i_dim:\n  assumes \"k < n\"\n  shows \"hadamard_on_i k \\<in> carrier_mat N N\"\nproof -\n  interpret st: partial_state2 dims \"{k}\" \"(vars1 - {k})\"\n    apply unfold_locales by auto\n  have vars1: \"{k} \\<union> (vars1 - {k}) = vars1\" unfolding vars1_def using assms by auto\n  show ?thesis unfolding hadamard_on_i_def N_def using st.pmat_extension_carrier unfolding st.d0_def st.dims0_def st.vars0_def\n    using vars1 dims_vars1 by auto\nqed\n\nlemma well_com_hadamard_k:\n  \"k \\<le> n \\<Longrightarrow> well_com (hadamard_n k)\"\nproof (induct k)\n  case 0\n  then show ?case by auto\nnext\n  case (Suc n)\n  then have \"well_com (hadamard_n n)\" by auto\n  then show ?case unfolding hadamard_n.simps well_com.simps using tensor_P_dim unitary_exhadamard_on_i Suc by auto\nqed\n\nlemma well_com_hadamard_n:\n  \"well_com (hadamard_n n)\"\n  using well_com_hadamard_k by auto\n\nlemma well_com_mat_O:\n  \"well_com (Utrans_P vars1 mat_O)\"\n  apply (subst Utrans_P_is_tensor_P1)\n  apply simp using tensor_P_dim unitary_ex_mat_O by auto\n\nlemma well_com_mat_Ph:\n  \"well_com (Utrans_P vars1 mat_Ph)\"\n  apply (subst Utrans_P_is_tensor_P1)\n  apply simp using tensor_P_dim unitary_ex_mat_Ph by auto\n\nlemma unitary_exmat_incr:\n  \"unitary (tensor_P (1\\<^sub>m N) (mat_incr K))\"\n  unfolding ps2_P.ptensor_mat_def\n  apply (subst ps_P.tensor_mat_unitary)\n  using  unitary_mat_incr K unitary_one by (auto simp add: ps_P_d1 ps_P_d2 mat_incr_def)\n\nlemma well_com_mat_incr:\n  \"well_com (Utrans_P vars2 (mat_incr K))\"\n  apply (subst Utrans_P_is_tensor_P2)\n  apply (simp add: mat_incr_def) using tensor_P_dim unitary_exmat_incr by auto\n\nlemma well_com_D: \"well_com D\"\n  unfolding D_def apply auto\n  using well_com_hadamard_n well_com_mat_incr well_com_mat_O well_com_mat_Ph \n  by auto\n\ntext \\<open>Test at while loop\\<close>\n\ndefinition M0 :: \"complex mat\" where\n  \"M0 = mat K K (\\<lambda>(i,j). if i = j \\<and> i \\<ge> R then 1 else 0)\"\n\nlemma hermitian_M0:\n  \"hermitian M0\"\n  by (auto simp add: hermitian_def M0_def adjoint_eval)\n\nlemma M0_dim:\n  \"M0 \\<in> carrier_mat K K\"\n  unfolding M0_def by auto\n\nlemma M0_mult_M0:\n  \"M0 * M0 = M0\"\n  by (auto simp add: M0_def scalar_prod_def sum_only_one_neq_0)\n\ndefinition M1 :: \"complex mat\" where\n  \"M1 = mat K K (\\<lambda>(i,j). if i = j \\<and> i < R then 1 else 0)\"\n\nlemma M1_dim:\n  \"M1 \\<in> carrier_mat K K\"\n  unfolding M1_def by auto\n\nlemma hermitian_M1:\n  \"hermitian M1\"\n  by (auto simp add: hermitian_def M1_def adjoint_eval)\n\nlemma M1_mult_M1:\n  \"M1 * M1 = M1\"\n  by (auto simp add: M1_def scalar_prod_def sum_only_one_neq_0)\n\nlemma M1_add_M0:\n  \"M1 + M0 = 1\\<^sub>m K\"\n  unfolding M0_def M1_def by auto\n\ntext \\<open>Test at the end\\<close>\n\ndefinition testN :: \"nat \\<Rightarrow> complex mat\" where\n  \"testN k = mat N N (\\<lambda>(i,j). if i = k \\<and> j = k then 1 else 0)\"\n\nlemma hermitian_testN:\n  \"hermitian (testN k)\"\n  unfolding hermitian_def testN_def\n  by (auto simp add: scalar_prod_def adjoint_eval)\n\nlemma testN_mult_testN:\n  \"testN k * testN k = testN k\"\n  unfolding testN_def\n  by (auto simp add: scalar_prod_def sum_only_one_neq_0)\n\nlemma testN_dim:\n  \"testN k \\<in> carrier_mat N N\"\n  unfolding testN_def by auto\n\ndefinition test_fst_k :: \"nat \\<Rightarrow> complex mat\" where\n  \"test_fst_k k = mat N N (\\<lambda>(i, j). if (i = j \\<and> i < k) then 1 else 0)\"\n\nlemma sum_test_k:\n  assumes \"m \\<le> N\"\n  shows \"matrix_sum N (\\<lambda>k. testN k) m = test_fst_k m\"\nproof -\n  have \"m \\<le> N \\<Longrightarrow> matrix_sum N (\\<lambda>k. testN k) m = mat N N (\\<lambda>(i, j). if (i = j \\<and> i < m) then 1 else 0)\" for m\n  proof (induct m)\n    case 0\n    then show ?case apply simp apply (rule eq_matI) by auto\n  next\n    case (Suc m)\n    then have m: \"m < N\" by auto\n    then have m': \"m \\<le> N\" by auto\n    have \"matrix_sum N testN (Suc m) = testN m + matrix_sum N testN m\" by simp\n    also have \"\\<dots> = mat N N (\\<lambda>(i, j). if (i = j \\<and> i < (Suc m)) then 1 else 0)\"\n      unfolding testN_def Suc(1)[OF m'] apply (rule eq_matI) by auto\n    finally show ?case by auto\n  qed\n  then show ?thesis unfolding test_fst_k_def using assms by auto\nqed\n\nlemma test_fst_kN:\n  \"test_fst_k N = 1\\<^sub>m N\"\n  apply (rule eq_matI)\n  unfolding test_fst_k_def by auto\n\nlemma matrix_sum_tensor_P1:\n  \"(\\<And>k. k < m \\<Longrightarrow> g k \\<in> carrier_mat N N) \\<Longrightarrow> (A \\<in> carrier_mat K K) \\<Longrightarrow>\n   matrix_sum d (\\<lambda>k. tensor_P (g k) A) m = tensor_P (matrix_sum N g m) A\"\nproof (induct m)\n  case 0\n  show ?case apply (simp) unfolding ps2_P.ptensor_mat_def \n    using ps_P.tensor_mat_zero1[simplified ps_P_d ps_P_d1, of A] by auto\nnext\n  case (Suc m)\n  then have ind: \"matrix_sum d (\\<lambda>k. tensor_P (g k) A) m = tensor_P (matrix_sum N g m) A\" \n    and dk: \"\\<And>k. k < m \\<Longrightarrow> g k \\<in> carrier_mat N N\" and \"A \\<in> carrier_mat K K\" by auto\n  have ds: \"matrix_sum N g m \\<in> carrier_mat N N\" apply (subst matrix_sum_dim)\n    using dk by auto\n  show ?case apply simp\n    apply (subst ind)\n    unfolding ps2_P.ptensor_mat_def apply (subst ps_P.tensor_mat_add1)\n    unfolding ps_P_d1 ps_P_d2 using Suc ds by auto\nqed\n\ntext \\<open>Grover's algorithm. Assume we start in the zero state\\<close>\ndefinition Grover :: com where\n  \"Grover = hadamard_n n ;;\n            While_P vars2 M0 M1 D ;;\n            Measure_P vars1 N testN (replicate N SKIP)\"\n\nlemma well_com_if:\n  \"well_com (Measure_P vars1 N testN (replicate N SKIP))\"\n  unfolding Measure_P_def apply auto\nproof -\n  have eq0: \"\\<And>n. mat_extension dims vars1 (testN n) = tensor_P (testN n) (1\\<^sub>m K)\"\n    unfolding mat_ext_vars1 by auto \n  have eq1: \"adjoint (tensor_P (testN j) (1\\<^sub>m K)) * tensor_P (testN j) (1\\<^sub>m K) = tensor_P (testN j) (1\\<^sub>m K)\" for j\n    unfolding ps2_P.ptensor_mat_def\n    apply (subst ps_P.tensor_mat_adjoint)\n      apply (auto simp add: ps_P_d1 ps_P_d2 testN_dim hermitian_testN[unfolded hermitian_def] hermitian_one[unfolded hermitian_def])\n    apply (subst ps_P.tensor_mat_mult[symmetric])\n    by (auto simp add: ps_P_d1 ps_P_d2 testN_dim testN_mult_testN)\n  have \"measurement d N (\\<lambda>n. tensor_P (testN n) (1\\<^sub>m K))\"\n    unfolding measurement_def\n    apply (simp add: tensor_P_dim)\n    apply (subst eq1)\n    apply (subst matrix_sum_tensor_P1)\n      apply (auto simp add: testN_dim)\n    apply (subst sum_test_k, simp)\n    apply (subst test_fst_kN)\n    unfolding ps2_P.ptensor_mat_def\n    using ps_P.tensor_mat_id ps_P_d ps_P_d1 ps_P_d2 by auto\n  then show \"measurement d N (\\<lambda>n. mat_extension dims vars1 (testN n))\" using eq0 by auto\n\n  show \"list_all well_com (replicate N SKIP)\" \n    apply (subst list_all_length) by simp\nqed\n\nlemma well_com_while:\n  \"well_com (While_P vars2 M0 M1 D)\"\n  unfolding While_P_def apply auto\n   apply (subst (1 2) mat_ext_vars2)\n  apply (auto simp add: M1_dim M0_dim)\nproof -\n  have 2: \"2 = Suc (Suc 0)\" by auto\n  have ad0: \"adjoint (tensor_P (1\\<^sub>m N) M0) = (tensor_P (1\\<^sub>m N) M0)\"\n    unfolding ps2_P.ptensor_mat_def apply (subst ps_P.tensor_mat_adjoint)\n    unfolding ps_P_d1 ps_P_d2 by (auto simp add: M0_dim adjoint_one hermitian_M0[unfolded hermitian_def])\n  have ad1: \"adjoint (tensor_P (1\\<^sub>m N) M1) = (tensor_P (1\\<^sub>m N) M1)\"\n    unfolding ps2_P.ptensor_mat_def apply (subst ps_P.tensor_mat_adjoint)\n    unfolding ps_P_d1 ps_P_d2 by (auto simp add: M1_dim adjoint_one hermitian_M1[unfolded hermitian_def])\n  have m0: \"tensor_P (1\\<^sub>m N) M0 * tensor_P (1\\<^sub>m N) M0 = tensor_P (1\\<^sub>m N) M0\"\n    unfolding ps2_P.ptensor_mat_def apply (subst ps_P.tensor_mat_mult[symmetric])\n    unfolding ps_P_d1 ps_P_d2 using M0_dim M0_mult_M0 by auto\n  have m1: \"tensor_P (1\\<^sub>m N) M1 * tensor_P (1\\<^sub>m N) M1 = tensor_P (1\\<^sub>m N) M1\"\n    unfolding ps2_P.ptensor_mat_def apply (subst ps_P.tensor_mat_mult[symmetric])\n    unfolding ps_P_d1 ps_P_d2 using M1_dim M1_mult_M1 by auto\n  have s: \"tensor_P (1\\<^sub>m N) M1 + tensor_P (1\\<^sub>m N) M0 = 1\\<^sub>m d\"\n    unfolding ps2_P.ptensor_mat_def apply (subst ps_P.tensor_mat_add2[symmetric])\n    unfolding ps_P_d1 ps_P_d2 \n    by (auto simp add: M1_dim M0_dim M1_add_M0 ps_P.tensor_mat_id[simplified ps_P_d1 ps_P_d2 ps_P_d])\n  show \"measurement d 2 (\\<lambda>n. if n = 0 then tensor_P (1\\<^sub>m N) M0 else if n = 1 then tensor_P (1\\<^sub>m N) M1 else undefined)\"\n    unfolding measurement_def apply (auto simp add: tensor_P_dim) apply (subst 2)\n    apply (simp add: ad0 ad1 m0 m1)\n    apply (subst assoc_add_mat[symmetric, of _ d d]) using tensor_P_dim s by auto\n  show \"well_com D\" using well_com_D by auto\nqed\n\nlemma well_com_Grover:\n  \"well_com Grover\"\n  unfolding Grover_def apply auto\n  using well_com_hadamard_n well_com_if well_com_while by auto\n\nsubsection \\<open>Correctness\\<close>\n\ntext \\<open>Pre-condition: assume in the zero state\\<close>\n\ndefinition ket_pre :: \"complex vec\" where\n  \"ket_pre = Matrix.vec N (\\<lambda>k. if k = 0 then 1 else 0)\"\n\nlemma ket_pre_dim:\n  \"ket_pre \\<in> carrier_vec N\" using ket_pre_def by auto\n\ndefinition pre :: \"complex mat\" where\n  \"pre = proj ket_pre\"\n\nlemma pre_dim:\n  \"pre \\<in> carrier_mat N N\"\n  using pre_def ket_pre_def by auto\n\nlemma norm_pre:\n  \"inner_prod ket_pre ket_pre = 1\"\n  unfolding ket_pre_def scalar_prod_def\n  using sum_only_one_neq_0[of \"{0..<N}\" 0 \"\\<lambda>i. (if i = 0 then 1 else 0) * cnj (if i = 0 then 1 else 0)\"] by auto\n\nlemma pre_trace:\n  \"trace pre = 1\"\n  unfolding pre_def\n  apply (subst trace_outer_prod[of _ N])\n  subgoal unfolding ket_pre_def by auto using norm_pre by auto\n\nlemma positive_pre:\n  \"positive pre\"\n  using positive_same_outer_prod unfolding pre_def ket_pre_def by auto\n\nlemma pre_le_one:\n  \"pre \\<le>\\<^sub>L 1\\<^sub>m N\"\n  unfolding pre_def using outer_prod_le_one norm_pre ket_pre_def by auto\n\ntext \\<open>Post-condition: should be in a state i with f i = 1\\<close>\n\ndefinition post :: \"complex mat\" where\n  \"post = mat N N (\\<lambda>(i, j). if (i = j \\<and> f i) then 1 else 0)\"\n\nlemma post_dim:\n  \"post \\<in> carrier_mat N N\"\n  unfolding post_def by auto\n\nlemma hermitian_post:\n  \"hermitian post\"\n  unfolding hermitian_def post_def\n  by (auto simp add: adjoint_eval)\n\ntext \\<open>Hoare triples of initialization\\<close>\n\ndefinition ket_zero :: \"complex vec\" where\n  \"ket_zero = Matrix.vec 2 (\\<lambda>k. if k = 0 then 1 else 0)\"\n\nlemma ket_zero_dim:\n  \"ket_zero \\<in> carrier_vec 2\" unfolding ket_zero_def by auto\n\ndefinition proj_zero where\n  \"proj_zero = proj ket_zero\"\n\ndefinition ket_one where\n  \"ket_one = Matrix.vec 2 (\\<lambda>k. if k = 1 then 1 else 0)\"\n\ndefinition proj_one where\n  \"proj_one = proj ket_one\"\n\ndefinition ket_plus where\n  \"ket_plus = Matrix.vec 2 (\\<lambda>k.1 / csqrt 2) \"\n\nlemma ket_plus_dim:\n  \"ket_plus \\<in> carrier_vec 2\" unfolding ket_plus_def by auto\n\nlemma ket_plus_eval [simp]:\n  \"i < 2 \\<Longrightarrow> ket_plus $ i = 1 / csqrt 2\"\n  apply (simp only: ket_plus_def)\n  using index_vec less_2_cases by force\n\n\n\nlemma ket_plus_tensor_n:\n  \"partial_state.tensor_vec [2, 2] {0} ket_plus ket_plus = Matrix.vec 4 (\\<lambda>k. 1 / 2)\"\n  unfolding partial_state.tensor_vec_def state_sig.d_def\nproof (rule eq_vecI, auto)\n  fix i :: nat assume i: \"i < 4\"\n  interpret st: partial_state \"[2, 2]\" \"{0}\" .\n  have d1_eq: \"st.d1 = 2\"\n    by (simp add: st.d1_def st.dims1_def nths_def)\n  have \"st.encode1 i < st.d1\"\n    by (simp add: st.d_def i)\n  then have i1_lt: \"st.encode1 i < 2\"\n    using d1_eq by auto\n  have d2_eq: \"st.d2 = 2\"\n    by (simp add: st.d2_def st.dims2_def nths_def)\n  have \"st.encode2 i < st.d2\"\n    by (simp add: st.d_def i)\n  then have i2_lt: \"st.encode2 i < 2\"\n    using d2_eq by auto\n  show \"ket_plus $ st.encode1 i * ket_plus $ st.encode2 i * 2 = 1\"\n    by (auto simp add: i1_lt i2_lt)\nqed\n\ndefinition proj_plus where\n  \"proj_plus = proj ket_plus\"\n\nlemma hadamard_on_zero:\n  \"hadamard *\\<^sub>v ket_zero = ket_plus\"\n  unfolding hadamard_def ket_zero_def ket_plus_def mat_of_rows_list_def  \n  apply (rule eq_vecI, auto simp add: scalar_prod_def)\n  subgoal for i\n    apply (drule less_2_cases)\n    apply (drule disjE, auto)\n    by (subst sum_le_2, auto)+.\n\nfun exH_k :: \"nat \\<Rightarrow> complex mat\" where\n  \"exH_k 0 = hadamard_on_i 0\"\n| \"exH_k (Suc k) = exH_k k * hadamard_on_i (Suc k)\"\n\nfun H_k :: \"nat \\<Rightarrow> complex mat\" where\n  \"H_k 0 = hadamard\"\n| \"H_k (Suc k) = ptensor_mat dims {0..<Suc k} {Suc k} (H_k k) hadamard\"\n\nlemma H_k_dim:\n  \"k < n \\<Longrightarrow> H_k k \\<in> carrier_mat (2^(Suc k)) (2^(Suc k))\"\nproof (induct k)\n  case 0\n  then show ?case using hadamard_dim by auto\nnext\n  case (Suc k)\n  interpret st: partial_state2 dims \"{0..<(Suc k)}\" \"{Suc k}\"\n    apply unfold_locales by auto\n  have \"Suc (Suc k) \\<le> n\" using Suc by auto\n  then have \"nths dims ({0..<Suc (Suc k)}) = replicate (Suc (Suc k)) 2\" using dims_nths_le_n by auto\n  moreover have \"prod_list (replicate l 2) = 2^l\" for l by simp\n  moreover have \"{0..<Suc k} \\<union> {Suc k} = {0..<(Suc (Suc k))}\" by auto\n  ultimately have plssk: \"prod_list (nths dims ({0..<Suc k} \\<union> {Suc k})) = 2^(Suc (Suc k))\" by auto\n  have \"dim_col (H_k (Suc k)) = 2^(Suc (Suc k))\" using st.ptensor_mat_dim_col unfolding st.d0_def st.dims0_def st.vars0_def using plssk by auto\n  moreover have \"dim_row (H_k (Suc k)) = 2^(Suc (Suc k))\" using st.ptensor_mat_dim_row unfolding st.d0_def st.dims0_def st.vars0_def using plssk by auto\n  ultimately show ?case by auto\nqed\n\nlemma exH_k_eq_H_k:\n  \"k < n \\<Longrightarrow> exH_k k = pmat_extension dims {0..<(Suc k)} {(Suc k)..<n} (H_k k)\"\nproof(induct k)\n  case 0\n  have \"{(Suc 0)..<n} = vars1 - {0..<(Suc 0)}\" using vars1_def by fastforce\n  then show ?case unfolding exH_k.simps using vars1_def by auto\nnext\n  case (Suc k)\n  interpret st: partial_state2 dims \"{0..<Suc k}\" \"{(Suc k)..<n}\"\n    apply unfold_locales by auto\n  interpret st1: partial_state2 dims \"{Suc k}\" \"{(Suc (Suc k))..<n}\"\n    apply unfold_locales by auto\n  interpret st2: partial_state2 dims \"{Suc k}\" \"vars1 - {Suc k}\"\n    apply unfold_locales by auto\n  interpret st3: partial_state2 dims \"{0..<Suc k}\" \"{Suc (Suc k)..<n}\"\n    apply unfold_locales by auto\n  interpret st4: partial_state2 dims \"{0..<Suc (Suc k)}\" \"{Suc (Suc k)..<n}\"\n    apply unfold_locales by auto\n\n  from Suc have eq0: \"exH_k (Suc k) \n    = (st.pmat_extension (H_k k)) * (st2.pmat_extension hadamard)\" by auto\n  have \"vars1 - {0..<Suc k} = {(Suc k)..<n}\" using vars1_def by auto\n\n  then have eql1: \"st.pmat_extension (H_k k) = st.ptensor_mat (H_k k) (1\\<^sub>m st.d2)\"\n    using st.pmat_extension_def by auto\n\n  from dims_nths_one_lt_n[OF Suc(2)] have st1d1: \"st1.d1 = 2\" unfolding st1.d1_def st1.dims1_def by fastforce\n  have \"{Suc k} \\<union> {Suc (Suc k)..<n} = {Suc k..<n}\" using Suc by auto\n  then have \"st1.d0 = st.d2\" unfolding st1.d0_def st1.dims0_def st1.vars0_def st.d2_def st.dims2_def by fastforce\n  then have eql2: \"st1.ptensor_mat (1\\<^sub>m 2) (1\\<^sub>m st1.d2) = 1\\<^sub>m st.d2\"\n    using st1.ptensor_mat_id st1d1 by auto\n  have eql3: \"st.ptensor_mat (H_k k) (1\\<^sub>m st.d2) = st.ptensor_mat (H_k k) (st1.ptensor_mat (1\\<^sub>m 2) (1\\<^sub>m st1.d2))\"\n    apply (subst eql2[symmetric]) by auto\n\n  have eqr1: \"(st2.pmat_extension hadamard) = st2.ptensor_mat hadamard (1\\<^sub>m st2.d2)\" using st2.pmat_extension_def by auto\n  have splitset: \"{0..<Suc k} \\<union> {Suc (Suc k)..<n} = vars1 - {Suc k}\" unfolding vars1_def using Suc(2) by auto\n\n  have Sksplit: \"{Suc k} \\<union> {Suc (Suc k)..<n} = {Suc k..<n}\" using Suc(2) by auto\n  have Sksplit1: \"{0..<Suc k}\\<union>{Suc k} = {0..<Suc (Suc k)}\" by auto\n  have \"st.ptensor_mat (H_k k) (st1.ptensor_mat (1\\<^sub>m 2) (1\\<^sub>m st1.d2)) \n    = ptensor_mat dims ({0..<Suc k}\\<union>{Suc k}) {Suc (Suc k)..<n} (ptensor_mat dims {0..<Suc k} {Suc k} (H_k k) (1\\<^sub>m 2)) (1\\<^sub>m st1.d2)\"\n    apply (subst ptensor_mat_assoc[symmetric, of \"{0..<Suc k}\" \"{Suc k}\" \"{Suc (Suc k)..<n}\" \"H_k k\" \"1\\<^sub>m 2\" \"1\\<^sub>m st1.d2\", simplified Sksplit])\n    using Suc length_dims by auto\n  also have \"\\<dots> = ptensor_mat dims ({0..<Suc k}\\<union>{Suc k}) {Suc (Suc k)..<n} (ptensor_mat dims {Suc k} {0..<Suc k} (1\\<^sub>m 2) (H_k k)) (1\\<^sub>m st1.d2)\"\n    using ptensor_mat_comm[of \"{0..<Suc k}\" \"{Suc k}\"] by auto\n  also have \"\\<dots> = ptensor_mat dims {Suc k} ({0..<Suc k} \\<union> {Suc (Suc k)..<n})\n                  (1\\<^sub>m 2) \n                  (ptensor_mat dims {0..<Suc k} {Suc (Suc k)..<n} (H_k k) (1\\<^sub>m st1.d2))\"\n    apply (subst sup_commute)\n    apply (subst ptensor_mat_assoc[of \"{Suc k}\" \"{0..<Suc k}\" \"{Suc (Suc k)..<n}\" \"(1\\<^sub>m 2)\" \"H_k k\" \"1\\<^sub>m st1.d2\"])\n    using Suc length_dims by auto\n  finally have eql4: \"st.pmat_extension (H_k k) \n    = st2.ptensor_mat (1\\<^sub>m 2) (st3.ptensor_mat (H_k k) (1\\<^sub>m st3.d2))\" using eql1 eql3 splitset by auto\n\n  have \"st2.ptensor_mat (1\\<^sub>m 2) (st3.ptensor_mat (H_k k) (1\\<^sub>m st3.d2)) * st2.ptensor_mat hadamard (1\\<^sub>m st2.d2)\n        = st2.ptensor_mat ((1\\<^sub>m 2)*hadamard) ((st3.ptensor_mat (H_k k) (1\\<^sub>m st3.d2))*(1\\<^sub>m st2.d2))\"\n    apply (rule st2.ptensor_mat_mult[symmetric, of \"1\\<^sub>m 2\" \"hadamard\" \"(st3.ptensor_mat (H_k k) (1\\<^sub>m st3.d2))\" \"(1\\<^sub>m st2.d2)\"])\n    subgoal unfolding st2.d1_def st2.dims1_def\n      by (simp add: dims_nths_one_lt_n Suc(2))\n    subgoal unfolding st2.d1_def st2.dims1_def\n      apply (simp add: dims_nths_one_lt_n Suc(2)) using hadamard_dim by auto\n    subgoal unfolding st2.d2_def[unfolded st2.dims2_def]\n      using st3.ptensor_mat_dim_col[unfolded st3.d0_def st3.dims0_def st3.vars0_def, simplified splitset]\n        st3.ptensor_mat_dim_row[unfolded st3.d0_def st3.dims0_def st3.vars0_def, simplified splitset] by auto\n    by auto\n  also have \"\\<dots> = st2.ptensor_mat (hadamard) (st3.ptensor_mat (H_k k) (1\\<^sub>m st3.d2))\"\n    unfolding st2.d2_def[unfolded st2.dims2_def]\n    using hadamard_dim st3.ptensor_mat_dim_col[unfolded st3.d0_def st3.dims0_def st3.vars0_def, simplified splitset]\n        st3.ptensor_mat_dim_row[unfolded st3.d0_def st3.dims0_def st3.vars0_def, simplified splitset] by auto\n  also have \"\\<dots> = ptensor_mat dims ({0..<Suc k}\\<union>{Suc k}) {Suc (Suc k)..<n} (ptensor_mat dims {Suc k} {0..<Suc k} hadamard (H_k k)) (1\\<^sub>m st3.d2)\"\n    apply (subst ptensor_mat_assoc[symmetric, of \"{Suc k}\" \"{0..<Suc k}\" \"{Suc (Suc k)..<n}\" \"hadamard\" \"H_k k\" \"1\\<^sub>m st3.d2\", simplified splitset]) \n    using Suc length_dims by auto\n  also have \"\\<dots> = ptensor_mat dims ({0..<Suc k}\\<union>{Suc k}) {Suc (Suc k)..<n} (H_k (Suc k)) (1\\<^sub>m st3.d2)\"\n    using ptensor_mat_comm[of \"{Suc k}\"] Sksplit1 by auto\n  also have \"\\<dots> = ptensor_mat dims ({0..<Suc (Suc k)}) {Suc (Suc k)..<n} (H_k (Suc k)) (1\\<^sub>m st3.d2)\" using Sksplit1 by auto\n  also have \"\\<dots> = pmat_extension dims {0..<Suc (Suc k)} {Suc (Suc k)..<n} (H_k (Suc k))\" \n    unfolding st4.pmat_extension_def by auto\n  finally show ?case using eq0 eql4 eqr1 by auto\nqed\n\nlemma mult_exH_k_left:\n  assumes \"Suc k < n\"\n  shows \"hadamard_on_i (Suc k) * exH_k k = exH_k (Suc k)\"\nproof -\n  interpret st: partial_state2 dims \"{0..<Suc k}\" \"{(Suc k)..<n}\"\n    apply unfold_locales by auto\n  interpret st1: partial_state2 dims \"{Suc k}\" \"{(Suc (Suc k))..<n}\"\n    apply unfold_locales by auto\n  interpret st2: partial_state2 dims \"{Suc k}\" \"vars1 - {Suc k}\"\n    apply unfold_locales by auto\n  interpret st3: partial_state2 dims \"{0..<Suc k}\" \"{Suc (Suc k)..<n}\"\n    apply unfold_locales by auto\n  interpret st4: partial_state2 dims \"{0..<Suc (Suc k)}\" \"{Suc (Suc k)..<n}\"\n    apply unfold_locales by auto\n\n  from exH_k_eq_H_k assms have eq0: \"exH_k (Suc k) \n    = (st.pmat_extension (H_k k)) * (st2.pmat_extension hadamard)\" by auto\n  have \"vars1 - {0..<Suc k} = {(Suc k)..<n}\" using vars1_def by auto\n\n  then have eql1: \"st.pmat_extension (H_k k) = st.ptensor_mat (H_k k) (1\\<^sub>m st.d2)\"\n    using st.pmat_extension_def by auto\n\n  from dims_nths_one_lt_n[OF assms] have st1d1: \"st1.d1 = 2\" unfolding st1.d1_def st1.dims1_def by fastforce\n  have \"{Suc k} \\<union> {Suc (Suc k)..<n} = {Suc k..<n}\" using assms by auto\n  then have \"st1.d0 = st.d2\" unfolding st1.d0_def st1.dims0_def st1.vars0_def st.d2_def st.dims2_def by fastforce\n  then have eql2: \"st1.ptensor_mat (1\\<^sub>m 2) (1\\<^sub>m st1.d2) = 1\\<^sub>m st.d2\"\n    using st1.ptensor_mat_id st1d1 by auto\n  have eql3: \"st.ptensor_mat (H_k k) (1\\<^sub>m st.d2) = st.ptensor_mat (H_k k) (st1.ptensor_mat (1\\<^sub>m 2) (1\\<^sub>m st1.d2))\"\n    apply (subst eql2[symmetric]) by auto\n\n  have eqr1: \"(st2.pmat_extension hadamard) = st2.ptensor_mat hadamard (1\\<^sub>m st2.d2)\" using st2.pmat_extension_def by auto\n  have splitset: \"{0..<Suc k} \\<union> {Suc (Suc k)..<n} = vars1 - {Suc k}\" unfolding vars1_def using assms by auto\n\n  have Sksplit: \"{Suc k} \\<union> {Suc (Suc k)..<n} = {Suc k..<n}\" using assms by auto\n  have Sksplit1: \"{0..<Suc k}\\<union>{Suc k} = {0..<Suc (Suc k)}\" by auto\n  have \"st.ptensor_mat (H_k k) (st1.ptensor_mat (1\\<^sub>m 2) (1\\<^sub>m st1.d2)) \n    = ptensor_mat dims ({0..<Suc k}\\<union>{Suc k}) {Suc (Suc k)..<n} (ptensor_mat dims {0..<Suc k} {Suc k} (H_k k) (1\\<^sub>m 2)) (1\\<^sub>m st1.d2)\"\n    apply (subst ptensor_mat_assoc[symmetric, of \"{0..<Suc k}\" \"{Suc k}\" \"{Suc (Suc k)..<n}\" \"H_k k\" \"1\\<^sub>m 2\" \"1\\<^sub>m st1.d2\", simplified Sksplit])\n    using assms length_dims by auto\n  also have \"\\<dots> = ptensor_mat dims ({0..<Suc k}\\<union>{Suc k}) {Suc (Suc k)..<n} (ptensor_mat dims {Suc k} {0..<Suc k} (1\\<^sub>m 2) (H_k k)) (1\\<^sub>m st1.d2)\"\n    using ptensor_mat_comm[of \"{0..<Suc k}\" \"{Suc k}\"] by auto\n  also have \"\\<dots> = ptensor_mat dims {Suc k} ({0..<Suc k} \\<union> {Suc (Suc k)..<n})\n                  (1\\<^sub>m 2) \n                  (ptensor_mat dims {0..<Suc k} {Suc (Suc k)..<n} (H_k k) (1\\<^sub>m st1.d2))\"\n    apply (subst sup_commute)\n    apply (subst ptensor_mat_assoc[of \"{Suc k}\" \"{0..<Suc k}\" \"{Suc (Suc k)..<n}\" \"(1\\<^sub>m 2)\" \"H_k k\" \"1\\<^sub>m st1.d2\"]) using assms length_dims by auto\n  finally have \"st.pmat_extension (H_k k) \n    = st2.ptensor_mat (1\\<^sub>m 2) (st3.ptensor_mat (H_k k) (1\\<^sub>m st3.d2))\" using eql1 eql3 splitset by auto\n  moreover have \"st.pmat_extension (H_k k) = exH_k k\" using exH_k_eq_H_k assms by auto\n  ultimately have eql4: \"exH_k k = st2.ptensor_mat (1\\<^sub>m 2) (st3.ptensor_mat (H_k k) (1\\<^sub>m st3.d2))\" by auto\n\n  have \"st2.ptensor_mat hadamard (1\\<^sub>m st2.d2) * st2.ptensor_mat (1\\<^sub>m 2) (st3.ptensor_mat (H_k k) (1\\<^sub>m st3.d2))\n        = st2.ptensor_mat (hadamard*(1\\<^sub>m 2)) ((1\\<^sub>m st2.d2)* (st3.ptensor_mat (H_k k) (1\\<^sub>m st3.d2)))\"\n    apply (rule st2.ptensor_mat_mult[symmetric, of \"hadamard\" \"1\\<^sub>m 2\" \"(1\\<^sub>m st2.d2)\" \"(st3.ptensor_mat (H_k k) (1\\<^sub>m st3.d2))\"])\n    subgoal unfolding st2.d1_def st2.dims1_def apply (simp add: dims_nths_one_lt_n assms) using hadamard_dim by auto\n    subgoal unfolding st2.d1_def st2.dims1_def by (simp add: dims_nths_one_lt_n assms) \n    subgoal by auto\n    subgoal unfolding st2.d2_def[unfolded st2.dims2_def] using st3.ptensor_mat_dim_col[unfolded st3.d0_def st3.dims0_def st3.vars0_def, simplified splitset]\n        st3.ptensor_mat_dim_row[unfolded st3.d0_def st3.dims0_def st3.vars0_def, simplified splitset] by auto\n    done\n  also have \"\\<dots> = st2.ptensor_mat (hadamard) (st3.ptensor_mat (H_k k) (1\\<^sub>m st3.d2))\"\n    unfolding st2.d2_def[unfolded st2.dims2_def]\n    using hadamard_dim st3.ptensor_mat_dim_col[unfolded st3.d0_def st3.dims0_def st3.vars0_def, simplified splitset]\n        st3.ptensor_mat_dim_row[unfolded st3.d0_def st3.dims0_def st3.vars0_def, simplified splitset] by auto\n  also have \"\\<dots> = ptensor_mat dims ({0..<Suc k}\\<union>{Suc k}) {Suc (Suc k)..<n} (ptensor_mat dims {Suc k} {0..<Suc k} hadamard (H_k k)) (1\\<^sub>m st3.d2)\"\n    apply (subst ptensor_mat_assoc[symmetric, of \"{Suc k}\" \"{0..<Suc k}\" \"{Suc (Suc k)..<n}\" \"hadamard\" \"H_k k\" \"1\\<^sub>m st3.d2\", simplified splitset]) \n    using assms length_dims by auto\n  also have \"\\<dots> = ptensor_mat dims ({0..<Suc k}\\<union>{Suc k}) {Suc (Suc k)..<n} (H_k (Suc k)) (1\\<^sub>m st3.d2)\"\n    using ptensor_mat_comm[of \"{Suc k}\"] Sksplit1 by auto\n  also have \"\\<dots> = ptensor_mat dims ({0..<Suc (Suc k)}) {Suc (Suc k)..<n} (H_k (Suc k)) (1\\<^sub>m st3.d2)\" using Sksplit1 by auto\n  also have \"\\<dots> = pmat_extension dims {0..<Suc (Suc k)} {Suc (Suc k)..<n} (H_k (Suc k))\" \n    unfolding st4.pmat_extension_def by auto\n  also have \"\\<dots> = exH_k (Suc k)\" using exH_k_eq_H_k[of \"Suc k\"] assms by auto\n  finally have \"st2.ptensor_mat hadamard (1\\<^sub>m st2.d2) * st2.ptensor_mat (1\\<^sub>m 2) (st3.ptensor_mat (H_k k) (1\\<^sub>m st3.d2)) \n    =exH_k (Suc k)\".\n  then show ?thesis unfolding hadamard_on_i_def\n    using eql4 eqr1 by auto \nqed\n\nlemma exH_eq_H:\n  \"exH_k (n - 1) = H_k (n - 1)\"\nproof -\n  have \"\\<exists>m. n = Suc (Suc m)\" using n by presburger\n  then obtain m where m: \"n = Suc (Suc m)\" using n by auto\n  then have \"exH_k m = pmat_extension dims {0..<(Suc m)} {(Suc m)..<n} (H_k m)\" using exH_k_eq_H_k by auto\n  then have \"exH_k (Suc m) = pmat_extension dims {0..<(Suc m)} {(Suc m)..<n} (H_k m) \n                            * (pmat_extension dims {Suc m} (vars1 - {Suc m}) hadamard)\" by auto\n  moreover have \"{(Suc m)..<n} = {Suc m}\" using m by auto\n  moreover have \"vars1 - {Suc m} = {0..<Suc m}\" unfolding vars1_def using m by auto\n  ultimately have eqSm: \"exH_k (Suc m) = pmat_extension dims {0..<(Suc m)} {Suc m} (H_k m) \n                            * (pmat_extension dims {Suc m} {0..<Suc m} hadamard)\" by auto\n\n  interpret stm1: partial_state2 dims \"{Suc m}\" \"{0..<Suc m}\" \n    apply unfold_locales by auto\n  interpret stm2: partial_state2 dims \"{0..<Suc m}\" \"{Suc m}\"\n    apply unfold_locales by auto\n  have \"nths dims {0..<Suc m} = replicate (Suc m) 2\" using dims_nths_le_n m by auto\n  then have stm2d1: \"stm2.d1 = 2^(Suc m)\" unfolding stm2.d1_def stm2.dims1_def by auto\n  have stm2d2: \"stm2.d2 = 2\" unfolding stm2.d2_def stm2.dims2_def using dims_nths_one_lt_n m by auto\n\n  have \"m < n\" using m by auto\n  then have \"H_k m \\<in> carrier_mat (2^(Suc m)) (2^(Suc m))\" using H_k_dim by auto\n  then have Hkm1: \"(H_k m) * (1\\<^sub>m stm2.d1) = (H_k m)\" unfolding stm2d1 by auto\n\n  have eqd12: \"stm1.d2 = stm2.d1\" unfolding stm1.d2_def stm1.dims2_def stm2.d1_def stm2.dims1_def by auto\n  have \"pmat_extension dims {Suc m} {0..<Suc m} hadamard = stm1.ptensor_mat hadamard (1\\<^sub>m stm1.d2)\" using stm1.pmat_extension_def by auto\n  also have \"\\<dots> = stm2.ptensor_mat (1\\<^sub>m stm2.d1) hadamard\" using ptensor_mat_comm eqd12 by auto\n  finally have eqr: \"(pmat_extension dims {Suc m} {0..<Suc m} hadamard) = stm2.ptensor_mat (1\\<^sub>m stm2.d1) hadamard\".\n  then have \"exH_k (Suc m) = stm2.ptensor_mat (H_k m) (1\\<^sub>m stm2.d2) * stm2.ptensor_mat (1\\<^sub>m stm2.d1) hadamard\" \n    using eqSm unfolding stm2.pmat_extension_def by auto\n  also have \"\\<dots> = stm2.ptensor_mat ((H_k m) * (1\\<^sub>m stm2.d1)) (1\\<^sub>m stm2.d2 * hadamard)\" \n    apply (rule stm2.ptensor_mat_mult[symmetric, of \"H_k m\" \"1\\<^sub>m stm2.d1\" \"1\\<^sub>m stm2.d2\" \"hadamard\"])\n    unfolding stm2d1 stm2d2 using H_k_dim m hadamard_dim by auto\n  also have \"\\<dots> = stm2.ptensor_mat (H_k m) (hadamard)\" using H_k_dim hadamard_dim stm2d1 stm2d2 Hkm1 by auto\n  also have \"\\<dots> = H_k (Suc m)\" unfolding stm2.ptensor_mat_def H_k.simps by auto\n  finally have  \"exH_k (Suc m) = H_k (Suc m)\" by auto\n  moreover have \"Suc m = n - 1\" using m by auto\n  ultimately show ?thesis by auto\nqed\n\nfun ket_zero_k :: \"nat \\<Rightarrow> complex vec\" where\n  \"ket_zero_k 0 = ket_zero\"\n| \"ket_zero_k (Suc k) = ptensor_vec dims {0..<(Suc k)} {Suc k} (ket_zero_k k) ket_zero\"\n\nlemma ket_zero_k_dim:\n  assumes \"k < n\"\n  shows \"ket_zero_k k \\<in> carrier_vec (2^(Suc k))\"\nproof (cases k)\n  case 0\n  show ?thesis using ket_zero_dim 0 by auto\nnext\n  case (Suc k)\n  interpret st: partial_state2 dims \"{0..<(Suc k)}\" \"{Suc k}\"\n    apply unfold_locales by auto\n  have \"Suc (Suc k) \\<le> n\" using assms Suc by auto\n  then have \"nths dims ({0..<Suc (Suc k)}) = replicate (Suc (Suc k)) 2\" using dims_nths_le_n by auto\n  moreover have \"prod_list (replicate l 2) = 2^l\" for l by simp\n  moreover have \"{0..<Suc k} \\<union> {Suc k} = {0..<(Suc (Suc k))}\" by auto\n  ultimately have plssk: \"prod_list (nths dims ({0..<Suc k} \\<union> {Suc k})) = 2^(Suc (Suc k))\" by auto\n  show ?thesis apply (rule carrier_vecI) unfolding ket_zero_k.simps Suc\n    using st.ptensor_vec_dim[of \"ket_zero_k k\" ket_zero] plssk unfolding st.d0_def st.dims0_def st.vars0_def by auto\nqed\n\nfun ket_plus_k where\n  \"ket_plus_k 0 = ket_plus\"\n| \"ket_plus_k (Suc k) = ptensor_vec dims {0..<(Suc k)} {Suc k} (ket_plus_k k) ket_plus\"\n\nlemma ket_plus_k_dim:\n  assumes \"k < n\"\n  shows \"ket_plus_k k \\<in> carrier_vec (2^(Suc k))\"\nproof (cases k)\n  case 0\n  show ?thesis using ket_plus_dim 0 by auto\nnext\n  case (Suc k)\n  interpret st: partial_state2 dims \"{0..<(Suc k)}\" \"{Suc k}\"\n    apply unfold_locales by auto\n  have \"Suc (Suc k) \\<le> n\" using assms Suc by auto\n  then have \"nths dims ({0..<Suc (Suc k)}) = replicate (Suc (Suc k)) 2\" using dims_nths_le_n by auto\n  moreover have \"prod_list (replicate l 2) = 2^l\" for l by simp\n  moreover have \"{0..<Suc k} \\<union> {Suc k} = {0..<(Suc (Suc k))}\" by auto\n  ultimately have plssk: \"prod_list (nths dims ({0..<Suc k} \\<union> {Suc k})) = 2^(Suc (Suc k))\" by auto\n  show ?thesis apply (rule carrier_vecI) unfolding ket_zero_k.simps Suc\n    using st.ptensor_vec_dim plssk unfolding st.d0_def st.dims0_def st.vars0_def by auto\nqed\n\n\nlemma H_k_ket_zero_k:\n  \"k < n \\<Longrightarrow> (H_k k) *\\<^sub>v (ket_zero_k k) = (ket_plus_k k)\"\nproof (induct k)\n  case 0\n  show ?case using hadamard_on_zero unfolding H_k.simps ket_zero_k.simps ket_plus_k.simps by auto\nnext\n  case (Suc k)\n  then have k: \"k < n\" by auto\n  interpret st: partial_state2 dims \"{0..<(Suc k)}\" \"{Suc k}\"\n    apply unfold_locales by auto\n  have \"nths dims {0..<Suc k} = replicate (Suc k) 2\" using dims_nths_le_n Suc by auto\n  then have std1: \"st.d1 = 2^(Suc k)\" unfolding st.d1_def st.dims1_def by auto\n  have std2: \"st.d2 = 2\" unfolding st.d2_def st.dims2_def using dims_nths_one_lt_n Suc by auto\n  have \"H_k (Suc k) *\\<^sub>v ket_zero_k (Suc k) = st.ptensor_mat (H_k k) hadamard *\\<^sub>v st.ptensor_vec (ket_zero_k k) ket_zero\" by auto\n  also have \"\\<dots> = st.ptensor_vec ((H_k k) *\\<^sub>v (ket_zero_k k)) (hadamard *\\<^sub>v ket_zero)\" \n    using st.ptensor_mat_mult_vec[unfolded std1 std2, OF H_k_dim[OF k] ket_zero_k_dim[OF k] hadamard_dim ket_zero_dim] by auto\n  also have \"\\<dots> = st.ptensor_vec (ket_plus_k k) ket_plus\" using Suc hadamard_on_zero by auto\n  finally show ?case by auto\nqed\n\n\nlemma encode1_replicate_2:\n  \"partial_state.encode1 (replicate (Suc k) 2) {0..<k} i = i mod (2 ^ k)\"\nproof -\n  have take_Suc: \"take k (replicate (Suc k) 2) = replicate k 2\"\n    apply (subst take_replicate) by auto\n  have take_encode: \"take k (digit_encode (replicate (Suc k) 2) i) = digit_encode (replicate k 2) i\"\n    apply (subst digit_encode_take) using take_Suc by metis\n  show ?thesis\n    unfolding partial_state.encode1_def partial_state.dims1_def\n      nths_upt_eq_take[simplified lessThan_atLeast0] take_Suc take_encode\n      digit_decode_encode prod_list_replicate ..\nqed\n\nlemma encode2_replicate_2:\n  assumes \"i < 2 ^ Suc k\"\n  shows \"partial_state.encode2 (replicate (Suc k) 2) {0..<k} i = i div (2 ^ k)\"\nproof -\n  have drop_Suc: \"drop k (replicate (Suc k) 2) = [2]\"\n    apply (subst drop_replicate) by auto\n  have drop_encode: \"drop k (digit_encode (replicate (Suc k) 2) i) = digit_encode [2] (i div (2 ^ k))\"\n    unfolding digit_encode_drop drop_Suc take_replicate prod_list_replicate\n    by (metis lessI min.strict_order_iff)\n  have le2: \"i div 2 ^ k < 2\"\n    using assms by (auto simp add: less_mult_imp_div_less)\n  have prod_list_2: \"prod_list [2] = 2\" by simp\n  show ?thesis\n    unfolding partial_state.encode2_def partial_state.dims2_def\n      nths_minus_upt_eq_drop[simplified lessThan_atLeast0] drop_Suc drop_encode\n      digit_decode_encode prod_list_2\n    using le2 by auto\nqed\n\nlemma ket_zero_k_decode:\n  \"k < n \\<Longrightarrow> ket_zero_k k = Matrix.vec (2^(Suc k)) (\\<lambda>k. if k = 0 then 1 else 0)\"\nproof (induct k)\n  case 0                            \n  show ?case apply (rule eq_vecI) by (auto simp add: ket_zero_def)\nnext\n  case (Suc k)\n  then have k: \"k < n\" by auto\n  have kzkk: \"ket_zero_k k = Matrix.vec (2 ^ Suc k) (\\<lambda>k. if (k = 0) then 1 else 0)\" using Suc(1)[OF k] by auto\n\n  have dSk: \"ket_zero_k (Suc k) \\<in> carrier_vec (2^(Suc (Suc k)))\" using ket_zero_k_dim[OF Suc(2)] by auto\n\n  interpret st: partial_state \"replicate (Suc (Suc k)) 2\" \"{0..<Suc k}\".\n  interpret st2: partial_state2 dims \"{0..<Suc k}\" \"{Suc k}\" by (unfold_locales, auto)\n\n  have splitset: \"({0..<Suc k} \\<union> {Suc k}) = {0..<Suc (Suc k)}\" by auto\n  then have st2dims0: \"st2.dims0 = replicate (Suc (Suc k)) 2\" unfolding st2.dims0_def st2.vars0_def \n    using dims_nths_le_n[of \"Suc (Suc k)\"] Suc by auto\n  have \"\\<And>x. (x \\<in> {0..<Suc k} \\<Longrightarrow> {y \\<in> {0..<Suc (Suc k)}. y < x} = {0..<x})\" by auto\n  then have cardeq: \"\\<And>x. (x \\<in> {0..<Suc k} \\<Longrightarrow> card {y \\<in> {0..<Suc (Suc k)}. y < x} = card {0..<x})\" by auto\n  have setcong: \"\\<And>g h I. (\\<And>x. (x \\<in> I \\<Longrightarrow> g x = h x)) \\<Longrightarrow> {g x | x. x \\<in> I} = {h x | x. x \\<in> I}\" by metis\n  have \"{card {y \\<in> {0..<Suc (Suc k)}. y < x} |x. x \\<in> {0..<Suc k}} = {card {0..<x} |x. x \\<in> {0..<Suc k}} \"\n    using setcong[OF cardeq, of \"{0..<Suc k}\"] by auto\n  also have \"\\<dots> = {0..<Suc k}\" by auto\n  finally have st2vars1': \"st2.vars1' = {0..<Suc k}\" unfolding st2.vars1'_def st2.vars0_def splitset ind_in_set_def by fastforce\n  have st2pvsttv: \"st2.ptensor_vec = st.tensor_vec\" unfolding st2.ptensor_vec_def using st2dims0 st2vars1' by auto\n  have \"st.encode1 0 = 0\" using encode1_replicate_2[of \"Suc k\" 0] by auto\n  moreover have \"st.encode2 0 = 0\" using encode2_replicate_2[of 0 \"Suc k\"] by auto\n  moreover have  std: \"st.d = 2^(Suc (Suc k))\" unfolding st.d_def by auto\n  ultimately have kzkk0: \"ket_zero_k (Suc k) $ 0 = 1\" \n    unfolding ket_zero_k.simps st2pvsttv st.tensor_vec_def ket_zero_def using kzkk by auto\n\n  have kzkki: \"ket_zero_k (Suc k) $ i = 0\" if ine0: \"i \\<noteq> 0\" and ile: \"i < 2^(Suc (Suc k))\" for i\n  proof (cases \"i mod (2 ^ Suc k) \\<noteq> 0\")\n    case True\n    then have \"ket_zero_k k $ st.encode1 i = 0\" unfolding kzkk using encode1_replicate_2[of \"Suc k\" i] ile by auto\n    then show ?thesis unfolding ket_zero_k.simps st2pvsttv st.tensor_vec_def ket_zero_def std using ile by auto\n  next\n    case False\n    have \"i div (2 ^ Suc k) \\<noteq> 0 \\<or> i mod (2 ^ Suc k) \\<noteq> 0\" using ine0 by fastforce\n    then have \"i div (2 ^ Suc k) \\<noteq> 0\" using False by auto\n    moreover have \"i div (2 ^ Suc k) < 2\" using ile less_mult_imp_div_less by auto\n    ultimately have \"i div (2 ^ Suc k) = 1\" by auto\n    then have \"st.encode2 i = 1\" using encode2_replicate_2[of i \"Suc k\"] ile by auto\n    then have \"Matrix.vec 2 (\\<lambda>k. if k = 0 then 1 else 0) $ st.encode2 i = 0\" \n      unfolding kzkk by fastforce\n    then show ?thesis unfolding ket_zero_k.simps st2pvsttv st.tensor_vec_def ket_zero_def std using ile by auto\n  qed\n\n  show ?case apply (rule eq_vecI)\n    subgoal for i using kzkk0 kzkki by auto\n    using carrier_vecD[OF dSk] by auto\nqed\n\nlemma ket_plus_k_decode:\n  \"k < n \\<Longrightarrow> ket_plus_k k = Matrix.vec (2^(Suc k)) (\\<lambda>l. 1 / csqrt (2^(Suc k)))\"\nproof (induct k)\n  case 0\n  then show ?case unfolding ket_plus_k.simps ket_plus_def by auto\nnext\n  case (Suc k)\n  then have kpkk: \"ket_plus_k k = Matrix.vec (2 ^ Suc k) (\\<lambda>l. 1 / csqrt (2 ^ Suc k))\" by auto\n\n  have dSk: \"ket_plus_k (Suc k) \\<in> carrier_vec (2^(Suc (Suc k)))\" using ket_plus_k_dim[OF Suc(2)] by auto\n\n  interpret st: partial_state \"replicate (Suc (Suc k)) 2\" \"{0..<Suc k}\".\n  interpret st2: partial_state2 dims \"{0..<Suc k}\" \"{Suc k}\" by (unfold_locales, auto)\n\n  have splitset: \"({0..<Suc k} \\<union> {Suc k}) = {0..<Suc (Suc k)}\" by auto\n  then have st2dims0: \"st2.dims0 = replicate (Suc (Suc k)) 2\" unfolding st2.dims0_def st2.vars0_def \n    using dims_nths_le_n[of \"Suc (Suc k)\"] Suc by auto\n  have \"\\<And>x. (x \\<in> {0..<Suc k} \\<Longrightarrow> {y \\<in> {0..<Suc (Suc k)}. y < x} = {0..<x})\" by auto\n  then have cardeq: \"\\<And>x. (x \\<in> {0..<Suc k} \\<Longrightarrow> card {y \\<in> {0..<Suc (Suc k)}. y < x} = card {0..<x})\" by auto\n  have setcong: \"\\<And>g h I. (\\<And>x. (x \\<in> I \\<Longrightarrow> g x = h x)) \\<Longrightarrow> {g x | x. x \\<in> I} = {h x | x. x \\<in> I}\" by metis\n  have \"{card {y \\<in> {0..<Suc (Suc k)}. y < x} |x. x \\<in> {0..<Suc k}} = {card {0..<x} |x. x \\<in> {0..<Suc k}} \"\n    using setcong[OF cardeq, of \"{0..<Suc k}\"] by auto\n  also have \"\\<dots> = {0..<Suc k}\" by auto\n  finally have st2vars1': \"st2.vars1' = {0..<Suc k}\" unfolding st2.vars1'_def st2.vars0_def splitset ind_in_set_def by blast\n  have st2pvsttv: \"st2.ptensor_vec = st.tensor_vec\" unfolding st2.ptensor_vec_def using st2dims0 st2vars1' by auto\n\n  have \"csqrt (2 ^ (Suc k)) = complex_of_real (sqrt (2 ^ (Suc k)))\" by simp\n  moreover have \"complex_of_real (sqrt (2 ^ (Suc k))) * complex_of_real (sqrt 2) = complex_of_real (sqrt (2 ^ (Suc (Suc k))))\"\n    by (metis of_real_mult power_Suc power_commutes real_sqrt_power)\n  ultimately have \"csqrt (2 ^ (Suc k)) * csqrt 2 = csqrt (2 ^ (Suc (Suc k)))\" by auto\n  moreover have \"1 / csqrt (2 ^ Suc k) * 1 / csqrt 2 = 1 / (csqrt (2 ^ (Suc k)) * csqrt 2)\" by simp\n  ultimately have csqrt2p :\"1 / csqrt (2 ^ Suc k) * 1 / csqrt 2 = 1 / (csqrt (2 ^ (Suc (Suc k))))\" by simp\n\n  have std: \"st.d = 2^(Suc (Suc k))\" unfolding st.d_def by auto\n\n  have nthsSSk2: \"nths (replicate (Suc (Suc k)) 2) {0..<Suc k} = replicate (Suc k) 2\" \n    unfolding nths_replicate[of \"Suc (Suc k)\" 2 \"{0..<Suc k}\"]\n    by (smt Collect_cong \\<open>{card {0..<x} |x. x \\<in> {0..<Suc k}} = {0..<Suc k}\\<close> atLeastLessThan_iff card_atLeastLessThan diff_zero less_SucI)\n  then have std1: \"st.d1 = 2^(Suc k)\" unfolding st.d1_def st.dims1_def nthsSSk2 by auto\n  have \"{i. i < Suc (Suc k) \\<and> i \\<in> {Suc k..}} = {Suc k}\" by auto\n  then have \"nths (replicate (Suc (Suc k)) 2) ({Suc k..}) = replicate 1 2\" unfolding nths_replicate by auto\n  moreover have \"(- {0..<Suc k}) = {Suc k..}\" by auto\n  ultimately have nthsSSk2c: \"nths (replicate (Suc (Suc k)) 2) (- {0..<Suc k}) = replicate 1 2\" by auto\n  have std2: \"st.d2 = 2\" unfolding st.d2_def st.dims2_def apply (subst nthsSSk2c) by auto\n\n  have \"st.encode1 i < st.d1\" if \"i < st.d\" for i using that st.encode1_lt[OF that] by auto\n  then have kpkki: \"ket_plus_k k $ st.encode1 i = 1 / csqrt (2^(Suc k))\" if \"i < st.d\" for i unfolding kpkk std1 using that by auto\n  have \"st.encode2 i < st.d2\" if \"i < st.d\" for i using that st.encode2_lt[OF that] by auto\n  then have kpi: \"ket_plus $ st.encode2 i = 1 / csqrt 2\" if \"i < st.d\" for i unfolding ket_plus_def std2 using that by auto\n  have kzkki: \"ket_plus_k (Suc k) $ i = 1 / (csqrt (2 ^ (Suc (Suc k))))\" if \"i < st.d\" for i\n    unfolding ket_plus_k.simps st2pvsttv st.tensor_vec_def using csqrt2p kpkki kpi that  by auto\n  show ?case apply (rule eq_vecI)\n    subgoal for i using kzkki unfolding std by auto\n    using carrier_vecD[OF dSk] by auto\nqed\n\nlemma exH_k_mult_pre_is_psi:\n  \"exH_k (n - 1) *\\<^sub>v ket_pre = \\<psi>\"\nproof -\n  have \"exH_k (n - 1) = H_k (n - 1)\" using exH_eq_H by auto\n  moreover have \"ket_zero_k (n - 1) = ket_pre\" using ket_zero_k_decode[of \"n - 1\"] ket_pre_def N_def n by auto\n  moreover have \"ket_plus_k (n - 1) = \\<psi>\" using ket_plus_k_decode[of \"n - 1\"] \\<psi>_def N_def n by auto\n  moreover have \"H_k (n - 1) *\\<^sub>v ket_zero_k (n - 1) = ket_plus_k (n - 1)\" using H_k_ket_zero_k n by auto\n  ultimately show ?thesis by auto\nqed\n\ndefinition ket_k :: \"nat \\<Rightarrow> complex vec\" where\n  \"ket_k x = Matrix.vec K (\\<lambda>k. if k = x then 1 else 0)\"\n\nlemma ket_k_dim:\n  \"ket_k k \\<in> carrier_vec K\"\n  unfolding ket_k_def by auto\n\nlemma mat_incr_mult_ket_k:\n  \"k < K \\<Longrightarrow> (mat_incr K) *\\<^sub>v (ket_k k) = (ket_k ((k + 1) mod K))\"\n  apply (rule eq_vecI)\n  unfolding mat_incr_def ket_k_def\n   apply (simp add: scalar_prod_def)\n   apply (case_tac \"k = K - 1\")\n  subgoal for i apply auto by (simp add: sum_only_one_neq_0[of _ \"K - 1\"])\n  subgoal for i apply auto by (simp add: sum_only_one_neq_0[of _ \"i - 1\"])\n  by auto\n\ndefinition proj_k where\n  \"proj_k x = proj (ket_k x)\"\n\n\n\n\n\nlemma norm_ket_k_ge_K:\n  \"k \\<ge> K \\<Longrightarrow> inner_prod (ket_k k) (ket_k k) = 0\"\n  unfolding ket_k_def by (simp add: scalar_prod_def)\n\nlemma norm_ket_k:\n  \"inner_prod (ket_k k) (ket_k k) \\<le> 1\"\n  apply (case_tac \"k < K\")\n  using norm_ket_k_lt_K norm_ket_k_ge_K by auto\n\nlemma proj_k_mat:\n  assumes \"k < K\"\n  shows \"proj_k k = mat K K (\\<lambda>(i, j). if (i = j \\<and> i = k) then 1 else 0)\" \n  apply (rule eq_matI)\n    apply (simp add: proj_k_def ket_k_def index_outer_prod) \n  using proj_k_dim by auto\n\nlemma positive_proj_k:\n  \"positive (proj_k k)\"\n  using positive_same_outer_prod unfolding proj_k_def ket_k_def by auto \n\nlemma proj_k_le_one:\n  \"(proj_k k) \\<le>\\<^sub>L 1\\<^sub>m K\"\n  unfolding proj_k_def using outer_prod_le_one norm_ket_k ket_k_def by auto\n\ndefinition proj_psi where\n  \"proj_psi = proj \\<psi>\"\n\nlemma proj_psi_dim:\n  \"proj_psi \\<in> carrier_mat N N\"\n  unfolding proj_psi_def \\<psi>_def by auto\n\nlemma norm_psi:\n  \"inner_prod \\<psi> \\<psi> = 1\"\n  apply (simp add: \\<psi>_eval scalar_prod_def)\n  by (metis norm_of_nat norm_of_real of_real_mult of_real_of_nat_eq real_sqrt_mult_self)\n\nlemma proj_psi_mat:\n  \"proj_psi = mat N N (\\<lambda>k. 1 / N)\"\n  unfolding proj_psi_def\n  apply (rule eq_matI, simp_all)\n    apply (simp add: \\<psi>_def index_outer_prod)\n    apply (smt of_nat_less_0_iff of_real_of_nat_eq of_real_power power2_eq_square real_sqrt_pow2)\n   by (auto simp add: carrier_matD[OF outer_prod_dim[OF \\<psi>_dim(1) \\<psi>_dim(1)]])\n\nlemma hermitian_proj_psi:\n  \"hermitian proj_psi\" \n  unfolding hermitian_def proj_psi_mat apply (rule eq_matI)\n  by (auto simp add: adjoint_eval)\n\nlemma hermitian_exproj_psi:\n  \"hermitian (tensor_P proj_psi (1\\<^sub>m K))\"\n  unfolding ps2_P.ptensor_mat_def\n  apply (subst ps_P.tensor_mat_hermitian)\n  using proj_psi_dim ps_P_d1 ps_P_d2 hermitian_proj_psi hermitian_one by auto\n\nlemma proj_psi_is_projection:\n  \"proj_psi * proj_psi = proj_psi\"\nproof -\n  have \"proj_psi * proj_psi = inner_prod \\<psi> \\<psi> \\<cdot>\\<^sub>m proj_psi\"\n    unfolding proj_psi_def \n    apply (subst outer_prod_mult_outer_prod) using  \\<psi>_def by auto\n  also have \"\\<dots> = proj_psi\"\n    using \\<psi>_inner by auto\n  finally show ?thesis.\nqed\n\nlemma proj_psi_trace:\n  \"trace (proj_psi) = 1\"\n  unfolding proj_psi_def\n  apply (subst trace_outer_prod[of _ N]) \n  subgoal unfolding \\<psi>_def by auto using norm_psi by auto\n\nlemma positive_proj_psi:\n  \"positive (proj_psi)\"\n  using positive_same_outer_prod unfolding proj_psi_def \\<psi>_def by auto \n\nlemma proj_psi_le_one:\n  \"(proj_psi) \\<le>\\<^sub>L 1\\<^sub>m N\"\n  unfolding proj_psi_def using outer_prod_le_one norm_psi \\<psi>_def by auto\n\nlemma hermitian_hadamard_on_k:\n  assumes \"k < n\"\n  shows \"hermitian (hadamard_on_i k)\"\nproof -\n  interpret st2: partial_state2 dims \"{k}\" \"(vars1 - {k})\"\n    apply unfold_locales by auto\n  have st2d1: \"st2.dims1 = [2]\" unfolding st2.dims1_def dims_def\n    using assms dims_nths_one_lt_n local.dims_def st2.dims1_def by auto\n  show \"hermitian (hadamard_on_i k)\" unfolding hadamard_on_i_def st2.pmat_extension_def st2.ptensor_mat_def\n    apply (rule partial_state.tensor_mat_hermitian)\n    subgoal unfolding partial_state.d1_def partial_state.dims1_def st2.nths_vars1' hadamard_def by (simp add: st2d1)\n    subgoal unfolding partial_state.d2_def partial_state.dims2_def st2.nths_vars2' st2.d2_def by auto\n    subgoal unfolding hermitian_def hadamard_def apply (rule eq_matI) by (auto simp add: adjoint_dim adjoint_eval)\n    using hermitian_one by auto\nqed\n\nlemma hermitian_H_k:\n  \"k < n \\<Longrightarrow> hermitian (H_k k)\"\nproof (induct k)\n  case 0\n  show ?case unfolding H_k.simps hermitian_def hadamard_def apply (rule eq_matI) by (auto simp add: adjoint_dim adjoint_eval)\nnext\n  case (Suc k)\n  interpret st2: partial_state2 dims \"{0..<Suc k}\" \"{Suc k}\"\n    apply unfold_locales by auto\n  have st2d1: \"prod_list st2.dims1 = (2^(Suc k))\" unfolding st2.dims1_def dims_def using Suc(2)\n    using dims_nths_le_n local.dims_def st2.dims1_def by auto\n  have st2d2: \"st2.dims2 = [2]\" unfolding st2.dims2_def dims_def using Suc(2)\n    using dims_nths_one_lt_n local.dims_def st2.dims2_def by auto\n  show ?case unfolding H_k.simps st2.ptensor_mat_def\n    apply (rule partial_state.tensor_mat_hermitian)\n    subgoal unfolding partial_state.d1_def partial_state.dims1_def st2.nths_vars1' using st2d1 H_k_dim Suc by auto\n    subgoal unfolding partial_state.d2_def partial_state.dims2_def st2.nths_vars2' st2.d2_def using st2d2 by (simp add: hadamard_def)\n    subgoal using Suc by auto\n    using hermitian_hadamard by auto\nqed\n\nlemma unitary_H_k:\n  \"k < n \\<Longrightarrow> unitary (H_k k)\"\nproof (induct k)\n  case 0\n  show ?case using unitary_hadamard by auto\nnext\n  case (Suc k)\n  then have k: \"k < n\" by auto\n  interpret st2: partial_state2 dims \"{0..<Suc k}\" \"{Suc k}\" by (unfold_locales, auto)\n\n  have st2d1: \"prod_list st2.dims1 = (2^(Suc k))\" unfolding st2.dims1_def dims_def using Suc(2)\n    using dims_nths_le_n local.dims_def st2.dims1_def by auto\n  have st2d2: \"st2.dims2 = [2]\" unfolding st2.dims2_def dims_def using Suc(2)\n    using dims_nths_one_lt_n local.dims_def st2.dims2_def by auto\n  show ?case unfolding H_k.simps st2.ptensor_mat_def\n    apply (rule partial_state.tensor_mat_unitary[of \"H_k k\" st2.dims0 st2.vars1' hadamard]  )\n    unfolding partial_state.d1_def partial_state.dims1_def st2.nths_vars1' partial_state.d2_def partial_state.dims2_def\n      st2.nths_vars2'\n       apply (auto simp add: st2d1 st2d2 )\n    subgoal using H_k_dim[OF k] by auto\n    subgoal using hadamard_dim by auto\n    subgoal using Suc by auto\n    using unitary_hadamard by auto\nqed\n\nlemma exH_k_dim:\n  shows \"k < n \\<Longrightarrow> exH_k k \\<in> carrier_mat N N\"\n  apply (induct k)\n  using hadamard_on_i_dim by auto\n\nlemma exH_n_dim:\n  shows \"exH_k (n - 1) \\<in> carrier_mat N N\"\n  using exH_k_dim n by auto\n\nlemma unitary_exH_k:\n  shows \"k < n \\<Longrightarrow> unitary (exH_k k)\" \nproof (induct k)\n  case 0\n  then show ?case unfolding exH_k.simps using unitary_hadamard_on_i 0 by auto \nnext\n  case (Suc k)\n  show ?case unfolding exH_k.simps apply (subst unitary_times_unitary[of _ N])\n    subgoal using exH_k_dim Suc by auto\n    subgoal using hadamard_on_i_dim Suc by auto\n    subgoal using Suc by auto\n    using unitary_hadamard_on_i Suc by auto\nqed\n\nlemma hermitian_exH_n:\n  \"hermitian (exH_k (n - 1))\"\n  using hermitian_H_k exH_eq_H n by auto\n\n\n\nfun exexH_k :: \"nat \\<Rightarrow> complex mat\" where\n  \"exexH_k k = tensor_P (exH_k k) (1\\<^sub>m K)\"\n\nlemma unitary_exexH_k:\n  \"k < n \\<Longrightarrow> unitary (exexH_k k)\" \n  unfolding exexH_k.simps ps2_P.ptensor_mat_def \n  apply (subst partial_state.tensor_mat_unitary)\n  subgoal using exH_k_dim unfolding partial_state.d1_def partial_state.dims1_def ps2_P.nths_vars1' ps2_P.dims1_def dims_vars1 N_def by auto\n  subgoal unfolding partial_state.d2_def partial_state.dims2_def ps2_P.nths_vars2' ps2_P.dims2_def dims_vars2 by auto\n  using unitary_exH_k unitary_one by auto\n\nlemma exexH_k_dim:\n  \"k < n \\<Longrightarrow> exexH_k k \\<in> carrier_mat d d\"\n  unfolding exexH_k.simps using ps2_P.ptensor_mat_carrier ps2_P_d0 by auto\n\nlemma hoare_seq_utrans:\n  fixes P :: \"complex mat\"\n  assumes \"unitary U1\" and \"unitary U2\" and \"is_quantum_predicate P\"\n    and dU1: \"U1 \\<in> carrier_mat d d\" and dU2: \"U2 \\<in> carrier_mat d d\"\n  shows \"\n   \\<turnstile>\\<^sub>p \n   {adjoint (U2 * U1) * P * (U2 * U1)} \n   Utrans U1;; Utrans U2\n   {P}\"\nproof -\n  have hp0: \"\\<turnstile>\\<^sub>p {adjoint (U2) * P * (U2)} Utrans U2 {P}\"\n    using assms hoare_partial.intros by auto\n  have qp: \"is_quantum_predicate (adjoint (U2) * P * (U2))\"\n    using qp_close_under_unitary_operator assms by auto\n  then have hp1: \"\\<turnstile>\\<^sub>p {adjoint U1 * (adjoint (U2) * P * (U2)) * U1} Utrans U1 {adjoint (U2) * P * (U2)}\"\n    using hoare_partial.intros by auto\n  have dP: \"P \\<in> carrier_mat d d\" using assms is_quantum_predicate_def by auto\n  have eq: \"adjoint U1 * (adjoint U2 * P * U2) * U1 = adjoint (U2 * U1) * P * (U2 * U1)\"\n    using dU1 dU2 dP by (mat_assoc d)\n  with hp1 have hp2: \"\\<turnstile>\\<^sub>p {adjoint (U2 * U1) * P * (U2 * U1)} Utrans U1 {adjoint (U2) * P * (U2)}\" by auto\n\n  have \"is_quantum_predicate (adjoint U1 * (adjoint U2 * P * U2) * U1)\" using qp qp_close_under_unitary_operator assms by auto\n  then have \"is_quantum_predicate (adjoint (U2 * U1) * P * (U2 * U1))\" using eq by auto\n  then show ?thesis using hoare_partial.intros(3)[OF _ qp assms(3)] hp0 hp2 by auto\nqed\n\nlemma qp_close_after_exexH_k:\n  fixes P :: \"complex mat\"\n  assumes \"is_quantum_predicate P\"\n  shows \"k < n \\<Longrightarrow> is_quantum_predicate (adjoint (exexH_k k) * P * exexH_k k)\"\n  apply (subst qp_close_under_unitary_operator)\n  subgoal using exexH_k_dim by auto\n  subgoal using unitary_exexH_k by auto\n  using assms by auto\n\nlemma hoare_hadamard_n:\n  fixes P :: \"complex mat\"\n  shows \"is_quantum_predicate P \\<Longrightarrow> k < n \\<Longrightarrow> \n   \\<turnstile>\\<^sub>p \n   {adjoint (exexH_k k) * P * exexH_k k} \n   hadamard_n (Suc k)\n   {P}\"\nproof (induct k arbitrary: P)\n  case 0\n  have qp: \"is_quantum_predicate (adjoint (exexH_k 0) * P * exexH_k 0)\"\n    using qp_close_under_unitary_operator[OF _ unitary_exhadamard_on_i[of 0]] tensor_P_dim 0 by auto\n  then have \"\\<turnstile>\\<^sub>p {adjoint (exexH_k 0) * P * exexH_k 0} SKIP {adjoint (exexH_k 0) * P * exexH_k 0}\"\n    using hoare_partial.intros(1) by auto\n  moreover have \"\\<turnstile>\\<^sub>p {adjoint (exexH_k 0) * P * exexH_k 0} Utrans (tensor_P (hadamard_on_i 0) (1\\<^sub>m K)) {P}\"\n    using hoare_partial.intros(2) 0 by auto\n  ultimately have \"\\<turnstile>\\<^sub>p {adjoint (exexH_k 0) * P * exexH_k 0} SKIP;; Utrans (tensor_P (hadamard_on_i 0) (1\\<^sub>m K)) {P}\"\n    using hoare_partial.intros(3) qp 0 by auto\n  then show ?case using qp by auto\nnext\n  case (Suc k)\n  have h1: \"\\<turnstile>\\<^sub>p \n    {adjoint (tensor_P (hadamard_on_i (Suc k)) (1\\<^sub>m K)) * P * (tensor_P (hadamard_on_i (Suc k)) (1\\<^sub>m K))} \n    Utrans (tensor_P (hadamard_on_i (Suc k)) (1\\<^sub>m K)) \n    {P}\"\n    using hoare_partial.intros Suc by auto\n  have qp: \"is_quantum_predicate (adjoint (tensor_P (hadamard_on_i (Suc k)) (1\\<^sub>m K)) * P * (tensor_P (hadamard_on_i (Suc k)) (1\\<^sub>m K)))\"\n    apply (subst qp_close_under_unitary_operator)\n    subgoal using ps2_P.ptensor_mat_carrier ps2_P_d0 by auto\n    subgoal unfolding ps2_P.ptensor_mat_def apply (subst partial_state.tensor_mat_unitary ) \n      subgoal unfolding partial_state.d1_def partial_state.dims1_def ps2_P.nths_vars1' ps2_P.dims1_def d_vars1 using hadamard_on_i_dim Suc by auto\n      subgoal unfolding partial_state.d2_def partial_state.dims2_def ps2_P.nths_vars2' ps2_P.dims2_def using dims_vars2 by auto\n      using unitary_hadamard_on_i unitary_one Suc by auto\n    using Suc by auto\n  then have h2: \"\\<turnstile>\\<^sub>p \n    {adjoint (exexH_k k) * (adjoint (tensor_P (hadamard_on_i (Suc k)) (1\\<^sub>m K)) * P * (tensor_P (hadamard_on_i (Suc k)) (1\\<^sub>m K))) * exexH_k k} \n    hadamard_n (Suc k)\n    {adjoint (tensor_P (hadamard_on_i (Suc k)) (1\\<^sub>m K)) * P * (tensor_P (hadamard_on_i (Suc k)) (1\\<^sub>m K))}\"\n    using Suc by auto\n  have \"(tensor_P (hadamard_on_i (Suc k)) (1\\<^sub>m K)) * exexH_k k\n    = (tensor_P (hadamard_on_i (Suc k) * (exH_k k)) (1\\<^sub>m K * (1\\<^sub>m K)))\"\n    apply (subst ps2_P.ptensor_mat_mult)\n    subgoal using hadamard_on_i_dim ps2_P_d1 Suc by auto\n    subgoal using exH_k_dim ps2_P_d1 Suc by auto\n    using ps2_P_d2 by auto\n  also have \"\\<dots> = exexH_k (Suc k)\" using mult_exH_k_left Suc by auto\n  finally have eq1: \"(tensor_P (hadamard_on_i (Suc k)) (1\\<^sub>m K)) * exexH_k k = exexH_k (Suc k)\".\n  then have eq2: \"adjoint (exexH_k k) * adjoint (tensor_P (hadamard_on_i (Suc k)) (1\\<^sub>m K)) = adjoint (exexH_k (Suc k))\"\n    apply (subst adjoint_mult[symmetric, of _ d d _ d])\n    subgoal using tensor_P_dim by auto\n    using exexH_k_dim Suc by auto\n  have dP: \"P \\<in> carrier_mat d d\" using is_quantum_predicate_def Suc by auto\n  moreover have dH: \"exexH_k k \\<in> carrier_mat d d\" using exexH_k_dim Suc by auto\n  moreover have dHi: \"tensor_P (hadamard_on_i (Suc k)) (1\\<^sub>m K) \\<in> carrier_mat d d\" using tensor_P_dim by auto\n  ultimately have eq3: \"adjoint (exexH_k k) * (adjoint (tensor_P (hadamard_on_i (Suc k)) (1\\<^sub>m K)) * P * tensor_P (hadamard_on_i (Suc k)) (1\\<^sub>m K)) * exexH_k k\n    = (adjoint (exexH_k k) * adjoint (tensor_P (hadamard_on_i (Suc k)) (1\\<^sub>m K))) * P * (tensor_P (hadamard_on_i (Suc k)) (1\\<^sub>m K) * exexH_k k)\"\n    by (mat_assoc d)\n  show ?case apply (subst hadamard_n.simps) \n    apply (subst hoare_partial.intros(3)[of _ \"adjoint (tensor_P (hadamard_on_i (Suc k)) (1\\<^sub>m K)) * P * (tensor_P (hadamard_on_i (Suc k)) (1\\<^sub>m K))\"])\n    subgoal using qp_close_after_exexH_k[of P \"Suc k\"] Suc by auto\n    subgoal using qp by auto\n    subgoal using Suc by auto\n    subgoal using h2[simplified eq3 eq1 eq2] by auto\n    using h1 by auto\nqed\n\nlemma qp_pre:\n  \"is_quantum_predicate (tensor_P pre (proj_k 0))\"\n  unfolding is_quantum_predicate_def\nproof (intro conjI)\n  show \"tensor_P pre (proj_k 0) \\<in> carrier_mat d d\" using tensor_P_dim by auto\n  interpret st: partial_state dims vars1 .\n  have d1: \"st.d1 = N\" unfolding st.d1_def st.dims1_def using d_vars1 by auto\n  have d2: \"st.d2 = K\" unfolding st.d2_def st.dims2_def nths_uminus_vars1 dims_vars2 by auto\n  show \"positive (tensor_P pre (proj_k 0))\"\n    unfolding ps2_P.ptensor_mat_def ps2_P_dims0  ps2_P_vars1' \n    apply (subst st.tensor_mat_positive)\n    subgoal unfolding pre_def using outer_prod_dim ket_pre_def d1 by auto\n    subgoal unfolding proj_k_def using outer_prod_dim ket_k_def d2 by auto\n    subgoal using positive_pre by auto\n    using positive_proj_k[of 0] K_gt_0 by auto\n  show \"tensor_P pre (proj_k 0) \\<le>\\<^sub>L 1\\<^sub>m d\"\n    unfolding ps2_P.ptensor_mat_def ps2_P_dims0  ps2_P_vars1' \n    apply (subst st.tensor_mat_le_one)\n    subgoal using pre_def ket_pre_def outer_prod_dim d1 by auto\n    subgoal using proj_k_def K_gt_0 ket_k_def outer_prod_dim d2 by auto\n    using d1 d2  K_gt_0 outer_prod_dim positive_pre positive_proj_k pre_le_one proj_k_le_one by auto\nqed\n\nlemma qp_init_post:\n  \"is_quantum_predicate (tensor_P proj_psi (proj_k 0))\"\n  unfolding is_quantum_predicate_def\nproof (intro conjI)\n  show \"tensor_P proj_psi (proj_k 0) \\<in> carrier_mat d d\" using tensor_P_dim by auto\n  interpret st: partial_state dims vars1 .\n  have d1: \"st.d1 = N\" unfolding st.d1_def st.dims1_def using d_vars1 by auto\n  have d2: \"st.d2 = K\" unfolding st.d2_def st.dims2_def nths_uminus_vars1 dims_vars2 by auto\n  show \"positive (tensor_P proj_psi (proj_k 0))\"\n    unfolding ps2_P.ptensor_mat_def ps2_P_dims0  ps2_P_vars1' \n    apply (subst st.tensor_mat_positive)\n    subgoal unfolding proj_psi_def using outer_prod_dim \\<psi>_def d1 by auto\n    subgoal unfolding proj_k_def using outer_prod_dim ket_k_def d2 by auto\n    subgoal using positive_proj_psi by auto\n    using positive_proj_k[of 0] K_gt_0 by auto\n  show \"tensor_P proj_psi (proj_k 0) \\<le>\\<^sub>L 1\\<^sub>m d\"\n    unfolding ps2_P.ptensor_mat_def ps2_P_dims0  ps2_P_vars1' \n    apply (subst st.tensor_mat_le_one)\n    subgoal using proj_psi_def outer_prod_dim d1 by auto\n    subgoal using proj_k_def K_gt_0 ket_k_def outer_prod_dim d2 by auto\n    using d1 d2  K_gt_0 outer_prod_dim positive_proj_psi positive_proj_k proj_psi_le_one proj_k_le_one by auto\nqed\n\nlemma tensor_P_adjoint_left_right:\n  assumes \"m1 \\<in> carrier_mat N N\" and \"m2 \\<in> carrier_mat K K\" and \"m3 \\<in> carrier_mat N N\" and \"m4 \\<in> carrier_mat K K\"\n  shows \"adjoint (tensor_P m1 m2) * tensor_P m3 m4 * tensor_P m1 m2 = tensor_P (adjoint m1 * m3 * m1) (adjoint m2 * m4 * m2)\"\nproof -\n  have eq1: \"adjoint (tensor_P m1 m2) = tensor_P (adjoint m1) (adjoint m2)\"\n    unfolding ps2_P.ptensor_mat_def\n    apply (subst ps_P.tensor_mat_adjoint)\n    using ps_P_d1 ps_P_d2 assms by auto\n  have eq2: \"adjoint (tensor_P m1 m2) * tensor_P m3 m4 = tensor_P (adjoint m1 * m3) (adjoint m2 * m4)\"\n    unfolding ps2_P.ptensor_mat_def\n    apply (subst ps_P.tensor_mat_mult)\n    using ps_P_d1 ps_P_d2 assms eq1 unfolding ps2_P.ptensor_mat_def by (auto simp add: adjoint_dim)\n  have eq3: \"tensor_P (adjoint m1 * m3) (adjoint m2 * m4) * (tensor_P m1 m2) = tensor_P (adjoint m1 * m3 * m1) (adjoint m2 * m4 * m2)\"\n    unfolding ps2_P.ptensor_mat_def\n    apply (subst ps_P.tensor_mat_mult[of \"adjoint m1 * m3\"])\n    using ps_P_d1 ps_P_d2 assms by (auto simp add: adjoint_dim)\n  show ?thesis using eq1 eq2 eq3 by auto\nqed\n\nabbreviation exH_n where\n  \"exH_n \\<equiv> exH_k (n - 1)\"\n\nlemma hoare_triple_init:\n  \"\\<turnstile>\\<^sub>p \n   {tensor_P pre (proj_k 0)} \n   hadamard_n n\n   {tensor_P proj_psi (proj_k 0)}\"\nproof -\n  have h: \"\\<turnstile>\\<^sub>p \n   {adjoint (exexH_k (n - 1)) * (tensor_P proj_psi (proj_k 0)) * (exexH_k (n - 1))} \n   hadamard_n n\n   {tensor_P proj_psi (proj_k 0)}\"\n    using hoare_hadamard_n[OF qp_init_post, of \"n - 1\"] qp_init_post n by auto\n  have \"adjoint (exexH_k (n - 1)) * tensor_P proj_psi (proj_k 0) * exexH_k (n - 1) =\n        tensor_P (adjoint exH_n * proj_psi * exH_n) (adjoint (1\\<^sub>m K) * proj_k 0 * 1\\<^sub>m K)\"\n    unfolding exexH_k.simps\n    apply (subst tensor_P_adjoint_left_right)\n    using exH_k_dim proj_psi_def \\<psi>_def  proj_k_def ket_k_def n by (auto)\n  moreover have \"adjoint exH_n * proj_psi * exH_n = pre\"\n    unfolding proj_psi_def pre_def\n    apply (subst outer_prod_left_right_mat[of _ N _ N _ N _ N])\n    subgoal using \\<psi>_def by auto\n    subgoal using exH_k_dim n by (simp add: adjoint_dim)\n    subgoal using exH_k_dim n by simp\n    apply (subst (1 2) hermitian_exH_n[simplified hermitian_def])\n    apply (subst (1 2) exH_k_mult_psi_is_pre)\n    by auto\n  moreover have \"adjoint (1\\<^sub>m K) * (proj_k 0) * (1\\<^sub>m K) = proj_k 0\"\n    apply (subst adjoint_one) using proj_k_dim[of 0] K_gt_0 by auto\n  ultimately have \"adjoint (exexH_k (n - 1)) * tensor_P proj_psi (proj_k 0) * exexH_k (n - 1) = tensor_P pre (proj_k 0)\"\n    by auto\n  with h show ?thesis by auto\nqed\n\ntext \\<open>Hoare triples of while loop\\<close>\n\ndefinition proj_psi_l where\n  \"proj_psi_l l = proj (psi_l l)\"\n\nlemma positive_psi_l:\n  \"k < K \\<Longrightarrow> positive (proj_psi_l k)\"\n  unfolding proj_psi_l_def\n  apply (subst positive_same_outer_prod)\n  using psi_l_dim by auto\n\nlemma hermitian_proj_psi_l:\n  \"k < K \\<Longrightarrow> hermitian (proj_psi_l k)\"\n  using positive_psi_l positive_is_hermitian by auto\n\ndefinition P' where\n  \"P' = tensor_P (proj_psi_l R) (proj_k R)\"\n\nlemma proj_psi_l_dim:\n  \"proj_psi_l l \\<in> carrier_mat N N\"\n  unfolding proj_psi_l_def using psi_l_def by auto\n\ndefinition Q :: \"complex mat\" where\n  \"Q = matrix_sum d (\\<lambda>l. tensor_P (proj_psi_l l) (proj_k l)) R\"\n\nlemma psi_l_le_id:\n  shows \"proj_psi_l l \\<le>\\<^sub>L 1\\<^sub>m N\"\nproof -\n  have \"inner_prod (psi_l l) (psi_l l) = 1\"\n    using inner_psi_l by auto\n  then show ?thesis using outer_prod_le_one psi_l_def proj_psi_l_def by auto\nqed\n\nlemma positive_proj_psi_l:\n  shows \"positive (proj_psi_l l)\"\n  using positive_same_outer_prod proj_psi_l_def psi_l_dim by auto\n\ndefinition proj_fst_k :: \"nat \\<Rightarrow> complex mat\" where\n  \"proj_fst_k k = mat K K (\\<lambda>(i, j). if (i = j \\<and> i < k) then 1 else 0)\"\n\nlemma hermitian_proj_fst_k:\n  \"adjoint (proj_fst_k k) = proj_fst_k k\"\n  by (auto simp add: proj_fst_k_def adjoint_eval)\n\nlemma proj_fst_k_is_projection:\n  \"proj_fst_k k * proj_fst_k k = proj_fst_k k\"\n  by (auto simp add: proj_fst_k_def scalar_prod_def sum_only_one_neq_0)\n\nlemma positive_proj_fst_k:\n  \"positive (proj_fst_k k)\"\nproof -\n  have \"(proj_fst_k k) * adjoint (proj_fst_k k) = (proj_fst_k k)\"\n    using hermitian_proj_fst_k proj_fst_k_is_projection by auto\n  then have \"\\<exists>M. M * adjoint M = (proj_fst_k k)\" by auto\n  then show ?thesis apply (subst positive_if_decomp) using proj_fst_k_def by auto\nqed\n\nlemma proj_fst_k_le_one:\n  \"proj_fst_k k \\<le>\\<^sub>L 1\\<^sub>m K\"\nproof -\n  define M where \"M l = mat K K (\\<lambda>(i, j). if (i = j \\<and> i \\<ge> l) then (1::complex) else 0)\" for l\n  have eq: \"1\\<^sub>m K - proj_fst_k k = M k\" unfolding M_def proj_fst_k_def\n    apply (rule eq_matI) by auto\n  have \"M k * M k = M k\" unfolding M_def\n    apply (rule eq_matI) apply (simp add: scalar_prod_def)\n      apply (subst sum_only_one_neq_0[of _ j]) by auto\n  moreover have \"adjoint (M k) = M k\" unfolding M_def\n    apply (rule eq_matI) by (auto simp add: adjoint_eval)\n  ultimately have \"M k * adjoint (M k) = M k\" by auto\n  then have \"\\<exists>M. M * adjoint M = 1\\<^sub>m K - proj_fst_k k\" using eq by auto\n  then have \"positive (1\\<^sub>m K - proj_fst_k k)\" \n    apply (subst positive_if_decomp) using proj_fst_k_def by auto\n  then show ?thesis unfolding lowner_le_def using proj_fst_k_def by auto\nqed\n\nlemma sum_proj_k:\n  assumes \"m \\<le> K\"\n  shows \"matrix_sum K (\\<lambda>k. proj_k k) m = proj_fst_k m\"\nproof -\n  have \"m \\<le> K \\<Longrightarrow> matrix_sum K (\\<lambda>k. proj_k k) m = mat K K (\\<lambda>(i, j). if (i = j \\<and> i < m) then 1 else 0)\" for m\n  proof (induct m)\n    case 0\n    then show ?case apply simp apply (rule eq_matI) by auto\n  next\n    case (Suc m)\n    then have m: \"m < K\" by auto\n    then have m': \"m \\<le> K\" by auto\n    have \"matrix_sum K proj_k (Suc m) = proj_k m + matrix_sum K proj_k m\" by simp\n    also have \"\\<dots> = mat K K (\\<lambda>(i, j). if (i = j \\<and> i < (Suc m)) then 1 else 0)\"\n      unfolding proj_k_mat[OF m] Suc(1)[OF m'] apply (rule eq_matI) by auto\n    finally show ?case by auto\n  qed\n  then show ?thesis unfolding proj_fst_k_def using assms by auto\nqed\n\nlemma proj_psi_proj_k_le_exproj_k:\n  shows \"tensor_P (proj_psi_l k) (proj_k l) \\<le>\\<^sub>L tensor_P (1\\<^sub>m N) (proj_k l)\"\n  unfolding ps2_P.ptensor_mat_def\n  apply (subst ps_P.tensor_mat_positive_le) \n  subgoal using proj_psi_l_def psi_l_dim ps_P_d1 by auto\n  subgoal using proj_k_def ket_k_def ps_P_d2 by auto\n  subgoal using positive_proj_psi_l by auto\n  subgoal using positive_same_outer_prod proj_k_def ket_k_def by auto\n  subgoal using psi_l_le_id by auto\n  apply (subst lowner_le_refl[of _ K]) by (auto simp add: proj_k_def ket_k_def)\n\ndefinition Q1 :: \"complex mat\" where\n  \"Q1 = matrix_sum d (\\<lambda>l. tensor_P (proj_psi'_l l) (proj_k l)) R\"\n\nlemma tensor_P_left_right_partial1:\n  assumes \"m1 \\<in> carrier_mat N N\" and \"m2 \\<in> carrier_mat N N\" and \"m3 \\<in> carrier_mat K K\" and \"m4 \\<in> carrier_mat N N\"\n  shows \"tensor_P m1 (1\\<^sub>m K) * tensor_P m2 m3 * tensor_P m4 (1\\<^sub>m K) = tensor_P (m1 * m2 * m4) m3\"\nproof -\n  have \"tensor_P m1 (1\\<^sub>m K) * tensor_P m2 m3 = tensor_P (m1 * m2) m3\"\n    unfolding ps2_P.ptensor_mat_def \n    apply (subst ps_P.tensor_mat_mult[symmetric])\n    using assms ps_P_d1 ps_P_d2 by auto\n  moreover have \"tensor_P (m1 * m2) m3 * tensor_P m4 (1\\<^sub>m K) = tensor_P (m1 * m2 * m4) m3\"\n    unfolding ps2_P.ptensor_mat_def \n    apply (subst ps_P.tensor_mat_mult[symmetric])\n    using assms ps_P_d1 ps_P_d2 by auto\n  ultimately show ?thesis by auto\nqed\n\nlemma tensor_P_left_right_partial2:\n  assumes \"m1 \\<in> carrier_mat K K\" and \"m2 \\<in> carrier_mat K K\" and \"m3 \\<in> carrier_mat N N\" and \"m4 \\<in> carrier_mat K K\"\n  shows \"tensor_P (1\\<^sub>m N) m1 * tensor_P m3 m2 * tensor_P (1\\<^sub>m N) m4 = tensor_P m3 (m1 * m2 * m4)\"\nproof -\n  have \"tensor_P (1\\<^sub>m N) m1 * tensor_P m3 m2 = tensor_P m3 (m1 * m2)\"\n    unfolding ps2_P.ptensor_mat_def \n    apply (subst ps_P.tensor_mat_mult[symmetric])\n    using assms ps_P_d1 ps_P_d2 by auto\n  moreover have \"tensor_P m3 (m1 * m2) * tensor_P (1\\<^sub>m N) m4 = tensor_P m3 (m1 * m2 * m4)\"\n    unfolding ps2_P.ptensor_mat_def \n    apply (subst ps_P.tensor_mat_mult[symmetric])\n    using assms ps_P_d1 ps_P_d2 by auto\n  ultimately show ?thesis by auto\nqed\n\nlemma matrix_sum_mult_left_right:\n  fixes A B :: \"complex mat\"\n  assumes dg: \"(\\<And>k. k < l \\<Longrightarrow> g k \\<in> carrier_mat m m) \"\n    and dA: \"A \\<in> carrier_mat m m\" and dB: \"B \\<in> carrier_mat m m\"\n  shows \"matrix_sum m (\\<lambda>k. A * g k * B) l = A * matrix_sum m g l * B\"\nproof -\n  have eq: \"A * matrix_sum m g l = matrix_sum m (\\<lambda>k. A * g k) l\" \n    using matrix_sum_distrib_left assms by auto\n  have \"A * matrix_sum m g l * B = matrix_sum m (\\<lambda>k. A * g k * B) l\"\n    apply (subst eq)\n    using matrix_sum_mult_right[of l \"\\<lambda>k. A * g k\"] assms by auto\n  then show ?thesis by auto\nqed\n\nlemma mat_O_split:\n  \"mat_O = 1\\<^sub>m N - 2 \\<cdot>\\<^sub>m proj_O\"\n  apply (rule eq_matI)\n  unfolding mat_O_def proj_O_def by auto\n\nlemma mat_O_mult_psi'_l:\n  \"mat_O *\\<^sub>v (psi'_l l) = psi_l l\"\nproof -\n  have \"mat_O *\\<^sub>v (psi'_l l) = mat_O *\\<^sub>v ((alpha_l l) \\<cdot>\\<^sub>v \\<alpha>) - mat_O *\\<^sub>v ((beta_l l) \\<cdot>\\<^sub>v \\<beta>)\"\n    unfolding psi'_l_def apply (subst mult_minus_distrib_mat_vec)\n    using mat_O_dim \\<alpha>_dim \\<beta>_dim by auto\n  also have \"\\<dots> = (alpha_l l) \\<cdot>\\<^sub>v (mat_O *\\<^sub>v  \\<alpha>) - (beta_l l) \\<cdot>\\<^sub>v (mat_O *\\<^sub>v \\<beta>)\"\n    using mult_mat_vec_smult_vec_assoc[of mat_O N N] mat_O_dim \\<alpha>_dim \\<beta>_dim by auto\n  also have \"\\<dots> = (alpha_l l) \\<cdot>\\<^sub>v \\<alpha> - (beta_l l) \\<cdot>\\<^sub>v (- \\<beta>)\"\n    using mat_O_mult_alpha mat_O_mult_beta by auto\n  also have \"\\<dots> = (alpha_l l) \\<cdot>\\<^sub>v \\<alpha> + (beta_l l) \\<cdot>\\<^sub>v \\<beta>\"\n    by auto\n  finally show ?thesis unfolding psi_l_def by auto\nqed\n\nlemma mat_O_times_Q1:\n  \"adjoint (tensor_P mat_O (1\\<^sub>m K)) * Q1 * (tensor_P mat_O (1\\<^sub>m K)) = Q\"\nproof -\n  let ?m1 = \"tensor_P mat_O (1\\<^sub>m K)\"\n  have eq:\"adjoint ?m1 = ?m1\"\n    unfolding ps2_P.ptensor_mat_def \n    apply (subst ps_P.tensor_mat_adjoint)\n      apply (auto simp add: mat_O_dim ps_P_d1 ps_P_d2)\n    by (simp add: hermitian_mat_O[unfolded hermitian_def] hermitian_one[unfolded hermitian_def])\n  {\n    fix l\n    let ?m2 = \"tensor_P (proj_psi'_l l) (proj_k l)\"\n    have \"?m1 * ?m2 * ?m1 = tensor_P (mat_O * (proj_psi'_l l) * mat_O) (proj_k l)\"\n      apply (subst tensor_P_left_right_partial1)\n      using mat_O_dim proj_psi'_dim proj_k_dim by auto\n    moreover have \"mat_O * (proj_psi'_l l) * mat_O = outer_prod (psi_l l) (psi_l l)\"\n      unfolding proj_psi'_l_def apply (subst outer_prod_left_right_mat[of _ N _ N  _ N _ N])\n      using psi'_l_dim mat_O_dim mat_O_mult_psi'_l hermitian_mat_O[unfolded hermitian_def] by auto\n    ultimately have \"?m1 * ?m2 * ?m1 = tensor_P (proj_psi_l l) (proj_k l)\" unfolding proj_psi_l_def by auto\n  }\n  note p1 = this\n  have \"adjoint (tensor_P mat_O (1\\<^sub>m K)) * Q1 * (tensor_P mat_O (1\\<^sub>m K)) = ?m1 * Q1 * ?m1\"\n    using eq by auto\n  also have \"\\<dots> = matrix_sum d (\\<lambda>l. ?m1 * (tensor_P (proj_psi'_l l) (proj_k l)) * ?m1) R\"\n    unfolding Q1_def\n    apply (subst matrix_sum_mult_left_right) using tensor_P_dim by auto\n  also have \"\\<dots> = Q\"\n    unfolding Q_def using p1 by auto\n  finally show ?thesis by auto\nqed\n\ndefinition Q2 where\n  \"Q2 = matrix_sum d (\\<lambda>l. tensor_P (proj_psi_l (l + 1)) (proj_k l)) R\"\n\nlemma Q2_dim:\n  \"Q2 \\<in> carrier_mat d d\"\n  unfolding Q2_def apply (subst matrix_sum_dim) using tensor_P_dim by auto\n\nlemma Q2_le_one:\n  \"Q2 \\<le>\\<^sub>L 1\\<^sub>m d\" \nproof -\n  have leq: \"Q2 \\<le>\\<^sub>L matrix_sum d (\\<lambda>k. tensor_P (1\\<^sub>m N) (proj_k k)) R\"\n    unfolding Q2_def\n    apply (subst lowner_le_matrix_sum)\n    subgoal using tensor_P_dim by auto\n    subgoal using tensor_P_dim by auto\n    using proj_psi_proj_k_le_exproj_k by auto\n  have \"matrix_sum d (\\<lambda>k. tensor_P (1\\<^sub>m N) (proj_k k)) R\n      = tensor_P (1\\<^sub>m N) (matrix_sum K proj_k R)\"\n    unfolding ps2_P.ptensor_mat_def\n    apply (subst ps_P.tensor_mat_matrix_sum2[simplified ps_P_d ps_P_d2])\n    subgoal using ps_P_d1 by auto\n    using proj_k_dim by auto\n  also have \"\\<dots> = tensor_P (1\\<^sub>m N) (proj_fst_k R)\" using sum_proj_k K by auto\n  also have \"\\<dots> \\<le>\\<^sub>L tensor_P (1\\<^sub>m N) (1\\<^sub>m K)\" unfolding ps2_P.ptensor_mat_def\n    apply (subst ps_P.tensor_mat_positive_le)\n    subgoal using ps_P_d1 by auto\n    subgoal using ps_P_d2 proj_fst_k_def by auto\n    subgoal using positive_one by auto\n    subgoal using positive_proj_fst_k  by auto\n    subgoal using lowner_le_refl[of \"1\\<^sub>m N\" N] by auto\n    using proj_fst_k_le_one by auto\n  also have \"\\<dots> = 1\\<^sub>m d\" unfolding ps2_P.ptensor_mat_def\n    using ps_P.tensor_mat_id ps_P_d1 ps_P_d2 ps_P_d by auto\n  finally have leq2: \"matrix_sum d (\\<lambda>k. tensor_P (1\\<^sub>m N) (proj_k k)) R \\<le>\\<^sub>L 1\\<^sub>m d\" by auto\n  have ds: \"matrix_sum d (\\<lambda>k. tensor_P (1\\<^sub>m N) (proj_k k)) R \\<in> carrier_mat d d\"\n    apply (subst matrix_sum_dim) using tensor_P_dim by auto\n  then show ?thesis using leq leq2 lowner_le_trans[OF Q2_dim ds, of \"1\\<^sub>m d\"] by auto\nqed\n\nlemma qp_Q2:\n  \"is_quantum_predicate Q2\"\n  unfolding is_quantum_predicate_def\nproof (intro conjI)\n  show \"Q2 \\<in> carrier_mat d d\" unfolding Q2_def \n    apply (subst matrix_sum_dim) using tensor_P_dim by auto\nnext\n  show \"positive Q2\" unfolding Q2_def\n    apply (subst matrix_sum_positive)\n    subgoal using tensor_P_dim by auto\n    subgoal for k unfolding ps2_P.ptensor_mat_def \n      apply (subst ps_P.tensor_mat_positive)\n      subgoal using proj_psi_l_def psi_l_dim ps_P_d1 by auto\n      subgoal using proj_k_dim ps_P_d2 K by auto\n      subgoal using positive_proj_psi_l by auto\n       using positive_proj_k K by auto\n    by auto\nnext\n  show \"Q2 \\<le>\\<^sub>L 1\\<^sub>m d\" using Q2_le_one by auto\nqed\n\nlemma pre_mat:\n  \"pre = mat N N (\\<lambda>(i, j). if i = j \\<and> i = 0 then 1 else 0)\"\n  apply (rule eq_matI)\n  subgoal for i j  unfolding pre_def apply (subst index_outer_prod[OF ket_pre_dim ket_pre_dim])\n      apply simp_all\n    unfolding ket_pre_def by auto\n  using outer_prod_dim[OF ket_pre_dim ket_pre_dim, folded pre_def] by auto\n\nlemma mat_Ph_split:\n  \"mat_Ph = 2 \\<cdot>\\<^sub>m pre - 1\\<^sub>m N\"\n  unfolding mat_Ph_def pre_mat\n  apply (rule eq_matI) by auto\n  \nlemma H_Ph_H:\n  \"exexH_k (n-1) * tensor_P mat_Ph (1\\<^sub>m K) * exexH_k (n - 1) = 2 \\<cdot>\\<^sub>m tensor_P proj_psi (1\\<^sub>m K) - 1\\<^sub>m d\"\n  unfolding mat_Ph_split exexH_k.simps\n  apply (subst tensor_P_left_right_partial1)\n  subgoal using exH_k_dim[of \"n - 1\"] n by auto\n  subgoal using pre_dim by auto\n  subgoal by auto\nproof -\n  have eq1: \"exH_n * exH_n = 1\\<^sub>m N\"\n    using unitary_exH_k[of \"n - 1\"]\n    unfolding unitary_def inverts_mat_def\n    using n hermitian_exH_n[simplified hermitian_def] exH_n_dim by auto\n  have eq2: \"exH_n * pre * exH_n = proj_psi\"\n    unfolding pre_def proj_psi_def\n    apply (subst outer_prod_left_right_mat[of _ N _ N _ N _ N])\n    subgoal using ket_pre_dim by auto\n    subgoal using exH_n_dim by auto\n    apply (subst hermitian_exH_n[simplified hermitian_def])\n    using exH_k_mult_pre_is_psi by auto\n  have eq3: \"exH_n * (2 \\<cdot>\\<^sub>m pre) * exH_n = 2 \\<cdot>\\<^sub>m (exH_n * pre * exH_n)\"\n    using pre_dim exH_n_dim by (mat_assoc N)\n  have \"exH_n * (2 \\<cdot>\\<^sub>m pre - 1\\<^sub>m N) * exH_n = exH_n * (2 \\<cdot>\\<^sub>m pre) * exH_n - exH_n * exH_n\"\n    using pre_dim exH_n_dim apply (mat_assoc N) by auto\n  also have \"\\<dots> = 2 \\<cdot>\\<^sub>m (exH_n * pre * exH_n) - 1\\<^sub>m N\"\n    using eq1 eq3 by auto\n  finally have eq4: \"exH_n * (2 \\<cdot>\\<^sub>m pre - 1\\<^sub>m N) * exH_n = 2 \\<cdot>\\<^sub>m proj_psi - 1\\<^sub>m N\" using eq2 by auto\n  show \"tensor_P (exH_n * (2 \\<cdot>\\<^sub>m pre - 1\\<^sub>m N) * exH_n) (1\\<^sub>m K) = 2 \\<cdot>\\<^sub>m tensor_P proj_psi (1\\<^sub>m K) - 1\\<^sub>m d\"\n    unfolding eq4 unfolding ps2_P.ptensor_mat_def \n    apply (subst ps_P.tensor_mat_minus1)\n    unfolding ps_P_d1 ps_P_d2 apply (auto simp add: proj_psi_dim)\n    apply (subst ps_P.tensor_mat_scale1)\n    unfolding ps_P_d1 ps_P_d2 apply (auto simp add: proj_psi_dim)\n    apply (subst ps_P.tensor_mat_id[simplified ps_P_d1 ps_P_d2 ps_P_d]) by auto\nqed\n\nlemma hermitian_proj_psi_minus_1:\n  \"hermitian (2 \\<cdot>\\<^sub>m proj_psi - 1\\<^sub>m N)\"\n  unfolding hermitian_def\n  apply (subst adjoint_minus[of _ N N])\n    apply (auto simp add: proj_psi_dim)\n  apply (subst adjoint_scale)\n  using hermitian_proj_psi[simplified hermitian_def] hermitian_def adjoint_one by auto\n\nlemma unitary_proj_psi_minus_1:\n  \"unitary (2 \\<cdot>\\<^sub>m proj_psi - 1\\<^sub>m N)\"\nproof -\n  have a: \"adjoint (2 \\<cdot>\\<^sub>m proj_psi) = 2 \\<cdot>\\<^sub>m proj_psi\" \n    apply (subst adjoint_scale) using hermitian_proj_psi[simplified hermitian_def] by simp\n  have eq: \"adjoint (2 \\<cdot>\\<^sub>m proj_psi - 1\\<^sub>m N) = 2 \\<cdot>\\<^sub>m proj_psi - 1\\<^sub>m N\"\n    apply (subst adjoint_minus) using proj_psi_dim a adjoint_one by auto\n  have \"(2 \\<cdot>\\<^sub>m proj_psi) * (2 \\<cdot>\\<^sub>m proj_psi) = 4 \\<cdot>\\<^sub>m (proj_psi * proj_psi)\"\n    using proj_psi_dim by auto\n  also have \"\\<dots> = 4 \\<cdot>\\<^sub>m proj_psi\" using proj_psi_is_projection by auto\n  finally have sq: \"(2 \\<cdot>\\<^sub>m proj_psi) * (2 \\<cdot>\\<^sub>m proj_psi) = 4 \\<cdot>\\<^sub>m proj_psi\".\n  have l: \"(2 \\<cdot>\\<^sub>m proj_psi) * (2 \\<cdot>\\<^sub>m proj_psi - 1\\<^sub>m N) = 4 \\<cdot>\\<^sub>m proj_psi - (2 \\<cdot>\\<^sub>m proj_psi)\"\n    apply (subst mult_minus_distrib_mat) using proj_psi_dim sq by auto\n\n  have \"(2 \\<cdot>\\<^sub>m proj_psi - 1\\<^sub>m N) * adjoint (2 \\<cdot>\\<^sub>m proj_psi - 1\\<^sub>m N)\n    = (2 \\<cdot>\\<^sub>m proj_psi - 1\\<^sub>m N) * (2 \\<cdot>\\<^sub>m proj_psi - 1\\<^sub>m N)\" using eq by auto\n  also have \"\\<dots> = (2 \\<cdot>\\<^sub>m proj_psi) * (2 \\<cdot>\\<^sub>m proj_psi - 1\\<^sub>m N) - 2 \\<cdot>\\<^sub>m proj_psi + 1\\<^sub>m N\"\n    apply (subst minus_mult_distrib_mat[of _ N N]) using proj_psi_dim by auto\n  also have \"\\<dots> = 4 \\<cdot>\\<^sub>m proj_psi - (2 \\<cdot>\\<^sub>m proj_psi) - 2 \\<cdot>\\<^sub>m proj_psi + 1\\<^sub>m N\"\n    using l by auto\n  also have \"\\<dots> = 1\\<^sub>m N\" using proj_psi_dim by auto\n  finally have \"(2 \\<cdot>\\<^sub>m proj_psi - 1\\<^sub>m N) * adjoint (2 \\<cdot>\\<^sub>m proj_psi - 1\\<^sub>m N) = 1\\<^sub>m N\".\n  then show ?thesis unfolding unitary_def inverts_mat_def using proj_psi_dim by auto\nqed\n\nlemma proj_psi_minus_1_mult_psi'_l:\n  \"(2 \\<cdot>\\<^sub>m proj_psi - 1\\<^sub>m N) *\\<^sub>v psi'_l l = psi_l (l + 1)\"\nproof -\n  have eq1: \"(2 \\<cdot>\\<^sub>m proj_psi - 1\\<^sub>m N) *\\<^sub>v psi'_l l = 2 \\<cdot>\\<^sub>m proj_psi *\\<^sub>v psi'_l l - psi'_l l\"\n    apply (subst minus_mult_distrib_mat_vec)\n    using psi'_l_dim proj_psi'_dim proj_psi_dim by auto\n  have eq2: \"2 \\<cdot>\\<^sub>m proj_psi *\\<^sub>v (psi'_l l) = 2 \\<cdot>\\<^sub>v (proj_psi *\\<^sub>v (psi'_l l))\"\n    apply (subst smult_mat_mult_mat_vec_assoc) \n    using proj_psi_dim psi'_l_dim by auto\n  have \"proj_psi *\\<^sub>v (psi'_l l) = inner_prod \\<psi> (psi'_l l) \\<cdot>\\<^sub>v \\<psi>\"\n    unfolding proj_psi_def\n    apply (subst outer_prod_mult_vec[of _ N _ N])\n    using \\<psi>_dim psi'_l_dim  by auto\n  also have \"\\<dots> = ((alpha_l l) * ccos (\\<theta> / 2) - (beta_l l) * csin (\\<theta> / 2)) \\<cdot>\\<^sub>v \\<psi>\"\n    using psi_inner_psi'_l by auto\n  finally have \"proj_psi *\\<^sub>v (psi'_l l) = ((alpha_l l) * ccos (\\<theta> / 2) - (beta_l l) * csin (\\<theta> / 2)) \\<cdot>\\<^sub>v \\<psi>\" by auto\n  then have eq3: \"2 \\<cdot>\\<^sub>v (proj_psi *\\<^sub>v (psi'_l l)) = 2 * ((alpha_l l) * ccos (\\<theta> / 2) - (beta_l l) * csin (\\<theta> / 2)) \\<cdot>\\<^sub>v \\<psi>\" by auto\n  then show \"(2 \\<cdot>\\<^sub>m proj_psi - (1\\<^sub>m N)) *\\<^sub>v (psi'_l l) = psi_l (l + 1)\"\n    using eq1 eq2 eq3 psi_l_Suc_l_derive by simp\nqed\n\nlemma proj_psi_minus_1_mult_psi_Suc_l:\n  \"(2 \\<cdot>\\<^sub>m proj_psi - 1\\<^sub>m N) *\\<^sub>v psi_l (l + 1) = psi'_l l\"\nproof -\n  have id: \"(2 \\<cdot>\\<^sub>m proj_psi - 1\\<^sub>m N) * (2 \\<cdot>\\<^sub>m proj_psi - 1\\<^sub>m N) = 1\\<^sub>m N\"\n    using unitary_proj_psi_minus_1 unfolding unitary_def hermitian_proj_psi_minus_1[simplified hermitian_def]\n    unfolding inverts_mat_def by auto\n  have \"(2 \\<cdot>\\<^sub>m proj_psi - 1\\<^sub>m N) *\\<^sub>v psi_l (l + 1) = (2 \\<cdot>\\<^sub>m proj_psi - 1\\<^sub>m N) *\\<^sub>v ((2 \\<cdot>\\<^sub>m proj_psi - 1\\<^sub>m N) *\\<^sub>v psi'_l l)\"\n    using proj_psi_minus_1_mult_psi'_l by auto\n  also have \"\\<dots> = ((2 \\<cdot>\\<^sub>m proj_psi - 1\\<^sub>m N) * (2 \\<cdot>\\<^sub>m proj_psi - 1\\<^sub>m N) *\\<^sub>v psi'_l l)\"\n    apply (subst assoc_mult_mat_vec) using proj_psi_dim psi'_l_dim by auto\n  also have \"\\<dots> = psi'_l l\" using psi'_l_dim id by auto\n  finally show ?thesis by auto\nqed\n\nlemma exproj_psi_minus_1_tensor:\n  \"(2 \\<cdot>\\<^sub>m tensor_P proj_psi (1\\<^sub>m K)) - 1\\<^sub>m d = tensor_P (2 \\<cdot>\\<^sub>m proj_psi - (1\\<^sub>m N)) (1\\<^sub>m K)\"\n  unfolding ps2_P.ptensor_mat_def\n  apply (subst ps_P.tensor_mat_id[symmetric, simplified ps_P_d])\n  apply (auto simp add: ps_P_d1 ps_P_d2)\n  apply (subst ps_P.tensor_mat_scale1[symmetric])\n    apply (auto simp add: ps_P_d1 ps_P_d2 proj_psi_dim)\n  apply (subst ps_P.tensor_mat_minus1)\n  by (auto simp add: ps_P_d1 ps_P_d2 proj_psi_dim)\n\nlemma unitary_exproj_psi_minus_1:\n  \"unitary (2 \\<cdot>\\<^sub>m tensor_P proj_psi (1\\<^sub>m K) - 1\\<^sub>m d)\"\n  unfolding exproj_psi_minus_1_tensor\n  unfolding ps2_P.ptensor_mat_def \n  apply (subst ps_P.tensor_mat_unitary)\n  using ps_P_d1 ps_P_d2 unitary_proj_psi_minus_1 unitary_one by auto\n\nlemma proj_psi_minus_1_Q2:\n  \"adjoint (2 \\<cdot>\\<^sub>m tensor_P proj_psi (1\\<^sub>m K) - 1\\<^sub>m d) * Q2 * (2 \\<cdot>\\<^sub>m tensor_P proj_psi (1\\<^sub>m K) - 1\\<^sub>m d) = Q1\"\nproof -\n  have eq1: \"adjoint (2 \\<cdot>\\<^sub>m tensor_P proj_psi (1\\<^sub>m K) - 1\\<^sub>m d) = 2 \\<cdot>\\<^sub>m tensor_P proj_psi (1\\<^sub>m K) - 1\\<^sub>m d\"\n    apply (subst adjoint_minus[of _ d d])\n    subgoal using tensor_P_dim[of proj_psi] by auto\n    subgoal by auto\n    apply (subst adjoint_one) apply (subst adjoint_scale) \n    using hermitian_exproj_psi[simplified hermitian_def] by auto\n  let ?m1 = \"tensor_P (2 \\<cdot>\\<^sub>m proj_psi - (1\\<^sub>m N)) (1\\<^sub>m K)\"\n  {\n    fix l\n    let ?m2 = \"tensor_P (proj_psi_l (l + 1)) (proj_k l)\"\n    have 121: \"?m1 * ?m2 * ?m1 \n        = tensor_P ((2 \\<cdot>\\<^sub>m proj_psi - (1\\<^sub>m N)) * (proj_psi_l (l + 1)) * (2 \\<cdot>\\<^sub>m proj_psi - (1\\<^sub>m N)))\n            (proj_k l)\"\n      apply (subst tensor_P_left_right_partial1)\n      using proj_psi_dim proj_psi_l_dim proj_k_dim by auto\n    have \"(2 \\<cdot>\\<^sub>m proj_psi - (1\\<^sub>m N)) * (proj_psi_l (l + 1)) * (2 \\<cdot>\\<^sub>m proj_psi - (1\\<^sub>m N))\n      = outer_prod ((2 \\<cdot>\\<^sub>m proj_psi - (1\\<^sub>m N)) *\\<^sub>v (psi_l (l + 1))) ((2 \\<cdot>\\<^sub>m proj_psi - (1\\<^sub>m N)) *\\<^sub>v (psi_l (l + 1)))\"\n      unfolding proj_psi_l_def apply (subst outer_prod_left_right_mat[of _ N _ N _ N _ N])\n      using proj_psi_dim psi_l_dim hermitian_proj_psi_minus_1[simplified hermitian_def] by auto\n    also have \"\\<dots> = outer_prod (psi'_l l) (psi'_l l)\"\n      using proj_psi_minus_1_mult_psi_Suc_l by auto\n    finally have \"(2 \\<cdot>\\<^sub>m proj_psi - (1\\<^sub>m N)) * (proj_psi_l (l + 1)) * (2 \\<cdot>\\<^sub>m proj_psi - (1\\<^sub>m N)) \n      = outer_prod (psi'_l l) (psi'_l l)\".\n    then have \"?m1 * ?m2 * ?m1 = tensor_P (proj_psi'_l l) (proj_k l)\"\n      using 121 proj_psi'_l_def by auto\n  }\n  note p1 = this\n  have \"adjoint (2 \\<cdot>\\<^sub>m tensor_P proj_psi (1\\<^sub>m K) - 1\\<^sub>m d) * Q2 * (2 \\<cdot>\\<^sub>m tensor_P proj_psi (1\\<^sub>m K) - 1\\<^sub>m d)\n    = (2 \\<cdot>\\<^sub>m tensor_P proj_psi (1\\<^sub>m K) - 1\\<^sub>m d) * Q2 * (2 \\<cdot>\\<^sub>m tensor_P proj_psi (1\\<^sub>m K) - 1\\<^sub>m d)\"\n    using eq1 by auto\n  also have \"\\<dots> = matrix_sum d\n    (\\<lambda>l. (2 \\<cdot>\\<^sub>m tensor_P proj_psi (1\\<^sub>m K) - 1\\<^sub>m d) * tensor_P (proj_psi_l (l + 1)) (proj_k l) * (2 \\<cdot>\\<^sub>m tensor_P proj_psi (1\\<^sub>m K) - 1\\<^sub>m d))\n    R\" unfolding Q2_def apply (subst matrix_sum_mult_left_right)\n    using tensor_P_dim by auto\n  also have \"\\<dots> = matrix_sum d (\\<lambda>l. tensor_P (proj_psi'_l l) (proj_k l)) R\"\n    using p1 exproj_psi_minus_1_tensor by auto\n  also have \"\\<dots> = Q1\" unfolding Q1_def by auto\n  finally show ?thesis using eq1 by auto\nqed\n\nlemma qp_Q1:\n  \"is_quantum_predicate Q1\"\n  unfolding proj_psi_minus_1_Q2[symmetric]\n  apply (subst qp_close_under_unitary_operator)\n  using tensor_P_dim unitary_exproj_psi_minus_1 qp_Q2 by auto\n\nlemma qp_Q:\n  \"is_quantum_predicate Q\"\nproof -\n  have u: \"unitary (tensor_P mat_O (1\\<^sub>m K))\"\n    unfolding ps2_P.ptensor_mat_def\n    apply (subst ps_P.tensor_mat_unitary)\n    subgoal unfolding ps_P_d1 mat_O_def by auto\n    subgoal unfolding ps_P_d2 by auto\n    subgoal using unitary_mat_O by auto\n    using unitary_one by auto\n  then show ?thesis using tensor_P_dim qp_Q1 \n    using qp_close_under_unitary_operator[OF tensor_P_dim u qp_Q1]\n    by (simp add: mat_O_times_Q1 )\nqed\n\nlemma hoare_triple_D1:\n  \"\\<turnstile>\\<^sub>p \n   {Q} \n   Utrans_P vars1 mat_O\n   {Q1}\"\n  unfolding Utrans_P_is_tensor_P1\n    mat_O_times_Q1[symmetric]\n  apply (subst hoare_partial.intros(2))\n  using qp_Q1 by auto\n\nlemma hoare_triple_D2:\n  \"\\<turnstile>\\<^sub>p \n   {Q1}\n   hadamard_n n ;;\n   Utrans_P vars1 mat_Ph ;;\n   hadamard_n n \n   {Q2}\"\nproof -\n  let ?H = \"exexH_k (n - 1)\"\n  let ?Ph = \"tensor_P mat_Ph (1\\<^sub>m K)\"\n  let ?O = \"tensor_P mat_O (1\\<^sub>m K)\"\n  have h1: \"\\<turnstile>\\<^sub>p \n    {adjoint ?H * Q2 * ?H} \n    hadamard_n n \n    {Q2}\"\n    using hoare_hadamard_n[OF qp_Q2, of \"n - 1\"] n by auto\n  have qp1: \"is_quantum_predicate ((adjoint ?H) * Q2 * ?H)\"\n    using qp_close_under_unitary_operator unitary_exexH_k n exexH_k_dim qp_Q2 by auto\n  then have h2: \"\\<turnstile>\\<^sub>p \n    {adjoint ?Ph * (adjoint ?H * Q2 * ?H) * ?Ph} \n    Utrans_P vars1 mat_Ph \n    {adjoint ?H * Q2 * ?H}\"\n    using qp1 Utrans_P_is_tensor_P1 hoare_partial.intros by auto\n  have qp2: \"is_quantum_predicate (adjoint ?Ph * (adjoint ?H * Q2 * ?H) * ?Ph)\"\n    using qp_close_under_unitary_operator[of \"tensor_P mat_Ph (1\\<^sub>m K)\"] ps2_P.ptensor_mat_carrier ps2_P_d0 unitary_ex_mat_Ph qp1 by auto\n  then have  h3: \"\\<turnstile>\\<^sub>p \n    {adjoint ?H * (adjoint ?Ph * (adjoint ?H * Q2 * ?H) * ?Ph) * ?H} \n    hadamard_n n \n    {adjoint ?Ph * (adjoint ?H * Q2 * ?H) * ?Ph}\"\n    using hoare_hadamard_n[OF qp2, of \"n - 1\"] n by auto\n  have qp3: \"is_quantum_predicate (adjoint ?H * (adjoint ?Ph * (adjoint ?H * Q2 * ?H) * ?Ph) * ?H)\"\n    using qp_close_under_unitary_operator[of \"?H\"] exexH_k_dim unitary_exexH_k qp2 n by auto\n  have h4: \"\\<turnstile>\\<^sub>p \n    {adjoint ?H * (adjoint ?Ph * (adjoint ?H * Q2 * ?H) * ?Ph) * ?H} \n    hadamard_n n ;;\n    Utrans_P vars1 mat_Ph\n    {adjoint ?H * Q2 * ?H}\"\n    using h2 h3 qp1 qp2 qp3 hoare_partial.intros by auto\n  then have h5: \"\\<turnstile>\\<^sub>p \n   {adjoint ?H * (adjoint ?Ph * (adjoint ?H * Q2 * ?H) * ?Ph) * ?H}\n   hadamard_n n ;;\n   Utrans_P vars1 mat_Ph ;;\n   hadamard_n n \n   {Q2}\"\n    using h1 qp_Q2 qp3 qp1 hoare_partial.intros(3)[OF qp3 qp1 qp_Q2 h4 h1] by auto\n\n  have \"adjoint ?H * (adjoint ?Ph * (adjoint ?H * Q2 * ?H) * ?Ph) * ?H =\n        adjoint (?H * ?Ph * ?H) * Q2 * (?H * ?Ph * ?H)\"\n    apply (mat_assoc d) using exexH_k_dim n tensor_P_dim Q2_dim by auto\n  also have \"\\<dots> = Q1\" using H_Ph_H proj_psi_minus_1_Q2 by auto\n  finally show ?thesis using h5 by auto \nqed\n\ndefinition exM0 where\n  \"exM0 = tensor_P (1\\<^sub>m N) M0\"\n\nlemma M0_mult_ket_k_R:\n  \"M0 *\\<^sub>v ket_k R = ket_k R\"\n  apply (rule eq_vecI)\n  unfolding M0_def ket_k_def\n  by (auto simp add: scalar_prod_def sum_only_one_neq_0)\n\nlemma exP0_P':\n  \"adjoint exM0 * P' * exM0 = P'\"\nproof -\n  have eq: \"adjoint exM0 = exM0\"\n    unfolding exM0_def ps2_P.ptensor_mat_def \n    apply (subst ps_P.tensor_mat_adjoint)\n    unfolding ps_P_d1 ps_P_d2 using M0_dim adjoint_one hermitian_M0[unfolded hermitian_def] by auto\n  have eq2: \"M0 * (proj_k R) * M0 = (proj_k R)\"\n    unfolding proj_k_def\n    apply (subst outer_prod_left_right_mat[of _ K _ K _ K _ K])\n    unfolding hermitian_M0[unfolded hermitian_def] M0_mult_ket_k_R\n    using ket_k_dim M0_dim by auto\n  show ?thesis unfolding eq unfolding exM0_def P'_def\n    apply (subst tensor_P_left_right_partial2)\n    using M0_dim proj_k_dim eq2 proj_psi_l_dim by auto\nqed\n \ndefinition exM1 where\n  \"exM1 = tensor_P (1\\<^sub>m N) M1\"\n\nlemma M1_mult_ket_k:\n  assumes \"k < R\"\n  shows \"M1 *\\<^sub>v ket_k k = ket_k k\"\n  apply (rule eq_vecI)\n  unfolding M1_def ket_k_def\n  by (auto simp add: scalar_prod_def assms R sum_only_one_neq_0)\n\nlemma exP1_Q:\n  \"adjoint exM1 * Q * exM1 = Q\"\nproof -\n  have eq: \"adjoint exM1 = exM1\"\n    unfolding exM1_def ps2_P.ptensor_mat_def \n    apply (subst ps_P.tensor_mat_adjoint)\n    unfolding ps_P_d1 ps_P_d2 using M1_dim adjoint_one hermitian_M1[unfolded hermitian_def] by auto\n  {\n    fix k assume k: \"k < R\"\n    let ?m = \"tensor_P (proj_psi_l k) (proj_k k)\"\n    have \"exM1 * ?m * exM1 = tensor_P (proj_psi_l k) (M1 * (proj_k k) * M1)\"\n      unfolding exM1_def apply (subst tensor_P_left_right_partial2)\n      using M1_dim proj_k_dim proj_psi_l_dim by auto\n    also have \"\\<dots> = tensor_P (proj_psi_l k) (outer_prod (M1 *\\<^sub>v ket_k k) (M1 *\\<^sub>v ket_k k))\"\n      unfolding proj_k_def apply (subst outer_prod_left_right_mat[of _ K _ K _ K _ K])\n      unfolding hermitian_M1[unfolded hermitian_def]\n      using ket_k_dim M1_dim by auto\n    finally have \"exM1 * ?m * exM1 = ?m\" unfolding proj_k_def using k M1_mult_ket_k by auto\n  }\n  note p1 = this\n  have \"adjoint exM1 * Q * exM1 = exM1 * Q * exM1\" using eq by auto\n  also have \"\\<dots> = matrix_sum d (\\<lambda>k. exM1 * (tensor_P (proj_psi_l k) (proj_k k)) * exM1) R\"\n    unfolding Q_def\n    apply (subst matrix_sum_mult_left_right)\n    using tensor_P_dim exM1_def by auto\n  also have \"\\<dots> = matrix_sum d (\\<lambda>k. tensor_P (proj_psi_l k) (proj_k k)) R\"\n    apply (subst matrix_sum_cong)\n    using p1 by auto\n  finally show ?thesis using Q_def by auto\nqed\n         \nlemma qp_P':\n  \"is_quantum_predicate P'\"\n  unfolding is_quantum_predicate_def\nproof (intro conjI)\n  show \"P' \\<in> carrier_mat d d\" unfolding P'_def using tensor_P_dim by auto\n  show \"positive P'\" unfolding P'_def ps2_P.ptensor_mat_def\n    apply (subst ps_P.tensor_mat_positive)\n        apply (auto simp add: ps_P_d1 ps_P_d2 proj_O_dim proj_k_dim)\n    using proj_psi_l_dim positive_proj_psi_l positive_proj_k K by auto\n  show \"P' \\<le>\\<^sub>L 1\\<^sub>m d\" unfolding P'_def ps2_P.ptensor_mat_def\n    apply (subst ps_P.tensor_mat_le_one[simplified ps_P_d])\n    by (auto simp add: ps_P_d1 ps_P_d2 proj_psi_l_dim K proj_k_dim positive_proj_psi_l positive_proj_k proj_k_le_one psi_l_le_id)\nqed\n\nlemma P'_add_Q:\n  \"P' + Q = matrix_sum d (\\<lambda>l. tensor_P (proj_psi_l l) (proj_k l)) (R + 1)\"\n  apply simp unfolding P'_def Q_def by auto\n\nlemma positive_Qk:\n  \"positive (tensor_P (proj_psi_l l) (proj_k l))\"\n  unfolding ps2_P.ptensor_mat_def \n  apply (subst ps_P.tensor_mat_positive)\n  unfolding ps_P_d1 ps_P_d2\n  using proj_psi_l_dim proj_k_dim positive_proj_psi_l positive_proj_k by auto\n\nlemma P'_Q_dim:\n  \"P' + Q \\<in> carrier_mat d d\"\n  unfolding P'_add_Q\n  apply (subst matrix_sum_dim)\n  using tensor_P_dim by auto\n\n\n\nlemma qp_P'_Q:\n  \"is_quantum_predicate (P' + Q)\"\n  unfolding is_quantum_predicate_def\nproof (intro conjI)\n  show \"P' + Q \\<in> carrier_mat d d\"\n    unfolding P'_add_Q apply (subst matrix_sum_dim)\n    using tensor_P_dim by auto\n  show \"positive (P' + Q)\" unfolding P'_add_Q\n    apply (subst matrix_sum_positive)\n    using tensor_P_dim positive_Qk by auto\n  show \" P' + Q \\<le>\\<^sub>L 1\\<^sub>m d\" using P'_add_Q_le_one by auto\nqed\n\nlemma Q2_leq_lemma:\n  \"tensor_P (1\\<^sub>m N) (mat_incr K) * Q2 * adjoint (tensor_P (1\\<^sub>m N) (mat_incr K)) \\<le>\\<^sub>L P' + Q\"\nproof -\n  have ad: \"adjoint (tensor_P (1\\<^sub>m N) (mat_incr K)) = tensor_P (1\\<^sub>m N) (adjoint (mat_incr K))\"\n    unfolding ps2_P.ptensor_mat_def apply (subst ps_P.tensor_mat_adjoint)\n    using ps_P_d1 ps_P_d2 mat_incr_dim adjoint_one by auto\n  let ?m1 = \"tensor_P (1\\<^sub>m N) (mat_incr K)\"\n  let ?m3 = \"tensor_P (1\\<^sub>m N) (adjoint (mat_incr K))\"\n  {\n    fix l assume \"l < R\"\n    then have \"l < K - 1\" using K by auto\n    then have m: \"(mat_incr K) *\\<^sub>v (ket_k l) = (ket_k (l + 1))\"\n      using mat_incr_mult_ket_k by auto\n    let ?m2 = \"tensor_P (proj_psi_l (l + 1)) (proj_k l)\"\n    have eq: \"?m1 * ?m2 * ?m3 = tensor_P (proj_psi_l (l + 1)) ((mat_incr K) * (proj_k l) * adjoint (mat_incr K))\"\n      apply (subst tensor_P_left_right_partial2)\n      using proj_k_dim proj_psi_l_dim mat_incr_dim adjoint_dim[OF mat_incr_dim] by auto\n    have \"(mat_incr K) * (proj_k l) * adjoint (mat_incr K) = outer_prod ((mat_incr K) *\\<^sub>v (ket_k l)) ((mat_incr K) *\\<^sub>v (ket_k l))\"\n      unfolding proj_k_def apply (subst outer_prod_left_right_mat[of _ K _ K _ K _ K])\n      using ket_k_dim mat_incr_dim adjoint_dim[OF mat_incr_dim] adjoint_adjoint[of \"mat_incr K\"] by auto\n    also have \"\\<dots> = proj_k (l + 1)\" unfolding proj_k_def using m by auto\n    finally have \"?m1 * ?m2 * ?m3 = tensor_P (proj_psi_l (l + 1)) (proj_k (l + 1))\" using eq by auto\n  }\n  note p1 = this\n  have \"?m1 * Q2 * ?m3\n    = matrix_sum d (\\<lambda>l. ?m1 * (tensor_P (proj_psi_l (l + 1)) (proj_k l)) * ?m3) R\"\n    unfolding Q2_def apply(subst matrix_sum_mult_left_right)\n    using tensor_P_dim by auto\n  also have \"\\<dots> = matrix_sum d (\\<lambda>l. tensor_P (proj_psi_l (l + 1)) (proj_k (l + 1))) R\"\n    apply (subst matrix_sum_cong) using p1 by auto\n  finally have eq1: \"?m1 * Q2 * ?m3 = matrix_sum d (\\<lambda>l. tensor_P (proj_psi_l (l + 1)) (proj_k (l + 1))) R\" (is \"_=?r\") . \n  have eq2: \"P' + Q = tensor_P (proj_psi_l 0) (proj_k 0) + ?r\"\n    unfolding P'_add_Q\n    apply (subst matrix_sum_Suc_remove_head) using tensor_P_dim by auto\n  have \"tensor_P (proj_psi_l 0) (proj_k 0) + ?r \\<le>\\<^sub>L P' + Q\"\n    unfolding eq2[symmetric] apply (subst lowner_le_refl) using P'_Q_dim by auto\n  moreover have \"positive (tensor_P (proj_psi_l 0) (proj_k 0))\"\n    unfolding ps2_P.ptensor_mat_def apply (subst ps_P.tensor_mat_positive)\n    unfolding ps_P_d1 ps_P_d2 using proj_psi_l_dim proj_k_dim positive_proj_psi_l positive_proj_k by auto\n  moreover have \"matrix_sum d (\\<lambda>l. tensor_P (proj_psi_l (l + 1)) (proj_k (l + 1))) R \\<in> carrier_mat d d\"\n    apply (subst matrix_sum_dim) using tensor_P_dim by auto\n  ultimately have \"?r \\<le>\\<^sub>L P' + Q\"\n    apply (subst add_positive_le_reduce2[of ?r d \"tensor_P (proj_psi_l 0) (proj_k 0)\" \"P' + Q\"])\n    using tensor_P_dim P'_Q_dim by auto\n  then show ?thesis using eq1 ad by auto\nqed\n\nlemma Q2_leq:\n  \"Q2 \\<le>\\<^sub>L adjoint (tensor_P (1\\<^sub>m N) (mat_incr K)) * (P' + Q) * tensor_P (1\\<^sub>m N) (mat_incr K)\"\nproof -\n  let ?m1 = \"tensor_P (1\\<^sub>m N) (mat_incr K)\"\n  let ?m2 = \"adjoint (tensor_P (1\\<^sub>m N) (mat_incr K))\"\n  have \"?m1 * ?m2 = 1\\<^sub>m d\"\n    unfolding ps2_P.ptensor_mat_def\n    apply (subst ps_P.tensor_mat_adjoint)\n    unfolding ps_P_d1 ps_P_d2 apply (auto simp add: mat_incr_dim adjoint_one)\n    apply (subst ps_P.tensor_mat_mult[symmetric])\n    unfolding ps_P_d1 ps_P_d2 apply (auto simp add: mat_incr_dim adjoint_dim mat_incr_mult_adjoint_mat_incr)\n    using ps_P.tensor_mat_id ps_P_d ps_P_d1 ps_P_d2 by auto\n  then have inv: \"?m2 * ?m1 = 1\\<^sub>m d\"\n    using mat_mult_left_right_inverse[of ?m1 d ?m2] \n        tensor_P_dim adjoint_dim by auto\n  have d: \"?m1 * Q2 * ?m2 \\<in> carrier_mat d d\" using tensor_P_dim adjoint_dim[OF tensor_P_dim] Q2_dim by fastforce\n  have le: \"?m2 * (?m1 * Q2 * ?m2) * ?m1 \\<le>\\<^sub>L ?m2 * (P' + Q) * ?m1\" (is \"lowner_le ?l ?r\")\n    apply (subst lowner_le_keep_under_measurement[of _ d])\n    using Q2_leq_lemma tensor_P_dim P'_Q_dim d by auto\n  have \"?l = (?m2 * ?m1) * Q2 * (?m2 * ?m1)\"\n    apply (mat_assoc d) using tensor_P_dim Q2_dim by auto\n  also have \"\\<dots> = 1\\<^sub>m d * Q2 * 1\\<^sub>m d\" using inv by auto\n  also have \"\\<dots> = Q2\" using Q2_dim by auto\n  finally have eq: \"?l = Q2\".\n  show ?thesis using eq le by auto\nqed\n\nlemma hoare_triple_D3:\n  \"\\<turnstile>\\<^sub>p \n   {Q2}\n   Utrans_P vars2 (mat_incr K)\n   {adjoint exM0 * P' * exM0 + adjoint exM1 * Q * exM1}\"\n  unfolding exP0_P' exP1_Q \nproof -\n  let ?m = \"tensor_P (1\\<^sub>m N) (mat_incr K)\"\n  have h1: \"\\<turnstile>\\<^sub>p \n    {adjoint ?m * (P' + Q) * ?m} \n    Utrans ?m\n    {P' + Q}\"\n    using qp_P'_Q hoare_partial.intros by auto\n  have qp: \"is_quantum_predicate (adjoint ?m * (P' + Q) * ?m)\"\n    using qp_close_under_unitary_operator tensor_P_dim qp_P'_Q unitary_exmat_incr by auto\n  then have \"\\<turnstile>\\<^sub>p \n    {Q2} \n    Utrans ?m\n    {P' + Q}\"\n    using hoare_partial.intros(6)[OF qp_Q2 qp_P'_Q qp qp_P'_Q] Q2_leq h1 lowner_le_refl[OF P'_Q_dim] by auto\n  moreover have \"Utrans ?m = Utrans_P vars2 (mat_incr K)\"\n    apply (subst Utrans_P_is_tensor_P2) unfolding mat_incr_def by auto\n  ultimately show \"\\<turnstile>\\<^sub>p {Q2} Utrans_P vars2 (mat_incr K) {P' + Q}\" by auto\nqed\n\nlemma qp_D3_post:\n  \"is_quantum_predicate (adjoint exM0 * P' * exM0 + adjoint exM1 * Q * exM1)\"\n  unfolding exP0_P' exP1_Q using qp_P'_Q by auto\n\nlemma hoare_triple_D:\n  \"\\<turnstile>\\<^sub>p \n   {Q} \n   D\n   {adjoint exM0 * P' * exM0 + adjoint exM1 * Q * exM1}\"\nproof -\n  have \"\\<turnstile>\\<^sub>p {Q1} hadamard_n n;; (Utrans_P vars1 mat_Ph;; hadamard_n n) {Q2}\"\n    using  well_com_hadamard_n well_com_mat_Ph hoare_triple_D2 qp_Q1 qp_Q2 by (auto simp add: hoare_patial_seq_assoc)\n  then have \"\\<turnstile>\\<^sub>p {Q} Utrans_P vars1 mat_O;; (hadamard_n n;; (Utrans_P vars1 mat_Ph;; hadamard_n n)) {Q2}\"\n    using hoare_triple_D1 qp_Q qp_Q1 qp_Q2 hoare_partial.intros(3) by auto\n  moreover have \"well_com (Utrans_P vars1 mat_Ph;; hadamard_n n)\" using well_com_hadamard_n well_com_mat_Ph by auto\n  ultimately have \"\\<turnstile>\\<^sub>p {Q} (Utrans_P vars1 mat_O;; hadamard_n n);; (Utrans_P vars1 mat_Ph;; hadamard_n n) {Q2}\"\n    using well_com_hadamard_n well_com_mat_O qp_Q qp_Q2 by (auto simp add: hoare_patial_seq_assoc)\n  moreover have \"well_com (Utrans_P vars1 mat_O;; hadamard_n n)\"\n    using well_com_mat_O well_com_hadamard_n by auto\n  ultimately have \"\\<turnstile>\\<^sub>p {Q} Utrans_P vars1 mat_O;; hadamard_n n;; Utrans_P vars1 mat_Ph;; hadamard_n n {Q2}\"\n    using well_com_hadamard_n well_com_mat_Ph qp_Q qp_Q2 by (auto simp add: hoare_patial_seq_assoc)\n  with qp_Q qp_Q2 qp_D3_post hoare_triple_D3 show \"\\<turnstile>\\<^sub>p \n   {Q} \n   D\n   {adjoint exM0 * P' * exM0 + adjoint exM1 * Q * exM1}\"\n    unfolding D_def using hoare_partial.intros(3) by auto\nqed\n\nlemma psi_is_psi_l0:\n  \"\\<psi> = psi_l 0\"\n  unfolding \\<psi>_eq psi_l_def alpha_l_def beta_l_def by auto\n\nlemma proj_psi_is_proj_psi_l0:\n  \"proj_psi = proj_psi_l 0\"\n  unfolding proj_psi_def psi_is_psi_l0 proj_psi_l_def by auto\n\nlemma lowner_le_Q:\n  \"tensor_P proj_psi (proj_k 0) \\<le>\\<^sub>L adjoint exM0 * P' * exM0 + adjoint exM1 * Q * exM1\"\nproof -\n  let ?r = \"matrix_sum d (\\<lambda>l. tensor_P (proj_psi_l l) (proj_k l)) (R + 1)\"\n  let ?l = \"tensor_P (proj_psi_l 0) (proj_k 0)\"\n  have eq: \"?r = ?l + matrix_sum d (\\<lambda>l. tensor_P (proj_psi_l (l + 1)) (proj_k (l + 1))) R\" (is \"_ = _ + ?s\")\n    apply (subst matrix_sum_Suc_remove_head)\n    using tensor_P_dim by auto\n  have d: \"?s \\<in> carrier_mat d d\"\n    apply (subst matrix_sum_dim) using tensor_P_dim by auto\n  have pt: \"positive (tensor_P (proj_psi_l l) (proj_k l))\" for l\n    unfolding ps2_P.ptensor_mat_def apply (subst ps_P.tensor_mat_positive)\n    unfolding ps_P_d1 ps_P_d2 using proj_psi_l_dim proj_k_dim positive_proj_psi_l positive_proj_k by auto\n  have ps: \"positive ?s\"\n    apply (subst matrix_sum_positive) \n    subgoal using tensor_P_dim by auto\n    using pt by auto\n  have \"?l \\<le>\\<^sub>L ?r\"\n    unfolding eq\n    apply (subst add_positive_le_reduce1[of ?l d ?s])\n    subgoal using tensor_P_dim by auto\n    subgoal using d by auto\n    subgoal using tensor_P_dim d by auto\n    subgoal using ps by auto\n     apply (subst lowner_le_refl[of _ d])\n    using tensor_P_dim d by auto\n  then show ?thesis unfolding exP0_P' exP1_Q P'_add_Q proj_psi_is_proj_psi_l0  by auto\nqed\n\nlemma hoare_triple_while:\n  \"\\<turnstile>\\<^sub>p \n   {adjoint exM0 * P' * exM0 + adjoint exM1 * Q * exM1} \n   While_P vars2 M0 M1 D\n   {P'}\"\nproof -\n  let ?m = \"\\<lambda>(n::nat). if n = 0 then mat_extension dims vars2 M0 else\n                       if n = 1 then mat_extension dims vars2 M1 else undefined\"\n  have dM0: \"M0 \\<in> carrier_mat K K\" unfolding M0_def by auto\n  have dM1: \"M1 \\<in> carrier_mat K K\" unfolding M1_def by auto\n  have m0: \"?m 0 = exM0\" apply (simp) unfolding exM0_def ps2_P.ptensor_mat_def mat_ext_vars2[OF dM0] by auto\n  have m1: \"?m 1 = exM1\" unfolding exM1_def ps2_P.ptensor_mat_def mat_ext_vars2[OF dM1] by auto\n  have \"\\<turnstile>\\<^sub>p {Q} D {adjoint (?m 0) * P' * (?m 0) + adjoint (?m 1) * Q * (?m 1)}\"\n    using hoare_triple_D m0 m1 by auto\n  then show ?thesis unfolding While_P_def using qp_D3_post qp_P' hoare_partial.intros(5)[OF qp_P' qp_Q, of D ?m] m0 m1 by auto\nqed\n\nlemma R_and_a_half_\\<theta>:\n  \"(R + 1/2) * \\<theta> = pi / 2\"\n  using R \\<theta>_neq_0 by auto\n\n\n\nlemma post_mult_beta:\n  \"post *\\<^sub>v \\<beta> = \\<beta>\"\n  by (auto simp add: post_def \\<beta>_def scalar_prod_def sum_only_one_neq_0)\n\nlemma post_mult_post:\n  \"post * post = post\"\n  by (auto simp add: post_def scalar_prod_def sum_only_one_neq_0)\n\nlemma post_mult_proj_psi_lR:\n  \"post * proj_psi_l R = proj_psi_l R\"\nproof -\n  let ?R = \"proj_psi_l R\"\n  have \"post * ?R = post * ?R * 1\\<^sub>m N\"\n    using post_dim proj_psi_l_dim[of R] by auto\n  also have \"\\<dots> = outer_prod (post *\\<^sub>v psi_l R) ((1\\<^sub>m N) *\\<^sub>v psi_l R)\"\n    unfolding proj_psi_l_def\n    apply (subst outer_prod_left_right_mat[of _ N _ N _ N _ N])\n    by (auto simp add: psi_l_dim post_dim adjoint_one)\n  also have \"\\<dots> = ?R\" unfolding proj_psi_l_def unfolding psi_lR_is_beta unfolding post_mult_beta\n    using \\<beta>_dim by auto\n  finally show \"post * ?R = ?R\".\nqed\n\nlemma proj_psi_lR_mult_post:\n  \"proj_psi_l R * post = proj_psi_l R\"\nproof -\n  let ?R = \"proj_psi_l R\"\n  have \"?R * post = 1\\<^sub>m N * ?R * post\"\n    using post_dim proj_psi_l_dim[of R] by auto\n  also have \"\\<dots> = outer_prod ((1\\<^sub>m N) *\\<^sub>v psi_l R) (post *\\<^sub>v psi_l R)\"\n    unfolding proj_psi_l_def\n    apply (subst outer_prod_left_right_mat[of _ N _ N _ N _ N])\n    by (auto simp add: psi_l_dim post_dim hermitian_post[unfolded hermitian_def])\n  also have \"\\<dots> = ?R\" unfolding proj_psi_l_def unfolding psi_lR_is_beta unfolding post_mult_beta\n    using \\<beta>_dim by auto\n  finally show \"?R * post = ?R\".\nqed\n\nlemma proj_psi_lR_mult_proj_psi_lR:\n  \"proj_psi_l R * proj_psi_l R = proj_psi_l R\"\n  unfolding proj_psi_l_def psi_lR_is_beta\n  apply (subst outer_prod_mult_outer_prod[of _ N _ N _ _ N])\n  by (auto simp add: \\<beta>_inner)\n\nlemma proj_psi_lR_le_post:\n  \"proj_psi_l R \\<le>\\<^sub>L post\"\nproof -\n  let ?R = \"proj_psi_l R\"\n  let ?s = \"post - ?R\"\n  have eq1: \"post * (post - ?R) = post - ?R\"\n    apply (subst mult_minus_distrib_mat[of _ N N _ N])\n      apply (auto simp add: post_dim proj_psi_l_dim[of R])\n    using post_mult_post post_mult_proj_psi_lR by auto\n  have eq2: \"?R * (post - ?R) = 0\\<^sub>m N N\"\n    apply (subst mult_minus_distrib_mat[of _ N N _ N])\n      apply (auto simp add: post_dim proj_psi_l_dim[of R])\n    unfolding proj_psi_lR_mult_post proj_psi_lR_mult_proj_psi_lR \n    using proj_psi_l_dim[of R] by auto\n  have \"adjoint ?s = ?s\"\n    apply (subst adjoint_minus[of _ N N])\n    using post_dim proj_psi_l_dim hermitian_post hermitian_proj_psi_l K by (auto simp add: hermitian_def)\n  then have \"?s * adjoint ?s = ?s * ?s\" by auto\n  also have \"\\<dots> = post * (post - ?R) - ?R * (post - ?R)\"\n    using post_dim proj_psi_l_dim[of R] by (mat_assoc N)\n  also have \"\\<dots> = post - ?R\"\n    unfolding eq1 eq2 using post_dim proj_psi_l_dim[of R] by auto\n  finally have \"?s * adjoint ?s = ?s\". \n  then have \"\\<exists>M. M * adjoint M = ?s\" by auto\n  then have \"positive ?s\" apply (subst positive_if_decomp[of ?s N]) using post_dim proj_psi_l_dim[of R] by auto\n  then show ?thesis unfolding lowner_le_def using post_dim proj_psi_l_dim[of R] by auto\nqed\n\nlemma P'_le_post_R:\n  \"P' \\<le>\\<^sub>L (tensor_P post (proj_k R))\"\nproof -\n  let ?r = \"tensor_P post (proj_k R)\"\n  have \"?r - P' = tensor_P (post - proj_psi_l R) (proj_k R)\"\n    unfolding P'_def ps2_P.ptensor_mat_def\n    apply (subst ps_P.tensor_mat_minus1)\n    unfolding ps_P_d1 ps_P_d2\n    using post_dim proj_psi_l_dim proj_k_dim by auto\n  moreover have \"positive (tensor_P (post - proj_psi_l R) (proj_k R))\"\n    unfolding ps2_P.ptensor_mat_def\n    apply (subst ps_P.tensor_mat_positive)\n    unfolding ps_P_d1 ps_P_d2 \n    using proj_psi_lR_le_post[unfolded lowner_le_def]\n      post_dim proj_psi_l_dim[of R] proj_k_dim positive_proj_k\n    by auto\n  ultimately show \"P' \\<le>\\<^sub>L ?r\"\n    unfolding lowner_le_def P'_def\n    using tensor_P_dim by auto\nqed\n\nlemma positive_post:\n  \"positive post\"\nproof -\n  have ad: \"adjoint post = post\" using hermitian_post[unfolded hermitian_def] by auto\n  then have \"post * adjoint post = post\"\n    unfolding ad post_mult_post by auto\n  then have \"\\<exists>M. M * adjoint M = post\" by auto\n  then show ?thesis using positive_if_decomp post_dim by auto\nqed\n\nlemma lowner_le_P':\n  \"P' \\<le>\\<^sub>L tensor_P post (1\\<^sub>m K)\"\nproof -\n  let ?r = \"tensor_P post (1\\<^sub>m K)\"\n  let ?m = \"tensor_P post (proj_k R)\"\n  have \"?m \\<le>\\<^sub>L ?r\"\n    unfolding ps2_P.ptensor_mat_def\n    apply (subst ps_P.tensor_mat_positive_le)\n    unfolding ps_P_d1 ps_P_d2\n    using post_dim proj_k_dim positive_post positive_proj_k\n      lowner_le_refl[of post] proj_k_le_one by auto\n  then show \"P' \\<le>\\<^sub>L ?r\"\n    using lowner_le_trans[of P' d ?m ?r] P'_le_post_R\n    unfolding P'_def using tensor_P_dim by auto\nqed\n\nlemma post_mult_testNk:\n  assumes \"f k\"\n  shows \"post * (testN k) = testN k\"\n  using assms by (auto simp add: post_def testN_def scalar_prod_def sum_only_one_neq_0)\n\nlemma post_mult_testNk_neg:\n  assumes \"\\<not> f k\"\n  shows \"post * testN k = 0\\<^sub>m N N\"\n  using assms by (auto simp add: post_def testN_def scalar_prod_def sum_only_one_neq_0)\n\nlemma testN_post1:\n  \"f k \\<Longrightarrow> adjoint (testN k) * post * testN k = testN k\"\n  apply (subst assoc_mult_mat[of _ N N _ N _ N])\n     apply (auto simp add: adjoint_dim testN_dim post_dim)\n  apply (subst post_mult_testNk, simp)\n  unfolding hermitian_testN[unfolded hermitian_def]\n  using testN_mult_testN by auto\n\nlemma testN_post2:\n  \"\\<not> f k \\<Longrightarrow> adjoint (testN k) * post * testN k = 0\\<^sub>m N N\"\n  apply (subst assoc_mult_mat[of _ N N _ N _ N])\n     apply (auto simp add: adjoint_dim testN_dim post_dim)\n  apply (subst post_mult_testNk_neg, simp)\n  unfolding hermitian_testN[unfolded hermitian_def]\n  using testN_dim[of k] by auto\n\ndefinition post_fst_k :: \"nat \\<Rightarrow> complex mat\" where\n  \"post_fst_k k = mat N N (\\<lambda>(i, j). if (i = j \\<and> f i \\<and> i < k) then 1 else 0)\"\n\nlemma post_fst_kN:\n  \"post_fst_k N = post\"\n  unfolding post_fst_k_def post_def by auto\n\nlemma post_fst_k_Suc:\n  \"f i \\<Longrightarrow> post_fst_k (Suc i) = testN i + post_fst_k i\"\n  apply (rule eq_matI)\n  unfolding post_fst_k_def testN_def by auto\n\nlemma post_fst_k_Suc_neg:\n  \"\\<not> f i \\<Longrightarrow> post_fst_k (Suc i) = post_fst_k i\"\n  apply (rule eq_matI)\n  unfolding post_fst_k_def\n    apply auto\n  using less_antisym by fastforce\n\nlemma testN_sum:\n  \"matrix_sum N (\\<lambda>k. adjoint (testN k) * post * testN k) N = post\"\nproof -\n  have \"m \\<le> N \\<Longrightarrow> matrix_sum N (\\<lambda>k. adjoint (testN k) * post * testN k) m = post_fst_k m\" for m\n  proof (induct m)\n    case 0\n    then show ?case apply simp unfolding post_fst_k_def by auto\n  next\n    case (Suc m) \n    then have m: \"m \\<le> N\" by auto\n    show ?case\n    proof (cases \"f m\")\n      case True\n      show ?thesis apply simp\n        apply (subst testN_post1[OF True])\n        apply (subst Suc(1)[OF m])\n        using post_fst_k_Suc True by auto\n    next\n      case False\n      show ?thesis apply simp\n        apply (subst testN_post2[OF False])\n        apply (subst Suc(1)[OF m])\n        using post_fst_k_Suc_neg False post_fst_k_def by auto\n    qed\n  qed\n  then show ?thesis using post_fst_kN by auto\nqed\n\nlemma tensor_P_testN_sum:\n  \"matrix_sum d (\\<lambda>k. adjoint (tensor_P (testN k) (1\\<^sub>m K)) * tensor_P post (1\\<^sub>m K) * tensor_P (testN k) (1\\<^sub>m K)) N =\n   tensor_P post (1\\<^sub>m K)\"\nproof -\n  have eq: \"adjoint (tensor_P (testN k) (1\\<^sub>m K)) * tensor_P post (1\\<^sub>m K) * tensor_P (testN k) (1\\<^sub>m K) =\n            tensor_P (adjoint (testN k) * post * (testN k)) (1\\<^sub>m K)\" for k\n    apply (subst tensor_P_adjoint_left_right)\n    subgoal unfolding testN_def by auto\n    subgoal by auto\n    subgoal using post_dim by auto\n    using adjoint_one by auto\n  moreover have \"matrix_sum N (\\<lambda>k. adjoint (testN k) * post * testN k) N = post\"\n    using testN_sum by auto\n  show ?thesis unfolding eq\n    apply (subst matrix_sum_tensor_P1)\n    subgoal unfolding testN_def by auto\n    subgoal by auto\n    using testN_sum by auto\nqed\n\nlemma post_le_one:\n  \"post \\<le>\\<^sub>L 1\\<^sub>m N\"\nproof -\n  let ?s = \"1\\<^sub>m N - post\"\n  have eq1: \"1\\<^sub>m N * (1\\<^sub>m N - post) = 1\\<^sub>m N - post\"\n    apply (mat_assoc N) using post_dim by auto\n  have eq2: \"post * (1\\<^sub>m N - post) = 0\\<^sub>m N N\"\n    apply (subst mult_minus_distrib_mat[of _ N N])\n    using post_dim by (auto simp add: post_mult_post)\n\n  have \"adjoint ?s = ?s\" \n    apply (subst adjoint_minus)\n      apply (auto simp add: post_dim adjoint_dim)\n    using adjoint_one hermitian_post[unfolded hermitian_def] by auto\n  then have \"?s * adjoint ?s = ?s * ?s\" by auto\n  also have \"\\<dots> = 1\\<^sub>m N * (1\\<^sub>m N - post) - post * (1\\<^sub>m N - post)\"\n    apply (mat_assoc N) using post_dim by auto\n  also have \"\\<dots> = ?s\" unfolding eq1 eq2 using post_dim by auto\n  finally have \"?s * adjoint ?s = ?s\".\n  then have \"\\<exists>M. M * adjoint M = ?s\" by auto\n  then have \"positive ?s\" apply (subst positive_if_decomp[of ?s N]) using post_dim by auto\n  then show ?thesis unfolding lowner_le_def using post_dim by auto\nqed\n\nlemma qp_post:\n  \"is_quantum_predicate (tensor_P post (1\\<^sub>m K))\"\n  unfolding is_quantum_predicate_def\nproof (intro conjI)\n  show \"tensor_P post (1\\<^sub>m K) \\<in> carrier_mat d d\"\n    using tensor_P_dim by auto\n  show \"positive (tensor_P post (1\\<^sub>m K))\"\n    unfolding ps2_P.ptensor_mat_def\n    apply (subst ps_P.tensor_mat_positive)\n    by (auto simp add: ps_P_d1 ps_P_d2 post_dim positive_post positive_one)\n  show \"tensor_P post (1\\<^sub>m K) \\<le>\\<^sub>L 1\\<^sub>m d\"\n    unfolding ps_P.tensor_mat_id[symmetric, unfolded ps_P_d ps_P_d1 ps_P_d2]\n    unfolding ps2_P.ptensor_mat_def\n    apply (subst ps_P.tensor_mat_positive_le)\n    unfolding ps_P_d1 ps_P_d2 using post_dim positive_post positive_one post_le_one lowner_le_refl[of \"1\\<^sub>m K\" K]\n    by auto\nqed\n\nlemma hoare_triple_if:\n  \"\\<turnstile>\\<^sub>p \n   {tensor_P post (1\\<^sub>m K)} \n   Measure_P vars1 N testN (replicate N SKIP)\n   {tensor_P post (1\\<^sub>m K)}\"\nproof -\n  define M where \"M = (\\<lambda>n. mat_extension dims vars1 (testN n))\"\n  define Post where \"Post = (\\<lambda>(k::nat). tensor_P post (1\\<^sub>m K))\"\n  have M: \"M = (\\<lambda>n. tensor_P (testN n) (1\\<^sub>m K))\"\n    unfolding M_def using mat_ext_vars1 by auto\n  have skip: \"\\<And>k. k < N \\<Longrightarrow> (replicate N SKIP) ! k = SKIP\" by simp\n  have h: \"\\<And>k. k < N \\<Longrightarrow> \\<turnstile>\\<^sub>p {Post k} replicate N SKIP ! k {tensor_P post (1\\<^sub>m K)}\"\n    unfolding Post_def skip using qp_post hoare_partial.intros by auto\n  moreover have \"\\<And>k. k < N \\<Longrightarrow> is_quantum_predicate (Post k)\" unfolding Post_def using qp_post by auto\n  ultimately show ?thesis\n    unfolding Measure_P_def apply (fold M_def) \n    using hoare_partial.intros(4)[of N Post \"tensor_P post (1\\<^sub>m K)\" \"replicate N SKIP\" M]\n    unfolding M Post_def using tensor_P_testN_sum qp_post by auto\nqed\n\ntheorem grover_partial_deduct:\n  \"\\<turnstile>\\<^sub>p\n   {tensor_P pre (proj_k 0)}\n    Grover\n   {tensor_P post (1\\<^sub>m K)}\"\n  unfolding Grover_def\nproof -\n  have \"\\<turnstile>\\<^sub>p\n   {tensor_P pre (proj_k 0)}\n    hadamard_n n\n   {adjoint exM0 * P' * exM0 + adjoint exM1 * Q * exM1}\"\n    using hoare_partial.intros(6)[OF qp_pre qp_D3_post qp_pre qp_init_post]\n    hoare_triple_init lowner_le_refl[OF tensor_P_dim] lowner_le_Q by auto\n  then have \"\\<turnstile>\\<^sub>p\n   {tensor_P pre (proj_k 0)}\n    hadamard_n n;;\n    While_P vars2 M0 M1 D\n   {P'}\"\n    using hoare_triple_while hoare_partial.intros(3) qp_pre qp_D3_post qp_P' by auto\n  then have \"\\<turnstile>\\<^sub>p\n   {tensor_P pre (proj_k 0)}\n    hadamard_n n;;\n    While_P vars2 M0 M1 D\n   {tensor_P post (1\\<^sub>m K)}\"\n    using lowner_le_P' hoare_partial.intros(6)[OF qp_pre qp_post qp_pre qp_P'] \n      lowner_le_P' lowner_le_refl[OF tensor_P_dim] by auto\n  then show \" \\<turnstile>\\<^sub>p\n   {tensor_P pre (proj_k 0)}\n    hadamard_n n;;\n    While_P vars2 M0 M1 D;;\n    Measure_P vars1 N testN (replicate N SKIP)\n   {tensor_P post (1\\<^sub>m K)}\"\n    using hoare_triple_if qp_pre qp_post hoare_partial.intros(3) by auto\nqed\n\ntheorem grover_partial_correct:\n  \"\\<Turnstile>\\<^sub>p\n   {tensor_P pre (proj_k 0)}\n    Grover\n   {tensor_P post (1\\<^sub>m K)}\"\n  using grover_partial_deduct well_com_Grover qp_pre qp_post hoare_partial_sound by auto\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/QHLProver/Grover.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8688267626522814, "lm_q2_score": 0.8175744673038222, "lm_q1q2_score": 0.7103305776547434}}
{"text": "(*  Title:      Util_Div.thy\n    Date:       Oct 2006\n    Author:     David Trachtenherz\n*)\n\nheader {* Results for division and modulo operators on integers *}\n\ntheory Util_Div\nimports Util_Nat\nbegin\n\n\n\nsubsection {* Additional (in-)equalities with @{text div} and @{text mod} *}\n\ncorollary Suc_mod_le_divisor: \"0 < m \\<Longrightarrow> Suc (n mod m) \\<le> m\" \nby (rule Suc_leI, rule mod_less_divisor)\n\nlemma mod_less_dividend: \"\\<lbrakk> 0 < m; m \\<le> n \\<rbrakk> \\<Longrightarrow> n mod m < (n::nat)\" \nby (rule less_le_trans[OF mod_less_divisor])\n(*lemma mod_le_dividend: \"n mod m \\<le> (n::nat)\"*)\nlemmas mod_le_dividend = mod_less_eq_dividend\n\n\n\nlemma diff_mod_le: \"(t - r) mod m \\<le> (t::nat)\"\nby (rule le_trans[OF mod_le_dividend, OF diff_le_self])\n\n\n(*corollary div_mult_cancel: \"m div n * n = m - m mod (n::nat)\"*)\nlemmas div_mult_cancel = div_mod_equality'\n\nlemma mod_0_div_mult_cancel: \"(n mod (m::nat) = 0) = (n div m * m = n)\"\napply (insert eq_diff_left_iff[OF mod_le_dividend le0, of n m])\napply (simp add: mult.commute mult_div_cancel)\ndone\n\nlemma div_mult_le: \"(n::nat) div m * m \\<le> n\" \nby (simp add: mult.commute mult_div_cancel)\nlemma less_div_Suc_mult: \"0 < (m::nat) \\<Longrightarrow> n < Suc (n div m) * m\"\napply (simp add: mult.commute mult_div_cancel)\napply (rule less_add_diff)\nby (rule mod_less_divisor)\n\nlemma nat_ge2_conv: \"((2::nat) \\<le> n) = (n \\<noteq> 0 \\<and> n \\<noteq> 1)\"\nby fastforce\n\nlemma Suc0_mod: \"m \\<noteq> Suc 0 \\<Longrightarrow> Suc 0 mod m = Suc 0\"\nby (case_tac m, simp_all)\ncorollary Suc0_mod_subst: \"\n  \\<lbrakk> m \\<noteq> Suc 0; P (Suc 0) \\<rbrakk> \\<Longrightarrow> P (Suc 0 mod m)\"\nby (blast intro: subst[OF Suc0_mod[symmetric]])\ncorollary Suc0_mod_cong: \"\n  m \\<noteq> Suc 0 \\<Longrightarrow> f (Suc 0 mod m) = f (Suc 0)\"\nby (blast intro: arg_cong[OF Suc0_mod])\n\nsubsection {* Additional results for addition and subtraction with @{text mod} *}\n\nlemma mod_Suc_conv: \"\n  ((Suc a) mod m = (Suc b) mod m) = (a mod m = b mod m)\"\nby (simp add: mod_Suc)\n\nlemma mod_Suc': \"\n  0 < n \\<Longrightarrow> Suc m mod n = (if m mod n < n - Suc 0 then Suc (m mod n) else 0)\"\napply (simp add: mod_Suc)\napply (intro conjI impI)\n apply simp\napply (insert le_neq_trans[OF mod_less_divisor[THEN Suc_leI, of n m]], simp)\ndone\n\nlemma mod_add:\"\n  ((a + k) mod m = (b + k) mod m) = \n  ((a::nat) mod m = b mod m)\"\nby (induct \"k\", simp_all add: mod_Suc_conv)\n\ncorollary mod_sub_add: \"\n  k \\<le> (a::nat) \\<Longrightarrow>\n  ((a - k) mod m = b mod m) = (a mod m = (b + k) mod m)\"\nby (simp add: mod_add[where m=m and a=\"a-k\" and b=b and k=k, symmetric])\n\n\nlemma mod_sub_eq_mod_0_conv: \"\n  a + b \\<le> (n::nat) \\<Longrightarrow> \n  ((n - a) mod m = b mod m) = ((n - (a + b)) mod m = 0)\"\nby (insert mod_add[of \"n-(a+b)\" b m 0], simp)\nlemma mod_sub_eq_mod_swap: \"\n  \\<lbrakk> a \\<le> (n::nat); b \\<le> n \\<rbrakk> \\<Longrightarrow> \n  ((n - a) mod m = b mod m) = ((n - b) mod m = a mod m)\"\nby (simp add: mod_sub_add add.commute)\n\nlemma le_mod_greater_imp_div_less: \"\n  \\<lbrakk> a \\<le> (b::nat); a mod m > b mod m \\<rbrakk> \\<Longrightarrow> a div m < b div m\"\napply (rule ccontr, simp add: linorder_not_less)\napply (drule mult_le_mono1[of \"b div m\" _ m])\napply (drule add_less_le_mono[of \"b mod m\" \"a mod m\" \"b div m * m\" \"a div m * m\"])\napply simp_all\ndone\n\nlemma less_mod_ge_imp_div_less: \"\\<lbrakk> a < (b::nat); a mod m \\<ge> b mod m \\<rbrakk> \\<Longrightarrow> a div m < b div m\"\napply (case_tac \"m = 0\", simp)\napply (rule mult_less_cancel1[of m, THEN iffD1, THEN conjunct2])\napply (simp add: mult_div_cancel)\napply (rule order_less_le_trans[of _ \"b - a mod m\"])\napply (rule diff_less_mono)\napply simp+\ndone\ncorollary less_mod_0_imp_div_less: \"\\<lbrakk> a < (b::nat); b mod m = 0 \\<rbrakk> \\<Longrightarrow> a div m < b div m\"\nby (simp add: less_mod_ge_imp_div_less)\n\nlemma mod_diff_right_eq: \"\n  (a::nat) \\<le> b \\<Longrightarrow> (b - a) mod m = (b - a mod m) mod m\"\nproof -\n  assume a_as:\"a \\<le> b\"\n  have \"(b - a) mod m = (b - a + a div m * m) mod m\" by simp\n  also have \"\\<dots> = (b + a div m * m - a) mod m\" using a_as by simp\n  also have \"\\<dots> = (b + a div m * m - (a div m * m + a mod m)) mod m\" by simp\n  also have \"\\<dots> = (b + a div m * m - a div m * m - a mod m) mod m\" \n    by (simp only: diff_diff_left[symmetric])\n  also have \"\\<dots> = (b - a mod m) mod m\" by simp\n  finally show ?thesis .\nqed\ncorollary mod_eq_imp_diff_mod_eq: \"\n  \\<lbrakk> x mod m = y mod m; x \\<le> (t::nat); y \\<le> t \\<rbrakk> \\<Longrightarrow> \n  (t - x) mod m = (t - y) mod m\"\nby (simp only: mod_diff_right_eq)\nlemma mod_eq_imp_diff_mod_eq2: \"\n  \\<lbrakk> x mod m = y mod m; (t::nat) \\<le> x; t \\<le> y \\<rbrakk> \\<Longrightarrow> \n  (x - t) mod m = (y - t) mod m\"\napply (case_tac \"m = 0\", simp+)\napply (subst mod_mult_self2[of \"x - t\" m t, symmetric])\napply (subst mod_mult_self2[of \"y - t\" m t, symmetric])\napply (simp only: add_diff_assoc2 diff_add_assoc gr0_imp_self_le_mult2)\napply (simp only: mod_add)\ndone\n\nlemma divisor_add_diff_mod_if: \"\n  (m + b mod m - a mod m) mod (m::nat)= (\n  if a mod m \\<le> b mod m \n  then (b mod m - a mod m) \n  else (m + b mod m - a mod m))\"\napply (case_tac \"m = 0\", simp)\napply clarsimp\napply (subst diff_add_assoc, assumption)\napply (simp only: mod_add_self1)\napply (rule mod_less)\napply (simp add: less_imp_diff_less)\ndone\ncorollary divisor_add_diff_mod_eq1: \"\n  a mod m \\<le> b mod m \\<Longrightarrow> \n  (m + b mod m - a mod m) mod (m::nat) = b mod m - a mod m\"\nby (simp add: divisor_add_diff_mod_if)\ncorollary divisor_add_diff_mod_eq2: \"\n  b mod m < a mod m \\<Longrightarrow> \n  (m + b mod m - a mod m) mod (m::nat) = m + b mod m - a mod m\"\nby (simp add: divisor_add_diff_mod_if)\n\nlemma mod_add_mod_if: \"\n  (a mod m + b mod m) mod (m::nat)= (\n  if a mod m + b mod m < m\n  then a mod m + b mod m \n  else a mod m + b mod m - m)\"\napply (case_tac \"m = 0\", simp_all)\napply (clarsimp simp: linorder_not_less)\napply (simp add: mod_if[of \"a mod m + b mod m\"])\napply (rule mod_less)\napply (rule diff_less_conv[THEN iffD2], assumption)\napply (simp add: add_less_mono)\ndone\ncorollary mod_add_mod_eq1: \"\n  a mod m + b mod m < m \\<Longrightarrow> \n  (a mod m + b mod m) mod (m::nat) = a mod m + b mod m\"\nby (simp add: mod_add_mod_if)\ncorollary mod_add_mod_eq2: \"\n  m \\<le> a mod m + b mod m\\<Longrightarrow> \n  (a mod m + b mod m) mod (m::nat) = a mod m + b mod m - m\"\nby (simp add: mod_add_mod_if)\n\nlemma mod_add1_eq_if: \"\n  (a + b) mod (m::nat) = (\n  if (a mod m + b mod m < m) then a mod m + b mod m\n  else a mod m + b mod m - m)\"\nby (simp add: mod_add_eq[of a b] mod_add_mod_if)\n\nlemma mod_add_eq_mod_conv: \"0 < (m::nat) \\<Longrightarrow> \n  ((x + a) mod m = b mod m ) =\n  (x mod m = (m + b mod m - a mod m) mod m)\"\napply (simp only: mod_add_eq[of x a])\napply (rule iffI)\n apply (drule sym)\n apply (simp add: mod_add_mod_if)\napply (simp add: mod_add_left_eq[symmetric] le_add_diff_inverse2[OF trans_le_add1[OF mod_le_divisor]])\ndone\n\n\n\n\nlemma mod_diff1_eq: \"\n  (a::nat) \\<le> b \\<Longrightarrow> (b - a) mod m = (m + b mod m - a mod m) mod m\"\napply (case_tac \"m = 0\", simp)\napply simp\nproof -\n  assume a_as:\"a \\<le> b\"\n    and m_as: \"0 < m\"\n  have a_mod_le_b_s: \"a mod m \\<le> b\"\n    by (rule le_trans[of _ a], simp only: mod_le_dividend, simp only: a_as)\n  have \"(b - a) mod m = (b - a mod m) mod m\"\n    using a_as by (simp only: mod_diff_right_eq)\n  also have \"\\<dots> = (b - a mod m + m) mod m\"\n    by simp\n  also have \"\\<dots> = (b + m - a mod m) mod m\"\n    using a_mod_le_b_s by simp\n  also have \"\\<dots> = (b div m * m + b mod m + m - a mod m) mod m\"\n    by simp\n  also have \"\\<dots> = (b div m * m + (b mod m + m - a mod m)) mod m\"\n    by (simp add: diff_add_assoc[OF mod_le_divisor, OF m_as])\n  also have \"\\<dots> = ((b mod m + m - a mod m) + b div m * m) mod m\"\n    by simp\n  also have \"\\<dots> = (b mod m + m - a mod m) mod m\"\n    by simp\n  also have \"\\<dots> = (m + b mod m - a mod m) mod m\"\n    by (simp only: add.commute)\n  finally show ?thesis .\nqed\ncorollary mod_diff1_eq_if: \"\n  (a::nat) \\<le> b \\<Longrightarrow> (b - a) mod m = (\n    if a mod m \\<le> b mod m then b mod m - a mod m\n    else m + b mod m - a mod m)\"\nby (simp only: mod_diff1_eq divisor_add_diff_mod_if)\ncorollary mod_diff1_eq1: \"\n  \\<lbrakk> (a::nat) \\<le> b; a mod m \\<le> b mod m \\<rbrakk> \n  \\<Longrightarrow> (b - a) mod m = b mod m - a mod m\"\nby (simp add: mod_diff1_eq_if)\ncorollary mod_diff1_eq2: \"\n  \\<lbrakk> (a::nat) \\<le> b; b mod m < a mod m\\<rbrakk> \n  \\<Longrightarrow> (b - a) mod m = m + b mod m - a mod m\"\nby (simp add: mod_diff1_eq_if)\n\n\n\n\n\n\nsubsubsection {* Divisor subtraction with @{text div} and @{text mod} *}\n\nlemma mod_diff_self1: \"\n  0 < (n::nat) \\<Longrightarrow> (m - n) mod m = m - n\"\nby (case_tac \"m = 0\", simp_all)\nlemma mod_diff_self2: \"\n  m \\<le> (n::nat) \\<Longrightarrow> (n - m) mod m = n mod m\"\nby (simp add: mod_diff_right_eq)\nlemma mod_diff_mult_self1: \"\n  k * m \\<le> (n::nat) \\<Longrightarrow> (n - k * m) mod m = n mod m\"\nby (simp add: mod_diff_right_eq)\nlemma mod_diff_mult_self2: \"\n  m * k \\<le> (n::nat) \\<Longrightarrow> (n - m * k) mod m = n mod m\"\nby (simp only: mult.commute[of m k] mod_diff_mult_self1)\n\nlemma div_diff_self1: \"0 < (n::nat) \\<Longrightarrow> (m - n) div m = 0\"\nby (case_tac \"m = 0\", simp_all)\nlemma div_diff_self2: \"(n - m) div m = n div m - Suc 0\"\napply (case_tac \"m = 0\", simp)\napply (case_tac \"n < m\", simp)\napply (case_tac \"n = m\", simp)\napply (simp add: div_if)\ndone\n\nlemma div_diff_mult_self1: \"\n  (n - k * m) div m = n div m - (k::nat)\"\napply (case_tac \"m = 0\", simp)\napply (case_tac \"n < k * m\")\n apply simp\n apply (drule div_le_mono[OF less_imp_le, of n _ m])\n apply simp\napply (simp add: linorder_not_less)\napply (rule iffD1[OF mult_cancel1_gr0[where k=m]], assumption)\napply (subst diff_mult_distrib2)\napply (simp only: mult_div_cancel)\napply (simp only: diff_commute[of _ \"k*m\"])\napply (simp only: mult.commute[of m])\napply (simp only: mod_diff_mult_self1)\ndone\nlemma div_diff_mult_self2: \"\n  (n - m * k) div m = n div m - (k::nat)\"\nby (simp only: mult.commute div_diff_mult_self1)\n\n\n\nsubsubsection {* Modulo equality and modulo of difference*}\n\nlemma mod_eq_imp_diff_mod_0:\"\n  (a::nat) mod m = b mod m \\<Longrightarrow> (b - a) mod m = 0\"\n  (is \"?P \\<Longrightarrow> ?Q\")\nproof -\n  assume as1: ?P\n  have \"b - a = b div m * m + b mod m - (a div m * m + a mod m)\"\n    by simp\n  also have \"\\<dots> = b div m * m + b mod m - (a mod m + a div m * m)\" \n    by simp\n  also have \"\\<dots> = b div m * m + b mod m - a mod m - a div m * m\"\n    by simp\n  also have \"\\<dots> = b div m * m + b mod m - b mod m - a div m * m\"\n    using as1 by simp\n  also have \"\\<dots> = b div m * m - a div m * m\"\n    by (simp only: diff_add_inverse2)\n  also have \"\\<dots> = (b div m - a div m) * m\" \n    by (simp only: diff_mult_distrib)\n  finally have \"b - a = (b div m - a div m) * m\" .\n  hence \"(b - a) mod m = (b div m - a div m) * m mod m\"\n    by (rule arg_cong)\n  thus ?thesis by (simp only: mod_mult_self2_is_0)\nqed\ncorollary mod_eq_imp_diff_dvd: \"\n  (a::nat) mod m = b mod m \\<Longrightarrow> m dvd b - a\"\nby (rule dvd_eq_mod_eq_0[THEN iffD2, OF mod_eq_imp_diff_mod_0])\n\nlemma mod_neq_imp_diff_mod_neq0:\"\n  \\<lbrakk> (a::nat) mod m \\<noteq> b mod m; a \\<le> b \\<rbrakk> \\<Longrightarrow> 0 < (b - a) mod m\"\napply (case_tac \"m = 0\", simp)\napply (drule le_imp_less_or_eq, erule disjE)\n prefer 2 \n apply simp\napply (drule neq_iff[THEN iffD1], erule disjE)\n apply (simp add: mod_diff1_eq1)\napply (simp add: mod_diff1_eq2[OF less_imp_le] trans_less_add1[OF mod_less_divisor])\ndone\ncorollary mod_neq_imp_diff_not_dvd:\"\n  \\<lbrakk> (a::nat) mod m \\<noteq> b mod m; a \\<le> b \\<rbrakk> \\<Longrightarrow> \\<not> m dvd b - a\"\nby (simp add: dvd_eq_mod_eq_0 mod_neq_imp_diff_mod_neq0)\n\nlemma diff_mod_0_imp_mod_eq:\"\n  \\<lbrakk> (b - a) mod m = 0; a \\<le> b \\<rbrakk> \\<Longrightarrow> (a::nat) mod m = b mod m\"\napply (rule ccontr)\napply (drule mod_neq_imp_diff_mod_neq0)\napply simp_all\ndone\ncorollary diff_dvd_imp_mod_eq:\"\n  \\<lbrakk> m dvd b - a; a \\<le> b \\<rbrakk> \\<Longrightarrow> (a::nat) mod m = b mod m\"\nby (rule dvd_eq_mod_eq_0[THEN iffD1, THEN diff_mod_0_imp_mod_eq])\n\n\n\nlemma mod_eq_diff_mod_0_conv: \"\n  a \\<le> (b::nat) \\<Longrightarrow> (a mod m = b mod m) = ((b - a) mod m = 0)\"\napply (rule iffI)\napply (rule mod_eq_imp_diff_mod_0, assumption)\napply (rule diff_mod_0_imp_mod_eq, assumption+)\ndone\ncorollary mod_eq_diff_dvd_conv: \"\n  a \\<le> (b::nat) \\<Longrightarrow> (a mod m = b mod m) = (m dvd b - a)\"\nby (rule dvd_eq_mod_eq_0[symmetric, THEN subst], rule mod_eq_diff_mod_0_conv)\n\n\n\nsubsection {* Some additional lemmata about integer @{text div} and @{text mod} *}\n\nlemma zmod_eq_imp_diff_mod_0:\"\n  (a::int) mod m = b mod m \\<Longrightarrow> (b - a) mod m = 0\"\n  by (metis diff_minus_eq_add minus_minus mod_0 right_minus ring_div_class.mod_diff_right_eq)\n\n(*lemma int_mod_distrib: \"int (n mod m) = int n mod int m\"*)\nlemmas int_mod_distrib = zmod_int\n\nlemma zdiff_mod_0_imp_mod_eq__pos:\"\n  \\<lbrakk> (b - a) mod m = 0; 0 < (m::int) \\<rbrakk> \\<Longrightarrow> a mod m = b mod m\"\n  (is \"\\<lbrakk> ?P; ?Pm \\<rbrakk> \\<Longrightarrow> ?Q\")\nproof -\n  assume as1: ?P\n    and as2: \"0 < m\"\n\n  obtain r1 where a_r1:\"r1 = a mod m\" by blast\n  obtain r2 where b_r2:\"r2 = b mod m\" by blast\n\n  obtain q1 where a_q1: \"q1 = a div m\" by blast\n  obtain q2 where b_q2: \"q2 = b div m\" by blast\n\n  have a_r1_q1: \"a = m * q1 + r1\" \n    using a_r1 a_q1 by simp\n  have b_r2_q2: \"b = m * q2 + r2\"\n    using b_r2 b_q2 by simp\n\n  have \"b - a = m * q2 + r2 - (m * q1 + r1)\"\n    using a_r1_q1 b_r2_q2 by simp\n  also have \"\\<dots> = m * q2 + r2 - m * q1 - r1\"\n    by simp\n  also have \"\\<dots> = m * q2 - m * q1 + r2 - r1\"\n    by simp\n  finally have \"b - a = m * (q2 - q1) + (r2 - r1)\"\n    by (simp add: right_diff_distrib)\n  hence \"(b - a) mod m = (r2 - r1) mod m\"\n    by (simp add: mod_add_eq)\n  hence r2_r1_mod_m_0:\"(r2 - r1) mod m = 0\" (is \"?R1\")\n    by (simp only: as1)\n\n  have \"r1 = r2\"\n  proof (rule notI[of \"r1 \\<noteq> r2\", simplified])\n    assume as1': \"r1 \\<noteq> r2\"\n    have diff_le_s: \"\\<And>a b (m::int). \\<lbrakk> 0 \\<le> a; b < m \\<rbrakk> \\<Longrightarrow> b - a < m\"\n      by simp\n    have s_r1:\"0 \\<le> r1 \\<and> r1 < m\" and s_r2:\"0 \\<le> r2 \\<and> r2 < m\"\n      by (simp add: as2 a_r1 b_r2 pos_mod_conj)+\n    have mr2r1:\"-m < r2 - r1\" and r2r1m:\"r2 - r1 < m\"\n      by (simp add: minus_less_iff[of m] s_r1 s_r2 diff_le_s)+\n    have \"0 \\<le> r2 - r1 \\<Longrightarrow> (r2 - r1) mod m = (r2 - r1)\"\n      using r2r1m by (blast intro: mod_pos_pos_trivial)\n    hence s1_pos: \"0 \\<le> r2 - r1 \\<Longrightarrow> r2 - r1 = 0\"\n      using r2_r1_mod_m_0 by simp\n    \n    have \"(r2-r1) mod -m = 0\"\n      by (simp add: zmod_zminus2_eq_if[of \"r2-r1\" m, simplified] r2_r1_mod_m_0)\n    moreover\n    have \"r2 - r1 \\<le> 0 \\<Longrightarrow> (r2 - r1) mod -m = r2 - r1\"\n      using mr2r1\n      by (simp add: mod_neg_neg_trivial)\n    ultimately have s1_neg:\"r2 - r1 \\<le> 0 \\<Longrightarrow> r2 - r1 = 0\"\n      by simp\n    \n    have \"r2 - r1 = 0\"\n      using s1_pos s1_neg linorder_linear by blast\n    hence \"r1 = r2\" by simp\n    thus False\n      using as1' by blast\n  qed\n  thus ?thesis\n    using a_r1 b_r2 by blast\nqed\n\nlemma zmod_zminus_eq_conv_pos: \"\n  0 < (m::int) \\<Longrightarrow> (a mod - m = b mod - m) = (a mod m = b mod m)\"\napply (simp only: mod_minus_right neg_equal_iff_equal)\napply (simp only: zmod_zminus1_eq_if)\napply (split split_if)+\napply (safe, simp_all)\napply (insert pos_mod_bound[of m a] pos_mod_bound[of m b], simp_all)\ndone\nlemma zmod_zminus_eq_conv: \"\n  ((a::int) mod - m = b mod - m) = (a mod m = b mod m)\"\napply (insert linorder_less_linear[of 0 m], elim disjE)\napply (blast dest: zmod_zminus_eq_conv_pos)\napply simp\napply (simp add: zmod_zminus_eq_conv_pos[of \"-m\", symmetric])\ndone\n\nlemma zdiff_mod_0_imp_mod_eq:\"\n  (b - a) mod m = 0 \\<Longrightarrow> (a::int) mod m = b mod m\"\nby (metis dvd_eq_mod_eq_0 zmod_eq_dvd_iff)\n\nlemma zmod_eq_diff_mod_0_conv: \"\n  ((a::int) mod m = b mod m) = ((b - a) mod m = 0)\"\napply (rule iffI)\napply (rule zmod_eq_imp_diff_mod_0, assumption)\napply (rule zdiff_mod_0_imp_mod_eq, assumption)\ndone\n\nlemma \"\\<not>(\\<exists>(a::int) b m. (b - a) mod m = 0 \\<and> a mod m \\<noteq> b mod m)\"\nby (simp add: zmod_eq_diff_mod_0_conv)\nlemma \"\\<exists>(a::nat) b m. (b - a) mod m = 0 \\<and> a mod m \\<noteq> b mod m\"\napply (rule_tac x=1 in exI)\napply (rule_tac x=0 in exI)\napply (rule_tac x=2 in exI)\napply simp\ndone\n\n\n\nlemma zmult_div_leq_mono:\"\n  \\<lbrakk> (0::int) \\<le> x; a \\<le> b; 0 < d \\<rbrakk> \\<Longrightarrow> x * a div d \\<le> x * b div d\"\nby (metis mult_right_mono zdiv_mono1 mult.commute)\n\nlemma zmult_div_leq_mono_neg:\"\n  \\<lbrakk> x \\<le> (0::int); a \\<le> b; 0 < d \\<rbrakk> \\<Longrightarrow> x * b div d \\<le> x * a div d\"\nby (metis mult_left_mono_neg zdiv_mono1)\n\nlemma zmult_div_pos_le:\"\n  \\<lbrakk> (0::int) \\<le> a; 0 \\<le> b; b \\<le> c \\<rbrakk> \\<Longrightarrow> a * b div c \\<le> a\"\napply (case_tac \"b = 0\", simp)\napply (subgoal_tac \"b * a \\<le> c * a\")\n prefer 2 \n apply (simp only: mult_right_mono)\napply (simp only: mult.commute)\napply (subgoal_tac \"a * b div c \\<le> a * c div c\")\n prefer 2 \n apply (simp only: zdiv_mono1)\napply simp\ndone\n\nlemma zmult_div_neg_le:\"\n  \\<lbrakk> a \\<le> (0::int); 0 < c; c \\<le> b \\<rbrakk> \\<Longrightarrow> a * b div c \\<le> a\"\napply (subgoal_tac \"b * a \\<le> c * a\")\n prefer 2 \n apply (simp only: mult_right_mono_neg)\napply (simp only: mult.commute)\napply (subgoal_tac \"a * b div c \\<le> a * c div c\")\n prefer 2 \n apply (simp only: zdiv_mono1)\napply simp\ndone\n\nlemma zmult_div_ge_0:\"\\<lbrakk> (0::int) \\<le> x; 0 \\<le> a; 0 < c \\<rbrakk> \\<Longrightarrow> 0 \\<le> a * x div c\"\nby (metis pos_imp_zdiv_nonneg_iff split_mult_pos_le)\n\ncorollary zmult_div_plus_ge_0: \"\n  \\<lbrakk> (0::int) \\<le> x; 0 \\<le> a; 0 \\<le> b; 0 < c\\<rbrakk> \\<Longrightarrow> 0 \\<le> a * x div c + b\"\nby (insert zmult_div_ge_0[of x a c], simp)\n\n\n\n\nlemma zmult_div_abs_ge: \"\n  \\<lbrakk> (0::int) \\<le> b; b \\<le> b'; 0 \\<le> a; 0 < c\\<rbrakk> \\<Longrightarrow>\n  \\<bar>a * b div c\\<bar> \\<le> \\<bar>a * b' div c\\<bar>\"\napply (insert zmult_div_ge_0[of b a c] zmult_div_ge_0[of \"b'\" a c], simp)\nby (metis zmult_div_leq_mono)\n\nlemma zmult_div_plus_abs_ge: \" \n  \\<lbrakk> (0::int) \\<le> b; b \\<le> b'; 0 \\<le> a; 0 < c \\<rbrakk> \\<Longrightarrow>\n  \\<bar>a * b div c + a\\<bar> \\<le> \\<bar>a * b' div c + a\\<bar>\"\napply (insert zmult_div_plus_ge_0[of b a a c] zmult_div_plus_ge_0[of \"b'\" a a c], simp)\nby (metis zmult_div_leq_mono)\n\nsubsection {* Some further (in-)equality results for @{text div} and @{text mod} *}\n\nlemma less_mod_eq_imp_add_divisor_le: \"\n  \\<lbrakk> (x::nat) < y; x mod m = y mod m \\<rbrakk> \\<Longrightarrow> x + m \\<le> y\"\napply (case_tac \"m = 0\")\n apply simp\napply (rule contrapos_pp[of \"x mod m = y mod m\"])\n apply blast\napply (rule ccontr, simp only: not_not, clarify)\nproof -\n  assume m_greater_0: \"0 < m\"\n  assume x_less_y:\"x < y\"\n  hence y_x_greater_0:\"0 < y - x\"\n    by simp\n  assume \"x mod m = y mod m\"\n  hence y_x_mod_m: \"(y - x) mod m = 0\"\n    by (simp only: mod_eq_imp_diff_mod_0)\n  assume \"\\<not> x + m \\<le> y\"\n  hence \"y < x + m\" by simp\n  hence \"y - x < x + m - x\"\n    by (simp add: diff_add_inverse diff_less_conv m_greater_0)\n  hence y_x_less_m: \"y - x < m\"\n    by simp\n  have \"(y - x) mod m = y - x\" \n    using y_x_less_m by simp\n  hence \"y - x = 0\"\n    using y_x_mod_m by simp\n  thus False\n    using y_x_greater_0 by simp\nqed\n\n\nlemma less_div_imp_mult_add_divisor_le: \"\n  (x::nat) < n div m \\<Longrightarrow> x * m + m \\<le> n\"\napply (case_tac \"m = 0\", simp)\napply (case_tac \"n < m\", simp)\napply (simp add: linorder_not_less)\napply (subgoal_tac \"m \\<le> n - n mod m\")\n prefer 2\n apply (drule div_le_mono[of m _ m])\n apply (simp only: div_self)\n apply (drule mult_le_mono2[of 1 _ m])\n apply (simp only: mult_1_right mult_div_cancel)\napply (drule less_imp_le_pred[of x])\napply (drule mult_le_mono2[of x _ m])\napply (simp add: diff_mult_distrib2 mult_div_cancel del: diff_diff_left)\napply (simp only: le_diff_conv2[of m])\napply (drule le_diff_imp_le[of \"m * x + m\"])\napply (simp only: mult.commute[of _ m])\ndone\n\nlemma mod_add_eq_imp_mod_0: \"\n  ((n + k) mod (m::nat) = n mod m) = (k mod m = 0)\"\nby (metis add_eq_if mod_add mod_add_self1 mod_self add.commute)\n\nlemma between_imp_mod_between: \"\n  \\<lbrakk> b < (m::nat); m * k + a \\<le> n; n \\<le> m * k + b \\<rbrakk> \\<Longrightarrow>\n  a \\<le> n mod m \\<and> n mod m \\<le> b\"\napply (case_tac \"m = 0\", simp_all)\napply (frule gr_implies_gr0)\napply (subgoal_tac \"k = n div m\")\n prefer 2\n apply (rule split_div_lemma[THEN iffD1], assumption)\n apply simp\napply clarify\napply (rule conjI)\napply (rule add_le_imp_le_left[where c=\"m * (n div m)\"], simp)+\ndone\n\ncorollary between_imp_mod_le: \"\n  \\<lbrakk> b < (m::nat); m * k \\<le> n; n \\<le> m * k + b \\<rbrakk> \\<Longrightarrow> n mod m \\<le> b\"\nby (insert between_imp_mod_between[of b m k 0 n], simp)\ncorollary between_imp_mod_gr0: \"\n  \\<lbrakk> (m::nat) * k < n; n < m * k + m \\<rbrakk> \\<Longrightarrow> 0 < n mod m\"\napply (case_tac \"m = 0\", simp_all)\napply (rule Suc_le_lessD)\napply (rule between_imp_mod_between[THEN conjunct1, of \"m - Suc 0\" m k \"Suc 0\" n])\napply simp_all\ndone\n\ntext {* Some variations of @{term split_div_lemma} *}\ncorollary le_less_div_conv: \"\n  0 < m \\<Longrightarrow> (k * m \\<le> n \\<and> n < Suc k * m) = (n div m = k)\"\nby (metis div_mult_le mult.commute split_div_lemma)\nlemma le_less_imp_div: \"\n  \\<lbrakk> k * m \\<le> n; n < Suc k * m \\<rbrakk> \\<Longrightarrow> n div m = k\"\nby (metis gr_implies_not0 mult_eq_if mult.commute neq0_conv split_div_lemma)\nlemma div_imp_le_less: \"\n  \\<lbrakk> n div m = k; 0 < m \\<rbrakk> \\<Longrightarrow> k * m \\<le> n \\<and> n < Suc k * m\"\nby (rule le_less_div_conv[THEN iffD2])\n\n\n\n\nlemma div_le_mod_le_imp_le: \"\n  \\<lbrakk> (a::nat) div m \\<le> b div m; a mod m \\<le> b mod m \\<rbrakk> \\<Longrightarrow> a \\<le> b\"\napply (rule subst[OF mod_div_equality2[of m a]])\napply (rule subst[OF mod_div_equality2[of m b]])\napply (rule add_le_mono)\napply (rule mult_le_mono2)\napply assumption+\ndone\n\nlemma le_mod_add_eq_imp_add_mod_le: \"\n  \\<lbrakk> a \\<le> b; (a + k) mod m = (b::nat) mod m \\<rbrakk> \\<Longrightarrow> a + k mod m \\<le> b\"\nby (metis add_le_mono2 diff_add_inverse le_add1 le_add_diff_inverse mod_diff1_eq mod_less_eq_dividend)\n\ncorollary mult_divisor_le_mod_ge_imp_ge: \"\n  \\<lbrakk> (m::nat) * k \\<le> n; r \\<le> n mod m \\<rbrakk> \\<Longrightarrow> m * k + r \\<le> n\"\napply (insert le_mod_add_eq_imp_add_mod_le[of \"m * k\" n \"n mod m\" m])\napply (simp add: add.commute[of \"m * k\"])\ndone\n\n\n\n\nsubsection {* Additional multiplication results for @{text mod} and @{text div} *}\n\nlemma mod_0_imp_mod_mult_right_0: \"\n  n mod m = (0::nat) \\<Longrightarrow> n * k mod m = 0\"\nby fastforce\nlemma mod_0_imp_mod_mult_left_0: \"\n  n mod m = (0::nat) \\<Longrightarrow> k * n mod m = 0\"\nby fastforce\n\nlemma mod_0_imp_div_mult_left_eq: \"\n  n mod m = (0::nat) \\<Longrightarrow> k * n div m = k * (n div m)\"\nby fastforce\nlemma mod_0_imp_div_mult_right_eq: \"\n  n mod m = (0::nat) \\<Longrightarrow> n * k div m = k * (n div m)\"\nby fastforce\n\n\nlemma mod_0_imp_mod_factor_0_left: \"\n  n mod (m * m') = (0::nat) \\<Longrightarrow> n mod m = 0\"\nby fastforce\nlemma mod_0_imp_mod_factor_0_right: \"\n  n mod (m * m') = (0::nat) \\<Longrightarrow> n mod m' = 0\"\nby fastforce\n\n\n\n\nsubsection {* Some factor distribution facts for @{text mod}*}\n\nlemma mod_eq_mult_distrib: \"\n  (a::nat) mod m = b mod m \\<Longrightarrow> \n  a * k mod (m * k) = b * k mod (m * k)\"\nby simp\n\nlemma mod_mult_eq_imp_mod_eq: \"\n  (a::nat) mod (m * k) = b mod (m * k) \\<Longrightarrow> a mod m = b mod m\"\napply (simp only: mod_mult2_eq)\napply (drule_tac arg_cong[where f=\"\\<lambda>x. x mod m\"])\napply (simp add: add.commute)\ndone\ncorollary mod_eq_mod_0_imp_mod_eq: \"\n  \\<lbrakk> (a::nat) mod m' = b mod m'; m' mod m = 0 \\<rbrakk> \n  \\<Longrightarrow> a mod m = b mod m\"\nby (clarify, drule mod_mult_eq_imp_mod_eq)\n\nlemma mod_factor_imp_mod_0: \"\n  \\<lbrakk>(x::nat) mod (m * k) = y * k mod (m * k)\\<rbrakk> \\<Longrightarrow> x mod k = 0\"\n  (is \"\\<lbrakk> ?P1 \\<rbrakk> \\<Longrightarrow> ?Q\")\nproof -\n  assume as1: ?P1\n  have \"y * k mod (m * k) = y mod m * k\"\n    by simp\n  hence \"x mod (m * k) = y mod m * k\"\n    using as1 by simp\n  hence \"y mod m * k = k * (x div k mod m) + x mod k\" (is \"?l1 = ?r1\")\n    by (simp only: ac_simps mod_mult2_eq)\n  hence \"(y mod m * k) mod k = ?r1 mod k\"\n    by simp\n  hence \"0 = ?r1 mod k\"\n    by simp\n  thus \"x mod k = 0\"\n    by (simp add: mod_add_eq)\nqed\ncorollary mod_factor_div: \"\n  \\<lbrakk>(x::nat) mod (m * k) = y * k mod (m * k)\\<rbrakk> \\<Longrightarrow> x div k * k = x\"\nby (blast intro: mod_factor_imp_mod_0[THEN mod_0_div_mult_cancel[THEN iffD1]])\n\nlemma mod_factor_div_mod:\"\n  \\<lbrakk> (x::nat) mod (m * k) = y * k mod (m * k); 0 < k \\<rbrakk>\n  \\<Longrightarrow> x div k mod m = y mod m\"\n  (is \"\\<lbrakk> ?P1; ?P2 \\<rbrakk> \\<Longrightarrow> ?L = ?R\")\nproof -\n  assume as1: ?P1\n  assume as2: ?P2\n  have x_mod_k_0: \"x mod k = 0\"\n    using as1 by (blast intro: mod_factor_imp_mod_0)\n  have \"?L * k + x mod k = x mod (k * m)\"\n    by (simp only: mod_mult2_eq mult.commute[of _ k])\n  hence \"?L * k = x mod (k * m)\"\n    using x_mod_k_0 by simp\n  hence \"?L * k = y * k mod (m * k)\"\n    using as1 by (simp only: ac_simps)\n  hence \"?L * k = y mod m * k\"\n    by (simp only: mult_mod_left)\n  thus ?thesis\n    using as2 by simp\nqed\n\n\nsubsection {* More results about quotient @{text div} with addition and subtraction *}\n\nlemma div_add1_eq_if: \"0 < m \\<Longrightarrow> \n  (a + b) div (m::nat) = a div m + b div m + (\n    if a mod m + b mod m < m then 0 else Suc 0)\"\napply (simp only: div_add1_eq[of a b])\napply (rule arg_cong[of \"(a mod m + b mod m) div m\"])\napply (clarsimp simp: linorder_not_less)\napply (rule le_less_imp_div[of \"Suc 0\" m \"a mod m + b mod m\"], simp)\napply simp\napply (simp only: add_less_mono[OF mod_less_divisor mod_less_divisor]) \ndone\ncorollary div_add1_eq1: \"\n  a mod m + b mod m < (m::nat) \\<Longrightarrow>\n  (a + b) div (m::nat) = a div m + b div m\"\napply (case_tac \"m = 0\", simp)\napply (simp add: div_add1_eq_if)\ndone\ncorollary div_add1_eq1_mod_0_left: \"\n  a mod m = 0 \\<Longrightarrow> (a + b) div (m::nat) = a div m + b div m\"\napply (case_tac \"m = 0\", simp)\napply (simp add: div_add1_eq1)\ndone\ncorollary div_add1_eq1_mod_0_right: \"\n  b mod m = 0 \\<Longrightarrow> (a + b) div (m::nat) = a div m + b div m\"\nby (fastforce simp: div_add1_eq1_mod_0_left)\ncorollary div_add1_eq2: \"\n  \\<lbrakk> 0 < m; (m::nat) \\<le> a mod m + b mod m \\<rbrakk> \\<Longrightarrow>\n  (a + b) div (m::nat) = Suc (a div m + b div m)\"\nby (simp add: div_add1_eq_if)\n\nlemma div_Suc: \"\n  0 < n \\<Longrightarrow> Suc m div n = (if Suc (m mod n) = n then Suc (m div n) else m div n)\"\napply (drule Suc_leI, drule le_imp_less_or_eq)\napply (case_tac \"n = Suc 0\", simp)\napply (split split_if, intro conjI impI)\n apply (rule_tac t=\"Suc m\" and s=\"m + 1\" in subst, simp)\n apply (subst div_add1_eq2, simp+)\napply (insert le_neq_trans[OF mod_less_divisor[THEN Suc_leI, of n m]], simp)\napply (rule_tac t=\"Suc m\" and s=\"m + 1\" in subst, simp)\napply (subst div_add1_eq1, simp+)\ndone\nlemma div_Suc': \"\n  0 < n \\<Longrightarrow> Suc m div n = (if m mod n < n - Suc 0 then m div n else Suc (m div n))\"\napply (simp add: div_Suc)\napply (intro conjI impI)\n apply simp\napply (insert le_neq_trans[OF mod_less_divisor[THEN Suc_leI, of n m]], simp)\ndone\n\nlemma div_diff1_eq_if: \"\n  (b - a) div (m::nat) = \n  b div m - a div m - (if a mod m \\<le> b mod m then 0 else Suc 0)\"\napply (case_tac \"m = 0\", simp)\napply (case_tac \"b < a\")\n apply (frule less_imp_le[of b])\n apply (frule div_le_mono[of _ _ m])\n apply simp\napply (simp only: linorder_not_less neq0_conv) \nproof -\n  assume le_as: \"a \\<le> b\"\n    and m_as: \"0 < m\"\n  have div_le:\"a div m \\<le> b div m\"\n    using le_as by (simp only: div_le_mono)\n  have \"b - a = b div m * m + b mod m - (a div m * m + a mod m)\"\n    by simp\n  also have \"\\<dots> = b div m * m + b mod m - a div m * m - a mod m\"\n    by simp\n  also have \"\\<dots> = b div m * m - a div m * m + b mod m - a mod m\"\n    by (simp only: diff_add_assoc2[OF mult_le_mono1[OF div_le]])\n  finally have b_a_s1: \"b - a = (b div m - a div m) * m + b mod m - a mod m\"\n    (is \"?b_a = ?b_a1\")\n    by (simp only: diff_mult_distrib)\n  hence b_a_div_s: \"(b - a) div m = \n    ((b div m - a div m) * m + b mod m - a mod m) div m\"\n    by (rule arg_cong)\n  \n  show ?thesis\n  proof (cases \"a mod m \\<le> b mod m\")\n    case True\n    hence as': \"a mod m \\<le> b mod m\" .\n    \n    have \"(b - a) div m = ?b_a1 div m\" \n      using b_a_div_s .\n    also have \"\\<dots> = ((b div m - a div m) * m + (b mod m - a mod m)) div m\"\n      using as' by simp\n    also have \"\\<dots> = b div m - a div m + (b mod m - a mod m) div m\"\n      apply (simp only: add.commute)\n      by (simp only: div_mult_self1[OF less_imp_neq[OF m_as, THEN not_sym]])\n    finally have b_a_div_s': \"(b - a) div m = \\<dots>\" .\n    have \"(b mod m - a mod m) div m = 0\"\n      by (rule div_less, rule less_imp_diff_less, \n          rule mod_less_divisor, rule m_as)\n    thus ?thesis\n      using b_a_div_s' as'\n      by simp\n  next\n    case False\n    hence as1': \"\\<not> a mod m \\<le> b mod m\" .\n    hence as': \"b mod m < a mod m\" by simp\n\n    have a_div_less: \"a div m < b div m\"\n      using le_as as'\n      by (blast intro: le_mod_greater_imp_div_less)\n    \n    have \"b div m - a div m = b div m - a div m - (Suc 0 - Suc 0)\"\n      by simp\n    also have \"\\<dots> = b div m - a div m + Suc 0 - Suc 0\"\n      by simp\n    also have \"\\<dots> = b div m - a div m - Suc 0 + Suc 0\"\n      by (simp only: diff_add_assoc2\n        a_div_less[THEN zero_less_diff[THEN iffD2], THEN Suc_le_eq[THEN iffD2]])\n    finally have b_a_div_s': \"b div m - a div m = \\<dots>\" .\n    \n    have \"(b - a) div m = ?b_a1 div m\" \n      using b_a_div_s .\n    also have \"\\<dots> = ((b div m - a div m - Suc 0 + Suc 0) * m\n      + b mod m - a mod m ) div m\"\n      using b_a_div_s' by (rule arg_cong)\n    also have \"\\<dots> = ((b div m - a div m - Suc 0) * m\n      + Suc 0 * m + b mod m - a mod m ) div m\"\n      by (simp only: add_mult_distrib)\n    also have \"\\<dots> = ((b div m - a div m - Suc 0) * m\n      + m + b mod m - a mod m ) div m\"\n      by simp\n    also have \"\\<dots> = ((b div m - a div m - Suc 0) * m\n      + (m + b mod m - a mod m) ) div m\"\n      by (simp only: add.assoc m_as\n        diff_add_assoc[of \"a mod m\" \"m + b mod m\"]\n        trans_le_add1[of \"a mod m\" m, OF mod_le_divisor])\n    also have \"\\<dots> = b div m - a div m - Suc 0\n      + (m + b mod m - a mod m) div m\"\n      by (simp only: add.commute div_mult_self1[OF less_imp_neq[OF m_as, THEN not_sym]])\n    finally have b_a_div_s': \"(b - a) div m = \\<dots>\" .\n    \n    have div_0_s: \"(m + b mod m - a mod m) div m = 0\"\n      by (rule div_less, simp only: add_diff_less m_as as') \n    show ?thesis\n      by (simp add: as1' b_a_div_s' div_0_s)\n  qed\nqed\n\ncorollary div_diff1_eq: \"\n  (b - a) div (m::nat) = \n  b div m - a div m - (m + a mod m - Suc (b mod m)) div m\"\napply (case_tac \"m = 0\", simp)\napply (simp only: neq0_conv)\napply (rule subst[of \n  \"if a mod m \\<le> b mod m then 0 else Suc 0\"\n  \"(m + a mod m - Suc(b mod m)) div m\"])\n prefer 2 apply (rule div_diff1_eq_if)\napply (split split_if, rule conjI)\n apply simp\napply (clarsimp simp: linorder_not_le)\napply (rule sym)\napply (drule Suc_le_eq[of \"b mod m\", THEN iffD2])\napply (simp only: diff_add_assoc)\napply (simp only: div_add_self1)\napply (simp add: less_imp_diff_less)\ndone\n\ncorollary div_diff1_eq1: \"\n  a mod m \\<le> b mod m \\<Longrightarrow> \n  (b - a) div (m::nat) = b div m - a div m\"\nby (simp add: div_diff1_eq_if)\ncorollary div_diff1_eq1_mod_0: \"\n  a mod m = 0 \\<Longrightarrow>\n  (b - a) div (m::nat) = b div m - a div m\"\nby (simp add: div_diff1_eq1)\ncorollary div_diff1_eq2: \"\n  b mod m < a mod m \\<Longrightarrow> \n  (b - a) div (m::nat) = b div m - Suc (a div m)\"\nby (simp add: div_diff1_eq_if)\n\n\n\nsubsection {* Further results about @{text div} and @{text mod}*}\n\nsubsubsection {* Some auxiliary facts about @{text mod} *}\n\n\n\nlemma diff_less_divisor_imp_sub_mod_eq: \"\n  \\<lbrakk> (x::nat) \\<le> y; y - x < m \\<rbrakk> \\<Longrightarrow> x = y - (y - x) mod m\"\nby simp\nlemma diff_ge_divisor_imp_sub_mod_less: \"\n  \\<lbrakk> (x::nat) \\<le> y; m \\<le> y - x; 0 < m \\<rbrakk> \\<Longrightarrow> x < y - (y - x) mod m\"\napply (simp only: less_diff_conv)\napply (simp only: le_diff_conv2 add.commute[of m])\napply (rule less_le_trans[of _ \"x + m\"])\napply simp_all\ndone\n\nlemma le_imp_sub_mod_le: \"\n  (x::nat) \\<le> y \\<Longrightarrow> x \\<le> y - (y - x) mod m\"\napply (case_tac \"m = 0\", simp_all)\napply (case_tac \"m \\<le> y - x\")\napply (drule diff_ge_divisor_imp_sub_mod_less[of x y m])\napply simp_all\ndone\n\nlemma mod_less_diff_mod: \"\n  \\<lbrakk> n mod m < r; r \\<le> m; r \\<le> (n::nat) \\<rbrakk> \\<Longrightarrow> \n  (n - r) mod m = m + n mod m - r\"\napply (case_tac \"r = m\")\n apply (simp add: mod_diff_self2)\napply (simp add: mod_diff1_eq[of r n m])\ndone\n\nlemma mod_0_imp_mod_pred: \"\n  \\<lbrakk> 0 < (n::nat); n mod m = 0 \\<rbrakk> \\<Longrightarrow> \n  (n - Suc 0) mod m = m - Suc 0\"\napply (case_tac \"m = 0\", simp_all)\napply (simp only: Suc_le_eq[symmetric])\napply (simp only: mod_diff1_eq)\napply (case_tac \"m = Suc 0\")\napply simp_all\ndone\n\nlemma mod_pred: \"\n  0 < n \\<Longrightarrow>\n  (n - Suc 0) mod m = (\n    if n mod m = 0 then m - Suc 0 else n mod m - Suc 0)\"\napply (split split_if, rule conjI)\n apply (simp add: mod_0_imp_mod_pred)\napply clarsimp\napply (case_tac \"m = Suc 0\", simp)\napply (frule subst[OF Suc0_mod[symmetric], where P=\"\\<lambda>x. x \\<le> n mod m\"], simp)\napply (simp only: mod_diff1_eq1)\napply (simp add: Suc0_mod)\ndone\ncorollary mod_pred_Suc_mod: \"\n  0 < n \\<Longrightarrow> Suc ((n - Suc 0) mod m) mod m = n mod m\"\napply (case_tac \"m = 0\", simp)\napply (simp add: mod_pred)\ndone\ncorollary diff_mod_pred: \"\n  a < b \\<Longrightarrow>\n  (b - Suc a) mod m = (\n    if a mod m = b mod m then m - Suc 0 else (b - a) mod m - Suc 0)\"\napply (rule_tac t=\"b - Suc a\" and s=\"b - a - Suc 0\" in subst, simp)\napply (subst mod_pred, simp)\napply (simp add: mod_eq_diff_mod_0_conv)\ndone\ncorollary diff_mod_pred_Suc_mod: \"\n  a < b \\<Longrightarrow> Suc ((b - Suc a) mod m) mod m = (b - a) mod m\"\napply (case_tac \"m = 0\", simp)\napply (simp add: diff_mod_pred mod_eq_diff_mod_0_conv)\ndone\n\nlemma mod_eq_imp_diff_mod_eq_divisor: \"\n  \\<lbrakk> a < b; 0 < m; a mod m = b mod m \\<rbrakk> \\<Longrightarrow> \n  Suc ((b - Suc a) mod m) = m\"\napply (drule mod_eq_imp_diff_mod_0[of a])\napply (frule iffD2[OF zero_less_diff])\napply (drule mod_0_imp_mod_pred[of \"b-a\" m], assumption)\napply simp\ndone\n\n\nlemma sub_diff_mod_eq: \"\n  r \\<le> t \\<Longrightarrow> (t - (t - r) mod m) mod (m::nat) = r mod m\"\nby (metis mod_diff_right_eq diff_diff_cancel diff_le_self)\n\nlemma sub_diff_mod_eq': \"\n  r \\<le> t \\<Longrightarrow> (k * m + t - (t - r) mod m) mod (m::nat) = r mod m\"\napply (simp only: diff_mod_le[of t r m, THEN add_diff_assoc, symmetric])\napply (simp add: sub_diff_mod_eq)\ndone\n\nlemma mod_eq_Suc_0_conv: \"Suc 0 < k \\<Longrightarrow> ((x + k - Suc 0) mod k = 0) = (x mod k = Suc 0)\"\napply (simp only: mod_pred)\napply (case_tac \"x mod k = Suc 0\")\napply simp_all\ndone\n\nlemma mod_eq_divisor_minus_Suc_0_conv: \"Suc 0 < k \\<Longrightarrow> (x mod k = k - Suc 0) = (Suc x mod k = 0)\"\nby (simp only: mod_Suc, split split_if, fastforce)\n\n\n\nsubsubsection {* Some auxiliary facts about @{text div} *}\n\nlemma sub_mod_div_eq_div: \"((n::nat) - n mod m) div m = n div m\"\napply (case_tac \"m = 0\", simp)\napply (simp add: mult_div_cancel[symmetric])\ndone\n\nlemma mod_less_imp_diff_div_conv: \"\n  \\<lbrakk> n mod m < r; r \\<le> m + n mod m\\<rbrakk> \\<Longrightarrow> (n - r) div m = n div m - Suc 0\"\napply (case_tac \"m = 0\", simp)\napply (simp only: neq0_conv)\napply (case_tac \"n < m\", simp)\napply (simp only: linorder_not_less)\napply (rule iffD1[OF split_div_lemma, symmetric], assumption)\napply (rule conjI)\napply (simp_all add: diff_mult_distrib2 mult_div_cancel)\ndone\n\ncorollary mod_0_le_imp_diff_div_conv: \"\n  \\<lbrakk> n mod m = 0; 0 < r; r \\<le> m \\<rbrakk> \\<Longrightarrow> (n - r) div m = n div m - Suc 0\"\nby (simp add: mod_less_imp_diff_div_conv)\ncorollary mod_0_less_imp_diff_Suc_div_conv: \"\n  \\<lbrakk> n mod m = 0; r < m \\<rbrakk> \\<Longrightarrow> (n - Suc r) div m = n div m - Suc 0\"\nby (drule mod_0_le_imp_diff_div_conv[where r=\"Suc r\"], simp_all)\ncorollary mod_0_imp_diff_Suc_div_conv: \"\n  (n - r) mod m = 0 \\<Longrightarrow> (n - Suc r) div m = (n - r) div m - Suc 0\"\napply (case_tac \"m = 0\", simp)\napply (rule_tac t=\"n - Suc r\" and s=\"n - r - Suc 0\" in subst, simp)\napply (rule mod_0_le_imp_diff_div_conv, simp+)\ndone\ncorollary mod_0_imp_sub_1_div_conv: \"\n  n mod m = 0 \\<Longrightarrow> (n - Suc 0) div m = n div m - Suc 0\"\napply (case_tac \"m = 0\", simp)\napply (simp add: mod_0_less_imp_diff_Suc_div_conv)\ndone\ncorollary sub_Suc_mod_div_conv: \"\n  (n - Suc (n mod m)) div m = n div m - Suc 0\"\napply (case_tac \"m = 0\", simp)\napply (simp add: mod_less_imp_diff_div_conv)\ndone\n\n\nlemma div_le_conv: \"0 < m \\<Longrightarrow> n div m \\<le> k = (n \\<le> Suc k * m - Suc 0)\"\napply (rule iffI)\n apply (drule mult_le_mono1[of _ _ m])\n apply (simp only: mult.commute[of _ m] mult_div_cancel)\n apply (drule le_diff_conv[THEN iffD1])\n apply (rule le_trans[of _ \"m * k + n mod m\"], assumption)\n apply (simp add: add.commute[of m])\n apply (simp only: diff_add_assoc[OF Suc_leI])\n apply (rule add_le_mono[OF le_refl])\n apply (rule less_imp_le_pred)\n apply (rule mod_less_divisor, assumption)\napply (drule div_le_mono[of _ _ m])\napply (simp add: mod_0_imp_sub_1_div_conv)\ndone\n\nlemma le_div_conv: \"0 < (m::nat) \\<Longrightarrow> (n \\<le> k div m) = (n * m \\<le> k)\"\napply (rule iffI)\n apply (drule mult_le_mono1[of _ _ m])\n apply (simp add: div_mult_cancel)\napply (drule div_le_mono[of _ _ m])\napply simp\ndone\n\nlemma less_mult_imp_div_less: \"n < k * m \\<Longrightarrow> n div m < (k::nat)\"\napply (case_tac \"k = 0\", simp)\napply (case_tac \"m = 0\", simp)\napply simp\napply (drule less_imp_le_pred[of n])\napply (drule div_le_mono[of _ _ m])\napply (simp add: mod_0_imp_sub_1_div_conv)\ndone\n\nlemma div_less_imp_less_mult: \"\\<lbrakk> 0 < (m::nat); n div m < k \\<rbrakk> \\<Longrightarrow> n < k * m\"\napply (rule ccontr, simp only: linorder_not_less)\napply (drule div_le_mono[of _ _ m])\napply simp\ndone\n\nlemma div_less_conv: \"0 < (m::nat) \\<Longrightarrow> (n div m < k) = (n < k * m)\"\napply (rule iffI)\napply (rule div_less_imp_less_mult, assumption+)\napply (rule less_mult_imp_div_less, assumption)\ndone\n\nlemma div_eq_0_conv: \"(n div (m::nat) = 0) = (m = 0 \\<or> n < m)\"\napply (rule iffI)\n apply (case_tac \"m = 0\", simp)\n apply (rule ccontr)\n apply (simp add: linorder_not_less)\n apply (drule div_le_mono[of _ _ m])\n apply simp\napply fastforce\ndone\nlemma div_eq_0_conv': \"0 < m \\<Longrightarrow> (n div (m::nat) = 0) = (n < m)\"\nby (simp add: div_eq_0_conv)\ncorollary div_gr_imp_gr_divisor: \"x < n div (m::nat) \\<Longrightarrow> m \\<le> n\"\napply (drule gr_implies_gr0, drule neq0_conv[THEN iffD2])\napply (simp add: div_eq_0_conv)\ndone\n\nlemma mod_0_less_div_conv: \"\n  n mod (m::nat) = 0 \\<Longrightarrow> (k * m < n) = (k < n div m)\"\napply (case_tac \"m = 0\", simp)\napply fastforce\ndone\n\nlemma add_le_divisor_imp_le_Suc_div: \"\n  \\<lbrakk> x div m \\<le> n; y \\<le> m \\<rbrakk> \\<Longrightarrow> (x + y) div m \\<le> Suc n\"\napply (case_tac \"m = 0\", simp)\napply (simp only: div_add1_eq_if[of _ x])\napply (drule order_le_less[of y, THEN iffD1], fastforce)\ndone\n\n\ntext {* List of definitions and lemmas *}\n\nthm\n  Divides.mod_less\n  Divides.mod_less_divisor\n  Divides.mod_le_divisor\n  mod_less_dividend\n  mod_le_dividend\n\nthm \n  Divides.mult_div_cancel\n  mod_0_div_mult_cancel\n  div_mult_le\n  less_div_Suc_mult\nthm\n  Suc0_mod\n  Suc0_mod_subst\n  Suc0_mod_cong\n  \nthm\n  Divides.mod_Suc\nthm\n  mod_Suc_conv\n  \nthm\n  mod_add\n  mod_sub_add\n  \nthm\n  mod_sub_eq_mod_0_conv\n  mod_sub_eq_mod_swap\n     \nthm\n  le_mod_greater_imp_div_less  \nthm\n  mod_diff_right_eq\n  mod_eq_imp_diff_mod_eq\n\nthm \n  divisor_add_diff_mod_if\n  divisor_add_diff_mod_eq1\n  divisor_add_diff_mod_eq2\n\nthm\n  mod_add_eq\n  mod_add1_eq_if\nthm\n  mod_diff1_eq_if\n  mod_diff1_eq\n  mod_diff1_eq1\n  mod_diff1_eq2\n\nthm\n  Divides.nat_mod_distrib\n  int_mod_distrib\n\nthm\n  zmod_zminus_eq_conv\n\nthm\n  mod_eq_imp_diff_mod_0\n  zmod_eq_imp_diff_mod_0\n\nthm\n  mod_neq_imp_diff_mod_neq0\n  diff_mod_0_imp_mod_eq\n  zdiff_mod_0_imp_mod_eq\n\nthm \n  zmod_eq_diff_mod_0_conv\n  mod_eq_diff_mod_0_conv\n  \nthm\n  less_mod_eq_imp_add_divisor_le\nthm\n  mod_add_eq_imp_mod_0\nthm \n  mod_eq_mult_distrib\n  mod_factor_imp_mod_0\n  mod_factor_div\n  mod_factor_div_mod\n  \n  \nthm\n  Divides.mod_add_self1\n  Divides.mod_add_self2\n  Divides.mod_mult_self1\n  Divides.mod_mult_self2\n  \n  mod_diff_self1\n  mod_diff_self2\n  mod_diff_mult_self1\n  mod_diff_mult_self2\n  \nthm\n  Divides.div_add_self1\n  Divides.div_add_self2\n  Divides.div_mult_self1\n  Divides.div_mult_self2\n  \n  div_diff_self1\n  div_diff_self2\n  div_diff_mult_self1\n  div_diff_mult_self2\n  \nthm\n  le_less_imp_div\n  div_imp_le_less\nthm\n  le_less_div_conv\n  \nthm\n  diff_less_divisor_imp_sub_mod_eq\n  diff_ge_divisor_imp_sub_mod_less\n  le_imp_sub_mod_le\n\nthm\n  sub_mod_div_eq_div\n  \nthm\n  mod_less_imp_diff_div_conv\n  mod_0_le_imp_diff_div_conv\n  mod_0_less_imp_diff_Suc_div_conv\n  mod_0_imp_sub_1_div_conv\n  \n  \nthm\n  sub_Suc_mod_div_conv\n  \nthm\n  mod_less_diff_mod\n  mod_0_imp_mod_pred\n\nthm\n  mod_pred\n  mod_pred_Suc_mod\n  \nthm\n  mod_eq_imp_diff_mod_eq_divisor\n  \nthm\n  diff_mod_le\n  sub_diff_mod_eq\n  sub_diff_mod_eq'\n  \nthm\n  Divides.div_add1_eq\n  div_add1_eq_if\n  div_add1_eq1\n  div_add1_eq2\nthm  \n  div_diff1_eq_if\n  div_diff1_eq\n  div_diff1_eq1\n  div_diff1_eq2\n  \n\nthm \n  div_le_conv\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/CommonArith/Util_Div.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382165412808, "lm_q2_score": 0.8244619350028204, "lm_q1q2_score": 0.7103054650885032}}
{"text": "(*\n  Author: Jose Divas\u00f3n\n  Email:  jose.divason@unirioja.es\n*)\n\nsection \\<open>Definition of Smith normal form in JNF\\<close>\n\ntheory Smith_Normal_Form_JNF\n  imports\n    SNF_Missing_Lemmas\nbegin\n\ntext \\<open>Now, we define diagonal matrices and Smith normal form in JNF\\<close>\n\ndefinition \"isDiagonal_mat A = (\\<forall>i j. i \\<noteq> j \\<and> i < dim_row A \\<and> j < dim_col A \\<longrightarrow> A$$(i,j) = 0)\"\n\ndefinition \"Smith_normal_form_mat A = \n  (\n    (\\<forall>a. a + 1 < min (dim_row A) (dim_col A) \\<longrightarrow> A $$ (a,a) dvd A $$ (a+1,a+1))\n    \\<and> isDiagonal_mat A    \n  )\"\n\nlemma SNF_first_divides:\n  assumes SNF_A: \"Smith_normal_form_mat A\" and \"(A::('a::comm_ring_1) mat) \\<in> carrier_mat n m\"\n  and i: \"i < min (dim_row A) (dim_col A)\"\nshows \"A $$ (0,0) dvd A $$ (i,i)\"\n  using i\nproof (induct i)\n  case 0\n  then show ?case by auto\nnext\n  case (Suc i)\n  show ?case \n    by (metis (full_types) Smith_normal_form_mat_def Suc.hyps Suc.prems \n        Suc_eq_plus1 Suc_lessD SNF_A dvd_trans)\nqed\n\nlemma Smith_normal_form_mat_intro:\n  assumes \"(\\<forall>a. a + 1 < min (dim_row A) (dim_col A) \\<longrightarrow> A $$ (a,a) dvd A $$ (a+1,a+1))\"\n    and \"isDiagonal_mat A\" \n  shows \"Smith_normal_form_mat A\"\n  unfolding Smith_normal_form_mat_def using assms by auto\n\nlemma Smith_normal_form_mat_m0[simp]:\n  assumes A: \"A\\<in>carrier_mat m 0\"\n  shows \"Smith_normal_form_mat A\"\n  using A unfolding Smith_normal_form_mat_def isDiagonal_mat_def by auto\n\nlemma Smith_normal_form_mat_0m[simp]:\n  assumes A: \"A\\<in>carrier_mat 0 m\"\n  shows \"Smith_normal_form_mat A\"\n  using A unfolding Smith_normal_form_mat_def isDiagonal_mat_def by auto\n\nlemma S00_dvd_all_A:\n  assumes A: \"(A::'a::comm_ring_1 mat) \\<in> carrier_mat m n\"\n  and P: \"P \\<in> carrier_mat m m\"\n  and Q: \"Q \\<in> carrier_mat n n\"\n  and inv_P: \"invertible_mat P\"\n  and inv_Q: \"invertible_mat Q\"\n  and S_PAQ: \"S = P*A*Q\"\n  and SNF_S: \"Smith_normal_form_mat S\"\n  and i: \"i<m\" and j: \"j<n\"\nshows \"S$$(0,0) dvd A $$ (i,j)\"\nproof -\n  have S00: \"(\\<forall>i j. i<m \\<and> j<n \\<longrightarrow> S$$(0,0) dvd S$$(i,j))\"\n    using SNF_S unfolding Smith_normal_form_mat_def isDiagonal_mat_def\n    by (smt P Q SNF_first_divides A S_PAQ SNF_S carrier_matD \n        dvd_0_right min_less_iff_conj mult_carrier_mat)\n    obtain P' where PP': \"inverts_mat P P'\" and P'P: \"inverts_mat P' P\"\n      using inv_P unfolding invertible_mat_def by auto\n    obtain Q' where QQ': \"inverts_mat Q Q'\" and Q'Q: \"inverts_mat Q' Q\"\n      using inv_Q unfolding invertible_mat_def by auto\n    have A_P'SQ': \"P'*S*Q' = A\"\n    proof -\n      have \"P'*S*Q' = P'*(P*A*Q)*Q'\" unfolding S_PAQ by auto\n      also have \"... = (P'*P)*A*(Q*Q')\"\n        by (smt A PP' Q Q'Q P assoc_mult_mat carrier_mat_triv index_mult_mat(2) index_mult_mat(3) \n            index_one_mat(3) inverts_mat_def right_mult_one_mat)\n      also have \"... = A\"\n        by (metis A P'P QQ' A Q P carrier_matD(1) index_mult_mat(3) index_one_mat(3) inverts_mat_def\n            left_mult_one_mat right_mult_one_mat)\n      finally show ?thesis .\n    qed\n    have \"(\\<forall>i j. i<m \\<and> j<n \\<longrightarrow> S$$(0,0) dvd (P'*S*Q')$$(i,j))\"\n    proof (rule dvd_elements_mult_matrix_left_right[OF _ _ _ S00])\n      show \"S \\<in> carrier_mat m n\" using P A Q S_PAQ by auto\n      show \"P' \\<in> carrier_mat m m\"\n        by (metis (mono_tags, lifting) A_P'SQ' PP' P A carrier_matD carrier_matI index_mult_mat(2) \n            index_mult_mat(3) inverts_mat_def one_carrier_mat)\n      show \"Q' \\<in> carrier_mat n n\"\n        by (metis (mono_tags, lifting) A_P'SQ' Q'Q Q A carrier_matD(2) carrier_matI \n            index_mult_mat(3) inverts_mat_def one_carrier_mat)\n    qed\n    thus ?thesis using A_P'SQ' i j by auto\nqed\n\n\nlemma SNF_first_divides_all:\n  assumes SNF_A: \"Smith_normal_form_mat A\" and A: \"(A::('a::comm_ring_1) mat) \\<in> carrier_mat m n\"\n  and i: \"i < m\" and j: \"j<n\"\nshows \"A $$ (0,0) dvd A $$ (i,j)\"\nproof (cases \"i=j\")\n  case True\n  then show ?thesis using assms SNF_first_divides by (metis carrier_matD min_less_iff_conj)\nnext\n  case False\n  hence \"A$$(i,j) = 0\" using SNF_A i j A unfolding Smith_normal_form_mat_def isDiagonal_mat_def by auto\n  then show ?thesis by auto\nqed\n\n(*This can also be obtained from HOL Analysis via local type definitions*)\nlemma SNF_divides_diagonal:\n  fixes A::\"'a::comm_ring_1 mat\"\n  assumes A: \"A \\<in> carrier_mat n m\" \n    and SNF_A: \"Smith_normal_form_mat A\"\n    and j: \"j < min n m\"\n    and ij: \"i\\<le>j\"\n  shows \"A$$(i,i) dvd A$$(j,j)\" \n  using ij j\nproof (induct j)\n  case 0\n  then show ?case by auto\nnext\n  case (Suc j)\n  show ?case\n  proof (cases \"i\\<le>j\")\n    case True\n    have \"A $$ (i, i) dvd A $$ (j, j)\" using Suc.hyps Suc.prems True by simp\n    also have \"... dvd A $$ (Suc j, Suc j)\" \n      using SNF_A Suc.prems A \n      unfolding Smith_normal_form_mat_def by auto\n    finally show ?thesis by auto \n  next\n    case False\n    hence \"i=Suc j\" using Suc.prems by auto\n    then show ?thesis by auto\n  qed\nqed\n\nlemma Smith_zero_imp_zero:\n  fixes A::\"'a::comm_ring_1 mat\"\n  assumes  A: \"A \\<in> carrier_mat m n\"\n    and SNF: \"Smith_normal_form_mat A\"\n    and Aii: \"A$$(i,i) = 0\" \n    and j: \"j<min m n\" \n    and ij: \"i\\<le>j\"\n  shows \"A$$(j,j) = 0\"\nproof -\n  have \"A$$(i,i) dvd A$$(j,j)\" by (rule SNF_divides_diagonal[OF A SNF j ij])\n  thus ?thesis using Aii by auto\nqed\n\nlemma SNF_preserved_multiples_identity:\n  assumes S: \"S \\<in> carrier_mat m n\" and SNF: \"Smith_normal_form_mat (S::'a::comm_ring_1 mat)\"\n  shows \"Smith_normal_form_mat (S*(k \\<cdot>\\<^sub>m 1\\<^sub>m n))\"\nproof (rule Smith_normal_form_mat_intro)\n  have rw: \"S*(k \\<cdot>\\<^sub>m 1\\<^sub>m n) = Matrix.mat m n (\\<lambda>(i, j). S $$ (i, j) * k)\"\n    unfolding mat_diag_smult[symmetric] by (rule mat_diag_mult_right[OF S])\n  show \"isDiagonal_mat (S * (k \\<cdot>\\<^sub>m 1\\<^sub>m n))\" \n    using SNF S unfolding Smith_normal_form_mat_def isDiagonal_mat_def rw\n    by auto\n  show \"\\<forall>a. a + 1 < min (dim_row (S * (k \\<cdot>\\<^sub>m 1\\<^sub>m n))) (dim_col (S * (k \\<cdot>\\<^sub>m 1\\<^sub>m n))) \\<longrightarrow>\n        (S * (k \\<cdot>\\<^sub>m 1\\<^sub>m n)) $$ (a, a) dvd (S * (k \\<cdot>\\<^sub>m 1\\<^sub>m n)) $$ (a + 1, a + 1)\"\n    using SNF S unfolding Smith_normal_form_mat_def isDiagonal_mat_def rw\n    by (auto simp add: mult_dvd_mono)\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/Smith_Normal_Form/Smith_Normal_Form_JNF.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382058759128, "lm_q2_score": 0.8244619220634456, "lm_q1q2_score": 0.7103054451475476}}
{"text": "theory Exercise3p4\nimports Main\nbegin\n\n(* Exercise 3.4. \n\nTake a copy of theory AExp and modify it as follows. Extend type\naexp with a binary constructor Times that represents multiplication. Modify\nthe definition of the functions aval and asimp accordingly. You can remove\nasimp_const. Function asimp should eliminate 0 and 1 from multiplications as\nwell as evaluate constant subterms. Update all proofs concerned.\n\n*)\n  \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  \n\nvalue \"aval (Plus (N 3) (V ''x'')) (\\<lambda>x.0)\"\n \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 a1 a2 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 = 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 a1 a2 = Times a1 a2\"\n\nlemma aval_times: \"aval (times a1 a2) s = aval a1 s * aval a2 s\"\n  apply (induction a1 a2 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 a) s = aval a s\"\n  apply (induction a)\n    apply (auto simp: aval_plus aval_times)\n    done      \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/Exercise3p4.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199552262967, "lm_q2_score": 0.8479677564567912, "lm_q1q2_score": 0.7102747141966808}}
{"text": "(*\n * Copyright 2019, NTU\n *\n * This software may be distributed and modified according to the terms of\n * the BSD 2-Clause license. Note that NO WARRANTY is provided.\n * See \"LICENSE_BSD2.txt\" for details.\n *\n *  Author: Albert Rizaldi, NTU Singapore\n *)\n\ntheory Bits_Int_Aux\n  imports\n    Main \"HOL-Word.Word\" \"HOL.Archimedean_Field\"\nbegin\n\ntext \\<open>The function @{term \"bl_to_bin_aux\"} is the auxiliary function for converting a bit vector\n(list of booleans) into an integer with unsigned number interpretation. This semantics or conversion\nis taken from @{cite \"Bryant2010\"} (Chapter 2.2). Given a list x = [x_{n-1}, x_{n-2}, ... , x_0] of\nbooleans with conversion False \\<mapsto> 0 and True \\<mapsto> 1, the unsigned number it represents is\n\n    B2U (x) \\<equiv> \\<Sum>i=0..<n. x_i * 2 ^ i   .\n\nThe following lemma formalises this correctness.\\<close>\n\nlemma bl_to_bin_aux_correctness:\n  \" bl_to_bin_aux bs w =  w * 2 ^ length bs + (\\<Sum>i = 0..<length bs. (int \\<circ> of_bool) (rev bs ! i) * 2 ^ i)\"\nproof (induction bs arbitrary: w)\n  case Nil\n  then show ?case by auto\nnext\n  case (Cons a bs)\n    \\<comment> \\<open>from left hand side\\<close>\n  have \" bl_to_bin_aux (a # bs) w = bl_to_bin_aux bs (w BIT a)\"\n    by auto\n  also have \"... =  (w BIT a) * 2 ^ length bs + (\\<Sum>i = 0..<length bs. (int \\<circ> of_bool) (rev bs ! i) * 2 ^ i)\" (is \"_ = _ + ?rhs2\")\n    using Cons by auto\n  also have \"... = (2 * w + (int o of_bool) a) * 2 ^ length bs + ?rhs2\"\n    unfolding Bit_def by auto\n  also have \"... = w * 2 ^ (length (a # bs)) + (int o of_bool) a * 2 ^ length bs + ?rhs2\"\n    by (auto simp add: field_simps)\n  also have \"... = w * 2 ^ length (a # bs) + (\\<Sum>i = 0..<length (a # bs). (int \\<circ> of_bool) (rev (a # bs) ! i) * 2 ^ i)\"\n  proof -\n    have \"(\\<Sum>i = 0..<length (a # bs). (int \\<circ> of_bool) (rev (a # bs) ! i) * 2 ^ i) =\n          (\\<Sum>i = 0..<Suc (length bs). (int \\<circ> of_bool) (rev (a # bs) ! i) * 2 ^ i) \"\n      by auto\n    also have \"... = (\\<Sum>i = 0..<length bs. (int \\<circ> of_bool) (rev (a # bs) ! i) * 2 ^ i) + (int \\<circ> of_bool) a * 2 ^ length bs \"\n      using nth_rev_alt by fastforce\n    also have \"... = (\\<Sum>i= 0..< length bs. (int o of_bool) (rev bs ! i) * 2 ^ i) + (int o of_bool) a * 2 ^ length bs\"\n      unfolding cancel_semigroup_add_class.add_right_cancel\n    proof (intro sum.mono_neutral_cong)\n      fix x\n      assume \"x \\<in> {0..<length bs} \\<inter> {0..<length bs}\"\n      hence \"x \\<in> {0 ..< length bs}\"\n        by auto\n      thus \"(int \\<circ> of_bool) (rev (a # bs) ! x) * 2 ^ x = (int \\<circ> of_bool) (rev bs ! x) * 2 ^ x\"\n        by (smt atLeastLessThan_iff bin_nth_of_bl_aux bl_to_bin_aux.simps(2) length_Cons less_Suc_eq not_less)\n    qed (auto)\n    finally show ?thesis\n      by auto\n  qed\n  finally show ?case\n    by auto\nqed\n\nlemma bl_to_bin_correctness:\n  \"bl_to_bin bs = (\\<Sum>i = 0..<length bs. (int \\<circ> of_bool) (rev bs ! i) * 2 ^ i)\"\n  unfolding bl_to_bin_def using bl_to_bin_aux_correctness by auto\n\ntext \\<open> In case it is interpreted as a signed number, the equation is\n\n    B2S (x) \\<equiv> - x_{n-1} * 2 ^ {n - 1} + \\<Sum>i=0..<n-1. x_i * 2 ^ i .\n\nNote that the most significant bit has the value of (- 2 ^ {n - 1}) instead of (2 ^ {n - 1}).\nUnfortunately there is no such function in @{theory \"HOL-Word.Bits_Int\"}. Fortunately we can\neasily obtain such function with simple arithmetic as follows.\n\\<close>\n\nfun sbl_to_bin :: \"bool list \\<Rightarrow> int\" where\n  \"sbl_to_bin [] = 0\"\n| \"sbl_to_bin bs = bl_to_bin bs - (int o of_bool) (hd bs) * 2 ^ (length bs)\"\n\ntext \\<open>This is the correctness theorem according to the definition of B2S. \\<close>\n\nlemma sbl_to_bin_correctness:\n  \"sbl_to_bin (a # bs) = - (int o of_bool) a * 2 ^ (length bs) + (\\<Sum>i = 0 ..< length bs. ((int o of_bool) (rev bs ! i)) * 2 ^ i) \"\nproof -\n  have \"sbl_to_bin (a # bs) = bl_to_bin (a # bs) - (int o of_bool) a * 2 ^ (1 + length bs)\"\n    by auto\n  also have \"... = bl_to_bin (a # bs) - 2 * (int o of_bool) a * 2 ^ length bs\"\n    by auto\n  also have \"... = (\\<Sum>i = 0..< Suc (length bs). (int \\<circ> of_bool) (rev (a # bs) ! i) * 2 ^ i) - 2 * (int o of_bool) a * 2 ^ length bs\"\n    unfolding bl_to_bin_correctness by auto\n  also have \"... = (\\<Sum>i = 0..< length bs. (int \\<circ> of_bool) (rev (a # bs) ! i) * 2 ^ i) + (int o of_bool) a * 2 ^ length bs - 2 * (int o of_bool) a * 2 ^ length bs\"\n    using list.size(4) nth_rev_alt by fastforce\n  also have \"... = (\\<Sum>i = 0..< length bs. (int \\<circ> of_bool) (rev (a # bs) ! i) * 2 ^ i) - (int o of_bool) a * 2 ^ length bs\"\n    by auto\n  also have \"... = (\\<Sum>i = 0..< length bs. (int \\<circ> of_bool) (rev bs ! i) * 2 ^ i) - (int o of_bool) a * 2 ^ length bs\"\n  proof -\n    have \"(\\<Sum>i = 0..<length bs. (int \\<circ> of_bool) (rev (a # bs) ! i) * 2 ^ i) =\n          (\\<Sum>i = 0..<length bs. (int \\<circ> of_bool) (rev bs ! i) * 2 ^ i)\"\n      apply (intro sum.mono_neutral_cong[rotated 4])\n      by (smt One_nat_def add.commute atLeastLessThan_iff bin_nth_of_bl bin_nth_of_bl_aux\n      bl_to_bin_aux.Cons inf.idem less_Suc_eq list.size(4) not_less plus_1_eq_Suc) auto\n    thus ?thesis\n      by auto\n  qed\n  finally show ?thesis\n    by auto\nqed\n\nlemma sign_bit_is_0:\n  assumes \"0 \\<le> w\" and \"w < 2 ^ len\"\n  shows   \"hd (bin_to_bl (Suc len) w) = False\"\n  using assms sbintrunc_mod2p sign_Min_lt_0 unfolding bl_sbin_sign by auto\n\nlemma sign_bit_is_1:\n  assumes \"w < 0\" and \"- w < 2 ^ len\"\n  shows   \"hd (bin_to_bl (Suc len) w) = True\"\n  using assms bin_sign_def no_sbintr_alt2 unfolding bl_sbin_sign by auto\n\nlemma sbin_bl_bin:\n  assumes \"0 < n\" and \"\\<bar>w\\<bar> < 2 ^ (n - 1)\"\n  shows \"sbl_to_bin (bin_to_bl n w) = w\"\nproof -\n  obtain a bs where \"bin_to_bl n w = (a # bs)\"\n    using assms  size_bin_to_bl  by (metis list.size(3) not_less_zero sbl_to_bin.cases)\n  have \"sbl_to_bin (bin_to_bl n w) = sbl_to_bin (a # bs)\"\n    using \\<open>bin_to_bl n w = (a # bs)\\<close> by auto\n  also have \"... = - (int o of_bool) a * 2 ^ (length bs)\n                 + (\\<Sum>i = 0 ..< length bs. ((int o of_bool) (rev bs ! i)) * 2 ^ i)\"\n    unfolding sbl_to_bin_correctness by auto\n  finally have \"sbl_to_bin (bin_to_bl n w) = - (int o of_bool) a * 2 ^ (length bs)\n                                           + (\\<Sum>i = 0 ..< length bs. ((int o of_bool) (rev bs ! i)) * 2 ^ i)\"\n    by auto\n  have \"sbl_to_bin (bin_to_bl n w) = sbl_to_bin (a # bs)\"\n    using \\<open>bin_to_bl n w = a # bs\\<close> by auto\n  also have \"... = bl_to_bin (a # bs) - (int o of_bool) a * 2 ^ (1 + length bs)\"\n    by auto\n  also have \"... = bl_to_bin (bin_to_bl n w) - (int o of_bool) a * 2 ^ (1 + length bs)\"\n    using \\<open>bin_to_bl n w = a # bs\\<close> by auto\n  also have \"... = bintrunc n w - (int o of_bool) a * 2 ^ (1 + length bs)\"\n    unfolding bin_bl_bin by auto\n  also have \"... = w mod (2 ^ n) - (int o of_bool) a * 2 ^ (1 + length bs)\"\n    by (simp add: no_bintr_alt1)\n  also have \"... = w mod (2 ^ n) - (int o of_bool) a * 2 ^ n\"\n    by (metis \\<open>bin_to_bl n w = a # bs\\<close> length_Cons plus_1_eq_Suc size_bin_to_bl)\n  also have \"... = w\"\n  proof (cases \"0 \\<le> w\")\n    case True\n    hence \"a = False\"\n      using sign_bit_is_0\n      by (smt One_nat_def \\<open>bin_to_bl n w = a # bs\\<close> add.commute add_diff_cancel_left' assms(2)\n      length_Cons list.sel(1) list.size(4) size_bin_to_bl)\n    then show ?thesis\n      by (smt Bit_B1_2t One_nat_def True \\<open>bin_to_bl n w = a # bs\\<close> add.commute add_diff_cancel_left'\n      assms(2) comp_apply int_mod_eq' list.size(4) mult_eq_0_iff of_bool_eq(1) plus_1_eq_Suc\n      power_BIT semiring_1_class.of_nat_0 size_bin_to_bl)\n  next\n    case False\n    hence \"a = True\"\n      using sign_bit_is_1\n      by (smt One_nat_def \\<open>bin_to_bl n w = a # bs\\<close> add.commute add_diff_cancel_left' assms(2)\n      list.sel(1) list.size(4) plus_1_eq_Suc size_bin_to_bl)\n    obtain w' where \"w = -w'\"\n      using False  by (metis add.inverse_inverse)\n    hence *: \"- w' mod 2 ^ n = (if w' mod 2 ^ n = 0 then 0 else 2 ^ n - w' mod 2 ^ n)\"\n      unfolding zmod_zminus1_eq_if by auto\n    have \"w' < 2 ^ n\"\n      by (smt One_nat_def \\<open>bin_to_bl n w = a # bs\\<close> \\<open>w = - w'\\<close> add.commute add_diff_cancel_left'\n      assms(2) less_Suc_eq list.size(4) plus_1_eq_Suc power_strict_increasing_iff size_bin_to_bl)\n    hence \"w' mod 2 ^ n \\<noteq> 0\"\n      using False \\<open>w = - w'\\<close> by auto\n    hence \"- w' mod 2 ^ n = 2 ^ n - (w' mod 2 ^ n)\"\n      using * by auto\n    hence \"w mod 2 ^ n = 2 ^ n - (\\<bar>w\\<bar> mod 2 ^ n)\"\n      using False \\<open>w = - w'\\<close> by auto\n    hence \"w mod 2 ^ n - (int \\<circ> of_bool) a * 2 ^ n = 2 ^ n - (\\<bar>w\\<bar> mod 2 ^ n) - 2 ^ n\"\n      by (simp add: \\<open>a = True\\<close>)\n    also have \"... = - (\\<bar>w\\<bar> mod 2 ^ n)\"\n      by auto\n    also have \"... = w\"\n      using False \\<open>w = - w'\\<close> \\<open>w' < 2 ^ n\\<close> by auto\n    finally show ?thesis\n      by auto\n  qed\n  finally show ?thesis\n    by auto\nqed\n\nlemma sbin_bl_bin':\n  assumes \"0 < n\"\n  shows   \"sbl_to_bin (bin_to_bl n w) mod 2 ^ n = w mod 2 ^ n\"\nproof -\n  obtain a bs where \"bin_to_bl n w = (a # bs)\"\n    using assms  size_bin_to_bl  by (metis list.size(3) not_less_zero sbl_to_bin.cases)\n  have \"sbl_to_bin (bin_to_bl n w) = sbl_to_bin (a # bs)\"\n    using \\<open>bin_to_bl n w = (a # bs)\\<close> by auto\n  also have \"... = - (int o of_bool) a * 2 ^ (length bs)\n                 + (\\<Sum>i = 0 ..< length bs. ((int o of_bool) (rev bs ! i)) * 2 ^ i)\"\n    unfolding sbl_to_bin_correctness by auto\n  finally have \"sbl_to_bin (bin_to_bl n w) = - (int o of_bool) a * 2 ^ (length bs)\n                                           + (\\<Sum>i = 0 ..< length bs. ((int o of_bool) (rev bs ! i)) * 2 ^ i)\"\n    by auto\n  have \"sbl_to_bin (bin_to_bl n w) = sbl_to_bin (a # bs)\"\n    using \\<open>bin_to_bl n w = a # bs\\<close> by auto\n  also have \"... = bl_to_bin (a # bs) - (int o of_bool) a * 2 ^ (1 + length bs)\"\n    by auto\n  also have \"... = bl_to_bin (bin_to_bl n w) - (int o of_bool) a * 2 ^ (1 + length bs)\"\n    using \\<open>bin_to_bl n w = a # bs\\<close> by auto\n  also have \"... = bintrunc n w - (int o of_bool) a * 2 ^ (1 + length bs)\"\n    unfolding bin_bl_bin by auto\n  also have \"... = w mod (2 ^ n) - (int o of_bool) a * 2 ^ (1 + length bs)\"\n    by (simp add: no_bintr_alt1)\n  also have \"... = w mod (2 ^ n) - (int o of_bool) a * 2 ^ n\"\n    by (metis \\<open>bin_to_bl n w = a # bs\\<close> length_Cons plus_1_eq_Suc size_bin_to_bl)\n  finally have \"sbl_to_bin (bin_to_bl n w) = w mod (2 ^ n) - (int o of_bool) a * 2 ^ n\"\n    by auto\n  hence \"sbl_to_bin (bin_to_bl n w) mod 2 ^ n = (w mod 2 ^ n - (int o of_bool) a * 2 ^ n) mod 2 ^ n\"\n    by auto\n  also have \"... = (w - (int \\<circ> of_bool) a * 2 ^ n) mod 2 ^ n\"\n    using pull_mods(6)[where a=\"w\" and c=\"2 ^ n\" and b=\"(int o of_bool) a * 2 ^ n\"] by auto\n  also have \"... = w mod 2 ^ n\"\n    by simp\n  finally show ?thesis\n    by auto\nqed\n\nlemma butlast_pow_rest_bl2bin:\n  \"bl_to_bin ((butlast ^^ n) bl) = (bin_rest ^^ n) (bl_to_bin bl)\"\n  by (simp add: bin_rest_bl_to_bin fn_comm_power')\n\nlemma take_rest_bl2bin:\n  \"bl_to_bin (take (length bl - n) bl) = (bin_rest ^^ n) (bl_to_bin bl)\"\n  by (metis butlast_pow_rest_bl2bin butlast_power)\n\nlemma bin_rest_compow:\n  \"(bin_rest ^^ m) n = (n div 2 ^ m)\"\n  using bin_rest_shiftr shiftr_int_def by (induct m) auto\n\nlemma bin_rest_sbl_to_bin:\n  assumes \"1 < length bs\"\n  shows \"bin_rest (sbl_to_bin bs) = sbl_to_bin (butlast bs)\"\nproof -\n  have \"sbl_to_bin bs = bl_to_bin bs - (int o of_bool) (hd bs) * 2 ^ (length bs)\"\n    using assms  by (metis (full_types) list.size(3) not_less_zero sbl_to_bin.elims)\n  hence \"bin_rest (sbl_to_bin bs) = bin_rest (bl_to_bin bs + - (int o of_bool) (hd bs) * 2 ^ length bs)\"\n    by auto\n  also have \"... = bin_rest (bl_to_bin bs) - bin_rest ((int o of_bool) (hd bs) * 2 ^ length bs)\"\n  proof -\n    have \"2 dvd - (int \\<circ> of_bool) (hd bs) * 2 ^ length bs\"\n      using assms by auto\n    thus ?thesis\n      unfolding bin_rest_def  using div_plus_div_distrib_dvd_right\n      by (smt dvd_neg_div mult_minus_left)\n  qed\n  also have \"... = bl_to_bin (butlast bs) - (int o of_bool) (hd bs) * 2 ^ (length bs - 1)\"\n    unfolding bin_rest_bl_to_bin bin_rest_def\n    by (smt BIT_special_simps(3) assms bin_rest_BIT bin_rest_bl_to_bin bin_rest_def\n    mult_BIT_simps(1) mult_cancel_left2 mult_cancel_right2 not_less_zero o_apply of_bool_eq(1)\n    of_bool_eq(2) of_nat_1 power_eq_if semiring_1_class.of_nat_0)\n  also have \"... = bl_to_bin (butlast bs) - (int o of_bool) (hd (butlast bs)) * 2 ^ (length (butlast bs))\"\n    using assms hd_butlast by auto\n  also have \"... = sbl_to_bin (butlast bs)\"\n    by (metis assms length_butlast length_greater_0_conv sbl_to_bin.elims zero_less_diff)\n  finally show ?thesis\n    by auto\nqed\n\nlemma butlast_pow_rest_sbl2bin:\n  assumes \"n < length bl\"\n  shows   \"sbl_to_bin ((butlast ^^ n) bl) = (bin_rest ^^ n) (sbl_to_bin bl)\"\nproof -\n  let ?bs = \"(butlast ^^ n) bl\"\n  have \"(butlast ^^ n) bl \\<noteq> []\"\n    using assms unfolding butlast_power by auto\n  hence \"sbl_to_bin ?bs = bl_to_bin ?bs - (int o of_bool) (hd ?bs) * 2 ^ (length ?bs)\"\n    by (metis sbl_to_bin.elims)\n  moreover have \"hd ?bs = hd bl\"\n    unfolding butlast_power  by (simp add: assms)\n  moreover have \"length ?bs = length bl - n\"\n    unfolding butlast_power by simp\n  ultimately have \"sbl_to_bin ?bs = bl_to_bin ?bs - (int o of_bool) (hd bl) * 2 ^ (length bl - n)\"\n    by auto\n  also have \"... = (bin_rest ^^ n) (bl_to_bin bl) - (int o of_bool) (hd bl) * 2 ^ (length bl - n)\"\n    unfolding butlast_pow_rest_bl2bin by auto\n  also have \"... = (bin_rest ^^ n) (bl_to_bin bl) + (- (int o of_bool) (hd bl) * 2 ^ length bl) div 2 ^ n\"\n  proof -\n    have \"(2::int) ^ (length bl - n) = 2 ^ length bl div 2 ^ n\"\n      using power_diff[OF _ less_imp_le[OF assms], of \"2::int\"] by auto\n    hence \"(int o of_bool) (hd bl) * 2 ^ (length bl - n) = (int o of_bool) (hd bl) * 2 ^ length bl div 2 ^ n\"\n      by auto\n    thus ?thesis\n      by (smt add_diff_inverse_nat assms dvd_neg_div dvd_triv_left linorder_not_less\n      mult_cancel_right2 mult_minus_left o_apply of_bool_eq(1) of_bool_eq(2) of_nat_1\n      order_less_imp_le power_add semiring_1_class.of_nat_0)\n  qed\n  also have \"... = (bin_rest ^^ n) (bl_to_bin bl) + (bin_rest ^^ n) (- (int o of_bool) (hd bl) * 2 ^ length bl)\"\n    unfolding bin_rest_compow by auto\n  also have \"... = (bin_rest ^^ n) (bl_to_bin bl - (int o of_bool) (hd bl) * 2 ^ length bl)\"\n  proof -\n    have \"2 ^ n dvd (- (int \\<circ> of_bool) (hd bl) * 2 ^ length bl)\"\n      using assms  dvd_triv_right order_less_imp_le power_le_dvd by blast\n    thus ?thesis\n      unfolding bin_rest_compow\n      by (metis add.inverse_inverse diff_minus_eq_add div_plus_div_distrib_dvd_right\n          mult_minus_left)\n  qed\n  also have \"... = (bin_rest ^^ n) (sbl_to_bin bl)\"\n    by (metis (full_types) assms length_0_conv less_imp_diff_less less_not_refl2 sbl_to_bin.elims\n    zero_less_diff)\n  finally show ?thesis\n    by auto\nqed\n\nlemma take_rest_sbl2bin:\n  assumes \"n < length bl\"\n  shows   \"sbl_to_bin (take (length bl - n) bl) = (bin_rest ^^ n) (sbl_to_bin bl)\"\n  using butlast_pow_rest_sbl2bin[OF assms] by (simp add: butlast_power)\n\nlemma bl_to_bin_replicate_T:\n  \"bl_to_bin (replicate n True) = 2 ^ n - 1\"\nproof -\n  have \"bl_to_bin (replicate n True) = (\\<Sum>i = 0..<n. (int \\<circ> of_bool) ((replicate n True) ! i) * 2 ^ i)\"\n    unfolding bl_to_bin_correctness by auto\n  also have \"... = 2 ^ n - 1\"\n  proof (induction n)\n    case 0\n    then show ?case by auto\n  next\n    case (Suc n)\n    have \" (\\<Sum>i = 0..<Suc n. (int \\<circ> of_bool) (replicate (Suc n) True ! i) * 2 ^ i) =\n           (\\<Sum>i = 0..<n. (int \\<circ> of_bool) (replicate (Suc n) True ! i) * 2 ^ i) + 2 ^ n\"\n      by (metis (no_types, lifting) One_nat_def add_Suc add_diff_cancel_left' lessI nth_replicate\n      o_apply of_bool_eq(2) of_nat_1 plus_1_eq_Suc power_0 power_add sum.atLeast0_lessThan_Suc)\n    also have \"... = (\\<Sum>i = 0..<n. (int \\<circ> of_bool) (replicate n True ! i) * 2 ^ i) + 2 ^ n\"\n      by (metis (no_types, lifting) Diff_cancel atLeastLessThan_iff empty_iff finite_atLeastLessThan\n      inf.idem less_Suc_eq nth_replicate sum.mono_neutral_cong)\n    also have \"... = 2 ^ n - 1 + 2 ^ n\"\n      using Suc by auto\n    also have \"... = 2 ^ Suc n - 1\"\n      by auto\n    finally show ?case by auto\n  qed\n  finally show ?thesis\n    by auto\nqed\n\nlemma sbl_to_bin_replicate_app:\n  assumes \"0 < length bl\"\n  shows \"sbl_to_bin (replicate n (hd bl) @ bl) = sbl_to_bin bl\"\nproof (cases \"hd bl\")\n  case False\n  hence \"sbl_to_bin (replicate n (hd bl) @ bl) = sbl_to_bin (replicate n False @ bl)\"\n    by auto\n  also have \"... = bl_to_bin (replicate n False @ bl)\"\n    using sbl_to_bin.simps assms\n    by (smt False append_is_Nil_conv comp_apply hd_append hd_replicate length_greater_0_conv\n    mult_cancel_left of_bool_eq(1) power2_eq_square replicate_empty sbl_to_bin.elims\n    semiring_1_class.of_nat_0 zero_power2)\n  also have \"... = bl_to_bin bl\"\n    by (simp add: bl_to_bin_rep_F)\n  also have \"... = sbl_to_bin bl\"\n    using False sbl_to_bin.simps\n    by (smt assms comp_apply length_greater_0_conv mult_cancel_left of_bool_eq(1) power2_eq_square\n        sbl_to_bin.elims semiring_1_class.of_nat_0 zero_power2)\n  finally show ?thesis\n    by auto\nnext\n  case True\n  hence \"sbl_to_bin (replicate n (hd bl) @ bl) = sbl_to_bin (replicate n True @ bl)\"\n    by auto\n  also have \"... = bl_to_bin (replicate n True @ bl) - 2 ^ (length bl + n)\"\n    by (smt True add.commute assms comp_apply hd_append hd_replicate length_append\n    length_greater_0_conv length_replicate mult_cancel_right2 of_bool_eq(2) of_nat_1 replicate_empty\n    sbl_to_bin.elims)\n  also have \"... = bl_to_bin_aux bl (bl_to_bin (replicate n True)) - 2 ^ (length bl + n)\"\n    unfolding bl_to_bin_append by auto\n  also have \"... = bl_to_bin_aux bl (2 ^ n - 1) - 2 ^ (length bl + n)\"\n    unfolding bl_to_bin_replicate_T by auto\n  also have \"... = (2 ^ n - 1) * 2 ^ length bl + (\\<Sum>i = 0..<length bl. (int \\<circ> of_bool) (rev bl ! i) * 2 ^ i) - 2 ^ (length bl + n)\"\n    unfolding bl_to_bin_aux_correctness by auto\n  also have \"... = (2 ^ (length bl + n) - 2 ^ length bl) + (\\<Sum>i = 0..<length bl. (int \\<circ> of_bool) (rev bl ! i) * 2 ^ i) - 2 ^ (length bl + n)\"\n    by (simp add: mult.commute power_add right_diff_distrib)\n  also have \"... = (\\<Sum>i = 0..<length bl. (int \\<circ> of_bool) (rev bl ! i) * 2 ^ i) - 2 ^ length bl\"\n    by auto\n  also have \"... = bl_to_bin bl - 2 ^ length bl\"\n    unfolding bl_to_bin_correctness by auto\n  also have \"... = bl_to_bin bl - (int o of_bool) (hd bl) * 2 ^ length bl\"\n    using True by simp\n  also have \"... = sbl_to_bin bl\"\n    by (metis assms length_greater_0_conv sbl_to_bin.elims)\n  finally show ?thesis\n    by auto\nqed\n\ntext \\<open>Equivalence between @{term \"sbl_to_bin\"} and @{term \"sbintrunc\"} + @{term \"bl_to_bin\"}\\<close>\n\nlemma sbl_to_bin_alt_def:\n  \"sbl_to_bin bs = sbintrunc (length bs - 1) (bl_to_bin bs)\"\nproof (induction bs)\n  case Nil\n  then show ?case by auto\nnext\n  case (Cons a bs)\n  have \" sbl_to_bin (a # bs) =  bl_to_bin (a # bs) - (int \\<circ> of_bool) a * 2 ^ (length (bs) + 1)\"\n    unfolding sbl_to_bin.simps by auto\n  have \"a = True \\<or> a = False\"\n    by auto\n  moreover\n  { assume \"a = False\"\n    hence *: \"bl_to_bin (a # bs) - (int o of_bool) a * 2 ^ (length bs + 1) =  bl_to_bin (a # bs)\"\n      by auto\n    have \"bl_to_bin (a # bs) + 2 ^ length bs < 2 ^ (length bs + 1)\"\n      using `a = False` bl_to_bin_False by (auto simp add: bl_to_bin_lt2p)\n    hence \"bl_to_bin (a # bs) = sbintrunc (length (a # bs) - 1) (bl_to_bin (a # bs))\"\n      unfolding sbintrunc_mod2p  by (simp add: bl_to_bin_ge0)\n    hence ?case\n      using * by auto }\n  moreover\n  { assume \"a = True\"\n    hence *: \"bl_to_bin (a # bs) = 2 ^ length bs + bl_to_bin bs\"\n      using bl_to_bin_correctness  sbl_to_bin_correctness by auto\n    hence \"bl_to_bin (a # bs) - (int \\<circ> of_bool) a * 2 ^ (length (bs) + 1) =   bl_to_bin bs - 2 ^ length bs \"\n      using `a = True` by auto\n    also have \"... = sbintrunc (length bs) (bl_to_bin (a # bs))\"\n      unfolding sbintrunc_mod2p * \n      by (smt \"*\" \\<open>a = True\\<close> add.commute bl_to_bin_ge0 bl_to_bin_lt2p calculation int_mod_eq'\n      minus_mod_self2 mult_cancel_right2 o_apply of_bool_eq(2) of_nat_1 plus_1_eq_Suc)\n    finally have ?case\n      by simp }\n  ultimately show ?case by auto\nqed\n\nlemma\n  \"bl_to_bin (map Not bs) + 1 = 2 ^ length bs - bl_to_bin bs\"\nproof -\n  have \"bl_to_bin (map Not bs) = (\\<Sum>i = 0..<length bs. (int \\<circ> of_bool) (\\<not> (rev bs ! i)) * 2 ^ i)\"\n    unfolding bl_to_bin_correctness rev_map using nth_map[of _ \"rev bs\" \"Not\"] by auto\n  moreover have \"bl_to_bin bs = (\\<Sum>i = 0..<length bs. (int \\<circ> of_bool) (rev bs ! i) * 2 ^ i)\"\n    unfolding bl_to_bin_correctness by auto\n  ultimately have \"bl_to_bin (map Not bs) + bl_to_bin bs = (\\<Sum>i = 0..<length bs. (int \\<circ> of_bool) (\\<not> (rev bs ! i)) * 2 ^ i) +  (\\<Sum>i = 0..<length bs. (int \\<circ> of_bool) (rev bs ! i) * 2 ^ i)\"\n    by auto\n  also have \"... = (\\<Sum>x = 0..<length bs. (int \\<circ> of_bool) (\\<not> rev bs ! x) * 2 ^ x + (int \\<circ> of_bool) (rev bs ! x) * 2 ^ x)\"\n    unfolding sum.distrib[symmetric] by auto\n  also have \"... = (\\<Sum>x = 0..<length bs. ((int \\<circ> of_bool) (\\<not> rev bs ! x) + (int o of_bool) (rev bs ! x)) * 2 ^ x)\"\n    by (auto simp add: field_simps)\n  also have \"... = (\\<Sum>x = 0..<length bs. 2 ^ x)\"\n    by (smt comp_apply mult_cancel_right2 of_bool_eq(1) of_bool_eq(2) of_nat_1 semiring_1_class.of_nat_0 sum.cong)\n  also have \"... = bl_to_bin (replicate (length bs) True) \"\n    unfolding bl_to_bin_correctness by auto\n  also have \"... = 2 ^ length bs - 1\"\n    using bl_to_bin_replicate_T by auto\n  finally show ?thesis\n    by auto\nqed\n\nlemma uminus_alt':\n  \"sbl_to_bin (map Not (a # bs)) + 1 = - sbl_to_bin (a # bs)\"\nproof -\n  have \"sbl_to_bin (map Not (a # bs)) = sbl_to_bin (Not a # map Not bs)\"\n    by auto\n  also have \"... = - (int \\<circ> of_bool) (\\<not> a) * 2 ^ length bs + (\\<Sum>i = 0..<length bs. (int \\<circ> of_bool) ( \\<not> (rev bs ! i)) * 2 ^ i)\" (is \"_ = ?init_not + ?sbl_not\")\n    unfolding sbl_to_bin_correctness rev_map using nth_map[of _ \"rev bs\" \"Not\"] by auto\n  finally have \"sbl_to_bin (map Not (a # bs)) = ?init_not + ?sbl_not\"\n    by auto\n  have \"sbl_to_bin (a # bs) = - (int \\<circ> of_bool) a * 2 ^ length bs + (\\<Sum>i = 0..<length bs. (int \\<circ> of_bool) (rev bs ! i) * 2 ^ i)\" (is \"_ = ?init_def + ?sbl_def\")\n    unfolding sbl_to_bin_correctness by auto\n  hence \"sbl_to_bin (map Not (a # bs)) + sbl_to_bin (a # bs) = ?init_not + ?init_def + ?sbl_not + ?sbl_def\"\n    using `sbl_to_bin (map Not (a # bs)) = ?init_not + ?sbl_not` by auto\n  also have \"... = - (2 ^ length bs) + (?sbl_not + ?sbl_def)\"\n    by auto\n  also have \"... = - (2 ^ length bs) + (\\<Sum>x = 0..<length bs. (int \\<circ> of_bool) (\\<not> rev bs ! x) * 2 ^ x + (int \\<circ> of_bool) (rev bs ! x) * 2 ^ x)\"\n    unfolding sum.distrib[symmetric] by auto\n  also have \"... = - (2 ^ length bs) + (\\<Sum>x = 0..<length bs. ((int \\<circ> of_bool) (\\<not> rev bs ! x) + (int o of_bool) (rev bs ! x)) * 2 ^ x)\"\n    by (auto simp add: field_simps)\n  also have \"... = - (2 ^ length bs) + (\\<Sum>x = 0..<length bs. 2 ^ x)\"\n    by (smt comp_apply mult_cancel_right2 of_bool_eq(1) of_bool_eq(2) of_nat_1 semiring_1_class.of_nat_0 sum.cong)\n  also have \"... = - (2 ^ length bs) + bl_to_bin (replicate (length bs) True)\"\n    unfolding bl_to_bin_correctness by auto\n  also have \"... = - (2 ^ length bs) + 2 ^ length bs - 1\"\n    using bl_to_bin_replicate_T by auto\n  also have \"... = -1\"\n    by auto\n  finally show ?thesis\n    by auto\nqed\n\nlemma uminus_alt:\n  \"0 < length bs \\<Longrightarrow> sbl_to_bin (map Not bs) + 1 = - sbl_to_bin bs\"\n  using uminus_alt'  by (metis list_exhaust_size_gt0)\n\nlemma sbin_bl_bin_sbintruc:\n  \"0 < n \\<Longrightarrow> sbl_to_bin (bin_to_bl n w) = sbintrunc (n - 1) w\"\n  using bin_bl_bin sbl_to_bin_alt_def size_bin_to_bl by auto\n\nlemma sbl_to_bin_alt_def2:\n  \"sbl_to_bin bs = sbintrunc (length bs - 1) (sbl_to_bin bs)\"\n  by (simp add: sbl_to_bin_alt_def)\n\nlemma trunc_sbl2bin:\n  \"sbintrunc m (sbl_to_bin bs) = sbl_to_bin (drop (length bs - 1 - m) bs)\"\nproof -\n  have *: \"sbintrunc m (sbl_to_bin bs) =  sbintrunc m (sbintrunc (length bs - 1) (bl_to_bin bs))\"\n    unfolding sbl_to_bin_alt_def by auto\n  have \"length bs - 1 \\<le> m \\<or> m < length bs - 1\"\n    by auto\n  moreover\n  { assume less: \"length bs - 1 \\<le> m\"\n    have \"sbintrunc m (sbintrunc (length bs - 1) (bl_to_bin bs)) = sbintrunc (length bs - 1) (bl_to_bin bs)\"\n      unfolding sbintrunc_sbintrunc_l[OF less] by auto\n    also have \"... = sbl_to_bin bs\"\n      unfolding sbl_to_bin_alt_def by auto\n    finally have \"sbintrunc m (sbl_to_bin bs) = sbl_to_bin bs\"\n      using * by auto \n    also have \"... = sbl_to_bin (drop (length bs - 1 - m) bs)\"\n      using less by auto \n    finally have ?thesis\n      by blast }\n  moreover\n  { assume \"m < length bs - 1\"\n    hence ?thesis\n      using bl2bin_drop sbintrunc_bintrunc sbl_to_bin_alt_def by auto }\n  ultimately show ?thesis\n    by auto\nqed\n\nlemma sbl2bin_drop:\n  \"k < length bl \\<Longrightarrow> sbl_to_bin (drop k bl) = sbintrunc (length bl - 1 - k) (sbl_to_bin bl)\"\n  apply (rule trans)\n   prefer 2\n   apply (rule trunc_sbl2bin [symmetric])\n  apply (cases \"k \\<le> length bl - 1\")\n   apply auto\n  done\n\nlemma bin_rest_power_strunc:\n  \"k \\<le> n \\<Longrightarrow> (bin_rest ^^ k) (sbintrunc n bin) = sbintrunc (n - k) ((bin_rest ^^ k) bin)\"\nproof (induction k)\n  case 0\n  then show ?case by simp\nnext\n  case (Suc k)\n  hence \"(bin_rest ^^ k) (sbintrunc n bin) = sbintrunc (n - k) ((bin_rest ^^ k) bin)\"\n    by auto\n  then show ?case \n    using Suc.prems Suc_diff_le by fastforce\nqed  \n\n\nend", "meta": {"author": "rizaldialbert", "repo": "vhdl-semantics", "sha": "352f89c9ccdfe830c054757dfd86caeadbd67159", "save_path": "github-repos/isabelle/rizaldialbert-vhdl-semantics", "path": "github-repos/isabelle/rizaldialbert-vhdl-semantics/vhdl-semantics-352f89c9ccdfe830c054757dfd86caeadbd67159/Bits_Int_Aux.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8354835452961425, "lm_q2_score": 0.8499711756575749, "lm_q1q2_score": 0.710136931237921}}
{"text": "(*\n  File:     Miller_Rabin.thy\n  Authors:  Daniel St\u00fcwe\n\n  Some facts about Quadratic Residues that are missing from the library\n*)\nsection \\<open>Additional Material on Quadratic Residues\\<close>\ntheory QuadRes\nimports \n  Jacobi_Symbol\n  Algebraic_Auxiliaries\nbegin\n\ntext \\<open>Proofs are inspired by \\<^cite>\\<open>\"Quadratic_Residues\"\\<close>.\\<close>\n\nlemma inj_on_QuadRes:\n  fixes p :: int\n  assumes \"prime p\"\n  shows \"inj_on (\\<lambda>x. x^2 mod p) {0..(p-1) div 2}\"\nproof \n  fix x y :: int\n  assume elem: \"x \\<in> {0..(p-1) div 2}\" \"y \\<in> {0..(p-1) div 2}\"\n\n  have * : \"abs(a) < p \\<Longrightarrow> p dvd a \\<Longrightarrow> a = 0\" for a :: int\n    using dvd_imp_le_int by force\n\n  assume \"x\\<^sup>2 mod p = y\\<^sup>2 mod p\"\n\n  hence \"[x\\<^sup>2 = y\\<^sup>2] (mod p)\" unfolding cong_def .\n\n  hence \"p dvd (x\\<^sup>2 - y\\<^sup>2)\" by (simp add: cong_iff_dvd_diff)\n\n  hence \"p dvd (x + y) * (x - y)\" \n    by (simp add: power2_eq_square square_diff_square_factored) \n  \n  hence \"p dvd (x + y) \\<or> p dvd (x - y)\"\n    using \\<open>prime p\\<close> by (simp add: prime_dvd_mult_iff) \n\n  moreover have \"p dvd x + y \\<Longrightarrow> x + y = 0\" \"p dvd x - y \\<Longrightarrow> x - y = 0\" \n           and \"0 \\<le> x\" \"0 \\<le> y\"\n      using elem  \n      by (fastforce intro!: * )+\n  \n  ultimately show \"x = y\" by auto\nqed\n\nlemma QuadRes_set_prime: \n  assumes \"prime p\" and \"odd p\"\n  shows \"{x . QuadRes p x \\<and> x \\<in> {0..<p}} = {x^2 mod p | x . x \\<in> {0..(p-1) div 2}}\"\nproof(safe, goal_cases)\n  case (1 x)\n  then obtain y where \"[y\\<^sup>2 = x] (mod p)\" \n    unfolding QuadRes_def by blast\n\n  then have A: \"[(y mod p)\\<^sup>2 = x] (mod p)\" \n    unfolding cong_def\n    by (simp add: power_mod)\n\n  then have \"[(-(y mod p))\\<^sup>2 = x] (mod p)\" \n    by simp\n\n  then have B: \"[(p - (y mod p))\\<^sup>2 = x] (mod p)\" \n    unfolding cong_def \n    using minus_mod_self1\n    by (metis power_mod)\n\n  have \"p = 1 + ((p - 1) div 2) * 2\"\n    using prime_gt_0_int[OF \\<open>prime p\\<close>] \\<open>odd p\\<close>\n    by simp\n\n  then have C: \"(p - (y mod p)) \\<in> {0..(p - 1) div 2} \\<or> y mod p \\<in> {0..(p - 1) div 2}\"\n    using prime_gt_0_int[OF \\<open>prime p\\<close>] \n    by (clarsimp, auto simp: le_less)\n\n  then show ?case proof\n    show ?thesis if \"p - y mod p \\<in> {0..(p - 1) div 2}\"\n      using that B\n      unfolding cong_def\n      using \\<open>x \\<in> {0..<p}\\<close> by auto\n\n    show ?thesis if \"y mod p \\<in> {0..(p - 1) div 2}\"\n      using that A\n      unfolding cong_def\n      using \\<open>x \\<in> {0..<p}\\<close> by auto\n  qed\nqed (auto simp: QuadRes_def cong_def)\n\ncorollary QuadRes_iff: \n  assumes \"prime p\" and \"odd p\"\n  shows \"(QuadRes p x \\<and> x \\<in> {0..<p}) \\<longleftrightarrow> (\\<exists> a \\<in> {0..(p-1) div 2}. a^2 mod p = x)\"\nproof -\n  have \"(QuadRes p x \\<and> x \\<in> {0..<p}) \\<longleftrightarrow> x \\<in> {x. QuadRes p x \\<and> x \\<in> {0..<p}}\"\n    by auto\n  also note QuadRes_set_prime[OF assms]\n  also have \"(x \\<in> {x\\<^sup>2 mod p |x. x \\<in> {0..(p - 1) div 2}}) = (\\<exists>a\\<in>{0..(p - 1) div 2}. a\\<^sup>2 mod p = x)\"\n    by blast\n  finally show ?thesis .\nqed\n\ncorollary card_QuadRes_set_prime:\n  fixes p :: int\n  assumes \"prime p\" and \"odd p\"\n  shows \"card {x. QuadRes p x \\<and> x \\<in> {0..<p}} = nat (p+1) div 2\"\nproof -\n  have \"card {x. QuadRes p x \\<and> x \\<in> {0..<p}} = card {x\\<^sup>2 mod p | x . x \\<in> {0..(p-1) div 2}}\"\n    unfolding QuadRes_set_prime[OF assms] ..\n\n  also have \"{x\\<^sup>2 mod p | x . x \\<in> {0..(p-1) div 2}} = (\\<lambda>x. x\\<^sup>2 mod p) ` {0..(p-1) div 2}\"\n    by auto\n\n  also have \"card ... = card {0..(p-1) div 2}\"\n    using inj_on_QuadRes[OF \\<open>prime p\\<close>] by (rule card_image)\n\n  also have \"... = nat (p+1) div 2\" by simp\n\n  finally show ?thesis .\nqed\n\ncorollary card_not_QuadRes_set_prime:\n  fixes p :: int\n  assumes \"prime p\" and \"odd p\"\n  shows \"card {x. \\<not>QuadRes p x \\<and> x \\<in> {0..<p}} = nat (p-1) div 2\"\nproof -\n  have \"{0..<p} \\<inter> {x. QuadRes p x \\<and> x \\<in> {0..<p}} = {x. QuadRes p x \\<and> x \\<in> {0..<p}}\"\n    by blast\n\n  moreover have \"nat p - nat (p + 1) div 2 = nat (p - 1) div 2\"\n    using \\<open>odd p\\<close> prime_gt_0_int[OF \\<open>prime p\\<close>]\n    by (auto elim!: oddE simp: nat_add_distrib nat_mult_distrib)\n\n  ultimately have \"card {0..<p} - card ({0..<p} \\<inter> {x. QuadRes p x \\<and> x \\<in> {0..<p}}) = nat (p - 1) div 2\"\n    using card_QuadRes_set_prime[OF assms] and card_atLeastZeroLessThan_int by presburger    \n\n  moreover have \"{x. \\<not>QuadRes p x \\<and> x \\<in> {0..<p}} = {0..<p} - {x. QuadRes p x \\<and> x \\<in> {0..<p}}\"\n    by blast\n\n  ultimately show ?thesis by (auto simp add: card_Diff_subset_Int)\nqed\n\nlemma not_QuadRes_ex_if_prime:\n  assumes \"prime p\" and \"odd p\"\n  shows \"\\<exists> x. \\<not>QuadRes p x\"\nproof -\n  have \"2 < p\" using odd_prime_gt_2_int assms by blast\n\n  then have False if \"{x . \\<not>QuadRes p x \\<and> x \\<in> {0..<p}} = {}\"\n    using card_not_QuadRes_set_prime[OF assms]\n    unfolding that\n    by simp\n\n  thus ?thesis by blast\nqed\n\nlemma not_QuadRes_ex:\n  \"1 < p \\<Longrightarrow> odd p \\<Longrightarrow> \\<exists>x. \\<not>QuadRes p x\"\nproof (induction p rule: prime_divisors_induct)\n  case (factor p x)\n  then show ?case \n    by (meson not_QuadRes_ex_if_prime QuadRes_def cong_iff_dvd_diff dvd_mult_left even_mult_iff)\nqed simp_all\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/Probabilistic_Prime_Tests/QuadRes.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711794579723, "lm_q2_score": 0.8354835330070838, "lm_q1q2_score": 0.7101369239677447}}
{"text": "(*\n  File:     Balanced.thy\n  Author:   Martin Rau, TU M\u00fcnchen\n*)\n\nsection \\<open>Building a balanced \\<open>k\\<close>-d Tree from a List of Points\\<close>\n\ntheory Balanced\nimports\n  KDTree\n  Median_Of_Medians_Selection.Median_Of_Medians_Selection\nbegin\n\ntext \\<open>\n  Build a balanced \\<open>k\\<close>-d Tree by recursively partition the points into two lists.\n  The partitioning criteria will be the median at a particular axis \\<open>k\\<close>.\n  The left list will contain all points \\<open>p\\<close> with @{term \"p$k \\<le> median\"}.\n  The right list will contain all points with median at axis @{term \"median < p$k\"}.\n  The left and right list differ in length by one or none.\n  The axis \\<open>k\\<close> will the widest spread axis.\n\\<close>\n\nsubsection \"Auxiliary Lemmas\"\n\nlemma length_filter_mset_sorted_nth:\n  assumes \"distinct xs\" \"n < length xs\" \"sorted xs\"\n  shows \"{# x \\<in># mset xs. x \\<le> xs ! n #} = mset (take (n + 1) xs)\"\n  using assms\nproof (induction xs arbitrary: n rule: list.induct)\n  case (Cons x xs)\n  thus ?case\n  proof (cases n)\n    case 0\n    thus ?thesis\n      using Cons.prems(1,3) filter_mset_is_empty_iff by fastforce\n  next\n    case (Suc n')\n    thus ?thesis\n      using Cons by simp\n  qed\nqed auto\n\nlemma length_filter_sort_nth:\n  assumes \"distinct xs\" \"n < length xs\"\n  shows \"length (filter (\\<lambda>x. x \\<le> sort xs ! n) xs) = n + 1\"\nproof -\n  have \"length (filter (\\<lambda>x. x \\<le> sort xs ! n) xs) = length (filter (\\<lambda>x. x \\<le> sort xs ! n) (sort xs))\"\n    by (simp add: filter_sort)\n  also have \"... = size (mset (filter (\\<lambda>x. x \\<le> sort xs ! n) (sort xs)))\"\n    using size_mset by metis\n  also have \"... = size ({# x \\<in># mset (sort xs). x \\<le> sort xs ! n #})\"\n    using mset_filter by simp\n  also have \"... = size (mset (take (n + 1) (sort xs)))\"\n    using length_filter_mset_sorted_nth assms sorted_sort distinct_sort length_sort by metis\n  finally show ?thesis\n    using assms(2) by auto\nqed\n\n\nsubsection \\<open>Widest Spread Axis\\<close>\n\ndefinition calc_spread :: \"('k::finite) \\<Rightarrow> 'k point list \\<Rightarrow> real\" where\n  \"calc_spread k ps = (case ps of [] \\<Rightarrow> 0 | ps \\<Rightarrow>\n    let ks = map (\\<lambda>p. p$k) (tl ps) in\n    fold max ks ((hd ps)$k) - fold min ks ((hd ps)$k)\n  )\"\n\nfun widest_spread :: \"('k::finite) list \\<Rightarrow> 'k point list \\<Rightarrow> 'k \\<times> real\" where\n  \"widest_spread [] _ = undefined\"\n| \"widest_spread [k] ps = (k, calc_spread k ps)\"\n| \"widest_spread (k # ks) ps = (\n    let (k', s') = widest_spread ks ps in\n    let s = calc_spread k ps in\n    if s \\<le> s' then (k', s') else (k, s)\n  )\"\n\nlemma calc_spread_spec:\n  \"calc_spread k ps = spread k (set ps)\"\n  using Max.set_eq_fold[of \"(hd ps)$k\"] Min.set_eq_fold[of \"(hd ps)$k\"]\n  by (auto simp: Let_def spread_def calc_spread_def split: list.splits, metis set_map)\n\nlemma widest_spread_calc_spread:\n  \"ks \\<noteq> [] \\<Longrightarrow> (k, s) = widest_spread ks ps \\<Longrightarrow> s = calc_spread k ps\"\n  by (induction ks ps rule: widest_spread.induct) (auto simp: Let_def split: prod.splits if_splits)\n\nlemma widest_spread_axis_Un:\n  shows \"widest_spread_axis k K P \\<Longrightarrow> spread k' P \\<le> spread k P \\<Longrightarrow> widest_spread_axis k (K \\<union> { k' }) P\"\n    and \"widest_spread_axis k K P \\<Longrightarrow> spread k P \\<le> spread k' P \\<Longrightarrow> widest_spread_axis k' (K \\<union> { k' }) P\"\n  unfolding widest_spread_axis_def by auto\n\nlemma widest_spread_spec:\n  \"(k, s) = widest_spread ks ps \\<Longrightarrow> widest_spread_axis k (set ks) (set ps)\"\nproof (induction ks ps arbitrary: k s rule: widest_spread.induct)\n  case (3 k\\<^sub>0 k\\<^sub>1 ks ps)\n  obtain K' S' where K'_def: \"(K', S') = widest_spread (k\\<^sub>1 # ks) ps\"\n    by (metis surj_pair)\n  hence IH: \"widest_spread_axis K' (set (k\\<^sub>1 # ks)) (set ps)\"\n    using \"3.IH\" by blast\n  hence 0: \"S' = spread K' (set ps)\"\n    using K'_def widest_spread_calc_spread calc_spread_spec by blast\n  define S where \"S = calc_spread k\\<^sub>0 ps\"\n  hence 1: \"S = spread k\\<^sub>0 (set ps)\"\n    using calc_spread_spec by blast\n  show ?case\n  proof (cases \"S \\<le> S'\")\n    case True\n    hence \"widest_spread_axis K' (set (k\\<^sub>0 # k\\<^sub>1 # ks)) (set ps)\"\n      using 0 1 widest_spread_axis_Un(1)[OF IH, of k\\<^sub>0]  by auto\n    thus ?thesis\n      using True K'_def S_def \"3.prems\" by (auto split: prod.splits)\n  next\n    case False\n    hence \"widest_spread_axis k\\<^sub>0 (set (k\\<^sub>0 # k\\<^sub>1 # ks)) (set ps)\"\n      using 0 1 widest_spread_axis_Un(2)[OF IH, of k\\<^sub>0] \"3.prems\"(1) by auto\n    thus ?thesis\n      using False K'_def S_def \"3.prems\" by (auto split: prod.splits)\n  qed\nqed (auto simp: widest_spread_axis_def)\n\n\nsubsection \\<open>Fast Axis Median\\<close>\n\ndefinition axis_median :: \"('k::finite) \\<Rightarrow> 'k point list \\<Rightarrow> real\" where\n  \"axis_median k ps = (let n = (length ps - 1) div 2 in fast_select n (map (\\<lambda>p. p$k) ps))\"\n\nlemma length_filter_le_axis_median:\n  assumes \"0 < length ps\" \"\\<forall>k. distinct (map (\\<lambda>p. p$k) ps)\"\n  shows \"length (filter (\\<lambda>p. p$k \\<le> axis_median k ps) ps) = (length ps - 1) div 2 + 1\"\nproof -\n  let ?n = \"(length ps - 1) div 2\"\n  let ?ps = \"map (\\<lambda>p. p$k) ps\"\n  let ?m = \"fast_select ?n ?ps\"\n  have 0: \"?n < length ?ps\"\n    using assms(1) by (auto, linarith)\n  have 1: \"distinct ?ps\"\n    using assms(2) by blast\n  have \"?m = select ?n ?ps\"\n    using fast_select_correct[OF 0] by blast\n  hence \"length (filter (\\<lambda>p. p$k \\<le> axis_median k ps) ps) =\n        length (filter (\\<lambda>p. p$k \\<le> sort ?ps ! ?n) ps)\"\n    unfolding axis_median_def by (auto simp add: Let_def select_def simp del: fast_select.simps)\n  also have \"... = length (filter (\\<lambda>v. v \\<le> sort ?ps ! ?n) ?ps)\"\n    by (induction ps) (auto, metis comp_apply)\n  also have \"... = ?n + 1\"\n    using length_filter_sort_nth[OF 1 0] by blast\n  finally show ?thesis .\nqed\n\ndefinition partition_by_median :: \"('k::finite) \\<Rightarrow> 'k point list \\<Rightarrow> 'k point list \\<times> real \\<times> 'k point list\" where\n  \"partition_by_median k ps = (\n     let m = axis_median k ps in\n     let (l, r) = partition (\\<lambda>p. p$k \\<le> m) ps in\n     (l, m, r)\n  )\"\n\nlemma set_partition_by_median:\n  \"(l, m, r) = partition_by_median k ps \\<Longrightarrow> set ps = set l \\<union> set r\"\n  unfolding partition_by_median_def by (auto simp: Let_def)\n\nlemma filter_partition_by_median:\n  assumes \"(l, m, r) = partition_by_median k ps\"\n  shows \"\\<forall>p \\<in> set l. p$k \\<le> m\"\n    and \"\\<forall>p \\<in> set r. \\<not>p$k \\<le> m\"\n  using assms unfolding partition_by_median_def by (auto simp: Let_def)\n\nlemma sum_length_partition_by_median:\n  assumes \"(l, m, r) = partition_by_median k ps\"\n  shows \"length ps = length l + length r\"\n  using assms sum_length_filter_compl[of \"(\\<lambda>p. p $ k \\<le> axis_median k ps)\"]\n  unfolding partition_by_median_def by (simp add: Let_def o_def)\n\nlemma length_l_partition_by_median:\n  assumes \"0 < length ps\" \"\\<forall>k. distinct (map (\\<lambda>p. p$k) ps)\" \"(l, m, r) = partition_by_median k ps\"\n  shows \"length l = (length ps - 1) div 2 + 1\"\n  using assms unfolding partition_by_median_def by (auto simp: Let_def length_filter_le_axis_median)\n\ncorollary lengths_partition_by_median_1:\n  assumes \"0 < length ps\"  \"\\<forall>k. distinct (map (\\<lambda>p. p$k) ps)\" \"(l, m, r) = partition_by_median k ps\"\n  shows \"length l - length r \\<le> 1\"\n    and \"length r \\<le> length l\"\n    and \"0 < length l\"\n    and \"length r < length ps\"\n  using length_l_partition_by_median[OF assms] sum_length_partition_by_median[OF assms(3)] by auto\n\ncorollary lengths_partition_by_median_2:\n  assumes \"1 < length ps\" \"\\<forall>k. distinct (map (\\<lambda>p. p$k) ps)\" \"(l, m, r) = partition_by_median k ps\"\n  shows \"0 < length r\"\n    and \"length l < length ps\"\nproof -\n  have *: \"0 < length ps\"\n    using assms(1) by auto\n  show \"0 < length r\" \"length l < length ps\"\n    using length_l_partition_by_median[OF * assms(2,3)] sum_length_partition_by_median[OF assms(3)]\n    using assms(1) by linarith+\nqed\n\nlemmas length_partition_by_median =\n  sum_length_partition_by_median length_l_partition_by_median\n  lengths_partition_by_median_1 lengths_partition_by_median_2\n\n\nsubsection \\<open>Building the Tree\\<close>\n\nfunction (domintros, sequential) build :: \"('k::finite) list \\<Rightarrow> 'k point list \\<Rightarrow> 'k kdt\" where\n  \"build _ [] = undefined\"\n| \"build _ [p] = Leaf p\"\n| \"build ks ps = (\n    let (k, _) = widest_spread ks ps in\n    let (l, m, r) = partition_by_median k ps in\n    Node k m (build ks l) (build ks r)\n  )\"\n  by pat_completeness auto\n\nlemma build_domintros3:\n  assumes \"(k, s) = widest_spread ks (x # y # zs)\" \"(l, m, r) = partition_by_median k (x # y # zs)\"\n  assumes \"build_dom (ks, l)\" \"build_dom (ks, r)\"\n  shows \"build_dom (ks, x # y # zs)\"\nproof -\n  {\n    fix k s l m r\n    assume \"(k, s) = widest_spread ks (x # y # zs)\" \"(l, m, r) = partition_by_median k (x # y # zs)\"\n    hence \"build_dom (ks, l)\" \"build_dom (ks, r)\"\n      using assms by (metis Pair_inject)+\n  }\n  thus ?thesis\n    by (simp add: build.domintros(3))\nqed\n\nlemma build_termination:\n  assumes \"\\<forall>k. distinct (map (\\<lambda>p. p$k) ps)\"\n  shows \"build_dom (ks, ps)\"\n  using assms\nproof (induction ps rule: length_induct)\n  case (1 xs)\n  consider (A) \"xs = []\" | (B) \"\\<exists>x. xs = [x]\" | (C) \"\\<exists>x y zs. xs = x # y # zs\"\n    by (induction xs rule: induct_list012) auto\n  then show ?case\n  proof cases\n    case C\n    then obtain x y zs where xyzs_def: \"xs = x # y # zs\"\n      by blast\n    obtain k s where ks_def: \"(k, s) = widest_spread ks xs\"\n      by (metis surj_pair)\n    obtain l m r where lmr_def: \"(l, m, r) = partition_by_median k xs\"\n      by (metis prod_cases3)\n    note defs = xyzs_def ks_def lmr_def\n    have \"\\<forall>k. distinct (map (\\<lambda>p. p $ k) l)\" \"\\<forall>k. distinct (map (\\<lambda>p. p $ k) r)\"\n      using lmr_def unfolding partition_by_median_def\n      by (auto simp: Let_def \"1.prems\" distinct_map_filter)\n    moreover have \"length l < length xs\" \"length r < length xs\"\n      using length_partition_by_median(8)[OF _ \"1.prems\"] length_partition_by_median(6)[OF _ \"1.prems\"]\n      using defs by auto\n    ultimately have \"build_dom (ks, l)\" \"build_dom (ks, r)\"\n      using \"1.IH\" by blast+\n    thus ?thesis\n      using build_domintros3 defs by blast\n  qed (auto intro: build.domintros)\nqed\n\nlemma build_psimp_1:\n  \"ps = [p] \\<Longrightarrow> build k ps = Leaf p\"\n  by (simp add: build.domintros(2) build.psimps(2))\n\nlemma build_psimp_2:\n  assumes \"(k, s) = widest_spread ks (x # y # zs)\" \"(l, m, r) = partition_by_median k (x # y # zs)\"\n  assumes \"build_dom (ks, l)\" \"build_dom (ks, r)\"\n  shows \"build ks (x # y # zs) = Node k m (build ks l) (build ks r)\"\nproof -\n  have 0: \"build_dom (ks, x # y # zs)\"\n    using assms build_domintros3 by blast\n  thus ?thesis\n    using build.psimps(3)[OF 0] assms(1,2) by (auto split: prod.splits)\nqed\n\nlemma length_xs_gt_1:\n  \"1 < length xs \\<Longrightarrow> \\<exists>x y ys. xs = x # y # ys\"\n  by (cases xs, auto simp: neq_Nil_conv)\n\nlemma build_psimp_3:\n  assumes \"1 < length ps\" \"(k, s) = widest_spread ks ps\" \"(l, m, r) = partition_by_median k ps\"\n  assumes \"build_dom (ks, l)\" \"build_dom (ks, r)\"\n  shows \"build ks ps = Node k m (build ks l) (build ks r)\"\n  using build_psimp_2 length_xs_gt_1 assms by blast\n\nlemmas build_psimps[simp] = build_psimp_1 build_psimp_3\n\n\nsubsection \\<open>Main Theorems\\<close>\n\ntheorem set_build:\n  \"0 < length ps \\<Longrightarrow> \\<forall>k. distinct (map (\\<lambda>p. p$k) ps) \\<Longrightarrow> set ps = set_kdt (build ks ps)\"\nproof (induction ps rule: length_induct)\n  case (1 ps)\n  show ?case\n  proof (cases \"1 < length ps\")\n    case True\n    obtain k s where ks_def: \"(k, s) = widest_spread ks ps\"\n      by (metis surj_pair)\n    obtain l m r where lmr_def: \"(l, m, r) = partition_by_median k ps\"\n      by (metis prod_cases3)\n    have D: \"\\<forall>k. distinct (map (\\<lambda>p. p$k) l)\" \"\\<forall>k. distinct (map (\\<lambda>p. p$k) r)\"\n      using lmr_def unfolding partition_by_median_def\n      by (auto simp: \"1.prems\"(2) Let_def distinct_map_filter)\n    moreover have \"length l < length ps\" \"0 < length l\"\n                  \"length r < length ps\" \"0 < length r\"\n      using length_partition_by_median(8)[OF True \"1.prems\"(2)]\n            length_partition_by_median(5)[OF \"1.prems\"(1) \"1.prems\"(2)]\n            length_partition_by_median(6)[OF \"1.prems\"(1) \"1.prems\"(2)]\n            length_partition_by_median(7)[OF True \"1.prems\"(2)]\n            lmr_def by blast+\n    ultimately have \"set l = set_kdt (build ks l)\" \"set r = set_kdt (build ks r)\"\n      using \"1.IH\" by blast+\n    moreover have \"set ps = set l \\<union> set r\"\n      using lmr_def unfolding partition_by_median_def by (auto simp: Let_def)\n    moreover have \"build ks ps = Node k m (build ks l) (build ks r)\"\n      using build_psimp_3[OF True ks_def lmr_def] build_termination D by blast\n    ultimately show ?thesis\n      by simp\n  next\n    case False\n    thus ?thesis\n      using \"1.prems\" by (cases ps) auto\n  qed\nqed\n\ntheorem invar_build:\n  \"0 < length ps \\<Longrightarrow> \\<forall>k. distinct (map (\\<lambda>p. p$k) ps) \\<Longrightarrow> set ks = UNIV \\<Longrightarrow> invar (build ks ps)\"\nproof (induction ps rule: length_induct)\n  case (1 ps)\n  show ?case\n  proof (cases \"1 < length ps\")\n    case True\n    obtain k s where ks_def: \"(k, s) = widest_spread ks ps\"\n      by (metis surj_pair)\n    obtain l m r where lmr_def: \"(l, m, r) = partition_by_median k ps\"\n      by (metis prod_cases3)\n    have D: \"\\<forall>k. distinct (map (\\<lambda>p. p$k) l)\" \"\\<forall>k. distinct (map (\\<lambda>p. p$k) r)\"\n      using lmr_def unfolding partition_by_median_def\n      by (auto simp: \"1.prems\"(2) Let_def distinct_map_filter)\n    moreover have \"length l < length ps\" \"0 < length l\"\n                  \"length r < length ps\" \"0 < length r\"\n      using length_partition_by_median(8)[OF True \"1.prems\"(2)]\n            length_partition_by_median(5)[OF \"1.prems\"(1) \"1.prems\"(2)]\n            length_partition_by_median(6)[OF \"1.prems\"(1) \"1.prems\"(2)]\n            length_partition_by_median(7)[OF True \"1.prems\"(2)]\n            lmr_def by blast+\n    ultimately have \"invar (build ks l)\" \"invar (build ks r)\"\n      using \"1.IH\" \"1.prems\"(3) by blast+\n    moreover have \"\\<forall>p \\<in> set l. p$k \\<le> m\" \"\\<forall>p \\<in> set r. m < p$k\"\n      using filter_partition_by_median(1)[OF lmr_def]\n            filter_partition_by_median(2)[OF lmr_def] by auto\n    moreover have \"widest_spread_axis k UNIV (set l \\<union> set r)\"\n      using widest_spread_spec[OF ks_def] \"1.prems\"(3) set_partition_by_median[OF lmr_def] by simp\n    moreover have \"build ks ps = Node k m (build ks l) (build ks r)\"\n      using build_psimp_3[OF True ks_def lmr_def] build_termination D by blast\n    ultimately show ?thesis\n      using set_build[OF \\<open>0 < length l\\<close> D(1)] set_build[OF \\<open>0 < length r\\<close> D(2)] by simp\n  next\n    case False\n    thus ?thesis\n      using \"1.prems\" by (cases ps) auto\n  qed\nqed\n\ntheorem size_build:\n  \"0 < length ps \\<Longrightarrow> \\<forall>k. distinct (map (\\<lambda>p. p$k) ps) \\<Longrightarrow> size_kdt (build ks ps) = length ps\"\nproof (induction ps rule: length_induct)\n  case (1 ps)\n  show ?case\n  proof (cases \"1 < length ps\")\n    case True\n    obtain k s where ks_def: \"(k, s) = widest_spread ks ps\"\n      by (metis surj_pair)\n    obtain l m r where lmr_def: \"(l, m, r) = partition_by_median k ps\"\n      by (metis prod_cases3)\n    have D: \"\\<forall>k. distinct (map (\\<lambda>p. p$k) l)\" \"\\<forall>k. distinct (map (\\<lambda>p. p$k) r)\"\n      using lmr_def unfolding partition_by_median_def\n      by (auto simp: \"1.prems\"(2) Let_def distinct_map_filter)\n    moreover have \"length l < length ps\" \"0 < length l\"\n                  \"length r < length ps\" \"0 < length r\"\n      using length_partition_by_median(8)[OF True \"1.prems\"(2)]\n            length_partition_by_median(5)[OF \"1.prems\"(1) \"1.prems\"(2)]\n            length_partition_by_median(6)[OF \"1.prems\"(1) \"1.prems\"(2)]\n            length_partition_by_median(7)[OF True \"1.prems\"(2)]\n            lmr_def by blast+\n    ultimately have \"size_kdt (build ks l) = length l\" \"size_kdt (build ks r) = length r\"\n      using \"1.IH\" by blast+\n    moreover have \"build ks ps = Node k m (build ks l) (build ks r)\"\n      using build_psimp_3[OF True ks_def lmr_def] build_termination D by blast\n    ultimately show ?thesis\n      using length_partition_by_median(1)[OF lmr_def] by simp\n  next\n    case False\n    thus ?thesis\n      using \"1.prems\" by (cases ps) auto\n  qed\nqed\n\ntheorem balanced_build:\n  \"0 < length ps \\<Longrightarrow> \\<forall>k. distinct (map (\\<lambda>p. p$k) ps) \\<Longrightarrow> balanced (build ks ps)\"\nproof (induction ps rule: length_induct)\n  case (1 ps)\n  show ?case\n  proof (cases \"1 < length ps\")\n    case True\n    obtain k s where ks_def: \"(k, s) = widest_spread ks ps\"\n      by (metis surj_pair)\n    obtain l m r where lmr_def: \"(l, m, r) = partition_by_median k ps\"\n      by (metis prod_cases3)\n    have D: \"\\<forall>k. distinct (map (\\<lambda>p. p$k) l)\" \"\\<forall>k. distinct (map (\\<lambda>p. p$k) r)\"\n      using lmr_def unfolding partition_by_median_def\n      by (auto simp: \"1.prems\"(2) Let_def distinct_map_filter)\n    moreover have \"length l < length ps\" \"0 < length l\"\n                  \"length r < length ps\" \"0 < length r\"\n      using length_partition_by_median(8)[OF True \"1.prems\"(2)]\n            length_partition_by_median(5)[OF \"1.prems\"(1) \"1.prems\"(2)]\n            length_partition_by_median(6)[OF \"1.prems\"(1) \"1.prems\"(2)]\n            length_partition_by_median(7)[OF True \"1.prems\"(2)]\n            lmr_def by blast+\n    ultimately have IH: \"balanced (build ks l)\" \"balanced (build ks r)\"\n      using \"1.IH\" by blast+\n    have \"build ks ps = Node k m (build ks l) (build ks r)\"\n      using build_psimp_3[OF True ks_def lmr_def] build_termination D by blast\n    moreover have \"length r + 1 = length l \\<or> length r = length l\"\n      using length_partition_by_median(1)[OF lmr_def]\n            length_partition_by_median(3)[OF \"1.prems\"(1) \"1.prems\"(2) lmr_def]\n            length_partition_by_median(4)[OF \"1.prems\"(1) \"1.prems\"(2) lmr_def]\n      by linarith\n    ultimately show ?thesis\n      using balanced_Node_if_wbal1[OF IH] balanced_Node_if_wbal2[OF IH]\n            size_build[OF \\<open>0 < length l\\<close> D(1)] size_build[OF \\<open>0 < length r\\<close> D(2)]\n      by auto\n  next\n    case False\n    thus ?thesis\n      using \"1.prems\" by (cases ps) (auto simp: balanced_def)\n  qed\nqed\n\nlemma complete_if_balanced_size_2powh:\n  assumes \"balanced kdt\" \"size_kdt kdt = 2 ^ h\"\n  shows \"complete kdt\"\nproof (rule ccontr)\n  assume \"\\<not> complete kdt\"\n  hence \"2 ^ (min_height kdt) < size_kdt kdt\" \"size_kdt kdt < 2 ^ height kdt\"\n    by (simp_all add: min_height_size_if_incomplete size_height_if_incomplete)\n  hence \"height kdt - min_height kdt > 1\"\n    using assms(2) by simp\n  hence \"\\<not> balanced kdt\"\n    using balanced_def by force\n  thus \"False\"\n    using assms(1) by simp\nqed\n\ntheorem complete_build:\n  \"length ps = 2 ^ h \\<Longrightarrow> \\<forall>k. distinct (map (\\<lambda>p. p$k) ps) \\<Longrightarrow> complete (build k ps)\"\n  by (simp add: balanced_build complete_if_balanced_size_2powh size_build)\n\ncorollary height_build:\n  assumes \"length ps = 2 ^ h\" \"\\<forall>k. distinct (map (\\<lambda>p. p$k) ps)\"\n  shows \"h = height (build k ps)\"\n  using complete_build[OF assms] size_build[OF _ assms(2)] by (simp add: assms(1) complete_iff_size)\n\nend\n", "meta": {"author": "pacellie", "repo": "k_d_tree", "sha": "fdc79a45f7157ef69b487786b8effbde0518a4d4", "save_path": "github-repos/isabelle/pacellie-k_d_tree", "path": "github-repos/isabelle/pacellie-k_d_tree/k_d_tree-fdc79a45f7157ef69b487786b8effbde0518a4d4/Balanced.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8499711604559846, "lm_q2_score": 0.8354835330070839, "lm_q1q2_score": 0.710136908091897}}
{"text": "(* Suma de los primeros n\u00fameros impares *)\n\n(*<*)\ntheory SumaImpares\nimports Main \"HOL-Library.LaTeXsugar\" \"HOL-Library.OptionalSugar\" \nbegin\n(*>*) \n\nsection \\<open>Suma de los primeros n\u00fameros impares \\<close>\nsubsection \\<open>Demostraci\u00f3n en lenguaje natural\\<close>\n\ntext \\<open>El primer teorema es una propiedad de los n\u00fameros naturales.\n\n  \\begin{teorema}\n    La suma de los $n$ primeros n\u00fameros impares es $n^2$.\n  \\end{teorema}\n\n  \\begin{demostracion}\n    La demostraci\u00f3n la haremos por inducci\u00f3n sobre $n$.\n    \n    (Base de la inducci\u00f3n) El caso $n = 0$ es trivial.\n    \n    (Paso de la inducci\u00f3n) Supongamos que la propiedad se verifica para\n    $n$ y veamos que tambi\u00e9n se verifica para $n+1$. \n \n    Tenemos que demostrar que $\\sum_{j=1}^{n+1} k_j = (n+1)^2$ donde\n    $k_j$ el j--\u00e9simo impar; es decir, $k_j = 2j - 1$.\n\n    $$\\begin{array}{l}\n      \\sum_{j = 1}^{n+1} k_j    \\\\\n      = k_{n+1} + \\sum^{n}_{j=1} k_j   \\\\ \n      = k_{n+1} + n^2  \\quad @{text \" (Hip\u00f3tesis inducci\u00f3n) \"} \\\\\n      = 2(n+1) - 1 + n^2 \\\\\n      = n^2 + 2n + 1   \\\\ \n      = (n+1)^2 \n      \\end{array}$$ \n  \\end{demostracion}\n\\<close>\n\nsubsection \\<open>Especificaci\u00f3n en Isabelle/HOL\\<close>\n\ntext \\<open>Para especificar el teorema en Isabelle, se comienza definiendo \n  la funci\u00f3n @{term \"suma_impares\"} tal que @{term \"suma_impares n\"} es\n  la suma de los $n$ primeros n\u00fameros impares\\<close>\n\nfun suma_impares :: \"nat \\<Rightarrow> nat\" where\n  \"suma_impares 0 = 0\" \n| \"suma_impares (Suc n) = (2*(Suc n) - 1) + suma_impares n\"\n\ntext \\<open>El enunciado del teorema es el siguiente:\\<close>\n\nlemma \"suma_impares n = n * n\"\noops  \n\ntext \\<open>En la demostraci\u00f3n se usar\u00e1 la t\u00e1ctica @{text induct} que hace\n  uso del esquema de inducci\u00f3n sobre los naturales:\n  \\begin{itemize}\n  \\item[] @{thm[mode=Rule] nat.induct[no_vars]} \n          \\hfill (@{text nat.induct})\n  \\end{itemize}\n\n  Vamos a presentar distintas demostraciones del teorema. La \n  primera es la demostraci\u00f3n autom\u00e1tica.\\<close>\n\nsubsection \\<open>Demostraci\u00f3n autom\u00e1tica\\<close>\n\ntext \\<open>La correspondiente demostraci\u00f3n autom\u00e1tica es\\<close>\n\nlemma \"suma_impares n = n * n\"\n  by (induct n) simp_all\n\nsubsection \\<open>Demostraci\u00f3n estructurada\\<close>\n\ntext \\<open>La demostraci\u00f3n estructurada y detallada del lema anterior es:\\<close>\n\nlemma \"suma_impares n = n * n\"\nproof (induct n)\n  have \"suma_impares 0 = 0\" \n    by (simp only: suma_impares.simps(1))\n  also have \"\\<dots> = 0 * 0\"\n    by (simp only:  mult_0)\n  finally show \"suma_impares 0 = 0 * 0\"\n   by (simp only: mult_0_right)\nnext\n  fix n \n  assume HI: \"suma_impares n = n * n\"\n  have \"suma_impares (Suc n) = (2 * (Suc n) - 1) + suma_impares n\" \n    by (simp only: suma_impares.simps(2))\n  also have \"\\<dots> = (2 * (Suc n) - 1) + n * n\" \n    by (simp only: HI)\n  also have \"\\<dots> = n * n + 2 * n + 1\" \n    by (simp only: mult_Suc_right)\n  also have \"\\<dots> = (Suc n) * (Suc n)\"\n    by (simp only: mult_Suc mult_Suc_right)\n  finally show \"suma_impares (Suc n) = (Suc n) * (Suc n)\" \n   by this\nqed\n\ntext \\<open>En la demostraci\u00f3n anterior se pueden ocultar detalles.\\<close>\n\nlemma \"suma_impares n = n * n\"\nproof (induct n)\n  show \"suma_impares 0 = 0 * 0\" by simp\nnext\n  fix n \n  assume HI: \"suma_impares n = n * n\"\n  have \"suma_impares (Suc n) = (2 * (Suc n) - 1) + suma_impares n\" \n    by simp\n  also have \"\\<dots> = (2 * (Suc n) - 1) + n * n\" \n    using HI by simp\n  also have \"\\<dots> = (Suc n) * (Suc n)\" \n    by simp\n  finally show \"suma_impares (Suc n) = (Suc n) * (Suc n)\" \n    by simp\nqed\n\nsubsection \\<open>Demostraci\u00f3n con patrones\\<close>\n\ntext \\<open>La demostraci\u00f3n anterior se puede simplificar usando patrones.\\<close>\n\nlemma \"suma_impares n = n * n\" (is \"?P n = ?Q n\")\nproof (induct n)\n  show \"?P 0 = ?Q 0\" by simp\nnext\n  fix n \n  assume HI: \"?P n = ?Q n\"\n  have \"?P (Suc n) = (2 * (Suc n) - 1) + suma_impares n\" \n    by simp\n  also have \"\\<dots> = (2 * (Suc n) - 1) + n * n\" using HI by simp\n  also have \"\\<dots> = ?Q (Suc n)\" by simp\n  finally show \"?P (Suc n) = ?Q (Suc n)\" by simp\nqed\n\ntext \\<open>La demostraci\u00f3n usando otro patr\u00f3n es\\<close>\n\nlemma \"suma_impares n = n * n\" (is \"?P n\")\nproof (induct n)\n  show \"?P 0\" by simp\nnext\n  fix n \n  assume \"?P n\"\n  then show \"?P (Suc n)\" by simp\nqed\n\n(*<*) \nend\n(*>*) \n", "meta": {"author": "Carnunfer", "repo": "TFG", "sha": "d9f0989088f76442db615c1820f19fb3fad72541", "save_path": "github-repos/isabelle/Carnunfer-TFG", "path": "github-repos/isabelle/Carnunfer-TFG/TFG-d9f0989088f76442db615c1820f19fb3fad72541/SumaImpares.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624840223699, "lm_q2_score": 0.9073122182277756, "lm_q1q2_score": 0.7101192345019974}}
{"text": "section \"Abstract Interpretation\"\n\ntheory Complete_Lattice\nimports Main\nbegin\n\nlocale Complete_Lattice =\nfixes L :: \"'a::order set\" and Glb :: \"'a set \\<Rightarrow> 'a\"\nassumes Glb_lower: \"A \\<subseteq> L \\<Longrightarrow> a \\<in> A \\<Longrightarrow> Glb A \\<le> a\"\nand Glb_greatest: \"b : L \\<Longrightarrow> \\<forall>a\\<in>A. b \\<le> a \\<Longrightarrow> b \\<le> Glb A\"\nand Glb_in_L: \"A \\<subseteq> L \\<Longrightarrow> Glb A : L\"\nbegin\n\ndefinition lfp :: \"('a \\<Rightarrow> 'a) \\<Rightarrow> 'a\" where\n\"lfp f = Glb {a : L. f a \\<le> a}\"\n\nlemma index_lfp: \"lfp f : L\"\nby(auto simp: lfp_def intro: Glb_in_L)\n\nlemma lfp_lowerbound:\n  \"\\<lbrakk> a : L;  f a \\<le> a \\<rbrakk> \\<Longrightarrow> lfp f \\<le> a\"\nby (auto simp add: lfp_def intro: Glb_lower)\n\nlemma lfp_greatest:\n  \"\\<lbrakk> a : L;  \\<And>u. \\<lbrakk> u : L; f u \\<le> u\\<rbrakk> \\<Longrightarrow> a \\<le> u \\<rbrakk> \\<Longrightarrow> a \\<le> lfp f\"\nby (auto simp add: lfp_def intro: Glb_greatest)\n\n\n\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/IMP/Complete_Lattice.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9073122163480667, "lm_q2_score": 0.7826624738835052, "lm_q1q2_score": 0.710119223831704}}
{"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 \\<open>*<=\\<close> 70)\n  where \"S *<= x = (\\<forall>y\\<in>S. y \\<le> x)\"\n\ndefinition setge :: \"'a::ord \\<Rightarrow> 'a set \\<Rightarrow> bool\"  (infixl \\<open><=*\\<close> 70)\n  where \"x <=* S = (\\<forall>y\\<in>S. x \\<le> y)\"\n\n\nsubsection \\<open>Rules for the Relations \\<open>*<=\\<close> and \\<open><=*\\<close>\\<close>\n\nlemma setleI: \"\\<forall>y\\<in>S. y \\<le> x \\<Longrightarrow> S *<= x\"\n  by (simp add: setle_def)\n\nlemma setleD: \"S *<= x \\<Longrightarrow> y\\<in>S \\<Longrightarrow> y \\<le> x\"\n  by (simp add: setle_def)\n\nlemma setgeI: \"\\<forall>y\\<in>S. x \\<le> y \\<Longrightarrow> x <=* S\"\n  by (simp add: setge_def)\n\nlemma setgeD: \"x <=* S \\<Longrightarrow> y\\<in>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 \\<in> 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>\\<open>leastP\\<close>, \\<^term>\\<open>ub\\<close> and \\<^term>\\<open>lub\\<close>\\<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 \\<in> 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 \\<in> 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 \\<in> 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 \\<in> 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 \\<in> R\"\n  by (simp add: isUb_def)\n\nlemma isUbI: \"S *<= x \\<Longrightarrow> x \\<in> 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 \\<in> 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>\\<open>greatestP\\<close>, \\<^term>\\<open>isLb\\<close> and \\<^term>\\<open>isGlb\\<close>\\<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 \\<in> 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 \\<in> 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 \\<in> 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 \\<in> 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 \\<in> R\"\n  by (simp add: isLb_def)\n\nlemma isLbI: \"x <=* S \\<Longrightarrow> x \\<in> 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 \\<open>range X\\<close> *)\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": "seL4", "repo": "isabelle", "sha": "e1ab32a3bb41728cd19541063283e37919978a4c", "save_path": "github-repos/isabelle/seL4-isabelle", "path": "github-repos/isabelle/seL4-isabelle/isabelle-e1ab32a3bb41728cd19541063283e37919978a4c/src/HOL/Library/Lub_Glb.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737869342623, "lm_q2_score": 0.8840392817460332, "lm_q1q2_score": 0.7100371777186067}}
{"text": "(*  Title:      ZF/Perm.thy\n    Author:     Lawrence C Paulson, Cambridge University Computer Laboratory\n    Copyright   1991  University of Cambridge\n\nThe theory underlying permutation groups\n  -- Composition of relations, the identity relation\n  -- Injections, surjections, bijections\n  -- Lemmas for the Schroeder-Bernstein Theorem\n*)\n\nsection\\<open>Injections, Surjections, Bijections, Composition\\<close>\n\ntheory Perm imports func begin\n\ndefinition\n  (*composition of relations and functions; NOT Suppes's relative product*)\n  comp     :: \"[i,i]\\<Rightarrow>i\"      (infixr \\<open>O\\<close> 60)  where\n    \"r O s \\<equiv> {xz \\<in> domain(s)*range(r) .\n               \\<exists>x y z. xz=\\<langle>x,z\\<rangle> \\<and> \\<langle>x,y\\<rangle>:s \\<and> \\<langle>y,z\\<rangle>:r}\"\n\ndefinition\n  (*the identity function for A*)\n  id    :: \"i\\<Rightarrow>i\"  where\n    \"id(A) \\<equiv> (\\<lambda>x\\<in>A. x)\"\n\ndefinition\n  (*one-to-one functions from A to B*)\n  inj   :: \"[i,i]\\<Rightarrow>i\"  where\n    \"inj(A,B) \\<equiv> { f \\<in> A->B. \\<forall>w\\<in>A. \\<forall>x\\<in>A. f`w=f`x \\<longrightarrow> w=x}\"\n\ndefinition\n  (*onto functions from A to B*)\n  surj  :: \"[i,i]\\<Rightarrow>i\"  where\n    \"surj(A,B) \\<equiv> { f \\<in> A->B . \\<forall>y\\<in>B. \\<exists>x\\<in>A. f`x=y}\"\n\ndefinition\n  (*one-to-one and onto functions*)\n  bij   :: \"[i,i]\\<Rightarrow>i\"  where\n    \"bij(A,B) \\<equiv> inj(A,B) \\<inter> surj(A,B)\"\n\n\nsubsection\\<open>Surjective Function Space\\<close>\n\nlemma surj_is_fun: \"f \\<in> surj(A,B) \\<Longrightarrow> f \\<in> A->B\"\n  unfolding surj_def\napply (erule CollectD1)\ndone\n\nlemma fun_is_surj: \"f \\<in> Pi(A,B) \\<Longrightarrow> f \\<in> surj(A,range(f))\"\n  unfolding surj_def\napply (blast intro: apply_equality range_of_fun domain_type)\ndone\n\nlemma surj_range: \"f \\<in> surj(A,B) \\<Longrightarrow> range(f)=B\"\n  unfolding surj_def\napply (best intro: apply_Pair elim: range_type)\ndone\n\ntext\\<open>A function with a right inverse is a surjection\\<close>\n\nlemma f_imp_surjective:\n    \"\\<lbrakk>f \\<in> A->B;  \\<And>y. y \\<in> B \\<Longrightarrow> d(y): A;  \\<And>y. y \\<in> B \\<Longrightarrow> f`d(y) = y\\<rbrakk>\n     \\<Longrightarrow> f \\<in> surj(A,B)\"\n  by (simp add: surj_def, blast)\n\nlemma lam_surjective:\n    \"\\<lbrakk>\\<And>x. x \\<in> A \\<Longrightarrow> c(x): B;\n        \\<And>y. y \\<in> B \\<Longrightarrow> d(y): A;\n        \\<And>y. y \\<in> B \\<Longrightarrow> c(d(y)) = y\n\\<rbrakk> \\<Longrightarrow> (\\<lambda>x\\<in>A. c(x)) \\<in> surj(A,B)\"\napply (rule_tac d = d in f_imp_surjective)\napply (simp_all add: lam_type)\ndone\n\ntext\\<open>Cantor's theorem revisited\\<close>\nlemma cantor_surj: \"f \\<notin> surj(A,Pow(A))\"\napply (unfold surj_def, safe)\napply (cut_tac cantor)\napply (best del: subsetI)\ndone\n\n\nsubsection\\<open>Injective Function Space\\<close>\n\nlemma inj_is_fun: \"f \\<in> inj(A,B) \\<Longrightarrow> f \\<in> A->B\"\n  unfolding inj_def\napply (erule CollectD1)\ndone\n\ntext\\<open>Good for dealing with sets of pairs, but a bit ugly in use [used in AC]\\<close>\nlemma inj_equality:\n    \"\\<lbrakk>\\<langle>a,b\\<rangle>:f;  \\<langle>c,b\\<rangle>:f;  f \\<in> inj(A,B)\\<rbrakk> \\<Longrightarrow> a=c\"\n  unfolding inj_def\napply (blast dest: Pair_mem_PiD)\ndone\n\nlemma inj_apply_equality: \"\\<lbrakk>f \\<in> inj(A,B);  f`a=f`b;  a \\<in> A;  b \\<in> A\\<rbrakk> \\<Longrightarrow> a=b\"\nby (unfold inj_def, blast)\n\ntext\\<open>A function with a left inverse is an injection\\<close>\n\nlemma f_imp_injective: \"\\<lbrakk>f \\<in> A->B;  \\<forall>x\\<in>A. d(f`x)=x\\<rbrakk> \\<Longrightarrow> f \\<in> inj(A,B)\"\napply (simp (no_asm_simp) add: inj_def)\napply (blast intro: subst_context [THEN box_equals])\ndone\n\nlemma lam_injective:\n    \"\\<lbrakk>\\<And>x. x \\<in> A \\<Longrightarrow> c(x): B;\n        \\<And>x. x \\<in> A \\<Longrightarrow> d(c(x)) = x\\<rbrakk>\n     \\<Longrightarrow> (\\<lambda>x\\<in>A. c(x)) \\<in> inj(A,B)\"\napply (rule_tac d = d in f_imp_injective)\napply (simp_all add: lam_type)\ndone\n\nsubsection\\<open>Bijections\\<close>\n\nlemma bij_is_inj: \"f \\<in> bij(A,B) \\<Longrightarrow> f \\<in> inj(A,B)\"\n  unfolding bij_def\napply (erule IntD1)\ndone\n\nlemma bij_is_surj: \"f \\<in> bij(A,B) \\<Longrightarrow> f \\<in> surj(A,B)\"\n  unfolding bij_def\napply (erule IntD2)\ndone\n\nlemma bij_is_fun: \"f \\<in> bij(A,B) \\<Longrightarrow> f \\<in> A->B\"\n  by (rule bij_is_inj [THEN inj_is_fun])\n\nlemma lam_bijective:\n    \"\\<lbrakk>\\<And>x. x \\<in> A \\<Longrightarrow> c(x): B;\n        \\<And>y. y \\<in> B \\<Longrightarrow> d(y): A;\n        \\<And>x. x \\<in> A \\<Longrightarrow> d(c(x)) = x;\n        \\<And>y. y \\<in> B \\<Longrightarrow> c(d(y)) = y\n\\<rbrakk> \\<Longrightarrow> (\\<lambda>x\\<in>A. c(x)) \\<in> bij(A,B)\"\n  unfolding bij_def\napply (blast intro!: lam_injective lam_surjective)\ndone\n\nlemma RepFun_bijective: \"(\\<forall>y\\<in>x. \\<exists>!y'. f(y') = f(y))\n      \\<Longrightarrow> (\\<lambda>z\\<in>{f(y). y \\<in> x}. THE y. f(y) = z) \\<in> bij({f(y). y \\<in> x}, x)\"\napply (rule_tac d = f in lam_bijective)\napply (auto simp add: the_equality2)\ndone\n\n\nsubsection\\<open>Identity Function\\<close>\n\nlemma idI [intro!]: \"a \\<in> A \\<Longrightarrow> \\<langle>a,a\\<rangle> \\<in> id(A)\"\n  unfolding id_def\napply (erule lamI)\ndone\n\nlemma idE [elim!]: \"\\<lbrakk>p \\<in> id(A);  \\<And>x.\\<lbrakk>x \\<in> A; p=\\<langle>x,x\\<rangle>\\<rbrakk> \\<Longrightarrow> P\\<rbrakk> \\<Longrightarrow>  P\"\nby (simp add: id_def lam_def, blast)\n\nlemma id_type: \"id(A) \\<in> A->A\"\n  unfolding id_def\napply (rule lam_type, assumption)\ndone\n\nlemma id_conv [simp]: \"x \\<in> A \\<Longrightarrow> id(A)`x = x\"\n  unfolding id_def\napply (simp (no_asm_simp))\ndone\n\nlemma id_mono: \"A<=B \\<Longrightarrow> id(A) \\<subseteq> id(B)\"\n  unfolding id_def\napply (erule lam_mono)\ndone\n\nlemma id_subset_inj: \"A<=B \\<Longrightarrow> id(A): inj(A,B)\"\napply (simp add: inj_def id_def)\napply (blast intro: lam_type)\ndone\n\nlemmas id_inj = subset_refl [THEN id_subset_inj]\n\nlemma id_surj: \"id(A): surj(A,A)\"\n  unfolding id_def surj_def\napply (simp (no_asm_simp))\ndone\n\nlemma id_bij: \"id(A): bij(A,A)\"\n  unfolding bij_def\napply (blast intro: id_inj id_surj)\ndone\n\nlemma subset_iff_id: \"A \\<subseteq> B \\<longleftrightarrow> id(A) \\<in> A->B\"\n  unfolding id_def\napply (force intro!: lam_type dest: apply_type)\ndone\n\ntext\\<open>\\<^term>\\<open>id\\<close> as the identity relation\\<close>\nlemma id_iff [simp]: \"\\<langle>x,y\\<rangle> \\<in> id(A) \\<longleftrightarrow> x=y \\<and> y \\<in> A\"\nby auto\n\n\nsubsection\\<open>Converse of a Function\\<close>\n\nlemma inj_converse_fun: \"f \\<in> inj(A,B) \\<Longrightarrow> converse(f) \\<in> range(f)->A\"\n  unfolding inj_def\napply (simp (no_asm_simp) add: Pi_iff function_def)\napply (erule CollectE)\napply (simp (no_asm_simp) add: apply_iff)\napply (blast dest: fun_is_rel)\ndone\n\ntext\\<open>Equations for converse(f)\\<close>\n\ntext\\<open>The premises are equivalent to saying that f is injective...\\<close>\nlemma left_inverse_lemma:\n     \"\\<lbrakk>f \\<in> A->B;  converse(f): C->A;  a \\<in> A\\<rbrakk> \\<Longrightarrow> converse(f)`(f`a) = a\"\nby (blast intro: apply_Pair apply_equality converseI)\n\nlemma left_inverse [simp]: \"\\<lbrakk>f \\<in> inj(A,B);  a \\<in> A\\<rbrakk> \\<Longrightarrow> converse(f)`(f`a) = a\"\nby (blast intro: left_inverse_lemma inj_converse_fun inj_is_fun)\n\nlemma left_inverse_eq:\n     \"\\<lbrakk>f \\<in> inj(A,B); f ` x = y; x \\<in> A\\<rbrakk> \\<Longrightarrow> converse(f) ` y = x\"\nby auto\n\nlemmas left_inverse_bij = bij_is_inj [THEN left_inverse]\n\nlemma right_inverse_lemma:\n     \"\\<lbrakk>f \\<in> A->B;  converse(f): C->A;  b \\<in> C\\<rbrakk> \\<Longrightarrow> f`(converse(f)`b) = b\"\nby (rule apply_Pair [THEN converseD [THEN apply_equality]], auto)\n\n(*Should the premises be f \\<in> surj(A,B), b \\<in> B for symmetry with left_inverse?\n  No: they would not imply that converse(f) was a function! *)\nlemma right_inverse [simp]:\n     \"\\<lbrakk>f \\<in> inj(A,B);  b \\<in> range(f)\\<rbrakk> \\<Longrightarrow> f`(converse(f)`b) = b\"\nby (blast intro: right_inverse_lemma inj_converse_fun inj_is_fun)\n\nlemma right_inverse_bij: \"\\<lbrakk>f \\<in> bij(A,B);  b \\<in> B\\<rbrakk> \\<Longrightarrow> f`(converse(f)`b) = b\"\nby (force simp add: bij_def surj_range)\n\nsubsection\\<open>Converses of Injections, Surjections, Bijections\\<close>\n\nlemma inj_converse_inj: \"f \\<in> inj(A,B) \\<Longrightarrow> converse(f): inj(range(f), A)\"\napply (rule f_imp_injective)\napply (erule inj_converse_fun, clarify)\napply (rule right_inverse)\n apply assumption\napply blast\ndone\n\nlemma inj_converse_surj: \"f \\<in> inj(A,B) \\<Longrightarrow> converse(f): surj(range(f), A)\"\nby (blast intro: f_imp_surjective inj_converse_fun left_inverse inj_is_fun\n                 range_of_fun [THEN apply_type])\n\ntext\\<open>Adding this as an intro! rule seems to cause looping\\<close>\nlemma bij_converse_bij [TC]: \"f \\<in> bij(A,B) \\<Longrightarrow> converse(f): bij(B,A)\"\n  unfolding bij_def\napply (fast elim: surj_range [THEN subst] inj_converse_inj inj_converse_surj)\ndone\n\n\n\nsubsection\\<open>Composition of Two Relations\\<close>\n\ntext\\<open>The inductive definition package could derive these theorems for \\<^term>\\<open>r O s\\<close>\\<close>\n\nlemma compI [intro]: \"\\<lbrakk>\\<langle>a,b\\<rangle>:s; \\<langle>b,c\\<rangle>:r\\<rbrakk> \\<Longrightarrow> \\<langle>a,c\\<rangle> \\<in> r O s\"\nby (unfold comp_def, blast)\n\nlemma compE [elim!]:\n    \"\\<lbrakk>xz \\<in> r O s;\n        \\<And>x y z. \\<lbrakk>xz=\\<langle>x,z\\<rangle>;  \\<langle>x,y\\<rangle>:s;  \\<langle>y,z\\<rangle>:r\\<rbrakk> \\<Longrightarrow> P\\<rbrakk>\n     \\<Longrightarrow> P\"\nby (unfold comp_def, blast)\n\nlemma compEpair:\n    \"\\<lbrakk>\\<langle>a,c\\<rangle> \\<in> r O s;\n        \\<And>y. \\<lbrakk>\\<langle>a,y\\<rangle>:s;  \\<langle>y,c\\<rangle>:r\\<rbrakk> \\<Longrightarrow> P\\<rbrakk>\n     \\<Longrightarrow> P\"\nby (erule compE, simp)\n\nlemma converse_comp: \"converse(R O S) = converse(S) O converse(R)\"\nby blast\n\n\nsubsection\\<open>Domain and Range -- see Suppes, Section 3.1\\<close>\n\ntext\\<open>Boyer et al., Set Theory in First-Order Logic, JAR 2 (1986), 287-327\\<close>\nlemma range_comp: \"range(r O s) \\<subseteq> range(r)\"\nby blast\n\nlemma range_comp_eq: \"domain(r) \\<subseteq> range(s) \\<Longrightarrow> range(r O s) = range(r)\"\nby (rule range_comp [THEN equalityI], blast)\n\nlemma domain_comp: \"domain(r O s) \\<subseteq> domain(s)\"\nby blast\n\nlemma domain_comp_eq: \"range(s) \\<subseteq> domain(r) \\<Longrightarrow> domain(r O s) = domain(s)\"\nby (rule domain_comp [THEN equalityI], blast)\n\nlemma image_comp: \"(r O s)``A = r``(s``A)\"\nby blast\n\nlemma inj_inj_range: \"f \\<in> inj(A,B) \\<Longrightarrow> f \\<in> inj(A,range(f))\"\n  by (auto simp add: inj_def Pi_iff function_def)\n\nlemma inj_bij_range: \"f \\<in> inj(A,B) \\<Longrightarrow> f \\<in> bij(A,range(f))\"\n  by (auto simp add: bij_def intro: inj_inj_range inj_is_fun fun_is_surj)\n\n\nsubsection\\<open>Other Results\\<close>\n\nlemma comp_mono: \"\\<lbrakk>r'<=r; s'<=s\\<rbrakk> \\<Longrightarrow> (r' O s') \\<subseteq> (r O s)\"\nby blast\n\ntext\\<open>composition preserves relations\\<close>\nlemma comp_rel: \"\\<lbrakk>s<=A*B;  r<=B*C\\<rbrakk> \\<Longrightarrow> (r O s) \\<subseteq> A*C\"\nby blast\n\ntext\\<open>associative law for composition\\<close>\nlemma comp_assoc: \"(r O s) O t = r O (s O t)\"\nby blast\n\n(*left identity of composition; provable inclusions are\n        id(A) O r \\<subseteq> r\n  and   \\<lbrakk>r<=A*B; B<=C\\<rbrakk> \\<Longrightarrow> r \\<subseteq> id(C) O r *)\nlemma left_comp_id: \"r<=A*B \\<Longrightarrow> id(B) O r = r\"\nby blast\n\n(*right identity of composition; provable inclusions are\n        r O id(A) \\<subseteq> r\n  and   \\<lbrakk>r<=A*B; A<=C\\<rbrakk> \\<Longrightarrow> r \\<subseteq> r O id(C) *)\nlemma right_comp_id: \"r<=A*B \\<Longrightarrow> r O id(A) = r\"\nby blast\n\n\nsubsection\\<open>Composition Preserves Functions, Injections, and Surjections\\<close>\n\nlemma comp_function: \"\\<lbrakk>function(g);  function(f)\\<rbrakk> \\<Longrightarrow> function(f O g)\"\nby (unfold function_def, blast)\n\ntext\\<open>Don't think the premises can be weakened much\\<close>\nlemma comp_fun: \"\\<lbrakk>g \\<in> A->B;  f \\<in> B->C\\<rbrakk> \\<Longrightarrow> (f O g) \\<in> A->C\"\napply (auto simp add: Pi_def comp_function Pow_iff comp_rel)\napply (subst range_rel_subset [THEN domain_comp_eq], auto)\ndone\n\n(*Thanks to the new definition of \"apply\", the premise f \\<in> B->C is gone!*)\nlemma comp_fun_apply [simp]:\n     \"\\<lbrakk>g \\<in> A->B;  a \\<in> A\\<rbrakk> \\<Longrightarrow> (f O g)`a = f`(g`a)\"\napply (frule apply_Pair, assumption)\napply (simp add: apply_def image_comp)\napply (blast dest: apply_equality)\ndone\n\ntext\\<open>Simplifies compositions of lambda-abstractions\\<close>\nlemma comp_lam:\n    \"\\<lbrakk>\\<And>x. x \\<in> A \\<Longrightarrow> b(x): B\\<rbrakk>\n     \\<Longrightarrow> (\\<lambda>y\\<in>B. c(y)) O (\\<lambda>x\\<in>A. b(x)) = (\\<lambda>x\\<in>A. c(b(x)))\"\napply (subgoal_tac \"(\\<lambda>x\\<in>A. b(x)) \\<in> A -> B\")\n apply (rule fun_extension)\n   apply (blast intro: comp_fun lam_funtype)\n  apply (rule lam_funtype)\n apply simp\napply (simp add: lam_type)\ndone\n\nlemma comp_inj:\n     \"\\<lbrakk>g \\<in> inj(A,B);  f \\<in> inj(B,C)\\<rbrakk> \\<Longrightarrow> (f O g) \\<in> inj(A,C)\"\napply (frule inj_is_fun [of g])\napply (frule inj_is_fun [of f])\napply (rule_tac d = \"\\<lambda>y. converse (g) ` (converse (f) ` y)\" in f_imp_injective)\n apply (blast intro: comp_fun, simp)\ndone\n\nlemma comp_surj:\n    \"\\<lbrakk>g \\<in> surj(A,B);  f \\<in> surj(B,C)\\<rbrakk> \\<Longrightarrow> (f O g) \\<in> surj(A,C)\"\n  unfolding surj_def\napply (blast intro!: comp_fun comp_fun_apply)\ndone\n\nlemma comp_bij:\n    \"\\<lbrakk>g \\<in> bij(A,B);  f \\<in> bij(B,C)\\<rbrakk> \\<Longrightarrow> (f O g) \\<in> bij(A,C)\"\n  unfolding bij_def\napply (blast intro: comp_inj comp_surj)\ndone\n\n\nsubsection\\<open>Dual Properties of \\<^term>\\<open>inj\\<close> and \\<^term>\\<open>surj\\<close>\\<close>\n\ntext\\<open>Useful for proofs from\n    D Pastre.  Automatic theorem proving in set theory.\n    Artificial Intelligence, 10:1--27, 1978.\\<close>\n\nlemma comp_mem_injD1:\n    \"\\<lbrakk>(f O g): inj(A,C);  g \\<in> A->B;  f \\<in> B->C\\<rbrakk> \\<Longrightarrow> g \\<in> inj(A,B)\"\nby (unfold inj_def, force)\n\nlemma comp_mem_injD2:\n    \"\\<lbrakk>(f O g): inj(A,C);  g \\<in> surj(A,B);  f \\<in> B->C\\<rbrakk> \\<Longrightarrow> f \\<in> inj(B,C)\"\napply (unfold inj_def surj_def, safe)\napply (rule_tac x1 = x in bspec [THEN bexE])\napply (erule_tac [3] x1 = w in bspec [THEN bexE], assumption+, safe)\napply (rule_tac t = \"(`) (g) \" in subst_context)\napply (erule asm_rl bspec [THEN bspec, THEN mp])+\napply (simp (no_asm_simp))\ndone\n\nlemma comp_mem_surjD1:\n    \"\\<lbrakk>(f O g): surj(A,C);  g \\<in> A->B;  f \\<in> B->C\\<rbrakk> \\<Longrightarrow> f \\<in> surj(B,C)\"\n  unfolding surj_def\napply (blast intro!: comp_fun_apply [symmetric] apply_funtype)\ndone\n\n\nlemma comp_mem_surjD2:\n    \"\\<lbrakk>(f O g): surj(A,C);  g \\<in> A->B;  f \\<in> inj(B,C)\\<rbrakk> \\<Longrightarrow> g \\<in> surj(A,B)\"\napply (unfold inj_def surj_def, safe)\napply (drule_tac x = \"f`y\" in bspec, auto)\napply (blast intro: apply_funtype)\ndone\n\nsubsubsection\\<open>Inverses of Composition\\<close>\n\ntext\\<open>left inverse of composition; one inclusion is\n        \\<^term>\\<open>f \\<in> A->B \\<Longrightarrow> id(A) \\<subseteq> converse(f) O f\\<close>\\<close>\nlemma left_comp_inverse: \"f \\<in> inj(A,B) \\<Longrightarrow> converse(f) O f = id(A)\"\napply (unfold inj_def, clarify)\napply (rule equalityI)\n apply (auto simp add: apply_iff, blast)\ndone\n\ntext\\<open>right inverse of composition; one inclusion is\n                \\<^term>\\<open>f \\<in> A->B \\<Longrightarrow> f O converse(f) \\<subseteq> id(B)\\<close>\\<close>\nlemma right_comp_inverse:\n    \"f \\<in> surj(A,B) \\<Longrightarrow> f O converse(f) = id(B)\"\napply (simp add: surj_def, clarify)\napply (rule equalityI)\napply (best elim: domain_type range_type dest: apply_equality2)\napply (blast intro: apply_Pair)\ndone\n\n\nsubsubsection\\<open>Proving that a Function is a Bijection\\<close>\n\nlemma comp_eq_id_iff:\n    \"\\<lbrakk>f \\<in> A->B;  g \\<in> B->A\\<rbrakk> \\<Longrightarrow> f O g = id(B) \\<longleftrightarrow> (\\<forall>y\\<in>B. f`(g`y)=y)\"\napply (unfold id_def, safe)\n apply (drule_tac t = \"\\<lambda>h. h`y \" in subst_context)\n apply simp\napply (rule fun_extension)\n  apply (blast intro: comp_fun lam_type)\n apply auto\ndone\n\nlemma fg_imp_bijective:\n    \"\\<lbrakk>f \\<in> A->B;  g \\<in> B->A;  f O g = id(B);  g O f = id(A)\\<rbrakk> \\<Longrightarrow> f \\<in> bij(A,B)\"\n  unfolding bij_def\napply (simp add: comp_eq_id_iff)\napply (blast intro: f_imp_injective f_imp_surjective apply_funtype)\ndone\n\nlemma nilpotent_imp_bijective: \"\\<lbrakk>f \\<in> A->A;  f O f = id(A)\\<rbrakk> \\<Longrightarrow> f \\<in> bij(A,A)\"\nby (blast intro: fg_imp_bijective)\n\nlemma invertible_imp_bijective:\n     \"\\<lbrakk>converse(f): B->A;  f \\<in> A->B\\<rbrakk> \\<Longrightarrow> f \\<in> bij(A,B)\"\nby (simp add: fg_imp_bijective comp_eq_id_iff\n              left_inverse_lemma right_inverse_lemma)\n\nsubsubsection\\<open>Unions of Functions\\<close>\n\ntext\\<open>See similar theorems in func.thy\\<close>\n\ntext\\<open>Theorem by KG, proof by LCP\\<close>\nlemma inj_disjoint_Un:\n     \"\\<lbrakk>f \\<in> inj(A,B);  g \\<in> inj(C,D);  B \\<inter> D = 0\\<rbrakk>\n      \\<Longrightarrow> (\\<lambda>a\\<in>A \\<union> C. if a \\<in> A then f`a else g`a) \\<in> inj(A \\<union> C, B \\<union> D)\"\napply (rule_tac d = \"\\<lambda>z. if z \\<in> B then converse (f) `z else converse (g) `z\"\n       in lam_injective)\napply (auto simp add: inj_is_fun [THEN apply_type])\ndone\n\nlemma surj_disjoint_Un:\n    \"\\<lbrakk>f \\<in> surj(A,B);  g \\<in> surj(C,D);  A \\<inter> C = 0\\<rbrakk>\n     \\<Longrightarrow> (f \\<union> g) \\<in> surj(A \\<union> C, B \\<union> D)\"\napply (simp add: surj_def fun_disjoint_Un)\napply (blast dest!: domain_of_fun\n             intro!: fun_disjoint_apply1 fun_disjoint_apply2)\ndone\n\ntext\\<open>A simple, high-level proof; the version for injections follows from it,\n  using  \\<^term>\\<open>f \\<in> inj(A,B) \\<longleftrightarrow> f \\<in> bij(A,range(f))\\<close>\\<close>\nlemma bij_disjoint_Un:\n     \"\\<lbrakk>f \\<in> bij(A,B);  g \\<in> bij(C,D);  A \\<inter> C = 0;  B \\<inter> D = 0\\<rbrakk>\n      \\<Longrightarrow> (f \\<union> g) \\<in> bij(A \\<union> C, B \\<union> D)\"\napply (rule invertible_imp_bijective)\napply (subst converse_Un)\napply (auto intro: fun_disjoint_Un bij_is_fun bij_converse_bij)\ndone\n\n\nsubsubsection\\<open>Restrictions as Surjections and Bijections\\<close>\n\nlemma surj_image:\n    \"f \\<in> Pi(A,B) \\<Longrightarrow> f \\<in> surj(A, f``A)\"\napply (simp add: surj_def)\napply (blast intro: apply_equality apply_Pair Pi_type)\ndone\n\nlemma surj_image_eq: \"f \\<in> surj(A, B) \\<Longrightarrow> f``A = B\"\n  by (auto simp add: surj_def image_fun) (blast dest: apply_type) \n\nlemma restrict_image [simp]: \"restrict(f,A) `` B = f `` (A \\<inter> B)\"\nby (auto simp add: restrict_def)\n\nlemma restrict_inj:\n    \"\\<lbrakk>f \\<in> inj(A,B);  C<=A\\<rbrakk> \\<Longrightarrow> restrict(f,C): inj(C,B)\"\n  unfolding inj_def\napply (safe elim!: restrict_type2, auto)\ndone\n\nlemma restrict_surj: \"\\<lbrakk>f \\<in> Pi(A,B);  C<=A\\<rbrakk> \\<Longrightarrow> restrict(f,C): surj(C, f``C)\"\napply (insert restrict_type2 [THEN surj_image])\napply (simp add: restrict_image)\ndone\n\nlemma restrict_bij:\n    \"\\<lbrakk>f \\<in> inj(A,B);  C<=A\\<rbrakk> \\<Longrightarrow> restrict(f,C): bij(C, f``C)\"\napply (simp add: inj_def bij_def)\napply (blast intro: restrict_surj surj_is_fun)\ndone\n\n\nsubsubsection\\<open>Lemmas for Ramsey's Theorem\\<close>\n\nlemma inj_weaken_type: \"\\<lbrakk>f \\<in> inj(A,B);  B<=D\\<rbrakk> \\<Longrightarrow> f \\<in> inj(A,D)\"\n  unfolding inj_def\napply (blast intro: fun_weaken_type)\ndone\n\nlemma inj_succ_restrict:\n     \"\\<lbrakk>f \\<in> inj(succ(m), A)\\<rbrakk> \\<Longrightarrow> restrict(f,m) \\<in> inj(m, A-{f`m})\"\napply (rule restrict_bij [THEN bij_is_inj, THEN inj_weaken_type], assumption, blast)\n  unfolding inj_def\napply (fast elim: range_type mem_irrefl dest: apply_equality)\ndone\n\n\nlemma inj_extend:\n    \"\\<lbrakk>f \\<in> inj(A,B);  a\\<notin>A;  b\\<notin>B\\<rbrakk>\n     \\<Longrightarrow> cons(\\<langle>a,b\\<rangle>,f) \\<in> inj(cons(a,A), cons(b,B))\"\n  unfolding inj_def\napply (force intro: apply_type  simp add: fun_extend)\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/Perm.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8519528057272543, "lm_q2_score": 0.8333245994514084, "lm_q1q2_score": 0.7099532305841677}}
{"text": "(*  Title:       ODEs and Dynamical Systems for HS verification\n    Author:      Jonathan Juli\u00e1n Huerta y Munive, 2020\n    Maintainer:  Jonathan Juli\u00e1n Huerta y Munive <jonjulian23@gmail.com>\n*)\n\nsection \\<open> Ordinary Differential Equations \\<close>\n\ntext \\<open>Vector fields @{text \"f::real \\<Rightarrow> 'a \\<Rightarrow> ('a::real_normed_vector)\"} represent systems \nof ordinary differential equations (ODEs). Picard-Lindeloef's theorem guarantees existence \nand uniqueness of local solutions to initial value problems involving Lipschitz continuous \nvector fields. A (local) flow @{text \"\\<phi>::real \\<Rightarrow> 'a \\<Rightarrow> ('a::real_normed_vector)\"} for such \na system is the function that maps initial conditions to their unique solutions. In dynamical \nsystems, the set of all points @{text \"\\<phi> t s::'a\"} for a fixed @{text \"s::'a\"} is the flow's \norbit. If the orbit of each @{text \"s \\<in> I\"} is conatined in @{text I}, then @{text I} is an \ninvariant set of this system. This section formalises these concepts with a focus on hybrid \nsystems (HS) verification.\\<close>\n\ntheory HS_ODEs\n  imports \"HS_Preliminaries\"\nbegin\n\nsubsection \\<open> Initial value problems and orbits \\<close>\n\nnotation image (\"\\<P>\")\n\nlemma image_le_pred[simp]: \"(\\<P> f A \\<subseteq> {s. G s}) = (\\<forall>x\\<in>A. G (f x))\"\n  unfolding image_def by force\n\ndefinition ivp_sols :: \"(real \\<Rightarrow> 'a \\<Rightarrow> ('a::real_normed_vector)) \\<Rightarrow> ('a \\<Rightarrow> real set) \\<Rightarrow> 'a set \\<Rightarrow> \n  real \\<Rightarrow> 'a \\<Rightarrow> (real \\<Rightarrow> 'a) set\" (\"Sols\")\n  where \"Sols f U S t\\<^sub>0 s = {X \\<in> U s \\<rightarrow> S. (D X = (\\<lambda>t. f t (X t)) on U s) \\<and> X t\\<^sub>0 = s \\<and> t\\<^sub>0 \\<in> U s}\"\n\nlemma ivp_solsI: \n  assumes \"D X = (\\<lambda>t. f t (X t)) on U s\" and \"X t\\<^sub>0 = s\" \n      and \"X \\<in> U s \\<rightarrow> S\" and \"t\\<^sub>0 \\<in> U s\"\n    shows \"X \\<in> Sols f U S t\\<^sub>0 s\"\n  using assms unfolding ivp_sols_def by blast\n\nlemma ivp_solsD:\n  assumes \"X \\<in> Sols f U S t\\<^sub>0 s\"\n  shows \"D X = (\\<lambda>t. f t (X t)) on U s\" and \"X t\\<^sub>0 = s\" \n    and \"X \\<in> U s \\<rightarrow> S\" and \"t\\<^sub>0 \\<in> U s\"\n  using assms unfolding ivp_sols_def by auto\n\nlemma in_ivp_sols_subset:\n  \"t\\<^sub>0 \\<in> (U s) \\<Longrightarrow> (U s) \\<subseteq> (T s) \\<Longrightarrow> X \\<in> Sols f T S t\\<^sub>0 s \\<Longrightarrow> X \\<in> Sols f U S t\\<^sub>0 s \"\n  apply(rule ivp_solsI)\n  using ivp_solsD(1,2) has_vderiv_on_subset \n     apply blast+\n  by (drule ivp_solsD(3)) auto\n\nabbreviation \"down U t \\<equiv> {\\<tau> \\<in> U. \\<tau> \\<le> t}\"\n\ndefinition g_orbit :: \"(('a::ord) \\<Rightarrow> 'b) \\<Rightarrow> ('b \\<Rightarrow> bool) \\<Rightarrow> 'a set \\<Rightarrow> 'b set\" (\"\\<gamma>\")\n  where \"\\<gamma> X G U = \\<Union>{\\<P> X (down U t) |t. \\<P> X (down U t) \\<subseteq> {s. G s}}\"\n\nlemma g_orbit_eq: \n  fixes X::\"('a::preorder) \\<Rightarrow> 'b\"\n  shows \"\\<gamma> X G U = {X t |t. t \\<in> U \\<and> (\\<forall>\\<tau>\\<in>down U t. G (X \\<tau>))}\"\n  unfolding g_orbit_def using order_trans by auto blast\n\ndefinition g_orbital :: \"(real \\<Rightarrow> 'a \\<Rightarrow> 'a) \\<Rightarrow> ('a \\<Rightarrow> bool) \\<Rightarrow> ('a \\<Rightarrow> real set) \\<Rightarrow> 'a set \\<Rightarrow> real \\<Rightarrow> \n  ('a::real_normed_vector) \\<Rightarrow> 'a set\" \n  where \"g_orbital f G U S t\\<^sub>0 s = \\<Union>{\\<gamma> X G (U s) |X. X \\<in> ivp_sols f U S t\\<^sub>0 s}\"\n\nlemma g_orbital_eq: \"g_orbital f G U S t\\<^sub>0 s = \n  {X t |t X. t \\<in> U s \\<and> \\<P> X (down (U s) t) \\<subseteq> {s. G s} \\<and> X \\<in> Sols f U S t\\<^sub>0 s }\" \n  unfolding g_orbital_def ivp_sols_def g_orbit_eq by auto\n\nlemma g_orbitalI:\n  assumes \"X \\<in> Sols f U S t\\<^sub>0 s\"\n    and \"t \\<in> U s\" and \"(\\<P> X (down (U s) t) \\<subseteq> {s. G s})\"\n  shows \"X t \\<in> g_orbital f G U S t\\<^sub>0 s\"\n  using assms unfolding g_orbital_eq(1) by auto\n\nlemma g_orbitalD:\n  assumes \"s' \\<in> g_orbital f G U S t\\<^sub>0 s\"\n  obtains X and t where \"X \\<in> Sols f U S t\\<^sub>0 s\"\n  and \"X t = s'\" and \"t \\<in> U s\" and \"(\\<P> X (down (U s) t) \\<subseteq> {s. G s})\"\n  using assms unfolding g_orbital_def g_orbit_eq by auto\n\nlemma \"g_orbital f G U S t\\<^sub>0 s = {X t |t X. X t \\<in> \\<gamma> X G (U s) \\<and> X \\<in> Sols f U S t\\<^sub>0 s}\"\n  unfolding g_orbital_eq g_orbit_eq by auto\n\nlemma \"X \\<in> Sols f U S t\\<^sub>0 s \\<Longrightarrow> \\<gamma> X G (U s) \\<subseteq> g_orbital f G U S t\\<^sub>0 s\"\n  unfolding g_orbital_eq g_orbit_eq by auto\n\nlemma \"g_orbital f G U S t\\<^sub>0 s \\<subseteq> g_orbital f (\\<lambda>s. True) U S t\\<^sub>0 s\"\n  unfolding g_orbital_eq by auto\n\nno_notation g_orbit (\"\\<gamma>\")\n\n\nsubsection \\<open> Differential Invariants \\<close>\n\ndefinition diff_invariant :: \"('a \\<Rightarrow> bool) \\<Rightarrow> (real \\<Rightarrow> ('a::real_normed_vector) \\<Rightarrow> 'a) \\<Rightarrow> \n  ('a \\<Rightarrow> real set) \\<Rightarrow> 'a set \\<Rightarrow> real \\<Rightarrow> ('a \\<Rightarrow> bool) \\<Rightarrow> bool\" \n  where \"diff_invariant I f U S t\\<^sub>0 G \\<equiv> (\\<Union> \\<circ> (\\<P> (g_orbital f G U S t\\<^sub>0))) {s. I s} \\<subseteq> {s. I s}\"\n\nlemma diff_invariant_eq: \"diff_invariant I f U S t\\<^sub>0 G = \n  (\\<forall>s. I s \\<longrightarrow> (\\<forall>X\\<in>Sols f U S t\\<^sub>0 s. (\\<forall>t\\<in>U s.(\\<forall>\\<tau>\\<in>(down (U s) t). G (X \\<tau>)) \\<longrightarrow> I (X t))))\"\n  unfolding diff_invariant_def g_orbital_eq image_le_pred by auto\n\nlemma diff_inv_eq_inv_set:\n  \"diff_invariant I f U S t\\<^sub>0 G = (\\<forall>s. I s \\<longrightarrow> (g_orbital f G U S t\\<^sub>0 s) \\<subseteq> {s. I s})\"\n  unfolding diff_invariant_eq g_orbital_eq image_le_pred by auto\n\nlemma \"diff_invariant I f U S t\\<^sub>0 (\\<lambda>s. True) \\<Longrightarrow> diff_invariant I f U S t\\<^sub>0 G\"\n  unfolding diff_invariant_eq by auto\n\nnamed_theorems diff_invariant_rules \"rules for certifying differential invariants.\"\n\nlemma diff_invariant_eq_rule [diff_invariant_rules]:\n  assumes Uhyp: \"\\<And>s. s \\<in> S \\<Longrightarrow> is_interval (U s)\"\n    and dX: \"\\<And>X. (D X = (\\<lambda>\\<tau>. f \\<tau> (X \\<tau>)) on U(X t\\<^sub>0)) \\<Longrightarrow> (D (\\<lambda>\\<tau>. \\<mu>(X \\<tau>)-\\<nu>(X \\<tau>)) = ((*\\<^sub>R) 0) on U(X t\\<^sub>0))\"\n  shows \"diff_invariant (\\<lambda>s. \\<mu> s = \\<nu> s) f U S t\\<^sub>0 G\"\nproof(simp add: diff_invariant_eq ivp_sols_def, clarsimp)\n  fix X t \n  assume xivp:\"D X = (\\<lambda>\\<tau>. f \\<tau> (X \\<tau>)) on U (X t\\<^sub>0)\" \"\\<mu> (X t\\<^sub>0) = \\<nu> (X t\\<^sub>0)\" \"X \\<in> U (X t\\<^sub>0) \\<rightarrow> S\"\n    and tHyp:\"t \\<in> U (X t\\<^sub>0)\" and t0Hyp: \"t\\<^sub>0 \\<in> U (X t\\<^sub>0)\" \n  hence \"{t\\<^sub>0--t} \\<subseteq> U (X t\\<^sub>0)\"\n    using closed_segment_subset_interval[OF Uhyp t0Hyp tHyp] by blast\n  hence \"D (\\<lambda>\\<tau>. \\<mu> (X \\<tau>) - \\<nu> (X \\<tau>)) = (\\<lambda>\\<tau>. \\<tau> *\\<^sub>R 0) on {t\\<^sub>0--t}\"\n    using has_vderiv_on_subset[OF dX[OF xivp(1)]] by auto\n  then obtain \\<tau> where \"\\<mu> (X t) - \\<nu> (X t) - (\\<mu> (X t\\<^sub>0) - \\<nu> (X t\\<^sub>0)) = (t - t\\<^sub>0) * \\<tau> *\\<^sub>R 0\"\n    using mvt_very_simple_closed_segmentE by blast\n  thus \"\\<mu> (X t) = \\<nu> (X t)\" \n    by (simp add: xivp(2))\nqed\n\nlemma diff_invariant_leq_rule [diff_invariant_rules]:\n  fixes \\<mu>::\"'a::banach \\<Rightarrow> real\"\n  assumes Uhyp: \"\\<And>s. s \\<in> S \\<Longrightarrow> is_interval (U s)\"\n    and Gg: \"\\<And>X. (D X = (\\<lambda>\\<tau>. f \\<tau> (X \\<tau>)) on U(X t\\<^sub>0)) \\<Longrightarrow> (\\<forall>\\<tau>\\<in>U(X t\\<^sub>0). \\<tau> > t\\<^sub>0 \\<longrightarrow> G (X \\<tau>) \\<longrightarrow> \\<mu>' (X \\<tau>) \\<ge> \\<nu>' (X \\<tau>))\"\n    and Gl: \"\\<And>X. (D X = (\\<lambda>\\<tau>. f \\<tau> (X \\<tau>)) on U(X t\\<^sub>0)) \\<Longrightarrow> (\\<forall>\\<tau>\\<in>U(X t\\<^sub>0). \\<tau> < t\\<^sub>0 \\<longrightarrow> \\<mu>' (X \\<tau>) \\<le> \\<nu>' (X \\<tau>))\"\n    and dX: \"\\<And>X. (D X = (\\<lambda>\\<tau>. f \\<tau> (X \\<tau>)) on U(X t\\<^sub>0)) \\<Longrightarrow> D (\\<lambda>\\<tau>. \\<mu>(X \\<tau>)-\\<nu>(X \\<tau>)) = (\\<lambda>\\<tau>. \\<mu>'(X \\<tau>)-\\<nu>'(X \\<tau>)) on U(X t\\<^sub>0)\"\n  shows \"diff_invariant (\\<lambda>s. \\<nu> s \\<le> \\<mu> s) f U S t\\<^sub>0 G\"\nproof(simp_all add: diff_invariant_eq ivp_sols_def, safe)\n  fix X t assume Ghyp: \"\\<forall>\\<tau>. \\<tau> \\<in> U (X t\\<^sub>0) \\<and> \\<tau> \\<le> t \\<longrightarrow> G (X \\<tau>)\"\n  assume xivp: \"D X = (\\<lambda>x. f x (X x)) on U (X t\\<^sub>0)\" \"\\<nu> (X t\\<^sub>0) \\<le> \\<mu> (X t\\<^sub>0)\" \"X \\<in> U (X t\\<^sub>0) \\<rightarrow> S\"\n  assume tHyp: \"t \\<in> U (X t\\<^sub>0)\" and t0Hyp: \"t\\<^sub>0 \\<in> U (X t\\<^sub>0)\" \n  hence obs1: \"{t\\<^sub>0--t} \\<subseteq> U (X t\\<^sub>0)\" \"{t\\<^sub>0<--<t} \\<subseteq> U (X t\\<^sub>0)\"\n    using closed_segment_subset_interval[OF Uhyp t0Hyp tHyp] xivp(3) segment_open_subset_closed\n    by (force, metis PiE \\<open>X t\\<^sub>0 \\<in> S \\<Longrightarrow> {t\\<^sub>0--t} \\<subseteq> U (X t\\<^sub>0)\\<close> dual_order.trans)\n  hence obs2: \"D (\\<lambda>\\<tau>. \\<mu> (X \\<tau>) - \\<nu> (X \\<tau>)) = (\\<lambda>\\<tau>. \\<mu>' (X \\<tau>) - \\<nu>' (X \\<tau>)) on {t\\<^sub>0--t}\"\n    using has_vderiv_on_subset[OF dX[OF xivp(1)]] by auto\n  {assume \"t \\<noteq> t\\<^sub>0\"\n    then obtain r where rHyp: \"r \\<in> {t\\<^sub>0<--<t}\" \n      and \"(\\<mu>(X t)-\\<nu>(X t)) - (\\<mu>(X t\\<^sub>0)-\\<nu>(X t\\<^sub>0)) = (\\<lambda>\\<tau>. \\<tau>*(\\<mu>'(X r)-\\<nu>'(X r))) (t - t\\<^sub>0)\"\n      using mvt_simple_closed_segmentE obs2 by blast\n    hence mvt: \"\\<mu>(X t)-\\<nu>(X t) = (t - t\\<^sub>0)*(\\<mu>'(X r)-\\<nu>'(X r)) + (\\<mu>(X t\\<^sub>0)-\\<nu>(X t\\<^sub>0))\"\n      by force\n    have primed: \"\\<And>\\<tau>. \\<tau> \\<in> U (X t\\<^sub>0) \\<Longrightarrow> \\<tau> > t\\<^sub>0 \\<Longrightarrow> G (X \\<tau>) \\<Longrightarrow> \\<mu>' (X \\<tau>) \\<ge> \\<nu>' (X \\<tau>)\" \n      \"\\<And>\\<tau>. \\<tau> \\<in> U (X t\\<^sub>0) \\<Longrightarrow> \\<tau> < t\\<^sub>0 \\<Longrightarrow> \\<mu>' (X \\<tau>) \\<le> \\<nu>' (X \\<tau>)\"\n      using Gg[OF xivp(1)] Gl[OF xivp(1)] by auto\n    have \"t > t\\<^sub>0 \\<Longrightarrow> r > t\\<^sub>0 \\<and> G (X r)\" \"\\<not> t\\<^sub>0 \\<le> t \\<Longrightarrow> r < t\\<^sub>0\" \"r \\<in> U (X t\\<^sub>0)\"\n      using \\<open>r \\<in> {t\\<^sub>0<--<t}\\<close> obs1 Ghyp\n      unfolding open_segment_eq_real_ivl closed_segment_eq_real_ivl by auto\n    moreover have \"r > t\\<^sub>0 \\<Longrightarrow> G (X r) \\<Longrightarrow> (\\<mu>'(X r)- \\<nu>'(X r)) \\<ge> 0\" \"r < t\\<^sub>0 \\<Longrightarrow> (\\<mu>'(X r)-\\<nu>'(X r)) \\<le> 0\"\n      using primed(1,2)[OF \\<open>r \\<in> U (X t\\<^sub>0)\\<close>] by auto\n    ultimately have \"(t - t\\<^sub>0) * (\\<mu>'(X r)-\\<nu>'(X r)) \\<ge> 0\"\n      by (case_tac \"t \\<ge> t\\<^sub>0\", force, auto simp: split_mult_pos_le)\n    hence \"(t - t\\<^sub>0) * (\\<mu>'(X r)-\\<nu>'(X r)) + (\\<mu>(X t\\<^sub>0)-\\<nu>(X t\\<^sub>0)) \\<ge> 0\"\n      using xivp(2) by auto\n    hence \"\\<nu> (X t) \\<le> \\<mu> (X t)\"\n      using mvt by simp}\n  thus \"\\<nu> (X t) \\<le> \\<mu> (X t)\"\n    using xivp by blast\nqed\n\nlemma diff_invariant_less_rule [diff_invariant_rules]:\n  fixes \\<mu>::\"'a::banach \\<Rightarrow> real\"\n  assumes Uhyp: \"\\<And>s. s \\<in> S \\<Longrightarrow> is_interval (U s)\"\n    and Gg: \"\\<And>X. (D X = (\\<lambda>\\<tau>. f \\<tau> (X \\<tau>)) on U(X t\\<^sub>0)) \\<Longrightarrow> (\\<forall>\\<tau>\\<in>U(X t\\<^sub>0). \\<tau> > t\\<^sub>0 \\<longrightarrow> G (X \\<tau>) \\<longrightarrow> \\<mu>' (X \\<tau>) \\<ge> \\<nu>' (X \\<tau>))\"\n    and Gl: \"\\<And>X. (D X = (\\<lambda>\\<tau>. f \\<tau> (X \\<tau>)) on U(X t\\<^sub>0)) \\<Longrightarrow> (\\<forall>\\<tau>\\<in>U(X t\\<^sub>0). \\<tau> < t\\<^sub>0 \\<longrightarrow> \\<mu>' (X \\<tau>) \\<le> \\<nu>' (X \\<tau>))\"\n    and dX: \"\\<And>X. (D X = (\\<lambda>\\<tau>. f \\<tau> (X \\<tau>)) on U(X t\\<^sub>0)) \\<Longrightarrow> D (\\<lambda>\\<tau>. \\<mu>(X \\<tau>)-\\<nu>(X \\<tau>)) = (\\<lambda>\\<tau>. \\<mu>'(X \\<tau>)-\\<nu>'(X \\<tau>)) on U(X t\\<^sub>0)\"\n  shows \"diff_invariant (\\<lambda>s. \\<nu> s < \\<mu> s) f U S t\\<^sub>0 G\"\nproof(simp_all add: diff_invariant_eq ivp_sols_def, safe)\n  fix X t assume Ghyp: \"\\<forall>\\<tau>. \\<tau> \\<in> U (X t\\<^sub>0) \\<and> \\<tau> \\<le> t \\<longrightarrow> G (X \\<tau>)\"\n  assume xivp: \"D X = (\\<lambda>x. f x (X x)) on U (X t\\<^sub>0)\" \"\\<nu> (X t\\<^sub>0) < \\<mu> (X t\\<^sub>0)\" \"X \\<in> U (X t\\<^sub>0) \\<rightarrow> S\"\n  assume tHyp: \"t \\<in> U (X t\\<^sub>0)\" and t0Hyp: \"t\\<^sub>0 \\<in> U (X t\\<^sub>0)\" \n  hence obs1: \"{t\\<^sub>0--t} \\<subseteq> U (X t\\<^sub>0)\" \"{t\\<^sub>0<--<t} \\<subseteq> U (X t\\<^sub>0)\"\n    using closed_segment_subset_interval[OF Uhyp t0Hyp tHyp] xivp(3) segment_open_subset_closed\n    by (force, metis PiE \\<open>X t\\<^sub>0 \\<in> S \\<Longrightarrow> {t\\<^sub>0--t} \\<subseteq> U (X t\\<^sub>0)\\<close> dual_order.trans)\n  hence obs2: \"D (\\<lambda>\\<tau>. \\<mu> (X \\<tau>) - \\<nu> (X \\<tau>)) = (\\<lambda>\\<tau>. \\<mu>' (X \\<tau>) - \\<nu>' (X \\<tau>)) on {t\\<^sub>0--t}\"\n    using has_vderiv_on_subset[OF dX[OF xivp(1)]] by auto\n  {assume \"t \\<noteq> t\\<^sub>0\"\n    then obtain r where rHyp: \"r \\<in> {t\\<^sub>0<--<t}\" \n      and \"(\\<mu>(X t)-\\<nu>(X t)) - (\\<mu>(X t\\<^sub>0)-\\<nu>(X t\\<^sub>0)) = (\\<lambda>\\<tau>. \\<tau>*(\\<mu>'(X r)-\\<nu>'(X r))) (t - t\\<^sub>0)\"\n      using mvt_simple_closed_segmentE obs2 by blast\n    hence mvt: \"\\<mu>(X t)-\\<nu>(X t) = (t - t\\<^sub>0)*(\\<mu>'(X r)-\\<nu>'(X r)) + (\\<mu>(X t\\<^sub>0)-\\<nu>(X t\\<^sub>0))\"\n      by force\n    have primed: \"\\<And>\\<tau>. \\<tau> \\<in> U (X t\\<^sub>0) \\<Longrightarrow> \\<tau> > t\\<^sub>0 \\<Longrightarrow> G (X \\<tau>) \\<Longrightarrow> \\<mu>' (X \\<tau>) \\<ge> \\<nu>' (X \\<tau>)\" \n      \"\\<And>\\<tau>. \\<tau> \\<in> U (X t\\<^sub>0) \\<Longrightarrow> \\<tau> < t\\<^sub>0 \\<Longrightarrow> \\<mu>' (X \\<tau>) \\<le> \\<nu>' (X \\<tau>)\"\n      using Gg[OF xivp(1)] Gl[OF xivp(1)] by auto\n    have \"t > t\\<^sub>0 \\<Longrightarrow> r > t\\<^sub>0 \\<and> G (X r)\" \"\\<not> t\\<^sub>0 \\<le> t \\<Longrightarrow> r < t\\<^sub>0\" \"r \\<in> U (X t\\<^sub>0)\"\n      using \\<open>r \\<in> {t\\<^sub>0<--<t}\\<close> obs1 Ghyp\n      unfolding open_segment_eq_real_ivl closed_segment_eq_real_ivl by auto\n    moreover have \"r > t\\<^sub>0 \\<Longrightarrow> G (X r) \\<Longrightarrow> (\\<mu>'(X r)- \\<nu>'(X r)) \\<ge> 0\" \"r < t\\<^sub>0 \\<Longrightarrow> (\\<mu>'(X r)-\\<nu>'(X r)) \\<le> 0\"\n      using primed(1,2)[OF \\<open>r \\<in> U (X t\\<^sub>0)\\<close>] by auto\n    ultimately have \"(t - t\\<^sub>0) * (\\<mu>'(X r)-\\<nu>'(X r)) \\<ge> 0\"\n      by (case_tac \"t \\<ge> t\\<^sub>0\", force, auto simp: split_mult_pos_le)\n    hence \"(t - t\\<^sub>0) * (\\<mu>'(X r)-\\<nu>'(X r)) + (\\<mu>(X t\\<^sub>0)-\\<nu>(X t\\<^sub>0)) > 0\"\n      using xivp(2) by auto\n    hence \"\\<nu> (X t) < \\<mu> (X t)\"\n      using mvt by simp}\n  thus \"\\<nu> (X t) < \\<mu> (X t)\"\n    using xivp by blast\nqed\n\nlemma diff_invariant_nleq_rule:\n  fixes \\<mu>::\"'a::banach \\<Rightarrow> real\"\n  shows \"diff_invariant (\\<lambda>s. \\<not> \\<nu> s \\<le> \\<mu> s) f U S t\\<^sub>0 G \\<longleftrightarrow> diff_invariant (\\<lambda>s. \\<nu> s > \\<mu> s) f U S t\\<^sub>0 G\"\n  unfolding diff_invariant_eq apply safe\n  by (clarsimp, erule_tac x=s in allE, simp, erule_tac x=X in ballE, force, force)+\n\nlemma diff_invariant_neq_rule [diff_invariant_rules]:\n  fixes \\<mu>::\"'a::banach \\<Rightarrow> real\"\n  assumes \"diff_invariant (\\<lambda>s. \\<nu> s < \\<mu> s) f U S t\\<^sub>0 G\"\n    and \"diff_invariant (\\<lambda>s. \\<nu> s > \\<mu> s) f U S t\\<^sub>0 G\"\n  shows \"diff_invariant (\\<lambda>s. \\<nu> s \\<noteq> \\<mu> s) f U S t\\<^sub>0 G\"\nproof(unfold diff_invariant_eq, clarsimp)\n  fix s::'a and X::\"real \\<Rightarrow> 'a\" and t::real\n  assume \"\\<nu> s \\<noteq> \\<mu> s\" and Xhyp: \"X \\<in> Sols f U S t\\<^sub>0 s\" \n     and thyp: \"t \\<in> U s\" and Ghyp: \"\\<forall>\\<tau>. \\<tau> \\<in> U s \\<and> \\<tau> \\<le> t \\<longrightarrow> G (X \\<tau>)\"\n  hence \"\\<nu> s < \\<mu> s \\<or> \\<nu> s > \\<mu> s\"\n    by linarith\n  moreover have \"\\<nu> s < \\<mu> s \\<Longrightarrow> \\<nu> (X t) < \\<mu> (X t)\"\n    using assms(1) Xhyp thyp Ghyp unfolding diff_invariant_eq by auto\n  moreover have \"\\<nu> s > \\<mu> s \\<Longrightarrow> \\<nu> (X t) > \\<mu> (X t)\"\n    using assms(2) Xhyp thyp Ghyp unfolding diff_invariant_eq by auto\n  ultimately show \"\\<nu> (X t) = \\<mu> (X t) \\<Longrightarrow> False\"\n    by auto\nqed\n\nlemma diff_invariant_neq_rule_converse:\n  fixes \\<mu>::\"'a::banach \\<Rightarrow> real\"\n  assumes Uhyp: \"\\<And>s. s \\<in> S \\<Longrightarrow> is_interval (U s)\" \"\\<And>s t. s \\<in> S \\<Longrightarrow> t \\<in> U s \\<Longrightarrow> t\\<^sub>0 \\<le> t\"\n    and conts: \"\\<And>X. (D X = (\\<lambda>\\<tau>. f \\<tau> (X \\<tau>)) on U(X t\\<^sub>0)) \\<Longrightarrow> continuous_on (\\<P> X (U (X t\\<^sub>0))) \\<nu>\"\n      \"\\<And>X. (D X = (\\<lambda>\\<tau>. f \\<tau> (X \\<tau>)) on U(X t\\<^sub>0)) \\<Longrightarrow> continuous_on (\\<P> X (U (X t\\<^sub>0))) \\<mu>\"\n    and dI:\"diff_invariant (\\<lambda>s. \\<nu> s \\<noteq> \\<mu> s) f U S t\\<^sub>0 G\"\n  shows \"diff_invariant (\\<lambda>s. \\<nu> s < \\<mu> s) f U S t\\<^sub>0 G\"\nproof(unfold diff_invariant_eq ivp_sols_def, clarsimp)\n  fix X t assume Ghyp: \"\\<forall>\\<tau>. \\<tau> \\<in> U (X t\\<^sub>0) \\<and> \\<tau> \\<le> t \\<longrightarrow> G (X \\<tau>)\"\n  assume xivp: \"D X = (\\<lambda>x. f x (X x)) on U (X t\\<^sub>0)\" \"\\<nu> (X t\\<^sub>0) < \\<mu> (X t\\<^sub>0)\" \"X \\<in> U (X t\\<^sub>0) \\<rightarrow> S\"\n  assume tHyp: \"t \\<in> U (X t\\<^sub>0)\" and t0Hyp: \"t\\<^sub>0 \\<in> U (X t\\<^sub>0)\"\n  hence \"t\\<^sub>0 \\<le> t\" and \"\\<mu> (X t) \\<noteq> \\<nu> (X t)\"\n    using xivp(3) Uhyp(2) apply force\n    using dI tHyp xivp(2) Ghyp ivp_solsI[of X f U \"X t\\<^sub>0\", OF xivp(1) _ xivp(3) t0Hyp]\n    unfolding diff_invariant_eq by force\n  moreover\n  {assume ineq2:\"\\<nu> (X t) > \\<mu> (X t)\"\n    note continuous_on_compose[OF vderiv_on_continuous_on[OF xivp(1)]]\n    hence \"continuous_on (U (X t\\<^sub>0)) (\\<nu> \\<circ> X)\" and \"continuous_on (U (X t\\<^sub>0)) (\\<mu> \\<circ> X)\"\n      using xivp(1) conts by blast+\n    also have \"{t\\<^sub>0--t} \\<subseteq> U (X t\\<^sub>0)\"\n      using closed_segment_subset_interval[OF Uhyp(1) t0Hyp tHyp] xivp(3) t0Hyp by auto\n    ultimately have \"continuous_on {t\\<^sub>0--t} (\\<lambda>\\<tau>. \\<nu> (X \\<tau>))\" \n      and \"continuous_on {t\\<^sub>0--t} (\\<lambda>\\<tau>. \\<mu> (X \\<tau>))\"\n      using continuous_on_subset by auto\n    then obtain \\<tau> where \"\\<tau> \\<in> {t\\<^sub>0--t}\" \"\\<mu> (X \\<tau>) = \\<nu> (X \\<tau>)\"\n      using IVT_two_functions_real_ivl[OF _ _ xivp(2) ineq2] by force\n    hence \"\\<forall>r\\<in>down (U (X t\\<^sub>0)) \\<tau>. G (X r)\" and \"\\<tau> \\<in> U (X t\\<^sub>0)\"\n      using Ghyp \\<open>\\<tau> \\<in> {t\\<^sub>0--t}\\<close> \\<open>t\\<^sub>0 \\<le> t\\<close> \\<open>{t\\<^sub>0--t} \\<subseteq> U (X t\\<^sub>0)\\<close> \n      by (auto simp: closed_segment_eq_real_ivl)\n    hence \"\\<mu> (X \\<tau>) \\<noteq> \\<nu> (X \\<tau>)\"\n      using dI tHyp xivp(2) ivp_solsI[of X f U \"X t\\<^sub>0\", OF xivp(1) _ xivp(3) t0Hyp]\n      unfolding diff_invariant_eq by force\n    hence \"False\"\n      using \\<open>\\<mu> (X \\<tau>) = \\<nu> (X \\<tau>)\\<close> by blast}\n  ultimately show \"\\<nu> (X t) < \\<mu> (X t)\"\n    by fastforce\nqed\n\nlemma diff_invariant_conj_rule [diff_invariant_rules]:\n  assumes \"diff_invariant I\\<^sub>1 f U S t\\<^sub>0 G\"\n    and \"diff_invariant I\\<^sub>2 f U S t\\<^sub>0 G\"\n  shows \"diff_invariant (\\<lambda>s. I\\<^sub>1 s \\<and> I\\<^sub>2 s) f U S t\\<^sub>0 G\"\n  using assms unfolding diff_invariant_def by auto\n\nlemma diff_invariant_disj_rule [diff_invariant_rules]:\n  assumes \"diff_invariant I\\<^sub>1 f U S t\\<^sub>0 G\"\n    and \"diff_invariant I\\<^sub>2 f U S t\\<^sub>0 G\"\n  shows \"diff_invariant (\\<lambda>s. I\\<^sub>1 s \\<or> I\\<^sub>2 s) f U S t\\<^sub>0 G\"\n  using assms unfolding diff_invariant_def by auto\n\nsubsection \\<open> Picard-Lindeloef \\<close>\n\ntext\\<open> A locale with the assumptions of Picard-Lindeloef's theorem. It extends \n@{term \"ll_on_open_it\"} by providing an initial time @{term \"t\\<^sub>0 \\<in> T\"}.\\<close>\n\nlocale picard_lindeloef =\n  fixes f::\"real \\<Rightarrow> ('a::{heine_borel,banach}) \\<Rightarrow> 'a\" and T::\"real set\" and S::\"'a set\" and t\\<^sub>0::real\n  assumes open_domain: \"open T\" \"open S\"\n    and interval_time: \"is_interval T\"\n    and init_time: \"t\\<^sub>0 \\<in> T\"\n    and cont_vec_field: \"\\<forall>s \\<in> S. continuous_on T (\\<lambda>t. f t s)\"\n    and lipschitz_vec_field: \"local_lipschitz T S f\"\nbegin\n\nsublocale ll_on_open_it T f S t\\<^sub>0\n  by (unfold_locales) (auto simp: cont_vec_field lipschitz_vec_field interval_time open_domain) \n\nlemma ll_on_open: \"ll_on_open T f S\"\n  using local.general.ll_on_open_axioms .\n\nlemmas subintervalI = closed_segment_subset_domain\n   and init_time_ex_ivl = existence_ivl_initial_time[OF init_time]\n   and flow_at_init[simp] = general.flow_initial_time[OF init_time]\n                               \nabbreviation \"ex_ivl s \\<equiv> existence_ivl t\\<^sub>0 s\"\n\nlemma flow_has_vderiv_on_ex_ivl:\n  assumes \"s \\<in> S\"\n  shows \"D flow t\\<^sub>0 s = (\\<lambda>t. f t (flow t\\<^sub>0 s t)) on ex_ivl s\"\n  using flow_usolves_ode[OF init_time \\<open>s \\<in> S\\<close>] \n  unfolding usolves_ode_from_def solves_ode_def by blast\n\nlemma flow_funcset_ex_ivl:\n  assumes \"s \\<in> S\"\n  shows \"flow t\\<^sub>0 s \\<in> ex_ivl s \\<rightarrow> S\"\n  using flow_usolves_ode[OF init_time \\<open>s \\<in> S\\<close>] \n  unfolding usolves_ode_from_def solves_ode_def by blast\n\nlemma flow_in_ivp_sols_ex_ivl:\n  assumes \"s \\<in> S\"\n  shows \"flow t\\<^sub>0 s \\<in> Sols f (\\<lambda>s. ex_ivl s) S t\\<^sub>0 s\"\n  using flow_has_vderiv_on_ex_ivl[OF assms] apply(rule ivp_solsI)\n    apply(simp_all add: init_time assms)\n  by (rule flow_funcset_ex_ivl[OF assms])\n\nlemma csols_eq: \"csols t\\<^sub>0 s = {(x, t). t \\<in> T \\<and>  x \\<in> Sols f (\\<lambda>s. {t\\<^sub>0--t}) S t\\<^sub>0 s}\"\n  unfolding ivp_sols_def csols_def solves_ode_def \n  using closed_segment_subset_domain init_time by auto\n\nlemma subset_ex_ivlI:\n  \"Y\\<^sub>1 \\<in> Sols f (\\<lambda>s. T) S t\\<^sub>0 s \\<Longrightarrow> {t\\<^sub>0--t} \\<subseteq> T \\<Longrightarrow> A \\<subseteq> {t\\<^sub>0--t} \\<Longrightarrow> A \\<subseteq> ex_ivl s\"\n  apply(clarsimp simp: existence_ivl_def)\n  apply(subgoal_tac \"t\\<^sub>0 \\<in> T\", clarsimp simp: csols_eq)\n   apply(rule_tac x=Y\\<^sub>1 in exI, rule_tac x=t in exI, safe, force)\n  by (rule in_ivp_sols_subset[where T=\"\\<lambda>s. T\"], auto)\n\nlemma unique_solution: \\<comment> \\<open> proved for a subset of T for general applications \\<close>\n  assumes \"s \\<in> S\" and \"t\\<^sub>0 \\<in> U\" and \"t \\<in> U\" \n    and \"is_interval U\" and \"U \\<subseteq> ex_ivl s\" \n    and xivp: \"D Y\\<^sub>1 = (\\<lambda>t. f t (Y\\<^sub>1 t)) on U\" \"Y\\<^sub>1 t\\<^sub>0 = s\" \"Y\\<^sub>1 \\<in> U \\<rightarrow> S\"\n    and yivp: \"D Y\\<^sub>2 = (\\<lambda>t. f t (Y\\<^sub>2 t)) on U\" \"Y\\<^sub>2 t\\<^sub>0 = s\" \"Y\\<^sub>2 \\<in> U \\<rightarrow> S\"\n  shows \"Y\\<^sub>1 t = Y\\<^sub>2 t\"\nproof-\n  have \"t\\<^sub>0 \\<in> T\"\n    using assms existence_ivl_subset by auto\n  have key: \"(flow t\\<^sub>0 s usolves_ode f from t\\<^sub>0) (ex_ivl s) S\"\n    using flow_usolves_ode[OF \\<open>t\\<^sub>0 \\<in> T\\<close> \\<open>s \\<in> S\\<close>] .\n  hence \"\\<forall>t\\<in>U. Y\\<^sub>1 t = flow t\\<^sub>0 s t\"\n    unfolding usolves_ode_from_def solves_ode_def apply safe\n    by (erule_tac x=Y\\<^sub>1 in allE, erule_tac x=U in allE, auto simp: assms)\n  also have \"\\<forall>t\\<in>U. Y\\<^sub>2 t = flow t\\<^sub>0 s t\"\n    using key unfolding usolves_ode_from_def solves_ode_def apply safe\n    by (erule_tac x=Y\\<^sub>2 in allE, erule_tac x=U in allE, auto simp: assms)\n  ultimately show \"Y\\<^sub>1 t = Y\\<^sub>2 t\"\n    using assms by auto\nqed\n\ntext \\<open>Applications of lemma @{text \"unique_solution\"}: \\<close>\n\nlemma unique_solution_closed_ivl:\n  assumes xivp: \"D X = (\\<lambda>t. f t (X t)) on {t\\<^sub>0--t}\" \"X t\\<^sub>0 = s\" \"X \\<in> {t\\<^sub>0--t} \\<rightarrow> S\" and \"t \\<in> T\"\n    and yivp: \"D Y = (\\<lambda>t. f t (Y t)) on {t\\<^sub>0--t}\" \"Y t\\<^sub>0 = s\" \"Y \\<in> {t\\<^sub>0--t} \\<rightarrow> S\" and \"s \\<in> S\" \n  shows \"X t = Y t\"\n  apply(rule unique_solution[OF \\<open>s \\<in> S\\<close>, of \"{t\\<^sub>0--t}\"], simp_all add: assms)\n  apply(unfold existence_ivl_def csols_eq ivp_sols_def, clarsimp)\n  using xivp \\<open>t \\<in> T\\<close> by blast\n\nlemma solution_eq_flow:\n  assumes xivp: \"D X = (\\<lambda>t. f t (X t)) on ex_ivl s\" \"X t\\<^sub>0 = s\" \"X \\<in> ex_ivl s \\<rightarrow> S\" \n    and \"t \\<in> ex_ivl s\" and \"s \\<in> S\" \n  shows \"X t = flow t\\<^sub>0 s t\"\n  apply(rule unique_solution[OF \\<open>s \\<in> S\\<close> init_time_ex_ivl \\<open>t \\<in> ex_ivl s\\<close>])\n  using flow_has_vderiv_on_ex_ivl flow_funcset_ex_ivl \\<open>s \\<in> S\\<close> by (auto simp: assms)\n\nlemma ivp_unique_solution:\n  assumes \"s \\<in> S\" and ivl: \"is_interval (U s)\" and \"U s \\<subseteq> T\" and \"t \\<in> U s\" \n    and ivp1: \"Y\\<^sub>1 \\<in> Sols f U S t\\<^sub>0 s\" and ivp2: \"Y\\<^sub>2 \\<in> Sols f U S t\\<^sub>0 s\"\n  shows \"Y\\<^sub>1 t = Y\\<^sub>2 t\"\nproof(rule unique_solution[OF \\<open>s \\<in> S\\<close>, of \"{t\\<^sub>0--t}\"], simp_all)\n  have \"t\\<^sub>0 \\<in> U s\"\n    using ivp_solsD[OF ivp1] by auto\n  hence obs0: \"{t\\<^sub>0--t} \\<subseteq> U s\"\n    using closed_segment_subset_interval[OF ivl] \\<open>t \\<in> U s\\<close> by blast\n  moreover have obs1: \"Y\\<^sub>1 \\<in> Sols f (\\<lambda>s. {t\\<^sub>0--t}) S t\\<^sub>0 s\"\n    by (rule in_ivp_sols_subset[OF _ calculation(1) ivp1], simp)\n  moreover have obs2: \"Y\\<^sub>2 \\<in> Sols f (\\<lambda>s. {t\\<^sub>0--t}) S t\\<^sub>0 s\"\n    by (rule in_ivp_sols_subset[OF _ calculation(1) ivp2], simp)\n  ultimately show \"{t\\<^sub>0--t} \\<subseteq> ex_ivl s\"\n    apply(unfold existence_ivl_def csols_eq, clarsimp)\n    apply(rule_tac x=Y\\<^sub>1 in exI, rule_tac x=t in exI)\n    using \\<open>t \\<in> U s\\<close> and \\<open>U s \\<subseteq> T\\<close> by force\n  show \"D Y\\<^sub>1 = (\\<lambda>t. f t (Y\\<^sub>1 t)) on {t\\<^sub>0--t}\"\n    by (rule ivp_solsD[OF in_ivp_sols_subset[OF _ _ ivp1]], simp_all add: obs0)\n  show \"D Y\\<^sub>2 = (\\<lambda>t. f t (Y\\<^sub>2 t)) on {t\\<^sub>0--t}\"\n    by (rule ivp_solsD[OF in_ivp_sols_subset[OF _ _ ivp2]], simp_all add: obs0)\n  show \"Y\\<^sub>1 t\\<^sub>0 = s\" and \"Y\\<^sub>2 t\\<^sub>0 = s\"\n    using ivp_solsD[OF ivp1] ivp_solsD[OF ivp2] by auto\n  show \"Y\\<^sub>1 \\<in> {t\\<^sub>0--t} \\<rightarrow> S\" and \"Y\\<^sub>2 \\<in> {t\\<^sub>0--t} \\<rightarrow> S\"\n    using ivp_solsD[OF obs1] ivp_solsD[OF obs2] by auto\nqed\n\nlemma g_orbital_orbit:\n  assumes \"s \\<in> S\" and ivl: \"is_interval (U s)\" and \"U s \\<subseteq> T\"\n    and ivp: \"Y \\<in> Sols f U S t\\<^sub>0 s\"\n  shows \"g_orbital f G U S t\\<^sub>0 s = g_orbit Y G (U s)\"\nproof-\n  have eq1: \"\\<forall>Z \\<in> Sols f U S t\\<^sub>0 s. \\<forall>t\\<in>U s. Z t = Y t\"\n    by (clarsimp, rule ivp_unique_solution[OF assms(1,2,3) _ _ ivp], auto)\n  have \"g_orbital f G U S t\\<^sub>0 s \\<subseteq> g_orbit (\\<lambda>t. Y t) G (U s)\"\n  proof\n    fix x assume \"x \\<in> g_orbital f G U S t\\<^sub>0 s\"\n    then obtain Z and t \n      where z_def: \"x = Z t \\<and> t \\<in> U s \\<and> (\\<forall>\\<tau>\\<in>down (U s) t. G (Z \\<tau>)) \\<and> Z \\<in> Sols f U S t\\<^sub>0 s\"\n      unfolding g_orbital_eq by auto\n    hence \"{t\\<^sub>0--t} \\<subseteq> U s\"\n      using closed_segment_subset_interval[OF ivl ivp_solsD(4)[OF ivp]] by blast\n    hence \"\\<forall>\\<tau>\\<in>{t\\<^sub>0--t}. Z \\<tau> = Y \\<tau>\"\n      using z_def apply clarsimp\n      by (rule ivp_unique_solution[OF assms(1,2,3) _ _ ivp], auto)\n    thus \"x \\<in> g_orbit Y G (U s)\"\n      using z_def eq1 unfolding g_orbit_eq by simp metis\n  qed\n  moreover have \"g_orbit Y G (U s) \\<subseteq> g_orbital f G U S t\\<^sub>0 s\"\n    apply(unfold g_orbital_eq g_orbit_eq ivp_sols_def, clarsimp)\n    apply(rule_tac x=t in exI, rule_tac x=Y in exI)\n    using ivp_solsD[OF ivp] by auto\n  ultimately show ?thesis\n    by blast\nqed\n\nend\n\nlemma local_lipschitz_add: \n  fixes f1 f2 :: \"real \\<Rightarrow> 'a::banach \\<Rightarrow> 'a\"\n  assumes \"local_lipschitz T S f1\"\n      and \"local_lipschitz T S f2\" \n    shows \"local_lipschitz T S (\\<lambda>t s. f1 t s + f2 t s)\"\nproof(unfold local_lipschitz_def, clarsimp)\n  fix s and t assume \"s \\<in> S\" and \"t \\<in> T\"\n  obtain \\<epsilon>\\<^sub>1 L1 where \"\\<epsilon>\\<^sub>1 > 0\" and L1: \"\\<And>\\<tau>. \\<tau>\\<in>cball t \\<epsilon>\\<^sub>1 \\<inter> T \\<Longrightarrow> L1-lipschitz_on (cball s \\<epsilon>\\<^sub>1 \\<inter> S) (f1 \\<tau>)\"\n    using local_lipschitzE[OF assms(1) \\<open>t \\<in> T\\<close> \\<open>s \\<in> S\\<close>] by blast\n  obtain \\<epsilon>\\<^sub>2 L2 where \"\\<epsilon>\\<^sub>2 > 0\" and L2: \"\\<And>\\<tau>. \\<tau>\\<in>cball t \\<epsilon>\\<^sub>2 \\<inter> T \\<Longrightarrow> L2-lipschitz_on (cball s \\<epsilon>\\<^sub>2 \\<inter> S) (f2 \\<tau>)\"\n    using local_lipschitzE[OF assms(2) \\<open>t \\<in> T\\<close> \\<open>s \\<in> S\\<close>] by blast\n  have ballH: \"cball s (min \\<epsilon>\\<^sub>1 \\<epsilon>\\<^sub>2) \\<inter> S \\<subseteq> cball s \\<epsilon>\\<^sub>1 \\<inter> S\" \"cball s (min \\<epsilon>\\<^sub>1 \\<epsilon>\\<^sub>2) \\<inter> S \\<subseteq> cball s \\<epsilon>\\<^sub>2 \\<inter> S\"\n    by auto\n  have obs1: \"\\<forall>\\<tau>\\<in>cball t \\<epsilon>\\<^sub>1 \\<inter> T. L1-lipschitz_on (cball s (min \\<epsilon>\\<^sub>1 \\<epsilon>\\<^sub>2) \\<inter> S) (f1 \\<tau>)\"\n    using lipschitz_on_subset[OF L1 ballH(1)] by blast\n  also have obs2: \"\\<forall>\\<tau>\\<in>cball t \\<epsilon>\\<^sub>2 \\<inter> T. L2-lipschitz_on (cball s (min \\<epsilon>\\<^sub>1 \\<epsilon>\\<^sub>2) \\<inter> S) (f2 \\<tau>)\"\n    using lipschitz_on_subset[OF L2 ballH(2)] by blast\n  ultimately have \"\\<forall>\\<tau>\\<in>cball t (min \\<epsilon>\\<^sub>1 \\<epsilon>\\<^sub>2) \\<inter> T. \n    (L1 + L2)-lipschitz_on (cball s (min \\<epsilon>\\<^sub>1 \\<epsilon>\\<^sub>2) \\<inter> S) (\\<lambda>s. f1 \\<tau> s + f2 \\<tau> s)\"\n    using lipschitz_on_add by fastforce\n  thus \"\\<exists>u>0. \\<exists>L. \\<forall>t\\<in>cball t u \\<inter> T. L-lipschitz_on (cball s u \\<inter> S) (\\<lambda>s. f1 t s + f2 t s)\"\n    apply(rule_tac x=\"min \\<epsilon>\\<^sub>1 \\<epsilon>\\<^sub>2\" in exI)\n    using \\<open>\\<epsilon>\\<^sub>1 > 0\\<close> \\<open>\\<epsilon>\\<^sub>2 > 0\\<close> by force\nqed\n\nlemma picard_lindeloef_add: \"picard_lindeloef f1 T S t\\<^sub>0 \\<Longrightarrow> picard_lindeloef f2 T S t\\<^sub>0 \\<Longrightarrow> \n  picard_lindeloef (\\<lambda>t s. f1 t s + f2 t s) T S t\\<^sub>0\"\n  unfolding picard_lindeloef_def apply(clarsimp, rule conjI)\n  using continuous_on_add apply fastforce\n  using local_lipschitz_add by blast\n\nlemma picard_lindeloef_constant: \"picard_lindeloef (\\<lambda>t s. c) UNIV UNIV t\\<^sub>0\"\n  apply(unfold_locales, simp_all add: local_lipschitz_def lipschitz_on_def, clarsimp)\n  by (rule_tac x=1 in exI, clarsimp, rule_tac x=\"1/2\" in exI, simp)\n\n\nsubsection \\<open> Flows for ODEs \\<close>\n\ntext\\<open> A locale designed for verification of hybrid systems. The user can select the interval \nof existence and the defining flow equation via the variables @{term \"T\"} and @{term \"\\<phi>\"}.\\<close>\n\nlocale local_flow = picard_lindeloef \"(\\<lambda> t. f)\" T S 0 \n  for f::\"'a::{heine_borel,banach} \\<Rightarrow> 'a\" and T S L +\n  fixes \\<phi> :: \"real \\<Rightarrow> 'a \\<Rightarrow> 'a\"\n  assumes ivp:\n    \"\\<And> t s. t \\<in> T \\<Longrightarrow> s \\<in> S \\<Longrightarrow> D (\\<lambda>t. \\<phi> t s) = (\\<lambda>t. f (\\<phi> t s)) on {0--t}\"\n    \"\\<And> s. s \\<in> S \\<Longrightarrow> \\<phi> 0 s = s\"\n    \"\\<And> t s. t \\<in> T \\<Longrightarrow> s \\<in> S \\<Longrightarrow> (\\<lambda>t. \\<phi> t s) \\<in> {0--t} \\<rightarrow> S\"\nbegin\n\nlemma in_ivp_sols_ivl: \n  assumes \"t \\<in> T\" \"s \\<in> S\"\n  shows \"(\\<lambda>t. \\<phi> t s) \\<in> Sols (\\<lambda>t. f) (\\<lambda>s. {0--t}) S 0 s\"\n  apply(rule ivp_solsI)\n  using ivp assms by auto\n\nlemma eq_solution_ivl:\n  assumes xivp: \"D X = (\\<lambda>t. f (X t)) on {0--t}\" \"X 0 = s\" \"X \\<in> {0--t} \\<rightarrow> S\" \n    and indom: \"t \\<in> T\" \"s \\<in> S\"\n  shows \"X t = \\<phi> t s\"\n  apply(rule unique_solution_closed_ivl[OF xivp \\<open>t \\<in> T\\<close>])\n  using \\<open>s \\<in> S\\<close> ivp indom by auto\n\nlemma ex_ivl_eq:\n  assumes \"s \\<in> S\"\n  shows \"ex_ivl s = T\"\n  using existence_ivl_subset[of s] apply safe\n  unfolding existence_ivl_def csols_eq\n  using in_ivp_sols_ivl[OF _ assms] by blast\n\nlemma has_derivative_on_open1: \n  assumes  \"t > 0\" \"t \\<in> T\" \"s \\<in> S\"\n  obtains B where \"t \\<in> B\" and \"open B\" and \"B \\<subseteq> T\"\n    and \"D (\\<lambda>\\<tau>. \\<phi> \\<tau> s) \\<mapsto> (\\<lambda>\\<tau>. \\<tau> *\\<^sub>R f (\\<phi> t s)) at t within B\" \nproof-\n  obtain r::real where rHyp: \"r > 0\" \"ball t r \\<subseteq> T\"\n    using open_contains_ball_eq open_domain(1) \\<open>t \\<in> T\\<close> by blast\n  moreover have \"t + r/2 > 0\"\n    using \\<open>r > 0\\<close> \\<open>t > 0\\<close> by auto\n  moreover have \"{0--t} \\<subseteq> T\" \n    using subintervalI[OF init_time \\<open>t \\<in> T\\<close>] .\n  ultimately have subs: \"{0<--<t + r/2} \\<subseteq> T\"\n    unfolding abs_le_eq abs_le_eq real_ivl_eqs[OF \\<open>t > 0\\<close>] real_ivl_eqs[OF \\<open>t + r/2 > 0\\<close>] \n    by clarify (case_tac \"t < x\", simp_all add: cball_def ball_def dist_norm subset_eq field_simps)\n  have \"t + r/2 \\<in> T\"\n    using rHyp unfolding real_ivl_eqs[OF rHyp(1)] by (simp add: subset_eq)\n  hence \"{0--t + r/2} \\<subseteq> T\"\n    using subintervalI[OF init_time] by blast\n  hence \"(D (\\<lambda>t. \\<phi> t s) = (\\<lambda>t. f (\\<phi> t s)) on {0--(t + r/2)})\"\n    using ivp(1)[OF _ \\<open>s \\<in> S\\<close>] by auto\n  hence vderiv: \"(D (\\<lambda>t. \\<phi> t s) = (\\<lambda>t. f (\\<phi> t s)) on {0<--<t + r/2})\"\n    apply(rule has_vderiv_on_subset)\n    unfolding real_ivl_eqs[OF \\<open>t + r/2 > 0\\<close>] by auto\n  have \"t \\<in> {0<--<t + r/2}\"\n    unfolding real_ivl_eqs[OF \\<open>t + r/2 > 0\\<close>] using rHyp \\<open>t > 0\\<close> by simp\n  moreover have \"D (\\<lambda>\\<tau>. \\<phi> \\<tau> s) \\<mapsto> (\\<lambda>\\<tau>. \\<tau> *\\<^sub>R f (\\<phi> t s)) (at t within {0<--<t + r/2})\"\n    using vderiv calculation unfolding has_vderiv_on_def has_vector_derivative_def by blast\n  moreover have \"open {0<--<t + r/2}\"\n    unfolding real_ivl_eqs[OF \\<open>t + r/2 > 0\\<close>] by simp\n  ultimately show ?thesis\n    using subs that by blast\nqed\n\nlemma has_derivative_on_open2: \n  assumes \"t < 0\" \"t \\<in> T\" \"s \\<in> S\"\n  obtains B where \"t \\<in> B\" and \"open B\" and \"B \\<subseteq> T\"\n    and \"D (\\<lambda>\\<tau>. \\<phi> \\<tau> s) \\<mapsto> (\\<lambda>\\<tau>. \\<tau> *\\<^sub>R f (\\<phi> t s)) at t within B\" \nproof-\n  obtain r::real where rHyp: \"r > 0\" \"ball t r \\<subseteq> T\"\n    using open_contains_ball_eq open_domain(1) \\<open>t \\<in> T\\<close> by blast\n  moreover have \"t - r/2 < 0\"\n    using \\<open>r > 0\\<close> \\<open>t < 0\\<close> by auto\n  moreover have \"{0--t} \\<subseteq> T\" \n    using subintervalI[OF init_time \\<open>t \\<in> T\\<close>] .\n  ultimately have subs: \"{0<--<t - r/2} \\<subseteq> T\"\n    unfolding open_segment_eq_real_ivl closed_segment_eq_real_ivl\n      real_ivl_eqs[OF rHyp(1)] by(auto simp: subset_eq)\n  have \"t - r/2 \\<in> T\"\n    using rHyp unfolding real_ivl_eqs by (simp add: subset_eq)\n  hence \"{0--t - r/2} \\<subseteq> T\"\n    using subintervalI[OF init_time] by blast\n  hence \"(D (\\<lambda>t. \\<phi> t s) = (\\<lambda>t. f (\\<phi> t s)) on {0--(t - r/2)})\"\n    using ivp(1)[OF _ \\<open>s \\<in> S\\<close>] by auto\n  hence vderiv: \"(D (\\<lambda>t. \\<phi> t s) = (\\<lambda>t. f (\\<phi> t s)) on {0<--<t - r/2})\"\n    apply(rule has_vderiv_on_subset)\n    unfolding open_segment_eq_real_ivl closed_segment_eq_real_ivl by auto\n  have \"t \\<in> {0<--<t - r/2}\"\n    unfolding open_segment_eq_real_ivl using rHyp \\<open>t < 0\\<close> by simp\n  moreover have \"D (\\<lambda>\\<tau>. \\<phi> \\<tau> s) \\<mapsto> (\\<lambda>\\<tau>. \\<tau> *\\<^sub>R f (\\<phi> t s)) (at t within {0<--<t - r/2})\"\n    using vderiv calculation unfolding has_vderiv_on_def has_vector_derivative_def by blast\n  moreover have \"open {0<--<t - r/2}\"\n    unfolding open_segment_eq_real_ivl by simp\n  ultimately show ?thesis\n    using subs that by blast\nqed\n\nlemma has_derivative_on_open3: \n  assumes \"s \\<in> S\"\n  obtains B where \"0 \\<in> B\" and \"open B\" and \"B \\<subseteq> T\"\n    and \"D (\\<lambda>\\<tau>. \\<phi> \\<tau> s) \\<mapsto> (\\<lambda>\\<tau>. \\<tau> *\\<^sub>R f (\\<phi> 0 s)) at 0 within B\" \nproof-\n  obtain r::real where rHyp: \"r > 0\" \"ball 0 r \\<subseteq> T\"\n    using open_contains_ball_eq open_domain(1) init_time by blast\n  hence \"r/2 \\<in> T\" \"-r/2 \\<in> T\" \"r/2 > 0\"\n    unfolding real_ivl_eqs by auto\n  hence subs: \"{0--r/2} \\<subseteq> T\" \"{0--(-r/2)} \\<subseteq> T\"\n    using subintervalI[OF init_time] by auto\n  hence \"(D (\\<lambda>t. \\<phi> t s) = (\\<lambda>t. f (\\<phi> t s)) on {0--r/2})\"\n    \"(D (\\<lambda>t. \\<phi> t s) = (\\<lambda>t. f (\\<phi> t s)) on {0--(-r/2)})\"\n    using ivp(1)[OF _ \\<open>s \\<in> S\\<close>] by auto\n  also have \"{0--r/2} = {0--r/2} \\<union> closure {0--r/2} \\<inter> closure {0--(-r/2)}\"\n    \"{0--(-r/2)} = {0--(-r/2)} \\<union> closure {0--r/2} \\<inter> closure {0--(-r/2)}\"\n    unfolding closed_segment_eq_real_ivl \\<open>r/2 > 0\\<close> by auto\n  ultimately have vderivs:\n    \"(D (\\<lambda>t. \\<phi> t s) = (\\<lambda>t. f (\\<phi> t s)) on {0--r/2} \\<union> closure {0--r/2} \\<inter> closure {0--(-r/2)})\"\n    \"(D (\\<lambda>t. \\<phi> t s) = (\\<lambda>t. f (\\<phi> t s)) on {0--(-r/2)} \\<union> closure {0--r/2} \\<inter> closure {0--(-r/2)})\"\n    unfolding closed_segment_eq_real_ivl \\<open>r/2 > 0\\<close> by auto\n  have obs: \"0 \\<in> {-r/2<--<r/2}\"\n    unfolding open_segment_eq_real_ivl using \\<open>r/2 > 0\\<close> by auto\n  have union: \"{-r/2--r/2} = {0--r/2} \\<union> {0--(-r/2)}\"\n    unfolding closed_segment_eq_real_ivl by auto\n  hence \"(D (\\<lambda>t. \\<phi> t s) = (\\<lambda>t. f (\\<phi> t s)) on {-r/2--r/2})\"\n    using has_vderiv_on_union[OF vderivs] by simp\n  hence \"(D (\\<lambda>t. \\<phi> t s) = (\\<lambda>t. f (\\<phi> t s)) on {-r/2<--<r/2})\"\n    using has_vderiv_on_subset[OF _ segment_open_subset_closed[of \"-r/2\" \"r/2\"]] by auto\n  hence \"D (\\<lambda>\\<tau>. \\<phi> \\<tau> s) \\<mapsto> (\\<lambda>\\<tau>. \\<tau> *\\<^sub>R f (\\<phi> 0 s)) (at 0 within {-r/2<--<r/2})\"\n    unfolding has_vderiv_on_def has_vector_derivative_def using obs by blast\n  moreover have \"open {-r/2<--<r/2}\"\n    unfolding open_segment_eq_real_ivl by simp\n  moreover have \"{-r/2<--<r/2} \\<subseteq> T\"\n    using subs union segment_open_subset_closed by blast \n  ultimately show ?thesis\n    using obs that by blast\nqed\n\nlemma has_derivative_on_open: \n  assumes \"t \\<in> T\" \"s \\<in> S\"\n  obtains B where \"t \\<in> B\" and \"open B\" and \"B \\<subseteq> T\"\n    and \"D (\\<lambda>\\<tau>. \\<phi> \\<tau> s) \\<mapsto> (\\<lambda>\\<tau>. \\<tau> *\\<^sub>R f (\\<phi> t s)) at t within B\" \n  apply(subgoal_tac \"t < 0 \\<or> t = 0 \\<or> t > 0\")\n  using has_derivative_on_open1[OF _ assms] has_derivative_on_open2[OF _ assms]\n    has_derivative_on_open3[OF \\<open>s \\<in> S\\<close>] by blast force\n\nlemma in_domain:\n  assumes \"s \\<in> S\"\n  shows \"(\\<lambda>t. \\<phi> t s) \\<in> T \\<rightarrow> S\"\n  using ivp(3)[OF _ assms] by blast\n\nlemma has_vderiv_on_domain:\n  assumes \"s \\<in> S\"\n  shows \"D (\\<lambda>t. \\<phi> t s) = (\\<lambda>t. f (\\<phi> t s)) on T\"\nproof(unfold has_vderiv_on_def has_vector_derivative_def, clarsimp)\n  fix t assume \"t \\<in> T\"\n  then obtain B where \"t \\<in> B\" and \"open B\" and \"B \\<subseteq> T\" \n    and Dhyp: \"D (\\<lambda>t. \\<phi> t s) \\<mapsto> (\\<lambda>\\<tau>. \\<tau> *\\<^sub>R f (\\<phi> t s)) at t within B\"\n    using assms has_derivative_on_open[OF \\<open>t \\<in> T\\<close>] by blast\n  hence \"t \\<in> interior B\"\n    using interior_eq by auto\n  thus \"D (\\<lambda>t. \\<phi> t s) \\<mapsto> (\\<lambda>\\<tau>. \\<tau> *\\<^sub>R f (\\<phi> t s)) at t within T\"\n    using has_derivative_at_within_mono[OF _ \\<open>B \\<subseteq> T\\<close> Dhyp] by blast\nqed\n\nlemma in_ivp_sols: \n  assumes \"s \\<in> S\" and \"0 \\<in> U s\" and \"U s \\<subseteq> T\"\n  shows \"(\\<lambda>t. \\<phi> t s) \\<in> Sols (\\<lambda>t. f) U S 0 s\"\n  apply(rule in_ivp_sols_subset[OF _ _ ivp_solsI, of _ _ _ \"\\<lambda>s. T\"])\n  using  ivp(2)[OF \\<open>s \\<in> S\\<close>] has_vderiv_on_domain[OF \\<open>s \\<in> S\\<close>] \n    in_domain[OF \\<open>s \\<in> S\\<close>] assms by auto\n\nlemma eq_solution:\n  assumes \"s \\<in> S\" and \"is_interval (U s)\" and \"U s \\<subseteq> T\" and \"t \\<in> U s\"\n    and xivp: \"X \\<in> Sols (\\<lambda>t. f) U S 0 s\"\n  shows \"X t = \\<phi> t s\"\n  apply(rule ivp_unique_solution[OF assms], rule in_ivp_sols)\n  by (simp_all add: ivp_solsD(4)[OF xivp] assms)\n\nlemma ivp_sols_collapse: \n  assumes \"T = UNIV\" and \"s \\<in> S\"\n  shows \"Sols (\\<lambda>t. f) (\\<lambda>s. T) S 0 s = {(\\<lambda>t. \\<phi> t s)}\"\n  apply (safe, simp_all add: fun_eq_iff, clarsimp)\n   apply(rule eq_solution[of _ \"\\<lambda>s. T\"]; simp add: assms)\n  by (rule in_ivp_sols; simp add: assms)\n\nlemma additive_in_ivp_sols:\n  assumes \"s \\<in> S\" and \"\\<P> (\\<lambda>\\<tau>. \\<tau> + t) T \\<subseteq> T\"\n  shows \"(\\<lambda>\\<tau>. \\<phi> (\\<tau> + t) s) \\<in> Sols (\\<lambda>t. f) (\\<lambda>s. T) S 0 (\\<phi> (0 + t) s)\"\n  apply(rule ivp_solsI[OF vderiv_on_composeI])\n       apply(rule has_vderiv_on_subset[OF has_vderiv_on_domain])\n  using in_domain assms init_time by (auto intro!: poly_derivatives)\n\nlemma is_monoid_action:\n  assumes \"s \\<in> S\" and \"T = UNIV\"\n  shows \"\\<phi> 0 s = s\" and \"\\<phi> (t\\<^sub>1 + t\\<^sub>2) s = \\<phi> t\\<^sub>1 (\\<phi> t\\<^sub>2 s)\"\nproof-\n  show \"\\<phi> 0 s = s\"\n    using ivp assms by simp\n  have \"\\<phi> (0 + t\\<^sub>2) s = \\<phi> t\\<^sub>2 s\" \n    by simp\n  also have \"\\<phi> (0 + t\\<^sub>2) s \\<in> S\"\n    using in_domain assms by auto\n  ultimately show \"\\<phi> (t\\<^sub>1 + t\\<^sub>2) s = \\<phi> t\\<^sub>1 (\\<phi> t\\<^sub>2 s)\"\n    using eq_solution[OF _ _ _ _ additive_in_ivp_sols] assms by auto\nqed\n\nlemma g_orbital_collapses: \n  assumes \"s \\<in> S\" and \"is_interval (U s)\" and \"U s \\<subseteq> T\" and \"0 \\<in> U s\"\n  shows \"g_orbital (\\<lambda>t. f) G U S 0 s = {\\<phi> t s| t. t \\<in> U s \\<and> (\\<forall>\\<tau>\\<in>down (U s) t. G (\\<phi> \\<tau> s))}\"\n  apply (subst g_orbital_orbit[of _ _ \"\\<lambda>t. \\<phi> t s\"], simp_all add: assms g_orbit_eq)\n  by (rule in_ivp_sols, simp_all add: assms)\n\ndefinition orbit :: \"'a \\<Rightarrow> 'a set\" (\"\\<gamma>\\<^sup>\\<phi>\")\n  where \"\\<gamma>\\<^sup>\\<phi> s = g_orbital (\\<lambda>t. f) (\\<lambda>s. True) (\\<lambda>s. T) S 0 s\"\n\nlemma orbit_eq: \n  assumes \"s \\<in> S\"\n  shows \"\\<gamma>\\<^sup>\\<phi> s = {\\<phi> t s| t. t \\<in> T}\"\n  apply(unfold orbit_def, subst g_orbital_collapses)\n  by (simp_all add: assms init_time interval_time)\n\nlemma true_g_orbit_eq:\n  assumes \"s \\<in> S\"\n  shows \"g_orbit (\\<lambda>t. \\<phi> t s) (\\<lambda>s. True) T = \\<gamma>\\<^sup>\\<phi> s\"\n  unfolding g_orbit_eq orbit_eq[OF assms] by simp\n\nend\n\nlemma line_is_local_flow: \n  \"0 \\<in> T \\<Longrightarrow> is_interval T \\<Longrightarrow> open T \\<Longrightarrow> local_flow (\\<lambda> s. c) T UNIV (\\<lambda> t s. s + t *\\<^sub>R c)\"\n  apply(unfold_locales, simp_all add: local_lipschitz_def lipschitz_on_def, clarsimp)\n   apply(rule_tac x=1 in exI, clarsimp, rule_tac x=\"1/2\" in exI, simp)\n  apply(rule_tac f'1=\"\\<lambda> s. 0\" and g'1=\"\\<lambda> s. c\" in has_vderiv_on_add[THEN has_vderiv_on_eq_rhs])\n    apply(rule derivative_intros, simp)+\n  by simp_all\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_ODEs.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8333246035907933, "lm_q2_score": 0.8519527944504227, "lm_q1q2_score": 0.7099532247134671}}
{"text": "theory tut3sol \nimports\nMain\n\nbegin\n\nlocale Geom =\n  fixes on :: \"'p \\<Rightarrow> 'l \\<Rightarrow> bool\"\n  assumes line_on_two_pts: \"a \\<noteq> b \\<Longrightarrow> \\<exists>l. on a l \\<and> on b l\" \n  and line_on_two_pts_unique: \"\\<lbrakk> a \\<noteq> b; on a l; on b l; on a m; on b m \\<rbrakk> \\<Longrightarrow> l = m\"\n  and two_points_on_line: \"\\<exists>a b. a \\<noteq> b \\<and> on a l \\<and> on b l\"\n  and three_points_not_on_line: \"\\<exists>a b c. a \\<noteq> b \\<and> a \\<noteq> c \\<and> b \\<noteq> c \\<and> \n                                    \\<not> (\\<exists>l. on a l \\<and> on b l \\<and> on c l)\"\nbegin\n  \n\n(* Not asked for in tutorial: An alternative way of writing Axiom 4 *)  \nlemma three_points_not_on_line_alt:\n  \"\\<exists>a b c. a \\<noteq> b \\<and> a \\<noteq> c \\<and> b \\<noteq> c \\<and> (\\<forall>l. on a l \\<and> on b l \\<longrightarrow> \\<not> on c l)\"\nproof -\n  obtain a b c where distinct: \"a \\<noteq> b \\<and> a \\<noteq> c \\<and> b \\<noteq> c\" \"\\<not> (\\<exists>l. on a l \\<and> on b l \\<and> on c l)\" \n    using three_points_not_on_line by blast\n  then have \"\\<forall>l. on a l \\<and> on b l \\<longrightarrow> \\<not> on c l\"\n    by blast\n  thus ?thesis using distinct by blast\nqed        \n  \nlemma exists_pt_not_on_line: \"\\<exists>x. \\<not> on x l\"\nproof -\n   obtain a b c where l3: \"\\<not> (on a l \\<and> on b l \\<and> on c l)\" using three_points_not_on_line by blast \n   thus ?thesis by blast \nqed\n\nlemma two_lines_through_each_point: \"\\<exists>l m. on x l \\<and> on x m \\<and> l \\<noteq> m\"\nproof -\n  have \"\\<exists>z. z \\<noteq> x\" \n  proof (rule ccontr)\n    from two_points_on_line obtain a b where ab: \"(a::'p) \\<noteq> b\" by blast\n    assume \"\\<nexists>z. z \\<noteq> x\" then have univ: \"\\<forall>z. z = x\" by blast\n    then have \"a = x\" \"b = x\" by auto\n    then show False using ab by simp\n  qed\n  then obtain z where \"z \\<noteq> x\" by blast\n  then obtain l where xl: \"on x l\" and zl: \"on z l\" using line_on_two_pts by blast \n  obtain w where n_wl: \"\\<not> on w l\" using exists_pt_not_on_line by blast\n  obtain m where wm: \"on x m\" and zm: \"on w m\" using line_on_two_pts xl by force\n  then have \"l \\<noteq> m\" using n_wl by blast  \n  thus ?thesis using wm xl by blast \nqed\n\n(* Alternative proof of the above that uses Metis *)\nlemma two_lines_through_each_point2: \"\\<exists>l m. on x l \\<and> on x m \\<and> l \\<noteq> m\"\nproof -\n  obtain z where \"z \\<noteq> x\" using two_points_on_line by metis \n  then obtain l where xl: \"on x l\" and zl: \"on z l\" using line_on_two_pts by blast \n  obtain w where n_wl: \"\\<not> on w l\" using exists_pt_not_on_line by blast\n  obtain m where wm: \"on x m\" and zm: \"on w m\" using line_on_two_pts xl by force\n  then have \"l \\<noteq> m\" using n_wl by blast  \n  thus ?thesis using wm xl by blast \nqed\n\n\nlemma two_lines_through_each_point2: \"\\<exists>l m. on x l \\<and> on x m \\<and> l \\<noteq> m\"\nproof -\n  obtain z where \"z \\<noteq> x\" using two_points_on_line by metis \n  then obtain l where xl: \"on x l\" and zl: \"on z l\" using line_on_two_pts by blast \n  obtain w where n_wl: \"\\<not> on w l\" using exists_pt_not_on_line by blast\n  obtain m where wm: \"on x m\" and zm: \"on w m\" using line_on_two_pts xl by force\n  then have \"l \\<noteq> m\" using n_wl by blast  \n  thus ?thesis using wm xl by blast \nqed\n\nlemma two_lines_unique_intersect_pt: \n   assumes lm: \"l \\<noteq> m\" and \"on x l\" and \"on x m\" and \"on y l\" and \"on y m\" shows \"x = y\"\nproof (rule ccontr)\n   assume \"x \\<noteq> y\" then have \"l = m\" using line_on_two_pts_unique assms by simp\n   thus \"False\" using lm by simp\nqed\n\nend\n\n(* Not asked for in tutorial: An extension of the locale with a new definition \n   using the \"in\" keyword *)\n\ndefinition (in Geom) \n  collinear :: \"'p \\<Rightarrow> 'p \\<Rightarrow> 'p \\<Rightarrow> bool\" \n  where \"collinear a b c \\<equiv> \\<exists>l. on a l \\<and> on b l \\<and> on c l\"\n\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/tut3sol.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391624034103, "lm_q2_score": 0.8221891305219504, "lm_q1q2_score": 0.7098712086645338}}
{"text": "header{*Relations, Families, Ordinals*}\n\ntheory Ordinal imports HF\nbegin\n\nsection{*Relations and Functions*}\n\ndefinition is_hpair :: \"hf \\<Rightarrow> bool\"\n  where \"is_hpair z = (\\<exists>x y. z = \\<langle>x,y\\<rangle>)\"\n\ndefinition hconverse :: \"hf \\<Rightarrow> hf\"\n  where \"hconverse(r) = \\<lbrace>z. w \\<^bold>\\<in> r, \\<exists>x y. w = \\<langle>x,y\\<rangle> & z = \\<langle>y,x\\<rangle>\\<rbrace>\"\n\ndefinition hdomain :: \"hf \\<Rightarrow> hf\"\n  where \"hdomain(r) = \\<lbrace>x. w \\<^bold>\\<in> r, \\<exists>y. w = \\<langle>x,y\\<rangle>\\<rbrace>\"\n\ndefinition hrange :: \"hf \\<Rightarrow> hf\"\n  where \"hrange(r) = hdomain(hconverse(r))\"\n\ndefinition hrelation :: \"hf \\<Rightarrow> bool\"\n  where \"hrelation(r) = (\\<forall>z. z \\<^bold>\\<in> r \\<longrightarrow> is_hpair z)\"\n\ndefinition hrestrict :: \"hf \\<Rightarrow> hf \\<Rightarrow> hf\"\n  --{* Restrict the relation r to the domain A *}\n  where \"hrestrict r A = \\<lbrace>z \\<^bold>\\<in> r. \\<exists>x \\<^bold>\\<in> A. \\<exists>y. z = \\<langle>x,y\\<rangle>\\<rbrace>\"\n\ndefinition nonrestrict :: \"hf \\<Rightarrow> hf \\<Rightarrow> hf\"\n  where \"nonrestrict r A = \\<lbrace>z \\<^bold>\\<in> r. \\<forall>x \\<^bold>\\<in> A. \\<forall>y. z \\<noteq> \\<langle>x,y\\<rangle>\\<rbrace>\"\n\ndefinition hfunction :: \"hf \\<Rightarrow> bool\"\n  where \"hfunction(r) = (\\<forall>x y. \\<langle>x,y\\<rangle> \\<^bold>\\<in> r \\<longrightarrow> (\\<forall>y'. \\<langle>x,y'\\<rangle> \\<^bold>\\<in> r \\<longrightarrow> y=y'))\"\n\ndefinition app :: \"hf \\<Rightarrow> hf \\<Rightarrow> hf\"\n  where \"app f x = (THE y. \\<langle>x, y\\<rangle> \\<^bold>\\<in> f)\"\n\nlemma hrestrict_iff [iff]:\n    \"z \\<^bold>\\<in> hrestrict r A \\<longleftrightarrow> z \\<^bold>\\<in> r & (\\<exists> x y. z = \\<langle>x, y\\<rangle> & x \\<^bold>\\<in> A)\"\n  by (auto simp: hrestrict_def)\n\nlemma hrelation_0 [simp]: \"hrelation 0\"\n  by (force simp add: hrelation_def)\n\nlemma hrelation_restr [iff]: \"hrelation (hrestrict r x)\"\n  by (metis hrelation_def hrestrict_iff is_hpair_def)\n\nlemma hrelation_hunion [simp]: \"hrelation (f \\<squnion> g) \\<longleftrightarrow> hrelation f \\<and> hrelation g\"\n  by (auto simp: hrelation_def)\n\nlemma hfunction_restr: \"hfunction r \\<Longrightarrow> hfunction (hrestrict r x)\"\n  by (auto simp: hfunction_def hrestrict_def)\n\nlemma hdomain_restr [simp]: \"hdomain (hrestrict r x) = hdomain r \\<sqinter> x\"\n  by (force simp add: hdomain_def hrestrict_def)\n\nlemma hdomain_0 [simp]: \"hdomain 0 = 0\"\n  by (force simp add: hdomain_def)\n\nlemma hdomain_ins [simp]: \"hdomain (r \\<triangleleft> \\<langle>x, y\\<rangle>) = hdomain r \\<triangleleft> x\"\n  by (force simp add: hdomain_def)\n\nlemma hdomain_hunion [simp]: \"hdomain (f \\<squnion> g) = hdomain f \\<squnion> hdomain g\"\n  by (simp add: hdomain_def)\n\nlemma hdomain_not_mem [iff]: \"\\<not> \\<langle>hdomain r, a\\<rangle> \\<^bold>\\<in> r\"\n  by (metis hdomain_ins hinter_hinsert_right hmem_hinsert hmem_not_refl\n            hunion_hinsert_right sup_inf_absorb)\n\nlemma app_singleton [simp]: \"app \\<lbrace>\\<langle>x, y\\<rangle>\\<rbrace> x = y\"\n  by (simp add: app_def)\n\nlemma app_equality: \"hfunction f \\<Longrightarrow> \\<langle>x, y\\<rangle> <: f \\<Longrightarrow> app f x = y\"\n  by (auto simp: app_def hfunction_def intro: the1I2)\n\nlemma app_ins2: \"x' \\<noteq> x \\<Longrightarrow> app (f \\<triangleleft> \\<langle>x, y\\<rangle>) x' = app f x'\"\n  by (simp add: app_def)\n\nlemma hfunction_0 [simp]: \"hfunction 0\"\n  by (force simp add: hfunction_def)\n\nlemma hfunction_ins: \"hfunction f \\<Longrightarrow> ~ x <: hdomain f \\<Longrightarrow> hfunction (f\\<triangleleft> \\<langle>x, y\\<rangle>)\"\n  by (auto simp: hfunction_def hdomain_def)\n\nlemma hdomainI: \"\\<langle>x, y\\<rangle> \\<^bold>\\<in> f \\<Longrightarrow> x \\<^bold>\\<in> hdomain f\"\n  by (auto simp: hdomain_def)\n\nlemma hfunction_hunion: \"hdomain f \\<sqinter> hdomain g = 0\n            \\<Longrightarrow> hfunction (f \\<squnion> g) \\<longleftrightarrow> hfunction f \\<and> hfunction g\"\n  by (auto simp: hfunction_def) (metis hdomainI hinter_iff hmem_hempty)+\n\nlemma app_hrestrict [simp]: \"x \\<^bold>\\<in> A \\<Longrightarrow> app (hrestrict f A) x = app f x\"\n  by (simp add: hrestrict_def app_def)\n\nsection{*Operations on families of sets*}\n\ndefinition HLambda :: \"hf \\<Rightarrow> (hf \\<Rightarrow> hf) \\<Rightarrow> hf\"\n  where \"HLambda A b = RepFun A (\\<lambda>x. \\<langle>x, b x\\<rangle>)\"\n\ndefinition HSigma :: \"hf \\<Rightarrow> (hf \\<Rightarrow> hf) \\<Rightarrow> hf\"\n  where \"HSigma A B = (\\<Squnion>x\\<^bold>\\<in>A. \\<Squnion>y\\<^bold>\\<in>B(x). \\<lbrace>\\<langle>x,y\\<rangle>\\<rbrace>)\"\n\ndefinition HPi :: \"hf \\<Rightarrow> (hf \\<Rightarrow> hf) \\<Rightarrow> hf\"\n  where \"HPi A B = \\<lbrace> f \\<^bold>\\<in> HPow(HSigma A B). A \\<le> hdomain(f) & hfunction(f)\\<rbrace>\"\n\n\nsyntax\n  \"_PROD\"     :: \"[pttrn, hf, hf] \\<Rightarrow> hf\"        (\"(3PROD _<:_./ _)\" 10)\n  \"_SUM\"      :: \"[pttrn, hf, hf] \\<Rightarrow> hf\"        (\"(3SUM _<:_./ _)\" 10)\n  \"_lam\"      :: \"[pttrn, hf, hf] \\<Rightarrow> hf\"        (\"(3lam _<:_./ _)\" 10)\n\nsyntax (xsymbols)\n  \"_PROD\"     :: \"[pttrn, hf, hf] \\<Rightarrow> hf\"        (\"(3\\<Pi>_\\<^bold>\\<in>_./ _)\" 10)\n  \"_SUM\"      :: \"[pttrn, hf, hf] \\<Rightarrow> hf\"        (\"(3\\<Sigma>_\\<^bold>\\<in>_./ _)\" 10)\n  \"_lam\"      :: \"[pttrn, hf, hf] \\<Rightarrow> hf\"        (\"(3\\<lambda>_\\<^bold>\\<in>_./ _)\" 10)\n\nsyntax (HTML output)\n  \"_PROD\"     :: \"[pttrn, hf, hf] \\<Rightarrow> hf\"        (\"(3\\<Pi>_\\<^bold>\\<in>_./ _)\" 10)\n  \"_SUM\"      :: \"[pttrn, hf, hf] \\<Rightarrow> hf\"        (\"(3\\<Sigma>_\\<^bold>\\<in>_./ _)\" 10)\n  \"_lam\"      :: \"[pttrn, hf, hf] \\<Rightarrow> hf\"        (\"(3\\<lambda>_\\<^bold>\\<in>_./ _)\" 10)\n\ntranslations\n  \"PROD x<:A. B\" == \"CONST HPi A (%x. B)\"\n  \"SUM x<:A. B\"  == \"CONST HSigma A (%x. B)\"\n  \"lam x<:A. f\"  == \"CONST HLambda A (%x. f)\"\n\nsubsection{*Rules for Unions and Intersections of families*}\n\nlemma HUN_iff [simp]: \"b \\<^bold>\\<in> (\\<Squnion>x\\<^bold>\\<in>A. B(x)) \\<longleftrightarrow> (\\<exists>x\\<^bold>\\<in>A. b \\<^bold>\\<in> B(x))\"\n  by auto\n\n(*The order of the premises presupposes that A is rigid; b may be flexible*)\nlemma HUN_I: \"\\<lbrakk> a \\<^bold>\\<in> A;  b \\<^bold>\\<in> B(a) \\<rbrakk>  \\<Longrightarrow> b \\<^bold>\\<in> (\\<Squnion>x\\<^bold>\\<in>A. B(x))\"\n  by auto\n\nlemma HUN_E [elim!]: assumes \"b \\<^bold>\\<in> (\\<Squnion>x\\<^bold>\\<in>A. B(x))\" obtains x where \"x \\<^bold>\\<in> A\"  \"b \\<^bold>\\<in> B(x)\"\n  using assms  by blast\n\nlemma HINT_iff: \"b \\<^bold>\\<in> (\\<Sqinter>x\\<^bold>\\<in>A. B(x)) \\<longleftrightarrow> (\\<forall>x\\<^bold>\\<in>A. b \\<^bold>\\<in> B(x)) & A\\<noteq>0\"\n  by (simp add: HInter_def HBall_def) (metis foundation hmem_hempty)\n\nlemma HINT_I: \"\\<lbrakk> !!x. x \\<^bold>\\<in> A \\<Longrightarrow> b \\<^bold>\\<in> B(x);  A\\<noteq>0 \\<rbrakk> \\<Longrightarrow> b \\<^bold>\\<in> (\\<Sqinter>x\\<^bold>\\<in>A. B(x))\"\n  by (simp add: HINT_iff)\n\nlemma HINT_E: \"\\<lbrakk> b \\<^bold>\\<in> (\\<Sqinter>x\\<^bold>\\<in>A. B(x));  a \\<^bold>\\<in> A \\<rbrakk> \\<Longrightarrow> b \\<^bold>\\<in> B(a)\"\n  by (auto simp: HINT_iff)\n\n\nsubsection{*Generalized Cartesian product*}\n\n\n\nlemma HSigmaI [intro!]: \"\\<lbrakk> a \\<^bold>\\<in> A;  b \\<^bold>\\<in> B(a) \\<rbrakk>  \\<Longrightarrow> \\<langle>a,b\\<rangle> \\<^bold>\\<in> HSigma A B\"\n  by simp\n\nlemmas HSigmaD1 = HSigma_iff [THEN iffD1, THEN conjunct1]\nlemmas HSigmaD2 = HSigma_iff [THEN iffD1, THEN conjunct2]\n\ntext{*The general elimination rule*}\nlemma HSigmaE [elim!]:\n  assumes \"c \\<^bold>\\<in> HSigma A B\"\n  obtains x y where \"x \\<^bold>\\<in> A\" \"y \\<^bold>\\<in> B(x)\" \"c=\\<langle>x,y\\<rangle>\"\n  using assms  by (force simp add: HSigma_def)\n\nlemma HSigmaE2 [elim!]:\n  assumes \"\\<langle>a,b\\<rangle> \\<^bold>\\<in> HSigma A B\" obtains \"a \\<^bold>\\<in> A\" and \"b \\<^bold>\\<in> B(a)\"\n  using assms  by auto\n\nlemma HSigma_empty1 [simp]: \"HSigma 0 B = 0\"\n  by blast\n\ninstantiation hf :: times\nbegin\ndefinition times_hf where\n  \"times A B = HSigma A (\\<lambda>x. B)\"\ninstance proof qed\nend\n\nlemma times_iff [simp]: \"\\<langle>a,b\\<rangle> \\<^bold>\\<in> A * B \\<longleftrightarrow> a \\<^bold>\\<in> A & b \\<^bold>\\<in> B\"\n  by (simp add: times_hf_def)\n\nlemma timesI [intro!]: \"\\<lbrakk> a \\<^bold>\\<in> A;  b \\<^bold>\\<in> B \\<rbrakk>  \\<Longrightarrow> \\<langle>a,b\\<rangle> \\<^bold>\\<in> A * B\"\n  by simp\n\nlemmas timesD1 = times_iff [THEN iffD1, THEN conjunct1]\nlemmas timesD2 = times_iff [THEN iffD1, THEN conjunct2]\n\ntext{*The general elimination rule*}\nlemma timesE [elim!]:\n  assumes c: \"c \\<^bold>\\<in> A * B\"\n  obtains x y where \"x \\<^bold>\\<in> A\" \"y \\<^bold>\\<in> B\" \"c=\\<langle>x,y\\<rangle>\" using c\n  by (auto simp: times_hf_def)\n\ntext{*...and a specific one*}\nlemma timesE2 [elim!]:\n  assumes \"\\<langle>a,b\\<rangle> \\<^bold>\\<in> A * B\" obtains \"a \\<^bold>\\<in> A\" and \"b \\<^bold>\\<in> B\"\nusing assms\n  by auto\n\nlemma times_empty1 [simp]: \"0 * B = (0::hf)\"\n  by auto\n\nlemma times_empty2 [simp]: \"A*0 = (0::hf)\"\n  by blast\n\nlemma times_empty_iff: \"A*B=0 \\<longleftrightarrow> A=0 | B=(0::hf)\"\n  by (auto simp: times_hf_def hf_ext)\n\ninstantiation hf :: mult_zero\nbegin\ninstance proof qed auto\nend\n\nsection {*Disjoint Sum*}\n\ninstantiation hf :: zero_neq_one\nbegin\n\ndefinition\n  One_hf_def: \"1 = \\<lbrace>0\\<rbrace>\"\ninstance proof\n  qed (auto simp: One_hf_def)\nend\n\ninstantiation hf :: plus\nbegin\ndefinition plus_hf where\n  \"plus A B = (\\<lbrace>0\\<rbrace> * A) \\<squnion> (\\<lbrace>1\\<rbrace> * B)\"\ninstance proof qed\nend\n\ndefinition Inl :: \"hf=>hf\" where\n     \"Inl(a) \\<equiv> \\<langle>0,a\\<rangle>\"\n\ndefinition Inr :: \"hf=>hf\" where\n     \"Inr(b) \\<equiv> \\<langle>1,b\\<rangle>\"\n\nlemmas sum_defs = plus_hf_def Inl_def Inr_def\n\nlemma Inl_nonzero [simp]:\"Inl x \\<noteq> 0\"\n  by (metis Inl_def hpair_nonzero)\n\nlemma Inr_nonzero [simp]:\"Inr x \\<noteq> 0\"\n  by (metis Inr_def hpair_nonzero)\n\ntext{* Introduction rules for the injections (as equivalences) *}\n\nlemma Inl_in_sum_iff [iff]: \"Inl(a) \\<^bold>\\<in> A+B \\<longleftrightarrow> a \\<^bold>\\<in> A\"\n  by (auto simp: sum_defs)\n\nlemma Inr_in_sum_iff [iff]: \"Inr(b) \\<^bold>\\<in> A+B \\<longleftrightarrow> b \\<^bold>\\<in> B\"\n  by (auto simp: sum_defs)\n\ntext{*Elimination rule*}\n\nlemma sumE [elim!]:\n  assumes u: \"u \\<^bold>\\<in> A+B\"\n  obtains x where \"x \\<^bold>\\<in> A\" \"u=Inl(x)\" | y where \"y \\<^bold>\\<in> B\" \"u=Inr(y)\" using u\n  by (auto simp: sum_defs)\n\ntext{* Injection and freeness equivalences, for rewriting *}\n\nlemma Inl_iff [iff]: \"Inl(a)=Inl(b) \\<longleftrightarrow> a=b\"\n  by (simp add: sum_defs)\n\nlemma Inr_iff [iff]: \"Inr(a)=Inr(b) \\<longleftrightarrow> a=b\"\n  by (simp add: sum_defs)\n\nlemma Inl_Inr_iff [iff]: \"Inl(a)=Inr(b) \\<longleftrightarrow> False\"\n  by (simp add: sum_defs)\n\nlemma Inr_Inl_iff [iff]: \"Inr(b)=Inl(a) \\<longleftrightarrow> False\"\n  by (simp add: sum_defs)\n\nlemma sum_empty [simp]: \"0+0 = (0::hf)\"\n  by (auto simp: sum_defs)\n\nlemma sum_iff: \"u \\<^bold>\\<in> A+B \\<longleftrightarrow> (\\<exists>x. x \\<^bold>\\<in> A & u=Inl(x)) | (\\<exists>y. y \\<^bold>\\<in> B & u=Inr(y))\"\n  by blast\n\nlemma sum_subset_iff:\n  fixes A :: hf shows \"A+B \\<le> C+D \\<longleftrightarrow> A\\<le>C & B\\<le>D\"\n  by blast\n\nlemma sum_equal_iff:\n  fixes A :: hf shows \"A+B = C+D \\<longleftrightarrow> A=C & B=D\"\n  by (auto simp: hf_ext sum_subset_iff)\n\n\nsection{*Ordinals*}\n\nsubsection{*Basic Definitions*}\n\ntext{*Definition 2.1. We say that x is transitive if every element of x is a subset of x.*}\ndefinition\n  Transset  :: \"hf \\<Rightarrow> bool\"  where\n    \"Transset(x) \\<equiv> \\<forall>y. y \\<^bold>\\<in> x \\<longrightarrow> y \\<le> x\"\n\nlemma Transset_sup: \"Transset x \\<Longrightarrow> Transset y \\<Longrightarrow> Transset (x \\<squnion> y)\"\n  by (auto simp: Transset_def)\n\nlemma Transset_inf: \"Transset x \\<Longrightarrow> Transset y \\<Longrightarrow> Transset (x \\<sqinter> y)\"\n  by (auto simp: Transset_def)\n\nlemma Transset_hinsert: \"Transset x \\<Longrightarrow> y \\<le> x \\<Longrightarrow> Transset (x \\<triangleleft> y)\"\n  by (auto simp: Transset_def)\n\n\ntext{*In HF, the ordinals are simply the natural numbers. But the definitions are the same\n      as for transfinite ordinals.*}\ndefinition\n  Ord  :: \"hf \\<Rightarrow> bool\"  where\n    \"Ord(k)      \\<equiv> Transset(k) & (\\<forall>x \\<^bold>\\<in> k. Transset(x))\"\n\nsubsection {*Definition 2.2 (Successor).*}\ndefinition\n  succ  :: \"hf \\<Rightarrow> hf\"  where\n    \"succ(x)      \\<equiv> hinsert x x\"\n\nlemma succ_iff [simp]: \"x \\<^bold>\\<in> succ y \\<longleftrightarrow> x=y \\<or> x \\<^bold>\\<in> y\"\n  by (simp add: succ_def)\n\nlemma succ_ne_self [simp]: \"i \\<noteq> succ i\"\n  by (metis hmem_ne succ_iff)\n\nlemma succ_notin_self: \"~ succ i <: i\"\n  by (metis hmem_ne succ_iff)\n\nlemma succE [elim?]: assumes \"x \\<^bold>\\<in> succ y\" obtains \"x=y\" | \"x \\<^bold>\\<in> y\"\n  by (metis assms succ_iff)\n\nlemma hmem_succ_ne: \"succ x <: y \\<Longrightarrow> x \\<noteq> y\"\n  by (metis hmem_not_refl succ_iff)\n\nlemma hball_succ [simp]: \"(\\<forall>x \\<^bold>\\<in> succ k. P x) \\<longleftrightarrow> P k & (\\<forall>x \\<^bold>\\<in> k. P x)\"\n  by (auto simp: HBall_def)\n\nlemma hbex_succ [simp]: \"(\\<exists>x \\<^bold>\\<in> succ k. P x) \\<longleftrightarrow> P k | (\\<exists>x \\<^bold>\\<in> k. P x)\"\n  by (auto simp: HBex_def)\n\nlemma One_hf_eq_succ: \"1 = succ 0\"\n  by (metis One_hf_def succ_def)\n\nlemma zero_hmem_one [iff]: \"x \\<^bold>\\<in> 1 \\<longleftrightarrow> x = 0\"\n  by (metis One_hf_eq_succ hmem_hempty succ_iff)\n\nlemma hball_One [simp]: \"(\\<forall>x\\<^bold>\\<in>1. P x) = P 0\"\n  by (simp add: One_hf_eq_succ)\n\nlemma hbex_One [simp]: \"(\\<exists>x\\<^bold>\\<in>1. P x) = P 0\"\n  by (simp add: One_hf_eq_succ)\n\nlemma hpair_neq_succ [simp]: \"\\<langle>x,y\\<rangle> \\<noteq> succ k\"\n  by (auto simp: succ_def hpair_def) (metis hemptyE hmem_hinsert hmem_ne)\n\n\n\nlemma hpair_neq_one [simp]: \"\\<langle>x,y\\<rangle> \\<noteq> 1\"\n  by (metis One_hf_eq_succ hpair_neq_succ)\n\nlemma one_neq_hpair [simp]: \"1 \\<noteq> \\<langle>x,y\\<rangle>\"\n  by (metis hpair_neq_one)\n\n\n\nlemma hmem_succ: \"l \\<^bold>\\<in> k \\<Longrightarrow> l \\<^bold>\\<in> succ k\"\n  by (metis succ_iff)\n\ntext{*Theorem 2.3.*}\nlemma Ord_0 [iff]: \"Ord 0\"\n  by (simp add: Ord_def Transset_def)\n\nlemma Ord_succ: \"Ord(k) \\<Longrightarrow> Ord(succ(k))\"\n  by (simp add: Ord_def Transset_def succ_def less_eq_insert2_iff HBall_def)\n\nlemma Ord_1 [iff]: \"Ord 1\"\n  by (metis One_hf_def Ord_0 Ord_succ succ_def)\n\nlemma OrdmemD: \"Ord(k) \\<Longrightarrow> j \\<^bold>\\<in> k \\<Longrightarrow> j \\<le> k\"\n  by (simp add: Ord_def Transset_def HBall_def)\n\nlemma Ord_trans: \"\\<lbrakk> i\\<^bold>\\<in>j;  j\\<^bold>\\<in>k;  Ord(k) \\<rbrakk>  \\<Longrightarrow> i\\<^bold>\\<in>k\"\n  by (blast dest: OrdmemD)\n\nlemma hmem_0_Ord:\n  assumes k: \"Ord(k)\" and knz: \"k \\<noteq> 0\" shows \"0 \\<^bold>\\<in> k\"\n  by (metis foundation [OF knz] Ord_trans hempty_iff hinter_iff k)\n\nlemma Ord_in_Ord: \"\\<lbrakk> Ord(k);  m \\<^bold>\\<in> k \\<rbrakk>  \\<Longrightarrow> Ord(m)\"\n  by (auto simp: Ord_def Transset_def)\n\nsubsection{*Induction, Linearity, etc.*}\n\nlemma Ord_induct [consumes 1, case_names step]:\n  assumes k: \"Ord(k)\"\n      and step: \"!!x.\\<lbrakk> Ord(x);  \\<And>y. y \\<^bold>\\<in> x \\<Longrightarrow> P(y) \\<rbrakk>  \\<Longrightarrow> P(x)\"\n  shows \"P(k)\"\nproof -\n  have \"\\<forall>m \\<^bold>\\<in> k. Ord(m) \\<longrightarrow> P(m)\"\n    proof (induct k rule: hf_induct)\n      case 0 thus ?case  by simp\n    next\n      case (hinsert a b)\n      thus ?case\n        by (auto intro: Ord_in_Ord step)\n    qed\n  thus ?thesis using k\n    by (auto intro: Ord_in_Ord step)\nqed\n\ntext{*Theorem 2.4 (Comparability of ordinals).*}\nlemma Ord_linear: \"Ord(k) \\<Longrightarrow> Ord(l) \\<Longrightarrow> k\\<^bold>\\<in>l | k=l | l\\<^bold>\\<in>k\"\nproof (induct k arbitrary: l rule: Ord_induct)\n  case (step k)\n  note step_k = step\n  show ?case using `Ord(l)`\n    proof (induct l rule: Ord_induct)\n      case (step l)\n      thus ?case using step_k\n        by (metis Ord_trans hf_equalityI)\n    qed\nqed\n\ntext{*The trichotomy law for ordinals*}\nlemma Ord_linear_lt:\n  assumes o: \"Ord(k)\" \"Ord(l)\"\n  obtains (lt) \"k\\<^bold>\\<in>l\" | (eq) \"k=l\" | (gt) \"l\\<^bold>\\<in>k\"\nby (metis Ord_linear o)\n\nlemma Ord_linear2:\n  assumes o: \"Ord(k)\" \"Ord(l)\"\n  obtains (lt) \"k\\<^bold>\\<in>l\" | (ge) \"l \\<le> k\"\nby (metis Ord_linear OrdmemD order_eq_refl o)\n\nlemma Ord_linear_le:\n  assumes o: \"Ord(k)\" \"Ord(l)\"\n  obtains (le) \"k \\<le> l\" | (ge) \"l \\<le> k\"\nby (metis Ord_linear2 OrdmemD o)\n\nlemma hunion_less_iff [simp]: \"\\<lbrakk>Ord i; Ord j\\<rbrakk> \\<Longrightarrow> i \\<squnion> j < k \\<longleftrightarrow> i<k \\<and> j<k\"\n  by (metis Ord_linear_le le_iff_sup sup.order_iff sup.strict_boundedE)\n\ntext{*Theorem 2.5*}\nlemma Ord_mem_iff_lt: \"Ord(k) \\<Longrightarrow> Ord(l) \\<Longrightarrow> k\\<^bold>\\<in>l \\<longleftrightarrow> k < l\"\n  by (metis Ord_linear OrdmemD hmem_not_refl less_hf_def less_le_not_le)\n\nlemma le_succE: \"succ i \\<le> succ j \\<Longrightarrow> i \\<le> j\"\n  by (simp add: less_eq_hf_def) (metis hmem_not_sym)\n\nlemma le_succ_iff: \"Ord i \\<Longrightarrow> Ord j \\<Longrightarrow> succ i \\<le> succ j \\<longleftrightarrow> i \\<le> j\"\n  by (metis Ord_linear_le Ord_succ le_succE order_antisym)\n\nlemma succ_inject_iff [iff]: \"succ i = succ j \\<longleftrightarrow> i = j\"\n  by (metis succ_def hmem_hinsert hmem_not_sym)\n\nlemma mem_succ_iff [simp]: \"Ord j \\<Longrightarrow> succ i \\<^bold>\\<in> succ j \\<longleftrightarrow> i \\<^bold>\\<in> j\"\n  by (metis Ord_in_Ord Ord_mem_iff_lt Ord_succ succ_def less_eq_insert1_iff less_hf_def succ_iff)\n\nlemma Ord_mem_succ_cases:\n  assumes \"Ord(k)\" \"l \\<^bold>\\<in> k\"\n  shows \"succ l = k \\<or> succ l \\<^bold>\\<in> k\"\n  by (metis assms mem_succ_iff succ_iff)\n\nsubsection{*Supremum and Infimum*}\n\nlemma Ord_Union [intro,simp]: \"\\<lbrakk> !!i. i\\<^bold>\\<in>A \\<Longrightarrow> Ord(i) \\<rbrakk>  \\<Longrightarrow> Ord(\\<Squnion> A)\"\n  by (auto simp: Ord_def Transset_def) blast\n\nlemma Ord_Inter [intro,simp]: \"\\<lbrakk> !!i. i\\<^bold>\\<in>A \\<Longrightarrow> Ord(i) \\<rbrakk>  \\<Longrightarrow> Ord(\\<Sqinter> A)\"\n  apply (case_tac \"A=0\", auto simp: Ord_def Transset_def)\n  apply (force simp add: hf_ext)+\n  done\n\ntext{*Theorem 2.7. Every set x of ordinals is ordered by the binary relation <.\n      Moreover if x = 0 then x has a smallest and a largest element.*}\n\nlemma hmem_Sup_Ords: \"\\<lbrakk>A\\<noteq>0; !!i. i\\<^bold>\\<in>A \\<Longrightarrow> Ord(i)\\<rbrakk> \\<Longrightarrow> \\<Squnion>A \\<^bold>\\<in> A\"\nproof (induction A rule: hf_induct)\n  case 0 thus ?case  by simp\nnext\n  case (hinsert x A)\n  show ?case\n    proof (cases A rule: hf_cases)\n      case 0 thus ?thesis by simp\n    next\n      case (hinsert y A')\n      hence UA: \"\\<Squnion>A \\<^bold>\\<in> A\"\n        by (metis hinsert.IH(2) hinsert.prems(2) hinsert_nonempty hmem_hinsert)\n      hence \"\\<Squnion>A \\<le> x | x \\<le> \\<Squnion>A\"\n        by (metis Ord_linear2 OrdmemD hinsert.prems(2) hmem_hinsert)\n      thus ?thesis\n        by (metis HUnion_hinsert UA le_iff_sup less_eq_insert1_iff order_refl sup.commute)\n    qed\nqed\n\nlemma hmem_Inf_Ords: \"\\<lbrakk>A\\<noteq>0; !!i. i\\<^bold>\\<in>A \\<Longrightarrow> Ord(i)\\<rbrakk> \\<Longrightarrow> \\<Sqinter>A \\<^bold>\\<in> A\"\nproof (induction A rule: hf_induct)\n  case 0 thus ?case  by simp\nnext\n  case (hinsert x A)\n  show ?case\n    proof (cases A rule: hf_cases)\n      case 0 thus ?thesis by auto\n    next\n      case (hinsert y A')\n      hence IA: \"\\<Sqinter>A \\<^bold>\\<in> A\"\n        by (metis hinsert.IH(2) hinsert.prems(2) hinsert_nonempty hmem_hinsert)\n      hence \"\\<Sqinter>A \\<le> x | x \\<le> \\<Sqinter>A\"\n        by (metis Ord_linear2 OrdmemD hinsert.prems(2) hmem_hinsert)\n      thus ?thesis\n        by (metis HInter_hinsert IA hmem_hempty hmem_hinsert inf_absorb2 le_iff_inf)\n    qed\nqed\n\nlemma Ord_pred: \"\\<lbrakk>Ord(k); k \\<noteq> 0\\<rbrakk> \\<Longrightarrow> succ(\\<Squnion>k) = k\"\nby (metis (full_types) HUnion_iff Ord_in_Ord Ord_mem_succ_cases hmem_Sup_Ords hmem_ne succ_iff)\n\nlemma Ord_cases [cases type: hf, case_names 0 succ]:\n  assumes Ok: \"Ord(k)\"\n  obtains \"k = 0\" | l where \"Ord l\" \"succ l = k\"\nby (metis Ok Ord_in_Ord Ord_pred succ_iff)\n\nlemma Ord_induct2 [consumes 1, case_names 0 succ, induct type: hf]:\n  assumes k: \"Ord(k)\"\n      and P: \"P 0\" \"\\<And>k. Ord k \\<Longrightarrow> P k \\<Longrightarrow> P (succ k)\"\n  shows \"P k\"\nusing k\nproof (induction k rule: Ord_induct)\n  case (step k) thus ?case\n    by (metis Ord_cases P hmem_succ_self)\nqed\n\nlemma Ord_succ_iff [iff]: \"Ord (succ k) = Ord k\"\n  by (metis Ord_in_Ord Ord_succ less_eq_insert1_iff order_refl succ_def)\n\n\n\nlemma Ord_Sup_succ_eq [simp]: \"Ord k \\<Longrightarrow> \\<Squnion>(succ k) = k\"\n  by (metis Ord_pred Ord_succ_iff succ_inject_iff hinsert_nonempty succ_def)\n\nlemma Ord_lt_succ_iff_le: \"Ord k \\<Longrightarrow> Ord l \\<Longrightarrow> k < succ l \\<longleftrightarrow> k \\<le> l\"\n  by (metis Ord_mem_iff_lt Ord_succ_iff less_le_not_le order_eq_iff succ_iff)\n\nlemma zero_in_Ord: \"Ord k \\<Longrightarrow> k=0 \\<or> 0 \\<^bold>\\<in> k\"\n  by (induct k) auto\n\nlemma hpair_neq_Ord: \"Ord k \\<Longrightarrow> \\<langle>x,y\\<rangle> \\<noteq> k\"\n  by (cases k) auto\n\nlemma hpair_neq_Ord': assumes k: \"Ord k\" shows \"k \\<noteq> \\<langle>x,y\\<rangle>\"\n  by (metis k hpair_neq_Ord)\n\nlemma Not_Ord_hpair [iff]: \"~ Ord \\<langle>x,y\\<rangle>\"\n  by (metis hpair_neq_Ord)\n\nlemma is_hpair [simp]: \"is_hpair \\<langle>x,y\\<rangle>\"\n  by (force simp add: is_hpair_def)\n\nlemma Ord_not_hpair: \"Ord x \\<Longrightarrow> \\<not> is_hpair x\"\n  by (metis Not_Ord_hpair is_hpair_def)\n\nlemma zero_in_succ [simp,intro]: \"Ord i \\<Longrightarrow> 0 \\<^bold>\\<in> succ i\"\n  by (metis succ_iff zero_in_Ord)\n\nsubsection{*Converting Between Ordinals and Natural Numbers*}\n\nfun ord_of :: \"nat \\<Rightarrow> hf\"\n  where\n   \"ord_of 0 = 0\"\n | \"ord_of (Suc k) = succ (ord_of k)\"\n\nlemma Ord_ord_of [simp]: \"Ord (ord_of k)\"\n  by (induct k, auto)\n\nlemma ord_of_inject [iff]: \"ord_of i = ord_of j \\<longleftrightarrow> i=j\"\nproof (induct i arbitrary: j)\n  case 0 show ?case\n    by (metis Zero_neq_Suc hempty_iff hmem_succ_self ord_of.elims)\nnext\n  case (Suc i) show ?case\n    by (cases j) (auto simp: Suc)\nqed\n\nlemma ord_of_minus_1: \"n > 0 \\<Longrightarrow> ord_of n = succ (ord_of (n - 1))\"\n  by (metis Suc_diff_1 ord_of.simps(2))\n\ndefinition nat_of_ord :: \"hf \\<Rightarrow> nat\"\n  where \"nat_of_ord x = (THE n. x = ord_of n)\"\n\nlemma nat_of_ord_ord_of [simp]: \"nat_of_ord (ord_of n) = n\"\n  by (auto simp: nat_of_ord_def)\n\nlemma nat_of_ord_0 [simp]: \"nat_of_ord 0 = 0\"\n  by (metis (mono_tags) nat_of_ord_ord_of ord_of.simps(1))\n\nlemma ord_of_nat_of_ord [simp]: \"Ord x \\<Longrightarrow> ord_of (nat_of_ord x) = x\"\n  apply (erule Ord_induct2, simp)\n  apply (metis nat_of_ord_ord_of ord_of.simps(2))\n  done\n\nlemma nat_of_ord_inject: \"Ord x \\<Longrightarrow> Ord y \\<Longrightarrow> nat_of_ord x = nat_of_ord y \\<longleftrightarrow> x = y\"\n  by (metis ord_of_nat_of_ord)\n\nlemma nat_of_ord_succ [simp]: \"Ord x \\<Longrightarrow> nat_of_ord (succ x) = Suc (nat_of_ord x)\"\n  by (metis nat_of_ord_ord_of ord_of.simps(2) ord_of_nat_of_ord)\n\n\nsection{*Sequences and Ordinal Recursion*}\n\ntext{*Definition 3.2 (Sequence).*}\n\ndefinition Seq :: \"hf \\<Rightarrow> hf \\<Rightarrow> bool\"\n  where \"Seq s k \\<longleftrightarrow> hrelation s & hfunction s & k \\<le> hdomain s\"\n\nlemma Seq_0 [iff]: \"Seq 0 0\"\n  by (auto simp: Seq_def hrelation_def hfunction_def)\n\nlemma Seq_succ_D: \"Seq s (succ k) \\<Longrightarrow> Seq s k\"\n  by (simp add: Seq_def succ_def)\n\nlemma Seq_Ord_D: \"Seq s k \\<Longrightarrow> l \\<^bold>\\<in> k \\<Longrightarrow> Ord k \\<Longrightarrow> Seq s l\"\n  by (auto simp: Seq_def intro: Ord_trans)\n\nlemma Seq_restr: \"Seq s (succ k) \\<Longrightarrow> Seq (hrestrict s k) k\"\n  by (simp add: Seq_def hfunction_restr succ_def)\n\nlemma Seq_Ord_restr: \"\\<lbrakk>Seq s k; l \\<^bold>\\<in> k; Ord k\\<rbrakk> \\<Longrightarrow> Seq (hrestrict s l) l\"\n  by (auto simp: Seq_def hfunction_restr intro: Ord_trans)\n\nlemma Seq_ins: \"\\<lbrakk>Seq s k; ~ k <: hdomain s\\<rbrakk> \\<Longrightarrow> Seq (s \\<triangleleft> \\<langle>k, y\\<rangle>) (succ k)\"\n  by (auto simp: Seq_def hrelation_def succ_def hfunction_def hdomainI)\n\ndefinition insf :: \"hf \\<Rightarrow> hf \\<Rightarrow> hf \\<Rightarrow> hf\"\n  where \"insf s k y \\<equiv> nonrestrict s \\<lbrace>k\\<rbrace> \\<triangleleft> \\<langle>k, y\\<rangle>\"\n\nlemma hfunction_insf: \"hfunction s \\<Longrightarrow> hfunction (insf s k y)\"\n  by (auto simp: insf_def hfunction_def nonrestrict_def hmem_not_refl)\n\n\n\nlemma Seq_succ_iff: \"Seq s (succ k) \\<longleftrightarrow> Seq s k \\<and> (\\<exists>y. \\<langle>k, y\\<rangle> <: s)\"\n  apply (auto simp: Seq_def hdomain_def)\n  apply (metis hfst_conv, blast)\n  done\n\nlemma nonrestrictD: \"a \\<^bold>\\<in> nonrestrict s X \\<Longrightarrow> a \\<^bold>\\<in> s\"\n  by (auto simp: nonrestrict_def)\n\nlemma hpair_in_nonrestrict_iff [simp]: \"\\<langle>a,b\\<rangle> \\<^bold>\\<in> nonrestrict s X \\<longleftrightarrow> \\<langle>a,b\\<rangle> \\<^bold>\\<in> s \\<and> \\<not> a \\<^bold>\\<in> X\"\n  by (auto simp: nonrestrict_def)\n\nlemma app_nonrestrict_Seq: \"Seq s k \\<Longrightarrow> ~ z <: X \\<Longrightarrow> app (nonrestrict s X) z = app s z\"\n  by (auto simp: Seq_def nonrestrict_def app_def)\n\nlemma app_insf_Seq: \"Seq s k \\<Longrightarrow> app (insf s k y) k = y\"\n  by (metis Seq_def hfunction_insf app_equality hmem_hinsert insf_def)\n\nlemma app_insf2_Seq: \"Seq s k \\<Longrightarrow> k' \\<noteq> k \\<Longrightarrow> app (insf s k y) k' = app s k'\"\n  by (simp add: app_nonrestrict_Seq insf_def app_ins2)\n\nlemma app_insf_Seq_if: \"Seq s k \\<Longrightarrow> app (insf s k y) k' = (if k' = k then y else app s k')\"\n  by (metis app_insf2_Seq app_insf_Seq)\n\nlemma Seq_imp_eq_app: \"\\<lbrakk>Seq s d; \\<langle>x,y\\<rangle> \\<^bold>\\<in> s\\<rbrakk> \\<Longrightarrow> app s x = y\"\n  by (metis Seq_def app_equality)\n\nlemma Seq_iff_app: \"\\<lbrakk>Seq s d; x \\<^bold>\\<in> d\\<rbrakk> \\<Longrightarrow> \\<langle>x,y\\<rangle> \\<^bold>\\<in> s \\<longleftrightarrow> app s x = y\"\n  by (auto simp: Seq_def hdomain_def app_equality)\n\nlemma Exists_iff_app: \"Seq s d \\<Longrightarrow> x \\<^bold>\\<in> d \\<Longrightarrow> (\\<exists>y. \\<langle>x, y\\<rangle> \\<^bold>\\<in> s & P y) = P (app s x)\"\n  by (metis Seq_iff_app)\n\n\n\ndefinition ord_rec_Seq :: \"hf \\<Rightarrow> (hf \\<Rightarrow> hf) \\<Rightarrow> hf \\<Rightarrow> hf \\<Rightarrow> hf \\<Rightarrow> bool\"\n  where\n   \"ord_rec_Seq T G s k y \\<longleftrightarrow>\n        (Seq s k & y = G (app s (\\<Squnion>k)) & app s 0 = T &\n                   (\\<forall>n. succ n \\<^bold>\\<in> k \\<longrightarrow> app s (succ n) = G (app s n)))\"\n\nlemma Seq_succ_insf:\n  assumes s: \"Seq s (succ k)\"  shows \"\\<exists> y. s = insf s k y\"\nproof -\n  obtain y where y: \"\\<langle>k, y\\<rangle> <: s\" by (metis Seq_succ_iff s)\n  hence yuniq: \"\\<forall> y'. \\<langle>k, y'\\<rangle> <: s \\<longrightarrow> y' = y\" using s\n    by (simp add: Seq_def hfunction_def)\n  { fix z\n    assume z: \"z <: s\"\n    then obtain u v where uv: \"z = \\<langle>u, v\\<rangle>\" using s\n      by (metis Seq_def hrelation_def is_hpair_def)\n    hence \"z <: insf s k y\"\n      by (metis hemptyE hmem_hinsert hpair_in_nonrestrict_iff insf_def yuniq z)\n  }\n  note left2right = this\n  show ?thesis\n    proof\n      show \"s = insf s k y\"\n        by (rule hf_equalityI) (metis hmem_hinsert insf_def left2right nonrestrictD y)\n    qed\nqed\n\nlemma ord_rec_Seq_succ_iff:\n  assumes k: \"Ord k\" and knz: \"k \\<noteq> 0\"\n  shows \"ord_rec_Seq T G s (succ k) z \\<longleftrightarrow> (\\<exists> s' y. ord_rec_Seq T G s' k y & z = G y & s = insf s' k y)\"\nproof\n  assume os: \"ord_rec_Seq T G s (succ k) z\"\n  show \"\\<exists>s' y. ord_rec_Seq T G s' k y \\<and> z = G y \\<and> s = insf s' k y\"\n    apply (rule_tac x=s in exI)  using os k knz\n    apply (auto simp: Seq_insf ord_rec_Seq_def app_insf_Seq app_insf2_Seq\n                          hmem_succ_ne hmem_ne hmem_Sup_ne Seq_succ_iff hmem_0_Ord)\n    apply (metis Ord_pred)\n    apply (metis Ord_pred Seq_succ_iff Seq_succ_insf app_insf_Seq)\n    done\nnext\n  assume ok: \"\\<exists>s' y. ord_rec_Seq T G s' k y \\<and> z = G y \\<and> s = insf s' k y\"\n  thus \"ord_rec_Seq T G s (succ k) z\" using ok k knz\n    by (auto simp: ord_rec_Seq_def app_insf_Seq_if hmem_ne hmem_succ_ne Seq_insf)\nqed\n\nlemma ord_rec_Seq_functional:\n   \"Ord k \\<Longrightarrow> k \\<noteq> 0 \\<Longrightarrow> ord_rec_Seq T G s k y \\<Longrightarrow> ord_rec_Seq T G s' k y' \\<Longrightarrow> y' = y\"\nproof (induct k arbitrary: y y' s s' rule: Ord_induct2)\n  case 0 thus ?case\n    by (simp add: ord_rec_Seq_def)\nnext\n  case (succ k) show ?case\n    proof (cases \"k=0\")\n      case True thus ?thesis using succ\n        by (auto simp: ord_rec_Seq_def)\n    next\n      case False\n      thus ?thesis using succ\n        by (auto simp: ord_rec_Seq_succ_iff)\n    qed\nqed\n\ndefinition ord_recp :: \"hf \\<Rightarrow> (hf \\<Rightarrow> hf) \\<Rightarrow> (hf \\<Rightarrow> hf) \\<Rightarrow> hf \\<Rightarrow> hf \\<Rightarrow> bool\"\n  where\n   \"ord_recp T G H x y =\n    (if x=0 then y = T\n     else\n       if Ord(x) then \\<exists> s. ord_rec_Seq T G s x y\n       else y = H x)\"\n\nlemma ord_recp_functional: \"ord_recp T G H x y \\<Longrightarrow> ord_recp T G H x y' \\<Longrightarrow> y' = y\"\n  by (auto simp: ord_recp_def ord_rec_Seq_functional split: split_if_asm)\n\nlemma ord_recp_succ_iff:\n  assumes k: \"Ord k\" shows \"ord_recp T G H (succ k) z \\<longleftrightarrow> (\\<exists>y. z = G y & ord_recp T G H k y)\"\nproof (cases \"k=0\")\n  case True thus ?thesis\n    by (simp add: ord_recp_def ord_rec_Seq_def) (metis Seq_0 Seq_insf app_insf_Seq)\nnext\n  case False\n  thus ?thesis using k\n    by (auto simp: ord_recp_def ord_rec_Seq_succ_iff)\nqed\n\ndefinition ord_rec :: \"hf \\<Rightarrow> (hf \\<Rightarrow> hf) \\<Rightarrow> (hf \\<Rightarrow> hf) \\<Rightarrow> hf \\<Rightarrow> hf\"\n  where\n   \"ord_rec T G H x = (THE y. ord_recp T G H x y)\"\n\nlemma ord_rec_0 [simp]: \"ord_rec T G H 0 = T\"\n  by (simp add: ord_recp_def ord_rec_def)\n\nlemma ord_recp_total: \"\\<exists>y. ord_recp T G H x y\"\nproof (cases \"Ord x\")\n  case True thus ?thesis\n  proof (induct x rule: Ord_induct2)\n    case 0 thus ?case\n      by (simp add: ord_recp_def)\n  next\n    case (succ x) thus ?case\n      by (metis ord_recp_succ_iff)\n  qed\nnext\n  case False thus ?thesis\n    by (auto simp: ord_recp_def)\nqed\n\nlemma ord_rec_succ [simp]:\n  assumes k: \"Ord k\" shows \"ord_rec T G H (succ k) = G (ord_rec T G H k)\"\nproof -\n  from ord_recp_total [of T G H k]\n  obtain y where \"ord_recp T G H k y\" by auto\n  thus ?thesis using k\n    apply (simp add: ord_rec_def ord_recp_succ_iff)\n    apply (rule theI2)\n    apply (auto dest: ord_recp_functional)\n    done\nqed\n\nlemma ord_rec_non [simp]: \"~ Ord x \\<Longrightarrow> ord_rec T G H x = H x\"\n  by (metis Ord_0 ord_rec_def ord_recp_def the_equality)\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/Ordinal.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916170039421, "lm_q2_score": 0.8221891370573388, "lm_q1q2_score": 0.7098712085270115}}
{"text": "(* Author: Max P.L. Haslbeck, Bohua Zhan\n*)\n\ntheory MergeSort\n  imports \"Auto2_HOL.Auto2_Main\"\nbegin\n\nsection \\<open>Simple functional version\\<close>\n\nfun merge_list :: \"('a::linorder) list \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where\n  \"merge_list xs ys = (\n     if xs = [] then ys else if ys = [] then xs\n     else if last xs \\<ge> last ys then merge_list (butlast xs) ys @ [last xs]\n     else merge_list xs (butlast ys) @ [last ys])\"\nsetup \\<open>add_rewrite_rule @{thm merge_list.simps}\\<close>\n\nlemma merge_list_simps' [rewrite]:\n  \"merge_list [] ys = ys\"\n  \"merge_list xs [] = xs\"\n  \"merge_list (xs @ [x]) (ys @ [y]) =\n    (if x \\<ge> y then merge_list xs (ys @ [y]) @ [x]\n               else merge_list (xs @ [x]) ys @ [y])\" by auto2+\nsetup \\<open>del_prfstep_thm @{thm merge_list.simps}\\<close>\n\nlemma merge_list_length [rewrite]:\n  \"length (merge_list xs ys) = length xs + length ys\"\n@proof @fun_induct \"merge_list xs ys\"\n  @case \"xs = []\" @case \"ys = []\"\n  @have \"xs = butlast xs @ [last xs]\"\n  @have \"ys = butlast ys @ [last ys]\"\n@qed\n\nlemma merge_list_correct_mset [rewrite]:\n  \"mset (merge_list xs ys) = mset xs + mset ys\"\n@proof @fun_induct \"merge_list xs ys\"\n  @case \"xs = []\" @case \"ys = []\"\n  @have \"xs = butlast xs @ [last xs]\"\n  @have \"ys = butlast ys @ [last ys]\"\n@qed\n\nlemma merge_list_correct_set [rewrite]:\n  \"set (merge_list xs ys) = set xs \\<union> set ys\"\n@proof\n  @have \"set (merge_list xs ys) = set_mset (mset (merge_list xs ys))\"\n@qed\n\nlemma merge_list_sorted [forward]:\n  \"sorted xs \\<Longrightarrow> sorted ys \\<Longrightarrow> sorted (merge_list xs ys)\"\n@proof @fun_induct \"merge_list xs ys\"\n  @case \"xs = []\" @case \"ys = []\"\n  @have \"xs = butlast xs @ [last xs]\"\n  @have \"ys = butlast ys @ [last ys]\"\n@qed\n\nfun merge_sort_fun :: \"'a::linorder list \\<Rightarrow> 'a list\" where\n  \"merge_sort_fun xs =\n     (let n = length xs in\n      (if n \\<le> 1 then xs\n       else\n        let as = take (n div 2) xs;\n            bs = drop (n div 2) xs;\n            as' = merge_sort_fun as;\n            bs' = merge_sort_fun bs;\n            r = merge_list as' bs'\n        in r))\"\n\nlemma sort_length_le1 [rewrite]: \"length xs \\<le> 1 \\<Longrightarrow> sort xs = xs\"\n@proof\n  @case \"xs = []\" @have \"xs = hd xs # tl xs\" @case \"tl xs = []\"\n@qed\n\nlemma mergesort_fun_correct [rewrite]:\n  \"merge_sort_fun xs = sort xs\"\n@proof @fun_induct \"merge_sort_fun xs\"\n  @unfold \"merge_sort_fun xs\"\n  @case \"length xs \\<le> 1\"\n  @let \"l1 = length xs div 2\"\n  @have \"mset (take l1 xs) + mset (drop l1 xs) = mset xs\" @with\n    @have \"take l1 xs @ drop l1 xs = xs\"\n  @end\n@qed\n\nlemma mergesort_fun_length [rewrite]:\n  \"length (merge_sort_fun xs) = length xs\" by auto2\n\nsection \\<open>Actual functional version\\<close>\n\nfunction mergeinto_fun :: \"nat \\<Rightarrow> nat \\<Rightarrow> 'a::linorder list \\<Rightarrow> 'a list \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where\n  \"mergeinto_fun 0 0 a b c = c\"\n| \"mergeinto_fun (Suc la) 0 a b c = list_update (mergeinto_fun la 0 a b c) la (a ! la)\"\n| \"mergeinto_fun 0 (Suc lb) a b c = list_update (mergeinto_fun 0 lb a b c) lb (b ! lb)\"\n| \"mergeinto_fun (Suc la) (Suc lb) a b c =\n    (if a ! la \\<ge> b ! lb then\n       list_update (mergeinto_fun la (Suc lb) a b c) (Suc (la+lb)) (a ! la)\n     else\n       list_update (mergeinto_fun (Suc la) lb a b c) (Suc (la+lb)) (b ! lb))\"\nby pat_completeness auto\ntermination by (relation \"Wellfounded.measure (\\<lambda>(la, lb, a, b, c). la + lb)\") auto\n\nsetup \\<open>fold add_rewrite_rule @{thms mergeinto_fun.simps}\\<close>\n\nlemma mergeinto_fun_length [rewrite]:\n  \"length (mergeinto_fun la lb a b c) = length c\"\n@proof @fun_induct \"mergeinto_fun la lb a b c\" @qed\n\nlemma mergeinto_fun_to_merge_list_induct [backward]:\n  \"length c = length a + length b \\<Longrightarrow>\n  la \\<le> length a \\<Longrightarrow> lb \\<le> length b \\<Longrightarrow>\n  take (la + lb) (mergeinto_fun la lb a b c) = merge_list (take la a) (take lb b)\"\n@proof @fun_induct \"mergeinto_fun la lb a b c\" @with\n  @subgoal \"(la = Suc la, lb = Suc lb, a = a, b = b, c = c)\"\n    @have \"Suc (la + Suc lb) \\<le> length c\" @with\n      @have \"Suc (la + lb) < length c\"\n    @end\n    @case \"a ! la \\<ge> b ! lb\"\n  @endgoal @end\n@qed\n\nlemma mergeinto_fun_to_merge_list [rewrite]:\n  \"length c = length a + length b \\<Longrightarrow>\n   mergeinto_fun (length a) (length b) a b c = merge_list a b\"\n@proof\n  @let \"res = mergeinto_fun (length a) (length b) a b c\"\n  @have \"take (length a + length b) res = merge_list (take (length a) a) (take (length b) b)\"\n@qed\n\nend\n", "meta": {"author": "bzhan", "repo": "Imperative_HOL_Time", "sha": "09f9bc7a7cf177d3adf1e9ce6adae09a85ebe5ec", "save_path": "github-repos/isabelle/bzhan-Imperative_HOL_Time", "path": "github-repos/isabelle/bzhan-Imperative_HOL_Time/Imperative_HOL_Time-09f9bc7a7cf177d3adf1e9ce6adae09a85ebe5ec/Functional/MergeSort.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8633916205190225, "lm_q2_score": 0.8221891327004132, "lm_q1q2_score": 0.7098712076553394}}
{"text": "\\<^marker>\\<open>creator \"Kevin Kappelmann\"\\<close>\nsubsection \\<open>Symmetric\\<close>\ntheory SBinary_Relations_Symmetric\n  imports\n    Pairs\nbegin\n\ndefinition \"symmetric D R \\<equiv> \\<forall>x y \\<in> D. \\<langle>x, y\\<rangle> \\<in> R \\<longrightarrow> \\<langle>y, x\\<rangle> \\<in> R\"\n\nlemma symmetricI [intro]:\n  assumes \"\\<And>x y. x \\<in> D \\<Longrightarrow> y \\<in> D \\<Longrightarrow> \\<langle>x, y\\<rangle> \\<in> R \\<Longrightarrow> \\<langle>y, x\\<rangle> \\<in> R\"\n  shows \"symmetric D R\"\n  using assms unfolding symmetric_def by blast\n\nlemma symmetricD:\n  assumes \"symmetric D R\"\n  and \"x \\<in> D\" \"y \\<in> D\"\n  and \"\\<langle>x, y\\<rangle> \\<in> R\"\n  shows \"\\<langle>y, x\\<rangle> \\<in> R\"\n  using assms unfolding symmetric_def by blast\n\n\nend", "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/HOTG/Binary_Relations/Properties/SBinary_Relations_Symmetric.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391624034103, "lm_q2_score": 0.8221891283434876, "lm_q1q2_score": 0.7098712067836672}}
{"text": "section \\<open>Parity by counting inversions abstractly\\<close>\n\ntheory Parity_Inversions\nimports Parity_Swap\nbegin\n\ntext \\<open>The recursive definition of parity is equivalent to the evenness of the number of\n      inversions, expressed abstractly.\\<close>\n\ndefinition\n  inversions :: \"nat list \\<Rightarrow> (nat \\<times> nat) set\"\nwhere\n  \"inversions xs \\<equiv> {(i,j). j < length xs \\<and> i < j \\<and> xs ! i > xs ! j}\"\n\nlemma inversions_example:\n  \"inversions [0,2,4,3,1] = {(1,4),(2,3),(2,4),(3,4)}\"\n  unfolding inversions_def\n  apply (intro equalityI subsetI; clarsimp)\n  apply (case_tac b; clarsimp; rename_tac b)+\n  done\n\nlemma map_prod_comprehension:\n  \"map_prod f g ` {(i,j). P i j} = {(f i, g j) | i j. P i j}\"\n  by blast\n\nlemma inj_on_same_card: \"inj_on f (Collect P) \\<Longrightarrow> card {f i | i. P i} = card {i. P i}\"\n  by (rule bij_betw_same_card[of f, symmetric]) (auto simp: bij_betw_def)\n\nlemma set_prod_empty: \"(\\<And>i j. \\<not> P i j) \\<Longrightarrow> {(i,j). P i j} = {}\"\n  by blast\n\nlemma prod_split: \"(x,y) = z \\<Longrightarrow> x = fst z \\<and> y = snd z\"\n  by auto\n\nlemma inversions_nil [simp]: \"inversions [] = {}\"\n  by (simp add: inversions_def)\n\nlemma inversions_cons:\n  \"inversions (x # ys) = {(0, Suc j) | j. j < length ys \\<and> x > ys ! j}\n                       \\<union> map_prod Suc Suc ` inversions ys\"\n  by (auto simp add: inversions_def map_prod_comprehension less_Suc_eq_0_disj)\n\nlemma inversions_subset: \"inversions xs \\<subseteq> {0 ..< length xs} \\<times> {0 ..< length xs}\"\n  by (rule subsetI; clarsimp simp: inversions_def)\n\nlemma inversions_finite [simp]: \"finite (inversions xs)\"\n  by (rule finite_subset[OF inversions_subset]; simp)\n\nlemma card_inversions_cons [simp]:\n  \"card (inversions (x # ys)) = length [y \\<leftarrow> ys. x > y] + card (inversions ys)\"\n  apply (subst inversions_cons)\n  apply (subst card_Un_disjoint)\n     apply auto[3]\n  apply (subst card_image)\n   apply (metis inj_Suc inj_eq inj_onI prod.inj_map)\n  apply simp\n  apply (subst inj_on_same_card)\n   apply (meson Pair_inject Suc_inject inj_onI)\n  apply (simp add: length_filter_conv_card)\n  done\n\nlemma parity: \"parity = even \\<circ> card \\<circ> inversions\" (is \"?p = ?i\")\n  proof (rule ext)\n    fix xs show \"?p xs = ?i xs\" by (induct xs) auto\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_Inversions.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916134888614, "lm_q2_score": 0.8221891370573388, "lm_q1q2_score": 0.7098712056369503}}
{"text": "(*  Title:      CCL/Gfp.thy\n    Author:     Lawrence C Paulson, Cambridge University Computer Laboratory\n    Copyright   1992  University of Cambridge\n*)\n\nsection {* Greatest fixed points *}\n\ntheory Gfp\nimports Lfp\nbegin\n\ndefinition\n  gfp :: \"['a set\\<Rightarrow>'a set] \\<Rightarrow> 'a set\" where -- \"greatest fixed point\"\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 {* Definition forms of @{text \"gfp_Tarski\"}, to control unfolding *}\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": "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/Gfp.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916205190225, "lm_q2_score": 0.8221891239865619, "lm_q1q2_score": 0.7098712001318732}}
{"text": "theory Bipartite_Graphs imports Undirected_Graph_Walks\nbegin\n\nsection \\<open>Bipartite Graphs \\<close>\n\ntext \\<open>An introductory library for reasoning on bipartite graphs.\\<close>\n\nsubsection \\<open>Bipartite Set Up \\<close>\ntext \\<open>All \"edges\", i.e. pairs, between any two sets \\<close>\ndefinition all_bi_edges :: \"'a set \\<Rightarrow> 'a set \\<Rightarrow> 'a edge set\" where\n\"all_bi_edges X Y \\<equiv> mk_edge ` (X \\<times> Y)\"\n\nlemma all_bi_edges_alt: \n  assumes \"X \\<inter> Y = {}\"\n  shows \"all_bi_edges X Y = {e . card e = 2 \\<and> e \\<inter> X \\<noteq> {} \\<and> e \\<inter> Y \\<noteq> {}}\"\n  unfolding all_bi_edges_def \nproof (intro subset_antisym subsetI)\n  fix e assume \"e \\<in> mk_edge ` (X \\<times> Y)\"\n  then obtain v1 v2 where \"e = { v1, v2}\" and  \"v1 \\<in> X\" and \"v2 \\<in> Y\"\n    by auto\n  then show \"e \\<in> {e. card e = 2 \\<and> e \\<inter> X \\<noteq> {} \\<and> e \\<inter> Y \\<noteq> {}}\" using assms\n    using card_2_iff by blast \nnext \n  fix e' assume assm: \"e' \\<in> {e. card e = 2 \\<and> e \\<inter> X \\<noteq> {} \\<and> e \\<inter> Y \\<noteq> {}}\"\n  then obtain v1 where v1in: \"v1 \\<in> e'\" and \"v1 \\<in> X\"\n    by blast\n  moreover obtain v2 where v2in: \"v2 \\<in> e'\" and \"v2 \\<in> Y\" using assm by blast\n  then have ne: \"v1 \\<noteq> v2\"\n    using assms calculation(2) by blast \n  have \"card e' = 2\" using assm by blast\n  have \"{v1, v2} \\<subseteq> e'\" using v1in v2in by blast\n  then have \"e' = {v1, v2}\" using assm v1in v2in\n    by (metis (no_types, opaque_lifting) \\<open>card e' = 2\\<close> card_2_iff' insertCI ne subsetI subset_antisym) \n  then show \"e' \\<in> mk_edge ` (X \\<times> Y)\"\n    by (simp add: \\<open>v2 \\<in> Y\\<close> calculation(2) in_mk_edge_img) \nqed\n\nlemma all_bi_edges_alt2:  \"all_bi_edges X Y = {{x, y} | x y. x \\<in> X \\<and> y \\<in> Y }\"\n  unfolding all_bi_edges_def \nproof (intro subset_antisym subsetI)\n  fix x assume \"x \\<in> mk_edge ` (X \\<times> Y)\"\n  then obtain a b where \"(a, b) \\<in> (X \\<times> Y)\" and xeq: \"x = mk_edge (a, b) \" by blast\n  then show \"x \\<in> {{x, y} |x y. x \\<in> X \\<and> y \\<in> Y}\"\n    by auto \nnext\n  fix x assume \"x \\<in> {{x, y} |x y. x \\<in> X \\<and> y \\<in> Y}\"\n  then obtain a b where xeq: \"x = {a, b}\" and \"a \\<in> X\" and \"b \\<in> Y\"\n    by blast\n  then have \"(a, b) \\<in> (X \\<times> Y)\" by auto\n  then show \"x \\<in> mk_edge ` (X \\<times> Y)\"  using in_mk_edge_img xeq by metis \nqed\n\nlemma all_bi_edges_wf: \"e \\<in> all_bi_edges X Y \\<Longrightarrow> e \\<subseteq> X \\<union> Y\" \n  by (auto simp add: all_bi_edges_alt2)\n\nlemma all_bi_edges_2: \"X \\<inter> Y = {} \\<Longrightarrow> e \\<in> all_bi_edges X Y \\<Longrightarrow> card e = 2\" \n  using card_2_iff by (auto simp add: all_bi_edges_alt2)\n\nlemma all_bi_edges_main: \"X \\<inter> Y = {} \\<Longrightarrow> all_bi_edges X Y \\<subseteq> all_edges (X \\<union> Y)\"\n  unfolding  all_edges_def using all_bi_edges_wf all_bi_edges_2 by blast  \n\nlemma all_bi_edges_finite: \"finite X \\<Longrightarrow> finite Y \\<Longrightarrow> finite (all_bi_edges X Y)\"\n  by (simp add: all_bi_edges_def)\n\nlemma all_bi_edges_not_ssX: \"X \\<inter> Y = {} \\<Longrightarrow> e \\<in> all_bi_edges X Y \\<Longrightarrow> \\<not> e \\<subseteq> X\"\n  by (auto simp add: all_bi_edges_alt)\n\nlemma all_bi_edges_sym: \"all_bi_edges X Y = all_bi_edges Y X\"\n  by (auto simp add: all_bi_edges_alt2)\n\nlemma all_bi_edges_not_ssY: \"X \\<inter> Y = {} \\<Longrightarrow> e \\<in> all_bi_edges X Y \\<Longrightarrow> \\<not> e \\<subseteq> Y\"\n  by (auto simp add: all_bi_edges_alt)\n\nlemma card_all_bi_edges: \n  assumes \"finite X\" \"finite Y\"\n  assumes \"X \\<inter> Y = {}\"\n  shows \"card (all_bi_edges X Y) = card X * card Y\"\nproof -\n  have \"card (all_bi_edges X Y) = card (X \\<times> Y)\"\n    unfolding all_bi_edges_def using inj_on_mk_edge assms card_image by blast \n  thus ?thesis using card_cartesian_product by auto\nqed\n\nlemma (in sgraph) all_edges_between_bi_subset: \"mk_edge ` all_edges_between X Y \\<subseteq> all_bi_edges X Y\"\n  by (auto simp: all_edges_between_def all_bi_edges_def)\n\nsubsection \\<open> Bipartite Graph Locale \\<close>\n\ntext \\<open>For reasoning purposes, it is useful to explicitly label the two sets of vertices as X and Y. \nThese are parameters in the locale\\<close>\n\nlocale bipartite_graph = graph_system + \n  fixes X Y :: \"'a set\"\n  assumes partition: \"partition_on V {X, Y}\"\n  assumes ne: \"X \\<noteq> Y\"\n  assumes edge_betw: \"e \\<in> E \\<Longrightarrow> e \\<in> all_bi_edges X Y\"\nbegin\n\nlemma part_intersect_empty: \"X \\<inter> Y = {}\"\n  using partition_onD2 partition disjointD ne\n  by blast\n\nlemma X_not_empty: \"X \\<noteq> {}\"\n  using partition partition_onD3 by auto\n\nlemma Y_not_empty: \"Y \\<noteq> {}\"\n  using partition partition_onD3 by auto\n\nlemma XY_union: \"X \\<union> Y = V\"\n  using partition partition_onD1 by auto\n\nlemma card_edges_two: \"e \\<in> E \\<Longrightarrow> card e = 2\"\n  using edge_betw all_bi_edges_alt part_intersect_empty by auto \n\nlemma partitions_ss: \"X \\<subseteq> V\" \"Y \\<subseteq> V\"\n  using XY_union by auto\n\nend\n\ntext \\<open> By definition, we say an edge must be between X and Y, i.e. contains two vertices \\<close>\nsublocale bipartite_graph \\<subseteq> sgraph\n  using card_edges_two by (unfold_locales)\n\ncontext bipartite_graph\nbegin\n\nabbreviation \"density \\<equiv> edge_density X Y\"\n\nlemma bipartite_sym: \"bipartite_graph V E Y X\"\n  using partition ne edge_betw all_bi_edges_sym \n  by (unfold_locales) (auto simp add: insert_commute)\n\nlemma X_verts_not_adj: \n  assumes \"x1 \\<in> X\" \"x2 \\<in> X\"\n  shows \"\\<not> vert_adj x1 x2\"\nproof (rule ccontr, simp add: vert_adj_def)\n  assume \"{x1, x2} \\<in> E\"\n  then have \"\\<not> {x1, x2} \\<subseteq> X\" \n    using all_bi_edges_not_ssX edge_betw part_intersect_empty by auto \n  then show False using assms by auto\nqed\n\nlemma Y_verts_not_adj: \n  assumes \"y1 \\<in> Y\" \"y2 \\<in> Y\"\n  shows \"\\<not> vert_adj y1 y2\"\nproof -\n  interpret sym: bipartite_graph V E Y X using bipartite_sym by simp\n  show ?thesis using sym.X_verts_not_adj\n    by (simp add: assms(1) assms(2)) \nqed\n\nlemma X_vert_adj_Y: \"x \\<in>X \\<Longrightarrow> vert_adj x y \\<Longrightarrow> y \\<in> Y\"\n  using X_verts_not_adj XY_union vert_adj_imp_inV by blast \n\nlemma Y_vert_adj_X: \"y \\<in>Y \\<Longrightarrow> vert_adj y x \\<Longrightarrow> x \\<in> X\"\n  using Y_verts_not_adj XY_union vert_adj_imp_inV by blast \n\nlemma neighbors_ss_eq_neighborhoodX: \"v \\<in> X \\<Longrightarrow> neighborhood v = neighbors_ss v Y\"\n  unfolding neighborhood_def neighbors_ss_def \n  by(auto simp add: X_vert_adj_Y vert_adj_imp_inV)\n\nlemma neighbors_ss_eq_neighborhoodY: \"v \\<in> Y \\<Longrightarrow> neighborhood v = neighbors_ss v X\"\n  unfolding neighborhood_def neighbors_ss_def \n  by(auto simp add: Y_vert_adj_X vert_adj_imp_inV)\n\nlemma neighborhood_subset_oppX: \"v \\<in> X \\<Longrightarrow> neighborhood v \\<subseteq> Y\"\n  using neighbors_ss_eq_neighborhoodX neighbors_ss_def by auto\n\nlemma neighborhood_subset_oppY: \"v \\<in> Y \\<Longrightarrow> neighborhood v \\<subseteq> X\"\n  using neighbors_ss_eq_neighborhoodY neighbors_ss_def by auto\n\nlemma degree_neighbors_ssX: \"v \\<in> X \\<Longrightarrow> degree v = card (neighbors_ss v Y)\"\n  using neighbors_ss_eq_neighborhoodX alt_deg_neighborhood by auto\n\nlemma degree_neighbors_ssY: \"v \\<in> Y \\<Longrightarrow> degree v = card (neighbors_ss v X)\"\n  using neighbors_ss_eq_neighborhoodY alt_deg_neighborhood by auto\n\ndefinition is_bicomplete:: \"bool\" where\n\"is_bicomplete \\<equiv> E = all_bi_edges X Y\"\n\nlemma edge_betw_indiv: \n  assumes \"e \\<in> E\"\n  obtains x y where \"x \\<in> X \\<and> y \\<in> Y \\<and> e = {x, y}\"\nproof -\n  have \"e \\<in> {{x, y} | x y. x \\<in> X \\<and> y \\<in> Y }\"\n    using edge_betw all_bi_edges_alt2 assms by blast\n  thus ?thesis\n    using that by auto\nqed\n\nlemma edges_between_equals_edge_set: \"mk_edge ` (all_edges_between X Y) = E\"\n  by (simp add: all_edges_between_set, intro subset_antisym subsetI, auto) (metis edge_betw_indiv)\n\ntext \\<open> Lemmas for reasoning on walks and paths in a bipartite graph \\<close>\nlemma walk_alternates:\n  assumes \"is_walk w\"\n  assumes \"Suc i < length w\" \"i \\<ge> 0\"\n  shows \"w ! i \\<in> X \\<longleftrightarrow> w ! (i + 1) \\<in> Y\"\nproof -\n  have \"{w ! i, w ! (i +1)} \\<in> E\" using is_walk_index assms by auto\n  then show ?thesis\n    using X_vert_adj_Y not_vert_adj Y_vert_adj_X vert_adj_sym by blast \nqed\n\ntext \\<open>A useful reasoning pattern to mimic \"wlog\" statements for properties that are symmetric\nis to interpret the symmetric bipartite graph and then directly apply the lemma proven earlier\\<close>\nlemma walk_alternates_sym: \n  assumes \"is_walk w\"\n  assumes \"Suc i < length w\" \"i \\<ge> 0\"\n  shows \"w ! i \\<in> Y \\<longleftrightarrow> w ! (i + 1) \\<in> X\"\nproof -\n  interpret sym: bipartite_graph V E Y X using bipartite_sym by simp\n  show ?thesis using sym.walk_alternates assms by simp\nqed\n\nlemma walk_length_even: \n  assumes \"is_walk w\"\n  assumes \"hd w \\<in> X\" and \"last w \\<in> X\"\n  shows \"even (walk_length w)\"\n  using assms \nproof (induct \"length w\" arbitrary: w rule: nat_induct2)\n  case 0\n  then show ?case by (auto simp add: is_walk_def)\nnext\n  case 1\n  then have \"walk_length w = 0\" using walk_length_conv by auto\n  then show ?case by simp\nnext\n  case (step n)\n  then show ?case proof (cases \"n = 0\")\n    case True\n    then have \"length w = 2\" using step by simp\n    then have \"hd w \\<in> X \\<Longrightarrow> last w \\<in> Y\" using walk_alternates hd_conv_nth last_conv_nth\n      by (metis add_0 add_diff_cancel_right' less_2_cases_iff list.size(3) nat_1_add_1 step.prems(1) \n          zero_le zero_neq_numeral)\n    then show ?thesis\n      using part_intersect_empty step.prems(2) step.prems(3) by blast \n  next\n    case False\n    have IH: \"(\\<And>w. n = length w \\<Longrightarrow> is_walk w \\<Longrightarrow> hd w \\<in> X \\<Longrightarrow> last w \\<in> X \\<Longrightarrow> even (walk_length w))\" \n      using step by simp\n    obtain w1 w2 where weq: \"w = w1@w2\" and w1: \"w1 = take n w\" and w2: \"w2 = drop n w\"\n      by simp\n    then have ne: \"w1 \\<noteq> []\" using False is_walk_not_empty2 step.prems(1) by fastforce \n    then have w1_walk: \"is_walk w1\" using w1 is_walk_take False\n      by (metis nat_le_linear neq0_conv step.prems(1) take_all) \n    have hdw1: \"hd w1 \\<in> X\" using step ne weq by auto\n    then have w1n: \"length w1 = n\" using step length_take w1 by auto\n    then have \"length w2 = 2\" using step length_drop\n      by (simp add: w2) \n    have \"last w = w ! (n + 1)\" using step last_conv_nth is_walk_not_empty\n      by (metis add.left_commute diff_add_inverse nat_1_add_1) \n    then have \"w ! n \\<in> Y\" using step by (simp add: walk_alternates_sym) \n    then have \"w ! (n - 1) \\<in> X\" using False walk_alternates step by simp\n    then have \"last w1 \\<in> X\" using step last_conv_nth[of w1] ne w1n\n      by (metis last_list_update list_update_id take_update_swap w1) \n    then have \"even (walk_length w1)\" using w1_walk w1n hdw1 IH[of w1] by simp\n    then have \"even (walk_length w1 + 2)\" by simp\n    then show ?thesis using walk_length_conv weq step\n      by (simp add: False w1n) \n  qed\nqed\n\nlemma walk_length_even_sym: \n  assumes \"is_walk w\"\n  assumes \"hd w \\<in> Y\" \n  assumes \"last w \\<in> Y\"\n  shows \"even (walk_length w)\"\nproof -\n  interpret sym: bipartite_graph V E Y X using bipartite_sym by simp\n  show ?thesis using sym.walk_length_even assms by auto\nqed\n\nlemma walk_length_odd: \n  assumes \"is_walk w\"\n  assumes \"hd w \\<in> X\" and \"last w \\<in> Y\"\n  shows \"odd (walk_length w)\"\n  using assms \nproof (cases \"length w \\<ge> 2\")\n  case True\n  then have hdin: \"hd (tl w) \\<in> Y\" using walk_alternates hd_conv_nth\n    by (metis (mono_tags, lifting) Suc_1 Suc_less_eq2 assms(1) assms(2) is_walk_not_empty2 is_walk_tl \n        le_neq_implies_less le_numeral_extra(3) length_greater_0_conv less_Suc_eq nth_tl \n        numeral_1_eq_Suc_0 numerals(1) plus_nat.add_0) \n  have w: \"is_walk (tl w)\" using assms True is_walk_tl by auto\n  have last: \"last (tl w) \\<in> Y\" using assms(3) by (simp add: is_walk_not_empty last_tl w) \n  then have ev: \"even (walk_length (tl w))\" using hdin w  walk_length_even_sym[of \"tl w\"] by auto\n  then have \"walk_length w = walk_length (tl w) + 1\" using True walk_length_conv by auto\n  then show ?thesis using ev by simp\nnext\n  case False\n  have \"length w \\<noteq> 0\" using is_walk_not_empty assms by simp\n  then have \"length w = 1\" using False by linarith\n  then have \"hd w = last w\"\n    using \\<open>length w \\<noteq> 0\\<close> hd_conv_nth last_conv_nth by fastforce \n  then have \"hd w \\<in> X \\<Longrightarrow> last w \\<notin> Y\" using part_intersect_empty by auto \n  then show ?thesis using assms by simp\nqed\n\nlemma walk_length_odd_sym: \n  assumes \"is_walk w\"\n  assumes \"hd w \\<in> Y\" and \"last w \\<in> X\"\n  shows \"odd (walk_length w)\"\nproof -\n  interpret sym: bipartite_graph V E Y X using bipartite_sym by simp\n  show ?thesis using assms sym.walk_length_odd by simp\nqed\n\nlemma walk_length_even_iff: \n  assumes \"is_walk w\"\n  shows \"even (walk_length w) \\<longleftrightarrow> (hd w \\<in> X \\<and> last w \\<in> X) \\<or> (hd w \\<in> Y \\<and> last w \\<in> Y)\"\nproof (intro iffI)\n  assume ev: \"even (walk_length w)\"\n  show \"hd w \\<in> X \\<and> last w \\<in> X \\<or> hd w \\<in> Y \\<and> last w \\<in> Y\"\n  proof (rule ccontr)\n    assume \"\\<not> ((hd w \\<in> X \\<and> last w \\<in> X) \\<or> (hd w \\<in> Y \\<and> last w \\<in> Y))\"\n    then have \"(hd w \\<notin> X \\<or> last w \\<notin> X) \\<and> (hd w \\<notin> Y \\<or> last w \\<notin> Y)\" by simp\n    then have \"(hd w \\<in> Y \\<or> last w \\<in> Y) \\<and> (hd w \\<in> X \\<or> last w \\<in> X)\" using part_intersect_empty\n      using XY_union assms is_walk_wf_hd is_walk_wf_last by auto \n    then have split: \"(hd w \\<in> X \\<and> last w \\<in> Y) \\<or> (hd w \\<in> Y \\<and> last w \\<in> X)\" \n      using part_intersect_empty by auto\n    have o1: \"(hd w \\<in> X \\<and> last w \\<in> Y) \\<Longrightarrow> odd (walk_length w)\" using walk_length_odd assms by auto\n    have \"(hd w \\<in> Y \\<and> last w \\<in> X) \\<Longrightarrow> odd (walk_length w)\" using walk_length_odd_sym assms by auto\n    then show False using split ev o1 by auto\n  qed\nnext \n  show \"(hd w \\<in> X \\<and> last w \\<in> X) \\<or> (hd w \\<in> Y \\<and> last w \\<in> Y) \\<Longrightarrow> even (walk_length w)\" \n    using walk_length_even walk_length_even_sym assms by auto\nqed\n\nlemma walk_length_odd_iff: \n  assumes \"is_walk w\"\n  shows \"odd (walk_length w) \\<longleftrightarrow> (hd w \\<in> X \\<and> last w \\<in> Y) \\<or> (hd w \\<in> Y \\<and> last w \\<in> X)\"\nproof (intro iffI)\n  assume o: \"odd (walk_length w)\"\n  show \"(hd w \\<in> X \\<and> last w \\<in> Y) \\<or> (hd w \\<in> Y \\<and> last w \\<in> X)\"\n  proof (rule ccontr)\n    assume \"\\<not> ((hd w \\<in> X \\<and> last w \\<in> Y) \\<or> (hd w \\<in> Y \\<and> last w \\<in> X))\"\n    then have \"(hd w \\<notin> X \\<or> last w \\<notin> Y) \\<and> (hd w \\<notin> Y \\<or> last w \\<notin> X)\" by simp\n    then have \"(hd w \\<in> Y \\<or> last w \\<in> X) \\<and> (hd w \\<in> X \\<or> last w \\<in> Y)\" using part_intersect_empty\n      using XY_union assms is_walk_wf_hd is_walk_wf_last by auto \n    then have split: \"(hd w \\<in> X \\<and> last w \\<in> X) \\<or> (hd w \\<in> Y \\<and> last w \\<in> Y)\" \n      using part_intersect_empty by auto\n    have e1: \"(hd w \\<in> X \\<and> last w \\<in> X) \\<Longrightarrow> even (walk_length w)\" using walk_length_even assms by auto\n    have \"(hd w \\<in> Y \\<and> last w \\<in> Y) \\<Longrightarrow> even (walk_length w)\" using walk_length_even_sym assms by auto\n    then show False using split o e1 by auto\n  qed\nnext \n  show \"(hd w \\<in> X \\<and> last w \\<in> Y) \\<or> (hd w \\<in> Y \\<and> last w \\<in> X) \\<Longrightarrow> odd (walk_length w)\" \n    using walk_length_odd walk_length_odd_sym assms by auto\nqed\n\ntext \\<open> Classic basic theorem that a bipartite graph must not have any cycles with an odd length \\<close>\nlemma no_odd_cycles:\n  assumes \"is_walk w\"\n  assumes \"odd (walk_length w)\"\n  shows \"\\<not> is_cycle w\"\nproof -\n  have \"(hd w \\<in> X \\<and> last w \\<in> Y) \\<or> (hd w \\<in> Y \\<and> last w \\<in> X)\" using assms walk_length_odd_iff by auto\n  then have \"hd w \\<noteq> last w\" using part_intersect_empty by auto\n  thus ?thesis using is_cycle_def is_closed_walk_def by simp\nqed\n\nend\n\ntext \\<open> A few properties rely on cardinality definitions that require the vertex sets to be finite \\<close>\n\nlocale fin_bipartite_graph = bipartite_graph + fin_graph_system\nbegin\n\nlemma fin_bipartite_sym: \"fin_bipartite_graph V E Y X\"\n  by (intro_locales) (simp add: bipartite_sym bipartite_graph.axioms(2)) \n\nlemma partitions_finite: \"finite X\" \"finite Y\"\n  using partitions_ss finite_subset finV by auto\n\nlemma card_edges_between_set: \"card (all_edges_between X Y) = card E\"\nproof -\n  have \"card (all_edges_between X Y) = card (mk_edge ` (all_edges_between X Y))\"\n    using inj_on_mk_edge using partitions_finite card_image\n    by (metis inj_on_mk_edge part_intersect_empty)\n  then show ?thesis by (simp add: edges_between_equals_edge_set)\nqed\n\nlemma density_simp: \"density = card (E) / ((card X) * (card Y))\"\n  unfolding edge_density_def using card_edges_between_set by auto\n\nlemma edge_size_degree_sumY: \"card E = (\\<Sum>y \\<in> Y . degree y)\"\nproof -\n  have \"(\\<Sum>y \\<in> Y . degree y) = (\\<Sum>y \\<in> Y . card(neighbors_ss y X))\"\n    using degree_neighbors_ssY by (simp)\n  also have \"... = card (all_edges_between X Y)\"\n    using card_all_edges_betw_neighbor\n    by (metis card_all_edges_between_commute partitions_finite(1) partitions_finite(2)) \n  finally show ?thesis\n    by (simp add: card_edges_between_set) \nqed\n\nlemma edge_size_degree_sumX: \"card E = (\\<Sum>y \\<in> X . degree y)\"\nproof -\n  interpret sym: fin_bipartite_graph V E Y X \n    using fin_bipartite_sym by simp\n  show ?thesis using sym.edge_size_degree_sumY by simp\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/Undirected_Graph_Theory/Bipartite_Graphs.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916064586998, "lm_q2_score": 0.8221891261650248, "lm_q1q2_score": 0.7098711904524955}}
{"text": "(* Author: Tobias Nipkow *)\n\nsection \\<open>Association List Update and Deletion\\<close>\n\ntheory AList_Upd_Del\nimports Sorted_Less\nbegin\n\nabbreviation \"sorted1 ps \\<equiv> sorted(map fst ps)\"\n\ntext\\<open>Define own \\<open>map_of\\<close> function to avoid pulling in an unknown\namount of lemmas implicitly (via the simpset).\\<close>\n\nhide_const (open) map_of\n\nfun map_of :: \"('a*'b)list \\<Rightarrow> 'a \\<Rightarrow> 'b option\" where\n\"map_of [] = (\\<lambda>x. None)\" |\n\"map_of ((a,b)#ps) = (\\<lambda>x. if x=a then Some b else map_of ps x)\"\n\ntext \\<open>Updating an association list:\\<close>\n\nfun upd_list :: \"'a::linorder \\<Rightarrow> 'b \\<Rightarrow> ('a*'b) list \\<Rightarrow> ('a*'b) list\" where\n\"upd_list x y [] = [(x,y)]\" |\n\"upd_list x y ((a,b)#ps) =\n  (if x < a then (x,y)#(a,b)#ps else\n  if x = a then (x,y)#ps else (a,b) # upd_list x y ps)\"\n\nfun del_list :: \"'a::linorder \\<Rightarrow> ('a*'b)list \\<Rightarrow> ('a*'b)list\" where\n\"del_list x [] = []\" |\n\"del_list x ((a,b)#ps) = (if x = a then ps else (a,b) # del_list x ps)\"\n\n\nsubsection \\<open>Lemmas for \\<^const>\\<open>map_of\\<close>\\<close>\n\nlemma map_of_ins_list: \"map_of (upd_list x y ps) = (map_of ps)(x := Some y)\"\nby(induction ps) auto\n\nlemma map_of_append: \"map_of (ps @ qs) x =\n  (case map_of ps x of None \\<Rightarrow> map_of qs x | Some y \\<Rightarrow> Some y)\"\nby(induction ps)(auto)\n\nlemma map_of_None: \"sorted (x # map fst ps) \\<Longrightarrow> map_of ps x = None\"\nby (induction ps) (fastforce simp: sorted_lems sorted_wrt_Cons)+\n\nlemma map_of_None2: \"sorted (map fst ps @ [x]) \\<Longrightarrow> map_of ps x = None\"\nby (induction ps) (auto simp: sorted_lems)\n\nlemma map_of_del_list: \"sorted1 ps \\<Longrightarrow>\n  map_of(del_list x ps) = (map_of ps)(x := None)\"\nby(induction ps) (auto simp: map_of_None sorted_lems fun_eq_iff)\n\nlemma map_of_sorted_Cons: \"sorted (a # map fst ps) \\<Longrightarrow> x < a \\<Longrightarrow>\n   map_of ps x = None\"\nby (simp add: map_of_None sorted_Cons_le)\n\nlemma map_of_sorted_snoc: \"sorted (map fst ps @ [a]) \\<Longrightarrow> a \\<le> x \\<Longrightarrow>\n  map_of ps x = None\"\nby (simp add: map_of_None2 sorted_snoc_le)\n\nlemmas map_of_sorteds = map_of_sorted_Cons map_of_sorted_snoc\nlemmas map_of_simps = sorted_lems map_of_append map_of_sorteds\n\n\nsubsection \\<open>Lemmas for \\<^const>\\<open>upd_list\\<close>\\<close>\n\nlemma sorted_upd_list: \"sorted1 ps \\<Longrightarrow> sorted1 (upd_list x y ps)\"\napply(induction ps)\n apply simp\napply(case_tac ps)\n apply auto\ndone\n\nlemma upd_list_sorted: \"sorted1 (ps @ [(a,b)]) \\<Longrightarrow>\n  upd_list x y (ps @ (a,b) # qs) =\n    (if x < a then upd_list x y ps @ (a,b) # qs\n    else ps @ upd_list x y ((a,b) # qs))\"\nby(induction ps) (auto simp: sorted_lems)\n\ntext\\<open>In principle, @{thm upd_list_sorted} suffices, but the following two\ncorollaries speed up proofs.\\<close>\n\ncorollary upd_list_sorted1: \"\\<lbrakk> sorted (map fst ps @ [a]); x < a \\<rbrakk> \\<Longrightarrow>\n  upd_list x y (ps @ (a,b) # qs) =  upd_list x y ps @ (a,b) # qs\"\nby (auto simp: upd_list_sorted)\n\ncorollary upd_list_sorted2: \"\\<lbrakk> sorted (map fst ps @ [a]); a \\<le> x \\<rbrakk> \\<Longrightarrow>\n  upd_list x y (ps @ (a,b) # qs) = ps @ upd_list x y ((a,b) # qs)\"\nby (auto simp: upd_list_sorted)\n\nlemmas upd_list_simps = sorted_lems upd_list_sorted1 upd_list_sorted2\n\ntext\\<open>Splay trees need two additional \\<^const>\\<open>upd_list\\<close> lemmas:\\<close>\n\nlemma upd_list_Cons:\n  \"sorted1 ((x,y) # xs) \\<Longrightarrow> upd_list x y xs = (x,y) # xs\"\nby (induction xs) auto\n\nlemma upd_list_snoc:\n  \"sorted1 (xs @ [(x,y)]) \\<Longrightarrow> upd_list x y xs = xs @ [(x,y)]\"\nby(induction xs) (auto simp add: sorted_mid_iff2)\n\n\nsubsection \\<open>Lemmas for \\<^const>\\<open>del_list\\<close>\\<close>\n\nlemma sorted_del_list: \"sorted1 ps \\<Longrightarrow> sorted1 (del_list x ps)\"\napply(induction ps)\n apply simp\napply(case_tac ps)\napply (auto simp: sorted_Cons_le)\ndone\n\nlemma del_list_idem: \"x \\<notin> set(map fst xs) \\<Longrightarrow> del_list x xs = xs\"\nby (induct xs) auto\n\nlemma del_list_sorted: \"sorted1 (ps @ (a,b) # qs) \\<Longrightarrow>\n  del_list x (ps @ (a,b) # qs) =\n    (if x < a then del_list x ps @ (a,b) # qs\n     else ps @ del_list x ((a,b) # qs))\"\nby(induction ps)\n  (fastforce simp: sorted_lems sorted_wrt_Cons 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: \"sorted1 (xs @ (a,b) # ys) \\<Longrightarrow> a \\<le> x \\<Longrightarrow>\n  del_list x (xs @ (a,b) # ys) = xs @ del_list x ((a,b) # ys)\"\nby (auto simp: del_list_sorted)\n\nlemma del_list_sorted2: \"sorted1 (xs @ (a,b) # ys) \\<Longrightarrow> x < a \\<Longrightarrow>\n  del_list x (xs @ (a,b) # ys) = del_list x xs @ (a,b) # ys\"\nby (auto simp: del_list_sorted)\n\nlemma del_list_sorted3:\n  \"sorted1 (xs @ (a,a') # ys @ (b,b') # zs) \\<Longrightarrow> x < b \\<Longrightarrow>\n  del_list x (xs @ (a,a') # ys @ (b,b') # zs) = del_list x (xs @ (a,a') # ys) @ (b,b') # zs\"\nby (auto simp: del_list_sorted sorted_lems)\n\nlemma del_list_sorted4:\n  \"sorted1 (xs @ (a,a') # ys @ (b,b') # zs @ (c,c') # us) \\<Longrightarrow> x < c \\<Longrightarrow>\n  del_list x (xs @ (a,a') # ys @ (b,b') # zs @ (c,c') # us) = del_list x (xs @ (a,a') # ys @ (b,b') # zs) @ (c,c') # us\"\nby (auto simp: del_list_sorted sorted_lems)\n\nlemma del_list_sorted5:\n  \"sorted1 (xs @ (a,a') # ys @ (b,b') # zs @ (c,c') # us @ (d,d') # vs) \\<Longrightarrow> x < d \\<Longrightarrow>\n   del_list x (xs @ (a,a') # ys @ (b,b') # zs @ (c,c') # us @ (d,d') # vs) =\n   del_list x (xs @ (a,a') # ys @ (b,b') # zs @ (c,c') # us) @ (d,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 # map fst xs) \\<Longrightarrow> del_list x xs = xs\"\nby(induction xs)(fastforce simp: sorted_wrt_Cons)+\n\nlemma del_list_sorted_app:\n  \"sorted(map fst 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/AList_Upd_Del.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.822189121808099, "lm_q2_score": 0.863391599428538, "lm_q1q2_score": 0.7098711809106397}}
{"text": "theory Kyber_spec\nimports Main \"HOL-Computational_Algebra.Computational_Algebra\" \n  \"HOL-Computational_Algebra.Polynomial_Factorial\"\n  \"Berlekamp_Zassenhaus.Poly_Mod\" \n  \"Berlekamp_Zassenhaus.Poly_Mod_Finite_Field\"\n\nbegin\nsection \\<open>Type Class for Factorial Ring $\\mathbb{Z}_q[x]/(x^n+1)$.\\<close>\ntext \\<open>The Kyber algorithms work over the quotient ring $\\mathbb{Z}_q[x]/(x^n+1)$\nwhere $q$ is a prime with $q\\equiv 1 \\mod 4$ and $n$ is a power of $2$.\nWe encode this quotient ring as a type. In order to do so, we first look at the\nfinite field $\\mathbb{Z}_q$ implemented by \\<open>('a::prime_card) mod_ring\\<close>. \nThen we define polynomials using the constructor \\<open>poly\\<close>.\nFor factoring out $x^n+1$, we define an equivalence relation on the polynomial ring\n$\\mathbb{Z}_q[x]$ via the modulo operation with modulus $x^n+1$.\nFinally, we build the quotient of the equivalence relation using the construction \n\\<open>quotient_type\\<close>.\\<close>\ntext \\<open>The module $\\mathbb{Z}_q[x]/(x^n+1)$ was formalized with help from Manuel Eberl.\\<close>\n\ntext \\<open>Modulo relation between two polynomials. \\<close>\nlemma of_int_mod_ring_eq_0_iff:\n  \"(of_int n :: ('n :: {finite, nontriv} mod_ring)) = 0 \\<longleftrightarrow> \n    int (CARD('n)) dvd n\"\n  by transfer auto\n\nlemma of_int_mod_ring_eq_of_int_iff:\n  \"(of_int n :: ('n :: {finite, nontriv} mod_ring)) = of_int m \\<longleftrightarrow> \n    [n = m] (mod (int (CARD('n))))\"\n  by transfer (auto simp: cong_def)\n\ndefinition mod_poly_rel :: \"nat \\<Rightarrow> int poly \\<Rightarrow> int poly \\<Rightarrow> bool\" where\n  \"mod_poly_rel m p q \\<longleftrightarrow> \n    (\\<forall>n. [poly.coeff p n = poly.coeff q n] (mod (int m)))\"\n\nlemma mod_poly_rel_altdef:\n  \"mod_poly_rel CARD('n :: nontriv) p q \\<longleftrightarrow> \n    (of_int_poly p) = (of_int_poly q :: 'n mod_ring poly)\"\n  by (auto simp: poly_eq_iff mod_poly_rel_def \n    of_int_mod_ring_eq_of_int_iff)\n\ndefinition mod_poly_is_unit :: \"nat \\<Rightarrow> int poly \\<Rightarrow> bool\" where\n  \"mod_poly_is_unit m p \\<longleftrightarrow> (\\<exists>r. mod_poly_rel m (p * r) 1)\"\n\nlemma mod_poly_is_unit_altdef:\n  \"mod_poly_is_unit CARD('n :: nontriv) p \\<longleftrightarrow> \n    (of_int_poly p :: 'n mod_ring poly) dvd 1\"\nproof\n  assume \"mod_poly_is_unit CARD('n) p\"\n  thus \"(of_int_poly p :: 'n mod_ring poly) dvd 1\"\n    by (auto simp: mod_poly_is_unit_def dvd_def mod_poly_rel_altdef \n      of_int_poly_hom.hom_mult)\nnext \n  assume \"(of_int_poly p :: 'n mod_ring poly) dvd 1\"\n  then obtain q where q: \"(of_int_poly p :: 'n mod_ring poly) * q = 1\"\n    by auto\n  also have \"q = of_int_poly (map_poly to_int_mod_ring q)\"\n    by (simp add: of_int_of_int_mod_ring poly_eqI)\n  also have \"of_int_poly p * \\<dots> = \n      of_int_poly (p * map_poly to_int_mod_ring q)\"\n    by (simp add: of_int_poly_hom.hom_mult)\n  finally show \"mod_poly_is_unit CARD('n) p\"\n    by (auto simp: mod_poly_is_unit_def mod_poly_rel_altdef)\nqed\n\ndefinition mod_poly_irreducible :: \"nat \\<Rightarrow> int poly \\<Rightarrow> bool\" where\n  \"mod_poly_irreducible m Q \\<longleftrightarrow>\n     \\<not>mod_poly_rel m Q 0 \\<and>\n     \\<not>mod_poly_is_unit m Q \\<and>\n        (\\<forall>a b. mod_poly_rel m Q (a * b) \\<longrightarrow>\n               mod_poly_is_unit m a \\<or> mod_poly_is_unit m b)\"\n\nlemma of_int_poly_to_int_poly: \"of_int_poly (to_int_poly p) = p\"\n  by (simp add: of_int_of_int_mod_ring poly_eqI)\n\nlemma mod_poly_irreducible_altdef:\n  \"mod_poly_irreducible CARD('n :: nontriv) p \\<longleftrightarrow> \n    irreducible (of_int_poly p :: 'n mod_ring poly)\"\nproof\n  assume \"irreducible (of_int_poly p :: 'n mod_ring poly)\"\n  thus \"mod_poly_irreducible CARD('n) p\"\n    by (auto simp: mod_poly_irreducible_def mod_poly_rel_altdef \n    mod_poly_is_unit_altdef irreducible_def of_int_poly_hom.hom_mult)\nnext\n  assume *: \"mod_poly_irreducible CARD('n) p\"\n  show \"irreducible (of_int_poly p :: 'n mod_ring poly)\"\n    unfolding irreducible_def\n  proof (intro conjI impI allI)\n    fix a b assume ab: \"(of_int_poly p :: 'n mod_ring poly) = a * b\"\n    have \"of_int_poly (map_poly to_int_mod_ring a * \n      map_poly to_int_mod_ring b) =\n      of_int_poly (map_poly to_int_mod_ring a) *\n      (of_int_poly (map_poly to_int_mod_ring b) :: 'n mod_ring poly)\"\n      by (simp add: of_int_poly_hom.hom_mult)\n    also have \"\\<dots> = a * b\"\n      by (simp add: of_int_poly_to_int_poly)\n    also have \"\\<dots> = of_int_poly p\"\n      using ab by simp\n    finally have \"(of_int_poly p :: 'n mod_ring poly) = \n      of_int_poly (to_int_poly a * to_int_poly b)\" ..\n    hence \"of_int_poly (to_int_poly a) dvd (1 :: 'n mod_ring poly) \\<or>\n           of_int_poly (to_int_poly b) dvd (1 :: 'n mod_ring poly)\"\n      using * unfolding mod_poly_irreducible_def mod_poly_rel_altdef \n        mod_poly_is_unit_altdef by blast\n    thus \"(a dvd (1 :: 'n mod_ring poly)) \\<or> \n      (b dvd (1 :: 'n mod_ring poly))\"\n      by (simp add: of_int_poly_to_int_poly)\n  qed (use * in \\<open>auto simp: mod_poly_irreducible_def \n    mod_poly_rel_altdef mod_poly_is_unit_altdef\\<close>)\nqed\n    \ntext \\<open>Type class for quotient ring $\\mathbb{Z}_q[x]/(p)$. \n  The polynomial p is represented as \\<open>qr_poly'\\<close> (an polynomial over the integers).\\<close>\n\nclass qr_spec = prime_card +\n  fixes qr_poly' :: \"'a itself \\<Rightarrow> int poly\"\n  assumes not_dvd_lead_coeff_qr_poly':  \n      \"\\<not>int CARD('a) dvd lead_coeff (qr_poly' TYPE('a))\"\n  and deg_qr'_pos : \"degree (qr_poly' TYPE('a)) > 0\"\n\ntext \\<open>\\<open>qr_poly\\<close> is the respective polynomial in $\\mathbb{Z}_q[x]$.\\<close>\ndefinition qr_poly :: \"'a :: qr_spec mod_ring poly\" where\n  \"qr_poly = of_int_poly (qr_poly' TYPE('a))\"\n\ntext \\<open>Functions to get the degree of the polynomials to be factored out.\\<close>\ndefinition (in qr_spec) deg_qr :: \"'a itself \\<Rightarrow> nat\" where\n  \"deg_qr _ = degree (qr_poly' TYPE('a))\"\n\nlemma degree_qr_poly': \n  \"degree (qr_poly' TYPE('a :: qr_spec)) = deg_qr (TYPE('a))\"\n  by (simp add: deg_qr_def)\n\nlemma degree_of_int_poly':\n  assumes \"of_int (lead_coeff p) \\<noteq> (0 :: 'a :: ring_1)\"\n  shows \"degree (of_int_poly p :: 'a poly) = degree p\"\nproof (intro antisym)\n  show \"degree (of_int_poly p) \\<le> degree p\"\n    by (intro degree_le) (auto simp: coeff_eq_0)\n  show \"degree (of_int_poly p :: 'a poly) \\<ge> degree p\"\n    using assms by (intro le_degree) auto\nqed\n\nlemma degree_qr_poly:\n  \"degree (qr_poly :: 'a :: qr_spec mod_ring poly) = deg_qr (TYPE('a))\"\n  unfolding qr_poly_def \n  using not_dvd_lead_coeff_qr_poly'[where ?'a = 'a]\n  by (subst degree_of_int_poly') \n     (auto simp: of_int_mod_ring_eq_0_iff degree_qr_poly')\n\nlemma deg_qr_pos : \"deg_qr TYPE('a :: qr_spec) > 0\"\nby (metis deg_qr'_pos degree_qr_poly')\n\ntext \\<open>The factor polynomial is non-zero.\\<close>\nlemma qr_poly_nz [simp]: \"qr_poly \\<noteq> 0\"\n  using deg_qr_pos[where ?'a = 'a] by (auto simp flip: degree_qr_poly)\n\ntext \\<open>Thus, when factoring out $p$, it has no effect on the neutral element $1$.\\<close>\nlemma one_mod_qr_poly [simp]: \n  \"1 mod (qr_poly :: 'a :: qr_spec mod_ring poly) = 1\"\nproof -\n  have \"2 ^ 1 \\<le> (2 ^ deg_qr TYPE('a) :: nat)\"\n    using deg_qr_pos[where ?'a = 'a] \n    by (intro power_increasing) auto\n  thus ?thesis\n    by (intro mod_eqI[where q = 0]) \n       (auto simp: euclidean_size_poly_def degree_qr_poly)\nqed\n\ntext \\<open>We define a modulo relation for polynomials modulo a polynomial $p=$\\<open>qr_poly\\<close>.\\<close>\ndefinition qr_rel :: \"'a :: qr_spec mod_ring poly \\<Rightarrow> 'a mod_ring poly \\<Rightarrow> bool\" where\n  \"qr_rel P Q \\<longleftrightarrow> [P = Q] (mod qr_poly)\"\n\nlemma equivp_qr_rel: \"equivp qr_rel\"\n  by (intro equivpI sympI reflpI transpI)\n     (auto simp: qr_rel_def cong_sym intro: cong_trans)\n\ntext \\<open>Using this equivalence relation, we can define the quotient ring as a \\<open>quotient_type\\<close>.\\<close>\nquotient_type (overloaded) 'a qr = \"'a :: qr_spec mod_ring poly\" / qr_rel\n  by (rule equivp_qr_rel)\n\ntext \\<open>Defining the conversion functions.\\<close>\nlift_definition to_qr :: \"'a :: qr_spec mod_ring poly \\<Rightarrow> 'a qr\" \n  is \"\\<lambda>x. (x :: 'a mod_ring poly)\" .\n\nlift_definition of_qr :: \"'a qr \\<Rightarrow> 'a :: qr_spec mod_ring poly\" \n  is \"\\<lambda>P::'a mod_ring poly. P mod qr_poly\"\n  by (simp add: qr_rel_def cong_def)\n\ntext \\<open>Simplification lemmas on conversion functions.\\<close>\nlemma of_qr_to_qr: \"of_qr (to_qr (x)) = x mod qr_poly\"\n  apply (auto simp add: of_qr_def to_qr_def)\n  by (metis of_qr.abs_eq of_qr.rep_eq)\n\n\nlemma to_qr_of_qr: \"to_qr (of_qr (x)) = x\"\n  apply (auto simp add: of_qr_def to_qr_def)\n  by (metis (mono_tags, lifting) Quotient3_abs_rep Quotient3_qr \n    Quotient3_rel cong_def qr_rel_def mod_mod_trivial)\n\nlemma eq_to_qr: \"x = y \\<Longrightarrow> to_qr x = to_qr y\" by auto\n\n\n\n\n\ntext \\<open>Type class instantiation for \\<open>qr\\<close> (quotient ring).\\<close>\ninstantiation qr :: (qr_spec) comm_ring_1\nbegin\n\nlift_definition zero_qr :: \"'a qr\" is \"0\" .\n\nlift_definition one_qr :: \"'a qr\" is \"1\" .\n\nlift_definition plus_qr :: \"'a qr \\<Rightarrow> 'a qr \\<Rightarrow> 'a qr\"\n  is \"(+)\"\n  unfolding qr_rel_def using cong_add by blast\n\nlift_definition uminus_qr :: \"'a qr \\<Rightarrow> 'a qr\"\n  is \"uminus\"\n  unfolding qr_rel_def  using cong_minus_minus_iff by blast\n\nlift_definition minus_qr :: \"'a qr \\<Rightarrow> 'a qr \\<Rightarrow> 'a qr\"\n  is \"(-)\"\n  unfolding qr_rel_def using cong_diff by blast\n\nlift_definition times_qr :: \"'a qr \\<Rightarrow> 'a qr \\<Rightarrow> 'a qr\"\n  is \"(*)\"\n  unfolding qr_rel_def using cong_mult by blast\n\ninstance\nproof\n  show \"0 \\<noteq> (1 :: 'a qr)\"\n    by transfer (simp add: qr_rel_def cong_def)\nqed (transfer; simp add: qr_rel_def algebra_simps; fail)+\n\nend\n\nlemma of_qr_0 [simp]: \"of_qr 0 = 0\"\n  and of_qr_1 [simp]: \"of_qr 1 = 1\"\n  and of_qr_uminus [simp]: \"of_qr (-p) = -of_qr p\"\n  and of_qr_add [simp]: \"of_qr (p + q) = of_qr p + of_qr q\"\n  and of_qr_diff [simp]: \"of_qr (p - q) = of_qr p - of_qr q\"\n  by (transfer; simp add: poly_mod_add_left poly_mod_diff_left; fail)+\n\nlemma to_qr_0 [simp]: \"to_qr 0 = 0\"\n  and to_qr_1 [simp]: \"to_qr 1 = 1\"\n  and to_qr_uminus [simp]: \"to_qr (-p) = -to_qr p\"\n  and to_qr_add [simp]: \"to_qr (p + q) = to_qr p + to_qr q\"\n  and to_qr_diff [simp]: \"to_qr (p - q) = to_qr p - to_qr q\"\n  and to_qr_mult [simp]: \"to_qr (p * q) = to_qr p * to_qr q\"\n  by (transfer'; simp; fail)+\n\nlemma to_qr_of_nat [simp]: \"to_qr (of_nat n) = of_nat n\"\n  by (induction n) auto\n\nlemma to_qr_of_int [simp]: \"to_qr (of_int n) = of_int n\"\n  by (induction n) auto\n\nlemma of_qr_of_nat [simp]: \"of_qr (of_nat n) = of_nat n\"\n  by (induction n) auto\n\nlemma of_qr_of_int [simp]: \"of_qr (of_int n) = of_int n\"\n  by (induction n) auto\n\nlemma of_qr_eq_0_iff [simp]: \"of_qr p = 0 \\<longleftrightarrow> p = 0\"\n  by transfer (simp add: qr_rel_def cong_def)\n\nlemma to_qr_eq_0_iff:\n  \"to_qr p = 0 \\<longleftrightarrow> qr_poly dvd p\"\n  by transfer (auto simp: qr_rel_def cong_def)\n\n\ntext \\<open>Some more lemmas that will probably be useful.\\<close>\n\nlemma to_qr_eq_iff [simp]:\n  \"to_qr P = (to_qr Q :: 'a :: qr_spec qr) \\<longleftrightarrow> [P = Q] (mod qr_poly)\"\n  by transfer (auto simp: qr_rel_def)\n\ntext \\<open>Reduction modulo $x^n + 1$ is injective on polynomials of degree less than $n$\n  in particular, this means that \\<open>card(QR(q^n)) = q^n\\<close>. \\<close>\nlemma inj_on_to_qr:\n  \"inj_on\n     (to_qr :: 'a :: qr_spec mod_ring poly \\<Rightarrow> 'a qr)\n     {P. degree P < deg_qr TYPE('a)}\"\n  by (intro inj_onI) (auto simp: cong_def mod_poly_less \n      simp flip: degree_qr_poly)\n\ntext \\<open>Characteristic of quotient ring is exactly q.\\<close>\n\nlemma of_int_qr_eq_0_iff [simp]:\n  \"of_int n = (0 :: 'a :: qr_spec qr) \\<longleftrightarrow> int (CARD('a)) dvd n\"\nproof -\n  have \"of_int n = (0 :: 'a qr) \\<longleftrightarrow> (of_int n :: 'a mod_ring poly) = 0\"\n    by (smt (z3) of_qr_eq_0_iff of_qr_of_int)\n  also have \"\\<dots> \\<longleftrightarrow> (of_int n :: 'a mod_ring) = 0\"\n    by (simp add: of_int_poly)\n  also have \"\\<dots> \\<longleftrightarrow> int (CARD('a)) dvd n\"\n    by (simp add: of_int_mod_ring_eq_0_iff)\n  finally show ?thesis .\nqed\n\nlemma of_int_qr_eq_of_int_iff:\n  \"of_int n = (of_int m :: 'a :: qr_spec qr) \\<longleftrightarrow> \n    [n = m] (mod (int (CARD('a))))\"\n  using of_int_qr_eq_0_iff[of \"n - m\", where ?'a = 'a]\n  by (simp del: of_int_qr_eq_0_iff add: cong_iff_dvd_diff)\n\nlemma of_nat_qr_eq_of_nat_iff:\n  \"of_nat n = (of_nat m :: 'a :: qr_spec qr) \\<longleftrightarrow> \n    [n = m] (mod CARD('a))\"\n  using of_int_qr_eq_of_int_iff[of \"int n\" \"int m\"] \n  by (simp add: cong_int_iff)\n\nlemma of_nat_qr_eq_0_iff [simp]:\n  \"of_nat n = (0 :: 'a :: qr_spec qr) \\<longleftrightarrow> CARD('a) dvd n\"\n  using of_int_qr_eq_0_iff[of \"int n\"] by simp\n\n\nsection \\<open>Specification of Kyber\\<close>\ntext \\<open>\nWe now define a locale for the specification parameters of Kyber as in \\cite{kyber}.\nThe specifications use the parameters:\n\n\\begin{tabular}{r l}\n$n$ & $=256 = 2^{n'}$\\\\\n$n'$ & $= 8$\\\\\n$q$ & $= 7681$ or $3329$\\\\\n$k$ & $= 3$\\\\\n\\end{tabular}\n\nIt is important, that $q$ is a prime with the property $q\\equiv 1\\mod 4$.\n\\<close>\n\n\n\n\nlocale kyber_spec =\nfixes \"type_a\" :: \"('a :: qr_spec) itself\" \n  and \"type_k\" :: \"('k ::finite) itself\" \n  and n q::int and k n'::nat\nassumes\nn_powr_2: \"n = 2 ^ n'\" and\nn'_gr_0: \"n' > 0\" and \nq_gr_two: \"q > 2\" and\nq_mod_4: \"q mod 4 = 1\" and \nq_prime : \"prime q\" and\nCARD_a: \"int (CARD('a :: qr_spec)) = q\" and\nCARD_k: \"int (CARD('k :: finite)) = k\" and\nqr_poly'_eq: \"qr_poly' TYPE('a) = Polynomial.monom 1 (nat n) + 1\"\n\nbegin\ntext \\<open>Some properties of the modulus q.\\<close>\n\nlemma q_nonzero: \"q \\<noteq> 0\" \nusing kyber_spec_axioms kyber_spec_def by (smt (z3))\n\nlemma q_gt_zero: \"q>0\" \nusing kyber_spec_axioms kyber_spec_def by (smt (z3))\n\nlemma q_gt_two: \"q>2\"\nusing kyber_spec_axioms kyber_spec_def by (smt (z3))\n\nlemma q_odd: \"odd q\"\nusing kyber_spec_axioms kyber_spec_def\n prime_odd_int by blast\n\nlemma nat_q: \"nat q = q\"\nusing q_gt_zero by force\n\ntext \\<open>Some properties of the degree n.\\<close>\n\nlemma n_gt_1: \"n > 1\"\nusing kyber_spec_axioms kyber_spec_def\n  by (simp add: n'_gr_0 n_powr_2)\n\nlemma n_nonzero: \"n \\<noteq> 0\" \nusing n_gt_1 by auto\n\nlemma n_gt_zero: \"n>0\" \nusing n_gt_1 by auto\n\nlemma nat_n: \"nat n = n\"\nusing n_gt_zero by force\n\ntext \\<open>Properties in the ring \\<open>'a qr\\<close>. A good representative has degree up to n.\\<close>\nlemma deg_mod_qr_poly:\n  assumes \"degree x < deg_qr TYPE('a)\"\n  shows \"x mod (qr_poly :: 'a mod_ring poly) = x\"\nusing mod_poly_less[of x qr_poly] unfolding deg_qr_def\nby (metis assms degree_qr_poly) \n\nlemma of_qr_to_qr': \n  assumes \"degree x < deg_qr TYPE('a)\"\n  shows \"of_qr (to_qr x) = (x ::'a mod_ring poly)\"\nusing deg_mod_qr_poly[OF assms] of_qr_to_qr[of x] by simp\n\nlemma deg_qr_n: \n  \"deg_qr TYPE('a) = n\"\nunfolding deg_qr_def using qr_poly'_eq n_gt_1\nby (simp add: degree_add_eq_left degree_monom_eq)\n\nlemma deg_of_qr: \n  \"degree (of_qr (x ::'a qr)) < deg_qr TYPE('a)\"\nby (metis deg_qr_pos degree_0 degree_qr_poly degree_mod_less' \n  qr_poly_nz of_qr.rep_eq)\n\ndefinition to_module :: \"int \\<Rightarrow> 'a qr\" where\n  \"to_module x = to_qr (Poly [of_int_mod_ring x ::'a mod_ring])\"\n\nlemma to_qr_smult_to_module: \n  \"to_qr (Polynomial.smult a p) = (to_qr (Poly [a])) * (to_qr p)\"\nby (metis Poly.simps(1) Poly.simps(2) mult.left_neutral \n  mult_smult_left smult_one to_qr_mult)\n\nlemma of_qr_to_qr_smult:\n  \"of_qr (to_qr (Polynomial.smult a p)) = \n  Polynomial.smult a (of_qr (to_qr p))\"\nby (simp add: mod_smult_left of_qr_to_qr)\n\n\nend\nend", "meta": {"author": "ThikaXer", "repo": "Kyber_Formalization", "sha": "a1832e7b8e29852c35f252b5703083f912cfe5ff", "save_path": "github-repos/isabelle/ThikaXer-Kyber_Formalization", "path": "github-repos/isabelle/ThikaXer-Kyber_Formalization/Kyber_Formalization-a1832e7b8e29852c35f252b5703083f912cfe5ff/Kyber_spec.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9263037221561135, "lm_q2_score": 0.7662936377487304, "lm_q1q2_score": 0.7098206489111974}}
{"text": "(*<*)\ntheory Propositional_Logic\nimports Abstract_Completeness\nbegin\n(*>*)\n\nsection {* Toy instantiation: Propositional Logic *}\n\ndatatype fmla = Atom nat | Neg fmla | Conj fmla fmla\n\nprimrec max_depth where\n  \"max_depth (Atom _) = 0\"\n| \"max_depth (Neg \\<phi>) = Suc (max_depth \\<phi>)\"\n| \"max_depth (Conj \\<phi> \\<psi>) = Suc (max (max_depth \\<phi>) (max_depth \\<psi>))\"\n\nlemma max_depth_0: \"max_depth \\<phi> = 0 = (\\<exists>n. \\<phi> = Atom n)\"\n  by (cases \\<phi>) auto\n\nlemma max_depth_Suc: \"max_depth \\<phi> = Suc n = ((\\<exists>\\<psi>. \\<phi> = Neg \\<psi> \\<and> max_depth \\<psi> = n) \\<or>\n  (\\<exists>\\<psi>1 \\<psi>2. \\<phi> = Conj \\<psi>1 \\<psi>2 \\<and> max (max_depth \\<psi>1) (max_depth \\<psi>2) = n))\"\n  by (cases \\<phi>) auto\n\nabbreviation \"atoms \\<equiv> smap Atom nats\"\nabbreviation \"depth1 \\<equiv>\n  sinterleave (smap Neg atoms) (smap (case_prod Conj) (sproduct atoms atoms))\"\n\nabbreviation \"sinterleaves \\<equiv> fold sinterleave\"\n\nfun extendLevel where \"extendLevel (belowN, N) =\n  (let Next = sinterleaves\n    (map (smap (case_prod Conj)) [sproduct belowN N, sproduct N belowN, sproduct N N])\n    (smap Neg N)\n  in (sinterleave belowN N, Next))\"\n\nlemma extendLevel_step:\n  \"\\<lbrakk>sset belowN = {\\<phi>. max_depth \\<phi> < n};\n    sset N = {\\<phi>. max_depth \\<phi> = n}; st = (belowN, N)\\<rbrakk> \\<Longrightarrow>\n  \\<exists>belowNext Next. extendLevel st = (belowNext, Next) \\<and>\n     sset belowNext = {\\<phi>. max_depth \\<phi> < Suc n} \\<and> sset Next = {\\<phi>. max_depth \\<phi> = Suc n}\"\n  by (auto simp: sset_sinterleave sset_sproduct stream.set_map\n    image_iff max_depth_Suc)\n\nlemma sset_atoms: \"sset atoms = {\\<phi>. max_depth \\<phi> < 1}\"\n  by (auto simp: stream.set_map max_depth_0)\n\nlemma sset_depth1: \"sset depth1 = {\\<phi>. max_depth \\<phi> = 1}\"\n  by (auto simp: sset_sinterleave sset_sproduct stream.set_map\n    max_depth_Suc max_depth_0 max_def image_iff)\n\nlemma extendLevel_Nsteps:\n  \"\\<lbrakk>sset belowN = {\\<phi>. max_depth \\<phi> < n}; sset N = {\\<phi>. max_depth \\<phi> = n}\\<rbrakk> \\<Longrightarrow>\n  \\<exists>belowNext Next. (extendLevel ^^ m) (belowN, N) = (belowNext, Next) \\<and>\n     sset belowNext = {\\<phi>. max_depth \\<phi> < n + m} \\<and> sset Next = {\\<phi>. max_depth \\<phi> = n + m}\"\nproof (induction m arbitrary: belowN N n)\n  case (Suc m)\n  then obtain belowNext Next where \"(extendLevel ^^ m) (belowN, N) = (belowNext, Next)\"\n    \"sset belowNext = {\\<phi>. max_depth \\<phi> < n + m}\" \"sset Next = {\\<phi>. max_depth \\<phi> = n + m}\"\n    by blast\n  thus ?case unfolding funpow.simps o_apply add_Suc_right\n    by (intro extendLevel_step[of belowNext _ Next])\nqed simp\n\ncorollary extendLevel:\n  \"\\<exists>belowNext Next. (extendLevel ^^ m) (atoms, depth1) = (belowNext, Next) \\<and>\n     sset belowNext = {\\<phi>. max_depth \\<phi> < 1 + m} \\<and> sset Next = {\\<phi>. max_depth \\<phi> = 1 + m}\"\n  by (rule extendLevel_Nsteps) (auto simp: sset_atoms sset_depth1)\n\n\ndefinition \"fmlas = sinterleave atoms (smerge (smap snd (siterate extendLevel (atoms, depth1))))\"\n\nlemma fmlas_UNIV: \"sset fmlas = (UNIV :: fmla set)\"\nproof (intro equalityI subsetI UNIV_I)\n  fix \\<phi>\n  show \"\\<phi> \\<in> sset fmlas\"\n  proof (cases \"max_depth \\<phi>\")\n    case 0 thus ?thesis unfolding fmlas_def sset_sinterleave stream.set_map\n      by (intro UnI1) (auto simp: max_depth_0)\n  next\n    case (Suc m) thus ?thesis using extendLevel[of m]\n    unfolding fmlas_def sset_smerge sset_siterate sset_sinterleave stream.set_map\n      by (intro UnI2) (auto, metis (mono_tags) mem_Collect_eq)\n  qed\nqed\n\ndatatype rule = Idle | Ax nat | NegL fmla | NegR fmla | ConjL fmla fmla | ConjR fmla fmla\n\nabbreviation \"mkRules f \\<equiv> smap f fmlas\"\nabbreviation \"mkRulePairs f \\<equiv> smap (case_prod f) (sproduct fmlas fmlas)\"\n\ndefinition rules where\n  \"rules = Idle ## \n     sinterleaves [mkRules NegL, mkRules NegR, mkRulePairs ConjL, mkRulePairs ConjR]\n     (smap Ax nats)\"\n\nlemma rules_UNIV: \"sset rules = (UNIV :: rule set)\"\n  unfolding rules_def by (auto simp: sset_sinterleave sset_sproduct stream.set_map\n    fmlas_UNIV image_iff) (metis rule.exhaust)\n\ntype_synonym state = \"fmla fset * fmla fset\"\n\nfun eff' :: \"rule \\<Rightarrow> state \\<Rightarrow> state fset option\" where\n  \"eff' Idle (\\<Gamma>, \\<Delta>) = Some {|(\\<Gamma>, \\<Delta>)|}\"\n| \"eff' (Ax n) (\\<Gamma>, \\<Delta>) =\n    (if Atom n |\\<in>| \\<Gamma> \\<and> Atom n |\\<in>| \\<Delta> then Some {||} else None)\"\n| \"eff' (NegL \\<phi>) (\\<Gamma>, \\<Delta>) =\n    (if Neg \\<phi> |\\<in>| \\<Gamma> then Some {|(\\<Gamma> |-| {| Neg \\<phi> |}, finsert \\<phi> \\<Delta>)|} else None)\"\n| \"eff' (NegR \\<phi>) (\\<Gamma>, \\<Delta>) =\n    (if Neg \\<phi> |\\<in>| \\<Delta> then Some {|(finsert \\<phi> \\<Gamma>, \\<Delta> |-| {| Neg \\<phi> |})|} else None)\"\n| \"eff' (ConjL \\<phi> \\<psi>) (\\<Gamma>, \\<Delta>) =\n    (if Conj \\<phi> \\<psi> |\\<in>| \\<Gamma>\n    then Some {|(finsert \\<phi> (finsert \\<psi> (\\<Gamma> |-| {| Conj \\<phi> \\<psi> |})), \\<Delta>)|}\n    else None)\"\n| \"eff' (ConjR \\<phi> \\<psi>) (\\<Gamma>, \\<Delta>) =\n    (if Conj \\<phi> \\<psi> |\\<in>| \\<Delta>\n    then Some {|(\\<Gamma>, finsert \\<phi> (\\<Delta> |-| {| Conj \\<phi> \\<psi> |})), (\\<Gamma>, finsert \\<psi> (\\<Delta> |-| {| Conj \\<phi> \\<psi> |}))|}\n    else None)\"\n\n\nabbreviation \"Disj \\<phi> \\<psi> \\<equiv> Neg (Conj (Neg \\<phi>) (Neg \\<psi>))\"\nabbreviation \"Imp \\<phi> \\<psi> \\<equiv> Disj (Neg \\<phi>) \\<psi>\"\nabbreviation \"Iff \\<phi> \\<psi> \\<equiv> Conj (Imp \\<phi> \\<psi>) (Imp \\<psi> \\<phi>)\"\n\ndefinition \"thm1 \\<equiv> ({|Conj (Atom 0) (Neg (Atom 0))|}, {||})\"\n\ndeclare Stream.smember_code [code del]\n\n\ninterpretation RuleSystem \"\\<lambda>r s ss. eff' r s = Some ss\" rules UNIV\n  by unfold_locales (auto simp: rules_UNIV intro: exI[of _ Idle])\n\ninterpretation PersistentRuleSystem \"\\<lambda>r s ss. eff' r s = Some ss\" rules UNIV\nproof (unfold_locales, unfold enabled_def per_def rules_UNIV, clarsimp)\n  fix r \\<Gamma> \\<Delta> ss r' \\<Gamma>' \\<Delta>' ss'\n  assume \"r' \\<noteq> r\" \"eff' r (\\<Gamma>, \\<Delta>) = Some ss\" \"eff' r' (\\<Gamma>, \\<Delta>) = Some ss'\" \"(\\<Gamma>', \\<Delta>') |\\<in>| ss'\"\n  then show \"\\<exists>sl. eff' r (\\<Gamma>', \\<Delta>') = Some sl\"\n    by (cases r r' rule: rule.exhaust[case_product rule.exhaust]) (auto split: if_splits)\nqed\n\ndefinition \"rho \\<equiv> i.fenum rules\"\ndefinition \"propTree \\<equiv> i.mkTree eff' rho\"\n\nexport_code propTree thm1 in Haskell module_name PropInstance (* file \".\" *)\n\n(*<*)\nend\n(*>*)\n", "meta": {"author": "andredidier", "repo": "phd", "sha": "113f7c8b360a3914a571db13d9513e313954f4b2", "save_path": "github-repos/isabelle/andredidier-phd", "path": "github-repos/isabelle/andredidier-phd/phd-113f7c8b360a3914a571db13d9513e313954f4b2/thesis/Abstract_Completeness/Propositional_Logic.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869981319862, "lm_q2_score": 0.8104789178257654, "lm_q1q2_score": 0.7098068984918878}}
{"text": "header {*\\isaheader{Specification of Annotated Lists}*}\ntheory AnnotatedListSpec\nimports ICF_Spec_Base\nbegin\n\n(*@intf AnnotatedList\n  @abstype ('e \\<times> 'a::monoid_add) list\n  Lists with annotated elements. The annotations form a monoid, and there is\n  a split operation to split the list according to its annotations. This is the\n  abstract concept implemented by finger trees.\n*)\n\nsubsection \"Introduction\"\ntext {*\n  We define lists with annotated elements. The annotations form a monoid.\n\n  We provide standard list operations and the split-operation, that\n  splits the list according to its annotations.\n*}\nlocale al =\n  --\"Annotated lists are abstracted to lists of pairs of elements and annotations.\"\n  fixes \\<alpha> :: \"'s \\<Rightarrow> ('e \\<times> 'a::monoid_add) list\"\n  fixes invar :: \"'s \\<Rightarrow> bool\"\n  \nlocale al_no_invar = al +\n  assumes invar[simp, intro!]: \"\\<And>l. invar l\"\n\nsubsection \"Basic Annotated List Operations\"\n\nsubsubsection \"Empty Annotated List\"\nlocale al_empty = al +\n  constrains \\<alpha> :: \"'s \\<Rightarrow> ('e \\<times> 'a::monoid_add) list\"\n  fixes empty :: \"unit \\<Rightarrow> 's\"\n  assumes empty_correct: \n    \"invar (empty ())\" \n    \"\\<alpha> (empty ()) = Nil\" \n\nsubsubsection \"Emptiness Check\"\nlocale al_isEmpty = al + \n  constrains \\<alpha> :: \"'s \\<Rightarrow> ('e \\<times> 'a::monoid_add) list\"\n  fixes isEmpty :: \"'s \\<Rightarrow> bool\"\n  assumes isEmpty_correct: \n    \"invar s \\<Longrightarrow> isEmpty s \\<longleftrightarrow> \\<alpha> s = Nil\" \n\nsubsubsection \"Counting Elements\"\nlocale al_count = al + \n  constrains \\<alpha> :: \"'s \\<Rightarrow> ('e \\<times> 'a::monoid_add) list\"\n  fixes count :: \"'s \\<Rightarrow> nat\"\n  assumes count_correct: \n    \"invar s \\<Longrightarrow> count s = length(\\<alpha> s)\" \n\nsubsubsection \"Appending an Element from the Left\"\nlocale al_consl = al +\n  constrains \\<alpha> :: \"'s \\<Rightarrow> ('e \\<times> 'a::monoid_add) list\"\n  fixes consl :: \"'e \\<Rightarrow> 'a \\<Rightarrow> 's \\<Rightarrow> 's\"\n  assumes consl_correct:\n    \"invar s \\<Longrightarrow> invar (consl e a s)\"\n    \"invar s \\<Longrightarrow> (\\<alpha> (consl e a s)) = (e,a) # (\\<alpha> s)\"\n\nsubsubsection \"Appending an Element from the Right\"\nlocale al_consr = al +\n  constrains \\<alpha> :: \"'s \\<Rightarrow> ('e \\<times> 'a::monoid_add) list\"\n  fixes consr :: \"'s \\<Rightarrow> 'e \\<Rightarrow> 'a \\<Rightarrow> 's\"\n  assumes consr_correct:\n    \"invar s \\<Longrightarrow> invar (consr s e a)\"\n    \"invar s \\<Longrightarrow> (\\<alpha> (consr s e a)) = (\\<alpha> s) @ [(e,a)]\"\n  \nsubsubsection \"Take the First Element\"\nlocale al_head = al + \n  constrains \\<alpha> :: \"'s \\<Rightarrow> ('e \\<times> 'a::monoid_add) list\"\n  fixes head :: \"'s \\<Rightarrow> ('e \\<times> 'a)\"\n  assumes head_correct:\n    \"\\<lbrakk>invar s; \\<alpha> s \\<noteq> Nil\\<rbrakk> \\<Longrightarrow> head s = hd (\\<alpha> s)\"\n\nsubsubsection \"Drop the First Element\"\nlocale al_tail = al + \n  constrains \\<alpha> :: \"'s \\<Rightarrow> ('e \\<times> 'a::monoid_add) list\"\n  fixes tail :: \"'s \\<Rightarrow> 's\"\n  assumes tail_correct:\n    \"\\<lbrakk>invar s; \\<alpha> s \\<noteq> Nil\\<rbrakk> \\<Longrightarrow> \\<alpha> (tail s) = tl (\\<alpha> s)\"\n    \"\\<lbrakk>invar s; \\<alpha> s \\<noteq> Nil\\<rbrakk> \\<Longrightarrow> invar (tail s)\"\n\nsubsubsection \"Take the Last Element\"\nlocale al_headR = al + \n  constrains \\<alpha> :: \"'s \\<Rightarrow> ('e \\<times> 'a::monoid_add) list\"\n  fixes headR :: \"'s \\<Rightarrow> ('e \\<times> 'a)\"\n  assumes headR_correct:\n    \"\\<lbrakk>invar s; \\<alpha> s \\<noteq> Nil\\<rbrakk> \\<Longrightarrow> headR s = last (\\<alpha> s)\"\n\nsubsubsection \"Drop the Last Element\"\nlocale al_tailR = al +   \n  constrains \\<alpha> :: \"'s \\<Rightarrow> ('e \\<times> 'a::monoid_add) list\"\n  fixes tailR :: \"'s \\<Rightarrow> 's\"\n  assumes tailR_correct:\n    \"\\<lbrakk>invar s; \\<alpha> s \\<noteq> Nil\\<rbrakk> \\<Longrightarrow> \\<alpha> (tailR s) = butlast (\\<alpha> s)\"\n    \"\\<lbrakk>invar s; \\<alpha> s \\<noteq> Nil\\<rbrakk> \\<Longrightarrow> invar (tailR s)\"\n\nsubsubsection \"Fold a Function over the Elements from the Left\"\nlocale al_foldl = al + \n  constrains \\<alpha> :: \"'s \\<Rightarrow> ('e \\<times> 'a::monoid_add) list\"\n  fixes foldl :: \"('z \\<Rightarrow> 'e \\<times> 'a \\<Rightarrow> 'z) \\<Rightarrow> 'z \\<Rightarrow> 's \\<Rightarrow> 'z\"\n  assumes foldl_correct:\n    \"invar s \\<Longrightarrow> foldl f \\<sigma> s = List.foldl f \\<sigma> (\\<alpha> s)\"\n\nsubsubsection \"Fold a Function over the Elements from the Right\"\nlocale al_foldr = al + \n  constrains \\<alpha> :: \"'s \\<Rightarrow> ('e \\<times> 'a::monoid_add) list\"\n  fixes foldr :: \"('e \\<times> 'a \\<Rightarrow> 'z \\<Rightarrow> 'z) \\<Rightarrow> 's \\<Rightarrow> 'z \\<Rightarrow> 'z\"\n  assumes foldr_correct:\n    \"invar s \\<Longrightarrow> foldr f s \\<sigma> = List.foldr f (\\<alpha> s) \\<sigma>\"\n\nlocale poly_al_fold = al +\n  constrains \\<alpha> :: \"'s \\<Rightarrow> ('e \\<times> 'a::monoid_add) list\"\nbegin\n  definition foldl where \n    foldl_correct[code_unfold]: \"foldl f \\<sigma> s = List.foldl f \\<sigma> (\\<alpha> s)\"\n  definition foldr where \n    foldr_correct[code_unfold]: \"foldr f s \\<sigma> = List.foldr f (\\<alpha> s) \\<sigma>\"\nend\n    \nsubsubsection \"Concatenation of Two Annotated Lists\"\nlocale al_app = al +\n  constrains \\<alpha> :: \"'s \\<Rightarrow> ('e \\<times> 'a::monoid_add) list\"\n  fixes app :: \"'s \\<Rightarrow> 's \\<Rightarrow> 's\"\n  assumes app_correct:\n    \"\\<lbrakk>invar s;invar s'\\<rbrakk> \\<Longrightarrow> \\<alpha> (app s s') = (\\<alpha> s) @ (\\<alpha> s')\"\n    \"\\<lbrakk>invar s;invar s'\\<rbrakk> \\<Longrightarrow> invar (app s s')\"\n\nsubsubsection \"Readout the Summed up Annotations\"\nlocale al_annot = al +\n  constrains \\<alpha> :: \"'s \\<Rightarrow> ('e \\<times> 'a::monoid_add) list\"\n  fixes annot :: \"'s \\<Rightarrow> 'a\"\n  assumes annot_correct:\n    \"invar s \\<Longrightarrow> (annot s) = (listsum (map snd (\\<alpha> s)))\"\n\nsubsubsection \"Split by Monotone Predicate\"\nlocale al_splits = al + \n  constrains \\<alpha> :: \"'s \\<Rightarrow> ('e \\<times> 'a::monoid_add) list\"\n  fixes splits :: \"('a \\<Rightarrow> bool) \\<Rightarrow> 'a \\<Rightarrow> 's \\<Rightarrow> \n                                ('s \\<times> ('e \\<times> 'a) \\<times> 's)\"\n  assumes splits_correct:\n    \"\\<lbrakk>invar s;\n       \\<forall>a b. p a \\<longrightarrow> p (a + b);\n       \\<not> p i; \n       p (i + listsum (map snd (\\<alpha> s)));\n       (splits p i s) = (l, (e,a), r)\\<rbrakk> \n      \\<Longrightarrow> \n        (\\<alpha> s) = (\\<alpha> l) @ (e,a) # (\\<alpha> r)  \\<and>\n        \\<not> p (i + listsum (map snd (\\<alpha> l)))  \\<and>\n        p (i + listsum (map snd (\\<alpha> l)) + a)  \\<and>\n        invar l  \\<and>\n        invar r\n    \"\nbegin\n  lemma splitsE:\n    assumes \n    invar: \"invar s\" and\n    mono: \"\\<forall>a b. p a \\<longrightarrow> p (a + b)\" and\n    init_ff: \"\\<not> p i\" and\n    sum_tt: \"p (i + listsum (map snd (\\<alpha> s)))\"\n    obtains l e a r where\n    \"(splits p i s) = (l, (e,a), r)\"\n    \"(\\<alpha> s) = (\\<alpha> l) @ (e,a) # (\\<alpha> r)\"\n    \"\\<not> p (i + listsum (map snd (\\<alpha> l)))\"\n    \"p (i + listsum (map snd (\\<alpha> l)) + a)\"\n    \"invar l\"\n    \"invar r\"\n    using assms\n    apply (cases \"splits p i s\")\n    apply (case_tac b)\n    apply (drule_tac i = i and p = p \n      and l = a and r = c and e = aa and a = ba in  splits_correct)\n    apply (simp_all)\n    done\nend    \n\nsubsection \"Record Based Interface\"\nrecord ('e,'a,'s) alist_ops =\n  alist_op_\\<alpha> ::\"'s \\<Rightarrow> ('e \\<times> 'a::monoid_add) list\"\n  alist_op_invar :: \"'s \\<Rightarrow> bool\"\n  alist_op_empty :: \"unit \\<Rightarrow> 's\"\n  alist_op_isEmpty :: \"'s \\<Rightarrow> bool\"\n  alist_op_count :: \"'s \\<Rightarrow> nat\"\n  alist_op_consl :: \"'e \\<Rightarrow> 'a \\<Rightarrow> 's \\<Rightarrow> 's\"\n  alist_op_consr :: \"'s \\<Rightarrow> 'e \\<Rightarrow> 'a \\<Rightarrow> 's\"\n  alist_op_head :: \"'s \\<Rightarrow> ('e \\<times> 'a)\"\n  alist_op_tail :: \"'s \\<Rightarrow> 's\"\n  alist_op_headR :: \"'s \\<Rightarrow> ('e \\<times> 'a)\"\n  alist_op_tailR :: \"'s \\<Rightarrow> 's\"\n  alist_op_app :: \"'s \\<Rightarrow> 's \\<Rightarrow> 's\"\n  alist_op_annot :: \"'s \\<Rightarrow> 'a\"\n  alist_op_splits :: \"('a \\<Rightarrow> bool) \\<Rightarrow> 'a \\<Rightarrow> 's \\<Rightarrow> ('s \\<times> ('e \\<times> 'a) \\<times> 's)\"\n\nlocale StdALDefs = poly_al_fold \"alist_op_\\<alpha> ops\" \"alist_op_invar ops\"\n  for ops :: \"('e,'a::monoid_add,'s,'more) alist_ops_scheme\"\nbegin\n  abbreviation \\<alpha> where \"\\<alpha> == alist_op_\\<alpha> ops\"\n  abbreviation invar where \"invar == alist_op_invar ops \"\n  abbreviation empty where \"empty == alist_op_empty ops \"\n  abbreviation isEmpty where \"isEmpty == alist_op_isEmpty ops \"\n  abbreviation count where \"count == alist_op_count ops\"\n  abbreviation consl where \"consl == alist_op_consl ops \"\n  abbreviation consr where \"consr == alist_op_consr ops \"\n  abbreviation head where \"head == alist_op_head ops \"\n  abbreviation tail where \"tail == alist_op_tail ops \"\n  abbreviation headR where \"headR == alist_op_headR ops \"\n  abbreviation tailR where \"tailR == alist_op_tailR ops \"\n  abbreviation app where \"app == alist_op_app ops \"\n  abbreviation annot where \"annot == alist_op_annot ops \"\n  abbreviation splits where \"splits == alist_op_splits ops \"\nend\n\nlocale StdAL = StdALDefs ops +\n  al \\<alpha> invar +\n  al_empty \\<alpha> invar empty +\n  al_isEmpty \\<alpha> invar isEmpty +\n  al_count \\<alpha> invar count +\n  al_consl \\<alpha> invar consl +\n  al_consr \\<alpha> invar consr +\n  al_head \\<alpha> invar head +\n  al_tail \\<alpha> invar tail +\n  al_headR \\<alpha> invar headR +\n  al_tailR \\<alpha> invar tailR +\n  al_app \\<alpha> invar app +\n  al_annot \\<alpha> invar annot +\n  al_splits \\<alpha> invar splits\n  for ops\nbegin\n  lemmas correct =\n    empty_correct \n    isEmpty_correct\n    count_correct\n    consl_correct\n    consr_correct\n    head_correct\n    tail_correct\n    headR_correct\n    tailR_correct\n    app_correct\n    annot_correct      \n    foldl_correct\n    foldr_correct\nend\n\nlocale StdAL_no_invar = StdAL + al_no_invar \\<alpha> invar\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/Collections/ICF/spec/AnnotatedListSpec.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8757870046160257, "lm_q2_score": 0.8104788995148791, "lm_q1q2_score": 0.7098068877106288}}
{"text": "header {* Generic Computability *}\n\ntheory Computability\nimports HOLCF HOLCFUtils\nbegin\n\ntext {*\nShivers proves the computability of the abstract semantics functions only by generic and slightly simplified example. This theory contains the abstract treatment in Section 4.4.3. Later, we will work out the details apply this to @{text \\<aPR>}.\n*}\n\nsubsection {* Non-branching case *}\n\ntext {*\n\nAfter the following lemma (which could go into @{theory Set_Interval}), we show Shivers' Theorem 10. This says that the least fixed point of the equation\n\\[\nf\\ x = g\\ x \\cup f\\ (r\\ x)\n\\]\nis given by \n\\[\nf\\ x = \\bigcup_{i\\ge 0} g\\ (r^i\\ x).\n\\]\n\nThe proof follows the standard proof of showing an equality involving a fixed point: First we show that the right hand side fulfills the above equation and then show that our solution is less than any other solution to that equation.\n*}\n\nlemma insert_greaterThan:\n  \"insert (n::nat) {n<..} = {n..}\"\nby auto\n\nlemma theorem10:\n  fixes g :: \"'a::cpo \\<rightarrow> 'b::type set\" and r :: \"'a \\<rightarrow> 'a\"\n  shows \"fix\\<cdot>(\\<Lambda> f x. g\\<cdot>x \\<union> f\\<cdot>(r\\<cdot>x)) = (\\<Lambda> x. (\\<Union>i. g\\<cdot>(r\\<^bsup>i\\<^esup>\\<cdot>x)))\"\nproof(induct rule:fix_eqI[OF cfun_eqI cfun_belowI, case_names fp least])\ncase (fp x)\n  have \"g\\<cdot>x \\<union> (\\<Union>i. g\\<cdot>(r\\<^bsup>i\\<^esup>\\<cdot>(r\\<cdot>x))) = g\\<cdot>(r\\<^bsup>0\\<^esup>\\<cdot>x) \\<union> (\\<Union>i. g\\<cdot>(r\\<^bsup>Suc i\\<^esup>\\<cdot>x))\"\n    by (simp add: iterate_Suc2 del: iterate_Suc)\n  also have \"\\<dots> = g\\<cdot>(r\\<^bsup>0\\<^esup>\\<cdot>x) \\<union> (\\<Union>i\\<in>{0<..}. g\\<cdot>(r\\<^bsup>i\\<^esup>\\<cdot>x))\"\n    by auto\n  also have \"\\<dots>  = (\\<Union>i\\<in>insert 0 {0<..}. g\\<cdot>(r\\<^bsup>i\\<^esup>\\<cdot>x))\"\n    by simp\n  also have \"... = (\\<Union>i. g\\<cdot>(r\\<^bsup>i\\<^esup>\\<cdot>x))\"\n    by (simp only: insert_greaterThan atLeast_0 )\n  finally\n  show ?case by auto\nnext\ncase (least f x)\n  hence expand: \"\\<And>x. f\\<cdot>x = (g\\<cdot>x \\<union> f\\<cdot>(r\\<cdot>x))\" by (auto simp:cfun_eq_iff)\n  { fix n\n    have \"f\\<cdot>x = (\\<Union>i\\<in>{..n}. g\\<cdot>(r\\<^bsup>i\\<^esup>\\<cdot>x)) \\<union> f\\<cdot>(r\\<^bsup>Suc n\\<^esup>\\<cdot>x)\"\n    proof(induct n)\n      case 0 thus ?case by (auto simp add:expand[of x])\n      case (Suc n)\n      then have \"f\\<cdot>x = (\\<Union>i\\<in>{..n}. g\\<cdot>(r\\<^bsup>i\\<^esup>\\<cdot>x)) \\<union> f\\<cdot>(r\\<^bsup>Suc n\\<^esup>\\<cdot>x)\" by simp\n      also have \"\\<dots> = (\\<Union>i\\<in>{..n}. g\\<cdot>(r\\<^bsup>i\\<^esup>\\<cdot>x))\n                 \\<union> g\\<cdot>(r\\<^bsup>Suc n\\<^esup>\\<cdot>x) \\<union> f\\<cdot>(r\\<^bsup>Suc (Suc n)\\<^esup>\\<cdot>x)\"\n             by(subst expand[of \"r\\<^bsup>Suc n\\<^esup>\\<cdot>x\"], auto)\n      also have \"\\<dots> = (\\<Union>i\\<in>insert (Suc n) {..n}. g\\<cdot>(r\\<^bsup>i\\<^esup>\\<cdot>x)) \\<union> f\\<cdot>(r\\<^bsup>Suc (Suc n)\\<^esup>\\<cdot>x)\"\n             by auto\n      also have \"\\<dots> = (\\<Union>i\\<in>{..Suc n}. g\\<cdot>(r\\<^bsup>i\\<^esup>\\<cdot>x)) \\<union> f\\<cdot>(r\\<^bsup>Suc (Suc n)\\<^esup>\\<cdot>x)\"\n             by (simp add:atMost_Suc)\n      finally show ?case .\n    qed\n  } note fin = this\n  have \"(\\<Union>i. g\\<cdot>(r\\<^bsup>i\\<^esup>\\<cdot>x)) \\<subseteq> f\\<cdot>x\"\n    proof(rule UN_least)\n      fix i\n      show \"g\\<cdot>(r\\<^bsup>i\\<^esup>\\<cdot>x) \\<subseteq> f\\<cdot>x\"\n      using fin[of i] by auto\n    qed\n  thus ?case\n    apply (subst sqsubset_is_subset) by auto\nqed\n\nsubsection {* Branching case *}\n\ntext {*\nActually, our functions are more complicated than the one above: The abstract semantics functions recurse with multiple arguments. So we have to handle a recursive equation of the kind\n\\[\nf\\ x = g\\ x \\cup \\bigcup_{a \\in R\\ x} f\\ r.\n\\]\nBy moving to the power-set relatives of our function, e.g.\n\\[\n{\\uline g}Y = \\bigcup_{a\\in A} g\\ a \\quad \\text{and} {\\uline R}Y = \\bigcup_{a\\in R} R\\ a\n\\]\nthe equation becomes\n\\[\n{\\uline f}Y ={\\uline g}Y \\cup {\\uline f}\\ ({\\uline R}Y)\n\\]\n(which is shown in Lemma 11) and we can apply Theorem 10 to obtain Theorem 12.\n\nWe define the power-set relative for a function together with some properties.\n*}\n\ndefinition powerset_lift :: \"('a::cpo \\<rightarrow> 'b::type set) \\<Rightarrow> 'a set \\<rightarrow> 'b set\" (\"\\<^ps>\")\n  where \"\\<^ps>f = (\\<Lambda> S. (\\<Union>y\\<in>S . f\\<cdot>y))\"\n\nlemma powerset_lift_singleton[simp]:\n  \"\\<^ps>f\\<cdot>{x} = f\\<cdot>x\"\nunfolding powerset_lift_def by simp\n\nlemma powerset_lift_union[simp]:\n  \"\\<^ps>f\\<cdot>(A \\<union> B) = \\<^ps>f\\<cdot>A \\<union> \\<^ps>f\\<cdot>B\"\nunfolding powerset_lift_def by auto\n\nlemma UNION_commute:\"(\\<Union>x\\<in>A. \\<Union>y\\<in>B . P x y) = (\\<Union>y\\<in>B. \\<Union>x\\<in>A . P x y)\"\n  by auto\n\nlemma powerset_lift_UNION:\n  \"(\\<Union>x\\<in>S. \\<^ps>g\\<cdot>(A x)) = \\<^ps>g\\<cdot>(\\<Union>x\\<in>S. A x)\"\nunfolding powerset_lift_def by auto\n\nlemma powerset_lift_iterate_UNION:\n  \"(\\<Union>x\\<in>S. (\\<^ps>g)\\<^bsup>i\\<^esup>\\<cdot>(A x)) = (\\<^ps>g)\\<^bsup>i\\<^esup>\\<cdot>(\\<Union>x\\<in>S. A x)\"\nby (induct i, auto simp add:powerset_lift_UNION)\n\nlemmas powerset_distr = powerset_lift_UNION powerset_lift_iterate_UNION\n\n\ntext {*\nLemma 11 shows that if a function satisfies the relation with the branching $R$, its power-set function satisfies the powerset variant of the equation.\n\n*}\n\nlemma lemma11:\n  fixes f :: \"'a \\<rightarrow> 'b set\" and g :: \"'a \\<rightarrow> 'b set\" and R :: \"'a \\<rightarrow> 'a set\"\n  assumes \"\\<And>x. f\\<cdot>x = g\\<cdot>x \\<union> (\\<Union>y\\<in>R\\<cdot>x. f\\<cdot>y)\"\n  shows \"\\<^ps>f\\<cdot>S = \\<^ps>g\\<cdot>S \\<union> \\<^ps>f\\<cdot>(\\<^ps>R\\<cdot>S)\"\nproof-\n  have \"\\<^ps>f\\<cdot>S = (\\<Union>x\\<in>S . f\\<cdot>x)\" unfolding powerset_lift_def by auto\n  also have \"\\<dots> = (\\<Union>x\\<in>S . g\\<cdot>x \\<union> (\\<Union>y\\<in>R\\<cdot>x. f\\<cdot>y))\" apply (subst assms) by simp\n  also have \"\\<dots> = \\<^ps>g\\<cdot>S \\<union> \\<^ps>f\\<cdot>(\\<^ps>R\\<cdot>S)\" by (auto simp add:powerset_lift_def)\n  finally\n  show ?thesis .\nqed\n\ntext {*\nTheorem 10 as it will be used in Theorem 12.\n*}\nlemmas theorem10ps = theorem10[of \"\\<^ps>g\" \"\\<^ps>r\"] for g r\n\ntext {*\nNow we can show Lemma 12: If $F$ is the least solution to the recursive power-set equation, then $x \\mapsto F\\ {x}$ is the least solution to the equation with branching $R$.\n\nWe fix the type variable @{text 'a} to be a discrete cpo, as otherwise $x \\mapsto \\{x\\}$ is not continuous.\n*}\n\n(* discrete_cpo, otherwise x \\<mapsto> {x} not continous *)\nlemma theorem12':\n  fixes g :: \"'a::discrete_cpo \\<rightarrow> 'b::type set\" and R :: \"'a \\<rightarrow> 'a set\"\n  assumes F_fix: \"F = fix\\<cdot>(\\<Lambda> F x. \\<^ps>g\\<cdot>x \\<union> F\\<cdot>(\\<^ps>R\\<cdot>x))\"\n  shows \"fix\\<cdot>(\\<Lambda> f x. g\\<cdot>x \\<union> (\\<Union>y\\<in>R\\<cdot>x. f\\<cdot>y)) = (\\<Lambda> x. F\\<cdot>{x})\"\nproof(induct rule:fix_eqI[OF cfun_eqI cfun_belowI, case_names fp least])\nhave F_union: \"F = (\\<Lambda> x. \\<Union>i. \\<^ps>g\\<cdot>((\\<^ps>R)\\<^bsup>i\\<^esup>\\<cdot>x))\"\n  using F_fix by(simp)(rule theorem10ps)\ncase (fp x)\n   have \"g\\<cdot>x \\<union> (\\<Union>x'\\<in>R\\<cdot>x. F\\<cdot>{x'}) = \\<^ps>g\\<cdot>{x} \\<union> F\\<cdot>(\\<^ps>R\\<cdot>{x})\"\n    unfolding powerset_lift_singleton\n    by (auto simp add: powerset_distr UNION_commute F_union)\n  also have \"\\<dots> = F\\<cdot>{x}\"\n    by (subst (2) fix_eq4[OF F_fix], auto)\n  finally show ?case by simp\nnext\ncase (least f' x)\n  hence expand: \"f' = (\\<Lambda> x. g\\<cdot>x \\<union> (\\<Union>y\\<in>R\\<cdot>x. f'\\<cdot>y))\" by simp\n  have \"\\<^ps>f' = (\\<Lambda> S. \\<^ps>g\\<cdot>S \\<union> \\<^ps>f'\\<cdot>(\\<^ps>R\\<cdot>S))\"\n    by (subst expand, rule cfun_eqI, auto simp add:powerset_lift_def)\n  hence \"(\\<Lambda> F. \\<Lambda> x. \\<^ps>g\\<cdot>x \\<union> F\\<cdot>(\\<^ps>R\\<cdot>x))\\<cdot>(\\<^ps>f') = \\<^ps>f'\" by simp\n  from fix_least[OF this] and F_fix\n  have  \"F \\<sqsubseteq> \\<^ps>f'\"  by simp\n  hence  \"F\\<cdot>{x} \\<sqsubseteq> \\<^ps>f'\\<cdot>{x}\"\n    by (subst (asm)cfun_below_iff, auto simp del:powerset_lift_singleton)\n  thus ?case by (auto simp add:sqsubset_is_subset)\nqed\n\nlemma theorem12:\n  fixes g :: \"'a::discrete_cpo \\<rightarrow> 'b::type set\" and R :: \"'a \\<rightarrow> 'a set\"\n  shows \"fix\\<cdot>(\\<Lambda> f x. g\\<cdot>x \\<union> (\\<Union>y\\<in>R\\<cdot>x. f\\<cdot>y))\\<cdot>x =  \\<^ps>g\\<cdot>(\\<Union>i.((\\<^ps>R)\\<^bsup>i\\<^esup>\\<cdot>{x}))\"\n  by(subst theorem12'[OF theorem10ps[THEN sym]], auto simp add:powerset_distr)\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/Shivers-CFA/Computability.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104788995148791, "lm_q2_score": 0.8757870029950159, "lm_q1q2_score": 0.7098068863968345}}
{"text": "section \"Arithmetic and Boolean Expressions\"\n  \ntheory LExp imports Main begin\n  \nsubsection \"Arithmetic Expressions\"\n  \ntype_synonym vname = string\ntype_synonym val = int\ntype_synonym state = \"vname \\<Rightarrow> val\"\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 := x, b := y> = (<> (a := x)) (b := (y::int))\"\n  by (rule refl)\n    \nlemma\n  assumes \"a \\<noteq> b\"\n  shows\"<a := x, b := y> = <b := (y::int), a := x>\"\n  using assms by auto\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    \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    \nvalue \"aval (Plus (V ''x'') (N 5)) <''x'' := 7>\"  \n  \n  (* exercise 3.6 *)\n  \n(* The value of \nLet x e\\<^sub>x\\<^sub>_\\<^sub>i\\<^sub>s e\\<^sub>e\\<^sub>v\\<^sub>a\\<^sub>l\\<^sub>_\\<^sub>m\\<^sub>e\nis: replace the value of x in the original state with e\\<^sub>x\\<^sub>_\\<^sub>i\\<^sub>s, and evaluate e\\<^sub>e\\<^sub>v\\<^sub>a\\<^sub>l\\<^sub>_\\<^sub>m\\<^sub>e using\nthe new state*)\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 x) s = s x\" |\n  \"lval (Plusl a\\<^sub>1 a\\<^sub>2) s = lval a\\<^sub>1 s + lval a\\<^sub>2 s\"|\n  \"lval (Let x e\\<^sub>x\\<^sub>_\\<^sub>i\\<^sub>s e\\<^sub>e\\<^sub>v\\<^sub>a\\<^sub>l\\<^sub>_\\<^sub>m\\<^sub>e) s\\<^sub>o\\<^sub>u\\<^sub>t\\<^sub>e\\<^sub>r = lval e\\<^sub>e\\<^sub>v\\<^sub>a\\<^sub>l\\<^sub>_\\<^sub>m\\<^sub>e (s\\<^sub>o\\<^sub>u\\<^sub>t\\<^sub>e\\<^sub>r(x := (lval e\\<^sub>x\\<^sub>_\\<^sub>i\\<^sub>s s\\<^sub>o\\<^sub>u\\<^sub>t\\<^sub>e\\<^sub>r)))\"\n  \nvalue \"aval (Plus (V ''x'') (N 5)) <''x'' := 2>\"\n  \nvalue \"lval (Let ''x'' (Plusl (Nl 1)(Nl 3)) (Plusl (Vl ''x'') (Nl 5))) <''x'' := 2>\"\n  \n(* Convert every lexp into the corresponding aexp.\nLet will have to be converted into a (V x). *)  \nfun inline :: \"lexp \\<Rightarrow> aexp\"  where\n  \"inline (Nl n) = (N n)\" |\n \"inline (Vl x) = V x\" |\n \"inline (Plusl a\\<^sub>1 a\\<^sub>2) = Plus (inline a\\<^sub>1) (inline a\\<^sub>2)\"|\n(* Evaluate e\\<^sub>e\\<^sub>v\\<^sub>a\\<^sub>l\\<^sub>_\\<^sub>m\\<^sub>e, with the state that x := e\\<^sub>x\\<^sub>_\\<^sub>i\\<^sub>s *)\n(* The expression Let x e\\<^sub>x\\<^sub>_\\<^sub>i\\<^sub>s e\\<^sub>e\\<^sub>v\\<^sub>a\\<^sub>l\\<^sub>_\\<^sub>m\\<^sub>e is inlined by substituting the converted form of e\\<^sub>x\\<^sub>_\\<^sub>i\\<^sub>s for x in the\nconverted form of e\\<^sub>e\\<^sub>v\\<^sub>a\\<^sub>l\\<^sub>_\\<^sub>m\\<^sub>e. *)\n (* I think the problem is that lval e\\<^sub>x\\<^sub>_\\<^sub>i\\<^sub>s uses the empty state *)\n \"inline (Let x e\\<^sub>x\\<^sub>_\\<^sub>i\\<^sub>s e\\<^sub>e\\<^sub>v\\<^sub>a\\<^sub>l\\<^sub>_\\<^sub>m\\<^sub>e) = N (lval e\\<^sub>e\\<^sub>v\\<^sub>a\\<^sub>l\\<^sub>_\\<^sub>m\\<^sub>e <x := (lval e\\<^sub>x\\<^sub>_\\<^sub>i\\<^sub>s <>)>)\"\n \n(* Prove the so-called substitution lemma that says that we can either substitute first and evaluate\nafterwards or evaluate with an updated state *)\n (* lemma substitution:\"aval (subst x a e) s = aval e (s(x := aval a s))\" *)\n\ntheorem inline_substitution:\n  (* The exercise didn't say to set s = <>, but there's no way the proof would work otherwise. I guess\nit's possible I defined lval or inline incorrectly.*)\n  shows \"aval (inline expr) <> = lval expr <>\"\n  apply(induction expr arbitrary: s)\n  by simp_all\n\n    (* prove: *)\n    (* lval expr2 <x1a := lval expr1 <>> = lval expr2 (s(x1a := lval expr1 s)) *)\n    (* Evaluate expr1 using empty state; the variable referred to by x1a is now that N (a number).\n    Evaluate expr2 with the state containing the one variable, x1a. *)\n    (* Now compare the above to: *)\n    (* Evaluate expr1 using state s; x1a is now that N. Evaluate expr2 using state s with x1a set as\n    described. *)\n    \n    (* Obviously these are different, because s \\<noteq> empty state. *)\n\n    (* tried in vain *)\n  (* apply(induction rule:inline.induct)  *)\n  \nsubsection \"Constant Folding\"\n  \ntext{* Evaluate constant subsexpressions: *}\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\"\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 \\<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\"\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 \\<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\"\n  apply(induction a)\n  apply simp_all\n  done\n    \n(*     \n(* Define a substitution function \nsubst :: vname \\<Rightarrow> aexp \\<Rightarrow> aexp \\<Rightarrow> aexp \nsuch that \nsubst x a e \nis the result of replacing every\noccurrence of variable x by a in e *)\nfun subst :: \"vname \\<Rightarrow> aexp \\<Rightarrow> aexp \\<Rightarrow> 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\\<^sub>1 e\\<^sub>2) = \n      Plus (subst matchMe replaceWith e\\<^sub>1) (subst matchMe replaceWith e\\<^sub>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 =\\<Rightarrow> 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\\<^sub>1 s = aval a\\<^sub>2 s \n  \\<Longrightarrow> aval (subst x a\\<^sub>1 e) s = aval (subst x a\\<^sub>2 e) s\"\n  apply(induction e)\n  by auto *)\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/LExp.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8757869819218865, "lm_q2_score": 0.8104788995148791, "lm_q1q2_score": 0.7098068693175079}}
{"text": "(*  Title:       Jech Exercises\n    Author:      Georgy Dunaev <georgedunaev at gmail.com>, 2019\n    Maintainer:  Georgy Dunaev <georgedunaev at gmail.com>\n*)\n\nsection \"Jech Exrecises\"\ntheory JechExercises imports trivia\nbegin\n\ntext \\<open>preliminaries\\<close>\ndefinition Ind :: \\<open>i\\<Rightarrow>o\\<close>\n  where Ind_def : \\<open>Ind(x) == 0 \\<in> x \\<and> (\\<forall>y\\<in>x. succ(y) \\<in> x)\\<close>\n\nlemma IndInf : \\<open>Ind(Inf)\\<close>\n  by(unfold Ind_def, rule infinity)\n\nlemma IndI :\n  assumes c0 : \\<open>0 \\<in> x\\<close>\n      and cS : \\<open>\\<And>xa. xa \\<in> x \\<Longrightarrow> succ(xa) \\<in> x\\<close>\n    shows \\<open>Ind(x)\\<close>\nproof -\n  from cS have \\<open>\\<And>xa. xa \\<in> x \\<longrightarrow> succ(xa) \\<in> x\\<close>\n    by (rule impI)\n  hence \\<open>\\<forall>xa. xa \\<in> x \\<longrightarrow> succ(xa) \\<in> x\\<close>\n    by (rule allI)\n  hence \\<open>(\\<forall>y\\<in>x. succ(y) \\<in> x)\\<close>\n    by (fold Ball_def)\n  with c0 have \\<open>0 \\<in> x \\<and> (\\<forall>y\\<in>x. succ(y) \\<in> x)\\<close>\n    by (rule conjI)\n  thus \\<open>Ind(x)\\<close> by (fold Ind_def)\nqed\n\nlemma IndE1 :\n  assumes a:\\<open>Ind(x)\\<close>\n  shows \\<open>0 \\<in> x\\<close>\nproof -\n  from a\n  have \\<open>0 \\<in> x \\<and> (\\<forall>y\\<in>x. succ(y) \\<in> x)\\<close> by (unfold Ind_def)\n  thus \\<open>0 \\<in> x\\<close> by (rule conjunct1)\nqed\n\nlemma IndE2 :\n  assumes a:\\<open>Ind(x)\\<close>\n  shows \\<open>\\<forall>xa. xa \\<in> x \\<longrightarrow> succ(xa) \\<in> x\\<close>\nproof -\n  from a\n  have \\<open>0 \\<in> x \\<and> (\\<forall>y\\<in>x. succ(y) \\<in> x)\\<close> by (unfold Ind_def)\n  hence \\<open>(\\<forall>y\\<in>x. succ(y) \\<in> x)\\<close> by (rule conjunct2)\n  thus \\<open>\\<forall>xa. xa \\<in> x \\<longrightarrow> succ(xa) \\<in> x\\<close> by (unfold Ball_def)\nqed\n\nlemma IndE2R :\n  assumes \\<open>Ind(x)\\<close>\n  shows \\<open>\\<And>xa. xa \\<in> x \\<Longrightarrow> succ(xa) \\<in> x\\<close>\nproof -\n  from \\<open>Ind(x)\\<close> have \\<open>\\<forall>xa. xa \\<in> x \\<longrightarrow> succ(xa) \\<in> x\\<close> by (rule IndE2)\n  thus \\<open>\\<And>xa. xa \\<in> x \\<Longrightarrow> succ(xa) \\<in> x\\<close> by (rule spec[THEN impE])\nqed\n\ntext \\<open>ex 1.1: Verify (a, b) = (c, d) if and only if a = c and b = d.\\<close>\n\ntheorem ex_1_1 : \\<open><a,b> = <c,d> \\<longleftrightarrow> a=c & b=d\\<close>\n  by (rule pair.Pair_iff)\n\ntext \\<open>ex 1.2: There is no set X such that $Pow(X)\\subseteq X$.\\<close>\ncontext\n  fixes S\n  fixes W defines W_def : \\<open>W == {x\\<in>S. x\\<notin>x}\\<close>\nbegin\n\nlemma notWinW :\n  assumes y : \\<open>W \\<in> W\\<close> \n  shows \\<open>False\\<close>\nproof (rule notE[where P=\\<open>W \\<in> W\\<close>])\n  from y have \\<open>W \\<in> {x \\<in> S . x \\<notin> x}\\<close> by (unfold W_def)\n  then show \\<open>W \\<notin> W\\<close> by (rule CollectD2)\nnext\n  show \\<open>W \\<in> W\\<close> by (rule y)\nqed\n\ntheorem ex_1_2 : \\<open>\\<not> ( Pow(S) \\<subseteq> S )\\<close>\nproof (rule notI)\n  assume \\<open>Pow(S) \\<subseteq> S\\<close>\n  have \\<open>{x \\<in> S . x \\<notin> x} \\<subseteq> S\\<close> using CollectD1 by (rule subsetI)\n  hence \\<open>W \\<subseteq> S\\<close> by (unfold W_def)\n  hence \\<open>W \\<in> Pow(S)\\<close> by (rule PowI)\n  with \\<open>Pow(S) \\<subseteq> S\\<close> have \\<open>W \\<in> S\\<close> by (rule subsetD)\n  show \\<open>False\\<close>\n  proof (rule case_split[where P=\\<open>W \\<in> W\\<close>])\n    show \\<open>W \\<in> W \\<Longrightarrow> False\\<close> by (rule notWinW)\n  next\n    from \\<open>W \\<in> S\\<close> have \\<open>{x \\<in> S . x \\<notin> x} \\<in> S\\<close> by (unfold W_def) moreover\n    assume \\<open>W \\<notin> W\\<close>\n    hence \\<open>{x \\<in> S . x \\<notin> x} \\<notin> {x \\<in> S . x \\<notin> x}\\<close> by (unfold W_def)\n    ultimately have \\<open>{x \\<in> S . x \\<notin> x} \\<in> {x \\<in> S . x \\<notin> x}\\<close> by (rule CollectI)\n    hence \\<open>W \\<in> W\\<close> by (fold W_def) \n    with \\<open>W \\<notin> W\\<close>\n    show \\<open>False\\<close> by (rule notE)\n  qed\nqed\nend\n\ntext \\<open>ex 1.3: If X is inductive, then the set $\\{x \\in X : x \\subseteq X\\}$ is inductive. Hence N is\ntransitive, and for each n, $n = \\{m \\in N : m < n\\}$.\\<close>\ncontext\n  fixes x\n  assumes a:\\<open>Ind(x)\\<close>\nbegin\nlemma subsetsu : \\<open>\\<And>xa. xa \\<in> {y \\<in> x . y \\<subseteq> x} \\<Longrightarrow>\n          succ(xa) \\<in> {y \\<in> x . y \\<subseteq> x}\\<close> \nproof -\n  fix k\n  assume h:\\<open>k \\<in> {y \\<in> x . y \\<subseteq> x}\\<close>\n  from h have h1:\\<open>k \\<in> x\\<close> by (rule CollectD1[where A=\\<open>x\\<close>])\n  from h have h2:\\<open>k \\<subseteq> x\\<close> by (rule CollectD2[where P=\\<open>\\<lambda>w. w\\<subseteq>x\\<close>])\n  from a and h1 have \\<open>succ(k) \\<in> x\\<close> by (rule IndE2R)\n  have \\<open>\\<And>xa. xa \\<in> succ(k) \\<Longrightarrow> xa \\<in> x\\<close>\n  proof -\n    fix xa\n    assume \\<open>xa \\<in> succ(k)\\<close>\n    hence \\<open>xa = k \\<or> xa \\<in> k\\<close> by (rule SuccE)\n    thus \\<open>xa \\<in> x\\<close>\n    proof (rule disjE)\n      assume \\<open>xa = k\\<close>\n      with h1 show \\<open>xa \\<in> x\\<close> by (rule subst_elem)\n    next\n      assume \\<open>xa \\<in> k\\<close>\n      with h2  show \\<open>xa \\<in> x\\<close> by (rule subsetD)\n    qed\n  qed\n  hence \\<open>succ(k) \\<subseteq> x\\<close> by (rule subsetI)\n  with \\<open>succ(k) \\<in> x\\<close>\n  show \\<open>succ(k) \\<in> {y \\<in> x . y \\<subseteq> x}\\<close> by (rule CollectI[where P=\\<open>\\<lambda>y. y\\<subseteq>x\\<close>])\nqed  \n\ntheorem ex1_3:\n  shows \\<open>Ind({y\\<in>x. y\\<subseteq>x})\\<close>\nproof -\n  from a\n  have \\<open>0 \\<in> x\\<close> by (rule IndE1)\n  have \\<open>0 \\<subseteq> x\\<close> by (rule empty_subsetI)\n  with \\<open>0 \\<in> x\\<close> have d:\\<open>0 \\<in> {y \\<in> x . y \\<subseteq> x}\\<close> by (rule CollectI)\n  from d and subsetsu show \\<open>Ind({y\\<in>x. y\\<subseteq>x})\\<close> by (rule IndI)\nqed\n\nend\n\ndefinition ClassInter :: \\<open>(i\\<Rightarrow>o)\\<Rightarrow>(i\\<Rightarrow>o)\\<close>\n  where ClassInter_def : \\<open>ClassInter(P,x) == \\<forall>y. P(y) \\<longrightarrow> x\\<in>y\\<close>\n\ndefinition Nat :: \\<open>i\\<Rightarrow>o\\<close>\n  where \\<open>Nat == ClassInter(Ind)\\<close>\n\nlemma NatSubInf : \\<open>\\<And>x. Nat(x) \\<Longrightarrow> x\\<in>Inf\\<close>\nproof (unfold Nat_def)\n  fix x\n  assume p0:\\<open>ClassInter(Ind, x)\\<close>\n  show \\<open>x\\<in>Inf\\<close>\n  proof -\n    from p0 have \\<open>\\<forall>y. Ind(y) \\<longrightarrow> x \\<in> y\\<close> by (unfold ClassInter_def)\n    hence \\<open>Ind(Inf) \\<longrightarrow> x \\<in> Inf\\<close> by (rule spec)\n    hence p3:\\<open>Ind(Inf) \\<Longrightarrow> x \\<in> Inf\\<close> by (rule mp)\n    from IndInf show p4:\\<open>x \\<in> Inf\\<close> by (rule p3)\n  qed\nqed\n\nlemma NatSubInf' : \\<open>\\<forall>x. (Nat(x) \\<longrightarrow> x\\<in>Inf)\\<close>\nproof (rule allI)\n  fix x from NatSubInf show \\<open>(Nat(x) \\<longrightarrow> x\\<in>Inf)\\<close> by (rule impI)\nqed\n\ndefinition IsTransClass :: \\<open>(i\\<Rightarrow>o)\\<Rightarrow>o\\<close>\n  where IsTransClass_def : \\<open>IsTransClass(P) == \\<forall>y. P(y) \\<longrightarrow> (\\<forall>z. z\\<in>y \\<longrightarrow> P(z))\\<close>\n\nlemma Nat0 : \\<open>Nat(0)\\<close>\nproof -\n  have \\<open>\\<And>y. 0 \\<in> y \\<and> (\\<forall>ya\\<in>y. succ(ya) \\<in> y) \\<Longrightarrow> 0 \\<in> y\\<close> by (erule conjE)\n  hence \\<open>\\<And>y. Ind(y) \\<Longrightarrow> 0 \\<in> y\\<close> by (unfold Ind_def)\n  hence \\<open>\\<And>y. Ind(y) \\<longrightarrow> 0 \\<in> y\\<close> by (rule impI)\n  hence \\<open>\\<forall>y. Ind(y) \\<longrightarrow> 0 \\<in> y\\<close> by (rule allI)\n  hence \\<open>ClassInter(Ind, 0)\\<close> by (unfold ClassInter_def) \n  thus ?thesis by (unfold Nat_def)\nqed\n\nlemma NatSu:\n  fixes x w\n  assumes a:\\<open>\\<forall>y. Ind(y) \\<longrightarrow> x \\<in> y\\<close>\n  assumes b:\\<open>Ind(w)\\<close>\n  shows \\<open>succ(x) \\<in> w\\<close>\nproof -\n  from b have j:\\<open>\\<And>xa. xa \\<in> w \\<Longrightarrow> succ(xa) \\<in> w\\<close> by (rule IndE2R)\n  from a have \\<open>Ind(w) \\<longrightarrow> x \\<in> w\\<close> by (rule spec)\n  from this and b have \\<open>x \\<in> w\\<close> by (rule mp)\n  from \\<open>x \\<in> w\\<close> show \\<open>succ(x) \\<in> w\\<close> by (rule j)\nqed\n\nlemma NatSucc : \\<open>\\<forall>x. Nat(x) \\<longrightarrow> Nat(succ(x))\\<close>\nproof (rule allI[OF impI])\n  fix x\n  assume \\<open>Nat(x)\\<close>\n  hence \\<open>ClassInter(Ind)(x)\\<close> by (unfold Nat_def)\n  hence \\<open>\\<forall>y. Ind(y) \\<longrightarrow> x\\<in>y\\<close> by (unfold ClassInter_def)\n  have \\<open>\\<forall>y. Ind(y) \\<longrightarrow> succ(x)\\<in>y\\<close>\n  proof (rule allI[OF impI])\n    fix y\n    assume \\<open>Ind(y)\\<close>\n    with \\<open>\\<forall>y. Ind(y) \\<longrightarrow> x\\<in>y\\<close> show \\<open>succ(x)\\<in>y\\<close> by (rule NatSu)\n  qed\n  hence \\<open>ClassInter(Ind)(succ(x))\\<close> by (fold ClassInter_def)\n  then show \\<open>Nat(succ(x))\\<close> by (fold Nat_def)\nqed\n\ndefinition IsIndClass :: \\<open>(i\\<Rightarrow>o)\\<Rightarrow>o\\<close>\n  where IsIndClass_def : \\<open>IsIndClass(P) == P(0) \\<and> (\\<forall>y. P(y) \\<longrightarrow> P(succ(y)))\\<close>\n\nlemma NatIsInd : \\<open>IsIndClass(Nat)\\<close>\nproof (unfold IsIndClass_def)\n  from Nat0 and NatSucc \n  show \\<open>Nat(0) \\<and> (\\<forall>y. Nat(y) \\<longrightarrow> Nat(succ(y)))\\<close> by (rule conjI)\nqed\n\ndefinition Omega :: \\<open>i\\<close>\n  where Omega_def : \\<open>Omega == { y \\<in> Inf . Nat(y) }\\<close>\n\nlemma NatSubOmega : \\<open>\\<And>x. Nat(x) \\<Longrightarrow> x \\<in> Omega\\<close>\nproof -\n  fix x\n  assume \\<open>Nat(x)\\<close>\n  hence \\<open>x \\<in> Inf\\<close> by (rule NatSubInf)\n  from \\<open>x \\<in> Inf\\<close> and \\<open>Nat(x)\\<close> have \\<open>x \\<in> {x\\<in>Inf. Nat(x)}\\<close> by (rule CollectI)\n  thus \\<open>x \\<in> Omega\\<close> by (fold Omega_def)\nqed\n\nnotepad\nbegin\nassume a: A and b: B\nthm conjI\nthm conjI [of A B] (*\u2014 instantiation*)\nthm conjI [of A B, OF a b] (*\u2014 instantiation and composition*)\nthm conjI [OF a b] (*\u2014 composition via unification (trivial)*)\n(*thm conjI [OF \"A\" \"B\"]*)\nthm conjI [OF disjI1]\nend\n\n(* image f of union is the union of images f *)\n(* lemma image_UN: \"r `` (\\<Union>x\\<in>A. B(x)) = (\\<Union>x\\<in>A. r `` B(x))\" *)\n\nlemma \"r``(\\<Union>A) = (\\<Union>x\\<in>A. r``x)\"\n  by blast\n\nlemma \"r``(\\<Union>A) = (\\<Union>x\\<in>A. r``x)\"\nproof (rule equalityI)\n  have l1:\\<open>\\<And>x. x \\<in> r `` (\\<Union>A) \\<Longrightarrow>\n         x \\<in> (\\<Union>x\\<in>A. r `` x)\\<close>\n  proof -\n    fix x\n    assume a1:\\<open>x \\<in> r `` (\\<Union>A)\\<close>\n    hence a2:\\<open>x \\<in> {y \\<in> range(r) . \\<exists>x\\<in>\\<Union>A. \\<langle>x, y\\<rangle> \\<in> r}\\<close> by (unfold image_def)\n(*    from a2 have a3:\\<open>x \\<in> range(r)\\<close> by (rule CollectE)*)\n    from a2 have a4:\\<open>\\<exists>xa\\<in>\\<Union>A. \\<langle>xa, x\\<rangle> \\<in> r\\<close> by (rule CollectE)\n    from a4 obtain xa where b1:\"xa\\<in>\\<Union>A\" and b2:\"\\<langle>xa, x\\<rangle> \\<in> r\" by (rule bexE)\n    from b1 obtain y where q1:\\<open>xa\\<in>y\\<close> and q2:\\<open>y\\<in>A\\<close> by (rule UnionE)\n    from b2 and q1 have c1:\\<open>x \\<in> r `` y\\<close>  by (rule imageI)\n    from b2 have e1:\\<open>x \\<in> range(r)\\<close> by (rule rangeI)\n(*    from q2 and c1 show \\<open>x \\<in> (\\<Union>x\\<in>A. r `` x)\\<close> by (rule UN_I)*)\n    from q2 and c1 have q:\\<open>x \\<in> (\\<Union>x\\<in>A. r `` x)\\<close> by (rule UN_I)\n    show \\<open>x \\<in> (\\<Union>x\\<in>A. r `` x)\\<close> by (rule q)\n  qed\n  thus \\<open>r `` (\\<Union>A) \\<subseteq> (\\<Union>x\\<in>A. r `` x)\\<close> by (rule subsetI)\nnext\n  have l2:\\<open>\\<And>x. x \\<in> (\\<Union>x\\<in>A. r `` x) \\<Longrightarrow> x \\<in> r `` (\\<Union>A)\\<close>\n  proof -\n    fix x\n    assume a0:\\<open>x \\<in> (\\<Union>x\\<in>A. r `` x)\\<close> \n    (*! have \\<open>x \\<in> (\\<Union>x\\<in>A. r `` x)\\<close> apply standard sorry !*)\n    from a0 obtain B where \\<open>B \\<in> {r `` x . x \\<in> A}\\<close> and \\<open>x \\<in> B\\<close> by standard\n    (*! have \\<open>B \\<in> {r `` x . x \\<in> A}\\<close> apply standard sorry !*)\n    from \\<open>B \\<in> {r `` x . x \\<in> A}\\<close> obtain g where \\<open>B = r `` g\\<close> and \\<open>g \\<in> A\\<close> by standard\n    from \\<open>B = r `` g\\<close> and \\<open>x \\<in> B\\<close> have \\<open>x \\<in> r `` g\\<close> by (rule subst)\n(*    have  \\<open>x \\<in> r `` g\\<close> apply standard *)\n    from  \\<open>x \\<in> r `` g\\<close> obtain aa where  \"\\<langle>aa, x\\<rangle> \\<in> r\" and \"aa \\<in> g\" by standard\n    from \\<open>g \\<in> A\\<close> and \\<open>aa \\<in> g\\<close> have \\<open>aa \\<in> \\<Union>A\\<close> by (rule UnionI)\n    from \\<open>\\<langle>aa, x\\<rangle> \\<in> r\\<close> and \\<open>aa \\<in> \\<Union>A\\<close> show \\<open>x \\<in> r `` (\\<Union>A)\\<close> by standard\n    (*show \\<open>x \\<in> r `` (\\<Union>A)\\<close> sorry*)\n  qed\n  thus \\<open>(\\<Union>x\\<in>A. r `` x) \\<subseteq> r `` (\\<Union>A)\\<close> by (rule subsetI)\nqed\n\nlemma Transset_trans_Memrel:\n    \"\\<forall>j\\<in>i. Transset(j) ==> trans(Memrel(i))\"\n  by (unfold Transset_def trans_def, blast)\n\n(* comments:\n(*\n    from \\<open>x \\<in> \\<Union>Pow(A)\\<close> obtain B \n      where p1:\\<open>x \\<in> B\\<close> and p2:\\<open>B \\<in> Pow(A)\\<close>\n      by (erule UnionE)\n*)\n    have \\<open>x \\<in> {y \\<in> range(r) . \\<exists>x\\<in>\\<Union>A. \\<langle>x, y\\<rangle> \\<in> r}\\<close>\n      apply (rule CollectI)\n      sorry\n    \n    have \\<open>x \\<in> r `` (\\<Union>A)\\<close>\n      apply (unfold image_def)\n      sorry\n...\n    show \\<open>x \\<in> (\\<Union>x\\<in>A. r `` x)\\<close>\n      apply (rule UN_I)\n       apply (rule q2)\n      apply (rule c1)\n      apply (unfold image_def)\n      apply (rule CollectI)\n      apply (unfold range_def)\n    (*proof - \n      show ?thesis by blast*)\n      sorry\ncomments*)\n\n(*\nlemma\n  fixes f A B\n(*  assumes a:\\<open>\\<forall>y. Ind(y) \\<longrightarrow> x \\<in> y\\<close> *)\n  assumes b:\\<open>Ind(w)\\<close> \n  shows \\<open>succ(x) \\<in> w\\<close>\n*)\n(* recursion theorem *)\n\n(*\ntext\\<open>Cantor's theorem revisited\\<close>\nlemma cantor_surj: \"f \\<notin> surj(A,Pow(A))\"\n  apply (unfold surj_def, safe)\n  apply (cut_tac cantor)\n  apply (best del: subsetI)\n  done\n*)\n\n\naxiomatization\n  myeq :: \\<open>[i\\<Rightarrow>o, i\\<Rightarrow>o] \\<Rightarrow> o\\<close>  (infixl \\<open>=C\\<close> 50)\nwhere\n  myrefl: \\<open>a =C a\\<close> and\n  mysubst: \\<open>a =C b \\<Longrightarrow> P(a) \\<Longrightarrow> P(b)\\<close>\n\n(*\naxiomatization\n  eq :: \\<open>['a, 'a] \\<Rightarrow> o\\<close>  (infixl \\<open>=\\<close> 50)\nwhere\n  refl: \\<open>a = a\\<close> and\n  subst: \\<open>a = b \\<Longrightarrow> P(a) \\<Longrightarrow> P(b)\\<close>\n*)\n(*\nlemma qu:\n  fixes C::\\<open>i\\<Rightarrow>o\\<close>\n  shows \\<open>(=)(C,C)\\<close>\n*)\n(*\"\\<lbrakk>C 0;\\<And>\\<alpha>. \\<alpha>\\<in>C\\<Longrightarrow>\\<alpha>+1\\<in>C \\<rbrakk> \\<Longrightarrow> C=Ord\"*)\n  \n\n\nlemma transfinite_induction111 : \"\\<lbrakk>0\\<in>C;\\<And>\\<alpha>. \\<alpha>\\<in>C\\<Longrightarrow>\\<alpha>+1\\<in>C \\<rbrakk> \\<Longrightarrow> 0\\<in>C\"\n  apply assumption\n  done\n\nlemma transfinite_induction22 : \"0\\<in>C \\<Longrightarrow> 0\\<in>C\"\n  apply assumption\n  done\n\n(* untyped lambda calculus *)\n\n(*definition\n  POS  :: \"[i,[i,i]\\<Rightarrow>o]=>o\"  where\n    \"POS(D,\\<sqsubseteq>) == (\\<forall>x\\<in>D.\\<sqsubseteq>(x,x))\\<and>\"*)\n\ncontext\n  fixes D::i\n  (*fixes \\<sqsubseteq>::[i,i]\\<Rightarrow>o*)\n  fixes otn::i (\"\\<sqsubseteq>\")\n  assumes reflrel:\\<open>\\<forall>x\\<in>D. <x,y>\\<in>\\<sqsubseteq>\\<close>\n  assumes antisymrel:\\<open>\\<forall>x\\<in>D. \\<forall>y\\<in>D. <x,y>\\<in>\\<sqsubseteq> \\<and> <y,x>\\<in>\\<sqsubseteq> \\<longrightarrow> x=y\\<close>\n  assumes transrel:\\<open>\\<forall>x\\<in>D.\\<forall>y\\<in>D.\\<forall>z\\<in>D. <x,y>\\<in>\\<sqsubseteq> \\<and> <y,z>\\<in>\\<sqsubseteq> \\<longrightarrow> <x,z>\\<in>\\<sqsubseteq>\\<close>\n  (*assumes dpos:\\<open>POS(D,\\<sqsubseteq>)\\<close>*)\nbegin\nend\n\ndefinition\n  eqc  :: \"[(i\\<Rightarrow>o),(i\\<Rightarrow>o)]=>o\" where\n    \"eqc(A,B) == \\<forall>x. A(x) \\<longleftrightarrow> B(x)\"\n\n(* Transfinite induction. *)\nlemma transfinite_induction:\n  fixes C::\"i\\<Rightarrow>o\"\n  assumes c0:\\<open>C(0)\\<close>\n  assumes cS:\\<open>\\<forall>x. C(x)\\<longrightarrow>C(succ(x))\\<close>\n  assumes cL:\\<open>\\<forall>x. C(x)\\<longrightarrow>C(succ(x))\\<close>\nassumes a:\\<open>Ind(x)\\<close>\n  shows \\<open>eqc(C,Ord)\\<close>\n\n  oops\n\nend\n", "meta": {"author": "georgydunaev", "repo": "JechExercises", "sha": "3ccce3c880a8b965c34f8ca364f38bd53cfb9fdd", "save_path": "github-repos/isabelle/georgydunaev-JechExercises", "path": "github-repos/isabelle/georgydunaev-JechExercises/JechExercises-3ccce3c880a8b965c34f8ca364f38bd53cfb9fdd/JechExercises.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232489352, "lm_q2_score": 0.8705972700870909, "lm_q1q2_score": 0.7097391797161545}}
{"text": "(*  Title:      HOL/Proofs/Lambda/InductTermi.thy\n    Author:     Tobias Nipkow\n    Copyright   1998 TU Muenchen\n\nInductive characterization of terminating lambda terms.  Goes back to\nRaamsdonk & Severi. On normalization. CWI TR CS-R9545, 1995.  Also\nrediscovered by Matthes and Joachimski.\n*)\n\nsection \\<open>Inductive characterization of terminating lambda terms\\<close>\n\ntheory InductTermi imports ListBeta begin\n\nsubsection \\<open>Terminating lambda terms\\<close>\n\ninductive IT :: \"dB => bool\"\n  where\n    Var [intro]: \"listsp IT rs ==> IT (Var n \\<degree>\\<degree> rs)\"\n  | Lambda [intro]: \"IT r ==> IT (Abs r)\"\n  | Beta [intro]: \"IT ((r[s/0]) \\<degree>\\<degree> ss) ==> IT s ==> IT ((Abs r \\<degree> s) \\<degree>\\<degree> ss)\"\n\n\nsubsection \\<open>Every term in \\<open>IT\\<close> terminates\\<close>\n\nlemma double_induction_lemma [rule_format]:\n  \"termip beta s ==> \\<forall>t. termip beta t -->\n    (\\<forall>r ss. t = r[s/0] \\<degree>\\<degree> ss --> termip beta (Abs r \\<degree> s \\<degree>\\<degree> ss))\"\n  apply (erule accp_induct)\n  apply (rule allI)\n  apply (rule impI)\n  apply (erule thin_rl)\n  apply (erule accp_induct)\n  apply clarify\n  apply (rule accp.accI)\n  apply (safe elim!: apps_betasE)\n    apply (blast intro: subst_preserves_beta apps_preserves_beta)\n   apply (blast intro: apps_preserves_beta2 subst_preserves_beta2 rtranclp_converseI\n     dest: accp_downwards)  (* FIXME: acc_downwards can be replaced by acc(R ^* ) = acc(r) *)\n  apply (blast dest: apps_preserves_betas)\n  done\n\nlemma IT_implies_termi: \"IT t ==> termip beta t\"\n  apply (induct set: IT)\n    apply (drule rev_predicate1D [OF _ listsp_mono [where B=\"termip beta\"]])\n    apply (fast intro!: predicate1I)\n    apply (drule lists_accD)\n    apply (erule accp_induct)\n    apply (rule accp.accI)\n    apply (blast dest: head_Var_reduction)\n   apply (erule accp_induct)\n   apply (rule accp.accI)\n   apply blast\n  apply (blast intro: double_induction_lemma)\n  done\n\n\nsubsection \\<open>Every terminating term is in \\<open>IT\\<close>\\<close>\n\ndeclare Var_apps_neq_Abs_apps [symmetric, simp]\n\nlemma [simp, THEN not_sym, simp]: \"Var n \\<degree>\\<degree> ss \\<noteq> Abs r \\<degree> s \\<degree>\\<degree> ts\"\n  by (simp add: foldl_Cons [symmetric] del: foldl_Cons)\n\n\n\ninductive_cases [elim!]:\n  \"IT (Var n \\<degree>\\<degree> ss)\"\n  \"IT (Abs t)\"\n  \"IT (Abs r \\<degree> s \\<degree>\\<degree> ts)\"\n\ntheorem termi_implies_IT: \"termip beta r ==> IT r\"\n  apply (erule accp_induct)\n  apply (rename_tac r)\n  apply (erule thin_rl)\n  apply (erule rev_mp)\n  apply simp\n  apply (rule_tac t = r in Apps_dB_induct)\n   apply clarify\n   apply (rule IT.intros)\n   apply clarify\n   apply (drule bspec, assumption)\n   apply (erule mp)\n   apply clarify\n   apply (drule_tac r=beta in conversepI)\n   apply (drule_tac r=\"beta\\<inverse>\\<inverse>\" in ex_step1I, assumption)\n   apply clarify\n   apply (rename_tac us)\n   apply (erule_tac x = \"Var n \\<degree>\\<degree> us\" in allE)\n   apply force\n   apply (rename_tac u ts)\n   apply (case_tac ts)\n    apply simp\n    apply blast\n   apply (rename_tac s ss)\n   apply simp\n   apply clarify\n   apply (rule IT.intros)\n    apply (blast intro: apps_preserves_beta)\n   apply (erule mp)\n   apply clarify\n   apply (rename_tac t)\n   apply (erule_tac x = \"Abs u \\<degree> t \\<degree>\\<degree> ss\" in allE)\n   apply force\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/Proofs/Lambda/InductTermi.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8705972616934408, "lm_q2_score": 0.815232489352, "lm_q1q2_score": 0.7097391728733783}}
{"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 camilleri92}.\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": "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/Induct/Comb.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.815232480373843, "lm_q2_score": 0.8705972600147106, "lm_q1q2_score": 0.709739163688464}}
{"text": "section \\<open>Enumerating the SCCs of a Graph \\label{sec:scc}\\<close>\ntheory Gabow_SCC\nimports Gabow_Skeleton\nbegin\n\ntext \\<open>\n  As a first variant, we implement an algorithm that computes a list of SCCs \n  of a graph, in topological order. This is the standard variant described by\n  Gabow~\\cite{Gabow2000}.\n\\<close>\n\nsection \\<open>Specification\\<close>\ncontext fr_graph\nbegin\n  text \\<open>We specify a distinct list that covers all reachable nodes and\n    contains SCCs in topological order\\<close>\n\n  definition \"compute_SCC_spec \\<equiv> SPEC (\\<lambda>l. \n    distinct l \\<and> \\<Union>(set l) = E\\<^sup>*``V0 \\<and> (\\<forall>U\\<in>set l. is_scc E U) \n    \\<and> (\\<forall>i j. i<j \\<and> j<length l \\<longrightarrow> l!j \\<times> l!i \\<inter> E\\<^sup>* = {}) )\"\nend\n\nsection \\<open>Extended Invariant\\<close>\n\nlocale cscc_invar_ext = fr_graph G\n  for G :: \"('v,'more) graph_rec_scheme\" + \n  fixes l :: \"'v set list\" and D :: \"'v set\"\n  assumes l_is_D: \"\\<Union>(set l) = D\" \\<comment> \\<open>The output contains all done CNodes\\<close>\n  assumes l_scc: \"set l \\<subseteq> Collect (is_scc E)\" \\<comment> \\<open>The output contains only SCCs\\<close>\n  assumes l_no_fwd: \"\\<And>i j. \\<lbrakk>i<j; j<length l\\<rbrakk> \\<Longrightarrow> l!j \\<times> l!i \\<inter> E\\<^sup>* = {}\" \n    \\<comment> \\<open>The output contains no forward edges\\<close>\nbegin\n  lemma l_no_empty: \"{}\\<notin>set l\" using l_scc by (auto simp: in_set_conv_decomp)\nend\n  \nlocale cscc_outer_invar_loc = outer_invar_loc G it D + cscc_invar_ext G l D\n  for G :: \"('v,'more) graph_rec_scheme\" and it l D \nbegin\n  lemma locale_this: \"cscc_outer_invar_loc G it l D\" by unfold_locales\n  lemma abs_outer_this: \"outer_invar_loc G it D\" by unfold_locales\nend\n\nlocale cscc_invar_loc = invar_loc G v0 D0 p D pE + cscc_invar_ext G l D\n  for G :: \"('v,'more) graph_rec_scheme\" and v0 D0 and l :: \"'v set list\" \n  and p D pE\nbegin\n  lemma locale_this: \"cscc_invar_loc G v0 D0 l p D pE\" by unfold_locales\n  lemma invar_this: \"invar_loc G v0 D0 p D pE\" by unfold_locales\nend\n\ncontext fr_graph\nbegin\n  definition \"cscc_outer_invar \\<equiv> \\<lambda>it (l,D). cscc_outer_invar_loc G it l D\"\n  definition \"cscc_invar \\<equiv> \\<lambda>v0 D0 (l,p,D,pE). cscc_invar_loc G v0 D0 l p D pE\"\nend\n\nsection \\<open>Definition of the SCC-Algorithm\\<close>\n\ncontext fr_graph\nbegin\n  definition compute_SCC :: \"'v set list nres\" where\n    \"compute_SCC \\<equiv> do {\n      let so = ([],{});\n      (l,D) \\<leftarrow> FOREACHi cscc_outer_invar V0 (\\<lambda>v0 (l,D0). do {\n        if v0\\<notin>D0 then do {\n          let s = (l,initial v0 D0);\n\n          (l,p,D,pE) \\<leftarrow>\n          WHILEIT (cscc_invar v0 D0)\n            (\\<lambda>(l,p,D,pE). p \\<noteq> []) (\\<lambda>(l,p,D,pE). \n          do {\n            \\<comment> \\<open>Select edge from end of path\\<close>\n            (vo,(p,D,pE)) \\<leftarrow> select_edge (p,D,pE);\n\n            ASSERT (p\\<noteq>[]);\n            case vo of \n              Some v \\<Rightarrow> do {\n                if v \\<in> \\<Union>(set p) then do {\n                  \\<comment> \\<open>Collapse\\<close>\n                  RETURN (l,collapse v (p,D,pE))\n                } else if v\\<notin>D then do {\n                  \\<comment> \\<open>Edge to new node. Append to path\\<close>\n                  RETURN (l,push v (p,D,pE))\n                } else RETURN (l,p,D,pE)\n              }\n            | None \\<Rightarrow> do {\n                \\<comment> \\<open>No more outgoing edges from current node on path\\<close>\n                ASSERT (pE \\<inter> last p \\<times> UNIV = {});\n                let V = last p;\n                let (p,D,pE) = pop (p,D,pE);\n                let l = V#l;\n                RETURN (l,p,D,pE)\n              }\n          }) s;\n          ASSERT (p=[] \\<and> pE={});\n          RETURN (l,D)\n        } else\n          RETURN (l,D0)\n      }) so;\n      RETURN l\n    }\"\nend\n\nsection \\<open>Preservation of Invariant Extension\\<close>\ncontext cscc_invar_ext\nbegin\n  lemma l_disjoint: \n    assumes A: \"i<j\" \"j<length l\"\n    shows \"l!i \\<inter> l!j = {}\"\n  proof (rule disjointI)\n    fix u\n    assume \"u\\<in>l!i\" \"u\\<in>l!j\"\n    with l_no_fwd A show False by auto\n  qed\n\n  corollary l_distinct: \"distinct l\"\n    using l_disjoint l_no_empty\n    by (metis distinct_conv_nth inf_idem linorder_cases nth_mem)\nend\n\ncontext fr_graph\nbegin\n  definition \"cscc_invar_part \\<equiv> \\<lambda>(l,p,D,pE). cscc_invar_ext G l D\"\n\n  lemma cscc_invarI[intro?]:\n    assumes \"invar v0 D0 PDPE\"\n    assumes \"invar v0 D0 PDPE \\<Longrightarrow> cscc_invar_part (l,PDPE)\"\n    shows \"cscc_invar v0 D0 (l,PDPE)\"\n    using assms\n    unfolding initial_def cscc_invar_def invar_def\n    apply (simp split: prod.split_asm)\n    apply intro_locales\n    apply (simp add: invar_loc_def)\n    apply (simp add: cscc_invar_part_def cscc_invar_ext_def)\n    done\n\n  thm cscc_invarI[of v_0 D_0 s l]\n\n  lemma cscc_outer_invarI[intro?]:\n    assumes \"outer_invar it D\"\n    assumes \"outer_invar it D \\<Longrightarrow> cscc_invar_ext G l D\"\n    shows \"cscc_outer_invar it (l,D)\"\n    using assms\n    unfolding initial_def cscc_outer_invar_def outer_invar_def\n    apply (simp split: prod.split_asm)\n    apply intro_locales\n    apply (simp add: outer_invar_loc_def)\n    apply (simp add: cscc_invar_ext_def)\n    done\n\n  lemma cscc_invar_initial[simp, intro!]:\n    assumes A: \"v0\\<in>it\" \"v0\\<notin>D0\"\n    assumes INV: \"cscc_outer_invar it (l,D0)\"\n    shows \"cscc_invar_part (l,initial v0 D0)\"\n  proof -\n    from INV interpret cscc_outer_invar_loc G it l D0 \n      unfolding cscc_outer_invar_def by simp\n    \n    show ?thesis\n      unfolding cscc_invar_part_def initial_def\n      apply simp\n      by unfold_locales\n  qed\n\n  lemma cscc_invar_pop:\n    assumes INV: \"cscc_invar v0 D0 (l,p,D,pE)\"\n    assumes \"invar v0 D0 (pop (p,D,pE))\"\n    assumes NE[simp]: \"p\\<noteq>[]\"\n    assumes NO': \"pE \\<inter> (last p \\<times> UNIV) = {}\"\n    shows \"cscc_invar_part (last p # l, pop (p,D,pE))\"\n  proof -\n    from INV interpret cscc_invar_loc G v0 D0 l p D pE \n      unfolding cscc_invar_def by simp\n\n    have AUX_l_scc: \"is_scc E (last p)\"\n      unfolding is_scc_pointwise\n    proof safe\n      {\n        assume \"last p = {}\" thus False \n          using p_no_empty by (cases p rule: rev_cases) auto \n      }\n\n      fix u v\n      assume \"u\\<in>last p\" \"v\\<in>last p\"\n      with p_sc[of \"last p\"] have \"(u,v) \\<in> (lvE \\<inter> last p \\<times> last p)\\<^sup>*\" by auto\n      with lvE_ss_E show \"(u,v)\\<in>(E \\<inter> last p \\<times> last p)\\<^sup>*\"\n        by (metis Int_mono equalityE rtrancl_mono_mp)\n      \n      fix u'\n      assume \"u'\\<notin>last p\" \"(u,u')\\<in>E\\<^sup>*\" \"(u',v)\\<in>E\\<^sup>*\"\n\n      from \\<open>u'\\<notin>last p\\<close> \\<open>u\\<in>last p\\<close> \\<open>(u,u')\\<in>E\\<^sup>*\\<close>\n        and rtrancl_reachable_induct[OF order_refl lastp_un_D_closed[OF NE NO']]\n      have \"u'\\<in>D\" by auto\n      with \\<open>(u',v)\\<in>E\\<^sup>*\\<close> and rtrancl_reachable_induct[OF order_refl D_closed] \n      have \"v\\<in>D\" by auto\n      with \\<open>v\\<in>last p\\<close> p_not_D show False by (cases p rule: rev_cases) auto\n    qed\n\n    {\n      fix i j\n      assume A: \"i<j\" \"j<Suc (length l)\"\n      have \"l ! (j - Suc 0) \\<times> (last p # l) ! i \\<inter> E\\<^sup>* = {}\"\n      proof (rule disjointI, safe)\n        fix u v\n        assume \"(u, v) \\<in> E\\<^sup>*\" \"u \\<in> l ! (j - Suc 0)\" \"v \\<in> (last p # l) ! i\"\n        from \\<open>u \\<in> l ! (j - Suc 0)\\<close> A have \"u\\<in>\\<Union>(set l)\"\n          by (metis Ex_list_of_length Suc_pred UnionI length_greater_0_conv \n            less_nat_zero_code not_less_eq nth_mem) \n        with l_is_D have \"u\\<in>D\" by simp\n        with rtrancl_reachable_induct[OF order_refl D_closed] \\<open>(u,v)\\<in>E\\<^sup>*\\<close> \n        have \"v\\<in>D\" by auto\n\n        show False proof cases\n          assume \"i=0\" hence \"v\\<in>last p\" using \\<open>v \\<in> (last p # l) ! i\\<close> by simp\n          with p_not_D \\<open>v\\<in>D\\<close> show False by (cases p rule: rev_cases) auto\n        next\n          assume \"i\\<noteq>0\" with \\<open>v \\<in> (last p # l) ! i\\<close> have \"v\\<in>l!(i - 1)\" by auto\n          with l_no_fwd[of \"i - 1\" \"j - 1\"] \n            and \\<open>u \\<in> l ! (j - Suc 0)\\<close> \\<open>(u, v) \\<in> E\\<^sup>*\\<close> \\<open>i\\<noteq>0\\<close> A\n          show False by fastforce \n        qed\n      qed\n    } note AUX_l_no_fwd = this\n\n    show ?thesis\n      unfolding cscc_invar_part_def pop_def apply simp\n      apply unfold_locales\n      apply clarsimp_all\n      using l_is_D apply auto []\n\n      using l_scc AUX_l_scc apply auto []\n\n      apply (rule AUX_l_no_fwd, assumption+) []\n      done\n  qed\n\n  thm cscc_invar_pop[of v_0 D_0 l p D pE]\n\n  lemma cscc_invar_unchanged: \n    assumes INV: \"cscc_invar v0 D0 (l,p,D,pE)\"\n    shows \"cscc_invar_part (l,p',D,pE')\"\n    using INV unfolding cscc_invar_def cscc_invar_part_def cscc_invar_loc_def\n    by simp\n\n  corollary cscc_invar_collapse:\n    assumes INV: \"cscc_invar v0 D0 (l,p,D,pE)\"\n    shows \"cscc_invar_part (l,collapse v (p',D,pE'))\"\n    unfolding collapse_def\n    by (simp add: cscc_invar_unchanged[OF INV])\n\n  corollary cscc_invar_push:\n    assumes INV: \"cscc_invar v0 D0 (l,p,D,pE)\"\n    shows \"cscc_invar_part (l,push v (p',D,pE'))\"\n    unfolding push_def\n    by (simp add: cscc_invar_unchanged[OF INV])\n\n\n  lemma cscc_outer_invar_initial: \"cscc_invar_ext G [] {}\"\n    by unfold_locales auto\n\n\n  lemma cscc_invar_outer_newnode:\n    assumes A: \"v0\\<notin>D0\" \"v0\\<in>it\" \n    assumes OINV: \"cscc_outer_invar it (l,D0)\"\n    assumes INV: \"cscc_invar v0 D0 (l',[],D',pE)\"\n    shows \"cscc_invar_ext G l' D'\"\n  proof -\n    from OINV interpret cscc_outer_invar_loc G it l D0 \n      unfolding cscc_outer_invar_def by simp\n    from INV interpret inv: cscc_invar_loc G v0 D0 l' \"[]\" D' pE \n      unfolding cscc_invar_def by simp\n    \n    show ?thesis \n      by unfold_locales\n\n  qed\n\n  lemma cscc_invar_outer_Dnode:\n    assumes \"cscc_outer_invar it (l, D)\"\n    shows \"cscc_invar_ext G l D\"\n    using assms\n    by (simp add: cscc_outer_invar_def cscc_outer_invar_loc_def)\n    \n  lemmas cscc_invar_preserve = invar_preserve\n    cscc_invar_initial\n    cscc_invar_pop cscc_invar_collapse cscc_invar_push cscc_invar_unchanged \n    cscc_outer_invar_initial cscc_invar_outer_newnode cscc_invar_outer_Dnode\n\n  text \\<open>On termination, the invariant implies the specification\\<close>\n  lemma cscc_finI:\n    assumes INV: \"cscc_outer_invar {} (l,D)\"\n    shows fin_l_is_scc: \"\\<lbrakk>U\\<in>set l\\<rbrakk> \\<Longrightarrow> is_scc E U\"\n    and fin_l_distinct: \"distinct l\"\n    and fin_l_is_reachable: \"\\<Union>(set l) = E\\<^sup>* `` V0\"\n    and fin_l_no_fwd: \"\\<lbrakk>i<j; j<length l\\<rbrakk> \\<Longrightarrow> l!j \\<times>l!i \\<inter> E\\<^sup>* = {}\"\n  proof -\n    from INV interpret cscc_outer_invar_loc G \"{}\" l D\n      unfolding cscc_outer_invar_def by simp\n\n    show \"\\<lbrakk>U\\<in>set l\\<rbrakk> \\<Longrightarrow> is_scc E U\" using l_scc by auto\n\n    show \"distinct l\" by (rule l_distinct)\n\n    show \"\\<Union>(set l) = E\\<^sup>* `` V0\"\n      using fin_outer_D_is_reachable[OF outer_invar_this] l_is_D\n      by auto\n\n    show \"\\<lbrakk>i<j; j<length l\\<rbrakk> \\<Longrightarrow> l!j \\<times>l!i \\<inter> E\\<^sup>* = {}\"\n      by (rule l_no_fwd)\n\n  qed\n\nend\n\nsection \\<open>Main Correctness Proof\\<close>\n\ncontext fr_graph \nbegin\n  lemma invar_from_cscc_invarI: \"cscc_invar v0 D0 (L,PDPE) \\<Longrightarrow> invar v0 D0 PDPE\"\n    unfolding cscc_invar_def invar_def\n    apply (simp split: prod.splits)\n    unfolding cscc_invar_loc_def by simp\n\n  lemma outer_invar_from_cscc_invarI: \n    \"cscc_outer_invar it (L,D) \\<Longrightarrow>outer_invar it D\"\n    unfolding cscc_outer_invar_def outer_invar_def\n    apply (simp split: prod.splits)\n    unfolding cscc_outer_invar_loc_def by simp\n\n  text \\<open>With the extended invariant and the auxiliary lemmas, the actual \n    correctness proof is straightforward:\\<close>\n  theorem compute_SCC_correct: \"compute_SCC \\<le> compute_SCC_spec\"\n  proof -\n    note [[goals_limit = 2]]\n    note [simp del] = Union_iff\n\n    show ?thesis\n      unfolding compute_SCC_def compute_SCC_spec_def select_edge_def select_def\n      apply (refine_rcg\n        WHILEIT_rule[where R=\"inv_image (abs_wf_rel v0) snd\" for v0]\n        refine_vcg \n      )\n\n      apply (vc_solve\n        rec: cscc_invarI cscc_outer_invarI\n        solve: cscc_invar_preserve cscc_finI\n        intro: invar_from_cscc_invarI outer_invar_from_cscc_invarI\n        dest!: sym[of \"pop A\" for A]\n        simp: pE_fin'[OF invar_from_cscc_invarI] finite_V0\n      )\n      apply auto\n      done\n  qed\n\n\n  text \\<open>Simple proof, for presentation\\<close>\n  context \n    notes [refine]=refine_vcg\n    notes [[goals_limit = 1]]\n  begin\n    theorem \"compute_SCC \\<le> compute_SCC_spec\"\n      unfolding compute_SCC_def compute_SCC_spec_def select_edge_def select_def\n      by (refine_rcg \n        WHILEIT_rule[where R=\"inv_image (abs_wf_rel v0) snd\" for v0])\n      (vc_solve \n        rec: cscc_invarI cscc_outer_invarI solve: cscc_invar_preserve cscc_finI\n        intro: invar_from_cscc_invarI outer_invar_from_cscc_invarI\n        dest!: sym[of \"pop A\" for A]\n        simp: pE_fin'[OF invar_from_cscc_invarI] finite_V0, auto)\n  end\n\nend\n\n\nsection \\<open>Refinement to Gabow's Data Structure\\<close>\n\ncontext GS begin\n  definition \"seg_set_impl l u \\<equiv> do {\n    (_,res) \\<leftarrow> WHILET\n      (\\<lambda>(l,_). l<u) \n      (\\<lambda>(l,res). do { \n        ASSERT (l<length S); \n        let x = S!l;\n        ASSERT (x\\<notin>res); \n        RETURN (Suc l,insert x res)\n      }) \n      (l,{});\n      \n    RETURN res\n  }\"\n\n  \n\n    apply (auto simp: less_Suc_eq nth_eq_iff_index_eq)\n    done\n\n  lemma (in GS_invar) seg_set_impl_correct:\n    assumes \"i<length B\"\n    shows \"seg_set_impl (seg_start i) (seg_end i) \\<le> SPEC (\\<lambda>r. r=p_\\<alpha>!i)\"\n    apply (refine_rcg order_trans[OF seg_set_impl_aux] refine_vcg)\n\n    using assms \n    apply (simp_all add: seg_start_less_end seg_end_bound S_distinct) [3]\n\n    apply (auto simp: p_\\<alpha>_def assms seg_def) []\n    done\n\n  definition \"last_seg_impl \n    \\<equiv> do {\n      ASSERT (length B - 1 < length B);\n      seg_set_impl (seg_start (length B - 1)) (seg_end (length B - 1))\n    }\"\n\n  lemma (in GS_invar) last_seg_impl_correct:\n    assumes \"p_\\<alpha> \\<noteq> []\"\n    shows \"last_seg_impl \\<le> SPEC (\\<lambda>r. r=last p_\\<alpha>)\"\n    unfolding last_seg_impl_def\n    apply (refine_rcg order_trans[OF seg_set_impl_correct] refine_vcg)\n    using assms apply (auto simp add: p_\\<alpha>_def last_conv_nth)\n    done\n\nend\n\ncontext fr_graph\nbegin\n\n  definition \"last_seg_impl s \\<equiv> GS.last_seg_impl s\"\n  lemmas last_seg_impl_def_opt = \n    last_seg_impl_def[abs_def, THEN opt_GSdef, \n      unfolded GS.last_seg_impl_def GS.seg_set_impl_def \n    GS.seg_start_def GS.seg_end_def GS_sel_simps] \n    (* TODO: Some potential for optimization here: the assertion \n      guarantees that length B - 1 + 1 = length B !*)\n\n  lemma last_seg_impl_refine: \n    assumes A: \"(s,(p,D,pE))\\<in>GS_rel\"\n    assumes NE: \"p\\<noteq>[]\"\n    shows \"last_seg_impl s \\<le> \\<Down>Id (RETURN (last p))\"\n  proof -\n    from A have \n      [simp]: \"p=GS.p_\\<alpha> s \\<and> D=GS.D_\\<alpha> s \\<and> pE=GS.pE_\\<alpha> s\" \n        and INV: \"GS_invar s\"\n      by (auto simp add: GS_rel_def br_def GS_\\<alpha>_split)\n\n    show ?thesis\n      unfolding last_seg_impl_def[abs_def]\n      apply (rule order_trans[OF GS_invar.last_seg_impl_correct])\n      using INV NE\n      apply (simp_all) \n      done\n  qed\n\n  definition compute_SCC_impl :: \"'v set list nres\" where\n    \"compute_SCC_impl \\<equiv> do {\n      stat_start_nres;\n      let so = ([],Map.empty);\n      (l,D) \\<leftarrow> FOREACHi (\\<lambda>it (l,s). cscc_outer_invar it (l,oGS_\\<alpha> s)) \n        V0 (\\<lambda>v0 (l,I0). do {\n          if \\<not>is_done_oimpl v0 I0 then do {\n            let ls = (l,initial_impl v0 I0);\n\n            (l,(S,B,I,P))\\<leftarrow>WHILEIT (\\<lambda>(l,s). cscc_invar v0 (oGS_\\<alpha> I0) (l,GS.\\<alpha> s))\n              (\\<lambda>(l,s). \\<not>path_is_empty_impl s) (\\<lambda>(l,s).\n            do {\n              \\<comment> \\<open>Select edge from end of path\\<close>\n              (vo,s) \\<leftarrow> select_edge_impl s;\n\n              case vo of \n                Some v \\<Rightarrow> do {\n                  if is_on_stack_impl v s then do {\n                    s\\<leftarrow>collapse_impl v s;\n                    RETURN (l,s)\n                  } else if \\<not>is_done_impl v s then do {\n                    \\<comment> \\<open>Edge to new node. Append to path\\<close>\n                    RETURN (l,push_impl v s)\n                  } else do {\n                    \\<comment> \\<open>Edge to done node. Skip\\<close>\n                    RETURN (l,s)\n                  }\n                }\n              | None \\<Rightarrow> do {\n                  \\<comment> \\<open>No more outgoing edges from current node on path\\<close>\n                  scc \\<leftarrow> last_seg_impl s;\n                  s\\<leftarrow>pop_impl s;\n                  let l = scc#l;\n                  RETURN (l,s)\n                }\n            }) (ls);\n            RETURN (l,I)\n          } else RETURN (l,I0)\n      }) so;\n      stat_stop_nres;\n      RETURN l\n    }\"\n\n  lemma compute_SCC_impl_refine: \"compute_SCC_impl \\<le> \\<Down>Id compute_SCC\"\n  proof -\n    note [refine2] = bind_Let_refine2[OF last_seg_impl_refine]\n\n    have [refine2]: \"\\<And>s' p D pE l' l v' v. \\<lbrakk>\n      (s',(p,D,pE))\\<in>GS_rel;\n      (l',l)\\<in>Id;\n      (v',v)\\<in>Id;\n      v\\<in>\\<Union>(set p)\n    \\<rbrakk> \\<Longrightarrow> do { s'\\<leftarrow>collapse_impl v' s'; RETURN (l',s') } \n      \\<le> \\<Down>(Id \\<times>\\<^sub>r GS_rel) (RETURN (l,collapse v (p,D,pE)))\"\n      apply (refine_rcg order_trans[OF collapse_refine] refine_vcg)\n      apply assumption+\n      apply (auto simp add: pw_le_iff refine_pw_simps)\n      done\n\n    note [[goals_limit = 1]]\n    show ?thesis\n      unfolding compute_SCC_impl_def compute_SCC_def\n      apply (refine_rcg\n        bind_refine'\n        select_edge_refine push_refine \n        pop_refine\n        (*collapse_refine*) \n        initial_refine\n        oinitial_refine\n        (*last_seg_impl_refine*)\n        prod_relI IdI\n        inj_on_id\n      )\n\n      apply refine_dref_type\n      apply (vc_solve (nopre) solve: asm_rl I_to_outer\n        simp: GS_rel_def br_def GS.\\<alpha>_def oGS_rel_def oGS_\\<alpha>_def \n        is_on_stack_refine path_is_empty_refine is_done_refine is_done_orefine\n      )\n\n      done\n  qed\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/Gabow_SCC/Gabow_SCC.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8539127529517043, "lm_q2_score": 0.831143045767024, "lm_q1q2_score": 0.7097236463075839}}
{"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 {* First-Order Logic: propositional examples (classical version) *}\n\ntheory Propositional_Cla\nimports FOL\nbegin\n\ntext {* commutative laws of @{text \"&\"} and @{text \"|\"} *}\n\nlemma \"P & Q  -->  Q & P\"\n  by (tactic \"IntPr.fast_tac @{context} 1\")\n\nlemma \"P | Q  -->  Q | P\"\n  by fast\n\n\ntext {* associative laws of @{text \"&\"} and @{text \"|\"} *}\nlemma \"(P & Q) & R  -->  P & (Q & R)\"\n  by fast\n\nlemma \"(P | Q) | R  -->  P | (Q | R)\"\n  by fast\n\n\ntext {* distributive laws of @{text \"&\"} and @{text \"|\"} *}\nlemma \"(P & Q) | R  --> (P | R) & (Q | R)\"\n  by fast\n\nlemma \"(P | R) & (Q | R)  --> (P & Q) | R\"\n  by fast\n\nlemma \"(P | Q) & R  --> (P & R) | (Q & R)\"\n  by fast\n\nlemma \"(P & R) | (Q & R)  --> (P | Q) & R\"\n  by fast\n\n\ntext {* Laws involving implication *}\n\nlemma \"(P-->R) & (Q-->R) <-> (P|Q --> R)\"\n  by fast\n\nlemma \"(P & Q --> R) <-> (P--> (Q-->R))\"\n  by fast\n\nlemma \"((P-->R)-->R) --> ((Q-->R)-->R) --> (P&Q-->R) --> R\"\n  by fast\n\nlemma \"~(P-->R) --> ~(Q-->R) --> ~(P&Q-->R)\"\n  by fast\n\nlemma \"(P --> Q & R) <-> (P-->Q)  &  (P-->R)\"\n  by fast\n\n\ntext {* Propositions-as-types *}\n\n-- {* The combinator K *}\nlemma \"P --> (Q --> P)\"\n  by fast\n\n-- {* The combinator S *}\nlemma \"(P-->Q-->R)  --> (P-->Q) --> (P-->R)\"\n  by fast\n\n\n-- {* Converse is classical *}\nlemma \"(P-->Q) | (P-->R)  -->  (P --> Q | R)\"\n  by fast\n\nlemma \"(P-->Q)  -->  (~Q --> ~P)\"\n  by fast\n\n\ntext {* Schwichtenberg's examples (via T. Nipkow) *}\n\nlemma stab_imp: \"(((Q-->R)-->R)-->Q) --> (((P-->Q)-->R)-->R)-->P-->Q\"\n  by fast\n\nlemma stab_to_peirce:\n  \"(((P --> R) --> R) --> P) --> (((Q --> R) --> R) --> Q)  \n                              --> ((P --> Q) --> P) --> P\"\n  by fast\n\nlemma peirce_imp1: \"(((Q --> R) --> Q) --> Q)  \n                --> (((P --> Q) --> R) --> P --> Q) --> P --> Q\"\n  by fast\n  \nlemma peirce_imp2: \"(((P --> R) --> P) --> P) --> ((P --> Q --> R) --> P) --> P\"\n  by fast\n\nlemma mints: \"((((P --> Q) --> P) --> P) --> Q) --> Q\"\n  by fast\n\nlemma mints_solovev: \"(P --> (Q --> R) --> Q) --> ((P --> Q) --> R) --> R\"\n  by fast\n\nlemma tatsuta: \"(((P7 --> P1) --> P10) --> P4 --> P5)  \n  --> (((P8 --> P2) --> P9) --> P3 --> P10)  \n  --> (P1 --> P8) --> P6 --> P7  \n  --> (((P3 --> P2) --> P9) --> P4)  \n  --> (P1 --> P3) --> (((P6 --> P1) --> P2) --> P9) --> P5\"\n  by fast\n\nlemma tatsuta1: \"(((P8 --> P2) --> P9) --> P3 --> P10)  \n  --> (((P3 --> P2) --> P9) --> P4)  \n  --> (((P6 --> P1) --> P2) --> P9)  \n  --> (((P7 --> P1) --> P10) --> P4 --> P5)  \n  --> (P1 --> P3) --> (P1 --> P8) --> P6 --> P7 --> P5\"\n  by fast\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/Propositional_Cla.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789468908171, "lm_q2_score": 0.7931059438487663, "lm_q1q2_score": 0.7096628462843513}}
{"text": "theory Teoreme_Kompleksnih\n  imports Complex_Main\nbegin\n\ndefinition \"ccsqrt z = rcis (sqrt (cmod z)) (arg z / 2)\"\n\n(*ideja se oslanja na osobinu da su dva kompleksna broja jednaka ako su \nim jednaki realni deo i imaginarni deo*)\nlemma square_ccsqrt [simp]:\n  shows \"(ccsqrt x)\\<^sup>2 = x\"\nproof\n  show \"Re ((ccsqrt x)\\<^sup>2) = Re x\"\n  proof-\n    have \"Re ((ccsqrt x)\\<^sup>2) = Re (ccsqrt x * ccsqrt x)\"\n      by (simp add: power2_eq_square)\n    also have \"... = Re ((rcis (sqrt (cmod x)) (arg x / 2)) * (rcis (sqrt (cmod x)) (arg x / 2)))\"\n      using ccsqrt_def by presburger\n    also have \"... = Re (rcis (sqrt (cmod x) * sqrt (cmod x)) (arg x / 2 + arg x / 2))\"\n      using rcis_mult by presburger\n    also have \"... = Re (rcis (cmod x) (arg x))\"\n      by (metis abs_norm_cancel field_sum_of_halves real_sqrt_mult_self)\n    also have \"... = Re x\"\n      using rcis_cmod_arg by presburger\n    finally show ?thesis .\n  qed\nnext\n  show \"Im ((ccsqrt x)\\<^sup>2) = Im x\"\n  proof-\n    have \"Im ((ccsqrt x)\\<^sup>2) = Im (ccsqrt x * ccsqrt x)\"\n      by (simp add: power2_eq_square)\n    also have \"... = Im ((rcis (sqrt (cmod x)) (arg x / 2)) * (rcis (sqrt (cmod x)) (arg x / 2)))\"\n      using ccsqrt_def by presburger\n    also have \"... = Im (rcis (sqrt (cmod x) * sqrt (cmod x)) (arg x / 2 + arg x / 2))\"\n      using rcis_mult by presburger\n    also have \"... = Im (rcis (cmod x) (arg x))\"\n      by (metis abs_norm_cancel field_sum_of_halves real_sqrt_mult_self)\n    also have \"... = Im x\"\n      using rcis_cmod_arg by presburger\n    finally show ?thesis .\n  qed\nqed\n(*ista ideja se primenjuje i ovde*)\nlemma ex_complex_sqrt [simp]:\n  shows \"\\<exists> s::complex. s*s = z\"\n  apply (rule_tac x = \"ccsqrt z\" in exI)\nproof \n  show \"Re (ccsqrt z * ccsqrt z) = Re z\"\n  proof-\n    have \"Re (ccsqrt z * ccsqrt z) = Re ((rcis (sqrt (cmod z)) (arg z / 2)) * (rcis (sqrt (cmod z)) (arg z / 2)))\"\n      using ccsqrt_def by presburger\n    also have \"... = Re (rcis (sqrt (cmod z) * sqrt (cmod z)) (arg z /2 + arg z / 2))\"\n      using rcis_mult by presburger\n    also have \"... = Re (rcis (cmod z) (arg z))\"\n    by (metis ccsqrt_def power2_eq_square rcis_cmod_arg rcis_mult square_ccsqrt)\n  also have \"... = Re z\"\n    using rcis_cmod_arg by presburger\n  finally show ?thesis .\n  qed\nnext\n  show \"Im (ccsqrt z * ccsqrt z) = Im z\"\n  proof-\n    have \"Im (ccsqrt z * ccsqrt z) = Im ((rcis (sqrt (cmod z)) (arg z / 2)) * (rcis (sqrt (cmod z)) (arg z / 2)))\"\n      using ccsqrt_def by presburger\n    also have \"... = Im (rcis (sqrt (cmod z) * sqrt (cmod z)) (arg z /2 + arg z / 2))\"\n      using rcis_mult by presburger\n    also have \"... = Im (rcis (cmod z) (arg z))\"\n    by (metis ccsqrt_def power2_eq_square rcis_cmod_arg rcis_mult square_ccsqrt)\n  also have \"... = Im z\"\n    using rcis_cmod_arg by presburger\n  finally show ?thesis .\n  qed\nqed\n\n\nlemma ccsqrt [simp]:\n  assumes \"s*s = z\"\n  shows \"s = ccsqrt z \\<or> s = -ccsqrt z\"\nproof-\n  have \"s\\<^sup>2 = s*s\"\n    by (simp add: power2_eq_square)\n  then have \"... = z\"\n    using assms\n    by simp\n  then have \"... = ccsqrt z * ccsqrt z\"\n    by (metis power2_eq_square square_ccsqrt)\n  then have \"... = (ccsqrt z)\\<^sup>2\"\n    by auto\n  then have \"s\\<^sup>2 = (ccsqrt z)\\<^sup>2\"\n    using \\<open>s\\<^sup>2 = s * s\\<close> assms by auto\n  then have \"s = ccsqrt z \\<or> s = -ccsqrt z\"\n    using power2_eq_iff by blast\n  then show ?thesis.\nqed\n\n\nlemma ccsqrt_mult [simp]:\n  shows  \"ccsqrt (a*b) = ccsqrt a * ccsqrt b \\<or> ccsqrt (a*b) = - ccsqrt a * ccsqrt b\"\nproof - \n  have \"(ccsqrt (a*b))^2 = a*b\"\n  by simp\n  then have \"a * b = (ccsqrt a * ccsqrt a) * (ccsqrt b * ccsqrt b)\"\n    by (metis power2_eq_square square_ccsqrt)\n  then have \"... = (ccsqrt a * ccsqrt b)*(ccsqrt a * ccsqrt b)\"\n    by simp\n  then have \"... = (ccsqrt a * ccsqrt b)^2\"\n    by (simp add: semiring_normalization_rules(29))\n  then have \"(ccsqrt (a*b))\\<^sup>2 = (ccsqrt a * ccsqrt b)\\<^sup>2\"\n  by (simp add: \\<open>a * b = ccsqrt a * ccsqrt a * (ccsqrt b * ccsqrt b)\\<close> \\<open>ccsqrt a * ccsqrt a * (ccsqrt b * ccsqrt b) = ccsqrt a * ccsqrt b * (ccsqrt a * ccsqrt b)\\<close>)\n  then have \"ccsqrt (a*b) = ccsqrt a * ccsqrt b \\<or> ccsqrt (a*b) = - ccsqrt a * ccsqrt b\"\n    using power2_eq_iff by fastforce\n  then show ?thesis.\nqed\n\n(*neke pomocne leme za resavanje izraza*)\nlemma pomocna [simp]:\n  fixes a b :: complex\n  shows \"(a/b)\\<^sup>2 = a\\<^sup>2 / b\\<^sup>2\"\n  by (simp add: power_divide)\n\nlemma pomocna1 [simp]:\n  fixes a b ::complex\n  shows \"(a - b)\\<^sup>2 = a\\<^sup>2 - 2*a*b + b\\<^sup>2\"\n  by (simp add: power2_diff)\n\nlemma pomocna2 [simp]:\n  fixes a b::complex\n  shows \"(a*b\\<^sup>2)/(4*a\\<^sup>2) = b\\<^sup>2 / (4*a) \"\n  by (simp add: power2_eq_square)\n\nlemma pomocna3 [simp]:\n  fixes a b c::complex\n  shows \"(a*2*b*c) / (4*a\\<^sup>2) = (b*c) / (2*a)\"\nproof-\n  have \"(a*2*b*c) / (4*a\\<^sup>2) = (2*a*b*c) / (4*a\\<^sup>2)\"\n    by auto\n  also have \"... = (2*a)*(b*c) / (2*a)\\<^sup>2\"\n    by auto\n  finally show ?thesis\n    by (simp add: power2_eq_square)\nqed\n\nlemma pomocna4 [simp]:\n  fixes a b::complex\n  assumes \"a\\<noteq>0\"\n  shows \" - (4*a*b) / (4*a) = -b\"\n  using assms by auto\n\nlemma pomocna5 [simp]:\n  fixes a b:: complex\n  shows \"(-a+b)\\<^sup>2 = a\\<^sup>2 - 2*a*b + b\\<^sup>2\"\n  by auto\n\nlemma pomocna6 [simp]:\n  fixes a b::complex\n  shows \"(-a-b)\\<^sup>2 = a\\<^sup>2 + 2*a*b + b\\<^sup>2\"\n  by simp\n\n(*dodala sam pretpostavku da je a razlicito od nule kako bi moglo da se deli sa a*)\nlemma quadratic_equation:\n  fixes a b c x :: complex\n  assumes \"a \\<noteq> 0\"\n  shows \"a*x\\<^sup>2+b*x+c=0 \\<longleftrightarrow> x = (-b + ccsqrt (b\\<^sup>2-4*a*c)) / (2*a) \\<or> x = (-b - ccsqrt (b\\<^sup>2 - 4*a*c)) / (2*a)\"\nproof\n  assume \"x = (- b + ccsqrt (b\\<^sup>2 - 4 * a * c)) / (2 * a) \\<or> x = (- b - ccsqrt (b\\<^sup>2 - 4 * a * c)) / (2 * a)\"\n  show \"a*x\\<^sup>2 + b*x+c=0\"\n  proof-\n    have \"a*x\\<^sup>2 + b*x+c=a* ((- b + ccsqrt (b\\<^sup>2 - 4 * a * c)) / (2 * a))\\<^sup>2 + b * ((- b + ccsqrt (b\\<^sup>2 - 4 * a * c)) / (2 * a)) + c   \\<or> a*x\\<^sup>2 + b*x+c= a* ((- b - ccsqrt (b\\<^sup>2 - 4 * a * c)) / (2 * a))\\<^sup>2 + b * ((- b - ccsqrt (b\\<^sup>2 - 4 * a * c)) / (2 * a)) + c \"\n      using \\<open>x = (- b + ccsqrt (b\\<^sup>2 - 4 * a * c)) / (2 * a) \\<or> x = (- b - ccsqrt (b\\<^sup>2 - 4 * a * c)) / (2 * a)\\<close> by blast\n    then have \"a*x\\<^sup>2 + b*x+c = a * ((- b + ccsqrt (b\\<^sup>2 - 4 * a * c))\\<^sup>2 / (2*a)\\<^sup>2) +  b * ((- b + ccsqrt (b\\<^sup>2 - 4 * a * c)) / (2 * a)) + c \\<or> a*x\\<^sup>2 + b*x+c = a* ((- b - ccsqrt (b\\<^sup>2 - 4 * a * c))\\<^sup>2 / (2 * a)\\<^sup>2) + b * ((- b - ccsqrt (b\\<^sup>2 - 4 * a * c)) / (2 * a)) + c \"\n      by simp\n    then have \"a*x\\<^sup>2 + b*x+c = a * ((- b + ccsqrt (b\\<^sup>2 - 4 * a * c))\\<^sup>2 / (2*a)\\<^sup>2) +  (b*(- b + ccsqrt (b\\<^sup>2 - 4 * a * c))) / (2 * a) + c \\<or> a*x\\<^sup>2 + b*x+c=a * ((- b - ccsqrt (b\\<^sup>2 - 4 * a * c))\\<^sup>2 / (2*a)\\<^sup>2) +  (b*(- b - ccsqrt (b\\<^sup>2 - 4 * a * c))) / (2 * a) + c \"\n      by simp\n    then have \"a*x\\<^sup>2 + b*x+c = a * ((b\\<^sup>2-2*b*(ccsqrt (b\\<^sup>2 - 4 * a * c)) + (ccsqrt (b\\<^sup>2 - 4 * a * c))\\<^sup>2) / (4*a\\<^sup>2)) +  (b*(- b + ccsqrt (b\\<^sup>2 - 4 * a * c))) / (2 * a) + c \\<or> a*x\\<^sup>2 + b*x+c=a * ((b\\<^sup>2 + 2*b*(ccsqrt (b\\<^sup>2 - 4 * a * c)) + (ccsqrt (b\\<^sup>2 - 4 * a * c))\\<^sup>2)/(4*a\\<^sup>2)) +  (b*(- b - ccsqrt (b\\<^sup>2 - 4 * a * c))) / (2 * a) + c \"\n      by auto\n    then have \"a*x\\<^sup>2 + b*x+c = a * ((b\\<^sup>2-2*b*(ccsqrt (b\\<^sup>2 - 4 * a * c)) + (b\\<^sup>2 - 4 * a * c)) / (4*a\\<^sup>2)) +  (-b\\<^sup>2 + b*ccsqrt (b\\<^sup>2 - 4 * a * c)) / (2 * a) + c \\<or> a*x\\<^sup>2 + b*x+c=a * ((b\\<^sup>2 + 2*b*(ccsqrt (b\\<^sup>2 - 4 * a * c)) + (b\\<^sup>2 - 4 * a * c))/(4*a\\<^sup>2)) +  (- b\\<^sup>2 - b*ccsqrt (b\\<^sup>2 - 4 * a * c)) / (2 * a) + c \"\n      by (smt diff_0 mult_zero_right power2_eq_square right_diff_distrib square_ccsqrt uminus_add_conv_diff)\n    then have \"a*x\\<^sup>2 + b*x+c = ((b\\<^sup>2-2*b*(ccsqrt (b\\<^sup>2 - 4 * a * c)) + (b\\<^sup>2 - 4 * a * c)) / (4*a)) -b\\<^sup>2/(2*a) + b*ccsqrt (b\\<^sup>2 - 4 * a * c) / (2 * a) + c \\<or> a*x\\<^sup>2 + b*x+c=((b\\<^sup>2 + 2*b*(ccsqrt (b\\<^sup>2 - 4 * a * c)) + (b\\<^sup>2 - 4 * a * c))/(4*a)) - b\\<^sup>2/(2*a) - b*ccsqrt (b\\<^sup>2 - 4 * a * c) / (2 * a) + c\"\n    by (smt ab_group_add_class.ab_diff_conv_add_uminus add.assoc add_divide_distrib minus_divide_left pomocna2 pomocna5 pomocna6 square_ccsqrt times_divide_eq_right)\n  then have \"a*x\\<^sup>2 + b*x+c = b\\<^sup>2 / (4*a)-2*b*(ccsqrt (b\\<^sup>2 - 4 * a * c))/(4*a) + b\\<^sup>2/(4*a) - (4 * a * c) / (4*a) -b\\<^sup>2/(2*a) + b*ccsqrt (b\\<^sup>2 - 4 * a * c) / (2 * a) + c \\<or> a*x\\<^sup>2 + b*x+c=b\\<^sup>2/(4*a) + 2*b*(ccsqrt (b\\<^sup>2 - 4 * a * c))/(4*a) + b\\<^sup>2/(4*a) - (4 * a * c)/(4*a) - b\\<^sup>2/(2*a) - b*ccsqrt (b\\<^sup>2 - 4 * a * c) / (2 * a) + c\"\n    by (simp add: add_divide_distrib diff_divide_distrib)\n  then have  \"a*x\\<^sup>2 + b*x+c = b\\<^sup>2 / (4*a)-b*(ccsqrt (b\\<^sup>2 - 4 * a * c))/(2*a) + b\\<^sup>2/(4*a) - c -b\\<^sup>2/(2*a) + b*ccsqrt (b\\<^sup>2 - 4 * a * c) / (2 * a) + c \\<or> a*x\\<^sup>2 + b*x+c=b\\<^sup>2/(4*a) + b*(ccsqrt (b\\<^sup>2 - 4 * a * c))/(2*a) + b\\<^sup>2/(4*a) - c - b\\<^sup>2/(2*a) - b*ccsqrt (b\\<^sup>2 - 4 * a * c) / (2 * a) + c\"\n    using assms by auto\n  then have \"a*x\\<^sup>2 + b*x+c = b\\<^sup>2 / (4*a) + b\\<^sup>2/(4*a)  -b\\<^sup>2/(2*a)  \\<or> a*x\\<^sup>2 + b*x+c=b\\<^sup>2/(4*a)  + b\\<^sup>2/(4*a) - b\\<^sup>2/(2*a)\"\n    by simp\n  then have \"a*x\\<^sup>2 + b*x+c = 2*b\\<^sup>2 / (4*a)   -b\\<^sup>2/(2*a)  \\<or> a*x\\<^sup>2 + b*x+c=2*b\\<^sup>2/(4*a) - b\\<^sup>2/(2*a)\"\n    by auto\n  then have \"a*x\\<^sup>2 + b*x+c = b\\<^sup>2 / (2*a)   -b\\<^sup>2/(2*a)  \\<or> a*x\\<^sup>2 + b*x+c=b\\<^sup>2/(2*a) - b\\<^sup>2/(2*a)\"\n    by auto\n  then have \"a*x\\<^sup>2 + b*x+c = 0  \\<or> a*x\\<^sup>2 + b*x+c=0\"\n    by simp\n  then show ?thesis \n    by blast\nqed\nnext \n  assume \"a * x\\<^sup>2 + b * x + c = 0 \"\n  show \"x = (- b + ccsqrt (b\\<^sup>2 - 4 * a * c)) / (2*a) \\<or> x = (- b - ccsqrt (b\\<^sup>2 - 4 * a * c)) / (2*a)\"\n  proof-\n    have \"a*x\\<^sup>2+b*x+c = 0 \\<longleftrightarrow> 4*a*(a*x\\<^sup>2+b*x+c) = 0\"\n      by (simp add: \\<open>a * x\\<^sup>2 + b * x + c = 0\\<close>)\n    also have \"4*a*(a*x\\<^sup>2+b*x+c) = 4*a\\<^sup>2*x\\<^sup>2 +4*a*b*x + 4*a*c + b\\<^sup>2 -b\\<^sup>2\"\n      by (simp add: distrib_left power2_eq_square)\n    also have \"... = (2*a*x+b)\\<^sup>2 -b\\<^sup>2+4*a*c\"\n    by (smt add_diff_cancel_right' mult_2_right numeral_Bit0 power2_eq_square power2_sum semiring_normalization_rules(16) semiring_normalization_rules(18) semiring_normalization_rules(23))\n  also have \"(2*a*x+b)\\<^sup>2 - b\\<^sup>2 + 4*a*c=0\"\n    using \\<open>a * x\\<^sup>2 + b * x + c = 0\\<close> calculation by blast\n  also have \"(2*a*x+b)\\<^sup>2 = b\\<^sup>2 - 4*a*c\"\n    by (metis \\<open>(2 * a * x + b)\\<^sup>2 - b\\<^sup>2 + 4 * a * c = 0\\<close> add_diff_cancel diff_0 diff_add_cancel uminus_add_conv_diff)\n  then have \"2*a*x+b = ccsqrt (b\\<^sup>2 - 4*a*c) \\<or> 2*a*x + b = -ccsqrt (b\\<^sup>2 - 4*a*c)\"\n    by (metis \\<open>(2 * a * x + b)\\<^sup>2 = b\\<^sup>2 - 4 * a * c\\<close> ccsqrt power2_eq_square)\n  then have \"2*a*x = -b + ccsqrt (b\\<^sup>2 - 4*a*c) \\<or> 2*a*x = -b-ccsqrt (b\\<^sup>2 - 4*a*c)\"\n    by (smt \\<open>2 * a * x + b = ccsqrt (b\\<^sup>2 - 4 * a * c) \\<or> 2 * a * x + b = - ccsqrt (b\\<^sup>2 - 4 * a * c)\\<close> diff_minus_eq_add eq_diff_eq uminus_add_conv_diff)\n  then have \"x = (-b+ccsqrt (b\\<^sup>2 - 4*a*c)) / (2*a) \\<or> x = (-b - ccsqrt (b\\<^sup>2 - 4*a*c))/ (2*a)\"\n    by (metis assms divisors_zero nonzero_mult_div_cancel_left zero_neq_numeral)\n  thus ?thesis .\n  qed\nqed\nend", "meta": {"author": "Dara123M", "repo": "UIDT", "sha": "aafd223844e389613b0d471e1d7c3a3768cf898e", "save_path": "github-repos/isabelle/Dara123M-UIDT", "path": "github-repos/isabelle/Dara123M-UIDT/UIDT-aafd223844e389613b0d471e1d7c3a3768cf898e/Teoreme_Kompleksnih.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952948443462, "lm_q2_score": 0.7905303211371898, "lm_q1q2_score": 0.7096553497166452}}
{"text": "theory a2\nimports Main\nbegin\n\nsection \"Part 1\"\n\ndatatype condition =\n  Above nat nat | Joinable nat nat\n\ninductive_set connection :: \"condition set \\<Rightarrow> condition set\"\n  for A :: \"condition set\" where\n  con_refl:\n    \"Above a a \\<in> connection A\"\n| con_in:\n    \"\\<phi> \\<in> A \\<Longrightarrow> \\<phi> \\<in> connection A\"\n| con_mirror:\n    \"Joinable a b \\<in> connection A\n     \\<Longrightarrow> Joinable b a \\<in> connection A\"\n| con_trans:\n    \"\\<lbrakk>Above a b \\<in> connection A;\n      Above b c \\<in> connection A\\<rbrakk>\n     \\<Longrightarrow> Above a c \\<in> connection A\"\n| con_join:\n    \"\\<lbrakk>Above a b \\<in> connection A;\n      Above c b \\<in> connection A\\<rbrakk>\n     \\<Longrightarrow> Joinable a c \\<in> connection A\"\n| con_ext_join:\n    \"\\<lbrakk>Above a b \\<in> connection A;\n      Joinable b c \\<in> connection A\\<rbrakk>\n     \\<Longrightarrow> Joinable a c \\<in> connection A\"\n\nprint_theorems\n\nprimrec is_refl :: \"_\" where\n  \"is_refl(Above a b) = (a = b)\"\n| \"is_refl(Joinable a b) = (a = b)\"\n\nsection \"Question 1 (a)\"\n\n\n(*4 is router1 5 is router2*)\ndefinition example_network where\n\"example_network = {\nAbove 1 4 , Above 2 4, Above 2 5 , Above 3 5\n}\"  (* TODO *)\n\nlemma \"Joinable 1 2 \\<in> connection example_network\"\n  apply (unfold example_network_def)\n  apply (rule_tac b=4 in con_join)\n   apply (rule con_in)\n   apply (blast)\n  apply (simp add:con_in)\n  done \n\nsubsection \"Questions 1 (b)-(j)\"\n\n(* 1-b *)\nlemma connection_monotonic:\n  assumes \"\\<phi> \\<in> connection A\"\n  shows   \"\\<phi> \\<in> connection(A \\<union> B)\"\n  using assms\n  apply (induct rule:connection.induct)\n       apply (auto intro:connection.intros)\n  done\n\nlemma connection_mono : \n  \"connection (connection A) \\<subseteq> connection A\"\n  apply (safe)\n  apply (erule connection.induct)\n  apply (simp_all add: connection.intros)\n  done\n\n(* 1-c *)\nlemma connection_idem:\n  shows \"connection(connection A) = connection A\"\n  apply (rule equalityI)\n  apply (simp add:  connection_mono)\n  apply (auto intro:connection.intros)\n  done\n\n(* 1-d *)\nlemma connection_decompose:\n  assumes \"\\<phi> \\<in> connection(A \\<union> B)\"\n  shows   \"\\<exists>C D. C \\<subseteq> connection A \\<and>\n                 D \\<subseteq> connection B \\<and>\n                 \\<phi> \\<in> connection(C \\<union> D)\"\n  using assms\n  apply -\n  apply (simp add: connection.induct)\n  apply (auto intro:connection.intros)\n  done\n\n(* 1-e *)\nlemma connection_nil:\n  assumes \"\\<phi> \\<in> connection {}\"\n  shows \"is_refl \\<phi>\"\n  (* TODO *)\n  using assms\n  apply (induct \\<phi>)\n   apply (simp_all)\n  done\n\n(* 1-f *)\nlemma con_is_refl:\n  assumes \"is_refl \\<phi>\"\n  shows \"\\<phi> \\<in> connection A\"\n  (* TODO *)\n  using assms \n  apply - \n  apply (induct)\n   apply (simp_all add: connection.inducts)\n  apply (auto intro:connection.intros)\n  done \n  \n\n(* 1-g *)\nlemma refl_wont_loss: \"is_refl x \\<Longrightarrow> x \\<in> connection A\"\n  apply induct \n  apply (auto intro: connection_nil con_is_refl)\n  done\n\nlemma connection_filter_refl:\n  assumes \"\\<phi> \\<in> connection A\"\n  shows \"\\<phi> \\<in> connection(A - {\\<phi>. is_refl \\<phi>})\"\n  using assms \n  using refl_wont_loss\n  apply induct\n  apply (simp_all add:connection.intros)\n  by (metis DiffI connection.con_in mem_Collect_eq)\n  \n\n(* 1-h *)\nlemma not_refl_wont_derive_nil:\n  \"\\<And>a b . a \\<noteq> b \\<Longrightarrow> Above a b \\<notin> connection {} \"\n  apply safe\n  using connection.inducts\n  using connection_nil \n  using is_refl.simps(1) by blast\n\n\nlemma not_refl_wont_derive_no_reason:\n  \"\\<lbrakk>a \\<noteq> b; Above a b \\<notin> A; Above a c \\<in> A \\<and> Above c b \\<in> A \\<rbrakk> \\<Longrightarrow> Above a b \\<in> connection A\"\n  using connection.con_in connection.con_trans \n  by blast\n\nlemma no_above_from_join_lemma_gen:\n  \"\\<forall> x \\<in> A. x = Above c c \\<Longrightarrow> Above a b \\<in> connection A \\<Longrightarrow> a = b\"\n  using connection_idem connection_monotonic not_refl_wont_derive_nil refl_wont_loss \n  using le_iff_sup subsetI\n  by (metis is_refl.simps(1))\n\nlemma refl_derive_no_reson_2:\n  \"\\<And>a b. Above a b \\<notin> A \\<Longrightarrow> Above a a \\<in> connection A \\<and> Above b b \\<in> connection A\"\n  using connection.intros\n  by blast\n\nlemma \n  \"\\<And>a b c. \\<lbrakk>a \\<noteq> b; a \\<noteq> c; Above a c \\<notin> connection A ; Above c b \\<notin> connection A\\<rbrakk> \\<Longrightarrow> Above a b \\<notin> connection A\"\n  apply (case_tac \"c = b\")\n   apply simp \n  oops \n\nlemma must_be_above_or_joinable:\n  \" x \\<in> A \\<Longrightarrow>\\<exists> a b. x = Joinable a b \\<or> x = Above a b\"\n  using condition.exhaust by blast\n\nlemma no_joinable_from_join_lemma_gen:\n  \"\\<forall> x \\<in> A. x = Joinable c d \\<Longrightarrow> Above a b \\<in> connection A \\<Longrightarrow> a = b\"\n  using connection.intros \n  using connection.inducts \n  sorry \n\n\n\nlemma have_not_have_able_only_joinable:\n \" x \\<in> A\\<Longrightarrow> \\<lbrakk>\\<And>a b. Above a b \\<notin> A\\<rbrakk> \\<Longrightarrow>  x = Joinable c d\" \n\n  sorry\n\n\nlemma no_above_from_join_lemma:\n  assumes \"Above a b \\<in> connection A\"\n  and \"\\<And>a b. Above a b \\<notin> A\" \n  shows \"a = b\"\n  using assms\n  using no_joinable_from_join_lemma_gen\n  using have_not_have_able_only_joinable\n  by meson\n \n\n(* 1-i *)\nlemma \"\\<lbrakk> x \\<in> C \\<union> D ;C \\<subseteq> A ; D \\<subseteq> B \\<rbrakk> \\<Longrightarrow> x \\<in> A \\<union> B\"\n  by blast\n\nlemma connections_idem_simp: \"x \\<in> connection (connection C) \\<Longrightarrow> x \\<in> connection C\"\n  using connection_idem\n  by blast\n\nlemma connection_subset_simp: \"x \\<in> connection A \\<Longrightarrow> A \\<subseteq> B \\<Longrightarrow> x \\<in> connection B\"\n  by (metis connection_monotonic le_iff_sup)\n\nlemma connection_subset_con_simp: \"x \\<in> connection A \\<Longrightarrow> A \\<subseteq> connection B \\<Longrightarrow> x \\<in> connection B\"\n  using connections_idem_simp connection_subset_simp \n  by blast\n\nlemma connection_union_subset: \n  \"\\<lbrakk>A\\<subseteq>C; B\\<subseteq>D \\<rbrakk> \\<Longrightarrow> connection(A\\<union> B) \\<subseteq> connection (C\\<union> D)\"\n  by (meson Un_mono connection_subset_simp subset_eq)\n\nlemma connection_union_simp:\n  \"connection(connection A \\<union> connection B) = connection(A \\<union> B)\"\n  apply safe\n  using connection_union_subset connection_subset_con_simp \n  apply (metis (no_types, lifting) sup.bounded_iff sup.idem sup_ge2)\n  using connection_decompose connection_union_subset by blast\n\nlemma connection_compose:\n  assumes \"\\<phi> \\<in> connection(C \\<union> D)\"\n  and     \"C \\<subseteq> connection A\"\n  and     \"D \\<subseteq> connection B\"\n  shows   \"\\<phi> \\<in> connection(A \\<union> B)\"\n  using assms\n  using connection_union_subset connection_subset_con_simp connection_union_simp\n  by (smt connection_idem)\n  \n(* 1-j *)\nlemma connection_compositional:\n  assumes \"connection A = connection B\"\n  shows   \"connection(A \\<union> C) = connection(B \\<union> C)\"\n  using assms \n  using connection_compose\n  by (metis connection_union_simp)   \n  \n\nsection \"Part 2\"\n\ndatatype process =\n  Cond condition\n  | Par process process\n  | Input nat process\n  | Output nat process\n  | Nil\n\ndatatype action =\n  LInput nat | LOutput nat | LTau\n\nprimrec frame :: \"process \\<Rightarrow> condition set\" where\n  \"frame Nil = {}\"\n| \"frame(Cond \\<phi>) = {\\<phi>}\"\n| \"frame(Par P Q) = frame P \\<union> frame Q\"\n| \"frame(Input \\<phi> P) = {}\"\n| \"frame(Output \\<phi> P) = {}\"\n\n\ninductive semantics :: \"condition set \\<Rightarrow> process \\<Rightarrow> action \\<Rightarrow> process \\<Rightarrow> bool\"\n  where\n  semantics_input:\n     \"semantics A (Input n P) (LInput n) P\"\n| semantics_output:\n    \"semantics A (Output n P) (LOutput n) P\"\n| semantics_par_l:\n    \"semantics (A \\<union> frame Q) P \\<alpha> P'\n     \\<Longrightarrow> semantics A (Par P Q) \\<alpha> (Par P' Q)\"\n| semantics_par_r:\n    \"semantics (A \\<union> frame P) Q \\<alpha> Q'\n     \\<Longrightarrow> semantics A (Par P Q) \\<alpha> (Par P Q')\"\n| semantics_com_l:\n    \"\\<lbrakk>semantics (A \\<union> frame Q) P (LOutput n) P';\n      semantics (A \\<union> frame P) Q (LInput m) Q';\n      Joinable n m \\<in> connection(A \\<union> frame P \\<union> frame Q)\\<rbrakk>\n     \\<Longrightarrow> semantics A (Par P Q) LTau (Par P' Q')\"\n| semantics_com_r:\n    \"\\<lbrakk>semantics (A \\<union> frame Q) P (LInput n) P';\n      semantics (A \\<union> frame P) Q (LOutput m) Q';\n      Joinable n m \\<in> connection(A \\<union> frame P \\<union> frame Q)\\<rbrakk>\n     \\<Longrightarrow> semantics A (Par P Q) LTau (Par P' Q')\"\n\ninductive_cases\n  par: \"semantics A (Par P Q) x R\" and\n  nil: \"semantics A Nil x R\" and\n  cond: \"semantics A (Cond cond) x R\"\n\nsubsection \"Questions 2 (a)-(c)\"\n\n(* 2-a *)\nlemma semantics_monotonic:\n  assumes \"semantics A P \\<alpha> Q\"\n  shows \"semantics (A \\<union> B) P \\<alpha> Q\"\n  using assms \n  apply induct \n       apply (simp_all add:semantics.intros sup_assoc sup_commute  sup_left_commute)\n   apply (smt Un_assoc connection_monotonic inf_sup_aci(5) semantics_com_l)\n  apply (smt Un_commute connection_monotonic semantics_com_r sup_assoc)\n  done \n \n(* 2-b *)\nlemma semantics_empty_env:\n  assumes \"semantics A P \\<alpha> Q\"\n  shows \"\\<exists>\\<beta> Q'. semantics {} P \\<beta> Q'\"\n  (* TODO *)\n  \n  apply (rule_tac exI)+\n  using assms\n  apply induct\n  \n\n  oops\n\n(* 2-c *)\nlemma semantics_swap_frame:\n  assumes \"semantics A P \\<alpha> Q\"\n  and \"connection A = connection B\"\n  shows \"semantics B P \\<alpha> Q\"\n  using assms \n  apply - \n  apply induct \n  oops\n\nsection \"Part 3\"\n\ndefinition stuck :: \"process \\<Rightarrow> bool\"\nwhere\n  \"stuck P \\<equiv> \\<forall>\\<alpha> P'. semantics {} P \\<alpha> P' \\<longrightarrow> False\"\n\nprimrec list_trans :: \"_\" where\n  \"list_trans A P [] Q = (P = Q)\"\n| \"list_trans A P (\\<alpha>#tr) Q =\n    (\\<exists>R. semantics A P \\<alpha> R \\<and> list_trans A R tr Q)\"\n\ndefinition traces_of :: \"process \\<Rightarrow> action list set\"\n  where \"traces_of P = {tr | tr. \\<exists>Q. list_trans {} P tr Q \\<and> stuck Q}\"\n\ndefinition trace_eq :: \"process \\<Rightarrow> process \\<Rightarrow> bool\"\n  where \"trace_eq P Q = (traces_of P = traces_of Q)\"\n\nsubsection \"Question 3 (a)\"\n\nlemma trace_eq_refl:\n  shows \"trace_eq P P\"\n  (* TODO *)\n  oops\n\nlemma trace_eq_sym:\n  assumes \"trace_eq P Q\"\n    shows \"trace_eq Q P\"\n  (* TODO *)\n  oops\n\nlemma trace_eq_trans:\n  assumes \"trace_eq P Q\"\n      and \"trace_eq Q R\"\n    shows \"trace_eq P R\"\n  (* TODO *)\n  oops\n\nsubsection \"Question 3 (b)\"\n\nlemma trace_eq_stuck:\n  assumes \"stuck P\"\n      and \"stuck Q\"\n    shows \"trace_eq P Q\"\n  (* TODO *)\n  oops\n\nsubsection \"Question 3 (c)\"\n\nlemma traces_of_monotonic:\n  assumes \"stuck R\"\n  shows \"traces_of P \\<subseteq> traces_of (Par P R)\"\n  (* TODO *)\n  oops\n\nsubsection \"Question 3 (d)\"\n\ntext \\<open>Feel free to give this answer in free-text comments,\n      or as Isabelle definitions. \\<close>\n\nsubsection \"Question 3 (e)\"\n\nlemma traces_of_not_antimonotonic:\n  assumes \"\\<And>P R. stuck R \\<Longrightarrow> traces_of (Par P R) \\<subseteq> traces_of P\"\n  shows \"False\"\n  (* TODO *)\n  oops\n\nsubsection \"Question 3 (f)\"\n\nlemma semantics_par_assoc1:\n  assumes \"semantics A (Par P (Par Q S)) \\<alpha> R\"\n  shows \"\\<exists>P' Q' S'.\n           R = Par P' (Par Q' S') \\<and>\n           semantics A (Par (Par P Q) S) \\<alpha> (Par (Par P' Q') S')\"\n  (* TODO *)\n  oops\n\ntext \\<open>\n  This similar lemma will be needed later.\n  You may use it without proof. \\<close>\nlemma semantics_par_assoc2:\n  \"semantics A (Par (Par P Q) S) \\<alpha> R \\<Longrightarrow>\n  \\<exists> P' Q' S'. R = Par (Par P' Q') S' \\<and> semantics A (Par P (Par Q S)) \\<alpha> (Par P' (Par Q' S'))\"\n  sorry\n\nsubsection \"Question 3 (g)\"\n\nlemma list_trans_par_assoc:\n  \"list_trans A (Par (Par P Q) S) tr (Par (Par P' Q') S') =\n       list_trans A (Par P (Par Q S)) tr (Par P' (Par Q' S'))\"\n  (* TODO *)\n  oops\n\nsubsection \"Question 3 (h)\"\n\nlemma stuck_par:\n  \"stuck(Par P Q) = (stuck P \\<and> stuck Q)\"\n  (* TODO *)\n  oops\n\nsubsection \"Question 3 (i)\"\n\nlemma trace_eq_par_assoc:\n  shows \"trace_eq (Par (Par P Q) S) (Par P (Par Q S))\"\n  (* TODO *)\n  oops\n\nsubsection \"Question 3 (j)\"\n\nlemma trace_eq_nil_par:\n  shows \"trace_eq P (Par P Nil)\"\n  (* TODO *)\n  oops\n\nsubsection \"Question 3 (k)\"\n\nlemma trace_eq_par_comm:\n  shows \"trace_eq (Par P Q) (Par Q P)\"\n  (* TODO *)\n  oops\n\nend", "meta": {"author": "tecty", "repo": "COMP4161-Ass2", "sha": "6a77772b11a933fbb454704c162f65f51ef08f76", "save_path": "github-repos/isabelle/tecty-COMP4161-Ass2", "path": "github-repos/isabelle/tecty-COMP4161-Ass2/COMP4161-Ass2-6a77772b11a933fbb454704c162f65f51ef08f76/a2-old.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.897695292107347, "lm_q2_score": 0.7905303087996143, "lm_q1q2_score": 0.709655336477581}}
{"text": "theory Ex19 \nimports Main \nbegin \n\n(*distributivity of \"and\" over \"or\"*)\nlemma \"A \\<and> (B \\<or> C) \\<longleftrightarrow> (A \\<and> B) \\<or> (A \\<and> C)\"\nproof - \n{\n  assume \"A \\<and> (B \\<or> C)\"\n  hence A by (rule conjE)\n  from \\<open>A \\<and> (B \\<or> C)\\<close> have \"B \\<or> C\" by (rule conjE)\n  {\n    assume B\n    with  \\<open>A\\<close> have \"A \\<and> B\" by (rule conjI)\n    hence \"(A \\<and> B) \\<or> (A \\<and> C)\" by (rule disjI1)\n  }\n  moreover\n  {\n    assume C\n    with \\<open>A\\<close> have \"A \\<and> C\" by (rule conjI)\n    hence \"(A \\<and> B) \\<or> (A \\<and> C)\" by (rule disjI2)\n  }\n  from \\<open>B \\<or> C\\<close> and calculation and this have \"(A \\<and> B) \\<or> (A \\<and> C)\" by (rule disjE)\n}\nmoreover\n{\n  assume \"(A \\<and> B) \\<or> (A \\<and> C)\"\n  {\n    assume \"A \\<and> B\"\n    hence A by (rule conjE)\n    from \\<open>A \\<and> B\\<close> have B by (rule conjE)\n    hence \"B \\<or> C\" by (rule disjI1)\n    with \\<open>A\\<close> have \"A \\<and> (B \\<or> C)\" by (rule conjI)\n  }\n  moreover \n  {\n    assume \"A \\<and> C\"\n    hence A by (rule conjE)\n    from \\<open>A \\<and> C\\<close> have C by (rule conjE)\n    hence \"B \\<or> C\" by (rule disjI2)\n    with \\<open>A\\<close> have \"A \\<and> (B \\<or> C)\" by (rule conjI)\n  }\n  from \\<open>(A \\<and> B) \\<or> (A \\<and> C)\\<close> and calculation and this have \"A \\<and> (B \\<or> C)\" 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/Ex19.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110454379297, "lm_q2_score": 0.7956581049086031, "lm_q1q2_score": 0.7095766863497033}}
{"text": "(* Title: Program Correctness Component Based on Modal Kleene Algebra\n   Author: Peixin You\n*)\n\nsection \\<open>Verification Component Based on Modal Kleene Algebra\\<close>\n\ntheory MKA\n  imports KA Store\n\nbegin\n\nsubsection \\<open>Definitions\\<close>\n\nclass antidomain_kleene_algebra = kleene_algebra + \n  fixes ad :: \"'a \\<Rightarrow> 'a\" \n  assumes ad_annil [simp]: \"ad x \\<cdot> x = 0\"\n  and ad_local_sub [simp]: \"ad (x \\<cdot> y) \\<le> ad (x \\<cdot> ad (ad y))\"\n  and ad_compl1 [simp]: \"ad (ad x) + ad x = 1\"\n\nbegin\n\ndefinition dom_op :: \"'a \\<Rightarrow> 'a\" (\"do\") where\n  \"do x = ad (ad x)\"\n\ndefinition fdia :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a\" where\n  \"fdia x y = do (x \\<cdot> y)\"\n\ndefinition fbox :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a\" where\n  \"fbox x y = ad (x \\<cdot> ad y)\"\n\nend\n\nclass antirange_kleene_algebra = kleene_algebra +\n  fixes ar :: \"'a \\<Rightarrow> 'a\" \n  assumes ar_annil [simp]: \"x \\<cdot> ar x  = 0\"\n  and ar_local_sub [simp]: \"ar (x \\<cdot> y) \\<le> ar (ar (ar x) \\<cdot> y)\"\n  and ar_compl1 [simp]: \"ar (ar x) + ar x = 1\"\n\nbegin\n\ndefinition range_op :: \"'a \\<Rightarrow> 'a\" (\"ra\") where\n  \"ra x = ar (ar x)\"\n\ndefinition bdia :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a\" where\n  \"bdia x y = ra (y \\<cdot> x)\"\n\ndefinition bbox :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a\"  where\n  \"bbox x y = ar (ar y \\<cdot> x)\"\n\nend\n\nclass modal_kleene_algebra = antidomain_kleene_algebra + antirange_kleene_algebra \n\nsubsection \\<open>Formalisation of Opposition Duality\\<close>\n\nsublocale antirange_kleene_algebra \\<subseteq> op_arka: antidomain_kleene_algebra \"(+)\" \"0\" \"1\" \"\\<lambda>x y. y \\<cdot> x\" \"(\\<le>)\" \"(<)\" _ ar\n  rewrites \"op_arka.dom_op x = ra x\"\n  and \"op_arka.fdia x y = bdia x y\"\n  and \"op_arka.fbox x y = bbox x y\"\nproof -\n  show \"class.antidomain_kleene_algebra (+) 0 1 (\\<lambda>x y. y \\<cdot> x) (\\<le>) (<) star ar\"\n    by unfold_locales (simp_all add: mult_assoc distr distl star_inductl star_inductr)\n  then interpret op_arka: antidomain_kleene_algebra \"(+)\" \"0\" \"1\" \"(\\<lambda>x y. y \\<cdot> x)\" \"(\\<le>)\" \"(<)\" star ar.\n  show \"op_arka.dom_op x = ra x\"\n    by (simp add: range_op_def op_arka.dom_op_def)\n  show \"op_arka.fdia x y = bdia x y\"\n    by (simp add: bdia_def range_op_def op_arka.dom_op_def op_arka.fdia_def)\n  show \"op_arka.fbox x y = bbox x y\"\n    by (simp add: bbox_def op_arka.fbox_def)\nqed\n\nsublocale antidomain_kleene_algebra \\<subseteq> arka_op: antirange_kleene_algebra \"(+)\" \"0\" \"1\" \"(\\<lambda>x y. y \\<cdot> x)\" \"(\\<le>)\" \"(<)\" star ad\n  rewrites \"arka_op.range_op x = do x\"\n  and \"arka_op.bdia x y = fdia x y\"\n  and \"arka_op.bbox x y = fbox x y\"\nproof -\n  show \"class.antirange_kleene_algebra (+) 0 1 (\\<lambda>x y. y \\<cdot> x) (\\<le>) (<) star ad\"\n    by unfold_locales (simp_all add: mult_assoc distl distr star_inductl star_inductr)\n  then interpret arka_op: antirange_kleene_algebra \"(+)\" \"0\" \"1\" \"(\\<lambda>x y. y \\<cdot> x)\" \"(\\<le>)\" \"(<)\" star ad.\n  show \"arka_op.range_op x = do x\"\n    by (simp add: arka_op.range_op_def dom_op_def)\n  show \"arka_op.bdia x y = fdia x y\"\n    by (simp add: arka_op.bdia_def arka_op.range_op_def dom_op_def fdia_def)\n  show \"arka_op.bbox x y = fbox x y\"\n    by (simp add: arka_op.bbox_def fbox_def)\nqed\n\nsubsection \\<open>Basic Properties\\<close>\n\ncontext antidomain_kleene_algebra\nbegin\n\nlemma a_subid_aux: \"ad x \\<cdot> y \\<le> y\"\n  by (metis ad_compl1 add.commute add_ubl mult.left_neutral mult_isor)\n\nlemma d1_a [simp]: \"do x \\<cdot> x = x\"\n  unfolding dom_op_def by (metis add_0_right ad_annil ad_compl1 distr mult_1_left)\n                                  \nlemma ad_one [simp]: \"ad 1 = 0\"\n  by (metis ad_annil mult_1_right)\n\nlemma ad_zero [simp]: \"ad 0 = 1\"\n  by (metis ad_one ad_compl1 add_0_right)\n\nlemma ad_compl2 [simp]: \"ad x \\<cdot> do x = 0\"\n  by (metis antisym arka_op.ar_annil arka_op.ar_local_sub dom_op_def mult_1_left mult_isor zero_least)\n\nlemma ad_d: \"(ad x \\<cdot> y = 0) = (do x \\<cdot> y = y)\"\n  by (metis ad_compl2 add_commute dom_op_def ad_compl1 add_0_left annil distr mult_1_left mult_assoc)\n\nlemma d_a_closed [simp]: \"ad (do x) = ad x\"\n  by (metis ad_one ad_zero ad_zero d1_a dom_op_def ad_annil ad_compl1 annir distl mult_1_right)\n\nlemma a_idem [simp]: \"ad x \\<cdot> ad x = ad x\"\n  by (metis d1_a d_a_closed dom_op_def)\n\nlemma meet_ord: \"(ad x \\<le> ad y) = (ad x \\<cdot> ad y = ad x)\"\n  by (metis a_subid_aux d1_a d_a_closed dom_op_def antisym mult_1_right mult_isol)\n\nlemma d_wloc: \"(x \\<cdot> y = 0) = (x \\<cdot> do y = 0)\"\n  by (metis a_subid_aux d1_a dom_op_def ad_annil ad_local_sub antisym mult_1_right mult_assoc)\n\nlemma gla: \"(ad x \\<cdot> y = 0) = (ad x \\<le> ad y)\"\n  apply standard\n   apply (smt a_subid_aux add_commute d_wloc dom_op_def ad_compl1 add_0_right distl mult_1_right)\n  by (metis ad_annil annir mult_assoc meet_ord)\n\nlemma a_local [simp]: \"ad (x \\<cdot> do y) = ad (x \\<cdot> y)\"\n  by (smt d_wloc gla ad_annil antisym mult_assoc)                                              \n\nlemma a_supdist: \"ad (x + y) \\<le> ad x\"\n  by (metis gla ad_annil add_0_right add_ubl distl order_def)\n\nlemma a_antitone: \"x \\<le> y \\<Longrightarrow> ad y \\<le> ad x\"\n  by (metis a_supdist order_def)\n\nlemma d_iso: \"x \\<le> y \\<Longrightarrow> do x \\<le> do y\"\n  by (simp add: a_antitone dom_op_def)\n\nlemma d_a_ord: \"(do x \\<le> do y) = (ad y \\<le> ad x)\"\n  using a_antitone dom_op_def by fastforce\n\nlemma llp: \"(do y \\<cdot> x = x) = (do x \\<le> do y)\"\n  by (metis a_antitone ad_d d_a_closed dom_op_def gla)\n\nlemma a_comm: \"ad x \\<cdot> ad y = ad y \\<cdot> ad x\"\n  by (rule antisym) (metis a_local a_subid_aux d1_a d_a_closed d_iso dom_op_def eq_refl mult_1_right mult_iso)+\n\nlemma a_closed [simp]: \"do (ad x \\<cdot> ad y) = ad x \\<cdot> ad y\"\n  by (smt a_comm a_idem a_subid_aux ad_zero d1_a d_a_closed d_iso dom_op_def mult_1_right mult_assoc meet_ord)\n\n\n\nlemma a_de_morgan: \"ad (ad x \\<cdot> ad y) = do x + do y\"\n  by (simp add: dom_op_def)\n\nlemma d1_sum_var: \"x + y \\<le> (do x + do y) \\<cdot> (x + y)\"\n  by (simp add: add_commute add_iso add_ubl distl distr)\n\nlemma a_dual_add: \"ad (x + y) = ad x \\<cdot> ad y\"\n  apply (rule antisym)\n  apply (metis a_supdist add_commute  mult_isor meet_ord)\n  by (metis a_closed a_de_morgan a_exp a_subid_aux d1_sum_var antisym  order_def)\n\nlemma d_add: \"do (x + y) = do x + do y\"\n  by (simp add: a_dual_add dom_op_def)\n\nlemma a_absorb1 [simp]: \"ad x \\<cdot> (ad x + ad y) = ad x\"\n  using a_dual_add a_supdist add_commute distl order_def by auto\n\nlemma a_absorb2 [simp]: \"ad x + ad x \\<cdot> ad y = ad x\"\n  using a_dual_add a_supdist add_commute order_def by auto\n\nlemma a_dist: \"ad x + ad y \\<cdot> ad z = (ad x + ad y) \\<cdot> (ad x + ad z)\"\n  by (smt a_absorb1 a_subid_aux abel_semigroup.commute abel_semigroup.left_commute add.abel_semigroup_axioms distl distr order_def)\n\nlemma a_lbl: \"ad x \\<cdot> ad y \\<le> ad x\"\n  using a_dual_add a_supdist by simp\n\nlemma a_lower: \"ad x \\<le> ad y \\<Longrightarrow> ad x \\<le> ad z \\<Longrightarrow> ad x \\<le> ad y \\<cdot> ad z\"\n  by (simp add: a_dist order_def)\n\nlemma a_glb: \"(ad x \\<le> ad y \\<and> ad x \\<le> ad z) = (ad x \\<le> ad y \\<cdot> ad z)\"\n  using a_lbl a_lower a_subid_aux dual_order.trans by blast\n\nlemma at_shunt: \"(ad x \\<cdot> ad y \\<le> ad z) = (ad x \\<le> do y + ad z)\"\n  by (metis a_dual_add a_exp gla mult_assoc)\n\nlemma a_comp_dist [simp]: \"(ad p + ad q) \\<cdot> (do p + ad t) = ad p \\<cdot> ad t + do p \\<cdot> ad q\"\nproof-\n  have \"(ad p + ad q) \\<cdot> (do p + ad t) = ad p \\<cdot> ad t + do p \\<cdot> ad q + (ad p + do p) \\<cdot> ad q \\<cdot> ad t\"\n    using a_comm ad_compl2 add_commute add_assoc arka_op.ar_compl1 distl distr dom_op_def by simp\n  also have \"\\<dots> = ad p \\<cdot> ad t + do p \\<cdot> ad q + ad p \\<cdot> ad q \\<cdot> ad t + do p \\<cdot> ad q \\<cdot> ad t\"\n    by (simp add: add_assoc distr)\n  also have \"\\<dots> = (1 + ad q) \\<cdot> ad p \\<cdot> ad t + (1 + ad t) \\<cdot> do p \\<cdot> ad q\"\n    by (smt a_comm add_commute add.left_commute arka_op.distl arka_op.range_op_def mult.semigroup_axioms mult_1_left semigroup.assoc)\n  finally show ?thesis\n    by (metis a_absorb2 ad_zero mult_1_left)\nqed\n\nlemma pcorrect_if1: \"ad p \\<cdot> x \\<le> x \\<cdot> ad q \\<Longrightarrow> ad p \\<cdot> x \\<cdot> do q = 0\"\n  by (smt d_wloc ad_annil add_0_right annir arka_op.mult_assoc distr order_def)\n\nlemma pcorrect_if2: \"ad p \\<cdot> x \\<cdot> do q = 0 \\<Longrightarrow> ad p \\<cdot> x \\<cdot> ad q = ad p \\<cdot> x\"\n  by (metis a_absorb2 d_a_closed local.arka_op.annil arka_op.ar_annil arka_op.ar_compl1 arka_op.distr arka_op.range_op_def mult_1_right) \n\nlemma pcorrect_if3: \"ad p \\<cdot> x = ad p \\<cdot> x \\<cdot> ad q \\<Longrightarrow> ad p \\<cdot> x \\<le> x \\<cdot> ad q\"\n  by (metis a_subid_aux mult_isor)\n\nlemma pcorrect_iff1: \"(ad p \\<cdot> x \\<le> x \\<cdot> ad q) = (ad p \\<cdot> x \\<cdot> do q = 0)\"  \n   by (metis pcorrect_if1 pcorrect_if2 pcorrect_if3)\n\nlemma pcorrect_iff2: \"(ad p \\<cdot> x \\<cdot> do q = 0) = (ad p \\<cdot> x \\<cdot> ad q = ad p \\<cdot> x)\" \n  by (metis pcorrect_if1 pcorrect_if2 pcorrect_if3) \n\nlemma pcorrect_iff2_op: \"(do p \\<cdot> x \\<cdot> ad q = 0) = (x \\<cdot> ad q = ad p \\<cdot> x \\<cdot> ad q)\"\n  by (metis ad_d d_a_closed arka_op.mult_assoc dom_op_def)\n\nlemma pcorrect_iff3_op: \"(x \\<cdot> ad q = ad p \\<cdot> x \\<cdot> ad q) = (x \\<cdot> ad q \\<le> ad p \\<cdot> x)\"\n  apply standard\n  apply (metis a_subid_aux mult_1_right mult_isol)\n  by (metis a_antitone a_exp d_a_closed llp add_lub arka_op.mult_assoc dom_op_def)\n\nlemma pcorrect_iff1_op: \"(x \\<cdot> ad q \\<le> ad p \\<cdot> x) = (do p \\<cdot> x \\<cdot> ad q = 0)\"\n  by (simp add: pcorrect_iff2_op pcorrect_iff3_op)\n\nlemma pcorrect_var: \"(ad p \\<cdot> x \\<le> x \\<cdot> ad q) = (x \\<cdot> do q \\<le> do p \\<cdot> x)\"\n  using d_a_closed  dom_op_def pcorrect_iff1 pcorrect_iff1_op by auto\n\nlemma pcorrect_var2: \"(do p \\<cdot> x \\<le> x \\<cdot> do q) = (x \\<cdot> ad q \\<le> ad p \\<cdot> x)\"\n  by (metis d_a_closed local.dom_op_def pcorrect_iff1 pcorrect_iff1_op)\n\nlemma ad_star [simp]: \"ad (x\\<^sup>\\<star>) = 0\"\n  by (metis a_dual_add ad_one annil star_unfoldl_eq)\n\nend\n\ncontext antidomain_kleene_algebra\nbegin\n\nsubsection \\<open>Forward Diamond and Box Operators\\<close>\n\nlemma fbox_fdia: \"fbox x p = ad (fdia x (ad p))\"\n  by (simp add: fbox_def fdia_def)\n\nlemma fdia_fbox: \"fdia x p = ad (fbox x (ad p))\"\n  using a_local dom_op_def fbox_def fdia_def by simp\n\nlemma fdia_demod: \"(fdia x y \\<le> do z) = (x \\<cdot> do y \\<le> do z \\<cdot> x)\"\n  by (unfold fdia_def, metis a_local arka_op.mult_assoc dom_op_def llp pcorrect_iff3_op)\n\nlemma fbox_demod: \"(do y \\<le> fbox x z) = (do y \\<cdot> x  \\<le> x \\<cdot> do z)\"\n  by (unfold fbox_def, metis arka_op.mult_assoc d_a_closed dom_op_def gla pcorrect_iff1)\n\nlemma fdia_dom [simp]: \"fdia x 1 = do x\"\n  by (simp add: fdia_def)\n\nlemma fbox_dom [simp]: \"fbox x 0 = ad x\"\n  by (simp add: fbox_def)\n\nlemma fdia_one [simp]: \"fdia 1 x = do x\"\n  by (simp add: fdia_def)\n\nlemma fbox_zero [simp]: \"fbox 0 x = 1\"\n  by (simp add: fbox_def)\n\nlemma fdia_zero_var [simp]: \"fdia 0 x = 0\"\n  by (simp add: dom_op_def fdia_def)\n\nlemma fbox_zero_var [simp]: \"fbox 1 x = do x\"\n  by (simp add: dom_op_def fbox_def) \n\n\n\nlemma fbox_one_1 [simp]: \"fbox x 1 = 1\"\n  by (simp add: fbox_def)\n\nlemma fdia_add1: \"fdia x (y + z) = fdia x y + fdia x z\"\n  by (simp add: a_dual_add distl dom_op_def fdia_def)\n\nlemma fbox_add1: \"fbox x (do y \\<cdot> do z) = fbox x y \\<cdot> fbox x z\"\n  by (metis a_dual_add a_local arka_op.distr dom_op_def fbox_def)\n\nlemma fdia_add2: \"fdia (x + y) z = fdia x z + fdia y z\"\n  by (simp add: a_dual_add distr dom_op_def fdia_def)\n\nlemma fbox_add2: \"fbox (x + y) z = fbox x z \\<cdot> fbox y z\"\n  by (simp add: a_dual_add fbox_def distr)\n\nlemma fdia_comp: \"fdia (x \\<cdot> y) z = fdia x (fdia y z)\"\n  using a_local arka_op.mult_assoc arka_op.range_op_def fdia_def by auto\n\nlemma fbox_comp: \"fbox (x \\<cdot> y) z = fbox x (fbox y z)\"\n  using a_local dom_op_def fbox_def mult_assoc by auto\n\nlemma fdia_iso1: \"do x \\<le> do y \\<Longrightarrow> fdia z x \\<le> fdia z y\"\n  by (metis a_dual_add a_exp a_local arka_op.distr dom_op_def fdia_def order_def)\n\nlemma fbox_iso: \"do x \\<le> do y \\<Longrightarrow> fbox z x \\<le> fbox z y\"\n  by (metis a_antitone d_a_closed fbox_def mult_isol)\n\nlemma fdia_iso2: \"x \\<le> y \\<Longrightarrow> fdia x z \\<le> fdia y z\"\n  by (simp add: d_iso fdia_def mult_isor)\n\nlemma fbox_anti: \"x \\<le> y \\<Longrightarrow> fbox y z \\<le> fbox x z\"\n  by (simp add: a_antitone fbox_fdia fdia_iso2)\n\nlemma fdia_export: \"ad y \\<cdot> fdia x z = fdia (ad y \\<cdot> x) z\"\n  using a_closed dom_op_def fdia_def fdia_comp by simp\n\nlemma fbox_export: \"ad y + fbox x y = fbox (do y \\<cdot> x) y\"\n  by (metis fbox_fdia fdia_export a_exp d_a_closed  dom_op_def)\n\nlemma fdia_diff: \"fdia x (do y \\<cdot> ad z) \\<le> fdia x y + ad (fdia x z)\"\n  by (metis fdia_iso1 a_closed a_lbl add_ubl dom_op_def dual_order.trans)\n\nlemma fbox_diff: \"fbox x (do y + ad z) \\<le> fbox x y + ad (fbox x z)\"\nproof-\n  have \"fbox x (do y + ad z) \\<cdot> fbox x z \\<le> fbox x y\"\n    by (metis add_commute fbox_add1 fbox_iso a_closed a_idem arka_op.range_op_def at_shunt d1_sum_var d_add)\n  thus ?thesis\n    by (simp add: add_commute at_shunt dom_op_def fbox_def)\nqed\n\nlemma fdia_star_unfoldl [simp]: \"fdia 1 y + fdia x (fdia (x\\<^sup>\\<star>) y) = fdia (x\\<^sup>\\<star>) y\"\n  by (metis fdia_add2 fdia_comp star_unfoldl_eq)\n\nlemma fbox_star_unfoldl [simp]: \"fbox 1 y \\<cdot> fbox x (fbox (x\\<^sup>\\<star>) y) = fbox (x\\<^sup>\\<star>) y\"\n  by (metis fbox_add2 fbox_comp star_unfoldl_eq)\n\nlemma fdia_star_unfoldr [simp]: \"fdia 1 y + fdia (x\\<^sup>\\<star>) (fdia x y) = fdia (x\\<^sup>\\<star>) y\"\n  by (metis fdia_add2 fdia_comp star_unfoldr_eq)\n\nlemma fbox_star_unfoldr [simp]: \"fbox 1 y \\<cdot> fbox (x\\<^sup>\\<star>) (fbox x y) = fbox (x\\<^sup>\\<star>) y\"\n  by (metis fbox_add2 fbox_comp star_unfoldr_eq)\n\nlemma fdia_star_inductl_var: \"fdia x y \\<le> do y \\<Longrightarrow> fdia (x\\<^sup>\\<star>) y \\<le> do y\"\n  by (simp add: fdia_demod star_sim2)\n\nlemma fbox_star_inductl_var: \"do y \\<le> fbox x y \\<Longrightarrow> do y \\<le> fbox (x\\<^sup>\\<star>) y\"\n  using d_a_ord fdia_star_inductl_var dom_op_def fbox_def fdia_def by auto\n\nlemma fdia_star_inductl: \"do z + fdia x y \\<le> do y \\<Longrightarrow> fdia (x\\<^sup>\\<star>) z \\<le> do y\"\n  using fdia_iso1 fdia_star_inductl_var add_lub dual_order.trans by blast\n\nlemma fbox_star_inductl: \"do y \\<le> do z \\<cdot> fbox x y \\<Longrightarrow> do y \\<le> fbox (x\\<^sup>\\<star>) z\"\n  by (metis a_comm a_subid_aux fbox_fdia fbox_iso fbox_star_inductl_var dom_op_def dual_order.trans)\n\nend\n\nsubsection \\<open>Coherence, Galois Connections and Conjugations\\<close>\n\ncontext modal_kleene_algebra\nbegin\n\nlemma dr_coh_aux1 [simp]: \"ar x \\<cdot> do (ra x) = 0\"\nproof-\n  have \"ar x \\<cdot> ra x = 0\"\n    by (simp add: range_op_def)\n  thus \"ar x \\<cdot> do (ra x) = 0\"\n    using d_wloc by simp\nqed\n\nlemma dr_coh_aux2 [simp]: \"ra x \\<cdot> do (ra x) \\<cdot> ar x = 0\"\nproof-\n  have \"ra x \\<cdot> do (ra x) \\<cdot> ar x \\<le> ra x \\<cdot> ar x\"\n    by (metis a_subid_aux arka_op.mult_assoc dom_op_def mult_isol)\n  also have \"\\<dots> = 0\"\n    by simp\n  finally show ?thesis\n    using order_def by simp\nqed\n\nlemma dr_coh [simp]: \"do (ra x) = ra x\"\nproof -\n  have \"do (ra x) = (ar x + ra x) \\<cdot> do (ra x)\"\n    using add_commute op_arka.ad_compl1 range_op_def by auto\n  also have \"\\<dots> = ar x \\<cdot> do (ra x) + ra x \\<cdot> do (ra x) \\<cdot> (ar x + ra x)\"\n    by (metis (mono_tags, lifting) add_commute arka_op.distl mult_1_right op_arka.ad_compl1 range_op_def)\n  also have \"\\<dots> =  0 + ra x \\<cdot> do (ra x) \\<cdot> ar x + ra x \\<cdot> do (ra x) \\<cdot> ra x\"\n    using distl by simp\n  also have \"\\<dots> = 0 + ra x \\<cdot> ra x\"\n    by (simp add: mult.semigroup_axioms semigroup.assoc)\n  also have \"\\<dots> = ra x\"\n    by (simp add: local.range_op_def)\n  finally show ?thesis.\nqed\n\nlemma rd_coh [simp]: \"ra (do x) = do x\"\n  by (smt dr_coh a_comm ad_compl2 ad_d dom_op_def op_arka.d_wloc)\n\nlemma do_ra: \"(do x = x) = (ra x = x)\"\n  by (metis dr_coh rd_coh)\n\nlemma do_ra_alg: \"{x. do x = x} = {x. ra x = x}\"\n  by (simp add: do_ra)\n\nlemma dr_zero: \"(x \\<cdot> y = 0) = (ra x \\<cdot> do y = 0)\"\n  by (metis d_wloc op_arka.d_wloc)\n\n\n\nlemma fdia_bbox_galois: \n  assumes \"do p = p\" and \"do q = q\"\n  shows \"(fdia x p \\<le> q) = (p \\<le> bbox x q)\"\n  by (metis assms fdia_demod op_arka.fbox_demod rd_coh)\n\nlemma dia_conjugation: \n  assumes \"do p = p\" and \"do q = q\"\n  shows \"(p \\<cdot> fdia x q = 0) = (bdia x p \\<cdot> q = 0)\"\nproof-\n  have \"(p \\<cdot> fdia x q = 0) = (fdia x q \\<le> ad p)\"\n    by (metis assms ad_d dom_op_def fdia_fbox gla llp)\n  also have \"\\<dots> = (q \\<le> bbox x (ar p))\"\n    by (metis assms do_ra fdia_bbox_galois ad_d local.dom_op_def op_arka.a_idem op_arka.ad_d range_op_def)\n  also have \"\\<dots> = (q \\<le> ar (bdia x p))\"\n    by (metis assms op_arka.fbox_fdia range_op_def rd_coh)\n  also have \"\\<dots> = (bdia x p \\<cdot> q = 0)\"\n    by (metis assms op_arka.gla range_op_def rd_coh)\n  finally show ?thesis.\nqed\n\nlemma box_conjugation: \n  assumes \"do p = p\" and \"do q = q\"\n  shows \"(p + fbox x q = 1) = (bbox x p + q = 1)\"\nproof-\n  have \"(p + fbox x q = 1) = (ad p \\<cdot> ad (fbox x q) = 0)\"\n    by (metis assms a_dual_add a_exp a_local ad_one ad_zero dom_op_def fbox_def)\n  also have \"\\<dots> = (ad p \\<cdot> fdia x (ad q) = 0)\"\n    by (simp add: dom_op_def fbox_def fdia_def)\n  also have \"\\<dots> = (bdia x (ar p) \\<cdot> ar q = 0)\"\n    by (smt assms dia_conjugation do_ra ad_d dom_op_def op_arka.a_idem op_arka.ad_d range_op_def)\n  also have \"\\<dots> = (ar (bbox x p) \\<cdot> ar q = 0)\"\n    by (simp add: op_arka.fbox_def op_arka.fdia_def range_op_def)\n  also have \"\\<dots> = (bbox x p + q = 1)\"\n    by (metis \\<open>(bdia x (ar p) \\<cdot> ar q = 0) = (ar (bbox x p) \\<cdot> ar q = 0)\\<close> add_commute assms op_arka.a_dual_add op_arka.a_exp op_arka.ad_one op_arka.ad_zero op_arka.fbox_fdia rd_coh)\n  finally show ?thesis.\nqed\n\nend\n\nsubsection \\<open>Algebraic Laws for VCG\\<close>\n\ncontext antidomain_kleene_algebra\nbegin\n\ndefinition cond :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> 'a\" (\"if _ then _ else _ fi\" [64,64,64] 63) where\n  \"if p then x else y fi = do p \\<cdot> x + ad p \\<cdot> y\"\n\ndefinition while :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a\" (\"while _ do _ od\" [64,64] 63) where\n  \"while p do x od = (do p \\<cdot> x)\\<^sup>\\<star> \\<cdot> ad p\"\n\ndefinition while_inv :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> 'a\" (\"while _ inv _ do _ od\" [64,64,64] 63) where\n  \"while p inv i do x od = while p do x od\"\n\nlemma while_if: \"while p do x od = if p then x \\<cdot> (while p do x od) else 1 fi\"\n  by (smt abel_semigroup.commute cond_def a_comm ad_zero add.abel_semigroup_axioms distr mult.semigroup_axioms star_unfoldl_eq semigroup.assoc while_def)\n\nlemma fbox_cond: \"fbox (if p then x else y fi) q = (ad p + fbox x q) \\<cdot> (do p + fbox y q)\"\nproof- \n  have \"fbox (if p then x else y fi) q = fbox (do p \\<cdot> x + ad p \\<cdot> y) q\"\n    by (simp add: cond_def)\n  also have \"\\<dots> = fbox (do p \\<cdot> x) q \\<cdot> fbox (ad p \\<cdot> y) q\"\n    by (simp add: fbox_add2)\n  also have \"\\<dots> = (ad p + fbox x q) \\<cdot> (do p + fbox y q)\"\n    by (metis a_exp arka_op.mult_assoc d_a_closed dom_op_def fbox_def)\n  finally show ?thesis.\nqed\n\nlemma fbox_condl: \"do p \\<cdot> fbox (if p then x else y fi) q = do p \\<cdot> fbox x q\"\nproof-\n  have \"do p \\<cdot> fbox (if p then x else y fi) q = do p \\<cdot> (ad p + fbox x q) \\<cdot> (do p + fbox y q)\"\n    by (simp add: fbox_cond arka_op.mult_assoc)\n  also have \"\\<dots> = do p \\<cdot> fbox x q \\<cdot> (do p + fbox y q)\"\n    by (simp add: distl dom_op_def)\n  also have \"\\<dots> = do p \\<cdot> fbox x q\"\n    by (metis a_absorb1 a_comm arka_op.mult_assoc dom_op_def fbox_fdia)\n  finally show ?thesis.\nqed\n\nlemma fbox_condr: \"ad p \\<cdot> fbox (if p then x else y fi) q = ad p \\<cdot> fbox y q\"\nproof-\n  have \"ad p \\<cdot> fbox (if p then x else y fi) q = ad p \\<cdot> (ad p + fbox x q) \\<cdot> (do p + fbox y q)\"\n    by (simp add: fbox_cond arka_op.mult_assoc)\n  also have \"\\<dots> = ad p \\<cdot> (do p + fbox y q)\"\n    by (simp add: fbox_def)\n  also have \"\\<dots> = ad p \\<cdot> fbox y q\"\n    by (simp add: arka_op.distr)\n  finally show ?thesis.\nqed\n\nlemma fbox_cond_var: \"fbox (if p then x else y fi) q = (do p \\<cdot> fbox x q) + (ad p \\<cdot> fbox y q)\"\n  using add_commute fbox_cond fbox_def by simp\n\nlemma fbox_while: \n  assumes \"do p \\<cdot> do t \\<le> fbox x p\"\n  shows \"do p \\<le> fbox (while t do x od) (do p \\<cdot> ad t)\"\nproof -\n  have  \"do p \\<cdot> do t \\<cdot> x \\<le> do t \\<cdot> x \\<cdot> do p\"\n    by (metis assms a_exp arka_op.mult_assoc at_shunt dom_op_def fbox_def fbox_demod)\n  hence \"do p \\<cdot> (do t \\<cdot> x)\\<^sup>\\<star> \\<cdot> ad t \\<le> (do t \\<cdot> x)\\<^sup>\\<star> \\<cdot> do p \\<cdot> ad t\"\n    by (metis arka_op.mult_assoc mult_isor star_sim1)\n  also have \"\\<dots> = (do t \\<cdot> x)\\<^sup>\\<star> \\<cdot> ad t \\<cdot> do p \\<cdot> ad t\"\n    by (metis add_commute a_dual_add add_ubl arka_op.mult_assoc dom_op_def order_def)\n  finally show ?thesis\n    using a_closed arka_op.range_op_def fbox_demod mult.semigroup_axioms semigroup.assoc while_def by fastforce\nqed\n\nlemma fbox_whilet: \"do p \\<cdot> fbox (while p do x od) q = do p \\<cdot> fbox x (fbox (while p do x od) q)\"\n  by (metis fbox_condl fbox_comp while_if)\n\nlemma fbox_whilef: \"ad p \\<cdot> fbox (while p do x od) q = ad p \\<cdot> do q\"\n  by (metis fbox_condr fbox_zero_var while_if)\n\nlemma fbox_while_inv: \n  assumes \"do p \\<le> do i\"\n  and \"do i \\<cdot> ad t \\<le> do q\"\n  and \"do i \\<cdot> do t \\<le> fbox x i\"\nshows \"do p \\<le> fbox (while t inv i do x od) q\"\n  by (unfold while_inv_def, smt assms fbox_while a_closed distl dom_op_def dual_order.trans fbox_demod order_def)\n\nend\n\n\nsubsection \\<open>Relation and State Transformer KAD\\<close>\n\ndefinition rel_ad :: \"'a rel \\<Rightarrow> 'a rel\" (\"ad\\<^sub>r\") where\n  \"rel_ad R = {(x,x) | x. \\<not>(\\<exists>y. (x,y) \\<in> R)}\" \n\ninterpretation rel_aka: antidomain_kleene_algebra \"(\\<union>)\" \"{}\" Id \"(;)\" \"(\\<subseteq>)\" \"(\\<subset>)\" rtrancl \"ad\\<^sub>r\"\n  by unfold_locales (auto simp: rel_ad_def)\n\ndefinition sta_ad :: \"'a sta \\<Rightarrow> 'a sta\" (\"ad\\<^sub>s\")where\n  \"sta_ad f x = (if f x = {} then {x} else {})\"\n\ninterpretation sta_aka: antidomain_kleene_algebra \"(+\\<^sub>K)\" \"\\<nu>\" \"\\<eta>\" \"(\\<circ>\\<^sub>K)\" \"(\\<sqsubseteq>)\" \"(\\<sqsubset>)\" kstar \"ad\\<^sub>s\"\n  apply (unfold_locales, unfold sta_iff sta_ad_def kcomp_iff kleq_iff kadd_iff)\n  by clarsimp+ (auto simp: kcomp_def)\n\nlemma rel_d_fix_subid: \"(rel_aka.dom_op R = R) = (R \\<subseteq> Id)\" \n  unfolding rel_aka.dom_op_def rel_ad_def Id_def by force\n\nlemma sta_d_fix_subid: \"(sta_aka.dom_op f = f) = (f \\<sqsubseteq> \\<eta>)\"\n  unfolding sta_iff sta_aka.dom_op_def sta_ad_def kleq_iff by force\n\n\nsubsection \\<open>Optimised Laws for VCG\\<close>\n\nabbreviation rcond :: \"'a pred \\<Rightarrow> 'a rel \\<Rightarrow> 'a rel \\<Rightarrow> 'a rel\" (\"rif _ then _ else _ fi\" [64,64,64] 63) where\n  \"rif P then R else S fi \\<equiv> rel_aka.cond \\<lceil>P\\<rceil>\\<^sub>r R S\"\n\nabbreviation rwhile :: \"'a pred \\<Rightarrow> 'a rel \\<Rightarrow> 'a rel\" (\"rwhile _ do _ od\" [64,64] 63) where\n  \"rwhile P do R od \\<equiv> rel_aka.while \\<lceil>P\\<rceil>\\<^sub>r R\"\n\nabbreviation rwhile_inv :: \"'a pred \\<Rightarrow> 'a pred \\<Rightarrow> 'a rel \\<Rightarrow> 'a rel\" (\"rwhile _ inv _ do _ od\" [64,64,64] 63) where\n  \"rwhile P inv I do R od \\<equiv> rel_aka.while_inv \\<lceil>P\\<rceil>\\<^sub>r \\<lceil>I\\<rceil>\\<^sub>r R\"\n\nabbreviation scond :: \"'a pred \\<Rightarrow> 'a sta \\<Rightarrow> 'a sta \\<Rightarrow> 'a sta\" (\"sif _ then _ else _ fi\" [64,64,64] 63) where\n  \"sif P then f else g fi \\<equiv> sta_aka.cond \\<lceil>P\\<rceil>\\<^sub>s f g\"\n\nabbreviation swhile :: \"'a pred \\<Rightarrow> 'a sta \\<Rightarrow> 'a sta\" (\"swhile _ do _ od\" [64,64] 63) where\n  \"swhile P do f od \\<equiv> sta_aka.while \\<lceil>P\\<rceil>\\<^sub>s f\"\n\nabbreviation swhile_inv :: \"'a pred \\<Rightarrow> 'a pred \\<Rightarrow> 'a sta \\<Rightarrow> 'a sta\" (\"swhile _ inv _ do _ od\" [64,64,64] 63) where\n  \"swhile P inv I do f od \\<equiv> sta_aka.while_inv \\<lceil>P\\<rceil>\\<^sub>s \\<lceil>I\\<rceil>\\<^sub>s f\"\n\nlemma rel_fbox_subid: \"rel_aka.fbox R P \\<subseteq> Id\"\n  using rel_aka.fbox_anti by force\n\nlemma sta_fbox_subid: \"sta_aka.fbox f P \\<sqsubseteq> \\<eta>\"\n  by (simp add: kleq_iff sta_ad_def sta_aka.fbox_fdia)\n\nlemma rel_dom_pred [simp]: \"rel_aka.dom_op \\<lceil>P\\<rceil>\\<^sub>r = \\<lceil>P\\<rceil>\\<^sub>r\"\n  unfolding p2r_def rel_aka.dom_op_def rel_ad_def by simp\n\nlemma rel_ad_pred [simp]: \"ad\\<^sub>r \\<lceil>P\\<rceil>\\<^sub>r = \\<lceil>\\<lambda>s. \\<not> P s\\<rceil>\\<^sub>r\"\n  unfolding p2r_def rel_ad_def by simp\n\nlemma sta_dom_pred [simp]: \"sta_aka.dom_op \\<lceil>P\\<rceil>\\<^sub>s = \\<lceil>P\\<rceil>\\<^sub>s\"\n  unfolding p2s_def sta_aka.dom_op_def sta_ad_def sta_iff by simp\n\nlemma sta_ad_pred [simp]: \"ad\\<^sub>s \\<lceil>P\\<rceil>\\<^sub>s = \\<lceil>\\<lambda>s. \\<not> P s\\<rceil>\\<^sub>s\"\n  unfolding p2s_def sta_ad_def sta_iff by simp\n\nabbreviation \"rfbox R Q \\<equiv> \\<lfloor>rel_aka.fbox R \\<lceil>Q\\<rceil>\\<^sub>r\\<rfloor>\\<^sub>r\"\n\nabbreviation \"sfbox R Q \\<equiv> \\<lfloor>sta_aka.fbox R \\<lceil>Q\\<rceil>\\<^sub>s\\<rfloor>\\<^sub>s\"\n\nlemma rfbox_p2r2p: \"rel_aka.fbox R \\<lceil>P\\<rceil>\\<^sub>r = \\<lceil>rfbox R P\\<rceil>\\<^sub>r\"\n  by (simp add: p2r2p rel_fbox_subid)\n\nlemma sfbox_p2s2p: \"sta_aka.fbox R \\<lceil>P\\<rceil>\\<^sub>s = \\<lceil>sfbox R P\\<rceil>\\<^sub>s\"\n  by (simp add: p2s2p sta_fbox_subid)\n\nlemma rfbox_unfold: \"rfbox R P s = (\\<forall>s'. (s,s') \\<in> R \\<longrightarrow> P s')\"\n  unfolding p2r_def r2p_def rel_aka.fbox_def rel_ad_def by force\n\nlemma sfbox_unfold: \"sfbox f P s = (\\<forall>s'. s' \\<in> f s \\<longrightarrow> P s')\"\n  unfolding p2s_def s2p_def sta_aka.fbox_def sta_ad_def kcomp_def by force\n\nlemma rfbox_seq [simp]: \"rfbox (R ; S) P s = rfbox R (rfbox S P) s\"\n  by (metis rel_aka.fbox_comp rfbox_p2r2p)\n\nlemma rfbox_seq_var: \n  assumes \"\\<forall>s. w s \\<longrightarrow> rfbox y z s\"\n   and \"\\<forall>s. v s \\<longrightarrow> rfbox x w s\"\n  shows \"\\<forall>s. v s \\<longrightarrow> rfbox (x ; y) z s\"\n  by (metis assms rfbox_seq rfbox_unfold)\n\nlemma sfbox_seq [simp]: \"sfbox (f \\<circ>\\<^sub>K g) P s = sfbox f (sfbox g P) s\"\n  by (metis sfbox_p2s2p sta_aka.fbox_comp)\n\nlemma sfbox_seq_var: \n  assumes \"\\<forall>s. w s \\<longrightarrow> sfbox y z s\" \n  and \"\\<forall>s. v s \\<longrightarrow> sfbox x w s\" \n  shows \"\\<forall>s. v s \\<longrightarrow> sfbox (x \\<circ>\\<^sub>K y) z s\"\n  by (metis assms sfbox_seq sfbox_unfold)\n\nlemma rfbox_cond [simp]: \"rfbox (rif P then R else S fi) Q s = ((P s \\<longrightarrow> rfbox R Q s) \\<and> (\\<not> P s \\<longrightarrow> rfbox S Q s))\"\n  by (unfold rfbox_unfold rel_aka.cond_def relcomp_unfold, simp, unfold p2r_def, force)\n\nlemma rfbox_cond_var: \"rfbox (rif P then R else S fi) Q s = ((P s \\<and> rfbox R Q s) \\<or>  (\\<not> P s \\<and> rfbox S Q s))\"\n  by (metis (no_types, hide_lams) rfbox_cond)\n\nlemma sfbox_cond [simp]: \"sfbox (sif P then f else g fi) Q s = ((P s \\<longrightarrow> sfbox f Q s) \\<and> (\\<not> P s \\<longrightarrow> sfbox g Q s))\"\n  by (unfold sfbox_unfold sta_aka.cond_def sta_iff kadd_def kcomp_iff, simp, unfold p2s_def kcomp_iff, force)\n\nlemma sfbox_cond_var: \"sfbox (sif P then f else g fi) Q s = ((P s \\<and> sfbox f Q s) \\<or>  (\\<not> P s \\<and> sfbox g Q s))\"\n  unfolding sfbox_cond fun_eq_iff by force\n\nlemma rfbox_while_inv: \n  assumes \"\\<forall>s. P s \\<longrightarrow> I s\"\n  and \"\\<forall>s. I s \\<longrightarrow> \\<not> T s \\<longrightarrow> Q s\"\n  and \"\\<forall>s. I s \\<longrightarrow> T s \\<longrightarrow> rfbox R I s\"\n  shows \"\\<forall>s. P s \\<longrightarrow> rfbox (rwhile T inv I do R od) Q s\" \nproof-\n  have a: \"\\<lceil>P\\<rceil>\\<^sub>r \\<subseteq> \\<lceil>I\\<rceil>\\<^sub>r\"\n    using assms by simp\n  have b: \"\\<lceil>I\\<rceil>\\<^sub>r ; ad\\<^sub>r \\<lceil>T\\<rceil>\\<^sub>r \\<subseteq> \\<lceil>Q\\<rceil>\\<^sub>r\"\n    by (simp add: assms(2))\n  have c: \"\\<lceil>I\\<rceil>\\<^sub>r ; \\<lceil>T\\<rceil>\\<^sub>r \\<subseteq> rel_aka.fbox R \\<lceil>I\\<rceil>\\<^sub>r\"\n    by (smt assms(3) p2r_comp p2r_imp rfbox_p2r2p)\n  hence \"rel_aka.dom_op \\<lceil>P\\<rceil>\\<^sub>r \\<subseteq> rel_aka.fbox (rel_aka.while_inv \\<lceil>T\\<rceil>\\<^sub>r \\<lceil>I\\<rceil>\\<^sub>r R) \\<lceil>Q\\<rceil>\\<^sub>r\"\n    apply (intro rel_aka.fbox_while_inv)\n    using a b by simp_all\n  thus ?thesis\n    by (smt p2r_imp rel_dom_pred rfbox_p2r2p)\nqed\n\nlemma sfbox_while_inv: \n  assumes \"\\<forall>s. P s \\<longrightarrow> I s\"\n  and \"\\<forall>s. I s \\<longrightarrow> \\<not> T s \\<longrightarrow> Q s\"\n  and \"\\<forall>s. I s \\<longrightarrow> T s \\<longrightarrow> sfbox f I s\"\n  shows \"\\<forall>s. P s \\<longrightarrow> sfbox (swhile T inv I do f od) Q s\" \nproof-\n  have a: \"\\<lceil>P\\<rceil>\\<^sub>s \\<sqsubseteq> \\<lceil>I\\<rceil>\\<^sub>s\"\n    using assms by simp\n  have b: \"\\<lceil>I\\<rceil>\\<^sub>s \\<circ>\\<^sub>K ad\\<^sub>s \\<lceil>T\\<rceil>\\<^sub>s \\<sqsubseteq> \\<lceil>Q\\<rceil>\\<^sub>s\"\n    by (simp add: assms(2))\n  have c: \"\\<lceil>I\\<rceil>\\<^sub>s \\<circ>\\<^sub>K \\<lceil>T\\<rceil>\\<^sub>s \\<sqsubseteq> sta_aka.fbox f \\<lceil>I\\<rceil>\\<^sub>s\"\n    by (smt assms(3) p2s_comp p2s_imp sfbox_p2s2p)\n  hence \"sta_aka.dom_op \\<lceil>P\\<rceil>\\<^sub>s \\<sqsubseteq> sta_aka.fbox (sta_aka.while_inv \\<lceil>T\\<rceil>\\<^sub>s \\<lceil>I\\<rceil>\\<^sub>s f) \\<lceil>Q\\<rceil>\\<^sub>s\"\n    apply (intro sta_aka.fbox_while_inv)\n    using a b by simp_all\n  thus ?thesis\n     by (smt p2s_imp sta_dom_pred sfbox_p2s2p)\n qed\n\nlemma rfbox_while_inv_break: \n  assumes \"\\<forall>s. P s \\<longrightarrow> rfbox S I s\"\n  and \"\\<forall>s. I s \\<longrightarrow> \\<not> T s \\<longrightarrow> Q s\"\n  and \"\\<forall>s. I s \\<longrightarrow>  T s \\<longrightarrow> rfbox R I s\"\n  shows \"\\<forall>s. P s \\<longrightarrow> rfbox (S ; (rwhile T inv I do R od)) Q s\"\n  apply (intro rfbox_seq_var rfbox_while_inv) \n  using assms by simp_all\n\nlemma sfbox_while_inv_break: \n  assumes \"\\<forall>s. P s \\<longrightarrow> sfbox g I s\"\n  and \"\\<forall>s. I s \\<longrightarrow> \\<not> T s \\<longrightarrow> Q s\"\n  and \"\\<forall>s. I s \\<longrightarrow>  T s \\<longrightarrow> sfbox f I s\"\n  shows \"\\<forall>s. P s \\<longrightarrow> sfbox (g \\<circ>\\<^sub>K (swhile T inv I do f od)) Q s\"\n  apply (intro sfbox_seq_var sfbox_while_inv)\n  using assms by simp_all\n\n\nsubsection \\<open>Store and Assignment Semantics\\<close>\n\ntext \\<open>We reuse the store from KAT\\<close>\n\nlemma mka_rel_assign [simp]: \"rel_aka.fbox (v :=\\<^sub>r e) \\<lceil>Q\\<rceil>\\<^sub>r = \\<lceil>\\<lambda>s. Q (set v e s)\\<rceil>\\<^sub>r\"\n  by (auto simp: rel_aka.fbox_def rel_assign_def rel_ad_def p2r_def)\n\nlemma mka_sta_assign [simp]: \"sta_aka.fbox (v :=\\<^sub>s e) \\<lceil>Q\\<rceil>\\<^sub>s = \\<lceil>\\<lambda>s. Q (set v e s)\\<rceil>\\<^sub>s\"\n  by (auto simp: sta_iff sta_aka.fbox_def sta_assign_def kcomp_def sta_ad_def p2s_def)\n\nlemma rfbox_assign [simp]: \"rfbox (v :=\\<^sub>r e) Q s = Q (set v e s)\"\n  by simp\n\nlemma sfbox_assign [simp]: \"sfbox (v :=\\<^sub>s e) Q s = Q (set v e s)\"\n  by simp\n\n\nsubsection \\<open>Examples\\<close>\n\nlemma svar_swap:\n  \"s ''x'' = m \\<and> s ''y'' = n \\<Longrightarrow>  \n    sfbox ((''z'' :=\\<^sub>s (\\<lambda>s. s ''x''))\\<circ>\\<^sub>K\n    (''x'' :=\\<^sub>s (\\<lambda>s. s ''y''))\\<circ>\\<^sub>K\n    (''y'' :=\\<^sub>s (\\<lambda>s. s ''z'')))\n   (\\<lambda>s. s ''x'' = n \\<and> s ''y'' = m) s\"\n  by simp\n\nlemma rvar_swap: \n  \"s ''x'' = m \\<and> s ''y'' = n \\<Longrightarrow> \n    rfbox ((''z'' :=\\<^sub>r (\\<lambda>s. s ''x''));\n    (''x'' :=\\<^sub>r (\\<lambda>s. s ''y''));\n    (''y'' :=\\<^sub>r (\\<lambda>s. s ''z'')))\n   (\\<lambda>s. s ''x'' = n \\<and> s ''y'' = m) s\"\n  by simp\n\nlemma rmaximum:  \n  \"\\<forall>s::int store. \n   rfbox (rif (\\<lambda>s. s ''x'' \\<ge> s ''y'') \n    then (''z'' :=\\<^sub>r (\\<lambda>s. s ''x''))\n    else (''z'' :=\\<^sub>r (\\<lambda>s. s ''y''))\n    fi)\n   (\\<lambda>s. s ''z'' = max (s ''x'') (s ''y'')) s\"\n  by force\n\nlemma smaximum:  \n  \"\\<forall>s::int store. \n   sfbox (sif (\\<lambda>s. s ''x'' \\<ge> s ''y'') \n    then (''z'' :=\\<^sub>s (\\<lambda>s. s ''x''))\n    else (''z'' :=\\<^sub>s (\\<lambda>s. s ''y''))\n    fi)\n   (\\<lambda>s. s ''z'' = max (s ''x'') (s ''y'')) s\"\n  by force\n\nlemma rinteger_division: \n\"\\<forall>s::nat store. 0 < y \\<longrightarrow>\n    rfbox ((''q'' :=\\<^sub>r (\\<lambda>s. 0)); \n    (''r'' :=\\<^sub>r (\\<lambda>s. x));\n    (rwhile (\\<lambda>s. y \\<le> s ''r'') inv (\\<lambda>s. x = s ''q'' * y + s ''r'')\n     do\n      (''q'' :=\\<^sub>r (\\<lambda>s. s ''q'' + 1)) ;\n      (''r'' :=\\<^sub>r (\\<lambda>s. s ''r'' - y))\n     od))\n  (\\<lambda>s. x = s ''q'' * y + s ''r'' \\<and> s ''r'' < y) s\"\n  by (intro rfbox_seq_var rfbox_while_inv, auto simp: imp_refl)\n(*  by (rule rfbox_while_inv_break) simp_all*)\n\nlemma sinteger_division: \n\"\\<forall>s::nat store. 0 < y \\<longrightarrow>\n    sfbox ((''q'' :=\\<^sub>s (\\<lambda>s. 0)) \\<circ>\\<^sub>K\n    (''r'' :=\\<^sub>s (\\<lambda>s. x))  \\<circ>\\<^sub>K\n    (swhile (\\<lambda>s. y \\<le> s ''r'') inv (\\<lambda>s. x = s ''q'' * y + s ''r'')\n     do\n      (''q'' :=\\<^sub>s (\\<lambda>s. s ''q'' + 1)) \\<circ>\\<^sub>K\n      (''r'' :=\\<^sub>s (\\<lambda>s. s ''r'' - y))\n     od))\n  (\\<lambda>s. x = s ''q'' * y + s ''r'' \\<and> s ''r'' < y) s\"\n  by (rule sfbox_while_inv_break) simp_all\n\nend\n\n\n\n\n", "meta": {"author": "hyleIndex", "repo": "Kleene-Algebras-From-Foundations-to-Program-Verification", "sha": "9ec491714e5925c7a6e42738ad6af17be8e70e9f", "save_path": "github-repos/isabelle/hyleIndex-Kleene-Algebras-From-Foundations-to-Program-Verification", "path": "github-repos/isabelle/hyleIndex-Kleene-Algebras-From-Foundations-to-Program-Verification/Kleene-Algebras-From-Foundations-to-Program-Verification-9ec491714e5925c7a6e42738ad6af17be8e70e9f/MKA.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.89181104831338, "lm_q2_score": 0.7956581000631541, "lm_q1q2_score": 0.7095766843163536}}
{"text": "(*  Title:      HOL/Library/Order_Continuity.thy\n    Author:     David von Oheimb, TU M\u00fcnchen\n    Author:     Johannes H\u00f6lzl, TU M\u00fcnchen\n*)\n\nsection \\<open>Continuity and iterations\\<close>\n\ntheory Order_Continuity\nimports Complex_Main Countable_Complete_Lattices\nbegin\n\n(* TODO: Generalize theory to chain-complete partial orders *)\n\nlemma SUP_nat_binary:\n  \"(sup A (SUP x\\<in>Collect ((<) (0::nat)). B)) = (sup A B::'a::countable_complete_lattice)\"\n  apply (subst image_constant)\n   apply auto\n  done\n\nlemma INF_nat_binary:\n  \"inf A (INF x\\<in>Collect ((<) (0::nat)). B) = (inf A B::'a::countable_complete_lattice)\"\n  apply (subst image_constant)\n   apply auto\n  done\n\ntext \\<open>\n  The name \\<open>continuous\\<close> is already taken in \\<open>Complex_Main\\<close>, so we use\n  \\<open>sup_continuous\\<close> and \\<open>inf_continuous\\<close>. These names appear sometimes in literature\n  and have the advantage that these names are duals.\n\\<close>\n\nnamed_theorems order_continuous_intros\n\nsubsection \\<open>Continuity for complete lattices\\<close>\n\ndefinition\n  sup_continuous :: \"('a::countable_complete_lattice \\<Rightarrow> 'b::countable_complete_lattice) \\<Rightarrow> bool\"\nwhere\n  \"sup_continuous F \\<longleftrightarrow> (\\<forall>M::nat \\<Rightarrow> 'a. mono M \\<longrightarrow> F (SUP i. M i) = (SUP i. F (M i)))\"\n\nlemma sup_continuousD: \"sup_continuous F \\<Longrightarrow> mono M \\<Longrightarrow> F (SUP i::nat. M i) = (SUP i. F (M i))\"\n  by (auto simp: sup_continuous_def)\n\nlemma sup_continuous_mono:\n  \"mono F\" if \"sup_continuous F\"\nproof\n  fix A B :: \"'a\"\n  assume \"A \\<le> B\"\n  let ?f = \"\\<lambda>n::nat. if n = 0 then A else B\"\n  from \\<open>A \\<le> B\\<close> have \"incseq ?f\"\n    by (auto intro: monoI)\n  with \\<open>sup_continuous F\\<close> have *: \"F (SUP i. ?f i) = (SUP i. F (?f i))\"\n    by (auto dest: sup_continuousD)\n  from \\<open>A \\<le> B\\<close> have \"B = sup A B\"\n    by (simp add: le_iff_sup)\n  then have \"F B = F (sup A B)\"\n    by simp\n  also have \"\\<dots> = sup (F A) (F B)\"\n    using * by (simp add: if_distrib SUP_nat_binary cong del: SUP_cong)\n  finally show \"F A \\<le> F B\"\n    by (simp add: le_iff_sup)\nqed\n\nlemma [order_continuous_intros]:\n  shows sup_continuous_const: \"sup_continuous (\\<lambda>x. c)\"\n    and sup_continuous_id: \"sup_continuous (\\<lambda>x. x)\"\n    and sup_continuous_apply: \"sup_continuous (\\<lambda>f. f x)\"\n    and sup_continuous_fun: \"(\\<And>s. sup_continuous (\\<lambda>x. P x s)) \\<Longrightarrow> sup_continuous P\"\n    and sup_continuous_If: \"sup_continuous F \\<Longrightarrow> sup_continuous G \\<Longrightarrow> sup_continuous (\\<lambda>f. if C then F f else G f)\"\n  by (auto simp: sup_continuous_def image_comp)\n\nlemma sup_continuous_compose:\n  assumes f: \"sup_continuous f\" and g: \"sup_continuous g\"\n  shows \"sup_continuous (\\<lambda>x. f (g x))\"\n  unfolding sup_continuous_def\nproof safe\n  fix M :: \"nat \\<Rightarrow> 'c\"\n  assume M: \"mono M\"\n  then have \"mono (\\<lambda>i. g (M i))\"\n    using sup_continuous_mono[OF g] by (auto simp: mono_def)\n  with M show \"f (g (Sup (M ` UNIV))) = (SUP i. f (g (M i)))\"\n    by (auto simp: sup_continuous_def g[THEN sup_continuousD] f[THEN sup_continuousD])\nqed\n\nlemma sup_continuous_sup[order_continuous_intros]:\n  \"sup_continuous f \\<Longrightarrow> sup_continuous g \\<Longrightarrow> sup_continuous (\\<lambda>x. sup (f x) (g x))\"\n  by (simp add: sup_continuous_def ccSUP_sup_distrib)\n\nlemma sup_continuous_inf[order_continuous_intros]:\n  fixes P Q :: \"'a :: countable_complete_lattice \\<Rightarrow> 'b :: countable_complete_distrib_lattice\"\n  assumes P: \"sup_continuous P\" and Q: \"sup_continuous Q\"\n  shows \"sup_continuous (\\<lambda>x. inf (P x) (Q x))\"\n  unfolding sup_continuous_def\nproof (safe intro!: antisym)\n  fix M :: \"nat \\<Rightarrow> 'a\" assume M: \"incseq M\"\n  have \"inf (P (SUP i. M i)) (Q (SUP i. M i)) \\<le> (SUP j i. inf (P (M i)) (Q (M j)))\"\n    by (simp add: sup_continuousD[OF P M] sup_continuousD[OF Q M] inf_ccSUP ccSUP_inf)\n  also have \"\\<dots> \\<le> (SUP i. inf (P (M i)) (Q (M i)))\"\n  proof (intro ccSUP_least)\n    fix i j from M assms[THEN sup_continuous_mono] show \"inf (P (M i)) (Q (M j)) \\<le> (SUP i. inf (P (M i)) (Q (M i)))\"\n      by (intro ccSUP_upper2[of _ \"sup i j\"] inf_mono) (auto simp: mono_def)\n  qed auto\n  finally show \"inf (P (SUP i. M i)) (Q (SUP i. M i)) \\<le> (SUP i. inf (P (M i)) (Q (M i)))\" .\n\n  show \"(SUP i. inf (P (M i)) (Q (M i))) \\<le> inf (P (SUP i. M i)) (Q (SUP i. M i))\"\n    unfolding sup_continuousD[OF P M] sup_continuousD[OF Q M] by (intro ccSUP_least inf_mono ccSUP_upper) auto\nqed\n\nlemma sup_continuous_and[order_continuous_intros]:\n  \"sup_continuous P \\<Longrightarrow> sup_continuous Q \\<Longrightarrow> sup_continuous (\\<lambda>x. P x \\<and> Q x)\"\n  using sup_continuous_inf[of P Q] by simp\n\nlemma sup_continuous_or[order_continuous_intros]:\n  \"sup_continuous P \\<Longrightarrow> sup_continuous Q \\<Longrightarrow> sup_continuous (\\<lambda>x. P x \\<or> Q x)\"\n  by (auto simp: sup_continuous_def)\n\nlemma sup_continuous_lfp:\n  assumes \"sup_continuous F\" shows \"lfp F = (SUP i. (F ^^ i) bot)\" (is \"lfp F = ?U\")\nproof (rule antisym)\n  note mono = sup_continuous_mono[OF \\<open>sup_continuous F\\<close>]\n  show \"?U \\<le> lfp F\"\n  proof (rule SUP_least)\n    fix i show \"(F ^^ i) bot \\<le> lfp F\"\n    proof (induct i)\n      case (Suc i)\n      have \"(F ^^ Suc i) bot = F ((F ^^ i) bot)\" by simp\n      also have \"\\<dots> \\<le> F (lfp F)\" by (rule monoD[OF mono Suc])\n      also have \"\\<dots> = lfp F\" by (simp add: lfp_fixpoint[OF mono])\n      finally show ?case .\n    qed simp\n  qed\n  show \"lfp F \\<le> ?U\"\n  proof (rule lfp_lowerbound)\n    have \"mono (\\<lambda>i::nat. (F ^^ i) bot)\"\n    proof -\n      { fix i::nat have \"(F ^^ i) bot \\<le> (F ^^ (Suc i)) bot\"\n        proof (induct i)\n          case 0 show ?case by simp\n        next\n          case Suc thus ?case using monoD[OF mono Suc] by auto\n        qed }\n      thus ?thesis by (auto simp add: mono_iff_le_Suc)\n    qed\n    hence \"F ?U = (SUP i. (F ^^ Suc i) bot)\"\n      using \\<open>sup_continuous F\\<close> by (simp add: sup_continuous_def)\n    also have \"\\<dots> \\<le> ?U\"\n      by (fast intro: SUP_least SUP_upper)\n    finally show \"F ?U \\<le> ?U\" .\n  qed\nqed\n\nlemma lfp_transfer_bounded:\n  assumes P: \"P bot\" \"\\<And>x. P x \\<Longrightarrow> P (f x)\" \"\\<And>M. (\\<And>i. P (M i)) \\<Longrightarrow> P (SUP i::nat. M i)\"\n  assumes \\<alpha>: \"\\<And>M. mono M \\<Longrightarrow> (\\<And>i::nat. P (M i)) \\<Longrightarrow> \\<alpha> (SUP i. M i) = (SUP i. \\<alpha> (M i))\"\n  assumes f: \"sup_continuous f\" and g: \"sup_continuous g\"\n  assumes [simp]: \"\\<And>x. P x \\<Longrightarrow> x \\<le> lfp f \\<Longrightarrow> \\<alpha> (f x) = g (\\<alpha> x)\"\n  assumes g_bound: \"\\<And>x. \\<alpha> bot \\<le> g x\"\n  shows \"\\<alpha> (lfp f) = lfp g\"\nproof (rule antisym)\n  note mono_g = sup_continuous_mono[OF g]\n  note mono_f = sup_continuous_mono[OF f]\n  have lfp_bound: \"\\<alpha> bot \\<le> lfp g\"\n    by (subst lfp_unfold[OF mono_g]) (rule g_bound)\n\n  have P_pow: \"P ((f ^^ i) bot)\" for i\n    by (induction i) (auto intro!: P)\n  have incseq_pow: \"mono (\\<lambda>i. (f ^^ i) bot)\"\n    unfolding mono_iff_le_Suc\n  proof\n    fix i show \"(f ^^ i) bot \\<le> (f ^^ (Suc i)) bot\"\n    proof (induct i)\n      case Suc thus ?case using monoD[OF sup_continuous_mono[OF f] Suc] by auto\n    qed (simp add: le_fun_def)\n  qed\n  have P_lfp: \"P (lfp f)\"\n    using P_pow unfolding sup_continuous_lfp[OF f] by (auto intro!: P)\n\n  have iter_le_lfp: \"(f ^^ n) bot \\<le> lfp f\" for n\n    apply (induction n)\n    apply simp\n    apply (subst lfp_unfold[OF mono_f])\n    apply (auto intro!: monoD[OF mono_f])\n    done\n\n  have \"\\<alpha> (lfp f) = (SUP i. \\<alpha> ((f^^i) bot))\"\n    unfolding sup_continuous_lfp[OF f] using incseq_pow P_pow by (rule \\<alpha>)\n  also have \"\\<dots> \\<le> lfp g\"\n  proof (rule SUP_least)\n    fix i show \"\\<alpha> ((f^^i) bot) \\<le> lfp g\"\n    proof (induction i)\n      case (Suc n) then show ?case\n        by (subst lfp_unfold[OF mono_g]) (simp add: monoD[OF mono_g] P_pow iter_le_lfp)\n    qed (simp add: lfp_bound)\n  qed\n  finally show \"\\<alpha> (lfp f) \\<le> lfp g\" .\n\n  show \"lfp g \\<le> \\<alpha> (lfp f)\"\n  proof (induction rule: lfp_ordinal_induct[OF mono_g])\n    case (1 S) then show ?case\n      by (subst lfp_unfold[OF sup_continuous_mono[OF f]])\n         (simp add: monoD[OF mono_g] P_lfp)\n  qed (auto intro: Sup_least)\nqed\n\nlemma lfp_transfer:\n  \"sup_continuous \\<alpha> \\<Longrightarrow> sup_continuous f \\<Longrightarrow> sup_continuous g \\<Longrightarrow>\n    (\\<And>x. \\<alpha> bot \\<le> g x) \\<Longrightarrow> (\\<And>x. x \\<le> lfp f \\<Longrightarrow> \\<alpha> (f x) = g (\\<alpha> x)) \\<Longrightarrow> \\<alpha> (lfp f) = lfp g\"\n  by (rule lfp_transfer_bounded[where P=top]) (auto dest: sup_continuousD)\n\ndefinition\n  inf_continuous :: \"('a::countable_complete_lattice \\<Rightarrow> 'b::countable_complete_lattice) \\<Rightarrow> bool\"\nwhere\n  \"inf_continuous F \\<longleftrightarrow> (\\<forall>M::nat \\<Rightarrow> 'a. antimono M \\<longrightarrow> F (INF i. M i) = (INF i. F (M i)))\"\n\nlemma inf_continuousD: \"inf_continuous F \\<Longrightarrow> antimono M \\<Longrightarrow> F (INF i::nat. M i) = (INF i. F (M i))\"\n  by (auto simp: inf_continuous_def)\n\nlemma inf_continuous_mono:\n  \"mono F\" if \"inf_continuous F\"\nproof\n  fix A B :: \"'a\"\n  assume \"A \\<le> B\"\n  let ?f = \"\\<lambda>n::nat. if n = 0 then B else A\"\n  from \\<open>A \\<le> B\\<close> have \"decseq ?f\"\n    by (auto intro: antimonoI)\n  with \\<open>inf_continuous F\\<close> have *: \"F (INF i. ?f i) = (INF i. F (?f i))\"\n    by (auto dest: inf_continuousD)\n  from \\<open>A \\<le> B\\<close> have \"A = inf B A\"\n    by (simp add: inf.absorb_iff2)\n  then have \"F A = F (inf B A)\"\n    by simp\n  also have \"\\<dots> = inf (F B) (F A)\"\n    using * by (simp add: if_distrib INF_nat_binary cong del: INF_cong)\n  finally show \"F A \\<le> F B\"\n    by (simp add: inf.absorb_iff2)\nqed\n\nlemma [order_continuous_intros]:\n  shows inf_continuous_const: \"inf_continuous (\\<lambda>x. c)\"\n    and inf_continuous_id: \"inf_continuous (\\<lambda>x. x)\"\n    and inf_continuous_apply: \"inf_continuous (\\<lambda>f. f x)\"\n    and inf_continuous_fun: \"(\\<And>s. inf_continuous (\\<lambda>x. P x s)) \\<Longrightarrow> inf_continuous P\"\n    and inf_continuous_If: \"inf_continuous F \\<Longrightarrow> inf_continuous G \\<Longrightarrow> inf_continuous (\\<lambda>f. if C then F f else G f)\"\n  by (auto simp: inf_continuous_def image_comp)\n\nlemma inf_continuous_inf[order_continuous_intros]:\n  \"inf_continuous f \\<Longrightarrow> inf_continuous g \\<Longrightarrow> inf_continuous (\\<lambda>x. inf (f x) (g x))\"\n  by (simp add: inf_continuous_def ccINF_inf_distrib)\n\nlemma inf_continuous_sup[order_continuous_intros]:\n  fixes P Q :: \"'a :: countable_complete_lattice \\<Rightarrow> 'b :: countable_complete_distrib_lattice\"\n  assumes P: \"inf_continuous P\" and Q: \"inf_continuous Q\"\n  shows \"inf_continuous (\\<lambda>x. sup (P x) (Q x))\"\n  unfolding inf_continuous_def\nproof (safe intro!: antisym)\n  fix M :: \"nat \\<Rightarrow> 'a\" assume M: \"decseq M\"\n  show \"sup (P (INF i. M i)) (Q (INF i. M i)) \\<le> (INF i. sup (P (M i)) (Q (M i)))\"\n    unfolding inf_continuousD[OF P M] inf_continuousD[OF Q M] by (intro ccINF_greatest sup_mono ccINF_lower) auto\n\n  have \"(INF i. sup (P (M i)) (Q (M i))) \\<le> (INF j i. sup (P (M i)) (Q (M j)))\"\n  proof (intro ccINF_greatest)\n    fix i j from M assms[THEN inf_continuous_mono] show \"sup (P (M i)) (Q (M j)) \\<ge> (INF i. sup (P (M i)) (Q (M i)))\"\n      by (intro ccINF_lower2[of _ \"sup i j\"] sup_mono) (auto simp: mono_def antimono_def)\n  qed auto\n  also have \"\\<dots> \\<le> sup (P (INF i. M i)) (Q (INF i. M i))\"\n    by (simp add: inf_continuousD[OF P M] inf_continuousD[OF Q M] ccINF_sup sup_ccINF)\n  finally show \"sup (P (INF i. M i)) (Q (INF i. M i)) \\<ge> (INF i. sup (P (M i)) (Q (M i)))\" .\nqed\n\nlemma inf_continuous_and[order_continuous_intros]:\n  \"inf_continuous P \\<Longrightarrow> inf_continuous Q \\<Longrightarrow> inf_continuous (\\<lambda>x. P x \\<and> Q x)\"\n  using inf_continuous_inf[of P Q] by simp\n\nlemma inf_continuous_or[order_continuous_intros]:\n  \"inf_continuous P \\<Longrightarrow> inf_continuous Q \\<Longrightarrow> inf_continuous (\\<lambda>x. P x \\<or> Q x)\"\n  using inf_continuous_sup[of P Q] by simp\n\nlemma inf_continuous_compose:\n  assumes f: \"inf_continuous f\" and g: \"inf_continuous g\"\n  shows \"inf_continuous (\\<lambda>x. f (g x))\"\n  unfolding inf_continuous_def\nproof safe\n  fix M :: \"nat \\<Rightarrow> 'c\"\n  assume M: \"antimono M\"\n  then have \"antimono (\\<lambda>i. g (M i))\"\n    using inf_continuous_mono[OF g] by (auto simp: mono_def antimono_def)\n  with M show \"f (g (Inf (M ` UNIV))) = (INF i. f (g (M i)))\"\n    by (auto simp: inf_continuous_def g[THEN inf_continuousD] f[THEN inf_continuousD])\nqed\n\nlemma inf_continuous_gfp:\n  assumes \"inf_continuous F\" shows \"gfp F = (INF i. (F ^^ i) top)\" (is \"gfp F = ?U\")\nproof (rule antisym)\n  note mono = inf_continuous_mono[OF \\<open>inf_continuous F\\<close>]\n  show \"gfp F \\<le> ?U\"\n  proof (rule INF_greatest)\n    fix i show \"gfp F \\<le> (F ^^ i) top\"\n    proof (induct i)\n      case (Suc i)\n      have \"gfp F = F (gfp F)\" by (simp add: gfp_fixpoint[OF mono])\n      also have \"\\<dots> \\<le> F ((F ^^ i) top)\" by (rule monoD[OF mono Suc])\n      also have \"\\<dots> = (F ^^ Suc i) top\" by simp\n      finally show ?case .\n    qed simp\n  qed\n  show \"?U \\<le> gfp F\"\n  proof (rule gfp_upperbound)\n    have *: \"antimono (\\<lambda>i::nat. (F ^^ i) top)\"\n    proof -\n      { fix i::nat have \"(F ^^ Suc i) top \\<le> (F ^^ i) top\"\n        proof (induct i)\n          case 0 show ?case by simp\n        next\n          case Suc thus ?case using monoD[OF mono Suc] by auto\n        qed }\n      thus ?thesis by (auto simp add: antimono_iff_le_Suc)\n    qed\n    have \"?U \\<le> (INF i. (F ^^ Suc i) top)\"\n      by (fast intro: INF_greatest INF_lower)\n    also have \"\\<dots> \\<le> F ?U\"\n      by (simp add: inf_continuousD \\<open>inf_continuous F\\<close> *)\n    finally show \"?U \\<le> F ?U\" .\n  qed\nqed\n\nlemma gfp_transfer:\n  assumes \\<alpha>: \"inf_continuous \\<alpha>\" and f: \"inf_continuous f\" and g: \"inf_continuous g\"\n  assumes [simp]: \"\\<alpha> top = top\" \"\\<And>x. \\<alpha> (f x) = g (\\<alpha> x)\"\n  shows \"\\<alpha> (gfp f) = gfp g\"\nproof -\n  have \"\\<alpha> (gfp f) = (INF i. \\<alpha> ((f^^i) top))\"\n    unfolding inf_continuous_gfp[OF f] by (intro f \\<alpha> inf_continuousD antimono_funpow inf_continuous_mono)\n  moreover have \"\\<alpha> ((f^^i) top) = (g^^i) top\" for i\n    by (induction i; simp)\n  ultimately show ?thesis\n    unfolding inf_continuous_gfp[OF g] by simp\nqed\n\nlemma gfp_transfer_bounded:\n  assumes P: \"P (f top)\" \"\\<And>x. P x \\<Longrightarrow> P (f x)\" \"\\<And>M. antimono M \\<Longrightarrow> (\\<And>i. P (M i)) \\<Longrightarrow> P (INF i::nat. M i)\"\n  assumes \\<alpha>: \"\\<And>M. antimono M \\<Longrightarrow> (\\<And>i::nat. P (M i)) \\<Longrightarrow> \\<alpha> (INF i. M i) = (INF i. \\<alpha> (M i))\"\n  assumes f: \"inf_continuous f\" and g: \"inf_continuous g\"\n  assumes [simp]: \"\\<And>x. P x \\<Longrightarrow> \\<alpha> (f x) = g (\\<alpha> x)\"\n  assumes g_bound: \"\\<And>x. g x \\<le> \\<alpha> (f top)\"\n  shows \"\\<alpha> (gfp f) = gfp g\"\nproof (rule antisym)\n  note mono_g = inf_continuous_mono[OF g]\n\n  have P_pow: \"P ((f ^^ i) (f top))\" for i\n    by (induction i) (auto intro!: P)\n\n  have antimono_pow: \"antimono (\\<lambda>i. (f ^^ i) top)\"\n    unfolding antimono_iff_le_Suc\n  proof\n    fix i show \"(f ^^ Suc i) top \\<le> (f ^^ i) top\"\n    proof (induct i)\n      case Suc thus ?case using monoD[OF inf_continuous_mono[OF f] Suc] by auto\n    qed (simp add: le_fun_def)\n  qed\n  have antimono_pow2: \"antimono (\\<lambda>i. (f ^^ i) (f top))\"\n  proof\n    show \"x \\<le> y \\<Longrightarrow> (f ^^ y) (f top) \\<le> (f ^^ x) (f top)\" for x y\n      using antimono_pow[THEN antimonoD, of \"Suc x\" \"Suc y\"]\n      unfolding funpow_Suc_right by simp\n  qed\n\n  have gfp_f: \"gfp f = (INF i. (f ^^ i) (f top))\"\n    unfolding inf_continuous_gfp[OF f]\n  proof (rule INF_eq)\n    show \"\\<exists>j\\<in>UNIV. (f ^^ j) (f top) \\<le> (f ^^ i) top\" for i\n      by (intro bexI[of _ \"i - 1\"]) (auto simp: diff_Suc funpow_Suc_right simp del: funpow.simps(2) split: nat.split)\n    show \"\\<exists>j\\<in>UNIV. (f ^^ j) top \\<le> (f ^^ i) (f top)\" for i\n      by (intro bexI[of _ \"Suc i\"]) (auto simp: funpow_Suc_right simp del: funpow.simps(2))\n  qed\n\n  have P_lfp: \"P (gfp f)\"\n    unfolding gfp_f by (auto intro!: P P_pow antimono_pow2)\n\n  have \"\\<alpha> (gfp f) = (INF i. \\<alpha> ((f^^i) (f top)))\"\n    unfolding gfp_f by (rule \\<alpha>) (auto intro!: P_pow antimono_pow2)\n  also have \"\\<dots> \\<ge> gfp g\"\n  proof (rule INF_greatest)\n    fix i show \"gfp g \\<le> \\<alpha> ((f^^i) (f top))\"\n    proof (induction i)\n      case (Suc n) then show ?case\n        by (subst gfp_unfold[OF mono_g]) (simp add: monoD[OF mono_g] P_pow)\n    next\n      case 0\n      have \"gfp g \\<le> \\<alpha> (f top)\"\n        by (subst gfp_unfold[OF mono_g]) (rule g_bound)\n      then show ?case\n        by simp\n    qed\n  qed\n  finally show \"gfp g \\<le> \\<alpha> (gfp f)\" .\n\n  show \"\\<alpha> (gfp f) \\<le> gfp g\"\n  proof (induction rule: gfp_ordinal_induct[OF mono_g])\n    case (1 S) then show ?case\n      by (subst gfp_unfold[OF inf_continuous_mono[OF f]])\n         (simp add: monoD[OF mono_g] P_lfp)\n  qed (auto intro: Inf_greatest)\nqed\n\nsubsubsection \\<open>Least fixed points in countable complete lattices\\<close>\n\ndefinition (in countable_complete_lattice) cclfp :: \"('a \\<Rightarrow> 'a) \\<Rightarrow> 'a\"\n  where \"cclfp f = (SUP i. (f ^^ i) bot)\"\n\nlemma cclfp_unfold:\n  assumes \"sup_continuous F\" shows \"cclfp F = F (cclfp F)\"\nproof -\n  have \"cclfp F = (SUP i. F ((F ^^ i) bot))\"\n    unfolding cclfp_def\n    by (subst UNIV_nat_eq) (simp add: image_comp)\n  also have \"\\<dots> = F (cclfp F)\"\n    unfolding cclfp_def\n    by (intro sup_continuousD[symmetric] assms mono_funpow sup_continuous_mono)\n  finally show ?thesis .\nqed\n\nlemma cclfp_lowerbound: assumes f: \"mono f\" and A: \"f A \\<le> A\" shows \"cclfp f \\<le> A\"\n  unfolding cclfp_def\nproof (intro ccSUP_least)\n  fix i show \"(f ^^ i) bot \\<le> A\"\n  proof (induction i)\n    case (Suc i) from monoD[OF f this] A show ?case\n      by auto\n  qed simp\nqed simp\n\nlemma cclfp_transfer:\n  assumes \"sup_continuous \\<alpha>\" \"mono f\"\n  assumes \"\\<alpha> bot = bot\" \"\\<And>x. \\<alpha> (f x) = g (\\<alpha> x)\"\n  shows \"\\<alpha> (cclfp f) = cclfp g\"\nproof -\n  have \"\\<alpha> (cclfp f) = (SUP i. \\<alpha> ((f ^^ i) bot))\"\n    unfolding cclfp_def by (intro sup_continuousD assms mono_funpow sup_continuous_mono)\n  moreover have \"\\<alpha> ((f ^^ i) bot) = (g ^^ i) bot\" for i\n    by (induction i) (simp_all add: assms)\n  ultimately show ?thesis\n    by (simp add: cclfp_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/Order_Continuity.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8558511616741041, "lm_q2_score": 0.8289388104343892, "lm_q1q2_score": 0.709448243867022}}
{"text": "(* Author: Amine Chaieb, TU Muenchen *)\n\nsection{*Fundamental Theorem of Algebra*}\n\ntheory Fundamental_Theorem_Algebra\nimports Polynomial Complex_Main\nbegin\n\nsubsection {* More lemmas about module of complex numbers *}\n\ntext{* The triangle inequality for cmod *}\nlemma complex_mod_triangle_sub: \"cmod w \\<le> cmod (w + z) + norm z\"\n  using complex_mod_triangle_ineq2[of \"w + z\" \"-z\"] by auto\n\nsubsection {* Basic lemmas about polynomials *}\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  {\n    fix z :: 'a\n    assume H: \"norm z \\<le> r\"\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> norm c + r * m\"\n      using mult_mono[OF H th rp norm_ge_zero[of \"poly cs z\"]]\n      by (simp add: norm_mult)\n    also have \"\\<dots> \\<le> ?k\"\n      by simp\n    finally have \"norm (poly (pCons c cs) z) \\<le> ?k\" .\n  }\n  with kp show ?case by blast\nqed\n\n\ntext{* Offsetting the variable in a polynomial gives another of same degree *}\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: \"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  apply (induct p)\n  apply (simp add: offset_poly_0)\n  apply (simp add: offset_poly_pCons algebra_simps)\n  done\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: \"offset_poly p h = 0 \\<longleftrightarrow> p = 0\"\n  apply (safe intro!: offset_poly_0)\n  apply (induct p)\n  apply simp\n  apply (simp add: offset_poly_pCons)\n  apply (frule offset_poly_eq_0_lemma, simp)\n  done\n\nlemma degree_offset_poly: \"degree (offset_poly p h) = degree p\"\n  apply (induct p)\n  apply (simp add: offset_poly_0)\n  apply (case_tac \"p = 0\")\n  apply (simp add: offset_poly_0 offset_poly_pCons)\n  apply (simp add: offset_poly_pCons)\n  apply (subst degree_add_eq_right)\n  apply (rule le_less_trans [OF degree_smult_le])\n  apply (simp add: offset_poly_eq_0_iff)\n  apply (simp add: offset_poly_eq_0_iff)\n  done\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))\"\nproof (intro exI conjI)\n  show \"psize (offset_poly p a) = psize p\"\n    unfolding psize_def\n    by (simp add: offset_poly_eq_0_iff degree_offset_poly)\n  show \"\\<forall>x. poly (offset_poly p a) x = poly p (a + x)\"\n    by (simp add: poly_offset_poly)\nqed\n\ntext{* An alternative useful formulation of completeness of the reals *}\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\nsubsection {* Fundamental theorem of algebra *}\nlemma  unimodular_reduce_norm:\n  assumes md: \"cmod z = 1\"\n  shows \"cmod (z + 1) < 1 \\<or> cmod (z - 1) < 1 \\<or> cmod (z + ii) < 1 \\<or> cmod (z - ii) < 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  {\n    assume C: \"cmod (z + 1) \\<ge> 1\" \"cmod (z - 1) \\<ge> 1\" \"cmod (z + ii) \\<ge> 1\" \"cmod (z - ii) \\<ge> 1\"\n    from C 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 \"abs (2 * x) \\<le> 1\" \"abs (2 * y) \\<le> 1\"\n      by simp_all\n    then have \"(abs (2 * x))\\<^sup>2 \\<le> 1\\<^sup>2\" \"(abs (2 * y))\\<^sup>2 \\<le> 1\\<^sup>2\"\n      by - (rule power_mono, simp, simp)+\n    then have th0: \"4 * x\\<^sup>2 \\<le> 1\" \"4 * y\\<^sup>2 \\<le> 1\"\n      by (simp_all add: power_mult_distrib)\n    from add_mono[OF th0] xy have False by simp\n  }\n  then show ?thesis\n    unfolding linorder_not_le[symmetric] by blast\nqed\n\ntext{* Hence we can always reduce modulus of @{text \"1 + b z^n\"} if nonzero *}\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  {\n    assume e: \"even n\"\n    then have \"\\<exists>m. n = 2 * m\"\n      by presburger\n    then obtain m where m: \"n = 2 * m\"\n      by blast\n    from n m have \"m \\<noteq> 0\" \"m < n\"\n      by presburger+\n    with IH[rule_format, of m] 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 power2_csqrt)\n    then have \"\\<exists>z. ?P z n\" ..\n  }\n  moreover\n  {\n    assume o: \"odd n\"\n    have th0: \"cmod (complex_of_real (cmod b) / b) = 1\"\n      using b by (simp add: norm_divide)\n    from o have \"\\<exists>m. n = Suc (2 * m)\"\n      by presburger+\n    then obtain m where m: \"n = Suc (2 * m)\"\n      by blast\n    from unimodular_reduce_norm[OF th0] o\n    have \"\\<exists>v. cmod (complex_of_real (cmod b) / b + v^n) < 1\"\n      apply (cases \"cmod (complex_of_real (cmod b) / b + 1) < 1\")\n      apply (rule_tac x=\"1\" in exI)\n      apply simp\n      apply (cases \"cmod (complex_of_real (cmod b) / b - 1) < 1\")\n      apply (rule_tac x=\"-1\" in exI)\n      apply simp\n      apply (cases \"cmod (complex_of_real (cmod b) / b + ii) < 1\")\n      apply (cases \"even m\")\n      apply (rule_tac x=\"ii\" in exI)\n      apply (simp add: m power_mult)\n      apply (rule_tac x=\"- ii\" in exI)\n      apply (simp add: m power_mult)\n      apply (cases \"even m\")\n      apply (rule_tac x=\"- ii\" in exI)\n      apply (simp add: m power_mult)\n      apply (auto simp add: m power_mult)\n      apply (rule_tac x=\"ii\" in exI)\n      apply (auto simp add: m power_mult)\n      done\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 o, of \"cmod b\"]\n    have th1: \"?w ^ n = v^n / complex_of_real (cmod b)\"\n      by (simp add: power_divide of_real_power[symmetric])\n    have th2:\"cmod (complex_of_real (cmod b) / b) = 1\"\n      using b by (simp add: norm_divide)\n    then have th3: \"cmod (complex_of_real (cmod b) / b) \\<ge> 0\"\n      by simp\n    have th4: \"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: th2)\n      done\n    from mult_less_imp_less_left[OF th4 th3]\n    have \"?P ?w n\" unfolding th1 .\n    then have \"\\<exists>z. ?P z n\" ..\n  }\n  ultimately show \"\\<exists>z. ?P z n\" by blast\nqed\n\ntext{* Bolzano-Weierstrass type property for closed disc in complex plane. *}\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. subseq f \\<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: \"subseq 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: \"subseq g\" \"monoseq (\\<lambda>n. Im (s (f (g n))))\"\n    unfolding o_def by blast\n  let ?h = \"f \\<circ> g\"\n  from r[rule_format, of 0] have rp: \"r \\<ge> 0\"\n    using norm_ge_zero[of \"s 0\"] by arith\n  have th: \"\\<forall>n. r + 1 \\<ge> \\<bar>Re (s n)\\<bar>\"\n  proof\n    fix n\n    from abs_Re_le_cmod[of \"s n\"] r[rule_format, of n]\n    show \"\\<bar>Re (s n)\\<bar> \\<le> r + 1\" by arith\n  qed\n  have conv1: \"convergent (\\<lambda>n. Re (s (f n)))\"\n    apply (rule Bseq_monoseq_convergent)\n    apply (simp add: Bseq_def)\n    apply (metis gt_ex le_less_linear less_trans order.trans th)\n    apply (rule f(2))\n    done\n  have th: \"\\<forall>n. r + 1 \\<ge> \\<bar>Im (s n)\\<bar>\"\n  proof\n    fix n\n    from abs_Im_le_cmod[of \"s n\"] r[rule_format, of n]\n    show \"\\<bar>Im (s n)\\<bar> \\<le> r + 1\"\n      by arith\n  qed\n\n  have conv2: \"convergent (\\<lambda>n. Im (s (f (g n))))\"\n    apply (rule Bseq_monoseq_convergent)\n    apply (simp add: Bseq_def)\n    apply (metis gt_ex le_less_linear less_trans order.trans th)\n    apply (rule g(2))\n    done\n\n  from conv1[unfolded convergent_def] obtain x where \"LIMSEQ (\\<lambda>n. Re (s (f n))) x\"\n    by blast\n  then have x: \"\\<forall>r>0. \\<exists>n0. \\<forall>n\\<ge>n0. \\<bar>Re (s (f n)) - x\\<bar> < r\"\n    unfolding LIMSEQ_iff real_norm_def .\n\n  from conv2[unfolded convergent_def] obtain y where \"LIMSEQ (\\<lambda>n. Im (s (f (g n)))) y\"\n    by blast\n  then have y: \"\\<forall>r>0. \\<exists>n0. \\<forall>n\\<ge>n0. \\<bar>Im (s (f (g n))) - y\\<bar> < r\"\n    unfolding LIMSEQ_iff real_norm_def .\n  let ?w = \"Complex x y\"\n  from f(1) g(1) have hs: \"subseq ?h\"\n    unfolding subseq_def by auto\n  {\n    fix e :: real\n    assume ep: \"e > 0\"\n    then have e2: \"e/2 > 0\"\n      by simp\n    from x[rule_format, OF e2] y[rule_format, OF 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    {\n      fix n\n      assume nN12: \"n \\<ge> N1 + N2\"\n      then have nN1: \"g n \\<ge> N1\" and nN2: \"n \\<ge> N2\"\n        using seq_suble[OF g(1), of n] by arith+\n      from add_strict_mono[OF N1[rule_format, OF nN1] N2[rule_format, OF nN2]]\n      have \"cmod (s (?h n) - ?w) < e\"\n        using metric_bound_lemma[of \"s (f (g n))\" ?w] by simp\n    }\n    then have \"\\<exists>N. \\<forall>n\\<ge>N. cmod (s (?h n) - ?w) < e\"\n      by blast\n  }\n  with hs show ?thesis by blast\nqed\n\ntext{* Polynomial is continuous. *}\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 q: \"degree q = degree p\" \"\\<And>x. poly q x = poly p (z + x)\"\n  proof\n    show \"degree (offset_poly p z) = degree p\"\n      by (rule degree_offset_poly)\n    show \"\\<And>x. poly (offset_poly p z) x = poly p (z + x)\"\n      by (rule poly_offset_poly)\n  qed\n  have th: \"\\<And>w. poly q (w - z) = poly p w\"\n    using q(2)[of \"w - z\" for w] by simp\n  show ?thesis unfolding th[symmetric]\n  proof (induct q)\n    case 0\n    then show ?case\n      using ep by auto\n  next\n    case (pCons c cs)\n    from poly_bound_exists[of 1 \"cs\"]\n    obtain m where m: \"m > 0\" \"\\<And>z. norm z \\<le> 1 \\<Longrightarrow> norm (poly cs z) \\<le> m\"\n      by blast\n    from ep m(1) have em0: \"e/m > 0\"\n      by (simp add: field_simps)\n    have one0: \"1 > (0::real)\"\n      by arith\n    from real_lbound_gt_zero[OF one0 em0]\n    obtain d where d: \"d > 0\" \"d < 1\" \"d < e / m\"\n      by blast\n    from d(1,3) m(1) have dm: \"d * m > 0\" \"d * m < e\"\n      by (simp_all add: field_simps)\n    show ?case\n    proof (rule ex_forward[OF real_lbound_gt_zero[OF one0 em0]], clarsimp simp add: norm_mult)\n      fix d w\n      assume H: \"d > 0\" \"d < 1\" \"d < e/m\" \"w \\<noteq> z\" \"norm (w - z) < d\"\n      then have d1: \"norm (w-z) \\<le> 1\" \"d \\<ge> 0\"\n        by simp_all\n      from H(3) m(1) have dme: \"d*m < e\"\n        by (simp add: field_simps)\n      from H have th: \"norm (w - z) \\<le> d\"\n        by simp\n      from mult_mono[OF th m(2)[OF d1(1)] d1(2) norm_ge_zero] dme\n      show \"norm (w - z) * norm (poly cs (w - z)) < e\"\n        by simp\n    qed\n  qed\nqed\n\ntext{* Hence a polynomial attains minimum on a closed disc\n  in the complex plane. *}\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  {\n    assume \"\\<not> r \\<ge> 0\"\n    then have ?thesis\n      by (metis norm_ge_zero order.trans)\n  }\n  moreover\n  {\n    assume rp: \"r \\<ge> 0\"\n    from rp have \"cmod 0 \\<le> r \\<and> cmod (poly p 0) = - (- cmod (poly p 0))\"\n      by simp\n    then have mth1: \"\\<exists>x z. cmod z \\<le> r \\<and> cmod (poly p z) = - x\"\n      by blast\n    {\n      fix x z\n      assume H: \"cmod z \\<le> r\" \"cmod (poly p z) = - x\" \"\\<not> x < 1\"\n      then have \"- x < 0 \"\n        by arith\n      with H(2) norm_ge_zero[of \"poly p z\"] have False\n        by simp\n    }\n    then have mth2: \"\\<exists>z. \\<forall>x. (\\<exists>z. cmod z \\<le> r \\<and> cmod (poly p z) = - x) \\<longrightarrow> x < z\"\n      by blast\n    from real_sup_exists[OF mth1 mth2] obtain s where\n      s: \"\\<forall>y. (\\<exists>x. (\\<exists>z. cmod z \\<le> r \\<and> cmod (poly p z) = - x) \\<and> y < x) \\<longleftrightarrow> y < s\" by blast\n    let ?m = \"- s\"\n    {\n      fix y\n      from s[rule_format, of \"-y\"]\n      have \"(\\<exists>z x. cmod z \\<le> r \\<and> - (- cmod (poly p z)) < y) \\<longleftrightarrow> ?m < y\"\n        unfolding minus_less_iff[of y ] equation_minus_iff by blast\n    }\n    note s1 = this[unfolded minus_minus]\n    from s1[of ?m] have s1m: \"\\<And>z x. cmod z \\<le> r \\<Longrightarrow> cmod (poly p z) \\<ge> ?m\"\n      by auto\n    {\n      fix n :: nat\n      from s1[rule_format, of \"?m + 1/real (Suc n)\"]\n      have \"\\<exists>z. cmod z \\<le> r \\<and> cmod (poly p z) < - s + 1 / real (Suc n)\"\n        by simp\n    }\n    then have th: \"\\<forall>n. \\<exists>z. cmod z \\<le> r \\<and> cmod (poly p z) < - s + 1 / real (Suc n)\" ..\n    from choice[OF th] obtain g where\n        g: \"\\<forall>n. cmod (g n) \\<le> r\" \"\\<forall>n. cmod (poly p (g n)) <?m + 1 /real(Suc n)\"\n      by blast\n    from bolzano_weierstrass_complex_disc[OF g(1)]\n    obtain f z where fz: \"subseq 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        from poly_cont[OF e2, of z p] obtain d where\n            d: \"d > 0\" \"\\<forall>w. 0<cmod (w - z)\\<and> cmod(w - z) < d \\<longrightarrow> cmod(poly p w - poly p z) < ?e/2\"\n          by blast\n        {\n          fix w\n          assume w: \"cmod (w - z) < d\"\n          have \"cmod(poly p w - poly p z) < ?e / 2\"\n            using d(2)[rule_format, of w] w e by (cases \"w = z\") simp_all\n        }\n        note th1 = this\n\n        from fz(2) d(1) obtain N1 where N1: \"\\<forall>n\\<ge>N1. cmod (g (f n) - z) < d\"\n          by blast\n        from reals_Archimedean2[of \"2/?e\"] obtain N2 :: nat where N2: \"2/?e < real N2\"\n          by blast\n        have th2: \"cmod (poly p (g (f (N1 + N2))) - poly p z) < ?e/2\"\n          using N1[rule_format, of \"N1 + N2\"] th1 by simp\n        {\n          fix a b e2 m :: real\n          have \"a < e2 \\<Longrightarrow> \\<bar>b - m\\<bar> < e2 \\<Longrightarrow> 2 * e2 \\<le> \\<bar>b - m\\<bar> + a \\<Longrightarrow> False\"\n            by arith\n        }\n        note th0 = this\n        have ath: \"\\<And>m x e::real. m \\<le> x \\<Longrightarrow> x < m + e \\<Longrightarrow> \\<bar>x - m\\<bar> < e\"\n          by arith\n        from s1m[OF g(1)[rule_format]] have th31: \"?m \\<le> cmod(poly p (g (f (N1 + N2))))\" .\n        from seq_suble[OF fz(1), of \"N1 + N2\"]\n        have th00: \"real (Suc (N1 + N2)) \\<le> real (Suc (f (N1 + N2)))\"\n          by simp\n        have th000: \"0 \\<le> (1::real)\" \"(1::real) \\<le> 1\" \"real (Suc (N1 + N2)) > 0\"\n          using N2 by auto\n        from frac_le[OF th000 th00]\n        have th00: \"?m + 1 / real (Suc (f (N1 + N2))) \\<le> ?m + 1 / real (Suc (N1 + N2))\"\n          by simp\n        from g(2)[rule_format, of \"f (N1 + N2)\"]\n        have th01:\"cmod (poly p (g (f (N1 + N2)))) < - s + 1 / real (Suc (f (N1 + N2)))\" .\n        from order_less_le_trans[OF th01 th00]\n        have th32: \"cmod (poly p (g (f (N1 + N2)))) < ?m + (1/ real(Suc (N1 + N2)))\" .\n        from N2 have \"2/?e < real (Suc (N1 + N2))\"\n          by arith\n        with 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 ath[OF th31 th32]\n        have thc1: \"\\<bar>cmod (poly p (g (f (N1 + N2)))) - ?m\\<bar> < ?e/2\"\n          by arith\n        have ath2: \"\\<And>a b c m::real. \\<bar>a - b\\<bar> \\<le> c \\<Longrightarrow> \\<bar>b - m\\<bar> \\<le> \\<bar>a - m\\<bar> + c\"\n          by arith\n        have th22: \"\\<bar>cmod (poly p (g (f (N1 + N2)))) - cmod (poly p z)\\<bar> \\<le>\n            cmod (poly p (g (f (N1 + N2))) - poly p z)\"\n          by (simp add: norm_triangle_ineq3)\n        from ath2[OF th22, of ?m]\n        have thc2: \"2 * (?e/2) \\<le>\n            \\<bar>cmod(poly p (g (f (N1 + N2)))) - ?m\\<bar> + cmod (poly p (g (f (N1 + N2))) - poly p z)\"\n          by simp\n        from th0[OF th2 thc1 thc2] have False .\n      }\n      then have \"?e = 0\"\n        by auto\n      then have \"cmod (poly p z) = ?m\"\n        by simp\n      with s1m[OF wr] have \"cmod (poly p z) \\<le> cmod (poly p w)\"\n        by simp\n    }\n    then have ?thesis by blast\n  }\n  ultimately show ?thesis by blast\nqed\n\ntext {* Nonzero polynomial in z goes to infinity as z does. *}\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    {\n      fix z :: 'a\n      assume h: \"1 + \\<bar>r\\<bar> \\<le> norm z\"\n      have r0: \"r \\<le> norm z\"\n        using h by arith\n      from r[rule_format, OF r0] have th0: \"d + norm a \\<le> 1 * norm(poly (pCons c cs) z)\"\n        by arith\n      from h have z1: \"norm z \\<ge> 1\"\n        by arith\n      from order_trans[OF th0 mult_right_mono[OF z1 norm_ge_zero[of \"poly (pCons c cs) z\"]]]\n      have th1: \"d \\<le> norm(z * poly (pCons c cs) z) - norm a\"\n        unfolding norm_mult by (simp add: algebra_simps)\n      from norm_diff_ineq[of \"z * poly (pCons c cs) z\" a]\n      have th2: \"norm (z * poly (pCons c cs) z) - norm a \\<le> norm (poly (pCons a (pCons c cs)) z)\"\n        by (simp add: algebra_simps)\n      from th1 th2 have \"d \\<le> norm (poly (pCons a (pCons c cs)) z)\"\n        by arith\n    }\n    then show ?thesis by blast\n  next\n    case True\n    with pCons.prems have c0: \"c \\<noteq> 0\"\n      by simp\n    {\n      fix z :: 'a\n      assume h: \"(\\<bar>d\\<bar> + norm a) / norm c \\<le> norm z\"\n      from c0 have \"norm c > 0\"\n        by simp\n      from h c0 have th0: \"\\<bar>d\\<bar> + norm a \\<le> norm (z * c)\"\n        by (simp add: field_simps norm_mult)\n      have ath: \"\\<And>mzh mazh ma. mzh \\<le> mazh + ma \\<Longrightarrow> \\<bar>d\\<bar> + ma \\<le> mzh \\<Longrightarrow> d \\<le> mazh\"\n        by arith\n      from norm_diff_ineq[of \"z * c\" a] have th1: \"norm (z * c) \\<le> norm (a + z * c) + norm a\"\n        by (simp add: algebra_simps)\n      from ath[OF th1 th0] have \"d \\<le> norm (poly (pCons a (pCons c cs)) z)\"\n        using True by simp\n    }\n    then show ?thesis by blast\n  qed\nqed\n\ntext {* Hence polynomial's modulus attains its minimum somewhere. *}\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: \"\\<And>z. r \\<le> cmod z \\<Longrightarrow> cmod (poly (pCons c cs) 0) \\<le> cmod (poly (pCons c cs) z)\"\n      by blast\n    have ath: \"\\<And>z r. r \\<le> cmod z \\<or> cmod z \\<le> \\<bar>r\\<bar>\"\n      by arith\n    from poly_minimum_modulus_disc[of \"\\<bar>r\\<bar>\" \"pCons c cs\"]\n    obtain v where v: \"\\<And>w. cmod w \\<le> \\<bar>r\\<bar> \\<Longrightarrow> cmod (poly (pCons c cs) v) \\<le> cmod (poly (pCons c cs) w)\"\n      by blast\n    {\n      fix z\n      assume z: \"r \\<le> cmod z\"\n      from v[of 0] r[OF z] have \"cmod (poly (pCons c cs) v) \\<le> cmod (poly (pCons c cs) z)\"\n        by simp\n    }\n    note v0 = this\n    from v0 v ath[of r] show ?thesis\n      by blast\n  next\n    case True\n    with pCons.hyps show ?thesis by simp\n  qed\nqed\n\ntext{* Constant function (non-syntactic characterization). *}\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 {* Decomposition of polynomial, skipping zero coefficients\n  after the first.  *}\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, clarsimp)\n      apply (rule_tac x=\"q\" in exI)\n      apply auto\n      done\n  next\n    case False\n    show ?thesis\n      apply (rule exI[where x=0])\n      apply (rule exI[where x=c], auto simp add: False)\n      done\n  qed\nqed\n\nlemma poly_decompose:\n  assumes nc: \"\\<not> constant (poly p)\"\n  shows \"\\<exists>k a q. a \\<noteq> (0::'a::idom) \\<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  {\n    assume C: \"\\<forall>z. z \\<noteq> 0 \\<longrightarrow> poly cs z = 0\"\n    {\n      fix x y\n      from C have \"poly (pCons c cs) x = poly (pCons c cs) y\"\n        by (cases \"x = 0\") auto\n    }\n    with pCons.prems have False\n      by (auto simp add: constant_def)\n  }\n  then have th: \"\\<not> (\\<forall>z. z \\<noteq> 0 \\<longrightarrow> poly cs z = 0)\" ..\n  from poly_decompose_lemma[OF th]\n  show ?case\n    apply clarsimp\n    apply (rule_tac x=\"k+1\" in exI)\n    apply (rule_tac x=\"a\" in exI)\n    apply simp\n    apply (rule_tac x=\"q\" in exI)\n    apply (auto simp add: psize_def split: if_splits)\n    done\nqed\n\ntext{* Fundamental theorem of algebra *}\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    note pc0 = this\n    from poly_offset[of p c] obtain q where q: \"psize q = psize p\" \"\\<forall>x. poly q x = ?p (c + x)\"\n      by blast\n    {\n      assume h: \"constant (poly q)\"\n      from q(2) have th: \"\\<forall>x. poly q (x - c) = ?p x\"\n        by auto\n      {\n        fix x y\n        from th have \"?p x = poly q (x - c)\"\n          by auto\n        also have \"\\<dots> = poly q (y - c)\"\n          using h unfolding constant_def by blast\n        also have \"\\<dots> = ?p y\"\n          using th by auto\n        finally have \"?p x = ?p y\" .\n      }\n      with less(2) have False\n        unfolding constant_def by blast\n    }\n    then have qnc: \"\\<not> constant (poly q)\"\n      by blast\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 pc0 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      using a00\n      unfolding psize_def degree_def\n      by (simp add: poly_eq_iff)\n    {\n      assume h: \"\\<And>x y. poly ?r x = poly ?r y\"\n      {\n        fix x y\n        from qr[rule_format, of x] have \"poly q x = poly ?r x * ?a0\"\n          by auto\n        also have \"\\<dots> = poly ?r y * ?a0\"\n          using h by simp\n        also have \"\\<dots> = poly q y\"\n          using qr[rule_format, of y] by simp\n        finally have \"poly q x = poly q y\" .\n      }\n      with qnc have False\n        unfolding constant_def by blast\n    }\n    then have rnc: \"\\<not> constant (poly ?r)\"\n      unfolding constant_def by blast\n    from qr[rule_format, of 0] a00 have r01: \"poly ?r 0 = 1\"\n      by auto\n    {\n      fix w\n      have \"cmod (poly ?r w) < 1 \\<longleftrightarrow> cmod (poly q w / ?a0) < 1\"\n        using qr[rule_format, of w] a00 by (simp add: divide_inverse ac_simps)\n      also have \"\\<dots> \\<longleftrightarrow> cmod (poly q w) < cmod ?a0\"\n        using a00 unfolding norm_divide by (simp add: field_simps)\n      finally have \"cmod (poly ?r w) < 1 \\<longleftrightarrow> cmod (poly q w) < cmod ?a0\" .\n    }\n    note mrmq_eq = this\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    {\n      assume \"psize p = k + 1\"\n      with kas(3) lgqr[symmetric] q(1) have s0: \"s = 0\"\n        by auto\n      {\n        fix w\n        have \"cmod (poly ?r w) = cmod (1 + a * w ^ k)\"\n          using kas(4)[rule_format, of w] s0 r01 by (simp add: algebra_simps)\n      }\n      note hth = this [symmetric]\n      from reduce_poly_simple[OF kas(1,2)] have \"\\<exists>w. cmod (poly ?r w) < 1\"\n        unfolding hth by blast\n    }\n    moreover\n    {\n      assume kn: \"psize p \\<noteq> k + 1\"\n      from kn kas(3) q(1) lgqr have k1n: \"k + 1 < psize p\"\n        by simp\n      have th01: \"\\<not> constant (poly (pCons 1 (monom a (k - 1))))\"\n        unfolding constant_def poly_pCons poly_monom\n        using kas(1)\n        apply simp\n        apply (rule exI[where x=0])\n        apply (rule exI[where x=1])\n        apply simp\n        done\n      from kas(1) kas(2) have th02: \"k + 1 = psize (pCons 1 (monom a (k - 1)))\"\n        by (simp add: psize_def degree_monom_eq)\n      from less(1) [OF k1n [simplified th02] th01]\n      obtain w where w: \"1 + w^k * a = 0\"\n        unfolding poly_pCons poly_monom\n        using kas(2) by (cases k) (auto simp add: algebra_simps)\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 w0: \"w \\<noteq> 0\"\n        using kas(2) w by (auto simp add: power_0_left)\n      from w have \"(1 + w ^ k * a) - 1 = 0 - 1\"\n        by simp\n      then have wm1: \"w^k * a = - 1\"\n        by simp\n      have inv0: \"0 < inverse (cmod w ^ (k + 1) * m)\"\n        using norm_ge_zero[of w] w0 m(1)\n        by (simp add: inverse_eq_divide zero_less_mult_iff)\n      with real_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 th11: \"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 \"t * cmod w \\<le> 1 * cmod w\"\n        apply (rule mult_mono)\n        using t(1,2)\n        apply auto\n        done\n      then have tw: \"cmod ?w \\<le> cmod w\"\n        using t(1) by (simp add: norm_mult)\n      from t inv0 have \"t * (cmod w ^ (k + 1) * m) < 1\"\n        by (simp add: field_simps)\n      with zero_less_power[OF t(1), of k] have th30: \"t^k * (t* (cmod w ^ (k + 1) * m)) < t^k * 1\"\n        by (metis comm_mult_strict_left_mono)\n      have \"cmod (?w^k * ?w * poly s ?w) = t^k * (t* (cmod w ^ (k + 1) * cmod (poly s ?w)))\"\n        using w0 t(1)\n        by (simp add: algebra_simps power_mult_distrib norm_power norm_mult)\n      then have \"cmod (?w^k * ?w * poly s ?w) \\<le> t^k * (t* (cmod w ^ (k + 1) * m))\"\n        using t(1,2) m(2)[rule_format, OF tw] w0\n        by auto\n      with th30 have th120: \"cmod (?w^k * ?w * poly s ?w) < t^k\"\n        by simp\n      from power_strict_mono[OF t(2), of k] t(1) kas(2) have th121: \"t^k \\<le> 1\"\n        by auto\n      from ath[OF norm_ge_zero[of \"?w^k * ?w * poly s ?w\"] th120 th121]\n      have th12: \"\\<bar>1 - t^k\\<bar> + cmod (?w^k * ?w * poly s ?w) < 1\" .\n      from th11 th12 have \"cmod (1 + ?w^k * (a + ?w * poly s ?w)) < 1\"\n        by arith\n      then have \"cmod (poly ?r ?w) < 1\"\n        unfolding kas(4)[rule_format, of ?w] r01 by simp\n      then have \"\\<exists>w. cmod (poly ?r w) < 1\"\n        by blast\n    }\n    ultimately have cr0_contr: \"\\<exists>w. cmod (poly ?r w) < 1\"\n      by blast\n    from cr0_contr cq0 q(2) show ?thesis\n      unfolding mrmq_eq not_less[symmetric] by auto\n  qed\nqed\n\ntext {* Alternative version with a syntactic notion of constant polynomial. *}\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)\"\n  using nc\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    then show ?thesis by auto\n  next\n    case False\n    {\n      assume nc: \"constant (poly (pCons c cs))\"\n      from nc[unfolded constant_def, rule_format, of 0]\n      have \"\\<forall>w. w \\<noteq> 0 \\<longrightarrow> poly cs w = 0\" by auto\n      then have \"cs = 0\"\n      proof (induct cs)\n        case 0\n        then show ?case by simp\n      next\n        case (pCons d ds)\n        show ?case\n        proof (cases \"d = 0\")\n          case True\n          then show ?thesis using pCons.prems pCons.hyps by simp\n        next\n          case False\n          from poly_bound_exists[of 1 ds] obtain m where\n            m: \"m > 0\" \"\\<forall>z. \\<forall>z. cmod z \\<le> 1 \\<longrightarrow> cmod (poly ds z) \\<le> m\" by blast\n          have dm: \"cmod d / m > 0\"\n            using False m(1) by (simp add: field_simps)\n          from real_lbound_gt_zero[OF dm zero_less_one] obtain x where\n            x: \"x > 0\" \"x < cmod d / m\" \"x < 1\" by blast\n          let ?x = \"complex_of_real x\"\n          from x have cx: \"?x \\<noteq> 0\"  \"cmod ?x \\<le> 1\"\n            by simp_all\n          from pCons.prems[rule_format, OF cx(1)]\n          have cth: \"cmod (?x*poly ds ?x) = cmod d\"\n            by (simp add: eq_diff_eq[symmetric])\n          from m(2)[rule_format, OF cx(2)] x(1)\n          have th0: \"cmod (?x*poly ds ?x) \\<le> x*m\"\n            by (simp add: norm_mult)\n          from x(2) m(1) have \"x * m < cmod d\"\n            by (simp add: field_simps)\n          with th0 have \"cmod (?x*poly ds ?x) \\<noteq> cmod d\"\n            by auto\n          with cth show ?thesis\n            by blast\n        qed\n      qed\n    }\n    then have nc: \"\\<not> constant (poly (pCons c cs))\"\n      using pCons.prems False by blast\n    from fundamental_theorem_of_algebra[OF nc] show ?thesis .\n  qed\nqed\n\n\nsubsection{* Nullstellensatz, degrees and divisibility of polynomials *}\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  let ?ths = \"p dvd (q ^ n)\"\n  {\n    fix a\n    assume a: \"poly p a = 0\"\n    {\n      assume oa: \"order a p \\<noteq> 0\"\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      {\n        assume q0: \"q = 0\"\n        then have ?ths using n0\n          by (simp add: power_0_left)\n      }\n      moreover\n      {\n        assume q0: \"q \\<noteq> 0\"\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\" using s pne by auto\n        {\n          assume ds0: \"degree s = 0\"\n          from ds0 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 = p * ?w\"\n            apply (subst r)\n            apply (subst s)\n            apply (subst kpn)\n            using k oop [of a]\n            apply (subst power_mult_distrib)\n            apply simp\n            apply (subst power_add [symmetric])\n            apply simp\n            done\n          then have ?ths\n            unfolding dvd_def by blast\n        }\n        moreover\n        {\n          assume ds0: \"degree s \\<noteq> 0\"\n          from ds0 sne dpn s oa\n            have dsn: \"degree s < n\"\n              apply auto\n              apply (erule ssubst)\n              apply (simp add: degree_mult_eq degree_linear_power)\n              done\n            {\n              fix x assume h: \"poly s x = 0\"\n              {\n                assume xa: \"x = a\"\n                from h[unfolded xa poly_eq_0_iff_dvd] obtain u where u: \"s = [:- a, 1:] * u\"\n                  by (rule dvdE)\n                have \"p = [:- a, 1:] ^ (Suc ?op) * u\"\n                  apply (subst s)\n                  apply (subst u)\n                  apply (simp only: power_Suc ac_simps)\n                  done\n                with ap(2)[unfolded dvd_def] have False\n                  by blast\n              }\n              note xa = this\n              from h have \"poly p x = 0\"\n                by (subst s) simp\n              with pq0 have \"poly q x = 0\"\n                by blast\n              with r xa have \"poly r x = 0\"\n                by auto\n            }\n            note impth = this\n            from IH[rule_format, OF dsn, of s r] impth ds0\n            have \"s dvd (r ^ (degree s))\"\n              by blast\n            then obtain u where u: \"r ^ (degree s) = s * u\" ..\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            let ?w = \"(u * ([:-a,1:] ^ (n - ?op))) * (r ^ (n - degree s))\"\n            from oop[of a] dsn have \"q ^ n = p * ?w\"\n              apply -\n              apply (subst s)\n              apply (subst r)\n              apply (simp only: power_mult_distrib)\n              apply (subst mult.assoc [where b=s])\n              apply (subst mult.assoc [where a=u])\n              apply (subst mult.assoc [where b=u, symmetric])\n              apply (subst u [symmetric])\n              apply (simp add: ac_simps power_add [symmetric])\n              done\n            then have ?ths\n              unfolding dvd_def by blast\n        }\n        ultimately have ?ths by blast\n      }\n      ultimately have ?ths by blast\n    }\n    then have ?ths using a order_root pne by blast\n  }\n  moreover\n  {\n    assume exa: \"\\<not> (\\<exists>a. poly p a = 0)\"\n    from fundamental_theorem_of_algebra_alt[of p] exa\n    obtain c where ccs: \"c \\<noteq> 0\" \"p = pCons c 0\"\n      by blast\n    then have pp: \"\\<And>x. poly p x = c\"\n      by simp\n    let ?w = \"[:1/c:] * (q ^ n)\"\n    from ccs have \"(q ^ n) = (p * ?w)\"\n      by simp\n    then have ?ths\n      unfolding dvd_def by blast\n  }\n  ultimately show ?ths by blast\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  {\n    assume pe: \"p = 0\"\n    then have eq: \"(\\<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    {\n      assume \"p dvd (q ^ (degree p))\"\n      then obtain r where r: \"q ^ (degree p) = p * r\" ..\n      from r pe have False by simp\n    }\n    with eq pe have ?thesis by blast\n  }\n  moreover\n  {\n    assume pe: \"p \\<noteq> 0\"\n    {\n      assume dp: \"degree p = 0\"\n      then obtain k where k: \"p = [:k:]\" \"k \\<noteq> 0\" using pe\n        by (cases p) (simp split: if_splits)\n      then have th1: \"\\<forall>x. poly p x \\<noteq> 0\"\n        by simp\n      from k dp have \"q ^ (degree p) = p * [:1/k:]\"\n        by (simp add: one_poly_def)\n      then have th2: \"p dvd (q ^ (degree p))\" ..\n      from th1 th2 pe have ?thesis\n        by blast\n    }\n    moreover\n    {\n      assume dp: \"degree p \\<noteq> 0\"\n      then obtain n where n: \"degree p = Suc n \"\n        by (cases \"degree p\") auto\n      {\n        assume \"p dvd (q ^ (Suc n))\"\n        then obtain u where u: \"q ^ (Suc n) = p * u\" ..\n        {\n          fix x\n          assume h: \"poly p x = 0\" \"poly q x \\<noteq> 0\"\n          then have \"poly (q ^ (Suc n)) x \\<noteq> 0\"\n            by simp\n          then have False using u h(1)\n            by (simp only: poly_mult) simp\n        }\n      }\n      with n nullstellensatz_lemma[of p q \"degree p\"] dp\n      have ?thesis by auto\n    }\n    ultimately have ?thesis by blast\n  }\n  ultimately show ?thesis by blast\nqed\n\ntext {* Useful lemma *}\n\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  assume l: ?lhs\n  from l[unfolded constant_def, rule_format, of _ \"0\"]\n  have th: \"poly p = poly [:poly p 0:]\"\n    by auto\n  then have \"p = [:poly p 0:]\"\n    by (simp add: poly_eq_poly_eq_iff)\n  then have \"degree p = degree [:poly p 0:]\"\n    by simp\n  then show ?rhs\n    by simp\nnext\n  assume r: ?rhs\n  then obtain k where \"p = [:k:]\"\n    by (cases p) (simp split: if_splits)\n  then show ?lhs\n    unfolding constant_def by auto\nqed\n\nlemma divides_degree:\n  assumes pq: \"p dvd (q:: complex poly)\"\n  shows \"degree p \\<le> degree q \\<or> q = 0\"\n  by (metis dvd_imp_degree_le pq)\n\ntext {* Arithmetic operations on multivariate polynomials. *}\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)\"\nproof -\n  have \"pCons 0 q = q * [:0,1:]\" by simp\n  then have \"q dvd (pCons 0 q)\" ..\n  with pq show ?thesis by (rule dvd_trans)\nqed\n\nlemma poly_divides_conv0:\n  fixes p:: \"'a::field poly\"\n  assumes lgpq: \"degree q < degree p\"\n    and lq: \"p \\<noteq> 0\"\n  shows \"p dvd q \\<longleftrightarrow> q = 0\" (is \"?lhs \\<longleftrightarrow> ?rhs\")\nproof\n  assume r: ?rhs\n  then have \"q = p * 0\" by simp\n  then show ?lhs ..\nnext\n  assume l: ?lhs\n  show ?rhs\n  proof (cases \"q = 0\")\n    case True\n    then show ?thesis by simp\n  next\n    assume q0: \"q \\<noteq> 0\"\n    from l q0 have \"degree p \\<le> degree q\"\n      by (rule dvd_imp_degree_le)\n    with lgpq show ?thesis by simp\n  qed\nqed\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\" (is \"?lhs \\<longleftrightarrow> ?rhs\")\nproof\n  from pp' obtain t where t: \"p' = p * t\" ..\n  {\n    assume l: ?lhs\n    then obtain u where u: \"q = p * u\" ..\n    have \"r = p * (smult a u - t)\"\n      using u qrp' [symmetric] t by (simp add: algebra_simps)\n    then show ?rhs ..\n  next\n    assume r: ?rhs\n    then obtain u where u: \"r = p * u\" ..\n    from u [symmetric] t qrp' [symmetric] a0\n    have \"q = p * smult (1/a) (u + t)\" by (simp add: algebra_simps)\n    then show ?lhs ..\n  }\nqed\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)\"\nproof -\n  {\n    fix h t\n    assume h: \"h \\<noteq> 0\" \"t = 0\" and \"pCons a (pCons b p) = pCons h t\"\n    with l have False by simp\n  }\n  then have th: \"\\<not> (\\<exists> h t. h \\<noteq> 0 \\<and> t = 0 \\<and> pCons a (pCons b p) = pCons h t)\"\n    by blast\n  from fundamental_theorem_of_algebra_alt[OF th] show ?thesis\n    by auto\nqed\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)\"\nproof -\n  from l have dp: \"degree (pCons a p) = psize p\"\n    by (simp add: psize_def)\n  from nullstellensatz_univariate[of \"pCons a p\" q] l\n  show ?thesis\n    by (metis dp pCons_eq_0_iff)\nqed\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\"\nproof -\n  from h have \"poly (q ^ n) = poly r\"\n    by auto\n  then have \"(q ^ n) = r\"\n    by (simp add: poly_eq_poly_eq_iff)\n  then show \"p dvd (q ^ n) \\<longleftrightarrow> p dvd r\"\n    by simp\nqed\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": "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/Fundamental_Theorem_Algebra.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8289388040954683, "lm_q2_score": 0.8558511506439708, "lm_q1q2_score": 0.7094482292985436}}
{"text": "(* Title:      Construction of Stone Algebras\n   Author:     Walter Guttmann\n   Maintainer: Walter Guttmann <walter.guttmann at canterbury.ac.nz>\n*)\n\nsection \\<open>Stone Construction\\<close>\n\ntext \\<open>\nThis theory proves the uniqueness theorem for the triple representation of Stone algebras and the construction theorem of Stone algebras \\cite{ChenGraetzer1969,Katrinak1973}.\nEvery Stone algebra $S$ has an associated triple consisting of\n\\begin{itemize}\n\\item the set of regular elements $B(S)$ of $S$,\n\\item the set of dense elements $D(S)$ of $S$, and\n\\item the structure map $\\varphi(S) : B(S) \\to F(D(S))$ defined by $\\varphi(x) = {\\uparrow} x \\cap D(S)$.\n\\end{itemize}\nHere $F(X)$ is the set of filters of a partially ordered set $X$.\nWe first show that\n\\begin{itemize}\n\\item $B(S)$ is a Boolean algebra,\n\\item $D(S)$ is a distributive lattice with a greatest element, whence $F(D(S))$ is a bounded distributive lattice, and\n\\item $\\varphi(S)$ is a bounded lattice homomorphism.\n\\end{itemize}\nNext, from a triple $T = (B,D,\\varphi)$ such that $B$ is a Boolean algebra, $D$ is a distributive lattice with a greatest element and $\\varphi : B \\to F(D)$ is a bounded lattice homomorphism, we construct a Stone algebra $S(T)$.\nThe elements of $S(T)$ are pairs taken from $B \\times F(D)$ following the construction of \\cite{Katrinak1973}.\nWe need to represent $S(T)$ as a type to be able to instantiate the Stone algebra class.\nBecause the pairs must satisfy a condition depending on $\\varphi$, this would require dependent types.\nSince Isabelle/HOL does not have dependent types, we use a function lifting instead.\nThe lifted pairs form a Stone algebra.\n\nNext, we specialise the construction to start with the triple associated with a Stone algebra $S$, that is, we construct $S(B(S),D(S),\\varphi(S))$.\nIn this case, we can instantiate the lifted pairs to obtain a type of pairs (that no longer implements a dependent type).\nTo achieve this, we construct an embedding of the type of pairs into the lifted pairs, so that we inherit the Stone algebra axioms (using a technique of universal algebra that works for universally quantified equations and equational implications).\n\nNext, we show that the Stone algebras $S(B(S),D(S),\\varphi(S))$ and $S$ are isomorphic.\nWe give explicit mappings in both directions.\nThis implies the uniqueness theorem for the triple representation of Stone algebras.\n\nFinally, we show that the triples $(B(S(T)),D(S(T)),\\varphi(S(T)))$ and $T$ are isomorphic.\nThis requires an isomorphism of the Boolean algebras $B$ and $B(S(T))$, an isomorphism of the distributive lattices $D$ and $D(S(T))$, and a proof that they preserve the structure maps.\nWe give explicit mappings of the Boolean algebra isomorphism and the distributive lattice isomorphism in both directions.\nThis implies the construction theorem of Stone algebras.\nBecause $S(T)$ is implemented by lifted pairs, so are $B(S(T))$ and $D(S(T))$; we therefore also lift $B$ and $D$ to establish the isomorphisms.\n\\<close>\n\ntheory Stone_Construction\n\nimports P_Algebras Filters\n\nbegin\n\ntext \\<open>\nA triple consists of a Boolean algebra, a distributive lattice with a greatest element, and a structure map.\nThe Boolean algebra and the distributive lattice are represented as HOL types.\nBecause both occur in the type of the structure map, the triple is determined simply by the structure map and its HOL type.\nThe structure map needs to be a bounded lattice homomorphism.\n\\<close>\n\nlocale triple =\n  fixes phi :: \"'a::boolean_algebra \\<Rightarrow> 'b::distrib_lattice_top filter\"\n  assumes hom: \"bounded_lattice_homomorphism phi\"\n\nsubsection \\<open>The Triple of a Stone Algebra\\<close>\n\ntext \\<open>\nIn this section we construct the triple associated to a Stone algebra.\n\\<close>\n\nsubsubsection \\<open>Regular Elements\\<close>\n\ntext \\<open>\nThe regular elements of a Stone algebra form a Boolean subalgebra.\n\\<close>\n\ntypedef (overloaded) 'a regular = \"regular_elements::'a::stone_algebra set\"\n  by auto\n\nlemma simp_regular [simp]:\n  \"\\<exists>y . Rep_regular x = -y\"\n  using Rep_regular by simp\n\nsetup_lifting type_definition_regular\n\ninstantiation regular :: (stone_algebra) boolean_algebra\nbegin\n\nlift_definition sup_regular :: \"'a regular \\<Rightarrow> 'a regular \\<Rightarrow> 'a regular\" is sup\n  by (meson regular_in_p_image_iff regular_closed_sup)\n\nlift_definition inf_regular :: \"'a regular \\<Rightarrow> 'a regular \\<Rightarrow> 'a regular\" is inf\n  by (meson regular_in_p_image_iff regular_closed_inf)\n\nlift_definition minus_regular :: \"'a regular \\<Rightarrow> 'a regular \\<Rightarrow> 'a regular\" is \"\\<lambda>x y . x \\<sqinter> -y\"\n  by (meson regular_in_p_image_iff regular_closed_inf)\n\nlift_definition uminus_regular :: \"'a regular \\<Rightarrow> 'a regular\" is uminus\n  by auto\n\nlift_definition bot_regular :: \"'a regular\" is bot\n  by (meson regular_in_p_image_iff regular_closed_bot)\n\nlift_definition top_regular :: \"'a regular\" is top\n  by (meson regular_in_p_image_iff regular_closed_top)\n\nlift_definition less_eq_regular :: \"'a regular \\<Rightarrow> 'a regular \\<Rightarrow> bool\" is less_eq .\n\nlift_definition less_regular :: \"'a regular \\<Rightarrow> 'a regular \\<Rightarrow> bool\" is less .\n\ninstance\n  apply intro_classes\n  subgoal apply transfer by (simp add: less_le_not_le)\n  subgoal apply transfer by simp\n  subgoal apply transfer by simp\n  subgoal apply transfer by simp\n  subgoal apply transfer by simp\n  subgoal apply transfer by simp\n  subgoal apply transfer by simp\n  subgoal apply transfer by simp\n  subgoal apply transfer by simp\n  subgoal apply transfer by simp\n  subgoal apply transfer by simp\n  subgoal apply transfer by simp\n  subgoal apply transfer by (simp add: sup_inf_distrib1)\n  subgoal apply transfer by simp\n  subgoal apply transfer by auto\n  subgoal apply transfer by simp\n  done\n\nend\n\ninstantiation regular :: (non_trivial_stone_algebra) non_trivial_boolean_algebra\nbegin\n\ninstance\nproof (intro_classes, rule ccontr)\n  assume \"\\<not>(\\<exists>x y::'a regular . x \\<noteq> y)\"\n  hence \"(bot::'a regular) = top\"\n    by simp\n  hence \"(bot::'a) = top\"\n    by (metis bot_regular.rep_eq top_regular.rep_eq)\n  thus False\n    by (simp add: bot_not_top)\nqed\n\nend\n\nsubsubsection \\<open>Dense Elements\\<close>\n\ntext \\<open>\nThe dense elements of a Stone algebra form a distributive lattice with a greatest element.\n\\<close>\n\ntypedef (overloaded) 'a dense = \"dense_elements::'a::stone_algebra set\"\n  using dense_closed_top by blast\n\nlemma simp_dense [simp]:\n  \"-Rep_dense x = bot\"\n  using Rep_dense by simp\n\nsetup_lifting type_definition_dense\n\ninstantiation dense :: (stone_algebra) distrib_lattice_top\nbegin\n\nlift_definition sup_dense :: \"'a dense \\<Rightarrow> 'a dense \\<Rightarrow> 'a dense\" is sup\n  by simp\n\nlift_definition inf_dense :: \"'a dense \\<Rightarrow> 'a dense \\<Rightarrow> 'a dense\" is inf\n  by simp\n\nlift_definition top_dense :: \"'a dense\" is top\n  by simp\n\nlift_definition less_eq_dense :: \"'a dense \\<Rightarrow> 'a dense \\<Rightarrow> bool\" is less_eq .\n\nlift_definition less_dense :: \"'a dense \\<Rightarrow> 'a dense \\<Rightarrow> bool\" is less .\n\ninstance\n  apply intro_classes\n  subgoal apply transfer by (simp add: inf.less_le_not_le)\n  subgoal apply transfer by simp\n  subgoal apply transfer by simp\n  subgoal apply transfer by simp\n  subgoal apply transfer by simp\n  subgoal apply transfer by simp\n  subgoal apply transfer by simp\n  subgoal apply transfer by simp\n  subgoal apply transfer by simp\n  subgoal apply transfer by simp\n  subgoal apply transfer by simp\n  subgoal apply transfer by (simp add: sup_inf_distrib1)\n  done\n\nend\n\nlemma up_filter_dense_antitone_dense:\n  \"dense (x \\<squnion> -x \\<squnion> y) \\<and> dense (x \\<squnion> -x \\<squnion> y \\<squnion> z)\"\n  by simp\n\nlemma up_filter_dense_antitone:\n  \"up_filter (Abs_dense (x \\<squnion> -x \\<squnion> y \\<squnion> z)) \\<le> up_filter (Abs_dense (x \\<squnion> -x \\<squnion> y))\"\n  by (unfold up_filter_antitone[THEN sym]) (simp add: Abs_dense_inverse less_eq_dense.rep_eq)\n\ntext \\<open>\nThe filters of dense elements of a Stone algebra form a bounded distributive lattice.\n\\<close>\n\ntype_synonym 'a dense_filter = \"'a dense filter\"\n\ntypedef (overloaded) 'a dense_filter_type = \"{ x::'a dense_filter . True }\"\n  using filter_top by blast\n\nsetup_lifting type_definition_dense_filter_type\n\ninstantiation dense_filter_type :: (stone_algebra) bounded_distrib_lattice\nbegin\n\nlift_definition sup_dense_filter_type :: \"'a dense_filter_type \\<Rightarrow> 'a dense_filter_type \\<Rightarrow> 'a dense_filter_type\" is sup .\n\nlift_definition inf_dense_filter_type :: \"'a dense_filter_type \\<Rightarrow> 'a dense_filter_type \\<Rightarrow> 'a dense_filter_type\" is inf .\n\nlift_definition bot_dense_filter_type :: \"'a dense_filter_type\" is bot ..\n\nlift_definition top_dense_filter_type :: \"'a dense_filter_type\" is top ..\n\nlift_definition less_eq_dense_filter_type :: \"'a dense_filter_type \\<Rightarrow> 'a dense_filter_type \\<Rightarrow> bool\" is less_eq .\n\nlift_definition less_dense_filter_type :: \"'a dense_filter_type \\<Rightarrow> 'a dense_filter_type \\<Rightarrow> bool\" is less .\n\ninstance\n  apply intro_classes\n  subgoal apply transfer by (simp add: inf.less_le_not_le)\n  subgoal apply transfer by simp\n  subgoal apply transfer by simp\n  subgoal apply transfer by simp\n  subgoal apply transfer by simp\n  subgoal apply transfer by simp\n  subgoal apply transfer by simp\n  subgoal apply transfer by simp\n  subgoal apply transfer by simp\n  subgoal apply transfer by simp\n  subgoal apply transfer by simp\n  subgoal apply transfer by simp\n  subgoal apply transfer by (simp add: sup_inf_distrib1)\n  done\n\nend\n\nsubsubsection \\<open>The Structure Map\\<close>\n\ntext \\<open>\nThe structure map of a Stone algebra is a bounded lattice homomorphism.\nIt maps a regular element \\<open>x\\<close> to the set of all dense elements above \\<open>-x\\<close>.\nThis set is a filter.\n\\<close>\n\nabbreviation stone_phi_base :: \"'a::stone_algebra regular \\<Rightarrow> 'a dense set\"\n  where \"stone_phi_base x \\<equiv> { y . -Rep_regular x \\<le> Rep_dense y }\"\n\nlemma stone_phi_base_filter:\n  \"filter (stone_phi_base x)\"\n  apply (unfold filter_def, intro conjI)\n  apply (metis Collect_empty_eq top_dense.rep_eq top_greatest)\n  apply (metis inf_dense.rep_eq inf_le2 le_inf_iff mem_Collect_eq)\n  using order_trans less_eq_dense.rep_eq by blast\n\ndefinition stone_phi :: \"'a::stone_algebra regular \\<Rightarrow> 'a dense_filter\"\n  where \"stone_phi x = Abs_filter (stone_phi_base x)\"\n\ntext \\<open>\nTo show that we obtain a triple, we only need to prove that \\<open>stone_phi\\<close> is a bounded lattice homomorphism.\nThe Boolean algebra and the distributive lattice requirements are taken care of by the type system.\n\\<close>\n\ninterpretation stone_phi: triple \"stone_phi\"\nproof (unfold_locales, intro conjI)\n  have 1: \"Rep_regular (Abs_regular bot) = bot\"\n    by (metis bot_regular.rep_eq bot_regular_def)\n  show \"stone_phi bot = bot\"\n    apply (unfold stone_phi_def bot_regular_def 1 p_bot bot_filter_def)\n    by (metis (mono_tags, lifting) Collect_cong Rep_dense_inject order_refl singleton_conv top.extremum_uniqueI top_dense.rep_eq)\nnext\n  show \"stone_phi top = top\"\n    by (metis Collect_cong stone_phi_def UNIV_I bot.extremum dense_closed_top top_empty_eq top_filter.abs_eq top_regular.rep_eq top_set_def)\nnext\n  show \"\\<forall>x y::'a regular . stone_phi (x \\<squnion> y) = stone_phi x \\<squnion> stone_phi y\"\n  proof (intro allI)\n    fix x y :: \"'a regular\"\n    have \"stone_phi_base (x \\<squnion> y) = filter_sup (stone_phi_base x) (stone_phi_base y)\"\n    proof (rule set_eqI, rule iffI)\n      fix z\n      assume 2: \"z \\<in> stone_phi_base (x \\<squnion> y)\"\n      let ?t = \"-Rep_regular x \\<squnion> Rep_dense z\"\n      let ?u = \"-Rep_regular y \\<squnion> Rep_dense z\"\n      let ?v = \"Abs_dense ?t\"\n      let ?w = \"Abs_dense ?u\"\n      have 3: \"?v \\<in> stone_phi_base x \\<and> ?w \\<in> stone_phi_base y\"\n        by (simp add: Abs_dense_inverse)\n      have \"?v \\<sqinter> ?w = Abs_dense (?t \\<sqinter> ?u)\"\n        by (simp add: eq_onp_def inf_dense.abs_eq)\n      also have \"... = Abs_dense (-Rep_regular (x \\<squnion> y) \\<squnion> Rep_dense z)\"\n        by (simp add: distrib(1) sup_commute sup_regular.rep_eq)\n      also have \"... = Abs_dense (Rep_dense z)\"\n        using 2 by (simp add: le_iff_sup)\n      also have \"... = z\"\n        by (simp add: Rep_dense_inverse)\n      finally show \"z \\<in> filter_sup (stone_phi_base x) (stone_phi_base y)\"\n        using 3 mem_Collect_eq order_refl filter_sup_def by fastforce\n    next\n      fix z\n      assume \"z \\<in> filter_sup (stone_phi_base x) (stone_phi_base y)\"\n      then obtain v w where 4: \"v \\<in> stone_phi_base x \\<and> w \\<in> stone_phi_base y \\<and> v \\<sqinter> w \\<le> z\"\n        unfolding filter_sup_def by auto\n      have \"-Rep_regular (x \\<squnion> y) = Rep_regular (-(x \\<squnion> y))\"\n        by (metis uminus_regular.rep_eq)\n      also have \"... = -Rep_regular x \\<sqinter> -Rep_regular y\"\n        by (simp add: inf_regular.rep_eq uminus_regular.rep_eq)\n      also have \"... \\<le> Rep_dense v \\<sqinter> Rep_dense w\"\n        using 4 inf_mono mem_Collect_eq by blast\n      also have \"... = Rep_dense (v \\<sqinter> w)\"\n        by (simp add: inf_dense.rep_eq)\n      also have \"... \\<le> Rep_dense z\"\n        using 4 by (simp add: less_eq_dense.rep_eq)\n      finally show \"z \\<in> stone_phi_base (x \\<squnion> y)\"\n        by simp\n    qed\n    thus \"stone_phi (x \\<squnion> y) = stone_phi x \\<squnion> stone_phi y\"\n      by (simp add: stone_phi_def eq_onp_same_args stone_phi_base_filter sup_filter.abs_eq)\n  qed\nnext\n  show \"\\<forall>x y::'a regular . stone_phi (x \\<sqinter> y) = stone_phi x \\<sqinter> stone_phi y\"\n  proof (intro allI)\n    fix x y :: \"'a regular\"\n    have \"\\<forall>z . -Rep_regular (x \\<sqinter> y) \\<le> Rep_dense z \\<longleftrightarrow> -Rep_regular x \\<le> Rep_dense z \\<and> -Rep_regular y \\<le> Rep_dense z\"\n      by (simp add: inf_regular.rep_eq)\n    hence \"stone_phi_base (x \\<sqinter> y) = (stone_phi_base x) \\<inter> (stone_phi_base y)\"\n      by auto\n    thus \"stone_phi (x \\<sqinter> y) = stone_phi x \\<sqinter> stone_phi y\"\n      by (simp add: stone_phi_def eq_onp_same_args stone_phi_base_filter inf_filter.abs_eq)\n  qed\nqed\n\nsubsection \\<open>Properties of Triples\\<close>\n\ntext \\<open>\nIn this section we construct a certain set of pairs from a triple, introduce operations on these pairs and develop their properties.\nThe given set and operations will form a Stone algebra.\n\\<close>\n\ncontext triple\nbegin\n\nlemma phi_bot:\n  \"phi bot = Abs_filter {top}\"\n  by (metis hom bot_filter_def)\n\nlemma phi_top:\n  \"phi top = Abs_filter UNIV\"\n  by (metis hom top_filter_def)\n\ntext \\<open>\nThe occurrence of \\<open>phi\\<close> in the following definition of the pairs creates a need for dependent types.\n\\<close>\n\ndefinition pairs :: \"('a \\<times> 'b filter) set\"\n  where \"pairs = { (x,y) . \\<exists>z . y = phi (-x) \\<squnion> up_filter z }\"\n\ntext \\<open>\nOperations on pairs are defined in the following.\nThey will be used to establish that the pairs form a Stone algebra.\n\\<close>\n\nfun pairs_less_eq :: \"('a \\<times> 'b filter) \\<Rightarrow> ('a \\<times> 'b filter) \\<Rightarrow> bool\"\n  where \"pairs_less_eq (x,y) (z,w) = (x \\<le> z \\<and> w \\<le> y)\"\n\nfun pairs_less :: \"('a \\<times> 'b filter) \\<Rightarrow> ('a \\<times> 'b filter) \\<Rightarrow> bool\"\n  where \"pairs_less (x,y) (z,w) = (pairs_less_eq (x,y) (z,w) \\<and> \\<not> pairs_less_eq (z,w) (x,y))\"\n\nfun pairs_sup :: \"('a \\<times> 'b filter) \\<Rightarrow> ('a \\<times> 'b filter) \\<Rightarrow> ('a \\<times> 'b filter)\"\n  where \"pairs_sup (x,y) (z,w) = (x \\<squnion> z,y \\<sqinter> w)\"\n\nfun pairs_inf :: \"('a \\<times> 'b filter) \\<Rightarrow> ('a \\<times> 'b filter) \\<Rightarrow> ('a \\<times> 'b filter)\"\n  where \"pairs_inf (x,y) (z,w) = (x \\<sqinter> z,y \\<squnion> w)\"\n\nfun pairs_minus :: \"('a \\<times> 'b filter) \\<Rightarrow> ('a \\<times> 'b filter) \\<Rightarrow> ('a \\<times> 'b filter)\"\n  where \"pairs_minus (x,y) (z,w) = (x \\<sqinter> -z,y \\<squnion> phi z)\"\n\nfun pairs_uminus :: \"('a \\<times> 'b filter) \\<Rightarrow> ('a \\<times> 'b filter)\"\n  where \"pairs_uminus (x,y) = (-x,phi x)\"\n\nabbreviation pairs_bot :: \"('a \\<times> 'b filter)\"\n  where \"pairs_bot \\<equiv> (bot,Abs_filter UNIV)\"\n\nabbreviation pairs_top :: \"('a \\<times> 'b filter)\"\n  where \"pairs_top \\<equiv> (top,Abs_filter {top})\"\n\nlemma pairs_top_in_set:\n  \"(x,y) \\<in> pairs \\<Longrightarrow> top \\<in> Rep_filter y\"\n  by simp\n\nlemma phi_complemented:\n  \"complement (phi x) (phi (-x))\"\n  by (metis hom inf_compl_bot sup_compl_top)\n\nlemma phi_inf_principal:\n  \"\\<exists>z . up_filter z = phi x \\<sqinter> up_filter y\"\nproof -\n  let ?F = \"Rep_filter (phi x)\"\n  let ?G = \"Rep_filter (phi (-x))\"\n  have 1: \"eq_onp filter ?F ?F \\<and> eq_onp filter (\\<up>y) (\\<up>y)\"\n    by (simp add: eq_onp_def)\n  have \"filter_complements ?F ?G\"\n    apply (intro conjI)\n    apply simp\n    apply simp\n    apply (metis (no_types) phi_complemented sup_filter.rep_eq top_filter.rep_eq)\n    by (metis (no_types) phi_complemented inf_filter.rep_eq bot_filter.rep_eq)\n  hence \"is_principal_up (?F \\<inter> \\<up>y)\"\n    using complemented_filter_inf_principal by blast\n  then obtain z where \"\\<up>z = ?F \\<inter> \\<up>y\"\n    by auto\n  hence \"up_filter z = Abs_filter (?F \\<inter> \\<up>y)\"\n    by simp\n  also have \"... = Abs_filter ?F \\<sqinter> up_filter y\"\n    using 1 inf_filter.abs_eq by force\n  also have \"... = phi x \\<sqinter> up_filter y\"\n    by (simp add: Rep_filter_inverse)\n  finally show ?thesis\n    by auto\nqed\n\ntext \\<open>\nQuite a bit of filter theory is involved in showing that the intersection of \\<open>phi x\\<close> with a principal filter is a principal filter, so the following function can extract its least element.\n\\<close>\n\nfun rho :: \"'a \\<Rightarrow> 'b \\<Rightarrow> 'b\"\n  where \"rho x y = (SOME z . up_filter z = phi x \\<sqinter> up_filter y)\"\n\n\n\ntext \\<open>\nThe following results show that the pairs are closed under the given operations.\n\\<close>\n\nlemma pairs_sup_closed:\n  assumes \"(x,y) \\<in> pairs\"\n      and \"(z,w) \\<in> pairs\"\n    shows \"pairs_sup (x,y) (z,w) \\<in> pairs\"\nproof -\n  from assms obtain u v where \"y = phi (-x) \\<squnion> up_filter u \\<and> w = phi (-z) \\<squnion> up_filter v\"\n    using pairs_def by auto\n  hence \"pairs_sup (x,y) (z,w) = (x \\<squnion> z,(phi (-x) \\<squnion> up_filter u) \\<sqinter> (phi (-z) \\<squnion> up_filter v))\"\n    by simp\n  also have \"... = (x \\<squnion> z,(phi (-x) \\<sqinter> phi (-z)) \\<squnion> (phi (-x) \\<sqinter> up_filter v) \\<squnion> (up_filter u \\<sqinter> phi (-z)) \\<squnion> (up_filter u \\<sqinter> up_filter v))\"\n    by (simp add: inf.sup_commute inf_sup_distrib1 sup_commute sup_left_commute)\n  also have \"... = (x \\<squnion> z,phi (-(x \\<squnion> z)) \\<squnion> (phi (-x) \\<sqinter> up_filter v) \\<squnion> (up_filter u \\<sqinter> phi (-z)) \\<squnion> (up_filter u \\<sqinter> up_filter v))\"\n    using hom by simp\n  also have \"... = (x \\<squnion> z,phi (-(x \\<squnion> z)) \\<squnion> up_filter (rho (-x) v) \\<squnion> up_filter (rho (-z) u) \\<squnion> (up_filter u \\<sqinter> up_filter v))\"\n    by (metis inf.sup_commute rho_char)\n  also have \"... = (x \\<squnion> z,phi (-(x \\<squnion> z)) \\<squnion> up_filter (rho (-x) v) \\<squnion> up_filter (rho (-z) u) \\<squnion> up_filter (u \\<squnion> v))\"\n    by (metis up_filter_dist_sup)\n  also have \"... = (x \\<squnion> z,phi (-(x \\<squnion> z)) \\<squnion> up_filter (rho (-x) v \\<sqinter> rho (-z) u \\<sqinter> (u \\<squnion> v)))\"\n    by (simp add: sup_commute sup_left_commute up_filter_dist_inf)\n  finally show ?thesis\n    using pairs_def by auto\nqed\n\nlemma pairs_inf_closed:\n  assumes \"(x,y) \\<in> pairs\"\n      and \"(z,w) \\<in> pairs\"\n    shows \"pairs_inf (x,y) (z,w) \\<in> pairs\"\nproof -\n  from assms obtain u v where \"y = phi (-x) \\<squnion> up_filter u \\<and> w = phi (-z) \\<squnion> up_filter v\"\n    using pairs_def by auto\n  hence \"pairs_inf (x,y) (z,w) = (x \\<sqinter> z,(phi (-x) \\<squnion> up_filter u) \\<squnion> (phi (-z) \\<squnion> up_filter v))\"\n    by simp\n  also have \"... = (x \\<sqinter> z,(phi (-x) \\<squnion> phi (-z)) \\<squnion> (up_filter u \\<squnion> up_filter v))\"\n    by (simp add: sup_commute sup_left_commute)\n  also have \"... = (x \\<sqinter> z,phi (-(x \\<sqinter> z)) \\<squnion> (up_filter u \\<squnion> up_filter v))\"\n    using hom by simp\n  also have \"... = (x \\<sqinter> z,phi (-(x \\<sqinter> z)) \\<squnion> up_filter (u \\<sqinter> v))\"\n    by (simp add: up_filter_dist_inf)\n  finally show ?thesis\n    using pairs_def by auto\nqed\n\nlemma pairs_uminus_closed:\n  \"pairs_uminus (x,y) \\<in> pairs\"\nproof -\n  have \"pairs_uminus (x,y) = (-x,phi (--x) \\<squnion> bot)\"\n    by simp\n  also have \"... = (-x,phi (--x) \\<squnion> up_filter top)\"\n    by (simp add: bot_filter.abs_eq)\n  finally show ?thesis\n    by (metis (mono_tags, lifting) mem_Collect_eq old.prod.case pairs_def)\nqed\n\nlemma pairs_bot_closed:\n  \"pairs_bot \\<in> pairs\"\n  using pairs_def phi_top triple.hom triple_axioms by fastforce\n\nlemma pairs_top_closed:\n  \"pairs_top \\<in> pairs\"\n  by (metis p_bot pairs_uminus.simps pairs_uminus_closed phi_bot)\n\ntext \\<open>\nWe prove enough properties of the pair operations so that we can later show they form a Stone algebra.\n\\<close>\n\nlemma pairs_sup_dist_inf:\n  \"(x,y) \\<in> pairs \\<Longrightarrow> (z,w) \\<in> pairs \\<Longrightarrow> (u,v) \\<in> pairs \\<Longrightarrow> pairs_sup (x,y) (pairs_inf (z,w) (u,v)) = pairs_inf (pairs_sup (x,y) (z,w)) (pairs_sup (x,y) (u,v))\"\n  using sup_inf_distrib1 inf_sup_distrib1 by auto\n\nlemma pairs_phi_less_eq:\n  \"(x,y) \\<in> pairs \\<Longrightarrow> phi (-x) \\<le> y\"\n  using pairs_def by auto\n\nlemma pairs_uminus_galois:\n  assumes \"(x,y) \\<in> pairs\"\n      and \"(z,w) \\<in> pairs\"\n    shows \"pairs_inf (x,y) (z,w) = pairs_bot \\<longleftrightarrow> pairs_less_eq (x,y) (pairs_uminus (z,w))\"\nproof -\n  have 1: \"x \\<sqinter> z = bot \\<and> y \\<squnion> w = Abs_filter UNIV \\<longrightarrow> phi z \\<le> y\"\n    by (metis (no_types, lifting) assms(1) heyting.implies_inf_absorb hom le_supE pairs_phi_less_eq sup_bot_right)\n  have 2: \"x \\<le> -z \\<and> phi z \\<le> y \\<longrightarrow> y \\<squnion> w = Abs_filter UNIV\"\n  proof\n    assume 3: \"x \\<le> -z \\<and> phi z \\<le> y\"\n    have \"Abs_filter UNIV = phi z \\<squnion> phi (-z)\"\n      using hom phi_complemented phi_top by auto\n    also have \"... \\<le> y \\<squnion> w\"\n      using 3 assms(2) sup_mono pairs_phi_less_eq by auto\n    finally show \"y \\<squnion> w = Abs_filter UNIV\"\n      using hom phi_top top.extremum_uniqueI by auto\n  qed\n  have \"x \\<sqinter> z = bot \\<longleftrightarrow> x \\<le> -z\"\n    by (simp add: shunting_1)\n  thus ?thesis\n    using 1 2 Pair_inject pairs_inf.simps pairs_less_eq.simps pairs_uminus.simps by auto\nqed\n\nlemma pairs_stone:\n  \"(x,y) \\<in> pairs \\<Longrightarrow> pairs_sup (pairs_uminus (x,y)) (pairs_uminus (pairs_uminus (x,y))) = pairs_top\"\n  by (metis hom pairs_sup.simps pairs_uminus.simps phi_bot phi_complemented stone)\n\ntext \\<open>\nThe following results show how the regular elements and the dense elements among the pairs look like.\n\\<close>\n\nabbreviation \"dense_pairs \\<equiv> { (x,y) . (x,y) \\<in> pairs \\<and> pairs_uminus (x,y) = pairs_bot }\"\nabbreviation \"regular_pairs \\<equiv> { (x,y) . (x,y) \\<in> pairs \\<and> pairs_uminus (pairs_uminus (x,y)) = (x,y) }\"\nabbreviation \"is_principal_up_filter x \\<equiv> \\<exists>y . x = up_filter y\"\n\nlemma dense_pairs:\n  \"dense_pairs = { (x,y) . x = top \\<and> is_principal_up_filter y }\"\nproof -\n  have \"dense_pairs = { (x,y) . (x,y) \\<in> pairs \\<and> x = top }\"\n    by (metis Pair_inject compl_bot_eq double_compl pairs_uminus.simps phi_top)\n  also have \"... = { (x,y) . (\\<exists>z . y = up_filter z) \\<and> x = top }\"\n    using hom pairs_def by auto\n  finally show ?thesis\n    by auto\nqed\n\nlemma regular_pairs:\n  \"regular_pairs = { (x,y) . y = phi (-x) }\"\n  using pairs_def pairs_uminus_closed by fastforce\n\ntext \\<open>\nThe following extraction function will be used in defining one direction of the Stone algebra isomorphism.\n\\<close>\n\nfun rho_pair :: \"'a \\<times> 'b filter \\<Rightarrow> 'b\"\n  where \"rho_pair (x,y) = (SOME z . up_filter z = phi x \\<sqinter> y)\"\n\nlemma get_rho_pair_char:\n  assumes \"(x,y) \\<in> pairs\"\n    shows \"up_filter (rho_pair (x,y)) = phi x \\<sqinter> y\"\nproof -\n  from assms obtain w where \"y = phi (-x) \\<squnion> up_filter w\"\n    using pairs_def by auto\n  hence \"phi x \\<sqinter> y = phi x \\<sqinter> up_filter w\"\n    by (simp add: inf_sup_distrib1 phi_complemented)\n  thus ?thesis\n    using rho_char by auto\nqed\n\nlemma sa_iso_pair:\n  \"(--x,phi (-x) \\<squnion> up_filter y) \\<in> pairs\"\n  using pairs_def by auto\n\nend\n\nsubsection \\<open>The Stone Algebra of a Triple\\<close>\n\ntext \\<open>\nIn this section we prove that the set of pairs constructed in a triple forms a Stone Algebra.\nThe following type captures the parameter \\<open>phi\\<close> on which the type of triples depends.\nThis parameter is the structure map that occurs in the definition of the set of pairs.\nThe set of all structure maps is the set of all bounded lattice homomorphisms (of appropriate type).\nIn order to make it a HOL type, we need to show that at least one such structure map exists.\nTo this end we use the ultrafilter lemma: the required bounded lattice homomorphism is essentially the characteristic map of an ultrafilter, but the latter must exist.\nIn particular, the underlying Boolean algebra must contain at least two elements.\n\\<close>\n\ntypedef (overloaded) ('a,'b) phi = \"{ f::'a::non_trivial_boolean_algebra \\<Rightarrow> 'b::distrib_lattice_top filter . bounded_lattice_homomorphism f }\"\nproof -\n  from ultra_filter_exists obtain F :: \"'a set\" where 1: \"ultra_filter F\"\n    by auto\n  hence 2: \"prime_filter F\"\n    using ultra_filter_prime by auto\n  let ?f = \"\\<lambda>x . if x\\<in>F then top else bot::'b filter\"\n  have \"bounded_lattice_homomorphism ?f\"\n  proof (intro conjI)\n    show \"?f bot = bot\"\n      using 1 by (meson bot.extremum filter_def subset_eq top.extremum_unique)\n  next\n    show \"?f top = top\"\n      using 1 by simp\n  next\n    show \"\\<forall>x y . ?f (x \\<squnion> y) = ?f x \\<squnion> ?f y\"\n    proof (intro allI)\n      fix x y\n      show \"?f (x \\<squnion> y) = ?f x \\<squnion> ?f y\"\n        apply (cases \"x \\<in> F\"; cases \"y \\<in> F\")\n        using 1 filter_def apply fastforce\n        using 1 filter_def apply fastforce\n        using 1 filter_def apply fastforce\n        using 2 sup_bot_left by auto\n   qed\n  next\n    show \"\\<forall>x y . ?f (x \\<sqinter> y) = ?f x \\<sqinter> ?f y\"\n    proof (intro allI)\n      fix x y\n      show \"?f (x \\<sqinter> y) = ?f x \\<sqinter> ?f y\"\n        apply (cases \"x \\<in> F\"; cases \"y \\<in> F\")\n        using 1 apply (simp add: filter_inf_closed)\n        using 1 apply (metis (mono_tags, lifting) brouwer.inf_sup_ord(4) inf_top_left filter_def)\n        using 1 apply (metis (mono_tags, lifting) brouwer.inf_sup_ord(3) inf_top_right filter_def)\n        using 1 filter_def by force\n    qed\n  qed\n  hence \"?f \\<in> {f . bounded_lattice_homomorphism f}\"\n    by simp\n  thus ?thesis\n    by meson\nqed\n\nlemma simp_phi [simp]:\n  \"bounded_lattice_homomorphism (Rep_phi x)\"\n  using Rep_phi by simp\n\nsetup_lifting type_definition_phi\n\ntext \\<open>\nThe following implements the dependent type of pairs depending on structure maps.\nIt uses functions from structure maps to pairs with the requirement that, for each structure map, the corresponding pair is contained in the set of pairs constructed for a triple with that structure map.\n\nIf this type could be defined in the locale \\<open>triple\\<close> and instantiated to Stone algebras there, there would be no need for the lifting and we could work with triples directly.\n\\<close>\n\ntypedef (overloaded) ('a,'b) lifted_pair = \"{ pf::('a::non_trivial_boolean_algebra,'b::distrib_lattice_top) phi \\<Rightarrow> 'a \\<times> 'b filter . \\<forall>f . pf f \\<in> triple.pairs (Rep_phi f) }\"\nproof -\n  have \"\\<forall>f::('a,'b) phi . triple.pairs_bot \\<in> triple.pairs (Rep_phi f)\"\n  proof\n    fix f :: \"('a,'b) phi\"\n    have \"triple (Rep_phi f)\"\n      by (simp add: triple_def)\n    thus \"triple.pairs_bot \\<in> triple.pairs (Rep_phi f)\"\n      using triple.regular_pairs triple.phi_top by fastforce\n  qed\n  thus ?thesis\n    by auto\nqed\n\nlemma simp_lifted_pair [simp]:\n  \"\\<forall>f . Rep_lifted_pair pf f \\<in> triple.pairs (Rep_phi f)\"\n  using Rep_lifted_pair by simp\n\nsetup_lifting type_definition_lifted_pair\n\ntext \\<open>\nThe lifted pairs form a Stone algebra.\n\\<close>\n\ninstantiation lifted_pair :: (non_trivial_boolean_algebra,distrib_lattice_top) stone_algebra\nbegin\n\ntext \\<open>\nAll operations are lifted point-wise.\n\\<close>\n\nlift_definition sup_lifted_pair :: \"('a,'b) lifted_pair \\<Rightarrow> ('a,'b) lifted_pair \\<Rightarrow> ('a,'b) lifted_pair\" is \"\\<lambda>xf yf f . triple.pairs_sup (xf f) (yf f)\"\n  by (metis (no_types, hide_lams) simp_phi triple_def triple.pairs_sup_closed prod.collapse)\n\nlift_definition inf_lifted_pair :: \"('a,'b) lifted_pair \\<Rightarrow> ('a,'b) lifted_pair \\<Rightarrow> ('a,'b) lifted_pair\" is \"\\<lambda>xf yf f . triple.pairs_inf (xf f) (yf f)\"\n  by (metis (no_types, hide_lams) simp_phi triple_def triple.pairs_inf_closed prod.collapse)\n\nlift_definition uminus_lifted_pair :: \"('a,'b) lifted_pair \\<Rightarrow> ('a,'b) lifted_pair\" is \"\\<lambda>xf f . triple.pairs_uminus (Rep_phi f) (xf f)\"\n  by (metis (no_types, hide_lams) simp_phi triple_def triple.pairs_uminus_closed prod.collapse)\n\nlift_definition bot_lifted_pair :: \"('a,'b) lifted_pair\" is \"\\<lambda>f . triple.pairs_bot\"\n  by (metis (no_types, hide_lams) simp_phi triple_def triple.pairs_bot_closed)\n\nlift_definition top_lifted_pair :: \"('a,'b) lifted_pair\" is \"\\<lambda>f . triple.pairs_top\"\n  by (metis (no_types, hide_lams) simp_phi triple_def triple.pairs_top_closed)\n\nlift_definition less_eq_lifted_pair :: \"('a,'b) lifted_pair \\<Rightarrow> ('a,'b) lifted_pair \\<Rightarrow> bool\" is \"\\<lambda>xf yf . \\<forall>f . triple.pairs_less_eq (xf f) (yf f)\" .\n\nlift_definition less_lifted_pair :: \"('a,'b) lifted_pair \\<Rightarrow> ('a,'b) lifted_pair \\<Rightarrow> bool\" is \"\\<lambda>xf yf . (\\<forall>f . triple.pairs_less_eq (xf f) (yf f)) \\<and> \\<not> (\\<forall>f . triple.pairs_less_eq (yf f) (xf f))\" .\n\ninstance\nproof intro_classes\n  fix xf yf :: \"('a,'b) lifted_pair\"\n  show \"xf < yf \\<longleftrightarrow> xf \\<le> yf \\<and> \\<not> yf \\<le> xf\"\n    by (simp add: less_lifted_pair.rep_eq less_eq_lifted_pair.rep_eq)\nnext\n  fix xf :: \"('a,'b) lifted_pair\"\n  {\n    fix f :: \"('a,'b) phi\"\n    have 1: \"triple (Rep_phi f)\"\n      by (simp add: triple_def)\n    let ?x = \"Rep_lifted_pair xf f\"\n    obtain x1 x2 where \"(x1,x2) = ?x\"\n      using prod.collapse by blast\n    hence \"triple.pairs_less_eq ?x ?x\"\n      using 1 by (metis triple.pairs_less_eq.simps order_refl)\n  }\n  thus \"xf \\<le> xf\"\n    by (simp add: less_eq_lifted_pair.rep_eq)\nnext\n  fix xf yf zf :: \"('a,'b) lifted_pair\"\n  assume 1: \"xf \\<le> yf\" and 2: \"yf \\<le> zf\"\n  {\n    fix f :: \"('a,'b) phi\"\n    have 3: \"triple (Rep_phi f)\"\n      by (simp add: triple_def)\n    let ?x = \"Rep_lifted_pair xf f\"\n    let ?y = \"Rep_lifted_pair yf f\"\n    let ?z = \"Rep_lifted_pair zf f\"\n    obtain x1 x2 y1 y2 z1 z2 where 4: \"(x1,x2) = ?x \\<and> (y1,y2) = ?y \\<and> (z1,z2) = ?z\"\n      using prod.collapse by blast\n    have \"triple.pairs_less_eq ?x ?y \\<and> triple.pairs_less_eq ?y ?z\"\n      using 1 2 3 less_eq_lifted_pair.rep_eq by simp\n    hence \"triple.pairs_less_eq ?x ?z\"\n      using 3 4 by (metis (mono_tags, lifting) triple.pairs_less_eq.simps order_trans)\n  }\n  thus \"xf \\<le> zf\"\n    by (simp add: less_eq_lifted_pair.rep_eq)\nnext\n  fix xf yf :: \"('a,'b) lifted_pair\"\n  assume 1: \"xf \\<le> yf\" and 2: \"yf \\<le> xf\"\n  {\n    fix f :: \"('a,'b) phi\"\n    have 3: \"triple (Rep_phi f)\"\n      by (simp add: triple_def)\n    let ?x = \"Rep_lifted_pair xf f\"\n    let ?y = \"Rep_lifted_pair yf f\"\n    obtain x1 x2 y1 y2 where 4: \"(x1,x2) = ?x \\<and> (y1,y2) = ?y\"\n      using prod.collapse by blast\n    have \"triple.pairs_less_eq ?x ?y \\<and> triple.pairs_less_eq ?y ?x\"\n      using 1 2 3 less_eq_lifted_pair.rep_eq by simp\n    hence \"?x = ?y\"\n      using 3 4 by (metis (mono_tags, lifting) triple.pairs_less_eq.simps antisym)\n  }\n  thus \"xf = yf\"\n    by (metis Rep_lifted_pair_inverse ext)\nnext\n  fix xf yf :: \"('a,'b) lifted_pair\"\n  {\n    fix f :: \"('a,'b) phi\"\n    have 1: \"triple (Rep_phi f)\"\n      by (simp add: triple_def)\n    let ?x = \"Rep_lifted_pair xf f\"\n    let ?y = \"Rep_lifted_pair yf f\"\n    obtain x1 x2 y1 y2 where \"(x1,x2) = ?x \\<and> (y1,y2) = ?y\"\n      using prod.collapse by blast\n    hence \"triple.pairs_less_eq (triple.pairs_inf ?x ?y) ?y\"\n      using 1 by (metis (mono_tags, lifting) inf_sup_ord(2) sup.cobounded2 triple.pairs_inf.simps triple.pairs_less_eq.simps inf_lifted_pair.rep_eq)\n  }\n  thus \"xf \\<sqinter> yf \\<le> yf\"\n    by (simp add: less_eq_lifted_pair.rep_eq inf_lifted_pair.rep_eq)\nnext\n  fix xf yf :: \"('a,'b) lifted_pair\"\n  {\n    fix f :: \"('a,'b) phi\"\n    have 1: \"triple (Rep_phi f)\"\n      by (simp add: triple_def)\n    let ?x = \"Rep_lifted_pair xf f\"\n    let ?y = \"Rep_lifted_pair yf f\"\n    obtain x1 x2 y1 y2 where \"(x1,x2) = ?x \\<and> (y1,y2) = ?y\"\n      using prod.collapse by blast\n    hence \"triple.pairs_less_eq (triple.pairs_inf ?x ?y) ?x\"\n      using 1 by (metis (mono_tags, lifting) inf_sup_ord(1) sup.cobounded1 triple.pairs_inf.simps triple.pairs_less_eq.simps inf_lifted_pair.rep_eq)\n  }\n  thus \"xf \\<sqinter> yf \\<le> xf\"\n    by (simp add: less_eq_lifted_pair.rep_eq inf_lifted_pair.rep_eq)\nnext\n  fix xf yf zf :: \"('a,'b) lifted_pair\"\n  assume 1: \"xf \\<le> yf\" and 2: \"xf \\<le> zf\"\n  {\n    fix f :: \"('a,'b) phi\"\n    have 3: \"triple (Rep_phi f)\"\n      by (simp add: triple_def)\n    let ?x = \"Rep_lifted_pair xf f\"\n    let ?y = \"Rep_lifted_pair yf f\"\n    let ?z = \"Rep_lifted_pair zf f\"\n    obtain x1 x2 y1 y2 z1 z2 where 4: \"(x1,x2) = ?x \\<and> (y1,y2) = ?y \\<and> (z1,z2) = ?z\"\n      using prod.collapse by blast\n    have \"triple.pairs_less_eq ?x ?y \\<and> triple.pairs_less_eq ?x ?z\"\n      using 1 2 3 less_eq_lifted_pair.rep_eq by simp\n    hence \"triple.pairs_less_eq ?x (triple.pairs_inf ?y ?z)\"\n      using 3 4 by (metis (mono_tags, lifting) le_inf_iff sup.bounded_iff triple.pairs_inf.simps triple.pairs_less_eq.simps)\n  }\n  thus \"xf \\<le> yf \\<sqinter> zf\"\n    by (simp add: less_eq_lifted_pair.rep_eq inf_lifted_pair.rep_eq)\nnext\n  fix xf yf :: \"('a,'b) lifted_pair\"\n  {\n    fix f :: \"('a,'b) phi\"\n    have 1: \"triple (Rep_phi f)\"\n      by (simp add: triple_def)\n    let ?x = \"Rep_lifted_pair xf f\"\n    let ?y = \"Rep_lifted_pair yf f\"\n    obtain x1 x2 y1 y2 where \"(x1,x2) = ?x \\<and> (y1,y2) = ?y\"\n      using prod.collapse by blast\n    hence \"triple.pairs_less_eq ?x (triple.pairs_sup ?x ?y)\"\n      using 1 by (metis (no_types, lifting) inf_commute sup.cobounded1 inf.cobounded2 triple.pairs_sup.simps triple.pairs_less_eq.simps sup_lifted_pair.rep_eq)\n  }\n  thus \"xf \\<le> xf \\<squnion> yf\"\n    by (simp add: less_eq_lifted_pair.rep_eq sup_lifted_pair.rep_eq)\nnext\n  fix xf yf :: \"('a,'b) lifted_pair\"\n  {\n    fix f :: \"('a,'b) phi\"\n    have 1: \"triple (Rep_phi f)\"\n      by (simp add: triple_def)\n    let ?x = \"Rep_lifted_pair xf f\"\n    let ?y = \"Rep_lifted_pair yf f\"\n    obtain x1 x2 y1 y2 where \"(x1,x2) = ?x \\<and> (y1,y2) = ?y\"\n      using prod.collapse by blast\n    hence \"triple.pairs_less_eq ?y (triple.pairs_sup ?x ?y)\"\n      using 1 by (metis (no_types, lifting) sup.cobounded2 inf.cobounded2 triple.pairs_sup.simps triple.pairs_less_eq.simps sup_lifted_pair.rep_eq)\n  }\n  thus \"yf \\<le> xf \\<squnion> yf\"\n    by (simp add: less_eq_lifted_pair.rep_eq sup_lifted_pair.rep_eq)\nnext\n  fix xf yf zf :: \"('a,'b) lifted_pair\"\n  assume 1: \"yf \\<le> xf\" and 2: \"zf \\<le> xf\"\n  {\n    fix f :: \"('a,'b) phi\"\n    have 3: \"triple (Rep_phi f)\"\n      by (simp add: triple_def)\n    let ?x = \"Rep_lifted_pair xf f\"\n    let ?y = \"Rep_lifted_pair yf f\"\n    let ?z = \"Rep_lifted_pair zf f\"\n    obtain x1 x2 y1 y2 z1 z2 where 4: \"(x1,x2) = ?x \\<and> (y1,y2) = ?y \\<and> (z1,z2) = ?z\"\n      using prod.collapse by blast\n    have \"triple.pairs_less_eq ?y ?x \\<and> triple.pairs_less_eq ?z ?x\"\n      using 1 2 3 less_eq_lifted_pair.rep_eq by simp\n    hence \"triple.pairs_less_eq (triple.pairs_sup ?y ?z) ?x\"\n      using 3 4 by (metis (mono_tags, lifting) le_inf_iff sup.bounded_iff triple.pairs_sup.simps triple.pairs_less_eq.simps)\n  }\n  thus \"yf \\<squnion> zf \\<le> xf\"\n    by (simp add: less_eq_lifted_pair.rep_eq sup_lifted_pair.rep_eq)\nnext\n  fix xf :: \"('a,'b) lifted_pair\"\n  {\n    fix f :: \"('a,'b) phi\"\n    have 1: \"triple (Rep_phi f)\"\n      by (simp add: triple_def)\n    let ?x = \"Rep_lifted_pair xf f\"\n    obtain x1 x2 where \"(x1,x2) = ?x\"\n      using prod.collapse by blast\n    hence \"triple.pairs_less_eq triple.pairs_bot ?x\"\n      using 1 by (metis bot.extremum top_greatest top_filter.abs_eq triple.pairs_less_eq.simps)\n  }\n  thus \"bot \\<le> xf\"\n    by (simp add: less_eq_lifted_pair.rep_eq bot_lifted_pair.rep_eq)\nnext\n  fix xf :: \"('a,'b) lifted_pair\"\n  {\n    fix f :: \"('a,'b) phi\"\n    have 1: \"triple (Rep_phi f)\"\n      by (simp add: triple_def)\n    let ?x = \"Rep_lifted_pair xf f\"\n    obtain x1 x2 where \"(x1,x2) = ?x\"\n      using prod.collapse by blast\n    hence \"triple.pairs_less_eq ?x triple.pairs_top\"\n      using 1 by (metis top.extremum bot_least bot_filter.abs_eq triple.pairs_less_eq.simps)\n  }\n  thus \"xf \\<le> top\"\n    by (simp add: less_eq_lifted_pair.rep_eq top_lifted_pair.rep_eq)\nnext\n  fix xf yf zf :: \"('a,'b) lifted_pair\"\n  {\n    fix f :: \"('a,'b) phi\"\n    have 1: \"triple (Rep_phi f)\"\n      by (simp add: triple_def)\n    let ?x = \"Rep_lifted_pair xf f\"\n    let ?y = \"Rep_lifted_pair yf f\"\n    let ?z = \"Rep_lifted_pair zf f\"\n    obtain x1 x2 y1 y2 z1 z2 where \"(x1,x2) = ?x \\<and> (y1,y2) = ?y \\<and> (z1,z2) = ?z\"\n      using prod.collapse by blast\n    hence \"triple.pairs_sup ?x (triple.pairs_inf ?y ?z) = triple.pairs_inf (triple.pairs_sup ?x ?y) (triple.pairs_sup ?x ?z)\"\n      using 1 by (metis (no_types) sup_inf_distrib1 inf_sup_distrib1 triple.pairs_sup.simps triple.pairs_inf.simps)\n  }\n  thus \"xf \\<squnion> (yf \\<sqinter> zf) = (xf \\<squnion> yf) \\<sqinter> (xf \\<squnion> zf)\"\n    by (metis Rep_lifted_pair_inverse ext sup_lifted_pair.rep_eq inf_lifted_pair.rep_eq)\nnext\n  fix xf yf :: \"('a,'b) lifted_pair\"\n  {\n    fix f :: \"('a,'b) phi\"\n    have 1: \"triple (Rep_phi f)\"\n      by (simp add: triple_def)\n    let ?x = \"Rep_lifted_pair xf f\"\n    let ?y = \"Rep_lifted_pair yf f\"\n    obtain x1 x2 y1 y2 where 2: \"(x1,x2) = ?x \\<and> (y1,y2) = ?y\"\n      using prod.collapse by blast\n    have \"?x \\<in> triple.pairs (Rep_phi f) \\<and> ?y \\<in> triple.pairs (Rep_phi f)\"\n      by simp\n    hence \"(triple.pairs_inf ?x ?y = triple.pairs_bot) \\<longleftrightarrow> triple.pairs_less_eq ?x (triple.pairs_uminus (Rep_phi f) ?y)\"\n      using 1 2 by (metis triple.pairs_uminus_galois)\n  }\n  hence \"\\<forall>f . (Rep_lifted_pair (xf \\<sqinter> yf) f = Rep_lifted_pair bot f) \\<longleftrightarrow> triple.pairs_less_eq (Rep_lifted_pair xf f) (Rep_lifted_pair (-yf) f)\"\n    using bot_lifted_pair.rep_eq inf_lifted_pair.rep_eq uminus_lifted_pair.rep_eq by simp\n  hence \"(Rep_lifted_pair (xf \\<sqinter> yf) = Rep_lifted_pair bot) \\<longleftrightarrow> xf \\<le> -yf\"\n    using less_eq_lifted_pair.rep_eq by auto\n  thus \"(xf \\<sqinter> yf = bot) \\<longleftrightarrow> (xf \\<le> -yf)\"\n    by (simp add: Rep_lifted_pair_inject)\nnext\n  fix xf :: \"('a,'b) lifted_pair\"\n  {\n    fix f :: \"('a,'b) phi\"\n    have 1: \"triple (Rep_phi f)\"\n      by (simp add: triple_def)\n    let ?x = \"Rep_lifted_pair xf f\"\n    obtain x1 x2 where \"(x1,x2) = ?x\"\n      using prod.collapse by blast\n    hence \"triple.pairs_sup (triple.pairs_uminus (Rep_phi f) ?x) (triple.pairs_uminus (Rep_phi f) (triple.pairs_uminus (Rep_phi f) ?x)) = triple.pairs_top\"\n      using 1 by (metis simp_lifted_pair triple.pairs_stone)\n  }\n  hence \"Rep_lifted_pair (-xf \\<squnion> --xf) = Rep_lifted_pair top\"\n    using sup_lifted_pair.rep_eq uminus_lifted_pair.rep_eq top_lifted_pair.rep_eq by simp\n  thus \"-xf \\<squnion> --xf = top\"\n    by (simp add: Rep_lifted_pair_inject)\nqed\n\nend\n\nsubsection \\<open>The Stone Algebra of the Triple of a Stone Algebra\\<close>\n\ntext \\<open>\nIn this section we specialise the above construction to a particular structure map, namely the one obtained in the triple of a Stone algebra.\nFor this particular structure map (as well as for any other particular structure map) the resulting type is no longer a dependent type.\nIt is just the set of pairs obtained for the given structure map.\n\\<close>\n\ntypedef (overloaded) 'a stone_phi_pair = \"triple.pairs (stone_phi::'a::stone_algebra regular \\<Rightarrow> 'a dense_filter)\"\n  using stone_phi.pairs_bot_closed by auto\n\nsetup_lifting type_definition_stone_phi_pair\n\ninstantiation stone_phi_pair :: (stone_algebra) sup_inf_top_bot_uminus_ord\nbegin\n\nlift_definition sup_stone_phi_pair :: \"'a stone_phi_pair \\<Rightarrow> 'a stone_phi_pair \\<Rightarrow> 'a stone_phi_pair\" is triple.pairs_sup\n  using stone_phi.pairs_sup_closed by auto\n\nlift_definition inf_stone_phi_pair :: \"'a stone_phi_pair \\<Rightarrow> 'a stone_phi_pair \\<Rightarrow> 'a stone_phi_pair\" is triple.pairs_inf\n  using stone_phi.pairs_inf_closed by auto\n\nlift_definition uminus_stone_phi_pair :: \"'a stone_phi_pair \\<Rightarrow> 'a stone_phi_pair\" is \"triple.pairs_uminus stone_phi\"\n  using stone_phi.pairs_uminus_closed by auto\n\nlift_definition bot_stone_phi_pair :: \"'a stone_phi_pair\" is \"triple.pairs_bot\"\n  by (rule stone_phi.pairs_bot_closed)\n\nlift_definition top_stone_phi_pair :: \"'a stone_phi_pair\" is \"triple.pairs_top\"\n  by (rule stone_phi.pairs_top_closed)\n\nlift_definition less_eq_stone_phi_pair :: \"'a stone_phi_pair \\<Rightarrow> 'a stone_phi_pair \\<Rightarrow> bool\" is triple.pairs_less_eq .\n\nlift_definition less_stone_phi_pair :: \"'a stone_phi_pair \\<Rightarrow> 'a stone_phi_pair \\<Rightarrow> bool\" is triple.pairs_less .\n\ninstance ..\n\nend\n\n(*\ninstantiation stone_phi_pair :: (stone_algebra) stone_algebra\nbegin\n\ninstance\n  apply intro_classes\n  subgoal apply transfer by auto\n  subgoal apply transfer by auto\n  subgoal apply transfer by auto\n  subgoal apply transfer by auto\n  subgoal apply transfer by auto\n  subgoal apply transfer by auto\n  subgoal apply transfer by auto\n  subgoal apply transfer by auto\n  subgoal apply transfer by auto\n  subgoal apply transfer by auto\n  subgoal apply transfer by (metis (no_types, lifting) Pair_inject compl_bot_eq heyting.implies_order stone_phi.pairs_less_eq.elims(3) stone_phi.phi_top stone_phi.triple_axioms sup_top_left top_greatest triple_def)\n  subgoal apply transfer by (metis (no_types, lifting) Pair_inject stone_phi.pairs_less_eq.elims(3) top.extremum bot_least bot_filter.abs_eq)\n  subgoal apply transfer using stone_phi.triple_axioms triple.pairs_sup_dist_inf by fastforce\n  subgoal apply transfer using stone_phi.pairs_uminus_galois by fastforce\n  subgoal apply transfer using stone_phi.pairs_stone by fastforce\n  done\n\nend\n*)\n\ntext \\<open>\nThe result is a Stone algebra and could be proved so by repeating and specialising the above proof for lifted pairs.\nWe choose a different approach, namely by embedding the type of pairs into the lifted type.\nThe embedding injects a pair \\<open>x\\<close> into a function as the value at the given structure map; this makes the embedding injective.\nThe value of the function at any other structure map needs to be carefully chosen so that the resulting function is a Stone algebra homomorphism.\nWe use \\<open>--x\\<close>, which is essentially a projection to the regular element component of \\<open>x\\<close>, whence the image has the structure of a Boolean algebra.\n\\<close>\n\nfun stone_phi_embed :: \"'a::non_trivial_stone_algebra stone_phi_pair \\<Rightarrow> ('a regular,'a dense) lifted_pair\"\n  where \"stone_phi_embed x = Abs_lifted_pair (\\<lambda>f . if Rep_phi f = stone_phi then Rep_stone_phi_pair x else triple.pairs_uminus (Rep_phi f) (triple.pairs_uminus (Rep_phi f) (Rep_stone_phi_pair x)))\"\n\ntext \\<open>\nThe following lemma shows that in both cases the value of the function is a valid pair for the given structure map.\n\\<close>\n\nlemma stone_phi_embed_triple_pair:\n  \"(if Rep_phi f = stone_phi then Rep_stone_phi_pair x else triple.pairs_uminus (Rep_phi f) (triple.pairs_uminus (Rep_phi f) (Rep_stone_phi_pair x))) \\<in> triple.pairs (Rep_phi f)\"\n  by (metis (no_types, hide_lams) Rep_stone_phi_pair simp_phi surj_pair triple.pairs_uminus_closed triple_def)\n\ntext \\<open>\nThe following result shows that the embedding preserves the operations of Stone algebras.\nOf course, it is not (yet) a Stone algebra homomorphism as we do not know (yet) that the domain of the embedding is a Stone algebra.\nTo establish the latter is the purpose of the embedding.\n\\<close>\n\nlemma stone_phi_embed_homomorphism:\n  \"sup_inf_top_bot_uminus_ord_homomorphism stone_phi_embed\"\nproof (intro conjI)\n  let ?p = \"\\<lambda>f . triple.pairs_uminus (Rep_phi f)\"\n  let ?pp = \"\\<lambda>f x . ?p f (?p f x)\"\n  let ?q = \"\\<lambda>f x . ?pp f (Rep_stone_phi_pair x)\"\n  show \"\\<forall>x y::'a stone_phi_pair . stone_phi_embed (x \\<squnion> y) = stone_phi_embed x \\<squnion> stone_phi_embed y\"\n  proof (intro allI)\n    fix x y :: \"'a stone_phi_pair\"\n    have 1: \"\\<forall>f . triple.pairs_sup (?q f x) (?q f y) = ?q f (x \\<squnion> y)\"\n    proof\n      fix f :: \"('a regular,'a dense) phi\"\n      let ?r = \"Rep_phi f\"\n      obtain x1 x2 y1 y2 where 2: \"(x1,x2) = Rep_stone_phi_pair x \\<and> (y1,y2) = Rep_stone_phi_pair y\"\n        using prod.collapse by blast\n      hence \"triple.pairs_sup (?q f x) (?q f y) = triple.pairs_sup (?pp f (x1,x2)) (?pp f (y1,y2))\"\n        by simp\n      also have \"... = triple.pairs_sup (--x1,?r (-x1)) (--y1,?r (-y1))\"\n        by (simp add: triple.pairs_uminus.simps triple_def)\n      also have \"... = (--x1 \\<squnion> --y1,?r (-x1) \\<sqinter> ?r (-y1))\"\n        by simp\n      also have \"... = (--(x1 \\<squnion> y1),?r (-(x1 \\<squnion> y1)))\"\n        by simp\n      also have \"... = ?pp f (x1 \\<squnion> y1,x2 \\<sqinter> y2)\"\n        by (simp add: triple.pairs_uminus.simps triple_def)\n      also have \"... = ?pp f (triple.pairs_sup (x1,x2) (y1,y2))\"\n        by simp\n      also have \"... = ?q f (x \\<squnion> y)\"\n        using 2 by (simp add: sup_stone_phi_pair.rep_eq)\n      finally show \"triple.pairs_sup (?q f x) (?q f y) = ?q f (x \\<squnion> y)\"\n        .\n    qed\n    have \"stone_phi_embed x \\<squnion> stone_phi_embed y = Abs_lifted_pair (\\<lambda>f . if Rep_phi f = stone_phi then Rep_stone_phi_pair x else ?q f x) \\<squnion> Abs_lifted_pair (\\<lambda>f . if Rep_phi f = stone_phi then Rep_stone_phi_pair y else ?q f y)\"\n      by simp\n    also have \"... = Abs_lifted_pair (\\<lambda>f . triple.pairs_sup (if Rep_phi f = stone_phi then Rep_stone_phi_pair x else ?q f x) (if Rep_phi f = stone_phi then Rep_stone_phi_pair y else ?q f y))\"\n      by (rule sup_lifted_pair.abs_eq) (simp_all add: eq_onp_same_args stone_phi_embed_triple_pair)\n    also have \"... = Abs_lifted_pair (\\<lambda>f . if Rep_phi f = stone_phi then triple.pairs_sup (Rep_stone_phi_pair x) (Rep_stone_phi_pair y) else triple.pairs_sup (?q f x) (?q f y))\"\n      by (simp add: if_distrib_2)\n    also have \"... = Abs_lifted_pair (\\<lambda>f . if Rep_phi f = stone_phi then triple.pairs_sup (Rep_stone_phi_pair x) (Rep_stone_phi_pair y) else ?q f (x \\<squnion> y))\"\n      using 1 by meson\n    also have \"... = Abs_lifted_pair (\\<lambda>f . if Rep_phi f = stone_phi then Rep_stone_phi_pair (x \\<squnion> y) else ?q f (x \\<squnion> y))\"\n      by (metis sup_stone_phi_pair.rep_eq)\n    also have \"... = stone_phi_embed (x \\<squnion> y)\"\n      by simp\n    finally show \"stone_phi_embed (x \\<squnion> y) = stone_phi_embed x \\<squnion> stone_phi_embed y\"\n      by simp\n  qed\nnext\n  let ?p = \"\\<lambda>f . triple.pairs_uminus (Rep_phi f)\"\n  let ?pp = \"\\<lambda>f x . ?p f (?p f x)\"\n  let ?q = \"\\<lambda>f x . ?pp f (Rep_stone_phi_pair x)\"\n  show \"\\<forall>x y::'a stone_phi_pair . stone_phi_embed (x \\<sqinter> y) = stone_phi_embed x \\<sqinter> stone_phi_embed y\"\n  proof (intro allI)\n    fix x y :: \"'a stone_phi_pair\"\n    have 1: \"\\<forall>f . triple.pairs_inf (?q f x) (?q f y) = ?q f (x \\<sqinter> y)\"\n    proof\n      fix f :: \"('a regular,'a dense) phi\"\n      let ?r = \"Rep_phi f\"\n      obtain x1 x2 y1 y2 where 2: \"(x1,x2) = Rep_stone_phi_pair x \\<and> (y1,y2) = Rep_stone_phi_pair y\"\n        using prod.collapse by blast\n      hence \"triple.pairs_inf (?q f x) (?q f y) = triple.pairs_inf (?pp f (x1,x2)) (?pp f (y1,y2))\"\n        by simp\n      also have \"... = triple.pairs_inf (--x1,?r (-x1)) (--y1,?r (-y1))\"\n        by (simp add: triple.pairs_uminus.simps triple_def)\n      also have \"... = (--x1 \\<sqinter> --y1,?r (-x1) \\<squnion> ?r (-y1))\"\n        by simp\n      also have \"... = (--(x1 \\<sqinter> y1),?r (-(x1 \\<sqinter> y1)))\"\n        by simp\n      also have \"... = ?pp f (x1 \\<sqinter> y1,x2 \\<squnion> y2)\"\n        by (simp add: triple.pairs_uminus.simps triple_def)\n      also have \"... = ?pp f (triple.pairs_inf (x1,x2) (y1,y2))\"\n        by simp\n      also have \"... = ?q f (x \\<sqinter> y)\"\n        using 2 by (simp add: inf_stone_phi_pair.rep_eq)\n      finally show \"triple.pairs_inf (?q f x) (?q f y) = ?q f (x \\<sqinter> y)\"\n        .\n    qed\n    have \"stone_phi_embed x \\<sqinter> stone_phi_embed y = Abs_lifted_pair (\\<lambda>f . if Rep_phi f = stone_phi then Rep_stone_phi_pair x else ?q f x) \\<sqinter> Abs_lifted_pair (\\<lambda>f . if Rep_phi f = stone_phi then Rep_stone_phi_pair y else ?q f y)\"\n      by simp\n    also have \"... = Abs_lifted_pair (\\<lambda>f . triple.pairs_inf (if Rep_phi f = stone_phi then Rep_stone_phi_pair x else ?q f x) (if Rep_phi f = stone_phi then Rep_stone_phi_pair y else ?q f y))\"\n      by (rule inf_lifted_pair.abs_eq) (simp_all add: eq_onp_same_args stone_phi_embed_triple_pair)\n    also have \"... = Abs_lifted_pair (\\<lambda>f . if Rep_phi f = stone_phi then triple.pairs_inf (Rep_stone_phi_pair x) (Rep_stone_phi_pair y) else triple.pairs_inf (?q f x) (?q f y))\"\n      by (simp add: if_distrib_2)\n    also have \"... = Abs_lifted_pair (\\<lambda>f . if Rep_phi f = stone_phi then triple.pairs_inf (Rep_stone_phi_pair x) (Rep_stone_phi_pair y) else ?q f (x \\<sqinter> y))\"\n      using 1 by meson\n    also have \"... = Abs_lifted_pair (\\<lambda>f . if Rep_phi f = stone_phi then Rep_stone_phi_pair (x \\<sqinter> y) else ?q f (x \\<sqinter> y))\"\n      by (metis inf_stone_phi_pair.rep_eq)\n    also have \"... = stone_phi_embed (x \\<sqinter> y)\"\n      by simp\n    finally show \"stone_phi_embed (x \\<sqinter> y) = stone_phi_embed x \\<sqinter> stone_phi_embed y\"\n      by simp\n  qed\nnext\n  have \"stone_phi_embed (top::'a stone_phi_pair) = Abs_lifted_pair (\\<lambda>f . if Rep_phi f = stone_phi then Rep_stone_phi_pair top else triple.pairs_uminus (Rep_phi f) (triple.pairs_uminus (Rep_phi f) (Rep_stone_phi_pair top)))\"\n    by simp\n  also have \"... = Abs_lifted_pair (\\<lambda>f . if Rep_phi f = stone_phi then (top,bot) else triple.pairs_uminus (Rep_phi f) (triple.pairs_uminus (Rep_phi f) (top,bot)))\"\n    by (metis (no_types, hide_lams) bot_filter.abs_eq top_stone_phi_pair.rep_eq)\n  also have \"... = Abs_lifted_pair (\\<lambda>f . if Rep_phi f = stone_phi then (top,bot) else triple.pairs_uminus (Rep_phi f) (bot,top))\"\n    by (metis (no_types, hide_lams) dense_closed_top simp_phi triple.pairs_uminus.simps triple_def)\n  also have \"... = Abs_lifted_pair (\\<lambda>f . if Rep_phi f = stone_phi then (top,bot) else (top,bot))\"\n    by (metis (no_types, hide_lams) p_bot simp_phi triple.pairs_uminus.simps triple_def)\n  also have \"... = Abs_lifted_pair (\\<lambda>f . (top,Abs_filter {top}))\"\n    by (simp add: bot_filter.abs_eq)\n  also have \"... = top\"\n    by (rule top_lifted_pair.abs_eq[THEN sym])\n  finally show \"stone_phi_embed (top::'a stone_phi_pair) = top\"\n    .\nnext\n  have \"stone_phi_embed (bot::'a stone_phi_pair) = Abs_lifted_pair (\\<lambda>f . if Rep_phi f = stone_phi then Rep_stone_phi_pair bot else triple.pairs_uminus (Rep_phi f) (triple.pairs_uminus (Rep_phi f) (Rep_stone_phi_pair bot)))\"\n    by simp\n  also have \"... = Abs_lifted_pair (\\<lambda>f . if Rep_phi f = stone_phi then (bot,top) else triple.pairs_uminus (Rep_phi f) (triple.pairs_uminus (Rep_phi f) (bot,top)))\"\n    by (metis (no_types, hide_lams) top_filter.abs_eq bot_stone_phi_pair.rep_eq)\n  also have \"... = Abs_lifted_pair (\\<lambda>f . if Rep_phi f = stone_phi then (bot,top) else triple.pairs_uminus (Rep_phi f) (top,bot))\"\n    by (metis (no_types, hide_lams) p_bot simp_phi triple.pairs_uminus.simps triple_def)\n  also have \"... = Abs_lifted_pair (\\<lambda>f . if Rep_phi f = stone_phi then (bot,top) else (bot,top))\"\n    by (metis (no_types, hide_lams) p_top simp_phi triple.pairs_uminus.simps triple_def)\n  also have \"... = Abs_lifted_pair (\\<lambda>f . (bot,Abs_filter UNIV))\"\n    by (simp add: top_filter.abs_eq)\n  also have \"... = bot\"\n    by (rule bot_lifted_pair.abs_eq[THEN sym])\n  finally show \"stone_phi_embed (bot::'a stone_phi_pair) = bot\"\n    .\nnext\n  let ?p = \"\\<lambda>f . triple.pairs_uminus (Rep_phi f)\"\n  let ?pp = \"\\<lambda>f x . ?p f (?p f x)\"\n  let ?q = \"\\<lambda>f x . ?pp f (Rep_stone_phi_pair x)\"\n  show \"\\<forall>x::'a stone_phi_pair . stone_phi_embed (-x) = -stone_phi_embed x\"\n  proof (intro allI)\n    fix x :: \"'a stone_phi_pair\"\n    have 1: \"\\<forall>f . triple.pairs_uminus (Rep_phi f) (?q f x) = ?q f (-x)\"\n    proof\n      fix f :: \"('a regular,'a dense) phi\"\n      let ?r = \"Rep_phi f\"\n      obtain x1 x2 where 2: \"(x1,x2) = Rep_stone_phi_pair x\"\n        using prod.collapse by blast\n      hence \"triple.pairs_uminus (Rep_phi f) (?q f x) = triple.pairs_uminus (Rep_phi f) (?pp f (x1,x2))\"\n        by simp\n      also have \"... = triple.pairs_uminus (Rep_phi f) (--x1,?r (-x1))\"\n        by (simp add: triple.pairs_uminus.simps triple_def)\n      also have \"... = (---x1,?r (--x1))\"\n        by (simp add: triple.pairs_uminus.simps triple_def)\n      also have \"... = ?pp f (-x1,stone_phi x1)\"\n        by (simp add: triple.pairs_uminus.simps triple_def)\n      also have \"... = ?pp f (triple.pairs_uminus stone_phi (x1,x2))\"\n        by simp\n      also have \"... = ?q f (-x)\"\n        using 2 by (simp add: uminus_stone_phi_pair.rep_eq)\n      finally show \"triple.pairs_uminus (Rep_phi f) (?q f x) = ?q f (-x)\"\n        .\n    qed\n    have \"-stone_phi_embed x = -Abs_lifted_pair (\\<lambda>f . if Rep_phi f = stone_phi then Rep_stone_phi_pair x else ?q f x)\"\n      by simp\n    also have \"... = Abs_lifted_pair (\\<lambda>f . triple.pairs_uminus (Rep_phi f) (if Rep_phi f = stone_phi then Rep_stone_phi_pair x else ?q f x))\"\n      by (rule uminus_lifted_pair.abs_eq) (simp_all add: eq_onp_same_args stone_phi_embed_triple_pair)\n    also have \"... = Abs_lifted_pair (\\<lambda>f . if Rep_phi f = stone_phi then triple.pairs_uminus (Rep_phi f) (Rep_stone_phi_pair x) else triple.pairs_uminus (Rep_phi f) (?q f x))\"\n      by (simp add: if_distrib)\n    also have \"... = Abs_lifted_pair (\\<lambda>f . if Rep_phi f = stone_phi then triple.pairs_uminus (Rep_phi f) (Rep_stone_phi_pair x) else ?q f (-x))\"\n      using 1 by meson\n    also have \"... = Abs_lifted_pair (\\<lambda>f . if Rep_phi f = stone_phi then Rep_stone_phi_pair (-x) else ?q f (-x))\"\n      by (metis uminus_stone_phi_pair.rep_eq)\n    also have \"... = stone_phi_embed (-x)\"\n      by simp\n    finally show \"stone_phi_embed (-x) = -stone_phi_embed x\"\n      by simp\n  qed\nnext\n  let ?p = \"\\<lambda>f . triple.pairs_uminus (Rep_phi f)\"\n  let ?pp = \"\\<lambda>f x . ?p f (?p f x)\"\n  let ?q = \"\\<lambda>f x . ?pp f (Rep_stone_phi_pair x)\"\n  show \"\\<forall>x y::'a stone_phi_pair . x \\<le> y \\<longrightarrow> stone_phi_embed x \\<le> stone_phi_embed y\"\n  proof (intro allI, rule impI)\n    fix x y :: \"'a stone_phi_pair\"\n    assume 1: \"x \\<le> y\"\n    have \"\\<forall>f . triple.pairs_less_eq (if Rep_phi f = stone_phi then Rep_stone_phi_pair x else ?q f x) (if Rep_phi f = stone_phi then Rep_stone_phi_pair y else ?q f y)\"\n    proof\n      fix f :: \"('a regular,'a dense) phi\"\n      let ?r = \"Rep_phi f\"\n      obtain x1 x2 y1 y2 where 2: \"(x1,x2) = Rep_stone_phi_pair x \\<and> (y1,y2) = Rep_stone_phi_pair y\"\n        using prod.collapse by blast\n      have \"x1 \\<le> y1\"\n        using 1 2 by (metis less_eq_stone_phi_pair.rep_eq stone_phi.pairs_less_eq.simps)\n      hence \"--x1 \\<le> --y1 \\<and> ?r (-y1) \\<le> ?r (-x1)\"\n        by (metis compl_le_compl_iff le_iff_sup simp_phi)\n      hence \"triple.pairs_less_eq (--x1,?r (-x1)) (--y1,?r (-y1))\"\n        by simp\n      hence \"triple.pairs_less_eq (?pp f (x1,x2)) (?pp f (y1,y2))\"\n        by (simp add: triple.pairs_uminus.simps triple_def)\n      hence \"triple.pairs_less_eq (?q f x) (?q f y)\"\n        using 2 by simp\n      hence \"if ?r = stone_phi then triple.pairs_less_eq (Rep_stone_phi_pair x) (Rep_stone_phi_pair y) else triple.pairs_less_eq (?q f x) (?q f y)\"\n        using 1 by (simp add: less_eq_stone_phi_pair.rep_eq)\n      thus \"triple.pairs_less_eq (if ?r = stone_phi then Rep_stone_phi_pair x else ?q f x) (if ?r = stone_phi then Rep_stone_phi_pair y else ?q f y)\"\n        by (simp add: if_distrib_2)\n    qed\n    hence \"Abs_lifted_pair (\\<lambda>f . if Rep_phi f = stone_phi then Rep_stone_phi_pair x else ?q f x) \\<le> Abs_lifted_pair (\\<lambda>f . if Rep_phi f = stone_phi then Rep_stone_phi_pair y else ?q f y)\"\n      by (subst less_eq_lifted_pair.abs_eq) (simp_all add: eq_onp_same_args stone_phi_embed_triple_pair)\n    thus \"stone_phi_embed x \\<le> stone_phi_embed y\"\n      by simp\n  qed\nqed\n\ntext \\<open>\nThe following lemmas show that the embedding is injective and reflects the order.\nThe latter allows us to easily inherit properties involving inequalities from the target of the embedding, without transforming them to equations.\n\\<close>\n\nlemma stone_phi_embed_injective:\n  \"inj stone_phi_embed\"\nproof (rule injI)\n  fix x y :: \"'a stone_phi_pair\"\n  have 1: \"Rep_phi (Abs_phi stone_phi) = stone_phi\"\n    by (simp add: Abs_phi_inverse stone_phi.hom)\n  assume 2: \"stone_phi_embed x = stone_phi_embed y\"\n  have \"\\<forall>x::'a stone_phi_pair . Rep_lifted_pair (stone_phi_embed x) = (\\<lambda>f . if Rep_phi f = stone_phi then Rep_stone_phi_pair x else triple.pairs_uminus (Rep_phi f) (triple.pairs_uminus (Rep_phi f) (Rep_stone_phi_pair x)))\"\n    by (simp add: Abs_lifted_pair_inverse stone_phi_embed_triple_pair)\n  hence \"(\\<lambda>f . if Rep_phi f = stone_phi then Rep_stone_phi_pair x else triple.pairs_uminus (Rep_phi f) (triple.pairs_uminus (Rep_phi f) (Rep_stone_phi_pair x))) = (\\<lambda>f . if Rep_phi f = stone_phi then Rep_stone_phi_pair y else triple.pairs_uminus (Rep_phi f) (triple.pairs_uminus (Rep_phi f) (Rep_stone_phi_pair y)))\"\n    using 2 by metis\n  hence \"Rep_stone_phi_pair x = Rep_stone_phi_pair y\"\n    using 1 by metis\n  thus \"x = y\"\n    by (simp add: Rep_stone_phi_pair_inject)\nqed\n\n\n\nlemma stone_phi_embed_strict_order_isomorphism:\n  \"x < y \\<longleftrightarrow> stone_phi_embed x < stone_phi_embed y\"\n  by (smt less_eq_stone_phi_pair.rep_eq less_le_not_le less_stone_phi_pair.rep_eq stone_phi.pairs_less.elims(2,3) stone_phi_embed_homomorphism stone_phi_embed_order_injective)\n\ntext \\<open>\nNow all Stone algebra axioms can be inherited using the embedding.\nThis is due to the fact that the axioms are universally quantified equations or conditional equations (or inequalities); this is called a quasivariety in universal algebra.\nIt would be useful to have this construction available for arbitrary quasivarieties.\n\\<close>\n\ninstantiation stone_phi_pair :: (non_trivial_stone_algebra) stone_algebra\nbegin\n\ninstance\n  apply intro_classes\n  apply (metis (mono_tags, lifting) stone_phi_embed_homomorphism stone_phi_embed_strict_order_isomorphism stone_phi_embed_order_injective less_le_not_le)\n  apply (simp add: stone_phi_embed_order_injective)\n  apply (meson order.trans stone_phi_embed_homomorphism stone_phi_embed_order_injective)\n  apply (meson stone_phi_embed_homomorphism antisym stone_phi_embed_injective injD)\n  apply (metis inf.sup_ge1 stone_phi_embed_homomorphism stone_phi_embed_order_injective)\n  apply (metis inf.sup_ge2 stone_phi_embed_homomorphism stone_phi_embed_order_injective)\n  apply (metis inf_greatest stone_phi_embed_homomorphism stone_phi_embed_order_injective)\n  apply (metis stone_phi_embed_homomorphism stone_phi_embed_order_injective sup_ge1)\n  apply (metis stone_phi_embed_homomorphism stone_phi_embed_order_injective sup.cobounded2)\n  apply (metis stone_phi_embed_homomorphism stone_phi_embed_order_injective sup_least)\n  apply (metis bot.extremum stone_phi_embed_homomorphism stone_phi_embed_order_injective)\n  apply (metis stone_phi_embed_homomorphism stone_phi_embed_order_injective top_greatest)\n  apply (metis (mono_tags, lifting) stone_phi_embed_homomorphism sup_inf_distrib1 stone_phi_embed_injective injD)\n  apply (metis stone_phi_embed_homomorphism stone_phi_embed_injective injD stone_phi_embed_order_injective pseudo_complement)\n  by (metis injD stone_phi_embed_homomorphism stone_phi_embed_injective stone)\n\nend\n\nsubsection \\<open>Stone Algebra Isomorphism\\<close>\n\ntext \\<open>\nIn this section we prove that the Stone algebra of the triple of a Stone algebra is isomorphic to the original Stone algebra.\nThe following two definitions give the isomorphism.\n\\<close>\n\nabbreviation sa_iso_inv :: \"'a::non_trivial_stone_algebra stone_phi_pair \\<Rightarrow> 'a\"\n  where \"sa_iso_inv \\<equiv> \\<lambda>p . Rep_regular (fst (Rep_stone_phi_pair p)) \\<sqinter> Rep_dense (triple.rho_pair stone_phi (Rep_stone_phi_pair p))\"\n\nabbreviation sa_iso :: \"'a::non_trivial_stone_algebra \\<Rightarrow> 'a stone_phi_pair\"\n  where \"sa_iso \\<equiv> \\<lambda>x . Abs_stone_phi_pair (Abs_regular (--x),stone_phi (Abs_regular (-x)) \\<squnion> up_filter (Abs_dense (x \\<squnion> -x)))\"\n\nlemma sa_iso_triple_pair:\n  \"(Abs_regular (--x),stone_phi (Abs_regular (-x)) \\<squnion> up_filter (Abs_dense (x \\<squnion> -x))) \\<in> triple.pairs stone_phi\"\n  by (metis (mono_tags, lifting) double_compl eq_onp_same_args stone_phi.sa_iso_pair uminus_regular.abs_eq)\n\nlemma stone_phi_inf_dense:\n  \"stone_phi (Abs_regular (-x)) \\<sqinter> up_filter (Abs_dense (y \\<squnion> -y)) \\<le> up_filter (Abs_dense (y \\<squnion> -y \\<squnion> x))\"\nproof -\n  have \"Rep_filter (stone_phi (Abs_regular (-x)) \\<sqinter> up_filter (Abs_dense (y \\<squnion> -y))) \\<le> \\<up>(Abs_dense (y \\<squnion> -y \\<squnion> x))\"\n  proof\n    fix z :: \"'a dense\"\n    let ?r = \"Rep_dense z\"\n    assume \"z \\<in> Rep_filter (stone_phi (Abs_regular (-x)) \\<sqinter> up_filter (Abs_dense (y \\<squnion> -y)))\"\n    also have \"... = Rep_filter (stone_phi (Abs_regular (-x))) \\<inter> Rep_filter (up_filter (Abs_dense (y \\<squnion> -y)))\"\n      by (simp add: inf_filter.rep_eq)\n    also have \"... = stone_phi_base (Abs_regular (-x)) \\<inter> \\<up>(Abs_dense (y \\<squnion> -y))\"\n      by (metis Abs_filter_inverse mem_Collect_eq up_filter stone_phi_base_filter stone_phi_def)\n    finally have \"--x \\<le> ?r \\<and> Abs_dense (y \\<squnion> -y) \\<le> z\"\n      by (metis (mono_tags, lifting) Abs_regular_inverse Int_Collect mem_Collect_eq)\n    hence \"--x \\<le> ?r \\<and> y \\<squnion> -y \\<le> ?r\"\n      by (simp add: Abs_dense_inverse less_eq_dense.rep_eq)\n    hence \"y \\<squnion> -y \\<squnion> x \\<le> ?r\"\n      using order_trans pp_increasing by auto\n    hence \"Abs_dense (y \\<squnion> -y \\<squnion> x) \\<le> Abs_dense ?r\"\n      by (subst less_eq_dense.abs_eq) (simp_all add: eq_onp_same_args)\n    thus \"z \\<in> \\<up>(Abs_dense (y \\<squnion> -y \\<squnion> x))\"\n      by (simp add: Rep_dense_inverse)\n  qed\n  hence \"Abs_filter (Rep_filter (stone_phi (Abs_regular (-x)) \\<sqinter> up_filter (Abs_dense (y \\<squnion> -y)))) \\<le> up_filter (Abs_dense (y \\<squnion> -y \\<squnion> x))\"\n    by (simp add: eq_onp_same_args less_eq_filter.abs_eq)\n  thus ?thesis\n    by (simp add: Rep_filter_inverse)\nqed\n\nlemma stone_phi_complement:\n  \"complement (stone_phi (Abs_regular (-x))) (stone_phi (Abs_regular (--x)))\"\n  by (metis (mono_tags, lifting) eq_onp_same_args stone_phi.phi_complemented uminus_regular.abs_eq)\n\nlemma up_dense_stone_phi:\n  \"up_filter (Abs_dense (x \\<squnion> -x)) \\<le> stone_phi (Abs_regular (--x))\"\nproof -\n  have \"\\<up>(Abs_dense (x \\<squnion> -x)) \\<le> stone_phi_base (Abs_regular (--x))\"\n  proof\n    fix z :: \"'a dense\"\n    let ?r = \"Rep_dense z\"\n    assume \"z \\<in> \\<up>(Abs_dense (x \\<squnion> -x))\"\n    hence \"---x \\<le> ?r\"\n      by (simp add: Abs_dense_inverse less_eq_dense.rep_eq)\n    hence \"-Rep_regular (Abs_regular (--x)) \\<le> ?r\"\n      by (metis (mono_tags, lifting) Abs_regular_inverse mem_Collect_eq)\n    thus \"z \\<in> stone_phi_base (Abs_regular (--x))\"\n      by simp\n  qed\n  thus ?thesis\n    by (unfold stone_phi_def, subst less_eq_filter.abs_eq, simp_all add: eq_onp_same_args stone_phi_base_filter)\nqed\n\ntext \\<open>\nThe following two results prove that the isomorphisms are mutually inverse.\n\\<close>\n\nlemma sa_iso_left_invertible:\n  \"sa_iso_inv (sa_iso x) = x\"\nproof -\n  have \"up_filter (triple.rho_pair stone_phi (Abs_regular (--x),stone_phi (Abs_regular (-x)) \\<squnion> up_filter (Abs_dense (x \\<squnion> -x)))) = stone_phi (Abs_regular (--x)) \\<sqinter> (stone_phi (Abs_regular (-x)) \\<squnion> up_filter (Abs_dense (x \\<squnion> -x)))\"\n    using sa_iso_triple_pair stone_phi.get_rho_pair_char by blast\n  also have \"... = stone_phi (Abs_regular (--x)) \\<sqinter> up_filter (Abs_dense (x \\<squnion> -x))\"\n    by (simp add: inf.sup_commute inf_sup_distrib1 stone_phi_complement)\n  also have \"... = up_filter (Abs_dense (x \\<squnion> -x))\"\n    using up_dense_stone_phi inf.absorb2 by auto\n  finally have 1: \"triple.rho_pair stone_phi (Abs_regular (--x),stone_phi (Abs_regular (-x)) \\<squnion> up_filter (Abs_dense (x \\<squnion> -x))) = Abs_dense (x \\<squnion> -x)\"\n    using up_filter_injective by auto\n  have \"sa_iso_inv (sa_iso x) = (\\<lambda>p . Rep_regular (fst p) \\<sqinter> Rep_dense (triple.rho_pair stone_phi p)) (Abs_regular (--x),stone_phi (Abs_regular (-x)) \\<squnion> up_filter (Abs_dense (x \\<squnion> -x)))\"\n    by (simp add: Abs_stone_phi_pair_inverse sa_iso_triple_pair)\n  also have \"... = Rep_regular (Abs_regular (--x)) \\<sqinter> Rep_dense (triple.rho_pair stone_phi (Abs_regular (--x),stone_phi (Abs_regular (-x)) \\<squnion> up_filter (Abs_dense (x \\<squnion> -x))))\"\n    by simp\n  also have \"... = --x \\<sqinter> Rep_dense (Abs_dense (x \\<squnion> -x))\"\n    using 1 by (subst Abs_regular_inverse) auto\n  also have \"... = --x \\<sqinter> (x \\<squnion> -x)\"\n    by (subst Abs_dense_inverse) simp_all\n  also have \"... = x\"\n    by simp\n  finally show ?thesis\n    by auto\nqed\n\nlemma sa_iso_right_invertible:\n  \"sa_iso (sa_iso_inv p) = p\"\nproof -\n  obtain x y where 1: \"(x,y) = Rep_stone_phi_pair p\"\n    using prod.collapse by blast\n  hence 2: \"(x,y) \\<in> triple.pairs stone_phi\"\n    by (simp add: Rep_stone_phi_pair)\n  hence 3: \"stone_phi (-x) \\<le> y\"\n    by (simp add: stone_phi.pairs_phi_less_eq)\n  have 4: \"\\<forall>z . z \\<in> Rep_filter (stone_phi x \\<sqinter> y) \\<longrightarrow> -Rep_regular x \\<le> Rep_dense z\"\n  proof (rule allI, rule impI)\n    fix z :: \"'a dense\"\n    let ?r = \"Rep_dense z\"\n    assume \"z \\<in> Rep_filter (stone_phi x \\<sqinter> y)\"\n    hence \"z \\<in> Rep_filter (stone_phi x)\"\n      by (simp add: inf_filter.rep_eq)\n    also have \"... = stone_phi_base x\"\n      by (simp add: stone_phi_def Abs_filter_inverse stone_phi_base_filter)\n    finally show \"-Rep_regular x \\<le> ?r\"\n      by simp\n  qed\n  have \"triple.rho_pair stone_phi (x,y) \\<in> \\<up>(triple.rho_pair stone_phi (x,y))\"\n    by simp\n  also have \"... = Rep_filter (Abs_filter (\\<up>(triple.rho_pair stone_phi (x,y))))\"\n    by (simp add: Abs_filter_inverse)\n  also have \"... = Rep_filter (stone_phi x \\<sqinter> y)\"\n    using 2 stone_phi.get_rho_pair_char by fastforce\n  finally have \"triple.rho_pair stone_phi (x,y) \\<in> Rep_filter (stone_phi x \\<sqinter> y)\"\n    by simp\n  hence 5: \"-Rep_regular x \\<le> Rep_dense (triple.rho_pair stone_phi (x,y))\"\n    using 4 by simp\n  have 6: \"sa_iso_inv p = Rep_regular x \\<sqinter> Rep_dense (triple.rho_pair stone_phi (x,y))\"\n    using 1 by (metis fstI)\n  hence \"-sa_iso_inv p = -Rep_regular x\"\n    by simp\n  hence \"sa_iso (sa_iso_inv p) = Abs_stone_phi_pair (Abs_regular (--Rep_regular x),stone_phi (Abs_regular (-Rep_regular x)) \\<squnion> up_filter (Abs_dense ((Rep_regular x \\<sqinter> Rep_dense (triple.rho_pair stone_phi (x,y))) \\<squnion> -Rep_regular x)))\"\n    using 6 by simp\n  also have \"... = Abs_stone_phi_pair (x,stone_phi (-x) \\<squnion> up_filter (Abs_dense ((Rep_regular x \\<sqinter> Rep_dense (triple.rho_pair stone_phi (x,y))) \\<squnion> -Rep_regular x)))\"\n    by (metis (mono_tags, lifting) Rep_regular_inverse double_compl uminus_regular.rep_eq)\n  also have \"... = Abs_stone_phi_pair (x,stone_phi (-x) \\<squnion> up_filter (Abs_dense (Rep_dense (triple.rho_pair stone_phi (x,y)) \\<squnion> -Rep_regular x)))\"\n    by (metis inf_sup_aci(5) maddux_3_21_pp simp_regular)\n  also have \"... = Abs_stone_phi_pair (x,stone_phi (-x) \\<squnion> up_filter (Abs_dense (Rep_dense (triple.rho_pair stone_phi (x,y)))))\"\n    using 5 by (simp add: sup.absorb1)\n  also have \"... = Abs_stone_phi_pair (x,stone_phi (-x) \\<squnion> up_filter (triple.rho_pair stone_phi (x,y)))\"\n    by (simp add: Rep_dense_inverse)\n  also have \"... = Abs_stone_phi_pair (x,stone_phi (-x) \\<squnion> (stone_phi x \\<sqinter> y))\"\n    using 2 stone_phi.get_rho_pair_char by fastforce\n  also have \"... = Abs_stone_phi_pair (x,stone_phi (-x) \\<squnion> y)\"\n    by (simp add: stone_phi.phi_complemented sup.commute sup_inf_distrib1)\n  also have \"... = Abs_stone_phi_pair (x,y)\"\n    using 3 by (simp add: le_iff_sup)\n  also have \"... = p\"\n    using 1 by (simp add: Rep_stone_phi_pair_inverse)\n  finally show ?thesis\n    .\nqed\n\ntext \\<open>\nIt remains to show the homomorphism properties, which is done in the following result.\n\\<close>\n\nlemma sa_iso:\n  \"stone_algebra_isomorphism sa_iso\"\nproof (intro conjI)\n  have \"Abs_stone_phi_pair (Abs_regular (--bot),stone_phi (Abs_regular (-bot)) \\<squnion> up_filter (Abs_dense (bot \\<squnion> -bot))) = Abs_stone_phi_pair (bot,stone_phi top \\<squnion> up_filter top)\"\n    by (simp add: bot_regular.abs_eq top_regular.abs_eq top_dense.abs_eq)\n  also have \"... = Abs_stone_phi_pair (bot,stone_phi top)\"\n    by (simp add: stone_phi.hom)\n  also have \"... = bot\"\n    by (simp add: bot_stone_phi_pair_def stone_phi.phi_top)\n  finally show \"sa_iso bot = bot\"\n    .\nnext\n  have \"Abs_stone_phi_pair (Abs_regular (--top),stone_phi (Abs_regular (-top)) \\<squnion> up_filter (Abs_dense (top \\<squnion> -top))) = Abs_stone_phi_pair (top,stone_phi bot \\<squnion> up_filter top)\"\n    by (simp add: bot_regular.abs_eq top_regular.abs_eq top_dense.abs_eq)\n  also have \"... = top\"\n    by (simp add: stone_phi.phi_bot top_stone_phi_pair_def)\n  finally show \"sa_iso top = top\"\n    .\nnext\n  have 1: \"\\<forall>x y::'a . dense (x \\<squnion> -x \\<squnion> y)\"\n    by simp\n  have 2: \"\\<forall>x y::'a . up_filter (Abs_dense (x \\<squnion> -x \\<squnion> y)) \\<le> (stone_phi (Abs_regular (-x)) \\<squnion> up_filter (Abs_dense (x \\<squnion> -x))) \\<sqinter> (stone_phi (Abs_regular (-y)) \\<squnion> up_filter (Abs_dense (y \\<squnion> -y)))\"\n  proof (intro allI)\n    fix x y :: 'a\n    let ?u = \"Abs_dense (x \\<squnion> -x \\<squnion> --y)\"\n    let ?v = \"Abs_dense (y \\<squnion> -y)\"\n    have \"\\<up>(Abs_dense (x \\<squnion> -x \\<squnion> y)) \\<le> Rep_filter (stone_phi (Abs_regular (-y)) \\<squnion> up_filter ?v)\"\n    proof\n      fix z\n      assume \"z \\<in> \\<up>(Abs_dense (x \\<squnion> -x \\<squnion> y))\"\n      hence \"Abs_dense (x \\<squnion> -x \\<squnion> y) \\<le> z\"\n        by simp\n      hence 3: \"x \\<squnion> -x \\<squnion> y \\<le> Rep_dense z\"\n        by (simp add: Abs_dense_inverse less_eq_dense.rep_eq)\n      have \"y \\<le> x \\<squnion> -x \\<squnion> --y\"\n        by (simp add: le_supI2 pp_increasing)\n      hence \"(x \\<squnion> -x \\<squnion> --y) \\<sqinter> (y \\<squnion> -y) = y \\<squnion> ((x \\<squnion> -x \\<squnion> --y) \\<sqinter> -y)\"\n        by (simp add: le_iff_sup sup_inf_distrib1)\n      also have \"... = y \\<squnion> ((x \\<squnion> -x) \\<sqinter> -y)\"\n        by (simp add: inf_commute inf_sup_distrib1)\n      also have \"... \\<le> Rep_dense z\"\n        using 3 by (meson le_infI1 sup.bounded_iff)\n      finally have \"Abs_dense ((x \\<squnion> -x \\<squnion> --y) \\<sqinter> (y \\<squnion> -y)) \\<le> z\"\n        by (simp add: Abs_dense_inverse less_eq_dense.rep_eq)\n      hence 4: \"?u \\<sqinter> ?v \\<le> z\"\n        by (simp add: eq_onp_same_args inf_dense.abs_eq)\n      have \"-Rep_regular (Abs_regular (-y)) = --y\"\n        by (metis (mono_tags, lifting) mem_Collect_eq Abs_regular_inverse)\n      also have \"... \\<le> Rep_dense ?u\"\n        by (simp add: Abs_dense_inverse)\n      finally have \"?u \\<in> stone_phi_base (Abs_regular (-y))\"\n        by simp\n      hence 5: \"?u \\<in> Rep_filter (stone_phi (Abs_regular (-y)))\"\n        by (metis mem_Collect_eq stone_phi_def stone_phi_base_filter Abs_filter_inverse)\n      have \"?v \\<in> \\<up>?v\"\n        by simp\n      hence \"?v \\<in> Rep_filter (up_filter ?v)\"\n        by (metis Abs_filter_inverse mem_Collect_eq up_filter)\n      thus \"z \\<in> Rep_filter (stone_phi (Abs_regular (-y)) \\<squnion> up_filter ?v)\"\n        using 4 5 sup_filter.rep_eq filter_sup_def by blast\n    qed\n    hence \"up_filter (Abs_dense (x \\<squnion> -x \\<squnion> y)) \\<le> Abs_filter (Rep_filter (stone_phi (Abs_regular (-y)) \\<squnion> up_filter ?v))\"\n      by (simp add: eq_onp_same_args less_eq_filter.abs_eq)\n    also have \"... = stone_phi (Abs_regular (-y)) \\<squnion> up_filter ?v\"\n      by (simp add: Rep_filter_inverse)\n    finally show \"up_filter (Abs_dense (x \\<squnion> -x \\<squnion> y)) \\<le> (stone_phi (Abs_regular (-x)) \\<squnion> up_filter (Abs_dense (x \\<squnion> -x))) \\<sqinter> (stone_phi (Abs_regular (-y)) \\<squnion> up_filter (Abs_dense (y \\<squnion> -y)))\"\n      by (metis le_infI le_supI2 sup_bot.right_neutral up_filter_dense_antitone)\n  qed\n  have 6: \"\\<forall>x::'a . in_p_image (-x)\"\n    by auto\n  show \"\\<forall>x y::'a . sa_iso (x \\<squnion> y) = sa_iso x \\<squnion> sa_iso y\"\n  proof (intro allI)\n    fix x y :: 'a\n    have 7: \"up_filter (Abs_dense (x \\<squnion> -x)) \\<sqinter> up_filter (Abs_dense (y \\<squnion> -y)) \\<le> up_filter (Abs_dense (y \\<squnion> -y \\<squnion> x))\"\n    proof -\n      have \"up_filter (Abs_dense (x \\<squnion> -x)) \\<sqinter> up_filter (Abs_dense (y \\<squnion> -y)) = up_filter (Abs_dense (x \\<squnion> -x) \\<squnion> Abs_dense (y \\<squnion> -y))\"\n        by (metis up_filter_dist_sup)\n      also have \"... = up_filter (Abs_dense (x \\<squnion> -x \\<squnion> (y \\<squnion> -y)))\"\n        by (subst sup_dense.abs_eq) (simp_all add: eq_onp_same_args)\n      also have \"... = up_filter (Abs_dense (y \\<squnion> -y \\<squnion> x \\<squnion> -x))\"\n        by (simp add: sup_commute sup_left_commute)\n      also have \"... \\<le> up_filter (Abs_dense (y \\<squnion> -y \\<squnion> x))\"\n        using up_filter_dense_antitone by auto\n      finally show ?thesis\n        .\n    qed\n    have \"Abs_dense (x \\<squnion> y \\<squnion> -(x \\<squnion> y)) = Abs_dense ((x \\<squnion> -x \\<squnion> y) \\<sqinter> (y \\<squnion> -y \\<squnion> x))\"\n      by (simp add: sup_commute sup_inf_distrib1 sup_left_commute)\n    also have \"... = Abs_dense (x \\<squnion> -x \\<squnion> y) \\<sqinter> Abs_dense (y \\<squnion> -y \\<squnion> x)\"\n      using 1 by (metis (mono_tags, lifting) Abs_dense_inverse Rep_dense_inverse inf_dense.rep_eq mem_Collect_eq)\n    finally have 8: \"up_filter (Abs_dense (x \\<squnion> y \\<squnion> -(x \\<squnion> y))) = up_filter (Abs_dense (x \\<squnion> -x \\<squnion> y)) \\<squnion> up_filter (Abs_dense (y \\<squnion> -y \\<squnion> x))\"\n      by (simp add: up_filter_dist_inf)\n    also have \"... \\<le> (stone_phi (Abs_regular (-x)) \\<squnion> up_filter (Abs_dense (x \\<squnion> -x))) \\<sqinter> (stone_phi (Abs_regular (-y)) \\<squnion> up_filter (Abs_dense (y \\<squnion> -y)))\"\n      using 2 by (simp add: inf.sup_commute le_sup_iff)\n    finally have 9: \"(stone_phi (Abs_regular (-x)) \\<sqinter> stone_phi (Abs_regular (-y))) \\<squnion> up_filter (Abs_dense (x \\<squnion> y \\<squnion> -(x \\<squnion> y))) \\<le> ...\"\n      by (simp add: le_supI1)\n    have \"... = (stone_phi (Abs_regular (-x)) \\<sqinter> stone_phi (Abs_regular (-y))) \\<squnion> (stone_phi (Abs_regular (-x)) \\<sqinter> up_filter (Abs_dense (y \\<squnion> -y))) \\<squnion> ((up_filter (Abs_dense (x \\<squnion> -x)) \\<sqinter> stone_phi (Abs_regular (-y))) \\<squnion> (up_filter (Abs_dense (x \\<squnion> -x)) \\<sqinter> up_filter (Abs_dense (y \\<squnion> -y))))\"\n      by (metis (no_types) inf_sup_distrib1 inf_sup_distrib2)\n    also have \"... \\<le> (stone_phi (Abs_regular (-x)) \\<sqinter> stone_phi (Abs_regular (-y))) \\<squnion> up_filter (Abs_dense (y \\<squnion> -y \\<squnion> x)) \\<squnion> ((up_filter (Abs_dense (x \\<squnion> -x)) \\<sqinter> stone_phi (Abs_regular (-y))) \\<squnion> (up_filter (Abs_dense (x \\<squnion> -x)) \\<sqinter> up_filter (Abs_dense (y \\<squnion> -y))))\"\n      by (meson sup_left_isotone sup_right_isotone stone_phi_inf_dense)\n    also have \"... \\<le> (stone_phi (Abs_regular (-x)) \\<sqinter> stone_phi (Abs_regular (-y))) \\<squnion> up_filter (Abs_dense (y \\<squnion> -y \\<squnion> x)) \\<squnion> (up_filter (Abs_dense (x \\<squnion> -x \\<squnion> y)) \\<squnion> (up_filter (Abs_dense (x \\<squnion> -x)) \\<sqinter> up_filter (Abs_dense (y \\<squnion> -y))))\"\n      by (metis inf.commute sup_left_isotone sup_right_isotone stone_phi_inf_dense)\n    also have \"... \\<le> (stone_phi (Abs_regular (-x)) \\<sqinter> stone_phi (Abs_regular (-y))) \\<squnion> up_filter (Abs_dense (y \\<squnion> -y \\<squnion> x)) \\<squnion> up_filter (Abs_dense (x \\<squnion> -x \\<squnion> y))\"\n      using 7 by (simp add: sup.absorb1 sup_commute sup_left_commute)\n    also have \"... = (stone_phi (Abs_regular (-x)) \\<sqinter> stone_phi (Abs_regular (-y))) \\<squnion> up_filter (Abs_dense (x \\<squnion> y \\<squnion> -(x \\<squnion> y)))\"\n      using 8 by (simp add: sup.commute sup.left_commute)\n    finally have \"(stone_phi (Abs_regular (-x)) \\<squnion> up_filter (Abs_dense (x \\<squnion> -x))) \\<sqinter> (stone_phi (Abs_regular (-y)) \\<squnion> up_filter (Abs_dense (y \\<squnion> -y))) = ...\"\n      using 9 using antisym by blast\n    also have \"... = stone_phi (Abs_regular (-x) \\<sqinter> Abs_regular (-y)) \\<squnion> up_filter (Abs_dense (x \\<squnion> y \\<squnion> -(x \\<squnion> y)))\"\n      by (simp add: stone_phi.hom)\n    also have \"... = stone_phi (Abs_regular (-(x \\<squnion> y))) \\<squnion> up_filter (Abs_dense (x \\<squnion> y \\<squnion> -(x \\<squnion> y)))\"\n      using 6 by (subst inf_regular.abs_eq) (simp_all add: eq_onp_same_args)\n    finally have 10: \"stone_phi (Abs_regular (-(x \\<squnion> y))) \\<squnion> up_filter (Abs_dense (x \\<squnion> y \\<squnion> -(x \\<squnion> y))) = (stone_phi (Abs_regular (-x)) \\<squnion> up_filter (Abs_dense (x \\<squnion> -x))) \\<sqinter> (stone_phi (Abs_regular (-y)) \\<squnion> up_filter (Abs_dense (y \\<squnion> -y)))\"\n      by simp\n    have \"Abs_regular (--(x \\<squnion> y)) = Abs_regular (--x) \\<squnion> Abs_regular (--y)\"\n      using 6 by (subst sup_regular.abs_eq) (simp_all add: eq_onp_same_args)\n    hence \"Abs_stone_phi_pair (Abs_regular (--(x \\<squnion> y)),stone_phi (Abs_regular (-(x \\<squnion> y))) \\<squnion> up_filter (Abs_dense (x \\<squnion> y \\<squnion> -(x \\<squnion> y)))) = Abs_stone_phi_pair (triple.pairs_sup (Abs_regular (--x),stone_phi (Abs_regular (-x)) \\<squnion> up_filter (Abs_dense (x \\<squnion> -x))) (Abs_regular (--y),stone_phi (Abs_regular (-y)) \\<squnion> up_filter (Abs_dense (y \\<squnion> -y))))\"\n      using 10 by auto\n    also have \"... = Abs_stone_phi_pair (Abs_regular (--x),stone_phi (Abs_regular (-x)) \\<squnion> up_filter (Abs_dense (x \\<squnion> -x))) \\<squnion> Abs_stone_phi_pair (Abs_regular (--y),stone_phi (Abs_regular (-y)) \\<squnion> up_filter (Abs_dense (y \\<squnion> -y)))\"\n      by (rule sup_stone_phi_pair.abs_eq[THEN sym]) (simp_all add: eq_onp_same_args sa_iso_triple_pair)\n    finally show \"sa_iso (x \\<squnion> y) = sa_iso x \\<squnion> sa_iso y\"\n      .\n  qed\nnext\n  have 1: \"\\<forall>x y::'a . dense (x \\<squnion> -x \\<squnion> y)\"\n    by simp\n  have 2: \"\\<forall>x::'a . in_p_image (-x)\"\n    by auto\n  have 3: \"\\<forall>x y::'a . stone_phi (Abs_regular (-y)) \\<squnion> up_filter (Abs_dense (x \\<squnion> -x)) = stone_phi (Abs_regular (-y)) \\<squnion> up_filter (Abs_dense (x \\<squnion> -x \\<squnion> -y))\"\n  proof (intro allI)\n    fix x y :: 'a\n    have 4: \"up_filter (Abs_dense (x \\<squnion> -x)) \\<le> stone_phi (Abs_regular (-y)) \\<squnion> up_filter (Abs_dense (x \\<squnion> -x \\<squnion> -y))\"\n      by (metis (no_types, lifting) complement_shunting stone_phi_inf_dense stone_phi_complement complement_symmetric)\n    have \"up_filter (Abs_dense (x \\<squnion> -x \\<squnion> -y)) \\<le> up_filter (Abs_dense (x \\<squnion> -x))\"\n      by (metis sup_idem up_filter_dense_antitone)\n    thus \"stone_phi (Abs_regular (-y)) \\<squnion> up_filter (Abs_dense (x \\<squnion> -x)) = stone_phi (Abs_regular (-y)) \\<squnion> up_filter (Abs_dense (x \\<squnion> -x \\<squnion> -y))\"\n      using 4 by (simp add: le_iff_sup sup_commute sup_left_commute)\n  qed\n  show \"\\<forall>x y::'a . sa_iso (x \\<sqinter> y) = sa_iso x \\<sqinter> sa_iso y\"\n  proof (intro allI)\n    fix x y :: 'a\n    have \"Abs_dense ((x \\<sqinter> y) \\<squnion> -(x \\<sqinter> y)) = Abs_dense ((x \\<squnion> -x \\<squnion> -y) \\<sqinter> (y \\<squnion> -y \\<squnion> -x))\"\n      by (simp add: sup_commute sup_inf_distrib1 sup_left_commute)\n    also have \"... = Abs_dense (x \\<squnion> -x \\<squnion> -y) \\<sqinter> Abs_dense (y \\<squnion> -y \\<squnion> -x)\"\n      using 1 by (metis (mono_tags, lifting) Abs_dense_inverse Rep_dense_inverse inf_dense.rep_eq mem_Collect_eq)\n    finally have 5: \"up_filter (Abs_dense ((x \\<sqinter> y) \\<squnion> -(x \\<sqinter> y))) = up_filter (Abs_dense (x \\<squnion> -x \\<squnion> -y)) \\<squnion> up_filter (Abs_dense (y \\<squnion> -y \\<squnion> -x))\"\n      by (simp add: up_filter_dist_inf)\n    have \"(stone_phi (Abs_regular (-x)) \\<squnion> up_filter (Abs_dense (x \\<squnion> -x))) \\<squnion> (stone_phi (Abs_regular (-y)) \\<squnion> up_filter (Abs_dense (y \\<squnion> -y))) = (stone_phi (Abs_regular (-y)) \\<squnion> up_filter (Abs_dense (x \\<squnion> -x))) \\<squnion> (stone_phi (Abs_regular (-x)) \\<squnion> up_filter (Abs_dense (y \\<squnion> -y)))\"\n      by (simp add: inf_sup_aci(6) sup_left_commute)\n    also have \"... = (stone_phi (Abs_regular (-y)) \\<squnion> up_filter (Abs_dense (x \\<squnion> -x \\<squnion> -y))) \\<squnion> (stone_phi (Abs_regular (-x)) \\<squnion> up_filter (Abs_dense (y \\<squnion> -y \\<squnion> -x)))\"\n      using 3 by simp\n    also have \"... = (stone_phi (Abs_regular (-x)) \\<squnion> stone_phi (Abs_regular (-y))) \\<squnion> (up_filter (Abs_dense (x \\<squnion> -x \\<squnion> -y)) \\<squnion> up_filter (Abs_dense (y \\<squnion> -y \\<squnion> -x)))\"\n      by (simp add: inf_sup_aci(6) sup_left_commute)\n    also have \"... = (stone_phi (Abs_regular (-x)) \\<squnion> stone_phi (Abs_regular (-y))) \\<squnion> up_filter (Abs_dense ((x \\<sqinter> y) \\<squnion> -(x \\<sqinter> y)))\"\n      using 5 by (simp add: sup.commute sup.left_commute)\n    finally have \"(stone_phi (Abs_regular (-x)) \\<squnion> up_filter (Abs_dense (x \\<squnion> -x))) \\<squnion> (stone_phi (Abs_regular (-y)) \\<squnion> up_filter (Abs_dense (y \\<squnion> -y))) = ...\"\n      by simp\n    also have \"... = stone_phi (Abs_regular (-x) \\<squnion> Abs_regular (-y)) \\<squnion> up_filter (Abs_dense ((x \\<sqinter> y) \\<squnion> -(x \\<sqinter> y)))\"\n      by (simp add: stone_phi.hom)\n    also have \"... = stone_phi (Abs_regular (-(x \\<sqinter> y))) \\<squnion> up_filter (Abs_dense ((x \\<sqinter> y) \\<squnion> -(x \\<sqinter> y)))\"\n      using 2 by (subst sup_regular.abs_eq) (simp_all add: eq_onp_same_args)\n    finally have 6: \"stone_phi (Abs_regular (-(x \\<sqinter> y))) \\<squnion> up_filter (Abs_dense ((x \\<sqinter> y) \\<squnion> -(x \\<sqinter> y))) = (stone_phi (Abs_regular (-x)) \\<squnion> up_filter (Abs_dense (x \\<squnion> -x))) \\<squnion> (stone_phi (Abs_regular (-y)) \\<squnion> up_filter (Abs_dense (y \\<squnion> -y)))\"\n      by simp\n    have \"Abs_regular (--(x \\<sqinter> y)) = Abs_regular (--x) \\<sqinter> Abs_regular (--y)\"\n      using 2 by (subst inf_regular.abs_eq) (simp_all add: eq_onp_same_args)\n    hence \"Abs_stone_phi_pair (Abs_regular (--(x \\<sqinter> y)),stone_phi (Abs_regular (-(x \\<sqinter> y))) \\<squnion> up_filter (Abs_dense ((x \\<sqinter> y) \\<squnion> -(x \\<sqinter> y)))) = Abs_stone_phi_pair (triple.pairs_inf (Abs_regular (--x),stone_phi (Abs_regular (-x)) \\<squnion> up_filter (Abs_dense (x \\<squnion> -x))) (Abs_regular (--y),stone_phi (Abs_regular (-y)) \\<squnion> up_filter (Abs_dense (y \\<squnion> -y))))\"\n      using 6 by auto\n    also have \"... = Abs_stone_phi_pair (Abs_regular (--x),stone_phi (Abs_regular (-x)) \\<squnion> up_filter (Abs_dense (x \\<squnion> -x))) \\<sqinter> Abs_stone_phi_pair (Abs_regular (--y),stone_phi (Abs_regular (-y)) \\<squnion> up_filter (Abs_dense (y \\<squnion> -y)))\"\n      by (rule inf_stone_phi_pair.abs_eq[THEN sym]) (simp_all add: eq_onp_same_args sa_iso_triple_pair)\n    finally show \"sa_iso (x \\<sqinter> y) = sa_iso x \\<sqinter> sa_iso y\"\n      .\n  qed\nnext\n  show \"\\<forall>x::'a . sa_iso (-x) = -sa_iso x\"\n  proof\n    fix x :: 'a\n    have \"sa_iso (-x) = Abs_stone_phi_pair (Abs_regular (---x),stone_phi (Abs_regular (--x)) \\<squnion> up_filter top)\"\n      by (simp add: top_dense_def)\n    also have \"... = Abs_stone_phi_pair (Abs_regular (---x),stone_phi (Abs_regular (--x)))\"\n      by (metis bot_filter.abs_eq sup_bot.right_neutral up_top)\n    also have \"... = Abs_stone_phi_pair (triple.pairs_uminus stone_phi (Abs_regular (--x),stone_phi (Abs_regular (-x)) \\<squnion> up_filter (Abs_dense (x \\<squnion> -x))))\"\n      by (subst uminus_regular.abs_eq[THEN sym], unfold eq_onp_same_args) auto\n    also have \"... = -sa_iso x\"\n      by (simp add: eq_onp_def sa_iso_triple_pair uminus_stone_phi_pair.abs_eq)\n    finally show \"sa_iso (-x) = -sa_iso x\"\n      by simp\n  qed\nnext\n  show \"bij sa_iso\"\n    by (metis (mono_tags, lifting) sa_iso_left_invertible sa_iso_right_invertible invertible_bij[where g=sa_iso_inv])\nqed\n\nsubsection \\<open>Triple Isomorphism\\<close>\n\ntext \\<open>\nIn this section we prove that the triple of the Stone algebra of a triple is isomorphic to the original triple.\nThe notion of isomorphism for triples is described in \\cite{ChenGraetzer1969}.\nIt amounts to an isomorphism of Boolean algebras, an isomorphism of distributive lattices with a greatest element, and a commuting diagram involving the structure maps.\n\\<close>\n\nsubsubsection \\<open>Boolean Algebra Isomorphism\\<close>\n\ntext \\<open>\nWe first define and prove the isomorphism of Boolean algebras.\nBecause the Stone algebra of a triple is implemented as a lifted pair, we also lift the Boolean algebra.\n\\<close>\n\ntypedef (overloaded) ('a,'b) lifted_boolean_algebra = \"{ xf::('a::non_trivial_boolean_algebra,'b::distrib_lattice_top) phi \\<Rightarrow> 'a . True }\"\n  by simp\n\nsetup_lifting type_definition_lifted_boolean_algebra\n\ninstantiation lifted_boolean_algebra :: (non_trivial_boolean_algebra,distrib_lattice_top) boolean_algebra\nbegin\n\nlift_definition sup_lifted_boolean_algebra :: \"('a,'b) lifted_boolean_algebra \\<Rightarrow> ('a,'b) lifted_boolean_algebra \\<Rightarrow> ('a,'b) lifted_boolean_algebra\" is \"\\<lambda>xf yf f . sup (xf f) (yf f)\" .\n\nlift_definition inf_lifted_boolean_algebra :: \"('a,'b) lifted_boolean_algebra \\<Rightarrow> ('a,'b) lifted_boolean_algebra \\<Rightarrow> ('a,'b) lifted_boolean_algebra\" is \"\\<lambda>xf yf f . inf (xf f) (yf f)\" .\n\nlift_definition minus_lifted_boolean_algebra :: \"('a,'b) lifted_boolean_algebra \\<Rightarrow> ('a,'b) lifted_boolean_algebra \\<Rightarrow> ('a,'b) lifted_boolean_algebra\" is \"\\<lambda>xf yf f . minus (xf f) (yf f)\" .\n\nlift_definition uminus_lifted_boolean_algebra :: \"('a,'b) lifted_boolean_algebra \\<Rightarrow> ('a,'b) lifted_boolean_algebra\" is \"\\<lambda>xf f . uminus (xf f)\" .\n\nlift_definition bot_lifted_boolean_algebra :: \"('a,'b) lifted_boolean_algebra\" is \"\\<lambda>f . bot\" ..\n\nlift_definition top_lifted_boolean_algebra :: \"('a,'b) lifted_boolean_algebra\" is \"\\<lambda>f . top\" ..\n\nlift_definition less_eq_lifted_boolean_algebra :: \"('a,'b) lifted_boolean_algebra \\<Rightarrow> ('a,'b) lifted_boolean_algebra \\<Rightarrow> bool\" is \"\\<lambda>xf yf . \\<forall>f . less_eq (xf f) (yf f)\" .\n\nlift_definition less_lifted_boolean_algebra :: \"('a,'b) lifted_boolean_algebra \\<Rightarrow> ('a,'b) lifted_boolean_algebra \\<Rightarrow> bool\" is \"\\<lambda>xf yf . (\\<forall>f . less_eq (xf f) (yf f)) \\<and> \\<not> (\\<forall>f . less_eq (yf f) (xf f))\" .\n\ninstance\n  apply intro_classes\n  subgoal apply transfer by auto\n  subgoal apply transfer by auto\n  subgoal apply transfer using order_trans by blast\n  subgoal apply transfer using antisym ext by blast\n  subgoal apply transfer by auto\n  subgoal apply transfer by auto\n  subgoal apply transfer by auto\n  subgoal apply transfer by auto\n  subgoal apply transfer by auto\n  subgoal apply transfer by auto\n  subgoal apply transfer by auto\n  subgoal apply transfer by auto\n  subgoal apply transfer by (simp add: sup_inf_distrib1)\n  subgoal apply transfer by auto\n  subgoal apply transfer by auto\n  subgoal apply transfer by (simp add: diff_eq)\n  done\n\nend\n\ntext \\<open>\nThe following two definitions give the Boolean algebra isomorphism.\n\\<close>\n\nabbreviation ba_iso_inv :: \"('a::non_trivial_boolean_algebra,'b::distrib_lattice_top) lifted_boolean_algebra \\<Rightarrow> ('a,'b) lifted_pair regular\"\n  where \"ba_iso_inv \\<equiv> \\<lambda>xf . Abs_regular (Abs_lifted_pair (\\<lambda>f . (Rep_lifted_boolean_algebra xf f,Rep_phi f (-Rep_lifted_boolean_algebra xf f))))\"\n\nabbreviation ba_iso :: \"('a::non_trivial_boolean_algebra,'b::distrib_lattice_top) lifted_pair regular \\<Rightarrow> ('a,'b) lifted_boolean_algebra\"\n  where \"ba_iso \\<equiv> \\<lambda>pf . Abs_lifted_boolean_algebra (\\<lambda>f . fst (Rep_lifted_pair (Rep_regular pf) f))\"\n\nlemma ba_iso_inv_lifted_pair:\n  \"(Rep_lifted_boolean_algebra xf f,Rep_phi f (-Rep_lifted_boolean_algebra xf f)) \\<in> triple.pairs (Rep_phi f)\"\n  by (metis (no_types, hide_lams) double_compl simp_phi triple.pairs_uminus.simps triple_def triple.pairs_uminus_closed)\n\nlemma ba_iso_inv_regular:\n  \"regular (Abs_lifted_pair (\\<lambda>f . (Rep_lifted_boolean_algebra xf f,Rep_phi f (-Rep_lifted_boolean_algebra xf f))))\"\nproof -\n  have \"\\<forall>f . (Rep_lifted_boolean_algebra xf f,Rep_phi f (-Rep_lifted_boolean_algebra xf f)) = triple.pairs_uminus (Rep_phi f) (triple.pairs_uminus (Rep_phi f) (Rep_lifted_boolean_algebra xf f,Rep_phi f (-Rep_lifted_boolean_algebra xf f)))\"\n    by (simp add: triple.pairs_uminus.simps triple_def)\n  hence \"Abs_lifted_pair (\\<lambda>f . (Rep_lifted_boolean_algebra xf f,Rep_phi f (-Rep_lifted_boolean_algebra xf f))) = --Abs_lifted_pair (\\<lambda>f . (Rep_lifted_boolean_algebra xf f,Rep_phi f (-Rep_lifted_boolean_algebra xf f)))\"\n    by (simp add: triple.pairs_uminus_closed triple_def eq_onp_def uminus_lifted_pair.abs_eq ba_iso_inv_lifted_pair)\n  thus ?thesis\n    by simp\nqed\n\ntext \\<open>\nThe following two results prove that the isomorphisms are mutually inverse.\n\\<close>\n\nlemma ba_iso_left_invertible:\n  \"ba_iso_inv (ba_iso pf) = pf\"\nproof -\n  have 1: \"\\<forall>f . snd (Rep_lifted_pair (Rep_regular pf) f) = Rep_phi f (-fst (Rep_lifted_pair (Rep_regular pf) f))\"\n  proof\n    fix f :: \"('a,'b) phi\"\n    let ?r = \"Rep_phi f\"\n    have \"triple ?r\"\n      by (simp add: triple_def)\n    hence 2: \"\\<forall>p . triple.pairs_uminus ?r p = (-fst p,?r (fst p))\"\n      by (metis prod.collapse triple.pairs_uminus.simps)\n    have 3: \"Rep_regular pf = --Rep_regular pf\"\n      by (simp add: regular_in_p_image_iff)\n    show \"snd (Rep_lifted_pair (Rep_regular pf) f) = ?r (-fst (Rep_lifted_pair (Rep_regular pf) f))\"\n      using 2 3 by (metis fstI sndI uminus_lifted_pair.rep_eq)\n  qed\n  have \"ba_iso_inv (ba_iso pf) = Abs_regular (Abs_lifted_pair (\\<lambda>f . (fst (Rep_lifted_pair (Rep_regular pf) f),Rep_phi f (-fst (Rep_lifted_pair (Rep_regular pf) f)))))\"\n    by (simp add: Abs_lifted_boolean_algebra_inverse)\n  also have \"... = Abs_regular (Abs_lifted_pair (Rep_lifted_pair (Rep_regular pf)))\"\n    using 1 by (metis prod.collapse)\n  also have \"... = pf\"\n    by (simp add: Rep_regular_inverse Rep_lifted_pair_inverse)\n  finally show ?thesis\n    .\nqed\n\nlemma ba_iso_right_invertible:\n  \"ba_iso (ba_iso_inv xf) = xf\"\nproof -\n  let ?rf = \"Rep_lifted_boolean_algebra xf\"\n  have 1: \"\\<forall>f . (-?rf f,Rep_phi f (?rf f)) \\<in> triple.pairs (Rep_phi f) \\<and> (?rf f,Rep_phi f (-?rf f)) \\<in> triple.pairs (Rep_phi f)\"\n  proof\n    fix f\n    have \"up_filter top = bot\"\n      by (simp add: bot_filter.abs_eq)\n    hence \"(\\<exists>z . Rep_phi f (?rf f) = Rep_phi f (?rf f) \\<squnion> up_filter z) \\<and> (\\<exists>z . Rep_phi f (-?rf f) = Rep_phi f (-?rf f) \\<squnion> up_filter z)\"\n      by (metis sup_bot_right)\n    thus \"(-?rf f,Rep_phi f (?rf f)) \\<in> triple.pairs (Rep_phi f) \\<and> (?rf f,Rep_phi f (-?rf f)) \\<in> triple.pairs (Rep_phi f)\"\n      by (simp add: triple_def triple.pairs_def)\n  qed\n  have \"regular (Abs_lifted_pair (\\<lambda>f . (?rf f,Rep_phi f (-?rf f))))\"\n  proof -\n    have \"--Abs_lifted_pair (\\<lambda>f . (?rf f,Rep_phi f (-?rf f))) = -Abs_lifted_pair (\\<lambda>f . triple.pairs_uminus (Rep_phi f) (?rf f,Rep_phi f (-?rf f)))\"\n      using 1 by (simp add: eq_onp_same_args uminus_lifted_pair.abs_eq)\n    also have \"... = -Abs_lifted_pair (\\<lambda>f . (-?rf f,Rep_phi f (?rf f)))\"\n      by (metis (no_types, lifting) simp_phi triple_def triple.pairs_uminus.simps)\n    also have \"... = Abs_lifted_pair (\\<lambda>f . triple.pairs_uminus (Rep_phi f) (-?rf f,Rep_phi f (?rf f)))\"\n      using 1 by (simp add: eq_onp_same_args uminus_lifted_pair.abs_eq)\n    also have \"... = Abs_lifted_pair (\\<lambda>f . (?rf f,Rep_phi f (-?rf f)))\"\n      by (metis (no_types, lifting) simp_phi triple_def triple.pairs_uminus.simps double_compl)\n    finally show ?thesis\n      by simp\n  qed\n  hence \"in_p_image (Abs_lifted_pair (\\<lambda>f . (?rf f,Rep_phi f (-?rf f))))\"\n    by blast\n  thus ?thesis\n    using 1 by (simp add: Rep_lifted_boolean_algebra_inverse Abs_lifted_pair_inverse Abs_regular_inverse)\nqed\n\ntext \\<open>\nThe isomorphism is established by proving the remaining Boolean algebra homomorphism properties.\n\\<close>\n\nlemma ba_iso:\n  \"boolean_algebra_isomorphism ba_iso\"\nproof (intro conjI)\n  show \"Abs_lifted_boolean_algebra (\\<lambda>f . fst (Rep_lifted_pair (Rep_regular bot) f)) = bot\"\n    by (simp add: bot_lifted_boolean_algebra_def bot_regular.rep_eq bot_lifted_pair.rep_eq)\n  show \"Abs_lifted_boolean_algebra (\\<lambda>f . fst (Rep_lifted_pair (Rep_regular top) f)) = top\"\n    by (simp add: top_lifted_boolean_algebra_def top_regular.rep_eq top_lifted_pair.rep_eq)\n  show \"\\<forall>pf qf . Abs_lifted_boolean_algebra (\\<lambda>f::('a,'b) phi . fst (Rep_lifted_pair (Rep_regular (pf \\<squnion> qf)) f)) = Abs_lifted_boolean_algebra (\\<lambda>f . fst (Rep_lifted_pair (Rep_regular pf) f)) \\<squnion> Abs_lifted_boolean_algebra (\\<lambda>f . fst (Rep_lifted_pair (Rep_regular qf) f))\"\n  proof (intro allI)\n    fix pf qf :: \"('a,'b) lifted_pair regular\"\n    {\n      fix f\n      obtain x y z w where 1: \"(x,y) = Rep_lifted_pair (Rep_regular pf) f \\<and> (z,w) = Rep_lifted_pair (Rep_regular qf) f\"\n        using prod.collapse by blast\n      have \"triple (Rep_phi f)\"\n        by (simp add: triple_def)\n      hence \"fst (triple.pairs_sup (x,y) (z,w)) = fst (x,y) \\<squnion> fst (z,w)\"\n        using triple.pairs_sup.simps by force\n      hence \"fst (triple.pairs_sup (Rep_lifted_pair (Rep_regular pf) f) (Rep_lifted_pair (Rep_regular qf) f)) = fst (Rep_lifted_pair (Rep_regular pf) f) \\<squnion> fst (Rep_lifted_pair (Rep_regular qf) f)\"\n        using 1 by simp\n      hence \"fst (Rep_lifted_pair (Rep_regular (pf \\<squnion> qf)) f) = fst (Rep_lifted_pair (Rep_regular pf) f) \\<squnion> fst (Rep_lifted_pair (Rep_regular qf) f)\"\n        by (unfold sup_regular.rep_eq sup_lifted_pair.rep_eq) simp\n    }\n    thus \"Abs_lifted_boolean_algebra (\\<lambda>f . fst (Rep_lifted_pair (Rep_regular (pf \\<squnion> qf)) f)) = Abs_lifted_boolean_algebra (\\<lambda>f . fst (Rep_lifted_pair (Rep_regular pf) f)) \\<squnion> Abs_lifted_boolean_algebra (\\<lambda>f . fst (Rep_lifted_pair (Rep_regular qf) f))\"\n      by (simp add: eq_onp_same_args sup_lifted_boolean_algebra.abs_eq sup_regular.rep_eq sup_lifted_boolean_algebra.rep_eq)\n  qed\n  show 1: \"\\<forall>pf qf . Abs_lifted_boolean_algebra (\\<lambda>f::('a,'b) phi . fst (Rep_lifted_pair (Rep_regular (pf \\<sqinter> qf)) f)) = Abs_lifted_boolean_algebra (\\<lambda>f . fst (Rep_lifted_pair (Rep_regular pf) f)) \\<sqinter> Abs_lifted_boolean_algebra (\\<lambda>f . fst (Rep_lifted_pair (Rep_regular qf) f))\"\n  proof (intro allI)\n    fix pf qf :: \"('a,'b) lifted_pair regular\"\n    {\n      fix f\n      obtain x y z w where 1: \"(x,y) = Rep_lifted_pair (Rep_regular pf) f \\<and> (z,w) = Rep_lifted_pair (Rep_regular qf) f\"\n        using prod.collapse by blast\n      have \"triple (Rep_phi f)\"\n        by (simp add: triple_def)\n      hence \"fst (triple.pairs_inf (x,y) (z,w)) = fst (x,y) \\<sqinter> fst (z,w)\"\n        using triple.pairs_inf.simps by force\n      hence \"fst (triple.pairs_inf (Rep_lifted_pair (Rep_regular pf) f) (Rep_lifted_pair (Rep_regular qf) f)) = fst (Rep_lifted_pair (Rep_regular pf) f) \\<sqinter> fst (Rep_lifted_pair (Rep_regular qf) f)\"\n        using 1 by simp\n      hence \"fst (Rep_lifted_pair (Rep_regular (pf \\<sqinter> qf)) f) = fst (Rep_lifted_pair (Rep_regular pf) f) \\<sqinter> fst (Rep_lifted_pair (Rep_regular qf) f)\"\n        by (unfold inf_regular.rep_eq inf_lifted_pair.rep_eq) simp\n    }\n    thus \"Abs_lifted_boolean_algebra (\\<lambda>f . fst (Rep_lifted_pair (Rep_regular (pf \\<sqinter> qf)) f)) = Abs_lifted_boolean_algebra (\\<lambda>f . fst (Rep_lifted_pair (Rep_regular pf) f)) \\<sqinter> Abs_lifted_boolean_algebra (\\<lambda>f . fst (Rep_lifted_pair (Rep_regular qf) f))\"\n      by (simp add: eq_onp_same_args inf_lifted_boolean_algebra.abs_eq inf_regular.rep_eq inf_lifted_boolean_algebra.rep_eq)\n  qed\n  show \"\\<forall>pf . Abs_lifted_boolean_algebra (\\<lambda>f::('a,'b) phi . fst (Rep_lifted_pair (Rep_regular (-pf)) f)) = -Abs_lifted_boolean_algebra (\\<lambda>f . fst (Rep_lifted_pair (Rep_regular pf) f))\"\n  proof\n    fix pf :: \"('a,'b) lifted_pair regular\"\n    {\n      fix f\n      obtain x y where 1: \"(x,y) = Rep_lifted_pair (Rep_regular pf) f\"\n        using prod.collapse by blast\n      have \"triple (Rep_phi f)\"\n        by (simp add: triple_def)\n      hence \"fst (triple.pairs_uminus (Rep_phi f) (x,y)) = -fst (x,y)\"\n        using triple.pairs_uminus.simps by force\n      hence \"fst (triple.pairs_uminus (Rep_phi f) (Rep_lifted_pair (Rep_regular pf) f)) = -fst (Rep_lifted_pair (Rep_regular pf) f)\"\n        using 1 by simp\n      hence \"fst (Rep_lifted_pair (Rep_regular (-pf)) f) = -fst (Rep_lifted_pair (Rep_regular pf) f)\"\n        by (unfold uminus_regular.rep_eq uminus_lifted_pair.rep_eq) simp\n    }\n    thus \"Abs_lifted_boolean_algebra (\\<lambda>f . fst (Rep_lifted_pair (Rep_regular (-pf)) f)) = -Abs_lifted_boolean_algebra (\\<lambda>f . fst (Rep_lifted_pair (Rep_regular pf) f))\"\n      by (simp add: eq_onp_same_args uminus_lifted_boolean_algebra.abs_eq uminus_regular.rep_eq uminus_lifted_boolean_algebra.rep_eq)\n  qed\n  thus \"\\<forall>pf qf . Abs_lifted_boolean_algebra (\\<lambda>f::('a,'b) phi . fst (Rep_lifted_pair (Rep_regular (pf - qf)) f)) = Abs_lifted_boolean_algebra (\\<lambda>f . fst (Rep_lifted_pair (Rep_regular pf) f)) - Abs_lifted_boolean_algebra (\\<lambda>f . fst (Rep_lifted_pair (Rep_regular qf) f))\"\n    using 1 by (simp add: diff_eq)\n  show \"bij ba_iso\"\n    by (rule invertible_bij[where g=ba_iso_inv]) (simp_all add: ba_iso_left_invertible ba_iso_right_invertible)\nqed\n\nsubsubsection \\<open>Distributive Lattice Isomorphism\\<close>\n\ntext \\<open>\nWe carry out a similar development for the isomorphism of distributive lattices.\nAgain, the original distributive lattice with a greatest element needs to be lifted to match the lifted pairs.\n\\<close>\n\ntypedef (overloaded) ('a,'b) lifted_distrib_lattice_top = \"{ xf::('a::non_trivial_boolean_algebra,'b::distrib_lattice_top) phi \\<Rightarrow> 'b . True }\"\n  by simp\n\nsetup_lifting type_definition_lifted_distrib_lattice_top\n\ninstantiation lifted_distrib_lattice_top :: (non_trivial_boolean_algebra,distrib_lattice_top) distrib_lattice_top\nbegin\n\nlift_definition sup_lifted_distrib_lattice_top :: \"('a,'b) lifted_distrib_lattice_top \\<Rightarrow> ('a,'b) lifted_distrib_lattice_top \\<Rightarrow> ('a,'b) lifted_distrib_lattice_top\" is \"\\<lambda>xf yf f . sup (xf f) (yf f)\" .\n\nlift_definition inf_lifted_distrib_lattice_top :: \"('a,'b) lifted_distrib_lattice_top \\<Rightarrow> ('a,'b) lifted_distrib_lattice_top \\<Rightarrow> ('a,'b) lifted_distrib_lattice_top\" is \"\\<lambda>xf yf f . inf (xf f) (yf f)\" .\n\nlift_definition top_lifted_distrib_lattice_top :: \"('a,'b) lifted_distrib_lattice_top\" is \"\\<lambda>f . top\" ..\n\nlift_definition less_eq_lifted_distrib_lattice_top :: \"('a,'b) lifted_distrib_lattice_top \\<Rightarrow> ('a,'b) lifted_distrib_lattice_top \\<Rightarrow> bool\" is \"\\<lambda>xf yf . \\<forall>f . less_eq (xf f) (yf f)\" .\n\nlift_definition less_lifted_distrib_lattice_top :: \"('a,'b) lifted_distrib_lattice_top \\<Rightarrow> ('a,'b) lifted_distrib_lattice_top \\<Rightarrow> bool\" is \"\\<lambda>xf yf . (\\<forall>f . less_eq (xf f) (yf f)) \\<and> \\<not> (\\<forall>f . less_eq (yf f) (xf f))\" .\n\ninstance\n  apply intro_classes\n  subgoal apply transfer by auto\n  subgoal apply transfer by auto\n  subgoal apply transfer using order_trans by blast\n  subgoal apply transfer using antisym ext by blast\n  subgoal apply transfer by auto\n  subgoal apply transfer by auto\n  subgoal apply transfer by auto\n  subgoal apply transfer by auto\n  subgoal apply transfer by auto\n  subgoal apply transfer by auto\n  subgoal apply transfer by auto\n  subgoal apply transfer by (simp add: sup_inf_distrib1)\n  done\n\nend\n\ntext \\<open>\nThe following function extracts the least element of the filter of a dense pair, which turns out to be a principal filter.\nIt is used to define one of the isomorphisms below.\n\\<close>\n\nfun get_dense :: \"('a::non_trivial_boolean_algebra,'b::distrib_lattice_top) lifted_pair dense \\<Rightarrow> ('a,'b) phi \\<Rightarrow> 'b\"\n  where \"get_dense pf f = (SOME z . Rep_lifted_pair (Rep_dense pf) f = (top,up_filter z))\"\n\nlemma get_dense_char:\n  \"Rep_lifted_pair (Rep_dense pf) f = (top,up_filter (get_dense pf f))\"\nproof -\n  obtain x y where 1: \"(x,y) = Rep_lifted_pair (Rep_dense pf) f \\<and> (x,y) \\<in> triple.pairs (Rep_phi f) \\<and> triple.pairs_uminus (Rep_phi f) (x,y) = triple.pairs_bot\"\n    by (metis bot_lifted_pair.rep_eq prod.collapse simp_dense simp_lifted_pair uminus_lifted_pair.rep_eq)\n  hence 2: \"x = top\"\n    by (simp add: triple.intro triple.pairs_uminus.simps dense_pp)\n  have \"triple (Rep_phi f)\"\n    by (simp add: triple_def)\n  hence \"\\<exists>z. y = Rep_phi f (-x) \\<squnion> up_filter z\"\n    using 1 triple.pairs_def by blast\n  then obtain z where \"y = up_filter z\"\n    using 2 by auto\n  hence \"Rep_lifted_pair (Rep_dense pf) f = (top,up_filter z)\"\n    using 1 2 by simp\n  thus ?thesis\n    by (metis (mono_tags, lifting) tfl_some get_dense.simps)\nqed\n\ntext \\<open>\nThe following two definitions give the distributive lattice isomorphism.\n\\<close>\n\nabbreviation dl_iso_inv :: \"('a::non_trivial_boolean_algebra,'b::distrib_lattice_top) lifted_distrib_lattice_top \\<Rightarrow> ('a,'b) lifted_pair dense\"\n  where \"dl_iso_inv \\<equiv> \\<lambda>xf . Abs_dense (Abs_lifted_pair (\\<lambda>f . (top,up_filter (Rep_lifted_distrib_lattice_top xf f))))\"\n\nabbreviation dl_iso :: \"('a::non_trivial_boolean_algebra,'b::distrib_lattice_top) lifted_pair dense \\<Rightarrow> ('a,'b) lifted_distrib_lattice_top\"\n  where \"dl_iso \\<equiv> \\<lambda>pf . Abs_lifted_distrib_lattice_top (get_dense pf)\"\n\nlemma dl_iso_inv_lifted_pair:\n  \"(top,up_filter (Rep_lifted_distrib_lattice_top xf f)) \\<in> triple.pairs (Rep_phi f)\"\n  by (metis (no_types, hide_lams) compl_bot_eq double_compl simp_phi sup_bot.left_neutral triple.sa_iso_pair triple_def)\n\nlemma dl_iso_inv_dense:\n  \"dense (Abs_lifted_pair (\\<lambda>f . (top,up_filter (Rep_lifted_distrib_lattice_top xf f))))\"\nproof -\n  have \"\\<forall>f . triple.pairs_uminus (Rep_phi f) (top,up_filter (Rep_lifted_distrib_lattice_top xf f)) = triple.pairs_bot\"\n    by (simp add: top_filter.abs_eq triple.pairs_uminus.simps triple_def)\n  hence \"bot = -Abs_lifted_pair (\\<lambda>f . (top,up_filter (Rep_lifted_distrib_lattice_top xf f)))\"\n    by (simp add: eq_onp_def uminus_lifted_pair.abs_eq dl_iso_inv_lifted_pair bot_lifted_pair_def)\n  thus ?thesis\n    by simp\nqed\n\ntext \\<open>\nThe following two results prove that the isomorphisms are mutually inverse.\n\\<close>\n\nlemma dl_iso_left_invertible:\n  \"dl_iso_inv (dl_iso pf) = pf\"\nproof -\n  have \"dl_iso_inv (dl_iso pf) = Abs_dense (Abs_lifted_pair (\\<lambda>f . (top,up_filter (get_dense pf f))))\"\n    by (metis Abs_lifted_distrib_lattice_top_inverse UNIV_I UNIV_def)\n  also have \"... = Abs_dense (Abs_lifted_pair (Rep_lifted_pair (Rep_dense pf)))\"\n    by (metis get_dense_char)\n  also have \"... = pf\"\n    by (simp add: Rep_dense_inverse Rep_lifted_pair_inverse)\n  finally show ?thesis\n    .\nqed\n\nlemma dl_iso_right_invertible:\n  \"dl_iso (dl_iso_inv xf) = xf\"\nproof -\n  let ?rf = \"Rep_lifted_distrib_lattice_top xf\"\n  let ?pf = \"Abs_dense (Abs_lifted_pair (\\<lambda>f . (top,up_filter (?rf f))))\"\n  have 1: \"\\<forall>f . (top,up_filter (?rf f)) \\<in> triple.pairs (Rep_phi f)\"\n  proof\n    fix f :: \"('a,'b) phi\"\n    have \"triple (Rep_phi f)\"\n      by (simp add: triple_def)\n    thus \"(top,up_filter (?rf f)) \\<in> triple.pairs (Rep_phi f)\"\n      using triple.pairs_def by force\n  qed\n  have 2: \"dense (Abs_lifted_pair (\\<lambda>f . (top,up_filter (?rf f))))\"\n  proof -\n    have \"-Abs_lifted_pair (\\<lambda>f . (top,up_filter (?rf f))) = Abs_lifted_pair (\\<lambda>f . triple.pairs_uminus (Rep_phi f) (top,up_filter (?rf f)))\"\n      using 1 by (simp add: eq_onp_same_args uminus_lifted_pair.abs_eq)\n    also have \"... = Abs_lifted_pair (\\<lambda>f . (bot,Rep_phi f top))\"\n      by (simp add: triple.pairs_uminus.simps triple_def)\n    also have \"... = Abs_lifted_pair (\\<lambda>f . triple.pairs_bot)\"\n      by (metis (no_types, hide_lams) simp_phi triple.phi_top triple_def)\n    also have \"... = bot\"\n      by (simp add: bot_lifted_pair_def)\n    finally show ?thesis\n      by simp\n  qed\n  have \"get_dense ?pf = ?rf\"\n  proof\n    fix f\n    have \"(top,up_filter (get_dense ?pf f)) = Rep_lifted_pair (Rep_dense ?pf) f\"\n      by (metis get_dense_char)\n    also have \"... = Rep_lifted_pair (Abs_lifted_pair (\\<lambda>f . (top,up_filter (?rf f)))) f\"\n      using Abs_dense_inverse 2 by force\n    also have \"... = (top,up_filter (?rf f))\"\n      using 1 by (simp add: Abs_lifted_pair_inverse)\n    finally show \"get_dense ?pf f = ?rf f\"\n      using up_filter_injective by auto\n  qed\n  thus ?thesis\n    by (simp add: Rep_lifted_distrib_lattice_top_inverse)\nqed\n\ntext \\<open>\nTo obtain the isomorphism, it remains to show the homomorphism properties of lattices with a greatest element.\n\\<close>\n\nlemma dl_iso:\n  \"bounded_lattice_top_isomorphism dl_iso\"\nproof (intro conjI)\n  have \"get_dense top = (\\<lambda>f::('a,'b) phi . top)\"\n  proof\n    fix f :: \"('a,'b) phi\"\n    have \"Rep_lifted_pair (Rep_dense top) f = (top,Abs_filter {top})\"\n      by (simp add: top_dense.rep_eq top_lifted_pair.rep_eq)\n    hence \"up_filter (get_dense top f) = Abs_filter {top}\"\n      by (metis prod.inject get_dense_char)\n    hence \"Rep_filter (up_filter (get_dense top f)) = {top}\"\n      by (metis bot_filter.abs_eq bot_filter.rep_eq)\n    thus \"get_dense top f = top\"\n      by (metis self_in_upset singletonD Abs_filter_inverse mem_Collect_eq up_filter)\n  qed\n  thus \"Abs_lifted_distrib_lattice_top (get_dense top::('a,'b) phi \\<Rightarrow> 'b) = top\"\n    by (metis top_lifted_distrib_lattice_top_def)\nnext\n  show \"\\<forall>pf qf :: ('a,'b) lifted_pair dense . Abs_lifted_distrib_lattice_top (get_dense (pf \\<squnion> qf)) = Abs_lifted_distrib_lattice_top (get_dense pf) \\<squnion> Abs_lifted_distrib_lattice_top (get_dense qf)\"\n  proof (intro allI)\n    fix pf qf :: \"('a,'b) lifted_pair dense\"\n    have 1: \"Abs_lifted_distrib_lattice_top (get_dense pf) \\<squnion> Abs_lifted_distrib_lattice_top (get_dense qf) = Abs_lifted_distrib_lattice_top (\\<lambda>f . get_dense pf f \\<squnion> get_dense qf f)\"\n      by (simp add: eq_onp_same_args sup_lifted_distrib_lattice_top.abs_eq)\n    have \"(\\<lambda>f . get_dense (pf \\<squnion> qf) f) = (\\<lambda>f . get_dense pf f \\<squnion> get_dense qf f)\"\n    proof\n      fix f\n      have \"(top,up_filter (get_dense (pf \\<squnion> qf) f)) = Rep_lifted_pair (Rep_dense (pf \\<squnion> qf)) f\"\n        by (metis get_dense_char)\n      also have \"... = triple.pairs_sup (Rep_lifted_pair (Rep_dense pf) f) (Rep_lifted_pair (Rep_dense qf) f)\"\n        by (simp add: sup_lifted_pair.rep_eq sup_dense.rep_eq)\n      also have \"... = triple.pairs_sup (top,up_filter (get_dense pf f)) (top,up_filter (get_dense qf f))\"\n        by (metis get_dense_char)\n      also have \"... = (top,up_filter (get_dense pf f) \\<sqinter> up_filter (get_dense qf f))\"\n        by (metis (no_types, lifting) calculation prod.simps(1) simp_phi triple.pairs_sup.simps triple_def)\n      also have \"... = (top,up_filter (get_dense pf f \\<squnion> get_dense qf f))\"\n        by (metis up_filter_dist_sup)\n      finally show \"get_dense (pf \\<squnion> qf) f = get_dense pf f \\<squnion> get_dense qf f\"\n        using up_filter_injective by blast\n    qed\n    thus \"Abs_lifted_distrib_lattice_top (get_dense (pf \\<squnion> qf)) = Abs_lifted_distrib_lattice_top (get_dense pf) \\<squnion> Abs_lifted_distrib_lattice_top (get_dense qf)\"\n      using 1 by metis\n  qed\nnext\n  show \"\\<forall>pf qf :: ('a,'b) lifted_pair dense . Abs_lifted_distrib_lattice_top (get_dense (pf \\<sqinter> qf)) = Abs_lifted_distrib_lattice_top (get_dense pf) \\<sqinter> Abs_lifted_distrib_lattice_top (get_dense qf)\"\n  proof (intro allI)\n    fix pf qf :: \"('a,'b) lifted_pair dense\"\n    have 1: \"Abs_lifted_distrib_lattice_top (get_dense pf) \\<sqinter> Abs_lifted_distrib_lattice_top (get_dense qf) = Abs_lifted_distrib_lattice_top (\\<lambda>f . get_dense pf f \\<sqinter> get_dense qf f)\"\n      by (simp add: eq_onp_same_args inf_lifted_distrib_lattice_top.abs_eq)\n    have \"(\\<lambda>f . get_dense (pf \\<sqinter> qf) f) = (\\<lambda>f . get_dense pf f \\<sqinter> get_dense qf f)\"\n    proof\n      fix f\n      have \"(top,up_filter (get_dense (pf \\<sqinter> qf) f)) = Rep_lifted_pair (Rep_dense (pf \\<sqinter> qf)) f\"\n        by (metis get_dense_char)\n      also have \"... = triple.pairs_inf (Rep_lifted_pair (Rep_dense pf) f) (Rep_lifted_pair (Rep_dense qf) f)\"\n        by (simp add: inf_lifted_pair.rep_eq inf_dense.rep_eq)\n      also have \"... = triple.pairs_inf (top,up_filter (get_dense pf f)) (top,up_filter (get_dense qf f))\"\n        by (metis get_dense_char)\n      also have \"... = (top,up_filter (get_dense pf f) \\<squnion> up_filter (get_dense qf f))\"\n        by (metis (no_types, lifting) calculation prod.simps(1) simp_phi triple.pairs_inf.simps triple_def)\n      also have \"... = (top,up_filter (get_dense pf f \\<sqinter> get_dense qf f))\"\n        by (metis up_filter_dist_inf)\n      finally show \"get_dense (pf \\<sqinter> qf) f = get_dense pf f \\<sqinter> get_dense qf f\"\n        using up_filter_injective by blast\n    qed\n    thus \"Abs_lifted_distrib_lattice_top (get_dense (pf \\<sqinter> qf)) = Abs_lifted_distrib_lattice_top (get_dense pf) \\<sqinter> Abs_lifted_distrib_lattice_top (get_dense qf)\"\n      using 1 by metis\n  qed\nnext\n  show \"bij dl_iso\"\n    by (rule invertible_bij[where g=dl_iso_inv]) (simp_all add: dl_iso_left_invertible dl_iso_right_invertible)\nqed\n\nsubsubsection \\<open>Structure Map Preservation\\<close>\n\ntext \\<open>\nWe finally show that the isomorphisms are compatible with the structure maps.\nThis involves lifting the distributive lattice isomorphism to filters of distributive lattices (as these are the targets of the structure maps).\nTo this end, we first show that the lifted isomorphism preserves filters.\n\\<close>\n\nlemma phi_iso_filter:\n  \"filter ((\\<lambda>qf::('a::non_trivial_boolean_algebra,'b::distrib_lattice_top) lifted_pair dense . Rep_lifted_distrib_lattice_top (dl_iso qf) f) ` Rep_filter (stone_phi pf))\"\nproof (rule filter_map_filter)\n  show \"mono (\\<lambda>qf::('a::non_trivial_boolean_algebra,'b::distrib_lattice_top) lifted_pair dense . Rep_lifted_distrib_lattice_top (dl_iso qf) f)\"\n    by (metis (no_types, lifting) mono_def dl_iso le_iff_sup sup_lifted_distrib_lattice_top.rep_eq)\nnext\n  show \"\\<forall>qf y . Rep_lifted_distrib_lattice_top (dl_iso qf) f \\<le> y \\<longrightarrow> (\\<exists>rf . qf \\<le> rf \\<and> y = Rep_lifted_distrib_lattice_top (dl_iso rf) f)\"\n  proof (intro allI, rule impI)\n    fix qf :: \"('a,'b) lifted_pair dense\"\n    fix y :: 'b\n    assume 1: \"Rep_lifted_distrib_lattice_top (dl_iso qf) f \\<le> y\"\n    let ?rf = \"Abs_dense (Abs_lifted_pair (\\<lambda>g . if g = f then (top,up_filter y) else Rep_lifted_pair (Rep_dense qf) g))\"\n    have 2: \"\\<forall>g . (if g = f then (top,up_filter y) else Rep_lifted_pair (Rep_dense qf) g) \\<in> triple.pairs (Rep_phi g)\"\n      by (metis Abs_lifted_distrib_lattice_top_inverse dl_iso_inv_lifted_pair mem_Collect_eq simp_lifted_pair)\n    hence \"-Abs_lifted_pair (\\<lambda>g . if g = f then (top,up_filter y) else Rep_lifted_pair (Rep_dense qf) g) = Abs_lifted_pair (\\<lambda>g . triple.pairs_uminus (Rep_phi g) (if g = f then (top,up_filter y) else Rep_lifted_pair (Rep_dense qf) g))\"\n      by (simp add: eq_onp_def uminus_lifted_pair.abs_eq)\n    also have \"... = Abs_lifted_pair (\\<lambda>g . if g = f then triple.pairs_uminus (Rep_phi g) (top,up_filter y) else triple.pairs_uminus (Rep_phi g) (Rep_lifted_pair (Rep_dense qf) g))\"\n      by (simp add: if_distrib)\n    also have \"... = Abs_lifted_pair (\\<lambda>g . if g = f then (bot,top) else triple.pairs_uminus (Rep_phi g) (Rep_lifted_pair (Rep_dense qf) g))\"\n      by (subst triple.pairs_uminus.simps, simp add: triple_def, metis compl_top_eq simp_phi)\n    also have \"... = Abs_lifted_pair (\\<lambda>g . if g = f then (bot,top) else (bot,top))\"\n      by (metis bot_lifted_pair.rep_eq simp_dense top_filter.abs_eq uminus_lifted_pair.rep_eq)\n    also have \"... = bot\"\n      by (simp add: bot_lifted_pair.abs_eq top_filter.abs_eq)\n    finally have 3: \"Abs_lifted_pair (\\<lambda>g . if g = f then (top,up_filter y) else Rep_lifted_pair (Rep_dense qf) g) \\<in> dense_elements\"\n      by blast\n    hence \"(top,up_filter (get_dense (Abs_dense (Abs_lifted_pair (\\<lambda>g . if g = f then (top,up_filter y) else Rep_lifted_pair (Rep_dense qf) g))) f)) = Rep_lifted_pair (Rep_dense (Abs_dense (Abs_lifted_pair (\\<lambda>g . if g = f then (top,up_filter y) else Rep_lifted_pair (Rep_dense qf) g)))) f\"\n      by (metis (mono_tags, lifting) get_dense_char)\n    also have \"... = Rep_lifted_pair (Abs_lifted_pair (\\<lambda>g . if g = f then (top,up_filter y) else Rep_lifted_pair (Rep_dense qf) g)) f\"\n      using 3 by (simp add: Abs_dense_inverse)\n    also have \"... = (top,up_filter y)\"\n      using 2 by (simp add: Abs_lifted_pair_inverse)\n    finally have \"get_dense (Abs_dense (Abs_lifted_pair (\\<lambda>g . if g = f then (top,up_filter y) else Rep_lifted_pair (Rep_dense qf) g))) f = y\"\n      using up_filter_injective by blast\n    hence 4: \"Rep_lifted_distrib_lattice_top (dl_iso ?rf) f = y\"\n      by (simp add: Abs_lifted_distrib_lattice_top_inverse)\n    {\n      fix g\n      have \"Rep_lifted_distrib_lattice_top (dl_iso qf) g \\<le> Rep_lifted_distrib_lattice_top (dl_iso ?rf) g\"\n      proof (cases \"g = f\")\n        assume \"g = f\"\n        thus ?thesis\n          using 1 4 by simp\n      next\n        assume 5: \"g \\<noteq> f\"\n        have \"(top,up_filter (get_dense ?rf g)) = Rep_lifted_pair (Rep_dense (Abs_dense (Abs_lifted_pair (\\<lambda>g . if g = f then (top,up_filter y) else Rep_lifted_pair (Rep_dense qf) g)))) g\"\n          by (metis (mono_tags, lifting) get_dense_char)\n        also have \"... = Rep_lifted_pair (Abs_lifted_pair (\\<lambda>g . if g = f then (top,up_filter y) else Rep_lifted_pair (Rep_dense qf) g)) g\"\n          using 3 by (simp add: Abs_dense_inverse)\n        also have \"... = Rep_lifted_pair (Rep_dense qf) g\"\n          using 2 5 by (simp add: Abs_lifted_pair_inverse)\n        also have \"... = (top,up_filter (get_dense qf g))\"\n          using get_dense_char by auto\n        finally have \"get_dense ?rf g = get_dense qf g\"\n          using up_filter_injective by blast\n        thus \"Rep_lifted_distrib_lattice_top (dl_iso qf) g \\<le> Rep_lifted_distrib_lattice_top (dl_iso ?rf) g\"\n          by (simp add: Abs_lifted_distrib_lattice_top_inverse)\n      qed\n    }\n    hence \"Rep_lifted_distrib_lattice_top (dl_iso qf) \\<le> Rep_lifted_distrib_lattice_top (dl_iso ?rf)\"\n      by (simp add: le_funI)\n    hence 6: \"dl_iso qf \\<le> dl_iso ?rf\"\n      by (simp add: le_funD less_eq_lifted_distrib_lattice_top.rep_eq)\n    hence \"qf \\<le> ?rf\"\n      by (metis (no_types, lifting) dl_iso sup_isomorphism_ord_isomorphism)\n    thus \"\\<exists>rf . qf \\<le> rf \\<and> y = Rep_lifted_distrib_lattice_top (dl_iso rf) f\"\n      using 4 by auto\n  qed\nqed\n\ntext \\<open>\nThe commutativity property states that the same result is obtained in two ways by starting with a regular lifted pair \\<open>pf\\<close>:\n\\begin{itemize}\n\\item apply the Boolean algebra isomorphism to the pair; then apply a structure map \\<open>f\\<close> to obtain a filter of dense elements; or,\n\\item apply the structure map \\<open>stone_phi\\<close> to the pair; then apply the distributive lattice isomorphism lifted to the resulting filter.\n\\end{itemize}\n\\<close>\n\nlemma phi_iso:\n  \"Rep_phi f (Rep_lifted_boolean_algebra (ba_iso pf) f) = filter_map (\\<lambda>qf::('a::non_trivial_boolean_algebra,'b::distrib_lattice_top) lifted_pair dense . Rep_lifted_distrib_lattice_top (dl_iso qf) f) (stone_phi pf)\"\nproof -\n  let ?r = \"Rep_phi f\"\n  let ?ppf = \"\\<lambda>g . triple.pairs_uminus (Rep_phi g) (Rep_lifted_pair (Rep_regular pf) g)\"\n  have 1: \"triple ?r\"\n    by (simp add: triple_def)\n  have 2: \"Rep_filter (?r (fst (Rep_lifted_pair (Rep_regular pf) f))) \\<subseteq> { z . \\<exists>qf . -Rep_regular pf \\<le> Rep_dense qf \\<and> z = get_dense qf f }\"\n  proof\n    fix z\n    obtain x where 3: \"x = fst (Rep_lifted_pair (Rep_regular pf) f)\"\n      by simp\n    assume \"z \\<in> Rep_filter (?r (fst (Rep_lifted_pair (Rep_regular pf) f)))\"\n    hence \"\\<up>z \\<subseteq> Rep_filter (?r x)\"\n      using 3 filter_def by fastforce\n    hence 4: \"up_filter z \\<le> ?r x\"\n      by (metis Rep_filter_cases Rep_filter_inverse less_eq_filter.rep_eq mem_Collect_eq up_filter)\n    have 5: \"\\<forall>g . ?ppf g \\<in> triple.pairs (Rep_phi g)\"\n      by (metis (no_types) simp_lifted_pair uminus_lifted_pair.rep_eq)\n    let ?zf = \"\\<lambda>g . if g = f then (top,up_filter z) else triple.pairs_top\"\n    have 6: \"\\<forall>g . ?zf g \\<in> triple.pairs (Rep_phi g)\"\n    proof\n      fix g :: \"('a,'b) phi\"\n      have \"triple (Rep_phi g)\"\n        by (simp add: triple_def)\n      hence \"(top,up_filter z) \\<in> triple.pairs (Rep_phi g)\"\n        using triple.pairs_def by force\n      thus \"?zf g \\<in> triple.pairs (Rep_phi g)\"\n        by (metis simp_lifted_pair top_lifted_pair.rep_eq)\n    qed\n    hence \"-Abs_lifted_pair ?zf = Abs_lifted_pair (\\<lambda>g . triple.pairs_uminus (Rep_phi g) (?zf g))\"\n      by (subst uminus_lifted_pair.abs_eq) (simp_all add: eq_onp_same_args)\n    also have \"... = Abs_lifted_pair (\\<lambda>g . if g = f then triple.pairs_uminus (Rep_phi g) (top,up_filter z) else triple.pairs_uminus (Rep_phi g) triple.pairs_top)\"\n      by (rule arg_cong[where f=Abs_lifted_pair]) auto\n    also have \"... = Abs_lifted_pair (\\<lambda>g . triple.pairs_bot)\"\n      using 1 by (metis bot_lifted_pair.rep_eq dense_closed_top top_lifted_pair.rep_eq triple.pairs_uminus.simps uminus_lifted_pair.rep_eq)\n    finally have 7: \"Abs_lifted_pair ?zf \\<in> dense_elements\"\n      by (simp add: bot_lifted_pair.abs_eq)\n    let ?qf = \"Abs_dense (Abs_lifted_pair ?zf)\"\n    have \"\\<forall>g . triple.pairs_less_eq (?ppf g) (?zf g)\"\n    proof\n      fix g\n      show \"triple.pairs_less_eq (?ppf g) (?zf g)\"\n      proof (cases \"g = f\")\n        assume 8: \"g = f\"\n        hence 9: \"?ppf g = (-x,?r x)\"\n          using 1 3 by (metis prod.collapse triple.pairs_uminus.simps)\n        have \"triple.pairs_less_eq (-x,?r x) (top,up_filter z)\"\n          using 1 4 by (meson inf.bot_least triple.pairs_less_eq.simps)\n        thus ?thesis\n          using 8 9 by simp\n      next\n        assume 10: \"g \\<noteq> f\"\n        have \"triple.pairs_less_eq (?ppf g) triple.pairs_top\"\n          using 1 by (metis (no_types, hide_lams) bot.extremum top_greatest prod.collapse triple_def triple.pairs_less_eq.simps triple.phi_bot)\n        thus ?thesis\n          using 10 by simp\n      qed\n    qed\n    hence \"Abs_lifted_pair ?ppf \\<le> Abs_lifted_pair ?zf\"\n      using 5 6 by (subst less_eq_lifted_pair.abs_eq) (simp_all add: eq_onp_same_args)\n    hence 11: \"-Rep_regular pf \\<le> Rep_dense ?qf\"\n      using 7 by (simp add: uminus_lifted_pair_def Abs_dense_inverse)\n    have \"(top,up_filter (get_dense ?qf f)) = Rep_lifted_pair (Rep_dense ?qf) f\"\n      by (metis get_dense_char)\n    also have \"... = (top,up_filter z)\"\n      using 6 7 Abs_dense_inverse Abs_lifted_pair_inverse by force\n    finally have \"z = get_dense ?qf f\"\n      using up_filter_injective by force\n    thus \"z \\<in> { z . \\<exists>qf . -Rep_regular pf \\<le> Rep_dense qf \\<and> z = get_dense qf f }\"\n      using 11 by auto\n  qed\n  have 12: \"Rep_filter (?r (fst (Rep_lifted_pair (Rep_regular pf) f))) \\<supseteq> { z . \\<exists>qf . -Rep_regular pf \\<le> Rep_dense qf \\<and> z = get_dense qf f }\"\n  proof\n    fix z\n    assume \"z \\<in> { z . \\<exists>qf . -Rep_regular pf \\<le> Rep_dense qf \\<and> z = get_dense qf f }\"\n    hence \"\\<exists>qf . -Rep_regular pf \\<le> Rep_dense qf \\<and> z = get_dense qf f\"\n      by auto\n    hence \"triple.pairs_less_eq (Rep_lifted_pair (-Rep_regular pf) f) (top,up_filter z)\"\n      by (metis less_eq_lifted_pair.rep_eq get_dense_char)\n    hence \"up_filter z \\<le> snd (Rep_lifted_pair (-Rep_regular pf) f)\"\n      using 1 by (metis (no_types, hide_lams) prod.collapse triple.pairs_less_eq.simps)\n    also have \"... = snd (?ppf f)\"\n      by (metis uminus_lifted_pair.rep_eq)\n    also have \"... = ?r (fst (Rep_lifted_pair (Rep_regular pf) f))\"\n      using 1 by (metis (no_types) prod.collapse prod.inject triple.pairs_uminus.simps)\n    finally have \"Rep_filter (up_filter z) \\<subseteq> Rep_filter (?r (fst (Rep_lifted_pair (Rep_regular pf) f)))\"\n      by (simp add: less_eq_filter.rep_eq)\n    hence \"\\<up>z \\<subseteq> Rep_filter (?r (fst (Rep_lifted_pair (Rep_regular pf) f)))\"\n      by (metis Abs_filter_inverse mem_Collect_eq up_filter)\n    thus \"z \\<in> Rep_filter (?r (fst (Rep_lifted_pair (Rep_regular pf) f)))\"\n      by blast\n  qed\n  have 13: \"\\<forall>qf\\<in>Rep_filter (stone_phi pf) . Rep_lifted_distrib_lattice_top (Abs_lifted_distrib_lattice_top (get_dense qf)) f = get_dense qf f\"\n    by (metis Abs_lifted_distrib_lattice_top_inverse UNIV_I UNIV_def)\n  have \"Rep_filter (?r (fst (Rep_lifted_pair (Rep_regular pf) f))) = { z . \\<exists>qf\\<in>stone_phi_base pf . z = get_dense qf f }\"\n    using 2 12 by simp\n  hence \"?r (fst (Rep_lifted_pair (Rep_regular pf) f)) = Abs_filter { z . \\<exists>qf\\<in>stone_phi_base pf . z = get_dense qf f }\"\n    by (metis Rep_filter_inverse)\n  hence \"?r (Rep_lifted_boolean_algebra (ba_iso pf) f) = Abs_filter { z . \\<exists>qf\\<in>Rep_filter (stone_phi pf) . z = Rep_lifted_distrib_lattice_top (dl_iso qf) f }\"\n    using 13 by (simp add: Abs_filter_inverse stone_phi_base_filter stone_phi_def Abs_lifted_boolean_algebra_inverse)\n  thus ?thesis\n    by (simp add: image_def)\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_Algebras/Stone_Construction.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.888758793492457, "lm_q2_score": 0.7981867825403177, "lm_q1q2_score": 0.7093955218321589}}
{"text": "(*  File:       Evaluation_Function.thy\n    Copyright   2021  Karlsruhe Institute of Technology (KIT)\n*)\n\\<^marker>\\<open>creator \"Stephan Bohr, Karlsruhe Institute of Technology (KIT)\"\\<close>\n\\<^marker>\\<open>contributor \"Michael Kirsten, Karlsruhe Institute of Technology (KIT)\"\\<close>\n\nsection \\<open>Evaluation Function\\<close>\n\ntheory Evaluation_Function\n  imports \"Social_Choice_Types/Profile\"\nbegin\n\ntext\n\\<open>This is the evaluation function. From a set of currently eligible alternatives,\nthe evaluation function computes a numerical value that is then to be used for\nfurther (s)election, e.g., by the elimination module.\\<close>\n\nsubsection \\<open>Definition\\<close>\n\ntype_synonym 'a Evaluation_Function = \"'a  \\<Rightarrow> 'a set \\<Rightarrow> 'a Profile \\<Rightarrow> nat\"\n\nsubsection \\<open>Property\\<close>\n\n(*\n   An Evaluation function is Condorcet-rating iff the following holds:\n   If a Condorcet Winner w exists, w and only w has the highest value.\n*)\ndefinition condorcet_rating :: \"'a Evaluation_Function \\<Rightarrow> bool\" where\n  \"condorcet_rating f \\<equiv>\n    \\<forall>A p w . condorcet_winner A p w \\<longrightarrow>\n      (\\<forall>l \\<in> A . l \\<noteq> w \\<longrightarrow> f l A p < f w A p)\"\n\nsubsection \\<open>Theorems\\<close>\n\n(*\n   If e is Condorcet-rating, the following holds:\n   If a Condorcet Winner w exists, w has the maximum evaluation value.\n*)\ntheorem cond_winner_imp_max_eval_val:\n  assumes\n    rating: \"condorcet_rating e\" and\n    f_prof: \"finite_profile A p\" and\n    winner: \"condorcet_winner A p w\"\n  shows \"e w A p = Max {e a A p | a. a \\<in> A}\"\nproof -\n  (*\n    lemma eq_max_iff: \"\\<lbrakk> finite A; A \\<noteq> {} \\<rbrakk> \\<Longrightarrow>\n        m = Max A  \\<longleftrightarrow>  m \\<in> A \\<and> (\\<forall>a \\<in> A. a \\<le> m)\"\n  *)\n  let ?set = \"{e a A p | a. a \\<in> A}\" and\n      ?eMax = \"Max {e a A p | a. a \\<in> A}\" and\n      ?eW = \"e w A p\"\n  (*finite A*)\n  from f_prof have 0: \"finite ?set\"\n    by simp\n  (*2. non-empty A*)\n  have 1: \"?set \\<noteq> {}\"\n    using condorcet_winner.simps winner\n    by fastforce\n  (*3. m \\<in> A*)\n  have 2: \"?eW \\<in> ?set\"\n    using CollectI condorcet_winner.simps winner\n    by (metis (mono_tags, lifting))\n  (*4. (\\<forall>a \\<in> A. a \\<le> m)*)\n  have 3: \"\\<forall> e \\<in> ?set . e \\<le> ?eW\"\n  proof (safe)\n    fix a :: \"'a\"\n    assume aInA: \"a \\<in> A\"\n    have \"\\<forall>n na. (n::nat) \\<noteq> na \\<or> n \\<le> na\"\n      by simp\n    with aInA show \"e a A p \\<le> e w A p\"\n      using condorcet_rating_def\n            less_imp_le rating winner\n      by (metis (no_types))\n  qed\n  (*Result*)\n  from 2 3 have 4:\n    \"?eW \\<in> ?set \\<and> (\\<forall>a \\<in> ?set. a \\<le> ?eW)\"\n    by blast\n  from 0 1 4 Max_eq_iff\n  show ?thesis\n    by (metis (no_types, lifting))\nqed\n\n(*\n   If e is Condorcet-rating, the following holds:\n   If a Condorcet Winner w exists, a non-Condorcet\n   winner has a value lower than the maximum\n   evaluation value.\n*)\ntheorem non_cond_winner_not_max_eval:\n  assumes\n    rating: \"condorcet_rating e\" and\n    f_prof: \"finite_profile A p\" and\n    winner: \"condorcet_winner A p w\" and\n    linA: \"l \\<in> A\" and\n    loser: \"w \\<noteq> l\"\n  shows \"e l A p < Max {e a A p | a. a \\<in> A}\"\nproof -\n  have \"e l A p < e w A p\"\n    using condorcet_rating_def linA loser rating winner\n    by metis\n  also have \"e w A p = Max {e a A p |a. a \\<in> A}\"\n    using cond_winner_imp_max_eval_val f_prof rating winner\n    by fastforce\n  finally show ?thesis\n    by simp\nqed\n\nend\n", "meta": {"author": "ChrisMackKit", "repo": "ba-scoring-rule-reinforcement-homogeneity", "sha": "d87febd04743389ac578b332349ae446b9c55e89", "save_path": "github-repos/isabelle/ChrisMackKit-ba-scoring-rule-reinforcement-homogeneity", "path": "github-repos/isabelle/ChrisMackKit-ba-scoring-rule-reinforcement-homogeneity/ba-scoring-rule-reinforcement-homogeneity-d87febd04743389ac578b332349ae446b9c55e89/verifiedVotingRuleConstruction-master - Bevor Range/theories/Compositional_Structures/Basic_Modules/Component_Types/Evaluation_Function.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8887587993853654, "lm_q2_score": 0.7981867753392728, "lm_q1q2_score": 0.7093955201358085}}
{"text": "theory CS_Ch3_Ex4\nimports Main\nbegin\n\ntype_synonym vname = string\ndatatype aexp = N int | V vname | Plus aexp aexp | Times 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 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\"\napply(induction a1 a2 rule: plus.induct)\napply(auto)\ndone\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 (N i) a)\" |\n\"times a b = Times a b\"\n\nlemma aval_times: \"aval (times a1 a2) s = aval a1 s * aval a2 s\"\napply(induction a1 a2 rule: times.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 a1 a2) = plus (asimp a1) (asimp a2)\" |\n\"asimp (Times a1 a2) = times (asimp a1) (asimp a2)\"\n\nlemma \"aval (asimp a) s = aval a s\"\napply(induction a)\napply(auto simp add: aval_plus aval_times)\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_Ch3_Ex4.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587993853654, "lm_q2_score": 0.7981867705385762, "lm_q1q2_score": 0.7093955158691472}}
{"text": "(* Author: Tobias Nipkow *)\n\ntheory Def_Init_Exp\nimports Vars\nbegin\n\nsubsection \"Initialization-Sensitive Expressions Evaluation\"\n\ntype_synonym state = \"vname \\<Rightarrow> val option\"\n\n\nfun aval :: \"aexp \\<Rightarrow> state \\<Rightarrow> val option\" where\n\"aval (N i) s = Some i\" |\n\"aval (V x) s = s x\" |\n\"aval (Plus a\\<^sub>1 a\\<^sub>2) s =\n  (case (aval a\\<^sub>1 s, aval a\\<^sub>2 s) of\n     (Some i\\<^sub>1,Some i\\<^sub>2) \\<Rightarrow> Some(i\\<^sub>1+i\\<^sub>2) | _ \\<Rightarrow> None)\"\n\n\nfun bval :: \"bexp \\<Rightarrow> state \\<Rightarrow> bool option\" where\n\"bval (Bc v) s = Some v\" |\n\"bval (Not b) s = (case bval b s of None \\<Rightarrow> None | Some bv \\<Rightarrow> Some(\\<not> bv))\" |\n\"bval (And b\\<^sub>1 b\\<^sub>2) s = (case (bval b\\<^sub>1 s, bval b\\<^sub>2 s) of\n  (Some bv\\<^sub>1, Some bv\\<^sub>2) \\<Rightarrow> Some(bv\\<^sub>1 & bv\\<^sub>2) | _ \\<Rightarrow> None)\" |\n\"bval (Less a\\<^sub>1 a\\<^sub>2) s = (case (aval a\\<^sub>1 s, aval a\\<^sub>2 s) of\n (Some i\\<^sub>1, Some i\\<^sub>2) \\<Rightarrow> Some(i\\<^sub>1 < i\\<^sub>2) | _ \\<Rightarrow> None)\"\n\n\nlemma aval_Some: \"vars a \\<subseteq> dom s \\<Longrightarrow> \\<exists> i. aval a s = Some i\"\nby (induct a) auto\n\nlemma bval_Some: \"vars b \\<subseteq> dom s \\<Longrightarrow> \\<exists> bv. bval b s = Some bv\"\nby (induct b) (auto dest!: aval_Some)\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/Def_Init_Exp.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8652240756264638, "lm_q2_score": 0.8198933359135361, "lm_q1q2_score": 0.709391453678087}}
{"text": "theory SFHOL imports Main\nbegin \n\n(* A nonpolymorphic Embedding of Supervaluational Free Higher-Order Logic (SFHOL) in HOL *)\n\n\ntext \\<open> Negative Free Higher-Order Modal Logic \\<close>\n\n  (* A nonpolymorphic Embedding of Negative Free Higher-Order Modal Logic (NgFHOML) in HOL *)\n\n  typedecl i (* \u2014 Type for individuals *)\n  typedecl w (* \u2014 Type of possible worlds *) \n  type_synonym \\<mu> = \"w \\<Rightarrow> bool\" (* \u2014 Type of world depended formulas *) \n\n  consts fExistenceI :: \"i \\<Rightarrow> \\<mu>\" (\"E\\<^sup>i\") (* \u2014 Existence/definedness predicate for individuals *)\n  consts fExistenceP :: \"(i \\<Rightarrow> \\<mu>) \\<Rightarrow> \\<mu>\" (\"E\\<^sup>p\") (* \u2014 Existence/definedness predicate for predicates *)\n\n  consts r :: \"w \\<Rightarrow> w \\<Rightarrow> bool\" (infixr \"r\" 53) (* \u2014 Accessibility relation between worlds *)\n\n  (* Conditions on the accessibility relation *)\n  abbreviation reflexive :: \"bool\"\n    where \"reflexive \\<equiv> \\<forall>x. x r x\"\n  abbreviation transitive :: \"bool\"\n    where \"transitive \\<equiv> \\<forall>x y z. (x r y) \\<and> (y r z) \\<longrightarrow> (x r z)\"\n  abbreviation mcKinseysAxiom :: \"bool\"\n    where \"mcKinseysAxiom \\<equiv> \\<forall>x. \\<exists>y. (x r y) \\<and> (\\<forall>z. (y r z) \\<longrightarrow> y = z)\"\n  axiomatization where S41: \n    \"reflexive \\<and> transitive \\<and> mcKinseysAxiom\"\n\n  axiomatization where nestedDomains: (* \u2014 Nested domains property: If some object exists at a world w, then it also exists in all from w reachable worlds *) \n    \"\\<forall>x y. x r y \\<longrightarrow> (\\<forall>z. E\\<^sup>i z x \\<longrightarrow> E\\<^sup>i z y)\"\n  (* axiomatization where Ax2: \"\\<exists>x. \\<forall>y. x r y\" *) (* \u2014 There exists a world from which every world is reachable *)\n  (* axiomatization where Ax3: \"\\<forall>x y. x r y \\<longrightarrow> (\\<forall>z. ((E\\<^sup>i z x) \\<and> (P z x)) \\<longrightarrow> (P z y))\" *) (* \u2014 If some existent object in a world w has property P, this object has the same property in all from w reachable worlds *)\n\n  definition fmIdentity :: \"i \\<Rightarrow> i \\<Rightarrow> \\<mu>\" (infixr \"\\<^bold>=\\<^sub>f\\<^sub>m\" 56) (* \u2014 Free modal identity *)\n    where \"\\<phi> \\<^bold>=\\<^sub>f\\<^sub>m \\<psi> \\<equiv> \\<lambda>w. \\<phi> = \\<psi>\"\n\n  definition fmNot :: \"\\<mu> \\<Rightarrow> \\<mu>\" (\"\\<^bold>\\<not>\\<^sub>f\\<^sub>m_\" [52]53) (* \u2014 Free modal negation *)\n    where \"\\<^bold>\\<not>\\<^sub>f\\<^sub>m\\<phi> \\<equiv> \\<lambda>w. \\<not>(\\<phi> w)\"\n  definition fmOr :: \"\\<mu> \\<Rightarrow> \\<mu> \\<Rightarrow> \\<mu>\" (infixr \"\\<^bold>\\<or>\\<^sub>f\\<^sub>m\" 51) (* \u2014 Free modal disjunction *)\n    where \"\\<phi> \\<^bold>\\<or>\\<^sub>f\\<^sub>m \\<psi> \\<equiv> \\<lambda>w. \\<phi> w \\<or> \\<psi> w\" \n\n  definition fmBox :: \"\\<mu> \\<Rightarrow> \\<mu>\" (\"\\<^bold>\\<box>_\" [52]53) (* \u2014 Free modal necessity *)\n    where \"\\<^bold>\\<box>\\<phi> \\<equiv> \\<lambda>w. \\<forall>v. w r v \\<longrightarrow> \\<phi> v\"\n\n  definition fmForallI :: \"(i \\<Rightarrow> \\<mu>) \\<Rightarrow> \\<mu>\" (\"\\<^bold>\\<forall>\\<^sup>i\\<^sub>f\\<^sub>m\") (* \u2014 Free modal universal quantification over individuals guarded by predicate E *)\n    where \"\\<^bold>\\<forall>\\<^sup>i\\<^sub>f\\<^sub>m\\<Phi> \\<equiv> \\<lambda>w. \\<forall>x. E\\<^sup>i x w \\<longrightarrow> \\<Phi> x w\"\n  definition fmForallIBinder:: \"(i \\<Rightarrow> \\<mu>) \\<Rightarrow> \\<mu>\" (binder \"\\<^bold>\\<forall>\\<^sup>i\\<^sub>f\\<^sub>m\" [8]9) (* \u2014 Binder notation *)\n    where \"\\<^bold>\\<forall>\\<^sup>i\\<^sub>f\\<^sub>mx. \\<phi> x \\<equiv> \\<^bold>\\<forall>\\<^sup>i\\<^sub>f\\<^sub>m\\<phi>\"   \n  definition fmForallP :: \"((i \\<Rightarrow> \\<mu>) \\<Rightarrow> \\<mu>) \\<Rightarrow> \\<mu>\" (\"\\<^bold>\\<forall>\\<^sup>p\\<^sub>f\\<^sub>m\") (* \u2014 Free modal universal quantification over predicates guarded by predicate E *)\n    where \"\\<^bold>\\<forall>\\<^sup>p\\<^sub>f\\<^sub>m\\<Phi> \\<equiv> \\<lambda>w. \\<forall>x. E\\<^sup>p x w \\<longrightarrow> \\<Phi> x w\"\n  definition fmForallPBinder:: \"((i \\<Rightarrow> \\<mu>) \\<Rightarrow> \\<mu>) \\<Rightarrow> \\<mu>\" (binder \"\\<^bold>\\<forall>\\<^sup>p\\<^sub>f\\<^sub>m\" [8]9) (* \u2014 Binder notation *)\n    where \"\\<^bold>\\<forall>\\<^sup>p\\<^sub>f\\<^sub>mx. \\<phi> x \\<equiv> \\<^bold>\\<forall>\\<^sup>p\\<^sub>f\\<^sub>m\\<phi>\"\n\n  definition fmPredicateI :: \"(i \\<Rightarrow> \\<mu>) \\<Rightarrow> i \\<Rightarrow> \\<mu>\" (\"\\<^sup>f\\<^sup>m\") (* \u2014 Free modal predicate guarded by predicate E *)\n     where \"\\<^sup>f\\<^sup>mP x \\<equiv>  \\<lambda>w. E\\<^sup>i x w \\<and> P x w\"\n\n  definition fmValid :: \"\\<mu> \\<Rightarrow> bool\" (\"\\<lfloor>_\\<rfloor>\\<^sub>f\\<^sub>m\" [7]8) (* \u2014 Validity of lifted free modal formulas *)\n    where \"\\<lfloor>\\<phi>\\<rfloor>\\<^sub>f\\<^sub>m \\<equiv> \\<forall>w. \\<phi> w\"\n\n  text \\<open> Further logical constants can be defined as usual \\<close>\n\n  definition fmAnd :: \"\\<mu> \\<Rightarrow> \\<mu> \\<Rightarrow> \\<mu>\" (infixr \"\\<^bold>\\<and>\\<^sub>f\\<^sub>m\" 52) (* \u2014 Free modal conjunction *)\n    where \"\\<phi> \\<^bold>\\<and>\\<^sub>f\\<^sub>m \\<psi> \\<equiv> \\<^bold>\\<not>\\<^sub>f\\<^sub>m(\\<^bold>\\<not>\\<^sub>f\\<^sub>m\\<phi> \\<^bold>\\<or>\\<^sub>f\\<^sub>m \\<^bold>\\<not>\\<^sub>f\\<^sub>m\\<psi>)\"   \n  definition fmImp :: \"\\<mu> \\<Rightarrow> \\<mu> \\<Rightarrow> \\<mu>\" (infixr \"\\<^bold>\\<rightarrow>\\<^sub>f\\<^sub>m\" 49) (* \u2014 Free modal implication *)\n    where \"\\<phi> \\<^bold>\\<rightarrow>\\<^sub>f\\<^sub>m \\<psi> \\<equiv> \\<^bold>\\<not>\\<^sub>f\\<^sub>m\\<phi> \\<^bold>\\<or>\\<^sub>f\\<^sub>m \\<psi>\"\n  definition fmEquiv :: \"\\<mu> \\<Rightarrow> \\<mu> \\<Rightarrow> \\<mu>\" (infixr \"\\<^bold>\\<leftrightarrow>\\<^sub>f\\<^sub>m\" 50) (* \u2014 Free modal equivalence *)\n    where \"\\<phi> \\<^bold>\\<leftrightarrow>\\<^sub>f\\<^sub>m \\<psi> \\<equiv> \\<phi> \\<^bold>\\<rightarrow>\\<^sub>f\\<^sub>m \\<psi> \\<^bold>\\<and>\\<^sub>f\\<^sub>m \\<psi> \\<^bold>\\<rightarrow>\\<^sub>f\\<^sub>m \\<phi>\"  \n\n  definition fmDia :: \"\\<mu> \\<Rightarrow> \\<mu>\" (\"\\<^bold>\\<diamond>_\" [52]53) (* \u2014 Free modal possibility *)\n    where \"\\<^bold>\\<diamond>\\<phi> \\<equiv> \\<^bold>\\<not>\\<^sub>f\\<^sub>m(\\<^bold>\\<box>(\\<^bold>\\<not>\\<^sub>f\\<^sub>m\\<phi>))\"\n\n  definition fmExistsI :: \"(i \\<Rightarrow> \\<mu>) \\<Rightarrow> \\<mu>\" (\"\\<^bold>\\<exists>\\<^sup>i\\<^sub>f\\<^sub>m\") (* \u2014 Free modal existential quantification over individuals *)                                 \n    where \"\\<^bold>\\<exists>\\<^sup>i\\<^sub>f\\<^sub>m\\<Phi> \\<equiv> \\<^bold>\\<not>\\<^sub>f\\<^sub>m(\\<^bold>\\<forall>\\<^sup>i\\<^sub>f\\<^sub>m(\\<lambda>y. \\<^bold>\\<not>\\<^sub>f\\<^sub>m(\\<Phi> y)))\"\n  definition fmExistsIBinder :: \"(i \\<Rightarrow> \\<mu>) \\<Rightarrow> \\<mu>\" (binder \"\\<^bold>\\<exists>\\<^sup>i\\<^sub>f\\<^sub>m\" [8]9) (* \u2014 Binder notation *)                   \n    where \"\\<^bold>\\<exists>\\<^sup>i\\<^sub>f\\<^sub>mx. \\<phi> x \\<equiv> \\<^bold>\\<exists>\\<^sup>i\\<^sub>f\\<^sub>m\\<phi>\"\n  definition fmExistsP :: \"((i \\<Rightarrow> \\<mu>) \\<Rightarrow> \\<mu>) \\<Rightarrow> \\<mu>\" (\"\\<^bold>\\<exists>\\<^sup>p\\<^sub>f\\<^sub>m\") (* \u2014 Free modal existential quantification over predicates *)                                 \n    where \"\\<^bold>\\<exists>\\<^sup>p\\<^sub>f\\<^sub>m\\<Phi> \\<equiv> \\<^bold>\\<not>\\<^sub>f\\<^sub>m(\\<^bold>\\<forall>\\<^sup>p\\<^sub>f\\<^sub>m(\\<lambda>y. \\<^bold>\\<not>\\<^sub>f\\<^sub>m(\\<Phi> y)))\"\n  definition fmExistsPBinder :: \"((i \\<Rightarrow> \\<mu>) \\<Rightarrow> \\<mu>) \\<Rightarrow> \\<mu>\" (binder \"\\<^bold>\\<exists>\\<^sup>p\\<^sub>f\\<^sub>m\" [8]9) (* \u2014 Binder notation *)                   \n    where \"\\<^bold>\\<exists>\\<^sup>p\\<^sub>f\\<^sub>mx. \\<phi> x \\<equiv> \\<^bold>\\<exists>\\<^sup>p\\<^sub>f\\<^sub>m\\<phi>\"\n\n\n  (* Introducing \"Defs\" as the set of the above definitions; useful for convenient unfolding *)\n  named_theorems Defs declare fmIdentity_def[Defs] fmNot_def[Defs] fmOr_def[Defs] \n    fmForallI_def[Defs] fmForallIBinder_def[Defs] fmForallP_def[Defs] fmForallPBinder_def[Defs] \n    fmPredicateI_def[Defs] fmBox_def[Defs] fmAnd_def[Defs] fmImp_def[Defs] fmEquiv_def[Defs] \n    fmExistsI_def[Defs] fmExistsIBinder_def[Defs] fmExistsP_def[Defs] fmExistsPBinder_def[Defs] \n    fmDia_def[Defs] fmValid_def[Defs]\n\n\ntext \\<open> Some Tests \\<close>\n\n  lemma Kf: \"\\<lfloor>(\\<^bold>\\<box>((\\<^sup>f\\<^sup>m\\<phi> x) \\<^bold>\\<rightarrow>\\<^sub>f\\<^sub>m (\\<^sup>f\\<^sup>m\\<psi> x))) \\<^bold>\\<rightarrow>\\<^sub>f\\<^sub>m ((\\<^bold>\\<box>(\\<^sup>f\\<^sup>m\\<phi> x)) \\<^bold>\\<rightarrow>\\<^sub>f\\<^sub>m (\\<^bold>\\<box>(\\<^sup>f\\<^sup>m\\<psi> x)))\\<rfloor>\\<^sub>f\\<^sub>m\" unfolding Defs by blast (* \u2014 Verifying K principle *)\n  lemma NECf: \"\\<lfloor>\\<^sup>f\\<^sup>m\\<phi> x\\<rfloor>\\<^sub>f\\<^sub>m \\<Longrightarrow> \\<lfloor>\\<^bold>\\<box>(\\<^sup>f\\<^sup>m\\<phi> x)\\<rfloor>\\<^sub>f\\<^sub>m\" unfolding Defs by blast (* \u2014 Verifying necessitation rule *)\n\n\n  lemma \"\\<lfloor>(\\<^bold>\\<forall>\\<^sup>i\\<^sub>f\\<^sub>mx. \\<^sup>f\\<^sup>mP x) \\<^bold>\\<rightarrow>\\<^sub>f\\<^sub>m (\\<^sup>f\\<^sup>mP x)\\<rfloor>\\<^sub>f\\<^sub>m\" nitpick [user_axioms=true, show_all, format=2, card w=3] oops (* properly invalid *)\n  lemma \"\\<lfloor>((\\<^bold>\\<forall>\\<^sup>i\\<^sub>f\\<^sub>mx. (\\<^sup>f\\<^sup>mP x)) \\<^bold>\\<and>\\<^sub>f\\<^sub>m (E\\<^sup>i x)) \\<^bold>\\<rightarrow>\\<^sub>f\\<^sub>m (\\<^sup>f\\<^sup>mP x)\\<rfloor>\\<^sub>f\\<^sub>m\" unfolding Defs by blast (* properly valid *)\n\n  lemma \"\\<lfloor>(\\<^sup>f\\<^sup>mP x) \\<^bold>\\<rightarrow>\\<^sub>f\\<^sub>m (\\<^bold>\\<exists>\\<^sup>i\\<^sub>f\\<^sub>mx. \\<^sup>f\\<^sup>mP x)\\<rfloor>\\<^sub>f\\<^sub>m\" unfolding Defs by blast (* properly valid *)\n  lemma \"\\<lfloor>(\\<^sup>f\\<^sup>mP x) \\<^bold>\\<rightarrow>\\<^sub>f\\<^sub>m (E\\<^sup>i x)\\<rfloor>\\<^sub>f\\<^sub>m\" unfolding Defs by blast (* properly valid *)\n  lemma \"\\<lfloor>(\\<^sup>f\\<^sup>mP x) \\<^bold>\\<and>\\<^sub>f\\<^sub>m (\\<^bold>\\<exists>\\<^sup>i\\<^sub>f\\<^sub>mx. \\<^sup>f\\<^sup>mP x)\\<rfloor>\\<^sub>f\\<^sub>m\" nitpick [user_axioms=true, show_all, format=2] oops (* properly invalid *)\n\n  lemma \"\\<lfloor>\\<^bold>\\<box>(\\<^bold>\\<forall>\\<^sup>i\\<^sub>f\\<^sub>mx. E\\<^sup>i x)\\<rfloor>\\<^sub>f\\<^sub>m\" unfolding Defs by simp (* properly valid *)\n  lemma \"\\<lfloor>\\<^bold>\\<box>(E\\<^sup>i x)\\<rfloor>\\<^sub>f\\<^sub>m\" nitpick [user_axioms=true, show_all, format=2] oops (* properly invalid *)\n  lemma \"\\<lfloor>\\<^bold>\\<forall>\\<^sup>i\\<^sub>f\\<^sub>mx. \\<^bold>\\<box>(E\\<^sup>i x)\\<rfloor>\\<^sub>f\\<^sub>m\" unfolding Defs using nestedDomains by blast (* properly valid *)\n  lemma \"\\<lfloor>(\\<^bold>\\<box>(\\<^bold>\\<forall>\\<^sup>i\\<^sub>f\\<^sub>mx. \\<^sup>f\\<^sup>mP x)) \\<^bold>\\<leftrightarrow>\\<^sub>f\\<^sub>m (\\<^bold>\\<forall>\\<^sup>i\\<^sub>f\\<^sub>mx. \\<^bold>\\<box>(\\<^sup>f\\<^sup>mP x))\\<rfloor>\\<^sub>f\\<^sub>m\" unfolding Defs by blast (* properly valid *)\n\n  lemma \"\\<lfloor>(a \\<^bold>=\\<^sub>f\\<^sub>m b) \\<^bold>\\<rightarrow>\\<^sub>f\\<^sub>m (\\<^bold>\\<box>(a \\<^bold>=\\<^sub>f\\<^sub>m b))\\<rfloor>\\<^sub>f\\<^sub>m\" unfolding Defs by simp (* properly valid *)\n\n\ntext \\<open> Supervaluational Free Higher-Order Logic \\<close>\n\n  definition sIdentity :: \"i \\<Rightarrow> i \\<Rightarrow> \\<mu>\" (infixr \"\\<^bold>=\\<^sub>s\" 56) (* \u2014 Supervaluational free identity *)\n    where \"\\<phi> \\<^bold>=\\<^sub>s \\<psi> \\<equiv> \\<phi> \\<^bold>=\\<^sub>f\\<^sub>m \\<psi>\"\n\n  definition sNot :: \"\\<mu> \\<Rightarrow> \\<mu>\" (\"\\<^bold>\\<not>\\<^sub>s_\" [52]53) (* \u2014 Supervaluational free negation *)\n    where \"\\<^bold>\\<not>\\<^sub>s\\<phi> \\<equiv> \\<^bold>\\<not>\\<^sub>f\\<^sub>m\\<phi>\" \n  definition sOr :: \"\\<mu> \\<Rightarrow> \\<mu> \\<Rightarrow> \\<mu>\" (infixr \"\\<^bold>\\<or>\\<^sub>s\" 51) (* \u2014 Supervaluational free disjunction *)\n    where \"\\<phi> \\<^bold>\\<or>\\<^sub>s \\<psi> \\<equiv> \\<phi> \\<^bold>\\<or>\\<^sub>f\\<^sub>m \\<psi>\"\n\n  definition sForallI :: \"(i \\<Rightarrow> \\<mu>) \\<Rightarrow> \\<mu>\" (\"\\<^bold>\\<forall>\\<^sup>i\\<^sub>s\") (* \u2014 Supervaluational free universal quantification over individuals *)\n    where \"\\<^bold>\\<forall>\\<^sup>i\\<^sub>s\\<Phi> \\<equiv> \\<^bold>\\<forall>\\<^sup>i\\<^sub>f\\<^sub>mx. \\<Phi> x\"\n  definition sForallIBinder:: \"(i \\<Rightarrow> \\<mu>) \\<Rightarrow> \\<mu>\" (binder \"\\<^bold>\\<forall>\\<^sup>i\\<^sub>s\" [8]9) (* \u2014 Binder notation *)\n    where \"\\<^bold>\\<forall>\\<^sup>i\\<^sub>sx. \\<phi> x \\<equiv> \\<^bold>\\<forall>\\<^sup>i\\<^sub>s\\<phi>\"   \n  definition sForallP :: \"((i \\<Rightarrow> \\<mu>) \\<Rightarrow> \\<mu>) \\<Rightarrow> \\<mu>\" (\"\\<^bold>\\<forall>\\<^sup>p\\<^sub>s\") (* \u2014 Supervaluational free universal quantification over predicates *)\n    where \"\\<^bold>\\<forall>\\<^sup>p\\<^sub>s\\<Phi> \\<equiv> \\<^bold>\\<forall>\\<^sup>p\\<^sub>f\\<^sub>mx. \\<Phi> x\"\n  definition sForallPBinder:: \"((i \\<Rightarrow> \\<mu>) \\<Rightarrow> \\<mu>) \\<Rightarrow> \\<mu>\" (binder \"\\<^bold>\\<forall>\\<^sup>p\\<^sub>s\" [8]9) (* \u2014 Binder notation *)\n    where \"\\<^bold>\\<forall>\\<^sup>p\\<^sub>sx. \\<phi> x \\<equiv> \\<^bold>\\<forall>\\<^sup>p\\<^sub>s\\<phi>\"\n\n  definition sPredicateI :: \"(i \\<Rightarrow> \\<mu>) \\<Rightarrow> i \\<Rightarrow> \\<mu>\" (\"\\<^sup>s\") (* \u2014 Supervaluational free predicate *)\n    where \"\\<^sup>sP x \\<equiv> (E\\<^sup>i x \\<^bold>\\<rightarrow>\\<^sub>f\\<^sub>m (\\<^sup>f\\<^sup>mP x)) \\<^bold>\\<and>\\<^sub>f\\<^sub>m (\\<^bold>\\<not>\\<^sub>f\\<^sub>m(E\\<^sup>i x) \\<^bold>\\<rightarrow>\\<^sub>f\\<^sub>m (\\<^bold>\\<box>(\\<^bold>\\<diamond>(\\<^sup>f\\<^sup>mP x))))\"\n\n  text \\<open> Further logical constants can be defined as usual \\<close>\n\n  definition sAnd :: \"\\<mu> \\<Rightarrow> \\<mu> \\<Rightarrow> \\<mu>\" (infixr \"\\<^bold>\\<and>\\<^sub>s\" 52) (* \u2014 Supervaluational free conjunction *)\n    where \"\\<phi> \\<^bold>\\<and>\\<^sub>s \\<psi> \\<equiv> \\<^bold>\\<not>\\<^sub>s(\\<^bold>\\<not>\\<^sub>s\\<phi> \\<^bold>\\<or>\\<^sub>s \\<^bold>\\<not>\\<^sub>s\\<psi>)\"   \n  definition sImp :: \"\\<mu> \\<Rightarrow> \\<mu> \\<Rightarrow> \\<mu>\" (infixr \"\\<^bold>\\<rightarrow>\\<^sub>s\" 49) (* \u2014 Supervaluational free implication *)\n    where \"\\<phi> \\<^bold>\\<rightarrow>\\<^sub>s \\<psi> \\<equiv> \\<^bold>\\<not>\\<^sub>s\\<phi> \\<^bold>\\<or>\\<^sub>s \\<psi>\"\n  definition sEquiv :: \"\\<mu> \\<Rightarrow> \\<mu> \\<Rightarrow> \\<mu>\" (infixr \"\\<^bold>\\<leftrightarrow>\\<^sub>s\" 50) (* \u2014 Supervaluational free equivalence *)\n    where \"\\<phi> \\<^bold>\\<leftrightarrow>\\<^sub>s \\<psi> \\<equiv> \\<phi> \\<^bold>\\<rightarrow>\\<^sub>s \\<psi> \\<^bold>\\<and>\\<^sub>s \\<psi> \\<^bold>\\<rightarrow>\\<^sub>s \\<phi>\"  \n\n  definition sExistsI :: \"(i \\<Rightarrow> \\<mu>) \\<Rightarrow> \\<mu>\" (\"\\<^bold>\\<exists>\\<^sup>i\\<^sub>s\") (* \u2014 Supervaluational free existential quantification over individuals *)                                   \n    where \"\\<^bold>\\<exists>\\<^sup>i\\<^sub>s\\<Phi> \\<equiv> \\<^bold>\\<not>\\<^sub>s(\\<^bold>\\<forall>\\<^sup>i\\<^sub>s(\\<lambda>y. \\<^bold>\\<not>\\<^sub>s(\\<Phi> y)))\"\n  definition sExistsIBinder :: \"(i \\<Rightarrow> \\<mu>) \\<Rightarrow> \\<mu>\" (binder \"\\<^bold>\\<exists>\\<^sup>i\\<^sub>s\" [8]9) (* \u2014 Binder notation *)                   \n    where \"\\<^bold>\\<exists>\\<^sup>i\\<^sub>sx. \\<phi> x \\<equiv> \\<^bold>\\<exists>\\<^sup>i\\<^sub>s\\<phi>\"\n  definition sExistsP :: \"((i \\<Rightarrow> \\<mu>) \\<Rightarrow> \\<mu>) \\<Rightarrow> \\<mu>\" (\"\\<^bold>\\<exists>\\<^sup>p\\<^sub>s\") (* \u2014 Supervaluational free existential quantification over predicates *)                                   \n    where \"\\<^bold>\\<exists>\\<^sup>p\\<^sub>s\\<Phi> \\<equiv> \\<^bold>\\<not>\\<^sub>s(\\<^bold>\\<forall>\\<^sup>p\\<^sub>s(\\<lambda>y. \\<^bold>\\<not>\\<^sub>s(\\<Phi> y)))\"\n  definition sExistsPBinder :: \"((i \\<Rightarrow> \\<mu>) \\<Rightarrow> \\<mu>) \\<Rightarrow> \\<mu>\" (binder \"\\<^bold>\\<exists>\\<^sup>p\\<^sub>s\" [8]9) (* \u2014 Binder notation *)                   \n    where \"\\<^bold>\\<exists>\\<^sup>p\\<^sub>sx. \\<phi> x \\<equiv> \\<^bold>\\<exists>\\<^sup>p\\<^sub>s\\<phi>\"\n\n  definition sValid :: \"\\<mu> \\<Rightarrow> bool\" (\"\\<lfloor>_\\<rfloor>\\<^sub>s\" [7]8) (* \u2014 Validity of supervaluational free formulas *)\n    where \"\\<lfloor>\\<phi>\\<rfloor>\\<^sub>s \\<equiv> \\<forall>w. \\<phi> w\"\n\n\n  declare sIdentity_def[Defs] sNot_def[Defs] sOr_def[Defs] sForallI_def[Defs] \n    sForallIBinder_def[Defs] sForallP_def[Defs] sForallPBinder_def[Defs] sPredicateI_def[Defs] \n    sAnd_def[Defs] sImp_def[Defs] sEquiv_def[Defs] sExistsI_def[Defs] sExistsIBinder_def[Defs] \n    sExistsP_def[Defs] sExistsPBinder_def[Defs] sValid_def[Defs]\n\n\ntext \\<open> Some Tests \\<close>\n\n  lemma \"\\<lfloor>(\\<^bold>\\<forall>\\<^sup>i\\<^sub>sx. \\<^sup>sP x) \\<^bold>\\<rightarrow>\\<^sub>s (\\<^sup>sP x)\\<rfloor>\\<^sub>s\" nitpick [user_axioms=true, show_all, format=2] oops (* properly invalid *)\n  lemma \"\\<lfloor>((\\<^bold>\\<forall>\\<^sup>i\\<^sub>sx. (\\<^sup>sP x)) \\<^bold>\\<and>\\<^sub>s (E\\<^sup>i x)) \\<^bold>\\<rightarrow>\\<^sub>s (\\<^sup>sP x)\\<rfloor>\\<^sub>s\" unfolding Defs by blast (* properly valid *)\n\n  lemma \"\\<lfloor>(\\<^sup>sP x) \\<^bold>\\<rightarrow>\\<^sub>s (\\<^bold>\\<exists>\\<^sup>i\\<^sub>sx. \\<^sup>sP x)\\<rfloor>\\<^sub>s\" nitpick [user_axioms=true, show_all, format=2] oops (* properly invalid *)\n  lemma \"\\<lfloor>((\\<^sup>sP x) \\<^bold>\\<and>\\<^sub>s (E\\<^sup>i x)) \\<^bold>\\<rightarrow>\\<^sub>s (\\<^bold>\\<exists>\\<^sup>i\\<^sub>sx. \\<^sup>sP x)\\<rfloor>\\<^sub>s\" unfolding Defs by blast (* properly valid *)\n  lemma \"\\<lfloor>(\\<^sup>sP x) \\<^bold>\\<rightarrow>\\<^sub>s (E\\<^sup>i x)\\<rfloor>\\<^sub>s\" nitpick [user_axioms=true, show_all, format=2] oops (* properly invalid *)\n  lemma \"\\<lfloor>(\\<^sup>sP x) \\<^bold>\\<and>\\<^sub>s (\\<^bold>\\<exists>\\<^sup>i\\<^sub>sx. \\<^sup>sP x)\\<rfloor>\\<^sub>s\" nitpick [user_axioms=true, show_all, format=2] oops (* properly invalid *)\n\n  lemma \"\\<lfloor>(\\<^sup>sP x) \\<^bold>\\<or>\\<^sub>s (\\<^bold>\\<not>\\<^sub>s(\\<^sup>sP x))\\<rfloor>\\<^sub>s\" unfolding Defs by blast (* properly valid *)\n  lemma \"\\<lfloor>(\\<^sup>sP x) \\<^bold>\\<and>\\<^sub>s (\\<^bold>\\<not>\\<^sub>s(\\<^sup>sP x))\\<rfloor>\\<^sub>s\" nitpick [user_axioms=true, show_all, format=2] oops (* properly invalid *)\n  lemma \"\\<lfloor>\\<^bold>\\<not>\\<^sub>s((\\<^sup>sP x) \\<^bold>\\<and>\\<^sub>s (\\<^bold>\\<not>\\<^sub>s(\\<^sup>sP x)))\\<rfloor>\\<^sub>s\" unfolding Defs by blast (* properly valid *)\n\n  lemma \"\\<lfloor>\\<^bold>\\<box>(\\<^bold>\\<forall>\\<^sup>i\\<^sub>sx. E\\<^sup>i x)\\<rfloor>\\<^sub>s\" unfolding Defs by simp (* properly valid *)\n  lemma \"\\<lfloor>\\<^bold>\\<box>(E\\<^sup>i x)\\<rfloor>\\<^sub>s\" nitpick [user_axioms=true, show_all, format=2] oops (* properly invalid *)\n  lemma \"\\<lfloor>\\<^bold>\\<forall>\\<^sup>i\\<^sub>sx. \\<^bold>\\<box>(E\\<^sup>i x)\\<rfloor>\\<^sub>s\" unfolding Defs by (simp add: nestedDomains) (* properly valid *)\n  lemma \"\\<lfloor>(\\<^bold>\\<box>(\\<^bold>\\<forall>\\<^sup>i\\<^sub>sx. \\<^sup>sP x)) \\<^bold>\\<leftrightarrow>\\<^sub>s (\\<^bold>\\<forall>\\<^sup>i\\<^sub>sx. \\<^bold>\\<box>(\\<^sup>sP x))\\<rfloor>\\<^sub>s\" unfolding Defs by blast (* properly valid *)\n\n  lemma \"\\<lfloor>(a \\<^bold>=\\<^sub>s b) \\<^bold>\\<rightarrow>\\<^sub>s (\\<^bold>\\<box>(a \\<^bold>=\\<^sub>s b))\\<rfloor>\\<^sub>s\" unfolding Defs by simp (* properly valid *)\n\n\n  consts sIndividual1 :: \"i\" (\"i\\<^sub>1\")\n  axiomatization where sUndefIndividual1Axiom: \"\\<exists>w. \\<not>(E\\<^sup>i i\\<^sub>1 w)\"\n\n  lemma \"\\<lfloor>x \\<^bold>=\\<^sub>s x\\<rfloor>\\<^sub>s\" unfolding Defs by simp (* properly valid *)\n  lemma \"\\<lfloor>i\\<^sub>1 \\<^bold>=\\<^sub>s i\\<^sub>1\\<rfloor>\\<^sub>s\" unfolding Defs by simp (* properly valid *)\n\n  lemma \"\\<lfloor>\\<^sup>sP i\\<^sub>1\\<rfloor>\\<^sub>s\" nitpick [user_axioms=true, show_all, format=2] nitpick [satisfy, user_axioms=true, show_all, format=2, card w=2] oops (* should be truth-valueless *)\n  lemma \"\\<lfloor>\\<^bold>\\<not>\\<^sub>s(\\<^sup>sP i\\<^sub>1)\\<rfloor>\\<^sub>s\" nitpick [user_axioms=true, show_all, format=2] nitpick [satisfy, user_axioms=true, show_all, format=2] oops (* should be truth-valueless *)\n  lemma \"(\\<lfloor>(\\<^sup>sP i\\<^sub>1) \\<^bold>\\<or>\\<^sub>s (\\<^bold>\\<not>\\<^sub>s(\\<^sup>sP i\\<^sub>1))\\<rfloor>\\<^sub>s)\" unfolding Defs nitpick [satisfy, user_axioms=true, show_all, format=2] by blast (* properly valid *)\n  lemma \"(\\<lfloor>(\\<^sup>sP i\\<^sub>1) \\<^bold>\\<or>\\<^sub>s (\\<^bold>\\<not>\\<^sub>s(\\<^sup>sP i\\<^sub>1))\\<rfloor>\\<^sub>s)\" unfolding Defs nitpick [satisfy, user_axioms=true, show_all, format=2, card i=1, card w=2] by blast (* properly valid *)\n  lemma \"\\<lfloor>\\<^bold>\\<exists>\\<^sup>p\\<^sub>sP. \\<^sup>sP i\\<^sub>1\\<rfloor>\\<^sub>s\" nitpick [user_axioms=true, show_all, format=2] oops (* properly invalid *)\n  lemma \"\\<lfloor>\\<^bold>\\<not>\\<^sub>s(\\<^bold>\\<exists>\\<^sup>p\\<^sub>sP. \\<^sup>sP i\\<^sub>1)\\<rfloor>\\<^sub>s\" nitpick [user_axioms=true, show_all, format=2] nitpick [satisfy, user_axioms=true, show_all, format=2, card=2] oops (* properly invalid *)\n\n\n  lemma test_True: \"True\" by simp\n  lemma test_False: \"False\" nitpick [satisfy, user_axioms=true] oops\n", "meta": {"author": "stilleben", "repo": "Free-Higher-Order-Logic", "sha": "a9c41094db3dccfc6bcdc5f93298936119ff2d90", "save_path": "github-repos/isabelle/stilleben-Free-Higher-Order-Logic", "path": "github-repos/isabelle/stilleben-Free-Higher-Order-Logic/Free-Higher-Order-Logic-a9c41094db3dccfc6bcdc5f93298936119ff2d90/encodings/SFHOL.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9032942093072239, "lm_q2_score": 0.7853085859124002, "lm_q1q2_score": 0.7093646981739157}}
{"text": "text\\<open> 29 October 2021: Exercise for Homework Assignment 08 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 HW08\n  imports Main\nbegin\n\ntext\\<open> 'blast' is invoked three times, once in the proof of each of\n      lemmas K1, L1, and M1 below \\<close>\n\n(* lemma K1 is the same in Exercise 2.3.9 (k), page 161, in [LCS] *)\nlemma K1 : \"\\<forall> x. (P x \\<and> Q x) \\<Longrightarrow> (\\<forall> x. P x) \\<and> (\\<forall> x. Q x)\" \n  apply (rule conjI)\n   apply (rule allI)\n   apply (erule allE)\n   apply (erule conjE)\n   apply assumption\n  apply (rule allI)\n  apply (erule allE)\n  apply (erule conjE)\n  apply assumption\n  done \n\n(* lemma L1 is the same in Exercise 2.3.9 (l), page 161, in [LCS] *)\nlemma L1 : \"(\\<forall> x. P x) \\<or> (\\<forall> x. Q x) \\<Longrightarrow> \\<forall> x. (P x \\<or> Q x)\" \n  apply (rule allI)\n  apply (erule disjE)\n   apply (rule disjI1)\n   apply (erule allE)\n   apply assumption\n  apply (rule disjI2)\n  apply (erule allE)\n  apply assumption\n  done\n\n(* lemma M1 is the same in Exercise 2.3.9 (m), page 161, in [LCS] *)\nlemma M1 : \"\\<exists> x. (P x \\<and> Q x) \\<Longrightarrow> (\\<exists> x. P x) \\<and> (\\<exists> x. Q x)\" \n  apply (erule exE)\n  apply (rule conjI)\n   apply (rule exI)\n   apply (erule conjE)\n   apply assumption\n  apply (erule conjE)\n  apply (rule exI)\n  apply assumption\n  done\n\nend", "meta": {"author": "dzhou1337", "repo": "CS511-Fall2021", "sha": "d4b5ef9797a9c9fe10867769fa1b69fbb1ca05d5", "save_path": "github-repos/isabelle/dzhou1337-CS511-Fall2021", "path": "github-repos/isabelle/dzhou1337-CS511-Fall2021/CS511-Fall2021-d4b5ef9797a9c9fe10867769fa1b69fbb1ca05d5/HW8/HW08.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118026095992, "lm_q2_score": 0.857768108626046, "lm_q1q2_score": 0.709127019303265}}
{"text": "(*\n  File: Int.thy\n  Author: Bohua Zhan\n\n  Construction of integers (as pairs of natural numbers, under the equivalence\n  relation (a,b) ~ (c,d) iff a + d = b + c.\n*)\n\ntheory Int\n  imports Nat Ring EquivRel\nbegin\n\nsection \\<open>Integers as a quotient set\\<close>\n\ndefinition int_rel_space :: i where [rewrite]:\n  \"int_rel_space = nat\\<times>nat\"\n\ndefinition int_rel :: i where [rewrite]:\n  \"int_rel = Equiv(int_rel_space, \\<lambda>p q. let \\<langle>a,b\\<rangle> = p; \\<langle>c,d\\<rangle> = q in a +\\<^sub>\\<nat> d = b +\\<^sub>\\<nat> c)\"\nnotation int_rel (\"\\<R>\")\n\nlemma int_rel_spaceI [typing]: \"x \\<in> nat \\<Longrightarrow> y \\<in> nat \\<Longrightarrow> \\<langle>x,y\\<rangle> \\<in>. \\<R>\" by auto2\nlemma int_rel_spaceD [forward]: \"p \\<in>. \\<R> \\<Longrightarrow> p = \\<langle>fst(p),snd(p)\\<rangle> \\<and> fst(p) \\<in> nat \\<and> snd(p) \\<in> nat\" by auto2\nsetup {* del_prfstep_thm @{thm int_rel_space_def} *}\n\nlemma int_rel_trans [backward2]:\n  \"a1 \\<in>. \\<nat> \\<Longrightarrow> a2 \\<in>. \\<nat> \\<Longrightarrow> b1 \\<in>. \\<nat> \\<Longrightarrow> b2 \\<in>. \\<nat> \\<Longrightarrow> c1 \\<in>. \\<nat> \\<Longrightarrow> c2 \\<in>. \\<nat> \\<Longrightarrow>\n   a1 +\\<^sub>\\<nat> b2 = a2 +\\<^sub>\\<nat> b1 \\<Longrightarrow> b1 +\\<^sub>\\<nat> c2 = b2 +\\<^sub>\\<nat> c1 \\<Longrightarrow> a1 +\\<^sub>\\<nat> c2 = a2 +\\<^sub>\\<nat> c1\"\n@proof\n  @have \"(a1 +\\<^sub>\\<nat> c2) +\\<^sub>\\<nat> b2 = (a1 +\\<^sub>\\<nat> b2) +\\<^sub>\\<nat> c2\"\n  @have \"(a2 +\\<^sub>\\<nat> b1) +\\<^sub>\\<nat> c2 = a2 +\\<^sub>\\<nat> (b1 +\\<^sub>\\<nat> c2)\"\n  @have \"a2 +\\<^sub>\\<nat> (b2 +\\<^sub>\\<nat> c1) = (a2 +\\<^sub>\\<nat> c1) +\\<^sub>\\<nat> b2\"\n@qed\n\nlemma int_rel_is_rel [typing]: \"\\<R> \\<in> equiv_space(int_rel_space)\" by auto2\nsetup {* del_prfstep_thm @{thm int_rel_trans} *}\n\nlemma int_rel_eval:\n  \"x \\<in>. \\<R> \\<Longrightarrow> y \\<in>. \\<R> \\<Longrightarrow> x \\<sim>\\<^sub>\\<R> y \\<longleftrightarrow> fst(x) +\\<^sub>\\<nat> snd(y) = snd(x) +\\<^sub>\\<nat> fst(y)\" by auto2\nsetup {* add_rewrite_rule_cond @{thm int_rel_eval} [with_cond \"?x \\<noteq> ?y\"] *}\nsetup {* del_prfstep_thm @{thm int_rel_def} *}\n\ndefinition int :: i where int_def [rewrite_bidir]:\n  \"int = carrier(\\<R>) // \\<R>\"\n\nabbreviation Int :: \"i \\<Rightarrow> i\" where \"Int(p) \\<equiv> equiv_class(\\<R>,p)\"\n\nsection \\<open>Integers as a ring\\<close>\n  \ndefinition int_add_raw :: \"i \\<Rightarrow> i \\<Rightarrow> i\" where [rewrite]:\n  \"int_add_raw(p,q) = \\<langle>fst(p)+\\<^sub>\\<nat>fst(q),snd(p)+\\<^sub>\\<nat>snd(q)\\<rangle>\"\nsetup {* register_wellform_data (\"int_add_raw(p,q)\", [\"p \\<in>. \\<R>\", \"q \\<in>. \\<R>\"]) *}\n\nlemma int_add_raw_eval [rewrite]: \"int_add_raw(\\<langle>a,b\\<rangle>,\\<langle>c,d\\<rangle>) = \\<langle>a+\\<^sub>\\<nat>c, b+\\<^sub>\\<nat>d\\<rangle>\" by auto2\nsetup {* del_prfstep_thm @{thm int_add_raw_def} *}\n\ndefinition int_mult_raw :: \"i \\<Rightarrow> i \\<Rightarrow> i\" where [rewrite]:\n  \"int_mult_raw(p,q) = \\<langle>fst(p)*\\<^sub>\\<nat>fst(q) +\\<^sub>\\<nat> snd(p)*\\<^sub>\\<nat>snd(q), fst(p)*\\<^sub>\\<nat>snd(q) +\\<^sub>\\<nat> snd(p)*\\<^sub>\\<nat>fst(q)\\<rangle>\"\nsetup {* register_wellform_data (\"int_mult_raw(p,q)\", [\"p \\<in>. \\<R>\", \"q \\<in>. \\<R>\"]) *}\n\nlemma int_mult_raw_eval [rewrite]: \"int_mult_raw(\\<langle>a,b\\<rangle>,\\<langle>c,d\\<rangle>) = \\<langle>a*\\<^sub>\\<nat>c +\\<^sub>\\<nat> b*\\<^sub>\\<nat>d, a*\\<^sub>\\<nat>d +\\<^sub>\\<nat> b*\\<^sub>\\<nat>c\\<rangle>\" by auto2\nsetup {* del_prfstep_thm @{thm int_mult_raw_def} *}\n\ndefinition nonneg_int_raw :: \"i \\<Rightarrow> o\" where [rewrite]:\n  \"nonneg_int_raw(p) \\<longleftrightarrow> fst(p) \\<ge>\\<^sub>\\<nat> snd(p)\"\n\ndefinition nonneg_int :: \"i \\<Rightarrow> o\" where [rewrite]:\n  \"nonneg_int(x) \\<longleftrightarrow> nonneg_int_raw(rep(\\<R>,x))\"\n\ndefinition nonneg_ints :: i where [rewrite]:\n  \"nonneg_ints = {x\\<in>int. nonneg_int(x)}\"\n\ndefinition int_ring :: i where [rewrite]:\n  \"int_ring = Ring(int, Int(\\<langle>0,0\\<rangle>), \\<lambda>x y. Int(int_add_raw(rep(\\<R>,x), rep(\\<R>,y))),\n                        Int(\\<langle>1,0\\<rangle>), \\<lambda>x y. Int(int_mult_raw(rep(\\<R>,x), rep(\\<R>,y))))\"\n\nlemma int_ring_is_ring_raw [forward]: \"ring_form(int_ring)\" by auto2\n\ndefinition int_ord_ring :: i  (\"\\<int>\") where [rewrite]:\n  \"int_ord_ring = ord_ring_from_nonneg(int_ring, nonneg_ints)\"\n\nlemma int_is_ring_raw [forward]: \"is_ring_raw(\\<int>)\" by auto2\nlemma int_carrier [rewrite_bidir]: \"carrier(\\<int>) = int\" by auto2\nlemma int_evals [rewrite]:\n  \"\\<zero>\\<^sub>\\<int> = Int(\\<langle>0,0\\<rangle>)\"\n  \"\\<one>\\<^sub>\\<int> = Int(\\<langle>1,0\\<rangle>)\"\n  \"x \\<in>. \\<int> \\<Longrightarrow> y \\<in>. \\<int> \\<Longrightarrow> x +\\<^sub>\\<int> y = Int(int_add_raw(rep(\\<R>,x), rep(\\<R>,y)))\"\n  \"x \\<in>. \\<int> \\<Longrightarrow> y \\<in>. \\<int> \\<Longrightarrow> x *\\<^sub>\\<int> y = Int(int_mult_raw(rep(\\<R>,x), rep(\\<R>,y)))\" by auto2+\n    \nlemma int_is_ord_ring_prep [forward]:\n  \"is_comm_ring(\\<int>) \\<Longrightarrow> nonneg_compat(\\<int>,nonneg_ints) \\<Longrightarrow> is_ord_ring(\\<int>)\" by auto2\n\nsetup {* fold del_prfstep_thm [@{thm int_ring_def}, @{thm int_ord_ring_def}] *}\n\nlemma int_choose_rep: \"x \\<in>. \\<int> \\<Longrightarrow> x = Int(rep(\\<R>,x))\" by auto2\nsetup {* add_rewrite_rule_cond @{thm int_choose_rep} [with_filt (size1_filter \"x\")] *}\n\nsection \\<open>Addition on integers\\<close>\n\nlemma int_add_eval [rewrite]:\n  \"x \\<in>. \\<R> \\<Longrightarrow> y \\<in>. \\<R> \\<Longrightarrow> Int(x) +\\<^sub>\\<int> Int(y) = Int(int_add_raw(x,y))\"\n@proof\n  @have \"compat_meta_bin1(\\<R>, int_add_raw)\" @with\n    @have (@rule) \"\\<forall>a b c d a' b'. \\<langle>c,d\\<rangle> \\<in>. \\<R> \\<longrightarrow> \\<langle>a',b'\\<rangle> \\<sim>\\<^sub>\\<R> \\<langle>a,b\\<rangle> \\<longrightarrow>\n                   int_add_raw(\\<langle>a',b'\\<rangle>,\\<langle>c,d\\<rangle>) \\<sim>\\<^sub>\\<R> int_add_raw(\\<langle>a,b\\<rangle>,\\<langle>c,d\\<rangle>)\" @with\n      @have \"(a' +\\<^sub>\\<nat> c) +\\<^sub>\\<nat> (b +\\<^sub>\\<nat> d) = (a' +\\<^sub>\\<nat> b) +\\<^sub>\\<nat> (c +\\<^sub>\\<nat> d)\"\n      @have \"(b' +\\<^sub>\\<nat> d) +\\<^sub>\\<nat> (a +\\<^sub>\\<nat> c) = (b' +\\<^sub>\\<nat> a) +\\<^sub>\\<nat> (c +\\<^sub>\\<nat> d)\"\n    @end\n  @end\n  @have \"compat_meta_bin2(\\<R>, int_add_raw)\" @with\n    @have (@rule) \"\\<forall>a b c d c' d'. \\<langle>a,b\\<rangle> \\<in>. \\<R> \\<longrightarrow> \\<langle>c',d'\\<rangle> \\<sim>\\<^sub>\\<R> \\<langle>c,d\\<rangle> \\<longrightarrow>\n                   int_add_raw(\\<langle>a,b\\<rangle>,\\<langle>c',d'\\<rangle>) \\<sim>\\<^sub>\\<R> int_add_raw(\\<langle>a,b\\<rangle>,\\<langle>c,d\\<rangle>)\" @with\n      @have \"(a +\\<^sub>\\<nat> c') +\\<^sub>\\<nat> (b +\\<^sub>\\<nat> d) = (a +\\<^sub>\\<nat> b) +\\<^sub>\\<nat> (c' +\\<^sub>\\<nat> d)\"\n      @have \"(b +\\<^sub>\\<nat> d') +\\<^sub>\\<nat> (a +\\<^sub>\\<nat> c) = (a +\\<^sub>\\<nat> b) +\\<^sub>\\<nat> (d' +\\<^sub>\\<nat> c)\"\n    @end\n  @end\n  @have \"compat_meta_bin(\\<R>, int_add_raw)\"\n@qed\nsetup {* del_prfstep_thm @{thm int_evals(3)} *}\n\nlemma int_add_comm [forward]: \"is_plus_comm(\\<int>)\" by auto2\nlemma int_add_assoc [forward]: \"is_plus_assoc(\\<int>)\" by auto2\n\nsection \\<open>Multiplication on integers\\<close>\n\nlemma int_mult_eval [rewrite]:\n  \"x \\<in>. \\<R> \\<Longrightarrow> y \\<in>. \\<R> \\<Longrightarrow> Int(x) *\\<^sub>\\<int> Int(y) = Int(int_mult_raw(x,y))\"\n@proof\n  @have \"compat_meta_bin1(\\<R>, int_mult_raw)\" @with\n    @have (@rule) \"\\<forall>a b c d a' b'. \\<langle>c,d\\<rangle> \\<in>. \\<R> \\<longrightarrow> \\<langle>a',b'\\<rangle> \\<sim>\\<^sub>\\<R> \\<langle>a,b\\<rangle> \\<longrightarrow>\n                   int_mult_raw(\\<langle>a',b'\\<rangle>,\\<langle>c,d\\<rangle>) \\<sim>\\<^sub>\\<R> int_mult_raw(\\<langle>a,b\\<rangle>,\\<langle>c,d\\<rangle>)\" @with\n      @have \"(a'*\\<^sub>\\<nat>c +\\<^sub>\\<nat> b'*\\<^sub>\\<nat>d) +\\<^sub>\\<nat> (a*\\<^sub>\\<nat>d +\\<^sub>\\<nat> b*\\<^sub>\\<nat>c) = (a'+\\<^sub>\\<nat>b) *\\<^sub>\\<nat> c +\\<^sub>\\<nat> (b'+\\<^sub>\\<nat>a) *\\<^sub>\\<nat> d\"\n      @have \"(a'*\\<^sub>\\<nat>d +\\<^sub>\\<nat> b'*\\<^sub>\\<nat>c) +\\<^sub>\\<nat> (a*\\<^sub>\\<nat>c +\\<^sub>\\<nat> b*\\<^sub>\\<nat>d) = (b'+\\<^sub>\\<nat>a) *\\<^sub>\\<nat> c +\\<^sub>\\<nat> (a'+\\<^sub>\\<nat>b) *\\<^sub>\\<nat> d\"\n    @end\n  @end\n  @have \"compat_meta_bin2(\\<R>, int_mult_raw)\" @with\n    @have (@rule) \"\\<forall>a b c d c' d'. \\<langle>a,b\\<rangle> \\<in>. \\<R> \\<longrightarrow> \\<langle>c',d'\\<rangle> \\<sim>\\<^sub>\\<R> \\<langle>c,d\\<rangle> \\<longrightarrow>\n                   int_mult_raw(\\<langle>a,b\\<rangle>,\\<langle>c',d'\\<rangle>) \\<sim>\\<^sub>\\<R> int_mult_raw(\\<langle>a,b\\<rangle>,\\<langle>c,d\\<rangle>)\" @with\n      @have \"(a*\\<^sub>\\<nat>c' +\\<^sub>\\<nat> b*\\<^sub>\\<nat>d') +\\<^sub>\\<nat> (a*\\<^sub>\\<nat>d +\\<^sub>\\<nat> b*\\<^sub>\\<nat>c) = (c'+\\<^sub>\\<nat>d) *\\<^sub>\\<nat> a +\\<^sub>\\<nat> (d'+\\<^sub>\\<nat>c) *\\<^sub>\\<nat> b\"\n      @have \"(a*\\<^sub>\\<nat>d' +\\<^sub>\\<nat> b*\\<^sub>\\<nat>c') +\\<^sub>\\<nat> (a*\\<^sub>\\<nat>c +\\<^sub>\\<nat> b*\\<^sub>\\<nat>d) = (d'+\\<^sub>\\<nat>c) *\\<^sub>\\<nat> a +\\<^sub>\\<nat> (c'+\\<^sub>\\<nat>d) *\\<^sub>\\<nat> b\"\n    @end\n  @end  \n  @have \"compat_meta_bin(\\<R>, int_mult_raw)\"\n@qed\nsetup {* del_prfstep_thm @{thm int_evals(4)} *}\n\nlemma int_mult_comm [forward]: \"is_times_comm(\\<int>)\" by auto2\nlemma int_mult_assoc [forward]: \"is_times_assoc(\\<int>)\" by auto2\nlemma int_distrib_l [forward]: \"is_left_distrib(\\<int>)\" by auto2\n\nsection \\<open>0 and 1\\<close>\n\nlemma int_is_add_id [forward]: \"is_add_id(\\<int>)\" by auto2\nlemma int_is_mult_id [forward]: \"is_mult_id(\\<int>)\" by auto2\nlemma int_zero_neq_one [resolve]: \"\\<zero>\\<^sub>\\<int> \\<noteq> \\<one>\\<^sub>\\<int>\" by auto2\n\nsection \\<open>Negation and subtraction on integers\\<close>\n  \ndefinition int_neg_raw :: \"i \\<Rightarrow> i\" where [rewrite]:\n  \"int_neg_raw(p) = \\<langle>snd(p), fst(p)\\<rangle>\"\n\ndefinition int_neg :: \"i \\<Rightarrow> i\" where [rewrite]:\n  \"int_neg(x) = Int(int_neg_raw(rep(\\<R>,x)))\"\n\nlemma int_neg_typing [typing]: \"x \\<in>. \\<int> \\<Longrightarrow> int_neg(x) \\<in>. \\<int>\" by auto2\nlemma int_has_add_inverse [forward]: \"has_add_inverse(\\<int>)\"\n@proof @have \"\\<forall>x\\<in>.\\<int>. x +\\<^sub>\\<int> int_neg(x) = \\<zero>\\<^sub>\\<int>\" @qed\n  \nlemma int_is_comm_ring [forward]: \"is_comm_ring(\\<int>)\" by auto2\n\nsection \\<open>Nonnegative integers\\<close>\n\nlemma nonneg_int_eval [rewrite]:\n  \"x \\<in>. \\<R> \\<Longrightarrow> nonneg_int(Int(x)) \\<longleftrightarrow> nonneg_int_raw(x)\"\n@proof\n  @have (@rule) \"\\<forall>a b c d. \\<langle>a,b\\<rangle> \\<sim>\\<^sub>\\<R> \\<langle>c,d\\<rangle> \\<longrightarrow> a \\<ge>\\<^sub>\\<nat> b \\<longrightarrow> c \\<ge>\\<^sub>\\<nat> d\" @with\n    @contradiction @have \"a +\\<^sub>\\<nat> d >\\<^sub>\\<nat> b +\\<^sub>\\<nat> c\"\n  @end\n@qed\nsetup {* del_prfstep_thm @{thm nonneg_int_def} *}\n\nlemma int_neg_eval [rewrite]: \"x \\<in>. \\<R> \\<Longrightarrow> -\\<^sub>\\<int> Int(x) = Int(int_neg_raw(x))\"\n@proof @have \"Int(x) +\\<^sub>\\<int> Int(int_neg_raw(x)) = \\<zero>\\<^sub>\\<int>\" @qed\n\nlemma nonneg_int_raw_mult [backward2]:\n  \"\\<langle>a,b\\<rangle> \\<in>. \\<R> \\<Longrightarrow> \\<langle>c,d\\<rangle> \\<in>. \\<R> \\<Longrightarrow> nonneg_int_raw(\\<langle>a,b\\<rangle>) \\<Longrightarrow> nonneg_int_raw(\\<langle>c,d\\<rangle>) \\<Longrightarrow>\n   nonneg_int_raw(int_mult_raw(\\<langle>a,b\\<rangle>, \\<langle>c,d\\<rangle>))\"\n@proof\n  @obtain \"p\\<in>nat\" where \"a = b +\\<^sub>\\<nat> p\"\n  @obtain \"q\\<in>nat\" where \"c = d +\\<^sub>\\<nat> q\"\n  @have \"(b+\\<^sub>\\<nat>p)*\\<^sub>\\<nat>d +\\<^sub>\\<nat> b*\\<^sub>\\<nat>(d+\\<^sub>\\<nat>q) +\\<^sub>\\<nat> p*\\<^sub>\\<nat>q = (b+\\<^sub>\\<nat>p)*\\<^sub>\\<nat>(d+\\<^sub>\\<nat>q) +\\<^sub>\\<nat> b*\\<^sub>\\<nat>d\"\n@qed\n\nlemma int_nonneg_compat [resolve]: \"nonneg_compat(\\<int>, nonneg_ints)\" by auto2\nsetup {* fold del_prfstep_thm [@{thm nonneg_int_eval}, @{thm nonneg_int_raw_mult},\n  @{thm nonneg_int_raw_def}, @{thm nonneg_ints_def}] *}\n\nlemma int_is_ord_ring [forward]: \"is_ord_ring(\\<int>)\"\n@proof @have \"nonneg_compat(\\<int>, nonneg_ints)\" @qed\nsetup {* del_prfstep_thm @{thm int_is_ord_ring_prep} *}\n\nsection \\<open>Integers as integral domain\\<close>\n\nlemma int_is_domain_raw [forward]:\n  \"x1 \\<in>. \\<nat> \\<Longrightarrow> y1 \\<in>. \\<nat> \\<Longrightarrow> x2 \\<in>. \\<nat> \\<Longrightarrow> y2 \\<in>. \\<nat> \\<Longrightarrow>\n   x1 *\\<^sub>\\<nat> x2 +\\<^sub>\\<nat> y1 *\\<^sub>\\<nat> y2 = x1 *\\<^sub>\\<nat> y2 +\\<^sub>\\<nat> y1 *\\<^sub>\\<nat> x2 \\<Longrightarrow> x1 = y1 \\<or> x2 = y2\"\n@proof\n  @case \"x1 <\\<^sub>\\<nat> y1\" @with\n    @obtain \"p\\<in>nat\" where \"p \\<noteq> 0\" \"y1 = x1 +\\<^sub>\\<nat> p\"\n    @have \"x1 *\\<^sub>\\<nat> x2 +\\<^sub>\\<nat> (x1 +\\<^sub>\\<nat> p) *\\<^sub>\\<nat> y2 = (x1 *\\<^sub>\\<nat> x2 +\\<^sub>\\<nat> x1 *\\<^sub>\\<nat> y2) +\\<^sub>\\<nat> p *\\<^sub>\\<nat> y2\"\n    @have \"x1 *\\<^sub>\\<nat> y2 +\\<^sub>\\<nat> (x1 +\\<^sub>\\<nat> p) *\\<^sub>\\<nat> x2 = (x1 *\\<^sub>\\<nat> x2 +\\<^sub>\\<nat> x1 *\\<^sub>\\<nat> y2) +\\<^sub>\\<nat> p *\\<^sub>\\<nat> x2\" @end\n  @case \"x1 >\\<^sub>\\<nat> y1\" @with\n    @obtain \"p\\<in>nat\" where \"p \\<noteq> 0\" \"x1 = y1 +\\<^sub>\\<nat> p\"\n    @have \"(y1 +\\<^sub>\\<nat> p) *\\<^sub>\\<nat> x2 +\\<^sub>\\<nat> y1 *\\<^sub>\\<nat> y2 = (y1 *\\<^sub>\\<nat> x2 +\\<^sub>\\<nat> y1 *\\<^sub>\\<nat> y2) +\\<^sub>\\<nat> p *\\<^sub>\\<nat> x2\"\n    @have \"(y1 +\\<^sub>\\<nat> p) *\\<^sub>\\<nat> y2 +\\<^sub>\\<nat> y1 *\\<^sub>\\<nat> x2 = (y1 *\\<^sub>\\<nat> x2 +\\<^sub>\\<nat> y1 *\\<^sub>\\<nat> y2) +\\<^sub>\\<nat> p *\\<^sub>\\<nat> y2\" @end\n@qed\n\nlemma int_is_domain [forward]: \"integral_domain(\\<int>)\" by auto2\n\nsection \\<open>Integer as a difference of two natural numbers\\<close>\n\nlemma int_of_nat [rewrite]: \"n \\<in> nat \\<Longrightarrow> of_nat(\\<int>,n) = Int(\\<langle>n,0\\<rangle>)\"\n@proof @var_induct \"n \\<in> nat\" @qed\n\nlemma int_diff_eval [rewrite]:\n  \"\\<langle>a,b\\<rangle> \\<in>. \\<R> \\<Longrightarrow> \\<langle>c,d\\<rangle> \\<in>. \\<R> \\<Longrightarrow> Int(\\<langle>a,b\\<rangle>) -\\<^sub>\\<int> Int(\\<langle>c,d\\<rangle>) = Int(\\<langle>a+\\<^sub>\\<nat>d,b+\\<^sub>\\<nat>c\\<rangle>)\"\n@proof @have \"Int(\\<langle>a,b\\<rangle>) -\\<^sub>\\<int> Int(\\<langle>c,d\\<rangle>) = Int(\\<langle>a,b\\<rangle>) +\\<^sub>\\<int> (-\\<^sub>\\<int> Int(\\<langle>c,d\\<rangle>))\" @qed\n\nlemma int_is_diff [backward]:\n  \"n \\<in> int \\<Longrightarrow> \\<exists>a\\<in>.\\<nat>. \\<exists>b\\<in>.\\<nat>. n = of_nat(\\<int>,a) -\\<^sub>\\<int> of_nat(\\<int>,b)\"\n@proof\n  @let \"p = rep(\\<R>,n)\"\n  @have \"n = of_nat(\\<int>,fst(p)) -\\<^sub>\\<int> of_nat(\\<int>,snd(p))\"\n@qed\n\nsection \\<open>Definition of int\\_act\\<close>\n\ndefinition int_act_raw :: \"i \\<Rightarrow> i \\<Rightarrow> i \\<Rightarrow> i\" where [rewrite]:\n  \"int_act_raw(R,p,x) = nat_act(R,fst(p),x) -\\<^sub>R nat_act(R,snd(p),x)\"\n\nlemma int_act_raw_eval [rewrite]:\n  \"int_act_raw(R,\\<langle>a,b\\<rangle>,x) = nat_act(R,a,x) -\\<^sub>R nat_act(R,b,x)\" by auto2\nsetup {* del_prfstep_thm @{thm int_act_raw_def} *}\n\nlemma comm_ring_switch_sides4 [resolve]:\n  \"is_abgroup(R) \\<Longrightarrow> a \\<in>. R \\<Longrightarrow> b \\<in>. R \\<Longrightarrow> c \\<in>. R \\<Longrightarrow> d \\<in>. R \\<Longrightarrow>\n   a +\\<^sub>R d = b +\\<^sub>R c \\<Longrightarrow> a -\\<^sub>R b = c -\\<^sub>R d\"\n@proof @have \"a -\\<^sub>R b +\\<^sub>R (b +\\<^sub>R d) = c -\\<^sub>R d +\\<^sub>R (b +\\<^sub>R d)\" @qed\n\ndefinition int_act :: \"i \\<Rightarrow> i \\<Rightarrow> i \\<Rightarrow> i\" where [rewrite]:\n  \"int_act(R,z,x) = int_act_raw(R,rep(\\<R>,z),x)\"\nsetup {* register_wellform_data (\"int_act(R,z,x)\", [\"z \\<in>. \\<int>\"]) *}\n  \nlemma int_act_eval [rewrite]:\n  \"is_abgroup(R) \\<Longrightarrow> p \\<in>. \\<R> \\<Longrightarrow> x \\<in>. R \\<Longrightarrow> int_act(R,Int(p),x) = int_act_raw(R,p,x)\"\n@proof\n  @have (@rule) \"\\<forall>a b c d. \\<langle>a,b\\<rangle> \\<sim>\\<^sub>\\<R> \\<langle>c,d\\<rangle> \\<longrightarrow> int_act_raw(R,\\<langle>a,b\\<rangle>,x) = int_act_raw(R,\\<langle>c,d\\<rangle>,x)\" @with\n    @have \"nat_act(R,a,x) +\\<^sub>R nat_act(R,d,x) = nat_act(R,b,x) +\\<^sub>R nat_act(R,c,x)\"\n  @end\n@qed\nsetup {* del_prfstep_thm @{thm int_act_def} *}\n\nlemma int_act_type [typing]:\n  \"is_abgroup(R) \\<Longrightarrow> a \\<in>. \\<int> \\<Longrightarrow> x \\<in>. R \\<Longrightarrow> int_act(R,a,x) \\<in>. R\" by auto2\n\nlemma int_act_eval_diff [rewrite]:\n  \"is_abgroup(R) \\<Longrightarrow> a \\<in> nat \\<Longrightarrow> b \\<in> nat \\<Longrightarrow> x \\<in>. R \\<Longrightarrow>\n   int_act(R,of_nat(\\<int>,a) -\\<^sub>\\<int> of_nat(\\<int>,b),x) = nat_act(R,a,x) -\\<^sub>R nat_act(R,b,x)\" by auto2\n\nlemma int_act_of_nat [rewrite]:\n  \"is_abgroup(R) \\<Longrightarrow> n \\<in> nat \\<Longrightarrow> x \\<in>. R \\<Longrightarrow> int_act(R,of_nat(\\<int>,n),x) = nat_act(R,n,x)\" by auto2\n  \nlemma int_act_zero [rewrite]:\n  \"is_abgroup(R) \\<Longrightarrow> r \\<in>. R \\<Longrightarrow> int_act(R,\\<zero>\\<^sub>\\<int>,r) = \\<zero>\\<^sub>R\" by auto2\n\nlemma int_act_one [rewrite]:\n  \"is_abgroup(R) \\<Longrightarrow> r \\<in>. R \\<Longrightarrow> int_act(R,\\<one>\\<^sub>\\<int>,r) = r\" by auto2\n\nlemma int_act_zero_right [rewrite]:\n  \"is_abgroup(R) \\<Longrightarrow> n \\<in>. \\<int> \\<Longrightarrow> int_act(R,n,\\<zero>\\<^sub>R) = \\<zero>\\<^sub>R\" by auto2\n\nsetup {* del_prfstep_thm @{thm int_of_nat} *}\nsetup {* fold del_prfstep_thm [@{thm int_act_raw_eval}, @{thm int_act_eval}] *}\nsetup {* fold del_prfstep_thm [@{thm int_def}, @{thm int_rel_spaceI}, @{thm int_rel_spaceD}] *}\nsetup {* fold del_prfstep_thm @{thms int_evals(1-2)} *}\nsetup {* fold del_prfstep_thm [@{thm int_choose_rep}, @{thm int_neg_eval}, @{thm int_add_eval},\n  @{thm int_diff_eval}, @{thm int_mult_eval}] *}\nno_notation int_rel (\"\\<R>\")\nhide_const Int\n\nsection \\<open>Further properties of int\\_act\\<close>\n\nlemma int_act_add [rewrite_bidir]:\n  \"is_abgroup(R) \\<Longrightarrow> x \\<in>. \\<int> \\<Longrightarrow> y \\<in>. \\<int> \\<Longrightarrow> r \\<in>. R \\<Longrightarrow> int_act(R,x +\\<^sub>\\<int> y,r) = int_act(R,x,r) +\\<^sub>R int_act(R,y,r)\"\n@proof\n  @obtain \"a\\<in>.\\<nat>\" \"b\\<in>.\\<nat>\" where \"x = of_nat(\\<int>,a) -\\<^sub>\\<int> of_nat(\\<int>,b)\"\n  @obtain \"c\\<in>.\\<nat>\" \"d\\<in>.\\<nat>\" where \"y = of_nat(\\<int>,c) -\\<^sub>\\<int> of_nat(\\<int>,d)\"\n  @let \"za = of_nat(\\<int>,a)\" \"zb = of_nat(\\<int>,b)\" \"zc = of_nat(\\<int>,c)\" \"zd = of_nat(\\<int>,d)\"\n  @let \"ra = nat_act(R,a,r)\" \"rb = nat_act(R,b,r)\" \"rc = nat_act(R,c,r)\" \"rd = nat_act(R,d,r)\"\n  @have \"(za -\\<^sub>\\<int> zb) +\\<^sub>\\<int> (zc -\\<^sub>\\<int> zd) = (za +\\<^sub>\\<int> zc) -\\<^sub>\\<int> (zb +\\<^sub>\\<int> zd)\"\n  @have \"(ra -\\<^sub>R rb) +\\<^sub>R (rc -\\<^sub>R rd) = (ra +\\<^sub>R rc) -\\<^sub>R (rb +\\<^sub>R rd)\"\n@qed\n\nlemma int_act_uminus [rewrite_bidir]:\n  \"is_abgroup(R) \\<Longrightarrow> x \\<in>. \\<int> \\<Longrightarrow> r \\<in>. R \\<Longrightarrow> int_act(R,-\\<^sub>\\<int> x, r) = -\\<^sub>R int_act(R,x,r)\"\n@proof @have \"int_act(R,-\\<^sub>\\<int> x,r) +\\<^sub>R int_act(R,x,r) = \\<zero>\\<^sub>R\" @qed\n\nlemma int_act_minus [rewrite_bidir]:\n  \"is_abgroup(R) \\<Longrightarrow> x \\<in>. \\<int> \\<Longrightarrow> y \\<in>. \\<int> \\<Longrightarrow> r \\<in>. R \\<Longrightarrow> int_act(R,x -\\<^sub>\\<int> y,r) = int_act(R,x,r) -\\<^sub>R int_act(R,y,r)\"\n@proof @have \"int_act(R,x,r) -\\<^sub>R int_act(R,y,r) = int_act(R,x,r) +\\<^sub>R (-\\<^sub>R int_act(R,y,r))\" @qed\n\nlemma int_act_add_right [rewrite_bidir]:\n  \"is_abgroup(R) \\<Longrightarrow> x \\<in>. \\<int> \\<Longrightarrow> r \\<in>. R \\<Longrightarrow> s \\<in>. R \\<Longrightarrow> int_act(R,x,r +\\<^sub>R s) = int_act(R,x,r) +\\<^sub>R int_act(R,x,s)\"\n@proof\n  @obtain \"a\\<in>.\\<nat>\" \"b\\<in>.\\<nat>\" where \"x = of_nat(\\<int>,a) -\\<^sub>\\<int> of_nat(\\<int>,b)\"\n  @have \"(nat_act(R,a,r) +\\<^sub>R nat_act(R,a,s)) -\\<^sub>R (nat_act(R,b,r) +\\<^sub>R nat_act(R,b,s)) =\n         (nat_act(R,a,r) -\\<^sub>R nat_act(R,b,r)) +\\<^sub>R (nat_act(R,a,s) -\\<^sub>R nat_act(R,b,s))\"\n@qed\n\nlemma int_act_uminus_right [rewrite_bidir]:\n  \"is_abgroup(R) \\<Longrightarrow> x \\<in>. \\<int> \\<Longrightarrow> r \\<in>. R \\<Longrightarrow> int_act(R,x,-\\<^sub>R r) = -\\<^sub>R int_act(R,x,r)\"\n@proof @have \"int_act(R,x,-\\<^sub>R r) +\\<^sub>R int_act(R,x,r) = \\<zero>\\<^sub>R\" @qed\n\nlemma int_act_sub_right [rewrite_bidir]:\n  \"is_abgroup(R) \\<Longrightarrow> x \\<in>. \\<int> \\<Longrightarrow> r \\<in>. R \\<Longrightarrow> s \\<in>. R \\<Longrightarrow> int_act(R,x,r -\\<^sub>R s) = int_act(R,x,r) -\\<^sub>R int_act(R,x,s)\"\n@proof @have \"int_act(R,x,r) -\\<^sub>R int_act(R,x,s) = int_act(R,x,r) +\\<^sub>R (-\\<^sub>R int_act(R,x,s))\" @qed\n\nlemma int_act_mult [rewrite_bidir]:\n  \"is_abgroup(R) \\<Longrightarrow> x \\<in>. \\<int> \\<Longrightarrow> y \\<in>. \\<int> \\<Longrightarrow> r \\<in>. R \\<Longrightarrow> int_act(R,x *\\<^sub>\\<int> y, r) = int_act(R,x,int_act(R,y,r))\"\n@proof\n  @obtain \"a\\<in>.\\<nat>\" \"b\\<in>.\\<nat>\" where \"x = of_nat(\\<int>,a) -\\<^sub>\\<int> of_nat(\\<int>,b)\"\n  @obtain \"c\\<in>.\\<nat>\" \"d\\<in>.\\<nat>\" where \"y = of_nat(\\<int>,c) -\\<^sub>\\<int> of_nat(\\<int>,d)\"\n  @let \"za = of_nat(\\<int>,a)\" \"zb = of_nat(\\<int>,b)\" \"zc = of_nat(\\<int>,c)\" \"zd = of_nat(\\<int>,d)\"\n  @have \"(za -\\<^sub>\\<int> zb) *\\<^sub>\\<int> (zc -\\<^sub>\\<int> zd) = (za *\\<^sub>\\<int> zc +\\<^sub>\\<int> zb *\\<^sub>\\<int> zd) -\\<^sub>\\<int> (za *\\<^sub>\\<int> zd +\\<^sub>\\<int> zb *\\<^sub>\\<int> zc)\"\n@qed\n\nsection \\<open>Definition of of\\_int\\<close>\n\ndefinition of_int :: \"i \\<Rightarrow> i \\<Rightarrow> i\" where [rewrite_bidir]:\n  \"of_int(R,z) = int_act(R,z,\\<one>\\<^sub>R)\"\nsetup {* register_wellform_data (\"of_int(R,z)\", [\"z \\<in>. \\<int>\"]) *}\n\nlemma of_int_type [typing]:\n  \"is_comm_ring(R) \\<Longrightarrow> a \\<in>. \\<int> \\<Longrightarrow> of_int(R,a) \\<in>. R\" by auto2\n\nlemma of_int_of_nat [rewrite]:\n  \"is_comm_ring(R) \\<Longrightarrow> n \\<in> nat \\<Longrightarrow> of_int(R,of_nat(\\<int>,n)) = of_nat(R,n)\" by auto2\n\nlemma of_int_add [rewrite_bidir]:\n  \"is_comm_ring(R) \\<Longrightarrow> x \\<in>. \\<int> \\<Longrightarrow> y \\<in>. \\<int> \\<Longrightarrow> of_int(R,x) +\\<^sub>R of_int(R,y) = of_int(R,x +\\<^sub>\\<int> y)\" by auto2\n\nlemma of_int_uminus [rewrite_bidir]:\n  \"is_comm_ring(R) \\<Longrightarrow> x \\<in>. \\<int> \\<Longrightarrow> -\\<^sub>R of_int(R,x) = of_int(R,-\\<^sub>\\<int> x)\" by auto2\n\nlemma of_int_sub [rewrite_bidir]:\n  \"is_comm_ring(R) \\<Longrightarrow> x \\<in>. \\<int> \\<Longrightarrow> y \\<in>. \\<int> \\<Longrightarrow> of_int(R,x) -\\<^sub>R of_int(R,y) = of_int(R,x -\\<^sub>\\<int> y)\" by auto2\n      \nsetup {* del_prfstep_thm_str \"\" @{thm of_int_def} *}\n\nlemma of_int_mult [rewrite_bidir]:\n  \"is_comm_ring(R) \\<Longrightarrow> x \\<in>. \\<int> \\<Longrightarrow> y \\<in>. \\<int> \\<Longrightarrow> of_int(R,x) *\\<^sub>R of_int(R,y) = of_int(R,x *\\<^sub>\\<int> y)\"\n@proof\n  @obtain \"a\\<in>.\\<nat>\" \"b\\<in>.\\<nat>\" where \"x = of_nat(\\<int>,a) -\\<^sub>\\<int> of_nat(\\<int>,b)\"\n  @obtain \"c\\<in>.\\<nat>\" \"d\\<in>.\\<nat>\" where \"y = of_nat(\\<int>,c) -\\<^sub>\\<int> of_nat(\\<int>,d)\"\n  @let \"za = of_nat(\\<int>,a)\" \"zb = of_nat(\\<int>,b)\" \"zc = of_nat(\\<int>,c)\" \"zd = of_nat(\\<int>,d)\"\n  @let \"ra = of_nat(R,a)\" \"rb = of_nat(R,b)\" \"rc = of_nat(R,c)\" \"rd = of_nat(R,d)\"\n  @have \"(za -\\<^sub>\\<int> zb) *\\<^sub>\\<int> (zc -\\<^sub>\\<int> zd) = (za *\\<^sub>\\<int> zc +\\<^sub>\\<int> zb *\\<^sub>\\<int> zd) -\\<^sub>\\<int> (za *\\<^sub>\\<int> zd +\\<^sub>\\<int> zb *\\<^sub>\\<int> zc)\"\n  @have \"(ra -\\<^sub>R rb) *\\<^sub>R (rc -\\<^sub>R rd) = (ra *\\<^sub>R rc +\\<^sub>R rb *\\<^sub>R rd) -\\<^sub>R (ra *\\<^sub>R rd +\\<^sub>R rb *\\<^sub>R rc)\"\n@qed\n\nlemma ord_ring_switch_sides4 [resolve]:\n  \"is_ord_ring(R) \\<Longrightarrow> a \\<in>. R \\<Longrightarrow> b \\<in>. R \\<Longrightarrow> c \\<in>. R \\<Longrightarrow> d \\<in>. R \\<Longrightarrow>\n   a -\\<^sub>R b \\<le>\\<^sub>R c -\\<^sub>R d \\<Longrightarrow> a +\\<^sub>R d \\<le>\\<^sub>R b +\\<^sub>R c\" by auto2\n\nlemma ord_ring_switch_sides4' [resolve]:\n  \"is_ord_ring(R) \\<Longrightarrow> a \\<in>. R \\<Longrightarrow> b \\<in>. R \\<Longrightarrow> c \\<in>. R \\<Longrightarrow> d \\<in>. R \\<Longrightarrow>\n   a +\\<^sub>R d \\<le>\\<^sub>R b +\\<^sub>R c \\<Longrightarrow> a -\\<^sub>R b \\<le>\\<^sub>R c -\\<^sub>R d\" by auto2\n\nlemma ord_ring_switch_sides4_less [resolve]:\n  \"is_ord_ring(R) \\<Longrightarrow> a \\<in>. R \\<Longrightarrow> b \\<in>. R \\<Longrightarrow> c \\<in>. R \\<Longrightarrow> d \\<in>. R \\<Longrightarrow>\n   a -\\<^sub>R b <\\<^sub>R c -\\<^sub>R d \\<Longrightarrow> a +\\<^sub>R d <\\<^sub>R b +\\<^sub>R c\" by auto2\n\nlemma ord_ring_switch_sides4_less' [resolve]:\n  \"is_ord_ring(R) \\<Longrightarrow> a \\<in>. R \\<Longrightarrow> b \\<in>. R \\<Longrightarrow> c \\<in>. R \\<Longrightarrow> d \\<in>. R \\<Longrightarrow>\n   a +\\<^sub>R d <\\<^sub>R b +\\<^sub>R c \\<Longrightarrow> a -\\<^sub>R b <\\<^sub>R c -\\<^sub>R d\" by auto2\n\nlemma ord_ring_of_int_le [backward]:\n  \"is_ord_ring(R) \\<Longrightarrow> x \\<le>\\<^sub>\\<int> y \\<Longrightarrow> of_int(R,x) \\<le>\\<^sub>R of_int(R,y)\"\n@proof\n  @obtain \"a\\<in>.\\<nat>\" \"b\\<in>.\\<nat>\" where \"x = of_nat(\\<int>,a) -\\<^sub>\\<int> of_nat(\\<int>,b)\"\n  @obtain \"c\\<in>.\\<nat>\" \"d\\<in>.\\<nat>\" where \"y = of_nat(\\<int>,c) -\\<^sub>\\<int> of_nat(\\<int>,d)\"\n  @have \"of_nat(\\<int>,a) +\\<^sub>\\<int> of_nat(\\<int>,d) \\<le>\\<^sub>\\<int> of_nat(\\<int>,b) +\\<^sub>\\<int> of_nat(\\<int>,c)\"\n  @have \"of_nat(R,a) +\\<^sub>R of_nat(R,d) \\<le>\\<^sub>R of_nat(R,b) +\\<^sub>R of_nat(R,c)\"\n@qed\n\nlemma ord_ring_of_int_less [backward]:\n  \"is_ord_ring(R) \\<Longrightarrow> x <\\<^sub>\\<int> y \\<Longrightarrow> of_int(R,x) <\\<^sub>R of_int(R,y)\"\n@proof\n  @obtain \"a\\<in>.\\<nat>\" \"b\\<in>.\\<nat>\" where \"x = of_nat(\\<int>,a) -\\<^sub>\\<int> of_nat(\\<int>,b)\"\n  @obtain \"c\\<in>.\\<nat>\" \"d\\<in>.\\<nat>\" where \"y = of_nat(\\<int>,c) -\\<^sub>\\<int> of_nat(\\<int>,d)\"\n  @have \"of_nat(\\<int>,a) +\\<^sub>\\<int> of_nat(\\<int>,d) <\\<^sub>\\<int> of_nat(\\<int>,b) +\\<^sub>\\<int> of_nat(\\<int>,c)\"\n  @have \"of_nat(R,a) +\\<^sub>R of_nat(R,d) <\\<^sub>R of_nat(R,b) +\\<^sub>R of_nat(R,c)\"\n@qed\n\nlemma ord_ring_of_int_le_back [forward]:\n  \"is_ord_ring(R) \\<Longrightarrow> x \\<in>. \\<int> \\<Longrightarrow> y \\<in>. \\<int> \\<Longrightarrow> of_int(R,x) \\<le>\\<^sub>R of_int(R,y) \\<Longrightarrow> x \\<le>\\<^sub>\\<int> y\"\n@proof @case \"of_int(R,y) <\\<^sub>R of_int(R,x)\" @qed\n\nlemma ord_ring_of_int_eq [forward]:\n  \"is_ord_ring(R) \\<Longrightarrow> x \\<in>. \\<int> \\<Longrightarrow> y \\<in>. \\<int> \\<Longrightarrow> of_int(R,x) = of_int(R,y) \\<Longrightarrow> x = y\"\n@proof\n  @case \"x <\\<^sub>\\<int> y\" @with @have \"of_int(R,x) <\\<^sub>R of_int(R,y)\" @end\n  @case \"x >\\<^sub>\\<int> y\" @with @have \"of_int(R,x) >\\<^sub>R of_int(R,y)\" @end\n@qed\n\nlemma ord_ring_of_int_positive:\n  \"is_ord_ring(R) \\<Longrightarrow> b >\\<^sub>\\<int> 0\\<^sub>\\<int> \\<Longrightarrow> of_int(R,b) >\\<^sub>R 0\\<^sub>R\"\n@proof @have \"of_int(R,b) >\\<^sub>R of_int(R,0\\<^sub>\\<int>)\" @qed\nsetup {* add_forward_prfstep_cond @{thm ord_ring_of_int_positive} [with_term \"of_int(?R,?b)\"] *}\n\nlemma int_gt_to_ge [backward]:\n  \"x >\\<^sub>\\<int> y \\<Longrightarrow> x \\<ge>\\<^sub>\\<int> y +\\<^sub>\\<int> 1\\<^sub>\\<int>\"\n@proof\n  @obtain \"a\\<in>.\\<nat>\" \"b\\<in>.\\<nat>\" where \"x = of_nat(\\<int>,a) -\\<^sub>\\<int> of_nat(\\<int>,b)\"\n  @obtain \"c\\<in>.\\<nat>\" \"d\\<in>.\\<nat>\" where \"y = of_nat(\\<int>,c) -\\<^sub>\\<int> of_nat(\\<int>,d)\"\n  @have \"of_nat(\\<int>,a) +\\<^sub>\\<int> of_nat(\\<int>,d) >\\<^sub>\\<int> of_nat(\\<int>,b) +\\<^sub>\\<int> of_nat(\\<int>,c)\"\n  @have \"of_nat(\\<int>,a) +\\<^sub>\\<int> of_nat(\\<int>,d) \\<ge>\\<^sub>\\<int> of_nat(\\<int>,b) +\\<^sub>\\<int> of_nat(\\<int>,c) +\\<^sub>\\<int> 1\\<^sub>\\<int>\"\n  @have \"of_nat(\\<int>,a) -\\<^sub>\\<int> of_nat(\\<int>,b) \\<ge>\\<^sub>\\<int> of_nat(\\<int>,c) -\\<^sub>\\<int> of_nat(\\<int>,d) +\\<^sub>\\<int> 1\\<^sub>\\<int>\"\n@qed\n  \nlemma int_gt_to_ge_one [resolve]:\n  \"x >\\<^sub>\\<int> 0\\<^sub>\\<int> \\<Longrightarrow> x \\<ge>\\<^sub>\\<int> 1\\<^sub>\\<int>\"\n@proof @have \"1\\<^sub>\\<int> = 0\\<^sub>\\<int> +\\<^sub>\\<int> 1\\<^sub>\\<int>\" @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/Int.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8577681049901037, "lm_q2_score": 0.8267117940706734, "lm_q1q2_score": 0.7091270089729704}}
{"text": "\\<^marker>\\<open>creator \"Kevin Kappelmann\"\\<close>\nsection \\<open>Set-Theoretic Orders\\<close>\ntheory SOrders\n  imports\n    SBinary_Relations_Antisymmetric\n    SBinary_Relations_Connected\n    SBinary_Relations_Reflexive\n    SBinary_Relations_Transitive\nbegin\n\ndefinition \"partial_order D R \\<equiv>\n  reflexive D R \\<and> transitive D R \\<and> antisymmetric D R\"\n\ndefinition \"linear_order D R \\<equiv> connected D R \\<and> partial_order D R\"\n\ndefinition \"well_founded D R \\<equiv>\n  \\<forall>X. X \\<subseteq> D \\<and> X \\<noteq> {} \\<longrightarrow> (\\<exists>a \\<in> X. \\<forall>x \\<in> X. \\<langle>x, a\\<rangle> \\<in> R \\<longrightarrow> x = a)\"\n\nlemma well_foundedI:\n  assumes \"\\<And>X. \\<lbrakk>X \\<subseteq> D; X \\<noteq> {}\\<rbrakk> \\<Longrightarrow> \\<exists>a \\<in> X. \\<forall>x \\<in> X. \\<langle>x, a\\<rangle> \\<in> R \\<longrightarrow> x = a\"\n  shows \"well_founded D R\"\n  using assms unfolding well_founded_def by auto\n\ndefinition \"well_order D R \\<equiv> linear_order D R \\<and> well_founded D R\"\n\n\nend", "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/HOTG/Orders/SOrders.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680977182186, "lm_q2_score": 0.8267117983401363, "lm_q1q2_score": 0.7091270066234263}}
{"text": "theory ivt\n\nimports Complex_Main\n\nbegin\n\ntheorem ivt:\n  fixes f :: \"real \\<Rightarrow> real\" and a b :: real\n  assumes ctsf: \"continuous_on {a..b} f\" \n      and \"a < b\" and fa1: \"f a < 0\" and fa2: \"f b > 0\"\n  shows \"\\<exists> x \\<in> {a..b}. f x = 0\"\nproof -\n  have \"a \\<in> {a..b}\" using assms by auto\n  have [simp]: \"a \\<in> {x. x \\<in> {a..b} \\<and> f x < 0}\" using assms by auto\n  have \"bdd_above {a..b}\" by auto\n  have \"bdd_above {x. x \\<in> {a..b} \\<and> f x < 0}\" by auto\n  define y where \"y = Sup {x. x \\<in> {a..b} \\<and> f x < 0}\"\n  have \"y \\<in> {a..b}\"\n    by (smt \\<open>a \\<in> {x \\<in> {a..b}. f x < 0}\\<close> \\<open>bdd_above {a..b}\\<close> \n          \\<open>bdd_above {x \\<in> {a..b}. f x < 0}\\<close> atLeastAtMost_iff \n          cSup_atLeastAtMost cSup_mono empty_iff mem_Collect_eq y_def)\n  have \"\\<not> f y < 0\"\n  proof\n    assume \"f y < 0\"\n    hence \"- f y > 0\" by linarith\n    with ctsf have \"\\<exists> \\<delta>. \\<delta> > 0 \\<and> \n        (\\<forall> x. x \\<in> {a..b} \\<and> abs (x - y) < \\<delta> \\<longrightarrow> abs (f x - f y) < - f y)\"\n      apply (simp add: continuous_on_def tendsto_iff dist_real_def \n              eventually_at)\n      by (metis \\<open>0 < - f y\\<close> \\<open>y \\<in> {a..b}\\<close> abs_zero atLeastAtMost_iff \n            cancel_comm_monoid_add_class.diff_cancel)\n    then obtain \\<delta> where \"\\<delta> > 0\" and \n        h: \"\\<And>x. x \\<in> {a..b} \\<Longrightarrow> abs (x - y) < \\<delta> \\<Longrightarrow> abs (f x - f y) < - f y\"\n      by auto\n    let ?\\<delta>' = \"min (\\<delta> / 2) (b - y)\"\n    let ?y' = \"y + ?\\<delta>'\"\n    from \\<open>y \\<in> {a..b}\\<close> \\<open>f y < 0\\<close> \\<open>f b > 0\\<close> have \"y < b\"\n      by (smt atLeastAtMost_iff)\n    with \\<open>\\<delta> > 0\\<close> have \"?y' > y\" by linarith\n    from \\<open>y \\<in> {a..b}\\<close> \\<open>\\<delta> > 0\\<close> have \"?y' \\<in> {a..b}\" and \"abs (?y' - y) < \\<delta>\" \n      by auto\n    hence \"abs (f ?y' - f y) < - f y\" by (auto intro: h)\n    with \\<open>- f y > 0\\<close> have \"f ?y' < 0\" by auto\n    with \\<open>?y' \\<in> {a..b}\\<close> have \"y \\<ge> ?y'\"\n      by - (subst (3) y_def, rule cSup_upper, auto)      \n    thus False\n      using \\<open>0 < \\<delta>\\<close> \\<open>y < b\\<close> by linarith\n  qed\n  moreover have \"\\<not> f y > 0\"\n  proof\n    assume \"f y > 0\"\n    with ctsf have \"\\<exists> \\<delta>. \\<delta> > 0 \\<and> \n        (\\<forall> x. x \\<in> {a..b} \\<and> abs (x - y) < \\<delta> \\<longrightarrow> abs (f x - f y) < f y)\"\n      apply (simp add: continuous_on_def tendsto_iff dist_real_def \n              eventually_at)\n      by (metis \\<open>0 < f y\\<close> \\<open>y \\<in> {a..b}\\<close> abs_zero atLeastAtMost_iff \n            cancel_comm_monoid_add_class.diff_cancel)\n    then obtain \\<delta> where \"\\<delta> > 0\" and \n        h: \"\\<And>x. x \\<in> {a..b} \\<Longrightarrow> abs (x - y) < \\<delta> \\<Longrightarrow> abs (f x - f y) < f y\"\n      by auto\n    from \\<open>y \\<in> {a..b}\\<close> \\<open>f y > 0\\<close> \\<open>f a < 0\\<close> have \"y > a\"\n      by (smt atLeastAtMost_iff)\n    let ?\\<delta>' = \"min (\\<delta> / 2) (y - a)\"\n    let ?y' = \"y - ?\\<delta>'\"\n    from \\<open>0 < \\<delta>\\<close> \\<open>a < y\\<close> \\<open>a \\<in> {x. x \\<in> {a..b} \\<and> f x < 0}\\<close> \n        have \"\\<exists> y'' \\<in> {x. x \\<in> {a..b} \\<and> f x < 0}. ?y' < y''\"\n      by (subst y_def, subst less_cSup_iff [symmetric], auto)\n    then obtain y'' where \"y'' > ?y'\" \n           and hy'': \"y'' \\<in> {x. x \\<in> {a..b} \\<and> f x < 0}\" by auto\n    hence \"y'' \\<le> y\"\n      by (metis \\<open>bdd_above {x \\<in> {a..b}. f x < 0}\\<close> cSup_upper y_def)\n    with \\<open>y'' > ?y'\\<close> \\<open>y \\<in> {a..b}\\<close> \\<open>\\<delta> > 0\\<close> hy'' have \"abs (f y'' - f y) < f y\"\n      by (auto intro: h)\n    hence \"f y'' > 0\" by auto\n    with hy'' show False by auto\n  qed\n  ultimately have \"f y = 0\" by linarith\n  with \\<open>y \\<in> {a..b}\\<close> show ?thesis by blast\nqed\n\ntheorem ivt_original_beginning:\n  fixes f :: \"real \\<Rightarrow> real\" and a b :: real\n  assumes ctsf: \"continuous_on {a..b} f\" \n      and \"a < b\" and fa1: \"f a < 0\" and fa2: \"f b > 0\"\n  shows \"True\"\nproof -\n  define y where \"y = Sup {x. x \\<in> {a..b} \\<and> f x < 0}\"\n  have \"y \\<in> {a..b}\"\n  proof -\n    have \"y \\<le> Sup {a..b}\"\n      apply (subst y_def)\n      apply (rule cSup_mono)\n      using assms apply auto\n      apply (rule_tac x = \"a\" in exI)\n      by auto\n    hence \"y \\<le> b\" using \\<open>a < b\\<close> by auto\n    moreover have \"a \\<le> y\"\n      apply (auto simp add: y_def)\n      apply (rule cSup_upper)\n      using assms by auto\n    ultimately show ?thesis by auto\n  qed\n  show ?thesis by auto\nqed\n\nend\n\n(* Notes\nTo state the theorem, need to remember {a..b}, and find notation Sup in file.\n\nThe problem is that the library is deep. \n\nSledgehammer didn't get y \\<in> {a..b} or even y \\<le> b, so I added y \\<le> Sup {a..b}.\n\nGolfed down -- automation\n\nArithmetic -- auto, smt, and linarith\n\nTwo places where sledgehammer might have helped: figuring out how to go from continuity to the\nproperty I knew it had, and little properties of suprema. (In generality. Side conditions, set\nnot empty, bounded above.)\n*)\n", "meta": {"author": "avigad", "repo": "arwm", "sha": "c5e9654a07c7ec0b03959fce0ea98e0f9e76ce49", "save_path": "github-repos/isabelle/avigad-arwm", "path": "github-repos/isabelle/avigad-arwm/arwm-c5e9654a07c7ec0b03959fce0ea98e0f9e76ce49/isabelle_experiments/ivt.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8577681086260461, "lm_q2_score": 0.8267117876664789, "lm_q1q2_score": 0.7091270064855331}}
{"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.*)\n  theory TIP_prop_74\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 take :: \"Nat => 'a list => 'a list\" where\n\"take (Z) z = nil2\"\n| \"take (S z2) (nil2) = nil2\"\n| \"take (S z2) (cons2 x2 x3) = cons2 x2 (take z2 x3)\"\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 len :: \"'a list => Nat\" where\n\"len (nil2) = Z\"\n| \"len (cons2 z xs) = S (len xs)\"\n\nfun drop :: \"Nat => 'a list => 'a list\" where\n\"drop (Z) z = z\"\n| \"drop (S z2) (nil2) = nil2\"\n| \"drop (S z2) (cons2 x2 x3) = drop z2 x3\"\n\nfun t2 :: \"Nat => Nat => Nat\" where\n\"t2 (Z) z = Z\"\n| \"t2 (S z2) (Z) = S z2\"\n| \"t2 (S z2) (S x2) = t2 z2 x2\"\n\ntheorem property0 :\n  \"((rev (take i xs)) = (drop (t2 (len xs) i) (rev 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/Isaplanner/Isaplanner/TIP_prop_74.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314828740729, "lm_q2_score": 0.8006919997179627, "lm_q1q2_score": 0.7091180430356261}}
{"text": "(* \n  Title: Duality Based on a Data Type\n  Author: Georg Struth \n  Maintainer:Georg Struth <g.struth@sheffield.ac.uk> \n*)\n\nsection \\<open>Duality Based on a Data Type\\<close>\n\ntheory Order_Lattice_Props_Wenzel\n  imports Main \nbegin\n\nunbundle lattice_syntax\n\nsubsection \\<open>Wenzel's Approach Revisited\\<close>\n\ntext \\<open>This approach is similar to, but inferior to the explicit class-based one. The main caveat is that duality is not involutive \nwith this approach, and this allows dualising less theorems.\\<close>\n\ntext \\<open>I copy Wenzel's development \\<^cite>\\<open>\"Wenzel\"\\<close> in this subsection and extend it with additional properties. I show only the most important properties.\\<close>\n\ndatatype 'a dual = dual (un_dual: 'a) (\"\\<partial>\")\n\nnotation un_dual (\"\\<partial>\\<^sup>-\")\n\nlemma dual_inj: \"inj \\<partial>\"\n  using injI by fastforce\n\nlemma dual_surj: \"surj \\<partial>\"\n  using dual.exhaust_sel by blast\n\nlemma dual_bij: \"bij \\<partial>\"\n  by (simp add: bijI dual_inj dual_surj)\n\ntext \\<open>Dual is not idempotent, and I see no way of imposing this condition. Yet at least an inverse exists --- namely un-dual..\\<close>\n\nlemma dual_inv1 [simp]: \"\\<partial>\\<^sup>- \\<circ> \\<partial> = id\"\n  by fastforce\n\nlemma dual_inv2 [simp]: \"\\<partial> \\<circ> \\<partial>\\<^sup>- = id\"\n  by fastforce\n\n\n\nlemma dual_inv_surj: \"surj \\<partial>\\<^sup>-\"\n  by (metis dual.sel surj_def)\n\nlemma dual_inv_bij: \"bij \\<partial>\\<^sup>-\"\n  by (simp add: bij_def dual_inv_inj dual_inv_surj)\n\n\n\ntext \\<open>Isabelle data types come with a number of generic functions.\\<close>\n\ntext \\<open>The functor map-dual lifts functions to dual types. Isabelle's generic definition is not straightforward to \nunderstand and use. Yet conceptually it can be explained as follows.\\<close>\n\nlemma map_dual_def_var [simp]: \"(map_dual::('a \\<Rightarrow> 'b) \\<Rightarrow> 'a dual \\<Rightarrow> 'b dual) f = \\<partial> \\<circ> f \\<circ> \\<partial>\\<^sup>-\"  \n  unfolding fun_eq_iff comp_def by (metis dual.map_sel dual_iff)\n\nlemma map_dual_def_var2: \"\\<partial>\\<^sup>- \\<circ> map_dual f = f \\<circ> \\<partial>\\<^sup>-\"\n  by (simp add: rewriteL_comp_comp)\n\nlemma map_dual_func1: \"map_dual (f \\<circ> g) = map_dual f \\<circ> map_dual g\"\n  unfolding fun_eq_iff comp_def by (metis dual.exhaust dual.map) \n\nlemma map_dual_func2 : \"map_dual id = id\"\n  by simp\n\ntext \\<open>The functor map-dual has an inverse functor as well.\\<close>\n\ndefinition map_dual_inv :: \"('a dual \\<Rightarrow> 'b dual) => ('a => 'b)\" where\n  \"map_dual_inv f = \\<partial>\\<^sup>- \\<circ> f \\<circ> \\<partial>\"\n\nlemma map_dual_inv_func1: \"map_dual_inv id = id\"\n  by (simp add: map_dual_inv_def)\n\nlemma map_dual_inv_func2: \"map_dual_inv (f \\<circ> g) = map_dual_inv f \\<circ> map_dual_inv g\"\n  unfolding fun_eq_iff comp_def map_dual_inv_def by (metis dual_iff)\n\nlemma map_dual_inv1: \"map_dual \\<circ> map_dual_inv = id\"\n  unfolding fun_eq_iff map_dual_def_var map_dual_inv_def comp_def id_def\n  by (metis dual_iff) \n\nlemma map_dual_inv2: \"map_dual_inv \\<circ> map_dual = id\"\n  unfolding fun_eq_iff map_dual_def_var map_dual_inv_def comp_def id_def\n  by (metis dual_iff) \n\ntext \\<open>Hence dual is an isomorphism between categories.\\<close>\n\nlemma subset_dual: \"(\\<partial> ` X = Y) \\<longleftrightarrow> (X = \\<partial>\\<^sup>- ` Y)\"\n  by (metis dual_inj image_comp image_inv_f_f inv_o_cancel dual_inv2)\n\nlemma subset_dual1: \"(X \\<subseteq> Y) \\<longleftrightarrow> (\\<partial> ` X \\<subseteq> \\<partial> ` Y)\"\n  by (simp add: dual_inj inj_image_subset_iff) \n\nlemma dual_ball: \"(\\<forall>x \\<in> X. P (\\<partial> x)) \\<longleftrightarrow> (\\<forall>y \\<in> \\<partial> ` X. P y)\"\n  by simp\n\nlemma dual_inv_ball: \"(\\<forall>x \\<in> X. P (\\<partial>\\<^sup>- x)) \\<longleftrightarrow> (\\<forall>y \\<in> \\<partial>\\<^sup>- ` X. P y)\"\n  by simp\n\nlemma dual_all: \"(\\<forall>x. P (\\<partial> x)) \\<longleftrightarrow> (\\<forall>y. P y)\"\n  by (metis dual.collapse)\n\nlemma dual_inv_all: \"(\\<forall>x. P (\\<partial>\\<^sup>- x)) \\<longleftrightarrow> (\\<forall>y. P y)\"\n  by (metis dual_inv_surj surj_def)\n\nlemma dual_ex: \"(\\<exists>x. P (\\<partial> x)) \\<longleftrightarrow> (\\<exists>y. P y)\"  \n  by (metis UNIV_I bex_imageD dual_surj)\n\nlemma dual_inv_ex: \"(\\<exists>x. P (\\<partial>\\<^sup>- x)) \\<longleftrightarrow> (\\<exists>y. P y)\"\n  by (metis dual.sel)\n\nlemma dual_Collect: \"{\\<partial> x |x. P (\\<partial> x)} = {y. P y}\"\n  by (metis dual.exhaust)\n\nlemma dual_inv_Collect: \"{\\<partial>\\<^sup>- x |x. P (\\<partial>\\<^sup>- x)} = {y. P y}\"\n  by (metis dual.collapse dual.inject)\n\nlemma fun_dual1: \"(f \\<circ> \\<partial> = g) \\<longleftrightarrow> (f = g \\<circ> \\<partial>\\<^sup>-)\"\n  by auto\n\nlemma fun_dual2: \"(\\<partial> \\<circ> f = g) \\<longleftrightarrow> (f = \\<partial>\\<^sup>- \\<circ> g)\"\n  by auto\n\nlemma fun_dual3: \"(f \\<circ> (`) \\<partial> = g) \\<longleftrightarrow> (f = g \\<circ> (`) \\<partial>\\<^sup>-)\"\n  unfolding fun_eq_iff comp_def by (metis subset_dual)\n\nlemma fun_dual4: \"(f = \\<partial>\\<^sup>- \\<circ> g \\<circ> (`) \\<partial>) \\<longleftrightarrow> (\\<partial> \\<circ> f \\<circ> (`) \\<partial>\\<^sup>- = g)\"\n  by (metis fun_dual2 fun_dual3 o_assoc)\n\ntext \\<open>The next facts show incrementally that the dual of a complete lattice is a complete lattice.\nThis follows once again Wenzel.\\<close>\n\ninstantiation dual :: (ord) ord\nbegin  \n\ndefinition less_eq_dual_def: \"(\\<le>) = rel_dual (\\<ge>)\"\n\ndefinition less_dual_def: \"(<) = rel_dual (>)\"\n\ninstance..\n\nend\n\nlemma less_eq_dual_def_var: \"(x \\<le> y) = (\\<partial>\\<^sup>- y \\<le> \\<partial>\\<^sup>- x)\"\n  apply (rule antisym)\n  apply (simp add: dual.rel_sel less_eq_dual_def)\n  by (simp add: dual.rel_sel less_eq_dual_def)\n\nlemma less_dual_def_var: \"(x < y) = (\\<partial>\\<^sup>- y < \\<partial>\\<^sup>- x)\"\n  by (simp add: dual.rel_sel less_dual_def) \n\ninstance dual :: (preorder) preorder\n  apply standard\n  apply (simp add: less_dual_def_var less_eq_dual_def_var less_le_not_le)\n  apply (simp add: less_eq_dual_def_var)\n  by (meson less_eq_dual_def_var order_trans)\n \ninstance dual :: (order) order\n  by (standard, simp add: dual.expand less_eq_dual_def_var)\n\nlemma dual_anti: \"x \\<le> y \\<Longrightarrow> \\<partial> y \\<le> \\<partial> x\" \n  by (simp add: dual_inj less_eq_dual_def the_inv_f_f)\n\nlemma dual_anti_iff: \"(x \\<le> y) = (\\<partial> y \\<le> \\<partial> x)\"\n  by (simp add: dual_inj less_eq_dual_def the_inv_f_f)\n\ntext \\<open>map-dual does not map isotone functions to antitone ones. It simply lifts the type!\\<close>\n\nlemma \"mono f \\<Longrightarrow> mono (map_dual f)\"\n  unfolding map_dual_def_var mono_def by (metis comp_apply dual_anti less_eq_dual_def_var)\n\ninstantiation dual :: (lattice) lattice\nbegin\n\ndefinition inf_dual_def: \"x \\<sqinter> y = \\<partial> (\\<partial>\\<^sup>- x \\<squnion> \\<partial>\\<^sup>- y)\"\n\ndefinition sup_dual_def: \"x \\<squnion> y = \\<partial> (\\<partial>\\<^sup>- x \\<sqinter> \\<partial>\\<^sup>- y)\"\n\ninstance\n  by (standard, simp_all add: dual_inj inf_dual_def sup_dual_def less_eq_dual_def_var the_inv_f_f)\n\nend\n\ninstantiation dual :: (complete_lattice) complete_lattice\nbegin\n\ndefinition Inf_dual_def: \"Inf = \\<partial> \\<circ> Sup \\<circ> (`) \\<partial>\\<^sup>-\"\n\ndefinition Sup_dual_def: \"Sup = \\<partial> \\<circ> Inf \\<circ> (`) \\<partial>\\<^sup>-\"\n\ndefinition bot_dual_def: \"\\<bottom> = \\<partial> \\<top>\"\n\ndefinition top_dual_def: \"\\<top> = \\<partial> \\<bottom>\"\n\ninstance\n   by (standard, simp_all add: Inf_dual_def top_dual_def Sup_dual_def bot_dual_def dual_inj le_INF_iff SUP_le_iff INF_lower SUP_upper less_eq_dual_def_var the_inv_f_f)\n\nend\n\ntext \\<open>Next, directed and filtered sets, upsets, downsets, filters and ideals in posets are defined.\\<close>\n\ncontext ord\nbegin\n\ndefinition directed :: \"'a set \\<Rightarrow> bool\" where\n \"directed X = (\\<forall>Y. finite Y \\<and> Y \\<subseteq> X \\<longrightarrow> (\\<exists>x \\<in> X. \\<forall>y \\<in> Y. y \\<le> x))\"\n\ndefinition filtered :: \"'a set \\<Rightarrow> bool\" where\n \"filtered X = (\\<forall>Y. finite Y \\<and> Y \\<subseteq> X \\<longrightarrow> (\\<exists>x \\<in> X. \\<forall>y \\<in> Y. x \\<le> y))\"\n\ndefinition downset_set :: \"'a set \\<Rightarrow> 'a set\" (\"\\<Down>\") where\n  \"\\<Down>X = {y. \\<exists>x \\<in> X. y \\<le> x}\"\n\ndefinition upset_set :: \"'a set \\<Rightarrow> 'a set\" (\"\\<Up>\") where\n \"\\<Up>X = {y. \\<exists>x \\<in> X. x \\<le> y}\"\n\nend\n\nsubsection \\<open>Examples that Do Not Dualise\\<close>\n\ntext \\<open>Filtered and directed sets are dual.\\<close>\n\ntext \\<open>Proofs could be simplified if dual was idempotent.\\<close>\n\nlemma filtered_directed_dual: \"filtered \\<circ> (`) \\<partial> = directed\"\nproof-\n  {fix X::\"'a set\"\n    have \"(filtered \\<circ> (`) \\<partial>) X = (\\<forall>Y. finite (\\<partial>\\<^sup>- ` Y) \\<and> \\<partial>\\<^sup>- ` Y \\<subseteq> X \\<longrightarrow> (\\<exists>x \\<in> X.\\<forall>y \\<in> (\\<partial>\\<^sup>- ` Y). \\<partial> x \\<le> \\<partial> y))\"\n      unfolding filtered_def comp_def by (simp, metis dual_iff finite_subset_image subset_dual subset_dual1)\n    also have \"... = (\\<forall>Y. finite Y \\<and> Y \\<subseteq> X \\<longrightarrow> (\\<exists>x \\<in> X.\\<forall>y \\<in> Y. y \\<le> x))\"\n      by (metis dual_anti_iff dual_inv_surj finite_subset_image top.extremum)\n    finally have \"(filtered \\<circ> (`) \\<partial>) X = directed X\"\n      using directed_def by auto}\n  thus ?thesis\n    unfolding fun_eq_iff by simp \nqed\n\nlemma directed_filtered_dual: \"directed \\<circ> (`) \\<partial> = filtered\"\nproof-\n  {fix X::\"'a set\"\n    have \"(directed \\<circ> (`) \\<partial>) X = (\\<forall>Y. finite (\\<partial>\\<^sup>- ` Y) \\<and> \\<partial>\\<^sup>- ` Y \\<subseteq> X \\<longrightarrow> (\\<exists>x \\<in> X.\\<forall>y \\<in> (\\<partial>\\<^sup>- ` Y). \\<partial> y \\<le> \\<partial> x))\"\n      unfolding directed_def comp_def by (simp, metis dual_iff finite_subset_image subset_dual subset_dual1)\n  also have \"... = (\\<forall>Y. finite Y \\<and> Y \\<subseteq> X \\<longrightarrow> (\\<exists>x \\<in> X.\\<forall>y \\<in> Y. x \\<le> y))\"\n    unfolding dual_anti_iff[symmetric] by (metis dual_inv_surj finite_subset_image top_greatest)\n  finally have \"(directed \\<circ> (`) \\<partial>) X = filtered X\"\n    using filtered_def by auto}\n  thus ?thesis\n    unfolding fun_eq_iff by simp\nqed\n\ntext \\<open>This example illustrates the deficiency of the approach. In the class-based approach the second proof is trivial.\\<close>\n\ntext \\<open>The next example shows that this is a systematic problem.\\<close>\n\nlemma downset_set_upset_set_dual: \"(`) \\<partial> \\<circ> \\<Down> = \\<Up> \\<circ> (`) \\<partial>\"\n  proof-\n    {fix X::\"'a set\"\n  have \"((`) \\<partial> \\<circ> \\<Down>) X = {\\<partial> y |y. \\<exists>x \\<in> X. y \\<le> x}\"\n    by (simp add: downset_set_def setcompr_eq_image)\n  also have \"... = {\\<partial> y |y. \\<exists>x \\<in> X. \\<partial> x \\<le> \\<partial> y}\"\n    by (meson dual_anti_iff)\n  also have \"... = {y. \\<exists>x \\<in> \\<partial> ` X. x \\<le> y}\"\n    by (metis (mono_tags, opaque_lifting) dual.exhaust image_iff)\n  finally have \"((`) \\<partial> \\<circ> \\<Down>) X = (\\<Up> \\<circ> (`) \\<partial>) X\"\n    by (simp add: upset_set_def)}\n  thus ?thesis\n    unfolding fun_eq_iff by simp\nqed\n\nlemma upset_set_downset_set_dual: \"(`) \\<partial> \\<circ> \\<Up> = \\<Down> \\<circ> (`) \\<partial>\"\n  unfolding downset_set_def upset_set_def fun_eq_iff comp_def\n  apply (safe, force simp: dual_anti)\n  by (metis (mono_tags, lifting) dual.exhaust dual_anti_iff mem_Collect_eq rev_image_eqI)\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/Order_Lattice_Props/Order_Lattice_Props_Wenzel.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8723473846343393, "lm_q2_score": 0.8128673155708975, "lm_q1q2_score": 0.7091026767930085}}
{"text": "theory Ex014\nimports Main \nbegin \n\n(*commutativity of \"and\"*)\n\n\n\nlemma \"A \\<and> B \\<longleftrightarrow> B \\<and> A\" \nproof - \n{\n  assume \"A \\<and> B\"\n  hence A by (rule conjE)\n  from \\<open>A \\<and> B\\<close> have B  by (rule conjE)\n  from this and  \\<open>A\\<close> have \"B \\<and> A\" by (rule conjI) \n} (*A \\<and> B \\<Longrightarrow> B \\<and> A*)\n{\n  assume \"B \\<and> A\"\n  hence A by (rule conjE)\n  from \\<open>B \\<and> A\\<close> have B  by (rule conjE)\n  with  \\<open>A\\<close> have \"A \\<and> B\" by (rule conjI) \n}\nfrom  \\<open>A \\<and> B \\<Longrightarrow> B \\<and> A\\<close> and this show ?thesis by (rule iffI)\nqed\n\n\n(*using moreover and ultimately to collect facts*)\n\nlemma \"A \\<and> B \\<longleftrightarrow> B \\<and> A\" \nproof - \n{\n  assume \"A \\<and> B\"\n  hence A by (rule conjE)\n  from \\<open>A \\<and> B\\<close> have B  by (rule conjE)\n  from this and  \\<open>A\\<close> have \"B \\<and> A\" by (rule conjI) \n} (*A \\<and> B \\<Longrightarrow> B \\<and> A*)\nmoreover\n{\n  assume \"B \\<and> A\"\n  hence A by (rule conjE)\n  from \\<open>B \\<and> A\\<close> have B  by (rule conjE)\n  with  \\<open>A\\<close> have \"A \\<and> B\" by (rule conjI) \n}\nultimately show ?thesis by (rule iffI)\nqed\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/Ex014.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898229217591, "lm_q2_score": 0.782662489091802, "lm_q1q2_score": 0.7090842498997849}}
{"text": "theory lec8 imports Main begin \n\ntext {*\n  Proving two examples from Logic and Proof lecture 8\n*}\n\nlemma \" \\<forall>x.\\<exists>y. \\<not>(P(y,x) \\<longleftrightarrow> \\<not>P(y,y))\" \n  apply(rule allI)\n  apply(rule exI)\n  apply(rule notI)\n  apply(erule iffE)\n  apply (erule impE)\n   apply (rule classical)\n   apply (erule mp)\n   apply assumption\n  apply (erule impE)\n   apply assumption\n  apply(erule notE)\n  apply assumption\n  done\n  \n\nlemma \"(((\\<exists>x. P \\<longrightarrow> Q x) \\<and> ((\\<exists>x. Q x \\<longrightarrow> P)) \\<longrightarrow> ( \\<exists>x. (P = Q x)))) \" \n  apply(rule impI)\n  apply(erule conjE)\n  apply(erule exE)+\n  apply(rule classical)\n  apply (rule exI)\n  apply (rule iffI)\n   apply (erule notE)\n   apply(erule impE)\n    apply assumption\n   apply (rule exI)\n   apply (rule iffI)\n    apply assumption\n  apply assumption\n  apply (erule impE)\n   apply (erule impE)\n    apply assumption\n   apply assumption\n  apply (erule impE)\n   apply assumption+\n  done\n  \n\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/lec8.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898153067649, "lm_q2_score": 0.7826624789529376, "lm_q1q2_score": 0.7090842347541068}}
{"text": "theory ex2_7\nimports Main\nbegin\n\ndatatype 'a tree = Leaf | Node \"'a tree\" 'a \"'a tree\"\n\nfun mirror :: \"'a tree \\<Rightarrow> 'a tree\" where\n\"mirror Leaf = Leaf\" |\n\"mirror (Node l x r) = Node (mirror r) x (mirror l)\"\n\nfun pre_order :: \"'a tree \\<Rightarrow> 'a list\" where\n\"pre_order Leaf =[]\" |\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 Leaf = []\" |\n\"post_order (Node l x r) = (post_order l)@(post_order r)@[x]\"\n\nvalue \"mirror(Node (Node Leaf a Leaf) b t)\"\nvalue \"pre_order (Node (Node Leaf a Leaf) b t)\"\nvalue \"post_order (Node (Node Leaf a Leaf) b t)\"\n\nlemma order : \"pre_order (mirror t) = rev (post_order t)\"\napply (induction t)\napply (auto)\ndone\n\nend", "meta": {"author": "oguri257", "repo": "isabelle", "sha": "master", "save_path": "github-repos/isabelle/oguri257-isabelle", "path": "github-repos/isabelle/oguri257-isabelle/isabelle-main/ex2_7.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.877476800298183, "lm_q2_score": 0.8080672066194946, "lm_q1q2_score": 0.7090602268903649}}
{"text": "theory Ugraphs\nimports\n  Girth_Chromatic_Misc\nbegin\n\nsection {* Undirected Simple Graphs *}\n\ntext {*\n  In this section, we define some basics of graph theory needed to formalize\n  the Chromatic-Girth theorem.\n*}\n\ntext {*\n  For readability, we introduce synonyms for the types of vertexes, edges,\n  graphs and walks.\n*}\ntype_synonym uvert = nat\ntype_synonym uedge = \"nat set\"\ntype_synonym ugraph = \"uvert set \\<times> uedge set\"\ntype_synonym uwalk = \"uvert list\"\n\nabbreviation uedges :: \"ugraph \\<Rightarrow> uedge set\" where\n  \"uedges G \\<equiv> snd G\"\n\nabbreviation uverts :: \"ugraph \\<Rightarrow> uvert set\" where\n  \"uverts G \\<equiv> fst G\"\n\nfun mk_uedge :: \"uvert \\<times> uvert \\<Rightarrow> uedge\" where\n   \"mk_uedge (u,v) = {u,v}\"\n\ntext {* All edges over a set of vertexes @{term S}: *}\ndefinition \"all_edges S \\<equiv> mk_uedge ` {uv \\<in> S \\<times> S. fst uv \\<noteq> snd uv}\"\n\ndefinition uwellformed :: \"ugraph \\<Rightarrow> bool\" where\n  \"uwellformed G \\<equiv> (\\<forall>e\\<in>uedges G. card e = 2 \\<and> (\\<forall>u \\<in> e. u \\<in> uverts G))\"\n\nfun uwalk_edges :: \"uwalk \\<Rightarrow> uedge list\" where\n    \"uwalk_edges [] = []\"\n  | \"uwalk_edges [x] = []\"\n  | \"uwalk_edges (x # y # ys) = {x,y} # uwalk_edges (y # ys)\"\n\ndefinition uwalk_length :: \"uwalk \\<Rightarrow> nat\" where\n  \"uwalk_length p \\<equiv> length (uwalk_edges p)\"\n\ndefinition uwalks :: \"ugraph \\<Rightarrow> uwalk set\" where\n  \"uwalks G \\<equiv> {p. set p \\<subseteq> uverts G \\<and> set (uwalk_edges p) \\<subseteq> uedges G \\<and> p \\<noteq> []}\"\n\ndefinition ucycles :: \"ugraph \\<Rightarrow> uwalk set\" where\n  \"ucycles G \\<equiv> {p. uwalk_length p \\<ge> 3 \\<and> p \\<in> uwalks G \\<and> distinct (tl p) \\<and> hd p = last p}\"\n\ndefinition remove_vertex :: \"ugraph \\<Rightarrow> nat \\<Rightarrow> ugraph\" (\"_ -- _\" [60,60] 60) where\n  \"remove_vertex G u \\<equiv> (uverts G - {u}, uedges G - {A \\<in> uedges G. u \\<in> A})\"\n\n\nsubsection {* Basic Properties *}\n\nlemma uwalk_length_conv: \"uwalk_length p = length p - 1\"\n  by (induct p rule: uwalk_edges.induct) (auto simp: uwalk_length_def)\n\nlemma all_edges_mono:\n  \"vs \\<subseteq> ws \\<Longrightarrow> all_edges vs \\<subseteq> all_edges ws\"\nusing assms unfolding all_edges_def by auto\n\nlemma all_edges_subset_Pow: \"all_edges A \\<subseteq> Pow A\"\n  by (auto simp: all_edges_def)\n\nlemma in_mk_uedge_img: \"(a,b) \\<in> A \\<or> (b,a) \\<in> A \\<Longrightarrow> {a,b} \\<in> mk_uedge ` A\"\n  by (auto intro: rev_image_eqI)\n\nlemma distinct_edgesI:\n  assumes \"distinct p\" shows \"distinct (uwalk_edges p)\"\nproof -\n  from assms have \"?thesis\" \"\\<And>u. u \\<notin> set p \\<Longrightarrow> (\\<And>v. u \\<noteq> v \\<Longrightarrow> {u,v} \\<notin> set (uwalk_edges p))\"\n    by (induct p rule: uwalk_edges.induct) auto\n  then show ?thesis by simp\nqed\n\nlemma finite_ucycles:\n  assumes \"finite (uverts G)\"\n  shows \"finite (ucycles G)\"\nproof -\n  have \"ucycles G \\<subseteq> {xs. set xs \\<subseteq> uverts G \\<and> length xs \\<le> Suc (card (uverts G))}\"\n  proof (rule, simp)\n    fix p assume \"p \\<in> ucycles G\"\n    then have \"distinct (tl p)\" and \"set p \\<subseteq> uverts G\"\n      unfolding ucycles_def uwalks_def by auto\n    moreover\n    then have \"set (tl p) \\<subseteq> uverts G\"\n      by (auto simp: list_set_tl)\n    with assms have \"card (set (tl p)) \\<le> card (uverts G)\"\n      by (rule card_mono)\n    then have \"length (p) \\<le> 1 + card (uverts G)\"\n      using distinct_card[OF `distinct (tl p)`] by auto\n    ultimately show \"set p \\<subseteq> uverts G \\<and> length p \\<le> Suc (card (uverts G))\" by auto\n  qed\n  moreover\n  have \"finite {xs. set xs \\<subseteq> uverts G \\<and> length xs \\<le> Suc (card (uverts G))}\"\n    using assms by (rule finite_lists_length_le)\n  ultimately\n  show ?thesis by (rule finite_subset)\nqed\n\nlemma ucycles_distinct_edges:\n  assumes \"c \\<in> ucycles G\" shows \"distinct (uwalk_edges c)\"\nproof -\n  from assms have c_props: \"distinct (tl c)\" \"4 \\<le> length c\" \"hd c = last c\"\n    by (auto simp add: ucycles_def uwalk_length_conv)\n  then have \"{hd c, hd (tl c)} \\<notin> set (uwalk_edges (tl c))\"\n  proof (induct c rule: uwalk_edges.induct)\n    case (3 x y ys)\n    then have \"hd ys \\<noteq> last ys\" by (cases ys) auto\n    moreover\n    from 3 have \"uwalk_edges (y # ys) = {y, hd ys} # uwalk_edges ys\"\n      by (cases ys) auto\n    moreover\n    { fix xs have \"set (uwalk_edges xs) \\<subseteq> Pow (set xs)\"\n        by (induct xs rule: uwalk_edges.induct) auto }\n    ultimately\n    show ?case using 3 by auto\n  qed simp_all\n  moreover\n  from assms have \"distinct (uwalk_edges (tl c))\"\n    by (intro distinct_edgesI) (simp add: ucycles_def)\n  ultimately\n  show ?thesis by (cases c rule: list_exhaust3) auto\nqed\n\nlemma card_left_less_pair:\n  fixes A :: \"('a :: linorder) set\"\n  assumes \"finite A\"\n  shows \"card {(a,b). a \\<in> A \\<and> b \\<in> A \\<and> a < b}\n    = (card A * (card A - 1)) div 2\"\nusing assms\nproof (induct A)\n  case (insert x A)\n\n  show ?case\n  proof (cases \"card A\")\n    case (Suc n)\n    have \"{(a,b). a \\<in> insert x A \\<and> b \\<in> insert x A \\<and> a < b}\n        = {(a,b). a \\<in> A \\<and> b \\<in> A \\<and> a < b} \\<union> (\\<lambda>a. if a < x then (a,x) else (x,a)) ` A\"\n      using `x \\<notin> A` by (auto simp: order_less_le)\n    moreover\n    have \"finite {(a,b). a \\<in> A \\<and> b \\<in> A \\<and> a < b}\"\n      using insert by (auto intro: finite_subset[of _ \"A \\<times> A\"])\n    moreover \n    have \"{(a,b). a \\<in> A \\<and> b \\<in> A \\<and> a < b} \\<inter> (\\<lambda>a. if a < x then (a,x) else (x,a)) ` A = {}\"\n      using `x \\<notin> A` by auto\n    moreover have \"inj_on (\\<lambda>a. if a < x then (a, x) else (x, a)) A\"\n      by (auto intro: inj_onI split: split_if_asm)\n    ultimately show ?thesis using insert Suc\n      by (simp add: card_Un_disjoint card_image del: if_image_distrib)\n  qed (simp add: card_0_iff insert)\nqed simp\n\nlemma card_all_edges:\n  assumes \"finite A\"\n  shows \"card (all_edges A) = card A choose 2\"\nproof -\n  have inj_on_mk_uedge: \"inj_on mk_uedge {(a,b). a < b}\"\n    by (rule inj_onI) (auto simp: doubleton_eq_iff)\n  have \"all_edges A = mk_uedge ` {(a,b). a \\<in> A \\<and> b \\<in> A \\<and> a < b}\" (is \"?L = ?R\")\n    by (auto simp: all_edges_def intro!: in_mk_uedge_img)\n  then have \"card ?L = card ?R\" by simp\n  also have \"\\<dots> = card {(a,b). a \\<in> A \\<and> b \\<in> A \\<and> a < b}\"\n    using inj_on_mk_uedge by (blast intro: card_image subset_inj_on)\n  also have \"\\<dots> = (card A * (card A - 1)) div 2\"\n    using card_left_less_pair using assms by simp\n  also have \"\\<dots> = (card A choose 2)\"\n    by (simp add: n_choose_2_nat)\n  finally show ?thesis .\nqed\n\nlemma verts_Gu: \"uverts (G -- u) = uverts G - {u}\"\n  unfolding remove_vertex_def by simp\n\nlemma edges_Gu: \"uedges (G -- u) \\<subseteq> uedges G\"\n  unfolding remove_vertex_def by auto\n\n\nsubsection {* Girth, Independence and Vertex Colorings *}\n\ndefinition girth :: \"ugraph \\<Rightarrow> enat\" where\n  \"girth G \\<equiv> INF p: ucycles G. enat (uwalk_length p)\"\n\ndefinition independent_sets :: \"ugraph \\<Rightarrow> uvert set set\" where\n  \"independent_sets Gr \\<equiv> {vs. vs \\<subseteq> uverts Gr \\<and> all_edges vs \\<inter> uedges Gr = {}}\"\n\ndefinition \\<alpha> :: \"ugraph \\<Rightarrow> enat\" where\n   \"\\<alpha> G \\<equiv> SUP vs: independent_sets G. enat (card vs)\"\n\ndefinition vertex_colorings :: \"ugraph \\<Rightarrow> uvert set set set\" where\n  \"vertex_colorings G \\<equiv> {C. \\<Union>C = uverts G \\<and> (\\<forall>c1\\<in>C. \\<forall>c2\\<in>C. c1 \\<noteq> c2 \\<longrightarrow> c1 \\<inter> c2 = {}) \\<and>\n    (\\<forall>c\\<in>C. c \\<noteq> {} \\<and> (\\<forall>u \\<in> c. \\<forall>v \\<in> c. {u,v} \\<notin> uedges G))}\"\n\ntext {* The chromatic number $\\chi$: *}\ndefinition chromatic_number :: \"ugraph \\<Rightarrow> enat\" where\n  \"chromatic_number G \\<equiv> INF c: (vertex_colorings G). enat (card c)\"\n\nlemma independent_sets_mono:\n  \"vs \\<in> independent_sets G \\<Longrightarrow> us \\<subseteq> vs \\<Longrightarrow> us \\<in> independent_sets G\"\n  using Int_mono[OF all_edges_mono, of us vs \"uedges G\" \"uedges G\"]\n  unfolding independent_sets_def by auto\n\nlemma le_\\<alpha>_iff:\n  assumes \"0 < k\"\n  shows \"k \\<le> \\<alpha> Gr \\<longleftrightarrow> k \\<in> card ` independent_sets Gr\" (is \"?L \\<longleftrightarrow> ?R\")\nproof\n  assume ?L\n  then obtain vs where \"vs \\<in> independent_sets Gr\" and \"k \\<le> card vs\"\n    using assms unfolding \\<alpha>_def SUP_def enat_le_Sup_iff by auto\n  moreover\n  then obtain us where \"us \\<subseteq> vs\" and \"k = card us\"\n    using card_Ex_subset by auto\n  ultimately\n  have \"us \\<in> independent_sets Gr\"  by (auto intro: independent_sets_mono)\n  then show ?R using `k = card us` by auto\nqed (auto intro: SUP_upper simp: \\<alpha>_def)\n\nlemma zero_less_\\<alpha>:\n  assumes \"uverts G \\<noteq> {}\"\n  shows \"0 < \\<alpha> G\"\nproof -\n  from assms obtain a where \"a \\<in> uverts G\" by auto\n  then have \"0 < enat (card {a})\" \"{a} \\<in> independent_sets G\"\n    by (auto simp: independent_sets_def all_edges_def)\n  then show ?thesis unfolding \\<alpha>_def less_SUP_iff ..\nqed\n\nlemma \\<alpha>_le_card:\n  assumes \"finite (uverts G)\"\n  shows \"\\<alpha> G \\<le> card(uverts G)\"\nproof -\n  { fix x assume \"x \\<in> independent_sets G\"\n    then have \"x \\<subseteq> uverts G\" by (auto simp: independent_sets_def) }\n  with assms show ?thesis unfolding \\<alpha>_def\n    by (intro SUP_least) (auto intro: card_mono)\nqed\n\nlemma \\<alpha>_fin: \"finite (uverts G) \\<Longrightarrow> \\<alpha> G \\<noteq> \\<infinity>\"\n  using \\<alpha>_le_card[of G] by (cases \"\\<alpha> G\") auto\n\nlemma \\<alpha>_remove_le:\n  shows \"\\<alpha> (G -- u) \\<le> \\<alpha> G\"\nproof -\n  have \"independent_sets (G -- u) \\<subseteq> independent_sets G\" (is \"?L \\<subseteq> ?R\")\n    using all_edges_subset_Pow by (simp add: independent_sets_def remove_vertex_def) blast\n  then show ?thesis unfolding \\<alpha>_def\n    by (rule SUP_subset_mono) simp\nqed\n\ntext {*\n  A lower bound for the chromatic number of a graph can be given in terms of\n  the independence number\n*}\nlemma chromatic_lb:\n  assumes wf_G: \"uwellformed G\"\n    and fin_G: \"finite (uverts G)\"\n    and neG: \"uverts G \\<noteq> {}\"\n  shows \"card (uverts G) / \\<alpha> G \\<le> chromatic_number G\"\nproof -\n  from wf_G have \"(\\<lambda>v. {v}) ` uverts G \\<in> vertex_colorings G\"\n    by (auto simp: vertex_colorings_def uwellformed_def)\n  then have \"chromatic_number G \\<noteq> top\"\n    by (simp add: chromatic_number_def) (auto simp: top_enat_def)\n  then obtain vc where vc_vc: \"vc \\<in> vertex_colorings G\"\n    and vc_size:\"chromatic_number G = card vc\"\n    unfolding chromatic_number_def by (rule enat_in_INF)\n\n  have fin_vc_elems: \"\\<And>c. c \\<in> vc \\<Longrightarrow> finite c\"\n    using vc_vc by (intro finite_subset[OF _ fin_G]) (auto simp: vertex_colorings_def)\n\n  { have \"vc \\<subseteq> Pow (uverts G)\" \"finite (Pow (uverts G))\"\n      using assms vc_vc by (auto simp: vertex_colorings_def)\n    then have \"finite vc\" by (rule finite_subset)\n    with fin_vc_elems have \"(\\<Sum>c \\<in> vc. card c) = card (uverts G)\"\n      using vc_vc unfolding vertex_colorings_def\n      by (simp add: card_Union_disjoint[symmetric]) }\n  note sum_vc_card = this\n\n  have \"\\<And>c. c \\<in> vc \\<Longrightarrow> c \\<in> independent_sets G\"\n    using vc_vc by (auto simp: vertex_colorings_def independent_sets_def all_edges_def)\n  then have \"\\<And>c. c \\<in> vc \\<Longrightarrow> card c \\<le> \\<alpha> G\"\n    using vc_vc fin_vc_elems by (subst le_\\<alpha>_iff) (auto simp add: vertex_colorings_def)\n  then have \"(\\<Sum>c\\<in>vc. card c) \\<le> card vc * \\<alpha> G\"\n    using setsum_bounded[of vc card \"\\<alpha> G\"]\n    by (simp add: of_nat_eq_enat[symmetric] of_nat_setsum)\n  then have \"ereal_of_enat (card (uverts G)) \\<le> ereal_of_enat (\\<alpha> G) * ereal_of_enat (card vc)\"\n    by (simp add: sum_vc_card ereal_of_enat_pushout ac_simps del: ereal_of_enat_simps)\n  with zero_less_\\<alpha>[OF neG] \\<alpha>_fin[OF fin_G] vc_size show ?thesis\n    by (simp add: ereal_divide_le_pos)\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/Girth_Chromatic/Ugraphs.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8670357598021707, "lm_q2_score": 0.8175744695262775, "lm_q1q2_score": 0.7088663013805727}}
{"text": "(*  Title:      HOL/Proofs/Lambda/Commutation.thy\n    Author:     Tobias Nipkow\n    Copyright   1995  TU Muenchen\n*)\n\nsection \\<open>Abstract commutation and confluence notions\\<close>\n\ntheory Commutation\nimports Main\nbegin\n\ndeclare [[syntax_ambiguity_warning = false]]\n\n\nsubsection \\<open>Basic definitions\\<close>\n\ndefinition\n  square :: \"['a => 'a => bool, 'a => 'a => bool, 'a => 'a => bool, 'a => 'a => bool] => bool\" where\n  \"square R S T U =\n    (\\<forall>x y. R x y --> (\\<forall>z. S x z --> (\\<exists>u. T y u \\<and> U z u)))\"\n\ndefinition\n  commute :: \"['a => 'a => bool, 'a => 'a => bool] => bool\" where\n  \"commute R S = square R S S R\"\n\ndefinition\n  diamond :: \"('a => 'a => bool) => bool\" where\n  \"diamond R = commute R R\"\n\ndefinition\n  Church_Rosser :: \"('a => 'a => bool) => bool\" where\n  \"Church_Rosser R =\n    (\\<forall>x y. (sup R (R^--1))^** x y --> (\\<exists>z. R^** x z \\<and> R^** y z))\"\n\nabbreviation\n  confluent :: \"('a => 'a => bool) => bool\" where\n  \"confluent R == diamond (R^**)\"\n\n\nsubsection \\<open>Basic lemmas\\<close>\n\nsubsubsection \\<open>\\<open>square\\<close>\\<close>\n\nlemma square_sym: \"square R S T U ==> square S R U T\"\n  apply (unfold square_def)\n  apply blast\n  done\n\nlemma square_subset:\n    \"[| square R S T U; T \\<le> T' |] ==> square R S T' U\"\n  apply (unfold square_def)\n  apply (blast dest: predicate2D)\n  done\n\nlemma square_reflcl:\n    \"[| square R S T (R^==); S \\<le> T |] ==> square (R^==) S T (R^==)\"\n  apply (unfold square_def)\n  apply (blast dest: predicate2D)\n  done\n\nlemma square_rtrancl:\n    \"square R S S T ==> square (R^**) S S (T^**)\"\n  apply (unfold square_def)\n  apply (intro strip)\n  apply (erule rtranclp_induct)\n   apply blast\n  apply (blast intro: rtranclp.rtrancl_into_rtrancl)\n  done\n\nlemma square_rtrancl_reflcl_commute:\n    \"square R S (S^**) (R^==) ==> commute (R^**) (S^**)\"\n  apply (unfold commute_def)\n  apply (fastforce dest: square_reflcl square_sym [THEN square_rtrancl])\n  done\n\n\nsubsubsection \\<open>\\<open>commute\\<close>\\<close>\n\nlemma commute_sym: \"commute R S ==> commute S R\"\n  apply (unfold commute_def)\n  apply (blast intro: square_sym)\n  done\n\nlemma commute_rtrancl: \"commute R S ==> commute (R^**) (S^**)\"\n  apply (unfold commute_def)\n  apply (blast intro: square_rtrancl square_sym)\n  done\n\nlemma commute_Un:\n    \"[| commute R T; commute S T |] ==> commute (sup R S) T\"\n  apply (unfold commute_def square_def)\n  apply blast\n  done\n\n\nsubsubsection \\<open>\\<open>diamond\\<close>, \\<open>confluence\\<close>, and \\<open>union\\<close>\\<close>\n\nlemma diamond_Un:\n    \"[| diamond R; diamond S; commute R S |] ==> diamond (sup R S)\"\n  apply (unfold diamond_def)\n  apply (blast intro: commute_Un commute_sym) \n  done\n\nlemma diamond_confluent: \"diamond R ==> confluent R\"\n  apply (unfold diamond_def)\n  apply (erule commute_rtrancl)\n  done\n\nlemma square_reflcl_confluent:\n    \"square R R (R^==) (R^==) ==> confluent R\"\n  apply (unfold diamond_def)\n  apply (fast intro: square_rtrancl_reflcl_commute elim: square_subset)\n  done\n\nlemma confluent_Un:\n    \"[| confluent R; confluent S; commute (R^**) (S^**) |] ==> confluent (sup R S)\"\n  apply (rule rtranclp_sup_rtranclp [THEN subst])\n  apply (blast dest: diamond_Un intro: diamond_confluent)\n  done\n\nlemma diamond_to_confluence:\n    \"[| diamond R; T \\<le> R; R \\<le> T^** |] ==> confluent T\"\n  apply (force intro: diamond_confluent\n    dest: rtranclp_subset [symmetric])\n  done\n\n\nsubsection \\<open>Church-Rosser\\<close>\n\nlemma Church_Rosser_confluent: \"Church_Rosser R = confluent R\"\n  apply (unfold square_def commute_def diamond_def Church_Rosser_def)\n  apply (tactic \\<open>safe_tac (put_claset HOL_cs @{context})\\<close>)\n   apply (tactic \\<open>\n     blast_tac (put_claset HOL_cs @{context} addIs\n       [@{thm sup_ge2} RS @{thm rtranclp_mono} RS @{thm predicate2D} RS @{thm rtranclp_trans},\n        @{thm rtranclp_converseI}, @{thm conversepI},\n        @{thm sup_ge1} RS @{thm rtranclp_mono} RS @{thm predicate2D}]) 1\\<close>)\n  apply (erule rtranclp_induct)\n   apply blast\n  apply (blast del: rtranclp.rtrancl_refl intro: rtranclp_trans)\n  done\n\n\nsubsection \\<open>Newman's lemma\\<close>\n\ntext \\<open>Proof by Stefan Berghofer\\<close>\n\ntheorem newman:\n  assumes wf: \"wfP (R\\<inverse>\\<inverse>)\"\n  and lc: \"\\<And>a b c. R a b \\<Longrightarrow> R a c \\<Longrightarrow>\n    \\<exists>d. R\\<^sup>*\\<^sup>* b d \\<and> R\\<^sup>*\\<^sup>* c d\"\n  shows \"\\<And>b c. R\\<^sup>*\\<^sup>* a b \\<Longrightarrow> R\\<^sup>*\\<^sup>* a c \\<Longrightarrow>\n    \\<exists>d. R\\<^sup>*\\<^sup>* b d \\<and> R\\<^sup>*\\<^sup>* c d\"\n  using wf\nproof induct\n  case (less x b c)\n  have xc: \"R\\<^sup>*\\<^sup>* x c\" by fact\n  have xb: \"R\\<^sup>*\\<^sup>* x b\" by fact thus ?case\n  proof (rule converse_rtranclpE)\n    assume \"x = b\"\n    with xc have \"R\\<^sup>*\\<^sup>* b c\" by simp\n    thus ?thesis by iprover\n  next\n    fix y\n    assume xy: \"R x y\"\n    assume yb: \"R\\<^sup>*\\<^sup>* y b\"\n    from xc show ?thesis\n    proof (rule converse_rtranclpE)\n      assume \"x = c\"\n      with xb have \"R\\<^sup>*\\<^sup>* c b\" by simp\n      thus ?thesis by iprover\n    next\n      fix y'\n      assume y'c: \"R\\<^sup>*\\<^sup>* y' c\"\n      assume xy': \"R x y'\"\n      with xy have \"\\<exists>u. R\\<^sup>*\\<^sup>* y u \\<and> R\\<^sup>*\\<^sup>* y' u\" by (rule lc)\n      then obtain u where yu: \"R\\<^sup>*\\<^sup>* y u\" and y'u: \"R\\<^sup>*\\<^sup>* y' u\" by iprover\n      from xy have \"R\\<inverse>\\<inverse> y x\" ..\n      from this and yb yu have \"\\<exists>d. R\\<^sup>*\\<^sup>* b d \\<and> R\\<^sup>*\\<^sup>* u d\" by (rule less)\n      then obtain v where bv: \"R\\<^sup>*\\<^sup>* b v\" and uv: \"R\\<^sup>*\\<^sup>* u v\" by iprover\n      from xy' have \"R\\<inverse>\\<inverse> y' x\" ..\n      moreover from y'u and uv have \"R\\<^sup>*\\<^sup>* y' v\" by (rule rtranclp_trans)\n      moreover note y'c\n      ultimately have \"\\<exists>d. R\\<^sup>*\\<^sup>* v d \\<and> R\\<^sup>*\\<^sup>* c d\" by (rule less)\n      then obtain w where vw: \"R\\<^sup>*\\<^sup>* v w\" and cw: \"R\\<^sup>*\\<^sup>* c w\" by iprover\n      from bv vw have \"R\\<^sup>*\\<^sup>* b w\" by (rule rtranclp_trans)\n      with cw show ?thesis by iprover\n    qed\n  qed\nqed\n\ntext \\<open>\n  Alternative version.  Partly automated by Tobias\n  Nipkow. Takes 2 minutes (2002).\n\n  This is the maximal amount of automation possible using \\<open>blast\\<close>.\n\\<close>\n\ntheorem newman':\n  assumes wf: \"wfP (R\\<inverse>\\<inverse>)\"\n  and lc: \"\\<And>a b c. R a b \\<Longrightarrow> R a c \\<Longrightarrow>\n    \\<exists>d. R\\<^sup>*\\<^sup>* b d \\<and> R\\<^sup>*\\<^sup>* c d\"\n  shows \"\\<And>b c. R\\<^sup>*\\<^sup>* a b \\<Longrightarrow> R\\<^sup>*\\<^sup>* a c \\<Longrightarrow>\n    \\<exists>d. R\\<^sup>*\\<^sup>* b d \\<and> R\\<^sup>*\\<^sup>* c d\"\n  using wf\nproof induct\n  case (less x b c)\n  note IH = \\<open>\\<And>y b c. \\<lbrakk>R\\<inverse>\\<inverse> y x; R\\<^sup>*\\<^sup>* y b; R\\<^sup>*\\<^sup>* y c\\<rbrakk>\n                     \\<Longrightarrow> \\<exists>d. R\\<^sup>*\\<^sup>* b d \\<and> R\\<^sup>*\\<^sup>* c d\\<close>\n  have xc: \"R\\<^sup>*\\<^sup>* x c\" by fact\n  have xb: \"R\\<^sup>*\\<^sup>* x b\" by fact\n  thus ?case\n  proof (rule converse_rtranclpE)\n    assume \"x = b\"\n    with xc have \"R\\<^sup>*\\<^sup>* b c\" by simp\n    thus ?thesis by iprover\n  next\n    fix y\n    assume xy: \"R x y\"\n    assume yb: \"R\\<^sup>*\\<^sup>* y b\"\n    from xc show ?thesis\n    proof (rule converse_rtranclpE)\n      assume \"x = c\"\n      with xb have \"R\\<^sup>*\\<^sup>* c b\" by simp\n      thus ?thesis by iprover\n    next\n      fix y'\n      assume y'c: \"R\\<^sup>*\\<^sup>* y' c\"\n      assume xy': \"R x y'\"\n      with xy obtain u where u: \"R\\<^sup>*\\<^sup>* y u\" \"R\\<^sup>*\\<^sup>* y' u\"\n        by (blast dest: lc)\n      from yb u y'c show ?thesis\n        by (blast del: rtranclp.rtrancl_refl\n            intro: rtranclp_trans\n            dest: IH [OF conversepI, OF xy] IH [OF conversepI, OF xy'])\n    qed\n  qed\nqed\n\ntext \\<open>\n  Using the coherent logic prover, the proof of the induction step\n  is completely automatic.\n\\<close>\n\nlemma eq_imp_rtranclp: \"x = y \\<Longrightarrow> r\\<^sup>*\\<^sup>* x y\"\n  by simp\n\ntheorem newman'':\n  assumes wf: \"wfP (R\\<inverse>\\<inverse>)\"\n  and lc: \"\\<And>a b c. R a b \\<Longrightarrow> R a c \\<Longrightarrow>\n    \\<exists>d. R\\<^sup>*\\<^sup>* b d \\<and> R\\<^sup>*\\<^sup>* c d\"\n  shows \"\\<And>b c. R\\<^sup>*\\<^sup>* a b \\<Longrightarrow> R\\<^sup>*\\<^sup>* a c \\<Longrightarrow>\n    \\<exists>d. R\\<^sup>*\\<^sup>* b d \\<and> R\\<^sup>*\\<^sup>* c d\"\n  using wf\nproof induct\n  case (less x b c)\n  note IH = \\<open>\\<And>y b c. \\<lbrakk>R\\<inverse>\\<inverse> y x; R\\<^sup>*\\<^sup>* y b; R\\<^sup>*\\<^sup>* y c\\<rbrakk>\n                     \\<Longrightarrow> \\<exists>d. R\\<^sup>*\\<^sup>* b d \\<and> R\\<^sup>*\\<^sup>* c d\\<close>\n  show ?case\n    by (coherent\n      \\<open>R\\<^sup>*\\<^sup>* x c\\<close> \\<open>R\\<^sup>*\\<^sup>* x b\\<close>\n      refl [where 'a='a] sym\n      eq_imp_rtranclp\n      r_into_rtranclp [of R]\n      rtranclp_trans\n      lc IH [OF conversepI]\n      converse_rtranclpE)\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/Proofs/Lambda/Commutation.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.867035752930664, "lm_q2_score": 0.817574471748733, "lm_q1q2_score": 0.7088662976895527}}
{"text": "theory Classes\n  imports Main HOL.Real\nbegin\n\nsubsection \\<open>definition of classes\\<close>\nclass additive =\n  fixes add :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a\" (infixl \"\\<oplus>\" 70)\n  assumes assoc : \"(x \\<oplus> y) \\<oplus> z = x \\<oplus> (y \\<oplus> z)\"\n\nprint_locale additive\n\ninstantiation int :: additive\nbegin\n\ndefinition add_int_def : \"x \\<oplus> y = (x::int) + y\"\n\ninstance proof\n  fix x y z :: int\n  show \"x \\<oplus> y \\<oplus> z = x \\<oplus> (y \\<oplus> z)\" unfolding add_int_def by simp\nqed\n\nend\n\nvalue \"(2::int) \\<oplus> 12\"\n\ninstantiation bool :: additive\nbegin\ndefinition add_bool_def : \"x \\<oplus> y = ((x::bool) \\<or> y)\"\n\ninstance proof\n  fix x y z :: bool\n  show \"x \\<oplus> y \\<oplus> z = x \\<oplus> (y \\<oplus> z)\" unfolding add_bool_def by simp\nqed\n\nend\n\nvalue \"True \\<oplus> False\"\n\ndatatype Number = Natural nat | Integer int | Real real\n\ninstantiation Number :: additive\nbegin\n\ndefinition addnum :: \"Number \\<Rightarrow> Number \\<Rightarrow> Number\"\n  where \"addnum x y \\<equiv> Real ((case x of Real r \\<Rightarrow> r | Natural n \\<Rightarrow> of_nat n | Integer i \\<Rightarrow> of_int i)\n                           + (case y of Real r \\<Rightarrow> r | Natural n \\<Rightarrow> of_nat n | Integer i \\<Rightarrow> of_int i))\"\n\ndefinition add_Number_def : \"x \\<oplus> y = addnum x y\"\n\ninstance proof\n  fix x y z :: Number\n  show \"x \\<oplus> y \\<oplus> z = x \\<oplus> (y \\<oplus> z)\"\n    unfolding add_Number_def addnum_def\n    by auto\nqed\n\nend\n\nvalue \"(Real 2.0) \\<oplus> (Integer 3)\"\n\ninterpretation list_add : additive append\nproof \n  fix x y z :: \"'a list\"\n  show \"(x @ y) @ z = x @ y @ z\" by auto\nqed\n\nsubsection \\<open>parametric polymorphism and ad-hoc polymorphism (overloading)\\<close>\n\n\nsubsection \\<open>semigroup, monoid\\<close>\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\nprint_locale semigroup\n\ninstantiation int :: semigroup\nbegin\ndefinition multi_int_def : \"i \\<otimes> j = i + (j::int)\"\n\ninstance proof\n  fix x y z :: int have \"(x + y) + z = x + (y + z)\" by simp\n  then show \"x \\<otimes> y \\<otimes> z = x \\<otimes> (y \\<otimes> z)\" unfolding multi_int_def by simp\nqed\nend\n\n\nthm multi_int_def\n\ninstantiation nat :: semigroup\nbegin\ndefinition multi_nat_def : \"i \\<otimes> j = i + (j::nat)\"\n\ninstance proof\n  fix x y z :: nat have \"(x + y) + z = x + (y + z)\" by simp\n  then show \"x \\<otimes> y \\<otimes> z = x \\<otimes> (y \\<otimes> z)\" unfolding multi_nat_def by simp\nqed\nend\n\ninstantiation prod :: (semigroup, semigroup) semigroup\nbegin\ndefinition\nmult_prod_def : \"p1 \\<otimes> p2 = (fst p1 \\<otimes> fst p2, snd p1 \\<otimes> snd p2)\"\n\ninstance proof\n  fix p1 p2 p3 :: \"('a :: semigroup) \\<times> ('b :: semigroup)\"\n  show \"(p1 \\<otimes> p2) \\<otimes> p3 = p1 \\<otimes> (p2 \\<otimes> p3)\"\n  unfolding mult_prod_def by (simp add: assoc)\nqed\nend\n\n\nclass monoidl = semigroup + \n  fixes neutral :: 'a (\"\\<one>\")\n  assumes neutl : \"\\<one> \\<otimes> x = x\"\n\nprint_locale semigroup\nprint_locale monoidl\nthm monoidl_axioms\nthm semigroup_axioms\n\nsubclass (in monoidl) semigroup \n  using semigroup_axioms by simp\n\ninstantiation nat and int :: monoidl\nbegin\n\ndefinition neutral_nat_def : \"\\<one> = (0::nat)\"\n\ndefinition neutral_int_def : \"\\<one> = (0::int)\"\n\ninstance proof\n  fix n::nat\n  show \"\\<one> \\<otimes> n = n\" unfolding neutral_nat_def multi_nat_def by simp\nnext\n  fix n::int\n  show \"\\<one> \\<otimes> n = n\" unfolding neutral_int_def multi_int_def by simp\nqed\nend\n\ninstantiation prod :: (monoidl,monoidl) monoidl\nbegin\n\ndefinition neutral_prod_def: \"\\<one> = (\\<one>,\\<one>)\"\n\ninstance proof\n  fix p :: \"'a :: monoidl \\<times> 'b :: monoidl\"\n  show \"\\<one> \\<otimes> p = p\"\n    unfolding neutral_prod_def mult_prod_def by (simp add:neutl)\nqed\nend\n\n\nclass monoid = monoidl + \n  assumes neutr: \"x \\<otimes> \\<one> = x\"\n\ninstantiation int and nat :: monoid\nbegin\n\ninstance proof\n  fix x :: int\n  show \"x \\<otimes> \\<one> = x\"\n    by (simp add: multi_int_def neutral_int_def)\nnext\n  fix x :: nat\n  show \"x \\<otimes> \\<one> = x\"\n    by (simp add: multi_nat_def neutral_nat_def)\nqed   \nend\n\ninstantiation prod :: (monoid, monoid) monoid\nbegin\ninstance proof\n  fix p :: \"('a :: monoid) \\<times> ('b :: monoid)\"\n  show \"p \\<otimes> \\<one> = p\"\n    by (simp add: mult_prod_def neutr neutral_prod_def)\nqed\n\nend\n\nclass group = monoidl + \n  fixes inverse :: \"'a \\<Rightarrow> 'a\" (\"\\<ominus>_\" [1000] 900)\n  assumes invl : \"\\<ominus>x \\<otimes> x = \\<one>\"\n\nlemma (in group) left_cancel: \"x \\<otimes> y = x \\<otimes> z \\<longleftrightarrow> y = z\"\nproof\nassume \"x \\<otimes> y = x \\<otimes> z\"\nthen have \"\\<ominus>x \\<otimes> (x \\<otimes> y) = \\<ominus>x \\<otimes> (x \\<otimes> z)\" by simp\nthen have \"(\\<ominus>x \\<otimes> x) \\<otimes> y = (\\<ominus>x \\<otimes> x) \\<otimes> z\" using assoc by simp\nthen show \"y = z\" using neutl and invl by simp\nnext\nassume \"y = z\"\nthen show \"x \\<otimes> y = x \\<otimes> z\" by simp\nqed\n\nsubclass (in group) monoidl\n  using monoidl_axioms by auto\n\nsubclass (in group) monoid\nproof\n  fix x\n  from invl have \"\\<ominus>x \\<otimes> x = \\<one>\" by simp\n  with assoc [symmetric] neutl invl have \"\\<ominus>x \\<otimes> (x \\<otimes> \\<one>) = \\<ominus>x \\<otimes> x\" by simp\n  with left_cancel show \"x \\<otimes> \\<one> = x\" by simp\nqed\n\n\ninstantiation int :: group\nbegin\ndefinition inverse_int_def : \"\\<ominus>x = - (x::int)\"\n\ninstance proof\n  fix x :: int\n  show \"\\<ominus>x \\<otimes> x = \\<one>\"\n    by (simp add: inverse_int_def multi_int_def neutral_int_def) \nqed\nend\n\n\nlemma \"(x::int) \\<otimes> y \\<otimes> z = (x \\<otimes> y) \\<otimes> z\"\n  by simp\n\n\ninterpretation list_monoid: monoid append \"[]\"\nproof \n  fix x y z :: \"'a list\"\n  show \"(x @ y) @ z = x @ y @ z\" by auto\nnext\n  fix x :: \"'a list\"\n  show \"[] @ x = x\" by auto\nnext\n  fix x :: \"'a list\"\n  show \"x @ [] = x\" by auto\nqed\n\nlemma \"(xs @ ys) @ zs = xs @ (ys @ zs)\"\n  using list_monoid.assoc by auto\n\ninterpretation fun_monoid: monoid comp id\nproof\n  fix x y z :: \"'a \\<Rightarrow> 'a\"\n  show \"x \\<circ> y \\<circ> z = x \\<circ> (y \\<circ> z)\" by auto\nnext\n  fix x :: \"'a \\<Rightarrow> 'a\"\n  show \"id \\<circ> x = x\" by auto\nnext\n  fix x :: \"'a \\<Rightarrow> 'a\"\n  show \"x \\<circ> id = x\" by auto\nqed\n\nlemma \"(f \\<circ> g) \\<circ> h = f \\<circ> (g \\<circ> h)\"\n  using fun_monoid.assoc by auto\n\n\nclass eqclass =\n  fixes eq :: \"'a \\<Rightarrow> 'a \\<Rightarrow> bool\" (infixl \"\\<asymp>\" 70)\n  assumes refl : \"a \\<asymp> a\"\n    and   sym : \"a \\<asymp> b \\<longleftrightarrow> b \\<asymp> a\"\n    and   trans : \"a \\<asymp> b \\<and> b \\<asymp> c \\<longrightarrow> a \\<asymp> c\"\n\ninstantiation nat :: eqclass\nbegin\n \ndefinition eq_nat_def : \"x \\<asymp> y = (x = (y :: nat))\"\n\ninstance proof\n  fix a :: nat\n  show \"a \\<asymp> a\" using eq_nat_def by simp\nnext\n  fix a b :: nat\n  show \"a \\<asymp> b = b \\<asymp> a\" using eq_nat_def by auto\nnext\n  fix a b c :: nat\n  show \"a \\<asymp> b \\<and> b \\<asymp> c \\<longrightarrow> a \\<asymp> c\" using eq_nat_def by auto\nqed\n\nend\n\ninstantiation int :: eqclass\nbegin\n \ndefinition eq_int_def : \"x \\<asymp> y = (x = (y :: int))\"\n\ninstance proof\n  fix a :: int\n  show \"a \\<asymp> a\" using eq_int_def by simp\nnext\n  fix a b :: int\n  show \"a \\<asymp> b = b \\<asymp> a\" using eq_int_def by auto\nnext\n  fix a b c :: int\n  show \"a \\<asymp> b \\<and> b \\<asymp> c \\<longrightarrow> a \\<asymp> c\" using eq_int_def by auto\nqed\n\nend\n\ninstantiation prod :: (eqclass, eqclass) eqclass\nbegin\n \ndefinition eq_prod_def : \"x \\<asymp> y = (fst x = fst y \\<and> snd x = snd y)\"\n\ninstance proof\n  fix p :: \"'a :: eqclass \\<times> 'b :: eqclass\"\n  show \"p \\<asymp> p\" using eq_prod_def by simp\nnext\n  fix a b :: \"'a :: eqclass \\<times> 'b :: eqclass\"\n  show \"a \\<asymp> b = b \\<asymp> a\" using eq_prod_def by auto\nnext\n  fix a b c :: \"'a :: eqclass \\<times> 'b :: eqclass\"\n  show \"a \\<asymp> b \\<and> b \\<asymp> c \\<longrightarrow> a \\<asymp> c\" using eq_prod_def by auto\nqed\n\nend\n\nlemma \"((1::nat) + 2) \\<asymp> 3\"\n  by (simp add: eq_nat_def) \n\nlemma \"((1::int) + 2) \\<asymp> 3\"\n  by (simp add: eq_int_def) \n\nlemma \"(a::int) \\<asymp> c \\<and> (b::nat) \\<asymp> d \\<Longrightarrow> (a,b) \\<asymp> (c,d)\"\n  unfolding eq_prod_def eq_int_def eq_nat_def by simp\n\ninstantiation list :: (type) eqclass\nbegin\n\ndefinition eq_list_def : \"xs \\<asymp> ys = ((xs::'a list) = ys)\"\n\ninstance proof\n  fix a :: \"'a list\"\n  show \"a \\<asymp> a\" by (simp add: eq_list_def)\nnext\n  fix a b :: \"'a list\"\n  show \"a \\<asymp> b = b \\<asymp> a\" using eq_list_def by auto\nnext\n  fix a b c :: \"'a list\"\n  show \"a \\<asymp> b \\<and> b \\<asymp> c \\<longrightarrow> a \\<asymp> c\" using eq_list_def by auto\nqed\n\nend\n\n\nend\n", "meta": {"author": "LVPGroup", "repo": "fpp", "sha": "7e18377ea2c553bf6e57412727a4f06832d93577", "save_path": "github-repos/isabelle/LVPGroup-fpp", "path": "github-repos/isabelle/LVPGroup-fpp/fpp-7e18377ea2c553bf6e57412727a4f06832d93577/2_functionalprog/Classes.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278757303677, "lm_q2_score": 0.8031738057795402, "lm_q1q2_score": 0.7087429552763146}}
{"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.*)\n  theory TIP_prop_16\n  imports \"../../Test_Base\"\nbegin\n\ndatatype Nat = Z | S \"Nat\"\n\nfun even :: \"Nat => bool\" where\n\"even (Z) = True\"\n| \"even (S (Z)) = False\"\n| \"even (S (S z)) = even z\"\n\nfun t2 :: \"Nat => Nat => Nat\" where\n\"t2 (Z) y = y\"\n| \"t2 (S z) y = S (t2 z y)\"\n\nlemma t2_succ: \"t2 n (S m) = t2 (S n) m\"\n  by(induct n, auto)\n\ntheorem property0 :\n  \"even (t2 x x)\"\n  apply(induct x rule: even.induct , auto)\n  apply(simp add:t2_succ)\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_16.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278540866547, "lm_q2_score": 0.8031737869342624, "lm_q1q2_score": 0.7087429212630533}}
{"text": "section \\<open>Algebra-only Theorems\\<close>\n\ntext \\<open>This section verifies the linear algebraic counter-parts of the graph-theoretic theorems\nabout Random walks. The graph-theoretic results are then derived in Section~\\ref{sec:random_walks}.\\<close>\n\ntheory Expander_Graphs_Algebra\n  imports \n    \"HOL-Library.Monad_Syntax\"\n    Expander_Graphs_TTS\nbegin\n\nlemma pythagoras: \n  fixes v w :: \"'a::real_inner\"\n  assumes \"v \\<bullet> w  = 0\"\n  shows \"norm (v+w)^2 = norm v^2 + norm w^2\"  \n  using assms by (simp add:power2_norm_eq_inner algebra_simps inner_commute)\n\ndefinition diag :: \"('a :: zero)^'n \\<Rightarrow> 'a^'n^'n\"\n  where \"diag v = (\\<chi> i j. if i = j then (v $ i) else 0)\"\n\ndefinition ind_vec :: \"'n set \\<Rightarrow> real^'n\"\n  where \"ind_vec S = (\\<chi> i. of_bool( i \\<in> S))\"\n\nlemma diag_mult_eq: \"diag x ** diag y = diag (x * y)\"\n  unfolding diag_def \n  by (vector matrix_matrix_mult_def) \n   (auto simp add:if_distrib if_distribR sum.If_cases)\n\nlemma diag_vec_mult_eq: \"diag x *v y = x * y\"\n  unfolding diag_def matrix_vector_mult_def \n  by (simp add:if_distrib if_distribR sum.If_cases times_vec_def)\n\ndefinition matrix_norm_bound :: \"real^'n^'m \\<Rightarrow> real \\<Rightarrow> bool\"\n  where \"matrix_norm_bound A l = (\\<forall>x. norm (A *v x) \\<le> l * norm x)\"\n\nlemma  matrix_norm_boundI:\n  assumes \"\\<And>x. norm (A *v x) \\<le> l * norm x\"\n  shows \"matrix_norm_bound A l\"\n  using assms unfolding matrix_norm_bound_def by simp\n\nlemma matrix_norm_boundD:\n  assumes \"matrix_norm_bound A l\"\n  shows \"norm (A *v x) \\<le> l * norm x\"\n  using assms unfolding matrix_norm_bound_def by simp\n\nlemma matrix_norm_bound_nonneg:\n  fixes A :: \"real^'n^'m\"\n  assumes \"matrix_norm_bound A l\"\n  shows \"l \\<ge> 0\" \nproof -\n  have \"0 \\<le> norm (A *v 1)\" by simp\n  also have \"... \\<le> l * norm (1::real^'n)\" \n    using assms(1) unfolding matrix_norm_bound_def by simp\n  finally have \"0 \\<le> l  * norm (1::real^'n)\"\n    by simp\n  moreover have \"norm (1::real^'n) > 0\"\n    by simp\n  ultimately show ?thesis \n    by (simp add: zero_le_mult_iff)\nqed\n\nlemma  matrix_norm_bound_0: \n  assumes \"matrix_norm_bound A 0\" \n  shows \"A = (0::real^'n^'m)\"\nproof (intro iffD2[OF matrix_eq] allI)\n  fix x :: \"real^'n\"\n  have \"norm (A *v x) = 0\"\n    using assms unfolding matrix_norm_bound_def by simp\n  thus \"A *v x = 0 *v x\"\n    by simp\nqed\n\nlemma matrix_norm_bound_diag:\n  fixes x :: \"real^'n\"\n  assumes \"\\<And>i. \\<bar>x $ i\\<bar> \\<le> l\"\n  shows \"matrix_norm_bound (diag x) l\"\nproof (rule matrix_norm_boundI)\n  fix y :: \"real^'n\"\n\n  have l_ge_0: \"l \\<ge> 0\" using assms by fastforce\n\n  have a: \"\\<bar>x $ i * v\\<bar> \\<le> \\<bar>l * v\\<bar>\" for v i\n    using l_ge_0 assms by (simp add:abs_mult mult_right_mono)\n\n  have \"norm (diag x *v y) = sqrt (\\<Sum>i \\<in> UNIV. (x $ i * y $ i)^2)\"\n    unfolding matrix_vector_mult_def diag_def norm_vec_def L2_set_def\n    by (auto simp add:if_distrib if_distribR sum.If_cases)\n  also have \"... \\<le> sqrt (\\<Sum>i \\<in> UNIV. (l * y $ i)^2)\"\n    by (intro real_sqrt_le_mono sum_mono iffD1[OF abs_le_square_iff] a)\n  also have \"... = l * norm y\"\n    using l_ge_0 by (simp add:norm_vec_def L2_set_def algebra_simps \n        sum_distrib_left[symmetric] real_sqrt_mult)\n  finally show \"norm (diag x *v y) \\<le> l * norm y\" by simp\nqed\n\nlemma vector_scaleR_matrix_ac_2: \"b *\\<^sub>R (A::real^'n^'m) *v x = b *\\<^sub>R (A *v x)\" \n  unfolding vector_transpose_matrix[symmetric]  transpose_scalar\n  by (intro vector_scaleR_matrix_ac)\n\nlemma  matrix_norm_bound_scale: \n  assumes \"matrix_norm_bound A l\"\n  shows \"matrix_norm_bound (b *\\<^sub>R A) (\\<bar>b\\<bar> * l)\"\nproof (intro matrix_norm_boundI)\n  fix x\n  have \"norm (b *\\<^sub>R A *v x) = norm (b *\\<^sub>R (A *v x))\" \n    by (metis transpose_scalar vector_scaleR_matrix_ac vector_transpose_matrix)\n  also have \"... = \\<bar>b\\<bar> * norm (A *v x)\" \n    by simp\n  also have \"... \\<le> \\<bar>b\\<bar> * (l * norm x)\"\n    using assms matrix_norm_bound_def by (intro mult_left_mono) auto\n  also have \"... \\<le> (\\<bar>b\\<bar> * l) * norm x\" by simp\n  finally show \"norm (b *\\<^sub>R A *v x) \\<le> (\\<bar>b\\<bar> * l) * norm x\" by simp\nqed\n\ndefinition nonneg_mat :: \"real^'n^'m \\<Rightarrow> bool\"\n  where \"nonneg_mat A = (\\<forall>i j. A $ i $ j \\<ge> 0)\"\n\nlemma nonneg_mat_1:\n  shows \"nonneg_mat (mat 1)\"\n  unfolding nonneg_mat_def mat_def by auto\n\nlemma nonneg_mat_prod:\n  assumes \"nonneg_mat A\" \"nonneg_mat B\"\n  shows \"nonneg_mat (A ** B)\"\n  using assms unfolding nonneg_mat_def matrix_matrix_mult_def \n  by (auto intro:sum_nonneg)\n\nlemma nonneg_mat_transpose:\n  \"nonneg_mat (transpose A) = nonneg_mat A\"\n  unfolding nonneg_mat_def transpose_def \n  by auto\n\ndefinition spec_bound :: \"real^'n^'n \\<Rightarrow> real \\<Rightarrow> bool\"\n  where \"spec_bound M l = (l \\<ge> 0 \\<and> (\\<forall>v. v \\<bullet> 1 = 0 \\<longrightarrow> norm (M *v v) \\<le> l * norm v))\"\n\nlemma spec_boundD1:\n  assumes \"spec_bound M l\"\n  shows \"0 \\<le> l\" \n  using assms unfolding spec_bound_def by simp\n\nlemma spec_boundD2:\n  assumes \"spec_bound M l\"\n  assumes \"v \\<bullet> 1 = 0 \"\n  shows \"norm (M *v v) \\<le> l * norm v\" \n  using assms unfolding spec_bound_def by simp\n\nlemma spec_bound_mono:\n  assumes \"spec_bound M \\<alpha>\" \"\\<alpha> \\<le> \\<beta>\"\n  shows \"spec_bound M \\<beta>\"\nproof -\n  have \"norm (M *v v) \\<le> \\<beta> * norm v\" if \"inner v 1 = 0\"  for v\n  proof -\n    have \"norm (M *v v) \\<le> \\<alpha> * norm v\" \n      by (intro spec_boundD2[OF assms(1)] that)\n    also have \"... \\<le> \\<beta> * norm v\"\n      by (intro mult_right_mono assms(2)) auto\n    finally show ?thesis by simp\n  qed\n  moreover have \"\\<beta> \\<ge> 0\"\n    using assms(2) spec_boundD1[OF assms(1)] by simp\n  ultimately show ?thesis \n    unfolding spec_bound_def by simp\nqed\n\ndefinition markov :: \"real^'n^'n \\<Rightarrow> bool\"\n  where \"markov M = (nonneg_mat M \\<and> M *v 1  = 1 \\<and> 1 v* M = 1)\"\n\nlemma markov_symI:\n  assumes \"nonneg_mat A\" \"transpose A = A\" \"A *v 1 = 1\"\n  shows \"markov A\"\nproof -\n  have \"1 v* A = transpose A *v 1\"\n    unfolding vector_transpose_matrix[symmetric] by simp\n  also have \"... = 1\" unfolding assms(2,3) by simp\n  finally have \"1 v* A = 1\" by simp\n  thus ?thesis\n    unfolding markov_def using assms by auto\nqed\n\nlemma markov_apply:\n  assumes \"markov M\"\n  shows \"M *v 1 = 1\" \"1 v* M = 1\"\n  using assms unfolding markov_def by auto\n\nlemma markov_transpose:\n  \"markov A = markov (transpose A)\"\n  unfolding markov_def nonneg_mat_transpose by auto\nfun matrix_pow where \n  \"matrix_pow M 0 = mat 1\" |\n  \"matrix_pow M (Suc n) = M ** (matrix_pow M n)\"\n\nlemma markov_orth_inv: \n  assumes \"markov A\"\n  shows \"inner (A *v x) 1 = inner x 1\"\nproof -\n  have \"inner (A *v x) 1 = inner x (1 v* A)\"\n    using dot_lmul_matrix inner_commute by metis\n  also have \"... = inner x 1\"\n    using markov_apply[OF assms(1)] by simp\n  finally show ?thesis by simp\nqed\n\nlemma markov_id:\n  \"markov (mat 1)\"\n  unfolding markov_def using nonneg_mat_1 by simp\n\nlemma markov_mult:\n  assumes \"markov A\" \"markov B\"\n  shows \"markov (A ** B)\"\nproof -\n  have \"nonneg_mat (A ** B)\"\n    using assms unfolding markov_def by (intro nonneg_mat_prod) auto\n  moreover have \"(A ** B) *v 1 = 1\" \n    using assms unfolding markov_def\n    unfolding matrix_vector_mul_assoc[symmetric] by simp\n  moreover have \"1 v* (A ** B) = 1\" \n    using assms unfolding markov_def\n    unfolding vector_matrix_mul_assoc[symmetric] by simp\n  ultimately show ?thesis\n    unfolding markov_def by simp\nqed\n\nlemma markov_matrix_pow:\n  assumes \"markov A\"\n  shows \"markov (matrix_pow A k)\"\n  using markov_id assms markov_mult\n  by (induction k, auto)\n\nlemma spec_bound_prod: \n  assumes \"markov A\" \"markov B\"\n  assumes \"spec_bound A la\" \"spec_bound B lb\"\n  shows \"spec_bound (A ** B) (la*lb)\"\nproof -\n  have la_ge_0: \"la \\<ge> 0\" using spec_boundD1[OF assms(3)] by simp\n\n  have \"norm ((A ** B) *v x) \\<le> (la * lb) * norm x\" if \"inner x 1 = 0\" for x\n  proof -\n    have \"norm ((A ** B) *v x) = norm (A *v (B *v x))\"\n      by (simp add:matrix_vector_mul_assoc)\n    also have \"... \\<le> la * norm (B *v x)\"\n      by (intro spec_boundD2[OF assms(3)]) (simp add:markov_orth_inv that assms(2))\n    also have \"... \\<le> la * (lb * norm x)\" \n      by (intro spec_boundD2[OF assms(4)] mult_left_mono that la_ge_0)\n    finally show ?thesis by simp\n  qed\n  moreover have \"la * lb \\<ge> 0\"\n    using la_ge_0 spec_boundD1[OF assms(4)] by simp\n  ultimately show ?thesis\n    using spec_bound_def by auto\nqed\n\nlemma spec_bound_pow: \n  assumes \"markov A\"\n  assumes \"spec_bound A l\"\n  shows \"spec_bound (matrix_pow A k) (l^k)\"\nproof (induction k)\n  case 0\n  then show ?case unfolding spec_bound_def by simp\nnext\n  case (Suc k)\n  have \"spec_bound (A ** matrix_pow A k) (l * l ^ k)\"\n    by (intro spec_bound_prod assms Suc markov_matrix_pow)\n  thus ?case by simp\nqed\n\nfun intersperse :: \"'a \\<Rightarrow> 'a list \\<Rightarrow> 'a list\"\n  where \n    \"intersperse x [] = []\" |\n    \"intersperse x (y#[]) = y#[]\" |\n    \"intersperse x (y#z#zs) = y#x#intersperse x (z#zs)\"\n\nlemma intersperse_snoc:\n  assumes \"xs \\<noteq> []\"\n  shows \"intersperse z (xs@[y]) = intersperse z xs@[z,y]\"\n  using assms\nproof (induction xs rule:list_nonempty_induct)\n  case (single x)\n  then show ?case by simp\nnext\n  case (cons x xs)\n  then obtain xsh xst where t:\"xs = xsh#xst\"\n    by (metis neq_Nil_conv)\n  have \"intersperse z ((x # xs) @ [y]) = x#z#intersperse z (xs@[y])\"\n    unfolding t by simp\n  also have \"... = x#z#intersperse z xs@[z,y]\"\n    using cons by simp\n  also have \"... = intersperse z (x#xs)@[z,y]\"\n    unfolding t by simp\n  finally show ?case by simp\nqed\n\nlemma foldl_intersperse:\n  assumes \"xs \\<noteq> []\"\n  shows \"foldl f a ((intersperse x xs)@[x]) = foldl (\\<lambda>y z. f (f y z) x) a xs\"\n  using assms by (induction xs rule:rev_nonempty_induct) (auto simp add:intersperse_snoc)\n\nlemma foldl_intersperse_2:\n  shows \"foldl f a (intersperse y (x#xs)) = foldl (\\<lambda>x z. f (f x y) z) (f a x) xs\"\nproof (induction xs rule:rev_induct)\n  case Nil\n  then show ?case by simp\nnext\n  case (snoc xst xs)\n  have \"foldl f a (intersperse y ((x # xs) @ [xst])) = foldl (\\<lambda>x. f (f x y)) (f a x) (xs @ [xst])\" \n    by (subst intersperse_snoc, auto simp add:snoc)\n  then show ?case  by simp\nqed\n\n\ncontext regular_graph_tts\nbegin\n\ndefinition stat :: \"real^'n\"\n  where \"stat = (1 / real CARD('n)) *\\<^sub>R 1\"\n\ndefinition J :: \"('c :: field)^'n^'n\"\n  where \"J = (\\<chi> i j. of_nat 1 / of_nat CARD('n))\"\n\nlemma inner_1_1: \"1 \\<bullet> (1::real^'n) = CARD('n)\"\n  unfolding inner_vec_def by simp\n\ndefinition proj_unit :: \"real^'n \\<Rightarrow> real^'n\"\n  where \"proj_unit v = (1 \\<bullet> v) *\\<^sub>R stat\"\n\ndefinition proj_rem :: \"real^'n \\<Rightarrow> real^'n\" \n  where \"proj_rem v = v - proj_unit v\"\n\nlemma proj_rem_orth: \"1 \\<bullet> (proj_rem v) = 0\"\n  unfolding proj_rem_def proj_unit_def inner_diff_right stat_def\n  by (simp add:inner_1_1)\n\nlemma split_vec: \"v = proj_unit v + proj_rem v\" \n  unfolding proj_rem_def by simp\n\nlemma apply_J: \"J *v x = proj_unit x\"\nproof (intro iffD2[OF vec_eq_iff] allI)\n  fix i\n  have \"(J *v x) $ i = inner (\\<chi> j. 1 / real CARD('n)) x\" \n    unfolding matrix_vector_mul_component J_def by simp\n  also have \"... = inner stat x\"\n    unfolding stat_def scaleR_vec_def by auto\n  also have \"... = (proj_unit x) $ i\"\n    unfolding proj_unit_def stat_def by simp\n  finally show \"(J *v x) $ i = (proj_unit x) $ i\" by simp\nqed \n\nlemma spec_bound_J: \"spec_bound (J :: real^'n^'n) 0\"\nproof -\n  have \"norm (J *v v) = 0\" if \"inner v 1 = 0\" for v :: \"real^'n\"\n  proof -\n    have \"inner (proj_unit v + proj_rem v) 1 = 0\"\n      using that by (subst (asm) split_vec[of \"v\"], simp)\n    hence \"inner (proj_unit v) 1 = 0\"\n      using proj_rem_orth inner_commute unfolding inner_add_left \n      by (metis add_cancel_left_right)\n    hence \"proj_unit v = 0\"\n      unfolding proj_unit_def stat_def by simp\n    hence \"J *v v = 0\"\n      unfolding apply_J by simp\n    thus ?thesis by simp\n  qed\n  thus ?thesis\n    unfolding spec_bound_def by simp\nqed\n\nlemma matrix_decomposition_lemma_aux:\n  fixes A :: \"real^'n^'n\"\n  assumes \"markov A\"\n  shows \"spec_bound A l \\<longleftrightarrow> matrix_norm_bound (A - (1-l) *\\<^sub>R J) l\" (is \"?L \\<longleftrightarrow> ?R\")\nproof \n  assume a:\"?L\"\n  hence l_ge_0: \"l \\<ge> 0\" using spec_boundD1 by auto \n  show \"?R\" \n  proof (rule matrix_norm_boundI)\n    fix x :: \"real^'n\"\n    have \"(A - (1-l) *\\<^sub>R J) *v x = A *v x - (1-l) *\\<^sub>R (proj_unit x)\"\n      by (simp add:algebra_simps vector_scaleR_matrix_ac_2 apply_J)\n    also have \"... = A *v proj_unit x + A *v proj_rem x - (1-l) *\\<^sub>R (proj_unit x)\"\n      by (subst split_vec[of \"x\"], simp add:algebra_simps)\n    also have \"... = proj_unit x + A *v proj_rem x - (1-l) *\\<^sub>R (proj_unit x)\"\n      using markov_apply[OF assms(1)]\n      unfolding proj_unit_def stat_def by (simp add:algebra_simps)\n    also have \"... = A *v proj_rem x + l *\\<^sub>R proj_unit x\" (is \"_ = ?R1\")\n      by (simp add:algebra_simps)\n    finally have d:\"(A - (1-l) *\\<^sub>R J) *v x = ?R1\" by simp\n\n    have \"inner (l *\\<^sub>R proj_unit x) (A *v proj_rem x) = \n      inner ((l * inner 1 x / real CARD('n)) *\\<^sub>R 1 v* A) (proj_rem x)\"\n      by (subst dot_lmul_matrix[symmetric]) (simp add:proj_unit_def stat_def) \n    also have \"... = (l * inner 1 x / real CARD('n)) * inner 1 (proj_rem x)\" \n      unfolding scaleR_vector_matrix_assoc markov_apply[OF assms] by simp\n    also have \"... = 0\"\n      unfolding proj_rem_orth by simp\n    finally have b:\"inner (l *\\<^sub>R proj_unit x) (A *v proj_rem x) = 0\" by simp\n\n    have c: \"inner (proj_rem x) (proj_unit x) = 0\" \n      using proj_rem_orth[of \"x\"]\n      unfolding proj_unit_def stat_def by (simp add:inner_commute)\n\n    have \"norm (?R1)^2 = norm (A *v proj_rem x)^2 + norm (l *\\<^sub>R proj_unit x)^2\" \n      using b by (intro pythagoras) (simp add:inner_commute)\n    also have \"... \\<le> (l * norm (proj_rem x))^2 + norm (l *\\<^sub>R proj_unit x)^2\" \n      using proj_rem_orth[of \"x\"]\n      by (intro add_mono power_mono spec_boundD2 a) (auto simp add:inner_commute)\n    also have \"... = l^2 * (norm (proj_rem x)^2 + norm (proj_unit x)^2)\"\n      by (simp add:algebra_simps)\n    also have \"... = l^2 * (norm (proj_rem x + proj_unit x)^2)\"\n      using c by (subst pythagoras) auto\n    also have \"... = l^2 * norm x^2\"\n      by (subst (3) split_vec[of \"x\"]) (simp add:algebra_simps)\n    also have \"... = (l * norm x)^2\"\n      by (simp add:algebra_simps)\n    finally have \"norm (?R1)^2 \\<le> (l * norm x)^2\" by simp\n    hence \"norm (?R1) \\<le> l * norm x\"\n      using l_ge_0 by (subst (asm) power_mono_iff) auto\n\n    thus \"norm ((A - (1-l) *\\<^sub>R J) *v x) \\<le> l * norm x\"\n      unfolding d by simp\n  qed\nnext  \n  assume a:\"?R\" \n  have \"norm (A *v x) \\<le> l * norm x\" if \"inner x 1 = 0\" for x \n  proof -\n    have \"(1 - l) *\\<^sub>R J *v x = (1 - l) *\\<^sub>R (proj_unit x)\" \n      by (simp add:vector_scaleR_matrix_ac_2 apply_J)\n    also have \"... = 0\"\n      unfolding proj_unit_def using that by (simp add:inner_commute)\n    finally have b: \"(1 - l) *\\<^sub>R J *v x = 0\" by simp\n\n    have \"norm (A *v x) = norm ((A - (1-l) *\\<^sub>R J) *v x  + ((1-l) *\\<^sub>R J) *v x)\"\n      by (simp add:algebra_simps)\n    also have \"... \\<le> norm ((A - (1-l) *\\<^sub>R J) *v x) + norm (((1-l) *\\<^sub>R J) *v x)\"\n      by (intro norm_triangle_ineq)\n    also have \"... \\<le> l * norm x + 0\"\n      using a b unfolding  matrix_norm_bound_def by (intro add_mono, auto)\n    also have \"... = l * norm x\"\n      by simp\n    finally show ?thesis by simp\n  qed\n\n  moreover have \"l \\<ge> 0\" \n    using a matrix_norm_bound_nonneg by blast\n\n  ultimately show \"?L\" \n    unfolding spec_bound_def by simp\nqed\n\nlemma matrix_decomposition_lemma:\n  fixes A :: \"real^'n^'n\"\n  assumes \"markov A\"\n  shows \"spec_bound A l \\<longleftrightarrow> (\\<exists>E. A = (1-l) *\\<^sub>R J + l *\\<^sub>R E \\<and> matrix_norm_bound E 1 \\<and> l \\<ge> 0)\" \n    (is \"?L \\<longleftrightarrow> ?R\")\nproof -\n  have \"?L \\<longleftrightarrow> matrix_norm_bound (A - (1-l) *\\<^sub>R J) l\" \n    using matrix_decomposition_lemma_aux[OF assms] by simp\n  also have \"... \\<longleftrightarrow> ?R\"\n  proof\n    assume a:\"matrix_norm_bound (A - (1 - l) *\\<^sub>R J) l\"\n    hence l_ge_0: \"l \\<ge> 0\" using matrix_norm_bound_nonneg by auto\n    define E where \"E = (1/l) *\\<^sub>R (A - (1-l) *\\<^sub>R J)\"\n    have \"A = J\" if \"l = 0\" \n    proof -\n      have \"matrix_norm_bound (A - J) 0\"\n        using a that by simp\n      hence \"A - J = 0\" using matrix_norm_bound_0 by blast\n      thus \"A = J\" by simp\n    qed\n    hence \"A = (1-l) *\\<^sub>R J + l *\\<^sub>R E\"\n      unfolding E_def by simp\n    moreover have \"matrix_norm_bound E 1\" \n    proof (cases \"l = 0\")\n      case True\n      hence \"E = 0\" if \"l = 0\"\n        unfolding E_def by simp\n      thus \"matrix_norm_bound E 1\" if \"l = 0\"\n        using that unfolding matrix_norm_bound_def by auto\n    next\n      case False\n      hence \"l > 0\" using l_ge_0 by simp\n      moreover have \"matrix_norm_bound E (\\<bar>1 / l\\<bar>* l)\"\n        unfolding E_def\n        by (intro matrix_norm_bound_scale a)\n      ultimately show ?thesis by auto\n    qed\n    ultimately show ?R using l_ge_0 by auto\n  next\n    assume a:?R\n    then obtain E where E_def: \"A = (1 - l) *\\<^sub>R J + l *\\<^sub>R E\"  \"matrix_norm_bound E 1\" \"l \\<ge> 0\"\n      by auto\n    have \"matrix_norm_bound (l *\\<^sub>R E) (abs l*1)\" \n      by (intro matrix_norm_bound_scale E_def(2))\n    moreover have \"l \\<ge> 0\" using E_def by simp \n    moreover have \" l *\\<^sub>R E = (A - (1 - l) *\\<^sub>R J)\" \n      using E_def(1) by simp\n    ultimately show \"matrix_norm_bound (A - (1 - l) *\\<^sub>R J) l\"\n      by simp  \n  qed\n  finally show ?thesis by simp\nqed\n\nlemma hitting_property_alg:\n  fixes S :: \"('n :: finite) set\"\n  assumes l_range: \"l \\<in> {0..1}\"\n  defines \"P \\<equiv> diag (ind_vec S)\"\n  defines \"\\<mu> \\<equiv> card S / CARD('n)\"\n  assumes \"\\<And>M. M \\<in> set Ms \\<Longrightarrow> spec_bound M l \\<and> markov M\"\n  shows \"foldl (\\<lambda>x M. P *v (M *v x)) (P *v stat) Ms \\<bullet> 1 \\<le> (\\<mu> + l * (1-\\<mu>))^(length Ms+1)\"\nproof -\n  define t :: \"real^'n\" where \"t = (\\<chi> i. of_bool (i \\<in> S))\"\n  define r where \"r = foldl (\\<lambda>x M. P *v (M *v x)) (P *v stat) Ms\"\n  have P_proj: \"P ** P = P\"\n    unfolding P_def diag_mult_eq ind_vec_def by (intro arg_cong[where f=\"diag\"]) (vector)\n\n  have P_1_left: \"1 v* P = t\"\n    unfolding P_def diag_def ind_vec_def vector_matrix_mult_def t_def by simp\n\n  have P_1_right: \"P *v 1 = t\"\n    unfolding P_def diag_def ind_vec_def matrix_vector_mult_def t_def by simp\n\n  have P_norm :\"matrix_norm_bound P 1\"\n    unfolding P_def ind_vec_def by (intro matrix_norm_bound_diag) simp\n\n  have norm_t: \"norm t = sqrt (real (card S))\" \n    unfolding t_def norm_vec_def L2_set_def of_bool_def\n    by (simp add:sum.If_cases if_distrib if_distribR)\n\n  have \\<mu>_range: \"\\<mu> \\<ge> 0\" \"\\<mu> \\<le> 1\" \n    unfolding \\<mu>_def by (auto simp add:card_mono) \n\n  define condition :: \"real^'n \\<Rightarrow> nat \\<Rightarrow> bool\" \n    where \"condition = (\\<lambda>x n. norm x \\<le> (\\<mu> + l * (1-\\<mu>))^n * sqrt (card S)/CARD('n) \\<and> P *v x = x)\" \n\n  have a:\"condition r (length Ms)\"\n    unfolding r_def using assms(4)\n  proof (induction Ms rule:rev_induct)\n    case Nil\n    have \"norm (P *v stat) = (1 / real CARD('n)) * norm t\"\n      unfolding stat_def matrix_vector_mult_scaleR P_1_right by simp\n    also have \"... \\<le>  (1 / real CARD('n)) * sqrt (real (card S))\"\n      using  norm_t by (intro mult_left_mono) auto\n    also have \"... = sqrt (card S)/CARD('n)\" by simp\n    finally have \"norm (P *v stat) \\<le> sqrt (card S)/CARD('n)\" by simp\n    moreover have \"P *v (P *v stat) = P *v stat\"\n      unfolding matrix_vector_mul_assoc P_proj by simp\n    ultimately show ?case unfolding condition_def by simp\n  next\n    case (snoc M xs)\n    hence \"spec_bound M l \\<and> markov M\"\n        using snoc(2) by simp\n    then obtain E where E_def: \"M = (1-l) *\\<^sub>R J + l *\\<^sub>R E\" \"matrix_norm_bound E 1\" \n      using iffD1[OF matrix_decomposition_lemma] by auto\n\n    define y where \"y = foldl (\\<lambda>x M. P *v (M *v x)) (P *v stat) xs\"\n    have b:\"condition y (length xs)\"\n      using snoc unfolding y_def by simp\n    hence a:\"P *v y = y\" using condition_def by simp\n\n    have \"norm (P *v (M *v y)) = norm (P *v ((1-l)*\\<^sub>R J *v y) + P *v (l *\\<^sub>R E *v y))\"\n      by (simp add:E_def algebra_simps)\n    also have \"... \\<le> norm (P *v ((1-l)*\\<^sub>R J *v y)) + norm (P *v (l *\\<^sub>R E *v y)) \"\n      by (intro norm_triangle_ineq)\n    also have \"... = (1 - l) * norm (P *v (J *v y)) + l * norm (P *v (E *v y))\"\n      using l_range\n      by (simp add:vector_scaleR_matrix_ac_2 matrix_vector_mult_scaleR)\n    also have \"... = (1-l) * \\<bar>1 \\<bullet> (P *v y)/real CARD('n)\\<bar> * norm t + l * norm (P *v (E *v y))\"\n      by (subst a[symmetric]) \n        (simp add:apply_J proj_unit_def stat_def P_1_right matrix_vector_mult_scaleR)\n    also have \"... = (1-l) * \\<bar>t \\<bullet> y\\<bar>/real CARD('n) * norm t + l * norm (P *v (E *v y))\"\n      by (subst dot_lmul_matrix[symmetric]) (simp add:P_1_left)\n    also have \"... \\<le> (1-l) * (norm t * norm y) / real CARD('n) * norm t + l * (1 * norm (E *v y))\"\n      using P_norm Cauchy_Schwarz_ineq2 l_range\n      by (intro add_mono mult_right_mono mult_left_mono divide_right_mono matrix_norm_boundD) auto\n    also have \"... = (1-l) * \\<mu> * norm y + l * norm (E *v y)\"\n      unfolding \\<mu>_def norm_t by simp\n    also have \"... \\<le> (1-l) * \\<mu> * norm y + l * (1 * norm y)\"\n      using \\<mu>_range l_range\n      by (intro add_mono matrix_norm_boundD mult_left_mono E_def) auto\n    also have \"... = (\\<mu> + l * (1-\\<mu>)) * norm y\"\n      by (simp add:algebra_simps)\n    also have \"... \\<le> (\\<mu> + l * (1-\\<mu>)) * ((\\<mu> + l * (1-\\<mu>))^length xs * sqrt (card S)/CARD('n))\"\n      using b \\<mu>_range l_range unfolding condition_def\n      by (intro mult_left_mono) auto\n    also have \"... = (\\<mu> + l * (1-\\<mu>))^(length xs +1) * sqrt (card S)/CARD('n)\"\n      by simp\n    finally have \"norm (P *v (M *v y)) \\<le> (\\<mu> + l * (1-\\<mu>))^(length xs +1) * sqrt (card S)/CARD('n)\"\n      by simp\n\n    moreover have \"P *v (P *v (M *v y)) = P *v (M *v y)\"\n      unfolding matrix_vector_mul_assoc matrix_mul_assoc P_proj \n      by simp\n\n    ultimately have \"condition (P *v (M *v y)) (length (xs@[M]))\"\n      unfolding condition_def by simp\n  \n    then show ?case \n      unfolding y_def by simp\n  qed\n\n  have \"inner r 1 = inner (P *v r) 1\"\n    using a condition_def by simp\n  also have \"... = inner (1 v* P) r\"\n    unfolding dot_lmul_matrix by (simp add:inner_commute)\n  also have \"... = inner t r\"\n    unfolding P_1_left by simp\n  also have \"... \\<le> norm t * norm r\"\n    by (intro norm_cauchy_schwarz)\n  also have \"... \\<le> sqrt (card S) * ((\\<mu> + l * (1-\\<mu>))^(length Ms) * sqrt(card S)/CARD('n))\"\n    using a unfolding condition_def norm_t\n    by (intro mult_mono) auto\n  also have \"... = (\\<mu> + 0) * ((\\<mu> + l * (1-\\<mu>))^(length Ms))\"\n    by (simp add:\\<mu>_def)\n  also have \"... \\<le> (\\<mu> + l * (1-\\<mu>)) * (\\<mu> + l * (1-\\<mu>))^(length Ms)\"\n    using \\<mu>_range l_range\n    by (intro mult_right_mono zero_le_power add_mono) auto\n  also have \"... = (\\<mu> + l * (1-\\<mu>))^(length Ms+1)\" by simp\n  finally show ?thesis \n    unfolding r_def by simp\nqed\n\nlemma upto_append:\n  assumes \"i \\<le> j\" \"j \\<le> k\"\n  shows  \"[i..<j]@[j..<k] = [i..<k]\"\n  using assms by (metis less_eqE upt_add_eq_append)\n\ndefinition bool_list_split :: \"bool list \\<Rightarrow> (nat list \\<times> nat)\"\n  where \"bool_list_split xs = foldl (\\<lambda>(ys,z) x. (if x then (ys@[z],0) else (ys,z+1))) ([],0) xs\" \n\nlemma bool_list_split:\n  assumes \"bool_list_split xs = (ys,z)\"\n  shows \"xs = concat (map (\\<lambda>k. replicate k False@[True]) ys)@replicate z False\"\n  using assms\nproof (induction xs arbitrary: ys z rule:rev_induct)\n  case Nil\n  then show ?case unfolding bool_list_split_def by simp\nnext\n  case (snoc x xs)\n  obtain u v where uv_def: \"bool_list_split xs = (u,v)\" \n    by (metis surj_pair)\n\n  show ?case \n  proof (cases x)\n    case True\n    have a:\"ys = u@[v]\" \"z = 0\"\n      using snoc(2) True uv_def unfolding bool_list_split_def by auto\n    have \"xs@[x] = concat (map (\\<lambda>k. replicate k False@[True]) u)@replicate v False@[True]\"\n      using snoc(1)[OF uv_def] True by simp\n    also have \"... = concat (map (\\<lambda>k. replicate k False@[True]) (u@[v]))@replicate 0 False\"\n      by simp\n    also have \"... = concat (map (\\<lambda>k. replicate k False@[True]) (ys))@replicate z False\"\n      using a by simp\n    finally show ?thesis by simp\n  next\n    case False\n    have a:\"ys = u\" \"z = v+1\"\n      using snoc(2) False uv_def unfolding bool_list_split_def by auto\n    have \"xs@[x] = concat (map (\\<lambda>k. replicate k False@[True]) u)@replicate (v+1) False\"\n      using snoc(1)[OF uv_def] False unfolding replicate_add by simp\n    also have \"... = concat (map (\\<lambda>k. replicate k False@[True]) (ys))@replicate z False\"\n      using a by simp\n    finally show ?thesis by simp\n  qed\nqed\n\nlemma bool_list_split_count:\n  assumes \"bool_list_split xs = (ys,z)\"\n  shows \"length (filter id xs) = length ys\"\n  unfolding bool_list_split[OF assms(1)] by (simp add:filter_concat comp_def)\n\nlemma foldl_concat:\n  \"foldl f a (concat xss) = foldl (\\<lambda>y xs. foldl f y xs) a xss\"\n  by (induction xss rule:rev_induct, auto)\n\nlemma hitting_property_alg_2:\n  fixes S :: \"('n :: finite) set\" and l :: nat \n  fixes M :: \"real^'n^'n\"\n  assumes \\<alpha>_range: \"\\<alpha> \\<in> {0..1}\"\n  assumes \"I \\<subseteq> {..<l}\"\n  defines \"P i \\<equiv> (if i \\<in> I then diag (ind_vec S) else mat 1)\"\n  defines \"\\<mu> \\<equiv> real (card S) / real (CARD('n))\"\n  assumes \"spec_bound M \\<alpha>\" \"markov M\"\n  shows \n    \"foldl (\\<lambda>x M. M *v x) stat (intersperse M (map P [0..<l])) \\<bullet> 1 \\<le> (\\<mu>+\\<alpha>*(1-\\<mu>))^card I\"\n    (is \"?L \\<le> ?R\")\nproof (cases \"I \\<noteq> {}\")\n  case True\n  define xs where \"xs = map (\\<lambda>i. i \\<in> I) [0..<l]\"\n  define Q where \"Q = diag (ind_vec S)\"\n  define P' where \"P' = (\\<lambda>x. if x then Q else mat 1)\"\n\n  let ?rep = \"(\\<lambda>x. replicate x (mat 1))\"\n\n  have P_eq: \"P i = P' (i \\<in> I)\" for i\n    unfolding P_def P'_def Q_def by simp\n\n  have \"l > 0\" \n    using True assms(2) by auto\n  hence xs_ne: \"xs \\<noteq> []\" \n    unfolding xs_def by simp\n\n  obtain ys z where ys_z: \"bool_list_split xs = (ys,z)\"\n    by (metis surj_pair)\n\n\n  have \"length ys = length (filter id xs)\" \n    using bool_list_split_count[OF ys_z] by simp\n  also have \"... = card (I \\<inter> {0..<l})\"\n    unfolding xs_def filter_map by (simp add:comp_def distinct_length_filter)\n  also have \"... = card I\"\n    using Int_absorb2[OF assms(2)] unfolding atLeast0LessThan by simp\n  finally have  len_ys: \"length ys = card I\" by simp\n\n  hence \"length ys > 0\"\n    using True assms(2) by (metis card_gt_0_iff finite_nat_iff_bounded)\n  then obtain yh yt where ys_split: \"ys = yh#yt\" \n    by (metis length_greater_0_conv neq_Nil_conv)\n\n  have a:\"foldl (\\<lambda>x N. M *v (N *v x)) x (?rep z) \\<bullet> 1 = x \\<bullet> 1\" for x\n  proof (induction z)\n    case 0\n    then show ?case by simp\n  next\n    case (Suc z)\n    have \"foldl (\\<lambda>x N. M *v (N *v x)) x (?rep (z+1)) \\<bullet> 1 = x \\<bullet> 1\"\n      unfolding replicate_add using Suc \n      by (simp add:markov_orth_inv[OF assms(6)])\n    then show ?case by simp\n  qed\n\n  have \"M *v stat = stat\" \n    using assms(6) unfolding stat_def matrix_vector_mult_scaleR markov_def by simp\n  hence b: \"foldl (\\<lambda>x N. M *v (N *v x)) stat (?rep yh) = stat\"\n    by (induction yh, auto)\n\n  have \"foldl (\\<lambda>x N. N *v (M *v x)) a (?rep x) = matrix_pow M x *v a\" for x a\n  proof (induction x)\n    case 0\n    then show ?case by simp\n  next\n    case (Suc x)\n    have \"foldl (\\<lambda>x N. N *v (M *v x)) a (?rep (x+1)) =  matrix_pow M (x+1) *v a\"\n      unfolding replicate_add using Suc by (simp add: matrix_vector_mul_assoc)\n    then show ?case by simp\n  qed\n  hence c: \"foldl (\\<lambda>x N. N *v (M *v x)) a (?rep x @ [Q]) = Q *v (matrix_pow M (x+1) *v a)\" for x a\n    by (simp add:matrix_vector_mul_assoc matrix_mul_assoc)\n\n  have d: \"spec_bound N \\<alpha> \\<and> markov N\" if t1: \"N \\<in> set (map (\\<lambda>x. matrix_pow M (x + 1)) yt)\" for N\n  proof -\n    obtain y where N_def: \"N = matrix_pow M (y+1)\"\n      using t1 by auto\n    hence d1: \"spec_bound N (\\<alpha>^(y+1))\"\n      unfolding N_def using spec_bound_pow assms(5,6) by blast\n    have \"spec_bound N (\\<alpha>^1)\" \n      using \\<alpha>_range by (intro spec_bound_mono[OF d1] power_decreasing) auto \n    moreover have \"markov N\"\n      unfolding N_def by (intro markov_matrix_pow assms(6))\n    ultimately show ?thesis by simp\n  qed\n\n  have \"?L = foldl (\\<lambda>x M. M *v x) stat (intersperse M (map P' xs)) \\<bullet> 1\"\n    unfolding P_eq xs_def map_map by (simp add:comp_def)\n  also have \"... = foldl (\\<lambda>x M. M *v x) stat (intersperse M (map P' xs)@[M]) \\<bullet> 1\"\n    by (simp add:markov_orth_inv[OF assms(6)]) \n  also have \"... = foldl (\\<lambda>x N. M *v (N *v x)) stat (map P' xs) \\<bullet> 1\"\n    using xs_ne by (subst foldl_intersperse) auto\n  also have \"... = foldl (\\<lambda>x N. M *v (N *v x)) stat ((ys \\<bind> (\\<lambda>x. ?rep x @ [Q])) @ ?rep z) \\<bullet> 1\"\n    unfolding bool_list_split[OF ys_z] P'_def List.bind_def by (simp add: comp_def map_concat)\n  also have \"... = foldl (\\<lambda>x N. M *v (N *v x)) stat (ys \\<bind> (\\<lambda>x. ?rep x @ [Q])) \\<bullet> 1\"\n    by (simp add: a)\n  also have \"... = foldl (\\<lambda>x N. M *v (N *v x)) stat (?rep yh @[Q]@(yt \\<bind>(\\<lambda>x. ?rep x @ [Q]))) \\<bullet> 1\"\n    unfolding ys_split by simp\n  also have \"... = foldl (\\<lambda>x N. M *v (N *v x)) stat ([Q]@(yt \\<bind>(\\<lambda>x. ?rep x @ [Q]))) \\<bullet> 1\"\n    by (simp add:b)\n  also have \"... = foldl (\\<lambda>x N. N *v x) stat (intersperse M (Q#(yt \\<bind>(\\<lambda>x.?rep x@[Q])))@[M])\\<bullet>1\"\n    by (subst foldl_intersperse, auto)\n  also have \"... = foldl (\\<lambda>x N. N *v x) stat (intersperse M (Q#(yt \\<bind>(\\<lambda>x.?rep x@[Q])))) \\<bullet> 1\"\n    by (simp add:markov_orth_inv[OF assms(6)]) \n  also have \"... = foldl (\\<lambda>x N. N *v (M *v x)) (Q *v stat) (yt \\<bind>(\\<lambda>x.?rep x@[Q])) \\<bullet> 1\" \n    by (subst foldl_intersperse_2, simp)\n  also have \"... = foldl (\\<lambda>a x. foldl (\\<lambda>x N. N *v (M *v x)) a (?rep x @ [Q])) (Q *v stat) yt \\<bullet> 1\"\n    unfolding List.bind_def foldl_concat foldl_map by simp\n  also have \"... = foldl (\\<lambda>a x. Q *v (matrix_pow M (x+1) *v a)) (Q *v stat) yt \\<bullet> 1\"\n    unfolding c by simp\n  also have \"... = foldl (\\<lambda>a N. Q *v (N *v a)) (Q *v stat) (map (\\<lambda>x. matrix_pow M (x+1)) yt) \\<bullet> 1\"\n    by (simp add:foldl_map)\n  also have \"... \\<le> (\\<mu> + \\<alpha>*(1-\\<mu>))^(length (map (\\<lambda>x. matrix_pow M (x+1)) yt)+1)\"\n    unfolding \\<mu>_def Q_def by (intro hitting_property_alg \\<alpha>_range d) simp\n  also have \"... = (\\<mu> + \\<alpha>*(1-\\<mu>))^(length ys)\" \n    unfolding ys_split by simp\n  also have \"... = ?R\" unfolding len_ys by simp\n  finally show ?thesis by simp\nnext\n  case False\n  hence I_empty: \"I = {}\" by simp\n\n  have \"?L = stat \\<bullet> (1 :: real^'n)\"\n  proof (cases \"l > 0\")\n    case True\n    have \"?L = foldl (\\<lambda>x M. M *v x) stat ((intersperse M (map P [0..<l]))@[M]) \\<bullet> 1\"\n      by (simp add:markov_orth_inv[OF assms(6)]) \n    also have \"... = foldl (\\<lambda>x N. M *v (N *v x)) stat (map P [0..<l])  \\<bullet> 1\"\n      using True by (subst foldl_intersperse, auto)\n    also have \"... = foldl (\\<lambda>x N. M *v (N *v x)) stat (map (\\<lambda>_. mat 1) [0..<l])  \\<bullet> 1\"\n      unfolding  P_def using I_empty by simp\n    also have \"... = foldl (\\<lambda>x _. M *v x) stat [0..<l] \\<bullet> 1\"\n      unfolding foldl_map by simp\n    also have \"... = stat \\<bullet> (1 :: real^'n)\"\n      by (induction l, auto simp add:markov_orth_inv[OF assms(6)])\n    finally show ?thesis by simp\n  next\n    case False\n    then show ?thesis by simp\n  qed\n  also have \"... = 1\"\n    unfolding stat_def by (simp add:inner_vec_def)\n  also have \"... \\<le> ?R\" unfolding I_empty by simp\n  finally show ?thesis by simp\nqed\n\nlemma uniform_property_alg:\n  fixes x :: \"('n :: finite)\" and l :: nat\n  assumes \"i < l\"\n  defines \"P j \\<equiv> (if j = i then diag (ind_vec {x}) else mat 1)\"\n  assumes \"markov M\"\n  shows \"foldl (\\<lambda>x M. M *v x) stat (intersperse M (map P [0..<l])) \\<bullet> 1 = 1 / CARD('n)\"\n    (is \"?L = ?R\") \nproof -\n  have a:\"l > 0\" using assms(1) by simp\n\n  have 0: \"foldl (\\<lambda>x N. M *v (N *v x)) y (xs) \\<bullet> 1 = y  \\<bullet> 1\" if \"set xs \\<subseteq> {mat 1}\" for xs y\n    using that\n  proof (induction xs rule:rev_induct)\n    case Nil\n    then show ?case by simp\n  next\n    case (snoc x xs)\n    have \"x = mat 1\" \n      using snoc(2) by simp\n    hence \"foldl (\\<lambda>x N. M *v (N *v x)) y (xs @ [x]) \\<bullet> 1 = foldl (\\<lambda>x N. M *v (N *v x)) y xs \\<bullet> 1\"\n      by (simp add:markov_orth_inv[OF assms(3)])\n    also have \"... = y \\<bullet> 1\"\n      using snoc(2) by (intro snoc(1)) auto\n    finally show ?case by simp\n  qed\n\n  have M_stat: \"M *v stat = stat\" \n    using assms(3) unfolding stat_def matrix_vector_mult_scaleR markov_def by simp\n\n  hence 1: \"(foldl (\\<lambda>x N. M *v (N *v x)) stat xs) = stat\" if \"set xs \\<subseteq> {mat 1}\" for xs\n    using that by (induction xs, auto)\n\n  have \"?L = foldl (\\<lambda>x M. M *v x) stat ((intersperse M (map P [0..<l]))@[M]) \\<bullet> 1\"\n    by (simp add:markov_orth_inv[OF assms(3)]) \n  also have \"... = foldl (\\<lambda>x N. M *v (N *v x)) stat (map P [0..<l]) \\<bullet> 1\"\n    using a by (subst foldl_intersperse) auto\n  also have \"... = foldl (\\<lambda>x N. M *v (N *v x)) stat (map P ([0..<i+1]@[i+1..<l])) \\<bullet> 1\"\n    using assms(1) by (subst upto_append) auto\n  also have \"... = foldl (\\<lambda>x N. M *v (N *v x)) stat (map P [0..<i + 1]) \\<bullet> 1\"\n    unfolding map_append foldl_append  P_def by (subst 0) auto\n  also have \"... = foldl (\\<lambda>x N. M *v (N *v x)) stat (map P ([0..<i]@[i])) \\<bullet> 1\"\n    by simp\n  also have \"... = (M *v (diag (ind_vec {x}) *v stat)) \\<bullet> 1\"\n    unfolding map_append foldl_append P_def by (subst 1) auto\n  also have \"... = (diag (ind_vec {x}) *v stat) \\<bullet> 1\" \n    by (simp add:markov_orth_inv[OF assms(3)]) \n  also have \"... = ((1/CARD('n)) *\\<^sub>R ind_vec {x}) \\<bullet> 1\" \n    unfolding diag_def ind_vec_def  stat_def matrix_vector_mult_def \n    by (intro arg_cong2[where f=\"(\\<bullet>)\"] refl) \n      (vector of_bool_def sum.If_cases if_distrib if_distribR)\n  also have \"... = (1/CARD('n)) * (ind_vec {x} \\<bullet> 1)\"\n    by simp\n  also have \"... = (1/CARD('n)) * 1\"\n    unfolding inner_vec_def ind_vec_def of_bool_def \n    by (intro arg_cong2[where f=\"(*)\"] refl) (simp)\n  finally show ?thesis by simp\nqed\n\nend\n\nlemma foldl_matrix_mult_expand:\n  fixes Ms :: \"(('r::{semiring_1,comm_monoid_mult})^'a^'a) list\"\n  shows \"(foldl (\\<lambda>x M. M *v x) a Ms) $ k = (\\<Sum>x | length x = length Ms+1 \\<and> x! length Ms = k. \n  (\\<Prod> i< length Ms. (Ms ! i) $ (x ! (i+1)) $ (x ! i)) * a $ (x ! 0))\"\nproof (induction Ms arbitrary: k rule:rev_induct)\n  case Nil\n  have \"length x = Suc 0 \\<Longrightarrow> x = [x!0]\" for x :: \"'a list\"\n    by (cases x, auto)\n  hence \"{x. length x = Suc 0 \\<and> x ! 0 = k} = {[k]}\" \n    by auto \n  thus ?case by auto\nnext\n  case (snoc M Ms)\n  let ?l = \"length Ms\"\n\n  have 0: \"finite {w. length w = Suc (length Ms) \\<and> w ! length Ms = i}\" for i :: 'a\n    using finite_lists_length_eq[where A=\"UNIV::'a set\" and n=\"?l +1\"] by simp\n\n  have \"take (?l+1) x @ [x ! (?l+1)] = x\" if \"length x = ?l+2\" for x :: \"'a list\"\n  proof -\n    have \"take (?l+1) x @ [x ! (?l+1)] = take (Suc (?l+1)) x\"\n      using that by (intro take_Suc_conv_app_nth[symmetric], simp)\n    also have \"... = x\" \n      using that by simp\n    finally show ?thesis by simp\n  qed\n  hence 1: \"bij_betw  (take (?l+1)) {w. length w=?l+2 \\<and> w!(?l+1) =k} {w. length w = ?l+1}\"\n    by (intro bij_betwI[where g=\"\\<lambda>x. x@[k]\"]) (auto simp add:nth_append)\n\n  have \"foldl (\\<lambda>x M. M *v x) a (Ms @ [M]) $ k = (\\<Sum>j\\<in>UNIV. M$k$j *(foldl (\\<lambda>x M. M *v x) a Ms $ j))\"\n    by (simp add:matrix_vector_mult_def)\n  also have \"... = \n    (\\<Sum>j\\<in>UNIV. M$k$j * (\\<Sum>w|length w=?l+1\\<and>w!?l=j. (\\<Prod>i<?l. Ms!i $ w!(i+1) $ w!i) * a $ w!0))\"\n    unfolding snoc by simp\n  also have \"... = \n    (\\<Sum>j\\<in>UNIV. (\\<Sum>w|length w=?l+1\\<and>w!?l=j. M$k$w!?l * (\\<Prod>i<?l. Ms!i $ w!(i+1) $ w!i) * a $ w!0))\"\n    by (intro sum.cong refl) (simp add: sum_distrib_left algebra_simps)\n  also have \"... = (\\<Sum>w\\<in> (\\<Union>j \\<in> UNIV. {w. length w=?l+1 \\<and> w!?l =j}). \n    M$k$w!?l*(\\<Prod>i<?l. Ms!i $ w!(i+1) $ w!i) * a $ w!0)\"\n    using 0 by (subst sum.UNION_disjoint, simp, simp) auto \n  also have \"... = (\\<Sum>w | length w=?l+1. M$k$(w!?l)*(\\<Prod>i<?l. Ms!i $ w!(i+1) $ w!i) * a $ w!0)\"\n    by (intro sum.cong arg_cong2[where f=\"(*)\"] refl) auto\n  also have \"... = (\\<Sum>w \\<in> take (?l+1) ` {w. length w=?l+2 \\<and> w!(?l+1) =k}. \n    M$k$w!?l*(\\<Prod>i<?l. Ms!i $ w!(i+1) $ w!i) * a $ w!0)\"\n    using 1 unfolding bij_betw_def by (intro sum.cong refl, auto) \n  also have \"... = (\\<Sum>w|length w=?l+2\\<and>w!(?l+1)=k. M$k$w!?l*(\\<Prod>i<?l. Ms!i $ w!(i+1) $ w!i)* a$w!0)\"\n    using 1 unfolding bij_betw_def by (subst sum.reindex, auto)\n  also have \"... = (\\<Sum>w|length w=?l+2\\<and>w!(?l+1)=k. \n    (Ms@[M])!?l$k$w!?l*(\\<Prod>i<?l. (Ms@[M])!i $ w!(i+1) $ w!i)* a$w!0)\"\n    by (intro sum.cong arg_cong2[where f=\"(*)\"] prod.cong refl) (auto simp add:nth_append)\n  also have \"... = (\\<Sum>w|length w=?l+2\\<and>w!(?l+1)=k. (\\<Prod>i<(?l+1). (Ms@[M])!i $ w!(i+1) $ w!i)* a$w!0)\"\n    by (intro sum.cong, auto simp add:algebra_simps)\n  finally have \"foldl (\\<lambda>x M. M *v x) a (Ms @ [M]) $ k = \n    (\\<Sum> w | length w = ?l+2 \\<and> w ! (?l+1) = k. (\\<Prod>i<(?l+1). (Ms@[M])!i $ w!(i+1) $ w!i)* a$w!0)\"\n    by simp\n  then show ?case by simp\nqed\n\nlemma foldl_matrix_mult_expand_2:\n  fixes Ms :: \"(real^'a^'a) list\"\n  shows \"(foldl (\\<lambda>x M. M *v x) a Ms) \\<bullet> 1 = (\\<Sum>x | length x = length Ms+1. \n          (\\<Prod> i< length Ms. (Ms ! i) $ (x ! (i+1)) $ (x ! i)) * a $ (x ! 0))\"\n  (is \"?L = ?R\")\nproof -\n  let ?l = \"length Ms\"\n  have \"?L = (\\<Sum>j \\<in> UNIV. (foldl (\\<lambda>x M. M *v x) a Ms) $ j)\"\n    by (simp add:inner_vec_def)\n  also have \"... = (\\<Sum>j\\<in>UNIV. \\<Sum>x|length x=?l+1 \\<and> x!?l=j.(\\<Prod>i<?l. Ms!i $ x!(i+1) $ x!i) * a $ x!0)\"\n    unfolding foldl_matrix_mult_expand by simp\n  also have \"... = (\\<Sum>x \\<in> (\\<Union>j\\<in> UNIV.{w. length w = length Ms+1 \\<and> w ! length Ms = j}).\n          (\\<Prod> i< length Ms. (Ms ! i) $ (x ! (i+1)) $ (x ! i)) * a $ (x ! 0))\"\n    using finite_lists_length_eq[where A=\"UNIV::'a set\" and n=\"?l +1\"]\n    by (intro sum.UNION_disjoint[symmetric]) auto\n  also have \"... = ?R\"\n    by (intro sum.cong, auto)\n  finally show ?thesis by simp\nqed\n\nend\n", "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/Expander_Graphs/Expander_Graphs_Algebra.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8397339676722393, "lm_q2_score": 0.8438951104066295, "lm_q1q2_score": 0.7086473893609614}}
{"text": "(*  Title:      HOL/Map.thy\n    Author:     Tobias Nipkow, based on a theory by David von Oheimb\n    Copyright   1997-2003 TU Muenchen\n\nThe datatype of \"maps\"; strongly resembles maps in VDM.\n*)\n\nsection \\<open>Maps\\<close>\n\ntheory Map\n  imports List\n  abbrevs \"(=\" = \"\\<subseteq>\\<^sub>m\"\nbegin\n\ntype_synonym ('a, 'b) \"map\" = \"'a \\<Rightarrow> 'b option\" (infixr \"\\<rightharpoonup>\" 0)\n\nabbreviation (input)\n  empty :: \"'a \\<rightharpoonup> 'b\" where\n  \"empty \\<equiv> \\<lambda>x. None\"\n\ndefinition\n  map_comp :: \"('b \\<rightharpoonup> 'c) \\<Rightarrow> ('a \\<rightharpoonup> 'b) \\<Rightarrow> ('a \\<rightharpoonup> 'c)\"  (infixl \"\\<circ>\\<^sub>m\" 55) where\n  \"f \\<circ>\\<^sub>m g = (\\<lambda>k. case g k of None \\<Rightarrow> None | Some v \\<Rightarrow> f v)\"\n\ndefinition\n  map_add :: \"('a \\<rightharpoonup> 'b) \\<Rightarrow> ('a \\<rightharpoonup> 'b) \\<Rightarrow> ('a \\<rightharpoonup> 'b)\"  (infixl \"++\" 100) where\n  \"m1 ++ m2 = (\\<lambda>x. case m2 x of None \\<Rightarrow> m1 x | Some y \\<Rightarrow> Some y)\"\n\ndefinition\n  restrict_map :: \"('a \\<rightharpoonup> 'b) \\<Rightarrow> 'a set \\<Rightarrow> ('a \\<rightharpoonup> 'b)\"  (infixl \"|`\"  110) where\n  \"m|`A = (\\<lambda>x. if x \\<in> A then m x else None)\"\n\nnotation (latex output)\n  restrict_map  (\"_\\<restriction>\\<^bsub>_\\<^esub>\" [111,110] 110)\n\ndefinition\n  dom :: \"('a \\<rightharpoonup> 'b) \\<Rightarrow> 'a set\" where\n  \"dom m = {a. m a \\<noteq> None}\"\n\ndefinition\n  ran :: \"('a \\<rightharpoonup> 'b) \\<Rightarrow> 'b set\" where\n  \"ran m = {b. \\<exists>a. m a = Some b}\"\n\ndefinition\n  graph :: \"('a \\<rightharpoonup> 'b) \\<Rightarrow> ('a \\<times> 'b) set\" where\n  \"graph m = {(a, b) | a b. m a = Some b}\"\n\ndefinition\n  map_le :: \"('a \\<rightharpoonup> 'b) \\<Rightarrow> ('a \\<rightharpoonup> 'b) \\<Rightarrow> bool\"  (infix \"\\<subseteq>\\<^sub>m\" 50) where\n  \"(m\\<^sub>1 \\<subseteq>\\<^sub>m m\\<^sub>2) \\<longleftrightarrow> (\\<forall>a \\<in> dom m\\<^sub>1. m\\<^sub>1 a = m\\<^sub>2 a)\"\n\ntext \\<open>Function update syntax \\<open>f(x := y, \\<dots>)\\<close> is extended with \\<open>x \\<mapsto> y\\<close>, which is short for\n\\<open>x := Some y\\<close>. \\<open>:=\\<close> and \\<open>\\<mapsto>\\<close> can be mixed freely.\nThe syntax \\<open>[x \\<mapsto> y, \\<dots>]\\<close> is short for \\<open>Map.empty(x \\<mapsto> y, \\<dots>)\\<close>\nbut must only contain \\<open>\\<mapsto>\\<close>, not \\<open>:=\\<close>, because \\<open>[x:=y]\\<close> clashes with the list update syntax \\<open>xs[i:=x]\\<close>.\\<close>\n\nnonterminal maplet and maplets\n\nsyntax\n  \"_maplet\"  :: \"['a, 'a] \\<Rightarrow> maplet\"             (\"_ /\\<mapsto>/ _\")\n  \"\"         :: \"maplet \\<Rightarrow> updbind\"              (\"_\")\n  \"\"         :: \"maplet \\<Rightarrow> maplets\"             (\"_\")\n  \"_Maplets\" :: \"[maplet, maplets] \\<Rightarrow> maplets\" (\"_,/ _\")\n  \"_Map\"     :: \"maplets \\<Rightarrow> 'a \\<rightharpoonup> 'b\"           (\"(1[_])\")\n(* Syntax forbids \\<open>[\\<dots>, x := y, \\<dots>]\\<close> by introducing \\<open>maplets\\<close> in addition to \\<open>updbinds\\<close> *)\n\nsyntax (ASCII)\n  \"_maplet\"  :: \"['a, 'a] \\<Rightarrow> maplet\"             (\"_ /|->/ _\")\n\ntranslations\n  \"_Update f (_maplet x y)\" \\<rightleftharpoons> \"f(x := CONST Some y)\"\n  \"_Maplets m ms\" \\<rightharpoonup> \"_updbinds m ms\"\n  \"_Map ms\" \\<rightharpoonup> \"_Update (CONST empty) ms\"\n\n(* Printing must create \\<open>_Map\\<close> only for \\<open>_maplet\\<close> *)\n  \"_Map (_maplet x y)\"  \\<leftharpoondown> \"_Update (\\<lambda>u. CONST None) (_maplet x y)\"\n  \"_Map (_updbinds m (_maplet x y))\"  \\<leftharpoondown> \"_Update (_Map m) (_maplet x y)\"\n\ntext \\<open>Updating with lists:\\<close>\n\nprimrec map_of :: \"('a \\<times> 'b) list \\<Rightarrow> 'a \\<rightharpoonup> 'b\" where\n  \"map_of [] = empty\"\n| \"map_of (p # ps) = (map_of ps)(fst p \\<mapsto> snd p)\"\n\nlemma map_of_Cons_code [code]:\n  \"map_of [] k = None\"\n  \"map_of ((l, v) # ps) k = (if l = k then Some v else map_of ps k)\"\n  by simp_all\n\ndefinition map_upds :: \"('a \\<rightharpoonup> 'b) \\<Rightarrow> 'a list \\<Rightarrow> 'b list \\<Rightarrow> 'a \\<rightharpoonup> 'b\" where\n\"map_upds m xs ys = m ++ map_of (rev (zip xs ys))\"\n\ntext \\<open>There is also the more specialized update syntax \\<open>xs [\\<mapsto>] ys\\<close> for lists \\<open>xs\\<close> and \\<open>ys\\<close>.\\<close>\n\nsyntax\n  \"_maplets\"  :: \"['a, 'a] \\<Rightarrow> maplet\"             (\"_ /[\\<mapsto>]/ _\")\n\nsyntax (ASCII)\n  \"_maplets\" :: \"['a, 'a] \\<Rightarrow> maplet\"             (\"_ /[|->]/ _\")\n\ntranslations\n  \"_Update m (_maplets xs ys)\" \\<rightleftharpoons> \"CONST map_upds m xs ys\"\n\n  \"_Map (_maplets xs ys)\"  \\<leftharpoondown> \"_Update (\\<lambda>u. CONST None) (_maplets xs ys)\"\n  \"_Map (_updbinds m (_maplets xs ys))\"  \\<leftharpoondown> \"_Update (_Map m) (_maplets xs ys)\"\n\n\nsubsection \\<open>@{term [source] empty}\\<close>\n\nlemma empty_upd_none [simp]: \"empty(x := None) = empty\"\n  by (rule ext) simp\n\n\nsubsection \\<open>@{term [source] map_upd}\\<close>\n\nlemma map_upd_triv: \"t k = Some x \\<Longrightarrow> t(k\\<mapsto>x) = t\"\n  by (rule ext) simp\n\nlemma map_upd_nonempty [simp]: \"t(k\\<mapsto>x) \\<noteq> empty\"\nproof\n  assume \"t(k \\<mapsto> x) = empty\"\n  then have \"(t(k \\<mapsto> x)) k = None\" by simp\n  then show False by simp\nqed\n\nlemma map_upd_eqD1:\n  assumes \"m(a\\<mapsto>x) = n(a\\<mapsto>y)\"\n  shows \"x = y\"\nproof -\n  from assms have \"(m(a\\<mapsto>x)) a = (n(a\\<mapsto>y)) a\" by simp\n  then show ?thesis by simp\nqed\n\nlemma map_upd_Some_unfold:\n  \"((m(a\\<mapsto>b)) x = Some y) = (x = a \\<and> b = y \\<or> x \\<noteq> a \\<and> m x = Some y)\"\n  by auto\n\nlemma image_map_upd [simp]: \"x \\<notin> A \\<Longrightarrow> m(x \\<mapsto> y) ` A = m ` A\"\n  by auto\n\nlemma finite_range_updI:\n  assumes \"finite (range f)\" shows \"finite (range (f(a\\<mapsto>b)))\"\nproof -\n  have \"range (f(a\\<mapsto>b)) \\<subseteq> insert (Some b) (range f)\"\n    by auto\n  then show ?thesis\n    by (rule finite_subset) (use assms in auto)\nqed\n\n\nsubsection \\<open>@{term [source] map_of}\\<close>\n\nlemma map_of_eq_empty_iff [simp]:\n  \"map_of xys = empty \\<longleftrightarrow> xys = []\"\nproof\n  show \"map_of xys = empty \\<Longrightarrow> xys = []\"\n    by (induction xys) simp_all\nqed simp\n\nlemma empty_eq_map_of_iff [simp]:\n  \"empty = map_of xys \\<longleftrightarrow> xys = []\"\nby(subst eq_commute) simp\n\nlemma map_of_eq_None_iff:\n  \"(map_of xys x = None) = (x \\<notin> fst ` (set xys))\"\nby (induct xys) simp_all\n\nlemma map_of_eq_Some_iff [simp]:\n  \"distinct(map fst xys) \\<Longrightarrow> (map_of xys x = Some y) = ((x,y) \\<in> set xys)\"\nproof (induct xys)\n  case (Cons xy xys)\n  then show ?case\n    by (cases xy) (auto simp flip: map_of_eq_None_iff)\nqed auto\n\nlemma Some_eq_map_of_iff [simp]:\n  \"distinct(map fst xys) \\<Longrightarrow> (Some y = map_of xys x) = ((x,y) \\<in> set xys)\"\nby (auto simp del: map_of_eq_Some_iff simp: map_of_eq_Some_iff [symmetric])\n\nlemma map_of_is_SomeI [simp]: \n  \"\\<lbrakk>distinct(map fst xys); (x,y) \\<in> set xys\\<rbrakk> \\<Longrightarrow> map_of xys x = Some y\"\n  by simp\n\nlemma map_of_zip_is_None [simp]:\n  \"length xs = length ys \\<Longrightarrow> (map_of (zip xs ys) x = None) = (x \\<notin> set xs)\"\nby (induct rule: list_induct2) simp_all\n\nlemma map_of_zip_is_Some:\n  assumes \"length xs = length ys\"\n  shows \"x \\<in> set xs \\<longleftrightarrow> (\\<exists>y. map_of (zip xs ys) x = Some y)\"\nusing assms by (induct rule: list_induct2) simp_all\n\nlemma map_of_zip_upd:\n  fixes x :: 'a and xs :: \"'a list\" and ys zs :: \"'b list\"\n  assumes \"length ys = length xs\"\n    and \"length zs = length xs\"\n    and \"x \\<notin> set xs\"\n    and \"(map_of (zip xs ys))(x \\<mapsto> y) = (map_of (zip xs zs))(x \\<mapsto> z)\"\n  shows \"map_of (zip xs ys) = map_of (zip xs zs)\"\nproof\n  fix x' :: 'a\n  show \"map_of (zip xs ys) x' = map_of (zip xs zs) x'\"\n  proof (cases \"x = x'\")\n    case True\n    from assms True map_of_zip_is_None [of xs ys x']\n      have \"map_of (zip xs ys) x' = None\" by simp\n    moreover from assms True map_of_zip_is_None [of xs zs x']\n      have \"map_of (zip xs zs) x' = None\" by simp\n    ultimately show ?thesis by simp\n  next\n    case False from assms\n      have \"((map_of (zip xs ys))(x \\<mapsto> y)) x' = ((map_of (zip xs zs))(x \\<mapsto> z)) x'\" by auto\n    with False show ?thesis by simp\n  qed\nqed\n\nlemma map_of_zip_inject:\n  assumes \"length ys = length xs\"\n    and \"length zs = length xs\"\n    and dist: \"distinct xs\"\n    and map_of: \"map_of (zip xs ys) = map_of (zip xs zs)\"\n  shows \"ys = zs\"\n  using assms(1) assms(2)[symmetric]\n  using dist map_of\nproof (induct ys xs zs rule: list_induct3)\n  case Nil show ?case by simp\nnext\n  case (Cons y ys x xs z zs)\n  from \\<open>map_of (zip (x#xs) (y#ys)) = map_of (zip (x#xs) (z#zs))\\<close>\n    have map_of: \"(map_of (zip xs ys))(x \\<mapsto> y) = (map_of (zip xs zs))(x \\<mapsto> z)\" by simp\n  from Cons have \"length ys = length xs\" and \"length zs = length xs\"\n    and \"x \\<notin> set xs\" by simp_all\n  then have \"map_of (zip xs ys) = map_of (zip xs zs)\" using map_of by (rule map_of_zip_upd)\n  with Cons.hyps \\<open>distinct (x # xs)\\<close> have \"ys = zs\" by simp\n  moreover from map_of have \"y = z\" by (rule map_upd_eqD1)\n  ultimately show ?case by simp\nqed\n\nlemma map_of_zip_nth:\n  assumes \"length xs = length ys\"\n  assumes \"distinct xs\"\n  assumes \"i < length ys\"\n  shows \"map_of (zip xs ys) (xs ! i) = Some (ys ! i)\"\nusing assms proof (induct arbitrary: i rule: list_induct2)\n  case Nil\n  then show ?case by simp\nnext\n  case (Cons x xs y ys)\n  then show ?case\n    using less_Suc_eq_0_disj by auto\nqed\n\nlemma map_of_zip_map:\n  \"map_of (zip xs (map f xs)) = (\\<lambda>x. if x \\<in> set xs then Some (f x) else None)\"\n  by (induct xs) (simp_all add: fun_eq_iff)\n\nlemma finite_range_map_of: \"finite (range (map_of xys))\"\nproof (induct xys)\n  case (Cons a xys)\n  then show ?case\n    using finite_range_updI by fastforce\nqed auto\n\nlemma map_of_SomeD: \"map_of xs k = Some y \\<Longrightarrow> (k, y) \\<in> set xs\"\n  by (induct xs) (auto split: if_splits)\n\nlemma map_of_mapk_SomeI:\n  \"inj f \\<Longrightarrow> map_of t k = Some x \\<Longrightarrow>\n   map_of (map (case_prod (\\<lambda>k. Pair (f k))) t) (f k) = Some x\"\nby (induct t) (auto simp: inj_eq)\n\nlemma weak_map_of_SomeI: \"(k, x) \\<in> set l \\<Longrightarrow> \\<exists>x. map_of l k = Some x\"\nby (induct l) auto\n\nlemma map_of_filter_in:\n  \"map_of xs k = Some z \\<Longrightarrow> P k z \\<Longrightarrow> map_of (filter (case_prod P) xs) k = Some z\"\nby (induct xs) auto\n\nlemma map_of_map:\n  \"map_of (map (\\<lambda>(k, v). (k, f v)) xs) = map_option f \\<circ> map_of xs\"\n  by (induct xs) (auto simp: fun_eq_iff)\n\nlemma dom_map_option:\n  \"dom (\\<lambda>k. map_option (f k) (m k)) = dom m\"\n  by (simp add: dom_def)\n\nlemma dom_map_option_comp [simp]:\n  \"dom (map_option g \\<circ> m) = dom m\"\n  using dom_map_option [of \"\\<lambda>_. g\" m] by (simp add: comp_def)\n\n\nsubsection \\<open>\\<^const>\\<open>map_option\\<close> related\\<close>\n\nlemma map_option_o_empty [simp]: \"map_option f \\<circ> empty = empty\"\nby (rule ext) simp\n\nlemma map_option_o_map_upd [simp]:\n  \"map_option f \\<circ> m(a\\<mapsto>b) = (map_option f \\<circ> m)(a\\<mapsto>f b)\"\nby (rule ext) simp\n\n\nsubsection \\<open>@{term [source] map_comp} related\\<close>\n\nlemma map_comp_empty [simp]:\n  \"m \\<circ>\\<^sub>m empty = empty\"\n  \"empty \\<circ>\\<^sub>m m = empty\"\nby (auto simp: map_comp_def split: option.splits)\n\nlemma map_comp_simps [simp]:\n  \"m2 k = None \\<Longrightarrow> (m1 \\<circ>\\<^sub>m m2) k = None\"\n  \"m2 k = Some k' \\<Longrightarrow> (m1 \\<circ>\\<^sub>m m2) k = m1 k'\"\nby (auto simp: map_comp_def)\n\nlemma map_comp_Some_iff:\n  \"((m1 \\<circ>\\<^sub>m m2) k = Some v) = (\\<exists>k'. m2 k = Some k' \\<and> m1 k' = Some v)\"\nby (auto simp: map_comp_def split: option.splits)\n\nlemma map_comp_None_iff:\n  \"((m1 \\<circ>\\<^sub>m m2) k = None) = (m2 k = None \\<or> (\\<exists>k'. m2 k = Some k' \\<and> m1 k' = None)) \"\nby (auto simp: map_comp_def split: option.splits)\n\n\nsubsection \\<open>\\<open>++\\<close>\\<close>\n\nlemma map_add_empty[simp]: \"m ++ empty = m\"\nby(simp add: map_add_def)\n\nlemma empty_map_add[simp]: \"empty ++ m = m\"\nby (rule ext) (simp add: map_add_def split: option.split)\n\nlemma map_add_assoc[simp]: \"m1 ++ (m2 ++ m3) = (m1 ++ m2) ++ m3\"\nby (rule ext) (simp add: map_add_def split: option.split)\n\nlemma map_add_Some_iff:\n  \"((m ++ n) k = Some x) = (n k = Some x \\<or> n k = None \\<and> m k = Some x)\"\nby (simp add: map_add_def split: option.split)\n\nlemma map_add_SomeD [dest!]:\n  \"(m ++ n) k = Some x \\<Longrightarrow> n k = Some x \\<or> n k = None \\<and> m k = Some x\"\nby (rule map_add_Some_iff [THEN iffD1])\n\nlemma map_add_find_right [simp]: \"n k = Some xx \\<Longrightarrow> (m ++ n) k = Some xx\"\nby (subst map_add_Some_iff) fast\n\nlemma map_add_None [iff]: \"((m ++ n) k = None) = (n k = None \\<and> m k = None)\"\nby (simp add: map_add_def split: option.split)\n\nlemma map_add_upd[simp]: \"f ++ g(x\\<mapsto>y) = (f ++ g)(x\\<mapsto>y)\"\nby (rule ext) (simp add: map_add_def)\n\nlemma map_add_upds[simp]: \"m1 ++ (m2(xs[\\<mapsto>]ys)) = (m1++m2)(xs[\\<mapsto>]ys)\"\nby (simp add: map_upds_def)\n\nlemma map_add_upd_left: \"m\\<notin>dom e2 \\<Longrightarrow> e1(m \\<mapsto> u1) ++ e2 = (e1 ++ e2)(m \\<mapsto> u1)\"\nby (rule ext) (auto simp: map_add_def dom_def split: option.split)\n\nlemma map_of_append[simp]: \"map_of (xs @ ys) = map_of ys ++ map_of xs\"\n  unfolding map_add_def\nproof (induct xs)\n  case (Cons a xs)\n  then show ?case\n    by (force split: option.split)\nqed auto\n\nlemma finite_range_map_of_map_add:\n  \"finite (range f) \\<Longrightarrow> finite (range (f ++ map_of l))\"\nproof (induct l)\ncase (Cons a l)\n  then show ?case\n    by (metis finite_range_updI map_add_upd map_of.simps(2))\nqed auto\n\nlemma inj_on_map_add_dom [iff]:\n  \"inj_on (m ++ m') (dom m') = inj_on m' (dom m')\"\n  by (fastforce simp: map_add_def dom_def inj_on_def split: option.splits)\n\nlemma map_upds_fold_map_upd:\n  \"m(ks[\\<mapsto>]vs) = foldl (\\<lambda>m (k, v). m(k \\<mapsto> v)) m (zip ks vs)\"\nunfolding map_upds_def proof (rule sym, rule zip_obtain_same_length)\n  fix ks :: \"'a list\" and vs :: \"'b list\"\n  assume \"length ks = length vs\"\n  then show \"foldl (\\<lambda>m (k, v). m(k\\<mapsto>v)) m (zip ks vs) = m ++ map_of (rev (zip ks vs))\"\n    by(induct arbitrary: m rule: list_induct2) simp_all\nqed\n\nlemma map_add_map_of_foldr:\n  \"m ++ map_of ps = foldr (\\<lambda>(k, v) m. m(k \\<mapsto> v)) ps m\"\n  by (induct ps) (auto simp: fun_eq_iff map_add_def)\n\n\nsubsection \\<open>@{term [source] restrict_map}\\<close>\n\nlemma restrict_map_to_empty [simp]: \"m|`{} = empty\"\n  by (simp add: restrict_map_def)\n\nlemma restrict_map_insert: \"f |` (insert a A) = (f |` A)(a := f a)\"\n  by (auto simp: restrict_map_def)\n\nlemma restrict_map_empty [simp]: \"empty|`D = empty\"\n  by (simp add: restrict_map_def)\n\nlemma restrict_in [simp]: \"x \\<in> A \\<Longrightarrow> (m|`A) x = m x\"\n  by (simp add: restrict_map_def)\n\nlemma restrict_out [simp]: \"x \\<notin> A \\<Longrightarrow> (m|`A) x = None\"\n  by (simp add: restrict_map_def)\n\nlemma ran_restrictD: \"y \\<in> ran (m|`A) \\<Longrightarrow> \\<exists>x\\<in>A. m x = Some y\"\n  by (auto simp: restrict_map_def ran_def split: if_split_asm)\n\nlemma dom_restrict [simp]: \"dom (m|`A) = dom m \\<inter> A\"\n  by (auto simp: restrict_map_def dom_def split: if_split_asm)\n\nlemma restrict_upd_same [simp]: \"m(x\\<mapsto>y)|`(-{x}) = m|`(-{x})\"\n  by (rule ext) (auto simp: restrict_map_def)\n\nlemma restrict_restrict [simp]: \"m|`A|`B = m|`(A\\<inter>B)\"\n  by (rule ext) (auto simp: restrict_map_def)\n\nlemma restrict_fun_upd [simp]:\n  \"m(x := y)|`D = (if x \\<in> D then (m|`(D-{x}))(x := y) else m|`D)\"\n  by (simp add: restrict_map_def fun_eq_iff)\n\nlemma fun_upd_None_restrict [simp]:\n  \"(m|`D)(x := None) = (if x \\<in> D then m|`(D - {x}) else m|`D)\"\n  by (simp add: restrict_map_def fun_eq_iff)\n\nlemma fun_upd_restrict: \"(m|`D)(x := y) = (m|`(D-{x}))(x := y)\"\n  by (simp add: restrict_map_def fun_eq_iff)\n\nlemma fun_upd_restrict_conv [simp]:\n  \"x \\<in> D \\<Longrightarrow> (m|`D)(x := y) = (m|`(D-{x}))(x := y)\"\n  by (rule fun_upd_restrict)\n\nlemma map_of_map_restrict:\n  \"map_of (map (\\<lambda>k. (k, f k)) ks) = (Some \\<circ> f) |` set ks\"\n  by (induct ks) (simp_all add: fun_eq_iff restrict_map_insert)\n\nlemma restrict_complement_singleton_eq:\n  \"f |` (- {x}) = f(x := None)\"\n  by auto\n\n\nsubsection \\<open>@{term [source] map_upds}\\<close>\n\nlemma map_upds_Nil1 [simp]: \"m([] [\\<mapsto>] bs) = m\"\n  by (simp add: map_upds_def)\n\nlemma map_upds_Nil2 [simp]: \"m(as [\\<mapsto>] []) = m\"\n  by (simp add:map_upds_def)\n\nlemma map_upds_Cons [simp]: \"m(a#as [\\<mapsto>] b#bs) = (m(a\\<mapsto>b))(as[\\<mapsto>]bs)\"\n  by (simp add:map_upds_def)\n\nlemma map_upds_append1 [simp]:\n  \"size xs < size ys \\<Longrightarrow> m(xs@[x] [\\<mapsto>] ys) = m(xs [\\<mapsto>] ys, x \\<mapsto> ys!size xs)\"\nproof (induct xs arbitrary: ys m)\n  case Nil\n  then show ?case\n    by (auto simp: neq_Nil_conv)\nnext\n  case (Cons a xs)\n  then show ?case\n    by (cases ys) auto\nqed\n\nlemma map_upds_list_update2_drop [simp]:\n  \"size xs \\<le> i \\<Longrightarrow> m(xs[\\<mapsto>]ys[i:=y]) = m(xs[\\<mapsto>]ys)\"\nproof (induct xs arbitrary: m ys i)\n  case Nil\n  then show ?case\n    by auto\nnext\n  case (Cons a xs)\n  then show ?case\n    by (cases ys) (use Cons in \\<open>auto split: nat.split\\<close>)\nqed\n\ntext \\<open>Something weirdly sensitive about this proof, which needs only four lines in apply style\\<close>\nlemma map_upd_upds_conv_if:\n  \"(f(x\\<mapsto>y))(xs [\\<mapsto>] ys) =\n   (if x \\<in> set(take (length ys) xs) then f(xs [\\<mapsto>] ys)\n                                    else (f(xs [\\<mapsto>] ys))(x\\<mapsto>y))\"\nproof (induct xs arbitrary: x y ys f)\n  case (Cons a xs)\n  show ?case\n  proof (cases ys)\n    case (Cons z zs)\n    then show ?thesis\n      using Cons.hyps\n      apply (auto split: if_split simp: fun_upd_twist)\n      using Cons.hyps apply fastforce+\n      done\n  qed auto\nqed auto\n\n\nlemma map_upds_twist [simp]:\n  \"a \\<notin> set as \\<Longrightarrow> m(a\\<mapsto>b, as[\\<mapsto>]bs) = m(as[\\<mapsto>]bs, a\\<mapsto>b)\"\nusing set_take_subset by (fastforce simp add: map_upd_upds_conv_if)\n\nlemma map_upds_apply_nontin [simp]:\n  \"x \\<notin> set xs \\<Longrightarrow> (f(xs[\\<mapsto>]ys)) x = f x\"\nproof (induct xs arbitrary: ys)\n  case (Cons a xs)\n  then show ?case\n    by (cases ys) (auto simp: map_upd_upds_conv_if)\nqed auto\n\nlemma fun_upds_append_drop [simp]:\n  \"size xs = size ys \\<Longrightarrow> m(xs@zs[\\<mapsto>]ys) = m(xs[\\<mapsto>]ys)\"\nproof (induct xs arbitrary: ys)\n  case (Cons a xs)\n  then show ?case\n    by (cases ys) (auto simp: map_upd_upds_conv_if)\nqed auto\n\nlemma fun_upds_append2_drop [simp]:\n  \"size xs = size ys \\<Longrightarrow> m(xs[\\<mapsto>]ys@zs) = m(xs[\\<mapsto>]ys)\"\nproof (induct xs arbitrary: ys)\n  case (Cons a xs)\n  then show ?case\n    by (cases ys) (auto simp: map_upd_upds_conv_if)\nqed auto\n\nlemma restrict_map_upds[simp]:\n  \"\\<lbrakk> length xs = length ys; set xs \\<subseteq> D \\<rbrakk>\n    \\<Longrightarrow> m(xs [\\<mapsto>] ys)|`D = (m|`(D - set xs))(xs [\\<mapsto>] ys)\"\nproof (induct xs arbitrary: m ys)\n  case (Cons a xs)\n  then show ?case\n  proof (cases ys)\n    case (Cons z zs)\n    with Cons.hyps Cons.prems show ?thesis\n      apply (simp add: insert_absorb flip: Diff_insert)\n      apply (auto simp add: map_upd_upds_conv_if)\n      done\n  qed auto\nqed auto\n\n\nsubsection \\<open>@{term [source] dom}\\<close>\n\nlemma dom_eq_empty_conv [simp]: \"dom f = {} \\<longleftrightarrow> f = empty\"\n  by (auto simp: dom_def)\n\nlemma domI: \"m a = Some b \\<Longrightarrow> a \\<in> dom m\"\n  by (simp add: dom_def)\n(* declare domI [intro]? *)\n\nlemma domD: \"a \\<in> dom m \\<Longrightarrow> \\<exists>b. m a = Some b\"\n  by (cases \"m a\") (auto simp add: dom_def)\n\nlemma domIff [iff, simp del, code_unfold]: \"a \\<in> dom m \\<longleftrightarrow> m a \\<noteq> None\"\n  by (simp add: dom_def)\n\nlemma dom_empty [simp]: \"dom empty = {}\"\n  by (simp add: dom_def)\n\nlemma dom_fun_upd [simp]:\n  \"dom(f(x := y)) = (if y = None then dom f - {x} else insert x (dom f))\"\n  by (auto simp: dom_def)\n\nlemma dom_if:\n  \"dom (\\<lambda>x. if P x then f x else g x) = dom f \\<inter> {x. P x} \\<union> dom g \\<inter> {x. \\<not> P x}\"\n  by (auto split: if_splits)\n\nlemma dom_map_of_conv_image_fst:\n  \"dom (map_of xys) = fst ` set xys\"\n  by (induct xys) (auto simp add: dom_if)\n\nlemma dom_map_of_zip [simp]: \"length xs = length ys \\<Longrightarrow> dom (map_of (zip xs ys)) = set xs\"\n  by (induct rule: list_induct2) (auto simp: dom_if)\n\nlemma finite_dom_map_of: \"finite (dom (map_of l))\"\n  by (induct l) (auto simp: dom_def insert_Collect [symmetric])\n\nlemma dom_map_upds [simp]:\n  \"dom(m(xs[\\<mapsto>]ys)) = set(take (length ys) xs) \\<union> dom m\"\nproof (induct xs arbitrary: ys)\n  case (Cons a xs)\n  then show ?case\n    by (cases ys) (auto simp: map_upd_upds_conv_if)\nqed auto\n\n\nlemma dom_map_add [simp]: \"dom (m ++ n) = dom n \\<union> dom m\"\n  by (auto simp: dom_def)\n\nlemma dom_override_on [simp]:\n  \"dom (override_on f g A) =\n    (dom f  - {a. a \\<in> A - dom g}) \\<union> {a. a \\<in> A \\<inter> dom g}\"\n  by (auto simp: dom_def override_on_def)\n\n\n\nlemma map_add_dom_app_simps:\n  \"m \\<in> dom l2 \\<Longrightarrow> (l1 ++ l2) m = l2 m\"\n  \"m \\<notin> dom l1 \\<Longrightarrow> (l1 ++ l2) m = l2 m\"\n  \"m \\<notin> dom l2 \\<Longrightarrow> (l1 ++ l2) m = l1 m\"\n  by (auto simp add: map_add_def split: option.split_asm)\n\nlemma dom_const [simp]:\n  \"dom (\\<lambda>x. Some (f x)) = UNIV\"\n  by auto\n\n(* Due to John Matthews - could be rephrased with dom *)\nlemma finite_map_freshness:\n  \"finite (dom (f :: 'a \\<rightharpoonup> 'b)) \\<Longrightarrow> \\<not> finite (UNIV :: 'a set) \\<Longrightarrow>\n   \\<exists>x. f x = None\"\n  by (bestsimp dest: ex_new_if_finite)\n\nlemma dom_minus:\n  \"f x = None \\<Longrightarrow> dom f - insert x A = dom f - A\"\n  unfolding dom_def by simp\n\nlemma insert_dom:\n  \"f x = Some y \\<Longrightarrow> insert x (dom f) = dom f\"\n  unfolding dom_def by auto\n\nlemma map_of_map_keys:\n  \"set xs = dom m \\<Longrightarrow> map_of (map (\\<lambda>k. (k, the (m k))) xs) = m\"\n  by (rule ext) (auto simp add: map_of_map_restrict restrict_map_def)\n\nlemma map_of_eqI:\n  assumes set_eq: \"set (map fst xs) = set (map fst ys)\"\n  assumes map_eq: \"\\<forall>k\\<in>set (map fst xs). map_of xs k = map_of ys k\"\n  shows \"map_of xs = map_of ys\"\nproof (rule ext)\n  fix k show \"map_of xs k = map_of ys k\"\n  proof (cases \"map_of xs k\")\n    case None\n    then have \"k \\<notin> set (map fst xs)\" by (simp add: map_of_eq_None_iff)\n    with set_eq have \"k \\<notin> set (map fst ys)\" by simp\n    then have \"map_of ys k = None\" by (simp add: map_of_eq_None_iff)\n    with None show ?thesis by simp\n  next\n    case (Some v)\n    then have \"k \\<in> set (map fst xs)\" by (auto simp add: dom_map_of_conv_image_fst [symmetric])\n    with map_eq show ?thesis by auto\n  qed\nqed\n\nlemma map_of_eq_dom:\n  assumes \"map_of xs = map_of ys\"\n  shows \"fst ` set xs = fst ` set ys\"\nproof -\n  from assms have \"dom (map_of xs) = dom (map_of ys)\" by simp\n  then show ?thesis by (simp add: dom_map_of_conv_image_fst)\nqed\n\nlemma finite_set_of_finite_maps:\n  assumes \"finite A\" \"finite B\"\n  shows \"finite {m. dom m = A \\<and> ran m \\<subseteq> B}\" (is \"finite ?S\")\nproof -\n  let ?S' = \"{m. \\<forall>x. (x \\<in> A \\<longrightarrow> m x \\<in> Some ` B) \\<and> (x \\<notin> A \\<longrightarrow> m x = None)}\"\n  have \"?S = ?S'\"\n  proof\n    show \"?S \\<subseteq> ?S'\" by (auto simp: dom_def ran_def image_def)\n    show \"?S' \\<subseteq> ?S\"\n    proof\n      fix m assume \"m \\<in> ?S'\"\n      hence 1: \"dom m = A\" by force\n      hence 2: \"ran m \\<subseteq> B\" using \\<open>m \\<in> ?S'\\<close> by (auto simp: dom_def ran_def)\n      from 1 2 show \"m \\<in> ?S\" by blast\n    qed\n  qed\n  with assms show ?thesis by(simp add: finite_set_of_finite_funs)\nqed\n\n\nsubsection \\<open>@{term [source] ran}\\<close>\n\nlemma ranI: \"m a = Some b \\<Longrightarrow> b \\<in> ran m\"\n  by (auto simp: ran_def)\n(* declare ranI [intro]? *)\n\nlemma ran_empty [simp]: \"ran empty = {}\"\n  by (auto simp: ran_def)\n\nlemma ran_map_upd [simp]:  \"m a = None \\<Longrightarrow> ran(m(a\\<mapsto>b)) = insert b (ran m)\"\n  unfolding ran_def\n  by force\n\nlemma fun_upd_None_if_notin_dom[simp]: \"k \\<notin> dom m \\<Longrightarrow> m(k := None) = m\"\n  by auto\n\nlemma ran_map_upd_Some:\n  \"\\<lbrakk> m x = Some y; inj_on m (dom m); z \\<notin> ran m \\<rbrakk> \\<Longrightarrow> ran(m(x := Some z)) = ran m - {y} \\<union> {z}\"\nby(force simp add: ran_def domI inj_onD)\n\nlemma ran_map_add:\n  assumes \"dom m1 \\<inter> dom m2 = {}\"\n  shows \"ran (m1 ++ m2) = ran m1 \\<union> ran m2\"\nproof\n  show \"ran (m1 ++ m2) \\<subseteq> ran m1 \\<union> ran m2\"\n    unfolding ran_def by auto\nnext\n  show \"ran m1 \\<union> ran m2 \\<subseteq> ran (m1 ++ m2)\"\n  proof -\n    have \"(m1 ++ m2) x = Some y\" if \"m1 x = Some y\" for x y\n      using assms map_add_comm that by fastforce\n    moreover have \"(m1 ++ m2) x = Some y\" if \"m2 x = Some y\" for x y\n      using assms that by auto\n    ultimately show ?thesis\n      unfolding ran_def by blast\n  qed\nqed\n\nlemma finite_ran:\n  assumes \"finite (dom p)\"\n  shows \"finite (ran p)\"\nproof -\n  have \"ran p = (\\<lambda>x. the (p x)) ` dom p\"\n    unfolding ran_def by force\n  from this \\<open>finite (dom p)\\<close> show ?thesis by auto\nqed\n\nlemma ran_distinct:\n  assumes dist: \"distinct (map fst al)\"\n  shows \"ran (map_of al) = snd ` set al\"\n  using assms\nproof (induct al)\n  case Nil\n  then show ?case by simp\nnext\n  case (Cons kv al)\n  then have \"ran (map_of al) = snd ` set al\" by simp\n  moreover from Cons.prems have \"map_of al (fst kv) = None\"\n    by (simp add: map_of_eq_None_iff)\n  ultimately show ?case by (simp only: map_of.simps ran_map_upd) simp\nqed\n\nlemma ran_map_of_zip:\n  assumes \"length xs = length ys\" \"distinct xs\"\n  shows \"ran (map_of (zip xs ys)) = set ys\"\nusing assms by (simp add: ran_distinct set_map[symmetric])\n\nlemma ran_map_option: \"ran (\\<lambda>x. map_option f (m x)) = f ` ran m\"\n  by (auto simp add: ran_def)\n\nsubsection \\<open>@{term [source] graph}\\<close>\n\n\n\nlemma in_graphI: \"m k = Some v \\<Longrightarrow> (k, v) \\<in> graph m\"\n  unfolding graph_def by blast\n\nlemma in_graphD: \"(k, v) \\<in> graph m \\<Longrightarrow> m k = Some v\"\n  unfolding graph_def by blast\n\nlemma graph_map_upd[simp]: \"graph (m(k \\<mapsto> v)) = insert (k, v) (graph (m(k := None)))\"\n  unfolding graph_def by (auto split: if_splits)\n\nlemma graph_fun_upd_None: \"graph (m(k := None)) = {e \\<in> graph m. fst e \\<noteq> k}\"\n  unfolding graph_def by (auto split: if_splits)\n\nlemma graph_restrictD:\n  assumes \"(k, v) \\<in> graph (m |` A)\"\n  shows \"k \\<in> A\" and \"m k = Some v\"\n  using assms unfolding graph_def\n  by (auto simp: restrict_map_def split: if_splits)\n\nlemma graph_map_comp[simp]: \"graph (m1 \\<circ>\\<^sub>m m2) = graph m2 O graph m1\"\n  unfolding graph_def by (auto simp: map_comp_Some_iff relcomp_unfold)\n\nlemma graph_map_add: \"dom m1 \\<inter> dom m2 = {} \\<Longrightarrow> graph (m1 ++ m2) = graph m1 \\<union> graph m2\"\n  unfolding graph_def using map_add_comm by force\n\nlemma graph_eq_to_snd_dom: \"graph m = (\\<lambda>x. (x, the (m x))) ` dom m\"\n  unfolding graph_def dom_def by force\n\nlemma fst_graph_eq_dom: \"fst ` graph m = dom m\"\n  unfolding graph_eq_to_snd_dom by force\n\nlemma graph_domD: \"x \\<in> graph m \\<Longrightarrow> fst x \\<in> dom m\"\n  using fst_graph_eq_dom by (metis imageI)\n\nlemma snd_graph_ran: \"snd ` graph m = ran m\"\n  unfolding graph_def ran_def by force\n\nlemma graph_ranD: \"x \\<in> graph m \\<Longrightarrow> snd x \\<in> ran m\"\n  using snd_graph_ran by (metis imageI)\n\nlemma finite_graph_map_of: \"finite (graph (map_of al))\"\n  unfolding graph_eq_to_snd_dom finite_dom_map_of\n  using finite_dom_map_of by blast\n\nlemma graph_map_of_if_distinct_dom: \"distinct (map fst al) \\<Longrightarrow> graph (map_of al) = set al\"\n  unfolding graph_def by auto\n\nlemma finite_graph_iff_finite_dom[simp]: \"finite (graph m) = finite (dom m)\"\n  by (metis graph_eq_to_snd_dom finite_imageI fst_graph_eq_dom)\n\nlemma inj_on_fst_graph: \"inj_on fst (graph m)\"\n  unfolding graph_def inj_on_def by force\n\nsubsection \\<open>\\<open>map_le\\<close>\\<close>\n\nlemma map_le_empty [simp]: \"empty \\<subseteq>\\<^sub>m g\"\n  by (simp add: map_le_def)\n\nlemma upd_None_map_le [simp]: \"f(x := None) \\<subseteq>\\<^sub>m f\"\n  by (force simp add: map_le_def)\n\nlemma map_le_upd[simp]: \"f \\<subseteq>\\<^sub>m g ==> f(a := b) \\<subseteq>\\<^sub>m g(a := b)\"\n  by (fastforce simp add: map_le_def)\n\nlemma map_le_imp_upd_le [simp]: \"m1 \\<subseteq>\\<^sub>m m2 \\<Longrightarrow> m1(x := None) \\<subseteq>\\<^sub>m m2(x \\<mapsto> y)\"\n  by (force simp add: map_le_def)\n\nlemma map_le_upds [simp]:\n  \"f \\<subseteq>\\<^sub>m g \\<Longrightarrow> f(as [\\<mapsto>] bs) \\<subseteq>\\<^sub>m g(as [\\<mapsto>] bs)\"\nproof (induct as arbitrary: f g bs)\n  case (Cons a as)\n  then show ?case\n    by (cases bs) (use Cons in auto)\nqed auto\n\nlemma map_le_implies_dom_le: \"(f \\<subseteq>\\<^sub>m g) \\<Longrightarrow> (dom f \\<subseteq> dom g)\"\n  by (fastforce simp add: map_le_def dom_def)\n\nlemma map_le_refl [simp]: \"f \\<subseteq>\\<^sub>m f\"\n  by (simp add: map_le_def)\n\nlemma map_le_trans[trans]: \"\\<lbrakk> m1 \\<subseteq>\\<^sub>m m2; m2 \\<subseteq>\\<^sub>m m3\\<rbrakk> \\<Longrightarrow> m1 \\<subseteq>\\<^sub>m m3\"\n  by (auto simp add: map_le_def dom_def)\n\nlemma map_le_antisym: \"\\<lbrakk> f \\<subseteq>\\<^sub>m g; g \\<subseteq>\\<^sub>m f \\<rbrakk> \\<Longrightarrow> f = g\"\n  unfolding map_le_def\n  by (metis ext domIff)\n\nlemma map_le_map_add [simp]: \"f \\<subseteq>\\<^sub>m g ++ f\"\n  by (fastforce simp: map_le_def)\n\nlemma map_le_iff_map_add_commute: \"f \\<subseteq>\\<^sub>m f ++ g \\<longleftrightarrow> f ++ g = g ++ f\"\n  by (fastforce simp: map_add_def map_le_def fun_eq_iff split: option.splits)\n\nlemma map_add_le_mapE: \"f ++ g \\<subseteq>\\<^sub>m h \\<Longrightarrow> g \\<subseteq>\\<^sub>m h\"\n  by (fastforce simp: map_le_def map_add_def dom_def)\n\nlemma map_add_le_mapI: \"\\<lbrakk> f \\<subseteq>\\<^sub>m h; g \\<subseteq>\\<^sub>m h \\<rbrakk> \\<Longrightarrow> f ++ g \\<subseteq>\\<^sub>m h\"\n  by (auto simp: map_le_def map_add_def dom_def split: option.splits)\n\nlemma map_add_subsumed1: \"f \\<subseteq>\\<^sub>m g \\<Longrightarrow> f++g = g\"\nby (simp add: map_add_le_mapI map_le_antisym)\n\nlemma map_add_subsumed2: \"f \\<subseteq>\\<^sub>m g \\<Longrightarrow> g++f = g\"\nby (metis map_add_subsumed1 map_le_iff_map_add_commute)\n\nlemma dom_eq_singleton_conv: \"dom f = {x} \\<longleftrightarrow> (\\<exists>v. f = [x \\<mapsto> v])\"\n  (is \"?lhs \\<longleftrightarrow> ?rhs\")\nproof\n  assume ?rhs\n  then show ?lhs by (auto split: if_split_asm)\nnext\n  assume ?lhs\n  then obtain v where v: \"f x = Some v\" by auto\n  show ?rhs\n  proof\n    show \"f = [x \\<mapsto> v]\"\n    proof (rule map_le_antisym)\n      show \"[x \\<mapsto> v] \\<subseteq>\\<^sub>m f\"\n        using v by (auto simp add: map_le_def)\n      show \"f \\<subseteq>\\<^sub>m [x \\<mapsto> v]\"\n        using \\<open>dom f = {x}\\<close> \\<open>f x = Some v\\<close> by (auto simp add: map_le_def)\n    qed\n  qed\nqed\n\nlemma map_add_eq_empty_iff[simp]:\n  \"(f++g = empty) \\<longleftrightarrow> f = empty \\<and> g = empty\"\nby (metis map_add_None)\n\nlemma empty_eq_map_add_iff[simp]:\n  \"(empty = f++g) \\<longleftrightarrow> f = empty \\<and> g = empty\"\nby(subst map_add_eq_empty_iff[symmetric])(rule eq_commute)\n\n\nsubsection \\<open>Various\\<close>\n\nlemma set_map_of_compr:\n  assumes distinct: \"distinct (map fst xs)\"\n  shows \"set xs = {(k, v). map_of xs k = Some v}\"\n  using assms\nproof (induct xs)\n  case Nil\n  then show ?case by simp\nnext\n  case (Cons x xs)\n  obtain k v where \"x = (k, v)\" by (cases x) blast\n  with Cons.prems have \"k \\<notin> dom (map_of xs)\"\n    by (simp add: dom_map_of_conv_image_fst)\n  then have *: \"insert (k, v) {(k, v). map_of xs k = Some v} =\n    {(k', v'). ((map_of xs)(k \\<mapsto> v)) k' = Some v'}\"\n    by (auto split: if_splits)\n  from Cons have \"set xs = {(k, v). map_of xs k = Some v}\" by simp\n  with * \\<open>x = (k, v)\\<close> show ?case by simp\nqed\n\nlemma eq_key_imp_eq_value:\n  \"v1 = v2\"\n  if \"distinct (map fst xs)\" \"(k, v1) \\<in> set xs\" \"(k, v2) \\<in> set xs\"\nproof -\n  from that have \"inj_on fst (set xs)\"\n    by (simp add: distinct_map)\n  moreover have \"fst (k, v1) = fst (k, v2)\"\n    by simp\n  ultimately have \"(k, v1) = (k, v2)\"\n    by (rule inj_onD) (fact that)+\n  then show ?thesis\n    by simp\nqed\n\nlemma map_of_inject_set:\n  assumes distinct: \"distinct (map fst xs)\" \"distinct (map fst ys)\"\n  shows \"map_of xs = map_of ys \\<longleftrightarrow> set xs = set ys\" (is \"?lhs \\<longleftrightarrow> ?rhs\")\nproof\n  assume ?lhs\n  moreover from \\<open>distinct (map fst xs)\\<close> have \"set xs = {(k, v). map_of xs k = Some v}\"\n    by (rule set_map_of_compr)\n  moreover from \\<open>distinct (map fst ys)\\<close> have \"set ys = {(k, v). map_of ys k = Some v}\"\n    by (rule set_map_of_compr)\n  ultimately show ?rhs by simp\nnext\n  assume ?rhs show ?lhs\n  proof\n    fix k\n    show \"map_of xs k = map_of ys k\"\n    proof (cases \"map_of xs k\")\n      case None\n      with \\<open>?rhs\\<close> have \"map_of ys k = None\"\n        by (simp add: map_of_eq_None_iff)\n      with None show ?thesis by simp\n    next\n      case (Some v)\n      with distinct \\<open>?rhs\\<close> have \"map_of ys k = Some v\"\n        by simp\n      with Some show ?thesis by simp\n    qed\n  qed\nqed\n\nlemma finite_Map_induct[consumes 1, case_names empty update]:\n  assumes \"finite (dom m)\"\n  assumes \"P Map.empty\"\n  assumes \"\\<And>k v m. finite (dom m) \\<Longrightarrow> k \\<notin> dom m \\<Longrightarrow> P m \\<Longrightarrow> P (m(k \\<mapsto> v))\"\n  shows \"P m\"\n  using assms(1)\nproof(induction \"dom m\" arbitrary: m rule: finite_induct)\n  case empty\n  then show ?case using assms(2) unfolding dom_def by simp\nnext\n  case (insert x F) \n  then have \"finite (dom (m(x:=None)))\" \"x \\<notin> dom (m(x:=None))\" \"P (m(x:=None))\"\n    by (metis Diff_insert_absorb dom_fun_upd)+\n  with assms(3)[OF this] show ?case\n    by (metis fun_upd_triv fun_upd_upd option.exhaust)\nqed\n\nhide_const (open) Map.empty Map.graph\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/Map.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.843895106480586, "lm_q2_score": 0.8397339676722393, "lm_q1q2_score": 0.7086473860641294}}
{"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\nimports 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\n  monofun :: \"('a \\<Rightarrow> 'b) \\<Rightarrow> bool\"  \\<comment> \"monotonicity\"  where\n  \"monofun f = (\\<forall>x y. x \\<sqsubseteq> y \\<longrightarrow> f x \\<sqsubseteq> f y)\"\n\ndefinition\n  cont :: \"('a::cpo \\<Rightarrow> 'b::cpo) \\<Rightarrow> bool\"\nwhere\n  \"cont f = (\\<forall>Y. chain Y \\<longrightarrow> range (\\<lambda>i. f (Y i)) <<| f (\\<Squnion>i. Y i))\"\n\nlemma contI:\n  \"\\<lbrakk>\\<And>Y. chain Y \\<Longrightarrow> range (\\<lambda>i. f (Y i)) <<| f (\\<Squnion>i. Y i)\\<rbrakk> \\<Longrightarrow> cont f\"\nby (simp add: cont_def)\n\nlemma contE:\n  \"\\<lbrakk>cont f; chain Y\\<rbrakk> \\<Longrightarrow> range (\\<lambda>i. f (Y i)) <<| f (\\<Squnion>i. Y i)\"\nby (simp add: cont_def)\n\nlemma monofunI: \n  \"\\<lbrakk>\\<And>x y. x \\<sqsubseteq> y \\<Longrightarrow> f x \\<sqsubseteq> f y\\<rbrakk> \\<Longrightarrow> monofun f\"\nby (simp add: monofun_def)\n\nlemma monofunE: \n  \"\\<lbrakk>monofun f; x \\<sqsubseteq> y\\<rbrakk> \\<Longrightarrow> f x \\<sqsubseteq> f y\"\nby (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: \"\\<lbrakk>monofun f; chain Y\\<rbrakk> \\<Longrightarrow> chain (\\<lambda>i. f (Y i))\"\napply (rule chainI)\napply (erule monofunE)\napply (erule chainE)\ndone\n\ntext \\<open>monotone functions map upper bound to upper bounds\\<close>\n\nlemma ub2ub_monofun: \n  \"\\<lbrakk>monofun f; range Y <| u\\<rbrakk> \\<Longrightarrow> range (\\<lambda>i. f (Y i)) <| f u\"\napply (rule ub_rangeI)\napply (erule monofunE)\napply (erule ub_rangeD)\ndone\n\ntext \\<open>a lemma about binary chains\\<close>\n\nlemma binchain_cont:\n  \"\\<lbrakk>cont f; x \\<sqsubseteq> y\\<rbrakk> \\<Longrightarrow> range (\\<lambda>i::nat. f (if i = 0 then x else y)) <<| f y\"\napply (subgoal_tac \"f (\\<Squnion>i::nat. if i = 0 then x else y) = f y\")\napply (erule subst)\napply (erule contE)\napply (erule bin_chain)\napply (rule_tac f=f in arg_cong)\napply (erule is_lub_bin_chain [THEN lub_eqI])\ndone\n\ntext \\<open>continuity implies monotonicity\\<close>\n\nlemma cont2mono: \"cont f \\<Longrightarrow> monofun f\"\napply (rule monofunI)\napply (drule (1) binchain_cont)\napply (drule_tac i=0 in is_lub_rangeD1)\napply simp\ndone\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:\n  \"\\<lbrakk>cont f; chain Y\\<rbrakk> \\<Longrightarrow> f (\\<Squnion>i. Y i) = (\\<Squnion>i. f (Y i))\"\napply (rule lub_eqI [symmetric])\napply (erule (1) contE)\ndone\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>\n     \\<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\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)\"\napply (rule contI)\napply (erule cpo_lubI)\ndone\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\" 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\" 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:\n  \"\\<lbrakk>cont c; cont (\\<lambda>x. f x)\\<rbrakk> \\<Longrightarrow> cont (\\<lambda>x. c (f x))\"\nby (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)\" and cont: \"\\<And>i. cont (\\<lambda>x. F i x)\"\n  shows \"cont (\\<lambda>x. \\<Squnion>i. F i x)\"\napply (rule contI2)\napply (simp add: monofunI cont2monofunE [OF cont] lub_mono chain)\napply (simp add: cont2contlubE [OF cont])\napply (simp add: diag_lub ch2ch_cont [OF cont] chain)\ndone\n\ntext \\<open>if-then-else is continuous\\<close>\n\nlemma cont_if [simp, cont2cont]:\n  \"\\<lbrakk>cont f; cont g\\<rbrakk> \\<Longrightarrow> cont (\\<lambda>x. if b then f x else g x)\"\nby (induct b) simp_all\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:\n  \"\\<lbrakk>monofun f; finite_chain Y\\<rbrakk> \\<Longrightarrow> finite_chain (\\<lambda>n. f (Y n))\"\napply (unfold finite_chain_def)\napply (simp add: ch2ch_monofun)\napply (force simp add: max_in_chain_def)\ndone\n\ntext \\<open>The same holds for continuous functions.\\<close>\n\nlemma cont_finch2finch:\n  \"\\<lbrakk>cont f; finite_chain Y\\<rbrakk> \\<Longrightarrow> finite_chain (\\<lambda>n. f (Y n))\"\nby (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::'a::chfin \\<Rightarrow> 'b::cpo)\"\napply (erule contI2)\napply (frule chfin2finch)\napply (clarsimp simp add: finite_chain_def)\napply (subgoal_tac \"max_in_chain i (\\<lambda>i. f (Y i))\")\napply (simp add: maxinch_is_thelub ch2ch_monofun)\napply (force simp add: max_in_chain_def)\ndone\n\ntext \\<open>All strict functions with flat domain are continuous.\\<close>\n\nlemma flatdom_strict2mono: \"f \\<bottom> = \\<bottom> \\<Longrightarrow> monofun (f::'a::flat \\<Rightarrow> 'b::pcpo)\"\napply (rule monofunI)\napply (drule ax_flat)\napply auto\ndone\n\nlemma flatdom_strict2cont: \"f \\<bottom> = \\<bottom> \\<Longrightarrow> cont (f::'a::flat \\<Rightarrow> 'b::pcpo)\"\nby (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::'a::discrete_cpo \\<Rightarrow> 'b::cpo)\"\napply (rule contI)\napply (drule discrete_chain_const, clarify)\napply (simp add: is_lub_const)\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/HOLCF/Cont.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8438950868503681, "lm_q2_score": 0.8397339716830606, "lm_q1q2_score": 0.7086473729646809}}
{"text": "theory NaNoCop imports Main\nbegin\n\nprimrec member (infix\\<open>|\\<in>|\\<close> 200) where\n  \\<open>(_ |\\<in>| []) = False\\<close> |\n  \\<open>(x |\\<in>| (x' # xs)) = ((x = x') \\<or> (x |\\<in>| xs))\\<close>\n\nlemma member_simp[simp]: \\<open>x |\\<in>| xs \\<longleftrightarrow> x \\<in> (set xs)\\<close> \n  by (induct xs) simp_all\n\nabbreviation notmember (infix \\<open>|\\<notin>|\\<close> 200) where \\<open>x |\\<notin>| xs \\<equiv> \\<not> x |\\<in>| xs\\<close>\n\ndefinition \\<open>linsert x xs \\<equiv> (if (x |\\<in>| xs) then xs else x # xs)\\<close>\n\nlemma linsert_is_insert: \\<open>set (linsert x xs) = insert x (set xs)\\<close>\n  by (induct xs) (simp_all add: linsert_def insert_absorb)\n\nprimrec subseteq (infix \\<open>|\\<subseteq>|\\<close> 120) where\n  \\<open>([] |\\<subseteq>| _) = True\\<close> |\n  \\<open>((x # xs) |\\<subseteq>| ys) = ((x |\\<in>| ys) \\<and> (xs |\\<subseteq>| ys))\\<close>\n\nlemma subseteq_simp[simp]: \\<open>xs |\\<subseteq>| ys \\<longleftrightarrow> (set xs) \\<subseteq> (set ys)\\<close> \n  by (induct xs) simp_all\n\nprimrec lremove where\n  \\<open>lremove _ [] = []\\<close> |\n  \\<open>lremove x (y # ys) = (if y = x then lremove x ys else y # (lremove x ys))\\<close>\n\nlemma lremove_simp[simp]: \\<open>set (lremove x xs) = (set xs) - {x}\\<close>\n  by (induct xs) (simp_all add: insert_Diff_if)\n  \nprimrec lminus (infix \\<open>|-|\\<close> 210) where\n  \\<open>xs |-| [] = xs\\<close> |\n  \\<open>xs |-| (y # ys) = (lremove y xs) |-| ys\\<close>\n\nlemma hoist_lremove:\\<open>set ((lremove x xs) |-| ys) = set (lremove x (xs |-| ys))\\<close> \n  apply (induct ys arbitrary: x xs)\n   apply simp\n  by (metis Diff_insert Diff_insert2 lminus.simps(2) lremove_simp)\n\nlemma lminus_simp[simp]: \\<open>set (xs |-| ys) = (set xs) - (set ys)\\<close>\nproof (induct ys)\n  case Nil\n  then show ?case by simp\nnext\n  case (Cons y ys)\n  have \\<open>set (xs |-| (y # ys)) = set (xs |-| ys) - {y}\\<close>\n    by (simp add: hoist_lremove)\n  then show ?case\n    using Cons.hyps by force\nqed\n\ndefinition lequal (infix \\<open>|=|\\<close> 120) where \\<open>xs |=| ys \\<equiv> xs |\\<subseteq>| ys \\<and> ys |\\<subseteq>| xs\\<close>\n\nlemma lequal_simp[simp]: \\<open>xs |=| ys \\<longleftrightarrow> (set xs) = (set ys)\\<close>\n  by (simp add: lequal_def set_eq_subset)\n\nprimrec lunion (infix \\<open>|\\<union>|\\<close> 110) where\n  \\<open>lunion xs [] = xs\\<close> |\n  \\<open>lunion xs (y # ys) = (if y |\\<in>| xs then lunion xs ys else y # (lunion xs ys))\\<close>\n\nlemma lunion_simp[simp]: \\<open>set (xs |\\<union>| ys) = set xs \\<union> set ys\\<close> \n  by (induct ys) auto\n\nprimrec isset where\n  \\<open>isset [] = True\\<close> |\n  \\<open>isset (x # xs) = (x |\\<notin>| xs \\<and> isset xs)\\<close>\n\nlemma isset_length: \\<open>isset xs \\<Longrightarrow> size xs = size (sorted_list_of_set (set xs))\\<close>\n  by (induct xs) simp_all\n(*-------------------------*)\n\n\ndatatype trm\n  = Var nat\n  | Const nat\n  | Fun nat \\<open>trm list\\<close>\n\ndatatype mat\n  = Lit bool nat \\<open>trm list\\<close>\n  | Mat \\<open>(nat \\<times> mat list) list\\<close>\n\nfun exi_clause where\n  \\<open>exi_clause P (Lit _ _ _) = False\\<close> |\n  \\<open>exi_clause P (Mat []) = False\\<close> |\n  \\<open>exi_clause P (Mat ((n,ms) # cs)) = \n  (P (n,ms) \\<or> (\\<exists> m \\<in> set ms. exi_clause P m) \\<or> exi_clause P (Mat cs))\\<close>\n\ndefinition \\<open>exi_mat P m \\<equiv> P m \\<or> exi_clause (\\<lambda> (_,ms). \\<exists> m' \\<in> set ms. P m') m\\<close>\n\nfun all_clause where\n  \\<open>all_clause P (Lit _ _ _) = True\\<close> |\n  \\<open>all_clause P (Mat []) = True\\<close> |\n  \\<open>all_clause P (Mat ((n,ms) # cs)) = \n  (P (n,ms) \\<and> (\\<forall> m \\<in> set ms. all_clause P m) \\<and> all_clause P (Mat cs))\\<close>\n\ndefinition \\<open>all_mat P m \\<equiv> P m \\<and> all_clause (\\<lambda> (_,ms). \\<forall> m' \\<in> set ms. P m') m\\<close>\n\ndefinition \\<open>id_exists idty m \\<equiv> exi_clause (\\<lambda> (n,_). n = idty) m\\<close>\n\nfun ids_unique where\n  \\<open>ids_unique (Lit b n ts) = True\\<close> |\n  \\<open>ids_unique (Mat []) = True\\<close> |\n  \\<open>ids_unique (Mat ((n,ms) # cs)) = (\n    (\\<forall> m \\<in> set ms. ids_unique m \\<and> \\<not>id_exists n m) \\<and> \n    \\<not>id_exists n (Mat cs) \\<and> \n    ids_unique (Mat cs))\\<close>\n\nprimrec siblings where\n  \\<open>siblings c1 c2 (Lit _ _ _) = False\\<close> |\n  \\<open>siblings c1 c2 (Mat cs) = (member c1 cs \\<and> member c2 cs)\\<close>\n\nabbreviation \\<open>\n  alpha_top_level cid l m \\<equiv> (\\<exists> c cid' c'. \n    cid \\<noteq> cid' \\<and> \n    siblings (cid,c) (cid',c') m \\<and> \n    (\\<exists> m' \\<in> set c'. exi_mat (\\<lambda> l'. l = l') m'))\\<close>\n\ndefinition \\<open>\n  alpha_related m cid l \\<equiv> \n    exi_mat (alpha_top_level cid l) m\\<close>\n\nprimrec union_many where\n  \\<open>union_many [] = {}\\<close> |\n  \\<open>union_many (xs # ys) = xs \\<union> (union_many ys)\\<close>\n\nprimrec vars_term where \n  \\<open>vars_term (Var i) = {i}\\<close> |\n  \\<open>vars_term (Const i) = {}\\<close> |\n  \\<open>vars_term (Fun i ts) = union_many (map vars_term ts)\\<close>\n\nprimrec var_in_mat where\n  \\<open>var_in_mat v (Lit _ _ ts) = (\\<exists> t \\<in> set ts. v \\<in> vars_term t)\\<close> |\n  \\<open>var_in_mat v (Mat _) = False\\<close>\n\nabbreviation \\<open>var_in_mats v ms \\<equiv> (\\<exists> m \\<in> ms. exi_mat (var_in_mat v) m)\\<close>\n\nabbreviation \\<open>var_in_clause v cid m \\<close>\n\ndefinition \\<open>\n  free_var v cid m \\<equiv> \n    exi_mat (\\<lambda> m'. \\<exists> c. (cid,c) \\<in> set m') m\\<close>\n\nprimrec substitute where\n\\<open>substitute \\<sigma> (Var i) = Var (\\<sigma> i)\\<close> |\n\\<open>substitute \\<sigma> (Const i) = Const i\\<close> |\n\\<open>substitute \\<sigma> (Fun i ts) = Fun i (map (substitute \\<sigma>) ts)\\<close>\n\ndefinition \n\\<open>compliment \\<sigma> pol pred trms pol' pred' trms' \\<equiv>\n  (pol \\<longleftrightarrow> \\<not>pol') \\<and> pred = pred' \\<and> (map (substitute \\<sigma>) trms  = map (substitute \\<sigma>) trms')\\<close>\n\ndefinition \\<open>permutation xs ys \\<equiv> length xs = length ys \\<and> set xs \\<inter> set ys = {}\\<close>\n\ninductive CC' (\\<open>\\<turnstile> _ _ _ _\\<close> 0) where \nAxiom: \\<open>\\<turnstile> _ [] _ _\\<close> |\nReduction: \\<open>\n  (\\<turnstile> \\<sigma> C M ((pol,pred,trms) # P)) \\<Longrightarrow>\n  compliment \\<sigma> pol pred trms pol' pred' trms' \\<Longrightarrow>\n  (\\<turnstile> \\<sigma> ((Lit pol' pred' trms') # C) M ((pol,pred,trms) # P))\\<close> |\nPermutation: \\<open>\n  (\\<turnstile> \\<sigma> C M P) \\<Longrightarrow>\n  permutation C C' \\<Longrightarrow> permutation P P' \\<Longrightarrow>\n  (\\<turnstile> \\<sigma> C' M P')\\<close> \n\n(*\nExtension: \\<open>\n  (\\<turnstile> \\<sigma> C M P) \\<Longrightarrow>\n  copy_clause \\<delta> M C1 C2 \\<Longrightarrow>\n  (mat_replace C1 C2 (Mat M) (Mat M')) \\<Longrightarrow>\n  (\\<turnstile> \\<sigma> C3 M' (P |\\<union>| \\<lbrace>(pol,pred,trms)\\<rbrace>)) \\<Longrightarrow>\n  b_clause (pol,pred,trms) C2 (_,C3) \\<Longrightarrow>\n  extension_clause M (P |\\<union>| \\<lbrace>(pol,pred,trms)\\<rbrace>) C1 \\<Longrightarrow>\n  contains_mat_in_clause (Lit pol' pred' trms') C2 \\<Longrightarrow>\n  compliment \\<sigma> pol pred trms pol' pred' trms' \\<Longrightarrow>\n  (\\<turnstile> \\<sigma> (C |\\<union>| \\<lbrace>Lit pol pred trms\\<rbrace>) M P)\\<close> |\nDecomposition: \\<open>\n  (\\<turnstile> \\<sigma> (C |\\<union>| C') M P) \\<Longrightarrow>\n  (_,C') |\\<in>| M' \\<Longrightarrow>\n  (\\<turnstile> \\<sigma> (C |\\<union>| \\<lbrace>Mat M'\\<rbrace>) M P)\\<close>*)\n\n\nfunction free_vars where\n  \\<open>free_vars M\\<close>\n\nfunction b_clause where\n  \\<open>b_clause pol pred trms \\<lbrace>\\<rbrace> = \\<lbrace>\\<rbrace>\\<close> |\n  \\<open>b_clause pol pred trms (Insert (Lit pol' pred' trms') C) = (\n    if pol = pol' \\<and> pred = pred' \\<and> trms = trms'\n    then C\n    else Insert (Lit pol' pred' trms') (b_clause pol pred trms C))\\<close> |\n  \\<open>b_clause pol pred trms (Insert (Mat \\<lbrace>\\<rbrace>) C) = (Insert (Mat \\<lbrace>\\<rbrace>) C)\\<close> |\n  \\<open>b_clause pol pred trms (Insert (Mat (Insert (Cls idC' C') Cs)) C) = (\n    if mat_in_clause (Lit pol pred trms) (Cls idC' C')\n    then (Insert (Mat (\\<lbrace>(Cls idC' (b_clause pol pred trms C'))\\<rbrace>)) C)\n    else (Insert (Mat (Insert (Cls idC' C') Cs)) (b_clause pol pred trms C)))\\<close> \n  by pat_completeness auto\ntermination\n  apply (relation \\<open>measure (\\<lambda> (_, _, _, C). mat_elem_size (Cls 0 C))\\<close>) \n  by simp_all (metis add.assoc ignore_id less_SucI less_add_Suc1)\n\ninductive mat_replace where\n\\<open>\\<not> contains_clause_in_mat C M \\<Longrightarrow> mat_replace C C' (Mat M) (Mat M)\\<close> |\n\\<open>mat_replace C C' (Lit pol pred trms) (Lit pol pred trms)\\<close> |\n\\<open>C |\\<in>| Cs \\<Longrightarrow> mat_replace C C' (Mat Cs) (Mat (finsert C' (Cs |-| \\<lbrace>C\\<rbrace>)))\\<close> |\n\\<open>\n  contains_clause_in_mat C M \\<Longrightarrow> \n  (Mat M) |\\<in>| C'' \\<Longrightarrow> (idC'',C'') |\\<in>| Cs \\<Longrightarrow> \n  mat_replace C C' (Mat M) M' \\<Longrightarrow>\n  mat_replace C C' \n    (Mat Cs) \n    (Mat (finsert (idC'',finsert M' (C'' |-| \\<lbrace>Mat M\\<rbrace>)) (Cs |-| \\<lbrace>(idC'',C'')\\<rbrace>)))\\<close>\n\nfun free_vars_trm where\n  \\<open>free_vars_trm (Var n) = \\<lbrace>n\\<rbrace>\\<close> |\n  \\<open>free_vars_trm (Const n) = \\<lbrace>n\\<rbrace>\\<close> |\n  \\<open>free_vars_trm (Fun n trms) = fold (\\<lambda> t s. s |\\<union>| free_vars_trm t) trms \\<lbrace>\\<rbrace>\\<close>\n\ndefinition \\<open>free_vars_trms trms \\<equiv> fold (\\<lambda> t s. s |\\<union>| free_vars_trm t) trms \\<lbrace>\\<rbrace>\\<close>\n\nabbreviation \\<open>contains_var_in_lit_in_clause var pol pred trms C \\<equiv>\n  var |\\<in>| free_vars_trms trms \\<and> \n  contains_mat_in_clause (Lit pol pred trms) C\\<close>\n\nabbreviation \\<open>contains_mat_in_mat M M' \\<equiv> \n  (\\<exists> C. contains_mat_in_clause (Mat M) C \\<and> contains_clause_in_mat C M')\\<close>\n\ndefinition \\<open>alpha_related M C pol pred trms \\<equiv> \n  (\\<exists> M' C1 C2. (contains_mat_in_mat M' M \\<or> M' = M) \\<and>\n  C1 |\\<in>| M' \\<and> C2 |\\<in>| M' \\<and> C1 \\<noteq> C2 \\<and>\n  (C = C1 \\<or> contains_clause_in_clause C C1) \\<and>\n  contains_mat_in_clause (Lit pol pred trms) C2)\\<close>\n\ndefinition free_vars_clause where\n  \\<open>free_vars_clause M C \\<equiv> \n  THE vars. \\<forall> var. var |\\<in>| vars \\<longleftrightarrow> (\n    \\<exists> pol pred trms. \n    contains_var_in_lit_in_clause var pol pred trms C) \\<and> \n    (\\<forall> pol' pred' trms' C'. \n      contains_var_in_lit_in_clause var pol' pred' trms' C' \\<longrightarrow>\n      contains_clause_in_mat C' M \\<longrightarrow>\n        (contains_clause_in_clause C' C \\<or>\n        C' = C \\<or>\n        alpha_related M C pol' pred' trms'))\\<close>\n\ndefinition \\<open>vars_in_mat M \\<equiv> THE nset. \\<forall> var. var |\\<in>| nset \\<longleftrightarrow> (\\<exists> pol pred trms C idC.\n  var |\\<in>| free_vars_trms trms \\<and> Lit pol pred trms |\\<in>| C \\<and> contains_clause_in_mat (idC,C) M)\\<close>\n\nprimrec copy_term where\n\\<open>copy_term \\<delta> (Var i) = Var (\\<delta> i)\\<close> |\n\\<open>copy_term \\<delta> (Const i) = Const i\\<close> |\n\\<open>copy_term \\<delta> (Fun i trms) = Fun i (map (copy_term \\<delta>) trms)\\<close>\n\ninductive copy_clause_elem where\n\\<open>copy_clause_elem \\<delta> (Lit pol pred trms) (Lit pol pred (map (copy_term \\<delta>) trms))\\<close> |\n\\<open>\\<forall> C. C |\\<in>| M \\<longrightarrow> \n  (\\<exists> C'. C' |\\<in>| M' \\<and> C = (idC,C1) \\<and> C' = (idC',C2) \\<and> idC = idC' \\<and>\n    (\\<forall> cm. cm |\\<in>| C1 \\<longrightarrow>\n    (\\<exists> cm'. cm' |\\<in>| C2 \\<and> copy_clause_elem \\<delta> cm cm'\n  ))) \\<Longrightarrow>\n\\<forall> C'. C' |\\<in>| M' \\<longrightarrow> \n (\\<exists> C. C |\\<in>| M \\<and> C = (idC,C1) \\<and> C' = (idC',C2) \\<and> idC = idC' \\<and>\n   (\\<forall> cm'. cm' |\\<in>| C2 \\<longrightarrow>\n     (\\<exists> cm. cm |\\<in>| C1 \\<and> copy_clause_elem \\<delta> cm cm'\n  ))) \\<Longrightarrow> \ncopy_clause_elem \\<delta> (Mat M) (Mat M')\\<close>\n\nabbreviation \\<open>copy_function \\<delta> M C \\<equiv> \\<forall> var. \n  var |\\<in>| vars_in_mat \\<lbrace>C\\<rbrace> \\<longrightarrow> \n  (var |\\<in>| free_vars_clause M C \\<longrightarrow>\n  \\<delta> var |\\<notin>| vars_in_mat M) \\<and>\n  (var |\\<notin>| free_vars_clause M C \\<longrightarrow>\n  \\<delta> var = var)\\<close>\n\ndefinition \\<open>copy_clause \\<delta> M C1 C2 \\<equiv> \n  copy_function \\<delta> M C1 \\<and>\n  copy_clause_elem \\<delta> (Mat \\<lbrace>C1\\<rbrace>) (Mat \\<lbrace>C2\\<rbrace>)\\<close>\n\nfun snd_fold where\n  \\<open>snd_fold f (fst',snd') = (fst', fold f snd')\\<close>\n\ndefinition \\<open>parent_clause M C \\<equiv> THE (idC',C').\n  contains_clause_in_mat (idC',C') M \\<and> (\\<exists> M'. (Mat M') |\\<in>| C' \\<and> C |\\<in>| M')\\<close>\n\ndefinition \\<open>extension_clause M P C \\<equiv> \n  contains_clause_in_mat C M \\<and>\n  ((\\<exists> pol pred trms. \n    contains_mat_in_clause (Lit pol pred trms) C \\<and>\n    (pol,pred,trms) |\\<in>| P) \\<or>\n  ((\\<forall> pol pred trms C'. \n    (pol,pred,trms) |\\<in>| P \\<longrightarrow>\n    contains_mat_in_clause (Lit pol pred trms) C' \\<longrightarrow>\n    C' |\\<in>| M \\<longrightarrow>\n    alpha_related M C pol pred trms) \\<and>\n  (C |\\<notin>| M \\<longrightarrow> (\\<exists> pol pred trms. \n    (pol,pred,trms) |\\<in>| P \\<and>\n    contains_mat_in_clause (Lit pol pred trms) (parent_clause M C)))))\\<close>\n\ninductive CC' (\\<open>\\<turnstile> _ _ _ _\\<close> 0) where \nAxiom: \\<open>\\<turnstile> _ \\<lbrace>\\<rbrace> _ _\\<close> |\nReduction: \\<open>\n  (\\<turnstile> \\<sigma> C M (finsert (pol,pred,trms) P)) \\<Longrightarrow>\n  compliment \\<sigma> pol pred trms pol' pred' trms' \\<Longrightarrow>\n  (\\<turnstile> \\<sigma> (finsert (Lit pol pred trms) C) M (finsert (pol,pred,trms) P))\\<close> |\nExtension: \\<open>\n  (\\<turnstile> \\<sigma> C M P) \\<Longrightarrow>\n  copy_clause \\<delta> M C1 C2 \\<Longrightarrow>\n  (mat_replace C1 C2 (Mat M) (Mat M')) \\<Longrightarrow>\n  (\\<turnstile> \\<sigma> C3 M' (P |\\<union>| \\<lbrace>(pol,pred,trms)\\<rbrace>)) \\<Longrightarrow>\n  b_clause (pol,pred,trms) C2 (_,C3) \\<Longrightarrow>\n  extension_clause M (P |\\<union>| \\<lbrace>(pol,pred,trms)\\<rbrace>) C1 \\<Longrightarrow>\n  contains_mat_in_clause (Lit pol' pred' trms') C2 \\<Longrightarrow>\n  compliment \\<sigma> pol pred trms pol' pred' trms' \\<Longrightarrow>\n  (\\<turnstile> \\<sigma> (C |\\<union>| \\<lbrace>Lit pol pred trms\\<rbrace>) M P)\\<close> |\nDecomposition: \\<open>\n  (\\<turnstile> \\<sigma> (C |\\<union>| C') M P) \\<Longrightarrow>\n  (_,C') |\\<in>| M' \\<Longrightarrow>\n  (\\<turnstile> \\<sigma> (C |\\<union>| \\<lbrace>Mat M'\\<rbrace>) M P)\\<close>\n\ninductive CC where\nStart:\n\\<open>\\<turnstile> \\<sigma> C2 M \\<lbrace>\\<rbrace> \\<Longrightarrow> copy_clause \\<delta> M C1 (_,C2) \\<Longrightarrow> contains_clause_in_mat C1 M \\<Longrightarrow>\n  CC M\\<close>\n\n(*Examples*)\nlemma \\<open>CC \\<lbrace>(0,\\<lbrace>Lit True 1 []\\<rbrace>),(1,\\<lbrace>Lit False 1 []\\<rbrace>)\\<rbrace>\\<close>\nproof-\n  let ?f = \\<open>\\<lambda> i. i\\<close>\n  let ?C0 = \\<open>(0,\\<lbrace>Lit True 1 []\\<rbrace>)\\<close>\n  let ?C1 = \\<open>(1,\\<lbrace>Lit False 1 []\\<rbrace>)\\<close>\n  let ?M = \\<open>\\<lbrace>?C0,?C1\\<rbrace>\\<close>\n  have copy_fun: \\<open>copy_function ?f ?M ?C0\\<close> \n  proof-\n    have \\<open>vars_in_mat \\<lbrace>?C0\\<rbrace> = \\<lbrace>\\<rbrace>\\<close>\n  have copy1: \\<open>copy_clause ?f ?M (0,\\<lbrace>Lit True 1 []\\<rbrace>) (0,\\<lbrace>Lit True 1 []\\<rbrace>)\\<close> \n  from Start have ?thesis if \n    \\<open>\\<turnstile> (\\<lambda> i. i) \\<lbrace>Lit True 1 []\\<rbrace> \\<lbrace>(0,\\<lbrace>Lit True 1 []\\<rbrace>),(1,\\<lbrace>Lit False 1 []\\<rbrace>)\\<rbrace> \\<lbrace>\\<rbrace>\\<close>\n    using that \n\nend\n", "meta": {"author": "Barrikad", "repo": "nanoCoP-in-Isabelle", "sha": "5669ba700517a85b8fb2268ead80c921c3ad4132", "save_path": "github-repos/isabelle/Barrikad-nanoCoP-in-Isabelle", "path": "github-repos/isabelle/Barrikad-nanoCoP-in-Isabelle/nanoCoP-in-Isabelle-5669ba700517a85b8fb2268ead80c921c3ad4132/NaNoCop.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424411924673, "lm_q2_score": 0.8376199694135332, "lm_q1q2_score": 0.7085782817172441}}
{"text": "theory PartialOrderRelation3\n  imports Main\nbegin\n\ntext \"Partial order on relations that take three inputs\"\n\ndefinition rel_leq :: \"('a \\<Rightarrow> 'b \\<Rightarrow> 'c \\<Rightarrow> bool)\\<Rightarrow> ('a \\<Rightarrow> 'b \\<Rightarrow> 'c \\<Rightarrow> bool) \\<Rightarrow> bool\"\n  where\n\"rel_leq f g = ({(n, a, b) | n a b. f n a b} \\<subseteq> {(n, a, b) | n a b. g n a b})\"\n\nlemma rel_leqD:\n  \"\\<lbrakk>rel_leq f g; f a b c\\<rbrakk> \\<Longrightarrow> g a b c\"\n  unfolding rel_leq_def\n  apply (drule_tac c = \"(a, b, c)\" in subsetD; blast)\n  done\n\nend", "meta": {"author": "zilinc", "repo": "popl23-artefact", "sha": "1fe1490d2d34f93dc01ada940c160477db3b9b72", "save_path": "github-repos/isabelle/zilinc-popl23-artefact", "path": "github-repos/isabelle/zilinc-popl23-artefact/popl23-artefact-1fe1490d2d34f93dc01ada940c160477db3b9b72/arrays/loops/PartialOrderRelation3.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8962513675912912, "lm_q2_score": 0.7905303137346446, "lm_q1q2_score": 0.7085138748070476}}
{"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_times\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 times :: \"Bin => Bin => Bin\" where\n\"times (One) y = y\"\n| \"times (ZeroAnd xs1) y = ZeroAnd (times xs1 y)\"\n| \"times (OneAnd xs12) y = plus2 (ZeroAnd (times xs12 y)) y\"\n\nfun plus :: \"Nat => Nat => Nat\" where\n\"plus (Z) y = y\"\n| \"plus (S z) y = S (plus z y)\"\n\nfun times2 :: \"Nat => Nat => Nat\" where\n\"times2 (Z) y = Z\"\n| \"times2 (S z) y = plus y (times2 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 (times x y)) = (times2 (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_times.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513620489619, "lm_q2_score": 0.7905303087996143, "lm_q1q2_score": 0.7085138660026408}}
{"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_52\n  imports \"../../Test_Base\"\nbegin\n\ndatatype 'a list = nil2 | cons2 \"'a\" \"'a list\"\n\ndatatype Nat = Z | S \"Nat\"\n\nfun y :: \"'a list => 'a list => 'a list\" where\n  \"y (nil2) y2 = y2\"\n| \"y (cons2 z2 xs) y2 = cons2 z2 (y xs y2)\"\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 y22) = x x2 y22\"\n\nfun rev :: \"'a list => 'a list\" where\n  \"rev (nil2) = nil2\"\n| \"rev (cons2 y2 xs) = y (rev xs) (cons2 y2 (nil2))\"\n\nfun count :: \"Nat => Nat list => Nat\" where\n  \"count z (nil2) = Z\"\n| \"count z (cons2 z2 ys) =\n     (if x z z2 then S (count z ys) else count z ys)\"\n\ntheorem property0 :\n  \"((count n xs) = (count n (rev xs)))\"\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_52.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094060543487, "lm_q2_score": 0.7931059462938814, "lm_q1q2_score": 0.7084890018219594}}
{"text": "theory Uniform_Sampling imports \n  CryptHOL.CryptHOL\n  \"HOL-Number_Theory.Cong\"\nbegin \n\ndefinition sample_uniform_units :: \"nat \\<Rightarrow> nat spmf\"\n  where \"sample_uniform_units q = spmf_of_set ({..< q} - {0})\"\n\nlemma set_spmf_sample_uniform_units [simp]:\n  \"set_spmf (sample_uniform_units q) = {..< q} - {0}\" \n  by(simp add: sample_uniform_units_def)\n\nlemma lossless_sample_uniform_units:\n  assumes \"(p::nat) > 1\" \n  shows \"lossless_spmf (sample_uniform_units p)\" \n  unfolding sample_uniform_units_def\n  using assms by auto\n\nlemma weight_sample_uniform_units:\n  assumes \"(p::nat) > 1\" \n  shows \"weight_spmf (sample_uniform_units p) = 1\"\n  using assms lossless_sample_uniform_units \n  by (simp add: lossless_weight_spmfD)\n\n(*General lemma for mapping using sample_uniform*)\n\nlemma one_time_pad': \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\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\n(*(y + b)*)\n\nlemma plus_inj_eq: \n  assumes x: \"x < q\"\n    and x': \"x' < q\" \n    and map: \"((y :: nat) + x) mod q = (y + x') mod q\"  \nshows \"x = x'\"\nproof-\n  have \"((y :: nat) + x) mod q = (y + x') mod q \\<Longrightarrow> x mod q = x' mod q\"\n  proof-\n    have \"((y:: nat) + x) mod q = (y + x') mod q \\<Longrightarrow> [((y:: nat) + x) = (y + x')] (mod q)\"\n      by(simp add: cong_def)\n    moreover have \"[((y:: nat) + x) = (y + x')] (mod q) \\<Longrightarrow> [x = x'] (mod q)\"\n      by (simp add: cong_add_lcancel_nat)\n    moreover have \"[x = x'] (mod q) \\<Longrightarrow> x mod q = x' mod q\"\n      by(simp add: cong_def)\n    ultimately show ?thesis by(simp add: map)\n  qed\n  moreover have \"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_plus: \"inj_on  (\\<lambda>(b :: nat). (y + b) mod q ) {..<q}\" \n  by(simp add: inj_on_def)(auto simp only: plus_inj_eq)\n\nlemma surj_uni_samp_plus: \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: \nshows \"map_spmf (\\<lambda>b. (y + b) mod q) (sample_uniform q) = sample_uniform q\"\n  using inj_uni_samp_plus surj_uni_samp_plus one_time_pad by simp\n\n(*x*b*) \n\nlemma mult_inj_eq: \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\" \n  shows \"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    moreover have \"[x*y = x*y'] (mod q) = [y = y'] (mod q)\"\n      by(simp add: cong_mult_lcancel_nat coprime)\n    moreover 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  moreover 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: mult_inj_eq)\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\n\nlemma inj_on_mult':\n  assumes coprime: \"coprime x (q::nat)\" \n  shows \"inj_on (\\<lambda> b. x*b mod q) ({..<q} - {0})\"\n  apply(auto simp add: inj_on_def)\n  using coprime by(simp only: mult_inj_eq)\n\nlemma surj_on_mult': \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})\" by auto\n  show \"(\\<lambda>b. x * b mod q) ` ({..<q} - {0}) \\<subseteq> {..<q} - {0}\"  \n  proof-\n    obtain nn :: \"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) = (nn x0 x1 x2 \\<in> x2 \\<and> x1 (nn x0 x1 x2) \\<notin> x0)\"\n        by moura\n    hence 1: \"\\<forall>N f Na. nn Na f N \\<in> N \\<and> f (nn Na f N) \\<notin> Na \\<or> f ` N \\<subseteq> Na\"\n      by (meson image_subsetI)\n    have 2: \"x * nn ({..<q} - {0}) (\\<lambda>n. x * n mod q) ({..<q} - {0}) mod q \\<notin> {..<q} \\<or> x * nn ({..<q} - {0}) (\\<lambda>n. x * n mod q) ({..<q} - {0}) mod q \\<in> insert 0 {..<q}\"\n      by force\n    have 3: \"(x * nn ({..<q} - {0}) (\\<lambda>n. x * n mod q) ({..<q} - {0}) mod q \\<in> insert 0 {..<q} - {0}) = (x * nn ({..<q} - {0}) (\\<lambda>n. x * n mod q) ({..<q} - {0}) mod q \\<in> {..<q} - {0})\"\n      by simp \n    { assume \"x * nn ({..<q} - {0}) (\\<lambda>n. x * n mod q) ({..<q} - {0}) mod q = x * 0 mod q\" \n      hence \"(0 \\<le> q) = (0 = q) \\<or> (nn ({..<q} - {0}) (\\<lambda>n. x * n mod q) ({..<q} - {0}) \\<notin> {..<q} \\<or> nn ({..<q} - {0}) (\\<lambda>n. x * n mod q) ({..<q} - {0}) \\<in> {0}) \\<or> nn ({..<q} - {0}) (\\<lambda>n. x * n mod q) ({..<q} - {0}) \\<notin> {..<q} - {0} \\<or> x * nn ({..<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 mult_inj_eq) } \n    moreover\n    { assume \"0 \\<noteq> x * nn ({..<q} - {0}) (\\<lambda>n. x * n mod q) ({..<q} - {0}) mod q\"\n      moreover \n      { assume \"x * nn ({..<q} - {0}) (\\<lambda>n. x * n mod q) ({..<q} - {0}) mod q \\<in> insert 0 {..<q} \\<and> x * nn ({..<q} - {0}) (\\<lambda>n. x * n mod q) ({..<q} - {0}) mod q \\<notin> {0}\"\n        hence \"(\\<lambda>n. x * n mod q) ` ({..<q} - {0}) \\<subseteq> {..<q} - {0}\"\n          using 3 1 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 2 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> nn ({..<q} - {0}) (\\<lambda>n. x * n mod q) ({..<q} - {0}) \\<notin> {..<q} - {0} \\<or> x * nn ({..<q} - {0}) (\\<lambda>n. x * n mod q) ({..<q} - {0}) mod q \\<in> {..<q} - {0}\"\n      by force \n    thus \"(\\<lambda>n. x * n mod q) ` ({..<q} - {0}) \\<subseteq> {..<q} - {0}\"\n      using 1 by meson \n  qed\n  show \"inj_on (\\<lambda>b. x * b mod q) ({..<q} - {0})\" \n    using inj by blast\nqed\n\nlemma mult_one_time_pad':\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' surj_on_mult' one_time_pad' coprime by simp\n\n(*y + x*b*)\n\nlemma samp_uni_add_mult: \n  assumes coprime: \"coprime x (q::nat)\" \n    and x': \"x' < q\" \n    and y': \"y' < q\" \n    and map: \"(y + x * x') mod q = (y + x * y') mod q\" \n  shows \"x' = y'\"\nproof-\n  have \"(y + x * x') mod q = (y + x * y') mod q \\<Longrightarrow> x' mod q = y' mod q\"\n  proof-\n  have \"(y + x * x') mod q = (y + x * y') mod q \\<Longrightarrow> [y + x*x' = y + x *y'] (mod q)\"\n    using cong_def by blast\n  moreover have \"[y + x*x' = y + x *y'] (mod q) \\<Longrightarrow> [x' = y'] (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  moreover have \"x' mod q = y' mod q \\<Longrightarrow> x' = y'\"\n    by(simp add: x' y')\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: \n  assumes coprime: \"coprime x (q::nat)\" \n    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: \n  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\n(*(y - b) *)\n\nlemma inj_on_minus: \"inj_on  (\\<lambda>(b :: nat). (y + (q - b)) mod q ) {..<q}\"\nproof(unfold inj_on_def; auto)\n  fix x :: nat and y' :: nat\n  assume x: \"x < q\"\n  assume y': \"y' < q\"\n  assume map: \"(y + q - x) mod q = (y + q - y') mod q\"\n  have \"\\<forall>n na p. \\<exists>nb. \\<forall>nc nd pa. (\\<not> (nc::nat) < nd \\<or> \\<not> pa (nc - nd) \\<or> pa 0) \\<and> (\\<not> p (0::nat) \\<or> p (n - na) \\<or> na + nb = n)\"\n    by (metis (no_types) nat_diff_split)\n  hence \"\\<not> y < y' - q \\<and> \\<not> y < x - q\"\n    using y' x by (metis add.commute less_diff_conv not_add_less2)\n  hence \"\\<exists>n. (y' + n) mod q = (n + x) mod q\"\n    using map by (metis add.commute add_diff_inverse_nat less_diff_conv mod_add_left_eq)\n  thus \"x = y'\" \n    by (metis plus_inj_eq  x y' add.commute)\nqed\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) 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_spmf: \"map_spmf (\\<lambda> a. \\<not> a) coin_spmf = coin_spmf\" \nproof-\n  have \"inj_on Not {True, False}\" \n    by simp\n  moreover 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\nlemma ped_inv_mapping:\n  assumes \"(a::nat) < q\"\n    and \"[m \\<noteq> 0] (mod q)\"\n  shows \"map_spmf (\\<lambda> d. (d + a * (m::nat)) mod q) (sample_uniform q) = map_spmf (\\<lambda> d. (d + q * m - a * m) mod q) (sample_uniform q)\"\n(is \"?lhs = ?rhs\")\nproof-\n  have ineq: \"q * m - a * m > 0\" \n    using assms gr0I by force\n  have \"?lhs = map_spmf (\\<lambda> d. (a * m + d) mod q) (sample_uniform q)\" \n    using add.commute by metis\n  also have \"... = sample_uniform q\"\n    using samp_uni_plus_one_time_pad by simp\n  also have \"... = map_spmf (\\<lambda> d. ((q * m - a * m) + d) mod q) (sample_uniform q)\"\n    using ineq samp_uni_plus_one_time_pad by metis\n  ultimately show ?thesis \n    using add.commute ineq  \n    by (simp add: Groups.add_ac(2))\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/Sigma_Commit_Crypto/Uniform_Sampling.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933093975331752, "lm_q2_score": 0.7931059414036511, "lm_q1q2_score": 0.7084889906952773}}
{"text": "(*<*)theory Star imports Main begin(*>*)\n\nsection{*The Reflexive Transitive Closure*}\n\ntext{*\\label{sec:rtc}\n\\index{reflexive transitive closure!defining inductively|(}%\nAn inductive definition may accept parameters, so it can express \nfunctions that yield sets.\nRelations too can be defined inductively, since they are just sets of pairs.\nA perfect example is the function that maps a relation to its\nreflexive transitive closure.  This concept was already\nintroduced in \\S\\ref{sec:Relations}, where the operator @{text\"\\<^sup>*\"} was\ndefined as a least fixed point because inductive definitions were not yet\navailable. But now they are:\n*}\n\ninductive_set\n  rtc :: \"('a \\<times> 'a)set \\<Rightarrow> ('a \\<times> 'a)set\"   (\"_*\" [1000] 999)\n  for r :: \"('a \\<times> 'a)set\"\nwhere\n  rtc_refl[iff]:  \"(x,x) \\<in> r*\"\n| rtc_step:       \"\\<lbrakk> (x,y) \\<in> r; (y,z) \\<in> r* \\<rbrakk> \\<Longrightarrow> (x,z) \\<in> r*\"\n\ntext{*\\noindent\nThe function @{term rtc} is annotated with concrete syntax: instead of\n@{text\"rtc r\"} we can write @{term\"r*\"}. The actual definition\nconsists of two rules. Reflexivity is obvious and is immediately given the\n@{text iff} attribute to increase automation. The\nsecond rule, @{thm[source]rtc_step}, says that we can always add one more\n@{term r}-step to the left. Although we could make @{thm[source]rtc_step} an\nintroduction rule, this is dangerous: the recursion in the second premise\nslows down and may even kill the automatic tactics.\n\nThe above definition of the concept of reflexive transitive closure may\nbe sufficiently intuitive but it is certainly not the only possible one:\nfor a start, it does not even mention transitivity.\nThe rest of this section is devoted to proving that it is equivalent to\nthe standard definition. We start with a simple lemma:\n*}\n\nlemma [intro]: \"(x,y) \\<in> r \\<Longrightarrow> (x,y) \\<in> r*\"\nby(blast intro: rtc_step)\n\ntext{*\\noindent\nAlthough the lemma itself is an unremarkable consequence of the basic rules,\nit has the advantage that it can be declared an introduction rule without the\ndanger of killing the automatic tactics because @{term\"r*\"} occurs only in\nthe conclusion and not in the premise. Thus some proofs that would otherwise\nneed @{thm[source]rtc_step} can now be found automatically. The proof also\nshows that @{text blast} is able to handle @{thm[source]rtc_step}. But\nsome of the other automatic tactics are more sensitive, and even @{text\nblast} can be lead astray in the presence of large numbers of rules.\n\nTo prove transitivity, we need rule induction, i.e.\\ theorem\n@{thm[source]rtc.induct}:\n@{thm[display]rtc.induct}\nIt says that @{text\"?P\"} holds for an arbitrary pair @{thm (prem 1) rtc.induct}\nif @{text\"?P\"} is preserved by all rules of the inductive definition,\ni.e.\\ if @{text\"?P\"} holds for the conclusion provided it holds for the\npremises. In general, rule induction for an $n$-ary inductive relation $R$\nexpects a premise of the form $(x@1,\\dots,x@n) \\in R$.\n\nNow we turn to the inductive proof of transitivity:\n*}\n\nlemma rtc_trans: \"\\<lbrakk> (x,y) \\<in> r*; (y,z) \\<in> r* \\<rbrakk> \\<Longrightarrow> (x,z) \\<in> r*\"\napply(erule rtc.induct)\n\ntxt{*\\noindent\nUnfortunately, even the base case is a problem:\n@{subgoals[display,indent=0,goals_limit=1]}\nWe have to abandon this proof attempt.\nTo understand what is going on, let us look again at @{thm[source]rtc.induct}.\nIn the above application of @{text erule}, the first premise of\n@{thm[source]rtc.induct} is unified with the first suitable assumption, which\nis @{term\"(x,y) \\<in> r*\"} rather than @{term\"(y,z) \\<in> r*\"}. Although that\nis what we want, it is merely due to the order in which the assumptions occur\nin the subgoal, which it is not good practice to rely on. As a result,\n@{text\"?xb\"} becomes @{term x}, @{text\"?xa\"} becomes\n@{term y} and @{text\"?P\"} becomes @{term\"%u v. (u,z) : r*\"}, thus\nyielding the above subgoal. So what went wrong?\n\nWhen looking at the instantiation of @{text\"?P\"} we see that it does not\ndepend on its second parameter at all. The reason is that in our original\ngoal, of the pair @{term\"(x,y)\"} only @{term x} appears also in the\nconclusion, but not @{term y}. Thus our induction statement is too\ngeneral. Fortunately, it can easily be specialized:\ntransfer the additional premise @{prop\"(y,z):r*\"} into the conclusion:*}\n(*<*)oops(*>*)\nlemma rtc_trans[rule_format]:\n  \"(x,y) \\<in> r* \\<Longrightarrow> (y,z) \\<in> r* \\<longrightarrow> (x,z) \\<in> r*\"\n\ntxt{*\\noindent\nThis is not an obscure trick but a generally applicable heuristic:\n\\begin{quote}\\em\nWhen proving a statement by rule induction on $(x@1,\\dots,x@n) \\in R$,\npull all other premises containing any of the $x@i$ into the conclusion\nusing $\\longrightarrow$.\n\\end{quote}\nA similar heuristic for other kinds of inductions is formulated in\n\\S\\ref{sec:ind-var-in-prems}. The @{text rule_format} directive turns\n@{text\"\\<longrightarrow>\"} back into @{text\"\\<Longrightarrow>\"}: in the end we obtain the original\nstatement of our lemma.\n*}\n\napply(erule rtc.induct)\n\ntxt{*\\noindent\nNow induction produces two subgoals which are both proved automatically:\n@{subgoals[display,indent=0]}\n*}\n\n apply(blast)\napply(blast intro: rtc_step)\ndone\n\ntext{*\nLet us now prove that @{term\"r*\"} is really the reflexive transitive closure\nof @{term r}, i.e.\\ the least reflexive and transitive\nrelation containing @{term r}. The latter is easily formalized\n*}\n\ninductive_set\n  rtc2 :: \"('a \\<times> 'a)set \\<Rightarrow> ('a \\<times> 'a)set\"\n  for r :: \"('a \\<times> 'a)set\"\nwhere\n  \"(x,y) \\<in> r \\<Longrightarrow> (x,y) \\<in> rtc2 r\"\n| \"(x,x) \\<in> rtc2 r\"\n| \"\\<lbrakk> (x,y) \\<in> rtc2 r; (y,z) \\<in> rtc2 r \\<rbrakk> \\<Longrightarrow> (x,z) \\<in> rtc2 r\"\n\ntext{*\\noindent\nand the equivalence of the two definitions is easily shown by the obvious rule\ninductions:\n*}\n\nlemma \"(x,y) \\<in> rtc2 r \\<Longrightarrow> (x,y) \\<in> r*\"\napply(erule rtc2.induct)\n  apply(blast)\n apply(blast)\napply(blast intro: rtc_trans)\ndone\n\nlemma \"(x,y) \\<in> r* \\<Longrightarrow> (x,y) \\<in> rtc2 r\"\napply(erule rtc.induct)\n apply(blast intro: rtc2.intros)\napply(blast intro: rtc2.intros)\ndone\n\ntext{*\nSo why did we start with the first definition? Because it is simpler. It\ncontains only two rules, and the single step rule is simpler than\ntransitivity.  As a consequence, @{thm[source]rtc.induct} is simpler than\n@{thm[source]rtc2.induct}. Since inductive proofs are hard enough\nanyway, we should always pick the simplest induction schema available.\nHence @{term rtc} is the definition of choice.\n\\index{reflexive transitive closure!defining inductively|)}\n\n\\begin{exercise}\\label{ex:converse-rtc-step}\nShow that the converse of @{thm[source]rtc_step} also holds:\n@{prop[display]\"[| (x,y) : r*; (y,z) : r |] ==> (x,z) : r*\"}\n\\end{exercise}\n\\begin{exercise}\nRepeat the development of this section, but starting with a definition of\n@{term rtc} where @{thm[source]rtc_step} is replaced by its converse as shown\nin exercise~\\ref{ex:converse-rtc-step}.\n\\end{exercise}\n*}\n(*<*)\nlemma rtc_step2[rule_format]: \"(x,y) : r* \\<Longrightarrow> (y,z) : r --> (x,z) : r*\"\napply(erule rtc.induct)\n apply blast\napply(blast intro: rtc_step)\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/Inductive/Star.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8479677622198946, "lm_q2_score": 0.8354835432479661, "lm_q1q2_score": 0.7084631105395264}}
{"text": "(*  Title:      HOL/Quickcheck_Examples/Quickcheck_Lattice_Examples.thy\n    Author:     Lukas Bulwahn\n    Copyright   2010 TU Muenchen\n*)\n\ntheory Quickcheck_Lattice_Examples\nimports Main\nbegin\n\ndeclare [[quickcheck_finite_type_size=5]]\n\ntext \\<open>We show how other default types help to find counterexamples to propositions if\n  the standard default type @{typ int} is insufficient.\\<close>\n\nnotation\n  less_eq  (infix \"\\<sqsubseteq>\" 50) and\n  less  (infix \"\\<sqsubset>\" 50) and\n  top (\"\\<top>\") and\n  bot (\"\\<bottom>\") and\n  inf (infixl \"\\<sqinter>\" 70) and\n  sup (infixl \"\\<squnion>\" 65)\n\ndeclare [[quickcheck_narrowing_active = false, quickcheck_timeout = 3600]]\n\nsubsection \\<open>Distributive lattices\\<close>\n\nlemma sup_inf_distrib2:\n \"((y :: 'a :: distrib_lattice) \\<sqinter> z) \\<squnion> x = (y \\<squnion> x) \\<sqinter> (z \\<squnion> x)\"\n  quickcheck[expect = no_counterexample]\nby(simp add: inf_sup_aci sup_inf_distrib1)\n\nlemma sup_inf_distrib2_1:\n \"((y :: 'a :: lattice) \\<sqinter> z) \\<squnion> x = (y \\<squnion> x) \\<sqinter> (z \\<squnion> x)\"\n  quickcheck[expect = counterexample]\n  oops\n\nlemma sup_inf_distrib2_2:\n \"((y :: 'a :: distrib_lattice) \\<sqinter> z') \\<squnion> x = (y \\<squnion> x) \\<sqinter> (z \\<squnion> x)\"\n  quickcheck[expect = counterexample]\n  oops\n\nlemma inf_sup_distrib1_1:\n \"(x :: 'a :: distrib_lattice) \\<sqinter> (y \\<squnion> z) = (x \\<sqinter> y) \\<squnion> (x' \\<sqinter> z)\"\n  quickcheck[expect = counterexample]\n  oops\n\nlemma inf_sup_distrib2_1:\n \"((y :: 'a :: distrib_lattice) \\<squnion> z) \\<sqinter> x = (y \\<sqinter> x) \\<squnion> (y \\<sqinter> x)\"\n  quickcheck[expect = counterexample]\n  oops\n\nsubsection \\<open>Bounded lattices\\<close>\n\nlemma inf_bot_left [simp]:\n  \"\\<bottom> \\<sqinter> (x :: 'a :: bounded_lattice_bot) = \\<bottom>\"\n  quickcheck[expect = no_counterexample]\n  by (rule inf_absorb1) simp\n\nlemma inf_bot_left_1:\n  \"\\<bottom> \\<sqinter> (x :: 'a :: bounded_lattice_bot) = x\"\n  quickcheck[expect = counterexample]\n  oops\n\nlemma inf_bot_left_2:\n  \"y \\<sqinter> (x :: 'a :: bounded_lattice_bot) = \\<bottom>\"\n  quickcheck[expect = counterexample]\n  oops\n\nlemma inf_bot_left_3:\n  \"x \\<noteq> \\<bottom> ==> y \\<sqinter> (x :: 'a :: bounded_lattice_bot) \\<noteq> \\<bottom>\"\n  quickcheck[expect = counterexample]\n  oops\n\nlemma inf_bot_right [simp]:\n  \"(x :: 'a :: bounded_lattice_bot) \\<sqinter> \\<bottom> = \\<bottom>\"\n  quickcheck[expect = no_counterexample]\n  by (rule inf_absorb2) simp\n\nlemma inf_bot_right_1:\n  \"x \\<noteq> \\<bottom> ==> (x :: 'a :: bounded_lattice_bot) \\<sqinter> \\<bottom> = y\"\n  quickcheck[expect = counterexample]\n  oops\n\nlemma inf_bot_right_2:\n  \"(x :: 'a :: bounded_lattice_bot) \\<sqinter> \\<bottom> ~= \\<bottom>\"\n  quickcheck[expect = counterexample]\n  oops\n\nlemma sup_bot_right [simp]:\n  \"(x :: 'a :: bounded_lattice_bot) \\<squnion> \\<bottom> = \\<bottom>\"\n  quickcheck[expect = counterexample]\n  oops\n\nlemma sup_bot_left [simp]:\n  \"\\<bottom> \\<squnion> (x :: 'a :: bounded_lattice_bot) = x\"\n  quickcheck[expect = no_counterexample]\n  by (rule sup_absorb2) simp\n\nlemma sup_bot_right_2 [simp]:\n  \"(x :: 'a :: bounded_lattice_bot) \\<squnion> \\<bottom> = x\"\n  quickcheck[expect = no_counterexample]\n  by (rule sup_absorb1) simp\n\nlemma sup_eq_bot_iff [simp]:\n  \"(x :: 'a :: bounded_lattice_bot) \\<squnion> y = \\<bottom> \\<longleftrightarrow> x = \\<bottom> \\<and> y = \\<bottom>\"\n  quickcheck[expect = no_counterexample]\n  by (simp add: eq_iff)\n\nlemma sup_top_left [simp]:\n  \"\\<top> \\<squnion> (x :: 'a :: bounded_lattice_top) = \\<top>\"\n  quickcheck[expect = no_counterexample]\n  by (rule sup_absorb1) simp\n\nlemma sup_top_right [simp]:\n  \"(x :: 'a :: bounded_lattice_top) \\<squnion> \\<top> = \\<top>\"\n  quickcheck[expect = no_counterexample]\n  by (rule sup_absorb2) simp\n\nlemma inf_top_left [simp]:\n  \"\\<top> \\<sqinter> x = (x :: 'a :: bounded_lattice_top)\"\n  quickcheck[expect = no_counterexample]\n  by (rule inf_absorb2) simp\n\nlemma inf_top_right [simp]:\n  \"x \\<sqinter> \\<top> = (x :: 'a :: bounded_lattice_top)\"\n  quickcheck[expect = no_counterexample]\n  by (rule inf_absorb1) simp\n\nlemma inf_eq_top_iff [simp]:\n  \"(x :: 'a :: bounded_lattice_top) \\<sqinter> y = \\<top> \\<longleftrightarrow> x = \\<top> \\<and> y = \\<top>\"\n  quickcheck[expect = no_counterexample]\n  by (simp add: eq_iff)\n\n\nno_notation\n  less_eq  (infix \"\\<sqsubseteq>\" 50) and\n  less (infix \"\\<sqsubset>\" 50) and\n  inf  (infixl \"\\<sqinter>\" 70) and\n  sup  (infixl \"\\<squnion>\" 65) and\n  top (\"\\<top>\") and\n  bot (\"\\<bottom>\")\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/Quickcheck_Examples/Quickcheck_Lattice_Examples.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8479677506936878, "lm_q2_score": 0.8354835391516133, "lm_q1q2_score": 0.7084630974359952}}
{"text": "(* Title:   Setsum.thy\n   Author:  Minamide Yasuhiko\n*)\n\ntheory Setsum\n  imports Main\nbegin\n\n\nlemma sum1:\n  fixes f::\"'a \\<Rightarrow> nat\"\n  assumes \"finite s\" \"sum f s = 1\"\n  shows \"\\<exists>y \\<in> s. f y = 1 \\<and> sum f (s - {y}) = 0\"\n  using assms apply (simp add: sum_eq_1_iff[OF assms(1), simplified]) by fastforce\n\nlemma sumk:\n  fixes f::\"'a \\<Rightarrow> nat\"\n  assumes \"finite s\" \"x \\<in> s\" \"sum f s \\<le> k\"\n  shows \"f x \\<le> k\"\nproof (rule contrapos_pp)\n  assume H: \"\\<not> f x \\<le> k\"\n  have \"sum f s = sum f (insert x (s - {x}))\"\n    using assms by (simp add: insert_absorb)\n  also have \"... = f x + sum f (s - {x})\"\n    by (rule sum.insert, insert assms, auto)\n  finally have \"sum f s = f x + sum f (s - {x})\" .\n  thus \"\\<not> sum f s \\<le> k\"\n  proof (simp)\n    show \"\\<not> f x + sum f (s - {x}) \\<le> k\"\n      using H by auto\n  qed\nqed (fact)\n\n\nend\n", "meta": {"author": "akamah", "repo": "sst-isabelle", "sha": "e1b84bb2a51b1723542f4f919b581cc39ab14bcc", "save_path": "github-repos/isabelle/akamah-sst-isabelle", "path": "github-repos/isabelle/akamah-sst-isabelle/sst-isabelle-e1b84bb2a51b1723542f4f919b581cc39ab14bcc/Util/Setsum.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213880824789, "lm_q2_score": 0.7879312006227324, "lm_q1q2_score": 0.7084457948174052}}
{"text": "theory GraphIsomorphism\n  imports Main ColoredGraph\nbegin\n\nsection \\<open>Permutations of graphs\\<close>\n\nsubsection\\<open>The effect of vertices perm on edges\\<close>\ndefinition perm_edges :: \"perm \\<Rightarrow> (nat \\<times> nat) set \\<Rightarrow> (nat \\<times> nat) set\" where\n  \"perm_edges p es = (perm_fun_pair p) ` es\" \n\nlemma perm_edges_dom:\n  assumes \"\\<forall> (v1, v2) \\<in> E. v1 < n \\<and> v2 < n\" \n          \"(v1, v2) \\<in> perm_edges p E\" \"perm_dom p = n\"\n  shows \"v1 < n \\<and> v2 < n\"\n  using assms fst_conv snd_conv\n  unfolding perm_edges_def perm_fun_pair_def\n  by (metis (no_types, lifting) case_prodE imageE perm_comp_perm_inv2 perm_dom_perm_inv perm_fun_perm_inv_range perm_inv_solve)\n\nlemma card_perm_edges [simp]:\n  assumes \"perm_dom p = num_vertices G\"\n  shows \"card (perm_edges p (edges G)) = card (edges G)\"\nproof-\n  have \"inj_on (perm_fun_pair p) (edges G)\"\n    using assms\n    unfolding perm_fun_pair_def\n    by transfer (smt (verit, ccfv_threshold) Pair_inject distinct_perm edge_vertices(1) edge_vertices(2) edges.abs_eq eq_onp_same_args inj_on_def nth_eq_iff_index_eq num_vertices.abs_eq perm_fun'_def prod.collapse)\n  then show ?thesis\n    using assms\n    unfolding perm_edges_def Let_def\n    by (auto simp add: card_image)\nqed\n\nlemma perm_edges_perm_id' [simp]:\n  assumes \"\\<forall> (x, y) \\<in> es. x < n \\<and> y < n\"\n  shows \"perm_edges (perm_id n) es = es\" \n  using assms\n  unfolding perm_edges_def\n  by force\n\nlemma perm_edges_perm_id [simp]:\n  shows \"perm_edges (perm_id (num_vertices G)) (edges G) = edges G\"\n  unfolding perm_edges_def\n  by force\n  \nlemma perm_edges_perm_comp [simp]:\n  assumes \"perm_dom p1 = (num_vertices G)\" \"perm_dom p2 = (num_vertices G)\"\n  shows \"perm_edges (perm_comp p1 p2) (edges G) = \n         perm_edges p1 (perm_edges p2 (edges G))\"\n  using assms\n  unfolding perm_edges_def\n  by force\n  \nsubsection \\<open>The effect of vertices perm on the colored graph\\<close>\ndefinition perm_graph_Rep :: \"perm \\<Rightarrow> colored_graph_rec \\<Rightarrow> colored_graph_rec\" where\n  \"perm_graph_Rep p G = \n   \\<lparr>\n      num_vertices' = num_vertices' G,\n      edges' = perm_edges p (edges' G),\n      colors' = perm_coloring p (colors' G)\n   \\<rparr>\"\n\ndefinition perm_graph :: \"perm => colored_graph => colored_graph\" where\n  \"perm_graph p G = Abs_colored_graph (perm_graph_Rep p (Rep_colored_graph G))\"\n  \n\nlemma n_vertex_perm_graph_Rep:\n  assumes \"n_vertex G\" \"perm_dom p = num_vertices' G\"\n  shows \"n_vertex (perm_graph_Rep p G)\"\n  using assms\n  unfolding n_vertex_def Let_def perm_graph_Rep_def\n  by (smt (verit, ccfv_threshold) case_prodD case_prodI2 length_perm_coloring perm_edges_dom select_convs(1) select_convs(2) select_convs(3)) \n\nlemma perm_graph_Abs_inverse [simp]:\n  assumes \"perm_dom p = num_vertices' G\" \"n_vertex G\"\n  shows \"Rep_colored_graph (Abs_colored_graph (perm_graph_Rep p G)) = perm_graph_Rep p G\"\n  using assms\n  by (subst Abs_colored_graph_inverse) (simp_all add: n_vertex_perm_graph_Rep) \n\nlemma num_vertices_perm_graph [simp]:\n  assumes \"perm_dom p = num_vertices G\"\n  shows \"num_vertices (perm_graph p G) = num_vertices G\"\n  using assms\n  using Rep_colored_graph num_vertices.rep_eq perm_graph_Abs_inverse perm_graph_Rep_def perm_graph_def\n  by auto \n\nlemma vertex_perm_graph [simp]:\n  assumes \"perm_dom p = num_vertices G\" \"vertex G v\"\n  shows \"vertex (perm_graph p G) (perm_fun p v)\"\n  using assms\n  by simp\n\nlemma edges_perm_graph [simp]:\n  assumes \"perm_dom p = num_vertices G\"\n  shows \"edges (perm_graph p G) = perm_edges p (edges G)\"\n  using assms Rep_colored_graph edges.rep_eq num_vertices.rep_eq perm_graph_Abs_inverse perm_graph_Rep_def perm_graph_def\n  by force \n\nlemma edges_perm_graph_perm:\n  assumes \"perm_dom p = num_vertices G\" \"vertex G v\" \"vertex G w\"\n  shows \"(perm_fun p v, perm_fun p w) \\<in> edges (perm_graph p G) \\<longleftrightarrow> (v, w) \\<in> edges G\"\nproof\n  assume \"(v, w) \\<in> edges G\"\n  then show \"(perm_fun p v, perm_fun p w) \\<in> edges (perm_graph p G)\"\n    using assms image_iff \n    by (force simp add: perm_edges_def perm_fun_pair_def)\nnext\n  assume \"(perm_fun p v, perm_fun p w) \\<in> edges (perm_graph p G)\"\n  then obtain v' w' where \"(v', w') \\<in> edges G\" \"perm_fun p v' = perm_fun p v\" \"perm_fun p w' = perm_fun p w\"\n    using assms\n    by (force simp add: perm_edges_def perm_fun_pair_def)\n  then show \"(v, w) \\<in> edges G\"\n    using perm_fun_inj[OF assms(1), of v v']\n    using perm_fun_inj[OF assms(1), of w w'] assms(2-3)\n    by auto\nqed\n\nlemma colors_perm_graph [simp]:\n  assumes \"perm_dom p = num_vertices G\"\n  shows \"colors (perm_graph p G) = perm_coloring p (colors G)\"\n  using assms\n  using Rep_colored_graph colors.rep_eq num_vertices.rep_eq perm_graph_Abs_inverse perm_graph_Rep_def perm_graph_def\n  by force\n\nlemma num_colors_perm_graph [simp]:\n  assumes \"perm_dom p = num_vertices G\"\n  shows \"num_colors (perm_graph p G) = num_colors G\"\n  using assms\n  by simp\n\nlemma recolor_perm[simp]:\n  assumes \"perm_dom p = num_vertices G\" \"length \\<pi> = num_vertices G\"\n  shows \"recolor (perm_graph p G) (perm_coloring p \\<pi>) = perm_graph p (recolor G \\<pi>)\" (is \"?lhs=?rhs\")\nproof (rule graph_eqI)\n  show \"num_vertices ?lhs = num_vertices ?rhs\" \"edges ?lhs = edges ?rhs\"\n    using assms\n    by simp_all\nnext\n  show \"colors ?lhs = colors ?rhs\"\n    using assms\n    by simp\nqed\n  \nlemma perm_graph_coloring_perm_node [simp]:\n  assumes \"vertex G v\" \"perm_dom p = num_vertices G\"\n  shows \"color_fun (perm_graph p G) (perm_fun p v) = color_fun G v\"\n  using assms\n  by auto\n\nlemma perm_graph_perm_id [simp]:\n  shows \"perm_graph (perm_id (num_vertices G)) G = G\"\n  unfolding perm_graph_def\n  by (metis (full_types) Rep_colored_graph_inverse colors.rep_eq edges.rep_eq length_colors_num_vertices old.unit.exhaust perm_coloring_perm_id perm_edges_perm_id perm_graph_Rep_def surjective)\n\nlemma perm_graph_perm_comp [simp]:\n  assumes \"perm_dom p1 = num_vertices G\" \"perm_dom p2 = num_vertices G\"\n  shows \"perm_graph (perm_comp p1 p2) G = perm_graph p1 (perm_graph p2 G)\"\n  using assms\n  using perm_graph_def Rep_colored_graph colors.rep_eq edges.rep_eq length_colors_num_vertices mem_Collect_eq num_vertices.rep_eq perm_coloring_perm_comp perm_edges_perm_comp perm_graph_Abs_inverse perm_graph_Rep_def\n  by force\n  \nlemma perm_graph_perm_inv1 [simp]: \n  assumes \"perm_dom p = num_vertices G\"\n  shows \"perm_graph (perm_inv p) (perm_graph p G) = G\"\n  using assms\n  by (metis perm_comp_perm_inv1 perm_dom_perm_inv perm_graph_perm_comp perm_graph_perm_id)\n\nlemma perm_graph_perm_inv2 [simp]: \n  assumes \"perm_dom p = num_vertices G\"\n  shows \"perm_graph p (perm_graph (perm_inv p) G) = G\"\n  by (metis assms perm_dom_perm_inv perm_graph_perm_inv1 perm_inv_inv)\n\nlemma cells_perm_graph:\n  assumes \"perm_dom p = num_vertices G\"\n  shows \"cells (colors (perm_graph p G)) = map (perm_fun_set p) (cells (colors G))\"\n  using assms\n  by simp\n\nsubsection \\<open>Isomorphisms\\<close>\n\ndefinition is_isomorphism :: \"perm \\<Rightarrow> colored_graph \\<Rightarrow> colored_graph \\<Rightarrow> bool\" where\n  \"is_isomorphism p G1 G2 \\<longleftrightarrow> \n      perm_dom p = num_vertices G1 \\<and> \n      perm_graph p G1 = G2\"\n\ndefinition isomorphic :: \"colored_graph \\<Rightarrow> colored_graph \\<Rightarrow> bool\" (infixl \"\\<simeq>\" 100) where\n  \"isomorphic G1 G2 \\<longleftrightarrow> (\\<exists> p. is_isomorphism p G1 G2)\"\n\nlemma isomorphic_num_vertices:\n  assumes \"isomorphic G1 G2\"\n  shows \"num_vertices G1 = num_vertices G2\"\n  using assms\n  unfolding isomorphic_def is_isomorphism_def\n  by auto\n\nlemma isomorphic_num_edges:\n  assumes \"isomorphic G1 G2\"\n  shows \"card (edges G1) = card (edges G2)\"\n  using assms\n  unfolding isomorphic_def is_isomorphism_def\n  by auto\n\nsubsubsection \\<open>Automorphisms\\<close>\n\ndefinition is_automorphism :: \"colored_graph \\<Rightarrow> perm \\<Rightarrow> bool\" where\n  \"is_automorphism G p \\<longleftrightarrow> is_isomorphism p G G\"\n\ndefinition automorphisms :: \"colored_graph \\<Rightarrow> perm set\" where\n  \"automorphisms G = {p. is_automorphism G p}\"\n\nlemma id_automorphism [simp]:\n  shows \"perm_id (num_vertices G) \\<in> automorphisms G\"\n  unfolding automorphisms_def is_automorphism_def is_isomorphism_def\n  by auto\n\nlemma perm_comp_automorphism [simp]:\n  assumes \"is_automorphism G p1\" \"is_automorphism G p2\"\n  shows \"is_automorphism G (perm_comp p1 p2)\"\n  using assms\n  unfolding is_automorphism_def is_isomorphism_def\n  by auto\n\nlemma perm_inv_automorphism [simp]:\n  assumes \"is_automorphism G p\"\n  shows \"is_automorphism G (perm_inv p)\"\n  using assms\n  unfolding is_automorphism_def is_isomorphism_def\n  by (metis perm_dom_perm_inv perm_graph_perm_inv1)\n\nlemma automorphism_retains_colors [simp]:\n  assumes \"is_automorphism G p\" \"vertex G v\"\n  shows \"(color_fun G) (perm_fun p v) = (color_fun G) v\"\n  using assms\n  unfolding is_automorphism_def is_isomorphism_def\n  by (metis perm_graph_coloring_perm_node)\n\nlemma is_automorphism_perm_inv:\n  assumes \"is_automorphism G p\"\n  shows \"is_automorphism G (perm_inv p)\"\n  unfolding is_automorphism_def is_isomorphism_def\n  using assms\n  by (metis is_automorphism_def is_isomorphism_def perm_dom_perm_inv perm_graph_perm_inv1)\n\nsubsection \\<open>Canonical forms\\<close>\n\ndefinition is_canon_form :: \"(colored_graph \\<Rightarrow> colored_graph) \\<Rightarrow> bool\" where\n  \"is_canon_form C \\<longleftrightarrow> \n   (\\<forall> G. G \\<simeq> C G \\<and> \n         (\\<forall> p. perm_dom p = num_vertices G \\<longrightarrow> C (perm_graph p G) = C G))\"\n\nlemma isomorphic_same_canon_form:\n  assumes \"is_canon_form C\"\n  shows \"G \\<simeq> G' \\<longleftrightarrow> C G = C G'\"\nproof\n  assume \"G \\<simeq> G'\"\n  then show \"C G = C G'\"\n    using assms\n    unfolding is_canon_form_def isomorphic_def\n    by (metis is_isomorphism_def)\nnext\n  assume \"C G = C G'\"\n  show \"G \\<simeq> G'\"\n  proof-\n    obtain p where \"perm_dom p = num_vertices G\" \"perm_graph p G = C G\"\n      using assms\n      unfolding is_canon_form_def isomorphic_def is_isomorphism_def\n      by auto\n    moreover\n    obtain p' where \"perm_dom p' = num_vertices G'\" \"perm_graph p' G' = C G'\"\n      using assms\n      unfolding is_canon_form_def isomorphic_def is_isomorphism_def\n      by auto\n    ultimately\n    have \"perm_graph p G = perm_graph p' G'\"\n      using `C G = C G'`\n      by simp\n    then show ?thesis\n      by (metis \\<open>perm_dom p = num_vertices G\\<close> \\<open>perm_dom p' = num_vertices G'\\<close> is_isomorphism_def isomorphic_def isomorphic_num_vertices perm_dom_perm_comp perm_dom_perm_inv perm_graph_perm_comp perm_graph_perm_inv1)\n  qed\nqed\n\ndefinition orbits :: \"colored_graph \\<Rightarrow> vertex \\<Rightarrow> vertex set\" where \n  \"orbits G v = {perm_fun p v | p. p \\<in> automorphisms G}\"\n\ndefinition is_orbit_subset :: \"perm set \\<Rightarrow> vertex set \\<Rightarrow> bool\" where \n  \"is_orbit_subset A \\<Omega> \\<longleftrightarrow> (\\<forall> v1 \\<in> \\<Omega>. \\<forall> v2 \\<in> \\<Omega>. \\<exists> p \\<in> A. perm_fun p v1 = v2)\"\n\nend", "meta": {"author": "milanbankovic", "repo": "isocert", "sha": "0b160702bc0196739915541478fdfc9bb67a35db", "save_path": "github-repos/isabelle/milanbankovic-isocert", "path": "github-repos/isabelle/milanbankovic-isocert/isocert-0b160702bc0196739915541478fdfc9bb67a35db/thy/GraphIsomorphism.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8740772351648676, "lm_q2_score": 0.8104789178257654, "lm_q1q2_score": 0.7084211716525589}}
{"text": "theory Projective_Space_Axioms\n  imports Main\nbegin\n\n(* Author: Anthony Bordg, University of Cambridge, apdb3@cam.ac.uk *)\n\ntext \\<open>\nContents:\n\\<^item> We introduce the types @{typ 'point} of points and @{typ 'line} of lines and an incidence relation \nbetween them.\n\\<^item> A set of axioms for the (3-dimensional) projective space. \nAn alternative set of axioms could use planes as basic objects in addition to points and lines  \n\\<close>\n\nsection \\<open>The axioms of the Projective Space\\<close>\n\nlemma distinct4_def:\n\"distinct [A,B,C,D] = ((A \\<noteq> B) \\<and> (A \\<noteq> C) \\<and> (A \\<noteq> D)\\<and> (B \\<noteq> C) \\<and> (B \\<noteq> D) \\<and> (C \\<noteq> D))\"\n  by auto\n\nlemma distinct3_def:\n  \"distinct [A, B, C] = (A \\<noteq> B \\<and> A \\<noteq> C \\<and> B \\<noteq> C)\"\n  by auto\n\nlocale projective_space =\n  (* One has a type of 'point *)\n  (* We don't need an axiom for the existence of at least one point, \n  since we know that the type \"'point\" is not empty  \n  TODO: why would that be true? *)\n  (* One has a type of 'line *)\n  (* There is a relation of incidence between 'point and 'line *)\n  fixes incid :: \"'point \\<Rightarrow> 'line \\<Rightarrow> bool\"\n  fixes meet :: \"'line \\<Rightarrow> 'line \\<Rightarrow> 'point\"\n  assumes meet_def:  \"(incid (meet l m) l \\<and> incid (meet l m) m)\"\n\n  (* The relation of incidence is decidable *)\n  assumes incid_dec: \"(incid P l) \\<or> \\<not>(incid P l)\"\n\n  (* Ax1: Any two distinct 'point are incident with just one line *)\n  assumes ax1_existence: \"\\<exists>l. (incid P l) \\<and> (incid M l)\"\n  assumes ax1_uniqueness: \"(incid P k) \\<longrightarrow> (incid M k) \\<longrightarrow> (incid P l) \\<longrightarrow> (incid M l) \\<longrightarrow> (P = M) \\<or> (k = l)\"\n\n\n  (* Ax2: If A B C D are four distinct 'point such that AB meets CD then AC meets BD.\n  Sometimes this is called Pasch's axiom, but according to Wikipedia it is misleading\n  since Pasch's axiom refers to something else. *)\n  assumes ax2: \"distinct [A,B,C,D] \\<longrightarrow> (incid A lAB \\<and> incid B lAB) \n  \\<longrightarrow> (incid C lCD \\<and> incid D lCD) \\<longrightarrow> (incid A lAC \\<and> incid C lAC) \\<longrightarrow> \n  (incid B lBD \\<and> incid D lBD) \\<longrightarrow> (\\<exists>I.(incid I lAB \\<and> incid I lCD)) \\<longrightarrow> \n  (\\<exists>J.(incid J lAC \\<and> incid J lBD))\"\n\n\n\n  (** Dimension-related axioms **)\n  (* Ax3: Every line is incident with at least three Points.\n  As I understand it, this axiom makes sure that Lines are not degenerated into 'point\n  and since it asks for three distinct Points, not only 2, it captures the idea that\n  Lines are continuous, i.e. there is always a point between two distinct Points. *)\n  assumes ax3: \"\\<exists>A B C. distinct3 A B C \\<and> (incid A l) \\<and> (incid B l) \\<and> (incid C l)\"\n\n  (* Ax4: There exists two Lines that do not meet, \n  hence the geometry is at least 3-dimensional *)\n  assumes ax4: \"\\<exists>l m.\\<forall>P. \\<not>(incid P l \\<and> incid P m)\"\n\n\n  (* Ax5: The geometry is not 4-dimensional, hence it is exactly 3-dimensional *)\n  assumes ax5: \"distinct [l1,l2,l3] \\<longrightarrow> (\\<exists>l4 J1 J2 J3. distinct [J1,J2,J3] \\<and> \n  meet l1 l4 = J1 \\<and> meet l2 l4 = J2 \\<and> meet l3 l4 = J3)\"\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/Projective_Geometry/Projective_Space_Axioms.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8902942261220292, "lm_q2_score": 0.7956581073313276, "lm_q1q2_score": 0.7083698189242628}}
{"text": "theory GabrielaLimonta\nimports Main \"~~/src/HOL/IMP/Big_Step\"\nbegin                             \n\nfun exec :: \"com \\<Rightarrow> state \\<Rightarrow> nat \\<Rightarrow> state option\" where\n  \"exec _ s 0 = None\" \n| \"exec SKIP s (Suc f) = Some s\" \n| \"exec (x::=v) s (Suc f) = Some (s(x:=aval v s))\" \n| \"exec (c1;;c2) s (Suc f) = (\n    case (exec c1 s f) of None \\<Rightarrow> None | Some s' \\<Rightarrow> exec c2 s' f)\" \n| \"exec (IF b THEN c1 ELSE c2) s (Suc f) = \n    (if bval b s then exec c1 s f else exec c2 s f)\" \n| \"exec (WHILE b DO c) s (Suc f) = (\n    if bval b s then \n      (case (exec c s f) of \n        None \\<Rightarrow> None | \n        Some s' \\<Rightarrow> exec (WHILE b DO c) s' f) \n    else Some s)\"\n\n\ntext {* The two directions are proved separately. The proof of the first \n  direction should be quite straightforward, and is left to you. *}\nlemma exec_imp_bigstep: \"exec c s f = Some s' \\<Longrightarrow> (c,s) \\<Rightarrow> s'\"\nproof (induction arbitrary: s' rule: exec.induct[case_names None SKIP ASS SEMI IF WHILE])\nprint_cases\ncase (None uu sa)\n  from this have False by auto\n  thus ?case by blast\nnext\ncase (SKIP sa f)\n  from this have \"sa = s'\" by auto\n  thus ?case using `sa = s'` by auto\nnext\ncase (ASS x v sa f)\n  from this have \"s' = sa(x := aval v sa)\" by auto\n  thus ?case by blast\nnext \ncase (SEMI c1 c2 sa f)\n  thus ?case by (auto split: option.split_asm)\nnext\ncase (IF b c1 c2 sa f)\n  thus ?case by (metis IfFalse IfTrue exec.simps(5))\nnext\ncase (WHILE b c sa f) \n  thus ?case sorry\nqed\n\n\nlemma exec_mono: \"exec c s f = Some s' \\<Longrightarrow> exec c s (f+k) = Some s'\"\nproof (induction c s f arbitrary: s'\n    rule: exec.induct[case_names None SKIP ASS SEMI IF WHILE])\nprint_cases\ncase (None uu s s')\n  from this have False by simp\n  thus ?case by blast\nnext\ncase (SKIP s f s')\n  from this have \"s' = s\" by simp\n  thus ?case by auto\nnext\ncase (ASS x v s f s')\n  from this have \"s' = s(x := aval v s)\" by simp\n  thus ?case by auto\nnext\ncase (SEMI c1 c2 s f)\n  thus ?case by (auto split: option.split option.split_asm)\nnext\ncase (IF b c1 c2 s f s')\n  thus ?case by auto\nnext\ncase (WHILE b c s i s')\n  thus ?case by (auto split: option.split_asm)\nqed\n\nlemma bigstep_imp_si:\n  \"(c,s) \\<Rightarrow> s' \\<Longrightarrow> \\<exists>k. exec c s k = Some s'\"\nproof (induct rule: big_step_induct)\nprint_cases\n  case (Skip s) have \"exec SKIP s 1 = Some s\" by auto\n  thus ?case by blast\nnext\n  case (WhileTrue b s1 c s2 s3)\n  then obtain f1 f2 where \"exec c s1 f1 = Some s2\" \n    and \"exec (WHILE b DO c) s2 f2 = Some s3\" by auto\n  with exec_mono[of c s1 f1 s2 f2] \n    exec_mono[of \"WHILE b DO c\" s2 f2 s3 f1] have \n    \"exec c s1 (f1+f2) = Some s2\" \n    and \"exec (WHILE b DO c) s2 (f2+f1) = Some s3\"\n    by auto\n  hence \"exec (WHILE b DO c) s1 (Suc (f1+f2)) = Some s3\" \n    using `bval b s1` by (auto simp add: add_ac)\n  thus ?case by blast\nnext\n  case (Seq c1 s1 s2 c2 s3)\n  then obtain f1 f2 where \"exec c1 s1 f1 = Some s2\" and \"exec c2 s2 f2 = Some s3\"\n    by auto\n  with exec_mono[of c1 s1 f1 s2 f2] \n    exec_mono[of c2 s2 f2 s3 f1] \n  have \n    \"exec c1 s1 (f1+f2) = Some s2\" and \"exec c2 s2 (f2+f1) = Some s3\"\n    by auto\n  hence \"exec (c1;;c2) s1 (Suc (f1+f2)) = Some s3\" by (auto simp add: add_ac)\n  thus ?case by blast\nnext\n  case (Assign x a s)\n  have \"exec (x::=a) s (Suc 0) = Some (s(x := aval a s))\" by auto\n  thus ?case by blast\nnext\n  case (IfTrue b s c1 t c2)\n  then obtain f where \"exec c1 s f = Some t\" by auto\n  from this and `bval b s` and `(c1, s) \\<Rightarrow> t`\n  have \"exec (IF b THEN c1 ELSE c2) s (Suc f) = Some t\" by auto\n  thus ?case by blast\nnext\n  case (IfFalse b s c2 t c1)\n  then obtain f where \"exec c2 s f = Some t\" by auto\n  from this and `\\<not>bval b s` and `(c2, s) \\<Rightarrow> t`\n  have \"exec (IF b THEN c1 ELSE c2) s (Suc f) = Some t\" by auto\n  thus ?case by blast\nnext\n  case (WhileFalse b s c)\n  from this have \"exec (WHILE b DO c) s (Suc 0) = Some s\" by auto\n  thus ?case by blast\nqed\n\ntext {* Finally, prove the main theorem of the homework: *}\ntheorem exec_equiv_bigstep: \"(\\<exists>k. exec c s k = Some s') \\<longleftrightarrow> (c,s) \\<Rightarrow> s'\"\n  proof \n  assume \"\\<exists>k. exec c s k = Some s'\"\n  then obtain f where \"exec c s f = Some s'\" by auto\n  thus \"(c,s) \\<Rightarrow> s'\" using exec_imp_bigstep[of c s f] by auto\nnext\n  assume \"(c,s) \\<Rightarrow> s'\"\n  then show \"\\<exists>k. exec c s k = Some s'\" using bigstep_imp_si[of c s s'] by auto\nqed\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/Exercise5/GabrielaLimonta.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581097540519, "lm_q2_score": 0.8902942203004185, "lm_q1q2_score": 0.7083698164491885}}
{"text": "(* Author: R. Thiemann *)\n\nsubsection \\<open>Perron-Frobenius theorem via Brouwer's fixpoint theorem.\\<close>\n\ntheory Perron_Frobenius\nimports\n  \"HOL-Analysis.Brouwer_Fixpoint\"\n  Perron_Frobenius_Aux\nbegin\n\ntext \\<open>We follow the textbook proof of Serre \\cite[Theorem 5.2.1]{SerreMatrices}.\\<close>\n\ncontext\n  fixes A :: \"complex ^ 'n ^ 'n :: finite\"\n  assumes rnnA: \"real_non_neg_mat A\"\nbegin\n\nprivate abbreviation(input) sr where \"sr \\<equiv> spectral_radius A\"\n\nprivate definition max_v_ev :: \"(complex^'n) \\<times> complex\" where\n  \"max_v_ev = (SOME v_ev. eigen_vector A (fst v_ev) (snd v_ev)\n  \\<and> norm (snd v_ev) = sr)\"\n\nprivate definition \"max_v = (1 / norm1 (fst max_v_ev)) *\\<^sub>R fst max_v_ev\"\nprivate definition \"max_ev = snd max_v_ev\"\n\nprivate lemma max_v_ev:\n  \"eigen_vector A max_v max_ev\"\n  \"norm max_ev = sr\"\n  \"norm1 max_v = 1\"\nproof -\n  obtain v ev where id: \"max_v_ev = (v,ev)\" by force\n  from spectral_radius_ev[of A] someI_ex[of \"\\<lambda> v_ev. eigen_vector A (fst v_ev) (snd v_ev)\n  \\<and> norm (snd v_ev) = sr\", folded max_v_ev_def, unfolded id]\n  have v: \"eigen_vector A v ev\" and ev: \"norm ev = sr\" by auto\n  from normalize_eigen_vector[OF v] ev\n  show \"eigen_vector A max_v max_ev\" \"norm max_ev = sr\" \"norm1 max_v = 1\"\n    unfolding max_v_def max_ev_def id by auto\nqed\n\ntext \\<open>In the definition of S, we use the linear norm instead of the\n  default euclidean norm which is defined via the type-class.\n  The reason is that S is not convex if one uses the euclidean norm.\\<close>\n\nprivate definition B :: \"real ^ 'n ^ 'n\" where \"B \\<equiv> \\<chi> i j. Re (A $ i $ j)\"\nprivate definition S where \"S = {v :: real ^ 'n . norm1 v = 1 \\<and> (\\<forall> i. v $ i \\<ge> 0) \\<and>\n  (\\<forall> i. (B *v v) $ i \\<ge> sr * (v $ i))}\"\nprivate definition f :: \"real ^ 'n \\<Rightarrow> real ^ 'n\" where\n  \"f v = (1 / norm1 (B *v v)) *\\<^sub>R (B *v v)\"\n\nprivate \n\nprivate lemma boundedS: \"bounded S\"\nproof -\n  {\n    fix v :: \"real ^ 'n\"\n    from norm1_ge_norm[of v] have \"norm1 v = 1 \\<Longrightarrow> norm v \\<le> 1\" by auto\n  }\n  thus ?thesis\n  unfolding S_def bounded_iff\n  by (auto intro!: exI[of _ 1])\nqed\n\nprivate lemma compactS: \"compact S\"\n  using boundedS closedS\n  by (simp add: compact_eq_bounded_closed)\n\nprivate lemmas rnn = real_non_neg_matD[OF rnnA]\n\nlemma B_norm: \"B $ i $ j = norm (A $ i $ j)\"\n  using rnn[of i j]\n  by (cases \"A $ i $ j\", auto simp: B_def)\n\nlemma mult_B_mono: assumes \"\\<And> i. v $ i \\<ge> w $ i\"\n  shows \"(B *v v) $ i \\<ge> (B *v w) $ i\" unfolding matrix_vector_mult_def vec_lambda_beta\n  by (rule sum_mono, rule mult_left_mono[OF assms], unfold B_norm, auto)\n\n\nprivate lemma non_emptyS: \"S \\<noteq> {}\"\nproof -\n  let ?v = \"(\\<chi> i. norm (max_v $ i)) :: real ^ 'n\"\n  have \"norm1 max_v = 1\" by (rule max_v_ev(3))\n  hence nv: \"norm1 ?v = 1\" unfolding norm1_def by auto\n  {\n    fix i\n    have \"sr * (?v $ i) = sr * norm (max_v $ i)\" by auto\n    also have \"\\<dots> = (norm max_ev) * norm (max_v $ i)\" using max_v_ev by auto\n    also have \"\\<dots> = norm ((max_ev *s max_v) $ i)\" by (auto simp: norm_mult)\n    also have \"max_ev *s max_v = A *v max_v\" using max_v_ev(1)[unfolded eigen_vector_def] by auto\n    also have \"norm ((A *v max_v) $ i) \\<le> (B *v ?v) $ i\"\n      unfolding matrix_vector_mult_def vec_lambda_beta\n      by (rule sum_norm_le, auto simp: norm_mult B_norm)\n    finally have \"sr * (?v $ i) \\<le> (B *v ?v) $ i\" .\n  } note le = this\n  have \"?v \\<in> S\" unfolding S_def using nv le by auto\n  thus ?thesis by blast\nqed\n\nprivate lemma convexS: \"convex S\"\nproof (rule convexI)\n  fix v w a b\n  assume *: \"v \\<in> S\" \"w \\<in> S\" \"0 \\<le> a\" \"0 \\<le> b\" \"a + b = (1 :: real)\"\n  let ?lin = \"a *\\<^sub>R v + b *\\<^sub>R w\"\n  from * have 1: \"norm1 v = 1\" \"norm1 w = 1\" unfolding S_def by auto\n  have \"norm1 ?lin = a * norm1 v + b * norm1 w\"\n    unfolding norm1_def sum_distrib_left sum.distrib[symmetric]\n  proof (rule sum.cong)\n    fix i :: 'n\n    from * have \"v $ i \\<ge> 0\" \"w $ i \\<ge> 0\" unfolding S_def by auto\n    thus \"norm (?lin $ i) = a * norm (v $ i) + b * norm (w $ i)\"\n      using *(3-4) by auto\n  qed simp\n  also have \"\\<dots> = 1\" using *(5) 1 by auto\n  finally have norm1: \"norm1 ?lin = 1\" .\n  {\n    fix i\n    from * have \"0 \\<le> v $ i\" \"sr * v $ i \\<le> (B *v v) $ i\" unfolding S_def by auto\n    with \\<open>a \\<ge> 0\\<close> have a: \"a * (sr * v $ i) \\<le> a * (B *v v) $ i\" by (intro mult_left_mono)\n    from * have \"0 \\<le> w $ i\" \"sr * w $ i \\<le> (B *v w) $ i\" unfolding S_def by auto\n    with \\<open>b \\<ge> 0\\<close> have b: \"b * (sr * w $ i) \\<le> b * (B *v w) $ i\" by (intro mult_left_mono)\n    from a b have \"a * (sr * v $ i) + b * (sr * w $ i) \\<le> a * (B *v v) $ i + b * (B *v w) $ i\" by auto\n  } note le = this\n  have switch[simp]: \"\\<And> x y. x * a * y = a * x * y\"  \"\\<And> x y. x * b * y = b * x * y\" by auto\n  have [simp]: \"x \\<in> {v,w} \\<Longrightarrow> a * (r * x $h i) = r * (a * x $h i)\" for a r i x by auto\n  show \"a *\\<^sub>R v + b *\\<^sub>R w \\<in> S\" using * norm1 le unfolding S_def\n    by (auto simp: matrix_vect_scaleR matrix_vector_right_distrib ring_distribs)\nqed\n\nprivate abbreviation (input) r :: \"real \\<Rightarrow> complex\" where\n  \"r \\<equiv> of_real\"\n\nprivate abbreviation rv :: \"real ^'n \\<Rightarrow> complex ^'n\" where\n  \"rv v \\<equiv> \\<chi> i. r (v $ i)\"\n\nprivate lemma rv_0: \"(rv v = 0) = (v = 0)\"\n  by (simp add: of_real_hom.map_vector_0 map_vector_def vec_eq_iff)\n\nprivate lemma rv_mult: \"A *v rv v = rv (B *v v)\"\nproof -\n  have \"map_matrix r B = A\"\n    using rnnA unfolding map_matrix_def B_def real_non_neg_mat_def map_vector_def elements_mat_h_def\n    by vector\n  thus ?thesis\n    using of_real_hom.matrix_vector_mult_hom[of B, where 'a = complex]\n    unfolding map_vector_def by auto\nqed\n\ncontext\n  assumes zero_no_ev: \"\\<And> v. v \\<in> S \\<Longrightarrow> A *v rv v \\<noteq> 0\"\nbegin\nprivate lemma normB_S: assumes v: \"v \\<in> S\"\n  shows \"norm1 (B *v v) \\<noteq> 0\"\nproof -\n  from zero_no_ev[OF v, unfolded rv_mult rv_0]\n  show ?thesis by auto\nqed\n\nprivate lemma image_f: \"f ` S \\<subseteq> S\"\nproof -\n  {\n    fix v\n    assume v: \"v \\<in> S\"\n    hence norm: \"norm1 v = 1\" and ge: \"\\<And> i. v $ i \\<ge> 0\" \"\\<And> i. sr * v $ i \\<le> (B *v v) $ i\" unfolding S_def by auto\n    from normB_S[OF v] have normB: \"norm1 (B *v v) > 0\" using norm1_nonzero by auto\n    have fv: \"f v = (1 / norm1 (B *v v)) *\\<^sub>R (B *v v)\" unfolding f_def by auto\n    from normB have Bv0: \"B *v v \\<noteq> 0\" unfolding norm1_0_iff[symmetric] by linarith\n    have norm: \"norm1 (f v) = 1\" unfolding fv using normB Bv0 by simp\n    define c where \"c = (1 / norm1 (B *v v))\"\n    have c: \"c > 0\" unfolding c_def using normB by auto\n    {\n      fix i\n      have 1: \"f v $ i \\<ge> 0\" unfolding fv c_def[symmetric] using c ge\n        by (auto simp: matrix_vector_mult_def sum_distrib_left B_norm intro!: sum_nonneg)\n      have id1: \"\\<And> i. (B *v f v) $ i = c * ((B *v (B *v v)) $ i)\"\n        unfolding f_def c_def matrix_vect_scaleR by simp\n      have id3: \"\\<And> i. sr * f v $ i = c * ((B *v (sr *\\<^sub>R v)) $ i)\"\n        unfolding f_def c_def[symmetric] matrix_vect_scaleR by auto\n      have 2: \"sr * f v $ i \\<le> (B *v f v) $ i\" unfolding id1 id3\n        unfolding real_mult_le_cancel_iff2[OF \\<open>c > 0\\<close>]\n        by (rule mult_B_mono, insert ge(2), auto)\n      note 1 2\n    }\n    with norm have \"f v \\<in> S\" unfolding S_def by auto\n  }\n  thus ?thesis by blast\nqed\n\nprivate lemma cont_f: \"continuous_on S f\"\n  unfolding f_def[abs_def] continuous_on using normB_S\n  unfolding norm1_def\n  by (auto intro!: tendsto_eq_intros)\n\nqualified lemma perron_frobenius_positive_ev:\n  \"\\<exists> v. eigen_vector A v (r sr) \\<and> real_non_neg_vec v\"\nproof -\n  from brouwer[OF compactS convexS non_emptyS cont_f image_f]\n    obtain v where v: \"v \\<in> S\" and fv: \"f v = v\" by auto\n  define ev where \"ev = norm1 (B *v v)\"\n  from normB_S[OF v] have \"ev \\<noteq> 0\" unfolding ev_def by auto\n  with norm1_ge_0[of \"B *v v\", folded ev_def] have norm: \"ev > 0\" by auto\n  from arg_cong[OF fv[unfolded f_def], of \"\\<lambda> (w :: real ^ 'n). ev *\\<^sub>R w\"] norm\n  have ev: \"B *v v = ev *s v\" unfolding ev_def[symmetric] scalar_mult_eq_scaleR by simp\n  with v[unfolded S_def] have ge: \"\\<And> i. sr * v $ i \\<le> ev * v $ i\" by auto\n  have \"A *v rv v = rv (B *v v)\" unfolding rv_mult ..\n  also have \"\\<dots> = ev *s rv v\" unfolding ev vec_eq_iff\n    by (simp add: scaleR_conv_of_real scaleR_vec_def)\n  finally have ev: \"A *v rv v = ev *s rv v\" .\n  from v have v0: \"v \\<noteq> 0\" unfolding S_def by auto\n  hence \"rv v \\<noteq> 0\" unfolding rv_0 .\n  with ev have ev: \"eigen_vector A (rv v) ev\" unfolding eigen_vector_def by auto\n  hence \"eigen_value A ev\" unfolding eigen_value_def by auto\n  from spectral_radius_max[OF this] have le: \"norm (r ev) \\<le> sr\" .\n  from v0 obtain i where \"v $ i \\<noteq> 0\" unfolding vec_eq_iff by auto\n  from v have \"v $ i \\<ge> 0\" unfolding S_def by auto\n  with \\<open>v $ i \\<noteq> 0\\<close> have \"v $ i > 0\" by auto\n  with ge[of i] have ge: \"sr \\<le> ev\" by auto\n  with le have sr: \"r sr = ev\" by auto\n  from v have *: \"real_non_neg_vec (rv v)\" unfolding S_def real_non_neg_vec_def vec_elements_h_def by auto\n  show ?thesis unfolding sr\n    by (rule exI[of _ \"rv v\"], insert * ev norm, auto)\nqed\nend\n\nqualified lemma perron_frobenius_both:\n  \"\\<exists> v. eigen_vector A v (r sr) \\<and> real_non_neg_vec v\"\nproof (cases \"\\<forall> v \\<in> S. A *v rv v \\<noteq> 0\")\n  case True\n  show ?thesis\n    by (rule Perron_Frobenius.perron_frobenius_positive_ev[OF rnnA], insert True, auto)\nnext\n  case False\n  then obtain v where v: \"v \\<in> S\" and A0: \"A *v rv v = 0\" by auto\n  hence id: \"A *v rv v = 0 *s rv v\" and v0: \"v \\<noteq> 0\" unfolding S_def by auto\n  from v0 have \"rv v \\<noteq> 0\" unfolding rv_0 .\n  with id have ev: \"eigen_vector A (rv v) 0\" unfolding eigen_vector_def by auto\n  hence \"eigen_value A 0\" unfolding eigen_value_def ..\n  from spectral_radius_max[OF this] have 0: \"0 \\<le> sr\" by auto\n  from v[unfolded S_def] have ge: \"\\<And> i. sr * v $ i \\<le> (B *v v) $ i\" by auto\n  from v[unfolded S_def] have rnn: \"real_non_neg_vec (rv v)\"\n    unfolding real_non_neg_vec_def vec_elements_h_def by auto\n  from v0 obtain i where \"v $ i \\<noteq> 0\" unfolding vec_eq_iff by auto\n  from v have \"v $ i \\<ge> 0\" unfolding S_def by auto\n  with \\<open>v $ i \\<noteq> 0\\<close> have vi: \"v $ i > 0\" by auto\n  from rv_mult[of v, unfolded A0] have \"rv (B *v v) = 0\" by simp\n  hence \"B *v v = 0\" unfolding rv_0 .\n  from ge[of i, unfolded this] vi have ge: \"sr \\<le> 0\" by (simp add: mult_le_0_iff)\n  with \\<open>0 \\<le> sr\\<close> have \"sr = 0\" by auto\n  show ?thesis unfolding \\<open>sr = 0\\<close> using rnn ev by auto\nqed\nend\n\ntext \\<open>Perron Frobenius: The largest complex eigenvalue of a real-valued non-negative matrix\n  is a real one, and it has a real-valued non-negative eigenvector.\\<close>\n\nlemma perron_frobenius:\n  assumes \"real_non_neg_mat A\"\n  shows \"\\<exists>v. eigen_vector A v (of_real (spectral_radius A)) \\<and> real_non_neg_vec v\"\n  by (rule Perron_Frobenius.perron_frobenius_both[OF assms])\n\ntext \\<open>And a version which ignores the eigenvector.\\<close>\n\nlemma perron_frobenius_eigen_value:\n  assumes \"real_non_neg_mat A\"\n  shows \"eigen_value A (of_real (spectral_radius A))\"\n  using perron_frobenius[OF assms] unfolding eigen_value_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/Perron_Frobenius/Perron_Frobenius.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382236515258, "lm_q2_score": 0.822189134878876, "lm_q1q2_score": 0.7083473667691316}}
{"text": "(*  Title:      HOL/Power.thy\n    Author:     Lawrence C Paulson, Cambridge University Computer Laboratory\n    Copyright   1997  University of Cambridge\n*)\n\nsection \\<open>Exponentiation\\<close>\n\ntheory Power\n  imports Num\nbegin\n\nsubsection \\<open>Powers for Arbitrary Monoids\\<close>\n\nclass power = one + times\nbegin\n\nprimrec power :: \"'a \\<Rightarrow> nat \\<Rightarrow> 'a\"  (infixr \"^\" 80)\n  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\ntext \\<open>Special syntax for squares.\\<close>\nabbreviation power2 :: \"'a \\<Rightarrow> 'a\"  (\"(_\\<^sup>2)\" [1000] 999)\n  where \"x\\<^sup>2 \\<equiv> x ^ 2\"\n\nend\n\ncontext\n  includes lifting_syntax\nbegin\n\nlemma power_transfer [transfer_rule]:\n  \\<open>(R ===> (=) ===> R) (^) (^)\\<close>\n    if [transfer_rule]: \\<open>R 1 1\\<close>\n      \\<open>(R ===> R ===> R) (*) (*)\\<close>\n    for R :: \\<open>'a::power \\<Rightarrow> 'b::power \\<Rightarrow> bool\\<close>\n  by (simp only: power_def [abs_def]) transfer_prover\n\nend\n\ncontext monoid_mult\nbegin\n\nsubclass power .\n\nlemma power_one [simp]: \"1 ^ n = 1\"\n  by (induct n) simp_all\n\nlemma power_one_right [simp]: \"a ^ 1 = a\"\n  by simp\n\nlemma power_Suc0_right [simp]: \"a ^ Suc 0 = a\"\n  by simp\n\nlemma power_commutes: \"a ^ n * a = a * a ^ n\"\n  by (induct n) (simp_all add: mult.assoc)\n\nlemma power_Suc2: \"a ^ Suc n = a ^ n * a\"\n  by (simp add: power_commutes)\n\nlemma power_add: \"a ^ (m + n) = a ^ m * a ^ n\"\n  by (induct m) (simp_all add: algebra_simps)\n\nlemma power_mult: \"a ^ (m * n) = (a ^ m) ^ n\"\n  by (induct n) (simp_all add: power_add)\n\nlemma power_even_eq: \"a ^ (2 * n) = (a ^ n)\\<^sup>2\"\n  by (subst mult.commute) (simp add: power_mult)\n\nlemma power_odd_eq: \"a ^ Suc (2*n) = a * (a ^ n)\\<^sup>2\"\n  by (simp add: power_even_eq)\n\nlemma power_numeral_even: \"z ^ numeral (Num.Bit0 w) = (let w = z ^ (numeral w) in w * w)\"\n  by (simp only: numeral_Bit0 power_add Let_def)\n\nlemma power_numeral_odd: \"z ^ numeral (Num.Bit1 w) = (let w = z ^ (numeral w) in z * w * w)\"\n  by (simp only: numeral_Bit1 One_nat_def add_Suc_right add_0_right\n      power_Suc power_add Let_def mult.assoc)\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 power4_eq_xxxx: \"x^4 = x * x * x * x\"\n  by (simp add: mult.assoc power_numeral_even)\n\nlemma power_numeral_reduce: \"x ^ numeral n = x * x ^ pred_numeral n\"\n  by (simp add: numeral_eq_Suc)\n\nlemma funpow_times_power: \"(times x ^^ f x) = times (x ^ f x)\"\nproof (induct \"f x\" arbitrary: f)\n  case 0\n  then show ?case by (simp add: fun_eq_iff)\nnext\n  case (Suc n)\n  define g where \"g x = f x - 1\" for x\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\n    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 0\n  then show ?case by simp\nnext\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    by (simp only: Suc power_Suc2) (simp add: ac_simps)\n  finally show ?case .\nqed\n\nlemma power_minus_mult: \"0 < n \\<Longrightarrow> a ^ (n - 1) * a = a ^ n\"\n  by (simp add: power_commutes split: nat_diff_split)\n\nlemma left_right_inverse_power:\n  assumes \"x * y = 1\"\n  shows   \"x ^ n * y ^ n = 1\"\nproof (induct n)\n  case (Suc n)\n  moreover have \"x ^ Suc n * y ^ Suc n = x^n * (x * y) * y^n\"\n    by (simp add: power_Suc2[symmetric] mult.assoc[symmetric])\n  ultimately show ?case by (simp add: assms)\nqed simp\n\nend\n\ncontext comm_monoid_mult\nbegin\n\nlemma power_mult_distrib [algebra_simps, algebra_split_simps, field_simps, field_split_simps, divide_simps]:\n  \"(a * b) ^ n = (a ^ n) * (b ^ n)\"\n  by (induction n) (simp_all add: ac_simps)\n\nend\n\ntext \\<open>Extract constant factors from powers.\\<close>\ndeclare power_mult_distrib [where a = \"numeral w\" for w, simp]\ndeclare power_mult_distrib [where b = \"numeral w\" for w, simp]\n\nlemma power_add_numeral [simp]: \"a^numeral m * a^numeral n = a^numeral (m + n)\"\n  for a :: \"'a::monoid_mult\"\n  by (simp add: power_add [symmetric])\n\nlemma power_add_numeral2 [simp]: \"a^numeral m * (a^numeral n * b) = a^numeral (m + n) * b\"\n  for a :: \"'a::monoid_mult\"\n  by (simp add: mult.assoc [symmetric])\n\nlemma power_mult_numeral [simp]: \"(a^numeral m)^numeral n = a^numeral (m * n)\"\n  for a :: \"'a::monoid_mult\"\n  by (simp only: numeral_mult power_mult)\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)\n    (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\nlemma of_nat_power [simp]: \"of_nat (m ^ n) = of_nat m ^ n\"\n  by (induct n) simp_all\n\nlemma zero_power: \"0 < n \\<Longrightarrow> 0 ^ n = 0\"\n  by (cases n) simp_all\n\nlemma power_zero_numeral [simp]: \"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\nlemma power_0_Suc [simp]: \"0 ^ Suc n = 0\"\n  by simp\n\ntext \\<open>It looks plausible as a simprule, but its effect can be strange.\\<close>\nlemma power_0_left: \"0 ^ n = (if n = 0 then 1 else 0)\"\n  by (cases n) simp_all\n\nend\n\ncontext semiring_char_0 begin\n\nlemma numeral_power_eq_of_nat_cancel_iff [simp]:\n  \"numeral x ^ n = of_nat y \\<longleftrightarrow> numeral x ^ n = y\"\n  using of_nat_eq_iff by fastforce\n\nlemma real_of_nat_eq_numeral_power_cancel_iff [simp]:\n  \"of_nat y = numeral x ^ n \\<longleftrightarrow> y = numeral x ^ n\"\n  using numeral_power_eq_of_nat_cancel_iff [of x n y] by (metis (mono_tags))\n\nlemma of_nat_eq_of_nat_power_cancel_iff[simp]: \"(of_nat b) ^ w = of_nat x \\<longleftrightarrow> b ^ w = x\"\n  by (metis of_nat_power of_nat_eq_iff)\n\nlemma of_nat_power_eq_of_nat_cancel_iff[simp]: \"of_nat x = (of_nat b) ^ w \\<longleftrightarrow> x = b ^ w\"\n  by (metis of_nat_eq_of_nat_power_cancel_iff)\n\nend\n\ncontext comm_semiring_1\nbegin\n\ntext \\<open>The divides relation.\\<close>\n\nlemma le_imp_power_dvd:\n  assumes \"m \\<le> n\"\n  shows \"a ^ m dvd a ^ n\"\nproof\n  from assms have \"a ^ n = a ^ (m + (n - m))\" by simp\n  also have \"\\<dots> = a ^ m * a ^ (n - m)\" by (rule power_add)\n  finally show \"a ^ n = a ^ m * a ^ (n - m)\" .\nqed\n\nlemma power_le_dvd: \"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: \"x dvd y \\<Longrightarrow> x ^ n dvd y ^ n\"\n  by (induct n) (auto simp add: mult_dvd_mono)\n\nlemma dvd_power_le: \"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  fixes n :: nat\n  assumes \"n > 0 \\<or> x = 1\"\n  shows \"x dvd (x ^ n)\"\n  using assms\nproof\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 semiring_1_no_zero_divisors\nbegin\n\nsubclass power .\n\nlemma power_eq_0_iff [simp]: \"a ^ n = 0 \\<longleftrightarrow> a = 0 \\<and> n > 0\"\n  by (induct n) auto\n\nlemma power_not_zero: \"a \\<noteq> 0 \\<Longrightarrow> a ^ n \\<noteq> 0\"\n  by (induct n) auto\n\nlemma zero_eq_power2 [simp]: \"a\\<^sup>2 = 0 \\<longleftrightarrow> a = 0\"\n  unfolding power2_eq_square by simp\n\nend\n\ncontext ring_1\nbegin\n\nlemma power_minus: \"(- a) ^ n = (- 1) ^ n * a ^ n\"\nproof (induct n)\n  case 0\n  show ?case by simp\nnext\n  case (Suc n)\n  then show ?case\n    by (simp del: power_Suc add: power_Suc2 mult.assoc)\nqed\n\nlemma power_minus': \"NO_MATCH 1 x \\<Longrightarrow> (-x) ^ n = (-1)^n * x ^ n\"\n  by (rule power_minus)\n\nlemma power_minus_Bit0: \"(- 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: \"(- 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]: \"(- a)\\<^sup>2 = a\\<^sup>2\"\n  by (fact power_minus_Bit0)\n\nlemma power_minus1_even [simp]: \"(- 1) ^ (2*n) = 1\"\nproof (induct n)\n  case 0\n  show ?case by simp\nnext\n  case (Suc n)\n  then show ?case by (simp add: power_add power2_eq_square)\nqed\n\nlemma power_minus1_odd: \"(- 1) ^ Suc (2*n) = -1\"\n  by simp\n\nlemma power_minus_even [simp]: \"(-a) ^ (2*n) = a ^ (2*n)\"\n  by (simp add: power_minus [of a])\n\nend\n\ncontext ring_1_no_zero_divisors\nbegin\n\nlemma power2_eq_1_iff: \"a\\<^sup>2 = 1 \\<longleftrightarrow> a = 1 \\<or> a = - 1\"\n  using square_eq_1_iff [of a] by (simp add: power2_eq_square)\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 semidom_divide\nbegin\n\nlemma power_diff:\n  \"a ^ (m - n) = (a ^ m) div (a ^ n)\" if \"a \\<noteq> 0\" and \"n \\<le> m\"\nproof -\n  define q where \"q = m - n\"\n  with \\<open>n \\<le> m\\<close> have \"m = q + n\" by simp\n  with \\<open>a \\<noteq> 0\\<close> q_def show ?thesis\n    by (simp add: power_add)\nqed\n\nend\n\ncontext algebraic_semidom\nbegin\n\nlemma div_power: \"b dvd a \\<Longrightarrow> (a div b) ^ n = a ^ n div b ^ n\"\n  by (induct n) (simp_all add: div_mult_div_if_dvd dvd_power_same)\n\nlemma is_unit_power_iff: \"is_unit (a ^ n) \\<longleftrightarrow> is_unit a \\<or> n = 0\"\n  by (induct n) (auto simp add: is_unit_mult_iff)\n\nlemma dvd_power_iff:\n  assumes \"x \\<noteq> 0\"\n  shows   \"x ^ m dvd x ^ n \\<longleftrightarrow> is_unit x \\<or> m \\<le> n\"\nproof\n  assume *: \"x ^ m dvd x ^ n\"\n  {\n    assume \"m > n\"\n    note *\n    also have \"x ^ n = x ^ n * 1\" by simp\n    also from \\<open>m > n\\<close> have \"m = n + (m - n)\" by simp\n    also have \"x ^ \\<dots> = x ^ n * x ^ (m - n)\" by (rule power_add)\n    finally have \"x ^ (m - n) dvd 1\"\n      using assms by (subst (asm) dvd_times_left_cancel_iff) simp_all\n    with \\<open>m > n\\<close> have \"is_unit x\" by (simp add: is_unit_power_iff)\n  }\n  thus \"is_unit x \\<or> m \\<le> n\" by force\nqed (auto intro: unit_imp_dvd simp: is_unit_power_iff le_imp_power_dvd)\n\n\nend\n\ncontext normalization_semidom_multiplicative\nbegin\n\nlemma normalize_power: \"normalize (a ^ n) = normalize a ^ n\"\n  by (induct n) (simp_all add: normalize_mult)\n\nlemma unit_factor_power: \"unit_factor (a ^ n) = unit_factor a ^ n\"\n  by (induct n) (simp_all add: unit_factor_mult)\n\nend\n\ncontext division_ring\nbegin\n\ntext \\<open>Perhaps these should be simprules.\\<close>\nlemma power_inverse [field_simps, field_split_simps, divide_simps]: \"inverse a ^ n = inverse (a ^ n)\"\nproof (cases \"a = 0\")\n  case True\n  then show ?thesis by (simp add: power_0_left)\nnext\n  case False\n  then have \"inverse (a ^ n) = inverse a ^ n\"\n    by (induct n) (simp_all add: nonzero_inverse_mult_distrib power_commutes)\n  then show ?thesis by simp\nqed\n\nlemma power_one_over [field_simps, field_split_simps, divide_simps]: \"(1 / a) ^ n = 1 / a ^ n\"\n  using power_inverse [of a] by (simp add: divide_inverse)\n\nend\n\ncontext field\nbegin\n\nlemma power_divide [field_simps, field_split_simps, divide_simps]: \"(a / b) ^ n = a ^ n / b ^ n\"\n  by (induct n) simp_all\n\nend\n\n\nsubsection \\<open>Exponentiation on ordered types\\<close>\n\ncontext linordered_semidom\nbegin\n\nlemma zero_less_power [simp]: \"0 < a \\<Longrightarrow> 0 < a ^ n\"\n  by (induct n) simp_all\n\nlemma zero_le_power [simp]: \"0 \\<le> a \\<Longrightarrow> 0 \\<le> a ^ n\"\n  by (induct n) simp_all\n\nlemma power_mono: \"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: \"0 \\<le> a \\<Longrightarrow> a \\<le> 1 \\<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  from gt1 have \"1 * 1 < a * 1\" by simp\n  also from gt1 have \"\\<dots> \\<le> a * a ^ n\"\n    by (simp only: mult_mono \\<open>0 \\<le> a\\<close> one_le_power order_less_imp_le zero_le_one order_refl)\n  finally show ?thesis by simp\nqed\n\nlemma power_gt1: \"1 < a \\<Longrightarrow> 1 < a ^ Suc n\"\n  by (simp add: power_gt1_lemma)\n\nlemma one_less_power [simp]: \"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 have \"a * a ^ m \\<le> 1\" by simp\n    with gt1 show ?thesis\n      by (force simp only: power_gt1_lemma 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 simp add: less_trans [OF zero_less_one gt1])\n  qed\nqed\n\nlemma of_nat_zero_less_power_iff [simp]: \"of_nat x ^ n > 0 \\<longleftrightarrow> x > 0 \\<or> n = 0\"\n  by (induct n) auto\n\ntext \\<open>Surely we can strengthen this? It holds for \\<open>0<a<1\\<close> too.\\<close>\nlemma power_inject_exp [simp]:\n  \\<open>a ^ m = a ^ n \\<longleftrightarrow> m = n\\<close> if \\<open>1 < a\\<close>\n  using that by (force simp add: order_class.order.antisym power_le_imp_le_exp)\n\ntext \\<open>\n  Can relax the first premise to \\<^term>\\<open>0<a\\<close> in the case of the\n  natural numbers.\n\\<close>\nlemma power_less_imp_less_exp: \"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\"] power_le_imp_le_exp)\n                               \nlemma power_strict_mono: \"a < b \\<Longrightarrow> 0 \\<le> a \\<Longrightarrow> 0 < n \\<Longrightarrow> a ^ n < b ^ n\"\nproof (induct n)\n  case 0\n  then show ?case by simp\nnext\n  case (Suc n)\n  then show ?case\n    by (cases \"n = 0\") (auto simp: mult_strict_mono le_less_trans [of 0 a b])\nqed\n\nlemma power_mono_iff [simp]:\n  shows \"\\<lbrakk>a \\<ge> 0; b \\<ge> 0; n>0\\<rbrakk> \\<Longrightarrow> a ^ n \\<le> b ^ n \\<longleftrightarrow> a \\<le> b\"\n  using power_mono [of a b] power_strict_mono [of b a] not_le by auto\n\ntext\\<open>Lemma for \\<open>power_strict_decreasing\\<close>\\<close>\nlemma power_Suc_less: \"0 < a \\<Longrightarrow> a < 1 \\<Longrightarrow> a * a ^ n < a ^ n\"\n  by (induct n) (auto simp: mult_strict_left_mono)\n\nlemma power_strict_decreasing: \"n < N \\<Longrightarrow> 0 < a \\<Longrightarrow> a < 1 \\<Longrightarrow> a ^ N < a ^ n\"\nproof (induction N)\n   case 0\n   then show ?case by simp\n next\n   case (Suc N)\n   then show ?case\n     using mult_strict_mono[of a 1 \"a ^ N\" \"a ^ n\"]\n     by (auto simp add: power_Suc_less less_Suc_eq)\n qed\n\ntext \\<open>Proof resembles that of \\<open>power_strict_decreasing\\<close>.\\<close>\nlemma power_decreasing: \"n \\<le> N \\<Longrightarrow> 0 \\<le> a \\<Longrightarrow> a \\<le> 1 \\<Longrightarrow> a ^ N \\<le> a ^ n\"\nproof (induction N)\n  case 0\n  then show ?case by simp\nnext\n  case (Suc N)\n  then show ?case\n    using mult_mono[of a 1 \"a^N\" \"a ^ n\"]\n    by (auto simp add: le_Suc_eq)\nqed\n\nlemma power_decreasing_iff [simp]: \"\\<lbrakk>0 < b; b < 1\\<rbrakk> \\<Longrightarrow> b ^ m \\<le> b ^ n \\<longleftrightarrow> n \\<le> m\"\n  using power_strict_decreasing [of m n b]\n  by (auto intro: power_decreasing ccontr)\n\nlemma power_strict_decreasing_iff [simp]: \"\\<lbrakk>0 < b; b < 1\\<rbrakk> \\<Longrightarrow> b ^ m < b ^ n \\<longleftrightarrow> n < m\"\n  using power_decreasing_iff [of b m n] unfolding le_less\n  by (auto dest: power_strict_decreasing le_neq_implies_less)\n\nlemma power_Suc_less_one: \"0 < a \\<Longrightarrow> a < 1 \\<Longrightarrow> a ^ Suc n < 1\"\n  using power_strict_decreasing [of 0 \"Suc n\" a] by simp\n\ntext \\<open>Proof again resembles that of \\<open>power_strict_decreasing\\<close>.\\<close>\nlemma power_increasing: \"n \\<le> N \\<Longrightarrow> 1 \\<le> a \\<Longrightarrow> a ^ n \\<le> a ^ N\"\nproof (induct N)\n  case 0\n  then show ?case by simp\nnext\n  case (Suc N)\n  then show ?case\n    using mult_mono[of 1 a \"a ^ n\" \"a ^ N\"]\n    by (auto simp add: le_Suc_eq order_trans [OF zero_le_one])\nqed\n\ntext \\<open>Lemma for \\<open>power_strict_increasing\\<close>.\\<close>\nlemma power_less_power_Suc: \"1 < a \\<Longrightarrow> a ^ n < a * a ^ n\"\n  by (induct n) (auto simp: mult_strict_left_mono less_trans [OF zero_less_one])\n\nlemma power_strict_increasing: \"n < N \\<Longrightarrow> 1 < a \\<Longrightarrow> a ^ n < a ^ N\"\nproof (induct N)\n  case 0\n  then show ?case by simp\nnext\n  case (Suc N)\n  then show ?case\n    using mult_strict_mono[of 1 a \"a^n\" \"a^N\"]\n    by (auto simp add: power_less_power_Suc less_Suc_eq less_trans [OF zero_less_one] less_imp_le)\nqed\n\nlemma power_increasing_iff [simp]: \"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]: \"1 < b \\<Longrightarrow> b ^ x < b ^ y \\<longleftrightarrow> x < y\"\n  by (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 \"0 \\<le> b\"\n  shows \"a \\<le> b\"\nproof (rule ccontr)\n  assume \"\\<not> ?thesis\"\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(2) power_strict_mono)\n  with le 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 \"\\<not> ?thesis\"\n  then have \"b \\<le> a\" by (simp only: linorder_not_less)\n  from this nonneg have \"b ^ n \\<le> a ^ n\" by (rule power_mono)\n  then show \"\\<not> a ^ n < b ^ n\" by (simp only: linorder_not_less)\nqed\n\nlemma power_inject_base: \"a ^ Suc n = b ^ Suc n \\<Longrightarrow> 0 \\<le> a \\<Longrightarrow> 0 \\<le> b \\<Longrightarrow> a = b\"\n  by (blast intro: power_le_imp_le_base order.antisym eq_refl sym)\n\nlemma power_eq_imp_eq_base: \"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 power_eq_iff_eq_base: \"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\nlemma power2_le_imp_le: \"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: \"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: \"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\nlemma power_Suc_le_self: \"0 \\<le> a \\<Longrightarrow> a \\<le> 1 \\<Longrightarrow> a ^ Suc n \\<le> a\"\n  using power_decreasing [of 1 \"Suc n\" a] by simp\n\nlemma power2_eq_iff_nonneg [simp]:\n  assumes \"0 \\<le> x\" \"0 \\<le> y\"\n  shows \"(x ^ 2 = y ^ 2) \\<longleftrightarrow> x = y\"\nusing assms power2_eq_imp_eq by blast\n\nlemma of_nat_less_numeral_power_cancel_iff[simp]:\n  \"of_nat x < numeral i ^ n \\<longleftrightarrow> x < numeral i ^ n\"\n  using of_nat_less_iff[of x \"numeral i ^ n\", unfolded of_nat_numeral of_nat_power] .\n\nlemma of_nat_le_numeral_power_cancel_iff[simp]:\n  \"of_nat x \\<le> numeral i ^ n \\<longleftrightarrow> x \\<le> numeral i ^ n\"\n  using of_nat_le_iff[of x \"numeral i ^ n\", unfolded of_nat_numeral of_nat_power] .\n\nlemma numeral_power_less_of_nat_cancel_iff[simp]:\n  \"numeral i ^ n < of_nat x \\<longleftrightarrow> numeral i ^ n < x\"\n  using of_nat_less_iff[of \"numeral i ^ n\" x, unfolded of_nat_numeral of_nat_power] .\n\nlemma numeral_power_le_of_nat_cancel_iff[simp]:\n  \"numeral i ^ n \\<le> of_nat x \\<longleftrightarrow> numeral i ^ n \\<le> x\"\n  using of_nat_le_iff[of \"numeral i ^ n\" x, unfolded of_nat_numeral of_nat_power] .\n\nlemma of_nat_le_of_nat_power_cancel_iff[simp]: \"(of_nat b) ^ w \\<le> of_nat x \\<longleftrightarrow> b ^ w \\<le> x\"\n  by (metis of_nat_le_iff of_nat_power)\n\nlemma of_nat_power_le_of_nat_cancel_iff[simp]: \"of_nat x \\<le> (of_nat b) ^ w \\<longleftrightarrow> x \\<le> b ^ w\"\n  by (metis of_nat_le_iff of_nat_power)\n\nlemma of_nat_less_of_nat_power_cancel_iff[simp]: \"(of_nat b) ^ w < of_nat x \\<longleftrightarrow> b ^ w < x\"\n  by (metis of_nat_less_iff of_nat_power)\n\nlemma of_nat_power_less_of_nat_cancel_iff[simp]: \"of_nat x < (of_nat b) ^ w \\<longleftrightarrow> x < b ^ w\"\n  by (metis of_nat_less_iff of_nat_power)\n\nlemma power2_nonneg_ge_1_iff: \n  assumes \"x \\<ge> 0\"\n  shows   \"x ^ 2 \\<ge> 1 \\<longleftrightarrow> x \\<ge> 1\"\n  using assms by (auto intro: power2_le_imp_le)\n\nlemma power2_nonneg_gt_1_iff: \n  assumes \"x \\<ge> 0\"\n  shows   \"x ^ 2 > 1 \\<longleftrightarrow> x > 1\"\n  using assms  by (auto intro: power_less_imp_less_base)\n\nend\n\ntext \\<open>Some @{typ nat}-specific lemmas:\\<close>\n\nlemma mono_ge2_power_minus_self:\n  assumes \"k \\<ge> 2\" shows \"mono (\\<lambda>m. k ^ m - m)\"\nunfolding mono_iff_le_Suc\nproof\n  fix n\n  have \"k ^ n < k ^ Suc n\" using power_strict_increasing_iff[of k \"n\" \"Suc n\"] assms by linarith\n  thus \"k ^ n - n \\<le> k ^ Suc n - Suc n\" by linarith\nqed\n\nlemma self_le_ge2_pow[simp]:\n  assumes \"k \\<ge> 2\" shows \"m \\<le> k ^ m\"\nproof (induction m)\n  case 0 show ?case by simp\nnext\n  case (Suc m)\n  hence \"Suc m \\<le> Suc (k ^ m)\" by simp\n  also have \"... \\<le> k^m + k^m\" using one_le_power[of k m] assms by linarith\n  also have \"... \\<le> k * k^m\" by (metis mult_2 mult_le_mono1[OF assms])\n  finally show ?case by simp\nqed\n\nlemma diff_le_diff_pow[simp]:\n  assumes \"k \\<ge> 2\" shows \"m - n \\<le> k ^ m - k ^ n\"\nproof (cases \"n \\<le> m\")\n  case True\n  thus ?thesis\n    using monoD[OF mono_ge2_power_minus_self[OF assms] True] self_le_ge2_pow[OF assms, of m]\n    by (simp add: le_diff_conv le_diff_conv2)\nqed auto\n\n\ncontext linordered_ring_strict\nbegin\n\nlemma sum_squares_eq_zero_iff: \"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: \"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: \"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 zero_le_power2 [simp]: \"0 \\<le> a\\<^sup>2\"\n  by (simp add: power2_eq_square)\n\nlemma zero_less_power2 [simp]: \"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]: \"\\<not> a\\<^sup>2 < 0\"\n  by (force simp add: power2_eq_square mult_less_0_iff)\n\nlemma power_abs: \"\\<bar>a ^ n\\<bar> = \\<bar>a\\<bar> ^ n\" \\<comment> \\<open>FIXME simp?\\<close>\n  by (induct n) (simp_all add: abs_mult)\n\nlemma power_sgn [simp]: \"sgn (a ^ n) = sgn a ^ n\"\n  by (induct n) (simp_all add: sgn_mult)\n\nlemma abs_power_minus [simp]: \"\\<bar>(- a) ^ n\\<bar> = \\<bar>a ^ n\\<bar>\"\n  by (simp add: power_abs)\n\nlemma zero_less_power_abs_iff [simp]: \"0 < \\<bar>a\\<bar> ^ n \\<longleftrightarrow> a \\<noteq> 0 \\<or> n = 0\"\nproof (induct n)\n  case 0\n  show ?case by simp\nnext\n  case Suc\n  then show ?case by (auto simp: zero_less_mult_iff)\nqed\n\nlemma zero_le_power_abs [simp]: \"0 \\<le> \\<bar>a\\<bar> ^ n\"\n  by (rule zero_le_power [OF abs_ge_zero])\n\nlemma power2_less_eq_zero_iff [simp]: \"a\\<^sup>2 \\<le> 0 \\<longleftrightarrow> a = 0\"\n  by (simp add: le_less)\n\nlemma abs_power2 [simp]: \"\\<bar>a\\<^sup>2\\<bar> = a\\<^sup>2\"\n  by (simp add: power2_eq_square)\n\nlemma power2_abs [simp]: \"\\<bar>a\\<bar>\\<^sup>2 = a\\<^sup>2\"\n  by (simp add: power2_eq_square)\n\nlemma odd_power_less_zero: \"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  then show ?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: \"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]: \"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  then show ?case\n    by (simp add: Suc zero_le_mult_iff)\nqed\n\nlemma sum_power2_ge_zero: \"0 \\<le> x\\<^sup>2 + y\\<^sup>2\"\n  by (intro add_nonneg_nonneg zero_le_power2)\n\nlemma not_sum_power2_lt_zero: \"\\<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: \"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: \"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: \"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\nlemma abs_le_square_iff: \"\\<bar>x\\<bar> \\<le> \\<bar>y\\<bar> \\<longleftrightarrow> x\\<^sup>2 \\<le> y\\<^sup>2\"\n  (is \"?lhs \\<longleftrightarrow> ?rhs\")\nproof\n  assume ?lhs\n  then have \"\\<bar>x\\<bar>\\<^sup>2 \\<le> \\<bar>y\\<bar>\\<^sup>2\" by (rule power_mono) simp\n  then show ?rhs by simp\nnext\n  assume ?rhs\n  then show ?lhs\n    by (auto intro!: power2_le_imp_le [OF _ abs_ge_zero])\nqed\n\nlemma power2_le_iff_abs_le:\n  \"y \\<ge> 0 \\<Longrightarrow> x\\<^sup>2 \\<le> y\\<^sup>2 \\<longleftrightarrow> \\<bar>x\\<bar> \\<le> y\"\n  by (metis abs_le_square_iff abs_of_nonneg)\n\nlemma abs_square_le_1:\"x\\<^sup>2 \\<le> 1 \\<longleftrightarrow> \\<bar>x\\<bar> \\<le> 1\"\n  using abs_le_square_iff [of x 1] by simp\n\nlemma abs_square_eq_1: \"x\\<^sup>2 = 1 \\<longleftrightarrow> \\<bar>x\\<bar> = 1\"\n  by (auto simp add: abs_if power2_eq_1_iff)\n\nlemma abs_square_less_1: \"x\\<^sup>2 < 1 \\<longleftrightarrow> \\<bar>x\\<bar> < 1\"\n  using  abs_square_eq_1 [of x] abs_square_le_1 [of x] by (auto simp add: le_less)\n\nlemma square_le_1:\n  assumes \"- 1 \\<le> x\" \"x \\<le> 1\"\n  shows \"x\\<^sup>2 \\<le> 1\"\n    using assms\n    by (metis add.inverse_inverse linear mult_le_one neg_equal_0_iff_equal neg_le_iff_le power2_eq_square power_minus_Bit0)\n\nend\n\nsubsection \\<open>Miscellaneous rules\\<close>\n\nlemma (in linordered_semidom) self_le_power: \"1 \\<le> a \\<Longrightarrow> 0 < n \\<Longrightarrow> a \\<le> a ^ n\"\n  using power_increasing [of 1 n a] power_one_right [of a] by auto\n\nlemma power2_ge_1_iff: \"x ^ 2 \\<ge> 1 \\<longleftrightarrow> x \\<ge> 1 \\<or> x \\<le> (-1 :: 'a :: linordered_idom)\"\n  using abs_le_square_iff[of 1 x] by (auto simp: abs_if split: if_splits)\n\nlemma (in power) 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: \"(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\ncontext comm_ring_1\nbegin\n\nlemma power2_diff: \"(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 power2_commute: \"(x - y)\\<^sup>2 = (y - x)\\<^sup>2\"\n  by (simp add: algebra_simps power2_eq_square)\n\nlemma minus_power_mult_self: \"(- a) ^ n * (- a) ^ n = a ^ (2 * n)\"\n  by (simp add: power_mult_distrib [symmetric])\n    (simp add: power2_eq_square [symmetric] power_mult [symmetric])\n\nlemma minus_one_mult_self [simp]: \"(- 1) ^ n * (- 1) ^ n = 1\"\n  using minus_power_mult_self [of 1 n] by simp\n\nlemma left_minus_one_mult_self [simp]: \"(- 1) ^ n * ((- 1) ^ n * a) = a\"\n  by (simp add: mult.assoc [symmetric])\n\nend\n\ntext \\<open>Simprules for comparisons where common factors can be cancelled.\\<close>\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 \\<open>Exponentiation for the Natural Numbers\\<close>\n\nlemma nat_one_le_power [simp]: \"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]: \"x ^ n > 0 \\<longleftrightarrow> x > 0 \\<or> n = 0\"\n  for x :: nat\n  by (induct n) auto\n\nlemma nat_power_eq_Suc_0_iff [simp]: \"x ^ m = Suc 0 \\<longleftrightarrow> m = 0 \\<or> x = Suc 0\"\n  by (induct m) auto\n\nlemma power_Suc_0 [simp]: \"Suc 0 ^ n = Suc 0\"\n  by simp\n\ntext \\<open>\n  Valid for the naturals, but what if \\<open>0 < i < 1\\<close>? Premises cannot be\n  weakened: consider the case where \\<open>i = 0\\<close>, \\<open>m = 1\\<close> and \\<open>n = 0\\<close>.\n\\<close>\n\nlemma nat_power_less_imp_less:\n  fixes i :: nat\n  assumes nonneg: \"0 < i\"\n  assumes less: \"i ^ m < i ^ n\"\n  shows \"m < n\"\nproof (cases \"i = 1\")\n  case True\n  with less power_one [where 'a = nat] show ?thesis by simp\nnext\n  case False\n  with nonneg have \"1 < i\" by auto\n  from power_strict_increasing_iff [OF this] less show ?thesis ..\nqed\n\nlemma power_gt_expt: \"n > Suc 0 \\<Longrightarrow> n^k > k\"\n  by (induction k) (auto simp: less_trans_Suc n_less_m_mult_n)\n\nlemma less_exp [simp]:\n  \\<open>n < 2 ^ n\\<close>\n  by (simp add: power_gt_expt)\n\nlemma power_dvd_imp_le:\n  fixes i :: nat\n  assumes \"i ^ m dvd i ^ n\" \"1 < i\"\n  shows \"m \\<le> n\"\n  using assms by (auto intro: power_le_imp_le_exp [OF \\<open>1 < i\\<close> dvd_imp_le])\n\nlemma dvd_power_iff_le:\n  fixes k::nat\n  shows \"2 \\<le> k \\<Longrightarrow> ((k ^ m) dvd (k ^ n) \\<longleftrightarrow> m \\<le> n)\"\n  using le_imp_power_dvd power_dvd_imp_le by force\n\nlemma power2_nat_le_eq_le: \"m\\<^sup>2 \\<le> n\\<^sup>2 \\<longleftrightarrow> m \\<le> n\"\n  for m n :: nat\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\n  then show ?thesis by simp\nnext\n  case (Suc k)\n  show ?thesis\n  proof (rule ccontr)\n    assume \"\\<not> ?thesis\"\n    then have \"n < m\" by simp\n    with assms Suc show False\n      by (simp add: power2_eq_square)\n  qed\nqed\n\nlemma ex_power_ivl1: fixes b k :: nat assumes \"b \\<ge> 2\"\nshows \"k \\<ge> 1 \\<Longrightarrow> \\<exists>n. b^n \\<le> k \\<and> k < b^(n+1)\" (is \"_ \\<Longrightarrow> \\<exists>n. ?P k n\")\nproof(induction k)\n  case 0 thus ?case by simp\nnext\n  case (Suc k)\n  show ?case\n  proof cases\n    assume \"k=0\"\n    hence \"?P (Suc k) 0\" using assms by simp\n    thus ?case ..\n  next\n    assume \"k\\<noteq>0\"\n    with Suc obtain n where IH: \"?P k n\" by auto\n    show ?case\n    proof (cases \"k = b^(n+1) - 1\")\n      case True\n      hence \"?P (Suc k) (n+1)\" using assms\n        by (simp add: power_less_power_Suc)\n      thus ?thesis ..\n    next\n      case False\n      hence \"?P (Suc k) n\" using IH by auto\n      thus ?thesis ..\n    qed\n  qed\nqed\n\nlemma ex_power_ivl2: fixes b k :: nat assumes \"b \\<ge> 2\" \"k \\<ge> 2\"\n  shows \"\\<exists>n. b^n < k \\<and> k \\<le> b^(n+1)\"\nproof -\n  have \"1 \\<le> k - 1\" using assms(2) by arith\n  from ex_power_ivl1[OF assms(1) this]\n  obtain n where \"b ^ n \\<le> k - 1 \\<and> k - 1 < b ^ (n + 1)\" ..\n  hence \"b^n < k \\<and> k \\<le> b^(n+1)\" using assms by auto\n  thus ?thesis ..\nqed\n\n\nsubsubsection \\<open>Cardinality of the Powerset\\<close>\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 simp\nnext\n  case (insert x A)\n  from \\<open>x \\<notin> A\\<close> have disjoint: \"Pow A \\<inter> insert x ` Pow A = {}\" by blast\n  from \\<open>x \\<notin> A\\<close> have inj_on: \"inj_on (insert x) (Pow A)\"\n    unfolding inj_on_def by auto\n\n  have \"card (Pow (insert x A)) = card (Pow A \\<union> insert x ` Pow A)\"\n    by (simp only: Pow_insert)\n  also have \"\\<dots> = card (Pow A) + card (insert x ` Pow A)\"\n    by (rule card_Un_disjoint) (use \\<open>finite A\\<close> disjoint in simp_all)\n  also from inj_on have \"card (insert x ` Pow A) = card (Pow A)\"\n    by (rule card_image)\n  also have \"\\<dots> + \\<dots> = 2 * \\<dots>\" by (simp add: mult_2)\n  also from insert(3) have \"\\<dots> = 2 ^ Suc (card A)\" by simp\n  also from insert(1,2) have \"Suc (card A) = card (insert x A)\"\n    by (rule card_insert_disjoint [symmetric])\n  finally show ?case .\nqed\n\n\nsubsection \\<open>Code generator tweak\\<close>\n\ncode_identifier\n  code_module Power \\<rightharpoonup> (SML) Arith and (OCaml) Arith and (Haskell) Arith\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/Power.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891392358015, "lm_q2_score": 0.8615382129861584, "lm_q1q2_score": 0.7083473617538402}}
{"text": "theory Temporal imports Main\nbegin\n  section{*Linear Temporal Logic*}\n  text{*\n    In this section we introduce an algebraic axiomatization of Linear Temporal Logic (LTL).\n    We model LTL formulas semantically as predicates on traces. For example the LTL formula\n    $\\alpha = \\Box\\; \\diamondsuit\\; (x = 1)$ is modeled as a predicate \n    $\\alpha : (nat \\Rightarrow nat) \\Rightarrow bool$, where \n    $\\alpha \\;x = True$ if $x\\;i=1$ for infinitely many $i:nat$. In this formula $\\Box$\n    and $\\diamondsuit$ denote the always and eventually operators, respectively. \n    Formulas with multiple variables are modeled similarly. For example a formula $\\alpha$ in two \n    variables is modeled as $\\alpha : (nat \\Rightarrow \\tv a) \\Rightarrow (nat \\Rightarrow \\tv b) \\Rightarrow bool$,\n    and for example $(\\Box\\; \\alpha) \\; x\\; y$ is defined as $(\\forall i . \\alpha \\; x[i..]\\; y[i..])$,\n    where $x[i..]\\;j = x\\;(i+j)$. We would like to construct an algebraic structure (Isabelle class) \n    which has the temporal operators as operations, and which has instatiations to \n    $(nat \\Rightarrow \\tv a) \\Rightarrow bool$, $(nat \\Rightarrow \\tv a) \\Rightarrow (nat \\Rightarrow \\tv b) \\Rightarrow bool$,\n    and so on. Ideally our structure should be such that if we have this structure on a type $\\tv a::temporal$,\n    then we could extend it to $(nat \\Rightarrow \\tv b) \\Rightarrow \\tv a$ in a way similar to the\n    way Boolean algebras are extended from a type $\\tv a::boolean\\_algebra$ to $\\tv b\\Rightarrow \\tv a$.\n    Unfortunately, if we use for example $\\Box$ as primitive operation on our temporal structure,\n    then we cannot extend $\\Box$ from $\\tv a::temporal$ to $(nat \\Rightarrow \\tv b) \\Rightarrow \\tv a$. A\n    possible extension of $\\Box$ could be\n      $$(\\Box\\; \\alpha)\\;x = \\bigwedge_{i:nat} \\Box (\\alpha\\; x[i..]) \\mbox{ and } \\Box \\; b = b$$\n    where $\\alpha: (nat \\Rightarrow \\tv b) \\Rightarrow \\tv a$ and $b:bool$. However, if we apply this\n    definition to $\\alpha : (nat \\Rightarrow \\tv a) \\Rightarrow (nat \\Rightarrow \\tv b) \\Rightarrow bool$,\n    then we get\n      $$(\\Box\\; \\alpha) \\; x\\; y = (\\forall i\\;j. \\alpha \\; x[i..]\\; y[j..])$$\n    which is not correct.\n\n    To evercome this problem we introduce as a primitive operation $!!:\\tv a \\Rightarrow nat \\Rightarrow \\tv a$,\n    where $\\tv a$ is the type of temporal formulas, and $\\alpha !! i$ is the formula $\\alpha$ at time point $i$.\n    If $\\alpha$ is a formula in two variables as before, then\n      $$(\\alpha !! i)\\; x\\;y = \\alpha\\; x[i..]\\;y[i..].$$\n    and we define for example the the operator always by\n      $$\\Box \\alpha = \\bigwedge_{i:nat} \\alpha !! i$$\n  *}\n  notation\n    bot (\"\\<bottom>\") and\n    top (\"\\<top>\") and\n    inf (infixl \"\\<sqinter>\" 70)\n    and sup (infixl \"\\<squnion>\" 65)\n\n  class temporal = complete_boolean_algebra +\n    fixes at :: \"'a \\<Rightarrow> nat \\<Rightarrow> 'a\" (infixl \"!!\" 150)\n    assumes [simp]: \"a !! i !! j = a !! (i + j)\"\n    assumes [simp]: \"a !! 0 = a\"\n    assumes [simp]: \"\\<top> !! i = \\<top>\"\n    assumes [simp]: \"-(a !! i) = (-a) !! i\"\n    assumes [simp]: \"(a \\<sqinter> b) !! i = (a !! i) \\<sqinter> (b !! i)\"\n    begin\n      definition always :: \"'a \\<Rightarrow> 'a\"  (\"\\<box> (_)\" [900] 900) where\n        \"\\<box> p = (INF i . p !! i)\"\n\n      definition eventually :: \"'a \\<Rightarrow> 'a\"  (\"\\<diamondsuit> (_)\" [900] 900) where\n        \"\\<diamondsuit> p = (SUP i . p !! i)\"\n\n      definition \"next\" :: \"'a \\<Rightarrow> 'a\"  (\"\\<Odot> (_)\" [900] 900) where\n        \"\\<Odot> p = p !! (Suc 0)\"\n\n      definition until :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a\" (infix \"until\" 65) where \n        \"(p until q) = (SUP n . (INFIMUM {i . i < n}  (at p)) \\<sqinter> (q !! n))\"\n    end\n\ntext{*\nNext lemma, in the context of complete boolean algebras, will be used \nto prove $-(p\\ until\\ -p) = \\Box\\; p$.\n*}\n  context complete_boolean_algebra\n    begin\n      lemma until_always: \"(INF n. (SUP i : {i. i < n} . - p i) \\<squnion> ((p :: nat \\<Rightarrow> 'a) n)) \\<le> p n\"\n        proof -\n          have \"(INF n. (SUP i:{i. i < n}. - p i) \\<squnion> p n) \\<le> (INF i:{i. i \\<le> n}. p i)\"\n            proof (induction n)\n              have \"(INF n. (SUP i:{i. i < n}. - p i) \\<squnion> p n) \\<le> (SUP i:{i. i < 0}. - p i) \\<squnion> p 0\"\n                by (rule INF_lower, simp)\n              also have \"... \\<le> (INF i:{i. i \\<le> 0}. p i)\"\n                by (simp add: INF_def)\n              finally show \"(INF n. (SUP i:{i. i < n}. - p i) \\<squnion> p n) \\<le> (INF i:{i. i \\<le> 0}. p i)\"\n                by simp\n            next\n              fix n::nat assume \"(INF n. (SUP i:{i. i < n}. - p i) \\<squnion> p n) \\<le> (INF i : {i. i \\<le> n}. p i)\"\n              also have \"\\<And> i . i \\<le> n \\<Longrightarrow> ... \\<le> p i\" by (rule INF_lower, simp)\n              finally have [simp]: \"\\<And> i . i \\<le> n \\<Longrightarrow> (INF n. (SUP i:{i. i < n}. - p i) \\<squnion> p n) \\<le> p i\"\n                by simp\n              show \"(INF n. (SUP i:{i. i < n}. - p i) \\<squnion> p n) \\<le> (INF i : {i. i \\<le> Suc n}. p i)\"\n                proof (rule INF_greatest, safe, cases)\n                  fix i::nat\n                    assume \"i \\<le> n\" from this show \"(INF n. (SUP i:{i. i < n}. - p i) \\<squnion> p n) \\<le> p i\" by simp\n                next\n                  fix i::nat\n                    have A: \"{i. i \\<le> n} = {i . i < Suc n}\" by auto\n                    have B: \"(SUP i:{i. i \\<le> n}. - p i) \\<le> - (INF n. (SUP i:{i. i < n}. - p i) \\<squnion> p n)\"\n                      by (metis (lifting, mono_tags) `(INF n. (SUP i:{i. i < n}. - p i) \\<squnion> p n) \\<le> (INF i:{i. i \\<le> n}. p i)` compl_mono uminus_INF)\n                    assume \"i \\<le> Suc n\" and \"\\<not> i \\<le> n\"\n                    from this have [simp]: \"i = Suc n\" by simp\n                    have \"(INF n. (SUP i:{i. i < n}. - p i) \\<squnion> p n) \\<le> (INF n. (SUP i:{i. i < n}. - p i) \\<squnion> p n) \\<sqinter> ((SUP i:{i. i \\<le> n}. - p i) \\<squnion> p (Suc n))\"\n                      by (simp add: A, rule INF_lower, simp)\n                    also have \"... \\<le> ((INF n. (SUP i:{i. i < n}. - p i) \\<squnion> p n) \\<sqinter> ((- (INF n. (SUP i:{i. i < n}. - p i) \\<squnion> p n)) \\<squnion> p (Suc n)))\"\n                      by (rule inf_mono, simp_all, rule_tac y = \"- (INF n. (SUP i:{i. i < n}. - p i) \\<squnion> p n)\" in order_trans, simp_all add: B)\n                    also have \"... \\<le> p i\"\n                      by (simp add: inf_sup_distrib1 inf_compl_bot)\n                    finally show \"(INF n. (SUP i:{i. i < n}. - p i) \\<squnion> p n) \\<le> p i\" by simp\n                qed\n            qed\n        also have \"(INF i:{i. i \\<le> n}. p i) \\<le> p n\" by (rule INF_lower, auto)\n        finally show \"(INF n. (SUP i : {i. i < n} . - p i) \\<squnion> ((p :: nat \\<Rightarrow> 'a) n)) \\<le> p n\" by simp\n        qed\n\n     end\n\ntext{*\n  We prove now a number of results of the temporal class.\n*}\n  context temporal\n    begin   \n      \n\n      lemma always_less [simp]: \"\\<box> p \\<le> p\"\n        proof -\n          have \"\\<box> p \\<le> p !! 0\"\n            by (unfold always_def, rule INF_lower, simp)\n          also have \"p !! 0 = p\" by simp\n          finally show \"\\<box> p \\<le> p\" by simp\n        qed\n\n      lemma always_and: \"\\<box> (p \\<sqinter> q) = (\\<box> p) \\<sqinter> (\\<box> q)\"\n        by (simp add: always_def INF_inf_distrib)\n\n      lemma eventually_or: \"\\<diamondsuit> (p \\<squnion> q) = (\\<diamondsuit> p) \\<squnion> (\\<diamondsuit> q)\"\n        by (simp add: eventually_def SUP_sup_distrib)\n\n      lemma neg_until_always: \"-(p until -p) = \\<box> p\"\n        proof (rule antisym)\n          show \"- (p until - p) \\<le> \\<box> p\"\n           by (simp add: until_def always_def uminus_SUP uminus_INF, rule INF_greatest, cut_tac p = \"\\<lambda> n . p !! n\" in until_always, simp)\n        next\n          have \"\\<And> n . \\<box> p \\<le> p !! n\"\n            by (simp add: always_def INF_lower)\n          also have \"\\<And> n . p !! n \\<le> (SUP x:{i. i < n}. (- p) !! x) \\<squnion> p !! n\"\n            by simp\n          finally show \"\\<box> p \\<le> -(p until -p)\"\n            apply (simp add: until_def uminus_SUP uminus_INF)\n            by (rule INF_greatest, simp)\n        qed\n\n      lemma neg_always_eventually: \"\\<box> p = - \\<diamondsuit> (- p)\"\n        by (simp add: fun_eq_iff always_def eventually_def until_def uminus_SUP)\n        \n      lemma neg_true_until_always: \"-(\\<top> until -p) = \\<box> p\"\n        by (simp add: fun_eq_iff always_def until_def uminus_SUP uminus_INF)\n\n      lemma true_until_eventually: \"(\\<top> until p) = \\<diamondsuit> p\"\n        by (cut_tac p = \"-p\" in neg_always_eventually, cut_tac p = \"-p\" in neg_true_until_always, simp)\n    end\n\ntext{*\n  Boolean algebras with $b!!i = b$ form a temporal class.\n*}\n\n  instantiation bool :: temporal\n    begin\n      definition at_bool_def [simp]: \"(p::bool) !! i = p\"\n    instance proof \n      qed auto\n    end\n\n  type_synonym 'a trace = \"nat \\<Rightarrow> 'a\"\n\ntext{*\n  Asumming that $\\tv a::temporal$ is a type of class $temporal$, and $\\tv b$ is an arbitrary type,\n  we would like to create the instantiation of $\\tv b\\ trace \\Rightarrow \\tv a$ as a temporal\n  class. However Isabelle allows only instatiations of functions from a class to another \n  class. To solve this problem we introduce a new class called trace with an operation\n  $\\mathit{suffix}::\\tv a \\Rightarrow nat \\Rightarrow \\tv a$ where \n  $\\mathit{suffix}\\;a\\;i\\;j = (a[i..])\\; j = a\\;(i+j)$ when\n  $a$ is a trace with elements of some type $\\tv b$ ($\\tv a = nat \\Rightarrow \\tv b$). \n*}\n\n  class trace =\n    fixes suffix :: \"'a \\<Rightarrow> nat \\<Rightarrow> 'a\" (\"_[_ ..]\" [80, 15] 80)\n    assumes [simp]: \"a[i..][j..] = a[i + j..]\"\n    assumes [simp]: \"a[0..] = a\"\n    begin\n      definition \"next_trace\" :: \"'a \\<Rightarrow> 'a\"  (\"\\<odot> (_)\" [900] 900) where\n        \"\\<odot> p = p[Suc 0..]\"\n    end\n\n  instantiation \"fun\" :: (trace, temporal) temporal\n    begin\n      definition at_fun_def: \"(P:: 'a \\<Rightarrow> 'b) !! i = (\\<lambda> x . (P (x[i..])) !! i)\"\n      instance proof qed  (simp_all add: at_fun_def add.commute fun_eq_iff le_fun_def)\n    end\n\ntext{*\n  In the last part of our formalization, we need to instantiate the functions\n  from $nat$ to some arbitrary type $\\tv a$ as a trace class. However, this again is not\n  possible using the instatiation mechanism of Isabelle. We solve this problem\n  by creating another class called $nat$, and then we instatiate the functions\n  from $\\tv a::nat$ to $\\tv b$ as traces. The class $nat$ is defined such that if we\n  have a type $\\tv a::nat$, then $\\tv a$ is isomorphic to the type $nat$. \n*}\n\n  class nat = zero + plus + minus +\n    fixes RepNat :: \"'a \\<Rightarrow> nat\"\n    fixes AbsNat :: \"nat \\<Rightarrow> 'a\"\n    assumes [simp]: \"RepNat (AbsNat n) = n\"\n    and [simp]: \"AbsNat (RepNat x) = x\"\n    and zero_Nat_def: \"0 = AbsNat 0\"\n    and plus_Nat_def: \"a + b = AbsNat (RepNat a + RepNat b)\"\n    and minus_Nat_def: \"a - b = AbsNat (RepNat a - RepNat b)\"\n  begin\n    lemma AbsNat_plus: \"AbsNat (i + j) = AbsNat i + AbsNat j\"\n      by (simp add: plus_Nat_def)\n    lemma AbsNat_zero [simp]: \"AbsNat 0 + i = i\"\n      by (simp add: plus_Nat_def)\n\n    subclass comm_monoid_diff \n      apply (unfold_locales)\n        apply (simp_all add: plus_Nat_def zero_Nat_def minus_Nat_def add.assoc)\n        by (simp add: add.commute)\n  end\n\ntext{*\n  The type natural numbers is an instantiation of the class $nat$.\n*}\n\n  instantiation nat :: nat\n    begin\n      definition RepNat_nat_def [simp]: \"(RepNat:: nat \\<Rightarrow> nat) = id\"\n      definition AbsNat_nat_def [simp]: \"(AbsNat:: nat \\<Rightarrow> nat) = id\"\n      instance proof \n        qed auto\n    end\n\ntext{*\n  Finally, functions from $\\tv a::nat$ to some arbitrary type $\\tv b$ are instatiated\n  as a trace class. \n*}\n\n  instantiation \"fun\" :: (nat, type) trace\n    begin\n      definition at_trace_def [simp]: \"((t :: 'a \\<Rightarrow> 'b)[i..]) j = (t  (AbsNat i + j))\"\n    instance proof\n      qed (simp_all add: fun_eq_iff AbsNat_plus add.assoc)\n    end\n\ntext{*\n  By putting together all class definitions and instatiations introduced so far, we obtain the\n  temporal class structure for predicates on traces with arbitrary number of parameters.\n\n  For example in the next lemma $r$ and $r'$ are predicate relations, and the operator\n  always is available for them as a consequence of the above construction.\n*}\n\n\n  lemma \"(\\<box> r) OO (\\<box> r') \\<le> (\\<box> (r OO r'))\"\n    by (simp add: le_fun_def always_def at_fun_def, auto)\n\n  end\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/RefinementReactive/Temporal.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382236515258, "lm_q2_score": 0.8221891239865619, "lm_q1q2_score": 0.7083473573849866}}
{"text": "theory DBM\n  imports Floyd_Warshall Timed_Automata\nbegin\n\nchapter \\<open>Difference Bound Matrices\\<close>\n\nsection \\<open>Definitions\\<close>\n\ntext \\<open>\n  Difference Bound Matrices (DBMs) constrain differences of clocks\n  (or more precisely, the difference of values assigned to individual clocks by a valuation).\n  The possible constraints are given by the following datatype:\n\\<close>\n\ndatatype ('t::time) DBMEntry = Le 't | Lt 't | INF (\"\\<infinity>\")\n\ntext \\<open>\\noindent This yields a simple definition of DBMs:\\<close>\n\ntype_synonym 't DBM = \"nat \\<Rightarrow> nat \\<Rightarrow> 't DBMEntry\"\n\ntext \\<open>\\noindent\n  To relate clocks with rows and columns of\n  a DBM, we use a clock numbering \\<open>v\\<close> of type @{typ \"'c \\<Rightarrow> nat\"} to map clocks to indices.\n  DBMs will regularly be  accompanied by a natural number $n$,\n  which designates the number of clocks constrained by the matrix.\n  To be able to represent the full set of clock constraints with DBMs, we add an imaginary\n  clock \\<open>\\<zero>\\<close>, which shall be assigned to 0 in every valuation.\n  In the following predicate we explicitly keep track of \\<open>\\<zero>\\<close>.\n\\<close>\n\ninductive dbm_entry_val :: \"('c, 't) cval \\<Rightarrow> 'c option \\<Rightarrow> 'c option \\<Rightarrow> ('t::time) DBMEntry \\<Rightarrow> bool\"\nwhere\n  \"u r \\<le> d \\<Longrightarrow> dbm_entry_val u (Some r) None (Le d)\" |\n  \"-u c \\<le> d \\<Longrightarrow> dbm_entry_val u None (Some c) (Le d)\" |\n  \"u r < d \\<Longrightarrow> dbm_entry_val u (Some r) None (Lt d)\" |\n  \"-u c < d \\<Longrightarrow> dbm_entry_val u None (Some c) (Lt d)\" |\n  \"u r - u c \\<le> d \\<Longrightarrow> dbm_entry_val u (Some r) (Some c) (Le d)\" |\n  \"u r - u c < d \\<Longrightarrow> dbm_entry_val u (Some r) (Some c) (Lt d)\" |\n  \"dbm_entry_val _ _ _ \\<infinity>\"\n\ndeclare dbm_entry_val.intros[intro]\ninductive_cases[elim!]: \"dbm_entry_val u None (Some c) (Le d)\"\ninductive_cases[elim!]: \"dbm_entry_val u (Some c) None (Le d)\"\ninductive_cases[elim!]: \"dbm_entry_val u None (Some c) (Lt d)\"\ninductive_cases[elim!]: \"dbm_entry_val u (Some c) None (Lt d)\"\ninductive_cases[elim!]: \"dbm_entry_val u (Some r) (Some c) (Le d)\"\ninductive_cases[elim!]: \"dbm_entry_val u (Some r) (Some c) (Lt d)\"\n\nfun dbm_entry_bound :: \"('t::time) DBMEntry \\<Rightarrow> 't\"\nwhere\n  \"dbm_entry_bound (Le t) = t\" |\n  \"dbm_entry_bound (Lt t) = t\" |\n  \"dbm_entry_bound \\<infinity> = 0\"\n\ninductive dbm_lt :: \"('t::time) DBMEntry \\<Rightarrow> 't DBMEntry \\<Rightarrow> bool\"\n(\"_ \\<prec> _\" [51, 51] 50)\nwhere\n  \"dbm_lt (Lt _) \\<infinity>\" |\n  \"dbm_lt (Le _) \\<infinity>\" |\n  \"a < b  \\<Longrightarrow> dbm_lt (Le a) (Le b)\" |\n  \"a < b  \\<Longrightarrow> dbm_lt (Le a) (Lt b)\" |\n  \"a \\<le> b  \\<Longrightarrow> dbm_lt (Lt a) (Le b)\" |\n  \"a < b  \\<Longrightarrow> dbm_lt (Lt a) (Lt b)\"\n\ndeclare dbm_lt.intros[intro]\n\ndefinition dbm_le :: \"('t::time) DBMEntry \\<Rightarrow> 't DBMEntry \\<Rightarrow> bool\"\n(\"_ \\<preceq> _\" [51, 51] 50)\nwhere\n  \"dbm_le a b \\<equiv> (a \\<prec> b) \\<or> a = b\"\n\ntext \\<open>\n  Now a valuation is contained in the zone represented by a DBM if it fulfills all individual\n  constraints:\n\\<close>\n\ndefinition DBM_val_bounded :: \"('c \\<Rightarrow> nat) \\<Rightarrow> ('c, 't) cval \\<Rightarrow> ('t::time) DBM \\<Rightarrow> nat \\<Rightarrow> bool\"\nwhere\n  \"DBM_val_bounded v u m n \\<equiv> Le 0 \\<preceq> m 0 0 \\<and>\n    (\\<forall> c. v c \\<le> n \\<longrightarrow> (dbm_entry_val u None (Some c) (m 0 (v c))\n                      \\<and> dbm_entry_val u (Some c) None (m (v c) 0)))\n    \\<and> (\\<forall> c1 c2. v c1 \\<le> n \\<and> v c2 \\<le> n \\<longrightarrow> dbm_entry_val u (Some c1) (Some c2) (m (v c1) (v c2)))\"\n\nabbreviation DBM_val_bounded_abbrev ::\n  \"('c, 't) cval \\<Rightarrow> ('c \\<Rightarrow> nat) \\<Rightarrow> nat \\<Rightarrow> ('t::time) DBM \\<Rightarrow> bool\"\n(\"_ \\<turnstile>\\<^bsub>_,_\\<^esub> _\")\nwhere\n  \"u \\<turnstile>\\<^bsub>v,n\\<^esub> M \\<equiv> DBM_val_bounded v u M n\"\n\nabbreviation\n  \"dmin a b \\<equiv> if a \\<prec> b then a else b\"\n\nlemma dbm_le_dbm_min:\n  \"a \\<preceq> b \\<Longrightarrow> a = dmin a b\" unfolding dbm_le_def\nby auto\n\nlemma dbm_lt_asym:\n  assumes \"e \\<prec> f\"\n  shows \"~ f \\<prec> e\"\nusing assms\nproof (safe, cases e f rule: dbm_lt.cases, goal_cases)\n  case 1 from this(2) show ?case using 1(3-) by (cases f e rule: dbm_lt.cases) auto\nnext\n  case 2 from this(2) show ?case using 2(3-) by (cases f e rule: dbm_lt.cases) auto\nnext\n  case 3 from this(2) show ?case using 3(3-) by (cases f e rule: dbm_lt.cases) auto\nnext\n  case 4 from this(2) show ?case using 4(3-) by (cases f e rule: dbm_lt.cases) auto\nnext\n  case 5 from this(2) show ?case using 5(3-) by (cases f e rule: dbm_lt.cases) auto\nnext\n  case 6 from this(2) show ?case using 6(3-) by (cases f e rule: dbm_lt.cases) auto\nqed\n\nlemma dbm_le_dbm_min2:\n  \"a \\<preceq> b \\<Longrightarrow> a = dmin b a\"\nusing dbm_lt_asym by (auto simp: dbm_le_def)\n\nlemma dmb_le_dbm_entry_bound_inf:\n  \"a \\<preceq> b \\<Longrightarrow> a = \\<infinity> \\<Longrightarrow> b = \\<infinity>\"\napply (auto simp: dbm_le_def)\n  apply (cases rule: dbm_lt.cases)\nby auto\n\nlemma dbm_not_lt_eq: \"\\<not> a \\<prec> b \\<Longrightarrow> \\<not> b \\<prec> a \\<Longrightarrow> a = b\"\napply (cases a)\n  apply (cases b, fastforce+)+\ndone\n\nlemma dbm_not_lt_impl: \"\\<not> a \\<prec> b \\<Longrightarrow> b \\<prec> a \\<or> a = b\" using dbm_not_lt_eq by auto\n\nlemma \"dmin a b = dmin b a\"\nproof (cases \"a \\<prec> b\")\n  case True thus ?thesis by (simp add: dbm_lt_asym)\nnext\n  case False thus ?thesis by (simp add: dbm_not_lt_eq)\nqed\n\nlemma dbm_lt_trans: \"a \\<prec> b \\<Longrightarrow> b \\<prec> c \\<Longrightarrow> a \\<prec> c\"\nproof (cases a b rule: dbm_lt.cases, goal_cases)\n  case 1 thus ?case by simp\nnext\n  case 2 from this(2-) show ?case by (cases rule: dbm_lt.cases) simp+\nnext\n  case 3 from this(2-) show ?case by (cases rule: dbm_lt.cases) simp+\nnext\n  case 4 from this(2-) show ?case by (cases rule: dbm_lt.cases) auto\nnext\n  case 5 from this(2-) show ?case by (cases rule: dbm_lt.cases) auto\nnext\n  case 6 from this(2-) show ?case by (cases rule: dbm_lt.cases) auto\nnext\n  case 7 from this(2-) show ?case by (cases rule: dbm_lt.cases) auto\nqed\n\nlemma aux_3: \"\\<not> a \\<prec> b \\<Longrightarrow> \\<not> b \\<prec> c \\<Longrightarrow> a \\<prec> c \\<Longrightarrow> c = a\"\nproof goal_cases\n  case 1 thus ?case\n  proof (cases \"c \\<prec> b\")\n    case True\n    with \\<open>a \\<prec> c\\<close> have \"a \\<prec> b\" by (rule dbm_lt_trans)\n    thus ?thesis using 1 by auto\n  next\n    case False thus ?thesis using dbm_not_lt_eq 1 by auto\n  qed\nqed\n\ninductive_cases[elim!]: \"\\<infinity> \\<prec> x\"\n\nlemma dbm_lt_asymmetric[simp]: \"x \\<prec> y \\<Longrightarrow> y \\<prec> x \\<Longrightarrow> False\"\nby (cases x y rule: dbm_lt.cases) (auto elim: dbm_lt.cases)\n\nlemma le_dbm_le: \"Le a \\<preceq> Le b \\<Longrightarrow> a \\<le> b\" unfolding dbm_le_def by (auto elim: dbm_lt.cases)\n\nlemma le_dbm_lt: \"Le a \\<preceq> Lt b \\<Longrightarrow> a < b\" unfolding dbm_le_def by (auto elim: dbm_lt.cases)\n\nlemma lt_dbm_le: \"Lt a \\<preceq> Le b \\<Longrightarrow> a \\<le> b\" unfolding dbm_le_def by (auto elim: dbm_lt.cases)\n\nlemma lt_dbm_lt: \"Lt a \\<preceq> Lt b \\<Longrightarrow> a \\<le> b\" unfolding dbm_le_def by (auto elim: dbm_lt.cases)\n\nlemma not_dbm_le_le_impl: \"\\<not> Le a \\<prec> Le b \\<Longrightarrow> a \\<ge> b\" by (metis dbm_lt.intros(3) not_less)\n\nlemma not_dbm_lt_le_impl: \"\\<not> Lt a \\<prec> Le b \\<Longrightarrow> a > b\" by (metis dbm_lt.intros(5) not_less)\n\nlemma not_dbm_lt_lt_impl: \"\\<not> Lt a \\<prec> Lt b \\<Longrightarrow> a \\<ge> b\" by (metis dbm_lt.intros(6) not_less)\n\nlemma not_dbm_le_lt_impl: \"\\<not> Le a \\<prec> Lt b \\<Longrightarrow> a \\<ge> b\" by (metis dbm_lt.intros(4) not_less)\n\n(*>*)\n\n(*<*)\n\nfun dbm_add :: \"('t::time) DBMEntry \\<Rightarrow> 't DBMEntry \\<Rightarrow> 't DBMEntry\" (infixl \"\\<otimes>\" 70)\nwhere\n  \"dbm_add \\<infinity>     _      = \\<infinity>\" |\n  \"dbm_add _      \\<infinity>     = \\<infinity>\" |\n  \"dbm_add (Le a) (Le b) = (Le (a+b))\" |\n  \"dbm_add (Le a) (Lt b) = (Lt (a+b))\" |\n  \"dbm_add (Lt a) (Le b) = (Lt (a+b))\" |\n  \"dbm_add (Lt a) (Lt b) = (Lt (a+b))\"\n\nthm dbm_add.simps\n\nlemma aux_4: \"x \\<prec> y \\<Longrightarrow> \\<not> dbm_add x z \\<prec> dbm_add y z \\<Longrightarrow> dbm_add x z = dbm_add y z\"\nby (cases x y rule: dbm_lt.cases) ((cases z), auto)+\n\nlemma aux_5: \"\\<not> x \\<prec> y \\<Longrightarrow> dbm_add x z \\<prec> dbm_add y z \\<Longrightarrow> dbm_add y z = dbm_add x z\"\nproof -\n  assume lt: \"dbm_add x z \\<prec> dbm_add y z\" \"\\<not> x \\<prec> y\"\n  hence \"x = y \\<or> y \\<prec> x\" by (auto simp: dbm_not_lt_eq)\n  thus ?thesis\n  proof\n    assume \"x = y\" thus ?thesis by simp\n  next\n    assume \"y \\<prec> x\"\n    thus ?thesis\n    proof (cases y x rule: dbm_lt.cases, goal_cases)\n      case 1 thus ?case using lt by auto\n    next\n      case 2 thus ?case using lt by auto\n    next\n      case 3 thus ?case using dbm_lt_asymmetric lt(1) by (cases z) fastforce+\n    next\n      case 4 thus ?case using dbm_lt_asymmetric lt(1) by (cases z) fastforce+\n    next\n      case 5 thus ?case using dbm_lt_asymmetric lt(1) by (cases z) fastforce+\n    next\n      case 6 thus ?case using dbm_lt_asymmetric lt(1) by (cases z) fastforce+\n    qed\n  qed\nqed\n\nlemma aux_42: \"x \\<prec> y \\<Longrightarrow> \\<not> dbm_add z x \\<prec> dbm_add z y \\<Longrightarrow> dbm_add z x = dbm_add z y\"\nby (cases x y rule: dbm_lt.cases) ((cases z), auto)+\n\nlemma aux_52: \"\\<not> x \\<prec> y \\<Longrightarrow> dbm_add z x \\<prec> dbm_add z y \\<Longrightarrow> dbm_add z y = dbm_add z x\"\nproof -\n  assume lt: \"dbm_add z x \\<prec> dbm_add z y\" \"\\<not> x \\<prec> y\"\n  hence \"x = y \\<or> y \\<prec> x\" by (auto simp: dbm_not_lt_eq)\n  thus ?thesis\n  proof\n    assume \"x = y\" thus ?thesis by simp\n  next\n    assume \"y \\<prec> x\"\n    thus ?thesis\n    proof (cases y x rule: dbm_lt.cases, goal_cases)\n      case 1 thus ?case using lt by (cases z) fastforce+\n    next\n      case 2 thus ?case using lt by (cases z) fastforce+\n    next\n      case 3 thus ?case using dbm_lt_asymmetric lt(1) by (cases z) fastforce+\n    next\n      case 4 thus ?case using dbm_lt_asymmetric lt(1) by (cases z) fastforce+\n    next\n      case 5 thus ?case using dbm_lt_asymmetric lt(1) by (cases z) fastforce+\n    next\n      case 6 thus ?case using dbm_lt_asymmetric lt(1) by (cases z) fastforce+\n    qed\n  qed\nqed\n\nlemma dbm_add_not_inf:\n  \"a \\<noteq> \\<infinity> \\<Longrightarrow> b \\<noteq> \\<infinity> \\<Longrightarrow> dbm_add a b \\<noteq> \\<infinity>\"\nby (cases a, auto, cases b, auto, cases b, auto)\n\nlemma dbm_le_not_inf:\n  \"a \\<preceq> b \\<Longrightarrow> b \\<noteq> \\<infinity> \\<Longrightarrow> a \\<noteq> \\<infinity>\"\nby (cases \"a = b\") (auto simp: dbm_le_def)\n\nsection \\<open>DBM Entries Form a Linearly Ordered Abelian Monoid\\<close>\n\ninstantiation DBMEntry :: (time) linorder\nbegin\n  definition less_eq: \"(\\<le>) \\<equiv> dbm_le\"\n  definition less: \"(<) = dbm_lt\"\n  instance\n  proof ((standard; unfold less less_eq), goal_cases)\n    case 1 thus ?case unfolding dbm_le_def using dbm_lt_asymmetric by auto\n  next\n    case 2 thus ?case by (simp add: dbm_le_def)\n  next\n    case 3 thus ?case unfolding dbm_le_def using dbm_lt_trans by auto\n  next\n    case 4 thus ?case unfolding dbm_le_def using dbm_lt_asymmetric by auto\n  next\n    case 5 thus ?case unfolding dbm_le_def using dbm_not_lt_eq by auto\n  qed\nend\n\ninstantiation DBMEntry :: (time) linordered_ab_monoid_add\nbegin\n  definition mult: \"(+) = dbm_add\"\n  definition neutral: \"neutral = Le 0\"\n  instance proof ((standard; unfold mult neutral less less_eq), goal_cases)\n    case (1 a b c) thus ?case by (cases a; cases b; cases c; auto)\n  next\n    case (2 a b) thus ?case by (cases a; cases b) auto\n  next\n    case (3 a b c)\n    thus ?case unfolding dbm_le_def\n    apply safe\n     apply (rule dbm_lt.cases)\n          apply assumption\n    by (cases c; fastforce)+\n  next\n    case (4 x) thus ?case by (cases x) auto\n  next\n    case (5 x) thus ?case by (cases x) auto\n  qed\nend\n\ninterpretation linordered_monoid: linordered_ab_monoid_add dbm_add dbm_le dbm_lt \"Le 0\"\n  apply (standard, fold neutral mult less_eq less)\nusing add.commute add.commute add_left_mono assoc by auto\n\nlemma Le_Le_dbm_lt_D[dest]: \"Le a \\<prec> Lt b \\<Longrightarrow> a < b\" by (cases rule: dbm_lt.cases) auto\nlemma Le_Lt_dbm_lt_D[dest]: \"Le a \\<prec> Le b \\<Longrightarrow> a < b\" by (cases rule: dbm_lt.cases) auto\nlemma Lt_Le_dbm_lt_D[dest]: \"Lt a \\<prec> Le b \\<Longrightarrow> a \\<le> b\" by (cases rule: dbm_lt.cases) auto\nlemma Lt_Lt_dbm_lt_D[dest]: \"Lt a \\<prec> Lt b \\<Longrightarrow> a < b\" by (cases rule: dbm_lt.cases) auto\n\nlemma Le_le_LeI[intro]: \"a \\<le> b \\<Longrightarrow> Le a \\<le> Le b\" unfolding less_eq dbm_le_def by auto\nlemma Lt_le_LeI[intro]: \"a \\<le> b \\<Longrightarrow> Lt a \\<le> Le b\" unfolding less_eq dbm_le_def by auto\nlemma Lt_le_LtI[intro]: \"a \\<le> b \\<Longrightarrow> Lt a \\<le> Lt b\" unfolding less_eq dbm_le_def by auto\nlemma Le_le_LtI[intro]: \"a < b \\<Longrightarrow> Le a \\<le> Lt b\" unfolding less_eq dbm_le_def by auto\nlemma Lt_lt_LeI: \"x \\<le> y \\<Longrightarrow> Lt x < Le y\" unfolding less by auto\n\nlemma Le_le_LeD[dest]: \"Le a \\<le> Le b \\<Longrightarrow> a \\<le> b\" unfolding dbm_le_def less_eq by auto\nlemma Le_le_LtD[dest]: \"Le a \\<le> Lt b \\<Longrightarrow> a < b\" unfolding dbm_le_def less_eq by auto\nlemma Lt_le_LeD[dest]: \"Lt a \\<le> Le b \\<Longrightarrow> a \\<le> b\" unfolding less_eq dbm_le_def by auto\nlemma Lt_le_LtD[dest]: \"Lt a \\<le> Lt b \\<Longrightarrow> a \\<le> b\" unfolding less_eq dbm_le_def by auto\n\nlemma inf_not_le_Le[simp]: \"\\<infinity> \\<le> Le x = False\" unfolding less_eq dbm_le_def by auto\nlemma inf_not_le_Lt[simp]: \"\\<infinity> \\<le> Lt x = False\" unfolding less_eq dbm_le_def by auto\nlemma inf_not_lt[simp]: \"\\<infinity> \\<prec> x = False\" by auto\n\nlemma any_le_inf: \"x \\<le> \\<infinity>\" by (metis less_eq dmb_le_dbm_entry_bound_inf le_cases)\n\n\nsection \\<open>Basic Properties of DBMs\\<close>\n\nsubsection \\<open>DBMs and Length of Paths\\<close>\n\nlemma dbm_entry_val_add_1: \"dbm_entry_val u (Some c) (Some d) a \\<Longrightarrow>  dbm_entry_val u (Some d) None b\n       \\<Longrightarrow> dbm_entry_val u (Some c) None (dbm_add a b)\"\nproof (cases a, goal_cases)\n  case 1 thus ?thesis\n  apply (cases b)\n    apply auto\n   using add_mono_thms_linordered_semiring(1) apply fastforce\n  using add_le_less_mono by fastforce\nnext\n  case 2 thus ?thesis\n  apply (cases b)\n    apply auto\n   apply (simp add: dbm_entry_val.intros(3) diff_less_eq less_le_trans)\n  by (metis add_le_less_mono dbm_entry_val.intros(3) diff_add_cancel less_imp_le)\nnext\n  case 3 thus ?thesis by (cases b) auto\nqed\n\nlemma dbm_entry_val_add_2: \"dbm_entry_val u None (Some c) a \\<Longrightarrow> dbm_entry_val u (Some c) (Some d) b\n       \\<Longrightarrow> dbm_entry_val u None (Some d) (dbm_add a b)\"\nproof (cases a, goal_cases)\n  case 1 thus ?thesis\n  apply (cases b)\n    apply auto\n   using add_mono_thms_linordered_semiring(1) apply fastforce\n  using add_le_less_mono by fastforce\nnext\n  case 2 thus ?thesis\n  apply (cases b)\n    apply auto\n   using add_mono_thms_linordered_field(3) apply fastforce\n  using add_strict_mono by fastforce\nnext\n  case 3 thus ?thesis by (cases b) auto\nqed\n\nlemma dbm_entry_val_add_3:\n  \"dbm_entry_val u (Some c) (Some d) a \\<Longrightarrow>  dbm_entry_val u (Some d) (Some e) b\n   \\<Longrightarrow> dbm_entry_val u (Some c) (Some e) (dbm_add a b)\"\nproof (cases a, goal_cases)\n  case 1 thus ?thesis\n  apply (cases b)\n    apply auto\n   using add_mono_thms_linordered_semiring(1) apply fastforce\n  using add_le_less_mono by fastforce\nnext\n  case 2 thus ?thesis\n  apply (cases b)\n    apply auto\n   using add_mono_thms_linordered_field(3) apply fastforce\n  using add_strict_mono by fastforce\nnext\n  case 3 thus ?thesis by (cases b) auto\nqed\n\nlemma dbm_entry_val_add_4:\n  \"dbm_entry_val u (Some c) None a \\<Longrightarrow> dbm_entry_val u None (Some d) b\n   \\<Longrightarrow> dbm_entry_val u (Some c) (Some d) (dbm_add a b)\"\nproof (cases a, goal_cases)\n  case 1 thus ?thesis\n  apply (cases b)\n    apply auto\n   using add_mono_thms_linordered_semiring(1) apply fastforce\n  using add_le_less_mono by fastforce\nnext\n  case 2 thus ?thesis\n  apply (cases b)\n    apply auto\n   using add_mono_thms_linordered_field(3) apply fastforce\n  using add_strict_mono by fastforce\nnext\n  case 3 thus ?thesis by (cases b) auto\nqed\n\nno_notation dbm_add (infixl \"\\<otimes>\" 70)\n\nlemma DBM_val_bounded_len_1'_aux:\n  assumes \"DBM_val_bounded v u m n\" \"v c \\<le> n\" \"\\<forall> k \\<in> set vs. k > 0 \\<and> k \\<le> n \\<and> (\\<exists> c. v c = k)\"\n  shows \"dbm_entry_val u (Some c) None (len m (v c) 0 vs)\" using assms\nproof (induction vs arbitrary: c)\n  case Nil then show ?case unfolding DBM_val_bounded_def by auto\nnext\n  case (Cons k vs)\n  then obtain c' where c': \"k > 0\" \"k \\<le> n\" \"v c' = k\" by auto\n  with Cons have \"dbm_entry_val u (Some c') None (len m (v c') 0 vs)\" by auto\n  moreover have \"dbm_entry_val u (Some c) (Some c') (m (v c) (v c'))\" using Cons.prems c'\n  by (auto simp add: DBM_val_bounded_def)\n  ultimately have \"dbm_entry_val u (Some c) None (m (v c) (v c') + len m (v c') 0 vs)\"\n  using dbm_entry_val_add_1 unfolding mult by fastforce\n  with c' show ?case unfolding DBM_val_bounded_def by simp\nqed\n\nlemma DBM_val_bounded_len_3'_aux:\n  \"DBM_val_bounded v u m n \\<Longrightarrow> v c \\<le> n \\<Longrightarrow> v d \\<le> n \\<Longrightarrow> \\<forall> k \\<in> set vs. k > 0 \\<and> k \\<le> n \\<and> (\\<exists> c. v c = k)\n   \\<Longrightarrow> dbm_entry_val u (Some c) (Some d) (len m (v c) (v d) vs)\"\nproof (induction vs arbitrary: c)\n  case Nil thus ?case unfolding DBM_val_bounded_def by auto\nnext\n  case (Cons k vs)\n  then obtain c' where c': \"k > 0\" \"k \\<le> n\" \"v c' = k\" by auto\n  with Cons have \"dbm_entry_val u (Some c') (Some d) (len m (v c') (v d) vs)\" by auto\n  moreover have \"dbm_entry_val u (Some c) (Some c') (m (v c) (v c'))\" using Cons.prems c'\n  by (auto simp add: DBM_val_bounded_def)\n  ultimately have \"dbm_entry_val u (Some c) (Some d) (m (v c) (v c') + len m (v c') (v d) vs)\"\n  using dbm_entry_val_add_3 unfolding mult by fastforce\n  with c' show ?case unfolding DBM_val_bounded_def by simp\nqed\n\nlemma DBM_val_bounded_len_2'_aux:\n  \"DBM_val_bounded v u m n \\<Longrightarrow> v c \\<le> n \\<Longrightarrow> \\<forall> k \\<in> set vs. k > 0 \\<and> k \\<le> n \\<and> (\\<exists> c. v c = k)\n  \\<Longrightarrow> dbm_entry_val u None (Some c) (len m 0 (v c) vs)\"\nproof (cases vs, goal_cases)\n  case 1 then show ?thesis unfolding DBM_val_bounded_def by auto\nnext\n  case (2 k vs)\n  then obtain c' where c': \"k > 0\" \"k \\<le> n\" \"v c' = k\" by auto\n  with 2 have \"dbm_entry_val u (Some c') (Some c) (len m (v c') (v c) vs)\"\n  using DBM_val_bounded_len_3'_aux by auto\n  moreover have \"dbm_entry_val u None (Some c') (m 0 (v c'))\"\n  using 2 c' by (auto simp add: DBM_val_bounded_def)\n  ultimately have \"dbm_entry_val u None (Some c) (m 0 (v c') + len m (v c') (v c) vs)\"\n  using dbm_entry_val_add_2 unfolding mult by fastforce\n  with 2(4) c' show ?case unfolding DBM_val_bounded_def by simp\nqed\n\nlemma cnt_0_D:\n  \"cnt x xs = 0 \\<Longrightarrow> x \\<notin> set xs\"\napply (induction xs)\n apply simp\napply (rename_tac a xs)\napply (case_tac \"x = a\")\nby simp+\n\nlemma cnt_at_most_1_D:\n  \"cnt x (xs @ x # ys) \\<le> 1 \\<Longrightarrow> x \\<notin> set xs \\<and> x \\<notin> set ys\"\napply (induction xs)\n  apply auto[]\n  using cnt_0_D apply force\n apply (rename_tac a xs)\n apply (case_tac \"a = x\")\n  apply simp\n apply simp\ndone\n\nlemma nat_list_0 [intro]:\n  \"x \\<in> set xs \\<Longrightarrow> 0 \\<notin> set (xs :: nat list) \\<Longrightarrow> x > 0\"\nby (induction xs) auto\n\nlemma DBM_val_bounded_len':\n  fixes v\n  defines \"vo \\<equiv> \\<lambda> k. if k = 0 then None else Some (SOME c. v c = k)\"\n  assumes \"DBM_val_bounded v u m n\" \"cnt 0 (i # j # vs) \\<le> 1\"\n          \"\\<forall> k \\<in> set (i # j # vs). k > 0 \\<longrightarrow> k \\<le> n \\<and> (\\<exists> c. v c = k)\"\n  shows \"dbm_entry_val u (vo i) (vo j) (len m i j vs)\"\nproof -\n  show ?thesis\n  proof (cases \"\\<forall> k \\<in> set vs. k > 0\")\n    case True\n    with assms have *: \"\\<forall> k \\<in> set vs. k > 0 \\<and> k \\<le> n \\<and> (\\<exists> c. v c = k)\" by auto\n    show ?thesis\n    proof (cases \"i = 0\")\n      case True\n      then have i: \"vo i = None\" by (simp add: vo_def)\n      show ?thesis\n      proof (cases \"j = 0\")\n        case True with assms \\<open>i = 0\\<close> show ?thesis by auto\n      next\n        case False\n        with assms obtain c2 where c2: \"j \\<le> n\" \"v c2 = j\" \"vo j = Some c2\"\n        unfolding vo_def by (fastforce intro: someI)\n        with \\<open>i = 0\\<close> i DBM_val_bounded_len_2'_aux[OF assms(2) _ *] show ?thesis by auto\n      qed\n    next\n      case False\n      with assms(4) obtain c1 where c1: \"i \\<le> n\" \"v c1 = i\" \"vo i = Some c1\"\n      unfolding vo_def by (fastforce intro: someI)\n      show ?thesis\n      proof (cases \"j = 0\")\n        case True\n        with DBM_val_bounded_len_1'_aux[OF assms(2) _ *] c1 show ?thesis by (auto simp: vo_def)\n      next\n        case False\n        with assms obtain c2 where c2: \"j \\<le> n\" \"v c2 = j\" \"vo j = Some c2\"\n        unfolding vo_def by (fastforce intro: someI)\n        with c1 DBM_val_bounded_len_3'_aux[OF assms(2) _ _ *] show ?thesis by auto\n      qed\n    qed\n  next\n    case False\n    then have \"\\<exists> k \\<in> set vs. k = 0\" by auto\n    then obtain us ws where vs: \"vs = us @ 0 # ws\" by (meson split_list_last) \n    with cnt_at_most_1_D[of 0 \"i # j # us\"] assms(3) have\n      \"0 \\<notin> set us\" \"0 \\<notin> set ws\" \"i \\<noteq> 0\" \"j \\<noteq> 0\"\n    by auto\n    with vs have vs: \"vs = us @ 0 # ws\" \"\\<forall> k \\<in> set us. k > 0\" \"\\<forall> k \\<in> set ws. k > 0\" by auto\n    with assms(4) have v:\n      \"\\<forall>k\\<in>set us. 0 < k \\<and> k \\<le> n \\<and> (\\<exists>c. v c = k)\" \"\\<forall>k\\<in>set ws. 0 < k \\<and> k \\<le> n \\<and> (\\<exists>c. v c = k)\"\n    by auto\n    from \\<open>i \\<noteq> 0\\<close> \\<open>j \\<noteq> 0\\<close> assms obtain c1 c2 where\n      c1: \"i \\<le> n\" \"v c1 = i\" \"vo i = Some c1\" and c2: \"j \\<le> n\" \"v c2 = j\" \"vo j = Some c2\"\n    unfolding vo_def by (fastforce intro: someI)\n    with dbm_entry_val_add_4 [OF DBM_val_bounded_len_1'_aux[OF assms(2) _ v(1)] DBM_val_bounded_len_2'_aux[OF assms(2) _ v(2)]]\n    have \"dbm_entry_val u (Some c1) (Some c2) (dbm_add (len m (v c1) 0 us) (len m 0 (v c2) ws))\" by auto\n    moreover from vs have \"len m (v c1) (v c2) vs = dbm_add (len m (v c1) 0 us) (len m 0 (v c2) ws)\"\n    by (simp add: len_comp mult)\n    ultimately show ?thesis using c1 c2 by auto\n  qed\nqed\n\n\n\nlemma DBM_val_bounded_len'2:\n  fixes v\n  assumes \"DBM_val_bounded v u m n\" \"0 \\<notin> set vs\" \"v c \\<le> n\"\n          \"\\<forall> k \\<in> set vs. k > 0 \\<longrightarrow> k \\<le> n \\<and> (\\<exists> c. v c = k)\"\n  shows \"dbm_entry_val u None (Some c) (len m 0 (v c) vs)\"\nusing DBM_val_bounded_len_2'_aux[OF assms(1,3)] assms(2,4) by fastforce\n\nlemma DBM_val_bounded_len'3:\n  fixes v\n  assumes \"DBM_val_bounded v u m n\" \"cnt 0 vs \\<le> 1\" \"v c1 \\<le> n\" \"v c2 \\<le> n\"\n          \"\\<forall> k \\<in> set vs. k > 0 \\<longrightarrow> k \\<le> n \\<and> (\\<exists> c. v c = k)\"\n  shows \"dbm_entry_val u (Some c1) (Some c2) (len m (v c1) (v c2) vs)\"\nproof -\n  show ?thesis\n  proof (cases \"\\<forall> k \\<in> set vs. k > 0\")\n    case True\n    with assms have \"\\<forall> k \\<in> set vs. k > 0 \\<and> k \\<le> n \\<and> (\\<exists> c. v c = k)\" by auto\n    with DBM_val_bounded_len_3'_aux[OF assms(1,3,4)] show ?thesis by auto\n  next\n    case False\n    then have \"\\<exists> k \\<in> set vs. k = 0\" by auto\n    then obtain us ws where vs: \"vs = us @ 0 # ws\" by (meson split_list_last) \n    with cnt_at_most_1_D[of 0 \"us\"] assms(2) have\n      \"0 \\<notin> set us\" \"0 \\<notin> set ws\"\n    by auto\n    with vs have vs: \"vs = us @ 0 # ws\" \"\\<forall> k \\<in> set us. k > 0\" \"\\<forall> k \\<in> set ws. k > 0\" by auto\n    with assms(5) have v:\n      \"\\<forall>k\\<in>set us. 0 < k \\<and> k \\<le> n \\<and> (\\<exists>c. v c = k)\" \"\\<forall>k\\<in>set ws. 0 < k \\<and> k \\<le> n \\<and> (\\<exists>c. v c = k)\"\n    by auto\n    with dbm_entry_val_add_4 [OF DBM_val_bounded_len_1'_aux[OF assms(1,3) v(1)] DBM_val_bounded_len_2'_aux[OF assms(1,4) v(2)]]\n    have \"dbm_entry_val u (Some c1) (Some c2) (dbm_add (len m (v c1) 0 us) (len m 0 (v c2) ws))\" by auto\n    moreover from vs have \"len m (v c1) (v c2) vs = dbm_add (len m (v c1) 0 us) (len m 0 (v c2) ws)\"\n    by (simp add: len_comp mult)\n    ultimately show ?thesis by auto\n  qed\nqed\n\nlemma DBM_val_bounded_len'':\n  fixes v\n  defines \"vo \\<equiv> \\<lambda> k. if k = 0 then None else Some (SOME c. v c = k)\"\n  assumes \"DBM_val_bounded v u m n\" \"i \\<noteq> 0 \\<or> j \\<noteq> 0\"\n          \"\\<forall> k \\<in> set (i # j # vs). k > 0 \\<longrightarrow> k \\<le> n \\<and> (\\<exists> c. v c = k)\"\n  shows \"dbm_entry_val u (vo i) (vo j) (len m i j vs)\" using assms\nproof (induction \"length vs\" arbitrary: i vs rule: less_induct)\n  case less\n  show ?case\n  proof (cases \"\\<forall> k \\<in> set vs. k > 0\")\n    case True\n    with less.prems have *: \"\\<forall> k \\<in> set vs. k > 0 \\<and> k \\<le> n \\<and> (\\<exists> c. v c = k)\" by auto\n    show ?thesis\n    proof (cases \"i = 0\")\n      case True\n      then have i: \"vo i = None\" by (simp add: vo_def)\n      show ?thesis\n      proof (cases \"j = 0\")\n        case True with less.prems \\<open>i = 0\\<close> show ?thesis by auto\n      next\n        case False\n        with less.prems obtain c2 where c2: \"j \\<le> n\" \"v c2 = j\" \"vo j = Some c2\"\n        unfolding vo_def by (fastforce intro: someI)\n        with \\<open>i = 0\\<close> i DBM_val_bounded_len_2'_aux[OF less.prems(1) _ *] show ?thesis by auto\n      qed\n    next\n      case False\n      with less.prems obtain c1 where c1: \"i \\<le> n\" \"v c1 = i\" \"vo i = Some c1\"\n      unfolding vo_def by (fastforce intro: someI)\n      show ?thesis\n      proof (cases \"j = 0\")\n        case True\n        with DBM_val_bounded_len_1'_aux[OF less.prems(1) _ *] c1 show ?thesis by (auto simp: vo_def)\n      next\n        case False\n        with less.prems obtain c2 where c2: \"j \\<le> n\" \"v c2 = j\" \"vo j = Some c2\"\n        unfolding vo_def by (fastforce intro: someI)\n        with c1 DBM_val_bounded_len_3'_aux[OF less.prems(1) _ _ *] show ?thesis by auto\n      qed\n    qed\n  next\n    case False\n    then have \"\\<exists> us ws. vs = us @ 0 # ws \\<and> (\\<forall> k \\<in> set us. k > 0)\"\n    proof (induction vs)\n      case Nil then show ?case by auto\n    next\n      case (Cons x vs)\n      show ?case\n      proof (cases \"x = 0\")\n        case True then show ?thesis by fastforce\n      next\n        case False\n        with Cons.prems have \"\\<not> (\\<forall>a\\<in>set vs. 0 < a)\" by auto\n        from Cons.IH[OF this] obtain us ws where \"vs = us @ 0 # ws\" \"\\<forall>a\\<in>set us. 0 < a\" by auto\n        with False have \"x # vs = (x # us) @ 0 # ws\" \"\\<forall>a\\<in>set (x # us). 0 < a\" by auto\n        then show ?thesis by blast\n      qed\n    qed\n    then obtain us ws where vs: \"vs = us @ 0 # ws\" \"\\<forall> k \\<in> set us. k > 0\" by blast\n    then show ?thesis\noops\n\nlemma DBM_val_bounded_len_1: \"DBM_val_bounded v u m n \\<Longrightarrow> v c \\<le> n \\<Longrightarrow> \\<forall> c \\<in> set cs. v c \\<le> n\n      \\<Longrightarrow> dbm_entry_val u (Some c) None (len m (v c) 0 (map v cs))\"\nproof (induction cs arbitrary: c)\n  case Nil thus ?case unfolding DBM_val_bounded_def by auto\nnext\n  case (Cons c' cs)\n  hence \"dbm_entry_val u (Some c') None (len m (v c') 0 (map v cs))\" by auto\n  moreover have \"dbm_entry_val u (Some c) (Some c') (m (v c) (v c'))\" using Cons.prems\n  by (simp add: DBM_val_bounded_def)\n  ultimately have \"dbm_entry_val u (Some c) None (m (v c) (v c') + len m (v c') 0 (map v cs))\"\n  using dbm_entry_val_add_1 unfolding mult by fastforce\n  thus ?case unfolding DBM_val_bounded_def by simp\nqed\n\nlemma DBM_val_bounded_len_3: \"DBM_val_bounded v u m n \\<Longrightarrow> v c \\<le> n \\<Longrightarrow> v d \\<le> n \\<Longrightarrow> \\<forall> c \\<in> set cs. v c \\<le> n\n      \\<Longrightarrow> dbm_entry_val u (Some c) (Some d) (len m (v c) (v d) (map v cs))\"\nproof (induction cs arbitrary: c)\n  case Nil thus ?case unfolding DBM_val_bounded_def by auto\nnext\n  case (Cons c' cs)\n  hence \"dbm_entry_val u (Some c') (Some d) (len m (v c') (v d) (map v cs))\" by auto\n  moreover have \"dbm_entry_val u (Some c) (Some c') (m (v c) (v c'))\" using Cons.prems\n  by (simp add: DBM_val_bounded_def)\n  ultimately have \"dbm_entry_val u (Some c) (Some d) (m (v c) (v c') + len m (v c') (v d) (map v cs))\"\n  using dbm_entry_val_add_3 unfolding mult by fastforce\n  thus ?case unfolding DBM_val_bounded_def by simp\nqed\n\nlemma DBM_val_bounded_len_2: \"DBM_val_bounded v u m n \\<Longrightarrow> v c \\<le> n \\<Longrightarrow> \\<forall> c \\<in> set cs. v c \\<le> n\n      \\<Longrightarrow> dbm_entry_val u None (Some c) (len m 0 (v c) (map v cs))\"\nproof (cases cs, goal_cases)\n  case 1 thus ?thesis unfolding DBM_val_bounded_def by auto\nnext\n  case (2 c' cs)\n  hence \"dbm_entry_val u (Some c') (Some c) (len m (v c') (v c) (map v cs))\"\n  using DBM_val_bounded_len_3 by auto\n  moreover have \"dbm_entry_val u None (Some c') (m 0 (v c'))\"\n  using 2 by (simp add: DBM_val_bounded_def)\n  ultimately have \"dbm_entry_val u None (Some c) (m 0 (v c') + len m (v c') (v c) (map v cs))\"\n  using dbm_entry_val_add_2 unfolding mult by fastforce\n  thus ?case using 2(4) unfolding DBM_val_bounded_def 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/Evaluation/Timed_Automata/DBM.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8615382094310357, "lm_q2_score": 0.8221891370573388, "lm_q1q2_score": 0.708347356954028}}
{"text": "(* Author: Florian Haftmann, TU Muenchen *)\n\nsection \\<open>Common discrete functions\\<close>\n\ntheory Discrete\nimports Main\nbegin\n\nsubsection \\<open>Discrete logarithm\\<close>\n\ncontext\nbegin\n\nqualified fun log :: \"nat \\<Rightarrow> nat\"\n  where [simp del]: \"log n = (if n < 2 then 0 else Suc (log (n div 2)))\"\n\nlemma log_induct [consumes 1, case_names one double]:\n  fixes n :: nat\n  assumes \"n > 0\"\n  assumes one: \"P 1\"\n  assumes double: \"\\<And>n. n \\<ge> 2 \\<Longrightarrow> P (n div 2) \\<Longrightarrow> P n\"\n  shows \"P n\"\nusing \\<open>n > 0\\<close> proof (induct n rule: log.induct)\n  fix n\n  assume \"\\<not> n < 2 \\<Longrightarrow>\n          0 < n div 2 \\<Longrightarrow> P (n div 2)\"\n  then have *: \"n \\<ge> 2 \\<Longrightarrow> P (n div 2)\" by simp\n  assume \"n > 0\"\n  show \"P n\"\n  proof (cases \"n = 1\")\n    case True\n    with one show ?thesis by simp\n  next\n    case False\n    with \\<open>n > 0\\<close> have \"n \\<ge> 2\" by auto\n    with * have \"P (n div 2)\" .\n    with \\<open>n \\<ge> 2\\<close> show ?thesis by (rule double)\n  qed\nqed\n  \nlemma log_zero [simp]: \"log 0 = 0\"\n  by (simp add: log.simps)\n\nlemma log_one [simp]: \"log 1 = 0\"\n  by (simp add: log.simps)\n\nlemma log_Suc_zero [simp]: \"log (Suc 0) = 0\"\n  using log_one by simp\n\nlemma log_rec: \"n \\<ge> 2 \\<Longrightarrow> log n = Suc (log (n div 2))\"\n  by (simp add: log.simps)\n\nlemma log_twice [simp]: \"n \\<noteq> 0 \\<Longrightarrow> log (2 * n) = Suc (log n)\"\n  by (simp add: log_rec)\n\nlemma log_half [simp]: \"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\n  then show ?thesis by (simp add: log_rec)\nqed\n\nlemma log_exp [simp]: \"log (2 ^ n) = n\"\n  by (induct n) simp_all\n\nlemma log_mono: \"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 \\<ge> 2\")\n      case False\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 True then have \"\\<not> m < 2\" by simp\n      with mn2 have \"n \\<ge> 2\" by arith\n      from True 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 \\<open>\\<not> m < 2\\<close> \"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 \\<open>m \\<ge> 2\\<close> \\<open>n \\<ge> 2\\<close> show ?thesis by (simp only: log_rec [of m] log_rec [of n]) simp\n    qed\n  qed\nqed\n\nlemma log_exp2_le:\n  assumes \"n > 0\"\n  shows \"2 ^ log n \\<le> n\"\n  using assms\nproof (induct n rule: log_induct)\n  case one\n  then show ?case by simp\nnext\n  case (double n)\n  with log_mono have \"log n \\<ge> Suc 0\"\n    by (simp add: log.simps)\n  assume \"2 ^ log (n div 2) \\<le> n div 2\"\n  with \\<open>n \\<ge> 2\\<close> have \"2 ^ (log n - Suc 0) \\<le> n div 2\" by simp\n  then have \"2 ^ (log n - Suc 0) * 2 ^ 1 \\<le> n div 2 * 2\" by simp\n  with \\<open>log n \\<ge> Suc 0\\<close> have \"2 ^ log n \\<le> n div 2 * 2\"\n    unfolding power_add [symmetric] by simp\n  also have \"n div 2 * 2 \\<le> n\" by (cases \"even n\") simp_all\n  finally show ?case .\nqed\n\n\nsubsection \\<open>Discrete square root\\<close>\n\nqualified definition sqrt :: \"nat \\<Rightarrow> nat\"\n  where \"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\nlemma sqrt_unique:\n  assumes \"m^2 \\<le> n\" \"n < (Suc m)^2\"\n  shows   \"Discrete.sqrt n = m\"\nproof -\n  have \"m' \\<le> m\" if \"m'^2 \\<le> n\" for m'\n  proof -\n    note that\n    also note assms(2)\n    finally have \"m' < Suc m\" by (rule power_less_imp_less_base) simp_all\n    thus \"m' \\<le> m\" by simp\n  qed\n  with \\<open>m^2 \\<le> n\\<close> sqrt_aux[of n] show ?thesis unfolding Discrete.sqrt_def\n    by (intro antisym Max.boundedI Max.coboundedI) simp_all\nqed\n\n\nlemma sqrt_code[code]: \"sqrt n = Max (Set.filter (\\<lambda>m. m\\<^sup>2 \\<le> n) {0..n})\"\nproof -\n  from power2_nat_le_imp_le [of _ n] have \"{m. m \\<le> n \\<and> m\\<^sup>2 \\<le> n} = {m. m\\<^sup>2 \\<le> n}\" by auto\n  then show ?thesis by (simp add: sqrt_def Set.filter_def)\nqed\n\nlemma sqrt_inverse_power2 [simp]: \"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]: \"sqrt 0 = 0\"\n  using sqrt_inverse_power2 [of 0] by simp\n\nlemma sqrt_one [simp]: \"sqrt 1 = 1\"\n  using sqrt_inverse_power2 [of 1] by simp\n\nlemma mono_sqrt: \"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 \\<open>0 * 0 \\<le> m\\<close> finite_less_ub simp add: power2_eq_square sqrt_def)\nqed\n\nlemma mono_sqrt': \"m \\<le> n \\<Longrightarrow> Discrete.sqrt m \\<le> Discrete.sqrt n\"\n  using mono_sqrt unfolding mono_def by auto\n\nlemma sqrt_greater_zero_iff [simp]: \"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]: \"(sqrt n)\\<^sup>2 \\<le> n\" (* FIXME tune proof *)\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\n          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 \\<open>q * q \\<le> n\\<close>)\n          apply (metis \\<open>q * q \\<le> n\\<close> le_cases mult_le_mono1 mult_le_mono2 order_trans)\n          done\n      qed\n    qed\n  with * show ?thesis by (simp add: sqrt_def power2_eq_square)\nqed\n\nlemma sqrt_le: \"sqrt n \\<le> n\"\n  using sqrt_aux [of n] by (auto simp add: sqrt_def intro: power2_nat_le_imp_le)\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/Discrete.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8615382094310357, "lm_q2_score": 0.8221891218080991, "lm_q1q2_score": 0.7083473438162253}}
{"text": "\ntheory hw10\nimports Main\nbegin\n\ndatatype trie = LeafF | LeafT | Node \"trie * trie\"\n\nfun is_trie :: \"nat \\<Rightarrow> trie \\<Rightarrow> bool\"\n  where\n  \"is_trie 0 (Node(x,y)) \\<longleftrightarrow> False\"\n| \"is_trie 0 _ \\<longleftrightarrow> True\"\n| \"is_trie (Suc n) LeafF \\<longleftrightarrow> True\"\n| \"is_trie (Suc n) LeafT \\<longleftrightarrow> False\"\n| \"is_trie (Suc n) (Node (x,y)) \\<longleftrightarrow> is_trie n x \\<and> is_trie n y\"\n\ntext \\<open>Hint: The following should evaluate to true!\\<close>\nvalue \"is_trie 42 LeafF\"\nvalue \"is_trie 2 (Node (LeafF,Node (LeafT,LeafF)))\"\ntext \\<open>Whereas these should be false\\<close>\nvalue \"is_trie 42 LeafT\" -- \\<open>Wrong key length\\<close>\nvalue \"is_trie 2 (Node (LeafT,Node (LeafT,LeafF)))\" -- \\<open>Wrong key length\\<close>\nvalue \"is_trie 1 (Node (LeafT,Node (LeafF,LeafF)))\" -- \\<open>Superfluous node\\<close>\n\nfun isin :: \"trie \\<Rightarrow> bool list \\<Rightarrow> bool\"\n  where\n  \"isin (Node (x,y)) [] = False\"\n| \"isin LeafT [] = True\"\n| \"isin LeafF _ = False\"\n| \"isin (Node (x,y)) (b#bx) = (if b then isin y bx else isin x bx)\"\n| \"isin LeafT (b#bx) = False\"\n\nvalue \"isin (Node (LeafF,Node (LeafT,LeafF))) [True, False]\"\nvalue \"isin LeafT []\"\nvalue \"isin LeafF []\"\n\nfun ins :: \"bool list \\<Rightarrow> trie \\<Rightarrow> trie\"\n  where\n  \"ins [] _ = LeafT\"\n| \"ins (b#bx) LeafF = (if b then (Node (LeafF, ins bx LeafF)) else (Node ((ins bx LeafF), LeafF)))\"\n| \"ins (b#bx) (Node (x,y)) = (if b then (Node (x, ins bx y)) else (Node ((ins bx x),y)))\"\n| \"ins _ x = x\"\n\nvalue \"ins [] LeafF\"\nvalue \"ins [] LeafT\"\nvalue \"ins [] (Node(LeafF,LeafT))\"\nvalue \"ins [True] (Node(LeafF,LeafT))\"\nvalue \"ins [False] (Node(LeafF,LeafT))\"\nvalue \"ins [False, False] (Node (LeafF,Node (LeafF,LeafT)))\"\nvalue \"ins [False] LeafF\"\nvalue \"ins [True,True,True] (Node (LeafF,Node (LeafT,LeafF)))\"\n\n\nlemma aux1: \"\\<And>b bx x y bs.\n       (\\<And>bs n. is_trie n y \\<Longrightarrow> length bx = n \\<Longrightarrow> isin (ins bx y) bs = (bx = bs \\<or> isin y bs)) \\<Longrightarrow>\n       (\\<And>bs n. False \\<Longrightarrow> is_trie n x \\<Longrightarrow> length bx = n \\<Longrightarrow> isin (ins bx x) bs = (bx = bs \\<or> isin x bs)) \\<Longrightarrow>\n       b \\<Longrightarrow> isin (Node (x, ins bx y)) bs \\<Longrightarrow>\n             \\<not> isin (Node (x, y)) bs \\<Longrightarrow> is_trie (length bx) x \\<Longrightarrow> is_trie (length bx) y \\<Longrightarrow> True # bx = bs\"\n proof -\nfix b :: bool and bx :: \"bool list\" and x :: trie and y :: trie and bsa :: \"bool list\"\nassume a1: \"isin (Node (x, ins bx y)) bsa\"\nassume a2: \"\\<not> isin (Node (x, y)) bsa\"\nassume a3: \"\\<And>bs n. \\<lbrakk>is_trie n y; length bx = n\\<rbrakk> \\<Longrightarrow> isin (ins bx y) bs = (bx = bs \\<or> isin y bs)\"\nassume a4: \"is_trie (length bx) y\"\nhave \"bsa \\<noteq> []\"\nusing a1 by force\nthen show \"True # bx = bsa\"\n  using a4 a3 a2 a1 by (metis (full_types) isin.simps(4) list.exhaust)\nqed\n\n\n\nlemma isin_ins1:\n  assumes \"is_trie n t\" and \"length as = n\"\n  shows \"isin (ins as t) bs = (as = bs \\<or> isin t bs)\"\nproof -\n  show ?thesis using assms\n    apply (induction as t arbitrary: bs n rule: ins.induct)\n       apply (auto split:if_splits)\n    using isin.elims(2) apply blast\n    using is_trie.simps(1) isin.elims(2) apply blast\n           apply (metis (full_types) is_trie.simps(2) is_trie.simps(4) isin.simps(1) isin.simps(3) isin.simps(4) length_0_conv length_Cons list.exhaust)\n    using is_trie.elims(3) apply blast\n         apply (smt Suc_length_conv ins.simps(2) is_trie.simps(2) is_trie.simps(4) isin.simps(1) isin.simps(3) isin.simps(4) length_0_conv length_Cons list.exhaust list.inject neq_Nil_conv)\n    using is_trie.elims(3) apply blast\n    \n    using aux1 apply metis\n      apply (metis isin.elims(2) isin.simps(4) trie.distinct(5))\n     apply (smt isin.elims(2) isin.simps(4) trie.distinct(5))\n    by (metis isin.elims(2) isin.simps(4) trie.distinct(5))\nqed\n\nlemma isin_ins2:\n  assumes \"is_trie n t\" and \"length as = n\"\n  shows \"is_trie n (ins as t)\"\nproof -\n  show ?thesis using assms\n   apply (induction as t arbitrary: n rule: ins.induct)\n       apply (auto split:if_splits)\n    using is_trie.elims(3) apply blast\n    using is_trie.elims(3) apply blast\n    using is_trie.elims(3) apply blast\n    using is_trie.elims(3) by blast\nqed\n\nlemma isin_ins:\n  assumes \"is_trie n t\" and \"length as = n\"\n  shows \"isin (ins as t) bs = (as = bs \\<or> isin t bs)\"\n    and \"is_trie n (ins as t)\"\n  using assms(1) assms(2) isin_ins1 apply auto[1]\n  by (simp add: assms(1) assms(2) isin_ins2)\n\nfun node :: \"trie \\<times> trie \\<Rightarrow> trie\" where\n  \"node (x,y) = (if (x = LeafF \\<and> y = LeafF) then LeafF else (Node(x,y)))\"\n\n\nfun delete2 :: \"bool list \\<Rightarrow> trie \\<Rightarrow> trie\" where\n  \"delete2 [] _ = LeafF\"\n| \"delete2 (b#bx) LeafF = LeafF\"\n| \"delete2 (b#bx) (Node (x,y)) = (if b then (node (x, delete2 bx y)) else (node ((delete2 bx x),y)))\"\n| \"delete2 _ x = x\"\n\nlemma delaux1:\n  assumes \"is_trie n t\" and \"length as = n\"\n  shows \"isin (delete2 as t) bs = (as\\<noteq>bs \\<and> isin t bs)\"\nproof -\n  show ?thesis using assms\n   apply (induction as t arbitrary: bs n rule: delete2.induct)\n       apply (auto split!:if_splits)\n              apply (metis gen_length_code(1) ins.simps(1) is_trie.simps(2) isin.simps(3) isin_ins1 length_code)\n             apply (metis isin.elims(2) isin.simps(4) trie.distinct(5))\n            apply (metis isin.elims(2) isin.simps(4) trie.distinct(5))\n           apply (metis (full_types) isin.simps(1) isin.simps(3) isin.simps(4) list.exhaust)\n          apply (smt isin.elims(2) isin.simps(4) trie.simps(7))\n         apply (smt isin.elims(2) isin.simps(4) trie.simps(7))\n        apply (metis isin.elims(2) isin.simps(4) trie.distinct(5))\n       apply (metis isin.elims(2) isin.simps(4) trie.distinct(5))\n      apply (metis (full_types) isin.simps(1) isin.simps(3) isin.simps(4) list.exhaust)\n     apply (smt isin.elims(2) isin.simps(4) trie.simps(7))\n    by (smt isin.elims(2) isin.simps(4) trie.simps(7))\nqed\n\nlemma delaux2:\n  assumes \"is_trie n t\"\n  shows\"(is_trie n (delete2 as t))\"\nproof -\n show ?thesis using assms\n   apply (induction as t arbitrary: n rule: delete2.induct)\n      apply (auto split!:if_splits)\n   using is_trie.elims(3) apply blast\n   using is_trie.elims(3) apply blast\n       apply (metis is_trie.simps(1) is_trie.simps(6) old.nat.exhaust)\n      apply (metis is_trie.simps(1) is_trie.simps(6) not0_implies_Suc)\n     apply (metis is_trie.elims(2) is_trie.simps(4) trie.simps(7))\n    apply (metis is_trie.simps(1) is_trie.simps(6) old.nat.exhaust)\n   by (metis is_trie.simps(1) is_trie.simps(6) not0_implies_Suc)\nqed\n  \nlemma\n  assumes \"is_trie n t\" and \"length as = n\"\n  shows \"isin (delete2 as t) bs = (as\\<noteq>bs \\<and> isin t bs)\"\n    and \"(is_trie n (delete2 as t))\"\n  using assms(1) assms(2) delaux1 apply blast\n  by (simp add: assms(1) delaux2)\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/10/hw10.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.86153820232079, "lm_q2_score": 0.8221891261650248, "lm_q1q2_score": 0.7083473417239167}}
{"text": "(*\n * Copyright Data61, CSIRO (ABN 41 687 119 230)\n *\n * SPDX-License-Identifier: BSD-2-Clause\n *)\n\nsection \\<open>Arithmetic lemmas\\<close>\n\ntheory More_Arithmetic\n  imports Main \"HOL-Library.Type_Length\" \"HOL-Library.Bit_Operations\"\nbegin\n\ndeclare iszero_0 [intro]\n\ndeclare min.absorb1 [simp] min.absorb2 [simp]\n\nlemma n_less_equal_power_2 [simp]:\n  \"n < 2 ^ n\"\n  by (fact less_exp)\n\nlemma min_pm [simp]: \"min a b + (a - b) = a\"\n  for a b :: nat\n  by arith\n\nlemma min_pm1 [simp]: \"a - b + min a b = a\"\n  for a b :: nat\n  by arith\n\nlemma rev_min_pm [simp]: \"min b a + (a - b) = a\"\n  for a b :: nat\n  by arith\n\nlemma rev_min_pm1 [simp]: \"a - b + min b a = a\"\n  for a b :: nat\n  by arith\n\nlemma min_minus [simp]: \"min m (m - k) = m - k\"\n  for m k :: nat\n  by arith\n\nlemma min_minus' [simp]: \"min (m - k) m = m - k\"\n  for m k :: nat\n  by arith\n\nlemma nat_less_power_trans:\n  fixes n :: nat\n  assumes nv: \"n < 2 ^ (m - k)\"\n  and     kv: \"k \\<le> m\"\n  shows \"2 ^ k * n < 2 ^ m\"\nproof (rule order_less_le_trans)\n  show \"2 ^ k * n < 2 ^ k * 2 ^ (m - k)\"\n    by (rule mult_less_mono2 [OF nv zero_less_power]) simp\n  show \"(2::nat) ^ k * 2 ^ (m - k) \\<le> 2 ^ m\" using nv kv\n    by (subst power_add [symmetric]) simp\nqed\n\nlemma nat_le_power_trans:\n  fixes n :: nat\n  shows \"\\<lbrakk>n \\<le> 2 ^ (m - k); k \\<le> m\\<rbrakk> \\<Longrightarrow> 2 ^ k * n \\<le> 2 ^ m\"\n  by (metis le_add_diff_inverse mult_le_mono2 semiring_normalization_rules(26))\n\nlemma nat_add_offset_less:\n  fixes x :: nat\n  assumes yv: \"y < 2 ^ n\"\n  and     xv: \"x < 2 ^ m\"\n  and     mn: \"sz = m + n\"\n  shows   \"x * 2 ^ n + y < 2 ^ sz\"\nproof (subst mn)\n  from yv obtain qy where \"y + qy = 2 ^ n\" and \"0 < qy\"\n    by (auto dest: less_imp_add_positive)\n\n  have \"x * 2 ^ n + y < x * 2 ^ n + 2 ^ n\" by simp fact+\n  also have \"\\<dots> = (x + 1) * 2 ^ n\" by simp\n  also have \"\\<dots> \\<le> 2 ^ (m + n)\" using xv\n    by (subst power_add) (rule mult_le_mono1, simp)\n  finally show \"x * 2 ^ n + y < 2 ^ (m + n)\" .\nqed\n\nlemma nat_power_less_diff:\n  assumes lt: \"(2::nat) ^ n * q < 2 ^ m\"\n  shows \"q < 2 ^ (m - n)\"\n  using lt\nproof (induct n arbitrary: m)\n  case 0\n  then show ?case by simp\nnext\n  case (Suc n)\n\n  have ih: \"\\<And>m. 2 ^ n * q < 2 ^ m \\<Longrightarrow> q < 2 ^ (m - n)\"\n    and prem: \"2 ^ Suc n * q < 2 ^ m\" by fact+\n\n  show ?case\n  proof (cases m)\n    case 0\n    then show ?thesis using Suc by simp\n  next\n    case (Suc m')\n    then show ?thesis using prem\n      by (simp add: ac_simps ih)\n  qed\nqed\n\nlemma power_2_mult_step_le:\n  \"\\<lbrakk>n' \\<le> n; 2 ^ n' * k' < 2 ^ n * k\\<rbrakk> \\<Longrightarrow> 2 ^ n' * (k' + 1) \\<le> 2 ^ n * (k::nat)\"\n  apply (cases \"n'=n\", simp)\n   apply (metis Suc_leI le_refl mult_Suc_right mult_le_mono semiring_normalization_rules(7))\n  apply (drule (1) le_neq_trans)\n  apply clarsimp\n  apply (subgoal_tac \"\\<exists>m. n = n' + m\")\n   prefer 2\n   apply (simp add: le_Suc_ex)\n  apply (clarsimp simp: power_add)\n  apply (metis Suc_leI mult.assoc mult_Suc_right nat_mult_le_cancel_disj)\n  done\n\nlemma nat_mult_power_less_eq:\n  \"b > 0 \\<Longrightarrow> (a * b ^ n < (b :: nat) ^ m) = (a < b ^ (m - n))\"\n  using mult_less_cancel2[where m = a and k = \"b ^ n\" and n=\"b ^ (m - n)\"]\n        mult_less_cancel2[where m=\"a * b ^ (n - m)\" and k=\"b ^ m\" and n=1]\n  apply (simp only: power_add[symmetric] nat_minus_add_max)\n  apply (simp only: power_add[symmetric] nat_minus_add_max ac_simps)\n  apply (simp add: max_def split: if_split_asm)\n  done\n\nlemma diff_diff_less:\n  \"(i < m - (m - (n :: nat))) = (i < m \\<and> i < n)\"\n  by auto\n\nlemma small_powers_of_2:\n  \\<open>x < 2 ^ (x - 1)\\<close> if \\<open>x \\<ge> 3\\<close> for x :: nat\nproof -\n  define m where \\<open>m = x - 3\\<close>\n  with that have \\<open>x = m + 3\\<close>\n    by simp\n  moreover have \\<open>m + 3 < 4 * 2 ^ m\\<close>\n    by (induction m) simp_all\n  ultimately show ?thesis\n    by simp\nqed\n\nend\n", "meta": {"author": "ethereum", "repo": "yul-isabelle", "sha": "4d760a0dabfeab19efc772330be1059021208ad9", "save_path": "github-repos/isabelle/ethereum-yul-isabelle", "path": "github-repos/isabelle/ethereum-yul-isabelle/yul-isabelle-4d760a0dabfeab19efc772330be1059021208ad9/Word_Lib/More_Arithmetic.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.849971175657575, "lm_q2_score": 0.8333245911726382, "lm_q1q2_score": 0.7083018824633753}}
{"text": "(*  Title:      ZF/Induct/PropLog.thy\n    Author:     Tobias Nipkow & Lawrence C Paulson\n    Copyright   1993  University of Cambridge\n*)\n\nsection \\<open>Meta-theory of propositional logic\\<close>\n\ntheory PropLog imports ZF begin\n\ntext \\<open>\n  Datatype definition of propositional logic formulae and inductive\n  definition of the propositional tautologies.\n\n  Inductive definition of propositional logic.  Soundness and\n  completeness w.r.t.\\ truth-tables.\n\n  Prove: If \\<open>H |= p\\<close> then \\<open>G |= p\\<close> where \\<open>G \\<in>\n  Fin(H)\\<close>\n\\<close>\n\n\nsubsection \\<open>The datatype of propositions\\<close>\n\nconsts\n  propn :: i\n\ndatatype propn =\n    Fls\n  | Var (\"n \\<in> nat\")    (\\<open>#_\\<close> [100] 100)\n  | Imp (\"p \\<in> propn\", \"q \\<in> propn\")    (infixr \\<open>=>\\<close> 90)\n\n\nsubsection \\<open>The proof system\\<close>\n\nconsts thms     :: \"i => i\"\n\nabbreviation\n  thms_syntax :: \"[i,i] => o\"    (infixl \\<open>|-\\<close> 50)\n  where \"H |- p == p \\<in> thms(H)\"\n\ninductive\n  domains \"thms(H)\" \\<subseteq> \"propn\"\n  intros\n    H:  \"[| p \\<in> H;  p \\<in> propn |] ==> H |- p\"\n    K:  \"[| p \\<in> propn;  q \\<in> propn |] ==> H |- p=>q=>p\"\n    S:  \"[| p \\<in> propn;  q \\<in> propn;  r \\<in> propn |]\n         ==> H |- (p=>q=>r) => (p=>q) => p=>r\"\n    DN: \"p \\<in> propn ==> H |- ((p=>Fls) => Fls) => p\"\n    MP: \"[| H |- p=>q;  H |- p;  p \\<in> propn;  q \\<in> propn |] ==> H |- q\"\n  type_intros \"propn.intros\"\n\ndeclare propn.intros [simp]\n\n\nsubsection \\<open>The semantics\\<close>\n\nsubsubsection \\<open>Semantics of propositional logic.\\<close>\n\nconsts\n  is_true_fun :: \"[i,i] => i\"\nprimrec\n  \"is_true_fun(Fls, t) = 0\"\n  \"is_true_fun(Var(v), t) = (if v \\<in> t then 1 else 0)\"\n  \"is_true_fun(p=>q, t) = (if is_true_fun(p,t) = 1 then is_true_fun(q,t) else 1)\"\n\ndefinition\n  is_true :: \"[i,i] => o\"  where\n  \"is_true(p,t) == is_true_fun(p,t) = 1\"\n  \\<comment> \\<open>this definition is required since predicates can't be recursive\\<close>\n\nlemma is_true_Fls [simp]: \"is_true(Fls,t) \\<longleftrightarrow> False\"\n  by (simp add: is_true_def)\n\nlemma is_true_Var [simp]: \"is_true(#v,t) \\<longleftrightarrow> v \\<in> t\"\n  by (simp add: is_true_def)\n\nlemma is_true_Imp [simp]: \"is_true(p=>q,t) \\<longleftrightarrow> (is_true(p,t)\\<longrightarrow>is_true(q,t))\"\n  by (simp add: is_true_def)\n\n\nsubsubsection \\<open>Logical consequence\\<close>\n\ntext \\<open>\n  For every valuation, if all elements of \\<open>H\\<close> are true then so\n  is \\<open>p\\<close>.\n\\<close>\n\ndefinition\n  logcon :: \"[i,i] => o\"    (infixl \\<open>|=\\<close> 50)  where\n  \"H |= p == \\<forall>t. (\\<forall>q \\<in> H. is_true(q,t)) \\<longrightarrow> is_true(p,t)\"\n\n\ntext \\<open>\n  A finite set of hypotheses from \\<open>t\\<close> and the \\<open>Var\\<close>s in\n  \\<open>p\\<close>.\n\\<close>\n\nconsts\n  hyps :: \"[i,i] => i\"\nprimrec\n  \"hyps(Fls, t) = 0\"\n  \"hyps(Var(v), t) = (if v \\<in> t then {#v} else {#v=>Fls})\"\n  \"hyps(p=>q, t) = hyps(p,t) \\<union> hyps(q,t)\"\n\n\n\nsubsection \\<open>Proof theory of propositional logic\\<close>\n\nlemma thms_mono: \"G \\<subseteq> H ==> thms(G) \\<subseteq> thms(H)\"\n  apply (unfold thms.defs)\n  apply (rule lfp_mono)\n    apply (rule thms.bnd_mono)+\n  apply (assumption | rule univ_mono basic_monos)+\n  done\n\nlemmas thms_in_pl = thms.dom_subset [THEN subsetD]\n\ninductive_cases ImpE: \"p=>q \\<in> propn\"\n\nlemma thms_MP: \"[| H |- p=>q;  H |- p |] ==> H |- q\"\n  \\<comment> \\<open>Stronger Modus Ponens rule: no typechecking!\\<close>\n  apply (rule thms.MP)\n     apply (erule asm_rl thms_in_pl thms_in_pl [THEN ImpE])+\n  done\n\nlemma thms_I: \"p \\<in> propn ==> H |- p=>p\"\n  \\<comment> \\<open>Rule is called \\<open>I\\<close> for Identity Combinator, not for Introduction.\\<close>\n  apply (rule thms.S [THEN thms_MP, THEN thms_MP])\n      apply (rule_tac [5] thms.K)\n       apply (rule_tac [4] thms.K)\n         apply simp_all\n  done\n\n\nsubsubsection \\<open>Weakening, left and right\\<close>\n\nlemma weaken_left: \"[| G \\<subseteq> H;  G|-p |] ==> H|-p\"\n  \\<comment> \\<open>Order of premises is convenient with \\<open>THEN\\<close>\\<close>\n  by (erule thms_mono [THEN subsetD])\n\nlemma weaken_left_cons: \"H |- p ==> cons(a,H) |- p\"\n  by (erule subset_consI [THEN weaken_left])\n\nlemmas weaken_left_Un1  = Un_upper1 [THEN weaken_left]\nlemmas weaken_left_Un2  = Un_upper2 [THEN weaken_left]\n\nlemma weaken_right: \"[| H |- q;  p \\<in> propn |] ==> H |- p=>q\"\n  by (simp_all add: thms.K [THEN thms_MP] thms_in_pl)\n\n\nsubsubsection \\<open>The deduction theorem\\<close>\n\ntheorem deduction: \"[| cons(p,H) |- q;  p \\<in> propn |] ==>  H |- p=>q\"\n  apply (erule thms.induct)\n      apply (blast intro: thms_I thms.H [THEN weaken_right])\n     apply (blast intro: thms.K [THEN weaken_right])\n    apply (blast intro: thms.S [THEN weaken_right])\n   apply (blast intro: thms.DN [THEN weaken_right])\n  apply (blast intro: thms.S [THEN thms_MP [THEN thms_MP]])\n  done\n\n\nsubsubsection \\<open>The cut rule\\<close>\n\nlemma cut: \"[| H|-p;  cons(p,H) |- q |] ==>  H |- q\"\n  apply (rule deduction [THEN thms_MP])\n    apply (simp_all add: thms_in_pl)\n  done\n\nlemma thms_FlsE: \"[| H |- Fls; p \\<in> propn |] ==> H |- p\"\n  apply (rule thms.DN [THEN thms_MP])\n   apply (rule_tac [2] weaken_right)\n    apply (simp_all add: propn.intros)\n  done\n\nlemma thms_notE: \"[| H |- p=>Fls;  H |- p;  q \\<in> propn |] ==> H |- q\"\n  by (erule thms_MP [THEN thms_FlsE])\n\n\nsubsubsection \\<open>Soundness of the rules wrt truth-table semantics\\<close>\n\ntheorem soundness: \"H |- p ==> H |= p\"\n  apply (unfold logcon_def)\n  apply (induct set: thms)\n      apply auto\n  done\n\n\nsubsection \\<open>Completeness\\<close>\n\nsubsubsection \\<open>Towards the completeness proof\\<close>\n\nlemma Fls_Imp: \"[| H |- p=>Fls; q \\<in> propn |] ==> H |- p=>q\"\n  apply (frule thms_in_pl)\n  apply (rule deduction)\n   apply (rule weaken_left_cons [THEN thms_notE])\n     apply (blast intro: thms.H elim: ImpE)+\n  done\n\nlemma Imp_Fls: \"[| H |- p;  H |- q=>Fls |] ==> H |- (p=>q)=>Fls\"\n  apply (frule thms_in_pl)\n  apply (frule thms_in_pl [of concl: \"q=>Fls\"])\n  apply (rule deduction)\n   apply (erule weaken_left_cons [THEN thms_MP])\n   apply (rule consI1 [THEN thms.H, THEN thms_MP])\n    apply (blast intro: weaken_left_cons elim: ImpE)+\n  done\n\nlemma hyps_thms_if:\n    \"p \\<in> propn ==> hyps(p,t) |- (if is_true(p,t) then p else p=>Fls)\"\n  \\<comment> \\<open>Typical example of strengthening the induction statement.\\<close>\n  apply simp\n  apply (induct_tac p)\n    apply (simp_all add: thms_I thms.H)\n  apply (safe elim!: Fls_Imp [THEN weaken_left_Un1] Fls_Imp [THEN weaken_left_Un2])\n  apply (blast intro: weaken_left_Un1 weaken_left_Un2 weaken_right Imp_Fls)+\n  done\n\nlemma logcon_thms_p: \"[| p \\<in> propn;  0 |= p |] ==> hyps(p,t) |- p\"\n  \\<comment> \\<open>Key lemma for completeness; yields a set of assumptions satisfying \\<open>p\\<close>\\<close>\n  apply (drule hyps_thms_if)\n  apply (simp add: logcon_def)\n  done\n\ntext \\<open>\n  For proving certain theorems in our new propositional logic.\n\\<close>\n\nlemmas propn_SIs = propn.intros deduction\n  and propn_Is = thms_in_pl thms.H thms.H [THEN thms_MP]\n\ntext \\<open>\n  The excluded middle in the form of an elimination rule.\n\\<close>\n\nlemma thms_excluded_middle:\n    \"[| p \\<in> propn;  q \\<in> propn |] ==> H |- (p=>q) => ((p=>Fls)=>q) => q\"\n  apply (rule deduction [THEN deduction])\n    apply (rule thms.DN [THEN thms_MP])\n     apply (best intro!: propn_SIs intro: propn_Is)+\n  done\n\nlemma thms_excluded_middle_rule:\n  \"[| cons(p,H) |- q;  cons(p=>Fls,H) |- q;  p \\<in> propn |] ==> H |- q\"\n  \\<comment> \\<open>Hard to prove directly because it requires cuts\\<close>\n  apply (rule thms_excluded_middle [THEN thms_MP, THEN thms_MP])\n     apply (blast intro!: propn_SIs intro: propn_Is)+\n  done\n\n\nsubsubsection \\<open>Completeness -- lemmas for reducing the set of assumptions\\<close>\n\ntext \\<open>\n  For the case \\<^prop>\\<open>hyps(p,t)-cons(#v,Y) |- p\\<close> we also have \\<^prop>\\<open>hyps(p,t)-{#v} \\<subseteq> hyps(p, t-{v})\\<close>.\n\\<close>\n\nlemma hyps_Diff:\n    \"p \\<in> propn ==> hyps(p, t-{v}) \\<subseteq> cons(#v=>Fls, hyps(p,t)-{#v})\"\n  by (induct set: propn) auto\n\ntext \\<open>\n  For the case \\<^prop>\\<open>hyps(p,t)-cons(#v => Fls,Y) |- p\\<close> we also have\n  \\<^prop>\\<open>hyps(p,t)-{#v=>Fls} \\<subseteq> hyps(p, cons(v,t))\\<close>.\n\\<close>\n\nlemma hyps_cons:\n    \"p \\<in> propn ==> hyps(p, cons(v,t)) \\<subseteq> cons(#v, hyps(p,t)-{#v=>Fls})\"\n  by (induct set: propn) auto\n\ntext \\<open>Two lemmas for use with \\<open>weaken_left\\<close>\\<close>\n\nlemma cons_Diff_same: \"B-C \\<subseteq> cons(a, B-cons(a,C))\"\n  by blast\n\nlemma cons_Diff_subset2: \"cons(a, B-{c}) - D \\<subseteq> cons(a, B-cons(c,D))\"\n  by blast\n\ntext \\<open>\n  The set \\<^term>\\<open>hyps(p,t)\\<close> is finite, and elements have the form\n  \\<^term>\\<open>#v\\<close> or \\<^term>\\<open>#v=>Fls\\<close>; could probably prove the stronger\n  \\<^prop>\\<open>hyps(p,t) \\<in> Fin(hyps(p,0) \\<union> hyps(p,nat))\\<close>.\n\\<close>\n\nlemma hyps_finite: \"p \\<in> propn ==> hyps(p,t) \\<in> Fin(\\<Union>v \\<in> nat. {#v, #v=>Fls})\"\n  by (induct set: propn) auto\n\nlemmas Diff_weaken_left = Diff_mono [OF _ subset_refl, THEN weaken_left]\n\ntext \\<open>\n  Induction on the finite set of assumptions \\<^term>\\<open>hyps(p,t0)\\<close>.  We\n  may repeatedly subtract assumptions until none are left!\n\\<close>\n\nlemma completeness_0_lemma [rule_format]:\n    \"[| p \\<in> propn;  0 |= p |] ==> \\<forall>t. hyps(p,t) - hyps(p,t0) |- p\"\n  apply (frule hyps_finite)\n  apply (erule Fin_induct)\n   apply (simp add: logcon_thms_p Diff_0)\n  txt \\<open>inductive step\\<close>\n  apply safe\n   txt \\<open>Case \\<^prop>\\<open>hyps(p,t)-cons(#v,Y) |- p\\<close>\\<close>\n   apply (rule thms_excluded_middle_rule)\n     apply (erule_tac [3] propn.intros)\n    apply (blast intro: cons_Diff_same [THEN weaken_left])\n   apply (blast intro: cons_Diff_subset2 [THEN weaken_left]\n     hyps_Diff [THEN Diff_weaken_left])\n  txt \\<open>Case \\<^prop>\\<open>hyps(p,t)-cons(#v => Fls,Y) |- p\\<close>\\<close>\n  apply (rule thms_excluded_middle_rule)\n    apply (erule_tac [3] propn.intros)\n   apply (blast intro: cons_Diff_subset2 [THEN weaken_left]\n     hyps_cons [THEN Diff_weaken_left])\n  apply (blast intro: cons_Diff_same [THEN weaken_left])\n  done\n\n\nsubsubsection \\<open>Completeness theorem\\<close>\n\nlemma completeness_0: \"[| p \\<in> propn;  0 |= p |] ==> 0 |- p\"\n  \\<comment> \\<open>The base case for completeness\\<close>\n  apply (rule Diff_cancel [THEN subst])\n  apply (blast intro: completeness_0_lemma)\n  done\n\nlemma logcon_Imp: \"[| cons(p,H) |= q |] ==> H |= p=>q\"\n  \\<comment> \\<open>A semantic analogue of the Deduction Theorem\\<close>\n  by (simp add: logcon_def)\n\nlemma completeness:\n     \"H \\<in> Fin(propn) ==> p \\<in> propn \\<Longrightarrow> H |= p \\<Longrightarrow> H |- p\"\n  apply (induct arbitrary: p set: Fin)\n   apply (safe intro!: completeness_0)\n  apply (rule weaken_left_cons [THEN thms_MP])\n   apply (blast intro!: logcon_Imp propn.intros)\n  apply (blast intro: propn_Is)\n  done\n\ntheorem thms_iff: \"H \\<in> Fin(propn) ==> H |- p \\<longleftrightarrow> H |= p \\<and> p \\<in> propn\"\n  by (blast intro: soundness completeness thms_in_pl)\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/Induct/PropLog.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8333245870332531, "lm_q2_score": 0.8499711737573762, "lm_q1q2_score": 0.7083018773615349}}
{"text": "(*  Author:  S\u00e9bastien Gou\u00ebzel   sebastien.gouezel@univ-rennes1.fr\n    License: BSD\n*)\n\ntheory Functional_Spaces\nimports \"HOL-Analysis.Analysis\" Ergodic_Theory.SG_Library_Complement\nbegin\n\n\n\nsection \\<open>Functions as a real vector space\\<close>\n\ntext \\<open>Many functional spaces are spaces of functions. To be able to use the following\nframework, spaces of functions thus need to be endowed with a vector space\nstructure, coming from pointwise addition and multiplication.\n\nSome instantiations for \\verb+fun+ are already given in \\verb+Lattices.thy+, we add several.\\<close>\n\ninstantiation \"fun\" :: (type, plus) plus\nbegin\n\ndefinition plus_fun_def: \"f + g = (\\<lambda>x. f x + g x)\"\n\nlemma plus_apply [simp, code]: \"(f + g) x = f x + g x\"\n  by (simp add: plus_fun_def)\n\ninstance ..\nend\n\ntext \\<open>\\verb+minus_fun+ is already defined, in \\verb+Lattices.thy+, but under the strange name\n\\verb+fun_Compl_def+. We restate the definition so that \\verb+unfolding minus_fun_def+ works.\nSame thing for \\verb+minus_fun_def+. A better solution would be to have a coherent naming scheme\nin \\verb+Lattices.thy+.\\<close>\n\nlemmas uminus_fun_def = fun_Compl_def\nlemmas minus_fun_def = fun_diff_def\n\ninstantiation \"fun\" :: (type, zero) zero\nbegin\n\ndefinition zero_fun_def: \"0 = (\\<lambda>x. 0)\"\n\nlemma zero_fun [simp, code]:\n  \"0 x = 0\"\nby (simp add: zero_fun_def)\n\ninstance..\nend\n\ninstance \"fun\"::(type, semigroup_add) semigroup_add\nby (standard, rule ext, auto simp add: add.assoc)\n\ninstance \"fun\"::(type, ab_semigroup_add) ab_semigroup_add\nby (standard, rule ext, auto simp add: add_ac)\n\ninstance \"fun\"::(type, monoid_add) monoid_add\nby (standard, rule ext, auto)\n\ninstance \"fun\"::(type, comm_monoid_add) comm_monoid_add\nby (standard, rule ext, auto)\n\nlemma fun_sum_apply:\n  fixes u::\"'i \\<Rightarrow> 'a \\<Rightarrow> ('b::comm_monoid_add)\"\n  shows \"(sum u I) x = sum (\\<lambda>i. u i x) I\"\nby (induction I rule: infinite_finite_induct, auto)\n\ninstance \"fun\"::(type, cancel_semigroup_add) cancel_semigroup_add\nproof\n  fix a b c::\"'a \\<Rightarrow> 'b\" assume \"a + b = a + c\"\n  then have \"a x + b x = a x + c x\" for x by (metis plus_fun_def)\n  then show \"b = c\" by (intro ext, auto)\nnext\n  fix b a c::\"'a \\<Rightarrow> 'b\" assume \"b + a = c + a\"\n  then have \"b x + a x = c x + a x\" for x by (metis plus_fun_def)\n  then show \"b = c\" by (intro ext, auto)\nqed\n\ninstance \"fun\"::(type, cancel_ab_semigroup_add) cancel_ab_semigroup_add\nby (standard, rule ext, auto, rule ext, auto simp add: diff_diff_add)\n\ninstance \"fun\"::(type, cancel_comm_monoid_add) cancel_comm_monoid_add\nby standard\n\ninstance \"fun\"::(type, group_add) group_add\nby (standard, auto)\n\ninstance \"fun\"::(type, ab_group_add) ab_group_add\nby (standard, auto)\n\ninstantiation \"fun\" :: (type, real_vector) real_vector\nbegin\n\ndefinition scaleR_fun::\"real \\<Rightarrow> ('a \\<Rightarrow> 'b) \\<Rightarrow> 'a \\<Rightarrow> 'b\"\n  where \"scaleR_fun = (\\<lambda>c f. (\\<lambda>x. c *\\<^sub>R f x))\"\n\nlemma scaleR_apply [simp, code]: \"(c *\\<^sub>R f) x = c *\\<^sub>R (f x)\"\n  by (simp add: scaleR_fun_def)\n\ninstance by (standard, auto simp add: scaleR_add_right scaleR_add_left)\nend\n\nlemmas divideR_apply = scaleR_apply\n\nlemma [measurable]:\n  \"0 \\<in> borel_measurable M\"\nunfolding zero_fun_def by auto\n\nlemma borel_measurable_const_scaleR' [measurable (raw)]:\n  \"(f::('a \\<Rightarrow> 'b::real_normed_vector)) \\<in> borel_measurable M \\<Longrightarrow> c *\\<^sub>R f \\<in> borel_measurable M\"\nunfolding scaleR_fun_def using borel_measurable_add by auto\n\nlemma borel_measurable_add'[measurable (raw)]:\n  fixes f g :: \"'a \\<Rightarrow> 'b::{second_countable_topology, real_normed_vector}\"\n  assumes f: \"f \\<in> borel_measurable M\"\n  assumes g: \"g \\<in> borel_measurable M\"\n  shows \"f + g \\<in> borel_measurable M\"\nunfolding plus_fun_def using assms by auto\n\nlemma borel_measurable_uminus'[measurable (raw)]:\n  fixes f g :: \"'a \\<Rightarrow> 'b::{second_countable_topology, real_normed_vector}\"\n  assumes f: \"f \\<in> borel_measurable M\"\n  shows \"-f \\<in> borel_measurable M\"\nunfolding fun_Compl_def using assms by auto\n\nlemma borel_measurable_diff'[measurable (raw)]:\n  fixes f g :: \"'a \\<Rightarrow> 'b::{second_countable_topology, real_normed_vector}\"\n  assumes f: \"f \\<in> borel_measurable M\"\n  assumes g: \"g \\<in> borel_measurable M\"\n  shows \"f - g \\<in> borel_measurable M\"\nunfolding fun_diff_def using assms by auto\n\nlemma borel_measurable_sum'[measurable (raw)]:\n  fixes f::\"'i \\<Rightarrow> 'a \\<Rightarrow> 'b::{second_countable_topology, real_normed_vector}\"\n  assumes \"\\<And>i. i \\<in> I \\<Longrightarrow> f i \\<in> borel_measurable M\"\n  shows \"(\\<Sum>i\\<in>I. f i) \\<in> borel_measurable M\"\nusing borel_measurable_sum[of I f, OF assms] unfolding fun_sum_apply[symmetric] by simp\n\nlemma zero_applied_to [simp]:\n  \"(0::('a \\<Rightarrow> ('b::real_vector))) x = 0\"\nunfolding zero_fun_def by simp\n\n\n\nsection \\<open>Quasinorms on function spaces\\<close>\n\ntext \\<open>A central feature of modern analysis is the use of various functional\nspaces, and of results of functional analysis on them. Think for instance of\n$L^p$ spaces, of Sobolev or Besov spaces, or variations around them. Here are\nseveral relevant facts about this point of view:\n\\begin{itemize}\n\\item These spaces typically depend on one or several parameters.\nThis makes it difficult to play with type classes in a system without dependent\ntypes.\n\\item The $L^p$ spaces are not spaces of functions (their elements are\nequivalence classes of functions, where two functions are identified if they\ncoincide almost everywhere). However, in usual analysis proofs, one takes a\ndefinite representative and works with it, never going to the equivalence class\npoint of view (which only becomes relevant when one wants to use the fact that\none has a Banach space at our disposal, to apply functional analytic tools).\n\\item It is important to describe how the spaces are related to each other,\nwith respect to inclusions or compact inclusions. For instance, one of the most\nimportant theorems in analysis is Sobolev embedding theorem, describing when\none Sobolev space is included in another one. One also needs to be able to\ntake intersections or sums of Banach spaces, for instance to develop\ninterpolation theory.\n\\item Some other spaces play an important role in analysis, for instance the\nweak $L^1$ space. This space only has a quasi-norm (i.e., its norm satisfies the\ntriangular inequality up to a fixed multiplicative constant). A general enough setting\nshould also encompass this kind of space. (One could argue that one should also consider more\ngeneral topologies such as Frechet spaces, to deal with Gevrey or analytic functions.\nThis is true, but considering quasi-norms already gives a wealth of applications).\n\\end{itemize}\n\nGiven these points, it seems that the most effective way of formalizing this\nkind of question in Isabelle/HOL is to think of such a functional space not as\nan abstract space or type, but as a subset of the space of all functions or of\nall distributions. Functions that do not belong to the functional space\nunder consideration will then have infinite norm. Then inclusions, intersections,\nand so on, become trivial to implement. Since the same object contains both the information\nabout the norm and the space where the norm is finite, it conforms to the customary habit in\nmathematics of identifying the two of them, talking for instance about the $L^p$ space and the\n$L^p$ norm.\n\nAll in all, this approach seems quite promising for ``real life analysis''.\n\\<close>\n\nsubsection \\<open>Definition of quasinorms\\<close>\n\ntypedef (overloaded) ('a::real_vector) quasinorm = \"{(C::real, N::('a \\<Rightarrow> ennreal)). (C \\<ge> 1)\n      \\<and> (\\<forall> x c. N (c *\\<^sub>R x) = ennreal \\<bar>c\\<bar> * N(x)) \\<and> (\\<forall> x y. N(x+y) \\<le> C * N x + C * N y)}\"\nmorphisms Rep_quasinorm quasinorm_of\nproof\n  show \"(1,(\\<lambda>x. 0)) \\<in> {(C::real, N::('a \\<Rightarrow> ennreal)). (C \\<ge> 1)\n      \\<and> (\\<forall> x c. N (c *\\<^sub>R x) = ennreal \\<bar>c\\<bar> * N x) \\<and> (\\<forall> x y. N (x+y) \\<le> C * N x + C * N y)}\"\n    by auto\nqed\n\ndefinition eNorm::\"'a quasinorm \\<Rightarrow> ('a::real_vector) \\<Rightarrow> ennreal\"\n  where \"eNorm N x = (snd (Rep_quasinorm N)) x\"\n\ndefinition defect::\"('a::real_vector) quasinorm \\<Rightarrow> real\"\n  where \"defect N = fst (Rep_quasinorm N)\"\n\nlemma eNorm_triangular_ineq:\n  \"eNorm N (x + y) \\<le> defect N * eNorm N x + defect N * eNorm N y\"\nunfolding eNorm_def defect_def using Rep_quasinorm[of N] by auto\n\nlemma defect_ge_1:\n  \"defect N \\<ge> 1\"\nunfolding defect_def using Rep_quasinorm[of N] by auto\n\nlemma eNorm_cmult:\n  \"eNorm N (c *\\<^sub>R x) = ennreal \\<bar>c\\<bar> * eNorm N x\"\nunfolding eNorm_def using Rep_quasinorm[of N] by auto\n\nlemma eNorm_zero [simp]:\n  \"eNorm N 0 = 0\"\nby (metis eNorm_cmult abs_zero ennreal_0 mult_zero_left real_vector.scale_zero_left)\n\nlemma eNorm_uminus [simp]:\n  \"eNorm N (-x) = eNorm N x\"\nusing eNorm_cmult[of N \"-1\" x] by auto\n\nlemma eNorm_sum:\n  \"eNorm N (\\<Sum>i\\<in>{..<n}. u i) \\<le> (\\<Sum>i\\<in>{..<n}. (defect N)^(Suc i) * eNorm N (u i))\"\nproof (cases \"n=0\")\n  case True\n  then show ?thesis by simp\nnext\n  case False\n  then obtain m where \"n = Suc m\" using not0_implies_Suc by blast\n  have \"\\<And>v. eNorm N (\\<Sum>i\\<in>{..n}. v i) \\<le> (\\<Sum>i\\<in>{..<n}. (defect N)^(Suc i) * eNorm N (v i)) + (defect N)^n * eNorm N (v n)\" for n\n  proof (induction n)\n    case 0\n    then show ?case by simp\n  next\n    case (Suc n)\n    have *: \"(defect N)^(Suc n) = (defect N)^n * ennreal(defect N)\"\n      by (metis defect_ge_1 ennreal_le_iff ennreal_neg ennreal_power less_le not_less not_one_le_zero semiring_normalization_rules(28))\n    fix v::\"nat \\<Rightarrow> 'a\"\n    define w where \"w = (\\<lambda>i. if i = n then v n + v (Suc n) else v i)\"\n    have \"(\\<Sum>i\\<in>{..Suc n}. v i) = (\\<Sum>i\\<in>{..<n}. v i) + v n + v (Suc n)\"\n      using lessThan_Suc_atMost sum.lessThan_Suc by auto\n    also have \"... = (\\<Sum>i\\<in>{..<n}. w i) + w n\" unfolding w_def by auto\n    finally have \"(\\<Sum>i\\<in>{..Suc n}. v i) = (\\<Sum>i\\<in>{..n}. w i)\"\n      by (metis lessThan_Suc_atMost sum.lessThan_Suc)\n    then have \"eNorm N (\\<Sum>i\\<in>{..Suc n}. v i) = eNorm N (\\<Sum>i\\<in>{..n}. w i)\" by simp\n    also have \"... \\<le> (\\<Sum>i\\<in>{..<n}. (defect N)^(Suc i) * eNorm N (w i)) + (defect N)^n * eNorm N (w n)\"\n      using Suc.IH by auto\n    also have \"... = (\\<Sum>i\\<in>{..<n}. (defect N)^(Suc i) * eNorm N (v i)) + (defect N)^n * eNorm N (v n + v (Suc n))\"\n      unfolding w_def by auto\n    also have \"... \\<le> (\\<Sum>i\\<in>{..<n}. (defect N)^(Suc i) * eNorm N (v i)) +\n          (defect N)^n * (defect N * eNorm N (v n) + defect N * eNorm N (v (Suc n)))\"\n      by (rule add_mono, simp, rule mult_left_mono, auto simp add: eNorm_triangular_ineq)\n    also have \"... = (\\<Sum>i\\<in>{..<n}. (defect N)^(Suc i) * eNorm N (v i))\n        + (defect N)^(Suc n) * eNorm N (v n) + (defect N)^(Suc n) * eNorm N (v (Suc n))\"\n      unfolding * by (simp add: distrib_left semiring_normalization_rules(18))\n    also have \"... = (\\<Sum>i\\<in>{..<Suc n}. (defect N)^(Suc i) * eNorm N (v i)) + (defect N)^(Suc n) * eNorm N (v (Suc n))\"\n      by auto\n    finally show \"eNorm N (\\<Sum>i\\<in>{..Suc n}. v i)\n            \\<le> (\\<Sum>i<Suc n. ennreal (defect N ^ Suc i) * eNorm N (v i)) + ennreal (defect N ^ Suc n) * eNorm N (v (Suc n)) \"\n      by simp\n  qed\n  then have \"eNorm N (\\<Sum>i\\<in>{..<Suc m}. u i)\n      \\<le> (\\<Sum>i\\<in>{..<m}. (defect N)^(Suc i) * eNorm N (u i)) + (defect N)^m * eNorm N (u m)\"\n    using lessThan_Suc_atMost by auto\n  also have \"... \\<le> (\\<Sum>i\\<in>{..<m}. (defect N)^(Suc i) * eNorm N (u i)) + (defect N)^(Suc m) * eNorm N (u m)\"\n    apply (rule add_mono, auto intro!: mult_right_mono ennreal_leI)\n    using defect_ge_1 by (metis atMost_iff le_less lessThan_Suc_atMost lessThan_iff power_Suc power_increasing)\n  also have \"... = (\\<Sum>i\\<in>{..<Suc m}. (defect N)^(Suc i) * eNorm N (u i))\"\n    by auto\n  finally show \"eNorm N (\\<Sum>i\\<in>{..<n}. u i) \\<le> (\\<Sum>i<n. ennreal (defect N ^ Suc i) * eNorm N (u i))\"\n    unfolding \\<open>n = Suc m\\<close> by auto\nqed\n\n\ntext \\<open>Quasinorms are often defined by taking a meaningful formula on a vector subspace,\nand then extending by infinity elsewhere. Let us show that this results in a quasinorm on the\nwhole space.\\<close>\n\ndefinition quasinorm_on::\"('a set) \\<Rightarrow> real \\<Rightarrow> (('a::real_vector) \\<Rightarrow> ennreal) \\<Rightarrow> bool\"\n  where \"quasinorm_on F C N = (\n    (\\<forall>x y. (x \\<in> F \\<and> y \\<in> F) \\<longrightarrow> (x + y \\<in> F) \\<and> N (x+y) \\<le> C * N x + C * N y)\n    \\<and> (\\<forall>c x. x \\<in> F \\<longrightarrow> c *\\<^sub>R x \\<in> F \\<and> N(c *\\<^sub>R x) = \\<bar>c\\<bar> * N x)\n    \\<and> C \\<ge> 1 \\<and> 0 \\<in> F)\"\n\nlemma quasinorm_of:\n  fixes N::\"('a::real_vector) \\<Rightarrow> ennreal\" and C::real\n  assumes \"quasinorm_on UNIV C N\"\n  shows \"eNorm (quasinorm_of (C,N)) x = N x\"\n        \"defect (quasinorm_of (C,N)) = C\"\nusing assms unfolding eNorm_def defect_def quasinorm_on_def by (auto simp add: quasinorm_of_inverse)\n\nlemma quasinorm_onI:\n  fixes N::\"('a::real_vector) \\<Rightarrow> ennreal\" and C::real and F::\"'a set\"\n  assumes \"\\<And>x y. x \\<in> F \\<Longrightarrow> y \\<in> F \\<Longrightarrow> x + y \\<in> F\"\n          \"\\<And>x y. x \\<in> F \\<Longrightarrow> y \\<in> F \\<Longrightarrow> N (x + y) \\<le> C * N x + C * N y\"\n          \"\\<And>c x. c \\<noteq> 0 \\<Longrightarrow> x \\<in> F \\<Longrightarrow> c *\\<^sub>R x \\<in> F\"\n          \"\\<And>c x. c \\<noteq> 0 \\<Longrightarrow> x \\<in> F \\<Longrightarrow> N (c *\\<^sub>R x) \\<le> ennreal \\<bar>c\\<bar> * N x\"\n          \"0 \\<in> F\" \"N(0) = 0\" \"C \\<ge> 1\"\n  shows \"quasinorm_on F C N\"\nproof -\n  have \"N(c *\\<^sub>R x) = ennreal \\<bar>c\\<bar> * N x\" if \"x \\<in> F\" for c x\n  proof (cases \"c = 0\")\n    case True\n    then show ?thesis using \\<open>N 0 = 0\\<close> by auto\n  next\n    case False\n    have \"N((1/c) *\\<^sub>R (c *\\<^sub>R x)) \\<le> ennreal (abs (1/c)) * N (c *\\<^sub>R x)\"\n      apply (rule \\<open>\\<And>c x. c \\<noteq> 0 \\<Longrightarrow> x \\<in> F \\<Longrightarrow> N(c *\\<^sub>R x) \\<le> ennreal \\<bar>c\\<bar> * N x\\<close>) using False assms that by auto\n    then have \"N x \\<le> ennreal (abs (1/c)) * N (c *\\<^sub>R x)\" using False by auto\n    then have \"ennreal \\<bar>c\\<bar> * N x \\<le> ennreal \\<bar>c\\<bar> * ennreal (abs (1/c)) * N (c *\\<^sub>R x)\"\n      by (simp add: mult.assoc mult_left_mono)\n    also have \"... = N (c *\\<^sub>R x)\" using ennreal_mult' abs_mult False\n      by (metis abs_ge_zero abs_one comm_monoid_mult_class.mult_1 ennreal_1 eq_divide_eq_1 field_class.field_divide_inverse)\n    finally show ?thesis\n      using \\<open>\\<And>c x. c \\<noteq> 0 \\<Longrightarrow> x \\<in> F \\<Longrightarrow> N(c *\\<^sub>R x) \\<le> ennreal \\<bar>c\\<bar> * N x\\<close>[OF False \\<open>x \\<in> F\\<close>] by auto\n  qed\n  then show ?thesis\n    unfolding quasinorm_on_def using assms by (auto, metis real_vector.scale_zero_left)\nqed\n\nlemma extend_quasinorm:\n  assumes \"quasinorm_on F C N\"\n  shows \"quasinorm_on UNIV C (\\<lambda>x. if x \\<in> F then N x else \\<infinity>)\"\nproof -\n  have *: \"(if x + y \\<in> F then N (x + y) else \\<infinity>)\n    \\<le> ennreal C * (if x \\<in> F then N x else \\<infinity>) + ennreal C * (if y \\<in> F then N y else \\<infinity>)\" for x y\n  proof (cases \"x \\<in> F \\<and> y \\<in> F\")\n    case True\n    then show ?thesis using assms unfolding quasinorm_on_def by auto\n  next\n    case False\n    moreover have \"C \\<ge> 1\" using assms unfolding quasinorm_on_def by auto\n    ultimately have *: \"ennreal C * (if x \\<in> F then N x else \\<infinity>) + ennreal C * (if y \\<in> F then N y else \\<infinity>) = \\<infinity>\"\n      using ennreal_mult_eq_top_iff by auto\n    show ?thesis by (simp add: *)\n  qed\n  show ?thesis\n    apply (rule quasinorm_onI)\n    using assms * unfolding quasinorm_on_def apply (auto simp add: ennreal_top_mult mult.commute)\n    by (metis abs_zero ennreal_0 mult_zero_right real_vector.scale_zero_right)\nqed\n\n\nsubsection \\<open>The space and the zero space of a quasinorm\\<close>\n\ntext \\<open>The space of a quasinorm is the vector subspace where it is meaningful, i.e., finite.\\<close>\n\ndefinition space\\<^sub>N::\"('a::real_vector) quasinorm \\<Rightarrow> 'a set\"\n  where \"space\\<^sub>N N = {f. eNorm N f < \\<infinity>}\"\n\nlemma spaceN_iff:\n  \"x \\<in> space\\<^sub>N N \\<longleftrightarrow> eNorm N x < \\<infinity>\"\nunfolding space\\<^sub>N_def by simp\n\nlemma spaceN_cmult [simp]:\n  assumes \"x \\<in> space\\<^sub>N N\"\n  shows \"c *\\<^sub>R x \\<in> space\\<^sub>N N\"\nusing assms unfolding spaceN_iff using eNorm_cmult[of N c x] by (simp add: ennreal_mult_less_top)\n\nlemma spaceN_add [simp]:\n  assumes \"x \\<in> space\\<^sub>N N\" \"y \\<in> space\\<^sub>N N\"\n  shows \"x + y \\<in> space\\<^sub>N N\"\nproof -\n  have \"eNorm N x < \\<infinity>\" \"eNorm N y < \\<infinity>\" using assms unfolding space\\<^sub>N_def by auto\n  then have \"defect N * eNorm N x + defect N * eNorm N y < \\<infinity>\"\n    by (simp add: ennreal_mult_less_top)\n  then show ?thesis\n    unfolding space\\<^sub>N_def using eNorm_triangular_ineq[of N x y] le_less_trans by blast\nqed\n\nlemma spaceN_diff [simp]:\n  assumes \"x \\<in> space\\<^sub>N N\" \"y \\<in> space\\<^sub>N N\"\n  shows \"x - y \\<in> space\\<^sub>N N\"\nusing spaceN_add[OF assms(1) spaceN_cmult[OF assms(2), of \"-1\"]] by auto\n\nlemma spaceN_contains_zero [simp]:\n  \"0 \\<in> space\\<^sub>N N\"\nunfolding space\\<^sub>N_def by auto\n\nlemma spaceN_sum [simp]:\n  assumes \"\\<And>i. i \\<in> I \\<Longrightarrow> x i \\<in> space\\<^sub>N N\"\n  shows \"(\\<Sum>i\\<in>I. x i) \\<in> space\\<^sub>N N\"\nusing assms by (induction I rule: infinite_finite_induct, auto)\n\n\ntext \\<open>The zero space of a quasinorm is the vector subspace of vectors with zero norm. If one wants\nto get a true metric space, one should quotient the space by the zero space.\\<close>\n\ndefinition zero_space\\<^sub>N::\"('a::real_vector) quasinorm \\<Rightarrow> 'a set\"\n  where \"zero_space\\<^sub>N N = {f. eNorm N f = 0}\"\n\nlemma zero_spaceN_iff:\n  \"x \\<in> zero_space\\<^sub>N N \\<longleftrightarrow> eNorm N x = 0\"\nunfolding zero_space\\<^sub>N_def by simp\n\nlemma zero_spaceN_cmult:\n  assumes \"x \\<in> zero_space\\<^sub>N N\"\n  shows \"c *\\<^sub>R x \\<in> zero_space\\<^sub>N N\"\nusing assms unfolding zero_spaceN_iff using eNorm_cmult[of N c x] by simp\n\nlemma zero_spaceN_add:\n  assumes \"x \\<in> zero_space\\<^sub>N N\" \"y \\<in> zero_space\\<^sub>N N\"\n  shows \"x + y \\<in> zero_space\\<^sub>N N\"\nproof -\n  have \"eNorm N x = 0\" \"eNorm N y = 0\" using assms unfolding zero_space\\<^sub>N_def by auto\n  then have \"defect N * eNorm N x + defect N * eNorm N y = 0\" by auto\n  then show ?thesis\n    unfolding zero_spaceN_iff using eNorm_triangular_ineq[of N x y] by auto\nqed\n\nlemma zero_spaceN_diff:\n  assumes \"x \\<in> zero_space\\<^sub>N N\" \"y \\<in> zero_space\\<^sub>N N\"\n  shows \"x - y \\<in> zero_space\\<^sub>N N\"\nusing zero_spaceN_add[OF assms(1) zero_spaceN_cmult[OF assms(2), of \"-1\"]] by auto\n\nlemma zero_spaceN_subset_spaceN:\n  \"zero_space\\<^sub>N N \\<subseteq> space\\<^sub>N N\"\nby (simp add: spaceN_iff zero_spaceN_iff subset_eq)\n\ntext \\<open>On the space, the norms are finite. Hence, it is much more convenient to work there with\na real valued version of the norm. We use Norm with a capital N to distinguish it from norms\nin a (type class) banach space.\\<close>\n\ndefinition Norm::\"'a quasinorm \\<Rightarrow> ('a::real_vector) \\<Rightarrow> real\"\n  where \"Norm N x = enn2real (eNorm N x)\"\n\nlemma Norm_nonneg [simp]:\n  \"Norm N x \\<ge> 0\"\nunfolding Norm_def by auto\n\nlemma Norm_zero [simp]:\n  \"Norm N 0 = 0\"\nunfolding Norm_def by auto\n\nlemma Norm_uminus [simp]:\n  \"Norm N (-x) = Norm N x\"\nunfolding Norm_def by auto\n\nlemma eNorm_Norm:\n  assumes \"x \\<in> space\\<^sub>N N\"\n  shows \"eNorm N x = ennreal (Norm N x)\"\n  using assms unfolding Norm_def by (simp add: spaceN_iff)\n\nlemma eNorm_Norm':\n  assumes \"x \\<notin> space\\<^sub>N N\"\n  shows \"Norm N x = 0\"\nusing assms unfolding Norm_def apply (auto simp add: spaceN_iff)\nusing top.not_eq_extremum by fastforce\n\nlemma Norm_cmult:\n  \"Norm N (c *\\<^sub>R x) = abs c * Norm N x\"\nunfolding Norm_def unfolding eNorm_cmult by (simp add: enn2real_mult)\n\nlemma Norm_triangular_ineq:\n  assumes \"x \\<in> space\\<^sub>N N\"\n  shows \"Norm N (x + y) \\<le> defect N * Norm N x + defect N * Norm N y\"\nproof (cases \"y \\<in> space\\<^sub>N N\")\n  case True\n  have *: \"defect N * Norm N x + defect N * Norm N y \\<ge> 1 * 0 + 1 * 0\"\n    apply (rule add_mono) by (rule mult_mono'[OF defect_ge_1 Norm_nonneg], simp, simp)+\n  have \"ennreal (Norm N (x + y)) = eNorm N (x+y)\"\n    using eNorm_Norm[OF spaceN_add[OF assms True]] by auto\n  also have \"... \\<le> defect N * eNorm N x + defect N * eNorm N y\"\n    using eNorm_triangular_ineq[of N x y] by auto\n  also have \"... = defect N * ennreal(Norm N x) + defect N * ennreal(Norm N y)\"\n    using eNorm_Norm assms True by metis\n  also have \"... = ennreal(defect N * Norm N x + defect N * Norm N y)\"\n    using ennreal_mult ennreal_plus Norm_nonneg defect_ge_1\n    by (metis (no_types, hide_lams) ennreal_eq_0_iff less_le ennreal_ge_1 ennreal_mult' le_less_linear not_one_le_zero semiring_normalization_rules(34))\n  finally show ?thesis\n    apply (subst ennreal_le_iff[symmetric]) using * by auto\nnext\n  case False\n  have \"x + y \\<notin> space\\<^sub>N N\"\n  proof (rule ccontr)\n    assume \"\\<not> (x + y \\<notin> space\\<^sub>N N)\"\n    then have \"x + y \\<in> space\\<^sub>N N\" by simp\n    have \"y \\<in> space\\<^sub>N N\" using spaceN_diff[OF \\<open>x + y \\<in> space\\<^sub>N N\\<close> assms] by auto\n    then show False using False by simp\n  qed\n  then have \"Norm N (x+y) = 0\" unfolding Norm_def using spaceN_iff top.not_eq_extremum by force\n  moreover have \"defect N * Norm N x + defect N * Norm N y \\<ge> 1 * 0 + 1 * 0\"\n    apply (rule add_mono) by (rule mult_mono'[OF defect_ge_1 Norm_nonneg], simp, simp)+\n  ultimately show ?thesis by simp\nqed\n\nlemma Norm_triangular_ineq_diff:\n  assumes \"x \\<in> space\\<^sub>N N\"\n  shows \"Norm N (x - y) \\<le> defect N * Norm N x + defect N * Norm N y\"\nusing Norm_triangular_ineq[OF assms, of \"-y\"] by auto\n\nlemma zero_spaceN_iff':\n  \"x \\<in> zero_space\\<^sub>N N \\<longleftrightarrow> (x \\<in> space\\<^sub>N N \\<and> Norm N x = 0)\"\nusing eNorm_Norm unfolding space\\<^sub>N_def zero_space\\<^sub>N_def by (auto simp add: Norm_def, fastforce)\n\nlemma Norm_sum:\n  assumes \"\\<And>i. i < n \\<Longrightarrow> u i \\<in> space\\<^sub>N N\"\n  shows \"Norm N (\\<Sum>i\\<in>{..<n}. u i) \\<le> (\\<Sum>i\\<in>{..<n}. (defect N)^(Suc i) * Norm N (u i))\"\nproof -\n  have *: \"0 \\<le> defect N * defect N ^ i * Norm N (u i)\" for i\n    by (meson Norm_nonneg defect_ge_1 dual_order.trans linear mult_nonneg_nonneg not_one_le_zero zero_le_power)\n\n  have \"ennreal (Norm N (\\<Sum>i\\<in>{..<n}. u i)) = eNorm N (\\<Sum>i\\<in>{..<n}. u i)\"\n    apply (rule eNorm_Norm[symmetric], rule spaceN_sum) using assms by auto\n  also have \"... \\<le> (\\<Sum>i\\<in>{..<n}. (defect N)^(Suc i) * eNorm N (u i))\"\n    using eNorm_sum by simp\n  also have \"... = (\\<Sum>i\\<in>{..<n}. (defect N)^(Suc i) * ennreal (Norm N (u i)))\"\n    using eNorm_Norm[OF assms] by auto\n  also have \"... = (\\<Sum>i\\<in>{..<n}. ennreal((defect N)^(Suc i) * Norm N (u i)))\"\n    by (subst ennreal_mult'', auto)\n  also have \"... = ennreal (\\<Sum>i\\<in>{..<n}. (defect N)^(Suc i) * Norm N (u i))\"\n    by (auto intro!: sum_ennreal simp add: *)\n  finally have **: \"ennreal (Norm N (\\<Sum>i\\<in>{..<n}. u i)) \\<le> ennreal (\\<Sum>i\\<in>{..<n}. (defect N)^(Suc i) * Norm N (u i))\"\n    by simp\n  show ?thesis\n    apply (subst ennreal_le_iff[symmetric], rule sum_nonneg) using * ** by auto\nqed\n\nsubsection \\<open>An example: the ambient norm in a normed vector space\\<close>\n\ndefinition N_of_norm::\"'a::real_normed_vector quasinorm\"\n  where \"N_of_norm = quasinorm_of (1, \\<lambda>f. norm f)\"\n\nlemma N_of_norm:\n  \"eNorm N_of_norm f = ennreal (norm f)\"\n  \"Norm N_of_norm f = norm f\"\n  \"defect (N_of_norm) = 1\"\nproof -\n  have *: \"quasinorm_on UNIV 1 (\\<lambda>f. norm f)\"\n    by (rule quasinorm_onI, auto simp add: ennreal_mult', metis ennreal_leI ennreal_plus norm_imp_pos_and_ge norm_triangle_ineq)\n  show \"eNorm N_of_norm f = ennreal (norm f)\"\n       \"defect (N_of_norm) = 1\"\n    unfolding N_of_norm_def using quasinorm_of[OF *] by auto\n  then show \"Norm N_of_norm f = norm f\" unfolding Norm_def by auto\nqed\n\nlemma N_of_norm_space [simp]:\n  \"space\\<^sub>N N_of_norm = UNIV\"\nunfolding space\\<^sub>N_def apply auto unfolding N_of_norm(1) by auto\n\nlemma N_of_norm_zero_space [simp]:\n  \"zero_space\\<^sub>N N_of_norm = {0}\"\nunfolding zero_space\\<^sub>N_def apply auto unfolding N_of_norm(1) by auto\n\n\nsubsection \\<open>An example: the space of bounded continuous functions from a topological space to a normed\nreal vector space\\<close>\n\ntext \\<open>The Banach space of bounded continuous functions is defined in\n\\verb+Bounded_Continuous_Function.thy+, as a type \\verb+bcontfun+. We import very quickly the\nresults proved in this file to the current framework.\\<close>\n\ndefinition bcontfun\\<^sub>N::\"('a::topological_space \\<Rightarrow> 'b::real_normed_vector) quasinorm\"\n  where \"bcontfun\\<^sub>N = quasinorm_of (1, \\<lambda>f. if f \\<in> bcontfun then norm(Bcontfun f) else (\\<infinity>::ennreal))\"\n\nlemma bcontfun\\<^sub>N:\n  fixes f::\"('a::topological_space \\<Rightarrow> 'b::real_normed_vector)\"\n  shows \"eNorm bcontfun\\<^sub>N f = (if f \\<in> bcontfun then norm(Bcontfun f) else (\\<infinity>::ennreal))\"\n        \"Norm bcontfun\\<^sub>N f = (if f \\<in> bcontfun then norm(Bcontfun f) else 0)\"\n        \"defect (bcontfun\\<^sub>N::(('a \\<Rightarrow> 'b) quasinorm)) = 1\"\nproof -\n  have *: \"quasinorm_on bcontfun 1 (\\<lambda>(f::('a \\<Rightarrow> 'b)). norm(Bcontfun f))\"\n  proof (rule quasinorm_onI, auto)\n    fix f g::\"'a \\<Rightarrow> 'b\" assume H: \"f \\<in> bcontfun\" \"g \\<in> bcontfun\"\n    then show \"f + g \\<in> bcontfun\" unfolding plus_fun_def by (simp add: plus_cont)\n    have *: \"Bcontfun(f + g) = Bcontfun f + Bcontfun g\"\n      using H\n      by (auto simp: eq_onp_def plus_fun_def bcontfun_def intro!: plus_bcontfun.abs_eq[symmetric])\n    show \"ennreal (norm (Bcontfun (f + g))) \\<le> ennreal (norm (Bcontfun f)) + ennreal (norm (Bcontfun g))\"\n      unfolding * using ennreal_leI[OF norm_triangle_ineq] by auto\n  next\n    fix c::real and f::\"'a \\<Rightarrow> 'b\" assume H: \"f \\<in> bcontfun\"\n    then show \"c *\\<^sub>R f \\<in> bcontfun\" unfolding scaleR_fun_def by (simp add: scaleR_cont)\n    have *: \"Bcontfun(c *\\<^sub>R f) = c *\\<^sub>R Bcontfun f\"\n      using H\n      by (auto simp: eq_onp_def scaleR_fun_def bcontfun_def intro!: scaleR_bcontfun.abs_eq[symmetric])\n    show \"ennreal (norm (Bcontfun (c *\\<^sub>R f))) \\<le> ennreal \\<bar>c\\<bar> * ennreal (norm (Bcontfun f))\"\n      unfolding * by (simp add: ennreal_mult'')\n  next\n    show \"(0::'a\\<Rightarrow>'b) \\<in> bcontfun\" \"Bcontfun 0 = 0\"\n      unfolding zero_fun_def zero_bcontfun_def by (auto simp add: const_bcontfun)\n  qed\n  have **: \"quasinorm_on UNIV 1 (\\<lambda>(f::'a\\<Rightarrow>'b). if f \\<in> bcontfun then norm(Bcontfun f) else (\\<infinity>::ennreal))\"\n    by (rule extend_quasinorm[OF *])\n  show \"eNorm bcontfun\\<^sub>N f = (if f \\<in> bcontfun then norm(Bcontfun f) else (\\<infinity>::ennreal))\"\n       \"defect (bcontfun\\<^sub>N::('a \\<Rightarrow> 'b) quasinorm) = 1\"\n    using quasinorm_of[OF **] unfolding bcontfun\\<^sub>N_def by auto\n  then show \"Norm bcontfun\\<^sub>N f = (if f \\<in> bcontfun then norm(Bcontfun f) else 0)\"\n    unfolding Norm_def by auto\nqed\n\nlemma bcontfun\\<^sub>N_space:\n  \"space\\<^sub>N bcontfun\\<^sub>N = bcontfun\"\nusing bcontfun\\<^sub>N(1) by (metis (no_types, lifting) Collect_cong bcontfun_def enn2real_top ennreal_0\n  ennreal_enn2real ennreal_less_top ennreal_zero_neq_top infinity_ennreal_def mem_Collect_eq space\\<^sub>N_def)\n\nlemma bcontfun\\<^sub>N_zero_space:\n  \"zero_space\\<^sub>N bcontfun\\<^sub>N = {0}\"\n  apply (auto simp add: zero_spaceN_iff)\n  by (metis Bcontfun_inject bcontfun\\<^sub>N(1) eNorm_zero ennreal_eq_zero_iff ennreal_zero_neq_top infinity_ennreal_def norm_eq_zero norm_imp_pos_and_ge)\n\nlemma bcontfun\\<^sub>ND:\n  assumes \"f \\<in> space\\<^sub>N bcontfun\\<^sub>N\"\n  shows \"continuous_on UNIV f\"\n        \"\\<And>x. norm(f x) \\<le> Norm bcontfun\\<^sub>N f\"\nproof-\n  have \"f \\<in> bcontfun\" using assms unfolding bcontfun\\<^sub>N_space by simp\n  then show \"continuous_on UNIV f\" unfolding bcontfun_def by auto\n  show \"\\<And>x. norm(f x) \\<le> Norm bcontfun\\<^sub>N f\"\n    using norm_bounded bcontfun\\<^sub>N(2) \\<open>f \\<in> bcontfun\\<close> by (metis Bcontfun_inverse)\nqed\n\nlemma bcontfun\\<^sub>NI:\n  assumes \"continuous_on UNIV f\"\n          \"\\<And>x. norm(f x) \\<le> C\"\n  shows \"f \\<in> space\\<^sub>N bcontfun\\<^sub>N\"\n        \"Norm bcontfun\\<^sub>N f \\<le> C\"\nproof -\n  have \"f \\<in> bcontfun\" using assms bcontfun_normI by blast\n  then show \"f \\<in> space\\<^sub>N bcontfun\\<^sub>N\" unfolding bcontfun\\<^sub>N_space by simp\n  show \"Norm bcontfun\\<^sub>N f \\<le> C\" unfolding bcontfun\\<^sub>N(2) using \\<open>f \\<in> bcontfun\\<close> apply auto\n    using assms(2) by (metis apply_bcontfun_cases apply_bcontfun_inverse norm_bound)\nqed\n\n\nsubsection \\<open>Continuous inclusions between functional spaces\\<close>\n\ntext \\<open>Continuous inclusions between functional spaces are now defined\\<close>\n\ninstantiation quasinorm:: (real_vector) preorder\nbegin\n\ndefinition less_eq_quasinorm::\"'a quasinorm \\<Rightarrow> 'a quasinorm \\<Rightarrow> bool\"\n  where \"less_eq_quasinorm N1 N2 = (\\<exists>C\\<ge>(0::real). \\<forall>f. eNorm N2 f \\<le> C * eNorm N1 f)\"\n\ndefinition less_quasinorm::\"'a quasinorm \\<Rightarrow> 'a quasinorm \\<Rightarrow> bool\"\n  where \"less_quasinorm N1 N2 = (less_eq N1 N2 \\<and> (\\<not> less_eq N2 N1))\"\n\ninstance proof -\n  have E: \"N \\<le> N\" for N::\"'a quasinorm\"\n    unfolding less_eq_quasinorm_def by (rule exI[of _ 1], auto)\n  have T: \"N1 \\<le> N3\" if \"N1 \\<le> N2\" \"N2 \\<le> N3\" for N1 N2 N3::\"'a quasinorm\"\n  proof -\n    obtain C C' where *: \"\\<And>f. eNorm N2 f \\<le> ennreal C * eNorm N1 f\"\n                         \"\\<And>f. eNorm N3 f \\<le> ennreal C' * eNorm N2 f\"\n                         \"C \\<ge> 0\" \"C' \\<ge> 0\"\n      using \\<open>N1 \\<le> N2\\<close> \\<open>N2 \\<le> N3\\<close> unfolding less_eq_quasinorm_def by metis\n    {\n      fix f\n      have \"eNorm N3 f \\<le> ennreal C' * ennreal C * eNorm N1 f\"\n        by (metis *(1)[of f] *(2)[of f] mult.commute mult.left_commute mult_left_mono order_trans zero_le)\n      also have \"... = ennreal(C' * C) * eNorm N1 f\"\n        using \\<open>C \\<ge> 0\\<close> \\<open>C' \\<ge> 0\\<close> ennreal_mult by auto\n      finally have \"eNorm N3 f \\<le> ennreal(C' * C) * eNorm N1 f\" by simp\n    }\n    then show ?thesis\n      unfolding less_eq_quasinorm_def using \\<open>C \\<ge> 0\\<close> \\<open>C' \\<ge> 0\\<close> zero_le_mult_iff by auto\n  qed\n\n  show \"OFCLASS('a quasinorm, preorder_class)\"\n    apply standard\n    unfolding less_quasinorm_def apply simp\n    using E apply fast\n    using T apply fast\n    done\nqed\nend\n\nabbreviation quasinorm_subset :: \"('a::real_vector) quasinorm \\<Rightarrow> 'a quasinorm \\<Rightarrow> bool\"\n  where \"quasinorm_subset \\<equiv> less\"\n\nabbreviation quasinorm_subset_eq :: \"('a::real_vector) quasinorm \\<Rightarrow> 'a quasinorm \\<Rightarrow> bool\"\n  where \"quasinorm_subset_eq \\<equiv> less_eq\"\n\nnotation\n  quasinorm_subset (\"'(\\<subset>\\<^sub>N')\") and\n  quasinorm_subset (\"(_/ \\<subset>\\<^sub>N _)\" [51, 51] 50) and\n  quasinorm_subset_eq (\"'(\\<subseteq>\\<^sub>N')\") and\n  quasinorm_subset_eq (\"(_/ \\<subseteq>\\<^sub>N _)\" [51, 51] 50)\n\n\nlemma quasinorm_subsetD:\n  assumes \"N1 \\<subseteq>\\<^sub>N N2\"\n  shows \"\\<exists>C\\<ge>(0::real). \\<forall>f. eNorm N2 f \\<le> C * eNorm N1 f\"\nusing assms unfolding less_eq_quasinorm_def by auto\n\nlemma quasinorm_subsetI:\n  assumes \"\\<And>f. f \\<in> space\\<^sub>N N1 \\<Longrightarrow> eNorm N2 f \\<le> ennreal C * eNorm N1 f\"\n  shows \"N1 \\<subseteq>\\<^sub>N N2\"\nproof -\n  have \"eNorm N2 f \\<le> ennreal (max C 1) * eNorm N1 f\" for f\n  proof (cases \"f \\<in> space\\<^sub>N N1\")\n    case True\n    then show ?thesis using assms[OF \\<open>f \\<in> space\\<^sub>N N1\\<close>]\n      by (metis (no_types, hide_lams) dual_order.trans ennreal_leI max.cobounded2 max.commute\n      mult.commute ordered_comm_semiring_class.comm_mult_left_mono zero_le)\n  next\n    case False\n    then show ?thesis using spaceN_iff\n      by (metis ennreal_ge_1 ennreal_mult_less_top infinity_ennreal_def max.cobounded1\n      max.commute not_le not_one_le_zero top.not_eq_extremum)\n  qed\n  then show ?thesis unfolding less_eq_quasinorm_def\n    by (metis ennreal_max_0' max.cobounded2)\nqed\n\nlemma quasinorm_subsetI':\n  assumes \"\\<And>f. f \\<in> space\\<^sub>N N1 \\<Longrightarrow> f \\<in> space\\<^sub>N N2\"\n          \"\\<And>f. f \\<in> space\\<^sub>N N1 \\<Longrightarrow> Norm N2 f \\<le> C * Norm N1 f\"\n  shows \"N1 \\<subseteq>\\<^sub>N N2\"\nproof (rule quasinorm_subsetI)\n  fix f assume \"f \\<in> space\\<^sub>N N1\"\n  then have \"f \\<in> space\\<^sub>N N2\" using assms(1) by simp\n  then have \"eNorm N2 f = ennreal(Norm N2 f)\" using eNorm_Norm by auto\n  also have \"... \\<le> ennreal(C * Norm N1 f)\"\n    using assms(2)[OF \\<open>f \\<in> space\\<^sub>N N1\\<close>] ennreal_leI by blast\n  also have \"... = ennreal C * ennreal(Norm N1 f)\"\n    using ennreal_mult'' by auto\n  also have \"... = ennreal C * eNorm N1 f\"\n    using eNorm_Norm[OF \\<open>f \\<in> space\\<^sub>N N1\\<close>] by auto\n  finally show \"eNorm N2 f \\<le> ennreal C * eNorm N1 f\"\n    by simp\nqed\n\nlemma quasinorm_subset_space:\n  assumes \"N1 \\<subseteq>\\<^sub>N N2\"\n  shows \"space\\<^sub>N N1 \\<subseteq> space\\<^sub>N N2\"\nusing assms unfolding space\\<^sub>N_def less_eq_quasinorm_def\nby (auto, metis ennreal_mult_eq_top_iff ennreal_neq_top less_le top.extremum_strict top.not_eq_extremum)\n\nlemma quasinorm_subset_Norm_eNorm:\n  assumes \"f \\<in> space\\<^sub>N N1 \\<Longrightarrow> Norm N2 f \\<le> C * Norm N1 f\"\n          \"N1 \\<subseteq>\\<^sub>N N2\"\n          \"C > 0\"\n  shows \"eNorm N2 f \\<le> ennreal C * eNorm N1 f\"\nproof (cases \"f \\<in> space\\<^sub>N N1\")\n  case True\n  then have \"f \\<in> space\\<^sub>N N2\" using quasinorm_subset_space[OF \\<open>N1 \\<subseteq>\\<^sub>N N2\\<close>] by auto\n  then show ?thesis\n    using eNorm_Norm[OF True] eNorm_Norm assms(1)[OF True] by (metis Norm_nonneg ennreal_leI ennreal_mult'')\nnext\n  case False\n  then show ?thesis using \\<open>C > 0\\<close>\n    by (metis ennreal_eq_zero_iff ennreal_mult_eq_top_iff infinity_ennreal_def less_imp_le neq_top_trans not_le spaceN_iff)\nqed\n\nlemma quasinorm_subset_zero_space:\n  assumes \"N1 \\<subseteq>\\<^sub>N N2\"\n  shows \"zero_space\\<^sub>N N1 \\<subseteq> zero_space\\<^sub>N N2\"\nusing assms unfolding zero_space\\<^sub>N_def less_eq_quasinorm_def\nby (auto, metis le_zero_eq mult_zero_right)\n\ntext \\<open>We would like to define the equivalence relation associated to the above order, i.e., the\nequivalence between norms. This is not equality, so we do not have a true order, but nevertheless\nthis is handy, and not standard in a preorder in Isabelle. The file Library/Preorder.thy defines\nsuch an equivalence relation, but including it breaks some proofs so we go the naive way.\\<close>\n\ndefinition quasinorm_equivalent::\"('a::real_vector) quasinorm \\<Rightarrow> 'a quasinorm \\<Rightarrow> bool\" (infix \"=\\<^sub>N\" 60)\n  where \"quasinorm_equivalent N1 N2 = ((N1 \\<subseteq>\\<^sub>N N2) \\<and> (N2 \\<subseteq>\\<^sub>N N1))\"\n\nlemma quasinorm_equivalent_sym [sym]:\n  assumes \"N1 =\\<^sub>N N2\"\n  shows \"N2 =\\<^sub>N N1\"\nusing assms unfolding quasinorm_equivalent_def by auto\n\nlemma quasinorm_equivalent_trans [trans]:\n  assumes \"N1 =\\<^sub>N N2\" \"N2 =\\<^sub>N N3\"\n  shows \"N1 =\\<^sub>N N3\"\nusing assms order_trans unfolding quasinorm_equivalent_def by blast\n\nsubsection \\<open>The intersection and the sum of two functional spaces\\<close>\n\ntext \\<open>In this paragraph, we define the intersection and the sum of two functional spaces.\nIn terms of the order introduced above, this corresponds to the minimum and the maximum.\nMore important, these are the first two examples of interpolation spaces between two\nfunctional spaces, and they are central as all the other ones are built using them.\\<close>\n\ndefinition quasinorm_intersection::\"('a::real_vector) quasinorm \\<Rightarrow> 'a quasinorm \\<Rightarrow> 'a quasinorm\" (infix \"\\<inter>\\<^sub>N\" 70)\n  where \"quasinorm_intersection N1 N2 = quasinorm_of (max (defect N1) (defect N2), \\<lambda>f. eNorm N1 f + eNorm N2 f)\"\n\nlemma quasinorm_intersection:\n  \"eNorm (N1 \\<inter>\\<^sub>N N2) f = eNorm N1 f + eNorm N2 f\"\n  \"defect (N1 \\<inter>\\<^sub>N N2) = max (defect N1) (defect N2)\"\nproof -\n  have T: \"eNorm N1 (x + y) + eNorm N2 (x + y) \\<le>\n    ennreal (max (defect N1) (defect N2)) * (eNorm N1 x + eNorm N2 x) + ennreal (max (defect N1) (defect N2)) * (eNorm N1 y + eNorm N2 y)\" for x y\n  proof -\n    have \"eNorm N1 (x + y) \\<le> ennreal (max (defect N1) (defect N2)) * eNorm N1 x + ennreal (max (defect N1) (defect N2)) * eNorm N1 y\"\n      using eNorm_triangular_ineq[of N1 x y] by (metis (no_types) max_def distrib_left ennreal_leI mult_right_mono order_trans zero_le)\n    moreover have \"eNorm N2 (x + y) \\<le> ennreal (max (defect N1) (defect N2)) * eNorm N2 x + ennreal (max (defect N1) (defect N2)) * eNorm N2 y\"\n      using eNorm_triangular_ineq[of N2 x y] by (metis (no_types) max_def max.commute distrib_left ennreal_leI mult_right_mono order_trans zero_le)\n    ultimately have \"eNorm N1 (x + y) + eNorm N2 (x + y) \\<le> ennreal (max (defect N1) (defect N2)) * (eNorm N1 x + eNorm N1 y + (eNorm N2 x + eNorm N2 y))\"\n      by (simp add: add_mono_thms_linordered_semiring(1) distrib_left)\n    then show ?thesis\n      by (simp add: ab_semigroup_add_class.add_ac(1) add.left_commute distrib_left)\n  qed\n\n  have H: \"eNorm N1 (c *\\<^sub>R x) + eNorm N2 (c *\\<^sub>R x) \\<le> ennreal \\<bar>c\\<bar> * (eNorm N1 x + eNorm N2 x)\" for c x\n    by (simp add: eNorm_cmult[of N1 c x] eNorm_cmult[of N2 c x] distrib_left)\n  have *: \"quasinorm_on UNIV (max (defect N1) (defect N2)) (\\<lambda>f. eNorm N1 f + eNorm N2 f)\"\n    apply (rule quasinorm_onI) using T H defect_ge_1[of N1] defect_ge_1[of N2] by auto\n  show \"defect (N1 \\<inter>\\<^sub>N N2) = max (defect N1) (defect N2)\"\n       \"eNorm (N1 \\<inter>\\<^sub>N N2) f = eNorm N1 f + eNorm N2 f\"\n    unfolding quasinorm_intersection_def using quasinorm_of[OF *] by auto\nqed\n\nlemma quasinorm_intersection_commute:\n  \"N1 \\<inter>\\<^sub>N N2 = N2 \\<inter>\\<^sub>N N1\"\nunfolding quasinorm_intersection_def max.commute[of \"defect N1\"] add.commute[of \"eNorm N1 _\"] by simp\n\nlemma quasinorm_intersection_space:\n  \"space\\<^sub>N (N1 \\<inter>\\<^sub>N N2) = space\\<^sub>N N1 \\<inter> space\\<^sub>N N2\"\napply auto unfolding quasinorm_intersection(1) spaceN_iff by auto\n\nlemma quasinorm_intersection_zero_space:\n  \"zero_space\\<^sub>N (N1 \\<inter>\\<^sub>N N2) = zero_space\\<^sub>N N1 \\<inter> zero_space\\<^sub>N N2\"\napply auto unfolding quasinorm_intersection(1) zero_spaceN_iff by (auto simp add: add_eq_0_iff_both_eq_0)\n\nlemma quasinorm_intersection_subset:\n  \"N1 \\<inter>\\<^sub>N N2 \\<subseteq>\\<^sub>N N1\" \"N1 \\<inter>\\<^sub>N N2 \\<subseteq>\\<^sub>N N2\"\nby (rule quasinorm_subsetI[of _ _ 1], auto simp add: quasinorm_intersection(1))+\n\nlemma quasinorm_intersection_minimum:\n  assumes \"N \\<subseteq>\\<^sub>N N1\" \"N \\<subseteq>\\<^sub>N N2\"\n  shows \"N \\<subseteq>\\<^sub>N N1 \\<inter>\\<^sub>N N2\"\nproof -\n  obtain C1 C2::real where *: \"\\<And>f. eNorm N1 f \\<le> C1 * eNorm N f\"\n                              \"\\<And>f. eNorm N2 f \\<le> C2 * eNorm N f\"\n                              \"C1 \\<ge> 0\" \"C2 \\<ge> 0\"\n    using quasinorm_subsetD[OF assms(1)] quasinorm_subsetD[OF assms(2)] by blast\n  have **: \"eNorm (N1 \\<inter>\\<^sub>N N2) f \\<le> (C1 + C2) * eNorm N f\" for f\n    unfolding quasinorm_intersection(1) using add_mono[OF *(1) *(2)] by (simp add: distrib_right *)\n  show ?thesis\n    apply (rule quasinorm_subsetI) using ** by auto\nqed\n\nlemma quasinorm_intersection_assoc:\n  \"(N1 \\<inter>\\<^sub>N N2) \\<inter>\\<^sub>N N3 =\\<^sub>N N1 \\<inter>\\<^sub>N (N2 \\<inter>\\<^sub>N N3)\"\nunfolding quasinorm_equivalent_def by (meson order_trans quasinorm_intersection_minimum quasinorm_intersection_subset)\n\n\n\ndefinition quasinorm_sum::\"('a::real_vector) quasinorm \\<Rightarrow> 'a quasinorm \\<Rightarrow> 'a quasinorm\" (infix \"+\\<^sub>N\" 70)\n  where \"quasinorm_sum N1 N2 = quasinorm_of (max (defect N1) (defect N2), \\<lambda>f. Inf {eNorm N1 f1 + eNorm N2 f2| f1 f2. f = f1 + f2})\"\n\nlemma quasinorm_sum:\n  \"eNorm (N1 +\\<^sub>N N2) f = Inf {eNorm N1 f1 + eNorm N2 f2| f1 f2. f = f1 + f2}\"\n  \"defect (N1 +\\<^sub>N N2) = max (defect N1) (defect N2)\"\nproof -\n  define N where \"N = (\\<lambda>f. Inf {eNorm N1 f1 + eNorm N2 f2| f1 f2. f = f1 + f2})\"\n  have T: \"N (f+g) \\<le>\n    ennreal (max (defect N1) (defect N2)) * N f + ennreal (max (defect N1) (defect N2)) * N g\" for f g\n  proof -\n    have \"\\<exists>u. (\\<forall>n. u n \\<in> {eNorm N1 f1 + eNorm N2 f2| f1 f2. f = f1 + f2}) \\<and> u \\<longlonglongrightarrow> Inf {eNorm N1 f1 + eNorm N2 f2| f1 f2. f = f1 + f2}\"\n      by (rule Inf_as_limit, auto, rule exI[of _ \"f\"], rule exI[of _ 0], auto)\n    then obtain uf where uf: \"\\<And>n. uf n \\<in> {eNorm N1 f1 + eNorm N2 f2| f1 f2. f = f1 + f2}\"\n                             \"uf \\<longlonglongrightarrow> Inf {eNorm N1 f1 + eNorm N2 f2| f1 f2. f = f1 + f2}\"\n      by blast\n    have \"\\<exists>f1 f2. \\<forall>n. uf n = eNorm N1 (f1 n) + eNorm N2 (f2 n) \\<and> f = f1 n + f2 n\"\n      apply (rule SMT.choices(1)) using uf(1) by blast\n    then obtain f1 f2 where F: \"\\<And>n. uf n = eNorm N1 (f1 n) + eNorm N2 (f2 n)\" \"\\<And>n. f = f1 n + f2 n\"\n      by blast\n\n    have \"\\<exists>u. (\\<forall>n. u n \\<in> {eNorm N1 g1 + eNorm N2 g2| g1 g2. g = g1 + g2}) \\<and> u \\<longlonglongrightarrow> Inf {eNorm N1 g1 + eNorm N2 g2| g1 g2. g = g1 + g2}\"\n      by (rule Inf_as_limit, auto, rule exI[of _ \"g\"], rule exI[of _ 0], auto)\n    then obtain ug where ug: \"\\<And>n. ug n \\<in> {eNorm N1 g1 + eNorm N2 g2| g1 g2. g = g1 + g2}\"\n                             \"ug \\<longlonglongrightarrow> Inf {eNorm N1 g1 + eNorm N2 g2| g1 g2. g = g1 + g2}\"\n      by blast\n    have \"\\<exists>g1 g2. \\<forall>n. ug n = eNorm N1 (g1 n) + eNorm N2 (g2 n) \\<and> g = g1 n + g2 n\"\n      apply (rule SMT.choices(1)) using ug(1) by blast\n    then obtain g1 g2 where G: \"\\<And>n. ug n = eNorm N1 (g1 n) + eNorm N2 (g2 n)\" \"\\<And>n. g = g1 n + g2 n\"\n      by blast\n\n    define h1 where \"h1 = (\\<lambda>n. f1 n + g1 n)\"\n    define h2 where \"h2 = (\\<lambda>n. f2 n + g2 n)\"\n    have *: \"f + g = h1 n + h2 n\" for n\n      unfolding h1_def h2_def using F(2) G(2) by (auto simp add: algebra_simps)\n    have \"N (f+g) \\<le> ennreal (max (defect N1) (defect N2)) * (uf n + ug n)\" for n\n    proof -\n      have \"N (f+g) \\<le> eNorm N1 (h1 n) + eNorm N2 (h2 n)\"\n        unfolding N_def apply (rule Inf_lower, auto, rule exI[of _ \"h1 n\"], rule exI[of _ \"h2 n\"])\n        using * by auto\n      also have \"... \\<le> ennreal (defect N1) * eNorm N1 (f1 n) + ennreal (defect N1) * eNorm N1 (g1 n)\n                      + (ennreal (defect N2) * eNorm N2 (f2 n) + ennreal (defect N2) * eNorm N2 (g2 n))\"\n        unfolding h1_def h2_def apply (rule add_mono) using eNorm_triangular_ineq by auto\n      also have \"... \\<le> (ennreal (max (defect N1) (defect N2)) * eNorm N1 (f1 n) + ennreal (max (defect N1) (defect N2)) * eNorm N1 (g1 n))\n                      + (ennreal (max (defect N1) (defect N2)) * eNorm N2 (f2 n) + ennreal (max (defect N1) (defect N2)) * eNorm N2 (g2 n))\"\n        by (auto intro!: add_mono mult_mono ennreal_leI)\n      also have \"... = ennreal (max (defect N1) (defect N2)) * (uf n + ug n)\"\n        unfolding F(1) G(1) by (auto simp add: algebra_simps)\n      finally show ?thesis by simp\n    qed\n    moreover have \"... \\<longlonglongrightarrow> ennreal (max (defect N1) (defect N2)) * (N f + N g)\"\n      unfolding N_def by (auto intro!: tendsto_intros simp add: uf(2) ug(2))\n    ultimately have \"N (f+g) \\<le> ennreal (max (defect N1) (defect N2)) * (N f + N g)\"\n      using LIMSEQ_le_const by blast\n    then show ?thesis by (auto simp add: algebra_simps)\n  qed\n\n  have H: \"N (c *\\<^sub>R f) \\<le> ennreal \\<bar>c\\<bar> * N f\" for c f\n  proof -\n    have \"\\<exists>u. (\\<forall>n. u n \\<in> {eNorm N1 f1 + eNorm N2 f2| f1 f2. f = f1 + f2}) \\<and> u \\<longlonglongrightarrow> Inf {eNorm N1 f1 + eNorm N2 f2| f1 f2. f = f1 + f2}\"\n      by (rule Inf_as_limit, auto, rule exI[of _ \"f\"], rule exI[of _ 0], auto)\n    then obtain uf where uf: \"\\<And>n. uf n \\<in> {eNorm N1 f1 + eNorm N2 f2| f1 f2. f = f1 + f2}\"\n                             \"uf \\<longlonglongrightarrow> Inf {eNorm N1 f1 + eNorm N2 f2| f1 f2. f = f1 + f2}\"\n      by blast\n    have \"\\<exists>f1 f2. \\<forall>n. uf n = eNorm N1 (f1 n) + eNorm N2 (f2 n) \\<and> f = f1 n + f2 n\"\n      apply (rule SMT.choices(1)) using uf(1) by blast\n    then obtain f1 f2 where F: \"\\<And>n. uf n = eNorm N1 (f1 n) + eNorm N2 (f2 n)\" \"\\<And>n. f = f1 n + f2 n\"\n      by blast\n\n    have \"N (c *\\<^sub>R f) \\<le> \\<bar>c\\<bar> * uf n\" for n\n    proof -\n      have \"N (c *\\<^sub>R f) \\<le> eNorm N1 (c *\\<^sub>R f1 n) + eNorm N2 (c *\\<^sub>R f2 n)\"\n        unfolding N_def apply (rule Inf_lower, auto, rule exI[of _ \"c *\\<^sub>R f1 n\"], rule exI[of _ \"c *\\<^sub>R f2 n\"])\n        using F(2)[of n] scaleR_add_right by auto\n      also have \"... = \\<bar>c\\<bar> * (eNorm N1 (f1 n) + eNorm N2 (f2 n))\"\n        by (auto simp add: algebra_simps eNorm_cmult)\n      finally show ?thesis using F(1) by simp\n    qed\n    moreover have \"... \\<longlonglongrightarrow> \\<bar>c\\<bar> * N f\"\n      unfolding N_def by (auto intro!: tendsto_intros simp add: uf(2))\n    ultimately show ?thesis\n      using LIMSEQ_le_const by blast\n  qed\n\n  have \"Inf {eNorm N1 f1 + eNorm N2 f2| f1 f2. 0 = f1 + f2} \\<le> 0\"\n    by (rule Inf_lower, auto, rule exI[of _ 0], auto)\n  then have Z: \"Inf {eNorm N1 f1 + eNorm N2 f2| f1 f2. 0 = f1 + f2} = 0\"\n    by auto\n\n  have *: \"quasinorm_on UNIV (max (defect N1) (defect N2)) (\\<lambda>f. Inf {eNorm N1 f1 + eNorm N2 f2| f1 f2. f = f1 + f2})\"\n    apply (rule quasinorm_onI) using T H Z defect_ge_1[of N1] defect_ge_1[of N2] unfolding N_def by auto\n  show \"defect (N1 +\\<^sub>N N2) = max (defect N1) (defect N2)\"\n       \"eNorm (N1 +\\<^sub>N N2) f = Inf {eNorm N1 f1 + eNorm N2 f2| f1 f2. f = f1 + f2}\"\n    unfolding quasinorm_sum_def using quasinorm_of[OF *] by auto\nqed\n\nlemma quasinorm_sum_limit:\n  \"\\<exists>f1 f2. (\\<forall>n. f = f1 n + f2 n) \\<and> (\\<lambda>n. eNorm N1 (f1 n) + eNorm N2 (f2 n)) \\<longlonglongrightarrow> eNorm (N1 +\\<^sub>N N2) f\"\nproof -\n  have \"\\<exists>u. (\\<forall>n. u n \\<in> {eNorm N1 f1 + eNorm N2 f2| f1 f2. f = f1 + f2}) \\<and> u \\<longlonglongrightarrow> Inf {eNorm N1 f1 + eNorm N2 f2| f1 f2. f = f1 + f2}\"\n    by (rule Inf_as_limit, auto, rule exI[of _ \"f\"], rule exI[of _ 0], auto)\n  then obtain uf where uf: \"\\<And>n. uf n \\<in> {eNorm N1 f1 + eNorm N2 f2| f1 f2. f = f1 + f2}\"\n                           \"uf \\<longlonglongrightarrow> Inf {eNorm N1 f1 + eNorm N2 f2| f1 f2. f = f1 + f2}\"\n    by blast\n  have \"\\<exists>f1 f2. \\<forall>n. uf n = eNorm N1 (f1 n) + eNorm N2 (f2 n) \\<and> f = f1 n + f2 n\"\n    apply (rule SMT.choices(1)) using uf(1) by blast\n  then obtain f1 f2 where F: \"\\<And>n. uf n = eNorm N1 (f1 n) + eNorm N2 (f2 n)\" \"\\<And>n. f = f1 n + f2 n\"\n    by blast\n  have \"(\\<lambda>n. eNorm N1 (f1 n) + eNorm N2 (f2 n)) \\<longlonglongrightarrow> eNorm (N1 +\\<^sub>N N2) f\"\n    using F(1) uf(2) unfolding quasinorm_sum(1) by presburger\n  then show ?thesis using F(2) by auto\nqed\n\nlemma quasinorm_sum_space:\n  \"space\\<^sub>N (N1 +\\<^sub>N N2) = {f + g|f g. f \\<in> space\\<^sub>N N1 \\<and> g \\<in> space\\<^sub>N N2}\"\nproof (auto)\n  fix x assume \"x \\<in> space\\<^sub>N (N1 +\\<^sub>N N2)\"\n  then have \"Inf {eNorm N1 f + eNorm N2 g| f g. x = f + g} < \\<infinity>\"\n    unfolding quasinorm_sum(1) spaceN_iff.\n  then have \"\\<exists>z \\<in> {eNorm N1 f + eNorm N2 g| f g. x = f + g}. z < \\<infinity>\"\n    by (simp add: Inf_less_iff)\n  then show \"\\<exists>f g. x = f + g \\<and> f \\<in> space\\<^sub>N N1 \\<and> g \\<in> space\\<^sub>N N2\"\n    using spaceN_iff by force\nnext\n  fix f g assume H: \"f \\<in> space\\<^sub>N N1\" \"g \\<in> space\\<^sub>N N2\"\n  have \"Inf {eNorm N1 u + eNorm N2 v| u v. f + g = u + v} \\<le> eNorm N1 f + eNorm N2 g\"\n    by (rule Inf_lower, auto)\n  also have \"... < \\<infinity>\" using spaceN_iff H by auto\n  finally show \"f + g \\<in> space\\<^sub>N (N1 +\\<^sub>N N2)\"\n    unfolding spaceN_iff quasinorm_sum(1).\nqed\n\nlemma quasinorm_sum_zerospace:\n  \"{f + g |f g. f \\<in> zero_space\\<^sub>N N1 \\<and> g \\<in> zero_space\\<^sub>N N2} \\<subseteq> zero_space\\<^sub>N (N1 +\\<^sub>N N2)\"\nproof (auto, unfold zero_spaceN_iff)\n  fix f g assume H: \"eNorm N1 f = 0\" \"eNorm N2 g = 0\"\n  have \"Inf {eNorm N1 f1 + eNorm N2 f2| f1 f2. f + g = f1 + f2} \\<le> 0\"\n    by (rule Inf_lower, auto, rule exI[of _ f], auto simp add: H)\n  then show \"eNorm (N1 +\\<^sub>N N2) (f + g) = 0\" unfolding quasinorm_sum(1) by auto\nqed\n\nlemma quasinorm_sum_subset:\n  \"N1 \\<subseteq>\\<^sub>N N1 +\\<^sub>N N2\" \"N2 \\<subseteq>\\<^sub>N N1 +\\<^sub>N N2\"\nby (rule quasinorm_subsetI[of _ _ 1], auto simp add: quasinorm_sum(1), rule Inf_lower, auto,\n  metis add.commute add.left_neutral eNorm_zero)+\n\nlemma quasinorm_sum_maximum:\n  assumes \"N1 \\<subseteq>\\<^sub>N N\" \"N2 \\<subseteq>\\<^sub>N N\"\n  shows \"N1 +\\<^sub>N N2 \\<subseteq>\\<^sub>N N\"\nproof -\n  obtain C1 C2::real where *: \"\\<And>f. eNorm N f \\<le> C1 * eNorm N1 f\"\n                              \"\\<And>f. eNorm N f \\<le> C2 * eNorm N2 f\"\n                              \"C1 \\<ge> 0\" \"C2 \\<ge> 0\"\n    using quasinorm_subsetD[OF assms(1)] quasinorm_subsetD[OF assms(2)] by blast\n  have **: \"eNorm N f \\<le> (defect N * max C1 C2) * eNorm (N1 +\\<^sub>N N2) f\" for f\n  proof -\n    obtain f1 f2 where F: \"\\<And>n. f = f1 n + f2 n\"\n                          \"(\\<lambda>n. eNorm N1 (f1 n) + eNorm N2 (f2 n)) \\<longlonglongrightarrow> eNorm (N1 +\\<^sub>N N2) f\"\n      using quasinorm_sum_limit by blast\n    have \"eNorm N f \\<le> ennreal (defect N * max C1 C2) * (eNorm N1 (f1 n) + eNorm N2 (f2 n))\" for n\n    proof -\n      have \"eNorm N f \\<le> ennreal(defect N) * eNorm N (f1 n) + ennreal(defect N) * eNorm N (f2 n)\"\n        unfolding \\<open>f = f1 n + f2 n\\<close> using eNorm_triangular_ineq by auto\n      also have \"... \\<le> ennreal(defect N) * (C1 * eNorm N1 (f1 n)) + ennreal(defect N) * (C2 * eNorm N2 (f2 n))\"\n        apply (rule add_mono) by (rule mult_mono, simp, simp add: *, simp, simp)+\n      also have \"... \\<le> ennreal(defect N) * (max C1 C2 * eNorm N1 (f1 n)) + ennreal(defect N) * (max C1 C2 * eNorm N2 (f2 n))\"\n        by (auto intro!:add_mono mult_mono ennreal_leI)\n      also have \"... = ennreal (defect N * max C1 C2) * (eNorm N1 (f1 n) + eNorm N2 (f2 n))\"\n        apply (subst ennreal_mult') using defect_ge_1 order_trans zero_le_one apply blast\n        by (auto simp add: algebra_simps)\n      finally show ?thesis by simp\n    qed\n    moreover have \"... \\<longlonglongrightarrow> (defect N * max C1 C2) * eNorm (N1 +\\<^sub>N N2) f\"\n      by (auto intro!:tendsto_intros F(2))\n    ultimately show ?thesis\n      using LIMSEQ_le_const by blast\n  qed\n  then show ?thesis\n    using quasinorm_subsetI by force\nqed\n\nlemma quasinorm_sum_assoc:\n  \"(N1 +\\<^sub>N N2) +\\<^sub>N N3 =\\<^sub>N N1 +\\<^sub>N (N2 +\\<^sub>N N3)\"\nunfolding quasinorm_equivalent_def by (meson order_trans quasinorm_sum_maximum quasinorm_sum_subset)\n\n\nsubsection \\<open>Topology\\<close>\n\ndefinition topology\\<^sub>N::\"('a::real_vector) quasinorm \\<Rightarrow> 'a topology\"\n  where \"topology\\<^sub>N N = topology (\\<lambda>U. \\<forall>x\\<in>U. \\<exists>e>0. \\<forall>y. eNorm N (y-x) < e \\<longrightarrow> y \\<in> U)\"\n\nlemma istopology_topology\\<^sub>N:\n  \"istopology (\\<lambda>U. \\<forall>x\\<in>U. \\<exists>e>0. \\<forall>y. eNorm N (y-x) < e \\<longrightarrow> y \\<in> U)\"\nunfolding istopology_def by (auto, metis dual_order.strict_trans less_linear, meson)\n\nlemma openin_topology\\<^sub>N:\n  \"openin (topology\\<^sub>N N) U \\<longleftrightarrow> (\\<forall>x\\<in>U. \\<exists>e>0. \\<forall>y. eNorm N (y-x) < e \\<longrightarrow> y \\<in> U)\"\nunfolding topology\\<^sub>N_def using istopology_topology\\<^sub>N[of N] by (simp add: topology_inverse')\n\nlemma openin_topology\\<^sub>N_I:\n  assumes \"\\<And>x. x \\<in> U \\<Longrightarrow> \\<exists>e>0. \\<forall>y. eNorm N (y-x) < e \\<longrightarrow> y \\<in> U\"\n  shows \"openin (topology\\<^sub>N N) U\"\nusing assms unfolding openin_topology\\<^sub>N by auto\n\nlemma openin_topology\\<^sub>N_D:\n  assumes \"openin (topology\\<^sub>N N) U\"\n          \"x \\<in> U\"\n  shows \"\\<exists>e>0. \\<forall>y. eNorm N (y-x) < e \\<longrightarrow> y \\<in> U\"\n  using assms unfolding openin_topology\\<^sub>N by auto\n\ntext \\<open>One should then use this topology to define limits and so on. This is not something\nspecific to quasinorms, but to all topologies defined in this way, not using type classes.\nHowever, there is no such body of material (yet?) in Isabelle-HOL, where topology is\nessentially done with type classes. So, we do not go any further for now.\n\nOne exception is the notion of completeness, as it is so important in functional analysis.\nWe give a naive definition, which will be sufficient for the proof of completeness\nof several spaces. Usually, the most convenient criterion to prove completeness of\na normed vector space is in terms of converging series. This criterion\nis the only nontrivial thing we prove here. We will apply it to prove the\ncompleteness of $L^p$ spaces.\\<close>\n\ndefinition cauchy_ine\\<^sub>N::\"('a::real_vector) quasinorm \\<Rightarrow> (nat \\<Rightarrow> 'a) \\<Rightarrow> bool\"\n  where \"cauchy_ine\\<^sub>N N u = (\\<forall>e>0. \\<exists>M. \\<forall>n\\<ge>M. \\<forall>m\\<ge>M. eNorm N (u n - u m) < e)\"\n\n\ndefinition tendsto_ine\\<^sub>N::\"('a::real_vector) quasinorm \\<Rightarrow> (nat \\<Rightarrow> 'a) \\<Rightarrow> 'a => bool\"\n  where \"tendsto_ine\\<^sub>N N u x = (\\<lambda>n. eNorm N (u n - x)) \\<longlonglongrightarrow> 0\"\n\ndefinition complete\\<^sub>N::\"('a::real_vector) quasinorm \\<Rightarrow> bool\"\n  where \"complete\\<^sub>N N = (\\<forall>u. cauchy_ine\\<^sub>N N u \\<longrightarrow> (\\<exists>x. tendsto_ine\\<^sub>N N u x))\"\n\ntext \\<open>The above definitions are in terms of eNorms, but usually the nice definitions\nonly make sense on the space of the norm, and are expressed in terms of Norms. We formulate\nthe same definitions with norms, they will be more convenient for the proofs.\\<close>\n\ndefinition cauchy_in\\<^sub>N::\"('a::real_vector) quasinorm \\<Rightarrow> (nat \\<Rightarrow> 'a) \\<Rightarrow> bool\"\n  where \"cauchy_in\\<^sub>N N u = (\\<forall>e>0. \\<exists>M. \\<forall>n\\<ge>M. \\<forall>m\\<ge>M. Norm N (u n - u m) < e)\"\n\ndefinition tendsto_in\\<^sub>N::\"('a::real_vector) quasinorm \\<Rightarrow> (nat \\<Rightarrow> 'a) \\<Rightarrow> 'a => bool\"\n  where \"tendsto_in\\<^sub>N N u x = (\\<lambda>n. Norm N (u n - x)) \\<longlonglongrightarrow> 0\"\n\nlemma cauchy_ine\\<^sub>N_I:\n  assumes \"\\<And>e. e > 0 \\<Longrightarrow> (\\<exists>M. \\<forall>n\\<ge>M. \\<forall>m\\<ge>M. eNorm N (u n - u m) < e)\"\n  shows \"cauchy_ine\\<^sub>N N u\"\nusing assms unfolding cauchy_ine\\<^sub>N_def by auto\n\nlemma cauchy_in\\<^sub>N_I:\n  assumes \"\\<And>e. e > 0 \\<Longrightarrow> (\\<exists>M. \\<forall>n\\<ge>M. \\<forall>m\\<ge>M. Norm N (u n - u m) < e)\"\n  shows \"cauchy_in\\<^sub>N N u\"\nusing assms unfolding cauchy_in\\<^sub>N_def by auto\n\nlemma cauchy_ine_in:\n  assumes \"\\<And>n. u n \\<in> space\\<^sub>N N\"\n  shows \"cauchy_ine\\<^sub>N N u \\<longleftrightarrow> cauchy_in\\<^sub>N N u\"\nproof\n  assume \"cauchy_in\\<^sub>N N u\"\n  show \"cauchy_ine\\<^sub>N N u\"\n  proof (rule cauchy_ine\\<^sub>N_I)\n    fix e::ennreal assume \"e > 0\"\n    define e2 where \"e2 = min e 1\"\n    then obtain r where \"e2 = ennreal r\" \"r > 0\" unfolding e2_def using \\<open>e > 0\\<close>\n      by (metis ennreal_eq_1 ennreal_less_zero_iff le_ennreal_iff le_numeral_extra(1) min_def zero_less_one)\n    then obtain M where *: \"\\<forall>n\\<ge>M. \\<forall>m\\<ge>M. Norm N (u n - u m) < r\"\n      using \\<open>cauchy_in\\<^sub>N N u\\<close> \\<open>r > 0\\<close> unfolding cauchy_in\\<^sub>N_def by auto\n    then have \"\\<forall>n\\<ge>M. \\<forall>m\\<ge>M. eNorm N (u n - u m) < r\"\n      by (auto simp add: assms eNorm_Norm \\<open>0 < r\\<close> ennreal_lessI)\n    then have \"\\<forall>n\\<ge>M. \\<forall>m\\<ge>M. eNorm N (u n - u m) < e\"\n      unfolding \\<open>e2 = ennreal r\\<close>[symmetric] e2_def by auto\n    then show \"\\<exists>M. \\<forall>n\\<ge>M. \\<forall>m\\<ge>M. eNorm N (u n - u m) < e\"\n      by auto\n  qed\nnext\n  assume \"cauchy_ine\\<^sub>N N u\"\n  show \"cauchy_in\\<^sub>N N u\"\n  proof (rule cauchy_in\\<^sub>N_I)\n    fix e::real assume \"e > 0\"\n    then obtain M where *: \"\\<forall>n\\<ge>M. \\<forall>m\\<ge>M. eNorm N (u n - u m) < e\"\n      using \\<open>cauchy_ine\\<^sub>N N u\\<close> \\<open>e > 0\\<close> ennreal_less_zero_iff unfolding cauchy_ine\\<^sub>N_def by blast\n    then have \"\\<forall>n\\<ge>M. \\<forall>m\\<ge>M. Norm N (u n - u m) < e\"\n      by (auto, metis Norm_def \\<open>0 < e\\<close> eNorm_Norm eNorm_Norm' enn2real_nonneg ennreal_less_iff)\n    then show \"\\<exists>M. \\<forall>n\\<ge>M. \\<forall>m\\<ge>M. Norm N (u n - u m) < e\"\n      by auto\n  qed\nqed\n\nlemma tendsto_ine_in:\n  assumes \"\\<And>n. u n \\<in> space\\<^sub>N N\" \"x \\<in> space\\<^sub>N N\"\n  shows \"tendsto_ine\\<^sub>N N u x \\<longleftrightarrow> tendsto_in\\<^sub>N N u x\"\nproof -\n  have *: \"eNorm N (u n - x) = Norm N (u n - x)\" for n\n    using assms eNorm_Norm spaceN_diff by blast\n  show ?thesis unfolding tendsto_in\\<^sub>N_def tendsto_ine\\<^sub>N_def *\n    apply (auto)\n    apply (metis (full_types) Norm_nonneg ennreal_0 eventually_sequentiallyI order_refl tendsto_ennreal_iff)\n    using tendsto_ennrealI by fastforce\nqed\n\nlemma complete\\<^sub>N_I:\n  assumes \"\\<And>u. cauchy_in\\<^sub>N N u \\<Longrightarrow> (\\<forall>n. u n \\<in> space\\<^sub>N N) \\<Longrightarrow> (\\<exists>x\\<in> space\\<^sub>N N. tendsto_in\\<^sub>N N u x)\"\n  shows \"complete\\<^sub>N N\"\nproof -\n  have \"\\<exists>x. tendsto_ine\\<^sub>N N u x\" if \"cauchy_ine\\<^sub>N N u\" for u\n  proof -\n    obtain M::nat where *: \"\\<And>n m. n \\<ge> M \\<Longrightarrow> m \\<ge> M \\<Longrightarrow> eNorm N (u n - u m) < 1\"\n      using \\<open>cauchy_ine\\<^sub>N N u\\<close> ennreal_zero_less_one unfolding cauchy_ine\\<^sub>N_def by presburger\n    define v where \"v = (\\<lambda>n. u (n+M) - u M)\"\n    have \"eNorm N (v n) < 1\" for n unfolding v_def using * by auto\n    then have \"v n \\<in> space\\<^sub>N N\" for n using spaceN_iff[of _ N]\n      by (metis dual_order.strict_trans ennreal_1 ennreal_less_top infinity_ennreal_def)\n    have \"cauchy_ine\\<^sub>N N v\"\n    proof (rule cauchy_ine\\<^sub>N_I)\n      fix e::ennreal assume \"e > 0\"\n      then obtain P::nat where *: \"\\<And>n m. n \\<ge> P \\<Longrightarrow> m \\<ge> P \\<Longrightarrow> eNorm N (u n - u m) < e\"\n        using \\<open>cauchy_ine\\<^sub>N N u\\<close> unfolding cauchy_ine\\<^sub>N_def by presburger\n      have \"eNorm N (v n - v m) < e\" if \"n \\<ge> P\" \"m \\<ge> P\" for m n\n        unfolding v_def by (auto, rule *, insert that, auto)\n      then show \"\\<exists>M. \\<forall>n\\<ge>M. \\<forall>m\\<ge>M. eNorm N (v n - v m) < e\" by auto\n    qed\n    then have \"cauchy_in\\<^sub>N N v\" using cauchy_ine_in[OF \\<open>\\<And>n. v n \\<in> space\\<^sub>N N\\<close>] by auto\n    then obtain y where \"tendsto_in\\<^sub>N N v y\" \"y \\<in> space\\<^sub>N N\"\n      using assms \\<open>\\<And>n. v n \\<in> space\\<^sub>N N\\<close> by auto\n    then have *: \"tendsto_ine\\<^sub>N N v y\"\n      using tendsto_ine_in \\<open>\\<And>n. v n \\<in> space\\<^sub>N N\\<close> by auto\n    have \"tendsto_ine\\<^sub>N N u (y + u M)\"\n      unfolding tendsto_ine\\<^sub>N_def apply (rule LIMSEQ_offset[of _ M])\n      using * unfolding v_def tendsto_ine\\<^sub>N_def by (auto simp add: algebra_simps)\n    then show ?thesis by auto\n  qed\n  then show ?thesis unfolding complete\\<^sub>N_def by auto\nqed\n\nlemma cauchy_tendsto_in_subseq:\n  assumes \"\\<And>n. u n \\<in> space\\<^sub>N N\"\n          \"cauchy_in\\<^sub>N N u\"\n          \"strict_mono r\"\n          \"tendsto_in\\<^sub>N N (u o r) x\"\n  shows \"tendsto_in\\<^sub>N N u x\"\nproof -\n  have \"\\<exists>M. \\<forall>n\\<ge>M. Norm N (u n - x) < e\" if \"e > 0\" for e\n  proof -\n    define f where \"f = e / (2 * defect N)\"\n    have \"f > 0\" unfolding f_def using \\<open>e > 0\\<close> defect_ge_1[of N] by (auto simp add: divide_simps)\n    obtain M1 where M1: \"\\<And>m n. m \\<ge> M1 \\<Longrightarrow> n \\<ge> M1 \\<Longrightarrow> Norm N (u n - u m) < f\"\n      using \\<open>cauchy_in\\<^sub>N N u\\<close> unfolding cauchy_in\\<^sub>N_def using \\<open>f > 0\\<close> by meson\n    obtain M2 where M2: \"\\<And>n. n \\<ge> M2 \\<Longrightarrow> Norm N ((u o r) n - x) < f\"\n      using \\<open>tendsto_in\\<^sub>N N (u o r) x\\<close> \\<open>f > 0\\<close> unfolding tendsto_in\\<^sub>N_def order_tendsto_iff eventually_sequentially by blast\n    define M where \"M = max M1 M2\"\n    have \"Norm N (u n - x) < e\" if \"n \\<ge> M\" for n\n    proof -\n      have \"Norm N (u n - x) = Norm N ((u n - u (r M)) + (u (r M) - x))\" by auto\n      also have \"... \\<le> defect N * Norm N (u n - u (r M)) + defect N * Norm N (u (r M) - x)\"\n        apply (rule Norm_triangular_ineq) using \\<open>\\<And>n. u n \\<in> space\\<^sub>N N\\<close> by simp\n      also have \"... < defect N * f + defect N * f\"\n        apply (auto intro!: add_strict_mono mult_mono simp only:)\n        using defect_ge_1[of N] \\<open>n \\<ge> M\\<close> seq_suble[OF \\<open>strict_mono r\\<close>, of M] M1 M2 o_def unfolding M_def by auto\n      finally show ?thesis\n        unfolding f_def using \\<open>e > 0\\<close> defect_ge_1[of N] by (auto simp add: divide_simps)\n    qed\n    then show ?thesis by auto\n  qed\n  then show ?thesis\n    unfolding tendsto_in\\<^sub>N_def order_tendsto_iff eventually_sequentially using Norm_nonneg less_le_trans by blast\nqed\n\nproposition complete\\<^sub>N_I':\n  assumes \"\\<And>n. c n > 0\"\n          \"\\<And>u. (\\<forall>n. u n \\<in> space\\<^sub>N N) \\<Longrightarrow> (\\<forall>n. Norm N (u n) \\<le> c n) \\<Longrightarrow> \\<exists>x\\<in> space\\<^sub>N N. tendsto_in\\<^sub>N N (\\<lambda>n. (\\<Sum>i\\<in>{0..<n}. u i)) x\"\n  shows \"complete\\<^sub>N N\"\nproof (rule complete\\<^sub>N_I)\n  fix v assume \"cauchy_in\\<^sub>N N v\" \"\\<forall>n. v n \\<in> space\\<^sub>N N\"\n  have *: \"\\<exists>y. (\\<forall>m\\<ge>y. \\<forall>p\\<ge>y. Norm N (v m - v p) < c (Suc n)) \\<and> x < y\" if \"\\<forall>m\\<ge>x. \\<forall>p\\<ge>x. Norm N (v m - v p) < c n\" for x n\n  proof -\n    obtain M where i: \"\\<forall>m\\<ge>M. \\<forall>p\\<ge>M. Norm N (v m - v p) < c (Suc n)\"\n      using \\<open>cauchy_in\\<^sub>N N v\\<close> \\<open>c (Suc n) > 0\\<close> unfolding cauchy_in\\<^sub>N_def by (meson zero_less_power)\n    then show ?thesis\n      apply (intro exI[of _ \"max M (x+1)\"]) by auto\n  qed\n  have \"\\<exists>r. \\<forall>n. (\\<forall>m\\<ge>r n. \\<forall>p\\<ge>r n. Norm N (v m - v p) < c n) \\<and> r n < r (Suc n)\"\n    apply (intro dependent_nat_choice) using \\<open>cauchy_in\\<^sub>N N v\\<close> \\<open>\\<And>n. c n > 0\\<close> * unfolding cauchy_in\\<^sub>N_def by auto\n  then obtain r where r: \"strict_mono r\" \"\\<And>n. \\<forall>m\\<ge>r n. \\<forall>p\\<ge>r n. Norm N (v m - v p) < c n\"\n    by (auto simp: strict_mono_Suc_iff)\n  define u where \"u = (\\<lambda>n. v (r (Suc n)) - v (r n))\"\n  have \"u n \\<in> space\\<^sub>N N\" for n\n    unfolding u_def using \\<open>\\<forall>n. v n \\<in> space\\<^sub>N N\\<close> by simp\n  moreover have \"Norm N (u n) \\<le> c n\" for n\n    unfolding u_def using r by (simp add: less_imp_le strict_mono_def)\n  ultimately obtain y where y: \"y \\<in> space\\<^sub>N N\" \"tendsto_in\\<^sub>N N (\\<lambda>n. (\\<Sum>i\\<in>{0..<n}. u i)) y\"\n    using assms(2) by blast\n  define x where \"x = y + v (r 0)\"\n  have \"x \\<in> space\\<^sub>N N\"\n    unfolding x_def using \\<open>y \\<in> space\\<^sub>N N\\<close> \\<open>\\<forall>n. v n \\<in> space\\<^sub>N N\\<close> by simp\n  have \"Norm N (v (r n) - x) = Norm N ((\\<Sum>i\\<in>{0..<n}. u i) - y)\" for n\n  proof -\n    have \"v (r n) = (\\<Sum>i\\<in>{0..<n}. u i) + v (r 0)\" for n\n      unfolding u_def by (induct n, auto)\n    then show ?thesis unfolding x_def by (metis add_diff_cancel_right)\n  qed\n  then have \"(\\<lambda>n. Norm N (v (r n) - x)) \\<longlonglongrightarrow> 0\"\n    using y(2) unfolding tendsto_in\\<^sub>N_def by auto\n  then have \"tendsto_in\\<^sub>N N (v o r) x\"\n    unfolding tendsto_in\\<^sub>N_def comp_def by force\n  then have \"tendsto_in\\<^sub>N N v x\"\n    using \\<open>\\<forall>n. v n \\<in> space\\<^sub>N N\\<close> \n    by (intro cauchy_tendsto_in_subseq[OF _ \\<open>cauchy_in\\<^sub>N N v\\<close> \\<open>strict_mono r\\<close>], auto)\n  then show \"\\<exists>x\\<in>space\\<^sub>N N. tendsto_in\\<^sub>N N v x\"\n    using \\<open>x \\<in> space\\<^sub>N N\\<close> by blast\nqed\n\ntext \\<open>Next, we show when the two examples of norms we have introduced before, the ambient norm\nin a Banach space, and the norm on bounded continuous functions, are complete. We just have to\ntranslate in our setting the already known completeness of these spaces.\\<close>\n\nlemma complete_N_of_norm:\n  \"complete\\<^sub>N (N_of_norm::'a::banach quasinorm)\"\nproof (rule complete\\<^sub>N_I)\n  fix u::\"nat \\<Rightarrow> 'a\" assume \"cauchy_in\\<^sub>N N_of_norm u\"\n  then have \"Cauchy u\" unfolding Cauchy_def cauchy_in\\<^sub>N_def N_of_norm(2) by (simp add: dist_norm)\n  then obtain x where \"u \\<longlonglongrightarrow> x\" using convergent_eq_Cauchy by blast\n  then have \"tendsto_in\\<^sub>N N_of_norm u x\" unfolding tendsto_in\\<^sub>N_def N_of_norm(2)\n    using Lim_null tendsto_norm_zero_iff by fastforce\n  moreover have \"x \\<in> space\\<^sub>N N_of_norm\" by auto\n  ultimately show \"\\<exists>x\\<in>space\\<^sub>N N_of_norm. tendsto_in\\<^sub>N N_of_norm u x\" by auto\nqed\n\ntext \\<open>In the next statement, the assumption that \\verb+'a+ is a metric space is not necessary,\na topological space would be enough, but a statement about uniform convergence is not available\nin this setting.\nTODO: fix it.\n\\<close>\n\nlemma complete_bcontfunN:\n  \"complete\\<^sub>N (bcontfun\\<^sub>N::('a::metric_space \\<Rightarrow> 'b::banach) quasinorm)\"\nproof (rule complete\\<^sub>N_I)\n  fix u::\"nat \\<Rightarrow> ('a \\<Rightarrow> 'b)\" assume H: \"cauchy_in\\<^sub>N bcontfun\\<^sub>N u\" \"\\<forall>n. u n \\<in> space\\<^sub>N bcontfun\\<^sub>N\"\n  then have H2: \"u n \\<in> bcontfun\" for n using bcontfun\\<^sub>N_space by auto\n  then have **: \"Bcontfun(u n - u m) = Bcontfun (u n) - Bcontfun (u m)\" for m n\n    unfolding minus_fun_def minus_bcontfun_def by (simp add: Bcontfun_inverse)\n  have *: \"Norm bcontfun\\<^sub>N (u n - u m) = norm (Bcontfun (u n - u m))\" for n m\n    unfolding bcontfun\\<^sub>N(2) using H(2) bcontfun\\<^sub>N_space by auto\n  have \"Cauchy (\\<lambda>n. Bcontfun (u n))\"\n    using H(1) unfolding Cauchy_def cauchy_in\\<^sub>N_def dist_norm * ** by simp\n  then obtain v where v: \"(\\<lambda>n. Bcontfun (u n)) \\<longlonglongrightarrow> v\"\n    using convergent_eq_Cauchy by blast\n  have v_space: \"apply_bcontfun v \\<in> space\\<^sub>N bcontfun\\<^sub>N\" unfolding bcontfun\\<^sub>N_space by (simp add: apply_bcontfun)\n  have ***: \"Norm bcontfun\\<^sub>N (u n - v) = norm(Bcontfun (u n) - v)\" for n\n  proof -\n    have \"Norm bcontfun\\<^sub>N (u n - v) = norm (Bcontfun(u n - v))\"\n      unfolding bcontfun\\<^sub>N(2) using H(2) bcontfun\\<^sub>N_space v_space by auto\n    moreover have \"Bcontfun(u n - v) = Bcontfun (u n) - v\"\n      unfolding minus_fun_def minus_bcontfun_def by (simp add: Bcontfun_inverse H2)\n    ultimately show ?thesis by simp\n  qed\n  have \"tendsto_in\\<^sub>N bcontfun\\<^sub>N u v\"\n    unfolding tendsto_in\\<^sub>N_def *** using v Lim_null tendsto_norm_zero_iff by fastforce\n  then show \"\\<exists>v\\<in>space\\<^sub>N bcontfun\\<^sub>N. tendsto_in\\<^sub>N bcontfun\\<^sub>N u v\" using v_space 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/Lp/Functional_Spaces.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8333245787544825, "lm_q2_score": 0.8499711794579723, "lm_q1q2_score": 0.7083018750752654}}
{"text": "theory Practical\nimports Main\nbegin\n\nsection \\<open>Part 1\\<close>\n\n(* 1 mark *)\nlemma disjunction_idempotence:\n  \"A \\<or> A \\<longleftrightarrow> A\"\n  apply (rule iffI)\n  apply (erule disjE)\n  apply assumption+\n  apply (rule disjI1)\n  apply assumption\n  done\n\n(* 1 mark *)\nlemma conjunction_idempotence:\n  \"A \\<and> A \\<longleftrightarrow> A\"\n  apply (rule iffI)\n  apply (erule conjE)\n  apply (assumption)\n  apply (rule conjI)\n  apply assumption+\n  done\n\n(* 1 mark *)\nlemma disjunction_to_conditional:\n  \"(\\<not> P \\<or> R) \\<longrightarrow> (P \\<longrightarrow> R)\"\n  apply (rule impI)+\n  apply (erule disjE)\n  apply (erule notE)\n  apply assumption +\n  done\n\n\n(* 1 mark *)\nlemma\n  \"(\\<exists>x. P x \\<and> Q x) \\<longrightarrow> (\\<exists>x. P x) \\<and> (\\<exists>x. Q x)\"\n  apply (rule impI)\n  apply (rule conjI)\n  apply (erule exE, rule exI, erule conjE, assumption)+\n  done\n  \n\n(* 1 mark *)\nlemma\n  \"(\\<not> (\\<exists>x. \\<not>P x) \\<or> R) \\<longrightarrow> ((\\<exists>x. \\<not> P x) \\<longrightarrow> R)\"\n  apply (rule impI)\n  apply (erule disjE)\n   apply (rule impI)\n  apply (erule notE)\n  apply assumption\n  apply (rule impI)\n  apply assumption\n  done\n\n\n(* 2 marks *)\nlemma\n  \"(\\<forall>x. P x) \\<longrightarrow> \\<not> (\\<exists>x. \\<not> P x)\" \n  apply (rule impI)\n  apply (rule notI)\n  apply (erule exE)\n  apply (erule allE)\n  apply (erule notE)\n  apply assumption\n  done\n\n(* 3 marks *)\ntext \\<open>Prove using ccontr\\<close>\nlemma em:\n  \"P \\<or> \\<not> P\"\n  apply (rule ccontr)\n  apply (rule notE)\n   apply assumption\n  apply (rule disjI2)\n  apply (rule notI)\n  apply (erule notE)\n  apply (rule disjI1)\n  apply assumption\n  done\n\n(* 3 marks *)\ntext \\<open>Prove using excluded middle\\<close>\nlemma notnotD:\n  \"\\<not>\\<not> P \\<Longrightarrow> P\"\n  apply (cut_tac P =\"P\" in excluded_middle)\n  apply (erule disjE)\n  apply (erule notE)\n  apply assumption +\n  done\n\n(* 3 marks *)\ntext \\<open>Prove using double-negation (rule notnotD)\\<close>\nlemma classical:\n  \"(\\<not> P \\<Longrightarrow> P) \\<Longrightarrow> P\"\n  apply (drule impI)\n  apply (rule notnotD)\n  apply (rule notI)\n  apply (erule impE)\n  apply assumption\n  apply (erule notE)\n  apply assumption\n  done\n\n\n(* 3 marks *)\ntext \\<open>Prove using classical\\<close>\nlemma ccontr:\n  \"(\\<not> P \\<Longrightarrow> False) \\<Longrightarrow> P\"\n  apply (drule impI)\n  apply (rule classical)\n  apply (erule impE)\n  apply assumption\n  apply (erule FalseE)\n  done\n\n(* 3 marks *)\nlemma\n  \"(\\<not> (\\<forall>x. P x \\<or> R x)) = (\\<exists>x. \\<not> P x \\<and> \\<not> R x)\"\n  apply (rule iffI)\n   apply (rule classical)\n   apply (erule notE)+\n   apply (rule exI)\n   apply (rule conjI)\n    apply (rule notI)\n  apply assumption\n  apply (rule ccontr)\noops\n\n(* 3 marks *)\n\nlemma     \n  \"(\\<exists>x. P x \\<or> R x) = (\\<not>((\\<forall>x. \\<not> P x) \\<and> \\<not> (\\<exists>x. R x)))\"\n  apply (rule iffI)\n  apply (rule notI)\n  apply (erule exE)\n  apply (erule conjE)\n  apply (erule notE)+\n  apply (rule exI)\n  apply (erule disjE)\n  apply (erule allE)\n  apply (erule notE)\n    apply assumption+\n  apply (erule notE)\n  apply (rule conjI)\n   apply (rule allI)\n   apply (rule notI)\n  apply assumption\n\n\n  oops\nsection \\<open>Part 2.1\\<close>\n\nlocale partof =\n  fixes partof :: \"'region \\<Rightarrow> 'region \\<Rightarrow> bool\" (infix \"\\<sqsubseteq>\" 100)\nbegin\n\n(* 1 mark *)\ndefinition properpartof :: \"'region \\<Rightarrow> 'region \\<Rightarrow> bool\" (infix \"\\<sqsubset>\" 100) where\n  \"x \\<sqsubset> y \\<equiv> x \\<sqsubseteq> y \\<and> x \\<noteq> y\"\n\n(* 1 mark *)\ndefinition overlaps :: \"'region \\<Rightarrow> 'region \\<Rightarrow> bool\" (infix \"\\<frown>\" 100) where\n  \"x \\<frown> y \\<equiv> (\\<exists>z. z \\<sqsubseteq> x  \\<and> z \\<sqsubseteq> y)\"\n\ndefinition disjoint :: \"'region \\<Rightarrow> 'region \\<Rightarrow> bool\" (infix \"\\<asymp>\" 100) where\n  \"x \\<asymp> y \\<equiv> \\<not> x \\<frown> y\"\n\n(* 1 mark *)\ndefinition partialoverlap :: \"'region \\<Rightarrow> 'region \\<Rightarrow> bool\" (infix \"~\\<frown>\" 100) where\n  \"x ~\\<frown> y \\<equiv> x \\<frown> y \\<and> \\<not>x \\<sqsubseteq> y \\<and>  \\<not>y \\<sqsubseteq> x \"\n\n(* 1 mark *)\ndefinition sumregions :: \"'region set \\<Rightarrow> 'region \\<Rightarrow> bool\" (\"\\<Squnion> _ _\" [100, 100] 100) where\n  \"\\<Squnion> \\<alpha> x \\<equiv> (\\<forall>y \\<in> \\<alpha>. y \\<sqsubseteq> x) \\<and> (\\<forall>y. y \\<sqsubseteq> x  \\<longrightarrow> (\\<exists>z \\<in> \\<alpha>. y \\<frown> z))\"\n\nend\n\n(* 1+1+1=3 marks *)\nlocale mereology = partof +\n  assumes A1: \"\\<forall>xyz. x \\<sqsubseteq> y \\<and> y \\<sqsubseteq> z  \\<longrightarrow> x \\<sqsubseteq> z \"\n      and A2: \"\\<forall> \\<alpha>.  \\<alpha> \\<noteq> {}  \\<longrightarrow> (\\<exists>x. \\<Squnion> \\<alpha> x) \"\n      and A2': \"\\<forall>\\<alpha>xy. \\<Squnion> \\<alpha> x \\<and>  \\<Squnion> \\<alpha> y \\<longrightarrow> x = y \"\nbegin\n\nsection \\<open>Part 2.2\\<close>\n\n(* 2 marks *)\ntheorem overlaps_sym:\n  \"(x \\<frown> y) = (y \\<frown> x)\"\n  apply (unfold overlaps_def)\n  apply (rule iffI)\n  apply (erule exE, erule conjE, rule exI, rule conjI, assumption+)+\n  done\n\n(* 1 mark *)\ntheorem in_sum_set_partof:\n  \"x \\<in> \\<alpha>  \\<longrightarrow>  \\<Squnion> \\<alpha> x \"\nproof (unfold sumregions_def)\n  show  \"x \\<in> \\<alpha> \\<longrightarrow> (\\<forall>y\\<in>\\<alpha>. y \\<sqsubseteq> x) \\<and> (\\<forall>y. y \\<sqsubseteq> x \\<longrightarrow>(\\<exists>z\\<in>\\<alpha>. y \\<frown> z))\"\n    using sumregions_def by blast\nqed\n\n(* 3 marks *)\ntheorem overlaps_refl:\n  \"x \\<frown> x\\<longrightarrow>  \\<Squnion> \\<alpha> x \\<and> \\<Squnion> \\<alpha> y \\<and> x = y\"\nproof (unfold overlaps_def)\n  show \"(\\<exists>z. z \\<sqsubseteq> x \\<and> z \\<sqsubseteq> x) \\<longrightarrow> \\<Squnion> \\<alpha> x \\<and> \\<Squnion> \\<alpha> y \\<and> x = y\"\n    using sumregions_def A2' by blast\nqed\n\n(* 1 mark *)\ntheorem all_has_partof:\n  \"\\<forall>r. \\<exists>x. x \\<sqsubset> r\"\nproof (unfold properpartof_def)\n  show \"\\<forall>r. \\<exists>x. x \\<sqsubseteq> r \\<and> x \\<noteq> r\"\n    using properpartof_def by blast\nqed\n\n(* 2 marks *)\ntheorem partof_overlaps:\n  assumes \"x \\<sqsubset> y\"\n  shows \" \\<forall>r. r \\<sqsubset> x \\<longrightarrow> r \\<sqsubset> y\"\nproof (unfold properpartof_def)\n  show \" \\<forall>r. r \\<sqsubseteq> x \\<and> r \\<noteq> x \\<longrightarrow> r \\<sqsubseteq> y \\<and> r \\<noteq> y\"\n  using A1 properpartof_def by blast\nqed\n\n(* 1 mark *)\ntheorem sum_parts_eq:\n  \"\\<Squnion> {x} x\"\nproof (unfold sumregions_def)\n  show \"(\\<forall>y\\<in>{x}. y \\<sqsubseteq> x) \\<and> (\\<forall>y. y \\<sqsubseteq> x \\<longrightarrow>(\\<exists>z\\<in>{x}. y \\<frown> z))\"\n    by blast\nqed\n\n(* 2 marks *)\ntheorem sum_relation_is_same':\n  assumes \"\\<And>c. r y c \\<Longrightarrow> c \\<sqsubseteq> y\"\n      and \"\\<And>f. y \\<frown> f \\<Longrightarrow> \\<exists>g. r y g \\<and> g \\<frown> f\"\n      and \"\\<Squnion> {y} x\"\n    shows \"\\<Squnion> {k. r y k} x\"\nproof (unfold sumregions_def)\n  show \"(\\<forall>y\\<in>Collect (r y).y \\<sqsubseteq> x) \\<and> (\\<forall>ya. ya \\<sqsubseteq> x \\<longrightarrow> (\\<exists>z\\<in>Collect (r y). ya \\<frown> z))\"\n    using sumregions_def by blast\nqed\n\n\n(* 1 mark *)\ntheorem overlap_has_partof_overlap:\n  assumes \"e \\<frown> f\"\n  shows \"\\<exists>r. r \\<sqsubseteq> e \\<and> r  \\<frown> f\"\nproof (unfold overlaps_def)\n  show \"\\<exists>r. r \\<sqsubseteq> e \\<and> (\\<exists>z. z \\<sqsubseteq> r \\<and> z \\<sqsubseteq> f)\"\n    using overlaps_def by blast\noops\n\n(* 1 marks *)\ntheorem sum_parts_of_one_eq:\n  assumes \"undefined\"\n  shows \"undefined\"\noops\n\n(* 5 marks *)\ntheorem both_partof_eq:\n  assumes \"undefined\"\n  shows \"undefined\"\noops\n\n(* 4 marks *)\ntheorem sum_all_with_parts_overlapping:\n  assumes \"undefined\"\n  shows \"undefined\"\noops\n\n(* 2 marks *)\ntheorem sum_one_is_self:\n  \"undefined\"\noops\n\n(* 2 marks *)\ntheorem sum_all_with_parts_overlapping_self:\n  \"undefined\"\noops\n\n(* 4 marks *)\ntheorem proper_have_nonoverlapping_proper:\n  assumes \"undefined\"\n  shows \"undefined\"\noops\n\n(* 1 mark *)\nsublocale parthood_partial_order: order \"(\\<sqsubseteq>)\" \"(\\<sqsubset>)\"\nproof\n  show \"\\<And>x y. x \\<sqsubset> y = (x \\<sqsubseteq> y \\<and> \\<not> y \\<sqsubseteq> x)\"\n    sorry\nnext\n  show \"\\<And>x. x \\<sqsubseteq> x\"\n    sorry\nnext\n  show \"\\<And>x y z. \\<lbrakk>x \\<sqsubseteq> y; y \\<sqsubseteq> z\\<rbrakk> \\<Longrightarrow> x \\<sqsubseteq> z\"\n    sorry\nnext\n  show \"\\<And>x y. \\<lbrakk>x \\<sqsubseteq> y; y \\<sqsubseteq> x\\<rbrakk> \\<Longrightarrow> x = y\"\n    sorry\nqed\n\nend\n\nsection \\<open>Part 2.3\\<close>\n\nlocale sphere =\n  fixes sphere :: \"'a \\<Rightarrow> bool\"\nbegin\n\nabbreviation AllSpheres :: \"('a \\<Rightarrow> bool) \\<Rightarrow> bool\" (binder \"\\<forall>\\<degree>\" 10) where\n  \"\\<forall>\\<degree>x. P x \\<equiv> \\<forall>x. sphere x \\<longrightarrow> P x\"\n\nabbreviation ExSpheres :: \"('a \\<Rightarrow> bool) \\<Rightarrow> bool\" (binder \"\\<exists>\\<degree>\" 10) where\n  \"\\<exists>\\<degree>x. P x \\<equiv> \\<exists>x. sphere x \\<and> P x\"\n\nend\n\nlocale mereology_sphere = mereology partof + sphere sphere\n  for partof :: \"'region \\<Rightarrow> 'region \\<Rightarrow> bool\" (infix \"\\<sqsubseteq>\" 100)\n  and sphere :: \"'region \\<Rightarrow> bool\"\nbegin\n\ndefinition exttan :: \"'region \\<Rightarrow> 'region \\<Rightarrow> bool\" where\n  \"exttan a b \\<equiv> sphere a \\<and> sphere b \\<and> a \\<asymp> b \\<and> (\\<forall>\\<degree>x y. a \\<sqsubseteq> x \\<and> a \\<sqsubseteq> y \\<and> b \\<asymp> x \\<and> b \\<asymp> y\n                                                        \\<longrightarrow> x \\<sqsubseteq> y \\<or> y \\<sqsubseteq> x)\"\n\ndefinition inttan :: \"'region \\<Rightarrow> 'region \\<Rightarrow> bool\" where\n  \"inttan a b \\<equiv> sphere a \\<and> sphere b \\<and> a \\<asymp> b \\<and> (\\<forall>\\<degree>x y. a \\<sqsubseteq> x \\<and> a \\<sqsubseteq> y \\<and> x \\<sqsubseteq> b \\<and> y \\<sqsubseteq> b\n                                                        \\<longrightarrow> x \\<sqsubseteq> y \\<or> y \\<sqsubseteq> x)\"\n\ndefinition extdiam :: \"'region \\<Rightarrow> 'region \\<Rightarrow> 'region \\<Rightarrow> bool\" where\n  \"extdiam a b c \\<equiv> exttan a c \\<and> exttan b c\n                 \\<and> (\\<forall>\\<degree>x y. x \\<asymp> c \\<and> y \\<asymp> c \\<and> a \\<sqsubseteq> x \\<and> b \\<sqsubseteq> y \\<longrightarrow> x \\<asymp> y)\"\n\ndefinition intdiam :: \"'region \\<Rightarrow> 'region \\<Rightarrow> 'region \\<Rightarrow> bool\" where\n  \"intdiam a b c \\<equiv> inttan a c \\<and> inttan b c\n                 \\<and> (\\<forall>\\<degree>x y. x \\<asymp> c \\<and> y \\<asymp> c \\<and> exttan a x \\<and> exttan b y \\<longrightarrow> x \\<asymp> y)\"\n\nabbreviation properconcentric :: \"'region \\<Rightarrow> 'region \\<Rightarrow> bool\" where\n  \"properconcentric a b \\<equiv> a \\<sqsubset> b\n                        \\<and> (\\<forall>\\<degree>x y. extdiam x y a \\<and> inttan x b \\<and> inttan y b \\<longrightarrow> intdiam x y b)\"\n\ndefinition concentric :: \"'region \\<Rightarrow> 'region \\<Rightarrow> bool\" (infix \"\\<odot>\" 100) where\n  \"a \\<odot> b \\<equiv> sphere a \\<and> sphere b \\<and> (a = b \\<or> properconcentric a b \\<or> properconcentric b a)\"\n\ndefinition onboundary :: \"'region \\<Rightarrow> 'region \\<Rightarrow> bool\" where\n  \"onboundary s r \\<equiv> sphere s \\<and> (\\<forall>s'. s' \\<odot> s \\<longrightarrow> s' \\<frown> r \\<and> \\<not> s' \\<sqsubseteq> r)\"\n\ndefinition equidistant3 :: \"'region \\<Rightarrow> 'region \\<Rightarrow> 'region \\<Rightarrow> bool\" where\n  \"equidistant3 x y z \\<equiv> \\<exists>\\<degree>z'. z' \\<odot> z \\<and> onboundary y z' \\<and> onboundary x z'\"\n\ndefinition betw :: \"'region \\<Rightarrow> 'region \\<Rightarrow> 'region \\<Rightarrow> bool\" (\"[_ _ _]\" [100, 100, 100] 100) where\n  \"[x y z] \\<equiv> sphere x \\<and> sphere z\n             \\<and> (x \\<odot> y \\<or> y \\<odot> z\n                \\<or> (\\<exists>x' y' z' v w. x' \\<odot> x \\<and> y' \\<odot> y \\<and> z' \\<odot> z\n                                  \\<and> extdiam x' y' v \\<and> extdiam v w y' \\<and> extdiam y' z' w))\"\n\ndefinition mid :: \"'region \\<Rightarrow> 'region \\<Rightarrow> 'region \\<Rightarrow> bool\" where\n  \"mid x y z \\<equiv> [x y z] \\<and> (\\<exists>\\<degree>y'. y' \\<odot> y \\<and> onboundary x y' \\<and> onboundary z y')\"\n\ndefinition equidistant4 :: \"'region \\<Rightarrow> 'region \\<Rightarrow> 'region \\<Rightarrow> 'region \\<Rightarrow> bool\" (\"_ _ \\<doteq> _ _\" [100, 100, 100, 100] 100) where\n  \"x y \\<doteq> z w \\<equiv> \\<exists>\\<degree>u v. mid w u y \\<and> mid x u v \\<and> equidistant3 v z y\"\n\ndefinition oninterior :: \"'region \\<Rightarrow> 'region \\<Rightarrow> bool\" where\n  \"oninterior s r \\<equiv> \\<exists>s'. s' \\<odot> s \\<and> s' \\<sqsubseteq> r\"\n\ndefinition nearer :: \"'region \\<Rightarrow> 'region \\<Rightarrow> 'region \\<Rightarrow> 'region \\<Rightarrow> bool\" where\n  \"nearer w x y z \\<equiv> \\<exists>\\<degree>x'. [w x x'] \\<and> \\<not> x \\<odot> x' \\<and> w x' \\<doteq> y z\"\n\nend\n\nlocale partial_region_geometry = mereology_sphere partof sphere\n  for partof :: \"'region \\<Rightarrow> 'region \\<Rightarrow> bool\" (infix \"\\<sqsubseteq>\" 100)\n  and sphere :: \"'region \\<Rightarrow> bool\" +\n  assumes A4: \"\\<lbrakk>x \\<odot> y; y \\<odot> z\\<rbrakk> \\<Longrightarrow> x \\<odot> z\"\n      and A5: \"\\<lbrakk>x y \\<doteq> z w; x' \\<odot> x\\<rbrakk> \\<Longrightarrow> x' y \\<doteq> z w\"\n      and A6: \"\\<lbrakk>sphere x; sphere y; \\<not> x \\<odot> y\\<rbrakk>\n               \\<Longrightarrow> \\<exists>\\<degree>s. \\<forall>\\<degree>z. oninterior z s = nearer x z x y\"\n      and A7: \"sphere x \\<Longrightarrow> \\<exists>\\<degree>y. \\<not> x \\<odot> y \\<and> (\\<forall>\\<degree>z. oninterior z x = nearer x z x y)\"\n      and A8: \"x \\<sqsubseteq> y = (\\<forall>s. oninterior s x \\<longrightarrow> oninterior s y)\"\n      and A9: \"\\<exists>\\<degree>s. s \\<sqsubseteq> r\"\nbegin\n\n(* 2 marks *)\nthm equiv_def\ntheorem conc_equiv:\n  \"equiv undefined undefined\"\noops\n\n(* 6 marks *)\ntheorem region_is_spherical_sum:\n  \"undefined\"\noops\n\n(* 1 mark *)\ntheorem region_spherical_interior:\n  \"undefined\"\noops\n\n(* 2 marks *)\ntheorem equal_interiors_equal_regions:\n  assumes \"undefined\"\n  shows \"undefined\"\noops\n\n(* 2 marks *)\ntheorem proper_have_nonoverlapping_proper_sphere:\n  assumes \"undefined\"\n  shows \"undefined\"\noops\n\n(* 4 marks *)\ntheorem not_sphere_spherical_parts_gt1:\n  assumes \"undefined\"\n      and \"undefined\"\n  shows \"undefined\"\noops\n\nend\n\nsection \\<open>Part 3\\<close>\n\ncontext mereology_sphere\nbegin\n\n(* 3 marks *)\nlemma\n  assumes T4: \"\\<And>x y. \\<lbrakk>sphere x; sphere y\\<rbrakk> \\<Longrightarrow> x y \\<doteq> y x\"\n      and A9: \"\\<exists>\\<degree>s. s \\<sqsubseteq> r\"\n  shows False\noops\n\n(* 3 marks *)\ndefinition equidistant3' :: \"'region \\<Rightarrow> 'region \\<Rightarrow> 'region \\<Rightarrow> bool\" where\n  \"equidistant3' x y z \\<equiv> undefined\"\n\nno_notation equidistant4 (\"_ _ \\<doteq> _ _\" [100, 100, 100, 100] 100)\n\ndefinition equidistant4' :: \"'region \\<Rightarrow> 'region \\<Rightarrow> 'region \\<Rightarrow> 'region \\<Rightarrow> bool\" (\"_ _ \\<doteq> _ _\" [100, 100, 100, 100] 100) where\n  \"x y \\<doteq> z w \\<equiv> \\<exists>\\<degree>u v. mid w u y \\<and> mid x u v \\<and> equidistant3' v z y\"\n\nend\n\ndatatype two_reg = Left | Right | Both\n\n(* 2 marks *)\ndefinition tworeg_partof :: \"two_reg \\<Rightarrow> two_reg \\<Rightarrow> bool\" (infix \"\\<sqsubseteq>\" 100) where\n  \"x \\<sqsubseteq> y \\<equiv> undefined\"\n\n(* 12 marks *)\ninterpretation mereology \"(\\<sqsubseteq>)\"\noops\n\n\nend", "meta": {"author": "kenza-amira", "repo": "Automated_Reasoning_Coursework", "sha": "b1ef674d7cf81ce6e32c64bdb6dec4b134478600", "save_path": "github-repos/isabelle/kenza-amira-Automated_Reasoning_Coursework", "path": "github-repos/isabelle/kenza-amira-Automated_Reasoning_Coursework/Automated_Reasoning_Coursework-b1ef674d7cf81ce6e32c64bdb6dec4b134478600/Practical.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8688267830311354, "lm_q2_score": 0.8152324848629215, "lm_q1q2_score": 0.7082958172459309}}
{"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_MSortBU2Permutes\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 elem :: \"'a => 'a list => bool\" where\n  \"elem x (nil2) = False\"\n| \"elem x (cons2 z xs) = ((z = x) | (elem x xs))\"\n\nfun deleteBy :: \"('a => ('a => bool)) => 'a => 'a list =>\n                 'a list\" where\n  \"deleteBy x y (nil2) = nil2\"\n| \"deleteBy x y (cons2 y2 ys) =\n     (if (x y) y2 then ys else cons2 y2 (deleteBy x y ys))\"\n\nfun isPermutation :: \"'a list => 'a list => bool\" where\n  \"isPermutation (nil2) (nil2) = True\"\n| \"isPermutation (nil2) (cons2 z x2) = False\"\n| \"isPermutation (cons2 x3 xs) y =\n     ((elem x3 y) &\n        (isPermutation\n           xs (deleteBy (% (x4 :: 'a) => % (x5 :: 'a) => (x4 = x5)) x3 y)))\"\n\ntheorem property0 :\n  \"isPermutation (msortbu2 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_sort_nat_MSortBU2Permutes.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206738932334, "lm_q2_score": 0.7853085708384735, "lm_q1q2_score": 0.708286035424768}}
{"text": "theory tree_sort_SortPermutes\nimports Main\n        \"$HIPSTER_HOME/IsaHipster\"\nbegin\n\ndatatype 'a list = Nil2 | Cons2 \"'a\" \"'a list\"\n\ndatatype 'a Tree = Node \"'a Tree\" \"'a\" \"'a Tree\" | Nil2\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 flatten :: \"'a Tree => 'a list => 'a list\" where\n\"flatten (Node q z q2) y = flatten q (Cons2 z (flatten q2 y))\"\n| \"flatten (Nil2) y = y\"\n\nfun equal2 :: \"Nat => Nat => bool\" where\n\"equal2 (Z) (Z) = True\"\n| \"equal2 (Z) (S z) = False\"\n| \"equal2 (S x2) (Z) = False\"\n| \"equal2 (S x2) (S y2) = equal2 x2 y2\"\n\nfun count :: \"Nat => Nat list => Nat\" where\n\"count x (Nil2) = Z\"\n| \"count x (Cons2 z xs) =\n     (if equal2 x z then S (count x xs) else count x xs)\"\n\nfun add :: \"Nat => Nat Tree => Nat Tree\" where\n\"add x (Node q z q2) =\n   (if le x z then Node (add x q) z q2 else Node q z (add x q2))\"\n| \"add x (Nil2) = Node (Nil2) x (Nil2)\"\n\nfun toTree :: \"Nat list => Nat Tree\" where\n\"toTree (Nil2) = Nil2\"\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\n(*hipster le flatten equal2 count add toTree tsort *)\n\ntheorem x0 :\n  \"!! (x :: Nat) (y :: Nat list) . (count x (tsort y)) = (count x y)\"\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/tree_sort_SortPermutes.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9207896758909757, "lm_q2_score": 0.7690802423634963, "lm_q1q2_score": 0.7081611471000367}}
{"text": "(* Title:      Demonic refinement algebra\n   Author:     Alasdair Armstrong, Victor B. F. Gomes, Georg Struth\n   Maintainer: Georg Struth <g.struth at sheffield.ac.uk>\n               Tjark Weber <tjark.weber at it.uu.se>\n*)\n\nsection \\<open>Demonic Refinement Algebras\\<close>\n\ntheory DRA\n  imports Kleene_Algebra \nbegin\n\ntext \\<open>\n  A demonic refinement algebra *DRA)~\\<^cite>\\<open>\"vonwright04refinement\"\\<close> is a Kleene algebra without right annihilation plus \n  an operation for possibly infinite iteration.\n\\<close>\nclass dra = kleene_algebra_zerol +\n  fixes strong_iteration :: \"'a \\<Rightarrow> 'a\" (\"_\\<^sup>\\<infinity>\" [101] 100)\n  assumes iteration_unfoldl [simp] : \"1 + x \\<cdot> x\\<^sup>\\<infinity> = x\\<^sup>\\<infinity>\"\n  and coinduction: \"y \\<le> z + x \\<cdot> y \\<longrightarrow> y \\<le> x\\<^sup>\\<infinity> \\<cdot> z\"\n  and isolation [simp]: \"x\\<^sup>\\<star> + x\\<^sup>\\<infinity> \\<cdot> 0 = x\\<^sup>\\<infinity>\"\nbegin\n\ntext \\<open>$\\top$ is an abort statement, defined as an infinite skip. It is the maximal element of any DRA.\\<close>\n\nabbreviation top_elem :: \"'a\" (\"\\<top>\") where \"\\<top> \\<equiv> 1\\<^sup>\\<infinity>\"\n\ntext \\<open>Simple/basic lemmas about the iteration operator\\<close>\n\nlemma iteration_refl: \"1 \\<le> x\\<^sup>\\<infinity>\"\n  using local.iteration_unfoldl local.order_prop by blast\n\nlemma iteration_1l: \"x \\<cdot> x\\<^sup>\\<infinity> \\<le> x\\<^sup>\\<infinity>\"\n  by (metis local.iteration_unfoldl local.join.sup.cobounded2)\n\nlemma top_ref: \"x \\<le> \\<top>\"\nproof -\n  have \"x \\<le> 1 + 1 \\<cdot> x\"\n    by simp\n  thus ?thesis\n    using local.coinduction by fastforce\nqed\n\nlemma it_ext: \"x \\<le> x\\<^sup>\\<infinity>\"\nproof -\n  have \"x \\<le> x \\<cdot> x\\<^sup>\\<infinity>\"\n    using iteration_refl local.mult_isol by fastforce\n  thus ?thesis\n    by (metis (full_types) local.isolation local.join.sup.coboundedI1 local.star_ext)\nqed\n\nlemma it_idem [simp]: \"(x\\<^sup>\\<infinity>)\\<^sup>\\<infinity> = x\\<^sup>\\<infinity>\"\n(*nitpick [expect=genuine]*)\noops\n\nlemma top_mult_annil [simp]: \"\\<top> \\<cdot> x = \\<top>\"\n  by (simp add: local.coinduction local.order.antisym top_ref)\n\nlemma top_add_annil [simp]: \"\\<top> + x = \\<top>\"\n  by (simp add: local.join.sup.absorb1 top_ref)\n\nlemma top_elim: \"x \\<cdot> y \\<le> x \\<cdot> \\<top>\"\n  by (simp add: local.mult_isol top_ref)\n\nlemma iteration_unfoldl_distl [simp]: \" y + y \\<cdot> x \\<cdot> x\\<^sup>\\<infinity> = y \\<cdot> x\\<^sup>\\<infinity>\"\n  by (metis distrib_left mult.assoc mult_oner iteration_unfoldl)\n\nlemma iteration_unfoldl_distr [simp]: \" y + x \\<cdot> x\\<^sup>\\<infinity> \\<cdot> y = x\\<^sup>\\<infinity> \\<cdot> y\"\n  by (metis distrib_right' mult_1_left iteration_unfoldl)\n\nlemma iteration_unfoldl' [simp]: \"z \\<cdot> y + z \\<cdot> x \\<cdot> x\\<^sup>\\<infinity> \\<cdot> y = z \\<cdot> x\\<^sup>\\<infinity> \\<cdot> y\"\n  by (metis iteration_unfoldl_distl local.distrib_right)\n\nlemma iteration_idem [simp]: \"x\\<^sup>\\<infinity> \\<cdot> x\\<^sup>\\<infinity> = x\\<^sup>\\<infinity>\"\nproof (rule order.antisym)\n  have \"x\\<^sup>\\<infinity> \\<cdot> x\\<^sup>\\<infinity> \\<le> 1 + x \\<cdot> x\\<^sup>\\<infinity> \\<cdot> x\\<^sup>\\<infinity>\"\n    by (metis add_assoc iteration_unfoldl_distr local.eq_refl local.iteration_unfoldl local.subdistl_eq mult_assoc)\n  thus \"x\\<^sup>\\<infinity> \\<cdot> x\\<^sup>\\<infinity> \\<le> x\\<^sup>\\<infinity>\"\n    using local.coinduction mult_assoc by fastforce\n  show \"x\\<^sup>\\<infinity> \\<le>  x\\<^sup>\\<infinity> \\<cdot> x\\<^sup>\\<infinity>\"\n    using local.coinduction by auto\nqed\n\nlemma iteration_induct: \"x \\<cdot> x\\<^sup>\\<infinity> \\<le> x\\<^sup>\\<infinity> \\<cdot> x\"\nproof -\n  have \"x + x \\<cdot> (x \\<cdot> x\\<^sup>\\<infinity>) = x \\<cdot> x\\<^sup>\\<infinity>\"\n    by (metis (no_types) local.distrib_left local.iteration_unfoldl local.mult_oner)\n  thus ?thesis\n    by (simp add: local.coinduction)\nqed\n\nlemma iteration_ref_star: \"x\\<^sup>\\<star> \\<le> x\\<^sup>\\<infinity>\"\n  by (simp add: local.star_inductl_one)\n\nlemma iteration_subdist: \"x\\<^sup>\\<infinity> \\<le> (x + y)\\<^sup>\\<infinity>\"\n  by (metis add_assoc' distrib_right' mult_oner coinduction join.sup_ge1 iteration_unfoldl)\n\nlemma iteration_iso: \"x \\<le> y \\<Longrightarrow> x\\<^sup>\\<infinity> \\<le> y\\<^sup>\\<infinity>\"\n  using iteration_subdist local.order_prop by auto\n \nlemma iteration_unfoldr [simp]: \"1 + x\\<^sup>\\<infinity> \\<cdot> x = x\\<^sup>\\<infinity>\"\n  by (metis add_0_left annil eq_refl isolation mult.assoc iteration_idem iteration_unfoldl iteration_unfoldl_distr star_denest star_one star_prod_unfold star_slide tc)\n\nlemma iteration_unfoldr_distl [simp]: \" y + y \\<cdot> x\\<^sup>\\<infinity> \\<cdot> x = y \\<cdot> x\\<^sup>\\<infinity>\"\n  by (metis distrib_left mult.assoc mult_oner iteration_unfoldr)\n\nlemma iteration_unfoldr_distr [simp]: \" y + x\\<^sup>\\<infinity> \\<cdot> x \\<cdot> y = x\\<^sup>\\<infinity> \\<cdot> y\"\n  by (metis iteration_unfoldl_distr iteration_unfoldr_distl)\n\nlemma iteration_unfold_eq: \"x\\<^sup>\\<infinity> \\<cdot> x = x \\<cdot> x\\<^sup>\\<infinity>\"\n  by (metis iteration_unfoldl_distr iteration_unfoldr_distl)\n  \nlemma iteration_unfoldr' [simp]: \"z \\<cdot> y + z \\<cdot> x\\<^sup>\\<infinity> \\<cdot> x \\<cdot> y = z \\<cdot> x\\<^sup>\\<infinity> \\<cdot> y\"\n  by (metis distrib_left mult.assoc iteration_unfoldr_distr)\n\nlemma iteration_double [simp]: \"(x\\<^sup>\\<infinity>)\\<^sup>\\<infinity> = \\<top>\"\n  by (simp add: iteration_iso iteration_refl order.eq_iff top_ref)\n\nlemma star_iteration [simp]: \"(x\\<^sup>\\<star>)\\<^sup>\\<infinity> = \\<top>\"\n  by (simp add: iteration_iso order.eq_iff top_ref)\n\nlemma iteration_star [simp]: \"(x\\<^sup>\\<infinity>)\\<^sup>\\<star> = x\\<^sup>\\<infinity>\"\n  by (metis (no_types) iteration_idem iteration_refl local.star_inductr_var_eq2 local.sup_id_star1)\n\nlemma iteration_star2 [simp]: \"x\\<^sup>\\<star> \\<cdot> x\\<^sup>\\<infinity> = x\\<^sup>\\<infinity>\"\nproof -\n  have f1: \"(x\\<^sup>\\<infinity>)\\<^sup>\\<star> \\<cdot> x\\<^sup>\\<star> = x\\<^sup>\\<infinity>\"\n    by (metis (no_types) it_ext iteration_induct iteration_star local.bubble_sort local.join.sup.absorb1)\n  have \"x\\<^sup>\\<infinity> = x\\<^sup>\\<infinity> \\<cdot> x\\<^sup>\\<infinity>\"\n    by simp\n  hence \"x\\<^sup>\\<star> \\<cdot> x\\<^sup>\\<infinity> = x\\<^sup>\\<star> \\<cdot> (x\\<^sup>\\<infinity>)\\<^sup>\\<star> \\<cdot> (x\\<^sup>\\<star> \\<cdot> (x\\<^sup>\\<infinity>)\\<^sup>\\<star>)\\<^sup>\\<star>\"\n    using f1 by (metis (no_types) iteration_star local.star_denest_var_4 mult_assoc)\n  thus ?thesis\n    using f1 by (metis (no_types) iteration_star local.star_denest_var_4 local.star_denest_var_8)\nqed\n\nlemma iteration_zero [simp]: \"0\\<^sup>\\<infinity> = 1\"\n  by (metis add_zeror annil iteration_unfoldl)\n\n\n\nlemma iteration_subdenest: \"x\\<^sup>\\<infinity> \\<cdot> y\\<^sup>\\<infinity> \\<le> (x + y)\\<^sup>\\<infinity>\"\n  by (metis add_commute iteration_idem iteration_subdist local.mult_isol_var)\n  \nlemma sup_id_top: \"1 \\<le> y \\<Longrightarrow> y \\<cdot> \\<top> = \\<top>\"\n  using order.eq_iff local.mult_isol_var top_ref by fastforce\n\nlemma iteration_top [simp]: \"x\\<^sup>\\<infinity> \\<cdot> \\<top> = \\<top>\"\n  by (simp add: iteration_refl sup_id_top)\n\ntext \\<open>Next, we prove some simulation laws for data refinement.\\<close>\n\nlemma iteration_sim: \"z \\<cdot> y \\<le> x \\<cdot> z \\<Longrightarrow> z \\<cdot> y\\<^sup>\\<infinity> \\<le> x\\<^sup>\\<infinity> \\<cdot> z\"\nproof -\n  assume assms: \"z \\<cdot> y \\<le> x \\<cdot> z\"\n  have \"z \\<cdot> y\\<^sup>\\<infinity> = z + z \\<cdot> y \\<cdot> y\\<^sup>\\<infinity>\"\n    by simp\n  also have \"... \\<le> z + x \\<cdot> z \\<cdot> y\\<^sup>\\<infinity>\"\n    by (metis assms add.commute add_iso mult_isor)\n  finally show \"z \\<cdot> y\\<^sup>\\<infinity> \\<le> x\\<^sup>\\<infinity> \\<cdot> z\"\n    by (simp add: local.coinduction mult_assoc)\nqed\n\ntext \\<open>Nitpick gives a counterexample to the dual simulation law.\\<close>\n\nlemma \"y \\<cdot> z \\<le> z \\<cdot> x \\<Longrightarrow> y\\<^sup>\\<infinity> \\<cdot> z \\<le> z \\<cdot> x\\<^sup>\\<infinity>\"\n(*nitpick [expect=genuine]*)\noops\n  \ntext \\<open>Next, we prove some sliding laws.\\<close>\n\nlemma iteration_slide_var: \"x \\<cdot> (y \\<cdot> x)\\<^sup>\\<infinity> \\<le> (x \\<cdot> y)\\<^sup>\\<infinity> \\<cdot> x\"\n  by (simp add: iteration_sim mult_assoc)\n\nlemma iteration_prod_unfold [simp]: \"1 + y \\<cdot> (x \\<cdot> y)\\<^sup>\\<infinity> \\<cdot> x = (y \\<cdot> x)\\<^sup>\\<infinity>\"\nproof (rule order.antisym)\n  have \"1 + y \\<cdot> (x \\<cdot> y)\\<^sup>\\<infinity> \\<cdot> x \\<le> 1 + (y \\<cdot> x)\\<^sup>\\<infinity> \\<cdot> y \\<cdot> x\"\n    using iteration_slide_var local.join.sup_mono local.mult_isor by blast\n  thus \"1 + y \\<cdot> (x \\<cdot> y)\\<^sup>\\<infinity> \\<cdot> x \\<le>  (y \\<cdot> x)\\<^sup>\\<infinity>\"\n    by (simp add: mult_assoc)\n  have \"(y \\<cdot> x)\\<^sup>\\<infinity> = 1 + y \\<cdot> x \\<cdot> (y \\<cdot> x)\\<^sup>\\<infinity>\"\n    by simp\n  thus \"(y \\<cdot> x)\\<^sup>\\<infinity> \\<le> 1 + y \\<cdot> (x \\<cdot> y)\\<^sup>\\<infinity> \\<cdot> x\"\n    by (metis iteration_sim local.eq_refl local.join.sup.mono local.mult_isol mult_assoc)\nqed\n\nlemma iteration_slide: \"x \\<cdot> (y \\<cdot> x)\\<^sup>\\<infinity> = (x \\<cdot> y)\\<^sup>\\<infinity> \\<cdot> x\"\n  by (metis iteration_prod_unfold iteration_unfoldl_distr distrib_left mult_1_right mult.assoc)\n\nlemma star_iteration_slide [simp]: \" y\\<^sup>\\<star> \\<cdot> (x\\<^sup>\\<star> \\<cdot> y)\\<^sup>\\<infinity> = (x\\<^sup>\\<star> \\<cdot> y)\\<^sup>\\<infinity>\"\n  by (metis iteration_star2 local.conway.dagger_unfoldl_distr local.join.sup.orderE local.mult_isor local.star_invol local.star_subdist local.star_trans_eq)\n\ntext \\<open>The following laws are called denesting laws.\\<close>\n\nlemma iteration_sub_denest: \"(x + y)\\<^sup>\\<infinity> \\<le> x\\<^sup>\\<infinity> \\<cdot> (y \\<cdot> x\\<^sup>\\<infinity>)\\<^sup>\\<infinity>\"\nproof -\n  have \"(x + y)\\<^sup>\\<infinity> = x \\<cdot> (x + y)\\<^sup>\\<infinity> + y \\<cdot> (x + y)\\<^sup>\\<infinity> + 1\"\n    by (metis add.commute distrib_right' iteration_unfoldl)\n  hence \"(x + y)\\<^sup>\\<infinity> \\<le> x\\<^sup>\\<infinity> \\<cdot> (y \\<cdot> (x + y)\\<^sup>\\<infinity> + 1)\"\n    by (metis add_assoc' join.sup_least join.sup_ge1 join.sup_ge2 coinduction)\n  moreover hence \"x\\<^sup>\\<infinity> \\<cdot> (y \\<cdot> (x + y)\\<^sup>\\<infinity> + 1) \\<le> x\\<^sup>\\<infinity> \\<cdot> (y \\<cdot> x\\<^sup>\\<infinity>)\\<^sup>\\<infinity>\"\n    by (metis add_iso mult.assoc mult_isol add.commute coinduction mult_oner mult_isol)\n  ultimately show ?thesis\n    using local.order_trans by blast\nqed\n\nlemma iteration_denest: \"(x + y)\\<^sup>\\<infinity> = x\\<^sup>\\<infinity> \\<cdot> (y \\<cdot> x\\<^sup>\\<infinity>)\\<^sup>\\<infinity>\"\nproof -\n  have \"x\\<^sup>\\<infinity> \\<cdot> (y \\<cdot> x\\<^sup>\\<infinity>)\\<^sup>\\<infinity> \\<le> x \\<cdot> x\\<^sup>\\<infinity> \\<cdot> (y \\<cdot> x\\<^sup>\\<infinity>)\\<^sup>\\<infinity> + y \\<cdot> x\\<^sup>\\<infinity> \\<cdot> (y \\<cdot> x\\<^sup>\\<infinity>)\\<^sup>\\<infinity> + 1\"\n    by (metis add.commute iteration_unfoldl_distr add_assoc' add.commute iteration_unfoldl order_refl)\n  thus ?thesis\n    by (metis add.commute iteration_sub_denest order.antisym coinduction distrib_right' iteration_sub_denest mult.assoc mult_oner order.antisym)\nqed\n(*\nend\n\nsublocale dra \\<subseteq> conway_zerol strong_iteration \n  apply (unfold_locales)\n  apply (simp add: iteration_denest iteration_slide)\n  apply simp\n  by (simp add: iteration_sim)\n\n\ncontext dra\nbegin\n*)\nlemma iteration_denest2 [simp]: \"y\\<^sup>\\<star> \\<cdot> x \\<cdot> (x + y)\\<^sup>\\<infinity> + y\\<^sup>\\<infinity> = (x + y)\\<^sup>\\<infinity>\"\nproof -\n  have \"(x + y)\\<^sup>\\<infinity> = y\\<^sup>\\<infinity> \\<cdot> x \\<cdot> (y\\<^sup>\\<infinity> \\<cdot> x)\\<^sup>\\<infinity> \\<cdot> y\\<^sup>\\<infinity> + y\\<^sup>\\<infinity>\"\n    by (metis add.commute iteration_denest iteration_slide iteration_unfoldl_distr)\n  also have \"... = y\\<^sup>\\<star> \\<cdot> x \\<cdot> (y\\<^sup>\\<infinity> \\<cdot> x)\\<^sup>\\<infinity> \\<cdot> y\\<^sup>\\<infinity> + y\\<^sup>\\<infinity> \\<cdot> 0 + y\\<^sup>\\<infinity>\"\n    by (metis isolation mult.assoc distrib_right' annil mult.assoc)\n  also have \"... = y\\<^sup>\\<star> \\<cdot> x \\<cdot> (y\\<^sup>\\<infinity> \\<cdot> x)\\<^sup>\\<infinity> \\<cdot> y\\<^sup>\\<infinity> + y\\<^sup>\\<infinity>\"\n    by (metis add.assoc distrib_left mult_1_right add_0_left mult_1_right)\n  finally show ?thesis\n    by (metis add.commute iteration_denest iteration_slide mult.assoc)\nqed\n\nlemma iteration_denest3: \"(y\\<^sup>\\<star> \\<cdot> x)\\<^sup>\\<infinity> \\<cdot> y\\<^sup>\\<infinity> = (x + y)\\<^sup>\\<infinity>\"\nproof (rule order.antisym)\n  have  \"(y\\<^sup>\\<star> \\<cdot> x)\\<^sup>\\<infinity> \\<cdot> y\\<^sup>\\<infinity> \\<le> (y\\<^sup>\\<infinity> \\<cdot> x)\\<^sup>\\<infinity> \\<cdot> y\\<^sup>\\<infinity>\"\n    by (simp add: iteration_iso iteration_ref_star local.mult_isor)\n  thus  \"(y\\<^sup>\\<star> \\<cdot> x)\\<^sup>\\<infinity> \\<cdot> y\\<^sup>\\<infinity> \\<le> (x + y)\\<^sup>\\<infinity>\"\n    by (metis iteration_denest iteration_slide local.join.sup_commute)\n  have \"(x + y)\\<^sup>\\<infinity> = y\\<^sup>\\<infinity> + y\\<^sup>\\<star> \\<cdot> x \\<cdot> (x + y)\\<^sup>\\<infinity>\"\n    by (metis iteration_denest2 local.join.sup_commute)\n  thus \"(x + y)\\<^sup>\\<infinity> \\<le> (y\\<^sup>\\<star> \\<cdot> x)\\<^sup>\\<infinity> \\<cdot> y\\<^sup>\\<infinity>\"\n    by (simp add: local.coinduction) \nqed\n\ntext \\<open>Now we prove separation laws for reasoning about distributed systems in the context of action systems.\\<close>\n\nlemma iteration_sep: \"y \\<cdot> x \\<le> x \\<cdot> y \\<Longrightarrow> (x + y)\\<^sup>\\<infinity> = x\\<^sup>\\<infinity> \\<cdot> y\\<^sup>\\<infinity>\"\nproof -\n  assume \"y \\<cdot> x \\<le> x \\<cdot> y\"\n  hence \"y\\<^sup>\\<star> \\<cdot> x \\<le> x\\<cdot>(x + y)\\<^sup>\\<star>\"\n    by (metis star_sim1 add.commute mult_isol order_trans star_subdist)\n  hence \"y\\<^sup>\\<star> \\<cdot> x \\<cdot> (x + y)\\<^sup>\\<infinity> + y\\<^sup>\\<infinity> \\<le> x \\<cdot> (x + y)\\<^sup>\\<infinity> + y\\<^sup>\\<infinity>\"\n    by (metis mult_isor mult.assoc iteration_star2 join.sup.mono eq_refl)\n  thus ?thesis\n    by (metis iteration_denest2 add.commute coinduction add.commute less_eq_def iteration_subdenest)\nqed\n\nlemma iteration_sim2: \"y \\<cdot> x \\<le> x \\<cdot> y \\<Longrightarrow> y\\<^sup>\\<infinity> \\<cdot> x\\<^sup>\\<infinity> \\<le> x\\<^sup>\\<infinity> \\<cdot> y\\<^sup>\\<infinity>\"\n  by (metis add.commute iteration_sep iteration_subdenest)\n\nlemma iteration_sep2: \"y \\<cdot> x \\<le> x \\<cdot> y\\<^sup>\\<star> \\<Longrightarrow> (x + y)\\<^sup>\\<infinity> = x\\<^sup>\\<infinity> \\<cdot> y\\<^sup>\\<infinity>\"\nproof - \n  assume \"y \\<cdot> x \\<le> x \\<cdot> y\\<^sup>\\<star>\"\n  hence \"y\\<^sup>\\<star> \\<cdot> (y\\<^sup>\\<star> \\<cdot> x)\\<^sup>\\<infinity> \\<cdot> y\\<^sup>\\<infinity> \\<le> x\\<^sup>\\<infinity> \\<cdot> y\\<^sup>\\<star> \\<cdot> y\\<^sup>\\<infinity>\"\n    by (metis mult.assoc mult_isor iteration_sim star_denest_var_2 star_sim1 star_slide_var star_trans_eq tc_eq)\n  moreover have \"x\\<^sup>\\<infinity> \\<cdot> y\\<^sup>\\<star> \\<cdot> y\\<^sup>\\<infinity> \\<le> x\\<^sup>\\<infinity> \\<cdot> y\\<^sup>\\<infinity>\"\n    by (metis eq_refl mult.assoc iteration_star2)\n  moreover have \"(y\\<^sup>\\<star> \\<cdot> x)\\<^sup>\\<infinity> \\<cdot> y\\<^sup>\\<infinity> \\<le> y\\<^sup>\\<star> \\<cdot> (y\\<^sup>\\<star> \\<cdot> x)\\<^sup>\\<infinity> \\<cdot> y\\<^sup>\\<infinity>\"\n    by (metis mult_isor mult_onel star_ref)\n  ultimately show ?thesis\n    by (metis order.antisym iteration_denest3 iteration_subdenest order_trans)\nqed\n\nlemma iteration_sep3: \"y \\<cdot> x \\<le> x \\<cdot> (x + y) \\<Longrightarrow> (x + y)\\<^sup>\\<infinity> = x\\<^sup>\\<infinity> \\<cdot> y\\<^sup>\\<infinity>\"\nproof -\n  assume \"y \\<cdot> x \\<le> x \\<cdot> (x + y)\"\n  hence \"y\\<^sup>\\<star> \\<cdot> x \\<le> x \\<cdot> (x + y)\\<^sup>\\<star>\"\n    by (metis star_sim1)\n  hence \"y\\<^sup>\\<star> \\<cdot> x \\<cdot> (x + y)\\<^sup>\\<infinity> + y\\<^sup>\\<infinity> \\<le> x \\<cdot> (x + y)\\<^sup>\\<star> \\<cdot> (x + y)\\<^sup>\\<infinity> + y\\<^sup>\\<infinity>\"\n    by (metis add_iso mult_isor)\n  hence \"(x + y)\\<^sup>\\<infinity> \\<le> x\\<^sup>\\<infinity> \\<cdot> y\\<^sup>\\<infinity>\"\n    by (metis mult.assoc iteration_denest2 iteration_star2 add.commute coinduction)\n  thus ?thesis\n    by (metis add.commute less_eq_def iteration_subdenest)\nqed\n\nlemma iteration_sep4: \"y \\<cdot> 0 = 0 \\<Longrightarrow> z \\<cdot> x = 0 \\<Longrightarrow> y \\<cdot> x \\<le> (x + z) \\<cdot> y\\<^sup>\\<star> \\<Longrightarrow> (x + y + z)\\<^sup>\\<infinity> = x\\<^sup>\\<infinity> \\<cdot> (y + z)\\<^sup>\\<infinity>\"\nproof -\n  assume assms: \"y \\<cdot> 0 = 0\" \"z \\<cdot> x = 0\" \"y \\<cdot> x \\<le> (x + z) \\<cdot> y\\<^sup>\\<star>\"\n  have \"y \\<cdot> y\\<^sup>\\<star> \\<cdot> z \\<le> y\\<^sup>\\<star> \\<cdot> z \\<cdot> y\\<^sup>\\<star>\"\n    by (metis mult_isor star_1l mult_oner order_trans star_plus_one subdistl)\n  have \"y\\<^sup>\\<star> \\<cdot> z \\<cdot> x \\<le> x \\<cdot> y\\<^sup>\\<star> \\<cdot> z\"\n    by (metis join.bot_least assms(1) assms(2) independence1 mult.assoc)\n  have \"y \\<cdot> (x + y\\<^sup>\\<star> \\<cdot> z) \\<le> (x + z) \\<cdot> y\\<^sup>\\<star> + y \\<cdot> y\\<^sup>\\<star> \\<cdot> z\"\n    by (metis assms(3) distrib_left mult.assoc add_iso)\n  also have \"... \\<le> (x + y\\<^sup>\\<star> \\<cdot> z) \\<cdot> y\\<^sup>\\<star> + y \\<cdot> y\\<^sup>\\<star> \\<cdot> z\" \n    by (metis star_ref join.sup.mono eq_refl mult_1_left mult_isor)\n  also have \"... \\<le> (x + y\\<^sup>\\<star> \\<cdot> z) \\<cdot> y\\<^sup>\\<star> + y\\<^sup>\\<star> \\<cdot> z  \\<cdot> y\\<^sup>\\<star>\" using \\<open>y \\<cdot> y\\<^sup>\\<star> \\<cdot> z \\<le> y\\<^sup>\\<star> \\<cdot> z \\<cdot> y\\<^sup>\\<star>\\<close>\n    by (metis add.commute add_iso)\n  finally have \"y \\<cdot> (x + y\\<^sup>\\<star> \\<cdot> z) \\<le> (x + y\\<^sup>\\<star> \\<cdot> z) \\<cdot> y\\<^sup>\\<star>\"\n    by (metis add.commute add_idem' add.left_commute distrib_right)\n  moreover have \"(x + y + z)\\<^sup>\\<infinity> \\<le> (x + y + y\\<^sup>\\<star> \\<cdot> z)\\<^sup>\\<infinity>\"\n    by (metis star_ref join.sup.mono eq_refl mult_1_left mult_isor iteration_iso)  \n  moreover have \"... = (x + y\\<^sup>\\<star> \\<cdot> z)\\<^sup>\\<infinity> \\<cdot> y\\<^sup>\\<infinity>\"\n    by (metis add_commute calculation(1) iteration_sep2 local.add_left_comm)\n  moreover have \"... = x\\<^sup>\\<infinity> \\<cdot> (y\\<^sup>\\<star> \\<cdot> z)\\<^sup>\\<infinity> \\<cdot> y\\<^sup>\\<infinity>\" using \\<open>y\\<^sup>\\<star> \\<cdot> z \\<cdot> x \\<le> x \\<cdot> y\\<^sup>\\<star> \\<cdot> z\\<close>\n    by (metis iteration_sep mult.assoc)\n  ultimately have \"(x + y + z)\\<^sup>\\<infinity> \\<le> x\\<^sup>\\<infinity> \\<cdot> (y + z)\\<^sup>\\<infinity>\"\n    by (metis add.commute mult.assoc iteration_denest3)\n  thus ?thesis\n    by (metis add.commute add.left_commute less_eq_def iteration_subdenest)\nqed\n\ntext \\<open>Finally, we prove some blocking laws.\\<close>\n\ntext \\<open>Nitpick refutes the next lemma.\\<close>\n\nlemma \"x \\<cdot> y = 0 \\<Longrightarrow> x\\<^sup>\\<infinity> \\<cdot> y = y\"\n(*nitpick*)\noops\n\nlemma iteration_idep: \"x \\<cdot> y = 0 \\<Longrightarrow> x \\<cdot> y\\<^sup>\\<infinity> = x\"\n  by (metis add_zeror annil iteration_unfoldl_distl)\n\ntext \\<open>Nitpick refutes the next lemma.\\<close>\n\nlemma \"y \\<cdot> w \\<le> x \\<cdot> y + z \\<Longrightarrow> y \\<cdot> w\\<^sup>\\<infinity> \\<le> x\\<^sup>\\<infinity> \\<cdot> z\"\n(*nitpick [expect=genuine]*)\noops\n\ntext \\<open>At the end of this file, we consider a data refinement example from von Wright~\\<^cite>\\<open>\"Wright02\"\\<close>.\\<close>\n\nlemma data_refinement:\n  assumes \"s' \\<le> s \\<cdot> z\" and \"z \\<cdot> e' \\<le> e\" and \"z \\<cdot> a' \\<le> a \\<cdot> z\" and \"z \\<cdot> b \\<le> z\" and \"b\\<^sup>\\<infinity> = b\\<^sup>\\<star>\"\n  shows \"s' \\<cdot> (a' + b)\\<^sup>\\<infinity> \\<cdot> e' \\<le> s \\<cdot> a\\<^sup>\\<infinity> \\<cdot> e\"\nproof -\n  have \"z \\<cdot> b\\<^sup>\\<star> \\<le> z\"\n    by (metis assms(4) star_inductr_var)\n  have \"(z \\<cdot> a') \\<cdot> b\\<^sup>\\<star> \\<le> (a \\<cdot> z) \\<cdot> b\\<^sup>\\<star>\"\n    by (metis assms(3) mult.assoc mult_isor)\n  hence \"z \\<cdot> (a' \\<cdot> b\\<^sup>\\<star>)\\<^sup>\\<infinity> \\<le>  a\\<^sup>\\<infinity> \\<cdot> z\" using \\<open>z \\<cdot> b\\<^sup>\\<star> \\<le> z\\<close>\n    by (metis mult.assoc mult_isol order_trans iteration_sim mult.assoc)\n  have \"s' \\<cdot> (a' + b)\\<^sup>\\<infinity> \\<cdot> e' \\<le> s' \\<cdot> b\\<^sup>\\<star> \\<cdot> (a' \\<cdot> b\\<^sup>\\<star>)\\<^sup>\\<infinity> \\<cdot> e'\"\n    by (metis add.commute assms(5) eq_refl iteration_denest mult.assoc)\n  also have \"... \\<le> s \\<cdot> z \\<cdot> b\\<^sup>\\<star> \\<cdot> (a' \\<cdot> b\\<^sup>\\<star>)\\<^sup>\\<infinity> \\<cdot> e'\"\n    by (metis assms(1) mult_isor)\n  also have \"... \\<le> s \\<cdot> z \\<cdot> (a' \\<cdot> b\\<^sup>\\<star>)\\<^sup>\\<infinity> \\<cdot> e'\" using \\<open>z \\<cdot> b\\<^sup>\\<star> \\<le> z\\<close>\n    by (metis mult.assoc mult_isol mult_isor)\n  also have \"... \\<le> s \\<cdot> a\\<^sup>\\<infinity> \\<cdot> z \\<cdot> e'\" using \\<open>z \\<cdot> (a' \\<cdot> b\\<^sup>\\<star>)\\<^sup>\\<infinity> \\<le>  a\\<^sup>\\<infinity> \\<cdot> z\\<close>\n    by (metis mult.assoc mult_isol mult_isor)\n  finally show ?thesis\n    by (metis assms(2) mult.assoc mult_isol mult.assoc mult_isol order_trans)\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/Kleene_Algebra/DRA.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8872045966995027, "lm_q2_score": 0.7981867825403177, "lm_q1q2_score": 0.7081549824945562}}
{"text": "theory PermEnv\n  imports Main\nbegin\n  \n    (* \n      ####################################\n        P1. permission definitions\n      ####################################\n    *)  \n  \ndatatype p_perm = NoPerm | UsePerm | OwnPerm  \n\ndatatype ext_perm = NoEP | DiffEP | OwnEP    \n  \nfun leq_perm where\n  \"leq_perm UsePerm NoPerm = False\"\n| \"leq_perm OwnPerm NoPerm = False\"\n| \"leq_perm OwnPerm UsePerm = False\"\n| \"leq_perm p1 p2 = True\"\n \nfun minus_ep where\n  \"minus_ep NoPerm p = NoPerm\"\n| \"minus_ep UsePerm OwnEP = NoPerm\"\n| \"minus_ep UsePerm p = UsePerm\"\n| \"minus_ep OwnPerm OwnEP = NoPerm\"\n| \"minus_ep OwnPerm DiffEP = UsePerm\"\n| \"minus_ep OwnPerm p = OwnPerm\"\n  \nfun union_ep where\n  \"union_ep OwnPerm p = OwnPerm\"\n| \"union_ep UsePerm OwnEP = OwnPerm\"\n| \"union_ep UsePerm DiffEP = OwnPerm\"\n| \"union_ep UsePerm p = UsePerm\"\n| \"union_ep NoPerm OwnEP = OwnPerm\"\n| \"union_ep NoPerm DiffEP = UsePerm\"\n| \"union_ep NoPerm NoEP = NoPerm\"\n  \nfun union_perm where\n  \"union_perm OwnPerm p = OwnPerm\"\n| \"union_perm p OwnPerm = OwnPerm\"\n| \"union_perm NoPerm NoPerm = NoPerm\"\n| \"union_perm p1 p2 = UsePerm\"      \n  \n    (* \n      ####################################\n        P2.\n      ####################################\n    *)    \n  \ntype_synonym perm_use_env = \"string \\<Rightarrow> p_perm\"  \n\ntype_synonym ep_use_env = \"string \\<Rightarrow> ext_perm\"  \n  \ndefinition empty_use_env where\n  \"empty_use_env x = NoPerm\"\n  \ndefinition add_use_env where\n  \"add_use_env env x p = (\\<lambda> x'. if x = x' then p else env x')\"\n\ndefinition rem_use_env where\n  \"rem_use_env env x = (\\<lambda> x'. if x = x' then NoPerm else env x')\"  \n  \ndefinition leq_use_env where\n  \"leq_use_env env1 env2 = (\\<forall> x. leq_perm (env1 x) (env2 x))\"  \n\n   (* shift related functions *)\n  \ndefinition one_use_env where\n  \"one_use_env x r = (\\<lambda> x'. if x = x' then r else NoPerm)\"    \n  \nfun neg_perm where\n  \"neg_perm OwnPerm = OwnEP\"\n| \"neg_perm p = NoEP\"\n  \ndefinition neg_use_env where\n  \"neg_use_env env = (\\<lambda> x. neg_perm (env x))\"\n  \ndefinition empty_ep_use_env where\n  \"empty_ep_use_env x = NoEP\"\n  \ndefinition minus_use_env where\n  \"minus_use_env env1 env2 = (\\<lambda> x. minus_ep (env1 x) (env2 x))\"  \n  \ndefinition diff_use_env where\n  \"diff_use_env env1 env2 = minus_use_env env1 (neg_use_env env2)\"  \n  \ndefinition comp_use_env where\n  \"comp_use_env r_s1 r_s2 = (\\<lambda> x. union_perm (r_s1 x) (r_s2 x))\"  \n\ndefinition mini_disj_use_env where     \n  \"mini_disj_use_env r_s r_ex = (\\<forall> x. r_s x = OwnPerm \\<longrightarrow> r_ex x = NoPerm)\"    \n  \ndefinition disj_use_env where\n  \"disj_use_env r_s1 r_s2 = (mini_disj_use_env r_s1 r_s2 \\<and> mini_disj_use_env r_s2 r_s1)\"\n \ndefinition weak_use_env where\n  \"weak_use_env r_s = (\\<forall> x. r_s x \\<noteq> OwnPerm)\"   \n \ndefinition is_own where\n  \"is_own r = (r = OwnPerm)\"  \n  \n    (* #### no perm lemmas #### *)\n    \n    (* - none lemmas *)\n  \nlemma leq_use_none: \"\\<lbrakk> leq_use_env r_x r_s; r_s x = NoPerm \\<rbrakk> \\<Longrightarrow> r_x x = NoPerm\"    \n  apply (simp add: leq_use_env_def)\n  apply (erule_tac x=\"x\" in allE)\n  apply (case_tac \"r_x x\")\n    apply (auto)\n  done  \n  \nlemma add_use_none_rev: \"\\<lbrakk> r_s x = NoPerm ; x \\<noteq> y \\<rbrakk> \\<Longrightarrow> add_use_env r_s y r x = NoPerm\"\n  apply (simp add: add_use_env_def)\n  done    \n\nlemma minus_use_none_infer: \"\\<lbrakk> minus_use_env r_s r_ex x = NoPerm; r_s x \\<noteq> NoPerm \\<rbrakk> \\<Longrightarrow> minus_use_env r_x r_ex x = NoPerm\"\n  apply (simp add: minus_use_env_def)\n  apply (case_tac \"r_s x\")\n    apply (auto)\n   apply (case_tac \"r_ex x\")\n     apply (auto)\n   apply (case_tac \"r_x x\")\n     apply (auto)\n  apply (case_tac \"r_ex x\")\n    apply (auto)\n  apply (case_tac \"r_x x\")\n    apply (auto)\n  done\n\nlemma diff_use_none_infer: \"\\<lbrakk> r_x x = OwnPerm; diff_use_env r_x r_ex x \\<noteq> OwnPerm \\<rbrakk> \\<Longrightarrow> diff_use_env r_s r_ex x = NoPerm\"    \n  apply (simp add: diff_use_env_def)\n  apply (simp add: neg_use_env_def)\n  apply (simp add: minus_use_env_def)\n  apply (case_tac \"r_ex x\")\n    apply (auto)\n  apply (case_tac \"r_s x\")\n    apply (auto)\n  done\n\nlemma diff_use_none: \"\\<lbrakk> r_x x \\<noteq> NoPerm; diff_use_env r_x r_ex x = NoPerm \\<rbrakk> \\<Longrightarrow> diff_use_env r_s r_ex x = NoPerm\"    \n  apply (simp add: diff_use_env_def)\n  apply (simp add: neg_use_env_def)\n  apply (simp add: minus_use_env_def)\n  apply (case_tac \"r_x x\")\n    apply (auto)\n   apply (case_tac \"r_s x\")\n     apply (auto)\n   apply (case_tac \"r_ex x\")\n     apply (auto)\n  apply (case_tac \"r_ex x\")\n    apply (auto)\n  apply (case_tac \"r_s x\")\n    apply (auto)\n  done\n    \nlemma diff_use_none_ex: \"\\<lbrakk> r_ex x = OwnPerm \\<rbrakk> \\<Longrightarrow> diff_use_env r_s r_ex x = NoPerm\"    \n  apply (simp add: diff_use_env_def)\n  apply (simp add: neg_use_env_def)\n  apply (simp add: minus_use_env_def)\n  apply (case_tac \"r_s x\")\n    apply (auto)\n  done        \n    \nlemma comp_use_none: \"\\<lbrakk> r_sa x = NoPerm; r_sb x = NoPerm \\<rbrakk> \\<Longrightarrow> comp_use_env r_sa r_sb x = NoPerm\"    \n  apply (simp add: comp_use_env_def)\n  done       \n    \nlemma comp_use_none_both: \"\\<lbrakk> comp_use_env r_sa r_sb x = NoPerm \\<rbrakk> \\<Longrightarrow> r_sa x = NoPerm \\<and> r_sb x = NoPerm\"    \n  apply (simp add: comp_use_env_def)\n  apply (case_tac \"r_sa x\")\n    apply (auto)\n   apply (case_tac \"r_sb x\")\n     apply (auto)\n  apply (case_tac \"r_sb x\")\n    apply (auto)\n  done  \n    \n    (* - no own lemmas *)\n  \nlemma leq_use_no_own: \"\\<lbrakk> r_s x \\<noteq> OwnPerm; leq_use_env r_x r_s \\<rbrakk> \\<Longrightarrow> r_x x \\<noteq> OwnPerm\"\n  apply (simp add: leq_use_env_def)\n  apply (erule_tac x=\"x\" in allE)\n  apply (case_tac \"r_s x\")\n    apply (auto)\n  done\n    \nlemma comp_use_no_own_both: \"\\<lbrakk> comp_use_env r_sa r_sb x \\<noteq> OwnPerm \\<rbrakk> \\<Longrightarrow> r_sa x \\<noteq> OwnPerm \\<and> r_sb x \\<noteq> OwnPerm\"   \n  apply (simp add: comp_use_env_def)\n  apply (auto)\n  apply (case_tac \"r_sa x\")\n    apply (auto)\n  done    \n    \nlemma diff_use_no_own: \"\\<lbrakk> diff_use_env r_s r_ex x \\<noteq> NoPerm \\<rbrakk> \\<Longrightarrow> r_ex x \\<noteq> OwnPerm\"    \n  apply (simp add: diff_use_env_def)\n  apply (simp add: minus_use_env_def)\n  apply (simp add: neg_use_env_def)\n  apply (case_tac \"r_ex x\")\n    apply (auto)\n  apply (case_tac \"r_s x\")\n    apply (auto)\n  done\n    \n    (* - own lemmas *)\n\nlemma leq_use_own: \"\\<lbrakk> r_x x = OwnPerm; leq_use_env r_x r_s \\<rbrakk> \\<Longrightarrow> r_s x = OwnPerm\"\n  apply (simp add: leq_use_env_def)\n  apply (erule_tac x=\"x\" in allE)\n  apply (auto)\n  apply (case_tac \"r_s x\")\n    apply (auto)\n  done    \n \nlemma diff_use_own: \"\\<lbrakk> leq_use_env (diff_use_env r_x r_ex) r_s; r_x x \\<noteq> NoPerm; r_s x = NoPerm \\<rbrakk> \\<Longrightarrow> r_ex x = OwnPerm\"    \n  apply (simp add: diff_use_env_def)\n  apply (simp add: minus_use_env_def)\n  apply (simp add: neg_use_env_def)\n  apply (simp add: leq_use_env_def)\n  apply (erule_tac x=\"x\" in allE)\n  apply (case_tac \"r_x x\")\n    apply (auto)\n   apply (case_tac \"r_ex x\")\n     apply (auto)\n  apply (case_tac \"r_ex x\")\n    apply (auto)\n  done    \n    \n   (* - eq lemmas *) \n    \nlemma diff_use_eq: \"\\<lbrakk> r_x x \\<noteq> OwnPerm \\<rbrakk> \\<Longrightarrow> diff_use_env r_s r_x x = r_s x\"  \n  apply (simp add: diff_use_env_def)\n  apply (simp add: minus_use_env_def)\n  apply (simp add: neg_use_env_def)\n  apply (case_tac \"r_x x\")\n    apply (auto)\n   apply (case_tac \"r_s x\")\n     apply (auto)\n  apply (case_tac \"r_s x\")\n    apply (auto)\n  done\n\n    (* - fundamental lemmas *)\n\nlemma spec_leq_perm: \"\\<lbrakk> leq_use_env r_x r_s \\<rbrakk> \\<Longrightarrow> leq_perm (r_x x) (r_s x)\"    \n  apply (simp add: leq_use_env_def)\n  done    \n\n    (* - leq lemmas *)\n    \nlemma diff_use_leq: \"\\<lbrakk> r_ex x \\<noteq> OwnPerm; leq_use_env (diff_use_env r_x r_ex) r_s \\<rbrakk> \\<Longrightarrow> leq_perm (r_x x) (r_s x)\"\n  apply (simp add: leq_use_env_def)\n  apply (erule_tac x=\"x\" in allE)\n  apply (simp add: diff_use_env_def)\n  apply (simp add: minus_use_env_def)\n  apply (simp add: neg_use_env_def)\n  apply (case_tac \"r_x x\")\n    apply (auto)\n   apply (case_tac \"r_ex x\")\n     apply (auto)\n  apply (case_tac \"r_ex x\")\n    apply (auto)\n  done\n\nlemma diff_use_leq2: \"\\<lbrakk> leq_use_env r_x (diff_use_env r_s r_ex); r_ex x \\<noteq> OwnPerm \\<rbrakk> \\<Longrightarrow> leq_perm (r_x x) (r_s x)\"    \n  apply (simp add: leq_use_env_def)\n  apply (erule_tac x=\"x\" in allE)\n  apply (simp add: diff_use_env_def)\n  apply (simp add: minus_use_env_def)\n  apply (simp add: neg_use_env_def)\n  apply (case_tac \"r_ex x\")\n    apply (auto)\n   apply (case_tac \"r_s x\")\n     apply (auto)\n  apply (case_tac \"r_s x\")\n    apply (auto)\n  done\n    \nend\n  ", "meta": {"author": "dcco", "repo": "perm_lang_ax1", "sha": "5742edc2c5db417002ed6b8acd159c522b3e6e38", "save_path": "github-repos/isabelle/dcco-perm_lang_ax1", "path": "github-repos/isabelle/dcco-perm_lang_ax1/perm_lang_ax1-5742edc2c5db417002ed6b8acd159c522b3e6e38/perm_unsafe_lift/PermEnv.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8872045937171068, "lm_q2_score": 0.7981867777396211, "lm_q1q2_score": 0.7081549758548472}}
{"text": "theory Chap5 imports Main\nbegin   \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 simp: surj_def)\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 simp: 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 ?thesis 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 \\<in> f a \\<longleftrightarrow> a \\<notin> f a\" by blast\n  thus \"False\" by blast\nqed\n\nlemma \"R\"\nproof cases\n  assume P\n  show R sorry\nnext\n  assume \"\\<not>P\"\n  show R sorry\nqed\n\nlemma assumes \"P \\<or> Q\" shows R\n  using assms\nproof\n  assume P\n  show R sorry\nnext\n  assume Q\n  show R sorry\nqed\n\nlemma \"P \\<longleftrightarrow> Q\"\nproof\n  assume P show Q sorry\nnext\n  assume Q show P sorry\nqed\n\nlemma \"P\"\nproof (rule ccontr)\n  assume \"\\<not>P\"\n  show \"False\" sorry\nqed\n\nlemma \"\\<forall>x. P x\"\nproof\n  fix y\n  show \"P y\" sorry\nqed\n\nlemma \"(A::'a set) = B\"\nproof\n  show \"A\\<le>B\" sorry\nnext\n  show \"B\\<le>A\" sorry\nqed\n\nlemma \"(A::'a set) \\<le> B\"\nproof\n  fix x\n  assume \"x \\<in> A\"\n  show \"x \\<in> B\" sorry\nqed\n\nlemma \"formula\\<^sub>1 \\<longleftrightarrow> formula\\<^sub>2\" (is \"?L \\<longleftrightarrow> ?R\")\nproof\n  assume \"?L\"\n  show \"?R\" sorry\nnext\n  assume \"?R\"\n  show \"?L\" sorry\nqed\n\nlemma \"\\<forall>(x::nat). x \\<ge> 0\"\nproof\n  fix x :: nat\n  have \"x \\<ge> 0\" sorry\n  from `x \\<ge> 0` show \"x \\<ge> 0\" sorry\nqed\n\nlemma P\nproof -\n  have P1 sorry\n  moreover have P2 sorry\n  ultimately have P3 sorry\n  thus P sorry\nqed\n\nlemma fixes a b :: int assumes \"b dvd (a+b)\" 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\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\" and \"A x y\"\nshows \"T x y\"\nproof (rule disjE[of \"T x y\" \"T y x\"])\n  show \"T x y \\<or> T y x\" using T by blast\nnext\n  show \"T x y \\<Longrightarrow> T x y\" by assumption\nnext\n  assume 1: \"T y x\"\n  hence \"A y x\" using TA by blast\n  hence \"x = y\" using A assms by blast\n  thus \"T x y\" using 1 by blast\nqed\n\nlemma \"\\<exists>ys zs. xs = ys@zs \\<and> (length ys = length zs \\<or> length ys = length zs + 1)\"\nproof -\n  obtain k r where f1: \"length xs = 2*k + r\" and f2: \"r = 0 \\<or> r = 1\" \n    by (metis bot_nat_0.not_eq_extremum mod2_gr_0 mult_div_mod_eq)\n  let ?ys = \"take (k+r) xs\" and ?zs = \"drop (k+r) xs\"\n  have \"length ?ys = k+r\" and \"length ?zs = k\" using f1 by auto\n  hence \"length ?ys = length ?zs \\<or> length ?ys = length ?zs + 1\" using f2 by simp\n  moreover have \"xs = ?ys@?zs\" by simp\n  ultimately show ?thesis by blast\nqed\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\nlemma \"length (tl xs) = length xs - 1\"\nproof (cases xs)\n  case Nil\n  then show ?thesis by simp\nnext\n  case (Cons a list)\n  then show ?thesis 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\nlemma \"\\<Sum>{0..n::nat} = n*(n+1) div 2\" (is \"?P n\")\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\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 n \\<Longrightarrow> evn n\"\nproof (induction rule: ev.induct)\n  case ev0\n  then show ?case by simp\nnext\n  case evSS\n  thus ?case by simp\nqed\n\nlemma \"ev n \\<Longrightarrow> evn n\"\nproof (induction rule: ev.induct)\n  case ev0\n  then show ?case by simp\nnext\n  case (evSS n)\n  thm evSS.IH\n  thm evSS.hyps\n  thm evSS.prems\n  then have \"evn (Suc (Suc n)) = evn n\" by simp\n  thus ?case using \\<open>evn n\\<close> by blast\nqed\n\nlemma \"ev n \\<Longrightarrow> ev (n-2)\"\nproof -\n  assume \"ev n\"\n  thus \"ev (n-2)\"\n  proof cases\n    case ev0\n    then show ?thesis by (simp add: ev.ev0)\n  next\n    case (evSS n)\n    then show ?thesis by (simp add: ev.evSS)\n  qed\nqed\n\nlemma \"ev (Suc 0) \\<Longrightarrow> P\"\nproof -\n  assume \"ev (Suc 0)\" then show \"P\" by cases\nqed\n\nlemma \"\\<not>ev (Suc (Suc (Suc 0)))\"\nproof\n  assume \"ev (Suc (Suc (Suc 0)))\"\n  from this have \"ev (Suc 0)\" by cases\n  thus False by cases\nqed\n\nfun P :: \"nat \\<Rightarrow> bool\" where\n\"P (Suc n) = (\\<not>ev n)\"\n| \"P _ = True\"\n\nlemma \"ev n \\<Longrightarrow> P n \\<Longrightarrow> \\<not> ev (Suc n)\"\nproof (cases n)\n  case 0\n  then show ?thesis sorry\nnext\n  case (Suc nat)\n  then show ?thesis sorry\nqed\n   \nlemma \"ev (Suc m) \\<Longrightarrow>\nP 0 \\<Longrightarrow> (\\<And>n. ev n \\<Longrightarrow> P n \\<Longrightarrow> P (Suc (Suc n))) \\<Longrightarrow> P (Suc m)\"\n  apply simp\n  oops\n\nlemma \"ev (Suc m) \\<Longrightarrow> \\<not>ev m\"\n  thm ev.induct[where x=\"Suc m\" and P=P]\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 \n  assumes \"ev (Suc (Suc n))\"\n  shows \"ev n\"\n  using assms\nproof cases\n  assume \"ev n\" thus \"ev n\" by blast\nqed\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\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 \"iter r n x y \\<Longrightarrow> star r x y\"\nproof (induction rule: iter.induct)\n  case (1 x)\n  show ?case using refl by force\nnext\n  case (2 n y z x)\n  from 2(2) 2(3) show ?case using step by force\nqed\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  hence False by simp\n  thus ?case by blast\nnext\n  case (Cons a xs)\n  show ?case\n  proof (cases \"x = a\")\n    case True\n    hence \"a # xs = [] @ x # xs\" by simp\n    moreover have \"x \\<notin> elems []\" by simp\n    ultimately show ?thesis by blast\n  next\n    case False\n    then obtain ys zs where \"xs = ys @ x # zs\" and 1: \"x \\<notin> elems ys\"\n      using Cons by auto\n    hence \"a # xs = (a#ys) @ x # zs\" by simp\n    moreover have \"x \\<notin> elems (a#ys)\" using False 1 by simp\n    ultimately show ?thesis by blast\n  qed\nqed\n\ndatatype alphabet = a | b\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\nfun balanced :: \"nat \\<Rightarrow> alphabet list \\<Rightarrow> bool\" where\n\"balanced 0 [] = True\"\n| \"balanced (Suc n) [] = False\"\n| \"balanced n (a#xs) = balanced (Suc n) xs\"\n| \"balanced 0 (b#xs) = False\"\n| \"balanced (Suc n) (b#xs) = balanced n xs\"\n\nlemma balanced1: \"S (replicate n a) \\<Longrightarrow> n > 0 \\<Longrightarrow> False\"\nproof (induction \"replicate n a\" arbitrary: n rule: S.induct)\n  case 1\n  then show ?case by simp\nnext\n  case (2 w)\n  then show ?case\n    by (metis alphabet.distinct(1) append_is_Nil_conv bot_nat_0.not_eq_extremum last.simps last_replicate last_snoc list.distinct(1))\nnext\n  case (3 v w)\n  then obtain n' n'' where f1: \"v = replicate n' a\" and f2: \"w = replicate n'' a\"\n    by (metis map_eq_append_conv map_replicate_const map_replicate_trivial)\n  have \"n' = 0 \\<Longrightarrow> n'' = 0 \\<Longrightarrow> False\" using 3 f1 by simp\n  hence \"n' > 0 \\<or> n'' > 0\" by blast\n  then show ?case using 3 f1 f2 by blast\nqed\n\nlemma balanced6:\n  assumes a1: \"v \\<noteq> []\" and a2: \"S v\" and a3: \"S w\" \n  and a4: \"v @ w = replicate n a @ xs\"\n  shows \"\\<exists>ys. v = replicate n a @ ys\"\nproof -\n  have \"\\<not>(\\<exists>v'. v@v' = replicate n a)\"\n  proof\n    assume \"\\<exists>v'. v @ v' = replicate n a\"\n    then obtain n' where f1: \"v = replicate n' a\" and f2: \"n' > 0\"\n      by (metis a1 gr_zeroI list.simps(8) list.size(3) map_eq_append_conv map_replicate_const map_replicate_trivial)\n    have \"S v \\<Longrightarrow> False\" using f1 balanced1 f2 by blast\n    then show \"False\" using a2 by simp\n  qed\n  thus ?thesis\n    by (meson a4 append_eq_append_conv2)\nqed\n\nlemma balanced2: \"S (replicate n a @ xs) \\<Longrightarrow> S (replicate (Suc n) a @ b # xs)\"\nproof (induction \"replicate n a @ xs\" arbitrary: n xs rule: S.induct)\n  case 1\n  then show ?case using S.intros(1) S.intros(2) by force\nnext\n  case (2 w)\n  then show ?case\n  proof (cases n)\n    assume f1: \"n = 0\"\n    hence \"S xs\" using 2 S.intros by force\n    moreover have \"S [a, b]\" using S.intros by force\n    ultimately have \"S ([a, b] @ xs)\" using S.intros 2 by force\n    hence \"S (replicate (Suc 0) a @ b # xs)\" by simp\n    thus ?thesis using f1 by simp\n  next\n    case (Suc nat)\n    then obtain xs' where f1: \"w = replicate nat a @ xs'\" using 2(3)\n      by (metis alphabet.distinct(1) append.right_neutral append_Cons butlast_append list.sel(3) replicate_Suc replicate_append_same snoc_eq_iff_butlast) \n    with 2(2) have \"S (replicate (Suc nat) a @ b # xs')\" by simp\n    moreover have \"xs = xs'@[b]\" using 2(3) f1 Suc by simp\n    ultimately show ?thesis using Suc S.intros by force\n  qed\nnext\n  case (3 v w)\n  show ?case\n  proof (cases v)\n    case Nil\n    then show ?thesis using 3 S.intros by force\n  next\n    case Cons\n    with 3(1,3,5) obtain ys where f1: \"v = replicate n a @ ys\"\n      using balanced6 by blast\n    hence \"S (replicate (Suc n) a @ b # ys)\" using 3 by blast\n    moreover have \"replicate (Suc n) a @ b # xs = replicate (Suc n) a @ b # ys @ w\"\n      using 3 f1 by force\n    ultimately show ?thesis using 3 by (metis S.intros(3) append.assoc append_Cons)\n  qed\nqed\n\nlemma balanced3: \"balanced n w \\<Longrightarrow> S (replicate n a @ w)\"\nproof (induction n w rule: balanced.induct)\n  case 1\n  then show ?case\n    by (simp add: S.intros(1))\nnext\n  case (2 n)\n  then show ?case by simp\nnext\n  case (3 n xs)\n  hence \"balanced (Suc n) xs\" by simp\n  hence \"S (replicate (Suc n) a @ xs)\" using 3 by simp\n  then show ?case by (simp add: replicate_app_Cons_same)\nnext                                                       \n  case (4 xs)\n  then show ?case by simp\nnext\n  case (5 n xs)\n  hence \"balanced n xs\" by simp\n  hence \"S (replicate n a @ xs)\" using 5 by simp\n  then show ?case using balanced2 by blast\nqed\n\nlemma balanced5: \"balanced n w \\<Longrightarrow> balanced (Suc n) (w@[b])\"\n  apply (induction n w rule: balanced.induct)\n  by auto\n\nlemma balanced7: \"balanced m v \\<Longrightarrow> balanced 0 w \\<Longrightarrow> balanced m (v@w)\"\n  apply (induction arbitrary: w rule: balanced.induct)\n  by auto\n\nlemma balanced4: \"S (replicate n a @ w) \\<Longrightarrow> balanced n w\"\nproof (induction \"replicate n a @ w\" arbitrary: n w rule: S.induct)\n  case 1\n  then show ?case by simp\nnext\n  case (2 w')\n  then show ?case\n  proof (cases n)\n    case 0\n    hence \"balanced 0 w'\" using 2 by simp\n    hence \"balanced 1 (w' @ [b])\" using balanced5 by simp\n    then show ?thesis using 0 2 by auto\n  next\n    case (Suc nat)\n    then obtain w'' where f1: \"w' = replicate nat a @ w''\" using 2\n      by (metis alphabet.distinct(1) append_Cons append_is_Nil_conv butlast_append butlast_snoc last_snoc list.distinct(1) list.sel(3) replicate_Suc replicate_append_same)\n    hence \"balanced nat w''\" using 2 by simp\n    moreover have \"w'' @ [b] = w\" using Suc 2 f1 by simp\n    ultimately show ?thesis using 2 Suc apply clarsimp\n      using balanced5 by presburger\n  qed\nnext\n  case (3 v' w')\n  show ?case\n  proof (cases v')\n    case Nil\n    then show ?thesis using 3 by simp\n  next\n    case Cons\n    hence \"v' \\<noteq> []\" by simp\n    then obtain ys where f1: \"v' = replicate n a @ ys\"\n      using 3 balanced6 by meson\n    hence \"balanced n ys\" using 3 by blast\n    moreover have \"balanced 0 w'\" using 3 by simp\n    moreover have \"ys @ w' = w\" using 3 f1 by simp\n    ultimately show ?thesis using balanced7 by blast\n  qed\nqed\n\nlemma \"balanced n w = S (replicate n a @ w)\"\n  using balanced3 balanced4 by blast\n\nend\n", "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/Chap5.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528132451417, "lm_q2_score": 0.8311430436757313, "lm_q1q2_score": 0.708094654268669}}
{"text": "theory Fresh_Monad\nimports\n  \"HOL-Library.State_Monad\"\n  Term_Utils\nbegin\n\ntext \\<open>\n  Generation of fresh names in general can be thought of as picking a string that is not an element\n  of a (finite) set of already existing names. For Isabelle, the \\<^emph>\\<open>Nominal\\<close> framework\n  @{cite urban2008nominal and urban2013nominal} provides support for reasoning over fresh names, but\n  unfortunately, its definitions are not executable.\n\n  Instead, I chose to model generation of fresh names as a monad based on @{type state}. With this,\n  it becomes possible to write programs using \\<open>do\\<close>-notation. This is implemented abstractly as a\n  @{command locale} that expects two operations:\n\n  \\<^item> \\<open>next\\<close> expects a value and generates a larger value, according to @{class linorder}\n  \\<^item> \\<open>arb\\<close> produces any value, similarly to @{const undefined}, but executable\n\\<close>\n\nlocale fresh =\n  fixes \"next\" :: \"'a::linorder \\<Rightarrow> 'a\" and arb :: 'a\n  assumes next_ge: \"next x > x\"\nbegin\n\nabbreviation update_next :: \"('a, unit) state\" where\n\"update_next \\<equiv> State_Monad.update next\"\n\nlemma update_next_strict_mono[simp, intro]: \"strict_mono_state update_next\"\nusing next_ge by (auto intro: update_strict_mono)\n\nlemma update_next_mono[simp, intro]: \"mono_state update_next\"\nby (rule strict_mono_implies_mono) (rule update_next_strict_mono)\n\ndefinition create :: \"('a, 'a) state\" where\n\"create = update_next \\<bind> (\\<lambda>_. State_Monad.get)\"\n\nlemma create_alt_def[code]: \"create = State (\\<lambda>a. (next a, next a))\"\nunfolding create_def State_Monad.update_def State_Monad.get_def State_Monad.set_def State_Monad.bind_def\nby simp\n\nabbreviation fresh_in :: \"'a set \\<Rightarrow> 'a \\<Rightarrow> bool\" where\n\"fresh_in S s \\<equiv> Ball S ((\\<ge>) s)\"\n\nlemma next_ge_all: \"finite S \\<Longrightarrow> fresh_in S s \\<Longrightarrow> next s \\<notin> S\"\nby (metis antisym less_imp_le less_irrefl next_ge)\n\ndefinition Next :: \"'a set \\<Rightarrow> 'a\" where\n\"Next S = (if S = {} then arb else next (Max S))\"\n\nlemma Next_ge_max: \"finite S \\<Longrightarrow> S \\<noteq> {} \\<Longrightarrow> Next S > Max S\"\nunfolding Next_def using next_ge by simp\n\nlemma Next_not_member_subset: \"finite S' \\<Longrightarrow> S \\<subseteq> S' \\<Longrightarrow> Next S' \\<notin> S\"\nunfolding Next_def using next_ge\nby (metis Max_ge Max_mono empty_iff finite_subset leD less_le_trans subset_empty)\n\nlemma Next_not_member: \"finite S \\<Longrightarrow> Next S \\<notin> S\"\nby (rule Next_not_member_subset) auto\n\nlemma Next_geq_not_member: \"finite S \\<Longrightarrow> s \\<ge> Next S \\<Longrightarrow> s \\<notin> S\"\nunfolding Next_def using next_ge\nby (metis (full_types) Max_ge all_not_in_conv leD le_less_trans)\n\nlemma next_not_member: \"finite S \\<Longrightarrow> s \\<ge> Next S \\<Longrightarrow> next s \\<notin> S\"\nby (meson Next_geq_not_member less_imp_le next_ge order_trans)\n\nlemma create_mono[simp, intro]: \"mono_state create\"\nunfolding create_def\nby (auto intro: bind_mono_strong)\n\nlemma create_strict_mono[simp, intro]: \"strict_mono_state create\"\nunfolding create_def\nby (rule bind_strict_mono_strong2) auto\n\nabbreviation run_fresh where\n\"run_fresh m S \\<equiv> fst (run_state m (Next S))\"\n\nabbreviation fresh_fin :: \"'a fset \\<Rightarrow> 'a \\<Rightarrow> bool\" where\n\"fresh_fin S s \\<equiv> fBall S ((\\<ge>) s)\"\n\ncontext includes fset.lifting begin\n\nlemma next_ge_fall: \"fresh_fin S s \\<Longrightarrow> next s |\\<notin>| S\"\nby (transfer fixing: \"next\") (rule next_ge_all)\n\nlift_definition fNext :: \"'a fset \\<Rightarrow> 'a\" is Next .\n\nlemma fNext_ge_max: \"S \\<noteq> {||} \\<Longrightarrow> fNext S > fMax S\"\nby transfer (rule Next_ge_max)\n\nlemma next_not_fmember: \"s \\<ge> fNext S \\<Longrightarrow> next s |\\<notin>| S\"\nby transfer (rule next_not_member)\n\nlemma fNext_geq_not_member: \"s \\<ge> fNext S \\<Longrightarrow> s |\\<notin>| S\"\nby transfer (rule Next_geq_not_member)\n\nlemma fNext_not_member: \"fNext S |\\<notin>| S\"\nby transfer (rule Next_not_member)\n\nlemma fNext_not_member_subset: \"S |\\<subseteq>| S' \\<Longrightarrow> fNext S' |\\<notin>| S\"\nby transfer (rule Next_not_member_subset)\n\nabbreviation frun_fresh where\n\"frun_fresh m S \\<equiv> fst (run_state m (fNext S))\"\n\nend\n\nend\n\nend", "meta": {"author": "Stixxl", "repo": "turing2while", "sha": "078b9a2970c1b376ae6e6efc8ffac134c12d5972", "save_path": "github-repos/isabelle/Stixxl-turing2while", "path": "github-repos/isabelle/Stixxl-turing2while/turing2while-078b9a2970c1b376ae6e6efc8ffac134c12d5972/fresh_names/Fresh_Monad.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8519528057272543, "lm_q2_score": 0.831143045767024, "lm_q1q2_score": 0.7080946498019118}}
{"text": "(* ----------------------------------------------------------------- *)\nsubsection \\<open>Generalized unitary matrices with signature $(1, 1)$\\<close>\n(* ----------------------------------------------------------------- *)\n\ntheory Unitary11_Matrices\nimports Matrices More_Complex\nbegin\n\ntext \\<open> When acting as M\u00f6bius transformations in the extended\ncomplex plane, generalized complex $2\\times 2$ unitary matrices fix\nthe imaginary unit circle (a Hermitean form with (2, 0) signature). We\nnow describe matrices that fix the ordinary unit circle (a Hermitean\nform with (1, 1) signature, i.e., one positive and one negative\nelement on the diagonal). These are extremely important for further\nformalization, since they will represent disc automorphisims and\nisometries of the Poincar\\'e disc. The development of this theory\nfollows the development of the theory of generalized unitary matrices.\n\\<close>\n\ntext \\<open>Unitary11 matrices\\<close>\ndefinition unitary11 where\n  \"unitary11 M \\<longleftrightarrow> congruence M (1, 0, 0, -1) = (1, 0, 0, -1)\"\n\ntext \\<open>Generalized unitary11 matrices\\<close>\ndefinition unitary11_gen where\n  \"unitary11_gen M \\<longleftrightarrow> (\\<exists> k. k \\<noteq> 0 \\<and> congruence M (1, 0, 0, -1) = k *\\<^sub>s\\<^sub>m (1, 0, 0, -1))\"\n\ntext \\<open>Scalar can always be a non-zero real number\\<close>\nlemma unitary11_gen_real:\n  shows \"unitary11_gen M \\<longleftrightarrow> (\\<exists> k. k \\<noteq> 0 \\<and> congruence M (1, 0, 0, -1) = cor k *\\<^sub>s\\<^sub>m (1, 0, 0, -1))\"\n  unfolding unitary11_gen_def\nproof (auto simp del: congruence_def)\n  fix k\n  assume \"k \\<noteq> 0\" \"congruence M (1, 0, 0, -1) = (k, 0, 0, - k)\"\n  hence \"mat_det (congruence M (1, 0, 0, -1)) = -k*k\"\n    by simp\n  moreover\n  have \"is_real (mat_det (congruence M (1, 0, 0, -1)))\" \"Re (mat_det (congruence M (1, 0, 0, -1))) \\<le> 0\"\n    by (auto simp add: mat_det_adj)\n  ultimately\n  have \"is_real (k*k)\" \"Re (-k*k) \\<le> 0\"\n    by auto\n  hence \"is_real (k*k) \\<and> Re (k * k) > 0\"\n    using \\<open>k \\<noteq> 0\\<close>\n    by (smt complex_eq_if_Re_eq mult_eq_0_iff mult_minus_left uminus_complex.simps(1) zero_complex.simps(1) zero_complex.simps(2))\n  hence \"is_real k\"\n    by auto\n  thus \"\\<exists>ka. ka \\<noteq> 0 \\<and> k = cor ka\"\n    using \\<open>k \\<noteq> 0\\<close>\n    by (rule_tac x=\"Re k\" in exI) (cases k, auto simp add: Complex_eq)\nqed\n\ntext \\<open>Unitary11 matrices are special cases of generalized unitary 11 matrices\\<close>\nlemma unitary11_unitary11_gen [simp]:\n  assumes \"unitary11 M\"\n  shows \"unitary11_gen M\"\n  using assms\n  unfolding unitary11_gen_def unitary11_def\n  by (rule_tac x=\"1\" in exI, auto)\n\ntext \\<open>All generalized unitary11 matrices are regular\\<close>\nlemma unitary11_gen_regular:\n  assumes \"unitary11_gen M\"\n  shows \"mat_det M \\<noteq> 0\"\nproof-\n  from assms obtain k where\n    \"k \\<noteq> 0\" \"mat_adj M *\\<^sub>m\\<^sub>m (1, 0, 0, -1) *\\<^sub>m\\<^sub>m M = cor k *\\<^sub>s\\<^sub>m (1, 0, 0, -1)\"\n    unfolding unitary11_gen_real\n    by auto\n  hence \"mat_det (mat_adj M *\\<^sub>m\\<^sub>m (1, 0, 0, -1) *\\<^sub>m\\<^sub>m M) \\<noteq> 0\"\n    by simp\n  thus ?thesis\n    by (simp add: mat_det_adj)\nqed\n\nlemmas unitary11_regular = unitary11_gen_regular[OF unitary11_unitary11_gen]\n\n(* ----------------------------------------------------------------- *)\nsubsubsection \\<open>The characterization in terms of matrix elements\\<close>\n(* ----------------------------------------------------------------- *)\n\ntext \\<open>Special matrices are those having the determinant equal to 1. We first give their characterization.\\<close>\nlemma unitary11_special:\n  assumes \"unitary11 M\" and \"mat_det M = 1\"\n  shows \"\\<exists> a b. M = (a, b, cnj b, cnj a)\"\nproof-\n  have \"mat_adj M *\\<^sub>m\\<^sub>m (1, 0, 0, -1) = (1, 0, 0, -1) *\\<^sub>m\\<^sub>m mat_inv M\"\n    using assms mult_mm_inv_r\n    by (simp add: unitary11_def)\n  thus ?thesis\n    using assms(2)\n    by (cases M) (simp add: mat_adj_def mat_cnj_def)\nqed\n\nlemma unitary11_gen_special:\n  assumes \"unitary11_gen M\" and \"mat_det M = 1\"\n  shows \"\\<exists> a b. M = (a, b, cnj b, cnj a) \\<or> M = (a, b, -cnj b, -cnj a)\"\nproof-\n  from assms\n  obtain k where *: \"k \\<noteq> 0\" \"mat_adj M *\\<^sub>m\\<^sub>m (1, 0, 0, -1) *\\<^sub>m\\<^sub>m M = cor k *\\<^sub>s\\<^sub>m (1, 0, 0, -1)\"\n    unfolding unitary11_gen_real\n    by auto\n  hence \"mat_det (mat_adj M *\\<^sub>m\\<^sub>m (1, 0, 0, -1) *\\<^sub>m\\<^sub>m M) = -  cor k* cor k\"\n    by simp\n  hence \"mat_det (mat_adj M *\\<^sub>m\\<^sub>m M) = cor k* cor k\"\n    by simp\n  hence \"cor k* cor k = 1\"\n    using assms(2)\n    by (simp add: mat_det_adj)\n  hence \"cor k = 1 \\<or> cor k = -1\"\n    using square_eq_1_iff[of \"cor k\"]\n    by simp\n  moreover\n  have \"mat_adj M *\\<^sub>m\\<^sub>m (1, 0, 0, -1) = (cor k *\\<^sub>s\\<^sub>m (1, 0, 0, -1)) *\\<^sub>m\\<^sub>m mat_inv M \"\n    using *\n    using assms mult_mm_inv_r mat_eye_r mat_eye_l\n    by auto\n  moreover\n  obtain a b c d where \"M = (a, b, c, d)\"\n    by (cases M) auto\n  ultimately\n  have \"M = (a, b, cnj b, cnj a) \\<or> M = (a, b, -cnj b, -cnj a)\"\n    using assms(2)\n    by (auto simp add: mat_adj_def mat_cnj_def)\n  thus ?thesis\n    by auto\nqed\n\ntext \\<open>A characterization of all generalized unitary11 matrices\\<close>\nlemma unitary11_gen_iff':\n  shows \"unitary11_gen M \\<longleftrightarrow>\n         (\\<exists> a b k. k \\<noteq> 0 \\<and> mat_det (a, b, cnj b, cnj a) \\<noteq> 0 \\<and>\n                           (M = k *\\<^sub>s\\<^sub>m (a, b, cnj b, cnj a) \\<or> \n                            M = k *\\<^sub>s\\<^sub>m (-1, 0, 0, 1) *\\<^sub>m\\<^sub>m (a, b, cnj b, cnj a)))\" (is \"?lhs = ?rhs\")\nproof\n  assume ?lhs\n  obtain d where *: \"d*d = mat_det M\"\n    using ex_complex_sqrt\n    by auto\n  hence \"d \\<noteq> 0\"\n    using unitary11_gen_regular[OF \\<open>unitary11_gen M\\<close>]\n    by auto\n  from \\<open>unitary11_gen M\\<close>\n  obtain k where \"k \\<noteq> 0\" \"mat_adj M *\\<^sub>m\\<^sub>m (1, 0, 0, -1) *\\<^sub>m\\<^sub>m M = cor k *\\<^sub>s\\<^sub>m (1, 0, 0, -1)\"\n    unfolding unitary11_gen_real\n    by auto\n  hence \"mat_adj ((1/d)*\\<^sub>s\\<^sub>mM)*\\<^sub>m\\<^sub>m (1, 0, 0, -1) *\\<^sub>m\\<^sub>m ((1/d)*\\<^sub>s\\<^sub>mM) = (cor k / (d*cnj d)) *\\<^sub>s\\<^sub>m (1, 0, 0, -1)\"\n    by simp\n  moreover\n  have \"is_real (cor k / (d * cnj d))\"\n    by (metis complex_In_mult_cnj_zero div_reals Im_complex_of_real)\n  hence \"cor (Re (cor k / (d * cnj d))) = cor k / (d * cnj d)\"\n    by simp\n  ultimately\n  have \"unitary11_gen ((1/d)*\\<^sub>s\\<^sub>mM)\"\n    unfolding unitary11_gen_real\n    using \\<open>d \\<noteq> 0\\<close> \\<open>k \\<noteq> 0\\<close>\n    using \\<open>cor (Re (cor k / (d * cnj d))) = cor k / (d * cnj d)\\<close>\n    by (rule_tac x=\"Re (cor k / (d * cnj d))\" in exI, auto, simp add: *)\n  moreover\n  have \"mat_det ((1 / d) *\\<^sub>s\\<^sub>m M) = 1\"\n    using * unitary11_gen_regular[of M] \\<open>unitary11_gen M\\<close>\n    by auto\n  ultimately\n  obtain a b where \"(a, b, cnj b, cnj a) = (1 / d) *\\<^sub>s\\<^sub>m M \\<or> (a, b, -cnj b, -cnj a) = (1 / d) *\\<^sub>s\\<^sub>m M\"\n    using unitary11_gen_special[of \"(1 / d) *\\<^sub>s\\<^sub>m M\"]\n    by force\n  thus ?rhs\n  proof\n    assume \"(a, b, cnj b, cnj a) = (1 / d) *\\<^sub>s\\<^sub>m M\"\n    moreover\n    hence \"mat_det (a, b, cnj b, cnj a) \\<noteq> 0\"\n      using unitary11_gen_regular[OF \\<open>unitary11_gen M\\<close>] \\<open>d \\<noteq> 0\\<close>\n      by auto\n    ultimately\n    show ?rhs\n      using \\<open>d \\<noteq> 0\\<close>\n      by (rule_tac x=\"a\" in exI, rule_tac x=\"b\" in exI, rule_tac x=\"d\" in exI, simp)\n  next\n    assume *: \"(a, b, -cnj b, -cnj a) = (1 / d) *\\<^sub>s\\<^sub>m M\"\n    hence \" (1 / d) *\\<^sub>s\\<^sub>m M = (a, b, -cnj b, -cnj a)\"\n      by simp\n    hence \"M = (a * d, b * d, - (d * cnj b), - (d * cnj a))\"\n      using \\<open>d \\<noteq> 0\\<close>\n      using mult_sm_inv_l[of \"1/d\" M \"(a, b, -cnj b, -cnj a)\", symmetric]\n      by (simp add: field_simps)\n    moreover\n    have \"mat_det (a, b, -cnj b, -cnj a) \\<noteq> 0\"\n      using * unitary11_gen_regular[OF \\<open>unitary11_gen M\\<close>] \\<open>d \\<noteq> 0\\<close>\n      by auto\n    ultimately\n    show ?thesis\n      using \\<open>d \\<noteq> 0\\<close>\n      by (rule_tac x=\"a\" in exI, rule_tac x=\"b\" in exI, rule_tac x=\"-d\" in exI) (simp add: field_simps)\n  qed\nnext\n  assume ?rhs\n  then obtain a b k where \"k \\<noteq> 0\" \"mat_det (a, b, cnj b, cnj a) \\<noteq> 0\"\n    \"M = k *\\<^sub>s\\<^sub>m (a, b, cnj b, cnj a) \\<or> M = k *\\<^sub>s\\<^sub>m (-1, 0, 0, 1) *\\<^sub>m\\<^sub>m (a, b, cnj b, cnj a)\"\n    by auto\n  moreover\n  let ?x = \"cnj k * cnj a * (k * a) + - (cnj k * b * (k * cnj b))\"\n  have \"?x = (k*cnj k)*(a*cnj a - b*cnj b)\"\n    by (auto simp add: field_simps)\n  hence \"is_real ?x\"\n    by simp\n  hence \"cor (Re ?x) = ?x\"\n    by (rule complex_of_real_Re)\n  moreover\n  have \"?x \\<noteq> 0\"\n    using mult_eq_0_iff[of \"cnj k * k\" \"(cnj a * a + - cnj b * b)\"]\n    using \\<open>mat_det (a, b, cnj b, cnj a) \\<noteq> 0\\<close> \\<open>k \\<noteq> 0\\<close>\n    by (auto simp add: field_simps)\n  hence \"Re ?x \\<noteq> 0\"\n    using \\<open>is_real ?x\\<close>\n    by (metis calculation(4) of_real_0)\n  ultimately\n  show ?lhs\n    unfolding unitary11_gen_real\n    by (rule_tac x=\"Re ?x\" in exI) (auto simp add: mat_adj_def mat_cnj_def)\nqed\n\ntext \\<open>Another characterization of all generalized unitary11 matrices. They are products of \nrotation and Blaschke factor matrices.\\<close>\nlemma unitary11_gen_cis_blaschke:\n  assumes \"k \\<noteq> 0\" and \"M = k *\\<^sub>s\\<^sub>m (a, b, cnj b, cnj a)\" and \n          \"a \\<noteq> 0\" and \"mat_det (a, b, cnj b, cnj a) \\<noteq> 0\"\n  shows \"\\<exists> k' \\<phi> a'. k' \\<noteq> 0 \\<and> a' * cnj a' \\<noteq> 1 \\<and> \n                                 M = k' *\\<^sub>s\\<^sub>m (cis \\<phi>, 0, 0, 1) *\\<^sub>m\\<^sub>m (1, -a', -cnj a', 1)\"\nproof-\n  have \"a = cnj a * cis (2 * arg a)\"\n    using rcis_cmod_arg[of a] rcis_cnj[of a]\n    using cis_rcis_eq rcis_mult\n    by simp\n  thus ?thesis\n    using assms\n    by (rule_tac x=\"k*cnj a\" in exI, rule_tac x=\"2*arg a\" in exI, rule_tac x=\"- b / a\" in exI) (auto simp add: field_simps)\nqed\n\nlemma unitary11_gen_cis_blaschke':\n  assumes \"k \\<noteq> 0\" and \"M = k *\\<^sub>s\\<^sub>m (-1, 0, 0, 1) *\\<^sub>m\\<^sub>m (a, b, cnj b, cnj a)\" and\n          \"a \\<noteq> 0\" and \"mat_det (a, b, cnj b, cnj a) \\<noteq> 0\"\n  shows \"\\<exists> k' \\<phi> a'. k' \\<noteq> 0 \\<and> a' * cnj a' \\<noteq> 1 \\<and>\n                                 M = k' *\\<^sub>s\\<^sub>m (cis \\<phi>, 0, 0, 1) *\\<^sub>m\\<^sub>m (1, -a', -cnj a', 1)\"\nproof-\n  obtain k' \\<phi> a' where *: \"k' \\<noteq> 0\" \"k *\\<^sub>s\\<^sub>m (a, b, cnj b, cnj a) = k' *\\<^sub>s\\<^sub>m (cis \\<phi>, 0, 0, 1) *\\<^sub>m\\<^sub>m (1, -a', -cnj a', 1)\" \"a' * cnj a' \\<noteq> 1\"\n    using unitary11_gen_cis_blaschke[OF \\<open>k \\<noteq> 0\\<close> _ \\<open>a \\<noteq> 0\\<close>] \\<open>mat_det (a, b, cnj b, cnj a) \\<noteq> 0\\<close>\n    by blast\n  have \"(cis \\<phi>, 0, 0, 1) *\\<^sub>m\\<^sub>m (-1, 0, 0, 1) = (cis (\\<phi> + pi), 0, 0, 1)\"\n   by (simp add: cis_def complex.corec Complex_eq)\n  thus ?thesis\n    using * \\<open>M = k *\\<^sub>s\\<^sub>m (-1, 0, 0, 1) *\\<^sub>m\\<^sub>m (a, b, cnj b, cnj a)\\<close>\n    by (rule_tac x=\"k'\" in exI, rule_tac x=\"\\<phi> + pi\" in exI, rule_tac x=\"a'\" in exI, simp)\nqed\n\nlemma unitary11_gen_cis_blaschke_rev:\n  assumes \"k' \\<noteq> 0\" and \"M = k' *\\<^sub>s\\<^sub>m (cis \\<phi>, 0, 0, 1) *\\<^sub>m\\<^sub>m (1, -a', -cnj a', 1)\" and\n          \"a' * cnj a' \\<noteq> 1\"\n  shows \"\\<exists> k a b. k \\<noteq> 0 \\<and> mat_det (a, b, cnj b, cnj a) \\<noteq> 0  \\<and>\n                          M = k *\\<^sub>s\\<^sub>m (a, b, cnj b, cnj a)\"\n  using assms\n  apply (rule_tac x=\"k'*cis(\\<phi>/2)\" in exI, rule_tac x=\"cis(\\<phi>/2)\" in exI, rule_tac x=\"-a'*cis(\\<phi>/2)\" in exI)\n  apply (simp add: cis_mult mult.commute mult.left_commute)\n  done\n\nlemma unitary11_gen_cis_inversion:\n  assumes \"k \\<noteq> 0\" and \"M = k *\\<^sub>s\\<^sub>m (0, b, cnj b, 0)\" and \"b \\<noteq> 0\"\n  shows \"\\<exists> k' \\<phi>. k' \\<noteq> 0 \\<and>\n                              M = k' *\\<^sub>s\\<^sub>m (cis \\<phi>, 0, 0, 1) *\\<^sub>m\\<^sub>m (0, 1, 1, 0)\"\nusing assms\nusing rcis_cmod_arg[of b, symmetric] rcis_cnj[of b] cis_rcis_eq\nby simp (rule_tac x=\"2*arg b\" in exI, simp add: rcis_mult)\n\nlemma unitary11_gen_cis_inversion':\n  assumes \"k \\<noteq> 0\" and \"M = k *\\<^sub>s\\<^sub>m (-1, 0, 0, 1) *\\<^sub>m\\<^sub>m (0, b, cnj b, 0)\" and \"b \\<noteq> 0\"\n  shows \"\\<exists> k' \\<phi>. k' \\<noteq> 0 \\<and>\n                   M = k' *\\<^sub>s\\<^sub>m (cis \\<phi>, 0, 0, 1) *\\<^sub>m\\<^sub>m (0, 1, 1, 0)\"\nproof-\n  obtain k' \\<phi> where *: \"k' \\<noteq> 0\" \"k *\\<^sub>s\\<^sub>m (0, b, cnj b, 0) = k' *\\<^sub>s\\<^sub>m (cis \\<phi>, 0, 0, 1) *\\<^sub>m\\<^sub>m (0, 1, 1, 0)\"\n    using unitary11_gen_cis_inversion[OF \\<open>k \\<noteq> 0\\<close> _ \\<open>b \\<noteq> 0\\<close>]\n    by metis\n  have \"(cis \\<phi>, 0, 0, 1) *\\<^sub>m\\<^sub>m (-1, 0, 0, 1) = (cis (\\<phi> + pi), 0, 0, 1)\"\n    by (simp add: cis_def complex.corec Complex_eq)\n  thus ?thesis\n    using * \\<open>M = k *\\<^sub>s\\<^sub>m (-1, 0, 0, 1) *\\<^sub>m\\<^sub>m (0, b, cnj b, 0)\\<close>\n    by (rule_tac x=\"k'\" in exI, rule_tac x=\"\\<phi> + pi\" in exI, simp)\nqed\n\nlemma unitary11_gen_cis_inversion_rev:\n  assumes \"k' \\<noteq> 0\" and \"M = k' *\\<^sub>s\\<^sub>m (cis \\<phi>, 0, 0, 1) *\\<^sub>m\\<^sub>m (0, 1, 1, 0)\"\n  shows \"\\<exists> k a b. k \\<noteq> 0 \\<and> mat_det (a, b, cnj b, cnj a) \\<noteq> 0 \\<and>\n                          M = k *\\<^sub>s\\<^sub>m (a, b, cnj b, cnj a)\"\n  using assms\n  by (rule_tac x=\"k'*cis(\\<phi>/2)\" in exI, rule_tac x=0 in exI, rule_tac x=\"cis(\\<phi>/2)\" in exI) (simp add: cis_mult)\n\ntext \\<open>Another characterization of generalized unitary11 matrices\\<close>\nlemma unitary11_gen_iff:\n  shows \"unitary11_gen M \\<longleftrightarrow> \n         (\\<exists> k a b. k \\<noteq> 0 \\<and> mat_det (a, b, cnj b, cnj a) \\<noteq> 0 \\<and>\n                           M = k *\\<^sub>s\\<^sub>m (a, b, cnj b, cnj a))\" (is \"?lhs = ?rhs\")\nproof\n  assume ?lhs\n  then obtain a b k where *: \"k \\<noteq> 0\" \"mat_det (a, b, cnj b, cnj a) \\<noteq> 0\" \"M = k *\\<^sub>s\\<^sub>m (a, b, cnj b, cnj a) \\<or> M = k *\\<^sub>s\\<^sub>m (-1, 0, 0, 1) *\\<^sub>m\\<^sub>m (a, b, cnj b, cnj a)\"\n    using unitary11_gen_iff'\n    by auto\n  show ?rhs\n  proof (cases \"M = k *\\<^sub>s\\<^sub>m (a, b, cnj b, cnj a)\")\n    case True\n    thus ?thesis\n      using *\n      by auto\n  next\n    case False\n    hence **: \"M = k *\\<^sub>s\\<^sub>m (-1, 0, 0, 1) *\\<^sub>m\\<^sub>m (a, b, cnj b, cnj a)\"\n      using *\n      by simp\n    show ?thesis\n    proof (cases \"a = 0\")\n      case True\n      hence \"b \\<noteq> 0\"\n        using *\n        by auto\n      show ?thesis\n        using unitary11_gen_cis_inversion_rev[of _ M]\n        using ** \\<open>a = 0\\<close>\n        using unitary11_gen_cis_inversion'[OF \\<open>k \\<noteq> 0\\<close> _ \\<open>b \\<noteq> 0\\<close>, of M]\n        by auto\n    next\n      case False\n      show ?thesis\n        using unitary11_gen_cis_blaschke_rev[of _ M]\n        using **\n        using unitary11_gen_cis_blaschke'[OF \\<open>k \\<noteq> 0\\<close> _ \\<open>a \\<noteq> 0\\<close>, of M b] \\<open>mat_det (a, b, cnj b, cnj a) \\<noteq> 0\\<close>\n        by blast\n    qed\n  qed\nnext\n  assume ?rhs\n  thus ?lhs\n    using unitary11_gen_iff'\n    by auto\nqed\n\nlemma unitary11_iff:\n  shows \"unitary11 M \\<longleftrightarrow>\n         (\\<exists> a b k. (cmod a)\\<^sup>2 > (cmod b)\\<^sup>2 \\<and>\n                           (cmod k)\\<^sup>2 = 1 / ((cmod a)\\<^sup>2 - (cmod b)\\<^sup>2) \\<and>\n                           M = k *\\<^sub>s\\<^sub>m (a, b, cnj b, cnj a))\" (is \"?lhs = ?rhs\")\nproof\n  assume ?lhs\n  obtain k a b where *:\n    \"M = k *\\<^sub>s\\<^sub>m (a, b, cnj b, cnj a)\"\"mat_det (a, b, cnj b, cnj a) \\<noteq> 0\" \"k \\<noteq> 0\"\n    using unitary11_gen_iff unitary11_unitary11_gen[OF \\<open>unitary11 M\\<close>]\n    by auto\n\n  have md: \"mat_det (a, b, cnj b, cnj a) = cor ((cmod a)\\<^sup>2 - (cmod b)\\<^sup>2)\"\n    by (auto simp add: complex_mult_cnj_cmod)\n  hence **: \"(cmod a)\\<^sup>2 \\<noteq> (cmod b)\\<^sup>2\"\n    using \\<open>mat_det (a, b, cnj b, cnj a) \\<noteq> 0\\<close>\n    by auto\n\n  have \"k * cnj k * mat_det (a, b, cnj b, cnj a) = 1\"\n    using \\<open>M = k *\\<^sub>s\\<^sub>m (a, b, cnj b, cnj a)\\<close>\n    using \\<open>unitary11 M\\<close>\n    unfolding unitary11_def\n    by (auto simp add: mat_adj_def mat_cnj_def) (simp add: field_simps)\n  hence ***: \"(cmod k)\\<^sup>2 * ((cmod a)\\<^sup>2 - (cmod b)\\<^sup>2) = 1\"\n    by (subst (asm) complex_mult_cnj_cmod, subst (asm) md, subst (asm) cor_mult[symmetric]) (metis of_real_1 of_real_eq_iff)\n  hence \"((cmod a)\\<^sup>2 - (cmod b)\\<^sup>2) = 1 / (cmod k)\\<^sup>2\"\n    by (cases \"k=0\") (auto simp add: field_simps)\n  hence \"cmod a ^ 2 = cmod b ^ 2 + 1 / cmod k ^ 2\"\n    by simp\n  thus ?rhs\n    using \\<open>M = k *\\<^sub>s\\<^sub>m (a, b, cnj b, cnj a)\\<close> ** mat_eye_l\n    by (rule_tac x=\"a\" in exI, rule_tac x=\"b\" in exI, rule_tac x=\"k\" in exI)\n       (auto simp add: complex_mult_cnj_cmod intro!: )\nnext\n  assume ?rhs\n  then obtain a b k where \"(cmod b)\\<^sup>2 < (cmod a)\\<^sup>2 \\<and> (cmod k)\\<^sup>2 = 1 / ((cmod a)\\<^sup>2 - (cmod b)\\<^sup>2) \\<and> M = k *\\<^sub>s\\<^sub>m (a, b, cnj b, cnj a)\"\n    by auto\n  moreover\n  have \"cnj k * cnj a * (k * a) + - (cnj k * b * (k * cnj b)) = (cor ((cmod k)\\<^sup>2 * ((cmod a)\\<^sup>2 - (cmod b)\\<^sup>2)))\"\n  proof-\n    have \"cnj k * cnj a * (k * a) = cor ((cmod k)\\<^sup>2 * (cmod a)\\<^sup>2)\"\n      using complex_mult_cnj_cmod[of a] complex_mult_cnj_cmod[of k]\n      by (auto simp add: field_simps)\n    moreover\n    have \"cnj k * b * (k * cnj b) = cor ((cmod k)\\<^sup>2 * (cmod b)\\<^sup>2)\"\n      using complex_mult_cnj_cmod[of b, symmetric] complex_mult_cnj_cmod[of k]\n      by (auto simp add: field_simps)\n    ultimately\n    show ?thesis\n      by (auto simp add: field_simps)\n  qed\n  ultimately\n  show ?lhs\n    unfolding unitary11_def\n    by (auto simp add: mat_adj_def mat_cnj_def field_simps)\nqed\n\n(* ----------------------------------------------------------------- *)\nsubsubsection \\<open>Group properties\\<close>\n(* ----------------------------------------------------------------- *)\n\ntext \\<open>Generalized unitary11 matrices form a group under\nmultiplication (it is sometimes denoted by $GU_{1, 1}(2,\n\\mathbb{C})$). The group is also closed under non-zero complex scalar\nmultiplication. Since these matrices are always regular, they form a\nsubgroup of general linear group (usually denoted by $GL(2,\n\\mathbb{C})$) of all regular matrices.\\<close>\n\nlemma unitary11_gen_mult_sm:\n  assumes \"k \\<noteq> 0\" and \"unitary11_gen M\"\n  shows \"unitary11_gen (k *\\<^sub>s\\<^sub>m M)\"\nproof-\n  have \"k * cnj k = cor (Re (k * cnj k))\"\n    by (subst complex_of_real_Re) auto\n  thus ?thesis\n    using assms\n    unfolding unitary11_gen_real\n    by auto (rule_tac x=\"Re (k*cnj k) * ka\" in exI, auto)\nqed\n\nlemma unitary11_gen_div_sm:\n  assumes \"k \\<noteq> 0\" and \"unitary11_gen (k *\\<^sub>s\\<^sub>m M)\"\n  shows \"unitary11_gen M\"\n  using assms unitary11_gen_mult_sm[of \"1/k\" \"k *\\<^sub>s\\<^sub>m M\"]\n  by simp\n\n\nlemma unitary11_inv:\n  assumes \"k \\<noteq> 0\" and \"M = k *\\<^sub>s\\<^sub>m (a, b, cnj b, cnj a)\" and \"mat_det (a, b, cnj b, cnj a) \\<noteq> 0\"\n  shows \"\\<exists> k' a' b'. k' \\<noteq> 0 \\<and> mat_inv M = k' *\\<^sub>s\\<^sub>m (a', b', cnj b', cnj a') \\<and> mat_det (a', b', cnj b', cnj a') \\<noteq> 0\"\n  using assms\n  by (subst assms, subst mat_inv_mult_sm[OF assms(1)])\n     (rule_tac x=\"1/(k * mat_det (a, b, cnj b, cnj a))\" in exI, rule_tac x=\"cnj a\" in exI, rule_tac x=\"-b\" in exI, simp add: field_simps)\n\nlemma unitary11_comp:\n  assumes \"k1 \\<noteq> 0\" and \"M1 = k1 *\\<^sub>s\\<^sub>m (a1, b1, cnj b1, cnj a1)\" and \"mat_det (a1, b1, cnj b1, cnj a1) \\<noteq> 0\"\n          \"k2 \\<noteq> 0\" \"M2 = k2 *\\<^sub>s\\<^sub>m (a2, b2, cnj b2, cnj a2)\" \"mat_det (a2, b2, cnj b2, cnj a2) \\<noteq> 0\"\n  shows \"\\<exists> k a b. k \\<noteq> 0 \\<and> M1 *\\<^sub>m\\<^sub>m M2 = k *\\<^sub>s\\<^sub>m (a, b, cnj b, cnj a) \\<and> mat_det (a, b, cnj b, cnj a) \\<noteq> 0\"\n  using assms\n  apply (rule_tac x=\"k1*k2\" in exI)\n  apply (rule_tac x=\"a1*a2 + b1*cnj b2\" in exI)\n  apply (rule_tac x=\"a1*b2 + b1*cnj a2\" in exI)\nproof (auto simp add: algebra_simps)\n  assume *: \"a1 * (a2 * (cnj a1 * cnj a2)) + b1 * (b2 * (cnj b1 * cnj b2)) =\n            a1 * (b2 * (cnj a1 * cnj b2)) + a2 * (b1 * (cnj a2 * cnj b1))\" and\n         **: \"a1*cnj a1 \\<noteq> b1 * cnj b1\" \"a2*cnj a2 \\<noteq> b2*cnj b2\"\n  hence \"(a1*cnj a1)*(a2*cnj a2 - b2*cnj b2) = (b1*cnj b1)*(a2*cnj a2 - b2*cnj b2)\"\n    by (simp add: field_simps)\n  hence \"a1*cnj a1 = b1*cnj b1\"\n    using **(2)\n    by simp\n  thus False\n    using **(1)\n    by simp\nqed\n\nlemma unitary11_gen_mat_inv:\n  assumes \"unitary11_gen M\" and \"mat_det M \\<noteq> 0\"\n  shows \"unitary11_gen (mat_inv M)\"\nproof-\n  obtain k a b where \"k \\<noteq> 0 \\<and> mat_det (a, b, cnj b, cnj a) \\<noteq> 0 \\<and> M = k *\\<^sub>s\\<^sub>m (a, b, cnj b, cnj a)\"\n    using assms unitary11_gen_iff[of M]\n    by auto\n  then obtain k' a' b' where \"k' \\<noteq> 0 \\<and> mat_inv M = k' *\\<^sub>s\\<^sub>m (a', b', cnj b', cnj a') \\<and> mat_det (a', b', cnj b', cnj a') \\<noteq> 0\"\n    using unitary11_inv [of k M a b]\n    by auto\n  thus ?thesis\n    using unitary11_gen_iff[of \"mat_inv M\"]\n    by auto\nqed\n\nlemma unitary11_gen_comp:\n  assumes \"unitary11_gen M1\" and \"mat_det M1 \\<noteq> 0\" and \"unitary11_gen M2\"  and \"mat_det M2 \\<noteq> 0\"\n  shows \"unitary11_gen (M1 *\\<^sub>m\\<^sub>m M2)\"\nproof-\n  from assms obtain k1 k2 a1 a2 b1 b2 where\n    \"k1 \\<noteq> 0 \\<and> mat_det (a1, b1, cnj b1, cnj a1) \\<noteq> 0 \\<and> M1 = k1 *\\<^sub>s\\<^sub>m (a1, b1, cnj b1, cnj a1)\"\n    \"k2 \\<noteq> 0 \\<and> mat_det (a2, b2, cnj b2, cnj a2) \\<noteq> 0 \\<and> M2 = k2 *\\<^sub>s\\<^sub>m (a2, b2, cnj b2, cnj a2)\"\n    using unitary11_gen_iff[of M1]  unitary11_gen_iff[of M2]\n    by blast\n  then obtain k a b where \"k \\<noteq> 0 \\<and> M1 *\\<^sub>m\\<^sub>m M2 = k *\\<^sub>s\\<^sub>m (a, b, cnj b, cnj a) \\<and> mat_det (a, b, cnj b, cnj a) \\<noteq> 0\"\n    using unitary11_comp[of k1 M1 a1 b1 k2 M2 a2 b2]\n    by blast\n  thus ?thesis\n    using unitary11_gen_iff[of \"M1 *\\<^sub>m\\<^sub>m M2\"]\n    by blast\nqed\n\ntext \\<open>Classification into orientation-preserving and orientation-reversing matrices\\<close>\nlemma unitary11_sgn_det_orientation:\n  assumes \"k \\<noteq> 0\" and \"mat_det (a, b, cnj b, cnj a) \\<noteq> 0\" and \"M = k *\\<^sub>s\\<^sub>m (a, b, cnj b, cnj a)\"\n  shows \"\\<exists> k'. sgn k' = sgn (Re (mat_det (a, b, cnj b, cnj a))) \\<and> congruence M (1, 0, 0, -1) = cor k' *\\<^sub>s\\<^sub>m (1, 0, 0, -1)\"\nproof-\n  let ?x = \"cnj k * cnj a * (k * a) - (cnj k * b * (k * cnj b))\"\n  have *: \"?x = k * cnj k * (a * cnj a - b * cnj b)\"\n    by (auto simp add: field_simps)\n  hence \"is_real ?x\"\n    by auto\n  hence \"cor (Re ?x) = ?x\"\n    by (rule complex_of_real_Re)\n  moreover\n  have \"sgn (Re ?x) = sgn (Re (a * cnj a - b * cnj b))\"\n  proof-\n    have *: \"Re ?x = (cmod k)\\<^sup>2 * Re (a * cnj a - b * cnj b)\"\n      by (subst *, subst complex_mult_cnj_cmod, subst Re_mult_real) (metis Im_complex_of_real, metis Re_complex_of_real)\n    show ?thesis\n      using \\<open>k \\<noteq> 0\\<close>\n      by (subst *) (simp add: sgn_mult)\n  qed\n  ultimately\n  show ?thesis\n    using assms(3)\n    by (rule_tac x=\"Re ?x\" in exI) (auto simp add: mat_adj_def mat_cnj_def)\nqed\n\nlemma unitary11_sgn_det:\n  assumes \"k \\<noteq> 0\" and \"mat_det (a, b, cnj b, cnj a) \\<noteq> 0\" and \"M = k *\\<^sub>s\\<^sub>m (a, b, cnj b, cnj a)\" and \"M = (A, B, C, D)\"\n  shows \"sgn (Re (mat_det (a, b, cnj b, cnj a))) = (if b = 0 then 1 else sgn (Re ((A*D)/(B*C)) - 1))\"\nproof (cases \"b = 0\")\n  case True\n  thus ?thesis\n    using assms\n    by (simp only: mat_det.simps, subst complex_mult_cnj_cmod, subst minus_complex.sel, subst Re_complex_of_real, simp)\nnext\n  case False\n  from assms have *: \"A =  k * a\" \"B =  k * b\" \"C =  k * cnj b\" \"D =  k * cnj a\"\n    by auto\n  hence *: \"(A*D)/(B*C) = (a*cnj a)/(b*cnj b)\"\n    using \\<open>k \\<noteq> 0\\<close>\n    by simp\n  show ?thesis\n    using \\<open>b \\<noteq> 0\\<close>\n    apply (subst *, subst Re_divide_real, simp, simp)\n    apply (simp only: mat_det.simps)\n    apply (subst complex_mult_cnj_cmod)+\n    apply ((subst Re_complex_of_real)+, subst minus_complex.sel, (subst Re_complex_of_real)+, simp add: field_simps sgn_if)\n    done\nqed\n\nlemma unitary11_orientation:\n  assumes \"unitary11_gen M\" and \"M = (A, B, C, D)\"\n  shows \"\\<exists> k'. sgn k' = sgn (if B = 0 then 1 else sgn (Re ((A*D)/(B*C)) - 1)) \\<and> congruence M (1, 0, 0, -1) = cor k' *\\<^sub>s\\<^sub>m (1, 0, 0, -1)\"\nproof-\n  from \\<open>unitary11_gen M\\<close>\n  obtain k a b where *: \"k \\<noteq> 0\" \"mat_det (a, b, cnj b, cnj a) \\<noteq> 0\" \"M = k*\\<^sub>s\\<^sub>m (a, b, cnj b, cnj a)\"\n    using unitary11_gen_iff[of M]\n    by auto\n  moreover\n  have \"b = 0 \\<longleftrightarrow> B = 0\"\n    using \\<open>M = (A, B, C, D)\\<close> *\n    by auto\n  ultimately\n  show ?thesis\n    using unitary11_sgn_det_orientation[OF *] unitary11_sgn_det[OF * \\<open>M = (A, B, C, D)\\<close>]\n    by auto\nqed\n\nlemma unitary11_sgn_det_orientation':\n  assumes \"congruence M (1, 0, 0, -1) = cor k' *\\<^sub>s\\<^sub>m (1, 0, 0, -1)\" and \"k' \\<noteq> 0\"\n  shows \"\\<exists> a b k. k \\<noteq> 0 \\<and> M = k *\\<^sub>s\\<^sub>m (a, b, cnj b, cnj a) \\<and> sgn k' = sgn (Re (mat_det (a, b, cnj b, cnj a)))\"\nproof-\n  obtain a b k where\n    \"k \\<noteq> 0\" \"mat_det (a, b, cnj b, cnj a) \\<noteq> 0\" \"M = k *\\<^sub>s\\<^sub>m (a, b, cnj b, cnj a)\"\n    using assms\n    using unitary11_gen_iff[of M]\n    unfolding unitary11_gen_def\n    by auto\n  moreover\n  have \"sgn k' = sgn (Re (mat_det (a, b, cnj b, cnj a)))\"\n  proof-\n    let ?x = \"cnj k * cnj a * (k * a) - (cnj k * b * (k * cnj b))\"\n    have *: \"?x = k * cnj k * (a * cnj a - b * cnj b)\"\n      by (auto simp add: field_simps)\n    hence \"is_real ?x\"\n      by auto\n    hence \"cor (Re ?x) = ?x\"\n      by (rule complex_of_real_Re)\n\n    have **: \"sgn (Re ?x) = sgn (Re (a * cnj a - b * cnj b))\"\n    proof-\n      have *: \"Re ?x = (cmod k)\\<^sup>2 * Re (a * cnj a - b * cnj b)\"\n        by (subst *, subst complex_mult_cnj_cmod, subst Re_mult_real) (metis Im_complex_of_real, metis Re_complex_of_real)\n      show ?thesis\n        using \\<open>k \\<noteq> 0\\<close>\n        by (subst *) (simp add: sgn_mult)\n    qed\n    moreover\n    have \"?x = cor k'\"\n      using \\<open>M = k *\\<^sub>s\\<^sub>m (a, b, cnj b, cnj a)\\<close> assms\n      by (simp add: mat_adj_def mat_cnj_def)\n    hence \"sgn (Re ?x) = sgn k'\"\n      using \\<open>cor (Re ?x) = ?x\\<close>\n      unfolding complex_of_real_def\n      by simp\n    ultimately\n    show ?thesis\n      by simp\n  qed\n  ultimately\n  show ?thesis\n    by (rule_tac x=\"a\" in exI, rule_tac x=\"b\" in exI, rule_tac x=\"k\" in exI)  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/Complex_Geometry/Unitary11_Matrices.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8519528019683106, "lm_q2_score": 0.8311430415844384, "lm_q1q2_score": 0.7080946431143263}}
{"text": "(* Author: R. Thiemann *)\n\nsection \\<open>Unsatisfiability over the Reals\\<close>\n\ntext \\<open>By using Farkas' Lemma we prove that a finite set of \n  linear rational inequalities is satisfiable over the rational numbers\n  if and only if it is satisfiable over the real numbers.\n  Hence, the simplex algorithm either gives a rational solution or\n  shows unsatisfiability over the real numbers.\\<close>\n\ntheory Simplex_for_Reals\n  imports \n    Farkas\n    Simplex.Simplex_Incremental\nbegin\n\n\ninstantiation real :: lrv\nbegin\ndefinition scaleRat_real :: \"rat \\<Rightarrow> real \\<Rightarrow> real\" where\n  [simp]: \"x *R y = real_of_rat x * y\"\ninstance by standard (auto simp add: field_simps of_rat_mult of_rat_add)\nend\n\nabbreviation real_satisfies_constraints :: \"real valuation \\<Rightarrow> constraint set \\<Rightarrow> bool\" (infixl \"\\<Turnstile>\\<^sub>r\\<^sub>c\\<^sub>s\" 100) where\n  \"v \\<Turnstile>\\<^sub>r\\<^sub>c\\<^sub>s cs \\<equiv> \\<forall> c \\<in> cs. v \\<Turnstile>\\<^sub>c c\"\n\ndefinition of_rat_val :: \"rat valuation \\<Rightarrow> real valuation\" where\n  \"of_rat_val v x = of_rat (v x)\" \n\nlemma of_rat_val_eval: \"p \\<lbrace>of_rat_val v\\<rbrace> = of_rat (p \\<lbrace>v\\<rbrace>)\" \n  unfolding of_rat_val_def linear_poly_sum of_rat_sum \n  by (rule sum.cong, auto simp: of_rat_mult)\n\nlemma of_rat_val_constraint: \"of_rat_val v \\<Turnstile>\\<^sub>c c \\<longleftrightarrow> v \\<Turnstile>\\<^sub>c c\" \n  by (cases c, auto simp: of_rat_val_eval of_rat_less of_rat_less_eq)\n\nlemma of_rat_val_constraints: \"of_rat_val v \\<Turnstile>\\<^sub>r\\<^sub>c\\<^sub>s cs \\<longleftrightarrow> v \\<Turnstile>\\<^sub>c\\<^sub>s cs\" \n  using of_rat_val_constraint by auto\n\nlemma sat_scale_rat_real: assumes \"(v :: real valuation) \\<Turnstile>\\<^sub>c c\"\n  shows \"v \\<Turnstile>\\<^sub>c (r *R c)\"\nproof -\n  have \"r < 0 \\<or> r = 0 \\<or> r > 0\" by auto\n  then show ?thesis using assms by (cases c, simp_all add: right_diff_distrib \n        valuate_minus valuate_scaleRat scaleRat_leq1 scaleRat_leq2 valuate_zero\n        of_rat_less of_rat_mult)\nqed\n\nfun of_rat_lec :: \"rat le_constraint \\<Rightarrow> real le_constraint\" where\n  \"of_rat_lec (Le_Constraint r p c) = Le_Constraint r p (of_rat c)\" \n\nlemma lec_of_constraint_real: \n  assumes \"is_le c\"\n  shows \"(v \\<Turnstile>\\<^sub>l\\<^sub>e of_rat_lec (lec_of_constraint c)) \\<longleftrightarrow> (v \\<Turnstile>\\<^sub>c c)\"\n  using assms by (cases c, auto)\n\nlemma of_rat_lec_add: \"of_rat_lec (c + d) = of_rat_lec c + of_rat_lec d\" \n  by (cases c; cases d, auto simp: of_rat_add)\n\nlemma of_rat_lec_zero: \"of_rat_lec 0 = 0\" \n  unfolding zero_le_constraint_def by simp\n\nlemma of_rat_lec_sum: \"of_rat_lec (sum_list c) = sum_list (map of_rat_lec c)\" \n  by (induct c, auto simp: of_rat_lec_zero of_rat_lec_add)\n\ntext \\<open>This is the main lemma: a finite set of linear constraints is \n  satisfiable over Q if and only if it is satisfiable over R.\\<close>\nlemma rat_real_conversion: assumes \"finite cs\" \n  shows \"(\\<exists> v :: rat valuation. v \\<Turnstile>\\<^sub>c\\<^sub>s cs) \\<longleftrightarrow> (\\<exists> v :: real valuation. v \\<Turnstile>\\<^sub>r\\<^sub>c\\<^sub>s cs)\" \nproof\n  show \"\\<exists>v. v \\<Turnstile>\\<^sub>c\\<^sub>s cs \\<Longrightarrow> \\<exists>v. v \\<Turnstile>\\<^sub>r\\<^sub>c\\<^sub>s cs\" using of_rat_val_constraint by auto\n  assume \"\\<exists>v. v \\<Turnstile>\\<^sub>r\\<^sub>c\\<^sub>s cs\" \n  then obtain v where *: \"v \\<Turnstile>\\<^sub>r\\<^sub>c\\<^sub>s cs\" by auto\n  show \"\\<exists>v. v \\<Turnstile>\\<^sub>c\\<^sub>s cs\" \n  proof (rule ccontr)\n    assume \"\\<nexists>v. v \\<Turnstile>\\<^sub>c\\<^sub>s cs\" \n    from farkas_coefficients[OF assms] this\n    obtain C where \"farkas_coefficients cs C\" by auto\n    from this[unfolded farkas_coefficients_def]\n    obtain d rel where\n      isleq: \"(\\<forall>(r,c) \\<in> set C. c \\<in> cs \\<and> is_le (r *R c) \\<and> r \\<noteq> 0)\" and\n      leq: \"(\\<Sum> (r,c) \\<leftarrow> C. lec_of_constraint (r *R c)) = Le_Constraint rel 0 d\" and\n      choice: \"rel = Lt_Rel \\<and> d \\<le> 0 \\<or> rel = Leq_Rel \\<and> d < 0\" by blast\n    {\n      fix r c\n      assume c: \"(r,c) \\<in> set C\" \n      from c * isleq have \"v \\<Turnstile>\\<^sub>c c\" by auto\n      hence v: \"v \\<Turnstile>\\<^sub>c (r *R c)\" by (rule sat_scale_rat_real)\n      from c isleq have \"is_le (r *R c)\" by auto\n      from lec_of_constraint_real[OF this] v \n      have \"v \\<Turnstile>\\<^sub>l\\<^sub>e of_rat_lec (lec_of_constraint (r *R c))\" by blast\n    } note v = this\n    have \"Le_Constraint rel 0 (of_rat d) = of_rat_lec (\\<Sum> (r,c) \\<leftarrow> C. lec_of_constraint (r *R c))\" \n      unfolding leq by simp\n    also have \"\\<dots> = (\\<Sum> (r,c) \\<leftarrow> C. of_rat_lec (lec_of_constraint (r *R c)))\" (is \"_ = ?sum\")\n      unfolding of_rat_lec_sum map_map o_def by (rule arg_cong[of _ _ sum_list], auto)\n    finally have leq: \"Le_Constraint rel 0 (of_rat d) = ?sum\" by simp\n    have \"v \\<Turnstile>\\<^sub>l\\<^sub>e Le_Constraint rel 0 (of_rat d)\" unfolding leq\n      by (rule satisfies_sumlist_le_constraints, insert v, auto)\n    with choice show False by (auto simp: linear_poly_sum)\n  qed\nqed\n\ntext \\<open>The main result of simplex, now using unsatisfiability over the reals.\\<close>\n\nfun i_satisfies_cs_real (infixl \"\\<Turnstile>\\<^sub>r\\<^sub>i\\<^sub>c\\<^sub>s\" 100) where\n  \"(I,v) \\<Turnstile>\\<^sub>r\\<^sub>i\\<^sub>c\\<^sub>s cs \\<longleftrightarrow> v \\<Turnstile>\\<^sub>r\\<^sub>c\\<^sub>s Simplex.restrict_to I cs\"\n\nlemma simplex_index_real:\n  \"simplex_index cs = Unsat I \\<Longrightarrow> set I \\<subseteq> fst ` set cs \\<and> \\<not> (\\<exists> v. (set I, v) \\<Turnstile>\\<^sub>r\\<^sub>i\\<^sub>c\\<^sub>s set cs) \\<and> \n     (distinct_indices cs \\<longrightarrow> (\\<forall> J \\<subset> set I. (\\<exists> v. (J, v) \\<Turnstile>\\<^sub>i\\<^sub>c\\<^sub>s set cs)))\" \\<comment> \\<open>minimal unsat core over the reals\\<close>\n  \"simplex_index cs = Sat v \\<Longrightarrow> \\<langle>v\\<rangle> \\<Turnstile>\\<^sub>c\\<^sub>s (snd ` set cs)\" \\<comment> \\<open>satisfying assingment\\<close>\n  using simplex_index(1)[of cs I] simplex_index(2)[of cs v] \n    rat_real_conversion[of \"Simplex.restrict_to (set I) (set cs)\"]\n  by auto\n\n\nlemma simplex_real:\n  \"simplex cs = Unsat I \\<Longrightarrow> \\<not> (\\<exists> v. v \\<Turnstile>\\<^sub>r\\<^sub>c\\<^sub>s set cs)\" \\<comment> \\<open>unsat of original constraints over the reals\\<close>\n  \"simplex cs = Unsat I \\<Longrightarrow> set I \\<subseteq> {0..<length cs} \\<and> \\<not> (\\<exists> v. v \\<Turnstile>\\<^sub>r\\<^sub>c\\<^sub>s {cs ! i | i. i \\<in> set I})\n    \\<and> (\\<forall>J\\<subset>set I. \\<exists>v. v \\<Turnstile>\\<^sub>c\\<^sub>s {cs ! i |i. i \\<in> J})\" \\<comment> \\<open>minimal unsat core over reals\\<close>\n  \"simplex cs = Sat v \\<Longrightarrow> \\<langle>v\\<rangle> \\<Turnstile>\\<^sub>c\\<^sub>s set cs\"  \\<comment> \\<open>satisfying assignment over the rationals\\<close>\nproof (intro simplex(1)[unfolded rat_real_conversion[OF finite_set]])\n  assume unsat: \"simplex cs = Inl I\" \n  have \"finite {cs ! i |i. i \\<in> set I}\" by auto\n  from simplex(2)[OF unsat, unfolded rat_real_conversion[OF this]]\n  show \"set I \\<subseteq> {0..<length cs} \\<and> \\<not> (\\<exists> v. v \\<Turnstile>\\<^sub>r\\<^sub>c\\<^sub>s {cs ! i | i. i \\<in> set I})\n    \\<and> (\\<forall>J\\<subset>set I. \\<exists>v. v \\<Turnstile>\\<^sub>c\\<^sub>s {cs ! i |i. i \\<in> J})\" by auto\nqed (insert simplex(3), auto)\n\ntext \\<open>Define notion of minimal unsat core over the reals:\n  the subset has to be unsat over the reals, and every proper subset has\n  to be satisfiable over the rational numbers.\\<close>\n\ndefinition minimal_unsat_core_real :: \"'i set \\<Rightarrow> 'i i_constraint list \\<Rightarrow> bool\" where\n  \"minimal_unsat_core_real I ics  = ((I \\<subseteq> fst ` set ics) \\<and> (\\<not> (\\<exists> v. (I,v) \\<Turnstile>\\<^sub>r\\<^sub>i\\<^sub>c\\<^sub>s set ics))\n     \\<and> (distinct_indices ics \\<longrightarrow> (\\<forall> J. J \\<subset> I \\<longrightarrow> (\\<exists> v. (J,v) \\<Turnstile>\\<^sub>i\\<^sub>c\\<^sub>s set ics))))\"\n\ntext \\<open>Because of equi-satisfiability the two notions of minimal unsat cores coincide.\\<close>\nlemma minimal_unsat_core_real_conv: \"minimal_unsat_core_real I ics = minimal_unsat_core I ics\" \nproof \n  show \"minimal_unsat_core_real I ics \\<Longrightarrow> minimal_unsat_core I ics\" \n    unfolding minimal_unsat_core_real_def minimal_unsat_core_def\n    using of_rat_val_constraint by simp metis\nnext\n  assume \"minimal_unsat_core I ics\"     \n  thus \"minimal_unsat_core_real I ics\" \n    unfolding minimal_unsat_core_real_def minimal_unsat_core_def\n    using rat_real_conversion[of \"Simplex.restrict_to I (set ics)\"]\n    by auto\nqed\n\ntext \\<open>Easy consequence: The incremental simplex algorithm is also sound wrt. \n  minimal-unsat-cores over the reals.\\<close>\nlemmas incremental_simplex_real = \n  init_simplex\n  assert_simplex_ok\n  assert_simplex_unsat[folded minimal_unsat_core_real_conv]\n  assert_all_simplex_ok\n  assert_all_simplex_unsat[folded minimal_unsat_core_real_conv]\n  check_simplex_ok\n  check_simplex_unsat[folded minimal_unsat_core_real_conv]\n  solution_simplex\n  backtrack_simplex\n  checked_invariant_simplex\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/Farkas/Simplex_for_Reals.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.831143031127974, "lm_q2_score": 0.8519527982093666, "lm_q1q2_score": 0.7080946310816922}}
{"text": "theory DeterministicRelation3\n  imports PartialOrderRelation3\nbegin\n\ntext \"Deterministic relation of three inputs\"\n\ndefinition determ :: \"('a \\<Rightarrow> 'b \\<Rightarrow> 'c \\<Rightarrow> bool) \\<Rightarrow> bool\"\n  where\n\"determ r = (\\<forall>f a b c. r f a b \\<and> r f a c \\<longrightarrow> b = c)\"\n\nlemma determD:\n  \"\\<lbrakk>determ r; r f a b; r f a c\\<rbrakk> \\<Longrightarrow> b = c\" \n  unfolding determ_def\n  by blast\n\ntext \"Any relation that is less than or equal to a deterministic relation is also deterministic\"\n\nlemma determ_rel_leqD:\n  \"\\<lbrakk>rel_leq f g; determ g\\<rbrakk> \\<Longrightarrow> determ f\"\n  unfolding determ_def\n  apply clarsimp\n  apply (drule (1) rel_leqD[rotated 1]; simp?)\n  apply (drule (1) rel_leqD[rotated 1]; simp?)\n  done\n\nend", "meta": {"author": "zilinc", "repo": "popl23-artefact", "sha": "1fe1490d2d34f93dc01ada940c160477db3b9b72", "save_path": "github-repos/isabelle/zilinc-popl23-artefact", "path": "github-repos/isabelle/zilinc-popl23-artefact/popl23-artefact-1fe1490d2d34f93dc01ada940c160477db3b9b72/arrays/loops/DeterministicRelation3.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9046505299595162, "lm_q2_score": 0.7826624789529375, "lm_q1q2_score": 0.7080360263642036}}
{"text": "theory Automation\n  imports Main\nbegin\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  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\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/Automation.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505248181418, "lm_q2_score": 0.7826624789529375, "lm_q1q2_score": 0.7080360223402428}}
{"text": "(*\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\nsection \\<open>\\<open>Complex_Inner_Product\\<close> -- Complex Inner Product Spaces\\<close>\n\ntheory Complex_Inner_Product\n  imports\n    Complex_Inner_Product0\nbegin\n\nsubsection \\<open>Complex inner product spaces\\<close>\n\nunbundle cinner_syntax\n\nlemma cinner_real: \"cinner x x \\<in> \\<real>\"\n  by (simp add: cdot_square_norm)\n\nlemmas cinner_commute' [simp] = cinner_commute[symmetric]\n\nlemma (in complex_inner) cinner_eq_flip: \\<open>(cinner x y = cinner z w) \\<longleftrightarrow> (cinner y x = cinner w z)\\<close>\n  by (metis cinner_commute)\n\nlemma Im_cinner_x_x[simp]: \"Im (x \\<bullet>\\<^sub>C x) = 0\"\n  using comp_Im_same[OF cinner_ge_zero] by simp\n\n\nlemma of_complex_inner_1' [simp]:\n  \"cinner (1 :: 'a :: {complex_inner, complex_normed_algebra_1}) (of_complex x) = x\"\n  by (metis cinner_commute complex_cnj_cnj of_complex_inner_1)\n\n\nclass chilbert_space =  complex_inner + complete_space\nbegin\nsubclass cbanach by standard\nend\n\ninstantiation complex :: \"chilbert_space\" begin\ninstance ..\nend\n\nsubsection \\<open>Misc facts\\<close>\n\nlemma cinner_scaleR_left [simp]: \"cinner (scaleR r x) y = of_real r * (cinner x y)\"\n  by (simp add: scaleR_scaleC)\n\nlemma cinner_scaleR_right [simp]: \"cinner x (scaleR r y) = of_real r * (cinner x y)\"\n  by (simp add: scaleR_scaleC)\n\ntext \\<open>This is a useful rule for establishing the equality of vectors\\<close>\nlemma cinner_extensionality:\n  assumes \\<open>\\<And>\\<gamma>. \\<gamma> \\<bullet>\\<^sub>C \\<psi> = \\<gamma> \\<bullet>\\<^sub>C \\<phi>\\<close>\n  shows \\<open>\\<psi> = \\<phi>\\<close>\n  by (metis assms cinner_eq_zero_iff cinner_simps(3) right_minus_eq)\n\nlemma polar_identity:\n  includes notation_norm\n  shows \\<open>\\<parallel>x + y\\<parallel>^2 = \\<parallel>x\\<parallel>^2 + \\<parallel>y\\<parallel>^2 + 2 * Re (x \\<bullet>\\<^sub>C y)\\<close>\n    \\<comment> \\<open>Shown in the proof of Corollary 1.5 in \\<^cite>\\<open>conway2013course\\<close>\\<close>\nproof -\n  have \\<open>(x \\<bullet>\\<^sub>C y) + (y \\<bullet>\\<^sub>C x) = (x \\<bullet>\\<^sub>C y) + cnj (x \\<bullet>\\<^sub>C y)\\<close>\n    by simp\n  hence \\<open>(x \\<bullet>\\<^sub>C y) + (y \\<bullet>\\<^sub>C x) = 2 * Re (x \\<bullet>\\<^sub>C y) \\<close>\n    using complex_add_cnj by presburger\n  have \\<open>\\<parallel>x + y\\<parallel>^2 = (x+y) \\<bullet>\\<^sub>C (x+y)\\<close>\n    by (simp add: cdot_square_norm)\n  hence \\<open>\\<parallel>x + y\\<parallel>^2 = (x \\<bullet>\\<^sub>C x) + (x \\<bullet>\\<^sub>C y) + (y \\<bullet>\\<^sub>C x) + (y \\<bullet>\\<^sub>C y)\\<close>\n    by (simp add: cinner_add_left cinner_add_right)\n  thus ?thesis using  \\<open>(x \\<bullet>\\<^sub>C y) + (y \\<bullet>\\<^sub>C x) = 2 * Re (x \\<bullet>\\<^sub>C y)\\<close>\n    by (smt (verit, ccfv_SIG) Re_complex_of_real plus_complex.simps(1) power2_norm_eq_cinner')\nqed\n\nlemma polar_identity_minus:\n  includes notation_norm\n  shows \\<open>\\<parallel>x - y\\<parallel>^2 = \\<parallel>x\\<parallel>^2 + \\<parallel>y\\<parallel>^2 - 2 * Re (x \\<bullet>\\<^sub>C y)\\<close>\nproof-\n  have \\<open>\\<parallel>x + (-y)\\<parallel>^2 = \\<parallel>x\\<parallel>^2 + \\<parallel>-y\\<parallel>^2 + 2 * Re (x \\<bullet>\\<^sub>C -y)\\<close>\n    using polar_identity by blast\n  hence \\<open>\\<parallel>x - y\\<parallel>^2 = \\<parallel>x\\<parallel>^2 + \\<parallel>y\\<parallel>^2 - 2*Re (x \\<bullet>\\<^sub>C y)\\<close>\n    by simp\n  thus ?thesis\n    by blast\nqed\n\nproposition parallelogram_law:\n  includes notation_norm\n  fixes x y :: \"'a::complex_inner\"\n  shows \\<open>\\<parallel>x+y\\<parallel>^2 + \\<parallel>x-y\\<parallel>^2 = 2*( \\<parallel>x\\<parallel>^2 + \\<parallel>y\\<parallel>^2 )\\<close>\n    \\<comment> \\<open>Shown in the proof of Theorem 2.3 in \\<^cite>\\<open>conway2013course\\<close>\\<close>\n  by (simp add: polar_identity_minus polar_identity)\n\n\ntheorem pythagorean_theorem:\n  includes notation_norm\n  shows \\<open>(x \\<bullet>\\<^sub>C y) = 0 \\<Longrightarrow> \\<parallel> x + y \\<parallel>^2 = \\<parallel> x \\<parallel>^2 + \\<parallel> y \\<parallel>^2\\<close>\n    \\<comment> \\<open>Shown in the proof of Theorem 2.2 in \\<^cite>\\<open>conway2013course\\<close>\\<close>\n  by (simp add: polar_identity)\n\nlemma pythagorean_theorem_sum:\n  assumes q1: \"\\<And>a a'. a \\<in> t \\<Longrightarrow> a' \\<in> t \\<Longrightarrow> a \\<noteq> a' \\<Longrightarrow> f a \\<bullet>\\<^sub>C f a' = 0\"\n    and q2: \"finite t\"\n  shows \"(norm  (\\<Sum>a\\<in>t. f a))^2 = (\\<Sum>a\\<in>t.(norm (f a))^2)\"\nproof (insert q1, use q2 in induction)\n  case empty\n  show ?case\n    by auto\nnext\n  case (insert x F)\n  have r1: \"f x \\<bullet>\\<^sub>C f a = 0\"\n    if \"a \\<in> F\"\n    for a\n    using that insert.hyps(2) insert.prems by auto\n  have \"sum f F = (\\<Sum>a\\<in>F. f a)\"\n    by simp\n  hence s4: \"f x \\<bullet>\\<^sub>C sum f F = f x \\<bullet>\\<^sub>C (\\<Sum>a\\<in>F. f a)\"\n    by simp\n  also have s3: \"\\<dots> = (\\<Sum>a\\<in>F. f x \\<bullet>\\<^sub>C f a)\"\n    using cinner_sum_right by auto\n  also have s2: \"\\<dots> = (\\<Sum>a\\<in>F. 0)\"\n    using r1\n    by simp\n  also have s1: \"\\<dots> = 0\"\n    by simp\n  finally have xF_ortho: \"f x \\<bullet>\\<^sub>C sum f F = 0\"\n    using s2 s3 by auto\n  have \"(norm (sum f (insert x F)))\\<^sup>2 = (norm (f x + sum f F))\\<^sup>2\"\n    by (simp add: insert.hyps(1) insert.hyps(2))\n  also have \"\\<dots> = (norm (f x))\\<^sup>2 + (norm (sum f F))\\<^sup>2\"\n    using xF_ortho by (rule pythagorean_theorem)\n  also have \"\\<dots> = (norm (f x))\\<^sup>2 + (\\<Sum>a\\<in>F.(norm (f a))^2)\"\n    apply (subst insert.IH) using insert.prems by auto\n  also have \"\\<dots> = (\\<Sum>a\\<in>insert x F.(norm (f a))^2)\"\n    by (simp add: insert.hyps(1) insert.hyps(2))\n  finally show ?case\n    by simp\nqed\n\n\nlemma Cauchy_cinner_Cauchy:\n  fixes x y :: \\<open>nat \\<Rightarrow> 'a::complex_inner\\<close>\n  assumes a1: \\<open>Cauchy x\\<close> and a2: \\<open>Cauchy y\\<close>\n  shows \\<open>Cauchy (\\<lambda> n. x n \\<bullet>\\<^sub>C y n)\\<close>\nproof-\n  have \\<open>bounded (range x)\\<close>\n    using a1\n    by (simp add: Elementary_Metric_Spaces.cauchy_imp_bounded)\n  hence b1: \\<open>\\<exists>M. \\<forall>n. norm (x n) < M\\<close>\n    by (meson bounded_pos_less rangeI)\n  have \\<open>bounded (range y)\\<close>\n    using a2\n    by (simp add: Elementary_Metric_Spaces.cauchy_imp_bounded)\n  hence b2: \\<open>\\<exists> M. \\<forall> n. norm (y n) < M\\<close>\n    by (meson bounded_pos_less rangeI)\n  have \\<open>\\<exists>M. \\<forall>n. norm (x n) < M \\<and> norm (y n) < M\\<close>\n    using b1 b2\n    by (metis dual_order.strict_trans linorder_neqE_linordered_idom)\n  then obtain M where M1: \\<open>\\<And>n. norm (x n) < M\\<close> and M2: \\<open>\\<And>n. norm (y n) < M\\<close>\n    by blast\n  have M3: \\<open>M > 0\\<close>\n    by (smt M2 norm_not_less_zero)\n  have \\<open>\\<exists>N. \\<forall>n \\<ge> N. \\<forall>m \\<ge> N. norm ( (\\<lambda> i. x i \\<bullet>\\<^sub>C y i) n -  (\\<lambda> i. x i \\<bullet>\\<^sub>C y i) m ) < e\\<close>\n    if \"e > 0\" for e\n  proof-\n    have \\<open>e / (2*M) > 0\\<close>\n      using M3\n      by (simp add: that)\n    hence \\<open>\\<exists>N. \\<forall>n\\<ge>N. \\<forall>m\\<ge>N. norm (x n - x m) < e / (2*M)\\<close>\n      using a1\n      by (simp add: Cauchy_iff)\n    then obtain N1 where N1_def: \\<open>\\<And>n m. n\\<ge>N1 \\<Longrightarrow> m\\<ge>N1 \\<Longrightarrow> norm (x n - x m) < e / (2*M)\\<close>\n      by blast\n    have x1: \\<open>\\<exists>N. \\<forall> n\\<ge>N. \\<forall> m\\<ge>N. norm (y n - y m) < e / (2*M)\\<close>\n      using a2 \\<open>e / (2*M) > 0\\<close>\n      by (simp add: Cauchy_iff)\n    obtain N2 where N2_def: \\<open>\\<And>n m.  n\\<ge>N2 \\<Longrightarrow> m\\<ge>N2 \\<Longrightarrow> norm (y n - y m) < e / (2*M)\\<close>\n      using x1\n      by blast\n    define N where N_def: \\<open>N = N1 + N2\\<close>\n    hence \\<open>N \\<ge> N1\\<close>\n      by auto\n    have \\<open>N \\<ge> N2\\<close>\n      using N_def\n      by auto\n    have \\<open>norm (x n \\<bullet>\\<^sub>C y n - x m \\<bullet>\\<^sub>C y m) < e\\<close>\n      if \\<open>n \\<ge> N\\<close> and \\<open>m \\<ge> N\\<close>\n      for n m\n    proof -\n      have \\<open>x n \\<bullet>\\<^sub>C y n - x m \\<bullet>\\<^sub>C y m = (x n \\<bullet>\\<^sub>C y n - x m \\<bullet>\\<^sub>C y n) + (x m \\<bullet>\\<^sub>C y n - x m \\<bullet>\\<^sub>C y m)\\<close>\n        by simp\n      hence y1: \\<open>norm (x n \\<bullet>\\<^sub>C y n - x m \\<bullet>\\<^sub>C y m) \\<le> norm (x n \\<bullet>\\<^sub>C y n - x m \\<bullet>\\<^sub>C y n)\n           + norm (x m \\<bullet>\\<^sub>C y n - x m \\<bullet>\\<^sub>C y m)\\<close>\n        by (metis norm_triangle_ineq)\n\n      have \\<open>x n \\<bullet>\\<^sub>C y n - x m \\<bullet>\\<^sub>C y n = (x n - x m) \\<bullet>\\<^sub>C y n\\<close>\n        by (simp add: cinner_diff_left)\n      hence \\<open>norm (x n \\<bullet>\\<^sub>C y n - x m \\<bullet>\\<^sub>C y n) = norm ((x n - x m) \\<bullet>\\<^sub>C y n)\\<close>\n        by simp\n      moreover have \\<open>norm ((x n - x m) \\<bullet>\\<^sub>C y n) \\<le> norm (x n - x m) * norm (y n)\\<close>\n        using complex_inner_class.Cauchy_Schwarz_ineq2 by blast\n      moreover have \\<open>norm (y n) < M\\<close>\n        by (simp add: M2)\n      moreover have \\<open>norm (x n - x m) < e/(2*M)\\<close>\n        using \\<open>N \\<le> m\\<close> \\<open>N \\<le> n\\<close> \\<open>N1 \\<le> N\\<close> N1_def by auto\n      ultimately have \\<open>norm ((x n \\<bullet>\\<^sub>C y n) - (x m \\<bullet>\\<^sub>C y n)) < (e/(2*M)) * M\\<close>\n        by (smt linordered_semiring_strict_class.mult_strict_mono norm_ge_zero)\n      moreover have \\<open> (e/(2*M)) * M = e/2\\<close>\n        using \\<open>M > 0\\<close> by simp\n      ultimately have  \\<open>norm ((x n \\<bullet>\\<^sub>C y n) - (x m \\<bullet>\\<^sub>C y n)) < e/2\\<close>\n        by simp\n      hence y2: \\<open>norm (x n \\<bullet>\\<^sub>C y n - x m \\<bullet>\\<^sub>C y n) < e/2\\<close>\n        by blast\n      have \\<open>x m \\<bullet>\\<^sub>C y n - x m \\<bullet>\\<^sub>C y m = x m \\<bullet>\\<^sub>C (y n - y m)\\<close>\n        by (simp add: cinner_diff_right)\n      hence \\<open>norm ((x m \\<bullet>\\<^sub>C y n) - (x m \\<bullet>\\<^sub>C y m)) = norm (x m \\<bullet>\\<^sub>C (y n - y m))\\<close>\n        by simp\n      moreover have \\<open>norm (x m \\<bullet>\\<^sub>C (y n - y m)) \\<le> norm (x m) * norm (y n - y m)\\<close>\n        by (meson complex_inner_class.Cauchy_Schwarz_ineq2)\n      moreover have \\<open>norm (x m) < M\\<close>\n        by (simp add: M1)\n      moreover have \\<open>norm (y n - y m) < e/(2*M)\\<close>\n        using \\<open>N \\<le> m\\<close> \\<open>N \\<le> n\\<close> \\<open>N2 \\<le> N\\<close> N2_def by auto\n      ultimately have \\<open>norm ((x m \\<bullet>\\<^sub>C y n) - (x m \\<bullet>\\<^sub>C y m)) < M * (e/(2*M))\\<close>\n        by (smt linordered_semiring_strict_class.mult_strict_mono norm_ge_zero)\n      moreover have \\<open>M * (e/(2*M)) = e/2\\<close>\n        using \\<open>M > 0\\<close> by simp\n      ultimately have  \\<open>norm ((x m \\<bullet>\\<^sub>C y n) - (x m \\<bullet>\\<^sub>C y m)) < e/2\\<close>\n        by simp\n      hence y3: \\<open>norm ((x m \\<bullet>\\<^sub>C y n) - (x m \\<bullet>\\<^sub>C y m)) < e/2\\<close>\n        by blast\n      show \\<open>norm ( (x n \\<bullet>\\<^sub>C y n) - (x m \\<bullet>\\<^sub>C y m) ) < e\\<close>\n        using y1 y2 y3 by simp\n    qed\n    thus ?thesis by blast\n  qed\n  thus ?thesis\n    by (simp add: CauchyI)\nqed\n\n\nlemma cinner_sup_norm: \\<open>norm \\<psi> = (SUP \\<phi>. cmod (cinner \\<phi> \\<psi>) / norm \\<phi>)\\<close>\nproof (rule sym, rule cSup_eq_maximum)\n  have \\<open>norm \\<psi> = cmod (cinner \\<psi> \\<psi>) / norm \\<psi>\\<close>\n    by (metis norm_eq_sqrt_cinner norm_ge_zero real_div_sqrt)\n  then show \\<open>norm \\<psi> \\<in> range (\\<lambda>\\<phi>. cmod (cinner \\<phi> \\<psi>) / norm \\<phi>)\\<close>\n    by blast\nnext\n  fix n assume \\<open>n \\<in> range (\\<lambda>\\<phi>. cmod (cinner \\<phi> \\<psi>) / norm \\<phi>)\\<close>\n  then obtain \\<phi> where n\\<phi>: \\<open>n = cmod (cinner \\<phi> \\<psi>) / norm \\<phi>\\<close>\n    by auto\n  show \\<open>n \\<le> norm \\<psi>\\<close>\n    unfolding n\\<phi>\n    by (simp add: complex_inner_class.Cauchy_Schwarz_ineq2 divide_le_eq ordered_field_class.sign_simps(33))\nqed\n\nlemma cinner_sup_onorm:\n  fixes A :: \\<open>'a::{real_normed_vector,not_singleton} \\<Rightarrow> 'b::complex_inner\\<close>\n  assumes \\<open>bounded_linear A\\<close>\n  shows \\<open>onorm A = (SUP (\\<psi>,\\<phi>). cmod (cinner \\<psi> (A \\<phi>)) / (norm \\<psi> * norm \\<phi>))\\<close>\nproof (unfold onorm_def, rule cSup_eq_cSup)\n  show \\<open>bdd_above (range (\\<lambda>x. norm (A x) / norm x))\\<close>\n    by (meson assms bdd_aboveI2 le_onorm)\nnext\n  fix a\n  assume \\<open>a \\<in> range (\\<lambda>\\<phi>. norm (A \\<phi>) / norm \\<phi>)\\<close>\n  then obtain \\<phi> where \\<open>a = norm (A \\<phi>) / norm \\<phi>\\<close>\n    by auto\n  then have \\<open>a \\<le> cmod (cinner (A \\<phi>) (A \\<phi>)) / (norm (A \\<phi>) * norm \\<phi>)\\<close>\n    apply auto\n    by (smt (verit) divide_divide_eq_left norm_eq_sqrt_cinner norm_imp_pos_and_ge real_div_sqrt)\n  then show \\<open>\\<exists>b\\<in>range (\\<lambda>(\\<psi>, \\<phi>). cmod (cinner \\<psi> (A \\<phi>)) / (norm \\<psi> * norm \\<phi>)). a \\<le> b\\<close>\n    by force\nnext\n  fix b\n  assume \\<open>b \\<in> range (\\<lambda>(\\<psi>, \\<phi>). cmod (cinner \\<psi> (A \\<phi>)) / (norm \\<psi> * norm \\<phi>))\\<close>\n  then obtain \\<psi> \\<phi> where b: \\<open>b = cmod (cinner \\<psi> (A \\<phi>)) / (norm \\<psi> * norm \\<phi>)\\<close>\n    by auto\n  then have \\<open>b \\<le> norm (A \\<phi>) / norm \\<phi>\\<close>\n    apply auto\n    by (smt (verit, ccfv_threshold) complex_inner_class.Cauchy_Schwarz_ineq2 division_ring_divide_zero linordered_field_class.divide_right_mono mult_cancel_left1 nonzero_mult_divide_mult_cancel_left2 norm_imp_pos_and_ge ordered_field_class.sign_simps(33) zero_le_divide_iff)\n  then show \\<open>\\<exists>a\\<in>range (\\<lambda>x. norm (A x) / norm x). b \\<le> a\\<close>\n    by auto\nqed\n\n\nlemma sum_cinner:\n  fixes f :: \"'a \\<Rightarrow> 'b::complex_inner\"\n  shows \"cinner (sum f A) (sum g B) = (\\<Sum>i\\<in>A. \\<Sum>j\\<in>B. cinner (f i) (g j))\"\n  by (simp add: cinner_sum_right cinner_sum_left) (rule sum.swap)\n\nlemma Cauchy_cinner_product_summable':\n  fixes a b :: \"nat \\<Rightarrow> 'a::complex_inner\"\n  shows \\<open>(\\<lambda>(x, y). cinner (a x) (b y)) summable_on UNIV \\<longleftrightarrow> (\\<lambda>(x, y). cinner (a y) (b (x - y))) summable_on {(k, i). i \\<le> k}\\<close>\nproof -\n  have img: \\<open>(\\<lambda>(k::nat, i). (i, k - i)) ` {(k, i). i \\<le> k} = UNIV\\<close>\n    apply (auto simp: image_def)\n    by (metis add.commute add_diff_cancel_right' diff_le_self)\n  have inj: \\<open>inj_on (\\<lambda>(k::nat, i). (i, k - i)) {(k, i). i \\<le> k}\\<close>\n    by (smt (verit, del_insts) Pair_inject case_prodE case_prod_conv eq_diff_iff inj_onI mem_Collect_eq)\n\n  have \\<open>(\\<lambda>(x, y). cinner (a x) (b y)) summable_on UNIV \\<longleftrightarrow> (\\<lambda>(k, l). cinner (a k) (b l)) summable_on (\\<lambda>(k, i). (i, k - i)) ` {(k, i). i \\<le> k}\\<close>\n    by (simp only: img)\n  also have \\<open>\\<dots> \\<longleftrightarrow> ((\\<lambda>(k, l). cinner (a k) (b l)) \\<circ> (\\<lambda>(k, i). (i, k - i))) summable_on {(k, i). i \\<le> k}\\<close>\n    using inj by (rule summable_on_reindex)\n  also have \\<open>\\<dots> \\<longleftrightarrow> (\\<lambda>(x, y). cinner (a y) (b (x - y))) summable_on {(k, i). i \\<le> k}\\<close>\n    by (simp add: o_def case_prod_unfold)\n  finally show ?thesis\n    by -\nqed\n\ninstantiation prod :: (complex_inner, complex_inner) complex_inner\nbegin\n\ndefinition cinner_prod_def:\n  \"cinner x y = cinner (fst x) (fst y) + cinner (snd x) (snd y)\"\n\ninstance\nproof\n  fix r :: complex\n  fix x y z :: \"'a::complex_inner \\<times> 'b::complex_inner\"\n  show \"cinner x y = cnj (cinner y x)\"\n    unfolding cinner_prod_def\n    by simp\n  show \"cinner (x + y) z = cinner x z + cinner y z\"\n    unfolding cinner_prod_def\n    by (simp add: cinner_add_left)\n  show \"cinner (scaleC r x) y = cnj r * cinner x y\"\n    unfolding cinner_prod_def\n    by (simp add: distrib_left)\n  show \"0 \\<le> cinner x x\"\n    unfolding cinner_prod_def\n    by (intro add_nonneg_nonneg cinner_ge_zero)\n  show \"cinner x x = 0 \\<longleftrightarrow> x = 0\"\n    unfolding cinner_prod_def prod_eq_iff\n    by (metis antisym cinner_eq_zero_iff cinner_ge_zero fst_zero le_add_same_cancel2 snd_zero verit_sum_simplify)\n  show \"norm x = sqrt (cmod (cinner x x))\"\n    unfolding norm_prod_def cinner_prod_def\n    by (metis (no_types, lifting) Re_complex_of_real add_nonneg_nonneg cinner_ge_zero complex_of_real_cmod plus_complex.simps(1) power2_norm_eq_cinner')\nqed\n\nend\n\nlemma sgn_cinner[simp]: \\<open>sgn \\<psi> \\<bullet>\\<^sub>C \\<psi> = norm \\<psi>\\<close>\n  apply (cases \\<open>\\<psi> = 0\\<close>)\n   apply (auto simp: sgn_div_norm)\n  by (smt (verit, ccfv_SIG) cinner_scaleR_left cinner_scaleR_right cnorm_eq cnorm_eq_1 complex_of_real_cmod complex_of_real_nn_iff left_inverse mult.right_neutral mult_scaleR_right norm_eq_zero norm_not_less_zero norm_one of_real_def of_real_eq_iff)\n\ninstance prod :: (chilbert_space, chilbert_space) chilbert_space..\n\nsubsection \\<open>Orthogonality\\<close>\n\ndefinition \"orthogonal_complement S = {x| x. \\<forall>y\\<in>S. cinner x y = 0}\"\n\nlemma orthogonal_complement_orthoI:\n  \\<open>x \\<in> orthogonal_complement M \\<Longrightarrow> y \\<in> M \\<Longrightarrow> x \\<bullet>\\<^sub>C y = 0\\<close>\n  unfolding orthogonal_complement_def by auto\n\nlemma orthogonal_complement_orthoI':\n  \\<open>x \\<in> M \\<Longrightarrow> y \\<in> orthogonal_complement M \\<Longrightarrow> x \\<bullet>\\<^sub>C y = 0\\<close>\n  by (metis cinner_commute' complex_cnj_zero orthogonal_complement_orthoI)\n\nlemma orthogonal_complementI:\n  \\<open>(\\<And>x. x \\<in> M \\<Longrightarrow> y \\<bullet>\\<^sub>C x = 0) \\<Longrightarrow> y \\<in> orthogonal_complement M\\<close>\n  unfolding orthogonal_complement_def\n  by simp\n\nabbreviation is_orthogonal::\\<open>'a::complex_inner \\<Rightarrow> 'a \\<Rightarrow> bool\\<close>  where\n  \\<open>is_orthogonal x y \\<equiv> x \\<bullet>\\<^sub>C y = 0\\<close>\n\nbundle orthogonal_notation begin\nnotation is_orthogonal (infixl \"\\<bottom>\" 69)\nend\n\nbundle no_orthogonal_notation begin\nno_notation is_orthogonal (infixl \"\\<bottom>\" 69)\nend\n\n\nlemma is_orthogonal_sym: \"is_orthogonal \\<psi> \\<phi> = is_orthogonal \\<phi> \\<psi>\"\n  by (metis cinner_commute' complex_cnj_zero)\n\nlemma is_orthogonal_sgn_right[simp]: \\<open>is_orthogonal e (sgn f) \\<longleftrightarrow> is_orthogonal e f\\<close>\nproof (cases \\<open>f = 0\\<close>)\n  case True\n  then show ?thesis\n    by simp\nnext\n  case False\n  have \\<open>cinner e (sgn f) = cinner e f / norm f\\<close>\n    by (simp add: sgn_div_norm divide_inverse scaleR_scaleC)\n  moreover have \\<open>norm f \\<noteq> 0\\<close>\n    by (simp add: False)\n  ultimately show ?thesis\n    by force\nqed\n\nlemma is_orthogonal_sgn_left[simp]: \\<open>is_orthogonal (sgn e) f \\<longleftrightarrow> is_orthogonal e f\\<close>\n  by (simp add: is_orthogonal_sym)\n\nlemma orthogonal_complement_closed_subspace[simp]:\n  \"closed_csubspace (orthogonal_complement A)\"\n  for A :: \\<open>('a::complex_inner) set\\<close>\nproof (intro closed_csubspace.intro complex_vector.subspaceI)\n  fix x y and c\n  show \\<open>0 \\<in> orthogonal_complement A\\<close>\n    by (rule orthogonal_complementI, simp)\n  show \\<open>x + y \\<in> orthogonal_complement A\\<close>\n    if \\<open>x \\<in> orthogonal_complement A\\<close> and \\<open>y \\<in> orthogonal_complement A\\<close>\n    using that by (auto intro!: orthogonal_complementI dest!: orthogonal_complement_orthoI\n        simp add: cinner_add_left)\n  show \\<open>c *\\<^sub>C x \\<in> orthogonal_complement A\\<close> if \\<open>x \\<in> orthogonal_complement A\\<close>\n    using that by (auto intro!: orthogonal_complementI dest!: orthogonal_complement_orthoI)\n\n  show \"closed (orthogonal_complement A)\"\n  proof (auto simp add: closed_sequential_limits, rename_tac an a)\n    fix an a\n    assume ortho: \\<open>\\<forall>n::nat. an n \\<in> orthogonal_complement A\\<close>\n    assume lim: \\<open>an \\<longlonglongrightarrow> a\\<close>\n\n    have \\<open>\\<forall> y \\<in> A. \\<forall> n. is_orthogonal y (an n)\\<close>\n      using orthogonal_complement_orthoI'\n      by (simp add: orthogonal_complement_orthoI' ortho)\n    moreover have \\<open>isCont (\\<lambda> x. y \\<bullet>\\<^sub>C x) a\\<close> for y\n      using bounded_clinear_cinner_right clinear_continuous_at\n      by (simp add: clinear_continuous_at bounded_clinear_cinner_right)\n    ultimately have \\<open>(\\<lambda> n. (\\<lambda> v. y \\<bullet>\\<^sub>C v) (an n)) \\<longlonglongrightarrow> (\\<lambda> v. y \\<bullet>\\<^sub>C v) a\\<close> for y\n      using isCont_tendsto_compose\n      by (simp add: isCont_tendsto_compose lim)\n    hence  \\<open>\\<forall> y\\<in>A. (\\<lambda> n. y \\<bullet>\\<^sub>C an n) \\<longlonglongrightarrow>  y \\<bullet>\\<^sub>C a\\<close>\n      by simp\n    hence  \\<open>\\<forall> y\\<in>A. (\\<lambda> n. 0) \\<longlonglongrightarrow>  y \\<bullet>\\<^sub>C a\\<close>\n      using \\<open>\\<forall> y \\<in> A. \\<forall> n. is_orthogonal y (an n)\\<close>\n      by fastforce\n    hence  \\<open>\\<forall> y \\<in> A. is_orthogonal y a\\<close>\n      using limI by fastforce\n    then show \\<open>a \\<in> orthogonal_complement A\\<close>\n      by (simp add: orthogonal_complementI is_orthogonal_sym)\n  qed\nqed\n\nlemma orthogonal_complement_zero_intersection:\n  assumes \"0\\<in>M\"\n  shows \\<open>M \\<inter> (orthogonal_complement M) = {0}\\<close>\nproof -\n  have \"x=0\" if \"x\\<in>M\" and \"x\\<in>orthogonal_complement M\" for x\n  proof -\n    from that have \"is_orthogonal x x\"\n      unfolding orthogonal_complement_def by auto\n    thus \"x=0\"\n      by auto\n  qed\n  with assms show ?thesis\n    unfolding orthogonal_complement_def by auto\nqed\n\nlemma is_orthogonal_closure_cspan:\n  assumes \"\\<And>x y. x \\<in> X \\<Longrightarrow> y \\<in> Y \\<Longrightarrow> is_orthogonal x y\"\n  assumes \\<open>x \\<in> closure (cspan X)\\<close> \\<open>y \\<in> closure (cspan Y)\\<close>\n  shows \"is_orthogonal x y\"\nproof -\n  have *: \\<open>cinner x y = 0\\<close> if \\<open>y \\<in> Y\\<close> for y\n    using bounded_antilinear_cinner_left apply (rule bounded_antilinear_eq_on[where G=X])\n    using assms that by auto\n  show \\<open>cinner x y = 0\\<close>\n    using bounded_clinear_cinner_right apply (rule bounded_clinear_eq_on[where G=Y])\n    using * assms by auto\nqed\n\n\ninstantiation ccsubspace :: (complex_inner) \"uminus\"\nbegin\nlift_definition uminus_ccsubspace::\\<open>'a ccsubspace  \\<Rightarrow> 'a ccsubspace\\<close>\n  is \\<open>orthogonal_complement\\<close>\n  by simp\n\ninstance ..\nend\n\nlemma orthocomplement_top[simp]: \\<open>- top = (bot :: 'a::complex_inner ccsubspace)\\<close>\n  \\<comment> \\<open>For \\<^typ>\\<open>'a\\<close> of sort \\<^class>\\<open>chilbert_space\\<close>, this is covered by @{thm [source] orthocomplemented_lattice_class.compl_top_eq} already.\n      But here we give it a wider sort.\\<close>\n  apply transfer\n  by (metis Int_UNIV_left UNIV_I orthogonal_complement_zero_intersection)\n\ninstantiation ccsubspace :: (complex_inner) minus begin\nlift_definition minus_ccsubspace :: \"'a ccsubspace \\<Rightarrow> 'a ccsubspace \\<Rightarrow> 'a ccsubspace\"\n  is \"\\<lambda>A B. A \\<inter> (orthogonal_complement B)\"\n  by simp\ninstance..\nend\n\ndefinition is_ortho_set :: \"'a::complex_inner set \\<Rightarrow> bool\" where\n  \\<comment> \\<open>Orthogonal set\\<close>\n  \\<open>is_ortho_set S = ((\\<forall>x\\<in>S. \\<forall>y\\<in>S. x \\<noteq> y \\<longrightarrow> (x \\<bullet>\\<^sub>C y) = 0) \\<and> 0 \\<notin> S)\\<close>\n\ndefinition is_onb where \\<open>is_onb E \\<longleftrightarrow> is_ortho_set E \\<and> (\\<forall>b\\<in>E. norm b = 1) \\<and> ccspan E = top\\<close>\n\nlemma is_ortho_set_empty[simp]: \"is_ortho_set {}\"\n  unfolding is_ortho_set_def by auto\n\nlemma is_ortho_set_antimono: \\<open>A \\<subseteq> B \\<Longrightarrow> is_ortho_set B \\<Longrightarrow> is_ortho_set A\\<close>\n  unfolding is_ortho_set_def by auto\n\nlemma orthogonal_complement_of_closure:\n  fixes A ::\"('a::complex_inner) set\"\n  shows \"orthogonal_complement A = orthogonal_complement (closure A)\"\nproof-\n  have s1: \\<open>is_orthogonal y x\\<close>\n    if a1: \"x \\<in> (orthogonal_complement A)\"\n      and a2: \\<open>y \\<in> closure A\\<close>\n    for x y\n  proof-\n    have \\<open>\\<forall> y \\<in> A. is_orthogonal y x\\<close>\n      by (simp add: a1 orthogonal_complement_orthoI')\n    then obtain yy where \\<open>\\<forall> n. yy n \\<in> A\\<close> and \\<open>yy \\<longlonglongrightarrow> y\\<close>\n      using a2 closure_sequential by blast\n    have \\<open>isCont (\\<lambda> t. t \\<bullet>\\<^sub>C x) y\\<close>\n      by simp\n    hence \\<open>(\\<lambda> n. yy n \\<bullet>\\<^sub>C x) \\<longlonglongrightarrow> y \\<bullet>\\<^sub>C x\\<close>\n      using \\<open>yy \\<longlonglongrightarrow> y\\<close> isCont_tendsto_compose\n      by fastforce\n    hence \\<open>(\\<lambda> n. 0) \\<longlonglongrightarrow> y \\<bullet>\\<^sub>C x\\<close>\n      using \\<open>\\<forall> y \\<in> A. is_orthogonal y x\\<close>  \\<open>\\<forall> n. yy n \\<in> A\\<close> by simp\n    thus ?thesis\n      using limI by force\n  qed\n  hence \"x \\<in> orthogonal_complement (closure A)\"\n    if a1: \"x \\<in> (orthogonal_complement A)\"\n    for x\n    using that\n    by (meson orthogonal_complementI is_orthogonal_sym)\n  moreover have \\<open>x \\<in> (orthogonal_complement A)\\<close>\n    if \"x \\<in> (orthogonal_complement (closure A))\"\n    for x\n    using that\n    by (meson closure_subset orthogonal_complement_orthoI orthogonal_complementI subset_eq)\n  ultimately show ?thesis by blast\nqed\n\n\nlemma is_orthogonal_closure:\n  assumes \\<open>\\<And>s. s \\<in> S \\<Longrightarrow> is_orthogonal a  s\\<close>\n  assumes \\<open>x \\<in> closure S\\<close>\n  shows \\<open>is_orthogonal a x\\<close>\n  by (metis assms(1) assms(2) orthogonal_complementI orthogonal_complement_of_closure orthogonal_complement_orthoI)\n\n\nlemma is_orthogonal_cspan:\n  assumes a1: \"\\<And>s. s \\<in> S \\<Longrightarrow> is_orthogonal a s\" and a3: \"x \\<in> cspan S\"\n  shows \"is_orthogonal a x\"\nproof-\n  have \"\\<exists>t r. finite t \\<and> t \\<subseteq> S \\<and> (\\<Sum>a\\<in>t. r a *\\<^sub>C a) = x\"\n    using complex_vector.span_explicit\n    by (smt a3 mem_Collect_eq)\n  then obtain t r where b1: \"finite t\" and b2: \"t \\<subseteq> S\" and b3: \"(\\<Sum>a\\<in>t. r a *\\<^sub>C a) = x\"\n    by blast\n  have x1: \"is_orthogonal a i\"\n    if \"i\\<in>t\" for i\n    using b2 a1 that by blast\n  have  \"a \\<bullet>\\<^sub>C x = a \\<bullet>\\<^sub>C (\\<Sum>i\\<in>t. r i *\\<^sub>C i)\"\n    by (simp add: b3)\n  also have  \"\\<dots> = (\\<Sum>i\\<in>t. r i *\\<^sub>C (a \\<bullet>\\<^sub>C i))\"\n    by (simp add: cinner_sum_right)\n  also have  \"\\<dots> = 0\"\n    using x1 by simp\n  finally show ?thesis.\nqed\n\nlemma ccspan_leq_ortho_ccspan:\n  assumes \"\\<And>s t. s\\<in>S \\<Longrightarrow> t\\<in>T \\<Longrightarrow> is_orthogonal s t\"\n  shows \"ccspan S \\<le> - (ccspan T)\"\n  using assms apply transfer\n  by (smt (verit, ccfv_threshold) is_orthogonal_closure is_orthogonal_cspan is_orthogonal_sym orthogonal_complementI subsetI)\n\nlemma double_orthogonal_complement_increasing[simp]:\n  shows \"M \\<subseteq> orthogonal_complement (orthogonal_complement M)\"\nproof (rule subsetI)\n  fix x assume s1: \"x \\<in> M\"\n  have \\<open>\\<forall> y \\<in> (orthogonal_complement M). is_orthogonal x y\\<close>\n    using s1 orthogonal_complement_orthoI' by auto\n  hence \\<open>x \\<in> orthogonal_complement (orthogonal_complement M)\\<close>\n    by (simp add: orthogonal_complement_def)\n  then show \"x \\<in> orthogonal_complement (orthogonal_complement M)\"\n    by blast\nqed\n\n\nlemma orthonormal_basis_of_cspan:\n  fixes S::\"'a::complex_inner set\"\n  assumes \"finite S\"\n  shows \"\\<exists>A. is_ortho_set A \\<and> (\\<forall>x\\<in>A. norm x = 1) \\<and> cspan A = cspan S \\<and> finite A\"\nproof (use assms in induction)\n  case empty\n  show ?case\n    apply (rule exI[of _ \"{}\"])\n    by auto\nnext\n  case (insert s S)\n  from insert.IH\n  obtain A where orthoA: \"is_ortho_set A\" and normA: \"\\<And>x. x\\<in>A \\<Longrightarrow> norm x = 1\" and spanA: \"cspan A = cspan S\" and finiteA: \"finite A\"\n    by auto\n  show ?case\n  proof (cases \\<open>s \\<in> cspan S\\<close>)\n    case True\n    then have \\<open>cspan (insert s S) = cspan S\\<close>\n      by (simp add: complex_vector.span_redundant)\n    with orthoA normA spanA finiteA\n    show ?thesis\n      by auto\n  next\n    case False\n    obtain a where a_ortho: \\<open>\\<And>x. x\\<in>A \\<Longrightarrow> is_orthogonal x a\\<close> and sa_span: \\<open>s - a \\<in> cspan A\\<close>\n    proof (atomize_elim, use \\<open>finite A\\<close> \\<open>is_ortho_set A\\<close> in induction)\n      case empty\n      then show ?case\n        by auto\n    next\n      case (insert x A)\n      then obtain a where orthoA: \\<open>\\<And>x. x \\<in> A \\<Longrightarrow> is_orthogonal x a\\<close> and sa: \\<open>s - a \\<in> cspan A\\<close>\n        by (meson is_ortho_set_antimono subset_insertI)\n      define a' where \\<open>a' = a - cinner x a *\\<^sub>C inverse (cinner x x) *\\<^sub>C x\\<close>\n      have \\<open>is_orthogonal x a'\\<close>\n        unfolding a'_def cinner_diff_right cinner_scaleC_right\n        apply (cases \\<open>cinner x x = 0\\<close>)\n        by auto\n      have orthoA: \\<open>is_orthogonal y a'\\<close> if \\<open>y \\<in> A\\<close> for y\n        unfolding a'_def cinner_diff_right cinner_scaleC_right\n        apply auto by (metis insert.prems insertCI is_ortho_set_def mult_not_zero orthoA that)\n      have \\<open>s - a' \\<in> cspan (insert x A)\\<close>\n        unfolding a'_def apply auto\n        by (metis (no_types, lifting) complex_vector.span_breakdown_eq diff_add_cancel diff_diff_add sa)\n      with \\<open>is_orthogonal x a'\\<close> orthoA\n      show ?case\n        apply (rule_tac exI[of _ a'])\n        by auto\n    qed\n\n    from False sa_span\n    have \\<open>a \\<noteq> 0\\<close>\n      unfolding spanA by auto\n    define a' where \\<open>a' = inverse (norm a) *\\<^sub>C a\\<close>\n    with \\<open>a \\<noteq> 0\\<close> have \\<open>norm a' = 1\\<close>\n      by (simp add: norm_inverse)\n    have a: \\<open>a = norm a *\\<^sub>C a'\\<close>\n      by (simp add: \\<open>a \\<noteq> 0\\<close> a'_def)\n\n    from sa_span spanA\n    have a'_span: \\<open>a' \\<in> cspan (insert s S)\\<close>\n      unfolding a'_def\n      by (metis complex_vector.eq_span_insert_eq complex_vector.span_scale complex_vector.span_superset in_mono insertI1)\n    from sa_span\n    have s_span: \\<open>s \\<in> cspan (insert a' A)\\<close>\n      apply (subst (asm) a)\n      using complex_vector.span_breakdown_eq by blast\n\n    from \\<open>a \\<noteq> 0\\<close> a_ortho orthoA\n    have ortho: \"is_ortho_set (insert a' A)\"\n      unfolding is_ortho_set_def a'_def\n      apply auto\n      by (meson is_orthogonal_sym)\n\n    have span: \\<open>cspan (insert a' A) = cspan (insert s S)\\<close>\n      using a'_span s_span spanA apply auto\n       apply (metis (full_types) complex_vector.span_breakdown_eq complex_vector.span_redundant insert_commute s_span)\n      by (metis (full_types) complex_vector.span_breakdown_eq complex_vector.span_redundant insert_commute s_span)\n\n    show ?thesis\n      apply (rule exI[of _ \\<open>insert a' A\\<close>])\n      by (simp add: ortho \\<open>norm a' = 1\\<close> normA finiteA span)\n  qed\nqed\n\nlemma is_ortho_set_cindependent:\n  assumes \"is_ortho_set A\"\n  shows \"cindependent A\"\nproof -\n  have \"u v = 0\"\n    if b1: \"finite t\" and b2: \"t \\<subseteq> A\" and b3: \"(\\<Sum>v\\<in>t. u v *\\<^sub>C v) = 0\" and b4: \"v \\<in> t\"\n    for t u v\n  proof -\n    have \"is_orthogonal v v'\" if c1: \"v'\\<in>t-{v}\" for v'\n      by (metis DiffE assms b2 b4 insertI1 is_ortho_set_antimono is_ortho_set_def that)\n    hence sum0: \"(\\<Sum>v'\\<in>t-{v}. u v' * (v \\<bullet>\\<^sub>C v')) = 0\"\n      by simp\n    have \"v \\<bullet>\\<^sub>C (\\<Sum>v'\\<in>t. u v' *\\<^sub>C v') = (\\<Sum>v'\\<in>t. u v' * (v \\<bullet>\\<^sub>C v'))\"\n      using b1\n      by (metis (mono_tags, lifting) cinner_scaleC_right cinner_sum_right sum.cong)\n    also have \"\\<dots> = u v * (v \\<bullet>\\<^sub>C v) + (\\<Sum>v'\\<in>t-{v}. u v' * (v \\<bullet>\\<^sub>C v'))\"\n      by (meson b1 b4 sum.remove)\n    also have \"\\<dots> = u v * (v \\<bullet>\\<^sub>C v)\"\n      using sum0 by simp\n    finally have \"v \\<bullet>\\<^sub>C (\\<Sum>v'\\<in>t. u v' *\\<^sub>C v') =  u v * (v \\<bullet>\\<^sub>C v)\"\n      by blast\n    hence \"u v * (v \\<bullet>\\<^sub>C v) = 0\" using b3 by simp\n    moreover have \"(v \\<bullet>\\<^sub>C v) \\<noteq> 0\"\n      using assms is_ortho_set_def b2 b4 by auto\n    ultimately show \"u v = 0\" by simp\n  qed\n  thus ?thesis using complex_vector.independent_explicit_module\n    by (smt cdependent_raw_def)\nqed\n\n\nlemma onb_expansion_finite:\n  includes notation_norm\n  fixes T::\\<open>'a::{complex_inner,cfinite_dim} set\\<close>\n  assumes a1: \\<open>cspan T = UNIV\\<close> and a3: \\<open>is_ortho_set T\\<close>\n    and a4: \\<open>\\<And>t. t\\<in>T \\<Longrightarrow> \\<parallel>t\\<parallel> = 1\\<close>\n  shows \\<open>x = (\\<Sum>t\\<in>T. (t \\<bullet>\\<^sub>C x) *\\<^sub>C t)\\<close>\nproof -\n  have \\<open>finite T\\<close>\n    apply (rule cindependent_cfinite_dim_finite)\n    by (simp add: a3 is_ortho_set_cindependent)\n  have \\<open>closure (complex_vector.span T)  = complex_vector.span T\\<close>\n    by (simp add: a1)\n  have \\<open>{\\<Sum>a\\<in>t. r a *\\<^sub>C a |t r. finite t \\<and> t \\<subseteq> T} = {\\<Sum>a\\<in>T. r a *\\<^sub>C a |r. True}\\<close>\n    apply auto\n     apply (rule_tac x=\\<open>\\<lambda>a. if a \\<in> t then r a else 0\\<close> in exI)\n     apply (simp add: \\<open>finite T\\<close> sum.mono_neutral_cong_right)\n    using \\<open>finite T\\<close> by blast\n\n  have f1: \"\\<forall>A. {a. \\<exists>Aa f. (a::'a) = (\\<Sum>a\\<in>Aa. f a *\\<^sub>C a) \\<and> finite Aa \\<and> Aa \\<subseteq> A} = cspan A\"\n    by (simp add: complex_vector.span_explicit)\n  have f2: \"\\<forall>a. (\\<exists>f. a = (\\<Sum>a\\<in>T. f a *\\<^sub>C a)) \\<or> (\\<forall>A. (\\<forall>f. a \\<noteq> (\\<Sum>a\\<in>A. f a *\\<^sub>C a)) \\<or> infinite A \\<or> \\<not> A \\<subseteq> T)\"\n    using \\<open>{\\<Sum>a\\<in>t. r a *\\<^sub>C a |t r. finite t \\<and> t \\<subseteq> T} = {\\<Sum>a\\<in>T. r a *\\<^sub>C a |r. True}\\<close> by auto\n  have f3: \"\\<forall>A a. (\\<exists>Aa f. (a::'a) = (\\<Sum>a\\<in>Aa. f a *\\<^sub>C a) \\<and> finite Aa \\<and> Aa \\<subseteq> A) \\<or> a \\<notin> cspan A\"\n    using f1 by blast\n  have \"cspan T = UNIV\"\n    by (metis (full_types, lifting)  \\<open>complex_vector.span T = UNIV\\<close>)\n  hence \\<open>\\<exists> r. x = (\\<Sum> a\\<in>T. r a *\\<^sub>C a)\\<close>\n    using f3 f2 by blast\n  then obtain r where \\<open>x = (\\<Sum> a\\<in>T. r a *\\<^sub>C a)\\<close>\n    by blast\n\n  have \\<open>r a = a \\<bullet>\\<^sub>C x\\<close> if \\<open>a \\<in> T\\<close> for a\n  proof-\n    have \\<open>norm a = 1\\<close>\n      using a4\n      by (simp add: \\<open>a \\<in> T\\<close>)\n    moreover have \\<open>norm a = sqrt (norm (a \\<bullet>\\<^sub>C a))\\<close>\n      using norm_eq_sqrt_cinner by auto\n    ultimately have \\<open>sqrt (norm (a \\<bullet>\\<^sub>C a)) = 1\\<close>\n      by simp\n    hence \\<open>norm (a \\<bullet>\\<^sub>C a) = 1\\<close>\n      using real_sqrt_eq_1_iff by blast\n    moreover have \\<open>(a \\<bullet>\\<^sub>C a) \\<in> \\<real>\\<close>\n      by (simp add: cinner_real)\n    moreover have \\<open>(a \\<bullet>\\<^sub>C a) \\<ge> 0\\<close>\n      using cinner_ge_zero by blast\n    ultimately have w1: \\<open>(a \\<bullet>\\<^sub>C a) = 1\\<close>\n      by (metis \\<open>0 \\<le> (a \\<bullet>\\<^sub>C a)\\<close> \\<open>cmod (a \\<bullet>\\<^sub>C a) = 1\\<close> complex_of_real_cmod of_real_1)\n\n    have \\<open>r t * (a \\<bullet>\\<^sub>C t) = 0\\<close> if \\<open>t \\<in> T-{a}\\<close> for t\n      by (metis DiffD1 DiffD2 \\<open>a \\<in> T\\<close> a3 is_ortho_set_def mult_eq_0_iff singletonI that)\n    hence s1: \\<open>(\\<Sum> t\\<in>T-{a}. r t * (a \\<bullet>\\<^sub>C t)) = 0\\<close>\n      by (simp add: \\<open>\\<And>t. t \\<in> T - {a} \\<Longrightarrow> r t * (a \\<bullet>\\<^sub>C t) = 0\\<close>)\n    have \\<open>(a \\<bullet>\\<^sub>C x) = a \\<bullet>\\<^sub>C (\\<Sum> t\\<in>T. r t *\\<^sub>C t)\\<close>\n      using \\<open>x = (\\<Sum> a\\<in>T. r a *\\<^sub>C a)\\<close>\n      by simp\n    also have \\<open>\\<dots> = (\\<Sum> t\\<in>T. a \\<bullet>\\<^sub>C (r t *\\<^sub>C t))\\<close>\n      using cinner_sum_right by blast\n    also have \\<open>\\<dots> = (\\<Sum> t\\<in>T. r t * (a \\<bullet>\\<^sub>C t))\\<close>\n      by simp\n    also have \\<open>\\<dots> = r a * (a \\<bullet>\\<^sub>C a) + (\\<Sum> t\\<in>T-{a}. r t * (a \\<bullet>\\<^sub>C t))\\<close>\n      using \\<open>a \\<in> T\\<close>\n      by (meson \\<open>finite T\\<close> sum.remove)\n    also have \\<open>\\<dots> = r a * (a \\<bullet>\\<^sub>C a)\\<close>\n      using s1\n      by simp\n    also have \\<open>\\<dots> = r a\\<close>\n      by (simp add: w1)\n    finally show ?thesis by auto\n  qed\n  thus ?thesis\n    using \\<open>x = (\\<Sum> a\\<in>T. r a *\\<^sub>C a)\\<close>\n    by fastforce\nqed\n\nlemma is_ortho_set_singleton[simp]: \\<open>is_ortho_set {x} \\<longleftrightarrow> x \\<noteq> 0\\<close>\n  by (simp add: is_ortho_set_def)\n\nlemma orthogonal_complement_antimono[simp]:\n  fixes  A B :: \\<open>('a::complex_inner) set\\<close>\n  assumes \"A \\<supseteq> B\"\n  shows \\<open>orthogonal_complement A \\<subseteq> orthogonal_complement B\\<close>\n  by (meson assms orthogonal_complementI orthogonal_complement_orthoI' subsetD subsetI)\n\nlemma orthogonal_complement_UNIV[simp]:\n  \"orthogonal_complement UNIV = {0}\"\n  by (metis Int_UNIV_left complex_vector.subspace_UNIV complex_vector.subspace_def orthogonal_complement_zero_intersection)\n\nlemma orthogonal_complement_zero[simp]:\n  \"orthogonal_complement {0} = UNIV\"\n  unfolding orthogonal_complement_def by auto\n\nsubsection \\<open>Projections\\<close>\n\nlemma smallest_norm_exists:\n  \\<comment> \\<open>Theorem 2.5 in \\<^cite>\\<open>conway2013course\\<close> (inside the proof)\\<close>\n  includes notation_norm\n  fixes M :: \\<open>'a::chilbert_space set\\<close>\n  assumes q1: \\<open>convex M\\<close> and q2: \\<open>closed M\\<close> and q3: \\<open>M \\<noteq> {}\\<close>\n  shows  \\<open>\\<exists>k. is_arg_min (\\<lambda> x. \\<parallel>x\\<parallel>) (\\<lambda> t. t \\<in> M) k\\<close>\nproof -\n  define d where \\<open>d = Inf { \\<parallel>x\\<parallel>^2 | x. x \\<in> M }\\<close>\n  have w4: \\<open>{ \\<parallel>x\\<parallel>^2 | x. x \\<in> M } \\<noteq> {}\\<close>\n    by (simp add: assms(3))\n  have \\<open>\\<forall> x. \\<parallel>x\\<parallel>^2 \\<ge> 0\\<close>\n    by simp\n  hence bdd_below1: \\<open>bdd_below { \\<parallel>x\\<parallel>^2 | x. x \\<in> M }\\<close>\n    by fastforce\n  have \\<open>d \\<le> \\<parallel>x\\<parallel>^2\\<close> if a1: \"x \\<in> M\" for x\n  proof-\n    have \"\\<forall>v. (\\<exists>w. Re (v \\<bullet>\\<^sub>C v) = \\<parallel>w\\<parallel>\\<^sup>2 \\<and> w \\<in> M) \\<or> v \\<notin> M\"\n      by (metis (no_types) power2_norm_eq_cinner')\n    hence \"Re (x \\<bullet>\\<^sub>C x) \\<in> {\\<parallel>v\\<parallel>\\<^sup>2 |v. v \\<in> M}\"\n      using a1 by blast\n    thus ?thesis\n      unfolding d_def\n      by (metis (lifting) bdd_below1 cInf_lower power2_norm_eq_cinner')\n  qed\n\n  have \\<open>\\<forall> \\<epsilon> > 0. \\<exists> t \\<in> { \\<parallel>x\\<parallel>^2 | x. x \\<in> M }.  t < d + \\<epsilon>\\<close>\n    unfolding d_def\n    using w4  bdd_below1\n    by (meson cInf_lessD less_add_same_cancel1)\n  hence \\<open>\\<forall> \\<epsilon> > 0. \\<exists> x \\<in> M.  \\<parallel>x\\<parallel>^2 < d + \\<epsilon>\\<close>\n    by auto\n  hence \\<open>\\<forall> \\<epsilon> > 0. \\<exists> x \\<in> M.  \\<parallel>x\\<parallel>^2 < d + \\<epsilon>\\<close>\n    by (simp add: \\<open>\\<And>x. x \\<in> M \\<Longrightarrow> d \\<le> \\<parallel>x\\<parallel>\\<^sup>2\\<close>)\n  hence w1: \\<open>\\<forall> n::nat. \\<exists> x \\<in> M.  \\<parallel>x\\<parallel>^2 < d + 1/(n+1)\\<close> by auto\n\n  then obtain r::\\<open>nat \\<Rightarrow> 'a\\<close> where w2: \\<open>\\<forall> n. r n \\<in> M \\<and>  \\<parallel> r n \\<parallel>^2 < d + 1/(n+1)\\<close>\n    by metis\n  have w3: \\<open>\\<forall> n. r n \\<in> M\\<close>\n    by (simp add: w2)\n  have \\<open>\\<forall> n. \\<parallel> r n \\<parallel>^2 < d + 1/(n+1)\\<close>\n    by (simp add: w2)\n  have w5: \\<open>\\<parallel> (r n) - (r m) \\<parallel>^2 < 2*(1/(n+1) + 1/(m+1))\\<close>\n    for m n\n  proof-\n    have w6: \\<open>\\<parallel> r n \\<parallel>^2 < d + 1/(n+1)\\<close>\n      by (metis w2  of_nat_1 of_nat_add)\n    have \\<open> \\<parallel> r m \\<parallel>^2 < d + 1/(m+1)\\<close>\n      by (metis w2 of_nat_1 of_nat_add)\n    have \\<open>(r n) \\<in> M\\<close>\n      by (simp add: \\<open>\\<forall>n. r n \\<in> M\\<close>)\n    moreover have \\<open>(r m) \\<in> M\\<close>\n      by (simp add: \\<open>\\<forall>n. r n \\<in> M\\<close>)\n    ultimately have \\<open>(1/2) *\\<^sub>R (r n) + (1/2) *\\<^sub>R (r m) \\<in> M\\<close>\n      using \\<open>convex M\\<close>\n      by (simp add: convexD)\n    hence \\<open>\\<parallel> (1/2) *\\<^sub>R (r n) + (1/2) *\\<^sub>R (r m) \\<parallel>^2 \\<ge> d\\<close>\n      by (simp add: \\<open>\\<And>x. x \\<in> M \\<Longrightarrow> d \\<le> \\<parallel>x\\<parallel>\\<^sup>2\\<close>)\n    have \\<open>\\<parallel> (1/2) *\\<^sub>R (r n) - (1/2) *\\<^sub>R (r m) \\<parallel>^2\n              = (1/2)*( \\<parallel> r n \\<parallel>^2 + \\<parallel> r m \\<parallel>^2 ) - \\<parallel> (1/2) *\\<^sub>R (r n) + (1/2) *\\<^sub>R (r m) \\<parallel>^2\\<close>\n      by (smt (z3) div_by_1 field_sum_of_halves nonzero_mult_div_cancel_left parallelogram_law polar_identity power2_norm_eq_cinner' scaleR_collapse times_divide_eq_left)\n    also have  \\<open>...\n              < (1/2)*( d + 1/(n+1) + \\<parallel> r m \\<parallel>^2 ) - \\<parallel> (1/2) *\\<^sub>R (r n) + (1/2) *\\<^sub>R (r m) \\<parallel>^2\\<close>\n      using \\<open>\\<parallel>r n\\<parallel>\\<^sup>2 < d + 1 / real (n + 1)\\<close> by auto\n    also have  \\<open>...\n              < (1/2)*( d + 1/(n+1) + d + 1/(m+1) ) - \\<parallel> (1/2) *\\<^sub>R (r n) + (1/2) *\\<^sub>R (r m) \\<parallel>^2\\<close>\n      using \\<open>\\<parallel>r m\\<parallel>\\<^sup>2 < d + 1 / real (m + 1)\\<close> by auto\n    also have  \\<open>...\n              \\<le> (1/2)*( d + 1/(n+1) + d + 1/(m+1) ) - d\\<close>\n      by (simp add: \\<open>d \\<le> \\<parallel>(1 / 2) *\\<^sub>R r n + (1 / 2) *\\<^sub>R r m\\<parallel>\\<^sup>2\\<close>)\n    also have  \\<open>...\n              \\<le> (1/2)*( 1/(n+1) + 1/(m+1) + 2*d ) - d\\<close>\n      by simp\n    also have  \\<open>...\n              \\<le> (1/2)*( 1/(n+1) + 1/(m+1) ) + (1/2)*(2*d) - d\\<close>\n      by (simp add: distrib_left)\n    also have  \\<open>...\n              \\<le> (1/2)*( 1/(n+1) + 1/(m+1) ) + d - d\\<close>\n      by simp\n    also have  \\<open>...\n              \\<le> (1/2)*( 1/(n+1) + 1/(m+1) )\\<close>\n      by simp\n    finally have \\<open> \\<parallel>(1 / 2) *\\<^sub>R r n - (1 / 2) *\\<^sub>R r m\\<parallel>\\<^sup>2 < 1 / 2 * (1 / real (n + 1) + 1 / real (m + 1)) \\<close>\n      by blast\n    hence \\<open> \\<parallel>(1 / 2) *\\<^sub>R (r n - r m) \\<parallel>\\<^sup>2 < (1 / 2) * (1 / real (n + 1) + 1 / real (m + 1)) \\<close>\n      by (simp add: real_vector.scale_right_diff_distrib)\n    hence \\<open> ((1 / 2)*\\<parallel> (r n - r m) \\<parallel>)\\<^sup>2 < (1 / 2) * (1 / real (n + 1) + 1 / real (m + 1)) \\<close>\n      by simp\n    hence \\<open> (1 / 2)^2*(\\<parallel> (r n - r m) \\<parallel>)\\<^sup>2 < (1 / 2) * (1 / real (n + 1) + 1 / real (m + 1)) \\<close>\n      by (metis power_mult_distrib)\n    hence \\<open> (1 / 4) *(\\<parallel> (r n - r m) \\<parallel>)\\<^sup>2 < (1 / 2) * (1 / real (n + 1) + 1 / real (m + 1)) \\<close>\n      by (simp add: power_divide)\n    hence \\<open> \\<parallel> (r n - r m) \\<parallel>\\<^sup>2 < 2 * (1 / real (n + 1) + 1 / real (m + 1)) \\<close>\n      by simp\n    thus ?thesis\n      by (metis of_nat_1 of_nat_add)\n  qed\n  hence \"\\<exists> N. \\<forall> n m. n \\<ge> N \\<and> m \\<ge> N \\<longrightarrow> \\<parallel> (r n) - (r m) \\<parallel>^2 < \\<epsilon>^2\"\n    if \"\\<epsilon> > 0\"\n    for \\<epsilon>\n  proof-\n    obtain N::nat where \\<open>1/(N + 1) < \\<epsilon>^2/4\\<close>\n      using LIMSEQ_ignore_initial_segment[OF lim_inverse_n', where k=1]\n      by (metis Suc_eq_plus1 \\<open>0 < \\<epsilon>\\<close> nat_approx_posE zero_less_divide_iff zero_less_numeral\n          zero_less_power )\n    hence \\<open>4/(N + 1) < \\<epsilon>^2\\<close>\n      by simp\n    have \"2*(1/(n+1) + 1/(m+1)) < \\<epsilon>^2\"\n      if f1: \"n \\<ge> N\" and f2: \"m \\<ge> N\"\n      for m n::nat\n    proof-\n      have \\<open>1/(n+1) \\<le> 1/(N+1)\\<close>\n        by (simp add: f1 linordered_field_class.frac_le)\n      moreover have \\<open>1/(m+1) \\<le> 1/(N+1)\\<close>\n        by (simp add: f2 linordered_field_class.frac_le)\n      ultimately have  \\<open>2*(1/(n+1) + 1/(m+1)) \\<le> 4/(N+1)\\<close>\n        by simp\n      thus ?thesis using \\<open>4/(N + 1) < \\<epsilon>^2\\<close>\n        by linarith\n    qed\n    hence \"\\<parallel> (r n) - (r m) \\<parallel>^2 < \\<epsilon>^2\"\n      if y1: \"n \\<ge> N\" and y2: \"m \\<ge> N\"\n      for m n::nat\n      using that\n      by (smt \\<open>\\<And>n m. \\<parallel>r n - r m\\<parallel>\\<^sup>2 < 2 * (1 / (real n + 1) + 1 / (real m + 1))\\<close> of_nat_1 of_nat_add)\n    thus ?thesis\n      by blast\n  qed\n  hence  \\<open>\\<forall> \\<epsilon> > 0. \\<exists> N::nat. \\<forall> n m::nat. n \\<ge> N \\<and> m \\<ge> N \\<longrightarrow> \\<parallel> (r n) - (r m) \\<parallel>^2 < \\<epsilon>^2\\<close>\n    by blast\n  hence  \\<open>\\<forall> \\<epsilon> > 0. \\<exists> N::nat. \\<forall> n m::nat. n \\<ge> N \\<and> m \\<ge> N \\<longrightarrow> \\<parallel> (r n) - (r m) \\<parallel> < \\<epsilon>\\<close>\n    by (meson less_eq_real_def power_less_imp_less_base)\n  hence \\<open>Cauchy r\\<close>\n    using CauchyI by fastforce\n  then obtain k where \\<open>r \\<longlonglongrightarrow> k\\<close>\n    using  convergent_eq_Cauchy by auto\n  have \\<open>k \\<in> M\\<close> using \\<open>closed M\\<close>\n    using \\<open>\\<forall>n. r n \\<in> M\\<close> \\<open>r \\<longlonglongrightarrow> k\\<close> closed_sequentially by auto\n  have  \\<open>(\\<lambda> n.  \\<parallel> r n \\<parallel>^2) \\<longlonglongrightarrow>  \\<parallel> k \\<parallel>^2\\<close>\n    by (simp add: \\<open>r \\<longlonglongrightarrow> k\\<close> tendsto_norm tendsto_power)\n  moreover  have  \\<open>(\\<lambda> n.  \\<parallel> r n \\<parallel>^2) \\<longlonglongrightarrow>  d\\<close>\n  proof-\n    have \\<open>\\<bar>\\<parallel> r n \\<parallel>^2 - d\\<bar> < 1/(n+1)\\<close> for n :: nat\n      using \\<open>\\<And>x. x \\<in> M \\<Longrightarrow> d \\<le> \\<parallel>x\\<parallel>\\<^sup>2\\<close> \\<open>\\<forall>n. r n \\<in> M \\<and> \\<parallel>r n\\<parallel>\\<^sup>2 < d + 1 / (real n + 1)\\<close> of_nat_1 of_nat_add\n      by smt\n    moreover have \\<open>(\\<lambda>n. 1 / real (n + 1)) \\<longlonglongrightarrow> 0\\<close>\n      using  LIMSEQ_ignore_initial_segment[OF lim_inverse_n', where k=1] by blast\n    ultimately have \\<open>(\\<lambda> n. \\<bar>\\<parallel> r n \\<parallel>^2 - d\\<bar> ) \\<longlonglongrightarrow> 0\\<close>\n      by (simp add: LIMSEQ_norm_0)\n    hence \\<open>(\\<lambda> n. \\<parallel> r n \\<parallel>^2 - d ) \\<longlonglongrightarrow> 0\\<close>\n      by (simp add: tendsto_rabs_zero_iff)\n    moreover have \\<open>(\\<lambda> n. d ) \\<longlonglongrightarrow> d\\<close>\n      by simp\n    ultimately have \\<open>(\\<lambda> n. (\\<parallel> r n \\<parallel>^2 - d)+d ) \\<longlonglongrightarrow> 0+d\\<close>\n      using tendsto_add by fastforce\n    thus ?thesis by simp\n  qed\n  ultimately have \\<open>d = \\<parallel> k \\<parallel>^2\\<close>\n    using LIMSEQ_unique by auto\n  hence \\<open>t \\<in> M \\<Longrightarrow> \\<parallel> k \\<parallel>^2 \\<le> \\<parallel> t \\<parallel>^2\\<close> for t\n    using \\<open>\\<And>x. x \\<in> M \\<Longrightarrow> d \\<le> \\<parallel>x\\<parallel>\\<^sup>2\\<close> by auto\n  hence q1: \\<open>\\<exists> k. is_arg_min (\\<lambda> x. \\<parallel>x\\<parallel>^2) (\\<lambda> t. t \\<in> M) k\\<close>\n    using \\<open>k \\<in> M\\<close>\n      is_arg_min_def \\<open>d = \\<parallel>k\\<parallel>\\<^sup>2\\<close>\n    by smt\n  thus \\<open>\\<exists> k. is_arg_min (\\<lambda> x. \\<parallel>x\\<parallel>) (\\<lambda> t. t \\<in> M) k\\<close>\n    by (smt is_arg_min_def norm_ge_zero power2_eq_square power2_le_imp_le)\nqed\n\n\nlemma smallest_norm_unique:\n  \\<comment> \\<open>Theorem 2.5 in \\<^cite>\\<open>conway2013course\\<close> (inside the proof)\\<close>\n  includes notation_norm\n  fixes M :: \\<open>'a::complex_inner set\\<close>\n  assumes q1: \\<open>convex M\\<close>\n  assumes r: \\<open>is_arg_min (\\<lambda> x. \\<parallel>x\\<parallel>) (\\<lambda> t. t \\<in> M) r\\<close>\n  assumes s: \\<open>is_arg_min (\\<lambda> x. \\<parallel>x\\<parallel>) (\\<lambda> t. t \\<in> M) s\\<close>\n  shows \\<open>r = s\\<close>\nproof -\n  have \\<open>r \\<in> M\\<close>\n    using \\<open>is_arg_min (\\<lambda>x. \\<parallel>x\\<parallel>) (\\<lambda> t. t \\<in> M) r\\<close>\n    by (simp add: is_arg_min_def)\n  moreover have \\<open>s \\<in> M\\<close>\n    using \\<open>is_arg_min (\\<lambda>x. \\<parallel>x\\<parallel>) (\\<lambda> t. t \\<in> M) s\\<close>\n    by (simp add: is_arg_min_def)\n  ultimately have \\<open>((1/2) *\\<^sub>R r + (1/2) *\\<^sub>R s) \\<in> M\\<close> using \\<open>convex M\\<close>\n    by (simp add: convexD)\n  hence \\<open>\\<parallel>r\\<parallel> \\<le> \\<parallel> (1/2) *\\<^sub>R r + (1/2) *\\<^sub>R s \\<parallel>\\<close>\n    by (metis is_arg_min_linorder r)\n  hence u2: \\<open>\\<parallel>r\\<parallel>^2 \\<le> \\<parallel> (1/2) *\\<^sub>R r + (1/2) *\\<^sub>R s \\<parallel>^2\\<close>\n    using norm_ge_zero power_mono by blast\n\n  have \\<open>\\<parallel>r\\<parallel> \\<le> \\<parallel>s\\<parallel>\\<close>\n    using r s is_arg_min_def\n    by (metis is_arg_min_linorder)\n  moreover have \\<open>\\<parallel>s\\<parallel> \\<le> \\<parallel>r\\<parallel>\\<close>\n    using r s is_arg_min_def\n    by (metis is_arg_min_linorder)\n  ultimately have u3: \\<open>\\<parallel>r\\<parallel> = \\<parallel>s\\<parallel>\\<close> by simp\n\n  have \\<open>\\<parallel> (1/2) *\\<^sub>R r - (1/2) *\\<^sub>R s \\<parallel>^2 \\<le> 0\\<close>\n    using u2 u3 parallelogram_law\n    by (smt (verit, ccfv_SIG) polar_identity_minus power2_norm_eq_cinner' scaleR_add_right scaleR_half_double)\n  hence \\<open>\\<parallel> (1/2) *\\<^sub>R r - (1/2) *\\<^sub>R s \\<parallel>^2 = 0\\<close>\n    by simp\n  hence \\<open>\\<parallel> (1/2) *\\<^sub>R r - (1/2) *\\<^sub>R s \\<parallel> = 0\\<close>\n    by auto\n  hence \\<open>(1/2) *\\<^sub>R r - (1/2) *\\<^sub>R s = 0\\<close>\n    using norm_eq_zero by blast\n  thus ?thesis by simp\nqed\n\ntheorem smallest_dist_exists:\n  \\<comment> \\<open>Theorem 2.5 in \\<^cite>\\<open>conway2013course\\<close>\\<close>\n  fixes M::\\<open>'a::chilbert_space set\\<close> and h\n  assumes a1: \\<open>convex M\\<close> and a2: \\<open>closed M\\<close> and a3: \\<open>M \\<noteq> {}\\<close>\n  shows  \\<open>\\<exists>k. is_arg_min (\\<lambda> x. dist x h) (\\<lambda> x. x \\<in> M) k\\<close>\nproof -\n  have *: \"is_arg_min (\\<lambda>x. dist x h) (\\<lambda>x. x\\<in>M) (k+h) \\<longleftrightarrow> is_arg_min (\\<lambda>x. norm x) (\\<lambda>x. x\\<in>(\\<lambda>x. x-h) ` M) k\" for k\n    unfolding dist_norm is_arg_min_def apply auto using add_implies_diff by blast\n  have \\<open>\\<exists>k. is_arg_min (\\<lambda>x. dist x h) (\\<lambda>x. x\\<in>M) (k+h)\\<close>\n    apply (subst *)\n    apply (rule smallest_norm_exists)\n    using assms by (auto simp: closed_translation_subtract)\n  then show \\<open>\\<exists>k. is_arg_min (\\<lambda> x. dist x h) (\\<lambda> x. x \\<in> M) k\\<close>\n    by metis\nqed\n\ntheorem smallest_dist_unique:\n  \\<comment> \\<open>Theorem 2.5 in \\<^cite>\\<open>conway2013course\\<close>\\<close>\n  fixes M::\\<open>'a::complex_inner set\\<close> and h\n  assumes a1: \\<open>convex M\\<close>\n  assumes \\<open>is_arg_min (\\<lambda> x. dist x h) (\\<lambda> x. x \\<in> M) r\\<close>\n  assumes \\<open>is_arg_min (\\<lambda> x. dist x h) (\\<lambda> x. x \\<in> M) s\\<close>\n  shows  \\<open>r = s\\<close>\nproof-\n  have *: \"is_arg_min (\\<lambda>x. dist x h) (\\<lambda>x. x\\<in>M) k \\<longleftrightarrow> is_arg_min (\\<lambda>x. norm x) (\\<lambda>x. x\\<in>(\\<lambda>x. x-h) ` M) (k-h)\" for k\n    unfolding dist_norm is_arg_min_def by auto\n  have \\<open>r - h = s - h\\<close>\n    using _ assms(2,3)[unfolded *] apply (rule smallest_norm_unique)\n    by (simp add: a1)\n  thus \\<open>r = s\\<close>\n    by auto\nqed\n\n\n\\<comment> \\<open>Theorem 2.6 in \\<^cite>\\<open>conway2013course\\<close>\\<close>\ntheorem smallest_dist_is_ortho:\n  fixes M::\\<open>'a::complex_inner set\\<close> and h k::'a\n  assumes b1: \\<open>closed_csubspace M\\<close>\n  shows  \\<open>(is_arg_min (\\<lambda> x. dist x h) (\\<lambda> x. x \\<in> M) k) \\<longleftrightarrow>\n          h - k \\<in> orthogonal_complement M \\<and> k \\<in> M\\<close>\nproof -\n  include notation_norm\n  have  \\<open>csubspace M\\<close>\n    using \\<open>closed_csubspace M\\<close> unfolding closed_csubspace_def by blast\n  have r1: \\<open>2 * Re ((h - k) \\<bullet>\\<^sub>C f) \\<le> \\<parallel> f \\<parallel>^2\\<close>\n    if \"f \\<in> M\" and \\<open>k \\<in> M\\<close> and \\<open>is_arg_min (\\<lambda>x. dist x h) (\\<lambda> x. x \\<in> M) k\\<close>\n    for f\n  proof-\n    have \\<open>k + f \\<in>  M\\<close>\n      using \\<open>csubspace M\\<close>\n      by (simp add:complex_vector.subspace_add that)\n    have \"\\<forall>f A a b. \\<not> is_arg_min f (\\<lambda> x. x \\<in> A) (a::'a) \\<or> (f a::real) \\<le> f b \\<or> b \\<notin> A\"\n      by (metis (no_types) is_arg_min_linorder)\n    hence \"dist k h \\<le> dist (f + k) h\"\n      by (metis \\<open>is_arg_min (\\<lambda>x. dist x h) (\\<lambda> x. x \\<in> M) k\\<close> \\<open>k + f \\<in> M\\<close> add.commute)\n    hence \\<open>dist h k \\<le> dist  h (k + f)\\<close>\n      by (simp add: add.commute dist_commute)\n    hence \\<open>\\<parallel> h - k \\<parallel> \\<le> \\<parallel> h - (k + f) \\<parallel>\\<close>\n      by (simp add: dist_norm)\n    hence \\<open>\\<parallel> h - k \\<parallel>^2 \\<le> \\<parallel> h - (k + f) \\<parallel>^2\\<close>\n      by (simp add: power_mono)\n    also have \\<open>... \\<le> \\<parallel> (h - k) - f \\<parallel>^2\\<close>\n      by (simp add: diff_diff_add)\n    also have \\<open>... \\<le> \\<parallel> (h - k) \\<parallel>^2 + \\<parallel> f \\<parallel>^2 -  2 * Re ((h - k) \\<bullet>\\<^sub>C f)\\<close>\n      by (simp add: polar_identity_minus)\n    finally have \\<open>\\<parallel> (h - k) \\<parallel>^2 \\<le> \\<parallel> (h - k) \\<parallel>^2 + \\<parallel> f \\<parallel>^2 -  2 * Re ((h - k) \\<bullet>\\<^sub>C f)\\<close>\n      by simp\n    thus ?thesis by simp\n  qed\n\n  have q4: \\<open>\\<forall> c > 0.  2 * Re ((h - k) \\<bullet>\\<^sub>C f) \\<le> c\\<close>\n    if  \\<open>\\<forall>c>0. 2 * Re ((h - k) \\<bullet>\\<^sub>C f) \\<le> c * \\<parallel>f\\<parallel>\\<^sup>2\\<close>\n    for f\n  proof (cases \\<open>\\<parallel> f \\<parallel>^2 > 0\\<close>)\n    case True\n    hence \\<open>\\<forall> c > 0.  2 * Re (((h - k) \\<bullet>\\<^sub>C f)) \\<le> (c/\\<parallel> f \\<parallel>^2)*\\<parallel> f \\<parallel>^2\\<close>\n      using that linordered_field_class.divide_pos_pos by blast\n    thus ?thesis\n      using True by auto\n  next\n    case False\n    hence \\<open>\\<parallel> f \\<parallel>^2 = 0\\<close>\n      by simp\n    thus ?thesis\n      by auto\n  qed\n  have q3: \\<open>\\<forall> c::real. c > 0 \\<longrightarrow> 2 * Re (((h - k) \\<bullet>\\<^sub>C f)) \\<le> 0\\<close>\n    if a3: \\<open>\\<forall>f. f \\<in> M \\<longrightarrow> (\\<forall>c>0. 2 * Re ((h - k) \\<bullet>\\<^sub>C f) \\<le> c * \\<parallel>f\\<parallel>\\<^sup>2)\\<close>\n      and a2: \"f \\<in>  M\"\n      and a1: \"is_arg_min (\\<lambda> x. dist x h) (\\<lambda> x. x \\<in> M) k\"\n    for f\n  proof-\n    have \\<open>\\<forall> c > 0.  2 * Re (((h - k) \\<bullet>\\<^sub>C f)) \\<le> c*\\<parallel> f \\<parallel>^2\\<close>\n      by (simp add: that )\n    thus ?thesis\n      using q4 by smt\n  qed\n  have w2: \"h - k \\<in> orthogonal_complement M \\<and> k \\<in> M\"\n    if a1: \"is_arg_min (\\<lambda> x. dist x h) (\\<lambda> x. x \\<in> M) k\"\n  proof-\n    have  \\<open>k \\<in> M\\<close>\n      using is_arg_min_def that by fastforce\n    hence \\<open>\\<forall> f. f \\<in>  M \\<longrightarrow> 2 * Re (((h - k) \\<bullet>\\<^sub>C f)) \\<le> \\<parallel> f \\<parallel>^2\\<close>\n      using r1\n      by (simp add: that)\n    have \\<open>\\<forall> f. f \\<in>  M \\<longrightarrow>\n                (\\<forall> c::real.  2 * Re ((h - k) \\<bullet>\\<^sub>C (c *\\<^sub>R f)) \\<le> \\<parallel> c *\\<^sub>R f \\<parallel>^2)\\<close>\n      using  assms scaleR_scaleC complex_vector.subspace_def \\<open>csubspace M\\<close>\n      by (metis \\<open>\\<forall>f. f \\<in> M \\<longrightarrow> 2 * Re ((h - k) \\<bullet>\\<^sub>C f) \\<le> \\<parallel>f\\<parallel>\\<^sup>2\\<close>)\n    hence  \\<open>\\<forall> f. f \\<in>  M \\<longrightarrow>\n                (\\<forall> c::real. c * (2 * Re (((h - k) \\<bullet>\\<^sub>C f))) \\<le> \\<parallel> c *\\<^sub>R f \\<parallel>^2)\\<close>\n      by (metis Re_complex_of_real cinner_scaleC_right complex_add_cnj complex_cnj_complex_of_real\n          complex_cnj_mult of_real_mult scaleR_scaleC semiring_normalization_rules(34))\n    hence  \\<open>\\<forall> f. f \\<in>  M \\<longrightarrow>\n                (\\<forall> c::real. c * (2 * Re (((h - k) \\<bullet>\\<^sub>C f))) \\<le> \\<bar>c\\<bar>^2*\\<parallel> f \\<parallel>^2)\\<close>\n      by (simp add: power_mult_distrib)\n    hence  \\<open>\\<forall> f. f \\<in>  M \\<longrightarrow>\n                (\\<forall> c::real. c * (2 * Re (((h - k) \\<bullet>\\<^sub>C f))) \\<le> c^2*\\<parallel> f \\<parallel>^2)\\<close>\n      by auto\n    hence  \\<open>\\<forall> f. f \\<in>  M \\<longrightarrow>\n                (\\<forall> c::real. c > 0 \\<longrightarrow> c * (2 * Re (((h - k) \\<bullet>\\<^sub>C f))) \\<le> c^2*\\<parallel> f \\<parallel>^2)\\<close>\n      by simp\n    hence  \\<open>\\<forall> f. f \\<in>  M \\<longrightarrow>\n                (\\<forall> c::real. c > 0 \\<longrightarrow> c*(2 * Re (((h - k) \\<bullet>\\<^sub>C f))) \\<le> c*(c*\\<parallel> f \\<parallel>^2))\\<close>\n      by (simp add: power2_eq_square)\n    hence  q4: \\<open>\\<forall> f. f \\<in>  M \\<longrightarrow>\n                (\\<forall> c::real. c > 0 \\<longrightarrow> 2 * Re (((h - k) \\<bullet>\\<^sub>C f)) \\<le> c*\\<parallel> f \\<parallel>^2)\\<close>\n      by simp\n    have  \\<open>\\<forall> f. f \\<in>  M \\<longrightarrow>\n                (\\<forall> c::real. c > 0 \\<longrightarrow> 2 * Re (((h - k) \\<bullet>\\<^sub>C f)) \\<le> 0)\\<close>\n      using q3\n      by (simp add: q4 that)\n    hence  \\<open>\\<forall> f. f \\<in>  M \\<longrightarrow>\n                (\\<forall> c::real. c > 0 \\<longrightarrow> (2 * Re ((h - k) \\<bullet>\\<^sub>C (-1 *\\<^sub>R f))) \\<le> 0)\\<close>\n      using assms scaleR_scaleC complex_vector.subspace_def\n      by (metis \\<open>csubspace M\\<close>)\n    hence  \\<open>\\<forall> f. f \\<in>  M \\<longrightarrow>\n                (\\<forall> c::real. c > 0 \\<longrightarrow> -(2 * Re (((h - k) \\<bullet>\\<^sub>C f))) \\<le> 0)\\<close>\n      by simp\n    hence  \\<open>\\<forall> f. f \\<in>  M \\<longrightarrow>\n                (\\<forall> c::real. c > 0 \\<longrightarrow> 2 * Re (((h - k) \\<bullet>\\<^sub>C f)) \\<ge> 0)\\<close>\n      by simp\n    hence \\<open>\\<forall> f. f \\<in>  M \\<longrightarrow>\n                (\\<forall> c::real. c > 0 \\<longrightarrow> 2 * Re (((h - k) \\<bullet>\\<^sub>C f)) = 0)\\<close>\n      using  \\<open>\\<forall> f. f \\<in>  M \\<longrightarrow>\n                (\\<forall> c::real. c > 0 \\<longrightarrow> (2 * Re (((h - k) \\<bullet>\\<^sub>C f))) \\<le> 0)\\<close>\n      by fastforce\n\n    have \\<open>\\<forall> f. f \\<in>  M \\<longrightarrow>\n                 ((1::real) > 0 \\<longrightarrow> 2 * Re (((h - k) \\<bullet>\\<^sub>C f)) = 0)\\<close>\n      using \\<open>\\<forall>f. f \\<in>  M \\<longrightarrow> (\\<forall>c>0. 2 * Re (((h - k) \\<bullet>\\<^sub>C f) ) = 0)\\<close> by blast\n    hence \\<open>\\<forall> f. f \\<in>  M \\<longrightarrow> 2 * Re (((h - k) \\<bullet>\\<^sub>C f)) = 0\\<close>\n      by simp\n    hence \\<open>\\<forall> f. f \\<in>  M \\<longrightarrow> Re (((h - k) \\<bullet>\\<^sub>C f)) = 0\\<close>\n      by simp\n    have  \\<open>\\<forall> f. f \\<in>  M \\<longrightarrow> Re ((h - k) \\<bullet>\\<^sub>C ((Complex 0 (-1)) *\\<^sub>C f)) = 0\\<close>\n      using assms  complex_vector.subspace_def \\<open>csubspace M\\<close>\n      by (metis \\<open>\\<forall>f. f \\<in> M \\<longrightarrow> Re ((h - k) \\<bullet>\\<^sub>C f) = 0\\<close>)\n    hence  \\<open>\\<forall> f. f \\<in>  M \\<longrightarrow> Re ( (Complex 0 (-1))*(((h - k) \\<bullet>\\<^sub>C f)) ) = 0\\<close>\n      by simp\n    hence \\<open>\\<forall> f. f \\<in>  M \\<longrightarrow> Im (((h - k) \\<bullet>\\<^sub>C f)) = 0\\<close>\n      using Complex_eq_neg_1 Re_i_times cinner_scaleC_right complex_of_real_def by auto\n\n    have \\<open>\\<forall> f. f \\<in>  M \\<longrightarrow> (((h - k) \\<bullet>\\<^sub>C f)) = 0\\<close>\n      using complex_eq_iff\n      by (simp add: \\<open>\\<forall>f. f \\<in> M \\<longrightarrow> Im ((h - k) \\<bullet>\\<^sub>C f) = 0\\<close> \\<open>\\<forall>f. f \\<in> M \\<longrightarrow> Re ((h - k) \\<bullet>\\<^sub>C f) = 0\\<close>)\n    hence \\<open>h - k \\<in> orthogonal_complement M \\<and> k \\<in> M\\<close>\n      by (simp add: \\<open>k \\<in> M\\<close> orthogonal_complementI)\n    have  \\<open>\\<forall> c. c *\\<^sub>R f \\<in> M\\<close>\n      if \"f \\<in> M\"\n      for f\n      using that scaleR_scaleC  \\<open>csubspace M\\<close> complex_vector.subspace_def\n      by (simp add: complex_vector.subspace_def scaleR_scaleC)\n    have \\<open>((h - k) \\<bullet>\\<^sub>C f) = 0\\<close>\n      if \"f \\<in> M\"\n      for f\n      using \\<open>h - k \\<in> orthogonal_complement M \\<and> k \\<in> M\\<close> orthogonal_complement_orthoI that by auto\n    hence \\<open>h - k \\<in> orthogonal_complement M\\<close>\n      by (simp add: orthogonal_complement_def)\n    thus ?thesis\n      using \\<open>k \\<in> M\\<close> by auto\n  qed\n\n  have q1: \\<open>dist h k \\<le> dist h f \\<close>\n    if \"f \\<in> M\" and  \\<open>h - k \\<in> orthogonal_complement M \\<and> k \\<in> M\\<close>\n    for f\n  proof-\n    have \\<open>(h - k) \\<bullet>\\<^sub>C (k - f) = 0\\<close>\n      by (metis (no_types, lifting) that\n          cinner_diff_right diff_0_right orthogonal_complement_orthoI that)\n    have \\<open>\\<parallel> h - f \\<parallel>^2 = \\<parallel> (h - k) + (k - f) \\<parallel>^2\\<close>\n      by simp\n    also have \\<open>... = \\<parallel> h - k \\<parallel>^2 + \\<parallel> k - f \\<parallel>^2\\<close>\n      using  \\<open>((h - k) \\<bullet>\\<^sub>C (k - f)) = 0\\<close> pythagorean_theorem by blast\n    also have \\<open>... \\<ge> \\<parallel> h - k \\<parallel>^2\\<close>\n      by simp\n    finally have \\<open>\\<parallel>h - k\\<parallel>\\<^sup>2 \\<le> \\<parallel>h - f\\<parallel>\\<^sup>2 \\<close>\n      by blast\n    hence \\<open>\\<parallel>h - k\\<parallel> \\<le> \\<parallel>h - f\\<parallel>\\<close>\n      using norm_ge_zero power2_le_imp_le by blast\n    thus ?thesis\n      by (simp add: dist_norm)\n  qed\n\n  have  w1: \"is_arg_min (\\<lambda> x. dist x h) (\\<lambda> x. x \\<in> M) k\"\n    if \"h - k \\<in> orthogonal_complement M \\<and> k \\<in>  M\"\n  proof-\n    have \\<open>h - k \\<in> orthogonal_complement M\\<close>\n      using that by blast\n    have \\<open>k \\<in> M\\<close> using \\<open>h - k \\<in> orthogonal_complement M \\<and> k \\<in>  M\\<close>\n      by blast\n    thus ?thesis\n      by (metis (no_types, lifting) dist_commute is_arg_min_linorder q1 that)\n  qed\n  show ?thesis\n    using w1 w2 by blast\nqed\n\ncorollary orthog_proj_exists:\n  fixes M :: \\<open>'a::chilbert_space set\\<close>\n  assumes \\<open>closed_csubspace M\\<close>\n  shows  \\<open>\\<exists>k. h - k \\<in> orthogonal_complement M \\<and> k \\<in> M\\<close>\nproof -\n  from  \\<open>closed_csubspace M\\<close>\n  have \\<open>M \\<noteq> {}\\<close>\n    using closed_csubspace.subspace complex_vector.subspace_0 by blast\n  have \\<open>closed  M\\<close>\n    using  \\<open>closed_csubspace M\\<close>\n    by (simp add: closed_csubspace.closed)\n  have \\<open>convex  M\\<close>\n    using  \\<open>closed_csubspace M\\<close>\n    by (simp)\n  have \\<open>\\<exists>k.  is_arg_min (\\<lambda> x. dist x h) (\\<lambda> x. x \\<in> M) k\\<close>\n    by (simp add: smallest_dist_exists \\<open>closed M\\<close> \\<open>convex M\\<close> \\<open>M \\<noteq> {}\\<close>)\n  thus ?thesis\n    by (simp add: assms smallest_dist_is_ortho)\nqed\n\ncorollary orthog_proj_unique:\n  fixes M :: \\<open>'a::complex_inner set\\<close>\n  assumes \\<open>closed_csubspace M\\<close>\n  assumes \\<open>h - r \\<in> orthogonal_complement M \\<and> r \\<in> M\\<close>\n  assumes \\<open>h - s \\<in> orthogonal_complement M \\<and> s \\<in> M\\<close>\n  shows  \\<open>r = s\\<close>\n  using _ assms(2,3) unfolding smallest_dist_is_ortho[OF assms(1), symmetric]\n  apply (rule smallest_dist_unique)\n  using assms(1) by (simp)\n\ndefinition is_projection_on::\\<open>('a \\<Rightarrow> 'a) \\<Rightarrow> ('a::metric_space) set \\<Rightarrow> bool\\<close> where\n  \\<open>is_projection_on \\<pi> M \\<longleftrightarrow> (\\<forall>h. is_arg_min (\\<lambda> x. dist x h) (\\<lambda> x. x \\<in> M) (\\<pi> h))\\<close>\n\nlemma is_projection_on_iff_orthog:\n  \\<open>closed_csubspace M \\<Longrightarrow> is_projection_on \\<pi> M \\<longleftrightarrow> (\\<forall>h. h - \\<pi> h \\<in> orthogonal_complement M \\<and> \\<pi> h \\<in> M)\\<close>\n  by (simp add: is_projection_on_def smallest_dist_is_ortho)\n\nlemma is_projection_on_exists:\n  fixes M :: \\<open>'a::chilbert_space set\\<close>\n  assumes \\<open>convex M\\<close> and \\<open>closed M\\<close> and \\<open>M \\<noteq> {}\\<close>\n  shows \"\\<exists>\\<pi>. is_projection_on \\<pi> M\"\n  unfolding is_projection_on_def apply (rule choice)\n  using smallest_dist_exists[OF assms] by auto\n\nlemma is_projection_on_unique:\n  fixes M :: \\<open>'a::complex_inner set\\<close>\n  assumes \\<open>convex M\\<close>\n  assumes \"is_projection_on \\<pi>\\<^sub>1 M\"\n  assumes \"is_projection_on \\<pi>\\<^sub>2 M\"\n  shows \"\\<pi>\\<^sub>1 = \\<pi>\\<^sub>2\"\n  using smallest_dist_unique[OF assms(1)] using assms(2,3)\n  unfolding is_projection_on_def by blast\n\ndefinition projection :: \\<open>'a::metric_space set \\<Rightarrow> ('a \\<Rightarrow> 'a)\\<close> where\n  \\<open>projection M \\<equiv> SOME \\<pi>. is_projection_on \\<pi> M\\<close>\n\nlemma projection_is_projection_on:\n  fixes M :: \\<open>'a::chilbert_space set\\<close>\n  assumes \\<open>convex M\\<close> and \\<open>closed M\\<close> and \\<open>M \\<noteq> {}\\<close>\n  shows \"is_projection_on (projection M) M\"\n  by (metis assms(1) assms(2) assms(3) is_projection_on_exists projection_def someI)\n\nlemma projection_is_projection_on'[simp]:\n  \\<comment> \\<open>Common special case of @{thm projection_is_projection_on}\\<close>\n  fixes M :: \\<open>'a::chilbert_space set\\<close>\n  assumes \\<open>closed_csubspace M\\<close>\n  shows \"is_projection_on (projection M) M\"\n  apply (rule projection_is_projection_on)\n    apply (auto simp add: assms closed_csubspace.closed)\n  using assms closed_csubspace.subspace complex_vector.subspace_0 by blast\n\nlemma projection_orthogonal:\n  fixes M :: \\<open>'a::chilbert_space set\\<close>\n  assumes \"closed_csubspace M\" and \\<open>m \\<in> M\\<close>\n  shows \\<open>is_orthogonal (h - projection M h) m\\<close>\n  by (metis assms(1) assms(2) closed_csubspace.closed closed_csubspace.subspace csubspace_is_convex empty_iff is_projection_on_iff_orthog orthogonal_complement_orthoI projection_is_projection_on)\n\nlemma is_projection_on_in_image:\n  assumes \"is_projection_on \\<pi> M\"\n  shows \"\\<pi> h \\<in> M\"\n  using assms\n  by (simp add: is_arg_min_def is_projection_on_def)\n\nlemma is_projection_on_image:\n  assumes \"is_projection_on \\<pi> M\"\n  shows \"range \\<pi> = M\"\n  using assms\n  apply (auto simp: is_projection_on_in_image)\n  by (smt (verit, ccfv_threshold) dist_pos_lt dist_self is_arg_min_def is_projection_on_def rangeI)\n\nlemma projection_in_image[simp]:\n  fixes M :: \\<open>'a::chilbert_space set\\<close>\n  assumes \\<open>convex M\\<close> and \\<open>closed M\\<close> and \\<open>M \\<noteq> {}\\<close>\n  shows \\<open>projection M h \\<in> M\\<close>\n  by (simp add: assms(1) assms(2) assms(3) is_projection_on_in_image projection_is_projection_on)\n\nlemma projection_image[simp]:\n  fixes M :: \\<open>'a::chilbert_space set\\<close>\n  assumes \\<open>convex M\\<close> and \\<open>closed M\\<close> and \\<open>M \\<noteq> {}\\<close>\n  shows \\<open>range (projection M) = M\\<close>\n  by (simp add: assms(1) assms(2) assms(3) is_projection_on_image projection_is_projection_on)\n\nlemma projection_eqI':\n  fixes M :: \\<open>'a::complex_inner set\\<close>\n  assumes \\<open>convex M\\<close>\n  assumes \\<open>is_projection_on f M\\<close>\n  shows \\<open>projection M = f\\<close>\n  by (metis assms(1) assms(2) is_projection_on_unique projection_def someI_ex)\n\nlemma is_projection_on_eqI:\n  fixes  M :: \\<open>'a::complex_inner set\\<close>\n  assumes a1: \\<open>closed_csubspace M\\<close> and a2: \\<open>h - x \\<in> orthogonal_complement M\\<close> and a3: \\<open>x \\<in> M\\<close>\n    and a4: \\<open>is_projection_on \\<pi> M\\<close>\n  shows \\<open>\\<pi> h = x\\<close>\n  by (meson a1 a2 a3 a4 closed_csubspace.subspace csubspace_is_convex is_projection_on_def smallest_dist_is_ortho smallest_dist_unique)\n\nlemma projection_eqI:\n  fixes  M :: \\<open>('a::chilbert_space) set\\<close>\n  assumes  \\<open>closed_csubspace M\\<close> and \\<open>h - x \\<in> orthogonal_complement M\\<close> and \\<open>x \\<in> M\\<close>\n  shows \\<open>projection M h = x\\<close>\n  by (metis assms(1) assms(2) assms(3) is_projection_on_iff_orthog orthog_proj_exists projection_def is_projection_on_eqI tfl_some)\n\nlemma is_projection_on_fixes_image:\n  fixes M :: \\<open>'a::metric_space set\\<close>\n  assumes a1: \"is_projection_on \\<pi> M\" and a3: \"x \\<in> M\"\n  shows \"\\<pi> x = x\"\n  by (metis a1 a3 dist_pos_lt dist_self is_arg_min_def is_projection_on_def)\n\nlemma projection_fixes_image:\n  fixes M :: \\<open>('a::chilbert_space) set\\<close>\n  assumes \"closed_csubspace M\" and \"x \\<in> M\"\n  shows \"projection M x = x\"\n  using is_projection_on_fixes_image\n    \\<comment> \\<open>Theorem 2.7 in \\<^cite>\\<open>conway2013course\\<close>\\<close>\n  by (simp add: assms complex_vector.subspace_0 projection_eqI)\n\nlemma is_projection_on_closed:\n  assumes cont_f: \\<open>\\<And>x. x \\<in> closure M \\<Longrightarrow> isCont f x\\<close>\n  assumes \\<open>is_projection_on f M\\<close>\n  shows \\<open>closed M\\<close>\nproof -\n  have \\<open>x \\<in> M\\<close> if \\<open>s \\<longlonglongrightarrow> x\\<close> and \\<open>range s \\<subseteq> M\\<close> for s x\n  proof -\n    from \\<open>is_projection_on f M\\<close> \\<open>range s \\<subseteq> M\\<close>\n    have \\<open>s = (f o s)\\<close>\n      by (simp add: comp_def is_projection_on_fixes_image range_subsetD)\n    also from cont_f \\<open>s \\<longlonglongrightarrow> x\\<close> \n    have \\<open>(f o s) \\<longlonglongrightarrow> f x\\<close>\n      apply (rule continuous_imp_tendsto)\n      using \\<open>s \\<longlonglongrightarrow> x\\<close> \\<open>range s \\<subseteq> M\\<close>\n      by (meson closure_sequential range_subsetD)\n    finally have \\<open>x = f x\\<close>\n      using \\<open>s \\<longlonglongrightarrow> x\\<close>\n      by (simp add: LIMSEQ_unique)\n    then have \\<open>x \\<in> range f\\<close>\n      by simp\n    with \\<open>is_projection_on f M\\<close> show \\<open>x \\<in> M\\<close>\n      by (simp add: is_projection_on_image)\n  qed\n  then show ?thesis\n    by (metis closed_sequential_limits image_subset_iff)\nqed\n\nproposition is_projection_on_reduces_norm:\n  includes notation_norm\n  fixes M :: \\<open>('a::complex_inner) set\\<close>\n  assumes \\<open>is_projection_on \\<pi> M\\<close> and \\<open>closed_csubspace M\\<close>\n  shows \\<open>\\<parallel> \\<pi>  h \\<parallel> \\<le> \\<parallel> h \\<parallel>\\<close>\nproof-\n  have \\<open>h - \\<pi> h \\<in> orthogonal_complement M\\<close>\n    using assms is_projection_on_iff_orthog by blast\n  hence \\<open>\\<forall> k \\<in> M. is_orthogonal (h - \\<pi> h) k\\<close>\n    using orthogonal_complement_orthoI by blast\n  also have \\<open>\\<pi> h \\<in>  M\\<close>\n    using \\<open>is_projection_on \\<pi> M\\<close>\n    by (simp add: is_projection_on_in_image)\n  ultimately have \\<open>is_orthogonal (h - \\<pi> h) (\\<pi> h)\\<close>\n    by auto\n  hence \\<open>\\<parallel> \\<pi> h \\<parallel>^2 + \\<parallel> h - \\<pi> h \\<parallel>^2 = \\<parallel> h \\<parallel>^2\\<close>\n    using pythagorean_theorem by fastforce\n  hence \\<open>\\<parallel>\\<pi> h \\<parallel>^2 \\<le> \\<parallel> h \\<parallel>^2\\<close>\n    by (smt zero_le_power2)\n  thus ?thesis\n    using norm_ge_zero power2_le_imp_le by blast\nqed\n\nproposition projection_reduces_norm:\n  includes notation_norm\n  fixes M :: \\<open>'a::chilbert_space set\\<close>\n  assumes a1: \"closed_csubspace M\"\n  shows \\<open>\\<parallel> projection M h \\<parallel> \\<le> \\<parallel> h \\<parallel>\\<close>\n  using assms is_projection_on_iff_orthog orthog_proj_exists is_projection_on_reduces_norm projection_eqI by blast\n\n\\<comment> \\<open>Theorem 2.7 (version) in \\<^cite>\\<open>conway2013course\\<close>\\<close>\ntheorem is_projection_on_bounded_clinear:\n  fixes M :: \\<open>'a::complex_inner set\\<close>\n  assumes a1: \"is_projection_on \\<pi> M\" and a2: \"closed_csubspace M\"\n  shows \"bounded_clinear \\<pi>\"\nproof\n  have b1:  \\<open>csubspace (orthogonal_complement M)\\<close>\n    by (simp add: a2)\n  have f1: \"\\<forall>a. a - \\<pi> a \\<in> orthogonal_complement M \\<and> \\<pi> a \\<in> M\"\n    using a1 a2 is_projection_on_iff_orthog by blast\n  hence \"c *\\<^sub>C x - c *\\<^sub>C \\<pi> x \\<in> orthogonal_complement M\"\n    for c x\n    by (metis (no_types) b1\n        add_diff_cancel_right' complex_vector.subspace_def diff_add_cancel scaleC_add_right)\n  thus r1: \\<open>\\<pi> (c *\\<^sub>C x) = c *\\<^sub>C (\\<pi> x)\\<close> for x c\n    using f1 by (meson a2 a1 closed_csubspace.subspace\n        complex_vector.subspace_def is_projection_on_eqI)\n  show r2: \\<open>\\<pi> (x + y) =  (\\<pi> x) + (\\<pi> y)\\<close>\n    for x y\n  proof-\n    have \"\\<forall>A. \\<not> closed_csubspace (A::'a set) \\<or> csubspace A\"\n      by (metis closed_csubspace.subspace)\n    hence \"csubspace M\"\n      using a2 by auto\n    hence \\<open>\\<pi> (x + y) - ( (\\<pi> x) + (\\<pi> y) ) \\<in> M\\<close>\n      by (simp add: complex_vector.subspace_add complex_vector.subspace_diff f1)\n    have \\<open>closed_csubspace (orthogonal_complement M)\\<close>\n      using a2\n      by simp\n    have f1: \"\\<forall>a b. (b::'a) + (a - b) = a\"\n      by (metis add.commute diff_add_cancel)\n    have f2: \"\\<forall>a b. (b::'a) - b = a - a\"\n      by auto\n    hence f3: \"\\<forall>a. a - a \\<in> orthogonal_complement M\"\n      by (simp add: complex_vector.subspace_0)\n    have \"\\<forall>a b. (a \\<in> orthogonal_complement M \\<or> a + b \\<notin> orthogonal_complement M)\n             \\<or> b \\<notin> orthogonal_complement M\"\n      using add_diff_cancel_right' b1 complex_vector.subspace_diff\n      by metis\n    hence \"\\<forall>a b c. (a \\<in> orthogonal_complement M \\<or> c - (b + a) \\<notin> orthogonal_complement M)\n              \\<or> c - b \\<notin> orthogonal_complement M\"\n      using f1 by (metis diff_diff_add)\n    hence f4: \"\\<forall>a b f. (f a - b \\<in> orthogonal_complement M \\<or> a - b \\<notin> orthogonal_complement M)\n              \\<or> \\<not> is_projection_on f M\"\n      using f1\n      by (metis a2 is_projection_on_iff_orthog)\n    have f5: \"\\<forall>a b c d. (d::'a) - (c + (b - a)) = d + (a - (b + c))\"\n      by auto\n    have \"x - \\<pi> x \\<in> orthogonal_complement M\"\n      using a1 a2 is_projection_on_iff_orthog by blast\n    hence q1: \\<open>\\<pi> (x + y) - ( (\\<pi> x) + (\\<pi> y) ) \\<in> orthogonal_complement M\\<close>\n      using f5 f4 f3 by (metis \\<open>csubspace (orthogonal_complement M)\\<close>\n          \\<open>is_projection_on \\<pi> M\\<close> add_diff_eq complex_vector.subspace_diff diff_diff_add\n          diff_diff_eq2)\n    hence \\<open>\\<pi> (x + y) - ( (\\<pi> x) + (\\<pi> y) ) \\<in> M \\<inter> (orthogonal_complement M)\\<close>\n      by (simp add: \\<open>\\<pi> (x + y) - (\\<pi> x + \\<pi> y) \\<in> M\\<close>)\n    moreover have \\<open>M \\<inter> (orthogonal_complement M) = {0}\\<close>\n      by (simp add: \\<open>closed_csubspace M\\<close> complex_vector.subspace_0 orthogonal_complement_zero_intersection)\n    ultimately have \\<open>\\<pi> (x + y) - ( (\\<pi> x) + (\\<pi> y) ) = 0\\<close>\n      by auto\n    thus ?thesis by simp\n  qed\n  from is_projection_on_reduces_norm\n  show t1: \\<open>\\<exists> K. \\<forall> x. norm (\\<pi> x) \\<le> norm x * K\\<close>\n    by (metis a1 a2 mult.left_neutral ordered_field_class.sign_simps(5))\nqed\n\ntheorem projection_bounded_clinear:\n  fixes M :: \\<open>('a::chilbert_space) set\\<close>\n  assumes a1: \"closed_csubspace M\"\n  shows \\<open>bounded_clinear (projection M)\\<close>\n    \\<comment> \\<open>Theorem 2.7 in \\<^cite>\\<open>conway2013course\\<close>\\<close>\n  using assms is_projection_on_iff_orthog orthog_proj_exists is_projection_on_bounded_clinear projection_eqI by blast\n\nproposition is_projection_on_idem:\n  fixes M :: \\<open>('a::complex_inner) set\\<close>\n  assumes \"is_projection_on \\<pi> M\"\n  shows \"\\<pi> (\\<pi> x) = \\<pi> x\"\n  using is_projection_on_fixes_image is_projection_on_in_image assms by blast\n\nproposition projection_idem:\n  fixes M :: \"'a::chilbert_space set\"\n  assumes a1: \"closed_csubspace M\"\n  shows \"projection M (projection M x) = projection M x\"\n  by (metis assms closed_csubspace.closed closed_csubspace.subspace complex_vector.subspace_0 csubspace_is_convex equals0D projection_fixes_image projection_in_image)\n\n\nproposition is_projection_on_kernel_is_orthogonal_complement:\n  fixes M :: \\<open>'a::complex_inner set\\<close>\n  assumes a1: \"is_projection_on \\<pi> M\" and a2: \"closed_csubspace M\"\n  shows \"\\<pi> -` {0} = orthogonal_complement M\"\nproof-\n  have \"x \\<in> (\\<pi> -` {0})\"\n    if \"x \\<in> orthogonal_complement M\"\n    for x\n    by (smt (verit, ccfv_SIG) a1 a2 closed_csubspace_def complex_vector.subspace_def complex_vector.subspace_diff is_projection_on_eqI orthogonal_complement_closed_subspace that vimage_singleton_eq)\n  moreover have \"x \\<in> orthogonal_complement M\"\n    if s1: \"x \\<in> \\<pi> -` {0}\" for x\n    by (metis a1 a2 diff_zero is_projection_on_iff_orthog that vimage_singleton_eq)\n  ultimately show ?thesis\n    by blast\nqed\n\n\\<comment> \\<open>Theorem 2.7 in \\<^cite>\\<open>conway2013course\\<close>\\<close>\nproposition projection_kernel_is_orthogonal_complement:\n  fixes M :: \\<open>'a::chilbert_space set\\<close>\n  assumes \"closed_csubspace M\"\n  shows \"(projection M) -` {0} = (orthogonal_complement M)\"\n  by (metis assms closed_csubspace_def complex_vector.subspace_def csubspace_is_convex insert_absorb insert_not_empty is_projection_on_kernel_is_orthogonal_complement projection_is_projection_on)\n\nlemma is_projection_on_id_minus:\n  fixes M :: \\<open>'a::complex_inner set\\<close>\n  assumes is_proj: \"is_projection_on \\<pi> M\"\n    and cc: \"closed_csubspace M\"\n  shows \"is_projection_on (id - \\<pi>) (orthogonal_complement M)\"\n  using is_proj apply (simp add: cc is_projection_on_iff_orthog)\n  using double_orthogonal_complement_increasing by blast\n\n\ntext \\<open>Exercise 2 (section 2, chapter I) in  \\<^cite>\\<open>conway2013course\\<close>\\<close>\nlemma projection_on_orthogonal_complement[simp]:\n  fixes M :: \"'a::chilbert_space set\"\n  assumes a1: \"closed_csubspace M\"\n  shows \"projection (orthogonal_complement M) = id - projection M\"\n  apply (auto intro!: ext)\n  by (smt (verit, ccfv_SIG) add_diff_cancel_left' assms closed_csubspace.closed closed_csubspace.subspace complex_vector.subspace_0 csubspace_is_convex diff_add_cancel double_orthogonal_complement_increasing insert_absorb insert_not_empty is_projection_on_iff_orthog orthogonal_complement_closed_subspace projection_eqI projection_is_projection_on subset_eq)\n\nlemma is_projection_on_zero:\n  \"is_projection_on (\\<lambda>_. 0) {0}\"\n  by (simp add: is_projection_on_def is_arg_min_def)\n\nlemma projection_zero[simp]:\n  \"projection {0} = (\\<lambda>_. 0)\"\n  using is_projection_on_zero\n  by (metis (full_types) is_projection_on_in_image projection_def singletonD someI_ex)\n\nlemma is_projection_on_rank1:\n  fixes t :: \\<open>'a::complex_inner\\<close>\n  shows \\<open>is_projection_on (\\<lambda>x. ((t \\<bullet>\\<^sub>C x) / (t \\<bullet>\\<^sub>C t)) *\\<^sub>C t) (cspan {t})\\<close>\nproof (cases \\<open>t = 0\\<close>)\n  case True\n  then show ?thesis\n    by (simp add: is_projection_on_zero)\nnext\n  case False\n  define P where \\<open>P x = ((t \\<bullet>\\<^sub>C x) / (t \\<bullet>\\<^sub>C t)) *\\<^sub>C t\\<close> for x\n  define t' where \\<open>t' = t /\\<^sub>C norm t\\<close>\n  with False have \\<open>norm t' = 1\\<close>\n    by (simp add: norm_inverse)\n  have P_def': \\<open>P x = cinner t' x *\\<^sub>C t'\\<close> for x\n    unfolding P_def t'_def apply auto\n    by (metis divide_divide_eq_left divide_inverse mult.commute power2_eq_square power2_norm_eq_cinner)\n  have spant': \\<open>cspan {t} = cspan {t'}\\<close>\n    by (simp add: False t'_def)\n  have cc: \\<open>closed_csubspace (cspan {t})\\<close>\n    by (auto intro!: finite_cspan_closed closed_csubspace.intro)\n  have ortho: \\<open>h - P h \\<in> orthogonal_complement (cspan {t})\\<close> for h\n    unfolding orthogonal_complement_def P_def' spant' apply auto\n    by (smt (verit, ccfv_threshold) \\<open>norm t' = 1\\<close> add_cancel_right_left cinner_add_right cinner_commute' cinner_scaleC_right cnorm_eq_1 complex_vector.span_breakdown_eq complex_vector.span_empty diff_add_cancel mult_cancel_left1 singletonD)\n  have inspan: \\<open>P h \\<in> cspan {t}\\<close> for h\n    unfolding P_def' spant'\n    by (simp add: complex_vector.span_base complex_vector.span_scale)\n  show \\<open>is_projection_on P (cspan {t})\\<close>\n    apply (subst is_projection_on_iff_orthog)\n    using cc ortho inspan by auto\nqed\n\nlemma projection_rank1:\n  fixes t x :: \\<open>'a::complex_inner\\<close>\n  shows \\<open>projection (cspan {t}) x = ((t \\<bullet>\\<^sub>C x) / (t \\<bullet>\\<^sub>C t)) *\\<^sub>C t\\<close>\n  apply (rule fun_cong, rule projection_eqI', simp)\n  by (rule is_projection_on_rank1)\n\nsubsection \\<open>More orthogonal complement\\<close>\n\ntext \\<open>The following lemmas logically fit into the \"orthogonality\" section but depend on projections for their proofs.\\<close>\n\ntext \\<open>Corollary 2.8 in \\<^cite>\\<open>conway2013course\\<close>\\<close>\ntheorem double_orthogonal_complement_id[simp]:\n  fixes M :: \\<open>'a::chilbert_space set\\<close>\n  assumes a1: \"closed_csubspace M\"\n  shows \"orthogonal_complement (orthogonal_complement M) = M\"\nproof-\n  have b2: \"x \\<in> (id - projection M) -` {0}\"\n    if c1: \"x \\<in> M\" for x\n    by (simp add: assms projection_fixes_image that)\n\n  have b3: \\<open>x \\<in> M\\<close>\n    if c1: \\<open>x \\<in> (id - projection M) -` {0}\\<close> for x\n    by (metis assms closed_csubspace.closed closed_csubspace.subspace complex_vector.subspace_0 csubspace_is_convex eq_id_iff equals0D fun_diff_def projection_in_image right_minus_eq that vimage_singleton_eq)\n  have \\<open>x \\<in>  M \\<longleftrightarrow> x \\<in> (id - projection M) -` {0}\\<close> for x\n    using b2 b3 by blast\n  hence b4: \\<open>( id - (projection M) ) -` {0} =  M\\<close>\n    by blast\n  have b1: \"orthogonal_complement (orthogonal_complement M)\n          = (projection (orthogonal_complement M)) -` {0}\"\n    by (simp add: a1 projection_kernel_is_orthogonal_complement del: projection_on_orthogonal_complement)\n  also have \\<open>... = ( id - (projection M) ) -` {0}\\<close>\n    by (simp add: a1)\n  also have \\<open>... = M\\<close>\n    by (simp add: b4)\n  finally show ?thesis by blast\nqed\n\nlemma orthogonal_complement_antimono_iff[simp]:\n  fixes  A B :: \\<open>('a::chilbert_space) set\\<close>\n  assumes \\<open>closed_csubspace A\\<close> and  \\<open>closed_csubspace B\\<close>\n  shows \\<open>orthogonal_complement A \\<subseteq> orthogonal_complement B \\<longleftrightarrow> A \\<supseteq> B\\<close>\nproof (rule iffI)\n  show \\<open>orthogonal_complement A \\<subseteq> orthogonal_complement B\\<close> if \\<open>A \\<supseteq> B\\<close>\n    using that by auto\n\n  assume \\<open>orthogonal_complement A \\<subseteq> orthogonal_complement B\\<close>\n  then have \\<open>orthogonal_complement (orthogonal_complement A) \\<supseteq> orthogonal_complement (orthogonal_complement B)\\<close>\n    by simp\n  then show \\<open>A \\<supseteq> B\\<close>\n    using assms by auto\nqed\n\nlemma de_morgan_orthogonal_complement_plus:\n  fixes A B::\"('a::complex_inner) set\"\n  assumes \\<open>0 \\<in> A\\<close> and \\<open>0 \\<in> B\\<close>\n  shows \\<open>orthogonal_complement (A +\\<^sub>M B) = orthogonal_complement A \\<inter> orthogonal_complement B\\<close>\nproof -\n  have \"x \\<in> (orthogonal_complement A) \\<inter> (orthogonal_complement B)\"\n    if \"x \\<in> orthogonal_complement (A +\\<^sub>M B)\" for x\n  proof -\n    have \\<open>orthogonal_complement (A +\\<^sub>M B) = orthogonal_complement (A + B)\\<close>\n      unfolding closed_sum_def by (subst orthogonal_complement_of_closure[symmetric], simp)\n    hence \\<open>x \\<in> orthogonal_complement (A + B)\\<close>\n      using that by blast\n    hence t1: \\<open>\\<forall>z \\<in> (A + B). (z \\<bullet>\\<^sub>C x) = 0\\<close>\n      by (simp add: orthogonal_complement_orthoI')\n    have \\<open>A \\<subseteq> A + B\\<close>\n      using subset_iff add.commute set_zero_plus2 \\<open>0 \\<in> B\\<close>\n      by fastforce\n    hence \\<open>\\<forall>z \\<in> A. (z \\<bullet>\\<^sub>C x) = 0\\<close>\n      using t1 by auto\n    hence w1: \\<open>x \\<in> (orthogonal_complement A)\\<close>\n      by (smt mem_Collect_eq is_orthogonal_sym orthogonal_complement_def)\n    have \\<open>B \\<subseteq> A + B\\<close>\n      using \\<open>0 \\<in> A\\<close> subset_iff set_zero_plus2 by blast\n    hence \\<open>\\<forall> z \\<in> B. (z \\<bullet>\\<^sub>C x) = 0\\<close>\n      using t1 by auto\n    hence \\<open>x \\<in> (orthogonal_complement B)\\<close>\n      by (smt mem_Collect_eq is_orthogonal_sym orthogonal_complement_def)\n    thus ?thesis\n      using w1 by auto\n  qed\n  moreover have \"x \\<in> (orthogonal_complement (A +\\<^sub>M B))\"\n    if v1: \"x \\<in> (orthogonal_complement A) \\<inter> (orthogonal_complement B)\"\n    for x\n  proof-\n    have \\<open>x \\<in> (orthogonal_complement A)\\<close>\n      using v1\n      by blast\n    hence \\<open>\\<forall>y\\<in> A. (y \\<bullet>\\<^sub>C x) = 0\\<close>\n      by (simp add: orthogonal_complement_orthoI')\n    have \\<open>x \\<in> (orthogonal_complement B)\\<close>\n      using v1\n      by blast\n    hence \\<open>\\<forall> y\\<in> B. (y \\<bullet>\\<^sub>C x) = 0\\<close>\n      by (simp add: orthogonal_complement_orthoI')\n    have \\<open>\\<forall> a\\<in>A. \\<forall> b\\<in>B. (a+b) \\<bullet>\\<^sub>C x = 0\\<close>\n      by (simp add: \\<open>\\<forall>y\\<in>A. y \\<bullet>\\<^sub>C x = 0\\<close> \\<open>\\<forall>y\\<in>B. (y \\<bullet>\\<^sub>C x) = 0\\<close> cinner_add_left)\n    hence \\<open>\\<forall> y \\<in> (A + B). y \\<bullet>\\<^sub>C x = 0\\<close>\n      using set_plus_elim by force\n    hence \\<open>x \\<in> (orthogonal_complement (A + B))\\<close>\n      by (smt mem_Collect_eq is_orthogonal_sym orthogonal_complement_def)\n    moreover have \\<open>(orthogonal_complement (A + B)) = (orthogonal_complement (A +\\<^sub>M B))\\<close>\n      unfolding closed_sum_def by (subst orthogonal_complement_of_closure[symmetric], simp)\n    ultimately have \\<open>x \\<in> (orthogonal_complement (A +\\<^sub>M B))\\<close>\n      by blast\n    thus ?thesis\n      by blast\n  qed\n  ultimately show ?thesis by blast\nqed\n\nlemma de_morgan_orthogonal_complement_inter:\n  fixes A B::\"'a::chilbert_space set\"\n  assumes a1: \\<open>closed_csubspace A\\<close> and a2: \\<open>closed_csubspace B\\<close>\n  shows  \\<open>orthogonal_complement (A \\<inter> B) = orthogonal_complement A +\\<^sub>M orthogonal_complement B\\<close>\nproof-\n  have \\<open>orthogonal_complement A +\\<^sub>M orthogonal_complement B\n    = orthogonal_complement (orthogonal_complement (orthogonal_complement A +\\<^sub>M orthogonal_complement B))\\<close>\n    by (simp add: closed_subspace_closed_sum)\n  also have \\<open>\\<dots> = orthogonal_complement (orthogonal_complement (orthogonal_complement A) \\<inter> orthogonal_complement (orthogonal_complement B))\\<close>\n    by (simp add: de_morgan_orthogonal_complement_plus orthogonal_complementI)\n  also have \\<open>\\<dots> = orthogonal_complement (A \\<inter> B)\\<close>\n    by (simp add: a1 a2)\n  finally show ?thesis\n    by simp\nqed\n\nlemma orthogonal_complement_of_cspan: \\<open>orthogonal_complement A = orthogonal_complement (cspan A)\\<close>\n  by (metis (no_types, opaque_lifting) closed_csubspace.subspace complex_vector.span_minimal complex_vector.span_superset double_orthogonal_complement_increasing orthogonal_complement_antimono orthogonal_complement_closed_subspace subset_antisym)\n\nlemma orthogonal_complement_orthogonal_complement_closure_cspan:\n  \\<open>orthogonal_complement (orthogonal_complement S) = closure (cspan S)\\<close> for S :: \\<open>'a::chilbert_space set\\<close>\nproof -\n  have \\<open>orthogonal_complement (orthogonal_complement S) = orthogonal_complement (orthogonal_complement (closure (cspan S)))\\<close>\n    by (simp flip: orthogonal_complement_of_closure orthogonal_complement_of_cspan)\n  also have \\<open>\\<dots> = closure (cspan S)\\<close>\n    by simp\n  finally show \\<open>orthogonal_complement (orthogonal_complement S) = closure (cspan S)\\<close>\n    by -\nqed\n\ninstance ccsubspace :: (chilbert_space) complete_orthomodular_lattice\nproof\n  fix X Y :: \\<open>'a ccsubspace\\<close>\n\n  show \"inf X (- X) = bot\"\n    apply transfer\n    by (simp add: closed_csubspace_def complex_vector.subspace_0 orthogonal_complement_zero_intersection)\n\n  have \\<open>t \\<in> M +\\<^sub>M orthogonal_complement M\\<close>\n    if \\<open>closed_csubspace M\\<close> for t::'a and M\n    by (metis (no_types, lifting) UNIV_I closed_csubspace.subspace complex_vector.subspace_def de_morgan_orthogonal_complement_inter double_orthogonal_complement_id orthogonal_complement_closed_subspace orthogonal_complement_zero orthogonal_complement_zero_intersection that)\n  hence b1: \\<open>M +\\<^sub>M orthogonal_complement M = UNIV\\<close>\n    if \\<open>closed_csubspace M\\<close> for M :: \\<open>'a set\\<close>\n    using that by blast\n  show \"sup X (- X) = top\"\n    apply transfer\n    using b1 by auto\n  show \"- (- X) = X\"\n    apply transfer by simp\n\n  show \"- Y \\<le> - X\"\n    if \"X \\<le> Y\"\n    using that apply transfer by simp\n\n  have c1: \"M +\\<^sub>M orthogonal_complement M \\<inter> N \\<subseteq> N\"\n    if \"closed_csubspace M\" and \"closed_csubspace N\" and \"M \\<subseteq> N\"\n    for M N :: \"'a set\"\n    using that\n    by (simp add: closed_sum_is_sup)\n\n  have c2: \\<open>u \\<in> M +\\<^sub>M (orthogonal_complement M \\<inter> N)\\<close>\n    if a1: \"closed_csubspace M\" and a2: \"closed_csubspace N\" and a3: \"M \\<subseteq> N\" and x1: \\<open>u \\<in> N\\<close>\n    for M :: \"'a set\" and N :: \"'a set\"  and u\n  proof -\n    have d4: \\<open>(projection M) u \\<in> M\\<close>\n      by (metis a1 closed_csubspace_def csubspace_is_convex equals0D orthog_proj_exists projection_in_image)\n    hence d2: \\<open>(projection M) u \\<in> N\\<close>\n      using a3 by auto\n    have d1: \\<open>csubspace N\\<close>\n      by (simp add: a2)\n    have \\<open>u - (projection M) u \\<in> orthogonal_complement M\\<close>\n      by (simp add: a1 orthogonal_complementI projection_orthogonal)\n    moreover have  \\<open>u - (projection M) u \\<in> N\\<close>\n      by (simp add: d1 d2 complex_vector.subspace_diff x1)\n    ultimately have d3: \\<open>u - (projection M) u \\<in> ((orthogonal_complement M) \\<inter> N)\\<close>\n      by simp\n    hence \\<open>\\<exists> v \\<in> ((orthogonal_complement M) \\<inter> N). u = (projection M) u + v\\<close>\n      by (metis d3 diff_add_cancel ordered_field_class.sign_simps(2))\n    then obtain v where \\<open>v \\<in> ((orthogonal_complement M) \\<inter> N)\\<close> and \\<open>u = (projection M) u + v\\<close>\n      by blast\n    hence \\<open>u \\<in> M + ((orthogonal_complement M) \\<inter> N)\\<close>\n      by (metis d4 set_plus_intro)\n    thus ?thesis\n      unfolding closed_sum_def\n      using closure_subset by blast\n  qed\n\n  have c3: \"N \\<subseteq> M +\\<^sub>M ((orthogonal_complement M) \\<inter> N)\"\n    if \"closed_csubspace M\" and \"closed_csubspace N\" and \"M \\<subseteq> N\"\n    for M N :: \"'a set\"\n    using c2 that by auto\n\n  show \"sup X (inf (- X) Y) = Y\"\n    if \"X \\<le> Y\"\n    using that apply transfer\n    using c1 c3\n    by (simp add: subset_antisym)\n\n  show \"X - Y = inf X (- Y)\"\n    apply transfer by simp\nqed\n\nsubsection \\<open>Orthogonal spaces\\<close>\n\ndefinition \\<open>orthogonal_spaces S T \\<longleftrightarrow> (\\<forall>x\\<in>space_as_set S. \\<forall>y\\<in>space_as_set T. is_orthogonal x y)\\<close>\n\nlemma orthogonal_spaces_leq_compl: \\<open>orthogonal_spaces S T \\<longleftrightarrow> S \\<le> -T\\<close>\n  unfolding orthogonal_spaces_def apply transfer\n  by (auto simp: orthogonal_complement_def)\n\nlemma orthogonal_bot[simp]: \\<open>orthogonal_spaces S bot\\<close>\n  by (simp add: orthogonal_spaces_def)\n\nlemma orthogonal_spaces_sym: \\<open>orthogonal_spaces S T \\<Longrightarrow> orthogonal_spaces T S\\<close>\n  unfolding orthogonal_spaces_def\n  using is_orthogonal_sym by blast\n\nlemma orthogonal_sup: \\<open>orthogonal_spaces S T1 \\<Longrightarrow> orthogonal_spaces S T2 \\<Longrightarrow> orthogonal_spaces S (sup T1 T2)\\<close>\n  apply (rule orthogonal_spaces_sym)\n  apply (simp add: orthogonal_spaces_leq_compl)\n  using orthogonal_spaces_leq_compl orthogonal_spaces_sym by blast\n\nlemma orthogonal_sum:\n  assumes \\<open>finite F\\<close> and \\<open>\\<And>x. x\\<in>F \\<Longrightarrow> orthogonal_spaces S (T x)\\<close> \n  shows \\<open>orthogonal_spaces S (sum T F)\\<close>\n  using assms\n  apply induction\n  by (auto intro!: orthogonal_sup)\n\nlemma orthogonal_spaces_ccspan: \\<open>(\\<forall>x\\<in>S. \\<forall>y\\<in>T. is_orthogonal x y) \\<longleftrightarrow> orthogonal_spaces (ccspan S) (ccspan T)\\<close>\n  by (meson ccspan_leq_ortho_ccspan ccspan_superset orthogonal_spaces_def orthogonal_spaces_leq_compl subset_iff)\n\nsubsection \\<open>Orthonormal bases\\<close>\n\nlemma ortho_basis_exists: \n  fixes S :: \\<open>'a::chilbert_space set\\<close>\n  assumes \\<open>is_ortho_set S\\<close>\n  shows \\<open>\\<exists>B. B \\<supseteq> S \\<and> is_ortho_set B \\<and> closure (cspan B) = UNIV\\<close>\nproof -\n  define on where \\<open>on B \\<longleftrightarrow> B \\<supseteq> S \\<and> is_ortho_set B\\<close> for B :: \\<open>'a set\\<close>\n  have \\<open>\\<exists>B\\<in>Collect on. \\<forall>B'\\<in>Collect on. B \\<subseteq> B' \\<longrightarrow> B' = B\\<close>\n  proof (rule subset_Zorn_nonempty; simp)\n    show \\<open>\\<exists>S. on S\\<close>\n      apply (rule exI[of _ S])\n      using assms on_def by fastforce\n  next\n    fix C :: \\<open>'a set set\\<close>\n    assume \\<open>C \\<noteq> {}\\<close>\n    assume \\<open>subset.chain (Collect on) C\\<close>\n    then have C_on: \\<open>B \\<in> C \\<Longrightarrow> on B\\<close> and C_order: \\<open>B \\<in> C \\<Longrightarrow> B' \\<in> C \\<Longrightarrow> B \\<subseteq> B' \\<or> B' \\<subseteq> B\\<close> for B B'\n      by (auto simp: subset.chain_def)\n    have \\<open>is_orthogonal x y\\<close> if \\<open>x\\<in>\\<Union>C\\<close> \\<open>y\\<in>\\<Union>C\\<close> \\<open>x \\<noteq> y\\<close> for x y\n      by (smt (verit) UnionE C_order C_on on_def is_ortho_set_def subsetD that(1) that(2) that(3))\n    moreover have \\<open>0 \\<notin> \\<Union> C\\<close>\n      by (meson UnionE C_on is_ortho_set_def on_def)\n    moreover have \\<open>\\<Union>C \\<supseteq> S\\<close>\n      using C_on \\<open>C \\<noteq> {}\\<close> on_def by blast\n    ultimately show \\<open>on (\\<Union> C)\\<close>\n      unfolding on_def is_ortho_set_def by simp\n  qed\n  then obtain B where \\<open>on B\\<close> and B_max: \\<open>B' \\<supseteq> B \\<Longrightarrow> on B' \\<Longrightarrow> B=B'\\<close> for B'\n    by auto\n  have \\<open>\\<psi> = 0\\<close> if \\<psi>ortho: \\<open>\\<forall>b\\<in>B. is_orthogonal \\<psi> b\\<close> for \\<psi> :: 'a\n  proof (rule ccontr)\n    assume \\<open>\\<psi> \\<noteq> 0\\<close>\n    define \\<phi> B' where \\<open>\\<phi> = \\<psi> /\\<^sub>R norm \\<psi>\\<close> and \\<open>B' = B \\<union> {\\<phi>}\\<close>\n    have [simp]: \\<open>norm \\<phi> = 1\\<close>\n      using \\<open>\\<psi> \\<noteq> 0\\<close> by (auto simp: \\<phi>_def)\n    have \\<phi>ortho: \\<open>is_orthogonal \\<phi> b\\<close> if \\<open>b \\<in> B\\<close> for b\n      using \\<psi>ortho that \\<phi>_def  by auto\n    have orthoB': \\<open>is_orthogonal x y\\<close> if \\<open>x\\<in>B'\\<close> \\<open>y\\<in>B'\\<close> \\<open>x \\<noteq> y\\<close> for x y\n      using that \\<open>on B\\<close> \\<phi>ortho \\<phi>ortho[THEN is_orthogonal_sym[THEN iffD1]]\n      by (auto simp: B'_def on_def is_ortho_set_def)\n    have B'0: \\<open>0 \\<notin> B'\\<close>\n      using B'_def \\<open>norm \\<phi> = 1\\<close> \\<open>on B\\<close> is_ortho_set_def on_def by fastforce\n    have \\<open>S \\<subseteq> B'\\<close>\n      using B'_def \\<open>on B\\<close> on_def by auto\n    from orthoB' B'0 \\<open>S \\<subseteq> B'\\<close> have \\<open>on B'\\<close>\n      by (simp add: on_def is_ortho_set_def)\n    with B_max have \\<open>B = B'\\<close>\n      by (metis B'_def Un_upper1)\n    then have \\<open>\\<phi> \\<in> B\\<close>\n      using B'_def by blast\n    then have \\<open>is_orthogonal \\<phi> \\<phi>\\<close>\n      using \\<phi>ortho by blast\n    then show False\n      using B'0 \\<open>B = B'\\<close> \\<open>\\<phi> \\<in> B\\<close> by fastforce\n  qed \n  then have \\<open>orthogonal_complement B = {0}\\<close>\n    by (auto simp: orthogonal_complement_def)\n  then have \\<open>UNIV = orthogonal_complement (orthogonal_complement B)\\<close>\n    by simp\n  also have \\<open>\\<dots> = orthogonal_complement (orthogonal_complement (closure (cspan B)))\\<close>\n    by (metis (mono_tags, opaque_lifting) \\<open>orthogonal_complement B = {0}\\<close> cinner_zero_left complex_vector.span_superset empty_iff insert_iff orthogonal_complementI orthogonal_complement_antimono orthogonal_complement_of_closure subsetI subset_antisym)\n  also have \\<open>\\<dots> = closure (cspan B)\\<close>\n    apply (rule double_orthogonal_complement_id)\n    by simp\n  finally have \\<open>closure (cspan B) = UNIV\\<close>\n    by simp\n  with \\<open>on B\\<close> show ?thesis\n    by (auto simp: on_def)\nqed\n\nlemma orthonormal_basis_exists: \n  fixes S :: \\<open>'a::chilbert_space set\\<close>\n  assumes \\<open>is_ortho_set S\\<close> and \\<open>\\<And>x. x\\<in>S \\<Longrightarrow> norm x = 1\\<close>\n  shows \\<open>\\<exists>B. B \\<supseteq> S \\<and> is_onb B\\<close>\nproof -\n  from \\<open>is_ortho_set S\\<close>\n  obtain B where \\<open>is_ortho_set B\\<close> and \\<open>B \\<supseteq> S\\<close> and \\<open>closure (cspan B) = UNIV\\<close>\n    using ortho_basis_exists by blast\n  define B' where \\<open>B' = (\\<lambda>x. x /\\<^sub>R norm x) ` B\\<close>\n  have \\<open>S = (\\<lambda>x. x /\\<^sub>R norm x) ` S\\<close>\n    by (simp add: assms(2))\n  then have \\<open>B' \\<supseteq> S\\<close>\n    using B'_def \\<open>S \\<subseteq> B\\<close> by blast\n  moreover \n  have \\<open>ccspan B' = top\\<close>\n    apply (transfer fixing: B')\n    apply (simp add: B'_def scaleR_scaleC)\n    apply (subst complex_vector.span_image_scale')\n    using \\<open>is_ortho_set B\\<close> \\<open>closure (cspan B) = UNIV\\<close> is_ortho_set_def \n    by auto\n  moreover have \\<open>is_ortho_set B'\\<close>\n    using \\<open>is_ortho_set B\\<close> by (auto simp: B'_def is_ortho_set_def)\n  moreover have \\<open>\\<forall>b\\<in>B'. norm b = 1\\<close>\n    using \\<open>is_ortho_set B\\<close> apply (auto simp: B'_def is_ortho_set_def)\n    by (metis field_class.field_inverse norm_eq_zero)\n  ultimately show ?thesis\n    by (auto simp: is_onb_def)\nqed\n\n\ndefinition some_chilbert_basis :: \\<open>'a::chilbert_space set\\<close> where\n  \\<open>some_chilbert_basis = (SOME B::'a set. is_onb B)\\<close>\n\nlemma is_onb_some_chilbert_basis[simp]: \\<open>is_onb (some_chilbert_basis :: 'a::chilbert_space set)\\<close>\n  using orthonormal_basis_exists[OF is_ortho_set_empty]\n  by (auto simp add: some_chilbert_basis_def intro: someI2)\n\nlemma is_ortho_set_some_chilbert_basis[simp]: \\<open>is_ortho_set some_chilbert_basis\\<close>\n  using is_onb_def is_onb_some_chilbert_basis by blast\n\nlemma is_normal_some_chilbert_basis: \\<open>\\<And>x. x \\<in> some_chilbert_basis \\<Longrightarrow> norm x = 1\\<close>\n  using is_onb_def is_onb_some_chilbert_basis by blast\n\nlemma ccspan_some_chilbert_basis[simp]: \\<open>ccspan some_chilbert_basis = top\\<close>\n  using is_onb_def is_onb_some_chilbert_basis by blast\n\nlemma span_some_chilbert_basis[simp]: \\<open>closure (cspan some_chilbert_basis) = UNIV\\<close>\n  by (metis ccspan.rep_eq ccspan_some_chilbert_basis top_ccsubspace.rep_eq)\n\nlemma cindependent_some_chilbert_basis[simp]: \\<open>cindependent some_chilbert_basis\\<close>\n  using is_ortho_set_cindependent is_ortho_set_some_chilbert_basis by blast\n\nlemma finite_some_chilbert_basis[simp]: \\<open>finite (some_chilbert_basis :: 'a :: {chilbert_space, cfinite_dim} set)\\<close>\n  apply (rule cindependent_cfinite_dim_finite)\n  by simp\n\nlemma some_chilbert_basis_nonempty: \\<open>(some_chilbert_basis :: 'a::{chilbert_space, not_singleton} set) \\<noteq> {}\\<close>\nproof (rule ccontr, simp)\n  define B :: \\<open>'a set\\<close> where \\<open>B = some_chilbert_basis\\<close>\n  assume [simp]: \\<open>B = {}\\<close>\n  have \\<open>UNIV = closure (cspan B)\\<close>\n    using B_def span_some_chilbert_basis by blast\n  also have \\<open>\\<dots> = {0}\\<close>\n    by simp\n  also have \\<open>\\<dots> \\<noteq> UNIV\\<close>\n    using Extra_General.UNIV_not_singleton by blast\n  finally show False\n    by simp\nqed\n\nsubsection \\<open>Riesz-representation theorem\\<close>\n\nlemma orthogonal_complement_kernel_functional:\n  fixes f :: \\<open>'a::complex_inner \\<Rightarrow> complex\\<close>\n  assumes \\<open>bounded_clinear f\\<close>\n  shows \\<open>\\<exists>x. orthogonal_complement (f -` {0}) = cspan {x}\\<close>\nproof (cases \\<open>orthogonal_complement (f -` {0}) = {0}\\<close>)\n  case True\n  then show ?thesis\n    apply (rule_tac x=0 in exI) by auto\nnext\n  case False\n  then obtain x where xortho: \\<open>x \\<in> orthogonal_complement (f -` {0})\\<close> and xnon0: \\<open>x \\<noteq> 0\\<close>\n    using complex_vector.subspace_def by fastforce\n\n  from xnon0 xortho\n  have r1: \\<open>f x \\<noteq> 0\\<close>\n    by (metis cinner_eq_zero_iff orthogonal_complement_orthoI vimage_singleton_eq)\n\n  have \\<open>\\<exists> k. y = k *\\<^sub>C x\\<close> if \\<open>y \\<in> orthogonal_complement (f -` {0})\\<close> for y\n  proof (cases \\<open>y = 0\\<close>)\n    case True\n    then show ?thesis by auto\n  next\n    case False\n    with that\n    have \\<open>f y \\<noteq> 0\\<close>\n      by (metis cinner_eq_zero_iff orthogonal_complement_orthoI vimage_singleton_eq)\n    then obtain k where k_def: \\<open>f x = k * f y\\<close>\n      by (metis add.inverse_inverse minus_divide_eq_eq)\n    with assms have \\<open>f x = f (k *\\<^sub>C y)\\<close>\n      by (simp add: bounded_clinear.axioms(1) clinear.scaleC)\n    hence \\<open>f x - f (k *\\<^sub>C y) = 0\\<close>\n      by simp\n    with assms have s1: \\<open>f (x - k *\\<^sub>C y) = 0\\<close>\n      by (simp add: bounded_clinear.axioms(1) complex_vector.linear_diff)\n    from that have \\<open>k *\\<^sub>C y \\<in> orthogonal_complement (f -` {0})\\<close>\n      by (simp add: complex_vector.subspace_scale)\n    with xortho have s2: \\<open>x - (k *\\<^sub>C y) \\<in> orthogonal_complement (f -` {0})\\<close>\n      by (simp add: complex_vector.subspace_diff)\n    have s3: \\<open>(x - (k *\\<^sub>C y)) \\<in> f -` {0}\\<close>\n      using s1 by simp\n    moreover have \\<open>(f -` {0}) \\<inter> (orthogonal_complement (f -` {0})) = {0}\\<close>\n      by (meson assms closed_csubspace_def complex_vector.subspace_def kernel_is_closed_csubspace\n          orthogonal_complement_zero_intersection)\n    ultimately have \\<open>x - (k *\\<^sub>C y) = 0\\<close>\n      using s2 by blast\n    thus ?thesis\n      by (metis ceq_vector_fraction_iff eq_iff_diff_eq_0 k_def r1 scaleC_scaleC)\n  qed\n  then have \\<open>orthogonal_complement (f -` {0}) \\<subseteq> cspan {x}\\<close>\n    using complex_vector.span_superset complex_vector.subspace_scale by blast\n\n  moreover from xortho have \\<open>orthogonal_complement (f -` {0}) \\<supseteq> cspan {x}\\<close>\n    by (simp add: complex_vector.span_minimal)\n\n  ultimately show ?thesis\n    by auto\nqed\n\nlemma riesz_frechet_representation_existence:\n  \\<comment> \\<open>Theorem 3.4 in \\<^cite>\\<open>conway2013course\\<close>\\<close>\n  fixes f::\\<open>'a::chilbert_space \\<Rightarrow> complex\\<close>\n  assumes a1: \\<open>bounded_clinear f\\<close>\n  shows \\<open>\\<exists>t. \\<forall>x.  f x = t \\<bullet>\\<^sub>C x\\<close>\nproof(cases \\<open>\\<forall> x. f x = 0\\<close>)\n  case True\n  thus ?thesis\n    by (metis cinner_zero_left)\nnext\n  case False\n  obtain t where spant: \\<open>orthogonal_complement (f -` {0}) = cspan {t}\\<close>\n    using orthogonal_complement_kernel_functional\n    using assms by blast\n  have \\<open>projection (orthogonal_complement (f -` {0})) x = ((t \\<bullet>\\<^sub>C x)/(t \\<bullet>\\<^sub>C t)) *\\<^sub>C t\\<close> for x\n    apply (subst spant) by (rule projection_rank1)\n  hence \\<open>f (projection (orthogonal_complement (f -` {0})) x) = (((t \\<bullet>\\<^sub>C x))/(t \\<bullet>\\<^sub>C t)) * (f t)\\<close> for x\n    using a1 unfolding bounded_clinear_def\n    by (simp add: complex_vector.linear_scale)\n  hence l2: \\<open>f (projection (orthogonal_complement (f -` {0})) x) = ((cnj (f t)/(t \\<bullet>\\<^sub>C t)) *\\<^sub>C t) \\<bullet>\\<^sub>C x\\<close> for x\n    using complex_cnj_divide by force\n  have \\<open>f (projection (f -` {0}) x) = 0\\<close> for x\n    by (metis (no_types, lifting) assms bounded_clinear_def closed_csubspace.closed\n        complex_vector.linear_subspace_vimage complex_vector.subspace_0 complex_vector.subspace_single_0\n        csubspace_is_convex insert_absorb insert_not_empty kernel_is_closed_csubspace projection_in_image vimage_singleton_eq)\n  hence \"\\<And>a b. f (projection (f -` {0}) a + b) = 0 + f b\"\n    using additive.add assms\n    by (simp add: bounded_clinear_def complex_vector.linear_add)\n  hence \"\\<And>a. 0 + f (projection (orthogonal_complement (f -` {0})) a) = f a\"\n    apply (simp add: assms)\n    by (metis add.commute diff_add_cancel)\n  hence \\<open>f x = ((cnj (f t)/(t \\<bullet>\\<^sub>C t)) *\\<^sub>C t) \\<bullet>\\<^sub>C x\\<close> for x\n    by (simp add: l2)\n  thus ?thesis\n    by blast\nqed\n\nlemma riesz_frechet_representation_unique:\n  \\<comment> \\<open>Theorem 3.4 in \\<^cite>\\<open>conway2013course\\<close>\\<close>\n  fixes f::\\<open>'a::complex_inner \\<Rightarrow> complex\\<close>\n  assumes \\<open>\\<And>x. f x = (t \\<bullet>\\<^sub>C x)\\<close>\n  assumes \\<open>\\<And>x. f x = (u \\<bullet>\\<^sub>C x)\\<close>\n  shows \\<open>t = u\\<close>\n  by (metis add_diff_cancel_left' assms(1) assms(2) cinner_diff_left cinner_gt_zero_iff diff_add_cancel diff_zero)\n\nsubsection \\<open>Adjoints\\<close>\n\ndefinition \"is_cadjoint F G \\<longleftrightarrow> (\\<forall>x. \\<forall>y. (F x \\<bullet>\\<^sub>C y) = (x \\<bullet>\\<^sub>C G y))\"\n\nlemma is_adjoint_sym:\n  \\<open>is_cadjoint F G \\<Longrightarrow> is_cadjoint G F\\<close>\n  unfolding is_cadjoint_def apply auto\n  by (metis cinner_commute')\n\ndefinition \\<open>cadjoint G = (SOME F. is_cadjoint F G)\\<close>\n  for G :: \"'b::complex_inner \\<Rightarrow> 'a::complex_inner\"\n\nlemma cadjoint_exists:\n  fixes G :: \"'b::chilbert_space \\<Rightarrow> 'a::complex_inner\"\n  assumes [simp]: \\<open>bounded_clinear G\\<close>\n  shows \\<open>\\<exists>F. is_cadjoint F G\\<close>\nproof -\n  include notation_norm\n  have [simp]: \\<open>clinear G\\<close>\n    using assms unfolding bounded_clinear_def by blast\n  define g :: \\<open>'a \\<Rightarrow> 'b \\<Rightarrow> complex\\<close>\n    where \\<open>g x y = (x \\<bullet>\\<^sub>C G y)\\<close> for x y\n  have \\<open>bounded_clinear (g x)\\<close> for x\n  proof -\n    have \\<open>g x (a + b) = g x a + g x b\\<close> for a b\n      unfolding g_def\n      using additive.add cinner_add_right clinear_def\n      by (simp add: cinner_add_right complex_vector.linear_add)\n    moreover have  \\<open>g x (k *\\<^sub>C a) = k *\\<^sub>C (g x a)\\<close>\n      for a k\n      unfolding g_def\n      by (simp add: complex_vector.linear_scale)\n    ultimately have \\<open>clinear (g x)\\<close>\n      by (simp add: clinearI)\n    moreover\n    have \\<open>\\<exists> M. \\<forall> y. \\<parallel> G y \\<parallel> \\<le> \\<parallel> y \\<parallel> * M\\<close>\n      using \\<open>bounded_clinear G\\<close>\n      unfolding bounded_clinear_def bounded_clinear_axioms_def by blast\n    then have \\<open>\\<exists>M. \\<forall>y. \\<parallel> g x y \\<parallel> \\<le> \\<parallel> y \\<parallel> * M\\<close>\n      using g_def\n      by (simp add: bounded_clinear.bounded bounded_clinear_cinner_right_comp)\n    ultimately show ?thesis unfolding bounded_linear_def\n      using bounded_clinear.intro\n      using bounded_clinear_axioms_def by blast\n  qed\n  hence \\<open>\\<forall>x. \\<exists>t. \\<forall>y.  g x y = (t \\<bullet>\\<^sub>C y)\\<close>\n    using riesz_frechet_representation_existence by blast\n  then obtain F where \\<open>\\<forall>x. \\<forall>y. g x y = (F x \\<bullet>\\<^sub>C y)\\<close>\n    by metis\n  then have \\<open>is_cadjoint F G\\<close>\n    unfolding is_cadjoint_def g_def by simp\n  thus ?thesis\n    by auto\nqed\n\nlemma cadjoint_is_cadjoint[simp]:\n  fixes G :: \"'b::chilbert_space \\<Rightarrow> 'a::complex_inner\"\n  assumes [simp]: \\<open>bounded_clinear G\\<close>\n  shows \\<open>is_cadjoint (cadjoint G) G\\<close>\n  by (metis assms cadjoint_def cadjoint_exists someI_ex)\n\nlemma is_cadjoint_unique:\n  assumes \\<open>is_cadjoint F1 G\\<close>\n  assumes \\<open>is_cadjoint F2 G\\<close>\n  shows \\<open>F1 = F2\\<close>\n  by (metis (full_types) assms(1) assms(2) ext is_cadjoint_def riesz_frechet_representation_unique)\n\nlemma cadjoint_univ_prop:\n  fixes G :: \"'b::chilbert_space \\<Rightarrow> 'a::complex_inner\"\n  assumes a1: \\<open>bounded_clinear G\\<close>\n  shows \\<open>cadjoint G x \\<bullet>\\<^sub>C y = x \\<bullet>\\<^sub>C G y\\<close>\n  using assms cadjoint_is_cadjoint is_cadjoint_def by blast\n\nlemma cadjoint_univ_prop':\n  fixes G :: \"'b::chilbert_space \\<Rightarrow> 'a::complex_inner\"\n  assumes a1: \\<open>bounded_clinear G\\<close>\n  shows \\<open>x \\<bullet>\\<^sub>C cadjoint G y = G x \\<bullet>\\<^sub>C y\\<close>\n  by (metis cadjoint_univ_prop assms cinner_commute')\n\nnotation cadjoint (\"_\\<^sup>\\<dagger>\" [99] 100)\n\nlemma cadjoint_eqI:\n  fixes G:: \\<open>'b::complex_inner \\<Rightarrow> 'a::complex_inner\\<close>\n    and F:: \\<open>'a \\<Rightarrow> 'b\\<close>\n  assumes \\<open>\\<And>x y. (F x \\<bullet>\\<^sub>C y) = (x \\<bullet>\\<^sub>C G y)\\<close>\n  shows \\<open>G\\<^sup>\\<dagger> = F\\<close>\n  by (metis assms cadjoint_def is_cadjoint_def is_cadjoint_unique someI_ex)\n\nlemma cadjoint_bounded_clinear:\n  fixes A :: \"'a::chilbert_space \\<Rightarrow> 'b::complex_inner\"\n  assumes a1: \"bounded_clinear A\"\n  shows \\<open>bounded_clinear (A\\<^sup>\\<dagger>)\\<close>\nproof\n  include notation_norm\n  have b1: \\<open>((A\\<^sup>\\<dagger>) x \\<bullet>\\<^sub>C y) = (x \\<bullet>\\<^sub>C A y)\\<close> for x y\n    using cadjoint_univ_prop a1 by auto\n  have \\<open>is_orthogonal ((A\\<^sup>\\<dagger>) (x1 + x2) - ((A\\<^sup>\\<dagger>) x1 + (A\\<^sup>\\<dagger>) x2)) y\\<close> for x1 x2 y\n    by (simp add: b1 cinner_diff_left cinner_add_left)\n  hence b2: \\<open>(A\\<^sup>\\<dagger>) (x1 + x2) - ((A\\<^sup>\\<dagger>) x1 + (A\\<^sup>\\<dagger>) x2) = 0\\<close> for x1 x2\n    using cinner_eq_zero_iff by blast\n  thus z1: \\<open>(A\\<^sup>\\<dagger>) (x1 + x2) = (A\\<^sup>\\<dagger>) x1 + (A\\<^sup>\\<dagger>) x2\\<close> for x1 x2\n    by (simp add: b2 eq_iff_diff_eq_0)\n\n  have f1: \\<open>is_orthogonal ((A\\<^sup>\\<dagger>) (r *\\<^sub>C x) - (r *\\<^sub>C (A\\<^sup>\\<dagger>) x )) y\\<close> for r x y\n    by (simp add: b1 cinner_diff_left)\n  thus z2: \\<open>(A\\<^sup>\\<dagger>) (r *\\<^sub>C x) = r *\\<^sub>C (A\\<^sup>\\<dagger>) x\\<close> for r x\n    using cinner_eq_zero_iff eq_iff_diff_eq_0 by blast\n  have \\<open>\\<parallel> (A\\<^sup>\\<dagger>) x \\<parallel>^2 = ((A\\<^sup>\\<dagger>) x \\<bullet>\\<^sub>C (A\\<^sup>\\<dagger>) x)\\<close> for x\n    by (metis cnorm_eq_square)\n  moreover have \\<open>\\<parallel> (A\\<^sup>\\<dagger>) x \\<parallel>^2 \\<ge> 0\\<close> for x\n    by simp\n  ultimately have \\<open>\\<parallel> (A\\<^sup>\\<dagger>) x \\<parallel>^2 = \\<bar> ((A\\<^sup>\\<dagger>) x \\<bullet>\\<^sub>C (A\\<^sup>\\<dagger>) x) \\<bar>\\<close> for x\n    by (metis abs_pos cinner_ge_zero)\n  hence \\<open>\\<parallel> (A\\<^sup>\\<dagger>) x \\<parallel>^2 = \\<bar> (x \\<bullet>\\<^sub>C A ((A\\<^sup>\\<dagger>) x)) \\<bar>\\<close> for x\n    by (simp add: b1)\n  moreover have  \\<open>\\<bar>(x \\<bullet>\\<^sub>C A ((A\\<^sup>\\<dagger>) x))\\<bar> \\<le> \\<parallel>x\\<parallel> *  \\<parallel>A ((A\\<^sup>\\<dagger>) x)\\<parallel>\\<close> for x\n    by (simp add: abs_complex_def complex_inner_class.Cauchy_Schwarz_ineq2 less_eq_complex_def)\n  ultimately have b5: \\<open>\\<parallel> (A\\<^sup>\\<dagger>) x \\<parallel>^2  \\<le> \\<parallel>x\\<parallel> * \\<parallel>A ((A\\<^sup>\\<dagger>) x)\\<parallel>\\<close> for x\n    by (metis complex_of_real_mono_iff)\n  have \\<open>\\<exists>M. M \\<ge> 0 \\<and> (\\<forall> x. \\<parallel>A ((A\\<^sup>\\<dagger>) x)\\<parallel> \\<le> M *  \\<parallel>(A\\<^sup>\\<dagger>) x\\<parallel>)\\<close>\n    using a1\n    by (metis (mono_tags, opaque_lifting) bounded_clinear.bounded linear mult_nonneg_nonpos\n        mult_zero_right norm_ge_zero order.trans semiring_normalization_rules(7))\n  then obtain M where q1: \\<open>M \\<ge> 0\\<close> and q2: \\<open>\\<forall> x. \\<parallel>A ((A\\<^sup>\\<dagger>) x)\\<parallel> \\<le> M * \\<parallel>(A\\<^sup>\\<dagger>) x\\<parallel>\\<close>\n    by blast\n  have \\<open>\\<forall> x::'b. \\<parallel>x\\<parallel> \\<ge> 0\\<close>\n    by simp\n  hence b6: \\<open>\\<parallel>x\\<parallel> * \\<parallel>A ((A\\<^sup>\\<dagger>) x)\\<parallel> \\<le>  \\<parallel>x\\<parallel> * M * \\<parallel>(A\\<^sup>\\<dagger>) x\\<parallel>\\<close> for x\n    using q2\n    by (smt ordered_comm_semiring_class.comm_mult_left_mono vector_space_over_itself.scale_scale)\n  have z3: \\<open>\\<parallel> (A\\<^sup>\\<dagger>) x \\<parallel> \\<le> \\<parallel>x\\<parallel> * M\\<close> for x\n  proof(cases \\<open>\\<parallel>(A\\<^sup>\\<dagger>) x\\<parallel> = 0\\<close>)\n    case True\n    thus ?thesis\n      by (simp add: \\<open>0 \\<le> M\\<close>)\n  next\n    case False\n    have \\<open>\\<parallel> (A\\<^sup>\\<dagger>) x \\<parallel>^2 \\<le> \\<parallel>x\\<parallel> *  M *  \\<parallel>(A\\<^sup>\\<dagger>) x\\<parallel>\\<close>\n      by (smt b5 b6)\n    thus ?thesis\n      by (smt False mult_right_cancel mult_right_mono norm_ge_zero semiring_normalization_rules(29))\n  qed\n  thus \\<open>\\<exists>K. \\<forall>x. \\<parallel>(A\\<^sup>\\<dagger>) x\\<parallel> \\<le> \\<parallel>x\\<parallel> * K\\<close>\n    by auto\nqed\n\nproposition double_cadjoint:\n  fixes U :: \\<open>'a::chilbert_space \\<Rightarrow> 'b::complex_inner\\<close>\n  assumes a1: \"bounded_clinear U\"\n  shows \"U\\<^sup>\\<dagger>\\<^sup>\\<dagger> = U\"\n  by (metis assms cadjoint_def cadjoint_is_cadjoint is_adjoint_sym is_cadjoint_unique someI_ex)\n\nlemma cadjoint_id[simp]: \\<open>id\\<^sup>\\<dagger> = id\\<close>\n  by (simp add: cadjoint_eqI id_def)\n\nlemma scaleC_cadjoint:\n  fixes A::\"'a::chilbert_space \\<Rightarrow> 'b::complex_inner\"\n  assumes \"bounded_clinear A\"\n  shows \\<open>(\\<lambda>t. a *\\<^sub>C A t)\\<^sup>\\<dagger> = (\\<lambda>s. cnj a *\\<^sub>C (A\\<^sup>\\<dagger>) s)\\<close>\nproof -\n  have b3: \\<open>((\\<lambda> s. (cnj a) *\\<^sub>C ((A\\<^sup>\\<dagger>) s)) x \\<bullet>\\<^sub>C y) = (x \\<bullet>\\<^sub>C (\\<lambda> t. a *\\<^sub>C (A t)) y)\\<close>\n    for x y\n    by (simp add: assms cadjoint_univ_prop)\n\n  have \"((\\<lambda>t. a *\\<^sub>C A t)\\<^sup>\\<dagger>) b = cnj a *\\<^sub>C (A\\<^sup>\\<dagger>) b\"\n    for b::'b\n  proof-\n    have \"bounded_clinear (\\<lambda>t. a *\\<^sub>C A t)\"\n      by (simp add: assms bounded_clinear_const_scaleC)\n    thus ?thesis\n      by (metis (no_types) cadjoint_eqI b3)\n  qed\n  thus ?thesis\n    by blast\nqed\n\n\nlemma is_projection_on_is_cadjoint:\n  fixes M :: \\<open>'a::complex_inner set\\<close>\n  assumes a1: \\<open>is_projection_on \\<pi> M\\<close> and a2: \\<open>closed_csubspace M\\<close>\n  shows \\<open>is_cadjoint \\<pi> \\<pi>\\<close>\n  by (smt (verit, ccfv_threshold) a1 a2 cinner_diff_left cinner_eq_flip is_cadjoint_def is_projection_on_iff_orthog orthogonal_complement_orthoI right_minus_eq)\n\nlemma is_projection_on_cadjoint:\n  fixes M :: \\<open>'a::complex_inner set\\<close>\n  assumes \\<open>is_projection_on \\<pi> M\\<close> and \\<open>closed_csubspace M\\<close>\n  shows \\<open>\\<pi>\\<^sup>\\<dagger> = \\<pi>\\<close>\n  using assms is_projection_on_is_cadjoint cadjoint_eqI is_cadjoint_def by blast\n\nlemma projection_cadjoint:\n  fixes M :: \\<open>'a::chilbert_space set\\<close>\n  assumes \\<open>closed_csubspace M\\<close>\n  shows \\<open>(projection M)\\<^sup>\\<dagger> = projection M\\<close>\n  using is_projection_on_cadjoint assms\n  by (metis closed_csubspace.closed closed_csubspace.subspace csubspace_is_convex empty_iff orthog_proj_exists projection_is_projection_on)\n\n\nsubsection \\<open>More projections\\<close>\n\ntext \\<open>These lemmas logically belong in the \"projections\" section above but depend on lemmas developed later.\\<close>\n\nlemma is_projection_on_plus:\n  assumes \"\\<And>x y. x \\<in> A \\<Longrightarrow> y \\<in> B \\<Longrightarrow> is_orthogonal x y\"\n  assumes \\<open>closed_csubspace A\\<close>\n  assumes \\<open>closed_csubspace B\\<close>\n  assumes \\<open>is_projection_on \\<pi>A A\\<close>\n  assumes \\<open>is_projection_on \\<pi>B B\\<close>\n  shows \\<open>is_projection_on (\\<lambda>x. \\<pi>A x + \\<pi>B x) (A +\\<^sub>M B)\\<close>\nproof (rule is_projection_on_iff_orthog[THEN iffD2, rule_format])\n  show clAB: \\<open>closed_csubspace (A +\\<^sub>M B)\\<close>\n    by (simp add: assms(2) assms(3) closed_subspace_closed_sum)\n  fix h\n  have 1: \\<open>\\<pi>A h + \\<pi>B h \\<in> A +\\<^sub>M B\\<close>\n    by (meson clAB assms(2) assms(3) assms(4) assms(5) closed_csubspace_def closed_sum_left_subset closed_sum_right_subset complex_vector.subspace_def in_mono is_projection_on_in_image)\n\n  have \\<open>\\<pi>A (\\<pi>B h) = 0\\<close>\n    by (smt (verit, del_insts) assms(1) assms(2) assms(4) assms(5) cinner_eq_zero_iff is_cadjoint_def is_projection_on_in_image is_projection_on_is_cadjoint)\n  then have \\<open>h - (\\<pi>A h + \\<pi>B h) = (h - \\<pi>B h) - \\<pi>A (h - \\<pi>B h)\\<close>\n    by (smt (verit) add.right_neutral add_diff_cancel_left' assms(2) assms(4) closed_csubspace.subspace complex_vector.subspace_diff diff_add_eq_diff_diff_swap diff_diff_add is_projection_on_iff_orthog orthog_proj_unique orthogonal_complement_closed_subspace)\n  also have \\<open>\\<dots> \\<in> orthogonal_complement A\\<close>\n    using assms(2) assms(4) is_projection_on_iff_orthog by blast\n  finally have orthoA: \\<open>h - (\\<pi>A h + \\<pi>B h) \\<in> orthogonal_complement A\\<close>\n    by -\n\n  have \\<open>\\<pi>B (\\<pi>A h) = 0\\<close>\n    by (smt (verit, del_insts) assms(1) assms(3) assms(4) assms(5) cinner_eq_zero_iff is_cadjoint_def is_projection_on_in_image is_projection_on_is_cadjoint)\n  then have \\<open>h - (\\<pi>A h + \\<pi>B h) = (h - \\<pi>A h) - \\<pi>B (h - \\<pi>A h)\\<close>\n    by (smt (verit) add.right_neutral add_diff_cancel assms(3) assms(5) closed_csubspace.subspace complex_vector.subspace_diff diff_add_eq_diff_diff_swap diff_diff_add is_projection_on_iff_orthog orthog_proj_unique orthogonal_complement_closed_subspace)\n  also have \\<open>\\<dots> \\<in> orthogonal_complement B\\<close>\n    using assms(3) assms(5) is_projection_on_iff_orthog by blast\n  finally have orthoB: \\<open>h - (\\<pi>A h + \\<pi>B h) \\<in> orthogonal_complement B\\<close>\n    by -\n\n  from orthoA orthoB\n  have 2: \\<open>h - (\\<pi>A h + \\<pi>B h) \\<in> orthogonal_complement (A +\\<^sub>M B)\\<close>\n    by (metis IntI assms(2) assms(3) closed_csubspace_def complex_vector.subspace_def de_morgan_orthogonal_complement_plus)\n\n  from 1 2 show \\<open>h - (\\<pi>A h + \\<pi>B h) \\<in> orthogonal_complement (A +\\<^sub>M B) \\<and> \\<pi>A h + \\<pi>B h \\<in> A +\\<^sub>M B\\<close>\n    by simp\nqed\n\nlemma projection_plus:\n  fixes A B :: \"'a::chilbert_space set\"\n  assumes \"\\<And>x y. x:A \\<Longrightarrow> y:B \\<Longrightarrow> is_orthogonal x y\"\n  assumes \\<open>closed_csubspace A\\<close>\n  assumes \\<open>closed_csubspace B\\<close>\n  shows \\<open>projection (A +\\<^sub>M B) = (\\<lambda>x. projection A x + projection B x)\\<close>\nproof -\n  have \\<open>is_projection_on (\\<lambda>x. projection A x + projection B x) (A +\\<^sub>M B)\\<close>\n    apply (rule is_projection_on_plus)\n    using assms by auto\n  then show ?thesis\n    by (meson assms(2) assms(3) closed_csubspace.subspace closed_subspace_closed_sum csubspace_is_convex projection_eqI')\nqed\n\nlemma is_projection_on_insert:\n  assumes ortho: \"\\<And>s. s \\<in> S \\<Longrightarrow> is_orthogonal a s\"\n  assumes \\<open>is_projection_on \\<pi> (closure (cspan S))\\<close>\n  assumes \\<open>is_projection_on \\<pi>a (cspan {a})\\<close>\n  shows \"is_projection_on (\\<lambda>x. \\<pi>a x + \\<pi> x) (closure (cspan (insert a S)))\"\nproof -\n  from ortho\n  have \\<open>x \\<in> cspan {a} \\<Longrightarrow> y \\<in> closure (cspan S) \\<Longrightarrow> is_orthogonal x y\\<close> for x y\n    using is_orthogonal_cspan is_orthogonal_closure is_orthogonal_sym\n    by (smt (verit, ccfv_threshold) empty_iff insert_iff)\n  then have \\<open>is_projection_on (\\<lambda>x. \\<pi>a x + \\<pi> x) (cspan {a} +\\<^sub>M closure (cspan S))\\<close>\n    apply (rule is_projection_on_plus)\n    using assms by (auto simp add: closed_csubspace.intro)\n  also have \\<open>\\<dots> = closure (cspan (insert a S))\\<close>\n    using closed_sum_cspan[where X=\\<open>{a}\\<close>] by simp\n  finally show ?thesis\n    by -\nqed\n\nlemma projection_insert:\n  fixes a :: \\<open>'a::chilbert_space\\<close>\n  assumes a1: \"\\<And>s. s \\<in> S \\<Longrightarrow> is_orthogonal a s\"\n  shows \"projection (closure (cspan (insert a S))) u\n        = projection (cspan {a}) u + projection (closure (cspan S)) u\"\n  using is_projection_on_insert[where S=S, OF a1]\n  by (metis (no_types, lifting) closed_closure closed_csubspace.intro closure_is_csubspace complex_vector.subspace_span csubspace_is_convex finite.intros(1) finite.intros(2) finite_cspan_closed_csubspace projection_eqI' projection_is_projection_on')\n\nlemma projection_insert_finite:\n  fixes S :: \\<open>'a::chilbert_space set\\<close>\n  assumes a1: \"\\<And>s. s \\<in> S \\<Longrightarrow> is_orthogonal a s\" and a2: \"finite S\"\n  shows \"projection (cspan (insert a S)) u\n        = projection (cspan {a}) u + projection (cspan S) u\"\n  using projection_insert\n  by (metis a1 a2 closure_finite_cspan finite.insertI)\n\nsubsection \\<open>Canonical basis (\\<open>onb_enum\\<close>)\\<close>\n\nsetup \\<open>Sign.add_const_constraint (\\<^const_name>\\<open>is_ortho_set\\<close>, SOME \\<^typ>\\<open>'a set \\<Rightarrow> bool\\<close>)\\<close>\n\nclass onb_enum = basis_enum + complex_inner +\n  assumes is_orthonormal: \"is_ortho_set (set canonical_basis)\"\n    and is_normal: \"\\<And>x. x \\<in> (set canonical_basis) \\<Longrightarrow> norm x = 1\"\n\nsetup \\<open>Sign.add_const_constraint (\\<^const_name>\\<open>is_ortho_set\\<close>, SOME \\<^typ>\\<open>'a::complex_inner set \\<Rightarrow> bool\\<close>)\\<close>\n\nlemma cinner_canonical_basis:\n  assumes \\<open>i < length (canonical_basis :: 'a::onb_enum list)\\<close>\n  assumes \\<open>j < length (canonical_basis :: 'a::onb_enum list)\\<close>\n  shows \\<open>cinner (canonical_basis!i :: 'a) (canonical_basis!j) = (if i=j then 1 else 0)\\<close>\n  by (metis assms(1) assms(2) distinct_canonical_basis is_normal is_ortho_set_def is_orthonormal nth_eq_iff_index_eq nth_mem of_real_1 power2_norm_eq_cinner power_one)\n\ninstance onb_enum \\<subseteq> chilbert_space\nproof\n  have \\<open>complete (UNIV :: 'a set)\\<close>\n    using finite_cspan_complete[where B=\\<open>set canonical_basis\\<close>]\n    by simp\n  then show \"convergent X\" if \"Cauchy X\" for X :: \"nat \\<Rightarrow> 'a\"\n    by (simp add: complete_def convergent_def that)\nqed\n\nsubsection \\<open>Conjugate space\\<close>\n\ninstantiation conjugate_space :: (complex_inner) complex_inner begin\nlift_definition cinner_conjugate_space :: \"'a conjugate_space \\<Rightarrow> 'a conjugate_space \\<Rightarrow> complex\" is\n  \\<open>\\<lambda>x y. cinner y x\\<close>.\ninstance\n  apply (intro_classes; transfer)\n       apply (simp_all add: )\n    apply (simp add: cinner_add_right)\n  using cinner_ge_zero norm_eq_sqrt_cinner by auto\nend\n\ninstance conjugate_space :: (chilbert_space) chilbert_space..\n\nsubsection \\<open>Misc (ctd.)\\<close>\n\n\nlemma separating_dense_span: \n  assumes \\<open>\\<And>F G :: 'a::chilbert_space \\<Rightarrow> 'b::{complex_normed_vector,not_singleton}. \n           bounded_clinear F \\<Longrightarrow> bounded_clinear G \\<Longrightarrow> (\\<forall>x\\<in>S. F x = G x) \\<Longrightarrow> F = G\\<close>\n  shows \\<open>closure (cspan S) = UNIV\\<close>\nproof -\n  have \\<open>\\<psi> = 0\\<close> if \\<open>\\<psi> \\<in> orthogonal_complement S\\<close> for \\<psi>\n  proof -\n    obtain \\<phi> :: 'b where \\<open>\\<phi> \\<noteq> 0\\<close>\n      by fastforce\n    have \\<open>(\\<lambda>x. cinner \\<psi> x *\\<^sub>C \\<phi>) = (\\<lambda>_. 0)\\<close> \n      apply (rule assms[rule_format])\n      using orthogonal_complement_orthoI that\n      by (auto simp add: bounded_clinear_cinner_right bounded_clinear_scaleC_const)\n    then have \\<open>cinner \\<psi> \\<psi> = 0\\<close>\n      by (meson \\<open>\\<phi> \\<noteq> 0\\<close> scaleC_eq_0_iff)\n    then show \\<open>\\<psi> = 0\\<close>\n      by auto\n  qed\n  then have \\<open>orthogonal_complement (orthogonal_complement S) = UNIV\\<close>\n    by (metis UNIV_eq_I cinner_zero_right orthogonal_complementI)\n  then show \\<open>closure (cspan S) = UNIV\\<close>\n    by (simp add: orthogonal_complement_orthogonal_complement_closure_cspan)\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/Complex_Bounded_Operators/Complex_Inner_Product.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8633916134888614, "lm_q2_score": 0.8198933425148213, "lm_q1q2_score": 0.7078890358826472}}
{"text": "theory Subsumption_Graphs\n  imports\n    Graphs\n    More_List\nbegin\n\nchapter \\<open>Subsumption Graphs\\<close>\n\nsection \\<open>Preliminaries\\<close>\n\nsubsection \\<open>Transitive Closure\\<close>\n\ncontext\n  fixes R :: \"'a \\<Rightarrow> 'a \\<Rightarrow> bool\"\n  assumes R_trans[intro]: \"\\<And> x y z. R x y \\<Longrightarrow> R y z \\<Longrightarrow> R x z\"\nbegin\n\nlemma rtranclp_transitive_compress1: \"R a c\" if \"R a b\" \"R\\<^sup>*\\<^sup>* b c\"\n  using that(2,1) by induction auto\n\nlemma rtranclp_transitive_compress2: \"R a c\" if \"R\\<^sup>*\\<^sup>* a b\" \"R b c\"\n  using that by induction auto\n\nend (* Transitivity *)\n\n(* XXX Move *)\nlemma rtranclp_ev_induct[consumes 1, case_names irrefl trans step]:\n  fixes P :: \"'a \\<Rightarrow> bool\" and R :: \"'a \\<Rightarrow> 'a \\<Rightarrow> bool\"\n  assumes reachable_finite: \"finite {x. R\\<^sup>*\\<^sup>* a x}\"\n  assumes R_irrefl: \"\\<And> x. \\<not> R x x\" and R_trans[intro]: \"\\<And> x y z. R x y \\<Longrightarrow> R y z \\<Longrightarrow> R x z\"\n  assumes step: \"\\<And> x. R\\<^sup>*\\<^sup>* a x \\<Longrightarrow> P x \\<or> (\\<exists> y. R x y)\"\n  shows \"\\<exists> x. P x \\<and> R\\<^sup>*\\<^sup>* a x\"\nproof -\n  let ?S = \"{y. R\\<^sup>*\\<^sup>* a y}\"\n  from reachable_finite have \"finite ?S\"\n    by auto\n  then have \"\\<exists> x \\<in> ?S. P x\"\n    using step\n  proof (induction ?S arbitrary: a rule: finite_psubset_induct)\n    case psubset\n    let ?S = \"{y. R\\<^sup>*\\<^sup>* a y}\"\n    from psubset have \"finite ?S\" by auto\n    show ?case\n    proof (cases \"?S = {}\")\n      case True\n      then show ?thesis by auto\n    next\n      case False\n      then obtain y where \"R\\<^sup>*\\<^sup>* a y\"\n        by auto\n      from psubset(3)[OF this] show ?thesis\n      proof\n        assume \"P y\"\n        with \\<open>R\\<^sup>*\\<^sup>* a y\\<close> show ?thesis by auto\n      next\n        assume \"\\<exists> z. R y z\"\n        then obtain z where \"R y z\" by safe\n        let ?T = \"{y. R\\<^sup>*\\<^sup>* z y}\"\n        from \\<open>R y z\\<close> \\<open>R\\<^sup>*\\<^sup>* a y\\<close> have \"\\<not> R\\<^sup>*\\<^sup>* z a\"\n          by (auto simp: R_irrefl dest!: rtranclp_transitive_compress2[of R, rotated])\n        then have \"a \\<notin> ?T\" by auto\n        moreover have \"?T \\<subseteq> ?S\"\n          using \\<open>R\\<^sup>*\\<^sup>* a y\\<close> \\<open>R y z\\<close> by auto\n        ultimately have \"?T \\<subset> ?S\"\n          by auto\n        have \"P x \\<or> Ex (R x)\" if \"R\\<^sup>*\\<^sup>* z x\" for x\n          using that \\<open>R y z\\<close> \\<open>R\\<^sup>*\\<^sup>* a y\\<close> by (auto intro!: psubset.prems)\n        from psubset.hyps(2)[OF \\<open>?T \\<subset> ?S\\<close> this] psubset.prems \\<open>R y z\\<close> \\<open>R\\<^sup>*\\<^sup>* a y\\<close> obtain w\n          where \"R\\<^sup>*\\<^sup>* z w\" \"P w\" by auto\n        with \\<open>R\\<^sup>*\\<^sup>* a y\\<close> \\<open>R y z\\<close> have \"R\\<^sup>*\\<^sup>* a w\" by auto\n        with \\<open>P w\\<close> show ?thesis by auto\n      qed\n    qed\n  qed\n  then show ?thesis by auto\nqed\n\n(* XXX Move *)\nlemma rtranclp_ev_induct2[consumes 2, case_names irrefl trans step]:\n  fixes P Q :: \"'a \\<Rightarrow> bool\"\n  assumes Q_finite: \"finite {x. Q x}\" and Q_witness: \"Q a\"\n  assumes R_irrefl: \"\\<And> x. \\<not> R x x\" and R_trans[intro]: \"\\<And> x y z. R x y \\<Longrightarrow> R y z \\<Longrightarrow> R x z\"\n  assumes step: \"\\<And> x. Q x \\<Longrightarrow> P x \\<or> (\\<exists> y. R x y \\<and> Q y)\"\n  shows \"\\<exists> x. P x \\<and> Q x \\<and> R\\<^sup>*\\<^sup>* a x\"\nproof -\n  let ?R = \"\\<lambda> x y. R x y \\<and> Q x \\<and> Q y\"\n  have [intro]: \"R\\<^sup>*\\<^sup>* a x\" if \"?R\\<^sup>*\\<^sup>* a x\" for x\n    using that by induction auto\n  have [intro]: \"Q x\" if \"?R\\<^sup>*\\<^sup>* a x\" for x\n    using that \\<open>Q a\\<close> by (auto elim: rtranclp.cases)\n  have \"{x. ?R\\<^sup>*\\<^sup>* a x} \\<subseteq> {x. Q x}\" by auto\n  with \\<open>finite _\\<close> have \"finite {x. ?R\\<^sup>*\\<^sup>* a x}\" by - (rule finite_subset)\n  then have \"\\<exists>x. P x \\<and> ?R\\<^sup>*\\<^sup>* a x\"\n  proof (induction rule: rtranclp_ev_induct)\n    case prems: (step x)\n    with step[of x] show ?case by auto\n  qed (auto simp: R_irrefl)\n  then show ?thesis by auto\nqed\n\n\nsection \\<open>Definitions\\<close>\n\nlocale Subsumption_Graph_Pre_Defs =\n  ord less_eq less for less_eq :: \"'a \\<Rightarrow> 'a \\<Rightarrow> bool\" (infix \"\\<preceq>\" 50) and less (infix \"\\<prec>\" 50) +\n  fixes E ::  \"'a \\<Rightarrow> 'a \\<Rightarrow> bool\" \\<comment> \\<open>The full edge set\\<close>\nbegin\n\nsublocale Graph_Defs E .\n\nend\n\n\nlocale Subsumption_Graph_Pre_Nodes_Defs = Subsumption_Graph_Pre_Defs +\n  fixes V :: \"'a \\<Rightarrow> bool\"\nbegin\n\nsublocale Subgraph_Node_Defs_Notation .\n\nend  (* Subsumption Graph Pre Nodes Defs *)\n\n\n(* XXX Merge with Worklist locales *)\nlocale Subsumption_Graph_Defs = Subsumption_Graph_Pre_Defs +\n  fixes s\\<^sub>0 :: 'a \\<comment> \\<open>Start state\\<close>\n  fixes RE :: \"'a \\<Rightarrow> 'a \\<Rightarrow> bool\" \\<comment> \\<open>Subgraph of the graph given by the full edge set\\<close>\nbegin\n\nsublocale Graph_Start_Defs E s\\<^sub>0 .\n\nsublocale G: Graph_Start_Defs RE s\\<^sub>0 .\n\nsublocale G': Graph_Start_Defs \"\\<lambda> x y. RE x y \\<or> (x \\<prec> y \\<and> G.reachable y)\" s\\<^sub>0 .\n\nabbreviation G'_E    (\"_ \\<rightarrow>\\<^sub>G\\<^sub>' _\" [100, 100] 40) where\n  \"G'_E x y \\<equiv> RE x y \\<or> (x \\<prec> y \\<and> G.reachable y)\"\n\nnotation RE          (\"_ \\<rightarrow>\\<^sub>G _\"   [100, 100] 40)\n\nnotation G.reaches   (\"_ \\<rightarrow>\\<^sub>G* _\"  [100, 100] 40)\n\nnotation G.reaches1  (\"_ \\<rightarrow>\\<^sub>G\\<^sup>+ _\"  [100, 100] 40)\n\nnotation G'.reaches  (\"_ \\<rightarrow>\\<^sub>G*'' _\" [100, 100] 40)\n\nnotation G'.reaches1 (\"_ \\<rightarrow>\\<^sub>G\\<^sup>+'' _\" [100, 100] 40)\n\nend (* Subsumption Graph Defs *)\n\nlocale Subsumption_Graph_Pre = Subsumption_Graph_Defs + preorder less_eq less +\n  assumes mono:\n    \"a \\<preceq> b \\<Longrightarrow> E a a' \\<Longrightarrow> reachable a \\<Longrightarrow> reachable b \\<Longrightarrow> \\<exists> b'. E b b' \\<and> a' \\<preceq> b'\"\nbegin\n\nlemmas preorder_intros = order_trans less_trans less_imp_le\n\nend (* Subsumption Graph Pre *)\n\n\nlocale Subsumption_Graph_Pre_Nodes = Subsumption_Graph_Pre_Nodes_Defs + preorder less_eq less +\n  assumes mono:\n    \"a \\<preceq> b \\<Longrightarrow> a \\<rightarrow> a' \\<Longrightarrow> V a \\<Longrightarrow> V b \\<Longrightarrow> \\<exists> b'. b \\<rightarrow> b' \\<and> a' \\<preceq> b'\"\nbegin\n\nlemmas preorder_intros = order_trans less_trans less_imp_le\n\nend (* Subsumption Graph Pre Nodes *)\n\ntext \\<open>\n  This is sufficient to show that if \\<open>\\<rightarrow>\\<^sub>G\\<close> cannot reach an accepting state,\n  then \\<open>\\<rightarrow>\\<close> cannot either.\n\\<close>\nlocale Reachability_Compatible_Subsumption_Graph_Pre =\n  Subsumption_Graph_Defs + preorder less_eq less +\n  assumes mono:\n    \"a \\<preceq> b \\<Longrightarrow> E a a' \\<Longrightarrow> reachable a \\<or> G.reachable a \\<Longrightarrow> reachable b \\<or> G.reachable b\n    \\<Longrightarrow> \\<exists> b'. E b b' \\<and> a' \\<preceq> b'\"\n  assumes reachability_compatible:\n    \"\\<forall> s. G.reachable s \\<longrightarrow> (\\<forall> s'. E s s' \\<longrightarrow> RE s s') \\<or> (\\<exists> t. s \\<prec> t \\<and> G.reachable t)\"\n  assumes finite_reachable: \"finite {a. G.reachable a}\"\n\nlocale Reachability_Compatible_Subsumption_Graph =\n  Subsumption_Graph_Defs + Subsumption_Graph_Pre +\n  assumes reachability_compatible:\n    \"\\<forall> s. G.reachable s \\<longrightarrow> (\\<forall> s'. E s s' \\<longrightarrow> RE s s') \\<or> (\\<exists> t. s \\<prec> t \\<and> G.reachable t)\"\n  assumes subgraph: \"\\<forall> s s'. RE s s' \\<longrightarrow> E s s'\"\n  assumes finite_reachable: \"finite {a. G.reachable a}\"\n\nlocale Subsumption_Graph_View_Defs = Subsumption_Graph_Defs +\n  fixes SE ::  \"'a \\<Rightarrow> 'a \\<Rightarrow> bool\" \\<comment> \\<open>Subsumption edges\\<close>\n    and covered :: \"'a \\<Rightarrow> bool\"\n\nlocale Reachability_Compatible_Subsumption_Graph_View =\n  Subsumption_Graph_View_Defs + Subsumption_Graph_Pre +\n  assumes reachability_compatible:\n    \"\\<forall> s. G.reachable s \\<longrightarrow>\n      (if covered s then (\\<exists> t. SE s t \\<and> G.reachable t) else (\\<forall> s'. E s s' \\<longrightarrow> RE s s'))\"\n  assumes subsumption: \"\\<forall> s'. SE s s' \\<longrightarrow> s \\<prec> s'\"\n  assumes subgraph: \"\\<forall> s s'. RE s s' \\<longrightarrow> E s s'\"\n  assumes finite_reachable: \"finite {a. G.reachable a}\"\nbegin\n\nsublocale Reachability_Compatible_Subsumption_Graph \"(\\<preceq>)\" \"(\\<prec>)\" E s\\<^sub>0 RE\nproof unfold_locales\n  have \"(\\<forall>s'. E s s' \\<longrightarrow> RE s s') \\<or> (\\<exists>t. s \\<prec> t \\<and> G.reachable t)\" if \"G.reachable s\" for s\n    using that reachability_compatible subsumption by (cases \"covered s\"; fastforce)\n  then show \"\\<forall>s. G.reachable s \\<longrightarrow> (\\<forall>s'. E s s' \\<longrightarrow> RE s s') \\<or> (\\<exists>t. s \\<prec> t \\<and> G.reachable t)\"\n    by auto\nqed (use subgraph in \\<open>auto intro: finite_reachable mono\\<close>)\n\nend (* Reachability Compatible Subsumption Graph View *)\n\nlocale Subsumption_Graph_Closure_View_Defs =\n  ord less_eq less for less_eq :: \"'b \\<Rightarrow> 'b \\<Rightarrow> bool\" (infix \"\\<preceq>\" 50) and less (infix \"\\<prec>\" 50) +\n  fixes E ::  \"'a \\<Rightarrow> 'a \\<Rightarrow> bool\" \\<comment> \\<open>The full edge set\\<close>\n    and s\\<^sub>0 :: 'a                 \\<comment> \\<open>Start state\\<close>\n  fixes RE :: \"'a \\<Rightarrow> 'a \\<Rightarrow> bool\" \\<comment> \\<open>Subgraph of the graph given by the full edge set\\<close>\n  fixes SE ::  \"'a \\<Rightarrow> 'a \\<Rightarrow> bool\" \\<comment> \\<open>Subsumption edges\\<close>\n    and covered :: \"'a \\<Rightarrow> bool\"\n  fixes closure :: \"'a \\<Rightarrow> 'b\"\n  fixes P :: \"'a \\<Rightarrow> bool\"\n  fixes Q :: \"'a \\<Rightarrow> bool\"\nbegin\n\nsublocale Graph_Start_Defs E s\\<^sub>0 .\n\nsublocale G: Graph_Start_Defs RE s\\<^sub>0 .\n\nend (* Subsumption Graph Closure View Defs *)\n\nlocale Reachability_Compatible_Subsumption_Graph_Closure_View =\n  Subsumption_Graph_Closure_View_Defs +\n  preorder less_eq less +\n  assumes mono:\n    \"closure a \\<preceq> closure b \\<Longrightarrow> E a a' \\<Longrightarrow> P a \\<Longrightarrow> P b \\<Longrightarrow> \\<exists> b'. E b b' \\<and> closure a' \\<preceq> closure b'\"\n  assumes closure_eq:\n    \"closure a = closure b \\<Longrightarrow> E a a' \\<Longrightarrow> P a \\<Longrightarrow> P b \\<Longrightarrow> \\<exists> b'. E b b' \\<and> closure a' = closure b'\"\n  assumes reachability_compatible:\n    \"\\<forall> s. Q s \\<longrightarrow> (if covered s then (\\<exists> t. SE s t \\<and> G.reachable t) else (\\<forall> s'. E s s' \\<longrightarrow> RE s s'))\"\n  assumes subsumption: \"\\<forall> s'. SE s s' \\<longrightarrow> closure s \\<prec> closure s'\"\n  assumes subgraph: \"\\<forall> s s'. RE s s' \\<longrightarrow> E s s'\"\n  assumes finite_closure: \"finite (closure ` UNIV)\"\n  assumes P_post: \"a \\<rightarrow> b \\<Longrightarrow> P b\"\n  assumes P_pre: \"a \\<rightarrow> b \\<Longrightarrow> P a\"\n  assumes P_s\\<^sub>0: \"P s\\<^sub>0\"\n  assumes Q_post: \"RE a b \\<Longrightarrow> Q b\"\n  assumes Q_s\\<^sub>0: \"Q s\\<^sub>0\"\nbegin\n\ndefinition close where \"close e a b = (\\<exists> x y. e x y \\<and> a = closure x \\<and> b = closure y)\"\n\nlemma Simulation_close:\n  \"Simulation A (close A) (\\<lambda> a b. b = closure a)\"\n  unfolding close_def by standard auto\n\nsublocale view: Reachability_Compatible_Subsumption_Graph\n  \"(\\<preceq>)\" \"(\\<prec>)\" \"close E\" \"closure s\\<^sub>0\" \"close RE\"\n  supply [simp] = close_def\n  supply [intro] = P_pre P_post Q_post\nproof (standard, goal_cases)\n  case prems: (1 a b a')\n  then obtain x y where [simp]: \"x \\<rightarrow> y\" \"a = closure x\" \"a' = closure y\"\n    by auto\n  then have \"P x\" \"P y\"\n    by blast+\n  from prems(4) P_s\\<^sub>0 obtain x' where [simp]: \"b = closure x'\" \"P x'\"\n    unfolding Graph_Start_Defs.reachable_def by cases auto\n  from mono[OF \\<open>_ \\<preceq> _\\<close>[simplified] \\<open>x \\<rightarrow> y\\<close> \\<open>P x\\<close> \\<open>P x'\\<close>] obtain b' where\n    \"x' \\<rightarrow> b'\" \"closure y \\<preceq> closure b'\"\n    by auto\n  then show ?case\n    by auto\nnext\n  case 2\n  interpret Simulation RE \"close RE\" \"\\<lambda> a b. b = closure a\"\n    by (rule Simulation_close)\n  { fix x assume \"Graph_Start_Defs.reachable (close RE) (closure s\\<^sub>0) x\"\n    then obtain x' where [simp]: \"x = closure x'\" \"Q x'\" \"P x'\"\n      using Q_s\\<^sub>0 P_s\\<^sub>0 subgraph unfolding Graph_Start_Defs.reachable_def by cases auto\n    have \"(\\<forall>s'. close E x s' \\<longrightarrow> close RE x s')\n        \\<or> (\\<exists>t. x \\<prec> t \\<and> Graph_Start_Defs.reachable (close RE) (closure s\\<^sub>0) t)\"\n    proof (cases \"covered x'\")\n      case True\n      with reachability_compatible \\<open>Q x'\\<close> obtain t where \"SE x' t\" \"G.reachable t\"\n        by fastforce\n      then show ?thesis\n        using subsumption\n        by - (rule disjI2, auto dest: simulation_reaches simp: Graph_Start_Defs.reachable_def)\n    next\n      case False\n      with reachability_compatible \\<open>Q x'\\<close> have \"\\<forall>s'. x' \\<rightarrow> s' \\<longrightarrow> RE x' s'\"\n        by auto\n      then show ?thesis\n        unfolding close_def using closure_eq[OF _ _ _ \\<open>P x'\\<close>] by - (rule disjI1, force)\n    qed\n  }\n  then show ?case\n    by (intro allI impI)\nnext\n  case 3\n  then show ?case\n    using subgraph by auto\nnext\n  case 4\n  have \"{a. Graph_Start_Defs.reachable (close RE) (closure s\\<^sub>0) a} \\<subseteq> closure ` UNIV\"\n    by (smt Graph_Start_Defs.reachable_induct close_def full_SetCompr_eq mem_Collect_eq subsetI)\n  also have \"finite \\<dots>\"\n    by (rule finite_closure)\n  finally show ?case .\nqed\n\nend (* Reachability Compatible Subsumption Graph Closure View *)\n\nlocale Reachability_Compatible_Subsumption_Graph_Final = Reachability_Compatible_Subsumption_Graph +\n  fixes F :: \"'a \\<Rightarrow> bool\" \\<comment> \\<open>Final states\\<close>\n  assumes F_mono[intro]: \"F a \\<Longrightarrow> a \\<preceq> b \\<Longrightarrow> F b\"\n\nlocale Liveness_Compatible_Subsumption_Graph = Reachability_Compatible_Subsumption_Graph_Final +\n  assumes no_subsumption_cycle:\n    \"G'.reachable x \\<Longrightarrow> x \\<rightarrow>\\<^sub>G\\<^sup>+' x \\<Longrightarrow> x \\<rightarrow>\\<^sub>G\\<^sup>+ x\"\n\nsection \\<open>Reachability\\<close>\n\ncontext Subsumption_Graph_Defs\nbegin\n\ntext \\<open>Setup for automation\\<close>\ncontext\n  includes graph_automation\nbegin\n\nlemma G'_reachable_G_reachable[intro]:\n  \"G.reachable a\" if \"G'.reachable a\"\n  using that by (induction; blast)\n\nlemma G_reachable_G'_reachable[intro]:\n  \"G'.reachable a\" if \"G.reachable a\"\n  using that by (induction; blast)\n\nlemma G_G'_reachable_iff:\n  \"G.reachable a \\<longleftrightarrow> G'.reachable a\"\n  by blast\n\nend (* Automation *)\n\nend (* Subsumption Graph Defs *)\n\n\ncontext Reachability_Compatible_Subsumption_Graph_Pre\nbegin\n\nlemmas preorder_intros = order_trans less_trans less_imp_le\n\nlemma G'_finite_reachable: \"finite {a. G'.reachable a}\"\n  by (blast intro: finite_subset[OF _ finite_reachable])\n\nlemma G_reachable_has_surrogate:\n  \"\\<exists> t. G.reachable t \\<and> s \\<preceq> t \\<and> (\\<forall> s'. E t s' \\<longrightarrow> RE t s')\" if \"G.reachable s\"\nproof -\n  note [intro] = preorder_intros\n  from finite_reachable \\<open>G.reachable s\\<close> obtain x where\n    \"\\<forall>s'. E x s' \\<longrightarrow> RE x s'\" \"G.reachable x\" \"((\\<prec>)\\<^sup>*\\<^sup>*) s x\"\n    apply atomize_elim\n    apply (induction rule: rtranclp_ev_induct2)\n    using reachability_compatible by auto\n  moreover from \\<open>((\\<prec>)\\<^sup>*\\<^sup>*) s x\\<close> have \"s \\<prec> x \\<or> s = x\"\n    by induction auto\n  ultimately show ?thesis\n    by auto\nqed\n\nlemma reachable_has_surrogate:\n  \"\\<exists> t. G.reachable t \\<and> s \\<preceq> t \\<and> (\\<forall> s'. E t s' \\<longrightarrow> RE t s')\" if \"reachable s\"\n  using that\nproof induction\n  case start\n  have \"G.reachable s\\<^sub>0\"\n    by auto\n  then show ?case\n    by (rule G_reachable_has_surrogate)\nnext\n  case (step a b)\n  then obtain t where *: \"G.reachable t\" \"a \\<preceq> t\" \"(\\<forall>s'. t \\<rightarrow> s' \\<longrightarrow> t \\<rightarrow>\\<^sub>G s')\"\n    by auto\n  from mono[OF \\<open>a \\<preceq> t\\<close> \\<open>a \\<rightarrow> b\\<close>] \\<open>reachable a\\<close> \\<open>G.reachable t\\<close> obtain b' where\n    \"t \\<rightarrow> b'\" \"b \\<preceq> b'\"\n    by auto\n  with G_reachable_has_surrogate[of b'] * show ?case\n    by (auto intro: preorder_intros G.reachable_step)\nqed\n\ncontext\n  fixes F :: \"'a \\<Rightarrow> bool\" \\<comment> \\<open>Final states\\<close>\n  assumes F_mono[intro]: \"F a \\<Longrightarrow> a \\<preceq> b \\<Longrightarrow> F b\"\nbegin\n\ncorollary reachability_correct:\n  \"\\<nexists> s'. reachable s' \\<and> F s'\" if \"\\<nexists> s'. G.reachable s' \\<and> F s'\"\n  using that by (auto dest!: reachable_has_surrogate)\n\nend (* Context for property *)\n\nend (* Reachability Compatible Subsumption Graph Pre *)\n\n\ncontext Reachability_Compatible_Subsumption_Graph\nbegin\n\ntext \\<open>Setup for automation\\<close>\ncontext\n  includes graph_automation\nbegin\n\nlemma subgraph'[intro]:\n  \"E s s'\" if \"RE s s'\"\n  using that subgraph by blast\n\nlemma G_reachability_sound[intro]:\n  \"reachable a\" if \"G.reachable a\"\n  using that by (induction; blast)\n\nlemma G_steps_sound[intro]:\n  \"steps xs\" if \"G.steps xs\"\n  using that by (induction; blast)\n\nlemma G_run_sound[intro]:\n  \"run xs\" if \"G.run xs\"\n  using that by (coinduction arbitrary: xs) (auto 4 3 elim: G.run.cases)\n\nlemma G'_reachability_sound[intro]:\n  \"reachable a\" if \"G'.reachable a\"\n  using that by (induction; blast)\n\nlemma G'_finite_reachable: \"finite {a. G'.reachable a}\"\n  by (blast intro: finite_subset[OF _ finite_reachable])\n\nlemma G_steps_G'_steps[intro]:\n  \"G'.steps as\" if \"G.steps as\"\n  using that by induction auto\n\nlemma reachable_has_surrogate:\n  \"\\<exists> t. G.reachable t \\<and> s \\<preceq> t \\<and> (\\<forall> s'. E t s' \\<longrightarrow> RE t s')\" if \"G.reachable s\"\nproof -\n  note [intro] = preorder_intros\n  from finite_reachable \\<open>G.reachable s\\<close> obtain x where\n    \"\\<forall>s'. E x s' \\<longrightarrow> RE x s'\" \"G.reachable x\" \"((\\<prec>)\\<^sup>*\\<^sup>*) s x\"\n    apply atomize_elim\n    apply (induction rule: rtranclp_ev_induct2)\n    using reachability_compatible by auto\n  moreover from \\<open>((\\<prec>)\\<^sup>*\\<^sup>*) s x\\<close> have \"s \\<prec> x \\<or> s = x\"\n    by induction auto\n  ultimately show ?thesis\n    by auto\nqed\n\nlemma reachable_has_surrogate':\n  \"\\<exists> t. s \\<preceq> t \\<and> s \\<rightarrow>\\<^sub>G*' t \\<and> (\\<forall> s'. E t s' \\<longrightarrow> RE t s')\" if \"G.reachable s\"\nproof -\n  note [intro] = preorder_intros\n  from \\<open>G.reachable s\\<close> have \\<open>G.reachable s\\<close> by auto\n  from finite_reachable this obtain x where\n    real_edges: \"\\<forall>s'. E x s' \\<longrightarrow> RE x s'\" and \"G.reachable x\" \"((\\<prec>)\\<^sup>*\\<^sup>*) s x\"\n    apply atomize_elim\n    apply (induction rule: rtranclp_ev_induct2)\n    using reachability_compatible by auto\n  from \\<open>((\\<prec>)\\<^sup>*\\<^sup>*) s x\\<close> have \"s \\<prec> x \\<or> s = x\"\n    by induction auto\n  then show ?thesis\n  proof\n    assume \"s \\<prec> x\"\n    with real_edges \\<open>G.reachable x\\<close> show ?thesis\n      by (inst_existentials \"x\") auto\n  next\n    assume \"s = x\"\n    with real_edges show ?thesis\n      by (inst_existentials \"s\") auto\n  qed\nqed\n\nlemma subsumption_step:\n  \"\\<exists> a'' b'. a' \\<preceq> a'' \\<and> b \\<preceq> b' \\<and> a'' \\<rightarrow>\\<^sub>G b' \\<and> G.reachable a''\" if\n  \"reachable a\" \"E a b\" \"G.reachable a'\" \"a \\<preceq> a'\"\nproof -\n  note [intro] = preorder_intros\n  from mono[OF \\<open>a \\<preceq> a'\\<close> \\<open>E a b\\<close> \\<open>reachable a\\<close>] \\<open>G.reachable a'\\<close> obtain b' where \"E a' b'\" \"b \\<preceq> b'\"\n    by auto\n  from reachable_has_surrogate[OF \\<open>G.reachable a'\\<close>] obtain a''\n    where \"a' \\<preceq> a''\" \"G.reachable a''\" and *: \"\\<forall> s'. E a'' s' \\<longrightarrow> RE a'' s'\"\n    by auto\n  from mono[OF \\<open>a' \\<preceq> a''\\<close> \\<open>E a' b'\\<close>] \\<open>G.reachable a'\\<close> \\<open>G.reachable a''\\<close> obtain b'' where\n    \"E a'' b''\" \"b' \\<preceq> b''\"\n    by auto\n  with * \\<open>a' \\<preceq> a''\\<close> \\<open>b \\<preceq> b'\\<close> \\<open>G.reachable a''\\<close> show ?thesis\n    by auto\nqed\n\nlemma subsumption_step':\n  \"\\<exists> b'. b \\<preceq> b' \\<and> a' \\<rightarrow>\\<^sub>G\\<^sup>+' b'\" if \"reachable a\" \"a \\<rightarrow> b\" \"G'.reachable a'\" \"a \\<preceq> a'\"\nproof -\n  note [intro] = preorder_intros\n  from mono[OF \\<open>a \\<preceq> a'\\<close> \\<open>E a b\\<close> \\<open>reachable a\\<close>] \\<open>G'.reachable a'\\<close> obtain b' where\n    \"b \\<preceq> b'\" \"a' \\<rightarrow> b'\"\n    by auto\n  from reachable_has_surrogate'[of a'] \\<open>G'.reachable a'\\<close> obtain a'' where *:\n    \"a' \\<preceq> a''\" \"a' \\<rightarrow>\\<^sub>G*' a''\" \"\\<forall>s'. a'' \\<rightarrow> s' \\<longrightarrow> a'' \\<rightarrow>\\<^sub>G s'\"\n    by auto\n  with \\<open>G'.reachable a'\\<close> have \"G'.reachable a''\"\n    by blast\n  with mono[OF \\<open>a' \\<preceq> a''\\<close> \\<open>E a' b'\\<close>] \\<open>G'.reachable a'\\<close> obtain b'' where\n    \"b' \\<preceq> b''\" \"a'' \\<rightarrow> b''\"\n    by auto\n  with * \\<open>b \\<preceq> b'\\<close> \\<open>b' \\<preceq> b''\\<close> \\<open>G'.reachable a''\\<close> show ?thesis\n    by (auto simp: G'.reaches1_reaches_iff2) (* XXX *)\nqed\n\ntheorem reachability_complete':\n  \"\\<exists> s'. s \\<preceq> s' \\<and> G.reachable s'\" if \"a \\<rightarrow>* s\" \"G.reachable a\"\n  using that\nproof (induction)\n  case base\n  then show ?case by auto\nnext\n  case (step s t)\n  then obtain s' where \"s \\<preceq> s'\" \"G.reachable s'\"\n    by auto\n  with step(4) have \"reachable a\" \"G.reachable s'\"\n    by auto\n  with step(1) have \"reachable s\"\n    by auto\n  from subsumption_step[OF \\<open>reachable s\\<close> \\<open>E s t\\<close> \\<open>G.reachable s'\\<close> \\<open>s \\<preceq> s'\\<close>] guess s'' t' by clarify\n  with \\<open>G.reachable s'\\<close> show ?case\n    by auto\nqed\n\ntheorem steps_complete':\n  \"\\<exists> ys. list_all2 (\\<preceq>) xs ys \\<and> G.steps (a # ys)\" if\n  \"steps (a # xs)\" \"G.reachable a\"\n  using that\nproof (induction \"a # xs\" arbitrary: a xs rule: steps_alt_induct)\n  case (Single x)\n  then show ?case by auto\noops\n\ntheorem steps_complete':\n  \"\\<exists> c ys. list_all2 (\\<preceq>) xs ys \\<and> G.steps (c # ys) \\<and> b \\<preceq> c\" if\n  \"steps (a # xs)\" \"reachable a\" \"a \\<preceq> b\" \"G.reachable b\"\noops\n\n(* XXX Does this hold? *)\ntheorem run_complete':\n  \"\\<exists> ys. stream_all2 (\\<preceq>) xs ys \\<and> G.run (a ## ys)\" if \"run (a ## xs)\" \"G.reachable a\"\nproof -\n  define f where \"f = (\\<lambda> x b. SOME y. x \\<preceq> y \\<and> RE b y)\"\n  define gen where \"gen a xs = sscan f xs a\" for a xs\n  have gen_ctr: \"gen x xs = f (shd xs) x ## gen (f (shd xs) x) (stl xs)\" for x xs\n    unfolding gen_def by (subst sscan.ctr) (rule HOL.refl)\n  from that have \"G.run (gen a xs)\"\n  proof (coinduction arbitrary: a xs)\n    case run\n    then show ?case\n      apply (cases xs)\n      apply auto\n      apply (subst gen_ctr)\n      apply simp\n      apply (subst gen_ctr)\n      apply simp\n      apply rule\noops\n\ncorollary reachability_complete:\n  \"\\<exists> s'. s \\<preceq> s' \\<and> G.reachable s'\" if \"reachable s\"\n  using reachability_complete'[of s\\<^sub>0 s] that unfolding reachable_def by auto\n\ncorollary reachability_correct:\n  \"(\\<exists> s'. s \\<preceq> s' \\<and> reachable s') \\<longleftrightarrow> (\\<exists> s'. s \\<preceq> s' \\<and> G.reachable s')\"\n  by (blast dest: reachability_complete intro: preorder_intros)\n\nlemma steps_G'_steps:\n  \"\\<exists> ys ns. list_all2 (\\<preceq>) xs (nths ys ns) \\<and> G'.steps (b # ys)\" if\n  \"steps (a # xs)\" \"reachable a\" \"a \\<preceq> b\" \"G'.reachable b\"\n  using that\nproof (induction \"a # xs\" arbitrary: a b xs)\n  case (Single)\n  then show ?case by force\nnext\n  case (Cons x y xs)\n  from subsumption_step'[OF \\<open>reachable x\\<close> \\<open>E x y\\<close> _ \\<open>x \\<preceq> b\\<close>] \\<open>G'.reachable b\\<close> obtain b' where\n    \"y \\<preceq> b'\" \"b \\<rightarrow>\\<^sub>G\\<^sup>+' b'\"\n    by auto\n  with \\<open>reachable x\\<close> Cons.hyps(1) Cons.prems(3) obtain ys ns where\n    \"list_all2 (\\<preceq>) xs (nths ys ns)\" \"G'.steps (b' # ys)\"\n    by atomize_elim (blast intro: Cons.hyps(3)[OF _ \\<open>y \\<preceq> b'\\<close>] intro: graphI_aggressive)\n  from  \\<open>b \\<rightarrow>\\<^sub>G\\<^sup>+' b'\\<close> this(2) obtain as where\n    \"G'.steps (b # as @ b' # ys)\"\n    by (fastforce intro: G'.graphI_aggressive1)\n  with \\<open>y \\<preceq> b'\\<close> show ?case\n    apply (inst_existentials \"as @ b' # ys\" \"{length as} \\<union> {n + length as + 1 | n. n \\<in> ns}\")\n    subgoal\n      apply (subst nths_split, force)\n      apply (subst nths_nth, (simp; fail))\n      apply simp\n      apply (subst nths_shift, force)\n      subgoal premises prems\n      proof -\n        have\n          \"{x - length as |x. x \\<in> {Suc (n + length as) |n. n \\<in> ns}} = {n + 1 | n. n \\<in> ns}\"\n          by force\n        with \\<open>list_all2 _ _ _\\<close> show ?thesis\n          by (simp add: nths_Cons)\n      qed\n      done\n    by assumption\nqed\n\nlemma cycle_G'_cycle'':\n  assumes \"steps (s\\<^sub>0 # ws @ x # xs @ [x])\"\n  shows \"\\<exists> x' xs' ys'. x \\<preceq> x' \\<and> G'.steps (s\\<^sub>0 # xs' @ x' # ys' @ [x'])\"\nproof -\n  let ?n  = \"card {x. G'.reachable x} + 1\"\n  let ?xs = \"x # concat (replicate ?n (xs @ [x]))\"\n  from assms(1) have \"steps (x # xs @ [x])\"\n    by (auto intro: graphI_aggressive2)\n  with steps_replicate[of \"x # xs @ [x]\" ?n] have \"steps ?xs\"\n    by auto\n  have \"steps (s\\<^sub>0 # ws @ ?xs)\"\n  proof -\n    from assms have \"steps (s\\<^sub>0 # ws @ [x])\" (* XXX *)\n      by (auto intro: graphI_aggressive2)\n    with \\<open>steps ?xs\\<close> show ?thesis\n      by (fastforce intro: graphI_aggressive1)\n  qed\n  from steps_G'_steps[OF this, of s\\<^sub>0] obtain ys ns where ys:\n    \"list_all2 (\\<preceq>) (ws @ x # concat (replicate ?n (xs @ [x]))) (nths ys ns)\"\n    \"G'.steps (s\\<^sub>0 # ys)\"\n    by auto\n  then obtain x' ys' ns' ws' where ys':\n    \"G'.steps (x' # ys')\" \"G'.steps (s\\<^sub>0 # ws' @ [x'])\"\n    \"list_all2 (\\<preceq>) (concat (replicate ?n (xs @ [x]))) (nths ys' ns')\"\n    apply atomize_elim\n    apply auto\n    apply (subst (asm) list_all2_append1)\n    apply safe\n    apply (subst (asm) list_all2_Cons1)\n    apply safe\n    apply (drule nths_eq_appendD)\n    apply safe\n    apply (drule nths_eq_ConsD)\n    apply safe\n    subgoal for ys1 ys2 z ys3 ys4 ys5 ys6 ys7 i\n      apply (inst_existentials z ys7)\n      subgoal premises prems\n        using prems(1) by (auto intro: G'.graphI_aggressive2)\n      subgoal premises prems\n      proof -\n        from prems have \"G'.steps ((s\\<^sub>0 # ys4 @ ys6 @ [z]) @ ys7)\"\n          by auto\n        moreover then have \"G'.steps (s\\<^sub>0 # ys4 @ ys6 @ [z])\"\n          by (auto intro: G'.graphI_aggressive2)\n        ultimately show ?thesis\n          by (inst_existentials \"ys4 @ ys6\") auto\n      qed\n      by force\n    done\n  let ?ys = \"filter ((\\<preceq>) x) ys'\"\n  have \"length ?ys \\<ge> ?n\"\n    using list_all2_replicate_elem_filter[OF ys'(3), of x]\n    using filter_nths_length[of \"((\\<preceq>) x)\" ys' ns']\n    by auto\n  from \\<open>G'.steps (s\\<^sub>0 # ws' @ [x'])\\<close> have \"G'.reachable x'\"\n    by - (rule G'.reachable_reaches, auto)\n  have \"set ?ys \\<subseteq> set ys'\"\n    by auto\n  also have \"\\<dots> \\<subseteq> {x. G'.reachable x}\"\n    using \\<open>G'.steps (x' # _)\\<close> \\<open>G'.reachable x'\\<close>\n    by clarsimp (rule G'.reachable_steps_elem[rotated], assumption, auto)\n  finally have \"\\<not> distinct ?ys\"\n    using distinct_card[of ?ys] \\<open>_ >= ?n\\<close>\n    by - (rule ccontr; drule distinct_length_le[OF G'_finite_reachable]; simp)\n  from not_distinct_decomp[OF this] obtain as y bs cs where \"?ys = as @ [y] @ bs @ [y] @ cs\"\n    by auto\n  then obtain as' bs' cs' where\n    \"ys' = as' @ [y] @ bs' @ [y] @ cs'\"\n    apply atomize_elim\n    apply simp\n    apply (drule filter_eq_appendD filter_eq_ConsD filter_eq_appendD[OF sym], clarify)+\n    apply clarsimp\n    subgoal for as1 as2 bs1 bs2 cs'\n      by (inst_existentials \"as1 @ as2\" \"bs1 @ bs2\") simp\n    done\n  have \"G'.steps (y # bs' @ [y])\"\n  proof -\n    (* XXX Decision procedure? *)\n    from \\<open>G'.steps (x' # _)\\<close> \\<open>ys' = _\\<close> show ?thesis\n      by (force intro: G'.graphI_aggressive2)\n  qed\n  moreover have \"G'.steps (s\\<^sub>0 # ws' @ x' # as' @ [y])\"\n  proof -\n    (* XXX Decision procedure? *)\n    from \\<open>G'.steps (x' # ys')\\<close> \\<open>ys' = _\\<close> have \"G'.steps (x' # as' @ [y])\"\n      by (force intro: G'.graphI_aggressive2)\n    with \\<open>G'.steps (s\\<^sub>0 # ws' @ [x'])\\<close> show ?thesis\n      by (fastforce intro: G'.graphI_aggressive1)\n  qed\n  moreover from \\<open>?ys = _\\<close> have \"x \\<preceq> y\"\n  proof -\n    from \\<open>?ys = _\\<close> have \"y \\<in> set ?ys\" by auto\n    then show ?thesis by auto\n  qed\n  ultimately show ?thesis\n    by (inst_existentials y \"ws' @ x' # as'\" bs'; fastforce intro: G'.graphI_aggressive1)\nqed\n\nlemma cycle_G'_cycle':\n  assumes \"steps (s\\<^sub>0 # ws @ x # xs @ [x])\"\n  shows \"\\<exists> y ys. x \\<preceq> y \\<and> G'.steps (y # ys @ [y]) \\<and> G'.reachable y\"\nproof -\n  from cycle_G'_cycle''[OF assms] obtain x' xs' ys' where\n    \"x \\<preceq> x'\" \"G'.steps (s\\<^sub>0 # xs' @ x' # ys' @ [x'])\"\n    by auto\n  then show ?thesis\n    apply (inst_existentials x' ys')\n    subgoal by assumption\n    subgoal by (auto intro: G'.graphI_aggressive2)\n    by (rule G'.reachable_reaches, auto intro: G'.graphI_aggressive2)\nqed\n\nlemma cycle_G'_cycle:\n  assumes \"reachable x\" \"x \\<rightarrow>\\<^sup>+ x\"\n  shows \"\\<exists> y ys. x \\<preceq> y \\<and> G'.reachable y \\<and> y \\<rightarrow>\\<^sub>G\\<^sup>+' y\"\nproof -\n  from assms(2) obtain xs where *: \"steps (x # xs @ x # xs @ [x])\"\n    by (fastforce intro: graphI_aggressive1)\n  from reachable_steps[of x] assms(1) obtain ws where \"steps ws\" \"hd ws = s\\<^sub>0\" \"last ws = x\"\n    by auto\n  with * obtain us where \"steps (s\\<^sub>0 # (us @ xs) @ x # xs @ [x])\"\n    by (cases ws; force intro: graphI_aggressive1) (* slow *)\n  from cycle_G'_cycle'[OF this] show ?thesis\n    by (auto intro: G'.graphI_aggressive2)\nqed\n\ncorollary G'_reachability_complete:\n  \"\\<exists> s'. s \\<preceq> s' \\<and> G.reachable s'\" if \"G'.reachable s\"\n  using reachability_complete that by auto\n\nend (* Subsumption *)\n\nend (* Reachability Compatible Subsumption Graph *)\n\ncorollary (in Reachability_Compatible_Subsumption_Graph_Final) reachability_correct:\n  \"(\\<exists> s'. reachable s' \\<and> F s') \\<longleftrightarrow> (\\<exists> s'. G.reachable s' \\<and> F s')\"\n  using reachability_complete by blast\n\n\nsection \\<open>Liveness\\<close>\n\ntheorem (in Liveness_Compatible_Subsumption_Graph) cycle_iff:\n  \"(\\<exists> x. x \\<rightarrow>\\<^sup>+ x \\<and> reachable x \\<and> F x) \\<longleftrightarrow> (\\<exists> x. x \\<rightarrow>\\<^sub>G\\<^sup>+ x \\<and> G.reachable x \\<and> F x)\"\n  by (auto 4 4 intro: no_subsumption_cycle steps_reaches1 dest: cycle_G'_cycle G.graphD)\n\nsection \\<open>Appendix\\<close>\n\ncontext Subsumption_Graph_Pre_Nodes\nbegin\n\ntext \\<open>Setup for automation\\<close>\ncontext\n  includes graph_automation\nbegin\n\nlemma steps_mono:\n  assumes \"G'.steps (x # xs)\" \"x \\<preceq> y\" \"V x\" \"V y\"\n  shows \"\\<exists> ys. G'.steps (y # ys) \\<and> list_all2 (\\<preceq>) xs ys\"\n  using assms including subgraph_automation\nproof (induction \"x # xs\" arbitrary: x y xs)\n  case (Single x)\n  then show ?case by auto\nnext\n  case (Cons x y xs x')\n  from mono[OF \\<open>x \\<preceq> x'\\<close>] \\<open>x \\<rightarrow> y\\<close> Cons.prems obtain y' where \"x' \\<rightarrow> y'\" \"y \\<preceq> y'\"\n    by auto\n  with Cons.hyps(3)[OF \\<open>y \\<preceq> y'\\<close>] \\<open>x \\<rightarrow> y\\<close> Cons.prems obtain ys where\n    \"G'.steps (y' # ys)\" \"list_all2 (\\<preceq>) xs ys\"\n    by auto\n  with \\<open>x' \\<rightarrow> y'\\<close> \\<open>y \\<preceq> y'\\<close> show ?case\n    by auto\nqed\n\nlemma steps_append_subsumption:\n  assumes \"G'.steps (x # xs)\" \"G'.steps (y # ys)\" \"y \\<preceq> last (x # xs)\" \"V x\" \"V y\"\n  shows \"\\<exists> ys'. G'.steps (x # xs @ ys') \\<and> list_all2 (\\<preceq>) ys ys'\"\nproof -\n  from assms have \"V (last (x # xs))\"\n    by - (rule G'_steps_V_last, auto)\n  from steps_mono[OF \\<open>G'.steps (y # ys)\\<close> \\<open>y \\<preceq> _\\<close> \\<open>V y\\<close> this] obtain ys' where\n    \"G'.steps (last (x # xs) # ys')\" \"list_all2 (\\<preceq>) ys ys'\"\n    by auto\n  with G'.steps_append[OF \\<open>G'.steps (x # xs)\\<close> this(1)] show ?thesis\n    by auto\nqed\n\nlemma steps_replicate_subsumption:\n  assumes \"x \\<preceq> last (x # xs)\" \"G'.steps (x # xs)\" \"n > 0\" \"V x\"\n  notes [intro] = preorder_intros\n  shows \"\\<exists> ys. G'.steps (x # ys) \\<and> list_all2 (\\<preceq>) (concat (replicate n xs)) ys\"\n  using assms\nproof (induction 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    with Suc.prems show ?thesis\n      by (inst_existentials xs) (auto intro: list_all2_refl)\n  next\n    case prems: (Suc n')\n    with Suc \\<open>n = _\\<close> obtain ys where ys:\n      \"list_all2 (\\<preceq>) (concat (replicate n xs)) ys\" \"G'.steps (x # ys)\"\n      by auto\n    with \\<open>n = _\\<close> have \"list_all2 (\\<preceq>) (concat (replicate n' xs) @ xs) ys\"\n      by (metis append_Nil2 concat.simps(1,2) concat_append replicate_Suc replicate_append_same)\n    with \\<open>x \\<preceq> _\\<close> have \"x \\<preceq> last (x # ys)\"\n      by (cases xs; auto 4 3 dest: list_all2_last split: if_split_asm)\n    from steps_append_subsumption[OF \\<open>G'.steps (x # ys)\\<close> \\<open>G'.steps (x # xs)\\<close> this] \\<open>V x\\<close> obtain\n      ys' where \"G'.steps (x # ys @ ys')\" \"list_all2 (\\<preceq>) xs ys'\"\n      by auto\n    with ys(1) \\<open>n = _\\<close> show ?thesis\n      apply (inst_existentials \"ys @ ys'\")\n      by auto\n        (metis\n          append_Nil2 concat.simps(1,2) concat_append list_all2_appendI replicate_Suc\n          replicate_append_same\n        )\n  qed\nqed\n\ncontext\n  assumes finite_V: \"finite {x. V x}\"\nbegin\n\n(* XXX Unused *)\nlemma wf_less_on_reachable_set:\n  assumes antisym: \"\\<And> x y. x \\<preceq> y \\<Longrightarrow> y \\<preceq> x \\<Longrightarrow> x = y\"\n  shows \"wf {(x, y). y \\<prec> x \\<and> V x \\<and> V y}\" (is \"wf ?S\")\nproof (rule finite_acyclic_wf)\n  have \"?S \\<subseteq> {(x, y). V x \\<and> V y}\"\n    by auto\n  also have \"finite \\<dots>\"\n    using finite_V by auto\n  finally show \"finite ?S\" .\nnext\n  interpret order by unfold_locales (rule antisym)\n  show \"acyclicP (\\<lambda>x y. y \\<prec> x \\<and> V x \\<and> V y)\"\n    by (rule acyclicI_order[where f = id]) auto\nqed\n\ntext \\<open>\n  This shows that looking for cycles and pre-cycles is equivalent in monotone subsumption graphs.\n\\<close>\n(* XXX Duplication -- cycle_G'_cycle'' *)\nlemma pre_cycle_cycle':\n  (* XXX Move to different locale *)\n  assumes A: \"x \\<preceq> x'\" \"G'.steps (x # xs @ [x'])\" \"V x\"\n  shows \"\\<exists> x'' ys. x' \\<preceq> x'' \\<and> G'.steps (x'' # ys @ [x'']) \\<and> V x''\"\nproof -\n  let ?n  = \"card {x. V x} + 1\"\n  let ?xs = \"concat (replicate ?n (xs @ [x']))\"\n  from steps_replicate_subsumption[OF _ \\<open>G'.steps _\\<close>, of ?n] \\<open>V x\\<close> \\<open>x \\<preceq> x'\\<close> obtain ys where\n    \"G'.steps (x # ys)\" \"list_all2 (\\<preceq>) ?xs ys\"\n    by auto\n  let ?ys = \"filter ((\\<preceq>) x') ys\"\n  have \"length ?ys \\<ge> ?n\"\n    using list_all2_replicate_elem_filter[OF \\<open>list_all2 (\\<preceq>) ?xs ys\\<close>, of x']\n    by auto\n  have \"set ?ys \\<subseteq> set ys\"\n    by auto\n  also have \"\\<dots> \\<subseteq> {x. V x}\"\n    using G'_steps_V_all[OF \\<open>G'.steps (x # ys)\\<close>] \\<open>V x\\<close> unfolding list_all_iff by auto\n  finally have \"\\<not> distinct ?ys\"\n    using distinct_card[of ?ys] \\<open>_ >= ?n\\<close>\n    by - (rule ccontr, drule distinct_length_le[OF finite_V], auto)\n  from not_distinct_decomp[OF this] obtain as y bs cs where \"?ys = as @ [y] @ bs @ [y] @ cs\"\n    by auto\n  then obtain as' bs' cs' where\n    \"ys = as' @ [y] @ bs' @ [y] @ cs'\"\n    apply atomize_elim\n    apply simp\n    apply (drule filter_eq_appendD filter_eq_ConsD filter_eq_appendD[OF sym], clarify)+\n    apply clarsimp\n    subgoal for as1 as2 bs1 bs2 cs'\n      by (inst_existentials \"as1 @ as2\" \"bs1 @ bs2\") simp\n    done\n  have \"G'.steps (y # bs' @ [y])\"\n  proof -\n    (* XXX Decision procedure? *)\n    from \\<open>G'.steps (x # ys)\\<close> \\<open>ys = _\\<close> have \"G'.steps (x # as' @ (y # bs' @ [y]) @ cs')\"\n      by auto\n    then show ?thesis\n      by - ((simp; fail) | drule G'.stepsD)+\n  qed\n  moreover have \"V y\"\n  proof -\n    from \\<open>G'.steps (x # ys)\\<close> \\<open>ys = _\\<close> have \"G'.steps ((x # as' @ [y]) @ (bs' @ y # cs'))\" (* XXX *)\n      by simp\n    then have \"G'.steps (x # as' @ [y])\"\n      by (blast dest: G'.stepsD)\n    with \\<open>V x\\<close> show ?thesis\n      by (auto dest: G'_steps_V_last)\n  qed\n  moreover from \\<open>?ys = _\\<close> have \"x' \\<preceq> y\"\n  proof -\n    from \\<open>?ys = _\\<close> have \"y \\<in> set ?ys\" by auto\n    then show ?thesis by auto\n  qed\n  ultimately show ?thesis\n    by auto\nqed\n\nlemma pre_cycle_cycle:\n  \"(\\<exists> x x'. V x \\<and> x \\<rightarrow>\\<^sup>+ x' \\<and> x \\<preceq> x') \\<longleftrightarrow> (\\<exists> x. V x \\<and> x \\<rightarrow>\\<^sup>+ x)\"\n  including reaches_steps_iff by (force dest: pre_cycle_cycle')\n\n(* XXX Generalize subgraph properties *)\nlemma pre_cycle_cycle_reachable:\n  \"(\\<exists> x x'. a\\<^sub>0 \\<rightarrow>* x \\<and> V x \\<and> x \\<rightarrow>\\<^sup>+ x' \\<and> x \\<preceq> x') \\<longleftrightarrow> (\\<exists> x. a\\<^sub>0 \\<rightarrow>* x \\<and> V x \\<and> x \\<rightarrow>\\<^sup>+ x)\"\nproof -\n  interpret interp: Subsumption_Graph_Pre_Nodes _ _ E \"\\<lambda> x. a\\<^sub>0 \\<rightarrow>* x \\<and> V x\"\n    including graph_automation_aggressive\n    by standard (drule mono, auto 4 3 simp: Subgraph_Node_Defs.E'_def E'_def)\n  interpret start: Graph_Start_Defs E' a\\<^sub>0 .\n  have *: \"start.reachable_subgraph.E' = interp.E'\"\n    unfolding interp.E'_def start.reachable_subgraph.E'_def\n    unfolding start.reachable_def E'_def\n    by auto\n  have *: \"start.reachable_subgraph.G'.reaches1 = interp.G'.reaches1\"\n    unfolding tranclp_def * ..\n  have *: \"interp.G'.reaches1 x y \\<longleftrightarrow> x \\<rightarrow>\\<^sup>+ y\" if \"a\\<^sub>0 \\<rightarrow>* x\" for x y\n    using start.reachable_reaches1_equiv[of x y] that unfolding * by (simp add: start.reachable_def)\n  from interp.pre_cycle_cycle finite_V show ?thesis\n    by (auto simp: *)\nqed\n\nend (* Automation *)\n\nend (* Finite Subgraph *)\n\nend (* Subsumption Graph Pre Nodes *)\n\n\n(* XXX Obsolete *)\ncontext Subsumption_Graph_Pre\nbegin\n\ntext \\<open>Setup for automation\\<close>\ncontext\n  includes graph_automation\nbegin\n\ninterpretation Subsumption_Graph_Pre_Nodes _ _ E reachable\n  apply standard\n  apply (drule mono)\n     apply (simp_all add: Subgraph_Node_Defs.E'_def)\n     apply force\n  by auto\n\nlemma steps_mono:\n  assumes \"steps (x # xs)\" \"x \\<preceq> y\" \"reachable x\" \"reachable y\"\n  shows \"\\<exists> ys. steps (y # ys) \\<and> list_all2 (\\<preceq>) xs ys\"\n  using assms steps_mono by (simp add: reachable_steps_equiv)\n\nlemma steps_append_subsumption:\n  assumes \"steps (x # xs)\" \"steps (y # ys)\" \"y \\<preceq> last (x # xs)\" \"reachable x\" \"reachable y\"\n  shows \"\\<exists> ys'. steps (x # xs @ ys') \\<and> list_all2 (\\<preceq>) ys ys'\"\n  using assms steps_append_subsumption by (simp add: reachable_steps_equiv)\n\nlemma steps_replicate_subsumption:\n  assumes \"x \\<preceq> last (x # xs)\" \"steps (x # xs)\" \"n > 0\" \"reachable x\"\n  notes [intro] = preorder_intros\n  shows \"\\<exists> ys. steps (x # ys) \\<and> list_all2 (\\<preceq>) (concat (replicate n xs)) ys\"\n  using assms steps_replicate_subsumption by (simp add: reachable_steps_equiv)\n\ncontext\n  assumes finite_reachable: \"finite {x. reachable x}\"\nbegin\n\n(* XXX Unused *)\nlemma wf_less_on_reachable_set:\n  assumes antisym: \"\\<And> x y. x \\<preceq> y \\<Longrightarrow> y \\<preceq> x \\<Longrightarrow> x = y\"\n  shows \"wf {(x, y). y \\<prec> x \\<and> reachable x \\<and> reachable y}\" (is \"wf ?S\")\nproof (rule finite_acyclic_wf)\n  have \"?S \\<subseteq> {(x, y). reachable x \\<and> reachable y}\"\n    by auto\n  also have \"finite \\<dots>\"\n    using finite_reachable by auto\n  finally show \"finite ?S\" .\nnext\n  interpret order by standard (rule antisym)\n  show \"acyclicP (\\<lambda>x y. y \\<prec> x \\<and> reachable x \\<and> reachable y)\"\n    by (rule acyclicI_order[where f = id]) auto\nqed\n\ntext \\<open>\n  This shows that looking for cycles and pre-cycles is equivalent in monotone subsumption graphs.\n\\<close>\n(* XXX Duplication -- cycle_G'_cycle'' *)\nlemma pre_cycle_cycle':\n  (* XXX Move to different locale *)\n  assumes A: \"x \\<preceq> x'\" \"steps (x # xs @ [x'])\" \"reachable x\"\n  shows \"\\<exists> x'' ys. x' \\<preceq> x'' \\<and> steps (x'' # ys @ [x'']) \\<and> reachable x''\"\n  using assms pre_cycle_cycle'[OF finite_reachable] reachable_steps_equiv by meson\n\nlemma pre_cycle_cycle:\n  \"(\\<exists> x x'. reachable x \\<and> reaches x x' \\<and> x \\<preceq> x') \\<longleftrightarrow> (\\<exists> x. reachable x \\<and> reaches x x)\"\n  including reaches_steps_iff by (force dest: pre_cycle_cycle')\n\nend (* Automation *)\n\nend (* Finite Reachable Subgraph *)\n\nend (* Subsumption Graph Pre *)\n\n\ncontext Subsumption_Graph_Defs\nbegin\n\nsublocale G'': Graph_Start_Defs \"\\<lambda> x y. \\<exists> z. G.reachable z \\<and> x \\<preceq> z \\<and> RE z y\" s\\<^sub>0 .\n\nlemma G''_reachable_G'[intro]:\n  \"G'.reachable x\" if \"G''.reachable x\"\n  using that\n  unfolding G'.reachable_def G''.reachable_def G_G'_reachable_iff Graph_Start_Defs.reachable_def\nproof (induction)\n  case base\n  then show ?case\n    by blast\nnext\n  case (step y z)\n  then obtain z' where\n    \"RE\\<^sup>*\\<^sup>* s\\<^sub>0 z'\" \"y \\<preceq> z'\" \"RE z' z\"\n    by auto\n  from this(1) have \"(\\<lambda>x y. RE x y \\<or> x \\<prec> y \\<and> RE\\<^sup>*\\<^sup>* s\\<^sub>0 y)\\<^sup>*\\<^sup>* s\\<^sub>0 z'\"\n    by (induction; blast intro: rtranclp.intros(2))\n  with \\<open>RE z' z\\<close> show ?case\n    by (blast intro: rtranclp.intros(2))\nqed\n\nend (* Subsumption Graph Defs *)\n\nlocale Reachability_Compatible_Subsumption_Graph_Total = Reachability_Compatible_Subsumption_Graph +\n  assumes total: \"reachable a \\<Longrightarrow> reachable b \\<Longrightarrow> a \\<preceq> b \\<or> b \\<preceq> a\"\nbegin\n\nsublocale G''_pre: Subsumption_Graph_Pre \"(\\<preceq>)\" \"(\\<prec>)\" \"\\<lambda> x y. \\<exists> z. G.reachable z \\<and> x \\<preceq> z \\<and> RE z y\"\nproof (standard, safe, goal_cases)\n  case prems: (1 a b a' z)\n  show ?case\n  proof (cases \"b \\<preceq> z\")\n    case True\n    with prems show ?thesis\n      by auto\n  next\n    case False\n    with total[of b z] prems have \"z \\<preceq> b\"\n      by auto\n    with subsumption_step[of z a' b] prems obtain a'' b' where\n      \"b \\<preceq> a''\" \"a' \\<preceq> b'\" \"RE a'' b'\" \"G.reachable a''\"\n      by auto\n    then show ?thesis\n      by (inst_existentials b' a'') auto\n  qed\nqed\n\nend (* Reachability Compatible Subsumption Graph Total *)\n\nsection \\<open>Old Material\\<close>\n\nlocale Reachability_Compatible_Subsumption_Graph' = Subsumption_Graph_Defs + order \"(\\<preceq>)\" \"(\\<prec>)\" +\n  assumes reachability_compatible:\n    \"\\<forall> s. G.reachable s \\<longrightarrow> (\\<forall> s'. E s s' \\<longrightarrow> RE s s') \\<or> (\\<exists> t. s \\<prec> t \\<and> G.reachable t)\"\n  assumes subgraph: \"\\<forall> s s'. RE s s' \\<longrightarrow> E s s'\"\n  assumes finite_reachable: \"finite {a. G.reachable a}\"\n  assumes mono:\n    \"a \\<preceq> b \\<Longrightarrow> E a a' \\<Longrightarrow> reachable a \\<Longrightarrow> G.reachable b \\<Longrightarrow> \\<exists> b'. E b b' \\<and> a' \\<preceq> b'\"\nbegin\n\ntext \\<open>Setup for automation\\<close>\ncontext\n  includes graph_automation\n  notes [intro] = order.trans\nbegin\n\nlemma subgraph'[intro]:\n  \"E s s'\" if \"RE s s'\"\n  using that subgraph by blast\n\nlemma G_reachability_sound[intro]:\n  \"reachable a\" if \"G.reachable a\"\n  using that unfolding reachable_def G.reachable_def by (induction; blast intro: rtranclp.intros(2))\n\nlemma G_steps_sound[intro]:\n  \"steps xs\" if \"G.steps xs\"\n  using that by induction auto\n\nlemma G_run_sound[intro]:\n  \"run xs\" if \"G.run xs\"\n  using that by (coinduction arbitrary: xs) (auto 4 3 elim: G.run.cases)\n\nlemma reachable_has_surrogate:\n  \"\\<exists> t. G.reachable t \\<and> s \\<preceq> t \\<and> (\\<forall> s'. E t s' \\<longrightarrow> RE t s')\" if \"G.reachable s\"\n  using that\nproof -\n  from finite_reachable \\<open>G.reachable s\\<close> obtain x where\n    \"\\<forall>s'. E x s' \\<longrightarrow> RE x s'\" \"G.reachable x\" \"((\\<prec>)\\<^sup>*\\<^sup>*) s x\"\n    apply atomize_elim\n    apply (induction rule: rtranclp_ev_induct2)\n    using reachability_compatible by auto\n  moreover from \\<open>((\\<prec>)\\<^sup>*\\<^sup>*) s x\\<close> have \"s \\<prec> x \\<or> s = x\"\n    by induction auto\n  ultimately show ?thesis by auto\nqed\n\nlemma subsumption_step:\n  \"\\<exists> a'' b'. a' \\<preceq> a'' \\<and> b \\<preceq> b' \\<and> RE a'' b' \\<and> G.reachable a''\" if\n  \"reachable a\" \"E a b\" \"G.reachable a'\" \"a \\<preceq> a'\"\nproof -\n  from mono[OF \\<open>a \\<preceq> a'\\<close> \\<open>E a b\\<close> \\<open>reachable a\\<close> \\<open>G.reachable a'\\<close>] obtain b' where \"E a' b'\" \"b \\<preceq> b'\"\n    by auto\n  from reachable_has_surrogate[OF \\<open>G.reachable a'\\<close>] obtain a''\n    where \"a' \\<preceq> a''\" \"G.reachable a''\" and *: \"\\<forall> s'. E a'' s' \\<longrightarrow> RE a'' s'\"\n    by auto\n  from mono[OF \\<open>a' \\<preceq> a''\\<close> \\<open>E a' b'\\<close>] \\<open>G.reachable a'\\<close> \\<open>G.reachable a''\\<close> obtain b'' where\n    \"E a'' b''\" \"b' \\<preceq> b''\"\n    by auto\n  with * \\<open>a' \\<preceq> a''\\<close> \\<open>b \\<preceq> b'\\<close> \\<open>G.reachable a''\\<close> show ?thesis by auto\nqed\n\ntheorem reachability_complete':\n  \"\\<exists> s'. s \\<preceq> s' \\<and> G.reachable s'\" if \"E\\<^sup>*\\<^sup>* a s\" \"G.reachable a\"\n  using that\nproof (induction)\n  case base\n  then show ?case by auto\nnext\n  case (step s t)\n  then obtain s' where \"s \\<preceq> s'\" \"G.reachable s'\"\n    by auto\n  with step(4) have \"reachable a\" \"G.reachable s'\"\n    by auto\n  with step(1) have \"reachable s\"\n    by (auto simp: reachable_def)\n  from subsumption_step[OF \\<open>reachable s\\<close> \\<open>E s t\\<close> \\<open>G.reachable s'\\<close> \\<open>s \\<preceq> s'\\<close>] guess s'' t' by clarify\n  with \\<open>G.reachable s'\\<close> show ?case\n    by (auto simp: reachable_def)\nqed\n\ntheorem steps_complete':\n  \"\\<exists> ys. list_all2 (\\<preceq>) xs ys \\<and> G.steps (a # ys)\" if\n  \"steps (a # xs)\" \"G.reachable a\"\n  using that\nproof (induction \"a # xs\" arbitrary: a xs rule: steps_alt_induct)\n  case (Single x)\n  then show ?case by auto\noops\n\ntheorem steps_complete':\n  \"\\<exists> c ys. list_all2 (\\<preceq>) xs ys \\<and> G.steps (c # ys) \\<and> b \\<preceq> c\" if\n  \"steps (a # xs)\" \"reachable a\" \"a \\<preceq> b\" \"G.reachable b\"\n  using that\nproof (induction \"a # xs\" arbitrary: a b xs)\n  case (Single x)\n  then show ?case by auto\nnext\n  case (Cons x y xs)\n  from subsumption_step[OF \\<open>reachable x\\<close> \\<open>E _ _\\<close> \\<open>G.reachable b\\<close> \\<open>x \\<preceq> b\\<close>] guess b' y' by clarify\n  with Cons obtain y'' ys where \"list_all2 (\\<preceq>) xs ys\" \"G.steps (y'' # ys)\" \"y' \\<preceq> y''\"\n    oops\n\n(* XXX Does this hold? *)\ntheorem run_complete':\n  \"\\<exists> ys. stream_all2 (\\<preceq>) xs ys \\<and> G.run (a ## ys)\" if \"run (a ## xs)\" \"G.reachable a\"\nproof -\n  define f where \"f = (\\<lambda> x b. SOME y. x \\<preceq> y \\<and> RE b y)\"\n  define gen where \"gen a xs = sscan f xs a\" for a xs\n  have gen_ctr: \"gen x xs = f (shd xs) x ## gen (f (shd xs) x) (stl xs)\" for x xs\n    unfolding gen_def by (subst sscan.ctr) (rule HOL.refl)\n  from that have \"G.run (gen a xs)\"\n  proof (coinduction arbitrary: a xs)\n    case run\n    then show ?case\n      apply (cases xs)\n      apply auto\n      apply (subst gen_ctr)\n      apply simp\n      apply (subst gen_ctr)\n      apply simp\n      apply rule\noops\n\ncorollary reachability_complete:\n  \"\\<exists> s'. s \\<preceq> s' \\<and> G.reachable s'\" if \"reachable s\"\n  using reachability_complete'[of s\\<^sub>0 s] that unfolding reachable_def by auto\n\ncorollary reachability_correct:\n  \"(\\<exists> s'. s \\<preceq> s' \\<and> reachable s') \\<longleftrightarrow> (\\<exists> s'. s \\<preceq> s' \\<and> G.reachable s')\"\n  using reachability_complete by blast\n\nlemma G'_reachability_sound[intro]:\n  \"reachable a\" if \"G'.reachable a\"\n  using that by induction auto\n\ncorollary G'_reachability_complete:\n  \"\\<exists> s'. s \\<preceq> s' \\<and> G.reachable s'\" if \"G'.reachable s\"\n  using reachability_complete that by auto\n\nend (* Automation *)\n\nend (* Reachability Compatible Subsumption Graph' *)\n\nend (* Theory *)\n", "meta": {"author": "wimmers", "repo": "munta", "sha": "62cb1a4a4dbcfcf62c365e90faba15b0012d5a12", "save_path": "github-repos/isabelle/wimmers-munta", "path": "github-repos/isabelle/wimmers-munta/munta-62cb1a4a4dbcfcf62c365e90faba15b0012d5a12/library/Subsumption_Graphs.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8198933447152497, "lm_q2_score": 0.8633916011860785, "lm_q1q2_score": 0.7078890276955088}}
{"text": "theory homework2\n  imports Main begin\n\n(* isabelle part exercise 1 *)\nfun count :: \"'a \\<Rightarrow> 'a list \\<Rightarrow> nat\" where\n  \"count x Nil = 0\" |\n  \"count x (y#xs) = (\n  if x = y then\n    Suc (count x xs)\n  else\n    count x xs)\"\n\nvalue \"count (1::nat) (1#2#3#[])\"\n\nlemma occurrence: \"count x xs \\<le> length xs\"\n  apply(induction xs)\n  apply(auto)\n  done\n\n(* isabelle part exercise 2 *)\ndatatype 'a tree2 = Leaf 'a | Node \"'a tree2\" 'a \"'a tree2\"\n\nfun mirror2 :: \"'a tree2 \\<Rightarrow> 'a tree2\" where\n  \"mirror2 (Leaf x) = Leaf x\" | (* don't miss the parenthness! *)\n  \"mirror2 (Node lhs x rhs) = Node (mirror2 rhs) x (mirror2 lhs)\"\n\nthm mirror2.induct\n\nfun pre_order :: \"'a tree2 \\<Rightarrow> 'a list\" where\n  \"pre_order (Leaf x) = x # Nil\" |\n  (* be careful of constructor of tree2! *)\n  \"pre_order (Node lhs x rhs) = x # (pre_order(lhs)) @ (pre_order(rhs))\"\n\nfun post_order :: \"'a tree2 \\<Rightarrow> 'a list\" where\n  \"post_order (Leaf x) = x # Nil\" |\n  \"post_order (Node lhs x rhs) = (post_order(lhs)) @ (post_order(rhs)) @ [x]\"\n\nlemma mirror_order: \"pre_order (mirror2 t) = rev (post_order t)\"\n  apply(induction t) \n  apply(auto)\n  done\nend\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/homework2.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916029436189, "lm_q2_score": 0.8198933425148214, "lm_q1q2_score": 0.7078890272366732}}
{"text": "(*  Author:  S\u00e9bastien Gou\u00ebzel   sebastien.gouezel@univ-rennes1.fr\n    Author:  Johannes H\u00f6lzl (TUM) -- ported to Limsup\n    License: BSD\n*)\n\ntheory Essential_Supremum\nimports \"../Analysis/Analysis\"\nbegin\n\nlemma ae_filter_eq_bot_iff: \"ae_filter M = bot \\<longleftrightarrow> emeasure M (space M) = 0\"\n  by (simp add: AE_iff_measurable trivial_limit_def)\n\nsection {*The essential supremum*}\n\ntext {*In this paragraph, we define the essential supremum and give its basic properties. The\nessential supremum of a function is its maximum value if one is allowed to throw away a set\nof measure $0$. It is convenient to define it to be infinity for non-measurable functions, as\nit allows for neater statements in general. This is a prerequisiste to define the space $L^\\infty$.*}\n\ndefinition esssup::\"'a measure \\<Rightarrow> ('a \\<Rightarrow> 'b::{second_countable_topology, dense_linorder, linorder_topology, complete_linorder}) \\<Rightarrow> 'b\"\n  where \"esssup M f = (if f \\<in> borel_measurable M then Limsup (ae_filter M) f else top)\"\n\nlemma esssup_non_measurable: \"f \\<notin> M \\<rightarrow>\\<^sub>M borel \\<Longrightarrow> esssup M f = top\"\n  by (simp add: esssup_def)\n\nlemma esssup_eq_AE:\n  assumes f: \"f \\<in> M \\<rightarrow>\\<^sub>M borel\" shows \"esssup M f = Inf {z. AE x in M. f x \\<le> z}\"\n  unfolding esssup_def if_P[OF f] Limsup_def\nproof (intro antisym INF_greatest Inf_greatest; clarsimp)\n  fix y assume \"AE x in M. f x \\<le> y\"\n  then have \"(\\<lambda>x. f x \\<le> y) \\<in> {P. AE x in M. P x}\"\n    by simp\n  then show \"(INF P:{P. AE x in M. P x}. SUP x:Collect P. f x) \\<le> y\"\n    by (rule INF_lower2) (auto intro: SUP_least)\nnext\n  fix P assume P: \"AE x in M. P x\"\n  show \"Inf {z. AE x in M. f x \\<le> z} \\<le> (SUP x:Collect P. f x)\"\n  proof (rule Inf_lower; clarsimp)\n    show \"AE x in M. f x \\<le> (SUP x:Collect P. f x)\"\n      using P by (auto elim: eventually_mono simp: SUP_upper)\n  qed\nqed\n\nlemma esssup_eq: \"f \\<in> M \\<rightarrow>\\<^sub>M borel \\<Longrightarrow> esssup M f = Inf {z. emeasure M {x \\<in> space M. f x > z} = 0}\"\n  by (auto simp add: esssup_eq_AE not_less[symmetric] AE_iff_measurable[OF _ refl] intro!: arg_cong[where f=Inf])\n\nlemma esssup_zero_measure:\n  \"emeasure M {x \\<in> space M. f x > esssup M f} = 0\"\nproof (cases \"esssup M f = top\")\n  case True\n  then show ?thesis by auto\nnext\n  case False\n  then have f[measurable]: \"f \\<in> M \\<rightarrow>\\<^sub>M borel\" unfolding esssup_def by meson\n  have \"esssup M f < top\" using False by (auto simp: less_top)\n  have *: \"{x \\<in> space M. f x > z} \\<in> null_sets M\" if \"z > esssup M f\" for z\n  proof -\n    have \"\\<exists>w. w < z \\<and> emeasure M {x \\<in> space M. f x > w} = 0\"\n      using `z > esssup M f` f by (auto simp: esssup_eq Inf_less_iff)\n    then obtain w where \"w < z\" \"emeasure M {x \\<in> space M. f x > w} = 0\" by auto\n    then have a: \"{x \\<in> space M. f x > w} \\<in> null_sets M\" by auto\n    have b: \"{x \\<in> space M. f x > z} \\<subseteq> {x \\<in> space M. f x > w}\" using `w < z` by auto\n    show ?thesis using null_sets_subset[OF a _ b] by simp\n  qed\n  obtain u::\"nat \\<Rightarrow> 'b\" where u: \"\\<And>n. u n > esssup M f\" \"u \\<longlonglongrightarrow> esssup M f\"\n    using approx_from_above_dense_linorder[OF `esssup M f < top`] by auto\n  have \"{x \\<in> space M. f x > esssup M f} = (\\<Union>n. {x \\<in> space M. f x > u n})\"\n    using u apply auto\n    apply (metis (mono_tags, lifting) order_tendsto_iff eventually_mono LIMSEQ_unique)\n    using less_imp_le less_le_trans by blast\n  also have \"... \\<in> null_sets M\"\n    using *[OF u(1)] by auto\n  finally show ?thesis by auto\nqed\n\nlemma esssup_AE: \"AE x in M. f x \\<le> esssup M f\"\nproof (cases \"f \\<in> M \\<rightarrow>\\<^sub>M borel\")\n  case True then show ?thesis\n    by (intro AE_I[OF _ esssup_zero_measure[of _ f]]) auto\nqed (simp add: esssup_non_measurable)\n\nlemma esssup_pos_measure:\n  \"f \\<in> borel_measurable M \\<Longrightarrow> z < esssup M f \\<Longrightarrow> emeasure M {x \\<in> space M. f x > z} > 0\"\n  using Inf_less_iff mem_Collect_eq not_gr_zero by (force simp: esssup_eq)\n\nlemma esssup_I [intro]: \"f \\<in> borel_measurable M \\<Longrightarrow> AE x in M. f x \\<le> c \\<Longrightarrow> esssup M f \\<le> c\"\n  unfolding esssup_def by (simp add: Limsup_bounded)\n\nlemma esssup_AE_mono: \"f \\<in> borel_measurable M \\<Longrightarrow> AE x in M. f x \\<le> g x \\<Longrightarrow> esssup M f \\<le> esssup M g\"\n  by (auto simp: esssup_def Limsup_mono)\n\nlemma esssup_mono: \"f \\<in> borel_measurable M \\<Longrightarrow> (\\<And>x. f x \\<le> g x) \\<Longrightarrow> esssup M f \\<le> esssup M g\"\n  by (rule esssup_AE_mono) auto\n\nlemma esssup_AE_cong:\n  \"f \\<in> borel_measurable M \\<Longrightarrow> g \\<in> borel_measurable M \\<Longrightarrow> AE x in M. f x = g x \\<Longrightarrow> esssup M f = esssup M g\"\n  by (auto simp: esssup_def intro!: Limsup_eq)\n\nlemma esssup_const: \"emeasure M (space M) \\<noteq> 0 \\<Longrightarrow> esssup M (\\<lambda>x. c) = c\"\n  by (simp add: esssup_def Limsup_const ae_filter_eq_bot_iff)\n\nlemma esssup_cmult: assumes \"c > (0::real)\" shows \"esssup M (\\<lambda>x. c * f x::ereal) = c * esssup M f\"\nproof -\n  have \"(\\<lambda>x. ereal c * f x) \\<in> M \\<rightarrow>\\<^sub>M borel \\<Longrightarrow> f \\<in> M \\<rightarrow>\\<^sub>M borel\"\n  proof (subst measurable_cong)\n    fix \\<omega> show \"f \\<omega> = ereal (1/c) * (ereal c * f \\<omega>)\"\n      using \\<open>0 < c\\<close> by (cases \"f \\<omega>\") auto\n  qed auto\n  then have \"(\\<lambda>x. ereal c * f x) \\<in> M \\<rightarrow>\\<^sub>M borel \\<longleftrightarrow> f \\<in> M \\<rightarrow>\\<^sub>M borel\"\n    by(safe intro!: borel_measurable_ereal_times borel_measurable_const)\n  with \\<open>0<c\\<close> show ?thesis\n    by (cases \"ae_filter M = bot\")\n       (auto simp: esssup_def bot_ereal_def top_ereal_def Limsup_ereal_mult_left)\nqed\n\nlemma esssup_add:\n  \"esssup M (\\<lambda>x. f x + g x::ereal) \\<le> esssup M f + esssup M g\"\nproof (cases \"f \\<in> borel_measurable M \\<and> g \\<in> borel_measurable M\")\n  case True\n  then have [measurable]: \"(\\<lambda>x. f x + g x) \\<in> borel_measurable M\" by auto\n  have \"f x + g x \\<le> esssup M f + esssup M g\" if \"f x \\<le> esssup M f\" \"g x \\<le> esssup M g\" for x\n    using that ereal_add_mono by auto\n  then have \"AE x in M. f x + g x \\<le> esssup M f + esssup M g\"\n    using esssup_AE[of f M] esssup_AE[of g M] by auto\n  then show ?thesis using esssup_I by auto\nnext\n  case False\n  then have \"esssup M f + esssup M g = \\<infinity>\" unfolding esssup_def top_ereal_def by auto\n  then show ?thesis by auto\nqed\n\nlemma esssup_zero_space:\n  \"emeasure M (space M) = 0 \\<Longrightarrow> f \\<in> borel_measurable M \\<Longrightarrow> esssup M f = (- \\<infinity>::ereal)\"\n  by (simp add: esssup_def ae_filter_eq_bot_iff[symmetric] bot_ereal_def)\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/Probability/Essential_Supremum.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.863391595913457, "lm_q2_score": 0.8198933447152497, "lm_q1q2_score": 0.7078890233725216}}
{"text": "(*  Title:      HOL/Groups.thy\n    Author:     Gertrud Bauer\n    Author:     Steven Obua\n    Author:     Lawrence C Paulson\n    Author:     Markus Wenzel\n    Author:     Jeremy Avigad\n*)\n\nsection \\<open>Groups, also combined with orderings\\<close>\n\ntheory Groups\n  imports Orderings\nbegin\n\nsubsection \\<open>Dynamic facts\\<close>\n\nnamed_theorems ac_simps \"associativity and commutativity simplification rules\"\n  and algebra_simps \"algebra simplification rules for rings\"\n  and algebra_split_simps \"algebra simplification rules for rings, with potential goal splitting\"\n  and field_simps \"algebra simplification rules for fields\"\n  and field_split_simps \"algebra simplification rules for fields, with potential goal splitting\"\n\ntext \\<open>\n  The rewrites accumulated in \\<open>algebra_simps\\<close> deal with the classical\n  algebraic structures of groups, rings and family. They simplify terms by\n  multiplying everything out (in case of a ring) and bringing sums and\n  products into a canonical form (by ordered rewriting). As a result it\n  decides group and ring equalities but also helps with inequalities.\n\n  Of course it also works for fields, but it knows nothing about\n  multiplicative inverses or division. This is catered for by \\<open>field_simps\\<close>.\n\n  Facts in \\<open>field_simps\\<close> multiply with denominators in (in)equations if they\n  can be proved to be non-zero (for equations) or positive/negative (for\n  inequalities). Can be too aggressive and is therefore separate from the more\n  benign \\<open>algebra_simps\\<close>.\n\n  Collections \\<open>algebra_split_simps\\<close> and \\<open>field_split_simps\\<close>\n  correspond to \\<open>algebra_simps\\<close> and \\<open>field_simps\\<close>\n  but contain more aggresive rules that may lead to goal splitting.\n\\<close>\n\n\nsubsection \\<open>Abstract structures\\<close>\n\ntext \\<open>\n  These locales provide basic structures for interpretation into bigger\n  structures; extensions require careful thinking, otherwise undesired effects\n  may occur due to interpretation.\n\\<close>\n\nlocale semigroup =\n  fixes f :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a\"  (infixl \"\\<^bold>*\" 70)\n  assumes assoc [ac_simps]: \"a \\<^bold>* b \\<^bold>* c = a \\<^bold>* (b \\<^bold>* c)\"\n\nlocale abel_semigroup = semigroup +\n  assumes commute [ac_simps]: \"a \\<^bold>* b = b \\<^bold>* a\"\nbegin\n\nlemma left_commute [ac_simps]: \"b \\<^bold>* (a \\<^bold>* c) = a \\<^bold>* (b \\<^bold>* c)\"\nproof -\n  have \"(b \\<^bold>* a) \\<^bold>* c = (a \\<^bold>* b) \\<^bold>* c\"\n    by (simp only: commute)\n  then show ?thesis\n    by (simp only: assoc)\nqed\n\nend\n\nlocale monoid = semigroup +\n  fixes z :: 'a (\"\\<^bold>1\")\n  assumes left_neutral [simp]: \"\\<^bold>1 \\<^bold>* a = a\"\n  assumes right_neutral [simp]: \"a \\<^bold>* \\<^bold>1 = a\"\n\nlocale comm_monoid = abel_semigroup +\n  fixes z :: 'a (\"\\<^bold>1\")\n  assumes comm_neutral: \"a \\<^bold>* \\<^bold>1 = a\"\nbegin\n\nsublocale monoid\n  by standard (simp_all add: commute comm_neutral)\n\nend\n\nlocale group = semigroup +\n  fixes z :: 'a (\"\\<^bold>1\")\n  fixes inverse :: \"'a \\<Rightarrow> 'a\"\n  assumes group_left_neutral: \"\\<^bold>1 \\<^bold>* a = a\"\n  assumes left_inverse [simp]:  \"inverse a \\<^bold>* a = \\<^bold>1\"\nbegin\n\nlemma left_cancel: \"a \\<^bold>* b = a \\<^bold>* c \\<longleftrightarrow> b = c\"\nproof\n  assume \"a \\<^bold>* b = a \\<^bold>* c\"\n  then have \"inverse a \\<^bold>* (a \\<^bold>* b) = inverse a \\<^bold>* (a \\<^bold>* c)\" by simp\n  then have \"(inverse a \\<^bold>* a) \\<^bold>* b = (inverse a \\<^bold>* a) \\<^bold>* c\"\n    by (simp only: assoc)\n  then show \"b = c\" by (simp add: group_left_neutral)\nqed simp\n\nsublocale monoid\nproof\n  fix a\n  have \"inverse a \\<^bold>* a = \\<^bold>1\" by simp\n  then have \"inverse a \\<^bold>* (a \\<^bold>* \\<^bold>1) = inverse a \\<^bold>* a\"\n    by (simp add: group_left_neutral assoc [symmetric])\n  with left_cancel show \"a \\<^bold>* \\<^bold>1 = a\"\n    by (simp only: left_cancel)\nqed (fact group_left_neutral)\n\nlemma inverse_unique:\n  assumes \"a \\<^bold>* b = \\<^bold>1\"\n  shows \"inverse a = b\"\nproof -\n  from assms have \"inverse a \\<^bold>* (a \\<^bold>* b) = inverse a\"\n    by simp\n  then show ?thesis\n    by (simp add: assoc [symmetric])\nqed\n\nlemma inverse_neutral [simp]: \"inverse \\<^bold>1 = \\<^bold>1\"\n  by (rule inverse_unique) simp\n\nlemma inverse_inverse [simp]: \"inverse (inverse a) = a\"\n  by (rule inverse_unique) simp\n\nlemma right_inverse [simp]: \"a \\<^bold>* inverse a = \\<^bold>1\"\nproof -\n  have \"a \\<^bold>* inverse a = inverse (inverse a) \\<^bold>* inverse a\"\n    by simp\n  also have \"\\<dots> = \\<^bold>1\"\n    by (rule left_inverse)\n  then show ?thesis by simp\nqed\n\nlemma inverse_distrib_swap: \"inverse (a \\<^bold>* b) = inverse b \\<^bold>* inverse a\"\nproof (rule inverse_unique)\n  have \"a \\<^bold>* b \\<^bold>* (inverse b \\<^bold>* inverse a) =\n    a \\<^bold>* (b \\<^bold>* inverse b) \\<^bold>* inverse a\"\n    by (simp only: assoc)\n  also have \"\\<dots> = \\<^bold>1\"\n    by simp\n  finally show \"a \\<^bold>* b \\<^bold>* (inverse b \\<^bold>* inverse a) = \\<^bold>1\" .\nqed\n\nlemma right_cancel: \"b \\<^bold>* a = c \\<^bold>* a \\<longleftrightarrow> b = c\"\nproof\n  assume \"b \\<^bold>* a = c \\<^bold>* a\"\n  then have \"b \\<^bold>* a \\<^bold>* inverse a= c \\<^bold>* a \\<^bold>* inverse a\"\n    by simp\n  then show \"b = c\"\n    by (simp add: assoc)\nqed simp\n\nend\n\n\nsubsection \\<open>Generic operations\\<close>\n\nclass zero =\n  fixes zero :: 'a  (\"0\")\n\nclass one =\n  fixes one  :: 'a  (\"1\")\n\nhide_const (open) zero one\n\nlemma Let_0 [simp]: \"Let 0 f = f 0\"\n  unfolding Let_def ..\n\nlemma Let_1 [simp]: \"Let 1 f = f 1\"\n  unfolding Let_def ..\n\nsetup \\<open>\n  Reorient_Proc.add\n    (fn Const(\\<^const_name>\\<open>Groups.zero\\<close>, _) => true\n      | Const(\\<^const_name>\\<open>Groups.one\\<close>, _) => true\n      | _ => false)\n\\<close>\n\nsimproc_setup reorient_zero (\"0 = x\") = Reorient_Proc.proc\nsimproc_setup reorient_one (\"1 = x\") = Reorient_Proc.proc\n\ntyped_print_translation \\<open>\n  let\n    fun tr' c = (c, fn ctxt => fn T => fn ts =>\n      if null ts andalso Printer.type_emphasis ctxt T then\n        Syntax.const \\<^syntax_const>\\<open>_constrain\\<close> $ Syntax.const c $\n          Syntax_Phases.term_of_typ ctxt T\n      else raise Match);\n  in map tr' [\\<^const_syntax>\\<open>Groups.one\\<close>, \\<^const_syntax>\\<open>Groups.zero\\<close>] end\n\\<close> \\<comment> \\<open>show types that are presumably too general\\<close>\n\nclass plus =\n  fixes plus :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a\"  (infixl \"+\" 65)\n\nclass minus =\n  fixes minus :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a\"  (infixl \"-\" 65)\n\nclass uminus =\n  fixes uminus :: \"'a \\<Rightarrow> 'a\"  (\"- _\" [81] 80)\n\nclass times =\n  fixes times :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a\"  (infixl \"*\" 70)\n\n\nsubsection \\<open>Semigroups and Monoids\\<close>\n\nclass semigroup_add = plus +\n  assumes add_assoc [algebra_simps, algebra_split_simps, field_simps, field_split_simps]:\n    \"(a + b) + c = a + (b + c)\"\nbegin\n\nsublocale add: semigroup plus\n  by standard (fact add_assoc)\n\nend\n\nhide_fact add_assoc\n\nclass ab_semigroup_add = semigroup_add +\n  assumes add_commute [algebra_simps, algebra_split_simps, field_simps, field_split_simps]:\n    \"a + b = b + a\"\nbegin\n\nsublocale add: abel_semigroup plus\n  by standard (fact add_commute)\n\ndeclare add.left_commute [algebra_simps, algebra_split_simps, field_simps, field_split_simps]\n\nlemmas add_ac = add.assoc add.commute add.left_commute\n\nend\n\nhide_fact add_commute\n\nlemmas add_ac = add.assoc add.commute add.left_commute\n\nclass semigroup_mult = times +\n  assumes mult_assoc [algebra_simps, algebra_split_simps, field_simps, field_split_simps]:\n    \"(a * b) * c = a * (b * c)\"\nbegin\n\nsublocale mult: semigroup times\n  by standard (fact mult_assoc)\n\nend\n\nhide_fact mult_assoc\n\nclass ab_semigroup_mult = semigroup_mult +\n  assumes mult_commute [algebra_simps, algebra_split_simps, field_simps, field_split_simps]:\n    \"a * b = b * a\"\nbegin\n\nsublocale mult: abel_semigroup times\n  by standard (fact mult_commute)\n\ndeclare mult.left_commute [algebra_simps, algebra_split_simps, field_simps, field_split_simps]\n\nlemmas mult_ac = mult.assoc mult.commute mult.left_commute\n\nend\n\nhide_fact mult_commute\n\nlemmas mult_ac = mult.assoc mult.commute mult.left_commute\n\nclass monoid_add = zero + semigroup_add +\n  assumes add_0_left: \"0 + a = a\"\n    and add_0_right: \"a + 0 = a\"\nbegin\n\nsublocale add: monoid plus 0\n  by standard (fact add_0_left add_0_right)+\n\nend\n\nlemma zero_reorient: \"0 = x \\<longleftrightarrow> x = 0\"\n  by (fact eq_commute)\n\nclass comm_monoid_add = zero + ab_semigroup_add +\n  assumes add_0: \"0 + a = a\"\nbegin\n\nsubclass monoid_add\n  by standard (simp_all add: add_0 add.commute [of _ 0])\n\nsublocale add: comm_monoid plus 0\n  by standard (simp add: ac_simps)\n\nend\n\nclass monoid_mult = one + semigroup_mult +\n  assumes mult_1_left: \"1 * a  = a\"\n    and mult_1_right: \"a * 1 = a\"\nbegin\n\nsublocale mult: monoid times 1\n  by standard (fact mult_1_left mult_1_right)+\n\nend\n\nlemma one_reorient: \"1 = x \\<longleftrightarrow> x = 1\"\n  by (fact eq_commute)\n\nclass comm_monoid_mult = one + ab_semigroup_mult +\n  assumes mult_1: \"1 * a = a\"\nbegin\n\nsubclass monoid_mult\n  by standard (simp_all add: mult_1 mult.commute [of _ 1])\n\nsublocale mult: comm_monoid times 1\n  by standard (simp add: ac_simps)\n\nend\n\nclass cancel_semigroup_add = semigroup_add +\n  assumes add_left_imp_eq: \"a + b = a + c \\<Longrightarrow> b = c\"\n  assumes add_right_imp_eq: \"b + a = c + a \\<Longrightarrow> b = c\"\nbegin\n\nlemma add_left_cancel [simp]: \"a + b = a + c \\<longleftrightarrow> b = c\"\n  by (blast dest: add_left_imp_eq)\n\nlemma add_right_cancel [simp]: \"b + a = c + a \\<longleftrightarrow> b = c\"\n  by (blast dest: add_right_imp_eq)\n\nend\n\nclass cancel_ab_semigroup_add = ab_semigroup_add + minus +\n  assumes add_diff_cancel_left' [simp]: \"(a + b) - a = b\"\n  assumes diff_diff_add [algebra_simps, algebra_split_simps, field_simps, field_split_simps]:\n    \"a - b - c = a - (b + c)\"\nbegin\n\nlemma add_diff_cancel_right' [simp]: \"(a + b) - b = a\"\n  using add_diff_cancel_left' [of b a] by (simp add: ac_simps)\n\nsubclass cancel_semigroup_add\nproof\n  fix a b c :: 'a\n  assume \"a + b = a + c\"\n  then have \"a + b - a = a + c - a\"\n    by simp\n  then show \"b = c\"\n    by simp\nnext\n  fix a b c :: 'a\n  assume \"b + a = c + a\"\n  then have \"b + a - a = c + a - a\"\n    by simp\n  then show \"b = c\"\n    by simp\nqed\n\nlemma add_diff_cancel_left [simp]: \"(c + a) - (c + b) = a - b\"\n  unfolding diff_diff_add [symmetric] by simp\n\nlemma add_diff_cancel_right [simp]: \"(a + c) - (b + c) = a - b\"\n  using add_diff_cancel_left [symmetric] by (simp add: ac_simps)\n\nlemma diff_right_commute: \"a - c - b = a - b - c\"\n  by (simp add: diff_diff_add add.commute)\n\nend\n\nclass cancel_comm_monoid_add = cancel_ab_semigroup_add + comm_monoid_add\nbegin\n\nlemma diff_zero [simp]: \"a - 0 = a\"\n  using add_diff_cancel_right' [of a 0] by simp\n\nlemma diff_cancel [simp]: \"a - a = 0\"\nproof -\n  have \"(a + 0) - (a + 0) = 0\"\n    by (simp only: add_diff_cancel_left diff_zero)\n  then show ?thesis by simp\nqed\n\nlemma add_implies_diff:\n  assumes \"c + b = a\"\n  shows \"c = a - b\"\nproof -\n  from assms have \"(b + c) - (b + 0) = a - b\"\n    by (simp add: add.commute)\n  then show \"c = a - b\" by simp\nqed\n\nlemma add_cancel_right_right [simp]: \"a = a + b \\<longleftrightarrow> b = 0\"\n  (is \"?P \\<longleftrightarrow> ?Q\")\nproof\n  assume ?Q\n  then show ?P by simp\nnext\n  assume ?P\n  then have \"a - a = a + b - a\" by simp\n  then show ?Q by simp\nqed\n\nlemma add_cancel_right_left [simp]: \"a = b + a \\<longleftrightarrow> b = 0\"\n  using add_cancel_right_right [of a b] by (simp add: ac_simps)\n\nlemma add_cancel_left_right [simp]: \"a + b = a \\<longleftrightarrow> b = 0\"\n  by (auto dest: sym)\n\nlemma add_cancel_left_left [simp]: \"b + a = a \\<longleftrightarrow> b = 0\"\n  by (auto dest: sym)\n\nend\n\nclass comm_monoid_diff = cancel_comm_monoid_add +\n  assumes zero_diff [simp]: \"0 - a = 0\"\nbegin\n\nlemma diff_add_zero [simp]: \"a - (a + b) = 0\"\nproof -\n  have \"a - (a + b) = (a + 0) - (a + b)\"\n    by simp\n  also have \"\\<dots> = 0\"\n    by (simp only: add_diff_cancel_left zero_diff)\n  finally show ?thesis .\nqed\n\nend\n\n\nsubsection \\<open>Groups\\<close>\n\nclass group_add = minus + uminus + monoid_add +\n  assumes left_minus: \"- a + a = 0\"\n  assumes add_uminus_conv_diff [simp]: \"a + (- b) = a - b\"\nbegin\n\nlemma diff_conv_add_uminus: \"a - b = a + (- b)\"\n  by simp\n\nsublocale add: group plus 0 uminus\n  by standard (simp_all add: left_minus)\n\nlemma minus_unique: \"a + b = 0 \\<Longrightarrow> - a = b\"\n  by (fact add.inverse_unique)\n\nlemma minus_zero: \"- 0 = 0\"\n  by (fact add.inverse_neutral)\n\nlemma minus_minus: \"- (- a) = a\"\n  by (fact add.inverse_inverse)\n\nlemma right_minus: \"a + - a = 0\"\n  by (fact add.right_inverse)\n\nlemma diff_self [simp]: \"a - a = 0\"\n  using right_minus [of a] by simp\n\nsubclass cancel_semigroup_add\n  by standard (simp_all add: add.left_cancel add.right_cancel)\n\nlemma minus_add_cancel [simp]: \"- a + (a + b) = b\"\n  by (simp add: add.assoc [symmetric])\n\nlemma add_minus_cancel [simp]: \"a + (- a + b) = b\"\n  by (simp add: add.assoc [symmetric])\n\nlemma diff_add_cancel [simp]: \"a - b + b = a\"\n  by (simp only: diff_conv_add_uminus add.assoc) simp\n\nlemma add_diff_cancel [simp]: \"a + b - b = a\"\n  by (simp only: diff_conv_add_uminus add.assoc) simp\n\nlemma minus_add: \"- (a + b) = - b + - a\"\n  by (fact add.inverse_distrib_swap)\n\nlemma right_minus_eq [simp]: \"a - b = 0 \\<longleftrightarrow> a = b\"\nproof\n  assume \"a - b = 0\"\n  have \"a = (a - b) + b\" by (simp add: add.assoc)\n  also have \"\\<dots> = b\" using \\<open>a - b = 0\\<close> by simp\n  finally show \"a = b\" .\nnext\n  assume \"a = b\"\n  then show \"a - b = 0\" by simp\nqed\n\nlemma eq_iff_diff_eq_0: \"a = b \\<longleftrightarrow> a - b = 0\"\n  by (fact right_minus_eq [symmetric])\n\nlemma diff_0 [simp]: \"0 - a = - a\"\n  by (simp only: diff_conv_add_uminus add_0_left)\n\nlemma diff_0_right [simp]: \"a - 0 = a\"\n  by (simp only: diff_conv_add_uminus minus_zero add_0_right)\n\nlemma diff_minus_eq_add [simp]: \"a - - b = a + b\"\n  by (simp only: diff_conv_add_uminus minus_minus)\n\nlemma neg_equal_iff_equal [simp]: \"- a = - b \\<longleftrightarrow> a = b\"\nproof\n  assume \"- a = - b\"\n  then have \"- (- a) = - (- b)\" by simp\n  then show \"a = b\" by simp\nnext\n  assume \"a = b\"\n  then show \"- a = - b\" by simp\nqed\n\nlemma neg_equal_0_iff_equal [simp]: \"- a = 0 \\<longleftrightarrow> a = 0\"\n  by (subst neg_equal_iff_equal [symmetric]) simp\n\nlemma neg_0_equal_iff_equal [simp]: \"0 = - a \\<longleftrightarrow> 0 = a\"\n  by (subst neg_equal_iff_equal [symmetric]) simp\n\ntext \\<open>The next two equations can make the simplifier loop!\\<close>\n\nlemma equation_minus_iff: \"a = - b \\<longleftrightarrow> b = - a\"\nproof -\n  have \"- (- a) = - b \\<longleftrightarrow> - a = b\"\n    by (rule neg_equal_iff_equal)\n  then show ?thesis\n    by (simp add: eq_commute)\nqed\n\nlemma minus_equation_iff: \"- a = b \\<longleftrightarrow> - b = a\"\nproof -\n  have \"- a = - (- b) \\<longleftrightarrow> a = -b\"\n    by (rule neg_equal_iff_equal)\n  then show ?thesis\n    by (simp add: eq_commute)\nqed\n\nlemma eq_neg_iff_add_eq_0: \"a = - b \\<longleftrightarrow> a + b = 0\"\nproof\n  assume \"a = - b\"\n  then show \"a + b = 0\" by simp\nnext\n  assume \"a + b = 0\"\n  moreover have \"a + (b + - b) = (a + b) + - b\"\n    by (simp only: add.assoc)\n  ultimately show \"a = - b\"\n    by simp\nqed\n\nlemma add_eq_0_iff2: \"a + b = 0 \\<longleftrightarrow> a = - b\"\n  by (fact eq_neg_iff_add_eq_0 [symmetric])\n\nlemma neg_eq_iff_add_eq_0: \"- a = b \\<longleftrightarrow> a + b = 0\"\n  by (auto simp add: add_eq_0_iff2)\n\nlemma add_eq_0_iff: \"a + b = 0 \\<longleftrightarrow> b = - a\"\n  by (auto simp add: neg_eq_iff_add_eq_0 [symmetric])\n\nlemma minus_diff_eq [simp]: \"- (a - b) = b - a\"\n  by (simp only: neg_eq_iff_add_eq_0 diff_conv_add_uminus add.assoc minus_add_cancel) simp\n\nlemma add_diff_eq [algebra_simps, algebra_split_simps, field_simps, field_split_simps]:\n    \"a + (b - c) = (a + b) - c\"\n  by (simp only: diff_conv_add_uminus add.assoc)\n\nlemma diff_add_eq_diff_diff_swap: \"a - (b + c) = a - c - b\"\n  by (simp only: diff_conv_add_uminus add.assoc minus_add)\n\nlemma diff_eq_eq [algebra_simps, algebra_split_simps, field_simps, field_split_simps]:\n  \"a - b = c \\<longleftrightarrow> a = c + b\"\n  by auto\n\nlemma eq_diff_eq [algebra_simps, algebra_split_simps, field_simps, field_split_simps]:\n  \"a = c - b \\<longleftrightarrow> a + b = c\"\n  by auto\n\nlemma diff_diff_eq2 [algebra_simps, algebra_split_simps, field_simps, field_split_simps]:\n  \"a - (b - c) = (a + c) - b\"\n  by (simp only: diff_conv_add_uminus add.assoc) simp\n\nlemma diff_eq_diff_eq: \"a - b = c - d \\<Longrightarrow> a = b \\<longleftrightarrow> c = d\"\n  by (simp only: eq_iff_diff_eq_0 [of a b] eq_iff_diff_eq_0 [of c d])\n\nend\n\nclass ab_group_add = minus + uminus + comm_monoid_add +\n  assumes ab_left_minus: \"- a + a = 0\"\n  assumes ab_diff_conv_add_uminus: \"a - b = a + (- b)\"\nbegin\n\nsubclass group_add\n  by standard (simp_all add: ab_left_minus ab_diff_conv_add_uminus)\n\nsubclass cancel_comm_monoid_add\nproof\n  fix a b c :: 'a\n  have \"b + a - a = b\"\n    by simp\n  then show \"a + b - a = b\"\n    by (simp add: ac_simps)\n  show \"a - b - c = a - (b + c)\"\n    by (simp add: algebra_simps)\nqed\n\nlemma uminus_add_conv_diff [simp]: \"- a + b = b - a\"\n  by (simp add: add.commute)\n\nlemma minus_add_distrib [simp]: \"- (a + b) = - a + - b\"\n  by (simp add: algebra_simps)\n\nlemma diff_add_eq [algebra_simps, algebra_split_simps, field_simps, field_split_simps]:\n  \"(a - b) + c = (a + c) - b\"\n  by (simp add: algebra_simps)\n\nlemma minus_diff_commute:\n  \"- b - a = - a - b\"\n  by (simp only: diff_conv_add_uminus add.commute)\n\nend\n\n\nsubsection \\<open>(Partially) Ordered Groups\\<close>\n\ntext \\<open>\n  The theory of partially ordered groups is taken from the books:\n\n    \\<^item> \\<^emph>\\<open>Lattice Theory\\<close> by Garret Birkhoff, American Mathematical Society, 1979\n    \\<^item> \\<^emph>\\<open>Partially Ordered Algebraic Systems\\<close>, Pergamon Press, 1963\n\n  Most of the used notions can also be looked up in\n    \\<^item> \\<^url>\\<open>http://www.mathworld.com\\<close> by Eric Weisstein et. al.\n    \\<^item> \\<^emph>\\<open>Algebra I\\<close> by van der Waerden, Springer\n\\<close>\n\nclass ordered_ab_semigroup_add = order + ab_semigroup_add +\n  assumes add_left_mono: \"a \\<le> b \\<Longrightarrow> c + a \\<le> c + b\"\nbegin\n\nlemma add_right_mono: \"a \\<le> b \\<Longrightarrow> a + c \\<le> b + c\"\n  by (simp add: add.commute [of _ c] add_left_mono)\n\ntext \\<open>non-strict, in both arguments\\<close>\nlemma add_mono: \"a \\<le> b \\<Longrightarrow> c \\<le> d \\<Longrightarrow> a + c \\<le> b + d\"\n  by (simp add: add.commute add_left_mono add_right_mono [THEN order_trans])\n\nend\n\ntext \\<open>Strict monotonicity in both arguments\\<close>\nclass strict_ordered_ab_semigroup_add = ordered_ab_semigroup_add +\n  assumes add_strict_mono: \"a < b \\<Longrightarrow> c < d \\<Longrightarrow> a + c < b + d\"\n\nclass ordered_cancel_ab_semigroup_add =\n  ordered_ab_semigroup_add + cancel_ab_semigroup_add\nbegin\n\nlemma add_strict_left_mono: \"a < b \\<Longrightarrow> c + a < c + b\"\n  by (auto simp add: less_le add_left_mono)\n\nlemma add_strict_right_mono: \"a < b \\<Longrightarrow> a + c < b + c\"\n  by (simp add: add.commute [of _ c] add_strict_left_mono)\n\nsubclass strict_ordered_ab_semigroup_add\nproof\n  show \"\\<And>a b c d. \\<lbrakk>a < b; c < d\\<rbrakk> \\<Longrightarrow> a + c < b + d\"\n    by (iprover intro: add_strict_left_mono add_strict_right_mono less_trans)\nqed\n\nlemma add_less_le_mono: \"a < b \\<Longrightarrow> c \\<le> d \\<Longrightarrow> a + c < b + d\"\n  by (iprover intro: add_left_mono add_strict_right_mono less_le_trans)\n\nlemma add_le_less_mono: \"a \\<le> b \\<Longrightarrow> c < d \\<Longrightarrow> a + c < b + d\"\n  by (iprover intro: add_strict_left_mono add_right_mono less_le_trans)\n\nend\n\nclass ordered_ab_semigroup_add_imp_le = ordered_cancel_ab_semigroup_add +\n  assumes add_le_imp_le_left: \"c + a \\<le> c + b \\<Longrightarrow> a \\<le> b\"\nbegin\n\nlemma add_less_imp_less_left:\n  assumes less: \"c + a < c + b\"\n  shows \"a < b\"\nproof -\n  from less have le: \"c + a \\<le> c + b\"\n    by (simp add: order_le_less)\n  have \"a \\<le> b\"\n    using add_le_imp_le_left [OF le] .\n  moreover have \"a \\<noteq> b\"\n  proof (rule ccontr)\n    assume \"\\<not> ?thesis\"\n    then have \"a = b\" by simp\n    then have \"c + a = c + b\" by simp\n    with less show \"False\" by simp\n  qed\n  ultimately show \"a < b\"\n    by (simp add: order_le_less)\nqed\n\nlemma add_less_imp_less_right: \"a + c < b + c \\<Longrightarrow> a < b\"\n  by (rule add_less_imp_less_left [of c]) (simp add: add.commute)\n\nlemma add_less_cancel_left [simp]: \"c + a < c + b \\<longleftrightarrow> a < b\"\n  by (blast intro: add_less_imp_less_left add_strict_left_mono)\n\nlemma add_less_cancel_right [simp]: \"a + c < b + c \\<longleftrightarrow> a < b\"\n  by (blast intro: add_less_imp_less_right add_strict_right_mono)\n\nlemma add_le_cancel_left [simp]: \"c + a \\<le> c + b \\<longleftrightarrow> a \\<le> b\"\n  by (auto simp: dest: add_le_imp_le_left add_left_mono)\n\nlemma add_le_cancel_right [simp]: \"a + c \\<le> b + c \\<longleftrightarrow> a \\<le> b\"\n  by (simp add: add.commute [of a c] add.commute [of b c])\n\nlemma add_le_imp_le_right: \"a + c \\<le> b + c \\<Longrightarrow> a \\<le> b\"\n  by simp\n\nlemma max_add_distrib_left: \"max x y + z = max (x + z) (y + z)\"\n  unfolding max_def by auto\n\nlemma min_add_distrib_left: \"min x y + z = min (x + z) (y + z)\"\n  unfolding min_def by auto\n\nlemma max_add_distrib_right: \"x + max y z = max (x + y) (x + z)\"\n  unfolding max_def by auto\n\nlemma min_add_distrib_right: \"x + min y z = min (x + y) (x + z)\"\n  unfolding min_def by auto\n\nend\n\nsubsection \\<open>Support for reasoning about signs\\<close>\n\nclass ordered_comm_monoid_add = comm_monoid_add + ordered_ab_semigroup_add\nbegin\n\nlemma add_nonneg_nonneg [simp]: \"0 \\<le> a \\<Longrightarrow> 0 \\<le> b \\<Longrightarrow> 0 \\<le> a + b\"\n  using add_mono[of 0 a 0 b] by simp\n\nlemma add_nonpos_nonpos: \"a \\<le> 0 \\<Longrightarrow> b \\<le> 0 \\<Longrightarrow> a + b \\<le> 0\"\n  using add_mono[of a 0 b 0] by simp\n\nlemma add_nonneg_eq_0_iff: \"0 \\<le> x \\<Longrightarrow> 0 \\<le> y \\<Longrightarrow> x + y = 0 \\<longleftrightarrow> x = 0 \\<and> y = 0\"\n  using add_left_mono[of 0 y x] add_right_mono[of 0 x y] by auto\n\nlemma add_nonpos_eq_0_iff: \"x \\<le> 0 \\<Longrightarrow> y \\<le> 0 \\<Longrightarrow> x + y = 0 \\<longleftrightarrow> x = 0 \\<and> y = 0\"\n  using add_left_mono[of y 0 x] add_right_mono[of x 0 y] by auto\n\nlemma add_increasing: \"0 \\<le> a \\<Longrightarrow> b \\<le> c \\<Longrightarrow> b \\<le> a + c\"\n  using add_mono [of 0 a b c] by simp\n\nlemma add_increasing2: \"0 \\<le> c \\<Longrightarrow> b \\<le> a \\<Longrightarrow> b \\<le> a + c\"\n  by (simp add: add_increasing add.commute [of a])\n\nlemma add_decreasing: \"a \\<le> 0 \\<Longrightarrow> c \\<le> b \\<Longrightarrow> a + c \\<le> b\"\n  using add_mono [of a 0 c b] by simp\n\nlemma add_decreasing2: \"c \\<le> 0 \\<Longrightarrow> a \\<le> b \\<Longrightarrow> a + c \\<le> b\"\n  using add_mono[of a b c 0] by simp\n\nlemma add_pos_nonneg: \"0 < a \\<Longrightarrow> 0 \\<le> b \\<Longrightarrow> 0 < a + b\"\n  using less_le_trans[of 0 a \"a + b\"] by (simp add: add_increasing2)\n\nlemma add_pos_pos: \"0 < a \\<Longrightarrow> 0 < b \\<Longrightarrow> 0 < a + b\"\n  by (intro add_pos_nonneg less_imp_le)\n\nlemma add_nonneg_pos: \"0 \\<le> a \\<Longrightarrow> 0 < b \\<Longrightarrow> 0 < a + b\"\n  using add_pos_nonneg[of b a] by (simp add: add_commute)\n\nlemma add_neg_nonpos: \"a < 0 \\<Longrightarrow> b \\<le> 0 \\<Longrightarrow> a + b < 0\"\n  using le_less_trans[of \"a + b\" a 0] by (simp add: add_decreasing2)\n\nlemma add_neg_neg: \"a < 0 \\<Longrightarrow> b < 0 \\<Longrightarrow> a + b < 0\"\n  by (intro add_neg_nonpos less_imp_le)\n\nlemma add_nonpos_neg: \"a \\<le> 0 \\<Longrightarrow> b < 0 \\<Longrightarrow> a + b < 0\"\n  using add_neg_nonpos[of b a] by (simp add: add_commute)\n\nlemmas add_sign_intros =\n  add_pos_nonneg add_pos_pos add_nonneg_pos add_nonneg_nonneg\n  add_neg_nonpos add_neg_neg add_nonpos_neg add_nonpos_nonpos\n\nend\n\nclass strict_ordered_comm_monoid_add = comm_monoid_add + strict_ordered_ab_semigroup_add\nbegin\n\nlemma pos_add_strict: \"0 < a \\<Longrightarrow> b < c \\<Longrightarrow> b < a + c\"\n  using add_strict_mono [of 0 a b c] by simp\n\nend\n\nclass ordered_cancel_comm_monoid_add = ordered_comm_monoid_add + cancel_ab_semigroup_add\nbegin\n\nsubclass ordered_cancel_ab_semigroup_add ..\nsubclass strict_ordered_comm_monoid_add ..\n\nlemma add_strict_increasing: \"0 < a \\<Longrightarrow> b \\<le> c \\<Longrightarrow> b < a + c\"\n  using add_less_le_mono [of 0 a b c] by simp\n\nlemma add_strict_increasing2: \"0 \\<le> a \\<Longrightarrow> b < c \\<Longrightarrow> b < a + c\"\n  using add_le_less_mono [of 0 a b c] by simp\n\nend\n\nclass ordered_ab_semigroup_monoid_add_imp_le = monoid_add + ordered_ab_semigroup_add_imp_le\nbegin\n\nlemma add_less_same_cancel1 [simp]: \"b + a < b \\<longleftrightarrow> a < 0\"\n  using add_less_cancel_left [of _ _ 0] by simp\n\nlemma add_less_same_cancel2 [simp]: \"a + b < b \\<longleftrightarrow> a < 0\"\n  using add_less_cancel_right [of _ _ 0] by simp\n\nlemma less_add_same_cancel1 [simp]: \"a < a + b \\<longleftrightarrow> 0 < b\"\n  using add_less_cancel_left [of _ 0] by simp\n\nlemma less_add_same_cancel2 [simp]: \"a < b + a \\<longleftrightarrow> 0 < b\"\n  using add_less_cancel_right [of 0] by simp\n\nlemma add_le_same_cancel1 [simp]: \"b + a \\<le> b \\<longleftrightarrow> a \\<le> 0\"\n  using add_le_cancel_left [of _ _ 0] by simp\n\nlemma add_le_same_cancel2 [simp]: \"a + b \\<le> b \\<longleftrightarrow> a \\<le> 0\"\n  using add_le_cancel_right [of _ _ 0] by simp\n\nlemma le_add_same_cancel1 [simp]: \"a \\<le> a + b \\<longleftrightarrow> 0 \\<le> b\"\n  using add_le_cancel_left [of _ 0] by simp\n\nlemma le_add_same_cancel2 [simp]: \"a \\<le> b + a \\<longleftrightarrow> 0 \\<le> b\"\n  using add_le_cancel_right [of 0] by simp\n\nsubclass cancel_comm_monoid_add\n  by standard auto\n\nsubclass ordered_cancel_comm_monoid_add\n  by standard\n\nend\n\nclass ordered_ab_group_add = ab_group_add + ordered_ab_semigroup_add\nbegin\n\nsubclass ordered_cancel_ab_semigroup_add ..\n\nsubclass ordered_ab_semigroup_monoid_add_imp_le\nproof\n  fix a b c :: 'a\n  assume \"c + a \\<le> c + b\"\n  then have \"(-c) + (c + a) \\<le> (-c) + (c + b)\"\n    by (rule add_left_mono)\n  then have \"((-c) + c) + a \\<le> ((-c) + c) + b\"\n    by (simp only: add.assoc)\n  then show \"a \\<le> b\" by simp\nqed\n\nlemma max_diff_distrib_left: \"max x y - z = max (x - z) (y - z)\"\n  using max_add_distrib_left [of x y \"- z\"] by simp\n\nlemma min_diff_distrib_left: \"min x y - z = min (x - z) (y - z)\"\n  using min_add_distrib_left [of x y \"- z\"] by simp\n\nlemma le_imp_neg_le:\n  assumes \"a \\<le> b\"\n  shows \"- b \\<le> - a\"\nproof -\n  from assms have \"- a + a \\<le> - a + b\"\n    by (rule add_left_mono)\n  then have \"0 \\<le> - a + b\"\n    by simp\n  then have \"0 + (- b) \\<le> (- a + b) + (- b)\"\n    by (rule add_right_mono)\n  then show ?thesis\n    by (simp add: algebra_simps)\nqed\n\nlemma neg_le_iff_le [simp]: \"- b \\<le> - a \\<longleftrightarrow> a \\<le> b\"\nproof\n  assume \"- b \\<le> - a\"\n  then have \"- (- a) \\<le> - (- b)\"\n    by (rule le_imp_neg_le)\n  then show \"a \\<le> b\"\n    by simp\nnext\n  assume \"a \\<le> b\"\n  then show \"- b \\<le> - a\"\n    by (rule le_imp_neg_le)\nqed\n\nlemma neg_le_0_iff_le [simp]: \"- a \\<le> 0 \\<longleftrightarrow> 0 \\<le> a\"\n  by (subst neg_le_iff_le [symmetric]) simp\n\nlemma neg_0_le_iff_le [simp]: \"0 \\<le> - a \\<longleftrightarrow> a \\<le> 0\"\n  by (subst neg_le_iff_le [symmetric]) simp\n\nlemma neg_less_iff_less [simp]: \"- b < - a \\<longleftrightarrow> a < b\"\n  by (auto simp add: less_le)\n\nlemma neg_less_0_iff_less [simp]: \"- a < 0 \\<longleftrightarrow> 0 < a\"\n  by (subst neg_less_iff_less [symmetric]) simp\n\nlemma neg_0_less_iff_less [simp]: \"0 < - a \\<longleftrightarrow> a < 0\"\n  by (subst neg_less_iff_less [symmetric]) simp\n\ntext \\<open>The next several equations can make the simplifier loop!\\<close>\n\nlemma less_minus_iff: \"a < - b \\<longleftrightarrow> b < - a\"\nproof -\n  have \"- (- a) < - b \\<longleftrightarrow> b < - a\"\n    by (rule neg_less_iff_less)\n  then show ?thesis by simp\nqed\n\nlemma minus_less_iff: \"- a < b \\<longleftrightarrow> - b < a\"\nproof -\n  have \"- a < - (- b) \\<longleftrightarrow> - b < a\"\n    by (rule neg_less_iff_less)\n  then show ?thesis by simp\nqed\n\nlemma le_minus_iff: \"a \\<le> - b \\<longleftrightarrow> b \\<le> - a\"\n  by (auto simp: order.order_iff_strict less_minus_iff)\n\nlemma minus_le_iff: \"- a \\<le> b \\<longleftrightarrow> - b \\<le> a\"\n  by (auto simp add: le_less minus_less_iff)\n\nlemma diff_less_0_iff_less [simp]: \"a - b < 0 \\<longleftrightarrow> a < b\"\nproof -\n  have \"a - b < 0 \\<longleftrightarrow> a + (- b) < b + (- b)\"\n    by simp\n  also have \"\\<dots> \\<longleftrightarrow> a < b\"\n    by (simp only: add_less_cancel_right)\n  finally show ?thesis .\nqed\n\nlemmas less_iff_diff_less_0 = diff_less_0_iff_less [symmetric]\n\nlemma diff_less_eq [algebra_simps, algebra_split_simps, field_simps, field_split_simps]:\n  \"a - b < c \\<longleftrightarrow> a < c + b\"\nproof (subst less_iff_diff_less_0 [of a])\n  show \"(a - b < c) = (a - (c + b) < 0)\"\n    by (simp add: algebra_simps less_iff_diff_less_0 [of _ c])\nqed\n\nlemma less_diff_eq [algebra_simps, algebra_split_simps, field_simps, field_split_simps]:\n  \"a < c - b \\<longleftrightarrow> a + b < c\"\nproof (subst less_iff_diff_less_0 [of \"a + b\"])\n  show \"(a < c - b) = (a + b - c < 0)\"\n    by (simp add: algebra_simps less_iff_diff_less_0 [of a])\nqed\n\nlemma diff_gt_0_iff_gt [simp]: \"a - b > 0 \\<longleftrightarrow> a > b\"\n  by (simp add: less_diff_eq)\n\nlemma diff_le_eq [algebra_simps, algebra_split_simps, field_simps, field_split_simps]:\n  \"a - b \\<le> c \\<longleftrightarrow> a \\<le> c + b\"\n  by (auto simp add: le_less diff_less_eq )\n\nlemma le_diff_eq [algebra_simps, algebra_split_simps, field_simps, field_split_simps]:\n  \"a \\<le> c - b \\<longleftrightarrow> a + b \\<le> c\"\n  by (auto simp add: le_less less_diff_eq)\n\nlemma diff_le_0_iff_le [simp]: \"a - b \\<le> 0 \\<longleftrightarrow> a \\<le> b\"\n  by (simp add: algebra_simps)\n\nlemmas le_iff_diff_le_0 = diff_le_0_iff_le [symmetric]\n\nlemma diff_ge_0_iff_ge [simp]: \"a - b \\<ge> 0 \\<longleftrightarrow> a \\<ge> b\"\n  by (simp add: le_diff_eq)\n\nlemma diff_eq_diff_less: \"a - b = c - d \\<Longrightarrow> a < b \\<longleftrightarrow> c < d\"\n  by (auto simp only: less_iff_diff_less_0 [of a b] less_iff_diff_less_0 [of c d])\n\nlemma diff_eq_diff_less_eq: \"a - b = c - d \\<Longrightarrow> a \\<le> b \\<longleftrightarrow> c \\<le> d\"\n  by (auto simp only: le_iff_diff_le_0 [of a b] le_iff_diff_le_0 [of c d])\n\nlemma diff_mono: \"a \\<le> b \\<Longrightarrow> d \\<le> c \\<Longrightarrow> a - c \\<le> b - d\"\n  by (simp add: field_simps add_mono)\n\nlemma diff_left_mono: \"b \\<le> a \\<Longrightarrow> c - a \\<le> c - b\"\n  by (simp add: field_simps)\n\nlemma diff_right_mono: \"a \\<le> b \\<Longrightarrow> a - c \\<le> b - c\"\n  by (simp add: field_simps)\n\nlemma diff_strict_mono: \"a < b \\<Longrightarrow> d < c \\<Longrightarrow> a - c < b - d\"\n  by (simp add: field_simps add_strict_mono)\n\nlemma diff_strict_left_mono: \"b < a \\<Longrightarrow> c - a < c - b\"\n  by (simp add: field_simps)\n\nlemma diff_strict_right_mono: \"a < b \\<Longrightarrow> a - c < b - c\"\n  by (simp add: field_simps)\n\nend\n\nlocale group_cancel\nbegin\n\nlemma add1: \"(A::'a::comm_monoid_add) \\<equiv> k + a \\<Longrightarrow> A + b \\<equiv> k + (a + b)\"\n  by (simp only: ac_simps)\n\nlemma add2: \"(B::'a::comm_monoid_add) \\<equiv> k + b \\<Longrightarrow> a + B \\<equiv> k + (a + b)\"\n  by (simp only: ac_simps)\n\nlemma sub1: \"(A::'a::ab_group_add) \\<equiv> k + a \\<Longrightarrow> A - b \\<equiv> k + (a - b)\"\n  by (simp only: add_diff_eq)\n\nlemma sub2: \"(B::'a::ab_group_add) \\<equiv> k + b \\<Longrightarrow> a - B \\<equiv> - k + (a - b)\"\n  by (simp only: minus_add diff_conv_add_uminus ac_simps)\n\nlemma neg1: \"(A::'a::ab_group_add) \\<equiv> k + a \\<Longrightarrow> - A \\<equiv> - k + - a\"\n  by (simp only: minus_add_distrib)\n\nlemma rule0: \"(a::'a::comm_monoid_add) \\<equiv> a + 0\"\n  by (simp only: add_0_right)\n\nend\n\nML_file \\<open>Tools/group_cancel.ML\\<close>\n\nsimproc_setup group_cancel_add (\"a + b::'a::ab_group_add\") =\n  \\<open>fn phi => fn ss => try Group_Cancel.cancel_add_conv\\<close>\n\nsimproc_setup group_cancel_diff (\"a - b::'a::ab_group_add\") =\n  \\<open>fn phi => fn ss => try Group_Cancel.cancel_diff_conv\\<close>\n\nsimproc_setup group_cancel_eq (\"a = (b::'a::ab_group_add)\") =\n  \\<open>fn phi => fn ss => try Group_Cancel.cancel_eq_conv\\<close>\n\nsimproc_setup group_cancel_le (\"a \\<le> (b::'a::ordered_ab_group_add)\") =\n  \\<open>fn phi => fn ss => try Group_Cancel.cancel_le_conv\\<close>\n\nsimproc_setup group_cancel_less (\"a < (b::'a::ordered_ab_group_add)\") =\n  \\<open>fn phi => fn ss => try Group_Cancel.cancel_less_conv\\<close>\n\nclass linordered_ab_semigroup_add =\n  linorder + ordered_ab_semigroup_add\n\nclass linordered_cancel_ab_semigroup_add =\n  linorder + ordered_cancel_ab_semigroup_add\nbegin\n\nsubclass linordered_ab_semigroup_add ..\n\nsubclass ordered_ab_semigroup_add_imp_le\nproof\n  fix a b c :: 'a\n  assume le1: \"c + a \\<le> c + b\"\n  show \"a \\<le> b\"\n  proof (rule ccontr)\n    assume *: \"\\<not> ?thesis\"\n    then have \"b \\<le> a\" by (simp add: linorder_not_le)\n    then have \"c + b \\<le> c + a\" by (rule add_left_mono)\n    then have \"c + a = c + b\"\n      using le1 by (iprover intro: order.antisym)\n    then have \"a = b\"\n      by simp\n    with * show False\n      by (simp add: linorder_not_le [symmetric])\n  qed\nqed\n\nend\n\nclass linordered_ab_group_add = linorder + ordered_ab_group_add\nbegin\n\nsubclass linordered_cancel_ab_semigroup_add ..\n\nlemma equal_neg_zero [simp]: \"a = - a \\<longleftrightarrow> a = 0\"\nproof\n  assume \"a = 0\"\n  then show \"a = - a\" by simp\nnext\n  assume A: \"a = - a\"\n  show \"a = 0\"\n  proof (cases \"0 \\<le> a\")\n    case True\n    with A have \"0 \\<le> - a\" by auto\n    with le_minus_iff have \"a \\<le> 0\" by simp\n    with True show ?thesis by (auto intro: order_trans)\n  next\n    case False\n    then have B: \"a \\<le> 0\" by auto\n    with A have \"- a \\<le> 0\" by auto\n    with B show ?thesis by (auto intro: order_trans)\n  qed\nqed\n\nlemma neg_equal_zero [simp]: \"- a = a \\<longleftrightarrow> a = 0\"\n  by (auto dest: sym)\n\nlemma neg_less_eq_nonneg [simp]: \"- a \\<le> a \\<longleftrightarrow> 0 \\<le> a\"\nproof\n  assume *: \"- a \\<le> a\"\n  show \"0 \\<le> a\"\n  proof (rule classical)\n    assume \"\\<not> ?thesis\"\n    then have \"a < 0\" by auto\n    with * have \"- a < 0\" by (rule le_less_trans)\n    then show ?thesis by auto\n  qed\nnext\n  assume *: \"0 \\<le> a\"\n  then have \"- a \\<le> 0\" by (simp add: minus_le_iff)\n  from this * show \"- a \\<le> a\" by (rule order_trans)\nqed\n\nlemma neg_less_pos [simp]: \"- a < a \\<longleftrightarrow> 0 < a\"\n  by (auto simp add: less_le)\n\nlemma less_eq_neg_nonpos [simp]: \"a \\<le> - a \\<longleftrightarrow> a \\<le> 0\"\n  using neg_less_eq_nonneg [of \"- a\"] by simp\n\nlemma less_neg_neg [simp]: \"a < - a \\<longleftrightarrow> a < 0\"\n  using neg_less_pos [of \"- a\"] by simp\n\nlemma double_zero [simp]: \"a + a = 0 \\<longleftrightarrow> a = 0\"\nproof\n  assume \"a + a = 0\"\n  then have a: \"- a = a\" by (rule minus_unique)\n  then show \"a = 0\" by (simp only: neg_equal_zero)\nnext\n  assume \"a = 0\"\n  then show \"a + a = 0\" by simp\nqed\n\nlemma double_zero_sym [simp]: \"0 = a + a \\<longleftrightarrow> a = 0\"\n  using double_zero [of a] by (simp only: eq_commute)\n\nlemma zero_less_double_add_iff_zero_less_single_add [simp]: \"0 < a + a \\<longleftrightarrow> 0 < a\"\nproof\n  assume \"0 < a + a\"\n  then have \"0 - a < a\" by (simp only: diff_less_eq)\n  then have \"- a < a\" by simp\n  then show \"0 < a\" by simp\nnext\n  assume \"0 < a\"\n  with this have \"0 + 0 < a + a\"\n    by (rule add_strict_mono)\n  then show \"0 < a + a\" by simp\nqed\n\nlemma zero_le_double_add_iff_zero_le_single_add [simp]: \"0 \\<le> a + a \\<longleftrightarrow> 0 \\<le> a\"\n  by (auto simp add: le_less)\n\nlemma double_add_less_zero_iff_single_add_less_zero [simp]: \"a + a < 0 \\<longleftrightarrow> a < 0\"\nproof -\n  have \"\\<not> a + a < 0 \\<longleftrightarrow> \\<not> a < 0\"\n    by (simp add: not_less)\n  then show ?thesis by simp\nqed\n\nlemma double_add_le_zero_iff_single_add_le_zero [simp]: \"a + a \\<le> 0 \\<longleftrightarrow> a \\<le> 0\"\nproof -\n  have \"\\<not> a + a \\<le> 0 \\<longleftrightarrow> \\<not> a \\<le> 0\"\n    by (simp add: not_le)\n  then show ?thesis by simp\nqed\n\nlemma minus_max_eq_min: \"- max x y = min (- x) (- y)\"\n  by (auto simp add: max_def min_def)\n\nlemma minus_min_eq_max: \"- min x y = max (- x) (- y)\"\n  by (auto simp add: max_def min_def)\n\nend\n\nclass abs =\n  fixes abs :: \"'a \\<Rightarrow> 'a\"  (\"\\<bar>_\\<bar>\")\n\nclass sgn =\n  fixes sgn :: \"'a \\<Rightarrow> 'a\"\n\nclass ordered_ab_group_add_abs = ordered_ab_group_add + abs +\n  assumes abs_ge_zero [simp]: \"\\<bar>a\\<bar> \\<ge> 0\"\n    and abs_ge_self: \"a \\<le> \\<bar>a\\<bar>\"\n    and abs_leI: \"a \\<le> b \\<Longrightarrow> - a \\<le> b \\<Longrightarrow> \\<bar>a\\<bar> \\<le> b\"\n    and abs_minus_cancel [simp]: \"\\<bar>-a\\<bar> = \\<bar>a\\<bar>\"\n    and abs_triangle_ineq: \"\\<bar>a + b\\<bar> \\<le> \\<bar>a\\<bar> + \\<bar>b\\<bar>\"\nbegin\n\nlemma abs_minus_le_zero: \"- \\<bar>a\\<bar> \\<le> 0\"\n  unfolding neg_le_0_iff_le by simp\n\nlemma abs_of_nonneg [simp]:\n  assumes nonneg: \"0 \\<le> a\"\n  shows \"\\<bar>a\\<bar> = a\"\nproof (rule order.antisym)\n  show \"a \\<le> \\<bar>a\\<bar>\" by (rule abs_ge_self)\n  from nonneg le_imp_neg_le have \"- a \\<le> 0\" by simp\n  from this nonneg have \"- a \\<le> a\" by (rule order_trans)\n  then show \"\\<bar>a\\<bar> \\<le> a\" by (auto intro: abs_leI)\nqed\n\nlemma abs_idempotent [simp]: \"\\<bar>\\<bar>a\\<bar>\\<bar> = \\<bar>a\\<bar>\"\n  by (rule order.antisym) (auto intro!: abs_ge_self abs_leI order_trans [of \"- \\<bar>a\\<bar>\" 0 \"\\<bar>a\\<bar>\"])\n\nlemma abs_eq_0 [simp]: \"\\<bar>a\\<bar> = 0 \\<longleftrightarrow> a = 0\"\nproof -\n  have \"\\<bar>a\\<bar> = 0 \\<Longrightarrow> a = 0\"\n  proof (rule order.antisym)\n    assume zero: \"\\<bar>a\\<bar> = 0\"\n    with abs_ge_self show \"a \\<le> 0\" by auto\n    from zero have \"\\<bar>-a\\<bar> = 0\" by simp\n    with abs_ge_self [of \"- a\"] have \"- a \\<le> 0\" by auto\n    with neg_le_0_iff_le show \"0 \\<le> a\" by auto\n  qed\n  then show ?thesis by auto\nqed\n\nlemma abs_zero [simp]: \"\\<bar>0\\<bar> = 0\"\n  by simp\n\nlemma abs_0_eq [simp]: \"0 = \\<bar>a\\<bar> \\<longleftrightarrow> a = 0\"\nproof -\n  have \"0 = \\<bar>a\\<bar> \\<longleftrightarrow> \\<bar>a\\<bar> = 0\" by (simp only: eq_ac)\n  then show ?thesis by simp\nqed\n\nlemma abs_le_zero_iff [simp]: \"\\<bar>a\\<bar> \\<le> 0 \\<longleftrightarrow> a = 0\"\nproof\n  assume \"\\<bar>a\\<bar> \\<le> 0\"\n  then have \"\\<bar>a\\<bar> = 0\" by (rule order.antisym) simp\n  then show \"a = 0\" by simp\nnext\n  assume \"a = 0\"\n  then show \"\\<bar>a\\<bar> \\<le> 0\" by simp\nqed\n\nlemma abs_le_self_iff [simp]: \"\\<bar>a\\<bar> \\<le> a \\<longleftrightarrow> 0 \\<le> a\"\nproof -\n  have \"0 \\<le> \\<bar>a\\<bar>\"\n    using abs_ge_zero by blast\n  then have \"\\<bar>a\\<bar> \\<le> a \\<Longrightarrow> 0 \\<le> a\"\n    using order.trans by blast\n  then show ?thesis\n    using abs_of_nonneg eq_refl by blast\nqed\n\nlemma zero_less_abs_iff [simp]: \"0 < \\<bar>a\\<bar> \\<longleftrightarrow> a \\<noteq> 0\"\n  by (simp add: less_le)\n\nlemma abs_not_less_zero [simp]: \"\\<not> \\<bar>a\\<bar> < 0\"\nproof -\n  have \"x \\<le> y \\<Longrightarrow> \\<not> y < x\" for x y by auto\n  then show ?thesis by simp\nqed\n\nlemma abs_ge_minus_self: \"- a \\<le> \\<bar>a\\<bar>\"\nproof -\n  have \"- a \\<le> \\<bar>-a\\<bar>\" by (rule abs_ge_self)\n  then show ?thesis by simp\nqed\n\nlemma abs_minus_commute: \"\\<bar>a - b\\<bar> = \\<bar>b - a\\<bar>\"\nproof -\n  have \"\\<bar>a - b\\<bar> = \\<bar>- (a - b)\\<bar>\"\n    by (simp only: abs_minus_cancel)\n  also have \"\\<dots> = \\<bar>b - a\\<bar>\" by simp\n  finally show ?thesis .\nqed\n\nlemma abs_of_pos: \"0 < a \\<Longrightarrow> \\<bar>a\\<bar> = a\"\n  by (rule abs_of_nonneg) (rule less_imp_le)\n\nlemma abs_of_nonpos [simp]:\n  assumes \"a \\<le> 0\"\n  shows \"\\<bar>a\\<bar> = - a\"\nproof -\n  let ?b = \"- a\"\n  have \"- ?b \\<le> 0 \\<Longrightarrow> \\<bar>- ?b\\<bar> = - (- ?b)\"\n    unfolding abs_minus_cancel [of ?b]\n    unfolding neg_le_0_iff_le [of ?b]\n    unfolding minus_minus by (erule abs_of_nonneg)\n  then show ?thesis using assms by auto\nqed\n\nlemma abs_of_neg: \"a < 0 \\<Longrightarrow> \\<bar>a\\<bar> = - a\"\n  by (rule abs_of_nonpos) (rule less_imp_le)\n\nlemma abs_le_D1: \"\\<bar>a\\<bar> \\<le> b \\<Longrightarrow> a \\<le> b\"\n  using abs_ge_self by (blast intro: order_trans)\n\nlemma abs_le_D2: \"\\<bar>a\\<bar> \\<le> b \\<Longrightarrow> - a \\<le> b\"\n  using abs_le_D1 [of \"- a\"] by simp\n\nlemma abs_le_iff: \"\\<bar>a\\<bar> \\<le> b \\<longleftrightarrow> a \\<le> b \\<and> - a \\<le> b\"\n  by (blast intro: abs_leI dest: abs_le_D1 abs_le_D2)\n\nlemma abs_triangle_ineq2: \"\\<bar>a\\<bar> - \\<bar>b\\<bar> \\<le> \\<bar>a - b\\<bar>\"\nproof -\n  have \"\\<bar>a\\<bar> = \\<bar>b + (a - b)\\<bar>\"\n    by (simp add: algebra_simps)\n  then have \"\\<bar>a\\<bar> \\<le> \\<bar>b\\<bar> + \\<bar>a - b\\<bar>\"\n    by (simp add: abs_triangle_ineq)\n  then show ?thesis\n    by (simp add: algebra_simps)\nqed\n\nlemma abs_triangle_ineq2_sym: \"\\<bar>a\\<bar> - \\<bar>b\\<bar> \\<le> \\<bar>b - a\\<bar>\"\n  by (simp only: abs_minus_commute [of b] abs_triangle_ineq2)\n\nlemma abs_triangle_ineq3: \"\\<bar>\\<bar>a\\<bar> - \\<bar>b\\<bar>\\<bar> \\<le> \\<bar>a - b\\<bar>\"\n  by (simp add: abs_le_iff abs_triangle_ineq2 abs_triangle_ineq2_sym)\n\nlemma abs_triangle_ineq4: \"\\<bar>a - b\\<bar> \\<le> \\<bar>a\\<bar> + \\<bar>b\\<bar>\"\nproof -\n  have \"\\<bar>a - b\\<bar> = \\<bar>a + - b\\<bar>\"\n    by (simp add: algebra_simps)\n  also have \"\\<dots> \\<le> \\<bar>a\\<bar> + \\<bar>- b\\<bar>\"\n    by (rule abs_triangle_ineq)\n  finally show ?thesis by simp\nqed\n\nlemma abs_diff_triangle_ineq: \"\\<bar>a + b - (c + d)\\<bar> \\<le> \\<bar>a - c\\<bar> + \\<bar>b - d\\<bar>\"\nproof -\n  have \"\\<bar>a + b - (c + d)\\<bar> = \\<bar>(a - c) + (b - d)\\<bar>\"\n    by (simp add: algebra_simps)\n  also have \"\\<dots> \\<le> \\<bar>a - c\\<bar> + \\<bar>b - d\\<bar>\"\n    by (rule abs_triangle_ineq)\n  finally show ?thesis .\nqed\n\nlemma abs_add_abs [simp]: \"\\<bar>\\<bar>a\\<bar> + \\<bar>b\\<bar>\\<bar> = \\<bar>a\\<bar> + \\<bar>b\\<bar>\"\n  (is \"?L = ?R\")\nproof (rule order.antisym)\n  show \"?L \\<ge> ?R\" by (rule abs_ge_self)\n  have \"?L \\<le> \\<bar>\\<bar>a\\<bar>\\<bar> + \\<bar>\\<bar>b\\<bar>\\<bar>\" by (rule abs_triangle_ineq)\n  also have \"\\<dots> = ?R\" by simp\n  finally show \"?L \\<le> ?R\" .\nqed\n\nend\n\nlemma dense_eq0_I:\n  fixes x::\"'a::{dense_linorder,ordered_ab_group_add_abs}\"\n  assumes \"\\<And>e. 0 < e \\<Longrightarrow> \\<bar>x\\<bar> \\<le> e\"\n  shows \"x = 0\"\nproof (cases \"\\<bar>x\\<bar> = 0\")\n  case False\n  then have \"\\<bar>x\\<bar> > 0\"\n    by simp\n  then obtain z where \"0 < z\" \"z < \\<bar>x\\<bar>\"\n    using dense by force\n  then show ?thesis\n    using assms by (simp flip: not_less)\nqed auto\n\nhide_fact (open) ab_diff_conv_add_uminus add_0 mult_1 ab_left_minus\n\nlemmas add_0 = add_0_left (* FIXME duplicate *)\nlemmas mult_1 = mult_1_left (* FIXME duplicate *)\nlemmas ab_left_minus = left_minus (* FIXME duplicate *)\nlemmas diff_diff_eq = diff_diff_add (* FIXME duplicate *)\n\n\nsubsection \\<open>Canonically ordered monoids\\<close>\n\ntext \\<open>Canonically ordered monoids are never groups.\\<close>\n\nclass canonically_ordered_monoid_add = comm_monoid_add + order +\n  assumes le_iff_add: \"a \\<le> b \\<longleftrightarrow> (\\<exists>c. b = a + c)\"\nbegin\n\nlemma zero_le[simp]: \"0 \\<le> x\"\n  by (auto simp: le_iff_add)\n\nlemma le_zero_eq[simp]: \"n \\<le> 0 \\<longleftrightarrow> n = 0\"\n  by (auto intro: order.antisym)\n\nlemma not_less_zero[simp]: \"\\<not> n < 0\"\n  by (auto simp: less_le)\n\nlemma zero_less_iff_neq_zero: \"0 < n \\<longleftrightarrow> n \\<noteq> 0\"\n  by (auto simp: less_le)\n\ntext \\<open>This theorem is useful with \\<open>blast\\<close>\\<close>\nlemma gr_zeroI: \"(n = 0 \\<Longrightarrow> False) \\<Longrightarrow> 0 < n\"\n  by (rule zero_less_iff_neq_zero[THEN iffD2]) iprover\n\nlemma not_gr_zero[simp]: \"\\<not> 0 < n \\<longleftrightarrow> n = 0\"\n  by (simp add: zero_less_iff_neq_zero)\n\nsubclass ordered_comm_monoid_add\n  proof qed (auto simp: le_iff_add add_ac)\n\nlemma gr_implies_not_zero: \"m < n \\<Longrightarrow> n \\<noteq> 0\"\n  by auto\n\nlemma add_eq_0_iff_both_eq_0[simp]: \"x + y = 0 \\<longleftrightarrow> x = 0 \\<and> y = 0\"\n  by (intro add_nonneg_eq_0_iff zero_le)\n\nlemma zero_eq_add_iff_both_eq_0[simp]: \"0 = x + y \\<longleftrightarrow> x = 0 \\<and> y = 0\"\n  using add_eq_0_iff_both_eq_0[of x y] unfolding eq_commute[of 0] .\n\nlemma less_eqE:\n  assumes \\<open>a \\<le> b\\<close>\n  obtains c where \\<open>b = a + c\\<close>\n  using assms by (auto simp add: le_iff_add)\n\nlemma lessE:\n  assumes \\<open>a < b\\<close>\n  obtains c where \\<open>b = a + c\\<close> and \\<open>c \\<noteq> 0\\<close>\nproof -\n  from assms have \\<open>a \\<le> b\\<close> \\<open>a \\<noteq> b\\<close>\n    by simp_all\n  from \\<open>a \\<le> b\\<close> obtain c where \\<open>b = a + c\\<close>\n    by (rule less_eqE)\n  moreover have \\<open>c \\<noteq> 0\\<close> using \\<open>a \\<noteq> b\\<close> \\<open>b = a + c\\<close>\n    by auto\n  ultimately show ?thesis\n    by (rule that)\nqed\n\nlemmas zero_order = zero_le le_zero_eq not_less_zero zero_less_iff_neq_zero not_gr_zero\n  \\<comment> \\<open>This should be attributed with \\<open>[iff]\\<close>, but then \\<open>blast\\<close> fails in \\<open>Set\\<close>.\\<close>\n\nend\n\nclass ordered_cancel_comm_monoid_diff =\n  canonically_ordered_monoid_add + comm_monoid_diff + ordered_ab_semigroup_add_imp_le\nbegin\n\ncontext\n  fixes a b :: 'a\n  assumes le: \"a \\<le> b\"\nbegin\n\nlemma add_diff_inverse: \"a + (b - a) = b\"\n  using le by (auto simp add: le_iff_add)\n\nlemma add_diff_assoc: \"c + (b - a) = c + b - a\"\n  using le by (auto simp add: le_iff_add add.left_commute [of c])\n\nlemma add_diff_assoc2: \"b - a + c = b + c - a\"\n  using le by (auto simp add: le_iff_add add.assoc)\n\nlemma diff_add_assoc: \"c + b - a = c + (b - a)\"\n  using le by (simp add: add.commute add_diff_assoc)\n\nlemma diff_add_assoc2: \"b + c - a = b - a + c\"\n  using le by (simp add: add.commute add_diff_assoc)\n\nlemma diff_diff_right: \"c - (b - a) = c + a - b\"\n  by (simp add: add_diff_inverse add_diff_cancel_left [of a c \"b - a\", symmetric] add.commute)\n\nlemma diff_add: \"b - a + a = b\"\n  by (simp add: add.commute add_diff_inverse)\n\nlemma le_add_diff: \"c \\<le> b + c - a\"\n  by (auto simp add: add.commute diff_add_assoc2 le_iff_add)\n\nlemma le_imp_diff_is_add: \"a \\<le> b \\<Longrightarrow> b - a = c \\<longleftrightarrow> b = c + a\"\n  by (auto simp add: add.commute add_diff_inverse)\n\nlemma le_diff_conv2: \"c \\<le> b - a \\<longleftrightarrow> c + a \\<le> b\"\n  (is \"?P \\<longleftrightarrow> ?Q\")\nproof\n  assume ?P\n  then have \"c + a \\<le> b - a + a\"\n    by (rule add_right_mono)\n  then show ?Q\n    by (simp add: add_diff_inverse add.commute)\nnext\n  assume ?Q\n  then have \"a + c \\<le> a + (b - a)\"\n    by (simp add: add_diff_inverse add.commute)\n  then show ?P by simp\nqed\n\nend\n\nend\n\n\nsubsection \\<open>Tools setup\\<close>\n\nlemma add_mono_thms_linordered_semiring:\n  fixes i j k :: \"'a::ordered_ab_semigroup_add\"\n  shows \"i \\<le> j \\<and> k \\<le> l \\<Longrightarrow> i + k \\<le> j + l\"\n    and \"i = j \\<and> k \\<le> l \\<Longrightarrow> i + k \\<le> j + l\"\n    and \"i \\<le> j \\<and> k = l \\<Longrightarrow> i + k \\<le> j + l\"\n    and \"i = j \\<and> k = l \\<Longrightarrow> i + k = j + l\"\n  by (rule add_mono, clarify+)+\n\nlemma add_mono_thms_linordered_field:\n  fixes i j k :: \"'a::ordered_cancel_ab_semigroup_add\"\n  shows \"i < j \\<and> k = l \\<Longrightarrow> i + k < j + l\"\n    and \"i = j \\<and> k < l \\<Longrightarrow> i + k < j + l\"\n    and \"i < j \\<and> k \\<le> l \\<Longrightarrow> i + k < j + l\"\n    and \"i \\<le> j \\<and> k < l \\<Longrightarrow> i + k < j + l\"\n    and \"i < j \\<and> k < l \\<Longrightarrow> i + k < j + l\"\n  by (auto intro: add_strict_right_mono add_strict_left_mono\n      add_less_le_mono add_le_less_mono add_strict_mono)\n\ncode_identifier\n  code_module Groups \\<rightharpoonup> (SML) Arith and (OCaml) Arith and (Haskell) Arith\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/Groups.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8633916029436189, "lm_q2_score": 0.8198933359135361, "lm_q1q2_score": 0.7078890215371789}}
{"text": "section \\<open>Fixpoints and Complete Lattices\\<close>\n\n(*\n    Author: Viorel Preoteasa\n*)\n\ntheory Complete_Lattice_Prop\nimports WellFoundedTransitive\nbegin\n\ntext\\<open>\nThis theory introduces some results about fixpoints of functions on \ncomplete lattices. The main result is that a monotonic function \nmapping momotonic functions to monotonic functions has the least \nfixpoint monotonic.\n\\<close>\n\ncontext complete_lattice begin\n\nlemma inf_Inf: assumes nonempty: \"A \\<noteq> {}\"\n  shows \"inf x (Inf A) = Inf ((inf x) ` A)\"\n  using assms by (auto simp add: INF_inf_const1 nonempty) \n\nend\n\n\n(*\nMonotonic applications which map monotonic to monotonic have monotonic fixpoints\n*)\n\ndefinition\n  \"mono_mono F = (mono F \\<and> (\\<forall> f . mono f \\<longrightarrow> mono (F f)))\"\n\ntheorem lfp_mono [simp]:\n  \"mono_mono F \\<Longrightarrow> mono (lfp F)\"\n  apply (simp add: mono_mono_def)\n  apply (rule_tac f=\"F\" and P = \"mono\" in lfp_ordinal_induct)\n  apply (simp_all add: mono_def)\n  apply (intro allI impI SUP_least)\n  apply (rule_tac y = \"f y\" in order_trans)\n  apply (auto intro: SUP_upper)\n  done\n\nlemma gfp_ordinal_induct:\n  fixes f :: \"'a::complete_lattice => 'a\"\n  assumes mono: \"mono f\"\n  and P_f: \"!!S. P S ==> P (f S)\"\n  and P_Union: \"!!M. \\<forall>S\\<in>M. P S ==> P (Inf M)\"\n  shows \"P (gfp f)\"\nproof -\n  let ?M = \"{S. gfp f \\<le> S \\<and> P S}\"\n  have \"P (Inf ?M)\" using P_Union by simp\n  also have \"Inf ?M = gfp f\"\n  proof (rule antisym)\n    show \"gfp f \\<le> Inf ?M\" by (blast intro: Inf_greatest)\n    hence \"f (gfp f) \\<le> f (Inf ?M)\" by (rule mono [THEN monoD])\n    hence \"gfp f \\<le> f (Inf ?M)\" using mono [THEN gfp_unfold] by simp\n    hence \"f (Inf ?M) \\<in> ?M\" using P_f P_Union by simp\n    hence \"Inf ?M \\<le> f (Inf ?M)\" by (rule Inf_lower)\n    thus \"Inf ?M \\<le> gfp f\" by (rule gfp_upperbound)\n  qed\n  finally show ?thesis .\nqed \ntheorem gfp_mono [simp]:\n  \"mono_mono F \\<Longrightarrow> mono (gfp F)\"\n  apply (simp add: mono_mono_def)\n  apply (rule_tac f=\"F\" and P = \"mono\" in gfp_ordinal_induct)\n  apply (simp_all, safe)\n  apply (simp_all add: mono_def)\n  apply (intro allI impI INF_greatest)\n  apply (rule_tac y = \"f x\" in order_trans)\n  apply (auto intro: INF_lower)\n  done\n\ncontext complete_lattice begin\n\ndefinition\n  \"Sup_less x (w::'b::well_founded) = Sup {y ::'a . \\<exists> v < w . y = x v}\"\n\nlemma Sup_less_upper:\n  \"v < w \\<Longrightarrow> P v \\<le> Sup_less P w\"\n  by (simp add: Sup_less_def, rule Sup_upper, blast)\n\n\nlemma Sup_less_least:\n  \"(!! v . v < w \\<Longrightarrow> P v \\<le> Q) \\<Longrightarrow> Sup_less P w \\<le> Q\"\n  by (simp add: Sup_less_def, rule Sup_least, blast)\n\nend\n\nlemma Sup_less_fun_eq:\n  \"((Sup_less P w) i) = (Sup_less (\\<lambda> v . P v i)) w\"\n  apply (simp add: Sup_less_def fun_eq_iff)\n  apply (rule arg_cong [of _ _ Sup])\n  apply auto\n  done\n\ntheorem fp_wf_induction:\n  \"f x  = x \\<Longrightarrow> mono f \\<Longrightarrow> (\\<forall> w . (y w) \\<le> f (Sup_less y w)) \\<Longrightarrow> Sup (range y) \\<le> x\"\n  apply (rule Sup_least)\n  apply (simp add: image_def, safe, simp)\n  apply (rule less_induct1, simp_all)\n  apply (rule_tac y = \"f (Sup_less y xa)\" in order_trans, simp)\n  apply (drule_tac x = \"Sup_less y xa\" and y = \"x\" in monoD)\n  by (simp add: Sup_less_least, auto)\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/LatticeProperties/Complete_Lattice_Prop.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392939666335, "lm_q2_score": 0.800691997339971, "lm_q1q2_score": 0.7078431880131615}}
{"text": "theory Jordan\n  imports Walkup\nbegin\n\ntheorem even_genus: \"hypermap H \\<Longrightarrow> even (genus H)\"\nproof (induct \"card (darts H)\" arbitrary: H)\n  case 0\n  then interpret H: hypermap H by simp\n  have \"darts H = {}\"\n    by (metis 0 card_eq_0_iff hypermap_def)\n  then have \"verts (glink H) = {}\"\n    by (simp add: cedge_def cface_def cnode_def glink_def)\n  then have \"pre_digraph.sccs (glink H) = {}\"\n    apply auto\n    by (metis \\<open>verts (with_proj (glink H)) = {}\\<close> pre_digraph.in_sccsE\n      pre_digraph.induced_subgraph_altdef strongly_connected_def subgraph_imp_subverts subset_empty)\n  then have \"euler_lhs H = 0\"\n    by (simp add: \"0.hyps\" euler_lhs_def)\n  also have \"euler_rhs H = 0\"\n    unfolding euler_rhs_def\n    by (metis H.perm_edge H.perm_face H.perm_node \\<open>darts H = {}\\<close> add_eq_0_iff_both_eq_0 \n        perm_on.count_cycles_on_empty perm_on.intro)\n  ultimately have \"genus H = 0\" \n    unfolding genus_def by presburger\n  then show ?case by auto\nnext\n  case (Suc x)\n  then obtain d where \"d \\<in> darts H\"\n    by fastforce\n  then interpret H': walkup H d\n    by (simp add: Suc.prems walkup.intro walkup_axioms.intro)\n  have \"even (genus (walkupE H d))\"\n    by (metis H'.H'_def H'.card_darts_walkup H'.hypermap_walkupE Suc.hyps diff_Suc_1)\n  then show \"even (genus H)\"\n    by (simp add: H'.H'_def H'.even_genus_walkupE)\nqed\n\n(********************* Excerpt from jordan.v **********************************)\n(*  For the induction we consider the following cases for the reduction       *)\n(*  1) a dart not in p, with an E-transform                                   *)\n(*  2) x with an E-transform if x is followed by an N-link (i.e., x = node y) *)\n(*  3) y = face x with an F-transform, if y is followed by an N-link.         *)\n(*  4) y with an E-transform, if y != t (by 3), z = face y)                   *)\n(*  5) y with an N-transform, if y != node x                                  *)\n(*  6) z with an E-transform, if z is followed by an F-link in p              *)\n(*  7) z with an F-transform, otherwise (z is followed by an N-link in p)     *)\n(******************************************************************************)\n\ntheorem planar_Jordan: \"\\<lbrakk>hypermap H; planar H\\<rbrakk> \\<Longrightarrow> hypermap.jordan H\"\nproof (induct \"card (darts H)\" arbitrary: H)\n  case 0\n  then have \"verts (clink H) = {}\"\n    by (metis card_0_eq hypermap.finite_darts hypermap.verts_clink)\n  then have \"\\<And>p. set p \\<subseteq> verts (clink H) \\<Longrightarrow> p = []\"\n    by force\n  then show ?case\n    by (metis \"0.prems\"(1) hypermap.jordan_def hypermap.moebius_path.elims(2) vpathE vwalk_def)\nnext\n  case (Suc n)\n  then interpret H: hypermap H by simp\n  have IHe: \"z \\<in> darts H \\<Longrightarrow> hypermap.jordan (walkupE H z)\" for z\n    by (metis H.finite_darts H.hypermap_axioms Suc.hyps Suc.prems(2) card_Diff_singleton\n        diff_Suc_1 pre_hypermap.select_convs(1) walkup.H'_def hypermap.hypermap_walkupE walkup.intro\n        walkup.planar_walkupE walkupE_def walkup_axioms.intro)\n  have IHn: \"z \\<in> darts H \\<Longrightarrow> hypermap.jordan (walkupN H z)\" for z\n    by (metis H.finite_darts H.hypermap_axioms H.hypermap_permN Suc.hyps Suc.prems(2)\n        card_Diff_singleton diff_Suc_1 hypermap.hypermap_permF walkup.darts_walkupN walkupN_def\n        hypermap.hypermap_walkupE walkup.intro walkup.planar_walkupN walkup_axioms.intro)    \n  have IHf: \"z \\<in> darts H \\<Longrightarrow> hypermap.jordan (walkupF H z)\" for z\n    by (metis H.finite_darts H.hypermap_axioms H.hypermap_permF Suc.hyps Suc.prems(2)\n        card_Diff_singleton diff_Suc_1 hypermap.hypermap_permN walkup.darts_walkupF walkupF_def\n        hypermap.hypermap_walkupE walkup.intro walkup.planar_walkupF walkup_axioms.intro)\n  \n  have liftE: \"\\<lbrakk>z \\<notin> set p; vpath p (clink H)\\<rbrakk> \\<Longrightarrow> vpath p (clink (walkupE H z))\" for p z\n    unfolding vpath_def\n  proof (auto; rule vwalkI; rule)\n    define H' where \"H' = walkupE H z\"\n    assume *: \"z \\<notin> set p\" \"vwalk p (clink H)\" \"distinct p\"\n    { fix x assume \"x \\<in> set p\"\n      then have \"x \\<noteq> z\"\n        using *(1) by blast\n      also have \"x \\<in> darts H\"\n        using \"*\"(2) H.verts_clink \\<open>x \\<in> set p\\<close> by blast\n      ultimately show \"x \\<in> verts (clink H')\"\n        by (metis Diff_iff H'_def H.hypermap_walkupE distinct.simps(2) distinct_singleton \n            empty_set hypermap.verts_clink insert_iff pre_hypermap.select_convs(1) walkupE_def)\n    }\n    {\n      fix x assume **: \"x \\<in> set (vwalk_arcs p)\"\n      then obtain u v where \"(u,v) = x\"\n        by (metis surj_pair)\n      then have \"face H u = v \\<or> node H v = u\"\n        by (metis \"*\"(2) H.arc_clink H.verts_clink \\<open>x \\<in> set (vwalk_arcs p)\\<close>\n            in_set_vwalk_arcsE subsetD vwalkE)\n      also have \"u \\<noteq> z \\<and> v \\<noteq> z\"\n        by (metis *(1) \\<open>(u, v) = x\\<close> \\<open>x \\<in> set (vwalk_arcs p)\\<close> in_set_vwalk_arcsE)\n      ultimately have \"face H' u = v \\<or> node H' v = u\"\n        by (metis H'_def pre_hypermap.select_convs(3) pre_hypermap.select_convs(4) \n            skip_perm_invariant walkupE_def)\n      then show \"x \\<in> arcs_ends (clink H')\"\n        by (metis ** H'_def H.hypermap_walkupE \\<open>(u, v) = x\\<close> hypermap.verts_clink in_set_vwalk_arcsE\n            \\<open>\\<And>x. x \\<in> set p \\<Longrightarrow> x \\<in> verts (with_proj (clink H'))\\<close> hypermap.arc_clink)\n    }\n    show \"p = [] \\<Longrightarrow> False\"\n      using \"*\"(2) by blast\n  qed\n\n  have liftN: \"\\<lbrakk>z \\<notin> set (x#p); face H z \\<notin> set p; vpath (x#p) (clink H)\\<rbrakk>\n                \\<Longrightarrow> vpath (x#p) (clink (walkupN H z))\" for p x z\n  unfolding vpath_def\n  proof (simp; rule vwalkI; rule; auto)\n    assume *: \"face H z \\<notin> set p\" \"z \\<noteq> x\" \"z \\<notin> set p\" \"vwalk (x # p) (clink H)\" \"x \\<notin> set p\" \"distinct p\"\n    define H' where \"H' \\<equiv> walkupN H z\"\n    have \"x \\<in> darts H\"\n      by (metis *(4) H.verts_clink list.set_intros(1) vwalk_verts_in_verts)\n    then have \"x \\<in> darts H'\"\n      by (metis (no_types, lifting) *(2) Diff_iff H'_def H.darts_permN distinct.simps(2) \n          distinct_singleton empty_set insert_iff permF_def pre_hypermap.ext_inject \n          pre_hypermap.surjective walkupE_def walkupN_def)\n    then show \"x \\<in> pverts (clink H')\"\n      by (metis H'_def H.hypermap_permN hypermap.hypermap_permF hypermap.hypermap_walkupE \n          hypermap.verts_clink walkupN_def with_proj_simps(1))\n    { fix v assume \"v \\<in> set p\"\n      then have \"v \\<noteq> z\"\n        using *(3) by fast\n      also have \"v \\<in> darts H\"\n        using *(4) H.verts_clink \\<open>v \\<in> set p\\<close> by fastforce\n      ultimately have \"v \\<in> darts H'\"\n        by (simp add: H'_def H.darts_permN permF_def walkupE_def walkupN_def)\n      then show \"v \\<in> pverts (clink H')\"\n        by (simp add: clink_def cnode_def pair_union_def reverse_def)\n    }\n    fix u v assume \"(u, v) \\<in> set (vwalk_arcs (x # p))\"\n    then have \"u\\<rightarrow>\\<^bsub>clink H\\<^esub>v\"\n      using *(4) by blast\n    then consider (face) \"face H u = v\" | (node) \"node H v = u\"\n      by (metis Gr_eq H.clinkP cface_def cnode_def)\n    then have \"face H' u = v \\<or> node H' v = u\"\n    proof cases\n      case face\n      then have \"face H' u = v\"\n        by (metis \"*\"(2) \"*\"(3) H'_def \\<open>(u, v) \\<in> set (vwalk_arcs (x # p))\\<close> in_set_vwalk_arcsE\n            permF_def permN_def pre_hypermap.select_convs(3) pre_hypermap.select_convs(4) set_ConsD \n            skip_perm_invariant walkupE_def walkupN_def)\n      then show ?thesis by simp\n    next\n      case node\n      then have \"v \\<noteq> face H z \\<and> node H v \\<noteq> z\"\n        by (smt (verit, ccfv_threshold) *(1-3) \\<open>(u, v) \\<in> set (vwalk_arcs (x # p))\\<close>\n            in_set_vwalk_arcsE list.distinct(1) list.inject list.set_cases list.set_sel(1)\n            prod.sel(2) vwalk_arcs.simps(2) vwalk_arcs_Cons)\n      then have \"node H' v = u\"\n        by (smt (z3) \"*\"(2) \"*\"(3) H'_def H.hypermap_permN \\<open>(u, v) \\<in> set (vwalk_arcs (x # p))\\<close>\n            hypermap.skip_edge_Perm in_set_vwalk_arcsE node permF_def permN_def\n            pre_hypermap.select_convs(2) pre_hypermap.select_convs(3) set_ConsD skip_edge_def\n            walkupE_def walkupN_def)\n      then show ?thesis by simp\n    qed\n    then show \"(u,v) \\<in> parcs (clink H')\"\n      by (metis H'_def H.hypermap_permN \\<open>(u, v) \\<in> set (vwalk_arcs (x # p))\\<close>\n          \\<open>\\<And>v. v \\<in> set p \\<Longrightarrow> v \\<in> pverts (clink H')\\<close> \\<open>x \\<in> darts H'\\<close> hypermap.hypermap_permF\n          hypermap.hypermap_walkupE hypermap.parcs_clink hypermap.verts_clink in_set_vwalk_arcsE \n          set_ConsD walkupN_def with_proj_simps(1))\n  qed\n     \n have liftF: \"\\<lbrakk>z \\<notin> set (x#p); face H (edge H z) \\<notin> set p; vpath (x#p) (clink H)\\<rbrakk>\n                \\<Longrightarrow> vpath (x#p) (clink (walkupF H z))\" for p x z\n   unfolding vpath_def\n proof (simp; rule vwalkI; rule; auto)\n   assume *: \"face H (edge H z) \\<notin> set p\" \"z \\<noteq> x\" \"z \\<notin> set p\" \"vwalk (x # p) (clink H)\"\n             \"x \\<notin> set p\" \"distinct p\"\n    define H' where \"H' \\<equiv> walkupF H z\"\n    have \"x \\<in> darts H\"\n      by (metis *(4) H.verts_clink list.set_intros(1) vwalk_verts_in_verts)\n    then have \"x \\<in> darts H'\"\n      by (metis (no_types, lifting) *(2) Diff_iff H'_def H.darts_permF distinct.simps(2) \n          distinct_singleton empty_set insert_iff permN_def pre_hypermap.ext_inject \n          pre_hypermap.surjective walkupE_def walkupF_def)\n    then show \"x \\<in> pverts (clink H')\"\n      by (simp add: clink_def cnode_def pair_union_def reverse_def)\n    { fix v assume \"v \\<in> set p\"\n      then have \"v \\<noteq> z\"\n        using *(3) by fast\n      also have \"v \\<in> darts H\"\n        using *(4) H.verts_clink \\<open>v \\<in> set p\\<close> by fastforce\n      ultimately have \"v \\<in> darts H'\"\n        by (simp add: H'_def H.darts_permF permN_def walkupE_def walkupF_def)\n      then show \"v \\<in> pverts (clink H')\"\n        by (simp add: clink_def cnode_def pair_union_def reverse_def)\n    }\n    fix u v assume \"(u, v) \\<in> set (vwalk_arcs (x # p))\"\n    then have \"u\\<rightarrow>\\<^bsub>clink H\\<^esub>v\"\n      using *(4) by blast\n    then consider (face) \"face H u = v\" | (node) \"node H v = u\"\n      by (metis Gr_eq H.clinkP cface_def cnode_def)\n    then have \"face H' u = v \\<or> node H' v = u\"\n    proof cases\n      case face\n      then have \"u \\<noteq> edge H z \\<and> face H u \\<noteq> z\"\n        by (smt (verit, ccfv_threshold) *(1-3) \\<open>(u, v) \\<in> set (vwalk_arcs (x # p))\\<close>\n            in_set_vwalk_arcsE list.distinct(1) list.inject list.set_cases list.set_sel(1)\n            prod.sel(2) vwalk_arcs.simps(2) vwalk_arcs_Cons)\n      then have \"face H' u = v\"\n        by (metis (no_types, lifting) \"*\"(2,3) H'_def H.hypermap_axioms H.hypermap_permF \n            \\<open>(u, v) \\<in> set (vwalk_arcs (x # p))\\<close> face hypermap.edgeK hypermap.hypermap_walkupE \n            in_set_vwalk_arcsE permF_def permN_def pre_hypermap.select_convs(3,4) set_ConsD\n            skip_perm_invariant walkupE_def walkupF_def)\n      then show ?thesis by simp\n    next\n      case node\n      then have \"node H' v = u\"\n        by (metis \"*\"(2,3) H'_def \\<open>(u, v) \\<in> set (vwalk_arcs (x # p))\\<close> in_set_vwalk_arcsE permF_def\n            permN_def pre_hypermap.select_convs(3,4) set_ConsD skip_perm_invariant\n            walkupE_def walkupF_def)\n      then show ?thesis by simp\n    qed\n    then show \"(u,v) \\<in> parcs (clink H')\"\n      by (metis H'_def H.hypermap_permF \\<open>(u, v) \\<in> set (vwalk_arcs (x # p))\\<close> \n          \\<open>\\<And>v. v \\<in> set p \\<Longrightarrow> v \\<in> pverts (clink H')\\<close> \\<open>x \\<in> pverts (clink H')\\<close> hypermap.hypermap_permN\n          hypermap.hypermap_walkupE hypermap.parcs_clink hypermap.verts_clink in_set_vwalk_arcsE \n          set_ConsD walkupF_def with_proj_simps(1))\n  qed\n\n  {\n    assume \"\\<not> H.jordan\"\n    then obtain x q where xq_def: \"H.moebius_path (x#q)\"\n      using H.jordan_def H.moebius_path.elims(2) by blast\n    define p where \"p \\<equiv> x#q\"\n    then have vpath_p: \"vpath p (clink H)\"\n      using H.moebius_path.elims(2) xq_def by blast\n    have dart_x: \"x \\<in> darts H\"\n      by (metis H.verts_clink list.set_intros(1) vpathE p_def vpath_p vwalk_verts_in_verts)\n    obtain t where t_def: \"(node H t) = last q\"\n      using H.nodeK by blast\n    have dart_t: \"t \\<in> darts H\"\n      by (metis H.moebius_path.simps(2) H.perm_node H.verts_clink Permutations.permutes_not_in\n          last_ConsR last_in_set p_def subsetD t_def vpathE vpath_p vwalkE xq_def)\n    have \"appears_before q t (node H x)\"\n      by (smt (verit, ccfv_threshold) H.faceK H.moebius_path.elims(2) list.inject p_def t_def xq_def)\n    (* Case 1: WalkupE on a dart outside the path *)\n    have \"set p = darts H\"\n    proof (rule ccontr)\n      assume \"set p \\<noteq> darts H\"\n      then obtain u where u_def: \"u \\<notin> set (x#q) \\<and> u \\<in> darts H\"\n        by (metis H.finite_darts H.verts_clink List.finite_set card_mono card_seteq \n            subsetI vpathE vpath_p vwalk_def p_def)\n      interpret H': walkup H u\n        by (simp add: H.hypermap_axioms u_def walkup_axioms.intro walkup_def)\n      define H' where \"H' \\<equiv> walkupE H u\"\n      then have \"vpath (x#q) (clink H')\"\n        using \\<open>u \\<notin> set (x # q) \\<and> u \\<in> darts H\\<close> liftE vpath_p xq_def p_def by blast\n      also have \"appears_before q (face H' (edge H' (last q))) (node H' x)\"\n        by (smt (z3) H'.H'_def H'.walkup_edge H'.walkup_face H'.walkup_node H'_def H.faceK\n            H.moebius_path.simps(2) H.skip_edge_Perm skip_edge_noteq_z xq_def\n            \\<open>appears_before q t ((node H) \\<langle>$\\<rangle> x)\\<close> appears_before_in apply_skip_perm last_in_set\n            list.set_intros p_def skip_edge_def skip_fz skip_perm_invariant t_def u_def)\n      ultimately have \"hypermap.moebius_path H' (x#q)\"\n        using H'_def H.hypermap_walkupE H.moebius_path.simps(2)\n          hypermap.moebius_path.elims(3) p_def xq_def by blast\n      then show False\n        using H'.z_dart H'_def H.hypermap_walkupE IHe hypermap.jordan_def by blast\n    qed\n    obtain y z q' where \"q = y#z#q'\"\n      by (metis H.moebius_path.cases H.moebius_path.elims(2) \\<open>appears_before q t ((node H) \\<langle>$\\<rangle> x)\\<close>\n          appears_before_in apply_inj_eq_iff distinct_length_2_or_more empty_iff empty_set\n          last.simps set_ConsD t_def vpathE xq_def)\n    have dart_y: \"y \\<in> darts H\" and dart_z: \"z \\<in> darts H\"\n      using \\<open>q = y # z # q'\\<close> \\<open>set p = darts H\\<close> p_def by auto\n    have vpath_q': \"q' \\<noteq> [] \\<Longrightarrow> vpath q' (clink H)\"\n      by (metis distinct.simps(2) list.simps(3) vpathE vpathI vpath_p p_def vwalk_consE \\<open>q = y#z#q'\\<close>)\n    have \"y \\<noteq> x\"\n      by (metis \\<open>q = y # z# q'\\<close> distinct_length_2_or_more vpathE vpath_p p_def)\n    have \"t \\<noteq> x\"\n      by (metis \\<open>appears_before q t ((node H) \\<langle>$\\<rangle> x)\\<close> appears_before_in(1) distinct.simps(2)\n          p_def vpathE vpath_p)\n    have \"node H t \\<noteq> x\"\n      by (metis \\<open>q = y#z#q'\\<close> distinct.simps(2) last_in_set list.distinct(1) p_def t_def vpathE vpath_p)\n    have \"node H t \\<noteq> y\"\n      by (metis \\<open>q = y # z # q'\\<close> distinct.simps(2) last_ConsR last_in_set\n          list.simps(3) t_def vpathE vpath_p p_def)\n\n    (* Case 2: node H y = x with WalkupE *)\n    have \"face H x = y\"\n    proof (rule ccontr)\n      assume \"face H x \\<noteq> y\"\n      then have \"node H y = x\"\n        by (metis H.arc_clink H.wf_clink \\<open>q = y # z # q'\\<close> \\<open>set p = darts H\\<close> p_def\n            list.set_intros(1) vpathE vpath_p wf_digraph.vwalk_Cons_Cons wf_digraph_wp_iff)\n      interpret H': walkup H x\n        by (metis H.hypermap_axioms \\<open>set p = darts H\\<close> p_def list.set_intros(1)\n            walkup.intro walkup_axioms.intro)\n      define H' where \" H' \\<equiv> walkupE H x\"\n      have \"vpath q (clink H')\"\n        by (metis H'_def \\<open>q = y # z # q'\\<close> distinct.simps(2) liftE list.distinct(1) p_def\n            vpathE vpathI vpath_p vwalk_consE)\n      also have \"appears_before (z#q') (face H' (edge H' (last (z#q')))) (node H' y)\"\n        by (metis H'.H'_def H.hypermap_walkupE H'.walkup_node H'_def \\<open>node H t \\<noteq> x\\<close> \\<open>node H y = x\\<close>\n            \\<open>appears_before q t (node H x)\\<close> \\<open>q = y # z # q'\\<close> \\<open>t \\<noteq> x\\<close> appears_before_cons\n            apply_inj_eq_iff apply_skip_perm hypermap.nodeK last_ConsR list.simps(3) skip_def t_def)\n      then have \"hypermap.moebius_path H' q\"\n        by (metis H.hypermap_walkupE H'_def \\<open>q = y # z # q'\\<close> calculation \n            hypermap.moebius_path.simps(3))\n      then show False\n        using H'.H'_def H.hypermap_walkupE H'.z_dart H'_def IHe hypermap.jordan_def by auto\n    qed\n\n    have ptnx: \"if y = t then node H x \\<in> set q else appears_before (z # q') t (node H x)\"\n      by (metis \\<open>appears_before q t ((node H) \\<langle>$\\<rangle> x)\\<close> \\<open>q = y # z # q'\\<close> appears_before_cons)\n\n    (* Case 3 - y with walkupF if z = node y *)\n    text_raw \\<open>\\DefineSnippet{jordan_3}{\\<close>\n    have \"face H y = z\"\n    proof (rule ccontr)\n      assume \"face H y \\<noteq> z\"\n      then have \"node H z = y\"\n        by (metis H.arc_clink H.perm_face H.wf_clink \\<open>face H x = y\\<close> \\<open>q = y # z # q'\\<close> \\<open>y \\<noteq> x\\<close> p_def\n          apply_inj_eq_iff permutes_def vpathE vpath_p wf_digraph.vwalk_Cons_Cons wf_digraph_wp_iff)\n      interpret H': walkup H y\n        by (metis H.hypermap_axioms \\<open>q = y # z # q'\\<close> \\<open>set p = darts H\\<close> list.set_intros p_def\n            walkup.intro walkup_axioms_def)\n      define H' where \"H' \\<equiv> walkupF H y\"\n      have vpath_H'_q': \"vpath (z#q') (clink H')\"\n        by (metis H'_def H.faceK \\<open>node H z = y\\<close> \\<open>q = y # z # q'\\<close> distinct.simps(2) liftF \n            list.simps(3) vpathE vpathI vpath_p vwalk_consE p_def)\n      also have \"face H' x = z\"\n        by (metis (no_types, lifting) H'.walkup_axioms H'_def H.faceK \\<open>face H x = y\\<close>\n            \\<open>node H z = y\\<close> \\<open>q = y # z # q'\\<close> apply_inj_eq_iff distinct_length_2_or_more\n            skip_face_def vpathE vpath_p walkup.face_walkupF p_def)\n      then have \"x\\<rightarrow>\\<^bsub>clink H'\\<^esub>z\"\n        by (metis Gr_eq H'.darts_walkupF H'.z_dart H'_def \\<open>set p = darts H\\<close> \\<open>y \\<noteq> x\\<close> p_def\n            arc_in_union cface_def clink_def insert_Diff insert_iff list.set_intros(1))\n      ultimately have vpath_p': \"vpath (x#z#q') (clink H')\"\n        by (metis H'_def H.hypermap_permF \\<open>q = y # z # q'\\<close> distinct_length_2_or_more\n            fin_digraph.axioms(1) hypermap.finite_clink hypermap.hypermap_permN \n            hypermap.hypermap_walkupE list.sel(1) p_def vpathE vpathI vpath_p walkupF_def\n            wf_digraph.vwalk_wf_digraph_consI)\n      then have H'_t: \"face H' (edge H' (last (z#q'))) = (if t=y then z else t)\"\n        by (smt (z3) H'.edge_walkupF H'.walkup_axioms H'_def H.faceK \\<open>(node H) \\<langle>$\\<rangle> t \\<noteq> y\\<close>\n            \\<open>node H z = y\\<close> \\<open>q = y # z # q'\\<close> apply_inj_eq_iff apply_skip_perm last_ConsR\n            list.simps(3) skip_def skip_face_def t_def walkup.face_walkupF)\n      then have moebius_q': \"appears_before (z#q') (if t=y then z else t) (node H' x)\"\n        by (smt (z3) H'.node_walkupF H'_def H.faceK \\<open>(node H) \\<langle>$\\<rangle> z = y\\<close> \\<open>q = y # z # q'\\<close>\n            appears_before_cons apply_skip_perm distinct.simps(2) distinct_length_2_or_more\n            ptnx skip_def vpathE vpath_p p_def)\n      then have \"hypermap.moebius_path H' (x#z#q')\"\n        by (smt (z3) H'_def H.darts_permF H.hypermap_permF vpath_p' H'_t dart_y\n            hypermap.hypermap_permN hypermap.moebius_path.simps(3) walkup.H'_def \n            hypermap.hypermap_walkupE walkup.intro walkupF_def walkup_axioms.intro)\n      then have \"\\<not> hypermap.jordan H'\"\n          by (metis H'_def H.hypermap_permF hypermap.hypermap_permN hypermap.hypermap_walkupE\n              hypermap.jordan_def walkupF_def)\n      then show False\n        by (simp add: H'_def IHf dart_y)\n    qed\n    text_raw \\<open>}%EndSnippet\\<close>\n    \n    (* Case 4: y with walkupE if y \\<noteq> t *)\n    have \"t = y\"\n    proof (rule ccontr)\n      assume \"t \\<noteq> y\"\n      interpret H': walkup H y\n        by (metis H.hypermap_axioms \\<open>q = y # z # q'\\<close> \\<open>set p = darts H\\<close> list.set_intros p_def\n            walkup.intro walkup_axioms_def)\n      define H' where \"H' \\<equiv> walkupE H y\"\n      then have \"vpath (z#q') (clink H')\"\n        by (metis \\<open>q = y # z # q'\\<close> distinct.simps(2) liftE list.simps(3) p_def\n            vpathE vpathI vpath_p vwalk_consE)\n      also have \"face H' x = z\"\n        by (metis H'.H'_def H'.walkup_face H'_def \\<open>face H x = y\\<close> \\<open>face H y = z\\<close> apply_skip_perm skip_fz)\n      ultimately have vpath_H': \"vpath (x#z#q') (clink H')\"\n        by (metis H'_def H.hypermap_walkupE \\<open>q = y # z # q'\\<close> dart_x dart_y distinct_length_2_or_more\n            hypermap.arc_clink hypermap.wf_clink insert_Diff insert_iff pre_hypermap.select_convs(1)\n            vpath_def vpath_p walkupE_def wf_digraph.vwalk_Cons_Cons wf_digraph_wp_iff p_def)\n      moreover have \"appears_before (z#q') t (node H' x)\"\n        by (metis H'.H'_def H'.walkup_node H'_def \\<open>q = y # z # q'\\<close> \\<open>t \\<noteq> y\\<close> appears_before_in(2) \n          distinct.simps(2) distinct_length_2_or_more p_def ptnx skip_perm_invariant vpathE vpath_p)\n      ultimately have \"hypermap.moebius_path H' (x#z#q')\"\n        by (smt (z3) H'.H'_def H'.walkup_node H'_def H.faceK H.hypermap_axioms \\<open>(node H) \\<langle>$\\<rangle> t \\<noteq> y\\<close>\n            \\<open>q = y # z # q'\\<close> \\<open>t \\<noteq> y\\<close> apply_skip_perm hypermap.hypermap_walkupE \n            hypermap.moebius_path.simps(3) hypermap.nodeK last_ConsR list.simps(3) skip_def t_def)\n      then show False\n        using H'_def H.hypermap_walkupE IHe dart_y hypermap.jordan_def by blast\n    qed\n\n    (* Case 5: y with walkupN if y \\<noteq> node x *)\n    have \"node H x = y\"\n    proof (rule ccontr)\n      assume \"node H x \\<noteq> y\"\n      interpret H': walkup H y\n        by (metis H.hypermap_axioms \\<open>q = y # z # q'\\<close> \\<open>set p = darts H\\<close> list.set_intros p_def\n            walkup.intro walkup_axioms_def)\n      define H' where \"H' \\<equiv> walkupN H y\"\n      then have \"vpath (z#q') (clink H')\"\n        by (metis \\<open>(face H) \\<langle>$\\<rangle> y = z\\<close> \\<open>q = y # z # q'\\<close> distinct.simps(2) liftN list.simps(3)\n            vpathE vpathI vpath_p vwalk_consE p_def)\n      also have \"x\\<rightarrow>\\<^bsub>clink H'\\<^esub>z\"\n        by (metis Gr_eq H'.darts_walkupN H'_def \\<open>(face H) \\<langle>$\\<rangle> x = y\\<close> \\<open>(face H) \\<langle>$\\<rangle> y = z\\<close> \\<open>y \\<noteq> x\\<close> \n            apply_skip_perm arc_in_union cface_def clink_def dart_x dart_y insert_Diff insert_iff \n            permF_def permN_def pre_hypermap.select_convs(3) pre_hypermap.select_convs(4) skip_fz \n            walkupE_def walkupN_def)\n      ultimately have vpath_H': \"vpath (x#z#q') (clink H')\"\n        by (metis H'_def H.hypermap_permN \\<open>q = y # z # q'\\<close> distinct_length_2_or_more p_def\n            hypermap.hypermap_permF hypermap.hypermap_walkupE hypermap.wf_clink list.sel(1) \n            vpath_def vpath_p vwalk_consI walkupN_def wf_digraph.adj_in_verts(1) wf_digraph_wp_iff)\n      have \"face H' (edge H' (last (z#q'))) = z\" \n        by (metis H'.edge_walkupN H'.face_walkupN H'_def H.edgeK \\<open>face H x = y\\<close> \n            \\<open>face H y = z\\<close> \\<open>node H t \\<noteq> y\\<close> \\<open>q = y # z # q'\\<close> \\<open>t = y\\<close> \\<open>y \\<noteq> x\\<close> apply_skip_perm \n            last_ConsR list.simps(3) skip_def t_def)\n      then have \"appears_before (z#q') (face H' (edge H' (last (z#q')))) (node H' x)\"\n        by (metis (no_types, lifting) H'.walkup_axioms H'_def \\<open>(face H) \\<langle>$\\<rangle> y = z\\<close> \n            \\<open>(node H) \\<langle>$\\<rangle> x \\<noteq> y\\<close> \\<open>q = y # z # q'\\<close> \\<open>t = y\\<close> \\<open>y \\<noteq> x\\<close> appears_before_cons \n         distinct_length_2_or_more ptnx set_ConsD skip_node_def vpathE vpath_H' walkup.node_walkupN)\n      then have \"hypermap.moebius_path H' (x#z#q')\"\n        by (metis H'_def H.hypermap_permN hypermap.hypermap_permF hypermap.hypermap_walkupE\n            hypermap.moebius_path.simps(3) vpath_H' walkupN_def)\n      then show False\n        by (metis H'_def H.hypermap_permN IHn dart_y hypermap.hypermap_permF \n            hypermap.hypermap_walkupE hypermap.jordan_def walkupN_def)\n    qed\n\n    (* Base case: when there are less than 4 darts we can directly prove a contradiction *)\n    have \"length p \\<ge> 4\"\n    proof (rule ccontr)\n      have \"length p \\<ge> 2\"\n        by (metis H.moebius_path_length add_2_eq_Suc le_add1 less_le_trans not_less\n            numeral_3_eq_3 p_def xq_def)\n      moreover have \"length p = 3 \\<Longrightarrow> False\"\n      proof -\n        assume \"length p = 3\"\n        then have \"q' = []\"\n          by (simp add: \\<open>q = y # z # q'\\<close> p_def)\n        then have \"p = [x,y,z]\"\n          by (simp add: \\<open>q = y # z # q'\\<close> p_def)\n        then have \"darts H = {x,y,z}\"\n          using \\<open>set p = darts H\\<close> by force\n        then have \"face H z = x\"\n          by (smt (verit) H.perm_face \\<open>(face H) \\<langle>$\\<rangle> x = y\\<close> \\<open>(face H) \\<langle>$\\<rangle> y = z\\<close> \\<open>(node H) \\<langle>$\\<rangle> t \\<noteq> x\\<close>\n     \\<open>q = y # z # q'\\<close> \\<open>q' = []\\<close> empty_iff insert_iff last.simps list.distinct(1) permutes_def t_def)\n        have \"node H y = z\"\n          using \\<open>q = y # z # q'\\<close> \\<open>q' = []\\<close> \\<open>t = y\\<close> t_def by auto\n        then have \"node H z = x\"\n          by (smt (z3) H.edgeK H.perm_edge Permutations.permutes_not_in \\<open>(face H) \\<langle>$\\<rangle> y = z\\<close>\n              \\<open>(node H) \\<langle>$\\<rangle> t \\<noteq> x\\<close> \\<open>(node H) \\<langle>$\\<rangle> t \\<noteq> y\\<close> \\<open>(node H) \\<langle>$\\<rangle> x = y\\<close> \\<open>q = y # z # q'\\<close>\n              \\<open>q' = []\\<close> \\<open>set p = darts H\\<close> \\<open>t = y\\<close> apply_inj_eq_iff distinct.simps(2) \n              distinct_singleton insert_iff list.simps(15) p_def)\n        then have \"edge H x = y \\<and> edge H y = z \\<and> edge H z = x\"\n          by (metis H.edgeK \\<open>face H x = y\\<close> \\<open>face H y = z\\<close> \\<open>face H z = x\\<close> \n                            \\<open>node H x = y\\<close> \\<open>node H y = z\\<close>)\n        {\n          fix u assume \"u \\<in> darts H\"\n          then have  \"u = x \\<or> u = y \\<or> u = z\"\n            using \\<open>darts H = {x,y,z}\\<close> by blast\n          then have \"u\\<rightarrow>\\<^sup>*\\<^bsub>cedge H\\<^esub>v \\<and> u\\<rightarrow>\\<^sup>*\\<^bsub>cnode H\\<^esub>v \\<and> u\\<rightarrow>\\<^sup>*\\<^bsub>cface H\\<^esub>v\" if \"v \\<in> darts H\" for v\n            by (smt (z3) Gr_eq Gr_verts H.arc_clink H.cedge_connect_sym H.cface_connect_sym\n              H.clinkP H.cnode_connect_sym H.wf_cedge H.wf_cface H.wf_cnode\n              \\<open>(edge H) \\<langle>$\\<rangle> x = y \\<and> (edge H) \\<langle>$\\<rangle> y = z \\<and> (edge H) \\<langle>$\\<rangle> z = x\\<close> \\<open>(face H) \\<langle>$\\<rangle> x = y\\<close>\n              \\<open>(face H) \\<langle>$\\<rangle> y = z\\<close> \\<open>(face H) \\<langle>$\\<rangle> z = x\\<close> \\<open>(node H) \\<langle>$\\<rangle> x = y\\<close> \\<open>(node H) \\<langle>$\\<rangle> y = z\\<close> \n              \\<open>(node H) \\<langle>$\\<rangle> z = x\\<close> \\<open>p = [x, y, z]\\<close> \\<open>set p = darts H\\<close> cedge_def cface_def cnode_def \n              empty_iff empty_set set_ConsD that wf_digraph.reach_sym_arc wf_digraph.reachable_adjI\n              wf_digraph.reachable_refl wf_digraph_wp_iff)\n        } note reach_enf = this\n        then have strongly_connected_enf: \"strongly_connected (cedge H)\"\n                  \"strongly_connected (cnode H)\" \n                  \"strongly_connected (cface H)\"\n          by (metis Gr_verts cedge_def cnode_def cface_def reach_enf\n              dart_y equals0D strongly_connectedI)+\n        then have \"card (pre_digraph.sccs (cedge H)) = 1\" \n                  \"card (pre_digraph.sccs (cnode H)) = 1\" \n                  \"card (pre_digraph.sccs (cface H)) = 1\"\n          using H.wf_cedge H.wf_cnode H.wf_cface wf_digraph.card_sccs_connected wf_digraph_wp_iff \n          by blast+\n        then have \"euler_rhs H = 3\"\n          unfolding euler_rhs_def\n          by (simp add: perm_on.count_cycles_card_sccs H.finite_darts H.perm_edge H.perm_face\n              H.perm_node cedge_def cface_def cnode_def perm_on.intro)\n\n        have \"card (darts H) = 3\"\n          by (metis \\<open>length p = 3\\<close> \\<open>set p = darts H\\<close> distinct_card vpathE vpath_p)\n        also have \"strongly_connected (glink H)\"\n        proof\n          show \"verts (glink H) \\<noteq> {}\"\n            by (metis H.hypermap_axioms H.verts_clink H.wf_clink dart_x empty_iff \n             hypermap.clink_glink reachable_in_vertsE wf_digraph.reachable_refl wf_digraph_wp_iff)\n          fix u v assume \"u \\<in> verts (glink H)\" \"v \\<in> verts (glink H)\"\n          then show \"u \\<rightarrow>\\<^sup>*\\<^bsub>with_proj (glink H)\\<^esub> v\"\n            by (metis H.arc_clink H.clink_connect_sym H.clink_glink H.verts_clink H.wf_clink\n                H.wf_glink \\<open>(face H) \\<langle>$\\<rangle> x = y\\<close> \\<open>(face H) \\<langle>$\\<rangle> y = z\\<close> \\<open>(node H) \\<langle>$\\<rangle> z = x\\<close> \n                \\<open>q = y # z # q'\\<close> \\<open>q' = []\\<close> \\<open>set p = darts H\\<close> empty_iff empty_set p_def \n                reachable_in_vertsE set_ConsD wf_digraph.reach_sym_arc wf_digraph.reachable_adjI \n                wf_digraph.reachable_refl wf_digraph_wp_iff)\n        qed\n        then have \"card (pre_digraph.sccs (glink H)) = 1\"\n          using H.wf_glink wf_digraph.card_sccs_connected wf_digraph_wp_iff by blast\n        then have \"euler_lhs H = 5\"\n          unfolding euler_lhs_def using \\<open>card (darts H) = 3\\<close> by simp\n        then have \"genus H = 1\"\n          using \\<open>euler_rhs H = 3\\<close> by (simp add: genus_def)\n        then show False\n          by (metis H.finite_darts One_nat_def Suc.prems(2) calculation card_0_eq dart_t\n              empty_iff numeral_3_eq_3 planar_def)\n      qed\n      ultimately show \"\\<not> 4 \\<le> length p \\<Longrightarrow> False\"\n        by (metis H.moebius_path_length Suc_leI le_neq_implies_less numeral_eq_Suc p_def \n            pred_numeral_simps(2) semiring_norm(26,27) xq_def)\n    qed\n\n    then obtain w q'' where \"w # q'' = q'\"\n      by (metis One_nat_def Suc_le_length_iff Suc_le_mono \\<open>q = y # z # q'\\<close> add.commute list.size(4)\n          numeral_3_eq_3 numeral_eq_Suc p_def plus_1_eq_Suc pred_numeral_simps(2) semiring_norm(26,27))\n    then have xyzw: \"p = x#y#z#w#q''\"\n      by (simp add: \\<open>q = y # z # q'\\<close> p_def)\n\n    (* Case 6: z with walkupE if z is followed by an f-link *)\n    have \"node H w = z\"\n    proof (rule ccontr)\n      assume \"node H w \\<noteq> z\"\n      then have \"face H z = w\"\n        by (metis H.arc_clink \\<open>q = y # z # q'\\<close> \\<open>w # q'' = q'\\<close> dart_z list.sel(1)\n            list.simps(3) p_def vpathE vpath_p vwalk_consE)\n      interpret H': walkup H z\n        by (metis H.hypermap_axioms \\<open>q = y # z # q'\\<close> \\<open>set p = darts H\\<close> list.set_intros p_def\n            walkup.intro walkup_axioms_def)\n      define H' where \"H' \\<equiv> walkupE H z\"\n      have \"vpath q' (clink H')\"\n        unfolding H'_def apply (rule liftE)\n        using \\<open>q = y # z # q'\\<close> p_def vpath_p apply auto\n        using \\<open>w # q'' = q'\\<close> vpath_q' by blast\n      moreover have \"x\\<rightarrow>\\<^bsub>clink H'\\<^esub>y\"\n        by (metis H'.H'_def H'.walkup_face H'_def H.hypermap_walkupE \\<open>(face H) \\<langle>$\\<rangle> x = y\\<close> \n            \\<open>q = y # z # q'\\<close> apply_skip_perm dart_x dart_z distinct.simps(2) hypermap.arc_clink\n            insert_Diff insert_iff list.simps(15) p_def pre_hypermap.select_convs(1) skip_invariant\n            vpathE vpath_p walkupE_def)\n      moreover have \"y\\<rightarrow>\\<^bsub>clink H'\\<^esub>w\"\n        by (metis H'.H'_def H'.walkup_face H'_def H.hypermap_walkupE \\<open>(face H) \\<langle>$\\<rangle> y = z\\<close> \n            \\<open>(face H) \\<langle>$\\<rangle> z = w\\<close> apply_skip_perm calculation(2) hypermap.arc_clink \n            hypermap.verts_clink hypermap.wf_clink skip_fz wf_digraph.adj_in_verts(2)\n            wf_digraph_wp_iff)\n      ultimately have \"vpath (x#y#q') (clink H')\"\n        by (metis H'_def H.hypermap_walkupE \\<open>q = y # z # q'\\<close> \\<open>w # q'' = q'\\<close>\n            distinct_length_2_or_more hypermap.wf_clink list.sel(1) p_def vpathE vpathI vpath_p\n            wf_digraph.vwalk_wf_digraph_consI wf_digraph_wp_iff)\n      also have \"appears_before (y#q') t (node H' x)\"\n        by (metis H'.H'_def H'.walkup_node H'_def \\<open>(face H) \\<langle>$\\<rangle> x = y\\<close> \\<open>(face H) \\<langle>$\\<rangle> y = z\\<close> \n            \\<open>(face H) \\<langle>$\\<rangle> z = w\\<close> \\<open>(node H) \\<langle>$\\<rangle> x = y\\<close> \\<open>t = y\\<close> \\<open>w # q'' = q'\\<close> appears_before_id\n            calculation distinct_length_2_or_more list.set_intros(1) skip_perm_invariant vpathE)\n      ultimately have \"hypermap.moebius_path H' (x#y#q')\"\n        by (smt (z3) H'.H'_def H'.walkup_axioms H'.walkup_face H'_def H.edgeK H.hypermap_walkupE\n          H.skip_edge_Perm \\<open>(face H) \\<langle>$\\<rangle> x = y\\<close> \\<open>(face H) \\<langle>$\\<rangle> y = z\\<close> \\<open>q = y # z # q'\\<close> \\<open>t = y\\<close>\n          \\<open>w # q'' = q'\\<close> distinct.simps(2) distinct_length_2_or_more hypermap.moebius_path.simps(3) \n          last_ConsR last_in_set list.distinct(1) p_def skip_edge_def skip_perm_invariant t_def\n          vpathE vpath_p walkup.walkup_edge)\n      then show False\n        using H'_def H.hypermap_walkupE IHe dart_z hypermap.jordan_def by blast\n    qed\n\n    (* Case 7: otherwise z with F-transform *)\n    then have False\n    proof -\n       interpret H': walkup H z\n        by (metis H.hypermap_axioms \\<open>q = y # z # q'\\<close> \\<open>set p = darts H\\<close> list.set_intros p_def\n            walkup.intro walkup_axioms_def)\n      define H' where \"H' \\<equiv> walkupF H z\"\n      have \"vpath (w#q'') (clink H')\"\n        unfolding H'_def apply (rule liftF)\n          apply (metis distinct.simps(2) vpathE vpath_p xyzw)\n         apply (metis H.faceK \\<open>(node H) \\<langle>$\\<rangle> w = z\\<close> \\<open>w # q'' = q'\\<close>\n            distinct.simps(2) list.distinct(1) vpathE vpath_q')\n        using \\<open>w # q'' = q'\\<close> vpath_q' by fastforce\n      moreover have \"face H' x = y\"\n        by (metis H'.walkup_axioms H'_def H.faceK \\<open>(face H) \\<langle>$\\<rangle> x = y\\<close> \\<open>(node H) \\<langle>$\\<rangle> w = z\\<close> \n            \\<open>q = y # z # q'\\<close> \\<open>w # q'' = q'\\<close> distinct_length_2_or_more p_def skip_face_def vpathE \n            vpath_p walkup.face_walkupF)\n      moreover have \"face H' y = w\"\n        by (metis H'.walkup_axioms H'_def H.faceK \\<open>face H y = z\\<close> \\<open>node H w = z\\<close> \\<open>q = y # z # q'\\<close>\n            \\<open>w # q'' = q'\\<close> apply_perm_neq_idI apply_set_perm distinct_length_2_or_more in_set_permI\n            p_def skip_face_def vpathE vpath_p walkup.face_walkupF)\n      ultimately have \"vpath (x#y#q') (clink H')\"\n        by (metis H'.darts_walkupF H'_def H.hypermap_permF \\<open>q = y # z # q'\\<close> \\<open>w # q'' = q'\\<close> dart_x \n            dart_y dart_z distinct_length_2_or_more hypermap.clinkF hypermap.hypermap_permN \n            hypermap.hypermap_walkupE hypermap.verts_clink insert_Diff insert_iff list.sel(1) p_def\n            vpath_def vpath_p vwalk_consI walkupF_def)\n      also have \"appears_before (y#q') t (node H' x)\"\n        by (metis H'.node_walkupF H'.walkup_axioms H'_def \\<open>(face H') \\<langle>$\\<rangle> x = y\\<close> \\<open>(node H) \\<langle>$\\<rangle> x = y\\<close> \n            \\<open>t = y\\<close> \\<open>y \\<noteq> x\\<close> appears_before_cons apply_inj_eq_iff insert_iff list.simps(15)\n            skip_face_def skip_perm_invariant walkup.face_walkupF)\n      ultimately have \"hypermap.moebius_path H' (x#y#q')\"\n        by (smt (z3) H'.edge_walkupF H'_def H.edgeK H.hypermap_permF \\<open>(face H') \\<langle>$\\<rangle> x = y\\<close> \n            \\<open>(face H) \\<langle>$\\<rangle> x = y\\<close> \\<open>(node H) \\<langle>$\\<rangle> w = z\\<close> \\<open>q = y # z # q'\\<close> \\<open>t = y\\<close> \\<open>w # q'' = q'\\<close> \n            apply_inj_eq_iff distinct_length_2_or_more hypermap.hypermap_permN \n            hypermap.hypermap_walkupE hypermap.moebius_path.simps(3) last_ConsR list.distinct(1) \n            p_def skip_perm_invariant t_def vpathE vpath_p walkupF_def)\n      then show False\n        by (metis H'_def H.hypermap_permF IHf dart_z hypermap.hypermap_permN \n            hypermap.hypermap_walkupE hypermap.jordan_def walkupF_def)\n    qed\n  }\n  then show ?case\n    by auto\nqed\n\n\ntheorem Jordan_planar: \"\\<lbrakk>hypermap H; hypermap.jordan H\\<rbrakk> \\<Longrightarrow> planar H\"\nproof (induction \"card (darts H)\" arbitrary: H)\n  case 0\n  then have \"darts H = {}\"\n    by (metis card_0_eq hypermap.finite_darts)\n  then have \"verts (glink H) = {}\"\n    by (simp add: cedge_def cface_def cnode_def glink_def)\n  then have \"pre_digraph.sccs (glink H) = {}\"\n    by (simp add: \"0.prems\"(1) hypermap.wf_glink wf_digraph.sccs_empty wf_digraph_wp_iff)\n  then have \"euler_lhs H = 0\"\n    by (simp add: \"0.hyps\" euler_lhs_def)\n  also have \"euler_rhs H = 0\"\n    by (metis \"0.prems\"(1) \\<open>darts H = {}\\<close> add_eq_0_iff_both_eq_0 euler_rhs_def hypermap.perm_edge \n        hypermap.perm_face hypermap.perm_node perm_on.count_cycles_on_empty perm_on.intro)\n  ultimately show ?case\n    unfolding planar_def genus_def by presburger\nnext\n  case (Suc x)\n  then show ?case sorry\nqed\n\nend", "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/Jordan.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8840392909114836, "lm_q2_score": 0.8006919997179627, "lm_q1q2_score": 0.7078431876691655}}
{"text": "(*  Title:      HOL/ex/Abstract_NAT.thy\n    Author:     Makarius\n*)\n\nsection \\<open>Abstract Natural Numbers primitive recursion\\<close>\n\ntheory Abstract_NAT\nimports Main\nbegin\n\ntext \\<open>Axiomatic Natural Numbers (Peano) -- a monomorphic theory.\\<close>\n\nlocale NAT =\n  fixes zero :: 'n\n    and succ :: \"'n \\<Rightarrow> 'n\"\n  assumes succ_inject [simp]: \"succ m = succ n \\<longleftrightarrow> m = n\"\n    and succ_neq_zero [simp]: \"succ m \\<noteq> zero\"\n    and 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:\n  fixes x :: 'n\n  shows \"\\<exists>!y::'a. Rec e r x y\"\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 NAT 0 Suc\nproof (rule NAT.intro)\n  fix m n\n  show \"Suc m = Suc n \\<longleftrightarrow> m = n\" by simp\n  show \"Suc m \\<noteq> 0\" 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": "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/Abstract_NAT.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392909114836, "lm_q2_score": 0.8006919997179627, "lm_q1q2_score": 0.7078431876691655}}
{"text": "theory Chapter5Guisen\nimports 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\ninductive iter :: \"('a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> nat \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> bool\" for r where\niter_0: \"iter r 0 x x\" |\niter_Suc: \"r x y \\<Longrightarrow> iter r n y z \\<Longrightarrow> iter r (Suc n) x z\"\n\ntext\\<open>\n\\section*{Chapter 5}\n\n\\exercise\nGive a readable, structured proof of the following lemma:\n\\<close>\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\"\n(* your definition/proof here *)\n\ntext\\<open>\nEach step should use at most one of the assumptions @{text T}, @{text A}\nor @{text TA}.\n\\endexercise\n\n\\exercise\nGive a readable, structured proof of the following lemma:\n\\<close>\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)\"\n(* your definition/proof here *)\n\ntext\\<open>\nHint: There are predefined functions @{const take} and {const drop} of type\n@{typ \"nat \\<Rightarrow> 'a list \\<Rightarrow> 'a list\"} such that @{text\"take k [x\\<^sub>1,\\<dots>] = [x\\<^sub>1,\\<dots>,x\\<^sub>k]\"}\nand @{text\"drop k [x\\<^sub>1,\\<dots>] = [x\\<^bsub>k+1\\<^esub>,\\<dots>]\"}. Let sledgehammer find and apply\nthe relevant @{const take} and @{const drop} lemmas for you.\n\\endexercise\n\n\\exercise\nGive a structured proof by rule inversion:\n\\<close>\ninductive ev :: \"nat \\<Rightarrow> bool\" where\nev0: \"ev 0\" |\nevSS: \"ev n \\<Longrightarrow> ev(Suc(Suc n))\"\nlemma assumes a: \"ev(Suc(Suc n))\" shows \"ev n\"\n(* your definition/proof here *)\n\ntext\\<open>\n\\exercise\nGive a structured proof by rule inversions:\n\\<close>\n\nlemma \"\\<not> ev(Suc(Suc(Suc 0)))\"\n(* your definition/proof here *)\n\ntext\\<open>\nIf there are no cases to be proved you can close\na proof immediateley with \\isacom{qed}.\n\\endexercise\n\n\\exercise\nRecall predicate @{const star} from Section 4.5 and @{const iter}\nfrom Exercise~\\ref{exe:iter}.\n\\<close>\n\nlemma \"iter r n x y \\<Longrightarrow> star r x y\"\n(* your definition/proof here *)\n\ntext\\<open>\nProve this lemma in a structured style, do not just sledgehammer each case of the\nrequired induction.\n\\endexercise\n\n\\exercise\nDefine a recursive function\n\\<close>\n\nfun elems :: \"'a list \\<Rightarrow> 'a set\" where\n(* your definition/proof here *)\n\ntext\\<open> that collects all elements of a list into a set. Prove \\<close>\n\nlemma \"x \\<in> elems xs \\<Longrightarrow> \\<exists>ys zs. xs = ys @ x # zs \\<and> x \\<notin> elems ys\"\n(* your definition/proof here *)\n\ntext\\<open>\n\\endexercise\n\n\\exercise\nExtend Exercise~\\ref{exe:cfg} with a function that checks if some\n\\mbox{@{text \"alpha list\"}} is a balanced\nstring of parentheses. More precisely, define a recursive function \\<close>\n(* your definition/proof here *)\nfun balanced :: \"nat \\<Rightarrow> alpha list \\<Rightarrow> bool\" where\n(* your definition/proof here *)\n\ntext\\<open> such that @{term\"balanced n w\"}\nis true iff (informally) @{text\"a\\<^sup>n @ w \\<in> S\"}. Formally, prove \\<close>\n\ncorollary \"balanced n w \\<longleftrightarrow> S (replicate n a @ w)\"\n\n\ntext\\<open> where @{const replicate} @{text\"::\"} @{typ\"nat \\<Rightarrow> 'a \\<Rightarrow> 'a list\"} is predefined\nand @{term\"replicate n x\"} yields the list @{text\"[x, \\<dots>, x]\"} of length @{text n}.\n\\<close>\n\nend\n\n", "meta": {"author": "LuckyYZC", "repo": "-Exercises-of-the-Book-Concrete-semantics", "sha": "e67b3f263af302c454b0298cade9e04375fe96a6", "save_path": "github-repos/isabelle/LuckyYZC--Exercises-of-the-Book-Concrete-semantics", "path": "github-repos/isabelle/LuckyYZC--Exercises-of-the-Book-Concrete-semantics/-Exercises-of-the-Book-Concrete-semantics-e67b3f263af302c454b0298cade9e04375fe96a6/templates/Chapter5Guisen.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.853912760387131, "lm_q2_score": 0.8289388040954683, "lm_q1q2_score": 0.7078414223971685}}
{"text": "(*  Title:      HOL/Rat.thy\n    Author:     Markus Wenzel, TU Muenchen\n*)\n\nsection \\<open>Rational numbers\\<close>\n\ntheory Rat\n  imports GCD Archimedean_Field\nbegin\n\nsubsection \\<open>Rational numbers as quotient\\<close>\n\nsubsubsection \\<open>Construction of the type of rational numbers\\<close>\n\ndefinition ratrel :: \"(int \\<times> int) \\<Rightarrow> (int \\<times> int) \\<Rightarrow> bool\"\n  where \"ratrel = (\\<lambda>x y. snd x \\<noteq> 0 \\<and> snd y \\<noteq> 0 \\<and> fst x * snd y = fst y * snd x)\"\n\nlemma ratrel_iff [simp]: \"ratrel 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: ratrel_def)\n\nlemma exists_ratrel_refl: \"\\<exists>x. ratrel x x\"\n  by (auto intro!: one_neq_zero)\n\nlemma symp_ratrel: \"symp ratrel\"\n  by (simp add: ratrel_def symp_def)\n\nlemma transp_ratrel: \"transp ratrel\"\nproof (rule transpI, unfold split_paired_all)\n  fix a b a' b' a'' b'' :: int\n  assume *: \"ratrel (a, b) (a', b')\"\n  assume **: \"ratrel (a', b') (a'', b'')\"\n  have \"b' * (a * b'') = b'' * (a * b')\" by simp\n  also from * have \"a * b' = a' * b\" by auto\n  also have \"b'' * (a' * b) = b * (a' * b'')\" by simp\n  also from ** have \"a' * b'' = a'' * b'\" by auto\n  also have \"b * (a'' * b') = b' * (a'' * b)\" by simp\n  finally have \"b' * (a * b'') = b' * (a'' * b)\" .\n  moreover from ** have \"b' \\<noteq> 0\" by auto\n  ultimately have \"a * b'' = a'' * b\" by simp\n  with * ** show \"ratrel (a, b) (a'', b'')\" by auto\nqed\n\nlemma part_equivp_ratrel: \"part_equivp ratrel\"\n  by (rule part_equivpI [OF exists_ratrel_refl symp_ratrel transp_ratrel])\n\nquotient_type rat = \"int \\<times> int\" / partial: \"ratrel\"\n  morphisms Rep_Rat Abs_Rat\n  by (rule part_equivp_ratrel)\n\nlemma Domainp_cr_rat [transfer_domain_rule]: \"Domainp pcr_rat = (\\<lambda>x. snd x \\<noteq> 0)\"\n  by (simp add: rat.domain_eq)\n\n\nsubsubsection \\<open>Representation and basic operations\\<close>\n\nlift_definition Fract :: \"int \\<Rightarrow> int \\<Rightarrow> rat\"\n  is \"\\<lambda>a b. if b = 0 then (0, 1) else (a, b)\"\n  by simp\n\nlemma eq_rat:\n  \"\\<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>a. Fract a 0 = Fract 0 1\"\n  \"\\<And>a c. Fract 0 a = Fract 0 c\"\n  by (transfer, simp)+\n\nlemma Rat_cases [case_names Fract, cases type: rat]:\n  assumes that: \"\\<And>a b. q = Fract a b \\<Longrightarrow> b > 0 \\<Longrightarrow> coprime a b \\<Longrightarrow> C\"\n  shows C\nproof -\n  obtain a b :: int where q: \"q = Fract a b\" and b: \"b \\<noteq> 0\"\n    by transfer simp\n  let ?a = \"a div gcd a b\"\n  let ?b = \"b div gcd a b\"\n  from b have \"?b * gcd a b = b\"\n    by simp\n  with b have \"?b \\<noteq> 0\"\n    by fastforce\n  with q b have q2: \"q = Fract ?a ?b\"\n    by (simp add: eq_rat dvd_div_mult mult.commute [of a])\n  from b have coprime: \"coprime ?a ?b\"\n    by (auto intro: div_gcd_coprime)\n  show C\n  proof (cases \"b > 0\")\n    case True\n    then have \"?b > 0\"\n      by (simp add: nonneg1_imp_zdiv_pos_iff)\n    from q2 this coprime show C by (rule that)\n  next\n    case False\n    have \"q = Fract (- ?a) (- ?b)\"\n      unfolding q2 by transfer simp\n    moreover from False b have \"- ?b > 0\"\n      by (simp add: pos_imp_zdiv_neg_iff)\n    moreover from coprime have \"coprime (- ?a) (- ?b)\"\n      by simp\n    ultimately show C\n      by (rule that)\n  qed\nqed\n\nlemma Rat_induct [case_names Fract, induct type: rat]:\n  assumes \"\\<And>a b. b > 0 \\<Longrightarrow> coprime a b \\<Longrightarrow> P (Fract a b)\"\n  shows \"P q\"\n  using assms by (cases q) simp\n\ninstantiation rat :: field\nbegin\n\nlift_definition zero_rat :: \"rat\" is \"(0, 1)\"\n  by simp\n\nlift_definition one_rat :: \"rat\" is \"(1, 1)\"\n  by simp\n\nlemma Zero_rat_def: \"0 = Fract 0 1\"\n  by transfer simp\n\nlemma One_rat_def: \"1 = Fract 1 1\"\n  by transfer simp\n\nlift_definition plus_rat :: \"rat \\<Rightarrow> rat \\<Rightarrow> rat\"\n  is \"\\<lambda>x y. (fst x * snd y + fst y * snd x, snd x * snd y)\"\n  by (auto simp: distrib_right) (simp add: ac_simps)\n\nlemma add_rat [simp]:\n  assumes \"b \\<noteq> 0\" and \"d \\<noteq> 0\"\n  shows \"Fract a b + Fract c d = Fract (a * d + c * b) (b * d)\"\n  using assms by transfer simp\n\nlift_definition uminus_rat :: \"rat \\<Rightarrow> rat\" is \"\\<lambda>x. (- fst x, snd x)\"\n  by simp\n\nlemma minus_rat [simp]: \"- Fract a b = Fract (- a) b\"\n  by transfer simp\n\nlemma minus_rat_cancel [simp]: \"Fract (- a) (- b) = Fract a b\"\n  by (cases \"b = 0\") (simp_all add: eq_rat)\n\ndefinition diff_rat_def: \"q - r = q + - r\" for q r :: rat\n\nlemma diff_rat [simp]:\n  \"b \\<noteq> 0 \\<Longrightarrow> d \\<noteq> 0 \\<Longrightarrow> Fract a b - Fract c d = Fract (a * d - c * b) (b * d)\"\n  by (simp add: diff_rat_def)\n\nlift_definition times_rat :: \"rat \\<Rightarrow> rat \\<Rightarrow> rat\"\n  is \"\\<lambda>x y. (fst x * fst y, snd x * snd y)\"\n  by (simp add: ac_simps)\n\nlemma mult_rat [simp]: \"Fract a b * Fract c d = Fract (a * c) (b * d)\"\n  by transfer simp\n\nlemma mult_rat_cancel: \"c \\<noteq> 0 \\<Longrightarrow> Fract (c * a) (c * b) = Fract a b\"\n  by transfer simp\n\nlift_definition inverse_rat :: \"rat \\<Rightarrow> rat\"\n  is \"\\<lambda>x. if fst x = 0 then (0, 1) else (snd x, fst x)\"\n  by (auto simp add: mult.commute)\n\nlemma inverse_rat [simp]: \"inverse (Fract a b) = Fract b a\"\n  by transfer simp\n\ndefinition divide_rat_def: \"q div r = q * inverse r\" for q r :: rat\n\nlemma divide_rat [simp]: \"Fract a b div Fract c d = Fract (a * d) (b * c)\"\n  by (simp add: divide_rat_def)\n\ninstance\nproof\n  fix q r s :: rat\n  show \"(q * r) * s = q * (r * s)\"\n    by transfer simp\n  show \"q * r = r * q\"\n    by transfer simp\n  show \"1 * q = q\"\n    by transfer simp\n  show \"(q + r) + s = q + (r + s)\"\n    by transfer (simp add: algebra_simps)\n  show \"q + r = r + q\"\n    by transfer simp\n  show \"0 + q = q\"\n    by transfer simp\n  show \"- q + q = 0\"\n    by transfer simp\n  show \"q - r = q + - r\"\n    by (fact diff_rat_def)\n  show \"(q + r) * s = q * s + r * s\"\n    by transfer (simp add: algebra_simps)\n  show \"(0::rat) \\<noteq> 1\"\n    by transfer simp\n  show \"inverse q * q = 1\" if \"q \\<noteq> 0\"\n    using that by transfer simp\n  show \"q div r = q * inverse r\"\n    by (fact divide_rat_def)\n  show \"inverse 0 = (0::rat)\"\n    by transfer simp\nqed\n\nend\n\n(* We cannot state these two rules earlier because of pending sort hypotheses *)\nlemma div_add_self1_no_field [simp]:\n  assumes \"NO_MATCH (x :: 'b :: field) b\" \"(b :: 'a :: semiring_div) \\<noteq> 0\"\n  shows \"(b + a) div b = a div b + 1\"\n  using assms(2) by (fact div_add_self1)\n\nlemma div_add_self2_no_field [simp]:\n  assumes \"NO_MATCH (x :: 'b :: field) b\" \"(b :: 'a :: semiring_div) \\<noteq> 0\"\n  shows \"(a + b) div b = a div b + 1\"\n  using assms(2) by (fact div_add_self2)\n\nlemma of_nat_rat: \"of_nat k = Fract (of_nat k) 1\"\n  by (induct k) (simp_all add: Zero_rat_def One_rat_def)\n\nlemma of_int_rat: \"of_int k = Fract k 1\"\n  by (cases k rule: int_diff_cases) (simp add: of_nat_rat)\n\nlemma Fract_of_nat_eq: \"Fract (of_nat k) 1 = of_nat k\"\n  by (rule of_nat_rat [symmetric])\n\nlemma Fract_of_int_eq: \"Fract k 1 = of_int k\"\n  by (rule of_int_rat [symmetric])\n\nlemma rat_number_collapse:\n  \"Fract 0 k = 0\"\n  \"Fract 1 1 = 1\"\n  \"Fract (numeral w) 1 = numeral w\"\n  \"Fract (- numeral w) 1 = - numeral w\"\n  \"Fract (- 1) 1 = - 1\"\n  \"Fract k 0 = 0\"\n  using Fract_of_int_eq [of \"numeral w\"]\n    and Fract_of_int_eq [of \"- numeral w\"]\n  by (simp_all add: Zero_rat_def One_rat_def eq_rat)\n\nlemma rat_number_expand:\n  \"0 = Fract 0 1\"\n  \"1 = Fract 1 1\"\n  \"numeral k = Fract (numeral k) 1\"\n  \"- 1 = Fract (- 1) 1\"\n  \"- numeral k = Fract (- numeral k) 1\"\n  by (simp_all add: rat_number_collapse)\n\nlemma Rat_cases_nonzero [case_names Fract 0]:\n  assumes Fract: \"\\<And>a b. q = Fract a b \\<Longrightarrow> b > 0 \\<Longrightarrow> a \\<noteq> 0 \\<Longrightarrow> coprime a b \\<Longrightarrow> C\"\n    and 0: \"q = 0 \\<Longrightarrow> C\"\n  shows C\nproof (cases \"q = 0\")\n  case True\n  then show C using 0 by auto\nnext\n  case False\n  then obtain a b where *: \"q = Fract a b\" \"b > 0\" \"coprime a b\"\n    by (cases q) auto\n  with False have \"0 \\<noteq> Fract a b\"\n    by simp\n  with \\<open>b > 0\\<close> have \"a \\<noteq> 0\"\n    by (simp add: Zero_rat_def eq_rat)\n  with Fract * show C by blast\nqed\n\n\nsubsubsection \\<open>Function \\<open>normalize\\<close>\\<close>\n\nlemma Fract_coprime: \"Fract (a div gcd a b) (b div gcd a b) = Fract a b\"\nproof (cases \"b = 0\")\n  case True\n  then show ?thesis\n    by (simp add: eq_rat)\nnext\n  case False\n  moreover have \"b div gcd a b * gcd a b = b\"\n    by (rule dvd_div_mult_self) simp\n  ultimately have \"b div gcd a b * gcd a b \\<noteq> 0\"\n    by simp\n  then have \"b div gcd a b \\<noteq> 0\"\n    by fastforce\n  with False show ?thesis\n    by (simp add: eq_rat dvd_div_mult mult.commute [of a])\nqed\n\ndefinition normalize :: \"int \\<times> int \\<Rightarrow> int \\<times> int\"\n  where \"normalize p =\n   (if snd p > 0 then (let a = gcd (fst p) (snd p) in (fst p div a, snd p div a))\n    else if snd p = 0 then (0, 1)\n    else (let a = - gcd (fst p) (snd p) in (fst p div a, snd p div a)))\"\n\nlemma normalize_crossproduct:\n  assumes \"q \\<noteq> 0\" \"s \\<noteq> 0\"\n  assumes \"normalize (p, q) = normalize (r, s)\"\n  shows \"p * s = r * q\"\nproof -\n  have *: \"p * s = q * r\"\n    if \"p * gcd r s = sgn (q * s) * r * gcd p q\" and \"q * gcd r s = sgn (q * s) * s * gcd p q\"\n  proof -\n    from that have \"(p * gcd r s) * (sgn (q * s) * s * gcd p q) =\n        (q * gcd r s) * (sgn (q * s) * r * gcd p q)\"\n      by simp\n    with assms show ?thesis\n      by (auto simp add: ac_simps sgn_mult sgn_0_0)\n  qed\n  from assms show ?thesis\n    by (auto simp: normalize_def Let_def dvd_div_div_eq_mult mult.commute sgn_mult\n        split: if_splits intro: *)\nqed\n\nlemma normalize_eq: \"normalize (a, b) = (p, q) \\<Longrightarrow> Fract p q = Fract a b\"\n  by (auto simp: normalize_def Let_def Fract_coprime dvd_div_neg rat_number_collapse\n      split: if_split_asm)\n\nlemma normalize_denom_pos: \"normalize r = (p, q) \\<Longrightarrow> q > 0\"\n  by (auto simp: normalize_def Let_def dvd_div_neg pos_imp_zdiv_neg_iff nonneg1_imp_zdiv_pos_iff\n      split: if_split_asm)\n\nlemma normalize_coprime: \"normalize r = (p, q) \\<Longrightarrow> coprime p q\"\n  by (auto simp: normalize_def Let_def dvd_div_neg div_gcd_coprime split: if_split_asm)\n\nlemma normalize_stable [simp]: \"q > 0 \\<Longrightarrow> coprime p q \\<Longrightarrow> normalize (p, q) = (p, q)\"\n  by (simp add: normalize_def)\n\nlemma normalize_denom_zero [simp]: \"normalize (p, 0) = (0, 1)\"\n  by (simp add: normalize_def)\n\nlemma normalize_negative [simp]: \"q < 0 \\<Longrightarrow> normalize (p, q) = normalize (- p, - q)\"\n  by (simp add: normalize_def Let_def dvd_div_neg dvd_neg_div)\n\ntext\\<open>\n  Decompose a fraction into normalized, i.e. coprime numerator and denominator:\n\\<close>\n\ndefinition quotient_of :: \"rat \\<Rightarrow> int \\<times> int\"\n  where \"quotient_of x =\n    (THE pair. x = Fract (fst pair) (snd pair) \\<and> snd pair > 0 \\<and> coprime (fst pair) (snd pair))\"\n\nlemma quotient_of_unique: \"\\<exists>!p. r = Fract (fst p) (snd p) \\<and> snd p > 0 \\<and> coprime (fst p) (snd p)\"\nproof (cases r)\n  case (Fract a b)\n  then have \"r = Fract (fst (a, b)) (snd (a, b)) \\<and>\n      snd (a, b) > 0 \\<and> coprime (fst (a, b)) (snd (a, b))\"\n    by auto\n  then show ?thesis\n  proof (rule ex1I)\n    fix p\n    assume r: \"r = Fract (fst p) (snd p) \\<and> snd p > 0 \\<and> coprime (fst p) (snd p)\"\n    obtain c d where p: \"p = (c, d)\" by (cases p)\n    with r have Fract': \"r = Fract c d\" \"d > 0\" \"coprime c d\"\n      by simp_all\n    have \"(c, d) = (a, b)\"\n    proof (cases \"a = 0\")\n      case True\n      with Fract Fract' show ?thesis\n        by (simp add: eq_rat)\n    next\n      case False\n      with Fract Fract' have *: \"c * b = a * d\" and \"c \\<noteq> 0\"\n        by (auto simp add: eq_rat)\n      then have \"c * b > 0 \\<longleftrightarrow> a * d > 0\"\n        by auto\n      with \\<open>b > 0\\<close> \\<open>d > 0\\<close> have \"a > 0 \\<longleftrightarrow> c > 0\"\n        by (simp add: zero_less_mult_iff)\n      with \\<open>a \\<noteq> 0\\<close> \\<open>c \\<noteq> 0\\<close> have sgn: \"sgn a = sgn c\"\n        by (auto simp add: not_less)\n      from \\<open>coprime a b\\<close> \\<open>coprime c d\\<close> have \"\\<bar>a\\<bar> * \\<bar>d\\<bar> = \\<bar>c\\<bar> * \\<bar>b\\<bar> \\<longleftrightarrow> \\<bar>a\\<bar> = \\<bar>c\\<bar> \\<and> \\<bar>d\\<bar> = \\<bar>b\\<bar>\"\n        by (simp add: coprime_crossproduct_int)\n      with \\<open>b > 0\\<close> \\<open>d > 0\\<close> have \"\\<bar>a\\<bar> * d = \\<bar>c\\<bar> * b \\<longleftrightarrow> \\<bar>a\\<bar> = \\<bar>c\\<bar> \\<and> d = b\"\n        by simp\n      then have \"a * sgn a * d = c * sgn c * b \\<longleftrightarrow> a * sgn a = c * sgn c \\<and> d = b\"\n        by (simp add: abs_sgn)\n      with sgn * show ?thesis\n        by (auto simp add: sgn_0_0)\n    qed\n    with p show \"p = (a, b)\"\n      by simp\n  qed\nqed\n\nlemma quotient_of_Fract [code]: \"quotient_of (Fract a b) = normalize (a, b)\"\nproof -\n  have \"Fract a b = Fract (fst (normalize (a, b))) (snd (normalize (a, b)))\" (is ?Fract)\n    by (rule sym) (auto intro: normalize_eq)\n  moreover have \"0 < snd (normalize (a, b))\" (is ?denom_pos)\n    by (cases \"normalize (a, b)\") (rule normalize_denom_pos, simp)\n  moreover have \"coprime (fst (normalize (a, b))) (snd (normalize (a, b)))\" (is ?coprime)\n    by (rule normalize_coprime) simp\n  ultimately have \"?Fract \\<and> ?denom_pos \\<and> ?coprime\" by blast\n  then have \"(THE p. Fract a b = Fract (fst p) (snd p) \\<and> 0 < snd p \\<and>\n    coprime (fst p) (snd p)) = normalize (a, b)\"\n    by (rule the1_equality [OF quotient_of_unique])\n  then show ?thesis by (simp add: quotient_of_def)\nqed\n\nlemma quotient_of_number [simp]:\n  \"quotient_of 0 = (0, 1)\"\n  \"quotient_of 1 = (1, 1)\"\n  \"quotient_of (numeral k) = (numeral k, 1)\"\n  \"quotient_of (- 1) = (- 1, 1)\"\n  \"quotient_of (- numeral k) = (- numeral k, 1)\"\n  by (simp_all add: rat_number_expand quotient_of_Fract)\n\nlemma quotient_of_eq: \"quotient_of (Fract a b) = (p, q) \\<Longrightarrow> Fract p q = Fract a b\"\n  by (simp add: quotient_of_Fract normalize_eq)\n\nlemma quotient_of_denom_pos: \"quotient_of r = (p, q) \\<Longrightarrow> q > 0\"\n  by (cases r) (simp add: quotient_of_Fract normalize_denom_pos)\n\nlemma quotient_of_coprime: \"quotient_of r = (p, q) \\<Longrightarrow> coprime p q\"\n  by (cases r) (simp add: quotient_of_Fract normalize_coprime)\n\nlemma quotient_of_inject:\n  assumes \"quotient_of a = quotient_of b\"\n  shows \"a = b\"\nproof -\n  obtain p q r s where a: \"a = Fract p q\" and b: \"b = Fract r s\" and \"q > 0\" and \"s > 0\"\n    by (cases a, cases b)\n  with assms show ?thesis\n    by (simp add: eq_rat quotient_of_Fract normalize_crossproduct)\nqed\n\nlemma quotient_of_inject_eq: \"quotient_of a = quotient_of b \\<longleftrightarrow> a = b\"\n  by (auto simp add: quotient_of_inject)\n\n\nsubsubsection \\<open>Various\\<close>\n\nlemma Fract_of_int_quotient: \"Fract k l = of_int k / of_int l\"\n  by (simp add: Fract_of_int_eq [symmetric])\n\nlemma Fract_add_one: \"n \\<noteq> 0 \\<Longrightarrow> Fract (m + n) n = Fract m n + 1\"\n  by (simp add: rat_number_expand)\n\nlemma quotient_of_div:\n  assumes r: \"quotient_of r = (n,d)\"\n  shows \"r = of_int n / of_int d\"\nproof -\n  from theI'[OF quotient_of_unique[of r], unfolded r[unfolded quotient_of_def]]\n  have \"r = Fract n d\" by simp\n  then show ?thesis using Fract_of_int_quotient\n    by simp\nqed\n\n\nsubsubsection \\<open>The ordered field of rational numbers\\<close>\n\nlift_definition positive :: \"rat \\<Rightarrow> bool\"\n  is \"\\<lambda>x. 0 < fst x * snd x\"\nproof clarsimp\n  fix a b c d :: int\n  assume \"b \\<noteq> 0\" and \"d \\<noteq> 0\" and \"a * d = c * b\"\n  then have \"a * d * b * d = c * b * b * d\"\n    by simp\n  then have \"a * b * d\\<^sup>2 = c * d * b\\<^sup>2\"\n    unfolding power2_eq_square by (simp add: ac_simps)\n  then have \"0 < a * b * d\\<^sup>2 \\<longleftrightarrow> 0 < c * d * b\\<^sup>2\"\n    by simp\n  then show \"0 < a * b \\<longleftrightarrow> 0 < c * d\"\n    using \\<open>b \\<noteq> 0\\<close> and \\<open>d \\<noteq> 0\\<close>\n    by (simp add: zero_less_mult_iff)\nqed\n\nlemma positive_zero: \"\\<not> positive 0\"\n  by transfer simp\n\nlemma positive_add: \"positive x \\<Longrightarrow> positive y \\<Longrightarrow> positive (x + y)\"\n  apply transfer\n  apply (simp add: zero_less_mult_iff)\n  apply (elim disjE)\n     apply (simp_all add: add_pos_pos add_neg_neg mult_pos_neg mult_neg_pos mult_neg_neg)\n  done\n\nlemma positive_mult: \"positive x \\<Longrightarrow> positive y \\<Longrightarrow> positive (x * y)\"\n  apply transfer\n  apply (drule (1) mult_pos_pos)\n  apply (simp add: ac_simps)\n  done\n\nlemma positive_minus: \"\\<not> positive x \\<Longrightarrow> x \\<noteq> 0 \\<Longrightarrow> positive (- x)\"\n  by transfer (auto simp: neq_iff zero_less_mult_iff mult_less_0_iff)\n\ninstantiation rat :: linordered_field\nbegin\n\ndefinition \"x < y \\<longleftrightarrow> positive (y - x)\"\n\ndefinition \"x \\<le> y \\<longleftrightarrow> x < y \\<or> x = y\" for x y :: rat\n\ndefinition \"\\<bar>a\\<bar> = (if a < 0 then - a else a)\" for a :: rat\n\ndefinition \"sgn a = (if a = 0 then 0 else if 0 < a then 1 else - 1)\" for a :: rat\n\ninstance\nproof\n  fix a b c :: rat\n  show \"\\<bar>a\\<bar> = (if a < 0 then - a else a)\"\n    by (rule abs_rat_def)\n  show \"a < b \\<longleftrightarrow> a \\<le> b \\<and> \\<not> b \\<le> a\"\n    unfolding less_eq_rat_def less_rat_def\n    apply auto\n     apply (drule (1) positive_add)\n     apply (simp_all add: positive_zero)\n    done\n  show \"a \\<le> a\"\n    unfolding less_eq_rat_def by simp\n  show \"a \\<le> b \\<Longrightarrow> b \\<le> c \\<Longrightarrow> a \\<le> c\"\n    unfolding less_eq_rat_def less_rat_def\n    apply auto\n    apply (drule (1) positive_add)\n    apply (simp add: algebra_simps)\n    done\n  show \"a \\<le> b \\<Longrightarrow> b \\<le> a \\<Longrightarrow> a = b\"\n    unfolding less_eq_rat_def less_rat_def\n    apply auto\n    apply (drule (1) positive_add)\n    apply (simp add: positive_zero)\n    done\n  show \"a \\<le> b \\<Longrightarrow> c + a \\<le> c + b\"\n    unfolding less_eq_rat_def less_rat_def by auto\n  show \"sgn a = (if a = 0 then 0 else if 0 < a then 1 else - 1)\"\n    by (rule sgn_rat_def)\n  show \"a \\<le> b \\<or> b \\<le> a\"\n    unfolding less_eq_rat_def less_rat_def\n    by (auto dest!: positive_minus)\n  show \"a < b \\<Longrightarrow> 0 < c \\<Longrightarrow> c * a < c * b\"\n    unfolding less_rat_def\n    apply (drule (1) positive_mult)\n    apply (simp add: algebra_simps)\n    done\nqed\n\nend\n\ninstantiation rat :: distrib_lattice\nbegin\n\ndefinition \"(inf :: rat \\<Rightarrow> rat \\<Rightarrow> rat) = min\"\n\ndefinition \"(sup :: rat \\<Rightarrow> rat \\<Rightarrow> rat) = max\"\n\ninstance\n  by standard (auto simp add: inf_rat_def sup_rat_def max_min_distrib2)\n\nend\n\nlemma positive_rat: \"positive (Fract a b) \\<longleftrightarrow> 0 < a * b\"\n  by transfer simp\n\nlemma less_rat [simp]:\n  \"b \\<noteq> 0 \\<Longrightarrow> d \\<noteq> 0 \\<Longrightarrow> Fract a b < Fract c d \\<longleftrightarrow> (a * d) * (b * d) < (c * b) * (b * d)\"\n  by (simp add: less_rat_def positive_rat algebra_simps)\n\nlemma le_rat [simp]:\n  \"b \\<noteq> 0 \\<Longrightarrow> d \\<noteq> 0 \\<Longrightarrow> Fract a b \\<le> Fract c d \\<longleftrightarrow> (a * d) * (b * d) \\<le> (c * b) * (b * d)\"\n  by (simp add: le_less eq_rat)\n\nlemma abs_rat [simp, code]: \"\\<bar>Fract a b\\<bar> = Fract \\<bar>a\\<bar> \\<bar>b\\<bar>\"\n  by (auto simp add: abs_rat_def zabs_def Zero_rat_def not_less le_less eq_rat zero_less_mult_iff)\n\nlemma sgn_rat [simp, code]: \"sgn (Fract a b) = of_int (sgn a * sgn b)\"\n  unfolding Fract_of_int_eq\n  by (auto simp: zsgn_def sgn_rat_def Zero_rat_def eq_rat)\n    (auto simp: rat_number_collapse not_less le_less zero_less_mult_iff)\n\nlemma Rat_induct_pos [case_names Fract, induct type: rat]:\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  have step': \"P (Fract a b)\" if b: \"b < 0\" for a b :: int\n  proof -\n    from b have \"0 < - b\"\n      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  from Fract show \"P q\"\n    by (auto simp add: linorder_neq_iff step step')\nqed\n\nlemma zero_less_Fract_iff: \"0 < b \\<Longrightarrow> 0 < Fract a b \\<longleftrightarrow> 0 < a\"\n  by (simp add: Zero_rat_def zero_less_mult_iff)\n\nlemma Fract_less_zero_iff: \"0 < b \\<Longrightarrow> Fract a b < 0 \\<longleftrightarrow> a < 0\"\n  by (simp add: Zero_rat_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 (simp add: Zero_rat_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 (simp add: Zero_rat_def mult_le_0_iff)\n\nlemma one_less_Fract_iff: \"0 < b \\<Longrightarrow> 1 < Fract a b \\<longleftrightarrow> b < a\"\n  by (simp add: One_rat_def mult_less_cancel_right_disj)\n\nlemma Fract_less_one_iff: \"0 < b \\<Longrightarrow> Fract a b < 1 \\<longleftrightarrow> a < b\"\n  by (simp add: One_rat_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 (simp add: One_rat_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 (simp add: One_rat_def mult_le_cancel_right)\n\n\nsubsubsection \\<open>Rationals are an Archimedean field\\<close>\n\nlemma rat_floor_lemma: \"of_int (a div b) \\<le> Fract a b \\<and> Fract a b < of_int (a div b + 1)\"\nproof -\n  have \"Fract a b = of_int (a div b) + Fract (a mod b) b\"\n    by (cases \"b = 0\") (simp, simp add: of_int_rat)\n  moreover have \"0 \\<le> Fract (a mod b) b \\<and> Fract (a mod b) b < 1\"\n    unfolding Fract_of_int_quotient\n    by (rule linorder_cases [of b 0]) (simp_all add: divide_nonpos_neg)\n  ultimately show ?thesis by simp\nqed\n\ninstance rat :: archimedean_field\nproof\n  show \"\\<exists>z. r \\<le> of_int z\" for r :: rat\n  proof (induct r)\n    case (Fract a b)\n    have \"Fract a b \\<le> of_int (a div b + 1)\"\n      using rat_floor_lemma [of a b] by simp\n    then show \"\\<exists>z. Fract a b \\<le> of_int z\" ..\n  qed\nqed\n\ninstantiation rat :: floor_ceiling\nbegin\n\ndefinition [code del]: \"\\<lfloor>x\\<rfloor> = (THE z. of_int z \\<le> x \\<and> x < of_int (z + 1))\" for x :: rat\n\ninstance\nproof\n  show \"of_int \\<lfloor>x\\<rfloor> \\<le> x \\<and> x < of_int (\\<lfloor>x\\<rfloor> + 1)\" for x :: rat\n    unfolding floor_rat_def using floor_exists1 by (rule theI')\nqed\n\nend\n\nlemma floor_Fract: \"\\<lfloor>Fract a b\\<rfloor> = a div b\"\n  by (simp add: Fract_of_int_quotient floor_divide_of_int_eq)\n\n\nsubsection \\<open>Linear arithmetic setup\\<close>\n\ndeclaration \\<open>\n  K (Lin_Arith.add_inj_thms [@{thm of_nat_le_iff} RS iffD2, @{thm of_nat_eq_iff} RS iffD2]\n    (* not needed because x < (y::nat) can be rewritten as Suc x <= y: of_nat_less_iff RS iffD2 *)\n  #> Lin_Arith.add_inj_thms [@{thm of_int_le_iff} RS iffD2, @{thm of_int_eq_iff} RS iffD2]\n    (* not needed because x < (y::int) can be rewritten as x + 1 <= y: of_int_less_iff RS iffD2 *)\n  #> Lin_Arith.add_simps [@{thm neg_less_iff_less},\n      @{thm True_implies_equals},\n      @{thm distrib_left [where a = \"numeral v\" for v]},\n      @{thm distrib_left [where a = \"- numeral v\" for v]},\n      @{thm div_by_1}, @{thm div_0},\n      @{thm times_divide_eq_right}, @{thm times_divide_eq_left},\n      @{thm minus_divide_left} RS sym, @{thm minus_divide_right} RS sym,\n      @{thm add_divide_distrib}, @{thm diff_divide_distrib},\n      @{thm of_int_minus}, @{thm of_int_diff},\n      @{thm of_int_of_nat_eq}]\n  #> Lin_Arith.add_simprocs [Numeral_Simprocs.field_divide_cancel_numeral_factor]\n  #> Lin_Arith.add_inj_const (@{const_name of_nat}, @{typ \"nat \\<Rightarrow> rat\"})\n  #> Lin_Arith.add_inj_const (@{const_name of_int}, @{typ \"int \\<Rightarrow> rat\"}))\n\\<close>\n\n\nsubsection \\<open>Embedding from Rationals to other Fields\\<close>\n\ncontext field_char_0\nbegin\n\nlift_definition of_rat :: \"rat \\<Rightarrow> 'a\"\n  is \"\\<lambda>x. of_int (fst x) / of_int (snd x)\"\n  by (auto simp: nonzero_divide_eq_eq nonzero_eq_divide_eq) (simp only: of_int_mult [symmetric])\n\nend\n\nlemma of_rat_rat: \"b \\<noteq> 0 \\<Longrightarrow> of_rat (Fract a b) = of_int a / of_int b\"\n  by transfer simp\n\nlemma of_rat_0 [simp]: \"of_rat 0 = 0\"\n  by transfer simp\n\nlemma of_rat_1 [simp]: \"of_rat 1 = 1\"\n  by transfer simp\n\nlemma of_rat_add: \"of_rat (a + b) = of_rat a + of_rat b\"\n  by transfer (simp add: add_frac_eq)\n\nlemma of_rat_minus: \"of_rat (- a) = - of_rat a\"\n  by transfer simp\n\nlemma of_rat_neg_one [simp]: \"of_rat (- 1) = - 1\"\n  by (simp add: of_rat_minus)\n\nlemma of_rat_diff: \"of_rat (a - b) = of_rat a - of_rat b\"\n  using of_rat_add [of a \"- b\"] by (simp add: of_rat_minus)\n\nlemma of_rat_mult: \"of_rat (a * b) = of_rat a * of_rat b\"\n  by transfer (simp add: divide_inverse nonzero_inverse_mult_distrib ac_simps)\n\nlemma of_rat_sum: \"of_rat (\\<Sum>a\\<in>A. f a) = (\\<Sum>a\\<in>A. of_rat (f a))\"\n  by (induct rule: infinite_finite_induct) (auto simp: of_rat_add)\n\nlemma of_rat_prod: \"of_rat (\\<Prod>a\\<in>A. f a) = (\\<Prod>a\\<in>A. of_rat (f a))\"\n  by (induct rule: infinite_finite_induct) (auto simp: of_rat_mult)\n\nlemma nonzero_of_rat_inverse: \"a \\<noteq> 0 \\<Longrightarrow> of_rat (inverse a) = inverse (of_rat a)\"\n  by (rule inverse_unique [symmetric]) (simp add: of_rat_mult [symmetric])\n\nlemma of_rat_inverse: \"(of_rat (inverse a) :: 'a::{field_char_0,field}) = inverse (of_rat a)\"\n  by (cases \"a = 0\") (simp_all add: nonzero_of_rat_inverse)\n\nlemma nonzero_of_rat_divide: \"b \\<noteq> 0 \\<Longrightarrow> of_rat (a / b) = of_rat a / of_rat b\"\n  by (simp add: divide_inverse of_rat_mult nonzero_of_rat_inverse)\n\nlemma of_rat_divide: \"(of_rat (a / b) :: 'a::{field_char_0,field}) = of_rat a / of_rat b\"\n  by (cases \"b = 0\") (simp_all add: nonzero_of_rat_divide)\n\nlemma of_rat_power: \"(of_rat (a ^ n) :: 'a::field_char_0) = of_rat a ^ n\"\n  by (induct n) (simp_all add: of_rat_mult)\n\nlemma of_rat_eq_iff [simp]: \"of_rat a = of_rat b \\<longleftrightarrow> a = b\"\n  apply transfer\n  apply (simp add: nonzero_divide_eq_eq nonzero_eq_divide_eq)\n  apply (simp only: of_int_mult [symmetric] of_int_eq_iff)\n  done\n\nlemma of_rat_eq_0_iff [simp]: \"of_rat a = 0 \\<longleftrightarrow> a = 0\"\n  using of_rat_eq_iff [of _ 0] by simp\n\nlemma zero_eq_of_rat_iff [simp]: \"0 = of_rat a \\<longleftrightarrow> 0 = a\"\n  by simp\n\nlemma of_rat_eq_1_iff [simp]: \"of_rat a = 1 \\<longleftrightarrow> a = 1\"\n  using of_rat_eq_iff [of _ 1] by simp\n\nlemma one_eq_of_rat_iff [simp]: \"1 = of_rat a \\<longleftrightarrow> 1 = a\"\n  by simp\n\nlemma of_rat_less: \"(of_rat r :: 'a::linordered_field) < of_rat s \\<longleftrightarrow> r < s\"\nproof (induct r, induct s)\n  fix a b c d :: int\n  assume not_zero: \"b > 0\" \"d > 0\"\n  then have \"b * d > 0\" by simp\n  have of_int_divide_less_eq:\n    \"(of_int a :: 'a) / of_int b < of_int c / of_int d \\<longleftrightarrow>\n      (of_int a :: 'a) * of_int d < of_int c * of_int b\"\n    using not_zero by (simp add: pos_less_divide_eq pos_divide_less_eq)\n  show \"(of_rat (Fract a b) :: 'a::linordered_field) < of_rat (Fract c d) \\<longleftrightarrow>\n      Fract a b < Fract c d\"\n    using not_zero \\<open>b * d > 0\\<close>\n    by (simp add: of_rat_rat of_int_divide_less_eq of_int_mult [symmetric] del: of_int_mult)\nqed\n\nlemma of_rat_less_eq: \"(of_rat r :: 'a::linordered_field) \\<le> of_rat s \\<longleftrightarrow> r \\<le> s\"\n  unfolding le_less by (auto simp add: of_rat_less)\n\nlemma of_rat_le_0_iff [simp]: \"(of_rat r :: 'a::linordered_field) \\<le> 0 \\<longleftrightarrow> r \\<le> 0\"\n  using of_rat_less_eq [of r 0, where 'a = 'a] by simp\n\nlemma zero_le_of_rat_iff [simp]: \"0 \\<le> (of_rat r :: 'a::linordered_field) \\<longleftrightarrow> 0 \\<le> r\"\n  using of_rat_less_eq [of 0 r, where 'a = 'a] by simp\n\nlemma of_rat_le_1_iff [simp]: \"(of_rat r :: 'a::linordered_field) \\<le> 1 \\<longleftrightarrow> r \\<le> 1\"\n  using of_rat_less_eq [of r 1] by simp\n\nlemma one_le_of_rat_iff [simp]: \"1 \\<le> (of_rat r :: 'a::linordered_field) \\<longleftrightarrow> 1 \\<le> r\"\n  using of_rat_less_eq [of 1 r] by simp\n\nlemma of_rat_less_0_iff [simp]: \"(of_rat r :: 'a::linordered_field) < 0 \\<longleftrightarrow> r < 0\"\n  using of_rat_less [of r 0, where 'a = 'a] by simp\n\nlemma zero_less_of_rat_iff [simp]: \"0 < (of_rat r :: 'a::linordered_field) \\<longleftrightarrow> 0 < r\"\n  using of_rat_less [of 0 r, where 'a = 'a] by simp\n\nlemma of_rat_less_1_iff [simp]: \"(of_rat r :: 'a::linordered_field) < 1 \\<longleftrightarrow> r < 1\"\n  using of_rat_less [of r 1] by simp\n\nlemma one_less_of_rat_iff [simp]: \"1 < (of_rat r :: 'a::linordered_field) \\<longleftrightarrow> 1 < r\"\n  using of_rat_less [of 1 r] by simp\n\nlemma of_rat_eq_id [simp]: \"of_rat = id\"\nproof\n  show \"of_rat a = id a\" for a\n    by (induct a) (simp add: of_rat_rat Fract_of_int_eq [symmetric])\nqed\n\ntext \\<open>Collapse nested embeddings.\\<close>\nlemma of_rat_of_nat_eq [simp]: \"of_rat (of_nat n) = of_nat n\"\n  by (induct n) (simp_all add: of_rat_add)\n\nlemma of_rat_of_int_eq [simp]: \"of_rat (of_int z) = of_int z\"\n  by (cases z rule: int_diff_cases) (simp add: of_rat_diff)\n\nlemma of_rat_numeral_eq [simp]: \"of_rat (numeral w) = numeral w\"\n  using of_rat_of_int_eq [of \"numeral w\"] by simp\n\nlemma of_rat_neg_numeral_eq [simp]: \"of_rat (- numeral w) = - numeral w\"\n  using of_rat_of_int_eq [of \"- numeral w\"] by simp\n\nlemmas zero_rat = Zero_rat_def\nlemmas one_rat = One_rat_def\n\nabbreviation rat_of_nat :: \"nat \\<Rightarrow> rat\"\n  where \"rat_of_nat \\<equiv> of_nat\"\n\nabbreviation rat_of_int :: \"int \\<Rightarrow> rat\"\n  where \"rat_of_int \\<equiv> of_int\"\n\n\nsubsection \\<open>The Set of Rational Numbers\\<close>\n\ncontext field_char_0\nbegin\n\ndefinition Rats :: \"'a set\" (\"\\<rat>\")\n  where \"\\<rat> = range of_rat\"\n\nend\n\nlemma Rats_of_rat [simp]: \"of_rat r \\<in> \\<rat>\"\n  by (simp add: Rats_def)\n\nlemma Rats_of_int [simp]: \"of_int z \\<in> \\<rat>\"\n  by (subst of_rat_of_int_eq [symmetric]) (rule Rats_of_rat)\n\nlemma Rats_of_nat [simp]: \"of_nat n \\<in> \\<rat>\"\n  by (subst of_rat_of_nat_eq [symmetric]) (rule Rats_of_rat)\n\nlemma Rats_number_of [simp]: \"numeral w \\<in> \\<rat>\"\n  by (subst of_rat_numeral_eq [symmetric]) (rule Rats_of_rat)\n\nlemma Rats_0 [simp]: \"0 \\<in> \\<rat>\"\n  unfolding Rats_def by (rule range_eqI) (rule of_rat_0 [symmetric])\n\nlemma Rats_1 [simp]: \"1 \\<in> \\<rat>\"\n  unfolding Rats_def by (rule range_eqI) (rule of_rat_1 [symmetric])\n\nlemma Rats_add [simp]: \"a \\<in> \\<rat> \\<Longrightarrow> b \\<in> \\<rat> \\<Longrightarrow> a + b \\<in> \\<rat>\"\n  apply (auto simp add: Rats_def)\n  apply (rule range_eqI)\n  apply (rule of_rat_add [symmetric])\n  done\n\nlemma Rats_minus [simp]: \"a \\<in> \\<rat> \\<Longrightarrow> - a \\<in> \\<rat>\"\n  apply (auto simp add: Rats_def)\n  apply (rule range_eqI)\n  apply (rule of_rat_minus [symmetric])\n  done\n\nlemma Rats_diff [simp]: \"a \\<in> \\<rat> \\<Longrightarrow> b \\<in> \\<rat> \\<Longrightarrow> a - b \\<in> \\<rat>\"\n  apply (auto simp add: Rats_def)\n  apply (rule range_eqI)\n  apply (rule of_rat_diff [symmetric])\n  done\n\nlemma Rats_mult [simp]: \"a \\<in> \\<rat> \\<Longrightarrow> b \\<in> \\<rat> \\<Longrightarrow> a * b \\<in> \\<rat>\"\n  apply (auto simp add: Rats_def)\n  apply (rule range_eqI)\n  apply (rule of_rat_mult [symmetric])\n  done\n\nlemma nonzero_Rats_inverse: \"a \\<in> \\<rat> \\<Longrightarrow> a \\<noteq> 0 \\<Longrightarrow> inverse a \\<in> \\<rat>\"\n  for a :: \"'a::field_char_0\"\n  apply (auto simp add: Rats_def)\n  apply (rule range_eqI)\n  apply (erule nonzero_of_rat_inverse [symmetric])\n  done\n\nlemma Rats_inverse [simp]: \"a \\<in> \\<rat> \\<Longrightarrow> inverse a \\<in> \\<rat>\"\n  for a :: \"'a::{field_char_0,field}\"\n  apply (auto simp add: Rats_def)\n  apply (rule range_eqI)\n  apply (rule of_rat_inverse [symmetric])\n  done\n\nlemma nonzero_Rats_divide: \"a \\<in> \\<rat> \\<Longrightarrow> b \\<in> \\<rat> \\<Longrightarrow> b \\<noteq> 0 \\<Longrightarrow> a / b \\<in> \\<rat>\"\n  for a b :: \"'a::field_char_0\"\n  apply (auto simp add: Rats_def)\n  apply (rule range_eqI)\n  apply (erule nonzero_of_rat_divide [symmetric])\n  done\n\nlemma Rats_divide [simp]: \"a \\<in> \\<rat> \\<Longrightarrow> b \\<in> \\<rat> \\<Longrightarrow> a / b \\<in> \\<rat>\"\n  for a b :: \"'a::{field_char_0, field}\"\n  apply (auto simp add: Rats_def)\n  apply (rule range_eqI)\n  apply (rule of_rat_divide [symmetric])\n  done\n\nlemma Rats_power [simp]: \"a \\<in> \\<rat> \\<Longrightarrow> a ^ n \\<in> \\<rat>\"\n  for a :: \"'a::field_char_0\"\n  apply (auto simp add: Rats_def)\n  apply (rule range_eqI)\n  apply (rule of_rat_power [symmetric])\n  done\n\nlemma Rats_cases [cases set: Rats]:\n  assumes \"q \\<in> \\<rat>\"\n  obtains (of_rat) r where \"q = of_rat r\"\nproof -\n  from \\<open>q \\<in> \\<rat>\\<close> have \"q \\<in> range of_rat\"\n    by (simp only: Rats_def)\n  then obtain r where \"q = of_rat r\" ..\n  then show thesis ..\nqed\n\nlemma Rats_induct [case_names of_rat, induct set: Rats]: \"q \\<in> \\<rat> \\<Longrightarrow> (\\<And>r. P (of_rat r)) \\<Longrightarrow> P q\"\n  by (rule Rats_cases) auto\n\nlemma Rats_infinite: \"\\<not> finite \\<rat>\"\n  by (auto dest!: finite_imageD simp: inj_on_def infinite_UNIV_char_0 Rats_def)\n\n\nsubsection \\<open>Implementation of rational numbers as pairs of integers\\<close>\n\ntext \\<open>Formal constructor\\<close>\n\ndefinition Frct :: \"int \\<times> int \\<Rightarrow> rat\"\n  where [simp]: \"Frct p = Fract (fst p) (snd p)\"\n\nlemma [code abstype]: \"Frct (quotient_of q) = q\"\n  by (cases q) (auto intro: quotient_of_eq)\n\n\ntext \\<open>Numerals\\<close>\n\ndeclare quotient_of_Fract [code abstract]\n\ndefinition of_int :: \"int \\<Rightarrow> rat\"\n  where [code_abbrev]: \"of_int = Int.of_int\"\n\nhide_const (open) of_int\n\nlemma quotient_of_int [code abstract]: \"quotient_of (Rat.of_int a) = (a, 1)\"\n  by (simp add: of_int_def of_int_rat quotient_of_Fract)\n\nlemma [code_unfold]: \"numeral k = Rat.of_int (numeral k)\"\n  by (simp add: Rat.of_int_def)\n\nlemma [code_unfold]: \"- numeral k = Rat.of_int (- numeral k)\"\n  by (simp add: Rat.of_int_def)\n\nlemma Frct_code_post [code_post]:\n  \"Frct (0, a) = 0\"\n  \"Frct (a, 0) = 0\"\n  \"Frct (1, 1) = 1\"\n  \"Frct (numeral k, 1) = numeral k\"\n  \"Frct (1, numeral k) = 1 / numeral k\"\n  \"Frct (numeral k, numeral l) = numeral k / numeral l\"\n  \"Frct (- a, b) = - Frct (a, b)\"\n  \"Frct (a, - b) = - Frct (a, b)\"\n  \"- (- Frct q) = Frct q\"\n  by (simp_all add: Fract_of_int_quotient)\n\n\ntext \\<open>Operations\\<close>\n\nlemma rat_zero_code [code abstract]: \"quotient_of 0 = (0, 1)\"\n  by (simp add: Zero_rat_def quotient_of_Fract normalize_def)\n\nlemma rat_one_code [code abstract]: \"quotient_of 1 = (1, 1)\"\n  by (simp add: One_rat_def quotient_of_Fract normalize_def)\n\nlemma rat_plus_code [code abstract]:\n  \"quotient_of (p + q) = (let (a, c) = quotient_of p; (b, d) = quotient_of q\n     in normalize (a * d + b * c, c * d))\"\n  by (cases p, cases q) (simp add: quotient_of_Fract)\n\nlemma rat_uminus_code [code abstract]:\n  \"quotient_of (- p) = (let (a, b) = quotient_of p in (- a, b))\"\n  by (cases p) (simp add: quotient_of_Fract)\n\nlemma rat_minus_code [code abstract]:\n  \"quotient_of (p - q) =\n    (let (a, c) = quotient_of p; (b, d) = quotient_of q\n     in normalize (a * d - b * c, c * d))\"\n  by (cases p, cases q) (simp add: quotient_of_Fract)\n\nlemma rat_times_code [code abstract]:\n  \"quotient_of (p * q) =\n    (let (a, c) = quotient_of p; (b, d) = quotient_of q\n     in normalize (a * b, c * d))\"\n  by (cases p, cases q) (simp add: quotient_of_Fract)\n\nlemma rat_inverse_code [code abstract]:\n  \"quotient_of (inverse p) =\n    (let (a, b) = quotient_of p\n     in if a = 0 then (0, 1) else (sgn a * b, \\<bar>a\\<bar>))\"\nproof (cases p)\n  case (Fract a b)\n  then show ?thesis\n    by (cases \"0::int\" a rule: linorder_cases) (simp_all add: quotient_of_Fract gcd.commute)\nqed\n\nlemma rat_divide_code [code abstract]:\n  \"quotient_of (p / q) =\n    (let (a, c) = quotient_of p; (b, d) = quotient_of q\n     in normalize (a * d, c * b))\"\n  by (cases p, cases q) (simp add: quotient_of_Fract)\n\nlemma rat_abs_code [code abstract]: \"quotient_of \\<bar>p\\<bar> = (let (a, b) = quotient_of p in (\\<bar>a\\<bar>, b))\"\n  by (cases p) (simp add: quotient_of_Fract)\n\nlemma rat_sgn_code [code abstract]: \"quotient_of (sgn p) = (sgn (fst (quotient_of p)), 1)\"\nproof (cases p)\n  case (Fract a b)\n  then show ?thesis\n    by (cases \"0::int\" a rule: linorder_cases) (simp_all add: quotient_of_Fract)\nqed\n\nlemma rat_floor_code [code]: \"\\<lfloor>p\\<rfloor> = (let (a, b) = quotient_of p in a div b)\"\n  by (cases p) (simp add: quotient_of_Fract floor_Fract)\n\ninstantiation rat :: equal\nbegin\n\ndefinition [code]: \"HOL.equal a b \\<longleftrightarrow> quotient_of a = quotient_of b\"\n\ninstance\n  by standard (simp add: equal_rat_def quotient_of_inject_eq)\n\nlemma rat_eq_refl [code nbe]: \"HOL.equal (r::rat) r \\<longleftrightarrow> True\"\n  by (rule equal_refl)\n\nend\n\nlemma rat_less_eq_code [code]:\n  \"p \\<le> q \\<longleftrightarrow> (let (a, c) = quotient_of p; (b, d) = quotient_of q in a * d \\<le> c * b)\"\n  by (cases p, cases q) (simp add: quotient_of_Fract mult.commute)\n\nlemma rat_less_code [code]:\n  \"p < q \\<longleftrightarrow> (let (a, c) = quotient_of p; (b, d) = quotient_of q in a * d < c * b)\"\n  by (cases p, cases q) (simp add: quotient_of_Fract mult.commute)\n\n\n\n\ntext \\<open>Quickcheck\\<close>\n\ndefinition (in term_syntax)\n  valterm_fract :: \"int \\<times> (unit \\<Rightarrow> Code_Evaluation.term) \\<Rightarrow>\n    int \\<times> (unit \\<Rightarrow> Code_Evaluation.term) \\<Rightarrow>\n    rat \\<times> (unit \\<Rightarrow> Code_Evaluation.term)\"\n  where [code_unfold]: \"valterm_fract k l = Code_Evaluation.valtermify Fract {\\<cdot>} k {\\<cdot>} l\"\n\nnotation fcomp (infixl \"\\<circ>>\" 60)\nnotation scomp (infixl \"\\<circ>\\<rightarrow>\" 60)\n\ninstantiation rat :: random\nbegin\n\ndefinition\n  \"Quickcheck_Random.random i =\n    Quickcheck_Random.random i \\<circ>\\<rightarrow> (\\<lambda>num. Random.range i \\<circ>\\<rightarrow> (\\<lambda>denom. Pair\n      (let j = int_of_integer (integer_of_natural (denom + 1))\n       in valterm_fract num (j, \\<lambda>u. Code_Evaluation.term_of j))))\"\n\ninstance ..\n\nend\n\nno_notation fcomp (infixl \"\\<circ>>\" 60)\nno_notation scomp (infixl \"\\<circ>\\<rightarrow>\" 60)\n\ninstantiation rat :: exhaustive\nbegin\n\ndefinition\n  \"exhaustive_rat f d =\n    Quickcheck_Exhaustive.exhaustive\n      (\\<lambda>l. Quickcheck_Exhaustive.exhaustive\n        (\\<lambda>k. f (Fract k (int_of_integer (integer_of_natural l) + 1))) d) d\"\n\ninstance ..\n\nend\n\ninstantiation rat :: full_exhaustive\nbegin\n\ndefinition\n  \"full_exhaustive_rat f d =\n    Quickcheck_Exhaustive.full_exhaustive\n      (\\<lambda>(l, _). Quickcheck_Exhaustive.full_exhaustive\n        (\\<lambda>k. f\n          (let j = int_of_integer (integer_of_natural l) + 1\n           in valterm_fract k (j, \\<lambda>_. Code_Evaluation.term_of j))) d) d\"\n\ninstance ..\n\nend\n\ninstance rat :: partial_term_of ..\n\nlemma [code]:\n  \"partial_term_of (ty :: rat itself) (Quickcheck_Narrowing.Narrowing_variable p tt) \\<equiv>\n    Code_Evaluation.Free (STR ''_'') (Typerep.Typerep (STR ''Rat.rat'') [])\"\n  \"partial_term_of (ty :: rat itself) (Quickcheck_Narrowing.Narrowing_constructor 0 [l, k]) \\<equiv>\n    Code_Evaluation.App\n      (Code_Evaluation.Const (STR ''Rat.Frct'')\n        (Typerep.Typerep (STR ''fun'')\n          [Typerep.Typerep (STR ''Product_Type.prod'')\n           [Typerep.Typerep (STR ''Int.int'') [], Typerep.Typerep (STR ''Int.int'') []],\n           Typerep.Typerep (STR ''Rat.rat'') []]))\n      (Code_Evaluation.App\n        (Code_Evaluation.App\n          (Code_Evaluation.Const (STR ''Product_Type.Pair'')\n            (Typerep.Typerep (STR ''fun'')\n              [Typerep.Typerep (STR ''Int.int'') [],\n               Typerep.Typerep (STR ''fun'')\n                [Typerep.Typerep (STR ''Int.int'') [],\n                 Typerep.Typerep (STR ''Product_Type.prod'')\n                 [Typerep.Typerep (STR ''Int.int'') [], Typerep.Typerep (STR ''Int.int'') []]]]))\n          (partial_term_of (TYPE(int)) l)) (partial_term_of (TYPE(int)) k))\"\n  by (rule partial_term_of_anything)+\n\ninstantiation rat :: narrowing\nbegin\n\ndefinition\n  \"narrowing =\n    Quickcheck_Narrowing.apply\n      (Quickcheck_Narrowing.apply\n        (Quickcheck_Narrowing.cons (\\<lambda>nom denom. Fract nom denom)) narrowing) narrowing\"\n\ninstance ..\n\nend\n\n\nsubsection \\<open>Setup for Nitpick\\<close>\n\ndeclaration \\<open>\n  Nitpick_HOL.register_frac_type @{type_name rat}\n    [(@{const_name Abs_Rat}, @{const_name Nitpick.Abs_Frac}),\n     (@{const_name zero_rat_inst.zero_rat}, @{const_name Nitpick.zero_frac}),\n     (@{const_name one_rat_inst.one_rat}, @{const_name Nitpick.one_frac}),\n     (@{const_name plus_rat_inst.plus_rat}, @{const_name Nitpick.plus_frac}),\n     (@{const_name times_rat_inst.times_rat}, @{const_name Nitpick.times_frac}),\n     (@{const_name uminus_rat_inst.uminus_rat}, @{const_name Nitpick.uminus_frac}),\n     (@{const_name inverse_rat_inst.inverse_rat}, @{const_name Nitpick.inverse_frac}),\n     (@{const_name ord_rat_inst.less_rat}, @{const_name Nitpick.less_frac}),\n     (@{const_name ord_rat_inst.less_eq_rat}, @{const_name Nitpick.less_eq_frac}),\n     (@{const_name field_char_0_class.of_rat}, @{const_name Nitpick.of_frac})]\n\\<close>\n\nlemmas [nitpick_unfold] =\n  inverse_rat_inst.inverse_rat\n  one_rat_inst.one_rat ord_rat_inst.less_rat\n  ord_rat_inst.less_eq_rat plus_rat_inst.plus_rat times_rat_inst.times_rat\n  uminus_rat_inst.uminus_rat zero_rat_inst.zero_rat\n\n\nsubsection \\<open>Float syntax\\<close>\n\nsyntax \"_Float\" :: \"float_const \\<Rightarrow> 'a\"    (\"_\")\n\nparse_translation \\<open>\n  let\n    fun mk_frac str =\n      let\n        val {mant = i, exp = n} = Lexicon.read_float str;\n        val exp = Syntax.const @{const_syntax Power.power};\n        val ten = Numeral.mk_number_syntax 10;\n        val exp10 = if n = 1 then ten else exp $ ten $ Numeral.mk_number_syntax n;\n      in Syntax.const @{const_syntax Fields.inverse_divide} $ Numeral.mk_number_syntax i $ exp10 end;\n\n    fun float_tr [(c as Const (@{syntax_const \"_constrain\"}, _)) $ t $ u] = c $ float_tr [t] $ u\n      | float_tr [t as Const (str, _)] = mk_frac str\n      | float_tr ts = raise TERM (\"float_tr\", ts);\n  in [(@{syntax_const \"_Float\"}, K float_tr)] end\n\\<close>\n\ntext\\<open>Test:\\<close>\nlemma \"123.456 = -111.111 + 200 + 30 + 4 + 5/10 + 6/100 + (7/1000::rat)\"\n  by simp\n\n\nsubsection \\<open>Hiding implementation details\\<close>\n\nhide_const (open) normalize positive\n\nlifting_update rat.lifting\nlifting_forget rat.lifting\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/Rat.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388125473628, "lm_q2_score": 0.8539127492339909, "lm_q1q2_score": 0.7078414203690784}}
{"text": "theory sat\n  imports Main\nbegin\n\ndatatype var = P \"nat\" | N \"nat\"\n\ndatatype clause = C \"nat\" \"var set\"\n\ntype_synonym cnf = \"clause set\"\n\nfun clause_set :: \"clause => var set\" where\n\"clause_set (C _ s) = s\"\n\nfun clause_index :: \"clause => nat\" where\n\"clause_index (C n _) = n\"\n\nfun index :: \"var => nat\" where\n\"index (P n) = n\" | \"index (N n) = n\"\n\nfun evaluate :: \"var => bool list => bool\" where\n\"evaluate (P n) values = nth values n\" |\n\"evaluate (N n) values = (\\<not>(nth values n))\"\n\ndefinition satisfy :: \"cnf => bool list => bool\" where\n\"satisfy f values = (\n    if (\\<exists>x \\<in> f. \\<exists>n s .x = (C n s) \\<and> True \\<notin> {y. \\<exists>b \\<in> s. y = evaluate b values}) then False\n    else True\n)\"\n\nlemma satisfy_empty : \"satisfy {} [] = True\"\nby (auto simp add: satisfy_def)\n\nlemma unsatisfy_empty_clausel: \"satisfy {(C n {})} [] = False\"\nby (auto simp add: satisfy_def)\n\nlemma satisfy_decrease : \"\\<lbrakk>satisfy c1 values; c2 \\<subseteq> c1\\<rbrakk> \\<Longrightarrow> satisfy c2 values\"\nby (auto simp add: satisfy_def split: if_splits)\n\nfun tcnf :: \"cnf => bool\" where\n\"tcnf f = (\\<forall>x \\<in> f. \\<exists> s. x = (C 3 s))\"\n\n(*TODO:\nformalisation of sat and sat reduction to 3cnf\n*)\n\n\nend ", "meta": {"author": "AlexiosFan", "repo": "SimpleMaths", "sha": "3d2045a83a4683c695065dc78b5a816322784adf", "save_path": "github-repos/isabelle/AlexiosFan-SimpleMaths", "path": "github-repos/isabelle/AlexiosFan-SimpleMaths/SimpleMaths-3d2045a83a4683c695065dc78b5a816322784adf/Polynomial_reductions/sat.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9136765234137297, "lm_q2_score": 0.7745833789613197, "lm_q1q2_score": 0.707718648783438}}
{"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_MSortTDIsSort\n  imports \"../../Test_Base\"\nbegin\n\ndatatype 'a list = nil2 | cons2 \"'a\" \"'a list\"\n\nfun take :: \"int => 'a list => 'a list\" where\n  \"take x y =\n   (if x <= 0 then nil2 else\n      (case y of\n         nil2 => nil2\n         | cons2 z xs => cons2 z (take (x - 1) 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 length :: \"'a list => int\" where\n  \"length (nil2) = 0\"\n| \"length (cons2 y l) = 1 + (length l)\"\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\nfun drop :: \"int => 'a list => 'a list\" where\n  \"drop x y =\n   (if x <= 0 then y else\n      (case y of\n         nil2 => nil2\n         | cons2 z xs1 => drop (x - 1) xs1))\"\n\n(*fun did not finish the proof*)\nfunction msorttd :: \"int list => int list\" where\n  \"msorttd (nil2) = nil2\"\n| \"msorttd (cons2 y (nil2)) = cons2 y (nil2)\"\n| \"msorttd (cons2 y (cons2 x2 x3)) =\n     (let k :: int = (op div) (length (cons2 y (cons2 x2 x3))) 2\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  \"((msorttd 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_MSortTDIsSort.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869948899665, "lm_q2_score": 0.8080672158638528, "lm_q1q2_score": 0.7076947586505055}}
{"text": "(*  Title:      InfiniteSet2.thy\n    Date:       Aug 2008\n    Author:     David Trachtenherz\n*)\n\nsection \\<open>Set operations with results of type enat\\<close>\n\ntheory InfiniteSet2\nimports SetInterval2\nbegin\n\nsubsection \\<open>Set operations with @{typ enat}\\<close>\n\nsubsubsection \\<open>Basic definitions\\<close>\n\ndefinition icard :: \"'a set \\<Rightarrow> enat\"\n  where \"icard A \\<equiv> if finite A then enat (card A) else \\<infinity>\"\n\n\nsubsection \\<open>Results for \\<open>icard\\<close>\\<close>\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\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\n\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\n\nlemmas icard_0_eq = icard_empty_iff\n\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\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\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\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\nlemma icard_insert_le: \"icard A \\<le> icard (insert x A)\"\nby (simp add: icard_insert_if)\n\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\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\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\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 apply (simp add: icard_finite card_Un_Int[of A])\napply simp_all\ndone\n\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\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\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)\n\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\nlemma icard_Diff1_le: \"icard (A - {x}) \\<le> icard A\"\nby (rule icard_mono, rule Diff_subset)\n\nlemma icard_psubset: \"\\<lbrakk> A \\<subseteq> B; icard A < icard B \\<rbrakk> \\<Longrightarrow> A \\<subset> B\"\nby (metis less_le psubset_eq)\n\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  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  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 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)\napply (frule Union_upper)\napply (rule infinite_super, assumption)\napply simp\ndone\n\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\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\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\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\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\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\nlemma icard_cartesian_product_singleton: \"icard ({x} \\<times> A) = icard A\"\nby (simp add: icard_cartesian_product mult_eSuc)\n\nlemma icard_cartesian_product_singleton_right: \"icard (A \\<times> {x}) = icard A\"\nby (simp add: icard_cartesian_product mult_eSuc_right)\n\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)\n\nlemma icard_greaterThan: \"icard {(u::nat)<..} = \\<infinity>\"\nby (simp add: infinite_greaterThan)\n\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": "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/CommonSet/InfiniteSet2.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511543206819, "lm_q2_score": 0.8267117962054048, "lm_q1q2_score": 0.7075422450729201}}
{"text": "(*  Title:      HOL/Deriv.thy\n    Author:     Jacques D. Fleuriot, University of Cambridge, 1998\n    Author:     Brian Huffman\n    Author:     Lawrence C Paulson, 2004\n    Author:     Benjamin Porter, 2005\n*)\n\nsection \\<open>Differentiation\\<close>\n\ntheory Deriv\n  imports Limits\nbegin\n\nsubsection \\<open>Frechet derivative\\<close>\n\ndefinition has_derivative :: \"('a::real_normed_vector \\<Rightarrow> 'b::real_normed_vector) \\<Rightarrow>\n    ('a \\<Rightarrow> 'b) \\<Rightarrow> 'a filter \\<Rightarrow> bool\"  (infix \"(has'_derivative)\" 50)\n  where \"(f has_derivative f') F \\<longleftrightarrow>\n    bounded_linear f' \\<and>\n    ((\\<lambda>y. ((f y - f (Lim F (\\<lambda>x. x))) - f' (y - Lim F (\\<lambda>x. x))) /\\<^sub>R norm (y - Lim F (\\<lambda>x. x))) \\<longlongrightarrow> 0) F\"\n\ntext \\<open>\n  Usually the filter @{term F} is @{term \"at x within s\"}.  @{term \"(f has_derivative D)\n  (at x within s)\"} means: @{term D} is the derivative of function @{term f} at point @{term x}\n  within the set @{term s}. Where @{term s} is used to express left or right sided derivatives. In\n  most cases @{term s} is either a variable or @{term UNIV}.\n\\<close>\n\nlemma has_derivative_eq_rhs: \"(f has_derivative f') F \\<Longrightarrow> f' = g' \\<Longrightarrow> (f has_derivative g') F\"\n  by simp\n\ndefinition has_field_derivative :: \"('a::real_normed_field \\<Rightarrow> 'a) \\<Rightarrow> 'a \\<Rightarrow> 'a filter \\<Rightarrow> bool\"\n    (infix \"(has'_field'_derivative)\" 50)\n  where \"(f has_field_derivative D) F \\<longleftrightarrow> (f has_derivative op * D) F\"\n\nlemma DERIV_cong: \"(f has_field_derivative X) F \\<Longrightarrow> X = Y \\<Longrightarrow> (f has_field_derivative Y) F\"\n  by simp\n\ndefinition has_vector_derivative :: \"(real \\<Rightarrow> 'b::real_normed_vector) \\<Rightarrow> 'b \\<Rightarrow> real filter \\<Rightarrow> bool\"\n    (infix \"has'_vector'_derivative\" 50)\n  where \"(f has_vector_derivative f') net \\<longleftrightarrow> (f has_derivative (\\<lambda>x. x *\\<^sub>R f')) net\"\n\nlemma has_vector_derivative_eq_rhs:\n  \"(f has_vector_derivative X) F \\<Longrightarrow> X = Y \\<Longrightarrow> (f has_vector_derivative Y) F\"\n  by simp\n\nnamed_theorems derivative_intros \"structural introduction rules for derivatives\"\nsetup \\<open>\n  let\n    val eq_thms = @{thms has_derivative_eq_rhs DERIV_cong has_vector_derivative_eq_rhs}\n    fun eq_rule thm = get_first (try (fn eq_thm => eq_thm OF [thm])) eq_thms\n  in\n    Global_Theory.add_thms_dynamic\n      (@{binding derivative_eq_intros},\n        fn context =>\n          Named_Theorems.get (Context.proof_of context) @{named_theorems derivative_intros}\n          |> map_filter eq_rule)\n  end;\n\\<close>\n\ntext \\<open>\n  The following syntax is only used as a legacy syntax.\n\\<close>\nabbreviation (input)\n  FDERIV :: \"('a::real_normed_vector \\<Rightarrow> 'b::real_normed_vector) \\<Rightarrow> 'a \\<Rightarrow>  ('a \\<Rightarrow> 'b) \\<Rightarrow> bool\"\n  (\"(FDERIV (_)/ (_)/ :> (_))\" [1000, 1000, 60] 60)\n  where \"FDERIV f x :> f' \\<equiv> (f has_derivative f') (at x)\"\n\nlemma has_derivative_bounded_linear: \"(f has_derivative f') F \\<Longrightarrow> bounded_linear f'\"\n  by (simp add: has_derivative_def)\n\nlemma has_derivative_linear: \"(f has_derivative f') F \\<Longrightarrow> linear f'\"\n  using bounded_linear.linear[OF has_derivative_bounded_linear] .\n\nlemma has_derivative_ident[derivative_intros, simp]: \"((\\<lambda>x. x) has_derivative (\\<lambda>x. x)) F\"\n  by (simp add: has_derivative_def)\n\nlemma has_derivative_id [derivative_intros, simp]: \"(id has_derivative id) (at a)\"\n  by (metis eq_id_iff has_derivative_ident)\n\nlemma has_derivative_const[derivative_intros, simp]: \"((\\<lambda>x. c) has_derivative (\\<lambda>x. 0)) F\"\n  by (simp add: has_derivative_def)\n\nlemma (in bounded_linear) bounded_linear: \"bounded_linear f\" ..\n\nlemma (in bounded_linear) has_derivative:\n  \"(g has_derivative g') F \\<Longrightarrow> ((\\<lambda>x. f (g x)) has_derivative (\\<lambda>x. f (g' x))) F\"\n  unfolding has_derivative_def\n  apply safe\n   apply (erule bounded_linear_compose [OF bounded_linear])\n  apply (drule tendsto)\n  apply (simp add: scaleR diff add zero)\n  done\n\nlemmas has_derivative_scaleR_right [derivative_intros] =\n  bounded_linear.has_derivative [OF bounded_linear_scaleR_right]\n\nlemmas has_derivative_scaleR_left [derivative_intros] =\n  bounded_linear.has_derivative [OF bounded_linear_scaleR_left]\n\nlemmas has_derivative_mult_right [derivative_intros] =\n  bounded_linear.has_derivative [OF bounded_linear_mult_right]\n\nlemmas has_derivative_mult_left [derivative_intros] =\n  bounded_linear.has_derivative [OF bounded_linear_mult_left]\n\nlemma has_derivative_add[simp, derivative_intros]:\n  assumes f: \"(f has_derivative f') F\"\n    and g: \"(g has_derivative g') F\"\n  shows \"((\\<lambda>x. f x + g x) has_derivative (\\<lambda>x. f' x + g' x)) F\"\n  unfolding has_derivative_def\nproof safe\n  let ?x = \"Lim F (\\<lambda>x. x)\"\n  let ?D = \"\\<lambda>f f' y. ((f y - f ?x) - f' (y - ?x)) /\\<^sub>R norm (y - ?x)\"\n  have \"((\\<lambda>x. ?D f f' x + ?D g g' x) \\<longlongrightarrow> (0 + 0)) F\"\n    using f g by (intro tendsto_add) (auto simp: has_derivative_def)\n  then show \"(?D (\\<lambda>x. f x + g x) (\\<lambda>x. f' x + g' x) \\<longlongrightarrow> 0) F\"\n    by (simp add: field_simps scaleR_add_right scaleR_diff_right)\nqed (blast intro: bounded_linear_add f g has_derivative_bounded_linear)\n\nlemma has_derivative_sum[simp, derivative_intros]:\n  \"(\\<And>i. i \\<in> I \\<Longrightarrow> (f i has_derivative f' i) F) \\<Longrightarrow>\n    ((\\<lambda>x. \\<Sum>i\\<in>I. f i x) has_derivative (\\<lambda>x. \\<Sum>i\\<in>I. f' i x)) F\"\n  by (induct I rule: infinite_finite_induct) simp_all\n\nlemma has_derivative_minus[simp, derivative_intros]:\n  \"(f has_derivative f') F \\<Longrightarrow> ((\\<lambda>x. - f x) has_derivative (\\<lambda>x. - f' x)) F\"\n  using has_derivative_scaleR_right[of f f' F \"-1\"] by simp\n\nlemma has_derivative_diff[simp, derivative_intros]:\n  \"(f has_derivative f') F \\<Longrightarrow> (g has_derivative g') F \\<Longrightarrow>\n    ((\\<lambda>x. f x - g x) has_derivative (\\<lambda>x. f' x - g' x)) F\"\n  by (simp only: diff_conv_add_uminus has_derivative_add has_derivative_minus)\n\nlemma has_derivative_at_within:\n  \"(f has_derivative f') (at x within s) \\<longleftrightarrow>\n    (bounded_linear f' \\<and> ((\\<lambda>y. ((f y - f x) - f' (y - x)) /\\<^sub>R norm (y - x)) \\<longlongrightarrow> 0) (at x within s))\"\n  by (cases \"at x within s = bot\") (simp_all add: has_derivative_def Lim_ident_at)\n\nlemma has_derivative_iff_norm:\n  \"(f has_derivative f') (at x within s) \\<longleftrightarrow>\n    bounded_linear f' \\<and> ((\\<lambda>y. norm ((f y - f x) - f' (y - x)) / norm (y - x)) \\<longlongrightarrow> 0) (at x within s)\"\n  using tendsto_norm_zero_iff[of _ \"at x within s\", where 'b=\"'b\", symmetric]\n  by (simp add: has_derivative_at_within divide_inverse ac_simps)\n\nlemma has_derivative_at:\n  \"(f has_derivative D) (at x) \\<longleftrightarrow>\n    (bounded_linear D \\<and> (\\<lambda>h. norm (f (x + h) - f x - D h) / norm h) \\<midarrow>0\\<rightarrow> 0)\"\n  unfolding has_derivative_iff_norm LIM_offset_zero_iff[of _ _ x] by simp\n\nlemma field_has_derivative_at:\n  fixes x :: \"'a::real_normed_field\"\n  shows \"(f has_derivative op * D) (at x) \\<longleftrightarrow> (\\<lambda>h. (f (x + h) - f x) / h) \\<midarrow>0\\<rightarrow> D\"\n  apply (unfold has_derivative_at)\n  apply (simp add: bounded_linear_mult_right)\n  apply (simp cong: LIM_cong add: nonzero_norm_divide [symmetric])\n  apply (subst diff_divide_distrib)\n  apply (subst times_divide_eq_left [symmetric])\n  apply (simp cong: LIM_cong)\n  apply (simp add: tendsto_norm_zero_iff LIM_zero_iff)\n  done\n\nlemma has_derivativeI:\n  \"bounded_linear f' \\<Longrightarrow>\n    ((\\<lambda>y. ((f y - f x) - f' (y - x)) /\\<^sub>R norm (y - x)) \\<longlongrightarrow> 0) (at x within s) \\<Longrightarrow>\n    (f has_derivative f') (at x within s)\"\n  by (simp add: has_derivative_at_within)\n\nlemma has_derivativeI_sandwich:\n  assumes e: \"0 < e\"\n    and bounded: \"bounded_linear f'\"\n    and sandwich: \"(\\<And>y. y \\<in> s \\<Longrightarrow> y \\<noteq> x \\<Longrightarrow> dist y x < e \\<Longrightarrow>\n      norm ((f y - f x) - f' (y - x)) / norm (y - x) \\<le> H y)\"\n    and \"(H \\<longlongrightarrow> 0) (at x within s)\"\n  shows \"(f has_derivative f') (at x within s)\"\n  unfolding has_derivative_iff_norm\nproof safe\n  show \"((\\<lambda>y. norm (f y - f x - f' (y - x)) / norm (y - x)) \\<longlongrightarrow> 0) (at x within s)\"\n  proof (rule tendsto_sandwich[where f=\"\\<lambda>x. 0\"])\n    show \"(H \\<longlongrightarrow> 0) (at x within s)\" by fact\n    show \"eventually (\\<lambda>n. norm (f n - f x - f' (n - x)) / norm (n - x) \\<le> H n) (at x within s)\"\n      unfolding eventually_at using e sandwich by auto\n  qed (auto simp: le_divide_eq)\nqed fact\n\nlemma has_derivative_subset:\n  \"(f has_derivative f') (at x within s) \\<Longrightarrow> t \\<subseteq> s \\<Longrightarrow> (f has_derivative f') (at x within t)\"\n  by (auto simp add: has_derivative_iff_norm intro: tendsto_within_subset)\n\nlemmas has_derivative_within_subset = has_derivative_subset\n\n\nsubsection \\<open>Continuity\\<close>\n\nlemma has_derivative_continuous:\n  assumes f: \"(f has_derivative f') (at x within s)\"\n  shows \"continuous (at x within s) f\"\nproof -\n  from f interpret F: bounded_linear f'\n    by (rule has_derivative_bounded_linear)\n  note F.tendsto[tendsto_intros]\n  let ?L = \"\\<lambda>f. (f \\<longlongrightarrow> 0) (at x within s)\"\n  have \"?L (\\<lambda>y. norm ((f y - f x) - f' (y - x)) / norm (y - x))\"\n    using f unfolding has_derivative_iff_norm by blast\n  then have \"?L (\\<lambda>y. norm ((f y - f x) - f' (y - x)) / norm (y - x) * norm (y - x))\" (is ?m)\n    by (rule tendsto_mult_zero) (auto intro!: tendsto_eq_intros)\n  also have \"?m \\<longleftrightarrow> ?L (\\<lambda>y. norm ((f y - f x) - f' (y - x)))\"\n    by (intro filterlim_cong) (simp_all add: eventually_at_filter)\n  finally have \"?L (\\<lambda>y. (f y - f x) - f' (y - x))\"\n    by (rule tendsto_norm_zero_cancel)\n  then have \"?L (\\<lambda>y. ((f y - f x) - f' (y - x)) + f' (y - x))\"\n    by (rule tendsto_eq_intros) (auto intro!: tendsto_eq_intros simp: F.zero)\n  then have \"?L (\\<lambda>y. f y - f x)\"\n    by simp\n  from tendsto_add[OF this tendsto_const, of \"f x\"] show ?thesis\n    by (simp add: continuous_within)\nqed\n\n\nsubsection \\<open>Composition\\<close>\n\nlemma tendsto_at_iff_tendsto_nhds_within:\n  \"f x = y \\<Longrightarrow> (f \\<longlongrightarrow> y) (at x within s) \\<longleftrightarrow> (f \\<longlongrightarrow> y) (inf (nhds x) (principal s))\"\n  unfolding tendsto_def eventually_inf_principal eventually_at_filter\n  by (intro ext all_cong imp_cong) (auto elim!: eventually_mono)\n\nlemma has_derivative_in_compose:\n  assumes f: \"(f has_derivative f') (at x within s)\"\n    and g: \"(g has_derivative g') (at (f x) within (f`s))\"\n  shows \"((\\<lambda>x. g (f x)) has_derivative (\\<lambda>x. g' (f' x))) (at x within s)\"\nproof -\n  from f interpret F: bounded_linear f'\n    by (rule has_derivative_bounded_linear)\n  from g interpret G: bounded_linear g'\n    by (rule has_derivative_bounded_linear)\n  from F.bounded obtain kF where kF: \"\\<And>x. norm (f' x) \\<le> norm x * kF\"\n    by fast\n  from G.bounded obtain kG where kG: \"\\<And>x. norm (g' x) \\<le> norm x * kG\"\n    by fast\n  note G.tendsto[tendsto_intros]\n\n  let ?L = \"\\<lambda>f. (f \\<longlongrightarrow> 0) (at x within s)\"\n  let ?D = \"\\<lambda>f f' x y. (f y - f x) - f' (y - x)\"\n  let ?N = \"\\<lambda>f f' x y. norm (?D f f' x y) / norm (y - x)\"\n  let ?gf = \"\\<lambda>x. g (f x)\" and ?gf' = \"\\<lambda>x. g' (f' x)\"\n  define Nf where \"Nf = ?N f f' x\"\n  define Ng where [abs_def]: \"Ng y = ?N g g' (f x) (f y)\" for y\n\n  show ?thesis\n  proof (rule has_derivativeI_sandwich[of 1])\n    show \"bounded_linear (\\<lambda>x. g' (f' x))\"\n      using f g by (blast intro: bounded_linear_compose has_derivative_bounded_linear)\n  next\n    fix y :: 'a\n    assume neq: \"y \\<noteq> x\"\n    have \"?N ?gf ?gf' x y = norm (g' (?D f f' x y) + ?D g g' (f x) (f y)) / norm (y - x)\"\n      by (simp add: G.diff G.add field_simps)\n    also have \"\\<dots> \\<le> norm (g' (?D f f' x y)) / norm (y - x) + Ng y * (norm (f y - f x) / norm (y - x))\"\n      by (simp add: add_divide_distrib[symmetric] divide_right_mono norm_triangle_ineq G.zero Ng_def)\n    also have \"\\<dots> \\<le> Nf y * kG + Ng y * (Nf y + kF)\"\n    proof (intro add_mono mult_left_mono)\n      have \"norm (f y - f x) = norm (?D f f' x y + f' (y - x))\"\n        by simp\n      also have \"\\<dots> \\<le> norm (?D f f' x y) + norm (f' (y - x))\"\n        by (rule norm_triangle_ineq)\n      also have \"\\<dots> \\<le> norm (?D f f' x y) + norm (y - x) * kF\"\n        using kF by (intro add_mono) simp\n      finally show \"norm (f y - f x) / norm (y - x) \\<le> Nf y + kF\"\n        by (simp add: neq Nf_def field_simps)\n    qed (use kG in \\<open>simp_all add: Ng_def Nf_def neq zero_le_divide_iff field_simps\\<close>)\n    finally show \"?N ?gf ?gf' x y \\<le> Nf y * kG + Ng y * (Nf y + kF)\" .\n  next\n    have [tendsto_intros]: \"?L Nf\"\n      using f unfolding has_derivative_iff_norm Nf_def ..\n    from f have \"(f \\<longlongrightarrow> f x) (at x within s)\"\n      by (blast intro: has_derivative_continuous continuous_within[THEN iffD1])\n    then have f': \"LIM x at x within s. f x :> inf (nhds (f x)) (principal (f`s))\"\n      unfolding filterlim_def\n      by (simp add: eventually_filtermap eventually_at_filter le_principal)\n\n    have \"((?N g  g' (f x)) \\<longlongrightarrow> 0) (at (f x) within f`s)\"\n      using g unfolding has_derivative_iff_norm ..\n    then have g': \"((?N g  g' (f x)) \\<longlongrightarrow> 0) (inf (nhds (f x)) (principal (f`s)))\"\n      by (rule tendsto_at_iff_tendsto_nhds_within[THEN iffD1, rotated]) simp\n\n    have [tendsto_intros]: \"?L Ng\"\n      unfolding Ng_def by (rule filterlim_compose[OF g' f'])\n    show \"((\\<lambda>y. Nf y * kG + Ng y * (Nf y + kF)) \\<longlongrightarrow> 0) (at x within s)\"\n      by (intro tendsto_eq_intros) auto\n  qed simp\nqed\n\nlemma has_derivative_compose:\n  \"(f has_derivative f') (at x within s) \\<Longrightarrow> (g has_derivative g') (at (f x)) \\<Longrightarrow>\n  ((\\<lambda>x. g (f x)) has_derivative (\\<lambda>x. g' (f' x))) (at x within s)\"\n  by (blast intro: has_derivative_in_compose has_derivative_subset)\n\nlemma (in bounded_bilinear) FDERIV:\n  assumes f: \"(f has_derivative f') (at x within s)\" and g: \"(g has_derivative g') (at x within s)\"\n  shows \"((\\<lambda>x. f x ** g x) has_derivative (\\<lambda>h. f x ** g' h + f' h ** g x)) (at x within s)\"\nproof -\n  from bounded_linear.bounded [OF has_derivative_bounded_linear [OF f]]\n  obtain KF where norm_F: \"\\<And>x. norm (f' x) \\<le> norm x * KF\" by fast\n\n  from pos_bounded obtain K\n    where K: \"0 < K\" and norm_prod: \"\\<And>a b. norm (a ** b) \\<le> norm a * norm b * K\"\n    by fast\n  let ?D = \"\\<lambda>f f' y. f y - f x - f' (y - x)\"\n  let ?N = \"\\<lambda>f f' y. norm (?D f f' y) / norm (y - x)\"\n  define Ng where \"Ng = ?N g g'\"\n  define Nf where \"Nf = ?N f f'\"\n\n  let ?fun1 = \"\\<lambda>y. norm (f y ** g y - f x ** g x - (f x ** g' (y - x) + f' (y - x) ** g x)) / norm (y - x)\"\n  let ?fun2 = \"\\<lambda>y. norm (f x) * Ng y * K + Nf y * norm (g y) * K + KF * norm (g y - g x) * K\"\n  let ?F = \"at x within s\"\n\n  show ?thesis\n  proof (rule has_derivativeI_sandwich[of 1])\n    show \"bounded_linear (\\<lambda>h. f x ** g' h + f' h ** g x)\"\n      by (intro bounded_linear_add\n        bounded_linear_compose [OF bounded_linear_right] bounded_linear_compose [OF bounded_linear_left]\n        has_derivative_bounded_linear [OF g] has_derivative_bounded_linear [OF f])\n  next\n    from g have \"(g \\<longlongrightarrow> g x) ?F\"\n      by (intro continuous_within[THEN iffD1] has_derivative_continuous)\n    moreover from f g have \"(Nf \\<longlongrightarrow> 0) ?F\" \"(Ng \\<longlongrightarrow> 0) ?F\"\n      by (simp_all add: has_derivative_iff_norm Ng_def Nf_def)\n    ultimately have \"(?fun2 \\<longlongrightarrow> norm (f x) * 0 * K + 0 * norm (g x) * K + KF * norm (0::'b) * K) ?F\"\n      by (intro tendsto_intros) (simp_all add: LIM_zero_iff)\n    then show \"(?fun2 \\<longlongrightarrow> 0) ?F\"\n      by simp\n  next\n    fix y :: 'd\n    assume \"y \\<noteq> x\"\n    have \"?fun1 y =\n        norm (f x ** ?D g g' y + ?D f f' y ** g y + f' (y - x) ** (g y - g x)) / norm (y - x)\"\n      by (simp add: diff_left diff_right add_left add_right field_simps)\n    also have \"\\<dots> \\<le> (norm (f x) * norm (?D g g' y) * K + norm (?D f f' y) * norm (g y) * K +\n        norm (y - x) * KF * norm (g y - g x) * K) / norm (y - x)\"\n      by (intro divide_right_mono mult_mono'\n                order_trans [OF norm_triangle_ineq add_mono]\n                order_trans [OF norm_prod mult_right_mono]\n                mult_nonneg_nonneg order_refl norm_ge_zero norm_F\n                K [THEN order_less_imp_le])\n    also have \"\\<dots> = ?fun2 y\"\n      by (simp add: add_divide_distrib Ng_def Nf_def)\n    finally show \"?fun1 y \\<le> ?fun2 y\" .\n  qed simp\nqed\n\nlemmas has_derivative_mult[simp, derivative_intros] = bounded_bilinear.FDERIV[OF bounded_bilinear_mult]\nlemmas has_derivative_scaleR[simp, derivative_intros] = bounded_bilinear.FDERIV[OF bounded_bilinear_scaleR]\n\nlemma has_derivative_prod[simp, derivative_intros]:\n  fixes f :: \"'i \\<Rightarrow> 'a::real_normed_vector \\<Rightarrow> 'b::real_normed_field\"\n  shows \"(\\<And>i. i \\<in> I \\<Longrightarrow> (f i has_derivative f' i) (at x within s)) \\<Longrightarrow>\n    ((\\<lambda>x. \\<Prod>i\\<in>I. f i x) has_derivative (\\<lambda>y. \\<Sum>i\\<in>I. f' i y * (\\<Prod>j\\<in>I - {i}. f j x))) (at x within s)\"\nproof (induct I rule: infinite_finite_induct)\n  case infinite\n  then show ?case by simp\nnext\n  case empty\n  then show ?case by simp\nnext\n  case (insert i I)\n  let ?P = \"\\<lambda>y. f i x * (\\<Sum>i\\<in>I. f' i y * (\\<Prod>j\\<in>I - {i}. f j x)) + (f' i y) * (\\<Prod>i\\<in>I. f i x)\"\n  have \"((\\<lambda>x. f i x * (\\<Prod>i\\<in>I. f i x)) has_derivative ?P) (at x within s)\"\n    using insert by (intro has_derivative_mult) auto\n  also have \"?P = (\\<lambda>y. \\<Sum>i'\\<in>insert i I. f' i' y * (\\<Prod>j\\<in>insert i I - {i'}. f j x))\"\n    using insert(1,2)\n    by (auto simp add: sum_distrib_left insert_Diff_if intro!: ext sum.cong)\n  finally show ?case\n    using insert by simp\nqed\n\nlemma has_derivative_power[simp, derivative_intros]:\n  fixes f :: \"'a :: real_normed_vector \\<Rightarrow> 'b :: real_normed_field\"\n  assumes f: \"(f has_derivative f') (at x within s)\"\n  shows \"((\\<lambda>x. f x^n) has_derivative (\\<lambda>y. of_nat n * f' y * f x^(n - 1))) (at x within s)\"\n  using has_derivative_prod[OF f, of \"{..< n}\"] by (simp add: prod_constant ac_simps)\n\nlemma has_derivative_inverse':\n  fixes x :: \"'a::real_normed_div_algebra\"\n  assumes x: \"x \\<noteq> 0\"\n  shows \"(inverse has_derivative (\\<lambda>h. - (inverse x * h * inverse x))) (at x within s)\"\n    (is \"(?inv has_derivative ?f) _\")\nproof (rule has_derivativeI_sandwich)\n  show \"bounded_linear (\\<lambda>h. - (?inv x * h * ?inv x))\"\n    apply (rule bounded_linear_minus)\n    apply (rule bounded_linear_mult_const)\n    apply (rule bounded_linear_const_mult)\n    apply (rule bounded_linear_ident)\n    done\n  show \"0 < norm x\" using x by simp\n  show \"((\\<lambda>y. norm (?inv y - ?inv x) * norm (?inv x)) \\<longlongrightarrow> 0) (at x within s)\"\n    apply (rule tendsto_mult_left_zero)\n    apply (rule tendsto_norm_zero)\n    apply (rule LIM_zero)\n    apply (rule tendsto_inverse)\n     apply (rule tendsto_ident_at)\n    apply (rule x)\n    done\nnext\n  fix y :: 'a\n  assume h: \"y \\<noteq> x\" \"dist y x < norm x\"\n  then have \"y \\<noteq> 0\" by auto\n  have \"norm (?inv y - ?inv x - ?f (y -x)) / norm (y - x) =\n      norm ((?inv y - ?inv x) * (y - x) * ?inv x) / norm (y - x)\"\n    apply (subst inverse_diff_inverse [OF \\<open>y \\<noteq> 0\\<close> x])\n    apply (subst minus_diff_minus)\n    apply (subst norm_minus_cancel)\n    apply (simp add: left_diff_distrib)\n    done\n  also have \"\\<dots> \\<le> norm (?inv y - ?inv x) * norm (y - x) * norm (?inv x) / norm (y - x)\"\n    apply (rule divide_right_mono [OF _ norm_ge_zero])\n    apply (rule order_trans [OF norm_mult_ineq])\n    apply (rule mult_right_mono [OF _ norm_ge_zero])\n    apply (rule norm_mult_ineq)\n    done\n  also have \"\\<dots> = norm (?inv y - ?inv x) * norm (?inv x)\"\n    by simp\n  finally show \"norm (?inv y - ?inv x - ?f (y -x)) / norm (y - x) \\<le>\n    norm (?inv y - ?inv x) * norm (?inv x)\" .\nqed\n\nlemma has_derivative_inverse[simp, derivative_intros]:\n  fixes f :: \"_ \\<Rightarrow> 'a::real_normed_div_algebra\"\n  assumes x:  \"f x \\<noteq> 0\"\n    and f: \"(f has_derivative f') (at x within s)\"\n  shows \"((\\<lambda>x. inverse (f x)) has_derivative (\\<lambda>h. - (inverse (f x) * f' h * inverse (f x))))\n    (at x within s)\"\n  using has_derivative_compose[OF f has_derivative_inverse', OF x] .\n\nlemma has_derivative_divide[simp, derivative_intros]:\n  fixes f :: \"_ \\<Rightarrow> 'a::real_normed_div_algebra\"\n  assumes f: \"(f has_derivative f') (at x within s)\"\n    and g: \"(g has_derivative g') (at x within s)\"\n  assumes x: \"g x \\<noteq> 0\"\n  shows \"((\\<lambda>x. f x / g x) has_derivative\n                (\\<lambda>h. - f x * (inverse (g x) * g' h * inverse (g x)) + f' h / g x)) (at x within s)\"\n  using has_derivative_mult[OF f has_derivative_inverse[OF x g]]\n  by (simp add: field_simps)\n\n\ntext \\<open>Conventional form requires mult-AC laws. Types real and complex only.\\<close>\n\nlemma has_derivative_divide'[derivative_intros]:\n  fixes f :: \"_ \\<Rightarrow> 'a::real_normed_field\"\n  assumes f: \"(f has_derivative f') (at x within s)\"\n    and g: \"(g has_derivative g') (at x within s)\"\n    and x: \"g x \\<noteq> 0\"\n  shows \"((\\<lambda>x. f x / g x) has_derivative (\\<lambda>h. (f' h * g x - f x * g' h) / (g x * g x))) (at x within s)\"\nproof -\n  have \"f' h / g x - f x * (inverse (g x) * g' h * inverse (g x)) =\n      (f' h * g x - f x * g' h) / (g x * g x)\" for h\n    by (simp add: field_simps x)\n  then show ?thesis\n    using has_derivative_divide [OF f g] x\n    by simp\nqed\n\n\nsubsection \\<open>Uniqueness\\<close>\n\ntext \\<open>\nThis can not generally shown for @{const has_derivative}, as we need to approach the point from\nall directions. There is a proof in \\<open>Analysis\\<close> for \\<open>euclidean_space\\<close>.\n\\<close>\n\nlemma has_derivative_zero_unique:\n  assumes \"((\\<lambda>x. 0) has_derivative F) (at x)\"\n  shows \"F = (\\<lambda>h. 0)\"\nproof -\n  interpret F: bounded_linear F\n    using assms by (rule has_derivative_bounded_linear)\n  let ?r = \"\\<lambda>h. norm (F h) / norm h\"\n  have *: \"?r \\<midarrow>0\\<rightarrow> 0\"\n    using assms unfolding has_derivative_at by simp\n  show \"F = (\\<lambda>h. 0)\"\n  proof\n    show \"F h = 0\" for h\n    proof (rule ccontr)\n      assume **: \"\\<not> ?thesis\"\n      then have h: \"h \\<noteq> 0\"\n        by (auto simp add: F.zero)\n      with ** have \"0 < ?r h\"\n        by simp\n      from LIM_D [OF * this] obtain s\n        where s: \"0 < s\" and r: \"\\<And>x. x \\<noteq> 0 \\<Longrightarrow> norm x < s \\<Longrightarrow> ?r x < ?r h\"\n        by auto\n      from dense [OF s] obtain t where t: \"0 < t \\<and> t < s\" ..\n      let ?x = \"scaleR (t / norm h) h\"\n      have \"?x \\<noteq> 0\" and \"norm ?x < s\"\n        using t h by simp_all\n      then have \"?r ?x < ?r h\"\n        by (rule r)\n      then show False\n        using t h by (simp add: F.scaleR)\n    qed\n  qed\nqed\n\nlemma has_derivative_unique:\n  assumes \"(f has_derivative F) (at x)\"\n    and \"(f has_derivative F') (at x)\"\n  shows \"F = F'\"\nproof -\n  have \"((\\<lambda>x. 0) has_derivative (\\<lambda>h. F h - F' h)) (at x)\"\n    using has_derivative_diff [OF assms] by simp\n  then have \"(\\<lambda>h. F h - F' h) = (\\<lambda>h. 0)\"\n    by (rule has_derivative_zero_unique)\n  then show \"F = F'\"\n    unfolding fun_eq_iff right_minus_eq .\nqed\n\n\nsubsection \\<open>Differentiability predicate\\<close>\n\ndefinition differentiable :: \"('a::real_normed_vector \\<Rightarrow> 'b::real_normed_vector) \\<Rightarrow> 'a filter \\<Rightarrow> bool\"\n    (infix \"differentiable\" 50)\n  where \"f differentiable F \\<longleftrightarrow> (\\<exists>D. (f has_derivative D) F)\"\n\nlemma differentiable_subset:\n  \"f differentiable (at x within s) \\<Longrightarrow> t \\<subseteq> s \\<Longrightarrow> f differentiable (at x within t)\"\n  unfolding differentiable_def by (blast intro: has_derivative_subset)\n\nlemmas differentiable_within_subset = differentiable_subset\n\nlemma differentiable_ident [simp, derivative_intros]: \"(\\<lambda>x. x) differentiable F\"\n  unfolding differentiable_def by (blast intro: has_derivative_ident)\n\nlemma differentiable_const [simp, derivative_intros]: \"(\\<lambda>z. a) differentiable F\"\n  unfolding differentiable_def by (blast intro: has_derivative_const)\n\nlemma differentiable_in_compose:\n  \"f differentiable (at (g x) within (g`s)) \\<Longrightarrow> g differentiable (at x within s) \\<Longrightarrow>\n    (\\<lambda>x. f (g x)) differentiable (at x within s)\"\n  unfolding differentiable_def by (blast intro: has_derivative_in_compose)\n\nlemma differentiable_compose:\n  \"f differentiable (at (g x)) \\<Longrightarrow> g differentiable (at x within s) \\<Longrightarrow>\n    (\\<lambda>x. f (g x)) differentiable (at x within s)\"\n  by (blast intro: differentiable_in_compose differentiable_subset)\n\nlemma differentiable_sum [simp, derivative_intros]:\n  \"f differentiable F \\<Longrightarrow> g differentiable F \\<Longrightarrow> (\\<lambda>x. f x + g x) differentiable F\"\n  unfolding differentiable_def by (blast intro: has_derivative_add)\n\nlemma differentiable_minus [simp, derivative_intros]:\n  \"f differentiable F \\<Longrightarrow> (\\<lambda>x. - f x) differentiable F\"\n  unfolding differentiable_def by (blast intro: has_derivative_minus)\n\nlemma differentiable_diff [simp, derivative_intros]:\n  \"f differentiable F \\<Longrightarrow> g differentiable F \\<Longrightarrow> (\\<lambda>x. f x - g x) differentiable F\"\n  unfolding differentiable_def by (blast intro: has_derivative_diff)\n\nlemma differentiable_mult [simp, derivative_intros]:\n  fixes f g :: \"'a::real_normed_vector \\<Rightarrow> 'b::real_normed_algebra\"\n  shows \"f differentiable (at x within s) \\<Longrightarrow> g differentiable (at x within s) \\<Longrightarrow>\n    (\\<lambda>x. f x * g x) differentiable (at x within s)\"\n  unfolding differentiable_def by (blast intro: has_derivative_mult)\n\nlemma differentiable_inverse [simp, derivative_intros]:\n  fixes f :: \"'a::real_normed_vector \\<Rightarrow> 'b::real_normed_field\"\n  shows \"f differentiable (at x within s) \\<Longrightarrow> f x \\<noteq> 0 \\<Longrightarrow>\n    (\\<lambda>x. inverse (f x)) differentiable (at x within s)\"\n  unfolding differentiable_def by (blast intro: has_derivative_inverse)\n\nlemma differentiable_divide [simp, derivative_intros]:\n  fixes f g :: \"'a::real_normed_vector \\<Rightarrow> 'b::real_normed_field\"\n  shows \"f differentiable (at x within s) \\<Longrightarrow> g differentiable (at x within s) \\<Longrightarrow>\n    g x \\<noteq> 0 \\<Longrightarrow> (\\<lambda>x. f x / g x) differentiable (at x within s)\"\n  unfolding divide_inverse by simp\n\nlemma differentiable_power [simp, derivative_intros]:\n  fixes f g :: \"'a::real_normed_vector \\<Rightarrow> 'b::real_normed_field\"\n  shows \"f differentiable (at x within s) \\<Longrightarrow> (\\<lambda>x. f x ^ n) differentiable (at x within s)\"\n  unfolding differentiable_def by (blast intro: has_derivative_power)\n\nlemma differentiable_scaleR [simp, derivative_intros]:\n  \"f differentiable (at x within s) \\<Longrightarrow> g differentiable (at x within s) \\<Longrightarrow>\n    (\\<lambda>x. f x *\\<^sub>R g x) differentiable (at x within s)\"\n  unfolding differentiable_def by (blast intro: has_derivative_scaleR)\n\nlemma has_derivative_imp_has_field_derivative:\n  \"(f has_derivative D) F \\<Longrightarrow> (\\<And>x. x * D' = D x) \\<Longrightarrow> (f has_field_derivative D') F\"\n  unfolding has_field_derivative_def\n  by (rule has_derivative_eq_rhs[of f D]) (simp_all add: fun_eq_iff mult.commute)\n\nlemma has_field_derivative_imp_has_derivative:\n  \"(f has_field_derivative D) F \\<Longrightarrow> (f has_derivative op * D) F\"\n  by (simp add: has_field_derivative_def)\n\nlemma DERIV_subset:\n  \"(f has_field_derivative f') (at x within s) \\<Longrightarrow> t \\<subseteq> s \\<Longrightarrow>\n    (f has_field_derivative f') (at x within t)\"\n  by (simp add: has_field_derivative_def has_derivative_within_subset)\n\nlemma has_field_derivative_at_within:\n  \"(f has_field_derivative f') (at x) \\<Longrightarrow> (f has_field_derivative f') (at x within s)\"\n  using DERIV_subset by blast\n\nabbreviation (input)\n  DERIV :: \"('a::real_normed_field \\<Rightarrow> 'a) \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> bool\"\n    (\"(DERIV (_)/ (_)/ :> (_))\" [1000, 1000, 60] 60)\n  where \"DERIV f x :> D \\<equiv> (f has_field_derivative D) (at x)\"\n\nabbreviation has_real_derivative :: \"(real \\<Rightarrow> real) \\<Rightarrow> real \\<Rightarrow> real filter \\<Rightarrow> bool\"\n    (infix \"(has'_real'_derivative)\" 50)\n  where \"(f has_real_derivative D) F \\<equiv> (f has_field_derivative D) F\"\n\nlemma real_differentiable_def:\n  \"f differentiable at x within s \\<longleftrightarrow> (\\<exists>D. (f has_real_derivative D) (at x within s))\"\nproof safe\n  assume \"f differentiable at x within s\"\n  then obtain f' where *: \"(f has_derivative f') (at x within s)\"\n    unfolding differentiable_def by auto\n  then obtain c where \"f' = (op * c)\"\n    by (metis real_bounded_linear has_derivative_bounded_linear mult.commute fun_eq_iff)\n  with * show \"\\<exists>D. (f has_real_derivative D) (at x within s)\"\n    unfolding has_field_derivative_def by auto\nqed (auto simp: differentiable_def has_field_derivative_def)\n\nlemma real_differentiableE [elim?]:\n  assumes f: \"f differentiable (at x within s)\"\n  obtains df where \"(f has_real_derivative df) (at x within s)\"\n  using assms by (auto simp: real_differentiable_def)\n\nlemma differentiableD:\n  \"f differentiable (at x within s) \\<Longrightarrow> \\<exists>D. (f has_real_derivative D) (at x within s)\"\n  by (auto elim: real_differentiableE)\n\nlemma differentiableI:\n  \"(f has_real_derivative D) (at x within s) \\<Longrightarrow> f differentiable (at x within s)\"\n  by (force simp add: real_differentiable_def)\n\nlemma has_field_derivative_iff:\n  \"(f has_field_derivative D) (at x within S) \\<longleftrightarrow>\n    ((\\<lambda>y. (f y - f x) / (y - x)) \\<longlongrightarrow> D) (at x within S)\"\n  apply (simp add: has_field_derivative_def has_derivative_iff_norm bounded_linear_mult_right\n      LIM_zero_iff[symmetric, of _ D])\n  apply (subst (2) tendsto_norm_zero_iff[symmetric])\n  apply (rule filterlim_cong)\n    apply (simp_all add: eventually_at_filter field_simps nonzero_norm_divide)\n  done\n\nlemma DERIV_def: \"DERIV f x :> D \\<longleftrightarrow> (\\<lambda>h. (f (x + h) - f x) / h) \\<midarrow>0\\<rightarrow> D\"\n  unfolding field_has_derivative_at has_field_derivative_def has_field_derivative_iff ..\n\nlemma mult_commute_abs: \"(\\<lambda>x. x * c) = op * c\"\n  for c :: \"'a::ab_semigroup_mult\"\n  by (simp add: fun_eq_iff mult.commute)\n\n\nsubsection \\<open>Vector derivative\\<close>\n\nlemma has_field_derivative_iff_has_vector_derivative:\n  \"(f has_field_derivative y) F \\<longleftrightarrow> (f has_vector_derivative y) F\"\n  unfolding has_vector_derivative_def has_field_derivative_def real_scaleR_def mult_commute_abs ..\n\nlemma has_field_derivative_subset:\n  \"(f has_field_derivative y) (at x within s) \\<Longrightarrow> t \\<subseteq> s \\<Longrightarrow>\n    (f has_field_derivative y) (at x within t)\"\n  unfolding has_field_derivative_def by (rule has_derivative_subset)\n\nlemma has_vector_derivative_const[simp, derivative_intros]: \"((\\<lambda>x. c) has_vector_derivative 0) net\"\n  by (auto simp: has_vector_derivative_def)\n\nlemma has_vector_derivative_id[simp, derivative_intros]: \"((\\<lambda>x. x) has_vector_derivative 1) net\"\n  by (auto simp: has_vector_derivative_def)\n\nlemma has_vector_derivative_minus[derivative_intros]:\n  \"(f has_vector_derivative f') net \\<Longrightarrow> ((\\<lambda>x. - f x) has_vector_derivative (- f')) net\"\n  by (auto simp: has_vector_derivative_def)\n\nlemma has_vector_derivative_add[derivative_intros]:\n  \"(f has_vector_derivative f') net \\<Longrightarrow> (g has_vector_derivative g') net \\<Longrightarrow>\n    ((\\<lambda>x. f x + g x) has_vector_derivative (f' + g')) net\"\n  by (auto simp: has_vector_derivative_def scaleR_right_distrib)\n\nlemma has_vector_derivative_sum[derivative_intros]:\n  \"(\\<And>i. i \\<in> I \\<Longrightarrow> (f i has_vector_derivative f' i) net) \\<Longrightarrow>\n    ((\\<lambda>x. \\<Sum>i\\<in>I. f i x) has_vector_derivative (\\<Sum>i\\<in>I. f' i)) net\"\n  by (auto simp: has_vector_derivative_def fun_eq_iff scaleR_sum_right intro!: derivative_eq_intros)\n\nlemma has_vector_derivative_diff[derivative_intros]:\n  \"(f has_vector_derivative f') net \\<Longrightarrow> (g has_vector_derivative g') net \\<Longrightarrow>\n    ((\\<lambda>x. f x - g x) has_vector_derivative (f' - g')) net\"\n  by (auto simp: has_vector_derivative_def scaleR_diff_right)\n\nlemma has_vector_derivative_add_const:\n  \"((\\<lambda>t. g t + z) has_vector_derivative f') net = ((\\<lambda>t. g t) has_vector_derivative f') net\"\n  apply (intro iffI)\n   apply (drule has_vector_derivative_diff [where g = \"\\<lambda>t. z\", OF _ has_vector_derivative_const])\n   apply simp\n  apply (drule has_vector_derivative_add [OF _ has_vector_derivative_const])\n  apply simp\n  done\n\nlemma has_vector_derivative_diff_const:\n  \"((\\<lambda>t. g t - z) has_vector_derivative f') net = ((\\<lambda>t. g t) has_vector_derivative f') net\"\n  using has_vector_derivative_add_const [where z = \"-z\"]\n  by simp\n\nlemma (in bounded_linear) has_vector_derivative:\n  assumes \"(g has_vector_derivative g') F\"\n  shows \"((\\<lambda>x. f (g x)) has_vector_derivative f g') F\"\n  using has_derivative[OF assms[unfolded has_vector_derivative_def]]\n  by (simp add: has_vector_derivative_def scaleR)\n\nlemma (in bounded_bilinear) has_vector_derivative:\n  assumes \"(f has_vector_derivative f') (at x within s)\"\n    and \"(g has_vector_derivative g') (at x within s)\"\n  shows \"((\\<lambda>x. f x ** g x) has_vector_derivative (f x ** g' + f' ** g x)) (at x within s)\"\n  using FDERIV[OF assms(1-2)[unfolded has_vector_derivative_def]]\n  by (simp add: has_vector_derivative_def scaleR_right scaleR_left scaleR_right_distrib)\n\nlemma has_vector_derivative_scaleR[derivative_intros]:\n  \"(f has_field_derivative f') (at x within s) \\<Longrightarrow> (g has_vector_derivative g') (at x within s) \\<Longrightarrow>\n    ((\\<lambda>x. f x *\\<^sub>R g x) has_vector_derivative (f x *\\<^sub>R g' + f' *\\<^sub>R g x)) (at x within s)\"\n  unfolding has_field_derivative_iff_has_vector_derivative\n  by (rule bounded_bilinear.has_vector_derivative[OF bounded_bilinear_scaleR])\n\nlemma has_vector_derivative_mult[derivative_intros]:\n  \"(f has_vector_derivative f') (at x within s) \\<Longrightarrow> (g has_vector_derivative g') (at x within s) \\<Longrightarrow>\n    ((\\<lambda>x. f x * g x) has_vector_derivative (f x * g' + f' * g x)) (at x within s)\"\n  for f g :: \"real \\<Rightarrow> 'a::real_normed_algebra\"\n  by (rule bounded_bilinear.has_vector_derivative[OF bounded_bilinear_mult])\n\nlemma has_vector_derivative_of_real[derivative_intros]:\n  \"(f has_field_derivative D) F \\<Longrightarrow> ((\\<lambda>x. of_real (f x)) has_vector_derivative (of_real D)) F\"\n  by (rule bounded_linear.has_vector_derivative[OF bounded_linear_of_real])\n    (simp add: has_field_derivative_iff_has_vector_derivative)\n\nlemma has_vector_derivative_continuous:\n  \"(f has_vector_derivative D) (at x within s) \\<Longrightarrow> continuous (at x within s) f\"\n  by (auto intro: has_derivative_continuous simp: has_vector_derivative_def)\n\nlemma has_vector_derivative_mult_right[derivative_intros]:\n  fixes a :: \"'a::real_normed_algebra\"\n  shows \"(f has_vector_derivative x) F \\<Longrightarrow> ((\\<lambda>x. a * f x) has_vector_derivative (a * x)) F\"\n  by (rule bounded_linear.has_vector_derivative[OF bounded_linear_mult_right])\n\nlemma has_vector_derivative_mult_left[derivative_intros]:\n  fixes a :: \"'a::real_normed_algebra\"\n  shows \"(f has_vector_derivative x) F \\<Longrightarrow> ((\\<lambda>x. f x * a) has_vector_derivative (x * a)) F\"\n  by (rule bounded_linear.has_vector_derivative[OF bounded_linear_mult_left])\n\n\nsubsection \\<open>Derivatives\\<close>\n\nlemma DERIV_D: \"DERIV f x :> D \\<Longrightarrow> (\\<lambda>h. (f (x + h) - f x) / h) \\<midarrow>0\\<rightarrow> D\"\n  by (simp add: DERIV_def)\n\nlemma has_field_derivativeD:\n  \"(f has_field_derivative D) (at x within S) \\<Longrightarrow>\n    ((\\<lambda>y. (f y - f x) / (y - x)) \\<longlongrightarrow> D) (at x within S)\"\n  by (simp add: has_field_derivative_iff)\n\nlemma DERIV_const [simp, derivative_intros]: \"((\\<lambda>x. k) has_field_derivative 0) F\"\n  by (rule has_derivative_imp_has_field_derivative[OF has_derivative_const]) auto\n\nlemma DERIV_ident [simp, derivative_intros]: \"((\\<lambda>x. x) has_field_derivative 1) F\"\n  by (rule has_derivative_imp_has_field_derivative[OF has_derivative_ident]) auto\n\nlemma field_differentiable_add[derivative_intros]:\n  \"(f has_field_derivative f') F \\<Longrightarrow> (g has_field_derivative g') F \\<Longrightarrow>\n    ((\\<lambda>z. f z + g z) has_field_derivative f' + g') F\"\n  by (rule has_derivative_imp_has_field_derivative[OF has_derivative_add])\n     (auto simp: has_field_derivative_def field_simps mult_commute_abs)\n\ncorollary DERIV_add:\n  \"(f has_field_derivative D) (at x within s) \\<Longrightarrow> (g has_field_derivative E) (at x within s) \\<Longrightarrow>\n    ((\\<lambda>x. f x + g x) has_field_derivative D + E) (at x within s)\"\n  by (rule field_differentiable_add)\n\nlemma field_differentiable_minus[derivative_intros]:\n  \"(f has_field_derivative f') F \\<Longrightarrow> ((\\<lambda>z. - (f z)) has_field_derivative -f') F\"\n  by (rule has_derivative_imp_has_field_derivative[OF has_derivative_minus])\n     (auto simp: has_field_derivative_def field_simps mult_commute_abs)\n\ncorollary DERIV_minus:\n  \"(f has_field_derivative D) (at x within s) \\<Longrightarrow>\n    ((\\<lambda>x. - f x) has_field_derivative -D) (at x within s)\"\n  by (rule field_differentiable_minus)\n\nlemma field_differentiable_diff[derivative_intros]:\n  \"(f has_field_derivative f') F \\<Longrightarrow>\n    (g has_field_derivative g') F \\<Longrightarrow> ((\\<lambda>z. f z - g z) has_field_derivative f' - g') F\"\n  by (simp only: diff_conv_add_uminus field_differentiable_add field_differentiable_minus)\n\ncorollary DERIV_diff:\n  \"(f has_field_derivative D) (at x within s) \\<Longrightarrow>\n    (g has_field_derivative E) (at x within s) \\<Longrightarrow>\n    ((\\<lambda>x. f x - g x) has_field_derivative D - E) (at x within s)\"\n  by (rule field_differentiable_diff)\n\nlemma DERIV_continuous: \"(f has_field_derivative D) (at x within s) \\<Longrightarrow> continuous (at x within s) f\"\n  by (drule has_derivative_continuous[OF has_field_derivative_imp_has_derivative]) simp\n\ncorollary DERIV_isCont: \"DERIV f x :> D \\<Longrightarrow> isCont f x\"\n  by (rule DERIV_continuous)\n\nlemma DERIV_continuous_on:\n  \"(\\<And>x. x \\<in> s \\<Longrightarrow> (f has_field_derivative (D x)) (at x within s)) \\<Longrightarrow> continuous_on s f\"\n  unfolding continuous_on_eq_continuous_within\n  by (intro continuous_at_imp_continuous_on ballI DERIV_continuous)\n\nlemma DERIV_mult':\n  \"(f has_field_derivative D) (at x within s) \\<Longrightarrow> (g has_field_derivative E) (at x within s) \\<Longrightarrow>\n    ((\\<lambda>x. f x * g x) has_field_derivative f x * E + D * g x) (at x within s)\"\n  by (rule has_derivative_imp_has_field_derivative[OF has_derivative_mult])\n     (auto simp: field_simps mult_commute_abs dest: has_field_derivative_imp_has_derivative)\n\nlemma DERIV_mult[derivative_intros]:\n  \"(f has_field_derivative Da) (at x within s) \\<Longrightarrow> (g has_field_derivative Db) (at x within s) \\<Longrightarrow>\n    ((\\<lambda>x. f x * g x) has_field_derivative Da * g x + Db * f x) (at x within s)\"\n  by (rule has_derivative_imp_has_field_derivative[OF has_derivative_mult])\n     (auto simp: field_simps dest: has_field_derivative_imp_has_derivative)\n\ntext \\<open>Derivative of linear multiplication\\<close>\n\nlemma DERIV_cmult:\n  \"(f has_field_derivative D) (at x within s) \\<Longrightarrow>\n    ((\\<lambda>x. c * f x) has_field_derivative c * D) (at x within s)\"\n  by (drule DERIV_mult' [OF DERIV_const]) simp\n\nlemma DERIV_cmult_right:\n  \"(f has_field_derivative D) (at x within s) \\<Longrightarrow>\n    ((\\<lambda>x. f x * c) has_field_derivative D * c) (at x within s)\"\n  using DERIV_cmult by (auto simp add: ac_simps)\n\nlemma DERIV_cmult_Id [simp]: \"(op * c has_field_derivative c) (at x within s)\"\n  using DERIV_ident [THEN DERIV_cmult, where c = c and x = x] by simp\n\nlemma DERIV_cdivide:\n  \"(f has_field_derivative D) (at x within s) \\<Longrightarrow>\n    ((\\<lambda>x. f x / c) has_field_derivative D / c) (at x within s)\"\n  using DERIV_cmult_right[of f D x s \"1 / c\"] by simp\n\nlemma DERIV_unique: \"DERIV f x :> D \\<Longrightarrow> DERIV f x :> E \\<Longrightarrow> D = E\"\n  unfolding DERIV_def by (rule LIM_unique)\n\nlemma DERIV_sum[derivative_intros]:\n  \"(\\<And> n. n \\<in> S \\<Longrightarrow> ((\\<lambda>x. f x n) has_field_derivative (f' x n)) F) \\<Longrightarrow>\n    ((\\<lambda>x. sum (f x) S) has_field_derivative sum (f' x) S) F\"\n  by (rule has_derivative_imp_has_field_derivative [OF has_derivative_sum])\n     (auto simp: sum_distrib_left mult_commute_abs dest: has_field_derivative_imp_has_derivative)\n\nlemma DERIV_inverse'[derivative_intros]:\n  assumes \"(f has_field_derivative D) (at x within s)\"\n    and \"f x \\<noteq> 0\"\n  shows \"((\\<lambda>x. inverse (f x)) has_field_derivative - (inverse (f x) * D * inverse (f x)))\n    (at x within s)\"\nproof -\n  have \"(f has_derivative (\\<lambda>x. x * D)) = (f has_derivative op * D)\"\n    by (rule arg_cong [of \"\\<lambda>x. x * D\"]) (simp add: fun_eq_iff)\n  with assms have \"(f has_derivative (\\<lambda>x. x * D)) (at x within s)\"\n    by (auto dest!: has_field_derivative_imp_has_derivative)\n  then show ?thesis using \\<open>f x \\<noteq> 0\\<close>\n    by (auto intro: has_derivative_imp_has_field_derivative has_derivative_inverse)\nqed\n\ntext \\<open>Power of \\<open>-1\\<close>\\<close>\n\nlemma DERIV_inverse:\n  \"x \\<noteq> 0 \\<Longrightarrow> ((\\<lambda>x. inverse(x)) has_field_derivative - (inverse x ^ Suc (Suc 0))) (at x within s)\"\n  by (drule DERIV_inverse' [OF DERIV_ident]) simp\n\ntext \\<open>Derivative of inverse\\<close>\n\nlemma DERIV_inverse_fun:\n  \"(f has_field_derivative d) (at x within s) \\<Longrightarrow> f x \\<noteq> 0 \\<Longrightarrow>\n    ((\\<lambda>x. inverse (f x)) has_field_derivative (- (d * inverse(f x ^ Suc (Suc 0))))) (at x within s)\"\n  by (drule (1) DERIV_inverse') (simp add: ac_simps nonzero_inverse_mult_distrib)\n\ntext \\<open>Derivative of quotient\\<close>\n\nlemma DERIV_divide[derivative_intros]:\n  \"(f has_field_derivative D) (at x within s) \\<Longrightarrow>\n    (g has_field_derivative E) (at x within s) \\<Longrightarrow> g x \\<noteq> 0 \\<Longrightarrow>\n    ((\\<lambda>x. f x / g x) has_field_derivative (D * g x - f x * E) / (g x * g x)) (at x within s)\"\n  by (rule has_derivative_imp_has_field_derivative[OF has_derivative_divide])\n     (auto dest: has_field_derivative_imp_has_derivative simp: field_simps)\n\nlemma DERIV_quotient:\n  \"(f has_field_derivative d) (at x within s) \\<Longrightarrow>\n    (g has_field_derivative e) (at x within s)\\<Longrightarrow> g x \\<noteq> 0 \\<Longrightarrow>\n    ((\\<lambda>y. f y / g y) has_field_derivative (d * g x - (e * f x)) / (g x ^ Suc (Suc 0))) (at x within s)\"\n  by (drule (2) DERIV_divide) (simp add: mult.commute)\n\nlemma DERIV_power_Suc:\n  \"(f has_field_derivative D) (at x within s) \\<Longrightarrow>\n    ((\\<lambda>x. f x ^ Suc n) has_field_derivative (1 + of_nat n) * (D * f x ^ n)) (at x within s)\"\n  by (rule has_derivative_imp_has_field_derivative[OF has_derivative_power])\n     (auto simp: has_field_derivative_def)\n\nlemma DERIV_power[derivative_intros]:\n  \"(f has_field_derivative D) (at x within s) \\<Longrightarrow>\n    ((\\<lambda>x. f x ^ n) has_field_derivative of_nat n * (D * f x ^ (n - Suc 0))) (at x within s)\"\n  by (rule has_derivative_imp_has_field_derivative[OF has_derivative_power])\n     (auto simp: has_field_derivative_def)\n\nlemma DERIV_pow: \"((\\<lambda>x. x ^ n) has_field_derivative real n * (x ^ (n - Suc 0))) (at x within s)\"\n  using DERIV_power [OF DERIV_ident] by simp\n\nlemma DERIV_chain': \"(f has_field_derivative D) (at x within s) \\<Longrightarrow> DERIV g (f x) :> E \\<Longrightarrow>\n  ((\\<lambda>x. g (f x)) has_field_derivative E * D) (at x within s)\"\n  using has_derivative_compose[of f \"op * D\" x s g \"op * E\"]\n  by (simp only: has_field_derivative_def mult_commute_abs ac_simps)\n\ncorollary DERIV_chain2: \"DERIV f (g x) :> Da \\<Longrightarrow> (g has_field_derivative Db) (at x within s) \\<Longrightarrow>\n  ((\\<lambda>x. f (g x)) has_field_derivative Da * Db) (at x within s)\"\n  by (rule DERIV_chain')\n\ntext \\<open>Standard version\\<close>\n\nlemma DERIV_chain:\n  \"DERIV f (g x) :> Da \\<Longrightarrow> (g has_field_derivative Db) (at x within s) \\<Longrightarrow>\n    (f \\<circ> g has_field_derivative Da * Db) (at x within s)\"\n  by (drule (1) DERIV_chain', simp add: o_def mult.commute)\n\nlemma DERIV_image_chain:\n  \"(f has_field_derivative Da) (at (g x) within (g ` s)) \\<Longrightarrow>\n    (g has_field_derivative Db) (at x within s) \\<Longrightarrow>\n    (f \\<circ> g has_field_derivative Da * Db) (at x within s)\"\n  using has_derivative_in_compose [of g \"op * Db\" x s f \"op * Da \"]\n  by (simp add: has_field_derivative_def o_def mult_commute_abs ac_simps)\n\n(*These two are from HOL Light: HAS_COMPLEX_DERIVATIVE_CHAIN*)\nlemma DERIV_chain_s:\n  assumes \"(\\<And>x. x \\<in> s \\<Longrightarrow> DERIV g x :> g'(x))\"\n    and \"DERIV f x :> f'\"\n    and \"f x \\<in> s\"\n  shows \"DERIV (\\<lambda>x. g(f x)) x :> f' * g'(f x)\"\n  by (metis (full_types) DERIV_chain' mult.commute assms)\n\nlemma DERIV_chain3: (*HAS_COMPLEX_DERIVATIVE_CHAIN_UNIV*)\n  assumes \"(\\<And>x. DERIV g x :> g'(x))\"\n    and \"DERIV f x :> f'\"\n  shows \"DERIV (\\<lambda>x. g(f x)) x :> f' * g'(f x)\"\n  by (metis UNIV_I DERIV_chain_s [of UNIV] assms)\n\ntext \\<open>Alternative definition for differentiability\\<close>\n\nlemma DERIV_LIM_iff:\n  fixes f :: \"'a::{real_normed_vector,inverse} \\<Rightarrow> 'a\"\n  shows \"((\\<lambda>h. (f (a + h) - f a) / h) \\<midarrow>0\\<rightarrow> D) = ((\\<lambda>x. (f x - f a) / (x - a)) \\<midarrow>a\\<rightarrow> D)\"\n  apply (rule iffI)\n   apply (drule_tac k=\"- a\" in LIM_offset)\n   apply simp\n  apply (drule_tac k=\"a\" in LIM_offset)\n  apply (simp add: add.commute)\n  done\n\nlemmas DERIV_iff2 = has_field_derivative_iff\n\nlemma has_field_derivative_cong_ev:\n  assumes \"x = y\"\n    and *: \"eventually (\\<lambda>x. x \\<in> s \\<longrightarrow> f x = g x) (nhds x)\"\n    and \"u = v\" \"s = t\" \"x \\<in> s\"\n  shows \"(f has_field_derivative u) (at x within s) = (g has_field_derivative v) (at y within t)\"\n  unfolding DERIV_iff2\nproof (rule filterlim_cong)\n  from assms have \"f y = g y\"\n    by (auto simp: eventually_nhds)\n  with * show \"\\<forall>\\<^sub>F xa in at x within s. (f xa - f x) / (xa - x) = (g xa - g y) / (xa - y)\"\n    unfolding eventually_at_filter\n    by eventually_elim (auto simp: assms \\<open>f y = g y\\<close>)\nqed (simp_all add: assms)\n\nlemma DERIV_cong_ev:\n  \"x = y \\<Longrightarrow> eventually (\\<lambda>x. f x = g x) (nhds x) \\<Longrightarrow> u = v \\<Longrightarrow>\n    DERIV f x :> u \\<longleftrightarrow> DERIV g y :> v\"\n  by (rule has_field_derivative_cong_ev) simp_all\n\nlemma DERIV_shift:\n  \"(f has_field_derivative y) (at (x + z)) = ((\\<lambda>x. f (x + z)) has_field_derivative y) (at x)\"\n  by (simp add: DERIV_def field_simps)\n\nlemma DERIV_mirror: \"(DERIV f (- x) :> y) \\<longleftrightarrow> (DERIV (\\<lambda>x. f (- x)) x :> - y)\"\n  for f :: \"real \\<Rightarrow> real\" and x y :: real\n  by (simp add: DERIV_def filterlim_at_split filterlim_at_left_to_right\n      tendsto_minus_cancel_left field_simps conj_commute)\n\nlemma floor_has_real_derivative:\n  fixes f :: \"real \\<Rightarrow> 'a::{floor_ceiling,order_topology}\"\n  assumes \"isCont f x\"\n    and \"f x \\<notin> \\<int>\"\n  shows \"((\\<lambda>x. floor (f x)) has_real_derivative 0) (at x)\"\nproof (subst DERIV_cong_ev[OF refl _ refl])\n  show \"((\\<lambda>_. floor (f x)) has_real_derivative 0) (at x)\"\n    by simp\n  have \"\\<forall>\\<^sub>F y in at x. \\<lfloor>f y\\<rfloor> = \\<lfloor>f x\\<rfloor>\"\n    by (rule eventually_floor_eq[OF assms[unfolded continuous_at]])\n  then show \"\\<forall>\\<^sub>F y in nhds x. real_of_int \\<lfloor>f y\\<rfloor> = real_of_int \\<lfloor>f x\\<rfloor>\"\n    unfolding eventually_at_filter\n    by eventually_elim auto\nqed\n\n\ntext \\<open>Caratheodory formulation of derivative at a point\\<close>\n\nlemma CARAT_DERIV: (*FIXME: SUPERSEDED BY THE ONE IN Deriv.thy. But still used by NSA/HDeriv.thy*)\n  \"(DERIV f x :> l) \\<longleftrightarrow> (\\<exists>g. (\\<forall>z. f z - f x = g z * (z - x)) \\<and> isCont g x \\<and> g x = l)\"\n  (is \"?lhs = ?rhs\")\nproof\n  assume ?lhs\n  show \"\\<exists>g. (\\<forall>z. f z - f x = g z * (z - x)) \\<and> isCont g x \\<and> g x = l\"\n  proof (intro exI conjI)\n    let ?g = \"(\\<lambda>z. if z = x then l else (f z - f x) / (z-x))\"\n    show \"\\<forall>z. f z - f x = ?g z * (z - x)\"\n      by simp\n    show \"isCont ?g x\"\n      using \\<open>?lhs\\<close> by (simp add: isCont_iff DERIV_def cong: LIM_equal [rule_format])\n    show \"?g x = l\"\n      by simp\n  qed\nnext\n  assume ?rhs\n  then obtain g where \"(\\<forall>z. f z - f x = g z * (z - x))\" and \"isCont g x\" and \"g x = l\"\n    by blast\n  then show ?lhs\n    by (auto simp add: isCont_iff DERIV_def cong: LIM_cong)\nqed\n\n\nsubsection \\<open>Local extrema\\<close>\n\ntext \\<open>If @{term \"0 < f' x\"} then @{term x} is Locally Strictly Increasing At The Right.\\<close>\n\nlemma has_real_derivative_pos_inc_right:\n  fixes f :: \"real \\<Rightarrow> real\"\n  assumes der: \"(f has_real_derivative l) (at x within S)\"\n    and l: \"0 < l\"\n  shows \"\\<exists>d > 0. \\<forall>h > 0. x + h \\<in> S \\<longrightarrow> h < d \\<longrightarrow> f x < f (x + h)\"\n  using assms\nproof -\n  from der [THEN has_field_derivativeD, THEN tendstoD, OF l, unfolded eventually_at]\n  obtain s where s: \"0 < s\"\n    and all: \"\\<And>xa. xa\\<in>S \\<Longrightarrow> xa \\<noteq> x \\<and> dist xa x < s \\<longrightarrow> \\<bar>(f xa - f x) / (xa - x) - l\\<bar> < l\"\n    by (auto simp: dist_real_def)\n  then show ?thesis\n  proof (intro exI conjI strip)\n    show \"0 < s\" by (rule s)\n  next\n    fix h :: real\n    assume \"0 < h\" \"h < s\" \"x + h \\<in> S\"\n    with all [of \"x + h\"] show \"f x < f (x+h)\"\n    proof (simp add: abs_if dist_real_def pos_less_divide_eq split: if_split_asm)\n      assume \"\\<not> (f (x + h) - f x) / h < l\" and h: \"0 < h\"\n      with l have \"0 < (f (x + h) - f x) / h\"\n        by arith\n      then show \"f x < f (x + h)\"\n        by (simp add: pos_less_divide_eq h)\n    qed\n  qed\nqed\n\nlemma DERIV_pos_inc_right:\n  fixes f :: \"real \\<Rightarrow> real\"\n  assumes der: \"DERIV f x :> l\"\n    and l: \"0 < l\"\n  shows \"\\<exists>d > 0. \\<forall>h > 0. h < d \\<longrightarrow> f x < f (x + h)\"\n  using has_real_derivative_pos_inc_right[OF assms]\n  by auto\n\nlemma has_real_derivative_neg_dec_left:\n  fixes f :: \"real \\<Rightarrow> real\"\n  assumes der: \"(f has_real_derivative l) (at x within S)\"\n    and \"l < 0\"\n  shows \"\\<exists>d > 0. \\<forall>h > 0. x - h \\<in> S \\<longrightarrow> h < d \\<longrightarrow> f x < f (x - h)\"\nproof -\n  from \\<open>l < 0\\<close> have l: \"- l > 0\"\n    by simp\n  from der [THEN has_field_derivativeD, THEN tendstoD, OF l, unfolded eventually_at]\n  obtain s where s: \"0 < s\"\n    and all: \"\\<And>xa. xa\\<in>S \\<Longrightarrow> xa \\<noteq> x \\<and> dist xa x < s \\<longrightarrow> \\<bar>(f xa - f x) / (xa - x) - l\\<bar> < - l\"\n    by (auto simp: dist_real_def)\n  then show ?thesis\n  proof (intro exI conjI strip)\n    show \"0 < s\" by (rule s)\n  next\n    fix h :: real\n    assume \"0 < h\" \"h < s\" \"x - h \\<in> S\"\n    with all [of \"x - h\"] show \"f x < f (x-h)\"\n    proof (simp add: abs_if pos_less_divide_eq dist_real_def split: if_split_asm)\n      assume \"- ((f (x-h) - f x) / h) < l\" and h: \"0 < h\"\n      with l have \"0 < (f (x-h) - f x) / h\"\n        by arith\n      then show \"f x < f (x - h)\"\n        by (simp add: pos_less_divide_eq h)\n    qed\n  qed\nqed\n\nlemma DERIV_neg_dec_left:\n  fixes f :: \"real \\<Rightarrow> real\"\n  assumes der: \"DERIV f x :> l\"\n    and l: \"l < 0\"\n  shows \"\\<exists>d > 0. \\<forall>h > 0. h < d \\<longrightarrow> f x < f (x - h)\"\n  using has_real_derivative_neg_dec_left[OF assms]\n  by auto\n\nlemma has_real_derivative_pos_inc_left:\n  fixes f :: \"real \\<Rightarrow> real\"\n  shows \"(f has_real_derivative l) (at x within S) \\<Longrightarrow> 0 < l \\<Longrightarrow>\n    \\<exists>d>0. \\<forall>h>0. x - h \\<in> S \\<longrightarrow> h < d \\<longrightarrow> f (x - h) < f x\"\n  by (rule has_real_derivative_neg_dec_left [of \"\\<lambda>x. - f x\" \"-l\" x S, simplified])\n      (auto simp add: DERIV_minus)\n\nlemma DERIV_pos_inc_left:\n  fixes f :: \"real \\<Rightarrow> real\"\n  shows \"DERIV f x :> l \\<Longrightarrow> 0 < l \\<Longrightarrow> \\<exists>d > 0. \\<forall>h > 0. h < d \\<longrightarrow> f (x - h) < f x\"\n  using has_real_derivative_pos_inc_left\n  by blast\n\nlemma has_real_derivative_neg_dec_right:\n  fixes f :: \"real \\<Rightarrow> real\"\n  shows \"(f has_real_derivative l) (at x within S) \\<Longrightarrow> l < 0 \\<Longrightarrow>\n    \\<exists>d > 0. \\<forall>h > 0. x + h \\<in> S \\<longrightarrow> h < d \\<longrightarrow> f x > f (x + h)\"\n  by (rule has_real_derivative_pos_inc_right [of \"\\<lambda>x. - f x\" \"-l\" x S, simplified])\n      (auto simp add: DERIV_minus)\n\nlemma DERIV_neg_dec_right:\n  fixes f :: \"real \\<Rightarrow> real\"\n  shows \"DERIV f x :> l \\<Longrightarrow> l < 0 \\<Longrightarrow> \\<exists>d > 0. \\<forall>h > 0. h < d \\<longrightarrow> f x > f (x + h)\"\n  using has_real_derivative_neg_dec_right by blast\n\nlemma DERIV_local_max:\n  fixes f :: \"real \\<Rightarrow> real\"\n  assumes der: \"DERIV f x :> l\"\n    and d: \"0 < d\"\n    and le: \"\\<forall>y. \\<bar>x - y\\<bar> < d \\<longrightarrow> f y \\<le> f x\"\n  shows \"l = 0\"\nproof (cases rule: linorder_cases [of l 0])\n  case equal\n  then show ?thesis .\nnext\n  case less\n  from DERIV_neg_dec_left [OF der less]\n  obtain d' where d': \"0 < d'\" and lt: \"\\<forall>h > 0. h < d' \\<longrightarrow> f x < f (x - h)\"\n    by blast\n  obtain e where \"0 < e \\<and> e < d \\<and> e < d'\"\n    using real_lbound_gt_zero [OF d d']  ..\n  with lt le [THEN spec [where x=\"x - e\"]] show ?thesis\n    by (auto simp add: abs_if)\nnext\n  case greater\n  from DERIV_pos_inc_right [OF der greater]\n  obtain d' where d': \"0 < d'\" and lt: \"\\<forall>h > 0. h < d' \\<longrightarrow> f x < f (x + h)\"\n    by blast\n  obtain e where \"0 < e \\<and> e < d \\<and> e < d'\"\n    using real_lbound_gt_zero [OF d d'] ..\n  with lt le [THEN spec [where x=\"x + e\"]] show ?thesis\n    by (auto simp add: abs_if)\nqed\n\ntext \\<open>Similar theorem for a local minimum\\<close>\nlemma DERIV_local_min:\n  fixes f :: \"real \\<Rightarrow> real\"\n  shows \"DERIV f x :> l \\<Longrightarrow> 0 < d \\<Longrightarrow> \\<forall>y. \\<bar>x - y\\<bar> < d \\<longrightarrow> f x \\<le> f y \\<Longrightarrow> l = 0\"\n  by (drule DERIV_minus [THEN DERIV_local_max]) auto\n\n\ntext\\<open>In particular, if a function is locally flat\\<close>\nlemma DERIV_local_const:\n  fixes f :: \"real \\<Rightarrow> real\"\n  shows \"DERIV f x :> l \\<Longrightarrow> 0 < d \\<Longrightarrow> \\<forall>y. \\<bar>x - y\\<bar> < d \\<longrightarrow> f x = f y \\<Longrightarrow> l = 0\"\n  by (auto dest!: DERIV_local_max)\n\n\nsubsection \\<open>Rolle's Theorem\\<close>\n\ntext \\<open>Lemma about introducing open ball in open interval\\<close>\nlemma lemma_interval_lt: \"a < x \\<Longrightarrow> x < b \\<Longrightarrow> \\<exists>d. 0 < d \\<and> (\\<forall>y. \\<bar>x - y\\<bar> < d \\<longrightarrow> a < y \\<and> y < b)\"\n  for a b x :: real\n  apply (simp add: abs_less_iff)\n  apply (insert linorder_linear [of \"x - a\" \"b - x\"])\n  apply safe\n   apply (rule_tac x = \"x - a\" in exI)\n   apply (rule_tac [2] x = \"b - x\" in exI)\n   apply auto\n  done\n\nlemma lemma_interval: \"a < x \\<Longrightarrow> x < b \\<Longrightarrow> \\<exists>d. 0 < d \\<and> (\\<forall>y. \\<bar>x - y\\<bar> < d \\<longrightarrow> a \\<le> y \\<and> y \\<le> b)\"\n  for a b x :: real\n  apply (drule lemma_interval_lt)\n   apply auto\n  apply force\n  done\n\ntext \\<open>Rolle's Theorem.\n   If @{term f} is defined and continuous on the closed interval\n   \\<open>[a,b]\\<close> and differentiable on the open interval \\<open>(a,b)\\<close>,\n   and @{term \"f a = f b\"},\n   then there exists \\<open>x0 \\<in> (a,b)\\<close> such that @{term \"f' x0 = 0\"}\\<close>\ntheorem Rolle:\n  fixes a b :: real\n  assumes lt: \"a < b\"\n    and eq: \"f a = f b\"\n    and con: \"\\<forall>x. a \\<le> x \\<and> x \\<le> b \\<longrightarrow> isCont f x\"\n    and dif [rule_format]: \"\\<forall>x. a < x \\<and> x < b \\<longrightarrow> f differentiable (at x)\"\n  shows \"\\<exists>z. a < z \\<and> z < b \\<and> DERIV f z :> 0\"\nproof -\n  have le: \"a \\<le> b\"\n    using lt by simp\n  from isCont_eq_Ub [OF le con]\n  obtain x where x_max: \"\\<forall>z. a \\<le> z \\<and> z \\<le> b \\<longrightarrow> f z \\<le> f x\" and \"a \\<le> x\" \"x \\<le> b\"\n    by blast\n  from isCont_eq_Lb [OF le con]\n  obtain x' where x'_min: \"\\<forall>z. a \\<le> z \\<and> z \\<le> b \\<longrightarrow> f x' \\<le> f z\" and \"a \\<le> x'\" \"x' \\<le> b\"\n    by blast\n  consider \"a < x\" \"x < b\" | \"x = a \\<or> x = b\"\n    using \\<open>a \\<le> x\\<close> \\<open>x \\<le> b\\<close> by arith\n  then show ?thesis\n  proof cases\n    case 1\n    \\<comment>\\<open>@{term f} attains its maximum within the interval\\<close>\n    obtain d where d: \"0 < d\" and bound: \"\\<forall>y. \\<bar>x - y\\<bar> < d \\<longrightarrow> a \\<le> y \\<and> y \\<le> b\"\n      using lemma_interval [OF 1] by blast\n    then have bound': \"\\<forall>y. \\<bar>x - y\\<bar> < d \\<longrightarrow> f y \\<le> f x\"\n      using x_max by blast\n    obtain l where der: \"DERIV f x :> l\"\n      using differentiableD [OF dif [OF conjI [OF 1]]] ..\n    \\<comment>\\<open>the derivative at a local maximum is zero\\<close>\n    have \"l = 0\"\n      by (rule DERIV_local_max [OF der d bound'])\n    with 1 der show ?thesis by auto\n  next\n    case 2\n    then have fx: \"f b = f x\" by (auto simp add: eq)\n    consider \"a < x'\" \"x' < b\" | \"x' = a \\<or> x' = b\"\n      using \\<open>a \\<le> x'\\<close> \\<open>x' \\<le> b\\<close> by arith\n    then show ?thesis\n    proof cases\n      case 1\n        \\<comment> \\<open>@{term f} attains its minimum within the interval\\<close>\n      from lemma_interval [OF 1]\n      obtain d where d: \"0<d\" and bound: \"\\<forall>y. \\<bar>x'-y\\<bar> < d \\<longrightarrow> a \\<le> y \\<and> y \\<le> b\"\n        by blast\n      then have bound': \"\\<forall>y. \\<bar>x' - y\\<bar> < d \\<longrightarrow> f x' \\<le> f y\"\n        using x'_min by blast\n      from differentiableD [OF dif [OF conjI [OF 1]]]\n      obtain l where der: \"DERIV f x' :> l\" ..\n      have \"l = 0\" by (rule DERIV_local_min [OF der d bound'])\n        \\<comment> \\<open>the derivative at a local minimum is zero\\<close>\n      then show ?thesis using 1 der by auto\n    next\n      case 2\n        \\<comment> \\<open>@{term f} is constant throughout the interval\\<close>\n      then have fx': \"f b = f x'\" by (auto simp: eq)\n      from dense [OF lt] obtain r where r: \"a < r\" \"r < b\" by blast\n      obtain d where d: \"0 < d\" and bound: \"\\<forall>y. \\<bar>r - y\\<bar> < d \\<longrightarrow> a \\<le> y \\<and> y \\<le> b\"\n        using lemma_interval [OF r] by blast\n      have eq_fb: \"f z = f b\" if \"a \\<le> z\" and \"z \\<le> b\" for z\n      proof (rule order_antisym)\n        show \"f z \\<le> f b\" by (simp add: fx x_max that)\n        show \"f b \\<le> f z\" by (simp add: fx' x'_min that)\n      qed\n      have bound': \"\\<forall>y. \\<bar>r - y\\<bar> < d \\<longrightarrow> f r = f y\"\n      proof (intro strip)\n        fix y :: real\n        assume lt: \"\\<bar>r - y\\<bar> < d\"\n        then have \"f y = f b\" by (simp add: eq_fb bound)\n        then show \"f r = f y\" by (simp add: eq_fb r order_less_imp_le)\n      qed\n      obtain l where der: \"DERIV f r :> l\"\n        using differentiableD [OF dif [OF conjI [OF r]]] ..\n      have \"l = 0\"\n        by (rule DERIV_local_const [OF der d bound'])\n        \\<comment> \\<open>the derivative of a constant function is zero\\<close>\n      with r der show ?thesis by auto\n    qed\n  qed\nqed\n\n\nsubsection \\<open>Mean Value Theorem\\<close>\n\nlemma lemma_MVT: \"f a - (f b - f a) / (b - a) * a = f b - (f b - f a) / (b - a) * b\"\n  for a b :: real\n  by (cases \"a = b\") (simp_all add: field_simps)\n\ntheorem MVT:\n  fixes a b :: real\n  assumes lt: \"a < b\"\n    and con: \"\\<forall>x. a \\<le> x \\<and> x \\<le> b \\<longrightarrow> isCont f x\"\n    and dif [rule_format]: \"\\<forall>x. a < x \\<and> x < b \\<longrightarrow> f differentiable (at x)\"\n  shows \"\\<exists>l z. a < z \\<and> z < b \\<and> DERIV f z :> l \\<and> f b - f a = (b - a) * l\"\nproof -\n  let ?F = \"\\<lambda>x. f x - ((f b - f a) / (b - a)) * x\"\n  have cont_f: \"\\<forall>x. a \\<le> x \\<and> x \\<le> b \\<longrightarrow> isCont ?F x\"\n    using con by (fast intro: continuous_intros)\n  have dif_f: \"\\<forall>x. a < x \\<and> x < b \\<longrightarrow> ?F differentiable (at x)\"\n  proof clarify\n    fix x :: real\n    assume x: \"a < x\" \"x < b\"\n    obtain l where der: \"DERIV f x :> l\"\n      using differentiableD [OF dif [OF conjI [OF x]]] ..\n    show \"?F differentiable (at x)\"\n      by (rule differentiableI [where D = \"l - (f b - f a) / (b - a)\"],\n          blast intro: DERIV_diff DERIV_cmult_Id der)\n  qed\n  from Rolle [where f = ?F, OF lt lemma_MVT cont_f dif_f]\n  obtain z where z: \"a < z\" \"z < b\" and der: \"DERIV ?F z :> 0\"\n    by blast\n  have \"DERIV (\\<lambda>x. ((f b - f a) / (b - a)) * x) z :> (f b - f a) / (b - a)\"\n    by (rule DERIV_cmult_Id)\n  then have der_f: \"DERIV (\\<lambda>x. ?F x + (f b - f a) / (b - a) * x) z :> 0 + (f b - f a) / (b - a)\"\n    by (rule DERIV_add [OF der])\n  show ?thesis\n  proof (intro exI conjI)\n    show \"a < z\" and \"z < b\" using z .\n    show \"f b - f a = (b - a) * ((f b - f a) / (b - a))\" by simp\n    show \"DERIV f z :> ((f b - f a) / (b - a))\" using der_f by simp\n  qed\nqed\n\nlemma MVT2:\n  \"a < b \\<Longrightarrow> \\<forall>x. a \\<le> x \\<and> x \\<le> b \\<longrightarrow> DERIV f x :> f' x \\<Longrightarrow>\n    \\<exists>z::real. a < z \\<and> z < b \\<and> (f b - f a = (b - a) * f' z)\"\n  apply (drule MVT)\n    apply (blast intro: DERIV_isCont)\n   apply (force dest: order_less_imp_le simp add: real_differentiable_def)\n  apply (blast dest: DERIV_unique order_less_imp_le)\n  done\n\n\ntext \\<open>A function is constant if its derivative is 0 over an interval.\\<close>\n\nlemma DERIV_isconst_end:\n  fixes f :: \"real \\<Rightarrow> real\"\n  shows \"a < b \\<Longrightarrow>\n    \\<forall>x. a \\<le> x \\<and> x \\<le> b \\<longrightarrow> isCont f x \\<Longrightarrow>\n    \\<forall>x. a < x \\<and> x < b \\<longrightarrow> DERIV f x :> 0 \\<Longrightarrow> f b = f a\"\n  apply (drule (1) MVT)\n   apply (blast intro: differentiableI)\n  apply (auto dest!: DERIV_unique simp add: diff_eq_eq)\n  done\n\nlemma DERIV_isconst1:\n  fixes f :: \"real \\<Rightarrow> real\"\n  shows \"a < b \\<Longrightarrow>\n    \\<forall>x. a \\<le> x \\<and> x \\<le> b \\<longrightarrow> isCont f x \\<Longrightarrow>\n    \\<forall>x. a < x \\<and> x < b \\<longrightarrow> DERIV f x :> 0 \\<Longrightarrow>\n    \\<forall>x. a \\<le> x \\<and> x \\<le> b \\<longrightarrow> f x = f a\"\n  apply safe\n  apply (drule_tac x = a in order_le_imp_less_or_eq)\n  apply safe\n  apply (drule_tac b = x in DERIV_isconst_end)\n    apply auto\n  done\n\nlemma DERIV_isconst2:\n  fixes f :: \"real \\<Rightarrow> real\"\n  shows \"a < b \\<Longrightarrow>\n    \\<forall>x. a \\<le> x \\<and> x \\<le> b \\<longrightarrow> isCont f x \\<Longrightarrow>\n    \\<forall>x. a < x \\<and> x < b \\<longrightarrow> DERIV f x :> 0 \\<Longrightarrow>\n    a \\<le> x \\<Longrightarrow> x \\<le> b \\<Longrightarrow> f x = f a\"\n  by (blast dest: DERIV_isconst1)\n\nlemma DERIV_isconst3:\n  fixes a b x y :: real\n  assumes \"a < b\"\n    and \"x \\<in> {a <..< b}\"\n    and \"y \\<in> {a <..< b}\"\n    and derivable: \"\\<And>x. x \\<in> {a <..< b} \\<Longrightarrow> DERIV f x :> 0\"\n  shows \"f x = f y\"\nproof (cases \"x = y\")\n  case False\n  let ?a = \"min x y\"\n  let ?b = \"max x y\"\n\n  have \"\\<forall>z. ?a \\<le> z \\<and> z \\<le> ?b \\<longrightarrow> DERIV f z :> 0\"\n  proof (rule allI, rule impI)\n    fix z :: real\n    assume \"?a \\<le> z \\<and> z \\<le> ?b\"\n    then have \"a < z\" and \"z < b\"\n      using \\<open>x \\<in> {a <..< b}\\<close> and \\<open>y \\<in> {a <..< b}\\<close> by auto\n    then have \"z \\<in> {a<..<b}\" by auto\n    then show \"DERIV f z :> 0\" by (rule derivable)\n  qed\n  then have isCont: \"\\<forall>z. ?a \\<le> z \\<and> z \\<le> ?b \\<longrightarrow> isCont f z\"\n    and DERIV: \"\\<forall>z. ?a < z \\<and> z < ?b \\<longrightarrow> DERIV f z :> 0\"\n    using DERIV_isCont by auto\n\n  have \"?a < ?b\" using \\<open>x \\<noteq> y\\<close> by auto\n  from DERIV_isconst2[OF this isCont DERIV, of x] and DERIV_isconst2[OF this isCont DERIV, of y]\n  show ?thesis by auto\nqed auto\n\nlemma DERIV_isconst_all:\n  fixes f :: \"real \\<Rightarrow> real\"\n  shows \"\\<forall>x. DERIV f x :> 0 \\<Longrightarrow> f x = f y\"\n  apply (rule linorder_cases [of x y])\n    apply (blast intro: sym DERIV_isCont DERIV_isconst_end)+\n  done\n\nlemma DERIV_const_ratio_const:\n  fixes f :: \"real \\<Rightarrow> real\"\n  shows \"a \\<noteq> b \\<Longrightarrow> \\<forall>x. DERIV f x :> k \\<Longrightarrow> f b - f a = (b - a) * k\"\n  apply (rule linorder_cases [of a b])\n    apply auto\n   apply (drule_tac [!] f = f in MVT)\n       apply (auto dest: DERIV_isCont DERIV_unique simp: real_differentiable_def)\n  apply (auto dest: DERIV_unique simp: ring_distribs)\n  done\n\nlemma DERIV_const_ratio_const2:\n  fixes f :: \"real \\<Rightarrow> real\"\n  shows \"a \\<noteq> b \\<Longrightarrow> \\<forall>x. DERIV f x :> k \\<Longrightarrow> (f b - f a) / (b - a) = k\"\n  apply (rule_tac c1 = \"b-a\" in mult_right_cancel [THEN iffD1])\n   apply (auto dest!: DERIV_const_ratio_const simp add: mult.assoc)\n  done\n\nlemma real_average_minus_first [simp]: \"(a + b) / 2 - a = (b - a) / 2\"\n  for a b :: real\n  by simp\n\nlemma real_average_minus_second [simp]: \"(b + a) / 2 - a = (b - a) / 2\"\n  for a b :: real\n  by simp\n\ntext \\<open>Gallileo's \"trick\": average velocity = av. of end velocities.\\<close>\n\nlemma DERIV_const_average:\n  fixes v :: \"real \\<Rightarrow> real\"\n    and a b :: real\n  assumes neq: \"a \\<noteq> b\"\n    and der: \"\\<forall>x. DERIV v x :> k\"\n  shows \"v ((a + b) / 2) = (v a + v b) / 2\"\nproof (cases rule: linorder_cases [of a b])\n  case equal\n  with neq show ?thesis by simp\nnext\n  case less\n  have \"(v b - v a) / (b - a) = k\"\n    by (rule DERIV_const_ratio_const2 [OF neq der])\n  then have \"(b - a) * ((v b - v a) / (b - a)) = (b - a) * k\"\n    by simp\n  moreover have \"(v ((a + b) / 2) - v a) / ((a + b) / 2 - a) = k\"\n    by (rule DERIV_const_ratio_const2 [OF _ der]) (simp add: neq)\n  ultimately show ?thesis\n    using neq by force\nnext\n  case greater\n  have \"(v b - v a) / (b - a) = k\"\n    by (rule DERIV_const_ratio_const2 [OF neq der])\n  then have \"(b - a) * ((v b - v a) / (b - a)) = (b - a) * k\"\n    by simp\n  moreover have \" (v ((b + a) / 2) - v a) / ((b + a) / 2 - a) = k\"\n    by (rule DERIV_const_ratio_const2 [OF _ der]) (simp add: neq)\n  ultimately show ?thesis\n    using neq by (force simp add: add.commute)\nqed\n\ntext \\<open>\n  A function with positive derivative is increasing.\n  A simple proof using the MVT, by Jeremy Avigad. And variants.\n\\<close>\nlemma DERIV_pos_imp_increasing_open:\n  fixes a b :: real\n    and f :: \"real \\<Rightarrow> real\"\n  assumes \"a < b\"\n    and \"\\<And>x. a < x \\<Longrightarrow> x < b \\<Longrightarrow> (\\<exists>y. DERIV f x :> y \\<and> y > 0)\"\n    and con: \"\\<And>x. a \\<le> x \\<Longrightarrow> x \\<le> b \\<Longrightarrow> isCont f x\"\n  shows \"f a < f b\"\nproof (rule ccontr)\n  assume f: \"\\<not> ?thesis\"\n  have \"\\<exists>l z. a < z \\<and> z < b \\<and> DERIV f z :> l \\<and> f b - f a = (b - a) * l\"\n    by (rule MVT) (use assms Deriv.differentiableI in \\<open>force+\\<close>)\n  then obtain l z where z: \"a < z\" \"z < b\" \"DERIV f z :> l\" and \"f b - f a = (b - a) * l\"\n    by auto\n  with assms f have \"\\<not> l > 0\"\n    by (metis linorder_not_le mult_le_0_iff diff_le_0_iff_le)\n  with assms z show False\n    by (metis DERIV_unique)\nqed\n\nlemma DERIV_pos_imp_increasing:\n  fixes a b :: real\n    and f :: \"real \\<Rightarrow> real\"\n  assumes \"a < b\"\n    and \"\\<forall>x. a \\<le> x \\<and> x \\<le> b \\<longrightarrow> (\\<exists>y. DERIV f x :> y \\<and> y > 0)\"\n  shows \"f a < f b\"\n  by (metis DERIV_pos_imp_increasing_open [of a b f] assms DERIV_continuous less_imp_le)\n\nlemma DERIV_nonneg_imp_nondecreasing:\n  fixes a b :: real\n    and f :: \"real \\<Rightarrow> real\"\n  assumes \"a \\<le> b\"\n    and \"\\<forall>x. a \\<le> x \\<and> x \\<le> b \\<longrightarrow> (\\<exists>y. DERIV f x :> y \\<and> y \\<ge> 0)\"\n  shows \"f a \\<le> f b\"\nproof (rule ccontr, cases \"a = b\")\n  assume \"\\<not> ?thesis\" and \"a = b\"\n  then show False by auto\nnext\n  assume *: \"\\<not> ?thesis\"\n  assume \"a \\<noteq> b\"\n  with assms have \"\\<exists>l z. a < z \\<and> z < b \\<and> DERIV f z :> l \\<and> f b - f a = (b - a) * l\"\n    apply -\n    apply (rule MVT)\n      apply auto\n     apply (metis DERIV_isCont)\n    apply (metis differentiableI less_le)\n    done\n  then obtain l z where lz: \"a < z\" \"z < b\" \"DERIV f z :> l\" and **: \"f b - f a = (b - a) * l\"\n    by auto\n  with * have \"a < b\" \"f b < f a\" by auto\n  with ** have \"\\<not> l \\<ge> 0\" by (auto simp add: not_le algebra_simps)\n    (metis * add_le_cancel_right assms(1) less_eq_real_def mult_right_mono add_left_mono linear order_refl)\n  with assms lz show False\n    by (metis DERIV_unique order_less_imp_le)\nqed\n\nlemma DERIV_neg_imp_decreasing_open:\n  fixes a b :: real\n    and f :: \"real \\<Rightarrow> real\"\n  assumes \"a < b\"\n    and \"\\<And>x. a < x \\<Longrightarrow> x < b \\<Longrightarrow> (\\<exists>y. DERIV f x :> y \\<and> y < 0)\"\n    and con: \"\\<And>x. a \\<le> x \\<Longrightarrow> x \\<le> b \\<Longrightarrow> isCont f x\"\n  shows \"f a > f b\"\nproof -\n  have \"(\\<lambda>x. -f x) a < (\\<lambda>x. -f x) b\"\n    apply (rule DERIV_pos_imp_increasing_open [of a b \"\\<lambda>x. -f x\"])\n    using assms\n      apply auto\n    apply (metis field_differentiable_minus neg_0_less_iff_less)\n    done\n  then show ?thesis\n    by simp\nqed\n\nlemma DERIV_neg_imp_decreasing:\n  fixes a b :: real\n    and f :: \"real \\<Rightarrow> real\"\n  assumes \"a < b\"\n    and \"\\<forall>x. a \\<le> x \\<and> x \\<le> b \\<longrightarrow> (\\<exists>y. DERIV f x :> y \\<and> y < 0)\"\n  shows \"f a > f b\"\n  by (metis DERIV_neg_imp_decreasing_open [of a b f] assms DERIV_continuous less_imp_le)\n\nlemma DERIV_nonpos_imp_nonincreasing:\n  fixes a b :: real\n    and f :: \"real \\<Rightarrow> real\"\n  assumes \"a \\<le> b\"\n    and \"\\<forall>x. a \\<le> x \\<and> x \\<le> b \\<longrightarrow> (\\<exists>y. DERIV f x :> y \\<and> y \\<le> 0)\"\n  shows \"f a \\<ge> f b\"\nproof -\n  have \"(\\<lambda>x. -f x) a \\<le> (\\<lambda>x. -f x) b\"\n    apply (rule DERIV_nonneg_imp_nondecreasing [of a b \"\\<lambda>x. -f x\"])\n    using assms\n     apply auto\n    apply (metis DERIV_minus neg_0_le_iff_le)\n    done\n  then show ?thesis\n    by simp\nqed\n\nlemma DERIV_pos_imp_increasing_at_bot:\n  fixes f :: \"real \\<Rightarrow> real\"\n  assumes \"\\<And>x. x \\<le> b \\<Longrightarrow> (\\<exists>y. DERIV f x :> y \\<and> y > 0)\"\n    and lim: \"(f \\<longlongrightarrow> flim) at_bot\"\n  shows \"flim < f b\"\nproof -\n  have \"\\<exists>N. \\<forall>n\\<le>N. f n \\<le> f (b - 1)\"\n    apply (rule_tac x=\"b - 2\" in exI)\n    apply (force intro: order.strict_implies_order DERIV_pos_imp_increasing [where f=f] assms)\n    done\n  then have \"flim \\<le> f (b - 1)\"\n     by (auto simp: trivial_limit_at_bot_linorder eventually_at_bot_linorder tendsto_upperbound [OF lim])\n  also have \"\\<dots> < f b\"\n    by (force intro: DERIV_pos_imp_increasing [where f=f] assms)\n  finally show ?thesis .\nqed\n\nlemma DERIV_neg_imp_decreasing_at_top:\n  fixes f :: \"real \\<Rightarrow> real\"\n  assumes der: \"\\<And>x. x \\<ge> b \\<Longrightarrow> (\\<exists>y. DERIV f x :> y \\<and> y < 0)\"\n    and lim: \"(f \\<longlongrightarrow> flim) at_top\"\n  shows \"flim < f b\"\n  apply (rule DERIV_pos_imp_increasing_at_bot [where f = \"\\<lambda>i. f (-i)\" and b = \"-b\", simplified])\n   apply (metis DERIV_mirror der le_minus_iff neg_0_less_iff_less)\n  apply (metis filterlim_at_top_mirror lim)\n  done\n\ntext \\<open>Derivative of inverse function\\<close>\n\nlemma DERIV_inverse_function:\n  fixes f g :: \"real \\<Rightarrow> real\"\n  assumes der: \"DERIV f (g x) :> D\"\n    and neq: \"D \\<noteq> 0\"\n    and x: \"a < x\" \"x < b\"\n    and inj: \"\\<forall>y. a < y \\<and> y < b \\<longrightarrow> f (g y) = y\"\n    and cont: \"isCont g x\"\n  shows \"DERIV g x :> inverse D\"\nunfolding DERIV_iff2\nproof (rule LIM_equal2)\n  show \"0 < min (x - a) (b - x)\"\n    using x by arith\nnext\n  fix y\n  assume \"norm (y - x) < min (x - a) (b - x)\"\n  then have \"a < y\" and \"y < b\"\n    by (simp_all add: abs_less_iff)\n  then show \"(g y - g x) / (y - x) = inverse ((f (g y) - x) / (g y - g x))\"\n    by (simp add: inj)\nnext\n  have \"(\\<lambda>z. (f z - f (g x)) / (z - g x)) \\<midarrow>g x\\<rightarrow> D\"\n    by (rule der [unfolded DERIV_iff2])\n  then have 1: \"(\\<lambda>z. (f z - x) / (z - g x)) \\<midarrow>g x\\<rightarrow> D\"\n    using inj x by simp\n  have 2: \"\\<exists>d>0. \\<forall>y. y \\<noteq> x \\<and> norm (y - x) < d \\<longrightarrow> g y \\<noteq> g x\"\n  proof (rule exI, safe)\n    show \"0 < min (x - a) (b - x)\"\n      using x by simp\n  next\n    fix y\n    assume \"norm (y - x) < min (x - a) (b - x)\"\n    then have y: \"a < y\" \"y < b\"\n      by (simp_all add: abs_less_iff)\n    assume \"g y = g x\"\n    then have \"f (g y) = f (g x)\" by simp\n    then have \"y = x\" using inj y x by simp\n    also assume \"y \\<noteq> x\"\n    finally show False by simp\n  qed\n  have \"(\\<lambda>y. (f (g y) - x) / (g y - g x)) \\<midarrow>x\\<rightarrow> D\"\n    using cont 1 2 by (rule isCont_LIM_compose2)\n  then show \"(\\<lambda>y. inverse ((f (g y) - x) / (g y - g x))) \\<midarrow>x\\<rightarrow> inverse D\"\n    using neq by (rule tendsto_inverse)\nqed\n\nsubsection \\<open>Generalized Mean Value Theorem\\<close>\n\ntheorem GMVT:\n  fixes a b :: real\n  assumes alb: \"a < b\"\n    and fc: \"\\<forall>x. a \\<le> x \\<and> x \\<le> b \\<longrightarrow> isCont f x\"\n    and fd: \"\\<forall>x. a < x \\<and> x < b \\<longrightarrow> f differentiable (at x)\"\n    and gc: \"\\<forall>x. a \\<le> x \\<and> x \\<le> b \\<longrightarrow> isCont g x\"\n    and gd: \"\\<forall>x. a < x \\<and> x < b \\<longrightarrow> g differentiable (at x)\"\n  shows \"\\<exists>g'c f'c c.\n    DERIV g c :> g'c \\<and> DERIV f c :> f'c \\<and> a < c \\<and> c < b \\<and> (f b - f a) * g'c = (g b - g a) * f'c\"\nproof -\n  let ?h = \"\\<lambda>x. (f b - f a) * g x - (g b - g a) * f x\"\n  have \"\\<exists>l z. a < z \\<and> z < b \\<and> DERIV ?h z :> l \\<and> ?h b - ?h a = (b - a) * l\"\n  proof (rule MVT)\n    from assms show \"a < b\" by simp\n    show \"\\<forall>x. a \\<le> x \\<and> x \\<le> b \\<longrightarrow> isCont ?h x\"\n      using fc gc by simp\n    show \"\\<forall>x. a < x \\<and> x < b \\<longrightarrow> ?h differentiable (at x)\"\n      using fd gd by simp\n  qed\n  then obtain l where l: \"\\<exists>z. a < z \\<and> z < b \\<and> DERIV ?h z :> l \\<and> ?h b - ?h a = (b - a) * l\" ..\n  then obtain c where c: \"a < c \\<and> c < b \\<and> DERIV ?h c :> l \\<and> ?h b - ?h a = (b - a) * l\" ..\n\n  from c have cint: \"a < c \\<and> c < b\" by auto\n  with gd have \"g differentiable (at c)\" by simp\n  then have \"\\<exists>D. DERIV g c :> D\" by (rule differentiableD)\n  then obtain g'c where g'c: \"DERIV g c :> g'c\" ..\n\n  from c have \"a < c \\<and> c < b\" by auto\n  with fd have \"f differentiable (at c)\" by simp\n  then have \"\\<exists>D. DERIV f c :> D\" by (rule differentiableD)\n  then obtain f'c where f'c: \"DERIV f c :> f'c\" ..\n\n  from c have \"DERIV ?h c :> l\" by auto\n  moreover have \"DERIV ?h c :>  g'c * (f b - f a) - f'c * (g b - g a)\"\n    using g'c f'c by (auto intro!: derivative_eq_intros)\n  ultimately have leq: \"l =  g'c * (f b - f a) - f'c * (g b - g a)\" by (rule DERIV_unique)\n\n  have \"?h b - ?h a = (b - a) * (g'c * (f b - f a) - f'c * (g b - g a))\"\n  proof -\n    from c have \"?h b - ?h a = (b - a) * l\" by auto\n    also from leq have \"\\<dots> = (b - a) * (g'c * (f b - f a) - f'c * (g b - g a))\" by simp\n    finally show ?thesis by simp\n  qed\n  moreover have \"?h b - ?h a = 0\"\n  proof -\n    have \"?h b - ?h a =\n      ((f b)*(g b) - (f a)*(g b) - (g b)*(f b) + (g a)*(f b)) -\n      ((f b)*(g a) - (f a)*(g a) - (g b)*(f a) + (g a)*(f a))\"\n      by (simp add: algebra_simps)\n    then show ?thesis  by auto\n  qed\n  ultimately have \"(b - a) * (g'c * (f b - f a) - f'c * (g b - g a)) = 0\" by auto\n  with alb have \"g'c * (f b - f a) - f'c * (g b - g a) = 0\" by simp\n  then have \"g'c * (f b - f a) = f'c * (g b - g a)\" by simp\n  then have \"(f b - f a) * g'c = (g b - g a) * f'c\" by (simp add: ac_simps)\n  with g'c f'c cint show ?thesis by auto\nqed\n\nlemma GMVT':\n  fixes f g :: \"real \\<Rightarrow> real\"\n  assumes \"a < b\"\n    and isCont_f: \"\\<And>z. a \\<le> z \\<Longrightarrow> z \\<le> b \\<Longrightarrow> isCont f z\"\n    and isCont_g: \"\\<And>z. a \\<le> z \\<Longrightarrow> z \\<le> b \\<Longrightarrow> isCont g z\"\n    and DERIV_g: \"\\<And>z. a < z \\<Longrightarrow> z < b \\<Longrightarrow> DERIV g z :> (g' z)\"\n    and DERIV_f: \"\\<And>z. a < z \\<Longrightarrow> z < b \\<Longrightarrow> DERIV f z :> (f' z)\"\n  shows \"\\<exists>c. a < c \\<and> c < b \\<and> (f b - f a) * g' c = (g b - g a) * f' c\"\nproof -\n  have \"\\<exists>g'c f'c c. DERIV g c :> g'c \\<and> DERIV f c :> f'c \\<and>\n      a < c \\<and> c < b \\<and> (f b - f a) * g'c = (g b - g a) * f'c\"\n    using assms by (intro GMVT) (force simp: real_differentiable_def)+\n  then obtain c where \"a < c\" \"c < b\" \"(f b - f a) * g' c = (g b - g a) * f' c\"\n    using DERIV_f DERIV_g by (force dest: DERIV_unique)\n  then show ?thesis\n    by auto\nqed\n\n\nsubsection \\<open>L'Hopitals rule\\<close>\n\nlemma isCont_If_ge:\n  fixes a :: \"'a :: linorder_topology\"\n  shows \"continuous (at_left a) g \\<Longrightarrow> (f \\<longlongrightarrow> g a) (at_right a) \\<Longrightarrow>\n    isCont (\\<lambda>x. if x \\<le> a then g x else f x) a\"\n  unfolding isCont_def continuous_within\n  apply (intro filterlim_split_at)\n   apply (subst filterlim_cong[OF refl refl, where g=g])\n    apply (simp_all add: eventually_at_filter less_le)\n  apply (subst filterlim_cong[OF refl refl, where g=f])\n   apply (simp_all add: eventually_at_filter less_le)\n  done\n\nlemma lhopital_right_0:\n  fixes f0 g0 :: \"real \\<Rightarrow> real\"\n  assumes f_0: \"(f0 \\<longlongrightarrow> 0) (at_right 0)\"\n    and g_0: \"(g0 \\<longlongrightarrow> 0) (at_right 0)\"\n    and ev:\n      \"eventually (\\<lambda>x. g0 x \\<noteq> 0) (at_right 0)\"\n      \"eventually (\\<lambda>x. g' x \\<noteq> 0) (at_right 0)\"\n      \"eventually (\\<lambda>x. DERIV f0 x :> f' x) (at_right 0)\"\n      \"eventually (\\<lambda>x. DERIV g0 x :> g' x) (at_right 0)\"\n    and lim: \"filterlim (\\<lambda> x. (f' x / g' x)) F (at_right 0)\"\n  shows \"filterlim (\\<lambda> x. f0 x / g0 x) F (at_right 0)\"\nproof -\n  define f where [abs_def]: \"f x = (if x \\<le> 0 then 0 else f0 x)\" for x\n  then have \"f 0 = 0\" by simp\n\n  define g where [abs_def]: \"g x = (if x \\<le> 0 then 0 else g0 x)\" for x\n  then have \"g 0 = 0\" by simp\n\n  have \"eventually (\\<lambda>x. g0 x \\<noteq> 0 \\<and> g' x \\<noteq> 0 \\<and>\n      DERIV f0 x :> (f' x) \\<and> DERIV g0 x :> (g' x)) (at_right 0)\"\n    using ev by eventually_elim auto\n  then obtain a where [arith]: \"0 < a\"\n    and g0_neq_0: \"\\<And>x. 0 < x \\<Longrightarrow> x < a \\<Longrightarrow> g0 x \\<noteq> 0\"\n    and g'_neq_0: \"\\<And>x. 0 < x \\<Longrightarrow> x < a \\<Longrightarrow> g' x \\<noteq> 0\"\n    and f0: \"\\<And>x. 0 < x \\<Longrightarrow> x < a \\<Longrightarrow> DERIV f0 x :> (f' x)\"\n    and g0: \"\\<And>x. 0 < x \\<Longrightarrow> x < a \\<Longrightarrow> DERIV g0 x :> (g' x)\"\n    unfolding eventually_at by (auto simp: dist_real_def)\n\n  have g_neq_0: \"\\<And>x. 0 < x \\<Longrightarrow> x < a \\<Longrightarrow> g x \\<noteq> 0\"\n    using g0_neq_0 by (simp add: g_def)\n\n  have f: \"DERIV f x :> (f' x)\" if x: \"0 < x\" \"x < a\" for x\n    using that\n    by (intro DERIV_cong_ev[THEN iffD1, OF _ _ _ f0[OF x]])\n      (auto simp: f_def eventually_nhds_metric dist_real_def intro!: exI[of _ x])\n\n  have g: \"DERIV g x :> (g' x)\" if x: \"0 < x\" \"x < a\" for x\n    using that\n    by (intro DERIV_cong_ev[THEN iffD1, OF _ _ _ g0[OF x]])\n         (auto simp: g_def eventually_nhds_metric dist_real_def intro!: exI[of _ x])\n\n  have \"isCont f 0\"\n    unfolding f_def by (intro isCont_If_ge f_0 continuous_const)\n\n  have \"isCont g 0\"\n    unfolding g_def by (intro isCont_If_ge g_0 continuous_const)\n\n  have \"\\<exists>\\<zeta>. \\<forall>x\\<in>{0 <..< a}. 0 < \\<zeta> x \\<and> \\<zeta> x < x \\<and> f x / g x = f' (\\<zeta> x) / g' (\\<zeta> x)\"\n  proof (rule bchoice, rule ballI)\n    fix x\n    assume \"x \\<in> {0 <..< a}\"\n    then have x[arith]: \"0 < x\" \"x < a\" by auto\n    with g'_neq_0 g_neq_0 \\<open>g 0 = 0\\<close> have g': \"\\<And>x. 0 < x \\<Longrightarrow> x < a  \\<Longrightarrow> 0 \\<noteq> g' x\" \"g 0 \\<noteq> g x\"\n      by auto\n    have \"\\<And>x. 0 \\<le> x \\<Longrightarrow> x < a \\<Longrightarrow> isCont f x\"\n      using \\<open>isCont f 0\\<close> f by (auto intro: DERIV_isCont simp: le_less)\n    moreover have \"\\<And>x. 0 \\<le> x \\<Longrightarrow> x < a \\<Longrightarrow> isCont g x\"\n      using \\<open>isCont g 0\\<close> g by (auto intro: DERIV_isCont simp: le_less)\n    ultimately have \"\\<exists>c. 0 < c \\<and> c < x \\<and> (f x - f 0) * g' c = (g x - g 0) * f' c\"\n      using f g \\<open>x < a\\<close> by (intro GMVT') auto\n    then obtain c where *: \"0 < c\" \"c < x\" \"(f x - f 0) * g' c = (g x - g 0) * f' c\"\n      by blast\n    moreover\n    from * g'(1)[of c] g'(2) have \"(f x - f 0)  / (g x - g 0) = f' c / g' c\"\n      by (simp add: field_simps)\n    ultimately show \"\\<exists>y. 0 < y \\<and> y < x \\<and> f x / g x = f' y / g' y\"\n      using \\<open>f 0 = 0\\<close> \\<open>g 0 = 0\\<close> by (auto intro!: exI[of _ c])\n  qed\n  then obtain \\<zeta> where \"\\<forall>x\\<in>{0 <..< a}. 0 < \\<zeta> x \\<and> \\<zeta> x < x \\<and> f x / g x = f' (\\<zeta> x) / g' (\\<zeta> x)\" ..\n  then have \\<zeta>: \"eventually (\\<lambda>x. 0 < \\<zeta> x \\<and> \\<zeta> x < x \\<and> f x / g x = f' (\\<zeta> x) / g' (\\<zeta> x)) (at_right 0)\"\n    unfolding eventually_at by (intro exI[of _ a]) (auto simp: dist_real_def)\n  moreover\n  from \\<zeta> have \"eventually (\\<lambda>x. norm (\\<zeta> x) \\<le> x) (at_right 0)\"\n    by eventually_elim auto\n  then have \"((\\<lambda>x. norm (\\<zeta> x)) \\<longlongrightarrow> 0) (at_right 0)\"\n    by (rule_tac real_tendsto_sandwich[where f=\"\\<lambda>x. 0\" and h=\"\\<lambda>x. x\"]) auto\n  then have \"(\\<zeta> \\<longlongrightarrow> 0) (at_right 0)\"\n    by (rule tendsto_norm_zero_cancel)\n  with \\<zeta> have \"filterlim \\<zeta> (at_right 0) (at_right 0)\"\n    by (auto elim!: eventually_mono simp: filterlim_at)\n  from this lim have \"filterlim (\\<lambda>t. f' (\\<zeta> t) / g' (\\<zeta> t)) F (at_right 0)\"\n    by (rule_tac filterlim_compose[of _ _ _ \\<zeta>])\n  ultimately have \"filterlim (\\<lambda>t. f t / g t) F (at_right 0)\" (is ?P)\n    by (rule_tac filterlim_cong[THEN iffD1, OF refl refl])\n       (auto elim: eventually_mono)\n  also have \"?P \\<longleftrightarrow> ?thesis\"\n    by (rule filterlim_cong) (auto simp: f_def g_def eventually_at_filter)\n  finally show ?thesis .\nqed\n\nlemma lhopital_right:\n  \"(f \\<longlongrightarrow> 0) (at_right x) \\<Longrightarrow> (g \\<longlongrightarrow> 0) (at_right x) \\<Longrightarrow>\n    eventually (\\<lambda>x. g x \\<noteq> 0) (at_right x) \\<Longrightarrow>\n    eventually (\\<lambda>x. g' x \\<noteq> 0) (at_right x) \\<Longrightarrow>\n    eventually (\\<lambda>x. DERIV f x :> f' x) (at_right x) \\<Longrightarrow>\n    eventually (\\<lambda>x. DERIV g x :> g' x) (at_right x) \\<Longrightarrow>\n    filterlim (\\<lambda> x. (f' x / g' x)) F (at_right x) \\<Longrightarrow>\n  filterlim (\\<lambda> x. f x / g x) F (at_right x)\"\n  for x :: real\n  unfolding eventually_at_right_to_0[of _ x] filterlim_at_right_to_0[of _ _ x] DERIV_shift\n  by (rule lhopital_right_0)\n\nlemma lhopital_left:\n  \"(f \\<longlongrightarrow> 0) (at_left x) \\<Longrightarrow> (g \\<longlongrightarrow> 0) (at_left x) \\<Longrightarrow>\n    eventually (\\<lambda>x. g x \\<noteq> 0) (at_left x) \\<Longrightarrow>\n    eventually (\\<lambda>x. g' x \\<noteq> 0) (at_left x) \\<Longrightarrow>\n    eventually (\\<lambda>x. DERIV f x :> f' x) (at_left x) \\<Longrightarrow>\n    eventually (\\<lambda>x. DERIV g x :> g' x) (at_left x) \\<Longrightarrow>\n    filterlim (\\<lambda> x. (f' x / g' x)) F (at_left x) \\<Longrightarrow>\n  filterlim (\\<lambda> x. f x / g x) F (at_left x)\"\n  for x :: real\n  unfolding eventually_at_left_to_right filterlim_at_left_to_right DERIV_mirror\n  by (rule lhopital_right[where f'=\"\\<lambda>x. - f' (- x)\"]) (auto simp: DERIV_mirror)\n\nlemma lhopital:\n  \"(f \\<longlongrightarrow> 0) (at x) \\<Longrightarrow> (g \\<longlongrightarrow> 0) (at x) \\<Longrightarrow>\n    eventually (\\<lambda>x. g x \\<noteq> 0) (at x) \\<Longrightarrow>\n    eventually (\\<lambda>x. g' x \\<noteq> 0) (at x) \\<Longrightarrow>\n    eventually (\\<lambda>x. DERIV f x :> f' x) (at x) \\<Longrightarrow>\n    eventually (\\<lambda>x. DERIV g x :> g' x) (at x) \\<Longrightarrow>\n    filterlim (\\<lambda> x. (f' x / g' x)) F (at x) \\<Longrightarrow>\n  filterlim (\\<lambda> x. f x / g x) F (at x)\"\n  for x :: real\n  unfolding eventually_at_split filterlim_at_split\n  by (auto intro!: lhopital_right[of f x g g' f'] lhopital_left[of f x g g' f'])\n\n\nlemma lhopital_right_0_at_top:\n  fixes f g :: \"real \\<Rightarrow> real\"\n  assumes g_0: \"LIM x at_right 0. g x :> at_top\"\n    and ev:\n      \"eventually (\\<lambda>x. g' x \\<noteq> 0) (at_right 0)\"\n      \"eventually (\\<lambda>x. DERIV f x :> f' x) (at_right 0)\"\n      \"eventually (\\<lambda>x. DERIV g x :> g' x) (at_right 0)\"\n    and lim: \"((\\<lambda> x. (f' x / g' x)) \\<longlongrightarrow> x) (at_right 0)\"\n  shows \"((\\<lambda> x. f x / g x) \\<longlongrightarrow> x) (at_right 0)\"\n  unfolding tendsto_iff\nproof safe\n  fix e :: real\n  assume \"0 < e\"\n  with lim[unfolded tendsto_iff, rule_format, of \"e / 4\"]\n  have \"eventually (\\<lambda>t. dist (f' t / g' t) x < e / 4) (at_right 0)\"\n    by simp\n  from eventually_conj[OF eventually_conj[OF ev(1) ev(2)] eventually_conj[OF ev(3) this]]\n  obtain a where [arith]: \"0 < a\"\n    and g'_neq_0: \"\\<And>x. 0 < x \\<Longrightarrow> x < a \\<Longrightarrow> g' x \\<noteq> 0\"\n    and f0: \"\\<And>x. 0 < x \\<Longrightarrow> x \\<le> a \\<Longrightarrow> DERIV f x :> (f' x)\"\n    and g0: \"\\<And>x. 0 < x \\<Longrightarrow> x \\<le> a \\<Longrightarrow> DERIV g x :> (g' x)\"\n    and Df: \"\\<And>t. 0 < t \\<Longrightarrow> t < a \\<Longrightarrow> dist (f' t / g' t) x < e / 4\"\n    unfolding eventually_at_le by (auto simp: dist_real_def)\n\n  from Df have \"eventually (\\<lambda>t. t < a) (at_right 0)\" \"eventually (\\<lambda>t::real. 0 < t) (at_right 0)\"\n    unfolding eventually_at by (auto intro!: exI[of _ a] simp: dist_real_def)\n\n  moreover\n  have \"eventually (\\<lambda>t. 0 < g t) (at_right 0)\" \"eventually (\\<lambda>t. g a < g t) (at_right 0)\"\n    using g_0 by (auto elim: eventually_mono simp: filterlim_at_top_dense)\n\n  moreover\n  have inv_g: \"((\\<lambda>x. inverse (g x)) \\<longlongrightarrow> 0) (at_right 0)\"\n    using tendsto_inverse_0 filterlim_mono[OF g_0 at_top_le_at_infinity order_refl]\n    by (rule filterlim_compose)\n  then have \"((\\<lambda>x. norm (1 - g a * inverse (g x))) \\<longlongrightarrow> norm (1 - g a * 0)) (at_right 0)\"\n    by (intro tendsto_intros)\n  then have \"((\\<lambda>x. norm (1 - g a / g x)) \\<longlongrightarrow> 1) (at_right 0)\"\n    by (simp add: inverse_eq_divide)\n  from this[unfolded tendsto_iff, rule_format, of 1]\n  have \"eventually (\\<lambda>x. norm (1 - g a / g x) < 2) (at_right 0)\"\n    by (auto elim!: eventually_mono simp: dist_real_def)\n\n  moreover\n  from inv_g have \"((\\<lambda>t. norm ((f a - x * g a) * inverse (g t))) \\<longlongrightarrow> norm ((f a - x * g a) * 0))\n      (at_right 0)\"\n    by (intro tendsto_intros)\n  then have \"((\\<lambda>t. norm (f a - x * g a) / norm (g t)) \\<longlongrightarrow> 0) (at_right 0)\"\n    by (simp add: inverse_eq_divide)\n  from this[unfolded tendsto_iff, rule_format, of \"e / 2\"] \\<open>0 < e\\<close>\n  have \"eventually (\\<lambda>t. norm (f a - x * g a) / norm (g t) < e / 2) (at_right 0)\"\n    by (auto simp: dist_real_def)\n\n  ultimately show \"eventually (\\<lambda>t. dist (f t / g t) x < e) (at_right 0)\"\n  proof eventually_elim\n    fix t assume t[arith]: \"0 < t\" \"t < a\" \"g a < g t\" \"0 < g t\"\n    assume ineq: \"norm (1 - g a / g t) < 2\" \"norm (f a - x * g a) / norm (g t) < e / 2\"\n\n    have \"\\<exists>y. t < y \\<and> y < a \\<and> (g a - g t) * f' y = (f a - f t) * g' y\"\n      using f0 g0 t(1,2) by (intro GMVT') (force intro!: DERIV_isCont)+\n    then obtain y where [arith]: \"t < y\" \"y < a\"\n      and D_eq0: \"(g a - g t) * f' y = (f a - f t) * g' y\"\n      by blast\n    from D_eq0 have D_eq: \"(f t - f a) / (g t - g a) = f' y / g' y\"\n      using \\<open>g a < g t\\<close> g'_neq_0[of y] by (auto simp add: field_simps)\n\n    have *: \"f t / g t - x = ((f t - f a) / (g t - g a) - x) * (1 - g a / g t) + (f a - x * g a) / g t\"\n      by (simp add: field_simps)\n    have \"norm (f t / g t - x) \\<le>\n        norm (((f t - f a) / (g t - g a) - x) * (1 - g a / g t)) + norm ((f a - x * g a) / g t)\"\n      unfolding * by (rule norm_triangle_ineq)\n    also have \"\\<dots> = dist (f' y / g' y) x * norm (1 - g a / g t) + norm (f a - x * g a) / norm (g t)\"\n      by (simp add: abs_mult D_eq dist_real_def)\n    also have \"\\<dots> < (e / 4) * 2 + e / 2\"\n      using ineq Df[of y] \\<open>0 < e\\<close> by (intro add_le_less_mono mult_mono) auto\n    finally show \"dist (f t / g t) x < e\"\n      by (simp add: dist_real_def)\n  qed\nqed\n\nlemma lhopital_right_at_top:\n  \"LIM x at_right x. (g::real \\<Rightarrow> real) x :> at_top \\<Longrightarrow>\n    eventually (\\<lambda>x. g' x \\<noteq> 0) (at_right x) \\<Longrightarrow>\n    eventually (\\<lambda>x. DERIV f x :> f' x) (at_right x) \\<Longrightarrow>\n    eventually (\\<lambda>x. DERIV g x :> g' x) (at_right x) \\<Longrightarrow>\n    ((\\<lambda> x. (f' x / g' x)) \\<longlongrightarrow> y) (at_right x) \\<Longrightarrow>\n    ((\\<lambda> x. f x / g x) \\<longlongrightarrow> y) (at_right x)\"\n  unfolding eventually_at_right_to_0[of _ x] filterlim_at_right_to_0[of _ _ x] DERIV_shift\n  by (rule lhopital_right_0_at_top)\n\nlemma lhopital_left_at_top:\n  \"LIM x at_left x. g x :> at_top \\<Longrightarrow>\n    eventually (\\<lambda>x. g' x \\<noteq> 0) (at_left x) \\<Longrightarrow>\n    eventually (\\<lambda>x. DERIV f x :> f' x) (at_left x) \\<Longrightarrow>\n    eventually (\\<lambda>x. DERIV g x :> g' x) (at_left x) \\<Longrightarrow>\n    ((\\<lambda> x. (f' x / g' x)) \\<longlongrightarrow> y) (at_left x) \\<Longrightarrow>\n    ((\\<lambda> x. f x / g x) \\<longlongrightarrow> y) (at_left x)\"\n  for x :: real\n  unfolding eventually_at_left_to_right filterlim_at_left_to_right DERIV_mirror\n  by (rule lhopital_right_at_top[where f'=\"\\<lambda>x. - f' (- x)\"]) (auto simp: DERIV_mirror)\n\nlemma lhopital_at_top:\n  \"LIM x at x. (g::real \\<Rightarrow> real) x :> at_top \\<Longrightarrow>\n    eventually (\\<lambda>x. g' x \\<noteq> 0) (at x) \\<Longrightarrow>\n    eventually (\\<lambda>x. DERIV f x :> f' x) (at x) \\<Longrightarrow>\n    eventually (\\<lambda>x. DERIV g x :> g' x) (at x) \\<Longrightarrow>\n    ((\\<lambda> x. (f' x / g' x)) \\<longlongrightarrow> y) (at x) \\<Longrightarrow>\n    ((\\<lambda> x. f x / g x) \\<longlongrightarrow> y) (at x)\"\n  unfolding eventually_at_split filterlim_at_split\n  by (auto intro!: lhopital_right_at_top[of g x g' f f'] lhopital_left_at_top[of g x g' f f'])\n\nlemma lhospital_at_top_at_top:\n  fixes f g :: \"real \\<Rightarrow> real\"\n  assumes g_0: \"LIM x at_top. g x :> at_top\"\n    and g': \"eventually (\\<lambda>x. g' x \\<noteq> 0) at_top\"\n    and Df: \"eventually (\\<lambda>x. DERIV f x :> f' x) at_top\"\n    and Dg: \"eventually (\\<lambda>x. DERIV g x :> g' x) at_top\"\n    and lim: \"((\\<lambda> x. (f' x / g' x)) \\<longlongrightarrow> x) at_top\"\n  shows \"((\\<lambda> x. f x / g x) \\<longlongrightarrow> x) at_top\"\n  unfolding filterlim_at_top_to_right\nproof (rule lhopital_right_0_at_top)\n  let ?F = \"\\<lambda>x. f (inverse x)\"\n  let ?G = \"\\<lambda>x. g (inverse x)\"\n  let ?R = \"at_right (0::real)\"\n  let ?D = \"\\<lambda>f' x. f' (inverse x) * - (inverse x ^ Suc (Suc 0))\"\n  show \"LIM x ?R. ?G x :> at_top\"\n    using g_0 unfolding filterlim_at_top_to_right .\n  show \"eventually (\\<lambda>x. DERIV ?G x  :> ?D g' x) ?R\"\n    unfolding eventually_at_right_to_top\n    using Dg eventually_ge_at_top[where c=1]\n    apply eventually_elim\n    apply (rule DERIV_cong)\n     apply (rule DERIV_chain'[where f=inverse])\n      apply (auto intro!:  DERIV_inverse)\n    done\n  show \"eventually (\\<lambda>x. DERIV ?F x  :> ?D f' x) ?R\"\n    unfolding eventually_at_right_to_top\n    using Df eventually_ge_at_top[where c=1]\n    apply eventually_elim\n    apply (rule DERIV_cong)\n     apply (rule DERIV_chain'[where f=inverse])\n      apply (auto intro!:  DERIV_inverse)\n    done\n  show \"eventually (\\<lambda>x. ?D g' x \\<noteq> 0) ?R\"\n    unfolding eventually_at_right_to_top\n    using g' eventually_ge_at_top[where c=1]\n    by eventually_elim auto\n  show \"((\\<lambda>x. ?D f' x / ?D g' x) \\<longlongrightarrow> x) ?R\"\n    unfolding filterlim_at_right_to_top\n    apply (intro filterlim_cong[THEN iffD2, OF refl refl _ lim])\n    using eventually_ge_at_top[where c=1]\n    by eventually_elim simp\nqed\n\nlemma lhopital_right_at_top_at_top:\n  fixes f g :: \"real \\<Rightarrow> real\"\n  assumes f_0: \"LIM x at_right a. f x :> at_top\"\n  assumes g_0: \"LIM x at_right a. g x :> at_top\"\n    and ev:\n      \"eventually (\\<lambda>x. DERIV f x :> f' x) (at_right a)\"\n      \"eventually (\\<lambda>x. DERIV g x :> g' x) (at_right a)\"\n    and lim: \"filterlim (\\<lambda> x. (f' x / g' x)) at_top (at_right a)\"\n  shows \"filterlim (\\<lambda> x. f x / g x) at_top (at_right a)\"\nproof -\n  from lim have pos: \"eventually (\\<lambda>x. f' x / g' x > 0) (at_right a)\"\n    unfolding filterlim_at_top_dense by blast\n  have \"((\\<lambda>x. g x / f x) \\<longlongrightarrow> 0) (at_right a)\"\n  proof (rule lhopital_right_at_top)\n    from pos show \"eventually (\\<lambda>x. f' x \\<noteq> 0) (at_right a)\" by eventually_elim auto\n    from tendsto_inverse_0_at_top[OF lim]\n      show \"((\\<lambda>x. g' x / f' x) \\<longlongrightarrow> 0) (at_right a)\" by simp\n  qed fact+\n  moreover from f_0 g_0 \n    have \"eventually (\\<lambda>x. f x > 0) (at_right a)\" \"eventually (\\<lambda>x. g x > 0) (at_right a)\"\n    unfolding filterlim_at_top_dense by blast+\n  hence \"eventually (\\<lambda>x. g x / f x > 0) (at_right a)\" by eventually_elim simp\n  ultimately have \"filterlim (\\<lambda>x. inverse (g x / f x)) at_top (at_right a)\"\n    by (rule filterlim_inverse_at_top)\n  thus ?thesis by simp\nqed\n\nlemma lhopital_right_at_top_at_bot:\n  fixes f g :: \"real \\<Rightarrow> real\"\n  assumes f_0: \"LIM x at_right a. f x :> at_top\"\n  assumes g_0: \"LIM x at_right a. g x :> at_bot\"\n    and ev:\n      \"eventually (\\<lambda>x. DERIV f x :> f' x) (at_right a)\"\n      \"eventually (\\<lambda>x. DERIV g x :> g' x) (at_right a)\"\n    and lim: \"filterlim (\\<lambda> x. (f' x / g' x)) at_bot (at_right a)\"\n  shows \"filterlim (\\<lambda> x. f x / g x) at_bot (at_right a)\"\nproof -\n  from ev(2) have ev': \"eventually (\\<lambda>x. DERIV (\\<lambda>x. -g x) x :> -g' x) (at_right a)\"\n    by eventually_elim (auto intro: derivative_intros)\n  have \"filterlim (\\<lambda>x. f x / (-g x)) at_top (at_right a)\"\n    by (rule lhopital_right_at_top_at_top[where f' = f' and g' = \"\\<lambda>x. -g' x\"])\n       (insert assms ev', auto simp: filterlim_uminus_at_bot)\n  hence \"filterlim (\\<lambda>x. -(f x / g x)) at_top (at_right a)\" by simp\n  thus ?thesis by (simp add: filterlim_uminus_at_bot)\nqed\n\nlemma lhopital_left_at_top_at_top:\n  fixes f g :: \"real \\<Rightarrow> real\"\n  assumes f_0: \"LIM x at_left a. f x :> at_top\"\n  assumes g_0: \"LIM x at_left a. g x :> at_top\"\n    and ev:\n      \"eventually (\\<lambda>x. DERIV f x :> f' x) (at_left a)\"\n      \"eventually (\\<lambda>x. DERIV g x :> g' x) (at_left a)\"\n    and lim: \"filterlim (\\<lambda> x. (f' x / g' x)) at_top (at_left a)\"\n  shows \"filterlim (\\<lambda> x. f x / g x) at_top (at_left a)\"\n  by (insert assms, unfold eventually_at_left_to_right filterlim_at_left_to_right DERIV_mirror,\n      rule lhopital_right_at_top_at_top[where f'=\"\\<lambda>x. - f' (- x)\"]) \n     (insert assms, auto simp: DERIV_mirror)\n\nlemma lhopital_left_at_top_at_bot:\n  fixes f g :: \"real \\<Rightarrow> real\"\n  assumes f_0: \"LIM x at_left a. f x :> at_top\"\n  assumes g_0: \"LIM x at_left a. g x :> at_bot\"\n    and ev:\n      \"eventually (\\<lambda>x. DERIV f x :> f' x) (at_left a)\"\n      \"eventually (\\<lambda>x. DERIV g x :> g' x) (at_left a)\"\n    and lim: \"filterlim (\\<lambda> x. (f' x / g' x)) at_bot (at_left a)\"\n  shows \"filterlim (\\<lambda> x. f x / g x) at_bot (at_left a)\"\n  by (insert assms, unfold eventually_at_left_to_right filterlim_at_left_to_right DERIV_mirror,\n      rule lhopital_right_at_top_at_bot[where f'=\"\\<lambda>x. - f' (- x)\"]) \n     (insert assms, auto simp: DERIV_mirror)\n\nlemma lhopital_at_top_at_top:\n  fixes f g :: \"real \\<Rightarrow> real\"\n  assumes f_0: \"LIM x at a. f x :> at_top\"\n  assumes g_0: \"LIM x at a. g x :> at_top\"\n    and ev:\n      \"eventually (\\<lambda>x. DERIV f x :> f' x) (at a)\"\n      \"eventually (\\<lambda>x. DERIV g x :> g' x) (at a)\"\n    and lim: \"filterlim (\\<lambda> x. (f' x / g' x)) at_top (at a)\"\n  shows \"filterlim (\\<lambda> x. f x / g x) at_top (at a)\"\n  using assms unfolding eventually_at_split filterlim_at_split\n  by (auto intro!: lhopital_right_at_top_at_top[of f a g f' g'] \n                   lhopital_left_at_top_at_top[of f a g f' g'])\n\nlemma lhopital_at_top_at_bot:\n  fixes f g :: \"real \\<Rightarrow> real\"\n  assumes f_0: \"LIM x at a. f x :> at_top\"\n  assumes g_0: \"LIM x at a. g x :> at_bot\"\n    and ev:\n      \"eventually (\\<lambda>x. DERIV f x :> f' x) (at a)\"\n      \"eventually (\\<lambda>x. DERIV g x :> g' x) (at a)\"\n    and lim: \"filterlim (\\<lambda> x. (f' x / g' x)) at_bot (at a)\"\n  shows \"filterlim (\\<lambda> x. f x / g x) at_bot (at a)\"\n  using assms unfolding eventually_at_split filterlim_at_split\n  by (auto intro!: lhopital_right_at_top_at_bot[of f a g f' g'] \n                   lhopital_left_at_top_at_bot[of f a g f' g'])\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/Deriv.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8558511469672594, "lm_q2_score": 0.8267117983401363, "lm_q1q2_score": 0.7075422408207713}}
{"text": "(******************************************************************************)\n(* Project: Isabelle/UTP Toolkit                                              *)\n(* File: Countable_Set_Extra.thy                                              *)\n(* Authors: Simon Foster and Frank Zeyda                                      *)\n(* Emails: simon.foster@york.ac.uk and frank.zeyda@york.ac.uk                 *)\n(******************************************************************************)\n\nsection \\<open> Countable Sets: Extra functions and properties \\<close>\n\ntheory Countable_Set_Extra\nimports\n  \"HOL-Library.Countable_Set_Type\"\n  Infinite_Sequence\n  \nbegin\n\nsubsection \\<open> Extra syntax \\<close>\n\nnotation cempty (\"{}\\<^sub>c\")\nnotation cin (infix \"\\<in>\\<^sub>c\" 50)\nnotation cUn (infixl \"\\<union>\\<^sub>c\" 65)\nnotation cInt (infixl \"\\<inter>\\<^sub>c\" 70)\nnotation cDiff (infixl \"-\\<^sub>c\" 65)\nnotation cUnion (\"\\<Union>\\<^sub>c_\" [900] 900)\nnotation cimage (infixr \"`\\<^sub>c\" 90)\n\nabbreviation csubseteq :: \"'a cset \\<Rightarrow> 'a cset \\<Rightarrow> bool\" (\"(_/ \\<subseteq>\\<^sub>c _)\" [51, 51] 50)\nwhere \"A \\<subseteq>\\<^sub>c B \\<equiv> A \\<le> B\"\n\nabbreviation csubset :: \"'a cset \\<Rightarrow> 'a cset \\<Rightarrow> bool\" (\"(_/ \\<subset>\\<^sub>c _)\" [51, 51] 50)\nwhere \"A \\<subset>\\<^sub>c B \\<equiv> A < B\"\n\nsubsection \\<open> Countable set functions \\<close>\n\nsetup_lifting type_definition_cset\n\nlift_definition cnin :: \"'a \\<Rightarrow> 'a cset \\<Rightarrow> bool\" (infix \"\\<notin>\\<^sub>c\" 50) is \"(\\<notin>)\" .\n\ndefinition cBall :: \"'a cset \\<Rightarrow> ('a \\<Rightarrow> bool) \\<Rightarrow> bool\" where\n\"cBall A P = (\\<forall>x. x \\<in>\\<^sub>c A \\<longrightarrow> P x)\"\n\ndefinition cBex :: \"'a cset \\<Rightarrow> ('a \\<Rightarrow> bool) \\<Rightarrow> bool\" where\n\"cBex A P = (\\<exists>x. x \\<in>\\<^sub>c A \\<longrightarrow> P x)\"\n\ndeclare cBall_def [mono,simp]\ndeclare cBex_def [mono,simp]\n\nsyntax\n  \"_cBall\" :: \"pttrn => 'a cset => bool => bool\" (\"(3\\<forall> _\\<in>\\<^sub>c_./ _)\" [0, 0, 10] 10)\n  \"_cBex\"  :: \"pttrn => 'a cset => bool => bool\" (\"(3\\<exists> _\\<in>\\<^sub>c_./ _)\" [0, 0, 10] 10)\n\ntranslations\n  \"\\<forall> x\\<in>\\<^sub>cA. P\" == \"CONST cBall A (%x. P)\"\n  \"\\<exists> x\\<in>\\<^sub>cA. P\" == \"CONST cBex  A (%x. P)\"\n\ndefinition cset_Collect :: \"('a \\<Rightarrow> bool) \\<Rightarrow> 'a cset\" where\n\"cset_Collect = (acset o Collect)\"\n\nlift_definition cset_Coll :: \"'a cset \\<Rightarrow> ('a \\<Rightarrow> bool) \\<Rightarrow> 'a cset\" is \"\\<lambda> A P. {x \\<in> A. P x}\"\n  by (auto)\n\nlemma cset_Coll_equiv: \"cset_Coll A P = cset_Collect (\\<lambda> x. x \\<in>\\<^sub>c A \\<and> P x)\"\n  by (simp add:cset_Collect_def cset_Coll_def cin_def)\n\ndeclare cset_Collect_def [simp]\n\nsyntax\n  \"_cColl\" :: \"pttrn => bool => 'a cset\" (\"(1{_./ _}\\<^sub>c)\")\n\ntranslations\n  \"{x . P}\\<^sub>c\" \\<rightleftharpoons> \"(CONST cset_Collect) (\\<lambda> x . P)\"\n\nsyntax (xsymbols)\n  \"_cCollect\" :: \"pttrn => 'a cset => bool => 'a cset\"    (\"(1{_ \\<in>\\<^sub>c/ _./ _}\\<^sub>c)\")\ntranslations\n  \"{x \\<in>\\<^sub>c A. P}\\<^sub>c\" => \"CONST cset_Coll A (\\<lambda> x. P)\"\n\nlemma cset_CollectI: \"P (a :: 'a::countable) \\<Longrightarrow> a \\<in>\\<^sub>c {x. P x}\\<^sub>c\"\n  by (simp add: cin_def)\n\nlemma cset_CollI: \"\\<lbrakk> a \\<in>\\<^sub>c A; P a \\<rbrakk> \\<Longrightarrow> a \\<in>\\<^sub>c {x \\<in>\\<^sub>c A. P x}\\<^sub>c\"\n  by (simp add: cin.rep_eq cset_Coll.rep_eq)\n\nlemma cset_CollectD: \"(a :: 'a::countable) \\<in>\\<^sub>c {x. P x}\\<^sub>c \\<Longrightarrow> P a\"\n  by (simp add: cin_def)\n\nlemma cset_Collect_cong: \"(\\<And>x. P x = Q x) ==> {x. P x}\\<^sub>c = {x. Q x}\\<^sub>c\"\n  by simp\n\ntext \\<open> Avoid eta-contraction for robust pretty-printing. \\<close>\n\nprint_translation \\<open>\n [Syntax_Trans.preserve_binder_abs_tr'\n   @{const_syntax cset_Collect} @{syntax_const \"_cColl\"}]\n\\<close>\n\nlift_definition cset_set :: \"'a list \\<Rightarrow> 'a cset\" is set\n  using countable_finite by blast\n\nlemma countable_finite_power:\n  \"countable(A) \\<Longrightarrow> countable {B. B \\<subseteq> A \\<and> finite(B)}\"\n  by (metis Collect_conj_eq Int_commute countable_Collect_finite_subset)\n\nlift_definition cInter :: \"'a cset cset \\<Rightarrow> 'a cset\"  (\"\\<Inter>\\<^sub>c_\" [900] 900)\n  is \"\\<lambda>A. if A = {} then {} else \\<Inter> A\"\n  using countable_INT [of _ _ id] by auto\n\nabbreviation (input) cINTER :: \"'a cset \\<Rightarrow> ('a \\<Rightarrow> 'b cset) \\<Rightarrow> 'b cset\"\n  where \"cINTER A f \\<equiv> cInter (cimage f A)\"\n\nlift_definition cfinite :: \"'a cset \\<Rightarrow> bool\" is finite .\nlift_definition cInfinite :: \"'a cset \\<Rightarrow> bool\" is infinite .\nlift_definition clist :: \"'a::linorder cset \\<Rightarrow> 'a list\" is sorted_list_of_set .\nlift_definition ccard :: \"'a cset \\<Rightarrow> nat\" is card .\nlift_definition cPow :: \"'a cset \\<Rightarrow> 'a cset cset\" is \"\\<lambda> A. {B. B \\<subseteq>\\<^sub>c A \\<and> cfinite(B)}\"\nproof -\n  fix A\n  have \"{B :: 'a cset. B \\<subseteq>\\<^sub>c A \\<and> cfinite B} = acset ` {B :: 'a set. B \\<subseteq> rcset A \\<and> finite B}\"\n    apply (auto simp add: cfinite.rep_eq cin_def less_eq_cset_def countable_finite)\n    using image_iff apply fastforce\n    done\n\n  moreover have \"countable {B :: 'a set. B \\<subseteq> rcset A \\<and> finite B}\"\n    by (auto intro: countable_finite_power)\n\n  ultimately show \"countable {B. B \\<subseteq>\\<^sub>c A \\<and> cfinite B}\"\n    by simp\nqed\n\ndefinition CCollect :: \"('a \\<Rightarrow> bool option) \\<Rightarrow> 'a cset option\" where\n\"CCollect p = (if (None \\<notin> range p) then Some (cset_Collect (the \\<circ> p)) else None)\"\n\ndefinition cset_mapM :: \"'a option cset \\<Rightarrow> 'a cset option\" where\n\"cset_mapM A = (if (None \\<in>\\<^sub>c A) then None else Some (the `\\<^sub>c A))\"\n\nlemma cset_mapM_Some_image [simp]:\n  \"cset_mapM (cimage Some A) = Some A\"\n  apply (auto simp add: cset_mapM_def)\n  apply (metis cimage_cinsert cinsertI1 option.sel set_cinsert)\n  done\n\ndefinition CCollect_ext :: \"('a \\<Rightarrow> 'b option) \\<Rightarrow> ('a \\<Rightarrow> bool option) \\<Rightarrow> 'b cset option\" where\n\"CCollect_ext f p = do { xs \\<leftarrow> CCollect p; cset_mapM (f `\\<^sub>c xs) }\"\n\nlemma the_Some_image [simp]:\n  \"the ` Some ` xs = xs\"\n  by (auto simp add:image_iff)\n\nlemma CCollect_ext_Some [simp]:\n  \"CCollect_ext Some xs = CCollect xs\"\n  apply (case_tac \"CCollect xs\")\n   apply (auto simp add:CCollect_ext_def)\n  done\n\nlift_definition list_of_cset :: \"'a :: linorder cset \\<Rightarrow> 'a list\" is sorted_list_of_set .\n\ndefinition cset_count :: \"'a cset \\<Rightarrow> 'a \\<Rightarrow> nat\" where\n\"cset_count A =\n  (if (finite (rcset A))\n   then (SOME f::'a\\<Rightarrow>nat. inj_on f (rcset A))\n   else (SOME f::'a\\<Rightarrow>nat. bij_betw f (rcset A) UNIV))\"\n\nlemma cset_count_inj_seq:\n  \"inj_on (cset_count A) (rcset A)\"\nproof (cases \"finite (rcset A)\")\n  case True note fin = this\n  obtain count :: \"'a \\<Rightarrow> nat\" where count_inj: \"inj_on count (rcset A)\"\n    by (metis countable_def mem_Collect_eq rcset)\n  with fin show ?thesis\n    by (metis (poly_guards_query) cset_count_def someI_ex)\nnext\n  case False note inf = this\n  obtain count :: \"'a \\<Rightarrow> nat\" where count_bij: \"bij_betw count (rcset A) UNIV\"\n    by (metis countableE_infinite inf mem_Collect_eq rcset)\n  with inf have \"bij_betw (cset_count A) (rcset A) UNIV\"\n    by (metis (poly_guards_query) cset_count_def someI_ex)\n  thus ?thesis\n    by (metis bij_betw_imp_inj_on)\nqed\n\nlemma cset_count_infinite_bij:\n  assumes \"infinite (rcset A)\"\n  shows \"bij_betw (cset_count A) (rcset A) UNIV\"\nproof -\n  from assms obtain count :: \"'a \\<Rightarrow> nat\" where count_bij: \"bij_betw count (rcset A) UNIV\"\n    by (metis countableE_infinite mem_Collect_eq rcset)\n  with assms show ?thesis\n    by (metis (poly_guards_query) cset_count_def someI_ex)\nqed\n\ndefinition cset_seq :: \"'a cset \\<Rightarrow> (nat \\<rightharpoonup> 'a)\" where\n\"cset_seq A i = (if (i \\<in> range (cset_count A) \\<and> inv_into (rcset A) (cset_count A) i \\<in>\\<^sub>c A)\n                 then Some (inv_into (rcset A) (cset_count A) i)\n                 else None)\"\n\nlemma cset_seq_ran: \"ran (cset_seq A) = rcset(A)\"\n  apply (auto simp add: ran_def cset_seq_def cin.rep_eq)\n  apply (metis cset_count_inj_seq inv_into_f_f rangeI)\n  done\n\nlemma cset_seq_inj: \"inj cset_seq\"\nproof (rule injI)\n  fix A B :: \"'a cset\"\n  assume \"cset_seq A = cset_seq B\"\n  thus \"A = B\"\n    by (metis cset_seq_ran rcset_inverse)\nqed\n\nlift_definition cset2infseq :: \"'a cset \\<Rightarrow> 'a infseq\"\nis \"(\\<lambda> A i. if (i \\<in> cset_count A ` rcset A) then inv_into (rcset A) (cset_count A) i else (SOME x. x \\<in>\\<^sub>c A))\" .\n\nlemma range_cset2infseq:\n  \"A \\<noteq> {}\\<^sub>c \\<Longrightarrow> range (Rep_infseq (cset2infseq A)) = rcset A\"\n  by (force intro: someI2 simp add: cset2infseq.rep_eq cset_count_inj_seq bot_cset.rep_eq cin.rep_eq)\n\nlemma infinite_cset_count_surj: \"infinite (rcset A) \\<Longrightarrow> surj (cset_count A)\"\n  using bij_betw_imp_surj cset_count_infinite_bij by auto\n\nlemma cset2infseq_inj:\n  \"inj_on cset2infseq {A. A \\<noteq> {}\\<^sub>c}\"\n  apply (rule inj_onI)\n  apply (simp)\n  apply (metis range_cset2infseq rcset_inject)\n  done\n\nlift_definition nat_infseq2set :: \"nat infseq \\<Rightarrow> nat set\" is\n\"\\<lambda> f. prod_encode ` {(x, f x) | x. True}\" .\n\nlemma inj_nat_infseq2set: \"inj nat_infseq2set\"\nproof (rule injI, transfer)\n  fix f g\n  assume \"prod_encode ` {(x, f x) |x. True} = prod_encode ` {(x, g x) |x. True}\"\n  hence \"{(x, f x) |x. True} = {(x, g x) |x. True}\"\n    by (simp add: inj_image_eq_iff[OF inj_prod_encode])\n  thus \"f = g\"\n    by (auto simp add: set_eq_iff)\nqed\n\nlift_definition bit_infseq_of_nat_set :: \"nat set \\<Rightarrow> bool infseq\"\nis \"\\<lambda> A i. i \\<in> A\" .\n\nlemma bit_infseq_of_nat_set_inj: \"inj bit_infseq_of_nat_set\"\n  apply (rule injI)\n  apply transfer\n  apply (auto simp add: fun_eq_iff)\n  done\n\nlemma bit_infseq_of_nat_cset_bij: \"bij bit_infseq_of_nat_set\"\n  apply (rule bijI)\n   apply (fact bit_infseq_of_nat_set_inj)\n  apply transfer\n  apply (rule surjI)\n  apply auto\n  done\n\ntext \\<open> This function is a partial injection from countable sets of natural sets to natural sets.\n        When used with the Schroeder-Bernstein theorem, it can be used to conjure a total\n        bijection between these two types. \\<close>\n\ndefinition nat_set_cset_collapse :: \"nat set cset \\<Rightarrow> nat set\" where\n\"nat_set_cset_collapse = inv bit_infseq_of_nat_set \\<circ> infseq_inj \\<circ> cset2infseq \\<circ> (\\<lambda> A. (bit_infseq_of_nat_set `\\<^sub>c A))\"\n\nlemma nat_set_cset_collapse_inj: \"inj_on nat_set_cset_collapse {A. A \\<noteq> {}\\<^sub>c}\"\nproof -\n  have \"(`\\<^sub>c) bit_infseq_of_nat_set ` {A. A \\<noteq> {}\\<^sub>c} \\<subseteq> {A. A \\<noteq> {}\\<^sub>c}\"\n    by (auto simp add:cimage.rep_eq)\n  thus ?thesis\n    apply (simp add: nat_set_cset_collapse_def)\n    apply (rule comp_inj_on)\n     apply (meson bit_infseq_of_nat_set_inj cset.inj_map injD inj_onI)\n    apply (rule comp_inj_on)\n     apply (metis cset2infseq_inj subset_inj_on)\n    apply (rule comp_inj_on)\n     apply (rule subset_inj_on)\n      apply (rule infseq_inj)\n     apply (simp)\n    apply (meson UNIV_I bij_imp_bij_inv bij_is_inj bit_infseq_of_nat_cset_bij subsetI subset_inj_on)\n    done\nqed\n\nlemma inj_csingle:\n  \"inj csingle\"\n  by (auto intro: injI simp add: cinsert_def bot_cset.rep_eq)\n\nlemma range_csingle:\n  \"range csingle \\<subseteq> {A. A \\<noteq> {}\\<^sub>c}\"\n  by (auto)\n\nlift_definition csets :: \"'a set \\<Rightarrow> 'a cset set\" is\n\"\\<lambda> A. {B. B \\<subseteq> A \\<and> countable B}\" by auto\n\nlemma csets_finite: \"finite A \\<Longrightarrow> finite (csets A)\"\n  by (auto simp add: csets_def)\n\nlemma csets_infinite: \"infinite A \\<Longrightarrow> infinite (csets A)\"\n  by (auto simp add: csets_def, metis csets.abs_eq csets.rep_eq finite_countable_subset finite_imageI)\n\nlemma csets_UNIV:\n  \"csets (UNIV :: 'a set) = (UNIV :: 'a cset set)\"\n  by (auto simp add: csets_def, metis image_iff rcset rcset_inverse)\n\nlemma infinite_nempty_cset:\n  assumes \"infinite (UNIV :: 'a set)\"\n  shows \"infinite ({A. A \\<noteq> {}\\<^sub>c} :: 'a cset set)\"\nproof -\n  have \"infinite (UNIV :: 'a cset set)\"\n    by (metis assms csets_UNIV csets_infinite)\n  hence \"infinite ((UNIV :: 'a cset set) - {{}\\<^sub>c})\"\n    by (rule infinite_remove)\n  thus ?thesis\n    by (auto)\nqed\n\nlemma nat_set_cset_partial_bij:\n  obtains f :: \"nat set cset \\<Rightarrow> nat set\" where \"bij_betw f {A. A \\<noteq> {}\\<^sub>c} UNIV\"\n  using Schroeder_Bernstein[OF nat_set_cset_collapse_inj, of UNIV csingle, simplified, OF inj_csingle range_csingle]\n  by (auto)\n\nlemma nat_set_cset_bij:\n  obtains f :: \"nat set cset \\<Rightarrow> nat set\" where \"bij f\"\nproof -\n  obtain g :: \"nat set cset \\<Rightarrow> nat set\" where \"bij_betw g {A. A \\<noteq> {}\\<^sub>c} UNIV\"\n    using nat_set_cset_partial_bij by blast\n  moreover obtain h :: \"nat set cset \\<Rightarrow> nat set cset\" where \"bij_betw h UNIV {A. A \\<noteq> {}\\<^sub>c}\"\n  proof -\n    have \"infinite (UNIV :: nat set cset set)\"\n      by (metis Finite_Set.finite_set csets_UNIV csets_infinite infinite_UNIV_char_0)\n    then obtain h' :: \"nat set cset \\<Rightarrow> nat set cset\" where \"bij_betw h' UNIV (UNIV - {{}\\<^sub>c})\"\n      using infinite_imp_bij_betw[of \"UNIV :: nat set cset set\" \"{}\\<^sub>c\"] by auto\n    moreover have \"(UNIV :: nat set cset set) - {{}\\<^sub>c} = {A. A \\<noteq> {}\\<^sub>c}\"\n      by (auto)\n    ultimately show ?thesis\n      using that by (auto)\n  qed\n  ultimately have \"bij (g \\<circ> h)\"\n    using bij_betw_trans by blast\n  with that show ?thesis\n    by (auto)\nqed\n\ndefinition \"nat_set_cset_bij = (SOME f :: nat set cset \\<Rightarrow> nat set. bij f)\"\n\nlemma bij_nat_set_cset_bij:\n  \"bij nat_set_cset_bij\"\n  by (metis nat_set_cset_bij nat_set_cset_bij_def someI_ex)\n\nlemma inj_on_image_csets:\n  \"inj_on f A \\<Longrightarrow> inj_on ((`\\<^sub>c) f) (csets A)\"\n  by (fastforce simp add: inj_on_def cimage_def cin_def csets_def)\n\nlemma image_csets_surj:\n  \"\\<lbrakk> inj_on f A; f ` A = B \\<rbrakk> \\<Longrightarrow> (`\\<^sub>c) f ` csets A = csets B\"\n  apply (auto simp add: cimage_def csets_def image_mono map_fun_def)\n  apply (simp add: image_comp)\n  apply (auto simp add: image_Collect)\n  apply (erule subset_imageE)\n  using countable_image_inj_on subset_inj_on by blast\n\nlemma bij_betw_image_csets:\n  \"bij_betw f A B \\<Longrightarrow> bij_betw ((`\\<^sub>c) f) (csets A) (csets B)\"\n  by (simp add: bij_betw_def inj_on_image_csets image_csets_surj)\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/Countable_Set_Extra.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8558511469672594, "lm_q2_score": 0.8267117983401363, "lm_q1q2_score": 0.7075422408207713}}
{"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 \n  Z_Sets\n\nimports \n  Z_Exp\n  Z_Rel_Chap\n\nbegin\n\nsection {* The Set Order *}\n\ntext {*\n\nThe empty set, universal set and subset relations~\\cite[p 90]{Spivey:ZRef}\\cite[p 95]{ZStand02}\nare defined as operators in HOL. We make use of the existing, type-generic operators,\nwith appropriate Z-style syntax. \n\n*}\n\nlemma Z_empty_def:\n  \"\\<emptyset> = { x | \\<False> }\"\n  by (auto)\n\nlemma Z_UNIV_def:\n  \"\\<univ> = { x | \\<True> }\"\n  by (auto)\n\nlemma Z_subseteq_def:\n  \"S \\<subseteq> T \\<defs> (\\<forall> x \\<bullet> x \\<in> S \\<Rightarrow> x \\<in> T)\"\n  apply (rule eq_reflection)\n  apply (auto)\n  done\n\nlemma Z_subset_def:\n  \"S \\<subset> T \\<defs> S \\<subseteq> T \\<and> S \\<noteq> T\"\n  apply (rule eq_reflection)\n  apply (auto)\n  done\n\ntext {*\n\nThe non-empty power set~\\cite[p 90]{Spivey:ZRef}\\cite[p 96]{ZStand02} \nwe define as an operator on sets.\n\n*}\n\ndefinition\n  Pow1 :: \"'a set \\<rightarrow> 'a set set\"\nwhere\n  Z_Pow1_def: \"Pow1 X \\<defs> { S | S \\<in> \\<pset> X \\<and> S \\<noteq> \\<emptyset> }\"\n\nnotation (xsymbols)\n  Pow1 (\"\\<pset>\\<subone>\")\n\nlemma Z_notin_empty:\n  \"x \\<notin> \\<emptyset>\"\n  by (auto)\n\nlemma Z_subset_Pow:\n  \"S \\<subseteq> T \\<Leftrightarrow> S \\<in> \\<pset> T\"\n  by (auto)\n\nlemma Z_subset_refl:\n  \"S \\<subseteq> S\"\n  by (rule order_refl)\n\nlemma Z_subset_antisym:\n  \"S \\<subseteq> T \\<and> T \\<subseteq> S \\<Leftrightarrow> S = T\"\n  by (auto intro: order_antisym) \n\nlemma Z_subset_trans:\n  \"S \\<subseteq> T \\<and> T \\<subseteq> V \\<Rightarrow> S \\<subseteq> V\"\n  by (auto)\n\nlemma Z_psubset_not_refl:\n  \"\\<not>\\<^zid>{:(S \\<subset> S):}\"\n  by (auto)\n\nlemma Z_psubset_chained:\n  \"\\<not>(S \\<subset> T \\<and> T \\<subset> S)\"\n  by (auto)\n\nlemma Z_psubset_trans:\n  \"S \\<subset> T \\<and> T \\<subset> V \\<Rightarrow> S \\<subset> V\"\n  by (auto)\n\nlemma Z_empty_subset:\n  \"\\<emptyset> \\<subseteq> S\"\n  by (auto)\n\nlemma Z_empty_psubset:\n  \"\\<emptyset> \\<subset> S \\<Leftrightarrow> S \\<noteq> \\<emptyset>\"\n  by (auto)\n\nlemma Z_Pow1_empty:\n  \"\\<pset>\\<subone> X = \\<emptyset> \\<Leftrightarrow> X = \\<emptyset>\"\n  by (auto simp add: Z_Pow1_def) \n\nlemma Z_nempty_Pow1:\n  \"X \\<noteq> \\<emptyset> \\<Leftrightarrow> X \\<in> \\<pset>\\<subone> X\"\n  by (auto simp add: Z_Pow1_def)\n\nsection {* Set operators *}\n\ntext {*\n\nSet union, intersection, and difference~\\cite[p 91]{Spivey:ZRef}\\cite[p 97]{ZStand02}\nare already defined in HOL.\nWe make use of the existing, type-generic operators,\nwith appropriate Z-style syntax.\n\nDifference is type generic in Isabelle, so we provide a specialised syntax for the\nset instantiation.\n\n*}\n\nabbreviation\n  set_minus :: \"['a set, 'a set] \\<rightarrow> 'a set\" (infixl \"\\<setminus>\" 55)\nwhere\n  \"S \\<setminus> T \\<defs> S - T\"\n\n(*\n\nBPM [130408]: I think this is now unnecessary.\n\nsyntax (xsymbols output)\n  \"_Z_Sets\\<ZZ>setsub\" :: \"[logic, logic] \\<fun> logic\" (infixl \"\\<setminus>\" 55)\n\nsyntax (zed)\n  \"_Z_Sets\\<ZZ>setsub\" :: \"[logic, logic] \\<fun> logic\" (infixl \"\\<setminus>\" 55)\n\ntranslations\n  \"X \\<setminus> Y\" \\<rightharpoonup> \"(X::_ set) - Y\"\n\ntyped_print_translation {*\n\nlet\n  fun is_setT (Type(\"fun\", [Type(\"fun\", [_, Type(\"bool\", _)]), _])) = true\n   |  is_setT _ = false;\n  fun trT' flag typ [a, b] = \n    if is_setT (typ) then\n      Const(\"_Z_Sets\\<ZZ>setsub\", typ) $ a $ b\n    else\n      raise Match;\nin\n  [(\"\\<^const>HOL.minus_class.minus\", trT')]\nend;\n*}\n\n*)\n\nlemma Z_set_operations_def:\n  \"\\<forall> S T \\<bullet> \n     S \\<union> T = { x | x \\<in> S \\<or> x \\<in> T} \\<and>\n     S \\<inter> T = { x | x \\<in> S \\<and> x \\<in> T} \\<and>\n     S \\<setminus> T = { x | x \\<in> S \\<and> x \\<notin> T}\"\n  by (auto)\n\nlemma Z_union_def:\n  \"S \\<union> T = { x | x \\<in> S \\<or> x \\<in> T}\"\n  by (auto simp add: Un_def)\n\nlemma Z_inter_def:\n  \"S \\<inter> T = { x | x \\<in> S \\<and> x \\<in> T}\"\n  by (auto simp add: Int_def)\n\nlemma Z_set_diff_def:\n  \"S \\<setminus> T = { x | x \\<in> S \\<and> x \\<notin> T}\"\n  by (auto)\n\nlemma Z_set_identities:\n  shows \n    set_union_idem: \"S \\<union> S = S\" and\n    set_union_empty: \"S \\<union> \\<emptyset> = S\" and\n    set_inter_idem: \"S \\<inter> S = S\" and\n    set_diff_empty: \"S \\<setminus> \\<emptyset> = S\"\n  by (auto)\n\nlemma Z_empty_identities:\n  shows \n    set_inter_empty: \"S \\<inter> \\<emptyset> = \\<emptyset>\" and\n    set_diff_set: \"S \\<setminus> S = \\<emptyset>\" and\n    empty_diff: \"\\<emptyset> \\<setminus> S = \\<emptyset>\"\n  by (auto)\n\nlemma Z_union_comm:\n  \"S \\<union> T = T \\<union> S\"\n  by (auto)\n\nlemma Z_union_assoc:\n  \"S \\<union> (T \\<union> V) = (S \\<union> T) \\<union> V\"\n  by (auto)\n\nlemma Z_inter_comm:\n  \"S \\<inter> T = T \\<inter> S\"\n  by (auto)\n\nlemma Z_inter_assoc:\n  \"S \\<inter> (T \\<inter> V) = (S \\<inter> T) \\<inter> V\"\n  by (auto)\n\nlemma Z_union_dist:\n  \"S \\<union> (T \\<inter> V) = (S \\<union> T) \\<inter> (S \\<union> V)\"\n  by (auto)\n\nlemma Z_inter_dist:\n  \"S \\<inter> (T \\<union> V) = (S \\<inter> T) \\<union> (S \\<inter> V)\"\n  by (auto)\n\nlemma Z_partition:\n  \"(S \\<inter> T) \\<union> (S \\<setminus> T) = S\"\n  by (auto)\n\nlemma Z_diff_disjoint:\n  \"(S \\<setminus> T) \\<inter> T = \\<emptyset>\"\n  by (auto)\n\nlemma Z_union_diff:\n  \"S \\<union> (T \\<setminus> V) = (S \\<union> T) \\<setminus> (V \\<setminus> S)\"\n  by (auto)\n\nlemma Z_inter_diff:\n  \"S \\<inter> (T \\<setminus> V) = (S \\<inter> T) \\<setminus> V\"\n  by (auto)\n\nlemma Z_diff_diff1:\n  \"S \\<setminus> (T \\<setminus> V) = (S \\<setminus> T) \\<union> (S \\<inter> V)\"\n  by (auto)\n\nlemma Z_diff_diff2:\n  \"(S \\<setminus> T) \\<setminus> V = S \\<setminus> (T \\<union> V)\"\n  by (auto)\n\nlemma Z_diff_union:\n  \"(S \\<union> T) \\<setminus> V = (S \\<setminus> V) \\<union> (T \\<setminus> V)\"\n  by (auto)\n\nlemma Z_diff_inter:\n  \"S \\<setminus> (T \\<inter> V) = (S \\<setminus> T) \\<union> (S \\<setminus> V)\"\n  by (auto)\n\ntext {*\n\nThe symmetric set difference operator~\\cite[p 97]{ZStand02} is not already defined in HOL.\nWe define it as a binary set operator.\n\n*}\n\ndefinition\n  sym_diff :: \"['a set, 'a set] \\<rightarrow> 'a set\"\nwhere\n  sym_diff_def: \"sym_diff X Y \\<defs> { x | x \\<in> X \\<xor> x \\<in> Y }\"\n\nnotation (xsymbols)\n  sym_diff (infixl \"\\<ominus>\" 60)\n\nlemma Z_union_inter_diff_idem:\n  \"\\<lch> S \\<union> S \\<chEq> S \\<union> \\<emptyset> \\<chEq> S \\<inter> S \\<chEq> S \\<setminus> \\<emptyset> \\<chEq> S \\<rch>\"\n  by (simp add: set_union_idem set_union_empty set_inter_idem)\n\nlemma Z_inter_diff_empty:\n  \"\\<lch> S \\<inter> \\<emptyset> \\<chEq> S \\<setminus> S \\<chEq> \\<emptyset> \\<setminus> S \\<chEq> \\<emptyset> \\<rch>\"\n  by (simp add: set_inter_empty set_diff_set empty_diff)\n\n\ntext {*\n\nGeneralised union and intersection~\\cite[p 92]{Spivey:ZRef}\\cite[p 97]{ZStand02}\nare defined as operators in HOL.\nWe make use of the existing, type-generic operators,\nwith appropriate Z-style syntax.\n\n*}\n\nlemma Z_Union_Inter_def:\n  \"\\<forall> A \\<bullet> \n    \\<Union>A = { x | (\\<exists> S | S \\<in> A \\<bullet> x \\<in> S) } \\<and>\n    \\<Inter>A = { x | (\\<forall> S | S \\<in> A \\<bullet> x \\<in> S) }\"\n  by (auto)\n\nlemma Z_Union_def:\n  \"\\<Union>A = { x | (\\<exists> S | S \\<in> A \\<bullet> x \\<in> S) }\"\n  by (auto simp add: Union_eq)\n\nlemma Z_Inter_def:\n  \"\\<Inter>A = { x | (\\<forall> S | S \\<in> A \\<bullet> x \\<in> S) }\"\n  by (auto simp add: Inter_eq)\n\nlemma Z_Union_union_dist:\n  \"\\<Union>(A \\<union> B) = (\\<Union>A) \\<union> (\\<Union>B)\"\n  by (auto)\n\nlemma Z_Inter_union_dist:\n  \"\\<Inter>(A \\<union> B) = (\\<Inter>A) \\<inter> (\\<Inter>B)\"\n  by (auto)\n\nlemma Z_Union_empty:\n  \"\\<Union>\\<emptyset> = \\<emptyset>\"\n  by (auto)\n\ntext {* \n\nSince generalised intersection is type generic, so the intersection of the empty \nset is the whole type, rather than the set generic.\n\n*}\n\nlemma Z_Inter_empty:\n  \"\\<Inter>\\<emptyset> = \\<univ>\"                                                            \n  by (auto)\n\nlemma Z_inter_Union_dist:\n  \"S \\<inter> (\\<Union>A) = (\\<Union> T | T \\<in> A \\<bullet> S \\<inter> T)\"\n  by (auto simp add: eind_def)\n\nlemma Z_union_Inter_dist:\n  \"S \\<union> (\\<Inter>A) = (\\<Inter> T | T \\<in> A \\<bullet> S \\<union> T)\"\n  by (auto)+\n\nlemma Z_Union_diff_dist:\n  \"(\\<Union>A) \\<setminus> S = (\\<Union> T | T \\<in> A \\<bullet> T \\<setminus> S)\"\n  by (auto)+\n\nlemma Z_diff_Inter_dist:\n  \"S \\<setminus> (\\<Inter>A) = (\\<Union> T | T \\<in> A \\<bullet> S \\<setminus> T)\"\n  by (auto)+\n\nlemma Z_diff_Union_dist:\n  \"A \\<noteq> \\<emptyset> \\<Rightarrow> S \\<setminus> (\\<Union>A) = (\\<Inter> T | T \\<in> A \\<bullet> S \\<setminus> T)\"\n  by (auto)+\n\nlemma Z_Inter_diff_dist:\n  \"A \\<noteq> \\<emptyset> \\<Rightarrow> (\\<Inter>A) \\<setminus> S = (\\<Inter> T | T \\<in> A \\<bullet> T \\<setminus> S)\"\n  by (auto)+\n\nlemma Z_Union_mono:\n  \"A \\<subseteq> B \\<Rightarrow> \\<Union>A \\<subseteq> \\<Union>B\"\n  by (auto)\n\nlemma Z_Inter_antimono:\n  \"A \\<subseteq> B \\<Rightarrow> \\<Inter>B \\<subseteq> \\<Inter>A\"\n  by (auto)\n\nsection {* Finite Sets *}\n\ntext {*\n\nWe introduce finite subsets and finite non-empty \nsubsets~\\cite[p 111]{Spivey:ZRef}\\cite[p 97]{ZStand02} as set operators.\nWe define them as restrictions of the existing HOL finite set operator,\ngiving the semantics.\n\n*}\n\ndefinition\n  fin_pow :: \"'a set \\<rightarrow> 'a set set\"\nwhere\n  fin_pow_def: \"fin_pow X \\<defs> { Y | Y \\<in> \\<pset> X \\<and> finite Y }\"\n\nnotation (xsymbols)\n  fin_pow (\"\\<fset>\")\n\ndefinition\n  fin_pow1 :: \"'a set \\<rightarrow> 'a set set\"\nwhere\n  fin_pow1_def: \"fin_pow1 X \\<defs> \\<fset> X \\<setminus> {\\<emptyset>}\"\n\nnotation (zed)\n  fin_pow1 (\"\\<fset>\\<subone>\")\n\nlemma fin_pow_induct [induct set: fin_pow]:\n  assumes \n    a1: \"S \\<in> \\<fset> X\" and\n    a2: \"P \\<emptyset>\" and\n    a3: \"\\<And> x S \\<bullet> \\<lbrakk> S \\<in> \\<fset> X; P S; x \\<in> X; x \\<notin> S \\<rbrakk>  \\<turnstile> P (insert x S)\"\n  shows \"P S\"\nproof -\n  from a1 have\n    b1: \"finite S\"\n    by (simp add: fin_pow_def)\n  from b1 have \n    \"S \\<subseteq> X \\<Rightarrow> P S\"\n    apply (induct set: finite)\n    using a2 a3\n    apply (auto simp add: fin_pow_def)\n    done\n  with a1 show \"P S\"\n    by (simp add: fin_pow_def)\nqed\n\ntext {*\n\nFinally we introduce some results about the set order~\\cite[p 94]{Spivey:ZRef}.\n\n*}\n\nlemma Z_union_lub:\n  shows \n    union_ub1: \"S \\<subseteq> S \\<union> T\" and\n    union_ub2: \"T \\<subseteq> S \\<union> T\" and\n    union_least: \"S \\<subseteq> W \\<and> T \\<subseteq> W \\<Rightarrow> S \\<union> T \\<subseteq> W\"\n  by (auto)\n\nlemma Z_Union_lub:\n  shows \n    Union_ub: \"S \\<in> A \\<Rightarrow> S \\<subseteq> (\\<Union>A)\" and\n    Union_least: \"(\\<forall> S | S \\<in> A \\<bullet> S \\<subseteq> W) \\<Rightarrow> (\\<Union>A) \\<subseteq> W\"\n  by (auto)\n\nlemma Z_inter_glb:\n  shows \n    inter_lb1: \"S \\<inter> T \\<subseteq> S\" and\n    inter_lb2: \"S \\<inter> T \\<subseteq> T\" and\n    inter_greatest: \"W \\<subseteq> S \\<and> W \\<subseteq> T \\<Rightarrow> W \\<subseteq> S \\<inter> T\"\n  by (auto)\n\nlemma Z_Inter_glb:\n  shows \n    Z_Inter_lb: \"S \\<in> A \\<Rightarrow> (\\<Inter>A) \\<subseteq> S\" and\n    Z_Inter_greatest: \"(\\<forall> S | S \\<in> A \\<bullet> W \\<subseteq> S) \\<Rightarrow> W \\<subseteq> (\\<Inter>A)\"\n  by (auto)\n\nlemma diff_gdlb:\n  shows \n    diff_lb: \"S \\<setminus> T \\<subseteq> S\" and\n    diff_disjoint: \"(S \\<setminus> T) \\<inter> T = \\<emptyset>\" and\n    diff_greatest: \"W \\<subseteq> S \\<and> W \\<inter> T = \\<emptyset> \\<Rightarrow> W \\<subseteq> S \\<setminus> T\"\n  by (auto)\n\nend\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/Z_Sets.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511506439708, "lm_q2_score": 0.8267117940706734, "lm_q1q2_score": 0.7075422402063273}}
{"text": "(*  Title:      HOL/Nunchaku_Examples/Core_Nuns.thy\n    Author:     Jasmin Blanchette, Inria Nancy, LORIA, MPII\n    Copyright   2009-2015\n\nExamples featuring Nunchaku's functional core.\n*)\n\nsection {* Examples Featuring Nunchaku's Functional Core *}\n\ntheory Core_Nuns\nimports \"../Nunchaku\"\nbegin\n\nnunchaku_params [verbose, max_potential = 0, timeout = 240]\n\n\nsubsection {* Curry in a Hurry *}\n\nlemma \"(\\<lambda>f x y. (curry o case_prod) f x y) = (\\<lambda>f x y. (\\<lambda>x. x) f x y)\"\nnunchaku [expect = none]\nby auto\n\nlemma \"(\\<lambda>f p. (case_prod o curry) f p) = (\\<lambda>f p. (\\<lambda>x. x) f p)\"\nnunchaku [expect = none]\nby auto\n\nlemma \"case_prod (curry f) = f\"\nnunchaku [expect = none]\nby auto\n\nlemma \"curry (case_prod f) = f\"\nnunchaku [expect = none]\nby auto\n\nlemma \"case_prod (\\<lambda>x y. f (x, y)) = f\"\nnunchaku [expect = none]\nby auto\n\n\nsubsection {* Representations *}\n\nlemma \"\\<exists>f. f = (\\<lambda>x. x) \\<and> f y = y\"\nnunchaku [expect = none]\nby auto\n\nlemma \"(\\<exists>g. \\<forall>x. g (f x) = x) \\<longrightarrow> (\\<forall>y. \\<exists>x. y = f x)\"\nnunchaku [card 'a = 25, card 'b = 24, expect = genuine]\nnunchaku [mono, expect = none]\noops\n\nlemma \"\\<exists>f. f = (\\<lambda>x. x) \\<and> f y \\<noteq> y\"\nnunchaku [expect = genuine]\noops\n\nlemma \"P (\\<lambda>x. x)\"\nnunchaku [expect = genuine]\noops\n\nlemma \"{(a :: 'a \\<times> 'a, b :: 'b)}^-1 = {(b, a)}\"\nnunchaku [expect = none]\nby auto\n\nlemma \"fst (a, b) = a\"\nnunchaku [expect = none]\nby auto\n\nlemma \"\\<exists>P. P = Id\"\nnunchaku [expect = none]\nby auto\n\nlemma \"(a :: 'a \\<Rightarrow> 'b, a) \\<in> Id\\<^sup>*\"\nnunchaku [expect = none]\nby auto\n\nlemma \"(a :: 'a \\<times> 'a, a) \\<in> Id\\<^sup>* \\<union> {(a, b)}\\<^sup>*\"\nnunchaku [expect = none]\nby auto\n\nlemma \"(a, a) \\<in> Id\"\nnunchaku [expect = none]\nby (auto simp: Id_def)\n\nlemma \"((a :: 'a, b :: 'a), (a, b)) \\<in> Id\"\nnunchaku [expect = none]\nby (auto simp: Id_def)\n\nlemma \"(x :: 'a \\<times> 'a) \\<in> UNIV\"\nnunchaku [expect = none]\nsorry\n\nlemma \"{} = A - A\"\nnunchaku [expect = none]\nby auto\n\nlemma \"g = Let (A \\<or> B)\"\nnunchaku [expect = genuine]\noops\n\nlemma \"(let a_or_b = A \\<or> B in a_or_b \\<or> \\<not> a_or_b)\"\nnunchaku [expect = none]\nby auto\n\nlemma \"A \\<subseteq> B\"\nnunchaku [expect = genuine]\noops\n\nlemma \"A = {b}\"\nnunchaku [expect = genuine]\noops\n\nlemma \"{a, b} = {b}\"\nnunchaku [expect = genuine]\noops\n\nlemma \"(a :: 'a \\<times> 'a, a :: 'a \\<times> 'a) \\<in> R\"\nnunchaku [expect = genuine]\noops\n\nlemma \"f (g :: 'a \\<Rightarrow> 'a) = x\"\nnunchaku [expect = genuine]\noops\n\nlemma \"f (a, b) = x\"\nnunchaku [expect = genuine]\noops\n\nlemma \"f (a, a) = f (c, d)\"\nnunchaku [expect = genuine]\noops\n\nlemma \"(x :: 'a) = (\\<lambda>a. \\<lambda>b. \\<lambda>c. if c then a else b) x x True\"\nnunchaku [expect = none]\nby auto\n\nlemma \"\\<exists>F. F a b = G a b\"\nnunchaku [expect = none]\nby auto\n\nlemma \"f = case_prod\"\nnunchaku [expect = genuine]\noops\n\nlemma \"(A :: 'a \\<times> 'a, B :: 'a \\<times> 'a) \\<in> R \\<Longrightarrow> (A, B) \\<in> R\"\nnunchaku [expect = none]\nby auto\n\nlemma \"(A, B) \\<in> R \\<or> (\\<exists>C. (A, C) \\<in> R \\<and> (C, B) \\<in> R) \\<Longrightarrow>\n       A = B \\<or> (A, B) \\<in> R \\<or> (\\<exists>C. (A, C) \\<in> R \\<and> (C, B) \\<in> R)\"\nnunchaku [expect = none]\nby auto\n\nlemma \"f = (\\<lambda>x :: 'a \\<times> 'b. x)\"\nnunchaku [expect = genuine]\noops\n\n\nsubsection {* Quantifiers *}\n\nlemma \"x = y\"\nnunchaku [expect = genuine]\noops\n\nlemma \"\\<forall>x. x = y\"\nnunchaku [expect = genuine]\noops\n\nlemma \"\\<forall>x :: 'a \\<Rightarrow> bool. x = y\"\nnunchaku [expect = genuine]\noops\n\nlemma \"\\<exists>x :: 'a \\<Rightarrow> bool. x = y\"\nnunchaku [expect = unknown]\nby auto\n\nlemma \"\\<exists>x y :: 'a \\<Rightarrow> bool. x = y\"\nnunchaku [expect = unknown]\nby auto\n\nlemma \"\\<forall>x. \\<exists>y. f x y = f x (g x)\"\nnunchaku [expect = none]\nby auto\n\nlemma \"\\<forall>u. \\<exists>v. \\<forall>w. \\<exists>x. f u v w x = f u (g u) w (h u w)\"\nnunchaku [expect = none]\nby auto\n\nlemma \"\\<forall>u. \\<exists>v. \\<forall>w. \\<exists>x. f u v w x = f u (g u w) w (h u)\"\nnunchaku [expect = genuine]\noops\n\nlemma \"\\<forall>u. \\<exists>v. \\<forall>w. \\<exists>x. \\<forall>y. \\<exists>z. f u v w x y z = f u (g u) w (h u w) y (k u w y)\"\nnunchaku [expect = none]\nby auto\n\nlemma \"\\<forall>u. \\<exists>v. \\<forall>w. \\<exists>x. \\<forall>y. \\<exists>z. f u v w x y z = f u (g u) w (h u w y) y (k u w y)\"\nnunchaku [expect = genuine]\noops\n\nlemma \"\\<forall>u. \\<exists>v. \\<forall>w. \\<exists>x. \\<forall>y. \\<exists>z. f u v w x y z = f u (g u w) w (h u w) y (k u w y)\"\nnunchaku [expect = genuine]\noops\n\nlemma \"\\<forall>u :: 'a \\<times> 'b. \\<exists>v :: 'c. \\<forall>w :: 'd. \\<exists>x :: 'e \\<times> 'f. f u v w x = f u (g u) w (h u w)\"\nnunchaku [expect = none]\nby blast\n\nlemma \"\\<forall>u :: 'a \\<times> 'b. \\<exists>v :: 'c. \\<forall>w :: 'd. \\<exists>x :: 'e \\<times> 'f. f u v w x = f u (g u w) w (h u)\"\nnunchaku [expect = genuine]\noops\n\nlemma \"\\<forall>u :: 'a \\<Rightarrow> 'b. \\<exists>v :: 'c. \\<forall>w :: 'd. \\<exists>x :: 'e \\<Rightarrow> 'f. f u v w x = f u (g u) w (h u w)\"\nnunchaku [expect = none]\nby blast\n\nlemma \"\\<forall>u :: 'a \\<Rightarrow> 'b. \\<exists>v :: 'c. \\<forall>w :: 'd. \\<exists>x :: 'e \\<Rightarrow> 'f. f u v w x = f u (g u w) w (h u)\"\nnunchaku [expect = genuine]\noops\n\nlemma \"\\<forall>x. if \\<forall>y. x = y then False else True\"\nnunchaku [expect = genuine]\noops\n\nlemma \"\\<forall>x :: 'a \\<times> 'b. if \\<forall>y. x = y then False else True\"\nnunchaku [expect = genuine]\noops\n\nlemma \"\\<forall>x. if \\<exists>y. x = y then True else False\"\nnunchaku [expect = none]\nby simp\n\nlemma \"(\\<exists>x :: 'a. \\<forall>y. P x y) \\<or> (\\<exists>x :: 'a \\<times> 'a. \\<forall>y. P y x)\"\nnunchaku [expect = genuine]\noops\n\nlemma \"\\<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)\"\nnunchaku [expect = none]\nby auto\n\nlemma \"\\<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)\"\nnunchaku [expect = none]\nby auto\n\nlemma \"let x = (\\<forall>x. P x) in if x then x else \\<not> x\"\nnunchaku [expect = none]\nby auto\n\nlemma \"let x = (\\<forall>x :: 'a \\<times> 'b. P x) in if x then x else \\<not> x\"\nnunchaku [expect = none]\nby auto\n\n\nsubsection {* Schematic Variables *}\n\nschematic_goal \"x = ?x\"\nnunchaku [expect = none]\nby auto\n\nschematic_goal \"\\<forall>x. x = ?x\"\nnunchaku [expect = genuine]\noops\n\nschematic_goal \"\\<exists>x. x = ?x\"\nnunchaku [expect = none]\nby auto\n\nschematic_goal \"\\<exists>x :: 'a \\<Rightarrow> 'b. x = ?x\"\nnunchaku [expect = unknown]\nby auto\n\nschematic_goal \"\\<forall>x. ?x = ?y\"\nnunchaku [expect = none]\nby auto\n\nschematic_goal \"\\<exists>x. ?x = ?y\"\nnunchaku [expect = none]\nby auto\n\n\nsubsection {* Known Constants *}\n\nlemma \"\\<And>x. f x y = f x y\"\nnunchaku [expect = none]\noops\n\nlemma \"\\<And>x. f x y = f y x\"\nnunchaku [expect = genuine]\noops\n\nlemma \"P x \\<equiv> P x\"\nnunchaku [expect = none]\nby auto\n\nlemma \"P x \\<equiv> Q x \\<Longrightarrow> P x = Q x\"\nnunchaku [expect = none]\nby auto\n\nlemma \"P x = Q x \\<Longrightarrow> P x \\<equiv> Q x\"\nnunchaku [expect = none]\nby auto\n\nlemma \"P x \\<Longrightarrow> P x\"\nnunchaku [expect = none]\nby auto\n\nlemma \"True \\<Longrightarrow> True\" \"False \\<Longrightarrow> True\" \"False \\<Longrightarrow> False\"\nnunchaku [expect = none]\nby auto\n\nlemma \"True \\<Longrightarrow> False\"\nnunchaku [expect = genuine]\noops\n\nlemma \"x = Not\"\nnunchaku [expect = genuine]\noops\n\nlemma \"I = (\\<lambda>x. x) \\<Longrightarrow> Not = (\\<lambda>x. Not (I x))\"\nnunchaku [expect = none]\nby auto\n\nlemma \"x = True\"\nnunchaku [expect = genuine]\noops\n\nlemma \"x = False\"\nnunchaku [expect = genuine]\noops\n\nlemma \"x = undefined\"\nnunchaku [expect = genuine]\noops\n\nlemma \"(False, ()) = undefined \\<Longrightarrow> ((), False) = undefined\"\nnunchaku [expect = genuine]\noops\n\nlemma \"undefined = undefined\"\nnunchaku [expect = none]\nby auto\n\nlemma \"f undefined = f undefined\"\nnunchaku [expect = none]\nby auto\n\nlemma \"f undefined = g undefined\"\nnunchaku [expect = genuine]\noops\n\nlemma \"\\<exists>!x. x = undefined\"\nnunchaku [expect = none]\nby auto\n\nlemma \"\\<forall>x. f x y = f x y\"\nnunchaku [expect = none]\noops\n\nlemma \"\\<forall>x. f x y = f y x\"\nnunchaku [expect = genuine]\noops\n\nlemma \"All (\\<lambda>x. f x y = f x y) = True\"\nnunchaku [expect = none]\nby auto\n\nlemma \"All (\\<lambda>x. f x y = f x y) = False\"\nnunchaku [expect = genuine]\noops\n\nlemma \"x = Ex \\<Longrightarrow> False\"\nnunchaku [expect = genuine]\noops\n\nlemma \"\\<exists>x. f x y = f x y\"\nnunchaku [expect = none]\noops\n\nlemma \"\\<exists>x. f x y = f y x\"\nnunchaku [expect = none]\noops\n\nlemma \"Ex (\\<lambda>x. f x y = f x y) = True\"\nnunchaku [expect = none]\nby auto\n\nlemma \"Ex (\\<lambda>x. f x y = f y x) = True\"\nnunchaku [expect = none]\nby auto\n\nlemma \"Ex (\\<lambda>x. f x y = f x y) = False\"\nnunchaku [expect = genuine]\noops\n\nlemma \"Ex (\\<lambda>x. f x y \\<noteq> f x y) = False\"\nnunchaku [expect = none]\nby auto\n\nlemma \"I = (\\<lambda>x. x) \\<Longrightarrow> Ex P = Ex (\\<lambda>x. P (I x))\"\nnunchaku [expect = none]\nby auto\n\nlemma \"x = y \\<Longrightarrow> y = x\"\nnunchaku [expect = none]\nby auto\n\nlemma \"x = y \\<Longrightarrow> f x = f y\"\nnunchaku [expect = none]\nby auto\n\nlemma \"x = y \\<and> y = z \\<Longrightarrow> x = z\"\nnunchaku [expect = none]\nby auto\n\nlemma\n  \"I = (\\<lambda>x. x) \\<Longrightarrow> (op \\<and>) = (\\<lambda>x. op \\<and> (I x))\"\n  \"I = (\\<lambda>x. x) \\<Longrightarrow> (op \\<and>) = (\\<lambda>x y. x \\<and> (I y))\"\nnunchaku [expect = none]\nby auto\n\nlemma \"(a \\<and> b) = (\\<not> (\\<not> a \\<or> \\<not> b))\"\nnunchaku [expect = none]\nby auto\n\nlemma \"a \\<and> b \\<Longrightarrow> a\" \"a \\<and> b \\<Longrightarrow> b\"\nnunchaku [expect = none]\nby auto\n\nlemma \"(op \\<longrightarrow>) = (\\<lambda>x. op \\<longrightarrow> x)\" \"(op \\<longrightarrow> ) = (\\<lambda>x y. x \\<longrightarrow> y)\"\nnunchaku [expect = none]\nby auto\n\nlemma \"((if a then b else c) = d) = ((a \\<longrightarrow> (b = d)) \\<and> (\\<not> a \\<longrightarrow> (c = d)))\"\nnunchaku [expect = none]\nby auto\n\nlemma \"(if a then b else c) = (THE d. (a \\<longrightarrow> (d = b)) \\<and> (\\<not> a \\<longrightarrow> (d = c)))\"\nnunchaku [expect = none]\nby auto\n\nlemma \"fst (x, y) = x\"\nnunchaku [expect = none]\nby simp\n\nlemma \"snd (x, y) = y\"\nnunchaku [expect = none]\nby simp\n\nlemma \"fst (x :: 'a \\<Rightarrow> 'b, y) = x\"\nnunchaku [expect = none]\nby simp\n\nlemma \"snd (x :: 'a \\<Rightarrow> 'b, y) = y\"\nnunchaku [expect = none]\nby simp\n\nlemma \"fst (x, y :: 'a \\<Rightarrow> 'b) = x\"\nnunchaku [expect = none]\nby simp\n\nlemma \"snd (x, y :: 'a \\<Rightarrow> 'b) = y\"\nnunchaku [expect = none]\nby simp\n\nlemma \"fst (x :: 'a \\<times> 'b, y) = x\"\nnunchaku [expect = none]\nby simp\n\nlemma \"snd (x :: 'a \\<times> 'b, y) = y\"\nnunchaku [expect = none]\nby simp\n\nlemma \"fst (x, y :: 'a \\<times> 'b) = x\"\nnunchaku [expect = none]\nby simp\n\nlemma \"snd (x, y :: 'a \\<times> 'b) = y\"\nnunchaku [expect = none]\nby simp\n\nlemma \"I = (\\<lambda>x. x) \\<Longrightarrow> fst = (\\<lambda>x. fst (I x))\"\nnunchaku [expect = none]\nby auto\n\nlemma \"fst (x, y) = snd (y, x)\"\nnunchaku [expect = none]\nby auto\n\nlemma \"(x, x) \\<in> Id\"\nnunchaku [expect = none]\nby auto\n\nlemma \"(x, y) \\<in> Id \\<Longrightarrow> x = y\"\nnunchaku [expect = none]\nby auto\n\nlemma \"I = (\\<lambda>x. x) \\<Longrightarrow> Id = {x. I x \\<in> Id}\"\nnunchaku [expect = none]\nby auto\n\nlemma \"{} = {x. False}\"\nnunchaku [expect = none]\nby simp\n\nlemma \"x \\<in> {}\"\nnunchaku [expect = genuine]\noops\n\nlemma \"{a, b} = {b}\"\nnunchaku [expect = genuine]\noops\n\nlemma \"{a, b} \\<noteq> {b}\"\nnunchaku [expect = genuine]\noops\n\nlemma \"{a} = {b}\"\nnunchaku [expect = genuine]\noops\n\nlemma \"{a} \\<noteq> {b}\"\nnunchaku [expect = genuine]\noops\n\nlemma \"{a, b, c} = {c, b, a}\"\nnunchaku [expect = unknown]\nby auto\n\nlemma \"UNIV = {x. True}\"\nnunchaku [expect = none]\nby simp\n\nlemma \"x \\<in> UNIV \\<longleftrightarrow> True\"\nnunchaku [expect = none]\nby simp\n\nlemma \"x \\<notin> UNIV\"\nnunchaku [expect = genuine]\noops\n\nlemma \"I = (\\<lambda>x. x) \\<Longrightarrow> op \\<in> = (\\<lambda>x. (op \\<in> (I x)))\"\nnunchaku [expect = none]\napply (rule ext)\napply (rule ext)\nby simp\n\nlemma \"insert = (\\<lambda>x y. insert x (y \\<union> y))\"\nnunchaku [expect = none]\nby simp\n\nlemma \"I = (\\<lambda>x. x) \\<Longrightarrow> trancl = (\\<lambda>x. trancl (I x))\"\nnunchaku [expect = none]\nby auto\n\nlemma \"rtrancl = (\\<lambda>x. rtrancl x \\<union> {(y, y)})\"\nnunchaku [expect = none]\napply (rule ext)\nby auto\n\nlemma \"(x, x) \\<in> rtrancl {(y, y)}\"\nnunchaku [expect = none]\nby auto\n\nlemma \"((x, x), (x, x)) \\<in> rtrancl {}\"\nnunchaku [expect = none]\nby auto\n\nlemma \"I = (\\<lambda>x. x) \\<Longrightarrow> op \\<union> = (\\<lambda>x. op \\<union> (I x))\"\nnunchaku [expect = none]\nby auto\n\nlemma \"a \\<in> A \\<Longrightarrow> a \\<in> A \\<union> B\" \"b \\<in> B \\<Longrightarrow> b \\<in> A \\<union> B\"\nnunchaku [expect = none]\nby auto\n\nlemma \"I = (\\<lambda>x. x) \\<Longrightarrow> op \\<inter> = (\\<lambda>x. op \\<inter> (I x))\"\nnunchaku [expect = none]\nby auto\n\nlemma \"a \\<notin> A \\<Longrightarrow> a \\<notin> A \\<inter> B\" \"b \\<notin> B \\<Longrightarrow> b \\<notin> A \\<inter> B\"\nnunchaku [expect = none]\nby auto\n\nlemma \"x \\<in> ((A :: 'a set) - B) \\<longleftrightarrow> x \\<in> A \\<and> x \\<notin> B\"\nnunchaku [expect = none]\nby auto\n\nlemma \"I = (\\<lambda>x. x) \\<Longrightarrow> op \\<subset> = (\\<lambda>x. op \\<subset> (I x))\"\nnunchaku [expect = none]\nby auto\n\nlemma \"A \\<subset> B \\<Longrightarrow> (\\<forall>a \\<in> A. a \\<in> B) \\<and> (\\<exists>b \\<in> B. b \\<notin> A)\"\nnunchaku [expect = none]\nby auto\n\nlemma \"A \\<subseteq> B \\<Longrightarrow> \\<forall>a \\<in> A. a \\<in> B\"\nnunchaku [expect = none]\nby auto\n\nlemma \"A \\<subseteq> B \\<Longrightarrow> A \\<subset> B\"\nnunchaku [expect = genuine]\noops\n\nlemma \"A \\<subset> B \\<Longrightarrow> A \\<subseteq> B\"\nnunchaku [expect = none]\nby auto\n\nlemma \"I = (\\<lambda>x :: 'a set. x) \\<Longrightarrow> uminus = (\\<lambda>x. uminus (I x))\"\nnunchaku [expect = none]\nby auto\n\nlemma \"A \\<union> - A = UNIV\"\nnunchaku [expect = none]\nby auto\n\nlemma \"A \\<inter> - A = {}\"\nnunchaku [expect = none]\nby auto\n\nlemma \"A = - A\"\nnunchaku [expect = genuine]\noops\n\nlemma \"finite A\"\nnunchaku [expect = none]\noops\n\nlemma \"finite A \\<Longrightarrow> finite B\"\nnunchaku [expect = none]\noops\n\nlemma \"All finite\"\nnunchaku [expect = none]\noops\n\nsubsection {* The and Eps *}\n\nlemma \"x = The\"\nnunchaku [expect = genuine]\noops\n\nlemma \"\\<exists>x. x = The\"\nnunchaku [expect = none]\noops\n\nlemma \"P x \\<Longrightarrow> P (The P)\"\nnunchaku [expect = genuine]\noops\n\nlemma \"(\\<forall>x. \\<not> P x) \\<longrightarrow> The P = y\"\nnunchaku [expect = genuine]\noops\n\nlemma \"I = (\\<lambda>x. x) \\<Longrightarrow> The = (\\<lambda>x. The (I x))\"\nnunchaku [expect = none]\nby auto\n\nlemma \"x = Eps\"\nnunchaku [expect = genuine]\noops\n\nlemma \"\\<exists>x. x = Eps\"\nnunchaku [expect = none]\nby auto\n\nlemma \"P x \\<and> (\\<forall>y. P y \\<longrightarrow> y = x) \\<longrightarrow> Eps P = x\"\nnunchaku [expect = none]\nby auto\n\nlemma \"P x \\<and> P y \\<and> x \\<noteq> y \\<longrightarrow> Eps P = z\"\nnunchaku [expect = genuine]\napply auto\noops\n\nlemma \"P x \\<Longrightarrow> P (Eps P)\"\nnunchaku [expect = none]\nby (metis exE_some)\n\nlemma \"\\<forall>x. \\<not> P x \\<longrightarrow> Eps P = y\"\nnunchaku [expect = genuine]\noops\n\nlemma \"P (Eps P)\"\nnunchaku [expect = genuine]\noops\n\nlemma \"Eps (\\<lambda>x. x \\<in> P) \\<in> (P :: nat set)\"\nnunchaku [expect = genuine]\noops\n\nlemma \"\\<not> P (Eps P)\"\nnunchaku [expect = genuine]\noops\n\nlemma \"\\<not> (P :: nat \\<Rightarrow> bool) (Eps P)\"\nnunchaku [expect = genuine]\noops\n\nlemma \"P \\<noteq> bot \\<Longrightarrow> P (Eps P)\"\nnunchaku [expect = none]\nsorry\n\nlemma \"(P :: nat \\<Rightarrow> bool) \\<noteq> bot \\<Longrightarrow> P (Eps P)\"\nnunchaku [expect = none]\nsorry\n\nlemma \"P (The P)\"\nnunchaku [expect = genuine]\noops\n\nlemma \"(P :: nat \\<Rightarrow> bool) (The P)\"\nnunchaku [expect = genuine]\noops\n\nlemma \"\\<not> P (The P)\"\nnunchaku [expect = genuine]\noops\n\nlemma \"\\<not> (P :: nat \\<Rightarrow> bool) (The P)\"\nnunchaku [expect = genuine]\noops\n\nlemma \"The P \\<noteq> x\"\nnunchaku [expect = genuine]\noops\n\nlemma \"The P \\<noteq> (x :: nat)\"\nnunchaku [expect = genuine]\noops\n\nlemma \"P x \\<Longrightarrow> P (The P)\"\nnunchaku [expect = genuine]\noops\n\nlemma \"P (x :: nat) \\<Longrightarrow> P (The P)\"\nnunchaku [expect = genuine]\noops\n\nlemma \"P = {x} \\<Longrightarrow> (THE x. x \\<in> P) \\<in> P\"\nnunchaku [expect = none]\noops\n\nlemma \"P = {x :: nat} \\<Longrightarrow> (THE x. x \\<in> P) \\<in> P\"\nnunchaku [expect = none]\noops\n\nconsts Q :: 'a\n\nlemma \"Q (Eps Q)\"\nnunchaku [expect = genuine]\noops\n\nlemma \"(Q :: nat \\<Rightarrow> bool) (Eps Q)\"\nnunchaku [expect = genuine]\noops\n\nlemma \"\\<not> (Q :: nat \\<Rightarrow> bool) (Eps Q)\"\nnunchaku [expect = genuine]\noops\n\nlemma \"\\<not> (Q :: nat \\<Rightarrow> bool) (Eps Q)\"\nnunchaku [expect = genuine]\noops\n\nlemma \"(Q :: 'a \\<Rightarrow> bool) \\<noteq> bot \\<Longrightarrow> (Q :: 'a \\<Rightarrow> bool) (Eps Q)\"\nnunchaku [expect = none]\nsorry\n\nlemma \"(Q :: nat \\<Rightarrow> bool) \\<noteq> bot \\<Longrightarrow> (Q :: nat \\<Rightarrow> bool) (Eps Q)\"\nnunchaku [expect = none]\nsorry\n\nlemma \"Q (The Q)\"\nnunchaku [expect = genuine]\noops\n\nlemma \"(Q :: nat \\<Rightarrow> bool) (The Q)\"\nnunchaku [expect = genuine]\noops\n\nlemma \"\\<not> Q (The Q)\"\nnunchaku [expect = genuine]\noops\n\nlemma \"\\<not> (Q :: nat \\<Rightarrow> bool) (The Q)\"\nnunchaku [expect = genuine]\noops\n\nlemma \"The Q \\<noteq> x\"\nnunchaku [expect = genuine]\noops\n\nlemma \"The Q \\<noteq> (x :: nat)\"\nnunchaku [expect = genuine]\noops\n\nlemma \"Q x \\<Longrightarrow> Q (The Q)\"\nnunchaku [expect = genuine]\noops\n\nlemma \"Q (x :: nat) \\<Longrightarrow> Q (The Q)\"\nnunchaku [expect = genuine]\noops\n\nlemma \"Q = (\\<lambda>x :: 'a. x = a) \\<Longrightarrow> (Q :: 'a \\<Rightarrow> bool) (The Q)\"\nnunchaku [expect = none]\nsorry\n\nlemma \"Q = (\\<lambda>x :: nat. x = a) \\<Longrightarrow> (Q :: nat \\<Rightarrow> bool) (The Q)\"\nnunchaku [expect = none]\nsorry\n\nlemma \"(THE j. j > Suc 2 \\<and> j \\<le> 3) \\<noteq> 0\"\nnunchaku [expect = genuine]\noops\n\nlemma \"(THE j. j > Suc 2 \\<and> j \\<le> 4) = x \\<Longrightarrow> x \\<noteq> 0\"\nnunchaku [expect = none]\nsorry\n\nlemma \"(THE j. j > Suc 2 \\<and> j \\<le> 4) = x \\<Longrightarrow> x = 4\"\nnunchaku [expect = none]\nsorry\n\nlemma \"(THE j. j > Suc 2 \\<and> j \\<le> 5) = x \\<Longrightarrow> x = 4\"\nnunchaku [expect = genuine]\noops\n\nlemma \"(THE j. j > Suc 2 \\<and> j \\<le> 5) = x \\<Longrightarrow> x = 4 \\<or> x = 5\"\nnunchaku [expect = genuine]\noops\n\nlemma \"(SOME j. j > Suc 2 \\<and> j \\<le> 3) \\<noteq> 0\"\nnunchaku [expect = genuine]\noops\n\nlemma \"(SOME j. j > Suc 2 \\<and> j \\<le> 4) = x \\<Longrightarrow> x \\<noteq> 0\"\nnunchaku [expect = none]\nsorry\n\nlemma \"(SOME j. j > Suc 2 \\<and> j \\<le> 4) = x \\<Longrightarrow> x = 4\"\nnunchaku [expect = none]\nsorry\n\nlemma \"(SOME j. j > Suc 2 \\<and> j \\<le> 5) = x \\<Longrightarrow> x = 4\"\nnunchaku [expect = genuine]\noops\n\nlemma \"(SOME j. j > Suc 2 \\<and> j \\<le> 5) = x \\<Longrightarrow> x = 4 \\<or> x = 5\"\nnunchaku [expect = none]\nsorry\n\n\nsubsection {* Destructors and Recursors *}\n\nlemma \"(x :: 'a) = (case True of True \\<Rightarrow> x | False \\<Rightarrow> x)\"\nnunchaku [expect = none]\nby auto\n\nlemma \"x = (case (x, y) of (x', y') \\<Rightarrow> x')\"\nnunchaku [expect = none]\nby auto\n\nend\n", "meta": {"author": "nunchaku-inria", "repo": "isabelle-nunchaku", "sha": "c3508f581c3a17bb8e1fdebb20c29fc5e3d061be", "save_path": "github-repos/isabelle/nunchaku-inria-isabelle-nunchaku", "path": "github-repos/isabelle/nunchaku-inria-isabelle-nunchaku/isabelle-nunchaku-c3508f581c3a17bb8e1fdebb20c29fc5e3d061be/Nunchaku_Examples/Core_Nuns.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511396138366, "lm_q2_score": 0.8267117940706734, "lm_q1q2_score": 0.7075422310875853}}
{"text": "(*  Title:       The Cauchy-Schwarz Inequality\n    Author:      Benjamin Porter <Benjamin.Porter at gmail.com>, 2006\n    Maintainer:  Benjamin Porter <Benjamin.Porter at gmail.com>\n*)\n\nchapter \\<open>The Cauchy-Schwarz Inequality\\<close>\n\ntheory CauchySchwarz\nimports Complex_Main\nbegin\n\n(*<*)\n\n(* Some basic results that don't need to be in the final doc ..*)\n\n\nlemmas real_sq = power2_eq_square [where 'a = real, symmetric]\n\nlemmas real_sq_exp = power_mult_distrib [where 'a = real and ?n = 2]\n\nlemma double_sum_equiv:\n  fixes f::\"nat \\<Rightarrow> real\"\n  shows\n  \"(\\<Sum>k\\<in>{1..n}. (\\<Sum>j\\<in>{1..n}. f k * g j)) =\n   (\\<Sum>k\\<in>{1..n}. (\\<Sum>j\\<in>{1..n}. f j * g k))\"\n  by (rule sum.swap)\n\n(*>*)\n\n\n\nsection \\<open>Abstract\\<close>\n\ntext \\<open>The following document presents a formalised proof of the\nCauchy-Schwarz Inequality for the specific case of $R^n$. The system\nused is Isabelle/Isar. \n\n{\\em Theorem:} Take $V$ to be some vector space possessing a norm and\ninner product, then for all $a,b \\in V$ the following inequality\nholds: \\<open>\\<bar>a\\<cdot>b\\<bar> \\<le> \\<parallel>a\\<parallel>*\\<parallel>b\\<parallel>\\<close>. Specifically, in the Real case, the\nnorm is the Euclidean length and the inner product is the standard dot\nproduct.\\<close>\n\n\nsection \\<open>Formal Proof\\<close>\n\nsubsection \\<open>Vector, Dot and Norm definitions.\\<close>\n\ntext \\<open>This section presents definitions for a real vector type, a\ndot product function and a norm function.\\<close>\n\nsubsubsection \\<open>Vector\\<close>\n\ntext \\<open>We now define a vector type to be a tuple of (function,\nlength). Where the function is of type @{typ \"nat\\<Rightarrow>real\"}. We also\ndefine some accessor functions and appropriate notation.\\<close>\n\ntype_synonym vector = \"(nat\\<Rightarrow>real) * nat\"\n\ndefinition\n  ith :: \"vector \\<Rightarrow> nat \\<Rightarrow> real\" (\"((_)\\<^bsub>_\\<^esub>)\" [80,100] 100) where\n  \"ith v i = fst v i\"\n\ndefinition\n  vlen :: \"vector \\<Rightarrow> nat\" where\n  \"vlen v = snd v\"\n\ntext \\<open>Now to access the second element of some vector $v$ the syntax\nis $v_2$.\\<close>\n\nsubsubsection \\<open>Dot and Norm\\<close>\n\ntext \\<open>We now define the dot product and norm operations.\\<close>\n\ndefinition\n  dot :: \"vector \\<Rightarrow> vector \\<Rightarrow> real\" (infixr \"\\<cdot>\" 60) where\n  \"dot a b = (\\<Sum>j\\<in>{1..(vlen a)}. a\\<^bsub>j\\<^esub>*b\\<^bsub>j\\<^esub>)\"\n\ndefinition\n  norm :: \"vector \\<Rightarrow> real\"                  (\"\\<parallel>_\\<parallel>\" 100) where\n  \"norm v = sqrt (\\<Sum>j\\<in>{1..(vlen v)}. v\\<^bsub>j\\<^esub>^2)\"\n\ntext \\<open>Another definition of the norm is @{term \"\\<parallel>v\\<parallel> = sqrt\n(v\\<cdot>v)\"}. We show that our definition leads to this one.\\<close>\n\nlemma norm_dot:\n \"\\<parallel>v\\<parallel> = sqrt (v\\<cdot>v)\"\nproof -\n  have \"sqrt (v\\<cdot>v) = sqrt (\\<Sum>j\\<in>{1..(vlen v)}. v\\<^bsub>j\\<^esub>*v\\<^bsub>j\\<^esub>)\" unfolding dot_def by simp\n  also with real_sq have \"\\<dots> = sqrt (\\<Sum>j\\<in>{1..(vlen v)}. v\\<^bsub>j\\<^esub>^2)\" by simp\n  also have \"\\<dots> = \\<parallel>v\\<parallel>\" unfolding norm_def by simp\n  finally show ?thesis ..\nqed\n\ntext \\<open>A further important property is that the norm is never negative.\\<close>\n\nlemma norm_pos:\n  \"\\<parallel>v\\<parallel> \\<ge> 0\"\nproof -\n  have \"\\<forall>j. v\\<^bsub>j\\<^esub>^2 \\<ge> 0\" unfolding ith_def by auto\n  have \"(\\<Sum>j\\<in>{1..(vlen v)}. v\\<^bsub>j\\<^esub>^2) \\<ge> 0\" by (simp add: sum_nonneg)\n  with real_sqrt_ge_zero have \"sqrt (\\<Sum>j\\<in>{1..(vlen v)}. v\\<^bsub>j\\<^esub>^2) \\<ge> 0\" .\n  thus ?thesis unfolding norm_def .\nqed\n\ntext \\<open>We now prove an intermediary lemma regarding double summation.\\<close>\n\nlemma double_sum_aux:\n  fixes f::\"nat \\<Rightarrow> real\"\n  shows\n  \"(\\<Sum>k\\<in>{1..n}. (\\<Sum>j\\<in>{1..n}. f k * g j)) =\n   (\\<Sum>k\\<in>{1..n}. (\\<Sum>j\\<in>{1..n}. (f k * g j + f j * g k) / 2))\"\nproof -\n  have\n    \"2 * (\\<Sum>k\\<in>{1..n}. (\\<Sum>j\\<in>{1..n}. f k * g j)) =\n    (\\<Sum>k\\<in>{1..n}. (\\<Sum>j\\<in>{1..n}. f k * g j)) +\n    (\\<Sum>k\\<in>{1..n}. (\\<Sum>j\\<in>{1..n}. f k * g j))\"\n    by simp\n  also have\n    \"\\<dots> =\n    (\\<Sum>k\\<in>{1..n}. (\\<Sum>j\\<in>{1..n}. f k * g j)) +\n    (\\<Sum>k\\<in>{1..n}. (\\<Sum>j\\<in>{1..n}. f j * g k))\"\n    by (simp only: double_sum_equiv)\n  also have\n    \"\\<dots> =\n    (\\<Sum>k\\<in>{1..n}. (\\<Sum>j\\<in>{1..n}. f k * g j + f j * g k))\"\n    by (auto simp add: sum.distrib)\n  finally have\n    \"2 * (\\<Sum>k\\<in>{1..n}. (\\<Sum>j\\<in>{1..n}. f k * g j)) =\n    (\\<Sum>k\\<in>{1..n}. (\\<Sum>j\\<in>{1..n}. f k * g j + f j * g k))\" .\n  hence\n    \"(\\<Sum>k\\<in>{1..n}. (\\<Sum>j\\<in>{1..n}. f k * g j)) =\n     (\\<Sum>k\\<in>{1..n}. (\\<Sum>j\\<in>{1..n}. (f k * g j + f j * g k)))*(1/2)\"\n    by auto\n  also have\n    \"\\<dots> =\n     (\\<Sum>k\\<in>{1..n}. (\\<Sum>j\\<in>{1..n}. (f k * g j + f j * g k)*(1/2)))\"\n    by (simp add: sum_distrib_left mult.commute)\n  finally show ?thesis by (auto simp add: inverse_eq_divide)\nqed\n\ntext \\<open>The final theorem can now be proven. It is a simple forward\nproof that uses properties of double summation and the preceding\nlemma.\\<close>\n\ntheorem CauchySchwarzReal:\n  fixes x::vector\n  assumes \"vlen x = vlen y\"\n  shows \"\\<bar>x\\<cdot>y\\<bar> \\<le> \\<parallel>x\\<parallel>*\\<parallel>y\\<parallel>\"\nproof -\n  have \"\\<bar>x\\<cdot>y\\<bar>^2 \\<le> (\\<parallel>x\\<parallel>*\\<parallel>y\\<parallel>)^2\"\n  proof -\n    txt \\<open>We can rewrite the goal in the following form ...\\<close>\n    have \"(\\<parallel>x\\<parallel>*\\<parallel>y\\<parallel>)^2 - \\<bar>x\\<cdot>y\\<bar>^2 \\<ge> 0\"\n    proof -\n      obtain n where nx: \"n = vlen x\" by simp\n      with \\<open>vlen x = vlen y\\<close> have ny: \"n = vlen y\" by simp\n      {\n        txt \\<open>Some preliminary simplification rules.\\<close>\n        have \"(\\<Sum>j\\<in>{1..n}. x\\<^bsub>j\\<^esub>^2) \\<ge> 0\" by (simp add: sum_nonneg)\n        hence xp: \"(sqrt (\\<Sum>j\\<in>{1..n}. x\\<^bsub>j\\<^esub>^2))^2 = (\\<Sum>j\\<in>{1..n}. x\\<^bsub>j\\<^esub>^2)\"\n          by (rule real_sqrt_pow2)\n\n        have \"(\\<Sum>j\\<in>{1..n}. y\\<^bsub>j\\<^esub>^2) \\<ge> 0\" by (simp add: sum_nonneg)\n        hence yp: \"(sqrt (\\<Sum>j\\<in>{1..n}. y\\<^bsub>j\\<^esub>^2))^2 = (\\<Sum>j\\<in>{1..n}. y\\<^bsub>j\\<^esub>^2)\"\n          by (rule real_sqrt_pow2)\n\n        txt \\<open>The main result of this section is that \\<open>(\\<parallel>x\\<parallel>*\\<parallel>y\\<parallel>)^2\\<close> can be written as a double sum.\\<close>\n        have\n          \"(\\<parallel>x\\<parallel>*\\<parallel>y\\<parallel>)^2 = \\<parallel>x\\<parallel>^2 * \\<parallel>y\\<parallel>^2\"\n          by (simp add: real_sq_exp)\n        also from nx ny have\n          \"\\<dots> = (sqrt (\\<Sum>j\\<in>{1..n}. x\\<^bsub>j\\<^esub>^2))^2 * (sqrt (\\<Sum>j\\<in>{1..n}. y\\<^bsub>j\\<^esub>^2))^2\"\n          unfolding norm_def by auto\n        also from xp yp have\n          \"\\<dots> = (\\<Sum>j\\<in>{1..n}. x\\<^bsub>j\\<^esub>^2)*(\\<Sum>j\\<in>{1..n}. y\\<^bsub>j\\<^esub>^2)\"\n          by simp\n        also from sum_product have\n          \"\\<dots> = (\\<Sum>k\\<in>{1..n}. (\\<Sum>j\\<in>{1..n}. (x\\<^bsub>k\\<^esub>^2)*(y\\<^bsub>j\\<^esub>^2)))\" .\n        finally have\n          \"(\\<parallel>x\\<parallel>*\\<parallel>y\\<parallel>)^2 = (\\<Sum>k\\<in>{1..n}. (\\<Sum>j\\<in>{1..n}. (x\\<^bsub>k\\<^esub>^2)*(y\\<^bsub>j\\<^esub>^2)))\" .\n      }\n      moreover\n      {\n        txt \\<open>We also show that \\<open>\\<bar>x\\<cdot>y\\<bar>^2\\<close> can be expressed as a double sum.\\<close>\n        have\n          \"\\<bar>x\\<cdot>y\\<bar>^2 = (x\\<cdot>y)^2\"\n          by simp\n        also from nx have\n          \"\\<dots> = (\\<Sum>j\\<in>{1..n}. x\\<^bsub>j\\<^esub>*y\\<^bsub>j\\<^esub>)^2\"\n          unfolding dot_def by simp\n        also from real_sq have\n          \"\\<dots> = (\\<Sum>j\\<in>{1..n}. x\\<^bsub>j\\<^esub>*y\\<^bsub>j\\<^esub>)*(\\<Sum>j\\<in>{1..n}. x\\<^bsub>j\\<^esub>*y\\<^bsub>j\\<^esub>)\"\n          by simp\n        also from sum_product have\n          \"\\<dots> = (\\<Sum>k\\<in>{1..n}. (\\<Sum>j\\<in>{1..n}. (x\\<^bsub>k\\<^esub>*y\\<^bsub>k\\<^esub>)*(x\\<^bsub>j\\<^esub>*y\\<^bsub>j\\<^esub>)))\" .\n        finally have\n          \"\\<bar>x\\<cdot>y\\<bar>^2 = (\\<Sum>k\\<in>{1..n}. (\\<Sum>j\\<in>{1..n}. (x\\<^bsub>k\\<^esub>*y\\<^bsub>k\\<^esub>)*(x\\<^bsub>j\\<^esub>*y\\<^bsub>j\\<^esub>)))\" .\n      }\n      txt \\<open>We now manipulate the double sum expressions to get the\n      required inequality.\\<close>\n      ultimately have\n        \"(\\<parallel>x\\<parallel>*\\<parallel>y\\<parallel>)^2 - \\<bar>x\\<cdot>y\\<bar>^2 =\n         (\\<Sum>k\\<in>{1..n}. (\\<Sum>j\\<in>{1..n}. (x\\<^bsub>k\\<^esub>^2)*(y\\<^bsub>j\\<^esub>^2))) -\n         (\\<Sum>k\\<in>{1..n}. (\\<Sum>j\\<in>{1..n}. (x\\<^bsub>k\\<^esub>*y\\<^bsub>k\\<^esub>)*(x\\<^bsub>j\\<^esub>*y\\<^bsub>j\\<^esub>)))\"\n        by simp\n      also have\n        \"\\<dots> =\n         (\\<Sum>k\\<in>{1..n}. (\\<Sum>j\\<in>{1..n}. ((x\\<^bsub>k\\<^esub>^2*y\\<^bsub>j\\<^esub>^2) + (x\\<^bsub>j\\<^esub>^2*y\\<^bsub>k\\<^esub>^2))/2)) -\n         (\\<Sum>k\\<in>{1..n}. (\\<Sum>j\\<in>{1..n}. (x\\<^bsub>k\\<^esub>*y\\<^bsub>k\\<^esub>)*(x\\<^bsub>j\\<^esub>*y\\<^bsub>j\\<^esub>)))\"\n        by (simp only: double_sum_aux)\n      also have\n        \"\\<dots> =\n         (\\<Sum>k\\<in>{1..n}.  (\\<Sum>j\\<in>{1..n}. ((x\\<^bsub>k\\<^esub>^2*y\\<^bsub>j\\<^esub>^2) + (x\\<^bsub>j\\<^esub>^2*y\\<^bsub>k\\<^esub>^2))/2 - (x\\<^bsub>k\\<^esub>*y\\<^bsub>k\\<^esub>)*(x\\<^bsub>j\\<^esub>*y\\<^bsub>j\\<^esub>)))\"\n        by (auto simp add: sum_subtractf)\n      also have\n        \"\\<dots> =\n         (\\<Sum>k\\<in>{1..n}.  (\\<Sum>j\\<in>{1..n}. (inverse 2)*2*\n         (((x\\<^bsub>k\\<^esub>^2*y\\<^bsub>j\\<^esub>^2) + (x\\<^bsub>j\\<^esub>^2*y\\<^bsub>k\\<^esub>^2))*(1/2) - (x\\<^bsub>k\\<^esub>*y\\<^bsub>k\\<^esub>)*(x\\<^bsub>j\\<^esub>*y\\<^bsub>j\\<^esub>))))\"\n        by auto\n      also have\n        \"\\<dots> =\n         (\\<Sum>k\\<in>{1..n}.  (\\<Sum>j\\<in>{1..n}. (inverse 2)*(2*\n        (((x\\<^bsub>k\\<^esub>^2*y\\<^bsub>j\\<^esub>^2) + (x\\<^bsub>j\\<^esub>^2*y\\<^bsub>k\\<^esub>^2))*(1/2) - (x\\<^bsub>k\\<^esub>*y\\<^bsub>k\\<^esub>)*(x\\<^bsub>j\\<^esub>*y\\<^bsub>j\\<^esub>)))))\"\n        by (simp only: mult.assoc)\n      also have\n        \"\\<dots> =\n         (\\<Sum>k\\<in>{1..n}.  (\\<Sum>j\\<in>{1..n}. (inverse 2)*\n        ((((x\\<^bsub>k\\<^esub>^2*y\\<^bsub>j\\<^esub>^2) + (x\\<^bsub>j\\<^esub>^2*y\\<^bsub>k\\<^esub>^2))*2*(inverse 2) - 2*(x\\<^bsub>k\\<^esub>*y\\<^bsub>k\\<^esub>)*(x\\<^bsub>j\\<^esub>*y\\<^bsub>j\\<^esub>)))))\"\n        by (auto simp add: distrib_right mult.assoc ac_simps)\n      also have\n        \"\\<dots> =\n        (\\<Sum>k\\<in>{1..n}.  (\\<Sum>j\\<in>{1..n}. (inverse 2)*\n        ((((x\\<^bsub>k\\<^esub>^2*y\\<^bsub>j\\<^esub>^2) + (x\\<^bsub>j\\<^esub>^2*y\\<^bsub>k\\<^esub>^2)) - 2*(x\\<^bsub>k\\<^esub>*y\\<^bsub>k\\<^esub>)*(x\\<^bsub>j\\<^esub>*y\\<^bsub>j\\<^esub>)))))\"\n        by (simp only: mult.assoc, simp)\n      also have\n        \"\\<dots> =\n         (inverse 2)*(\\<Sum>k\\<in>{1..n}. (\\<Sum>j\\<in>{1..n}.\n         (((x\\<^bsub>k\\<^esub>^2*y\\<^bsub>j\\<^esub>^2) + (x\\<^bsub>j\\<^esub>^2*y\\<^bsub>k\\<^esub>^2)) - 2*(x\\<^bsub>k\\<^esub>*y\\<^bsub>k\\<^esub>)*(x\\<^bsub>j\\<^esub>*y\\<^bsub>j\\<^esub>))))\"\n        by (simp only: sum_distrib_left)\n      also have\n        \"\\<dots> =\n         (inverse 2)*(\\<Sum>k\\<in>{1..n}. (\\<Sum>j\\<in>{1..n}. (x\\<^bsub>k\\<^esub>*y\\<^bsub>j\\<^esub> - x\\<^bsub>j\\<^esub>*y\\<^bsub>k\\<^esub>)^2))\"\n        by (simp only: power2_diff real_sq_exp, auto simp add: ac_simps)\n      also have \"\\<dots> \\<ge> 0\"\n      proof -\n        have \"(\\<Sum>k\\<in>{1..n}. (\\<Sum>j\\<in>{1..n}. (x\\<^bsub>k\\<^esub>*y\\<^bsub>j\\<^esub> - x\\<^bsub>j\\<^esub>*y\\<^bsub>k\\<^esub>)^2)) \\<ge> 0\"\n          by (simp add: sum_nonneg)\n        thus ?thesis by simp\n      qed\n      finally show \"(\\<parallel>x\\<parallel>*\\<parallel>y\\<parallel>)^2 - \\<bar>x\\<cdot>y\\<bar>^2 \\<ge> 0\" .\n    qed\n    thus ?thesis by simp\n  qed\n  moreover have \"0 \\<le> \\<parallel>x\\<parallel>*\\<parallel>y\\<parallel>\"\n    by (auto simp add: norm_pos)\n  ultimately show ?thesis by (rule power2_le_imp_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/Cauchy/CauchySchwarz.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.880797068590724, "lm_q2_score": 0.8031738057795403, "lm_q1q2_score": 0.7074331336994747}}
{"text": "section \\<open>Formalization using Locales\\<close>\n\ntheory Elliptic_Locale\nimports \"HOL-Decision_Procs.Reflective_Field\"\nbegin\n\nsubsection \\<open>Affine Coordinates\\<close>\n\ndatatype 'a point = Infinity | Point 'a 'a\n\nlocale ell_field = field +\n  assumes two_not_zero: \"\\<guillemotleft>2\\<guillemotright> \\<noteq> \\<zero>\"\nbegin\n\ndeclare two_not_zero [simplified, simp add]\n\nlemma neg_equal_zero:\n  assumes x: \"x \\<in> carrier R\"\n  shows \"(\\<ominus> x = x) = (x = \\<zero>)\"\nproof\n  assume \"\\<ominus> x = x\"\n  with x have \"\\<guillemotleft>2\\<guillemotright> \\<otimes> x = x \\<oplus> \\<ominus> x\"\n    by (simp add: of_int_2 l_distr)\n  with x show \"x = \\<zero>\" by (simp add: r_neg integral_iff)\nqed simp\n\nlemmas equal_neg_zero = trans [OF eq_commute neg_equal_zero]\n\ndefinition nonsingular :: \"'a \\<Rightarrow> 'a \\<Rightarrow> bool\" where\n  \"nonsingular a b = (\\<guillemotleft>4\\<guillemotright> \\<otimes> a [^] (3::nat) \\<oplus> \\<guillemotleft>27\\<guillemotright> \\<otimes> b [^] (2::nat) \\<noteq> \\<zero>)\"\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> x \\<in> carrier R \\<and> y \\<in> carrier R \\<and>\n         y [^] (2::nat) = x [^] (3::nat) \\<oplus> a \\<otimes> x \\<oplus> 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 = \\<ominus> y\\<^sub>2 then Infinity\n             else\n               let\n                 l = (\\<guillemotleft>3\\<guillemotright> \\<otimes> x\\<^sub>1 [^] (2::nat) \\<oplus> a) \\<oslash> (\\<guillemotleft>2\\<guillemotright> \\<otimes> y\\<^sub>1);\n                 x\\<^sub>3 = l [^] (2::nat) \\<ominus> \\<guillemotleft>2\\<guillemotright> \\<otimes> x\\<^sub>1\n               in\n                 Point x\\<^sub>3 (\\<ominus> y\\<^sub>1 \\<ominus> l \\<otimes> (x\\<^sub>3 \\<ominus> x\\<^sub>1))\n           else\n             let\n               l = (y\\<^sub>2 \\<ominus> y\\<^sub>1) \\<oslash> (x\\<^sub>2 \\<ominus> x\\<^sub>1);\n               x\\<^sub>3 = l [^] (2::nat) \\<ominus> x\\<^sub>1 \\<ominus> x\\<^sub>2\n             in\n               Point x\\<^sub>3 (\\<ominus> y\\<^sub>1 \\<ominus> l \\<otimes> (x\\<^sub>3 \\<ominus> 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 (\\<ominus> y))\"\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 (\\<ominus> y)\"\n  by (simp add: opp_def)\n\nlemma opp_opp: \"on_curve a b p \\<Longrightarrow> opp (opp p) = p\"\n  by (auto simp add: opp_def on_curve_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    l_minus r_minus 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 \\<in> carrier R\" \"y\\<^sub>1 [^] (2::nat) = x\\<^sub>1 [^] (3::nat) \\<oplus> a \\<otimes> x\\<^sub>1 \\<oplus> 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 \"y\\<^sub>2 \\<in> carrier R\" \"x\\<^sub>1 [^] (3::nat) \\<oplus> a \\<otimes> x\\<^sub>1 \\<oplus> b = y\\<^sub>2 [^] (2::nat)\"\n    by (simp_all add: on_curve_def)\n  ultimately have \"y\\<^sub>1 = y\\<^sub>2 \\<or> y\\<^sub>1 = \\<ominus> 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 4, case_names InfL InfR Opp Tan Gen]:\n  assumes \"a \\<in> carrier R\"\n  and \"b \\<in> carrier R\"\n  and 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> \\<zero> \\<Longrightarrow>\n    l = (\\<guillemotleft>3\\<guillemotright> \\<otimes> x\\<^sub>1 [^] (2::nat) \\<oplus> a) \\<oslash> (\\<guillemotleft>2\\<guillemotright> \\<otimes> y\\<^sub>1) \\<Longrightarrow>\n    x\\<^sub>2 = l [^] (2::nat) \\<ominus> \\<guillemotleft>2\\<guillemotright> \\<otimes> x\\<^sub>1 \\<Longrightarrow>\n    y\\<^sub>2 = \\<ominus> y\\<^sub>1 \\<ominus> l \\<otimes> (x\\<^sub>2 \\<ominus> 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 \\<ominus> y\\<^sub>1) \\<oslash> (x\\<^sub>2 \\<ominus> x\\<^sub>1) \\<Longrightarrow>\n    x\\<^sub>3 = l [^] (2::nat) \\<ominus> x\\<^sub>1 \\<ominus> x\\<^sub>2 \\<Longrightarrow>\n    y\\<^sub>3 = \\<ominus> y\\<^sub>1 \\<ominus> l \\<otimes> (x\\<^sub>3 \\<ominus> 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  with p have \"x\\<^sub>1 \\<in> carrier R\" \"y\\<^sub>1 \\<in> carrier R\"\n    and p': \"y\\<^sub>1 [^] (2::nat) = x\\<^sub>1 [^] (3::nat) \\<oplus> a \\<otimes> x\\<^sub>1 \\<oplus> b\"\n    by (simp_all add: on_curve_def)\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    with q have \"x\\<^sub>2 \\<in> carrier R\" \"y\\<^sub>2 \\<in> carrier R\"\n      and q': \"y\\<^sub>2 [^] (2::nat) = x\\<^sub>2 [^] (3::nat) \\<oplus> a \\<otimes> x\\<^sub>2 \\<oplus> b\"\n      by (simp_all add: on_curve_def)\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 = \\<ominus> y\\<^sub>2\")\n        case True\n        with p Point Point' True' R3 [of p] \\<open>y\\<^sub>2 \\<in> carrier R\\<close> show ?thesis\n          by (simp add: add_def opp_def)\n      next\n        case False\n        have \"(y\\<^sub>1 \\<ominus> y\\<^sub>2) \\<otimes> (y\\<^sub>1 \\<oplus> y\\<^sub>2) = \\<zero>\"\n          by (ring True' p' q')\n        with False \\<open>y\\<^sub>1 \\<in> carrier R\\<close> \\<open>y\\<^sub>2 \\<in> carrier R\\<close> have \"y\\<^sub>1 = y\\<^sub>2\"\n          by (simp add: eq_neg_iff_add_eq_0 integral_iff eq_diff0)\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 add_casew [consumes 4, case_names InfL InfR Opp Gen]:\n  assumes a: \"a \\<in> carrier R\"\n  and b: \"b \\<in> carrier R\"\n  and 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 = (\\<guillemotleft>3\\<guillemotright> \\<otimes> x\\<^sub>1 [^] (2::nat) \\<oplus> a) \\<oslash> (\\<guillemotleft>2\\<guillemotright> \\<otimes> y\\<^sub>1) \\<or>\n    x\\<^sub>1 \\<noteq> x\\<^sub>2 \\<and> l = (y\\<^sub>2 \\<ominus> y\\<^sub>1) \\<oslash> (x\\<^sub>2 \\<ominus> x\\<^sub>1) \\<Longrightarrow>\n    x\\<^sub>3 = l [^] (2::nat) \\<ominus> x\\<^sub>1 \\<ominus> x\\<^sub>2 \\<Longrightarrow>\n    y\\<^sub>3 = \\<ominus> y\\<^sub>1 \\<ominus> l \\<otimes> (x\\<^sub>3 \\<ominus> 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 a b p q p q\nproof (induct rule: add_case)\n  case InfL\n  show ?case by (rule R1)\nnext\n  case InfR\n  show ?case by (rule R2)\nnext\n  case (Opp p)\n  from \\<open>on_curve a b p\\<close> show ?case by (rule R3)\nnext\n  case (Tan p\\<^sub>1 x\\<^sub>1 y\\<^sub>1 p\\<^sub>2 x\\<^sub>2 y\\<^sub>2 l)\n  with a b show ?case\n    apply (rule_tac R4)\n    apply assumption+\n    apply (simp add: opp_Point equal_neg_zero on_curve_def)\n    apply simp\n    apply (simp add: minus_eq mult2 integral_iff a_assoc r_minus on_curve_def)\n    apply simp\n    done\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 show ?case\n    apply (rule_tac R4)\n    apply assumption+\n    apply (simp add: opp_Point)\n    apply simp_all\n    done\nqed\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 spec1_assoc:\n  assumes a: \"a \\<in> carrier R\"\n  and b: \"b \\<in> carrier R\"\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 \"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 a b 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 a b \\<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 a b \\<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 a b \\<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>on_curve a b p\\<close> \\<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 a b \\<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      with a b 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>on_curve a b p\\<close> \\<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        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          \\<open>on_curve a b p\\<^sub>3\\<close> \\<open>p\\<^sub>3 = Point x\\<^sub>3 y\\<^sub>3\\<close>\n        have\n          \"x\\<^sub>1 \\<in> carrier R\" \"y\\<^sub>1 \\<in> carrier R\" and y1: \"y\\<^sub>1 [^] (2::nat) = x\\<^sub>1 [^] (3::nat) \\<oplus> a \\<otimes> x\\<^sub>1 \\<oplus> b\" and\n          \"x\\<^sub>2 \\<in> carrier R\" \"y\\<^sub>2 \\<in> carrier R\" and y2: \"y\\<^sub>2 [^] (2::nat) = x\\<^sub>2 [^] (3::nat) \\<oplus> a \\<otimes> x\\<^sub>2 \\<oplus> b\" and\n          \"x\\<^sub>3 \\<in> carrier R\" \"y\\<^sub>3 \\<in> carrier R\" and y3: \"y\\<^sub>3 [^] (2::nat) = x\\<^sub>3 [^] (3::nat) \\<oplus> a \\<otimes> x\\<^sub>3 \\<oplus> b\"\n          by (simp_all add: on_curve_def)\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 [^] 2 \\<ominus> x\\<^sub>1' \\<ominus> x\\<^sub>5'\\<close> \\<open>x\\<^sub>7 = l\\<^sub>3 [^] 2 \\<ominus> x\\<^sub>4' \\<ominus> x\\<^sub>3'\\<close>\n            \\<open>y\\<^sub>6 = \\<ominus> y\\<^sub>1' \\<ominus> l\\<^sub>2 \\<otimes> (x\\<^sub>6 \\<ominus> x\\<^sub>1')\\<close> \\<open>y\\<^sub>7 = \\<ominus> y\\<^sub>4' \\<ominus> l\\<^sub>3 \\<otimes> (x\\<^sub>7 \\<ominus> x\\<^sub>4')\\<close>\n            \\<open>l\\<^sub>2 = (y\\<^sub>5' \\<ominus> y\\<^sub>1') \\<oslash> (x\\<^sub>5' \\<ominus> x\\<^sub>1')\\<close> \\<open>l\\<^sub>3 = (y\\<^sub>3' \\<ominus> y\\<^sub>4') \\<oslash> (x\\<^sub>3' \\<ominus> x\\<^sub>4')\\<close>\n            \\<open>l\\<^sub>1 = (y\\<^sub>3 \\<ominus> y\\<^sub>2') \\<oslash> (x\\<^sub>3 \\<ominus> x\\<^sub>2')\\<close> \\<open>l = (y\\<^sub>2 \\<ominus> y\\<^sub>1) \\<oslash> (x\\<^sub>2 \\<ominus> x\\<^sub>1)\\<close>\n            \\<open>x\\<^sub>5 = l\\<^sub>1 [^] 2 \\<ominus> x\\<^sub>2' \\<ominus> x\\<^sub>3\\<close> \\<open>y\\<^sub>5 = \\<ominus> y\\<^sub>2' \\<ominus> l\\<^sub>1 \\<otimes> (x\\<^sub>5 \\<ominus> x\\<^sub>2')\\<close>\n            \\<open>x\\<^sub>4 = l [^] 2 \\<ominus> x\\<^sub>1 \\<ominus> x\\<^sub>2\\<close> \\<open>y\\<^sub>4 = \\<ominus> y\\<^sub>1 \\<ominus> l \\<otimes> (x\\<^sub>4 \\<ominus> x\\<^sub>1)\\<close>)\n          apply (rule conjI)\n          apply (field y1 y2 y3)\n          apply (rule conjI)\n          apply (simp add: eq_diff0 \\<open>x\\<^sub>3 \\<in> carrier R\\<close> \\<open>x\\<^sub>2 \\<in> carrier R\\<close>\n            not_sym [OF \\<open>x\\<^sub>2' \\<noteq> x\\<^sub>3\\<close> [simplified \\<open>x\\<^sub>2' = x\\<^sub>2\\<close>]])\n          apply (rule conjI)\n          apply (rule notI)\n          apply (ring (prems) y1 y2)\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 [^] 2 \\<ominus> x\\<^sub>2' \\<ominus> x\\<^sub>3\\<close>\n            \\<open>l\\<^sub>1 = (y\\<^sub>3 \\<ominus> y\\<^sub>2') \\<oslash> (x\\<^sub>3 \\<ominus> 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 y1 y2)\n          apply (simp add: eq_diff0 \\<open>x\\<^sub>3 \\<in> carrier R\\<close> \\<open>x\\<^sub>2 \\<in> carrier R\\<close>\n            not_sym [OF \\<open>x\\<^sub>2' \\<noteq> x\\<^sub>3\\<close> [simplified \\<open>x\\<^sub>2' = x\\<^sub>2\\<close>]])\n          apply (rule conjI)\n          apply (simp add: eq_diff0 \\<open>x\\<^sub>2 \\<in> carrier R\\<close> \\<open>x\\<^sub>1 \\<in> carrier R\\<close> not_sym [OF \\<open>x\\<^sub>1 \\<noteq> x\\<^sub>2\\<close>])\n          apply (rule notI)\n          apply (ring (prems) y1 y2)\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 [^] 2 \\<ominus> x\\<^sub>1 \\<ominus> x\\<^sub>2\\<close>\n            \\<open>l = (y\\<^sub>2 \\<ominus> y\\<^sub>1) \\<oslash> (x\\<^sub>2 \\<ominus> x\\<^sub>1)\\<close>])\n          apply (erule notE)\n          apply (rule sym)\n          apply (field y1 y2)\n          apply (simp add: eq_diff0 \\<open>x\\<^sub>2 \\<in> carrier R\\<close> \\<open>x\\<^sub>1 \\<in> carrier R\\<close> not_sym [OF \\<open>x\\<^sub>1 \\<noteq> x\\<^sub>2\\<close>])\n          apply (field y1 y2 y3)\n          apply (rule conjI)\n          apply (rule notI)\n          apply (ring (prems) y1 y2)\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 [^] 2 \\<ominus> x\\<^sub>2' \\<ominus> x\\<^sub>3\\<close>\n            \\<open>l\\<^sub>1 = (y\\<^sub>3 \\<ominus> y\\<^sub>2') \\<oslash> (x\\<^sub>3 \\<ominus> 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 y1 y2)\n          apply (simp add: eq_diff0 \\<open>x\\<^sub>3 \\<in> carrier R\\<close> \\<open>x\\<^sub>2 \\<in> carrier R\\<close>\n            not_sym [OF \\<open>x\\<^sub>2' \\<noteq> x\\<^sub>3\\<close> [simplified \\<open>x\\<^sub>2' = x\\<^sub>2\\<close>]])\n          apply (rule conjI)\n          apply (simp add: eq_diff0 \\<open>x\\<^sub>3 \\<in> carrier R\\<close> \\<open>x\\<^sub>2 \\<in> carrier R\\<close>\n            not_sym [OF \\<open>x\\<^sub>2' \\<noteq> x\\<^sub>3\\<close> [simplified \\<open>x\\<^sub>2' = x\\<^sub>2\\<close>]])\n          apply (rule conjI)\n          apply (rule notI)\n          apply (ring (prems) y1 y2)\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 [^] 2 \\<ominus> x\\<^sub>1 \\<ominus> x\\<^sub>2\\<close>\n            \\<open>l = (y\\<^sub>2 \\<ominus> y\\<^sub>1) \\<oslash> (x\\<^sub>2 \\<ominus> x\\<^sub>1)\\<close>])\n          apply (erule notE)\n          apply (rule sym)\n          apply (field y1 y2)\n          apply (simp_all add: eq_diff0 \\<open>x\\<^sub>2 \\<in> carrier R\\<close> \\<open>x\\<^sub>1 \\<in> carrier R\\<close> not_sym [OF \\<open>x\\<^sub>1 \\<noteq> x\\<^sub>2\\<close>])\n          done\n      qed\n    qed\n  qed\nqed\n\nlemma spec2_assoc:\n  assumes a: \"a \\<in> carrier R\"\n  and b: \"b \\<in> carrier R\"\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 \"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 a b 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 a b \\<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 a b \\<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 a b \\<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 a b \\<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      with a b 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> \\<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>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          \"x\\<^sub>1 \\<in> carrier R\" \"y\\<^sub>1 \\<in> carrier R\" and y1: \"y\\<^sub>1 [^] (2::nat) = x\\<^sub>1 [^] (3::nat) \\<oplus> a \\<otimes> x\\<^sub>1 \\<oplus> b\" and\n          \"x\\<^sub>2 \\<in> carrier R\" \"y\\<^sub>2 \\<in> carrier R\" and y2: \"y\\<^sub>2 [^] (2::nat) = x\\<^sub>2 [^] (3::nat) \\<oplus> a \\<otimes> x\\<^sub>2 \\<oplus> 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 \\<ominus> x\\<^sub>4' \\<ominus> x\\<^sub>3'\\<close>\n            \\<open>y\\<^sub>7 = \\<ominus> y\\<^sub>4' \\<ominus> l\\<^sub>3 \\<otimes> (x\\<^sub>7 \\<ominus> x\\<^sub>4')\\<close>\n            \\<open>l\\<^sub>3 = (y\\<^sub>3' \\<ominus> y\\<^sub>4') \\<oslash> (x\\<^sub>3' \\<ominus> x\\<^sub>4')\\<close>\n            \\<open>x\\<^sub>6 = l\\<^sub>2 [^] 2 \\<ominus> x\\<^sub>1' \\<ominus> x\\<^sub>5'\\<close>\n            \\<open>y\\<^sub>6 = \\<ominus> y\\<^sub>1' \\<ominus> l\\<^sub>2 \\<otimes> (x\\<^sub>6 \\<ominus> x\\<^sub>1')\\<close>\n            \\<open>l\\<^sub>2 = (y\\<^sub>5' \\<ominus> y\\<^sub>1') \\<oslash> (x\\<^sub>5' \\<ominus> x\\<^sub>1')\\<close>\n            \\<open>x\\<^sub>5 = l\\<^sub>1 [^] 2 \\<ominus> \\<guillemotleft>2\\<guillemotright> \\<otimes> x\\<^sub>2'\\<close>\n            \\<open>y\\<^sub>5 = \\<ominus> y\\<^sub>2' \\<ominus> l\\<^sub>1 \\<otimes> (x\\<^sub>5 \\<ominus> x\\<^sub>2')\\<close>\n            \\<open>l\\<^sub>1 = (\\<guillemotleft>3\\<guillemotright> \\<otimes> x\\<^sub>2' [^] 2 \\<oplus> a) \\<oslash> (\\<guillemotleft>2\\<guillemotright> \\<otimes> y\\<^sub>2')\\<close>\n            \\<open>x\\<^sub>4 = l [^] 2 \\<ominus> x\\<^sub>1 \\<ominus> x\\<^sub>2\\<close>\n            \\<open>y\\<^sub>4 = \\<ominus> y\\<^sub>1 \\<ominus> l \\<otimes> (x\\<^sub>4 \\<ominus> x\\<^sub>1)\\<close>\n            \\<open>l = (y\\<^sub>2 \\<ominus> y\\<^sub>1) \\<oslash> (x\\<^sub>2 \\<ominus> x\\<^sub>1)\\<close>)\n          apply (rule conjI)\n          apply (field y1 y2)\n          apply (intro conjI)\n          apply (simp add: integral_iff [OF _ \\<open>y\\<^sub>2 \\<in> carrier R\\<close>] \\<open>y\\<^sub>2' \\<noteq> \\<zero>\\<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 \\<ominus> \\<guillemotleft>2\\<guillemotright> \\<otimes> x\\<^sub>2'\\<close>\n            \\<open>l\\<^sub>1 = (\\<guillemotleft>3\\<guillemotright> \\<otimes> x\\<^sub>2' [^] 2 \\<oplus> a) \\<oslash> (\\<guillemotleft>2\\<guillemotright> \\<otimes> 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: integral_iff [OF _ \\<open>y\\<^sub>2 \\<in> carrier R\\<close>] \\<open>y\\<^sub>2' \\<noteq> \\<zero>\\<close> [simplified \\<open>y\\<^sub>2' = y\\<^sub>2\\<close>])\n          apply (simp add: eq_diff0 \\<open>x\\<^sub>2 \\<in> carrier R\\<close> \\<open>x\\<^sub>1 \\<in> carrier R\\<close> not_sym [OF \\<open>x\\<^sub>1 \\<noteq> x\\<^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 \\<ominus> x\\<^sub>1 \\<ominus> x\\<^sub>2\\<close>\n            \\<open>l = (y\\<^sub>2 \\<ominus> y\\<^sub>1) \\<oslash> (x\\<^sub>2 \\<ominus> 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: eq_diff0 \\<open>x\\<^sub>2 \\<in> carrier R\\<close> \\<open>x\\<^sub>1 \\<in> carrier R\\<close> not_sym [OF \\<open>x\\<^sub>1 \\<noteq> x\\<^sub>2\\<close>])\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 \\<ominus> \\<guillemotleft>2\\<guillemotright> \\<otimes> x\\<^sub>2'\\<close>\n            \\<open>l\\<^sub>1 = (\\<guillemotleft>3\\<guillemotright> \\<otimes> x\\<^sub>2' [^] 2 \\<oplus> a) \\<oslash> (\\<guillemotleft>2\\<guillemotright> \\<otimes> 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: integral_iff [OF _ \\<open>y\\<^sub>2 \\<in> carrier R\\<close>] \\<open>y\\<^sub>2' \\<noteq> \\<zero>\\<close> [simplified \\<open>y\\<^sub>2' = y\\<^sub>2\\<close>])\n          apply (simp add: integral_iff [OF _ \\<open>y\\<^sub>2 \\<in> carrier R\\<close>] \\<open>y\\<^sub>2' \\<noteq> \\<zero>\\<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 \\<ominus> x\\<^sub>1 \\<ominus> x\\<^sub>2\\<close>\n            \\<open>l = (y\\<^sub>2 \\<ominus> y\\<^sub>1) \\<oslash> (x\\<^sub>2 \\<ominus> 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: eq_diff0 \\<open>x\\<^sub>2 \\<in> carrier R\\<close> \\<open>x\\<^sub>1 \\<in> carrier R\\<close> not_sym [OF \\<open>x\\<^sub>1 \\<noteq> x\\<^sub>2\\<close>])\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 a: \"a \\<in> carrier R\"\n  and b: \"b \\<in> carrier R\"\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 \"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 a b 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 a b \\<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 a b \\<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 a b \\<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 a b \\<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      with a b 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> \\<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>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          \"x\\<^sub>1 \\<in> carrier R\" \"y\\<^sub>1 \\<in> carrier R\" and y1: \"y\\<^sub>1 [^] (2::nat) = x\\<^sub>1 [^] (3::nat) \\<oplus> a \\<otimes> x\\<^sub>1 \\<oplus> b\" and\n          \"x\\<^sub>2 \\<in> carrier R\" \"y\\<^sub>2 \\<in> carrier R\" and y2: \"y\\<^sub>2 [^] (2::nat) = x\\<^sub>2 [^] (3::nat) \\<oplus> a \\<otimes> x\\<^sub>2 \\<oplus> 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 \\<ominus> x\\<^sub>4' \\<ominus> x\\<^sub>2''\\<close>\n          \\<open>y\\<^sub>7 = \\<ominus> y\\<^sub>4' \\<ominus> l\\<^sub>3 \\<otimes> (x\\<^sub>7 \\<ominus> x\\<^sub>4')\\<close>\n          \\<open>l\\<^sub>3 = (y\\<^sub>2'' \\<ominus> y\\<^sub>4') \\<oslash> (x\\<^sub>2'' \\<ominus> x\\<^sub>4')\\<close>\n          \\<open>x\\<^sub>6 = l\\<^sub>2 [^] 2 \\<ominus> \\<guillemotleft>2\\<guillemotright> \\<otimes> x\\<^sub>1'\\<close>\n          \\<open>y\\<^sub>6 = \\<ominus> y\\<^sub>1' \\<ominus> l\\<^sub>2 \\<otimes> (x\\<^sub>6 \\<ominus> x\\<^sub>1')\\<close>\n          \\<open>x\\<^sub>5 = l\\<^sub>1 [^] 2 \\<ominus> \\<guillemotleft>2\\<guillemotright> \\<otimes> x\\<^sub>2'\\<close>\n          \\<open>y\\<^sub>5 = \\<ominus> y\\<^sub>2' \\<ominus> l\\<^sub>1 \\<otimes> (x\\<^sub>5 \\<ominus> x\\<^sub>2')\\<close>\n          \\<open>l\\<^sub>1 = (\\<guillemotleft>3\\<guillemotright> \\<otimes> x\\<^sub>2' [^] 2 \\<oplus> a) \\<oslash> (\\<guillemotleft>2\\<guillemotright> \\<otimes> y\\<^sub>2')\\<close>\n          \\<open>l\\<^sub>2 = (\\<guillemotleft>3\\<guillemotright> \\<otimes> x\\<^sub>1' [^] 2 \\<oplus> a) \\<oslash> (\\<guillemotleft>2\\<guillemotright> \\<otimes> y\\<^sub>1')\\<close>\n          \\<open>x\\<^sub>4 = l [^] 2 \\<ominus> x\\<^sub>1 \\<ominus> x\\<^sub>2\\<close>\n          \\<open>y\\<^sub>4 = \\<ominus> y\\<^sub>1 \\<ominus> l \\<otimes> (x\\<^sub>4 \\<ominus> x\\<^sub>1)\\<close>\n          \\<open>l = (y\\<^sub>2 \\<ominus> y\\<^sub>1) \\<oslash> (x\\<^sub>2 \\<ominus> x\\<^sub>1)\\<close>\n        from \\<open>y\\<^sub>2 \\<in> carrier R\\<close> \\<open>y\\<^sub>2' \\<noteq> \\<zero>\\<close> \\<open>y\\<^sub>2' = y\\<^sub>2\\<close>\n        have \"\\<guillemotleft>2\\<guillemotright> \\<otimes> y\\<^sub>2 \\<noteq> \\<zero>\" by (simp add: integral_iff)\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> \\<zero>\\<close>])\n          apply (simp only: ps qs)\n          apply field\n          apply (rule \\<open>\\<guillemotleft>2\\<guillemotright> \\<otimes> y\\<^sub>2 \\<noteq> \\<zero>\\<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>\\<guillemotleft>2\\<guillemotright> \\<otimes> y\\<^sub>2 \\<noteq> \\<zero>\\<close>)\n          apply (rule \\<open>\\<guillemotleft>2\\<guillemotright> \\<otimes> y\\<^sub>2 \\<noteq> \\<zero>\\<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>\\<guillemotleft>2\\<guillemotright> \\<otimes> y\\<^sub>2 \\<noteq> \\<zero>\\<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>\\<guillemotleft>2\\<guillemotright> \\<otimes> y\\<^sub>2 \\<noteq> \\<zero>\\<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> \\<zero>\\<close>])\n          apply (simp only: ps qs)\n          apply field\n          apply (rule \\<open>\\<guillemotleft>2\\<guillemotright> \\<otimes> y\\<^sub>2 \\<noteq> \\<zero>\\<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>\\<guillemotleft>2\\<guillemotright> \\<otimes> y\\<^sub>2 \\<noteq> \\<zero>\\<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>\\<guillemotleft>2\\<guillemotright> \\<otimes> y\\<^sub>2 \\<noteq> \\<zero>\\<close>)\n          apply (rule \\<open>\\<guillemotleft>2\\<guillemotright> \\<otimes> y\\<^sub>2 \\<noteq> \\<zero>\\<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>\\<guillemotleft>2\\<guillemotright> \\<otimes> y\\<^sub>2 \\<noteq> \\<zero>\\<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 \"a \\<in> carrier R\" \"b \\<in> carrier R\" \"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 \"x\\<^sub>1 \\<in> carrier R\" \"y\\<^sub>1 \\<in> carrier R\"\n    and y1: \"y\\<^sub>1 [^] (2::nat) = x\\<^sub>1 [^] (3::nat) \\<oplus> a \\<otimes> x\\<^sub>1 \\<oplus> b\"\n    by (simp_all 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> have \"x\\<^sub>2 \\<in> carrier R\" \"y\\<^sub>2 \\<in> carrier R\"\n      and y2: \"y\\<^sub>2 [^] (2::nat) = x\\<^sub>2 [^] (3::nat) \\<oplus> a \\<otimes> x\\<^sub>2 \\<oplus> b\"\n      by (simp_all 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 = \\<ominus> y\\<^sub>2\")\n        case True\n        with Point Point' \\<open>x\\<^sub>1 = x\\<^sub>2\\<close> \\<open>y\\<^sub>2 \\<in> carrier R\\<close> show ?thesis\n          by (simp add: add_def)\n      next\n        case False\n        with y1 y2 [symmetric] \\<open>y\\<^sub>1 \\<in> carrier R\\<close> \\<open>y\\<^sub>2 \\<in> carrier R\\<close> \\<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 (cut_tac \\<open>x\\<^sub>1 \\<in> carrier R\\<close> \\<open>x\\<^sub>2 \\<in> carrier R\\<close>)\n        apply (simp add: eq_diff0)\n        apply field\n        apply (cut_tac \\<open>x\\<^sub>1 \\<in> carrier R\\<close> \\<open>x\\<^sub>2 \\<in> carrier R\\<close>)\n        apply (simp add: eq_diff0)\n        done\n    qed\n  qed\nqed\n\nlemma uniq_opp:\n  assumes \"on_curve a b p\\<^sub>2\"\n  and \"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: on_curve_def add_def opp_def Let_def\n    split: point.split_asm if_split_asm)\n\nlemma uniq_zero:\n  assumes a: \"a \\<in> carrier R\"\n  and b: \"b \\<in> carrier R\"\n  and 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 a b 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>on_curve a b p\\<^sub>1\\<close> \\<open>p\\<^sub>1 = Point x\\<^sub>1 y\\<^sub>1\\<close>\n  have \"x\\<^sub>1 \\<in> carrier R\" \"y\\<^sub>1 \\<in> carrier R\" by (simp_all add: on_curve_def)\n  with a \\<open>l = (\\<guillemotleft>3\\<guillemotright> \\<otimes> x\\<^sub>1 [^] 2 \\<oplus> a) \\<oslash> (\\<guillemotleft>2\\<guillemotright> \\<otimes> y\\<^sub>1)\\<close> \\<open>y\\<^sub>1 \\<noteq> \\<zero>\\<close>\n  have \"l \\<in> carrier R\" by (simp add: integral_iff)\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>x\\<^sub>1 \\<in> carrier R\\<close> \\<open>y\\<^sub>1 \\<in> carrier R\\<close> \\<open>l \\<in> carrier R\\<close> \\<open>y\\<^sub>2 = \\<ominus> y\\<^sub>1 \\<ominus> l \\<otimes> (x\\<^sub>2 \\<ominus> x\\<^sub>1)\\<close> \\<open>y\\<^sub>1 \\<noteq> \\<zero>\\<close>\n  have \"\\<ominus> y\\<^sub>1 = y\\<^sub>1\" by (simp add: r_neg minus_eq)\n  with \\<open>y\\<^sub>1 \\<in> carrier R\\<close> \\<open>y\\<^sub>1 \\<noteq> \\<zero>\\<close>\n  show ?case by (simp add: neg_equal_zero)\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 \"x\\<^sub>1 \\<in> carrier R\" \"y\\<^sub>1 \\<in> carrier R\" \"x\\<^sub>2 \\<in> carrier R\" \"y\\<^sub>2 \\<in> carrier R\"\n    and y1: \"y\\<^sub>1 [^] (2::nat) = x\\<^sub>1 [^] (3::nat) \\<oplus> a \\<otimes> x\\<^sub>1 \\<oplus> b\"\n    and y2: \"y\\<^sub>2 [^] (2::nat) = x\\<^sub>2 [^] (3::nat) \\<oplus> a \\<otimes> x\\<^sub>2 \\<oplus> b\"\n    by (simp_all add: on_curve_def)\n  with \\<open>l = (y\\<^sub>2 \\<ominus> y\\<^sub>1) \\<oslash> (x\\<^sub>2 \\<ominus> x\\<^sub>1)\\<close> \\<open>x\\<^sub>1 \\<noteq> x\\<^sub>2\\<close>\n  have \"l \\<in> carrier R\" by (simp add: eq_diff0)\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 = \\<ominus> y\\<^sub>1 \\<ominus> l \\<otimes> (x\\<^sub>3 \\<ominus> x\\<^sub>1)\\<close>\n  have \"y\\<^sub>2 = \\<ominus> y\\<^sub>1 \\<ominus> l \\<otimes> (x\\<^sub>2 \\<ominus> x\\<^sub>1)\" by simp\n  also from \\<open>l = (y\\<^sub>2 \\<ominus> y\\<^sub>1) \\<oslash> (x\\<^sub>2 \\<ominus> x\\<^sub>1)\\<close> \\<open>x\\<^sub>1 \\<noteq> x\\<^sub>2\\<close>\n    \\<open>x\\<^sub>1 \\<in> carrier R\\<close> \\<open>x\\<^sub>2 \\<in> carrier R\\<close> \\<open>y\\<^sub>1 \\<in> carrier R\\<close> \\<open>y\\<^sub>2 \\<in> carrier R\\<close>\n  have \"l \\<otimes> (x\\<^sub>2 \\<ominus> x\\<^sub>1) = y\\<^sub>2 \\<ominus> y\\<^sub>1\"\n    by (simp add: m_div_def m_assoc eq_diff0)\n  also from \\<open>y\\<^sub>1 \\<in> carrier R\\<close> \\<open>y\\<^sub>2 \\<in> carrier R\\<close>\n  have \"\\<ominus> y\\<^sub>1 \\<ominus> (y\\<^sub>2 \\<ominus> y\\<^sub>1) = (\\<ominus> y\\<^sub>1 \\<oplus> y\\<^sub>1) \\<oplus> \\<ominus> y\\<^sub>2\"\n    by (simp add: minus_eq minus_add a_ac)\n  finally have \"y\\<^sub>2 = \\<zero>\" using \\<open>y\\<^sub>1 \\<in> carrier R\\<close> \\<open>y\\<^sub>2 \\<in> carrier R\\<close>\n    by (simp add: l_neg equal_neg_zero)\n  with \\<open>p\\<^sub>2 = Point x\\<^sub>2 y\\<^sub>2\\<close> \\<open>on_curve a b p\\<^sub>2\\<close>\n    \\<open>a \\<in> carrier R\\<close> \\<open>b \\<in> carrier R\\<close> \\<open>x\\<^sub>2 \\<in> carrier R\\<close>\n  have x2: \"x\\<^sub>2 [^] (3::nat) = \\<ominus> (a \\<otimes> x\\<^sub>2 \\<oplus> b)\"\n    by (simp add: on_curve_def nat_pow_zero eq_neg_iff_add_eq_0 a_assoc)\n  from \\<open>x\\<^sub>3 = l [^] 2 \\<ominus> x\\<^sub>1 \\<ominus> x\\<^sub>2\\<close> \\<open>x\\<^sub>3 = x\\<^sub>2\\<close>\n  have \"l [^] (2::nat) \\<ominus> x\\<^sub>1 \\<ominus> x\\<^sub>2 \\<ominus> x\\<^sub>2 = x\\<^sub>2 \\<ominus> x\\<^sub>2\" by simp\n  with \\<open>x\\<^sub>1 \\<in> carrier R\\<close> \\<open>x\\<^sub>2 \\<in> carrier R\\<close> \\<open>l \\<in> carrier R\\<close>\n  have \"l [^] (2::nat) \\<ominus> x\\<^sub>1 \\<ominus> \\<guillemotleft>2\\<guillemotright> \\<otimes> x\\<^sub>2 = \\<zero>\"\n    by (simp add: of_int_2 l_distr minus_eq a_ac minus_add r_neg)\n  then have \"x\\<^sub>2 \\<otimes> (l [^] (2::nat) \\<ominus> x\\<^sub>1 \\<ominus> \\<guillemotleft>2\\<guillemotright> \\<otimes> x\\<^sub>2) = x\\<^sub>2 \\<otimes> \\<zero>\" by simp\n  then have \"(x\\<^sub>2 \\<ominus> x\\<^sub>1) \\<otimes> (\\<guillemotleft>2\\<guillemotright> \\<otimes> a \\<otimes> x\\<^sub>2 \\<oplus> \\<guillemotleft>3\\<guillemotright> \\<otimes> b) = \\<zero>\"\n    apply (simp add: \\<open>l = (y\\<^sub>2 \\<ominus> y\\<^sub>1) \\<oslash> (x\\<^sub>2 \\<ominus> x\\<^sub>1)\\<close> \\<open>y\\<^sub>2 = \\<zero>\\<close>)\n    apply (field (prems) y1 x2)\n    apply (ring y1 x2)\n    apply (simp add: eq_diff0 \\<open>x\\<^sub>2 \\<in> carrier R\\<close> \\<open>x\\<^sub>1 \\<in> carrier R\\<close> not_sym [OF \\<open>x\\<^sub>1 \\<noteq> x\\<^sub>2\\<close>])\n    done\n  with not_sym [OF \\<open>x\\<^sub>1 \\<noteq> x\\<^sub>2\\<close>]\n    \\<open>x\\<^sub>2 \\<in> carrier R\\<close> \\<open>x\\<^sub>1 \\<in> carrier R\\<close> \\<open>a \\<in> carrier R\\<close> \\<open>b \\<in> carrier R\\<close>\n  have \"\\<guillemotleft>2\\<guillemotright> \\<otimes> a \\<otimes> x\\<^sub>2 \\<oplus> \\<guillemotleft>3\\<guillemotright> \\<otimes> b = \\<zero>\"\n    by (simp add: integral_iff eq_diff0)\n  with \\<open>a \\<in> carrier R\\<close> \\<open>b \\<in> carrier R\\<close> \\<open>x\\<^sub>2 \\<in> carrier R\\<close>\n  have \"\\<guillemotleft>2\\<guillemotright> \\<otimes> a \\<otimes> x\\<^sub>2 = \\<ominus> (\\<guillemotleft>3\\<guillemotright> \\<otimes> b)\"\n    by (simp add: eq_neg_iff_add_eq_0)\n  from y2 [symmetric] \\<open>y\\<^sub>2 = \\<zero>\\<close> \\<open>a \\<in> carrier R\\<close>\n  have \"\\<ominus> (\\<guillemotleft>2\\<guillemotright> \\<otimes> a) [^] (3::nat) \\<otimes> (x\\<^sub>2 [^] (3::nat) \\<oplus> a \\<otimes> x\\<^sub>2 \\<oplus> b) = \\<zero>\"\n    by (simp add: nat_pow_zero)\n  then have \"b \\<otimes> (\\<guillemotleft>4\\<guillemotright> \\<otimes> a [^] (3::nat) \\<oplus> \\<guillemotleft>27\\<guillemotright> \\<otimes> b [^] (2::nat)) = \\<zero>\"\n    apply (ring (prems) \\<open>\\<guillemotleft>2\\<guillemotright> \\<otimes> a \\<otimes> x\\<^sub>2 = \\<ominus> (\\<guillemotleft>3\\<guillemotright> \\<otimes> b)\\<close>)\n    apply (ring \\<open>\\<guillemotleft>2\\<guillemotright> \\<otimes> a \\<otimes> x\\<^sub>2 = \\<ominus> (\\<guillemotleft>3\\<guillemotright> \\<otimes> b)\\<close>)\n    done\n  with ab a b have \"b = \\<zero>\" by (simp add: nonsingular_def integral_iff)\n  with \\<open>\\<guillemotleft>2\\<guillemotright> \\<otimes> a \\<otimes> x\\<^sub>2 \\<oplus> \\<guillemotleft>3\\<guillemotright> \\<otimes> b = \\<zero>\\<close> ab a b \\<open>x\\<^sub>2 \\<in> carrier R\\<close>\n  have \"x\\<^sub>2 = \\<zero>\" by (simp add: nonsingular_def nat_pow_zero integral_iff)\n  from \\<open>l [^] (2::nat) \\<ominus> x\\<^sub>1 \\<ominus> \\<guillemotleft>2\\<guillemotright> \\<otimes> x\\<^sub>2 = \\<zero>\\<close>\n  show ?case\n    apply (simp add: \\<open>x\\<^sub>2 = \\<zero>\\<close> \\<open>y\\<^sub>2 = \\<zero>\\<close> \\<open>l = (y\\<^sub>2 \\<ominus> y\\<^sub>1) \\<oslash> (x\\<^sub>2 \\<ominus> x\\<^sub>1)\\<close>)\n    apply (field (prems) y1 \\<open>b = \\<zero>\\<close>)\n    apply (insert a b ab \\<open>x\\<^sub>1 \\<in> carrier R\\<close> \\<open>b = \\<zero>\\<close> \\<open>x\\<^sub>1 \\<noteq> x\\<^sub>2\\<close> \\<open>x\\<^sub>2 = \\<zero>\\<close>)\n    apply (simp add: nonsingular_def nat_pow_zero integral_iff)\n    apply (simp add: trans [OF eq_commute eq_neg_iff_add_eq_0])\n    done\nqed\n\nlemma opp_add:\n  assumes a: \"a \\<in> carrier R\"\n  and b: \"b \\<in> carrier R\"\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 \"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 \\<in> carrier R\" \"y\\<^sub>1 \\<in> carrier R\" \"x\\<^sub>1 [^] (3::nat) \\<oplus> a \\<otimes> x\\<^sub>1 \\<oplus> b = y\\<^sub>1 [^] (2::nat)\"\n      \"x\\<^sub>2 \\<in> carrier R\" \"y\\<^sub>2 \\<in> carrier R\" \"x\\<^sub>2 [^] (3::nat) \\<oplus> a \\<otimes> x\\<^sub>2 \\<oplus> b = y\\<^sub>2 [^] (2::nat)\"\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 = \\<ominus> y\\<^sub>2\")\n      apply (simp add: add_def opp_def Let_def)\n      apply (simp add: add_def opp_def Let_def neg_equal_swap)\n      apply (rule conjI)\n      apply field\n      apply (auto simp add: integral_iff nat_pow_zero\n        trans [OF eq_commute eq_neg_iff_add_eq_0])[1]\n      apply field\n      apply (auto simp add: integral_iff nat_pow_zero\n        trans [OF eq_commute eq_neg_iff_add_eq_0])[1]\n      apply (simp add: add_def opp_def Let_def)\n      apply (rule conjI)\n      apply field\n      apply (simp add: eq_diff0)\n      apply field\n      apply (simp add: eq_diff0)\n      done\n  qed\nqed\n\nlemma compat_add_opp:\n  assumes a: \"a \\<in> carrier R\"\n  and b: \"b \\<in> carrier R\"\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 = 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 a b 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  with \\<open>on_curve a b p\\<close> 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  with \\<open>on_curve a b p\\<^sub>1\\<close> 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  then have \"x\\<^sub>1 \\<in> carrier R\" \"y\\<^sub>1 \\<in> carrier R\" \"x\\<^sub>2 \\<in> carrier R\" \"y\\<^sub>2 \\<in> carrier R\"\n    by (simp_all add: on_curve_def)\n  have \"\\<guillemotleft>2\\<guillemotright> \\<otimes> \\<guillemotleft>2\\<guillemotright> \\<noteq> \\<zero>\"\n    by (simp add: integral_iff)\n  then have \"\\<guillemotleft>4\\<guillemotright> \\<noteq> \\<zero>\" by (simp add: of_int_mult [symmetric])\n  from Gen have \"((\\<ominus> y\\<^sub>2 \\<ominus> y\\<^sub>1) \\<oslash> (x\\<^sub>2 \\<ominus> x\\<^sub>1)) [^] (2::nat) \\<ominus> x\\<^sub>1 \\<ominus> x\\<^sub>2 =\n    ((y\\<^sub>2 \\<ominus> y\\<^sub>1) \\<oslash> (x\\<^sub>2 \\<ominus> x\\<^sub>1)) [^] (2::nat) \\<ominus> x\\<^sub>1 \\<ominus> 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>y\\<^sub>1 \\<in> carrier R\\<close> \\<open>y\\<^sub>2 \\<in> carrier R\\<close> \\<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>\\<guillemotleft>4\\<guillemotright> \\<noteq> \\<zero>\\<close>)[1]\n    apply (simp add: integral_iff opp_def eq_neg_iff_add_eq_0 mult2)\n    apply (insert \\<open>x\\<^sub>1 \\<in> carrier R\\<close> \\<open>x\\<^sub>2 \\<in> carrier R\\<close> \\<open>x\\<^sub>1 \\<noteq> x\\<^sub>2\\<close>)\n    apply (simp add: eq_diff0)\n    done\nqed\n\n\n\nlemma add_opp_double_opp:\n  assumes a: \"a \\<in> carrier R\"\n  and b: \"b \\<in> carrier R\"\n  and 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 a b 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 a b 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 a b \\<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 \"x\\<^sub>1 \\<in> carrier R\" \"y\\<^sub>1 \\<in> carrier R\"\n      and y\\<^sub>1: \"y\\<^sub>1 [^] (2::nat) = x\\<^sub>1 [^] (3::nat) \\<oplus> a \\<otimes> x\\<^sub>1 \\<oplus> b\"\n      by (simp_all 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 \"x\\<^sub>2 \\<in> carrier R\" \"y\\<^sub>2 \\<in> carrier R\"\n      and y\\<^sub>2: \"y\\<^sub>2 [^] (2::nat) = x\\<^sub>2 [^] (3::nat) \\<oplus> a \\<otimes> x\\<^sub>2 \\<oplus> b\"\n      by (simp_all 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> \\<open>y\\<^sub>1 \\<in> carrier R\\<close>\n    have \"y\\<^sub>1 \\<noteq> \\<zero>\"\n      by (simp add: opp_Point integral_iff equal_neg_zero)\n    from Gen have \"x\\<^sub>1 = ((y\\<^sub>2 \\<ominus> y\\<^sub>1) \\<oslash> (x\\<^sub>2 \\<ominus> x\\<^sub>1)) [^] (2::nat) \\<ominus> x\\<^sub>1 \\<ominus> x\\<^sub>2\"\n      by (simp add: opp_Point)\n    then have \"\\<guillemotleft>2\\<guillemotright> \\<otimes> y\\<^sub>2 \\<otimes> y\\<^sub>1 = a \\<otimes> x\\<^sub>2 \\<oplus> \\<guillemotleft>3\\<guillemotright> \\<otimes> x\\<^sub>2 \\<otimes> x\\<^sub>1 [^] (2::nat) \\<oplus> a \\<otimes> x\\<^sub>1 \\<ominus>\n      x\\<^sub>1 [^] (3::nat) \\<oplus> \\<guillemotleft>2\\<guillemotright> \\<otimes> 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 (insert \\<open>x\\<^sub>1 \\<noteq> x\\<^sub>2\\<close> \\<open>x\\<^sub>1 \\<in> carrier R\\<close> \\<open>x\\<^sub>2 \\<in> carrier R\\<close>)\n      apply (simp add: eq_diff0)\n      done\n    then have \"(x\\<^sub>2 \\<ominus> (((\\<guillemotleft>3\\<guillemotright> \\<otimes> x\\<^sub>1 [^] (2::nat) \\<oplus> a) \\<oslash> (\\<guillemotleft>2\\<guillemotright> \\<otimes> (\\<ominus> y\\<^sub>1))) [^] (2::nat) \\<ominus>\n      \\<guillemotleft>2\\<guillemotright> \\<otimes> x\\<^sub>1)) \\<otimes> (x\\<^sub>2 \\<ominus> x\\<^sub>1) [^] (2::nat) = \\<zero>\"\n      apply (drule_tac f=\"\\<lambda>x. x [^] (2::nat)\" in arg_cong)\n      apply (field (prems) y\\<^sub>1 y\\<^sub>2)\n      apply (field y\\<^sub>1 y\\<^sub>2)\n      apply (insert \\<open>y\\<^sub>1 \\<noteq> \\<zero>\\<close> \\<open>y\\<^sub>1 \\<in> carrier R\\<close>)\n      apply (simp_all add: integral_iff neg_equal_swap)\n      done\n    with a \\<open>x\\<^sub>1 \\<in> carrier R\\<close> \\<open>y\\<^sub>1 \\<in> carrier R\\<close> \\<open>x\\<^sub>2 \\<in> carrier R\\<close>\n      \\<open>y\\<^sub>1 \\<noteq> \\<zero>\\<close> \\<open>x\\<^sub>1 \\<noteq> x\\<^sub>2\\<close>\n    have \"x\\<^sub>2 = ((\\<guillemotleft>3\\<guillemotright> \\<otimes> x\\<^sub>1 [^] (2::nat) \\<oplus> a) \\<oslash> (\\<guillemotleft>2\\<guillemotright> \\<otimes> (\\<ominus> y\\<^sub>1))) [^] (2::nat) \\<ominus>\n      \\<guillemotleft>2\\<guillemotright> \\<otimes> x\\<^sub>1\"\n      by (simp add: integral_iff eq_diff0 neg_equal_swap)\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 a b\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 (insert \\<open>y\\<^sub>1 \\<in> carrier R\\<close> \\<open>y\\<^sub>1 \\<noteq> \\<zero>\\<close>)\n      apply (simp add: add_def opp_Point neg_equal_zero Let_def \\<open>p\\<^sub>1 = Point x\\<^sub>1 y\\<^sub>1\\<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 a b \\<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 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 a b \\<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 a b \\<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 add_closed opp_closed opp_opp add_comm)\n        with a b 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 a b \\<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 a b \\<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 a: \"a \\<in> carrier R\"\n  and b: \"b \\<in> carrier R\"\n  and 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 a b 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 a b p\\<^sub>3 have \"add a p\\<^sub>3 p = p\" by (simp add: add_comm)\n  with a b 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 p\\<^sub>3 \\<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> \\<open>p\\<^sub>1 = Point x\\<^sub>1 y\\<^sub>1\\<close>\n  have \"x\\<^sub>1 \\<in> carrier R\" \"y\\<^sub>1 \\<in> carrier R\"\n    by (simp_all 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 \"x\\<^sub>2 \\<in> carrier R\" \"y\\<^sub>2 \\<in> carrier R\"\n    by (simp_all add: on_curve_def)\n  from add_closed [OF a b \\<open>on_curve a b p\\<^sub>1\\<close> \\<open>on_curve a b p\\<^sub>2\\<close>]\n    \\<open>p\\<^sub>4 = add a p\\<^sub>1 p\\<^sub>2\\<close> [symmetric] \\<open>p\\<^sub>4 = Point x\\<^sub>4 y\\<^sub>4\\<close>\n  have \"x\\<^sub>4 \\<in> carrier R\" \"y\\<^sub>4 \\<in> carrier R\"\n    by (simp_all add: on_curve_def)\n  from \\<open>_ \\<or> _\\<close> a \\<open>p\\<^sub>1 \\<noteq> opp p\\<^sub>2\\<close> \\<open>p\\<^sub>1 = Point x\\<^sub>1 y\\<^sub>1\\<close> \\<open>p\\<^sub>2 = Point x\\<^sub>2 y\\<^sub>2\\<close>\n    \\<open>x\\<^sub>1 \\<in> carrier R\\<close> \\<open>y\\<^sub>1 \\<in> carrier R\\<close>\n    \\<open>x\\<^sub>2 \\<in> carrier R\\<close> \\<open>y\\<^sub>2 \\<in> carrier R\\<close>\n  have \"l \\<in> carrier R\"\n    by (auto simp add: opp_Point equal_neg_zero integral_iff eq_diff0)\n  from a b \\<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 a b \\<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 a b 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    with \\<open>on_curve a b p\\<^sub>2\\<close> 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>on_curve a b p\\<^sub>3\\<close> \\<open>p\\<^sub>3 = Point x\\<^sub>3 y\\<^sub>3\\<close>\n    have \"x\\<^sub>3 \\<in> carrier R\" \"y\\<^sub>3 \\<in> carrier R\"\n      by (simp_all add: on_curve_def)\n    from \\<open>x\\<^sub>1' = x\\<^sub>3 \\<and> _ \\<or> _\\<close> a \\<open>p\\<^sub>1 \\<noteq> opp p\\<^sub>3\\<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> \\<open>p\\<^sub>3 = Point x\\<^sub>3 y\\<^sub>3\\<close>\n      \\<open>x\\<^sub>1 \\<in> carrier R\\<close> \\<open>y\\<^sub>1 \\<in> carrier R\\<close>\n      \\<open>x\\<^sub>3 \\<in> carrier R\\<close> \\<open>y\\<^sub>3 \\<in> carrier R\\<close>\n    have \"l' \\<in> carrier R\"\n      by (auto simp add: opp_Point equal_neg_zero integral_iff eq_diff0)\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 = \\<ominus> y\\<^sub>1 \\<ominus> l \\<otimes> (x\\<^sub>4 \\<ominus> x\\<^sub>1)\\<close> \\<open>y\\<^sub>5 = \\<ominus> y\\<^sub>1' \\<ominus> l' \\<otimes> (x\\<^sub>5 \\<ominus> x\\<^sub>1')\\<close>\n      \\<open>x\\<^sub>1 \\<in> carrier R\\<close> \\<open>y\\<^sub>1 \\<in> carrier R\\<close> \\<open>x\\<^sub>4 \\<in> carrier R\\<close> \\<open>l' \\<in> carrier R\\<close>\n    have \"\\<zero> = \\<ominus> y\\<^sub>1 \\<ominus> l \\<otimes> (x\\<^sub>4 \\<ominus> x\\<^sub>1) \\<ominus> (\\<ominus> y\\<^sub>1 \\<ominus> l' \\<otimes> (x\\<^sub>4 \\<ominus> x\\<^sub>1))\"\n      by (auto simp add: trans [OF eq_commute eq_diff0])\n    with \\<open>x\\<^sub>1 \\<in> carrier R\\<close> \\<open>y\\<^sub>1 \\<in> carrier R\\<close> \\<open>x\\<^sub>4 \\<in> carrier R\\<close>\n      \\<open>l \\<in> carrier R\\<close> \\<open>l' \\<in> carrier R\\<close>\n    have \"(l' \\<ominus> l) \\<otimes> (x\\<^sub>4 \\<ominus> x\\<^sub>1) = \\<zero>\"\n      apply simp\n      apply (rule eq_diff0 [THEN iffD1])\n      apply simp\n      apply simp\n      apply ring\n      done\n    with \\<open>x\\<^sub>1 \\<in> carrier R\\<close> \\<open>x\\<^sub>4 \\<in> carrier R\\<close> \\<open>l \\<in> carrier R\\<close> \\<open>l' \\<in> carrier R\\<close>\n    have \"l' = l \\<or> x\\<^sub>4 = x\\<^sub>1\"\n      by (simp add: integral_iff eq_diff0)\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 \\<ominus> x\\<^sub>1 \\<ominus> x\\<^sub>2\\<close> \\<open>x\\<^sub>5 = l' [^] 2 \\<ominus> x\\<^sub>1' \\<ominus> x\\<^sub>3\\<close>\n        \\<open>x\\<^sub>1 \\<in> carrier R\\<close> \\<open>x\\<^sub>3 \\<in> carrier R\\<close> \\<open>l \\<in> carrier R\\<close>\n      have \"\\<zero> = l [^] (2::nat) \\<ominus> x\\<^sub>1 \\<ominus> x\\<^sub>2 \\<ominus> (l [^] (2::nat) \\<ominus> x\\<^sub>1 \\<ominus> x\\<^sub>3)\"\n        by (simp add: trans [OF eq_commute eq_diff0])\n      with \\<open>x\\<^sub>1 \\<in> carrier R\\<close> \\<open>x\\<^sub>2 \\<in> carrier R\\<close> \\<open>x\\<^sub>3 \\<in> carrier R\\<close> \\<open>l \\<in> carrier R\\<close>\n      have \"x\\<^sub>2 = x\\<^sub>3\"\n        apply (rule_tac eq_diff0 [THEN iffD1, THEN sym])\n        apply simp_all\n        apply (rule eq_diff0 [THEN iffD1])\n        apply simp_all[2]\n        apply ring\n        done\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 \\<ominus> y\\<^sub>1) \\<oslash> (x\\<^sub>2 \\<ominus> x\\<^sub>1) = (y\\<^sub>3 \\<ominus> y\\<^sub>1) \\<oslash> (x\\<^sub>2 \\<ominus> 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 (rule eq_diff0 [THEN iffD1])\n            apply (insert \\<open>x\\<^sub>1 \\<noteq> x\\<^sub>2\\<close> \\<open>x\\<^sub>1 \\<in> carrier R\\<close> \\<open>y\\<^sub>1 \\<in> carrier R\\<close>\n              \\<open>x\\<^sub>2 \\<in> carrier R\\<close> \\<open>y\\<^sub>2 \\<in> carrier R\\<close> \\<open>y\\<^sub>3 \\<in> carrier R\\<close>)\n            apply simp_all\n            apply (erule subst)\n            apply (rule eq_diff0 [THEN iffD1])\n            apply simp_all\n            apply ring\n            apply (simp add: eq_diff0)\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 a b \\<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 a b \\<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 a b \\<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 a b 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          a b \\<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 a b 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 a b 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 a b 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 a: \"a \\<in> carrier R\"\n  and b: \"b \\<in> carrier R\"\n  and 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 a b 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 a b 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 a b 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 a b ab \\<open>on_curve a b p\\<^sub>1\\<close>\n    moreover 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 \\<in> carrier R\" by (simp add: on_curve_def)\n    with \\<open>y\\<^sub>1 \\<noteq> \\<zero>\\<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 equal_neg_zero)\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 a b\n      add_closed [OF a b \\<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 \\<open>on_curve a b p\\<^sub>2\\<close>]\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>on_curve a b p\\<close> \\<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 a b 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>1\\<close> \\<open>p\\<^sub>1 = Point x\\<^sub>1 y\\<^sub>1\\<close>\n      have \"x\\<^sub>1 \\<in> carrier R\" \"y\\<^sub>1 \\<in> carrier R\"\n        by (simp_all 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 \"x\\<^sub>2 \\<in> carrier R\" \"y\\<^sub>2 \\<in> carrier R\"\n        by (simp_all add: on_curve_def)\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 = \\<ominus> 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 = \\<ominus> 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 \\<ominus> x\\<^sub>4 \\<ominus> x\\<^sub>5\\<close> \\<open>y\\<^sub>6 = \\<ominus> y\\<^sub>4 \\<ominus> l' \\<otimes> (x\\<^sub>6 \\<ominus> x\\<^sub>4)\\<close>\n          \\<open>l' = (y\\<^sub>5 \\<ominus> y\\<^sub>4) \\<oslash> (x\\<^sub>5 \\<ominus> x\\<^sub>4)\\<close>\n          \\<open>x\\<^sub>3 = l [^] 2 \\<ominus> x\\<^sub>1 \\<ominus> x\\<^sub>2\\<close> \\<open>y\\<^sub>3 = \\<ominus> y\\<^sub>1 \\<ominus> l \\<otimes> (x\\<^sub>3 \\<ominus> x\\<^sub>1)\\<close>\n          \\<open>l = (y\\<^sub>2 \\<ominus> y\\<^sub>1) \\<oslash> (x\\<^sub>2 \\<ominus> 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: eq_diff0 [OF \\<open>x\\<^sub>2 \\<in> carrier R\\<close> \\<open>x\\<^sub>1 \\<in> carrier R\\<close>]\n          \\<open>x\\<^sub>1 \\<noteq> x\\<^sub>2\\<close> [THEN not_sym])\n        apply field\n        apply (rule conjI)\n        apply (simp add: eq_diff0 [OF \\<open>x\\<^sub>2 \\<in> carrier R\\<close> \\<open>x\\<^sub>1 \\<in> carrier R\\<close>]\n          \\<open>x\\<^sub>1 \\<noteq> x\\<^sub>2\\<close> [THEN not_sym])\n        apply (rule notI)\n        apply (erule notE)\n        apply (ring (prems))\n        apply (rule sym)\n        apply field\n        apply (simp add: eq_diff0 [OF \\<open>x\\<^sub>2 \\<in> carrier R\\<close> \\<open>x\\<^sub>1 \\<in> carrier R\\<close>]\n          \\<open>x\\<^sub>1 \\<noteq> x\\<^sub>2\\<close> [THEN not_sym])\n        done\n    qed\n  qed\nqed\n\nlemma add_shift_minus:\n  assumes a: \"a \\<in> carrier R\"\n  and b: \"b \\<in> carrier R\"\n  and 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 a b 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 a b p\\<^sub>1 p\\<^sub>2 p\\<^sub>3\n    by (simp add: add_comm add_closed opp_closed)\n  with a b ab p\\<^sub>2 p\\<^sub>1 add_closed [OF a b p\\<^sub>3 opp_closed [OF p\\<^sub>2]]\n  show ?thesis by (rule cancel)\nqed\n\nlemma degen_assoc:\n  assumes a: \"a \\<in> carrier R\"\n  and b: \"b \\<in> carrier R\"\n  and 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 a b 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 add_closed opp_closed)\n  also from a b 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 a b 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 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 a b 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 opp_closed)\n  also from a b 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 a b p\\<^sub>3 have \"\\<dots> = add a (opp p\\<^sub>3) p\\<^sub>3\"\n    by (simp add: add_comm opp_closed)\n  also from a b 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 a b 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 opp_opp opp_closed)\n  finally show ?thesis\n    using opp_add [OF a b 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 a b 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 a b 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 opp_opp add_closed opp_closed)\n  also from a b 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 a b p\\<^sub>3 have \"\\<dots> = add a (opp p\\<^sub>3) p\\<^sub>3\"\n    by (simp add: add_comm opp_closed)\n  finally show ?thesis using eq [symmetric] by simp\nqed\n\nlemma spec4_assoc:\n  assumes a: \"a \\<in> carrier R\"\n  and b: \"b \\<in> carrier R\"\n  and 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 a b 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 a b 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 a b 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 a b 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 a b 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 a b 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 a b 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 [OF a b])\n                apply (simp_all add: is_generic_def is_tangent_def)\n                apply (rule notI)\n                apply (drule uniq_zero [OF a b 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 b])\n                apply (simp_all add: add_comm add_closed)[2]\n                apply (erule notE)\n                apply (drule uniq_zero [OF a b ab add_closed [OF a b 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 a b 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 a b p\\<^sub>2 show ?thesis\n                    by (simp add: add_comm add_closed)\n                next\n                  case False\n                  with a b 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 [OF a b])\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)\n                    apply assumption\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 [OF add_closed [OF a b p\\<^sub>2 p\\<^sub>2]])\n                    done\n                qed\n              qed\n            qed\n          qed\n        qed\n      qed\n    qed\n  qed\nqed\n\n\n\n\nprimrec 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: \"a \\<in> carrier R \\<Longrightarrow> b \\<in> carrier R \\<Longrightarrow>\n  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  \"a \\<in> carrier R \\<Longrightarrow> b \\<in> carrier R \\<Longrightarrow> 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  \"a \\<in> carrier R \\<Longrightarrow> b \\<in> carrier R \\<Longrightarrow> 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\nend\n\nsubsection \\<open>Projective Coordinates\\<close>\n\ntype_synonym 'a ppoint = \"'a \\<times> 'a \\<times> 'a\"\n\ndefinition (in cring) pdouble :: \"'a \\<Rightarrow> 'a ppoint \\<Rightarrow> 'a ppoint\" where\n  \"pdouble a p =\n     (let (x, y, z) = p\n      in\n        if z = \\<zero> then p\n        else\n          let\n            l = \\<guillemotleft>2\\<guillemotright> \\<otimes> y \\<otimes> z;\n            m = \\<guillemotleft>3\\<guillemotright> \\<otimes> x [^] (2::nat) \\<oplus> a \\<otimes> z [^] (2::nat)\n          in\n            (l \\<otimes> (m [^] (2::nat) \\<ominus> \\<guillemotleft>4\\<guillemotright> \\<otimes> x \\<otimes> y \\<otimes> l),\n             m \\<otimes> (\\<guillemotleft>6\\<guillemotright> \\<otimes> x \\<otimes> y \\<otimes> l \\<ominus> m [^] (2::nat)) \\<ominus>\n             \\<guillemotleft>2\\<guillemotright> \\<otimes> y [^] (2::nat) \\<otimes> l [^] (2::nat),\n             l [^] (3::nat)))\"\n\ndefinition (in cring) 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 = \\<zero> then p\\<^sub>2\n        else if z\\<^sub>2 = \\<zero> then p\\<^sub>1\n        else\n          let\n            d\\<^sub>1 = x\\<^sub>2 \\<otimes> z\\<^sub>1;\n            d\\<^sub>2 = x\\<^sub>1 \\<otimes> z\\<^sub>2;\n            l = d\\<^sub>1 \\<ominus> d\\<^sub>2;\n            m = y\\<^sub>2 \\<otimes> z\\<^sub>1 \\<ominus> y\\<^sub>1 \\<otimes> z\\<^sub>2\n          in\n            if l = \\<zero> then\n              if m = \\<zero> then pdouble a p\\<^sub>1\n              else (\\<zero>, \\<zero>, \\<zero>)\n            else\n              let h = m [^] (2::nat) \\<otimes> z\\<^sub>1 \\<otimes> z\\<^sub>2 \\<ominus> (d\\<^sub>1 \\<oplus> d\\<^sub>2) \\<otimes> l [^] (2::nat)\n              in\n                (l \\<otimes> h,\n                 (d\\<^sub>2 \\<otimes> l [^] (2::nat) \\<ominus> h) \\<otimes> m \\<ominus> l [^] (3::nat) \\<otimes> y\\<^sub>1 \\<otimes> z\\<^sub>2,\n                 l [^] (3::nat) \\<otimes> z\\<^sub>1 \\<otimes> z\\<^sub>2))\"\n\ndefinition (in field) make_affine :: \"'a ppoint \\<Rightarrow> 'a point\" where\n  \"make_affine p =\n     (let (x, y, z) = p\n      in if z = \\<zero> then Infinity else Point (x \\<oslash> z) (y \\<oslash> z))\"\n\ndefinition (in cring) in_carrierp :: \"'a ppoint \\<Rightarrow> bool\" where\n  \"in_carrierp = (\\<lambda>(x, y, z). x \\<in> carrier R \\<and> y \\<in> carrier R \\<and> z \\<in> carrier R)\"\n\ndefinition (in cring) on_curvep :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a ppoint \\<Rightarrow> bool\" where\n  \"on_curvep a b = (\\<lambda>(x, y, z).\n     x \\<in> carrier R \\<and> y \\<in> carrier R \\<and> z \\<in> carrier R \\<and>\n     (z \\<noteq> \\<zero> \\<longrightarrow>\n      y [^] (2::nat) \\<otimes> z = x [^] (3::nat) \\<oplus> a \\<otimes> x \\<otimes> z [^] (2::nat) \\<oplus> b \\<otimes> z [^] (3::nat)))\"\n\nlemma (in cring) on_curvep_infinity [simp]: \"on_curvep a b (x, y, \\<zero>) = (x \\<in> carrier R \\<and> y \\<in> carrier R)\"\n  by (simp add: on_curvep_def)\n\nlemma (in field) make_affine_infinity [simp]: \"make_affine (x, y, \\<zero>) = Infinity\"\n  by (simp add: make_affine_def)\n\nlemma (in cring) on_curvep_imp_in_carrierp [simp]: \"on_curvep a b p \\<Longrightarrow> in_carrierp p\"\n  by (auto simp add: on_curvep_def in_carrierp_def)\n\nlemma (in ell_field) on_curvep_iff_on_curve:\n  assumes \"a \\<in> carrier R\" \"b \\<in> carrier R\" \"in_carrierp p\"\n  shows \"on_curvep a b p = on_curve a b (make_affine p)\"\n  using assms\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 carrier: \"x \\<in> carrier R\" \"y \\<in> carrier R\" \"z \\<in> carrier R\"\n      and yz: \"z \\<noteq> \\<zero> \\<Longrightarrow>\n        y [^] (2::nat) \\<otimes> z = x [^] (3::nat) \\<oplus> a \\<otimes> x \\<otimes> z [^] (2::nat) \\<oplus> b \\<otimes> z [^] (3::nat)\"\n      by (simp_all add: on_curvep_def)\n    show \"on_curve a b (make_affine (x, y, z))\"\n    proof (cases \"z = \\<zero>\")\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 carrier)\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 = \\<zero>\")\n      case True\n      with \\<open>in_carrierp (x, y, z)\\<close> show ?thesis\n        by (simp add: on_curvep_def in_carrierp_def)\n    next\n      case False\n      from \\<open>in_carrierp (x, y, z)\\<close>\n      have carrier: \"x \\<in> carrier R\" \"y \\<in> carrier R\" \"z \\<in> carrier R\"\n        by (simp_all add: in_carrierp_def)\n      from H show ?thesis\n        apply (simp add: on_curve_def on_curvep_def make_affine_def carrier False)\n        apply (field (prems))\n        apply field\n        apply (simp_all add: False)\n        done\n    qed\n  qed\nqed\n\nlemma (in cring) pdouble_in_carrierp:\n  \"a \\<in> carrier R \\<Longrightarrow> in_carrierp p \\<Longrightarrow> in_carrierp (pdouble a p)\"\n  by (auto simp add: in_carrierp_def pdouble_def Let_def split: prod.split)\n\n\n\nlemma (in cring) pdouble_infinity [simp]: \"pdouble a (x, y, \\<zero>) = (x, y, \\<zero>)\"\n  by (simp add: pdouble_def)\n\nlemma (in cring) padd_infinity_l [simp]: \"padd a (x, y, \\<zero>) p = p\"\n  by (simp add: padd_def)\n\nlemma (in ell_field) pdouble_correct:\n  \"a \\<in> carrier R \\<Longrightarrow> in_carrierp p \\<Longrightarrow>\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 have \"x \\<in> carrier R\" \"y \\<in> carrier R\" \"z \\<in> carrier R\"\n    by (simp_all add: in_carrierp_def)\n  then show ?case\n    apply (auto simp add: add_def pdouble_def make_affine_def equal_neg_zero divide_eq_0_iff\n      integral_iff Let_def simp del: minus_divide_left)\n    apply field\n    apply (simp add: integral_iff)\n    apply field\n    apply (simp add: integral_iff)\n    done\nqed\n\nlemma (in ell_field) padd_correct:\n  assumes a: \"a \\<in> carrier R\" and b: \"b \\<in> carrier R\"\n  and 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 \"x\\<^sub>2 \\<in> carrier R\" \"y\\<^sub>2 \\<in> carrier R\" \"z\\<^sub>2 \\<in> carrier R\" and\n      yz\\<^sub>2: \"z\\<^sub>2 \\<noteq> \\<zero> \\<Longrightarrow> y\\<^sub>2 [^] (2::nat) \\<otimes> z\\<^sub>2 \\<otimes> z\\<^sub>1 [^] (3::nat) =\n        (x\\<^sub>2 [^] (3::nat) \\<oplus> a \\<otimes> x\\<^sub>2 \\<otimes> z\\<^sub>2 [^] (2::nat) \\<oplus> b \\<otimes> z\\<^sub>2 [^] (3::nat)) \\<otimes> z\\<^sub>1 [^] (3::nat)\"\n      by (simp_all add: on_curvep_def)\n    from p\\<^sub>1' have \"x\\<^sub>1 \\<in> carrier R\" \"y\\<^sub>1 \\<in> carrier R\" \"z\\<^sub>1 \\<in> carrier R\" and\n      yz\\<^sub>1: \"z\\<^sub>1 \\<noteq> \\<zero> \\<Longrightarrow> y\\<^sub>1 [^] (2::nat) \\<otimes> z\\<^sub>1 \\<otimes> z\\<^sub>2 [^] (3::nat) =\n        (x\\<^sub>1 [^] (3::nat) \\<oplus> a \\<otimes> x\\<^sub>1 \\<otimes> z\\<^sub>1 [^] (2::nat) \\<oplus> b \\<otimes> z\\<^sub>1 [^] (3::nat)) \\<otimes> z\\<^sub>2 [^] (3::nat)\"\n      by (simp_all add: on_curvep_def)\n    show ?case\n    proof (cases \"z\\<^sub>1 = \\<zero>\")\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 = \\<zero>\")\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 \\<otimes> z\\<^sub>1 \\<ominus> x\\<^sub>1 \\<otimes> z\\<^sub>2 = \\<zero>\")\n          case True\n          note x = this\n          with \\<open>x\\<^sub>1 \\<in> carrier R\\<close> \\<open>x\\<^sub>2 \\<in> carrier R\\<close> \\<open>z\\<^sub>1 \\<in> carrier R\\<close> \\<open> z\\<^sub>2 \\<in> carrier R\\<close>\n          have x': \"x\\<^sub>2 \\<otimes> z\\<^sub>1 = x\\<^sub>1 \\<otimes> z\\<^sub>2\" by (simp add: eq_diff0)\n          show ?thesis\n          proof (cases \"y\\<^sub>2 \\<otimes> z\\<^sub>1 \\<ominus> y\\<^sub>1 \\<otimes> z\\<^sub>2 = \\<zero>\")\n            case True\n            with \\<open>y\\<^sub>1 \\<in> carrier R\\<close> \\<open>y\\<^sub>2 \\<in> carrier R\\<close> \\<open>z\\<^sub>1 \\<in> carrier R\\<close> \\<open> z\\<^sub>2 \\<in> carrier R\\<close>\n            have y: \"y\\<^sub>2 \\<otimes> z\\<^sub>1 = y\\<^sub>1 \\<otimes> z\\<^sub>2\" by (simp add: eq_diff0)\n            from \\<open>z\\<^sub>1 \\<noteq> \\<zero>\\<close> \\<open>z\\<^sub>2 \\<noteq> \\<zero>\\<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> \\<zero>\\<close> \\<open>z\\<^sub>2 \\<noteq> \\<zero>\\<close> p\\<^sub>1' fields a show ?thesis\n              by (simp add: padd_def pdouble_correct)\n          next\n            case False\n            have \"y\\<^sub>2 [^] (2::nat) \\<otimes> z\\<^sub>1 [^] (3::nat) \\<otimes> z\\<^sub>2 =\n              y\\<^sub>1 [^] (2::nat) \\<otimes> z\\<^sub>1 \\<otimes> z\\<^sub>2 [^] (3::nat)\"\n              by (ring yz\\<^sub>1 [OF \\<open>z\\<^sub>1 \\<noteq> \\<zero>\\<close>] yz\\<^sub>2 [OF \\<open>z\\<^sub>2 \\<noteq> \\<zero>\\<close>] x')\n            then have \"y\\<^sub>2 [^] (2::nat) \\<otimes> z\\<^sub>1 [^] (3::nat) \\<otimes> z\\<^sub>2 \\<oslash> z\\<^sub>1 \\<oslash> z\\<^sub>2 =\n              y\\<^sub>1 [^] (2::nat) \\<otimes> z\\<^sub>1 \\<otimes> z\\<^sub>2 [^] (3::nat) \\<oslash> z\\<^sub>1 \\<oslash> z\\<^sub>2\"\n              by simp\n            then have \"(y\\<^sub>2 \\<otimes> z\\<^sub>1) \\<otimes> (y\\<^sub>2 \\<otimes> z\\<^sub>1) = (y\\<^sub>1 \\<otimes> z\\<^sub>2) \\<otimes> (y\\<^sub>1 \\<otimes> z\\<^sub>2)\"\n              apply (field (prems))\n              apply (field)\n              apply (rule TrueI)\n              apply (simp add: \\<open>z\\<^sub>1 \\<noteq> \\<zero>\\<close> \\<open>z\\<^sub>2 \\<noteq> \\<zero>\\<close>)\n              done\n            with False\n            have y\\<^sub>2z\\<^sub>1: \"y\\<^sub>2 \\<otimes> z\\<^sub>1 = \\<ominus> (y\\<^sub>1 \\<otimes> z\\<^sub>2)\"\n              by (simp add: square_eq_iff eq_diff0\n                \\<open>y\\<^sub>1 \\<in> carrier R\\<close> \\<open>y\\<^sub>2 \\<in> carrier R\\<close> \\<open>z\\<^sub>1 \\<in> carrier R\\<close> \\<open>z\\<^sub>2 \\<in> carrier R\\<close>)\n            from x False \\<open>z\\<^sub>1 \\<noteq> \\<zero>\\<close> \\<open>z\\<^sub>2 \\<noteq> \\<zero>\\<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 \\<oslash> z\\<^sub>1 \\<noteq> x\\<^sub>2 \\<oslash> 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> \\<zero>\\<close> \\<open>z\\<^sub>2 \\<noteq> \\<zero>\\<close>)\n            done\n          with False \\<open>z\\<^sub>1 \\<noteq> \\<zero>\\<close> \\<open>z\\<^sub>2 \\<noteq> \\<zero>\\<close>\n            \\<open>x\\<^sub>1 \\<in> carrier R\\<close> \\<open>x\\<^sub>2 \\<in> carrier R\\<close> \\<open>z\\<^sub>1 \\<in> carrier R\\<close> \\<open>z\\<^sub>2 \\<in> carrier R\\<close>\n          show ?thesis\n            apply (auto simp add: padd_def add_def make_affine_def Let_def integral_iff)\n            apply field\n            apply (simp add: integral_iff)\n            apply field\n            apply (simp add: integral_iff)\n            done\n        qed\n      qed\n    qed\n  qed\nqed\n\n\n\nlemma (in ell_field) padd_closed:\n  assumes \"a \\<in> carrier R\" \"b \\<in> carrier R\" \"on_curvep a b p\\<^sub>1\" \"on_curvep a b p\\<^sub>2\"\n  shows \"on_curvep a b (padd a p\\<^sub>1 p\\<^sub>2)\"\nproof -\n  from \\<open>on_curvep a b p\\<^sub>1\\<close> have \"in_carrierp p\\<^sub>1\" by simp\n  from \\<open>on_curvep a b p\\<^sub>2\\<close> have \"in_carrierp p\\<^sub>2\" by simp\n  from assms show ?thesis\n    by (simp add: on_curvep_iff_on_curve padd_in_carrierp padd_correct\n      add_closed \\<open>in_carrierp p\\<^sub>1\\<close> \\<open>in_carrierp p\\<^sub>2\\<close>)\nqed\n\nprimrec (in cring) ppoint_mult :: \"'a \\<Rightarrow> nat \\<Rightarrow> 'a ppoint \\<Rightarrow> 'a ppoint\"\nwhere\n    \"ppoint_mult a 0 p = (\\<zero>, \\<zero>, \\<zero>)\"\n  | \"ppoint_mult a (Suc n) p = padd a p (ppoint_mult a n p)\"\n\nlemma (in ell_field) ppoint_mult_closed [simp]:\n  \"a \\<in> carrier R \\<Longrightarrow> b \\<in> carrier R \\<Longrightarrow> 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 (in ell_field) ppoint_mult_correct: \"a \\<in> carrier R \\<Longrightarrow> b \\<in> carrier R \\<Longrightarrow> 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\ndefinition (in cring) 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 = \\<zero>) = (z\\<^sub>2 = \\<zero>) \\<and> x\\<^sub>1 \\<otimes> z\\<^sub>2 = x\\<^sub>2 \\<otimes> z\\<^sub>1 \\<and> y\\<^sub>1 \\<otimes> z\\<^sub>2 = y\\<^sub>2 \\<otimes> z\\<^sub>1)\"\n\nlemma (in cring) proj_eq_refl: \"proj_eq p p\"\n  by (auto simp add: proj_eq_def)\n\n\n\nlemma (in domain) 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 carrier:\n        \"x \\<in> carrier R\" \"y \\<in> carrier R\" \"z \\<in> carrier R\"\n        \"x' \\<in> carrier R\" \"y' \\<in> carrier R\" \"z' \\<in> carrier R\"\n        \"x'' \\<in> carrier R\" \"y'' \\<in> carrier R\" \"z'' \\<in> carrier R\"\n        and z: \"(z = \\<zero>) = (z' = \\<zero>)\" \"(z' = \\<zero>) = (z'' = \\<zero>)\" and\n        \"x \\<otimes> z' \\<otimes> z'' = x' \\<otimes> z \\<otimes> z''\"\n        \"y \\<otimes> z' \\<otimes> z'' = y' \\<otimes> z \\<otimes> z''\"\n        and xy:\n        \"x' \\<otimes> z'' = x'' \\<otimes> z'\"\n        \"y' \\<otimes> z'' = y'' \\<otimes> z'\"\n        by (simp_all add: in_carrierp_def proj_eq_def)\n      from \\<open>x \\<otimes> z' \\<otimes> z'' = x' \\<otimes> z \\<otimes> z''\\<close>\n      have \"(x \\<otimes> z'') \\<otimes> z' = (x'' \\<otimes> z) \\<otimes> z'\"\n        by (ring (prems) xy) (ring xy)\n      moreover from \\<open>y \\<otimes> z' \\<otimes> z'' = y' \\<otimes> z \\<otimes> z''\\<close>\n      have \"(y \\<otimes> z'') \\<otimes> z' = (y'' \\<otimes> z) \\<otimes> z'\"\n        by (ring (prems) xy) (ring xy)\n      ultimately show ?case using z\n        by (auto simp add: proj_eq_def carrier conc)\n    qed\n  qed\nqed\n\nlemma (in field) make_affine_proj_eq_iff:\n  \"in_carrierp p \\<Longrightarrow> in_carrierp p' \\<Longrightarrow> 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    then have carrier:\n      \"x \\<in> carrier R\" \"y \\<in> carrier R\" \"z \\<in> carrier R\"\n      \"x' \\<in> carrier R\" \"y' \\<in> carrier R\" \"z' \\<in> carrier R\"\n      by (simp_all add: in_carrierp_def)\n    show ?case\n    proof\n      assume \"proj_eq (x, y, z) (x', y', z')\"\n      then have \"(z = \\<zero>) = (z' = \\<zero>)\"\n        and xy: \"x \\<otimes> z' = x' \\<otimes> z\" \"y \\<otimes> z' = y' \\<otimes> 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 = \\<zero>\")\n        case True\n        with H have \"z' = \\<zero>\" by (simp add: make_affine_def split: if_split_asm)\n        with True carrier show ?thesis by (simp add: proj_eq_def)\n      next\n        case False\n        with H have \"z' \\<noteq> \\<zero>\" \"x \\<oslash> z = x' \\<oslash> z'\" \"y \\<oslash> z = y' \\<oslash> z'\"\n          by (simp_all add: make_affine_def split: if_split_asm)\n        from \\<open>x \\<oslash> z = x' \\<oslash> z'\\<close>\n        have \"x \\<otimes> z' = x' \\<otimes> z\"\n          apply (field (prems))\n          apply field\n          apply (simp_all add: \\<open>z \\<noteq> \\<zero>\\<close> \\<open>z' \\<noteq> \\<zero>\\<close>)\n          done\n        moreover from \\<open>y \\<oslash> z = y' \\<oslash> z'\\<close>\n        have \"y \\<otimes> z' = y' \\<otimes> z\"\n          apply (field (prems))\n          apply field\n          apply (simp_all add: \\<open>z \\<noteq> \\<zero>\\<close> \\<open>z' \\<noteq> \\<zero>\\<close>)\n          done\n        ultimately show ?thesis\n          by (simp add: proj_eq_def \\<open>z \\<noteq> \\<zero>\\<close> \\<open>z' \\<noteq> \\<zero>\\<close>)\n      qed\n    qed\n  qed\nqed\n\nlemma (in ell_field) pdouble_proj_eq_cong:\n  \"a \\<in> carrier R \\<Longrightarrow> in_carrierp p \\<Longrightarrow> in_carrierp p' \\<Longrightarrow> proj_eq p p' \\<Longrightarrow>\n   proj_eq (pdouble a p) (pdouble a p')\"\n  by (simp add: make_affine_proj_eq_iff pdouble_in_carrierp pdouble_correct)\n\nlemma (in ell_field) padd_proj_eq_cong:\n  \"a \\<in> carrier R \\<Longrightarrow> b \\<in> carrier R \\<Longrightarrow> on_curvep a b p\\<^sub>1 \\<Longrightarrow> on_curvep a b p\\<^sub>1' \\<Longrightarrow>\n   on_curvep a b p\\<^sub>2 \\<Longrightarrow> on_curvep a b p\\<^sub>2' \\<Longrightarrow> proj_eq p\\<^sub>1 p\\<^sub>1' \\<Longrightarrow> proj_eq p\\<^sub>2 p\\<^sub>2' \\<Longrightarrow>\n   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_in_carrierp 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_Locale.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8807970811069351, "lm_q2_score": 0.8031737892899222, "lm_q1q2_score": 0.70743312922816}}
{"text": "(*  Title:      HOL/Multivariate_Analysis/Determinants.thy\n    Author:     Amine Chaieb, University of Cambridge\n*)\n\nsection {* Traces, Determinant of square matrices and some properties *}\n\ntheory Determinants\nimports\n  Cartesian_Euclidean_Space\n  \"~~/src/HOL/Library/Permutations\"\nbegin\n\nsubsection{* First some facts about products*}\n\nlemma setprod_add_split:\n  fixes m n :: nat\n  assumes mn: \"m \\<le> n + 1\"\n  shows \"setprod f {m..n+p} = setprod f {m .. n} * setprod f {n+1..n+p}\"\nproof -\n  let ?A = \"{m..n+p}\"\n  let ?B = \"{m..n}\"\n  let ?C = \"{n+1..n+p}\"\n  from mn have un: \"?B \\<union> ?C = ?A\"\n    by auto\n  from mn have dj: \"?B \\<inter> ?C = {}\"\n    by auto\n  have f: \"finite ?B\" \"finite ?C\"\n    by simp_all\n  from setprod.union_disjoint[OF f dj, of f, unfolded un] show ?thesis .\nqed\n\n\nlemma setprod_offset:\n  fixes m n :: nat\n  shows \"setprod f {m + p .. n + p} = setprod (\\<lambda>i. f (i + p)) {m..n}\"\n  by (rule setprod.reindex_bij_witness[where i=\"op + p\" and j=\"\\<lambda>i. i - p\"]) auto\n\nlemma setprod_singleton: \"setprod f {x} = f x\"\n  by simp\n\nlemma setprod_singleton_nat_seg:\n  fixes n :: \"'a::order\"\n  shows \"setprod f {n..n} = f n\"\n  by simp\n\nlemma setprod_numseg:\n  \"setprod f {m..0} = (if m = 0 then f 0 else 1)\"\n  \"setprod f {m .. Suc n} =\n    (if m \\<le> Suc n then f (Suc n) * setprod f {m..n} else setprod f {m..n})\"\n  by (auto simp add: atLeastAtMostSuc_conv)\n\nlemma setprod_le:\n  fixes f g :: \"'b \\<Rightarrow> 'a::linordered_idom\"\n  assumes fS: \"finite S\"\n    and fg: \"\\<forall>x\\<in>S. f x \\<ge> 0 \\<and> f x \\<le> g x\"\n  shows \"setprod f S \\<le> setprod g S\"\n  using fS fg\n  apply (induct S)\n  apply simp\n  apply auto\n  apply (rule mult_mono)\n  apply (auto intro: setprod_nonneg)\n  done\n\n(* FIXME: In Finite_Set there is a useless further assumption *)\nlemma setprod_inversef:\n  \"finite A \\<Longrightarrow> setprod (inverse \\<circ> f) A = (inverse (setprod f A) :: 'a:: field_inverse_zero)\"\n  apply (erule finite_induct)\n  apply (simp)\n  apply simp\n  done\n\nlemma setprod_le_1:\n  fixes f :: \"'b \\<Rightarrow> 'a::linordered_idom\"\n  assumes fS: \"finite S\"\n    and f: \"\\<forall>x\\<in>S. f x \\<ge> 0 \\<and> f x \\<le> 1\"\n  shows \"setprod f S \\<le> 1\"\n  using setprod_le[OF fS f] unfolding setprod.neutral_const .\n\n\nsubsection {* Trace *}\n\ndefinition trace :: \"'a::semiring_1^'n^'n \\<Rightarrow> 'a\"\n  where \"trace A = setsum (\\<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 setsum.distrib)\n\nlemma trace_sub: \"trace ((A::'a::comm_ring_1^'n^'n) - B) = trace A - trace B\"\n  by (simp add: trace_def setsum_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 setsum.commute)\n  apply (simp add: mult.commute)\n  done\n\ntext {* Definition of determinant. *}\n\ndefinition det:: \"'a::comm_ring_1^'n^'n \\<Rightarrow> 'a\" where\n  \"det A =\n    setsum (\\<lambda>p. of_int (sign p) * setprod (\\<lambda>i. A$i$p i) (UNIV :: 'n set))\n      {p. p permutes (UNIV :: 'n set)}\"\n\ntext {* A few general lemmas we need below. *}\n\nlemma setprod_permute:\n  assumes p: \"p permutes S\"\n  shows \"setprod f S = setprod (f \\<circ> p) S\"\n  using assms by (fact setprod.permute)\n\nlemma setproduct_permute_nat_interval:\n  fixes m n :: nat\n  shows \"p permutes {m..n} \\<Longrightarrow> setprod f {m..n} = setprod (f \\<circ> p) {m..n}\"\n  by (blast intro!: setprod_permute)\n\ntext {* Basic determinant properties. *}\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 \"setprod (\\<lambda>i. ?di (transpose A) i (inv p i)) ?U =\n      setprod (\\<lambda>i. ?di (transpose A) i (inv p i)) (p ` ?U)\"\n      by simp\n    also have \"\\<dots> = setprod ((\\<lambda>i. ?di (transpose A) i (inv p i)) \\<circ> p) ?U\"\n      unfolding setprod.reindex[OF pi] ..\n    also have \"\\<dots> = setprod (\\<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 \"setprod ((\\<lambda>i. ?di (transpose A) i (inv p i)) \\<circ> p) ?U =\n        setprod (\\<lambda>i. ?di A i (p i)) ?U\"\n        by (auto intro: setprod.cong)\n    qed\n    finally have \"of_int (sign (inv p)) * (setprod (\\<lambda>i. ?di (transpose A) i (inv p i)) ?U) =\n      of_int (sign p) * (setprod (\\<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 setsum_permutations_inverse)\n    apply (rule setsum.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 = setprod (\\<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) * setprod (\\<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 setprod_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 setsum.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 = setprod (\\<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) * setprod (\\<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 setprod_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 setsum.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 = setprod (\\<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) * setprod (\\<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 setprod_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 setsum.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: \"setprod (\\<lambda>i. ?f i i) ?U = setprod (\\<lambda>x. 1) ?U\"\n    by (auto intro: setprod.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 = setprod (\\<lambda>i. ?f i i) ?U\"\n    using det_diagonal by blast\n  also have \"\\<dots> = 1\"\n    unfolding th setprod.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 setprod_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 setsum_right_distrib mult.assoc[symmetric])\n  apply (subst sum_permutations_compose_right[OF p])\nproof (rule setsum.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 \"setprod (\\<lambda>i. A$p i$ (q \\<circ> p) i) ?U = setprod ((\\<lambda>i. A$p i$(q \\<circ> p) i) \\<circ> inv p) ?U\"\n    by (simp only: setprod_permute[OF ip, symmetric])\n  also have \"\\<dots> = setprod (\\<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> = setprod (\\<lambda>i. A$i$q i) ?U\"\n    by (simp only: o_def permutes_inverses[OF p])\n  finally have thp: \"setprod (\\<lambda>i. A$p i$ (q \\<circ> p) i) ?U = setprod (\\<lambda>i. A$i$q i) ?U\"\n    by blast\n  show \"of_int (sign (q \\<circ> p)) * setprod (\\<lambda>i. A$ p i$ (q \\<circ> p) i) ?U =\n    of_int (sign p) * of_int (sign q) * setprod (\\<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 setsum.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 setsum.distrib[symmetric]\nproof (rule setsum.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: \"setprod (\\<lambda>i. ?f i $ p i) ?Uk = setprod (\\<lambda>i. ?g i $ p i) ?Uk\"\n    and th2: \"setprod (\\<lambda>i. ?f i $ p i) ?Uk = setprod (\\<lambda>i. ?h i $ p i) ?Uk\"\n    apply -\n    apply (rule setprod.cong, simp_all)+\n    done\n  have th3: \"finite ?Uk\" \"k \\<notin> ?Uk\"\n    by auto\n  have \"setprod (\\<lambda>i. ?f i $ p i) ?U = setprod (\\<lambda>i. ?f i $ p i) (insert k ?Uk)\"\n    unfolding kU[symmetric] ..\n  also have \"\\<dots> = ?f k $ p k * setprod (\\<lambda>i. ?f i $ p i) ?Uk\"\n    apply (rule setprod.insert)\n    apply simp\n    apply blast\n    done\n  also have \"\\<dots> = (a k $ p k * setprod (\\<lambda>i. ?f i $ p i) ?Uk) + (b k$ p k * setprod (\\<lambda>i. ?f i $ p i) ?Uk)\"\n    by (simp add: field_simps)\n  also have \"\\<dots> = (a k $ p k * setprod (\\<lambda>i. ?g i $ p i) ?Uk) + (b k$ p k * setprod (\\<lambda>i. ?h i $ p i) ?Uk)\"\n    by (metis th1 th2)\n  also have \"\\<dots> = setprod (\\<lambda>i. ?g i $ p i) (insert k ?Uk) + setprod (\\<lambda>i. ?h i $ p i) (insert k ?Uk)\"\n    unfolding  setprod.insert[OF th3] by simp\n  finally have \"setprod (\\<lambda>i. ?f i $ p i) ?U = setprod (\\<lambda>i. ?g i $ p i) ?U + setprod (\\<lambda>i. ?h i $ p i) ?U\"\n    unfolding kU[symmetric] .\n  then show \"of_int (sign p) * setprod (\\<lambda>i. ?f i $ p i) ?U =\n    of_int (sign p) * setprod (\\<lambda>i. ?g i $ p i) ?U + of_int (sign p) * setprod (\\<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 setsum_right_distrib\nproof (rule setsum.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: \"setprod (\\<lambda>i. ?f i $ p i) ?Uk = setprod (\\<lambda>i. ?g i $ p i) ?Uk\"\n    apply -\n    apply (rule setprod.cong)\n    apply simp_all\n    done\n  have th3: \"finite ?Uk\" \"k \\<notin> ?Uk\"\n    by auto\n  have \"setprod (\\<lambda>i. ?f i $ p i) ?U = setprod (\\<lambda>i. ?f i $ p i) (insert k ?Uk)\"\n    unfolding kU[symmetric] ..\n  also have \"\\<dots> = ?f k $ p k  * setprod (\\<lambda>i. ?f i $ p i) ?Uk\"\n    apply (rule setprod.insert)\n    apply simp\n    apply blast\n    done\n  also have \"\\<dots> = (c*s a k) $ p k * setprod (\\<lambda>i. ?f i $ p i) ?Uk\"\n    by (simp add: field_simps)\n  also have \"\\<dots> = c* (a k $ p k * setprod (\\<lambda>i. ?g i $ p i) ?Uk)\"\n    unfolding th1 by (simp add: ac_simps)\n  also have \"\\<dots> = c* (setprod (\\<lambda>i. ?g i $ p i) (insert k ?Uk))\"\n    unfolding setprod.insert[OF th3] by simp\n  finally have \"setprod (\\<lambda>i. ?f i $ p i) ?U = c* (setprod (\\<lambda>i. ?g i $ p i) ?U)\"\n    unfolding kU[symmetric] .\n  then show \"of_int (sign p) * setprod (\\<lambda>i. ?f i $ p i) ?U =\n    c * (of_int (sign p) * setprod (\\<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 {*\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*}\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 {* Multilinearity and the multiplication formula. *}\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_setsum:\n  assumes fS: \"finite S\"\n  shows \"det ((\\<chi> i. if i = k then setsum (a i) S else c i)::'a::comm_ring_1^'n^'n) =\n    setsum (\\<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 setsum.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 eq_id_iff[simp]: \"(\\<forall>x. f x = x) \\<longleftrightarrow> f = id\"\n  by auto\n\nlemma det_linear_rows_setsum_lemma:\n  assumes fS: \"finite S\"\n    and fT: \"finite T\"\n  shows \"det ((\\<chi> i. if i \\<in> T then setsum (a i) S else c i):: 'a::comm_ring_1^'n^'n) =\n    setsum (\\<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\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 `z \\<notin> T` 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 setsum (a i) S else c i) =\n    det (\\<chi> i. if i = z then setsum (a i) S else if i \\<in> T then setsum (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 setsum (a i) S else if i = z then a i j else c i))\"\n    unfolding det_linear_row_setsum[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 setsum (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 setsum.cartesian_product by blast\n  show ?case unfolding tha\n    using `z \\<notin> T`\n    by (intro setsum.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_setsum:\n  fixes S :: \"'n::finite set\"\n  assumes fS: \"finite S\"\n  shows \"det (\\<chi> i. setsum (a i) S) =\n    setsum (\\<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_setsum_lemma[OF fS, of \"UNIV :: 'n set\" a, unfolded th0, OF finite]\n  show ?thesis by simp\nqed\n\nlemma matrix_mul_setsum_alt:\n  fixes A B :: \"'a::comm_ring_1^'n^'n\"\n  shows \"A ** B = (\\<chi> i. setsum (\\<lambda>k. A$i$k *s B $ k) (UNIV :: 'n set))\"\n  by (vector matrix_matrix_mult_def setsum_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 \"(setsum (\\<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      (setsum (\\<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 setsum.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: \"setprod (\\<lambda>i. B$i$ q (inv p i)) ?U = setprod ((\\<lambda>i. B$i$ q (inv p i)) \\<circ> p) ?U\"\n        by (rule setprod_permute[OF p])\n      have thp: \"setprod (\\<lambda>i. (\\<chi> i. A$i$p i *s B$p i :: 'a^'n^'n) $i $ q i) ?U =\n        setprod (\\<lambda>i. A$i$p i) ?U * setprod (\\<lambda>i. B$i$ q (inv p i)) ?U\"\n        unfolding th001 setprod.distrib[symmetric] o_def permutes_inverses[OF p]\n        apply (rule setprod.cong[OF refl])\n        using permutes_in_image[OF q]\n        apply vector\n        done\n      show \"?s q * setprod (\\<lambda>i. (((\\<chi> i. A$i$p i *s B$p i) :: 'a^'n^'n)$i$q i)) ?U =\n        ?s p * (setprod (\\<lambda>i. A$i$p i) ?U) * (?s (q \\<circ> inv p) * setprod (\\<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: \"setsum (\\<lambda>f. det (\\<chi> i. A$i$f i *s B$f i)) ?PU = det A * det B\"\n    unfolding det_def setsum_product\n    by (rule setsum.cong [OF refl])\n  have \"det (A**B) = setsum (\\<lambda>f.  det (\\<chi> i. A $ i $ f i *s B $ f i)) ?F\"\n    unfolding matrix_mul_setsum_alt det_linear_rows_setsum[OF fU]\n    by simp\n  also have \"\\<dots> = setsum (\\<lambda>f. det (\\<chi> i. A$i$f i *s B$f i)) ?PU\"\n    using setsum.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 {* Relation to invertibility. *}\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: \"setsum (\\<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 = setsum (\\<lambda>j. (1/ c i) *s (c j *s row j A)) (?U - {i})\"\n      unfolding setsum.remove[OF fU iU] setsum_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_setsum)\n      apply simp\n      apply (rule ballI)\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 {* Cramer's rule. *}\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 setsum (\\<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_setsum)\n    apply (rule ballI)\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 setsum.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. setsum (\\<lambda>i. c i *s row i (transpose A)) ?U = setsum (\\<lambda>i. c i *s column i A) ?U\"\n    by (auto simp add: row_transpose intro: setsum.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 {* Orthogonality of a transformation and matrix. *}\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\", unfolded 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 setsum.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      unfolding orthogonal_matrix_def norm_eq orthogonal_transformation\n      unfolding 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 {* Linearity of scaling, and hence isometry, that preserves origin. *}\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 {* Hence another formulation of orthogonal transformation. *}\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_sub[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 {* Can extend an isometry from unit sphere. *}\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 {* Rotation, reflection, rotoinversion. *}\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 {* Explicit formulas for low dimensions. *}\n\nlemma setprod_neutral_const: \"setprod f {(1::nat)..1} = f 1\"\n  by (fact setprod_singleton_nat_seg)\n\nlemma setprod_2: \"setprod f {(1::nat)..2} = f 1 * f 2\"\n  by (simp add: eval_nat_numeral setprod_numseg mult.commute)\n\nlemma setprod_3: \"setprod f {(1::nat)..3} = f 1 * f 2 * f 3\"\n  by (simp add: eval_nat_numeral setprod_numseg mult.commute)\n\nlemma det_1: \"det (A::'a::comm_ring_1^1^1) = A$1$1\"\n  by (simp add: det_def 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 setsum_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 setsum_over_permutations_insert[OF f123]\n    unfolding setsum_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": "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/Determinants.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8175744761936437, "lm_q2_score": 0.8652240947405564, "lm_q1q2_score": 0.7073851360476299}}
{"text": "theory Quantifying_Lists\nimports\n  Main\nbegin\n\nfun alls :: \"('a \\<Rightarrow> bool) \\<Rightarrow> 'a list \\<Rightarrow> bool\" where\n\"alls _ Nil = True\" |\n\"alls f (x # xs) = (f x \\<and> alls f xs)\"\n\nfun exs :: \"('a \\<Rightarrow> bool) \\<Rightarrow> 'a list \\<Rightarrow> bool\" where\n\"exs _ Nil = False\" |\n\"exs f (x # xs) = (f x \\<or> exs f xs)\"\n\n\n\nlemma [simp]: \"alls P (xs @ ys) = (alls P xs \\<and> alls P ys)\"\nproof(induct xs)\n  case Nil\n  then show ?case \n    by simp\nnext\ncase (Cons a xs)\n  then show ?case by simp\nqed\n\nlemma \"alls P (rev xs) = alls P xs\"\nproof(induct xs)\ncase Nil\nthen show ?case by simp\nnext\n  case (Cons a xs)\n  then show ?case by auto\nqed\n\nlemma nex_all: \"\\<not>(\\<exists>x. P x) \\<equiv> \\<forall> x. \\<not>P x\"\n  by simp\n\n(* Disproven by counterexample\nlemma \"\\<exists>P Q xs. exs (\\<lambda>x. P x \\<and> Q x) xs \\<noteq> (exs P xs \\<and> exs Q xs)\"\nproof(rule ccontr)\n  assume \"\\<not>?thesis\"\n  then have \"\\<forall>P Q xs. \\<not>(exs (\\<lambda>x. P x \\<and> Q x) xs \\<noteq> (exs P xs \\<and> exs Q xs))\"\n    apply(simp only: nex_all) *)\n\nlemma \"exs P (map f xs) = exs (P o f) xs\"\n  by(induct xs, simp+)\n\nlemma [simp]: \"exs P (xs @ ys) = (exs P xs \\<or> exs P ys)\"\n  by(induct xs, auto)\n\nlemma \"exs P (rev xs) = exs P xs\"\nproof(induct xs)\ncase Nil\n  then show ?case by simp\nnext\ncase (Cons a xs)\n  then show ?case by(auto)\nqed\n\nlemma \"exs (\\<lambda>x. P x \\<or> Q x) xs = (exs P xs \\<or> exs Q xs)\"\nproof(induct xs)\ncase Nil\n  then show ?case by simp\nnext\n  case (Cons a xs)\n  then show ?case by auto\nqed\n\nlemma \"exs P xs = (\\<not>(\\<forall>x\\<in>set xs.\\<not>(P x)))\"\n  by(induct xs, auto)\n\nprimrec is_in :: \"'a \\<Rightarrow> 'a list \\<Rightarrow> bool\" where\n\"is_in _ Nil = False\" | \n\"is_in v (Cons x xs) = (if v = x then True else is_in v xs)\"\n\nlemma \"is_in a xs = exs (\\<lambda>x. x = a) xs\"\n  by(induct xs, auto)\n\nend", "meta": {"author": "bobismijnnaam", "repo": "IsabelleProjects", "sha": "ae777c98339ef2f47beeded297af16ee41ecb52d", "save_path": "github-repos/isabelle/bobismijnnaam-IsabelleProjects", "path": "github-repos/isabelle/bobismijnnaam-IsabelleProjects/IsabelleProjects-ae777c98339ef2f47beeded297af16ee41ecb52d/Quantifying_Lists.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240895276222, "lm_q2_score": 0.817574478416099, "lm_q1q2_score": 0.7073851337085898}}
{"text": "(*  Title:      ZF/Nat_ZF.thy\n    Author:     Lawrence C Paulson, Cambridge University Computer Laboratory\n    Copyright   1994  University of Cambridge\n*)\n\nsection\\<open>The Natural numbers As a Least Fixed Point\\<close>\n\ntheory Nat_ZF imports OrdQuant Bool begin\n\ndefinition\n  nat :: i  where\n    \"nat == lfp Inf (%X. {0} \\<union> {succ(i). i \\<in> X})\"\n\ndefinition\n  quasinat :: \"i => o\"  where\n    \"quasinat(n) == n=0 | (\\<exists>m. n = succ(m))\"\n\ndefinition\n  (*Has an unconditional succ case, which is used in \"recursor\" below.*)\n  nat_case :: \"[i, i=>i, i]=>i\"  where\n    \"nat_case a b k == THE y. k=0 & y=a | (\\<exists>x. k=succ(x) & y=b(x))\"\n\ndefinition\n  nat_rec :: \"[i, i, [i,i]=>i]=>i\"  where\n    \"nat_rec k a b ==\n          wfrec (Memrel nat) k (%n f. nat_case a (%m. b m (f`m)) n)\"\n\n  (*Internalized relations on the naturals*)\n\ndefinition\n  Le :: i  where\n    \"Le == {<x,y>:nat*nat. x \\<le> y}\"\n\ndefinition\n  Lt :: i  where\n    \"Lt == {<x, y>:nat*nat. x < y}\"\n\ndefinition\n  Ge :: i  where\n    \"Ge == {<x,y>:nat*nat. y \\<le> x}\"\n\ndefinition\n  Gt :: i  where\n    \"Gt == {<x,y>:nat*nat. y < x}\"\n\ndefinition\n  greater_than :: \"i=>i\"  where\n    \"greater_than(n) == {i \\<in> nat. n < i}\"\n\ntext\\<open>No need for a less-than operator: a natural number is its list of\npredecessors!\\<close>\n\n\nlemma nat_bnd_mono: \"bnd_mono Inf (%X. {0} \\<union> {succ(i). i \\<in> X})\"\napply (rule bnd_monoI)\napply (cut_tac infinity, blast, blast)\ndone\n\n(* @{term\"nat = {0} \\<union> {succ(x). x \\<in> nat}\"} *)\nlemmas nat_unfold = nat_bnd_mono [THEN nat_def [THEN def_lfp_unfold]]\n\n(** Type checking of 0 and successor **)\n\nlemma nat_0I [iff,TC]: \"0 \\<in> nat\"\napply (subst nat_unfold)\napply (rule singletonI [THEN UnI1])\ndone\n\nlemma nat_succI [intro!,TC]: \"n \\<in> nat ==> succ(n) \\<in> nat\"\napply (subst nat_unfold)\napply (erule RepFunI [THEN UnI2])\ndone\n\nlemma nat_1I [iff,TC]: \"1 \\<in> nat\"\nby (rule nat_0I [THEN nat_succI])\n\nlemma nat_2I [iff,TC]: \"2 \\<in> nat\"\nby (rule nat_1I [THEN nat_succI])\n\nlemma bool_subset_nat: \"bool \\<subseteq> nat\"\nby (blast elim!: boolE)\n\nlemmas bool_into_nat = bool_subset_nat [THEN subsetD]\n\n\nsubsection\\<open>Injectivity Properties and Induction\\<close>\n\n(*Mathematical induction*)\nlemma nat_induct [case_names 0 succ, induct set: nat]:\n    \"[| n \\<in> nat;  P(0);  !!x. [| x \\<in> nat;  P(x) |] ==> P(succ(x)) |] ==> P(n)\"\nby (erule def_induct [OF nat_def nat_bnd_mono], blast)\n\nlemma natE:\n assumes \"n \\<in> nat\"\n obtains (\"0\") \"n=0\" | (succ) x where \"x \\<in> nat\" \"n=succ(x)\"\nusing assms\nby (rule nat_unfold [THEN equalityD1, THEN subsetD, THEN UnE]) auto\n\nlemma nat_into_Ord [simp]: \"n \\<in> nat ==> Ord(n)\"\nby (erule nat_induct, auto)\n\n(* @{term\"i \\<in> nat ==> 0 \\<le> i\"}; same thing as @{term\"0<succ(i)\"}  *)\nlemmas nat_0_le = nat_into_Ord [THEN Ord_0_le]\n\n(* @{term\"i \\<in> nat ==> i \\<le> i\"}; same thing as @{term\"i<succ(i)\"}  *)\nlemmas nat_le_refl = nat_into_Ord [THEN le_refl]\n\nlemma Ord_nat [iff]: \"Ord(nat)\"\napply (rule OrdI)\napply (erule_tac [2] nat_into_Ord [THEN Ord_is_Transset])\napply (unfold Transset_def)\napply (rule ballI)\napply (erule nat_induct, auto)\ndone\n\nlemma Limit_nat [iff]: \"Limit(nat)\"\napply (unfold Limit_def)\napply (safe intro!: ltI Ord_nat)\napply (erule ltD)\ndone\n\nlemma naturals_not_limit: \"a \\<in> nat ==> ~ Limit(a)\"\nby (induct a rule: nat_induct, auto)\n\nlemma succ_natD: \"succ(i): nat ==> i \\<in> nat\"\nby (rule Ord_trans [OF succI1], auto)\n\nlemma nat_succ_iff [iff]: \"succ(n): nat \\<longleftrightarrow> n \\<in> nat\"\nby (blast dest!: succ_natD)\n\nlemma nat_le_Limit: \"Limit(i) ==> nat \\<le> i\"\napply (rule subset_imp_le)\napply (simp_all add: Limit_is_Ord)\napply (rule subsetI)\napply (erule nat_induct)\n apply (erule Limit_has_0 [THEN ltD])\napply (blast intro: Limit_has_succ [THEN ltD] ltI Limit_is_Ord)\ndone\n\n(* [| succ(i): k;  k \\<in> nat |] ==> i \\<in> k *)\nlemmas succ_in_naturalD = Ord_trans [OF succI1 _ nat_into_Ord]\n\nlemma lt_nat_in_nat: \"[| m<n;  n \\<in> nat |] ==> m \\<in> nat\"\napply (erule ltE)\napply (erule Ord_trans, assumption, simp)\ndone\n\nlemma le_in_nat: \"[| m \\<le> n; n \\<in> nat |] ==> m \\<in> nat\"\nby (blast dest!: lt_nat_in_nat)\n\n\nsubsection\\<open>Variations on Mathematical Induction\\<close>\n\n(*complete induction*)\n\nlemmas complete_induct = Ord_induct [OF _ Ord_nat, case_names less, consumes 1]\n\nlemmas complete_induct_rule =\n        complete_induct [rule_format, case_names less, consumes 1]\n\n\nlemma nat_induct_from_lemma [rule_format]:\n    \"[| n \\<in> nat;  m \\<in> nat;\n        !!x. [| x \\<in> nat;  m \\<le> x;  P(x) |] ==> P(succ(x)) |]\n     ==> m \\<le> n \\<longrightarrow> P(m) \\<longrightarrow> P(n)\"\napply (erule nat_induct)\napply (simp_all add: distrib_simps le0_iff le_succ_iff)\ndone\n\n(*Induction starting from m rather than 0*)\nlemma nat_induct_from:\n    \"[| m \\<le> n;  m \\<in> nat;  n \\<in> nat;\n        P(m);\n        !!x. [| x \\<in> nat;  m \\<le> x;  P(x) |] ==> P(succ(x)) |]\n     ==> P(n)\"\napply (blast intro: nat_induct_from_lemma)\ndone\n\n(*Induction suitable for subtraction and less-than*)\nlemma diff_induct [case_names 0 0_succ succ_succ, consumes 2]:\n    \"[| m \\<in> nat;  n \\<in> nat;\n        !!x. x \\<in> nat ==> P x 0;\n        !!y. y \\<in> nat ==> P 0 (succ y);\n        !!x y. [| x \\<in> nat;  y \\<in> nat;  P x y |] ==> P (succ x) (succ y) |]\n     ==> P m n\"\napply (erule_tac x = m in rev_bspec)\napply (erule nat_induct, simp)\napply (rule ballI)\napply (rename_tac i j)\napply (erule_tac n=j in nat_induct, auto)\ndone\n\n\n(** Induction principle analogous to trancl_induct **)\n\nlemma succ_lt_induct_lemma [rule_format]:\n     \"m \\<in> nat ==> P m (succ m) \\<longrightarrow> (\\<forall>x\\<in>nat. P m x \\<longrightarrow> P m (succ x)) \\<longrightarrow>\n                 (\\<forall>n\\<in>nat. m<n \\<longrightarrow> P m n)\"\napply (erule nat_induct)\n apply (intro impI, rule nat_induct [THEN ballI])\n   prefer 4 apply (intro impI, rule nat_induct [THEN ballI])\napply (auto simp add: le_iff)\ndone\n\nlemma succ_lt_induct:\n    \"[| m<n;  n \\<in> nat;\n        P m (succ m);\n        !!x. [| x \\<in> nat;  P m x |] ==> P m (succ x) |]\n     ==> P m n\"\nby (blast intro: succ_lt_induct_lemma lt_nat_in_nat)\n\nsubsection\\<open>quasinat: to allow a case-split rule for @{term nat_case}\\<close>\n\ntext\\<open>True if the argument is zero or any successor\\<close>\n\n\nlemma [iff]: \"quasinat(succ(x))\"\nby (simp add: quasinat_def)\n\nlemma nat_imp_quasinat: \"n \\<in> nat ==> quasinat(n)\"\nby (erule natE, simp_all)\n\nlemma non_nat_case: \"~ quasinat(x) ==> nat_case a b x = 0\"\nby (simp add: quasinat_def nat_case_def)\n\nlemma nat_cases_disj: \"k=0 | (\\<exists>y. k = succ(y)) | ~ quasinat(k)\"\napply (case_tac \"k=0\", simp)\napply (case_tac \"\\<exists>m. k = succ(m)\")\napply (simp_all add: quasinat_def)\ndone\n\nlemma nat_cases:\n     \"[|k=0 ==> P;  !!y. k = succ(y) ==> P; ~ quasinat(k) ==> P|] ==> P\"\nby (insert nat_cases_disj [of k], blast)\n\n(** nat_case **)\n\nlemma nat_case_0 [simp]: \"nat_case a b 0 = a\"\nby (simp add: nat_case_def)\n\nlemma nat_case_succ [simp]: \"nat_case a b (succ n) = b(n)\"\nby (simp add: nat_case_def)\n\nlemma nat_case_type [TC]:\n    \"[| n \\<in> nat;  a \\<in> C(0);  !!m. m \\<in> nat ==> b(m): C(succ(m)) |]\n     ==> nat_case a b n \\<in> C(n)\"\nby (erule nat_induct, auto)\n\nlemma split_nat_case:\n  \"P(nat_case a b k) \\<longleftrightarrow>\n   ((k=0 \\<longrightarrow> P(a)) & (\\<forall>x. k=succ(x) \\<longrightarrow> P(b(x))) & (~ quasinat(k) \\<longrightarrow> P(0)))\"\napply (rule nat_cases [of k])\napply (auto simp add: non_nat_case)\ndone\n\n\nsubsection\\<open>Recursion on the Natural Numbers\\<close>\n\n(** nat_rec is used to define eclose and transrec, then becomes obsolete.\n    The operator rec, from arith.thy, has fewer typing conditions **)\n\nlemma nat_rec_0: \"nat_rec 0 a b = a\"\napply (rule nat_rec_def [THEN def_wfrec, THEN trans])\n apply (rule wf_Memrel)\napply (rule nat_case_0)\ndone\n\nlemma nat_rec_succ: \"m \\<in> nat ==> nat_rec (succ m) a b = b m (nat_rec m a b)\"\napply (rule nat_rec_def [THEN def_wfrec, THEN trans])\n apply (rule wf_Memrel)\napply (simp add: vimage_singleton_iff)\ndone\n\n(** The union of two natural numbers is a natural number -- their maximum **)\n\nlemma Un_nat_type [TC]: \"[| i \\<in> nat; j \\<in> nat |] ==> i \\<union> j \\<in> nat\"\napply (rule Un_least_lt [THEN ltD])\napply (simp_all add: lt_def)\ndone\n\nlemma Int_nat_type [TC]: \"[| i \\<in> nat; j \\<in> nat |] ==> i \\<inter> j \\<in> nat\"\napply (rule Int_greatest_lt [THEN ltD])\napply (simp_all add: lt_def)\ndone\n\n(*needed to simplify unions over nat*)\nlemma nat_nonempty [simp]: \"nat \\<noteq> 0\"\nby blast\n\ntext\\<open>A natural number is the set of its predecessors\\<close>\nlemma nat_eq_Collect_lt: \"i \\<in> nat ==> {j\\<in>nat. j<i} = i\"\napply (rule equalityI)\napply (blast dest: ltD)\napply (auto simp add: Ord_mem_iff_lt)\napply (blast intro: lt_trans)\ndone\n\nlemma Le_iff [iff]: \"<x,y> \\<in> Le \\<longleftrightarrow> x \\<le> y & x \\<in> nat & y \\<in> nat\"\nby (force simp add: Le_def)\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/Nat_ZF.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8652240756264639, "lm_q2_score": 0.8175744828610095, "lm_q1q2_score": 0.7073851261892012}}
{"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.*)\n  theory TIP_prop_76\nimports \"../../Test_Base\"\nbegin\n\ndatatype 'a list = nil2 | cons2 \"'a\" \"'a list\"\n\ndatatype Nat = Z | S \"Nat\"\n\nfun y :: \"'a list => 'a list => 'a list\" where\n\"y (nil2) y2 = y2\"\n| \"y (cons2 z2 xs) y2 = cons2 z2 (y xs y2)\"\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 y22) = x x2 y22\"\n\nfun count :: \"Nat => Nat list => Nat\" where\n\"count z (nil2) = Z\"\n| \"count z (cons2 z2 ys) =\n     (if x z z2 then S (count z ys) else count z ys)\"\n\ntheorem property0 :\n  \"((~ (x n m)) ==>\n      ((count n (y xs (cons2 m (nil2)))) = (count n 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/Isaplanner/Isaplanner/TIP_prop_76.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952811593495, "lm_q2_score": 0.7879311906630568, "lm_q1q2_score": 0.7073221117364938}}
{"text": "theory Memory_Allocation_Model\nimports Main\nbegin\n\nsubsection \\<open>def of datetype\\<close>\n(*------------------------------------------------------------------------------------------------*)\ndatatype (set: 'a) tree = leaf: Leaf (L: 'a) |\n                          node: Node (LL:\"'a tree\") (LR:\"'a tree\") (RL:\"'a tree\") (RR:\"'a tree\")\n                        for map: tree_map   \n\ndatatype block_state_type = FREE | ALLOC\ntype_synonym ID = nat\ntype_synonym Block = \"(block_state_type \\<times> ID) tree\"\n\ntype_synonym poolname = \"string\"\nrecord Pool = zerolevelblocks :: \"Block set\"\n              pname :: poolname\n\nsubsection \\<open>def of 'a tree function\\<close>\n(*------------------------------------------------------------------------------------------------*)\ndefinition compare2 :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\"\n  where \"compare2 a b \\<equiv> (if a > b then a else b)\"\n\ndefinition compare4 :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> nat\"\n  where \"compare4 a b c d \\<equiv> (let c1 = compare2 a b;\n                                 c2 = compare2 c1 c in compare2 c2 d)\"\n\nfun get_level' :: \"'a tree \\<Rightarrow> 'a \\<Rightarrow> nat \\<Rightarrow> nat\"\n  where \"get_level' (Leaf x) b n = (if (x = b) then n else 0)\" |\n        \"get_level' (Node n1 n2 n3 n4) b n = compare4 (get_level' n1 b (Suc n))\n                                                      (get_level' n2 b (Suc n))\n                                                      (get_level' n3 b (Suc n))\n                                                      (get_level' n4 b (Suc n))\"\n\ndefinition get_level :: \"'a tree \\<Rightarrow> 'a \\<Rightarrow> nat\"\n  where \"get_level B b \\<equiv> get_level' B b 0\"\n\nlemma level_notbelong:\n  \"b \\<notin> set B \\<Longrightarrow>\n  get_level' B b lv = 0\"\nproof(induct B arbitrary: lv)\ncase (Leaf x)\n  then show ?case by auto\nnext\n  case (Node B1 B2 B3 B4)\n  have b1: \"b \\<notin> set B1\"\n    using Node.prems by auto \n  have b2: \"b \\<notin> set B2\"\n    using Node.prems by auto \n  have b3: \"b \\<notin> set B3\"\n    using Node.prems by auto \n  have b4: \"b \\<notin> set B4\"\n    using Node.prems by auto \n  have l_node': \"get_level' (Node B1 B2 B3 B4) b lv =\n                compare4 (get_level' B1 b (Suc lv))\n                         (get_level' B2 b (Suc lv))\n                         (get_level' B3 b (Suc lv))\n                         (get_level' B4 b (Suc lv))\"\n    using get_level'.simps(2) by auto\n  have l1: \"get_level' B1 b (Suc lv) = 0\"\n    using Node.hyps(1) b1 by auto \n  have l2: \"get_level' B2 b (Suc lv) = 0\"\n    using Node.hyps(2) b2 by auto \n  have l3: \"get_level' B3 b (Suc lv) = 0\"\n    using Node.hyps(3) b3 by auto \n  have l4: \"get_level' B4 b (Suc lv) = 0\"\n    using Node.hyps(4) b4 by auto \n  have l_node: \"compare4 (get_level' B1 b (Suc lv))\n                         (get_level' B2 b (Suc lv))\n                         (get_level' B3 b (Suc lv))\n                         (get_level' B4 b (Suc lv)) = 0\"\n    unfolding compare4_def Let_def compare2_def l1 l2 l3 l4 by auto\n  show ?case using l_node' l_node by auto\nqed\n\nfun get_level_node' :: \"'a tree \\<Rightarrow> 'a tree \\<Rightarrow> nat \\<Rightarrow> nat\"\n  where \"get_level_node' (Leaf x) b n = (if leaf b \\<and> (L b) = x then n else 0)\" |\n        \"get_level_node' (Node n1 n2 n3 n4) b n = (if (Node n1 n2 n3 n4) = b then n\n                                                  else compare4 (get_level_node' n1 b (Suc n))\n                                                                (get_level_node' n2 b (Suc n))\n                                                                (get_level_node' n3 b (Suc n))\n                                                                (get_level_node' n4 b (Suc n)))\"\n\ndefinition get_level_node :: \"'a tree \\<Rightarrow> 'a tree \\<Rightarrow> nat\"\n  where \"get_level_node B b \\<equiv> get_level_node' B b 0\"\n\nlemma level_node_notbelong:\n  \"leaf b \\<Longrightarrow>\n  L b \\<notin> set B \\<Longrightarrow>\n  get_level_node' B b lv = 0\"\nproof(induct B arbitrary: lv)\ncase (Leaf x)\n  then show ?case by auto\nnext\n  case (Node B1 B2 B3 B4)\n  have b1: \"L b \\<notin> set B1\"\n    using Node.prems by auto \n  have b2: \"L b \\<notin> set B2\"\n    using Node.prems by auto \n  have b3: \"L b \\<notin> set B3\"\n    using Node.prems by auto \n  have b4: \"L b \\<notin> set B4\"\n    using Node.prems by auto \n  have node_not_l: \"Node B1 B2 B3 B4 \\<noteq> b\"\n    using Node.prems(1) by auto\n  have l_node': \"get_level_node' (Node B1 B2 B3 B4) b lv =\n                compare4 (get_level_node' B1 b (Suc lv))\n                         (get_level_node' B2 b (Suc lv))\n                         (get_level_node' B3 b (Suc lv))\n                         (get_level_node' B4 b (Suc lv))\"\n    using get_level_node'.simps(2) node_not_l by auto\n  have l1: \"get_level_node' B1 b (Suc lv) = 0\"\n    using Node.hyps(1) Node.prems(1) b1 by auto \n  have l2: \"get_level_node' B2 b (Suc lv) = 0\"\n    using Node.hyps(2) Node.prems(1) b2 by auto \n  have l3: \"get_level_node' B3 b (Suc lv) = 0\"\n    using Node.hyps(3) Node.prems(1) b3 by auto \n  have l4: \"get_level_node' B4 b (Suc lv) = 0\"\n    using Node.hyps(4) Node.prems(1) b4 by auto\n  have l_node: \"compare4 (get_level_node' B1 b (Suc lv))\n                         (get_level_node' B2 b (Suc lv))\n                         (get_level_node' B3 b (Suc lv))\n                         (get_level_node' B4 b (Suc lv)) = 0\"\n    unfolding compare4_def Let_def compare2_def using l1 l2 l3 l4 by auto\n  show ?case using l_node' l_node by auto\nqed\n\nlemma level_node_notbelong2:\n  \"node b \\<Longrightarrow>\n  \\<not> tree.set b \\<subseteq> tree.set B \\<Longrightarrow>\n  get_level_node' B b lv = 0\"\nproof(induct B arbitrary: lv)\n  case (Leaf x)\n  show ?case using Leaf.prems(1) by auto\nnext\n  case (Node B1 B2 B3 B4)\n  have not_eq: \"b \\<noteq> Node B1 B2 B3 B4\"\n    using Node.prems(2) by blast \n  have b1: \"\\<not> tree.set b \\<subseteq> tree.set B1\"\n    using Node.prems(2) dual_order.trans by auto\n  have b2: \"\\<not> tree.set b \\<subseteq> tree.set B2\"\n    using Node.prems(2) dual_order.trans by auto\n  have b3: \"\\<not> tree.set b \\<subseteq> tree.set B3\"\n    using Node.prems(2) dual_order.trans by auto\n  have b4: \"\\<not> tree.set b \\<subseteq> tree.set B4\"\n    using Node.prems(2) dual_order.trans by auto\n  have l1: \"get_level_node' B1 b (Suc lv) = 0\"\n    using Node.hyps(1) Node.prems(1) b1 by auto\n  have l2: \"get_level_node' B2 b (Suc lv) = 0\"\n    using Node.hyps(2) Node.prems(1) b2 by auto\n  have l3: \"get_level_node' B3 b (Suc lv) = 0\"\n    using Node.hyps(3) Node.prems(1) b3 by auto\n  have l4: \"get_level_node' B4 b (Suc lv) = 0\"\n    using Node.hyps(4) Node.prems(1) b4 by auto\n  have l_node': \"get_level_node' (Node B1 B2 B3 B4) b lv =\n                compare4 (get_level_node' B1 b (Suc lv))\n                         (get_level_node' B2 b (Suc lv))\n                         (get_level_node' B3 b (Suc lv))\n                         (get_level_node' B4 b (Suc lv))\"\n    using get_level_node'.simps(2) not_eq by auto\n  have l_node: \"compare4 (get_level_node' B1 b (Suc lv))\n                         (get_level_node' B2 b (Suc lv))\n                         (get_level_node' B3 b (Suc lv))\n                         (get_level_node' B4 b (Suc lv)) = 0\"\n    unfolding compare4_def Let_def compare2_def using l1 l2 l3 l4 by auto\n  then show ?case using l_node' l_node by auto\nqed\n\nsubsection \\<open>def of function_call\\<close>\n(*------------------------------------------------------------------------------------------------*)\ndefinition getnewid :: \"ID set \\<Rightarrow> (ID \\<times> ID \\<times> ID \\<times> ID \\<times> ID set)\"\n  where \"getnewid ids \\<equiv> let nid1 = SOME p1. p1 \\<notin> ids;\n                            ids1 = ids \\<union> {nid1};\n                            nid2 = SOME p2. p2 \\<notin> ids1;\n                            ids2 = ids1 \\<union> {nid2};\n                            nid3 = SOME p3. p3 \\<notin> ids2;\n                            ids3 = ids2 \\<union> {nid3};\n                            nid4 = SOME p4. p4 \\<notin> ids3;\n                            ids4 = ids3 \\<union> {nid4} in\n                        (nid1, nid2, nid3, nid4, ids4)\"\n\nlemma getnewid_inc: \"ids \\<subseteq> snd(snd(snd(snd(getnewid ids))))\"\n  unfolding getnewid_def Let_def by auto\n\nlemma newid1_in_getnewid: \"fst(getnewid ids) \\<in> snd(snd(snd(snd(getnewid ids))))\"\n  unfolding getnewid_def Let_def by auto\n\nlemma newid2_in_getnewid: \"fst(snd(getnewid ids)) \\<in> snd(snd(snd(snd(getnewid ids))))\"\n  unfolding getnewid_def Let_def by auto\n\nlemma newid3_in_getnewid: \"fst(snd(snd(getnewid ids))) \\<in> snd(snd(snd(snd(getnewid ids))))\"\n  unfolding getnewid_def Let_def by auto\n\nlemma newid4_in_getnewid: \"fst(snd(snd(snd(getnewid ids)))) \\<in> snd(snd(snd(snd(getnewid ids))))\"\n  unfolding getnewid_def Let_def by auto\n\nlemma exists_p_getnewid:\n  \"\\<exists>xa xb xc xd. getnewid ids = (xa, xb, xc, xd, ids \\<union> {xa, xb, xc, xd})\"\n  unfolding getnewid_def Let_def by auto\n\nlemma getnewid_diffab:\n  \"finite ids \\<Longrightarrow>\n  newid = getnewid ids \\<Longrightarrow>\n  xa = fst newid \\<Longrightarrow>\n  xb = fst (snd newid) \\<Longrightarrow>\n  xc = fst (snd (snd newid)) \\<Longrightarrow>\n  xd = fst (snd (snd (snd newid))) \\<Longrightarrow>\n  xa \\<noteq> xb\"\n  unfolding getnewid_def Let_def\n  apply auto\n  by (metis (mono_tags, lifting) add.left_neutral finite_nat_set_iff_bounded lessI not_add_less2 plus_nat.simps(2) someI_ex)\n\nlemma getnewid_diffac:\n  \"finite ids \\<Longrightarrow>\n  newid = getnewid ids \\<Longrightarrow>\n  xa = fst newid \\<Longrightarrow>\n  xb = fst (snd newid) \\<Longrightarrow>\n  xc = fst (snd (snd newid)) \\<Longrightarrow>\n  xd = fst (snd (snd (snd newid))) \\<Longrightarrow>\n  xa \\<noteq> xc\"\n  unfolding getnewid_def Let_def\n  apply auto\n  by (smt ex_new_if_finite finite.insertI infinite_UNIV_nat insertCI some_eq_ex someI_ex)\n\nlemma getnewid_diffad:\n  \"finite ids \\<Longrightarrow>\n  newid = getnewid ids \\<Longrightarrow>\n  xa = fst newid \\<Longrightarrow>\n  xb = fst (snd newid) \\<Longrightarrow>\n  xc = fst (snd (snd newid)) \\<Longrightarrow>\n  xd = fst (snd (snd (snd newid))) \\<Longrightarrow>\n  xa \\<noteq> xd\"\n  unfolding getnewid_def Let_def\n  apply auto\n  by (smt ex_new_if_finite finite.insertI infinite_UNIV_nat insertCI some_eq_ex someI_ex)\n\nlemma getnewid_diffbc:\n  \"finite ids \\<Longrightarrow>\n  newid = getnewid ids \\<Longrightarrow>\n  xa = fst newid \\<Longrightarrow>\n  xb = fst (snd newid) \\<Longrightarrow>\n  xc = fst (snd (snd newid)) \\<Longrightarrow>\n  xd = fst (snd (snd (snd newid))) \\<Longrightarrow>\n  xb \\<noteq> xc\"\n  unfolding getnewid_def Let_def\n  apply auto\n  by (smt ex_new_if_finite finite.insertI infinite_UNIV_nat insertCI some_eq_ex someI_ex)\n\nlemma getnewid_diffbd:\n  \"finite ids \\<Longrightarrow>\n  newid = getnewid ids \\<Longrightarrow>\n  xa = fst newid \\<Longrightarrow>\n  xb = fst (snd newid) \\<Longrightarrow>\n  xc = fst (snd (snd newid)) \\<Longrightarrow>\n  xd = fst (snd (snd (snd newid))) \\<Longrightarrow>\n  xb \\<noteq> xd\"\n  unfolding getnewid_def Let_def\n  apply auto\n  by (smt ex_new_if_finite finite.insertI infinite_UNIV_nat insertCI some_eq_ex someI_ex)\n\nlemma getnewid_diffcd:\n  \"finite ids \\<Longrightarrow>\n  newid = getnewid ids \\<Longrightarrow>\n  xa = fst newid \\<Longrightarrow>\n  xb = fst (snd newid) \\<Longrightarrow>\n  xc = fst (snd (snd newid)) \\<Longrightarrow>\n  xd = fst (snd (snd (snd newid))) \\<Longrightarrow>\n  xc \\<noteq> xd\"\n  unfolding getnewid_def Let_def\n  apply auto\n  by (smt ex_new_if_finite finite.insertI infinite_UNIV_nat insertCI some_eq_ex someI_ex)\n\nlemma getnewid_diff1:\n  \"finite ids \\<Longrightarrow>\n  xa = fst (getnewid ids) \\<Longrightarrow>\n  xb = fst (snd (getnewid ids)) \\<Longrightarrow>\n  xc = fst (snd (snd (getnewid ids))) \\<Longrightarrow>\n  xd = fst (snd (snd (snd (getnewid ids)))) \\<Longrightarrow>\n  xa \\<noteq> xb \\<and> xa \\<noteq> xc \\<and> xa \\<noteq> xd\"\n  by (meson getnewid_diffab getnewid_diffac getnewid_diffad)\n\nlemma getnewid_diff2:\n  \"finite ids \\<Longrightarrow>\n  xa = fst (getnewid ids) \\<Longrightarrow>\n  xb = fst (snd (getnewid ids)) \\<Longrightarrow>\n  xc = fst (snd (snd (getnewid ids))) \\<Longrightarrow>\n  xd = fst (snd (snd (snd (getnewid ids)))) \\<Longrightarrow>\n  xb \\<noteq> xc \\<and> xb \\<noteq> xd \\<and> xc \\<noteq> xd\"\n  by (meson getnewid_diffbc getnewid_diffbd getnewid_diffcd)\n\nlemma getnewid_anot:\n  \"finite ids \\<Longrightarrow>\n  newid = getnewid ids \\<Longrightarrow>\n  xa = fst newid \\<Longrightarrow>\n  xb = fst (snd newid) \\<Longrightarrow>\n  xc = fst (snd (snd newid)) \\<Longrightarrow>\n  xd = fst (snd (snd (snd newid))) \\<Longrightarrow>\n  xa \\<notin> ids\"\n  unfolding getnewid_def Let_def\n  apply auto\n  by (metis Collect_mem_eq finite_Collect_not infinite_UNIV_nat not_finite_existsD someI_ex)\n\nlemma getnewid_bnot:\n  \"finite ids \\<Longrightarrow>\n  newid = getnewid ids \\<Longrightarrow>\n  xa = fst newid \\<Longrightarrow>\n  xb = fst (snd newid) \\<Longrightarrow>\n  xc = fst (snd (snd newid)) \\<Longrightarrow>\n  xd = fst (snd (snd (snd newid))) \\<Longrightarrow>\n  xb \\<notin> ids\"\n  unfolding getnewid_def Let_def\n  apply auto\n  by (metis (mono_tags, lifting) finite_nat_set_iff_bounded lessI less_irrefl not_add_less2 plus_nat.simps(2) someI_ex)\n\nlemma getnewid_cnot:\n  \"finite ids \\<Longrightarrow>\n  newid = getnewid ids \\<Longrightarrow>\n  xa = fst newid \\<Longrightarrow>\n  xb = fst (snd newid) \\<Longrightarrow>\n  xc = fst (snd (snd newid)) \\<Longrightarrow>\n  xd = fst (snd (snd (snd newid))) \\<Longrightarrow>\n  xc \\<notin> ids\"\n  unfolding getnewid_def Let_def\n  apply auto\n  by (smt finite.insertI finite_nat_set_iff_bounded insert_compr less_irrefl mem_Collect_eq someI_ex)\n\nlemma getnewid_dnot:\n  \"finite ids \\<Longrightarrow>\n  newid = getnewid ids \\<Longrightarrow>\n  xa = fst newid \\<Longrightarrow>\n  xb = fst (snd newid) \\<Longrightarrow>\n  xc = fst (snd (snd newid)) \\<Longrightarrow>\n  xd = fst (snd (snd (snd newid))) \\<Longrightarrow>\n  xd \\<notin> ids\"\n  unfolding getnewid_def Let_def\n  apply auto\n  by (smt ball_empty empty_Collect_eq ex_new_if_finite finite.insertI infinite_UNIV_nat insert_compr mem_Collect_eq some_eq_ex)\n\nlemma getnewid_notbelong:\n  \"finite ids \\<Longrightarrow>\n  xa = fst (getnewid ids) \\<Longrightarrow>\n  xb = fst (snd (getnewid ids)) \\<Longrightarrow>\n  xc = fst (snd (snd (getnewid ids))) \\<Longrightarrow>\n  xd = fst (snd (snd (snd (getnewid ids)))) \\<Longrightarrow>\n  xa \\<notin> ids \\<and> xb \\<notin> ids \\<and> xc \\<notin> ids \\<and> xd \\<notin> ids\"\n  by (simp add: getnewid_anot getnewid_bnot getnewid_cnot getnewid_dnot)\n\ndefinition divide :: \"Block \\<Rightarrow> ID set \\<Rightarrow> (Block \\<times> ID set)\"\n  where \"divide bl ids \\<equiv>\n         (let b = L bl;\n              nids = getnewid ids;\n              x1 = fst nids;\n              x2 = fst (snd nids);\n              x3 = fst (snd (snd nids));\n              x4 = fst (snd (snd (snd nids)));\n              newids = snd (snd (snd (snd nids))) in                              \n         (Node (Leaf (ALLOC, x1)) (Leaf (FREE, x2)) (Leaf (FREE, x3)) (Leaf (FREE, x4)), newids))\"\n\nlemma divide_diff:\n  \"finite ids \\<Longrightarrow>\n  fst (divide b ids) = Node (Leaf ll) (Leaf lr) (Leaf rl) (Leaf rr) \\<Longrightarrow>\n  snd ll \\<noteq> snd lr \\<and> snd ll \\<noteq> snd rl \\<and> snd ll \\<noteq> snd rr\"\n  unfolding divide_def Let_def using getnewid_diff1 by auto\n\nlemma divide_diff2:\n  \"finite ids \\<Longrightarrow>\n  fst (divide b ids) = Node (Leaf ll) (Leaf lr) (Leaf rl) (Leaf rr) \\<Longrightarrow>\n  snd lr \\<noteq> snd rl \\<and> snd lr \\<noteq> snd rr \\<and> snd rl \\<noteq> snd rr\"\n  unfolding divide_def Let_def using getnewid_diff2 by auto\n\nlemma divide_belong:\n  \"fst (divide b ids) = Node (Leaf ll) (Leaf lr) (Leaf rl) (Leaf rr) \\<Longrightarrow>\n  snd ll \\<in> snd (divide b ids) \\<and>\n  snd lr \\<in> snd (divide b ids) \\<and>\n  snd rl \\<in> snd (divide b ids) \\<and>\n  snd rr \\<in> snd (divide b ids)\"\n  unfolding divide_def Let_def\n  using newid1_in_getnewid newid2_in_getnewid newid3_in_getnewid newid4_in_getnewid by auto\n\nlemma divide_notbelong:\n  \"finite ids \\<Longrightarrow>\n  fst (divide b ids) = Node (Leaf ll) (Leaf lr) (Leaf rl) (Leaf rr) \\<Longrightarrow>\n  snd ll \\<notin> ids \\<and> snd lr \\<notin> ids \\<and> snd rl \\<notin> ids \\<and> snd rr \\<notin> ids\"\n  unfolding divide_def Let_def using getnewid_notbelong by auto\n\nlemma divide_finite:\n  \"finite ids \\<Longrightarrow>\n  finite (snd (divide b ids))\"\nproof-\n  assume a0: \"finite ids\"\n  have p0: \"snd (divide b ids) = snd (snd (snd (snd (getnewid ids))))\"\n    unfolding divide_def Let_def by auto\n  obtain xa xb xc xd\n    where obtain_divide: \"snd (divide b ids) = ids \\<union> {xa, xb, xc, xd}\"\n    using p0 exists_p_getnewid by (metis sndI)\n  have \"finite (ids \\<union> {xa, xb, xc, xd})\" using a0 by auto\n  then show ?thesis using obtain_divide by auto\nqed\n\ndefinition getnewid2 :: \"ID set \\<Rightarrow> (ID \\<times> ID set)\"\n  where \"getnewid2 ids \\<equiv> let nid = SOME p. p \\<notin> ids;\n                             nids = ids \\<union> {nid} in\n                             (nid, nids)\"\n\nlemma getnewid2_inc: \"ids \\<subseteq> snd(getnewid2 ids)\"\n  unfolding getnewid2_def Let_def by auto\n\nlemma newid_in_getnewid2: \"fst(getnewid2 ids) \\<in> snd(getnewid2 ids)\"\n  unfolding getnewid2_def Let_def by auto\n\nlemma exists_p_getnewid2: \"\\<exists>p. getnewid2 ids = (p, ids \\<union> {p})\"\n  unfolding getnewid2_def by metis\n\nlemma getnewid2_anot:\n  \"finite ids \\<Longrightarrow>\n  xa = fst (getnewid2 ids) \\<Longrightarrow>\n  xa \\<notin> ids\"\n  unfolding getnewid2_def Let_def\n  apply auto\n  by (metis Collect_mem_eq finite_Collect_not infinite_UNIV_char_0 not_finite_existsD someI_ex)\n\ndefinition combine :: \"Block \\<Rightarrow> ID set \\<Rightarrow> (Block \\<times> ID set)\"\n  where \"combine b ids \\<equiv> (if (\\<exists>a1 a2 a3 a4. b = Node (Leaf (FREE, a1)) (Leaf (FREE, a2)) (Leaf (FREE, a3)) (Leaf (FREE, a4))) then\n                              let nids = getnewid2 ids;\n                                  newid = fst nids;\n                                  newids = snd nids in (Leaf (FREE, newid), newids)\n                           else (b, ids))\"\n\nlemma combine_ids:\n  \"ids \\<subseteq> snd (combine b ids)\"\n  unfolding combine_def Let_def\n  using getnewid2_inc by auto\n\nlemma combine_finite:\n  \"finite ids \\<Longrightarrow>\n  finite (snd (combine b ids))\"\n  unfolding combine_def Let_def apply auto\n  using exists_p_getnewid2 snd_conv\n  by (metis Un_insert_right finite_insert sup_bot.right_neutral)\n\ndefinition freesets :: \"Block \\<Rightarrow> Block set\"\n  where \"freesets b = {l. leaf l \\<and> L l \\<in> set b \\<and> fst (L l) = FREE}\"\n\ndefinition freesets_level :: \"Block \\<Rightarrow> nat \\<Rightarrow> Block set\"\n  where \"freesets_level b lv = {l. l \\<in> freesets b \\<and> get_level b (L l) = lv}\"\n\ndefinition freesets_level_pool :: \"Block set \\<Rightarrow> nat \\<Rightarrow> Block set\"\n  where \"freesets_level_pool bset lv = {l. \\<exists>b \\<in> bset. l \\<in> freesets_level b lv}\"\n\ndefinition freesets_maxlevel :: \"Block set \\<Rightarrow> nat \\<Rightarrow> nat\"\n  where \"freesets_maxlevel bset lv \\<equiv>\n          THE lmax. lmax \\<le> lv \\<and>\n                    freesets_level_pool bset lmax \\<noteq> {} \\<and>\n                    (\\<forall>l. l \\<le> lv \\<and> freesets_level_pool bset l \\<noteq> {} \\<longrightarrow> l \\<le> lmax)\"\n\ndefinition exists_freelevel :: \"Block set \\<Rightarrow> nat \\<Rightarrow> bool\"\n  where \"exists_freelevel bset lv \\<equiv> \\<exists>lv'. lv' \\<le> lv \\<and> freesets_level_pool bset lv' \\<noteq> {}\"\n\nlemma exist_lmax_h:\n  \"freesets_level_pool bset lv = {} \\<Longrightarrow>\n  \\<exists>lv'. lv' < lv \\<and> freesets_level_pool bset lv' \\<noteq> {} \\<Longrightarrow>\n  \\<exists>lmax. lmax < lv \\<and>\n         freesets_level_pool bset lmax \\<noteq> {} \\<and>\n         (\\<forall>l. l \\<le> lv \\<and> l > lmax \\<longrightarrow> freesets_level_pool bset l = {})\"\nproof(induct lv)\n  case 0\n  then show ?case by auto\nnext\n  case (Suc xa)\n  then show ?case\n    by (smt Suc_leI Suc_le_lessD le_Suc_eq lessI not_less)\nqed\n\nlemma exist_lmax:\n  \"exists_freelevel bset lv \\<Longrightarrow>\n  \\<exists>!lmax. lmax \\<le> lv \\<and>\n          freesets_level_pool bset lmax \\<noteq> {} \\<and>\n          (\\<forall>l. l \\<le> lv \\<and> freesets_level_pool bset l \\<noteq> {} \\<longrightarrow> l \\<le> lmax)\"\nproof-\n  assume exi_level: \"exists_freelevel bset lv\"\n  hence exi_level_def: \"\\<exists>lv'. lv' \\<le> lv \\<and> freesets_level_pool bset lv' \\<noteq> {}\"\n    unfolding exists_freelevel_def by auto\n  {assume a0: \"freesets_level_pool bset lv \\<noteq> {}\"\n    hence \"lv \\<le> lv \\<and>\n          freesets_level_pool bset lv \\<noteq> {} \\<and>\n          (\\<forall>l. l \\<le> lv \\<and> freesets_level_pool bset l \\<noteq> {} \\<longrightarrow> l \\<le> lv)\"\n      using exi_level_def by auto\n    then have ?thesis using le_antisym by blast\n  }moreover\n  {assume a1: \"freesets_level_pool bset lv = {}\"\n    hence exi_level_less: \"\\<exists>lv'. lv' < lv \\<and> freesets_level_pool bset lv' \\<noteq> {}\"\n      using exi_level_def le_neq_implies_less by blast\n    have \"\\<exists>lmax. lmax < lv \\<and>\n                 freesets_level_pool bset lmax \\<noteq> {} \\<and>\n                 (\\<forall>l. l \\<le> lv \\<and> l > lmax \\<longrightarrow> freesets_level_pool bset l = {})\"\n      using exist_lmax_h a1 exi_level_less by auto\n    then obtain lmax where exi_lmax:\n      \"lmax < lv \\<and>\n      freesets_level_pool bset lmax \\<noteq> {} \\<and>\n      (\\<forall>l. l \\<le> lv \\<and> l > lmax \\<longrightarrow> freesets_level_pool bset l = {})\" by auto\n    then have \"\\<forall>l. l \\<le> lv \\<and> freesets_level_pool bset l \\<noteq> {} \\<longrightarrow> l \\<le> lmax\"\n      using a1 by (metis le_less_linear)\n    then have ?thesis using exi_lmax\n      by (meson le_less_Suc_eq le_simps(2) less_imp_le_nat)\n  }\n  ultimately have ?thesis by linarith\n  then show ?thesis by auto\nqed\n\nsubsection \\<open>def of sub core function\\<close>\n(*------------------------------------------------------------------------------------------------*)\ndefinition set_state_type :: \"Block \\<Rightarrow> block_state_type \\<Rightarrow> Block\"\n  where \"set_state_type bl t \\<equiv> (let b = (L bl) in Leaf (t, snd b))\"\n\ndefinition replace :: \"Block \\<Rightarrow> Block \\<Rightarrow> Block \\<Rightarrow> Block\"\n  where \"replace B b b' \\<equiv> (tree_map (\\<lambda>b1. if (b1 = L b) then (L b') else b1) B)\"\n\nlemma no_replace:\n  \"L b \\<notin> set blo \\<Longrightarrow>\n  b' = set_state_type b t \\<Longrightarrow>\n  tree_map (\\<lambda>b1. if b1 = L b then L b' else b1) blo = blo\"\n  by (smt tree.map_cong0 tree.map_ident)\n\nfun split :: \"Block \\<Rightarrow> ID set \\<Rightarrow> nat \\<Rightarrow> (Block \\<times> ID set \\<times> ID)\"\n  where \"split b ids lv = (if lv = 0 then (b, ids, snd (L b))\n                          else\n                            let re = divide b ids;\n                                node = fst re;\n                                newids = snd re;\n                                c1 = split (LL node) newids (lv - 1) in\n                                (Node (fst c1) (LR node) (RL node) (RR node), fst (snd c1), snd (snd c1)))\"\n\nlemma split_induct:\n  \"lv > 0 \\<Longrightarrow>\n  fst (divide b ids) = Node (Leaf ll) (Leaf lr) (Leaf rl) (Leaf rr) \\<Longrightarrow>\n  newids = snd (divide b ids) \\<Longrightarrow>\n  fst (split b ids lv) = Node (fst (split (Leaf ll) newids (lv - 1))) (Leaf lr) (Leaf rl) (Leaf rr)\"\n  using split.simps unfolding Let_def\n  by (metis fst_conv less_not_refl3 tree.sel(2) tree.sel(3) tree.sel(4) tree.sel(5))\n\nfun replace_leaf :: \"Block \\<Rightarrow> Block \\<Rightarrow> Block \\<Rightarrow> Block\"\n  where \"replace_leaf (Leaf x) y st = (if (x = (L y)) then st else (Leaf x))\" |\n        \"replace_leaf (Node n1 n2 n3 n4) y st = Node (replace_leaf n1 y st)\n                                                     (replace_leaf n2 y st)\n                                                     (replace_leaf n3 y st)\n                                                     (replace_leaf n4 y st)\"\n\nlemma no_replace_leaf:\n  \"(L b) \\<notin> set B \\<Longrightarrow>\n  replace_leaf B b subbtr = B\"\n  apply(induct B)\n  by auto\n\nlemma replace_leaf_belong:\n  \"(L b) \\<in> set B \\<Longrightarrow>\n  (L l) \\<in> set subbtr \\<Longrightarrow>\n  (L l) \\<in> set (replace_leaf B b subbtr)\"\n  apply(induct B)\n  by auto\n\nlemma replace_subbtr_belong:\n  \"(L b) \\<in> set B \\<Longrightarrow>\n  tree.set subbtr \\<subseteq> tree.set (replace_leaf B b subbtr)\"\n  apply(induct B)\n  by auto\n\nfun merge :: \"Block \\<Rightarrow> ID set \\<Rightarrow> (Block \\<times> ID set)\"\n  where \"merge (Leaf v) ids = ((Leaf v), ids)\" |\n        \"merge (Node ll lr rl rr) ids =\n                (if (\\<exists>xa xb xc xd. (Node ll lr rl rr) = Node (Leaf (FREE, xa))\n                                                             (Leaf (FREE, xb))\n                                                             (Leaf (FREE, xc))\n                                                             (Leaf (FREE, xd)))\n                 then combine (Node ll lr rl rr) ids\n                 else\n                    let m1 = merge ll ids;\n                        m2 = merge lr (snd m1);\n                        m3 = merge rl (snd m2);\n                        m4 = merge rr (snd m3) in\n                    combine (Node (fst m1) (fst m2) (fst m3) (fst m4)) (snd m4))\"\n\ndefinition alloc1 :: \"Block set \\<Rightarrow> nat \\<Rightarrow> ID set \\<Rightarrow> (Block set \\<times> ID set \\<times> bool \\<times> ID set)\"\n  where \"alloc1 bset lv ids \\<equiv> (let blo = (SOME b. b \\<in> bset \\<and> freesets_level b lv \\<noteq> {});\n                                   b = (SOME l. l \\<in> freesets_level blo lv);\n                                   allocid = snd (L b);\n                                   newblo = replace blo b (set_state_type b ALLOC) in\n                              ((bset - {blo}) \\<union> {newblo}, ids, True, {allocid}))\"\n\ndefinition alloc :: \"Block set \\<Rightarrow> nat \\<Rightarrow> ID set \\<Rightarrow> (Block set \\<times> ID set \\<times> bool \\<times> ID set)\"\n  where \"alloc bset lv ids \\<equiv>\n         if (exists_freelevel bset lv) then\n            let lmax = freesets_maxlevel bset lv in\n                if lmax = lv then\n                   alloc1 bset lv ids\n                else\n                   let blo = (SOME b. b \\<in> bset \\<and> freesets_level b lmax \\<noteq> {});\n                       b = (SOME l. l \\<in> freesets_level blo lmax);\n                       re = split b ids (lv - lmax);\n                       subbtr = fst re;\n                       newids = fst (snd re);\n                       allocid = snd (snd re);\n                       newbtr = replace_leaf blo b subbtr in\n                   (((bset - {blo}) \\<union> {newbtr}), newids, True, {allocid})\n         else (bset, ids, False, {})\"\n\ndefinition free :: \"Block set \\<Rightarrow> Block \\<Rightarrow> ID set \\<Rightarrow> (Block set \\<times> ID set \\<times> bool)\"\n  where \"free bset b ids \\<equiv>\n         if (\\<exists>btree \\<in> bset. (L b) \\<in> set btree) then\n            if fst (L b) = FREE then\n                (bset, ids, False)\n            else\n                let btree = (THE t. t \\<in> bset \\<and> (L b) \\<in> set t);\n                    freeblo = replace btree b (set_state_type b FREE);\n                    re = merge freeblo ids;\n                    newblo = fst re;\n                    newids = snd re in\n                ((bset - {btree}) \\<union> {newblo}, newids, True)\n         else\n            (bset, ids, False)\"\n\nend", "meta": {"author": "johnakeke", "repo": "Buddy-Memory-Verification", "sha": "bc6ea9213f93938d51dc7a9e225ce9ce14cdfb27", "save_path": "github-repos/isabelle/johnakeke-Buddy-Memory-Verification", "path": "github-repos/isabelle/johnakeke-Buddy-Memory-Verification/Buddy-Memory-Verification-bc6ea9213f93938d51dc7a9e225ce9ce14cdfb27/Memory_Allocation_Model.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110454379297, "lm_q2_score": 0.7931059487389968, "lm_q1q2_score": 0.7073006452879658}}
{"text": "theory sort_NMSortTDPermutes\nimports Main\n        \"$HIPSTER_HOME/IsaHipster\"\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 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 length :: \"'t list => Nat\" where\n\"length (Nil2) = Z\"\n| \"length (Cons2 y xs) = S (length xs)\"\n\nfun half :: \"Nat => Nat\" where\n\"half (Z) = Z\"\n| \"half (S (Z)) = Z\"\n| \"half (S (S n)) = S (half n)\"\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\nfun nmsorttd :: \"int list => int list\" where\n\"nmsorttd (Nil2) = Nil2\"\n| \"nmsorttd (Cons2 y (Nil2)) = Cons2 y (Nil2)\"\n| \"nmsorttd (Cons2 y (Cons2 x2 x3)) =\n     lmerge\n       (nmsorttd\n          (take\n             (half (length (Cons2 y (Cons2 x2 x3)))) (Cons2 y (Cons2 x2 x3))))\n       (nmsorttd\n          (drop\n             (half (length (Cons2 y (Cons2 x2 x3)))) (Cons2 y (Cons2 x2 x3))))\"\n\nfun count :: \"int => int list => Nat\" where\n\"count x (Nil2) = Z\"\n| \"count x (Cons2 z xs) =\n     (if x = z then S (count x xs) else count x xs)\"\n\n(*hipster take lmerge length half drop nmsorttd count *)\n\ntheorem x0 :\n  \"!! (x :: int) (y :: int list) .\n     (count x (nmsorttd y)) = (count x y)\"\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/koen/sort_NMSortTDPermutes.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425377849806, "lm_q2_score": 0.7690802423634963, "lm_q1q2_score": 0.7072789058474537}}
{"text": "theory Support \n  imports \"../Nominal\" \nbegin\n\ntext \\<open>\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\\<close>\n\natom_decl atom\n\ntext \\<open>The set of even atoms.\\<close>\nabbreviation\n  EVEN :: \"atom set\"\nwhere\n  \"EVEN \\<equiv> {atom n | n. \\<exists>i. n=2*i}\"\n\ntext \\<open>The set of odd atoms:\\<close>\nabbreviation  \n  ODD :: \"atom set\"\nwhere\n  \"ODD \\<equiv> {atom n | n. \\<exists>i. n=2*i+1}\"\n\ntext \\<open>An atom is either even or odd.\\<close>\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 \\<open>\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.)\\<close>\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 \\<open>The sets of even and odd atoms are disjunct.\\<close>\nlemma EVEN_intersect_ODD:\n  shows \"EVEN \\<inter> ODD = {}\"\n  using even_or_odd\n  by (auto) (presburger)\n\ntext \\<open>\n  The preceeding two lemmas help us to prove \n  the following two useful equalities:\\<close>\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 \\<open>The sets EVEN and ODD are infinite.\\<close>\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 \\<open>\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.\\<close>\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 \\<open>As a corollary we get that EVEN and ODD have infinite support.\\<close>\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 \\<open>\n  The set of all atoms has empty support, since any swappings leaves \n  this set unchanged.\\<close>\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 \\<open>Putting everything together.\\<close>\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 \\<open>Moral: support is a sublte notion.\\<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/Nominal/Examples/Support.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.857768108626046, "lm_q2_score": 0.8244619242200081, "lm_q1q2_score": 0.7071971453723868}}
{"text": "header \"Weights for Dijkstra's Algorithm\"\ntheory Weight\nimports Complex_Main\nbegin\n\ntext {*\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*}\n\nsubsection {* Type Classes Setup *}\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 {* Adding Infinity *}\ntext {*\n  We provide a standard way to add an infinity element to any type.\n*}\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 {* Unboxing *}\n\ntext {* Conversion between the constants defined by the\n  typeclass, and the concrete functions on the @{typ \"'a infty\"} type. \n*}\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": "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/Weight.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297861178929, "lm_q2_score": 0.7853085909370422, "lm_q1q2_score": 0.7071937774330784}}
{"text": "theory sort_MSortBU2Sorts\nimports Main\n        \"$HIPSTER_HOME/IsaHipster\"\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 => risers (Cons2 y2 xs)\n          | Cons2 ys yss => Cons2 (Cons2 y ys) yss\n        end\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\nfun 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\nfun dot :: \"('b => 'c) => ('a => 'b) => 'a => 'c\" where\n\"dot x y z = x (y z)\"\n\nfun msortbu2 :: \"int list => int list\" where\n\"msortbu2 x =\n   dot\n     (% (y :: (int list) list) => mergingbu2 y)\n     (% (z :: int list) => risers z) x\"\n\nfun and2 :: \"bool => bool => bool\" where\n\"and2 True y = y\"\n| \"and2 False y = False\"\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     and2 (y <= y2) (ordered (Cons2 y2 xs))\"\n\n(*hipster risers\n          lmerge\n          pairwise\n          mergingbu2\n          dot\n          msortbu2\n          and2\n          ordered *)\n\ntheorem x0 :\n  \"!! (x :: int list) . ordered (msortbu2 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/koen/sort_MSortBU2Sorts.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.900529778109184, "lm_q2_score": 0.7853085708384736, "lm_q1q2_score": 0.707193753044411}}
{"text": "section \\<open>Exponentiation of ordinals\\<close>\n\ntheory Ordinal_Exp\n  imports Kirby\n\nbegin\n\ntext \\<open>Source: Schl\u00f6der, Julian.  Ordinal Arithmetic; available online at\n    \\url{http://www.math.uni-bonn.de/ag/logik/teaching/2012WS/Set%20theory/oa.pdf}\\<close>\n\ndefinition oexp :: \"[V,V] \\<Rightarrow> V\" (infixr \"\\<up>\" 80)\n  where \"oexp a b \\<equiv> transrec (\\<lambda>f x. if x=0 then 1\n                                    else if Limit x then if a=0 then 0 else \\<Squnion>\\<xi> \\<in> elts x. f \\<xi>\n                                    else f (\\<Squnion>(elts x)) * a)  b\"\n\ntext \\<open>@{term \"0\\<up>\\<omega> = 1\"} if we don't make a special case for Limit ordinals and zero\\<close>\n\n\nlemma oexp_0_right [simp]: \"\\<alpha>\\<up>0 = 1\"\n  by (simp add: def_transrec [OF oexp_def])\n\nlemma oexp_succ [simp]: \"Ord \\<beta> \\<Longrightarrow> \\<alpha>\\<up>(succ \\<beta>) = \\<alpha>\\<up>\\<beta> * \\<alpha>\"\n  by (simp add: def_transrec [OF oexp_def])\n\nlemma oexp_Limit: \"Limit \\<beta> \\<Longrightarrow> \\<alpha>\\<up>\\<beta> = (if \\<alpha>=0 then 0 else \\<Squnion>\\<xi> \\<in> elts \\<beta>. \\<alpha>\\<up>\\<xi>)\"\n  by (auto simp: def_transrec [OF oexp_def, of _ \\<beta>])\n\nlemma oexp_1_right [simp]: \"\\<alpha>\\<up>1 = \\<alpha>\"\n  using one_V_def oexp_succ by fastforce\n\nlemma oexp_1 [simp]: \"Ord \\<alpha> \\<Longrightarrow> 1\\<up>\\<alpha> = 1\"\n  by (induction rule: Ord_induct3) (use Limit_def oexp_Limit in auto)\n\nlemma oexp_0 [simp]: \"Ord \\<alpha> \\<Longrightarrow> 0\\<up>\\<alpha> = (if \\<alpha> = 0 then 1 else 0)\"\n  by (induction rule: Ord_induct3) (use Limit_def oexp_Limit in auto)\n\nlemma oexp_eq_0_iff [simp]:\n  assumes \"Ord \\<beta>\" shows \"\\<alpha>\\<up>\\<beta> = 0 \\<longleftrightarrow> \\<alpha>=0 \\<and> \\<beta>\\<noteq>0\"\n  using \\<open>Ord \\<beta>\\<close>\nproof (induction rule: Ord_induct3)\n  case (Limit \\<mu>)\n  then show ?case\n    using Limit_def oexp_Limit by auto\nqed auto\n\nlemma oexp_gt_0_iff [simp]:\n  assumes \"Ord \\<beta>\" shows \"\\<alpha>\\<up>\\<beta> > 0 \\<longleftrightarrow> \\<alpha>>0 \\<or> \\<beta>=0\"\n  by (simp add: assms less_V_def)\n\nlemma ord_of_nat_oexp: \"ord_of_nat (m^n) = ord_of_nat m\\<up>ord_of_nat n\"\nproof (induction n)\n  case (Suc n)\n  then show ?case\n    by (simp add: mult.commute [of m]) (simp add: ord_of_nat_mult)\nqed auto\n\nlemma omega_closed_oexp [intro]:\n  assumes \"\\<alpha> \\<in> elts \\<omega>\" \"\\<beta> \\<in> elts \\<omega>\" shows \"\\<alpha>\\<up>\\<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>\\<up>\\<beta> = ord_of_nat (m^n)\"\n    by (simp add: ord_of_nat_oexp)\n  then show ?thesis\n    by (simp add: \\<omega>_def)\nqed\n\n\nlemma Ord_oexp [simp]:\n  assumes \"Ord \\<alpha>\" \"Ord \\<beta>\" shows \"Ord (\\<alpha>\\<up>\\<beta>)\"\n  using \\<open>Ord \\<beta>\\<close>\nproof (induction rule: Ord_induct3)\n  case (Limit \\<alpha>)\n  then show ?case\n    by (auto simp: oexp_Limit image_iff intro: Ord_Sup)\nqed (auto intro: Ord_mult assms)\n\ntext \\<open>Lemma 3.19\\<close>\nlemma le_oexp:\n  assumes \"Ord \\<alpha>\" \"Ord \\<beta>\" \"\\<beta> \\<noteq> 0\" shows \"\\<alpha> \\<le> \\<alpha>\\<up>\\<beta>\"\n  using \\<open>Ord \\<beta>\\<close> \\<open>\\<beta> \\<noteq> 0\\<close>\nproof (induction rule: Ord_induct3)\n  case (succ \\<beta>)\n  then show ?case\n    by simp (metis \\<open>Ord \\<alpha>\\<close> le_0 le_mult mult.left_neutral oexp_0_right order_refl order_trans)\nnext\n  case (Limit \\<mu>)\n  then show ?case\n    by (metis Limit_def Limit_eq_Sup_self ZFC_in_HOL.Sup_upper eq_iff image_eqI image_ident oexp_1_right oexp_Limit replacement small_elts one_V_def)\nqed auto\n\n\ntext \\<open>Lemma 3.20\\<close>\nlemma le_oexp':\n  assumes \"Ord \\<alpha>\" \"1 < \\<alpha>\" \"Ord \\<beta>\" shows \"\\<beta> \\<le> \\<alpha>\\<up>\\<beta>\"\nproof (cases \"\\<beta> = 0\")\n  case True\n  then show ?thesis\n    by auto\nnext\n  case False\n  show ?thesis\n    using \\<open>Ord \\<beta>\\<close>\n  proof (induction rule: Ord_induct3)\n    case 0\n    then show ?case\n      by auto\n  next\n    case (succ \\<gamma>)\n    then have \"\\<alpha>\\<up>\\<gamma> * 1 < \\<alpha>\\<up>\\<gamma> * \\<alpha>\"\n      using \\<open>Ord \\<alpha>\\<close> \\<open>1 < \\<alpha>\\<close>\n      by (metis le_mult less_V_def mult.right_neutral mult_cancellation not_less_0 oexp_eq_0_iff succ.hyps)\n    then have \" \\<gamma> < \\<alpha>\\<up>succ \\<gamma>\"\n      using succ.IH succ.hyps by auto\n    then show ?case\n      using False \\<open>Ord \\<alpha>\\<close> \\<open>1 < \\<alpha>\\<close> succ\n      by (metis Ord_mem_iff_lt Ord_oexp Ord_succ elts_succ insert_subset less_eq_V_def less_imp_le)\n  next\n    case (Limit \\<mu>)\n    with False \\<open>1 < \\<alpha>\\<close> show ?case\n      by (force simp: Limit_def oexp_Limit intro: elts_succ)\n  qed\nqed\n\n\nlemma oexp_Limit_le:\n  assumes \"\\<beta> < \\<gamma>\" \"Limit \\<gamma>\" \"Ord \\<beta>\" \"\\<alpha> > 0\" shows \"\\<alpha>\\<up>\\<beta> \\<le> \\<alpha>\\<up>\\<gamma>\"\nproof -\n  have \"Ord \\<gamma>\"\n    using Limit_def assms(2) by blast\n  with assms show ?thesis\n    using Ord_mem_iff_lt ZFC_in_HOL.Sup_upper oexp_Limit by auto\nqed\n\nproposition oexp_less:\n  assumes \\<beta>: \"\\<beta> \\<in> elts \\<gamma>\" and \"Ord \\<gamma>\" and \\<alpha>: \"\\<alpha> > 1\" \"Ord \\<alpha>\" shows \"\\<alpha>\\<up>\\<beta> < \\<alpha>\\<up>\\<gamma>\"\nproof -\n  obtain \"\\<beta> < \\<gamma>\" \"Ord \\<beta>\"\n    using Ord_in_Ord OrdmemD assms by auto\n  have gt0: \"\\<alpha>\\<up>\\<beta> > 0\"\n    using \\<open>Ord \\<beta>\\<close> \\<alpha> dual_order.order_iff_strict by auto\n  show ?thesis\n    using \\<open>Ord \\<gamma>\\<close> \\<beta>\n  proof (induction rule: Ord_induct3)\n    case 0\n    then show ?case\n      by auto\n  next\n    case (succ \\<delta>)\n    then consider \"\\<beta> = \\<delta>\" | \"\\<beta> < \\<delta>\"\n      using OrdmemD elts_succ by blast\n    then show ?case\n    proof cases\n      case 1\n      then have \"(\\<alpha>\\<up>\\<beta>) * 1 < (\\<alpha>\\<up>\\<delta>) * \\<alpha>\"\n        using Ord_1 Ord_oexp \\<alpha> gt0 mult_cancel_less_iff succ.hyps by metis\n      then show ?thesis\n        by (simp add: succ.hyps)\n    next\n      case 2\n      then have \"(\\<alpha>\\<up>\\<delta>) * 1 < (\\<alpha>\\<up>\\<delta>) * \\<alpha>\"\n        by (meson Ord_1 Ord_mem_iff_lt Ord_oexp \\<open>Ord \\<beta>\\<close> \\<alpha> gt0 less_trans mult_cancel_less_iff succ)\n      with 2 show ?thesis\n        using Ord_mem_iff_lt \\<open>Ord \\<beta>\\<close> succ by auto\n    qed\n  next\n    case (Limit \\<gamma>)\n    then obtain \"Ord \\<gamma>\" \"succ \\<beta> < \\<gamma>\"\n      using Limit_def Ord_in_Ord OrdmemD assms by auto\n    have \"\\<alpha>\\<up>\\<beta> = (\\<alpha>\\<up>\\<beta>) * 1\"\n      by simp\n    also have \"\\<dots> < (\\<alpha>\\<up>\\<beta>) * \\<alpha>\"\n      using Ord_oexp \\<open>Ord \\<beta>\\<close> assms gt0 mult_cancel_less_iff by blast\n    also have \"\\<dots> = \\<alpha>\\<up>succ \\<beta>\"\n      by (simp add: \\<open>Ord \\<beta>\\<close>)\n    also have \"\\<dots> \\<le> (\\<Squnion>\\<xi> \\<in> elts \\<gamma>. \\<alpha>\\<up>\\<xi>)\"\n    proof -\n      have \"succ \\<beta> \\<in> elts \\<gamma>\"\n        using Limit.hyps Limit.prems Limit_def by auto\n      then show ?thesis\n        by (simp add: ZFC_in_HOL.Sup_upper)\n    qed\n    finally\n    have \"\\<alpha>\\<up>\\<beta> < (\\<Squnion>\\<xi> \\<in> elts \\<gamma>. \\<alpha>\\<up>\\<xi>)\" .\n    then show ?case\n      using Limit.hyps oexp_Limit \\<open>\\<alpha> > 1\\<close> by auto\n  qed\nqed\n\ncorollary oexp_less_iff:\n  assumes \"\\<alpha> > 0\" \"Ord \\<alpha>\" \"Ord \\<beta>\" \"Ord \\<gamma>\" shows \"\\<alpha>\\<up>\\<beta> < \\<alpha>\\<up>\\<gamma> \\<longleftrightarrow> \\<beta> \\<in> elts \\<gamma> \\<and> \\<alpha> > 1\"\nproof safe\n  show \"\\<beta> \\<in> elts \\<gamma>\" \"1 < \\<alpha>\"\n    if \"\\<alpha>\\<up>\\<beta> < \\<alpha>\\<up>\\<gamma>\"\n  proof -\n    show \"\\<alpha> > 1\"\n    proof (rule ccontr)\n      assume \"\\<not> \\<alpha> > 1\"\n      then consider \"\\<alpha>=0\" | \"\\<alpha>=1\"\n        using \\<open>Ord \\<alpha>\\<close> less_V_def mem_0_Ord by fastforce\n      then show False\n        by cases (use that \\<open>\\<alpha> > 0\\<close> \\<open>Ord \\<beta>\\<close> \\<open>Ord \\<gamma>\\<close> in \\<open>auto split: if_split_asm\\<close>)\n    qed\n    show \\<beta>: \"\\<beta> \\<in> elts \\<gamma>\"\n    proof (rule ccontr)\n      assume \"\\<beta> \\<notin> elts \\<gamma>\"\n      then have \"\\<gamma> \\<le> \\<beta>\"\n        by (meson Ord_linear_le Ord_mem_iff_lt assms less_le_not_le)\n      then consider \"\\<gamma> = \\<beta>\" | \"\\<gamma> < \\<beta>\"\n        using less_V_def by blast\n      then show False\n      proof cases\n        case 1\n        then show ?thesis\n          using that by blast\n      next\n        case 2\n        with \\<open>\\<alpha> > 1\\<close> have \"\\<alpha>\\<up>\\<gamma> < \\<alpha>\\<up>\\<beta>\"\n          by (simp add: Ord_mem_iff_lt assms oexp_less)\n        with that show ?thesis\n          by auto\n      qed\n    qed\n  qed\n  show \"\\<alpha>\\<up>\\<beta> < \\<alpha>\\<up>\\<gamma>\" if \"\\<beta> \\<in> elts \\<gamma>\" \"1 < \\<alpha>\"\n    using that by (simp add: assms oexp_less)\nqed\n\nlemma \\<omega>_oexp_iff [simp]: \"\\<lbrakk>Ord \\<alpha>; Ord \\<beta>\\<rbrakk> \\<Longrightarrow> \\<omega>\\<up>\\<alpha> = \\<omega>\\<up>\\<beta> \\<longleftrightarrow> \\<alpha>=\\<beta>\"\n  by (metis Ord_\\<omega> Ord_linear \\<omega>_gt1 less_irrefl oexp_less)\n\nlemma Limit_oexp:\n  assumes \"Limit \\<gamma>\" \"Ord \\<alpha>\" \"\\<alpha> > 1\" shows \"Limit (\\<alpha>\\<up>\\<gamma>)\"\n  unfolding Limit_def\nproof safe\n  show O\\<alpha>\\<gamma>: \"Ord (\\<alpha>\\<up>\\<gamma>)\"\n    using Limit_def Ord_oexp \\<open>Limit \\<gamma>\\<close> assms(2) by blast\n  show 0: \"0 \\<in> elts (\\<alpha>\\<up>\\<gamma>)\"\n    using Limit_def oexp_Limit \\<open>Limit \\<gamma>\\<close> \\<open>\\<alpha> > 1\\<close> by fastforce\n  have \"Ord \\<gamma>\"\n    using Limit_def \\<open>Limit \\<gamma>\\<close> by blast\n  fix x\n  assume x: \"x \\<in> elts (\\<alpha>\\<up>\\<gamma>)\"\n  with \\<open>Limit \\<gamma>\\<close> \\<open>\\<alpha> > 1\\<close>\n  obtain \\<beta> where \"\\<beta> < \\<gamma>\" \"Ord \\<beta>\" \"Ord x\" and x\\<beta>: \"x \\<in> elts (\\<alpha>\\<up>\\<beta>)\"\n    apply (simp add: oexp_Limit split: if_split_asm)\n    using Ord_in_Ord OrdmemD \\<open>Ord \\<gamma>\\<close> O\\<alpha>\\<gamma> x by blast\n  then have O\\<alpha>\\<beta>: \"Ord (\\<alpha>\\<up>\\<beta>)\"\n    using Ord_oexp assms(2) by blast\n  have \"\\<beta> \\<in> elts \\<gamma>\"\n    by (simp add: Ord_mem_iff_lt \\<open>Ord \\<beta>\\<close> \\<open>Ord \\<gamma>\\<close> \\<open>\\<beta> < \\<gamma>\\<close>)\n  moreover have \"\\<alpha> \\<noteq> 0\"\n    using \\<open>\\<alpha> > 1\\<close> by blast\n  ultimately have \\<alpha>\\<beta>\\<gamma>: \"\\<alpha>\\<up>\\<beta> \\<le> \\<alpha>\\<up>\\<gamma>\"\n    by (simp add: Sup_upper oexp_Limit \\<open>Limit \\<gamma>\\<close>)\n  have \"succ x \\<le> \\<alpha>\\<up>\\<beta>\"\n    by (simp add: OrdmemD O\\<alpha>\\<beta> \\<open>Ord x\\<close> succ_le_iff x\\<beta>)\n  then consider \"succ x < \\<alpha>\\<up>\\<beta>\" | \"succ x = \\<alpha>\\<up>\\<beta>\"\n    using le_neq_trans by blast\n  then show \"succ x \\<in> elts (\\<alpha>\\<up>\\<gamma>)\"\n  proof cases\n    case 1\n    with \\<alpha>\\<beta>\\<gamma> show ?thesis\n      using O\\<alpha>\\<beta> Ord_mem_iff_lt \\<open>Ord x\\<close> by blast\n  next\n    case 2\n    then have \"succ \\<beta> < \\<gamma>\"\n      using Limit_def OrdmemD \\<open>\\<beta> \\<in> elts \\<gamma>\\<close> assms(1) by auto\n    have ge1: \"1 \\<le> \\<alpha>\\<up>\\<beta>\"\n      by (metis \"2\" Ord_0 \\<open>Ord x\\<close> le_0 le_succ_iff one_V_def)\n    have \"succ x < succ (\\<alpha>\\<up>\\<beta>)\"\n      using \"2\" O\\<alpha>\\<beta> succ_le_iff by auto\n    also have \"\\<dots> \\<le> (\\<alpha>\\<up>\\<beta>) + (\\<alpha>\\<up>\\<beta>)\"\n      using ge1 by (simp add: succ_eq_add1)\n    also have \"\\<dots> = (\\<alpha>\\<up>\\<beta>) * succ (succ 0)\"\n      by (simp add: mult_succ)\n    also have \"\\<dots> \\<le> (\\<alpha>\\<up>\\<beta>) * \\<alpha>\"\n      using O\\<alpha>\\<beta> Ord_succ assms(2) assms(3) one_V_def succ_le_iff by auto\n    also have \"\\<dots> = \\<alpha>\\<up>succ \\<beta>\"\n      by (simp add: \\<open>Ord \\<beta>\\<close>)\n    also have \"\\<dots> \\<le> \\<alpha>\\<up>\\<gamma>\"\n      by (meson Limit_def \\<open>\\<beta> \\<in> elts \\<gamma>\\<close> assms dual_order.order_iff_strict oexp_less)\n  finally show ?thesis\n    by (simp add: \"2\" O\\<alpha>\\<beta> O\\<alpha>\\<gamma> Ord_mem_iff_lt)\n  qed\nqed\n\n\n\nlemma oexp_mono:\n  assumes \\<alpha>: \"Ord \\<alpha>\" \"\\<alpha> \\<noteq> 0\" and \\<beta>: \"Ord \\<beta>\" \"\\<gamma> \\<sqsubseteq> \\<beta>\" shows \"\\<alpha>\\<up>\\<gamma> \\<le> \\<alpha>\\<up>\\<beta>\"\n  using \\<beta>\nproof (induction rule: Ord_induct3)\n  case 0\n  then show ?case\n    by simp\nnext\n  case (succ \\<beta>)\n  with \\<alpha> le_mult show ?case\n    by (auto simp: le_TC_succ)\nnext\n  case (Limit \\<mu>)\n  then have \"\\<alpha>\\<up>\\<gamma> \\<le> \\<Squnion> ((\\<up>) \\<alpha> ` elts \\<mu>)\"\n    using Limit.hyps Ord_less_TC_mem \\<open>\\<alpha> \\<noteq> 0\\<close> le_TC_def by (auto simp: oexp_Limit Limit_def)\n  then show ?case\n    using \\<alpha> by (simp add: oexp_Limit Limit.hyps)\nqed\n\nlemma oexp_mono_le:\n  assumes \"\\<gamma> \\<le> \\<beta>\" \"\\<alpha> \\<noteq> 0\" \"Ord \\<alpha>\" \"Ord \\<beta>\" \"Ord \\<gamma>\" shows \"\\<alpha>\\<up>\\<gamma> \\<le> \\<alpha>\\<up>\\<beta>\"\n  by (simp add: assms oexp_mono vle2 vle_iff_le_Ord)\n\nlemma oexp_sup:\n  assumes \"\\<alpha> \\<noteq> 0\" \"Ord \\<alpha>\" \"Ord \\<beta>\" \"Ord \\<gamma>\" shows \"\\<alpha>\\<up>(\\<beta> \\<squnion> \\<gamma>) = \\<alpha>\\<up>\\<beta> \\<squnion> \\<alpha>\\<up>\\<gamma>\"\n  by (metis Ord_linear_le assms oexp_mono_le sup.absorb2 sup.orderE)\n\nlemma oexp_Sup:\n  assumes \\<alpha>: \"\\<alpha> \\<noteq> 0\" \"Ord \\<alpha>\" and X: \"X \\<subseteq> ON\" \"small X\" \"X \\<noteq> {}\" shows \"\\<alpha>\\<up>\\<Squnion> X = \\<Squnion> ((\\<up>) \\<alpha> ` X)\"\nproof (rule order_antisym)\n  show \"\\<Squnion> ((\\<up>) \\<alpha> ` X) \\<le> \\<alpha>\\<up>\\<Squnion> X\"\n    by (metis ON_imp_Ord Ord_Sup ZFC_in_HOL.Sup_upper assms cSUP_least oexp_mono_le)\nnext\n  have \"Ord (Sup X)\"\n    using Ord_Sup X by auto\n  then show \"\\<alpha>\\<up>\\<Squnion> X \\<le> \\<Squnion> ((\\<up>) \\<alpha> ` X)\"\n  proof (cases rule: Ord_cases)\n    case 0\n    then show ?thesis\n      using X dual_order.antisym by fastforce\n  next\n    case (succ \\<beta>)\n    then show ?thesis\n      using ZFC_in_HOL.Sup_upper X succ_in_Sup_Ord by auto\n  next\n    case limit\n    show ?thesis\n    proof (clarsimp simp: assms oexp_Limit limit)\n      fix x y z\n      assume x: \"x \\<in> elts (\\<alpha> \\<up> y)\" and \"z \\<in> X\" \"y \\<in> elts z\"\n      then have \"\\<alpha> \\<up> y \\<le> \\<alpha> \\<up> z\"\n        by (meson ON_imp_Ord Ord_in_Ord OrdmemD \\<alpha> \\<open>X \\<subseteq> ON\\<close> le_less oexp_mono_le)\n      with x have \"x \\<in> elts (\\<alpha> \\<up> z)\" by blast\n      then show \"\\<exists>u\\<in>X. x \\<in> elts (\\<alpha> \\<up> u)\"\n        using \\<open>z \\<in> X\\<close> by blast\n    qed\n  qed\nqed\n\n\nlemma omega_le_Limit:\n  assumes \"Limit \\<mu>\" shows \"\\<omega> \\<le> \\<mu>\"\nproof\n  fix \\<rho>\n  assume \"\\<rho> \\<in> elts \\<omega>\"\n  then obtain n where \"\\<rho> = ord_of_nat n\"\n    using elts_\\<omega> by auto\n  have \"ord_of_nat n \\<in> elts \\<mu>\"\n    by (induction n) (use Limit_def assms in auto)\n  then show \"\\<rho> \\<in> elts \\<mu>\"\n    using \\<open>\\<rho> = ord_of_nat n\\<close> by auto\nqed\n\nlemma finite_omega_power [simp]:\n  assumes \"1 < n\" \"n \\<in> elts \\<omega>\" shows \"n\\<up>\\<omega> = \\<omega>\"\nproof (rule order_antisym)\n  have \"\\<Squnion> ((\\<up>) (ord_of_nat k) ` elts \\<omega>) \\<le> \\<omega>\" for k\n  proof (induction k)\n    case 0\n    then show ?case\n      by auto\n  next\n    case (Suc k)\n    then show ?case\n      by (metis Ord_\\<omega> OrdmemD Sup_eq_0_iff ZFC_in_HOL.SUP_le_iff le_0 le_less omega_closed_oexp ord_of_nat_\\<omega>)\n  qed\n  then show \"n\\<up>\\<omega> \\<le> \\<omega>\"\n    using assms\n    by (simp add: elts_\\<omega> oexp_Limit) metis\n  show \"\\<omega> \\<le> n\\<up>\\<omega>\"\n    using Ord_in_Ord assms le_oexp' by blast\nqed\n\n\nproposition oexp_add:\n  assumes \"Ord \\<alpha>\" \"Ord \\<beta>\" \"Ord \\<gamma>\" shows \"\\<alpha>\\<up>(\\<beta> + \\<gamma>) = \\<alpha>\\<up>\\<beta> * \\<alpha>\\<up>\\<gamma>\"\nproof (cases \\<open>\\<alpha> = 0\\<close>)\n  case True\n  then show ?thesis\n    using assms by simp\nnext\n  case False\n  show ?thesis\n    using \\<open>Ord \\<gamma>\\<close>\n  proof (induction rule: Ord_induct3)\n    case 0\n    then show ?case\n      by auto\n  next\n    case (succ \\<xi>)\n    then show ?case\n      using \\<open>Ord \\<beta>\\<close> by (auto simp: plus_V_succ_right mult.assoc)\n  next\n    case (Limit \\<mu>)\n    have \"\\<alpha>\\<up>(\\<beta> + (\\<Squnion>\\<xi>\\<in>elts \\<mu>. \\<xi>)) = (\\<Squnion>\\<xi>\\<in>elts (\\<beta> + \\<mu>). \\<alpha>\\<up>\\<xi>)\"\n      by (simp add: Limit.hyps oexp_Limit assms False)\n    also have \"\\<dots> = (\\<Squnion>\\<xi> \\<in> {\\<xi>. Ord \\<xi> \\<and> \\<beta> + \\<xi> < \\<beta> + \\<mu>}. \\<alpha>\\<up>(\\<beta> + \\<xi>))\"\n    proof (rule Sup_eq_Sup)\n      show \"(\\<lambda>\\<xi>. \\<alpha>\\<up>(\\<beta> + \\<xi>)) ` {\\<xi>. Ord \\<xi> \\<and> \\<beta> + \\<xi> < \\<beta> + \\<mu>} \\<subseteq> (\\<up>) \\<alpha> ` elts (\\<beta> + \\<mu>)\"\n        using Limit.hyps Limit_def Ord_mem_iff_lt imageI by blast\n      fix x\n      assume \"x \\<in> (\\<up>) \\<alpha> ` elts (\\<beta> + \\<mu>)\"\n      then obtain \\<xi> where \\<xi>: \"\\<xi> \\<in> elts (\\<beta> + \\<mu>)\" and x: \"x = \\<alpha>\\<up>\\<xi>\"\n        by auto\n      have \"\\<exists>\\<gamma>. Ord \\<gamma> \\<and> \\<gamma> < \\<mu> \\<and> \\<alpha>\\<up>\\<xi> \\<le> \\<alpha>\\<up>(\\<beta> + \\<gamma>)\"\n      proof (rule mem_plus_V_E [OF \\<xi>])\n        assume \"\\<xi> \\<in> elts \\<beta>\"\n        then have \"\\<alpha>\\<up>\\<xi> \\<le> \\<alpha>\\<up>\\<beta>\"\n          by (meson arg_subset_TC assms False le_TC_def less_TC_def oexp_mono vsubsetD)\n        with zero_less_Limit [OF \\<open>Limit \\<mu>\\<close>]\n        show \"\\<exists>\\<gamma>. Ord \\<gamma> \\<and> \\<gamma> < \\<mu> \\<and> \\<alpha>\\<up>\\<xi> \\<le> \\<alpha>\\<up>(\\<beta> + \\<gamma>)\"\n          by force\n      next\n        fix \\<delta>\n        assume \"\\<delta> \\<in> elts \\<mu>\" and \"\\<xi> = \\<beta> + \\<delta>\"\n        have \"Ord \\<delta>\"\n          using Limit.hyps Limit_def Ord_in_Ord \\<open>\\<delta> \\<in> elts \\<mu>\\<close> by blast\n        moreover have \"\\<delta> < \\<mu>\"\n          using Limit.hyps Limit_def OrdmemD \\<open>\\<delta> \\<in> elts \\<mu>\\<close> by auto\n        ultimately show \"\\<exists>\\<gamma>. Ord \\<gamma> \\<and> \\<gamma> < \\<mu> \\<and> \\<alpha>\\<up>\\<xi> \\<le> \\<alpha>\\<up>(\\<beta> + \\<gamma>)\"\n          using \\<open>\\<xi> = \\<beta> + \\<delta>\\<close> by blast\n      qed\n      then show \"\\<exists>y\\<in>(\\<lambda>\\<xi>. \\<alpha>\\<up>(\\<beta> + \\<xi>)) ` {\\<xi>. Ord \\<xi> \\<and> \\<beta> + \\<xi> < \\<beta> + \\<mu>}. x \\<le> y\"\n        using x by auto\n    qed auto\n    also have \"\\<dots> = (\\<Squnion>\\<xi>\\<in>elts \\<mu>. \\<alpha>\\<up>(\\<beta> + \\<xi>))\"\n      using \\<open>Limit \\<mu>\\<close>\n      by (simp add: Ord_Collect_lt Limit_def)\n    also have \"\\<dots> = (\\<Squnion>\\<xi>\\<in>elts \\<mu>. \\<alpha>\\<up>\\<beta> * \\<alpha>\\<up>\\<xi>)\"\n      using Limit.IH by auto\n    also have \"\\<dots> = \\<alpha>\\<up>\\<beta> * \\<alpha>\\<up>(\\<Squnion>\\<xi>\\<in>elts \\<mu>. \\<xi>)\"\n      using \\<open>\\<alpha> \\<noteq> 0\\<close> Limit.hyps\n      by (simp add: image_image oexp_Limit mult_Sup_distrib)\n    finally show ?case .\n  qed\nqed\n\nproposition oexp_mult:\n  assumes \"Ord \\<alpha>\" \"Ord \\<beta>\" \"Ord \\<gamma>\" shows \"\\<alpha>\\<up>(\\<beta> * \\<gamma>) = (\\<alpha>\\<up>\\<beta>)\\<up>\\<gamma>\"\nproof (cases \"\\<alpha> = 0 \\<or> \\<beta> = 0\")\n  case True\n  then show ?thesis\n    by (auto simp: \\<open>Ord \\<beta>\\<close> \\<open>Ord \\<gamma>\\<close>)\nnext\n  case False\n  show ?thesis\n    using \\<open>Ord \\<gamma>\\<close>\n  proof (induction rule: Ord_induct3)\n    case 0\n    then show ?case\n      by auto\n  next\n    case succ\n    then show ?case\n      using assms by (auto simp: mult_succ oexp_add)\n  next\n    case (Limit \\<mu>)\n    have Lim: \"Limit (\\<Squnion> ((*) \\<beta> ` elts \\<mu>))\"\n      unfolding Limit_def\n    proof (intro conjI allI impI)\n      show \"Ord (\\<Squnion> ((*) \\<beta> ` elts \\<mu>))\"\n        using Limit.hyps Limit_def Ord_in_Ord \\<open>Ord \\<beta>\\<close> by (auto intro: Ord_Sup)\n      have \"succ 0 \\<in> elts \\<mu>\"\n        using Limit.hyps Limit_def by blast\n      then show \"0 \\<in> elts (\\<Squnion> ((*) \\<beta> ` elts \\<mu>))\"\n        using False \\<open>Ord \\<beta>\\<close> mem_0_Ord by force\n      show \"succ y \\<in> elts (\\<Squnion> ((*) \\<beta> ` elts \\<mu>))\"\n        if \"y \\<in> elts (\\<Squnion> ((*) \\<beta> ` elts \\<mu>))\" for y\n        using that False Limit.hyps\n        apply (clarsimp simp: Limit_def)\n        by (metis Ord_in_Ord Ord_linear Ord_mem_iff_lt Ord_mult Ord_succ assms(2) less_V_def mult_cancellation mult_succ not_add_mem_right succ_le_iff succ_ne_self)\n    qed\n    have \"\\<alpha>\\<up>(\\<beta> * (\\<Squnion>\\<xi>\\<in>elts \\<mu>. \\<xi>)) = \\<alpha>\\<up>\\<Squnion> ((*) \\<beta> ` elts \\<mu>)\"\n      by (simp add: mult_Sup_distrib)\n    also have \"\\<dots> = \\<Squnion> (\\<Union>x\\<in>elts \\<mu>. (\\<up>) \\<alpha> ` elts (\\<beta> * x))\"\n      using False Lim oexp_Limit by fastforce\n    also have \"\\<dots> = (\\<Squnion>x\\<in>elts \\<mu>. \\<alpha>\\<up>(\\<beta> * x))\"\n    proof (rule Sup_eq_Sup)\n      show \"(\\<lambda>x. \\<alpha>\\<up>(\\<beta> * x)) ` elts \\<mu> \\<subseteq> (\\<Union>x\\<in>elts \\<mu>. (\\<up>) \\<alpha> ` elts (\\<beta> * x))\"\n        using \\<open>Ord \\<alpha>\\<close> \\<open>Ord \\<beta>\\<close> False Limit\n        apply clarsimp\n        by (metis Limit_def elts_succ imageI insertI1 mem_0_Ord mult_add_mem_0)\n      show \"\\<exists>y\\<in>(\\<lambda>x. \\<alpha>\\<up>(\\<beta> * x)) ` elts \\<mu>. x \\<le> y\"\n        if \"x \\<in> (\\<Union>x\\<in>elts \\<mu>. (\\<up>) \\<alpha> ` elts (\\<beta> * x))\" for x\n        using that \\<open>Ord \\<alpha>\\<close> \\<open>Ord \\<beta>\\<close> False Limit\n        by clarsimp (metis Limit_def Ord_in_Ord Ord_mult VWO_TC_le mem_imp_VWO oexp_mono)\n    qed auto\n    also have \"\\<dots> = \\<Squnion> ((\\<up>) (\\<alpha>\\<up>\\<beta>) ` elts (\\<Squnion>\\<xi>\\<in>elts \\<mu>. \\<xi>))\"\n      using Limit.IH Limit.hyps by auto\n    also have \"\\<dots> = (\\<alpha>\\<up>\\<beta>)\\<up>(\\<Squnion>\\<xi>\\<in>elts \\<mu>. \\<xi>)\"\n      using False Limit.hyps oexp_Limit \\<open>Ord \\<beta>\\<close> by auto\n    finally show ?case .\n  qed\nqed\n\nlemma Limit_omega_oexp:\n  assumes \"Ord \\<delta>\" \"\\<delta> \\<noteq> 0\"\n  shows \"Limit (\\<omega>\\<up>\\<delta>)\"\n  using assms\nproof (cases \\<delta> rule: Ord_cases)\n  case 0\n  then show ?thesis\n    using assms(2) by blast\nnext\n  case (succ l)\n  have *: \"succ \\<beta> \\<in> elts (\\<omega>\\<up>l * n + \\<omega>\\<up>l)\"\n    if n: \"n \\<in> elts \\<omega>\" and \\<beta>: \"\\<beta> \\<in> elts (\\<omega>\\<up>l * n)\" for n \\<beta>\n  proof -\n    obtain \"Ord n\" \"Ord \\<beta>\"\n      by (meson Ord_\\<omega> Ord_in_Ord Ord_mult Ord_oexp \\<beta> n succ(1))\n    obtain oo: \"Ord (\\<omega>\\<up>l)\" \"Ord (\\<omega>\\<up>l * n)\"\n      by (simp add: \\<open>Ord n\\<close> succ(1))\n    moreover have f4: \"\\<beta> < \\<omega>\\<up>l * n\"\n      using oo Ord_mem_iff_lt \\<open>Ord \\<beta>\\<close> \\<open>\\<beta> \\<in> elts (\\<omega>\\<up>l * n)\\<close> by blast\n    moreover have f5: \"Ord (succ \\<beta>)\"\n      using \\<open>Ord \\<beta>\\<close> by blast\n    moreover have \"\\<omega>\\<up>l \\<noteq> 0\"\n      using oexp_eq_0_iff omega_nonzero succ(1) by blast\n    ultimately show ?thesis\n      by (metis add_less_cancel_left Ord_\\<omega> Ord_add Ord_mem_iff_lt OrdmemD \\<open>Ord \\<beta>\\<close> add.right_neutral dual_order.strict_trans2 oexp_gt_0_iff succ(1) succ_le_iff zero_in_omega)\n  qed\n  show ?thesis\n    using succ\n    apply (clarsimp simp: Limit_def mem_0_Ord)\n    apply (simp add: mult_Limit)\n    by (metis * mult_succ succ_in_omega)\nnext\n  case limit\n  then show ?thesis\n    by (metis Limit_oexp Ord_\\<omega> OrdmemD one_V_def succ_in_omega zero_in_omega)\nqed\n\nlemma oexp_mult_commute:\n  fixes j::nat\n  assumes \"Ord \\<alpha>\"\n  shows \"(\\<alpha> \\<up> j) * \\<alpha> = \\<alpha> * (\\<alpha> \\<up> j)\"\nproof -\n  have \"(\\<alpha> \\<up> j) * \\<alpha> = \\<alpha> \\<up> (1 + ord_of_nat j)\"\n    by (simp add: one_V_def)\n  also have \"... = \\<alpha> * (\\<alpha> \\<up> j)\"\n    by (simp add: assms oexp_add)\n  finally show ?thesis .\nqed\n\nlemma oexp_\\<omega>_Limit: \"Limit \\<beta> \\<Longrightarrow> \\<omega>\\<up>\\<beta> = (\\<Squnion>\\<xi> \\<in> elts \\<beta>. \\<omega>\\<up>\\<xi>)\"\n  by (simp add: oexp_Limit)\n\nlemma \\<omega>_power_succ_gtr: \"Ord \\<alpha> \\<Longrightarrow> \\<omega> \\<up> \\<alpha> * ord_of_nat n < \\<omega> \\<up> succ \\<alpha>\"\n  by (simp add: OrdmemD)\n\nlemma countable_oexp:\n  assumes \\<nu>: \"\\<alpha> \\<in> elts \\<omega>1\" \n  shows \"\\<omega> \\<up> \\<alpha> \\<in> elts \\<omega>1\"\nproof -\n  have \"Ord \\<alpha>\"\n    using Ord_\\<omega>1 Ord_in_Ord assms by blast\n  then show ?thesis\n    using assms\n  proof (induction rule: Ord_induct3)\n    case 0\n    then show ?case\n      by (simp add: Ord_mem_iff_lt)\n  next\n    case (succ \\<alpha>)\n    then have \"countable (elts (\\<omega> \\<up> \\<alpha> * \\<omega>))\"\n      by (simp add: succ_in_Limit_iff countable_mult less_\\<omega>1_imp_countable)\n    then show ?case\n      using Ord_mem_iff_lt countable_iff_less_\\<omega>1 succ.hyps by auto\n  next\n    case (Limit \\<alpha>)\n    with Ord_\\<omega>1 have \"countable (\\<Union>\\<beta>\\<in>elts \\<alpha>. elts (\\<omega> \\<up> \\<beta>))\" \"Ord (\\<omega> \\<up> \\<Squnion> (elts \\<alpha>))\"\n      by (force simp: Limit_def intro: Ord_trans less_\\<omega>1_imp_countable)+\n    then have \"\\<omega> \\<up> \\<Squnion> (elts \\<alpha>) < \\<omega>1\"\n      using Limit.hyps countable_iff_less_\\<omega>1 oexp_Limit by fastforce\n    then show ?case\n      using Limit.hyps Limit_def Ord_mem_iff_lt by auto\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/ZFC_in_HOL/Ordinal_Exp.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8887587993853654, "lm_q2_score": 0.7956580952177051, "lm_q1q2_score": 0.7071481334269344}}
{"text": "section \\<open>Graph Theory Inheritance\\<close>\ntext \\<open> This theory aims to demonstrate the use of locales to transfer theorems between different \ngraph/combinatorial structure representations \\<close>\n\ntheory Graph_Theory_Relations imports Undirected_Graph_Basics Bipartite_Graphs \n\"Design_Theory.Block_Designs\" \"Design_Theory.Group_Divisible_Designs\"\nbegin\n\nsubsection \\<open> Design Inheritance \\<close>\ntext \\<open>A graph is a type of incidence system, and more specifically a type of combinatorial design. \nThis section demonstrates the correspondence between designs and graphs \\<close>\n\nsublocale graph_system \\<subseteq> inc: incidence_system V \"mset_set E\"\n  by (unfold_locales) (metis wellformed elem_mset_set ex_in_conv infinite_set_mset_mset_set) \n\nsublocale fin_graph_system \\<subseteq> finc: finite_incidence_system V \"mset_set E\"\n  using finV by unfold_locales\n\nsublocale fin_ulgraph \\<subseteq> d: design V \"mset_set E\"\n  using edge_size empty_not_edge fin_edges by unfold_locales auto \n\nsublocale fin_ulgraph \\<subseteq> d: simple_design V \"mset_set E\"\n  by unfold_locales (simp add: fin_edges) \n\nlocale graph_has_edges = graph_system + \n  assumes edges_nempty: \"E \\<noteq> {}\"\n\nlocale fin_sgraph_wedges = fin_sgraph + graph_has_edges\n\ntext \\<open>The simple graph definition of degree overlaps with the definition of a point replication number \\<close>\nsublocale fin_sgraph_wedges \\<subseteq> bd: block_design V \"mset_set E\" 2\n  rewrites \"point_replication_number (mset_set E) x = degree x\" \n    and \"points_index (mset_set E) vs = degree_set vs\"\nproof (unfold_locales) \n  show \"inc.\\<b> \\<noteq> 0\"  by (simp add: edges_nempty fin_edges)\n  show \"\\<And>bl. bl \\<in># mset_set E \\<Longrightarrow> card bl = 2\" by (simp add: fin_edges two_edges)\n  show \"mset_set E index vs = degree_set vs\"\n    unfolding degree_set_def points_index_def by (simp add: fin_edges) \nnext\n  have \"size {#b \\<in># (mset_set E) . x \\<in> b#} = card (incident_edges x)\"\n    unfolding incident_edges_def incident_def\n    by (simp add: fin_edges) \n  then show \"mset_set E rep x = degree x\" using alt_degree_def point_replication_number_def\n    by metis\nqed\n\nlocale fin_bipartite_graph_wedges = fin_bipartite_graph + fin_sgraph_wedges\n\nsublocale fin_bipartite_graph_wedges \\<subseteq> group_design V \"mset_set E\" \"{X, Y}\"\n  by unfold_locales (simp_all add: partition ne)\n\n\nsubsection \\<open>Adjacency Relation Definition \\<close>\n\ntext \\<open> Another common formal representation of graphs is as a vertex set and an adjacency relation\nThis is a useful representation in some contexts - we use locales to enable the transfer of \nresults between the two representations, specifically the mutual sublocales approach \\<close>\n\nlocale graph_rel = \n  fixes vertices :: \"'a set\" (\"V\")\n  fixes adj_rel :: \"'a rel\"\n  assumes wf: \"\\<And> u v. (u, v) \\<in> adj_rel \\<Longrightarrow> u \\<in> V \\<and> v \\<in> V\"\nbegin \n\nabbreviation \"adj u v \\<equiv> (u, v) \\<in> adj_rel\"\n\nlemma wf_alt: \"adj u v \\<Longrightarrow> (u, v) \\<in> V \\<times> V\"\n  using wf by blast\n\nend\n\n\nlocale ulgraph_rel = graph_rel + \n  assumes sym_adj: \"sym adj_rel\"\nbegin\n\ntext \\<open> This definition makes sense in the context of an undirected graph \\<close>\ndefinition edge_set:: \"'a edge set\" where\n\"edge_set \\<equiv> {{u, v} | u v. adj u v}\"\n\nlemma obtain_edge_pair_adj:\n  assumes \"e \\<in> edge_set\"\n  obtains u v where \"e = {u, v}\" and \"adj u v\" \n  using assms edge_set_def mem_Collect_eq\n  by fastforce \n\nlemma adj_to_edge_set_card: \n  assumes \"e \\<in> edge_set\"\n  shows \"card e = 1 \\<or> card e = 2\"\nproof -\n  obtain u v where \"e = {u, v}\" and \"adj u v\" using obtain_edge_pair_adj assms by blast \n  then show ?thesis by (cases \"u = v\", simp_all)\nqed\n\nlemma adj_to_edge_set_card_lim: \n  assumes \"e \\<in> edge_set\"\n  shows \"card e > 0 \\<and> card e \\<le> 2\"\nproof -\n  obtain u v where \"e = {u, v}\" and \"adj u v\" using obtain_edge_pair_adj assms by blast \n  then show ?thesis by (cases \"u = v\", simp_all)\nqed\n\nlemma edge_set_wf: \"e \\<in> edge_set \\<Longrightarrow> e \\<subseteq> V\"\n  using obtain_edge_pair_adj wf by (metis insert_iff singletonD subsetI) \n\nlemma is_graph_system: \"graph_system V edge_set\"\n  by (unfold_locales) (simp add: edge_set_wf)\n\nlemma sym_alt: \"adj u v \\<longleftrightarrow> adj v u\"\n  using sym_adj by (meson symE)\n\nlemma is_ulgraph: \"ulgraph V edge_set\"\n  using ulgraph_axioms_def is_graph_system adj_to_edge_set_card_lim \n  by (intro_locales) auto\n\nend\n\ncontext ulgraph\nbegin\n\ndefinition adj_relation :: \"'a rel\" where\n\"adj_relation \\<equiv> {(u, v) | u v . vert_adj u v}\"\n\nlemma adj_relation_wf: \"(u, v) \\<in> adj_relation \\<Longrightarrow> {u, v} \\<subseteq> V\"\n  unfolding adj_relation_def using vert_adj_imp_inV by auto\n\nlemma adj_relation_sym: \"sym adj_relation\"\n  unfolding adj_relation_def sym_def using vert_adj_sym by auto\n\nlemma is_ulgraph_rel: \"ulgraph_rel V adj_relation\"\n  using adj_relation_wf adj_relation_sym by (unfold_locales) auto\n\ntext \\<open> Temporary interpretation - mutual sublocale setup \\<close>\n\ninterpretation ulgraph_rel V adj_relation by (rule is_ulgraph_rel)\n\nlemma vert_adj_rel_iff: \n  assumes \"u \\<in> V\" \"v \\<in> V\"\n  shows \"vert_adj u v \\<longleftrightarrow> adj u v\"\n  using adj_relation_def by auto\n\nlemma edges_rel_is: \"E = edge_set\"\nproof -\n  have \"E = {{u, v} | u v . vert_adj u v}\"\n  proof (intro subset_antisym subsetI)\n    show \"\\<And>x. x \\<in> {{u, v} |u v. vert_adj u v} \\<Longrightarrow> x \\<in> E\"\n      using vert_adj_def by fastforce\n  next \n    fix x assume \"x \\<in> E\"\n    then have \"x \\<subseteq> V\" and \"card x > 0\" and \"card x \\<le> 2\" using wellformed edge_size by auto \n    then obtain u v where \"x = {u, v}\" and \"{u, v} \\<in> E\"\n      by (metis \\<open>x \\<in> E\\<close> alt_edge_size card_1_singletonE card_2_iff insert_absorb2) \n    then show \"x \\<in> {{u, v} |u v. vert_adj u v}\" unfolding vert_adj_def by blast    \n  qed\n  then have \"E = {{u, v} | u v . adj u v}\" using vert_adj_rel_iff Collect_cong\n    by (smt (verit) local.wf vert_adj_imp_inV) \n  thus ?thesis using edge_set_def by simp\nqed\n\nend\n\ncontext ulgraph_rel \nbegin\n\ntext \\<open> Temporary interpretation - mutual sublocale setup \\<close>\ninterpretation ulgraph V edge_set by (rule is_ulgraph)\n\nlemma rel_vert_adj_iff:  \"vert_adj u v \\<longleftrightarrow> adj u v\"\nproof (intro iffI)\n  assume \"vert_adj u v\"\n  then have \"{u, v} \\<in> edge_set\" by (simp add: vert_adj_def)\n  then show \"adj u v\" using edge_set_def\n    by (metis (no_types, lifting) doubleton_eq_iff obtain_edge_pair_adj sym_alt) \nnext\n  assume \"adj u v\"\n  then have \"{u, v} \\<in> edge_set\" using edge_set_def by auto\n  then show \"vert_adj u v\" by (simp add: vert_adj_def)\nqed\n\nlemma rel_item_is: \"(u, v) \\<in> adj_rel \\<longleftrightarrow> (u, v) \\<in> adj_relation\"\n  unfolding adj_relation_def using rel_vert_adj_iff by auto\n\nlemma rel_edges_is: \"adj_rel = adj_relation\"\n  using rel_item_is by auto\n\nend\n\nsublocale ulgraph_rel \\<subseteq> ulgraph \"V\" \"edge_set\"\n  rewrites \"ulgraph.adj_relation edge_set = adj_rel\"\n  using local.is_ulgraph rel_edges_is by simp_all\n\nsublocale ulgraph \\<subseteq> ulgraph_rel \"V\" \"adj_relation\"\n  rewrites \"ulgraph_rel.edge_set adj_relation = E\"\n  using is_ulgraph_rel edges_rel_is by simp_all\n\nlocale sgraph_rel = ulgraph_rel +\n  assumes irrefl_adj: \"irrefl adj_rel\"\nbegin\n\nlemma irrefl_alt: \"adj u v \\<Longrightarrow> u \\<noteq> v\"\n  using irrefl_adj irrefl_def by fastforce \n\nlemma edge_is_card2: \n  assumes \"e \\<in> edge_set\"\n  shows \"card e = 2\"\nproof -\n  obtain u v where eq: \"e = {u, v}\" and \"adj u v\" using assms edge_set_def by blast\n  then have \"u \\<noteq> v\" using irrefl_alt by simp\n  thus ?thesis using eq by simp\nqed\n\nlemma is_sgraph: \"sgraph V edge_set\"\n  using is_graph_system edge_is_card2 sgraph_axioms_def by (intro_locales) auto\n\nend\n\ncontext sgraph\nbegin\n\nlemma is_rel_irrefl_alt: \n  assumes \"(u, v) \\<in> adj_relation\"\n  shows \"u \\<noteq> v\"\nproof -\n  have \"vert_adj u v\" using adj_relation_def assms by blast\n  then have \"{u, v} \\<in> E\" using vert_adj_def by simp\n  then have \"card {u, v} = 2\" using two_edges by simp\n  thus ?thesis by auto\nqed\n\nlemma is_rel_irrefl: \"irrefl adj_relation\"\n  using irrefl_def is_rel_irrefl_alt by auto\n\nlemma is_sgraph_rel: \"sgraph_rel V adj_relation\"\n  by (unfold_locales) (simp add: is_rel_irrefl)\n\nend\n\nsublocale sgraph_rel \\<subseteq> sgraph V \"edge_set\"\n  rewrites \"ulgraph.adj_relation edge_set = adj_rel\"\n  using is_sgraph rel_edges_is by simp_all\n\nsublocale sgraph \\<subseteq> sgraph_rel V \"adj_relation\"\n  rewrites \"ulgraph_rel.edge_set adj_relation = E\"\n  using is_sgraph_rel edges_rel_is by simp_all\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/Undirected_Graph_Theory/Graph_Theory_Relations.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8723473713594992, "lm_q2_score": 0.8104789109591832, "lm_q1q2_score": 0.7070191475175531}}
{"text": "(* Author: Tobias Nipkow & Stefan Dirix *)\n\nsection \\<open>Weight Balanced Tree Implementation of Sets\\<close>\n\ntext \\<open>This theory follows Hirai and Yamamoto but we do not prove their general\ntheorem. Instead we provide a short parameterized theory that, when\ninterpreted with valid parameters, will prove perservation of the invariant\nfor these parameters.\\<close>\n\ntheory Weight_Balanced_Trees\nimports\n  \"HOL-Data_Structures.Isin2\"\nbegin\n\nlemma neq_Leaf2_iff: \"t \\<noteq> Leaf \\<longleftrightarrow> (\\<exists>l a n r. t = Node l (a,n) r)\"\nby(cases t) auto\n\ntype_synonym 'a wbt = \"('a * nat) tree\"\n\nfun size_wbt :: \"'a wbt \\<Rightarrow> nat\" where\n\"size_wbt Leaf = 0\" |\n\"size_wbt (Node _ (_, n) _) = n\"\n\ntext \\<open>Smart constructor:\\<close>\n\nfun N :: \"'a wbt \\<Rightarrow> 'a \\<Rightarrow> 'a wbt \\<Rightarrow> 'a wbt\" where\n\"N l a r = Node l (a, size_wbt l + size_wbt r + 1) r\"\n\ntext \"Basic Rotations:\"\n\nfun rot1L :: \"'a wbt \\<Rightarrow> 'a \\<Rightarrow> 'a wbt \\<Rightarrow> 'a \\<Rightarrow> 'a wbt \\<Rightarrow> 'a wbt\" where\n\"rot1L A a B b C = N (N A a B) b C\"\n\nfun rot1R :: \"'a wbt \\<Rightarrow> 'a \\<Rightarrow> 'a wbt \\<Rightarrow> 'a \\<Rightarrow> 'a wbt \\<Rightarrow> 'a wbt\" where\n\"rot1R A a B b C = N A a (N B b C)\"\n\nfun rot2 :: \"'a wbt \\<Rightarrow> 'a \\<Rightarrow> 'a wbt \\<Rightarrow> 'a \\<Rightarrow> 'a wbt \\<Rightarrow> 'a wbt\" where\n\"rot2 A a (Node B1 (b,_) B2) c C = N (N A a B1) b (N B2 c C)\"\n\n\nsubsection \"WB trees\"\n\ntext \\<open>\nParameters:\n  \\<^descr> \\<open>\\<Delta>\\<close> determines when a tree needs to be rebalanced\n  \\<^descr> \\<open>\\<Gamma>\\<close> determines whether it needs to be single or double rotation.\n\n\\noindent We represent rational numbers as pairs: \\<open>\\<Delta> = \\<Delta>1/\\<Delta>2\\<close> and \\<open>\\<Gamma> = \\<Gamma>1/\\<Gamma>2\\<close>.\n\\bigskip\n\nHirai and Yamamoto \\<^cite>\\<open>\"HiraiY11\"\\<close> proved that under the following constraints\ninsertion and deletion preserve the WB invariant, i.e.\\\n\\<open>\\<Delta>\\<close> and \\<open>\\<Gamma>\\<close> are \\emph{valid}:\\<close>\n\ndefinition valid_params :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> bool\" where\n\"valid_params \\<Delta>1 \\<Delta>2 \\<Gamma>1 \\<Gamma>2 = (\n  \\<Delta>1 * 2 < \\<Delta>2 * 9  \\<comment> \\<open>right: \\<open>\\<Delta> < 4.5\\<close>\\<close> \\<and>\n  \\<Gamma>1 * \\<Delta>2 + \\<Gamma>2 * \\<Delta>2 \\<le> \\<Gamma>2 * \\<Delta>1 \\<comment> \\<open>left: \\<open>\\<Gamma> + 1 \\<le> \\<Delta>\\<close>\\<close> \\<and>\n  \\<Gamma>1 * \\<Delta>1 \\<ge> \\<Gamma>2 * (\\<Delta>1 + \\<Delta>2)  \\<comment> \\<open>lower: \\<open>\\<Gamma> \\<ge> (\\<Delta> + 1) / \\<Delta>\\<close>\\<close> \\<and>\n  \\<comment> \\<open>upper:\\<close>\n  (5*\\<Delta>2 \\<le> 2*\\<Delta>1 \\<and> 1*\\<Delta>1 < 3*\\<Delta>2 \\<longrightarrow> \\<Gamma>1*2 \\<le> \\<Gamma>2*3)\n     \\<comment> \\<open>\\<open>\\<Gamma> \\<le> 3/2\\<close> if \\<open>2.5 \\<le> \\<Delta> < 3\\<close>\\<close> \\<and>\n  (3*\\<Delta>2 \\<le> 1*\\<Delta>1 \\<and> 2*\\<Delta>1 < 7*\\<Delta>2 \\<longrightarrow> \\<Gamma>1*2 \\<le> \\<Gamma>2*4)\n     \\<comment> \\<open>\\<open>\\<Gamma> \\<le> 4/2\\<close> if \\<open>3 \\<le> \\<Delta> < 3.5\\<close>\\<close> \\<and>\n  (7*\\<Delta>2 \\<le> 2*\\<Delta>1 \\<and> 1*\\<Delta>1 < 4*\\<Delta>2 \\<longrightarrow> \\<Gamma>1*3 \\<le> \\<Gamma>2*4)\n     \\<comment> \\<open>\\<open>\\<Gamma> \\<le> 4/3\\<close> when \\<open>3.5 \\<le> \\<Delta> < 4\\<close>\\<close> \\<and>\n  (4*\\<Delta>2 \\<le> 1*\\<Delta>1 \\<and> 2*\\<Delta>1 < 9*\\<Delta>2 \\<longrightarrow> \\<Gamma>1*3 \\<le> \\<Gamma>2*5)\n     \\<comment> \\<open>\\<open>\\<Gamma> \\<le> 5/3\\<close> when \\<open>4 \\<le> \\<Delta> < 4.5\\<close>\\<close>\n  )\"\n\ntext \\<open>We do not make use of these constraints and do not prove that they guarantee\npreservation of the invariant. Instead, we provide generic proofs of invariant preservation\nthat work for many (all?) interpretations of locale \\<open>WBT\\<close> (below) with valid parameters.\nFurther down we demonstrate this by interpreting \\<open>WBT\\<close> with a selection of valid parameters.\n[For some parameters, some \\<open>smt\\<close> proofs fail because \\<open>smt\\<close> on \\<open>nat\\<close>s fails although\non non-negative \\<open>int\\<close>s it succeeds, i.e.\\ the goal should be provable.\nThis is a shortcoming of \\<open>smt\\<close> that is under investigation.]\n\nLocale \\<open>WBT\\<close> comes with some minimal assumptions (\\<open>\\<Gamma>1 > \\<Gamma>2\\<close> and \\<open>\\<Delta>1 > \\<Delta>2\\<close>) which follow\nfrom @{const valid_params} and from which we conclude some simple lemmas.\n\\<close>\n\nlocale WBT =\nfixes \\<Delta>1 \\<Delta>2 :: nat and \\<Gamma>1 \\<Gamma>2 :: nat\nassumes Delta_gr1: \"\\<Delta>1 > \\<Delta>2\" and Gamma_gr1: \"\\<Gamma>1 > \\<Gamma>2\"\nbegin\n\n(* How to prove the assumptions from valid_params:\nlemma Gamma_gr1: \"\\<Gamma>1 > \\<Gamma>2\"\nproof -\n  have \"\\<not> (\\<Delta>1 + \\<Delta>2) * \\<Gamma>2 \\<le> \\<Delta>1 * \\<Gamma>2\" by (simp add: not0)\n  thus ?thesis by (metis order.trans lower mult.commute mult_le_cancel2 not_le)\nqed\n\nlemma Delta_gr2: \"\\<Delta>1 > 2 * \\<Delta>2\"\nproof -\n  from Gamma_gr1 have \"\\<Gamma>2 * \\<Delta>2 < \\<Gamma>1 * \\<Delta>2\" by (simp add: not0)\n  with left have \"2 * \\<Gamma>2 * \\<Delta>2 < \\<Gamma>2 * \\<Delta>1\" by linarith\n  thus ?thesis by(simp)\nqed\n*)\n\nsubsubsection \"Balance Indicators\"\n\nfun balanced1 :: \"'a wbt \\<Rightarrow> 'a wbt \\<Rightarrow> bool\" where\n\"balanced1 t1 t2 = (\\<Delta>1 * (size_wbt t1 + 1) \\<ge> \\<Delta>2 * (size_wbt t2 + 1))\"\n\ntext \\<open>The global weight-balanced tree invariant:\\<close>\n\nfun wbt :: \"'a wbt \\<Rightarrow> bool\" where\n\"wbt Leaf = True\"|\n\"wbt (Node l (_, n) r) =\n  (n = size l + size r + 1 \\<and> balanced1 l r \\<and> balanced1 r l \\<and> wbt l \\<and> wbt r)\"\n\nlemma size_wbt_eq_size[simp]: \"wbt t \\<Longrightarrow> size_wbt t = size t\"\nby(induction t) auto\n\nfun single :: \"'a wbt \\<Rightarrow> 'a wbt \\<Rightarrow> bool\" where\n\"single t1 t2 = (\\<Gamma>1 * (size_wbt t2 + 1) > \\<Gamma>2 * (size_wbt t1 + 1))\"\n\nsubsubsection \"Code\"\n\nfun rotateL :: \"'a wbt \\<Rightarrow> 'a \\<Rightarrow> 'a wbt \\<Rightarrow> 'a wbt\" where\n\"rotateL A a (Node B (b, _) C) =\n   (if single B C then rot1L A a B b C else rot2 A a B b C)\"\n\nfun balanceL :: \"'a wbt \\<Rightarrow> 'a \\<Rightarrow> 'a wbt \\<Rightarrow> 'a wbt\" where\n\"balanceL l a r = (if balanced1 l r then N l a r else rotateL l a r)\"\n\nfun rotateR :: \"'a wbt \\<Rightarrow> 'a \\<Rightarrow> 'a wbt \\<Rightarrow> 'a wbt\" where\n\"rotateR (Node A (a, _) B) b C =\n  (if single B A then rot1R A a B b C else rot2 A a B b C)\"\n\nfun balanceR :: \"'a wbt \\<Rightarrow> 'a \\<Rightarrow> 'a wbt \\<Rightarrow> 'a wbt\" where\n\"balanceR l a r = (if balanced1 r l then N l a r else rotateR l a r)\"\n\nfun insert :: \"'a::linorder \\<Rightarrow> 'a wbt \\<Rightarrow> 'a wbt\" where\n\"insert x Leaf = Node Leaf (x, 1) Leaf\" |\n\"insert x (Node l (a, n) r) =\n   (case cmp x a of\n      LT \\<Rightarrow> balanceR (insert x l) a r |\n      GT \\<Rightarrow> balanceL l a (insert x r) |\n      EQ \\<Rightarrow> Node l (a, n) r )\"\n\nfun split_min :: \"'a wbt \\<Rightarrow> 'a * 'a wbt\" where\n\"split_min (Node l (a, _) r) =\n   (if l = Leaf then (a,r) else let (x,l') = split_min l in (x, balanceL l' a r))\"\n\nfun del_max :: \"'a wbt \\<Rightarrow> 'a * 'a wbt\" where\n\"del_max (Node l (a, _) r) =\n   (if r = Leaf then (a,l) else let (x,r') = del_max r in (x, balanceR l a r'))\"\n\nfun combine :: \"'a wbt \\<Rightarrow> 'a wbt \\<Rightarrow> 'a wbt\"  where\n\"combine Leaf Leaf = Leaf\"|\n\"combine Leaf r = r\"|\n\"combine l Leaf = l\"|\n\"combine l r =\n   (if size l > size r then\n      let (lMax, l') = del_max l in balanceL l' lMax r\n    else\n      let (rMin, r') = split_min r in balanceR l rMin r')\"\n\nfun delete :: \"'a::linorder \\<Rightarrow> 'a wbt \\<Rightarrow> 'a wbt\" where\n\"delete _ Leaf = Leaf\" |\n\"delete x (Node l (a, _) r) =\n  (case cmp x a of\n     LT \\<Rightarrow> balanceL (delete x l) a r |\n     GT \\<Rightarrow> balanceR l a (delete x r) |\n     EQ \\<Rightarrow> combine l r)\"\n\n\nsubsection \"Functional Correctness Proofs\"\n\ntext \\<open>A WB tree must be of a certain structure if balanced1 and single are False.\\<close>\n\nlemma not_Leaf_if_not_balanced1:\n  assumes \"\\<not> balanced1 l r\"\n  shows \"r \\<noteq> Leaf\"\nproof\n  assume \"r = Leaf\" with assms Delta_gr1 show False by simp\nqed\n\nlemma not_Leaf_if_not_single:\n  assumes \"\\<not> single l r\"\n  shows \"l \\<noteq> Leaf\"\nproof\n  assume \"l = Leaf\" with assms Gamma_gr1 show False by simp\nqed\n\nsubsubsection \"Inorder Properties\"\n\n\n\nlemma inorder_rotateL:\n  \"r \\<noteq> Leaf \\<Longrightarrow> inorder(rotateL l a r) = inorder l @ a # inorder r\"\nby (induction l a r rule: rotateL.induct) (auto simp add: inorder_rot2 not_Leaf_if_not_single)\n\nlemma inorder_rotateR:\n  \"l \\<noteq> Leaf \\<Longrightarrow> inorder(rotateR l a r) = inorder l @ a # inorder r\"\nby (induction l a r rule: rotateR.induct) (auto simp add: inorder_rot2 not_Leaf_if_not_single)\n\nlemma inorder_insert:\n  \"sorted(inorder t) \\<Longrightarrow> inorder(insert x t) = ins_list x (inorder t)\"\nby (induction t)\n   (auto simp: ins_list_simps inorder_rotateL inorder_rotateR not_Leaf_if_not_balanced1)\n\nlemma split_minD:\n  \"split_min t = (x,t') \\<Longrightarrow> t \\<noteq> Leaf \\<Longrightarrow> x # inorder t' = inorder t\"\nby (induction t arbitrary: t' rule: split_min.induct)\n   (auto simp: sorted_lems inorder_rotateL not_Leaf_if_not_balanced1\n     split: prod.splits if_splits)\n\nlemma del_maxD:\n  \"del_max t = (x,t') \\<Longrightarrow> t \\<noteq> Leaf \\<Longrightarrow> inorder t' @ [x] = inorder t\"\nby (induction t arbitrary: t' rule: del_max.induct)\n   (auto simp: sorted_lems inorder_rotateR not_Leaf_if_not_balanced1\n     split: prod.splits if_splits)\n\nlemma inorder_combine:\n  \"inorder(combine l r) = inorder l @ inorder r\"\nby(induction l r rule: combine.induct)\n  (auto simp: del_maxD split_minD inorder_rotateL inorder_rotateR not_Leaf_if_not_balanced1\n    simp del: rotateL.simps rotateR.simps split: prod.splits)\n\nlemma inorder_delete:\n  \"sorted(inorder t) \\<Longrightarrow> inorder(delete x t) = del_list x (inorder t)\"\nby(induction t)\n  (auto simp: del_list_simps inorder_combine inorder_rotateL inorder_rotateR\n     not_Leaf_if_not_balanced1 simp del: rotateL.simps rotateR.simps)\n\n\nsubsection \"Size Lemmas\"\n\nsubsubsection \"Insertion\"\n\nlemma size_rot2L[simp]:\n  \"B \\<noteq> Leaf \\<Longrightarrow> size(rot2 A a B b C) = size A + size B + size C + 2\"\nby(induction A a B b C rule: rot2.induct) auto\n\nlemma size_rotateR[simp]:\n  \"l \\<noteq> Leaf \\<Longrightarrow> size(rotateR l a r) = size l + size r + 1\"\nby(induction l a r rule: rotateR.induct)\n  (auto simp: not_Leaf_if_not_single simp del: rot2.simps)\n\nlemma size_rotateL[simp]:\n  \"r \\<noteq> Leaf \\<Longrightarrow> size(rotateL l a r) = size l + size r + 1\"\nby(induction l a r rule: rotateL.induct)\n  (auto simp: not_Leaf_if_not_single simp del: rot2.simps)\n\nlemma size_length: \"size t = length (inorder t)\"\nby (induction t rule: inorder.induct) auto\n\nlemma size_insert: \"size (insert x t) = (if isin t x then size t else Suc (size t))\"\nby (induction t rule: tree2_induct) (auto simp: not_Leaf_if_not_balanced1)\n\nsubsubsection \"Deletion\"\n\nlemma size_delete_if_isin: \"isin t x \\<Longrightarrow> size t = Suc (size(delete x t))\"\nproof (induction t rule: tree2_induct)\n  case (Node _ a _ _)\n  thus ?case\n  proof (cases \"cmp x a\")\n    case LT thus ?thesis using Node.prems by (simp add: Node.IH(1) not_Leaf_if_not_balanced1)\n  next\n    case EQ thus ?thesis by simp (metis size_length inorder_combine length_append)\n  next\n    case GT thus ?thesis using Node.prems by (simp add: Node.IH(2) not_Leaf_if_not_balanced1)\n  qed\nqed (auto)\n\nlemma delete_id_if_wbt_notin: \"wbt t \\<Longrightarrow> \\<not> isin t x \\<Longrightarrow> delete x t = t\"\nby (induction t) auto\n\nlemma size_split_min: \"t \\<noteq> Leaf \\<Longrightarrow> size t = Suc (size (snd (split_min t)))\"\nby(induction t) (auto simp: not_Leaf_if_not_balanced1 split: if_splits prod.splits)\n\n\n\n\nsubsection \"Auxiliary Definitions\"\n\nfun balanced1_arith :: \"nat \\<Rightarrow> nat \\<Rightarrow> bool\" where\n\"balanced1_arith a b = (\\<Delta>1 * (a + 1) \\<ge> \\<Delta>2 * (b + 1))\"\n\nfun balanced2_arith :: \"nat \\<Rightarrow> nat \\<Rightarrow> bool\" where\n\"balanced2_arith a b = (balanced1_arith a b \\<and> balanced1_arith b a)\"\n\nfun singly_balanced_arith :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> bool\" where\n\"singly_balanced_arith x y w = (balanced2_arith x y \\<and> balanced2_arith (x+y+1) w)\"\n\nfun doubly_balanced_arith :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> bool\" where\n\"doubly_balanced_arith x y z w =\n  (balanced2_arith x y \\<and> balanced2_arith z w \\<and> balanced2_arith (x+y+1) (z+w+1))\"\n\nend\n\n\nsubsection \"Preservation of WB tree Invariant for Concrete Parameters\"\n\ntext \\<open>A number of sample interpretations with valid parameters:\\<close>\n\ninterpretation WBT where\n  \\<Delta>1 = 25 and \\<Delta>2 = 10 and \\<Gamma>1 = 14 and \\<Gamma>2 = 10\n(* \\<Delta>1 = 25 and \\<Delta>2 = 10 and \\<Gamma>1 = 15 and \\<Gamma>2 = 10*)\n(* \\<Delta>1 = 28 and \\<Delta>2 = 10 and \\<Gamma>1 = 10 and \\<Gamma>2 = 7*)\n\n(* \\<Delta>1 = 3 and \\<Delta>2 = \"Suc 0\" and \\<Gamma>1 = 4 and \\<Gamma>2 = 3*)\n  (* The only integer solution: *)\n(* \\<Delta>1 = 3 and \\<Delta>2 = \"Suc 0\" and \\<Gamma>1 = 2 and \\<Gamma>2 = \"Suc 0\"*)\n(* \\<Delta>1 = 31 and \\<Delta>2 = 10 and \\<Gamma>1 = 18 and \\<Gamma>2 = 10*)\n\n(* \\<Delta>1 = 35 and \\<Delta>2 = 10 and \\<Gamma>1 = 45 and \\<Gamma>2 = 35*)\n(* \\<Delta>1 = 35 and \\<Delta>2 = 10 and \\<Gamma>1 = 4 and \\<Gamma>2 = 3*)\n(* \\<Delta>1 = 37 and \\<Delta>2 = 10 and \\<Gamma>1 = 13 and \\<Gamma>2 = 10*)\n\n(* \\<Delta>1 = 4 and \\<Delta>2 = \"Suc 0\" and \\<Gamma>1 = 5 and \\<Gamma>2 = 4*)\n(* \\<Delta>1 = 4 and \\<Delta>2 = \"Suc 0\" and \\<Gamma>1 = 5 and \\<Gamma>2 = 3*)\n(* \\<Delta>1 = 17 and \\<Delta>2 = 4 and \\<Gamma>1 = 5 and \\<Gamma>2 = 3 *)\nby (auto simp add: WBT_def)\n\nlemma wbt_insert:\n  \"wbt t \\<Longrightarrow> wbt (insert x t)\"\nproof (induction t rule: tree2_induct)\n  case Leaf show ?case by simp\nnext\n  case (Node l a _ r)\n  show ?case\n  proof (cases \"cmp x a\")\n    case EQ thus ?thesis using Node.prems by auto\n  next\n    case [simp]: LT\n    let ?l' = \"insert x l\"\n    show ?thesis\n    proof (cases \"balanced1 r ?l'\")\n      case True thus ?thesis using Node size_insert[of x l] by auto\n    next\n      case [simp]: False\n      hence \"?l' \\<noteq> Leaf\" using not_Leaf_if_not_balanced1 by auto\n      then obtain k ll' al' rl' where [simp]: \"?l' = (Node ll' (al', k) rl')\"\n        by(meson neq_Leaf2_iff)\n      show ?thesis\n      proof (cases \"single rl' ll'\")\n        case True thus ?thesis using Node size_insert[of x l]\n          by (auto split: if_splits)\n      next\n        case isDouble: False\n        then obtain k llr' alr' rlr' where [simp]: \"rl' = (Node llr' (alr', k) rlr')\"\n          using not_Leaf_if_not_single tree2_cases by blast\n        show ?thesis using isDouble Node size_insert[of x l]\n          by (auto split: if_splits)\n      qed\n    qed\n  next\n    case [simp]: GT\n    let ?r' = \"insert x r\"\n    show ?thesis\n    proof (cases \"balanced1 l ?r'\")\n      case True thus ?thesis using Node size_insert[of x r] by auto\n    next\n      case [simp]: False\n      hence \"?r' \\<noteq> Leaf\" using not_Leaf_if_not_balanced1 by auto\n      then obtain k lr' ar' rr' where [simp]: \"?r' = (Node lr' (ar', k) rr')\"\n        by(meson neq_Leaf2_iff)\n      show ?thesis\n      proof (cases \"single lr' rr'\")\n        case True thus ?thesis using Node size_insert[of x r]\n          by (auto split: if_splits)\n      next\n        case isDouble: False\n        hence \"lr' \\<noteq> Leaf\" using not_Leaf_if_not_single by auto\n        thus ?thesis\n          using Node isDouble size_insert[of x r]\n          by (auto simp: neq_Leaf2_iff split: if_splits)\n      qed\n    qed\n  qed\nqed\n\ndeclare [[smt_nat_as_int]]\n\ntext \\<open>\n  Show that invariant is preserved by deletion in the left/right subtree:\n\\<close>\n\nlemma wbt_balanceL:\n  assumes \"wbt (Node l (a, n) r)\" \"wbt l'\" \"size l = size l' + 1\"\n  shows \"wbt (balanceL l' a' r)\"\nproof -\n  have rl'Balanced: \"balanced1 r l'\" using assms by auto\n  have rBalanced: \"wbt r\" using assms(1) by simp\n  show ?thesis\n  proof (cases \"balanced1 l' r\")\n    case True thus ?thesis using assms(2) rBalanced rl'Balanced by auto\n  next\n    case notBalanced: False\n    hence \"r \\<noteq> Leaf\" using not_Leaf_if_not_balanced1 by auto\n    then obtain k lr ar rr where [simp]: \"r = Node lr (ar, k) rr\" by(meson neq_Leaf2_iff)\n    show ?thesis\n    proof (cases \"single lr rr\")\n      case single: True\n      have \"singly_balanced_arith (size l') (size lr) (size rr)\"\n        using assms(1) notBalanced rl'Balanced rBalanced single assms\n        by (simp) (smt?)\n      thus ?thesis using notBalanced single assms(2) rBalanced by simp\n    next\n      case isDouble: False\n      hence \"lr \\<noteq> Leaf\" using not_Leaf_if_not_single by auto\n      then obtain k2 llr alr rlr where [simp]: \"lr = (Node llr (alr, k2) rlr)\"\n        by(meson neq_Leaf2_iff)\n      have \"doubly_balanced_arith (size l') (size llr) (size rlr) (size rr)\"\n        using assms(1) notBalanced rl'Balanced rBalanced isDouble assms(2,3)\n        apply (auto) apply((thin_tac \"_ = _\")+, smt)? done\n      thus ?thesis using notBalanced isDouble assms(2) rBalanced by simp\n    qed\n  qed\nqed\n\nlemma wbt_balanceR:\n  assumes \"wbt (Node l (a, n) r)\" \"wbt r'\" \"size r = size r' + 1\"\n  shows \"wbt (balanceR l a' r')\"\nproof -\n  have lr'Balanced: \"balanced1 l r'\" using assms by auto\n  have lBalanced: \"wbt l\" using assms(1) by simp\n  show ?thesis\n  proof (cases \"balanced1 r' l\")\n    case True thus ?thesis using assms(2) lBalanced lr'Balanced by simp\n  next\n    case notBalanced: False\n    hence \"l \\<noteq> Leaf\" using not_Leaf_if_not_balanced1 by auto\n    then obtain k ll al rl where [simp]: \"l = (Node ll (al, k) rl)\" by(meson neq_Leaf2_iff)\n    show ?thesis\n    proof (cases \"single rl ll\")\n      case single: True\n      have \"singly_balanced_arith (size rl) (size r') (size ll)\"\n        using assms(1) notBalanced lr'Balanced lBalanced single assms(2,3)\n        apply (auto) apply((thin_tac \"_ = _\")+, smt)? done\n      thus ?thesis using assms(2) lBalanced notBalanced single by simp\n    next\n      case isDouble: False\n      hence \"rl \\<noteq> Leaf\" using not_Leaf_if_not_single by auto\n      then obtain k lrl arl rrl where [simp]: \"rl = (Node lrl (arl, k) rrl)\"\n        by(meson neq_Leaf2_iff)\n      have \"doubly_balanced_arith (size ll) (size lrl) (size rrl) (size r')\"\n        using assms(1) notBalanced lr'Balanced lBalanced isDouble assms(2,3)\n        apply (auto) apply((thin_tac \"_ = _\")+, smt)? done\n      thus ?thesis using assms(2) lBalanced notBalanced isDouble by simp\n    qed\n  qed\nqed\n\nlemma wbt_split_min: \"t \\<noteq> Leaf \\<Longrightarrow> wbt t \\<Longrightarrow> wbt (snd (split_min t))\"\nproof (induction t rule: split_min.induct)\n  case (1 l a m r)\n  show ?case\n  proof (cases l rule: tree2_cases)\n    case Leaf thus ?thesis using \"1.prems\"(2) by simp\n  next\n    case (Node ll al n rl)\n    let ?l' = \"snd (split_min (Node ll (al, n) rl))\"\n    have delBalanceL: \"snd (split_min (Node l (a, m) r)) = balanceL ?l' a r\"\n      using Node by(auto split: prod.splits)\n    have \"wbt ?l'\" using \"1\"(1) \"1.prems\"(2) Node by auto\n    moreover have \"size l = size ?l' + 1\"\n      using Node size_split_min by (metis Suc_eq_plus1 neq_Leaf2_iff)\n    ultimately have \"wbt (balanceL ?l' a r)\"\n      by (meson \"1.prems\"(2) wbt_balanceL)\n    thus ?thesis using delBalanceL by auto\n  qed\nqed (blast)\n\nlemma wbt_del_max: \"t \\<noteq> Leaf \\<Longrightarrow> wbt t \\<Longrightarrow> wbt (snd (del_max t))\"\nproof (induction t rule: del_max.induct)\n  case (1 l a m r)\n  show ?case\n  proof (cases r rule: tree2_cases)\n    case Leaf thus ?thesis using \"1.prems\"(2) by simp\n  next\n    case (Node lr ar n rr)\n    then obtain r' where delMaxR: \"r' = snd (del_max (Node lr (ar, n) rr))\"\n      by simp\n    hence delBalanceR: \"snd (del_max (Node l (a, m) r)) = balanceR l a r'\"\n      using Node by(auto split: prod.splits)\n    have \"wbt r'\" using \"1\"(1) \"1.prems\"(2) Node delMaxR by auto\n    moreover have \"size r = size r' + 1\" using size_del_max Node delMaxR\n      by (metis Suc_eq_plus1 tree.simps(3))\n    ultimately have \"wbt (balanceR l a r')\"\n      using wbt_balanceR by (metis \"1.prems\"(2))\n    thus ?thesis using delBalanceR by auto\n  qed\nqed (blast)\n\nlemma wbt_delete: \"wbt t \\<Longrightarrow> wbt (delete x t)\"\nproof (induction t rule: tree2_induct)\n  case Leaf thus ?case by simp\nnext\n  case (Node l a n r)\n  show ?case\n  proof (cases \"isin (Node l (a, n) r) x\")\n    case False thus ?thesis using Node.prems delete_id_if_wbt_notin by metis\n  next\n    case isin: True\n    thus ?thesis\n    proof (cases \"cmp x a\")\n      case LT\n      let ?l' = \"delete x l\"\n      have \"size l = size ?l' + 1\"\n        using LT isin by (auto simp: size_delete_if_isin)\n      hence \"wbt (balanceL ?l' a r)\"\n        using Node.IH(1) Node.prems by (fastforce intro: wbt_balanceL)\n      thus ?thesis by (simp add: LT)\n    next\n      case GT\n      let ?r' = \"delete x r\"\n      have \"wbt ?r'\" using Node.IH(2) Node.prems by simp\n      moreover have \"size r = size ?r' + 1\"\n        using GT Node.prems isin size_delete_if_isin by auto\n      ultimately have \"wbt (balanceR l a ?r')\"\n        by (meson Node.prems wbt_balanceR)\n      thus ?thesis by (simp add: GT)\n    next\n      case [simp]: EQ\n      hence xCombine: \"delete x (Node l (a, n) r) = combine l r\" by simp\n      {\n        assume \"l = Leaf\" \"r = Leaf\" hence ?thesis by simp\n      }\n      moreover\n      {\n        assume \"l = Leaf\" \"r \\<noteq> Leaf\"\n        hence ?thesis using Node.prems by (auto simp: neq_Leaf2_iff)\n      }\n      moreover\n      {\n        assume \"l \\<noteq> Leaf\" \"r = Leaf\"\n        hence ?thesis using Node.prems by (auto simp: neq_Leaf2_iff)\n      }\n      moreover\n      {\n        assume lrNotLeaf: \"l \\<noteq> Leaf\" \"r \\<noteq> Leaf\"\n        then obtain kl kr ll al rl lr ar rr\n          where [simp]: \"l = (Node ll (al, kl) rl)\" \"r = (Node lr (ar, kr) rr)\"\n          by (meson neq_Leaf2_iff)\n        have ?thesis\n        proof (cases \"size l > size r\")\n          case True\n          obtain lMax l' where letMax: \"del_max l = (lMax, l')\"\n            by (metis prod.exhaust)\n          hence balanceLeft: \"combine l r = balanceL l' lMax r\"\n            using \\<open>size l > size r\\<close> by (simp)\n          have \"wbt l'\"\n            using Node.prems wbt_del_max[OF lrNotLeaf(1)] letMax\n            by (metis wbt.simps(2) snd_conv)\n          moreover have \"size l = size l' + 1\"\n            using size_del_max[OF lrNotLeaf(1)] letMax by (simp)\n          ultimately have \"wbt(balanceL l' lMax r)\"\n            using wbt_balanceL by (metis Node.prems)\n          thus ?thesis using balanceLeft by simp\n        next\n          case False\n          obtain rMin r' where letMin: \"split_min r = (rMin, r')\"\n            by (metis prod.exhaust)\n          hence balanceRight: \"combine l r = balanceR l rMin r'\"\n            using \\<open>\\<not> size l > size r\\<close> by (simp)\n          have \"wbt r'\"\n            using Node.prems wbt_split_min[OF lrNotLeaf(2)] letMin\n            by (metis wbt.simps(2) snd_conv)\n          moreover have \"size r = size r' + 1\"\n            using size_split_min[OF lrNotLeaf(2)] letMin by simp\n          ultimately have \"wbt(balanceR l rMin r')\"\n            using wbt_balanceR by (metis Node.prems)\n          thus ?thesis using balanceRight by simp\n        qed\n      }\n      ultimately show ?thesis by blast\n    qed\n  qed\nqed\n\nsubsection \\<open>The final correctness proof\\<close>\n\ninterpretation S: Set_by_Ordered\nwhere empty = Leaf and isin = isin and insert = insert and delete = delete\nand inorder = inorder and inv = wbt\nproof (standard, goal_cases)\n  case 1 show ?case by simp\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 show ?case by simp\nnext\n  case 6 thus ?case using wbt_insert by blast\nnext\n  case 7 thus ?case using wbt_delete 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/Weight_Balanced_Trees/Weight_Balanced_Trees.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8104789040926008, "lm_q2_score": 0.8723473697001441, "lm_q1q2_score": 0.7070191401826357}}
{"text": "(*<*)\ntheory Typing\n  imports Formula\nbegin\n(*>*)\n\nsection \\<open>Typing\\<close>\n\nsubsection \\<open>Types\\<close>\n\ndatatype ty = TInt | TFloat | TString\n\n\nfun ty_of :: \"event_data \\<Rightarrow> ty\" where\n  \"ty_of (EInt _) = TInt\"\n| \"ty_of (EFloat _) = TFloat\"\n| \"ty_of (EString _) = TString\"\n\n\ndefinition \"numeric_ty = {TInt, TFloat}\"\n\nsubsection \\<open>Terms\\<close>\n\ntype_synonym tyenv = \"nat \\<Rightarrow> ty\"\n\ninductive wty_trm :: \"tyenv \\<Rightarrow> Formula.trm \\<Rightarrow> ty \\<Rightarrow> bool\" (\"(_)/ \\<turnstile> (_) :: _\" [50,50,50] 50)\n  for E where\n  Var: \"E x = t \\<Longrightarrow> E \\<turnstile> Formula.Var x :: t\"\n| Const: \"ty_of x = t \\<Longrightarrow> E \\<turnstile> Formula.Const x :: t\"\n| Plus: \"E \\<turnstile> x :: t \\<Longrightarrow> E \\<turnstile> y :: t \\<Longrightarrow> t \\<in> numeric_ty \\<Longrightarrow> E \\<turnstile> Formula.Plus x y :: t\"\n| Minus: \"E \\<turnstile> x :: t \\<Longrightarrow> E \\<turnstile> y :: t \\<Longrightarrow> t \\<in> numeric_ty \\<Longrightarrow> E \\<turnstile> Formula.Minus x y :: t\"\n| UMinus: \"E \\<turnstile> x :: t \\<Longrightarrow> t \\<in> numeric_ty \\<Longrightarrow> E \\<turnstile>  Formula.UMinus x :: t\"\n| Mult: \"E \\<turnstile> x :: t \\<Longrightarrow> E \\<turnstile> y :: t \\<Longrightarrow> t \\<in> numeric_ty \\<Longrightarrow> E \\<turnstile> Formula.Mult x y :: t\"\n| Div: \"E \\<turnstile> x :: t \\<Longrightarrow> E \\<turnstile> y :: t \\<Longrightarrow> t \\<in> numeric_ty \\<Longrightarrow> E \\<turnstile> Formula.Div x y :: t\"\n| Mod:\"E \\<turnstile> x :: TInt \\<Longrightarrow> E \\<turnstile> y :: TInt \\<Longrightarrow> E \\<turnstile> Formula.Mod x y :: TInt\"\n| F2i: \"E \\<turnstile> x ::  TFloat \\<Longrightarrow> E \\<turnstile> Formula.F2i x :: TInt\"\n| I2f: \"E \\<turnstile> x ::  TInt \\<Longrightarrow> E \\<turnstile> Formula.I2f x :: TFloat\"\n\n\nlemma ty_of_plus: \"ty_of x = t \\<Longrightarrow> ty_of y = t \\<Longrightarrow> t \\<in> numeric_ty \\<Longrightarrow> ty_of (x + y) = t\"\n  by (cases x; cases y) (simp_all add: numeric_ty_def)\n\nlemma ty_of_minus: \"ty_of x = t \\<Longrightarrow> ty_of y = t \\<Longrightarrow> t \\<in> numeric_ty \\<Longrightarrow> ty_of (x - y) = t\"\n  by (cases x; cases y) (simp_all add: numeric_ty_def)\n\nlemma ty_of_uminus: \"ty_of x = t \\<Longrightarrow> ty_of y = t \\<Longrightarrow> t \\<in> numeric_ty \\<Longrightarrow> ty_of (-x) = t\"\n  by (cases x) (simp_all add: numeric_ty_def)\nlemma ty_of_mult: \"ty_of x = t \\<Longrightarrow> ty_of y = t \\<Longrightarrow> t \\<in> numeric_ty \\<Longrightarrow> ty_of (x * y) = t\"\n  by (cases x; cases y) (simp_all add: numeric_ty_def)\n\nlemma ty_of_div: \"ty_of x = t \\<Longrightarrow> ty_of y = t \\<Longrightarrow> t \\<in> numeric_ty \\<Longrightarrow> ty_of (x div y) = t\"\n  by (cases x; cases y) (simp_all add: numeric_ty_def)\n\nlemma ty_of_mod: \"ty_of x = TInt \\<Longrightarrow> ty_of y = TInt \\<Longrightarrow> ty_of (x mod y) = TInt\"\n  by (cases x; cases y) simp_all\n\nlemma ty_of_eval_trm: \"E \\<turnstile> x :: t \\<Longrightarrow> \\<forall>y\\<in>fv_trm x. ty_of (v ! y) = E y \\<Longrightarrow> \nty_of (Formula.eval_trm v x) = t\"\n  by (induction pred: wty_trm) (simp_all add: ty_of_plus ty_of_minus ty_of_uminus \n      ty_of_mult ty_of_div ty_of_mod)\n\nlemma  value_of_eval_trm: \"E \\<turnstile> x :: TInt \\<Longrightarrow> \\<forall>y\\<in>fv_trm x. ty_of (v ! y) = E y \\<Longrightarrow> \n\\<exists> z .(Formula.eval_trm v x) = EInt z\"\n\"E \\<turnstile> x :: TFloat \\<Longrightarrow> \\<forall>y\\<in>fv_trm x. ty_of (v ! y) = E y \\<Longrightarrow> \n\\<exists> z .(Formula.eval_trm v x) = EFloat z\"\n\"E \\<turnstile> x :: TString \\<Longrightarrow> \\<forall>y\\<in>fv_trm x. ty_of (v ! y) = E y \\<Longrightarrow> \n\\<exists> z .(Formula.eval_trm v x) = EString z\"\n  subgoal using ty_of_eval_trm by (cases \"Formula.eval_trm v x\") fastforce+\n  subgoal using ty_of_eval_trm by (cases \"Formula.eval_trm v x\") fastforce+\n  subgoal using ty_of_eval_trm by (cases \"Formula.eval_trm v x\") fastforce+\n  done\n\nlemma wty_trm_fv_cong:\n  assumes \"\\<And>y. y \\<in> fv_trm x \\<Longrightarrow> E y = E' y\"\n  shows \"E \\<turnstile> x :: t \\<longleftrightarrow> E' \\<turnstile> x :: t\"\nproof -\n  have \"E \\<turnstile> x :: t \\<Longrightarrow> (\\<And>y. y \\<in> fv_trm x \\<Longrightarrow> E y = E' y) \\<Longrightarrow> E' \\<turnstile> x :: t\" for E E'\n    by (induction pred: wty_trm) (auto intro: wty_trm.intros)\n  with assms show ?thesis by auto\nqed\n\n\nsubsection \\<open>Formulas\\<close>\n\ntype_synonym sig = \"Formula.name \\<rightharpoonup> ty list\"\n\ndefinition wty_tuple :: \"ty list \\<Rightarrow> event_data list \\<Rightarrow> bool\" where\n  \"wty_tuple = list_all2 (\\<lambda>t x. ty_of x = t)\"\n\ndefinition wty_event :: \"sig \\<Rightarrow> Formula.name \\<Rightarrow> event_data list \\<Rightarrow> bool\" where\n  \"wty_event S p xs \\<longleftrightarrow> (case S p of Some ts \\<Rightarrow> wty_tuple ts xs | None \\<Rightarrow> False)\"\n\ndefinition wty_envs :: \"sig \\<Rightarrow> Formula.trace \\<Rightarrow> (Formula.name \\<rightharpoonup> nat \\<Rightarrow> event_data list set) \\<Rightarrow> bool\" where\n  \"wty_envs S \\<sigma> V \\<longleftrightarrow> (\\<forall>i.\n    (\\<forall>(p,xs)\\<in>\\<Gamma> \\<sigma> i. p \\<notin> dom V \\<longrightarrow> wty_event S p xs) \\<and>\n    (\\<forall>p\\<in>dom V. \\<forall>xs\\<in>the (V p) i. wty_event S p xs))\"\n\nabbreviation wty_trace :: \"sig \\<Rightarrow> Formula.trace \\<Rightarrow> bool\" where\n  \"wty_trace S \\<sigma> \\<equiv> wty_envs S \\<sigma> Map.empty\"\n\ndefinition wty_db :: \"sig \\<Rightarrow> (Formula.name \\<times> event_data list) set \\<Rightarrow> bool\" where\n  \"wty_db S db \\<longleftrightarrow> (\\<forall>(p, xs) \\<in> db. wty_event S p xs)\"\n\nlift_definition wty_prefix :: \"sig \\<Rightarrow> Formula.prefix \\<Rightarrow> bool\" is\n  \"\\<lambda>S \\<pi>. \\<forall>x\\<in>set \\<pi>. wty_db S (fst x)\" .\n\nlemma wty_pnil: \"wty_prefix S pnil\"\n  by (transfer fixing: S) simp\n\nlemma wty_psnoc: \"wty_prefix S \\<pi> \\<Longrightarrow> wty_db S (fst x) \\<Longrightarrow> last_ts \\<pi> \\<le> snd x \\<Longrightarrow>\n  wty_prefix S (psnoc \\<pi> x)\"\n  by (transfer fixing: S x) simp\n\nlemma wty_envs_\\<Gamma>_D: \"wty_envs S \\<sigma> V \\<Longrightarrow> p \\<notin> dom V \\<Longrightarrow> (p, xs) \\<in> \\<Gamma> \\<sigma> i \\<Longrightarrow> S p = Some ts \\<Longrightarrow>\n  wty_tuple ts xs\"\n  by (fastforce simp: wty_envs_def wty_event_def split: option.splits)\n\nlemma wty_envs_V_D: \"wty_envs S \\<sigma> V \\<Longrightarrow> p \\<in> dom V \\<Longrightarrow> xs \\<in> the (V p) i \\<Longrightarrow> S p = Some ts \\<Longrightarrow>\n  wty_tuple ts xs\"\n  by (fastforce simp: wty_envs_def wty_event_def split: option.splits)\n\nfind_theorems \"Regex.pred_regex\"\ndeclare regex.pred_mono[mono]\n\ndefinition agg_env :: \"tyenv \\<Rightarrow> ty list \\<Rightarrow> tyenv \" where\n\"agg_env E tys =  (\\<lambda>z. if z < length tys then tys ! z else E (z - length tys))\"\n\nfun t_res :: \"Formula.agg_type \\<Rightarrow> ty \\<Rightarrow> ty\" where\n\"t_res Formula.Agg_Sum t = t\"\n| \"t_res Formula.Agg_Cnt _ = TInt\"\n| \"t_res Formula.Agg_Avg _ = TFloat\"\n| \"t_res agg_type.Agg_Med _ = TFloat \"\n| \"t_res Formula.Agg_Min t = t\"\n| \"t_res Formula.Agg_Max t = t\"\n\nfun agg_trm_type :: \"Formula.agg_type \\<Rightarrow> ty set\" where\n\"agg_trm_type Formula.Agg_Sum = numeric_ty\"\n| \"agg_trm_type Formula.Agg_Cnt = UNIV\"\n| \"agg_trm_type Formula.Agg_Avg = numeric_ty\"\n| \"agg_trm_type Formula.Agg_Med = numeric_ty\"\n| \"agg_trm_type Formula.Agg_Min = UNIV\"\n| \"agg_trm_type Formula.Agg_Max = UNIV\"\n\n\ninductive wty_formula :: \"sig \\<Rightarrow> tyenv \\<Rightarrow> ty Formula.formula \\<Rightarrow> bool\" (\"(_),/ (_)/ \\<turnstile> (_)\" [50,50,50] 50) where\n  Pred: \"S p = Some tys \\<Longrightarrow> list_all2 (\\<lambda>tm ty. E \\<turnstile> tm :: ty) tms tys \\<Longrightarrow> S, E \\<turnstile> Formula.Pred p tms\"\n| Let: \"S, E' \\<turnstile> \\<phi> \\<Longrightarrow> S(p \\<mapsto> tabulate E' 0 (Formula.nfv \\<phi>)), E \\<turnstile> \\<psi> \\<Longrightarrow> S, E \\<turnstile> Formula.Let p \\<phi> \\<psi>\"\n| Eq: \"E \\<turnstile> x :: t \\<Longrightarrow> E \\<turnstile> y :: t \\<Longrightarrow> S, E \\<turnstile> Formula.Eq x y\"\n| Less: \"E \\<turnstile> x :: t \\<Longrightarrow> E \\<turnstile> y :: t \\<Longrightarrow> S, E \\<turnstile> Formula.Less x y\"\n| LessEq: \"E \\<turnstile> x :: t \\<Longrightarrow> E \\<turnstile> y :: t \\<Longrightarrow> S, E \\<turnstile> Formula.LessEq x y\"\n| Neg: \"S, E \\<turnstile> \\<phi> \\<Longrightarrow> S, E \\<turnstile> Formula.Neg \\<phi>\"\n| Or: \"S, E \\<turnstile> \\<phi> \\<Longrightarrow> S, E \\<turnstile> \\<psi> \\<Longrightarrow> S, E \\<turnstile> Formula.Or \\<phi> \\<psi>\"\n| And: \"S, E \\<turnstile> \\<phi> \\<Longrightarrow> S, E \\<turnstile> \\<psi> \\<Longrightarrow> S, E \\<turnstile> Formula.And \\<phi> \\<psi>\" \n| Ands: \"\\<forall>\\<phi> \\<in> set \\<phi>s. S, E \\<turnstile> \\<phi> \\<Longrightarrow> S, E \\<turnstile> Formula.Ands \\<phi>s\"\n| Exists: \"S, case_nat t E \\<turnstile> \\<phi> \\<Longrightarrow> S, E \\<turnstile> Formula.Exists t \\<phi>\"\n| Agg: \" E y =  t_res agg_type t \\<Longrightarrow> agg_env E tys  \\<turnstile> f :: t \\<Longrightarrow> S, agg_env E tys \\<turnstile> \\<phi>  \\<Longrightarrow>\n   t \\<in> agg_trm_type agg_type \\<Longrightarrow> ty_of d = t_res agg_type t \\<Longrightarrow>\n          S, E \\<turnstile> Formula.Agg y (agg_type, d) tys f \\<phi>\"\n| Prev: \"S, E \\<turnstile> \\<phi> \\<Longrightarrow> S, E \\<turnstile> Formula.Prev \\<I> \\<phi>\"\n| Next: \"S, E \\<turnstile> \\<phi> \\<Longrightarrow> S, E \\<turnstile> Formula.Next \\<I> \\<phi>\"\n| Since: \"S, E \\<turnstile> \\<phi> \\<Longrightarrow> S, E \\<turnstile> \\<psi> \\<Longrightarrow> S, E \\<turnstile> Formula.Since \\<phi> \\<I> \\<psi>\" \n| Until: \"S, E \\<turnstile> \\<phi> \\<Longrightarrow> S, E \\<turnstile> \\<psi> \\<Longrightarrow> S, E \\<turnstile> Formula.Until \\<phi> \\<I> \\<psi>\" \n| MatchP: \"Regex.pred_regex (\\<lambda>\\<phi>. S, E \\<turnstile> \\<phi>) r \\<Longrightarrow> S, E \\<turnstile> Formula.MatchP I r\"\n| MatchF: \"Regex.pred_regex (\\<lambda>\\<phi>. S, E \\<turnstile> \\<phi>) r \\<Longrightarrow> S, E \\<turnstile> Formula.MatchF I r\"\n\nlemma wty_regexatms_atms:\n  assumes \"safe_formula (Formula.MatchP I r) \\<or> safe_formula (Formula.MatchF I r)\"\n  shows \"(\\<forall>x \\<in> Regex.atms r. S, E \\<turnstile> x) \\<longleftrightarrow> (\\<forall>x \\<in> atms r. S, E \\<turnstile> x)\"\nproof -\n  have \"\\<forall>x \\<in> Regex.atms r. S, E \\<turnstile> x\" if \"\\<forall>x \\<in> atms r. S, E \\<turnstile> x\"\n    \"Regex.safe_regex fv (\\<lambda>g \\<phi>. safe_formula \\<phi> \\<or>\n      (g = Lax \\<and> (case \\<phi> of Formula.Neg \\<phi>' \\<Rightarrow> safe_formula \\<phi>' | _ \\<Rightarrow> False))) m g r\" for m g\n    using that\n    apply (induction r arbitrary: m g)\n        apply auto\n    subgoal for x\n      by (cases \"safe_formula x\") (auto split: formula.splits intro: wty_formula.intros)\n    subgoal for r1 r2 m g x\n      by (cases m) auto\n    subgoal for r1 r2 m g x\n      by (cases m) auto\n    done\n  moreover have \"\\<forall>x \\<in> Regex.atms r. S, E \\<turnstile> x \\<Longrightarrow> \\<forall>x \\<in> atms r. S, E \\<turnstile> x\"\n    by (induction r) (auto split: formula.splits elim: wty_formula.cases)\n  ultimately show ?thesis\n    using assms\n    by fastforce\nqed\n\nlemma wty_formula_fv_cong:\n  assumes \"\\<And>y. y \\<in> fv \\<phi> \\<Longrightarrow> E y = E' y\"\n  shows \"S, E \\<turnstile> \\<phi> \\<longleftrightarrow> S, E' \\<turnstile> \\<phi>\"\nproof -\n  have \"S, E \\<turnstile> \\<phi> \\<Longrightarrow> (\\<And>y. y \\<in> fv \\<phi> \\<Longrightarrow> E y = E' y) \\<Longrightarrow> S, E' \\<turnstile> \\<phi>\" for E E'\n  proof (induction arbitrary: E' pred: wty_formula)\n    case (Pred S p tys E tms)\n    then show ?case\n      by (fastforce intro!: wty_formula.Pred\n          elim!: list.rel_mono_strong wty_trm_fv_cong[THEN iffD1, rotated])\n  next \n    case(Let S E'' \\<phi>  p E  \\<psi>)\n    then show ?case\n      using fvi.simps(2) wty_formula.Let by blast\n  next\n    case(Eq E x t y' S)\n    then show ?case by (fastforce intro!: wty_formula.Eq\n          elim!: wty_trm_fv_cong[THEN iffD1, rotated])\n  next\n     case(Less E x t y' S)\n    then show ?case by (fastforce intro!: wty_formula.Less\n          elim!:  wty_trm_fv_cong[THEN iffD1, rotated])\n  next\n    case(LessEq E x t y' S)\n    then show ?case by (fastforce intro!: wty_formula.LessEq\n          elim!: wty_trm_fv_cong[THEN iffD1, rotated])\n  next\n    case(Neg E S \\<phi>)\n    then show ?case by (simp add: wty_formula.Neg)\n  next \n    case(Or E S \\<phi> \\<psi>)\n    thus ?case by (simp add: wty_formula.Or)\n  next \n    case(And E S \\<phi> \\<psi>)\n    thus ?case by (simp add: wty_formula.And)\n  next \n    case(Ands E S \\<phi>s)\n    from this show ?case  by (metis  wty_formula.Ands fv_subset_Ands subset_eq)\n  next\n    case (Exists S t E \\<phi>)\n    then show ?case\n      by (fastforce simp: fvi_Suc intro!: wty_formula.Exists[where t=t] split: nat.split)\n  next\n    case (Agg E s agg_type t tys f S \\<phi> d)\n    from Agg.prems Agg.hyps(1) have part1: \"E' s = t_res agg_type t\" by auto\n    from Agg  have  aggenv: \"\\<forall>y\\<in> Formula.fvi_trm (length tys) f. E y = E' y\" by (auto simp: agg_env_def)\n    from this have \"\\<forall>y\\<in> Formula.fvi_trm 0 f. y\\<ge> length tys \\<longrightarrow>  E (y - length tys)  = E' (y - length tys) \" by (meson fvi_trm_iff_fv_trm fvi_trm_minus fvi_trm_plus)\n    from this  Agg.hyps(2) have  \"(\\<lambda>z. if z < length tys then tys ! z else E' (z - length tys)) \\<turnstile> f :: t\" using wty_trm_fv_cong\n    by (smt (verit, del_insts) agg_env_def not_less) \n  from this have part2: \"agg_env E' tys \\<turnstile> f :: t\" by (auto simp add: agg_env_def)\n\n    from Agg have  \"\\<forall>y\\<in> Formula.fvi (length tys) \\<phi>. E y = E' y\" by auto\n    from this have \"\\<forall>y\\<in> Formula.fvi 0 \\<phi>. y\\<ge> length tys \\<longrightarrow>  (E (y - length tys)  = E' (y - length tys))\" using fvi_minus[where b=0] by auto\n    from this Agg have part3: \" S, agg_env E' tys \\<turnstile> \\<phi>\" by (auto simp: agg_env_def)\n    from part1 part2 part3 Agg.hyps(5) Agg.hyps(4) show ?case by (simp add: wty_formula.Agg)\n  next\n    case (Prev S E \\<phi> \\<I>)\n    thus ?case by (simp add: wty_formula.Prev)\n  next\n    case (Next S E \\<phi>)\n    thus ?case by (simp add: wty_formula.Next)\n\n  next \n    case (Since S E \\<phi>)\n    thus ?case by (simp add: wty_formula.Since)\n  next\n    case (Until S E \\<phi>)\n    thus ?case by (simp add: wty_formula.Until)\n  next \n    case (MatchP S E r I)\n    from this have \"regex.pred_regex (\\<lambda>\\<phi>. S, E' \\<turnstile> \\<phi>) r\" by (induction r) auto\n    thus ?case by (auto simp add: wty_formula.MatchP)\n next \n    case (MatchF S E r I)\n    from this have \"regex.pred_regex (\\<lambda>\\<phi>. S, E' \\<turnstile> \\<phi>) r\" by (induction r) auto\n    thus ?case by (auto simp add: wty_formula.MatchF)\n  qed \n  with assms show ?thesis by auto\nqed\n\nlemma match_sat_fv: assumes \"safe_regex temp Strict r\"\n    \"Regex.match (Formula.sat \\<sigma> V v) r j i\"\n    \"x \\<in> fv (formula.MatchP I r) \\<or> x \\<in>fv (formula.MatchF I r)\"\n  shows \"\\<exists>\\<phi>\\<in>atms r. \\<exists>k. Formula.sat \\<sigma> V v k \\<phi> \\<and> x \\<in> fv \\<phi>\"\n  using assms\n  proof (induction r arbitrary:i j)\n\n    case (Plus r1 r2)\n  moreover obtain k where \"\\<exists>j. Regex.match (Formula.sat \\<sigma> V v) r1 j k \\<or>  Regex.match (Formula.sat \\<sigma> V v) r2 j k\" using  Plus.prems(2)  by auto\n  moreover {\n    assume assm: \"\\<exists>j. Regex.match (Formula.sat \\<sigma> V v) r1 j k\"\n    then have ?case using Plus.prems(1,3) Plus.IH(1)  by (fastforce simp add: atms_def) \n  } moreover {\n    assume assm: \"\\<exists>j. Regex.match (Formula.sat \\<sigma> V v) r2 j k\"\n    from this have ?case using Plus.prems(1,3) Plus.IH(2) by (fastforce simp add: atms_def)\n  }\n  ultimately show ?case by auto\nnext\n  case (Times r1 r2)\n  then show ?case  using Times.prems match_le Times.IH  by (cases temp) fastforce+\nqed  auto\n\nlemma finite_fst: assumes \"finite  {(x,f x) | x. P x}\" shows \"finite {x . P x}\"\nproof -\n  have  fstSet: \" fst ` {(x, f x) |x. P x} = {x . P x}\" by (auto simp add: image_iff)\n  show ?thesis using assms fstSet finite_image_iff[of fst \"{(x,f x) | x. P x}\"] by (auto simp add: inj_on_def)\nqed\n\n\nlemma set_of_flatten_multiset:\n  assumes \"M = {(x, ecard Zs) | x Zs. Zs = f x \\<and> Zs \\<noteq> {}}\" \"finite {x. f x \\<noteq> {}}\"\n  shows \"set (flatten_multiset M) \\<subseteq> fst ` M\"\nproof -\n  have fin_M: \"finite M\"\n    using assms(2)\n    by (auto simp: assms(1))\n  obtain c :: \"(event_data \\<times> enat) comparator\" where c: \"ID ccompare = Some c\"\n    by (auto simp: ID_def ccompare_prod_def ccompare_event_data_def ccompare_enat_def)\n  show ?thesis\n    using fin_M image_iff\n    by (fastforce simp: flatten_multiset_def csorted_list_of_set_def c\n        linorder.set_sorted_list_of_set[OF ID_ccompare[OF c]])\nqed\n\nlocale sat_general =\n  fixes \nundef_plus :: \"event_data \\<Rightarrow> event_data \\<Rightarrow> event_data\" and\nundef_minus :: \"event_data \\<Rightarrow> event_data \\<Rightarrow> event_data\" and\nundef_uminus :: \" event_data \\<Rightarrow> event_data\" and\nundef_times :: \"event_data \\<Rightarrow> event_data \\<Rightarrow> event_data\" and\nundef_divide :: \"event_data \\<Rightarrow> event_data \\<Rightarrow> event_data\" and\nundef_modulo :: \"event_data \\<Rightarrow> event_data \\<Rightarrow> event_data\"  and\nundef_double_of_event_data :: \"event_data \\<Rightarrow> double\" and\nundef_double_of_event_data_agg :: \"event_data \\<Rightarrow> double\" and\nundef_integer_of_event_data :: \"event_data \\<Rightarrow> integer\" and\nundef_less_eq :: \"event_data \\<Rightarrow> event_data \\<Rightarrow> bool\"\nassumes undef_plus_sound:  \"\\<And>x y. undef_plus (EInt x) (EInt y) = EInt x + EInt y\" \n    \"\\<And> x y . undef_plus (EFloat x) (EFloat y) = EFloat x + EFloat y\"\nassumes undef_minus_sound:  \"\\<And>x y. undef_minus (EInt x) (EInt y) = EInt x - EInt y\" \n    \"\\<And> x y . undef_minus (EFloat x) (EFloat y) = EFloat x - EFloat y\"\nassumes undef_uminus_sound:  \"\\<And>x . undef_uminus (EInt x) = - EInt x\"\n   \"\\<And> x. undef_uminus (EFloat x) = - EFloat x \"\nassumes undef_times_sound:  \"\\<And>x y.  undef_times (EInt x) (EInt y) = EInt x * EInt y\" \n    \"\\<And> x y . undef_times (EFloat x) (EFloat y) = EFloat x * EFloat y\"\nassumes undef_divide_sound:  \"\\<And>x y. undef_divide (EInt x) (EInt y) = EInt x div EInt y\" \n    \"\\<And> x y .  undef_divide (EFloat x) (EFloat y) = EFloat x div EFloat y\"\nassumes undef_modulo_sound:  \"\\<And>x y.  undef_modulo (EInt x) (EInt y) = EInt x mod EInt y\"  \n\nassumes undef_double_of_event_data_sound: \"\\<And>x.  undef_double_of_event_data (EInt x) = double_of_event_data (EInt x)\"\nassumes undef_double_of_event_data_agg_sound: \"\\<And>x.  undef_double_of_event_data_agg (EInt x) = double_of_event_data_agg (EInt x)\"\n\"\\<And>x.  undef_double_of_event_data_agg (EFloat x) = double_of_event_data_agg (EFloat x)\"\nassumes undef_integer_of_event_data_sound: \"\\<And>x. undef_integer_of_event_data (EFloat x) = integer_of_event_data (EFloat x)\"\n\nassumes undef_less_eq_sound: \"\\<And>x y. undef_less_eq (EInt x) (EInt y) \\<longleftrightarrow> EInt x \\<le> EInt y\"\n \"\\<And>x y. undef_less_eq (EFloat x) (EFloat y) \\<longleftrightarrow> EFloat x \\<le> EFloat y\"\n \"\\<And> x y. undef_less_eq (EString x) (EString y) \\<longleftrightarrow> EString x \\<le> EString y\"\n\nbegin\n\ndefinition undef_less :: \"event_data \\<Rightarrow> event_data \\<Rightarrow> bool\"  where\n  \"undef_less x y \\<longleftrightarrow> undef_less_eq x y \\<and> \\<not> undef_less_eq y x\"\n\ndefinition undef_min :: \"event_data \\<Rightarrow> event_data \\<Rightarrow> event_data\" where\n  \"undef_min a b = (if undef_less_eq a b then a else b)\"\n\ndefinition undef_max :: \"event_data \\<Rightarrow> event_data \\<Rightarrow> event_data\" where\n  \"undef_max a b = (if undef_less_eq a b then b else a)\"\n\nprimrec eval_trm' :: \"Formula.env \\<Rightarrow> Formula.trm \\<Rightarrow> event_data\" where\n  \"eval_trm' v (Formula.Var x) = v ! x\"\n| \"eval_trm' v (Formula.Const x) = x\"\n| \"eval_trm' v (Formula.Plus x y) = undef_plus (eval_trm' v x) ( eval_trm' v y)\"\n| \"eval_trm' v (Formula.Minus x y) = undef_minus (eval_trm' v x) ( eval_trm' v y)\"\n| \"eval_trm' v (Formula.UMinus x) = undef_uminus (eval_trm' v x)\"\n| \"eval_trm' v (Formula.Mult x y) = undef_times (eval_trm' v x) (eval_trm' v y)\"\n| \"eval_trm' v (Formula.Div x y) = undef_divide (eval_trm' v x) (eval_trm' v y)\"\n| \"eval_trm' v (Formula.Mod x y) = undef_modulo (eval_trm' v x) (eval_trm' v y)\"\n| \"eval_trm' v (Formula.F2i x) = EInt (undef_integer_of_event_data (eval_trm' v x))\"\n| \"eval_trm' v (Formula.I2f x) = EFloat (undef_double_of_event_data (eval_trm' v x))\"\n\n\nfun eval_agg_op' :: \"Formula.agg_op \\<Rightarrow> (event_data \\<times> enat) set \\<Rightarrow> event_data\" where\n  \"eval_agg_op' (agg_type.Agg_Cnt, y0) M = (case (flatten_multiset M, finite_multiset M) of\n    (_, False) \\<Rightarrow> y0\n    |    ([],_) \\<Rightarrow> y0\n    | (xs,_) \\<Rightarrow> EInt (integer_of_int (length xs)))\"\n| \"eval_agg_op' (agg_type.Agg_Min, y0) M = (case  (flatten_multiset M, finite_multiset M) of\n    (_, False) \\<Rightarrow> y0\n    |    ([],_) \\<Rightarrow> y0\n    | (x # xs,_) \\<Rightarrow> foldl undef_min x xs)\"\n| \"eval_agg_op' (agg_type.Agg_Max, y0) M = (case  (flatten_multiset M, finite_multiset M) of\n    (_, False) \\<Rightarrow> y0\n    |    ([],_) \\<Rightarrow> y0\n    | (x # xs,_) \\<Rightarrow> foldl undef_max x xs)\"\n| \"eval_agg_op' (agg_type.Agg_Sum, y0) M = (case  (flatten_multiset M, finite_multiset M) of\n    (_, False) \\<Rightarrow> y0\n    |    ([],_) \\<Rightarrow> y0\n    | (x # xs,_) \\<Rightarrow> foldl undef_plus x xs)\"\n| \"eval_agg_op' (agg_type.Agg_Avg, y0) M =(case  (flatten_multiset M, finite_multiset M) of\n    (_, False) \\<Rightarrow> y0\n    |    ([],_) \\<Rightarrow> y0\n    | (x#xs,_) \\<Rightarrow> EFloat ( undef_double_of_event_data_agg (foldl undef_plus x xs) / double_of_int (length (x#xs))))\"\n| \"eval_agg_op' (agg_type.Agg_Med, y0) M =(case (flatten_multiset M, finite_multiset M) of\n    (_, False) \\<Rightarrow> y0\n    |    ([],_) \\<Rightarrow> y0\n    | (xs,_) \\<Rightarrow> EFloat (let u = length xs;  u' = u div 2 in\n          if even u then\n            (undef_double_of_event_data_agg (xs ! (u'-1)) + undef_double_of_event_data_agg (xs ! u') / double_of_int 2)\n          else undef_double_of_event_data_agg (xs ! u')))\"\n\nfun sat' :: \"Formula.trace \\<Rightarrow> (Formula.name \\<rightharpoonup> nat \\<Rightarrow> event_data list set) \\<Rightarrow> Formula.env \\<Rightarrow> nat \\<Rightarrow> 't Formula.formula \\<Rightarrow> bool\" where\n  \"sat' \\<sigma> V v i (Formula.Pred r ts) = (case V r of\n       None \\<Rightarrow> (r, map (eval_trm' v) ts) \\<in> \\<Gamma> \\<sigma> i\n     | Some X \\<Rightarrow> map (eval_trm' v) ts \\<in> X i)\"\n| \"sat' \\<sigma> V v i (Formula.Let p \\<phi> \\<psi>) =\n    sat' \\<sigma> (V(p \\<mapsto> \\<lambda>i. {v. length v = Formula.nfv \\<phi> \\<and> sat' \\<sigma> V v i \\<phi>})) v i \\<psi>\"\n| \"sat' \\<sigma> V v i (Formula.Eq t1 t2) =  (eval_trm' v t1 = eval_trm' v t2)\"\n| \"sat' \\<sigma> V v i (Formula.Less t1 t2) = undef_less (eval_trm' v t1) (eval_trm' v t2)\"\n| \"sat' \\<sigma> V v i (Formula.LessEq t1 t2) = undef_less_eq (eval_trm' v t1) (eval_trm' v t2)\"\n| \"sat' \\<sigma> V v i (Formula.Neg \\<phi>) = (\\<not> sat' \\<sigma> V v i \\<phi>)\"\n| \"sat' \\<sigma> V v i (Formula.Or \\<phi> \\<psi>) = (sat' \\<sigma> V v i \\<phi> \\<or> sat' \\<sigma> V v i \\<psi>)\"\n| \"sat' \\<sigma> V v i (Formula.And \\<phi> \\<psi>) = (sat' \\<sigma> V v i \\<phi> \\<and> sat' \\<sigma> V v i \\<psi>)\"\n| \"sat' \\<sigma> V v i (Formula.Ands l) = (\\<forall>\\<phi> \\<in> set l. sat' \\<sigma> V v i \\<phi>)\"\n| \"sat' \\<sigma> V v i (Formula.Exists t \\<phi>) = (\\<exists>z. sat' \\<sigma> V (z # v) i \\<phi>)\"\n| \"sat' \\<sigma> V v i (Formula.Agg y \\<omega> tys f \\<phi>) =\n    (let M = {(x, ecard Zs) | x Zs. Zs = {zs. length zs = length tys \\<and> sat' \\<sigma> V (zs @ v) i \\<phi> \\<and> eval_trm' (zs @ v) f = x} \\<and> Zs \\<noteq> {}}\n    in (M = {} \\<longrightarrow> fv \\<phi> \\<subseteq> {0..< length tys}) \\<and> v ! y = eval_agg_op' \\<omega> M)\"\n| \"sat' \\<sigma> V v i (Formula.Prev I \\<phi>) = (case i of 0 \\<Rightarrow> False | Suc j \\<Rightarrow> mem I (\\<tau> \\<sigma> i - \\<tau> \\<sigma> j) \\<and> sat' \\<sigma> V v j \\<phi>)\"\n| \"sat' \\<sigma> V v i (Formula.Next I \\<phi>) = (mem I ((\\<tau> \\<sigma> (Suc i) - \\<tau> \\<sigma> i)) \\<and> sat' \\<sigma> V v (Suc i) \\<phi>)\"\n| \"sat' \\<sigma> V v i (Formula.Since \\<phi> I \\<psi>) = (\\<exists>j\\<le>i. mem I (\\<tau> \\<sigma> i - \\<tau> \\<sigma> j) \\<and> sat' \\<sigma> V v j \\<psi> \\<and> (\\<forall>k \\<in> {j <.. i}. sat' \\<sigma> V v k \\<phi>))\"\n| \"sat' \\<sigma> V v i (Formula.Until \\<phi> I \\<psi>) = (\\<exists>j\\<ge>i. mem I (\\<tau> \\<sigma> j - \\<tau> \\<sigma> i) \\<and> sat' \\<sigma> V v j \\<psi> \\<and> (\\<forall>k \\<in> {i ..< j}. sat' \\<sigma> V v k \\<phi>))\"\n| \"sat' \\<sigma> V v i (Formula.MatchP I r) = (\\<exists>j\\<le>i. mem I (\\<tau> \\<sigma> i - \\<tau> \\<sigma> j) \\<and> Regex.match (sat' \\<sigma> V v) r j i)\"\n| \"sat' \\<sigma> V v i (Formula.MatchF I r) = (\\<exists>j\\<ge>i. mem I (\\<tau> \\<sigma> j - \\<tau> \\<sigma> i) \\<and> Regex.match (sat' \\<sigma> V v) r i j)\"\n\n\n\nlemma eval_trm_sound: \n  assumes \"E \\<turnstile> f :: t\"  \"\\<forall>y\\<in>fv_trm f. ty_of (v ! y) = E y\"\n  shows \"Formula.eval_trm v f = eval_trm' v f\"\n  using assms  \n  apply  (induction  rule: wty_trm.induct) apply (auto simp add: numeric_ty_def)\n  subgoal for x y  using  value_of_eval_trm[of E x v] value_of_eval_trm[of E y v] by (auto simp add: undef_plus_sound)\n    subgoal for x y  using  value_of_eval_trm[of E x v] value_of_eval_trm[of E y v] by (auto simp add: undef_plus_sound)\n  subgoal for x y\n    using  value_of_eval_trm[of E x v] value_of_eval_trm[of E y v] by (auto simp add: undef_minus_sound) \n subgoal for x y\n   using  value_of_eval_trm[of E x v] value_of_eval_trm[of E y v] by (auto simp add: undef_minus_sound)\n subgoal for x \n   using  value_of_eval_trm[of E x v]  by (auto simp add: undef_uminus_sound)\n subgoal for x \n   using  value_of_eval_trm[of E x v]  by (auto simp add: undef_uminus_sound)\n  subgoal for x y  using  value_of_eval_trm[of E x v] value_of_eval_trm[of E y v] by (auto simp add: undef_times_sound)\n  subgoal for x y  using  value_of_eval_trm[of E x v] value_of_eval_trm[of E y v] by (auto simp add: undef_times_sound)\n  subgoal for x y  using  value_of_eval_trm[of E x v] value_of_eval_trm[of E y v] by (auto simp add: undef_divide_sound)\n  subgoal for x y  using  value_of_eval_trm[of E x v] value_of_eval_trm[of E y v] by (auto simp add: undef_divide_sound)\n  subgoal for x y  using  value_of_eval_trm[of E x v] value_of_eval_trm[of E y v] by (auto simp add: undef_modulo_sound)\n  subgoal for x  using  value_of_eval_trm[of E x v] by (auto simp add: undef_integer_of_event_data_sound)\n  subgoal for x  using  value_of_eval_trm[of E x v] by (auto simp add: undef_double_of_event_data_sound)\n  done\n\n\nlemma poly_value_of: \"E \\<turnstile> x :: t\\<Longrightarrow> E \\<turnstile> y :: t \\<Longrightarrow> \\<forall>w\\<in>fv_trm x \\<union> fv_trm y. ty_of (v ! w) = E w \\<Longrightarrow> \n(\\<exists> z z'.(eval_trm' v x) = EInt z \\<and> eval_trm' v y = EInt z'\\<and> (Formula.eval_trm v x) = EInt z \\<and> Formula.eval_trm v y = EInt z') \\<or>\n (\\<exists> z z'.(eval_trm' v x) = EFloat z \\<and> eval_trm' v y = EFloat z' \\<and> (Formula.eval_trm v x) = EFloat z \\<and> Formula.eval_trm v y = EFloat z' ) \\<or> \n(\\<exists> z z'.(eval_trm' v x) = EString z \\<and> eval_trm' v y = EString z' \\<and> (Formula.eval_trm v x) = EString z \\<and> Formula.eval_trm v y = EString z') \"\n  using value_of_eval_trm[of E x v] value_of_eval_trm[of E y v] eval_trm_sound[of E x _ v] eval_trm_sound[of E y _ v] \n  by (cases t)  auto \n\n\nlemma nfv_exists: \" Formula.nfv \\<phi> \\<le> Suc (Formula.nfv (Formula.Exists t \\<phi>))\"\n   apply (auto simp add: Formula.nfv_def fvi_Suc) \n  by (metis Max.coboundedI finite_fvi finite_imageI finite_insert fvi_Suc imageI insertCI list_decode.cases)\n\nlemma match_safe_wty_nfv: assumes \"\\<phi> \\<in> atms r\"   \"safe_formula (formula.MatchP I r) \\<or> safe_formula (formula.MatchF I r)\" \" S, E \\<turnstile> formula.MatchP I r \\<or>  S, E \\<turnstile> formula.MatchF I r\"\n   \" Formula.nfv (formula.MatchF I r) \\<le> length v \\<or>  Formula.nfv (formula.MatchP I r) \\<le> length v\"\n  shows \"S, E \\<turnstile> \\<phi>\" \"Formula.nfv \\<phi> \\<le> length v\"\nproof -\n have \"\\<forall>a \\<in> fv \\<phi>. a \\<in> fv_regex r\" using   assms(1)  apply (induction r) apply auto \n      subgoal for \\<psi>  apply (cases \"safe_formula \\<psi>\") apply (auto elim: safe_formula.cases) by (cases \\<psi>) auto \n      done\n    from this assms(4) show  \"Formula.nfv \\<phi> \\<le> length v\" by (auto simp add: Formula.nfv_def) \n  next\n    from assms(3) assms(2) show  \"S, E \\<turnstile> \\<phi>\" using  Regex.Regex.regex.pred_set[of \"(\\<lambda>\\<phi>. S, E \\<turnstile> \\<phi>)\"] assms(1) wty_regexatms_atms  \n      by (auto elim: wty_formula.cases)\n  qed\n\nlemma match_sat'_fv: assumes \"safe_regex temp Strict r\"\n    \"Regex.match (sat' \\<sigma> V v) r j i\"\n    \"x \\<in> fv (formula.MatchP I r) \\<or> x \\<in>fv (formula.MatchF I r)\"\n  shows \"\\<exists>\\<phi>\\<in>atms r. \\<exists>k. sat' \\<sigma> V v k \\<phi> \\<and> x \\<in> fv \\<phi>\"\n  using assms\n  proof (induction r arbitrary:i j)\n\n    case (Plus r1 r2)\n  moreover obtain k where \"\\<exists>j. Regex.match (sat' \\<sigma> V v) r1 j k \\<or>  Regex.match (sat' \\<sigma> V v) r2 j k\" using  Plus.prems(2)  by auto\n  moreover {\n    assume assm: \"\\<exists>j. Regex.match (sat' \\<sigma> V v) r1 j k\"\n    then have ?case using Plus.prems(1,3) Plus.IH(1)  by (fastforce simp add: atms_def) \n  } moreover {\n    assume assm: \"\\<exists>j. Regex.match (sat' \\<sigma> V v) r2 j k\"\n    from this have ?case using Plus.prems(1,3) Plus.IH(2) by (fastforce simp add: atms_def)\n  }\n  ultimately show ?case by auto\nnext\n  case (Times r1 r2)\n  then show ?case  using Times.prems match_le Times.IH  by (cases temp) fastforce+\nqed  auto\n\n(*Theorem 3.7*)\nlemma ty_of_sat'_safe: \"safe_formula \\<phi> \\<Longrightarrow> S, E \\<turnstile> \\<phi> \\<Longrightarrow> wty_envs S \\<sigma> V \\<Longrightarrow> \n  sat' \\<sigma> V v i \\<phi> \\<Longrightarrow> x \\<in> Formula.fv \\<phi> \\<Longrightarrow> Formula.nfv \\<phi> \\<le> length v \\<Longrightarrow> ty_of (v ! x) = E x\" (*Theorem 3.7*)\nproof (induction arbitrary: S E V v i x rule: safe_formula_induct)\n  case (Eq_Const c d)\n  then show ?case by auto\nnext\n  case (Eq_Var1 c xa)\n   case (Eq_Var1 c xa)\n  from Eq_Var1.prems(1) obtain t where \n\" E \\<turnstile> (trm.Const c) :: t\" and \"E \\<turnstile> (trm.Var xa) :: t\"\n    by cases\n  from Eq_Var1(4)  have \"x = xa\" by auto\n  from this `E \\<turnstile> (trm.Var xa) :: t` have \"E x = t\" using  wty_trm.cases by fastforce\n  from this Eq_Var1 ` E \\<turnstile> (trm.Const c) :: t` show ?case\n    by (metis \\<open>x = xa\\<close> empty_iff eval_trm'.simps(1) fvi_trm.simps(2) sat'.simps(3) eval_trm_sound ty_of_eval_trm)\n\nnext\n  case (Eq_Var2 c xa)\n    from Eq_Var2.prems(1) obtain t where \n\" E \\<turnstile> (trm.Const c) :: t\" and \"E \\<turnstile> (trm.Var xa) :: t\"\n    by cases\n  from Eq_Var2(4)  have \"x = xa\" by auto\n  from this `E \\<turnstile> (trm.Var xa) :: t` have \"E x = t\" using  wty_trm.cases by fastforce\n  from this Eq_Var2 ` E \\<turnstile> (trm.Const c) :: t` show ?case\n    by (metis \\<open>x = xa\\<close> empty_iff eval_trm'.simps(1) fvi_trm.simps(2) sat'.simps(3) eval_trm_sound ty_of_eval_trm)\nnext\n  case (Pred p tms)\n  from Pred.prems(1) obtain tys where\n    S_p: \"S p = Some tys\" and\n    xs_ts: \"list_all2 (\\<lambda>tm ty. E \\<turnstile> tm :: ty) tms tys\"\n    by cases\n  let ?xs = \"map (eval_trm' v) tms\"\n  have wty_xs: \"wty_tuple tys ?xs\"\n  proof (cases \"p \\<in> dom V\")\n    case True\n    then have \"?xs \\<in> the (V p) i\"\n      using Pred.prems(3) by auto\n    with True show ?thesis\n      using Pred.prems(2) by (auto simp: S_p dest!: wty_envs_V_D)\n  next\n    case False\n    then have \"(p, ?xs) \\<in> \\<Gamma> \\<sigma> i\"\n      using Pred.prems(3) by (auto split: option.splits)\n    with False show ?thesis\n      using Pred.prems(2) by (auto simp: S_p dest!: wty_envs_\\<Gamma>_D)\n  qed\n  from Pred obtain k where k: \"k < length tms\" \"tms ! k = Formula.Var x\"\n    by (fastforce simp: trm.is_Var_def trm.is_Const_def in_set_conv_nth)\n  with Pred.prems have \"v ! x = ?xs ! k\" by simp\n  with wty_xs k have \"ty_of (v ! x) = tys ! k\"\n    by (auto simp: wty_tuple_def list_all2_conv_all_nth)\n  also have \"\\<dots> = E x\"\n    using xs_ts k\n    by (fastforce simp: list_all2_conv_all_nth elim: wty_trm.cases)\n  finally show ?case .\nnext\n  case (Let p \\<phi> \\<psi>)\n  let ?V' = \"V(p \\<mapsto> \\<lambda>i. {v. length v = Formula.nfv \\<phi> \\<and> sat' \\<sigma> V v i \\<phi>})\"\n  from Let.prems(1) obtain E' where\n    wty_\\<phi>: \"S, E' \\<turnstile> \\<phi>\" and\n    wty_\\<psi>: \"S(p \\<mapsto> tabulate E' 0 (Formula.nfv \\<phi>)), E \\<turnstile> \\<psi>\"\n    by (cases pred: wty_formula)\n  let ?tys = \"tabulate E' 0 (Formula.nfv \\<phi>)\"\n  {\n    fix v' i\n    assume \"length v' = Formula.nfv \\<phi>\" and \"sat' \\<sigma> V v' i \\<phi>\"\n    then have \"wty_tuple ?tys v'\"\n      using Let.IH(1) wty_\\<phi> Let.prems(2) Let.hyps(1)\n      by (auto simp: wty_tuple_def list_all2_conv_all_nth)\n  }\n  with Let.prems(2) have \"wty_envs (S(p \\<mapsto> ?tys)) \\<sigma> ?V'\"\n    by (auto simp: wty_envs_def wty_event_def)\n  from Let.prems(3) have \"sat' \\<sigma> ?V' v i \\<psi>\" by simp\n  from Let.prems(4) have \"x \\<in> fv \\<psi>\" by simp\n  from Let have \"Formula.nfv \\<psi> \\<le> length v\" by auto\n  show ?case by (rule Let.IH(2)) fact+\nnext\n  case (And_assign \\<phi> \\<psi>)\n  from And_assign.prems(1) have phi1: \"S, E \\<turnstile> \\<phi>\" by cases\n  from And_assign.prems(3) have phi2: \"sat' \\<sigma> V v i \\<psi>\" by auto\n  from And_assign.prems(4) have \"x \\<in> fv \\<phi> \\<or> x \\<in> fv \\<psi>\" by auto\n  from this show ?case\n  proof cases\n    assume \"x \\<in> fv \\<phi>\"\n    from this And_assign phi1 phi2 show ?case by auto\n  next\n    assume x_not_\\<phi>: \"x \\<notin> fv \\<phi>\"\n    from this And_assign.prems(4) have \"x \\<in> fv \\<psi>\" by auto\n    from And_assign.hyps(2) obtain a b where \\<psi>_eq: \"\\<psi> = Formula.Eq a b\"\n      by (auto simp: safe_assignment_def split: formula.splits)\n    moreover {\n      assume a_def: \"a = Formula.Var x\"\n      from this  x_not_\\<phi> have fvb: \"fv_trm b \\<subseteq> fv \\<phi>\" using And_assign(2) by  (auto simp: safe_assignment_def \\<psi>_eq split: trm.splits) \n      have eval:\" v! x = eval_trm' v b\" using And_assign(6) a_def \\<psi>_eq by auto\n      have Ebx: \"E \\<turnstile> b :: E  x\"  using And_assign(4) by (auto simp: \\<psi>_eq a_def elim: wty_trm.cases wty_formula.cases)\n      have \"(\\<lambda>y. ty_of (v ! y)) \\<turnstile> b :: E x\" apply (rule  iffD1[OF wty_trm_fv_cong,OF _ Ebx]) apply (subst eq_commute) \n        apply (rule And_assign(3)) using And_assign fvb by (auto elim: wty_formula.cases) \n      then have ?case using ty_of_eval_trm unfolding eval\n        using And_assign(4) by (auto simp: \\<psi>_eq a_def eval_trm_sound elim: wty_formula.cases)\n    }\n    moreover {\n     assume a_def: \"b = Formula.Var x\"\n      from this  x_not_\\<phi> have fvb: \"fv_trm a \\<subseteq> fv \\<phi>\" using And_assign(2) by  (auto simp: safe_assignment_def \\<psi>_eq split: trm.splits) \n      have eval:\" v! x = eval_trm' v a\" using And_assign(6) a_def \\<psi>_eq by auto\n      have Ebx: \"E \\<turnstile> a :: E  x\"  using And_assign(4) by (auto simp: \\<psi>_eq a_def elim: wty_trm.cases wty_formula.cases)\n      have \"(\\<lambda>y. ty_of (v ! y)) \\<turnstile> a :: E x\" apply (rule  iffD1[OF wty_trm_fv_cong,OF _ Ebx]) apply (subst eq_commute) \n        apply (rule And_assign(3)) using And_assign fvb by (auto elim: wty_formula.cases) \n      then have ?case using ty_of_eval_trm unfolding eval\n        using And_assign(4)  by (auto simp: \\<psi>_eq a_def eval_trm_sound elim: wty_formula.cases)\n    }\n    moreover\n      have \"a = Formula.Var x \\<or> b = Formula.Var x\" using And_assign(2) And_assign(7) x_not_\\<phi> by (auto simp: \\<psi>_eq safe_assignment_def split: Formula.trm.splits) \n    ultimately show ?case by auto\nqed\n next\n  case (And_safe \\<phi> \\<psi>)\n  from And_safe.prems(1) obtain \"S, E \\<turnstile> \\<phi>\" and \"S, E \\<turnstile> \\<psi>\" by cases\n  from And_safe.prems(3) have \"sat' \\<sigma> V v i \\<phi>\" and \"sat' \\<sigma> V v i \\<psi>\"\n    by simp_all\n  from And_safe.prems(4) consider (in_\\<phi>) \"x \\<in> fv \\<phi>\" | (in_\\<psi>) \"x \\<in> fv \\<psi>\" by auto\n  then show ?case\n  proof cases\n    case in_\\<phi>\n  from And_safe have \"Formula.nfv \\<phi> \\<le> length v\" by auto\n    show ?thesis by (rule And_safe.IH(1)) fact+\n  next\n    case in_\\<psi>\n  from And_safe have \"Formula.nfv \\<psi> \\<le> length v\" by auto\n    show ?thesis by (rule And_safe.IH(2)) fact+\n  qed\nnext\n  case (And_constraint \\<phi> \\<psi>)\n  have xfree: \"x \\<in> fv \\<phi>\" using And_constraint(4) And_constraint(10) by auto\n  from And_constraint(7) have \"S, E \\<turnstile> \\<phi>\" by cases\n  from this xfree And_constraint(6,8-9,11) show ?case by auto\nnext\n  case (And_Not \\<phi> \\<psi>)\n  from And_Not.prems(4) And_Not.hyps(4) have xfree: \"x \\<in> fv \\<phi>\" by auto\n  from And_Not.prems(1) have \"S, E \\<turnstile> \\<phi>\" by cases\n  from this xfree And_Not  show ?case by auto \nnext\n  case (Ands l pos neg)\n  from Ands have \"\\<exists>\\<phi> \\<in> set l . x \\<in> fv \\<phi>\" by auto\n  from this obtain \\<psi> where psidef: \"\\<psi> \\<in> set l \\<and> x \\<in> fv \\<psi>\" by blast\n  from this have \"\\<exists>\\<phi>\\<in>set pos. x \\<in>fv  \\<phi>\" \n  proof cases\n    assume \"safe_formula \\<psi>\"\n    then have \"\\<psi> \\<in> set pos\" using Ands(1) by (auto simp add: psidef)\n    thus \"\\<exists>\\<phi>\\<in>set pos. x \\<in>fv  \\<phi>\" using psidef by auto\n  next\n    assume \" \\<not> safe_formula \\<psi>\"\n    then have \"\\<psi> \\<in> set neg\" using Ands(1) by (auto simp add: psidef)\n    thus \"\\<exists>\\<phi>\\<in>set pos. x \\<in>fv  \\<phi>\" using Ands(1) Ands(5) psidef by auto\n  qed\n  from this obtain \\<phi> where phidef: \"\\<phi> \\<in> set pos \\<and> x \\<in> fv \\<phi>\" by blast\n  from this Ands(1) have phi_in_l: \"\\<phi> \\<in> set l\" by auto\n  from phidef Ands(6) have phi_IH: \"S, E \\<turnstile> \\<phi> \\<Longrightarrow>\n    wty_envs S \\<sigma> V \\<Longrightarrow>\n    sat' \\<sigma> V v i \\<phi> \\<Longrightarrow> x \\<in> fv \\<phi> \\<Longrightarrow> Formula.nfv \\<phi> \\<le> length v \\<Longrightarrow> ty_of (v ! x) = E x\"\n        using list_all2_iff by (smt (verit, ccfv_SIG) Ball_set_list_all)\n      from Ands.prems(1) have  \"\\<forall>\\<phi> \\<in> set l. S, E \\<turnstile> \\<phi>\" by cases\n      from this phi_in_l have p1: \"S, E \\<turnstile> \\<phi>\"  by auto\n      from phi_in_l Ands.prems(3) have p3: \"sat' \\<sigma> V v i \\<phi>\" by auto\n      from phi_in_l Ands have p5: \"Formula.nfv \\<phi> \\<le> length v\" by auto\n  from  phi_IH p1 Ands.prems(2) p3 phidef p5  show ?case by auto\nnext\n  case (Neg \\<phi>)\n  from Neg show ?case by auto\nnext\n  case (Or \\<phi> \\<psi>)\n  from Or.prems(3) have \" (sat' \\<sigma> V v i \\<phi>) \\<or>( sat' \\<sigma> V v i \\<psi>)\" by auto\n  from this show ?case \n  proof\n    assume assm: \"(sat' \\<sigma> V v i \\<phi>)\"\n  from Or(1) Or.prems(4) have xfv: \"x \\<in> fv \\<phi>\" by auto\n  from Or.prems(1) have \"S, E \\<turnstile> \\<phi>\" by cases\n  from this assm Or.prems(2,3) Or(4) Or.prems(5) xfv show ?case by auto\nnext \n  assume assm: \"( sat' \\<sigma> V v i \\<psi>)\"\n from Or(1) Or.prems(4) have xfv: \"x \\<in> fv \\<psi>\" by auto\n  from Or.prems(1) have \"S, E \\<turnstile> \\<psi>\" by cases\n  from this assm Or.prems(2,3) Or(5) Or.prems(5) xfv show ?case by auto\nqed\nnext\n  case (Exists \\<phi>)\n  from Exists.prems(1) obtain t where \"S, case_nat t E \\<turnstile> \\<phi>\" by cases\n  from Exists.prems(3) obtain z where \"sat' \\<sigma> V (z#v) i \\<phi>\" by auto\n  from Exists.prems(4) have \"Suc x \\<in> fv \\<phi>\" by (simp add: fvi_Suc)\n  from Exists have \"Formula.nfv \\<phi> \\<le> Suc (length v)\" apply (auto simp add: Formula.nfv_def)\n    by (metis fvi_Suc le0 old.nat.exhaust)\n\n  have \"ty_of ((z#v) ! Suc x) = case_nat t E (Suc x)\"\n    by (rule Exists.IH) (simp?, fact)+\n  then show ?case by simp\nnext\n  case (Agg y \\<omega> tys f \\<phi>)\n have \"\\<forall>z \\<in>Formula.fvi (length tys) \\<phi>. Suc z \\<le> length v \" using Agg.prems(5) by (auto simp add: Formula.nfv_def)\n    from this have \"\\<forall>z \\<in>Formula.fv \\<phi>. Suc z - length tys \\<le> length v \"  using  fvi_iff_fv  nat_le_linear \n      by (metis Suc_diff_le diff_add diff_is_0_eq' diff_zero not_less_eq_eq) \n    from this have nfv_tys_v: \"Formula.nfv \\<phi> \\<le> length tys + length v\" by (auto simp add: Formula.nfv_def)\n\n  have case_split:\" x \\<in> Formula.fvi (length tys) \\<phi> \\<or> x \\<in> Formula.fvi_trm (length tys) f \\<or> x = y\" using Agg.prems(4) by auto\n \n  moreover {\n    assume asm: \"x \\<in> Formula.fvi (length tys) \\<phi>\"\n    from this have \"\\<not> fv \\<phi> \\<subseteq> {0..< length tys}\" using fvi_iff_fv[of x \"length tys\" \\<phi>] by auto\n    from this have M: \"{(x, ecard Zs) | \n  x Zs. Zs = {zs. length zs = length tys \\<and> sat' \\<sigma> V (zs @ v) i \\<phi> \\<and> eval_trm' (zs @ v) f = x} \\<and> Zs \\<noteq> {}} \\<noteq> {}\" using Agg.prems(3) by auto\n    from this obtain zs where sat: \"sat' \\<sigma> V (zs @ v) i \\<phi> \\<and> length zs = length tys\" by auto\n    from nfv_tys_v have nfv: \"Formula.nfv \\<phi> \\<le> length (zs @ v)\"  by (auto simp add: sat)\n    have \"ty_of ((zs@v) ! (x + length tys)) = agg_env E tys (x + length tys)\"\n      apply (rule Agg.IH[of \\<phi> S \"agg_env E tys\" V \"zs @ v\" i \"x+ length tys\"]) using Agg.prems(1) Agg(4) sat asm nfv Agg.prems(1-2) fvi_iff_fv\n      by (auto elim: wty_formula.cases)\n    from this have ?case apply (auto simp add: agg_env_def) by (metis add.commute nth_append_length_plus sat)\n  } \n  moreover {\n    assume \"x \\<notin> Formula.fvi (length tys) \\<phi>\"\n    from this have eq: \"x = y\" using Agg(3) case_split fvi_iff_fv fvi_trm_iff_fv_trm by blast\n    obtain d agg_type where omega_def: \"\\<omega> = (agg_type, d)\" using surjective_pairing by blast\n    from Agg.prems(1) this have  \"\\<exists>t .E y = t_res agg_type t\" by cases auto\n    from this eq obtain t where t_def: \"E x = t_res agg_type t\" by blast\n    from  Agg.prems(1) have\n ty_of_d: \"ty_of d = t_res agg_type t\" apply cases using eq omega_def t_def by auto\n    from Agg.prems(3) eq obtain M where  M_def: \"M = {(x, ecard Zs) | x Zs. Zs = {zs. length zs = length tys \\<and> sat' \\<sigma> V (zs @ v) i \\<phi>\n        \\<and> eval_trm' (zs @ v) f = x} \\<and> Zs \\<noteq> {}} \\<and> v!x = eval_agg_op' \\<omega> M\" by auto\n   \n        {\n           assume finite_M: \"finite_multiset M\"\n    from this   have finite_set:\"finite {x. {zs. length zs = length tys \\<and> sat' \\<sigma> V (zs @ v) i \\<phi> \\<and> eval_trm' (zs @ v) f = x} \\<noteq> {}}\"\n       using finite_fst by (auto simp add: finite_multiset_def M_def ) \n    have flatten: \"set (flatten_multiset M) \\<subseteq> fst ` M\" using finite_set  set_of_flatten_multiset[of M\n \"(\\<lambda>x . {zs . length zs = length tys \\<and> sat' \\<sigma> V (zs @ v) i \\<phi> \\<and> eval_trm' (zs @ v) f = x} )\"]\n       by (auto simp add:  M_def) \n    from this  have evaltrm: \"z \\<in> set (flatten_multiset M) \\<Longrightarrow>  \\<exists> zs. length zs = length tys \\<and> sat' \\<sigma> V (zs @ v) i \\<phi> \\<and> eval_trm' (zs @ v) f = z\" \n      for z using  M_def by (auto simp add: image_def)\n     have th2: ?case if minmaxsum: \"agg_type = agg_type.Agg_Min \\<or> agg_type = agg_type.Agg_Max \\<or> agg_type = agg_type.Agg_Sum\" and alist_def: \" flatten_multiset\n     {(x, ecard {zs. length zs = length tys \\<and> sat' \\<sigma> V (zs @ v) i \\<phi> \\<and> eval_trm' (zs @ v) f = x}) |x.\n      \\<exists>xa. sat' \\<sigma> V (xa @ v) i \\<phi> \\<and> length xa = length tys \\<and> eval_trm' (xa @ v) f = x} =\n    a # list\"  for a list\n     proof -\n      have ty_of_list: \"z=a \\<or> z \\<in> set list \\<Longrightarrow> \\<exists>zs .ty_of (eval_trm' (zs @ v) f) = t \\<and> ty_of z = t\" for z\n      proof -\n          assume z_def: \"z=a \\<or> z \\<in> set list\"\n        from z_def obtain zs where zs_def: \" length zs = length tys \\<and> sat' \\<sigma> V (zs @ v) i \\<phi> \\<and> eval_trm' (zs @ v) f = z\" using alist_def evaltrm M_def by auto\n        from Agg.prems(1) have wty_f: \" agg_env E tys  \\<turnstile> f :: t\" apply cases  using omega_def t_def minmaxsum eq  by auto  \n        have fv_ty:\"\\<forall>y\\<in>fv_trm f. ty_of ((zs @ v) ! y) = agg_env E tys y\"\n        proof \n          fix y\n          assume assm: \"y \\<in> fv_trm f\"\n          have  sat: \"sat' \\<sigma> V (zs @ v) i \\<phi>\"  using zs_def by auto \n          show \"ty_of ((zs @ v) ! y) = agg_env E tys y\" using zs_def assm Agg(3,4) Agg.prems(1-2) nfv_tys_v sat  Agg.IH[of \\<phi> S \"agg_env E tys\" V \"zs@v\" i y]\n            by (auto elim: wty_formula.cases)\n        qed      \n        have ty_of_z: \"ty_of (eval_trm' (zs @ v) f) = t\" using wty_f fv_ty   ty_of_eval_trm[of \"agg_env E tys\" f t \"zs@v\" ]\n          by (auto simp add: eval_trm_sound)\n        from this zs_def show  ?thesis by auto\n      qed \n      from this obtain zs where zs_def: \"ty_of (eval_trm' (zs @ v) f) = t\" by auto\n      from ty_of_list have indass: \"ty_of a = t \\<and> (\\<forall>z \\<in> set list . ty_of z = t)\" by auto\n     \n      from this have foldl_evaltrm: \"foldfun = min \\<or> foldfun = max\n        \\<Longrightarrow> ty_of (foldl foldfun a list) = ty_of (eval_trm' (zs @ v) f)\" for foldfun using indass \n          proof  (induction list arbitrary: a foldfun)\n            case Nil\n            then show ?case using zs_def by auto\n          next\n            case (Cons aa tail)\n             have minmax: \" ty_of (foldl foldfun (foldfun a aa) tail) = ty_of (eval_trm' (zs @ v) f)\"\n              using Cons.IH[of _ \"foldfun a aa\"] Cons apply auto \n               apply (metis min_def) by (metis max_def) \n              then show ?case by auto\n            qed\n\n          from indass have foldl_evaltrm_Sum: \n              \"t \\<in> numeric_ty \\<Longrightarrow> ty_of (foldl undef_plus a list) = ty_of (eval_trm' (zs@v) f)\" \n              proof (induction list arbitrary: a)\n                  case (Cons aa tail)\n                  from this have \"ty_of (undef_plus a aa) = t\"  apply (cases aa)  apply ( auto simp add: numeric_ty_def ty_of_plus)\n                     apply (cases a) apply (auto simp add: undef_plus_sound)\n                    by (cases a)(auto simp add: undef_plus_sound)\n\n                  then show ?case using Cons.prems(1) Cons.IH[of \"undef_plus a aa\"] apply auto \n                    by (metis Cons.prems(2) list.set_intros(2))\n                qed (auto simp add: zs_def)\n\n from indass have foldl_evaltrm_Min: \n              \" ty_of (foldl undef_min a list) = t\" \n              proof (induction list arbitrary: a)\n                  case (Cons aa tail)\n            from this have \"ty_of (undef_min a aa) = t\"  apply (cases aa) by ( auto simp add: numeric_ty_def undef_min_def undef_less_eq_sound)\n                  then show ?case using Cons.prems(1) Cons.IH[of \"undef_min a aa\"] by auto \n                qed auto\n\n from indass have foldl_evaltrm_Max: \n              \" ty_of (foldl undef_max a list) = t\" \n              proof (induction list arbitrary: a)\n                  case (Cons aa tail)\n            from this have \"ty_of (undef_max a aa) = t\"  apply (cases aa) by ( auto simp add: numeric_ty_def undef_max_def undef_less_eq_sound)\n                  then show ?case using Cons.prems(1) Cons.IH[of \"undef_max a aa\"] by auto \n              qed auto\n           from Agg.prems(1) t_def eq omega_def have num_ty: \"agg_type = agg_type.Agg_Sum \\<Longrightarrow> t \\<in> numeric_ty\" by cases auto\n         \n    \n            from  num_ty  finite_M foldl_evaltrm foldl_evaltrm_Sum foldl_evaltrm_Min foldl_evaltrm_Max show  ?thesis apply (cases agg_type)\n               by (auto simp add: M_def  alist_def omega_def finite_multiset_def   \n                      t_def zs_def   split: list.splits) \n   \n         qed\n          from  finite_M th2  M_def t_def omega_def  have ?case apply (cases agg_type) \n            by (auto simp add: ty_of_d split: list.splits)        \n        }\n        moreover{\n             assume not_finite: \"\\<not> finite_multiset M\"\n         from this t_def  M_def  omega_def have  ?case apply (cases agg_type)\n                by ( auto simp add: ty_of_d split: list.splits) \n         }\n         ultimately have ?case by auto \n     \n  } \n  ultimately show ?case by auto\nnext\n  \n  case (Prev I \\<phi>)\n   from Prev.prems(1) have wty: \"S, E \\<turnstile> \\<phi>\" by cases\n  from Prev.prems(3) have forall_j: \"\\<forall>j . i = Suc j \\<longrightarrow> sat' \\<sigma> V v j \\<phi>\" by auto\n  from this have \"sat' \\<sigma> V v (Nat.pred i) \\<phi>\" using Prev.prems by (auto split: nat.splits)\n  from this wty Prev.prems(2-5) Prev.IH show ?case by auto\nnext\n  case (Next I \\<phi>)\n  from Next.prems(1,2-5) Next.IH show ?case by (auto elim: wty_formula.cases)\nnext\n  case (Since \\<phi> I \\<psi>)\n  from Since(1,9) have xfv: \"x \\<in> fv \\<psi>\" by auto\n  from this  Since.prems(1,2-5) Since.IH show ?case by (auto elim: wty_formula.cases)\nnext\n  case (Not_Since \\<phi> I \\<psi>)\n  from Not_Since.prems(1) have wty: \"S, E \\<turnstile> \\<psi>\" by cases\n  from Not_Since(1,10) have xfv: \"x \\<in> fv \\<psi>\" by auto\n  from this wty Not_Since.prems(2-5) Not_Since.IH show ?case by auto\nnext\n  case (Until \\<phi> I \\<psi>)\n  from Until(1,9) have xfv: \"x \\<in> fv \\<psi>\" by auto\n  from this  Until.prems(1,2-5) Until.IH show ?case by (auto elim: wty_formula.cases)\nnext\n  case (Not_Until \\<phi> I \\<psi>)\n from Not_Until.prems(1) have wty: \"S, E \\<turnstile> \\<psi>\" by cases\n  from Not_Until(1,10) have xfv: \"x \\<in> fv \\<psi>\" by auto\n  from this wty Not_Until.prems(2-5) Not_Until.IH show ?case by auto\nnext\n  case (MatchP I r)\n  from MatchP.prems(3) have \"(\\<exists>j. Regex.match (sat' \\<sigma> V v) r j i)\" by auto\n    from this  MatchP(1)  MatchP.prems(4) obtain \\<phi> j where phidef: \" \\<phi> \\<in> atms r\" \" sat' \\<sigma> V v j \\<phi>\" \"x \\<in> fv \\<phi> \" using match_sat'_fv  by auto blast\n    from   MatchP.prems(1) MatchP(1)  MatchP.prems(5) phidef(1)  have wty: \"S, E \\<turnstile> \\<phi>\" and  nfv:\"Formula.nfv \\<phi> \\<le> length v\" \n      using  match_safe_wty_nfv[of \\<phi> r I S E v] by auto\n    from MatchP.IH MatchP.prems have IH: \"S, E \\<turnstile> \\<phi> \\<Longrightarrow>\\<phi> \\<in> atms r \\<Longrightarrow>\n     sat' \\<sigma> V v j \\<phi> \\<Longrightarrow> x \\<in> fv \\<phi> \\<Longrightarrow> Formula.nfv \\<phi> \\<le> length v \\<Longrightarrow> ty_of (v ! x ) = E x\"\n    for \\<phi> E  v  x by blast\n   show ?case apply (rule IH) using wty nfv  MatchP.prems(5) phidef by auto\n \nnext\n  case (MatchF I r)\n from MatchF.prems(3) have \"(\\<exists>j. Regex.match (sat' \\<sigma> V v) r  i j)\" by auto\n    from this  MatchF(1)  MatchF.prems(4) obtain \\<phi> j where phidef: \" \\<phi> \\<in> atms r\" \" sat' \\<sigma> V v j \\<phi>\" \"x \\<in> fv \\<phi> \" using match_sat'_fv  by auto blast\n    from   MatchF.prems(1) MatchF(1)  MatchF.prems(5) phidef(1)  have wty: \"S, E \\<turnstile> \\<phi>\" and  nfv:\"Formula.nfv \\<phi> \\<le> length v\" \n      using  match_safe_wty_nfv[of \\<phi> r I S E v] by auto\n    from MatchF.IH MatchF.prems have IH: \"S, E \\<turnstile> \\<phi> \\<Longrightarrow>\\<phi> \\<in> atms r \\<Longrightarrow>\n     sat' \\<sigma> V v j \\<phi> \\<Longrightarrow> x \\<in> fv \\<phi> \\<Longrightarrow> Formula.nfv \\<phi> \\<le> length v \\<Longrightarrow> ty_of (v ! x ) = E x\"\n    for \\<phi> E  v  x by blast\n   show ?case apply (rule IH) using wty nfv  MatchF.prems(5)  phidef by auto\n\nqed\n\nend\n\ninterpretation  sat_inst: sat_general \"(+)\" \"(-)\" \"uminus\" \"(*)\" \"(div)\" \"(mod)\" \"Event_Data.double_of_event_data\" \"Event_Data.double_of_event_data_agg\" \"Event_Data.integer_of_event_data\" \"(\\<le>)\"\n  by unfold_locales  auto\n\nlemma eval_trm_inst: \" sat_inst.eval_trm'  = Formula.eval_trm \"\nproof -\n  have  \"sat_inst.eval_trm' v f = Formula.eval_trm v f\" for v f\n  by (induction f)  auto \n  then show ?thesis  by auto\nqed \n\nlemma eval_agg_op_inst: \" sat_inst.eval_agg_op' (\\<omega>, d) M  = Formula.eval_agg_op (\\<omega>, d) M\"\n  apply (cases \\<omega>)   apply (auto ) apply (induction \"flatten_multiset M\")  apply (cases \\<omega>) apply (auto simp add:  split: list.splits) \n  apply (smt (verit) foldl_cong min_def sat_inst.undef_min_def sat_inst.undef_min_def) \n  by (smt (verit) foldl_cong max_def sat_inst.undef_max_def) \n  \n\nlemma sat_inst_of_sat': \"Formula.sat \\<sigma> V v i \\<phi> = sat_inst.sat' \\<sigma> V v i \\<phi>\"\n apply (induction \\<phi> arbitrary: v V i)  apply  (auto simp add: eval_trm_inst less_event_data_def sat_inst.undef_less_def  split: nat.splits)\n  using eval_trm_inst apply presburger\n                      apply (metis eval_trm_inst) \n  using eval_agg_op_inst apply presburger+  by  (metis match_cong_strong)+\n\n(*Theorem 3.7 instantiated with sat*)\nlemma ty_of_sat_safe: \"safe_formula \\<phi> \\<Longrightarrow> S, E \\<turnstile> \\<phi> \\<Longrightarrow> wty_envs S \\<sigma> V \\<Longrightarrow> \n  Formula.sat \\<sigma> V v i \\<phi> \\<Longrightarrow> x \\<in> Formula.fv \\<phi> \\<Longrightarrow> Formula.nfv \\<phi> \\<le> length v \\<Longrightarrow> ty_of (v ! x) = E x\"\n  using  sat_inst.sat_general_axioms sat_inst_of_sat'\n    sat_general.ty_of_sat'_safe[of  \"(+)\" \"(-)\" \"uminus\" \"(*)\" \"(div)\" \"(mod)\" double_of_event_data double_of_event_data_agg integer_of_event_data \"(\\<le>)\"]  \n  by auto  blast\n\nlemma rel_regex_fv_aux: \"regex.rel_regex (\\<lambda>a b. \\<forall>x. Formula.fvi x a = Formula.fvi x b) r r' \\<Longrightarrow>\n  Regex.fv_regex (Formula.fvi x) r = Regex.fv_regex (Formula.fvi x) r'\"\n  by (induction r r' rule: regex.rel_induct) auto\n\nlemma rel_formula_fv: \"formula.rel_formula f \\<phi> \\<phi>' \\<Longrightarrow> Formula.fvi b \\<phi> = Formula.fvi b \\<phi>'\"\nproof (induction \\<phi> \\<phi>' arbitrary: b rule: formula.rel_induct)\n  case (Ands l l')\n  then show ?case\n    by (induction l l' rule: list.rel_induct) auto\nqed (auto simp add: list_all2_lengthD rel_regex_fv_aux)\n\nlemma rel_regex_fv: \"regex.rel_regex (formula.rel_formula f) r r' \\<Longrightarrow>\n  Regex.fv_regex (Formula.fvi x) r = Regex.fv_regex (Formula.fvi x) r'\"\n  by (induction r r' rule: regex.rel_induct) (auto simp: rel_formula_fv)\n\nlemma rel_regex_fv_cong: \"Regex.rel_regex (\\<lambda>a b. P a b) r r' \\<Longrightarrow> (\\<And>\\<phi> \\<phi>'. P \\<phi> \\<phi>' \\<Longrightarrow> fv \\<phi> = fv \\<phi>') \\<Longrightarrow>\n  fv_regex r = fv_regex r'\"\n  by (induction r r' rule: regex.rel_induct) auto\n\nlemma rel_regex_safe_aux: \"safe_regex m g r \\<Longrightarrow>\n  (\\<And>\\<phi> \\<phi>'. \\<phi> \\<in> atms r \\<Longrightarrow> P \\<phi> \\<phi>' \\<Longrightarrow> safe_formula \\<phi> \\<Longrightarrow> safe_formula \\<phi>') \\<Longrightarrow>\n  (\\<And>\\<phi> \\<phi>'. P \\<phi> \\<phi>' \\<Longrightarrow> fv \\<phi> = fv \\<phi>') \\<Longrightarrow>\n  (\\<And>\\<phi> \\<phi>'. P (formula.Neg \\<phi>) \\<phi>' \\<Longrightarrow> (case \\<phi>' of formula.Neg \\<phi>'' \\<Rightarrow> P \\<phi> \\<phi>'' | _ \\<Rightarrow> False)) \\<Longrightarrow>\n  Regex.rel_regex (\\<lambda>a b. P a b) r r' \\<Longrightarrow> safe_regex m g r'\"\nproof (induction m g r arbitrary: r' rule: safe_regex_induct)\n  case (Skip m g n)\n  then show ?case\n    by (cases r') auto\nnext\n  case (Test m g \\<phi>)\n  then show ?case\n    apply (cases r')\n        apply auto\n    subgoal for \\<psi>\n      apply (cases \"safe_formula \\<phi>\")\n       apply simp\n      apply (cases \\<phi>)\n                      apply (auto)\n      subgoal for \\<phi>' x\n        using Test(4)[of \\<phi>' \\<psi>]\n        by (cases \\<psi>) auto\n      done\n    done\nnext\n  case (Plus m g r s)\n  then show ?case\n    using rel_regex_fv_cong[OF _ Plus(5)]\n    by (cases r') auto\nnext\n  case (TimesF g r s)\n  then show ?case\n    using rel_regex_fv_cong[OF _ TimesF(5)]\n    by (cases r') auto\nnext\n  case (TimesP g r s)\n  then show ?case\n    using rel_regex_fv_cong[OF _ TimesP(5)]\n    by (cases r') auto\nnext\n  case (Star m g r)\n  then show ?case\n    using rel_regex_fv_cong[OF _ Star(4)]\n    by (cases r') auto\nqed\n\nlemma list_all2_setD1: \"list_all2 f xs ys \\<Longrightarrow> x \\<in> set xs \\<Longrightarrow> \\<exists>y \\<in> set ys. f x y\"\n  by (induction xs ys rule: list.rel_induct) auto\n\nlemma list_all2_setD2: \"list_all2 f xs ys \\<Longrightarrow> y \\<in> set ys \\<Longrightarrow> \\<exists>x \\<in> set xs. f x y\"\n  by (induction xs ys rule: list.rel_induct) auto\n\nlemma rel_formula_safe: \"safe_formula \\<phi> \\<Longrightarrow> formula.rel_formula f \\<phi> \\<psi> \\<Longrightarrow> safe_formula \\<psi>\"\nproof (induction \\<phi> arbitrary: \\<psi> rule: safe_formula_induct)\n  case (Eq_Const c d)\n  then show ?case\n    by (cases \\<psi>) auto\nnext\n  case (Eq_Var1 c x)\n  then show ?case\n    by (cases \\<psi>) auto\nnext\n  case (Eq_Var2 c x)\n  then show ?case\n    by (cases \\<psi>) auto\nnext\n  case (Pred e ts)\n  then show ?case\n    by (cases \\<psi>) auto\nnext\n  case (Let p \\<phi>' \\<phi> \\<psi> )\n  then show ?case\n    by (cases \\<psi>) (auto simp: Formula.nfv_def rel_formula_fv)\nnext\n  case (And_assign \\<phi> \\<phi>' \\<psi>)\n  then show ?case\n    apply (cases \\<psi>)\n                    apply (auto simp: rel_formula_fv)\n     apply (auto simp: safe_assignment_def split: formula.splits)\n    done\nnext\n  case (And_safe \\<phi> \\<psi>)\n  then show ?case\n    by (cases \\<psi>) auto\nnext\n  case (And_constraint \\<phi> \\<phi>' \\<psi>)\n  moreover have \"is_constraint \\<phi>' \\<Longrightarrow> formula.rel_formula f \\<phi>' \\<psi>' \\<Longrightarrow> is_constraint \\<psi>'\" for \\<psi>'\n    by (cases \\<phi>' rule: is_constraint.cases; cases \\<psi>' rule: is_constraint.cases) auto\n  ultimately show ?case\n    by (cases \\<psi>) (auto simp: rel_formula_fv)\nnext\n  case (And_Not \\<phi> \\<phi>' \\<psi>)\n  then show ?case\n    by (cases \\<psi>) (auto simp: rel_formula_fv elim!: formula.rel_cases[of _ \"formula.Neg \\<phi>'\"])\nnext\n  case (Ands l pos neg \\<psi>)\n  obtain l' pos' neg' where \\<psi>_def: \"\\<psi> = formula.Ands l'\" \"partition safe_formula l' = (pos', neg')\"\n    \"list_all2 (formula.rel_formula f) l l'\"\n    using Ands(8)\n    by (cases \\<psi>) auto\n  note part = partition_P[OF \\<psi>_def(2)] partition_set[OF Ands(1)[symmetric], symmetric]\n    partition_set[OF \\<psi>_def(2), symmetric]\n  have pos_pos': \"\\<exists>p' \\<in> set pos'. formula.rel_formula f p p'\" if \"p \\<in> set pos\" for p\n    using that list_all2_setD1[OF \\<psi>_def(3), of p] part Ands(6)\n    by (auto simp: list_all_def)\n  have neg'_neg: \"\\<exists>n \\<in> set neg. formula.rel_formula f n n'\" if \"n' \\<in> set neg'\" for n'\n    using that list_all2_setD2[OF \\<psi>_def(3), of n'] part Ands(6)\n    by (auto simp: list_all_def)\n  have \"pos' \\<noteq> []\"\n    using Ands(2) pos_pos'\n    by fastforce\n  moreover have \"safe_formula (remove_neg x')\" if \"x' \\<in> set neg'\" for x'\n  proof -\n    have \"formula.rel_formula f (remove_neg g) (remove_neg h)\" if \"formula.rel_formula f g h\" for g h\n      using that\n      by (cases g; cases h) auto\n    then show ?thesis\n      using neg'_neg[OF that] Ands(4,7)\n      by (auto simp: list_all_def dest!: bspec spec[of _ \"remove_neg x'\"])\n  qed\n  moreover have \"\\<exists>p' \\<in> set pos'. x \\<in> fv p'\" if n': \"n' \\<in> set neg'\" \"x \\<in> fv n'\" for x n'\n  proof -\n    obtain n where n_def: \"n \\<in> set neg\" \"x \\<in> fv n\"\n      using neg'_neg[OF n'(1)] n'(2)\n      by (auto simp: rel_formula_fv)\n    then obtain p where p_def: \"p \\<in> set pos\" \"x \\<in> fv p\"\n      using Ands(5)\n      by auto\n    show ?thesis\n      using pos_pos'[OF p_def(1)] p_def(2)\n      by (auto simp: rel_formula_fv)\n  qed\n  ultimately show ?case\n    by (auto simp: \\<psi>_def(1,2) list_all_def simp del: partition_filter_conv)\nnext\n  case (Neg \\<phi>)\n  then show ?case\n    by (cases \\<psi>) (auto simp: rel_formula_fv)\nnext\n  case (Or \\<phi> \\<phi>' \\<psi>)\n  then show ?case\n    by (cases \\<psi>) (auto simp: rel_formula_fv)\nnext\n  case (Exists \\<phi> t)\n  then show ?case\n    by (cases \\<psi>) (auto simp: rel_formula_fv)\nnext\n  case (Agg y \\<omega> tys t \\<phi>)\n  then show ?case\n    using list_all2_lengthD[of f tys]\n    by (cases \\<psi>) (auto simp: rel_formula_fv)\nnext\n  case (Prev I \\<phi>)\n  then show ?case\n    by (cases \\<psi>) auto\nnext\n  case (Next I \\<phi>)\n  then show ?case\n    by (cases \\<psi>) auto\nnext\n  case (Since \\<phi> I \\<phi>' \\<psi>)\n  then show ?case\n    by (cases \\<psi>) (auto simp: rel_formula_fv)\nnext\n  case (Not_Since \\<phi> I \\<phi>' \\<psi>)\n  then show ?case\n    by (cases \\<psi>) (auto simp: rel_formula_fv elim!: formula.rel_cases[of _ \"formula.Neg \\<phi>\"])\nnext\n  case (Until \\<phi> I \\<phi>' \\<psi>)\n  then show ?case\n    by (cases \\<psi>) (auto simp: rel_formula_fv)\nnext\n  case (Not_Until \\<phi> I \\<phi>' \\<psi>)\n  then show ?case\n    by (cases \\<psi>) (auto simp: rel_formula_fv elim!: formula.rel_cases[of _ \"formula.Neg \\<phi>\"])\nnext\n  case (MatchP I r)\n  have \"regex.rel_regex (formula.rel_formula f) r r' \\<Longrightarrow> safe_regex Past Strict r'\" for r'\n    apply (rule rel_regex_safe_aux[OF MatchP(1), where ?P=\"formula.rel_formula f\"])\n    using MatchP(2)\n    by (auto simp: rel_formula_fv split: formula.splits)\n  then show ?case\n    using MatchP\n    by (cases \\<psi>) auto\nnext\n  case (MatchF I r)\n  have \"regex.rel_regex (formula.rel_formula f) r r' \\<Longrightarrow> safe_regex Futu Strict r'\" for r'\n    apply (rule rel_regex_safe_aux[OF MatchF(1), where ?P=\"formula.rel_formula f\"])\n    using MatchF(2)\n    by (auto simp: rel_formula_fv split: formula.splits)\n  then show ?case\n    using MatchF\n    by (cases \\<psi>) auto\nqed\n\nlemma rel_regex_regex_atms: \"Regex.rel_regex f r r' \\<Longrightarrow> x \\<in> Regex.atms r \\<Longrightarrow> \\<exists>x' \\<in> Regex.atms r'. f x x'\"\n  by (induction r r' rule: regex.rel_induct) auto\n\nlemma list_all2_swap: \"list_all2 f xs ys \\<Longrightarrow> list_all2 (\\<lambda>x y. f y x) ys xs\"\n  by (induction xs ys rule: list.rel_induct) auto\n\nlemma rel_regex_swap: \"regex.rel_regex f r r' \\<Longrightarrow> regex.rel_regex (\\<lambda>x y. f y x) r' r\"\n  by (induction r r' rule: regex.rel_induct) auto\n\nlemma rel_formula_swap: \"formula.rel_formula f x y \\<Longrightarrow> formula.rel_formula (\\<lambda>x y. f y x) y x\"\n  by (induction x y rule: formula.rel_induct) (auto intro: list_all2_swap rel_regex_swap)\n\nlemma rel_regex_safe:\n  assumes \"Regex.rel_regex (formula.rel_formula f) r r'\" \"safe_regex m g r\"\n  shows \"safe_regex m g r'\"\nproof -\n  have rel_Neg: \"\\<And>\\<phi> \\<phi>'. formula.rel_formula f (formula.Neg \\<phi>) \\<phi>' \\<Longrightarrow>\n    case \\<phi>' of formula.Neg x \\<Rightarrow> formula.rel_formula f \\<phi> x | _ \\<Rightarrow> False\"\n    by (auto split: formula.splits)\n  show ?thesis\n    using rel_regex_safe_aux[OF _ _ _ rel_Neg assms(1)] rel_formula_safe assms(2)\n    by (fastforce simp: rel_formula_fv)\nqed\n\nlemma rel_regex_atms:\n  assumes \"Regex.rel_regex (formula.rel_formula f) r r'\" \"x \\<in> atms r\"\n  shows \"\\<exists>x' \\<in> atms r'. formula.rel_formula f x x'\"\nproof -\n  obtain \\<phi> where \\<phi>_def: \"\\<phi> \\<in> Regex.atms r\" \"safe_formula \\<phi> \\<Longrightarrow> \\<phi> = x\"\n    \"\\<not>safe_formula \\<phi> \\<Longrightarrow> \\<phi> = formula.Neg x\"\n    using assms(2)\n    by (auto simp: atms_def) (force split: formula.splits)\n  obtain x' where x'_def: \"x' \\<in> regex.atms r'\" \"formula.rel_formula f \\<phi> x'\"\n    using rel_regex_regex_atms[OF assms(1) \\<phi>_def(1)]\n    by auto\n  show ?thesis\n  proof (cases \"safe_formula \\<phi>\")\n    case True\n    then show ?thesis\n      using x'_def rel_formula_safe[OF True x'_def(2)]\n      by (auto simp: \\<phi>_def(2)[OF True] atms_def intro!: UN_I[OF x'_def(1)] bexI[of _ x'])\n  next\n    case False\n    obtain x'' where x''_def: \"x' = formula.Neg x''\" \"formula.rel_formula f x x''\"\n      using x'_def(2)\n      by (cases x') (auto simp: \\<phi>_def(3)[OF False])    \n    show ?thesis\n      using x''_def(2) rel_formula_safe[OF _ rel_formula_swap[OF x'_def(2)]] False\n      unfolding atms_def\n      by (fastforce simp: x''_def intro!: UN_I[OF x'_def(1)] bexI[of _ x''])\n  qed\nqed\n\nlemma fv_safe_regex_atms: \"safe_regex m g r \\<Longrightarrow> x \\<in> Regex.fv_regex Formula.fv r \\<Longrightarrow>\n  \\<exists>\\<phi> \\<in> atms r. safe_formula \\<phi> \\<and> x \\<in> Formula.fv \\<phi>\"\nproof (induction r)\n  case (Test z)\n  then show ?case\n    by (cases z) (auto simp: atms_def)\nnext\n  case (Times r1 r2)\n  then show ?case\n    by (cases m) auto\nqed auto\n\nlemma pred_regex_wty_formula: \"regex.pred_regex (wty_formula S E) r \\<Longrightarrow> \\<phi> \\<in> atms r \\<Longrightarrow> S, E \\<turnstile> \\<phi>\"\n  by (induction r) (auto split: if_splits formula.splits elim: wty_formula.cases)\n\nlemma wty_trm_cong_aux: \"E \\<turnstile> t :: typ \\<Longrightarrow> E \\<turnstile> t :: typ' \\<Longrightarrow> typ = typ'\"\nproof (induction t \"typ\" arbitrary: typ' rule: wty_trm.induct)\n  case (Plus x t y)\n  have \"E \\<turnstile> x :: typ'\"\n    using Plus(6)\n    by (auto elim: wty_trm.cases)\n  then show ?case\n    using Plus(4)\n    by auto\nnext\n  case (Minus x t y)\n  have \"E \\<turnstile> x :: typ'\"\n    using Minus(6)\n    by (auto elim: wty_trm.cases)\n  then show ?case\n    using Minus(4)\n    by auto\nnext\n  case (UMinus x t)\n  then show ?case\n    by (fastforce elim!: wty_trm.cases[of E \"trm.UMinus x\" typ'])\nnext\n  case (Mult x t y)\n  have \"E \\<turnstile> x :: typ'\"\n    using Mult(6)\n    by (auto elim: wty_trm.cases)\n  then show ?case\n    using Mult(4)\n    by auto\nnext\n  case (Div x t y)\n  have \"E \\<turnstile> x :: typ'\"\n    using Div(6)\n    by (auto elim: wty_trm.cases)\n  then show ?case\n    using Div(4)\n    by auto\nnext\n  case (Mod x y)\n  have \"E \\<turnstile> x :: typ'\"\n    using Mod(5)\n    by (auto elim: wty_trm.cases)\n  then show ?case\n    using Mod(3)\n    by auto\nnext\n  case (F2i x)\n  then show ?case\n    by (fastforce elim!: wty_trm.cases[of E \"trm.F2i x\" typ'])\nnext\n  case (I2f x)\n  then show ?case\n    by (fastforce elim!: wty_trm.cases[of E \"trm.I2f x\" typ'])\nqed (auto elim: wty_trm.cases)\n\nlemma wty_trm_cong: \" (\\<And>y. y \\<in> fv_trm t \\<Longrightarrow> E y = E' y) \\<Longrightarrow>\n  E \\<turnstile> t :: typ \\<Longrightarrow> E' \\<turnstile> t :: typ' \\<Longrightarrow> typ = typ'\"\n  using wty_trm_fv_cong wty_trm_cong_aux\n  by blast\n\nlemma wty_safe_assignment_dest: \"wty_formula S E \\<psi> \\<Longrightarrow> safe_assignment X \\<psi> \\<Longrightarrow> x \\<in> fv \\<psi> - X \\<Longrightarrow>\n  \\<exists>t. E \\<turnstile> t :: E x \\<and> fv_trm t \\<subseteq> X \\<and> (\\<psi> = formula.Eq (trm.Var x) t \\<or> \\<psi> = formula.Eq t (trm.Var x))\"\n  by (auto simp: safe_assignment_def elim!: wty_formula.cases[of S E \\<psi>])\n     (auto elim!: wty_trm.cases[of E \"trm.Var x\"] split: trm.splits)\n\n(*Lemma 5.1*)\nlemma rel_formula_wty_unique_fv: \"safe_formula \\<phi> \\<Longrightarrow> wty_formula S E \\<phi> \\<Longrightarrow> wty_formula S E' \\<phi>' \\<Longrightarrow>\n  Formula.rel_formula f \\<phi> \\<phi>' \\<Longrightarrow> x \\<in> fv \\<phi> \\<Longrightarrow> E x = E' x\"\nproof (induction \\<phi> arbitrary: S E E' \\<phi>' x rule: safe_formula_induct)\n  case (Eq_Var1 c y)\n  then show ?case\n    by (auto elim!: wty_formula.cases[of S E \"formula.Eq (trm.Const c) (trm.Var y)\"] wty_formula.cases[of S E' \\<phi>'])\n       (auto elim!: wty_trm.cases[of E] wty_trm.cases[of E'])\nnext\n  case (Eq_Var2 c y)\n  then show ?case\n    by (auto elim!: wty_formula.cases[of S E \"formula.Eq (trm.Var y) (trm.Const c)\"] wty_formula.cases[of S E' \\<phi>'])\n       (auto elim!: wty_trm.cases[of E] wty_trm.cases[of E'])\nnext\n  case (Pred e ts)\n  then show ?case\n    apply (auto elim!: wty_formula.cases[of S E \"formula.Pred e ts\"] wty_formula.cases[of S E' \\<phi>'])\n    subgoal for t tys\n      apply (cases t)\n               apply (auto simp: list_all2_conv_all_nth elim!: wty_trm.cases[of _ \"trm.Var x\"])\n      apply (auto simp: in_set_conv_nth)\n      apply (auto dest!: spec elim!: wty_trm.cases[of _ \"trm.Var x\"])\n      done\n    done\nnext\n  case (Let p \\<phi> \\<phi>' S E E' \\<alpha>)\n  obtain \\<psi> \\<psi>' where \\<alpha>_def: \"\\<alpha> = formula.Let p \\<psi> \\<psi>'\"\n    \"formula.rel_formula f \\<phi> \\<psi>\" \"formula.rel_formula f \\<phi>' \\<psi>'\"\n    using Let(8)\n    by (cases \\<alpha>) auto\n  obtain F where F_def: \"S, F \\<turnstile> \\<phi>\"\n    \"S(p \\<mapsto> tabulate F 0 (Formula.nfv \\<phi>)), E \\<turnstile> \\<phi>'\"\n    using Let(6)\n    by (auto elim: wty_formula.cases)\n  obtain F' where F'_def: \"S, F' \\<turnstile> \\<psi>\"\n    \"S(p \\<mapsto> tabulate F' 0 (Formula.nfv \\<psi>)), E' \\<turnstile> \\<psi>'\"\n    using Let(7)\n    by (auto simp: \\<alpha>_def(1) elim: wty_formula.cases)\n  have nfv: \"Formula.nfv \\<phi> = Formula.nfv \\<psi>\"\n    using \\<alpha>_def(2)\n    by (auto simp: Formula.nfv_def rel_formula_fv)\n  have tab: \"tabulate F 0 (Formula.nfv \\<psi>) = tabulate F' 0 (Formula.nfv \\<psi>)\"\n    using Let(1) Let(4)[OF F_def(1) F'_def(1) \\<alpha>_def(2)]\n    by (auto simp: nfv tabulate_alt)\n  show ?case\n    using Let(5)[OF F_def(2) F'_def(2)[folded tab nfv] \\<alpha>_def(3)] Let(9)\n    by auto\nnext\n  case (And_assign \\<phi> \\<psi> S E E' \\<alpha>)\n  have case_\\<phi>: \"E z = E' z\" if \"z \\<in> fv \\<phi>\" for z\n    using And_assign that\n    by (auto elim!: wty_formula.cases[of S E \"Formula.And \\<phi> \\<psi>\"] wty_formula.cases[of S E' \\<alpha>])\n  {\n    assume notin: \"x \\<notin> fv \\<phi>\"\n    obtain \\<phi>' \\<psi>' where \\<alpha>_def: \"\\<alpha> = Formula.And \\<phi>' \\<psi>'\"\n      \"Formula.rel_formula f \\<phi> \\<phi>'\" \"Formula.rel_formula f \\<psi> \\<psi>'\"\n      using And_assign\n      by (cases \\<alpha>) auto\n    obtain t where t_def: \"E \\<turnstile> t :: E x\" \"fv_trm t \\<subseteq> fv \\<phi>\"\n      \"\\<psi> = formula.Eq (trm.Var x) t \\<or> \\<psi> = formula.Eq t (trm.Var x)\"\n      using wty_safe_assignment_dest[of S E \\<psi> \"fv \\<phi>\" x] notin And_assign(2,4,7)\n      by (auto elim: wty_formula.cases)\n    have \"safe_assignment (fv \\<phi>') \\<psi>'\"\n      using And_assign(2) \\<alpha>_def(2,3)\n      by (auto simp: rel_formula_fv safe_assignment_def split: formula.splits)\n    then obtain t' where t'_def: \"E' \\<turnstile> t' :: E' x\" \"fv_trm t' \\<subseteq> fv \\<phi>'\"\n      \"\\<psi>' = formula.Eq (trm.Var x) t' \\<or> \\<psi>' = formula.Eq t' (trm.Var x)\"\n      using wty_safe_assignment_dest[of S E' \\<psi>' \"fv \\<phi>'\" x] notin And_assign(2,5,7) \\<alpha>_def(2,3)\n      by (auto simp: \\<alpha>_def(1) rel_formula_fv elim: wty_formula.cases)\n    have ?case\n      using t_def t'_def \\<alpha>_def(2,3) wty_trm_cong[of t' E E', OF case_\\<phi>]\n      by (fastforce simp: rel_formula_fv)\n  }\n  then show ?case\n    using case_\\<phi>\n    by (cases \"x \\<in> fv \\<phi>\") auto\nnext\n  case (And_safe \\<phi> \\<psi> S E E' \\<alpha>)\n  then show ?case\n    by (auto elim!: wty_formula.cases[of S E \"Formula.And \\<phi> \\<psi>\"] wty_formula.cases[of S E' \\<alpha>])\nnext\n  case (And_constraint \\<phi> \\<psi> S E E' \\<alpha>)\n  then show ?case\n    by (auto elim!: wty_formula.cases[of S E \"Formula.And \\<phi> \\<psi>\"] wty_formula.cases[of S E' \\<alpha>])\nnext\n  case (And_Not \\<phi> \\<psi> S E E' \\<alpha>)\n  then show ?case\n    by (auto elim!: wty_formula.cases[of S E \"Formula.And \\<phi> (Formula.Neg \\<psi>)\"] wty_formula.cases[of S E' \\<alpha>])\nnext\n  case (Ands l pos neg S E E' \\<psi>)\n  obtain l' pos' neg' where \\<psi>_def: \"\\<psi> = formula.Ands l'\" \"partition safe_formula l' = (pos', neg')\"\n    \"list_all2 (formula.rel_formula f) l l'\"\n    using Ands(10)\n    by (cases \\<psi>) auto\n  note part = partition_P[OF Ands(1)[symmetric]] partition_P[OF \\<psi>_def(2)] partition_set[OF Ands(1)[symmetric], symmetric]\n    partition_set[OF \\<psi>_def(2), symmetric]\n  have pos_pos': \"\\<exists>p' \\<in> set pos'. formula.rel_formula f p p'\" if \"p \\<in> set pos\" for p\n    using that list_all2_setD1[OF \\<psi>_def(3), of p] part rel_formula_safe\n    by (fastforce simp: list_all_def)\n  obtain p where p_def: \"p \\<in> set pos\" \"x \\<in> fv p\"\n    using Ands(5,11) part\n    by auto\n  then obtain p' where p'_def: \"p' \\<in> set pos'\" \"formula.rel_formula f p p'\"\n    using pos_pos'\n    by auto\n  show ?case\n    using Ands(6,8,9) part(3,4) p_def p'_def\n    by (force simp: list_all_def \\<psi>_def(1) elim!: wty_formula.cases[of S _ \"formula.Ands _\"])\nnext\n  case (Neg \\<phi>)\n  then show ?case\n    by (auto elim!: wty_formula.cases[of S E \"formula.Neg \\<phi>\"] wty_formula.cases[of S E' \\<phi>'])\nnext\n  case (Or \\<phi> \\<psi> S E E' \\<alpha>)\n  then show ?case\n    by (auto elim!: wty_formula.cases[of S E \"Formula.Or \\<phi> \\<psi>\"] wty_formula.cases[of S E' \\<alpha>])\nnext\n  case (Exists \\<phi> t)\n  then show ?case\n    by (fastforce simp: fvi_Suc elim!: wty_formula.cases[of S E \"Formula.Exists t \\<phi>\"] wty_formula.cases[of S E' \\<phi>'])\nnext\n  case (Agg y \\<omega> tys trm \\<phi> S E E' \\<psi>)\n  obtain agg_type d where \\<omega>_def: \"\\<omega> = (agg_type, d)\"\n    by fastforce\n  obtain t where wty_\\<phi>: \"S, agg_env E tys \\<turnstile> \\<phi>\" \"E y = t_res agg_type t\" \"agg_env E tys \\<turnstile> trm :: t\"\n    using Agg\n    by (auto simp: \\<omega>_def elim!: wty_formula.cases[of S E \"formula.Agg y (agg_type, d) tys trm \\<phi>\"])\n  obtain tys' \\<phi>' where \\<psi>_def: \"\\<psi> = formula.Agg y \\<omega> tys' trm \\<phi>'\"\n    \"formula.rel_formula f \\<phi> \\<phi>'\" \"list_all2 f tys tys'\"\n    using Agg(8)\n    by (cases \\<psi>) auto\n  have tys_tys': \"length tys = length tys'\"\n    using \\<psi>_def(3)\n    by (auto simp: list_all2_lengthD)\n  obtain t' where wty_\\<phi>': \"S, agg_env E' tys' \\<turnstile> \\<phi>'\" \"E' y = t_res agg_type t'\" \"agg_env E' tys' \\<turnstile> trm :: t'\"\n    using Agg(7)\n    by (auto simp: \\<psi>_def(1) \\<omega>_def elim!: wty_formula.cases[of S E' \"formula.Agg y (agg_type, d) tys' trm \\<phi>'\"])\n  note IH = Agg(5)[OF order.refl Agg(4) wty_\\<phi>(1) wty_\\<phi>'(1) \\<psi>_def(2)]\n  {\n    assume x: \"x \\<in> fv (formula.Agg y \\<omega> tys trm \\<phi>)\" \"x \\<noteq> y\"\n    have x_fv_\\<phi>: \"x + length tys \\<in> fv \\<phi>\"\n      using Agg(3) x\n      by (auto simp: fvi_iff_fv[where ?b=\"length tys\"] fvi_trm_iff_fv_trm[where ?b=\"length tys\"])\n    have \"E x = E' x\"\n      using IH[OF x_fv_\\<phi>]\n      by (auto simp: agg_env_def tys_tys')\n  }\n  then show ?case\n    using Agg(3,9) wty_\\<phi>(3) wty_\\<phi>'(3) wty_trm_cong[of trm \"agg_env E tys\" \"agg_env E' tys'\", OF IH]\n    by (cases \"x = y\") (auto simp: \\<psi>_def(1) wty_\\<phi>(2) wty_\\<phi>'(2))\nnext\n  case (Prev I \\<phi>)\n  then show ?case\n    by (auto elim!: wty_formula.cases[of S E \"formula.Prev I \\<phi>\"] wty_formula.cases[of S E' \\<phi>'])\nnext\n  case (Next I \\<phi>)\n  then show ?case\n    by (auto elim!: wty_formula.cases[of S E \"formula.Next I \\<phi>\"] wty_formula.cases[of S E' \\<phi>'])\nnext\n  case (Since \\<phi> I \\<psi> S E E' \\<alpha>)\n  then show ?case\n    by (auto elim!: wty_formula.cases[of S E \"Formula.Since \\<phi> I \\<psi>\"] wty_formula.cases[of S E' \\<alpha>])\nnext\n  case (Not_Since \\<phi> I \\<psi> S E E' \\<alpha>)\n  then show ?case\n    by (auto elim!: wty_formula.cases[of S E \"Formula.Since (Formula.Neg \\<phi>) I \\<psi>\"] wty_formula.cases[of S E' \\<alpha>])\nnext\n  case (Until \\<phi> I \\<psi> S E E' \\<alpha>)\n  then show ?case\n    by (auto elim!: wty_formula.cases[of S E \"Formula.Until \\<phi> I \\<psi>\"] wty_formula.cases[of S E' \\<alpha>])\nnext\n  case (Not_Until \\<phi> I \\<psi> S E E' \\<alpha>)\n  then show ?case\n    by (auto elim!: wty_formula.cases[of S E \"Formula.Until (Formula.Neg \\<phi>) I \\<psi>\"] wty_formula.cases[of S E' \\<alpha>])\nnext\n  case (MatchP I r)\n  obtain r' where r'_def: \"\\<phi>' = formula.MatchP I r'\" \"Regex.rel_regex (formula.rel_formula f) r r'\"\n    using MatchP(5)\n    by (cases \\<phi>') auto\n  obtain a where a_def: \"a \\<in> atms r\" \"x \\<in> fv a\"\n    using MatchP(6) fv_safe_regex_atms[OF MatchP(1)]\n    by force\n  obtain a' where a'_def: \"a' \\<in> atms r'\" \"formula.rel_formula f a a'\"\n    using rel_regex_atms[OF r'_def(2) a_def(1)]\n    by auto\n  have wty: \"S, E \\<turnstile> a\" \"S, E' \\<turnstile> a'\"\n    using MatchP(3,4) a_def(1) a'_def(1)\n    by (auto simp: r'_def(1) elim!: wty_formula.cases[of S E \"formula.MatchP I r\"]\n        wty_formula.cases[of S E' \"formula.MatchP I r'\"] intro: pred_regex_wty_formula)\n  show ?case\n    using MatchP(2) a_def(1) wty a'_def(2) a_def(2)\n    by auto\nnext\n  case (MatchF I r)\n  obtain r' where r'_def: \"\\<phi>' = formula.MatchF I r'\" \"Regex.rel_regex (formula.rel_formula f) r r'\"\n    using MatchF(5)\n    by (cases \\<phi>') auto\n  obtain a where a_def: \"a \\<in> atms r\" \"x \\<in> fv a\"\n    using MatchF(6) fv_safe_regex_atms[OF MatchF(1)]\n    by force\n  obtain a' where a'_def: \"a' \\<in> atms r'\" \"formula.rel_formula f a a'\"\n    using rel_regex_atms[OF r'_def(2) a_def(1)]\n    by auto\n  have wty: \"S, E \\<turnstile> a\" \"S, E' \\<turnstile> a'\"\n    using MatchF(3,4) a_def(1) a'_def(1)\n    by (auto simp: r'_def(1) elim!: wty_formula.cases[of S E \"formula.MatchF I r\"]\n        wty_formula.cases[of S E' \"formula.MatchF I r'\"] intro: pred_regex_wty_formula)\n  show ?case\n    using MatchF(2) a_def(1) wty a'_def(2) a_def(2)\n    by auto\nqed auto\n\nlemma safe_regex_regex_atms_dest:\n  assumes \"safe_regex m g r\" \"a \\<in> regex.atms r\"\n  shows \"safe_formula a \\<and> a \\<in> atms r \\<or> (\\<not>safe_formula a \\<and> (case a of formula.Neg \\<phi> \\<Rightarrow> \\<phi> \\<in> atms r | _ \\<Rightarrow> False))\"\n  using assms\nproof (induction m g r rule: safe_regex.induct)\n  case (2 m g \\<phi>)\n  then show ?case\n    by (cases \"safe_formula a\") (auto split: formula.splits)\nnext\n  case (3 m g r s)\n  then show ?case\n    by (cases a) auto\nnext\n  case (4 g r s)\n  then show ?case\n    by (cases a) auto\nnext\n  case (5 g r s)\n  then show ?case\n    by (cases a) auto\nnext\n  case (6 m g r)\n  then show ?case\n    by (cases a) auto\nqed (auto split: formula.splits)\n\n(*Lemma 5.2*)\nlemma rel_formula_wty_unique_bv_aux: \"safe_formula \\<phi> \\<Longrightarrow> wty_formula S E \\<phi> \\<Longrightarrow> wty_formula S E' \\<phi>' \\<Longrightarrow>\n  Formula.rel_formula f \\<phi> \\<phi>' \\<Longrightarrow> Formula.rel_formula (=) \\<phi> \\<phi>'\"\nproof (induction \\<phi> arbitrary: S E E' \\<phi>' rule: safe_formula_induct)\n  case (Eq_Const c d)\n  then show ?case\n    by (cases \\<phi>') auto\nnext\n  case (Eq_Var1 c x)\n  then show ?case\n    by (cases \\<phi>') auto\nnext\n  case (Eq_Var2 c x)\n  then show ?case\n    by (cases \\<phi>') auto\nnext\n  case (Pred e ts)\n  then show ?case\n    by (cases \\<phi>') auto\nnext\n  case (Let p \\<phi> \\<phi>' S E E' \\<alpha>)\n  obtain \\<psi> \\<psi>' where \\<alpha>_def: \"\\<alpha> = formula.Let p \\<psi> \\<psi>'\"\n    \"formula.rel_formula f \\<phi> \\<psi>\" \"formula.rel_formula f \\<phi>' \\<psi>'\"\n    using Let(8)\n    by (cases \\<alpha>) auto\n  obtain F where F_def: \"S, F \\<turnstile> \\<phi>\"\n    \"S(p \\<mapsto> tabulate F 0 (Formula.nfv \\<phi>)), E \\<turnstile> \\<phi>'\"\n    using Let(6)\n    by (auto elim: wty_formula.cases)\n  obtain F' where F'_def: \"S, F' \\<turnstile> \\<psi>\"\n    \"S(p \\<mapsto> tabulate F' 0 (Formula.nfv \\<psi>)), E' \\<turnstile> \\<psi>'\"\n    using Let(7)\n    by (auto simp: \\<alpha>_def(1) elim: wty_formula.cases)\n  have nfv: \"Formula.nfv \\<phi> = Formula.nfv \\<psi>\"\n    using \\<alpha>_def(2)\n    by (auto simp: Formula.nfv_def rel_formula_fv)\n  have tab: \"tabulate F 0 (Formula.nfv \\<psi>) = tabulate F' 0 (Formula.nfv \\<psi>)\"\n    using Let(1) rel_formula_wty_unique_fv[OF Let(2) F_def(1) F'_def(1) \\<alpha>_def(2)]\n    by (auto simp: nfv tabulate_alt)\n  show ?case\n    using Let(4)[OF F_def(1) F'_def(1) \\<alpha>_def(2)]\n      Let(5)[OF F_def(2) F'_def(2)[folded tab nfv] \\<alpha>_def(3)]\n    by (auto simp: \\<alpha>_def(1))\nnext\n  case (And_assign \\<phi> \\<psi>)\n  then show ?case\n    apply (cases \\<phi>')\n                    apply (auto elim!: wty_formula.cases[of _ _ \"formula.And _ _\"])\n    subgoal for x' y'\n      by (cases \\<psi>; cases y') (auto simp: safe_assignment_def)\n    done\nnext\n  case (And_safe \\<phi> \\<psi>)\n  then show ?case\n    by (cases \\<phi>') (auto elim!: wty_formula.cases[of _ _ \"formula.And _ _\"])\nnext\n  case (And_constraint \\<phi> \\<psi>)\n  then show ?case\n    apply (cases \\<phi>')\n                    apply (auto elim!: wty_formula.cases[of _ _ \"formula.And _ _\"])\n    subgoal for x' y'\n      by (cases \\<psi> rule: is_constraint.cases; cases y' rule: is_constraint.cases) auto\n    done\nnext\n  case (And_Not \\<phi> \\<psi>)\n  then show ?case\n    apply (cases \\<phi>') apply (auto elim!: wty_formula.cases[of _ _ \"formula.And _ _\"])\n    subgoal for x y z\n      by (cases z) (auto elim!: wty_formula.cases[of _ _ \"formula.Neg _\"])\n    done\nnext\n  case (Ands l pos neg)\n  have not_safe: \"(case z of formula.Neg \\<phi> \\<Rightarrow> True | _ \\<Rightarrow> False)\" if \"\\<not>safe_formula z\" \"z \\<in> set l\" for z\n    using Ands that\n    by (cases z) (auto simp: list_all_def simp del: safe_formula.simps)\n  have \"formula.rel_formula (=) z z'\"\n    if prems: \"z \\<in> set l\" \"z' \\<in> set l'\" \"formula.rel_formula f z z'\" \"\\<phi>' = formula.Ands l'\" for z z' l'\n  proof (cases \"safe_formula z\")\n    case True\n    then show ?thesis\n      using Ands that\n      by (fastforce simp: list_all_def elim!: wty_formula.cases[of _ _ \"formula.Ands _\"])\n  next\n    case False\n    obtain \\<phi> where z_def: \"z = formula.Neg \\<phi>\"\n      using not_safe[OF False prems(1)]\n      by (auto split: formula.splits)\n    show ?thesis\n      using prems(3)\n      apply (cases z')\n                      apply (auto simp: z_def)\n      using Ands prems False\n      by (fastforce simp: list_all_def z_def elim!: wty_formula.cases[of _ _ \"formula.Ands _\"] wty_formula.cases[of _ _ \"formula.Neg _\"] dest!: bspec[of \"set l\" _ \"formula.Neg \\<phi>\"]\n          bspec[of \"set l'\" _ \"formula.Neg _\"])\n  qed\n  then show ?case\n    using Ands\n    apply (cases \\<phi>')\n                    apply (auto simp: list_all_def)\n    apply (rule list.rel_mono_strong)\n     apply fastforce+\n    done\nnext\n  case (Neg \\<phi>)\n  then show ?case\n    by (cases \\<phi>') (auto elim!: wty_formula.cases[of _ _ \"formula.Neg _\"])\nnext\n  case (Or \\<phi> \\<psi>)\n  then show ?case\n    by (cases \\<phi>') (auto elim!: wty_formula.cases[of _ _ \"formula.Or _ _\"])\nnext\n  case (Exists \\<phi> t)\n  then show ?case\n    using rel_formula_wty_unique_fv[where ?x=0]\n    by (cases \\<phi>') (fastforce elim!: wty_formula.cases[of _ _ \"formula.Exists _ _ \"])+\nnext\n  case (Agg y \\<omega> tys trm \\<phi> S E E' \\<psi>)\n  obtain tys' \\<phi>' where \\<psi>_def: \"\\<psi> = formula.Agg y \\<omega> tys' trm \\<phi>'\" \"list_all2 f tys tys'\"\n    using Agg\n    by (cases \\<psi>) auto\n  have \"agg_env E tys x = agg_env E' tys' x\" if \"x \\<in> fv \\<phi>\" for x\n    using Agg rel_formula_wty_unique_fv[of \\<phi> S \"agg_env E tys\" \"agg_env E' tys'\" \\<phi>' f] that\n    by (auto simp: \\<psi>_def(1) elim!: wty_formula.cases[of _ _ \"formula.Agg _ _ _ _ _\"])\n  then have \"list_all2 (=) tys tys'\"\n    using Agg(2) \\<psi>_def(2)\n    by (fastforce simp: list_all2_conv_all_nth agg_env_def)\n  then show ?case\n    using Agg\n    by (auto simp: \\<psi>_def(1) elim!: wty_formula.cases[of _ _ \"formula.Agg _ _ _ _ _\"])\nnext\n  case (Prev I \\<phi>)\n  then show ?case\n    by (cases \\<phi>') (auto elim!: wty_formula.cases[of _ _ \"formula.Prev _ _\"])\nnext\n  case (Next I \\<phi>)\n  then show ?case\n    by (cases \\<phi>') (auto elim!: wty_formula.cases[of _ _ \"formula.Next _ _\"])\nnext\n  case (Since \\<phi> I \\<psi>)\n  then show ?case\n    by (cases \\<phi>') (auto elim!: wty_formula.cases[of _ _ \"formula.Since _ _ _\"])\nnext\n  case (Not_Since \\<phi> I \\<psi>)\n  then show ?case\n    apply (cases \\<phi>')\n                    apply (auto elim!: wty_formula.cases[of _ _ \"formula.Since _ _ _\"])\n    subgoal for x y z\n      by (cases y) (auto elim!: wty_formula.cases[of _ _ \"formula.Neg _\"])\n    done\nnext\n  case (Until \\<phi> I \\<psi>)\n  then show ?case\n    by (cases \\<phi>') (auto elim!: wty_formula.cases[of _ _ \"formula.Until _ _ _\"])\nnext\n  case (Not_Until \\<phi> I \\<psi>)\n  then show ?case\n    apply (cases \\<phi>')\n                    apply (auto elim!: wty_formula.cases[of _ _ \"formula.Until _ _ _\"])\n    subgoal for x y z\n      by (cases y) (auto elim!: wty_formula.cases[of _ _ \"formula.Neg _\"])\n    done\nnext\n  case (MatchP I r)\n  obtain r' where r'_def: \"\\<phi>' = formula.MatchP I r'\" \"Regex.rel_regex (formula.rel_formula f) r r'\"\n    using MatchP(5)\n    by (cases \\<phi>') auto\n  show ?case\n    using MatchP\n    apply (auto simp: r'_def(1))\n    apply (rule regex.rel_mono_strong)\n     apply assumption\n    subgoal for z z'\n      using rel_regex_safe[of f r r' Past Strict]\n        safe_regex_regex_atms_dest[of Past Strict r z]\n        safe_regex_regex_atms_dest[of Past Strict r' z']\n      apply (auto elim!: wty_formula.cases[of _ _ \"formula.MatchP _ _\"])\n      using pred_regex_wty_formula[of S E r] pred_regex_wty_formula[of S E' r']\n         apply fastforce\n        apply (meson rel_formula_safe)\n      using rel_formula_safe rel_formula_swap apply blast\n      subgoal\n        apply (cases z; cases z')\n                            apply auto\n        using pred_regex_wty_formula[of S E r] pred_regex_wty_formula[of S E' r']\n        by (fastforce elim!: wty_formula.cases[of _ _ \"formula.Neg _\"])+\n      done\n    done\nnext\n  case (MatchF I r)\n  obtain r' where r'_def: \"\\<phi>' = formula.MatchF I r'\" \"Regex.rel_regex (formula.rel_formula f) r r'\"\n    using MatchF(5)\n    by (cases \\<phi>') auto\n  show ?case\n    using MatchF\n    apply (auto simp: r'_def(1))\n    apply (rule regex.rel_mono_strong)\n     apply assumption\n    subgoal for z z'\n      using rel_regex_safe[of f r r' Futu Strict]\n        safe_regex_regex_atms_dest[of Futu Strict r z]\n        safe_regex_regex_atms_dest[of Futu Strict r' z']\n      apply (auto elim!: wty_formula.cases[of _ _ \"formula.MatchF _ _\"])\n      using pred_regex_wty_formula[of S E r] pred_regex_wty_formula[of S E' r']\n         apply fastforce\n        apply (meson rel_formula_safe)\n      using rel_formula_safe rel_formula_swap apply blast\n      subgoal\n        apply (cases z; cases z')\n                            apply auto\n        using pred_regex_wty_formula[of S E r] pred_regex_wty_formula[of S E' r']\n        by (fastforce elim!: wty_formula.cases[of _ _ \"formula.Neg _\"])+\n      done\n    done\nqed\n\nlemma list_all2_eq: \"list_all2 (=) xs ys \\<Longrightarrow> xs = ys\"\n  by (induction xs ys rule: list.rel_induct) auto\n\nlemma rel_regex_eq: \"regex.rel_regex (=) r r' \\<Longrightarrow> r = r'\"\n  by (induction r r' rule: regex.rel_induct) auto\n\nlemma rel_formula_eq: \"Formula.rel_formula (=) \\<phi> \\<phi>' \\<Longrightarrow> \\<phi> = \\<phi>'\"\n  by (induction \\<phi> \\<phi>' rule: formula.rel_induct) (auto simp: list_all2_eq rel_regex_eq)\n\nlemma rel_formula_wty_unique_bv: \"safe_formula \\<phi> \\<Longrightarrow> wty_formula S E \\<phi> \\<Longrightarrow> wty_formula S E' \\<phi>' \\<Longrightarrow>\n  Formula.rel_formula f \\<phi> \\<phi>' \\<Longrightarrow> \\<phi> = \\<phi>'\"\n  using rel_formula_wty_unique_bv_aux\n  by (auto simp: rel_formula_eq)\n\n\ndatatype tysym = TAny nat | TNum nat | TCst ty\n                                 \ntype_synonym tysenv = \"nat \\<Rightarrow> tysym\"\n\ndefinition agg_tysenv :: \"tysenv \\<Rightarrow> tysym list \\<Rightarrow> tysenv \" where\n\"agg_tysenv E tys =  (\\<lambda>z. if z < length tys then tys ! z else E (z - length tys))\"\n\ndefinition new_type_symbol :: \"tysym \\<Rightarrow> tysym\" where\n\"new_type_symbol t = (case t of TCst t \\<Rightarrow> TCst t | TAny n \\<Rightarrow> TAny (Suc n)| TNum n \\<Rightarrow> TNum (Suc n) )\"\n\nfun tyless :: \"tysym \\<Rightarrow> tysym \\<Rightarrow> bool\" where \n\"tyless (TNum a) (TNum b)  = (a \\<le> b)\"\n| \"tyless (TAny a) (TAny b)  = (a \\<le> b)\"\n| \"tyless (TNum _) (TAny _) = True\"\n| \"tyless (TCst _) ( _) = True\"\n| \"tyless _ _ = False\"\n\nfun type_clash :: \"tysym \\<Rightarrow> tysym \\<Rightarrow> bool\" where\n\"type_clash (TCst t1) (TCst t2) = (t1 \\<noteq> t2)\"\n| \"type_clash (TNum _) (TCst TString) = True\"\n| \"type_clash  (TCst TString) (TNum _) = True\"\n| \"type_clash  _ _ = False\"\n\nfun min_type :: \"tysym \\<Rightarrow> tysym \\<rightharpoonup> tysym \\<times> tysym\" where\n\"min_type (TNum a) (TNum b)  = Some (if a \\<le> b then (TNum a, TNum b) else (TNum b, TNum a) )\"\n| \"min_type (TAny a) (TAny b)  = Some (if a \\<le> b then (TAny a, TAny b) else (TAny b, TAny a) )\"\n| \"min_type ( x) (TAny y) = Some ( x, TAny y)\"\n| \"min_type (TAny y) x= Some ( x, TAny y)\"\n| \"min_type (TCst TString) (TNum _) = None\"\n| \"min_type  (TNum _) (TCst TString) = None\"\n| \"min_type (TCst x) (TNum y) = Some (TCst x, TNum y)\"\n| \"min_type  (TNum y) (TCst x)= Some (TCst x, TNum y)\"\n| \"min_type (TCst x) (TCst y) = (if x = y then Some (TCst x, TCst y) else None)\"\n\n\n\nlemma min_comm: \"min_type a b =  min_type b a\"\n  by (induction a b rule: min_type.induct)  auto\n\nlemma min_consistent: assumes \"min_type a b = Some(x,y)\" shows \"x = a \\<and> y=b \\<or> x = b \\<and> y = a\"\n  using assms by (induction a b rule: min_type.induct) (auto split: if_splits)\n\nlemma min_const: assumes \"min_type (TCst x) y = Some(a,b)\" shows \"a = TCst x\"\n  using assms by (induction \"TCst x\" y rule: min_type.induct) (auto split: if_splits)\n\ndefinition propagate_constraints :: \"tysym \\<Rightarrow> tysym \\<Rightarrow> tysenv \\<Rightarrow> tysenv\" where\n\"propagate_constraints t1 t2 E = (let (told,tnew) = if tyless t1 t2 then (t2,t1) else (t1,t2) in (\\<lambda>v. if E v = told then tnew else E v) )\"\n\ndefinition update_env :: \"tysym \\<times> tysym \\<Rightarrow> tysenv \\<Rightarrow> tysenv\" where\n\"update_env x E \\<equiv> case x of (tnew,told) \\<Rightarrow>(\\<lambda>v. if E v = told then tnew else E v) \"\n\n(* takes two types as input, checks if there's no clash, returns updated env and the more specific type*)\ndefinition clash_propagate :: \"tysym \\<Rightarrow> tysym \\<Rightarrow> tysenv \\<Rightarrow> (tysenv*tysym) option\" where\n\"clash_propagate t1 t2 E = (case min_type t1 t2 of Some (newt,oldt) \\<Rightarrow> Some ((update_env (newt,oldt) E),newt)| None \\<Rightarrow> None ) \"\n\ndefinition clash_propagate2 :: \"tysym \\<Rightarrow> tysym \\<Rightarrow> tysenv \\<rightharpoonup> (tysenv*tysym)\" where\n\"clash_propagate2 t1 t2 E = map_option  (\\<lambda>x . (update_env x E, fst x)) (min_type t1 t2)\"\n \nlemma clash_prop_alt: \"clash_propagate2 t1 t2 E = clash_propagate t1 t2 E\"\n  by (auto simp add: clash_propagate2_def clash_propagate_def split: option.splits) \n\nlemma clash_prop_comm: \"clash_propagate2 t1 t2 E = clash_propagate2 t2 t1 E\"\n  using min_comm by (auto simp add: clash_propagate2_def)\n\n\ndefinition trm_f :: \"(nat \\<Rightarrow> tysym) \\<Rightarrow> (nat \\<Rightarrow> tysym) \\<Rightarrow>nat set \\<Rightarrow> tysym set \\<Rightarrow> (tysym \\<Rightarrow> tysym) \" where\n\"trm_f E' E W X= undefined\"\n(*(\\<lambda>t. foldl (\\<lambda> t' n . if E n = t then E' n else t') t (sorted_list_of_set W) )*)\ndefinition trm_f_new :: \"(nat \\<Rightarrow> tysym) \\<Rightarrow> (nat \\<Rightarrow> tysym) \\<Rightarrow>tysym \\<Rightarrow> tysym \\<Rightarrow>nat set  \\<Rightarrow> tysym set \\<Rightarrow> (tysym \\<Rightarrow> tysym) \" where\n\"trm_f_new E' E typ' typ W X = undefined\"\n(* \"trm_f_new E' E typ' typ  W = (\\<lambda>t. if t = typ then typ' else foldl (\\<lambda> t' n\n. if E n = t then E' n else t') t (sorted_list_of_set W) )\" *)\n\n\nlemma trm_f_not_in_fv: assumes  \"\\<not>(\\<exists>n \\<in> set xs . E n = t)\" shows \"foldl (\\<lambda>t' n. if E n = t then E2 n else t') t xs = t\"\n  using assms by (induction xs) auto\n\n(*lemma trm_f_not_in_fv_high:   assumes  \"\\<not>(\\<exists>n \\<in> W . E n = t)\" \"finite W\" shows \"trm_f E2 E W X t = t\"\n unfolding trm_f_def apply (rule trm_f_not_in_fv) using  assms by (auto simp add: set_sorted_list_of_set[OF assms(2)])*)\n\nlemma trm_f_in_fv: assumes  \"n \\<in> set xs\" \"E n = t\" \"\\<forall>n' \\<in> set xs . E n' = t \\<longrightarrow> E2 n' = E2 n \"\n  shows \"foldl (\\<lambda>t' n. if E n = t then E2 n else t') t xs = E2 n\"\n  using assms(1,3) proof (induction xs rule: rev_induct)\n  case (snoc x xs)\n  {assume \"x = n\"\n    then have ?case using assms(2) by auto \n  }moreover {assume asm: \"x \\<noteq> n\"\n    have \" foldl (\\<lambda>t' n. if E n = t then E2 n else t') t xs = E2 n\" apply (rule snoc.IH) using snoc asm by auto\n    then have ?case using asm snoc.prems(2) by auto\n    }\n  ultimately show ?case by blast\nqed auto\n\n(*lemma trm_f_in_fv_high:   assumes  \"n \\<in> W\" \"E n = t\" \"finite W\" \"\\<forall>n' \\<in>W . E n' = t \\<longrightarrow> E2 n' = E2 n \"\n    shows \"trm_f E2 E W t =  E2 n\"\n  unfolding trm_f_def apply (rule trm_f_in_fv) using  assms(1,2) apply (auto simp add:  set_sorted_list_of_set[OF assms(3)])\n  using assms(4)\n  by blast\n*)\n\nlemma trm_f_foldl_id: assumes \"\\<forall>n \\<in> set w . t \\<noteq> E n \" shows \"foldl (\\<lambda>t' n. if E n = t then E' n else t') t w = t\"\n  using assms by (induction w)  auto \n(*\nlemma trm_f_id: assumes \"\\<forall>n' \\<in> W .t \\<noteq> E n'\" \"finite W\" shows \"(trm_f E' E W) t = t\"\n  unfolding trm_f_def using trm_f_foldl_id[of \"sorted_list_of_set W\"  \"t\" E E'] assms set_sorted_list_of_set[of W] \n  by simp *)\n\n\n\nlemma map_regex_size: assumes \"\\<And>x . x \\<in> regex.atms r \\<Longrightarrow>   size (f x) = size x\" shows \"regex.size_regex size r = regex.size_regex size (regex.map_regex f r) \"\n  using assms by (induction r arbitrary: ) auto\n\nlemma map_regex_map_formula_size[simp]: \" size (regex.map_regex (formula.map_formula f) r) = size r\"\n  by (induction r)  auto\n\nlemma map_formula_size[simp]:\"size (formula.map_formula f \\<psi>) = size \\<psi>\" \n  apply (induction \\<psi> arbitrary: f) \n apply auto apply ( simp add: dual_order.eq_iff size_list_pointwise) using map_regex_size  by metis+\n\n\ndefinition check_binop where  (* what if typ < exp_typ? e.g typ = TCst TInt*)\n\"check_binop check_trm E typ t1 t2 exp_typ  \\<equiv> \n(case  min_type exp_typ typ  of Some (newt,oldt) \\<Rightarrow> \n  (case check_trm (update_env (newt,oldt) E) newt t1  of\n     Some (E', t_typ) \\<Rightarrow>\n          (case check_trm E' t_typ t2  of\n             Some (E'', t_typ2) \\<Rightarrow> Some ( E'', t_typ2 )\n            | None \\<Rightarrow> None ) \n     | None \\<Rightarrow> None)\n  | None \\<Rightarrow> None )\"\n\ndefinition check_binop2 where\n\"check_binop2 check_trm E typ t1 t2 exp_typ  \\<equiv> \n(case  clash_propagate2 exp_typ typ E  of Some (E1,newt) \\<Rightarrow> \n  (case check_trm E1 newt t1  of\n     Some (E', t_typ) \\<Rightarrow> check_trm E' t_typ t2\n     | None \\<Rightarrow> None)\n  | None \\<Rightarrow> None )\"\n\nlemma [fundef_cong]: \"(\\<And>  E typ t . size t \\<le> size t1 + size t2 \\<Longrightarrow> check_trm E typ t = check_trm' E typ t) \\<Longrightarrow> check_binop check_trm E typ t1 t2 exp_typ = check_binop check_trm' E typ t1 t2 exp_typ\"\n by (auto simp add: check_binop_def split: option.split ) \n\nlemma [fundef_cong]: \"(\\<And>  E typ t . size t \\<le> size t1 + size t2 \\<Longrightarrow> check_trm E typ t = check_trm' E typ t) \\<Longrightarrow> check_binop2 check_trm E typ t1 t2 exp_typ = check_binop2 check_trm' E typ t1 t2 exp_typ\"\n by (auto simp add: check_binop2_def split: option.split ) \n(*2nd propagate needed?*)\nfun check_trm :: \"tysenv \\<Rightarrow> tysym \\<Rightarrow>  Formula.trm  \\<Rightarrow> (tysenv * tysym) option\" where\n\"check_trm E typ (Formula.Var v) = clash_propagate2  (E v) typ E \"\n| \"check_trm E typ (Formula.Const c)  =  clash_propagate2 (TCst (ty_of c)) typ  E\"\n| \"check_trm E typ (Formula.F2i t)  =   (case clash_propagate2  typ (TCst TInt) E of Some (E',precise_type) \\<Rightarrow> \n (case check_trm E' (TCst TFloat) t  of Some ( E'', t_typ) \\<Rightarrow>\n    Some ( E'', TCst TInt)\n    | None \\<Rightarrow> None) \n| None \\<Rightarrow> None)\" \n| \"check_trm E typ (Formula.I2f t)  =   (case clash_propagate2  typ (TCst TFloat) E of Some (E',precise_type) \\<Rightarrow> \n (case check_trm E' (TCst TInt) t  of Some ( E'', t_typ) \\<Rightarrow>\n    Some ( E'', TCst TFloat)\n    | None \\<Rightarrow> None) \n| None \\<Rightarrow> None)\" \n|\"check_trm E typ (Formula.UMinus t)  = (case clash_propagate2 (TNum 0) (new_type_symbol typ) (new_type_symbol \\<circ> E) of \n  Some (E', precise_type) \\<Rightarrow>  check_trm E' precise_type t\n  | None \\<Rightarrow> None)\"\n|\"check_trm E typ (Formula.Plus t1 t2)  = check_binop2 check_trm  (new_type_symbol \\<circ> E) (new_type_symbol typ) t1 t2  (TNum 0) \" \n|\"check_trm E typ (Formula.Minus t1 t2)  = check_binop2 check_trm  (new_type_symbol \\<circ> E) (new_type_symbol typ) t1 t2  (TNum 0) \"\n|\"check_trm E typ (Formula.Mult t1 t2)  = check_binop2 check_trm  (new_type_symbol \\<circ> E)  (new_type_symbol typ) t1 t2  (TNum 0) \"\n|\"check_trm E typ (Formula.Div t1 t2)  = check_binop2 check_trm  (new_type_symbol \\<circ> E) (new_type_symbol typ) t1 t2  (TNum 0) \"\n|\"check_trm E typ (Formula.Mod t1 t2)  = check_binop2 check_trm E typ t1 t2  (TCst TInt) \"\n\ndefinition used_tys where\n\"used_tys E \\<phi> \\<equiv> E ` fv \\<phi> \\<union> formula.set_formula \\<phi>\"\n\ndefinition check_comparison where\n\"check_comparison E X t1 t2  \\<equiv> (case check_trm   (new_type_symbol \\<circ> E) (TAny 0) t1  of\n   Some (E',t1_typ ) \\<Rightarrow> (case check_trm  E' t1_typ t2  of Some (E'', t2_typ) \\<Rightarrow>\n   Some ( trm_f E'' (new_type_symbol \\<circ> E) (fv_trm t1 \\<union> fv_trm t2) (new_type_symbol `X) \\<circ> new_type_symbol ) | None \\<Rightarrow> None)\n| None \\<Rightarrow> None)\"\n\ndefinition check_two_formulas :: \"(sig \\<Rightarrow> tysenv \\<Rightarrow> tysym set \\<Rightarrow> tysym Formula.formula  \\<Rightarrow>   (tysym \\<Rightarrow> tysym) option) \\<Rightarrow> sig \\<Rightarrow> tysenv  \\<Rightarrow> tysym set  \\<Rightarrow> tysym Formula.formula  \\<Rightarrow> tysym Formula.formula \\<Rightarrow>  (tysym \\<Rightarrow> tysym) option\" where\n\"check_two_formulas check S E X  \\<phi> \\<psi>  \\<equiv> (case check S E X \\<phi>  of\n   Some f \\<Rightarrow> (case check S (f \\<circ> E) (f ` X) (formula.map_formula f \\<psi>) of Some f' \\<Rightarrow> Some (f' \\<circ> f) | None \\<Rightarrow> None )\n   | None \\<Rightarrow> None)\"\n\ndefinition check_ands_f :: \"(sig \\<Rightarrow> tysenv \\<Rightarrow> tysym set \\<Rightarrow> tysym Formula.formula  \\<Rightarrow>   (tysym \\<Rightarrow> tysym) option) \\<Rightarrow> sig \\<Rightarrow> tysenv \\<Rightarrow> tysym set \\<Rightarrow>  (tysym \\<Rightarrow> tysym) option \\<Rightarrow> tysym Formula.formula \\<Rightarrow>(tysym \\<Rightarrow> tysym) option  \" where\n\"check_ands_f check S E X = (\\<lambda> f_op \\<phi> . case f_op of Some f \\<Rightarrow> (case check S (f \\<circ> E) (f ` X)(formula.map_formula f \\<phi>) of Some f' \\<Rightarrow> Some (f' \\<circ> f)| None \\<Rightarrow> None )\n    | None \\<Rightarrow> None )\"\n\ndefinition check_ands where\n\"check_ands check S E X \\<phi>s = foldl (check_ands_f check S E X) (Some id) \\<phi>s\"\n\ndefinition highest_bound_TAny where\n\"highest_bound_TAny \\<phi> \\<equiv> Max ((\\<lambda>t. case t of TAny n \\<Rightarrow> n | _ \\<Rightarrow> 0) ` formula.set_formula \\<phi>)\"\n\ndefinition E_empty where\n\"E_empty \\<phi> = (TAny \\<circ> (+) (highest_bound_TAny \\<phi> + 1))\"\n\nfun check_pred :: \"tysenv \\<Rightarrow> tysym set \\<Rightarrow> Formula.trm list \\<Rightarrow> tysym list \\<Rightarrow>  (tysym \\<Rightarrow> tysym) option\" where\n\"check_pred  E  X (trm#trms) (t#ts)  = (case check_trm  E t trm of\n Some (E', new_t) \\<Rightarrow> (case check_pred  E' X trms ts of Some f \\<Rightarrow> Some (f \\<circ> trm_f_new E' E new_t t (fv_trm trm) X) | None \\<Rightarrow> None)\n | None \\<Rightarrow> None)\"\n|\"check_pred  E  X [] []  = Some id\"\n|\"check_pred  E X  _ _  = None\"\n\nfun check_regex :: \"(sig \\<Rightarrow> tysenv  \\<Rightarrow> tysym set \\<Rightarrow> tysym Formula.formula  \\<Rightarrow>   (tysym \\<Rightarrow> tysym) option) \\<Rightarrow>sig \\<Rightarrow> tysenv  \\<Rightarrow> tysym set \\<Rightarrow> tysym Formula.formula Regex.regex  \\<Rightarrow>   (tysym \\<Rightarrow> tysym) option\"  where\n\"check_regex check S E X (Regex.Skip l)  = Some id\"\n| \"check_regex check S E X (Regex.Test \\<phi>)  = check S E X \\<phi>\"\n| \"check_regex check S E X (Regex.Plus r s)  = (case check_regex check S E X r  of\n  Some f \\<Rightarrow> (case check_regex check S (f \\<circ> E) (f ` X) (regex.map_regex (formula.map_formula f) s) of Some f' \\<Rightarrow> Some (f' \\<circ> f) | None \\<Rightarrow> None )\n| None \\<Rightarrow> None )\"\n| \"check_regex check S E X (Regex.Times r s)  = (case check_regex check S E X r  of\n  Some f \\<Rightarrow> (case check_regex check S (f \\<circ> E) (f ` X) (regex.map_regex (formula.map_formula f) s) of Some f' \\<Rightarrow> Some (f' \\<circ> f) | None \\<Rightarrow> None )\n| None \\<Rightarrow> None )\"\n| \"check_regex check S E X (Regex.Star r)  = check_regex check S E X r\"\n\n\nfun agg_trm_tysym :: \"Formula.agg_type \\<Rightarrow> tysym\" where\n\"agg_trm_tysym Formula.Agg_Sum = TNum 0\"\n| \"agg_trm_tysym Formula.Agg_Cnt = TAny 0\"\n| \"agg_trm_tysym Formula.Agg_Avg = TNum 0\"\n| \"agg_trm_tysym Formula.Agg_Med = TNum 0\"\n| \"agg_trm_tysym Formula.Agg_Min = TAny 0\"\n| \"agg_trm_tysym Formula.Agg_Max = TAny 0\"\n\nfun agg_ret_tysym :: \"Formula.agg_type \\<Rightarrow> tysym \\<Rightarrow> tysym\" where\n\"agg_ret_tysym Formula.Agg_Sum t = t\"\n| \"agg_ret_tysym Formula.Agg_Cnt _ = TCst TInt\"\n| \"agg_ret_tysym Formula.Agg_Avg _ = TCst TFloat\"\n| \"agg_ret_tysym agg_type.Agg_Med _ = TCst TFloat \"\n| \"agg_ret_tysym Formula.Agg_Min t = t\"\n| \"agg_ret_tysym Formula.Agg_Max t = t\"\n\n\nlemma [fundef_cong]: \"(\\<And> S E \\<phi>' X . size \\<phi>' \\<le> size \\<phi> + size \\<psi> \\<Longrightarrow> check S E X \\<phi>' = check' S E X \\<phi>') \\<Longrightarrow> check_two_formulas check S E X \\<phi> \\<psi> = check_two_formulas check' S E X \\<phi> \\<psi>\"\n  by (auto simp add: check_two_formulas_def split: option.split ) \n\nlemma foldl_check_ands_f_fundef_cong: \"(\\<And> S E \\<phi>' X .  size \\<phi>' \\<le> size_list size \\<phi>s \\<Longrightarrow> check S E X \\<phi>' = check' S E X \\<phi>') \\<Longrightarrow> foldl (check_ands_f check S E X) f \\<phi>s = foldl (check_ands_f check' S E X) f \\<phi>s\"\n  by (induction \\<phi>s arbitrary: f) (auto simp: check_ands_f_def split: option.splits)\n\nlemma [fundef_cong]: \"(\\<And> S E \\<phi>' X .  size \\<phi>' \\<le> size_list size \\<phi>s \\<Longrightarrow> check S E X \\<phi>' = check' S E X \\<phi>') \\<Longrightarrow> check_ands check S E X \\<phi>s = check_ands check' S E X \\<phi>s\"\n  using foldl_check_ands_f_fundef_cong[of \\<phi>s check]\n  by (auto simp: check_ands_def)\n\n(*\ndefinition \"check_f f f' W = f \" *)\n(*\nfun check :: \"sig \\<Rightarrow> tysenv \\<Rightarrow> tysym set  \\<Rightarrow> tysym Formula.formula  \\<Rightarrow>   (tysym \\<Rightarrow> tysym) option\"\n  where (*what to do if predicate is not in sigs?*)\n  \"check S E X (Formula.Pred r ts)  = (case S r of \n  None \\<Rightarrow> None \n  | Some tys \\<Rightarrow>  check_pred E X ts (map TCst tys))\"\n| \"check S E X (Formula.Let p \\<phi> \\<psi>)  = (case check S (E_empty \\<phi>) (used_tys (E_empty \\<phi>) \\<phi>) \\<phi> of \n  Some f \\<Rightarrow> if \\<forall>x \\<in> Formula.fv \\<phi> . case f ((E_empty \\<phi>) x) of TCst _ \\<Rightarrow> True | _ \\<Rightarrow> False \n      then  check (S(p \\<mapsto> tabulate (\\<lambda>x. case f ((E_empty \\<phi>) x) of TCst t \\<Rightarrow> t ) 0 (Formula.nfv \\<phi>))) E X \\<psi> \n      else None  | None \\<Rightarrow> None)\"\n| \"check S E X (Formula.Eq t1 t2)  = check_comparison E X t1 t2 \"\n| \"check S E X (Formula.Less t1 t2)  = check_comparison  E X t1 t2 \"\n| \"check S E X (Formula.LessEq t1 t2)  = check_comparison E X t1 t2 \"\n| \"check S E X (Formula.Neg \\<phi>)  =  check S E X \\<phi>\"\n| \"check S E X (Formula.Or \\<phi> \\<psi>)  =  check_two_formulas check S E X \\<phi> \\<psi>\"\n| \"check S E X (Formula.And \\<phi> \\<psi>)  = check_two_formulas check S E X \\<phi> \\<psi>\"\n| \"check S E X (Formula.Ands \\<phi>s)  = check_ands check S E X \\<phi>s\" \n| \"check S E X (Formula.Exists t \\<phi>)  =   check S (case_nat  t E) X \\<phi> \" (*change/check f' somehow?*)\n| \"check S E X (Formula.Agg y (agg_type, d) tys trm \\<phi>)  = (case check_trm  (new_type_symbol \\<circ> (agg_tysenv E  tys)) (agg_trm_tysym agg_type) trm of\n   Some (E', trm_type) \\<Rightarrow> (case check S E' X (formula.map_formula (trm_f_new  E' E trm_type (agg_trm_tysym agg_type) (fv_trm trm) X )  \\<phi>) of \n       Some  f \\<Rightarrow> (case clash_propagate2 ((f \\<circ> E'\\<circ> (+) (length tys)) y) (TCst (ty_of d) ) (f \\<circ> E' \\<circ> (+) (length tys)) of \n          Some (E''', ret_t) \\<Rightarrow> (case clash_propagate2 ret_t (agg_ret_tysym agg_type trm_type) E''' of \n              Some (E4, t4) \\<Rightarrow> \n                 Some  (trm_f_new E4 E''' t4 ret_t {y} X \\<circ> trm_f_new E''' (f \\<circ> E' \\<circ> (+) (length tys)) ret_t (TCst (ty_of d)) {y} X \\<circ> f ) \n               | None \\<Rightarrow> None )\n          | None \\<Rightarrow> None)\n       | None \\<Rightarrow> None)\n   | None \\<Rightarrow> None)\"\n| \"check S E X (Formula.Prev I \\<phi>)  =  check S E X \\<phi> \"\n| \"check S E X (Formula.Next I \\<phi>)  =   check S E X \\<phi> \"\n| \"check S E X (Formula.Since \\<phi> I \\<psi>)  = check_two_formulas check S E X \\<phi> \\<psi>\"\n| \"check S E X (Formula.Until \\<phi> I \\<psi>) =  check_two_formulas check S E X \\<phi> \\<psi>  \"\n| \"check S E X (Formula.MatchF I r)  = check_regex check S E X r\"\n| \"check S E X (Formula.MatchP I r)  = check_regex check S E X r \"\n*)\n\nprimrec newSymsList :: \"unit list \\<Rightarrow> nat \\<Rightarrow> tysym list\" where\n\"newSymsList (_#xs) n =  TAny n #newSymsList xs (n+1) \"\n| \"newSymsList [] n = []\"\n\n\nprimrec unitToSymRegex :: \"(unit Formula.formula \\<Rightarrow> nat \\<Rightarrow> tysym Formula.formula * nat) \\<Rightarrow> unit Formula.formula Regex.regex \\<Rightarrow>  nat \\<Rightarrow> tysym Formula.formula Regex.regex * nat\" where \n  \"unitToSymRegex formulasym (Regex.Skip l) n = (Regex.Skip l, n)\"\n| \"unitToSymRegex formulasym (Regex.Test \\<phi>) n = (case formulasym \\<phi> n of (\\<phi>', k) \\<Rightarrow>  (Regex.Test \\<phi>',k))\"\n| \"unitToSymRegex formulasym (Regex.Plus r s) n = (case unitToSymRegex formulasym r n of (r',k) \\<Rightarrow> \n      (case unitToSymRegex formulasym s k of (s',k') \\<Rightarrow> (Regex.Plus r' s' ,k')))\"\n| \"unitToSymRegex formulasym (Regex.Times r s) n = (case unitToSymRegex formulasym r n of (r',k) \\<Rightarrow> \n      (case unitToSymRegex formulasym s k of (s',k') \\<Rightarrow> (Regex.Times r' s' ,k')))\"\n| \"unitToSymRegex formulasym (Regex.Star r) n = (case unitToSymRegex formulasym r n of (r',k) \\<Rightarrow> (Regex.Star r', k))\"\n\nlemma [fundef_cong]: \"(\\<And> n \\<phi>' . \\<phi>' \\<in> regex.atms r \\<Longrightarrow> formulasym \\<phi>' n = formulasym' \\<phi>' n) \\<Longrightarrow> unitToSymRegex formulasym r n = unitToSymRegex formulasym' r n\"\n   by (induction r arbitrary: n) auto \n  \n\n\nprimrec unitToSymAnds :: \"(unit Formula.formula \\<Rightarrow> nat \\<Rightarrow> tysym Formula.formula * nat) \\<Rightarrow> unit Formula.formula list \\<Rightarrow> nat \\<Rightarrow> tysym Formula.formula list * nat\" where\n\"unitToSymAnds formulasym (\\<phi>#\\<phi>s) n = (case formulasym \\<phi> n of (\\<phi>',k) \\<Rightarrow> ( case unitToSymAnds formulasym \\<phi>s k of (\\<phi>'s, l) \\<Rightarrow>  (  \\<phi>'#\\<phi>'s, l)))\"\n|\"unitToSymAnds formulasym [] n = ([] ,n)\"\n\nlemma [fundef_cong]: \"(\\<And> \\<phi> n .  \\<phi> \\<in> set \\<phi>s  \\<Longrightarrow> formulasym \\<phi> n = formulasym' \\<phi> n) \\<Longrightarrow> unitToSymAnds formulasym \\<phi>s n = unitToSymAnds formulasym' \\<phi>s n\"\n by (induction \\<phi>s arbitrary: n)  auto\n\nfun unitToSym :: \"unit Formula.formula \\<Rightarrow> nat \\<Rightarrow> tysym Formula.formula * nat\"  where\n\"unitToSym (Formula.Exists () \\<phi>) n = (case unitToSym \\<phi> (n+1) of (\\<phi>',k) \\<Rightarrow> (Formula.Exists (TAny n) \\<phi>', k))\"\n| \"unitToSym (Formula.Agg y \\<omega> tys f  \\<phi>) n = \n  (case unitToSym \\<phi> (n+ length tys) of (\\<phi>',k) \\<Rightarrow> (Formula.Agg y \\<omega> (newSymsList tys n) f \\<phi>', k))\"\n|  \"unitToSym (Formula.Pred r ts) n = (Formula.Pred r ts, n)\"\n| \"unitToSym (Formula.Let p \\<phi> \\<psi>) n = (case unitToSym \\<phi> n of (\\<phi>',k) \\<Rightarrow> \n      (case unitToSym \\<psi> k of (\\<psi>',k') \\<Rightarrow> (Formula.Let p \\<phi>' \\<psi>' ,k')))\"\n| \"unitToSym (Formula.Eq t1 t2) n  = (Formula.Eq t1 t2, n) \"\n| \"unitToSym (Formula.Less t1 t2) n = (Formula.Less t1 t2, n)\"\n| \"unitToSym (Formula.LessEq t1 t2) n = (Formula.LessEq t1 t2, n)\"\n| \"unitToSym (Formula.Neg \\<phi>) n  = (case unitToSym \\<phi> n of (\\<phi>',k) \\<Rightarrow>(Formula.Neg \\<phi>',k)) \"\n| \"unitToSym (Formula.Or \\<phi> \\<psi>) n = (case unitToSym \\<phi> n of (\\<phi>',k) \\<Rightarrow> \n      (case unitToSym \\<psi> k of (\\<psi>',k') \\<Rightarrow> (Formula.Or \\<phi>' \\<psi>' ,k')))\"\n| \"unitToSym (Formula.And \\<phi> \\<psi>) n = (case unitToSym \\<phi> n of (\\<phi>',k) \\<Rightarrow> \n      (case unitToSym \\<psi> k of (\\<psi>',k') \\<Rightarrow> (Formula.And \\<phi>' \\<psi>' ,k')))\"\n| \"unitToSym (Formula.Ands \\<phi>s) n = (case  unitToSymAnds unitToSym \\<phi>s n of (\\<phi>'s, k) \\<Rightarrow>  (Formula.Ands \\<phi>'s,k))\"\n| \"unitToSym (Formula.Prev I \\<phi>) n = (case unitToSym \\<phi> n of (\\<phi>',k) \\<Rightarrow>(Formula.Prev I \\<phi>',k)) \"\n| \"unitToSym (Formula.Next I \\<phi>) n = (case unitToSym \\<phi> n of (\\<phi>',k) \\<Rightarrow>(Formula.Next I \\<phi>',k))\"\n| \"unitToSym (Formula.Since \\<phi> I \\<psi>) n = (case unitToSym \\<phi> n of (\\<phi>',k) \\<Rightarrow> \n      (case unitToSym \\<psi> k of (\\<psi>',k') \\<Rightarrow> (Formula.Since \\<phi>' I \\<psi>' ,k')))\"\n| \"unitToSym (Formula.Until \\<phi> I \\<psi>) n = (case unitToSym \\<phi> n of (\\<phi>',k) \\<Rightarrow> \n      (case unitToSym \\<psi> k of (\\<psi>',k') \\<Rightarrow> (Formula.Until \\<phi>' I \\<psi>' ,k')))\"\n| \"unitToSym (Formula.MatchF I r) n = (case unitToSymRegex unitToSym r n of (r',k) \\<Rightarrow> (Formula.MatchF I r',k))\"\n| \"unitToSym (Formula.MatchP I r) n = (case unitToSymRegex unitToSym r n of (r',k) \\<Rightarrow> (Formula.MatchP I r',k))\"\n\n\n(* definition check_safe :: \"sig \\<Rightarrow> unit Formula.formula \\<Rightarrow> (tyenv * ty Formula.formula) option\" where\n  \"check_safe S \\<phi> = map_option \n  (\\<lambda>(E,\\<phi>).  ((\\<lambda>x. case E x of TCst t' \\<Rightarrow> t'), Formula.map_formula (\\<lambda>t. case t of TCst t' \\<Rightarrow> t') \\<phi>))\n     (case unitToSym \\<phi> 0 of (\\<phi>', n ) \\<Rightarrow> check S (\\<lambda> k. TAny (n + k) ) \\<phi>')\" *)\n\ndefinition wf_f :: \"(tysym \\<Rightarrow> tysym) \\<Rightarrow> bool\" where\n\"wf_f f \\<equiv> (\\<forall>x. f (TCst x) = TCst x) \\<and> (\\<forall>n . case f (TNum n) of TCst x \\<Rightarrow> x \\<in> numeric_ty | TNum x \\<Rightarrow> True | _ \\<Rightarrow> False)\"\n\nlemma wf_f_comp: \"wf_f f \\<Longrightarrow> wf_f g \\<Longrightarrow> wf_f (f \\<circ> g)\"\napply (auto simp add: comp_def wf_f_def split: tysym.splits) \n  by (metis tysym.exhaust)+ \n\n\n\ndefinition tysenvless :: \"tysenv \\<Rightarrow> tysenv \\<Rightarrow> bool\" where\n\"tysenvless E' E \\<longleftrightarrow> (\\<exists>f . wf_f f \\<and> E' = f \\<circ> E )\"\n\nlemma tysenvless_trans: \"tysenvless E'' E' \\<Longrightarrow> tysenvless E' E \\<Longrightarrow> tysenvless E'' E\"\n  apply (auto simp add: tysenvless_def) subgoal for f g apply (rule exI[of _ \"f \\<circ> g\"]) \n    using wf_f_comp by auto done\n\ndefinition \"resultless_trm E' E typ' typ \\<longleftrightarrow> (\\<exists> f. wf_f f \\<and>   E' = f \\<circ> E  \\<and> typ' = f typ)\"\n\ndefinition \"resultless_trm_f E' E typ' typ f W  \\<longleftrightarrow> wf_f f \\<and> (\\<forall>x \\<in> W.   E' x  = (f \\<circ> E) x) \\<and> typ' = f typ\"\n\ndefinition \"resultless_trm_f' E' E f W  \\<longleftrightarrow> wf_f f \\<and> (\\<forall>x \\<in> W.   E' x  = (f \\<circ> E) x)\"\n  \nlemma resultless_trm_f'_trans: \"resultless_trm_f' E'' E' f' W \\<Longrightarrow> resultless_trm_f' E' E f W \\<Longrightarrow> resultless_trm_f' E'' E (f'\\<circ>f) W\"\n   using wf_f_comp by (auto simp add: resultless_trm_f'_def) \n    \nlemma tysenvless_resultless_trm: assumes\n \"tysenvless E' E\" \"case typ of TCst t' \\<Rightarrow> typ = typ' | TNum n \\<Rightarrow> t \\<in> numeric_ty \\<and> typ' = TCst t \\<or> typ' = typ |_  \\<Rightarrow> True \"\n  \"(\\<forall>x. E x \\<noteq> typ) \\<or> typ = TCst t\"\n  shows \"resultless_trm E' E typ' typ\"\n  using assms apply (auto simp add: tysenvless_def resultless_trm_def)  subgoal for g apply (rule exI[of _ \"g(typ := typ')\" ]) \n    by (auto simp add: wf_f_def split: tysym.splits)  subgoal for g  apply (rule exI[of _ \"g(typ := typ')\" ]) \n    by (auto simp add: wf_f_def) done\n\nlemma resultless_trm_tysenvless: assumes \"resultless_trm  E'' E' t t'\"\n  shows \"tysenvless  E'' E'\"\n  using assms unfolding resultless_trm_def tysenvless_def by auto\n\n\nlemma some_min_resless: assumes \"min_type typ z = Some y\"\n  shows \"resultless_trm (update_env y E) E (fst y) typ \"\nproof -\n  obtain tnew told where y_def: \"y = (tnew,told)\" by (cases y)\n  define f where \"f = (\\<lambda>x . if x = told then tnew else x)\"\n  have wf: \"wf_f f\" using assms  apply (induction \"z\"  \"typ\" rule: min_type.induct)\n    by (auto simp add: y_def f_def numeric_ty_def wf_f_def eq_commute[where ?b= \"z\"] split: if_splits tysym.splits)\n  show ?thesis unfolding resultless_trm_def apply (rule exI[of _ f])  \n    using assms wf apply (induction \"z\"  \"typ\" rule: min_type.induct)\n    by (auto simp add: y_def f_def comp_def update_env_def eq_commute[where ?b= \"z\"] split: if_splits)\nqed\n\nlemma resless_newtype: \"resultless_trm (new_type_symbol \\<circ> E) E  (new_type_symbol typ) typ \"\n \"resultless_trm E (new_type_symbol \\<circ> E) typ (new_type_symbol typ)\"\n   unfolding resultless_trm_def  apply (rule exI[of _ \"new_type_symbol \"]) subgoal \n     by (auto simp add:   wf_f_def new_type_symbol_def)\n   apply (rule exI[of _ \"(\\<lambda>x.  case x of TCst t \\<Rightarrow> TCst t | TAny n \\<Rightarrow> TAny (n-1)| TNum n \\<Rightarrow> TNum (n-1) )\"]) \n   by (auto simp add: wf_f_def new_type_symbol_def  split: tysym.splits) \n\n\n(*\nDecision for F2i / I2f:\n\nlemma \" (case clash_propagate2  typ (TCst TInt) E of Some (E',precise_type) \\<Rightarrow> \n (case check_trm E' (TCst TFloat) t  of Some ( E'', t_typ) \\<Rightarrow>\n    Some ( E'', TCst TInt)\n    | None \\<Rightarrow> None) \n| None \\<Rightarrow> None) = (case check_trm E (TCst TFloat) t  of Some ( E', t_typ) \\<Rightarrow> clash_propagate2  typ (TCst TInt) E' | None \\<Rightarrow> None)\"\n   using min_const apply (auto simp add: clash_propagate2_def min_comm[where ?b=\"TCst TInt\"] split: option.splits )\n   oops\n\nlemma \"t = trm.Var x \\<Longrightarrow> E x = TAny 0 \\<Longrightarrow> typ = TAny 0 \\<Longrightarrow> (case clash_propagate2  typ (TCst TInt) E of Some (E',precise_type) \\<Rightarrow> \n (case check_trm E' (TCst TFloat) t  of Some ( E'', t_typ) \\<Rightarrow>\n    Some ( E'', TCst TInt)\n    | None \\<Rightarrow> None) \n| None \\<Rightarrow> None) = (case check_trm E (TCst TFloat) t  of Some ( E', t_typ) \\<Rightarrow> clash_propagate2  typ (TCst TInt) E' | None \\<Rightarrow> None) \\<Longrightarrow> False\"\n    by (auto simp add: clash_propagate2_def  update_env_def split: option.splits) \n*)\n\nlemma resultless_trm_refl: \"resultless_trm E E type type\"\n  apply (auto simp add: resultless_trm_def ) apply (rule exI[of _ id]) by (auto simp add: wf_f_def)\n\nlemma resultless_trm_trans: assumes \" resultless_trm E'' E' type'' type'\" \"resultless_trm E' E type' type\"   \n  shows \"resultless_trm E'' E type'' type\"\n  using assms apply (auto simp add: resultless_trm_def) subgoal for f g \n apply (rule exI[of _ \"f \\<circ> g\"]) \n    using wf_f_comp by auto done\n\n\n(*\nlemma resultless_trm_trans_typeless: assumes \" resultless_trm E'' E' type'' type1\" \"resultless_trm E' E type2 type\"   \n  shows \"resultless_trm E'' E type'' type\"\n  using assms apply (auto simp add: resultless_trm_def) subgoal for f g \n apply (rule exI[of _ \"f \\<circ> g\"]) \n    using wf_f_comp apply auto done\n*)\nlemma assumes \"resultless_trm (TCst \\<circ> E'') E (TCst type'') type\" \"resultless_trm E' E type' type\" \n\"E'' \\<turnstile> t :: type''\"   \" check_trm E type t = Some (E', type')\"\nshows \"resultless_trm (TCst \\<circ> E'') E'  (TCst type'') type'\"\n   using assms apply (induction t ) apply (auto simp add: resultless_trm_def clash_propagate2_def elim: wty_trm.cases)  \n  oops\nlemma resless_all_const_eq: \"resultless_trm (TCst \\<circ> E'') E ty1 ty2 \\<Longrightarrow> E x = TCst t \\<Longrightarrow> E'' x =  t\"\n  unfolding resultless_trm_def wf_f_def  \n  by (metis comp_eq_elim tysym.inject(3))\n\nlemma resless_all_numeric: \"resultless_trm (TCst \\<circ> E'') E ty1 ty2 \\<Longrightarrow> E x = TNum n \\<Longrightarrow> E'' x \\<in> numeric_ty\"\n  unfolding resultless_trm_def wf_f_def \n  by (metis comp_eq_elim tysym.simps(12))\n\n\n\nlemma resless_wty_num: assumes \" resultless_trm (TCst \\<circ> E'') E (TCst typ'') type\"\n    \"Some (newt, oldt) = min_type x (new_type_symbol type)\" \"case x of TNum 0 \\<Rightarrow> typ'' \\<in> numeric_ty | TCst t \\<Rightarrow> t = typ'' | _ \\<Rightarrow> False\"\n  shows  \"resultless_trm (TCst \\<circ> E'') (update_env (newt, oldt) (new_type_symbol \\<circ> E)) (TCst typ'') newt\"\nproof -\n  have newtype_E: \"resultless_trm (TCst \\<circ> E'') (new_type_symbol \\<circ> E) (TCst typ'') (new_type_symbol type)\" apply (rule resultless_trm_trans[where ?E'=E]) \n    using assms(1) resless_newtype(2) by auto\n  then obtain f where f_def: \"wf_f f \\<and> TCst \\<circ> E'' = f \\<circ>  new_type_symbol \\<circ> E \\<and> TCst typ'' = f  (new_type_symbol type)\"  unfolding resultless_trm_def  by (auto simp add: comp_def)\n  define g where g_def: \"g = (\\<lambda>x. if x = newt then TCst typ'' else f x)\"\n  show ?thesis using assms(2-3) f_def  apply (auto simp add: resultless_trm_def) apply (rule exI[of _ g])\n   apply (auto simp add: wf_f_def g_def split: tysym.splits nat.splits) \n    apply (metis min_consistent tysym.distinct(5) tysym.inject(3)) apply (rule ext) subgoal for  x\n       apply (auto simp add: update_env_def new_type_symbol_def comp_def split:if_splits tysym.splits)  \n      apply (metis min_consistent tysym.distinct(1))\n      apply (metis min_consistent tysym.distinct(1))\n      apply (metis Suc_neq_Zero min_consistent tysym.inject(2)) \n      apply (metis Suc_neq_Zero min_consistent tysym.inject(2)) \n      apply (metis min_consistent tysym.distinct(5) tysym.inject(3))\n      by (metis min_consistent tysym.distinct(5) tysym.inject(3)) \n    apply (metis min_const tysym.inject(3)) \n    apply (metis min_const) apply (rule ext) subgoal for  x\n       apply (auto simp add: update_env_def new_type_symbol_def comp_def split:if_splits tysym.splits) \n      apply (metis min_consistent) \n      apply (metis min_const)\n      apply (metis min_consistent)\n      apply (metis min_const)\n      apply (metis min_consistent tysym.inject(3))\n      by (metis min_const tysym.inject(3)) done\n      \n    (*apply (metis min_consistent tysym.distinct(5))\n     apply (metis tysym.simps(12)) apply (rule ext) subgoal for  x\n       apply (auto simp add: update_env_def new_type_symbol_def comp_def split:if_splits tysym.splits)  \n      apply (metis min_consistent tysym.distinct(1))\n            apply (metis min_consistent tysym.distinct(1))\n      apply (metis Suc_neq_Zero min_consistent tysym.inject(2)) \n         apply (metis Suc_neq_Zero min_consistent tysym.inject(2))\n      apply (metis min_consistent tysym.distinct(5) tysym.inject(3)) \n      by (metis min_consistent tysym.distinct(5) tysym.inject(3)) done *)\n\nqed \n\nlemma resless_wty_const: assumes \" resultless_trm (TCst \\<circ> E'') E (TCst typ'') type\"\n    \"Some (newt, oldt) = min_type (TCst typ'') type\"\n  shows  \"resultless_trm (TCst \\<circ> E'') (update_env (newt, oldt) E) (TCst typ'') newt\"\nproof -\n  obtain f where f_def: \"wf_f f\" \"f \\<circ> E = TCst \\<circ> E''\" \"f type = TCst typ''\" using assms(1) by (auto simp add: resultless_trm_def)\n  show ?thesis  unfolding resultless_trm_def apply (rule exI[of _ f]) using assms(2) f_def min_const[of typ'' type] \n    apply (auto  simp add: eq_commute[where ?a=\"Some(newt,oldt)\"] wf_f_def  ) apply (rule ext) subgoal for x\n      using min_consistent[of \"TCst typ''\" type] \n      apply (auto simp add:  update_env_def comp_def ) \n      apply (metis tysym.inject(3)) \n      apply metis \n      apply (metis tysym.inject(3))\n  by metis done \nqed\n\nlemma resless_wty_num_dir2: assumes\n\"resultless_trm E1 E2 (TCst typ'') newt\"\n    \"Some (newt, oldt) = min_type (TNum n) ty\" \n  shows  \" typ'' \\<in> numeric_ty\"\n  using assms \n  by (induction \"TNum n\" \"ty\" rule: min_type.induct)\n  (auto simp add: resultless_trm_def  numeric_ty_def new_type_symbol_def wf_f_def split: tysym.splits if_splits) \n  \nlemma resless_wty_const_dir2: assumes \n\"resultless_trm E1 E2 (TCst typ'') newt\"\n    \"Some (newt, oldt) = min_type (TCst t) type\"\n  shows \"typ'' = t\"\n  using assms  min_const[of t type ]\n  by (auto simp add: eq_commute[where ?a=\"Some(newt,oldt)\"] resultless_trm_def wf_f_def) \n\n\ndefinition wty_result_trm :: \" Formula.trm \\<Rightarrow> tysenv \\<Rightarrow> tysym \\<Rightarrow> tysenv \\<Rightarrow> tysym \\<Rightarrow> bool\" where\n \"wty_result_trm  t E' typ' E typ \\<longleftrightarrow> resultless_trm E' E typ' typ \\<and> \n(\\<forall>E'' typ'' .   resultless_trm (TCst \\<circ>  E'') E (TCst typ'') typ \\<longrightarrow> ( E'' \\<turnstile> t :: typ'' \\<longleftrightarrow> resultless_trm (TCst \\<circ>  E'') E' (TCst typ'') typ' ))\"\n\ndefinition wty_result_fX_trm :: \"tysenv \\<Rightarrow> tysym \\<Rightarrow> Formula.trm  \\<Rightarrow> (tysym \\<Rightarrow> tysym) \\<Rightarrow> tysym set \\<Rightarrow> bool\" where\n  \"wty_result_fX_trm E typ trm f X \\<longleftrightarrow> wf_f f \\<and> \n(\\<forall>f'' .  wf_f (TCst \\<circ> f'') \\<longrightarrow> \n  ((f''\\<circ> E) \\<turnstile> trm :: f'' typ) = (\\<exists> g. wf_f (TCst \\<circ> g) \\<and>(\\<forall>t \\<in> X. f'' t = (g \\<circ> f) t) \\<and> f'' typ = (g \\<circ> f) typ ))\"\n\n\ndefinition half_wty_trm ::  \" Formula.trm \\<Rightarrow> tysenv \\<Rightarrow> tysym \\<Rightarrow> tysenv \\<Rightarrow> tysym \\<Rightarrow> bool\" where\n\"half_wty_trm t E' type' E type \\<longleftrightarrow> resultless_trm E' E type' type \\<and> \n(\\<forall> E'' typ'' . (resultless_trm (TCst \\<circ> E'') E (TCst typ'') type \\<longrightarrow>\n       E'' \\<turnstile> t :: typ'' \\<longrightarrow> resultless_trm (TCst \\<circ> E'') E' (TCst typ'') type'))\"\n\n\nlemma subterm_half_wty: assumes \"half_wty_trm t E' type' E type\" \n \"\\<And> E'' type'' . E'' \\<turnstile> subtrm :: type'' \\<Longrightarrow>  E'' \\<turnstile> t :: type'' \"\nshows  \"half_wty_trm subtrm E' type' E type\"\n  using assms unfolding half_wty_trm_def by (auto)\n\nlemma check_trm_step0_half: assumes\n  \"Some (E', type') = clash_propagate2 t type  E\" \nshows \" resultless_trm E' E type' type \"\nproof -  \n obtain  oldt where t_def: \"Some (type',oldt) = min_type (t) type\" using assms\n    by (cases \"min_type t (type)\") (auto simp add:  clash_propagate2_def ) \n  then have E1_def: \"E' =  update_env (type', oldt) ( E)\" using assms\n    by (cases \"min_type (t) (type)\")   (auto simp add:  clash_propagate2_def ) \n  then show g1: \"resultless_trm E' E type' type\"\n    using  t_def resultless_trm_trans[of \"update_env (type', oldt) ( E)\"]  \n      some_min_resless[of \"type\" \"t\" \"(type',oldt)\" \" E\"]\n    by  (auto simp add: min_comm[where ?b=\"type\"])\nqed\n\nlemma check_trm_step0_num: assumes\n  \"Some (E1, precise_type) = clash_propagate2 (TNum 0) (new_type_symbol type) (new_type_symbol \\<circ> E)\" \n  \"\\<And>E''. (E'' \\<turnstile> t :: typ'') \\<Longrightarrow> typ'' \\<in> numeric_ty\" \nshows \" resultless_trm E1 E precise_type type \"\n  \"(resultless_trm (TCst \\<circ> E'') E (TCst typ'') type \\<Longrightarrow>\n       E'' \\<turnstile> t :: typ'' \\<Longrightarrow>  resultless_trm (TCst \\<circ> E'') E1 (TCst typ'') precise_type)\" \n  \"(resultless_trm (TCst \\<circ> E'') E (TCst typ'') type \\<Longrightarrow>\n       resultless_trm (TCst \\<circ> E'') E1 (TCst typ'') precise_type \\<Longrightarrow> typ'' \\<in> numeric_ty)\"\n  (* 2 subgoals for \"wty_result_trm t E type E1 precise_type \"\n      cant show other direction of 2nd subgoal only typ'' \\<in> numeric_ty *)\nproof -\n  obtain  oldt where t_def: \"Some (precise_type,oldt) = min_type (TNum 0) (new_type_symbol type)\" using assms(1)\n    by (cases \"min_type (TNum 0) (new_type_symbol type)\")   (auto simp add:  clash_propagate2_def ) \n  then have E1_def: \"E1 =  update_env (precise_type, oldt) (new_type_symbol \\<circ> E)\" using assms(1) \n    apply (cases \"min_type (TNum 0) (new_type_symbol type)\")  by (auto simp add:  clash_propagate2_def ) \n  then show f1: \"resultless_trm E1 E precise_type type\"\n    using  t_def resultless_trm_trans[of \"update_env (precise_type, oldt) (new_type_symbol \\<circ> E)\"] resless_newtype[of E type] \n      some_min_resless[of \"new_type_symbol type\" \"TNum 0\" \"(precise_type,oldt)\" \"new_type_symbol \\<circ> E\"]\n    by  (auto simp add: min_comm[where ?b=\"new_type_symbol type\"])\n\n  then show \"(resultless_trm (TCst \\<circ> E'') E (TCst typ'') type \\<Longrightarrow>\n       E'' \\<turnstile> t :: typ'' \\<Longrightarrow>  resultless_trm (TCst \\<circ> E'') E1 (TCst typ'') precise_type) \" using \n    assms(2)[of E'' ] t_def E1_def resless_wty_num[of E'' E typ'' type precise_type oldt \"TNum 0\"]\n    by auto\n\n  show \"(resultless_trm (TCst \\<circ> E'') E (TCst typ'') type \\<Longrightarrow>\n       resultless_trm (TCst \\<circ> E'') E1 (TCst typ'') precise_type \\<Longrightarrow> typ'' \\<in> numeric_ty)\"\n    using t_def  resless_wty_num_dir2[of \"TCst \\<circ> E''\" E1 typ'' precise_type oldt 0 \"new_type_symbol type\"]\n    by auto\nqed\n\nlemma check_trm_step0_cst2: assumes\n  \"Some (E1, precise_type) = clash_propagate2 (TCst typ'') type  E\" \nshows \" resultless_trm E1 E precise_type type \"\n  \"(resultless_trm (TCst \\<circ> E'') E (TCst typ'') type \\<Longrightarrow>  resultless_trm (TCst \\<circ> E'') E1 (TCst typ'') precise_type)\" \n\nproof -\n  obtain  oldt where t_def: \"Some (precise_type,oldt) = min_type (TCst typ'') ( type)\" using assms(1)\n    by (cases \"min_type (TCst typ'') ( type)\")   (auto simp add:  clash_propagate2_def ) \n  then have E1_def: \"E1 =  update_env (precise_type, oldt) (E)\" using assms(1) \n    apply (cases \"min_type (TCst typ'') ( type)\")  by (auto simp add:  clash_propagate2_def ) \n  then show f1: \"resultless_trm E1 E precise_type type\"\n    using  t_def resultless_trm_trans[of \"update_env (precise_type, oldt) ( E)\"] resless_newtype[of E type] \n      some_min_resless[of \" type\" \"TCst typ''\" \"(precise_type,oldt)\" \" E\"]\n    by  (auto simp add: min_comm[where ?b=\" type\"])\n\n  then show \"(resultless_trm (TCst \\<circ> E'') E (TCst typ'') type \\<Longrightarrow>\n       resultless_trm (TCst \\<circ> E'') E1 (TCst typ'') precise_type) \" using \n     t_def E1_def resless_wty_const[of E'' E typ'' type precise_type oldt ]\n    by auto\nqed\n\nlemma check_trm_step0_cst: assumes\n    \"Some (E1, precise_type) = clash_propagate2 (TCst ty) type  E\" \n    \"\\<And>E'' y . (E'' \\<turnstile> t :: y) \\<longleftrightarrow>  y = ty\"\n  shows \"wty_result_trm t E1 precise_type E type \"\nproof -\n  obtain  oldt where t_def: \"Some (precise_type,oldt) = min_type (TCst ty) type\" using assms(1)\n    by (cases \"min_type (TCst ty)  type\")   (auto simp add:  clash_propagate2_def ) \n  then have E1_def: \"E1 =  update_env (precise_type, oldt)  E\" using assms(1) \n    apply (cases \"min_type (TCst ty)  type\")  by (auto simp add:  clash_propagate2_def ) \n  then have f1: \"resultless_trm E1 E precise_type type\"\n      using  t_def resultless_trm_trans[of \"update_env (precise_type, oldt)  E\"]  \n        some_min_resless[of \"type\" \"TCst ty\" \"(precise_type,oldt)\" E]\n      by  (auto simp add: min_comm[where ?b=\" type\"])\n    then show ?thesis   apply (auto simp add: wty_result_trm_def) subgoal for E'' typ''\n        using assms(2)[of E'' typ''] t_def E1_def resless_wty_const[of E'' E typ'' type precise_type oldt]\n        by auto subgoal for E'' typ'' using E1_def t_def \n         resless_wty_const_dir2[of \"TCst \\<circ> E''\" E1 typ'' precise_type oldt ] assms(2)\n        by auto done\n    qed\n\nlemma check_trm_step1: assumes \"wty_result_trm t E' type' E1 precise_type\"\n\"half_wty_trm t E1 precise_type E type\"\n    shows \"wty_result_trm t E' type' E type\"\n  using assms(1,2) resultless_trm_trans[of E'] unfolding half_wty_trm_def apply (auto simp add: wty_result_trm_def) subgoal for E'' typ''\n      using resultless_trm_trans[of \"TCst \\<circ> E''\"]  by blast \n    subgoal for E'' typ'' using resultless_trm_trans[of \"TCst \\<circ> E''\"] by auto done\n\nlemma half_wty_trm_trans: assumes \n\"half_wty_trm t E' type' E1 type1\"\n\"half_wty_trm  t E1 type1 E type\"\nshows \"half_wty_trm t E' type' E type\"\n  using assms resultless_trm_trans apply (auto simp add: half_wty_trm_def)\n  by blast\n\nlemma check_binop_sound: assumes \"\\<And>E E' type type' . check_trm E type t1 = Some (E', type') \\<Longrightarrow> wty_result_trm t1 E' type' E type\"\n  \"\\<And>E E' type type' . check_trm E type t2 = Some (E', type') \\<Longrightarrow> wty_result_trm t2 E' type' E type\"\n  \"check_trm E type (trm t1 t2) = Some (E', type')\" \n  \"trm \\<in> {trm.Plus, trm.Minus, trm.Mult, trm.Div } \\<and> constr = TNum 0 \\<and> E_start = new_type_symbol \\<circ> E \\<and> type_start = new_type_symbol type \\<and> (P = (\\<lambda>y.  y \\<in> numeric_ty))\n \\<or> trm = trm.Mod \\<and> constr = TCst TInt \\<and> E_start =  E \\<and> type_start = type \\<and> (P = (\\<lambda>y.  y = TInt))\"\nshows \" wty_result_trm (trm t1 t2) E' type' E type\"\nproof -\n  obtain E_constr constr_type where constr_def: \"Some (E_constr, constr_type) = clash_propagate2 constr type_start E_start\" using assms\n    by (auto simp add: check_binop2_def clash_propagate2_def split: option.splits)\n  then have constr_int: \"constr = TCst TInt \\<Longrightarrow> resultless_trm (TCst \\<circ> E'') E_constr (TCst typ'') constr_type \\<Longrightarrow>\n   typ'' = TInt\" for E'' typ'' unfolding clash_propagate2_def using         resless_wty_const_dir2[where ?t=TInt and ?typ''=typ'' and ?newt=constr_type and ?E1.0=\"TCst \\<circ> E''\" and ?E2.0=E_constr]\n    apply (cases \"min_type (TCst TInt) type_start\") by auto  metis\n obtain E1 t_typ where  E1_def: \"Some (E1,t_typ) = check_trm E_constr constr_type t1\" using assms   constr_def\n   by (auto simp add: check_binop2_def clash_propagate2_def split: option.splits) \n  then have E'_def: \"Some (E',type') = check_trm E1 t_typ t2\" using assms  constr_def\n    by (auto simp add: check_binop2_def clash_propagate2_def split: option.splits)\n  have wtynum: \"\\<And>E'' y. E'' \\<turnstile> trm t1 t2 :: y  \\<Longrightarrow> P y\" using assms(4) by (auto elim: wty_trm.cases) \n  have wty_res2: \"wty_result_trm t2 E' type' E1 t_typ\" using E'_def assms(2)  by auto\n  have wty_res1: \"wty_result_trm t1  E1 t_typ E_constr constr_type\" using E1_def constr_def assms(1) by auto\n  have half_wty: \"half_wty_trm  (trm t1 t2) E' type' E type\"  apply (rule half_wty_trm_trans[where ?E1.0=E1 and ?type1.0=t_typ]) defer 1\n apply (rule half_wty_trm_trans[where ?E1.0=E_constr and ?type1.0=constr_type]) apply (cases \"trm t1 t2\")\n    using   wty_res1 wty_res2 constr_def wtynum check_trm_step0_cst2 check_trm_step0_num[of E_constr constr_type type E \"trm t1 t2\"] assms(4)\n    by (auto simp add: half_wty_trm_def wty_result_trm_def elim:wty_trm.cases )\n  show ?thesis  using  half_wty  wty_res1 wty_res2 apply (auto simp add: half_wty_trm_def wty_result_trm_def ) subgoal for E'' typ''\n      apply (cases \"trm t1 t2\")  using   assms(4) resultless_trm_trans[of \"TCst \\<circ> E''\" E' \"TCst typ''\" type' E1 t_typ]\n        resultless_trm_trans[of \"TCst \\<circ> E''\" E1 \"TCst typ''\" t_typ E_constr constr_type]\n               apply (auto intro!: wty_trm.intros) using check_trm_step0_num(3)  constr_def wtynum apply blast+ \n      using  wty_trm.Mod[where ?E=E'' and ?x=t1 and ?y=t2 ] constr_int[of E'' typ''] by (auto intro: wty_trm.intros)\n       done\nqed\n\n\nlemma check_conversion_sound: assumes \" \\<And>E type  E' type'. check_trm E type t = Some (E', type') \\<Longrightarrow> wty_result_trm t E' type' E type\"\n    \"check_trm E type (trm t) = Some (E', type')\" \"trm = trm.F2i \\<and> a = TInt \\<and> b = TFloat \\<or> trm = trm.I2f \\<and> a = TFloat \\<and> b = TInt\"\n  shows \"wty_result_trm (trm t) E' type' E type\"\nproof - \n   obtain E1 precise_type where E1_def: \"Some (E1, precise_type) = clash_propagate2 type (TCst a) E\" using assms(2,3) by (auto split: option.splits)\n  then have prec_int: \"precise_type = TCst a\" using assms(3) by (cases type) (auto simp add: clash_propagate2_def split: if_splits)\n  have type'_def: \"type' = TCst a\" using assms(2,3) by (auto split: option.splits)\n  have type_int: \"case type of TCst t \\<Rightarrow> t = a | _ \\<Rightarrow> True\" using E1_def by (cases type)(auto simp add: clash_propagate2_def split: if_splits)\n  obtain fl_type where E2_def: \"check_trm E1 (TCst b) t = Some (E', fl_type) \" using E1_def assms(2,3) by (auto split: option.splits) \n  have wtytrm: \"(\\<And>E'' y. (E'' \\<turnstile> trm t :: y) \\<longrightarrow> (y = a))\" using assms(3) by (auto elim:wty_trm.cases)\n   have half: \"half_wty_trm (trm t) E1 precise_type E type\" using assms E1_def check_trm_step0_cst2[of E1 precise_type a type E]  \n    wtytrm clash_prop_comm by (auto simp add: half_wty_trm_def)  blast+ \n   have wty: \"wty_result_trm t E' fl_type E1 (TCst b)\"using E2_def assms(3) assms(1)[of E1 \"TCst b\" E' fl_type] by auto\n   then have fl_def: \"fl_type = TCst b\" unfolding wty_result_trm_def resultless_trm_def wf_f_def by auto\n     have E'_less: \"tysenvless E' E1\"  using wty half resultless_trm_tysenvless\n       by (auto simp add: wty_result_trm_def half_wty_trm_def  )\n     have typ''_def: \"resultless_trm (TCst \\<circ> E'') E' (TCst typ'') (TCst a) \\<Longrightarrow> typ'' = a\" for E'' typ'' using assms(3) \n       unfolding resultless_trm_def wf_f_def by auto \n     have \" resultless_trm (TCst \\<circ> E'') E (TCst typ'') type \\<Longrightarrow>  E'' \\<turnstile> trm t :: typ'' \\<Longrightarrow>  resultless_trm (TCst \\<circ> E'') E1 (TCst b) (TCst b)\"\n       for  E'' typ'' apply (rule tysenvless_resultless_trm)  \n         using half assms(3)   unfolding resultless_trm_def half_wty_trm_def wty_result_trm_def tysenvless_def by (cases typ'') auto  \n       then  have  \"  E'' \\<turnstile> trm t :: typ'' \\<Longrightarrow> resultless_trm (TCst \\<circ> E'') E (TCst typ'') type \\<Longrightarrow>\n          (E'' \\<turnstile> t :: b) = resultless_trm (TCst \\<circ> E'') E' (TCst b) fl_type\"\n         for E'' typ'' using wty assms(3) unfolding wty_result_trm_def by auto  \n       then have sub2:\" E'' \\<turnstile> trm t :: typ'' \\<Longrightarrow> resultless_trm (TCst \\<circ> E'') E (TCst typ'') type \\<Longrightarrow>\n          (E'' \\<turnstile> t :: b)  =  resultless_trm (TCst \\<circ> E'') E' (TCst typ'') (TCst a)\" for E'' typ''\n         using tysenvless_resultless_trm[of \"TCst \\<circ> E''\" E' a  \"TCst typ''\" \"TCst a\"] assms(3)  unfolding resultless_trm_def tysenvless_def \n         by (auto simp add: fl_def wf_f_def elim: wty_trm.cases)\n     have \"(\\<forall>x. E1 x \\<noteq> type) \\<or> type = TCst a\" using E1_def min_const assms(3) apply (auto simp add: clash_propagate2_def) subgoal for x \n         by (cases \"E1 x\") (auto simp add: update_env_def split: if_splits)\n        subgoal for x \n         by (cases \"E1 x\") (auto simp add: update_env_def split: if_splits) done\n then have \" resultless_trm E' E1 (TCst a) precise_type\"  using E'_less\n       tysenvless_resultless_trm[of E' E1 a \"TCst a\" precise_type] wf_f_comp type_int assms(3)\n   unfolding type'_def by (cases type) (auto simp add: prec_int wty_result_trm_def half_wty_trm_def numeric_ty_def ) \n  moreover have \"resultless_trm E1  E precise_type type\" using prec_int half    by (auto simp add: half_wty_trm_def resultless_trm_def) \n\n  ultimately have \" resultless_trm E' E (TCst a) type\" by ( rule resultless_trm_trans ) \n  then show ?thesis using E'_less wty wf_f_comp resultless_trm_trans[of ]  assms(3) \n    unfolding type'_def  apply (auto simp add: prec_int wty_result_trm_def half_wty_trm_def ) subgoal for E'' typ''\n      using sub2[of E'' typ''] by (auto elim: wty_trm.cases)\n    subgoal for E'' typ''  using wty   tysenvless_resultless_trm[of \"TCst \\<circ> E''\" E' b \"TCst b\" \"TCst b\"] unfolding wty_result_trm_def\n      using typ''_def[of E'' typ''] resultless_trm_tysenvless resultless_trm_trans[of \"TCst \\<circ> E''\"]  by (auto simp add: fl_def intro!: wty_trm.intros) \n    subgoal for E'' typ''\n      using sub2[of E'' typ''] by (auto elim: wty_trm.cases)\n    subgoal for E'' typ''  using wty   tysenvless_resultless_trm[of \"TCst \\<circ> E''\" E' b \"TCst b\" \"TCst b\"] unfolding wty_result_trm_def\n      using typ''_def[of E'' typ''] resultless_trm_tysenvless resultless_trm_trans[of \"TCst \\<circ> E''\"]  by (auto simp add: fl_def intro!: wty_trm.intros)\n    done\nqed\n\n(*Theorem 4.1*)\nlemma check_trm_sound: \"check_trm  E type t = Some (E', type') \\<Longrightarrow> wty_result_trm t  E' type' E type\" (*Theorem 4.1*)\nproof (induction t arbitrary:  E type E' type')                                     \n  case (Var x) \n have  wtyres1: \"resultless_trm E' E type' type\" apply (rule check_trm_step0_half[where ?t=\"E x\"])using Var by auto\n  { assume assm: \"type' = type\"\n      then have E'_def: \"E' = update_env (type,E x) E\" using Var  apply (auto simp add: clash_propagate2_def)\n      using min_consistent by blast\n    { fix E'' type'' fa\n    assume wty: \"E'' \\<turnstile> trm.Var x :: type''\" and  fa_def: \"wf_f fa \"   \"TCst  \\<circ> E'' = fa \\<circ> E \"  \"TCst type'' = fa type\"\n    let ?g = \"(\\<lambda>t. if type = t then TCst type'' else fa t)\"\n    have g1: \"wf_f ?g\" using   fa_def by (auto simp add: wf_f_def) \n    have \"(fa \\<circ> E) xa = ((\\<lambda>t. if type = t then TCst type'' else fa t) \\<circ> (\\<lambda>v. if E v = E x then type else E v)) xa \" for xa\n      using fa_def wty by (auto simp add: comp_def elim!: wty_trm.cases) metis\n     then have g2: \" TCst  \\<circ> E'' = ?g \\<circ> E'\" using  Var fa_def E'_def by (auto simp add:  update_env_def) \n      have res_less'': \"resultless_trm (TCst \\<circ> E'') E' (TCst type'') type'\"  using g1 g2 fa_def assm by (auto simp add: wf_f_def resultless_trm_def)\n    }\n\n    moreover have \"resultless_trm (TCst \\<circ>  E'') E' (TCst type'') type' \\<Longrightarrow> E'' \\<turnstile> trm.Var x :: type''\" \n      for E'' type'' using E'_def assm     apply (cases type'')\n          apply (auto  simp add: resultless_trm_def wf_f_def update_env_def comp_def intro!:wty_trm.intros) \n        by (metis tysym.inject(3))+    \n \n      ultimately have ?case  using assm wtyres1  apply (auto simp add:  wty_result_trm_def resultless_trm_def) by metis \n    } moreover {\n      assume assm: \"type' = E x\"\n      then have E'_def: \"E' = update_env (E x,type) E\" using Var  apply (auto simp add: clash_propagate2_def)\n      using min_consistent by blast\n    { fix E'' type'' fa\n    assume wty: \"E'' \\<turnstile> trm.Var x :: type''\" and  fa_def: \"wf_f fa \"   \"TCst  \\<circ> E'' = fa \\<circ> E \"  \"TCst type'' = fa type\"\n    let ?g = \"(\\<lambda>t. if E x = t then TCst type'' else fa t)\"\n    have g1: \"wf_f ?g\" using   fa_def apply (auto simp add: wf_f_def) \n      by (metis comp_eq_dest wty wty_trm.Var wty_trm_cong_aux)+ \n    have \" (fa \\<circ> E) y = (?g \\<circ> (E')) y \" for y\n      using fa_def wty E'_def by (auto simp add: update_env_def comp_def elim!: wty_trm.cases) metis\n     then have g2: \" TCst  \\<circ> E'' = ?g \\<circ> E'\" using  E'_def fa_def by auto\n      have res_less'': \"resultless_trm (TCst \\<circ> E'') E' (TCst type'') type'\"  using g1 g2 fa_def assm by (auto simp add: wf_f_def resultless_trm_def)\n    }\nmoreover\n    {\n      fix fa type'' E''\n      assume  \" TCst type'' = fa type'\" \"wf_f fa\" \"TCst \\<circ> E'' = fa \\<circ> (E')\"\n      from this have \" E'' \\<turnstile> trm.Var x :: type''\"  using  assm E'_def\n          apply (auto  simp add: wf_f_def update_env_def comp_def  intro!:wty_trm.intros ) \n        by (metis tysym.inject(3))\n    } \n ultimately have ?case using assm wtyres1  apply (auto simp add:  wty_result_trm_def resultless_trm_def)  by metis \n    } ultimately show ?case using min_consistent Var by (auto simp add: clash_propagate2_def)\nnext\n  case (Const x)\n  show ?case  apply (rule check_trm_step0_cst[where ty=\"ty_of x\"]) \n    using Const wty_trm.Const wty_trm_cong_aux by auto \nnext\n  case (Plus t1 t2)\n  then show ?case by (rule check_binop_sound) auto\nnext\n  case (Minus t1 t2)\n  then show ?case  by (rule check_binop_sound) auto\nnext\n\n  case (UMinus t)\n  then obtain E1 precise_type where E1_def: \"Some (E1, precise_type) = clash_propagate2 (TNum 0) (new_type_symbol type) (new_type_symbol \\<circ> E)\" by (auto split: option.splits)\n  have wtynum: \"\\<And> E'' y . E'' \\<turnstile> trm.UMinus t :: y \\<Longrightarrow> y \\<in> numeric_ty\" by (auto elim: wty_trm.cases)\n  have res_E1_E': \"wty_result_trm t E' type' E1 precise_type\"  apply  (rule UMinus.IH) using UMinus(2) E1_def by (auto split: option.splits)\n  show ?case apply (rule check_trm_step1[where ?E1.0=E1 and ?precise_type=precise_type]) \n    using  res_E1_E' E1_def wtynum check_trm_step0_num[of E1 precise_type type E \"trm.UMinus t\" ] \n      apply (auto simp add: half_wty_trm_def wty_result_trm_def elim: wty_trm.cases) subgoal for E'' typ'' \n      using check_trm_step0_num(2-3)[of E1 precise_type type E \"trm.UMinus t\" typ'' E''] resultless_trm_trans[of \"TCst \\<circ> E''\"]\n      by (auto  intro: wty_trm.intros) done\nnext\n  case (Mult t1 t2)\n  then show ?case by (rule check_binop_sound) auto\nnext\n  case (Div t1 t2)\n  then show ?case by (rule check_binop_sound) auto\nnext\n  case (Mod t1 t2)\n  then show ?case by (rule check_binop_sound[where ?constr=\"TCst TInt\"]) auto\nnext\n  case (F2i t)\n  then show ?case by (rule check_conversion_sound) auto\nnext\n  case (I2f t)\n  then show ?case by (rule check_conversion_sound[where ?a=TFloat])  auto\nqed \n\n\ndefinition wty_result_fX :: \"sig \\<Rightarrow> tysenv \\<Rightarrow> tysym Formula.formula  \\<Rightarrow> (tysym \\<Rightarrow> tysym) \\<Rightarrow> tysym set \\<Rightarrow> bool\" where\n  \"wty_result_fX S E \\<phi> f X \\<longleftrightarrow> wf_f f \\<and> \n(\\<forall>f'' .  wf_f (TCst \\<circ> f'') \\<longrightarrow> \n  (S, (f''\\<circ> E) \\<turnstile> (formula.map_formula  f'' \\<phi>)) = (\\<exists> g. wf_f (TCst \\<circ> g) \\<and>(\\<forall>t \\<in> X. f'' t = (g \\<circ> f) t)))\"\n\nlemma map_regex_fv:  assumes \"\\<And>x . x \\<in> regex.atms x2 \\<Longrightarrow>  g (formula.map_formula f x) = g' x\"\n  shows \"Regex.fv_regex g (regex.map_regex (formula.map_formula f) x2) = Regex.fv_regex g' x2\" using assms by (induction x2) auto\n\nlemma map_regex_pred:  assumes \"\\<And>x . x \\<in> regex.atms x2 \\<Longrightarrow>  g (formula.map_formula f x) = g' x\"\n  shows \"regex.pred_regex g (regex.map_regex (formula.map_formula f) x2) = regex.pred_regex g' x2\" using assms by (induction x2) auto\n\nlemma[simp]:  shows \"Formula.fvi b (formula.map_formula f \\<psi>) = Formula.fvi b \\<psi>\" \nproof (induction \\<psi> arbitrary: b)\n  case (MatchF x1 x2)\n  show ?case using map_regex_fv[where ?g=\"Formula.fvi b\" and ?f=f] MatchF by auto\n  case (MatchP x1 x2)\n  show ?case using map_regex_fv[where ?g=\"Formula.fvi b\" and ?f=f] MatchP by auto\nqed  auto\n\n\n\nlemma[simp]: \"Formula.nfv (formula.map_formula f \\<psi>) = Formula.nfv \\<psi>\" unfolding Formula.nfv_def by auto\n\nlemma[simp]: \" wf_formula (formula.map_formula f \\<psi>) = wf_formula \\<psi>\" by (induction \\<psi>) (auto simp add: list_all_def map_regex_pred)\n\nlemma used_tys_map[simp]: \"used_tys (f \\<circ> E) (formula.map_formula f \\<psi>) = f ` used_tys E \\<psi>\"\n  by (auto simp: used_tys_def formula.set_map)\n\nlemma map_formula_f_cong: \"(\\<And>t. t \\<in> X \\<Longrightarrow> f t = g t) \\<Longrightarrow> formula.set_formula \\<psi> \\<subseteq> X \\<Longrightarrow>\n  formula.map_formula f \\<psi> = formula.map_formula g \\<psi>\"\n  apply (induction \\<psi>)\n                  apply auto\n  subgoal for r\n    by (induction r) auto\n  subgoal for r\n    by (induction r) auto\n  done\n\nlemma wty_map_formula_cong: \"S, f \\<circ> E \\<turnstile> formula.map_formula f \\<psi> \\<Longrightarrow> used_tys E \\<psi> \\<subseteq> X \\<Longrightarrow>\n       (\\<And>t. t \\<in> X \\<Longrightarrow> f t = g t) \\<Longrightarrow> S, g \\<circ> E \\<turnstile> formula.map_formula g \\<psi>\"\n  apply (rule iffD1[OF wty_formula_fv_cong, where ?E1=\"f \\<circ> E\"])\n   apply (auto simp: used_tys_def)[1]\n  using map_formula_f_cong[of X f g]\n  by (auto simp: used_tys_def)\n\n\n\nlemma eq_refinement_min_type: assumes \"\\<exists> f g . wf_f f \\<and> wf_f g \\<and> f typ = g typ'\"\n  shows \"\\<exists> t1 t2 . min_type typ typ' = Some (t1,t2)\"\nproof -\n  obtain f g where typs: \"wf_f f\"  \"wf_f g\" \"f typ = g typ'\" using assms  by auto\n  then show ?thesis unfolding wf_f_def apply (induction \"typ\" typ' rule: min_type.induct) \n    by (auto  simp add: eq_commute[where ?b=  \"g (TAny _)\"] eq_commute[where ?b=  \"g (TNum _)\"] numeric_ty_def \n        split: tysym.splits nat.splits) \nqed\n\n\nlemma constr_complete: assumes \"resultless_trm (TCst \\<circ> E'') E (TCst typ'') typ\"\n  \"P typ''\" \n  \"P = (\\<lambda>x. x \\<in> numeric_ty) \\<and> constr = TNum 0 \\<and> E_start = new_type_symbol \\<circ> E \\<and> type_start = new_type_symbol typ \\<and> (P = (\\<lambda>y. y \\<in> numeric_ty))\n \\<or> P = (\\<lambda> x. x =  t) \\<and> constr = TCst t \\<and> E_start =  E \\<and> type_start = typ\"\n  \" clash_propagate2 constr type_start E_start = None\"\nshows False\nproof -\n  obtain f where f_def: \"wf_f f \\<and> f typ = TCst typ''\" using assms(1) unfolding resultless_trm_def by auto\n  have \"\\<exists> EE tt. min_type  constr type_start = Some(EE,tt)\" apply (rule eq_refinement_min_type)\n    apply (rule exI[of _ \"(\\<lambda> x. if x = constr then TCst typ'' else x)\"])\n    apply (rule exI[of _ \"(\\<lambda>x.  if x = type_start then f typ else x)\"])\n    using f_def assms(2,3)   unfolding wf_f_def new_type_symbol_def \n    by (auto simp add:  split: tysym.splits) \n  then show False using assms(4) by (auto simp add: clash_propagate2_def  split: option.splits) \nqed\n\nlemma check_binop_complete: \n  assumes \"\\<And>E typ E'' typ''. check_trm E typ t1 = None \\<Longrightarrow> resultless_trm (TCst \\<circ> E'') E (TCst typ'') typ \\<Longrightarrow> E'' \\<turnstile> t1 :: typ'' \\<Longrightarrow> False\"\n    \"\\<And>E typ E'' typ''. check_trm E typ t2 = None \\<Longrightarrow> resultless_trm (TCst \\<circ> E'') E (TCst typ'') typ \\<Longrightarrow> E'' \\<turnstile> t2 :: typ'' \\<Longrightarrow> False\"\n    \"check_trm E typ (trm t1 t2) = None\"\n    \"resultless_trm (TCst \\<circ> E'') E (TCst typ'') typ\"\n    \" E'' \\<turnstile> trm t1 t2 :: typ''\" \n    \"trm \\<in> {trm.Plus, trm.Minus, trm.Mult, trm.Div } \\<and> constr = TNum 0 \\<and> E_start = new_type_symbol \\<circ> E \\<and> type_start = new_type_symbol typ \\<and> P = (\\<lambda>x. x \\<in> numeric_ty)\n \\<or> trm = trm.Mod \\<and> constr = TCst TInt \\<and> E_start =  E \\<and> type_start = typ \\<and> P = (\\<lambda> x. x =  TInt)\"\n  shows False\nproof -\n  have \"clash_propagate2 constr type_start E_start = None \\<Longrightarrow>  False\"\n    apply (rule constr_complete[where ?t=TInt and ?P=P]) using assms(4-6)  by (auto elim: wty_trm.cases)\n    then obtain E1 t_typ where some_cp: \" Some(E1, t_typ) = clash_propagate2 constr type_start E_start\" by fastforce\n    then have half: \"half_wty_trm (trm t1 t2) E1 t_typ E  typ \"\n      unfolding half_wty_trm_def apply (cases \"trm t1 t2\") using  assms(6) check_trm_step0_num(1-2)[of E1 t_typ \" typ\" E \"trm t1 t2\"]\n        check_trm_step0_cst2\n      by (auto simp add:  elim:wty_trm.cases)  \n    then have \"resultless_trm (TCst \\<circ> E'') E1 (TCst typ'') t_typ\" unfolding half_wty_trm_def\n      using assms(5,6)  by (auto simp add:  assms(4) elim:wty_trm.cases)\n    then have t1_none: \" check_trm E1 t_typ t1 = None \\<Longrightarrow> False\" using assms(1)[of E1 t_typ E'' typ''] assms(5,6)\n      by (auto simp add: comp_def elim:wty_trm.cases)\n    have half2: \"check_trm E1 t_typ t1 = Some(E',type') \\<Longrightarrow> half_wty_trm  (trm t1 t2) E' type' E1 t_typ\" for E' type'\n      apply (rule subterm_half_wty[where ?t=t1]) using check_trm_sound assms(6) unfolding half_wty_trm_def wty_result_trm_def\n      by (auto elim: wty_trm.cases) \n    have E'_less: \"check_trm E1 t_typ t1 = Some(E',type') \\<Longrightarrow> resultless_trm (TCst \\<circ> E'') E' (TCst typ'') type'\" for E' type'\n      using assms(5,6) half_wty_trm_trans[OF half2 half] unfolding half_wty_trm_def \n      by (auto simp add: assms(4) elim: wty_trm.cases) \n    have t2_none: \"check_trm E1 t_typ t1 = Some(E',type') \\<Longrightarrow> False\"  for E' type' \n      apply  (rule assms(2)[of E' type']) using assms(3,5,6) some_cp E'_less\n      by (auto simp add: comp_def check_binop2_def split: option.splits elim:wty_trm.cases)\n    show False using t1_none t2_none  by fast\n  qed\n\nlemma check_conversion_complete: assumes   \n  \"\\<And>E typ E'' typ'' . check_trm E typ t = None \\<Longrightarrow> resultless_trm (TCst \\<circ> E'') E (TCst typ'') typ \\<Longrightarrow> E'' \\<turnstile> t :: typ'' \\<Longrightarrow> False\"\n    \"check_trm E typ (trm t) = None\"\n    \"resultless_trm (TCst \\<circ> E'') E (TCst typ'') typ\"\n   \" E'' \\<turnstile> trm t :: typ''\"\n\"trm = trm.F2i \\<and> a = TInt \\<and> b = TFloat \\<or> trm = trm.I2f \\<and> a = TFloat \\<and> b = TInt\"\n shows False\nproof -\n have cp_none: \"clash_propagate2 typ (TCst a)  E = None \\<Longrightarrow> False \"\n    apply (simp add: clash_prop_comm[where ?t1.0=\"typ\"])\n         apply (rule constr_complete[where ?t=a and ?P=\"(\\<lambda>x. x = a)\" and ?typ=\"typ\" and ?E''=E'' and ?E=E and ?typ''=typ'']) \n    using  assms(2-5)  by (auto simp add: comp_def elim:wty_trm.cases) \n  then obtain E_constr where constr_def: \"clash_propagate2 typ (TCst a)  E = Some (E_constr, TCst a)\"\n    using clash_propagate2_def min_comm min_const by fastforce\n  have  \"resultless_trm ( TCst \\<circ> E'') E_constr (TCst a) (TCst a)\" apply (rule check_trm_step0_cst2(2)[where ?E=E and ?type=\"typ\"]) \n    using constr_def assms(3-5) by (auto simp add: comp_def clash_prop_comm[where ?t1.0=\"typ\"] elim: wty_trm.cases) \n  then have  resless: \"resultless_trm ( TCst \\<circ> E'') E_constr (TCst b) (TCst b)\"\n    using tysenvless_resultless_trm[OF resultless_trm_tysenvless] by force \n   have  \"check_trm E_constr (TCst b) t = None \\<Longrightarrow> False\"  apply (rule assms(1)[where ?typ=\"TCst b\"]) using assms(2-5)\n      using resless by (auto simp add: comp_def elim: wty_trm.cases) \n  then show False using cp_none assms(2,5) constr_def by (auto simp add: clash_propagate2_def split: option.splits) \nqed\n\n(*Theorem 4.3*)\nlemma check_trm_complete: \" check_trm  E typ t = None \\<Longrightarrow> resultless_trm (TCst \\<circ> E'') E (TCst typ'') typ \\<Longrightarrow> E'' \\<turnstile> t :: typ'' \\<Longrightarrow> False\"\nproof (induction t arbitrary:  E \"typ\" E'' typ'')\n  case (Var x)\n   have \"\\<exists> f . wf_f f \\<and> TCst (typ'')  = f (E x) \\<and> (TCst typ'') = f typ \" using Var(2-3) \n    apply (auto simp add: resultless_trm_def comp_def elim!: wty_trm.cases)  by metis\n  then show ?case using eq_refinement_min_type[of \"E x\" \"typ\"] Var(1) by (auto simp add: clash_propagate2_def) fastforce   \nnext\n  case (Const x)\n  then show ?case using eq_refinement_min_type[of \"TCst (ty_of x)\" \"typ\"] \n    by (auto simp add: clash_propagate2_def resultless_trm_def wf_f_def elim!: wty_trm.cases ) metis  \nnext\n  case (Plus t1 t2)\n then show ?case by (rule check_binop_complete[where ?trm=\"trm.Plus\"]) (auto simp add: comp_def)\nnext\ncase (Minus t1 t2)\n  then show ?case by (rule check_binop_complete[where ?trm=\"trm.Minus\"]) (auto simp add: comp_def)\nnext\n  case (UMinus t)\n  have \"clash_propagate2 (TNum 0) (new_type_symbol typ) (new_type_symbol \\<circ> E) = None \\<Longrightarrow> False \"\n         apply (rule constr_complete[where ?t=TInt and ?P=\"(\\<lambda>x. x \\<in> numeric_ty)\"]) \n    using  UMinus(2-4)  by (auto simp add: comp_def elim: wty_trm.cases) \n  then obtain E_constr constr_type where constr_def: \" Some(E_constr, constr_type) = clash_propagate2 (TNum 0) (new_type_symbol typ) (new_type_symbol \\<circ> E)\"\n    by fastforce\n  have resless: \"resultless_trm (TCst \\<circ> E'') E_constr (TCst typ'') constr_type\" \n    by (rule check_trm_step0_num(2)[OF constr_def _ UMinus(3) UMinus(4)]) (auto elim:wty_trm.cases) \n  have \"check_trm E_constr constr_type t = None \" using UMinus(2) constr_def \n  by (auto simp add: eq_commute[where ?a=\"Some(E_constr, constr_type)\"] clash_propagate2_def)\n    then show ?case apply (rule UMinus.IH[OF _ resless]) using UMinus(4) by (auto elim: wty_trm.cases)\nnext\n  case (Mult t1 t2)\n  then show ?case by (rule check_binop_complete[where ?trm=\"trm.Mult\"]) (auto simp add: comp_def)\nnext                                 \ncase (Div t1 t2)\n  then show ?case by (rule check_binop_complete[where ?trm=\"trm.Div\"]) (auto simp add: comp_def)\nnext\n  case (Mod t1 t2)\n  then show ?case by (rule check_binop_complete[where ?trm=\"trm.Mod\" and ?constr=\"TCst TInt\"]) (auto simp add: comp_def)\nnext\n  case (F2i t)\n  then show ?case by (rule check_conversion_complete[where ?trm=trm.F2i]) (auto simp add: comp_def)  \nnext\n  case (I2f t)\n  then show ?case by (rule check_conversion_complete[where ?trm=trm.I2f and ?a=TFloat]) (auto simp add: comp_def)  \nqed \n\n\n\nlocale check_trm_f = fixes check_trm_f ::  \" tysenv \\<Rightarrow> tysym \\<Rightarrow> tysym set  \\<Rightarrow>  Formula.trm  \\<Rightarrow>   (tysym \\<Rightarrow> tysym) option\"\n  assumes check_trm_sound: \" check_trm_f E type X t = Some f \\<Longrightarrow> E`fv_trm t \\<subseteq> X \\<Longrightarrow> wty_result_fX_trm E type t f X\"\n  assumes check_trm_complete: \" check_trm_f  E type X t = None \\<Longrightarrow> E`fv_trm t \\<subseteq> X \\<Longrightarrow> wty_result_fX_trm E type t f X \\<Longrightarrow> False\"\nbegin\n\ndefinition check_comparison where\n\"check_comparison E X t1 t2  \\<equiv> (case check_trm_f   (new_type_symbol \\<circ> E) (TAny 0) (new_type_symbol ` X) t1  of\n   Some f \\<Rightarrow> (case check_trm_f (f \\<circ> new_type_symbol \\<circ> E) (f (TAny 0)) ((f \\<circ> new_type_symbol) `X) t2 of Some f' \\<Rightarrow> Some (f' \\<circ> f \\<circ> new_type_symbol) | None \\<Rightarrow> None )\n| None \\<Rightarrow> None)\"\n\ndefinition check_two_formulas :: \"(sig \\<Rightarrow> tysenv \\<Rightarrow> tysym set \\<Rightarrow> tysym Formula.formula  \\<Rightarrow>   (tysym \\<Rightarrow> tysym) option) \\<Rightarrow> sig \\<Rightarrow> tysenv  \\<Rightarrow> tysym set  \\<Rightarrow> tysym Formula.formula  \\<Rightarrow> tysym Formula.formula \\<Rightarrow>  (tysym \\<Rightarrow> tysym) option\" where\n\"check_two_formulas check S E X \\<phi> \\<psi>  \\<equiv> (case check S E X \\<phi>  of\n   Some f \\<Rightarrow> (case check S (f \\<circ> E) (f ` X) (formula.map_formula f \\<psi>) of Some f' \\<Rightarrow> Some (f' \\<circ> f) | None \\<Rightarrow> None )\n   | None \\<Rightarrow> None)\"\n\ndefinition check_ands_f :: \"(sig \\<Rightarrow> tysenv \\<Rightarrow> tysym set \\<Rightarrow> tysym Formula.formula  \\<Rightarrow>   (tysym \\<Rightarrow> tysym) option) \\<Rightarrow> sig \\<Rightarrow> tysenv \\<Rightarrow> tysym set \\<Rightarrow>  (tysym \\<Rightarrow> tysym) option \\<Rightarrow> tysym Formula.formula \\<Rightarrow>(tysym \\<Rightarrow> tysym) option  \" where\n\"check_ands_f check S E X = (\\<lambda> f_op \\<phi> . case f_op of Some f \\<Rightarrow> (case check S (f \\<circ> E) (f ` X)(formula.map_formula f \\<phi>) of Some f' \\<Rightarrow> Some (f' \\<circ> f)| None \\<Rightarrow> None )\n    | None \\<Rightarrow> None )\"\n\ndefinition check_ands where\n\"check_ands check S E X \\<phi>s = foldl (check_ands_f check S E X) (Some id) \\<phi>s\"\n\ndefinition highest_bound_TAny where\n\"highest_bound_TAny \\<phi> \\<equiv> Max ((\\<lambda>t. case t of TAny n \\<Rightarrow> n | _ \\<Rightarrow> 0) ` formula.set_formula \\<phi>)\"\n\ndefinition E_empty where\n\"E_empty \\<phi> = (TAny \\<circ> (+) (highest_bound_TAny \\<phi> + 1))\"\n\nfun check_pred :: \"tysenv \\<Rightarrow> tysym set \\<Rightarrow> Formula.trm list \\<Rightarrow> ty list \\<Rightarrow>  (tysym \\<Rightarrow> tysym) option\" where\n\"check_pred  E  X (trm#trms) (t#ts)  = (case check_trm_f  E (TCst t) X trm of\n Some f \\<Rightarrow> (case check_pred  (f\\<circ>E) (f `X) trms ts of Some f' \\<Rightarrow> Some (f' \\<circ>f) | None \\<Rightarrow> None)\n | None \\<Rightarrow> None)\"\n|\"check_pred  E  X [] []  = Some id\"\n|\"check_pred  E X  _ _  = None\"\n\nfun check_regex :: \"(sig \\<Rightarrow> tysenv  \\<Rightarrow> tysym set \\<Rightarrow> tysym Formula.formula  \\<Rightarrow>   (tysym \\<Rightarrow> tysym) option) \\<Rightarrow>sig \\<Rightarrow> tysenv  \\<Rightarrow> tysym set \\<Rightarrow> tysym Formula.formula Regex.regex  \\<Rightarrow>   (tysym \\<Rightarrow> tysym) option\"  where\n\"check_regex check S E X (Regex.Skip l)  = Some id\"\n| \"check_regex check S E X (Regex.Test \\<phi>)  = check S E X \\<phi>\"\n| \"check_regex check S E X (Regex.Plus r s)  = (case check_regex check S E X r  of\n  Some f \\<Rightarrow> (case check_regex check S (f \\<circ> E) (f ` X) (regex.map_regex (formula.map_formula f) s) of Some f' \\<Rightarrow> Some (f' \\<circ> f) | None \\<Rightarrow> None )\n| None \\<Rightarrow> None )\"\n| \"check_regex check S E X (Regex.Times r s)  = (case check_regex check S E X r  of\n  Some f \\<Rightarrow> (case check_regex check S (f \\<circ> E) (f ` X) (regex.map_regex (formula.map_formula f) s) of Some f' \\<Rightarrow> Some (f' \\<circ> f) | None \\<Rightarrow> None )\n| None \\<Rightarrow> None )\"\n| \"check_regex check S E X (Regex.Star r)  = check_regex check S E X r\"\n\n\nfun agg_trm_tysym :: \"Formula.agg_type \\<Rightarrow> tysym\" where\n\"agg_trm_tysym Formula.Agg_Sum = TNum 0\"\n| \"agg_trm_tysym Formula.Agg_Cnt = TAny 0\"\n| \"agg_trm_tysym Formula.Agg_Avg = TNum 0\"\n| \"agg_trm_tysym Formula.Agg_Med = TNum 0\"\n| \"agg_trm_tysym Formula.Agg_Min = TAny 0\"\n| \"agg_trm_tysym Formula.Agg_Max = TAny 0\"\n\nfun agg_ret_tysym :: \"Formula.agg_type \\<Rightarrow> tysym \\<Rightarrow> tysym\" where\n\"agg_ret_tysym Formula.Agg_Sum t = t\"\n| \"agg_ret_tysym Formula.Agg_Cnt _ = TCst TInt\"\n| \"agg_ret_tysym Formula.Agg_Avg _ = TCst TFloat\"\n| \"agg_ret_tysym agg_type.Agg_Med _ = TCst TFloat \"\n| \"agg_ret_tysym Formula.Agg_Min t = t\"\n| \"agg_ret_tysym Formula.Agg_Max t = t\"\n\n\nlemma [fundef_cong]: \"(\\<And> S E \\<phi>' X . size \\<phi>' \\<le> size \\<phi> + size \\<psi> \\<Longrightarrow> check S E X \\<phi>' = check' S E X \\<phi>') \\<Longrightarrow> check_two_formulas check S E X \\<phi> \\<psi> = check_two_formulas check' S E X \\<phi> \\<psi>\"\n  by (auto simp add: check_two_formulas_def split: option.split ) \n\nlemma foldl_check_ands_f_fundef_cong: \"(\\<And> S E \\<phi>' X .  size \\<phi>' \\<le> size_list size \\<phi>s \\<Longrightarrow> check S E X \\<phi>' = check' S E X \\<phi>') \\<Longrightarrow> foldl (check_ands_f check S E X) f \\<phi>s = foldl (check_ands_f check' S E X) f \\<phi>s\"\n  by (induction \\<phi>s arbitrary: f) (auto simp: check_ands_f_def split: option.splits)\n\nlemma [fundef_cong]: \"(\\<And> S E \\<phi>' X .  size \\<phi>' \\<le> size_list size \\<phi>s \\<Longrightarrow> check S E X \\<phi>' = check' S E X \\<phi>') \\<Longrightarrow> check_ands check S E X \\<phi>s = check_ands check' S E X \\<phi>s\"\n  using foldl_check_ands_f_fundef_cong[of \\<phi>s check]\n  by (auto simp: check_ands_def)\n\nlemma[simp]: \"regex.size_regex size (regex.map_regex (formula.map_formula x2) s) = regex.size_regex size s\"\n  by (induction s)  auto\n\nlemma [fundef_cong]: \"(\\<And> S E \\<phi>' X . size \\<phi>' \\<le> regex.size_regex size r \\<Longrightarrow> check S E X \\<phi>' = check' S E X \\<phi>') \\<Longrightarrow> check_regex check S E X r = check_regex check' S E X r\"\n   by (induction check S E X r  rule: check_regex.induct) (auto split: option.splits)    \n  \n\n\nfun check :: \"sig \\<Rightarrow> tysenv \\<Rightarrow> tysym set  \\<Rightarrow> tysym Formula.formula  \\<Rightarrow>   (tysym \\<Rightarrow> tysym) option\"\n  where (*what to do if predicate is not in sigs?*)\n  \"check S E X (Formula.Pred r ts)  = (case S r of \n  None \\<Rightarrow> None \n  | Some tys \\<Rightarrow>  check_pred E X ts tys)\"\n| \"check S E X (Formula.Let p \\<phi> \\<psi>)  = (case check S (E_empty \\<phi>) (used_tys (E_empty \\<phi>) \\<phi>) \\<phi> of \n  Some f \\<Rightarrow> if \\<forall>x \\<in> Formula.fv \\<phi> . case f ((E_empty \\<phi>) x) of TCst _ \\<Rightarrow> True | _ \\<Rightarrow> False \n      then  check (S(p \\<mapsto> tabulate (\\<lambda>x. case f ((E_empty \\<phi>) x) of TCst t \\<Rightarrow> t ) 0 (Formula.nfv \\<phi>))) E X \\<psi> \n      else None  | None \\<Rightarrow> None)\"\n| \"check S E X (Formula.Eq t1 t2)  = check_comparison E X t1 t2 \"\n| \"check S E X (Formula.Less t1 t2)  = check_comparison  E X t1 t2 \"\n| \"check S E X (Formula.LessEq t1 t2)  = check_comparison E X t1 t2 \"\n| \"check S E X (Formula.Neg \\<phi>)  =  check S E X \\<phi>\"\n| \"check S E X (Formula.Or \\<phi> \\<psi>)  =  check_two_formulas check S E X \\<phi> \\<psi>\"\n| \"check S E X (Formula.And \\<phi> \\<psi>)  = check_two_formulas check S E X \\<phi> \\<psi>\"\n| \"check S E X (Formula.Ands \\<phi>s)  = check_ands check S E X \\<phi>s\" \n| \"check S E X (Formula.Exists t \\<phi>)  =   check S (case_nat  t E) X \\<phi> \" \n| \"check S E X (Formula.Agg y (agg_type, d) tys trm \\<phi>)  = (case check_trm  (new_type_symbol \\<circ> (agg_tysenv E  tys)) (agg_trm_tysym agg_type) trm of\n   Some (E', trm_type) \\<Rightarrow> (case check S E' X (formula.map_formula (trm_f_new  E' E trm_type (agg_trm_tysym agg_type) (fv_trm trm) X )  \\<phi>) of \n       Some  f \\<Rightarrow> (case clash_propagate2 ((f \\<circ> E'\\<circ> (+) (length tys)) y) (TCst (ty_of d) ) (f \\<circ> E' \\<circ> (+) (length tys)) of \n          Some (E''', ret_t) \\<Rightarrow> (case clash_propagate2 ret_t (agg_ret_tysym agg_type trm_type) E''' of \n              Some (E4, t4) \\<Rightarrow> \n                 Some  (trm_f_new E4 E''' t4 ret_t {y} X \\<circ> trm_f_new E''' (f \\<circ> E' \\<circ> (+) (length tys)) ret_t (TCst (ty_of d)) {y} X \\<circ> f ) \n               | None \\<Rightarrow> None )\n          | None \\<Rightarrow> None)\n       | None \\<Rightarrow> None)\n   | None \\<Rightarrow> None)\"\n| \"check S E X (Formula.Prev I \\<phi>)  =  check S E X \\<phi> \"\n| \"check S E X (Formula.Next I \\<phi>)  =   check S E X \\<phi> \"\n| \"check S E X (Formula.Since \\<phi> I \\<psi>)  = check_two_formulas check S E X \\<phi> \\<psi>\"\n| \"check S E X (Formula.Until \\<phi> I \\<psi>) =  check_two_formulas check S E X \\<phi> \\<psi>  \"\n| \"check S E X (Formula.MatchF I r)  = check_regex check S E X r\"\n| \"check S E X (Formula.MatchP I r)  = check_regex check S E X r \"\n\n\ninductive proven_frm :: \"'t Formula.formula \\<Rightarrow> bool\"\n where\nEq: \"proven_frm (Formula.Eq x y)\"\n| Less: \"proven_frm (Formula.Less x y)\"\n| LessEq: \"proven_frm (Formula.LessEq x y)\"\n| Neg: \"proven_frm \\<phi> \\<Longrightarrow> proven_frm ( Formula.Neg \\<phi>)\"\n| Or: \"proven_frm \\<phi> \\<Longrightarrow>proven_frm  \\<psi> \\<Longrightarrow>proven_frm ( Formula.Or \\<phi> \\<psi>)\"\n| And: \"proven_frm \\<phi> \\<Longrightarrow>proven_frm  \\<psi> \\<Longrightarrow>proven_frm ( Formula.And \\<phi> \\<psi>)\"\n| Exists: \"proven_frm \\<phi> \\<Longrightarrow> proven_frm  (Formula.Exists t \\<phi>)\"\n| Prev: \"proven_frm \\<phi> \\<Longrightarrow>proven_frm ( Formula.Prev \\<I> \\<phi>)\"\n| Next: \"proven_frm \\<phi> \\<Longrightarrow>proven_frm ( Formula.Next \\<I> \\<phi>)\"\n| Since: \"proven_frm \\<phi> \\<Longrightarrow>proven_frm  \\<psi> \\<Longrightarrow>proven_frm (Formula.Since \\<phi> \\<I> \\<psi>)\" \n| Until: \"proven_frm \\<phi> \\<Longrightarrow>proven_frm  \\<psi> \\<Longrightarrow>proven_frm (Formula.Until \\<phi> \\<I> \\<psi>)\"\n\nlemma proven_frm_map: \"proven_frm (formula.map_formula f \\<psi>) \\<Longrightarrow> proven_frm \\<psi>\"\n  by (induction \\<psi> )  (auto intro: proven_frm.intros elim: proven_frm.cases ) \n lemma proven_frm_map2: \" proven_frm \\<psi> \\<Longrightarrow> proven_frm (formula.map_formula f \\<psi>)\"\n   by (induction \\<psi> )  (auto intro: proven_frm.intros elim: proven_frm.cases ) \n\nlemma check_binary_sound: assumes \n  \"\\<And>\\<phi>' S E f' X. size \\<phi>' \\<le> size \\<phi> + size \\<psi> \\<Longrightarrow> check S E X \\<phi>' = Some f' \\<Longrightarrow> proven_frm \\<phi>' \\<Longrightarrow> used_tys E \\<phi>' \\<subseteq> X \\<Longrightarrow> wty_result_fX S E \\<phi>' f' X\"\n  \"check S E X form = Some f'\" \"used_tys E form \\<subseteq> X\"\n  \"proven_frm form\" \"form \\<in> {formula.Or \\<phi> \\<psi>, formula.And \\<phi> \\<psi>, formula.Since \\<phi> I \\<psi>, formula.Until \\<phi> I \\<psi>}\" shows \" wty_result_fX S E form f' X\"\nproof -\n  obtain  f where f_def: \"check S E X \\<phi> = Some  f\" using assms by (auto simp add: check_two_formulas_def split: option.splits)\n  have wty1: \" wty_result_fX S E \\<phi> f X\" apply (rule assms(1)[OF _ f_def])\n    using assms(2-)  unfolding used_tys_def\n    by (auto simp: check_two_formulas_def  intro:proven_frm.intros elim: proven_frm.cases split: option.splits)\n  obtain f1 where  f1_def: \"check S (f\\<circ>E) (f `X) (formula.map_formula f \\<psi>) = Some  f1 \\<and> f' = f1 \\<circ> f \"\n    using assms(2,4,5) f_def\n    by (auto simp add: check_two_formulas_def split: option.splits)\n  have used_tys_form: \"used_tys E form = used_tys E \\<phi> \\<union> used_tys E \\<psi>\"\n    using assms(5)\n    by (auto simp: used_tys_def)\n  then have aux: \"used_tys (f \\<circ> E) (formula.map_formula f \\<psi>) \\<subseteq> f ` X\"\n    using assms(3,5) by auto\n  have wty2:\" wty_result_fX S (f\\<circ>E) (formula.map_formula f \\<psi>) f1 (f ` X)\"\n    apply (rule assms(1)) using assms(3,4,5) f1_def aux\n    by (auto simp add: proven_frm_map2 comp_def intro:proven_frm.intros elim:proven_frm.cases) \n  have f'_def: \"f' = f1 \\<circ> f\"\n    by (auto simp: f1_def)\n  have wty_form_iff: \"S, f'' \\<circ> E \\<turnstile> formula.map_formula f'' form \\<longleftrightarrow>\n    S, f'' \\<circ> E \\<turnstile> formula.map_formula f'' \\<phi> \\<and> S, f'' \\<circ> E \\<turnstile> formula.map_formula f'' \\<psi>\" for f''\n    using assms(5)\n    by (auto elim: wty_formula.cases intro: wty_formula.intros)\n  show ?thesis\n    using wty1 wty2 assms(3) wty_map_formula_cong[of S _ E] \n    apply (auto simp: f'_def used_tys_form wty_form_iff wty_result_fX_def formula.set_map\n        formula.map_comp intro: wf_f_comp) \n      apply (smt (z3) comp_apply comp_assoc)\n     apply (metis comp_apply comp_assoc wf_f_comp)\n    subgoal premises prems for f'' g\n    proof -\n      have \"wf_f (TCst \\<circ> (g \\<circ> f1))\"\n        using prems(4,9) wf_f_comp[OF prems(9,4)]\n        by (auto simp: comp_assoc)\n      then have \"(S, (g \\<circ> f1 \\<circ> f) \\<circ> E \\<turnstile> formula.map_formula (g \\<circ> f1 \\<circ> f) \\<psi>)\"\n        using prems(9) spec[OF prems(5), where ?x=\"g \\<circ> f1\"]\n        by (auto simp: comp_assoc)\n      then show ?thesis\n        using prems(7)\n        apply (rule wty_map_formula_cong)\n        using prems(10)\n        by auto\n    qed\n    done\nqed\n\nlemma check_comparison_sound: assumes \"check S E X form = Some f'\"\n    \"wf_formula form\"\n   \" used_tys E form \\<subseteq> X\" \n\"form \\<in> {formula.Less t1 t2,formula.LessEq t1 t2,formula.Eq t1 t2}\"\n shows \" wty_result_fX S E (formula.Eq t1 t2) f' X\"\nproof -\n obtain f1 where f1_def: \"Some f1 = check_trm_f (new_type_symbol \\<circ> E) (TAny 0) (new_type_symbol ` X) t1\" using assms(1,4) by (auto simp add: check_comparison_def split: option.splits)\n    then obtain f2 where f2_def: \"Some f2 = check_trm_f (f1 \\<circ> new_type_symbol \\<circ> E) (f1 (TAny 0)) ((f1 \\<circ> new_type_symbol)` X) t2 \" using assms(1,4) by (auto simp add: check_comparison_def split: option.splits)\n    have wty1: \"wty_result_fX_trm (new_type_symbol \\<circ> E)  (TAny 0) t1 f1 (new_type_symbol ` X)\"  apply (rule check_trm_sound) using f1_def assms(3,4) by (auto simp add: used_tys_def)  fastforce+\n    have wty2:  \"wty_result_fX_trm (f1\\<circ> new_type_symbol \\<circ> E) (f1 (TAny 0)) t2 f2 ((f1 \\<circ> new_type_symbol) `X)\" apply (rule check_trm_sound) using f2_def assms(3,4) by (auto simp add: used_tys_def)  fastforce+\n    have f'_def: \"f' = f2 \\<circ> f1 \\<circ> new_type_symbol\" using assms(1,4) f1_def f2_def by (auto simp add: check_comparison_def split: option.splits)\n   \n    show ?thesis using wty1 wty2\n      apply (auto simp add: f'_def wty_result_fX_trm_def wty_result_fX_def check_comparison_def split: option.splits \n            elim!: wty_formula.cases )\n      subgoal using wf_f_comp[OF _ wf_f_comp[of f1 new_type_symbol], of f2] by (auto simp add: comp_def) subgoal\npremises prems  for f'' t\n      proof - \n        thm prems \n        define nn where \"nn = (\\<lambda>t'. case t' of TAny (Suc n) \\<Rightarrow> TAny n  | TAny 0 \\<Rightarrow> TCst t | TNum n \\<Rightarrow> TNum (n-1) | _ \\<Rightarrow> t' )\"\n        have nn_n: \"nn \\<circ> new_type_symbol = id\"  by (auto simp add: nn_def new_type_symbol_def split: tysym.splits nat.splits)\n        have wf_nn: \"wf_f nn\" by (auto simp add: nn_def wf_f_def)\n        have \"f'' \\<circ> nn \\<circ> new_type_symbol \\<circ> E \\<turnstile> t1 :: f'' (nn (TAny 0))\" using prems(6)\n          apply (auto simp add: comp_assoc nn_n) using prems(5) unfolding nn_def wf_f_def by (auto split: tysym.splits)\n        then have \"(\\<exists>g. wf_f (TCst \\<circ> g) \\<and> (\\<forall>t\\<in>X. (f'') t = g (f1 (new_type_symbol t))) \\<and> f'' (nn (TAny 0)) = g (f1  (TAny 0)))\" using prems(2) wf_f_comp[OF prems(5) wf_nn]\n          apply  (auto simp add: nn_n  o_assoc)  by (drule spec[of _ \"f'' \\<circ>nn\"])  (simp add: nn_n pointfree_idE rewriteR_comp_comp)\n        then obtain g  where g_def: \"wf_f (TCst \\<circ> g) \\<and> (\\<forall>t\\<in>X. (f'') t = g (f1 (new_type_symbol t))) \\<and> f'' (nn (TAny 0)) = g (f1  (TAny 0))\" by auto\n        have g_f1_t: \"g (f1 (TAny 0)) = t\" using g_def nn_def prems(5) wf_f_def by (auto split: tysym.splits)\n        have \"g \\<circ> (f1 \\<circ> new_type_symbol \\<circ> E) \\<turnstile> t2 :: g (f1 (TAny 0))\" using prems(7) g_def apply (auto simp add: g_f1_t)\n          apply (rule iffD1[OF wty_trm_fv_cong, of _ \"f''\\<circ>E\"]) using assms(3,4) unfolding used_tys_def by fastforce+\n          then have \"\\<exists>g'. wf_f (TCst \\<circ> g') \\<and> (\\<forall>t\\<in>X. g (f1 (new_type_symbol t)) = g' (f2 (f1 (new_type_symbol t))))\" using g_def prems(4,7) \n          by auto \n         then show ?thesis by (simp add: g_def)\n       qed\n       subgoal premises prems for f'' g\n       proof -\n         thm prems\n         define nn where \"nn = (\\<lambda>t'. case t' of TAny (Suc n) \\<Rightarrow> TAny n  | TAny 0 \\<Rightarrow> TCst (g (f2 (f1 (TAny 0)))) | TNum n \\<Rightarrow> TNum (n-1) | _ \\<Rightarrow> t' )\"\n        have nn_n: \"nn \\<circ> new_type_symbol = id\"  by (auto simp add: nn_def new_type_symbol_def split: tysym.splits nat.splits)\n        have wf_nn: \"wf_f nn\" by (auto simp add: nn_def wf_f_def)\n\n        have wt1:\"(f'' \\<circ> nn \\<circ> (new_type_symbol \\<circ> E) \\<turnstile> t1 :: f''(nn (TAny 0)))\" using spec[OF prems(2), of \"f'' \\<circ> nn\"] wf_f_comp[OF prems(5) wf_nn]\n          apply (auto simp add: o_assoc) apply (rule exI[of _ \"g\\<circ>f2\"]) using prems(7) wf_f_comp[OF prems(6) prems(3) ] nn_n \n          apply (auto simp add: comp_assoc) \n           apply (metis pointfree_idE) using prems(5) unfolding nn_def wf_f_def by auto  \n        have t_eq: \"g (f2 (f1 (TAny 0))) = f''(nn (TAny 0))\" using prems(5) unfolding nn_def wf_f_def by auto\n        have \"g \\<circ> f2 \\<circ> (f1 \\<circ> new_type_symbol \\<circ> E) \\<turnstile> t2 :: (g \\<circ> f2) (f1 (TAny 0))\" using spec[OF prems(4), of \"g \\<circ> f2\"] \n             wf_f_comp[OF prems(6) prems(3)]  prems(6,7) by (auto simp add: o_assoc)\n        then have wt2:\"g \\<circ> f2 \\<circ> (f1 \\<circ> new_type_symbol \\<circ> E) \\<turnstile> t2 :: f''(nn (TAny 0))\" by (auto simp add: t_eq)\n        show ?thesis  apply (auto  intro!: wty_formula.intros(3-5)[where ?t=\"f''(nn (TAny 0))\"])\n           apply (rule iffD1[OF wty_trm_fv_cong wt1]) using prems(7) assms(3) unfolding used_tys_def apply auto apply ( simp add: nn_n pointfree_idE)\n          apply (rule iffD1[OF wty_trm_fv_cong wt2]) using prems(7) assms(3,4) unfolding used_tys_def by (fastforce simp add: nn_n pointfree_idE)\n      qed done\n  qed\n\n(*Theorem 4.6 *)\nlemma check_sound_proven:  \"check S E X \\<phi> = Some f'  \\<Longrightarrow> proven_frm \\<phi> \\<Longrightarrow> used_tys E \\<phi> \\<subseteq> X  \\<Longrightarrow> wty_result_fX S E \\<phi> f' X\"\nproof (induction S E X \\<phi> arbitrary: f' rule:  check.induct)\n   case (3 S E X t1 t2) \n      obtain f1 where f1_def: \"Some f1 = check_trm_f (new_type_symbol \\<circ> E) (TAny 0) (new_type_symbol ` X) t1\" using 3(1) by (auto simp add: check_comparison_def split: option.splits)\n    then obtain f2 where f2_def: \"Some f2 = check_trm_f (f1 \\<circ> new_type_symbol \\<circ> E) (f1 (TAny 0)) ((f1 \\<circ> new_type_symbol)` X) t2 \" using 3(1) by (auto simp add: check_comparison_def split: option.splits)\n    have wty1: \"wty_result_fX_trm (new_type_symbol \\<circ> E)  (TAny 0) t1 f1 (new_type_symbol ` X)\"  apply (rule check_trm_sound) using f1_def 3(3) by (auto simp add: used_tys_def)\n    have wty2:  \"wty_result_fX_trm (f1\\<circ> new_type_symbol \\<circ> E) (f1 (TAny 0)) t2 f2 ((f1 \\<circ> new_type_symbol) `X)\" \n      apply (rule check_trm_sound) using f2_def 3(3) by (auto simp add: used_tys_def)\n    have f'_def: \"f' = f2 \\<circ> f1 \\<circ> new_type_symbol\" using 3(1) f1_def f2_def by (auto simp add: check_comparison_def split: option.splits)\n    show ?case using wty1 wty2 \n      apply (auto simp add: f'_def wty_result_fX_trm_def wty_result_fX_def check_comparison_def split: option.splits \n            elim!: wty_formula.cases )\n      subgoal using wf_f_comp[OF _ wf_f_comp[of f1 new_type_symbol], of f2] by (auto simp add: comp_def) subgoal\npremises prems  for f'' t\n      proof - \n        thm prems \n        define nn where \"nn = (\\<lambda>t'. case t' of TAny (Suc n) \\<Rightarrow> TAny n  | TAny 0 \\<Rightarrow> TCst t | TNum n \\<Rightarrow> TNum (n-1) | _ \\<Rightarrow> t' )\"\n        have nn_n: \"nn \\<circ> new_type_symbol = id\"  by (auto simp add: nn_def new_type_symbol_def split: tysym.splits nat.splits)\n        have wf_nn: \"wf_f nn\" by (auto simp add: nn_def wf_f_def)\n        have \"f'' \\<circ> nn \\<circ> new_type_symbol \\<circ> E \\<turnstile> t1 :: f'' (nn (TAny 0))\" using prems(6)\n          apply (auto simp add: comp_assoc nn_n) using prems(5) unfolding nn_def wf_f_def by (auto split: tysym.splits)\n        then have \"(\\<exists>g. wf_f (TCst \\<circ> g) \\<and> (\\<forall>t\\<in>X. (f'') t = g (f1 (new_type_symbol t))) \\<and> f'' (nn (TAny 0)) = g (f1  (TAny 0)))\" using prems(2) wf_f_comp[OF prems(5) wf_nn]\n          apply  (auto simp add: nn_n  o_assoc)  by (drule spec[of _ \"f'' \\<circ>nn\"])  (simp add: nn_n pointfree_idE rewriteR_comp_comp)\n        then obtain g  where g_def: \"wf_f (TCst \\<circ> g) \\<and> (\\<forall>t\\<in>X. (f'') t = g (f1 (new_type_symbol t))) \\<and> f'' (nn (TAny 0)) = g (f1  (TAny 0))\" by auto\n        have g_f1_t: \"g (f1 (TAny 0)) = t\" using g_def nn_def prems(5) wf_f_def by (auto split: tysym.splits)\n        have \"g \\<circ> (f1 \\<circ> new_type_symbol \\<circ> E) \\<turnstile> t2 :: g (f1 (TAny 0))\" using prems(7) g_def apply (auto simp add: g_f1_t)\n          apply (rule iffD1[OF wty_trm_fv_cong, of _ \"f''\\<circ>E\"]) using 3(3) unfolding used_tys_def by auto\n          then have \"\\<exists>g'. wf_f (TCst \\<circ> g') \\<and> (\\<forall>t\\<in>X. g (f1 (new_type_symbol t)) = g' (f2 (f1 (new_type_symbol t))))\" using g_def prems(4,7) \n          by auto \n         then show ?thesis by (simp add: g_def)\n       qed\n       subgoal premises prems for f'' g\n       proof -\n         thm prems\n         define nn where \"nn = (\\<lambda>t'. case t' of TAny (Suc n) \\<Rightarrow> TAny n  | TAny 0 \\<Rightarrow> TCst (g (f2 (f1 (TAny 0)))) | TNum n \\<Rightarrow> TNum (n-1) | _ \\<Rightarrow> t' )\"\n        have nn_n: \"nn \\<circ> new_type_symbol = id\"  by (auto simp add: nn_def new_type_symbol_def split: tysym.splits nat.splits)\n        have wf_nn: \"wf_f nn\" by (auto simp add: nn_def wf_f_def)\n\n        have wt1:\"(f'' \\<circ> nn \\<circ> (new_type_symbol \\<circ> E) \\<turnstile> t1 :: f''(nn (TAny 0)))\" using spec[OF prems(2), of \"f'' \\<circ> nn\"] wf_f_comp[OF prems(5) wf_nn]\n          apply (auto simp add: o_assoc) apply (rule exI[of _ \"g\\<circ>f2\"]) using prems(7) wf_f_comp[OF prems(6) prems(3) ] nn_n \n          apply (auto simp add: comp_assoc) \n           apply (metis pointfree_idE) using prems(5) unfolding nn_def wf_f_def by auto  \n        have t_eq: \"g (f2 (f1 (TAny 0))) = f''(nn (TAny 0))\" using prems(5) unfolding nn_def wf_f_def by auto\n        have \"g \\<circ> f2 \\<circ> (f1 \\<circ> new_type_symbol \\<circ> E) \\<turnstile> t2 :: (g \\<circ> f2) (f1 (TAny 0))\" using spec[OF prems(4), of \"g \\<circ> f2\"] \n             wf_f_comp[OF prems(6) prems(3)]  prems(6,7) by (auto simp add: o_assoc)\n        then have wt2:\"g \\<circ> f2 \\<circ> (f1 \\<circ> new_type_symbol \\<circ> E) \\<turnstile> t2 :: f''(nn (TAny 0))\" by (auto simp add: t_eq)\n        show ?thesis  apply (auto  intro!: wty_formula.intros(3-5)[where ?t=\"f''(nn (TAny 0))\"])\n           apply (rule iffD1[OF wty_trm_fv_cong wt1]) using prems(7) 3(3) unfolding used_tys_def apply auto apply ( simp add: nn_n pointfree_idE)\n          apply (rule iffD1[OF wty_trm_fv_cong wt2]) using prems(7) 3(3) unfolding used_tys_def by (auto simp add: nn_n pointfree_idE)\n       qed done\n  next\n    case (4 S E X t1 t2)\n    obtain f1 where f1_def: \"Some f1 = check_trm_f (new_type_symbol \\<circ> E) (TAny 0) (new_type_symbol ` X) t1\" using 4(1) by (auto simp add: check_comparison_def split: option.splits)\n    then obtain f2 where f2_def: \"Some f2 = check_trm_f (f1 \\<circ> new_type_symbol \\<circ> E) (f1 (TAny 0)) ((f1 \\<circ> new_type_symbol)` X) t2 \" using 4(1) by (auto simp add: check_comparison_def split: option.splits)\n    have wty1: \"wty_result_fX_trm (new_type_symbol \\<circ> E)  (TAny 0) t1 f1 (new_type_symbol ` X)\"  apply (rule check_trm_sound) using f1_def 4(3) by (auto simp add: used_tys_def)\n    have wty2:  \"wty_result_fX_trm (f1\\<circ> new_type_symbol \\<circ> E) (f1 (TAny 0)) t2 f2 ((f1 \\<circ> new_type_symbol) `X)\" apply (rule check_trm_sound) using f2_def 4(3) by (auto simp add: used_tys_def)\n    have f'_def: \"f' = f2 \\<circ> f1 \\<circ> new_type_symbol\" using 4(1) f1_def f2_def by (auto simp add: check_comparison_def split: option.splits)\n    show ?case using wty1 wty2 \n      apply (auto simp add: f'_def wty_result_fX_trm_def wty_result_fX_def check_comparison_def split: option.splits \n            elim!: wty_formula.cases )\n      subgoal using wf_f_comp[OF _ wf_f_comp[of f1 new_type_symbol], of f2] by (auto simp add: comp_def) subgoal\npremises prems  for f'' t\n      proof - \n        thm prems \n        define nn where \"nn = (\\<lambda>t'. case t' of TAny (Suc n) \\<Rightarrow> TAny n  | TAny 0 \\<Rightarrow> TCst t | TNum n \\<Rightarrow> TNum (n-1) | _ \\<Rightarrow> t' )\"\n        have nn_n: \"nn \\<circ> new_type_symbol = id\"  by (auto simp add: nn_def new_type_symbol_def split: tysym.splits nat.splits)\n        have wf_nn: \"wf_f nn\" by (auto simp add: nn_def wf_f_def)\n        have \"f'' \\<circ> nn \\<circ> new_type_symbol \\<circ> E \\<turnstile> t1 :: f'' (nn (TAny 0))\" using prems(6)\n          apply (auto simp add: comp_assoc nn_n) using prems(5) unfolding nn_def wf_f_def by (auto split: tysym.splits)\n        then have \"(\\<exists>g. wf_f (TCst \\<circ> g) \\<and> (\\<forall>t\\<in>X. (f'') t = g (f1 (new_type_symbol t))) \\<and> f'' (nn (TAny 0)) = g (f1  (TAny 0)))\" using prems(2) wf_f_comp[OF prems(5) wf_nn]\n          apply  (auto simp add: nn_n  o_assoc)  by (drule spec[of _ \"f'' \\<circ>nn\"])  (simp add: nn_n pointfree_idE rewriteR_comp_comp)\n        then obtain g  where g_def: \"wf_f (TCst \\<circ> g) \\<and> (\\<forall>t\\<in>X. (f'') t = g (f1 (new_type_symbol t))) \\<and> f'' (nn (TAny 0)) = g (f1  (TAny 0))\" by auto\n        have g_f1_t: \"g (f1 (TAny 0)) = t\" using g_def nn_def prems(5) wf_f_def by (auto split: tysym.splits)\n        have \"g \\<circ> (f1 \\<circ> new_type_symbol \\<circ> E) \\<turnstile> t2 :: g (f1 (TAny 0))\" using prems(7) g_def apply (auto simp add: g_f1_t)\n          apply (rule iffD1[OF wty_trm_fv_cong, of _ \"f''\\<circ>E\"]) using 4(3) unfolding used_tys_def by auto\n          then have \"\\<exists>g'. wf_f (TCst \\<circ> g') \\<and> (\\<forall>t\\<in>X. g (f1 (new_type_symbol t)) = g' (f2 (f1 (new_type_symbol t))))\" using g_def prems(4,7) \n          by auto \n         then show ?thesis by (simp add: g_def)\n       qed\n       subgoal premises prems for f'' g\n       proof -\n         thm prems\n         define nn where \"nn = (\\<lambda>t'. case t' of TAny (Suc n) \\<Rightarrow> TAny n  | TAny 0 \\<Rightarrow> TCst (g (f2 (f1 (TAny 0)))) | TNum n \\<Rightarrow> TNum (n-1) | _ \\<Rightarrow> t' )\"\n        have nn_n: \"nn \\<circ> new_type_symbol = id\"  by (auto simp add: nn_def new_type_symbol_def split: tysym.splits nat.splits)\n        have wf_nn: \"wf_f nn\" by (auto simp add: nn_def wf_f_def)\n\n        have wt1:\"(f'' \\<circ> nn \\<circ> (new_type_symbol \\<circ> E) \\<turnstile> t1 :: f''(nn (TAny 0)))\" using spec[OF prems(2), of \"f'' \\<circ> nn\"] wf_f_comp[OF prems(5) wf_nn]\n          apply (auto simp add: o_assoc) apply (rule exI[of _ \"g\\<circ>f2\"]) using prems(7) wf_f_comp[OF prems(6) prems(3) ] nn_n \n          apply (auto simp add: comp_assoc) \n           apply (metis pointfree_idE) using prems(5) unfolding nn_def wf_f_def by auto  \n        have t_eq: \"g (f2 (f1 (TAny 0))) = f''(nn (TAny 0))\" using prems(5) unfolding nn_def wf_f_def by auto\n        have \"g \\<circ> f2 \\<circ> (f1 \\<circ> new_type_symbol \\<circ> E) \\<turnstile> t2 :: (g \\<circ> f2) (f1 (TAny 0))\" using spec[OF prems(4), of \"g \\<circ> f2\"] \n             wf_f_comp[OF prems(6) prems(3)]  prems(6,7) by (auto simp add: o_assoc)\n        then have wt2:\"g \\<circ> f2 \\<circ> (f1 \\<circ> new_type_symbol \\<circ> E) \\<turnstile> t2 :: f''(nn (TAny 0))\" by (auto simp add: t_eq)\n        show ?thesis  apply (auto  intro!: wty_formula.intros(3-5)[where ?t=\"f''(nn (TAny 0))\"])\n           apply (rule iffD1[OF wty_trm_fv_cong wt1]) using prems(7) 4(3) unfolding used_tys_def apply auto apply ( simp add: nn_n pointfree_idE)\n          apply (rule iffD1[OF wty_trm_fv_cong wt2]) using prems(7) 4(3) unfolding used_tys_def by (auto simp add: nn_n pointfree_idE)\n       qed done\n  next \n    case (5 S E X t1 t2)\n       obtain f1 where f1_def: \"Some f1 = check_trm_f (new_type_symbol \\<circ> E) (TAny 0) (new_type_symbol ` X) t1\" using 5(1) by (auto simp add: check_comparison_def split: option.splits)\n    then obtain f2 where f2_def: \"Some f2 = check_trm_f (f1 \\<circ> new_type_symbol \\<circ> E) (f1 (TAny 0)) ((f1 \\<circ> new_type_symbol)` X) t2 \" using 5(1) by (auto simp add: check_comparison_def split: option.splits)\n    have wty1: \"wty_result_fX_trm (new_type_symbol \\<circ> E)  (TAny 0) t1 f1 (new_type_symbol ` X)\"  apply (rule check_trm_sound) using f1_def 5(3) by (auto simp add: used_tys_def)\n    have wty2:  \"wty_result_fX_trm (f1\\<circ> new_type_symbol \\<circ> E) (f1 (TAny 0)) t2 f2 ((f1 \\<circ> new_type_symbol) `X)\" \n      apply (rule check_trm_sound) using f2_def 5(3) by (auto simp add: used_tys_def)\n    have f'_def: \"f' = f2 \\<circ> f1 \\<circ> new_type_symbol\" using 5(1) f1_def f2_def by (auto simp add: check_comparison_def split: option.splits)\n    show ?case using wty1 wty2 \n      apply (auto simp add: f'_def wty_result_fX_trm_def wty_result_fX_def check_comparison_def split: option.splits \n            elim!: wty_formula.cases )\n      subgoal using wf_f_comp[OF _ wf_f_comp[of f1 new_type_symbol], of f2] by (auto simp add: comp_def) subgoal\npremises prems  for f'' t\n      proof - \n        thm prems \n        define nn where \"nn = (\\<lambda>t'. case t' of TAny (Suc n) \\<Rightarrow> TAny n  | TAny 0 \\<Rightarrow> TCst t | TNum n \\<Rightarrow> TNum (n-1) | _ \\<Rightarrow> t' )\"\n        have nn_n: \"nn \\<circ> new_type_symbol = id\"  by (auto simp add: nn_def new_type_symbol_def split: tysym.splits nat.splits)\n        have wf_nn: \"wf_f nn\" by (auto simp add: nn_def wf_f_def)\n        have \"f'' \\<circ> nn \\<circ> new_type_symbol \\<circ> E \\<turnstile> t1 :: f'' (nn (TAny 0))\" using prems(6)\n          apply (auto simp add: comp_assoc nn_n) using prems(5) unfolding nn_def wf_f_def by (auto split: tysym.splits)\n        then have \"(\\<exists>g. wf_f (TCst \\<circ> g) \\<and> (\\<forall>t\\<in>X. (f'') t = g (f1 (new_type_symbol t))) \\<and> f'' (nn (TAny 0)) = g (f1  (TAny 0)))\" using prems(2) wf_f_comp[OF prems(5) wf_nn]\n          apply  (auto simp add: nn_n  o_assoc)  by (drule spec[of _ \"f'' \\<circ>nn\"])  (simp add: nn_n pointfree_idE rewriteR_comp_comp)\n        then obtain g  where g_def: \"wf_f (TCst \\<circ> g) \\<and> (\\<forall>t\\<in>X. (f'') t = g (f1 (new_type_symbol t))) \\<and> f'' (nn (TAny 0)) = g (f1  (TAny 0))\" by auto\n        have g_f1_t: \"g (f1 (TAny 0)) = t\" using g_def nn_def prems(5) wf_f_def by (auto split: tysym.splits)\n        have \"g \\<circ> (f1 \\<circ> new_type_symbol \\<circ> E) \\<turnstile> t2 :: g (f1 (TAny 0))\" using prems(7) g_def apply (auto simp add: g_f1_t)\n          apply (rule iffD1[OF wty_trm_fv_cong, of _ \"f''\\<circ>E\"]) using 5(3) unfolding used_tys_def by auto\n          then have \"\\<exists>g'. wf_f (TCst \\<circ> g') \\<and> (\\<forall>t\\<in>X. g (f1 (new_type_symbol t)) = g' (f2 (f1 (new_type_symbol t))))\" using g_def prems(4,7) \n          by auto \n         then show ?thesis by (simp add: g_def)\n       qed\n       subgoal premises prems for f'' g\n       proof -\n         thm prems\n         define nn where \"nn = (\\<lambda>t'. case t' of TAny (Suc n) \\<Rightarrow> TAny n  | TAny 0 \\<Rightarrow> TCst (g (f2 (f1 (TAny 0)))) | TNum n \\<Rightarrow> TNum (n-1) | _ \\<Rightarrow> t' )\"\n        have nn_n: \"nn \\<circ> new_type_symbol = id\"  by (auto simp add: nn_def new_type_symbol_def split: tysym.splits nat.splits)\n        have wf_nn: \"wf_f nn\" by (auto simp add: nn_def wf_f_def)\n\n        have wt1:\"(f'' \\<circ> nn \\<circ> (new_type_symbol \\<circ> E) \\<turnstile> t1 :: f''(nn (TAny 0)))\" using spec[OF prems(2), of \"f'' \\<circ> nn\"] wf_f_comp[OF prems(5) wf_nn]\n          apply (auto simp add: o_assoc) apply (rule exI[of _ \"g\\<circ>f2\"]) using prems(7) wf_f_comp[OF prems(6) prems(3) ] nn_n \n          apply (auto simp add: comp_assoc) \n           apply (metis pointfree_idE) using prems(5) unfolding nn_def wf_f_def by auto  \n        have t_eq: \"g (f2 (f1 (TAny 0))) = f''(nn (TAny 0))\" using prems(5) unfolding nn_def wf_f_def by auto\n        have \"g \\<circ> f2 \\<circ> (f1 \\<circ> new_type_symbol \\<circ> E) \\<turnstile> t2 :: (g \\<circ> f2) (f1 (TAny 0))\" using spec[OF prems(4), of \"g \\<circ> f2\"] \n             wf_f_comp[OF prems(6) prems(3)]  prems(6,7) by (auto simp add: o_assoc)\n        then have wt2:\"g \\<circ> f2 \\<circ> (f1 \\<circ> new_type_symbol \\<circ> E) \\<turnstile> t2 :: f''(nn (TAny 0))\" by (auto simp add: t_eq)\n        show ?thesis  apply (auto  intro!: wty_formula.intros(3-5)[where ?t=\"f''(nn (TAny 0))\"])\n           apply (rule iffD1[OF wty_trm_fv_cong wt1]) using prems(7) 5(3) unfolding used_tys_def apply auto apply ( simp add: nn_n pointfree_idE)\n          apply (rule iffD1[OF wty_trm_fv_cong wt2]) using prems(7) 5(3) unfolding used_tys_def by (auto simp add: nn_n pointfree_idE)\n       qed done\n  next\n    case (6 S E X \\<phi>)\n  then have \"wty_result_fX S E \\<phi> f' X\" unfolding used_tys_def by (auto elim: proven_frm.cases) \n   then show ?case  unfolding wty_result_fX_def by (auto intro: wty_formula.intros elim: wty_formula.cases) \nnext\n\n  case (7 S E \\<phi> \\<psi>)\n     show ?case apply (rule check_binary_sound) using 7 by auto\n next \n    case (8 S E \\<phi> \\<psi>)\n    show ?case apply (rule check_binary_sound) using 8 by auto\n  next\n    case (10 S E X t \\<phi>) \n    have prv: \"proven_frm \\<phi>\" using 10(3) by cases\n    have case_nat_comp: \"f'' \\<circ> case_nat t E = case_nat (f'' t) (f'' \\<circ> E)\"   for f'' :: \"tysym \\<Rightarrow> ty\"  by (auto split: nat.splits) \n     have \"used_tys (case_nat t E) \\<phi> \\<subseteq> X\" using 10  unfolding  used_tys_def by (auto split: nat.splits) (meson fvi_Suc image_subset_iff)\n    then show ?case using 10 prv unfolding wty_result_fX_def apply auto subgoal for f''  apply (drule spec[of _ \"f''\"]) \n        by (auto simp add: case_nat_comp elim:  wty_formula.cases)\n      by (metis case_nat_comp wty_formula.Exists)\nnext\n  case (12 S E X I \\<phi>)\n  then have \"wty_result_fX S E \\<phi> f' X\" unfolding used_tys_def by (auto elim: proven_frm.cases) \n  then show ?case  unfolding wty_result_fX_def by (auto intro: wty_formula.intros elim: wty_formula.cases) \nnext\n  case (13 S E X I \\<phi>)\nthen have \"wty_result_fX S E \\<phi> f' X\" unfolding used_tys_def by (auto elim: proven_frm.cases) \n   then show ?case  unfolding wty_result_fX_def by (auto intro: wty_formula.intros elim: wty_formula.cases) \nnext\n  case (14 S E X \\<phi> I \\<psi>)\n  show ?case apply (rule check_binary_sound) using 14 by auto\nnext\n  case (15 S E X \\<phi> I \\<psi>)\n  show ?case apply (rule check_binary_sound) using 15 by auto\nqed (auto elim: proven_frm.cases)\n\nend\n\n\nlemma rel_regex_mono_trans:\n  \"regex.rel_regex (\\<lambda>a b. \\<forall>x. R a x \\<longrightarrow> R' b x) x y \\<Longrightarrow> regex.rel_regex R x z \\<Longrightarrow> regex.rel_regex R' y z\"\nproof (induction x y arbitrary: z rule: regex.rel_induct)\n  case (Skip a1 b1)\n  then show ?case\n    by (cases z) auto\nnext\n  case (Test a2 b2)\n  then show ?case\n    by (cases z) auto\nnext\n  case (Plus a31 a32 b31 b32)\n  then show ?case\n    by (cases z) auto\nnext\n  case (Times a41 a42 b41 b42)\n  then show ?case\n    by (cases z) auto\nnext\n  case (Star a5 b5)\n  then show ?case\n    by (cases z) auto\nqed\n\nlemma rel_formula_trans: \n  assumes Rtrans: \"\\<And>x y z. R x y \\<Longrightarrow> R x z \\<Longrightarrow> R' y z\"\n  shows \"formula.rel_formula R x y \\<Longrightarrow> formula.rel_formula R x z \\<Longrightarrow> formula.rel_formula R' y z\"\nproof (induction x y arbitrary: z rule: formula.rel_induct)\n  case (Pred a11 a12 b11 b12)\n  then show ?case\n    by (cases z) auto\nnext\n  case (Let a21 a22 a23 b21 b22 b23)\n  then show ?case\n    by (cases z) auto\nnext\n  case (Eq a31 a32 b31 b32)\n  then show ?case\n    by (cases z) auto\nnext\n  case (Less a41 a42 b41 b42)\n  then show ?case\n    by (cases z) auto\nnext\n  case (LessEq a51 a52 b51 b52)\n  then show ?case\n    by (cases z) auto\nnext\n  case (Neg a6 b6)\n  then show ?case\n    by (cases z) auto\nnext\n  case (Or a71 a72 b71 b72)\n  then show ?case\n    by (cases z) auto\nnext\n  case (And a81 a82 b81 b82)\n  then show ?case\n    by (cases z) auto\nnext\n  case (Ands a9 b9)\n  then show ?case\n    by (cases z) (auto simp: list_all2_conv_all_nth)\nnext\n  case (Exists a101 a102 b101 b102)\n  then show ?case\n    using Rtrans\n    by (cases z) auto\nnext\n  case (Agg a111 a112 a113 a114 a115 b111 b112 b113 b114 b115)\n  then show ?case\n    using Rtrans\n    by (cases z) (auto simp: list_all2_conv_all_nth)\nnext\n  case (Prev a121 a122 b121 b122)\n  then show ?case\n    by (cases z) auto\nnext\n  case (Next a131 a132 b131 b132)\n  then show ?case\n    by (cases z) auto\nnext\n  case (Since a141 a142 a143 b141 b142 b143)\n  then show ?case\n    by (cases z) auto\nnext\n  case (Until a151 a152 a153 b151 b152 b153)\n  then show ?case\n    by (cases z) auto\nnext\n  case (MatchF a161 a162 b161 b162)\n  then show ?case\n    by (cases z) (auto intro: rel_regex_mono_trans)\nnext\n  case (MatchP a171 a172 b171 b172)\n  then show ?case\n    by (cases z) (auto intro: rel_regex_mono_trans)\nqed\n\n(*<*)\nend\n(*>*)\n", "meta": {"author": "cc23", "repo": "MFODL-Typing", "sha": "d5c19d3035418f91dff8aaeb3f1a3984d81f7b64", "save_path": "github-repos/isabelle/cc23-MFODL-Typing", "path": "github-repos/isabelle/cc23-MFODL-Typing/MFODL-Typing-d5c19d3035418f91dff8aaeb3f1a3984d81f7b64/thys/MFODL_Monitor_Devel/Typing.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8723473647220787, "lm_q2_score": 0.81047890180374, "lm_q1q2_score": 0.7070191341513371}}
{"text": "theory Ch3\nimports Complex_Main \"~~/src/HOL/IMP/AExp\" \"~~/src/HOL/IMP/BExp\" \"~~/src/HOL/IMP/ASM\"\nbegin\n\n(* 3.1 *)\nfun optimal :: \"aexp \\<Rightarrow> bool\" where\n  \"optimal (Plus (N _) (N _)) = False\" |\n  \"optimal (Plus a1 a2) = (optimal a1 \\<and> optimal a2)\" |\n  \"optimal _ = True\"\n\ntheorem optimal_asimp_const [simp]: \"optimal (asimp_const a)\"\n  apply(induction a)\n  apply(auto split: aexp.split)\ndone\n\n(* 3.2 *)\nfun zero_N :: \"aexp \\<Rightarrow> aexp\" where\n  \"zero_N (N _) = (N 0)\" |\n  \"zero_N (Plus a1 a2) = Plus (zero_N a1) (zero_N a2)\" |\n  \"zero_N a = a\"\n\nfun full_sum :: \"aexp \\<Rightarrow> val\" where\n  \"full_sum (N n) = n\" |\n  \"full_sum (V v) = 0\" | \n  \"full_sum (Plus a1 a2) = full_sum a1 + full_sum a2\"\n\nfun expand_sum :: \"aexp \\<Rightarrow> aexp\" where\n  \"expand_sum a = N (full_sum a)\"\n\nlemma plus_sum_zero_equiv [simp]: \"aval (Plus (expand_sum a) (zero_N a)) s = aval a s\"\n  apply(induction a rule: zero_N.induct)\n  apply(auto)\ndone\n\nfun full_vars :: \"aexp \\<Rightarrow> vname list\" where\n  \"full_vars (N n) = []\" |\n  \"full_vars (V v) = [v]\" |\n  \"full_vars (Plus a1 a2) = full_vars a1 @ full_vars a2\"\n\nfun expand_vlist :: \"vname list \\<Rightarrow> aexp\" where\n  \"expand_vlist [v] = V v\" |\n  \"expand_vlist (v # vs) = Plus (V v) (expand_vlist vs)\" |\n  \"expand_vlist [] = N 0\"\n\nfun expand_vars :: \"aexp \\<Rightarrow> aexp\" where\n  \"expand_vars a = expand_vlist (full_vars a)\"\n\nlemma vlist_cons [simp]: \"aval (expand_vlist (v # vs)) s = aval (V v) s + aval (expand_vlist vs) s\"\n  apply(induction vs)\n  apply(auto)\ndone\n\nlemma vlist_app [simp]: \"aval (expand_vlist (vs1 @ vs2)) s =\n    aval (expand_vlist vs1) s + aval (expand_vlist vs2) s\"\n  apply(induction vs1)\n  apply(auto)\ndone\n\nlemma vars_zero_equiv [simp]: \"aval (expand_vars a) s = aval (zero_N a) s\"\n  apply(induction a)\n  apply(auto)\ndone\n\nfun sum_vars :: \"aexp \\<Rightarrow> aexp\" where\n  \"sum_vars a = Plus (expand_sum a) (expand_vars a)\"\n\nlemma sum_vars_correct [simp]: \"aval (sum_vars a) s = aval a s\"\n  apply(induction a)\n  apply(auto)\ndone\n\nfun full_asimp :: \"aexp \\<Rightarrow> aexp\" where\n  \"full_asimp a = asimp (sum_vars a)\"\n\ntheorem full_asimp_correct: \"aval (full_asimp a) s = aval a s\"\n  apply(induction a)\n  apply(auto)\ndone\n\n(* 3.3 *)\nfun subst :: \"vname \\<Rightarrow> aexp \\<Rightarrow> aexp \\<Rightarrow> aexp\" where\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  \"subst x a e = e\"\n\nvalue \"subst ''x'' (N 3) (Plus (V ''x'') (V ''y''))\"\n\nlemma subst_\n\ntheorem subst_eq: \"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)\ndone\n\n(* 3.4 *)\n(* See Ch3_AExp.thy *)\n\n(* 3.5 *)\ndatatype aexp2 = N2 val\n               | V2 vname\n               | Plus2 aexp2 aexp2\n               | Times2 aexp2 aexp2\n               | Div2 aexp2 aexp2\n               | PostInc2 vname\n\nfun aval2 :: \"aexp2 \\<Rightarrow> state \\<Rightarrow> ((val, state) prod) 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 = (\n    case aval2 a1 s of Some (x, t) \\<Rightarrow> (\n      case aval2 a2 t of Some (y, u) \\<Rightarrow> (\n        Some (x + y, u)\n      )\n    )\n  )\" |\n  \"aval2 (Times2 a1 a2) s = (\n    case aval2 a1 s of Some (x, t) \\<Rightarrow> (\n      case aval2 a2 t of Some (y, u) \\<Rightarrow> (\n        Some (x * y, u)\n      )\n    )\n  )\" |\n  \"aval2 (Div2 a1 a2) s = (\n    case aval2 a1 s of Some (x, t) \\<Rightarrow> (\n      case aval2 a2 t of Some (y, u) \\<Rightarrow> (\n        if y = 0 then None else Some (x div y, u)\n      )\n    )\n  )\" |\n  \"aval2 (PostInc2 v) s = Some (s v, s(v := s v + 1))\"\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 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\nfun inline :: \"lexp \\<Rightarrow> aexp\" where\n  \"inline (Nl n) = N n\" |\n  \"inline (Vl v) = V v\" |\n  \"inline (Plusl e1 e2) = Plus (inline e1) (inline e2)\" |\n  \"inline (LET v e1 e2) = subst v (inline e1) (inline e2)\"\n\ntheorem inline_correct: \"lval e s = aval (inline e) s\"\n  apply(induction e arbitrary: s)\n  apply(auto)\ndone\n\n(* 3.7 *)\nfun or :: \"bexp \\<Rightarrow> bexp \\<Rightarrow> bexp\" where\n  \"or (Bc True) _ = Bc True\" |\n  \"or _ (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\nfun Eq :: \"aexp \\<Rightarrow> aexp \\<Rightarrow> bexp\" where\n  \"Eq (N n1) (N n2) = Bc (n1 = n2)\" |\n  \"Eq a1 a2 = and (not(less a1 a2)) (not(less a2 a1))\"\n\nfun Le :: \"aexp \\<Rightarrow> aexp \\<Rightarrow> bexp\" where\n  \"Le (N n1) (N n2) = Bc (n1 \\<le> n2)\" |\n  \"Le a1 a2 = or (less a1 a2) (Eq a1 a2)\"\n\ntheorem eq_correct [simp]: \"bval (Eq a1 a2) s = (aval a1 s = aval a2 s)\"\n  apply(induction a1 rule: Eq.induct)\n  apply(auto)\ndone\n\ntheorem le_correct [simp]: \"bval (Le a1 a2) s = (aval a1 s \\<le> aval a2 s)\"\n  apply(induction a1 rule: Le.induct)\n  apply(auto)\ndone\n\n(* 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 v) s = v\" |\n  \"ifval (If bp bt be) s = (if (ifval bp s) then (ifval bt s) else (ifval be 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) (If (b2ifexp b2) (Bc2 True) (Bc2 False)) (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 bp bt be) = or (And (if2bexp bp) (if2bexp bt)) (And (Not (if2bexp bp)) (if2bexp be))\" |\n  \"if2bexp (Less2 a1 a2) = Less a1 a2\"\n\ntheorem b2ifexp_correct: \"ifval (b2ifexp b) s = bval b s\"\n  apply(induction b)\n  apply(auto)\ndone\n\ntheorem i2bfexp_correct: \"bval (if2bexp i) s = ifval i s\"\n  apply(induction i)\n  apply(auto)\ndone\n\n(* 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 _) = True\" |\n  \"is_nnf (NOT (VAR _)) = True\" |\n  \"is_nnf (NOT _) = 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\nfun nnf :: \"pbexp \\<Rightarrow> pbexp\" where\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  \"nnf b = b\"\n\ntheorem nnf_correct [simp]: \"pbval (nnf b) s = pbval b s\"\n  apply(induction b rule: nnf.induct)\n  apply(auto)\ndone\n\ntheorem nnf_is_nnf [simp]: \"is_nnf (nnf b)\"\n  apply(induction b rule: nnf.induct)\n  apply(auto)\ndone\n\nfun no_or :: \"pbexp \\<Rightarrow> bool\" where\n  \"no_or (AND b1 b2) = (no_or b1 \\<and> no_or b2)\" |\n  \"no_or (OR _ _) = False\" |\n  \"no_or _ = True\"\n\nfun is_dnf :: \"pbexp \\<Rightarrow> bool\" where\n  \"is_dnf (AND b1 b2) = (no_or b1 \\<and> no_or b2)\" |\n  \"is_dnf (OR b1 b2) = (is_dnf b1 \\<and> is_dnf b2)\" |\n  \"is_dnf _ = True\" \n\nfun dist_AND :: \"pbexp \\<Rightarrow> pbexp \\<Rightarrow> pbexp\" where\n  \"dist_AND b (OR b1 b2) = OR (dist_AND b b1) (dist_AND b b2)\" |\n  \"dist_AND (OR b1 b2) b = OR (dist_AND b1 b) (dist_AND b2 b)\" |\n  \"dist_AND b1 b2 = AND b1 b2\"\n\nlemma dist_AND_correct [simp]: \"pbval (dist_AND b1 b2) s = pbval (AND b1 b2) s\"\n  apply(induction b1 b2 rule: dist_AND.induct)\n  apply(auto)\ndone\n\nlemma is_dnf_dist [simp]: \"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)\ndone\n\nfun dnf_of_nnf :: \"pbexp \\<Rightarrow> pbexp\" where\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  \"dnf_of_nnf b = b\"\n\ntheorem dnf_of_nnf_correct [simp]: \"pbval (dnf_of_nnf b) s = pbval b s\"\n  apply(induction b)\n  apply(auto)\ndone\n\ntheorem dnf_of_nnf_converts: \"is_nnf b \\<Longrightarrow> is_dnf (dnf_of_nnf b)\"\n  apply(induction b rule: dnf_of_nnf.induct)\n  apply(auto)\ndone\n\n(* 3.10 *)\n(* See Ch3_ASM.thy *)\n\n(* 3.11 *)\ntype_synonym reg = nat\n\ndatatype instr = LDI val 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 n r) _ rs = rs(r := n)\" |\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\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 e1 e2) r = comp e1 r @ comp e2 (r + 1) @ [ADD r (r + 1)]\"\n\nlemma exec_dist_app [simp]: \"exec (is1 @ is2) s rs = exec is2 s (exec is1 s rs)\"\n  apply(induction is1 arbitrary: rs)\n  apply(auto)\ndone\n\nlemma exec_gt_r [simp]: \"r2 > r1 \\<Longrightarrow> exec (comp a r2) s rs r1 = rs r1\"\n  apply(induction a arbitrary: r1 r2 rs)\n  apply(auto)\ndone\n\ntheorem comp_correct [simp]: \"exec (comp a r) s rs r = aval a s\"\n  apply(induction a arbitrary: r rs)\n  apply(auto)\ndone\n\n(* 3.12 *)\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 n) _ rs = rs(0 := n)\" |\n  \"exec01 (LD0 v) s rs = rs(0 := s v)\" |\n  \"exec01 (MV0 r) _ 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\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 e1 e2) r =\n    comp0 e1 (r + 1) @\n    comp0 e2 (r + 2) @\n    [LDI0 0, ADD0 (r + 1), ADD0 (r + 2), MV0 r]\"\n\nlemma exec0_dist_app [simp]: \"exec0 (is1 @ is2) s rs = exec0 is2 s (exec0 is1 s rs)\"\n  apply(induction is1 arbitrary: rs)\n  apply(auto)\ndone\n\nlemma exec0_gt_r [simp]: \"r2 > r1 \\<Longrightarrow> r1 > 0 \\<Longrightarrow> exec0 (comp0 a r2) s rs r1 = rs r1\"\n  apply(induction a arbitrary: r1 r2 rs)\n  apply(auto)\ndone\n\ntheorem comp0_correct_r [simp]: \"exec0 (comp0 a r) s rs r = aval a s\"\n  apply(induction a arbitrary: r rs)\n  apply(auto)\ndone\n\ntheorem comp0_correct [simp]: \"exec0 (comp0 a r) s rs 0 = aval a s\"\n  apply(induction a arbitrary: r rs)\n  apply(auto)\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.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942171172603, "lm_q2_score": 0.782662489091802, "lm_q1q2_score": 0.7069745003512256}}
{"text": "theory PFHOL_pol imports Main\nbegin \n\n(* A polymorphic Embedding of Positive Free Higher-Order Logic (PFHOL) in HOL *)\n\n\ntext \\<open> Positive Free Higher-Order Logic \\<close>\n\n  typedecl i (* \u2014 Type for individuals *)\n\n  consts fExistence :: \"'a \\<Rightarrow> bool\" (\"E\") (* \u2014 Existence/definedness predicate *)\n\n  consts fUndef :: \"'a\" (\"\\<^bold>e\") (* Distinguished symbol for undefinedness or falsehood *)\n  axiomatization where fUndefIAxiom: \"\\<not>E (\\<^bold>e::i)\"\n  axiomatization where fFalsehoodBAxiom: \"(\\<^bold>e::bool) = False\"\n\n  (* axiomatization where fNonemptyDomains: \"\\<exists>x. E x\" *)\n\n  definition fIdentity :: \"'a \\<Rightarrow> 'a \\<Rightarrow> bool\" (infixr \"\\<^bold>=\" 56) (* \u2014 Free identity *)\n    where \"\\<phi> \\<^bold>= \\<psi> \\<equiv> \\<phi> = \\<psi>\"\n\n  definition fNot :: \"bool \\<Rightarrow> bool\" (\"\\<^bold>\\<not>_\" [52]53) (* \u2014 Free negation *)\n    where \"\\<^bold>\\<not>\\<phi> \\<equiv> \\<not>\\<phi>\" \n  definition fOr :: \"bool \\<Rightarrow> bool \\<Rightarrow> bool\" (infixr \"\\<^bold>\\<or>\" 51) (* \u2014 Free disjunction *)\n    where \"\\<phi> \\<^bold>\\<or> \\<psi> \\<equiv> \\<phi> \\<or> \\<psi>\" \n\n  definition fForall :: \"('a \\<Rightarrow> bool) \\<Rightarrow> bool\" (\"\\<^bold>\\<forall>\") (* \u2014 Free universal quantification guarded by predicate E *)\n    where \"\\<^bold>\\<forall>\\<Phi> \\<equiv> \\<forall>x. E x \\<longrightarrow> \\<Phi> x\"   \n  definition fForallBinder:: \"('a \\<Rightarrow> bool) \\<Rightarrow> bool\" (binder \"\\<^bold>\\<forall>\" [8]9) (* \u2014 Binder notation *)\n    where \"\\<^bold>\\<forall>x. \\<phi> x \\<equiv> \\<^bold>\\<forall>\\<phi>\"\n\n  definition fThat :: \"('a \\<Rightarrow> bool) \\<Rightarrow> 'a\" (\"\\<^bold>I\") (* \u2014 Free definite description guarded by predicate E *)  \n    where \"\\<^bold>I\\<Phi> \\<equiv> if \\<exists>x. E x \\<and> \\<Phi> x \\<and> (\\<forall>y. (E y \\<and> \\<Phi> y) \\<longrightarrow> (y = x)) \n                 then THE x. E x \\<and> \\<Phi> x\n                 else \\<^bold>e\"\n  definition fThatBinder:: \"('a \\<Rightarrow> bool) \\<Rightarrow> 'a\" (binder \"\\<^bold>I\" [8]9) (* \u2014 Binder notation *) \n    where \"\\<^bold>Ix. \\<phi> x \\<equiv> \\<^bold>I\\<phi>\"\n\n  text \\<open> Further logical constants can be defined as usual \\<close>\n\n  definition fAnd :: \"bool \\<Rightarrow> bool \\<Rightarrow> bool\" (infixr \"\\<^bold>\\<and>\" 52) (* \u2014 Free conjunction *)\n    where \"\\<phi> \\<^bold>\\<and> \\<psi> \\<equiv> \\<^bold>\\<not>(\\<^bold>\\<not>\\<phi> \\<^bold>\\<or> \\<^bold>\\<not>\\<psi>)\"   \n  definition fImp :: \"bool \\<Rightarrow> bool \\<Rightarrow> bool\" (infixr \"\\<^bold>\\<rightarrow>\" 49) (* \u2014 Free implication *)\n    where \"\\<phi> \\<^bold>\\<rightarrow> \\<psi> \\<equiv> \\<^bold>\\<not>\\<phi> \\<^bold>\\<or> \\<psi>\"\n  definition fEquiv :: \"bool \\<Rightarrow> bool \\<Rightarrow> bool\" (infixr \"\\<^bold>\\<leftrightarrow>\" 50) (* \u2014 Free equivalence *)\n    where \"\\<phi> \\<^bold>\\<leftrightarrow> \\<psi> \\<equiv> \\<phi> \\<^bold>\\<rightarrow> \\<psi> \\<^bold>\\<and> \\<psi> \\<^bold>\\<rightarrow> \\<phi>\"  \n\n  definition fExists :: \"('a \\<Rightarrow> bool) \\<Rightarrow> bool\" (\"\\<^bold>\\<exists>\") (* \u2014 Free existential quantification *)                                   \n    where \"\\<^bold>\\<exists>\\<Phi> \\<equiv> \\<^bold>\\<not>(\\<^bold>\\<forall>(\\<lambda>y. \\<^bold>\\<not>(\\<Phi> y)))\"\n  definition fExistsBinder :: \"('a \\<Rightarrow> bool) \\<Rightarrow> bool\" (binder \"\\<^bold>\\<exists>\" [8]9) (* \u2014 Binder notation *)                   \n    where \"\\<^bold>\\<exists>x. \\<phi> x \\<equiv> \\<^bold>\\<exists>\\<phi>\"\n\n\n  (* Introducing \"Defs\" as the set of the above definitions; useful for convenient unfolding *)\n  named_theorems Defs declare fIdentity_def[Defs] fNot_def[Defs] fOr_def[Defs] fForall_def[Defs] \n    fForallBinder_def[Defs] fThat_def[Defs] fThatBinder_def[Defs] fAnd_def[Defs] fImp_def[Defs] \n    fEquiv_def[Defs] fExists_def[Defs] fExistsBinder_def[Defs]\n\n\ntext \\<open> Some Tests \\<close>\n\n  lemma \"(\\<^bold>\\<forall>x. P x) \\<^bold>\\<rightarrow>  P x\" nitpick [user_axioms=true, show_all, format=2] oops (* properly invalid *)\n  lemma \"((\\<^bold>\\<forall>x. (P x)) \\<^bold>\\<and> (E x)) \\<^bold>\\<rightarrow> (P x)\"\n    by (metis fAnd_def fForallBinder_def fForall_def fImp_def fNot_def fOr_def) (* properly valid *)\n\n  lemma \"P x \\<^bold>\\<rightarrow> (\\<^bold>\\<exists>x. P x)\" nitpick [user_axioms=true, show_all, format=2] oops (* properly invalid *)\n  lemma \"(x \\<^bold>= y) \\<^bold>\\<rightarrow> (\\<^bold>\\<exists>x. (x \\<^bold>= y))\" nitpick [user_axioms=true, show_all, format=2] oops (* properly invalid *)\n  lemma \"(x \\<^bold>\\<or> y) \\<^bold>\\<rightarrow> (\\<^bold>\\<exists>x. (x \\<^bold>\\<or> y))\" nitpick [user_axioms=true, show_all, format=2] oops (* properly invalid *)\n  lemma \"((P x) \\<^bold>\\<and> (E x)) \\<^bold>\\<rightarrow> (\\<^bold>\\<exists>x. P x)\" unfolding Defs by blast (* properly valid *)\n  \n  lemma \"(P x) \\<^bold>\\<and> (\\<^bold>\\<exists>x. P x)\" nitpick [user_axioms=true, show_all, format=2] oops (* properly invalid *)\n  lemma \"(P x) \\<^bold>\\<rightarrow> (E x)\" nitpick [user_axioms=true, show_all, format=2] oops (* properly invalid *)\n\n  lemma \"(P x) \\<^bold>\\<or> (\\<^bold>\\<not>(P x))\" unfolding Defs by auto (* properly valid *)\n  lemma \"(P x) \\<^bold>\\<and> (\\<^bold>\\<not>(P x))\" nitpick [user_axioms=true, show_all, format=2] oops (* properly invalid *)\n  lemma \"\\<^bold>\\<not>((P x) \\<^bold>\\<and> (\\<^bold>\\<not>(P x)))\" unfolding Defs by auto (* properly valid *)\n\n\n  consts fIndividual1 :: \"i\" (\"i\\<^sub>1\")\n  axiomatization where fUndefIndividual1Axiom: \"\\<^bold>\\<not>(E i\\<^sub>1)\"\n\n  consts fIndividual2 :: \"i\" (\"i\\<^sub>2\")\n  axiomatization where fUndefIndividual2Axiom: \"\\<^bold>\\<not>(E i\\<^sub>2)\"\n\n  lemma \"x \\<^bold>= x\" unfolding Defs by auto (* properly valid *)\n  lemma \"i\\<^sub>1 \\<^bold>= i\\<^sub>1\" unfolding Defs by auto (* properly valid *)\n\n\n  lemma test_True: \"True\" by simp\n  lemma test_False: \"False\" nitpick [satisfy, user_axioms=true] oops \n\n\ntext \\<open> Prior's Theorem \\<close>\n\n  lemma \"(Q (\\<forall>p. (Q p \\<longrightarrow> (\\<not>p)))) \\<longrightarrow> ((\\<exists>p. Q p \\<and> p) \\<and> (\\<exists>p. Q p \\<and> (\\<not>p)))\" by blast\n\n  lemma \"(Q (\\<^bold>\\<forall>p. (Q p \\<^bold>\\<rightarrow> (\\<^bold>\\<not>p)))) \\<^bold>\\<rightarrow> ((\\<^bold>\\<exists>p. Q p \\<^bold>\\<and> p) \\<^bold>\\<and> (\\<^bold>\\<exists>p. Q p \\<^bold>\\<and> (\\<^bold>\\<not>p)))\" \n    nitpick [user_axioms=true, show_all, format=2] oops\n\n  axiomatization where fTrueAxiom: \"E True\"\n  axiomatization where fFalseAxiom: \"E False\"\n\n  lemma \"(Q (\\<^bold>\\<forall>p. (Q p \\<^bold>\\<rightarrow> (\\<^bold>\\<not>p)))) \\<^bold>\\<rightarrow> ((\\<^bold>\\<exists>p. Q p \\<^bold>\\<and> p) \\<^bold>\\<and> (\\<^bold>\\<exists>p. Q p \\<^bold>\\<and> (\\<^bold>\\<not>p)))\" \n    unfolding Defs \n    by (smt fFalseAxiom fTrueAxiom) \n", "meta": {"author": "stilleben", "repo": "Free-Higher-Order-Logic", "sha": "a9c41094db3dccfc6bcdc5f93298936119ff2d90", "save_path": "github-repos/isabelle/stilleben-Free-Higher-Order-Logic", "path": "github-repos/isabelle/stilleben-Free-Higher-Order-Logic/Free-Higher-Order-Logic-a9c41094db3dccfc6bcdc5f93298936119ff2d90/encodings/PFHOL_pol.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9032941962904956, "lm_q2_score": 0.7826624789529375, "lm_q1q2_score": 0.7069744748925206}}
{"text": "(*  Title:       Examples of hybrid systems verifications\n    Author:      Jonathan Juli\u00e1n Huerta y Munive, 2020\n    Maintainer:  Jonathan Juli\u00e1n 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    \"Hybrid-Verification.Real_Arith_Tactics\"\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_inv_rules vderiv_intros)\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!: vderiv_intros)\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_inv (\\<lambda>s. UNIV) S G (\\<lambda>t. f g) t\\<^sub>0 (\\<lambda>s. 2 * g * s$1 - 2 * g * h - s$2 * s$2 = 0)\"\n  by (auto intro!: vderiv_intros diff_inv_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!: vderiv_intros diff_inv_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\" \n    by auto\n  hence \"g * (g * \\<tau>\\<^sup>2  + 2 * v * \\<tau> + 2 * x) = 0\"\n    by auto\n  then have \"g\\<^sup>2 * \\<tau>\\<^sup>2  + 2 * g * v * \\<tau> + 2 * g * x = 0\"\n    apply -\n    by distribute (mon_simp_vars g x)\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    by bin_unfold\n      (metis (no_types, opaque_lifting) add.commute add.left_commute mult.assoc mult.commute)\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!: vderiv_intros)\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!: vderiv_intros 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!: vderiv_intros 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\nsubsubsection \\<open> Dynamics: Darboux equality \\<close>\n\nlemma mult_abs_right_mono: \"a < b \\<Longrightarrow> a * \\<bar>c\\<bar> \\<le> b * \\<bar>c\\<bar>\" for c::real\n  by (simp add: mult_right_mono)\n\nlemma local_lipschitz_first_order_linear:\n  fixes c::\"real \\<Rightarrow> real\"\n  assumes \"continuous_on T c\"\n  shows \"local_lipschitz T UNIV (\\<lambda>t. (*) (c t))\"\nproof(unfold local_lipschitz_def lipschitz_on_def, clarsimp simp: dist_norm)\n  fix x t::real assume \"t \\<in> T\"\n  then obtain \\<delta> where d_hyp: \"\\<delta> > 0 \\<and> (\\<forall>\\<tau>\\<in>T. \\<bar>\\<tau> - t\\<bar> < \\<delta> \\<longrightarrow> \\<bar>c \\<tau> - c t\\<bar> < max 1 \\<bar>c t\\<bar>)\"\n    using assms unfolding continuous_on_iff \n    apply(erule_tac x=t in ballE, erule_tac x=\"max 1 (\\<bar>c t\\<bar>)\" in allE; clarsimp)\n    by (metis dist_norm less_max_iff_disj real_norm_def zero_less_one)\n  {fix \\<tau> x\\<^sub>1 x\\<^sub>2 \n    assume \"\\<tau> \\<in> cball t (\\<delta>/2) \\<inter> T\" \"x\\<^sub>1 \\<in> cball x (\\<delta>/2)\" \"x\\<^sub>2 \\<in> cball x (\\<delta>/2)\" \n    hence \"\\<bar>\\<tau> - t\\<bar> < \\<delta>\" \"\\<tau> \\<in> T\"\n      by (auto simp: dist_norm, smt d_hyp)\n    hence \"\\<bar>c \\<tau> - c t\\<bar> < max 1 \\<bar>c t\\<bar>\"\n      using d_hyp by auto\n    hence \"- (max 1 \\<bar>c t\\<bar> + \\<bar>c t\\<bar>) < c \\<tau> \\<and> c \\<tau> < max 1 \\<bar>c t\\<bar> + \\<bar>c t\\<bar>\"\n      by (auto simp: abs_le_eq)\n    hence obs: \"\\<bar>c \\<tau>\\<bar> < max 1 \\<bar>c t\\<bar> + \\<bar>c t\\<bar>\"\n      by (simp add: abs_le_eq)\n    have \"\\<bar>c \\<tau> * x\\<^sub>1 - c \\<tau> * x\\<^sub>2\\<bar> = \\<bar>c \\<tau>\\<bar> * \\<bar>x\\<^sub>1 - x\\<^sub>2\\<bar>\"\n      by (metis abs_mult left_diff_distrib mult.commute)\n    also have \"... \\<le> (max 1 \\<bar>c t\\<bar> + \\<bar>c t\\<bar>) * \\<bar>x\\<^sub>1 - x\\<^sub>2\\<bar>\"\n      using mult_abs_right_mono[OF obs] by blast\n    finally have \"\\<bar>c \\<tau> * x\\<^sub>1 - c \\<tau> * x\\<^sub>2\\<bar> \\<le> (max 1 \\<bar>c t\\<bar> + \\<bar>c t\\<bar>) * \\<bar>x\\<^sub>1 - x\\<^sub>2\\<bar>\" .}\n  hence \"\\<exists>L. \\<forall>t\\<in>cball t (\\<delta>/2) \\<inter> T. 0 \\<le> L \\<and>\n    (\\<forall>x\\<^sub>1\\<in>cball x (\\<delta>/2). \\<forall>x\\<^sub>2\\<in>cball x (\\<delta>/2). \\<bar>c t * x\\<^sub>1 - c t * x\\<^sub>2\\<bar> \\<le> L * \\<bar>x\\<^sub>1 - x\\<^sub>2\\<bar>)\"\n    by (rule_tac x=\"max 1 \\<bar>c t\\<bar> + \\<bar>c t\\<bar>\" in exI, clarsimp simp: dist_norm)\n  thus \"\\<exists>u>0. \\<exists>L. \\<forall>t\\<in>cball t u \\<inter> T. 0 \\<le> L \\<and> \n    (\\<forall>xa\\<in>cball x u. \\<forall>y\\<in>cball x u. \\<bar>c t * xa - c t * y\\<bar> \\<le> L * \\<bar>xa - y\\<bar>)\"\n    apply(rule_tac x=\"\\<delta>/2\" in exI) \n    using d_hyp by auto\nqed\n\nlemma picard_lindeloef_first_order_linear: \"t\\<^sub>0 \\<in> T \\<Longrightarrow> open T \\<Longrightarrow> is_interval T \\<Longrightarrow> \n  continuous_on T c \\<Longrightarrow> picard_lindeloef (\\<lambda>t x::real. c t * x) T UNIV t\\<^sub>0\"\n  apply(unfold_locales; clarsimp?)\n   apply(intro continuous_intros, assumption)\n  by (rule local_lipschitz_first_order_linear)\n\n(* x+z=0 -> [{x'=(A*x^2+B()*x), z' = A*z*x+B()*z}] 0=-x-z *)\nlemma \"(\\<lambda>s::real^2. s$1 + s$2 = 0) \\<le> \n  |x\\<acute>= (\\<lambda>t s. (\\<chi> i. if i=1 then A*(s$1)^2+B*(s$1) else A*(s$2)*(s$1)+B*(s$2))) & G on (\\<lambda>s. UNIV) UNIV @ 0]\n  (\\<lambda>s. 0 = - s$1 - s$2)\"\nproof-\n  have key: \"diff_inv (\\<lambda>s. UNIV) UNIV G \n  (\\<lambda>t s. \\<chi> i. if i = 1 then A*(s$1)^2+B*(s$1) else A*(s$2)*(s$1)+B*(s$2)) 0 (\\<lambda>s. s$1 + s$2 = 0)\"\n  proof(clarsimp simp: diff_inv_eq ivp_sols_def forall_2)\n    fix X::\"real\\<Rightarrow>real^2\" and t::real\n    let \"?c\" = \"(\\<lambda>t.  X t$1 + X t$2)\"\n    assume init: \"?c 0 = 0\"\n      and D1: \"D (\\<lambda>t. X t$1) = (\\<lambda>t. A * (X t$1)\\<^sup>2 + B * X t$1) on UNIV\"\n      and D2: \"D (\\<lambda>t. X t$2) = (\\<lambda>t. A * X t$2 * X t$1 + B * X t$2) on UNIV\"\n    hence \"D ?c = (\\<lambda>t. ?c t * (A * (X t$1) + B)) on UNIV\"\n      by (auto intro!: vderiv_intros simp: field_simps)\n    hence \"D ?c = (\\<lambda>t. (A * X t$1 + B) * (X t$1 + X t$2)) on {0--t}\"\n      using has_vderiv_on_subset[OF _ subset_UNIV[of \"{0--t}\"]] by (simp add: mult.commute)\n    moreover have \"continuous_on UNIV (\\<lambda>t. A * (X t$1) + B)\"\n      apply(rule vderiv_on_continuous_on)\n      using D1 by (auto intro!: vderiv_intros simp: field_simps)\n    moreover have \"D (\\<lambda>t. 0) = (\\<lambda>t. (A * X t$1 + B) * 0) on {0--t}\"\n      by (auto intro!: vderiv_intros)\n    moreover note picard_lindeloef.ivp_unique_solution[OF \n      picard_lindeloef_first_order_linear[OF UNIV_I open_UNIV is_interval_univ calculation(2)] \n      UNIV_I is_interval_closed_segment_1 subset_UNIV _ \n      ivp_solsI[of ?c]\n      ivp_solsI[of \"\\<lambda>t. 0\"], of t \"\\<lambda>s. 0\" 0 \"\\<lambda>s. t\" 0]\n    ultimately show \"X t$1 + X t$2 = 0\"\n      using init by auto\n  qed\n  show ?thesis\n    apply(subgoal_tac \"(\\<lambda>s. 0 = - s$1 - s$2) = (\\<lambda>s. s$1 + s$2 = 0)\", erule ssubst)\n    using key by auto\nqed\n\n\nsubsubsection \\<open> Dynamics: Fractional Darboux equality \\<close> (*N 30 *)\n\n(* x+z=0 -> [{x'=(A*y+B()*x)/z^2, z' = (A*x+B())/z & y = x^2 & z^2 > 0}] x+z=0 *)\n(* requires picard-lindeloef for closed intervals *)\n\nsubsubsection \\<open> Dynamics: Darboux inequality \\<close> (*N 31 *)\n\nabbreviation darboux_ineq_f :: \"real^2 \\<Rightarrow> real^2\" (\"f\")\n  where \"f s \\<equiv> (\\<chi> i. if i=1 then (s$1)^2 else (s$2)*(s$1)+(s$1)^2)\"\n\nabbreviation darboux_ineq_flow2 :: \"real \\<Rightarrow> real^2 \\<Rightarrow> real^2\" (\"\\<phi>\")\n  where \"\\<phi> t s \\<equiv> (\\<chi> i. if i=1 then (s$1/(1 - t * s$1)) else\n      (s$2 - s$1 * ln(1 - t * s$1))/(1 - t * s$1))\"\n\nabbreviation darboux_ineq_df :: \"real \\<times> (real ^ 2) \\<Rightarrow> (real ^ 2) \\<Rightarrow>\\<^sub>L (real ^ 2)\" (\"df\")\n  where \"df p \\<equiv> (case p of (t,x) \\<Rightarrow> Blinfun (\\<lambda>s. (\\<chi> i::2. if i=1 then 2 * (s$1) * (x$1) else \n  x$2 * s$1 + s$2 * x$1 + 2 * s$1 * x$1)))\"\n\nthm c1_implies_local_lipschitz c1_local_lipschitz\n\n\nlemma picard_lindeloef_darboux_ineq: \"picard_lindeloef (\\<lambda>t. f) UNIV {s. s$1 + s$2 > 0} 0\"\n  apply(unfold_locales, simp_all)\n  prefer 2\n   apply(rule_tac f'=df in c1_implies_local_lipschitz)\n      apply (clarsimp simp: has_derivative_coordinate)\n  subgoal for s i\n    apply(cases \"i = 1\")\n     apply clarsimp\n     apply(subst Blinfun_inverse, clarsimp)\n      apply(subst bounded_linear_coordinate, clarsimp)\n    subgoal for j\n    using exhaust_2[of j] by (auto intro!: bounded_linear_intros)\n      apply(auto intro!: derivative_eq_intros)[1]\n  apply(subst Blinfun_inverse, clarsimp)\n   apply(subst bounded_linear_coordinate)\n   apply (clarsimp simp: has_derivative_coordinate)\n subgoal for j\n    using exhaust_2[of j] by (auto intro!: bounded_linear_intros)\n  by (auto intro!: derivative_eq_intros)[1]\n  apply (auto intro!: continuous_intros)\n  sorry\n\nlemma darboux_flow_ivp: \"(\\<lambda>t. \\<phi> t s) \\<in> Sols (\\<lambda>s. {t. 0 \\<le> t \\<and> t * s$1 < 1}) UNIV (\\<lambda>t. f) 0 s\"\n  by (rule ivp_solsI) (auto intro!: vderiv_intros \n      simp: forall_2 power2_eq_square add_divide_distrib power_divide vec_eq_iff)\n\nlemma darboux_ineq_arith:\n  assumes \"0 \\<le> s\\<^sub>1 + s\\<^sub>2\" and \"0 \\<le> (t::real)\" and \"t * s\\<^sub>1 < 1\"\n  shows \"0 \\<le> s\\<^sub>1 / (1 - t * s\\<^sub>1) + (s\\<^sub>2 - s\\<^sub>1 * ln (1 - t * s\\<^sub>1)) / (1 - t * s\\<^sub>1)\"\nproof-\n  have \"s\\<^sub>1 * ln (1 - t * s\\<^sub>1) \\<le> 0\"\n  proof(cases \"s\\<^sub>1 \\<le> 0\")\n    case True\n    hence \"1 - t * s\\<^sub>1 \\<ge> 1\"\n      using \\<open>0 \\<le> t\\<close> by (simp add: mult_le_0_iff)\n    thus ?thesis\n      using True ln_ge_zero mult_nonneg_nonpos2 by blast\n  next\n    case False\n    hence \"1 - t * s\\<^sub>1 \\<le> 1\"\n      using \\<open>0 \\<le> t\\<close> by auto\n    thus ?thesis\n      by (metis False add_0 assms(3) less_diff_eq ln_le_zero_iff mult_le_0_iff nle_le)\n  qed\n  hence \"s\\<^sub>1 + s\\<^sub>2 - s\\<^sub>1 * ln (1 - t * s\\<^sub>1) \\<ge> s\\<^sub>1 + s\\<^sub>2\"\n    by linarith\n  hence \"(s\\<^sub>1 + s\\<^sub>2 - s\\<^sub>1 * ln (1 - t * s\\<^sub>1))/(1 - t * s\\<^sub>1) \\<ge> (s\\<^sub>1 + s\\<^sub>2)/(1 - t * s\\<^sub>1)\"\n    using \\<open>t * s\\<^sub>1 < 1\\<close> by (simp add: \\<open>0 \\<le> s\\<^sub>1 + s\\<^sub>2\\<close> divide_le_cancel)\n  also have \"(s\\<^sub>1 + s\\<^sub>2)/(1 - t * s\\<^sub>1) \\<ge> 0\"\n    using \\<open>t * s\\<^sub>1 < 1\\<close> by (simp add: \\<open>0 \\<le> s\\<^sub>1 + s\\<^sub>2\\<close>)\n  ultimately show ?thesis\n    by (metis (full_types) add_diff_eq add_divide_distrib order_trans)\nqed\n\n(* x+z>=0 -> [{x'=x^2, z' = z*x+y & y = x^2}] x+z>=0 *)\n(* x' + z' \\<ge> 0 \\<longleftrightarrow> x^2 + z*x + x^2 \\<ge> 0*)\nlemma \"(\\<lambda>s::real^2. s$1 + s$2 \\<ge> 0) \\<le> \n  |EVOL \\<phi> (\\<lambda>s. y = (s$1)^2) (\\<lambda>s. {t. 0 \\<le> t \\<and> t * s$1 < 1})]\n  (\\<lambda>s. s$1 + s$2 \\<ge> 0)\"\n  apply(subst fbox_g_evol, simp_all add: le_fun_def)\n  using darboux_ineq_arith by smt\n\nno_notation darboux_ineq_flow2 (\"\\<phi>\")\n        and darboux_ineq_f (\"f\")\n\nsubsection \\<open> Dynamics: Fractional Darboux equality \\<close>\n\n(* x+z=0 -> [{x'=(A*y+B()*x)/z^2, z' = (A*x+B())/z & y = x^2 & z^2 > 0}] x+z=0 *)\n(* x' + z' = (A*y+B*x)/z^2 + (A*x+B)/z = (A*y+B*x+A*x*z+B*z)/z^2 = (x*(A*x+B)+z*(A*x+B))/z^2 *)\nlemma \"0 \\<le> t \\<Longrightarrow> (\\<lambda>s::real^3. s$1 + s$3 = 0) \\<le>\n  |x\\<acute>= (\\<lambda> s. (\\<chi> i::3. if i=1 then (A*(s$2)+B*(s$1))/(s$3)\\<^sup>2 else (if i = 3 then (A*(s$1)+B)/s$3 else 0))) & (\\<lambda>s. (s$2) = (s$1)^2 \\<and> (s$3)^2 > 0)] \n  (\\<lambda>s. s$1 + s$3 = 0)\"\nproof-\n  have \"diff_inv (\\<lambda>s. Collect ((\\<le>) 0)) UNIV (\\<lambda>s. s$2 = (s$1)\\<^sup>2 \\<and> s$3 \\<noteq> 0) \n  (\\<lambda>t s. \\<chi> i::3. if i = 1 then (A*(s$2)+B*(s$1))/(s$3)\\<^sup>2 else if i = 3 then (A*(s$1)+B)/s$3 else 0) \n  0 (\\<lambda>s::real^3. s$1 + s$3 = 0)\"\n  proof(clarsimp simp: diff_inv_eq ivp_sols_def forall_3)\n    fix X::\"real\\<Rightarrow>real^3\" and t::real\n    let \"?c\" = \"(\\<lambda>t.  X t$1 + X t$3)\"\n    assume init: \"?c 0 = 0\" and \"t \\<ge> 0\"\n      and guard: \"\\<forall>\\<tau>. 0 \\<le> \\<tau> \\<and> \\<tau> \\<le> t \\<longrightarrow> X \\<tau>$2 = (X \\<tau>$1)\\<^sup>2 \\<and> X \\<tau>$3 \\<noteq> 0\"\n      and D1: \"D (\\<lambda>t. X t$1) = (\\<lambda>t. (A * (X t$2) + B * X t$1)/(X t$3)\\<^sup>2) on Collect ((\\<le>) 0)\"\n      and D2: \"D (\\<lambda>t. X t$2) = (\\<lambda>t. 0) on Collect ((\\<le>) 0)\"\n      and D3: \"D (\\<lambda>t. X t$3) = (\\<lambda>t. (A * X t$1 + B)/(X t$3)) on Collect ((\\<le>) 0)\"\n    have \"D ?c = (\\<lambda>t. (A * (X t$2) + B * X t$1)/(X t$3)\\<^sup>2 + (A * X t$1 + B)/(X t$3)) on {0--t}\"\n      apply(rule_tac S=\"Collect ((\\<le>) 0)\" in has_vderiv_on_subset)\n      using \\<open>t \\<ge> 0\\<close> by (auto simp: closed_segment_eq_real_ivl intro!: vderiv_intros D1 D3)\n    hence \"D ?c = (\\<lambda>t. (A * X t$1 + B)/(X t$3)\\<^sup>2 * ?c t) on {0--t}\"\n      apply(rule has_vderiv_on_eq_rhs)\n      using guard \\<open>t \\<ge> 0\\<close>\n      using segment_open_subset_closed\n      by (auto simp: field_simps closed_segment_eq_real_ivl)\n    moreover have \"continuous_on {0--t} (\\<lambda>t. (A * X t$1 + B)/(X t$3)\\<^sup>2)\"\n      apply(rule vderiv_on_continuous_on)\n      apply(rule vderiv_intros)\n      using guard segment_open_subset_closed \\<open>t \\<ge> 0\\<close> apply (force simp: closed_segment_eq_real_ivl)\n        apply(intro vderiv_intros, rule vderiv_intros)\n      apply(rule has_vderiv_on_subset[OF D1])\n      using \\<open>t \\<ge> 0\\<close> apply(simp add: closed_segment_eq_real_ivl subset_eq, force)\n         apply(rule vderiv_intros, force)\n      apply(rule vderiv_intros,simp)\n      apply(rule has_vderiv_on_subset[OF D3])\n      using \\<open>t \\<ge> 0\\<close> by (simp_all add: closed_segment_eq_real_ivl subset_eq)\n    moreover have \"D (\\<lambda>t. 0) = (\\<lambda>t. (A * X t$1 + B)/(X t$3)\\<^sup>2 * 0) on {0--t}\"\n      by (auto intro!: vderiv_intros)   \n    (*moreover note picard_lindeloef.unique_solution_general[OF \n        picard_lindeloef_first_order_linear[OF _ _ _ calculation(2)] _ _ _ _ _ this _ _ calculation(1)]\n   *)\n    thm picard_lindeloef.unique_solution_closed_ivl\n    thm picard_lindeloef.unique_solution[of \"(\\<lambda>t. (*) ((A * X t$1 + B) / (X t$3)\\<^sup>2))\" _ _ 0]\n    thm picard_lindeloef_first_order_linear[OF _ _ _ calculation(2)]\n    moreover note picard_lindeloef.unique_solution_closed_ivl[OF \n        picard_lindeloef_first_order_linear[OF _ _ _ calculation(2)] this _ _ _ calculation(1)]\n    ultimately show \"X t$1 + X t$3 = 0\"\n      using init by auto\n        (* continuous because of guard need to change assumptions of picard_lindeloef *)\n        (* correct interval of existence or differentiabe \\<Longrightarrow> lipschitz *)\n  qed\n  thus ?thesis\n    by auto\nqed\n\nsubsection \\<open> STTT Tutorial: Example 9b \\<close>\n\nabbreviation f9 :: \"real ^ 3 \\<Rightarrow> real ^ 3\" \n  where \"f9 \\<equiv> (\\<lambda>s. \\<chi> i. if i = 1 then s $ 2 else if i = 2 then - 2 * (s $ 1 - s $ 3) - 3 * s $ 2 else 0)\"\n\n(* { x' = v, v' = -Kp*(x-xr) - Kd*v & v >= 0 } *)\nterm \"(\\<lambda>(t::real) (s::real^3). \\<chi> i::3. if i = 1 then s $ 2 else if i = 2 then - 2 * (s $ 1 - s $ 3) - 3 * s $ 2 else 0)\"\nlemma \"local_lipschitz UNIV UNIV (\\<lambda>(t::real). f9)\"\n  apply(rule_tac \\<DD>=f9 in c1_local_lipschitz; clarsimp?)\n  apply (clarsimp simp: has_derivative_coordinate)\n  subgoal for s i\n    using exhaust_3[of i]\n    by (auto intro!: derivative_eq_intros)\n  apply(rule_tac f'=\"\\<lambda>t. f9\" in has_derivative_continuous_on, clarsimp)\n  apply (clarsimp simp: has_derivative_coordinate)\n  subgoal for s i\n    using exhaust_3[of i]\n    by (auto intro!: derivative_eq_intros)\n  done\n\nend", "meta": {"author": "isabelle-utp", "repo": "Hybrid-Verification", "sha": "ccc5876d270a436a3c4be8c44932256e5d291cf3", "save_path": "github-repos/isabelle/isabelle-utp-Hybrid-Verification", "path": "github-repos/isabelle/isabelle-utp-Hybrid-Verification/Hybrid-Verification-ccc5876d270a436a3c4be8c44932256e5d291cf3/Legacy/HS_VC_Examples.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8397339797047029, "lm_q2_score": 0.8418256551882382, "lm_q1q2_score": 0.7069096076487382}}
{"text": "(*  Title:      HOL/Quickcheck_Examples/Quickcheck_Lattice_Examples.thy\n    Author:     Lukas Bulwahn\n    Copyright   2010 TU Muenchen\n*)\n\ntheory Quickcheck_Lattice_Examples\nimports Main\nbegin\n\ndeclare [[quickcheck_finite_type_size=5]]\n\ntext \\<open>We show how other default types help to find counterexamples to propositions if\n  the standard default type \\<^typ>\\<open>int\\<close> is insufficient.\\<close>\n\nnotation\n  less_eq  (infix \"\\<sqsubseteq>\" 50) and\n  less  (infix \"\\<sqsubset>\" 50) and\n  top (\"\\<top>\") and\n  bot (\"\\<bottom>\") and\n  inf (infixl \"\\<sqinter>\" 70) and\n  sup (infixl \"\\<squnion>\" 65)\n\ndeclare [[quickcheck_narrowing_active = false, quickcheck_timeout = 3600]]\n\nsubsection \\<open>Distributive lattices\\<close>\n\nlemma sup_inf_distrib2:\n \"((y :: 'a :: distrib_lattice) \\<sqinter> z) \\<squnion> x = (y \\<squnion> x) \\<sqinter> (z \\<squnion> x)\"\n  quickcheck[expect = no_counterexample]\nby(simp add: inf_sup_aci sup_inf_distrib1)\n\nlemma sup_inf_distrib2_1:\n \"((y :: 'a :: lattice) \\<sqinter> z) \\<squnion> x = (y \\<squnion> x) \\<sqinter> (z \\<squnion> x)\"\n  quickcheck[expect = counterexample]\n  oops\n\nlemma sup_inf_distrib2_2:\n \"((y :: 'a :: distrib_lattice) \\<sqinter> z') \\<squnion> x = (y \\<squnion> x) \\<sqinter> (z \\<squnion> x)\"\n  quickcheck[expect = counterexample]\n  oops\n\nlemma inf_sup_distrib1_1:\n \"(x :: 'a :: distrib_lattice) \\<sqinter> (y \\<squnion> z) = (x \\<sqinter> y) \\<squnion> (x' \\<sqinter> z)\"\n  quickcheck[expect = counterexample]\n  oops\n\nlemma inf_sup_distrib2_1:\n \"((y :: 'a :: distrib_lattice) \\<squnion> z) \\<sqinter> x = (y \\<sqinter> x) \\<squnion> (y \\<sqinter> x)\"\n  quickcheck[expect = counterexample]\n  oops\n\nsubsection \\<open>Bounded lattices\\<close>\n\nlemma inf_bot_left [simp]:\n  \"\\<bottom> \\<sqinter> (x :: 'a :: bounded_lattice_bot) = \\<bottom>\"\n  quickcheck[expect = no_counterexample]\n  by (rule inf_absorb1) simp\n\nlemma inf_bot_left_1:\n  \"\\<bottom> \\<sqinter> (x :: 'a :: bounded_lattice_bot) = x\"\n  quickcheck[expect = counterexample]\n  oops\n\nlemma inf_bot_left_2:\n  \"y \\<sqinter> (x :: 'a :: bounded_lattice_bot) = \\<bottom>\"\n  quickcheck[expect = counterexample]\n  oops\n\nlemma inf_bot_left_3:\n  \"x \\<noteq> \\<bottom> ==> y \\<sqinter> (x :: 'a :: bounded_lattice_bot) \\<noteq> \\<bottom>\"\n  quickcheck[expect = counterexample]\n  oops\n\nlemma inf_bot_right [simp]:\n  \"(x :: 'a :: bounded_lattice_bot) \\<sqinter> \\<bottom> = \\<bottom>\"\n  quickcheck[expect = no_counterexample]\n  by (rule inf_absorb2) simp\n\nlemma inf_bot_right_1:\n  \"x \\<noteq> \\<bottom> ==> (x :: 'a :: bounded_lattice_bot) \\<sqinter> \\<bottom> = y\"\n  quickcheck[expect = counterexample]\n  oops\n\nlemma inf_bot_right_2:\n  \"(x :: 'a :: bounded_lattice_bot) \\<sqinter> \\<bottom> ~= \\<bottom>\"\n  quickcheck[expect = counterexample]\n  oops\n\nlemma sup_bot_right [simp]:\n  \"(x :: 'a :: bounded_lattice_bot) \\<squnion> \\<bottom> = \\<bottom>\"\n  quickcheck[expect = counterexample]\n  oops\n\nlemma sup_bot_left [simp]:\n  \"\\<bottom> \\<squnion> (x :: 'a :: bounded_lattice_bot) = x\"\n  quickcheck[expect = no_counterexample]\n  by (rule sup_absorb2) simp\n\nlemma sup_bot_right_2 [simp]:\n  \"(x :: 'a :: bounded_lattice_bot) \\<squnion> \\<bottom> = x\"\n  quickcheck[expect = no_counterexample]\n  by (rule sup_absorb1) simp\n\nlemma sup_eq_bot_iff [simp]:\n  \"(x :: 'a :: bounded_lattice_bot) \\<squnion> y = \\<bottom> \\<longleftrightarrow> x = \\<bottom> \\<and> y = \\<bottom>\"\n  quickcheck[expect = no_counterexample]\n  by (simp add: eq_iff)\n\nlemma sup_top_left [simp]:\n  \"\\<top> \\<squnion> (x :: 'a :: bounded_lattice_top) = \\<top>\"\n  quickcheck[expect = no_counterexample]\n  by (rule sup_absorb1) simp\n\nlemma sup_top_right [simp]:\n  \"(x :: 'a :: bounded_lattice_top) \\<squnion> \\<top> = \\<top>\"\n  quickcheck[expect = no_counterexample]\n  by (rule sup_absorb2) simp\n\nlemma inf_top_left [simp]:\n  \"\\<top> \\<sqinter> x = (x :: 'a :: bounded_lattice_top)\"\n  quickcheck[expect = no_counterexample]\n  by (rule inf_absorb2) simp\n\nlemma inf_top_right [simp]:\n  \"x \\<sqinter> \\<top> = (x :: 'a :: bounded_lattice_top)\"\n  quickcheck[expect = no_counterexample]\n  by (rule inf_absorb1) simp\n\nlemma inf_eq_top_iff [simp]:\n  \"(x :: 'a :: bounded_lattice_top) \\<sqinter> y = \\<top> \\<longleftrightarrow> x = \\<top> \\<and> y = \\<top>\"\n  quickcheck[expect = no_counterexample]\n  by (simp add: eq_iff)\n\n\nno_notation\n  less_eq  (infix \"\\<sqsubseteq>\" 50) and\n  less (infix \"\\<sqsubset>\" 50) and\n  inf  (infixl \"\\<sqinter>\" 70) and\n  sup  (infixl \"\\<squnion>\" 65) and\n  top (\"\\<top>\") and\n  bot (\"\\<bottom>\")\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/Quickcheck_Examples/Quickcheck_Lattice_Examples.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8397339756938818, "lm_q2_score": 0.8418256512199033, "lm_q1q2_score": 0.7069096009399805}}
{"text": "(* Attempting to discover laws form Hinze's stream calculus using Hipster *)\ntheory \"Hinze_Streams\"\n  imports Main \"$HIPSTER_HOME/IsaHipster\"\n    \"~~/src/HOL/Library/BNF_Corec\"\nbegin\nsetup Tactic_Data.set_coinduct_sledgehammer \nsetup Misc_Data.set_noisy\nsetup Misc_Data.set_time\n\ncodatatype (sset: 'a) Stream =\n  SCons (shd: 'a) (stl: \"'a Stream\")\n\ndatatype ('a, 'b) Twople = Pair2 (fst2: 'a) (snd2: 'b)\n\nprimcorec smap :: \"('a \\<Rightarrow> 'b) \\<Rightarrow> 'a Stream \\<Rightarrow> 'b Stream\" where\n  \"smap f xs = SCons (f (shd xs)) (smap f (stl xs))\"\n\n(* Lifting *)\nprimcorec spure :: \"'a \\<Rightarrow> 'a Stream\" where  \n  \"shd (spure x) = x\"\n| \"stl (spure x) = spure x\"\n\n(* Sequential application *)\nprimcorec sapp :: \" ('a \\<Rightarrow> 'b) Stream \\<Rightarrow> 'a Stream \\<Rightarrow> 'b Stream\" where\n  \"shd (sapp fs xs) = (shd fs) (shd xs)\"\n| \"stl (sapp fs xs) = sapp (stl fs) (stl xs)\"\n\nprimcorec szip :: \"'a Stream \\<Rightarrow> 'b Stream \\<Rightarrow> (('a, 'b) Twople) Stream\" where\n  \"shd (szip s1 s2) = Pair2 (shd s1) (shd s2)\"\n| \"stl (szip s1 s2) = szip (stl s1) (stl s2)\"\n\n(* Map *)\nprimcorec smap2 :: \"('a \\<Rightarrow> 'b) \\<Rightarrow> 'a Stream \\<Rightarrow> 'b Stream\" where\n  \"smap2 f xs = sapp (spure f) xs\"\n\n(* Interleaving *)\nprimcorec sinterleave :: \"'a Stream \\<Rightarrow> 'a Stream \\<Rightarrow> 'a Stream\" where\n  \"sinterleave s t = SCons (shd s) (sinterleave t (stl s))\"\n\n(* Tabulate and lookup *)\ndatatype MyNat = MyZero | MySuc MyNat\n\nprimcorec stabulate :: \"(MyNat \\<Rightarrow> 'a) \\<Rightarrow> 'a Stream\" where\n  \"stabulate f = SCons (f MyZero) (stabulate (f \\<circ> (\\<lambda>x. MySuc x)))\"\n\nfun slookup :: \"'a Stream \\<Rightarrow> (MyNat \\<Rightarrow> 'a)\" where\n  \"slookup s MyZero = shd s\" |\n  \"slookup s (MySuc n) = slookup (stl s) n\"\n\n(* Pairs of streams *)\nprimcorec szip2 :: \"('a \\<Rightarrow> 'b \\<Rightarrow> 'c) \\<Rightarrow> 'a Stream \\<Rightarrow> 'b Stream \\<Rightarrow> 'c Stream\" where\n  \"szip2 g s t = sapp (sapp (spure g) s) t\"\n\nprimcorec spair :: \"'a Stream => 'b Stream => ('a, 'b) Twople Stream\" where\n  \"spair xs ys = szip2 Pair2 xs ys\"\n\n(* Iterate *)\nprimcorec siterate :: \"('a \\<Rightarrow> 'a) \\<Rightarrow> 'a \\<Rightarrow> 'a Stream\" where\n  \"siterate f a = SCons a (siterate f (f a))\"\n\n(* Recurse *)\nprimcorec monomap :: \"('a \\<Rightarrow> 'a) \\<Rightarrow> 'a Stream \\<Rightarrow> 'a Stream\" where\n  \"monomap f xs = SCons (f (shd xs)) (monomap f (stl xs))\"\n\nfriend_of_corec monomap where\n   \"monomap f xs = SCons (f (shd xs)) (monomap f (stl xs))\"\n  by (auto intro: monomap.code)\n\ncorec srecurse :: \"('a \\<Rightarrow> 'a) \\<Rightarrow> 'a \\<Rightarrow> 'a Stream\" where\n  \"srecurse f a = SCons a (monomap f (srecurse f a))\"\n\n(* Unfolding *)\nprimcorec sunfold :: \"('a \\<Rightarrow> 'b) \\<Rightarrow> ('a \\<Rightarrow> 'a) \\<Rightarrow> 'a \\<Rightarrow> 'b Stream\" where\n  \"sunfold g f a = SCons (g a) (sunfold g f (f a))\"\n\n(* Uncomment the following cohipster calls to explore this theory *)\n(* cohipster sapp spure Fun.id Fun.comp *)\n(* cohipster smap2 Fun.id Fun.comp *)\n(* cohipster spair smap2 fst2 snd2 *)\n(* cohipster sinterleave spure sapp *)\n(* cohipster stabulate smap2 Fun.comp *)\n(* cohipster slookup smap Fun.comp *)\n(* cohipster siterate srecurse *)\n(* cohipster sunfold Fun.comp smap *)\n(* cohipster sunfold shd stl Fun.id *)\n\n(* The output of the above cohipster calls follows below *)\n(* lemma_a is Hinze's property 1, lemma_aa is Hinze's property 3 *)\n(* cohipster sapp spure Fun.id Fun.comp *)\nlemma lemma_a [thy_expl]: \"sapp (spure id) y = y\"\nby(coinduction arbitrary: y rule: Stream.coinduct_strong)\n  simp\n\nlemma lemma_aa [thy_expl]: \"sapp (spure z) (spure x2) = spure (z x2)\"\nby(coinduction arbitrary: x2 z rule: Stream.coinduct_strong)\n  auto\n  \nlemma lemma_ab [thy_expl]: \"SCons (y (shd z)) (stl z) = sapp (SCons y (spure id)) z\"\nby(coinduction arbitrary: y z rule: Stream.coinduct_strong)\n  (simp add: lemma_a)\n  \nlemma lemma_ac [thy_expl]: \"SCons (z x2) (sapp (spure z) x3) = sapp (spure z) (SCons x2 x3)\"\nby(coinduction arbitrary: x2 x3 z rule: Stream.coinduct_strong)\n  simp\n  \nlemma lemma_ad [thy_expl]: \"sapp (SCons z (spure x2)) (spure x3) = SCons (z x3) (spure (x2 x3))\"\nby(coinduction arbitrary: x2 x3 z rule: Stream.coinduct_strong)\n  (simp add: lemma_aa)\n  \nlemma lemma_ae [thy_expl]: \"sapp (spure x2) (SCons z (spure x3)) = SCons (x2 z) (spure (x2 x3))\"\nby(coinduction arbitrary: x2 x3 z rule: Stream.coinduct_strong)\n  (simp add: lemma_aa)\n  \nlemma lemma_af [thy_expl]: \"sapp (spure x2) (sapp (spure x3) x4) = sapp (spure (x2 \\<circ> x3)) x4\"\nby(coinduction arbitrary: x2 x3 x4 rule: Stream.coinduct_strong)\n  auto\n  \nlemma lemma_ag [thy_expl]: \"sapp (SCons y (spure id)) (spure z) = SCons (y z) (spure z)\"\nby(coinduction arbitrary: y z rule: Stream.coinduct_strong)\n  (metis lemma_ab spure.simps(1) spure.simps(2))\n  \nlemma lemma_ah [thy_expl]: \"sapp (SCons id (spure y)) (spure z) = SCons z (spure (y z))\"\nby(coinduction arbitrary: y z rule: Stream.coinduct_strong)\n  (simp add: Hinze_Streams.lemma_aa)\n\n(* cohipster smap2 Fun.id Fun.comp *)\n(* lemma_ai is Hinze's property 5, lemma_aj is Hinze's property 6 *)\nlemma lemma_ai [thy_expl]: \"smap2 id y = y\"\n  by(coinduction arbitrary: y rule: Stream.coinduct_strong)\n  (simp add: smap2.code)\n  \nlemma lemma_aj [thy_expl]: \"smap2 z (spure x2) = spure (z x2)\"\n  by(coinduction arbitrary: x2 z rule: Stream.coinduct_strong)\n  (simp add: lemma_aa)\n  \nlemma lemma_ak [thy_expl]: \"stl (smap2 z x2) = smap2 z (stl x2)\"\nby(coinduction arbitrary: x2 z rule: Stream.coinduct_strong)\nsimp\n\nlemma lemma_al [thy_expl]: \"smap2 (x2 \\<circ> x3) x4 = smap2 x2 (smap2 x3 x4)\"\nby(coinduction arbitrary: x2 x3 x4 rule: Stream.coinduct_strong)\n(simp add: lemma_af)\n\nlemma lemma_am [thy_expl]: \"SCons (z x2) (smap2 z x3) = smap2 z (SCons x2 x3)\"\n  by(coinduction arbitrary: x2 x3 z rule: Stream.coinduct_strong)\n(simp add: smap2.code)\n\nlemma lemma_an [thy_expl]: \"SCons (shd z) (smap2 y (stl z)) = sapp (SCons id (spure y)) z\"\n  by(coinduction arbitrary: y z rule: Stream.coinduct_strong)\n    (simp add: smap2.code)\n\n(* cohipster spair smap2 fst2 snd2 *)\n(* None of these are among Hinze's properties *)\nlemma lemma_ao [thy_expl]: \"sapp (smap2 x2 x3) x4 = szip2 x2 x3 x4\"\n  by(coinduction arbitrary: x2 x3 x4 rule: Stream.coinduct_strong)\n  simp\n  \nlemma lemma_ap [thy_expl]: \"spair (stl z) (stl x2) = stl (spair z x2)\"\n  by(coinduction arbitrary: x2 z rule: Stream.coinduct_strong)\n  simp\n  \nlemma lemma_aq [thy_expl]: \"stl (spair z (spure x2)) = spair (stl z) (spure x2)\"\nby(coinduction arbitrary: x2 z rule: Stream.coinduct_strong)\n  simp\n\nlemma lemma_ar [thy_expl]: \"stl (spair (spure z) x2) = spair (spure z) (stl x2)\"\nby(coinduction arbitrary: x2 z rule: Stream.coinduct_strong)\n  simp\n  \nlemma lemma_as [thy_expl]: \"stl (spair x2 (SCons z x3)) = spair (stl x2) x3\"\nby(coinduction arbitrary: x2 x3 z rule: Stream.coinduct_strong)\n  simp\n  \nlemma lemma_at [thy_expl]: \"stl (spair (SCons z x2) x3) = spair x2 (stl x3)\"\nby(coinduction arbitrary: x2 x3 z rule: Stream.coinduct_strong)\n  simp\n  \nlemma lemma_au [thy_expl]: \"spair (smap2 x2 (stl x3)) (stl x4) = stl (spair (smap2 x2 x3) x4)\"\nby(coinduction arbitrary: x2 x3 x4 rule: Stream.coinduct_strong)\n  simp\n  \nlemma lemma_av [thy_expl]: \"spair (stl x2) (smap2 x3 (stl x4)) = stl (spair x2 (smap2 x3 x4))\"\nby(coinduction arbitrary: x2 x3 x4 rule: Stream.coinduct_strong)\n  simp\n  \nlemma unknown [thy_expl]: \"spair (spure z) (spure x2) = spure (Pair2 z x2)\"\noops\n  \nlemma unknown [thy_expl]: \"spair (SCons z x3) (SCons x2 x4) = SCons (Pair2 z x2) (spair x3 x4)\"\n  oops\n\n(* cohipster sinterleave spure sapp *)\n(* lemma_ax is Hinze's property 10 *)\nlemma lemma_aw [thy_expl]: \"sinterleave (SCons y x2) z = SCons y (sinterleave z x2)\"\n  by(coinduction arbitrary: x2 y z rule: Stream.coinduct_strong)\n  simp\n  \nlemma lemma_ax [thy_expl]: \"sinterleave (spure y) (spure y) = spure y\"\n  by(coinduction arbitrary: y rule: Stream.coinduct_strong)\n  auto\n\nlemma lemma_ay [thy_expl]: \"SCons y (sinterleave z (spure y)) = sinterleave (spure y) z\"\n  by(coinduction arbitrary: y z rule: Stream.coinduct_strong)\nsimp\n\nlemma lemma_az [thy_expl]: \"sinterleave (spure z) (SCons y (spure z)) = SCons z (SCons y (spure z))\"\n  by(coinduction arbitrary: y z rule: Stream.coinduct_strong)\n    (simp add: lemma_aw lemma_ax)\n\n(* cohipster stabulate smap2 Fun.comp *)\n(* lemma_ba is Hinze's property 12 (commuted) *)\nlemma lemma_ba [thy_expl]: \"stabulate (z \\<circ> x2) = smap2 z (stabulate x2)\"\n  by(coinduction arbitrary: x2 z rule: Stream.coinduct_strong)\n    (metis (no_types, lifting) comp_apply comp_assoc lemma_ak sapp.simps(1) smap2.code spure.simps(1) stabulate.simps(1) stabulate.simps(2))\n\n(* cohipster slookup smap Fun.comp *)\n(* lemma_bb is Hinze's property 13 (commuted) *)\nlemma lemma_bb [thy_expl]: \"slookup (smap z x2) x3 = z (slookup x2 x3)\"\n  apply (induct x3 arbitrary: x2)\n  apply simp\n  apply simp\n  done\n  \nlemma lemma_bc [thy_expl]: \"smap (x2 \\<circ> x3) x4 = smap x2 (smap x3 x4)\"\n  by(coinduction arbitrary: x2 x3 x4 rule: Stream.coinduct_strong)\n    auto\n    \nlemma lemma_bd [thy_expl]: \"SCons (z x2) (smap z x3) = smap z (SCons x2 x3)\"\nby(coinduction arbitrary: x2 x3 z rule: Stream.coinduct_strong)\n  simp\n\n(* cohipster siterate srecurse *)\n(* lemma_bg is Hinze's property 14 *)\nlemma lemma_be [thy_expl]: \"monomap y (siterate y z) = siterate y (y z)\"\n  by(coinduction arbitrary: y z rule: Stream.coinduct_strong)\nauto\n\nlemma lemma_bf [thy_expl]: \"monomap z (SCons y (siterate z x2)) = SCons (z y) (siterate z (z x2))\"\n  by(coinduction rule: monomap.coinduct)\n(simp add: lemma_be srecurse.cong_refl)\n\nlemma lemma_bg [thy_expl]: \"srecurse y z = siterate y z\"\nby(coinduction rule: srecurse.coinduct)\n  (smt Stream.collapse Stream.inject lemma_be siterate.code srecurse.code srecurse.cong_base srecurse.cong_monomap)\n\n(* cohipster sunfold Fun.comp smap *)\n(* lemma_bi is Hinze's property 18 (commuted) *)\nlemma lemma_bh [thy_expl]: \"smap z (sunfold x2 x2 x3) = sunfold z x2 (x2 x3)\"\n  by(coinduction arbitrary: x2 x3 z rule: Stream.coinduct_strong)\n    auto\n\nlemma lemma_bi [thy_expl]: \"sunfold (x2 \\<circ> x3) x4 x5 = smap x2 (sunfold x3 x4 x5)\"\n  by(coinduction arbitrary: x2 x3 x4 x5 rule: Stream.coinduct_strong)\n    auto\n\n(* cohipster sunfold shd stl Fun.id *)\n(* None of these are among Hinze's laws *)\nlemma lemma_bj [thy_expl]: \"sunfold id y (y z) = sunfold y y z\"\nby(coinduction arbitrary: y z rule: Stream.coinduct_strong)\n  auto\n\nlemma lemma_bk [thy_expl]: \"sunfold id id (z x2) = sunfold z id x2\"\nby(coinduction arbitrary: x2 z rule: Stream.coinduct_strong)\n  auto\n  \nlemma lemma_bl [thy_expl]: \"SCons z (sunfold y y z) = sunfold id y z\"\nby(coinduction arbitrary: y z rule: Stream.coinduct_strong)\n  (simp add: lemma_bj)\n  \nlemma lemma_bm [thy_expl]: \"SCons (z x2) (sunfold z id x2) = sunfold z id x2\"\nby(coinduction arbitrary: x2 z rule: Stream.coinduct_strong)\n  simp\n\nend", "meta": {"author": "moajohansson", "repo": "IsaHipster", "sha": "91f6ea3f1166a9de547722ece6445fe843ad89b4", "save_path": "github-repos/isabelle/moajohansson-IsaHipster", "path": "github-repos/isabelle/moajohansson-IsaHipster/IsaHipster-91f6ea3f1166a9de547722ece6445fe843ad89b4/benchmark/AISC18/Hinze_Streams.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339676722392, "lm_q2_score": 0.8418256532040708, "lm_q1q2_score": 0.7069095958533288}}
{"text": "(*  Author:     Tobias Nipkow\n    Copyright   1994 TU Muenchen\n*)\n\nsection {* Quicksort with function package *}\n\ntheory Quicksort\nimports \"~~/src/HOL/Library/Multiset\"\nbegin\n\ncontext linorder\nbegin\n\nfun quicksort :: \"'a list \\<Rightarrow> 'a list\" where\n  \"quicksort []     = []\"\n| \"quicksort (x#xs) = quicksort [y\\<leftarrow>xs. \\<not> x\\<le>y] @ [x] @ quicksort [y\\<leftarrow>xs. x\\<le>y]\"\n\n\n\nlemma quicksort_permutes [simp]:\n  \"multiset_of (quicksort xs) = multiset_of xs\"\n  by (induct xs rule: quicksort.induct) (simp_all add: ac_simps)\n\nlemma set_quicksort [simp]: \"set (quicksort xs) = set xs\"\n  by (simp add: set_count_greater_0)\n\nlemma sorted_quicksort: \"sorted (quicksort xs)\"\n  by (induct xs rule: quicksort.induct) (auto simp add: sorted_Cons sorted_append not_le less_imp_le)\n\ntheorem sort_quicksort:\n  \"sort = quicksort\"\n  by (rule ext, rule properties_for_sort) (fact quicksort_permutes sorted_quicksort)+\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/Quicksort.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8397339676722394, "lm_q2_score": 0.8418256432832333, "lm_q1q2_score": 0.7069095875224648}}
{"text": "(*  Title:      ZF/Cardinal.thy\n    Author:     Lawrence C Paulson, Cambridge University Computer Laboratory\n    Copyright   1994  University of Cambridge\n*)\n\nsection\\<open>Cardinal Numbers Without the Axiom of Choice\\<close>\n\ntheory Cardinal imports OrderType Finite Nat Sum begin\n\ndefinition\n  (*least ordinal operator*)\n   Least    :: \"(i=>o) => i\"    (binder \\<open>\\<mu> \\<close> 10)  where\n     \"Least(P) == THE i. Ord(i) & P(i) & (\\<forall>j. j<i \\<longrightarrow> ~P(j))\"\n\ndefinition\n  eqpoll   :: \"[i,i] => o\"     (infixl \\<open>\\<approx>\\<close> 50)  where\n    \"A \\<approx> B == \\<exists>f. f \\<in> bij(A,B)\"\n\ndefinition\n  lepoll   :: \"[i,i] => o\"     (infixl \\<open>\\<lesssim>\\<close> 50)  where\n    \"A \\<lesssim> B == \\<exists>f. f \\<in> inj(A,B)\"\n\ndefinition\n  lesspoll :: \"[i,i] => o\"     (infixl \\<open>\\<prec>\\<close> 50)  where\n    \"A \\<prec> B == A \\<lesssim> B & ~(A \\<approx> B)\"\n\ndefinition\n  cardinal :: \"i=>i\"           (\\<open>|_|\\<close>)  where\n    \"|A| == (\\<mu> i. i \\<approx> A)\"\n\ndefinition\n  Finite   :: \"i=>o\"  where\n    \"Finite(A) == \\<exists>n\\<in>nat. A \\<approx> n\"\n\ndefinition\n  Card     :: \"i=>o\"  where\n    \"Card(i) == (i = |i|)\"\n\n\nsubsection\\<open>The Schroeder-Bernstein Theorem\\<close>\ntext\\<open>See Davey and Priestly, page 106\\<close>\n\n(** Lemma: Banach's Decomposition Theorem **)\n\nlemma decomp_bnd_mono: \"bnd_mono(X, %W. X - g``(Y - f``W))\"\nby (rule bnd_monoI, blast+)\n\nlemma Banach_last_equation:\n    \"g \\<in> Y->X\n     ==> g``(Y - f`` lfp(X, %W. X - g``(Y - f``W))) =\n         X - lfp(X, %W. X - g``(Y - f``W))\"\napply (rule_tac P = \"%u. v = X-u\" for v\n       in decomp_bnd_mono [THEN lfp_unfold, THEN ssubst])\napply (simp add: double_complement  fun_is_rel [THEN image_subset])\ndone\n\nlemma decomposition:\n     \"[| f \\<in> X->Y;  g \\<in> Y->X |] ==>\n      \\<exists>XA XB YA YB. (XA \\<inter> XB = 0) & (XA \\<union> XB = X) &\n                      (YA \\<inter> YB = 0) & (YA \\<union> YB = Y) &\n                      f``XA=YA & g``YB=XB\"\napply (intro exI conjI)\napply (rule_tac [6] Banach_last_equation)\napply (rule_tac [5] refl)\napply (assumption |\n       rule  Diff_disjoint Diff_partition fun_is_rel image_subset lfp_subset)+\ndone\n\nlemma schroeder_bernstein:\n    \"[| f \\<in> inj(X,Y);  g \\<in> inj(Y,X) |] ==> \\<exists>h. h \\<in> bij(X,Y)\"\napply (insert decomposition [of f X Y g])\napply (simp add: inj_is_fun)\napply (blast intro!: restrict_bij bij_disjoint_Un intro: bij_converse_bij)\n(* The instantiation of exI to @{term\"restrict(f,XA) \\<union> converse(restrict(g,YB))\"}\n   is forced by the context!! *)\ndone\n\n\n(** Equipollence is an equivalence relation **)\n\nlemma bij_imp_eqpoll: \"f \\<in> bij(A,B) ==> A \\<approx> B\"\napply (unfold eqpoll_def)\napply (erule exI)\ndone\n\n(*A \\<approx> A*)\nlemmas eqpoll_refl = id_bij [THEN bij_imp_eqpoll, simp]\n\nlemma eqpoll_sym: \"X \\<approx> Y ==> Y \\<approx> X\"\napply (unfold eqpoll_def)\napply (blast intro: bij_converse_bij)\ndone\n\nlemma eqpoll_trans [trans]:\n    \"[| X \\<approx> Y;  Y \\<approx> Z |] ==> X \\<approx> Z\"\napply (unfold eqpoll_def)\napply (blast intro: comp_bij)\ndone\n\n(** Le-pollence is a partial ordering **)\n\nlemma subset_imp_lepoll: \"X<=Y ==> X \\<lesssim> Y\"\napply (unfold lepoll_def)\napply (rule exI)\napply (erule id_subset_inj)\ndone\n\nlemmas lepoll_refl = subset_refl [THEN subset_imp_lepoll, simp]\n\nlemmas le_imp_lepoll = le_imp_subset [THEN subset_imp_lepoll]\n\nlemma eqpoll_imp_lepoll: \"X \\<approx> Y ==> X \\<lesssim> Y\"\nby (unfold eqpoll_def bij_def lepoll_def, blast)\n\nlemma lepoll_trans [trans]: \"[| X \\<lesssim> Y;  Y \\<lesssim> Z |] ==> X \\<lesssim> Z\"\napply (unfold lepoll_def)\napply (blast intro: comp_inj)\ndone\n\nlemma eq_lepoll_trans [trans]: \"[| X \\<approx> Y;  Y \\<lesssim> Z |] ==> X \\<lesssim> Z\"\n by (blast intro: eqpoll_imp_lepoll lepoll_trans)\n\nlemma lepoll_eq_trans [trans]: \"[| X \\<lesssim> Y;  Y \\<approx> Z |] ==> X \\<lesssim> Z\"\n by (blast intro: eqpoll_imp_lepoll lepoll_trans)\n\n(*Asymmetry law*)\nlemma eqpollI: \"[| X \\<lesssim> Y;  Y \\<lesssim> X |] ==> X \\<approx> Y\"\napply (unfold lepoll_def eqpoll_def)\napply (elim exE)\napply (rule schroeder_bernstein, assumption+)\ndone\n\nlemma eqpollE:\n    \"[| X \\<approx> Y; [| X \\<lesssim> Y; Y \\<lesssim> X |] ==> P |] ==> P\"\nby (blast intro: eqpoll_imp_lepoll eqpoll_sym)\n\nlemma eqpoll_iff: \"X \\<approx> Y \\<longleftrightarrow> X \\<lesssim> Y & Y \\<lesssim> X\"\nby (blast intro: eqpollI elim!: eqpollE)\n\nlemma lepoll_0_is_0: \"A \\<lesssim> 0 ==> A = 0\"\napply (unfold lepoll_def inj_def)\napply (blast dest: apply_type)\ndone\n\n(*@{term\"0 \\<lesssim> Y\"}*)\nlemmas empty_lepollI = empty_subsetI [THEN subset_imp_lepoll]\n\nlemma lepoll_0_iff: \"A \\<lesssim> 0 \\<longleftrightarrow> A=0\"\nby (blast intro: lepoll_0_is_0 lepoll_refl)\n\nlemma Un_lepoll_Un:\n    \"[| A \\<lesssim> B; C \\<lesssim> D; B \\<inter> D = 0 |] ==> A \\<union> C \\<lesssim> B \\<union> D\"\napply (unfold lepoll_def)\napply (blast intro: inj_disjoint_Un)\ndone\n\n(*A \\<approx> 0 ==> A=0*)\nlemmas eqpoll_0_is_0 = eqpoll_imp_lepoll [THEN lepoll_0_is_0]\n\nlemma eqpoll_0_iff: \"A \\<approx> 0 \\<longleftrightarrow> A=0\"\nby (blast intro: eqpoll_0_is_0 eqpoll_refl)\n\nlemma eqpoll_disjoint_Un:\n    \"[| A \\<approx> B;  C \\<approx> D;  A \\<inter> C = 0;  B \\<inter> D = 0 |]\n     ==> A \\<union> C \\<approx> B \\<union> D\"\napply (unfold eqpoll_def)\napply (blast intro: bij_disjoint_Un)\ndone\n\n\nsubsection\\<open>lesspoll: contributions by Krzysztof Grabczewski\\<close>\n\nlemma lesspoll_not_refl: \"~ (i \\<prec> i)\"\nby (simp add: lesspoll_def)\n\nlemma lesspoll_irrefl [elim!]: \"i \\<prec> i ==> P\"\nby (simp add: lesspoll_def)\n\nlemma lesspoll_imp_lepoll: \"A \\<prec> B ==> A \\<lesssim> B\"\nby (unfold lesspoll_def, blast)\n\nlemma lepoll_well_ord: \"[| A \\<lesssim> B; well_ord(B,r) |] ==> \\<exists>s. well_ord(A,s)\"\napply (unfold lepoll_def)\napply (blast intro: well_ord_rvimage)\ndone\n\nlemma lepoll_iff_leqpoll: \"A \\<lesssim> B \\<longleftrightarrow> A \\<prec> B | A \\<approx> B\"\napply (unfold lesspoll_def)\napply (blast intro!: eqpollI elim!: eqpollE)\ndone\n\nlemma inj_not_surj_succ:\n  assumes fi: \"f \\<in> inj(A, succ(m))\" and fns: \"f \\<notin> surj(A, succ(m))\" \n  shows \"\\<exists>f. f \\<in> inj(A,m)\"\nproof -\n  from fi [THEN inj_is_fun] fns \n  obtain y where y: \"y \\<in> succ(m)\" \"\\<And>x. x\\<in>A \\<Longrightarrow> f ` x \\<noteq> y\"\n    by (auto simp add: surj_def)\n  show ?thesis\n    proof \n      show \"(\\<lambda>z\\<in>A. if f`z = m then y else f`z) \\<in> inj(A, m)\" using y fi\n        by (simp add: inj_def) \n           (auto intro!: if_type [THEN lam_type] intro: Pi_type dest: apply_funtype)\n      qed\nqed\n\n(** Variations on transitivity **)\n\nlemma lesspoll_trans [trans]:\n      \"[| X \\<prec> Y; Y \\<prec> Z |] ==> X \\<prec> Z\"\napply (unfold lesspoll_def)\napply (blast elim!: eqpollE intro: eqpollI lepoll_trans)\ndone\n\nlemma lesspoll_trans1 [trans]:\n      \"[| X \\<lesssim> Y; Y \\<prec> Z |] ==> X \\<prec> Z\"\napply (unfold lesspoll_def)\napply (blast elim!: eqpollE intro: eqpollI lepoll_trans)\ndone\n\nlemma lesspoll_trans2 [trans]:\n      \"[| X \\<prec> Y; Y \\<lesssim> Z |] ==> X \\<prec> Z\"\napply (unfold lesspoll_def)\napply (blast elim!: eqpollE intro: eqpollI lepoll_trans)\ndone\n\nlemma eq_lesspoll_trans [trans]:\n      \"[| X \\<approx> Y; Y \\<prec> Z |] ==> X \\<prec> Z\"\n  by (blast intro: eqpoll_imp_lepoll lesspoll_trans1)\n\nlemma lesspoll_eq_trans [trans]:\n      \"[| X \\<prec> Y; Y \\<approx> Z |] ==> X \\<prec> Z\"\n  by (blast intro: eqpoll_imp_lepoll lesspoll_trans2)\n\n\n(** \\<mu> -- the least number operator [from HOL/Univ.ML] **)\n\nlemma Least_equality:\n    \"[| P(i);  Ord(i);  !!x. x<i ==> ~P(x) |] ==> (\\<mu> x. P(x)) = i\"\napply (unfold Least_def)\napply (rule the_equality, blast)\napply (elim conjE)\napply (erule Ord_linear_lt, assumption, blast+)\ndone\n\nlemma LeastI: \n  assumes P: \"P(i)\" and i: \"Ord(i)\" shows \"P(\\<mu> x. P(x))\"\nproof -\n  { from i have \"P(i) \\<Longrightarrow> P(\\<mu> x. P(x))\"\n      proof (induct i rule: trans_induct)\n        case (step i) \n        show ?case\n          proof (cases \"P(\\<mu> a. P(a))\")\n            case True thus ?thesis .\n          next\n            case False\n            hence \"\\<And>x. x \\<in> i \\<Longrightarrow> ~P(x)\" using step\n              by blast\n            hence \"(\\<mu> a. P(a)) = i\" using step\n              by (blast intro: Least_equality ltD) \n            thus ?thesis using step.prems\n              by simp \n          qed\n      qed\n  }\n  thus ?thesis using P .\nqed\n\ntext\\<open>The proof is almost identical to the one above!\\<close>\nlemma Least_le: \n  assumes P: \"P(i)\" and i: \"Ord(i)\" shows \"(\\<mu> x. P(x)) \\<le> i\"\nproof -\n  { from i have \"P(i) \\<Longrightarrow> (\\<mu> x. P(x)) \\<le> i\"\n      proof (induct i rule: trans_induct)\n        case (step i) \n        show ?case\n          proof (cases \"(\\<mu> a. P(a)) \\<le> i\")\n            case True thus ?thesis .\n          next\n            case False\n            hence \"\\<And>x. x \\<in> i \\<Longrightarrow> ~ (\\<mu> a. P(a)) \\<le> i\" using step\n              by blast\n            hence \"(\\<mu> a. P(a)) = i\" using step\n              by (blast elim: ltE intro: ltI Least_equality lt_trans1)\n            thus ?thesis using step\n              by simp \n          qed\n      qed\n  }\n  thus ?thesis using P .\nqed\n\n(*\\<mu> really is the smallest*)\nlemma less_LeastE: \"[| P(i);  i < (\\<mu> x. P(x)) |] ==> Q\"\napply (rule Least_le [THEN [2] lt_trans2, THEN lt_irrefl], assumption+)\napply (simp add: lt_Ord)\ndone\n\n(*Easier to apply than LeastI: conclusion has only one occurrence of P*)\nlemma LeastI2:\n    \"[| P(i);  Ord(i);  !!j. P(j) ==> Q(j) |] ==> Q(\\<mu> j. P(j))\"\nby (blast intro: LeastI )\n\n(*If there is no such P then \\<mu> is vacuously 0*)\nlemma Least_0:\n    \"[| ~ (\\<exists>i. Ord(i) & P(i)) |] ==> (\\<mu> x. P(x)) = 0\"\napply (unfold Least_def)\napply (rule the_0, blast)\ndone\n\nlemma Ord_Least [intro,simp,TC]: \"Ord(\\<mu> x. P(x))\"\nproof (cases \"\\<exists>i. Ord(i) & P(i)\")\n  case True \n  then obtain i where \"P(i)\" \"Ord(i)\"  by auto\n  hence \" (\\<mu> x. P(x)) \\<le> i\"  by (rule Least_le) \n  thus ?thesis\n    by (elim ltE)\nnext\n  case False\n  hence \"(\\<mu> x. P(x)) = 0\"  by (rule Least_0)\n  thus ?thesis\n    by auto\nqed\n\n\nsubsection\\<open>Basic Properties of Cardinals\\<close>\n\n(*Not needed for simplification, but helpful below*)\nlemma Least_cong: \"(!!y. P(y) \\<longleftrightarrow> Q(y)) ==> (\\<mu> x. P(x)) = (\\<mu> x. Q(x))\"\nby simp\n\n(*Need AC to get @{term\"X \\<lesssim> Y ==> |X| \\<le> |Y|\"};  see well_ord_lepoll_imp_Card_le\n  Converse also requires AC, but see well_ord_cardinal_eqE*)\nlemma cardinal_cong: \"X \\<approx> Y ==> |X| = |Y|\"\napply (unfold eqpoll_def cardinal_def)\napply (rule Least_cong)\napply (blast intro: comp_bij bij_converse_bij)\ndone\n\n(*Under AC, the premise becomes trivial; one consequence is ||A|| = |A|*)\nlemma well_ord_cardinal_eqpoll:\n  assumes r: \"well_ord(A,r)\" shows \"|A| \\<approx> A\"\nproof (unfold cardinal_def)\n  show \"(\\<mu> i. i \\<approx> A) \\<approx> A\"\n    by (best intro: LeastI Ord_ordertype ordermap_bij bij_converse_bij bij_imp_eqpoll r) \nqed\n\n(* @{term\"Ord(A) ==> |A| \\<approx> A\"} *)\nlemmas Ord_cardinal_eqpoll = well_ord_Memrel [THEN well_ord_cardinal_eqpoll]\n\nlemma Ord_cardinal_idem: \"Ord(A) \\<Longrightarrow> ||A|| = |A|\"\n by (rule Ord_cardinal_eqpoll [THEN cardinal_cong])\n\nlemma well_ord_cardinal_eqE:\n  assumes woX: \"well_ord(X,r)\" and woY: \"well_ord(Y,s)\" and eq: \"|X| = |Y|\"\nshows \"X \\<approx> Y\"\nproof -\n  have \"X \\<approx> |X|\" by (blast intro: well_ord_cardinal_eqpoll [OF woX] eqpoll_sym)\n  also have \"... = |Y|\" by (rule eq)\n  also have \"... \\<approx> Y\" by (rule well_ord_cardinal_eqpoll [OF woY])\n  finally show ?thesis .\nqed\n\nlemma well_ord_cardinal_eqpoll_iff:\n     \"[| well_ord(X,r);  well_ord(Y,s) |] ==> |X| = |Y| \\<longleftrightarrow> X \\<approx> Y\"\nby (blast intro: cardinal_cong well_ord_cardinal_eqE)\n\n\n(** Observations from Kunen, page 28 **)\n\nlemma Ord_cardinal_le: \"Ord(i) ==> |i| \\<le> i\"\napply (unfold cardinal_def)\napply (erule eqpoll_refl [THEN Least_le])\ndone\n\nlemma Card_cardinal_eq: \"Card(K) ==> |K| = K\"\napply (unfold Card_def)\napply (erule sym)\ndone\n\n(* Could replace the  @{term\"~(j \\<approx> i)\"}  by  @{term\"~(i \\<preceq> j)\"}. *)\nlemma CardI: \"[| Ord(i);  !!j. j<i ==> ~(j \\<approx> i) |] ==> Card(i)\"\napply (unfold Card_def cardinal_def)\napply (subst Least_equality)\napply (blast intro: eqpoll_refl)+\ndone\n\nlemma Card_is_Ord: \"Card(i) ==> Ord(i)\"\napply (unfold Card_def cardinal_def)\napply (erule ssubst)\napply (rule Ord_Least)\ndone\n\nlemma Card_cardinal_le: \"Card(K) ==> K \\<le> |K|\"\napply (simp (no_asm_simp) add: Card_is_Ord Card_cardinal_eq)\ndone\n\nlemma Ord_cardinal [simp,intro!]: \"Ord(|A|)\"\napply (unfold cardinal_def)\napply (rule Ord_Least)\ndone\n\ntext\\<open>The cardinals are the initial ordinals.\\<close>\nlemma Card_iff_initial: \"Card(K) \\<longleftrightarrow> Ord(K) & (\\<forall>j. j<K \\<longrightarrow> ~ j \\<approx> K)\"\nproof -\n  { fix j\n    assume K: \"Card(K)\" \"j \\<approx> K\"\n    assume \"j < K\"\n    also have \"... = (\\<mu> i. i \\<approx> K)\" using K\n      by (simp add: Card_def cardinal_def)\n    finally have \"j < (\\<mu> i. i \\<approx> K)\" .\n    hence \"False\" using K\n      by (best dest: less_LeastE) \n  }\n  then show ?thesis\n    by (blast intro: CardI Card_is_Ord) \nqed\n\nlemma lt_Card_imp_lesspoll: \"[| Card(a); i<a |] ==> i \\<prec> a\"\napply (unfold lesspoll_def)\napply (drule Card_iff_initial [THEN iffD1])\napply (blast intro!: leI [THEN le_imp_lepoll])\ndone\n\nlemma Card_0: \"Card(0)\"\napply (rule Ord_0 [THEN CardI])\napply (blast elim!: ltE)\ndone\n\nlemma Card_Un: \"[| Card(K);  Card(L) |] ==> Card(K \\<union> L)\"\napply (rule Ord_linear_le [of K L])\napply (simp_all add: subset_Un_iff [THEN iffD1]  Card_is_Ord le_imp_subset\n                     subset_Un_iff2 [THEN iffD1])\ndone\n\n(*Infinite unions of cardinals?  See Devlin, Lemma 6.7, page 98*)\n\nlemma Card_cardinal [iff]: \"Card(|A|)\"\nproof (unfold cardinal_def)\n  show \"Card(\\<mu> i. i \\<approx> A)\"\n    proof (cases \"\\<exists>i. Ord (i) & i \\<approx> A\")\n      case False thus ?thesis           \\<comment> \\<open>degenerate case\\<close>\n        by (simp add: Least_0 Card_0)\n    next\n      case True                         \\<comment> \\<open>real case: \\<^term>\\<open>A\\<close> is isomorphic to some ordinal\\<close>\n      then obtain i where i: \"Ord(i)\" \"i \\<approx> A\" by blast\n      show ?thesis\n        proof (rule CardI [OF Ord_Least], rule notI)\n          fix j\n          assume j: \"j < (\\<mu> i. i \\<approx> A)\"\n          assume \"j \\<approx> (\\<mu> i. i \\<approx> A)\"\n          also have \"... \\<approx> A\" using i by (auto intro: LeastI)\n          finally have \"j \\<approx> A\" .\n          thus False\n            by (rule less_LeastE [OF _ j])\n        qed\n    qed\nqed\n\n(*Kunen's Lemma 10.5*)\nlemma cardinal_eq_lemma:\n  assumes i:\"|i| \\<le> j\" and j: \"j \\<le> i\" shows \"|j| = |i|\"\nproof (rule eqpollI [THEN cardinal_cong])\n  show \"j \\<lesssim> i\" by (rule le_imp_lepoll [OF j])\nnext\n  have Oi: \"Ord(i)\" using j by (rule le_Ord2)\n  hence \"i \\<approx> |i|\"\n    by (blast intro: Ord_cardinal_eqpoll eqpoll_sym)\n  also have \"... \\<lesssim> j\"\n    by (blast intro: le_imp_lepoll i)\n  finally show \"i \\<lesssim> j\" .\nqed\n\nlemma cardinal_mono:\n  assumes ij: \"i \\<le> j\" shows \"|i| \\<le> |j|\"\nusing Ord_cardinal [of i] Ord_cardinal [of j]\nproof (cases rule: Ord_linear_le)\n  case le thus ?thesis .\nnext\n  case ge\n  have i: \"Ord(i)\" using ij\n    by (simp add: lt_Ord)\n  have ci: \"|i| \\<le> j\"\n    by (blast intro: Ord_cardinal_le ij le_trans i)\n  have \"|i| = ||i||\"\n    by (auto simp add: Ord_cardinal_idem i)\n  also have \"... = |j|\"\n    by (rule cardinal_eq_lemma [OF ge ci])\n  finally have \"|i| = |j|\" .\n  thus ?thesis by simp\nqed\n\ntext\\<open>Since we have \\<^term>\\<open>|succ(nat)| \\<le> |nat|\\<close>, the converse of \\<open>cardinal_mono\\<close> fails!\\<close>\nlemma cardinal_lt_imp_lt: \"[| |i| < |j|;  Ord(i);  Ord(j) |] ==> i < j\"\napply (rule Ord_linear2 [of i j], assumption+)\napply (erule lt_trans2 [THEN lt_irrefl])\napply (erule cardinal_mono)\ndone\n\nlemma Card_lt_imp_lt: \"[| |i| < K;  Ord(i);  Card(K) |] ==> i < K\"\n  by (simp (no_asm_simp) add: cardinal_lt_imp_lt Card_is_Ord Card_cardinal_eq)\n\nlemma Card_lt_iff: \"[| Ord(i);  Card(K) |] ==> (|i| < K) \\<longleftrightarrow> (i < K)\"\nby (blast intro: Card_lt_imp_lt Ord_cardinal_le [THEN lt_trans1])\n\nlemma Card_le_iff: \"[| Ord(i);  Card(K) |] ==> (K \\<le> |i|) \\<longleftrightarrow> (K \\<le> i)\"\nby (simp add: Card_lt_iff Card_is_Ord Ord_cardinal not_lt_iff_le [THEN iff_sym])\n\n(*Can use AC or finiteness to discharge first premise*)\nlemma well_ord_lepoll_imp_Card_le:\n  assumes wB: \"well_ord(B,r)\" and AB: \"A \\<lesssim> B\"\n  shows \"|A| \\<le> |B|\"\nusing Ord_cardinal [of A] Ord_cardinal [of B]\nproof (cases rule: Ord_linear_le)\n  case le thus ?thesis .\nnext\n  case ge\n  from lepoll_well_ord [OF AB wB]\n  obtain s where s: \"well_ord(A, s)\" by blast\n  have \"B  \\<approx> |B|\" by (blast intro: wB eqpoll_sym well_ord_cardinal_eqpoll)\n  also have \"... \\<lesssim> |A|\" by (rule le_imp_lepoll [OF ge])\n  also have \"... \\<approx> A\" by (rule well_ord_cardinal_eqpoll [OF s])\n  finally have \"B \\<lesssim> A\" .\n  hence \"A \\<approx> B\" by (blast intro: eqpollI AB)\n  hence \"|A| = |B|\" by (rule cardinal_cong)\n  thus ?thesis by simp\nqed\n\nlemma lepoll_cardinal_le: \"[| A \\<lesssim> i; Ord(i) |] ==> |A| \\<le> i\"\napply (rule le_trans)\napply (erule well_ord_Memrel [THEN well_ord_lepoll_imp_Card_le], assumption)\napply (erule Ord_cardinal_le)\ndone\n\nlemma lepoll_Ord_imp_eqpoll: \"[| A \\<lesssim> i; Ord(i) |] ==> |A| \\<approx> A\"\nby (blast intro: lepoll_cardinal_le well_ord_Memrel well_ord_cardinal_eqpoll dest!: lepoll_well_ord)\n\nlemma lesspoll_imp_eqpoll: \"[| A \\<prec> i; Ord(i) |] ==> |A| \\<approx> A\"\napply (unfold lesspoll_def)\napply (blast intro: lepoll_Ord_imp_eqpoll)\ndone\n\nlemma cardinal_subset_Ord: \"[|A<=i; Ord(i)|] ==> |A| \\<subseteq> i\"\napply (drule subset_imp_lepoll [THEN lepoll_cardinal_le])\napply (auto simp add: lt_def)\napply (blast intro: Ord_trans)\ndone\n\nsubsection\\<open>The finite cardinals\\<close>\n\nlemma cons_lepoll_consD:\n \"[| cons(u,A) \\<lesssim> cons(v,B);  u\\<notin>A;  v\\<notin>B |] ==> A \\<lesssim> B\"\napply (unfold lepoll_def inj_def, safe)\napply (rule_tac x = \"\\<lambda>x\\<in>A. if f`x=v then f`u else f`x\" in exI)\napply (rule CollectI)\n(*Proving it's in the function space A->B*)\napply (rule if_type [THEN lam_type])\napply (blast dest: apply_funtype)\napply (blast elim!: mem_irrefl dest: apply_funtype)\n(*Proving it's injective*)\napply (simp (no_asm_simp))\napply blast\ndone\n\nlemma cons_eqpoll_consD: \"[| cons(u,A) \\<approx> cons(v,B);  u\\<notin>A;  v\\<notin>B |] ==> A \\<approx> B\"\napply (simp add: eqpoll_iff)\napply (blast intro: cons_lepoll_consD)\ndone\n\n(*Lemma suggested by Mike Fourman*)\nlemma succ_lepoll_succD: \"succ(m) \\<lesssim> succ(n) ==> m \\<lesssim> n\"\napply (unfold succ_def)\napply (erule cons_lepoll_consD)\napply (rule mem_not_refl)+\ndone\n\n\nlemma nat_lepoll_imp_le:\n     \"m \\<in> nat ==> n \\<in> nat \\<Longrightarrow> m \\<lesssim> n \\<Longrightarrow> m \\<le> n\"\nproof (induct m arbitrary: n rule: nat_induct)\n  case 0 thus ?case by (blast intro!: nat_0_le)\nnext\n  case (succ m)\n  show ?case  using \\<open>n \\<in> nat\\<close>\n    proof (cases rule: natE)\n      case 0 thus ?thesis using succ\n        by (simp add: lepoll_def inj_def)\n    next\n      case (succ n') thus ?thesis using succ.hyps \\<open> succ(m) \\<lesssim> n\\<close>\n        by (blast intro!: succ_leI dest!: succ_lepoll_succD)\n    qed\nqed\n\nlemma nat_eqpoll_iff: \"[| m \\<in> nat; n \\<in> nat |] ==> m \\<approx> n \\<longleftrightarrow> m = n\"\napply (rule iffI)\napply (blast intro: nat_lepoll_imp_le le_anti_sym elim!: eqpollE)\napply (simp add: eqpoll_refl)\ndone\n\n(*The object of all this work: every natural number is a (finite) cardinal*)\nlemma nat_into_Card:\n  assumes n: \"n \\<in> nat\" shows \"Card(n)\"\nproof (unfold Card_def cardinal_def, rule sym)\n  have \"Ord(n)\" using n  by auto\n  moreover\n  { fix i\n    assume \"i < n\" \"i \\<approx> n\"\n    hence False using n\n      by (auto simp add: lt_nat_in_nat [THEN nat_eqpoll_iff])\n  }\n  ultimately show \"(\\<mu> i. i \\<approx> n) = n\" by (auto intro!: Least_equality) \nqed\n\nlemmas cardinal_0 = nat_0I [THEN nat_into_Card, THEN Card_cardinal_eq, iff]\nlemmas cardinal_1 = nat_1I [THEN nat_into_Card, THEN Card_cardinal_eq, iff]\n\n\n(*Part of Kunen's Lemma 10.6*)\nlemma succ_lepoll_natE: \"[| succ(n) \\<lesssim> n;  n \\<in> nat |] ==> P\"\nby (rule nat_lepoll_imp_le [THEN lt_irrefl], auto)\n\nlemma nat_lepoll_imp_ex_eqpoll_n:\n     \"[| n \\<in> nat;  nat \\<lesssim> X |] ==> \\<exists>Y. Y \\<subseteq> X & n \\<approx> Y\"\napply (unfold lepoll_def eqpoll_def)\napply (fast del: subsetI subsetCE\n            intro!: subset_SIs\n            dest!: Ord_nat [THEN [2] OrdmemD, THEN [2] restrict_inj]\n            elim!: restrict_bij\n                   inj_is_fun [THEN fun_is_rel, THEN image_subset])\ndone\n\n\n(** \\<lesssim>, \\<prec> and natural numbers **)\n\nlemma lepoll_succ: \"i \\<lesssim> succ(i)\"\n  by (blast intro: subset_imp_lepoll)\n\nlemma lepoll_imp_lesspoll_succ:\n  assumes A: \"A \\<lesssim> m\" and m: \"m \\<in> nat\"\n  shows \"A \\<prec> succ(m)\"\nproof -\n  { assume \"A \\<approx> succ(m)\"\n    hence \"succ(m) \\<approx> A\" by (rule eqpoll_sym)\n    also have \"... \\<lesssim> m\" by (rule A)\n    finally have \"succ(m) \\<lesssim> m\" .\n    hence False by (rule succ_lepoll_natE) (rule m) }\n  moreover have \"A \\<lesssim> succ(m)\" by (blast intro: lepoll_trans A lepoll_succ)\n  ultimately show ?thesis by (auto simp add: lesspoll_def)\nqed\n\nlemma lesspoll_succ_imp_lepoll:\n     \"[| A \\<prec> succ(m); m \\<in> nat |] ==> A \\<lesssim> m\"\napply (unfold lesspoll_def lepoll_def eqpoll_def bij_def)\napply (auto dest: inj_not_surj_succ)\ndone\n\nlemma lesspoll_succ_iff: \"m \\<in> nat ==> A \\<prec> succ(m) \\<longleftrightarrow> A \\<lesssim> m\"\nby (blast intro!: lepoll_imp_lesspoll_succ lesspoll_succ_imp_lepoll)\n\nlemma lepoll_succ_disj: \"[| A \\<lesssim> succ(m);  m \\<in> nat |] ==> A \\<lesssim> m | A \\<approx> succ(m)\"\napply (rule disjCI)\napply (rule lesspoll_succ_imp_lepoll)\nprefer 2 apply assumption\napply (simp (no_asm_simp) add: lesspoll_def)\ndone\n\nlemma lesspoll_cardinal_lt: \"[| A \\<prec> i; Ord(i) |] ==> |A| < i\"\napply (unfold lesspoll_def, clarify)\napply (frule lepoll_cardinal_le, assumption)\napply (blast intro: well_ord_Memrel well_ord_cardinal_eqpoll [THEN eqpoll_sym]\n             dest: lepoll_well_ord  elim!: leE)\ndone\n\n\nsubsection\\<open>The first infinite cardinal: Omega, or nat\\<close>\n\n(*This implies Kunen's Lemma 10.6*)\nlemma lt_not_lepoll:\n  assumes n: \"n<i\" \"n \\<in> nat\" shows \"~ i \\<lesssim> n\"\nproof -\n  { assume i: \"i \\<lesssim> n\"\n    have \"succ(n) \\<lesssim> i\" using n\n      by (elim ltE, blast intro: Ord_succ_subsetI [THEN subset_imp_lepoll])\n    also have \"... \\<lesssim> n\" by (rule i)\n    finally have \"succ(n) \\<lesssim> n\" .\n    hence False  by (rule succ_lepoll_natE) (rule n) }\n  thus ?thesis by auto\nqed\n\ntext\\<open>A slightly weaker version of \\<open>nat_eqpoll_iff\\<close>\\<close>\nlemma Ord_nat_eqpoll_iff:\n  assumes i: \"Ord(i)\" and n: \"n \\<in> nat\" shows \"i \\<approx> n \\<longleftrightarrow> i=n\"\nusing i nat_into_Ord [OF n]\nproof (cases rule: Ord_linear_lt)\n  case lt\n  hence  \"i \\<in> nat\" by (rule lt_nat_in_nat) (rule n)\n  thus ?thesis by (simp add: nat_eqpoll_iff n)\nnext\n  case eq\n  thus ?thesis by (simp add: eqpoll_refl)\nnext\n  case gt\n  hence  \"~ i \\<lesssim> n\" using n  by (rule lt_not_lepoll)\n  hence  \"~ i \\<approx> n\" using n  by (blast intro: eqpoll_imp_lepoll)\n  moreover have \"i \\<noteq> n\" using \\<open>n<i\\<close> by auto\n  ultimately show ?thesis by blast\nqed\n\nlemma Card_nat: \"Card(nat)\"\nproof -\n  { fix i\n    assume i: \"i < nat\" \"i \\<approx> nat\"\n    hence \"~ nat \\<lesssim> i\"\n      by (simp add: lt_def lt_not_lepoll)\n    hence False using i\n      by (simp add: eqpoll_iff)\n  }\n  hence \"(\\<mu> i. i \\<approx> nat) = nat\" by (blast intro: Least_equality eqpoll_refl)\n  thus ?thesis\n    by (auto simp add: Card_def cardinal_def)\nqed\n\n(*Allows showing that |i| is a limit cardinal*)\nlemma nat_le_cardinal: \"nat \\<le> i ==> nat \\<le> |i|\"\napply (rule Card_nat [THEN Card_cardinal_eq, THEN subst])\napply (erule cardinal_mono)\ndone\n\nlemma n_lesspoll_nat: \"n \\<in> nat ==> n \\<prec> nat\"\n  by (blast intro: Ord_nat Card_nat ltI lt_Card_imp_lesspoll)\n\n\nsubsection\\<open>Towards Cardinal Arithmetic\\<close>\n(** Congruence laws for successor, cardinal addition and multiplication **)\n\n(*Congruence law for  cons  under equipollence*)\nlemma cons_lepoll_cong:\n    \"[| A \\<lesssim> B;  b \\<notin> B |] ==> cons(a,A) \\<lesssim> cons(b,B)\"\napply (unfold lepoll_def, safe)\napply (rule_tac x = \"\\<lambda>y\\<in>cons (a,A) . if y=a then b else f`y\" in exI)\napply (rule_tac d = \"%z. if z \\<in> B then converse (f) `z else a\" in lam_injective)\napply (safe elim!: consE')\n   apply simp_all\napply (blast intro: inj_is_fun [THEN apply_type])+\ndone\n\nlemma cons_eqpoll_cong:\n     \"[| A \\<approx> B;  a \\<notin> A;  b \\<notin> B |] ==> cons(a,A) \\<approx> cons(b,B)\"\nby (simp add: eqpoll_iff cons_lepoll_cong)\n\nlemma cons_lepoll_cons_iff:\n     \"[| a \\<notin> A;  b \\<notin> B |] ==> cons(a,A) \\<lesssim> cons(b,B)  \\<longleftrightarrow>  A \\<lesssim> B\"\nby (blast intro: cons_lepoll_cong cons_lepoll_consD)\n\nlemma cons_eqpoll_cons_iff:\n     \"[| a \\<notin> A;  b \\<notin> B |] ==> cons(a,A) \\<approx> cons(b,B)  \\<longleftrightarrow>  A \\<approx> B\"\nby (blast intro: cons_eqpoll_cong cons_eqpoll_consD)\n\nlemma singleton_eqpoll_1: \"{a} \\<approx> 1\"\napply (unfold succ_def)\napply (blast intro!: eqpoll_refl [THEN cons_eqpoll_cong])\ndone\n\nlemma cardinal_singleton: \"|{a}| = 1\"\napply (rule singleton_eqpoll_1 [THEN cardinal_cong, THEN trans])\napply (simp (no_asm) add: nat_into_Card [THEN Card_cardinal_eq])\ndone\n\nlemma not_0_is_lepoll_1: \"A \\<noteq> 0 ==> 1 \\<lesssim> A\"\napply (erule not_emptyE)\napply (rule_tac a = \"cons (x, A-{x}) \" in subst)\napply (rule_tac [2] a = \"cons(0,0)\" and P= \"%y. y \\<lesssim> cons (x, A-{x})\" in subst)\nprefer 3 apply (blast intro: cons_lepoll_cong subset_imp_lepoll, auto)\ndone\n\n(*Congruence law for  succ  under equipollence*)\nlemma succ_eqpoll_cong: \"A \\<approx> B ==> succ(A) \\<approx> succ(B)\"\napply (unfold succ_def)\napply (simp add: cons_eqpoll_cong mem_not_refl)\ndone\n\n(*Congruence law for + under equipollence*)\nlemma sum_eqpoll_cong: \"[| A \\<approx> C;  B \\<approx> D |] ==> A+B \\<approx> C+D\"\napply (unfold eqpoll_def)\napply (blast intro!: sum_bij)\ndone\n\n(*Congruence law for * under equipollence*)\nlemma prod_eqpoll_cong:\n    \"[| A \\<approx> C;  B \\<approx> D |] ==> A*B \\<approx> C*D\"\napply (unfold eqpoll_def)\napply (blast intro!: prod_bij)\ndone\n\nlemma inj_disjoint_eqpoll:\n    \"[| f \\<in> inj(A,B);  A \\<inter> B = 0 |] ==> A \\<union> (B - range(f)) \\<approx> B\"\napply (unfold eqpoll_def)\napply (rule exI)\napply (rule_tac c = \"%x. if x \\<in> A then f`x else x\"\n            and d = \"%y. if y \\<in> range (f) then converse (f) `y else y\"\n       in lam_bijective)\napply (blast intro!: if_type inj_is_fun [THEN apply_type])\napply (simp (no_asm_simp) add: inj_converse_fun [THEN apply_funtype])\napply (safe elim!: UnE')\n   apply (simp_all add: inj_is_fun [THEN apply_rangeI])\napply (blast intro: inj_converse_fun [THEN apply_type])+\ndone\n\n\nsubsection\\<open>Lemmas by Krzysztof Grabczewski\\<close>\n\n(*New proofs using cons_lepoll_cons. Could generalise from succ to cons.*)\n\ntext\\<open>If \\<^term>\\<open>A\\<close> has at most \\<^term>\\<open>n+1\\<close> elements and \\<^term>\\<open>a \\<in> A\\<close>\n      then \\<^term>\\<open>A-{a}\\<close> has at most \\<^term>\\<open>n\\<close>.\\<close>\nlemma Diff_sing_lepoll:\n      \"[| a \\<in> A;  A \\<lesssim> succ(n) |] ==> A - {a} \\<lesssim> n\"\napply (unfold succ_def)\napply (rule cons_lepoll_consD)\napply (rule_tac [3] mem_not_refl)\napply (erule cons_Diff [THEN ssubst], safe)\ndone\n\ntext\\<open>If \\<^term>\\<open>A\\<close> has at least \\<^term>\\<open>n+1\\<close> elements then \\<^term>\\<open>A-{a}\\<close> has at least \\<^term>\\<open>n\\<close>.\\<close>\nlemma lepoll_Diff_sing:\n  assumes A: \"succ(n) \\<lesssim> A\" shows \"n \\<lesssim> A - {a}\"\nproof -\n  have \"cons(n,n) \\<lesssim> A\" using A\n    by (unfold succ_def)\n  also have \"... \\<lesssim> cons(a, A-{a})\"\n    by (blast intro: subset_imp_lepoll)\n  finally have \"cons(n,n) \\<lesssim> cons(a, A-{a})\" .\n  thus ?thesis\n    by (blast intro: cons_lepoll_consD mem_irrefl)\nqed\n\nlemma Diff_sing_eqpoll: \"[| a \\<in> A; A \\<approx> succ(n) |] ==> A - {a} \\<approx> n\"\nby (blast intro!: eqpollI\n          elim!: eqpollE\n          intro: Diff_sing_lepoll lepoll_Diff_sing)\n\nlemma lepoll_1_is_sing: \"[| A \\<lesssim> 1; a \\<in> A |] ==> A = {a}\"\napply (frule Diff_sing_lepoll, assumption)\napply (drule lepoll_0_is_0)\napply (blast elim: equalityE)\ndone\n\nlemma Un_lepoll_sum: \"A \\<union> B \\<lesssim> A+B\"\napply (unfold lepoll_def)\napply (rule_tac x = \"\\<lambda>x\\<in>A \\<union> B. if x\\<in>A then Inl (x) else Inr (x)\" in exI)\napply (rule_tac d = \"%z. snd (z)\" in lam_injective)\napply force\napply (simp add: Inl_def Inr_def)\ndone\n\nlemma well_ord_Un:\n     \"[| well_ord(X,R); well_ord(Y,S) |] ==> \\<exists>T. well_ord(X \\<union> Y, T)\"\nby (erule well_ord_radd [THEN Un_lepoll_sum [THEN lepoll_well_ord]],\n    assumption)\n\n(*Krzysztof Grabczewski*)\nlemma disj_Un_eqpoll_sum: \"A \\<inter> B = 0 ==> A \\<union> B \\<approx> A + B\"\napply (unfold eqpoll_def)\napply (rule_tac x = \"\\<lambda>a\\<in>A \\<union> B. if a \\<in> A then Inl (a) else Inr (a)\" in exI)\napply (rule_tac d = \"%z. case (%x. x, %x. x, z)\" in lam_bijective)\napply auto\ndone\n\n\nsubsection \\<open>Finite and infinite sets\\<close>\n\nlemma eqpoll_imp_Finite_iff: \"A \\<approx> B ==> Finite(A) \\<longleftrightarrow> Finite(B)\"\napply (unfold Finite_def)\napply (blast intro: eqpoll_trans eqpoll_sym)\ndone\n\nlemma Finite_0 [simp]: \"Finite(0)\"\napply (unfold Finite_def)\napply (blast intro!: eqpoll_refl nat_0I)\ndone\n\nlemma Finite_cons: \"Finite(x) ==> Finite(cons(y,x))\"\napply (unfold Finite_def)\napply (case_tac \"y \\<in> x\")\napply (simp add: cons_absorb)\napply (erule bexE)\napply (rule bexI)\napply (erule_tac [2] nat_succI)\napply (simp (no_asm_simp) add: succ_def cons_eqpoll_cong mem_not_refl)\ndone\n\nlemma Finite_succ: \"Finite(x) ==> Finite(succ(x))\"\napply (unfold succ_def)\napply (erule Finite_cons)\ndone\n\nlemma lepoll_nat_imp_Finite:\n  assumes A: \"A \\<lesssim> n\" and n: \"n \\<in> nat\" shows \"Finite(A)\"\nproof -\n  have \"A \\<lesssim> n \\<Longrightarrow> Finite(A)\" using n\n    proof (induct n)\n      case 0\n      hence \"A = 0\" by (rule lepoll_0_is_0) \n      thus ?case by simp\n    next\n      case (succ n)\n      hence \"A \\<lesssim> n \\<or> A \\<approx> succ(n)\" by (blast dest: lepoll_succ_disj)\n      thus ?case using succ by (auto simp add: Finite_def) \n    qed\n  thus ?thesis using A .\nqed\n\nlemma lesspoll_nat_is_Finite:\n     \"A \\<prec> nat ==> Finite(A)\"\napply (unfold Finite_def)\napply (blast dest: ltD lesspoll_cardinal_lt\n                   lesspoll_imp_eqpoll [THEN eqpoll_sym])\ndone\n\nlemma lepoll_Finite:\n  assumes Y: \"Y \\<lesssim> X\" and X: \"Finite(X)\" shows \"Finite(Y)\"\nproof -\n  obtain n where n: \"n \\<in> nat\" \"X \\<approx> n\" using X\n    by (auto simp add: Finite_def)\n  have \"Y \\<lesssim> X\"         by (rule Y)\n  also have \"... \\<approx> n\"  by (rule n)\n  finally have \"Y \\<lesssim> n\" .\n  thus ?thesis using n by (simp add: lepoll_nat_imp_Finite)\nqed\n\nlemmas subset_Finite = subset_imp_lepoll [THEN lepoll_Finite]\n\nlemma Finite_cons_iff [iff]: \"Finite(cons(y,x)) \\<longleftrightarrow> Finite(x)\"\nby (blast intro: Finite_cons subset_Finite)\n\nlemma Finite_succ_iff [iff]: \"Finite(succ(x)) \\<longleftrightarrow> Finite(x)\"\nby (simp add: succ_def)\n\nlemma Finite_Int: \"Finite(A) | Finite(B) ==> Finite(A \\<inter> B)\"\nby (blast intro: subset_Finite)\n\nlemmas Finite_Diff = Diff_subset [THEN subset_Finite]\n\nlemma nat_le_infinite_Ord:\n      \"[| Ord(i);  ~ Finite(i) |] ==> nat \\<le> i\"\napply (unfold Finite_def)\napply (erule Ord_nat [THEN [2] Ord_linear2])\nprefer 2 apply assumption\napply (blast intro!: eqpoll_refl elim!: ltE)\ndone\n\nlemma Finite_imp_well_ord:\n    \"Finite(A) ==> \\<exists>r. well_ord(A,r)\"\napply (unfold Finite_def eqpoll_def)\napply (blast intro: well_ord_rvimage bij_is_inj well_ord_Memrel nat_into_Ord)\ndone\n\nlemma succ_lepoll_imp_not_empty: \"succ(x) \\<lesssim> y ==> y \\<noteq> 0\"\nby (fast dest!: lepoll_0_is_0)\n\nlemma eqpoll_succ_imp_not_empty: \"x \\<approx> succ(n) ==> x \\<noteq> 0\"\nby (fast elim!: eqpoll_sym [THEN eqpoll_0_is_0, THEN succ_neq_0])\n\nlemma Finite_Fin_lemma [rule_format]:\n     \"n \\<in> nat ==> \\<forall>A. (A\\<approx>n & A \\<subseteq> X) \\<longrightarrow> A \\<in> Fin(X)\"\napply (induct_tac n)\napply (rule allI)\napply (fast intro!: Fin.emptyI dest!: eqpoll_imp_lepoll [THEN lepoll_0_is_0])\napply (rule allI)\napply (rule impI)\napply (erule conjE)\napply (rule eqpoll_succ_imp_not_empty [THEN not_emptyE], assumption)\napply (frule Diff_sing_eqpoll, assumption)\napply (erule allE)\napply (erule impE, fast)\napply (drule subsetD, assumption)\napply (drule Fin.consI, assumption)\napply (simp add: cons_Diff)\ndone\n\nlemma Finite_Fin: \"[| Finite(A); A \\<subseteq> X |] ==> A \\<in> Fin(X)\"\nby (unfold Finite_def, blast intro: Finite_Fin_lemma)\n\nlemma Fin_lemma [rule_format]: \"n \\<in> nat ==> \\<forall>A. A \\<approx> n \\<longrightarrow> A \\<in> Fin(A)\"\napply (induct_tac n)\napply (simp add: eqpoll_0_iff, clarify)\napply (subgoal_tac \"\\<exists>u. u \\<in> A\")\napply (erule exE)\napply (rule Diff_sing_eqpoll [elim_format])\nprefer 2 apply assumption\napply assumption\napply (rule_tac b = A in cons_Diff [THEN subst], assumption)\napply (rule Fin.consI, blast)\napply (blast intro: subset_consI [THEN Fin_mono, THEN subsetD])\n(*Now for the lemma assumed above*)\napply (unfold eqpoll_def)\napply (blast intro: bij_converse_bij [THEN bij_is_fun, THEN apply_type])\ndone\n\nlemma Finite_into_Fin: \"Finite(A) ==> A \\<in> Fin(A)\"\napply (unfold Finite_def)\napply (blast intro: Fin_lemma)\ndone\n\nlemma Fin_into_Finite: \"A \\<in> Fin(U) ==> Finite(A)\"\nby (fast intro!: Finite_0 Finite_cons elim: Fin_induct)\n\nlemma Finite_Fin_iff: \"Finite(A) \\<longleftrightarrow> A \\<in> Fin(A)\"\nby (blast intro: Finite_into_Fin Fin_into_Finite)\n\nlemma Finite_Un: \"[| Finite(A); Finite(B) |] ==> Finite(A \\<union> B)\"\nby (blast intro!: Fin_into_Finite Fin_UnI\n          dest!: Finite_into_Fin\n          intro: Un_upper1 [THEN Fin_mono, THEN subsetD]\n                 Un_upper2 [THEN Fin_mono, THEN subsetD])\n\nlemma Finite_Un_iff [simp]: \"Finite(A \\<union> B) \\<longleftrightarrow> (Finite(A) & Finite(B))\"\nby (blast intro: subset_Finite Finite_Un)\n\ntext\\<open>The converse must hold too.\\<close>\nlemma Finite_Union: \"[| \\<forall>y\\<in>X. Finite(y);  Finite(X) |] ==> Finite(\\<Union>(X))\"\napply (simp add: Finite_Fin_iff)\napply (rule Fin_UnionI)\napply (erule Fin_induct, simp)\napply (blast intro: Fin.consI Fin_mono [THEN [2] rev_subsetD])\ndone\n\n(* Induction principle for Finite(A), by Sidi Ehmety *)\nlemma Finite_induct [case_names 0 cons, induct set: Finite]:\n\"[| Finite(A); P(0);\n    !! x B.   [| Finite(B); x \\<notin> B; P(B) |] ==> P(cons(x, B)) |]\n ==> P(A)\"\napply (erule Finite_into_Fin [THEN Fin_induct])\napply (blast intro: Fin_into_Finite)+\ndone\n\n(*Sidi Ehmety.  The contrapositive says ~Finite(A) ==> ~Finite(A-{a}) *)\nlemma Diff_sing_Finite: \"Finite(A - {a}) ==> Finite(A)\"\napply (unfold Finite_def)\napply (case_tac \"a \\<in> A\")\napply (subgoal_tac [2] \"A-{a}=A\", auto)\napply (rule_tac x = \"succ (n) \" in bexI)\napply (subgoal_tac \"cons (a, A - {a}) = A & cons (n, n) = succ (n) \")\napply (drule_tac a = a and b = n in cons_eqpoll_cong)\napply (auto dest: mem_irrefl)\ndone\n\n(*Sidi Ehmety.  And the contrapositive of this says\n   [| ~Finite(A); Finite(B) |] ==> ~Finite(A-B) *)\nlemma Diff_Finite [rule_format]: \"Finite(B) ==> Finite(A-B) \\<longrightarrow> Finite(A)\"\napply (erule Finite_induct, auto)\napply (case_tac \"x \\<in> A\")\n apply (subgoal_tac [2] \"A-cons (x, B) = A - B\")\napply (subgoal_tac \"A - cons (x, B) = (A - B) - {x}\", simp)\napply (drule Diff_sing_Finite, auto)\ndone\n\nlemma Finite_RepFun: \"Finite(A) ==> Finite(RepFun(A,f))\"\nby (erule Finite_induct, simp_all)\n\nlemma Finite_RepFun_iff_lemma [rule_format]:\n     \"[|Finite(x); !!x y. f(x)=f(y) ==> x=y|]\n      ==> \\<forall>A. x = RepFun(A,f) \\<longrightarrow> Finite(A)\"\napply (erule Finite_induct)\n apply clarify\n apply (case_tac \"A=0\", simp)\n apply (blast del: allE, clarify)\napply (subgoal_tac \"\\<exists>z\\<in>A. x = f(z)\")\n prefer 2 apply (blast del: allE elim: equalityE, clarify)\napply (subgoal_tac \"B = {f(u) . u \\<in> A - {z}}\")\n apply (blast intro: Diff_sing_Finite)\napply (thin_tac \"\\<forall>A. P(A) \\<longrightarrow> Finite(A)\" for P)\napply (rule equalityI)\n apply (blast intro: elim: equalityE)\napply (blast intro: elim: equalityCE)\ndone\n\ntext\\<open>I don't know why, but if the premise is expressed using meta-connectives\nthen  the simplifier cannot prove it automatically in conditional rewriting.\\<close>\nlemma Finite_RepFun_iff:\n     \"(\\<forall>x y. f(x)=f(y) \\<longrightarrow> x=y) ==> Finite(RepFun(A,f)) \\<longleftrightarrow> Finite(A)\"\nby (blast intro: Finite_RepFun Finite_RepFun_iff_lemma [of _ f])\n\nlemma Finite_Pow: \"Finite(A) ==> Finite(Pow(A))\"\napply (erule Finite_induct)\napply (simp_all add: Pow_insert Finite_Un Finite_RepFun)\ndone\n\nlemma Finite_Pow_imp_Finite: \"Finite(Pow(A)) ==> Finite(A)\"\napply (subgoal_tac \"Finite({{x} . x \\<in> A})\")\n apply (simp add: Finite_RepFun_iff )\napply (blast intro: subset_Finite)\ndone\n\nlemma Finite_Pow_iff [iff]: \"Finite(Pow(A)) \\<longleftrightarrow> Finite(A)\"\nby (blast intro: Finite_Pow Finite_Pow_imp_Finite)\n\nlemma Finite_cardinal_iff:\n  assumes i: \"Ord(i)\" shows \"Finite(|i|) \\<longleftrightarrow> Finite(i)\"\n  by (auto simp add: Finite_def) (blast intro: eqpoll_trans eqpoll_sym Ord_cardinal_eqpoll [OF i])+\n\n\n(*Krzysztof Grabczewski's proof that the converse of a finite, well-ordered\n  set is well-ordered.  Proofs simplified by lcp. *)\n\nlemma nat_wf_on_converse_Memrel: \"n \\<in> nat ==> wf[n](converse(Memrel(n)))\"\nproof (induct n rule: nat_induct)\n  case 0 thus ?case by (blast intro: wf_onI)\nnext\n  case (succ x)\n  hence wfx: \"\\<And>Z. Z = 0 \\<or> (\\<exists>z\\<in>Z. \\<forall>y. z \\<in> y \\<and> z \\<in> x \\<and> y \\<in> x \\<and> z \\<in> x \\<longrightarrow> y \\<notin> Z)\"\n    by (simp add: wf_on_def wf_def)  \\<comment> \\<open>not easy to erase the duplicate \\<^term>\\<open>z \\<in> x\\<close>!\\<close>\n  show ?case\n    proof (rule wf_onI)\n      fix Z u\n      assume Z: \"u \\<in> Z\" \"\\<forall>z\\<in>Z. \\<exists>y\\<in>Z. \\<langle>y, z\\<rangle> \\<in> converse(Memrel(succ(x)))\"\n      show False \n        proof (cases \"x \\<in> Z\")\n          case True thus False using Z\n            by (blast elim: mem_irrefl mem_asym)\n          next\n          case False thus False using wfx [of Z] Z\n            by blast\n        qed\n    qed\nqed\n\nlemma nat_well_ord_converse_Memrel: \"n \\<in> nat ==> well_ord(n,converse(Memrel(n)))\"\napply (frule Ord_nat [THEN Ord_in_Ord, THEN well_ord_Memrel])\napply (simp add: well_ord_def tot_ord_converse nat_wf_on_converse_Memrel) \ndone\n\nlemma well_ord_converse:\n     \"[|well_ord(A,r);\n        well_ord(ordertype(A,r), converse(Memrel(ordertype(A, r)))) |]\n      ==> well_ord(A,converse(r))\"\napply (rule well_ord_Int_iff [THEN iffD1])\napply (frule ordermap_bij [THEN bij_is_inj, THEN well_ord_rvimage], assumption)\napply (simp add: rvimage_converse converse_Int converse_prod\n                 ordertype_ord_iso [THEN ord_iso_rvimage_eq])\ndone\n\nlemma ordertype_eq_n:\n  assumes r: \"well_ord(A,r)\" and A: \"A \\<approx> n\" and n: \"n \\<in> nat\"\n  shows \"ordertype(A,r) = n\"\nproof -\n  have \"ordertype(A,r) \\<approx> A\"\n    by (blast intro: bij_imp_eqpoll bij_converse_bij ordermap_bij r)\n  also have \"... \\<approx> n\" by (rule A)\n  finally have \"ordertype(A,r) \\<approx> n\" .\n  thus ?thesis\n    by (simp add: Ord_nat_eqpoll_iff Ord_ordertype n r)\nqed\n\nlemma Finite_well_ord_converse:\n    \"[| Finite(A);  well_ord(A,r) |] ==> well_ord(A,converse(r))\"\napply (unfold Finite_def)\napply (rule well_ord_converse, assumption)\napply (blast dest: ordertype_eq_n intro!: nat_well_ord_converse_Memrel)\ndone\n\nlemma nat_into_Finite: \"n \\<in> nat ==> Finite(n)\"\n  by (auto simp add: Finite_def intro: eqpoll_refl) \n\nlemma nat_not_Finite: \"~ Finite(nat)\"\nproof -\n  { fix n\n    assume n: \"n \\<in> nat\" \"nat \\<approx> n\"\n    have \"n \\<in> nat\"    by (rule n)\n    also have \"... = n\" using n\n      by (simp add: Ord_nat_eqpoll_iff Ord_nat)\n    finally have \"n \\<in> n\" .\n    hence False\n      by (blast elim: mem_irrefl)\n  }\n  thus ?thesis\n    by (auto simp add: Finite_def)\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/ZF/Cardinal.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256432832333, "lm_q2_score": 0.8397339656668286, "lm_q1q2_score": 0.7069095858342584}}
{"text": "\n(* Authors: Amine Chaieb & Florian Haftmann, TU Muenchen *)\n\nheader {* Falling factorials *}\n\ntheory Factorials\nimports Complex_Main Stirling\nbegin\n\nprimrec ffact :: \"nat \\<Rightarrow> 'a::comm_ring_1 \\<Rightarrow> 'a\"\nwhere\n  \"ffact 0 a = 1\"\n| \"ffact (Suc n) a = a * ffact n (a - 1)\"\n\nlemma ffact_0 [simp]:\n  \"ffact 0 = (\\<lambda>x. 1)\"\n  by (simp add: fun_eq_iff)\n\nlemma ffact_fact:\n  \"ffact n (of_nat n) = of_nat (fact n)\"\n  by (induct n) (simp_all add: algebra_simps of_nat_mult)\n\nlemma ffact_Suc:\n  \"ffact (Suc n) a = (a - of_nat n) * ffact n a\"\nproof (induct n arbitrary: a)\n  case 0 thus ?case by simp\nnext\n  case (Suc n a)\n  moreover have \"-2 + a = (a - 1) - 1\"\n    by simp\n  ultimately have hyp:\n    \"ffact (Suc n) (a - 1) = (a - 1 - of_nat n) * ffact n (a - 1)\"\n    by (simp only:)\n  have \"ffact (Suc (Suc n)) a = a * ffact (Suc n) (a - 1)\" by simp\n  also have \"\\<dots> = a * (ffact n (a - 1) * (a - of_nat (n + 1)))\"\n    by (simp only: hyp) (simp add: algebra_simps)\n  also have \"\\<dots> = ffact (Suc n) a * (a - of_nat (Suc n))\" by (simp add: algebra_simps)\n  finally have \"ffact (Suc (Suc n)) a = ffact (Suc n) a * (a - of_nat (Suc n))\" .\n  then show ?case by (simp add: mult.commute)\nqed\n\nlemma ffact_add_diff_assoc:\n  \"(a - of_nat n) * ffact n a + of_nat n * ffact n a = a * ffact n a\"\n  by (simp add: algebra_simps)\n\nlemma mult_ffact:\n  \"a * ffact n a = ffact (Suc n) a + of_nat n * ffact n a\"\nproof -\n  have \"ffact (Suc n) a + of_nat n * (ffact n a) = (a - of_nat n) * (ffact n a) + of_nat n * (ffact n a)\"\n    using ffact_Suc [of n] by auto\n  also have \"\\<dots> = a * ffact n a\" using ffact_add_diff_assoc by (simp add: algebra_simps)\n  finally show ?thesis by simp\nqed\n\nlemma of_int_ffact:\n  \"of_int (ffact n k) = ffact n (of_int k)\"\nproof (induct n arbitrary: k)\n  case 0 then show ?case by simp\nnext\n  case (Suc n k) then have \"of_int (ffact n (k - 1)) = ffact n (of_int (k - 1) :: 'a)\" .\n  then show ?case by simp\nqed\n\n\ntext {* Conversion of natural potences into falling factorials *}\n\nlemma monomial_ffact:\n  \"a ^ n = (\\<Sum>k = 0..n. of_nat (Stirling n k) * ffact k a)\"\nproof (rule sym, induct n)\n  case 0 then show ?case by simp\nnext\n  case (Suc n) \n  then have \"a ^ Suc n = a * (\\<Sum>k = 0..n. of_nat (Stirling n k) * ffact k a)\" \n    by simp\n  also have \"\\<dots> = (\\<Sum>k = 0..n. of_nat (Stirling n k) * (a * ffact k a))\"\n    by (simp add: setsum_right_distrib algebra_simps)\n  also have \"\\<dots> = (\\<Sum>k = 0..n. of_nat (Stirling n k) * ffact (Suc k) a) +\n    (\\<Sum>k = 0..n. of_nat (Stirling n k) * (of_nat k * ffact k a))\" \n    by (simp add: setsum.distrib algebra_simps mult_ffact)\n  also have \"\\<dots> = (\\<Sum>k = 0.. Suc n. of_nat (Stirling n k) * ffact (Suc k) a) + \n    (\\<Sum>k = 0..Suc n. of_nat ((Suc k) * (Stirling n (Suc k))) * (ffact (Suc k) a))\"\n  proof -\n    have \"(\\<Sum>k = 0..n. of_nat (Stirling n k) * (of_nat k * ffact k a)) =\n      (\\<Sum>k = 0..n+2. of_nat (Stirling n k) * (of_nat k * ffact k a))\" by simp\n    also have \"\\<dots> = (\\<Sum>k = Suc 0 .. Suc (Suc n). of_nat (Stirling n k) * (of_nat k * ffact k a)) \"\n      by (simp only: setsum_head_Suc [of 0 \"n + 2\"]) simp\n    also have \"\\<dots> = (\\<Sum>k = 0 .. Suc n. of_nat (Stirling n (Suc k)) * (of_nat (Suc k) * ffact (Suc k) a))\"\n      by (simp only: image_Suc_atLeastAtMost setsum_shift_bounds_cl_Suc_ivl)\n    also have \"\\<dots> = (\\<Sum>k = 0 .. Suc n. of_nat ((Suc k) * Stirling n (Suc k)) * ffact (Suc k) a)\"\n      by (simp only: of_nat_mult algebra_simps)\n    finally have \"(\\<Sum>k = 0..n. of_nat (Stirling n k) * (of_nat k * ffact k a)) = \n      (\\<Sum>k = 0..Suc n. of_nat (Suc k * Stirling n (Suc k)) * ffact (Suc k) a)\" \n      by simp\n    then show ?thesis by simp\n  qed\n  also have \"\\<dots> = (\\<Sum>k = 0..n. of_nat (Stirling (Suc n) (Suc k)) * ffact (Suc k) a)\"\n    by (simp add: algebra_simps setsum.distrib)\n  also have \"\\<dots> = (\\<Sum>k = Suc 0..Suc n. of_nat (Stirling (Suc n) k) * ffact k a)\"\n    by (simp only: image_Suc_atLeastAtMost setsum_shift_bounds_cl_Suc_ivl)\n  also have \"\\<dots> = (\\<Sum>k = 0..Suc n. of_nat (Stirling (Suc n) k) * ffact k a)\"\n    by (simp only: setsum_head_Suc [of \"0\" \"Suc n\"]) simp\n  finally show ?case by simp\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/Discrete_Summation/Factorials.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339676722393, "lm_q2_score": 0.8418256393148982, "lm_q1q2_score": 0.7069095841901188}}
{"text": "theory Exercise6\n  imports Main\nbegin\n\nfun elems :: \"'a list \\<Rightarrow> 'a set\" where\n\"elems [] = {}\" |\n\"elems (a # as) = {x. x=a \\<or> x \\<in> (elems as)}\"\n\ntheorem \"\n  x \\<in> elems xs\n  \\<Longrightarrow> \\<exists> ys zs. xs = ys @ x # zs\n    \\<and> x \\<notin> elems ys\n\"\nproof (induction xs)\n  case Nil thus ?case by simp\nnext\n  case (Cons a xs)\n  hence \"x = a \\<or> (x \\<noteq> a \\<and> x \\<in> elems xs)\" by auto\n  thus ?case\n  proof\n    assume \"x = a\"\n    hence \"a # xs = [] @ x # xs \\<and> x \\<notin> elems []\" by simp\n    thus ?thesis by fastforce\n  next\n    assume \"x \\<noteq> a \\<and> x \\<in> elems xs\"\n    hence \"\n      \\<exists> ys zs. a # xs = (a # ys) @ x # zs\n      \\<and> x \\<notin> elems (a # ys)\n    \" using local.Cons.IH by simp\n    thus ?thesis by fastforce\n  qed\nqed\n\nend\n", "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/ch5/Exercise6.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8856314738181875, "lm_q2_score": 0.798186775339273, "lm_q1q2_score": 0.7068993302259069}}
{"text": "(*  Title:      Well-Quasi-Orders\n    Author:     Christian Sternagel <c.sternagel@gmail.com>\n    Maintainer: Christian Sternagel\n    License:    LGPL\n*)\n\nsection \\<open>Binary Predicates Restricted to Elements of a Given Set\\<close>\n\ntheory Restricted_Predicates\nimports Main\nbegin\n\ntext \\<open>\n  A subset \\<open>C\\<close> of \\<open>A\\<close> is a \\emph{chain} on \\<open>A\\<close> (w.r.t.\\ \\<open>P\\<close>)\n  iff for all pairs of elements of \\<open>C\\<close>, one is less than or equal\n  to the other one.\n\\<close>\nabbreviation \"chain_on P C A \\<equiv> pred_on.chain A P C\"\nlemmas chain_on_def = pred_on.chain_def\n\nlemma chain_on_subset:\n  \"A \\<subseteq> B \\<Longrightarrow> chain_on P C A \\<Longrightarrow> chain_on P C B\"\nby (force simp: chain_on_def)\n\nlemma chain_on_imp_subset:\n  \"chain_on P C A \\<Longrightarrow> C \\<subseteq> A\"\nby (simp add: chain_on_def)\n\nlemma subchain_on:\n  assumes \"C \\<subseteq> D\" and \"chain_on P D A\"\n  shows \"chain_on P C A\"\nusing assms by (auto simp: chain_on_def)\n\ndefinition restrict_to :: \"('a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> 'a set \\<Rightarrow> ('a \\<Rightarrow> 'a \\<Rightarrow> bool)\" where\n  \"restrict_to P A = (\\<lambda>x y. x \\<in> A \\<and> y \\<in> A \\<and> P x y)\"\n\ndefinition reflp_on :: \"('a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> 'a set \\<Rightarrow> bool\" where\n  \"reflp_on P A \\<longleftrightarrow> (\\<forall>a\\<in>A. P a a)\"\n\ndefinition transp_on :: \"('a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> 'a set \\<Rightarrow> bool\" where\n  \"transp_on P A \\<longleftrightarrow> (\\<forall>x\\<in>A. \\<forall>y\\<in>A. \\<forall>z\\<in>A. P x y \\<and> P y z \\<longrightarrow> P x z)\"\n\ndefinition total_on :: \"('a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> 'a set \\<Rightarrow> bool\" where\n  \"total_on P A \\<longleftrightarrow> (\\<forall>x\\<in>A. \\<forall>y\\<in>A. x = y \\<or> P x y \\<or> P y x)\"\n\nabbreviation \"strict P \\<equiv> \\<lambda>x y. P x y \\<and> \\<not> (P y x)\"\n\nabbreviation \"incomparable P \\<equiv> \\<lambda>x y. \\<not> P x y \\<and> \\<not> P y x\"\n\nabbreviation \"antichain_on P f A \\<equiv> \\<forall>(i::nat) j. f i \\<in> A \\<and> (i < j \\<longrightarrow> incomparable P (f i) (f j))\"\n\nlemma strict_reflclp_conv [simp]:\n  \"strict (P\\<^sup>=\\<^sup>=) = strict P\" by auto\n\nlemma reflp_onI [Pure.intro]:\n  \"(\\<And>a. a \\<in> A \\<Longrightarrow> P a a) \\<Longrightarrow> reflp_on P A\"\n  unfolding reflp_on_def by blast\n\nlemma transp_onI [Pure.intro]:\n  \"(\\<And>x y z. \\<lbrakk>x \\<in> A; y \\<in> A; z \\<in> A; P x y; P y z\\<rbrakk> \\<Longrightarrow> P x z) \\<Longrightarrow> transp_on P A\"\n  unfolding transp_on_def by blast\n\nlemma total_onI [Pure.intro]:\n  \"(\\<And>x y. \\<lbrakk>x \\<in> A; y \\<in> A\\<rbrakk> \\<Longrightarrow> x = y \\<or> P x y \\<or> P y x) \\<Longrightarrow> total_on P A\"\n  unfolding total_on_def by blast\n\nlemma reflp_on_reflclp_simp [simp]:\n  assumes \"reflp_on P A\" and \"a \\<in> A\" and \"b \\<in> A\"\n  shows \"P\\<^sup>=\\<^sup>= a b = P a b\"\n  using assms by (auto simp: reflp_on_def)\n\nlemma reflp_on_reflclp:\n  \"reflp_on (P\\<^sup>=\\<^sup>=) A\"\n  by (auto simp: reflp_on_def)\n\nlemma reflp_on_converse_simp [simp]:\n  \"reflp_on P\\<inverse>\\<inverse> A \\<longleftrightarrow> reflp_on P A\"\n  by (auto simp: reflp_on_def)\n\nlemma transp_on_converse:\n  \"transp_on P A \\<Longrightarrow> transp_on P\\<inverse>\\<inverse> A\"\n  unfolding transp_on_def by blast\n\nlemma transp_on_converse_simp [simp]:\n  \"transp_on P\\<inverse>\\<inverse> A \\<longleftrightarrow> transp_on P A\"\n  unfolding transp_on_def by blast\n\nlemma transp_on_reflclp:\n  \"transp_on P A \\<Longrightarrow> transp_on P\\<^sup>=\\<^sup>= A\"\n  unfolding transp_on_def by blast\n\nlemma transp_on_strict:\n  \"transp_on P A \\<Longrightarrow> transp_on (strict P) A\"\n  unfolding transp_on_def by blast\n\nlemma reflp_on_subset:\n  \"A \\<subseteq> B \\<Longrightarrow> reflp_on P B \\<Longrightarrow> reflp_on P A\"\n  by (auto simp: reflp_on_def)\n\nlemma transp_on_subset:\n  \"A \\<subseteq> B \\<Longrightarrow> transp_on P B \\<Longrightarrow> transp_on P A\"\n  by (auto simp: transp_on_def)\n\ndefinition wfp_on :: \"('a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> 'a set \\<Rightarrow> bool\"\nwhere\n  \"wfp_on P A \\<longleftrightarrow> \\<not> (\\<exists>f. \\<forall>i. f i \\<in> A \\<and> P (f (Suc i)) (f i))\"\n\ndefinition inductive_on :: \"('a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> 'a set \\<Rightarrow> bool\" where\n  \"inductive_on P A \\<longleftrightarrow> (\\<forall>Q. (\\<forall>y\\<in>A. (\\<forall>x\\<in>A. P x y \\<longrightarrow> Q x) \\<longrightarrow> Q y) \\<longrightarrow> (\\<forall>x\\<in>A. Q x))\"\n\nlemma inductive_onI [Pure.intro]:\n  assumes \"\\<And>Q x. \\<lbrakk>x \\<in> A; (\\<And>y. \\<lbrakk>y \\<in> A; \\<And>x. \\<lbrakk>x \\<in> A; P x y\\<rbrakk> \\<Longrightarrow> Q x\\<rbrakk> \\<Longrightarrow> Q y)\\<rbrakk> \\<Longrightarrow>  Q x\"\n  shows \"inductive_on P A\"\n  using assms unfolding inductive_on_def by metis\n\ntext \\<open>\n  If @{term P} is well-founded on @{term A} then every non-empty subset @{term Q} of @{term A} has a\n  minimal element @{term z} w.r.t. @{term P}, i.e., all elements that are @{term P}-smaller than\n  @{term z} are not in @{term Q}.\n\\<close>\nlemma wfp_on_imp_minimal:\n  assumes \"wfp_on P A\"\n  shows \"\\<forall>Q x. x \\<in> Q \\<and> Q \\<subseteq> A \\<longrightarrow> (\\<exists>z\\<in>Q. \\<forall>y. P y z \\<longrightarrow> y \\<notin> Q)\"\nproof (rule ccontr)\n  assume \"\\<not> ?thesis\"\n  then obtain Q x where *: \"x \\<in> Q\" \"Q \\<subseteq> A\"\n    and \"\\<forall>z. \\<exists>y. z \\<in> Q \\<longrightarrow> P y z \\<and> y \\<in> Q\" by metis\n  from choice [OF this(3)] obtain f\n    where **: \"\\<forall>x\\<in>Q. P (f x) x \\<and> f x \\<in> Q\" by blast\n  let ?S = \"\\<lambda>i. (f ^^ i) x\"\n  have ***: \"\\<forall>i. ?S i \\<in> Q\"\n  proof\n    fix i show \"?S i \\<in> Q\" by (induct i) (auto simp: * **)\n  qed\n  then have \"\\<forall>i. ?S i \\<in> A\" using * by blast\n  moreover have \"\\<forall>i. P (?S (Suc i)) (?S i)\"\n  proof\n    fix i show \"P (?S (Suc i)) (?S i)\"\n      by (induct i) (auto simp: * ** ***)\n  qed\n  ultimately have \"\\<forall>i. ?S i \\<in> A \\<and> P (?S (Suc i)) (?S i)\" by blast\n  with assms(1) show False\n    unfolding wfp_on_def by fast\nqed\n\nlemma minimal_imp_inductive_on:\n  assumes \"\\<forall>Q x. x \\<in> Q \\<and> Q \\<subseteq> A \\<longrightarrow> (\\<exists>z\\<in>Q. \\<forall>y. P y z \\<longrightarrow> y \\<notin> Q)\"\n  shows \"inductive_on P A\"\nproof (rule ccontr)\n  assume \"\\<not> ?thesis\"\n  then obtain Q x\n    where *: \"\\<forall>y\\<in>A. (\\<forall>x\\<in>A. P x y \\<longrightarrow> Q x) \\<longrightarrow> Q y\"\n    and **: \"x \\<in> A\" \"\\<not> Q x\"\n    by (auto simp: inductive_on_def)\n  let ?Q = \"{x\\<in>A. \\<not> Q x}\"\n  from ** have \"x \\<in> ?Q\" by auto\n  moreover have \"?Q \\<subseteq> A\" by auto\n  ultimately obtain z where \"z \\<in> ?Q\"\n    and min: \"\\<forall>y. P y z \\<longrightarrow> y \\<notin> ?Q\"\n    using assms [THEN spec [of _ ?Q], THEN spec [of _ x]] by blast\n  from \\<open>z \\<in> ?Q\\<close> have \"z \\<in> A\" and \"\\<not> Q z\" by auto\n  with * obtain y where \"y \\<in> A\" and \"P y z\" and \"\\<not> Q y\" by auto\n  then have \"y \\<in> ?Q\" by auto\n  with \\<open>P y z\\<close> and min show False by auto\nqed\n\nlemmas wfp_on_imp_inductive_on =\n  wfp_on_imp_minimal [THEN minimal_imp_inductive_on]\n\nlemma inductive_on_induct [consumes 2, case_names less, induct pred: inductive_on]:\n  assumes \"inductive_on P A\" and \"x \\<in> A\"\n    and \"\\<And>y. \\<lbrakk> y \\<in> A; \\<And>x. \\<lbrakk> x \\<in> A; P x y \\<rbrakk> \\<Longrightarrow> Q x \\<rbrakk> \\<Longrightarrow> Q y\"\n  shows \"Q x\"\n  using assms unfolding inductive_on_def by metis\n\nlemma inductive_on_imp_wfp_on:\n  assumes \"inductive_on P A\"\n  shows \"wfp_on P A\"\nproof -\n  let ?Q = \"\\<lambda>x. \\<not> (\\<exists>f. f 0 = x \\<and> (\\<forall>i. f i \\<in> A \\<and> P (f (Suc i)) (f i)))\"\n  { fix x assume \"x \\<in> A\"\n    with assms have \"?Q x\"\n    proof (induct rule: inductive_on_induct)\n      fix y assume \"y \\<in> A\" and IH: \"\\<And>x. x \\<in> A \\<Longrightarrow> P x y \\<Longrightarrow> ?Q x\"\n      show \"?Q y\"\n      proof (rule ccontr)\n        assume \"\\<not> ?Q y\"\n        then obtain f where *: \"f 0 = y\"\n          \"\\<forall>i. f i \\<in> A \\<and> P (f (Suc i)) (f i)\" by auto\n        then have \"P (f (Suc 0)) (f 0)\" and \"f (Suc 0) \\<in> A\" by auto\n        with IH and * have \"?Q (f (Suc 0))\" by auto\n        with * show False by auto\n      qed\n    qed }\n  then show ?thesis unfolding wfp_on_def by blast\nqed\n\ndefinition antisymp_on :: \"('a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> 'a set \\<Rightarrow> bool\" where\n  \"antisymp_on P A \\<longleftrightarrow> (\\<forall>a\\<in>A. \\<forall>b\\<in>A. P a b \\<and> P b a \\<longrightarrow> a = b)\"\n\nlemma antisymp_onI [Pure.intro]:\n  \"(\\<And>a b. \\<lbrakk>a \\<in> A; b \\<in> A; P a b; P b a\\<rbrakk> \\<Longrightarrow> a = b) \\<Longrightarrow> antisymp_on P A\"\n  by (auto simp: antisymp_on_def)\n\nlemma antisymp_on_reflclp [simp]:\n  \"antisymp_on P\\<^sup>=\\<^sup>= A = antisymp_on P A\"\n  by (auto simp: antisymp_on_def)\n\ndefinition qo_on :: \"('a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> 'a set \\<Rightarrow> bool\" where\n  \"qo_on P A \\<longleftrightarrow> reflp_on P A \\<and> transp_on P A\"\n\ndefinition irreflp_on :: \"('a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> 'a set \\<Rightarrow> bool\" where\n  \"irreflp_on P A \\<longleftrightarrow> (\\<forall>a\\<in>A. \\<not> P a a)\"\n\ndefinition po_on :: \"('a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> 'a set \\<Rightarrow> bool\" where\n  \"po_on P A \\<longleftrightarrow> (irreflp_on P A \\<and> transp_on P A)\"\n\nlemma po_onI [Pure.intro]:\n  \"\\<lbrakk>irreflp_on P A; transp_on P A\\<rbrakk> \\<Longrightarrow> po_on P A\"\n  by (auto simp: po_on_def)\n\nlemma irreflp_onI [Pure.intro]:\n  \"(\\<And>a. a \\<in> A \\<Longrightarrow> \\<not> P a a) \\<Longrightarrow> irreflp_on P A\"\n  unfolding irreflp_on_def by blast\n\nlemma irreflp_on_converse:\n  \"irreflp_on P A \\<Longrightarrow> irreflp_on P\\<inverse>\\<inverse> A\"\n  unfolding irreflp_on_def by blast\n\nlemma irreflp_on_converse_simp [simp]:\n  \"irreflp_on P\\<inverse>\\<inverse> A \\<longleftrightarrow> irreflp_on P A\"\n  by (auto simp: irreflp_on_def)\n\nlemma po_on_converse_simp [simp]:\n  \"po_on P\\<inverse>\\<inverse> A \\<longleftrightarrow> po_on P A\"\n  by (simp add: po_on_def)\n\nlemma po_on_imp_qo_on:\n  \"po_on P A \\<Longrightarrow> qo_on (P\\<^sup>=\\<^sup>=) A\"\n  unfolding po_on_def qo_on_def\n  by (metis reflp_on_reflclp transp_on_reflclp)\n\nlemma po_on_imp_irreflp_on:\n  \"po_on P A \\<Longrightarrow> irreflp_on P A\"\n  by (auto simp: po_on_def)\n\nlemma po_on_imp_transp_on:\n  \"po_on P A \\<Longrightarrow> transp_on P A\"\n  by (auto simp: po_on_def)\n\nlemma irreflp_on_subset:\n  assumes \"A \\<subseteq> B\" and \"irreflp_on P B\"\n  shows \"irreflp_on P A\"\n  using assms by (auto simp: irreflp_on_def)\n\nlemma po_on_subset:\n  assumes \"A \\<subseteq> B\" and \"po_on P B\"\n  shows \"po_on P A\"\n  using transp_on_subset and irreflp_on_subset and assms\n  unfolding po_on_def by blast\n\nlemma transp_on_irreflp_on_imp_antisymp_on:\n  assumes \"transp_on P A\" and \"irreflp_on P A\"\n  shows \"antisymp_on (P\\<^sup>=\\<^sup>=) A\"\nproof\n  fix a b assume \"a \\<in> A\"\n    and \"b \\<in> A\" and \"P\\<^sup>=\\<^sup>= a b\" and \"P\\<^sup>=\\<^sup>= b a\"\n  show \"a = b\"\n  proof (rule ccontr)\n    assume \"a \\<noteq> b\"\n    with \\<open>P\\<^sup>=\\<^sup>= a b\\<close> and \\<open>P\\<^sup>=\\<^sup>= b a\\<close> have \"P a b\" and \"P b a\" by auto\n    with \\<open>transp_on P A\\<close> and \\<open>a \\<in> A\\<close> and \\<open>b \\<in> A\\<close> have \"P a a\" unfolding transp_on_def by blast\n    with \\<open>irreflp_on P A\\<close> and \\<open>a \\<in> A\\<close> show False unfolding irreflp_on_def by blast\n  qed\nqed\n\nlemma po_on_imp_antisymp_on:\n  assumes \"po_on P A\"\n  shows \"antisymp_on P A\"\nusing transp_on_irreflp_on_imp_antisymp_on [of P A] and assms by (auto simp: po_on_def)\n\nlemma strict_reflclp [simp]:\n  assumes \"x \\<in> A\" and \"y \\<in> A\"\n    and \"transp_on P A\" and \"irreflp_on P A\"\n  shows \"strict (P\\<^sup>=\\<^sup>=) x y = P x y\"\n  using assms unfolding transp_on_def irreflp_on_def\n  by blast\n\nlemma qo_on_imp_reflp_on:\n  \"qo_on P A \\<Longrightarrow> reflp_on P A\"\n  by (auto simp: qo_on_def)\n\nlemma qo_on_imp_transp_on:\n  \"qo_on P A \\<Longrightarrow> transp_on P A\"\n  by (auto simp: qo_on_def)\n\nlemma qo_on_subset:\n  \"A \\<subseteq> B \\<Longrightarrow> qo_on P B \\<Longrightarrow> qo_on P A\"\n  unfolding qo_on_def\n  using reflp_on_subset\n    and transp_on_subset by blast\n\ntext \\<open>\n  Quasi-orders are instances of the @{class preorder} class.\n\\<close>\nlemma qo_on_UNIV_conv:\n  \"qo_on P UNIV \\<longleftrightarrow> class.preorder P (strict P)\" (is \"?lhs = ?rhs\")\nproof\n  assume \"?lhs\" then show \"?rhs\"\n    unfolding qo_on_def class.preorder_def\n    using qo_on_imp_reflp_on [of P UNIV]\n      and qo_on_imp_transp_on [of P UNIV]\n    by (auto simp: reflp_on_def) (unfold transp_on_def, blast)\nnext\n  assume \"?rhs\" then show \"?lhs\"\n    unfolding class.preorder_def\n    by (auto simp: qo_on_def reflp_on_def transp_on_def)\nqed\n\nlemma wfp_on_iff_inductive_on:\n  \"wfp_on P A \\<longleftrightarrow> inductive_on P A\"\n  by (blast intro: inductive_on_imp_wfp_on wfp_on_imp_inductive_on)\n\nlemma wfp_on_iff_minimal:\n  \"wfp_on P A \\<longleftrightarrow> (\\<forall>Q x.\n     x \\<in> Q \\<and> Q \\<subseteq> A \\<longrightarrow>\n     (\\<exists>z\\<in>Q. \\<forall>y. P y z \\<longrightarrow> y \\<notin> Q))\"\n  using wfp_on_imp_minimal [of P A]\n    and minimal_imp_inductive_on [of A P]\n    and inductive_on_imp_wfp_on [of P A]\n    by blast\n\ntext \\<open>\n  Every non-empty well-founded set @{term A} has a minimal element, i.e., an element that is not\n  greater than any other element.\n\\<close>\nlemma wfp_on_imp_has_min_elt:\n  assumes \"wfp_on P A\" and \"A \\<noteq> {}\"\n  shows \"\\<exists>x\\<in>A. \\<forall>y\\<in>A. \\<not> P y x\"\n  using assms unfolding wfp_on_iff_minimal by force\n\nlemma wfp_on_induct [consumes 2, case_names less, induct pred: wfp_on]:\n  assumes \"wfp_on P A\" and \"x \\<in> A\"\n    and \"\\<And>y. \\<lbrakk> y \\<in> A; \\<And>x. \\<lbrakk> x \\<in> A; P x y \\<rbrakk> \\<Longrightarrow> Q x \\<rbrakk> \\<Longrightarrow> Q y\"\n  shows \"Q x\"\n  using assms and inductive_on_induct [of P A x]\n  unfolding wfp_on_iff_inductive_on by blast\n\nlemma wfp_on_UNIV [simp]:\n  \"wfp_on P UNIV \\<longleftrightarrow> wfP P\"\n  unfolding wfp_on_iff_inductive_on inductive_on_def wfP_def wf_def by force\n\n\nsubsection \\<open>Measures on Sets (Instead of Full Types)\\<close>\n\ndefinition\n  inv_image_betw ::\n    \"('b \\<Rightarrow> 'b \\<Rightarrow> bool) \\<Rightarrow> ('a \\<Rightarrow> 'b) \\<Rightarrow> 'a set \\<Rightarrow> 'b set \\<Rightarrow> ('a \\<Rightarrow> 'a \\<Rightarrow> bool)\"\nwhere\n  \"inv_image_betw P f A B = (\\<lambda>x y. x \\<in> A \\<and> y \\<in> A \\<and> f x \\<in> B \\<and> f y \\<in> B \\<and> P (f x) (f y))\"\n\ndefinition\n  measure_on :: \"('a \\<Rightarrow> nat) \\<Rightarrow> 'a set \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> bool\"\nwhere\n  \"measure_on f A = inv_image_betw (<) f A UNIV\"\n\nlemma in_inv_image_betw [simp]:\n  \"inv_image_betw P f A B x y \\<longleftrightarrow> x \\<in> A \\<and> y \\<in> A \\<and> f x \\<in> B \\<and> f y \\<in> B \\<and> P (f x) (f y)\"\n  by (auto simp: inv_image_betw_def)\n\nlemma in_measure_on [simp, code_unfold]:\n  \"measure_on f A x y \\<longleftrightarrow> x \\<in> A \\<and> y \\<in> A \\<and> f x < f y\"\n  by (simp add: measure_on_def)\n\nlemma wfp_on_inv_image_betw [simp, intro!]:\n  assumes \"wfp_on P B\"\n  shows \"wfp_on (inv_image_betw P f A B) A\" (is \"wfp_on ?P A\")\nproof (rule ccontr)\n  assume \"\\<not> ?thesis\"\n  then obtain g where \"\\<forall>i. g i \\<in> A \\<and> ?P (g (Suc i)) (g i)\" by (auto simp: wfp_on_def)\n  with assms show False by (auto simp: wfp_on_def)\nqed\n\nlemma wfp_less:\n  \"wfp_on (<) (UNIV :: nat set)\"\n  using wf_less by (auto simp: wfP_def)\n\nlemma wfp_on_measure_on [iff]:\n  \"wfp_on (measure_on f A) A\"\n  unfolding measure_on_def\n  by (rule wfp_less [THEN wfp_on_inv_image_betw])\n\nlemma wfp_on_mono:\n  \"A \\<subseteq> B \\<Longrightarrow> (\\<And>x y. x \\<in> A \\<Longrightarrow> y \\<in> A \\<Longrightarrow> P x y \\<Longrightarrow> Q x y) \\<Longrightarrow> wfp_on Q B \\<Longrightarrow> wfp_on P A\"\n  unfolding wfp_on_def by (metis subsetD)\n\nlemma wfp_on_subset:\n  \"A \\<subseteq> B \\<Longrightarrow> wfp_on P B \\<Longrightarrow> wfp_on P A\"\n  using wfp_on_mono by blast\n\nlemma restrict_to_iff [iff]:\n  \"restrict_to P A x y \\<longleftrightarrow> x \\<in> A \\<and> y \\<in> A \\<and> P x y\"\n  by (simp add: restrict_to_def)\n\nlemma wfp_on_restrict_to [simp]:\n  \"wfp_on (restrict_to P A) A = wfp_on P A\"\n  by (auto simp: wfp_on_def)\n\nlemma irreflp_on_strict [simp, intro]:\n  \"irreflp_on (strict P) A\"\n  by (auto simp: irreflp_on_def)\n\nlemma transp_on_map':\n  assumes \"transp_on Q B\"\n    and \"g ` A \\<subseteq> B\"\n    and \"h ` A \\<subseteq> B\"\n    and \"\\<And>x. x \\<in> A \\<Longrightarrow> Q\\<^sup>=\\<^sup>= (h x) (g x)\"\n  shows \"transp_on (\\<lambda>x y. Q (g x) (h y)) A\"\n  using assms unfolding transp_on_def\n  by auto (metis imageI subsetD)\n\nlemma transp_on_map:\n  assumes \"transp_on Q B\"\n    and \"h ` A \\<subseteq> B\"\n  shows \"transp_on (\\<lambda>x y. Q (h x) (h y)) A\"\n  using transp_on_map' [of Q B h A h, simplified, OF assms] by blast\n\nlemma irreflp_on_map:\n  assumes \"irreflp_on Q B\"\n    and \"h ` A \\<subseteq> B\"\n  shows \"irreflp_on (\\<lambda>x y. Q (h x) (h y)) A\"\n  using assms unfolding irreflp_on_def by auto\n\nlemma po_on_map:\n  assumes \"po_on Q B\"\n    and \"h ` A \\<subseteq> B\"\n  shows \"po_on (\\<lambda>x y. Q (h x) (h y)) A\"\n  using assms and transp_on_map and irreflp_on_map\n  unfolding po_on_def by auto\n\nlemma chain_transp_on_less:\n  assumes \"\\<forall>i. f i \\<in> A \\<and> P (f i) (f (Suc i))\" and \"transp_on P A\" and \"i < j\"\n  shows \"P (f i) (f j)\"\nusing \\<open>i < j\\<close>\nproof (induct j)\n  case 0 then show ?case by simp\nnext\n  case (Suc j)\n  show ?case\n  proof (cases \"i = j\")\n    case True\n    with Suc show ?thesis using assms(1) by simp\n  next\n    case False\n    with Suc have \"P (f i) (f j)\" by force\n    moreover from assms have \"P (f j) (f (Suc j))\" by auto\n    ultimately show ?thesis using assms(1, 2) unfolding transp_on_def by blast\n  qed\nqed\n\nlemma wfp_on_imp_irreflp_on:\n  assumes \"wfp_on P A\"\n  shows \"irreflp_on P A\"\nproof\n  fix x\n  assume \"x \\<in> A\"\n  show \"\\<not> P x x\"\n  proof\n    let ?f = \"\\<lambda>_. x\"\n    assume \"P x x\"\n    then have \"\\<forall>i. P (?f (Suc i)) (?f i)\" by blast\n    with \\<open>x \\<in> A\\<close> have \"\\<not> wfp_on P A\" by (auto simp: wfp_on_def)\n    with assms show False by contradiction\n  qed\nqed\n\ninductive\n  accessible_on :: \"('a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> 'a set \\<Rightarrow> 'a \\<Rightarrow> bool\"\n  for P and A\nwhere\n  accessible_onI [Pure.intro]:\n    \"\\<lbrakk>x \\<in> A; \\<And>y. \\<lbrakk>y \\<in> A; P y x\\<rbrakk> \\<Longrightarrow> accessible_on P A y\\<rbrakk> \\<Longrightarrow> accessible_on P A x\"\n\nlemma accessible_on_imp_mem:\n  assumes \"accessible_on P A a\"\n  shows \"a \\<in> A\"\n  using assms by (induct) auto\n\nlemma accessible_on_induct [consumes 1, induct pred: accessible_on]:\n  assumes *: \"accessible_on P A a\"\n    and IH: \"\\<And>x. \\<lbrakk>accessible_on P A x; \\<And>y. \\<lbrakk>y \\<in> A; P y x\\<rbrakk> \\<Longrightarrow> Q y\\<rbrakk> \\<Longrightarrow> Q x\"\n  shows \"Q a\"\n  by (rule * [THEN accessible_on.induct]) (auto intro: IH accessible_onI)\n\nlemma accessible_on_downward:\n  \"accessible_on P A b \\<Longrightarrow> a \\<in> A \\<Longrightarrow> P a b \\<Longrightarrow> accessible_on P A a\"\n  by (cases rule: accessible_on.cases) fast\n\nlemma accessible_on_restrict_to_downwards:\n  assumes \"(restrict_to P A)\\<^sup>+\\<^sup>+ a b\" and \"accessible_on P A b\"\n  shows \"accessible_on P A a\"\n  using assms by (induct) (auto dest: accessible_on_imp_mem accessible_on_downward)\n\nlemma accessible_on_imp_inductive_on:\n  assumes \"\\<forall>x\\<in>A. accessible_on P A x\"\n  shows \"inductive_on P A\"\nproof\n  fix Q x\n  assume \"x \\<in> A\"\n    and *: \"\\<And>y. \\<lbrakk>y \\<in> A; \\<And>x. \\<lbrakk>x \\<in> A; P x y\\<rbrakk> \\<Longrightarrow> Q x\\<rbrakk> \\<Longrightarrow> Q y\"\n  with assms have \"accessible_on P A x\" by auto\n  then show \"Q x\"\n  proof (induct)\n    case (1 z)\n    then have \"z \\<in> A\" by (blast dest: accessible_on_imp_mem)\n    show ?case by (rule *) fact+\n  qed\nqed\n\nlemmas accessible_on_imp_wfp_on = accessible_on_imp_inductive_on [THEN inductive_on_imp_wfp_on]\n\nlemma wfp_on_tranclp_imp_wfp_on:\n  assumes \"wfp_on (P\\<^sup>+\\<^sup>+) A\"\n  shows \"wfp_on P A\"\n  by (rule ccontr) (insert assms, auto simp: wfp_on_def)\n\nlemma inductive_on_imp_accessible_on:\n  assumes \"inductive_on P A\"\n  shows \"\\<forall>x\\<in>A. accessible_on P A x\"\nproof\n  fix x\n  assume \"x \\<in> A\"\n  with assms show \"accessible_on P A x\"\n    by (induct) (auto intro: accessible_onI)\nqed\n\nlemma inductive_on_accessible_on_conv:\n  \"inductive_on P A \\<longleftrightarrow> (\\<forall>x\\<in>A. accessible_on P A x)\"\n  using inductive_on_imp_accessible_on\n    and accessible_on_imp_inductive_on\n    by blast\n\nlemmas wfp_on_imp_accessible_on =\n  wfp_on_imp_inductive_on [THEN inductive_on_imp_accessible_on]\n\nlemma wfp_on_accessible_on_iff:\n  \"wfp_on P A \\<longleftrightarrow> (\\<forall>x\\<in>A. accessible_on P A x)\"\n  by (blast dest: wfp_on_imp_accessible_on accessible_on_imp_wfp_on)\n\nlemma accessible_on_tranclp:\n  assumes \"accessible_on P A x\"\n  shows \"accessible_on ((restrict_to P A)\\<^sup>+\\<^sup>+) A x\"\n    (is \"accessible_on ?P A x\")\n  using assms\nproof (induct)\n  case (1 x)\n  then have \"x \\<in> A\" by (blast dest: accessible_on_imp_mem)\n  then show ?case\n  proof (rule accessible_onI)\n    fix y\n    assume \"y \\<in> A\"\n    assume \"?P y x\"\n    then show \"accessible_on ?P A y\"\n    proof (cases)\n      assume \"restrict_to P A y x\"\n      with 1 and \\<open>y \\<in> A\\<close> show ?thesis by blast\n    next\n      fix z\n      assume \"?P y z\" and \"restrict_to P A z x\"\n      with 1 have \"accessible_on ?P A z\" by (auto simp: restrict_to_def)\n      from accessible_on_downward [OF this \\<open>y \\<in> A\\<close> \\<open>?P y z\\<close>]\n        show ?thesis .\n    qed\n  qed\nqed\n\nlemma wfp_on_restrict_to_tranclp:\n  assumes \"wfp_on P A\"\n  shows \"wfp_on ((restrict_to P A)\\<^sup>+\\<^sup>+) A\"\n  using wfp_on_imp_accessible_on [OF assms]\n    and accessible_on_tranclp [of P A]\n    and accessible_on_imp_wfp_on [of A \"(restrict_to P A)\\<^sup>+\\<^sup>+\"]\n    by blast\n\nlemma wfp_on_restrict_to_tranclp':\n  assumes \"wfp_on (restrict_to P A)\\<^sup>+\\<^sup>+ A\"\n  shows \"wfp_on P A\"\n  by (rule ccontr) (insert assms, auto simp: wfp_on_def)\n\nlemma wfp_on_restrict_to_tranclp_wfp_on_conv:\n  \"wfp_on (restrict_to P A)\\<^sup>+\\<^sup>+ A \\<longleftrightarrow> wfp_on P A\"\n  using wfp_on_restrict_to_tranclp [of P A]\n    and wfp_on_restrict_to_tranclp' [of P A]\n    by blast\n\nlemma tranclp_idemp [simp]:\n  \"(P\\<^sup>+\\<^sup>+)\\<^sup>+\\<^sup>+ = P\\<^sup>+\\<^sup>+\" (is \"?l = ?r\")\nproof (intro ext)\n  fix x y\n  show \"?l x y = ?r x y\"\n  proof\n    assume \"?l x y\" then show \"?r x y\" by (induct) auto\n  next\n    assume \"?r x y\" then show \"?l x y\" by (induct) auto\n  qed\nqed\n\n(*TODO: move the following 3 lemmas to Transitive_Closure?*)\nlemma stepfun_imp_tranclp:\n  assumes \"f 0 = x\" and \"f (Suc n) = z\"\n    and \"\\<forall>i\\<le>n. P (f i) (f (Suc i))\"\n  shows \"P\\<^sup>+\\<^sup>+ x z\"\n  using assms\n  by (induct n arbitrary: x z)\n     (auto intro: tranclp.trancl_into_trancl)\n\nlemma tranclp_imp_stepfun:\n  assumes \"P\\<^sup>+\\<^sup>+ x z\"\n  shows \"\\<exists>f n. f 0 = x \\<and> f (Suc n) = z \\<and> (\\<forall>i\\<le>n. P (f i) (f (Suc i)))\"\n    (is \"\\<exists>f n. ?P x z f n\")\n  using assms\nproof (induct rule: tranclp_induct)\n  case (base y)\n  let ?f = \"(\\<lambda>_. y)(0 := x)\"\n  have \"?f 0 = x\" and \"?f (Suc 0) = y\" by auto\n  moreover have \"\\<forall>i\\<le>0. P (?f i) (?f (Suc i))\"\n    using base by auto\n  ultimately show ?case by blast\nnext\n  case (step y z)\n  then obtain f n where IH: \"?P x y f n\" by blast\n  then have *: \"\\<forall>i\\<le>n. P (f i) (f (Suc i))\"\n    and [simp]: \"f 0 = x\" \"f (Suc n) = y\"\n    by auto\n  let ?n = \"Suc n\"\n  let ?f = \"f(Suc ?n := z)\"\n  have \"?f 0 = x\" and \"?f (Suc ?n) = z\" by auto\n  moreover have \"\\<forall>i\\<le>?n. P (?f i) (?f (Suc i))\"\n    using \\<open>P y z\\<close> and * by auto\n  ultimately show ?case by blast\nqed\n\nlemma tranclp_stepfun_conv:\n  \"P\\<^sup>+\\<^sup>+ x y \\<longleftrightarrow> (\\<exists>f n. f 0 = x \\<and> f (Suc n) = y \\<and> (\\<forall>i\\<le>n. P (f i) (f (Suc i))))\"\n  using tranclp_imp_stepfun and stepfun_imp_tranclp by metis\n\n\nsubsection \\<open>Facts About Predecessor Sets\\<close>\n\nlemma qo_on_predecessor_subset_conv':\n  assumes \"qo_on P A\" and \"B \\<subseteq> A\" and \"C \\<subseteq> A\"\n  shows \"{x\\<in>A. \\<exists>y\\<in>B. P x y} \\<subseteq> {x\\<in>A. \\<exists>y\\<in>C. P x y} \\<longleftrightarrow> (\\<forall>x\\<in>B. \\<exists>y\\<in>C. P x y)\"\n  using assms\n  by (auto simp: subset_eq qo_on_def reflp_on_def, unfold transp_on_def) metis+\n\nlemma qo_on_predecessor_subset_conv:\n  \"\\<lbrakk>qo_on P A; x \\<in> A; y \\<in> A\\<rbrakk> \\<Longrightarrow> {z\\<in>A. P z x} \\<subseteq> {z\\<in>A. P z y} \\<longleftrightarrow> P x y\"\n  using qo_on_predecessor_subset_conv' [of P A \"{x}\" \"{y}\"] by simp\n\nlemma po_on_predecessors_eq_conv:\n  assumes \"po_on P A\" and \"x \\<in> A\" and \"y \\<in> A\"\n  shows \"{z\\<in>A. P\\<^sup>=\\<^sup>= z x} = {z\\<in>A. P\\<^sup>=\\<^sup>= z y} \\<longleftrightarrow> x = y\"\n  using assms(2-)\n    and reflp_on_reflclp [of P A]\n    and po_on_imp_antisymp_on [OF \\<open>po_on P A\\<close>]\n    unfolding antisymp_on_def reflp_on_def\n    by blast\n\nlemma restrict_to_rtranclp:\n  assumes \"transp_on P A\"\n    and \"x \\<in> A\" and \"y \\<in> A\"\n  shows \"(restrict_to P A)\\<^sup>*\\<^sup>* x y \\<longleftrightarrow> P\\<^sup>=\\<^sup>= x y\"\nproof -\n  { assume \"(restrict_to P A)\\<^sup>*\\<^sup>* x y\"\n    then have \"P\\<^sup>=\\<^sup>= x y\" using assms\n      by (induct) (auto, unfold transp_on_def, blast) }\n  with assms show ?thesis by auto\nqed\n\nlemma reflp_on_restrict_to_rtranclp:\n  assumes \"reflp_on P A\" and \"transp_on P A\"\n    and \"x \\<in> A\" and \"y \\<in> A\"\n  shows \"(restrict_to P A)\\<^sup>*\\<^sup>* x y \\<longleftrightarrow> P x y\"\n  unfolding restrict_to_rtranclp [OF assms(2-)]\n  unfolding reflp_on_reflclp_simp [OF assms(1, 3-)] ..\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/Restricted_Predicates.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8376199714402812, "lm_q2_score": 0.8438951025545426, "lm_q1q2_score": 0.7068633917003292}}
{"text": "(*\n    $Id: ex.thy,v 1.3 2008/07/04 15:37:21 nipkow Exp $\n*)\n\nheader {* Sum of List Elements, Tail-Recursively *}\n\n(*<*) theory ex 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  consts ListSum :: \"nat list \\<Rightarrow> nat\"\n\n  theorem \"2 * ListSum [0..<n+1] = n * (n + 1)\" (*<*) oops (*>*)\n\n  theorem \"ListSum (replicate n a) = n * a\" (*<*) oops (*>*)\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  consts ListSumTAux :: \"nat list \\<Rightarrow> nat \\<Rightarrow> nat\"\n\n  consts ListSumT :: \"nat list \\<Rightarrow> nat\"\n\n  theorem \"ListSum xs = ListSumT xs\" (*<*) 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/sum-tail/ex.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951104066293, "lm_q2_score": 0.8376199633332891, "lm_q1q2_score": 0.7068633914359429}}
{"text": "theory Inductive_Demo\nimports Main\nbegin\n\nsubsection{*Inductive definition of the even numbers*}\n\n  \n  \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{* Using the introduction rules: *}\nlemma \"ev (Suc(Suc(Suc(Suc 0))))\"\noops\n\nthm evSS[OF evSS[OF ev0]]\n\ntext{* A recursive definition 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\ntext{*A simple example of rule induction: *}\nlemma \"ev n \\<Longrightarrow> evn n\"\n  apply(induction rule: ev.induct)\n    by auto\n\n\ntext{* An induction on the computation of evn: *}\nlemma \"evn n \\<Longrightarrow> ev n\"\n  apply(induction n rule: evn.induct)\n    apply (simp add: ev0)\n   apply simp\n  apply (rule evSS)\n  apply simp\n    done\n\nlemma \"evn n \\<Longrightarrow> ev n\"\n  apply(induction n rule: evn.induct)\n  apply (auto intro: ev.intros)  \n  done\n      \n      \n      \ntext{* No problem with termination because the premises are always smaller\nthan the conclusion: *}\ndeclare ev.intros[simp,intro]\n\ntext{* A shorter proof: *}\nlemma \"evn n \\<Longrightarrow> ev n\"\napply(induction n rule: evn.induct)\napply(simp_all)\ndone\n\ntext{* The power of arith: *}\nlemma \"ev n \\<Longrightarrow> \\<exists>k. n = 2*k\"\n  apply(induction rule: ev.induct)\n    apply auto try0\n  by presburger\n    \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 (blast intro: step)\ndone\n\n(* The last definition defines star by prepending a new element in every step.\n  We could also have defined it by appending a new element:\n*)  \n\ninductive\n  star' :: \"('a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> bool\"\nfor r where\nrefl':  \"star' r x x\" |\nstep':  \"star' r x y \\<Longrightarrow> 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 (rotate_tac)  (* Note: Rule induction applies to first assumption! \n  However, we need to induction on the derivation of star' r y z! \n  With Isar, we will be able to write this more concisely.\n*)\napply(induction rule: star'.induct)\napply(assumption)\napply (blast intro: step')\ndone\n\n(* To prove equality of star and star', it's a good idea to prove both directions \\<Longrightarrow> and \\<Longleftarrow> separately: *)  \n\nlemma star_imp_star': \"star r x y \\<Longrightarrow> star' r x y\"\n  apply (induction rule: star.induct)\n   apply (rule refl')\n  thm star'_trans[OF step'[OF refl']] (* Let's assemble a suitable theorem to solve the second subgoal *)\n  apply (rule star'_trans[OF step'[OF refl']])  \n  apply (assumption)  \n  apply (assumption)  \n  done  \n\n(* Of course, we can summarize the whole proof into a single auto application *)    \nlemma \"star r x y \\<Longrightarrow> star' r x y\"\n  apply (induction rule: star.induct)\n  apply (auto intro: refl' star'_trans[OF step'[OF refl']])\n  done  \n    \n(* The other direction *)    \nlemma star'_imp_star: \"star' r x y \\<Longrightarrow> star r x y\"\n  apply (induction rule: star'.induct)\n  thm star_trans[OF _ step[OF _ refl]]\n  by (auto intro: refl star_trans[OF _ step[OF _ refl]])\n\n(* The equality lemma *)    \nlemma star'_eq_star: \"star' r x y = star r x y\"\n  by (auto intro: star_imp_star' star'_imp_star)\n    \n(* We can also omit the arguments *)  \nthm ext    \nlemma \"star' = star\"\n  apply (rule ext)\n  apply (rule ext)\n  apply (rule ext)\n  by (rule star'_eq_star)\n    \nthm ext (* Two functions are equal if they are equal for any argument *)   \n    \nlemma \"star' = star\"\n  apply (intro ext) (* Apply given rules as often as possible *)\n  by (rule star'_eq_star)\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/Inductive_Demo.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950986284991, "lm_q2_score": 0.8376199633332891, "lm_q1q2_score": 0.7068633815703458}}
{"text": "(*  Title:       Countable Ordinals\n\n    Author:      Brian Huffman, 2005\n    Maintainer:  Brian Huffman <brianh at cse.ogi.edu>\n*)\n\nheader {* Definition of Ordinals *}\n\ntheory OrdinalDef\nimports Main\nbegin\n\nsubsection {* Preliminary datatype for ordinals *}\n\ndatatype ord0 = ord0_Zero | ord0_Lim \"nat \\<Rightarrow> ord0\"\n\ntext {* subterm ordering on ord0 *}\n\ndefinition\n  ord0_prec :: \"(ord0 \\<times> ord0) set\" where\n  \"ord0_prec = (\\<Union>f i. {(f i, ord0_Lim f)})\"\n\nlemma wf_ord0_prec: \"wf ord0_prec\"\n apply (unfold ord0_prec_def)\n apply (rule wfUNIVI, induct_tac x)\n  apply (drule spec, erule mp, simp)\n apply (drule spec, erule mp, auto)\ndone\n\nlemmas ord0_prec_induct = wf_induct[OF wf_trancl[OF wf_ord0_prec]]\n\n\ntext {* less-than-or-equal ordering on ord0 *}\n\ninductive_set ord0_leq :: \"(ord0 \\<times> ord0) set\" where\n\"\\<lbrakk>\\<forall>a. (a,x) \\<in> ord0_prec\\<^sup>+ \\<longrightarrow> (\\<exists>b. (b,y) \\<in> ord0_prec\\<^sup>+ \\<and> (a,b) \\<in> ord0_leq)\\<rbrakk>\n  \\<Longrightarrow> (x,y) \\<in> ord0_leq\"\n\nlemma ord0_leqI:\n\"\\<lbrakk>\\<forall>a. (a,x) \\<in> ord0_prec\\<^sup>+ \\<longrightarrow> (a,y) \\<in> ord0_leq O ord0_prec\\<^sup>+\\<rbrakk>\n \\<Longrightarrow> (x,y) \\<in> ord0_leq\"\nby (rule ord0_leq.intros, auto)\n\nlemma ord0_leqD:\n\"\\<lbrakk>(x,y) \\<in> ord0_leq; (a,x) \\<in> ord0_prec\\<^sup>+\\<rbrakk> \\<Longrightarrow> (a,y) \\<in> ord0_leq O ord0_prec\\<^sup>+\"\nby (ind_cases \"(x,y) \\<in> ord0_leq\", auto)\n\nlemma ord0_leq_refl: \"(x, x) \\<in> ord0_leq\"\nby (rule ord0_prec_induct, rule ord0_leqI, auto)\n\nlemma ord0_leq_trans[rule_format]:\n\"\\<forall>y. (x,y) \\<in> ord0_leq \\<longrightarrow>\n   (\\<forall>z. (y,z) \\<in> ord0_leq \\<longrightarrow> (x,z) \\<in> ord0_leq)\"\n apply (rule ord0_prec_induct, clarify)\n apply (rule ord0_leqI, clarify)\n apply (drule spec, drule mp, assumption)\n apply (drule ord0_leqD, assumption, clarify)\n apply (drule spec, drule mp, assumption)\n apply (drule ord0_leqD, assumption, clarify)\n apply (drule spec, drule mp, assumption)\n apply auto\ndone\n\nlemma wf_ord0_leq: \"wf (ord0_leq O ord0_prec\\<^sup>+)\"\n apply (unfold wf_def, clarify)\n apply (subgoal_tac \"\\<forall>z. (z,x) \\<in> ord0_leq \\<longrightarrow> P z\")\n  apply (drule spec, erule mp, rule ord0_leq_refl)\n apply (rule ord0_prec_induct, clarify)\n apply (drule spec, erule mp, clarify)\n apply (drule ord0_leqD, assumption, clarify)\n apply (drule spec, drule mp, assumption)\n apply (drule spec, erule mp)\n apply (erule ord0_leq_trans, assumption)\ndone\n\n\ntext {* ordering on ord0 *}\n\ninstantiation ord0 :: ord\nbegin\n\ndefinition\n  ord0_less_def: \"x < y \\<longleftrightarrow> (x,y) \\<in> ord0_leq O ord0_prec\\<^sup>+\"\n\ndefinition\n  ord0_le_def:   \"x \\<le> y \\<longleftrightarrow> (x,y) \\<in> ord0_leq\"\n\ninstance ..\n\nend\n\nlemma ord0_order_refl[simp]: \"(x::ord0) \\<le> x\"\nby (unfold ord0_le_def, rule ord0_leq_refl)\n\nlemma ord0_order_trans: \"\\<lbrakk>(x::ord0) \\<le> y; y \\<le> z\\<rbrakk> \\<Longrightarrow> x \\<le> z\"\nby (unfold ord0_le_def, rule ord0_leq_trans)\n\nlemma ord0_wf: \"wf {(x,y::ord0). x < y}\"\n apply (subgoal_tac \"{(x,y). x < y} = ord0_leq O ord0_prec\\<^sup>+\")\n  apply (simp add: wf_ord0_leq)\n apply (auto simp add: ord0_less_def)\ndone\n\nlemmas ord0_less_induct = wf_induct[OF ord0_wf]\n\nlemma ord0_leI:\n\"\\<lbrakk>\\<forall>a::ord0. a < x \\<longrightarrow> a < y\\<rbrakk> \\<Longrightarrow> x \\<le> y\"\n apply (unfold ord0_less_def ord0_le_def)\n apply (rule ord0_leqI[rule_format])\n apply (drule spec, erule mp)\n apply (erule relcompI[OF ord0_leq_refl])\ndone\n\nlemma ord0_less_le_trans:\n\"\\<lbrakk>(x::ord0) < y; y \\<le> z\\<rbrakk> \\<Longrightarrow> x < z\"\n apply (unfold ord0_le_def ord0_less_def, clarify)\n apply (drule ord0_leqD, assumption, clarify)\nby (rule relcompI[OF ord0_leq_trans])\n\nlemma ord0_le_less_trans:\n\"\\<lbrakk>(x::ord0) \\<le> y; y < z\\<rbrakk> \\<Longrightarrow> x < z\"\n apply (unfold ord0_le_def ord0_less_def, clarify)\nby (rule relcompI[OF ord0_leq_trans])\n\nlemma rev_ord0_le_less_trans:\n\"\\<lbrakk>(y::ord0) < z; x \\<le> y\\<rbrakk> \\<Longrightarrow> x < z\"\nby (rule ord0_le_less_trans)\n\nlemma ord0_less_trans:\n\"\\<lbrakk>(x::ord0) < y; y < z\\<rbrakk> \\<Longrightarrow> x < z\"\n apply (unfold ord0_less_def, clarify)\n apply (drule ord0_leqD, assumption, clarify)\nby (rule relcompI[OF ord0_leq_trans trancl_trans])\n\nlemma ord0_less_imp_le: \"(x::ord0) < y \\<Longrightarrow> x \\<le> y\"\nby (rule ord0_leI[rule_format], rule ord0_less_trans)\n\nlemma ord0_linear_lemma:\nfixes m :: ord0 and n :: ord0\nshows \"m < n \\<or> n < m \\<or> (m \\<le> n \\<and> n \\<le> m)\"\n apply (rule_tac x=m in spec)\n apply (rule_tac a=n in ord0_less_induct, rename_tac n)\n apply (rule allI, rename_tac m)\n apply (rule_tac a=m in ord0_less_induct, rename_tac m)\n apply (case_tac \"\\<forall>a. a < n \\<longrightarrow> a < m\")\n  apply (rule disjI2)\n  apply (case_tac \"\\<forall>a. a < m \\<longrightarrow> a < n\")\n   apply (rule disjI2)\n   apply (rule conjI, erule ord0_leI, erule ord0_leI)\n  apply (rule disjI1, clarsimp)\n  apply (drule spec, drule mp, assumption)\n  apply (erule rev_ord0_le_less_trans)\n  apply (force simp add: ord0_less_imp_le)\n apply (rule disjI1, clarsimp)\n apply (drule spec, drule mp, assumption)\n apply (drule_tac x=m in spec, simp)\n apply (erule rev_ord0_le_less_trans)\n apply (force simp add: ord0_less_imp_le)\ndone\n\nlemma ord0_linear: \"(x::ord0) \\<le> y \\<or> y \\<le> x\"\n apply (cut_tac ord0_linear_lemma[of x y])\n apply (auto dest: ord0_less_imp_le)\ndone\n\nlemma ord0_order_less_le: \"(x::ord0) < y = (x \\<le> y \\<and> \\<not> y \\<le> x)\"\n apply (rule iffI)\n  apply (clarsimp simp add: ord0_less_imp_le)\n  apply (drule ord0_less_le_trans, assumption)\n  apply (cut_tac a=x in wf_not_refl[OF ord0_wf], simp)\n apply (cut_tac ord0_linear_lemma[of x y], simp)\n apply (auto dest: ord0_less_imp_le)\ndone\n\n\nsubsection {* Ordinal type *}\n\ndefinition\n  ord0rel :: \"(ord0 \\<times> ord0) set\" where\n  \"ord0rel = {(x,y). x \\<le> y \\<and> y \\<le> x}\"\n\ntypedef ordinal = \"(UNIV::ord0 set) // ord0rel\"\nby (unfold quotient_def, auto)\n\ntheorem Abs_ordinal_cases2 [case_names Abs_ordinal, cases type: ordinal]:\n\"(\\<And>z. x = Abs_ordinal (ord0rel `` {z}) \\<Longrightarrow> P) \\<Longrightarrow> P\"\nby (cases x, auto simp add: quotient_def)\n\n\ninstantiation ordinal :: ord\nbegin\n\ndefinition\n  ordinal_less_def: \"x < y \\<longleftrightarrow> (\\<forall>a\\<in>Rep_ordinal x. \\<forall>b\\<in>Rep_ordinal y. a < b)\"\n\ndefinition\n  ordinal_le_def: \"x \\<le> y \\<longleftrightarrow> (\\<forall>a\\<in>Rep_ordinal x. \\<forall>b\\<in>Rep_ordinal y. a \\<le> b)\"\n\ninstance ..\n\nend\n\nlemma Rep_Abs_ord0rel [simp]:\n\"Rep_ordinal (Abs_ordinal (ord0rel `` {x})) = (ord0rel `` {x})\"\nby (simp add: Abs_ordinal_inverse quotientI)\n\nlemma mem_ord0rel_Image [simp, intro!]: \"x \\<in> ord0rel `` {x}\"\nby (simp add: ord0rel_def)\n\nlemma equiv_ord0rel: \"equiv UNIV ord0rel\"\n apply (unfold equiv_def refl_on_def sym_def trans_def ord0rel_def)\n apply (auto elim: ord0_order_trans)\ndone\n\nlemma Abs_ordinal_eq[simp]:\n\"(Abs_ordinal (ord0rel `` {x}) = Abs_ordinal (ord0rel `` {y}))\n  = (x \\<le> y \\<and> y \\<le> x)\"\n apply (simp add: Abs_ordinal_inject quotientI)\n apply (simp add: eq_equiv_class_iff[OF equiv_ord0rel])\n apply (simp add: ord0rel_def)\ndone\n\nlemma Abs_ordinal_le[simp]:\n\"Abs_ordinal (ord0rel `` {x}) \\<le> Abs_ordinal (ord0rel `` {y}) = (x \\<le> y)\"\n apply (auto simp add: ordinal_le_def)\n apply (unfold ord0rel_def)\n apply (auto elim: ord0_order_trans)\ndone\n\nlemma Abs_ordinal_less[simp]:\n\"Abs_ordinal (ord0rel `` {x}) < Abs_ordinal (ord0rel `` {y}) = (x < y)\"\n apply (auto simp add: ordinal_less_def)\n apply (unfold ord0rel_def)\n apply (auto elim: ord0_less_le_trans[OF rev_ord0_le_less_trans])\ndone\n\nlemma ordinal_order_refl: \"(x::ordinal) \\<le> x\"\nby (cases x, simp)\n\nlemma ordinal_order_trans: \"(x::ordinal) \\<le> y \\<Longrightarrow> y \\<le> z \\<Longrightarrow> x \\<le> z\"\nby (cases x, cases y, cases z, auto elim: ord0_order_trans)\n\nlemma ordinal_order_antisym: \"(x::ordinal) \\<le> y \\<Longrightarrow> y \\<le> x \\<Longrightarrow> x = y\"\nby (cases x, cases y, simp)\n\n\n\nlemma ordinal_linear: \"(x::ordinal) \\<le> y \\<or> y \\<le> x\"\nby (cases x, cases y, simp add: ord0_linear)\n\nlemma ordinal_wf: \"wf {(x,y::ordinal). x < y}\"\n apply (rule wfUNIVI)\n apply (rule_tac x=x in Abs_ordinal_cases2, clarify)\n apply (rule ord0_less_induct, rename_tac a)\n apply (drule spec, erule mp, clarify)\n apply (rule_tac x=y in Abs_ordinal_cases2, simp)\ndone\n\ninstance ordinal :: wellorder\n apply (rule wf_wellorderI)\n apply (rule ordinal_wf)\n apply (intro_classes)\n       apply (rule ordinal_order_less_le_not_le)\n      apply (rule ordinal_order_refl)\n     apply (rule ordinal_order_trans, assumption+)\n    apply (rule ordinal_order_antisym, assumption+)\n  apply (rule ordinal_linear)\ndone\n\n\nsubsection {* Induction over ordinals *}\n\ntext \"zero and strict limits\"\n\ndefinition\n  oZero :: \"ordinal\" where\n    \"oZero = Abs_ordinal (ord0rel `` {ord0_Zero})\"\n\ndefinition\n  oStrictLimit :: \"(nat \\<Rightarrow> ordinal) \\<Rightarrow> ordinal\" where\n    \"oStrictLimit f = Abs_ordinal\n      (ord0rel `` {ord0_Lim (\\<lambda>n. SOME x. x \\<in> Rep_ordinal (f n))})\"\n\ntext \"induction over ordinals\"\n\nlemma ord0relD: \"(x,y) \\<in> ord0rel \\<Longrightarrow> x \\<le> y \\<and> y \\<le> x\"\nby (simp add: ord0rel_def)\n\nlemma ord0_precD: \"(x,y) \\<in> ord0_prec \\<Longrightarrow> \\<exists>f n. x = f n \\<and> y = ord0_Lim f\"\nby (simp add: ord0_prec_def)\n\nlemma less_ord0_LimI: \"f n < ord0_Lim f\"\n apply (simp add: ord0_less_def)\n apply (rule relcompI[OF ord0_leq_refl])\n apply (rule r_into_trancl)\n apply (auto simp add: ord0_prec_def)\ndone\n\nlemma less_ord0_LimD: \"x < ord0_Lim f \\<Longrightarrow> \\<exists>n. x \\<le> f n\"\n apply (simp add: ord0_less_def, clarify)\n apply (erule tranclE)\n  apply (drule ord0_precD, clarify)\n  apply (force simp add: ord0_le_def)\n apply (drule ord0_precD, clarify)\n apply (rule_tac x=n in exI)\n apply (rule ord0_less_imp_le)\n apply (auto simp add: ord0_less_def)\ndone\n\nlemma some_ord0rel: \"(x, SOME y. (x,y) \\<in> ord0rel) \\<in> ord0rel\"\nby (rule_tac x=x in someI, simp add: ord0rel_def)\n\nlemma ord0_Lim_le:\n\"\\<forall>n. f n \\<le> g n \\<Longrightarrow> ord0_Lim f \\<le> ord0_Lim g\"\n apply (rule ord0_leI[rule_format])\n apply (drule less_ord0_LimD, clarify)\n apply (erule ord0_le_less_trans)\n apply (drule_tac x=n in spec)\n apply (erule ord0_le_less_trans)\n apply (rule less_ord0_LimI)\ndone\n\nlemma ord0_Lim_ord0rel:\n\"\\<forall>n. (f n, g n) \\<in> ord0rel \\<Longrightarrow> (ord0_Lim f, ord0_Lim g) \\<in> ord0rel\"\nby (simp add: ord0rel_def ord0_Lim_le)\n\nlemma Abs_ordinal_oStrictLimit:\n\"Abs_ordinal (ord0rel `` {ord0_Lim f})\n  = oStrictLimit (\\<lambda>n. Abs_ordinal (ord0rel `` {f n}))\"\n apply (simp add: oStrictLimit_def)\n apply (rule ord0relD)\n apply (rule ord0_Lim_ord0rel)\n apply (simp add: some_ord0rel)\ndone\n\nlemma oStrictLimit_induct:\nassumes base: \"P oZero\"\nassumes step: \"\\<And>f. \\<forall>n. P (f n) \\<Longrightarrow> P (oStrictLimit f)\"\nshows \"P a\"\n apply (cases a, clarsimp)\n apply (induct_tac z)\n  apply (rule base[unfolded oZero_def])\n apply (simp add: Abs_ordinal_oStrictLimit step)\ndone\n\ntext \"order properties of 0 and strict limits\"\n\nlemma oZero_least: \"oZero \\<le> x\"\n apply (unfold oZero_def, cases x, clarsimp)\n apply (induct_tac z, simp, atomize)\n apply (rule ord0_less_imp_le)\n apply (rule ord0_le_less_trans)\n apply (auto simp: less_ord0_LimI)\ndone\n\nlemma oStrictLimit_ub: \"f n < oStrictLimit f\"\n apply (cases \"f n\", simp add: oStrictLimit_def)\n apply (rule_tac y=\"SOME x. x \\<in> Rep_ordinal (f n)\" in ord0_le_less_trans)\n  apply (simp, rule ord0relD[THEN conjunct1])\n  apply (rule some_ord0rel)\n apply (rule less_ord0_LimI)\ndone\n\nlemma oStrictLimit_lub: \"\\<forall>n. f n < x \\<Longrightarrow> oStrictLimit f \\<le> x\"\n apply (erule contrapos_pp, simp add: linorder_not_less linorder_not_le)\n apply (cases x, simp add: oStrictLimit_def)\n apply (drule less_ord0_LimD, clarify)\n apply (rule_tac x=n in exI)\n apply (rule_tac x=\"f n\" in Abs_ordinal_cases2, simp, rename_tac y)\n apply (erule ord0_order_trans)\n apply (rule ord0relD[THEN conjunct2])\n apply (rule some_ord0rel)\ndone\n\nlemma less_oStrictLimitD: \"x < oStrictLimit f \\<Longrightarrow> \\<exists>n. x \\<le> f n\"\n apply (erule contrapos_pp)\n apply (simp add: linorder_not_less linorder_not_le)\n apply (erule oStrictLimit_lub)\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/OrdinalDef.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357666736772, "lm_q2_score": 0.8152324871074608, "lm_q1q2_score": 0.7068357244765059}}
{"text": "(*  Title:      HOL/Algebra/Coset.thy\n    Authors:    Florian Kammueller, L C Paulson, Stephan Hohe\n\nWith additional contributions from Martin Baillon and Paulo Em\u00edlio de Vilhena.\n*)\n\ntheory Coset\nimports Group\nbegin\n\nsection \\<open>Cosets and Quotient Groups\\<close>\n\ndefinition\n  r_coset    :: \"[_, 'a set, 'a] \\<Rightarrow> 'a set\"    (infixl \"#>\\<index>\" 60)\n  where \"H #>\\<^bsub>G\\<^esub> a = (\\<Union>h\\<in>H. {h \\<otimes>\\<^bsub>G\\<^esub> a})\"\n\ndefinition\n  l_coset    :: \"[_, 'a, 'a set] \\<Rightarrow> 'a set\"    (infixl \"<#\\<index>\" 60)\n  where \"a <#\\<^bsub>G\\<^esub> H = (\\<Union>h\\<in>H. {a \\<otimes>\\<^bsub>G\\<^esub> h})\"\n\ndefinition\n  RCOSETS  :: \"[_, 'a set] \\<Rightarrow> ('a set)set\"   (\"rcosets\\<index> _\" [81] 80)\n  where \"rcosets\\<^bsub>G\\<^esub> H = (\\<Union>a\\<in>carrier G. {H #>\\<^bsub>G\\<^esub> a})\"\n\ndefinition\n  set_mult  :: \"[_, 'a set ,'a set] \\<Rightarrow> 'a set\" (infixl \"<#>\\<index>\" 60)\n  where \"H <#>\\<^bsub>G\\<^esub> K = (\\<Union>h\\<in>H. \\<Union>k\\<in>K. {h \\<otimes>\\<^bsub>G\\<^esub> k})\"\n\ndefinition\n  SET_INV :: \"[_,'a set] \\<Rightarrow> 'a set\"  (\"set'_inv\\<index> _\" [81] 80)\n  where \"set_inv\\<^bsub>G\\<^esub> H = (\\<Union>h\\<in>H. {inv\\<^bsub>G\\<^esub> h})\"\n\n\nlocale normal = subgroup + group +\n  assumes coset_eq: \"(\\<forall>x \\<in> carrier G. H #> x = x <# H)\"\n\nabbreviation\n  normal_rel :: \"['a set, ('a, 'b) monoid_scheme] \\<Rightarrow> bool\"  (infixl \"\\<lhd>\" 60) where\n  \"H \\<lhd> G \\<equiv> normal H G\"\n\nlemma (in comm_group) subgroup_imp_normal: \"subgroup A G \\<Longrightarrow> A \\<lhd> G\"\n  by (simp add: normal_def normal_axioms_def is_group l_coset_def r_coset_def m_comm subgroup.mem_carrier)\n\nlemma l_coset_eq_set_mult: \\<^marker>\\<open>contributor \\<open>Martin Baillon\\<close>\\<close>\n  fixes G (structure)\n  shows \"x <# H = {x} <#> H\"\n  unfolding l_coset_def set_mult_def by simp\n\nlemma r_coset_eq_set_mult: \\<^marker>\\<open>contributor \\<open>Martin Baillon\\<close>\\<close>\n  fixes G (structure)\n  shows \"H #> x = H <#> {x}\"\n  unfolding r_coset_def set_mult_def by simp\n\nlemma (in subgroup) rcosets_non_empty: \\<^marker>\\<open>contributor \\<open>Paulo Em\u00edlio de Vilhena\\<close>\\<close>\n  assumes \"R \\<in> rcosets H\"\n  shows \"R \\<noteq> {}\"\nproof -\n  obtain g where \"g \\<in> carrier G\" \"R = H #> g\"\n    using assms unfolding RCOSETS_def by blast\n  hence \"\\<one> \\<otimes> g \\<in> R\"\n    using one_closed unfolding r_coset_def by blast\n  thus ?thesis by blast\nqed\n\nlemma (in group) diff_neutralizes: \\<^marker>\\<open>contributor \\<open>Paulo Em\u00edlio de Vilhena\\<close>\\<close>\n  assumes \"subgroup H G\" \"R \\<in> rcosets H\"\n  shows \"\\<And>r1 r2. \\<lbrakk> r1 \\<in> R; r2 \\<in> R \\<rbrakk> \\<Longrightarrow> r1 \\<otimes> (inv r2) \\<in> H\"\nproof -\n  fix r1 r2 assume r1: \"r1 \\<in> R\" and r2: \"r2 \\<in> R\"\n  obtain g where g: \"g \\<in> carrier G\" \"R = H #> g\"\n    using assms unfolding RCOSETS_def by blast\n  then obtain h1 h2 where h1: \"h1 \\<in> H\" \"r1 = h1 \\<otimes> g\"\n                      and h2: \"h2 \\<in> H\" \"r2 = h2 \\<otimes> g\"\n    using r1 r2 unfolding r_coset_def by blast\n  hence \"r1 \\<otimes> (inv r2) = (h1 \\<otimes> g) \\<otimes> ((inv g) \\<otimes> (inv h2))\"\n    using inv_mult_group is_group assms(1) g(1) subgroup.mem_carrier by fastforce\n  also have \" ... =  (h1 \\<otimes> (g \\<otimes> inv g) \\<otimes> inv h2)\"\n    using h1 h2 assms(1) g(1) inv_closed m_closed monoid.m_assoc\n          monoid_axioms subgroup.mem_carrier\n  proof -\n    have \"h1 \\<in> carrier G\"\n      by (meson subgroup.mem_carrier assms(1) h1(1))\n    moreover have \"h2 \\<in> carrier G\"\n      by (meson subgroup.mem_carrier assms(1) h2(1))\n    ultimately show ?thesis\n      using g(1) inv_closed m_assoc m_closed by presburger\n  qed\n  finally have \"r1 \\<otimes> inv r2 = h1 \\<otimes> inv h2\"\n    using assms(1) g(1) h1(1) subgroup.mem_carrier by fastforce\n  thus \"r1 \\<otimes> inv r2 \\<in> H\" by (metis assms(1) h1(1) h2(1) subgroup_def)\nqed\n\nlemma mono_set_mult: \"\\<lbrakk> H \\<subseteq> H'; K \\<subseteq> K' \\<rbrakk> \\<Longrightarrow> H <#>\\<^bsub>G\\<^esub> K \\<subseteq> H' <#>\\<^bsub>G\\<^esub> K'\" \\<^marker>\\<open>contributor \\<open>Paulo Em\u00edlio de Vilhena\\<close>\\<close>\n  unfolding set_mult_def by (simp add: UN_mono)\n\n\nsubsection \\<open>Stable Operations for Subgroups\\<close>\n\nlemma set_mult_consistent [simp]: \\<^marker>\\<open>contributor \\<open>Paulo Em\u00edlio de Vilhena\\<close>\\<close>\n  \"N <#>\\<^bsub>(G \\<lparr> carrier := H \\<rparr>)\\<^esub> K = N <#>\\<^bsub>G\\<^esub> K\"\n  unfolding set_mult_def by simp\n\nlemma r_coset_consistent [simp]: \\<^marker>\\<open>contributor \\<open>Paulo Em\u00edlio de Vilhena\\<close>\\<close>\n  \"I #>\\<^bsub>G \\<lparr> carrier := H \\<rparr>\\<^esub> h = I #>\\<^bsub>G\\<^esub> h\"\n  unfolding r_coset_def by simp\n\nlemma l_coset_consistent [simp]: \\<^marker>\\<open>contributor \\<open>Paulo Em\u00edlio de Vilhena\\<close>\\<close>\n  \"h <#\\<^bsub>G \\<lparr> carrier := H \\<rparr>\\<^esub> I = h <#\\<^bsub>G\\<^esub> I\"\n  unfolding l_coset_def by simp\n\n\nsubsection \\<open>Basic Properties of set multiplication\\<close>\n\nlemma (in group) setmult_subset_G:\n  assumes \"H \\<subseteq> carrier G\" \"K \\<subseteq> carrier G\"\n  shows \"H <#> K \\<subseteq> carrier G\" using assms\n  by (auto simp add: set_mult_def subsetD)\n\nlemma (in monoid) set_mult_closed:\n  assumes \"H \\<subseteq> carrier G\" \"K \\<subseteq> carrier G\"\n  shows \"H <#> K \\<subseteq> carrier G\"\n  using assms by (auto simp add: set_mult_def subsetD)\n\nlemma (in group) set_mult_assoc: \\<^marker>\\<open>contributor \\<open>Martin Baillon\\<close>\\<close>\n  assumes \"M \\<subseteq> carrier G\" \"H \\<subseteq> carrier G\" \"K \\<subseteq> carrier G\"\n  shows \"(M <#> H) <#> K = M <#> (H <#> K)\"\nproof\n  show \"(M <#> H) <#> K \\<subseteq> M <#> (H <#> K)\"\n  proof\n    fix x assume \"x \\<in> (M <#> H) <#> K\"\n    then obtain m h k where x: \"m \\<in> M\" \"h \\<in> H\" \"k \\<in> K\" \"x = (m \\<otimes> h) \\<otimes> k\"\n      unfolding set_mult_def by blast\n    hence \"x = m \\<otimes> (h \\<otimes> k)\"\n      using assms m_assoc by blast\n    thus \"x \\<in> M <#> (H <#> K)\"\n      unfolding set_mult_def using x by blast\n  qed\nnext\n  show \"M <#> (H <#> K) \\<subseteq> (M <#> H) <#> K\"\n  proof\n    fix x assume \"x \\<in> M <#> (H <#> K)\"\n    then obtain m h k where x: \"m \\<in> M\" \"h \\<in> H\" \"k \\<in> K\" \"x = m \\<otimes> (h \\<otimes> k)\"\n      unfolding set_mult_def by blast\n    hence \"x = (m \\<otimes> h) \\<otimes> k\"\n      using assms m_assoc rev_subsetD by metis\n    thus \"x \\<in> (M <#> H) <#> K\"\n      unfolding set_mult_def using x by blast\n  qed\nqed\n\n\n\nsubsection \\<open>Basic Properties of Cosets\\<close>\n\nlemma (in group) coset_mult_assoc:\n  assumes \"M \\<subseteq> carrier G\" \"g \\<in> carrier G\" \"h \\<in> carrier G\"\n  shows \"(M #> g) #> h = M #> (g \\<otimes> h)\"\n  using assms by (force simp add: r_coset_def m_assoc)\n\nlemma (in group) coset_assoc:\n  assumes \"x \\<in> carrier G\" \"y \\<in> carrier G\" \"H \\<subseteq> carrier G\"\n  shows \"x <# (H #> y) = (x <# H) #> y\"\n  using set_mult_assoc[of \"{x}\" H \"{y}\"]\n  by (simp add: l_coset_eq_set_mult r_coset_eq_set_mult assms)\n\nlemma (in group) coset_mult_one [simp]: \"M \\<subseteq> carrier G ==> M #> \\<one> = M\"\nby (force simp add: r_coset_def)\n\nlemma (in group) coset_mult_inv1:\n  assumes \"M #> (x \\<otimes> (inv y)) = M\"\n    and \"x \\<in> carrier G\" \"y \\<in> carrier G\" \"M \\<subseteq> carrier G\"\n  shows \"M #> x = M #> y\" using assms\n  by (metis coset_mult_assoc group.inv_solve_right is_group subgroup_def subgroup_self)\n\nlemma (in group) coset_mult_inv2:\n  assumes \"M #> x = M #> y\"\n    and \"x \\<in> carrier G\"  \"y \\<in> carrier G\" \"M \\<subseteq> carrier G\"\n  shows \"M #> (x \\<otimes> (inv y)) = M \" using assms\n  by (metis group.coset_mult_assoc group.coset_mult_one inv_closed is_group r_inv)\n\nlemma (in group) coset_join1:\n  assumes \"H #> x = H\"\n    and \"x \\<in> carrier G\" \"subgroup H G\"\n  shows \"x \\<in> H\"\n  using assms r_coset_def l_one subgroup.one_closed sym by fastforce\n\nlemma (in group) solve_equation:\n  assumes \"subgroup H G\" \"x \\<in> H\" \"y \\<in> H\"\n  shows \"\\<exists>h \\<in> H. y = h \\<otimes> x\"\nproof -\n  have \"y = (y \\<otimes> (inv x)) \\<otimes> x\" using assms\n    by (simp add: m_assoc subgroup.mem_carrier)\n  moreover have \"y \\<otimes> (inv x) \\<in> H\" using assms\n    by (simp add: subgroup_def)\n  ultimately show ?thesis by blast\nqed\n\nlemma (in group_hom) inj_on_one_iff:\n   \"inj_on h (carrier G) \\<longleftrightarrow> (\\<forall>x. x \\<in> carrier G \\<longrightarrow> h x = one H \\<longrightarrow> x = one G)\"\nusing G.solve_equation G.subgroup_self by (force simp: inj_on_def)\n\nlemma inj_on_one_iff':\n   \"\\<lbrakk>h \\<in> hom G H; group G; group H\\<rbrakk> \\<Longrightarrow> inj_on h (carrier G) \\<longleftrightarrow> (\\<forall>x. x \\<in> carrier G \\<longrightarrow> h x = one H \\<longrightarrow> x = one G)\"\n  using group_hom.inj_on_one_iff group_hom.intro group_hom_axioms.intro by blast\n\nlemma mon_iff_hom_one:\n   \"\\<lbrakk>group G; group H\\<rbrakk> \\<Longrightarrow> f \\<in> mon G H \\<longleftrightarrow> f \\<in> hom G H \\<and> (\\<forall>x. x \\<in> carrier G \\<and> f x = \\<one>\\<^bsub>H\\<^esub> \\<longrightarrow> x = \\<one>\\<^bsub>G\\<^esub>)\"\n  by (auto simp: mon_def inj_on_one_iff')\n\nlemma (in group_hom) iso_iff: \"h \\<in> iso G H \\<longleftrightarrow> carrier H \\<subseteq> h ` carrier G \\<and> (\\<forall>x\\<in>carrier G. h x = \\<one>\\<^bsub>H\\<^esub> \\<longrightarrow> x = \\<one>)\"\n  by (auto simp: iso_def bij_betw_def inj_on_one_iff)\n\nlemma (in group) repr_independence:\n  assumes \"y \\<in> H #> x\" \"x \\<in> carrier G\" \"subgroup H G\"\n  shows \"H #> x = H #> y\" using assms\nby (auto simp add: r_coset_def m_assoc [symmetric]\n                   subgroup.subset [THEN subsetD]\n                   subgroup.m_closed solve_equation)\n\nlemma (in group) coset_join2:\n  assumes \"x \\<in> carrier G\" \"subgroup H G\" \"x \\<in> H\"\n  shows \"H #> x = H\" using assms\n  \\<comment> \\<open>Alternative proof is to put \\<^term>\\<open>x=\\<one>\\<close> in \\<open>repr_independence\\<close>.\\<close>\nby (force simp add: subgroup.m_closed r_coset_def solve_equation)\n\nlemma (in group) coset_join3:\n  assumes \"x \\<in> carrier G\" \"subgroup H G\" \"x \\<in> H\"\n  shows \"x <# H = H\"\nproof\n  have \"\\<And>h. h \\<in> H \\<Longrightarrow> x \\<otimes> h \\<in> H\" using assms\n    by (simp add: subgroup.m_closed)\n  thus \"x <# H \\<subseteq> H\" unfolding l_coset_def by blast\nnext\n  have \"\\<And>h. h \\<in> H \\<Longrightarrow> x \\<otimes> ((inv x) \\<otimes> h) = h\"\n    by (metis (no_types, lifting) assms group.inv_closed group.inv_solve_left is_group \n              monoid.m_closed monoid_axioms subgroup.mem_carrier)\n  moreover have \"\\<And>h. h \\<in> H \\<Longrightarrow> (inv x) \\<otimes> h \\<in> H\"\n    by (simp add: assms subgroup.m_closed subgroup.m_inv_closed)\n  ultimately show \"H \\<subseteq> x <# H\" unfolding l_coset_def by blast\nqed\n\nlemma (in monoid) r_coset_subset_G:\n  \"\\<lbrakk> H \\<subseteq> carrier G; x \\<in> carrier G \\<rbrakk> \\<Longrightarrow> H #> x \\<subseteq> carrier G\"\nby (auto simp add: r_coset_def)\n\nlemma (in group) rcosI:\n  \"\\<lbrakk> h \\<in> H; H \\<subseteq> carrier G; x \\<in> carrier G \\<rbrakk> \\<Longrightarrow> h \\<otimes> x \\<in> H #> x\"\nby (auto simp add: r_coset_def)\n\nlemma (in group) rcosetsI:\n     \"\\<lbrakk>H \\<subseteq> carrier G; x \\<in> carrier G\\<rbrakk> \\<Longrightarrow> H #> x \\<in> rcosets H\"\nby (auto simp add: RCOSETS_def)\n\nlemma (in group) rcos_self:\n  \"\\<lbrakk> x \\<in> carrier G; subgroup H G \\<rbrakk> \\<Longrightarrow> x \\<in> H #> x\"\n  by (metis l_one rcosI subgroup_def)\n\ntext (in group) \\<open>Opposite of @{thm [source] \"repr_independence\"}\\<close>\nlemma (in group) repr_independenceD:\n  assumes \"subgroup H G\" \"y \\<in> carrier G\"\n    and \"H #> x = H #> y\"\n  shows \"y \\<in> H #> x\"\n  using assms by (simp add: rcos_self)\n\ntext \\<open>Elements of a right coset are in the carrier\\<close>\nlemma (in subgroup) elemrcos_carrier:\n  assumes \"group G\" \"a \\<in> carrier G\"\n    and \"a' \\<in> H #> a\"\n  shows \"a' \\<in> carrier G\"\n  by (meson assms group.is_monoid monoid.r_coset_subset_G subset subsetCE)\n\nlemma (in subgroup) rcos_const:\n  assumes \"group G\" \"h \\<in> H\"\n  shows \"H #> h = H\"\n  using group.coset_join2[OF assms(1), of h H]\n  by (simp add: assms(2) subgroup_axioms)\n\nlemma (in subgroup) rcos_module_imp:\n  assumes \"group G\" \"x \\<in> carrier G\"\n    and \"x' \\<in> H #> x\"\n  shows \"(x' \\<otimes> inv x) \\<in> H\"\nproof -\n  obtain h where h: \"h \\<in> H\" \"x' = h \\<otimes> x\"\n    using assms(3) unfolding r_coset_def by blast\n  hence \"x' \\<otimes> inv x = h\"\n    by (metis assms elemrcos_carrier group.inv_solve_right mem_carrier)\n  thus ?thesis using h by blast\nqed\n\nlemma (in subgroup) rcos_module_rev:\n  assumes \"group G\" \"x \\<in> carrier G\" \"x' \\<in> carrier G\"\n    and \"(x' \\<otimes> inv x) \\<in> H\"\n  shows \"x' \\<in> H #> x\"\nproof -\n  obtain h where h: \"h \\<in> H\" \"x' \\<otimes> inv x = h\"\n    using assms(4) unfolding r_coset_def by blast\n  hence \"x' = h \\<otimes> x\"\n    by (metis assms group.inv_solve_right mem_carrier)\n  thus ?thesis using h unfolding r_coset_def by blast\nqed\n\ntext \\<open>Module property of right cosets\\<close>\nlemma (in subgroup) rcos_module:\n  assumes \"group G\" \"x \\<in> carrier G\" \"x' \\<in> carrier G\"\n  shows \"(x' \\<in> H #> x) = (x' \\<otimes> inv x \\<in> H)\"\n  using rcos_module_rev rcos_module_imp assms by blast\n\ntext \\<open>Right cosets are subsets of the carrier.\\<close>\nlemma (in subgroup) rcosets_carrier:\n  assumes \"group G\" \"X \\<in> rcosets H\"\n  shows \"X \\<subseteq> carrier G\"\n  using assms elemrcos_carrier singletonD\n  subset_eq unfolding RCOSETS_def by force\n\n\ntext \\<open>Multiplication of general subsets\\<close>\n\nlemma (in comm_group) mult_subgroups:\n  assumes HG: \"subgroup H G\" and KG: \"subgroup K G\"\n  shows \"subgroup (H <#> K) G\"\nproof (rule subgroup.intro)\n  show \"H <#> K \\<subseteq> carrier G\"\n    by (simp add: setmult_subset_G assms subgroup.subset)\nnext\n  have \"\\<one> \\<otimes> \\<one> \\<in> H <#> K\"\n    unfolding set_mult_def using assms subgroup.one_closed by blast\n  thus \"\\<one> \\<in> H <#> K\" by simp\nnext\n  show \"\\<And>x. x \\<in> H <#> K \\<Longrightarrow> inv x \\<in> H <#> K\"\n  proof -\n    fix x assume \"x \\<in> H <#> K\"\n    then obtain h k where hk: \"h \\<in> H\" \"k \\<in> K\" \"x = h \\<otimes> k\"\n      unfolding set_mult_def by blast\n    hence \"inv x = (inv k) \\<otimes> (inv h)\"\n      by (meson inv_mult_group assms subgroup.mem_carrier)\n    hence \"inv x = (inv h) \\<otimes> (inv k)\"\n      by (metis hk inv_mult assms subgroup.mem_carrier)\n    thus \"inv x \\<in> H <#> K\"\n      unfolding set_mult_def using hk assms\n      by (metis (no_types, lifting) UN_iff singletonI subgroup_def)\n  qed\nnext\n  show \"\\<And>x y. x \\<in> H <#> K \\<Longrightarrow> y \\<in> H <#> K \\<Longrightarrow> x \\<otimes> y \\<in> H <#> K\"\n  proof -\n    fix x y assume \"x \\<in> H <#> K\" \"y \\<in> H <#> K\"\n    then obtain h1 k1 h2 k2 where h1k1: \"h1 \\<in> H\" \"k1 \\<in> K\" \"x = h1 \\<otimes> k1\"\n                              and h2k2: \"h2 \\<in> H\" \"k2 \\<in> K\" \"y = h2 \\<otimes> k2\"\n      unfolding set_mult_def by blast\n    with KG HG have carr: \"k1 \\<in> carrier G\" \"h1 \\<in> carrier G\" \"k2 \\<in> carrier G\" \"h2 \\<in> carrier G\"\n        by (meson subgroup.mem_carrier)+\n    have \"x \\<otimes> y = (h1 \\<otimes> k1) \\<otimes> (h2 \\<otimes> k2)\"\n      using h1k1 h2k2 by simp\n    also have \" ... = h1 \\<otimes> (k1 \\<otimes> h2) \\<otimes> k2\"\n        by (simp add: carr comm_groupE(3) comm_group_axioms)\n    also have \" ... = h1 \\<otimes> (h2 \\<otimes> k1) \\<otimes> k2\"\n      by (simp add: carr m_comm)\n    finally have \"x \\<otimes> y  = (h1 \\<otimes> h2) \\<otimes> (k1 \\<otimes> k2)\"\n      by (simp add: carr comm_groupE(3) comm_group_axioms)\n    thus \"x \\<otimes> y \\<in> H <#> K\" unfolding set_mult_def\n      using subgroup.m_closed[OF assms(1) h1k1(1) h2k2(1)]\n            subgroup.m_closed[OF assms(2) h1k1(2) h2k2(2)] by blast\n  qed\nqed\n\nlemma (in subgroup) lcos_module_rev:\n  assumes \"group G\" \"x \\<in> carrier G\" \"x' \\<in> carrier G\"\n    and \"(inv x \\<otimes> x') \\<in> H\"\n  shows \"x' \\<in> x <# H\"\nproof -\n  obtain h where h: \"h \\<in> H\" \"inv x \\<otimes> x' = h\"\n    using assms(4) unfolding l_coset_def by blast\n  hence \"x' = x \\<otimes> h\"\n    by (metis assms group.inv_solve_left mem_carrier)\n  thus ?thesis using h unfolding l_coset_def by blast\nqed\n\n\nsubsection \\<open>Normal subgroups\\<close>\n\nlemma normal_imp_subgroup: \"H \\<lhd> G \\<Longrightarrow> subgroup H G\"\n  by (rule normal.axioms(1))\n\nlemma (in group) normalI:\n  \"subgroup H G \\<Longrightarrow> (\\<forall>x \\<in> carrier G. H #> x = x <# H) \\<Longrightarrow> H \\<lhd> G\"\n  by (simp add: normal_def normal_axioms_def is_group)\n\nlemma (in normal) inv_op_closed1:\n  assumes \"x \\<in> carrier G\" and \"h \\<in> H\"\n  shows \"(inv x) \\<otimes> h \\<otimes> x \\<in> H\"\nproof -\n  have \"h \\<otimes> x \\<in> x <# H\"\n    using assms coset_eq assms(1) unfolding r_coset_def by blast\n  then obtain h' where \"h' \\<in> H\" \"h \\<otimes> x = x \\<otimes> h'\"\n    unfolding l_coset_def by blast\n  thus ?thesis by (metis assms inv_closed l_inv l_one m_assoc mem_carrier)\nqed\n\nlemma (in normal) inv_op_closed2:\n  assumes \"x \\<in> carrier G\" and \"h \\<in> H\"\n  shows \"x \\<otimes> h \\<otimes> (inv x) \\<in> H\"\n  using assms inv_op_closed1 by (metis inv_closed inv_inv)\n\nlemma (in comm_group) normal_iff_subgroup:\n  \"N \\<lhd> G \\<longleftrightarrow> subgroup N G\"\nproof\n  assume \"subgroup N G\"\n  then show \"N \\<lhd> G\"\n    by unfold_locales (auto simp: subgroupE subgroup.one_closed l_coset_def r_coset_def m_comm subgroup.mem_carrier)\nqed (simp add: normal_imp_subgroup)\n\n\ntext\\<open>Alternative characterization of normal subgroups\\<close>\nlemma (in group) normal_inv_iff:\n     \"(N \\<lhd> G) =\n      (subgroup N G \\<and> (\\<forall>x \\<in> carrier G. \\<forall>h \\<in> N. x \\<otimes> h \\<otimes> (inv x) \\<in> N))\"\n      (is \"_ = ?rhs\")\nproof\n  assume N: \"N \\<lhd> G\"\n  show ?rhs\n    by (blast intro: N normal.inv_op_closed2 normal_imp_subgroup)\nnext\n  assume ?rhs\n  hence sg: \"subgroup N G\"\n    and closed: \"\\<And>x. x\\<in>carrier G \\<Longrightarrow> \\<forall>h\\<in>N. x \\<otimes> h \\<otimes> inv x \\<in> N\" by auto\n  hence sb: \"N \\<subseteq> carrier G\" by (simp add: subgroup.subset)\n  show \"N \\<lhd> G\"\n  proof (intro normalI [OF sg], simp add: l_coset_def r_coset_def, clarify)\n    fix x\n    assume x: \"x \\<in> carrier G\"\n    show \"(\\<Union>h\\<in>N. {h \\<otimes> x}) = (\\<Union>h\\<in>N. {x \\<otimes> h})\"\n    proof\n      show \"(\\<Union>h\\<in>N. {h \\<otimes> x}) \\<subseteq> (\\<Union>h\\<in>N. {x \\<otimes> h})\"\n      proof clarify\n        fix n\n        assume n: \"n \\<in> N\"\n        show \"n \\<otimes> x \\<in> (\\<Union>h\\<in>N. {x \\<otimes> h})\"\n        proof\n          from closed [of \"inv x\"]\n          show \"inv x \\<otimes> n \\<otimes> x \\<in> N\" by (simp add: x n)\n          show \"n \\<otimes> x \\<in> {x \\<otimes> (inv x \\<otimes> n \\<otimes> x)}\"\n            by (simp add: x n m_assoc [symmetric] sb [THEN subsetD])\n        qed\n      qed\n    next\n      show \"(\\<Union>h\\<in>N. {x \\<otimes> h}) \\<subseteq> (\\<Union>h\\<in>N. {h \\<otimes> x})\"\n      proof clarify\n        fix n\n        assume n: \"n \\<in> N\"\n        show \"x \\<otimes> n \\<in> (\\<Union>h\\<in>N. {h \\<otimes> x})\"\n        proof\n          show \"x \\<otimes> n \\<otimes> inv x \\<in> N\" by (simp add: x n closed)\n          show \"x \\<otimes> n \\<in> {x \\<otimes> n \\<otimes> inv x \\<otimes> x}\"\n            by (simp add: x n m_assoc sb [THEN subsetD])\n        qed\n      qed\n    qed\n  qed\nqed\n\ncorollary (in group) normal_invI:\n  assumes \"subgroup N G\" and \"\\<And>x h. \\<lbrakk> x \\<in> carrier G; h \\<in> N \\<rbrakk> \\<Longrightarrow> x \\<otimes> h \\<otimes> inv x \\<in> N\"\n  shows \"N \\<lhd> G\"\n  using assms normal_inv_iff by blast\n\ncorollary (in group) normal_invE:\n  assumes \"N \\<lhd> G\"\n  shows \"subgroup N G\" and \"\\<And>x h. \\<lbrakk> x \\<in> carrier G; h \\<in> N \\<rbrakk> \\<Longrightarrow> x \\<otimes> h \\<otimes> inv x \\<in> N\"\n  using assms normal_inv_iff apply blast\n  by (simp add: assms normal.inv_op_closed2)\n\n\nlemma (in group) one_is_normal: \"{\\<one>} \\<lhd> G\"\nproof(intro normal_invI)\n  show \"subgroup {\\<one>} G\"\n    by (simp add: subgroup_def)\nqed simp\n\n\nsubsection\\<open>More Properties of Left Cosets\\<close>\n\nlemma (in group) l_repr_independence:\n  assumes \"y \\<in> x <# H\" \"x \\<in> carrier G\" and HG: \"subgroup H G\"\n  shows \"x <# H = y <# H\"\nproof -\n  obtain h' where h': \"h' \\<in> H\" \"y = x \\<otimes> h'\"\n    using assms(1) unfolding l_coset_def by blast\n  hence \"x \\<otimes> h = y \\<otimes> ((inv h') \\<otimes> h)\" if \"h \\<in> H\" for h\n  proof -\n    have \"h' \\<in> carrier G\"\n      by (meson HG h'(1) subgroup.mem_carrier)\n    moreover have \"h \\<in> carrier G\"\n      by (meson HG subgroup.mem_carrier that)\n    ultimately show ?thesis\n      by (metis assms(2) h'(2) inv_closed inv_solve_right m_assoc m_closed)\n  qed\n  hence \"\\<And>xh. xh \\<in> x <# H \\<Longrightarrow> xh \\<in> y <# H\"\n    unfolding l_coset_def by (metis (no_types, lifting) UN_iff HG h'(1) subgroup_def)\n  moreover have \"\\<And>h. h \\<in> H \\<Longrightarrow> y \\<otimes> h = x \\<otimes> (h' \\<otimes> h)\"\n    using h' by (meson assms(2) HG m_assoc subgroup.mem_carrier)\n  hence \"\\<And>yh. yh \\<in> y <# H \\<Longrightarrow> yh \\<in> x <# H\"\n    unfolding l_coset_def using subgroup.m_closed[OF HG h'(1)] by blast\n  ultimately show ?thesis by blast\nqed\n\nlemma (in group) lcos_m_assoc:\n  \"\\<lbrakk> M \\<subseteq> carrier G; g \\<in> carrier G; h \\<in> carrier G \\<rbrakk> \\<Longrightarrow> g <# (h <# M) = (g \\<otimes> h) <# M\"\nby (force simp add: l_coset_def m_assoc)\n\nlemma (in group) lcos_mult_one: \"M \\<subseteq> carrier G \\<Longrightarrow> \\<one> <# M = M\"\nby (force simp add: l_coset_def)\n\nlemma (in group) l_coset_subset_G:\n  \"\\<lbrakk> H \\<subseteq> carrier G; x \\<in> carrier G \\<rbrakk> \\<Longrightarrow> x <# H \\<subseteq> carrier G\"\nby (auto simp add: l_coset_def subsetD)\n\nlemma (in group) l_coset_carrier:\n  \"\\<lbrakk> y \\<in> x <# H; x \\<in> carrier G; subgroup H G \\<rbrakk> \\<Longrightarrow> y \\<in> carrier G\"\n  by (auto simp add: l_coset_def m_assoc  subgroup.subset [THEN subsetD] subgroup.m_closed)\n\nlemma (in group) l_coset_swap:\n  assumes \"y \\<in> x <# H\" \"x \\<in> carrier G\" \"subgroup H G\"\n  shows \"x \\<in> y <# H\"\n  using assms(2) l_repr_independence[OF assms] subgroup.one_closed[OF assms(3)]\n  unfolding l_coset_def by fastforce\n\nlemma (in group) subgroup_mult_id:\n  assumes \"subgroup H G\"\n  shows \"H <#> H = H\"\nproof\n  show \"H <#> H \\<subseteq> H\"\n    unfolding set_mult_def using subgroup.m_closed[OF assms] by (simp add: UN_subset_iff)\n  show \"H \\<subseteq> H <#> H\"\n  proof\n    fix x assume x: \"x \\<in> H\" thus \"x \\<in> H <#> H\" unfolding set_mult_def\n      using subgroup.m_closed[OF assms subgroup.one_closed[OF assms] x] subgroup.one_closed[OF assms]\n      using assms subgroup.mem_carrier by force\n  qed\nqed\n\n\nsubsubsection \\<open>Set of Inverses of an \\<open>r_coset\\<close>.\\<close>\n\nlemma (in normal) rcos_inv:\n  assumes x:     \"x \\<in> carrier G\"\n  shows \"set_inv (H #> x) = H #> (inv x)\"\nproof (simp add: r_coset_def SET_INV_def x inv_mult_group, safe)\n  fix h\n  assume h: \"h \\<in> H\"\n  show \"inv x \\<otimes> inv h \\<in> (\\<Union>j\\<in>H. {j \\<otimes> inv x})\"\n  proof\n    show \"inv x \\<otimes> inv h \\<otimes> x \\<in> H\"\n      by (simp add: inv_op_closed1 h x)\n    show \"inv x \\<otimes> inv h \\<in> {inv x \\<otimes> inv h \\<otimes> x \\<otimes> inv x}\"\n      by (simp add: h x m_assoc)\n  qed\n  show \"h \\<otimes> inv x \\<in> (\\<Union>j\\<in>H. {inv x \\<otimes> inv j})\"\n  proof\n    show \"x \\<otimes> inv h \\<otimes> inv x \\<in> H\"\n      by (simp add: inv_op_closed2 h x)\n    show \"h \\<otimes> inv x \\<in> {inv x \\<otimes> inv (x \\<otimes> inv h \\<otimes> inv x)}\"\n      by (simp add: h x m_assoc [symmetric] inv_mult_group)\n  qed\nqed\n\n\nsubsubsection \\<open>Theorems for \\<open><#>\\<close> with \\<open>#>\\<close> or \\<open><#\\<close>.\\<close>\n\nlemma (in group) setmult_rcos_assoc:\n  \"\\<lbrakk>H \\<subseteq> carrier G; K \\<subseteq> carrier G; x \\<in> carrier G\\<rbrakk> \\<Longrightarrow>\n    H <#> (K #> x) = (H <#> K) #> x\"\n  using set_mult_assoc[of H K \"{x}\"] by (simp add: r_coset_eq_set_mult)\n\nlemma (in group) rcos_assoc_lcos:\n  \"\\<lbrakk>H \\<subseteq> carrier G; K \\<subseteq> carrier G; x \\<in> carrier G\\<rbrakk> \\<Longrightarrow>\n   (H #> x) <#> K = H <#> (x <# K)\"\n  using set_mult_assoc[of H \"{x}\" K]\n  by (simp add: l_coset_eq_set_mult r_coset_eq_set_mult)\n\nlemma (in normal) rcos_mult_step1:\n  \"\\<lbrakk>x \\<in> carrier G; y \\<in> carrier G\\<rbrakk> \\<Longrightarrow>\n   (H #> x) <#> (H #> y) = (H <#> (x <# H)) #> y\"\n  by (simp add: setmult_rcos_assoc r_coset_subset_G\n                subset l_coset_subset_G rcos_assoc_lcos)\n\nlemma (in normal) rcos_mult_step2:\n     \"\\<lbrakk>x \\<in> carrier G; y \\<in> carrier G\\<rbrakk>\n      \\<Longrightarrow> (H <#> (x <# H)) #> y = (H <#> (H #> x)) #> y\"\nby (insert coset_eq, simp add: normal_def)\n\nlemma (in normal) rcos_mult_step3:\n     \"\\<lbrakk>x \\<in> carrier G; y \\<in> carrier G\\<rbrakk>\n      \\<Longrightarrow> (H <#> (H #> x)) #> y = H #> (x \\<otimes> y)\"\nby (simp add: setmult_rcos_assoc coset_mult_assoc\n              subgroup_mult_id normal.axioms subset normal_axioms)\n\nlemma (in normal) rcos_sum:\n     \"\\<lbrakk>x \\<in> carrier G; y \\<in> carrier G\\<rbrakk>\n      \\<Longrightarrow> (H #> x) <#> (H #> y) = H #> (x \\<otimes> y)\"\nby (simp add: rcos_mult_step1 rcos_mult_step2 rcos_mult_step3)\n\nlemma (in normal) rcosets_mult_eq: \"M \\<in> rcosets H \\<Longrightarrow> H <#> M = M\"\n  \\<comment> \\<open>generalizes \\<open>subgroup_mult_id\\<close>\\<close>\n  by (auto simp add: RCOSETS_def subset\n        setmult_rcos_assoc subgroup_mult_id normal.axioms normal_axioms)\n\n\nsubsubsection\\<open>An Equivalence Relation\\<close>\n\ndefinition\n  r_congruent :: \"[('a,'b)monoid_scheme, 'a set] \\<Rightarrow> ('a*'a)set\"  (\"rcong\\<index> _\")\n  where \"rcong\\<^bsub>G\\<^esub> H = {(x,y). x \\<in> carrier G \\<and> y \\<in> carrier G \\<and> inv\\<^bsub>G\\<^esub> x \\<otimes>\\<^bsub>G\\<^esub> y \\<in> H}\"\n\n\nlemma (in subgroup) equiv_rcong:\n   assumes \"group G\"\n   shows \"equiv (carrier G) (rcong H)\"\nproof -\n  interpret group G by fact\n  show ?thesis\n  proof (intro equivI)\n    show \"refl_on (carrier G) (rcong H)\"\n      by (auto simp add: r_congruent_def refl_on_def)\n  next\n    show \"sym (rcong H)\"\n    proof (simp add: r_congruent_def sym_def, clarify)\n      fix x y\n      assume [simp]: \"x \\<in> carrier G\" \"y \\<in> carrier G\"\n         and \"inv x \\<otimes> y \\<in> H\"\n      hence \"inv (inv x \\<otimes> y) \\<in> H\" by simp\n      thus \"inv y \\<otimes> x \\<in> H\" by (simp add: inv_mult_group)\n    qed\n  next\n    show \"trans (rcong H)\"\n    proof (simp add: r_congruent_def trans_def, clarify)\n      fix x y z\n      assume [simp]: \"x \\<in> carrier G\" \"y \\<in> carrier G\" \"z \\<in> carrier G\"\n         and \"inv x \\<otimes> y \\<in> H\" and \"inv y \\<otimes> z \\<in> H\"\n      hence \"(inv x \\<otimes> y) \\<otimes> (inv y \\<otimes> z) \\<in> H\" by simp\n      hence \"inv x \\<otimes> (y \\<otimes> inv y) \\<otimes> z \\<in> H\"\n        by (simp add: m_assoc del: r_inv Units_r_inv)\n      thus \"inv x \\<otimes> z \\<in> H\" by simp\n    qed\n  qed\nqed\n\ntext\\<open>Equivalence classes of \\<open>rcong\\<close> correspond to left cosets.\n  Was there a mistake in the definitions? I'd have expected them to\n  correspond to right cosets.\\<close>\n\n(* CB: This is correct, but subtle.\n   We call H #> a the right coset of a relative to H.  According to\n   Jacobson, this is what the majority of group theory literature does.\n   He then defines the notion of congruence relation ~ over monoids as\n   equivalence relation with a ~ a' & b ~ b' \\<Longrightarrow> a*b ~ a'*b'.\n   Our notion of right congruence induced by K: rcong K appears only in\n   the context where K is a normal subgroup.  Jacobson doesn't name it.\n   But in this context left and right cosets are identical.\n*)\n\nlemma (in subgroup) l_coset_eq_rcong:\n  assumes \"group G\"\n  assumes a: \"a \\<in> carrier G\"\n  shows \"a <# H = (rcong H) `` {a}\"\nproof -\n  interpret group G by fact\n  show ?thesis by (force simp add: r_congruent_def l_coset_def m_assoc [symmetric] a )\nqed\n\n\nsubsubsection\\<open>Two Distinct Right Cosets are Disjoint\\<close>\n\nlemma (in group) rcos_equation:\n  assumes \"subgroup H G\"\n  assumes p: \"ha \\<otimes> a = h \\<otimes> b\" \"a \\<in> carrier G\" \"b \\<in> carrier G\" \"h \\<in> H\" \"ha \\<in> H\" \"hb \\<in> H\"\n  shows \"hb \\<otimes> a \\<in> (\\<Union>h\\<in>H. {h \\<otimes> b})\"\nproof -\n  interpret subgroup H G by fact\n  from p show ?thesis \n    by (rule_tac UN_I [of \"hb \\<otimes> ((inv ha) \\<otimes> h)\"]) (auto simp: inv_solve_left m_assoc)\nqed\n\nlemma (in group) rcos_disjoint:\n  assumes \"subgroup H G\"\n  shows \"pairwise disjnt (rcosets H)\"\nproof -\n  interpret subgroup H G by fact\n  show ?thesis\n    unfolding RCOSETS_def r_coset_def pairwise_def disjnt_def\n    by (blast intro: rcos_equation assms sym)\nqed\n\n\nsubsection \\<open>Further lemmas for \\<open>r_congruent\\<close>\\<close>\n\ntext \\<open>The relation is a congruence\\<close>\n\nlemma (in normal) congruent_rcong:\n  shows \"congruent2 (rcong H) (rcong H) (\\<lambda>a b. a \\<otimes> b <# H)\"\nproof (intro congruent2I[of \"carrier G\" _ \"carrier G\" _] equiv_rcong is_group)\n  fix a b c\n  assume abrcong: \"(a, b) \\<in> rcong H\"\n    and ccarr: \"c \\<in> carrier G\"\n\n  from abrcong\n      have acarr: \"a \\<in> carrier G\"\n        and bcarr: \"b \\<in> carrier G\"\n        and abH: \"inv a \\<otimes> b \\<in> H\"\n      unfolding r_congruent_def\n      by fast+\n\n  note carr = acarr bcarr ccarr\n\n  from ccarr and abH\n      have \"inv c \\<otimes> (inv a \\<otimes> b) \\<otimes> c \\<in> H\" by (rule inv_op_closed1)\n  moreover\n      from carr and inv_closed\n      have \"inv c \\<otimes> (inv a \\<otimes> b) \\<otimes> c = (inv c \\<otimes> inv a) \\<otimes> (b \\<otimes> c)\"\n      by (force cong: m_assoc)\n  moreover\n      from carr and inv_closed\n      have \"\\<dots> = (inv (a \\<otimes> c)) \\<otimes> (b \\<otimes> c)\"\n      by (simp add: inv_mult_group)\n  ultimately\n      have \"(inv (a \\<otimes> c)) \\<otimes> (b \\<otimes> c) \\<in> H\" by simp\n  from carr and this\n     have \"(b \\<otimes> c) \\<in> (a \\<otimes> c) <# H\"\n     by (simp add: lcos_module_rev[OF is_group])\n  from carr and this and is_subgroup\n     show \"(a \\<otimes> c) <# H = (b \\<otimes> c) <# H\" by (intro l_repr_independence, simp+)\nnext\n  fix a b c\n  assume abrcong: \"(a, b) \\<in> rcong H\"\n    and ccarr: \"c \\<in> carrier G\"\n\n  from ccarr have \"c \\<in> Units G\" by simp\n  hence cinvc_one: \"inv c \\<otimes> c = \\<one>\" by (rule Units_l_inv)\n\n  from abrcong\n      have acarr: \"a \\<in> carrier G\"\n       and bcarr: \"b \\<in> carrier G\"\n       and abH: \"inv a \\<otimes> b \\<in> H\"\n      by (unfold r_congruent_def, fast+)\n\n  note carr = acarr bcarr ccarr\n\n  from carr and inv_closed\n     have \"inv a \\<otimes> b = inv a \\<otimes> (\\<one> \\<otimes> b)\" by simp\n  also from carr and inv_closed\n      have \"\\<dots> = inv a \\<otimes> (inv c \\<otimes> c) \\<otimes> b\" by simp\n  also from carr and inv_closed\n      have \"\\<dots> = (inv a \\<otimes> inv c) \\<otimes> (c \\<otimes> b)\" by (force cong: m_assoc)\n  also from carr and inv_closed\n      have \"\\<dots> = inv (c \\<otimes> a) \\<otimes> (c \\<otimes> b)\" by (simp add: inv_mult_group)\n  finally\n      have \"inv a \\<otimes> b = inv (c \\<otimes> a) \\<otimes> (c \\<otimes> b)\" .\n  from abH and this\n      have \"inv (c \\<otimes> a) \\<otimes> (c \\<otimes> b) \\<in> H\" by simp\n\n  from carr and this\n     have \"(c \\<otimes> b) \\<in> (c \\<otimes> a) <# H\"\n     by (simp add: lcos_module_rev[OF is_group])\n  from carr and this and is_subgroup\n     show \"(c \\<otimes> a) <# H = (c \\<otimes> b) <# H\" by (intro l_repr_independence, simp+)\nqed\n\n\nsubsection \\<open>Order of a Group and Lagrange's Theorem\\<close>\n\ndefinition\n  order :: \"('a, 'b) monoid_scheme \\<Rightarrow> nat\"\n  where \"order S = card (carrier S)\"\n\nlemma (in monoid) order_gt_0_iff_finite: \"0 < order G \\<longleftrightarrow> finite (carrier G)\"\nby(auto simp add: order_def card_gt_0_iff)\n\nlemma (in group) rcosets_part_G:\n  assumes \"subgroup H G\"\n  shows \"\\<Union>(rcosets H) = carrier G\"\nproof -\n  interpret subgroup H G by fact\n  show ?thesis\n    unfolding RCOSETS_def r_coset_def by auto\nqed\n\nlemma (in group) cosets_finite:\n     \"\\<lbrakk>c \\<in> rcosets H;  H \\<subseteq> carrier G;  finite (carrier G)\\<rbrakk> \\<Longrightarrow> finite c\"\n  unfolding RCOSETS_def\n  by (auto simp add: r_coset_subset_G [THEN finite_subset])\n\ntext\\<open>The next two lemmas support the proof of \\<open>card_cosets_equal\\<close>.\\<close>\nlemma (in group) inj_on_f:\n  assumes \"H \\<subseteq> carrier G\" and a: \"a \\<in> carrier G\"\n  shows \"inj_on (\\<lambda>y. y \\<otimes> inv a) (H #> a)\"\nproof \n  fix x y\n  assume \"x \\<in> H #> a\" \"y \\<in> H #> a\" and xy: \"x \\<otimes> inv a = y \\<otimes> inv a\"\n  then have \"x \\<in> carrier G\" \"y \\<in> carrier G\"\n    using assms r_coset_subset_G by blast+\n  with xy a show \"x = y\"\n    by auto\nqed\n\nlemma (in group) inj_on_g:\n    \"\\<lbrakk>H \\<subseteq> carrier G;  a \\<in> carrier G\\<rbrakk> \\<Longrightarrow> inj_on (\\<lambda>y. y \\<otimes> a) H\"\nby (force simp add: inj_on_def subsetD)\n\n(* ************************************************************************** *)\n\nlemma (in group) card_cosets_equal:\n  assumes \"R \\<in> rcosets H\" \"H \\<subseteq> carrier G\"\n  shows \"\\<exists>f. bij_betw f H R\"\nproof -\n  obtain g where g: \"g \\<in> carrier G\" \"R = H #> g\"\n    using assms(1) unfolding RCOSETS_def by blast\n\n  let ?f = \"\\<lambda>h. h \\<otimes> g\"\n  have \"\\<And>r. r \\<in> R \\<Longrightarrow> \\<exists>h \\<in> H. ?f h = r\"\n  proof -\n    fix r assume \"r \\<in> R\"\n    then obtain h where \"h \\<in> H\" \"r = h \\<otimes> g\"\n      using g unfolding r_coset_def by blast\n    thus \"\\<exists>h \\<in> H. ?f h = r\" by blast\n  qed\n  hence \"R \\<subseteq> ?f ` H\" by blast\n  moreover have \"?f ` H \\<subseteq> R\"\n    using g unfolding r_coset_def by blast\n  ultimately show ?thesis using inj_on_g unfolding bij_betw_def\n    using assms(2) g(1) by auto\nqed\n\ncorollary (in group) card_rcosets_equal:\n  assumes \"R \\<in> rcosets H\" \"H \\<subseteq> carrier G\"\n  shows \"card H = card R\"\n  using card_cosets_equal assms bij_betw_same_card by blast\n\ncorollary (in group) rcosets_finite:\n  assumes \"R \\<in> rcosets H\" \"H \\<subseteq> carrier G\" \"finite H\"\n  shows \"finite R\"\n  using card_cosets_equal assms bij_betw_finite is_group by blast\n\n(* ************************************************************************** *)\n\nlemma (in group) rcosets_subset_PowG:\n     \"subgroup H G  \\<Longrightarrow> rcosets H \\<subseteq> Pow(carrier G)\"\n  using rcosets_part_G by auto\n\nproposition (in group) lagrange_finite:\n  assumes \"finite(carrier G)\" and HG: \"subgroup H G\"\n  shows \"card(rcosets H) * card(H) = order(G)\"\nproof -\n  have \"card H * card (rcosets H) = card (\\<Union>(rcosets H))\"\n  proof (rule card_partition)\n    show \"\\<And>c1 c2. \\<lbrakk>c1 \\<in> rcosets H; c2 \\<in> rcosets H; c1 \\<noteq> c2\\<rbrakk> \\<Longrightarrow> c1 \\<inter> c2 = {}\"\n      using HG rcos_disjoint by (auto simp: pairwise_def disjnt_def)\n  qed (auto simp: assms finite_UnionD rcosets_part_G card_rcosets_equal subgroup.subset)\n  then show ?thesis\n    by (simp add: HG mult.commute order_def rcosets_part_G)\nqed\n\ntheorem (in group) lagrange:\n  assumes \"subgroup H G\"\n  shows \"card (rcosets H) * card H = order G\"\nproof (cases \"finite (carrier G)\")\n  case True thus ?thesis using lagrange_finite assms by simp\nnext\n  case False \n  thus ?thesis\n  proof (cases \"finite H\")\n    case False thus ?thesis using \\<open>infinite (carrier G)\\<close>  by (simp add: order_def)\n  next\n    case True \n    have \"infinite (rcosets H)\"\n    proof \n      assume \"finite (rcosets H)\"\n      hence finite_rcos: \"finite (rcosets H)\" by simp\n      hence \"card (\\<Union>(rcosets H)) = (\\<Sum>R\\<in>(rcosets H). card R)\"\n        using card_Union_disjoint[of \"rcosets H\"] \\<open>finite H\\<close> rcos_disjoint[OF assms(1)]\n              rcosets_finite[where ?H = H] by (simp add: assms subgroup.subset)\n      hence \"order G = (\\<Sum>R\\<in>(rcosets H). card R)\"\n        by (simp add: assms order_def rcosets_part_G)\n      hence \"order G = (\\<Sum>R\\<in>(rcosets H). card H)\"\n        using card_rcosets_equal by (simp add: assms subgroup.subset)\n      hence \"order G = (card H) * (card (rcosets H))\" by simp\n      hence \"order G \\<noteq> 0\" using finite_rcos \\<open>finite H\\<close> assms ex_in_conv\n                                rcosets_part_G subgroup.one_closed by fastforce\n      thus False using \\<open>infinite (carrier G)\\<close> order_gt_0_iff_finite by blast\n    qed\n    thus ?thesis using \\<open>infinite (carrier G)\\<close> by (simp add: order_def)\n  qed\nqed\n\n\nsubsection \\<open>Quotient Groups: Factorization of a Group\\<close>\n\ndefinition\n  FactGroup :: \"[('a,'b) monoid_scheme, 'a set] \\<Rightarrow> ('a set) monoid\" (infixl \"Mod\" 65)\n    \\<comment> \\<open>Actually defined for groups rather than monoids\\<close>\n   where \"FactGroup G H = \\<lparr>carrier = rcosets\\<^bsub>G\\<^esub> H, mult = set_mult G, one = H\\<rparr>\"\n\nlemma (in normal) setmult_closed:\n     \"\\<lbrakk>K1 \\<in> rcosets H; K2 \\<in> rcosets H\\<rbrakk> \\<Longrightarrow> K1 <#> K2 \\<in> rcosets H\"\nby (auto simp add: rcos_sum RCOSETS_def)\n\nlemma (in normal) setinv_closed:\n     \"K \\<in> rcosets H \\<Longrightarrow> set_inv K \\<in> rcosets H\"\nby (auto simp add: rcos_inv RCOSETS_def)\n\nlemma (in normal) rcosets_assoc:\n     \"\\<lbrakk>M1 \\<in> rcosets H; M2 \\<in> rcosets H; M3 \\<in> rcosets H\\<rbrakk>\n      \\<Longrightarrow> M1 <#> M2 <#> M3 = M1 <#> (M2 <#> M3)\"\n  by (simp add: group.set_mult_assoc is_group rcosets_carrier)\n\nlemma (in subgroup) subgroup_in_rcosets:\n  assumes \"group G\"\n  shows \"H \\<in> rcosets H\"\nproof -\n  interpret group G by fact\n  from _ subgroup_axioms have \"H #> \\<one> = H\"\n    by (rule coset_join2) auto\n  then show ?thesis\n    by (auto simp add: RCOSETS_def)\nqed\n\nlemma (in normal) rcosets_inv_mult_group_eq:\n     \"M \\<in> rcosets H \\<Longrightarrow> set_inv M <#> M = H\"\nby (auto simp add: RCOSETS_def rcos_inv rcos_sum subgroup.subset normal.axioms normal_axioms)\n\ntheorem (in normal) factorgroup_is_group:\n  \"group (G Mod H)\"\n  unfolding FactGroup_def\n  apply (rule groupI)\n    apply (simp add: setmult_closed)\n   apply (simp add: normal_imp_subgroup subgroup_in_rcosets [OF is_group])\n  apply (simp add: restrictI setmult_closed rcosets_assoc)\n apply (simp add: normal_imp_subgroup\n                  subgroup_in_rcosets rcosets_mult_eq)\napply (auto dest: rcosets_inv_mult_group_eq simp add: setinv_closed)\ndone\n\nlemma carrier_FactGroup: \"carrier(G Mod N) = (\\<lambda>x. r_coset G N x) ` carrier G\"\n  by (auto simp: FactGroup_def RCOSETS_def)\n\nlemma one_FactGroup [simp]: \"one(G Mod N) = N\"\n  by (auto simp: FactGroup_def)\n\nlemma mult_FactGroup [simp]: \"monoid.mult (G Mod N) = set_mult G\"\n  by (auto simp: FactGroup_def)\n\nlemma (in normal) inv_FactGroup:\n  assumes \"X \\<in> carrier (G Mod H)\"\n  shows \"inv\\<^bsub>G Mod H\\<^esub> X = set_inv X\"\nproof -\n  have X: \"X \\<in> rcosets H\"\n    using assms by (simp add: FactGroup_def)\n  moreover have \"set_inv X <#> X = H\"\n    using X by (simp add: normal.rcosets_inv_mult_group_eq normal_axioms)\n  moreover have \"Group.group (G Mod H)\"\n    using normal.factorgroup_is_group normal_axioms by blast\n  moreover have \"set_inv X \\<in> rcosets H\"\n    by (simp add: \\<open>X \\<in> rcosets H\\<close> setinv_closed)\n  ultimately show ?thesis\n    by (simp add: FactGroup_def group.inv_equality)\nqed\n\ntext\\<open>The coset map is a homomorphism from \\<^term>\\<open>G\\<close> to the quotient group\n  \\<^term>\\<open>G Mod H\\<close>\\<close>\nlemma (in normal) r_coset_hom_Mod:\n  \"(\\<lambda>a. H #> a) \\<in> hom G (G Mod H)\"\n  by (auto simp add: FactGroup_def RCOSETS_def Pi_def hom_def rcos_sum)\n\n\nlemma (in comm_group) set_mult_commute:\n  assumes \"N \\<subseteq> carrier G\" \"x \\<in> rcosets N\" \"y \\<in> rcosets N\"\n  shows \"x <#> y = y <#> x\"\n  using assms unfolding set_mult_def RCOSETS_def\n  by auto (metis m_comm r_coset_subset_G subsetCE)+\n\nlemma (in comm_group) abelian_FactGroup:\n  assumes \"subgroup N G\" shows \"comm_group(G Mod N)\"\nproof (rule group.group_comm_groupI)\n  have \"N \\<lhd> G\"\n    by (simp add: assms normal_iff_subgroup)\n  then show \"Group.group (G Mod N)\"\n    by (simp add: normal.factorgroup_is_group)\n  fix x :: \"'a set\" and y :: \"'a set\"\n  assume \"x \\<in> carrier (G Mod N)\" \"y \\<in> carrier (G Mod N)\"\n  then show \"x \\<otimes>\\<^bsub>G Mod N\\<^esub> y = y \\<otimes>\\<^bsub>G Mod N\\<^esub> x\"\n    apply (simp add: FactGroup_def subgroup_def)\n    apply (rule set_mult_commute)\n    using assms apply (auto simp: subgroup_def)\n    done\nqed\n\n\nlemma FactGroup_universal:\n  assumes \"h \\<in> hom G H\" \"N \\<lhd> G\"\n    and h: \"\\<And>x y. \\<lbrakk>x \\<in> carrier G; y \\<in> carrier G; r_coset G N x = r_coset G N y\\<rbrakk> \\<Longrightarrow> h x = h y\"\n  obtains g\n  where \"g \\<in> hom (G Mod N) H\" \"\\<And>x. x \\<in> carrier G \\<Longrightarrow> g(r_coset G N x) = h x\"\nproof -\n  obtain g where g: \"\\<And>x. x \\<in> carrier G \\<Longrightarrow> h x = g(r_coset G N x)\"\n    using h function_factors_left_gen [of \"\\<lambda>x. x \\<in> carrier G\" \"r_coset G N\" h] by blast\n  show thesis\n  proof\n    show \"g \\<in> hom (G Mod N) H\"\n    proof (rule homI)\n      show \"g (u \\<otimes>\\<^bsub>G Mod N\\<^esub> v) = g u \\<otimes>\\<^bsub>H\\<^esub> g v\"\n        if \"u \\<in> carrier (G Mod N)\" \"v \\<in> carrier (G Mod N)\" for u v\n      proof -\n        from that\n        obtain x y where xy: \"x \\<in> carrier G\" \"u = r_coset G N x\" \"y \\<in> carrier G\"  \"v = r_coset G N y\"\n          by (auto simp: carrier_FactGroup)\n        then have \"h (x \\<otimes>\\<^bsub>G\\<^esub> y) = h x \\<otimes>\\<^bsub>H\\<^esub> h y\"\n           by (metis hom_mult [OF \\<open>h \\<in> hom G H\\<close>])\n        then show ?thesis\n          by (metis Coset.mult_FactGroup xy \\<open>N \\<lhd> G\\<close> g group.subgroup_self normal.axioms(2) normal.rcos_sum subgroup_def)\n      qed\n    qed (use \\<open>h \\<in> hom G H\\<close> in \\<open>auto simp: carrier_FactGroup Pi_iff hom_def simp flip: g\\<close>)\n  qed (auto simp flip: g)\nqed\n\n\nlemma (in normal) FactGroup_pow:\n  fixes k::nat\n  assumes \"a \\<in> carrier G\"\n  shows \"pow (FactGroup G H) (r_coset G H a) k = r_coset G H (pow G a k)\"\nproof (induction k)\n  case 0\n  then show ?case\n    by (simp add: r_coset_def)\nnext\n  case (Suc k)\n  then show ?case\n    by (simp add: assms rcos_sum)\nqed\n\nlemma (in normal) FactGroup_int_pow:\n  fixes k::int\n  assumes \"a \\<in> carrier G\"\n  shows \"pow (FactGroup G H) (r_coset G H a) k = r_coset G H (pow G a k)\"\n  by (metis Group.group.axioms(1) image_eqI is_group monoid.nat_pow_closed int_pow_def2 assms\n         FactGroup_pow carrier_FactGroup inv_FactGroup rcos_inv)\n\n\nsubsection\\<open>The First Isomorphism Theorem\\<close>\n\ntext\\<open>The quotient by the kernel of a homomorphism is isomorphic to the\n  range of that homomorphism.\\<close>\n\ndefinition\n  kernel :: \"('a, 'm) monoid_scheme \\<Rightarrow> ('b, 'n) monoid_scheme \\<Rightarrow>  ('a \\<Rightarrow> 'b) \\<Rightarrow> 'a set\"\n    \\<comment> \\<open>the kernel of a homomorphism\\<close>\n  where \"kernel G H h = {x. x \\<in> carrier G \\<and> h x = \\<one>\\<^bsub>H\\<^esub>}\"\n\nlemma (in group_hom) subgroup_kernel: \"subgroup (kernel G H h) G\"\n  by (auto simp add: kernel_def group.intro is_group intro: subgroup.intro)\n\ntext\\<open>The kernel of a homomorphism is a normal subgroup\\<close>\nlemma (in group_hom) normal_kernel: \"(kernel G H h) \\<lhd> G\"\n  apply (simp only: G.normal_inv_iff subgroup_kernel)\n  apply (simp add: kernel_def)\n  done\n\nlemma iso_kernel_image:\n  assumes \"group G\" \"group H\"\n  shows \"f \\<in> iso G H \\<longleftrightarrow> f \\<in> hom G H \\<and> kernel G H f = {\\<one>\\<^bsub>G\\<^esub>} \\<and> f ` carrier G = carrier H\"\n    (is \"?lhs = ?rhs\")\nproof (intro iffI conjI)\n  assume f: ?lhs\n  show \"f \\<in> hom G H\"\n    using Group.iso_iff f by blast\n  show \"kernel G H f = {\\<one>\\<^bsub>G\\<^esub>}\"\n    using assms f Group.group_def hom_one\n    by (fastforce simp add: kernel_def iso_iff_mon_epi mon_iff_hom_one set_eq_iff)\n  show \"f ` carrier G = carrier H\"\n    by (meson Group.iso_iff f)\nnext\n  assume ?rhs\n  with assms show ?lhs\n    by (auto simp: kernel_def iso_def bij_betw_def inj_on_one_iff')\nqed\n\n\nlemma (in group_hom) FactGroup_nonempty:\n  assumes X: \"X \\<in> carrier (G Mod kernel G H h)\"\n  shows \"X \\<noteq> {}\"\nproof -\n  from X\n  obtain g where \"g \\<in> carrier G\"\n             and \"X = kernel G H h #> g\"\n    by (auto simp add: FactGroup_def RCOSETS_def)\n  thus ?thesis\n   by (auto simp add: kernel_def r_coset_def image_def intro: hom_one)\nqed\n\n\nlemma (in group_hom) FactGroup_universal_kernel:\n  assumes \"N \\<lhd> G\" and h: \"N \\<subseteq> kernel G H h\"\n  obtains g where \"g \\<in> hom (G Mod N) H\" \"\\<And>x. x \\<in> carrier G \\<Longrightarrow> g(r_coset G N x) = h x\"\nproof -\n  have \"h x = h y\"\n    if \"x \\<in> carrier G\" \"y \\<in> carrier G\" \"r_coset G N x = r_coset G N y\" for x y\n  proof -\n    have \"x \\<otimes>\\<^bsub>G\\<^esub> inv\\<^bsub>G\\<^esub> y \\<in> N\"\n      using \\<open>N \\<lhd> G\\<close> group.rcos_self normal.axioms(2) normal_imp_subgroup\n         subgroup.rcos_module_imp that by metis \n    with h have xy: \"x \\<otimes>\\<^bsub>G\\<^esub> inv\\<^bsub>G\\<^esub> y \\<in> kernel G H h\"\n      by blast\n    have \"h x \\<otimes>\\<^bsub>H\\<^esub> inv\\<^bsub>H\\<^esub>(h y) = h (x \\<otimes>\\<^bsub>G\\<^esub> inv\\<^bsub>G\\<^esub> y)\"\n      by (simp add: that)\n    also have \"\\<dots> = \\<one>\\<^bsub>H\\<^esub>\"\n      using xy by (simp add: kernel_def)\n    finally have \"h x \\<otimes>\\<^bsub>H\\<^esub> inv\\<^bsub>H\\<^esub>(h y) = \\<one>\\<^bsub>H\\<^esub>\" .\n    then show ?thesis\n      using H.inv_equality that by fastforce\n  qed\n  with FactGroup_universal [OF homh \\<open>N \\<lhd> G\\<close>] that show thesis\n    by metis\nqed\n\nlemma (in group_hom) FactGroup_the_elem_mem:\n  assumes X: \"X \\<in> carrier (G Mod (kernel G H h))\"\n  shows \"the_elem (h`X) \\<in> carrier H\"\nproof -\n  from X\n  obtain g where g: \"g \\<in> carrier G\"\n             and \"X = kernel G H h #> g\"\n    by (auto simp add: FactGroup_def RCOSETS_def)\n  hence \"h ` X = {h g}\" by (auto simp add: kernel_def r_coset_def g intro!: imageI)\n  thus ?thesis by (auto simp add: g)\nqed\n\nlemma (in group_hom) FactGroup_hom:\n     \"(\\<lambda>X. the_elem (h`X)) \\<in> hom (G Mod (kernel G H h)) H\"\nproof -\n  have \"the_elem (h ` (X <#> X')) = the_elem (h ` X) \\<otimes>\\<^bsub>H\\<^esub> the_elem (h ` X')\"\n    if X: \"X  \\<in> carrier (G Mod kernel G H h)\" and X': \"X' \\<in> carrier (G Mod kernel G H h)\" for X X'\n  proof -\n    obtain g and g'\n      where \"g \\<in> carrier G\" and \"g' \\<in> carrier G\"\n        and \"X = kernel G H h #> g\" and \"X' = kernel G H h #> g'\"\n      using X X' by (auto simp add: FactGroup_def RCOSETS_def)\n    hence all: \"\\<forall>x\\<in>X. h x = h g\" \"\\<forall>x\\<in>X'. h x = h g'\"\n      and Xsub: \"X \\<subseteq> carrier G\" and X'sub: \"X' \\<subseteq> carrier G\"\n      by (force simp add: kernel_def r_coset_def image_def)+\n    hence \"h ` (X <#> X') = {h g \\<otimes>\\<^bsub>H\\<^esub> h g'}\" using X X'\n      by (auto dest!: FactGroup_nonempty intro!: image_eqI\n          simp add: set_mult_def\n          subsetD [OF Xsub] subsetD [OF X'sub])\n    then show \"the_elem (h ` (X <#> X')) = the_elem (h ` X) \\<otimes>\\<^bsub>H\\<^esub> the_elem (h ` X')\"\n      by (auto simp add: all FactGroup_nonempty X X' the_elem_image_unique)\n  qed\n  then show ?thesis\n    by (simp add: hom_def FactGroup_the_elem_mem normal.factorgroup_is_group [OF normal_kernel] group.axioms monoid.m_closed)\nqed\n\n\ntext\\<open>Lemma for the following injectivity result\\<close>\nlemma (in group_hom) FactGroup_subset:\n  assumes \"g \\<in> carrier G\" \"g' \\<in> carrier G\" \"h g = h g'\"\n  shows \"kernel G H h #> g \\<subseteq> kernel G H h #> g'\"\n  unfolding kernel_def r_coset_def\nproof clarsimp\n  fix y \n  assume \"y \\<in> carrier G\" \"h y = \\<one>\\<^bsub>H\\<^esub>\"\n  with assms show \"\\<exists>x. x \\<in> carrier G \\<and> h x = \\<one>\\<^bsub>H\\<^esub> \\<and> y \\<otimes> g = x \\<otimes> g'\"\n    by (rule_tac x=\"y \\<otimes> g \\<otimes> inv g'\" in exI) (auto simp: G.m_assoc)\nqed\n\nlemma (in group_hom) FactGroup_inj_on:\n     \"inj_on (\\<lambda>X. the_elem (h ` X)) (carrier (G Mod kernel G H h))\"\nproof (simp add: inj_on_def, clarify)\n  fix X and X'\n  assume X:  \"X  \\<in> carrier (G Mod kernel G H h)\"\n     and X': \"X' \\<in> carrier (G Mod kernel G H h)\"\n  then\n  obtain g and g'\n           where gX: \"g \\<in> carrier G\"  \"g' \\<in> carrier G\"\n              \"X = kernel G H h #> g\" \"X' = kernel G H h #> g'\"\n    by (auto simp add: FactGroup_def RCOSETS_def)\n  hence all: \"\\<forall>x\\<in>X. h x = h g\" \"\\<forall>x\\<in>X'. h x = h g'\"\n    by (force simp add: kernel_def r_coset_def image_def)+\n  assume \"the_elem (h ` X) = the_elem (h ` X')\"\n  hence h: \"h g = h g'\"\n    by (simp add: all FactGroup_nonempty X X' the_elem_image_unique)\n  show \"X=X'\" by (rule equalityI) (simp_all add: FactGroup_subset h gX)\nqed\n\ntext\\<open>If the homomorphism \\<^term>\\<open>h\\<close> is onto \\<^term>\\<open>H\\<close>, then so is the\nhomomorphism from the quotient group\\<close>\nlemma (in group_hom) FactGroup_onto:\n  assumes h: \"h ` carrier G = carrier H\"\n  shows \"(\\<lambda>X. the_elem (h ` X)) ` carrier (G Mod kernel G H h) = carrier H\"\nproof\n  show \"(\\<lambda>X. the_elem (h ` X)) ` carrier (G Mod kernel G H h) \\<subseteq> carrier H\"\n    by (auto simp add: FactGroup_the_elem_mem)\n  show \"carrier H \\<subseteq> (\\<lambda>X. the_elem (h ` X)) ` carrier (G Mod kernel G H h)\"\n  proof\n    fix y\n    assume y: \"y \\<in> carrier H\"\n    with h obtain g where g: \"g \\<in> carrier G\" \"h g = y\"\n      by (blast elim: equalityE)\n    hence \"(\\<Union>x\\<in>kernel G H h #> g. {h x}) = {y}\"\n      by (auto simp add: y kernel_def r_coset_def)\n    with g show \"y \\<in> (\\<lambda>X. the_elem (h ` X)) ` carrier (G Mod kernel G H h)\"\n      apply (auto intro!: bexI image_eqI simp add: FactGroup_def RCOSETS_def)\n      apply (subst the_elem_image_unique)\n      apply auto\n      done\n  qed\nqed\n\n\ntext\\<open>If \\<^term>\\<open>h\\<close> is a homomorphism from \\<^term>\\<open>G\\<close> onto \\<^term>\\<open>H\\<close>, then the\n quotient group \\<^term>\\<open>G Mod (kernel G H h)\\<close> is isomorphic to \\<^term>\\<open>H\\<close>.\\<close>\ntheorem (in group_hom) FactGroup_iso_set:\n  \"h ` carrier G = carrier H\n   \\<Longrightarrow> (\\<lambda>X. the_elem (h`X)) \\<in> iso (G Mod (kernel G H h)) H\"\nby (simp add: iso_def FactGroup_hom FactGroup_inj_on bij_betw_def\n              FactGroup_onto)\n\ncorollary (in group_hom) FactGroup_iso :\n  \"h ` carrier G = carrier H\n   \\<Longrightarrow> (G Mod (kernel G H h))\\<cong> H\"\n  using FactGroup_iso_set unfolding is_iso_def by auto\n\n\nlemma (in group_hom) trivial_hom_iff: \\<^marker>\\<open>contributor \\<open>Paulo Em\u00edlio de Vilhena\\<close>\\<close>\n  \"h ` (carrier G) = { \\<one>\\<^bsub>H\\<^esub> } \\<longleftrightarrow> kernel G H h = carrier G\"\n  unfolding kernel_def using one_closed by force\n\nlemma (in group_hom) trivial_ker_imp_inj: \\<^marker>\\<open>contributor \\<open>Paulo Em\u00edlio de Vilhena\\<close>\\<close>\n  assumes \"kernel G H h = { \\<one> }\"\n  shows \"inj_on h (carrier G)\"\nproof (rule inj_onI)\n  fix g1 g2 assume A: \"g1 \\<in> carrier G\" \"g2 \\<in> carrier G\" \"h g1 = h g2\"\n  hence \"h (g1 \\<otimes> (inv g2)) = \\<one>\\<^bsub>H\\<^esub>\" by simp\n  hence \"g1 \\<otimes> (inv g2) = \\<one>\"\n    using A assms unfolding kernel_def by blast\n  thus \"g1 = g2\"\n    using A G.inv_equality G.inv_inv by blast\nqed\n\nlemma (in group_hom) inj_iff_trivial_ker:\n  shows \"inj_on h (carrier G) \\<longleftrightarrow> kernel G H h = { \\<one> }\"\nproof\n  assume inj: \"inj_on h (carrier G)\" show \"kernel G H h = { \\<one> }\"\n    unfolding kernel_def\n  proof (auto)\n    fix a assume \"a \\<in> carrier G\" \"h a = \\<one>\\<^bsub>H\\<^esub>\" thus \"a = \\<one>\"\n      using inj hom_one unfolding inj_on_def by force\n  qed\nnext\n  show \"kernel G H h = { \\<one> } \\<Longrightarrow> inj_on h (carrier G)\"\n    using trivial_ker_imp_inj by simp\nqed\n\nlemma (in group_hom) induced_group_hom':\n  assumes \"subgroup I G\" shows \"group_hom (G \\<lparr> carrier := I \\<rparr>) H h\"\nproof -\n  have \"h \\<in> hom (G \\<lparr> carrier := I \\<rparr>) H\"\n    using homh subgroup.subset[OF assms] unfolding hom_def by (auto, meson hom_mult subsetCE)\n  thus ?thesis\n    using subgroup.subgroup_is_group[OF assms G.group_axioms] group_axioms\n    unfolding group_hom_def group_hom_axioms_def by auto\nqed\n\nlemma (in group_hom) inj_on_subgroup_iff_trivial_ker:\n  assumes \"subgroup I G\"\n  shows \"inj_on h I \\<longleftrightarrow> kernel (G \\<lparr> carrier := I \\<rparr>) H h = { \\<one> }\"\n  using group_hom.inj_iff_trivial_ker[OF induced_group_hom'[OF assms]] by simp\n\nlemma set_mult_hom:\n  assumes \"h \\<in> hom G H\" \"I \\<subseteq> carrier G\" and \"J \\<subseteq> carrier G\"\n  shows \"h ` (I <#>\\<^bsub>G\\<^esub> J) = (h ` I) <#>\\<^bsub>H\\<^esub> (h ` J)\"\nproof\n  show \"h ` (I <#>\\<^bsub>G\\<^esub> J) \\<subseteq> (h ` I) <#>\\<^bsub>H\\<^esub> (h ` J)\"\n  proof\n    fix a assume \"a \\<in> h ` (I <#>\\<^bsub>G\\<^esub> J)\"\n    then obtain i j where i: \"i \\<in> I\" and j: \"j \\<in> J\" and \"a = h (i \\<otimes>\\<^bsub>G\\<^esub> j)\"\n      unfolding set_mult_def by auto\n    hence \"a = (h i) \\<otimes>\\<^bsub>H\\<^esub> (h j)\"\n      using assms unfolding hom_def by blast\n    thus \"a \\<in> (h ` I) <#>\\<^bsub>H\\<^esub> (h ` J)\"\n      using i and j unfolding set_mult_def by auto\n  qed\nnext\n  show \"(h ` I) <#>\\<^bsub>H\\<^esub> (h ` J) \\<subseteq> h ` (I <#>\\<^bsub>G\\<^esub> J)\"\n  proof\n    fix a assume \"a \\<in> (h ` I) <#>\\<^bsub>H\\<^esub> (h ` J)\"\n    then obtain i j where i: \"i \\<in> I\" and j: \"j \\<in> J\" and \"a = (h i) \\<otimes>\\<^bsub>H\\<^esub> (h j)\"\n      unfolding set_mult_def by auto\n    hence \"a = h (i \\<otimes>\\<^bsub>G\\<^esub> j)\"\n      using assms unfolding hom_def by fastforce\n    thus \"a \\<in> h ` (I <#>\\<^bsub>G\\<^esub> J)\"\n      using i and j unfolding set_mult_def by auto\n  qed\nqed\n\ncorollary coset_hom:\n  assumes \"h \\<in> hom G H\" \"I \\<subseteq> carrier G\" \"a \\<in> carrier G\"\n  shows \"h ` (a <#\\<^bsub>G\\<^esub> I) = h a <#\\<^bsub>H\\<^esub> (h ` I)\" and \"h ` (I #>\\<^bsub>G\\<^esub> a) = (h ` I) #>\\<^bsub>H\\<^esub> h a\"\n  unfolding l_coset_eq_set_mult r_coset_eq_set_mult using assms set_mult_hom[OF assms(1)] by auto\n\ncorollary (in group_hom) set_mult_ker_hom:\n  assumes \"I \\<subseteq> carrier G\"\n  shows \"h ` (I <#> (kernel G H h)) = h ` I\" and \"h ` ((kernel G H h) <#> I) = h ` I\"\nproof -\n  have ker_in_carrier: \"kernel G H h \\<subseteq> carrier G\"\n    unfolding kernel_def by auto\n\n  have \"h ` (kernel G H h) = { \\<one>\\<^bsub>H\\<^esub> }\"\n    unfolding kernel_def by force\n  moreover have \"h ` I \\<subseteq> carrier H\"\n    using assms by auto\n  hence \"(h ` I) <#>\\<^bsub>H\\<^esub> { \\<one>\\<^bsub>H\\<^esub> } = h ` I\" and \"{ \\<one>\\<^bsub>H\\<^esub> } <#>\\<^bsub>H\\<^esub> (h ` I) = h ` I\"\n    unfolding set_mult_def by force+\n  ultimately show \"h ` (I <#> (kernel G H h)) = h ` I\" and \"h ` ((kernel G H h) <#> I) = h ` I\"\n    using set_mult_hom[OF homh assms ker_in_carrier] set_mult_hom[OF homh ker_in_carrier assms] by simp+\nqed\n\nsubsubsection\\<open>Trivial homomorphisms\\<close>\n\ndefinition trivial_homomorphism where\n \"trivial_homomorphism G H f \\<equiv> f \\<in> hom G H \\<and> (\\<forall>x \\<in> carrier G. f x = one H)\"\n\nlemma trivial_homomorphism_kernel:\n   \"trivial_homomorphism G H f \\<longleftrightarrow> f \\<in> hom G H \\<and> kernel G H f = carrier G\"\n  by (auto simp: trivial_homomorphism_def kernel_def)\n\nlemma (in group) trivial_homomorphism_image:\n   \"trivial_homomorphism G H f \\<longleftrightarrow> f \\<in> hom G H \\<and> f ` carrier G = {one H}\"\n  by (auto simp: trivial_homomorphism_def) (metis one_closed rev_image_eqI)\n\n\nsubsection \\<open>Image kernel theorems\\<close>\n\nlemma group_Int_image_ker:\n  assumes f: \"f \\<in> hom G H\" and g: \"g \\<in> hom H K\" and \"inj_on (g \\<circ> f) (carrier G)\" \"group G\" \"group H\" \"group K\"\n  shows \"(f ` carrier G) \\<inter> (kernel H K g) = {\\<one>\\<^bsub>H\\<^esub>}\"\nproof -\n  have \"(f ` carrier G) \\<inter> (kernel H K g) \\<subseteq> {\\<one>\\<^bsub>H\\<^esub>}\"\n    using assms\n    apply (clarsimp simp: kernel_def o_def)\n    by (metis group.is_monoid hom_one inj_on_eq_iff monoid.one_closed)\n  moreover have \"one H \\<in> f ` carrier G\"\n    by (metis f \\<open>group G\\<close> \\<open>group H\\<close> group.is_monoid hom_one image_iff monoid.one_closed)\n  moreover have \"one H \\<in> kernel H K g\"\n    apply (simp add: kernel_def)\n    using g group.is_monoid hom_one \\<open>group H\\<close> \\<open>group K\\<close> by blast\n  ultimately show ?thesis\n    by blast\nqed\n\n\nlemma group_sum_image_ker:\n  assumes f: \"f \\<in> hom G H\" and g: \"g \\<in> hom H K\" and eq: \"(g \\<circ> f) ` (carrier G) = carrier K\"\n     and \"group G\" \"group H\" \"group K\"\n  shows \"set_mult H (f ` carrier G) (kernel H K g) = carrier H\" (is \"?lhs = ?rhs\")\nproof\n  show \"?lhs \\<subseteq> ?rhs\"\n    apply (auto simp: kernel_def set_mult_def)\n    by (meson Group.group_def assms(5) f hom_carrier image_eqI monoid.m_closed subset_iff)\n  have \"\\<exists>x\\<in>carrier G. \\<exists>z. z \\<in> carrier H \\<and> g z = \\<one>\\<^bsub>K\\<^esub> \\<and> y = f x \\<otimes>\\<^bsub>H\\<^esub> z\"\n    if y: \"y \\<in> carrier H\" for y\n  proof -\n    have \"g y \\<in> carrier K\"\n      using g hom_carrier that by blast\n    with assms obtain x where x: \"x \\<in> carrier G\" \"(g \\<circ> f) x = g y\"\n      by (metis image_iff)\n    with assms have \"inv\\<^bsub>H\\<^esub> f x \\<otimes>\\<^bsub>H\\<^esub> y \\<in> carrier H\"\n      by (metis group.subgroup_self hom_carrier image_subset_iff subgroup_def y)\n    moreover\n    have \"g (inv\\<^bsub>H\\<^esub> f x \\<otimes>\\<^bsub>H\\<^esub> y) = \\<one>\\<^bsub>K\\<^esub>\"\n    proof -\n      have \"inv\\<^bsub>H\\<^esub> f x \\<in> carrier H\"\n        by (meson \\<open>group H\\<close> f group.inv_closed hom_carrier image_subset_iff x(1))\n      then have \"g (inv\\<^bsub>H\\<^esub> f x \\<otimes>\\<^bsub>H\\<^esub> y) = g (inv\\<^bsub>H\\<^esub> f x) \\<otimes>\\<^bsub>K\\<^esub> g y\"\n        by (simp add: hom_mult [OF g] y)\n      also have \"\\<dots> = inv\\<^bsub>K\\<^esub> (g (f x)) \\<otimes>\\<^bsub>K\\<^esub> g y\"\n        using assms x(1)\n        by (metis (mono_tags, lifting) group_hom.hom_inv group_hom.intro group_hom_axioms.intro hom_carrier image_subset_iff)\n      also have \"\\<dots> = \\<one>\\<^bsub>K\\<^esub>\"\n        using \\<open>g y \\<in> carrier K\\<close> assms(6) group.l_inv x(2) by fastforce\n      finally show ?thesis .\n    qed\n    moreover\n    have \"y = f x \\<otimes>\\<^bsub>H\\<^esub> (inv\\<^bsub>H\\<^esub> f x \\<otimes>\\<^bsub>H\\<^esub> y)\"\n      using x y\n      by (metis (no_types, opaque_lifting) assms(5) f group.inv_solve_left group.subgroup_self hom_carrier image_subset_iff subgroup_def that)\n    ultimately\n    show ?thesis\n      using x y by force\n  qed\n  then show \"?rhs \\<subseteq> ?lhs\"\n    by (auto simp: kernel_def set_mult_def)\nqed\n\n\nlemma group_sum_ker_image:\n  assumes f: \"f \\<in> hom G H\" and g: \"g \\<in> hom H K\" and eq: \"(g \\<circ> f) ` (carrier G) = carrier K\"\n     and \"group G\" \"group H\" \"group K\"\n   shows \"set_mult H (kernel H K g) (f ` carrier G) = carrier H\" (is \"?lhs = ?rhs\")\nproof\n  show \"?lhs \\<subseteq> ?rhs\"\n    apply (auto simp: kernel_def set_mult_def)\n    by (meson Group.group_def \\<open>group H\\<close> f hom_carrier image_eqI monoid.m_closed subset_iff)\n  have \"\\<exists>w\\<in>carrier H. \\<exists>x \\<in> carrier G. g w = \\<one>\\<^bsub>K\\<^esub> \\<and> y = w \\<otimes>\\<^bsub>H\\<^esub> f x\"\n    if y: \"y \\<in> carrier H\" for y\n  proof -\n    have \"g y \\<in> carrier K\"\n      using g hom_carrier that by blast\n    with assms obtain x where x: \"x \\<in> carrier G\" \"(g \\<circ> f) x = g y\"\n      by (metis image_iff)\n    with assms have carr: \"(y \\<otimes>\\<^bsub>H\\<^esub> inv\\<^bsub>H\\<^esub> f x) \\<in> carrier H\"\n      by (metis group.subgroup_self hom_carrier image_subset_iff subgroup_def y)\n    moreover\n    have \"g (y \\<otimes>\\<^bsub>H\\<^esub> inv\\<^bsub>H\\<^esub> f x) = \\<one>\\<^bsub>K\\<^esub>\"\n    proof -\n      have \"inv\\<^bsub>H\\<^esub> f x \\<in> carrier H\"\n        by (meson \\<open>group H\\<close> f group.inv_closed hom_carrier image_subset_iff x(1))\n      then have \"g (y \\<otimes>\\<^bsub>H\\<^esub> inv\\<^bsub>H\\<^esub> f x) = g y \\<otimes>\\<^bsub>K\\<^esub> g (inv\\<^bsub>H\\<^esub> f x)\"\n        by (simp add: hom_mult [OF g] y)\n      also have \"\\<dots> = g y \\<otimes>\\<^bsub>K\\<^esub> inv\\<^bsub>K\\<^esub> (g (f x))\"\n        using assms x(1)\n        by (metis (mono_tags, lifting) group_hom.hom_inv group_hom.intro group_hom_axioms.intro hom_carrier image_subset_iff)\n      also have \"\\<dots> = \\<one>\\<^bsub>K\\<^esub>\"\n        using \\<open>g y \\<in> carrier K\\<close> assms(6) group.l_inv x(2)\n        by (simp add: group.r_inv)\n      finally show ?thesis .\n    qed\n    moreover\n    have \"y = (y \\<otimes>\\<^bsub>H\\<^esub> inv\\<^bsub>H\\<^esub> f x) \\<otimes>\\<^bsub>H\\<^esub> f x\"\n      using x y by (meson \\<open>group H\\<close> carr f group.inv_solve_right hom_carrier image_subset_iff)\n    ultimately\n    show ?thesis\n      using x y by force\n  qed\n  then show \"?rhs \\<subseteq> ?lhs\"\n    by (force simp: kernel_def set_mult_def)\nqed\n\nlemma group_semidirect_sum_ker_image:\n  assumes \"(g \\<circ> f) \\<in> iso G K\" \"f \\<in> hom G H\" \"g \\<in> hom H K\" \"group G\" \"group H\" \"group K\"\n  shows \"(kernel H K g) \\<inter> (f ` carrier G) = {\\<one>\\<^bsub>H\\<^esub>}\"\n        \"kernel H K g <#>\\<^bsub>H\\<^esub> (f ` carrier G) = carrier H\"\n  using assms\n  by (simp_all add: iso_iff_mon_epi group_Int_image_ker group_sum_ker_image epi_def mon_def Int_commute [of \"kernel H K g\"])\n\nlemma group_semidirect_sum_image_ker:\n  assumes f: \"f \\<in> hom G H\" and g: \"g \\<in> hom H K\" and iso: \"(g \\<circ> f) \\<in> iso G K\"\n     and \"group G\" \"group H\" \"group K\"\n   shows \"(f ` carrier G) \\<inter> (kernel H K g) = {\\<one>\\<^bsub>H\\<^esub>}\"\n          \"f ` carrier G <#>\\<^bsub>H\\<^esub> (kernel H K g) = carrier H\"\n  using group_Int_image_ker [OF f g] group_sum_image_ker [OF f g] assms\n  by (simp_all add: iso_def bij_betw_def)\n\n\n\nsubsection \\<open>Factor Groups and Direct product\\<close>\n\nlemma (in group) DirProd_normal : \\<^marker>\\<open>contributor \\<open>Martin Baillon\\<close>\\<close>\n  assumes \"group K\"\n    and \"H \\<lhd> G\"\n    and \"N \\<lhd> K\"\n  shows \"H \\<times> N \\<lhd> G \\<times>\\<times> K\"\nproof (intro group.normal_invI[OF DirProd_group[OF group_axioms assms(1)]])\n  show sub : \"subgroup (H \\<times> N) (G \\<times>\\<times> K)\"\n    using DirProd_subgroups[OF group_axioms normal_imp_subgroup[OF assms(2)]assms(1)\n         normal_imp_subgroup[OF assms(3)]].\n  show \"\\<And>x h. x \\<in> carrier (G\\<times>\\<times>K) \\<Longrightarrow> h \\<in> H\\<times>N \\<Longrightarrow> x \\<otimes>\\<^bsub>G\\<times>\\<times>K\\<^esub> h \\<otimes>\\<^bsub>G\\<times>\\<times>K\\<^esub> inv\\<^bsub>G\\<times>\\<times>K\\<^esub> x \\<in> H\\<times>N\"\n  proof-\n    fix x h assume xGK : \"x \\<in> carrier (G \\<times>\\<times> K)\" and hHN : \" h \\<in> H \\<times> N\"\n    hence hGK : \"h \\<in> carrier (G \\<times>\\<times> K)\" using subgroup.subset[OF sub] by auto\n    from xGK obtain x1 x2 where x1x2 :\"x1 \\<in> carrier G\" \"x2 \\<in> carrier K\" \"x = (x1,x2)\"\n      unfolding DirProd_def by fastforce\n    from hHN obtain h1 h2 where h1h2 : \"h1 \\<in> H\" \"h2 \\<in> N\" \"h = (h1,h2)\"\n      unfolding DirProd_def by fastforce\n    hence h1h2GK : \"h1 \\<in> carrier G\" \"h2 \\<in> carrier K\"\n      using normal_imp_subgroup subgroup.subset assms by blast+\n    have \"inv\\<^bsub>G \\<times>\\<times> K\\<^esub> x = (inv\\<^bsub>G\\<^esub> x1,inv\\<^bsub>K\\<^esub> x2)\"\n      using inv_DirProd[OF group_axioms assms(1) x1x2(1)x1x2(2)] x1x2 by auto\n    hence \"x \\<otimes>\\<^bsub>G \\<times>\\<times> K\\<^esub> h \\<otimes>\\<^bsub>G \\<times>\\<times> K\\<^esub> inv\\<^bsub>G \\<times>\\<times> K\\<^esub> x = (x1 \\<otimes> h1 \\<otimes> inv x1,x2 \\<otimes>\\<^bsub>K\\<^esub> h2 \\<otimes>\\<^bsub>K\\<^esub> inv\\<^bsub>K\\<^esub> x2)\"\n      using h1h2 x1x2 h1h2GK by auto\n    moreover have \"x1 \\<otimes> h1 \\<otimes> inv x1 \\<in> H\" \"x2 \\<otimes>\\<^bsub>K\\<^esub> h2 \\<otimes>\\<^bsub>K\\<^esub> inv\\<^bsub>K\\<^esub> x2 \\<in> N\"\n      using assms x1x2 h1h2 assms by (simp_all add: normal.inv_op_closed2)\n    hence \"(x1 \\<otimes> h1 \\<otimes> inv x1, x2 \\<otimes>\\<^bsub>K\\<^esub> h2 \\<otimes>\\<^bsub>K\\<^esub> inv\\<^bsub>K\\<^esub> x2)\\<in> H \\<times> N\" by auto\n    ultimately show \" x \\<otimes>\\<^bsub>G \\<times>\\<times> K\\<^esub> h \\<otimes>\\<^bsub>G \\<times>\\<times> K\\<^esub> inv\\<^bsub>G \\<times>\\<times> K\\<^esub> x \\<in> H \\<times> N\" by auto\n  qed\nqed\n\nlemma (in group) FactGroup_DirProd_multiplication_iso_set : \\<^marker>\\<open>contributor \\<open>Martin Baillon\\<close>\\<close>\n  assumes \"group K\"\n    and \"H \\<lhd> G\"\n    and \"N \\<lhd> K\"\n  shows \"(\\<lambda> (X, Y). X \\<times> Y) \\<in> iso  ((G Mod H) \\<times>\\<times> (K Mod N)) (G \\<times>\\<times> K Mod H \\<times> N)\"\n\nproof-\n  have R :\"(\\<lambda>(X, Y). X \\<times> Y) \\<in> carrier (G Mod H) \\<times> carrier (K Mod N) \\<rightarrow> carrier (G \\<times>\\<times> K Mod H \\<times> N)\"\n    unfolding r_coset_def Sigma_def DirProd_def FactGroup_def RCOSETS_def by force\n  moreover have \"(\\<forall>x\\<in>carrier (G Mod H). \\<forall>y\\<in>carrier (K Mod N). \\<forall>xa\\<in>carrier (G Mod H).\n                \\<forall>ya\\<in>carrier (K Mod N). (x <#> xa) \\<times> (y <#>\\<^bsub>K\\<^esub> ya) =  x \\<times> y <#>\\<^bsub>G \\<times>\\<times> K\\<^esub> xa \\<times> ya)\"\n    unfolding set_mult_def by force\n  moreover have \"(\\<forall>x\\<in>carrier (G Mod H). \\<forall>y\\<in>carrier (K Mod N). \\<forall>xa\\<in>carrier (G Mod H).\n                 \\<forall>ya\\<in>carrier (K Mod N).  x \\<times> y = xa \\<times> ya \\<longrightarrow> x = xa \\<and> y = ya)\"\n    unfolding  FactGroup_def using times_eq_iff subgroup.rcosets_non_empty\n    by (metis assms(2) assms(3) normal_def partial_object.select_convs(1))\n  moreover have \"(\\<lambda>(X, Y). X \\<times> Y) ` (carrier (G Mod H) \\<times> carrier (K Mod N)) =\n                                     carrier (G \\<times>\\<times> K Mod H \\<times> N)\"\n  proof -\n    have 1: \"\\<And>x a b. \\<lbrakk>a \\<in> carrier (G Mod H); b \\<in> carrier (K Mod N)\\<rbrakk> \\<Longrightarrow> a \\<times> b \\<in> carrier (G \\<times>\\<times> K Mod H \\<times> N)\"\n      using R by force\n    have 2: \"\\<And>z. z \\<in> carrier (G \\<times>\\<times> K Mod H \\<times> N) \\<Longrightarrow> \\<exists>x\\<in>carrier (G Mod H). \\<exists>y\\<in>carrier (K Mod N). z = x \\<times> y\"\n      unfolding DirProd_def FactGroup_def RCOSETS_def r_coset_def by force\n    show ?thesis\n      unfolding image_def by (auto simp: intro: 1 2)\n  qed\n  ultimately show ?thesis\n    unfolding iso_def hom_def bij_betw_def inj_on_def by simp\nqed\n\ncorollary (in group) FactGroup_DirProd_multiplication_iso_1 : \\<^marker>\\<open>contributor \\<open>Martin Baillon\\<close>\\<close>\n  assumes \"group K\"\n    and \"H \\<lhd> G\"\n    and \"N \\<lhd> K\"\n  shows \"  ((G Mod H) \\<times>\\<times> (K Mod N)) \\<cong> (G \\<times>\\<times> K Mod H \\<times> N)\"\n  unfolding is_iso_def using FactGroup_DirProd_multiplication_iso_set assms by auto\n\ncorollary (in group) FactGroup_DirProd_multiplication_iso_2 : \\<^marker>\\<open>contributor \\<open>Martin Baillon\\<close>\\<close>\n  assumes \"group K\"\n    and \"H \\<lhd> G\"\n    and \"N \\<lhd> K\"\n  shows \"(G \\<times>\\<times> K Mod H \\<times> N) \\<cong> ((G Mod H) \\<times>\\<times> (K Mod N))\"\n  using FactGroup_DirProd_multiplication_iso_1 group.iso_sym assms\n        DirProd_group[OF normal.factorgroup_is_group normal.factorgroup_is_group]\n  by blast\n\nsubsubsection \"More Lemmas about set multiplication\"\n\n(*A group multiplied by a subgroup stays the same*)\nlemma (in group) set_mult_carrier_idem:\n  assumes \"subgroup H G\"\n  shows \"(carrier G) <#> H = carrier G\"\nproof\n  show \"(carrier G)<#>H \\<subseteq> carrier G\"\n    unfolding set_mult_def using subgroup.subset assms by blast\nnext\n  have \" (carrier G) #>  \\<one> = carrier G\" unfolding set_mult_def r_coset_def group_axioms by simp\n  moreover have \"(carrier G) #>  \\<one> \\<subseteq> (carrier G) <#> H\" unfolding set_mult_def r_coset_def\n    using assms subgroup.one_closed[OF assms] by blast\n  ultimately show \"carrier G \\<subseteq> (carrier G) <#> H\" by simp\nqed\n\n(*Same lemma as above, but everything is included in a subgroup*)\nlemma (in group) set_mult_subgroup_idem:\n  assumes HG: \"subgroup H G\" and NG: \"subgroup N (G \\<lparr> carrier := H \\<rparr>)\"\n  shows \"H <#> N = H\"\n  using group.set_mult_carrier_idem[OF subgroup.subgroup_is_group[OF HG group_axioms] NG] by simp\n\n(*A normal subgroup is commutative with set_mult*)\nlemma (in group) commut_normal:\n  assumes \"subgroup H G\" and \"N\\<lhd>G\"\n  shows \"H<#>N = N<#>H\"\nproof-\n  have aux1: \"{H <#> N} = {\\<Union>h\\<in>H. h <# N }\" unfolding set_mult_def l_coset_def by auto\n  also have \"... = {\\<Union>h\\<in>H. N #> h }\" using assms normal.coset_eq subgroup.mem_carrier by fastforce\n  moreover have aux2: \"{N <#> H} = {\\<Union>h\\<in>H. N #> h }\"unfolding set_mult_def r_coset_def by auto\n  ultimately show \"H<#>N = N<#>H\" by simp\nqed\n\n(*Same lemma as above, but everything is included in a subgroup*)\nlemma (in group) commut_normal_subgroup:\n  assumes \"subgroup H G\" and \"N \\<lhd> (G\\<lparr> carrier := H \\<rparr>)\"\n    and \"subgroup K (G \\<lparr> carrier := H \\<rparr>)\"\n  shows \"K <#> N = N <#> K\"\n  using group.commut_normal[OF subgroup.subgroup_is_group[OF assms(1) group_axioms] assms(3,2)] by simp\n\n\n\nsubsubsection \"Lemmas about intersection and normal subgroups\"\n\nlemma (in group) normal_inter:\n  assumes \"subgroup H G\"\n    and \"subgroup K G\"\n    and \"H1\\<lhd>G\\<lparr>carrier := H\\<rparr>\"\n  shows \" (H1\\<inter>K)\\<lhd>(G\\<lparr>carrier:= (H\\<inter>K)\\<rparr>)\"\nproof-\n  define HK and H1K and GH and GHK\n    where \"HK = H\\<inter>K\" and \"H1K=H1\\<inter>K\" and \"GH =G\\<lparr>carrier := H\\<rparr>\" and \"GHK = (G\\<lparr>carrier:= (H\\<inter>K)\\<rparr>)\"\n  show \"H1K\\<lhd>GHK\"\n  proof (intro group.normal_invI[of GHK H1K])\n    show \"Group.group GHK\"\n      using GHK_def subgroups_Inter_pair subgroup_imp_group assms by blast\n\n  next\n    have  H1K_incl:\"subgroup H1K (G\\<lparr>carrier:= (H\\<inter>K)\\<rparr>)\"\n    proof(intro subgroup_incl)\n      show \"subgroup H1K G\"\n        using assms normal_imp_subgroup subgroups_Inter_pair incl_subgroup H1K_def by blast\n    next\n      show \"subgroup (H\\<inter>K) G\" using HK_def subgroups_Inter_pair assms by auto\n    next\n      have \"H1 \\<subseteq> (carrier (G\\<lparr>carrier:=H\\<rparr>))\"\n        using  assms(3) normal_imp_subgroup subgroup.subset by blast\n      also have \"... \\<subseteq> H\" by simp\n      thus \"H1K \\<subseteq>H\\<inter>K\"\n        using H1K_def calculation by auto\n    qed\n    thus \"subgroup H1K GHK\" using GHK_def by simp\n  next\n    show \"\\<And> x h. x\\<in>carrier GHK \\<Longrightarrow> h\\<in>H1K \\<Longrightarrow> x \\<otimes>\\<^bsub>GHK\\<^esub> h \\<otimes>\\<^bsub>GHK\\<^esub> inv\\<^bsub>GHK\\<^esub> x\\<in> H1K\"\n    proof-\n      have invHK: \"\\<lbrakk>y\\<in>HK\\<rbrakk> \\<Longrightarrow> inv\\<^bsub>GHK\\<^esub> y = inv\\<^bsub>GH\\<^esub> y\"\n        using m_inv_consistent assms HK_def GH_def GHK_def subgroups_Inter_pair by simp\n      have multHK : \"\\<lbrakk>x\\<in>HK;y\\<in>HK\\<rbrakk> \\<Longrightarrow>  x \\<otimes>\\<^bsub>(G\\<lparr>carrier:=HK\\<rparr>)\\<^esub> y =  x \\<otimes> y\"\n        using HK_def by simp\n      fix x assume p: \"x\\<in>carrier GHK\"\n      fix h assume p2 : \"h:H1K\"\n      have \"carrier(GHK)\\<subseteq>HK\"\n        using GHK_def HK_def by simp\n      hence xHK:\"x\\<in>HK\" using p by auto\n      hence invx:\"inv\\<^bsub>GHK\\<^esub> x = inv\\<^bsub>GH\\<^esub> x\"\n        using invHK assms GHK_def HK_def GH_def m_inv_consistent subgroups_Inter_pair by simp\n      have \"H1\\<subseteq>carrier(GH)\"\n        using assms GH_def normal_imp_subgroup subgroup.subset by blast\n      hence hHK:\"h\\<in>HK\"\n        using p2 H1K_def HK_def GH_def by auto\n      hence xhx_egal : \"x \\<otimes>\\<^bsub>GHK\\<^esub> h \\<otimes>\\<^bsub>GHK\\<^esub> inv\\<^bsub>GHK\\<^esub>x =  x \\<otimes>\\<^bsub>GH\\<^esub> h \\<otimes>\\<^bsub>GH\\<^esub> inv\\<^bsub>GH\\<^esub> x\"\n        using invx invHK multHK GHK_def GH_def by auto\n      have xH:\"x\\<in>carrier(GH)\"\n        using xHK HK_def GH_def by auto\n      have hH:\"h\\<in>carrier(GH)\"\n        using hHK HK_def GH_def by auto\n      have  \"(\\<forall>x\\<in>carrier (GH). \\<forall>h\\<in>H1.  x \\<otimes>\\<^bsub>GH\\<^esub> h \\<otimes>\\<^bsub>GH\\<^esub> inv\\<^bsub>GH\\<^esub> x \\<in> H1)\"\n        using assms GH_def normal.inv_op_closed2 by fastforce\n      hence INCL_1 : \"x \\<otimes>\\<^bsub>GH\\<^esub> h \\<otimes>\\<^bsub>GH\\<^esub> inv\\<^bsub>GH\\<^esub> x \\<in> H1\"\n        using  xH H1K_def p2 by blast\n      have \" x \\<otimes>\\<^bsub>GH\\<^esub> h \\<otimes>\\<^bsub>GH\\<^esub> inv\\<^bsub>GH\\<^esub> x \\<in> HK\"\n        using assms HK_def subgroups_Inter_pair hHK xHK\n        by (metis GH_def inf.cobounded1 subgroup_def subgroup_incl)\n      hence \" x \\<otimes>\\<^bsub>GH\\<^esub> h \\<otimes>\\<^bsub>GH\\<^esub> inv\\<^bsub>GH\\<^esub> x \\<in> K\" using HK_def by simp\n      hence \" x \\<otimes>\\<^bsub>GH\\<^esub> h \\<otimes>\\<^bsub>GH\\<^esub> inv\\<^bsub>GH\\<^esub> x \\<in> H1K\" using INCL_1 H1K_def by auto\n      thus  \"x \\<otimes>\\<^bsub>GHK\\<^esub> h \\<otimes>\\<^bsub>GHK\\<^esub> inv\\<^bsub>GHK\\<^esub> x \\<in> H1K\" using xhx_egal by simp\n    qed\n  qed\nqed\n\nlemma (in group) normal_Int_subgroup:\n  assumes \"subgroup H G\"\n    and \"N \\<lhd> G\"\n  shows \"(N\\<inter>H) \\<lhd> (G\\<lparr>carrier := H\\<rparr>)\"\nproof -\n  define K where \"K = carrier G\"\n  have \"G\\<lparr>carrier := K\\<rparr> =  G\" using K_def by auto\n  moreover have \"subgroup K G\" using K_def subgroup_self by blast\n  moreover have \"normal N (G \\<lparr>carrier :=K\\<rparr>)\" using assms K_def by simp\n  ultimately have \"N \\<inter> H \\<lhd> G\\<lparr>carrier := K \\<inter> H\\<rparr>\"\n    using normal_inter[of K H N] assms(1) by blast\n  moreover have \"K \\<inter> H = H\" using K_def assms subgroup.subset by blast\n  ultimately show \"normal (N\\<inter>H) (G\\<lparr>carrier := H\\<rparr>)\"\n by auto\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/Algebra/Coset.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8221891435927269, "lm_q2_score": 0.8596637469145053, "lm_q1q2_score": 0.7068061998533518}}
{"text": "theory mp1_sol\nimports Main\nbegin\n\n(*\nIn this exercise, you will prove some lemmas of propositional\nlogic with the aid of a calculus of natural deduction.\n\nFor the proofs, you may only use \"assumption\", and the following rules\nwith rule, erule, rule_tac or erule_tac.  You may also use lemmas that\nyou have proved so long as they meet the same restriction.\n*)\n\nthm notI\nthm notE\nthm conjI\nthm conjE\nthm disjI1\nthm disjI2\nthm disjE\nthm impI\nthm impE\nthm iffI\nthm iffE\n\n(*\nnotI: (P \\<Longrightarrow> False) \\<Longrightarrow> \\<not> P\nnotE: \\<lbrakk> \\<not> P; P \\<rbrakk> \\<Longrightarrow> Q\nconjI: \\<lbrakk> P; Q \\<rbrakk> \\<Longrightarrow> P \\<and> Q\nconjE: \\<lbrakk> P \\<and> Q; \\<lbrakk> P; Q \\<rbrakk> \\<Longrightarrow> R \\<rbrakk> \\<Longrightarrow> R\ndisjI1: P \\<Longrightarrow> P \\<or> Q\ndisjI2: Q \\<Longrightarrow> P \\<or> Q\ndisjE: \\<lbrakk> P \\<or> Q; P \\<Longrightarrow> R; Q \\<Longrightarrow> R \\<rbrakk> \\<Longrightarrow> R\nimpI: (P \\<Longrightarrow> Q) \\<Longrightarrow> P \\<longrightarrow> Q\nimpE: \\<lbrakk> P \\<longrightarrow> Q; P; Q \\<Longrightarrow> R \\<rbrakk> \\<Longrightarrow> R\niffI: \\<lbrakk> P \\<Longrightarrow> Q; Q \\<Longrightarrow> P \\<rbrakk> \\<Longrightarrow> P = Q\niffE: \\<lbrakk> P = Q; \\<lbrakk> P \\<longrightarrow> Q; Q \\<longrightarrow> P \\<rbrakk> \\<Longrightarrow> R \\<rbrakk> \\<Longrightarrow> R\n\nProve:\n*)\n\n(* +3 *)\nlemma problem1: \"(A \\<and> B) \\<longrightarrow> (B \\<and> A)\"\napply (rule impI)\napply (erule conjE)\napply (rule conjI)\napply assumption\napply assumption\ndone\n\n(* + 4 *)\nlemma problem2thy: \"(A \\<or> A) \\<longrightarrow> (B \\<or> A)\"\napply (rule impI)\napply (rule disjI2)\napply (erule disjE)\napply (assumption)\napply (assumption)\ndone\n\nlemma problem2pdf: \"(A \\<or> B) \\<longrightarrow> (B \\<or> A)\"\napply (rule impI)\napply (erule disjE)\napply (rule disjI2)\napply (assumption)\napply (rule disjI1)\napply (assumption)\ndone\n\n(* +4  *)\nlemma problem3: \"(A \\<and> B) \\<longrightarrow> ((\\<not>B) \\<longrightarrow> (\\<not>A))\"\napply (rule impI)\napply (erule conjE)\napply (rule impI)\napply (erule notE)\napply assumption\ndone\n\n(* + 5 *)\nlemma problem4: \" (A \\<longrightarrow> B) \\<longrightarrow> ((\\<not> B) \\<longrightarrow> (\\<not> A))\"\napply (rule impI)\napply (rule impI)\napply (rule notI)\napply (rule impE, assumption, assumption)\napply (rule notE, assumption, assumption)\ndone\n\n(* + 5 *)\nlemma problem5: \"((A \\<and> B) \\<longrightarrow> C) \\<longrightarrow> (A \\<longrightarrow> (B \\<longrightarrow> C))\"\napply (rule impI)\napply (rule impI)\napply (rule impI)\napply (rule impE, assumption)\napply (rule conjI, assumption, assumption)\napply assumption\ndone\n\n(* + 7 *)\nlemma problem6: \"((\\<not> B) \\<or> (\\<not> A)) \\<longrightarrow> (\\<not>(A \\<and> B))\"\napply (rule impI)\napply (rule notI)\napply (rule conjE, assumption)\napply (rule disjE, assumption)\napply (rule notE, assumption, assumption)\napply (rule notE, assumption, assumption)\ndone\n\n(* + 7 *)\nlemma problem7: \"(\\<not>A \\<or> \\<not>B) \\<longrightarrow> (\\<not>(A \\<and> B))\"\napply (rule impI)\napply (rule notI)\napply (rule conjE, assumption)\napply (rule disjE, assumption)\napply (rule notE, assumption, assumption)\napply (rule notE, assumption, assumption)\ndone\n\n(* Extra Credit *)\nthm classical\n\n(* + 1 *)\nlemma problem8: \"\\<not> \\<not> A \\<longrightarrow> A\"\napply(rule impI)\napply(rule classical)\napply(erule notE)\napply assumption\ndone\n\n(* + 2 *)\nlemma problem9: \"A \\<or> \\<not> A\"\napply(rule classical)\napply(rule disjI2)\napply(rule notI)\napply(erule notE)\napply(rule disjI1)\napply assumption\ndone\n\n(* + 2 *)\nlemma problem10: \"(\\<not> A \\<longrightarrow> B) \\<longrightarrow> (\\<not> B \\<longrightarrow> A)\"\napply(rule impI)\napply(rule impI)\napply(rule classical)\napply(erule impE)\napply(assumption)\napply(erule notE)\napply assumption\ndone\n\n(* +2 *)\nlemma problem11: \"((A \\<longrightarrow> B) \\<longrightarrow> A) \\<longrightarrow> A\"\napply(rule impI)\napply(rule classical)\napply(erule impE)\napply(rule impI)\napply(erule notE)\napply assumption\napply assumption\ndone\n\n(* + 5 *)\nlemma problem12: \"(\\<not> (A \\<and> B)) = (\\<not> A \\<or> \\<not> B)\"\napply (rule iffI)\napply (rule classical)\napply (rule disjI1)\napply (rule notI)\napply (erule notE)\napply (rule conjI)\napply assumption\napply (rule classical)\napply (erule notE)\napply (rule disjI2)\napply assumption\napply (rule notI)\napply (erule conjE)\napply (erule disjE)\napply (erule notE)\napply assumption\napply (erule notE)\napply assumption\ndone\n\n(* + 3 *)\nlemma problem13: \"(\\<not> A \\<longrightarrow> False) \\<longrightarrow> A\"\napply (rule impI)\napply (rule classical)\napply (erule impE)\napply assumption\napply (rule_tac P = \"\\<not> A\" in notE)\napply (rule notI)\napply assumption\napply assumption\ndone\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/mp1_sol.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835371034368, "lm_q2_score": 0.845942439250491, "lm_q1q2_score": 0.7067709813309094}}
{"text": "(*\n  File: BigSet.thy\n  Author: Bohua Zhan\n\n  Some results about arbitrary union and intersection.\n*)\n\ntheory BigSet\n  imports Functions\nbegin\n\nsection \\<open>Big union\\<close>\n\nlemma Union_mem_D: \"x \\<in> A \\<Longrightarrow> A \\<in> S \\<Longrightarrow> x \\<in> \\<Union>(S)\" by auto2\n\nlemma Union_subset_iff: \"\\<Union>(A) \\<subseteq> C \\<longleftrightarrow> (\\<forall>x\\<in>A. x \\<subseteq> C)\" by auto2\n\nlemma Union_upper: \"B \\<in> A \\<Longrightarrow> B \\<subseteq> \\<Union>(A)\" by auto2\n\nlemma Union_Un_distrib: \"\\<Union>(A \\<union> B) = \\<Union>(A) \\<union> \\<Union>(B)\" by auto2\n\nlemma Union_Int_subset: \"\\<Union>(A \\<inter> B) \\<subseteq> \\<Union>(A) \\<inter> \\<Union>(B)\" by auto2\n\nlemma Union_disjoint: \"\\<Union>(C) \\<inter> A = \\<emptyset> \\<longleftrightarrow> (\\<forall>B\\<in>C. B \\<inter> A = \\<emptyset>)\" by auto2\n\nsection \\<open>Big intersection\\<close>\n\nlemma Inter_Un_distrib:\n  \"A \\<noteq> \\<emptyset> \\<Longrightarrow> B \\<noteq> \\<emptyset> \\<Longrightarrow> \\<Inter>(A \\<union> B) = \\<Inter>(A) \\<inter> \\<Inter>(B)\" by auto2\n\nsection \\<open>Parametrized union and intersection\\<close>  (* Bourbaki II.4.1 -- II.4.4 *)\n\nlemma UN_surj [rewrite]:\n  \"surjective(f) \\<Longrightarrow> is_function(B) \\<Longrightarrow> f \\<in> K \\<rightarrow> I \\<Longrightarrow> (\\<Union>x\\<in>K. B`(f`x)) = (\\<Union>x\\<in>I. B`x)\"\n@proof @have (@rule) \"\\<forall>y\\<in>I. \\<exists>x\\<in>K. f`x = y\" @qed\n\nlemma INT_surj [rewrite]:\n  \"surjective(f) \\<Longrightarrow> is_function(B) \\<Longrightarrow> f \\<in> K \\<rightarrow> I \\<Longrightarrow> I \\<noteq> \\<emptyset> \\<Longrightarrow> (\\<Inter>x\\<in>K. B`(f`x)) = (\\<Inter>x\\<in>I. B`x)\"\n@proof @have (@rule) \"\\<forall>y\\<in>I. \\<exists>x\\<in>K. f`x = y\" @qed\n\nlemma UN_image_subset [resolve]:\n  \"\\<forall>x\\<in>I. X(x) \\<subseteq> Y(x) \\<Longrightarrow> (\\<Union>x\\<in>I. X(x)) \\<subseteq> (\\<Union>x\\<in>I. Y(x))\" by auto2\n\nlemma INT_image_subset [backward2]:\n  \"\\<forall>x\\<in>I. X(x) \\<subseteq> Y(x) \\<Longrightarrow> I \\<noteq> \\<emptyset> \\<Longrightarrow> (\\<Inter>x\\<in>I. X(x)) \\<subseteq> (\\<Inter>x\\<in>I. Y(x))\" by auto2\n\nlemma UN_source_subset [backward]:\n  \"J \\<subseteq> I \\<Longrightarrow> (\\<Union>x\\<in>J. X(x)) \\<subseteq> (\\<Union>x\\<in>I. X(x))\" by auto2\n\nlemma INT_source_subset [backward2]:\n  \"J \\<subseteq> I \\<Longrightarrow> J \\<noteq> \\<emptyset> \\<Longrightarrow> (\\<Inter>x\\<in>I. X(x)) \\<subseteq> (\\<Inter>x\\<in>J. X(x))\" by auto2\n\nlemma UN_double_eq [rewrite_back]:\n  \"(\\<Union>a\\<in>(\\<Union>x\\<in>L. J(x)). X(a)) = (\\<Union>x\\<in>L. \\<Union>a\\<in>J(x). X(a))\" by auto2\n\nlemma UN_nonempty [backward]:\n  \"I \\<noteq> \\<emptyset> \\<Longrightarrow> \\<forall>a\\<in>I. X(a) \\<noteq> \\<emptyset> \\<Longrightarrow> (\\<Union>a\\<in>I. X(a)) \\<noteq> \\<emptyset>\" by auto2\n\nlemma INT_double_eq [rewrite_back]:\n  \"\\<forall>x\\<in>L. J(x) \\<noteq> \\<emptyset> \\<Longrightarrow> L \\<noteq> \\<emptyset> \\<Longrightarrow> (\\<Inter>a\\<in>(\\<Union>x\\<in>L. J(x)). X(a)) = (\\<Inter>x\\<in>L. \\<Inter>a\\<in>J(x). X(a))\" by auto2\n\nlemma INT_image_eq [rewrite]:\n  \"injective(f) \\<Longrightarrow> I \\<noteq> \\<emptyset> \\<Longrightarrow> f `` (\\<Inter>a\\<in>I. X(a)) = (\\<Inter>a\\<in>I. f `` X(a))\" by auto2\n\nlemma INT_vImage [backward]:\n  \"is_function(\\<Gamma>) \\<Longrightarrow> I \\<noteq> \\<emptyset> \\<Longrightarrow> \\<Gamma> -`` (\\<Inter>a\\<in>I. X(a)) = (\\<Inter>a\\<in>I. \\<Gamma> -`` X(a))\" by auto2\n\nlemma UN_complement:\n  \"I \\<noteq> \\<emptyset> \\<Longrightarrow> E \\<midarrow> (\\<Union>a\\<in>I. X(a)) = (\\<Inter>a\\<in>I. E \\<midarrow> X(a))\" by auto2\n\nlemma INT_complement [rewrite]:\n  \"I \\<noteq> \\<emptyset> \\<Longrightarrow> E \\<midarrow> (\\<Inter>a\\<in>I. X(a)) = (\\<Union>a\\<in>I. E \\<midarrow> X(a))\" by auto2\n\nsection \\<open>Union and intersection of two sets\\<close>  (* Bourbaki II.4.5 *)\n\nlemma Un_to_UN [rewrite_back]:\n  \"A \\<union> B = (\\<Union>{A, B})\" by auto2\n\nlemma Int_to_INT [rewrite_back]:\n  \"A \\<inter> B = (\\<Inter>{A, B})\" by auto2\n\nlemma Un_distrib [resolve]:\n  \"A \\<union> (B \\<inter> C) = (A \\<union> B) \\<inter> (A \\<union> C)\" by auto2\n\nlemma Int_distrib [resolve]:\n  \"A \\<inter> (B \\<union> C) = (A \\<inter> B) \\<union> (A \\<inter> C)\" by auto2\n\nlemma Un_complement [rewrite]:\n  \"E \\<midarrow> (A \\<union> B) = (E \\<midarrow> A) \\<inter> (E \\<midarrow> B)\" by auto2\n\nlemma Int_complement [rewrite]:\n  \"E \\<midarrow> (A \\<inter> B) = (E \\<midarrow> A) \\<union> (E \\<midarrow> B)\" by auto2\n\nlemma Un_with_complement [rewrite]:\n  \"A \\<subseteq> E \\<Longrightarrow> A \\<union> (E \\<midarrow> A) = E\" by auto2\n\nlemma Int_with_complement [rewrite]:\n  \"A \\<inter> (E \\<midarrow> A) = \\<emptyset>\" by auto2\n\nlemma Int_vImage [rewrite]:\n  \"is_function(f) \\<Longrightarrow> f -`` (A \\<inter> B) = (f -`` A) \\<inter> (f -`` B)\" by auto2\n\nlemma Diff_vImage [rewrite]:\n  \"is_function(f) \\<Longrightarrow> X \\<subseteq> E \\<Longrightarrow> f -`` (E \\<midarrow> X) = (f -`` E) \\<midarrow> (f -`` X)\" by auto2\n\nlemma Int_image_eq [rewrite]:\n  \"injective(f) \\<Longrightarrow> X \\<subseteq> source(f) \\<Longrightarrow> f `` (source(f) \\<midarrow> X) = image(f) \\<midarrow> f `` X\" by auto2\n\nsection \\<open>Finite roducts\\<close>\n  \nlemma prod_inter [rewrite]:\n  \"(A \\<times> B) \\<inter> (C \\<times> D) = (A \\<inter> C) \\<times> (B \\<inter> D)\" 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/BigSet.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424295406088, "lm_q2_score": 0.8354835411997897, "lm_q1q2_score": 0.7067709766837414}}
{"text": "(*  Title:      Dual_Ordered_Lattice.thy\n    Authors:    Makarius; Peter Gammie; Brian Huffman; Florian Haftmann, TU Muenchen\n*)\n\nsection \\<open>Type of dual ordered lattices\\<close>\n\ntheory Dual_Ordered_Lattice\nimports Main\nbegin\n\ntext \\<open>\n  The \\<^emph>\\<open>dual\\<close> of an ordered structure is an isomorphic copy of the\n  underlying type, with the \\<open>\\<le>\\<close> relation defined as the inverse\n  of the original one.\n\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\\<close>\n\ntypedef 'a dual = \"UNIV :: 'a set\"\n  morphisms undual dual ..\n\nsetup_lifting type_definition_dual\n\ncode_datatype dual\n\nlemma dual_eqI:\n  \"x = y\" if \"undual x = undual y\"\n  using that by transfer assumption\n\nlemma dual_eq_iff:\n  \"x = y \\<longleftrightarrow> undual x = undual y\"\n  by transfer simp\n\nlemma eq_dual_iff [iff]:\n  \"dual x = dual y \\<longleftrightarrow> x = y\"\n  by transfer simp\n\nlemma undual_dual [simp, code]:\n  \"undual (dual x) = x\"\n  by transfer rule\n\nlemma dual_undual [simp]:\n  \"dual (undual x) = x\"\n  by transfer rule\n\nlemma undual_comp_dual [simp]:\n  \"undual \\<circ> dual = id\"\n  by (simp add: fun_eq_iff)\n\nlemma dual_comp_undual [simp]:\n  \"dual \\<circ> undual = id\"\n  by (simp add: fun_eq_iff)\n\nlemma inj_dual:\n  \"inj dual\"\n  by (rule injI) simp\n\nlemma inj_undual:\n  \"inj undual\"\n  by (rule injI) (rule dual_eqI)\n\nlemma surj_dual:\n  \"surj dual\"\n  by (rule surjI [of _ undual]) simp\n\nlemma surj_undual:\n  \"surj undual\"\n  by (rule surjI [of _ dual]) simp\n\nlemma bij_dual:\n  \"bij dual\"\n  using inj_dual surj_dual by (rule bijI)\n\nlemma bij_undual:\n  \"bij undual\"\n  using inj_undual surj_undual by (rule bijI)\n\ninstance dual :: (finite) finite\nproof\n  from finite have \"finite (range dual :: 'a dual set)\"\n    by (rule finite_imageI)\n  then show \"finite (UNIV :: 'a dual set)\"\n    by (simp add: surj_dual)\nqed\n\ninstantiation dual :: (equal) equal\nbegin\n\nlift_definition equal_dual :: \"'a dual \\<Rightarrow> 'a dual \\<Rightarrow> bool\"\n  is HOL.equal .\n\ninstance\n  by (standard; transfer) (simp add: equal)\n\nend\n\n\nsubsection \\<open>Pointwise ordering\\<close>\n\ninstantiation dual :: (ord) ord\nbegin\n\nlift_definition less_eq_dual :: \"'a dual \\<Rightarrow> 'a dual \\<Rightarrow> bool\"\n  is \"(\\<ge>)\" .\n\nlift_definition less_dual :: \"'a dual \\<Rightarrow> 'a dual \\<Rightarrow> bool\"\n  is \"(>)\" .\n\ninstance ..\n\nend\n\nlemma dual_less_eqI:\n  \"x \\<le> y\" if \"undual y \\<le> undual x\"\n  using that by transfer assumption\n\nlemma dual_less_eq_iff:\n  \"x \\<le> y \\<longleftrightarrow> undual y \\<le> undual x\"\n  by transfer simp\n\nlemma less_eq_dual_iff [iff]:\n  \"dual x \\<le> dual y \\<longleftrightarrow> y \\<le> x\"\n  by transfer simp\n\nlemma dual_lessI:\n  \"x < y\" if \"undual y < undual x\"\n  using that by transfer assumption\n\nlemma dual_less_iff:\n  \"x < y \\<longleftrightarrow> undual y < undual x\"\n  by transfer simp\n\nlemma less_dual_iff [iff]:\n  \"dual x < dual y \\<longleftrightarrow> y < x\"\n  by transfer simp\n\ninstance dual :: (preorder) preorder\n  by (standard; transfer) (auto simp add: less_le_not_le intro: order_trans)\n\ninstance dual :: (order) order\n  by (standard; transfer) simp\n\n\nsubsection \\<open>Binary infimum and supremum\\<close>\n\ninstantiation dual :: (sup) inf\nbegin\n\nlift_definition inf_dual :: \"'a dual \\<Rightarrow> 'a dual \\<Rightarrow> 'a dual\"\n  is sup .\n\ninstance ..\n\nend\n\nlemma undual_inf_eq [simp]:\n  \"undual (inf x y) = sup (undual x) (undual y)\"\n  by (fact inf_dual.rep_eq)\n\nlemma dual_sup_eq [simp]:\n  \"dual (sup x y) = inf (dual x) (dual y)\"\n  by transfer rule\n\ninstantiation dual :: (inf) sup\nbegin\n\nlift_definition sup_dual :: \"'a dual \\<Rightarrow> 'a dual \\<Rightarrow> 'a dual\"\n  is inf .\n\ninstance ..\n\nend\n\nlemma undual_sup_eq [simp]:\n  \"undual (sup x y) = inf (undual x) (undual y)\"\n  by (fact sup_dual.rep_eq)\n\nlemma dual_inf_eq [simp]:\n  \"dual (inf x y) = sup (dual x) (dual y)\"\n  by transfer simp\n\ninstance dual :: (semilattice_sup) semilattice_inf\n  by (standard; transfer) simp_all\n\ninstance dual :: (semilattice_inf) semilattice_sup\n  by (standard; transfer) simp_all\n\ninstance dual :: (lattice) lattice ..\n\ninstance dual :: (distrib_lattice) distrib_lattice\n  by (standard; transfer) (fact inf_sup_distrib1)\n\n\nsubsection \\<open>Top and bottom elements\\<close>\n\ninstantiation dual :: (top) bot\nbegin\n\nlift_definition bot_dual :: \"'a dual\"\n  is top .\n\ninstance ..\n\nend\n\nlemma undual_bot_eq [simp]:\n  \"undual bot = top\"\n  by (fact bot_dual.rep_eq)\n\nlemma dual_top_eq [simp]:\n  \"dual top = bot\"\n  by transfer rule\n\ninstantiation dual :: (bot) top\nbegin\n\nlift_definition top_dual :: \"'a dual\"\n  is bot .\n\ninstance ..\n\nend\n\nlemma undual_top_eq [simp]:\n  \"undual top = bot\"\n  by (fact top_dual.rep_eq)\n\nlemma dual_bot_eq [simp]:\n  \"dual bot = top\"\n  by transfer rule\n\ninstance dual :: (order_top) order_bot\n  by (standard; transfer) simp\n\ninstance dual :: (order_bot) order_top\n  by (standard; transfer) simp\n\ninstance dual :: (bounded_lattice_top) bounded_lattice_bot ..\n\ninstance dual :: (bounded_lattice_bot) bounded_lattice_top ..\n\ninstance dual :: (bounded_lattice) bounded_lattice ..\n\n\nsubsection \\<open>Complement\\<close>\n\ninstantiation dual :: (uminus) uminus\nbegin\n\nlift_definition uminus_dual :: \"'a dual \\<Rightarrow> 'a dual\"\n  is uminus .\n\ninstance ..\n\nend\n\nlemma undual_uminus_eq [simp]:\n  \"undual (- x) = - undual x\"\n  by (fact uminus_dual.rep_eq)\n\nlemma dual_uminus_eq [simp]:\n  \"dual (- x) = - dual x\"\n  by transfer rule\n\ninstantiation dual :: (boolean_algebra) boolean_algebra\nbegin\n\nlift_definition minus_dual :: \"'a dual \\<Rightarrow> 'a dual \\<Rightarrow> 'a dual\"\n  is \"\\<lambda>x y. - (y - x)\" .\n\ninstance\n  by (standard; transfer) (simp_all add: diff_eq ac_simps)\n\nend\n\nlemma undual_minus_eq [simp]:\n  \"undual (x - y) = - (undual y - undual x)\"\n  by (fact minus_dual.rep_eq)\n\nlemma dual_minus_eq [simp]:\n  \"dual (x - y) = - (dual y - dual x)\"\n  by transfer simp\n\n\nsubsection \\<open>Complete lattice operations\\<close>\n\ntext \\<open>\n  The class of complete lattices is closed under formation of dual\n  structures.\n\\<close>\n\ninstantiation dual :: (Sup) Inf\nbegin\n\nlift_definition Inf_dual :: \"'a dual set \\<Rightarrow> 'a dual\"\n  is Sup .\n\ninstance ..\n\nend\n\nlemma undual_Inf_eq [simp]:\n  \"undual (Inf A) = Sup (undual ` A)\"\n  by (fact Inf_dual.rep_eq)\n\nlemma dual_Sup_eq [simp]:\n  \"dual (Sup A) = Inf (dual ` A)\"\n  by transfer simp\n\ninstantiation dual :: (Inf) Sup\nbegin\n\nlift_definition Sup_dual :: \"'a dual set \\<Rightarrow> 'a dual\"\n  is Inf .\n\ninstance ..\n\nend\n\nlemma undual_Sup_eq [simp]:\n  \"undual (Sup A) = Inf (undual ` A)\"\n  by (fact Sup_dual.rep_eq)\n\nlemma dual_Inf_eq [simp]:\n  \"dual (Inf A) = Sup (dual ` A)\"\n  by transfer simp\n\ninstance dual :: (complete_lattice) complete_lattice\n  by (standard; transfer) (auto intro: Inf_lower Sup_upper Inf_greatest Sup_least)\n\ncontext\n  fixes f :: \"'a::complete_lattice \\<Rightarrow> 'a\"\n    and g :: \"'a dual \\<Rightarrow> 'a dual\"\n  assumes \"mono f\"\n  defines \"g \\<equiv> dual \\<circ> f \\<circ> undual\"\nbegin\n\nprivate lemma mono_dual:\n  \"mono g\"\nproof\n  fix x y :: \"'a dual\"\n  assume \"x \\<le> y\"\n  then have \"undual y \\<le> undual x\"\n    by (simp add: dual_less_eq_iff)\n  with \\<open>mono f\\<close> have \"f (undual y) \\<le> f (undual x)\"\n    by (rule monoD)\n  then have \"(dual \\<circ> f \\<circ> undual) x \\<le> (dual \\<circ> f \\<circ> undual) y\"\n    by simp\n  then show \"g x \\<le> g y\"\n    by (simp add: g_def)\nqed\n\nlemma lfp_dual_gfp:\n  \"lfp f = undual (gfp g)\" (is \"?lhs = ?rhs\")\nproof (rule antisym)\n  have \"dual (undual (g (gfp g))) \\<le> dual (f (undual (gfp g)))\"\n    by (simp add: g_def)\n  with mono_dual have \"f (undual (gfp g)) \\<le> undual (gfp g)\"\n    by (simp add: gfp_unfold [where f = g, symmetric] dual_less_eq_iff)\n  then show \"?lhs \\<le> ?rhs\"\n    by (rule lfp_lowerbound)\n  from \\<open>mono f\\<close> have \"dual (lfp f) \\<le> dual (undual (gfp g))\"\n    by (simp add: lfp_fixpoint gfp_upperbound g_def)\n  then show \"?rhs \\<le> ?lhs\"\n    by (simp only: less_eq_dual_iff)\nqed\n\nlemma gfp_dual_lfp:\n  \"gfp f = undual (lfp g)\"\nproof -\n  have \"mono (\\<lambda>x. undual (undual x))\"\n    by (rule monoI)  (simp add: dual_less_eq_iff)\n  moreover have \"mono (\\<lambda>a. dual (dual (f a)))\"\n    using \\<open>mono f\\<close> by (auto intro: monoI dest: monoD)\n  moreover have \"gfp f = gfp (\\<lambda>x. undual (undual (dual (dual (f x)))))\"\n    by simp\n  ultimately have \"undual (undual (gfp (\\<lambda>x. dual\n    (dual (f (undual (undual x))))))) =\n      gfp (\\<lambda>x. undual (undual (dual (dual (f x)))))\"\n    by (subst gfp_rolling [where g = \"\\<lambda>x. undual (undual x)\"]) simp_all\n  then have \"gfp f =\n    undual\n     (undual\n       (gfp (\\<lambda>x. dual (dual (f (undual (undual x)))))))\"\n    by simp\n  also have \"\\<dots> = undual (undual (gfp (dual \\<circ> g \\<circ> undual)))\"\n    by (simp add: comp_def g_def)\n  also have \"\\<dots> = undual (lfp g)\"\n    using mono_dual by (simp only: Dual_Ordered_Lattice.lfp_dual_gfp)\n  finally show ?thesis .\nqed\n\nend\n\n\ntext \\<open>Finally\\<close>\n\nlifting_update dual.lifting\nlifting_forget dual.lifting\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/Dual_Ordered_Lattice.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424334245618, "lm_q2_score": 0.8354835289107307, "lm_q1q2_score": 0.7067709695328838}}
{"text": "section\\<open>Showing equivalence of links: An example\\<close>\n\ntheory Example\nimports Link_Algebra \nbegin\n\ntext\\<open>We prove that a link diagram with a single crossing is equivalent to the \nunknot\\<close>\n\n\n\nlemma prelim_cup_compress:\n \" ((basic (cup#[])) \\<circ> (basic (vert # vert # []))) ~\n      ((basic [])\\<circ>(basic (cup#[])))\"  \nproof-\n have \"domain_wall (basic (cup # [])) = 0\" \n       by auto\n moreover have \"codomain_wall (basic (cup # [])) = 2\" \n       by auto\n moreover \n     have \"make_vert_block (nat (codomain_wall (basic (cup # [])))) \n                                    = (vert # vert # [])\"\n       unfolding make_vert_block_def \n       by auto\n moreover have \"is_tangle_diagram   ((basic (cup#[])) \\<circ> (basic (vert # vert # [])))\"\n      using is_tangle_diagram.simps by auto \n ultimately \n  have \"compress_bottom \n          ((basic (cup#[])) \\<circ> (basic (vert # vert # []))) \n          ((basic []) \\<circ>(basic (cup#[])))\" \n      using compress_bottom_def by (metis is_tangle_diagram.simps(1))\n then have \"compress  ((basic (cup#[])) \\<circ> (basic (vert # vert # []))) \n      ((basic [])\\<circ>(basic (cup#[])))\" \n      using compress_def by auto\n then have \"linkrel ((basic (cup#[])) \\<circ> (basic (vert # vert # []))) \n      ((basic [])\\<circ>(basic (cup#[])))\" \n      unfolding linkrel_def by auto\n then show ?thesis \n     using Tangle_Equivalence.equality compress_bottom_def \n           Tangle_Moves.compress_bottom_def Tangle_Moves.compress_def \n           Tangle_Moves.linkrel_def \n     by auto\n qed\n\nlemma cup_compress:\n \"(basic (cup#[])) \\<circ> (basic (vert # vert # [])) ~ (basic (cup#[]))\"\n proof-\n have \" ((basic (cup#[])) \\<circ> (basic (vert # vert # []))) ~\n      ((basic [])\\<circ>(basic (cup#[])))\"  \n         using prelim_cup_compress  by auto\n moreover have \"((basic [])\\<circ>(basic (cup#[]))) ~  (basic (cup#[]))\"\n         using domain_compose refl sym Tangle_Equivalence.domain_compose \n         Tangle_Equivalence.sym domain.simps(2) domain_block.simps \n         domain_wall.simps(1) \n         is_tangle_diagram.simps(1) monoid_add_class.add.right_neutral\n         by auto\n ultimately show ?thesis using trans by (metis Example.transitive)\n qed\n \nabbreviation x::\"wall\"\nwhere\n\"x \\<equiv>   (basic [cup,cup])\\<circ>(basic [vert,over,vert]) \\<circ> (basic [cap,cap])\"\n\nabbreviation y::\"wall\"\nwhere\n\"y \\<equiv>    (basic [cup]) \\<circ> (basic [cap])\"\n\nlemma uncross_straighten_left_over:\"left_over ~ straight_line\"\nproof-\n have \"uncross right_over left_over\"\n        using uncross_positive_flip_def uncross_def by auto\n then have \"linkrel right_over left_over\"\n    using linkrel_def by auto\n then have \"right_over ~ left_over\"\n    using Tangle_Equivalence.equality by auto\n then have 1:\"left_over ~ right_over\"\n    using Tangle_Equivalence.sym by auto\n  have \"uncross right_over straight_line\"\n        using uncross_positive_straighten_def uncross_def by auto\n then have \"linkrel right_over straight_line\"\n    using linkrel_def by auto\n then have 2:\"right_over ~ straight_line\"\n    using Tangle_Equivalence.equality by auto\n  have \"(left_over ~  straight_line) \\<and> (right_over ~ straight_line)\n         \\<Longrightarrow> ?thesis\" \n            using transitive by auto\n then show ?thesis using 1 2 transitive  by blast\n qed\n\n\n\ntheorem Example:\n  \"x ~ y\" \nproof-\n have 1:\"left_over ~ straight_line\"\n    using Tangle_Equivalence.equality uncross_straighten_left_over by auto\n moreover have 2:\"straight_line ~ straight_line\"\n   using refl by auto\n have 3:\"(left_over \\<otimes> straight_line) ~ (straight_line \\<otimes> straight_line)\"\n proof-\n  have \"is_tangle_diagram (left_over)\"\n    unfolding is_tangle_diagram_def by auto \n  moreover have \"is_tangle_diagram (straight_line)\"\n    unfolding is_tangle_diagram_def by auto\n  ultimately show ?thesis using 1 2 by (metis Tangle_Equivalence.tensor_eq)\n qed\n then have 4:\n  \"((basic (cup#[])) \\<circ> (left_over \\<otimes> straight_line)) \n           ~   ((basic (cup#[])) \\<circ> (straight_line \\<otimes> straight_line))\"\n proof-\n  have \"is_tangle_diagram (left_over \\<otimes> straight_line)\"\n        by auto\n  moreover have \"is_tangle_diagram (straight_line \\<otimes> straight_line)\"\n        by auto\n  moreover have \"is_tangle_diagram (basic (cup#[]))\" \n         by auto\n  moreover have \"domain_wall (left_over \\<otimes> straight_line) = (codomain_wall (basic (cup#[])))\"\n        unfolding domain_wall_def by auto\n  moreover have \"domain_wall (straight_line \\<otimes> straight_line) = (codomain_wall (basic (cup#[])))\"\n        unfolding domain_wall_def by auto\n  moreover have \"(basic (cup#[])) ~ (basic (cup#[]))\" \n        using refl by auto\n  ultimately show ?thesis \n        using compose_eq 3  by (metis Tangle_Equivalence.compose_eq)\n qed\n moreover have 5:\"  (basic [cup])\\<circ> (straight_line \\<otimes> straight_line) \n                 ~ (basic [cup])\"\n proof-\n  have 0:\n   \"(basic ([cup])) \\<circ> (straight_line \\<otimes> straight_line) = (basic [cup]) \\<circ>(basic [vert,vert]) \n                                                         \\<circ> (basic [vert,vert])\\<circ>(basic [vert,vert])\"\n           by auto\n  let ?x =\"(basic (cup#[]))\n   \\<circ>(basic (vert#vert#[])) \\<circ> (basic (vert#vert#[]))\n   \\<circ> (basic (vert#vert#[]))\"\n  let ?x1 = \" (basic (vert#vert#[]))\\<circ> (basic (vert#vert#[]))\"\n  have 1:\"?x ~ ((basic (cup#[])) \\<circ> ?x1)\"\n  proof-\n   have \"(basic (cup#[]))\\<circ>(basic (vert # vert # [])) ~ (basic (cup#[]))\"\n        using cup_compress by auto\n   moreover have \"is_tangle_diagram  (basic (cup#[]))\" \n        using is_tangle_diagram_def by auto\n   moreover have \"is_tangle_diagram ((basic (cup#[]))\\<circ>(basic (vert # vert # [])))\"\n        using is_tangle_diagram_def by auto\n   moreover have \"is_tangle_diagram (?x1)\"\n        by auto\n   moreover have \"?x1 ~ ?x1\" \n        using refl by auto       \n   moreover have \n     \"codomain_wall (basic (cup#[])) = domain_wall  (basic (vert#vert#[]))\"\n        by auto\n   moreover have \"(basic (cup#[])) ~ (basic (cup#[]))\"\n         using refl by auto\n   ultimately show ?thesis \n         using compose_eq codomain_wall_compose compose_leftassociativity \n               converse_composition_of_tangle_diagrams domain_wall_compose\n         by (metis Tangle_Equivalence.compose_eq is_tangle_diagram.simps(1))\n  qed\n  have 2: \" ((basic (cup#[])) \\<circ> ?x1) ~ (basic (cup#[]))\"\n  proof-\n   have \"\n     ((basic (cup # []))\\<circ>(basic (vert # vert # [])))\\<circ>(basic (vert # vert # [])) \n          ~ ((basic(cup#[]))\\<circ>(basic(vert#vert#[])))\"\n   proof-\n    have \"(basic (cup#[]))\\<circ>(basic (vert # vert # [])) ~ (basic (cup#[]))\"\n         using cup_compress by auto\n    moreover have \"(basic(vert#vert#[])) ~ (basic(vert#vert#[]))\" \n         using refl by auto  \n    moreover have \"is_tangle_diagram  (basic (cup#[]))\" \n         using is_tangle_diagram_def by auto\n    moreover have \"is_tangle_diagram ((basic (cup#[]))\\<circ>(basic (vert # vert # [])))\"\n         using is_tangle_diagram_def by auto\n    moreover have \"is_tangle_diagram ((basic(vert#vert#[])))\"\n         by auto     \n    moreover have \n         \"codomain_wall ((basic (cup#[]))\\<circ>  (basic(vert#vert#[]))) \n                       = domain_wall  (basic(vert#vert#[]))  \"\n         by auto\n    moreover \n         have \"codomain_wall (basic (cup#[])) = domain_wall (basic(vert#vert#[]))\"\n         by auto       \n    ultimately show ?thesis \n                 using compose_eq \n                 by (metis Tangle_Equivalence.compose_eq)\n   qed \n   then have \"((basic (cup#[])) \\<circ> ?x1) ~\n           ((basic(cup#[]))\\<circ>(basic(vert#vert#[])))\"\n         by auto\n   then show ?thesis using cup_compress trans\n         by (metis (full_types) Example.transitive)\n  qed\n  from 0 1 2 show ?thesis using trans transp_def trans compose_Nil\n          by (metis (hide_lams, no_types) Example.transitive)\n qed\n let ?y = \"((basic ([])) \\<circ> (basic (cup#[])))  \"\n let ?temp = \"(basic (vert#over#vert#[]))\\<circ>(basic (cap#vert#vert#[])) \"  \n have 45:\"(left_over \\<otimes> straight_line) = \n          ((basic (cup#vert#vert#[])) \\<circ> ?temp)\"  \n          using tensor.simps by (metis compose_Nil concatenates_Cons concatenates_Nil)\n then have 55:\"(basic (cup#[])) \\<circ> (left_over \\<otimes> straight_line) \n             =  (basic (cup#[])) \\<circ>  (basic (cup#vert#vert#[])) \\<circ> ?temp\"\n          by auto\n then have \n  \"(basic (cup#[])) \\<circ> (basic (cup#vert#vert#[]))\n      =  (basic (([]) \\<otimes>(cup#[])))\\<circ>(basic ((cup#[])\\<otimes>(vert#vert#[])))\"\n          using concatenate.simps  by auto\n then have 6:\n \"(basic (cup#[])) \\<circ> (basic (cup#vert#vert#[]))\n          = ((basic ([]))\\<circ>(basic (cup#[])))\n            \\<otimes>((basic (cup#[])) \\<circ>(basic (vert#vert#[])))\"\n          using tensor.simps by auto\n then have \"((basic (cup#[])) \\<circ>(basic (vert#vert#[]))) \n                   ~ (basic ([]))\\<circ>(basic (cup#[]))\"\n          using prelim_cup_compress by auto\n moreover have \"((basic ([]))\\<circ>(basic (cup#[]))) \n                       ~ ((basic ([]))\\<circ>(basic (cup#[])))\"\n          using refl by auto\n moreover have \"is_tangle_diagram ((basic (cup#[])) \\<circ>(basic (vert#vert#[])))\"\n          by auto\n moreover have \"is_tangle_diagram ((basic ([]))\\<circ>(basic (cup#[]))) \"\n          by auto\n ultimately have 7:\"?y \\<otimes> ((basic (cup#[])) \\<circ>(basic (vert#vert#[])))~ ((?y) \\<otimes> (?y))\"\n          using tensor_eq cup_compress Nil_right_tensor is_tangle_diagram.simps(1) refl\n          by (metis Tangle_Equivalence.tensor_eq)\n then have \" ((?y) \\<otimes> (?y)) = (basic (([]) \\<otimes> ([])))\n                   \\<circ> ((basic (cup#[])) \\<otimes> (basic (cup#[])))\"\n          using tensor.simps(4)  by (metis compose_Nil) \n then have \"  ((?y) \\<otimes> (?y)) = (basic ([])) \\<circ>((basic (cup#cup#[])))\"\n          using tensor.simps(1) concatenate_def by auto\n then have \"(?y) \\<otimes> ((basic (cup#[])) \\<circ>(basic (vert#vert#[])))\n             ~ (basic ([])) \\<circ>(basic (cup#cup#[]))\" \n          using 7 by auto\n moreover have \"(basic ([]))\\<circ>(basic (cup#cup#[]))~(basic (cup#cup#[]))\"\n proof-\n  have \"domain_wall (basic (cup#cup#[])) = 0\"\n          by auto\n  then show ?thesis using domain_compose sym \n          by (metis Tangle_Equivalence.domain_compose Tangle_Equivalence.sym is_tangle_diagram.simps(1))\n qed\n ultimately have \"(?y) \\<otimes> ((basic (cup#[])) \\<circ>(basic (vert#vert#[])))\n               ~  (basic (cup#cup#[]))\"\n          using trans  by (metis (full_types) Example.transitive)\n then have \" (basic(cup#[]))\\<circ>(basic(cup#vert#vert#[]))~(basic(cup#cup#[]))\" \n          by auto\n moreover have \"?temp ~ ?temp\"\n          using refl by auto\n moreover  have \"is_tangle_diagram ((basic(cup#[]))\\<circ>(basic(cup#vert#vert#[])))\"\n          by auto\n moreover have \"is_tangle_diagram (basic(cup#cup#[]))\"\n          by auto\n moreover have \"is_tangle_diagram  (?temp)\"\n          by auto\n moreover have \"codomain_wall  ((basic(cup#[]))\\<circ>(basic(cup#vert#vert#[])))\n                    = domain_wall ?temp\"\n          by auto\n moreover have \"codomain_wall (basic(cup#cup#[])) = domain_wall ?temp\"\n          by auto\n ultimately have 8:\" ((basic(cup#[]))\\<circ>(basic(cup#vert#vert#[]))) \\<circ>(?temp)\n                       ~ (basic(cup#cup#[])) \\<circ> (?temp)\"\n          using compose_eq by (metis Tangle_Equivalence.compose_eq)\n then have \"((basic [cup,cup]) \\<circ> (?temp)) \n                 ~ (basic [cup] \\<circ> (left_over \\<otimes> straight_line))\"\n          using 55 compose_leftassociativity sym wall.simps   \n          by (metis Tangle_Equivalence.sym compose_Nil)\n moreover have \"(basic [cup]) \\<circ> (left_over \\<otimes> straight_line) \n                    ~ (basic [cup]) \\<circ> (straight_line \\<otimes> straight_line)\"\n          using 4 by auto\n ultimately have \"((basic [cup,cup]) \\<circ> (?temp)) \n                  ~ (basic [cup]) \\<circ> (straight_line \\<otimes> straight_line)\"          \n  proof-\n   have \"((basic [cup,cup]) \\<circ> (?temp)) \n                 ~ (basic [cup] \\<circ> (left_over \\<otimes> straight_line))\"\n          using 8 55 compose_leftassociativity sym wall.simps  Tangle_Equivalence.sym compose_Nil  \n          by (metis)    \n   moreover have \"(basic [cup]) \\<circ> (left_over \\<otimes> straight_line) \n                    ~ (basic [cup]) \\<circ> (straight_line \\<otimes> straight_line)\"\n          using 4 by auto\n   moreover have \"(((basic [cup,cup]) \\<circ> (?temp)) \n                 ~ (basic [cup] \\<circ> (left_over \\<otimes> straight_line)))\n        \\<and> ((basic [cup]) \\<circ> (left_over \\<otimes> straight_line) \n                    ~ (basic [cup]) \\<circ> (straight_line \\<otimes> straight_line))\n           \\<Longrightarrow> ?thesis\"\n          using Example.transitive by auto\n   ultimately show ?thesis by auto\n  qed\n  then have \"(basic ([cup,cup])) \\<circ> (?temp)  ~ (basic (cup # []))\"\n         using trans transp_def 5 by (metis Example.transitive)\n  moreover have \"(basic (cap#[])) ~ (basic (cap#[]))\"\n         using refl by auto\n  moreover have \"is_tangle_diagram ((basic(cup#cup#[])) \\<circ> (?temp))\"\n         by auto\n  moreover have \"is_tangle_diagram (basic (cup # []))\"\n         by auto\n  moreover have \"is_tangle_diagram (basic (cap # []))\"\n         by auto\n  moreover have \"codomain_wall ((basic(cup#cup#[])) \\<circ> (?temp)) \n                   = domain_wall (basic (cap # []))\"\n         by auto\n  moreover have \"codomain_wall (basic(cup#[])) = domain_wall (basic (cap # []))\"\n         by auto\n ultimately have 9:\"((basic(cup#cup#[])) \\<circ> (?temp)) \\<circ> (basic (cap#[]))\n                     ~ (basic (cup#[])) \\<circ> (basic (cap#[]))\"\n         using Tangle_Equivalence.compose_eq by metis\n  let ?z = \"((basic(cup#cup#[])) \\<circ> (basic(vert#over#vert#[])))\"\n  have 10:\"((basic(cup#cup#[])) \\<circ> (?temp)) \\<circ> (basic (cap#[]))\n              = ?z \\<circ> ((basic(cap#vert#vert#[])) \\<circ> (basic (cap#[])))\"\n         by auto\n  then have 11:\"((basic(cap#vert#vert#[])) \\<circ> (basic (cap#[])))\n                           = ((basic ((cap#[])\\<otimes>(vert#vert#[])))\\<circ>(basic (([]) \\<otimes>(cap#[]))))\"\n          unfolding concatenate_def by auto\n  then have 12:\" ((basic(cap#vert#vert#[])) \\<circ> (basic (cap#[]))) \n                       = ((basic (cap#[]))\\<circ>(basic ([])))\\<otimes>((basic (vert#vert#[]))\\<circ>(basic (cap#[])))\"\n          using tensor.simps by auto\n  let ?w = \"((basic (cap#[]))\\<circ>(basic ([])))\"\n  have 13:\"((basic (vert#vert#[]))\\<circ>(basic (cap#[]))) ~ ?w\"\n  proof-\n   have \"codomain_wall (basic (cap#[])) = 0\" \n        by auto\n   then have \"domain_wall (basic (cap#[])) = 2\" by auto\n   then have \"(vert#vert#[]) \n                          = make_vert_block (nat (domain_wall (basic (cap#[]))))\"\n     by (simp add: make_vert_block_def)\n   then have \"compress_top  ((basic (vert#vert#[]))\\<circ>(basic (cap#[]))) ?w\"\n        using compress_top_def by auto\n   then have \"compress ((basic (vert#vert#[]))\\<circ>(basic (cap#[]))) ?w\" \n        using compress_def by auto\n   then have \"linkrel  ((basic (vert#vert#[]))\\<circ>(basic (cap#[]))) ?w\" \n        using linkrel_def by auto\n   then have \" ((basic (vert#vert#[]))\\<circ>(basic (cap#[]))) ~ ?w\"\n        using Tangle_Equivalence.equality by auto\n   then show ?thesis by simp\n  qed\n  moreover have \"is_tangle_diagram ((basic (vert#vert#[]))\\<circ>(basic (cap#[])))\"\n        by auto\n  moreover have \"is_tangle_diagram ?w\"\n        by auto\n  moreover have \"?w ~ ?w\" \n        using refl by auto\n  ultimately have 14:\"(?w) \\<otimes> ((basic (vert#vert#[]))\\<circ>(basic (cap#[]))) ~ ((?w)\\<otimes> (?w))\"\n        using Tangle_Equivalence.tensor_eq by metis\n  then have \"((basic(cap#vert#vert#[])) \\<circ> (basic (cap#[]))) ~ ((?w)\\<otimes> (?w))\"\n        using 13 by auto\n  moreover have \" ((?w)\\<otimes> (?w)) = (basic (cap#cap#[])) \\<circ> (basic ([]))\"\n        using tensor.simps by auto\n  ultimately have \"((basic(cap#vert#vert#[]))\\<circ>(basic (cap#[])))~ (basic (cap#cap#[]))\\<circ>(basic ([]))\"\n        by auto\n  moreover have \"?z ~ ?z\" \n        using refl by auto\n  moreover have \"domain_wall ((basic(cap#cap#[])) \\<circ> (basic ([])))\n                                = codomain_wall (?z)\"\n        by auto\n  moreover have \"domain_wall (((basic(cap#vert#vert#[])) \\<circ> (basic (cap#[]))))\n                                = codomain_wall (?z)\" \n        by auto\n  moreover have \"is_tangle_diagram ((basic(cap#vert#vert#[])) \\<circ> (basic (cap#[])))\"\n        by auto\n  moreover have \"is_tangle_diagram (?z)\"\n        by auto\n  moreover have \"is_tangle_diagram  ((basic(cap#cap#[])) \\<circ> (basic ([])))\"\n        by auto\n  ultimately have 14:\" (?z) \\<circ>  ((basic(cap#vert#vert#[])) \\<circ> (basic (cap#[])))\n                      ~ (?z) \\<circ> ((basic(cap#cap#[])) \\<circ> (basic ([])))\" (is \"?aa ~ ?bb\")\n        using Tangle_Equivalence.compose_eq by metis\n  moreover  have 15: \"((?z) \\<circ> ((basic(cap#cap#[]))) \\<circ> (basic ([]))) \n                ~ ((?z) \\<circ> (basic(cap#cap#[])))\" (is \"?bb ~ ?cc\")\n        using Tangle_Equivalence.codomain_compose  Tangle_Equivalence.sym \n               \\<open>is_tangle_diagram (basic [cap, cap] \\<circ> basic [])\\<close> codomain_wall_compose \n               compose_leftassociativity converse_composition_of_tangle_diagrams \n               domain_block.simps(1) domain_wall.simps(1)\n        by (metis (hide_lams, mono_tags) Tangle_Equivalence.compose_eq \n                Tangle_Equivalence.refl \n                \\<open>codomain_wall (basic [cup, cup]) \n                         = domain_wall (basic [vert, over, vert] \\<circ> basic [cap, vert, vert])\\<close> \n                   \\<open>domain_wall (basic [cap, cap] \\<circ> basic []) \n          = codomain_wall (basic [cup, cup] \\<circ> basic [vert, over, vert])\\<close> \n                          comp_of_tangle_dgms domain_wall_compose is_tangle_diagram.simps(1))\n  ultimately have \"(?aa ~ ?bb)\\<and> (?bb ~ ?cc) \\<Longrightarrow>?aa ~ ?cc\"\n        using transitive by auto\n  then have 16:\"?aa ~ ?cc\"\n        using 14 15 by auto\n  then have 17:\" ((basic (cup#[]))\\<circ>(basic (cap#[])))~ ?aa\"\n        using 9 10 Tangle_Equivalence.trans  Tangle_Equivalence.sym \n        by (metis (hide_lams, no_types))\n  have \"(((basic (cup#[]))\\<circ>(basic (cap#[])))~ ?aa)\\<and>(?aa ~ ?cc)\n            \\<Longrightarrow> ((basic (cup#[]))\\<circ>(basic (cap#[])))~ ?cc\" \n        using transitive by auto\n  then have \"((basic (cup#[]))\\<circ>(basic (cap#[])))~ ?cc\"\n            using 17 16 by auto\n  then show ?thesis using Tangle_Equivalence.sym 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/Knot_Theory/Example.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.912436153333645, "lm_q2_score": 0.7745833945721304, "lm_q1q2_score": 0.7067578929795116}}
{"text": "theory List_Demo\nimports Main\nbegin\n\n  \ndatatype 'a list = Nil | Cons \"'a\" \"'a list\"\n\ndatatype 'a ll = Nil | Cons \"'a * 'a\" \"'a ll\"  \n  \ndatatype 'a tree = Leaf | Node \"'a tree\" 'a \"'a tree\"\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\n(* Associativity of append. \n  Intuitively: It makes no difference if we first append xs and ys, \n  and then append zs to the result, or if we first append ys and zs, \n  and append the result to xs.\n*)\nlemma \"app (app xs ys) zs = app xs (app ys zs)\"\n  apply (induction xs)\n  apply auto\n  done  \n\n(*\n  Reverse a list ... we'll come here later!\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\ntheorem rev_rev: \"rev (rev xs) = xs\"\napply (induction xs)\napply (auto)\n(* For now, we are stuck here: We'll later see how to complete the proof. *)    \noops (* Oops cancels unsuccessful proof attempt. *)\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/List_Demo.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361557147439, "lm_q2_score": 0.7745833893685269, "lm_q1q2_score": 0.7067578900759153}}
{"text": "theory CommOr\n  imports Main\nbegin\n \ntext\\<open> Apply style \\<close>\nlemma lem_w_1 : \"(p \\<or> q) \\<longrightarrow> (q \\<or> p)\"\n  apply (rule impI)\n  apply (erule disjE)\n   apply (rule disjI2)\n   apply assumption\n  apply (rule disjI1)\n  apply assumption\n  done\n\ntext\\<open> Apply style proof, more verbose than the preceding proof \\<close>\nlemma lem_w_2 : \"(p \\<or> q) \\<longrightarrow> (q \\<or> p)\"\n  apply (rule impI)\n  apply (rule disjE)\n    apply assumption\n   apply (rule disjI2)\n   apply assumption\n  apply (rule disjI1)\n  apply assumption\n  done\n\ntext\\<open> Isar style \\<close>\nlemma lem_x_1 : \"(p \\<or> q) \\<longrightarrow> (q \\<or> p)\"\nproof   \n  assume A : \"(p \\<or> q)\" \n  from A show \"(q \\<or> p)\"\n  proof \n    assume \"p\" thus \"(q \\<or> p)\" by (rule disjI2)\n    (* you can substitute '..' for 'by (rule disjI2)'*)\n  next\n    assume \"q\" thus \"(q \\<or> p)\" by (rule disjI1) \n    (* you can substitute '..' for 'by (rule disjI1)'*)\n  qed\nqed\n\n\nend\n\n", "meta": {"author": "peter-oldriver", "repo": "Zhangde_CS511", "sha": "148d667702326150e0e8285023fe4df2649db049", "save_path": "github-repos/isabelle/peter-oldriver-Zhangde_CS511", "path": "github-repos/isabelle/peter-oldriver-Zhangde_CS511/Zhangde_CS511-148d667702326150e0e8285023fe4df2649db049/CommOr.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8333246118695629, "lm_q2_score": 0.847967764140929, "lm_q1q2_score": 0.7066324079306406}}
{"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)\"\n  unfolding complete_def uwellformed_def all_edges_def\n  by 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)\"\n  unfolding all_edges_def\n  by simp\n\ncorollary complete_finite_edges: \"finite V \\<Longrightarrow> finite (uedges (complete V))\"\n  unfolding complete_def using all_edges_finite\n  by 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 = {}\"\n  unfolding all_edges_def\n  by 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)\"\n  using complete_finite_edges unfolding finite_graph_def complete_def\n  by 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)\"\n  using 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\"\n  unfolding subgraph_def\n  by simp\n\nlemma subgraph_trans: \"subgraph G'' G' \\<Longrightarrow> subgraph G' G \\<Longrightarrow> subgraph G'' G\"\n  unfolding subgraph_def\n  by auto\n\nlemma subgraph_antisym: \"subgraph G G' \\<Longrightarrow> subgraph G' G \\<Longrightarrow> G = G'\"\n  unfolding subgraph_def\n  by (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)\"\n  using subgraph_complete subgraph_def complete_def by simp\n\ncorollary max_edges_graph: \n  assumes \"uwellformed G\" \"finite (uverts G)\"\n  shows \"card (uedges G) \\<le> (card (uverts G))^2\"\nproof -\n  have \"card (uedges G) \\<le> card (uverts G) choose 2\" \n    by (metis all_edges_finite assms card_all_edges card_mono wellformed_all_edges)\n  thus ?thesis\n    by (metis binomial_le_pow le0 neq0_conv order.trans zero_less_binomial_iff) \nqed\n\nlemma subgraph_finite: \"\\<lbrakk> finite_graph G; subgraph G' G \\<rbrakk> \\<Longrightarrow> finite_graph G'\"\n  unfolding finite_graph_def subgraph_def\n  by (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  then show ?thesis\n    by (meson assms isomorphic_sym order_antisym_conv)\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\"\n  by (meson G V assms induced_is_subgraph(1) is_fixed_selector_def sub subgraph_isomorphic_def subgraph_trans)\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_Graph_Subgraph_Threshold/Ugraph_Lemmas.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8479677737461007, "lm_q2_score": 0.8333245891029456, "lm_q1q2_score": 0.7066323966295088}}
{"text": "theory FiniteListGraph\nimports \n  FiniteGraph\n  \"Transitive-Closure.Transitive_Closure_List_Impl\"\nbegin\n\nsection \\<open>Specification of a finite graph, implemented by lists\\<close>\n\ntext\\<open>A graph \\<open>G=(V,E)\\<close> consits of a list of vertices @{term V}, also called nodes, \n       and a list of edges @{term E}. The edges are tuples of vertices.\n       Using lists instead of sets, code can be easily created.\\<close>\n\n  record 'v list_graph =\n    nodesL :: \"'v list\"\n    edgesL :: \"('v \\<times>'v) list\"\n\ntext\\<open>Correspondence the FiniteGraph\\<close>\n  definition list_graph_to_graph :: \"'v list_graph \\<Rightarrow> 'v graph\" where \n    \"list_graph_to_graph G = \\<lparr> nodes = set (nodesL G), edges = set (edgesL G) \\<rparr>\"\n\n\n  definition wf_list_graph_axioms :: \"'v list_graph \\<Rightarrow> bool\" where\n    \"wf_list_graph_axioms G \\<longleftrightarrow> fst` set (edgesL G) \\<subseteq> set (nodesL G) \\<and> snd` set (edgesL G) \\<subseteq> set (nodesL G)\"\n\n\n  lemma wf_list_graph_iff_wf_graph: \"wf_graph (list_graph_to_graph G) \\<longleftrightarrow> wf_list_graph_axioms G\"\n  unfolding list_graph_to_graph_def wf_graph_def wf_list_graph_axioms_def\n  by simp\n\n  text\\<open>We say a @{typ \"'v list_graph\"} is valid if it fulfills the graph axioms and its lists are distinct\\<close>\n  definition wf_list_graph::\"('v) list_graph \\<Rightarrow> bool\" where\n   \"wf_list_graph G = (distinct (nodesL G) \\<and> distinct (edgesL G) \\<and> wf_list_graph_axioms G)\"\n\n\nsection\\<open>FiniteListGraph operations\\<close>\n\n  text \\<open>Adds a node to a graph.\\<close>\n  definition add_node :: \"'v \\<Rightarrow> 'v list_graph \\<Rightarrow> 'v list_graph\" where \n    \"add_node v G = \\<lparr> nodesL = (if v \\<in> set (nodesL G) then nodesL G else v#nodesL G), edgesL=edgesL G \\<rparr>\"\n\n  text \\<open>Adds an edge to a graph.\\<close>\n  definition add_edge :: \"'v \\<Rightarrow> 'v \\<Rightarrow> 'v list_graph \\<Rightarrow> 'v list_graph\" where \n    \"add_edge v v' G = (add_node v (add_node v' G)) \\<lparr>edgesL := (if (v, v') \\<in> set (edgesL G) then edgesL G else (v, v')#edgesL G) \\<rparr>\"\n\n  text \\<open>Deletes a node from a graph. Also deletes all adjacent edges.\\<close>\n  definition delete_node :: \"'v \\<Rightarrow> 'v list_graph \\<Rightarrow> 'v list_graph\" where \n  \"delete_node v G = \\<lparr> \n    nodesL = remove1 v (nodesL G), edgesL = [(e1,e2) \\<leftarrow> (edgesL G). e1 \\<noteq> v \\<and> e2 \\<noteq> v]\n    \\<rparr>\"\n\n  text \\<open>Deletes an edge from a graph.\\<close>\n  definition delete_edge :: \"'v \\<Rightarrow> 'v \\<Rightarrow> 'v list_graph \\<Rightarrow> 'v list_graph\" where \n    \"delete_edge v v' G = \\<lparr>nodesL = nodesL G, edgesL = [(e1,e2) \\<leftarrow> edgesL G. e1 \\<noteq> v \\<or> e2 \\<noteq> v'] \\<rparr>\"\n\n  \n  fun delete_edges::\"'v list_graph \\<Rightarrow> ('v \\<times> 'v) list \\<Rightarrow> 'v list_graph\" where \n    \"delete_edges G [] = G\"|\n    \"delete_edges G ((v,v')#es) = delete_edges (delete_edge v v' G) es\"\n\n\n\ntext \\<open>extended graph operations\\<close>\n   text \\<open>Reflexive transitive successors of a node. Or: All reachable nodes for v including v.\\<close>\n    definition succ_rtran :: \"'v list_graph \\<Rightarrow> 'v \\<Rightarrow> 'v list\" where\n      \"succ_rtran G v = rtrancl_list_impl (edgesL G) [v]\"\n\n   text \\<open>Transitive successors of a node. Or: All reachable nodes for v.\\<close>\n    definition succ_tran :: \"'v list_graph \\<Rightarrow> 'v \\<Rightarrow> 'v list\" where\n      \"succ_tran G v = trancl_list_impl (edgesL G) [v]\"\n  \n   text \\<open>The number of reachable nodes from v\\<close>\n    definition num_reachable :: \"'v list_graph \\<Rightarrow> 'v \\<Rightarrow> nat\" where\n      \"num_reachable G v = length (succ_tran G v)\"\n\n\n    definition num_reachable_norefl :: \"'v list_graph \\<Rightarrow> 'v \\<Rightarrow> nat\" where\n      \"num_reachable_norefl G v = length ([ x \\<leftarrow> succ_tran G v. x \\<noteq> v])\"\n\n\nsubsection\\<open>undirected graph simulation\\<close>\n  text \\<open>Create undirected graph from directed graph by adding backward links\\<close>\n  fun backlinks :: \"('v \\<times> 'v) list \\<Rightarrow> ('v \\<times> 'v) list\" where\n    \"backlinks [] = []\" |\n    \"backlinks ((e1, e2)#es) = (e2, e1)#(backlinks es)\"\n\n  definition undirected :: \"'v list_graph \\<Rightarrow> 'v list_graph\"\n    where \"undirected G \\<equiv> \\<lparr> nodesL = nodesL G, edgesL = remdups (edgesL G @ backlinks (edgesL G)) \\<rparr>\"\n\nsection\\<open>Correctness lemmata\\<close>\n\n  \\<comment> \\<open>add node\\<close>\n  lemma add_node_wf: \"wf_list_graph G \\<Longrightarrow> wf_list_graph (add_node v G)\"\n  unfolding wf_list_graph_def wf_list_graph_axioms_def add_node_def\n  by auto\n\n  lemma add_node_set_nodes: \"set (nodesL (add_node v G)) = set (nodesL G) \\<union> {v}\"\n  unfolding add_node_def\n  by auto\n\n  lemma add_node_set_edges: \"set (edgesL (add_node v G)) = set (edgesL G)\"\n  unfolding add_node_def\n  by auto\n\n  lemma add_node_correct: \"FiniteGraph.add_node v (list_graph_to_graph G) = list_graph_to_graph (add_node v G)\"\n  unfolding FiniteGraph.add_node_def list_graph_to_graph_def\n  by (simp add: add_node_set_edges add_node_set_nodes)\n\n  lemma add_node_wf2: \"wf_graph (list_graph_to_graph G) \\<Longrightarrow> wf_graph (list_graph_to_graph (add_node v G))\"\n  by (subst add_node_correct[symmetric]) simp\n\n  \\<comment> \\<open>add edge\\<close>\n  lemma add_edge_wf: \"wf_list_graph G \\<Longrightarrow> wf_list_graph (add_edge v v' G)\"\n  unfolding wf_list_graph_def add_edge_def add_node_def wf_list_graph_axioms_def\n  by auto\n\n  lemma add_edge_set_nodes: \"set (nodesL (add_edge v v' G)) = set (nodesL G) \\<union> {v,v'}\"\n  unfolding add_edge_def add_node_def\n  by auto\n\n  lemma add_edge_set_edges: \"set (edgesL (add_edge v v' G)) = set (edgesL G) \\<union> {(v,v')}\"\n  unfolding add_edge_def add_node_def\n  by auto\n\n  lemma add_edge_correct: \"FiniteGraph.add_edge v v' (list_graph_to_graph G) = list_graph_to_graph (add_edge v v' G)\"\n  unfolding FiniteGraph.add_edge_def add_edge_def list_graph_to_graph_def\n  by (auto simp: add_node_set_nodes)\n\n  lemma add_edge_wf2: \"wf_graph (list_graph_to_graph G) \\<Longrightarrow> wf_graph (list_graph_to_graph (add_edge v v' G))\"\n  by (subst add_edge_correct[symmetric]) simp\n\n  \\<comment> \\<open>delete node\\<close>\n  lemma delete_node_wf: \"wf_list_graph G \\<Longrightarrow> wf_list_graph (delete_node v G)\"\n  unfolding wf_list_graph_def delete_node_def wf_list_graph_axioms_def\n  by auto\n\n  lemma delete_node_set_edges:\n    \"set (edgesL (delete_node v G)) = {(a,b). (a, b) \\<in> set (edgesL G) \\<and> a \\<noteq> v \\<and> b \\<noteq> v}\"\n  unfolding delete_node_def\n  by auto\n\n  lemma delete_node_correct:\n    assumes \"wf_list_graph G\"\n    shows \"FiniteGraph.delete_node v (list_graph_to_graph G) = list_graph_to_graph (delete_node v G)\"\n  using assms\n  unfolding FiniteGraph.delete_node_def delete_node_def list_graph_to_graph_def wf_list_graph_def\n  by auto\n\n  \\<comment> \\<open>delete edge\\<close>\n  lemma delete_edge_set_nodes: \"set (nodesL (delete_edge v v' G)) = set (nodesL G)\"\n  unfolding delete_edge_def\n  by simp\n\n  lemma delete_edge_set_edges:\n    \"set (edgesL (delete_edge v v' G)) = {(a,b). (a,b) \\<in> set (edgesL G) \\<and> (a,b) \\<noteq> (v,v')}\"\n  unfolding delete_edge_def\n  by auto\n\n  \n\n  lemma delete_edge_wf: \"wf_list_graph G \\<Longrightarrow> wf_list_graph (delete_edge v v' G)\"\n  unfolding wf_list_graph_def delete_edge_def wf_list_graph_axioms_def\n  by auto\n    \n  \n\n  lemma delete_edge_commute: \"delete_edge a1 a2 (delete_edge b1 b2 G) = delete_edge b1 b2 (delete_edge a1 a2 G)\"\n  unfolding delete_edge_def\n  by simp metis (* auto doesn't seem to like filter_cong *)\n\n  lemma delete_edge_correct: \"FiniteGraph.delete_edge v v' (list_graph_to_graph G) = list_graph_to_graph (delete_edge v v' G)\"\n  unfolding FiniteGraph.delete_edge_def delete_edge_def list_graph_to_graph_def\n  by auto\n\n  lemma delete_edge_wf2: \"wf_graph (list_graph_to_graph G) \\<Longrightarrow> wf_graph (list_graph_to_graph (delete_edge v v' G))\"\n  by (subst delete_edge_correct[symmetric]) simp\n\n  \\<comment> \\<open>delete edges\\<close>\n  lemma delete_edges_wf: \"wf_list_graph G \\<Longrightarrow> wf_list_graph (delete_edges G E)\"\n  by (induction E arbitrary: G) (auto simp: delete_edge_wf)\n\n  lemma delete_edges_set_nodes: \"set (nodesL (delete_edges G E)) = set (nodesL G)\"\n  by (induction E arbitrary: G) (auto simp: delete_edge_set_nodes)\n\n  lemma delete_edges_nodes: \"nodesL (delete_edges G es) = nodesL G\"\n  by (induction es arbitrary: G) (auto simp: delete_edge_def)\n\n  lemma delete_edges_set_edges: \"set (edgesL (delete_edges G E)) = set (edgesL G) - set E\"\n  by (induction E arbitrary: G) (auto simp: delete_edge_def delete_edge_set_nodes)\n\n  lemma delete_edges_set_edges2:\n    \"set (edgesL (delete_edges G E)) = {(a,b). (a,b) \\<in> set (edgesL G) \\<and> (a,b) \\<notin> set E}\"\n  by (auto simp: delete_edges_set_edges)\n\n  lemma delete_edges_length: \"length (edgesL (delete_edges G f)) \\<le> length (edgesL G)\"\n  proof (induction f arbitrary:G)\n    case (Cons f fs)\n    thus ?case\n      apply (cases f, hypsubst)\n      apply (subst delete_edges.simps(2))\n      apply (metis delete_edge_length le_trans)\n      done\n  qed simp\n\n  lemma delete_edges_chain: \"delete_edges G (as @ bs) = delete_edges (delete_edges G as) bs\"\n  proof (induction as arbitrary: bs G)\n    case (Cons f fs)\n    thus ?case\n      by (cases f) auto\n  qed simp\n\n  lemma delete_edges_delete_edge_commute:\n    \"delete_edges (delete_edge a1 a2 G) as = delete_edge a1 a2 (delete_edges G as)\"\n  proof (induction as arbitrary: G a1 a2)\n    case (Cons f fs)\n    thus ?case\n      by (cases f) (simp add: delete_edge_commute)\n  qed simp\n\n  lemma delete_edges_commute:\n    \"delete_edges (delete_edges G as) bs = delete_edges (delete_edges G bs) as\"\n  proof (induction as arbitrary: bs G)\n    case (Cons f fs)\n    thus ?case\n      by (cases f) (simp add: delete_edges_delete_edge_commute)\n  qed simp\n\n  lemma delete_edges_as_filter:\n    \"delete_edges G l = \\<lparr> nodesL = nodesL G,  edgesL = [x \\<leftarrow> edgesL G. x \\<notin> set l] \\<rparr>\"\n  proof (induction l)\n    case (Cons f fs)\n    thus ?case\n      apply (cases f)\n      apply (simp add: delete_edges_delete_edge_commute)\n      apply (simp add: delete_edge_def)\n      apply (metis (lifting, full_types) prod.exhaust case_prodI split_conv)\n      done\n  qed simp\n\n  declare delete_edges.simps[simp del] (*do not automatically expand definition*)\n\n  lemma delete_edges_correct:\n    \"FiniteGraph.delete_edges (list_graph_to_graph G) (set E) = list_graph_to_graph (delete_edges G E)\"\n  unfolding list_graph_to_graph_def FiniteGraph.delete_edges_def\n  by (auto simp add: delete_edges_as_filter )\n  \n  lemma delete_edges_wf2:\n    \"wf_graph (list_graph_to_graph G) \\<Longrightarrow> wf_graph (list_graph_to_graph (delete_edges G E))\"\n  by (subst delete_edges_correct[symmetric]) simp\n\n  \\<comment> \\<open>helper about reflexive transitive closure impl\\<close>\n  lemma distinct_relpow_impl:\n    \"distinct L \\<Longrightarrow> distinct new \\<Longrightarrow> distinct have \\<Longrightarrow> distinct (new@have) \\<Longrightarrow> \n     distinct (relpow_impl (\\<lambda>as. remdups (map snd [(a, b)\\<leftarrow>L . a \\<in> set as])) (\\<lambda>xs ys. [x\\<leftarrow>xs . x \\<notin> set ys] @ ys) (\\<lambda>x xs. x \\<in> set xs) new have M)\"\n  proof (induction M arbitrary: \"new\" \"have\")\n    case Suc\n    hence\n      \"distinct ([x\\<leftarrow>new . x \\<notin> set have] @ have)\"\n      \"set ([n\\<leftarrow>remdups (map snd [(a, b)\\<leftarrow>L . a \\<in> set new]) . (n \\<in> set new \\<longrightarrow> n \\<in> set have) \\<and> n \\<notin> set have]) \\<inter> set ([x\\<leftarrow>new . x \\<notin> set have] @ have) = {}\"\n      by auto\n\n    with Suc show ?case\n      by auto\n  qed auto\n\n  lemma distinct_rtrancl_list_impl: \"distinct L \\<Longrightarrow> distinct ls \\<Longrightarrow> distinct (rtrancl_list_impl L ls)\"\n  unfolding rtrancl_list_impl_def rtrancl_impl_def\n  by (simp add:distinct_relpow_impl)\n\n  lemma distinct_trancl_list_impl: \"distinct L \\<Longrightarrow> distinct ls \\<Longrightarrow> distinct (trancl_list_impl L ls)\"\n  unfolding trancl_list_impl_def trancl_impl_def\n  by (simp add:distinct_relpow_impl)\n\n  \\<comment> \\<open>succ rtran\\<close>\n  value \"succ_rtran \\<lparr> nodesL = [1::nat,2,3,4,8,9,10], edgesL = [(1,2), (2,3), (3,4), (8,9),(9,8)] \\<rparr> 1\"\n\n  lemma succ_rtran_correct: \"FiniteGraph.succ_rtran (list_graph_to_graph G) v = set (succ_rtran G v)\"\n  unfolding FiniteGraph.succ_rtran_def succ_rtran_def list_graph_to_graph_def\n  by (simp add: rtrancl_list_impl)\n\n  lemma distinct_succ_rtran: \"wf_list_graph G \\<Longrightarrow> distinct (succ_rtran G v)\"\n  unfolding succ_rtran_def wf_list_graph_def\n  by (auto intro: distinct_rtrancl_list_impl)\n\n  lemma succ_rtran_set: \"set (succ_rtran G v) = {e2. (v,e2) \\<in> (set (edgesL G))\\<^sup>*}\"\n  unfolding succ_rtran_def\n  by (simp add: rtrancl_list_impl)\n\n  \\<comment> \\<open>succ tran\\<close>\n  lemma distinct_succ_tran: \"wf_list_graph G \\<Longrightarrow> distinct (succ_tran G v)\"\n  unfolding succ_tran_def wf_list_graph_def\n  by (auto intro: distinct_trancl_list_impl)\n\n  lemma succ_tran_set: \"set (succ_tran G v) = {e2. (v,e2) \\<in> (set (edgesL G))\\<^sup>+}\"\n  unfolding succ_tran_def\n  by (simp add: trancl_list_impl)\n\n  value \"succ_tran \\<lparr> nodesL = [1::nat,2,3,4,8,9,10], edgesL = [(1,2), (2,3), (3,4), (8,9),(9,8)] \\<rparr> 1\"\n\n  lemma succ_tran_correct: \"FiniteGraph.succ_tran (list_graph_to_graph G) v = set (succ_tran G v)\"\n  unfolding FiniteGraph.succ_tran_def succ_tran_def list_graph_to_graph_def\n  by (simp add:trancl_list_impl)\n  \n  \\<comment> \\<open>num_reachable\\<close>\n  lemma num_reachable_correct:\n    \"wf_list_graph G \\<Longrightarrow> FiniteGraph.num_reachable (list_graph_to_graph G) v = num_reachable G v\"\n  unfolding num_reachable_def FiniteGraph.num_reachable_def\n  by (metis List.distinct_card distinct_succ_tran succ_tran_correct)\n\n  \\<comment> \\<open>num_reachable_norefl\\<close>\n  lemma num_reachable_norefl_correct:\n    \"wf_list_graph G \\<Longrightarrow> \n     FiniteGraph.num_reachable_norefl (list_graph_to_graph G) v = num_reachable_norefl G v\"\n unfolding num_reachable_norefl_def FiniteGraph.num_reachable_norefl_def\n by (metis (full_types) List.distinct_card distinct_filter distinct_succ_tran set_minus_filter_out succ_tran_correct)\n\n  \\<comment> \\<open>backlinks, i.e. backflows in formal def\\<close>\n  lemma backlinks_alt: \"backlinks E = [(snd e, fst e). e \\<leftarrow> E]\"\n  by (induction E) auto\n\n  lemma backlinks_set: \"set (backlinks E) = {(e2, e1). (e1, e2) \\<in> set E}\"\n  by (induction E) auto\n\n  lemma undirected_nodes_set: \"set (edgesL (undirected G)) = set (edgesL G) \\<union> {(e2, e1). (e1, e2) \\<in> set (edgesL G)}\"\n  unfolding undirected_def\n  by (simp add: backlinks_set)\n\n  lemma undirected_succ_tran_set: \"set (succ_tran (undirected G) v) = {e2. (v,e2) \\<in> (set (edgesL (undirected G)))\\<^sup>+}\"\n  by (fact succ_tran_set)\n\n  lemma backlinks_in_nodes_G: \"\\<lbrakk> fst ` set (edgesL G) \\<subseteq> set (nodesL G); snd ` set (edgesL G) \\<subseteq> set (nodesL G) \\<rbrakk> \\<Longrightarrow> \n    fst` set (edgesL (undirected G)) \\<subseteq> set (nodesL (undirected G)) \\<and> snd` set (edgesL (undirected G)) \\<subseteq> set (nodesL (undirected G))\"\n  unfolding undirected_def\n  by(auto simp: backlinks_set)\n\n  lemma backlinks_distinct: \"distinct E \\<Longrightarrow> distinct (backlinks E)\"\n  by (induction E) (auto simp: backlinks_alt)\n\n  lemma backlinks_subset: \"set (backlinks X) \\<subseteq> set (backlinks Y) \\<longleftrightarrow> set X \\<subseteq> set Y\"\n  by (auto simp: backlinks_set)\n\n  lemma backlinks_correct: \"FiniteGraph.backflows (set E) = set (backlinks E)\"\n  unfolding backflows_def\n  by(simp add: backlinks_set)\n\n  \\<comment> \\<open>undirected\\<close>\n  lemma undirected_wf: \"wf_list_graph G \\<Longrightarrow> wf_list_graph (undirected G)\"\n  unfolding wf_list_graph_def wf_list_graph_axioms_def\n  by (simp add:backlinks_in_nodes_G) (simp add: undirected_def)\n\n  lemma undirected_correct: \n    \"FiniteGraph.undirected (list_graph_to_graph G) = list_graph_to_graph (undirected G)\"\n  unfolding FiniteGraph.undirected_def undirected_def list_graph_to_graph_def\n  by (simp add: backlinks_set)\n      \nlemmas wf_list_graph_wf =\n  add_node_wf\n  add_edge_wf\n  delete_node_wf\n  delete_edge_wf\n  delete_edges_wf\n  undirected_wf\n\nlemmas list_graph_correct =\n  add_node_correct\n  add_edge_correct\n  delete_node_correct\n  delete_edge_correct\n  delete_edges_correct\n  succ_rtran_correct\n  succ_tran_correct\n  num_reachable_correct\n  undirected_correct\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/Network_Security_Policy_Verification/Lib/FiniteListGraph.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8479677660619633, "lm_q2_score": 0.8333245891029456, "lm_q1q2_score": 0.7066323902261283}}
{"text": "theory axioms_class_existence\nimports ntuples\nbegin\n\nsection{* Axioms of Class Existence *}\n\ntext{* Mendelson introduces seven ``Axioms of Class Existence''\n       instead of the axiom schema of separation for classes. \n       We shall first introduce these axioms and then prove \n       that for any first order formula with one free variable, \n       whose bounded quantifiers are about sets, the following \n       axioms provide us with a class that contains exactly those\n       sets that satisfy this formula for any class parameter that\n       occurs in the formula. Before we give the Axioms of Class\n       existence, we need to be able to talk about triples, apart\n       from tuples. *}\n\naxiomatization\n  intersection :: \"Class \\<Rightarrow> Class \\<Rightarrow> Class\" (infixl \"\\<inter>\" 80)\nand\n  complement :: \"Class \\<Rightarrow> Class\" (\"Co\")\nand\n  domain :: \"Class \\<Rightarrow> Class\" (\"dom\")\n  where \n    B1: \"\\<exists>X::Class. \\<forall>u v::Set. ((\\<langle>u, v\\<rangle> \\<in> X) \\<longleftrightarrow> u \\<in> v)\" \n      --\"belongs-relation\"\nand B2: \"\\<forall>u::Set. (u \\<in> (X\\<inter>Y) \\<longleftrightarrow> u\\<in>X \\<and> u\\<in>Y)\"\n      -- \"intersection\"\nand B3: \"\\<forall>u::Set. (u \\<in> Co(X) \\<longleftrightarrow> u \\<notin> X)\"\n      -- \"complement\"\nand B4: \"\\<forall>u::Set. (u \\<in> dom(X)\\<longleftrightarrow>(\\<exists>v::Set. (\\<langle>u, v\\<rangle>\\<in>X)))\"\n      -- \"domain\"\nand B5: \"\\<exists>Z::Class. \\<forall>u v::Set.(\\<langle>u, v\\<rangle>\\<in>Z\\<longleftrightarrow>u\\<in>X)\" \n      -- \"projection to the first coordinate\"\nand B6: \"\\<exists>Z::Class. \\<forall>u v w::Set. (\\<langle>u, v, w\\<rangle>\\<in>Z \\<longleftrightarrow> \\<langle>v, w, u\\<rangle>\\<in>X)\"\n      -- \"permutation of coordinates, all move 'to the left'\"\nand B7: \"\\<exists>Z::Class. \\<forall>u v w::Set. (\\<langle>u, v, w\\<rangle>\\<in>Z \\<longleftrightarrow> \\<langle>u, w, v\\<rangle>\\<in>X)\"\n      -- \"permutation of the last two coordinates\"\n\n(* page 231 *)\n\n(* The following are the uniqueness lemmas mentioned in the comments in the \n           beginning of page 231. *)\n\nlemma intersection_unique: \"\\<exists>! Z :: Class. \\<forall> u :: Set. (u\\<in>Z \\<longleftrightarrow> (u\\<in>X \\<and> u\\<in>Y))\"\nunfolding Ex1_def \nproof (rule exI, rule conjI)\n  def Z \\<equiv> \"X\\<inter>Y\"\n  show \"(\\<forall>u::Set. u \\<in> Z \\<longleftrightarrow> (u \\<in> X \\<and> u \\<in> Y))\" using B2 Z_def by simp\n  thus \"(\\<forall>Z'. (\\<forall>u::Set. u \\<in> Z' \\<longleftrightarrow> (u \\<in> X \\<and> u \\<in> Y)) \\<longrightarrow> (Z' = Z)) \"\n    by (simp add: set_extensionality) \nqed\n\n(* Same proof below! *)\n\nlemma complement_unique: \"\\<exists>! Z :: Class. \\<forall> u :: Set. (u\\<in>Z \\<longleftrightarrow> u\\<notin>X)\" \nunfolding Ex1_def \nproof (rule exI, rule conjI)\n  def Z \\<equiv> \"Co X\"\n  show \"(\\<forall>u::Set. u \\<in> Z \\<longleftrightarrow> (u \\<notin> X))\" using B3 Z_def by simp\n  thus \"(\\<forall>Z'. (\\<forall>u::Set. u \\<in> Z' \\<longleftrightarrow> (u \\<notin> X)) \\<longrightarrow> (Z' = Z)) \"\n    by (simp add: set_extensionality) \nqed\n\n(* And again \"same\". *)\n\ntext{* \\textbf{FOMUS workshop exercise:} *}\n\nlemma domain_unique: \"\\<exists>!Z::Class. \\<forall>u::Set. (u\\<in>Z \\<longleftrightarrow> (\\<exists>v::Set. (\\<langle>u,v\\<rangle>\\<in>X)))\"\nsorry\n\nabbreviation union :: \"Class \\<Rightarrow> Class \\<Rightarrow> Class\" (infixl \"\\<union>\" 80) \nwhere \"X\\<union>Y \\<equiv> Co( Co(X) \\<inter> Co(Y) )\"\n\nabbreviation Class_difference :: \"Class \\<Rightarrow> Class \\<Rightarrow> Class\" \n  (infixl \"\\<setminus>\" 80) \nwhere \"X\\<setminus>Y \\<equiv> X \\<inter> (Co(Y))\"\n\ntext{* The last abbreviation in Mendelson's list of page 231 \n       is one for the universal set. We have this already so we \n       prove the following lemma instead. *}\n\ntext{* The following is Exercise 4.9 in Mendelson. *}\n\nlemma Ex4_9_a: \"\\<forall>u :: Set. u \\<in> X \\<union> Y \\<longleftrightarrow> u \\<in> X \\<or> u \\<in> Y\"\n  by (simp add: B2 B3)\n\nlemma Ex4_9_b: \"\\<forall>u :: Set. u \\<in> \\<V>\"\n  by (metis Quotient_Set Quotient_rep_reflp Quotient_to_Domainp Set.domain_eq Set.pcr_cr_eq)\n\nlemma Ex4_9_c: \"\\<forall>u::Set. u \\<in> X \\<setminus> Y \\<longleftrightarrow> u \\<in> X \\<and> u \\<notin> Y\"\n  by (simp add: B2 B3)\n\nlemma Ex4_10_a: \"X \\<inter> Y = Y \\<inter> X\"\nusing Ex4_2 B2 by auto\n\nlemma Ex4_10_b: \"X \\<union> Y = Y \\<union> X\"\nusing Ex4_2 B2 B3 by auto\n\nlemma Ex4_10_c: \"X \\<subseteq> Y \\<longleftrightarrow> (X \\<inter> Y = X)\"\nproof\n  assume \"X \\<subseteq> Y\"\n  with subclass'_def B2 Ex4_2 show \"X \\<inter> Y = X\" by auto\n  next\n  assume assm: \"X \\<inter> Y = X\"\n  have \"\\<forall>Z. (Z \\<in> X \\<longrightarrow> Z \\<in> Y)\"\n  proof\n    fix Z\n    show \"Z \\<in> X \\<longrightarrow> Z \\<in> Y\"\n    proof (rule ccontr, simp)\n      assume assm2: \"Z \\<in> X \\<and> Z \\<notin> Y\"\n      then have \"Z \\<notin> Y\" ..\n      with assm B2 have \"Z \\<notin> X\" by (metis Abs_Set_inverse Ex4_1 mem_Collect_eq universe) \n      with assm2 show \"False\" by simp\n    qed\n  qed\n  with subclass'_def show \"X \\<subseteq> Y\" by auto\nqed\n\n\nlemma Ex4_10_d: \"X \\<subseteq> Y \\<longleftrightarrow> (X \\<union> Y = Y)\"\nproof\n  show \"X \\<subseteq> Y \\<Longrightarrow> X \\<union> Y = Y\" using Ex4_2 B2 B3 subclass'_def by auto\n  next  \n  assume assm: \"X \\<union> Y = Y\"\n  have \"\\<forall>Z \\<in> X. (Z \\<in> Y)\" unfolding forall_in_def\n  proof\n    fix Z::Set\n    show \"Z \\<in> X \\<longrightarrow> Z \\<in> Y\" \n    proof (rule ccontr, simp)\n      assume assm1: \"Z \\<in> X \\<and> Z \\<notin> Y\"\n      then have \"Z \\<notin> Y\" ..\n      with assm have \"Z \\<notin> X \\<union> Y\" by simp\n      then have \"Z \\<notin> X\" using Ex4_9_a by blast \n      with assm1 show \"False\" by simp\n    qed\n  qed\n  with subclass'_def forall_in_def  show \"X \\<subseteq> Y\" by (metis Abs_Set_inverse CollectI Ex4_1 universe)\nqed\n\nlemma Ex4_10_e: \"(X \\<inter> Y) \\<inter> Z = X \\<inter> (Y \\<inter> Z)\"\nusing Ex4_2 B2 by auto\n\nlemma Ex4_10_f: \"(X \\<union> Y) \\<union> Z = X \\<union> (Y \\<union> Z)\"\nusing Ex4_2 B2 B3 by auto\n\nlemma Ex4_10_g: \"X \\<inter> X = X\"\nusing Ex4_2 B2 by auto\n\nlemma Ex4_10_h: \"X \\<union> X = X\"\nusing Ex4_2 B2 B3 by auto\n\nlemma Ex4_10_i: \"X \\<inter> \\<emptyset> = \\<emptyset>\"\nusing Ex4_2 empty_set B2 by auto\n\nlemma Ex4_10_j: \"X \\<union> \\<emptyset> = X\"\nusing Ex4_2 empty_set B2 B3 by auto\n\nlemma Ex4_10_k: \"X \\<inter> \\<V> = X\" \nproof -\n  have \"\\<forall>x::Set. x \\<in> X \\<inter> \\<V> \\<longleftrightarrow> x \\<in> X\"\n  proof\n    fix x\n    show \"x \\<in> X \\<inter> \\<V> = x \\<in> X\"\n    proof\n      assume \"x \\<in> X \\<inter> \\<V>\"\n      with B2 show \"x \\<in> X\" using Ex4_1 Ex4_10_c subclass'_def universe by metis\n      next\n      show \"x \\<in> X \\<Longrightarrow> x \\<in> X \\<inter> \\<V>\" using Ex4_1 Ex4_10_c subclass'_def universe by metis \n    qed\n  qed\n  then show \"X \\<inter> \\<V> = X\" using Ex4_2 by simp\nqed\n\nlemma Ex4_10_l: \"X \\<union> \\<V> = \\<V>\"\nusing Ex4_10_h Ex4_10_i by (metis Ex4_10_a Ex4_10_j Ex4_10_k) \n\nlemma Ex4_10_m: \"Co(X \\<union> Y) = Co(X) \\<inter> Co(Y)\"\nusing Ex4_10_g Ex4_10_h by auto\n\nlemma Ex4_10_n: \"Co(X \\<inter> Y) = Co(X) \\<union> Co(Y)\"\nusing Ex4_10_g Ex4_10_h by auto\n\nlemma Ex4_10_o: \"X\\<setminus>X = \\<emptyset>\" \nusing B2 B3 Ex4_2 empty_set by auto\n\nlemma Ex4_10_p: \"\\<V>\\<setminus>X = Co(X)\"\nusing Ex4_10_k Ex4_10_a by metis\n\nlemma Ex4_10_q: \"X \\<setminus> (X \\<setminus> Y) = X \\<inter> Y\"\nproof -\n  from B2 have \"\\<forall>x::Set. x \\<in> X \\<inter> (Co(X \\<inter> Co(Y))) \\<longleftrightarrow> x \\<in> X \\<and> x \\<in> Co(X \\<inter> Co(Y))\" by simp\n  with B3 have \"\\<forall>x::Set. x \\<in> X \\<inter> (Co(X \\<inter> Co(Y))) \\<longleftrightarrow> x \\<in> X \\<and> x \\<notin> (X \\<inter> Co(Y))\" by simp\n  with B2 have \"\\<forall>x::Set. x \\<in> X \\<inter> (Co(X \\<inter> Co(Y))) \\<longleftrightarrow> x \\<in> X \\<and> x \\<notin> Co(Y)\" by auto\n  with B3 have \"\\<forall>x::Set. x \\<in> X \\<inter> (Co(X \\<inter> Co(Y))) \\<longleftrightarrow> x \\<in> X \\<and> x \\<in> Y\" by simp\n  with B2 have \"\\<forall>x::Set. x \\<in> X \\<inter> (Co(X \\<inter> Co(Y))) \\<longleftrightarrow> x \\<in> X \\<inter> Y\" by simp\n  then show \"X \\<inter> (Co(X \\<inter> Co(Y))) = X \\<inter> Y\" using Ex4_2 by simp\nqed\n\nlemma Ex4_10_r: \"Y \\<subseteq> Co(X) \\<longrightarrow> X \\<setminus> Y = X\" by (metis Ex4_10_a Ex4_10_d Ex4_10_g Ex4_10_h)\n\nlemma Ex4_10_s: \"Co(Co(X)) = X\" using Ex4_10_g Ex4_10_h by auto\n\nlemma Ex4_10_t: \"Co(\\<V>) = \\<emptyset>\" by (metis Ex4_10_o Ex4_10_p) \n\n\nlemma Ex4_10_u: \"X \\<inter> (Y \\<union> Z) = (X \\<inter> Y) \\<union> (X \\<inter> Z)\"\nusing B2 B3 Ex4_2 Ex4_9_a by auto \n\nlemma Ex4_10_v: \"X \\<union> (Y \\<inter> Z) = (X \\<union> Y) \\<inter> (X \\<union> Z)\"\nusing B2 B3 Ex4_9_a Ex4_2  by auto\n\n\n\ntext{* Exercise 4.11. *}\n\nlemma Ex_4_11_a: \"\\<forall>X. \\<exists>Z. \\<forall>u v. \\<langle>u, v\\<rangle> \\<in> Z \\<longleftrightarrow> \\<langle>v, u\\<rangle> \\<in> X\"\nproof\n  fix X\n  obtain C where \"\\<forall>u v w. \\<langle>v, u, w\\<rangle> \\<in> C \\<longleftrightarrow> \\<langle>v, u\\<rangle> \\<in> X\" using B5 by blast\n  moreover obtain D where \"\\<forall>u v w. \\<langle>v, w, u\\<rangle> \\<in> D \\<longleftrightarrow> \\<langle>v, u, w\\<rangle> \\<in> C\" using B7 by blast\n  moreover obtain E where \"\\<forall>u v w. \\<langle>u, v, w\\<rangle> \\<in> E \\<longleftrightarrow> \\<langle>v, w, u\\<rangle> \\<in> D\" using B6 by blast\n  ultimately have \"\\<forall>u v. \\<langle>u, v\\<rangle> \\<in> dom(E) \\<longleftrightarrow> \\<langle>v, u\\<rangle> \\<in> X\" using B4 by simp\n  thus \"\\<exists>Z. \\<forall>u v. \\<langle>u, v\\<rangle> \\<in> Z \\<longleftrightarrow> \\<langle>v, u\\<rangle> \\<in> X\" ..\nqed\n\nlemma Ex_4_11_b: \"\\<forall>X. \\<exists>Z. \\<forall>u v w. \\<langle>u, v, w\\<rangle> \\<in> Z \\<longleftrightarrow> \\<langle>u, w\\<rangle> \\<in> X\"\nproof\n  fix X\n  obtain C where \"\\<forall>u v w. \\<langle>u, w, v\\<rangle> \\<in> C \\<longleftrightarrow> \\<langle>u, w\\<rangle> \\<in> X\" using B5 by blast\n  moreover obtain D where \"\\<forall>u v w. \\<langle>u, v, w\\<rangle> \\<in> D \\<longleftrightarrow> \\<langle>u, w, v\\<rangle> \\<in> C\" using B7 by blast\n  ultimately show \"\\<exists>Z. \\<forall>u v w. \\<langle>u, v, w\\<rangle> \\<in> Z \\<longleftrightarrow> \\<langle>u, w\\<rangle> \\<in> X\" by blast\nqed\n\nlemma Ex_4_11_c: \"\\<forall>X. \\<exists>Z. \\<forall>v. \\<forall>i :: nat \\<Rightarrow> Set. \\<langle>\\<dots>, i(n), v\\<rangle> \\<in> Z \\<longleftrightarrow> \\<langle>\\<dots>, i(n)\\<rangle> \\<in> X\"\nusing B5 by blast\n\n(* page 232 *)\n\nlemma Ex_4_11_d: \"\\<forall>X. \\<exists>Z. \\<forall>i :: nat \\<Rightarrow> Set. ( \\<langle>\\<dots>,i(n + k)\\<rangle> \\<in> Z \\<longleftrightarrow> \\<langle>\\<dots>,i(n)\\<rangle> \\<in> X)\"\nproof (induction k, simp_all, blast)\n  fix k::nat \n  assume IH:  \"\\<forall>X. \\<exists>Z. \\<forall>i. (\\<langle>\\<dots>, i(n + k)\\<rangle>) \\<in> Z \\<longleftrightarrow> \\<langle>\\<dots>, i(n)\\<rangle> \\<in> X\"\n  show \"\\<forall>X. \\<exists>Z. \\<forall>i. \\<langle>\\<dots>, i(n + k), i(Suc (n + k))\\<rangle> \\<in> Z \\<longleftrightarrow> \\<langle>\\<dots>, i(n)\\<rangle> \\<in> X\"\n  proof (rule allI)\n    fix X::Class\n    obtain C where C_def: \"\\<forall>i. \\<langle>\\<dots>, i(n + k)\\<rangle> \\<in> C \\<longleftrightarrow> \\<langle>\\<dots>, i(n)\\<rangle> \\<in> X\" using IH by blast\n    obtain D where \"\\<forall>v. \\<forall>i. \\<langle>\\<dots>, i(n + k), v\\<rangle> \\<in> D \\<longleftrightarrow> \\<langle>\\<dots>, i(n + k)\\<rangle> \\<in> C\"\n      using Ex_4_11_c by blast\n    hence \"\\<forall>i. \\<langle>\\<dots>, i(Suc (n + k))\\<rangle> \\<in> D \\<longleftrightarrow> \\<langle>\\<dots>, i(n + k)\\<rangle> \\<in> C\" using Tuple_All by simp\n    thus \"\\<exists>Z. \\<forall>i. \\<langle>\\<dots>, i(n + k), i(Suc (n + k))\\<rangle> \\<in> Z \\<longleftrightarrow> \\<langle>\\<dots>, i(n)\\<rangle> \\<in> X\" \n      using C_def by auto\n  qed\nqed\n\nlemma Ex4_11_e: \"\\<forall>X. \\<exists>Z. \\<forall>x::nat\\<Rightarrow>Set. \\<forall>xn::Set. (\\<langle>\\<dots>, x(k + m), xn\\<rangle> \\<in> Z \\<longleftrightarrow> \\<langle>\\<dots>, x(k), xn\\<rangle> \\<in> X)\"\nproof (induct m)\n  show \"\\<forall>X. \\<exists>Z. \\<forall>x xn. \\<langle>\\<dots>,x(k + 0), xn\\<rangle> \\<in> Z \\<longleftrightarrow> \\<langle>\\<dots>,x(k), xn\\<rangle> \\<in> X\" by auto\n  fix m \n  assume \"\\<forall>X. \\<exists>Z. \\<forall>x::nat\\<Rightarrow>Set. \\<forall>xn::Set. \\<langle>\\<dots>, x(k + m), xn\\<rangle> \\<in> Z \\<longleftrightarrow> \\<langle>\\<dots>, x(k), xn\\<rangle> \\<in> X\"\n  thus \"\\<forall>X. \\<exists>Z. \\<forall>x::nat\\<Rightarrow>Set. \\<forall>xn::Set. \\<langle>\\<dots>, x(k + Suc m), xn\\<rangle> \\<in> Z \\<longleftrightarrow> \\<langle>\\<dots>, x(k), xn\\<rangle> \\<in> X\" \n  proof -\n    fix m::nat\n    assume IA: \"\\<forall>X. \\<exists>Z. \\<forall>x::nat\\<Rightarrow>Set. \\<forall>xn::Set. \\<langle>\\<dots>, x(k + m), xn\\<rangle> \\<in> Z \\<longleftrightarrow> \\<langle>\\<dots>, x(k), xn\\<rangle> \\<in> X\"\n    show \"\\<forall>X. \\<exists>Z. \\<forall>x::nat\\<Rightarrow>Set. \\<forall>xn::Set. \\<langle>\\<dots>, x(k + Suc m), xn\\<rangle> \\<in> Z  \\<longleftrightarrow> \\<langle>\\<dots>, x(k), xn\\<rangle> \\<in> X\"\n    proof \n      fix X\n      have \"\\<exists>Z. \\<forall>x::nat\\<Rightarrow>Set. \\<forall>xn::Set. \\<forall>v. (\\<langle>\\<dots>, x(k+m), v, xn\\<rangle> \\<in> Z \\<longleftrightarrow> \\<langle>\\<dots>, x(k+m), xn\\<rangle> \\<in> X)\" \n        using Ex_4_11_b by blast\n      then obtain Z1 where \"\\<forall>x. \\<forall>xn. \\<forall>v.   (\\<langle>\\<dots>, x(k+m), v, xn\\<rangle> \\<in> Z1 \\<longleftrightarrow> \\<langle>\\<dots>, x(k+m), xn\\<rangle> \\<in> X)\" \n        by blast\n      from IA have \"\\<exists>Z. \\<forall>x::nat\\<Rightarrow>Set. \\<forall>xn::Set. \\<langle>\\<dots>, x(k+m), xn\\<rangle> \\<in> Z \\<longleftrightarrow> \\<langle>\\<dots>, x(k),xn\\<rangle> \\<in> X\"\n        by blast\n      then obtain Z2 where z2: \"\\<forall>x::nat\\<Rightarrow>Set. \\<forall>xn::Set. \\<langle>\\<dots>, x(k+m), xn\\<rangle> \\<in> Z2 \\<longleftrightarrow> \\<langle>\\<dots>, x(k), xn\\<rangle> \\<in> X\" \n        by blast\n      have \"\\<exists>Z. \\<forall>x::nat\\<Rightarrow>Set. \\<forall>xn::Set. \\<forall>v. (\\<langle>\\<dots>, x(k+m), v, xn\\<rangle> \\<in> Z \\<longleftrightarrow> \\<langle>\\<dots>, x(k+m), xn\\<rangle> \\<in> Z2)\" \n        using Ex_4_11_b by blast\n      hence *: \"\\<exists>Z. \\<forall>x::nat\\<Rightarrow>Set. \\<forall>xn::Set. \\<forall>v. (\\<langle>\\<dots>, x(k+m), v, xn\\<rangle> \\<in> Z \\<longleftrightarrow> \\<langle>\\<dots>, x(k), xn\\<rangle> \\<in> X)\" \n        using z2 by blast\n      then obtain Z where z_def: \"\\<forall>x::nat\\<Rightarrow>Set. \\<forall>xn::Set. \\<forall>v. \n        (\\<langle>\\<dots>, x(k+m), v, xn\\<rangle> \\<in> Z \\<longleftrightarrow> \\<langle>\\<dots>,x(k), xn\\<rangle> \\<in> X)\" by blast\n      have #: \"\\<forall>Z. \\<forall>xn::Set. \\<forall>x::nat\\<Rightarrow>Set. \\<exists>v. \n        (\\<langle>\\<dots>, x(k + Suc m), xn\\<rangle> \\<in> Z \\<longleftrightarrow> \\<langle>\\<dots>, x(k+m), v, xn\\<rangle> \\<in> Z)\" by auto\n      then have \"\\<forall>xn::Set. \\<forall>x::nat\\<Rightarrow>Set. (\\<langle>\\<dots>, x(k + Suc m), xn\\<rangle> \\<in> Z \\<longleftrightarrow> \\<langle>\\<dots>, x(k), xn\\<rangle> \\<in> X)\"\n        using z_def by blast\n      then show \"\\<exists>Z. \\<forall>x::nat\\<Rightarrow>Set. \\<forall>xn::Set. \\<langle>\\<dots>, x(k + Suc m), xn\\<rangle> \\<in> Z \\<longleftrightarrow> \\<langle>\\<dots>, x(k), xn\\<rangle> \\<in> X\"\n        by auto\n    qed\n  qed\nqed\n\nlemma Ex_4_11_f: \"\\<forall>X. \\<exists>Z. \\<forall>x. \\<forall>v :: nat \\<Rightarrow> Set. \\<langle>\\<dots>, v(m), x\\<rangle> \\<in> Z \\<longleftrightarrow> x \\<in> X\"\nproof\n  fix X\n  obtain C where \"\\<forall>u x. \\<langle>x, u\\<rangle> \\<in> C \\<longleftrightarrow> x \\<in> X\" using B5 by blast\n  then obtain D where \"\\<forall>u x. \\<langle>u, x\\<rangle> \\<in> D \\<longleftrightarrow> x \\<in> X\" using Ex_4_11_a by fast\n  then show \"\\<exists>Z. \\<forall>x. \\<forall>v :: nat \\<Rightarrow> Set. \\<langle>\\<dots>, v(m), x\\<rangle> \\<in> Z \\<longleftrightarrow> x \\<in> X\" by blast\nqed\n\n\nlemma Ex4_11_g: \"\\<forall>X. \\<exists>Z. \\<forall>x::nat\\<Rightarrow>Set. \\<langle>\\<dots>, x(n)\\<rangle> \\<in> Z \\<longleftrightarrow> (\\<exists>y::Set. \\<langle>\\<dots>, x(n), y\\<rangle> \\<in> X)\"\nusing B4 by blast\n\n\ntext{* \\textbf{FOMUS workshop extra exercise:} *}\n\nlemma Ex4_11_h: \"\\<forall>X. \\<exists>Z. \\<forall>u v w::Set. (\\<langle>v, u, w\\<rangle> \\<in> Z \\<longleftrightarrow> \\<langle>u, w\\<rangle> \\<in> X)\"\nsorry\n\nlemma Ex4_11_i: \"\\<forall>X. \\<exists>Z. \\<forall>v::nat\\<Rightarrow>Set. \\<forall>u w::Set. \\<langle>\\<dots>, v(n), u, w\\<rangle> \\<in> Z \\<longleftrightarrow> \\<langle>u, w\\<rangle> \\<in> X\"\nusing Ex4_11_h by blast\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/axioms_class_existence.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8479677545357568, "lm_q2_score": 0.8333245953120233, "lm_q1q2_score": 0.7066323858861546}}
{"text": "(*  Title:      HOL/Statespace/DistinctTreeProver.thy\n    Author:     Norbert Schirmer, TU Muenchen\n*)\n\nsection \\<open>Distinctness of Names in a Binary Tree \\label{sec:DistinctTreeProver}\\<close>\n\ntheory DistinctTreeProver \nimports MainRLT\nbegin\n\ntext \\<open>A state space manages a set of (abstract) names and assumes\nthat the names are distinct. The names are stored as parameters of a\nlocale and distinctness as an assumption. The most common request is\nto proof distinctness of two given names. We maintain the names in a\nbalanced binary tree and formulate a predicate that all nodes in the\ntree have distinct names. This setup leads to logarithmic certificates.\n\\<close>\n\nsubsection \\<open>The Binary Tree\\<close>\n\ndatatype 'a tree = Node \"'a tree\" 'a bool \"'a tree\" | Tip\n\n\ntext \\<open>The boolean flag in the node marks the content of the node as\ndeleted, without having to build a new tree. We prefer the boolean\nflag to an option type, so that the ML-layer can still use the node\ncontent to facilitate binary search in the tree. The ML code keeps the\nnodes sorted using the term order. We do not have to push ordering to\nthe HOL level.\\<close>\n\nsubsection \\<open>Distinctness of Nodes\\<close>\n\n\nprimrec set_of :: \"'a tree \\<Rightarrow> 'a set\"\nwhere\n  \"set_of Tip = {}\"\n| \"set_of (Node l x d r) = (if d then {} else {x}) \\<union> set_of l \\<union> set_of r\"\n\nprimrec all_distinct :: \"'a tree \\<Rightarrow> bool\"\nwhere\n  \"all_distinct Tip = True\"\n| \"all_distinct (Node l x d r) =\n    ((d \\<or> (x \\<notin> set_of l \\<and> x \\<notin> set_of r)) \\<and> \n      set_of l \\<inter> set_of r = {} \\<and>\n      all_distinct l \\<and> all_distinct r)\"\n\ntext \\<open>Given a binary tree \\<^term>\\<open>t\\<close> for which \n\\<^const>\\<open>all_distinct\\<close> holds, given two different nodes contained in the tree,\nwe want to write a ML function that generates a logarithmic\ncertificate that the content of the nodes is distinct. We use the\nfollowing lemmas to achieve this.\\<close> \n\nlemma all_distinct_left: \"all_distinct (Node l x b r) \\<Longrightarrow> all_distinct l\"\n  by simp\n\nlemma all_distinct_right: \"all_distinct (Node l x b r) \\<Longrightarrow> all_distinct r\"\n  by simp\n\nlemma distinct_left: \"all_distinct (Node l x False r) \\<Longrightarrow> y \\<in> set_of l \\<Longrightarrow> x \\<noteq> y\"\n  by auto\n\nlemma distinct_right: \"all_distinct (Node l x False r) \\<Longrightarrow> y \\<in> set_of r \\<Longrightarrow> x \\<noteq> y\"\n  by auto\n\nlemma distinct_left_right:\n    \"all_distinct (Node l z b r) \\<Longrightarrow> x \\<in> set_of l \\<Longrightarrow> y \\<in> set_of r \\<Longrightarrow> x \\<noteq> y\"\n  by auto\n\nlemma in_set_root: \"x \\<in> set_of (Node l x False r)\"\n  by simp\n\nlemma in_set_left: \"y \\<in> set_of l \\<Longrightarrow>  y \\<in> set_of (Node l x False r)\"\n  by simp\n\nlemma in_set_right: \"y \\<in> set_of r \\<Longrightarrow>  y \\<in> set_of (Node l x False r)\"\n  by simp\n\nlemma swap_neq: \"x \\<noteq> y \\<Longrightarrow> y \\<noteq> x\"\n  by blast\n\nlemma neq_to_eq_False: \"x\\<noteq>y \\<Longrightarrow> (x=y)\\<equiv>False\"\n  by simp\n\nsubsection \\<open>Containment of Trees\\<close>\n\ntext \\<open>When deriving a state space from other ones, we create a new\nname tree which contains all the names of the parent state spaces and\nassume the predicate \\<^const>\\<open>all_distinct\\<close>. We then prove that the new\nlocale interprets all parent locales. Hence we have to show that the\nnew distinctness assumption on all names implies the distinctness\nassumptions of the parent locales. This proof is implemented in ML. We\ndo this efficiently by defining a kind of containment check of trees\nby ``subtraction''.  We subtract the parent tree from the new tree. If\nthis succeeds we know that \\<^const>\\<open>all_distinct\\<close> of the new tree\nimplies \\<^const>\\<open>all_distinct\\<close> of the parent tree.  The resulting\ncertificate is of the order \\<^term>\\<open>n * log(m)\\<close> where \\<^term>\\<open>n\\<close> is\nthe size of the (smaller) parent tree and \\<^term>\\<open>m\\<close> the size of the\n(bigger) new tree.\\<close>\n\n\nprimrec delete :: \"'a \\<Rightarrow> 'a tree \\<Rightarrow> 'a tree option\"\nwhere\n  \"delete x Tip = None\"\n| \"delete x (Node l y d r) = (case delete x l of\n                                Some l' \\<Rightarrow>\n                                 (case delete x r of \n                                    Some r' \\<Rightarrow> Some (Node l' y (d \\<or> (x=y)) r')\n                                  | None \\<Rightarrow> Some (Node l' y (d \\<or> (x=y)) r))\n                               | None \\<Rightarrow>\n                                  (case delete x r of \n                                     Some r' \\<Rightarrow> Some (Node l y (d \\<or> (x=y)) r')\n                                   | None \\<Rightarrow> if x=y \\<and> \\<not>d then Some (Node l y True r)\n                                             else None))\"\n\n\nlemma delete_Some_set_of: \"delete x t = Some t' \\<Longrightarrow> set_of t' \\<subseteq> set_of t\"\nproof (induct t arbitrary: t')\n  case Tip thus ?case by simp\nnext\n  case (Node l y d r)\n  have del: \"delete x (Node l y d r) = Some t'\" by fact\n  show ?case\n  proof (cases \"delete x l\")\n    case (Some l')\n    note x_l_Some = this\n    with Node.hyps\n    have l'_l: \"set_of l' \\<subseteq> set_of l\"\n      by simp\n    show ?thesis\n    proof (cases \"delete x r\")\n      case (Some r')\n      with Node.hyps\n      have \"set_of r' \\<subseteq> set_of r\"\n        by simp\n      with l'_l Some x_l_Some del\n      show ?thesis\n        by (auto split: if_split_asm)\n    next\n      case None\n      with l'_l Some x_l_Some del\n      show ?thesis\n        by (fastforce split: if_split_asm)\n    qed\n  next\n    case None\n    note x_l_None = this\n    show ?thesis\n    proof (cases \"delete x r\")\n      case (Some r')\n      with Node.hyps\n      have \"set_of r' \\<subseteq> set_of r\"\n        by simp\n      with Some x_l_None del\n      show ?thesis\n        by (fastforce split: if_split_asm)\n    next\n      case None\n      with x_l_None del\n      show ?thesis\n        by (fastforce split: if_split_asm)\n    qed\n  qed\nqed\n\nlemma delete_Some_all_distinct:\n  \"delete x t = Some t' \\<Longrightarrow> all_distinct t \\<Longrightarrow> all_distinct t'\"\nproof (induct t arbitrary: t')\n  case Tip thus ?case by simp\nnext\n  case (Node l y d r)\n  have del: \"delete x (Node l y d r) = Some t'\" by fact\n  have \"all_distinct (Node l y d r)\" by fact\n  then obtain\n    dist_l: \"all_distinct l\" and\n    dist_r: \"all_distinct r\" and\n    d: \"d \\<or> (y \\<notin> set_of l \\<and> y \\<notin> set_of r)\" and\n    dist_l_r: \"set_of l \\<inter> set_of r = {}\"\n    by auto\n  show ?case\n  proof (cases \"delete x l\")\n    case (Some l')\n    note x_l_Some = this\n    from Node.hyps (1) [OF Some dist_l]\n    have dist_l': \"all_distinct l'\"\n      by simp\n    from delete_Some_set_of [OF x_l_Some]\n    have l'_l: \"set_of l' \\<subseteq> set_of l\".\n    show ?thesis\n    proof (cases \"delete x r\")\n      case (Some r')\n      from Node.hyps (2) [OF Some dist_r]\n      have dist_r': \"all_distinct r'\"\n        by simp\n      from delete_Some_set_of [OF Some]\n      have \"set_of r' \\<subseteq> set_of r\".\n      \n      with dist_l' dist_r' l'_l Some x_l_Some del d dist_l_r\n      show ?thesis\n        by fastforce\n    next\n      case None\n      with l'_l dist_l'  x_l_Some del d dist_l_r dist_r\n      show ?thesis\n        by fastforce\n    qed\n  next\n    case None\n    note x_l_None = this\n    show ?thesis\n    proof (cases \"delete x r\")\n      case (Some r')\n      with Node.hyps (2) [OF Some dist_r]\n      have dist_r': \"all_distinct r'\"\n        by simp\n      from delete_Some_set_of [OF Some]\n      have \"set_of r' \\<subseteq> set_of r\".\n      with Some dist_r' x_l_None del dist_l d dist_l_r\n      show ?thesis\n        by fastforce\n    next\n      case None\n      with x_l_None del dist_l dist_r d dist_l_r\n      show ?thesis\n        by (fastforce split: if_split_asm)\n    qed\n  qed\nqed\n\nlemma delete_None_set_of_conv: \"delete x t = None = (x \\<notin> set_of t)\"\nproof (induct t)\n  case Tip thus ?case by simp\nnext\n  case (Node l y d r)\n  thus ?case\n    by (auto split: option.splits)\nqed\n\nlemma delete_Some_x_set_of:\n  \"delete x t = Some t' \\<Longrightarrow> x \\<in> set_of t \\<and> x \\<notin> set_of t'\"\nproof (induct t arbitrary: t')\n  case Tip thus ?case by simp\nnext\n  case (Node l y d r)\n  have del: \"delete x (Node l y d r) = Some t'\" by fact\n  show ?case\n  proof (cases \"delete x l\")\n    case (Some l')\n    note x_l_Some = this\n    from Node.hyps (1) [OF Some]\n    obtain x_l: \"x \\<in> set_of l\" \"x \\<notin> set_of l'\"\n      by simp\n    show ?thesis\n    proof (cases \"delete x r\")\n      case (Some r')\n      from Node.hyps (2) [OF Some]\n      obtain x_r: \"x \\<in> set_of r\" \"x \\<notin> set_of r'\"\n        by simp\n      from x_r x_l Some x_l_Some del \n      show ?thesis\n        by (clarsimp split: if_split_asm)\n    next\n      case None\n      then have \"x \\<notin> set_of r\"\n        by (simp add: delete_None_set_of_conv)\n      with x_l None x_l_Some del\n      show ?thesis\n        by (clarsimp split: if_split_asm)\n    qed\n  next\n    case None\n    note x_l_None = this\n    then have x_notin_l: \"x \\<notin> set_of l\"\n      by (simp add: delete_None_set_of_conv)\n    show ?thesis\n    proof (cases \"delete x r\")\n      case (Some r')\n      from Node.hyps (2) [OF Some]\n      obtain x_r: \"x \\<in> set_of r\" \"x \\<notin> set_of r'\"\n        by simp\n      from x_r x_notin_l Some x_l_None del \n      show ?thesis\n        by (clarsimp split: if_split_asm)\n    next\n      case None\n      then have \"x \\<notin> set_of r\"\n        by (simp add: delete_None_set_of_conv)\n      with None x_l_None x_notin_l del\n      show ?thesis\n        by (clarsimp split: if_split_asm)\n    qed\n  qed\nqed\n\n\nprimrec subtract :: \"'a tree \\<Rightarrow> 'a tree \\<Rightarrow> 'a tree option\"\nwhere\n  \"subtract Tip t = Some t\"\n| \"subtract (Node l x b r) t =\n     (case delete x t of\n        Some t' \\<Rightarrow> (case subtract l t' of \n                     Some t'' \\<Rightarrow> subtract r t''\n                    | None \\<Rightarrow> None)\n       | None \\<Rightarrow> None)\"\n\nlemma subtract_Some_set_of_res: \n  \"subtract t\\<^sub>1 t\\<^sub>2 = Some t \\<Longrightarrow> set_of t \\<subseteq> set_of t\\<^sub>2\"\nproof (induct t\\<^sub>1 arbitrary: t\\<^sub>2 t)\n  case Tip thus ?case by simp\nnext\n  case (Node l x b r)\n  have sub: \"subtract (Node l x b r) t\\<^sub>2 = Some t\" by fact\n  show ?case\n  proof (cases \"delete x t\\<^sub>2\")\n    case (Some t\\<^sub>2')\n    note del_x_Some = this\n    from delete_Some_set_of [OF Some] \n    have t2'_t2: \"set_of t\\<^sub>2' \\<subseteq> set_of t\\<^sub>2\" .\n    show ?thesis\n    proof (cases \"subtract l t\\<^sub>2'\")\n      case (Some t\\<^sub>2'')\n      note sub_l_Some = this\n      from Node.hyps (1) [OF Some] \n      have t2''_t2': \"set_of t\\<^sub>2'' \\<subseteq> set_of t\\<^sub>2'\" .\n      show ?thesis\n      proof (cases \"subtract r t\\<^sub>2''\")\n        case (Some t\\<^sub>2''')\n        from Node.hyps (2) [OF Some ] \n        have \"set_of t\\<^sub>2''' \\<subseteq> set_of t\\<^sub>2''\" .\n        with Some sub_l_Some del_x_Some sub t2''_t2' t2'_t2\n        show ?thesis\n          by simp\n      next\n        case None\n        with del_x_Some sub_l_Some sub\n        show ?thesis\n          by simp\n      qed\n    next\n      case None\n      with del_x_Some sub \n      show ?thesis\n        by simp\n    qed\n  next\n    case None\n    with sub show ?thesis by simp\n  qed\nqed\n\nlemma subtract_Some_set_of: \n  \"subtract t\\<^sub>1 t\\<^sub>2 = Some t \\<Longrightarrow> set_of t\\<^sub>1 \\<subseteq> set_of t\\<^sub>2\"\nproof (induct t\\<^sub>1 arbitrary: t\\<^sub>2 t)\n  case Tip thus ?case by simp\nnext\n  case (Node l x d r)\n  have sub: \"subtract (Node l x d r) t\\<^sub>2 = Some t\" by fact\n  show ?case\n  proof (cases \"delete x t\\<^sub>2\")\n    case (Some t\\<^sub>2')\n    note del_x_Some = this\n    from delete_Some_set_of [OF Some] \n    have t2'_t2: \"set_of t\\<^sub>2' \\<subseteq> set_of t\\<^sub>2\" .\n    from delete_None_set_of_conv [of x t\\<^sub>2] Some\n    have x_t2: \"x \\<in> set_of t\\<^sub>2\"\n      by simp\n    show ?thesis\n    proof (cases \"subtract l t\\<^sub>2'\")\n      case (Some t\\<^sub>2'')\n      note sub_l_Some = this\n      from Node.hyps (1) [OF Some] \n      have l_t2': \"set_of l \\<subseteq> set_of t\\<^sub>2'\" .\n      from subtract_Some_set_of_res [OF Some]\n      have t2''_t2': \"set_of t\\<^sub>2'' \\<subseteq> set_of t\\<^sub>2'\" .\n      show ?thesis\n      proof (cases \"subtract r t\\<^sub>2''\")\n        case (Some t\\<^sub>2''')\n        from Node.hyps (2) [OF Some ] \n        have r_t\\<^sub>2'': \"set_of r \\<subseteq> set_of t\\<^sub>2''\" .\n        from Some sub_l_Some del_x_Some sub r_t\\<^sub>2'' l_t2' t2'_t2 t2''_t2' x_t2\n        show ?thesis\n          by auto\n      next\n        case None\n        with del_x_Some sub_l_Some sub\n        show ?thesis\n          by simp\n      qed\n    next\n      case None\n      with del_x_Some sub \n      show ?thesis\n        by simp\n    qed\n  next\n    case None\n    with sub show ?thesis by simp\n  qed\nqed\n\nlemma subtract_Some_all_distinct_res: \n  \"subtract t\\<^sub>1 t\\<^sub>2 = Some t \\<Longrightarrow> all_distinct t\\<^sub>2 \\<Longrightarrow> all_distinct t\"\nproof (induct t\\<^sub>1 arbitrary: t\\<^sub>2 t)\n  case Tip thus ?case by simp\nnext\n  case (Node l x d r)\n  have sub: \"subtract (Node l x d r) t\\<^sub>2 = Some t\" by fact\n  have dist_t2: \"all_distinct t\\<^sub>2\" by fact\n  show ?case\n  proof (cases \"delete x t\\<^sub>2\")\n    case (Some t\\<^sub>2')\n    note del_x_Some = this\n    from delete_Some_all_distinct [OF Some dist_t2] \n    have dist_t2': \"all_distinct t\\<^sub>2'\" .\n    show ?thesis\n    proof (cases \"subtract l t\\<^sub>2'\")\n      case (Some t\\<^sub>2'')\n      note sub_l_Some = this\n      from Node.hyps (1) [OF Some dist_t2'] \n      have dist_t2'': \"all_distinct t\\<^sub>2''\" .\n      show ?thesis\n      proof (cases \"subtract r t\\<^sub>2''\")\n        case (Some t\\<^sub>2''')\n        from Node.hyps (2) [OF Some dist_t2''] \n        have dist_t2''': \"all_distinct t\\<^sub>2'''\" .\n        from Some sub_l_Some del_x_Some sub \n             dist_t2'''\n        show ?thesis\n          by simp\n      next\n        case None\n        with del_x_Some sub_l_Some sub\n        show ?thesis\n          by simp\n      qed\n    next\n      case None\n      with del_x_Some sub \n      show ?thesis\n        by simp\n    qed\n  next\n    case None\n    with sub show ?thesis by simp\n  qed\nqed\n\n\nlemma subtract_Some_dist_res: \n  \"subtract t\\<^sub>1 t\\<^sub>2 = Some t \\<Longrightarrow> set_of t\\<^sub>1 \\<inter> set_of t = {}\"\nproof (induct t\\<^sub>1 arbitrary: t\\<^sub>2 t)\n  case Tip thus ?case by simp\nnext\n  case (Node l x d r)\n  have sub: \"subtract (Node l x d r) t\\<^sub>2 = Some t\" by fact\n  show ?case\n  proof (cases \"delete x t\\<^sub>2\")\n    case (Some t\\<^sub>2')\n    note del_x_Some = this\n    from delete_Some_x_set_of [OF Some]\n    obtain x_t2: \"x \\<in> set_of t\\<^sub>2\" and x_not_t2': \"x \\<notin> set_of t\\<^sub>2'\"\n      by simp\n    from delete_Some_set_of [OF Some]\n    have t2'_t2: \"set_of t\\<^sub>2' \\<subseteq> set_of t\\<^sub>2\" .\n    show ?thesis\n    proof (cases \"subtract l t\\<^sub>2'\")\n      case (Some t\\<^sub>2'')\n      note sub_l_Some = this\n      from Node.hyps (1) [OF Some ] \n      have dist_l_t2'': \"set_of l \\<inter> set_of t\\<^sub>2'' = {}\".\n      from subtract_Some_set_of_res [OF Some]\n      have t2''_t2': \"set_of t\\<^sub>2'' \\<subseteq> set_of t\\<^sub>2'\" .\n      show ?thesis\n      proof (cases \"subtract r t\\<^sub>2''\")\n        case (Some t\\<^sub>2''')\n        from Node.hyps (2) [OF Some] \n        have dist_r_t2''': \"set_of r \\<inter> set_of t\\<^sub>2''' = {}\" .\n        from subtract_Some_set_of_res [OF Some]\n        have t2'''_t2'': \"set_of t\\<^sub>2''' \\<subseteq> set_of t\\<^sub>2''\".\n        \n        from Some sub_l_Some del_x_Some sub t2'''_t2'' dist_l_t2'' dist_r_t2'''\n             t2''_t2' t2'_t2 x_not_t2'\n        show ?thesis\n          by auto\n      next\n        case None\n        with del_x_Some sub_l_Some sub\n        show ?thesis\n          by simp\n      qed\n    next\n      case None\n      with del_x_Some sub \n      show ?thesis\n        by simp\n    qed\n  next\n    case None\n    with sub show ?thesis by simp\n  qed\nqed\n        \nlemma subtract_Some_all_distinct:\n  \"subtract t\\<^sub>1 t\\<^sub>2 = Some t \\<Longrightarrow> all_distinct t\\<^sub>2 \\<Longrightarrow> all_distinct t\\<^sub>1\"\nproof (induct t\\<^sub>1 arbitrary: t\\<^sub>2 t)\n  case Tip thus ?case by simp\nnext\n  case (Node l x d r)\n  have sub: \"subtract (Node l x d r) t\\<^sub>2 = Some t\" by fact\n  have dist_t2: \"all_distinct t\\<^sub>2\" by fact\n  show ?case\n  proof (cases \"delete x t\\<^sub>2\")\n    case (Some t\\<^sub>2')\n    note del_x_Some = this\n    from delete_Some_all_distinct [OF Some dist_t2 ] \n    have dist_t2': \"all_distinct t\\<^sub>2'\" .\n    from delete_Some_set_of [OF Some]\n    have t2'_t2: \"set_of t\\<^sub>2' \\<subseteq> set_of t\\<^sub>2\" .\n    from delete_Some_x_set_of [OF Some]\n    obtain x_t2: \"x \\<in> set_of t\\<^sub>2\" and x_not_t2': \"x \\<notin> set_of t\\<^sub>2'\"\n      by simp\n\n    show ?thesis\n    proof (cases \"subtract l t\\<^sub>2'\")\n      case (Some t\\<^sub>2'')\n      note sub_l_Some = this\n      from Node.hyps (1) [OF Some dist_t2' ] \n      have dist_l: \"all_distinct l\" .\n      from subtract_Some_all_distinct_res [OF Some dist_t2'] \n      have dist_t2'': \"all_distinct t\\<^sub>2''\" .\n      from subtract_Some_set_of [OF Some]\n      have l_t2': \"set_of l \\<subseteq> set_of t\\<^sub>2'\" .\n      from subtract_Some_set_of_res [OF Some]\n      have t2''_t2': \"set_of t\\<^sub>2'' \\<subseteq> set_of t\\<^sub>2'\" .\n      from subtract_Some_dist_res [OF Some]\n      have dist_l_t2'': \"set_of l \\<inter> set_of t\\<^sub>2'' = {}\".\n      show ?thesis\n      proof (cases \"subtract r t\\<^sub>2''\")\n        case (Some t\\<^sub>2''')\n        from Node.hyps (2) [OF Some dist_t2''] \n        have dist_r: \"all_distinct r\" .\n        from subtract_Some_set_of [OF Some]\n        have r_t2'': \"set_of r \\<subseteq> set_of t\\<^sub>2''\" .\n        from subtract_Some_dist_res [OF Some]\n        have dist_r_t2''': \"set_of r \\<inter> set_of t\\<^sub>2''' = {}\".\n\n        from dist_l dist_r Some sub_l_Some del_x_Some r_t2'' l_t2' x_t2 x_not_t2' \n             t2''_t2' dist_l_t2'' dist_r_t2'''\n        show ?thesis\n          by auto\n      next\n        case None\n        with del_x_Some sub_l_Some sub\n        show ?thesis\n          by simp\n      qed\n    next\n      case None\n      with del_x_Some sub \n      show ?thesis\n        by simp\n    qed\n  next\n    case None\n    with sub show ?thesis by simp\n  qed\nqed\n\n\nlemma delete_left:\n  assumes dist: \"all_distinct (Node l y d r)\" \n  assumes del_l: \"delete x l = Some l'\"\n  shows \"delete x (Node l y d r) = Some (Node l' y d r)\"\nproof -\n  from delete_Some_x_set_of [OF del_l]\n  obtain x: \"x \\<in> set_of l\"\n    by simp\n  with dist \n  have \"delete x r = None\"\n    by (cases \"delete x r\") (auto dest:delete_Some_x_set_of)\n\n  with x \n  show ?thesis\n    using del_l dist\n    by (auto split: option.splits)\nqed\n\nlemma delete_right:\n  assumes dist: \"all_distinct (Node l y d r)\" \n  assumes del_r: \"delete x r = Some r'\"\n  shows \"delete x (Node l y d r) = Some (Node l y d r')\"\nproof -\n  from delete_Some_x_set_of [OF del_r]\n  obtain x: \"x \\<in> set_of r\"\n    by simp\n  with dist \n  have \"delete x l = None\"\n    by (cases \"delete x l\") (auto dest:delete_Some_x_set_of)\n\n  with x \n  show ?thesis\n    using del_r dist\n    by (auto split: option.splits)\nqed\n\nlemma delete_root: \n  assumes dist: \"all_distinct (Node l x False r)\" \n  shows \"delete x (Node l x False r) = Some (Node l x True r)\"\nproof -\n  from dist have \"delete x r = None\"\n    by (cases \"delete x r\") (auto dest:delete_Some_x_set_of)\n  moreover\n  from dist have \"delete x l = None\"\n    by (cases \"delete x l\") (auto dest:delete_Some_x_set_of)\n  ultimately show ?thesis\n    using dist\n       by (auto split: option.splits)\nqed               \n\nlemma subtract_Node:\n assumes del: \"delete x t = Some t'\"                                \n assumes sub_l: \"subtract l t' = Some t''\"\n assumes sub_r: \"subtract r t'' = Some t'''\"\n shows \"subtract (Node l x False r) t = Some t'''\"\nusing del sub_l sub_r\nby simp\n\nlemma subtract_Tip: \"subtract Tip t = Some t\"\n  by simp\n \ntext \\<open>Now we have all the theorems in place that are needed for the\ncertificate generating ML functions.\\<close>\n\nML_file \\<open>distinct_tree_prover.ML\\<close>\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/Statespace/DistinctTreeProver.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8824278695464501, "lm_q2_score": 0.8006920092299293, "lm_q1q2_score": 0.7065529438676331}}
{"text": "(* \n  Author: Jeremy Dawson and Gerwin Klein, NICTA\n\n  Definitions and basic theorems for bit-wise logical operations \n  for integers expressed using Pls, Min, BIT,\n  and converting them to and from lists of bools.\n*) \n\nsection {* Bitwise Operations on Binary Integers *}\n\ntheory Bits_Int\nimports Bits Bit_Representation\nbegin\n\nsubsection {* Logical operations *}\n\ntext \"bit-wise logical operations on the int type\"\n\ninstantiation int :: bit\nbegin\n\ndefinition int_not_def:\n  \"bitNOT = (\\<lambda>x::int. - x - 1)\"\n\nfunction bitAND_int where\n  \"bitAND_int x y =\n    (if x = 0 then 0 else if x = -1 then y else\n      (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 o abs o fst)\", simp_all add: bin_rest_def)\n\ndeclare bitAND_int.simps [simp del]\n\ndefinition int_or_def:\n  \"bitOR = (\\<lambda>x y::int. NOT (NOT x AND NOT y))\"\n\ndefinition int_xor_def:\n  \"bitXOR = (\\<lambda>x y::int. (x AND NOT y) OR (NOT x AND y))\"\n\ninstance ..\n\nend\n\nsubsubsection {* Basic simplification rules *}\n\nlemma int_not_BIT [simp]:\n  \"NOT (w BIT b) = (NOT w) BIT (\\<not> b)\"\n  unfolding int_not_def Bit_def by (cases b, simp_all)\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::int)) = x\"\n  unfolding int_not_def by simp\n\nlemma int_and_0 [simp]: \"(0::int) AND x = 0\"\n  by (simp add: bitAND_int.simps)\n\nlemma int_and_m1 [simp]: \"(-1::int) AND x = x\"\n  by (simp add: bitAND_int.simps)\n\nlemma int_and_Bits [simp]: \n  \"(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::int) OR x = x\"\n  unfolding int_or_def by simp\n\nlemma int_or_minus1 [simp]: \"(-1::int) OR x = -1\"\n  unfolding int_or_def by simp\n\nlemma int_or_Bits [simp]: \n  \"(x BIT b) OR (y BIT c) = (x OR y) BIT (b \\<or> c)\"\n  unfolding int_or_def by simp\n\nlemma int_xor_zero [simp]: \"(0::int) XOR x = x\"\n  unfolding int_xor_def by simp\n\nlemma int_xor_Bits [simp]: \n  \"(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\nsubsubsection {* Binary destructors *}\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]: \"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  \"!!x y. bin_nth (x AND y) n = (bin_nth x n & bin_nth y n)\" \n  \"!!x y. bin_nth (x OR y) n = (bin_nth x n | bin_nth y n)\"\n  \"!!x y. bin_nth (x XOR y) n = (bin_nth x n ~= bin_nth y n)\" \n  \"!!x. bin_nth (NOT x) n = (~ bin_nth x n)\"\n  by (induct n) auto\n\nsubsubsection {* Derived properties *}\n\nlemma int_xor_minus1 [simp]: \"(-1::int) XOR x = NOT x\"\n  by (auto simp add: bin_eq_iff bin_nth_ops)\n\nlemma int_xor_extra_simps [simp]:\n  \"w XOR (0::int) = w\"\n  \"w XOR (-1::int) = NOT w\"\n  by (auto simp add: bin_eq_iff bin_nth_ops)\n\nlemma int_or_extra_simps [simp]:\n  \"w OR (0::int) = w\"\n  \"w OR (-1::int) = -1\"\n  by (auto simp add: bin_eq_iff bin_nth_ops)\n\nlemma int_and_extra_simps [simp]:\n  \"w AND (0::int) = 0\"\n  \"w AND (-1::int) = w\"\n  by (auto simp add: bin_eq_iff bin_nth_ops)\n\n(* commutativity of the above *)\nlemma bin_ops_comm:\n  shows\n  int_and_comm: \"!!y::int. x AND y = y AND x\" and\n  int_or_comm:  \"!!y::int. x OR y = y OR x\" and\n  int_xor_comm: \"!!y::int. 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::int) AND x = x\" \n  \"(x::int) OR x = x\" \n  \"(x::int) XOR x = 0\"\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(* basic properties of logical (bit-wise) operations *)\n\nlemma bbw_ao_absorb: \n  \"!!y::int. x AND (y OR x) = x & x OR (y AND x) = x\"\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::int)\"\n  \"(y OR x) AND x = x \\<and> x OR (x AND y) = (x::int)\"\n  \"(x OR y) AND x = x \\<and> (x AND y) OR x = (x::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:\n  \"!!y::int. (NOT x) XOR y = NOT (x XOR y) & \n        x XOR (NOT y) = NOT (x XOR y)\"\n  by (auto simp add: bin_eq_iff bin_nth_ops)\n\nlemma int_and_assoc:\n  \"(x AND y) AND (z::int) = x AND (y AND z)\"\n  by (auto simp add: bin_eq_iff bin_nth_ops)\n\nlemma int_or_assoc:\n  \"(x OR y) OR (z::int) = x OR (y OR z)\"\n  by (auto simp add: bin_eq_iff bin_nth_ops)\n\nlemma int_xor_assoc:\n  \"(x XOR y) XOR (z::int) = x XOR (y XOR z)\"\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::int) AND (x AND z) = x AND (y AND z)\"\n  \"(y::int) OR (x OR z) = x OR (y OR z)\"\n  \"(y::int) XOR (x XOR z) = x XOR (y XOR z)\" \n  by (auto simp add: bin_eq_iff bin_nth_ops)\n\nlemma bbw_not_dist: \n  \"!!y::int. NOT (x OR y) = (NOT x) AND (NOT y)\" \n  \"!!y::int. NOT (x AND y) = (NOT x) OR (NOT y)\"\n  by (auto simp add: bin_eq_iff bin_nth_ops)\n\nlemma bbw_oa_dist: \n  \"!!y z::int. (x AND y) OR z = \n          (x OR z) AND (y OR z)\"\n  by (auto simp add: bin_eq_iff bin_nth_ops)\n\nlemma bbw_ao_dist: \n  \"!!y z::int. (x OR y) AND z = \n          (x AND z) OR (y AND z)\"\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\nsubsubsection {* Simplification with numerals *}\n\ntext {* Cases for @{text \"0\"} and @{text \"-1\"} are already covered by\n  other simp rules. *}\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 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\ntext {* 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, 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, 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, simp)+\n\nsubsubsection {* Interactions with arithmetic *}\n\nlemma plus_and_or [rule_format]:\n  \"ALL 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:\n  \"bin_sign (y::int) = 0 ==> x <= x OR y\"\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\n(* interaction between bit-wise and arithmetic *)\n(* good example of bin_induction *)\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\nsubsubsection {* Truncating results of bit-wise operations *}\n\nlemma bin_trunc_ao: \n  \"!!x y. (bintrunc n x) AND (bintrunc n y) = bintrunc n (x AND y)\" \n  \"!!x y. (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: \n  \"!!x y. bintrunc n (bintrunc n x XOR bintrunc n y) = \n          bintrunc n (x XOR y)\"\n  by (auto simp add: bin_eq_iff bin_nth_ops nth_bintr)\n\nlemma bin_trunc_not: \n  \"!!x. bintrunc n (NOT (bintrunc n x)) = bintrunc n (NOT x)\"\n  by (auto simp add: bin_eq_iff bin_nth_ops nth_bintr)\n\n(* want theorems of the form of bin_trunc_xor *)\nlemma bintr_bintr_i:\n  \"x = bintrunc n y ==> 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\nsubsection {* Setting and clearing bits *}\n\n(** nth bit, set/clear **)\n\nprimrec\n  bin_sc :: \"nat => bool => int => int\"\nwhere\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]: \n  \"bin_nth (bin_sc n b w) n \\<longleftrightarrow> b\"\n  by (induct n arbitrary: w) auto\n\nlemma bin_sc_sc_same [simp]: \n  \"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:\n  \"m ~= n ==> \n    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: \n  \"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]:\n  \"(bin_sc n (bin_nth w n) w) = w\"\n  by (induct n arbitrary: w) auto\n\nlemma bin_sign_sc [simp]:\n  \"bin_sign (bin_sc n b w) = bin_sign w\"\n  by (induct n arbitrary: w) auto\n  \nlemma bin_sc_bintr [simp]: \n  \"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:\n  \"bin_sc n False w <= 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:\n  \"bin_sc n True w >= 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:\n  \"bintrunc n (bin_sc m False w) <= 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:\n  \"bintrunc n (bin_sc m True w) >= 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:\n  \"0 < n ==> 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\n\nsubsection {* Splitting and concatenation *}\n\ndefinition bin_rcat :: \"nat \\<Rightarrow> int list \\<Rightarrow> int\"\nwhere\n  \"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\"\nwhere\n  \"bin_rsplit_aux n m c bs =\n    (if m = 0 | n = 0 then bs 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\"\nwhere\n  \"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\"\nwhere\n  \"bin_rsplitl_aux n m c bs =\n    (if m = 0 | n = 0 then bs 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\"\nwhere\n  \"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_sign_cat: \n  \"bin_sign (bin_cat x n y) = bin_sign x\"\n  by (induct n arbitrary: y) auto\n\nlemma bin_cat_Suc_Bit:\n  \"bin_cat w (Suc n) (v BIT b) = bin_cat w n v BIT b\"\n  by auto\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) ==> \n    (ALL k. bin_nth a k = bin_nth c (n + k)) & \n    (ALL k. bin_nth b k = (k < n & 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_assoc: \n  \"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:\n  \"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, clarsimp)\n  apply (case_tac m, 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: \n  \"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]: \n  \"bintrunc n (bin_cat a n b) = bintrunc n b\"\n  by (auto simp add : bintr_cat)\n\nlemma cat_bintr [simp]: \n  \"bin_cat a n (bintrunc n b) = bin_cat a n b\"\n  by (induct n arbitrary: b) auto\n\nlemma split_bintrunc: \n  \"bin_split n c = (a, b) ==> b = bintrunc n c\"\n  by (induct n arbitrary: b c) (auto simp: Let_def split: prod.split_asm)\n\nlemma bin_cat_split:\n  \"bin_split n w = (u, v) ==> 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:\n  \"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) ==> \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) ==> \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:\n  \"bin_cat a n b = a * 2 ^ n + bintrunc n b\"\n  apply (induct n arbitrary: b, clarsimp)\n  apply (simp add: Bit_def)\n  done\n\nlemma bin_split_num:\n  \"bin_split n b = (b div 2 ^ n, b mod 2 ^ n)\"\n  apply (induct n arbitrary: b, 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 p1mod22k)\n  done\n\nsubsection {* Miscellaneous lemmas *}\n\nlemma nth_2p_bin: \n  \"bin_nth (2 ^ n) m = (m = n)\"\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\n(* for use when simplifying with bin_nth_Bit *)\n\nlemma ex_eq_or:\n  \"(EX m. n = Suc m & (m = k | P m)) = (n = Suc k | (EX m. n = Suc m & P m))\"\n  by auto\n\nlemma power_BIT: \"2 ^ (Suc n) - 1 = (2 ^ n - 1) BIT True\"\n  unfolding Bit_B1\n  by (induct n) simp_all\n\nlemma mod_BIT:\n  \"bin BIT bit mod 2 ^ Suc n = (bin mod 2 ^ n) BIT bit\"\nproof -\n  have \"bin mod 2 ^ n < 2 ^ n\" by simp\n  then have \"bin mod 2 ^ n \\<le> 2 ^ n - 1\" by simp\n  then have \"2 * (bin mod 2 ^ n) \\<le> 2 * (2 ^ n - 1)\"\n    by (rule mult_left_mono) simp\n  then have \"2 * (bin mod 2 ^ n) + 1 < 2 * 2 ^ n\" by simp\n  then show ?thesis\n    by (auto simp add: Bit_def mod_mult_mult1 mod_add_left_eq [of \"2 * bin\"]\n      mod_pos_pos_trivial)\nqed\n\nlemma AND_mod:\n  fixes x :: int\n  shows \"x AND 2 ^ n - 1 = x mod 2 ^ n\"\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\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/Word/Bits_Int.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8824278695464501, "lm_q2_score": 0.8006920092299292, "lm_q1q2_score": 0.706552943867633}}
{"text": "theory \"Set-Cpo\"\nimports HOLCF\nbegin\n\ndefault_sort type\n\ninstantiation set :: (type) below\nbegin\n  definition below_set where \"(\\<sqsubseteq>) = (\\<subseteq>)\"\ninstance..  \nend\n\ninstance set :: (type) po\n  by standard (auto simp add: below_set_def)\n\nlemma is_lub_set:\n  \"S <<| \\<Union>S\"\n  by(auto simp add: is_lub_def below_set_def is_ub_def)\n\nlemma lub_set: \"lub S = \\<Union>S\"\n  by (metis is_lub_set lub_eqI)\n  \ninstance set  :: (type) cpo\n  by standard (rule exI, rule is_lub_set)\n\nlemma minimal_set: \"{} \\<sqsubseteq> S\"\n  unfolding below_set_def by simp\n\ninstance set  :: (type) pcpo\n  by standard (rule+, rule minimal_set)\n\nlemma set_contI:\n  assumes  \"\\<And> Y. chain Y \\<Longrightarrow> f (\\<Squnion> i. Y i) = \\<Union> (f ` range Y)\"\n  shows \"cont f\"\nproof(rule contI)\n  fix Y :: \"nat \\<Rightarrow> 'a\"\n  assume \"chain Y\"\n  hence \"f (\\<Squnion> i. Y i) = \\<Union> (f ` range Y)\" by (rule assms)\n  also have \"\\<dots> = \\<Union> (range (\\<lambda>i. f (Y i)))\" by simp\n  finally\n  show \"range (\\<lambda>i. f (Y i)) <<| f (\\<Squnion> i. Y i)\" using is_lub_set by metis\nqed\n\nlemma set_set_contI:\n  assumes  \"\\<And> S. f (\\<Union>S) = \\<Union> (f ` S)\"\n  shows \"cont f\"\n  by (metis set_contI assms is_lub_set  lub_eqI)\n\nlemma adm_subseteq[simp]:\n  assumes \"cont f\"\n  shows \"adm (\\<lambda>a. f a \\<subseteq> S)\"\nby (rule admI)(auto simp add: cont2contlubE[OF assms] lub_set)\n\nlemma adm_Ball[simp]: \"adm (\\<lambda>S. \\<forall>x\\<in>S. P x)\"\n  by (auto intro!: admI  simp add: lub_set)\n\nlemma finite_subset_chain:\n  fixes Y :: \"nat \\<Rightarrow> 'a set\"\n  assumes \"chain Y\"\n  assumes \"S \\<subseteq> \\<Union>(Y ` UNIV)\"\n  assumes \"finite S\"\n  shows \"\\<exists>i. S \\<subseteq> Y i\"\nproof-\n  from assms(2)\n  have \"\\<forall>x \\<in> S. \\<exists> i. x \\<in> Y i\" by auto\n  then obtain f where f: \"\\<forall> x\\<in> S. x \\<in> Y (f x)\" by metis\n\n  define i where \"i = Max (f ` S)\"\n  from \\<open>finite S\\<close>\n  have \"finite (f ` S)\" by simp\n  hence \"\\<forall> x\\<in>S. f x \\<le> i\" unfolding i_def by auto\n  with chain_mono[OF \\<open>chain Y\\<close>]\n  have \"\\<forall> x\\<in>S. Y (f x) \\<subseteq> Y i\" by (auto simp add: below_set_def)\n  with f\n  have \"S \\<subseteq> Y i\" by auto\n  thus ?thesis..\nqed\n\nlemma diff_cont[THEN cont_compose, simp, cont2cont]:\n  fixes S' :: \"'a set\"\n  shows  \"cont (\\<lambda>S. S - S')\"\nby (rule set_set_contI) simp\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/Set-Cpo.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.882427872638409, "lm_q2_score": 0.8006920020959544, "lm_q1q2_score": 0.7065529400481215}}
{"text": "theory OFEs\nimports BasicTypes \"HOL-Library.Finite_Map\"\nbegin\n\nsection \\<open> Ordered family of equivalences \\<close>\ntext \\<open> The definition of the class of OFEs and some instances. \\<close>\n\nsection \\<open> OFE \\<close>\nclass ofe =\n  fixes n_equiv :: \"nat \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> bool\"\n    and ofe_eq :: \"'a \\<Rightarrow> 'a \\<Rightarrow> bool\" (* Allow for custom equality *)\n  assumes ofe_refl: \"n_equiv n x x\"\n    and ofe_sym: \"n_equiv n x y \\<longleftrightarrow> n_equiv n y x\"\n    and ofe_trans: \"\\<lbrakk>n_equiv n x y; n_equiv n y z\\<rbrakk> \\<Longrightarrow> n_equiv n x z\"\n    and ofe_mono: \"\\<lbrakk>m\\<le>n; n_equiv n x y\\<rbrakk> \\<Longrightarrow> n_equiv m x y\"\n    and ofe_limit: \"(ofe_eq x y) \\<longleftrightarrow> (\\<forall>n. n_equiv n x y)\"\n    and ofe_eq_eq: \"(x=y) \\<Longrightarrow> ofe_eq x y\"\nbegin \nlemma  ofe_eq_limit: \"(x=y) \\<Longrightarrow> (\\<forall>n. n_equiv n x y)\"\n  using ofe_limit ofe_eq_eq by simp  \nend\n\nclass discrete = ofe + assumes d_equiv: \"n_equiv n a b = (a=b)\" and d_eq: \"ofe_eq a b = (a=b)\"\n\ndefinition discrete_val :: \"'a::ofe \\<Rightarrow> bool\" where\n  \"discrete_val v \\<equiv> (\\<forall>x n. n_equiv n v x \\<longleftrightarrow> (v=x)) \\<and> (\\<forall>y. ofe_eq v y \\<longleftrightarrow> (v=y))\"\n\nlemma discrete_discrete_val [simp]: \"discrete_val (x::'a::discrete)\" \n  by (simp add: discrete_val_def d_equiv d_eq)\n\nlemma ofe_down_contr: \"n_equiv n x y \\<longleftrightarrow> (\\<forall>m\\<le>n. n_equiv m x y)\"\n  by (auto simp: ofe_trans ofe_sym intro: ofe_mono)\n\nlemma ofe_trans_eqL: \"n_equiv n x y \\<Longrightarrow> n_equiv n x z \\<longleftrightarrow> n_equiv n y z\"\n  using ofe_sym ofe_trans by blast\n\nlemma ofe_trans_eqR: \"n_equiv n x y \\<Longrightarrow> n_equiv n z x \\<longleftrightarrow> n_equiv n z y\"\n  using ofe_sym ofe_trans by blast\n\nlemma ofe_trans': \"\\<lbrakk>ofe_eq x y; ofe_eq y z\\<rbrakk> \\<Longrightarrow> ofe_eq x z\"\n  by (auto simp: ofe_limit intro: ofe_trans)\n\nlemma ofe_eq_equiv: \"ofe_eq x y \\<Longrightarrow> n_equiv n x y\" by (simp add: ofe_limit)\n\nsubsection \\<open> Basic OFE instances \\<close>\nsubsubsection \\<open>unit OFE\\<close>\ninstantiation unit :: ofe begin\n  definition n_equiv_unit :: \"nat \\<Rightarrow> unit \\<Rightarrow> unit \\<Rightarrow> bool\" where\n    \"n_equiv_unit _ _ _ = True\"\n  fun ofe_eq_unit :: \"unit \\<Rightarrow> unit \\<Rightarrow> bool\" where \"ofe_eq_unit _ _ = True\"\ninstance by (standard, unfold n_equiv_unit_def) auto\nend\n\ninstance unit :: discrete by standard (auto simp: n_equiv_unit_def)\n\nsubsubsection \\<open>nat OFE\\<close>\ninstantiation nat :: ofe begin\n  definition n_equiv_nat :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> bool\" where [simp]: \"n_equiv_nat \\<equiv> \\<lambda>_. (=)\"\n  definition ofe_eq_nat :: \"nat \\<Rightarrow> nat \\<Rightarrow> bool\" where [simp]: \"ofe_eq_nat \\<equiv> (=)\"\ninstance by standard auto\nend\n\ninstance nat :: discrete by standard (auto)\n\nsubsubsection \\<open>bool OFE\\<close>\ninstantiation bool :: ofe begin\n  definition n_equiv_bool :: \"nat \\<Rightarrow> bool \\<Rightarrow> bool \\<Rightarrow> bool\" where [simp]: \"n_equiv_bool \\<equiv> \\<lambda>_. (=)\"\n  definition ofe_eq_bool :: \"bool \\<Rightarrow> bool \\<Rightarrow> bool\" where [simp]: \"ofe_eq_bool \\<equiv> (=)\"\ninstance by standard auto\nend\n\ninstance bool :: discrete by standard (auto)\n\nsubsubsection \\<open>Set type OFE\\<close>\ninstantiation set :: (type) ofe begin\ndefinition n_equiv_set :: \"nat \\<Rightarrow> 'a set \\<Rightarrow> 'a set \\<Rightarrow> bool\" where \"n_equiv_set _ \\<equiv> (=)\"\ndefinition ofe_eq_set :: \"'a set \\<Rightarrow> 'a set \\<Rightarrow> bool\" where \"ofe_eq_set \\<equiv> (=)\"\ninstance by (standard) (auto simp: n_equiv_set_def ofe_eq_set_def)\nend\n\ninstance set :: (type) discrete by standard (auto simp: n_equiv_set_def ofe_eq_set_def)\n\nsubsubsection \\<open>Disjoint set OFE\\<close>\ninstantiation dset :: (type) ofe begin\ndefinition n_equiv_dset :: \"nat \\<Rightarrow> 'a dset \\<Rightarrow> 'a dset \\<Rightarrow> bool\" where \"n_equiv_dset \\<equiv> \\<lambda>_. (=)\"\ndefinition ofe_eq_dset :: \"'a dset \\<Rightarrow> 'a dset \\<Rightarrow> bool\" where \"ofe_eq_dset \\<equiv> (=)\"\ninstance by standard (auto simp: n_equiv_dset_def ofe_eq_dset_def)\nend\n\ninstance dset :: (type) discrete by standard (auto simp: n_equiv_dset_def ofe_eq_dset_def)\n\nsubsubsection \\<open>option OFE\\<close>\ninstantiation option :: (ofe) ofe begin\n  definition n_equiv_option :: \"nat \\<Rightarrow> 'a option \\<Rightarrow> 'a option \\<Rightarrow> bool\" where\n  \"n_equiv_option n x y \\<equiv> (\\<exists>x' y'. x=Some x'\\<and>y=Some y'\\<and> n_equiv n x' y') \\<or> x=None\\<and>y=None\"\n  definition ofe_eq_option where\n    \"ofe_eq_option x y \\<equiv> (x=None\\<and>y=None)\\<or>(\\<exists>x' y'. x=Some x'\\<and>y=Some y'\\<and>(ofe_eq x' y'))\"\ninstance proof (standard)\n  fix x y\n  show \"(ofe_eq (x::'a option) y) \\<longleftrightarrow> (\\<forall>n. n_equiv n x y)\"\n  by (auto simp: n_equiv_option_def ofe_refl ofe_eq_option_def) (metis ofe_limit option.sel)+\nnext \n  fix x y n\n  show \"(n_equiv n (x::'a option) y) \\<longleftrightarrow> (n_equiv n y x)\"\n    by (auto simp: n_equiv_option_def ofe_sym)\nnext\n  fix m n x y\n  show \"\\<lbrakk>m \\<le> n; (n_equiv::nat\\<Rightarrow>'a option\\<Rightarrow>'a option\\<Rightarrow>bool) n x y\\<rbrakk> \\<Longrightarrow> n_equiv m x y\"\n    by (auto simp: n_equiv_option_def ofe_mono)\nqed (auto simp: n_equiv_option_def ofe_eq_option_def ofe_eq_eq ofe_refl intro: ofe_trans)\nend\n\ninstance option :: (discrete) discrete\nproof \nfix a b :: \"'a option\" fix n\nshow \"n_equiv n a b = (a=b)\" by (cases a; cases b) (auto simp: n_equiv_option_def d_equiv)\nnext\nfix a b :: \"'a option\"\nshow \"ofe_eq a b = (a = b)\" by (cases a; cases b) (auto simp: ofe_eq_option_def d_eq)\nqed\n\nsubsubsection \\<open>prod OFE\\<close>\ninstantiation prod :: (ofe,ofe) ofe begin\n  fun n_equiv_prod :: \"nat \\<Rightarrow> ('a\\<times>'b) \\<Rightarrow> ('a\\<times>'b) \\<Rightarrow> bool\" where\n    \"n_equiv_prod n (x1,y1) (x2,y2) = (n_equiv n x1 x2 \\<and> n_equiv n y1 y2)\"\n  fun ofe_eq_prod :: \"'a\\<times>'b \\<Rightarrow> 'a\\<times>'b \\<Rightarrow> bool\" where \n    \"ofe_eq_prod (a1,b1) (a2,b2) = (ofe_eq a1 a2 \\<and> ofe_eq b1 b2)\"\ninstance proof (standard)\n  fix x n \n  show \"n_equiv n x (x::('a\\<times>'b))\"\n    by (cases x) (auto simp: ofe_refl)\nnext\n  fix m n x y\n  assume \"m\\<le>(n::nat)\"\n  thus \"(n_equiv:: nat\\<Rightarrow>('a\\<times>'b)\\<Rightarrow>('a\\<times>'b)\\<Rightarrow>bool) n x y \\<Longrightarrow> n_equiv m x y\"\n    by (cases x; cases y) (auto simp: ofe_mono Pair_inject)\nnext\n  fix x y\n  show \"(ofe_eq (x::('a\\<times>'b)) y) \\<longleftrightarrow> (\\<forall>n. n_equiv n x y)\"\n    by (cases x; cases y) (auto simp: ofe_limit)\nqed (auto simp: ofe_sym ofe_eq_eq intro: ofe_refl ofe_trans)\nend\ninstance prod :: (discrete,discrete) discrete by standard (auto simp: d_equiv d_eq)\n\nsubsubsection \\<open>List type OFE\\<close>\ninstantiation list :: (ofe) ofe begin\ndefinition n_equiv_list :: \"nat \\<Rightarrow> 'a list \\<Rightarrow> 'a list \\<Rightarrow> bool\" where [simp]: \"n_equiv_list \\<equiv> \\<lambda>_. (=)\"\ndefinition ofe_eq_list :: \"'a list \\<Rightarrow> 'a list \\<Rightarrow> bool\" where [simp]: \"ofe_eq_list \\<equiv> (=)\"\ninstance by standard auto\nend\ninstance list :: (discrete) discrete by standard auto\n\nsubsubsection \\<open>Function type OFE\\<close>\ninstantiation \"fun\" :: (type,ofe) ofe begin\ndefinition n_equiv_fun :: \"nat \\<Rightarrow> ('a\\<Rightarrow>'b) \\<Rightarrow> ('a\\<Rightarrow>'b) \\<Rightarrow> bool\" where\n  \"n_equiv_fun n m1 m2 \\<equiv> \\<forall>i. n_equiv n (m1 i) (m2 i)\"\ndefinition ofe_eq_fun :: \"('a\\<Rightarrow>'b) \\<Rightarrow> ('a\\<Rightarrow>'b) \\<Rightarrow> bool\" where\n  \"ofe_eq_fun m1 m2 \\<equiv> \\<forall>i. ofe_eq (m1 i) (m2 i)\"\ninstance by (standard, unfold n_equiv_fun_def ofe_eq_fun_def) \n  (auto simp: ofe_sym  ofe_limit intro: ofe_refl ofe_trans ofe_mono ofe_limit ofe_eq_eq)\nend\n\ninstance \"fun\" :: (type,discrete) discrete \n  by standard (auto simp: n_equiv_fun_def d_equiv ofe_eq_fun_def d_eq)\n\nsubsubsection \\<open>Finite set OFE\\<close>\ninstantiation fset :: (type) ofe begin\ndefinition n_equiv_fset :: \"nat \\<Rightarrow> 'a fset \\<Rightarrow> 'a fset \\<Rightarrow> bool\" where [simp]: \"n_equiv_fset _ \\<equiv> (=)\"\ndefinition ofe_eq_fset :: \"'a fset \\<Rightarrow> 'a fset \\<Rightarrow> bool\" where [simp]: \"ofe_eq_fset \\<equiv> (=)\"\ninstance by (standard) auto\nend\n\ninstance fset :: (type) discrete by standard auto\n\nsubsubsection \\<open>Disjoint finite set OFE\\<close>\ninstantiation dfset :: (type) ofe begin\ndefinition n_equiv_dfset :: \"nat \\<Rightarrow> 'a dfset \\<Rightarrow> 'a dfset \\<Rightarrow> bool\" where \"n_equiv_dfset \\<equiv> \\<lambda>_. (=)\"\ndefinition ofe_eq_dfset :: \"'a dfset \\<Rightarrow> 'a dfset \\<Rightarrow> bool\" where \"ofe_eq_dfset \\<equiv> (=)\"\ninstance by standard (auto simp: n_equiv_dfset_def ofe_eq_dfset_def)\nend\n\ninstance dfset :: (type) discrete by standard (auto simp: n_equiv_dfset_def ofe_eq_dfset_def)\n\nsubsubsection \\<open>Finite map OFE\\<close>\ninstantiation fmap :: (type,ofe) ofe begin\ncontext includes fmap.lifting begin\nlift_definition n_equiv_fmap :: \"nat \\<Rightarrow> ('a, 'b) fmap \\<Rightarrow> ('a, 'b) fmap \\<Rightarrow> bool\" is\n  \"n_equiv::nat\\<Rightarrow>('a\\<rightharpoonup>'b) \\<Rightarrow> ('a\\<rightharpoonup>'b) \\<Rightarrow> bool\" .\nlift_definition ofe_eq_fmap :: \"('a, 'b) fmap \\<Rightarrow> ('a, 'b) fmap \\<Rightarrow> bool\" is\n  \"ofe_eq::('a\\<rightharpoonup>'b) \\<Rightarrow> ('a\\<rightharpoonup>'b) \\<Rightarrow> bool\" .\ninstance by (standard; transfer') \n  (auto simp: ofe_refl ofe_sym ofe_trans ofe_eq_eq ofe_limit intro: ofe_mono)\nend\nend\n\ninstance fmap :: (type,discrete) discrete by standard \n  (auto simp: d_equiv d_eq n_equiv_fmap.rep_eq ofe_eq_fmap.rep_eq fmlookup_inject)\n  \nsubsubsection \\<open>Extended sum type\\<close>\ninstantiation sum_ext :: (ofe,ofe) ofe begin\n  fun ofe_eq_sum_ext :: \"'a+\\<^sub>e'b \\<Rightarrow> 'a+\\<^sub>e'b \\<Rightarrow> bool\" where\n    \"ofe_eq_sum_ext (Inl a) (Inl b) = ofe_eq a b\"\n  | \"ofe_eq_sum_ext (Inr a) (Inr b) = ofe_eq a b\"\n  | \"ofe_eq_sum_ext sum_ext.Inv sum_ext.Inv = True\"\n  | \"ofe_eq_sum_ext _ _ = False\"\n  fun n_equiv_sum_ext :: \"nat \\<Rightarrow> 'a+\\<^sub>e'b \\<Rightarrow> 'a+\\<^sub>e'b \\<Rightarrow> bool\" where\n    \"n_equiv_sum_ext n (Inl x) (Inl y) = n_equiv n x y\"\n  | \"n_equiv_sum_ext n (Inr x) (Inr y) =  n_equiv n x y\"\n  | \"n_equiv_sum_ext _ sum_ext.Inv sum_ext.Inv = True\"\n  | \"n_equiv_sum_ext _ _ _ = False\"\ninstance proof\n  fix n x\n  show \"n_equiv n x (x::'a+\\<^sub>e'b)\" by (cases x) (auto simp: ofe_refl)\nnext\n  fix n x y\n  show \"n_equiv n x y = n_equiv n y (x::'a+\\<^sub>e'b)\" \n    by (cases x y rule: sum_ex2) (auto simp: ofe_sym)\nnext\n  fix n x y z \n  show \"n_equiv n x y \\<Longrightarrow> n_equiv n y z \\<Longrightarrow> n_equiv n x (z::'a+\\<^sub>e'b)\"\n    by (cases x y z rule: sum_ex3) (auto intro: ofe_trans)\nnext\n  fix m n x y\n  show \"m \\<le> n \\<Longrightarrow> n_equiv n x y \\<Longrightarrow> n_equiv m x (y::'a+\\<^sub>e'b)\"\n  by (cases x y rule: sum_ex2) (auto intro: ofe_mono)\nnext\n  fix x y :: \"'a+\\<^sub>e'b\"\n  show \"ofe_eq x y \\<longleftrightarrow> (\\<forall>n. n_equiv n x y)\"\n  apply (cases x; cases y) \n  apply simp_all\n  using ofe_limit by blast+\nnext\n  fix x y :: \"'a+\\<^sub>e'b\" \n  show \"(x=y) \\<Longrightarrow> ofe_eq x y\" by (cases x y rule: sum_ex2) (auto intro: ofe_eq_eq)\nqed\nend\n\ninstance sum_ext :: (discrete,discrete) discrete\nproof\nfix a b :: \"'a+\\<^sub>e'b\" fix n\nshow \"n_equiv n a b = (a = b)\" by (cases a b rule: sum_ex2) (auto simp: d_equiv)\nnext\nfix a b :: \"'a+\\<^sub>e'b\"\nshow \"ofe_eq a b = (a = b)\" by (cases a b rule: sum_ex2) (auto simp: d_eq)\nqed\n\nsubsection \\<open> Advanced OFE instances\\<close>\n\nsubsubsection \\<open> Step indexed proposition OFE\\<close> \ninstantiation sprop :: ofe begin\n  definition n_equiv_sprop :: \"nat \\<Rightarrow> sprop \\<Rightarrow> sprop \\<Rightarrow> bool\" where\n    \"n_equiv_sprop n x y \\<equiv> \\<forall>m\\<le>n. Rep_sprop x m \\<longleftrightarrow> Rep_sprop y m\"\n  definition ofe_eq_sprop :: \"sprop \\<Rightarrow> sprop \\<Rightarrow> bool\" where\n    \"ofe_eq_sprop x y \\<equiv> \\<forall>n. (Rep_sprop x n) \\<longleftrightarrow> (Rep_sprop y n)\"\ninstance by (standard, unfold n_equiv_sprop_def ofe_eq_sprop_def) auto\nend\n\nsubsubsection \\<open>later type OFE\\<close>\ninstantiation later :: (ofe) ofe begin\n  definition n_equiv_later :: \"nat \\<Rightarrow> 'a later \\<Rightarrow> 'a later \\<Rightarrow> bool\" where\n    \"n_equiv_later n x y = (n=0 \\<or> n_equiv (n-1) (later_car x) (later_car y))\"\n  fun ofe_eq_later :: \"'a later \\<Rightarrow> 'a later \\<Rightarrow> bool\" where \n    \"ofe_eq_later (Next a) (Next b) = ofe_eq a b\"\ninstance proof (standard)\n  fix x n\n  show \"n_equiv n (x::'a later) x\" \n    by (cases n; cases x) (auto simp: ofe_refl n_equiv_later_def)\nnext  \n  fix x y n\n  show \"(n_equiv n (x::'a later) y) \\<longleftrightarrow> (n_equiv n y x)\"\n    by (cases n; cases x y rule: later2_ex) (auto simp: ofe_limit ofe_sym n_equiv_later_def)\nnext\n  fix x y n z\n  show \"n_equiv n (x::'a later) y \\<Longrightarrow> n_equiv n y z \\<Longrightarrow> n_equiv n x z\"\n    by (cases n; cases x y z rule: later3_ex) (auto simp: n_equiv_later_def intro: ofe_trans)\nnext\n  fix m n x y\n  show \"m \\<le> n \\<Longrightarrow> (n_equiv::nat\\<Rightarrow>'a later\\<Rightarrow>'a later\\<Rightarrow>bool) n x y \\<Longrightarrow> n_equiv m x y\"\n    by (cases m; cases n; cases x y rule: later2_ex) (auto simp: ofe_mono n_equiv_later_def)\nnext\n  fix x y :: \"'a later\"\n  show \"(ofe_eq x y) \\<longleftrightarrow> (\\<forall>n. n_equiv n x y)\"\n  by (cases x y rule: later2_ex)\n    (metis Zero_not_Suc diff_Suc_1 later.sel n_equiv_later_def ofe_eq_later.simps ofe_limit)\nnext\nfix x y :: \"'a later\"\nshow \"(x=y) \\<Longrightarrow> ofe_eq x y\" using OFEs.ofe_eq_later.elims(3) ofe_eq_eq by auto\nqed\nend\n\nsubsubsection \\<open>Agreement camera combinator OFE\\<close>\ninstantiation ag :: (ofe) ofe begin\nlift_definition n_equiv_ag :: \"nat \\<Rightarrow> ('a::ofe) ag \\<Rightarrow> 'a ag \\<Rightarrow> bool\" is\n  \"\\<lambda>n a b. (\\<forall>x\\<in>a. \\<exists>y\\<in>b. n_equiv n x y) \\<and> (\\<forall>y\\<in>b. \\<exists>x\\<in>a. n_equiv n x y)\" .\ndefinition ofe_eq_ag :: \"('a::ofe) ag \\<Rightarrow> 'a ag \\<Rightarrow> bool\" where\n  \"ofe_eq_ag a b \\<equiv> \\<forall>n. n_equiv n a b\"\nlemmas defs = n_equiv_ag.rep_eq ofe_eq_ag_def\ninstance by (standard) (auto 4 4 simp: defs ofe_sym intro: ofe_refl ofe_trans ofe_mono)\nend\n\ninstance ag :: (discrete) discrete apply standard\n  apply (simp_all add: n_equiv_ag.rep_eq d_equiv ofe_eq_ag_def)\n  using Rep_ag_inject by blast+\n\nlemma to_ag_n_equiv: \"n_equiv n (to_ag a) (to_ag b) \\<longleftrightarrow> n_equiv n a b\"\n  unfolding to_ag.rep_eq n_equiv_ag.rep_eq by simp\n\nsubsubsection \\<open>Exclusive camera combinator OFE\\<close>\ninstantiation ex :: (ofe) ofe begin\nfun n_equiv_ex :: \"nat \\<Rightarrow> 'a::ofe ex \\<Rightarrow> 'a ex \\<Rightarrow> bool\" where\n  \"n_equiv_ex n (Ex a) (Ex b) = n_equiv n a b\"\n| \"n_equiv_ex _ ex.Inv ex.Inv = True\"\n| \"n_equiv_ex _ _ _ = False\"\nfun ofe_eq_ex :: \"'a ex \\<Rightarrow> 'a ex \\<Rightarrow> bool\" where\n  \"ofe_eq_ex (Ex a) (Ex b) = ofe_eq a b\"\n| \"ofe_eq_ex ex.Inv ex.Inv = True\"\n| \"ofe_eq_ex _ _ = False\"\ninstance proof\nfix x n show \"n_equiv n x (x::'a ex)\" by (cases x) (auto intro: ofe_refl)\nnext fix n x y show \"n_equiv n x y = n_equiv n y (x::'a ex)\" by (cases x; cases y) (auto simp: ofe_sym)\nnext fix n x y z show \"n_equiv n x y \\<Longrightarrow> n_equiv n y z \\<Longrightarrow> n_equiv n x (z::'a ex)\"\n  by (cases x; cases y; cases z) (auto intro: ofe_trans)\nnext fix m n x y show \"m \\<le> n \\<Longrightarrow> n_equiv n x y \\<Longrightarrow> n_equiv m x (y::'a ex)\" \n  by (cases x; cases y) (auto intro: ofe_mono)\nnext fix x y show \"ofe_eq x y \\<longleftrightarrow> (\\<forall>n. n_equiv n x (y::'a ex))\" \n  apply (cases x; cases y) apply simp_all using ofe_limit by blast+\nnext fix x y show \"x = y \\<Longrightarrow> ofe_eq x (y::'a ex)\" by (cases x; cases y) (auto intro: ofe_eq_eq)\nqed\nend\n\ninstance ex :: (discrete) discrete\nproof\nfix a b :: \"'a ex\" fix n\nshow \"n_equiv n a b = (a = b)\" by (cases a; cases b) (auto simp: d_equiv)\nnext\nfix a b :: \"'a ex\"\nshow \"ofe_eq a b = (a = b)\" by (cases a; cases b) (auto simp: d_eq)\nqed\n\nsubsubsection \\<open>Authoritative camera combinator OFE\\<close>\n\ninstantiation auth :: (ofe) ofe begin\nfun n_equiv_auth :: \"nat \\<Rightarrow> 'a auth \\<Rightarrow> 'a auth \\<Rightarrow> bool\" where\n  \"n_equiv_auth n (Auth a) (Auth b) = n_equiv n a b\"\nfun ofe_eq_auth :: \"'a auth \\<Rightarrow> 'a auth \\<Rightarrow> bool\" where\n  \"ofe_eq_auth (Auth a) (Auth b) = ofe_eq a b\"\ninstance proof\nfix n x show \"n_equiv n x (x::'a auth)\" by (cases x) (auto intro: ofe_refl) next\nfix n x y show \"n_equiv n x y \\<longleftrightarrow> n_equiv n y (x::'a auth)\" \n  by (cases x; cases y) (auto simp: ofe_sym) next\nfix n x y z show \"n_equiv n x y \\<Longrightarrow> n_equiv n y z \\<Longrightarrow> n_equiv n x (z::'a auth)\"\n  by (cases x; cases y; cases z) (auto intro: ofe_trans) next \nfix m n x y show \"m \\<le> n \\<Longrightarrow> n_equiv n x y \\<Longrightarrow> n_equiv m x (y::'a auth)\"\n  by (cases x; cases y) (auto intro: ofe_mono) next\nfix x y show \"ofe_eq x y \\<longleftrightarrow> (\\<forall>n. n_equiv n x (y::'a auth))\" apply (cases x; cases y; auto)\n  using ofe_limit by blast+ next\nfix x y show \" x = y \\<Longrightarrow> ofe_eq x (y::'a auth)\" by (cases x; cases y) (auto intro: ofe_eq_eq)\nqed\nend\n\ninstance auth :: (discrete) discrete\nproof\nfix a b :: \"'a auth\" fix n\nshow \"n_equiv n a b = (a = b)\" by (cases a; cases b) (auto simp: d_equiv)\nnext\nfix a b :: \"'a auth\"\nshow \"ofe_eq a b = (a = b)\" by (cases a; cases b) (auto simp: d_eq)\nqed\nend", "meta": {"author": "firefighterduck", "repo": "isariris", "sha": "d02268e1e11cf681cae70b366b52843cbd90cc49", "save_path": "github-repos/isabelle/firefighterduck-isariris", "path": "github-repos/isabelle/firefighterduck-isariris/isariris-d02268e1e11cf681cae70b366b52843cbd90cc49/IrisCore/OFEs.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.882427872638409, "lm_q2_score": 0.8006919997179627, "lm_q1q2_score": 0.7065529379497154}}
{"text": "\ntheory Binary_operations\n imports Bij_betw_simplicial_complex_bool_func\nbegin\n\nsection\\<open>Binary operations over Boolean functions and simplicial complexes\\<close>\n\ntext\\<open>In this theory some results on binary operations over Boolean functions and\n  their relationship to operations over the induced simplicial complexes are\n  presented. We follow the presentation by Chastain and Scoville~\\<^cite>\\<open>\\<open>Sect. 1.1\\<close> in \"CHSC\"\\<close>.\\<close>\n\ndefinition bool_fun_or :: \"nat \\<Rightarrow> (bool vec \\<Rightarrow> bool) \\<Rightarrow> (bool vec \\<Rightarrow> bool) \\<Rightarrow> (bool vec \\<Rightarrow> bool)\"\n  where \"(bool_fun_or n f g) \\<equiv> (\\<lambda>x. f x \\<or> g x)\"\n\ndefinition bool_fun_and :: \"nat \\<Rightarrow> (bool vec \\<Rightarrow> bool) \\<Rightarrow> (bool vec \\<Rightarrow> bool) \\<Rightarrow> (bool vec \\<Rightarrow> bool)\"\n  where \"(bool_fun_and n f g) \\<equiv> (\\<lambda>x. f x \\<and> g x)\"\n\nlemma eq_union_or:\n  \"simplicial_complex_induced_by_monotone_boolean_function n (bool_fun_or n f g)\n  = simplicial_complex_induced_by_monotone_boolean_function n f\n    \\<union> simplicial_complex_induced_by_monotone_boolean_function n g\"\n  (is \"?sc n (?bf_or n f g) = ?sc n f \\<union> ?sc n g\")\nproof\n  show \"?sc n f \\<union> ?sc n g \\<subseteq> ?sc n (?bf_or n f g)\"\n  proof\n    fix \\<sigma> :: \"nat set\"\n    assume \"\\<sigma> \\<in> (?sc n f \\<union> ?sc n g)\"\n    hence sigma: \"\\<sigma> \\<in> ?sc n f \\<or> \\<sigma> \\<in> ?sc n g\" by auto\n    have \"f (simplicial_complex.bool_vec_from_simplice n \\<sigma>)\n           \\<or> g (simplicial_complex.bool_vec_from_simplice n \\<sigma>)\"\n    proof (cases \"\\<sigma> \\<in> ?sc n f\")\n      case True\n      from simplicial_complex.simplicial_complex_implies_true [OF True]\n      show \"f (simplicial_complex.bool_vec_from_simplice n \\<sigma>)\n           \\<or> g (simplicial_complex.bool_vec_from_simplice n \\<sigma>)\" by fast\n    next\n      case False\n      hence sigmain: \"\\<sigma> \\<in> ?sc n g\" using sigma by fast\n      from simplicial_complex.simplicial_complex_implies_true [OF sigmain]\n      show \"f (simplicial_complex.bool_vec_from_simplice n \\<sigma>)\n           \\<or> g (simplicial_complex.bool_vec_from_simplice n \\<sigma>)\" by fast\n    qed\n    thus \"\\<sigma> \\<in> ?sc n (?bf_or n f g)\"\n      using simplicial_complex_induced_by_monotone_boolean_function_def\n      using bool_fun_or_def sigma by auto\n  qed\nnext\n  show \"?sc n (?bf_or n f g) \\<subseteq> ?sc n f \\<union> ?sc n g\"\n  proof\n    fix \\<sigma>::\"nat set\"\n    assume sigma: \"\\<sigma> \\<in> ?sc n (?bf_or n f g)\"\n    hence \"bool_fun_or n f g (simplicial_complex.bool_vec_from_simplice n \\<sigma>)\"\n      unfolding simplicial_complex.bool_vec_from_simplice_def\n      unfolding simplicial_complex_induced_by_monotone_boolean_function_def\n      unfolding ceros_of_boolean_input_def\n      by auto (smt (verit) dim_vec eq_vecI index_vec)+\n    hence \"(f (simplicial_complex.bool_vec_from_simplice n \\<sigma>))\n            \\<or> (g (simplicial_complex.bool_vec_from_simplice n \\<sigma>))\"\n      unfolding bool_fun_or_def\n      by auto\n    hence \"\\<sigma> \\<in> ?sc n f \\<or> \\<sigma> \\<in> ?sc n g\"\n      by (smt (z3) sigma bool_fun_or_def mem_Collect_eq\n            simplicial_complex_induced_by_monotone_boolean_function_def)\n    thus \"\\<sigma> \\<in> simplicial_complex_induced_by_monotone_boolean_function n f\n          \\<union> simplicial_complex_induced_by_monotone_boolean_function n g\"\n      by auto\n  qed\nqed\n\nlemma eq_inter_and:\n  \"simplicial_complex_induced_by_monotone_boolean_function n (bool_fun_and n f g)\n  = simplicial_complex_induced_by_monotone_boolean_function n f\n    \\<inter> simplicial_complex_induced_by_monotone_boolean_function n g\"\n  (is \"?sc n (?bf_and n f g) = ?sc n f \\<inter> ?sc n g\")\nproof\n  show \"?sc n f \\<inter> ?sc n g \\<subseteq> ?sc n (?bf_and n f g)\"\n  proof\n    fix \\<sigma> :: \"nat set\"\n    assume \"\\<sigma> \\<in> (?sc n f \\<inter> ?sc n g)\"\n    hence sigma: \"\\<sigma> \\<in> ?sc n f \\<and> \\<sigma> \\<in> ?sc n g\" by auto\n    have \"f (simplicial_complex.bool_vec_from_simplice n \\<sigma>)\n           \\<and> g (simplicial_complex.bool_vec_from_simplice n \\<sigma>)\"\n    proof -\n      from sigma have sigmaf: \"\\<sigma> \\<in> ?sc n f\" and sigmag: \"\\<sigma> \\<in> ?sc n g\"\n        by auto\n      have \"f (simplicial_complex.bool_vec_from_simplice n \\<sigma>)\"\n        using simplicial_complex.simplicial_complex_implies_true [OF sigmaf] .\n      moreover have \"g (simplicial_complex.bool_vec_from_simplice n \\<sigma>)\"\n        using simplicial_complex.simplicial_complex_implies_true [OF sigmag] .\n      ultimately show ?thesis by fast\n    qed\n    thus \"\\<sigma> \\<in> ?sc n (?bf_and n f g)\"\n      unfolding simplicial_complex_induced_by_monotone_boolean_function_def\n      unfolding bool_fun_and_def\n      using sigma apply auto\n      by (smt (z3) Collect_cong ceros_of_boolean_input_def dim_vec index_vec mem_Collect_eq\n          simplicial_complex.bool_vec_from_simplice_def\n          simplicial_complex_induced_by_monotone_boolean_function_def)\n  qed\nnext\n  show \"?sc n (?bf_and n f g) \\<subseteq> ?sc n f \\<inter> ?sc n g\"\n  proof\n    fix \\<sigma> :: \"nat set\"\n    assume sigma: \"\\<sigma> \\<in> ?sc n (?bf_and n f g)\"\n    hence \"bool_fun_and n f g (simplicial_complex.bool_vec_from_simplice n \\<sigma>)\"\n      unfolding simplicial_complex.bool_vec_from_simplice_def\n      unfolding simplicial_complex_induced_by_monotone_boolean_function_def\n      unfolding ceros_of_boolean_input_def\n      by auto (smt (verit) dim_vec eq_vecI index_vec)+\n    hence \"(f (simplicial_complex.bool_vec_from_simplice n \\<sigma>))\n          \\<and> (g (simplicial_complex.bool_vec_from_simplice n \\<sigma>))\"\n      unfolding bool_fun_and_def\n      by auto\n    hence \"\\<sigma> \\<in> ?sc n f \\<and> \\<sigma> \\<in> ?sc n g\"\n      using bool_fun_and_def sigma simplicial_complex_induced_by_monotone_boolean_function_def by auto\n    thus \"\\<sigma> \\<in> simplicial_complex_induced_by_monotone_boolean_function n f\n          \\<inter> simplicial_complex_induced_by_monotone_boolean_function n g\"\n      by auto\n  qed\nqed\n\ndefinition bool_fun_ast :: \"(nat \\<times> nat) \\<Rightarrow> (bool vec \\<Rightarrow> bool) \\<times> (bool vec \\<Rightarrow> bool)\n    \\<Rightarrow> (bool vec \\<times> bool vec \\<Rightarrow> bool)\"\n  where \"(bool_fun_ast n f) \\<equiv> (\\<lambda> (x,y). (fst f x) \\<and> (snd f y))\"\n\ndefinition\n  simplicial_complex_induced_by_monotone_boolean_function_ast\n    :: \"(nat \\<times> nat) \\<Rightarrow> ((bool vec \\<times> bool vec \\<Rightarrow> bool)) \\<Rightarrow> (nat set * nat set) set\"\n  where \"simplicial_complex_induced_by_monotone_boolean_function_ast n f =\n        {z. \\<exists>x y. dim_vec x = fst n \\<and> dim_vec y = snd n \\<and> f (x, y)\n          \\<and> ((ceros_of_boolean_input x), (ceros_of_boolean_input y)) = z}\"\n\nlemma fst_es_simplice:\n  \"a \\<in> simplicial_complex_induced_by_monotone_boolean_function_ast n f\n    \\<Longrightarrow> (\\<exists>x y. f (x, y) \\<and> (ceros_of_boolean_input x) = fst(a))\"\n  by (smt (verit) fst_conv mem_Collect_eq\n        simplicial_complex_induced_by_monotone_boolean_function_ast_def)\n\nlemma snd_es_simplice:\n  \"a \\<in> simplicial_complex_induced_by_monotone_boolean_function_ast n f\n    \\<Longrightarrow> (\\<exists>x y. f (x, y) \\<and> (ceros_of_boolean_input y) = snd(a))\"\n  by (smt (verit) snd_conv mem_Collect_eq\n      simplicial_complex_induced_by_monotone_boolean_function_ast_def)\n\ndefinition set_ast :: \"(nat set) set \\<Rightarrow> (nat set) set \\<Rightarrow> ((nat set*nat set) set)\"\n  where \"set_ast A B \\<equiv> {c. \\<exists>a\\<in>A. \\<exists>b\\<in>B. c = (a,b)}\"\n\ndefinition set_fst :: \"(nat*nat) set \\<Rightarrow> nat set\"\n  where \"set_fst AB = {a. \\<exists>ab\\<in>AB. a = fst ab}\"\n\nlemma set_fst_simp [simp]:\n  assumes \"y \\<noteq> {}\"\n  shows \"set_fst (x \\<times> y) = x\"\nproof\n  show \"set_fst (x \\<times> y) \\<subseteq> x\"\n    by (smt (verit) SigmaE mem_Collect_eq prod.sel(1) set_fst_def subsetI)\n  show \"x \\<subseteq> set_fst (x \\<times> y)\"\n  proof\n    fix a::\"nat\"\n    assume \"a \\<in> x\"\n    then obtain b where \"b \\<in> y\" and \"(a,b) \\<in> (x\\<times>y)\"\n      using assms by blast\n    then show \"a \\<in> set_fst (x \\<times> y)\"\n      using set_fst_def by fastforce\n  qed\nqed\n\ndefinition set_snd :: \"(nat*nat) set \\<Rightarrow> nat set\"\n  where \"set_snd AB = {b. \\<exists>ab\\<in>AB. b = snd(ab)}\"\n\nlemma\n  simplicial_complex_ast_implies_fst_true:\n  assumes \"\\<gamma> \\<in> simplicial_complex_induced_by_monotone_boolean_function_ast nn\n     (bool_fun_ast nn f)\"\n  shows \"fst f (simplicial_complex.bool_vec_from_simplice (fst nn) (fst \\<gamma>))\"\n  using assms\n  unfolding simplicial_complex.bool_vec_from_simplice_def\n  unfolding simplicial_complex_induced_by_monotone_boolean_function_ast_def\n  unfolding bool_fun_ast_def\n  unfolding ceros_of_boolean_input_def\n  apply auto\n  by (smt (verit, ccfv_threshold) bool_fun_ast_def case_prod_conv dim_vec index_vec vec_eq_iff)\n\nlemma\n  simplicial_complex_ast_implies_snd_true:\n  assumes \"\\<gamma> \\<in> simplicial_complex_induced_by_monotone_boolean_function_ast nn\n     (bool_fun_ast nn f)\"\n  shows \"snd f (simplicial_complex.bool_vec_from_simplice (snd nn) (snd \\<gamma>))\"\n  using assms\n  unfolding simplicial_complex.bool_vec_from_simplice_def\n  unfolding simplicial_complex_induced_by_monotone_boolean_function_ast_def\n  unfolding bool_fun_ast_def\n  unfolding ceros_of_boolean_input_def\n  by auto (smt (verit, ccfv_threshold) bool_fun_ast_def\n        case_prod_conv dim_vec index_vec vec_eq_iff)\n\nlemma eq_ast:\n\"simplicial_complex_induced_by_monotone_boolean_function_ast (n, m) (bool_fun_ast (n, m) f)\n= set_ast (simplicial_complex_induced_by_monotone_boolean_function n (fst f))\n          (simplicial_complex_induced_by_monotone_boolean_function m (snd f))\"\nproof\n  show \"set_ast (simplicial_complex_induced_by_monotone_boolean_function n (fst f))\n     (simplicial_complex_induced_by_monotone_boolean_function m (snd f))\n    \\<subseteq> simplicial_complex_induced_by_monotone_boolean_function_ast (n, m)\n        (bool_fun_ast (n, m) f)\"\n  proof\n    fix \\<gamma>::\"nat set*nat set\"\n    assume pert: \"\\<gamma> \\<in> set_ast (simplicial_complex_induced_by_monotone_boolean_function n (fst f))\n     (simplicial_complex_induced_by_monotone_boolean_function m (snd f))\"\n    hence f: \"(fst \\<gamma>) \\<in> simplicial_complex_induced_by_monotone_boolean_function n (fst f)\"\n      unfolding set_ast_def\n      by auto\n    have sigma: \"fst f (simplicial_complex.bool_vec_from_simplice n (fst \\<gamma>))\"\n      using simplicial_complex.simplicial_complex_implies_true [OF f] .\n    from pert have g: \"(snd \\<gamma>) \\<in> simplicial_complex_induced_by_monotone_boolean_function m (snd f)\"\n      unfolding set_ast_def by auto\n    have tau: \"(snd f) (simplicial_complex.bool_vec_from_simplice m (snd \\<gamma>))\"\n      using simplicial_complex.simplicial_complex_implies_true [OF g] .\n    from sigma and tau have sigtau: \"bool_fun_ast (n, m) f\n        ((simplicial_complex.bool_vec_from_simplice n (fst \\<gamma>)),\n         (simplicial_complex.bool_vec_from_simplice m (snd \\<gamma>)))\"\n      unfolding bool_fun_ast_def\n      by auto\n    from sigtau\n    show \"\\<gamma> \\<in> simplicial_complex_induced_by_monotone_boolean_function_ast (n, m)\n              (bool_fun_ast (n, m) f)\"\n      unfolding simplicial_complex_induced_by_monotone_boolean_function_ast_def\n      unfolding bool_fun_ast_def\n      using sigma apply auto\n      using f g simplicial_complex_induced_by_monotone_boolean_function_def by fastforce\n  qed\nnext\n  show \"simplicial_complex_induced_by_monotone_boolean_function_ast (n, m)\n     (bool_fun_ast (n, m) f)\n    \\<subseteq> set_ast (simplicial_complex_induced_by_monotone_boolean_function n (fst f))\n        (simplicial_complex_induced_by_monotone_boolean_function m (snd f))\"\n    proof\n    fix \\<gamma> :: \"nat set*nat set\"\n    assume pert: \"\\<gamma> \\<in> simplicial_complex_induced_by_monotone_boolean_function_ast (n, m)\n     (bool_fun_ast (n, m) f)\"\n    have sigma: \"(fst \\<gamma>) \\<in> simplicial_complex_induced_by_monotone_boolean_function n (fst f)\"\n      unfolding bool_fun_ast_def\n      unfolding simplicial_complex_induced_by_monotone_boolean_function_def\n      unfolding simplicial_complex_induced_by_monotone_boolean_function_ast_def\n      apply auto\n      apply (rule exI [of _ \"simplicial_complex.bool_vec_from_simplice n (fst \\<gamma>)\"], safe)\n      using simplicial_complex.bool_vec_from_simplice_def apply auto[1]\n        apply (metis fst_conv pert simplicial_complex_ast_implies_fst_true)\n      using ceros_of_boolean_input_def simplicial_complex.bool_vec_from_simplice_def\n        apply fastforce\n      using ceros_of_boolean_input_def pert\n          simplicial_complex.bool_vec_from_simplice_def\n          simplicial_complex_induced_by_monotone_boolean_function_ast_def by force\n   have tau: \"(snd \\<gamma>) \\<in> simplicial_complex_induced_by_monotone_boolean_function m (snd f)\"\n      unfolding bool_fun_ast_def\n      unfolding simplicial_complex_induced_by_monotone_boolean_function_def\n      unfolding simplicial_complex_induced_by_monotone_boolean_function_ast_def\n      apply auto\n      apply (rule exI [of _ \"simplicial_complex.bool_vec_from_simplice m (snd \\<gamma>)\"], safe)\n      using simplicial_complex.bool_vec_from_simplice_def apply auto[1]\n        apply (metis snd_conv pert simplicial_complex_ast_implies_snd_true)\n      using ceros_of_boolean_input_def simplicial_complex.bool_vec_from_simplice_def\n       apply fastforce\n      using ceros_of_boolean_input_def pert\n        simplicial_complex.bool_vec_from_simplice_def\n        simplicial_complex_induced_by_monotone_boolean_function_ast_def by force\n    from sigma and tau\n    show \"\\<gamma> \\<in> set_ast\n        (simplicial_complex_induced_by_monotone_boolean_function n (fst f))\n        (simplicial_complex_induced_by_monotone_boolean_function m (snd f))\"\n      using set_ast_def\n      by force\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/Simplicial_complexes_and_boolean_functions/Binary_operations.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8824278695464501, "lm_q2_score": 0.8006919925839875, "lm_q1q2_score": 0.7065529291787901}}
{"text": "(*  Title:      HOL/Statespace/DistinctTreeProver.thy\n    Author:     Norbert Schirmer, TU Muenchen\n*)\n\nsection \\<open>Distinctness of Names in a Binary Tree \\label{sec:DistinctTreeProver}\\<close>\n\ntheory DistinctTreeProver\nimports Main\nbegin\n\ntext \\<open>A state space manages a set of (abstract) names and assumes\nthat the names are distinct. The names are stored as parameters of a\nlocale and distinctness as an assumption. The most common request is\nto proof distinctness of two given names. We maintain the names in a\nbalanced binary tree and formulate a predicate that all nodes in the\ntree have distinct names. This setup leads to logarithmic certificates.\n\\<close>\n\nsubsection \\<open>The Binary Tree\\<close>\n\ndatatype 'a tree = Node \"'a tree\" 'a bool \"'a tree\" | Tip\n\n\ntext \\<open>The boolean flag in the node marks the content of the node as\ndeleted, without having to build a new tree. We prefer the boolean\nflag to an option type, so that the ML-layer can still use the node\ncontent to facilitate binary search in the tree. The ML code keeps the\nnodes sorted using the term order. We do not have to push ordering to\nthe HOL level.\\<close>\n\nsubsection \\<open>Distinctness of Nodes\\<close>\n\n\nprimrec set_of :: \"'a tree \\<Rightarrow> 'a set\"\nwhere\n  \"set_of Tip = {}\"\n| \"set_of (Node l x d r) = (if d then {} else {x}) \\<union> set_of l \\<union> set_of r\"\n\nprimrec all_distinct :: \"'a tree \\<Rightarrow> bool\"\nwhere\n  \"all_distinct Tip = True\"\n| \"all_distinct (Node l x d r) =\n    ((d \\<or> (x \\<notin> set_of l \\<and> x \\<notin> set_of r)) \\<and>\n      set_of l \\<inter> set_of r = {} \\<and>\n      all_distinct l \\<and> all_distinct r)\"\n\ntext \\<open>Given a binary tree \\<^term>\\<open>t\\<close> for which\n\\<^const>\\<open>all_distinct\\<close> holds, given two different nodes contained in the tree,\nwe want to write a ML function that generates a logarithmic\ncertificate that the content of the nodes is distinct. We use the\nfollowing lemmas to achieve this.\\<close>\n\nlemma all_distinct_left: \"all_distinct (Node l x b r) \\<Longrightarrow> all_distinct l\"\n  by simp\n\nlemma all_distinct_right: \"all_distinct (Node l x b r) \\<Longrightarrow> all_distinct r\"\n  by simp\n\nlemma distinct_left: \"all_distinct (Node l x False r) \\<Longrightarrow> y \\<in> set_of l \\<Longrightarrow> x \\<noteq> y\"\n  by auto\n\nlemma distinct_right: \"all_distinct (Node l x False r) \\<Longrightarrow> y \\<in> set_of r \\<Longrightarrow> x \\<noteq> y\"\n  by auto\n\nlemma distinct_left_right:\n    \"all_distinct (Node l z b r) \\<Longrightarrow> x \\<in> set_of l \\<Longrightarrow> y \\<in> set_of r \\<Longrightarrow> x \\<noteq> y\"\n  by auto\n\nlemma in_set_root: \"x \\<in> set_of (Node l x False r)\"\n  by simp\n\nlemma in_set_left: \"y \\<in> set_of l \\<Longrightarrow>  y \\<in> set_of (Node l x False r)\"\n  by simp\n\nlemma in_set_right: \"y \\<in> set_of r \\<Longrightarrow>  y \\<in> set_of (Node l x False r)\"\n  by simp\n\nlemma swap_neq: \"x \\<noteq> y \\<Longrightarrow> y \\<noteq> x\"\n  by blast\n\nlemma neq_to_eq_False: \"x\\<noteq>y \\<Longrightarrow> (x=y)\\<equiv>False\"\n  by simp\n\nsubsection \\<open>Containment of Trees\\<close>\n\ntext \\<open>When deriving a state space from other ones, we create a new\nname tree which contains all the names of the parent state spaces and\nassume the predicate \\<^const>\\<open>all_distinct\\<close>. We then prove that the new\nlocale interprets all parent locales. Hence we have to show that the\nnew distinctness assumption on all names implies the distinctness\nassumptions of the parent locales. This proof is implemented in ML. We\ndo this efficiently by defining a kind of containment check of trees\nby ``subtraction''.  We subtract the parent tree from the new tree. If\nthis succeeds we know that \\<^const>\\<open>all_distinct\\<close> of the new tree\nimplies \\<^const>\\<open>all_distinct\\<close> of the parent tree.  The resulting\ncertificate is of the order \\<^term>\\<open>n * log(m)\\<close> where \\<^term>\\<open>n\\<close> is\nthe size of the (smaller) parent tree and \\<^term>\\<open>m\\<close> the size of the\n(bigger) new tree.\\<close>\n\n\nprimrec delete :: \"'a \\<Rightarrow> 'a tree \\<Rightarrow> 'a tree option\"\nwhere\n  \"delete x Tip = None\"\n| \"delete x (Node l y d r) = (case delete x l of\n                                Some l' \\<Rightarrow>\n                                 (case delete x r of\n                                    Some r' \\<Rightarrow> Some (Node l' y (d \\<or> (x=y)) r')\n                                  | None \\<Rightarrow> Some (Node l' y (d \\<or> (x=y)) r))\n                               | None \\<Rightarrow>\n                                  (case delete x r of\n                                     Some r' \\<Rightarrow> Some (Node l y (d \\<or> (x=y)) r')\n                                   | None \\<Rightarrow> if x=y \\<and> \\<not>d then Some (Node l y True r)\n                                             else None))\"\n\n\nlemma delete_Some_set_of: \"delete x t = Some t' \\<Longrightarrow> set_of t' \\<subseteq> set_of t\"\nproof (induct t arbitrary: t')\n  case Tip thus ?case by simp\nnext\n  case (Node l y d r)\n  have del: \"delete x (Node l y d r) = Some t'\" by fact\n  show ?case\n  proof (cases \"delete x l\")\n    case (Some l')\n    note x_l_Some = this\n    with Node.hyps\n    have l'_l: \"set_of l' \\<subseteq> set_of l\"\n      by simp\n    show ?thesis\n    proof (cases \"delete x r\")\n      case (Some r')\n      with Node.hyps\n      have \"set_of r' \\<subseteq> set_of r\"\n        by simp\n      with l'_l Some x_l_Some del\n      show ?thesis\n        by (auto split: if_split_asm)\n    next\n      case None\n      with l'_l Some x_l_Some del\n      show ?thesis\n        by (fastforce split: if_split_asm)\n    qed\n  next\n    case None\n    note x_l_None = this\n    show ?thesis\n    proof (cases \"delete x r\")\n      case (Some r')\n      with Node.hyps\n      have \"set_of r' \\<subseteq> set_of r\"\n        by simp\n      with Some x_l_None del\n      show ?thesis\n        by (fastforce split: if_split_asm)\n    next\n      case None\n      with x_l_None del\n      show ?thesis\n        by (fastforce split: if_split_asm)\n    qed\n  qed\nqed\n\nlemma delete_Some_all_distinct:\n  \"delete x t = Some t' \\<Longrightarrow> all_distinct t \\<Longrightarrow> all_distinct t'\"\nproof (induct t arbitrary: t')\n  case Tip thus ?case by simp\nnext\n  case (Node l y d r)\n  have del: \"delete x (Node l y d r) = Some t'\" by fact\n  have \"all_distinct (Node l y d r)\" by fact\n  then obtain\n    dist_l: \"all_distinct l\" and\n    dist_r: \"all_distinct r\" and\n    d: \"d \\<or> (y \\<notin> set_of l \\<and> y \\<notin> set_of r)\" and\n    dist_l_r: \"set_of l \\<inter> set_of r = {}\"\n    by auto\n  show ?case\n  proof (cases \"delete x l\")\n    case (Some l')\n    note x_l_Some = this\n    from Node.hyps (1) [OF Some dist_l]\n    have dist_l': \"all_distinct l'\"\n      by simp\n    from delete_Some_set_of [OF x_l_Some]\n    have l'_l: \"set_of l' \\<subseteq> set_of l\".\n    show ?thesis\n    proof (cases \"delete x r\")\n      case (Some r')\n      from Node.hyps (2) [OF Some dist_r]\n      have dist_r': \"all_distinct r'\"\n        by simp\n      from delete_Some_set_of [OF Some]\n      have \"set_of r' \\<subseteq> set_of r\".\n\n      with dist_l' dist_r' l'_l Some x_l_Some del d dist_l_r\n      show ?thesis\n        by fastforce\n    next\n      case None\n      with l'_l dist_l'  x_l_Some del d dist_l_r dist_r\n      show ?thesis\n        by fastforce\n    qed\n  next\n    case None\n    note x_l_None = this\n    show ?thesis\n    proof (cases \"delete x r\")\n      case (Some r')\n      with Node.hyps (2) [OF Some dist_r]\n      have dist_r': \"all_distinct r'\"\n        by simp\n      from delete_Some_set_of [OF Some]\n      have \"set_of r' \\<subseteq> set_of r\".\n      with Some dist_r' x_l_None del dist_l d dist_l_r\n      show ?thesis\n        by fastforce\n    next\n      case None\n      with x_l_None del dist_l dist_r d dist_l_r\n      show ?thesis\n        by (fastforce split: if_split_asm)\n    qed\n  qed\nqed\n\nlemma delete_None_set_of_conv: \"delete x t = None = (x \\<notin> set_of t)\"\nproof (induct t)\n  case Tip thus ?case by simp\nnext\n  case (Node l y d r)\n  thus ?case\n    by (auto split: option.splits)\nqed\n\nlemma delete_Some_x_set_of:\n  \"delete x t = Some t' \\<Longrightarrow> x \\<in> set_of t \\<and> x \\<notin> set_of t'\"\nproof (induct t arbitrary: t')\n  case Tip thus ?case by simp\nnext\n  case (Node l y d r)\n  have del: \"delete x (Node l y d r) = Some t'\" by fact\n  show ?case\n  proof (cases \"delete x l\")\n    case (Some l')\n    note x_l_Some = this\n    from Node.hyps (1) [OF Some]\n    obtain x_l: \"x \\<in> set_of l\" \"x \\<notin> set_of l'\"\n      by simp\n    show ?thesis\n    proof (cases \"delete x r\")\n      case (Some r')\n      from Node.hyps (2) [OF Some]\n      obtain x_r: \"x \\<in> set_of r\" \"x \\<notin> set_of r'\"\n        by simp\n      from x_r x_l Some x_l_Some del\n      show ?thesis\n        by (clarsimp split: if_split_asm)\n    next\n      case None\n      then have \"x \\<notin> set_of r\"\n        by (simp add: delete_None_set_of_conv)\n      with x_l None x_l_Some del\n      show ?thesis\n        by (clarsimp split: if_split_asm)\n    qed\n  next\n    case None\n    note x_l_None = this\n    then have x_notin_l: \"x \\<notin> set_of l\"\n      by (simp add: delete_None_set_of_conv)\n    show ?thesis\n    proof (cases \"delete x r\")\n      case (Some r')\n      from Node.hyps (2) [OF Some]\n      obtain x_r: \"x \\<in> set_of r\" \"x \\<notin> set_of r'\"\n        by simp\n      from x_r x_notin_l Some x_l_None del\n      show ?thesis\n        by (clarsimp split: if_split_asm)\n    next\n      case None\n      then have \"x \\<notin> set_of r\"\n        by (simp add: delete_None_set_of_conv)\n      with None x_l_None x_notin_l del\n      show ?thesis\n        by (clarsimp split: if_split_asm)\n    qed\n  qed\nqed\n\n\nprimrec subtract :: \"'a tree \\<Rightarrow> 'a tree \\<Rightarrow> 'a tree option\"\nwhere\n  \"subtract Tip t = Some t\"\n| \"subtract (Node l x b r) t =\n     (case delete x t of\n        Some t' \\<Rightarrow> (case subtract l t' of\n                     Some t'' \\<Rightarrow> subtract r t''\n                    | None \\<Rightarrow> None)\n       | None \\<Rightarrow> None)\"\n\nlemma subtract_Some_set_of_res:\n  \"subtract t\\<^sub>1 t\\<^sub>2 = Some t \\<Longrightarrow> set_of t \\<subseteq> set_of t\\<^sub>2\"\nproof (induct t\\<^sub>1 arbitrary: t\\<^sub>2 t)\n  case Tip thus ?case by simp\nnext\n  case (Node l x b r)\n  have sub: \"subtract (Node l x b r) t\\<^sub>2 = Some t\" by fact\n  show ?case\n  proof (cases \"delete x t\\<^sub>2\")\n    case (Some t\\<^sub>2')\n    note del_x_Some = this\n    from delete_Some_set_of [OF Some]\n    have t2'_t2: \"set_of t\\<^sub>2' \\<subseteq> set_of t\\<^sub>2\" .\n    show ?thesis\n    proof (cases \"subtract l t\\<^sub>2'\")\n      case (Some t\\<^sub>2'')\n      note sub_l_Some = this\n      from Node.hyps (1) [OF Some]\n      have t2''_t2': \"set_of t\\<^sub>2'' \\<subseteq> set_of t\\<^sub>2'\" .\n      show ?thesis\n      proof (cases \"subtract r t\\<^sub>2''\")\n        case (Some t\\<^sub>2''')\n        from Node.hyps (2) [OF Some ]\n        have \"set_of t\\<^sub>2''' \\<subseteq> set_of t\\<^sub>2''\" .\n        with Some sub_l_Some del_x_Some sub t2''_t2' t2'_t2\n        show ?thesis\n          by simp\n      next\n        case None\n        with del_x_Some sub_l_Some sub\n        show ?thesis\n          by simp\n      qed\n    next\n      case None\n      with del_x_Some sub\n      show ?thesis\n        by simp\n    qed\n  next\n    case None\n    with sub show ?thesis by simp\n  qed\nqed\n\nlemma subtract_Some_set_of:\n  \"subtract t\\<^sub>1 t\\<^sub>2 = Some t \\<Longrightarrow> set_of t\\<^sub>1 \\<subseteq> set_of t\\<^sub>2\"\nproof (induct t\\<^sub>1 arbitrary: t\\<^sub>2 t)\n  case Tip thus ?case by simp\nnext\n  case (Node l x d r)\n  have sub: \"subtract (Node l x d r) t\\<^sub>2 = Some t\" by fact\n  show ?case\n  proof (cases \"delete x t\\<^sub>2\")\n    case (Some t\\<^sub>2')\n    note del_x_Some = this\n    from delete_Some_set_of [OF Some]\n    have t2'_t2: \"set_of t\\<^sub>2' \\<subseteq> set_of t\\<^sub>2\" .\n    from delete_None_set_of_conv [of x t\\<^sub>2] Some\n    have x_t2: \"x \\<in> set_of t\\<^sub>2\"\n      by simp\n    show ?thesis\n    proof (cases \"subtract l t\\<^sub>2'\")\n      case (Some t\\<^sub>2'')\n      note sub_l_Some = this\n      from Node.hyps (1) [OF Some]\n      have l_t2': \"set_of l \\<subseteq> set_of t\\<^sub>2'\" .\n      from subtract_Some_set_of_res [OF Some]\n      have t2''_t2': \"set_of t\\<^sub>2'' \\<subseteq> set_of t\\<^sub>2'\" .\n      show ?thesis\n      proof (cases \"subtract r t\\<^sub>2''\")\n        case (Some t\\<^sub>2''')\n        from Node.hyps (2) [OF Some ]\n        have r_t\\<^sub>2'': \"set_of r \\<subseteq> set_of t\\<^sub>2''\" .\n        from Some sub_l_Some del_x_Some sub r_t\\<^sub>2'' l_t2' t2'_t2 t2''_t2' x_t2\n        show ?thesis\n          by auto\n      next\n        case None\n        with del_x_Some sub_l_Some sub\n        show ?thesis\n          by simp\n      qed\n    next\n      case None\n      with del_x_Some sub\n      show ?thesis\n        by simp\n    qed\n  next\n    case None\n    with sub show ?thesis by simp\n  qed\nqed\n\nlemma subtract_Some_all_distinct_res:\n  \"subtract t\\<^sub>1 t\\<^sub>2 = Some t \\<Longrightarrow> all_distinct t\\<^sub>2 \\<Longrightarrow> all_distinct t\"\nproof (induct t\\<^sub>1 arbitrary: t\\<^sub>2 t)\n  case Tip thus ?case by simp\nnext\n  case (Node l x d r)\n  have sub: \"subtract (Node l x d r) t\\<^sub>2 = Some t\" by fact\n  have dist_t2: \"all_distinct t\\<^sub>2\" by fact\n  show ?case\n  proof (cases \"delete x t\\<^sub>2\")\n    case (Some t\\<^sub>2')\n    note del_x_Some = this\n    from delete_Some_all_distinct [OF Some dist_t2]\n    have dist_t2': \"all_distinct t\\<^sub>2'\" .\n    show ?thesis\n    proof (cases \"subtract l t\\<^sub>2'\")\n      case (Some t\\<^sub>2'')\n      note sub_l_Some = this\n      from Node.hyps (1) [OF Some dist_t2']\n      have dist_t2'': \"all_distinct t\\<^sub>2''\" .\n      show ?thesis\n      proof (cases \"subtract r t\\<^sub>2''\")\n        case (Some t\\<^sub>2''')\n        from Node.hyps (2) [OF Some dist_t2'']\n        have dist_t2''': \"all_distinct t\\<^sub>2'''\" .\n        from Some sub_l_Some del_x_Some sub\n             dist_t2'''\n        show ?thesis\n          by simp\n      next\n        case None\n        with del_x_Some sub_l_Some sub\n        show ?thesis\n          by simp\n      qed\n    next\n      case None\n      with del_x_Some sub\n      show ?thesis\n        by simp\n    qed\n  next\n    case None\n    with sub show ?thesis by simp\n  qed\nqed\n\n\nlemma subtract_Some_dist_res:\n  \"subtract t\\<^sub>1 t\\<^sub>2 = Some t \\<Longrightarrow> set_of t\\<^sub>1 \\<inter> set_of t = {}\"\nproof (induct t\\<^sub>1 arbitrary: t\\<^sub>2 t)\n  case Tip thus ?case by simp\nnext\n  case (Node l x d r)\n  have sub: \"subtract (Node l x d r) t\\<^sub>2 = Some t\" by fact\n  show ?case\n  proof (cases \"delete x t\\<^sub>2\")\n    case (Some t\\<^sub>2')\n    note del_x_Some = this\n    from delete_Some_x_set_of [OF Some]\n    obtain x_t2: \"x \\<in> set_of t\\<^sub>2\" and x_not_t2': \"x \\<notin> set_of t\\<^sub>2'\"\n      by simp\n    from delete_Some_set_of [OF Some]\n    have t2'_t2: \"set_of t\\<^sub>2' \\<subseteq> set_of t\\<^sub>2\" .\n    show ?thesis\n    proof (cases \"subtract l t\\<^sub>2'\")\n      case (Some t\\<^sub>2'')\n      note sub_l_Some = this\n      from Node.hyps (1) [OF Some ]\n      have dist_l_t2'': \"set_of l \\<inter> set_of t\\<^sub>2'' = {}\".\n      from subtract_Some_set_of_res [OF Some]\n      have t2''_t2': \"set_of t\\<^sub>2'' \\<subseteq> set_of t\\<^sub>2'\" .\n      show ?thesis\n      proof (cases \"subtract r t\\<^sub>2''\")\n        case (Some t\\<^sub>2''')\n        from Node.hyps (2) [OF Some]\n        have dist_r_t2''': \"set_of r \\<inter> set_of t\\<^sub>2''' = {}\" .\n        from subtract_Some_set_of_res [OF Some]\n        have t2'''_t2'': \"set_of t\\<^sub>2''' \\<subseteq> set_of t\\<^sub>2''\".\n\n        from Some sub_l_Some del_x_Some sub t2'''_t2'' dist_l_t2'' dist_r_t2'''\n             t2''_t2' t2'_t2 x_not_t2'\n        show ?thesis\n          by auto\n      next\n        case None\n        with del_x_Some sub_l_Some sub\n        show ?thesis\n          by simp\n      qed\n    next\n      case None\n      with del_x_Some sub\n      show ?thesis\n        by simp\n    qed\n  next\n    case None\n    with sub show ?thesis by simp\n  qed\nqed\n\nlemma subtract_Some_all_distinct:\n  \"subtract t\\<^sub>1 t\\<^sub>2 = Some t \\<Longrightarrow> all_distinct t\\<^sub>2 \\<Longrightarrow> all_distinct t\\<^sub>1\"\nproof (induct t\\<^sub>1 arbitrary: t\\<^sub>2 t)\n  case Tip thus ?case by simp\nnext\n  case (Node l x d r)\n  have sub: \"subtract (Node l x d r) t\\<^sub>2 = Some t\" by fact\n  have dist_t2: \"all_distinct t\\<^sub>2\" by fact\n  show ?case\n  proof (cases \"delete x t\\<^sub>2\")\n    case (Some t\\<^sub>2')\n    note del_x_Some = this\n    from delete_Some_all_distinct [OF Some dist_t2 ]\n    have dist_t2': \"all_distinct t\\<^sub>2'\" .\n    from delete_Some_set_of [OF Some]\n    have t2'_t2: \"set_of t\\<^sub>2' \\<subseteq> set_of t\\<^sub>2\" .\n    from delete_Some_x_set_of [OF Some]\n    obtain x_t2: \"x \\<in> set_of t\\<^sub>2\" and x_not_t2': \"x \\<notin> set_of t\\<^sub>2'\"\n      by simp\n\n    show ?thesis\n    proof (cases \"subtract l t\\<^sub>2'\")\n      case (Some t\\<^sub>2'')\n      note sub_l_Some = this\n      from Node.hyps (1) [OF Some dist_t2' ]\n      have dist_l: \"all_distinct l\" .\n      from subtract_Some_all_distinct_res [OF Some dist_t2']\n      have dist_t2'': \"all_distinct t\\<^sub>2''\" .\n      from subtract_Some_set_of [OF Some]\n      have l_t2': \"set_of l \\<subseteq> set_of t\\<^sub>2'\" .\n      from subtract_Some_set_of_res [OF Some]\n      have t2''_t2': \"set_of t\\<^sub>2'' \\<subseteq> set_of t\\<^sub>2'\" .\n      from subtract_Some_dist_res [OF Some]\n      have dist_l_t2'': \"set_of l \\<inter> set_of t\\<^sub>2'' = {}\".\n      show ?thesis\n      proof (cases \"subtract r t\\<^sub>2''\")\n        case (Some t\\<^sub>2''')\n        from Node.hyps (2) [OF Some dist_t2'']\n        have dist_r: \"all_distinct r\" .\n        from subtract_Some_set_of [OF Some]\n        have r_t2'': \"set_of r \\<subseteq> set_of t\\<^sub>2''\" .\n        from subtract_Some_dist_res [OF Some]\n        have dist_r_t2''': \"set_of r \\<inter> set_of t\\<^sub>2''' = {}\".\n\n        from dist_l dist_r Some sub_l_Some del_x_Some r_t2'' l_t2' x_t2 x_not_t2'\n             t2''_t2' dist_l_t2'' dist_r_t2'''\n        show ?thesis\n          by auto\n      next\n        case None\n        with del_x_Some sub_l_Some sub\n        show ?thesis\n          by simp\n      qed\n    next\n      case None\n      with del_x_Some sub\n      show ?thesis\n        by simp\n    qed\n  next\n    case None\n    with sub show ?thesis by simp\n  qed\nqed\n\n\nlemma delete_left:\n  assumes dist: \"all_distinct (Node l y d r)\"\n  assumes del_l: \"delete x l = Some l'\"\n  shows \"delete x (Node l y d r) = Some (Node l' y d r)\"\nproof -\n  from delete_Some_x_set_of [OF del_l]\n  obtain x: \"x \\<in> set_of l\"\n    by simp\n  with dist\n  have \"delete x r = None\"\n    by (cases \"delete x r\") (auto dest:delete_Some_x_set_of)\n\n  with x\n  show ?thesis\n    using del_l dist\n    by (auto split: option.splits)\nqed\n\nlemma delete_right:\n  assumes dist: \"all_distinct (Node l y d r)\"\n  assumes del_r: \"delete x r = Some r'\"\n  shows \"delete x (Node l y d r) = Some (Node l y d r')\"\nproof -\n  from delete_Some_x_set_of [OF del_r]\n  obtain x: \"x \\<in> set_of r\"\n    by simp\n  with dist\n  have \"delete x l = None\"\n    by (cases \"delete x l\") (auto dest:delete_Some_x_set_of)\n\n  with x\n  show ?thesis\n    using del_r dist\n    by (auto split: option.splits)\nqed\n\nlemma delete_root:\n  assumes dist: \"all_distinct (Node l x False r)\"\n  shows \"delete x (Node l x False r) = Some (Node l x True r)\"\nproof -\n  from dist have \"delete x r = None\"\n    by (cases \"delete x r\") (auto dest:delete_Some_x_set_of)\n  moreover\n  from dist have \"delete x l = None\"\n    by (cases \"delete x l\") (auto dest:delete_Some_x_set_of)\n  ultimately show ?thesis\n    using dist\n       by (auto split: option.splits)\nqed\n\nlemma subtract_Node:\n assumes del: \"delete x t = Some t'\"\n assumes sub_l: \"subtract l t' = Some t''\"\n assumes sub_r: \"subtract r t'' = Some t'''\"\n shows \"subtract (Node l x False r) t = Some t'''\"\nusing del sub_l sub_r\nby simp\n\nlemma subtract_Tip: \"subtract Tip t = Some t\"\n  by simp\n\ntext \\<open>Now we have all the theorems in place that are needed for the\ncertificate generating ML functions.\\<close>\n\nML_file \\<open>distinct_tree_prover.ML\\<close>\n\nend\n", "meta": {"author": "xqyww123", "repo": "phi-system", "sha": "c8dca186bcc8ac2c9b38d813fc0f0dfec486ebab", "save_path": "github-repos/isabelle/xqyww123-phi-system", "path": "github-repos/isabelle/xqyww123-phi-system/phi-system-c8dca186bcc8ac2c9b38d813fc0f0dfec486ebab/Phi_Semantics_Framework/Statespace/DistinctTreeProver.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8824278571786139, "lm_q2_score": 0.800691997339971, "lm_q1q2_score": 0.7065529234727751}}
{"text": "chapter \\<open>A monad for generating fresh names\\<close>\n\ntheory Fresh_Monad\nimports\n  \"HOL-Library.State_Monad\"\n  Term_Utils\nbegin\n\ntext \\<open>\n  Generation of fresh names in general can be thought of as picking a string that is not an element\n  of a (finite) set of already existing names. For Isabelle, the \\<^emph>\\<open>Nominal\\<close> framework\n  \\<^cite>\\<open>urban2008nominal and urban2013nominal\\<close> provides support for reasoning over fresh names, but\n  unfortunately, its definitions are not executable.\n\n  Instead, I chose to model generation of fresh names as a monad based on @{type state}. With this,\n  it becomes possible to write programs using \\<open>do\\<close>-notation. This is implemented abstractly as a\n  @{command locale} that expects two operations:\n\n  \\<^item> \\<open>next\\<close> expects a value and generates a larger value, according to @{class linorder}\n  \\<^item> \\<open>arb\\<close> produces any value, similarly to @{const undefined}, but executable\n\\<close>\n\nlocale fresh =\n  fixes \"next\" :: \"'a::linorder \\<Rightarrow> 'a\" and arb :: 'a\n  assumes next_ge: \"next x > x\"\nbegin\n\nabbreviation update_next :: \"('a, unit) state\" where\n\"update_next \\<equiv> State_Monad.update next\"\n\nlemma update_next_strict_mono[simp, intro]: \"strict_mono_state update_next\"\nusing next_ge by (auto intro: update_strict_mono)\n\nlemma update_next_mono[simp, intro]: \"mono_state update_next\"\nby (rule strict_mono_implies_mono) (rule update_next_strict_mono)\n\ndefinition create :: \"('a, 'a) state\" where\n\"create = update_next \\<bind> (\\<lambda>_. State_Monad.get)\"\n\nlemma create_alt_def[code]: \"create = State (\\<lambda>a. (next a, next a))\"\nunfolding create_def State_Monad.update_def State_Monad.get_def State_Monad.set_def State_Monad.bind_def\nby simp\n\nabbreviation fresh_in :: \"'a set \\<Rightarrow> 'a \\<Rightarrow> bool\" where\n\"fresh_in S s \\<equiv> Ball S ((\\<ge>) s)\"\n\nlemma next_ge_all: \"finite S \\<Longrightarrow> fresh_in S s \\<Longrightarrow> next s \\<notin> S\"\nby (metis antisym less_imp_le less_irrefl next_ge)\n\ndefinition Next :: \"'a set \\<Rightarrow> 'a\" where\n\"Next S = (if S = {} then arb else next (Max S))\"\n\nlemma Next_ge_max: \"finite S \\<Longrightarrow> S \\<noteq> {} \\<Longrightarrow> Next S > Max S\"\nunfolding Next_def using next_ge by simp\n\nlemma Next_not_member_subset: \"finite S' \\<Longrightarrow> S \\<subseteq> S' \\<Longrightarrow> Next S' \\<notin> S\"\nunfolding Next_def using next_ge\nby (metis Max_ge Max_mono empty_iff finite_subset leD less_le_trans subset_empty)\n\nlemma Next_not_member: \"finite S \\<Longrightarrow> Next S \\<notin> S\"\nby (rule Next_not_member_subset) auto\n\nlemma Next_geq_not_member: \"finite S \\<Longrightarrow> s \\<ge> Next S \\<Longrightarrow> s \\<notin> S\"\nunfolding Next_def using next_ge\nby (metis (full_types) Max_ge all_not_in_conv leD le_less_trans)\n\nlemma next_not_member: \"finite S \\<Longrightarrow> s \\<ge> Next S \\<Longrightarrow> next s \\<notin> S\"\nby (meson Next_geq_not_member less_imp_le next_ge order_trans)\n\nlemma create_mono[simp, intro]: \"mono_state create\"\nunfolding create_def\nby (auto intro: bind_mono_strong)\n\nlemma create_strict_mono[simp, intro]: \"strict_mono_state create\"\nunfolding create_def\nby (rule bind_strict_mono_strong2) auto\n\nabbreviation run_fresh where\n\"run_fresh m S \\<equiv> fst (run_state m (Next S))\"\n\nabbreviation fresh_fin :: \"'a fset \\<Rightarrow> 'a \\<Rightarrow> bool\" where\n\"fresh_fin S s \\<equiv> fBall S ((\\<ge>) s)\"\n\ncontext includes fset.lifting begin\n\nlemma next_ge_fall: \"fresh_fin S s \\<Longrightarrow> next s |\\<notin>| S\"\nby (transfer fixing: \"next\") (rule next_ge_all)\n\nlift_definition fNext :: \"'a fset \\<Rightarrow> 'a\" is Next .\n\nlemma fNext_ge_max: \"S \\<noteq> {||} \\<Longrightarrow> fNext S > fMax S\"\nby transfer (rule Next_ge_max)\n\nlemma next_not_fmember: \"s \\<ge> fNext S \\<Longrightarrow> next s |\\<notin>| S\"\nby transfer (rule next_not_member)\n\nlemma fNext_geq_not_member: \"s \\<ge> fNext S \\<Longrightarrow> s |\\<notin>| S\"\nby transfer (rule Next_geq_not_member)\n\nlemma fNext_not_member: \"fNext S |\\<notin>| S\"\nby transfer (rule Next_not_member)\n\nlemma fNext_not_member_subset: \"S |\\<subseteq>| S' \\<Longrightarrow> fNext S' |\\<notin>| S\"\nby transfer (rule Next_not_member_subset)\n\nabbreviation frun_fresh where\n\"frun_fresh m S \\<equiv> fst (run_state m (fNext S))\"\n\nend\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/Higher_Order_Terms/Fresh_Monad.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.84997116805678, "lm_q2_score": 0.8311430499496096, "lm_q1q2_score": 0.7064476289879443}}
{"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_MSortTDCount\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 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\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 (msorttd 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_MSortTDCount.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.92522995296862, "lm_q2_score": 0.7634837581726991, "lm_q1q2_score": 0.7063980416664316}}
{"text": "(*  Title:      HOL/Library/Order_Continuity.thy\n    Author:     David von Oheimb, TU M\u00fcnchen\n    Author:     Johannes H\u00f6lzl, TU M\u00fcnchen\n*)\n\nsection \\<open>Continuity and iterations\\<close>\n\ntheory Order_Continuity\nimports Complex_MainRLT Countable_Complete_Lattices\nbegin\n\n(* TODO: Generalize theory to chain-complete partial orders *)\n\nlemma SUP_nat_binary:\n  \"(sup A (SUP x\\<in>Collect ((<) (0::nat)). B)) = (sup A B::'a::countable_complete_lattice)\"\n  apply (subst image_constant)\n   apply auto\n  done\n\nlemma INF_nat_binary:\n  \"inf A (INF x\\<in>Collect ((<) (0::nat)). B) = (inf A B::'a::countable_complete_lattice)\"\n  apply (subst image_constant)\n   apply auto\n  done\n\ntext \\<open>\n  The name \\<open>continuous\\<close> is already taken in \\<open>Complex_MainRLT\\<close>, so we use\n  \\<open>sup_continuous\\<close> and \\<open>inf_continuous\\<close>. These names appear sometimes in literature\n  and have the advantage that these names are duals.\n\\<close>\n\nnamed_theorems order_continuous_intros\n\nsubsection \\<open>Continuity for complete lattices\\<close>\n\ndefinition\n  sup_continuous :: \"('a::countable_complete_lattice \\<Rightarrow> 'b::countable_complete_lattice) \\<Rightarrow> bool\"\nwhere\n  \"sup_continuous F \\<longleftrightarrow> (\\<forall>M::nat \\<Rightarrow> 'a. mono M \\<longrightarrow> F (SUP i. M i) = (SUP i. F (M i)))\"\n\nlemma sup_continuousD: \"sup_continuous F \\<Longrightarrow> mono M \\<Longrightarrow> F (SUP i::nat. M i) = (SUP i. F (M i))\"\n  by (auto simp: sup_continuous_def)\n\nlemma sup_continuous_mono:\n  \"mono F\" if \"sup_continuous F\"\nproof\n  fix A B :: \"'a\"\n  assume \"A \\<le> B\"\n  let ?f = \"\\<lambda>n::nat. if n = 0 then A else B\"\n  from \\<open>A \\<le> B\\<close> have \"incseq ?f\"\n    by (auto intro: monoI)\n  with \\<open>sup_continuous F\\<close> have *: \"F (SUP i. ?f i) = (SUP i. F (?f i))\"\n    by (auto dest: sup_continuousD)\n  from \\<open>A \\<le> B\\<close> have \"B = sup A B\"\n    by (simp add: le_iff_sup)\n  then have \"F B = F (sup A B)\"\n    by simp\n  also have \"\\<dots> = sup (F A) (F B)\"\n    using * by (simp add: if_distrib SUP_nat_binary cong del: SUP_cong)\n  finally show \"F A \\<le> F B\"\n    by (simp add: le_iff_sup)\nqed\n\nlemma [order_continuous_intros]:\n  shows sup_continuous_const: \"sup_continuous (\\<lambda>x. c)\"\n    and sup_continuous_id: \"sup_continuous (\\<lambda>x. x)\"\n    and sup_continuous_apply: \"sup_continuous (\\<lambda>f. f x)\"\n    and sup_continuous_fun: \"(\\<And>s. sup_continuous (\\<lambda>x. P x s)) \\<Longrightarrow> sup_continuous P\"\n    and sup_continuous_If: \"sup_continuous F \\<Longrightarrow> sup_continuous G \\<Longrightarrow> sup_continuous (\\<lambda>f. if C then F f else G f)\"\n  by (auto simp: sup_continuous_def image_comp)\n\nlemma sup_continuous_compose:\n  assumes f: \"sup_continuous f\" and g: \"sup_continuous g\"\n  shows \"sup_continuous (\\<lambda>x. f (g x))\"\n  unfolding sup_continuous_def\nproof safe\n  fix M :: \"nat \\<Rightarrow> 'c\"\n  assume M: \"mono M\"\n  then have \"mono (\\<lambda>i. g (M i))\"\n    using sup_continuous_mono[OF g] by (auto simp: mono_def)\n  with M show \"f (g (Sup (M ` UNIV))) = (SUP i. f (g (M i)))\"\n    by (auto simp: sup_continuous_def g[THEN sup_continuousD] f[THEN sup_continuousD])\nqed\n\nlemma sup_continuous_sup[order_continuous_intros]:\n  \"sup_continuous f \\<Longrightarrow> sup_continuous g \\<Longrightarrow> sup_continuous (\\<lambda>x. sup (f x) (g x))\"\n  by (simp add: sup_continuous_def ccSUP_sup_distrib)\n\nlemma sup_continuous_inf[order_continuous_intros]:\n  fixes P Q :: \"'a :: countable_complete_lattice \\<Rightarrow> 'b :: countable_complete_distrib_lattice\"\n  assumes P: \"sup_continuous P\" and Q: \"sup_continuous Q\"\n  shows \"sup_continuous (\\<lambda>x. inf (P x) (Q x))\"\n  unfolding sup_continuous_def\nproof (safe intro!: antisym)\n  fix M :: \"nat \\<Rightarrow> 'a\" assume M: \"incseq M\"\n  have \"inf (P (SUP i. M i)) (Q (SUP i. M i)) \\<le> (SUP j i. inf (P (M i)) (Q (M j)))\"\n    by (simp add: sup_continuousD[OF P M] sup_continuousD[OF Q M] inf_ccSUP ccSUP_inf)\n  also have \"\\<dots> \\<le> (SUP i. inf (P (M i)) (Q (M i)))\"\n  proof (intro ccSUP_least)\n    fix i j from M assms[THEN sup_continuous_mono] show \"inf (P (M i)) (Q (M j)) \\<le> (SUP i. inf (P (M i)) (Q (M i)))\"\n      by (intro ccSUP_upper2[of _ \"sup i j\"] inf_mono) (auto simp: mono_def)\n  qed auto\n  finally show \"inf (P (SUP i. M i)) (Q (SUP i. M i)) \\<le> (SUP i. inf (P (M i)) (Q (M i)))\" .\n\n  show \"(SUP i. inf (P (M i)) (Q (M i))) \\<le> inf (P (SUP i. M i)) (Q (SUP i. M i))\"\n    unfolding sup_continuousD[OF P M] sup_continuousD[OF Q M] by (intro ccSUP_least inf_mono ccSUP_upper) auto\nqed\n\nlemma sup_continuous_and[order_continuous_intros]:\n  \"sup_continuous P \\<Longrightarrow> sup_continuous Q \\<Longrightarrow> sup_continuous (\\<lambda>x. P x \\<and> Q x)\"\n  using sup_continuous_inf[of P Q] by simp\n\nlemma sup_continuous_or[order_continuous_intros]:\n  \"sup_continuous P \\<Longrightarrow> sup_continuous Q \\<Longrightarrow> sup_continuous (\\<lambda>x. P x \\<or> Q x)\"\n  by (auto simp: sup_continuous_def)\n\nlemma sup_continuous_lfp:\n  assumes \"sup_continuous F\" shows \"lfp F = (SUP i. (F ^^ i) bot)\" (is \"lfp F = ?U\")\nproof (rule antisym)\n  note mono = sup_continuous_mono[OF \\<open>sup_continuous F\\<close>]\n  show \"?U \\<le> lfp F\"\n  proof (rule SUP_least)\n    fix i show \"(F ^^ i) bot \\<le> lfp F\"\n    proof (induct i)\n      case (Suc i)\n      have \"(F ^^ Suc i) bot = F ((F ^^ i) bot)\" by simp\n      also have \"\\<dots> \\<le> F (lfp F)\" by (rule monoD[OF mono Suc])\n      also have \"\\<dots> = lfp F\" by (simp add: lfp_fixpoint[OF mono])\n      finally show ?case .\n    qed simp\n  qed\n  show \"lfp F \\<le> ?U\"\n  proof (rule lfp_lowerbound)\n    have \"mono (\\<lambda>i::nat. (F ^^ i) bot)\"\n    proof -\n      { fix i::nat have \"(F ^^ i) bot \\<le> (F ^^ (Suc i)) bot\"\n        proof (induct i)\n          case 0 show ?case by simp\n        next\n          case Suc thus ?case using monoD[OF mono Suc] by auto\n        qed }\n      thus ?thesis by (auto simp add: mono_iff_le_Suc)\n    qed\n    hence \"F ?U = (SUP i. (F ^^ Suc i) bot)\"\n      using \\<open>sup_continuous F\\<close> by (simp add: sup_continuous_def)\n    also have \"\\<dots> \\<le> ?U\"\n      by (fast intro: SUP_least SUP_upper)\n    finally show \"F ?U \\<le> ?U\" .\n  qed\nqed\n\nlemma lfp_transfer_bounded:\n  assumes P: \"P bot\" \"\\<And>x. P x \\<Longrightarrow> P (f x)\" \"\\<And>M. (\\<And>i. P (M i)) \\<Longrightarrow> P (SUP i::nat. M i)\"\n  assumes \\<alpha>: \"\\<And>M. mono M \\<Longrightarrow> (\\<And>i::nat. P (M i)) \\<Longrightarrow> \\<alpha> (SUP i. M i) = (SUP i. \\<alpha> (M i))\"\n  assumes f: \"sup_continuous f\" and g: \"sup_continuous g\"\n  assumes [simp]: \"\\<And>x. P x \\<Longrightarrow> x \\<le> lfp f \\<Longrightarrow> \\<alpha> (f x) = g (\\<alpha> x)\"\n  assumes g_bound: \"\\<And>x. \\<alpha> bot \\<le> g x\"\n  shows \"\\<alpha> (lfp f) = lfp g\"\nproof (rule antisym)\n  note mono_g = sup_continuous_mono[OF g]\n  note mono_f = sup_continuous_mono[OF f]\n  have lfp_bound: \"\\<alpha> bot \\<le> lfp g\"\n    by (subst lfp_unfold[OF mono_g]) (rule g_bound)\n\n  have P_pow: \"P ((f ^^ i) bot)\" for i\n    by (induction i) (auto intro!: P)\n  have incseq_pow: \"mono (\\<lambda>i. (f ^^ i) bot)\"\n    unfolding mono_iff_le_Suc\n  proof\n    fix i show \"(f ^^ i) bot \\<le> (f ^^ (Suc i)) bot\"\n    proof (induct i)\n      case Suc thus ?case using monoD[OF sup_continuous_mono[OF f] Suc] by auto\n    qed (simp add: le_fun_def)\n  qed\n  have P_lfp: \"P (lfp f)\"\n    using P_pow unfolding sup_continuous_lfp[OF f] by (auto intro!: P)\n\n  have iter_le_lfp: \"(f ^^ n) bot \\<le> lfp f\" for n\n    apply (induction n)\n    apply simp\n    apply (subst lfp_unfold[OF mono_f])\n    apply (auto intro!: monoD[OF mono_f])\n    done\n\n  have \"\\<alpha> (lfp f) = (SUP i. \\<alpha> ((f^^i) bot))\"\n    unfolding sup_continuous_lfp[OF f] using incseq_pow P_pow by (rule \\<alpha>)\n  also have \"\\<dots> \\<le> lfp g\"\n  proof (rule SUP_least)\n    fix i show \"\\<alpha> ((f^^i) bot) \\<le> lfp g\"\n    proof (induction i)\n      case (Suc n) then show ?case\n        by (subst lfp_unfold[OF mono_g]) (simp add: monoD[OF mono_g] P_pow iter_le_lfp)\n    qed (simp add: lfp_bound)\n  qed\n  finally show \"\\<alpha> (lfp f) \\<le> lfp g\" .\n\n  show \"lfp g \\<le> \\<alpha> (lfp f)\"\n  proof (induction rule: lfp_ordinal_induct[OF mono_g])\n    case (1 S) then show ?case\n      by (subst lfp_unfold[OF sup_continuous_mono[OF f]])\n         (simp add: monoD[OF mono_g] P_lfp)\n  qed (auto intro: Sup_least)\nqed\n\nlemma lfp_transfer:\n  \"sup_continuous \\<alpha> \\<Longrightarrow> sup_continuous f \\<Longrightarrow> sup_continuous g \\<Longrightarrow>\n    (\\<And>x. \\<alpha> bot \\<le> g x) \\<Longrightarrow> (\\<And>x. x \\<le> lfp f \\<Longrightarrow> \\<alpha> (f x) = g (\\<alpha> x)) \\<Longrightarrow> \\<alpha> (lfp f) = lfp g\"\n  by (rule lfp_transfer_bounded[where P=top]) (auto dest: sup_continuousD)\n\ndefinition\n  inf_continuous :: \"('a::countable_complete_lattice \\<Rightarrow> 'b::countable_complete_lattice) \\<Rightarrow> bool\"\nwhere\n  \"inf_continuous F \\<longleftrightarrow> (\\<forall>M::nat \\<Rightarrow> 'a. antimono M \\<longrightarrow> F (INF i. M i) = (INF i. F (M i)))\"\n\nlemma inf_continuousD: \"inf_continuous F \\<Longrightarrow> antimono M \\<Longrightarrow> F (INF i::nat. M i) = (INF i. F (M i))\"\n  by (auto simp: inf_continuous_def)\n\nlemma inf_continuous_mono:\n  \"mono F\" if \"inf_continuous F\"\nproof\n  fix A B :: \"'a\"\n  assume \"A \\<le> B\"\n  let ?f = \"\\<lambda>n::nat. if n = 0 then B else A\"\n  from \\<open>A \\<le> B\\<close> have \"decseq ?f\"\n    by (auto intro: antimonoI)\n  with \\<open>inf_continuous F\\<close> have *: \"F (INF i. ?f i) = (INF i. F (?f i))\"\n    by (auto dest: inf_continuousD)\n  from \\<open>A \\<le> B\\<close> have \"A = inf B A\"\n    by (simp add: inf.absorb_iff2)\n  then have \"F A = F (inf B A)\"\n    by simp\n  also have \"\\<dots> = inf (F B) (F A)\"\n    using * by (simp add: if_distrib INF_nat_binary cong del: INF_cong)\n  finally show \"F A \\<le> F B\"\n    by (simp add: inf.absorb_iff2)\nqed\n\nlemma [order_continuous_intros]:\n  shows inf_continuous_const: \"inf_continuous (\\<lambda>x. c)\"\n    and inf_continuous_id: \"inf_continuous (\\<lambda>x. x)\"\n    and inf_continuous_apply: \"inf_continuous (\\<lambda>f. f x)\"\n    and inf_continuous_fun: \"(\\<And>s. inf_continuous (\\<lambda>x. P x s)) \\<Longrightarrow> inf_continuous P\"\n    and inf_continuous_If: \"inf_continuous F \\<Longrightarrow> inf_continuous G \\<Longrightarrow> inf_continuous (\\<lambda>f. if C then F f else G f)\"\n  by (auto simp: inf_continuous_def image_comp)\n\nlemma inf_continuous_inf[order_continuous_intros]:\n  \"inf_continuous f \\<Longrightarrow> inf_continuous g \\<Longrightarrow> inf_continuous (\\<lambda>x. inf (f x) (g x))\"\n  by (simp add: inf_continuous_def ccINF_inf_distrib)\n\nlemma inf_continuous_sup[order_continuous_intros]:\n  fixes P Q :: \"'a :: countable_complete_lattice \\<Rightarrow> 'b :: countable_complete_distrib_lattice\"\n  assumes P: \"inf_continuous P\" and Q: \"inf_continuous Q\"\n  shows \"inf_continuous (\\<lambda>x. sup (P x) (Q x))\"\n  unfolding inf_continuous_def\nproof (safe intro!: antisym)\n  fix M :: \"nat \\<Rightarrow> 'a\" assume M: \"decseq M\"\n  show \"sup (P (INF i. M i)) (Q (INF i. M i)) \\<le> (INF i. sup (P (M i)) (Q (M i)))\"\n    unfolding inf_continuousD[OF P M] inf_continuousD[OF Q M] by (intro ccINF_greatest sup_mono ccINF_lower) auto\n\n  have \"(INF i. sup (P (M i)) (Q (M i))) \\<le> (INF j i. sup (P (M i)) (Q (M j)))\"\n  proof (intro ccINF_greatest)\n    fix i j from M assms[THEN inf_continuous_mono] show \"sup (P (M i)) (Q (M j)) \\<ge> (INF i. sup (P (M i)) (Q (M i)))\"\n      by (intro ccINF_lower2[of _ \"sup i j\"] sup_mono) (auto simp: mono_def antimono_def)\n  qed auto\n  also have \"\\<dots> \\<le> sup (P (INF i. M i)) (Q (INF i. M i))\"\n    by (simp add: inf_continuousD[OF P M] inf_continuousD[OF Q M] ccINF_sup sup_ccINF)\n  finally show \"sup (P (INF i. M i)) (Q (INF i. M i)) \\<ge> (INF i. sup (P (M i)) (Q (M i)))\" .\nqed\n\nlemma inf_continuous_and[order_continuous_intros]:\n  \"inf_continuous P \\<Longrightarrow> inf_continuous Q \\<Longrightarrow> inf_continuous (\\<lambda>x. P x \\<and> Q x)\"\n  using inf_continuous_inf[of P Q] by simp\n\nlemma inf_continuous_or[order_continuous_intros]:\n  \"inf_continuous P \\<Longrightarrow> inf_continuous Q \\<Longrightarrow> inf_continuous (\\<lambda>x. P x \\<or> Q x)\"\n  using inf_continuous_sup[of P Q] by simp\n\nlemma inf_continuous_compose:\n  assumes f: \"inf_continuous f\" and g: \"inf_continuous g\"\n  shows \"inf_continuous (\\<lambda>x. f (g x))\"\n  unfolding inf_continuous_def\nproof safe\n  fix M :: \"nat \\<Rightarrow> 'c\"\n  assume M: \"antimono M\"\n  then have \"antimono (\\<lambda>i. g (M i))\"\n    using inf_continuous_mono[OF g] by (auto simp: mono_def antimono_def)\n  with M show \"f (g (Inf (M ` UNIV))) = (INF i. f (g (M i)))\"\n    by (auto simp: inf_continuous_def g[THEN inf_continuousD] f[THEN inf_continuousD])\nqed\n\nlemma inf_continuous_gfp:\n  assumes \"inf_continuous F\" shows \"gfp F = (INF i. (F ^^ i) top)\" (is \"gfp F = ?U\")\nproof (rule antisym)\n  note mono = inf_continuous_mono[OF \\<open>inf_continuous F\\<close>]\n  show \"gfp F \\<le> ?U\"\n  proof (rule INF_greatest)\n    fix i show \"gfp F \\<le> (F ^^ i) top\"\n    proof (induct i)\n      case (Suc i)\n      have \"gfp F = F (gfp F)\" by (simp add: gfp_fixpoint[OF mono])\n      also have \"\\<dots> \\<le> F ((F ^^ i) top)\" by (rule monoD[OF mono Suc])\n      also have \"\\<dots> = (F ^^ Suc i) top\" by simp\n      finally show ?case .\n    qed simp\n  qed\n  show \"?U \\<le> gfp F\"\n  proof (rule gfp_upperbound)\n    have *: \"antimono (\\<lambda>i::nat. (F ^^ i) top)\"\n    proof -\n      { fix i::nat have \"(F ^^ Suc i) top \\<le> (F ^^ i) top\"\n        proof (induct i)\n          case 0 show ?case by simp\n        next\n          case Suc thus ?case using monoD[OF mono Suc] by auto\n        qed }\n      thus ?thesis by (auto simp add: antimono_iff_le_Suc)\n    qed\n    have \"?U \\<le> (INF i. (F ^^ Suc i) top)\"\n      by (fast intro: INF_greatest INF_lower)\n    also have \"\\<dots> \\<le> F ?U\"\n      by (simp add: inf_continuousD \\<open>inf_continuous F\\<close> *)\n    finally show \"?U \\<le> F ?U\" .\n  qed\nqed\n\nlemma gfp_transfer:\n  assumes \\<alpha>: \"inf_continuous \\<alpha>\" and f: \"inf_continuous f\" and g: \"inf_continuous g\"\n  assumes [simp]: \"\\<alpha> top = top\" \"\\<And>x. \\<alpha> (f x) = g (\\<alpha> x)\"\n  shows \"\\<alpha> (gfp f) = gfp g\"\nproof -\n  have \"\\<alpha> (gfp f) = (INF i. \\<alpha> ((f^^i) top))\"\n    unfolding inf_continuous_gfp[OF f] by (intro f \\<alpha> inf_continuousD antimono_funpow inf_continuous_mono)\n  moreover have \"\\<alpha> ((f^^i) top) = (g^^i) top\" for i\n    by (induction i; simp)\n  ultimately show ?thesis\n    unfolding inf_continuous_gfp[OF g] by simp\nqed\n\nlemma gfp_transfer_bounded:\n  assumes P: \"P (f top)\" \"\\<And>x. P x \\<Longrightarrow> P (f x)\" \"\\<And>M. antimono M \\<Longrightarrow> (\\<And>i. P (M i)) \\<Longrightarrow> P (INF i::nat. M i)\"\n  assumes \\<alpha>: \"\\<And>M. antimono M \\<Longrightarrow> (\\<And>i::nat. P (M i)) \\<Longrightarrow> \\<alpha> (INF i. M i) = (INF i. \\<alpha> (M i))\"\n  assumes f: \"inf_continuous f\" and g: \"inf_continuous g\"\n  assumes [simp]: \"\\<And>x. P x \\<Longrightarrow> \\<alpha> (f x) = g (\\<alpha> x)\"\n  assumes g_bound: \"\\<And>x. g x \\<le> \\<alpha> (f top)\"\n  shows \"\\<alpha> (gfp f) = gfp g\"\nproof (rule antisym)\n  note mono_g = inf_continuous_mono[OF g]\n\n  have P_pow: \"P ((f ^^ i) (f top))\" for i\n    by (induction i) (auto intro!: P)\n\n  have antimono_pow: \"antimono (\\<lambda>i. (f ^^ i) top)\"\n    unfolding antimono_iff_le_Suc\n  proof\n    fix i show \"(f ^^ Suc i) top \\<le> (f ^^ i) top\"\n    proof (induct i)\n      case Suc thus ?case using monoD[OF inf_continuous_mono[OF f] Suc] by auto\n    qed (simp add: le_fun_def)\n  qed\n  have antimono_pow2: \"antimono (\\<lambda>i. (f ^^ i) (f top))\"\n  proof\n    show \"x \\<le> y \\<Longrightarrow> (f ^^ y) (f top) \\<le> (f ^^ x) (f top)\" for x y\n      using antimono_pow[THEN antimonoD, of \"Suc x\" \"Suc y\"]\n      unfolding funpow_Suc_right by simp\n  qed\n\n  have gfp_f: \"gfp f = (INF i. (f ^^ i) (f top))\"\n    unfolding inf_continuous_gfp[OF f]\n  proof (rule INF_eq)\n    show \"\\<exists>j\\<in>UNIV. (f ^^ j) (f top) \\<le> (f ^^ i) top\" for i\n      by (intro bexI[of _ \"i - 1\"]) (auto simp: diff_Suc funpow_Suc_right simp del: funpow.simps(2) split: nat.split)\n    show \"\\<exists>j\\<in>UNIV. (f ^^ j) top \\<le> (f ^^ i) (f top)\" for i\n      by (intro bexI[of _ \"Suc i\"]) (auto simp: funpow_Suc_right simp del: funpow.simps(2))\n  qed\n\n  have P_lfp: \"P (gfp f)\"\n    unfolding gfp_f by (auto intro!: P P_pow antimono_pow2)\n\n  have \"\\<alpha> (gfp f) = (INF i. \\<alpha> ((f^^i) (f top)))\"\n    unfolding gfp_f by (rule \\<alpha>) (auto intro!: P_pow antimono_pow2)\n  also have \"\\<dots> \\<ge> gfp g\"\n  proof (rule INF_greatest)\n    fix i show \"gfp g \\<le> \\<alpha> ((f^^i) (f top))\"\n    proof (induction i)\n      case (Suc n) then show ?case\n        by (subst gfp_unfold[OF mono_g]) (simp add: monoD[OF mono_g] P_pow)\n    next\n      case 0\n      have \"gfp g \\<le> \\<alpha> (f top)\"\n        by (subst gfp_unfold[OF mono_g]) (rule g_bound)\n      then show ?case\n        by simp\n    qed\n  qed\n  finally show \"gfp g \\<le> \\<alpha> (gfp f)\" .\n\n  show \"\\<alpha> (gfp f) \\<le> gfp g\"\n  proof (induction rule: gfp_ordinal_induct[OF mono_g])\n    case (1 S) then show ?case\n      by (subst gfp_unfold[OF inf_continuous_mono[OF f]])\n         (simp add: monoD[OF mono_g] P_lfp)\n  qed (auto intro: Inf_greatest)\nqed\n\nsubsubsection \\<open>Least fixed points in countable complete lattices\\<close>\n\ndefinition (in countable_complete_lattice) cclfp :: \"('a \\<Rightarrow> 'a) \\<Rightarrow> 'a\"\n  where \"cclfp f = (SUP i. (f ^^ i) bot)\"\n\nlemma cclfp_unfold:\n  assumes \"sup_continuous F\" shows \"cclfp F = F (cclfp F)\"\nproof -\n  have \"cclfp F = (SUP i. F ((F ^^ i) bot))\"\n    unfolding cclfp_def\n    by (subst UNIV_nat_eq) (simp add: image_comp)\n  also have \"\\<dots> = F (cclfp F)\"\n    unfolding cclfp_def\n    by (intro sup_continuousD[symmetric] assms mono_funpow sup_continuous_mono)\n  finally show ?thesis .\nqed\n\nlemma cclfp_lowerbound: assumes f: \"mono f\" and A: \"f A \\<le> A\" shows \"cclfp f \\<le> A\"\n  unfolding cclfp_def\nproof (intro ccSUP_least)\n  fix i show \"(f ^^ i) bot \\<le> A\"\n  proof (induction i)\n    case (Suc i) from monoD[OF f this] A show ?case\n      by auto\n  qed simp\nqed simp\n\nlemma cclfp_transfer:\n  assumes \"sup_continuous \\<alpha>\" \"mono f\"\n  assumes \"\\<alpha> bot = bot\" \"\\<And>x. \\<alpha> (f x) = g (\\<alpha> x)\"\n  shows \"\\<alpha> (cclfp f) = cclfp g\"\nproof -\n  have \"\\<alpha> (cclfp f) = (SUP i. \\<alpha> ((f ^^ i) bot))\"\n    unfolding cclfp_def by (intro sup_continuousD assms mono_funpow sup_continuous_mono)\n  moreover have \"\\<alpha> ((f ^^ i) bot) = (g ^^ i) bot\" for i\n    by (induction i) (simp_all add: assms)\n  ultimately show ?thesis\n    by (simp add: cclfp_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/Order_Continuity.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.86153820232079, "lm_q2_score": 0.819893340314393, "lm_q1q2_score": 0.7063694345092498}}
{"text": "theory GabrielaLimonta\nimports Main\nbegin\n\n(* Pumping Lemma for regular languages *)\n\n(* We start by formalizing a representation of a DFA, the states will be represented by nat numbers.\n   The delta function has the type \"'a \\<Rightarrow> state \\<Rightarrow> state\".\n   A DFA has the following type: \"state set \\<Rightarrow> state \\<Rightarrow> state set \\<Rightarrow> ('a \\<Rightarrow> state \\<Rightarrow> state)\", this\n   represents the states of the DFA, the initial state, the final states and the delta function. *)\ntype_synonym state = nat\n\n(* the states for our DFA are identified by nat and a word is a list of nat numbers, a language\n   represented by the DFA is a set of nat list *)\n\n(* A word in a language is represented by a list. The language represented by a DFA is a set of lists.\n   The function consume takes a word and indicates the state the DFA is after consuming that word. *)\nfun consume :: \"'a list \\<Rightarrow> ('a \\<Rightarrow> state \\<Rightarrow> state) \\<Rightarrow> state set \\<Rightarrow> state \\<Rightarrow> state\" where\n  \"consume [] \\<delta> Q = id\" |\n  \"consume (a#w) \\<delta> Q = consume w \\<delta> Q \\<circ> \\<delta> a\"\n\nvalue \"consume [] (\\<lambda>x y. y+1) {0,1,2} 0\"\nvalue \"consume [1,2,3] (\\<lambda>x y. y+1) {0,1,2} 0\"\n\n(* The language represented by a DFA is the set of words w that allow us to go from the initial\n   state to one of the final states *)\nfun language :: \"state set \\<Rightarrow> state \\<Rightarrow> state set \\<Rightarrow> ('a \\<Rightarrow> state \\<Rightarrow> state) \\<Rightarrow> 'a list set\" where\n  \"language Q q\\<^sub>0 q\\<^sub>f \\<delta> = {w. consume w \\<delta> Q q\\<^sub>0 \\<in> q\\<^sub>f}\"\n\n(* This is an example for the abstraction of a DFA *)\ndatatype alphabet = a | b\n\nfun lang_ab :: \"alphabet \\<Rightarrow> state \\<Rightarrow> state\" where\n  \"lang_ab a s = (if s = 0 then 0 else 2)\" |\n  \"lang_ab b s = (if s = 0 \\<or> s = 1 then 1 else 2)\"\n\nvalue \"consume [a,a,a,a,a,a,a,a,b] lang_ab {0,1,2} 0 \\<in> {1}\"\nvalue \"consume [a,a,a,a,a,b,a,a,b] lang_ab {0,1,2} 0 \\<in> {1}\"\n\n(* A DFA is correctly formed when the set of states is finite, the initial state is in the set of\n   states the final states are a subset of the states and that the delta function always yields as\n   a result a state that belongs to the states of the DFA *)\ndefinition dfa :: \"state set \\<Rightarrow> state \\<Rightarrow> state set \\<Rightarrow> ('a \\<Rightarrow> state \\<Rightarrow> state) \\<Rightarrow> bool\" where\n  \"dfa Q q\\<^sub>0 q\\<^sub>f \\<delta> \\<equiv> finite Q \\<and> q\\<^sub>0 \\<in> Q \\<and> q\\<^sub>f \\<subseteq> Q \\<and> (\\<forall> a q. q \\<in> Q \\<and> \\<delta> a q \\<in> Q )\"\n\n(* We define injectivity for further use in the proof *)\ndefinition injective :: \"('a \\<Rightarrow> 'b) \\<Rightarrow> 'a set \\<Rightarrow> bool\" where\n  \"injective f A \\<longleftrightarrow> (\\<forall> x \\<in> A. \\<forall> y \\<in> A . f x = f y \\<longrightarrow> x = y)\"\n\n(* Auxiliary lemma to proove pidgeonhole: Assuming a set A is finite then a function f is\n   is injective over the set A iff the cardinality of the image of f applied to A is equal to\n   the cardinality of A *)\nlemma cardi: \"finite A \\<Longrightarrow> injective f A \\<longleftrightarrow> card {y. (\\<exists>x \\<in> A. y = f x)} = card A\"\nsorry\n\n(* Proof of the pidgeonhole principle *)\nlemma pigeonhole: \"finite A \\<Longrightarrow> finite B \\<Longrightarrow> card B < card A \\<Longrightarrow> (\\<forall> x \\<in> A. f x \\<in> B)\n  \\<Longrightarrow> (\\<exists> x y. x \\<noteq> y \\<and> f x = f y \\<and> x \\<in> A \\<and> y \\<in> A)\"\nproof -\n  assume \"(\\<forall>x \\<in> A. f x \\<in> B)\"\n  from this have a: \"{y. (\\<exists>x \\<in> A. y = f x)} \\<subseteq> B\" by auto\n  assume \"finite B\"\n  then have b: \"card {y. (\\<exists>x \\<in> A. y = f x)} \\<le> card B\" using a and card_mono by auto\n  assume \"card B < card A\"\n  then have \"card {y. (\\<exists>x \\<in> A. y = f x)} < card A\" using b by auto\n  then have c: \"card {y. (\\<exists>x \\<in> A. y = f x)} \\<noteq> card A\" by auto\n  assume \"finite A\"\n  then have \"\\<not> injective f A\" using cardi and c by auto\n  thus ?thesis using injective_def by blast\nqed\n\n(* We define a function pump that is meant to \"pump\" a word a k number of times, that is, it yields\n  the word repeated a k number of times. *)\nfun pump :: \"nat => 'a list \\<Rightarrow> 'a list\" where\n  \"pump 0 y = []\" |\n  \"pump k y = pump (k - 1) y@y\"\n\n(* Finally the formalization of the pumping lemma, this lemma is usually used to proof that some \n   language is not a regular language. *)\nlemma pumping: \n  assumes \"dfa Q q\\<^sub>0 q\\<^sub>f \\<delta>\"\n  shows \"\\<exists> p. p\\<ge>1 \\<and> (\\<forall>w. w \\<in> (language Q q\\<^sub>0 q\\<^sub>f \\<delta>) \\<and> length w \\<ge> p\n        \\<longrightarrow> (\\<exists> x y z. w = x@y@z \\<and> length y \\<ge> 1 \\<and> length (x@y) \\<le> p \\<and> (\\<forall>i. i\\<ge>0 \n            \\<longrightarrow> (x @ (pump i y) @ z) \\<in> (language Q q\\<^sub>0 q\\<^sub>f \\<delta>))))\"\nsorry\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/Exercise10/GabrielaLimonta.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772384450967, "lm_q2_score": 0.8080672066194945, "lm_q1q2_score": 0.706313152440011}}
{"text": "theory Sat\n  imports IMP\nbegin\n\nfun Sat :: \"bexp \\<Rightarrow> bool\" where\n\"Sat (Bc b) = b\" |\n\"Sat (Not b) = (\\<exists>s. \\<not> bval b s)\" |\n\"Sat (And a b) = (\\<exists>s. bval a s \\<and> bval b s)\" |\n\"Sat (Less a b) = (\\<exists>s. aval a s < aval b s)\"\n\ntheorem sat_equiv: \"Sat a \\<longleftrightarrow> (\\<exists>s. bval a s)\"\n  apply (induction a)\n     apply auto\n  done\n\ntheorem unsat_contradiction: \"\\<not> Sat (And a (Not a))\"\n  by simp\n\ntheorem sat_taut_incl: \"(\\<forall>s. bval a s) \\<Longrightarrow> Sat b \\<Longrightarrow> Sat (And a b)\"\n  apply (induction b arbitrary: a)\n     apply simp_all\n  done\n\ntheorem sat_split: \"Sat (And a b) \\<Longrightarrow> Sat a \\<and> Sat b\"\nproof -\n  assume \"Sat (And a b)\"\n  hence \"\\<exists>s. bval a s \\<and> bval b s\" by simp\n  hence \"(\\<exists>s. bval a s) \\<and> (\\<exists>s. bval b s)\" by auto\n  thus ?thesis using sat_equiv by simp\nqed\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/ch7/Sat.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9086179068309441, "lm_q2_score": 0.7772998663336158, "lm_q1q2_score": 0.7062685775280226}}
{"text": "(*  Title:       Examples of hybrid systems verifications\n    Author:      Jonathan Juli\u00e1n Huerta y Munive, 2019\n    Maintainer:  Jonathan Juli\u00e1n Huerta y Munive <jjhuertaymunive1@sheffield.ac.uk>\n*)\n\nsubsection \\<open> Examples \\<close>\n\ntext \\<open> We prove partial correctness specifications of some hybrid systems with our\nrecently described verification components.\\<close>\n\ntheory HS_VC_MKA_Examples_rel\n  imports HS_VC_MKA_rel\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\n  else - s$1 * sin t + s$2 * cos t)\"\n\n\\<comment> \\<open>Verified by providing dynamics. \\<close>\n\nlemma pendulum_dyn:\n  \"\\<lceil>\\<lambda>s. r\\<^sup>2 = (s$1)\\<^sup>2 + (s$2)\\<^sup>2\\<rceil> \\<le> wp (EVOL \\<phi> G T) \\<lceil>\\<lambda>s. r\\<^sup>2 = (s$1)\\<^sup>2 + (s$2)\\<^sup>2\\<rceil>\"\n  by simp\n\n\\<comment> \\<open>Verified with differential invariants. \\<close>\n\nlemma pendulum_inv:\n  \"\\<lceil>\\<lambda>s. r\\<^sup>2 = (s$1)\\<^sup>2 + (s$2)\\<^sup>2\\<rceil> \\<le> wp (x\\<acute>= f & G) \\<lceil>\\<lambda>s. r\\<^sup>2 = (s$1)\\<^sup>2 + (s$2)\\<^sup>2\\<rceil>\"\n  by (auto intro!: poly_derivatives diff_invariant_rules)\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:\n  \"\\<lceil>\\<lambda>s. r\\<^sup>2 = (s$1)\\<^sup>2 + (s$2)\\<^sup>2\\<rceil> \\<le> wp (x\\<acute>= f & G) \\<lceil>\\<lambda>s. r\\<^sup>2 = (s$1)\\<^sup>2 + (s$2)\\<^sup>2\\<rceil>\"\n  by (simp add: local_flow.wp_g_ode[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 assigntment that\nflips the velocity, thus it is a completely elastic collision with the ground. We use @{text \"s$1\"}\nto ball's height and @{text \"s$2\"} for its velocity. We prove that the ball remains above ground\nand 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 bouncing_ball_inv:\n  fixes h::real\n  shows \"g < 0 \\<Longrightarrow> h \\<ge> 0 \\<Longrightarrow> \\<lceil>\\<lambda>s. s$1 = h \\<and> s$2 = 0\\<rceil> \\<le>\n  wp\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  ) \\<lceil>\\<lambda>s. 0 \\<le> s$1 \\<and> s$1 \\<le> h\\<rceil>\"\n  apply(rule wp_loopI, simp_all, force simp: bb_real_arith)\n  by (rule wp_g_odei) (auto intro!: poly_derivatives diff_invariant_rules)\n\n\\<comment> \\<open>Verified by providing 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> * (g * \\<tau> + v) + 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, hide_lams) 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, hide_lams) 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> * (g * \\<tau> + v) + v * (g * \\<tau> + v)) = 0\"\n    by (simp add: monoid_mult_class.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> * (g * \\<tau> + v) + 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:\n  fixes h::real\n  assumes \"g < 0\" and \"h \\<ge> 0\"\n  shows \"g < 0 \\<Longrightarrow> h \\<ge> 0 \\<Longrightarrow>\n  \\<lceil>\\<lambda>s. s$1 = h \\<and> s$2 = 0\\<rceil> \\<le> wp\n    (LOOP\n      ((EVOL (\\<phi> g) (\\<lambda>s. 0 \\<le> s$1) 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  \\<lceil>\\<lambda>s. 0 \\<le> s$1 \\<and> s$1 \\<le> h\\<rceil>\"\n  by (rule wp_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:\n  fixes h::real\n  assumes \"g < 0\" and \"h \\<ge> 0\"\n  shows \"g < 0 \\<Longrightarrow> h \\<ge> 0 \\<Longrightarrow>\n  \\<lceil>\\<lambda>s. s$1 = h \\<and> s$2 = 0\\<rceil> \\<le> wp\n    (LOOP\n      ((x\\<acute>= f g & (\\<lambda> s. s$1 \\<ge> 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  \\<lceil>\\<lambda>s. 0 \\<le> s$1 \\<and> s$1 \\<le> h\\<rceil>\"\n  apply(rule wp_loopI, simp_all add: local_flow.wp_g_ode[OF local_flow_ball])\n  by (auto simp: bb_real_arith)\n\nno_notation fball (\"f\")\n        and ball_flow (\"\\<phi>\")\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_all 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_ivl[OF local_flow_temp _ UNIV_I]\n\nlemma thermostat:\n  assumes \"a > 0\" and \"0 \\<le> t\" and \"0 < Tmin\" and \"Tmax < L\"\n  shows \"\\<lceil>\\<lambda>s. Tmin \\<le> s$1 \\<and> s$1 \\<le> Tmax \\<and> s$4 = 0\\<rceil> \\<le> wp\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) on {0..t} UNIV @ 0)\n    ELSE (x\\<acute>=(f a L) & (\\<lambda>s. s$2 \\<le> - (ln ((L-Tmax)/(L-s$3)))/a) on {0..t} UNIV @ 0)) )\n  INV (\\<lambda>s. Tmin \\<le>s$1 \\<and> s$1 \\<le> Tmax \\<and> (s$4 = 0 \\<or> s$4 = 1)))\n  \\<lceil>\\<lambda>s. Tmin \\<le> s$1 \\<and> s$1 \\<le> Tmax\\<rceil>\"\n  apply(rule wp_loopI, simp_all add: fbox_temp_dyn[OF assms(1,2)])\n  using temp_dyn_up_real_arith[OF assms(1) _ _ assms(4), of Tmin]\n    and temp_dyn_down_real_arith[OF assms(1,3), of _ Tmax] by auto\n\nno_notation temp_vec_field (\"f\")\n        and temp_flow (\"\\<phi>\")\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/Hybrid_Systems_VCs/ModalKleeneAlgebra/HS_VC_MKA_Examples_rel.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8688267796346599, "lm_q2_score": 0.8128673269042767, "lm_q1q2_score": 0.7062409019044771}}
{"text": "theory TestRevList\nimports Main\nbegin\n\nno_notation Nil(\"[]\") and Cons (infixr \"#\" 65) and append (infixr \"@\" 65)\nhide_type list\nhide_const rev\n\ndatatype 'a list = Nil (\"[]\")\n| Cons 'a \"'a list\" (infixr \"#\" 65)\n\nprimrec app :: \"'a list => 'a list =>'a list\" (infixr \"@\" 65)\nwhere\n\"[] @ ys = ys\" |\n\"(x # xs) @ ys = x # (xs @ ys)\"\n\nprimrec rev :: \"'a list => 'a list\" where\n\"rev [] = []\" |\n\"rev (x # xs) = (rev xs) @ (x #[])\"\n\nvalue \"rev (True # False # [])\"\nvalue \"rev (a # b# c# [])\"\n\nlemma app_assoc [simp]: \"(xs @ys) @ zs = xs @(ys @zs)\"\n  apply(induct_tac xs)\n  apply(auto)\n  done\n\nlemma app_Nil [simp]: \"xs @ [] = xs\"\n  apply(induct_tac xs)\n  apply(auto)\n  done\n\nlemma rev_app [simp]: \"rev(xs@ys) = (rev ys) @ (rev xs)\"\n  apply(induct_tac xs)\n   apply(auto)\n  done\n\ntheorem rev_rev [simp]: \"rev(rev xs) = xs\"\n  apply(induct_tac xs)\n  apply(auto)\ndone\n", "meta": {"author": "DengYiping", "repo": "isabelle", "sha": "85ce9bf53b32959b4285b7f06159cf682166853f", "save_path": "github-repos/isabelle/DengYiping-isabelle", "path": "github-repos/isabelle/DengYiping-isabelle/isabelle-85ce9bf53b32959b4285b7f06159cf682166853f/TestRevList.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267830311354, "lm_q2_score": 0.8128673178375735, "lm_q1q2_score": 0.7062408967879664}}
{"text": "section\\<open>Functions\\<close>\ntheory Functions\nimports\n  Bin_Rels\n  Rewrite\n  HOTG.Set_Difference\nbegin\n\nsubsection \\<open>Evaluation of Functions\\<close>\n\ndefinition \"eval S x \\<equiv> THE y. \\<langle>x, y\\<rangle> \\<in> S\"\n\nbundle isa_set_eval_syntax begin notation eval (\"(_`_)\" [999, 1000] 999) end\nbundle no_isa_set_eval_syntax begin no_notation eval (\"_`_\" [999, 1000] 999) end\nunbundle isa_set_eval_syntax\n\nlemma eval_singleton_eq [simp]: \"{\\<langle>x, y\\<rangle>}`x = y\"\n  unfolding eval_def by auto\n\nlemma eval_repl_eq [simp]: \"x \\<in> A \\<Longrightarrow> {\\<langle>a, f a\\<rangle> | a \\<in> A}`x = f x\"\n  unfolding eval_def by auto\n\nlemma cons_eval_eq [simp]:\n  \"x \\<notin> dom A \\<Longrightarrow> (cons \\<langle>x, y\\<rangle> A)`x = y\"\n  unfolding eval_def by auto\n\nlemma cons_eval_eq' [simp]:\n  \"x \\<noteq> y \\<Longrightarrow> (cons \\<langle>y, z\\<rangle> A)`x = A`x\"\n  unfolding eval_def by auto\n\nlemma bin_union_eval_eq_left_eval [simp]:\n  \"x \\<notin> dom B \\<Longrightarrow> (A \\<union> B)`x = A`x\"\n  unfolding eval_def by (auto elim: not_mem_domE)\n\nlemma bin_union_eval_eq_right_eval [simp]:\n  \"x \\<notin> dom A \\<Longrightarrow> (A \\<union> B)`x = B`x\"\n  unfolding eval_def by (auto elim: not_mem_domE)\n\n\nsubsection \\<open>Functional Part of a Set\\<close>\n\ntext \\<open>The following expresses that a set S is a function on A (it need not even be\nrelation elsewhere).\\<close>\n\ndefinition \"function A S \\<equiv> \\<forall>x \\<in> A. \\<exists>!y. \\<langle>x, y\\<rangle> \\<in> S\"\n\n(*TODO: alternative with type constraints rather than set constraints*)\n(* definition \"fu A B \\<equiv> type (\\<lambda>f. \\<forall>x : A. \\<exists>!y. \\<langle>x, y\\<rangle> \\<in> f \\<and> y : B x)\"\ndefinition \"fu3 A B C \\<equiv> fu A (\\<lambda>x. fu (B x) (C x))\" *)\n\nlemma functionI [intro]:\n  assumes \"\\<And>x y y'. \\<lbrakk>x \\<in> A; \\<langle>x, y\\<rangle> \\<in> S; \\<langle>x, y'\\<rangle> \\<in> S\\<rbrakk> \\<Longrightarrow> y = y'\"\n  and \"\\<And>x. x \\<in> A \\<Longrightarrow> \\<exists>y. \\<langle>x, y\\<rangle> \\<in> S\"\n  shows \"function A S\"\n  unfolding function_def by (auto intro: assms)\n\nlemma functionD: \"function A S \\<Longrightarrow> x \\<in> A \\<Longrightarrow> \\<exists>!y. \\<langle>x, y\\<rangle> \\<in> S\"\n  unfolding function_def by auto\n\nlemma function_right_unique:\n  \"\\<lbrakk>function A S; x \\<in> A; S`x = y; S`x = y'\\<rbrakk> \\<Longrightarrow> y = y'\"\n  unfolding function_def by auto\n\nlemma function_pair_eval_mem_if_mem_dom [elim]:\n  \"\\<lbrakk>function A S; x \\<in> A\\<rbrakk> \\<Longrightarrow> \\<langle>x, S`x\\<rangle> \\<in> S\"\n  unfolding eval_def function_def by (rule theI', drule ballD)\n\nlemma function_pair_mem_iff_eval_eq [iff]:\n  \"\\<lbrakk>function A S; x \\<in> A\\<rbrakk> \\<Longrightarrow> \\<langle>x, y\\<rangle> \\<in> S \\<longleftrightarrow> S`x = y\"\n  unfolding function_def eval_def by (auto dest!: ballD intro: theI')\n\nlemma function_mem_domE:\n  assumes \"function A S\"\n  and \"x \\<in> A\"\n  obtains y where \"S`x = y\"\n  using assms by auto\n\nlemma function_empty_dom: \"function {} S\"\n  unfolding function_def by auto\n\n\nsubsection \\<open>Generic Notion of a Function\\<close>\n\ndefinition [typedef]: \"Fun \\<equiv> (\\<lambda>f. function (dom f) f) \\<sqdot> Bin_Rel\"\n\nlemma\n  FunI: \"\\<lbrakk>f : Bin_Rel; function (dom f) f\\<rbrakk> \\<Longrightarrow> f : Fun\" and\n  FunD: \"f : Fun \\<Longrightarrow> function (dom f) f \\<and> f : Bin_Rel\"\n  unfolding Fun_def by auto\n\nlemma FunE [elim]:\n  assumes \"f : Fun\"\n  obtains \"f : Bin_Rel\" \"function (dom f) f\"\n  using assms by (auto dest: FunD)\n\nlemma Fun_right_unique:\n  assumes \"f : Fun\"\n  and \"x \\<in> dom f\"\n  and \"f`x = y\"\n  and \"f`x = y'\"\n  shows \"y = y'\"\nproof -\n  from \\<open>f : Fun\\<close> have \"function (dom f) f\" by (auto dest: FunD)\n  with function_right_unique show \"y = y'\" using assms by auto\nqed\n\nlemma Fun_pair_mem_iff_eval_eq:\n  \"f : Fun \\<Longrightarrow> x \\<in> (dom f) \\<Longrightarrow> \\<langle>x, y\\<rangle> \\<in> f \\<longleftrightarrow> f`x = y\"\n  by auto\n\nlemma Fun_eval_eq_if_pair_mem [simp]:\n  \"\\<lbrakk>f : Fun; \\<langle>x, y\\<rangle> \\<in> f\\<rbrakk> \\<Longrightarrow> f`x = y\"\n  by auto\n\nlemma Fun_fst_snd_eq_pair_if_mem [simp]:\n  \"\\<lbrakk>f : Fun; p \\<in> f\\<rbrakk> \\<Longrightarrow> \\<langle>fst p, snd p\\<rangle> = p\"\n  by auto\n\nlemma Fun_fst_snd_mem_if_mem:\n  \"\\<lbrakk>f : Fun; p \\<in> f\\<rbrakk> \\<Longrightarrow> \\<langle>fst p, snd p\\<rangle> \\<in> f\"\n  by auto\n\nlemma Fun_fst_mem_dom_if_mem:\n  \"\\<lbrakk>f : Fun; p \\<in> f\\<rbrakk> \\<Longrightarrow> fst p \\<in> (dom f)\"\n  by auto\n\nlemma Fun_eval_fst_eq [simp]:\n  \"\\<lbrakk>f : Fun; p \\<in> f\\<rbrakk> \\<Longrightarrow> f`(fst p) = snd p\"\n  by auto\n\nlemma Fun_mem_domE:\n  assumes \"f : Fun\"\n  and \"x \\<in> dom f\"\n  obtains y where \"f`x = y\"\n  using assms by auto\n\nlemma Fun_memE [elim]:\n  assumes \"f : Fun\"\n  and \"p \\<in> f\"\n  obtains x y where \"p = \\<langle>x, y\\<rangle>\" \"f`x = y\"\n  using assms by (auto dest: Fun_fst_snd_eq_pair_if_mem[symmetric])\n\nsubsection \\<open>Functions with Explicit Domain and Codomain\\<close>\n\ndefinition [typedef]: \"Dep_Function A B \\<equiv> function A \\<sqdot> Subset (\\<Sum>x \\<in> A. (B x))\"\n\nabbreviation \"Function A B \\<equiv> Dep_Function A (\\<lambda>_. B)\"\n\ntext \\<open>Set model of \\<^term>\\<open>Dep_Function\\<close>:\\<close>\n\ndefinition\n  \"dep_functions A B \\<equiv> {f \\<in> powerset (\\<Sum>x \\<in> A. (B x)) | function A f}\"\n\n(*TODO: localise*)\nsyntax\n  \"_dep_functions\"  :: \\<open>[pttrns, set, set] \\<Rightarrow> set type\\<close> (\"(2\\<Prod>_ \\<in> _./ _)\" [0, 0, 100])\n  \"_dep_functions2\" :: \\<open>[pttrns, set, set] \\<Rightarrow> set type\\<close>\ntranslations\n  \"\\<Prod>x xs \\<in> A. B\" \\<rightharpoonup> \"CONST dep_functions A (\\<lambda>x. _dep_functions2 xs A B)\"\n  \"_dep_functions2 x A B\" \\<rightharpoonup> \"\\<Prod>x \\<in> A. B\"\n  \"\\<Prod>x \\<in> A. B\" \\<rightleftharpoons> \"CONST dep_functions A (\\<lambda>x. B)\"\n\ntext \\<open>Syntax rules converting soft type notation to underlying set representation:\\<close>\nsyntax\n  \"_telescope'\" :: \"logic \\<Rightarrow> logic \\<Rightarrow> logic\"  (infixr \"\\<rightarrow>\" 50)\ntranslations\n  \"(x \\<in> A) \\<rightarrow> (y \\<in> B) \\<rightarrow> C\" \\<rightleftharpoons> \"(x \\<in> A) \\<rightarrow> \\<Prod>y \\<in> B. C\"\n  \"(x \\<in> A) \\<rightarrow> B \\<rightarrow> C\" \\<rightleftharpoons> \"(x \\<in> A) \\<rightarrow> \\<Prod>_ \\<in> B. C\"\n  \"A \\<rightarrow> (y \\<in> B) \\<rightarrow> C\" \\<rightleftharpoons> \"A \\<rightarrow> \\<Prod>y \\<in> B. C\"\n  \"A \\<rightarrow> B \\<rightarrow> C\" \\<rightleftharpoons> \"A \\<rightarrow> \\<Prod>_ \\<in> B. C\"\n  \"\\<Prod>x \\<in> A. ((y \\<in> B) \\<rightarrow> C)\" \\<rightharpoonup> \"\\<Prod>x \\<in> A. \\<Prod>y \\<in> B. C\"\n  \"\\<Prod>x \\<in> A. (B \\<rightarrow> C)\" \\<rightharpoonup> \"\\<Prod>x \\<in> A. \\<Prod>_ \\<in> B. C\"\n  \"(x \\<in> A) \\<rightarrow> B\" \\<rightleftharpoons> \"CONST Dep_Function A (\\<lambda>x. B)\"\n  \"A \\<rightarrow> B\" \\<rightleftharpoons> \"CONST Function A B\"\n\nsoft_type_translation \"f \\<in> \\<Prod>x \\<in> A. (B x)\" \\<rightleftharpoons> \"f : (x \\<in> A) \\<rightarrow> B x\"\n  unfolding dep_functions_def by unfold_types auto\n\ncorollary mem_dep_functions_iff_Dep_Function:\n  \"f \\<in> \\<Prod>x \\<in> A. (B x) \\<longleftrightarrow> f : (x \\<in> A) \\<rightarrow> B x\"\n  by auto\n\ncorollary Element_dep_functions_iff_Dep_Function:\n  \"f : (Element \\<Prod>x \\<in> A. (B x)) \\<longleftrightarrow> f : (x \\<in> A) \\<rightarrow> B x\"\n  by (subst mem_iff_Element[symmetric]) (fact mem_dep_functions_iff_Dep_Function)\n\n(*TODO: rules like these should automatically be derivable from above lemma and\nallow for type simplification*)\nlemma Dep_Function_if_Element_dep_functions [derive]:\n  \"f : Element (\\<Prod>x \\<in> A. (B x)) \\<Longrightarrow> f : (x \\<in> A) \\<rightarrow> B x\"\n  by (fact iffD1[OF Element_dep_functions_iff_Dep_Function])\n\nlemma Element_dep_functions_if_Dep_Function [backward_derive]:\n  \"f : (x \\<in> A) \\<rightarrow> B x \\<Longrightarrow> f : Element (\\<Prod>x \\<in> A. (B x))\"\n  by (fact iffD2[OF Element_dep_functions_iff_Dep_Function])\n\nsubsection \\<open>Properties of generic functions\\<close>\n\nlemma Dep_Function_cong [cong]:\n  \"\\<lbrakk>A = A'; \\<And>x. x \\<in> A \\<Longrightarrow> B x = B' x\\<rbrakk> \\<Longrightarrow> f : (x \\<in> A) \\<rightarrow> B x \\<longleftrightarrow> f : (x \\<in> A') \\<rightarrow> B' x\"\n  unfolding Dep_Function_def by auto\n\nlemma function_if_Dep_Function: \"f : (x \\<in> A) \\<rightarrow> B x \\<Longrightarrow> function A f\"\n  by unfold_types\n\nlemma Dep_Function_Subset_dep_pairs [derive]:\n  \"f : (x \\<in> A) \\<rightarrow> B x \\<Longrightarrow> f : Subset (\\<Sum>x \\<in> A. (B x))\"\n  by unfold_types\n\nlemma Dep_Function_dom_eq [simp]:\n  assumes \"f : (x \\<in> A) \\<rightarrow> B x\"\n  shows \"dom f = A\"\nproof (rule eqI)\n  have \"function A f\" by (rule function_if_Dep_Function) discharge_types\n  fix x assume \"x \\<in> A\"\n  then show \"x \\<in> dom f\"\n    by (intro mem_domI) (auto dest!: functionD[OF \\<open>function A f\\<close>])\nnext\n  have f_subset: \"f \\<subseteq> \\<Sum>x \\<in> A. (B x)\" by discharge_types\n  fix x assume \"x \\<in> dom f\"\n  then obtain y where \"\\<langle>x, y\\<rangle> \\<in> f \"by auto\n  with f_subset have \"\\<langle>x, y\\<rangle> \\<in> \\<Sum>x \\<in> A. (B x)\" by auto\n  then show \"x \\<in> A\" by simp\nqed\n\nlemma Fun_if_Dep_Function [derive]: \"f : (x \\<in> A) \\<rightarrow> B x \\<Longrightarrow> f : Fun\"\n  by (rule FunI) (auto dest: function_if_Dep_Function)\n\nlemma Function_if_Dep_Function [derive]:\n  \"f : (x \\<in> A) \\<rightarrow> B x \\<Longrightarrow> f : A \\<rightarrow> (\\<Union>x \\<in> A. B x)\"\n  by unfold_types auto\n\nlemma Dep_FunctionI:\n  assumes func_f: \"function A f\"\n  and \"f : Bin_Rel\"\n  and [simp]: \"dom f = A\"\n  and f_eval_x_mem: \"\\<And>x. x \\<in> A \\<Longrightarrow> f`x \\<in> B x\"\n  shows \"f : (x \\<in> A) \\<rightarrow> B x\"\nproof -\n  {\n    have f_subset: \"f \\<subseteq> (dom f) \\<times> (rng f)\"\n      by (rule Bin_Rel_subset_pairs_dom_rng) discharge_types\n    fix p assume \"p \\<in> f\"\n    with f_subset obtain x y where \"x \\<in> A\" and [simp]: \"p = \\<langle>x, y\\<rangle>\" by auto\n    with \\<open>p \\<in> f\\<close> have \"f`x = y\" by auto\n    moreover have \"f`x \\<in> B x\" by (fact f_eval_x_mem[OF \\<open>x \\<in> A\\<close>])\n    ultimately have \"p \\<in> \\<Sum>x \\<in> A. B x\" by auto\n  }\n  then show ?thesis\n    by (intro iffD1[OF mem_dep_functions_iff_Dep_Function])\n      (auto simp only: dep_functions_def)\nqed\n\nlemma FunctionI' [derive]: \"f : function A \\<sqdot> Relation A B \\<Longrightarrow> f : A \\<rightarrow> B\"\n  by unfold_types\n\nlemma Dep_Function_pair_eval_mem_if_mem [elim]:\n  assumes \"f : (x \\<in> A) \\<rightarrow> B x\"\n  and \"x \\<in> A\"\n  shows \"\\<langle>x, f`x\\<rangle> \\<in> f\"\n  using assms by (auto dest: function_if_Dep_Function)\n\nlemma Dep_Function_mem_dom_if_pair_mem:\n  \"\\<lbrakk>f : (x \\<in> A) \\<rightarrow> B x; \\<langle>x, y\\<rangle> \\<in> f\\<rbrakk> \\<Longrightarrow> x \\<in> A\"\n  by unfold_types auto\n\nlemma Dep_Function_mem_codom_if_pair_mem:\n  \"\\<lbrakk>f : (x \\<in> A) \\<rightarrow> B x; \\<langle>x, y\\<rangle> \\<in> f\\<rbrakk> \\<Longrightarrow> y \\<in> B x\"\n  by unfold_types auto\n\nlemma Dep_Function_eval_mem_if_mem [elim]:\n  \"\\<lbrakk>f : (x \\<in> A) \\<rightarrow> B x; x \\<in> A\\<rbrakk> \\<Longrightarrow> f`x \\<in> B x\"\n  using Dep_Function_mem_codom_if_pair_mem\n  by (fast dest: Dep_Function_pair_eval_mem_if_mem)\n\nlemma Dep_Function_fst_mem_dom_if_mem [elim]:\n  \"\\<lbrakk>f : (x \\<in> A) \\<rightarrow> B x; p \\<in> f\\<rbrakk> \\<Longrightarrow> fst p \\<in> A\"\n  by (rule Dep_Function_mem_dom_if_pair_mem)\n    (auto intro: Fun_fst_snd_mem_if_mem)\n\nlemma Dep_Function_snd_mem_codom_if_mem:\n  \"\\<lbrakk>f : (x \\<in> A) \\<rightarrow> B x; p \\<in> f\\<rbrakk> \\<Longrightarrow> snd p \\<in> B (fst p)\"\n  by (rule Dep_Function_mem_codom_if_pair_mem)\n    (auto intro: Fun_fst_snd_mem_if_mem)\n\nlemma Dep_Function_subset_pairs: \"f : (x \\<in> A) \\<rightarrow> B x \\<Longrightarrow> f \\<subseteq> A \\<times> (\\<Union>x \\<in> A. B x)\"\n  by auto\n\nlemma Function_subset_pairs [derive]:\n  \"f : A \\<rightarrow> B \\<Longrightarrow> f : Subset (A \\<times> B)\"\n  by auto\n\nlemma Dep_Function_fst_snd_eq_pair [simp]:\n  assumes \"f : (x \\<in> A) \\<rightarrow> B x\"\n  and \"p \\<in> f\"\n  shows \"\\<langle>fst p, snd p\\<rangle> = p\"\n  using assms by (auto intro!: Fun_fst_snd_eq_pair_if_mem)\n\nlemma Dep_Function_fst_eval_fst_eq_pair [simp]:\n  assumes \"f : (x \\<in> A) \\<rightarrow> B x\"\n  and \"p \\<in> f\"\n  shows \"f`(fst p) = snd p\"\n  using assms by auto\n\nlemma Dep_Function_pair_mem_iff_eval_eq:\n  \"f : (x \\<in> A) \\<rightarrow> B x \\<Longrightarrow> x \\<in> A \\<Longrightarrow> \\<langle>x, y\\<rangle> \\<in> f \\<longleftrightarrow> f`x = y\"\n  by auto\n\nlemma Dep_Fun_eval_eq_if_pair_mem [simp]:\n  \"\\<lbrakk>f : (x \\<in> A) \\<rightarrow> B x; \\<langle>x, y\\<rangle> \\<in> f\\<rbrakk> \\<Longrightarrow> f`x = y\"\n  by auto\n\nlemma Dep_Function_mem_domE:\n  assumes \"f : (x \\<in> A) \\<rightarrow> B x\"\n  and \"x \\<in> A\"\n  obtains y where \"f`x = y\" \"y \\<in> B x\"\n  using assms Dep_Function_eval_mem_if_mem by auto\n\nlemma Dep_Function_memE [elim]:\n  assumes \"f : (x \\<in> A) \\<rightarrow> B x\"\n  and \"p \\<in> f\"\n  obtains x y where \"p = \\<langle>x, y\\<rangle>\" \"x \\<in> A\" \"y \\<in> B x\" \"f`x = y\"\nproof -\n  assume hyp: \"\\<And>x y. p = \\<langle>x, y\\<rangle> \\<Longrightarrow> x \\<in> A \\<Longrightarrow> y \\<in> B x \\<Longrightarrow> f`x = y \\<Longrightarrow> thesis\"\n  obtain x y where \"p = \\<langle>x, y\\<rangle>\" \"f`x = y\"\n    by (rule Fun_memE) (insert assms, auto)\n  then show thesis\n  proof (intro hyp[of x y])\n    from assms have \"p = \\<langle>fst p, snd p\\<rangle>\" by auto\n    moreover from Dep_Function_fst_mem_dom_if_mem have \"fst p \\<in> A\"\n      using assms by auto\n    moreover from Dep_Function_snd_mem_codom_if_mem have \"snd p \\<in> B (fst p)\"\n      using assms by auto\n    ultimately show \"x \\<in> A\" and \"y \\<in> B x\" using \\<open>p = \\<langle>x, y\\<rangle>\\<close> by auto\n  qed assumption\nqed\n\nlemma Dep_Function_Rep_eval_eq [simp]:\n  assumes \"f : (x \\<in> A) \\<rightarrow> B x\"\n  shows \"{\\<langle>x, f`x\\<rangle> | x \\<in> A} = f\"\n  using assms by (intro eqI) auto\n\nlemma Dep_Function_empty_dom_iff_eq_empty [iff]: \"f : (x \\<in> {}) \\<rightarrow> B x \\<longleftrightarrow> f = {}\"\n  by unfold_types auto\n\nlemma Dep_Function_subsetI:\n  assumes f_type: \"f : (x \\<in> A) \\<rightarrow> B x\"\n  and g_type: \"g : (x \\<in> A') \\<rightarrow> B' x\"\n  and A_subset: \"A \\<subseteq> A'\"\n  and f_g_agree: \"\\<And>x. x \\<in> A \\<Longrightarrow> f`x = g`x\"\n  shows \"f \\<subseteq> g\"\nproof\n  fix p assume \"p \\<in> f\"\n  then obtain x y where p_eq: \"p = \\<langle>x, y\\<rangle>\" and \"x \\<in> A\" \"f`x = y\"\n    by (rule Dep_Function_memE[OF f_type])\n  with f_g_agree have p_eq: \"p = \\<langle>x, g`x\\<rangle>\" by blast\n  show \"p \\<in> g\"\n    by (subst p_eq, rule Dep_Function_pair_eval_mem_if_mem[OF g_type])\n      (insert A_subset, auto)\nqed\n\nlemma Dep_Function_eval_eqI:\n  assumes \"f : (x \\<in> A) \\<rightarrow> B x\" \"g : (x \\<in> A') \\<rightarrow> B' x\"\n  and \"f \\<subseteq> g\"\n  and \"x \\<in> A \\<inter> A'\"\n  shows \"f`x = g`x\"\nproof -\n  from assms have \"\\<langle>x, f`x\\<rangle> \\<in> g\" and \"\\<langle>x, g`x\\<rangle> \\<in> g\" by auto\n  then show ?thesis by auto\nqed\n\nlemma Dep_Function_ex_dom_iff:\n  \"\\<exists>A. f : (x \\<in> A) \\<rightarrow> B x \\<longleftrightarrow> f : (x \\<in> dom f) \\<rightarrow> B x\"\n  by auto\n\nlemma empty_Function [type]: \"{} : {} \\<rightarrow> X\" by auto\n\nlemma singleton_FunctionI [intro]: \"y \\<in> B \\<Longrightarrow> {\\<langle>x, y\\<rangle>} : {x} \\<rightarrow> B\"\n  by (rule Dep_FunctionI) auto\n\nlemma Function_eq_singleton [simp]: \"f : {a} \\<rightarrow> {b} \\<Longrightarrow> f = {\\<langle>a, b\\<rangle>}\"\n  by (unfold_types, unfold function_def) auto\n\nlemma cons_FunctionI:\n  \"\\<lbrakk>f : A \\<rightarrow> B; x \\<notin> A\\<rbrakk> \\<Longrightarrow> cons \\<langle>x, y\\<rangle> f : A \\<union> {x} \\<rightarrow> B \\<union> {y}\"\n  by (unfold_types, unfold function_def) auto\n\nlemma cons_FunctionI':\n  assumes \"f : A \\<rightarrow> B\"\n  and \"x \\<notin> A\"\n  and \"y \\<in> B\"\n  shows \"cons \\<langle>x, y\\<rangle> f : A \\<union> {x} \\<rightarrow> B\"\nproof -\n  from assms(1-2) have \"cons \\<langle>x, y\\<rangle> f : A \\<union> {x} \\<rightarrow> B \\<union> {y}\"\n    by (rule cons_FunctionI)\n  moreover from \\<open>y \\<in> B\\<close> have \"B \\<union> {y} = B\" by simp\n  ultimately show \"cons \\<langle>x, y\\<rangle> f : A \\<union> {x} \\<rightarrow> B\" by simp\nqed\n\nlemma singleton_bin_union_FunctionI:\n  \"\\<lbrakk>f : A \\<rightarrow> B; x \\<notin> A\\<rbrakk> \\<Longrightarrow> {\\<langle>x, y\\<rangle>} \\<union> f : A \\<union> {x} \\<rightarrow> B \\<union> {y}\"\n  by (subst singleton_bin_union_eq_cons, fact cons_FunctionI)\n\n\nsubsection \\<open>Lambda abstraction\\<close>\n\ndefinition lambda :: \"set \\<Rightarrow> (set \\<Rightarrow> set) \\<Rightarrow> set\"\n  where \"lambda A f \\<equiv> {\\<langle>x, f x\\<rangle> | x \\<in> A}\"\n\n(*TODO: localise*)\nsyntax\n  \"_lam\"  :: \"[pttrns, set, set] \\<Rightarrow> set\" (\"(2\\<lambda>_ \\<in> _./ _)\" 60)\n  \"_lam2\" :: \\<open>[pttrns, set, set] \\<Rightarrow> set\\<close>\ntranslations\n  \"\\<lambda>x xs \\<in> A. f\" \\<rightharpoonup> \"CONST lambda A (\\<lambda>x. _lam2 xs A f)\"\n  \"_lam2 x A f\" \\<rightharpoonup> \"\\<lambda>x \\<in> A. f\"\n  \"\\<lambda>x \\<in> A. f\" \\<rightleftharpoons> \"CONST lambda A (\\<lambda>x. f)\"\n\nlemma lambda_cong [cong]:\n  \"\\<lbrakk>A = A'; \\<And>x. x \\<in> A \\<Longrightarrow> f x = f' x\\<rbrakk> \\<Longrightarrow> (\\<lambda>x \\<in> A. f x) = \\<lambda>x \\<in> A'. f' x\"\n  unfolding lambda_def by auto\n\nlemma eval_lambda_eq [simp]: \"a \\<in> A \\<Longrightarrow> (\\<lambda>x \\<in> A. f x)`a = f a\"\n  unfolding lambda_def by auto\n\nlemma eval_lambda_uncurry_eq [simp]:\n  assumes \"a \\<in> A\" \"b \\<in> B\"\n  shows \"(\\<lambda>p \\<in> A \\<times> B. uncurry f p)`\\<langle>a, b\\<rangle> = f a b\"\n  using assms by auto\n\nlemma lambda_pairs_eq_lambda_uncurry:\n  \"(\\<lambda>p \\<in> A \\<times> B. f p) = (\\<lambda>\\<langle>a, b\\<rangle> \\<in> A \\<times> B. f \\<langle>a, b\\<rangle>)\"\n  by (rule lambda_cong) auto\n\nlemma lambda_pair_mem_if_mem [intro]: \"a \\<in> A \\<Longrightarrow> \\<langle>a, f a\\<rangle> \\<in> \\<lambda>x \\<in> A. f x\"\n  unfolding lambda_def by auto\n\nlemma lambda_memE [elim]:\n  assumes \"p \\<in> \\<lambda>x \\<in> A. f x\"\n  obtains x y where \"p = \\<langle>x, y\\<rangle>\" \"x \\<in> A\" \"f x = y\"\n  using assms unfolding lambda_def by auto\n\nlemma lambda_memD [dest]: \"\\<langle>a, b\\<rangle> \\<in> \\<lambda>x \\<in> A. f x \\<Longrightarrow> b = f a\"\n  by auto\n\nlemma lambda_dom_eq [simp]: \"dom (\\<lambda>x \\<in> A. f x) = A\"\n  unfolding lambda_def by simp\n\nlemma app_eq_if_mem_if_lambda_eq:\n  \"\\<lbrakk>(\\<lambda>x \\<in> A. f x) = \\<lambda>x \\<in> A. g x; a \\<in> A\\<rbrakk> \\<Longrightarrow> f a = g a\"\n  by (erule eqE) auto\n\n\nsubsubsection\\<open>Type-theoretic rules\\<close>\n\nlemma lambda_type [type]:\n  \"lambda : (A : Set) \\<Rightarrow> ((x : Element A) \\<Rightarrow> Element (B x)) \\<Rightarrow> (x \\<in> A) \\<rightarrow> B x\"\n  by unfold_types auto\n\n(*TODO: it is necessery to specify this backward_derive rule since although\nabove type rule encodes that the type of f depends on A, this will not be\nused in the type_derivator when proving `lambda A f : T`; more specifically,\nthe derivator will merely derivate types for A and f and then see if they can be\nfed to Dep_fun_typeE together with lambda_type*)\nlemma lambda_app_type [backward_derive]:\n  assumes \"A : Set\" \"f : (x : Element A) \\<Rightarrow> Element (B x)\"\n  shows \"lambda A f : (x \\<in> A) \\<rightarrow> B x\"\n  by discharge_types\n\nlemma uncurry_type [type]:\n  \"uncurry : ((a : Element A) \\<Rightarrow> (b : Element B) \\<Rightarrow> C \\<langle>a, b\\<rangle>) \\<Rightarrow>\n    (p : Element (A \\<times> B)) \\<Rightarrow> C p\"\n  unfolding uncurry_def by unfold_types auto\n\n(*TODO: if f is a lambda abstraction, the derivator must use backward_derive\nrules to prove its type before being able to apply it to uncurry_type together\nwith Dep_fun_typeE; so we need to create this backward_derive rule to guide\nthe derivator*)\nlemma uncurry_app_type [backward_derive]:\n  assumes \"f : (a : Element A) \\<Rightarrow> (b : Element B) \\<Rightarrow> C \\<langle>a, b\\<rangle>\"\n  shows \"uncurry f : (p : Element (A \\<times> B)) \\<Rightarrow> C p\"\n  by discharge_types\n\nlemma eval_type [type]:\n  \"eval: ((x \\<in> A) \\<rightarrow> B x) \\<Rightarrow> (x : Element A) \\<Rightarrow> Element (B x)\"\n  (*TOOD: the type derivator should convert the set-theoretic statement\n    Dep_Function_eval_mem_if_mem to a type-theoretic one*)\n  using Dep_Function_eval_mem_if_mem\n  by (intro Dep_fun_typeI) (auto intro: ElementI dest: ElementD)\n\nnotepad\nbegin\n  have\n    \"\\<lbrakk>f : (x \\<in> A) \\<rightarrow> (y \\<in> B x) \\<rightarrow> C x y; a: Element A; b: Element (B a)\\<rbrakk>\n      \\<Longrightarrow> f`a`b: Element (C a b)\"\n    (*TODO: should not need an increase of the limit*)\n    using [[type_derivation_depth=3]]\n    by discharge_types\nend\n\nlemma lambda_type_dom_subset_if_Dep_Function:\n  assumes \"f : (x \\<in> A) \\<rightarrow> B x\"\n  and \"A' \\<subseteq> A\"\n  shows \"(\\<lambda>a \\<in> A'. f`a) : (x \\<in> A') \\<rightarrow> B x\"\n  using assms by (intro Dep_FunctionI) auto\n\nlemma lambda_type_dom_bin_inter_if_Dep_Function:\n  assumes \"f : (x \\<in> A) \\<rightarrow> B x\"\n  shows \"(\\<lambda>a \\<in> A \\<inter> A'. f`a) : (x \\<in> A \\<inter> A') \\<rightarrow> B x\"\n  using assms by (rule lambda_type_dom_subset_if_Dep_Function) auto\n\n\nsubsection \\<open>Extensionality\\<close>\n\nlemma Dep_Function_ext:\n  assumes \"f : (x \\<in> A) \\<rightarrow> B x\" \"g : (x \\<in> A) \\<rightarrow> C x\"\n  and \"\\<And>x. x \\<in> A \\<Longrightarrow> f`x = g`x\"\n  shows \"f = g\"\n  by (rule eq_if_subset_if_subset; rule Dep_Function_subsetI) (insert assms, auto)\n\nlemma lambda_ext:\n  assumes \"f : (x \\<in> A) \\<rightarrow> B x\"\n  and \"\\<And>a. a \\<in> A \\<Longrightarrow> g a = f`a\"\n  shows \"(\\<lambda>a \\<in> A. g a) = f\"\n  unfolding lambda_def\n  using assms\n  by (rewrite at \"{\\<langle>x, g x\\<rangle> | x \\<in> A}\" to \"{\\<langle>x, f`x\\<rangle> | x \\<in> A}\" repl_cong) auto\n\nlemma Dep_Function_eta [simp]: \"f : (x \\<in> A) \\<rightarrow> B x \\<Longrightarrow> (\\<lambda>x \\<in> A. f`x) = f\"\n  by (rule Dep_Function_ext) auto\n\nlemma Dep_Function_eq_if_subset:\n  assumes f_type: \"f : (x \\<in> A) \\<rightarrow> B x\" and g_type: \"g : (x \\<in> A) \\<rightarrow> C x\"\n  and \"f \\<subseteq> g\"\n  shows \"f = g\"\nproof (rule eqI)\n  fix p assume \"p \\<in> g\"\n  with g_type obtain x y where [simp]: \"p = \\<langle>x, y\\<rangle>\" \"g`x = y\" \"x \\<in> A\" by blast\n  then have [simp]: \"f`x = g`x\" by (intro Dep_Function_eval_eqI) auto\n  from Dep_Function_pair_mem_iff_eval_eq show \"p \\<in> f\" by auto\nqed (insert assms, auto)\n\n(*Every element of `(x \\<in> A) \\<rightarrow> B x` may be expressed as a lambda abstraction*)\nlemma Dep_Function_eq_lambdaE:\n  assumes \"f : (x \\<in> A) \\<rightarrow> B x\"\n  obtains g where \"g : (x : Element A) \\<Rightarrow> Element (B x)\" and \"f = (\\<lambda>x \\<in> A. g x)\"\nproof\n  let ?g=\"(\\<lambda>x. f`x)\"\n  show \"f = (\\<lambda>x \\<in> A. ?g x)\" by auto\n  show \"?g : (x : Element A) \\<Rightarrow> Element (B x)\" by discharge_types\nqed\n\n(*note: no contravariance with current definition possible*)\nlemma Dep_Function_covariant_codom:\n  assumes \"f : (x \\<in> A) \\<rightarrow> B x\"\n  and \"\\<And>x. x \\<in> A \\<Longrightarrow> f`x \\<in> B x \\<Longrightarrow> f`x \\<in> B' x\"\n  shows \"f : (x \\<in> A) \\<rightarrow> B' x\"\n  using assms by (intro Dep_FunctionI) (auto intro!: functionI)\n\ncorollary Dep_Function_covariant_codom_subset:\n  assumes \"f : (x \\<in> A) \\<rightarrow> B x\"\n  and \"\\<And>x. x \\<in> A \\<Longrightarrow> B x \\<subseteq> C x\"\n  shows \"f : (x \\<in> A) \\<rightarrow> C x\"\n  using assms(2) by (intro Dep_Function_covariant_codom[OF assms(1)]) auto\n\n(*Larry: Such functions arise in non-standard datatypes, ZF/ex/Ntree for\n  instance.*)\nlemma Dep_Function_collectI:\n  assumes \"f : (x \\<in> A) \\<rightarrow> B x\"\n  and \"\\<And>x. x \\<in> A \\<Longrightarrow> P x (f`x)\"\n  shows \"f : (x \\<in> A) \\<rightarrow> {y \\<in> B x | P x y}\"\n  by (rule Dep_Function_covariant_codom) (insert assms, auto)\n\nlemma Dep_Function_collectD:\n  assumes \"f : (x \\<in> A) \\<rightarrow> {y \\<in> B x | P x y}\"\n  shows \"f : (x \\<in> A) \\<rightarrow> B x\" and \"\\<And>x. x \\<in> A \\<Longrightarrow> P x (f`x)\"\nproof -\n  from assms show \"f : (x \\<in> A) \\<rightarrow> B x\"\n    by (rule Dep_Function_covariant_codom_subset) auto\n  fix x assume \"x \\<in> A\"\n  then show \"P x (f`x)\" by (auto dest: Dep_Function_eval_mem_if_mem[OF assms])\nqed\n\n\nsubsection \\<open>Injectivity and surjectivity\\<close>\n\ndefinition \"injective A f \\<equiv> \\<forall>x x' \\<in> A. f`x = f`x' \\<longrightarrow> x = x'\"\n\ndefinition \"surjective B f \\<equiv> \\<forall>y \\<in> B. \\<exists>x. f`x = y\"\n\nlemma injectiveI:\n  assumes \"\\<And>x x'. x \\<in> A \\<Longrightarrow> x' \\<in> A \\<Longrightarrow> f`x = f`x' \\<Longrightarrow> x = x'\"\n  shows \"injective A f\"\n  unfolding injective_def using assms by simp\n\nlemma surjectiveI:\n  assumes \"\\<And>y. y \\<in> B \\<Longrightarrow> \\<exists>x \\<in> A. f`x = y\"\n  shows \"surjective B f\"\n  unfolding surjective_def using assms by blast\n\n\ntext \\<open>Extend a function's domain by mapping new elements to the empty set.\\<close>\n\ndefinition triv_ext :: \"set \\<Rightarrow> set \\<Rightarrow> set\"\n  where \"triv_ext A f \\<equiv> f \\<union> (\\<lambda>x \\<in> (A \\<setminus> dom f). {})\"\n\nlemma dom_triv_ext_eq [simp]: \"dom (triv_ext A f) = dom f \\<union> A\"\n  unfolding triv_ext_def by auto\n\n\nsubsection \\<open>Composition\\<close>\n\ndefinition \"fun_comp g f \\<equiv> \\<lambda>x \\<in> dom f. g`(f`x)\"\n\nbundle isa_set_fun_comp_syntax begin notation fun_comp (infixr \"\\<circ>\" 80) end\nbundle no_isa_set_fun_comp_syntax begin no_notation fun_comp (infixr \"\\<circ>\" 80) end\nunbundle isa_set_fun_comp_syntax\n\nlemma fun_comp_type [type]:\n  \"(\\<circ>) : ((x \\<in> B) \\<rightarrow> C x) \\<Rightarrow> (f : A \\<rightarrow> B) \\<Rightarrow> (x \\<in> A) \\<rightarrow> C (f`x)\"\n  unfolding fun_comp_def\n  by (intro Dep_fun_typeI Dep_FunctionI) auto\n\nlemma lambda_comp_lambda_eq [simp]:\n  \"f : Element A \\<Rightarrow> Element B \\<Longrightarrow> (\\<lambda>y \\<in> B. g y) \\<circ> (\\<lambda>x \\<in> A. f x) = \\<lambda>x \\<in> A. g (f x)\"\n  unfolding fun_comp_def by auto\n\nlemma comp_id_eq [simp]: \"f : (x \\<in> A) \\<rightarrow> B x \\<Longrightarrow> f \\<circ> (\\<lambda>x \\<in> A. x) = f\"\n  unfolding fun_comp_def by auto\n\nlemma id_comp_eq [simp]: \"f : A \\<rightarrow> B \\<Longrightarrow> (\\<lambda>x \\<in> B. x) \\<circ> f = f\"\n  unfolding fun_comp_def by auto\n\nlemma comp_assoc [simp]:\n  assumes \"f : A \\<rightarrow> B\" \"g : B \\<rightarrow> C\"\n  shows \"h \\<circ> g \\<circ> f = (h \\<circ> g) \\<circ> f\"\n  (*TOOD: slow proof*)\n  unfolding fun_comp_def by auto\n\nsubsection \\<open>Restriction\\<close>\n\ndefinition \"restriction f A \\<equiv> \\<lambda>a \\<in> dom f \\<inter> A. f`a\"\n\nbundle isa_set_restriction_syntax begin notation restriction (infix \"\\<restriction>\" 100) end\nbundle no_isa_set_restriction_syntax begin no_notation restriction (infix \"\\<restriction>\" 100) end\nunbundle isa_set_restriction_syntax\n\nlemma restriction_type [type]:\n  \"(\\<restriction>) : ((x \\<in> A) \\<rightarrow> B x) \\<Rightarrow> (A' : Set) \\<Rightarrow> (x \\<in> A \\<inter> A') \\<rightarrow> B x\"\n  unfolding restriction_def\n  using lambda_type_dom_bin_inter_if_Dep_Function\n  by (auto simp only: Dep_Function_dom_eq)\n\nlemma Fun_restriction_subset [simp]: \"f : Fun \\<Longrightarrow> restriction f A \\<subseteq> f\"\n  unfolding restriction_def by auto\n\nlemma Fun_restriction_eq_collect:\n  assumes \"f : Fun\"\n  shows \"f\\<restriction>A = {p \\<in> f | fst p \\<in> A}\" (is \"?lhs = ?rhs\")\nproof (rule eqI)\n  fix p assume \"p \\<in> ?rhs\"\n  then have \"p \\<in> f\" \"fst p \\<in> A\" by auto\n  with Fun_fst_mem_dom_if_mem have \"fst p \\<in> dom f\" by auto\n  with assms obtain x y where [simp]: \"p = \\<langle>x, y\\<rangle>\" \"y = f`x\"\n    by (auto elim!: Fun_memE)\n  with assms \\<open>fst p \\<in> A\\<close> \\<open>fst p \\<in> dom f\\<close> show \"p \\<in> ?lhs\"\n    unfolding restriction_def by (auto intro!: lambda_pair_mem_if_mem)\nnext\n  fix p assume \"p \\<in> ?lhs\"\n  with assms show \"p \\<in> ?rhs\" unfolding restriction_def by auto\nqed\n\nlemma restriction_eval_eq [simp]: \"a \\<in> A \\<Longrightarrow> A \\<subseteq> dom f \\<Longrightarrow> (f\\<restriction>A)`a = f`a\"\n  unfolding restriction_def by auto\n\nlemma dom_restriction_eq [simp]: \"dom (f\\<restriction>A) = dom f \\<inter> A\"\n  unfolding restriction_def by auto\n\nlemma restriction_type_Subset:\n  \"(\\<restriction>) : ((x \\<in> A) \\<rightarrow> B x) \\<Rightarrow> (A' : Subset A) \\<Rightarrow> (x \\<in> A') \\<rightarrow> B x\"\n  by (intro Dep_fun_typeI,\n    rewrite at \"A'\" in \"(x \\<in> A') \\<rightarrow> _\" in for (A')\n      bin_inter_eq_right_if_subset[where ?A=A, symmetric])\n    auto\n\n\nsubsection \\<open>Gluing\\<close>\n\ndefinition \"glue X = \\<Union>X\"\n\nlemma glue_eval_eq:\n  assumes \"\\<And>f y'. \\<lbrakk>f \\<in> F; \\<langle>x, y'\\<rangle> \\<in> f\\<rbrakk> \\<Longrightarrow> y' = y\"\n  and \"f \\<in> F\"\n  and \"\\<langle>x, y\\<rangle> \\<in> f\"\n  shows \"(glue F)`x = y\"\n  unfolding eval_def glue_def by (rule the_equality) (auto intro: assms)\n\nlemma glue_Dep_Functions_typeI:\n  assumes all_fun: \"\\<And>f. f \\<in> F \\<Longrightarrow> f : (x \\<in> dom f) \\<rightarrow> B x\"\n  and all_agree: \"\\<And>f g x. \\<lbrakk>f \\<in> F; g \\<in> F; x \\<in> dom f; x \\<in> dom g\\<rbrakk> \\<Longrightarrow> f`x = g`x\"\n  shows \"glue F : (x \\<in> (\\<Union>f \\<in> F. dom f)) \\<rightarrow> B x\"\nproof (rule Dep_FunctionI)\n  {\n    fix x assume \"x \\<in> (\\<Union>f \\<in> F. dom f)\"\n    then obtain f where \"f \\<in> F\" \"x \\<in> dom f\" by auto\n    moreover have \"\\<langle>x, f`x\\<rangle> \\<in> f\"\n      by (simp only:\n        Dep_Function_pair_mem_iff_eval_eq[OF all_fun[OF \\<open>f \\<in> F\\<close>] \\<open>x \\<in> dom f\\<close>])\n    ultimately have \"\\<exists>f y. f \\<in> F \\<and> \\<langle>x, y\\<rangle> \\<in> f \\<and> f`x = y\" by auto\n  }\n  note ex_mem_F_pair_mem = this\n  show \"function (\\<Union>f \\<in> F. dom f) (glue F)\" unfolding glue_def\n  proof\n   fix x y y' assume \"x \\<in> (\\<Union>f \\<in> F. dom f)\" \"\\<langle>x, y\\<rangle> \\<in> \\<Union>F\" \"\\<langle>x, y'\\<rangle> \\<in> \\<Union>F\"\n    then obtain f g where f_g_props: \"\\<langle>x, y\\<rangle> \\<in> f\" \"\\<langle>x, y'\\<rangle> \\<in> g\" \"f \\<in> F\" \"g \\<in> F\"\n      by auto\n    with all_fun have \"y = f`x\" by auto\n    also with f_g_props have \"... = g`x\" by (intro all_agree) auto\n    also with all_fun f_g_props have \"... = y'\" by auto\n    finally show \"y = y'\" .\n  next\n    fix x assume \"x \\<in> (\\<Union>f \\<in> F. dom f)\"\n    from ex_mem_F_pair_mem[OF this] show \"\\<exists>y. \\<langle>x, y\\<rangle> \\<in> \\<Union>F\" by auto\n  qed\n  fix x assume \"x \\<in> (\\<Union>f \\<in> F. dom f)\"\n  from ex_mem_F_pair_mem[OF this]\n    obtain f y where \"f \\<in> F\" \"\\<langle>x, y\\<rangle> \\<in> f\" and \"f`x = y\" by auto\n  then have \"glue F`x = y\"\n  proof (intro glue_eval_eq)\n    fix f' y' assume \"f' \\<in> F\" \"\\<langle>x, y'\\<rangle> \\<in> f'\"\n    with all_fun have \"y' = f'`x\" by auto\n    also with \\<open>\\<langle>x, y'\\<rangle> \\<in> f'\\<close> have \"... = f`x\"\n      using \\<open>\\<langle>x, y\\<rangle> \\<in> f\\<close> by (intro all_agree) auto\n    finally show \"y' = y\" using \\<open>f`x = y\\<close> by simp\n  qed assumption\n  moreover from \\<open>f \\<in> F\\<close> have \"y \\<in> B x\" by\n    (intro Dep_Function_mem_codom_if_pair_mem[where ?B=B]) (auto dest: all_fun)\n  ultimately show \"glue F`x \\<in> B x\" unfolding glue_def by auto\nqed (unfold glue_def, auto dest: all_fun)\n\nlemma glue_Dep_Functions_eval_eq:\n  assumes all_fun: \"\\<And>f. f \\<in> F \\<Longrightarrow> f : (x \\<in> dom f) \\<rightarrow> B x\"\n  and all_agree: \"\\<And>f'. \\<lbrakk>f' \\<in> F; x \\<in> dom f'\\<rbrakk> \\<Longrightarrow> f'`x = f`x\"\n  and \"f \\<in> F\"\n  and \"x \\<in> dom f\"\n  shows \"(glue F)`x = f`x\"\nproof (rule glue_eval_eq[OF _ \\<open>f \\<in> F\\<close>])\n fix f' y' assume f'_props: \"f' \\<in> F\" \"\\<langle>x, y'\\<rangle> \\<in> f'\"\n  then have \"y' = f'`x\"\n    by (intro Dep_Fun_eval_eq_if_pair_mem[symmetric]) (auto dest: all_fun)\n  also have \"... = f`x\" using f'_props by (intro all_agree) auto\n  finally show \"y' = f`x\" .\nnext\n  show \"\\<langle>x, f`x\\<rangle> \\<in> f\"\n    by (rule Dep_Function_pair_eval_mem_if_mem) (auto intro: assms)\nqed\n\nlemma glue_upair_Dep_Functions_typeI:\n  assumes \"f : (x \\<in> A) \\<rightarrow> B x\" \"g : (x \\<in> A') \\<rightarrow> B x\"\n  and \"\\<And>x. \\<lbrakk>x \\<in> A; x \\<in> A'\\<rbrakk> \\<Longrightarrow> f`x = g`x\"\n  shows \"glue {f, g} : (x \\<in> A \\<union> A') \\<rightarrow> B x\"\nproof -\n  have \"(\\<Union>f \\<in> {f, g}. dom f) = (\\<Union>f \\<in> {f}. dom f) \\<union> (\\<Union>f \\<in> {g}. dom f)\"\n    by (auto simp only: idx_union_bin_union_dom_eq_bin_union_idx_union)\n  also have \"... = dom f \\<union> dom g\" by auto\n  also have \"... = A \\<union> A'\" by simp\n  finally have \"A \\<union> A' = (\\<Union>f \\<in> {f, g}. dom f)\" by auto\n  then show ?thesis using assms by (auto intro: glue_Dep_Functions_typeI)\nqed\n\nlemma glue_upair_Dep_Functions_eval_eq_left:\n  assumes \"f : (x \\<in> A) \\<rightarrow> B x\" \"g : (x \\<in> A') \\<rightarrow> B x\"\n  and \"\\<And>x. x \\<in> A \\<inter> A' \\<Longrightarrow> f`x = g`x\"\n  and \"x \\<in> A\"\n  shows \"(glue {f, g})`x = f`x\"\n  by (intro glue_Dep_Functions_eval_eq) (auto simp: assms)\n\nlemma glue_upair_Dep_Functions_eval_eq_right:\n  assumes \"f : (x \\<in> A) \\<rightarrow> B x\" \"g : (x \\<in> A') \\<rightarrow> B x\"\n  and \"\\<And>x. x \\<in> A \\<inter> A' \\<Longrightarrow> f`x = g`x\"\n  and  \"x \\<in> A'\"\n  shows \"(glue {f, g})`x = g`x\"\n  by (subst cons_comm, rule glue_upair_Dep_Functions_eval_eq_left)\n    (auto simp: assms)\n\n\nsubsection \\<open>Universes\\<close>\n\nlemma univ_closed_dep_functions [intro!]:\n  assumes \"A \\<in> univ U\"\n  and \"\\<And>x. x \\<in> A \\<Longrightarrow> B x \\<in> univ U\"\n  shows \"\\<Prod>x \\<in> A. (B x) \\<in> univ U\"\nproof -\n  let ?P = \"powerset \\<Sum>x \\<in> A. (B x)\"\n  have \"\\<Prod>x \\<in> A. (B x) \\<subseteq> ?P\" unfolding dep_functions_def by (fact collect_subset)\n  moreover have \"?P \\<in> univ U\" using assms by auto\n  ultimately show ?thesis by (auto intro: mem_univ_trans)\nqed\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/Old/Functions.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8519528019683105, "lm_q2_score": 0.8289388104343892, "lm_q1q2_score": 0.7062167422098561}}
{"text": "(*\n    File:        Poset.thy\n    Time-stamp:  <2020-06-22T03:40:26Z>\n    Author:      JRF\n    Web:         http://jrf.cocolog-nifty.com/software/2016/01/post.html\n    Logic Image: Logics_ZF (of Isabelle2020)\n*)\n\ntheory Poset imports ZF FinCard begin\n\ndefinition poset :: \"[[i,i]=>o, i]=>o\" where\n\"poset(R, P) == (ALL x: P. R(x, x)) &\n  (ALL x: P. ALL y: P. R(x, y) & R(y, x) --> x = y) &\n  (ALL x: P. ALL y: P. ALL z: P. R(x, y) & R(y, z) --> R(x, z))\"\n\ndefinition chain :: \"[[i,i]=>o, i]=>o\" where\n\"chain(R, P) == poset(R, P)\n   & (ALL x: P. ALL y: P. R(x, y) | R(y, x))\"\n\ndefinition invrel :: \"[[i, i]=>o, i, i]=>o\" where\n\"invrel(R, x, y) == R(y, x)\"\n\ndefinition least :: \"[[i,i]=>o, i, i]=>o\" where\n\"least(R, P, x) == x: P & (ALL y: P. R(x, y))\"\n\ndefinition greatest :: \"[[i,i]=>o, i, i]=>o\" where\n\"greatest(R, P, x) == x: P & (ALL y: P. R(y, x))\"\n\ndefinition minimal :: \"[[i, i]=>o, i, i]=>o\" where\n\"minimal(R, P, x) == x: P & (ALL y: P. R(y, x) --> y = x)\"\n\ndefinition maximal :: \"[[i, i]=>o, i, i]=>o\" where\n\"maximal(R, P, x) == x: P & (ALL y: P. R(x, y) --> y = x)\"\n\ndefinition downset :: \"[[i, i]=>o, i, i]=>i\" where\n\"downset(R, P, x) == {y: P. R(y, x)}\"\n\ndefinition upset :: \"[[i, i]=>o, i, i]=>i\" where\n\"upset(R, P, x) == {y: P. R(x, y)}\"\n\ndefinition upperbound :: \"[[i, i]=>o, i, i]=>i\" where\n\"upperbound(R, P, S) == {x: P. ALL y: S. R(y, x)}\"\n\ndefinition lowerbound :: \"[[i, i]=>o, i, i]=>i\" where\n\"lowerbound(R, P, S) == {x: P. ALL y: S. R(x, y)}\"\n\n(** poset **)\nlemma posetI:\n  \"[| !!x. x: P ==> R(x, x); \n      !!x y. [| x: P; y: P; R(x, y); R(y, x) |] ==> x = y; \n      !!x y z. [| x: P; y: P; z: P; R(x, y); R(y, z) |] ==> R(x, z)\n   |] ==> poset(R, P)\"\napply (unfold poset_def)\napply blast\ndone\n\nlemma poset_reflD:\n  \"[| poset(R, P); x: P |] ==> R(x, x)\"\napply (unfold poset_def)\napply blast\ndone\n\nlemma poset_antisymD:\n  \"[| poset(R, P); R(x, y); R(y, x); x: P; y: P |] ==> x = y\"\napply (unfold poset_def)\napply blast\ndone\n\nlemma poset_transD:\n  \"[| poset(R, P); R(x, y); R(y, z); x: P; y: P; z: P |] ==> R(x, z)\"\napply (unfold poset_def)\napply blast\ndone\n\nlemma poset_subset:\n  \"[| S <= P; poset(R, P) |] ==> poset(R, S)\"\napply (rule posetI)\napply (drule subsetD, assumption)\napply (erule poset_reflD, assumption)\napply (erule poset_antisymD, assumption+)\napply (erule subsetD, assumption)+\napply (erule poset_transD, assumption+)\napply (erule subsetD, assumption)+\ndone\n\nlemma poset_invrel_iff:\n  \"poset(invrel(R), P) <-> poset(R, P)\"\napply (unfold poset_def invrel_def)\napply blast\ndone\n\n(** chain **)\nlemma chainI:\n  \"[| poset(R, P); !!x y. [| x: P; y: P |] ==> R(x, y) | R(y, x) |]\n      ==> chain(R, P)\"\napply (unfold chain_def)\napply blast\ndone\n\nlemma chain_imp_poset:\n    \"chain(R, P) ==> poset(R, P)\"\napply (unfold chain_def)\napply blast\ndone\n\nlemmas chainD1 = chain_imp_poset\n\nlemma chainD2:\n  \"[| chain(R, P); x: P; y: P |] ==> R(x, y) | R(y, x)\"\napply (unfold chain_def)\napply blast\ndone\n\nlemma chain_subset:\n    \"[| S <= P; chain(R, P) |] ==> chain(R, S)\"\napply (blast intro: chainI poset_subset dest: chainD1 chainD2)\ndone\n\nlemma chain_invrel_iff:\n  \"chain(invrel(R), P) <-> chain(R, P)\"\napply (unfold chain_def)\napply (simp add: poset_invrel_iff)\napply (unfold invrel_def)\napply blast\ndone\n\n(** least/greatest **)\nlemma leastI:\n  \"[| !!y. y: P ==> R(x, y); x: P |] ==> least(R, P, x)\"\napply (unfold least_def)\napply blast\ndone\n\nlemma leastD1:\n  \"least(R, P, x) ==> x: P\"\napply (unfold least_def)\napply blast\ndone\n\nlemma leastD2:\n  \"[| least(R, P, x); y: P |] ==> R(x, y)\"\napply (unfold least_def)\napply blast\ndone\n\nlemma least_unique:\n  \"[| least(R, P, x); least(R, P, y); poset(R, P) |] ==> x = y\"\napply (erule poset_antisymD)\napply (erule leastD2, erule leastD1) \napply (erule leastD2, erule leastD1)\napply (erule leastD1)\napply (erule leastD1)\ndone\n\nlemma least_subset:\n  \"[| S <= P; least(R, P, x); x: S |] ==> least(R, S, x)\"\napply (rule leastI)\napply (drule subsetD)\napply (drule_tac [2] leastD2)\nby assumption+\n\nlemma Finite_non_empty_chain_has_least_element:\n  assumes major: \"Finite(P)\"\n  and prem1: \"chain(R, P)\"\n  and prem2: \"P ~= 0\"\n  shows \"EX x. least(R, P, x)\"\napply (rule prem2 [THEN rev_mp])\napply (rule prem1 [THEN rev_mp])\napply (rule major [THEN Finite_into_Fin, THEN Fin_induct])\napply blast\napply (intro impI)\napply (case_tac \"y = 0\")\napply hypsubst\napply (rule exI)\napply (rule leastI)\napply (rule_tac [2] singletonI)\napply (erule singletonE)\napply hypsubst\napply (erule chain_imp_poset [THEN poset_reflD])\napply (rule singletonI)\napply (drule mp [THEN mp])\napply (rule chain_subset)\napply (rule subset_consI)\napply assumption+\napply (erule exE)\napply (frule chainD2)\napply (rule consI1)\napply (rule consI2)\napply (erule leastD1)\napply (erule disjE)\napply (rename_tac [2] v)\napply (rule_tac x=\"x\" in exI)\napply (rule_tac [2] x=\"v\" in exI)\napply (rule_tac [2] leastI)\napply (rule leastI)\napply (rule_tac [4] consI2)\napply safe\napply (erule chain_imp_poset [THEN poset_reflD])\napply (erule_tac [2] chain_imp_poset [THEN poset_transD])\nprefer 2 apply assumption\napply (rule_tac [4] consI2)\napply (erule_tac [5] consI2)\napply (erule_tac [2] leastD2)\napply (erule_tac [5] leastD2)\napply (assumption | (rule consI1 leastD1))+\ndone\n\nlemma least_invrel_iff:\n    \"least(invrel(R), P, x) <-> greatest(R, P, x)\"\napply (unfold least_def greatest_def invrel_def)\napply (rule iff_refl)\ndone\n\nlemma greatest_invrel_iff:\n    \"greatest(invrel(R), P, x) <-> least(R, P, x)\"\napply (unfold least_def greatest_def invrel_def)\napply (rule iff_refl)\ndone\n\n(** minimal/maximal **)\nlemma minimalI:\n  \"[| !!y. [| y: P;  R(y, x) |] ==> y = x; x: P |] ==> minimal(R, P, x)\"\napply (unfold minimal_def)\napply blast\ndone\n\nlemma minimalD1:\n  \"minimal(R, P, x) ==> x: P\"\napply (unfold minimal_def)\napply blast\ndone\n\nlemma minimalD2:\n  \"[| minimal(R, P, x); R(y, x); y: P |] ==> y = x\"\napply (unfold minimal_def)\napply blast\ndone\n\nlemma minimal_subset:\n  \"[| S <= P; minimal(R, P, x); x: S |] ==> minimal(R, S, x)\"\napply (rule minimalI)\napply (erule minimalD2)\napply assumption\napply (erule subsetD)\napply assumption+\ndone\n\nlemma least_imp_minimal:\n  \"[| least(R, P, x); poset(R, P) |] ==> minimal(R, P, x)\"\napply (rule minimalI)\napply (erule poset_antisymD)\napply (erule_tac [2] leastD2)\napply (assumption | (erule leastD1))+\ndone\n\nlemma chain_minimal_imp_least:\n  \"[| minimal(R, P, x); chain(R, P) |] ==> least(R, P, x)\"\napply (rule leastI)\napply (rule chainD2 [THEN disjE])\napply assumption\napply (erule minimalD1)\napply assumption+\napply (drule minimalD2)\napply assumption+\napply hypsubst\napply (erule chainD1 [THEN poset_reflD], assumption)\napply (erule minimalD1)\ndone\n\nlemma minimal_invrel_iff:\n    \"minimal(invrel(R), P, x) <-> maximal(R, P, x)\"\napply (unfold minimal_def maximal_def invrel_def)\napply (rule iff_refl)\ndone\n\nlemma maximal_invrel_iff:\n    \"maximal(invrel(R), P, x) <-> minimal(R, P, x)\"\napply (unfold minimal_def maximal_def invrel_def)\napply (rule iff_refl)\ndone\n\n(** upset/downset **)\nlemma upsetI:\n  \"[| y: P; R(x, y) |] ==> y: upset(R, P, x)\"\napply (unfold upset_def)\napply blast\ndone\n\nlemma upsetE:\n  \"[| y: upset(R, P, x); [| y: P; R(x, y) |] ==> Q |] ==> Q\"\napply (unfold upset_def)\napply blast\ndone\n\nlemma upset_subset:\n    \"upset(R, P, x) <= P\"\napply (blast elim!: upsetE)\ndone\n\nlemma least_upset:\n  \"[| poset(R, P); x: P |] ==> least(R, upset(R, P, x), x)\"\napply (rule leastI)\napply (erule upsetE)\napply (assumption | (rule upsetI) | (erule poset_reflD))+\ndone\n\nlemma upset_invrel_eq:\n    \"upset(invrel(R), P, x) = downset(R, P, x)\"\napply (unfold downset_def upset_def invrel_def)\napply (rule refl)\ndone\n\nlemma downset_invrel_eq:\n    \"downset(invrel(R), P, x) = upset(R, P, x)\"\napply (unfold downset_def upset_def invrel_def)\napply (rule refl)\ndone\n\n(** upperbound/lowerbound **)\nlemma upperboundI:\n  \"[| x: P; !!y. y: S ==> R(y, x) |] ==> x: upperbound(R, P, S)\"\napply (unfold upperbound_def)\napply blast\ndone\n\nlemma upperboundE:\n  \"[| x: upperbound(R, P, S); [| x: P; ALL y: S. R(y, x) |] ==> Q |] ==> Q\"\napply (unfold upperbound_def)\napply blast\ndone\n\nlemma upperbound_invrel_eq:\n    \"upperbound(invrel(R), P, S) = lowerbound(R, P, S)\"\napply (unfold lowerbound_def upperbound_def invrel_def)\napply (rule refl)\ndone\n\nlemma lowerbound_invrel_eq:\n    \"lowerbound(invrel(R), P, S) = upperbound(R, P, S)\"\napply (unfold lowerbound_def upperbound_def invrel_def)\napply (rule refl)\ndone\n\n(** Prove symmetric theorems **)\nlemma greatestI:\n  \"[| !!y. y: P ==> R(y, x); x: P |] ==> greatest(R, P, x)\"\napply (unfold greatest_def)\napply blast\ndone\n\nlemma greatestD1:\n  \"greatest(R, P, x) ==> x: P\"\napply (unfold greatest_def)\napply blast\ndone\n\nlemma greatestD2:\n  \"[| greatest(R, P, x); y: P |] ==> R(y, x)\"\napply (unfold greatest_def)\napply blast\ndone\n\nlemma greatest_unique:\n  \"[| greatest(R, P, x); greatest(R, P, y); poset(R, P) |] ==> x = y\"\napply (simp only: least_invrel_iff [THEN iff_sym])\napply (subst (asm) poset_invrel_iff [THEN iff_sym])\napply (erule least_unique)\napply assumption+\ndone\n\nlemma greatest_subset:\n  \"[| S <= P; greatest(R, P, x); x: S |] ==> greatest(R, S, x)\"\napply (rule greatestI)\napply (drule subsetD)\napply (drule_tac [2] greatestD2)\nby assumption+\n\nlemma Finite_non_empty_chain_has_greatest_element:\n  assumes major: \"Finite(P)\"\n  and prem1: \"chain(R, P)\"\n  and prem2: \"P ~= 0\"\n  shows \"EX x. greatest(R, P, x)\"\napply (insert major prem1 prem2)\napply (simp only: least_invrel_iff [THEN iff_sym])\napply (subst (asm) chain_invrel_iff [THEN iff_sym])\napply (rule Finite_non_empty_chain_has_least_element)\napply assumption+\ndone\n\nlemma maximalI:\n  \"[| !!y. [| y: P;  R(x, y) |] ==> y = x; x: P |] ==> maximal(R, P, x)\"\napply (unfold maximal_def)\napply blast\ndone\n\nlemma maximalD1:\n  \"maximal(R, P, x) ==> x: P\"\napply (unfold maximal_def)\napply blast\ndone\n\nlemma maximalD2:\n  \"[| maximal(R, P, x); R(x, y); y: P |] ==> y = x\"\napply (unfold maximal_def)\napply blast\ndone\n\nlemma maximal_subset:\n  \"[| S <= P; maximal(R, P, x); x: S |] ==> maximal(R, S, x)\"\napply (rule maximalI)\napply (erule maximalD2)\napply assumption\napply (erule subsetD)\napply assumption+\ndone\n\nlemma greatest_imp_maximal:\n  \"[| greatest(R, P, x); poset(R, P) |] ==> maximal(R, P, x)\"\napply (rule maximalI)\napply (erule poset_antisymD)\napply (erule_tac [1] greatestD2)\napply (assumption | (erule greatestD1))+\ndone\n\nlemma chain_maximal_imp_greatest:\n  \"[| maximal(R, P, x); chain(R, P) |] ==> greatest(R, P, x)\"\napply (simp only: least_invrel_iff [THEN iff_sym])\napply (simp only: minimal_invrel_iff [THEN iff_sym])\napply (subst (asm) chain_invrel_iff [THEN iff_sym])\napply (rule chain_minimal_imp_least)\napply assumption+\ndone\n\nlemma downsetI:\n  \"[| y: P; R(y, x) |] ==> y: downset(R, P, x)\"\napply (unfold downset_def)\napply blast\ndone\n\nlemma downsetE:\n  \"[| y: downset(R, P, x); [| y: P; R(y, x) |] ==> Q |] ==> Q\"\napply (unfold downset_def)\napply blast\ndone\n\nlemma downset_subset:\n    \"downset(R, P, x) <= P\"\napply (blast elim!: downsetE)\ndone\n\nlemma greatest_downset:\n  \"[| poset(R, P); x: P |] ==> greatest(R, downset(R, P, x), x)\"\napply (rule greatestI)\napply (erule downsetE)\napply (assumption | (rule downsetI) | (erule poset_reflD))+\ndone\n\nlemma lowerboundI:\n  \"[| x: P; !!y. y: S ==> R(x, y) |] ==> x: lowerbound(R, P, S)\"\napply (unfold lowerbound_def)\napply blast\ndone\n\nlemma lowerboundE:\n  \"[| x: lowerbound(R, P, S); [| x: P; ALL y: S. R(x, y) |] ==> Q |] ==> Q\"\napply (unfold lowerbound_def)\napply blast\ndone\n\nend\n", "meta": {"author": "JRF-2018", "repo": "isabelle_TheLambda", "sha": "e89eff1cbbf26da9bc6a3af603ae9d099d97c1ad", "save_path": "github-repos/isabelle/JRF-2018-isabelle_TheLambda", "path": "github-repos/isabelle/JRF-2018-isabelle_TheLambda/isabelle_TheLambda-e89eff1cbbf26da9bc6a3af603ae9d099d97c1ad/Poset.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527944504227, "lm_q2_score": 0.8289388104343892, "lm_q1q2_score": 0.7062167359779871}}
{"text": "(*  \n    Title:      Elementary_Operations.thy\n    Author:     Jose Divas\u00f3n <jose.divasonm at unirioja.es>\n    Author:     Jes\u00fas Aransay <jesus-maria.aransay at unirioja.es>\n*)\n\nsection\\<open>Elementary Operations over matrices\\<close>\n\ntheory Elementary_Operations\nimports \n  Rank_Nullity_Theorem.Fundamental_Subspaces\n  Code_Matrix\nbegin\n\nsubsection\\<open>Some previous results:\\<close>\n\nlemma mat_1_fun: \"mat 1 $ a $ b = (\\<lambda>i j. if i=j then 1 else 0) a b\" unfolding mat_def by auto\n\nlemma mat1_sum_eq:\n  shows \"(\\<Sum>k\\<in>UNIV. mat (1::'a::{semiring_1}) $ s $ k * mat 1 $ k $ t) = mat 1 $ s $ t\"\nproof (unfold mat_def, auto)\n  let ?f=\"\\<lambda>k. (if t = k then 1::'a else (0::'a)) * (if k = t then 1::'a else (0::'a))\"\n  have univ_eq: \"UNIV = (UNIV - {t}) \\<union> {t}\" by fast\n  have \"sum ?f UNIV = sum ?f ((UNIV - {t}) \\<union> {t}) \" using univ_eq by simp\n  also have \"... = sum ?f (UNIV - {t}) + sum ?f {t}\" by (rule sum.union_disjoint, auto)\n  also have \"... = 0 + sum ?f {t}\" by auto\n  also have \"... = sum ?f {t}\" by simp\n  also have \"... = 1\" by simp\n  finally show \"sum ?f UNIV = 1\" .\nnext\n  assume s_not_t: \"s \\<noteq> t\"\n  let ?g=\"\\<lambda>k. (if s = k then 1::'a else 0) * (if k = t then 1 else 0)\"\n  have \"sum ?g UNIV = sum (\\<lambda>k. 0::'a) (UNIV::'b set)\" by (rule sum.cong, auto simp add: s_not_t)\n  also have \"... = 0\" by simp\n  finally show \"sum ?g UNIV = 0\" .\nqed\n\n\nlemma invertible_mat_n:\n  fixes n::\"'a::{field}\"\n  assumes n: \"n \\<noteq> 0\"\n  shows \"invertible ((mat n)::'a^'n^'n)\"\nproof (unfold invertible_def, rule exI[of _ \"mat (inverse n)\"], rule conjI)\n  show \"mat n ** mat (inverse n) = (mat 1::'a^'n^'n)\"\n  proof (unfold matrix_matrix_mult_def mat_def, vector, auto)\n    fix ia::'n\n    let ?f=\"(\\<lambda>k. (if ia = k then n else 0) * (if k = ia then inverse n else 0))\"\n    have UNIV_rw: \"(UNIV::'n set) = insert ia (UNIV-{ia})\" by auto\n    have \"(\\<Sum>k\\<in>(UNIV::'n set). (if ia = k then n else 0) * (if k = ia then inverse n else 0)) = \n      (\\<Sum>k\\<in>insert ia (UNIV-{ia}). (if ia = k then n else 0) * (if k = ia then inverse n else 0))\" using UNIV_rw by simp\n    also have \"... = ?f ia + sum ?f (UNIV-{ia})\"\n    proof (rule sum.insert)\n      show \"finite (UNIV - {ia})\"  using finite_UNIV by fastforce\n      show \"ia \\<notin> UNIV - {ia}\" by fast\n    qed\n    also have \"... = 1\" using right_inverse[OF n] by simp\n    finally show \" (\\<Sum>k\\<in>(UNIV::'n set). (if ia = k then n else 0) * (if k = ia then inverse n else 0)) = (1::'a)\" .\n    fix i::'n\n    assume i_not_ia: \"i \\<noteq> ia\"\n    show \"(\\<Sum>k\\<in>(UNIV::'n set). (if i = k then n else 0) * (if k = ia then inverse n else 0)) = 0\" by (rule sum.neutral, simp add: i_not_ia)\n  qed\nnext\n  show \"mat (inverse n) ** mat n = ((mat 1)::'a^'n^'n)\"\n  proof (unfold matrix_matrix_mult_def mat_def, vector, auto)\n    fix ia::'n\n    let ?f=\" (\\<lambda>k. (if ia = k then inverse n else 0) * (if k = ia then n else 0))\"\n    have UNIV_rw: \"(UNIV::'n set) = insert ia (UNIV-{ia})\" by auto\n    have \"(\\<Sum>k\\<in>(UNIV::'n set). (if ia = k then inverse n else 0) * (if k = ia then n else 0)) = \n      (\\<Sum>k\\<in>insert ia (UNIV-{ia}). (if ia = k then inverse n else 0) * (if k = ia then n else 0))\" using UNIV_rw by simp\n    also have \"... = ?f ia + sum ?f (UNIV-{ia})\"\n    proof (rule sum.insert)\n      show \"finite (UNIV - {ia})\"  using finite_UNIV by fastforce\n      show \"ia \\<notin> UNIV - {ia}\" by fast\n    qed\n    also have \"... = 1\" using left_inverse[OF n] by simp\n    finally show \" (\\<Sum>k\\<in>(UNIV::'n set). (if ia = k then inverse n else 0) * (if k = ia then n else 0)) = (1::'a)\" .\n    fix i::'n\n    assume i_not_ia: \"i \\<noteq> ia\"\n    show \"(\\<Sum>k\\<in>(UNIV::'n set). (if i = k then inverse n else 0) * (if k = ia then n else 0)) = 0\" by (rule sum.neutral, simp add: i_not_ia)\n  qed\nqed\n\ncorollary invertible_mat_1:\n  shows \"invertible (mat (1::'a::{field}))\" by (metis invertible_mat_n zero_neq_one)\n\nsubsection\\<open>Definitions of elementary row and column operations\\<close>\n\ntext\\<open>Definitions of elementary row operations\\<close>\n\ndefinition interchange_rows :: \"'a ^'n^'m => 'm => 'm \\<Rightarrow> 'a ^'n^'m\"\n  where \"interchange_rows A a b = (\\<chi> i j. if i=a then A $ b $ j else if i=b then A $ a $ j else A $ i $ j)\"\n\ndefinition mult_row :: \"('a::times) ^'n^'m => 'm => 'a \\<Rightarrow> 'a ^'n^'m\"\n  where \"mult_row A a q = (\\<chi> i j. if i=a then q*(A $ a $ j) else A $ i $ j)\"\n\ndefinition row_add :: \"('a::{plus, times}) ^'n^'m => 'm => 'm \\<Rightarrow> 'a \\<Rightarrow> 'a ^'n^'m\"\n  where \"row_add A a b q = (\\<chi> i j. if i=a then (A $ a $ j) + q*(A $ b $ j) else A $ i $ j)\"\n\ntext\\<open>Definitions of elementary column operations\\<close>\n\ndefinition interchange_columns :: \"'a ^'n^'m => 'n => 'n \\<Rightarrow> 'a ^'n^'m\"\n  where \"interchange_columns A n m = (\\<chi> i j. if j=n then A $ i $ m else if j=m then A $ i $ n else A $ i $ j)\"\n\ndefinition mult_column :: \"('a::times) ^'n^'m => 'n => 'a \\<Rightarrow> 'a ^'n^'m\"\n  where \" mult_column A n q = (\\<chi> i j. if j=n then (A $ i $ j)*q else A $ i $ j)\"\n\ndefinition column_add :: \"('a::{plus, times}) ^'n^'m => 'n => 'n \\<Rightarrow> 'a \\<Rightarrow> 'a ^'n^'m\"\n  where \"column_add A n m q = (\\<chi> i j. if j=n then ((A $ i $ n) + (A $ i $ m)*q) else A $ i $ j)\"\n\nsubsection\\<open>Properties about elementary row operations\\<close>\nsubsubsection\\<open>Properties about interchanging rows\\<close>\n\ntext\\<open>Properties about @{term \"interchange_rows\"}\\<close>\n\nlemma interchange_same_rows: \"interchange_rows A a a = A\"\n  unfolding interchange_rows_def by vector\n\nlemma interchange_rows_i[simp]: \"interchange_rows A i j $ i = A $ j\"\n  unfolding interchange_rows_def by vector\n\nlemma interchange_rows_j[simp]: \"interchange_rows A i j $ j = A $ i\"\n  unfolding interchange_rows_def by vector\n\nlemma interchange_rows_preserves:\n  assumes \"i \\<noteq> a\" and \"j \\<noteq> a\"\n  shows \"interchange_rows A i j $ a = A $ a\"\n  using assms unfolding interchange_rows_def by vector\n\nlemma interchange_rows_mat_1:\n  shows \"interchange_rows (mat 1) a b ** A = interchange_rows A a b\"\nproof (unfold matrix_matrix_mult_def interchange_rows_def, vector, auto)\n  fix ia\n  let ?f=\"(\\<lambda>k. mat (1::'a) $ a $ k * A $ k $ ia)\"\n  have univ_rw:\"UNIV = (UNIV-{a}) \\<union> {a}\" by auto\n  have \"sum ?f UNIV = sum ?f ((UNIV-{a}) \\<union> {a})\" using univ_rw by auto\n  also have \"... = sum ?f (UNIV-{a}) + sum ?f {a}\"\n  proof (rule sum.union_disjoint)\n    show \"finite (UNIV - {a})\" by (metis finite_code) \n    show \"finite {a}\" by simp\n    show \"(UNIV - {a}) \\<inter> {a} = {}\" by simp\n  qed\n  also have \"... = sum ?f {a}\" unfolding mat_def by auto\n  also have \"... = ?f a\" by auto\n  also have \"... = A $ a $ ia\" unfolding mat_def by auto\n  finally show \"(\\<Sum>k\\<in>UNIV. mat (1::'a) $ a $ k * A $ k $ ia) = A $ a $ ia\" .\n  assume i: \" a \\<noteq> b\"\n  let ?g= \"\\<lambda>k. mat (1::'a) $ b $ k * A $ k $ ia\"\n  have univ_rw':\"UNIV = (UNIV-{b}) \\<union> {b}\" by auto\n  have \"sum ?g UNIV = sum ?g ((UNIV-{b}) \\<union> {b})\" using univ_rw' by auto\n  also have \"... = sum ?g (UNIV-{b}) + sum ?g {b}\" by (rule sum.union_disjoint, auto)\n  also have \"... = sum ?g {b}\"  unfolding mat_def by auto\n  also have \"... = ?g b\" by simp\n  finally show \"(\\<Sum>k\\<in>UNIV. mat (1::'a) $ b $ k * A $ k $ ia) = A $ b $ ia\" unfolding mat_def by simp\nnext\n  fix i j\n  assume ib: \"i \\<noteq> b\" and ia:\"i \\<noteq> a\"\n  let ?h=\"\\<lambda>k. mat (1::'a) $ i $ k * A $ k $ j\"\n  have univ_rw'':\"UNIV = (UNIV-{i}) \\<union> {i}\" by auto\n  have \"sum ?h UNIV = sum ?h ((UNIV-{i}) \\<union> {i})\" using univ_rw'' by auto\n  also have \"... = sum ?h (UNIV-{i}) + sum ?h {i}\"  by (rule sum.union_disjoint, auto)\n  also have \"... =  sum ?h {i}\" unfolding mat_def by auto  \n  also have \"... = ?h i\" by simp\n  finally show \" (\\<Sum>k\\<in>UNIV. mat (1::'a) $ i $ k * A $ k $ j) = A $ i $ j\" unfolding mat_def by auto\nqed\n\n\n\nsubsubsection\\<open>Properties about multiplying a row by a constant\\<close>\ntext\\<open>Properties about @{term \"mult_row\"}\\<close>\n\nlemma mult_row_mat_1: \"mult_row (mat 1) a q ** A = mult_row A a q\"\nproof (unfold matrix_matrix_mult_def mult_row_def, vector, auto)\n  fix ia\n  let ?f=\"\\<lambda>k. q * mat (1::'a) $ a $ k * A $ k $ ia\"\n  have univ_rw:\"UNIV = (UNIV-{a}) \\<union> {a}\" by auto\n  have \"sum ?f UNIV = sum ?f ((UNIV-{a}) \\<union> {a})\" using univ_rw by auto\n  also have \"... = sum ?f (UNIV-{a}) + sum ?f {a}\" by (rule sum.union_disjoint, auto)\n  also have \"... = sum ?f {a}\" unfolding mat_def by auto  \n  also have \"... = ?f a\" by auto\n  also have \"... = q * A $ a $ ia\" unfolding mat_def by auto\n  finally show  \"(\\<Sum>k\\<in>UNIV. q * mat (1::'a) $ a $ k * A $ k $ ia) = q * A $ a $ ia\" .\n  fix i\n  assume i: \"i \\<noteq> a\"\n  let ?g=\"\\<lambda>k. mat (1::'a) $ i $ k * A $ k $ ia\"\n  have univ_rw'':\"UNIV = (UNIV-{i}) \\<union> {i}\" by auto\n  have \"sum ?g UNIV = sum ?g ((UNIV-{i}) \\<union> {i})\" using univ_rw'' by auto\n  also have \"... = sum ?g (UNIV-{i}) + sum ?g {i}\"  by (rule sum.union_disjoint, auto)\n  also have \"... =  sum ?g {i}\" unfolding mat_def by auto \n  also have \"... = ?g i\" by simp\n  finally show \"(\\<Sum>k\\<in>UNIV. mat (1::'a) $ i $ k * A $ k $ ia) = A $ i $ ia\" unfolding mat_def by simp\nqed\n\nlemma invertible_mult_row:\n  assumes qk: \"q * k = 1\" and kq: \"k*q=1\"\n  shows \"invertible (mult_row (mat 1) a q)\"\nproof (unfold invertible_def, rule exI[of _ \"mult_row (mat 1) a k\"],rule conjI)\n  show \"mult_row (mat (1::'a)) a q ** mult_row (mat (1::'a)) a k = mat (1::'a)\"\n  proof (unfold matrix_matrix_mult_def, vector, clarify, unfold mult_row_def, vector, unfold mat_1_fun, auto)\n    show \"(\\<Sum>ka\\<in>UNIV. q * (if a = ka then 1::'a else (0::'a)) * (if ka = a then k * (1::'a) else if ka = a then 1::'a else (0::'a))) = (1::'a)\"\n    proof -\n      let ?f=\"\\<lambda>ka. q * (if a = ka then 1::'a else (0::'a)) * (if ka = a then k * (1::'a) else if ka = a then 1::'a else (0::'a)) \"\n      have univ_eq: \"UNIV = ((UNIV - {a}) \\<union> {a})\" by auto\n      have \"sum ?f UNIV = sum ?f ((UNIV - {a}) \\<union> {a}) \" using univ_eq by simp\n      also have \"... = sum ?f (UNIV - {a}) + sum ?f {a}\" by (rule sum.union_disjoint, auto)\n      also have \"... = 0 + sum ?f {a}\" by auto\n      also have \"... = sum ?f {a}\" by simp\n      also have \"... = 1\" using qk by simp\n      finally show ?thesis .        \n    qed\n  next\n    fix s\n    assume s_noteq_a: \"s\\<noteq>a\"\n    show \"(\\<Sum>ka\\<in>UNIV. (if s = ka then 1::'a else (0::'a)) * (if ka = a then k * (1::'a) else if ka = a then 1::'a else 0)) = 0\"\n      by (rule sum.neutral, simp add: s_noteq_a)\n  next\n    fix t\n    assume a_noteq_t: \"a\\<noteq>t\"\n    show \"(\\<Sum>ka\\<in>UNIV. (if t = ka then 1::'a else (0::'a)) * (if ka = a then k * (0::'a) else if ka = t then 1::'a else (0::'a))) = (1::'a)\"\n    proof -\n      let ?f=\"\\<lambda>ka. (if t = ka then 1::'a else (0::'a)) * (if ka = a then k * (0::'a) else if ka = t then 1::'a else (0::'a)) \"\n      have univ_eq: \"UNIV = ((UNIV - {t}) \\<union> {t})\" by auto\n      have \"sum ?f UNIV = sum ?f ((UNIV - {t}) \\<union> {t}) \" using univ_eq by simp\n      also have \"... = sum ?f (UNIV - {t}) + sum ?f {t}\" by (rule sum.union_disjoint, auto)\n      also have \"... = sum ?f {t}\" by simp\n      also have \"... = 1\" using a_noteq_t by auto\n      finally show ?thesis .\n    qed            \n    fix s\n    assume s_not_t: \"s\\<noteq>t\"\n    show \"(\\<Sum>ka\\<in>UNIV. (if s = a then q * (if a = ka then 1::'a else (0::'a)) else if s = ka then 1::'a else (0::'a)) *\n      (if ka = a then k * (0::'a) else if ka = t then 1::'a else (0::'a))) = (0::'a)\"\n      by (rule sum.neutral, simp add: s_not_t a_noteq_t)\n  qed            \n  show \"mult_row (mat (1::'a)) a k ** mult_row (mat (1::'a)) a q = mat (1::'a)\"\n  proof (unfold matrix_matrix_mult_def, vector, clarify, unfold mult_row_def, vector, unfold mat_1_fun, auto)\n    show \"(\\<Sum>ka\\<in>UNIV. k * (if a = ka then 1::'a else (0::'a)) * (if ka = a then q * (1::'a) else if ka = a then 1::'a else (0::'a))) = (1::'a)\"\n    proof -\n      let ?f=\"\\<lambda>ka. k * (if a = ka then 1::'a else (0::'a)) * (if ka = a then q * (1::'a) else if ka = a then 1::'a else (0::'a)) \"\n      have univ_eq: \"UNIV = ((UNIV - {a}) \\<union> {a})\" by auto\n      have \"sum ?f UNIV = sum ?f ((UNIV - {a}) \\<union> {a}) \" using univ_eq by simp\n      also have \"... = sum ?f (UNIV - {a}) + sum ?f {a}\" by (rule sum.union_disjoint, auto)\n      also have \"... = 0 + sum ?f {a}\" by auto\n      also have \"... = sum ?f {a}\" by simp\n      also have \"... = 1\" using kq by simp\n      finally show ?thesis .        \n    qed\n  next\n    fix s\n    assume s_not_a: \"s\\<noteq>a\"\n    show \"(\\<Sum>k\\<in>UNIV. (if s = k then 1::'a else (0::'a)) * (if k = a then q * (1::'a) else if k = a then 1::'a else (0::'a))) = (0::'a)\"\n      by (rule sum.neutral, simp add: s_not_a)\n  next\n    fix t\n    assume a_not_t: \"a\\<noteq>t\"\n    show \"(\\<Sum>k\\<in>UNIV. (if t = k then 1::'a else (0::'a)) * (if k = a then q * (0::'a) else if k = t then 1::'a else (0::'a))) = (1::'a)\"\n    proof -\n      let ?f=\"\\<lambda>k. (if t = k then 1::'a else (0::'a)) * (if k = a then q * (0::'a) else if k = t then 1::'a else (0::'a))\"\n      have univ_eq: \"UNIV = ((UNIV - {t}) \\<union> {t})\" by auto\n      have \"sum ?f UNIV = sum ?f ((UNIV - {t}) \\<union> {t}) \" using univ_eq by simp\n      also have \"... = sum ?f (UNIV - {t}) + sum ?f {t}\" by (rule sum.union_disjoint, auto)\n      also have \"... = sum ?f {t}\" by simp\n      also have \"... = 1\" using a_not_t by simp\n      finally show ?thesis .\n    qed\n    fix s\n    assume s_not_t: \"s\\<noteq>t\"\n    show \" (\\<Sum>ka\\<in>UNIV. (if s = a then k * (if a = ka then 1::'a else (0::'a)) else if s = ka then 1::'a else (0::'a)) *\n      (if ka = a then q * (0::'a) else if ka = t then 1::'a else (0::'a))) = (0::'a)\"\n      by (rule sum.neutral, simp add: s_not_t)    \n  qed\nqed\n\ncorollary invertible_mult_row':\n  assumes q_not_zero: \"q \\<noteq> 0\"\n  shows \"invertible (mult_row (mat (1::'a::{field})) a q)\"\n  by (simp add: invertible_mult_row[of q \"inverse q\"] q_not_zero)\n\nsubsubsection\\<open>Properties about adding a row multiplied by a constant to another row\\<close>\ntext\\<open>Properties about @{term \"row_add\"}\\<close>\n\nlemma row_add_mat_1: \"row_add (mat 1) a b q ** A = row_add A a b q\"\nproof (unfold matrix_matrix_mult_def row_add_def, vector, auto)\n  fix j\n  let ?f=\" (\\<lambda>k. (mat (1::'a) $ a $ k + q * mat (1::'a) $ b $ k) * A $ k $ j)\"\n  show \"sum ?f UNIV = A $ a $ j + q * A $ b $ j\"\n  proof (cases \"a=b\")\n    case False\n    have univ_rw: \"UNIV = {a} \\<union> ({b} \\<union> (UNIV - {a} - {b}))\" by auto\n    have sum_rw: \"sum ?f ({b} \\<union> (UNIV - {a} - {b})) = sum ?f {b} + sum ?f (UNIV - {a} - {b})\" by (rule sum.union_disjoint, auto simp add: False)\n    have \"sum ?f UNIV = sum ?f ({a} \\<union> ({b} \\<union> (UNIV - {a} - {b})))\" using univ_rw by simp\n    also have \"... = sum ?f {a} + sum ?f ({b} \\<union> (UNIV - {a} - {b}))\" by (rule sum.union_disjoint, auto simp add: False)\n    also have \"... = sum ?f {a} + sum ?f {b} + sum ?f (UNIV - {a} - {b})\" unfolding sum_rw add.assoc ..\n    also have \"... = sum ?f {a} + sum ?f {b}\"\n    proof -\n      have \"sum ?f (UNIV - {a} - {b}) = sum (\\<lambda>k. 0) (UNIV - {a} - {b})\" unfolding mat_def by (rule sum.cong, auto)\n      also have \"... = 0\" unfolding sum.neutral_const ..\n      finally show ?thesis by simp\n    qed\n    also have \"... = A $ a $ j + q * A $ b $ j\" using False unfolding mat_def by simp\n    finally show ?thesis .\n  next\n    case True\n    have univ_rw: \"UNIV = {b} \\<union> (UNIV - {b})\" by auto\n    have \"sum ?f UNIV = sum ?f ({b} \\<union> (UNIV - {b}))\" using univ_rw by simp\n    also have \"... = sum ?f {b} + sum ?f (UNIV  - {b})\" by (rule sum.union_disjoint, auto)\n    also have \"... = sum ?f {b}\"\n    proof -\n      have \"sum ?f (UNIV - {b}) = sum (\\<lambda>k. 0) (UNIV - {b})\" using True unfolding mat_def by auto\n      also have \"... = 0\" unfolding sum.neutral_const ..\n      finally show ?thesis by simp\n    qed\n    also have \"... = A $ a $ j + q * A $ b $ j\" \n      by (unfold True mat_def, simp, metis (hide_lams, no_types) vector_add_component vector_sadd_rdistrib vector_smult_component vector_smult_lid)\n    finally show ?thesis .\n  qed\n  fix i assume i: \"i\\<noteq>a\"\n  let ?g=\"\\<lambda>k.  mat (1::'a) $ i $ k * A $ k $ j\"\n  have univ_rw: \"UNIV = {i} \\<union> (UNIV - {i})\" by auto\n  have \"sum ?g UNIV = sum ?g ({i} \\<union> (UNIV - {i}))\" using univ_rw by simp\n  also have \"... = sum ?g {i} + sum ?g (UNIV - {i})\" by (rule sum.union_disjoint, auto)\n  also have \"... = sum ?g {i}\"\n  proof -\n    have \"sum ?g (UNIV - {i}) = sum (\\<lambda>k. 0) (UNIV - {i})\" unfolding mat_def by auto\n    also have \"... = 0\" unfolding sum.neutral_const ..\n    finally show ?thesis by simp\n  qed\n  also have \"... =  A $ i $ j\" unfolding mat_def by simp\n  finally show \"(\\<Sum>k\\<in>UNIV. mat (1::'a) $ i $ k * A $ k $ j) = A $ i $ j\" .\nqed\n\nlemma invertible_row_add:\n  assumes a_noteq_b: \"a\\<noteq>b\"\n  shows \"invertible (row_add (mat (1::'a::{ring_1})) a b q)\"\nproof (unfold invertible_def, rule exI[of _ \"(row_add (mat 1) a b (-q))\"], rule conjI)\n  show \"row_add (mat (1::'a)) a b q ** row_add (mat (1::'a)) a b (- q) = mat (1::'a)\" using a_noteq_b\n  proof (unfold matrix_matrix_mult_def, vector, clarify, unfold row_add_def, vector, unfold mat_1_fun, auto)\n    show \" (\\<Sum>k::'b\\<in>UNIV. (if b = k then 1::'a else (0::'a)) * (if k = a then (0::'a) + - q * (1::'a) else if k = b then 1::'a else (0::'a))) = (1::'a)\"\n    proof -\n      let ?f=\"\\<lambda>k. (if b = k then 1::'a else (0::'a)) * (if k = a then (0::'a) + - q * (1::'a) else if k = b then 1::'a else (0::'a))\"\n      have univ_eq: \"UNIV = ((UNIV - {b}) \\<union> {b})\" by auto\n      have \"sum ?f UNIV = sum ?f ((UNIV - {b}) \\<union> {b}) \" using univ_eq by simp\n      also have \"... = sum ?f (UNIV - {b}) + sum ?f {b}\" by (rule sum.union_disjoint, auto)\n      also have \"... = 0 + sum ?f {b}\" by auto\n      also have \"... = sum ?f {b}\" by simp\n      also have \"... = 1\" using a_noteq_b by simp\n      finally show ?thesis .\n    qed\n    show \"(\\<Sum>k::'b\\<in>UNIV. ((if a = k then 1::'a else (0::'a)) + q * (if b = k then 1::'a else (0::'a))) * (if k = a then (1::'a) + - \n      q * (0::'a) else if k = a then 1::'a else (0::'a))) = (1::'a)\"\n    proof -\n      let ?f=\"\\<lambda>k.  ((if a = k then 1::'a else (0::'a)) + q * (if b = k then 1::'a else (0::'a))) * (if k = a then (1::'a) + - \n        q * (0::'a) else if k = a then 1::'a else (0::'a))\"\n      have univ_eq: \"UNIV = ((UNIV - {a}) \\<union> {a})\" by auto\n      have \"sum ?f UNIV = sum ?f ((UNIV - {a}) \\<union> {a}) \" using univ_eq by simp\n      also have \"... = sum ?f (UNIV - {a}) + sum ?f {a}\" by (rule sum.union_disjoint, auto)\n      also have \"... = 0 + sum ?f {a}\" by auto\n      also have \"... = sum ?f {a}\" by simp\n      also have \"... = 1\" using a_noteq_b by simp\n      finally show ?thesis .\n    qed\n  next\n    fix s\n    assume s_not_a: \"s \\<noteq> a\"\n    show \"(\\<Sum>k::'b\\<in>UNIV. (if s = k then 1::'a else (0::'a)) * (if k = a then (1::'a) + - q * (0::'a) else if k = a then 1::'a else (0::'a))) = (0::'a)\"\n      by (rule sum.neutral, auto simp add: s_not_a)       \n  next\n    fix t\n    assume b_not_t: \"b \\<noteq> t\" and a_not_t: \"a \\<noteq> t\"\n    show \"(\\<Sum>k\\<in>UNIV. (if t = k then 1::'a else (0::'a)) * (if k = a then (0::'a) + - q * (0::'a) else if k = t then 1::'a else (0::'a))) = (1::'a)\"\n    proof -\n      let ?f=\"\\<lambda>k. (if t = k then 1::'a else (0::'a)) * (if k = a then (0::'a) + - q * (0::'a) else if k = t then 1::'a else (0::'a)) \"\n      have univ_eq: \"UNIV = ((UNIV - {t}) \\<union> {t})\" by auto\n      have \"sum ?f UNIV = sum ?f ((UNIV - {t}) \\<union> {t}) \" using univ_eq by simp\n      also have \"... = sum ?f (UNIV - {t}) + sum ?f {t}\" by (rule sum.union_disjoint, auto)\n      also have \"... = 0 + sum ?f {t}\" by auto\n      also have \"... = sum ?f {t}\" by simp\n      also have \"... = 1\" using b_not_t a_not_t by simp\n      finally show ?thesis .\n    qed\n  next     \n    fix s t\n    assume  b_not_t: \"b \\<noteq> t\" and a_not_t: \"a \\<noteq> t\" and  s_not_t: \"s \\<noteq> t\"\n    show \" (\\<Sum>k\\<in>UNIV. (if s = a then (if a = k then 1::'a else (0::'a)) + q * (if b = k then 1::'a else (0::'a)) else if s = k then 1::'a else (0::'a)) *\n      (if k = a then (0::'a) + - q * (0::'a) else if k = t then 1::'a else (0::'a))) = (0::'a)\" by (rule sum.neutral, auto simp add: b_not_t a_not_t s_not_t)     \n  next         \n    fix s\n    assume s_not_b: \"s\\<noteq>b\"\n    let ?f=\"\\<lambda>k. (if s = a then (if a = k then 1::'a else (0::'a)) + q * (if b = k then 1::'a else (0::'a)) else if s = k then 1::'a else (0::'a)) *\n      (if k = a then (0::'a) + - q * (1::'a) else if k = b then 1::'a else (0::'a))\"\n    show \"sum ?f UNIV = (0::'a)\"         \n    proof (cases \"s=a\")         \n      case False\n      show ?thesis by (rule sum.neutral, auto simp add: False s_not_b a_noteq_b)\n    next         \n      case True \\<comment> \\<open>This case is different from the other cases\\<close>                  \n      have univ_eq: \"UNIV = ((UNIV - {a}- {b}) \\<union> ({b} \\<union> {a}))\" by auto\n      have sum_a: \"sum ?f {a} = -q\"  unfolding True using s_not_b using a_noteq_b by auto\n      have sum_b: \"sum ?f {b} = q\" unfolding True using s_not_b using a_noteq_b by auto\n      have sum_rest: \"sum ?f (UNIV - {a} - {b}) = 0\"  by (rule sum.neutral, auto simp add: True s_not_b a_noteq_b)\n      have \"sum ?f UNIV = sum ?f ((UNIV - {a}- {b}) \\<union> ({b} \\<union> {a}))\"  using univ_eq by simp\n      also have \"... = sum ?f (UNIV - {a} - {b}) + sum ?f ({b} \\<union> {a})\" by (rule sum.union_disjoint, auto)\n      also have \"... = sum ?f (UNIV - {a} - {b}) + sum ?f {b} + sum ?f {a}\" by (auto simp add: sum.union_disjoint a_noteq_b)     \n      also have \"... = 0\" unfolding sum_a sum_b sum_rest by simp\n      finally show ?thesis .\n    qed\n  qed\nnext\n  show \"row_add (mat (1::'a)) a b (- q) ** row_add (mat (1::'a)) a b q = mat (1::'a)\" using a_noteq_b\n  proof (unfold matrix_matrix_mult_def, vector, clarify, unfold row_add_def, vector, unfold mat_1_fun, auto)     \n    show \"(\\<Sum>k\\<in>UNIV. (if b = k then 1::'a else (0::'a)) * (if k = a then (0::'a) + q * (1::'a) else if k = b then 1::'a else (0::'a))) = (1::'a)\"\n    proof -\n      let ?f=\"\\<lambda>k. (if b = k then 1::'a else (0::'a)) * (if k = a then (0::'a) + q * (1::'a) else if k = b then 1::'a else (0::'a))\"\n      have univ_eq: \"UNIV = ((UNIV - {b}) \\<union> {b})\" by auto\n      have \"sum ?f UNIV = sum ?f ((UNIV - {b}) \\<union> {b}) \" using univ_eq by simp\n      also have \"... = sum ?f (UNIV - {b}) + sum ?f {b}\" by (rule sum.union_disjoint, auto)\n      also have \"... = 0 + sum ?f {b}\" by auto\n      also have \"... = sum ?f {b}\" by simp\n      also have \"... = 1\" using a_noteq_b by simp\n      finally show ?thesis .\n    qed\n  next\n    show \"(\\<Sum>k\\<in>UNIV. ((if a = k then 1 else 0) - q * (if b = k then 1 else 0)) * (if k = a then 1 + q * 0 else if k = a then 1 else 0)) = 1\"\n    proof -\n      let ?f=\"\\<lambda>k. ((if a = k then 1::'a else (0::'a)) + - (q * (if b = k then 1::'a else (0::'a)))) * (if k = a then (1::'a) + q * (0::'a) else if k = a then 1::'a else (0::'a))\"\n      have univ_eq: \"UNIV = ((UNIV - {a}) \\<union> {a})\" by auto\n      have \"sum ?f UNIV = sum ?f ((UNIV - {a}) \\<union> {a}) \" using univ_eq by simp\n      also have \"... = sum ?f (UNIV - {a}) + sum ?f {a}\" by (rule sum.union_disjoint, auto)\n      also have \"... = 0 + sum ?f {a}\" by auto\n      also have \"... = sum ?f {a}\" by simp\n      also have \"... = 1\" using a_noteq_b by simp\n      finally show ?thesis by simp\n    qed\n  next\n    fix s\n    assume s_not_a: \"s\\<noteq>a\"\n    show \"(\\<Sum>k\\<in>UNIV. (if s = k then 1::'a else (0::'a)) * (if k = a then (1::'a) + q * (0::'a) else if k = a then 1::'a else (0::'a))) = (0::'a)\"\n      by (rule sum.neutral, auto simp add: s_not_a)\n  next \n    fix t\n    assume b_not_t: \"b \\<noteq> t\" and a_not_t: \"a \\<noteq> t\"\n    show \"(\\<Sum>k\\<in>UNIV. (if t = k then 1::'a else (0::'a)) * (if k = a then (0::'a) + q * (0::'a) else if k = t then 1::'a else (0::'a))) = (1::'a)\"\n    proof -\n      let ?f=\"\\<lambda>k. (if t = k then 1::'a else (0::'a)) * (if k = a then (0::'a) + q * (0::'a) else if k = t then 1::'a else (0::'a))\"\n      have univ_eq: \"UNIV = ((UNIV - {t}) \\<union> {t})\" by auto\n      have \"sum ?f UNIV = sum ?f ((UNIV - {t}) \\<union> {t}) \" using univ_eq by simp\n      also have \"... = sum ?f (UNIV - {t}) + sum ?f {t}\" by (rule sum.union_disjoint, auto)\n      also have \"... = 0 + sum ?f {t}\" by auto\n      also have \"... = sum ?f {t}\" by simp\n      also have \"... = 1\" using b_not_t a_not_t by simp\n      finally show ?thesis .\n    qed\n  next\n    fix s t\n    assume b_not_t: \"b \\<noteq> t\" and a_not_t: \"a \\<noteq> t\" and s_not_t: \"s \\<noteq> t\"     \n    show \"(\\<Sum>k\\<in>UNIV. (if s = a then (if a = k then 1::'a else (0::'a)) + - q * (if b = k then 1::'a else (0::'a)) else if s = k then 1::'a else (0::'a)) *\n      (if k = a then (0::'a) + q * (0::'a) else if k = t then 1::'a else (0::'a))) = (0::'a)\"\n      by (rule sum.neutral, auto simp add: b_not_t a_not_t s_not_t)\n  next\n    fix s\n    assume s_not_b: \"s\\<noteq>b\"\n    let ?f=\"\\<lambda>k.(if s = a then (if a = k then 1::'a else (0::'a)) + - q * (if b = k then 1::'a else (0::'a)) else if s = k then 1::'a else (0::'a)) \n      * (if k = a then (0::'a) + q * (1::'a) else if k = b then 1::'a else (0::'a))\"\n    show \"sum ?f UNIV = 0\"\n    proof (cases \"s=a\")         \n      case False\n      show ?thesis by (rule sum.neutral, auto simp add: False s_not_b a_noteq_b)\n    next         \n      case True \\<comment> \\<open>This case is different from the other cases\\<close>                  \n      have univ_eq: \"UNIV = ((UNIV - {a}- {b}) \\<union> ({b} \\<union> {a}))\" by auto\n      have sum_a: \"sum ?f {a} = q\"  unfolding True using s_not_b using a_noteq_b by auto\n      have sum_b: \"sum ?f {b} = -q\" unfolding True using s_not_b using a_noteq_b by auto\n      have sum_rest: \"sum ?f (UNIV - {a} - {b}) = 0\"  by (rule sum.neutral, auto simp add: True s_not_b a_noteq_b)\n      have \"sum ?f UNIV = sum ?f ((UNIV - {a}- {b}) \\<union> ({b} \\<union> {a}))\"  using univ_eq by simp\n      also have \"... = sum ?f (UNIV - {a} - {b}) + sum ?f ({b} \\<union> {a})\" by (rule sum.union_disjoint, auto)\n      also have \"... = sum ?f (UNIV - {a} - {b}) + sum ?f {b} + sum ?f {a}\" by (auto simp add: sum.union_disjoint a_noteq_b)\n      also have \"... = 0\" unfolding sum_a sum_b sum_rest by simp\n      finally show ?thesis .\n    qed\n  qed\nqed\n\nsubsection\\<open>Properties about elementary column operations\\<close>\nsubsubsection\\<open>Properties about interchanging columns\\<close>\ntext\\<open>Properties about @{term \"interchange_columns\"}\\<close>\n\nlemma interchange_columns_mat_1: \"A ** interchange_columns (mat 1) a b = interchange_columns A a b\"\nproof (unfold matrix_matrix_mult_def, unfold interchange_columns_def, vector, auto) \n  fix i  \n  show \"(\\<Sum>k\\<in>UNIV. A $ i $ k * mat (1::'a) $ k $ a) = A $ i $ a\"\n  proof -\n    let ?f=\"(\\<lambda>k. A $ i $ k * mat (1::'a) $ k $ a)\"\n    have univ_rw:\"UNIV = (UNIV-{a}) \\<union> {a}\" by auto\n    have \"sum ?f UNIV = sum ?f ((UNIV-{a}) \\<union> {a})\" using univ_rw by auto\n    also have \"... = sum ?f (UNIV-{a}) + sum ?f {a}\" by (rule sum.union_disjoint, auto)\n    also have \"... = sum ?f {a}\" unfolding mat_def by auto\n    finally show ?thesis unfolding mat_def by simp\n  qed    \n  assume a_not_b: \"a\\<noteq>b\"\n  show \" (\\<Sum>k\\<in>UNIV. A $ i $ k * mat (1::'a) $ k $ b) = A $ i $ b\"\n  proof -\n    let ?f=\"(\\<lambda>k. A $ i $ k * mat (1::'a) $ k $ b)\"\n    have univ_rw:\"UNIV = (UNIV-{b}) \\<union> {b}\" by auto\n    have \"sum ?f UNIV = sum ?f ((UNIV-{b}) \\<union> {b})\" using univ_rw by auto\n    also have \"... = sum ?f (UNIV-{b}) + sum ?f {b}\" by (rule sum.union_disjoint, auto)\n    also have \"... = sum ?f {b}\" unfolding mat_def by auto\n    finally show ?thesis unfolding mat_def by simp\n  qed\nnext\n  fix i j\n  assume j_not_b: \"j \\<noteq> b\" and j_not_a: \"j \\<noteq> a\"\n  show \"(\\<Sum>k\\<in>UNIV. A $ i $ k * mat (1::'a) $ k $ j) = A $ i $ j\"\n  proof -\n    let ?f=\"(\\<lambda>k. A $ i $ k * mat (1::'a) $ k $ j)\"\n    have univ_rw:\"UNIV = (UNIV-{j}) \\<union> {j}\" by auto\n    have \"sum ?f UNIV = sum ?f ((UNIV-{j}) \\<union> {j})\" using univ_rw by auto\n    also have \"... = sum ?f (UNIV-{j}) + sum ?f {j}\" by (rule sum.union_disjoint, auto)\n    also have \"... = sum ?f {j}\" unfolding mat_def using j_not_b j_not_a by auto\n    finally show ?thesis unfolding mat_def by simp\n  qed\nqed\n\nlemma invertible_interchange_columns: \"invertible (interchange_columns (mat 1) a b)\"\nproof (unfold invertible_def, rule exI[of _ \"interchange_columns (mat 1) a b\"], simp, unfold matrix_matrix_mult_def, vector, clarify, \n    unfold interchange_columns_def, vector, unfold mat_1_fun, auto+) \n  show \"(\\<Sum>k\\<in>UNIV. (if k = b then 1::'a else if k = b then 1::'a else if b = k then 1::'a else (0::'a)) * (if k = b then 1::'a else (0::'a))) = (1::'a)\"\n  proof -\n    let ?f=\"(\\<lambda>k. (if k = b then 1::'a else if k = b then 1::'a else if b = k then 1::'a else (0::'a)) * (if k = b then 1::'a else (0::'a)))\"\n    have univ_rw:\"UNIV = (UNIV-{b}) \\<union> {b}\" by auto\n    have \"sum ?f UNIV = sum ?f ((UNIV-{b}) \\<union> {b})\" using univ_rw by auto\n    also have \"... = sum ?f (UNIV-{b}) + sum ?f {b}\" by (rule sum.union_disjoint, auto)\n    also have \"... = sum ?f {b}\" by auto\n    finally show ?thesis by simp\n  qed\n  assume a_not_b: \"a \\<noteq> b\"\n  show \"(\\<Sum>k\\<in>UNIV. (if k = a then 0::'a else if k = b then 1::'a else if a = k then 1::'a else (0::'a)) * (if k = b then 1::'a else (0::'a))) = (1::'a)\"\n  proof -\n    let ?f=\"\\<lambda>k. (if k = a then 0::'a else if k = b then 1::'a else if a = k then 1::'a else (0::'a)) * (if k = b then 1::'a else (0::'a))\"\n    have univ_rw:\"UNIV = (UNIV-{b}) \\<union> {b}\" by auto\n    have \"sum ?f UNIV = sum ?f ((UNIV-{b}) \\<union> {b})\" using univ_rw by auto\n    also have \"... = sum ?f (UNIV-{b}) + sum ?f {b}\" by (rule sum.union_disjoint, auto)\n    also have \"... = sum ?f {b}\" using a_not_b by simp\n    finally show ?thesis using a_not_b by auto\n  qed\nnext\n  fix t\n  assume b_not_t: \"b \\<noteq> t\"\n  show \" (\\<Sum>k\\<in>UNIV. (if k = b then 1::'a else if k = b then 1::'a else if b = k then 1::'a else (0::'a)) * (if k = t then 1::'a else (0::'a))) = (0::'a)\"\n    apply (rule sum.neutral) using b_not_t by auto\n  assume b_not_a: \"b \\<noteq> a\"\n  show \"(\\<Sum>k\\<in>UNIV. (if k = a then 1::'a else if k = b then 0::'a else if b = k then 1::'a else (0::'a)) *\n    (if t = a then if k = b then 1::'a else (0::'a) else if t = b then if k = a then 1::'a else (0::'a) else if k = t then 1::'a else (0::'a))) =\n    (0::'a)\" apply (rule sum.neutral) using b_not_t by auto\nnext\n  fix t\n  assume a_not_b: \"a \\<noteq> b\" and a_not_t: \"a \\<noteq> t\"\n  show \"(\\<Sum>k\\<in>UNIV. (if k = a then 0::'a else if k = b then 1::'a else if a = k then 1::'a else (0::'a)) *\n    (if t = b then if k = a then 1::'a else (0::'a) else if k = t then 1::'a else (0::'a))) = (0::'a)\"\n    by (rule sum.neutral, auto simp add: a_not_b a_not_t)\nnext\n  assume b_not_a: \"b \\<noteq> a\"\n  show \"(\\<Sum>k\\<in>UNIV. (if k = a then 1::'a else if k = b then 0::'a else if b = k then 1::'a else (0::'a)) * (if k = a then 1::'a else (0::'a))) = (1::'a)\"\n  proof -\n    let ?f=\"\\<lambda>k.  (if k = a then 1::'a else if k = b then 0::'a else if b = k then 1::'a else (0::'a)) * (if k = a then 1::'a else (0::'a))\"\n    have univ_rw:\"UNIV = (UNIV-{a}) \\<union> {a}\" by auto\n    have \"sum ?f UNIV = sum ?f ((UNIV-{a}) \\<union> {a})\" using univ_rw by auto\n    also have \"... = sum ?f (UNIV-{a}) + sum ?f {a}\" by (rule sum.union_disjoint, auto)\n    also have \"... = sum ?f {a}\" using b_not_a by simp\n    finally show ?thesis using b_not_a by auto\n  qed\nnext\n  fix t\n  assume t_not_a: \"t \\<noteq> a\" and t_not_b: \"t \\<noteq> b\"\n  show \"(\\<Sum>k\\<in>UNIV. (if k = a then 0::'a else if k = b then 0::'a else if t = k then 1::'a else (0::'a)) * (if k = t then 1::'a else (0::'a))) = (1::'a)\"\n  proof -\n    let ?f=\"\\<lambda>k. (if k = a then 0::'a else if k = b then 0::'a else if t = k then 1::'a else (0::'a)) * (if k = t then 1::'a else (0::'a))\"\n    have univ_rw:\"UNIV = (UNIV-{t}) \\<union> {t}\" by auto\n    have \"sum ?f UNIV = sum ?f ((UNIV-{t}) \\<union> {t})\" using univ_rw by auto\n    also have \"... = sum ?f (UNIV-{t}) + sum ?f {t}\" by (rule sum.union_disjoint, auto)\n    also have \"... = sum ?f {t}\" using t_not_a t_not_b by simp\n    also have \"... = 1\"  using t_not_a t_not_b by simp\n    finally show ?thesis .\n  qed\nnext\n  fix s t\n  assume s_not_a: \"s \\<noteq> a\" and s_not_b: \"s \\<noteq> b\" and s_not_t: \"s \\<noteq> t\"\n  show \"(\\<Sum>k\\<in>UNIV. (if k = a then 0::'a else if k = b then 0::'a else if s = k then 1::'a else (0::'a)) *\n    (if t = a then if k = b then 1::'a else (0::'a) else if t = b then if k = a then 1::'a else (0::'a) else if k = t then 1::'a else (0::'a))) =\n    (0::'a)\"\n    by (rule sum.neutral, auto simp add: s_not_a s_not_b s_not_t)\nqed\n\nsubsubsection\\<open>Properties about multiplying a column by a constant\\<close>\ntext\\<open>Properties about @{term \"mult_column\"}\\<close>\n\nlemma mult_column_mat_1: \"A ** mult_column (mat 1) a q = mult_column A a q\"\nproof (unfold matrix_matrix_mult_def, unfold mult_column_def, vector, auto)\n  fix i\n  show \"(\\<Sum>k\\<in>UNIV. A $ i $ k * (mat (1::'a) $ k $ a * q)) = A $ i $ a * q\"\n  proof -\n    let ?f=\"\\<lambda>k.  A $ i $ k * (mat (1::'a) $ k $ a * q)\"\n    have univ_rw:\"UNIV = (UNIV-{a}) \\<union> {a}\" by auto\n    have \"sum ?f UNIV = sum ?f ((UNIV-{a}) \\<union> {a})\" using univ_rw by auto\n    also have \"... = sum ?f (UNIV-{a}) + sum ?f {a}\" by (rule sum.union_disjoint, auto)\n    also have \"... = sum ?f {a}\" unfolding mat_def by auto\n    also have \"... = A $ i $ a * q\" unfolding mat_def by auto\n    finally show ?thesis .\n  qed\n  fix j\n  show \"(\\<Sum>k\\<in>UNIV. A $ i $ k * mat (1::'a) $ k $ j) = A $ i $ j\"\n  proof -\n    let ?f=\"\\<lambda>k. A $ i $ k * mat (1::'a) $ k $ j\"\n    have univ_rw:\"UNIV = (UNIV-{j}) \\<union> {j}\" by auto\n    have \"sum ?f UNIV = sum ?f ((UNIV-{j}) \\<union> {j})\" using univ_rw by auto\n    also have \"... = sum ?f (UNIV-{j}) + sum ?f {j}\" by (rule sum.union_disjoint, auto)\n    also have \"... = sum ?f {j}\" unfolding mat_def by auto\n    also have \"... = A $ i $ j\" unfolding mat_def by auto\n    finally show ?thesis .\n  qed\nqed\n\nlemma invertible_mult_column:\n  assumes qk: \"q * k = 1\" and kq: \"k * q = 1\"\n  shows \"invertible (mult_column (mat 1) a q)\"\nproof (unfold invertible_def, rule exI[of _ \"mult_column (mat 1) a k\"], rule conjI)  \n  show \"mult_column (mat 1) a q ** mult_column (mat 1) a k = mat 1\" \n  proof (unfold matrix_matrix_mult_def, vector, clarify, unfold mult_column_def, vector, unfold mat_1_fun, auto)\n    fix t    \n    show \"(\\<Sum>ka\\<in>UNIV. (if ka = a then (if t = ka then 1::'a else (0::'a)) * q else if t = ka then 1::'a else (0::'a)) *\n      (if t = a then (if ka = t then 1::'a else (0::'a)) * k else if ka = t then 1::'a else (0::'a))) =\n      (1::'a)\"\n    proof -\n      let ?f=\" \\<lambda>ka. (if ka = a then (if t = ka then 1::'a else (0::'a)) * q else if t = ka then 1::'a else (0::'a)) *\n        (if t = a then (if ka = t then 1::'a else (0::'a)) * k else if ka = t then 1::'a else (0::'a))\"\n      have univ_rw:\"UNIV = (UNIV-{t}) \\<union> {t}\" by auto\n      have \"sum ?f UNIV = sum ?f ((UNIV-{t}) \\<union> {t})\" using univ_rw by auto\n      also have \"... = sum ?f (UNIV-{t}) + sum ?f {t}\" by (rule sum.union_disjoint, auto)\n      also have \"... = sum ?f {t}\" by auto\n      also have \"... = 1\" using qk by auto\n      finally show ?thesis .     \n    qed   \n    fix s\n    assume s_not_t: \"s \\<noteq> t\"\n    show \"(\\<Sum>ka\\<in>UNIV. (if ka = a then (if s = ka then 1::'a else (0::'a)) * q else if s = ka then 1::'a else (0::'a)) *\n      (if t = a then (if ka = t then 1::'a else (0::'a)) * k else if ka = t then 1::'a else (0::'a))) =\n      (0::'a)\"\n      apply (rule sum.neutral) using s_not_t by auto\n  qed       \n  show \"mult_column (mat (1::'a)) a k ** mult_column (mat (1::'a)) a q = mat (1::'a)\"\n  proof (unfold matrix_matrix_mult_def, vector, clarify, unfold mult_column_def, vector, unfold mat_1_fun, auto)\n    fix t\n    show \"(\\<Sum>ka\\<in>UNIV. (if ka = a then (if t = ka then 1::'a else (0::'a)) * k else if t = ka then 1::'a else (0::'a)) *\n      (if t = a then (if ka = t then 1::'a else (0::'a)) * q else if ka = t then 1::'a else (0::'a))) = (1::'a)\"\n    proof -\n      let ?f=\" \\<lambda>ka. (if ka = a then (if t = ka then 1::'a else (0::'a)) * k else if t = ka then 1::'a else (0::'a)) *\n        (if t = a then (if ka = t then 1::'a else (0::'a)) * q else if ka = t then 1::'a else (0::'a))\"\n      have univ_rw:\"UNIV = (UNIV-{t}) \\<union> {t}\" by auto\n      have \"sum ?f UNIV = sum ?f ((UNIV-{t}) \\<union> {t})\" using univ_rw by auto\n      also have \"... = sum ?f (UNIV-{t}) + sum ?f {t}\" by (rule sum.union_disjoint, auto)\n      also have \"... = sum ?f {t}\" by auto\n      also have \"... = 1\" using kq by auto\n      finally show ?thesis .\n    qed   \n    fix s assume s_not_t: \"s \\<noteq> t\"\n    show \"(\\<Sum>ka\\<in>UNIV. (if ka = a then (if s = ka then 1::'a else (0::'a)) * k else if s = ka then 1::'a else (0::'a)) *\n      (if t = a then (if ka = t then 1::'a else (0::'a)) * q else if ka = t then 1::'a else (0::'a))) = 0\"\n      apply (rule sum.neutral) using s_not_t by auto\n  qed\nqed\n\ncorollary invertible_mult_column':  \n  assumes q_not_zero: \"q \\<noteq> 0\"\n  shows \"invertible (mult_column (mat (1::'a::{field})) a q)\"\n  by (simp add: invertible_mult_column[of q \"inverse q\"] q_not_zero)\n\nsubsubsection\\<open>Properties about adding a column multiplied by a constant to another column\\<close>\ntext\\<open>Properties about @{term \"column_add\"}\\<close>\n\nlemma column_add_mat_1: \"A ** column_add (mat 1) a b q = column_add A a b q\"\nproof (unfold matrix_matrix_mult_def, \n    unfold column_add_def, vector, auto)\n  fix i\n  let ?f=\"\\<lambda>k. A $ i $ k * (mat (1::'a) $ k $ a + mat (1::'a) $ k $ b * q)\"\n  show \"sum ?f UNIV =  A $ i $ a + A $ i $ b * q\"\n  proof (cases \"a=b\")\n    case True\n    have univ_rw:\"UNIV = (UNIV-{a}) \\<union> {a}\" by auto\n    have \"sum ?f UNIV = sum ?f ((UNIV-{a}) \\<union> {a})\" using univ_rw by auto\n    also have \"... = sum ?f (UNIV-{a}) + sum ?f {a}\" by (rule sum.union_disjoint, auto)\n    also have \"... = sum ?f {a}\" unfolding mat_def True by auto\n    also have \"... = ?f a\" by auto\n    also have \"... = A $ i $ a + A $ i $ b * q\" using True unfolding mat_1_fun using distrib_left[of \"A $ i $ b\" 1 q] by auto\n    finally show ?thesis .\n  next\n    case False\n    have univ_rw: \"UNIV = {a} \\<union> ({b} \\<union> (UNIV - {a} - {b}))\" by auto\n    have sum_rw: \"sum ?f ({b} \\<union> (UNIV - {a} - {b})) = sum ?f {b} + sum ?f (UNIV - {a} - {b})\" by (rule sum.union_disjoint, auto simp add: False)\n    have \"sum ?f UNIV = sum ?f ({a} \\<union> ({b} \\<union> (UNIV - {a} - {b})))\" using univ_rw by simp\n    also have \"... = sum ?f {a} + sum ?f ({b} \\<union> (UNIV - {a} - {b}))\" by (rule sum.union_disjoint, auto simp add: False)\n    also have \"... = sum ?f {a} + sum ?f {b} + sum ?f (UNIV - {a} - {b})\" \n      unfolding sum_rw add.assoc[symmetric] ..\n    also have \"... = sum ?f {a} + sum ?f {b}\" unfolding mat_def by auto    \n    also have \"... =  A $ i $ a + A $ i $ b * q\" using False unfolding mat_def by simp\n    finally show ?thesis .\n  qed    \n  fix j\n  assume j_noteq_a: \"j\\<noteq>a\"\n  show \"(\\<Sum>k\\<in>UNIV. A $ i $ k * mat (1::'a) $ k $ j) = A $ i $ j\"\n  proof -\n    let ?f=\"\\<lambda>k. A $ i $ k * mat (1::'a) $ k $ j\"\n    have univ_rw:\"UNIV = (UNIV-{j}) \\<union> {j}\" by auto\n    have \"sum ?f UNIV = sum ?f ((UNIV-{j}) \\<union> {j})\" using univ_rw by auto\n    also have \"... = sum ?f (UNIV-{j}) + sum ?f {j}\" by (rule sum.union_disjoint, auto)\n    also have \"... = sum ?f {j}\" unfolding mat_def by auto\n    also have \"... =  A $ i $ j\" unfolding mat_def by simp\n    finally show ?thesis .\n  qed\nqed\n\n\nlemma invertible_column_add:\n  assumes a_noteq_b: \"a\\<noteq>b\"\n  shows \"invertible (column_add (mat (1::'a::{ring_1})) a b q)\"\nproof (unfold invertible_def, rule exI[of _ \"(column_add (mat 1) a b (-q))\"], rule conjI)\n  show \" column_add (mat (1::'a)) a b q ** column_add (mat (1::'a)) a b (- q) = mat (1::'a)\"  using a_noteq_b\n  proof (unfold matrix_matrix_mult_def, vector, clarify, unfold column_add_def, vector, unfold mat_1_fun, auto)\n    show \" (\\<Sum>k\\<in>UNIV. (if k = a then (0::'a) + (1::'a) * q else if b = k then 1::'a else (0::'a)) * (if k = b then 1::'a else (0::'a))) = (1::'a)\"\n    proof -\n      let ?f=\"\\<lambda>k.  (if k = a then (0::'a) + (1::'a) * q else if b = k then 1::'a else (0::'a)) * (if k = b then 1::'a else (0::'a))\"\n      have univ_rw:\"UNIV = (UNIV-{b}) \\<union> {b}\" by auto\n      have \"sum ?f UNIV = sum ?f ((UNIV-{b}) \\<union> {b})\" using univ_rw by auto\n      also have \"... = sum ?f (UNIV-{b}) + sum ?f {b}\" by (rule sum.union_disjoint, auto)\n      also have \"... = sum ?f {b}\" by auto \n      also have \"... =  1\" using a_noteq_b by simp\n      finally show ?thesis .\n    qed\n    show \"(\\<Sum>k\\<in>UNIV. (if k = a then 1 + 0 * q else if a = k then 1 else 0) * ((if k = a then 1 else 0) - (if k = b then 1 else 0) * q)) = 1\"\n    proof -\n      let ?f=\"\\<lambda>k. (if k = a then (1::'a) + (0::'a) * q else if a = k then 1::'a else (0::'a)) * ((if k = a then 1::'a else (0::'a)) + - ((if k = b then 1::'a else (0::'a)) * q))\"\n      have univ_rw:\"UNIV = (UNIV-{a}) \\<union> {a}\" by auto\n      have \"sum ?f UNIV = sum ?f ((UNIV-{a}) \\<union> {a})\" using univ_rw by auto\n      also have \"... = sum ?f (UNIV-{a}) + sum ?f {a}\" by (rule sum.union_disjoint, auto)\n      also have \"... = sum ?f {a}\" by auto \n      also have \"... =  1\" using a_noteq_b by simp\n      finally show ?thesis by simp\n    qed  \n    fix i j\n    assume i_not_b: \"i \\<noteq> b\" and i_not_a: \"i \\<noteq> a\" and i_not_j: \"i \\<noteq> j\"\n    show \"(\\<Sum>k\\<in>UNIV. (if k = a then (0::'a) + (0::'a) * q else if i = k then 1::'a else (0::'a)) *\n      (if j = a then (if k = a then 1::'a else (0::'a)) + (if k = b then 1::'a else (0::'a)) * - q else if k = j then 1::'a else (0::'a))) = (0::'a)\"\n      by (rule sum.neutral, auto simp add: i_not_b i_not_a i_not_j)\n  next\n    fix j\n    assume a_not_j: \"a\\<noteq>j\"\n    show \" (\\<Sum>k\\<in>UNIV. (if k = a then (1::'a) + (0::'a) * q else if a = k then 1::'a else (0::'a)) * (if k = j then 1::'a else (0::'a))) = (0::'a)\"\n      apply (rule sum.neutral) using a_not_j a_noteq_b by auto\n  next\n    fix j\n    assume j_not_b: \"j \\<noteq> b\" and j_not_a: \"j \\<noteq> a\"\n    show \" (\\<Sum>k\\<in>UNIV. (if k = a then (0::'a) + (0::'a) * q else if j = k then 1::'a else (0::'a)) * (if k = j then 1::'a else (0::'a))) = (1::'a)\"\n    proof -\n      let ?f=\"\\<lambda>k. (if k = a then (0::'a) + (0::'a) * q else if j = k then 1::'a else (0::'a)) * (if k = j then 1::'a else (0::'a))\"\n      have univ_rw:\"UNIV = (UNIV-{j}) \\<union> {j}\" by auto\n      have \"sum ?f UNIV = sum ?f ((UNIV-{j}) \\<union> {j})\" using univ_rw by auto\n      also have \"... = sum ?f (UNIV-{j}) + sum ?f {j}\" by (rule sum.union_disjoint, auto)\n      also have \"... = sum ?f {j}\" using j_not_b j_not_a by auto \n      also have \"... =  1\" using j_not_b j_not_a by auto \n      finally show ?thesis .\n    qed\n  next\n    fix j\n    assume b_not_j: \"b \\<noteq> j\"\n    show \"(\\<Sum>k\\<in>UNIV. (if k = a then 0 + 1 * q else if b = k then 1 else 0) *\n      (if j = a then (if k = a then 1 else 0) + (if k = b then 1 else 0) * - q else if k = j then 1 else 0)) = 0\"\n    proof (cases \"j=a\")\n      case False\n      show ?thesis by (rule sum.neutral, auto simp add: False b_not_j)\n    next\n      case True \\<comment> \\<open>This case is different from the other cases\\<close>\n      let ?f=\"\\<lambda>k. (if k = a then 0 + 1 * q else if b = k then 1 else 0) *\n        (if j = a then (if k = a then 1 else 0) + (if k = b then 1 else 0) * - q else if k = j then 1 else 0)\"\n      have univ_eq: \"UNIV = ((UNIV - {a}- {b}) \\<union> ({b} \\<union> {a}))\" by auto\n      have sum_a: \"sum ?f {a} = q\"  unfolding True using b_not_j using a_noteq_b by auto\n      have sum_b: \"sum ?f {b} = -q\" unfolding True using b_not_j using a_noteq_b by auto\n      have sum_rest: \"sum ?f (UNIV - {a} - {b}) = 0\"  by (rule sum.neutral, auto simp add: True b_not_j a_noteq_b)\n      have \"sum ?f UNIV = sum ?f ((UNIV - {a}- {b}) \\<union> ({b} \\<union> {a}))\"  using univ_eq by simp\n      also have \"... = sum ?f (UNIV - {a} - {b}) + sum ?f ({b} \\<union> {a})\" by (rule sum.union_disjoint, auto)\n      also have \"... = sum ?f (UNIV - {a} - {b}) + sum ?f {b} + sum ?f {a}\" by (auto simp add: sum.union_disjoint a_noteq_b)     \n      also have \"... = 0\" unfolding sum_a sum_b sum_rest by simp\n      finally show ?thesis .\n    qed                        \n  qed\nnext\n  show \" column_add (mat (1::'a)) a b (- q) ** column_add (mat (1::'a)) a b q = mat (1::'a)\" using a_noteq_b\n  proof (unfold matrix_matrix_mult_def, vector, clarify, unfold column_add_def, vector, unfold mat_1_fun, auto)\n    show \"(\\<Sum>k\\<in>UNIV. (if k = a then (0::'a) + (1::'a) * - q else if b = k then 1::'a else (0::'a)) * (if k = b then 1::'a else (0::'a))) = (1::'a)\"\n    proof -\n      let ?f=\"\\<lambda>k. (if k = a then (0::'a) + (1::'a) * - q else if b = k then 1::'a else (0::'a)) * (if k = b then 1::'a else (0::'a))\"\n      have univ_rw:\"UNIV = (UNIV-{b}) \\<union> {b}\" by auto\n      have \"sum ?f UNIV = sum ?f ((UNIV-{b}) \\<union> {b})\" using univ_rw by auto\n      also have \"... = sum ?f (UNIV-{b}) + sum ?f {b}\" by (rule sum.union_disjoint, auto)\n      also have \"... = sum ?f {b}\" by auto \n      also have \"... =  1\" using a_noteq_b by auto\n      finally show ?thesis .\n    qed\n  next\n    show \"(\\<Sum>k\\<in>UNIV. (if k = a then (1::'a) + (0::'a) * - q else if a = k then 1::'a else (0::'a)) * ((if k = a then 1::'a else (0::'a)) + (if k = b then 1::'a else (0::'a)) * q)) =\n      (1::'a)\"\n    proof -\n      let ?f=\"\\<lambda>k. (if k = a then (1::'a) + (0::'a) * - q else if a = k then 1::'a else (0::'a)) * ((if k = a then 1::'a else (0::'a)) + (if k = b then 1::'a else (0::'a)) * q) \"\n      have univ_rw:\"UNIV = (UNIV-{a}) \\<union> {a}\" by auto\n      have \"sum ?f UNIV = sum ?f ((UNIV-{a}) \\<union> {a})\" using univ_rw by auto\n      also have \"... = sum ?f (UNIV-{a}) + sum ?f {a}\" by (rule sum.union_disjoint, auto)\n      also have \"... = sum ?f {a}\" by auto \n      also have \"... =  1\" using a_noteq_b by auto\n      finally show ?thesis .\n    qed\n  next\n    fix j\n    assume a_not_j: \"a \\<noteq> j\" show \"(\\<Sum>k\\<in>UNIV. (if k = a then (1::'a) + (0::'a) * - q else if a = k then 1::'a else (0::'a)) * (if k = j then 1::'a else (0::'a))) = (0::'a)\"\n      apply (rule sum.neutral) using a_not_j by auto\n  next\n    fix j\n    assume j_not_b: \"j \\<noteq> b\" and j_not_a: \"j \\<noteq> a\" \n    show \"(\\<Sum>k\\<in>UNIV. (if k = a then (0::'a) + (0::'a) * - q else if j = k then 1::'a else (0::'a)) * (if k = j then 1::'a else (0::'a))) = (1::'a)\"\n    proof -\n      let ?f=\"\\<lambda>k.(if k = a then (0::'a) + (0::'a) * - q else if j = k then 1::'a else (0::'a)) * (if k = j then 1::'a else (0::'a))\"\n      have univ_rw:\"UNIV = (UNIV-{j}) \\<union> {j}\" by auto\n      have \"sum ?f UNIV = sum ?f ((UNIV-{j}) \\<union> {j})\" using univ_rw by auto\n      also have \"... = sum ?f (UNIV-{j}) + sum ?f {j}\" by (rule sum.union_disjoint, auto)\n      also have \"... = sum ?f {j}\" by auto \n      also have \"... =  1\" using a_noteq_b j_not_b j_not_a by auto\n      finally show ?thesis .\n    qed\n  next\n    fix i j\n    assume i_not_b: \"i \\<noteq> b\" and i_not_a: \"i \\<noteq> a\" and i_not_j: \"i \\<noteq> j\"\n    show \"(\\<Sum>k\\<in>UNIV. (if k = a then (0::'a) + (0::'a) * - q else if i = k then 1::'a else (0::'a)) *\n      (if j = a then (if k = a then 1::'a else (0::'a)) + (if k = b then 1::'a else (0::'a)) * q else if k = j then 1::'a else (0::'a))) = (0::'a)\"\n      by (rule sum.neutral, auto simp add: i_not_b i_not_a i_not_j)\n  next\n    fix j\n    assume b_not_j: \"b \\<noteq> j\"\n    show \"(\\<Sum>k\\<in>UNIV. (if k = a then (0::'a) + (1::'a) * - q else if b = k then 1::'a else (0::'a)) *\n      (if j = a then (if k = a then 1::'a else (0::'a)) + (if k = b then 1::'a else (0::'a)) * q else if k = j then 1::'a else (0::'a))) = 0\"\n    proof (cases \"j=a\")\n      case False\n      show ?thesis by (rule sum.neutral, auto simp add: False b_not_j)\n    next\n      case True \\<comment> \\<open>This case is different from the other cases\\<close>\n      let ?f=\"\\<lambda>k. (if k = a then (0::'a) + (1::'a) * - q else if b = k then 1::'a else (0::'a)) *\n        (if j = a then (if k = a then 1::'a else (0::'a)) + (if k = b then 1::'a else (0::'a)) * q else if k = j then 1::'a else (0::'a))\"\n      have univ_eq: \"UNIV = ((UNIV - {a}- {b}) \\<union> ({b} \\<union> {a}))\" by auto\n      have sum_a: \"sum ?f {a} = -q\"  unfolding True using b_not_j using a_noteq_b by auto\n      have sum_b: \"sum ?f {b} = q\" unfolding True using b_not_j using a_noteq_b by auto\n      have sum_rest: \"sum ?f (UNIV - {a} - {b}) = 0\"  by (rule sum.neutral, auto simp add: True b_not_j a_noteq_b)\n      have \"sum ?f UNIV = sum ?f ((UNIV - {a}- {b}) \\<union> ({b} \\<union> {a}))\"  using univ_eq by simp\n      also have \"... = sum ?f (UNIV - {a} - {b}) + sum ?f ({b} \\<union> {a})\" by (rule sum.union_disjoint, auto)\n      also have \"... = sum ?f (UNIV - {a} - {b}) + sum ?f {b} + sum ?f {a}\" by (auto simp add: sum.union_disjoint a_noteq_b)     \n      also have \"... = 0\" unfolding sum_a sum_b sum_rest by simp\n      finally show ?thesis .\n    qed                   \n  qed\nqed\n\nsubsection\\<open>Relationships amongst the definitions\\<close>\n\ntext\\<open>Relationships between @{term \"interchange_rows\"} and @{term \"interchange_columns\"}\\<close>\n\nlemma interchange_rows_transpose:\n  shows \"interchange_rows (transpose A) a b = transpose (interchange_columns A a b)\"\n  unfolding interchange_rows_def interchange_columns_def transpose_def by vector\n\nlemma interchange_rows_transpose':\n  shows \"interchange_rows A a b = transpose (interchange_columns (transpose A) a b)\"\n  unfolding interchange_rows_def interchange_columns_def transpose_def by vector\n\nlemma interchange_columns_transpose:\n  shows \"interchange_columns (transpose A) a b = transpose (interchange_rows A a b)\"\n  unfolding interchange_rows_def interchange_columns_def transpose_def by vector\n\nlemma interchange_columns_transpose':\n  shows \"interchange_columns A a b = transpose (interchange_rows (transpose A) a b)\"\n  unfolding interchange_rows_def interchange_columns_def transpose_def by vector\n\nsubsection\\<open>Code Equations\\<close>\ntext\\<open>Code equations for @{thm interchange_rows_def}, @{thm interchange_columns_def}, @{thm row_add_def}, @{thm column_add_def}, \n@{thm mult_row_def} and @{thm mult_column_def}:\\<close>\n\ndefinition interchange_rows_row \n  where \"interchange_rows_row A a b i = vec_lambda (%j. if i = a then A $ b $ j else if i = b then A $ a $ j else A $ i $ j)\"\n\nlemma interchange_rows_code [code abstract]:\n  \"vec_nth (interchange_rows_row A a b i) = (%j. if i = a then A $ b $ j else if i = b then A $ a $ j else A $ i $ j)\"\n  unfolding interchange_rows_row_def by auto \n\nlemma interchange_rows_code_nth [code abstract]: \"vec_nth (interchange_rows A a b) = interchange_rows_row A a b\"\n  unfolding interchange_rows_def unfolding interchange_rows_row_def[abs_def]\n  by auto\n\ndefinition interchange_columns_row \n  where \"interchange_columns_row A n m i = vec_lambda (%j.  if j = n then A $ i $ m else if j = m then A $ i $ n else A $ i $ j)\"\n\nlemma interchange_columns_code [code abstract]:\n  \"vec_nth (interchange_columns_row A n m i) = (%j.  if j = n then A $ i $ m else if j = m then A $ i $ n else A $ i $ j)\"\n  unfolding interchange_columns_row_def by auto \n\nlemma interchange_columns_code_nth [code abstract]: \"vec_nth (interchange_columns A a b) = interchange_columns_row A a b\"\n  unfolding interchange_columns_def unfolding interchange_columns_row_def[abs_def]\n  by auto\n\ndefinition row_add_row \n  where \"row_add_row A a b q i = vec_lambda (%j. if i = a then A $ a $ j + q * A $ b $ j else A $ i $ j)\"\n\nlemma row_add_code [code abstract]:\n  \"vec_nth (row_add_row A a b q i) =  (%j. if i = a then A $ a $ j + q * A $ b $ j else A $ i $ j)\"\n  unfolding row_add_row_def by auto \n\nlemma row_add_code_nth [code abstract]: \"vec_nth (row_add A a b q) = row_add_row A a b q\"\n  unfolding row_add_def unfolding row_add_row_def[abs_def]\n  by auto\n\ndefinition column_add_row \n  where \"column_add_row  A n m q i = vec_lambda (%j. if j = n then A $ i $ n + A $ i $ m * q else A $ i $ j)\"\n\nlemma column_add_code [code abstract]:\n  \"vec_nth (column_add_row A n m q i) =  (%j. if j = n then A $ i $ n + A $ i $ m * q else A $ i $ j)\"\n  unfolding column_add_row_def by auto\n\nlemma column_add_code_nth [code abstract]: \"vec_nth (column_add A a b q) = column_add_row A a b q\"\n  unfolding column_add_def unfolding column_add_row_def[abs_def]\n  by auto\n\ndefinition mult_row_row \n  where \"mult_row_row A a q i = vec_lambda (%j. if i = a then q * A $ a $ j else A $ i $ j)\"\n\nlemma mult_row_code [code abstract]:\n  \"vec_nth (mult_row_row A a q i) = (%j. if i = a then q * A $ a $ j else A $ i $ j)\"\n  unfolding mult_row_row_def by auto\n\nlemma mult_row_code_nth [code abstract]: \"vec_nth (mult_row A a q) = mult_row_row A a q\"\n  unfolding mult_row_def unfolding mult_row_row_def[abs_def]\n  by auto\n\ndefinition mult_column_row \n  where \"mult_column_row A n q i = vec_lambda (%j. if j = n then A $ i $ j * q else A $ i $ j)\"\n\nlemma mult_column_code [code abstract]:\n  \"vec_nth (mult_column_row A n q i) = (%j. if j = n then A $ i $ j * q else A $ i $ j)\"\n  unfolding mult_column_row_def by auto\n\nlemma mult_column_code_nth [code abstract]: \"vec_nth (mult_column A a q) = mult_column_row A a q\"\n  unfolding mult_column_def unfolding mult_column_row_def[abs_def]\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/Gauss_Jordan/Elementary_Operations.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289387914176258, "lm_q2_score": 0.8519528076067262, "lm_q1q2_score": 0.7062167306823727}}
{"text": "(*  Title:      HOL/Algebra/Divisibility.thy\n    Author:     Clemens Ballarin\n    Author:     Stephan Hohe\n*)\n\nsection \\<open>Divisibility in monoids and rings\\<close>\n\ntheory Divisibility\n  imports \"~~/src/HOL/Library/Permutation\" Coset Group\nbegin\n\nsection \\<open>Factorial Monoids\\<close>\n\nsubsection \\<open>Monoids with Cancellation Law\\<close>\n\nlocale monoid_cancel = monoid +\n  assumes l_cancel: \"\\<lbrakk>c \\<otimes> a = c \\<otimes> b; a \\<in> carrier G; b \\<in> carrier G; c \\<in> carrier G\\<rbrakk> \\<Longrightarrow> a = b\"\n    and r_cancel: \"\\<lbrakk>a \\<otimes> c = b \\<otimes> c; a \\<in> carrier G; b \\<in> carrier G; c \\<in> carrier G\\<rbrakk> \\<Longrightarrow> a = b\"\n\nlemma (in monoid) monoid_cancelI:\n  assumes l_cancel: \"\\<And>a b c. \\<lbrakk>c \\<otimes> a = c \\<otimes> b; a \\<in> carrier G; b \\<in> carrier G; c \\<in> carrier G\\<rbrakk> \\<Longrightarrow> a = b\"\n    and r_cancel: \"\\<And>a b c. \\<lbrakk>a \\<otimes> c = b \\<otimes> c; a \\<in> carrier G; b \\<in> carrier G; c \\<in> carrier G\\<rbrakk> \\<Longrightarrow> a = b\"\n  shows \"monoid_cancel G\"\n    by standard fact+\n\nlemma (in monoid_cancel) is_monoid_cancel: \"monoid_cancel G\" ..\n\nsublocale group \\<subseteq> monoid_cancel\n  by standard simp_all\n\n\nlocale comm_monoid_cancel = monoid_cancel + comm_monoid\n\nlemma comm_monoid_cancelI:\n  fixes G (structure)\n  assumes \"comm_monoid G\"\n  assumes cancel: \"\\<And>a b c. \\<lbrakk>a \\<otimes> c = b \\<otimes> c; a \\<in> carrier G; b \\<in> carrier G; c \\<in> carrier G\\<rbrakk> \\<Longrightarrow> a = b\"\n  shows \"comm_monoid_cancel G\"\nproof -\n  interpret comm_monoid G by fact\n  show \"comm_monoid_cancel G\"\n    by unfold_locales (metis assms(2) m_ac(2))+\nqed\n\nlemma (in comm_monoid_cancel) is_comm_monoid_cancel: \"comm_monoid_cancel G\"\n  by intro_locales\n\nsublocale comm_group \\<subseteq> comm_monoid_cancel ..\n\n\nsubsection \\<open>Products of Units in Monoids\\<close>\n\nlemma (in monoid) Units_m_closed[simp, intro]:\n  assumes h1unit: \"h1 \\<in> Units G\"\n    and h2unit: \"h2 \\<in> Units G\"\n  shows \"h1 \\<otimes> h2 \\<in> Units G\"\n  unfolding Units_def\n  using assms\n  by auto (metis Units_inv_closed Units_l_inv Units_m_closed Units_r_inv)\n\nlemma (in monoid) prod_unit_l:\n  assumes abunit[simp]: \"a \\<otimes> b \\<in> Units G\"\n    and aunit[simp]: \"a \\<in> Units G\"\n    and carr[simp]: \"a \\<in> carrier G\"  \"b \\<in> carrier G\"\n  shows \"b \\<in> Units G\"\nproof -\n  have c: \"inv (a \\<otimes> b) \\<otimes> a \\<in> carrier G\" by simp\n\n  have \"(inv (a \\<otimes> b) \\<otimes> a) \\<otimes> b = inv (a \\<otimes> b) \\<otimes> (a \\<otimes> b)\"\n    by (simp add: m_assoc)\n  also have \"\\<dots> = \\<one>\" by simp\n  finally have li: \"(inv (a \\<otimes> b) \\<otimes> a) \\<otimes> b = \\<one>\" .\n\n  have \"\\<one> = inv a \\<otimes> a\" by (simp add: Units_l_inv[symmetric])\n  also have \"\\<dots> = inv a \\<otimes> \\<one> \\<otimes> a\" by simp\n  also have \"\\<dots> = inv a \\<otimes> ((a \\<otimes> b) \\<otimes> inv (a \\<otimes> b)) \\<otimes> a\"\n    by (simp add: Units_r_inv[OF abunit, symmetric] del: Units_r_inv)\n  also have \"\\<dots> = ((inv a \\<otimes> a) \\<otimes> b) \\<otimes> inv (a \\<otimes> b) \\<otimes> a\"\n    by (simp add: m_assoc del: Units_l_inv)\n  also have \"\\<dots> = b \\<otimes> inv (a \\<otimes> b) \\<otimes> a\" by simp\n  also have \"\\<dots> = b \\<otimes> (inv (a \\<otimes> b) \\<otimes> a)\" by (simp add: m_assoc)\n  finally have ri: \"b \\<otimes> (inv (a \\<otimes> b) \\<otimes> a) = \\<one> \" by simp\n\n  from c li ri show \"b \\<in> Units G\" by (auto simp: Units_def)\nqed\n\nlemma (in monoid) prod_unit_r:\n  assumes abunit[simp]: \"a \\<otimes> b \\<in> Units G\"\n    and bunit[simp]: \"b \\<in> Units G\"\n    and carr[simp]: \"a \\<in> carrier G\"  \"b \\<in> carrier G\"\n  shows \"a \\<in> Units G\"\nproof -\n  have c: \"b \\<otimes> inv (a \\<otimes> b) \\<in> carrier G\" by simp\n\n  have \"a \\<otimes> (b \\<otimes> inv (a \\<otimes> b)) = (a \\<otimes> b) \\<otimes> inv (a \\<otimes> b)\"\n    by (simp add: m_assoc del: Units_r_inv)\n  also have \"\\<dots> = \\<one>\" by simp\n  finally have li: \"a \\<otimes> (b \\<otimes> inv (a \\<otimes> b)) = \\<one>\" .\n\n  have \"\\<one> = b \\<otimes> inv b\" by (simp add: Units_r_inv[symmetric])\n  also have \"\\<dots> = b \\<otimes> \\<one> \\<otimes> inv b\" by simp\n  also have \"\\<dots> = b \\<otimes> (inv (a \\<otimes> b) \\<otimes> (a \\<otimes> b)) \\<otimes> inv b\"\n    by (simp add: Units_l_inv[OF abunit, symmetric] del: Units_l_inv)\n  also have \"\\<dots> = (b \\<otimes> inv (a \\<otimes> b) \\<otimes> a) \\<otimes> (b \\<otimes> inv b)\"\n    by (simp add: m_assoc del: Units_l_inv)\n  also have \"\\<dots> = b \\<otimes> inv (a \\<otimes> b) \\<otimes> a\" by simp\n  finally have ri: \"(b \\<otimes> inv (a \\<otimes> b)) \\<otimes> a = \\<one> \" by simp\n\n  from c li ri show \"a \\<in> Units G\" by (auto simp: Units_def)\nqed\n\nlemma (in comm_monoid) unit_factor:\n  assumes abunit: \"a \\<otimes> b \\<in> Units G\"\n    and [simp]: \"a \\<in> carrier G\"  \"b \\<in> carrier G\"\n  shows \"a \\<in> Units G\"\n  using abunit[simplified Units_def]\nproof clarsimp\n  fix i\n  assume [simp]: \"i \\<in> carrier G\"\n\n  have carr': \"b \\<otimes> i \\<in> carrier G\" by simp\n\n  have \"(b \\<otimes> i) \\<otimes> a = (i \\<otimes> b) \\<otimes> a\" by (simp add: m_comm)\n  also have \"\\<dots> = i \\<otimes> (b \\<otimes> a)\" by (simp add: m_assoc)\n  also have \"\\<dots> = i \\<otimes> (a \\<otimes> b)\" by (simp add: m_comm)\n  also assume \"i \\<otimes> (a \\<otimes> b) = \\<one>\"\n  finally have li': \"(b \\<otimes> i) \\<otimes> a = \\<one>\" .\n\n  have \"a \\<otimes> (b \\<otimes> i) = a \\<otimes> b \\<otimes> i\" by (simp add: m_assoc)\n  also assume \"a \\<otimes> b \\<otimes> i = \\<one>\"\n  finally have ri': \"a \\<otimes> (b \\<otimes> i) = \\<one>\" .\n\n  from carr' li' ri'\n  show \"a \\<in> Units G\" by (simp add: Units_def, fast)\nqed\n\n\nsubsection \\<open>Divisibility and Association\\<close>\n\nsubsubsection \\<open>Function definitions\\<close>\n\ndefinition factor :: \"[_, 'a, 'a] \\<Rightarrow> bool\" (infix \"divides\\<index>\" 65)\n  where \"a divides\\<^bsub>G\\<^esub> b \\<longleftrightarrow> (\\<exists>c\\<in>carrier G. b = a \\<otimes>\\<^bsub>G\\<^esub> c)\"\n\ndefinition associated :: \"[_, 'a, 'a] \\<Rightarrow> bool\" (infix \"\\<sim>\\<index>\" 55)\n  where \"a \\<sim>\\<^bsub>G\\<^esub> b \\<longleftrightarrow> a divides\\<^bsub>G\\<^esub> b \\<and> b divides\\<^bsub>G\\<^esub> a\"\n\nabbreviation \"division_rel G \\<equiv> \\<lparr>carrier = carrier G, eq = op \\<sim>\\<^bsub>G\\<^esub>, le = op divides\\<^bsub>G\\<^esub>\\<rparr>\"\n\ndefinition properfactor :: \"[_, 'a, 'a] \\<Rightarrow> bool\"\n  where \"properfactor G a b \\<longleftrightarrow> a divides\\<^bsub>G\\<^esub> b \\<and> \\<not>(b divides\\<^bsub>G\\<^esub> a)\"\n\ndefinition irreducible :: \"[_, 'a] \\<Rightarrow> bool\"\n  where \"irreducible G a \\<longleftrightarrow> a \\<notin> Units G \\<and> (\\<forall>b\\<in>carrier G. properfactor G b a \\<longrightarrow> b \\<in> Units G)\"\n\ndefinition prime :: \"[_, 'a] \\<Rightarrow> bool\"\n  where \"prime G p \\<longleftrightarrow>\n    p \\<notin> Units G \\<and>\n    (\\<forall>a\\<in>carrier G. \\<forall>b\\<in>carrier G. p divides\\<^bsub>G\\<^esub> (a \\<otimes>\\<^bsub>G\\<^esub> b) \\<longrightarrow> p divides\\<^bsub>G\\<^esub> a \\<or> p divides\\<^bsub>G\\<^esub> b)\"\n\n\nsubsubsection \\<open>Divisibility\\<close>\n\nlemma dividesI:\n  fixes G (structure)\n  assumes carr: \"c \\<in> carrier G\"\n    and p: \"b = a \\<otimes> c\"\n  shows \"a divides b\"\n  unfolding factor_def using assms by fast\n\nlemma dividesI' [intro]:\n  fixes G (structure)\n  assumes p: \"b = a \\<otimes> c\"\n    and carr: \"c \\<in> carrier G\"\n  shows \"a divides b\"\n  using assms by (fast intro: dividesI)\n\nlemma dividesD:\n  fixes G (structure)\n  assumes \"a divides b\"\n  shows \"\\<exists>c\\<in>carrier G. b = a \\<otimes> c\"\n  using assms unfolding factor_def by fast\n\nlemma dividesE [elim]:\n  fixes G (structure)\n  assumes d: \"a divides b\"\n    and elim: \"\\<And>c. \\<lbrakk>b = a \\<otimes> c; c \\<in> carrier G\\<rbrakk> \\<Longrightarrow> P\"\n  shows \"P\"\nproof -\n  from dividesD[OF d] obtain c where \"c \\<in> carrier G\" and \"b = a \\<otimes> c\" by auto\n  then show P by (elim elim)\nqed\n\nlemma (in monoid) divides_refl[simp, intro!]:\n  assumes carr: \"a \\<in> carrier G\"\n  shows \"a divides a\"\n  by (intro dividesI[of \"\\<one>\"]) (simp_all add: carr)\n\nlemma (in monoid) divides_trans [trans]:\n  assumes dvds: \"a divides b\"  \"b divides c\"\n    and acarr: \"a \\<in> carrier G\"\n  shows \"a divides c\"\n  using dvds[THEN dividesD] by (blast intro: dividesI m_assoc acarr)\n\nlemma (in monoid) divides_mult_lI [intro]:\n  assumes ab: \"a divides b\"\n    and carr: \"a \\<in> carrier G\"  \"b \\<in> carrier G\"  \"c \\<in> carrier G\"\n  shows \"(c \\<otimes> a) divides (c \\<otimes> b)\"\n  using ab\n  apply (elim dividesE)\n  apply (simp add: m_assoc[symmetric] carr)\n  apply (fast intro: dividesI)\n  done\n\nlemma (in monoid_cancel) divides_mult_l [simp]:\n  assumes carr: \"a \\<in> carrier G\"  \"b \\<in> carrier G\"  \"c \\<in> carrier G\"\n  shows \"(c \\<otimes> a) divides (c \\<otimes> b) = a divides b\"\n  apply safe\n   apply (elim dividesE, intro dividesI, assumption)\n   apply (rule l_cancel[of c])\n      apply (simp add: m_assoc carr)+\n  apply (fast intro: carr)\n  done\n\nlemma (in comm_monoid) divides_mult_rI [intro]:\n  assumes ab: \"a divides b\"\n    and carr: \"a \\<in> carrier G\"  \"b \\<in> carrier G\"  \"c \\<in> carrier G\"\n  shows \"(a \\<otimes> c) divides (b \\<otimes> c)\"\n  using carr ab\n  apply (simp add: m_comm[of a c] m_comm[of b c])\n  apply (rule divides_mult_lI, assumption+)\n  done\n\nlemma (in comm_monoid_cancel) divides_mult_r [simp]:\n  assumes carr: \"a \\<in> carrier G\"  \"b \\<in> carrier G\"  \"c \\<in> carrier G\"\n  shows \"(a \\<otimes> c) divides (b \\<otimes> c) = a divides b\"\n  using carr by (simp add: m_comm[of a c] m_comm[of b c])\n\nlemma (in monoid) divides_prod_r:\n  assumes ab: \"a divides b\"\n    and carr: \"a \\<in> carrier G\"  \"b \\<in> carrier G\"  \"c \\<in> carrier G\"\n  shows \"a divides (b \\<otimes> c)\"\n  using ab carr by (fast intro: m_assoc)\n\nlemma (in comm_monoid) divides_prod_l:\n  assumes carr[intro]: \"a \\<in> carrier G\"  \"b \\<in> carrier G\"  \"c \\<in> carrier G\"\n    and ab: \"a divides b\"\n  shows \"a divides (c \\<otimes> b)\"\n  using ab carr\n  apply (simp add: m_comm[of c b])\n  apply (fast intro: divides_prod_r)\n  done\n\nlemma (in monoid) unit_divides:\n  assumes uunit: \"u \\<in> Units G\"\n    and acarr: \"a \\<in> carrier G\"\n  shows \"u divides a\"\nproof (intro dividesI[of \"(inv u) \\<otimes> a\"], fast intro: uunit acarr)\n  from uunit acarr have xcarr: \"inv u \\<otimes> a \\<in> carrier G\" by fast\n  from uunit acarr have \"u \\<otimes> (inv u \\<otimes> a) = (u \\<otimes> inv u) \\<otimes> a\"\n    by (fast intro: m_assoc[symmetric])\n  also have \"\\<dots> = \\<one> \\<otimes> a\" by (simp add: Units_r_inv[OF uunit])\n  also from acarr have \"\\<dots> = a\" by simp\n  finally show \"a = u \\<otimes> (inv u \\<otimes> a)\" ..\nqed\n\nlemma (in comm_monoid) divides_unit:\n  assumes udvd: \"a divides u\"\n    and  carr: \"a \\<in> carrier G\"  \"u \\<in> Units G\"\n  shows \"a \\<in> Units G\"\n  using udvd carr by (blast intro: unit_factor)\n\nlemma (in comm_monoid) Unit_eq_dividesone:\n  assumes ucarr: \"u \\<in> carrier G\"\n  shows \"u \\<in> Units G = u divides \\<one>\"\n  using ucarr by (fast dest: divides_unit intro: unit_divides)\n\n\nsubsubsection \\<open>Association\\<close>\n\nlemma associatedI:\n  fixes G (structure)\n  assumes \"a divides b\"  \"b divides a\"\n  shows \"a \\<sim> b\"\n  using assms by (simp add: associated_def)\n\nlemma (in monoid) associatedI2:\n  assumes uunit[simp]: \"u \\<in> Units G\"\n    and a: \"a = b \\<otimes> u\"\n    and bcarr[simp]: \"b \\<in> carrier G\"\n  shows \"a \\<sim> b\"\n  using uunit bcarr\n  unfolding a\n  apply (intro associatedI)\n   apply (rule dividesI[of \"inv u\"], simp)\n   apply (simp add: m_assoc Units_closed)\n  apply fast\n  done\n\nlemma (in monoid) associatedI2':\n  assumes \"a = b \\<otimes> u\"\n    and \"u \\<in> Units G\"\n    and \"b \\<in> carrier G\"\n  shows \"a \\<sim> b\"\n  using assms by (intro associatedI2)\n\nlemma associatedD:\n  fixes G (structure)\n  assumes \"a \\<sim> b\"\n  shows \"a divides b\"\n  using assms by (simp add: associated_def)\n\nlemma (in monoid_cancel) associatedD2:\n  assumes assoc: \"a \\<sim> b\"\n    and carr: \"a \\<in> carrier G\"  \"b \\<in> carrier G\"\n  shows \"\\<exists>u\\<in>Units G. a = b \\<otimes> u\"\n  using assoc\n  unfolding associated_def\nproof clarify\n  assume \"b divides a\"\n  then obtain u where ucarr: \"u \\<in> carrier G\" and a: \"a = b \\<otimes> u\"\n    by (rule dividesE)\n\n  assume \"a divides b\"\n  then obtain u' where u'carr: \"u' \\<in> carrier G\" and b: \"b = a \\<otimes> u'\"\n    by (rule dividesE)\n  note carr = carr ucarr u'carr\n\n  from carr have \"a \\<otimes> \\<one> = a\" by simp\n  also have \"\\<dots> = b \\<otimes> u\" by (simp add: a)\n  also have \"\\<dots> = a \\<otimes> u' \\<otimes> u\" by (simp add: b)\n  also from carr have \"\\<dots> = a \\<otimes> (u' \\<otimes> u)\" by (simp add: m_assoc)\n  finally have \"a \\<otimes> \\<one> = a \\<otimes> (u' \\<otimes> u)\" .\n  with carr have u1: \"\\<one> = u' \\<otimes> u\" by (fast dest: l_cancel)\n\n  from carr have \"b \\<otimes> \\<one> = b\" by simp\n  also have \"\\<dots> = a \\<otimes> u'\" by (simp add: b)\n  also have \"\\<dots> = b \\<otimes> u \\<otimes> u'\" by (simp add: a)\n  also from carr have \"\\<dots> = b \\<otimes> (u \\<otimes> u')\" by (simp add: m_assoc)\n  finally have \"b \\<otimes> \\<one> = b \\<otimes> (u \\<otimes> u')\" .\n  with carr have u2: \"\\<one> = u \\<otimes> u'\" by (fast dest: l_cancel)\n\n  from u'carr u1[symmetric] u2[symmetric] have \"\\<exists>u'\\<in>carrier G. u' \\<otimes> u = \\<one> \\<and> u \\<otimes> u' = \\<one>\"\n    by fast\n  then have \"u \\<in> Units G\"\n    by (simp add: Units_def ucarr)\n  with ucarr a show \"\\<exists>u\\<in>Units G. a = b \\<otimes> u\" by fast\nqed\n\nlemma associatedE:\n  fixes G (structure)\n  assumes assoc: \"a \\<sim> b\"\n    and e: \"\\<lbrakk>a divides b; b divides a\\<rbrakk> \\<Longrightarrow> P\"\n  shows \"P\"\nproof -\n  from assoc have \"a divides b\" \"b divides a\"\n    by (simp_all add: associated_def)\n  then show P by (elim e)\nqed\n\nlemma (in monoid_cancel) associatedE2:\n  assumes assoc: \"a \\<sim> b\"\n    and e: \"\\<And>u. \\<lbrakk>a = b \\<otimes> u; u \\<in> Units G\\<rbrakk> \\<Longrightarrow> P\"\n    and carr: \"a \\<in> carrier G\"  \"b \\<in> carrier G\"\n  shows \"P\"\nproof -\n  from assoc and carr have \"\\<exists>u\\<in>Units G. a = b \\<otimes> u\"\n    by (rule associatedD2)\n  then obtain u where \"u \\<in> Units G\"  \"a = b \\<otimes> u\"\n    by auto\n  then show P by (elim e)\nqed\n\nlemma (in monoid) associated_refl [simp, intro!]:\n  assumes \"a \\<in> carrier G\"\n  shows \"a \\<sim> a\"\n  using assms by (fast intro: associatedI)\n\nlemma (in monoid) associated_sym [sym]:\n  assumes \"a \\<sim> b\"\n    and \"a \\<in> carrier G\"  \"b \\<in> carrier G\"\n  shows \"b \\<sim> a\"\n  using assms by (iprover intro: associatedI elim: associatedE)\n\nlemma (in monoid) associated_trans [trans]:\n  assumes \"a \\<sim> b\"  \"b \\<sim> c\"\n    and \"a \\<in> carrier G\"  \"b \\<in> carrier G\"  \"c \\<in> carrier G\"\n  shows \"a \\<sim> c\"\n  using assms by (iprover intro: associatedI divides_trans elim: associatedE)\n\nlemma (in monoid) division_equiv [intro, simp]: \"equivalence (division_rel G)\"\n  apply unfold_locales\n    apply simp_all\n   apply (metis associated_def)\n  apply (iprover intro: associated_trans)\n  done\n\n\nsubsubsection \\<open>Division and associativity\\<close>\n\nlemma divides_antisym:\n  fixes G (structure)\n  assumes \"a divides b\"  \"b divides a\"\n    and \"a \\<in> carrier G\"  \"b \\<in> carrier G\"\n  shows \"a \\<sim> b\"\n  using assms by (fast intro: associatedI)\n\nlemma (in monoid) divides_cong_l [trans]:\n  assumes \"x \\<sim> x'\"\n    and \"x' divides y\"\n    and [simp]: \"x \\<in> carrier G\"  \"x' \\<in> carrier G\"  \"y \\<in> carrier G\"\n  shows \"x divides y\"\nproof -\n  from assms(1) have \"x divides x'\" by (simp add: associatedD)\n  also note assms(2)\n  finally show \"x divides y\" by simp\nqed\n\nlemma (in monoid) divides_cong_r [trans]:\n  assumes \"x divides y\"\n    and \"y \\<sim> y'\"\n    and [simp]: \"x \\<in> carrier G\"  \"y \\<in> carrier G\"  \"y' \\<in> carrier G\"\n  shows \"x divides y'\"\nproof -\n  note assms(1)\n  also from assms(2) have \"y divides y'\" by (simp add: associatedD)\n  finally show \"x divides y'\" by simp\nqed\n\nlemma (in monoid) division_weak_partial_order [simp, intro!]:\n  \"weak_partial_order (division_rel G)\"\n  apply unfold_locales\n        apply simp_all\n      apply (simp add: associated_sym)\n     apply (blast intro: associated_trans)\n    apply (simp add: divides_antisym)\n   apply (blast intro: divides_trans)\n  apply (blast intro: divides_cong_l divides_cong_r associated_sym)\n  done\n\n\nsubsubsection \\<open>Multiplication and associativity\\<close>\n\nlemma (in monoid_cancel) mult_cong_r:\n  assumes \"b \\<sim> b'\"\n    and carr: \"a \\<in> carrier G\"  \"b \\<in> carrier G\"  \"b' \\<in> carrier G\"\n  shows \"a \\<otimes> b \\<sim> a \\<otimes> b'\"\n  using assms\n  apply (elim associatedE2, intro associatedI2)\n      apply (auto intro: m_assoc[symmetric])\n  done\n\nlemma (in comm_monoid_cancel) mult_cong_l:\n  assumes \"a \\<sim> a'\"\n    and carr: \"a \\<in> carrier G\"  \"a' \\<in> carrier G\"  \"b \\<in> carrier G\"\n  shows \"a \\<otimes> b \\<sim> a' \\<otimes> b\"\n  using assms\n  apply (elim associatedE2, intro associatedI2)\n      apply assumption\n     apply (simp add: m_assoc Units_closed)\n     apply (simp add: m_comm Units_closed)\n    apply simp_all\n  done\n\nlemma (in monoid_cancel) assoc_l_cancel:\n  assumes carr: \"a \\<in> carrier G\"  \"b \\<in> carrier G\"  \"b' \\<in> carrier G\"\n    and \"a \\<otimes> b \\<sim> a \\<otimes> b'\"\n  shows \"b \\<sim> b'\"\n  using assms\n  apply (elim associatedE2, intro associatedI2)\n      apply assumption\n     apply (rule l_cancel[of a])\n        apply (simp add: m_assoc Units_closed)\n       apply fast+\n  done\n\nlemma (in comm_monoid_cancel) assoc_r_cancel:\n  assumes \"a \\<otimes> b \\<sim> a' \\<otimes> b\"\n    and carr: \"a \\<in> carrier G\"  \"a' \\<in> carrier G\"  \"b \\<in> carrier G\"\n  shows \"a \\<sim> a'\"\n  using assms\n  apply (elim associatedE2, intro associatedI2)\n      apply assumption\n     apply (rule r_cancel[of a b])\n        apply (metis Units_closed assms(3) assms(4) m_ac)\n       apply fast+\n  done\n\n\nsubsubsection \\<open>Units\\<close>\n\nlemma (in monoid_cancel) assoc_unit_l [trans]:\n  assumes \"a \\<sim> b\"\n    and \"b \\<in> Units G\"\n    and \"a \\<in> carrier G\"\n  shows \"a \\<in> Units G\"\n  using assms by (fast elim: associatedE2)\n\nlemma (in monoid_cancel) assoc_unit_r [trans]:\n  assumes aunit: \"a \\<in> Units G\"\n    and asc: \"a \\<sim> b\"\n    and bcarr: \"b \\<in> carrier G\"\n  shows \"b \\<in> Units G\"\n  using aunit bcarr associated_sym[OF asc] by (blast intro: assoc_unit_l)\n\nlemma (in comm_monoid) Units_cong:\n  assumes aunit: \"a \\<in> Units G\" and asc: \"a \\<sim> b\"\n    and bcarr: \"b \\<in> carrier G\"\n  shows \"b \\<in> Units G\"\n  using assms by (blast intro: divides_unit elim: associatedE)\n\nlemma (in monoid) Units_assoc:\n  assumes units: \"a \\<in> Units G\"  \"b \\<in> Units G\"\n  shows \"a \\<sim> b\"\n  using units by (fast intro: associatedI unit_divides)\n\nlemma (in monoid) Units_are_ones: \"Units G {.=}\\<^bsub>(division_rel G)\\<^esub> {\\<one>}\"\n  apply (simp add: set_eq_def elem_def, rule, simp_all)\nproof clarsimp\n  fix a\n  assume aunit: \"a \\<in> Units G\"\n  show \"a \\<sim> \\<one>\"\n    apply (rule associatedI)\n     apply (fast intro: dividesI[of \"inv a\"] aunit Units_r_inv[symmetric])\n    apply (fast intro: dividesI[of \"a\"] l_one[symmetric] Units_closed[OF aunit])\n    done\nnext\n  have \"\\<one> \\<in> Units G\" by simp\n  moreover have \"\\<one> \\<sim> \\<one>\" by simp\n  ultimately show \"\\<exists>a \\<in> Units G. \\<one> \\<sim> a\" by fast\nqed\n\nlemma (in comm_monoid) Units_Lower: \"Units G = Lower (division_rel G) (carrier G)\"\n  apply (simp add: Units_def Lower_def)\n  apply (rule, rule)\n   apply clarsimp\n   apply (rule unit_divides)\n    apply (unfold Units_def, fast)\n   apply assumption\n  apply clarsimp\n  apply (metis Unit_eq_dividesone Units_r_inv_ex m_ac(2) one_closed)\n  done\n\n\nsubsubsection \\<open>Proper factors\\<close>\n\nlemma properfactorI:\n  fixes G (structure)\n  assumes \"a divides b\"\n    and \"\\<not>(b divides a)\"\n  shows \"properfactor G a b\"\n  using assms unfolding properfactor_def by simp\n\nlemma properfactorI2:\n  fixes G (structure)\n  assumes advdb: \"a divides b\"\n    and neq: \"\\<not>(a \\<sim> b)\"\n  shows \"properfactor G a b\"\nproof (rule properfactorI, rule advdb, rule notI)\n  assume \"b divides a\"\n  with advdb have \"a \\<sim> b\" by (rule associatedI)\n  with neq show \"False\" by fast\nqed\n\nlemma (in comm_monoid_cancel) properfactorI3:\n  assumes p: \"p = a \\<otimes> b\"\n    and nunit: \"b \\<notin> Units G\"\n    and carr: \"a \\<in> carrier G\"  \"b \\<in> carrier G\"  \"p \\<in> carrier G\"\n  shows \"properfactor G a p\"\n  unfolding p\n  using carr\n  apply (intro properfactorI, fast)\nproof (clarsimp, elim dividesE)\n  fix c\n  assume ccarr: \"c \\<in> carrier G\"\n  note [simp] = carr ccarr\n\n  have \"a \\<otimes> \\<one> = a\" by simp\n  also assume \"a = a \\<otimes> b \\<otimes> c\"\n  also have \"\\<dots> = a \\<otimes> (b \\<otimes> c)\" by (simp add: m_assoc)\n  finally have \"a \\<otimes> \\<one> = a \\<otimes> (b \\<otimes> c)\" .\n\n  then have rinv: \"\\<one> = b \\<otimes> c\" by (intro l_cancel[of \"a\" \"\\<one>\" \"b \\<otimes> c\"], simp+)\n  also have \"\\<dots> = c \\<otimes> b\" by (simp add: m_comm)\n  finally have linv: \"\\<one> = c \\<otimes> b\" .\n\n  from ccarr linv[symmetric] rinv[symmetric] have \"b \\<in> Units G\"\n    unfolding Units_def by fastforce\n  with nunit show False ..\nqed\n\nlemma properfactorE:\n  fixes G (structure)\n  assumes pf: \"properfactor G a b\"\n    and r: \"\\<lbrakk>a divides b; \\<not>(b divides a)\\<rbrakk> \\<Longrightarrow> P\"\n  shows \"P\"\n  using pf unfolding properfactor_def by (fast intro: r)\n\nlemma properfactorE2:\n  fixes G (structure)\n  assumes pf: \"properfactor G a b\"\n    and elim: \"\\<lbrakk>a divides b; \\<not>(a \\<sim> b)\\<rbrakk> \\<Longrightarrow> P\"\n  shows \"P\"\n  using pf unfolding properfactor_def by (fast elim: elim associatedE)\n\nlemma (in monoid) properfactor_unitE:\n  assumes uunit: \"u \\<in> Units G\"\n    and pf: \"properfactor G a u\"\n    and acarr: \"a \\<in> carrier G\"\n  shows \"P\"\n  using pf unit_divides[OF uunit acarr] by (fast elim: properfactorE)\n\nlemma (in monoid) properfactor_divides:\n  assumes pf: \"properfactor G a b\"\n  shows \"a divides b\"\n  using pf by (elim properfactorE)\n\nlemma (in monoid) properfactor_trans1 [trans]:\n  assumes dvds: \"a divides b\"  \"properfactor G b c\"\n    and carr: \"a \\<in> carrier G\"  \"b \\<in> carrier G\"  \"c \\<in> carrier G\"\n  shows \"properfactor G a c\"\n  using dvds carr\n  apply (elim properfactorE, intro properfactorI)\n   apply (iprover intro: divides_trans)+\n  done\n\nlemma (in monoid) properfactor_trans2 [trans]:\n  assumes dvds: \"properfactor G a b\"  \"b divides c\"\n    and carr: \"a \\<in> carrier G\"  \"b \\<in> carrier G\"  \"c \\<in> carrier G\"\n  shows \"properfactor G a c\"\n  using dvds carr\n  apply (elim properfactorE, intro properfactorI)\n   apply (iprover intro: divides_trans)+\n  done\n\nlemma properfactor_lless:\n  fixes G (structure)\n  shows \"properfactor G = lless (division_rel G)\"\n  apply (rule ext)\n  apply (rule ext)\n  apply rule\n   apply (fastforce elim: properfactorE2 intro: weak_llessI)\n  apply (fastforce elim: weak_llessE intro: properfactorI2)\n  done\n\nlemma (in monoid) properfactor_cong_l [trans]:\n  assumes x'x: \"x' \\<sim> x\"\n    and pf: \"properfactor G x y\"\n    and carr: \"x \\<in> carrier G\"  \"x' \\<in> carrier G\"  \"y \\<in> carrier G\"\n  shows \"properfactor G x' y\"\n  using pf\n  unfolding properfactor_lless\nproof -\n  interpret weak_partial_order \"division_rel G\" ..\n  from x'x have \"x' .=\\<^bsub>division_rel G\\<^esub> x\" by simp\n  also assume \"x \\<sqsubset>\\<^bsub>division_rel G\\<^esub> y\"\n  finally show \"x' \\<sqsubset>\\<^bsub>division_rel G\\<^esub> y\" by (simp add: carr)\nqed\n\nlemma (in monoid) properfactor_cong_r [trans]:\n  assumes pf: \"properfactor G x y\"\n    and yy': \"y \\<sim> y'\"\n    and carr: \"x \\<in> carrier G\"  \"y \\<in> carrier G\"  \"y' \\<in> carrier G\"\n  shows \"properfactor G x y'\"\n  using pf\n  unfolding properfactor_lless\nproof -\n  interpret weak_partial_order \"division_rel G\" ..\n  assume \"x \\<sqsubset>\\<^bsub>division_rel G\\<^esub> y\"\n  also from yy'\n  have \"y .=\\<^bsub>division_rel G\\<^esub> y'\" by simp\n  finally show \"x \\<sqsubset>\\<^bsub>division_rel G\\<^esub> y'\" by (simp add: carr)\nqed\n\nlemma (in monoid_cancel) properfactor_mult_lI [intro]:\n  assumes ab: \"properfactor G a b\"\n    and carr: \"a \\<in> carrier G\"  \"b \\<in> carrier G\"  \"c \\<in> carrier G\"\n  shows \"properfactor G (c \\<otimes> a) (c \\<otimes> b)\"\n  using ab carr by (fastforce elim: properfactorE intro: properfactorI)\n\nlemma (in monoid_cancel) properfactor_mult_l [simp]:\n  assumes carr: \"a \\<in> carrier G\"  \"b \\<in> carrier G\"  \"c \\<in> carrier G\"\n  shows \"properfactor G (c \\<otimes> a) (c \\<otimes> b) = properfactor G a b\"\n  using carr by (fastforce elim: properfactorE intro: properfactorI)\n\nlemma (in comm_monoid_cancel) properfactor_mult_rI [intro]:\n  assumes ab: \"properfactor G a b\"\n    and carr: \"a \\<in> carrier G\"  \"b \\<in> carrier G\"  \"c \\<in> carrier G\"\n  shows \"properfactor G (a \\<otimes> c) (b \\<otimes> c)\"\n  using ab carr by (fastforce elim: properfactorE intro: properfactorI)\n\nlemma (in comm_monoid_cancel) properfactor_mult_r [simp]:\n  assumes carr: \"a \\<in> carrier G\"  \"b \\<in> carrier G\"  \"c \\<in> carrier G\"\n  shows \"properfactor G (a \\<otimes> c) (b \\<otimes> c) = properfactor G a b\"\n  using carr by (fastforce elim: properfactorE intro: properfactorI)\n\nlemma (in monoid) properfactor_prod_r:\n  assumes ab: \"properfactor G a b\"\n    and carr[simp]: \"a \\<in> carrier G\"  \"b \\<in> carrier G\"  \"c \\<in> carrier G\"\n  shows \"properfactor G a (b \\<otimes> c)\"\n  by (intro properfactor_trans2[OF ab] divides_prod_r) simp_all\n\nlemma (in comm_monoid) properfactor_prod_l:\n  assumes ab: \"properfactor G a b\"\n    and carr[simp]: \"a \\<in> carrier G\"  \"b \\<in> carrier G\"  \"c \\<in> carrier G\"\n  shows \"properfactor G a (c \\<otimes> b)\"\n  by (intro properfactor_trans2[OF ab] divides_prod_l) simp_all\n\n\nsubsection \\<open>Irreducible Elements and Primes\\<close>\n\nsubsubsection \\<open>Irreducible elements\\<close>\n\nlemma irreducibleI:\n  fixes G (structure)\n  assumes \"a \\<notin> Units G\"\n    and \"\\<And>b. \\<lbrakk>b \\<in> carrier G; properfactor G b a\\<rbrakk> \\<Longrightarrow> b \\<in> Units G\"\n  shows \"irreducible G a\"\n  using assms unfolding irreducible_def by blast\n\nlemma irreducibleE:\n  fixes G (structure)\n  assumes irr: \"irreducible G a\"\n    and elim: \"\\<lbrakk>a \\<notin> Units G; \\<forall>b. b \\<in> carrier G \\<and> properfactor G b a \\<longrightarrow> b \\<in> Units G\\<rbrakk> \\<Longrightarrow> P\"\n  shows \"P\"\n  using assms unfolding irreducible_def by blast\n\nlemma irreducibleD:\n  fixes G (structure)\n  assumes irr: \"irreducible G a\"\n    and pf: \"properfactor G b a\"\n    and bcarr: \"b \\<in> carrier G\"\n  shows \"b \\<in> Units G\"\n  using assms by (fast elim: irreducibleE)\n\nlemma (in monoid_cancel) irreducible_cong [trans]:\n  assumes irred: \"irreducible G a\"\n    and aa': \"a \\<sim> a'\"\n    and carr[simp]: \"a \\<in> carrier G\"  \"a' \\<in> carrier G\"\n  shows \"irreducible G a'\"\n  using assms\n  apply (elim irreducibleE, intro irreducibleI)\n   apply simp_all\n   apply (metis assms(2) assms(3) assoc_unit_l)\n  apply (metis assms(2) assms(3) assms(4) associated_sym properfactor_cong_r)\n  done\n\nlemma (in monoid) irreducible_prod_rI:\n  assumes airr: \"irreducible G a\"\n    and bunit: \"b \\<in> Units G\"\n    and carr[simp]: \"a \\<in> carrier G\"  \"b \\<in> carrier G\"\n  shows \"irreducible G (a \\<otimes> b)\"\n  using airr carr bunit\n  apply (elim irreducibleE, intro irreducibleI, clarify)\n   apply (subgoal_tac \"a \\<in> Units G\", simp)\n   apply (intro prod_unit_r[of a b] carr bunit, assumption)\n  apply (metis assms(2,3) associatedI2 m_closed properfactor_cong_r)\n  done\n\nlemma (in comm_monoid) irreducible_prod_lI:\n  assumes birr: \"irreducible G b\"\n    and aunit: \"a \\<in> Units G\"\n    and carr [simp]: \"a \\<in> carrier G\"  \"b \\<in> carrier G\"\n  shows \"irreducible G (a \\<otimes> b)\"\n  apply (subst m_comm, simp+)\n  apply (intro irreducible_prod_rI assms)\n  done\n\nlemma (in comm_monoid_cancel) irreducible_prodE [elim]:\n  assumes irr: \"irreducible G (a \\<otimes> b)\"\n    and carr[simp]: \"a \\<in> carrier G\"  \"b \\<in> carrier G\"\n    and e1: \"\\<lbrakk>irreducible G a; b \\<in> Units G\\<rbrakk> \\<Longrightarrow> P\"\n    and e2: \"\\<lbrakk>a \\<in> Units G; irreducible G b\\<rbrakk> \\<Longrightarrow> P\"\n  shows P\n  using irr\nproof (elim irreducibleE)\n  assume abnunit: \"a \\<otimes> b \\<notin> Units G\"\n    and isunit[rule_format]: \"\\<forall>ba. ba \\<in> carrier G \\<and> properfactor G ba (a \\<otimes> b) \\<longrightarrow> ba \\<in> Units G\"\n  show P\n  proof (cases \"a \\<in> Units G\")\n    case aunit: True\n    have \"irreducible G b\"\n    proof (rule irreducibleI, rule notI)\n      assume \"b \\<in> Units G\"\n      with aunit have \"(a \\<otimes> b) \\<in> Units G\" by fast\n      with abnunit show \"False\" ..\n    next\n      fix c\n      assume ccarr: \"c \\<in> carrier G\"\n        and \"properfactor G c b\"\n      then have \"properfactor G c (a \\<otimes> b)\" by (simp add: properfactor_prod_l[of c b a])\n      with ccarr show \"c \\<in> Units G\" by (fast intro: isunit)\n    qed\n    with aunit show \"P\" by (rule e2)\n  next\n    case anunit: False\n    with carr have \"properfactor G b (b \\<otimes> a)\" by (fast intro: properfactorI3)\n    then have bf: \"properfactor G b (a \\<otimes> b)\" by (subst m_comm[of a b], simp+)\n    then have bunit: \"b \\<in> Units G\" by (intro isunit, simp)\n\n    have \"irreducible G a\"\n    proof (rule irreducibleI, rule notI)\n      assume \"a \\<in> Units G\"\n      with bunit have \"(a \\<otimes> b) \\<in> Units G\" by fast\n      with abnunit show \"False\" ..\n    next\n      fix c\n      assume ccarr: \"c \\<in> carrier G\"\n        and \"properfactor G c a\"\n      then have \"properfactor G c (a \\<otimes> b)\"\n        by (simp add: properfactor_prod_r[of c a b])\n      with ccarr show \"c \\<in> Units G\" by (fast intro: isunit)\n    qed\n    from this bunit show \"P\" by (rule e1)\n  qed\nqed\n\n\nsubsubsection \\<open>Prime elements\\<close>\n\nlemma primeI:\n  fixes G (structure)\n  assumes \"p \\<notin> Units G\"\n    and \"\\<And>a b. \\<lbrakk>a \\<in> carrier G; b \\<in> carrier G; p divides (a \\<otimes> b)\\<rbrakk> \\<Longrightarrow> p divides a \\<or> p divides b\"\n  shows \"prime G p\"\n  using assms unfolding prime_def by blast\n\nlemma primeE:\n  fixes G (structure)\n  assumes pprime: \"prime G p\"\n    and e: \"\\<lbrakk>p \\<notin> Units G; \\<forall>a\\<in>carrier G. \\<forall>b\\<in>carrier G.\n      p divides a \\<otimes> b \\<longrightarrow> p divides a \\<or> p divides b\\<rbrakk> \\<Longrightarrow> P\"\n  shows \"P\"\n  using pprime unfolding prime_def by (blast dest: e)\n\nlemma (in comm_monoid_cancel) prime_divides:\n  assumes carr: \"a \\<in> carrier G\"  \"b \\<in> carrier G\"\n    and pprime: \"prime G p\"\n    and pdvd: \"p divides a \\<otimes> b\"\n  shows \"p divides a \\<or> p divides b\"\n  using assms by (blast elim: primeE)\n\nlemma (in monoid_cancel) prime_cong [trans]:\n  assumes pprime: \"prime G p\"\n    and pp': \"p \\<sim> p'\"\n    and carr[simp]: \"p \\<in> carrier G\"  \"p' \\<in> carrier G\"\n  shows \"prime G p'\"\n  using pprime\n  apply (elim primeE, intro primeI)\n   apply (metis assms(2) assms(3) assoc_unit_l)\n  apply (metis assms(2) assms(3) assms(4) associated_sym divides_cong_l m_closed)\n  done\n\n\nsubsection \\<open>Factorization and Factorial Monoids\\<close>\n\nsubsubsection \\<open>Function definitions\\<close>\n\ndefinition factors :: \"[_, 'a list, 'a] \\<Rightarrow> bool\"\n  where \"factors G fs a \\<longleftrightarrow> (\\<forall>x \\<in> (set fs). irreducible G x) \\<and> foldr (op \\<otimes>\\<^bsub>G\\<^esub>) fs \\<one>\\<^bsub>G\\<^esub> = a\"\n\ndefinition wfactors ::\"[_, 'a list, 'a] \\<Rightarrow> bool\"\n  where \"wfactors G fs a \\<longleftrightarrow> (\\<forall>x \\<in> (set fs). irreducible G x) \\<and> foldr (op \\<otimes>\\<^bsub>G\\<^esub>) fs \\<one>\\<^bsub>G\\<^esub> \\<sim>\\<^bsub>G\\<^esub> a\"\n\nabbreviation list_assoc :: \"('a,_) monoid_scheme \\<Rightarrow> 'a list \\<Rightarrow> 'a list \\<Rightarrow> bool\" (infix \"[\\<sim>]\\<index>\" 44)\n  where \"list_assoc G \\<equiv> list_all2 (op \\<sim>\\<^bsub>G\\<^esub>)\"\n\ndefinition essentially_equal :: \"[_, 'a list, 'a list] \\<Rightarrow> bool\"\n  where \"essentially_equal G fs1 fs2 \\<longleftrightarrow> (\\<exists>fs1'. fs1 <~~> fs1' \\<and> fs1' [\\<sim>]\\<^bsub>G\\<^esub> fs2)\"\n\n\nlocale factorial_monoid = comm_monoid_cancel +\n  assumes factors_exist: \"\\<lbrakk>a \\<in> carrier G; a \\<notin> Units G\\<rbrakk> \\<Longrightarrow> \\<exists>fs. set fs \\<subseteq> carrier G \\<and> factors G fs a\"\n    and factors_unique:\n      \"\\<lbrakk>factors G fs a; factors G fs' a; a \\<in> carrier G; a \\<notin> Units G;\n        set fs \\<subseteq> carrier G; set fs' \\<subseteq> carrier G\\<rbrakk> \\<Longrightarrow> essentially_equal G fs fs'\"\n\n\nsubsubsection \\<open>Comparing lists of elements\\<close>\n\ntext \\<open>Association on lists\\<close>\n\nlemma (in monoid) listassoc_refl [simp, intro]:\n  assumes \"set as \\<subseteq> carrier G\"\n  shows \"as [\\<sim>] as\"\n  using assms by (induct as) simp_all\n\nlemma (in monoid) listassoc_sym [sym]:\n  assumes \"as [\\<sim>] bs\"\n    and \"set as \\<subseteq> carrier G\"\n    and \"set bs \\<subseteq> carrier G\"\n  shows \"bs [\\<sim>] as\"\n  using assms\nproof (induct as arbitrary: bs, simp)\n  case Cons\n  then show ?case\n    apply (induct bs)\n     apply simp\n    apply clarsimp\n    apply (iprover intro: associated_sym)\n    done\nqed\n\nlemma (in monoid) listassoc_trans [trans]:\n  assumes \"as [\\<sim>] bs\" and \"bs [\\<sim>] cs\"\n    and \"set as \\<subseteq> carrier G\" and \"set bs \\<subseteq> carrier G\" and \"set cs \\<subseteq> carrier G\"\n  shows \"as [\\<sim>] cs\"\n  using assms\n  apply (simp add: list_all2_conv_all_nth set_conv_nth, safe)\n  apply (rule associated_trans)\n      apply (subgoal_tac \"as ! i \\<sim> bs ! i\", assumption)\n      apply (simp, simp)\n    apply blast+\n  done\n\nlemma (in monoid_cancel) irrlist_listassoc_cong:\n  assumes \"\\<forall>a\\<in>set as. irreducible G a\"\n    and \"as [\\<sim>] bs\"\n    and \"set as \\<subseteq> carrier G\" and \"set bs \\<subseteq> carrier G\"\n  shows \"\\<forall>a\\<in>set bs. irreducible G a\"\n  using assms\n  apply (clarsimp simp add: list_all2_conv_all_nth set_conv_nth)\n  apply (blast intro: irreducible_cong)\n  done\n\n\ntext \\<open>Permutations\\<close>\n\nlemma perm_map [intro]:\n  assumes p: \"a <~~> b\"\n  shows \"map f a <~~> map f b\"\n  using p by induct auto\n\nlemma perm_map_switch:\n  assumes m: \"map f a = map f b\" and p: \"b <~~> c\"\n  shows \"\\<exists>d. a <~~> d \\<and> map f d = map f c\"\n  using p m by (induct arbitrary: a) (simp, force, force, blast)\n\nlemma (in monoid) perm_assoc_switch:\n  assumes a:\"as [\\<sim>] bs\" and p: \"bs <~~> cs\"\n  shows \"\\<exists>bs'. as <~~> bs' \\<and> bs' [\\<sim>] cs\"\n  using p a\n  apply (induct bs cs arbitrary: as, simp)\n    apply (clarsimp simp add: list_all2_Cons2, blast)\n   apply (clarsimp simp add: list_all2_Cons2)\n   apply blast\n  apply blast\n  done\n\nlemma (in monoid) perm_assoc_switch_r:\n  assumes p: \"as <~~> bs\" and a:\"bs [\\<sim>] cs\"\n  shows \"\\<exists>bs'. as [\\<sim>] bs' \\<and> bs' <~~> cs\"\n  using p a\n  apply (induct as bs arbitrary: cs, simp)\n    apply (clarsimp simp add: list_all2_Cons1, blast)\n   apply (clarsimp simp add: list_all2_Cons1)\n   apply blast\n  apply blast\n  done\n\ndeclare perm_sym [sym]\n\nlemma perm_setP:\n  assumes perm: \"as <~~> bs\"\n    and as: \"P (set as)\"\n  shows \"P (set bs)\"\nproof -\n  from perm have \"mset as = mset bs\"\n    by (simp add: mset_eq_perm)\n  then have \"set as = set bs\"\n    by (rule mset_eq_setD)\n  with as show \"P (set bs)\"\n    by simp\nqed\n\nlemmas (in monoid) perm_closed = perm_setP[of _ _ \"\\<lambda>as. as \\<subseteq> carrier G\"]\n\nlemmas (in monoid) irrlist_perm_cong = perm_setP[of _ _ \"\\<lambda>as. \\<forall>a\\<in>as. irreducible G a\"]\n\n\ntext \\<open>Essentially equal factorizations\\<close>\n\nlemma (in monoid) essentially_equalI:\n  assumes ex: \"fs1 <~~> fs1'\"  \"fs1' [\\<sim>] fs2\"\n  shows \"essentially_equal G fs1 fs2\"\n  using ex unfolding essentially_equal_def by fast\n\nlemma (in monoid) essentially_equalE:\n  assumes ee: \"essentially_equal G fs1 fs2\"\n    and e: \"\\<And>fs1'. \\<lbrakk>fs1 <~~> fs1'; fs1' [\\<sim>] fs2\\<rbrakk> \\<Longrightarrow> P\"\n  shows \"P\"\n  using ee unfolding essentially_equal_def by (fast intro: e)\n\nlemma (in monoid) ee_refl [simp,intro]:\n  assumes carr: \"set as \\<subseteq> carrier G\"\n  shows \"essentially_equal G as as\"\n  using carr by (fast intro: essentially_equalI)\n\nlemma (in monoid) ee_sym [sym]:\n  assumes ee: \"essentially_equal G as bs\"\n    and carr: \"set as \\<subseteq> carrier G\"  \"set bs \\<subseteq> carrier G\"\n  shows \"essentially_equal G bs as\"\n  using ee\nproof (elim essentially_equalE)\n  fix fs\n  assume \"as <~~> fs\"  \"fs [\\<sim>] bs\"\n  from perm_assoc_switch_r [OF this] obtain fs' where a: \"as [\\<sim>] fs'\" and p: \"fs' <~~> bs\"\n    by blast\n  from p have \"bs <~~> fs'\" by (rule perm_sym)\n  with a[symmetric] carr show ?thesis\n    by (iprover intro: essentially_equalI perm_closed)\nqed\n\nlemma (in monoid) ee_trans [trans]:\n  assumes ab: \"essentially_equal G as bs\" and bc: \"essentially_equal G bs cs\"\n    and ascarr: \"set as \\<subseteq> carrier G\"\n    and bscarr: \"set bs \\<subseteq> carrier G\"\n    and cscarr: \"set cs \\<subseteq> carrier G\"\n  shows \"essentially_equal G as cs\"\n  using ab bc\nproof (elim essentially_equalE)\n  fix abs bcs\n  assume \"abs [\\<sim>] bs\" and pb: \"bs <~~> bcs\"\n  from perm_assoc_switch [OF this] obtain bs' where p: \"abs <~~> bs'\" and a: \"bs' [\\<sim>] bcs\"\n    by blast\n\n  assume \"as <~~> abs\"\n  with p have pp: \"as <~~> bs'\" by fast\n\n  from pp ascarr have c1: \"set bs' \\<subseteq> carrier G\" by (rule perm_closed)\n  from pb bscarr have c2: \"set bcs \\<subseteq> carrier G\" by (rule perm_closed)\n  note a\n  also assume \"bcs [\\<sim>] cs\"\n  finally (listassoc_trans) have \"bs' [\\<sim>] cs\" by (simp add: c1 c2 cscarr)\n  with pp show ?thesis\n    by (rule essentially_equalI)\nqed\n\n\nsubsubsection \\<open>Properties of lists of elements\\<close>\n\ntext \\<open>Multiplication of factors in a list\\<close>\n\nlemma (in monoid) multlist_closed [simp, intro]:\n  assumes ascarr: \"set fs \\<subseteq> carrier G\"\n  shows \"foldr (op \\<otimes>) fs \\<one> \\<in> carrier G\"\n  using ascarr by (induct fs) simp_all\n\nlemma  (in comm_monoid) multlist_dividesI (*[intro]*):\n  assumes \"f \\<in> set fs\" and \"f \\<in> carrier G\" and \"set fs \\<subseteq> carrier G\"\n  shows \"f divides (foldr (op \\<otimes>) fs \\<one>)\"\n  using assms\n  apply (induct fs)\n   apply simp\n  apply (case_tac \"f = a\")\n   apply simp\n   apply (fast intro: dividesI)\n  apply clarsimp\n  apply (metis assms(2) divides_prod_l multlist_closed)\n  done\n\nlemma (in comm_monoid_cancel) multlist_listassoc_cong:\n  assumes \"fs [\\<sim>] fs'\"\n    and \"set fs \\<subseteq> carrier G\" and \"set fs' \\<subseteq> carrier G\"\n  shows \"foldr (op \\<otimes>) fs \\<one> \\<sim> foldr (op \\<otimes>) fs' \\<one>\"\n  using assms\nproof (induct fs arbitrary: fs', simp)\n  case (Cons a as fs')\n  then show ?case\n    apply (induct fs', simp)\n  proof clarsimp\n    fix b bs\n    assume \"a \\<sim> b\"\n      and acarr: \"a \\<in> carrier G\" and bcarr: \"b \\<in> carrier G\"\n      and ascarr: \"set as \\<subseteq> carrier G\"\n    then have p: \"a \\<otimes> foldr op \\<otimes> as \\<one> \\<sim> b \\<otimes> foldr op \\<otimes> as \\<one>\"\n      by (fast intro: mult_cong_l)\n    also\n    assume \"as [\\<sim>] bs\"\n      and bscarr: \"set bs \\<subseteq> carrier G\"\n      and \"\\<And>fs'. \\<lbrakk>as [\\<sim>] fs'; set fs' \\<subseteq> carrier G\\<rbrakk> \\<Longrightarrow> foldr op \\<otimes> as \\<one> \\<sim> foldr op \\<otimes> fs' \\<one>\"\n    then have \"foldr op \\<otimes> as \\<one> \\<sim> foldr op \\<otimes> bs \\<one>\" by simp\n    with ascarr bscarr bcarr have \"b \\<otimes> foldr op \\<otimes> as \\<one> \\<sim> b \\<otimes> foldr op \\<otimes> bs \\<one>\"\n      by (fast intro: mult_cong_r)\n    finally show \"a \\<otimes> foldr op \\<otimes> as \\<one> \\<sim> b \\<otimes> foldr op \\<otimes> bs \\<one>\"\n      by (simp add: ascarr bscarr acarr bcarr)\n  qed\nqed\n\nlemma (in comm_monoid) multlist_perm_cong:\n  assumes prm: \"as <~~> bs\"\n    and ascarr: \"set as \\<subseteq> carrier G\"\n  shows \"foldr (op \\<otimes>) as \\<one> = foldr (op \\<otimes>) bs \\<one>\"\n  using prm ascarr\n  apply (induct, simp, clarsimp simp add: m_ac, clarsimp)\nproof clarsimp\n  fix xs ys zs\n  assume \"xs <~~> ys\"  \"set xs \\<subseteq> carrier G\"\n  then have \"set ys \\<subseteq> carrier G\" by (rule perm_closed)\n  moreover assume \"set ys \\<subseteq> carrier G \\<Longrightarrow> foldr op \\<otimes> ys \\<one> = foldr op \\<otimes> zs \\<one>\"\n  ultimately show \"foldr op \\<otimes> ys \\<one> = foldr op \\<otimes> zs \\<one>\" by simp\nqed\n\nlemma (in comm_monoid_cancel) multlist_ee_cong:\n  assumes \"essentially_equal G fs fs'\"\n    and \"set fs \\<subseteq> carrier G\" and \"set fs' \\<subseteq> carrier G\"\n  shows \"foldr (op \\<otimes>) fs \\<one> \\<sim> foldr (op \\<otimes>) fs' \\<one>\"\n  using assms\n  apply (elim essentially_equalE)\n  apply (simp add: multlist_perm_cong multlist_listassoc_cong perm_closed)\n  done\n\n\nsubsubsection \\<open>Factorization in irreducible elements\\<close>\n\nlemma wfactorsI:\n  fixes G (structure)\n  assumes \"\\<forall>f\\<in>set fs. irreducible G f\"\n    and \"foldr (op \\<otimes>) fs \\<one> \\<sim> a\"\n  shows \"wfactors G fs a\"\n  using assms unfolding wfactors_def by simp\n\nlemma wfactorsE:\n  fixes G (structure)\n  assumes wf: \"wfactors G fs a\"\n    and e: \"\\<lbrakk>\\<forall>f\\<in>set fs. irreducible G f; foldr (op \\<otimes>) fs \\<one> \\<sim> a\\<rbrakk> \\<Longrightarrow> P\"\n  shows \"P\"\n  using wf unfolding wfactors_def by (fast dest: e)\n\nlemma (in monoid) factorsI:\n  assumes \"\\<forall>f\\<in>set fs. irreducible G f\"\n    and \"foldr (op \\<otimes>) fs \\<one> = a\"\n  shows \"factors G fs a\"\n  using assms unfolding factors_def by simp\n\nlemma factorsE:\n  fixes G (structure)\n  assumes f: \"factors G fs a\"\n    and e: \"\\<lbrakk>\\<forall>f\\<in>set fs. irreducible G f; foldr (op \\<otimes>) fs \\<one> = a\\<rbrakk> \\<Longrightarrow> P\"\n  shows \"P\"\n  using f unfolding factors_def by (simp add: e)\n\nlemma (in monoid) factors_wfactors:\n  assumes \"factors G as a\" and \"set as \\<subseteq> carrier G\"\n  shows \"wfactors G as a\"\n  using assms by (blast elim: factorsE intro: wfactorsI)\n\nlemma (in monoid) wfactors_factors:\n  assumes \"wfactors G as a\" and \"set as \\<subseteq> carrier G\"\n  shows \"\\<exists>a'. factors G as a' \\<and> a' \\<sim> a\"\n  using assms by (blast elim: wfactorsE intro: factorsI)\n\nlemma (in monoid) factors_closed [dest]:\n  assumes \"factors G fs a\" and \"set fs \\<subseteq> carrier G\"\n  shows \"a \\<in> carrier G\"\n  using assms by (elim factorsE, clarsimp)\n\nlemma (in monoid) nunit_factors:\n  assumes anunit: \"a \\<notin> Units G\"\n    and fs: \"factors G as a\"\n  shows \"length as > 0\"\nproof -\n  from anunit Units_one_closed have \"a \\<noteq> \\<one>\" by auto\n  with fs show ?thesis by (auto elim: factorsE)\nqed\n\nlemma (in monoid) unit_wfactors [simp]:\n  assumes aunit: \"a \\<in> Units G\"\n  shows \"wfactors G [] a\"\n  using aunit by (intro wfactorsI) (simp, simp add: Units_assoc)\n\nlemma (in comm_monoid_cancel) unit_wfactors_empty:\n  assumes aunit: \"a \\<in> Units G\"\n    and wf: \"wfactors G fs a\"\n    and carr[simp]: \"set fs \\<subseteq> carrier G\"\n  shows \"fs = []\"\nproof (cases fs)\n  case Nil\n  then show ?thesis .\nnext\n  case fs: (Cons f fs')\n  from carr have fcarr[simp]: \"f \\<in> carrier G\" and carr'[simp]: \"set fs' \\<subseteq> carrier G\"\n    by (simp_all add: fs)\n\n  from fs wf have \"irreducible G f\" by (simp add: wfactors_def)\n  then have fnunit: \"f \\<notin> Units G\" by (fast elim: irreducibleE)\n\n  from fs wf have a: \"f \\<otimes> foldr (op \\<otimes>) fs' \\<one> \\<sim> a\" by (simp add: wfactors_def)\n\n  note aunit\n  also from fs wf\n  have a: \"f \\<otimes> foldr (op \\<otimes>) fs' \\<one> \\<sim> a\" by (simp add: wfactors_def)\n  have \"a \\<sim> f \\<otimes> foldr (op \\<otimes>) fs' \\<one>\"\n    by (simp add: Units_closed[OF aunit] a[symmetric])\n  finally have \"f \\<otimes> foldr (op \\<otimes>) fs' \\<one> \\<in> Units G\" by simp\n  then have \"f \\<in> Units G\" by (intro unit_factor[of f], simp+)\n  with fnunit show ?thesis by contradiction\nqed\n\n\ntext \\<open>Comparing wfactors\\<close>\n\nlemma (in comm_monoid_cancel) wfactors_listassoc_cong_l:\n  assumes fact: \"wfactors G fs a\"\n    and asc: \"fs [\\<sim>] fs'\"\n    and carr: \"a \\<in> carrier G\"  \"set fs \\<subseteq> carrier G\"  \"set fs' \\<subseteq> carrier G\"\n  shows \"wfactors G fs' a\"\n  using fact\n  apply (elim wfactorsE, intro wfactorsI)\n   apply (metis assms(2) assms(4) assms(5) irrlist_listassoc_cong)\nproof -\n  from asc[symmetric] have \"foldr op \\<otimes> fs' \\<one> \\<sim> foldr op \\<otimes> fs \\<one>\"\n    by (simp add: multlist_listassoc_cong carr)\n  also assume \"foldr op \\<otimes> fs \\<one> \\<sim> a\"\n  finally show \"foldr op \\<otimes> fs' \\<one> \\<sim> a\" by (simp add: carr)\nqed\n\nlemma (in comm_monoid) wfactors_perm_cong_l:\n  assumes \"wfactors G fs a\"\n    and \"fs <~~> fs'\"\n    and \"set fs \\<subseteq> carrier G\"\n  shows \"wfactors G fs' a\"\n  using assms\n  apply (elim wfactorsE, intro wfactorsI)\n   apply (rule irrlist_perm_cong, assumption+)\n  apply (simp add: multlist_perm_cong[symmetric])\n  done\n\nlemma (in comm_monoid_cancel) wfactors_ee_cong_l [trans]:\n  assumes ee: \"essentially_equal G as bs\"\n    and bfs: \"wfactors G bs b\"\n    and carr: \"b \\<in> carrier G\"  \"set as \\<subseteq> carrier G\"  \"set bs \\<subseteq> carrier G\"\n  shows \"wfactors G as b\"\n  using ee\nproof (elim essentially_equalE)\n  fix fs\n  assume prm: \"as <~~> fs\"\n  with carr have fscarr: \"set fs \\<subseteq> carrier G\" by (simp add: perm_closed)\n\n  note bfs\n  also assume [symmetric]: \"fs [\\<sim>] bs\"\n  also (wfactors_listassoc_cong_l)\n  note prm[symmetric]\n  finally (wfactors_perm_cong_l)\n  show \"wfactors G as b\" by (simp add: carr fscarr)\nqed\n\nlemma (in monoid) wfactors_cong_r [trans]:\n  assumes fac: \"wfactors G fs a\" and aa': \"a \\<sim> a'\"\n    and carr[simp]: \"a \\<in> carrier G\"  \"a' \\<in> carrier G\"  \"set fs \\<subseteq> carrier G\"\n  shows \"wfactors G fs a'\"\n  using fac\nproof (elim wfactorsE, intro wfactorsI)\n  assume \"foldr op \\<otimes> fs \\<one> \\<sim> a\" also note aa'\n  finally show \"foldr op \\<otimes> fs \\<one> \\<sim> a'\" by simp\nqed\n\n\nsubsubsection \\<open>Essentially equal factorizations\\<close>\n\nlemma (in comm_monoid_cancel) unitfactor_ee:\n  assumes uunit: \"u \\<in> Units G\"\n    and carr: \"set as \\<subseteq> carrier G\"\n  shows \"essentially_equal G (as[0 := (as!0 \\<otimes> u)]) as\"\n    (is \"essentially_equal G ?as' as\")\n  using assms\n  apply (intro essentially_equalI[of _ ?as'], simp)\n  apply (cases as, simp)\n  apply (clarsimp, fast intro: associatedI2[of u])\n  done\n\nlemma (in comm_monoid_cancel) factors_cong_unit:\n  assumes uunit: \"u \\<in> Units G\"\n    and anunit: \"a \\<notin> Units G\"\n    and afs: \"factors G as a\"\n    and ascarr: \"set as \\<subseteq> carrier G\"\n  shows \"factors G (as[0 := (as!0 \\<otimes> u)]) (a \\<otimes> u)\"\n    (is \"factors G ?as' ?a'\")\n  using assms\n  apply (elim factorsE, clarify)\n  apply (cases as)\n   apply (simp add: nunit_factors)\n  apply clarsimp\n  apply (elim factorsE, intro factorsI)\n   apply (clarsimp, fast intro: irreducible_prod_rI)\n  apply (simp add: m_ac Units_closed)\n  done\n\nlemma (in comm_monoid) perm_wfactorsD:\n  assumes prm: \"as <~~> bs\"\n    and afs: \"wfactors G as a\"\n    and bfs: \"wfactors G bs b\"\n    and [simp]: \"a \\<in> carrier G\"  \"b \\<in> carrier G\"\n    and ascarr [simp]: \"set as \\<subseteq> carrier G\"\n  shows \"a \\<sim> b\"\n  using afs bfs\nproof (elim wfactorsE)\n  from prm have [simp]: \"set bs \\<subseteq> carrier G\" by (simp add: perm_closed)\n  assume \"foldr op \\<otimes> as \\<one> \\<sim> a\"\n  then have \"a \\<sim> foldr op \\<otimes> as \\<one>\" by (rule associated_sym, simp+)\n  also from prm\n  have \"foldr op \\<otimes> as \\<one> = foldr op \\<otimes> bs \\<one>\" by (rule multlist_perm_cong, simp)\n  also assume \"foldr op \\<otimes> bs \\<one> \\<sim> b\"\n  finally show \"a \\<sim> b\" by simp\nqed\n\nlemma (in comm_monoid_cancel) listassoc_wfactorsD:\n  assumes assoc: \"as [\\<sim>] bs\"\n    and afs: \"wfactors G as a\"\n    and bfs: \"wfactors G bs b\"\n    and [simp]: \"a \\<in> carrier G\"  \"b \\<in> carrier G\"\n    and [simp]: \"set as \\<subseteq> carrier G\"  \"set bs \\<subseteq> carrier G\"\n  shows \"a \\<sim> b\"\n  using afs bfs\nproof (elim wfactorsE)\n  assume \"foldr op \\<otimes> as \\<one> \\<sim> a\"\n  then have \"a \\<sim> foldr op \\<otimes> as \\<one>\" by (rule associated_sym, simp+)\n  also from assoc\n  have \"foldr op \\<otimes> as \\<one> \\<sim> foldr op \\<otimes> bs \\<one>\" by (rule multlist_listassoc_cong, simp+)\n  also assume \"foldr op \\<otimes> bs \\<one> \\<sim> b\"\n  finally show \"a \\<sim> b\" by simp\nqed\n\nlemma (in comm_monoid_cancel) ee_wfactorsD:\n  assumes ee: \"essentially_equal G as bs\"\n    and afs: \"wfactors G as a\" and bfs: \"wfactors G bs b\"\n    and [simp]: \"a \\<in> carrier G\"  \"b \\<in> carrier G\"\n    and ascarr[simp]: \"set as \\<subseteq> carrier G\" and bscarr[simp]: \"set bs \\<subseteq> carrier G\"\n  shows \"a \\<sim> b\"\n  using ee\nproof (elim essentially_equalE)\n  fix fs\n  assume prm: \"as <~~> fs\"\n  then have as'carr[simp]: \"set fs \\<subseteq> carrier G\"\n    by (simp add: perm_closed)\n  from afs prm have afs': \"wfactors G fs a\"\n    by (rule wfactors_perm_cong_l) simp\n  assume \"fs [\\<sim>] bs\"\n  from this afs' bfs show \"a \\<sim> b\"\n    by (rule listassoc_wfactorsD) simp_all\nqed\n\nlemma (in comm_monoid_cancel) ee_factorsD:\n  assumes ee: \"essentially_equal G as bs\"\n    and afs: \"factors G as a\" and bfs:\"factors G bs b\"\n    and \"set as \\<subseteq> carrier G\"  \"set bs \\<subseteq> carrier G\"\n  shows \"a \\<sim> b\"\n  using assms by (blast intro: factors_wfactors dest: ee_wfactorsD)\n\nlemma (in factorial_monoid) ee_factorsI:\n  assumes ab: \"a \\<sim> b\"\n    and afs: \"factors G as a\" and anunit: \"a \\<notin> Units G\"\n    and bfs: \"factors G bs b\" and bnunit: \"b \\<notin> Units G\"\n    and ascarr: \"set as \\<subseteq> carrier G\" and bscarr: \"set bs \\<subseteq> carrier G\"\n  shows \"essentially_equal G as bs\"\nproof -\n  note carr[simp] = factors_closed[OF afs ascarr] ascarr[THEN subsetD]\n    factors_closed[OF bfs bscarr] bscarr[THEN subsetD]\n\n  from ab carr obtain u where uunit: \"u \\<in> Units G\" and a: \"a = b \\<otimes> u\"\n    by (elim associatedE2)\n\n  from uunit bscarr have ee: \"essentially_equal G (bs[0 := (bs!0 \\<otimes> u)]) bs\"\n    (is \"essentially_equal G ?bs' bs\")\n    by (rule unitfactor_ee)\n\n  from bscarr uunit have bs'carr: \"set ?bs' \\<subseteq> carrier G\"\n    by (cases bs) (simp_all add: Units_closed)\n\n  from uunit bnunit bfs bscarr have fac: \"factors G ?bs' (b \\<otimes> u)\"\n    by (rule factors_cong_unit)\n\n  from afs fac[simplified a[symmetric]] ascarr bs'carr anunit\n  have \"essentially_equal G as ?bs'\"\n    by (blast intro: factors_unique)\n  also note ee\n  finally show \"essentially_equal G as bs\"\n    by (simp add: ascarr bscarr bs'carr)\nqed\n\nlemma (in factorial_monoid) ee_wfactorsI:\n  assumes asc: \"a \\<sim> b\"\n    and asf: \"wfactors G as a\" and bsf: \"wfactors G bs b\"\n    and acarr[simp]: \"a \\<in> carrier G\" and bcarr[simp]: \"b \\<in> carrier G\"\n    and ascarr[simp]: \"set as \\<subseteq> carrier G\" and bscarr[simp]: \"set bs \\<subseteq> carrier G\"\n  shows \"essentially_equal G as bs\"\n  using assms\nproof (cases \"a \\<in> Units G\")\n  case aunit: True\n  also note asc\n  finally have bunit: \"b \\<in> Units G\" by simp\n\n  from aunit asf ascarr have e: \"as = []\"\n    by (rule unit_wfactors_empty)\n  from bunit bsf bscarr have e': \"bs = []\"\n    by (rule unit_wfactors_empty)\n\n  have \"essentially_equal G [] []\"\n    by (fast intro: essentially_equalI)\n  then show ?thesis\n    by (simp add: e e')\nnext\n  case anunit: False\n  have bnunit: \"b \\<notin> Units G\"\n  proof clarify\n    assume \"b \\<in> Units G\"\n    also note asc[symmetric]\n    finally have \"a \\<in> Units G\" by simp\n    with anunit show False ..\n  qed\n\n  from wfactors_factors[OF asf ascarr] obtain a' where fa': \"factors G as a'\" and a': \"a' \\<sim> a\"\n    by blast\n  from fa' ascarr have a'carr[simp]: \"a' \\<in> carrier G\"\n    by fast\n\n  have a'nunit: \"a' \\<notin> Units G\"\n  proof clarify\n    assume \"a' \\<in> Units G\"\n    also note a'\n    finally have \"a \\<in> Units G\" by simp\n    with anunit\n    show \"False\" ..\n  qed\n\n  from wfactors_factors[OF bsf bscarr] obtain b' where fb': \"factors G bs b'\" and b': \"b' \\<sim> b\"\n    by blast\n  from fb' bscarr have b'carr[simp]: \"b' \\<in> carrier G\"\n    by fast\n\n  have b'nunit: \"b' \\<notin> Units G\"\n  proof clarify\n    assume \"b' \\<in> Units G\"\n    also note b'\n    finally have \"b \\<in> Units G\" by simp\n    with bnunit show False ..\n  qed\n\n  note a'\n  also note asc\n  also note b'[symmetric]\n  finally have \"a' \\<sim> b'\" by simp\n  from this fa' a'nunit fb' b'nunit ascarr bscarr show \"essentially_equal G as bs\"\n    by (rule ee_factorsI)\nqed\n\nlemma (in factorial_monoid) ee_wfactors:\n  assumes asf: \"wfactors G as a\"\n    and bsf: \"wfactors G bs b\"\n    and acarr: \"a \\<in> carrier G\" and bcarr: \"b \\<in> carrier G\"\n    and ascarr: \"set as \\<subseteq> carrier G\" and bscarr: \"set bs \\<subseteq> carrier G\"\n  shows asc: \"a \\<sim> b = essentially_equal G as bs\"\n  using assms by (fast intro: ee_wfactorsI ee_wfactorsD)\n\nlemma (in factorial_monoid) wfactors_exist [intro, simp]:\n  assumes acarr[simp]: \"a \\<in> carrier G\"\n  shows \"\\<exists>fs. set fs \\<subseteq> carrier G \\<and> wfactors G fs a\"\nproof (cases \"a \\<in> Units G\")\n  case True\n  then have \"wfactors G [] a\" by (rule unit_wfactors)\n  then show ?thesis by (intro exI) force\nnext\n  case False\n  with factors_exist [OF acarr] obtain fs where fscarr: \"set fs \\<subseteq> carrier G\" and f: \"factors G fs a\"\n    by blast\n  from f have \"wfactors G fs a\" by (rule factors_wfactors) fact\n  with fscarr show ?thesis by fast\nqed\n\nlemma (in monoid) wfactors_prod_exists [intro, simp]:\n  assumes \"\\<forall>a \\<in> set as. irreducible G a\" and \"set as \\<subseteq> carrier G\"\n  shows \"\\<exists>a. a \\<in> carrier G \\<and> wfactors G as a\"\n  unfolding wfactors_def using assms by blast\n\nlemma (in factorial_monoid) wfactors_unique:\n  assumes \"wfactors G fs a\"\n    and \"wfactors G fs' a\"\n    and \"a \\<in> carrier G\"\n    and \"set fs \\<subseteq> carrier G\"\n    and \"set fs' \\<subseteq> carrier G\"\n  shows \"essentially_equal G fs fs'\"\n  using assms by (fast intro: ee_wfactorsI[of a a])\n\nlemma (in monoid) factors_mult_single:\n  assumes \"irreducible G a\" and \"factors G fb b\" and \"a \\<in> carrier G\"\n  shows \"factors G (a # fb) (a \\<otimes> b)\"\n  using assms unfolding factors_def by simp\n\nlemma (in monoid_cancel) wfactors_mult_single:\n  assumes f: \"irreducible G a\"  \"wfactors G fb b\"\n    \"a \\<in> carrier G\"  \"b \\<in> carrier G\"  \"set fb \\<subseteq> carrier G\"\n  shows \"wfactors G (a # fb) (a \\<otimes> b)\"\n  using assms unfolding wfactors_def by (simp add: mult_cong_r)\n\nlemma (in monoid) factors_mult:\n  assumes factors: \"factors G fa a\"  \"factors G fb b\"\n    and ascarr: \"set fa \\<subseteq> carrier G\"\n    and bscarr: \"set fb \\<subseteq> carrier G\"\n  shows \"factors G (fa @ fb) (a \\<otimes> b)\"\n  using assms\n  unfolding factors_def\n  apply safe\n   apply force\n  apply hypsubst_thin\n  apply (induct fa)\n   apply simp\n  apply (simp add: m_assoc)\n  done\n\nlemma (in comm_monoid_cancel) wfactors_mult [intro]:\n  assumes asf: \"wfactors G as a\" and bsf:\"wfactors G bs b\"\n    and acarr: \"a \\<in> carrier G\" and bcarr: \"b \\<in> carrier G\"\n    and ascarr: \"set as \\<subseteq> carrier G\" and bscarr:\"set bs \\<subseteq> carrier G\"\n  shows \"wfactors G (as @ bs) (a \\<otimes> b)\"\n  using wfactors_factors[OF asf ascarr] and wfactors_factors[OF bsf bscarr]\nproof clarsimp\n  fix a' b'\n  assume asf': \"factors G as a'\" and a'a: \"a' \\<sim> a\"\n    and bsf': \"factors G bs b'\" and b'b: \"b' \\<sim> b\"\n  from asf' have a'carr: \"a' \\<in> carrier G\" by (rule factors_closed) fact\n  from bsf' have b'carr: \"b' \\<in> carrier G\" by (rule factors_closed) fact\n\n  note carr = acarr bcarr a'carr b'carr ascarr bscarr\n\n  from asf' bsf' have \"factors G (as @ bs) (a' \\<otimes> b')\"\n    by (rule factors_mult) fact+\n\n  with carr have abf': \"wfactors G (as @ bs) (a' \\<otimes> b')\"\n    by (intro factors_wfactors) simp_all\n  also from b'b carr have trb: \"a' \\<otimes> b' \\<sim> a' \\<otimes> b\"\n    by (intro mult_cong_r)\n  also from a'a carr have tra: \"a' \\<otimes> b \\<sim> a \\<otimes> b\"\n    by (intro mult_cong_l)\n  finally show \"wfactors G (as @ bs) (a \\<otimes> b)\"\n    by (simp add: carr)\nqed\n\nlemma (in comm_monoid) factors_dividesI:\n  assumes \"factors G fs a\"\n    and \"f \\<in> set fs\"\n    and \"set fs \\<subseteq> carrier G\"\n  shows \"f divides a\"\n  using assms by (fast elim: factorsE intro: multlist_dividesI)\n\nlemma (in comm_monoid) wfactors_dividesI:\n  assumes p: \"wfactors G fs a\"\n    and fscarr: \"set fs \\<subseteq> carrier G\" and acarr: \"a \\<in> carrier G\"\n    and f: \"f \\<in> set fs\"\n  shows \"f divides a\"\n  using wfactors_factors[OF p fscarr]\nproof clarsimp\n  fix a'\n  assume fsa': \"factors G fs a'\" and a'a: \"a' \\<sim> a\"\n  with fscarr have a'carr: \"a' \\<in> carrier G\"\n    by (simp add: factors_closed)\n\n  from fsa' fscarr f have \"f divides a'\"\n    by (fast intro: factors_dividesI)\n  also note a'a\n  finally show \"f divides a\"\n    by (simp add: f fscarr[THEN subsetD] acarr a'carr)\nqed\n\n\nsubsubsection \\<open>Factorial monoids and wfactors\\<close>\n\nlemma (in comm_monoid_cancel) factorial_monoidI:\n  assumes wfactors_exists: \"\\<And>a. a \\<in> carrier G \\<Longrightarrow> \\<exists>fs. set fs \\<subseteq> carrier G \\<and> wfactors G fs a\"\n    and wfactors_unique:\n      \"\\<And>a fs fs'. \\<lbrakk>a \\<in> carrier G; set fs \\<subseteq> carrier G; set fs' \\<subseteq> carrier G;\n        wfactors G fs a; wfactors G fs' a\\<rbrakk> \\<Longrightarrow> essentially_equal G fs fs'\"\n  shows \"factorial_monoid G\"\nproof\n  fix a\n  assume acarr: \"a \\<in> carrier G\" and anunit: \"a \\<notin> Units G\"\n\n  from wfactors_exists[OF acarr]\n  obtain as where ascarr: \"set as \\<subseteq> carrier G\" and afs: \"wfactors G as a\"\n    by blast\n  from wfactors_factors [OF afs ascarr] obtain a' where afs': \"factors G as a'\" and a'a: \"a' \\<sim> a\"\n    by blast\n  from afs' ascarr have a'carr: \"a' \\<in> carrier G\"\n    by fast\n  have a'nunit: \"a' \\<notin> Units G\"\n  proof clarify\n    assume \"a' \\<in> Units G\"\n    also note a'a\n    finally have \"a \\<in> Units G\" by (simp add: acarr)\n    with anunit show False ..\n  qed\n\n  from a'carr acarr a'a obtain u where uunit: \"u \\<in> Units G\" and a': \"a' = a \\<otimes> u\"\n    by (blast elim: associatedE2)\n\n  note [simp] = acarr Units_closed[OF uunit] Units_inv_closed[OF uunit]\n\n  have \"a = a \\<otimes> \\<one>\" by simp\n  also have \"\\<dots> = a \\<otimes> (u \\<otimes> inv u)\" by (simp add: uunit)\n  also have \"\\<dots> = a' \\<otimes> inv u\" by (simp add: m_assoc[symmetric] a'[symmetric])\n  finally have a: \"a = a' \\<otimes> inv u\" .\n\n  from ascarr uunit have cr: \"set (as[0:=(as!0 \\<otimes> inv u)]) \\<subseteq> carrier G\"\n    by (cases as) auto\n\n  from afs' uunit a'nunit acarr ascarr have \"factors G (as[0:=(as!0 \\<otimes> inv u)]) a\"\n    by (simp add: a factors_cong_unit)\n  with cr show \"\\<exists>fs. set fs \\<subseteq> carrier G \\<and> factors G fs a\"\n    by fast\nqed (blast intro: factors_wfactors wfactors_unique)\n\n\nsubsection \\<open>Factorizations as Multisets\\<close>\n\ntext \\<open>Gives useful operations like intersection\\<close>\n\n(* FIXME: use class_of x instead of closure_of {x} *)\n\nabbreviation \"assocs G x \\<equiv> eq_closure_of (division_rel G) {x}\"\n\ndefinition \"fmset G as = mset (map (\\<lambda>a. assocs G a) as)\"\n\n\ntext \\<open>Helper lemmas\\<close>\n\nlemma (in monoid) assocs_repr_independence:\n  assumes \"y \\<in> assocs G x\"\n    and \"x \\<in> carrier G\"\n  shows \"assocs G x = assocs G y\"\n  using assms\n  apply safe\n   apply (elim closure_ofE2, intro closure_ofI2[of _ _ y])\n     apply (clarsimp, iprover intro: associated_trans associated_sym, simp+)\n  apply (elim closure_ofE2, intro closure_ofI2[of _ _ x])\n    apply (clarsimp, iprover intro: associated_trans, simp+)\n  done\n\nlemma (in monoid) assocs_self:\n  assumes \"x \\<in> carrier G\"\n  shows \"x \\<in> assocs G x\"\n  using assms by (fastforce intro: closure_ofI2)\n\nlemma (in monoid) assocs_repr_independenceD:\n  assumes repr: \"assocs G x = assocs G y\"\n    and ycarr: \"y \\<in> carrier G\"\n  shows \"y \\<in> assocs G x\"\n  unfolding repr using ycarr by (intro assocs_self)\n\nlemma (in comm_monoid) assocs_assoc:\n  assumes \"a \\<in> assocs G b\"\n    and \"b \\<in> carrier G\"\n  shows \"a \\<sim> b\"\n  using assms by (elim closure_ofE2) simp\n\nlemmas (in comm_monoid) assocs_eqD = assocs_repr_independenceD[THEN assocs_assoc]\n\n\nsubsubsection \\<open>Comparing multisets\\<close>\n\nlemma (in monoid) fmset_perm_cong:\n  assumes prm: \"as <~~> bs\"\n  shows \"fmset G as = fmset G bs\"\n  using perm_map[OF prm] unfolding mset_eq_perm fmset_def by blast\n\nlemma (in comm_monoid_cancel) eqc_listassoc_cong:\n  assumes \"as [\\<sim>] bs\"\n    and \"set as \\<subseteq> carrier G\" and \"set bs \\<subseteq> carrier G\"\n  shows \"map (assocs G) as = map (assocs G) bs\"\n  using assms\n  apply (induct as arbitrary: bs, simp)\n  apply (clarsimp simp add: Cons_eq_map_conv list_all2_Cons1, safe)\n   apply (clarsimp elim!: closure_ofE2) defer 1\n   apply (clarsimp elim!: closure_ofE2) defer 1\nproof -\n  fix a x z\n  assume carr[simp]: \"a \\<in> carrier G\"  \"x \\<in> carrier G\"  \"z \\<in> carrier G\"\n  assume \"x \\<sim> a\"\n  also assume \"a \\<sim> z\"\n  finally have \"x \\<sim> z\" by simp\n  with carr show \"x \\<in> assocs G z\"\n    by (intro closure_ofI2) simp_all\nnext\n  fix a x z\n  assume carr[simp]: \"a \\<in> carrier G\"  \"x \\<in> carrier G\"  \"z \\<in> carrier G\"\n  assume \"x \\<sim> z\"\n  also assume [symmetric]: \"a \\<sim> z\"\n  finally have \"x \\<sim> a\" by simp\n  with carr show \"x \\<in> assocs G a\"\n    by (intro closure_ofI2) simp_all\nqed\n\nlemma (in comm_monoid_cancel) fmset_listassoc_cong:\n  assumes \"as [\\<sim>] bs\"\n    and \"set as \\<subseteq> carrier G\" and \"set bs \\<subseteq> carrier G\"\n  shows \"fmset G as = fmset G bs\"\n  using assms unfolding fmset_def by (simp add: eqc_listassoc_cong)\n\nlemma (in comm_monoid_cancel) ee_fmset:\n  assumes ee: \"essentially_equal G as bs\"\n    and ascarr: \"set as \\<subseteq> carrier G\" and bscarr: \"set bs \\<subseteq> carrier G\"\n  shows \"fmset G as = fmset G bs\"\n  using ee\nproof (elim essentially_equalE)\n  fix as'\n  assume prm: \"as <~~> as'\"\n  from prm ascarr have as'carr: \"set as' \\<subseteq> carrier G\"\n    by (rule perm_closed)\n\n  from prm have \"fmset G as = fmset G as'\"\n    by (rule fmset_perm_cong)\n  also assume \"as' [\\<sim>] bs\"\n  with as'carr bscarr have \"fmset G as' = fmset G bs\"\n    by (simp add: fmset_listassoc_cong)\n  finally show \"fmset G as = fmset G bs\" .\nqed\n\nlemma (in monoid_cancel) fmset_ee__hlp_induct:\n  assumes prm: \"cas <~~> cbs\"\n    and cdef: \"cas = map (assocs G) as\"  \"cbs = map (assocs G) bs\"\n  shows \"\\<forall>as bs. (cas <~~> cbs \\<and> cas = map (assocs G) as \\<and>\n    cbs = map (assocs G) bs) \\<longrightarrow> (\\<exists>as'. as <~~> as' \\<and> map (assocs G) as' = cbs)\"\n  apply (rule perm.induct[of cas cbs], rule prm)\n     apply safe\n     apply (simp_all del: mset_map)\n    apply (simp add: map_eq_Cons_conv)\n    apply blast\n   apply force\nproof -\n  fix ys as bs\n  assume p1: \"map (assocs G) as <~~> ys\"\n    and r1[rule_format]:\n      \"\\<forall>asa bs. map (assocs G) as = map (assocs G) asa \\<and> ys = map (assocs G) bs\n        \\<longrightarrow> (\\<exists>as'. asa <~~> as' \\<and> map (assocs G) as' = map (assocs G) bs)\"\n    and p2: \"ys <~~> map (assocs G) bs\"\n    and r2[rule_format]: \"\\<forall>as bsa. ys = map (assocs G) as \\<and> map (assocs G) bs = map (assocs G) bsa\n      \\<longrightarrow> (\\<exists>as'. as <~~> as' \\<and> map (assocs G) as' = map (assocs G) bsa)\"\n    and p3: \"map (assocs G) as <~~> map (assocs G) bs\"\n\n  from p1 have \"mset (map (assocs G) as) = mset ys\"\n    by (simp add: mset_eq_perm del: mset_map)\n  then have setys: \"set (map (assocs G) as) = set ys\"\n    by (rule mset_eq_setD)\n\n  have \"set (map (assocs G) as) = {assocs G x | x. x \\<in> set as}\" by auto\n  with setys have \"set ys \\<subseteq> { assocs G x | x. x \\<in> set as}\" by simp\n  then have \"\\<exists>yy. ys = map (assocs G) yy\"\n  proof (induct ys)\n    case Nil\n    then show ?case by simp\n  next\n    case Cons\n    then show ?case\n    proof clarsimp\n      fix yy x\n      show \"\\<exists>yya. assocs G x # map (assocs G) yy = map (assocs G) yya\"\n        by (rule exI[of _ \"x#yy\"]) simp\n    qed\n  qed\n  then obtain yy where ys: \"ys = map (assocs G) yy\" ..\n\n  from p1 ys have \"\\<exists>as'. as <~~> as' \\<and> map (assocs G) as' = map (assocs G) yy\"\n    by (intro r1) simp\n  then obtain as' where asas': \"as <~~> as'\" and as'yy: \"map (assocs G) as' = map (assocs G) yy\"\n    by auto\n\n  from p2 ys have \"\\<exists>as'. yy <~~> as' \\<and> map (assocs G) as' = map (assocs G) bs\"\n    by (intro r2) simp\n  then obtain as'' where yyas'': \"yy <~~> as''\" and as''bs: \"map (assocs G) as'' = map (assocs G) bs\"\n    by auto\n\n  from perm_map_switch [OF as'yy yyas'']\n  obtain cs where as'cs: \"as' <~~> cs\" and csas'': \"map (assocs G) cs = map (assocs G) as''\"\n    by blast\n\n  from asas' and as'cs have ascs: \"as <~~> cs\"\n    by fast\n  from csas'' and as''bs have \"map (assocs G) cs = map (assocs G) bs\"\n    by simp\n  with ascs show \"\\<exists>as'. as <~~> as' \\<and> map (assocs G) as' = map (assocs G) bs\"\n    by fast\nqed\n\nlemma (in comm_monoid_cancel) fmset_ee:\n  assumes mset: \"fmset G as = fmset G bs\"\n    and ascarr: \"set as \\<subseteq> carrier G\" and bscarr: \"set bs \\<subseteq> carrier G\"\n  shows \"essentially_equal G as bs\"\nproof -\n  from mset have mpp: \"map (assocs G) as <~~> map (assocs G) bs\"\n    by (simp add: fmset_def mset_eq_perm del: mset_map)\n\n  define cas where \"cas = map (assocs G) as\"\n  define cbs where \"cbs = map (assocs G) bs\"\n\n  from cas_def cbs_def mpp have [rule_format]:\n    \"\\<forall>as bs. (cas <~~> cbs \\<and> cas = map (assocs G) as \\<and> cbs = map (assocs G) bs)\n      \\<longrightarrow> (\\<exists>as'. as <~~> as' \\<and> map (assocs G) as' = cbs)\"\n    by (intro fmset_ee__hlp_induct, simp+)\n  with mpp cas_def cbs_def have \"\\<exists>as'. as <~~> as' \\<and> map (assocs G) as' = map (assocs G) bs\"\n    by simp\n\n  then obtain as' where tp: \"as <~~> as'\" and tm: \"map (assocs G) as' = map (assocs G) bs\"\n    by auto\n  from tm have lene: \"length as' = length bs\"\n    by (rule map_eq_imp_length_eq)\n  from tp have \"set as = set as'\"\n    by (simp add: mset_eq_perm mset_eq_setD)\n  with ascarr have as'carr: \"set as' \\<subseteq> carrier G\"\n    by simp\n\n  from tm as'carr[THEN subsetD] bscarr[THEN subsetD] have \"as' [\\<sim>] bs\"\n    by (induct as' arbitrary: bs) (simp, fastforce dest: assocs_eqD[THEN associated_sym])\n  with tp show \"essentially_equal G as bs\"\n    by (fast intro: essentially_equalI)\nqed\n\nlemma (in comm_monoid_cancel) ee_is_fmset:\n  assumes \"set as \\<subseteq> carrier G\" and \"set bs \\<subseteq> carrier G\"\n  shows \"essentially_equal G as bs = (fmset G as = fmset G bs)\"\n  using assms by (fast intro: ee_fmset fmset_ee)\n\n\nsubsubsection \\<open>Interpreting multisets as factorizations\\<close>\n\nlemma (in monoid) mset_fmsetEx:\n  assumes elems: \"\\<And>X. X \\<in> set_mset Cs \\<Longrightarrow> \\<exists>x. P x \\<and> X = assocs G x\"\n  shows \"\\<exists>cs. (\\<forall>c \\<in> set cs. P c) \\<and> fmset G cs = Cs\"\nproof -\n  from surjE[OF surj_mset] obtain Cs' where Cs: \"Cs = mset Cs'\"\n    by blast\n  have \"\\<exists>cs. (\\<forall>c \\<in> set cs. P c) \\<and> mset (map (assocs G) cs) = Cs\"\n    using elems\n    unfolding Cs\n    apply (induct Cs', simp)\n  proof (clarsimp simp del: mset_map)\n    fix a Cs' cs\n    assume ih: \"\\<And>X. X = a \\<or> X \\<in> set Cs' \\<Longrightarrow> \\<exists>x. P x \\<and> X = assocs G x\"\n      and csP: \"\\<forall>x\\<in>set cs. P x\"\n      and mset: \"mset (map (assocs G) cs) = mset Cs'\"\n    from ih obtain c where cP: \"P c\" and a: \"a = assocs G c\"\n      by auto\n    from cP csP have tP: \"\\<forall>x\\<in>set (c#cs). P x\"\n      by simp\n    from mset a have \"mset (map (assocs G) (c#cs)) = add_mset a (mset Cs')\"\n      by simp\n    with tP show \"\\<exists>cs. (\\<forall>x\\<in>set cs. P x) \\<and> mset (map (assocs G) cs) = add_mset a (mset Cs')\"\n      by fast\n  qed\n  then show ?thesis by (simp add: fmset_def)\nqed\n\nlemma (in monoid) mset_wfactorsEx:\n  assumes elems: \"\\<And>X. X \\<in> set_mset Cs \\<Longrightarrow> \\<exists>x. (x \\<in> carrier G \\<and> irreducible G x) \\<and> X = assocs G x\"\n  shows \"\\<exists>c cs. c \\<in> carrier G \\<and> set cs \\<subseteq> carrier G \\<and> wfactors G cs c \\<and> fmset G cs = Cs\"\nproof -\n  have \"\\<exists>cs. (\\<forall>c\\<in>set cs. c \\<in> carrier G \\<and> irreducible G c) \\<and> fmset G cs = Cs\"\n    by (intro mset_fmsetEx, rule elems)\n  then obtain cs where p[rule_format]: \"\\<forall>c\\<in>set cs. c \\<in> carrier G \\<and> irreducible G c\"\n    and Cs[symmetric]: \"fmset G cs = Cs\" by auto\n  from p have cscarr: \"set cs \\<subseteq> carrier G\" by fast\n  from p have \"\\<exists>c. c \\<in> carrier G \\<and> wfactors G cs c\"\n    by (intro wfactors_prod_exists) auto\n  then obtain c where ccarr: \"c \\<in> carrier G\" and cfs: \"wfactors G cs c\" by auto\n  with cscarr Cs show ?thesis by fast\nqed\n\n\nsubsubsection \\<open>Multiplication on multisets\\<close>\n\nlemma (in factorial_monoid) mult_wfactors_fmset:\n  assumes afs: \"wfactors G as a\"\n    and bfs: \"wfactors G bs b\"\n    and cfs: \"wfactors G cs (a \\<otimes> b)\"\n    and carr: \"a \\<in> carrier G\"  \"b \\<in> carrier G\"\n              \"set as \\<subseteq> carrier G\"  \"set bs \\<subseteq> carrier G\"  \"set cs \\<subseteq> carrier G\"\n  shows \"fmset G cs = fmset G as + fmset G bs\"\nproof -\n  from assms have \"wfactors G (as @ bs) (a \\<otimes> b)\"\n    by (intro wfactors_mult)\n  with carr cfs have \"essentially_equal G cs (as@bs)\"\n    by (intro ee_wfactorsI[of \"a\\<otimes>b\" \"a\\<otimes>b\"]) simp_all\n  with carr have \"fmset G cs = fmset G (as@bs)\"\n    by (intro ee_fmset) simp_all\n  also have \"fmset G (as@bs) = fmset G as + fmset G bs\"\n    by (simp add: fmset_def)\n  finally show \"fmset G cs = fmset G as + fmset G bs\" .\nqed\n\nlemma (in factorial_monoid) mult_factors_fmset:\n  assumes afs: \"factors G as a\"\n    and bfs: \"factors G bs b\"\n    and cfs: \"factors G cs (a \\<otimes> b)\"\n    and \"set as \\<subseteq> carrier G\"  \"set bs \\<subseteq> carrier G\"  \"set cs \\<subseteq> carrier G\"\n  shows \"fmset G cs = fmset G as + fmset G bs\"\n  using assms by (blast intro: factors_wfactors mult_wfactors_fmset)\n\nlemma (in comm_monoid_cancel) fmset_wfactors_mult:\n  assumes mset: \"fmset G cs = fmset G as + fmset G bs\"\n    and carr: \"a \\<in> carrier G\"  \"b \\<in> carrier G\"  \"c \\<in> carrier G\"\n      \"set as \\<subseteq> carrier G\"  \"set bs \\<subseteq> carrier G\"  \"set cs \\<subseteq> carrier G\"\n    and fs: \"wfactors G as a\"  \"wfactors G bs b\"  \"wfactors G cs c\"\n  shows \"c \\<sim> a \\<otimes> b\"\nproof -\n  from carr fs have m: \"wfactors G (as @ bs) (a \\<otimes> b)\"\n    by (intro wfactors_mult)\n\n  from mset have \"fmset G cs = fmset G (as@bs)\"\n    by (simp add: fmset_def)\n  then have \"essentially_equal G cs (as@bs)\"\n    by (rule fmset_ee) (simp_all add: carr)\n  then show \"c \\<sim> a \\<otimes> b\"\n    by (rule ee_wfactorsD[of \"cs\" \"as@bs\"]) (simp_all add: assms m)\nqed\n\n\nsubsubsection \\<open>Divisibility on multisets\\<close>\n\nlemma (in factorial_monoid) divides_fmsubset:\n  assumes ab: \"a divides b\"\n    and afs: \"wfactors G as a\"\n    and bfs: \"wfactors G bs b\"\n    and carr: \"a \\<in> carrier G\"  \"b \\<in> carrier G\"  \"set as \\<subseteq> carrier G\"  \"set bs \\<subseteq> carrier G\"\n  shows \"fmset G as \\<le># fmset G bs\"\n  using ab\nproof (elim dividesE)\n  fix c\n  assume ccarr: \"c \\<in> carrier G\"\n  from wfactors_exist [OF this]\n  obtain cs where cscarr: \"set cs \\<subseteq> carrier G\" and cfs: \"wfactors G cs c\"\n    by blast\n  note carr = carr ccarr cscarr\n\n  assume \"b = a \\<otimes> c\"\n  with afs bfs cfs carr have \"fmset G bs = fmset G as + fmset G cs\"\n    by (intro mult_wfactors_fmset[OF afs cfs]) simp_all\n  then show ?thesis by simp\nqed\n\nlemma (in comm_monoid_cancel) fmsubset_divides:\n  assumes msubset: \"fmset G as \\<le># fmset G bs\"\n    and afs: \"wfactors G as a\"\n    and bfs: \"wfactors G bs b\"\n    and acarr: \"a \\<in> carrier G\"\n    and bcarr: \"b \\<in> carrier G\"\n    and ascarr: \"set as \\<subseteq> carrier G\"\n    and bscarr: \"set bs \\<subseteq> carrier G\"\n  shows \"a divides b\"\nproof -\n  from afs have airr: \"\\<forall>a \\<in> set as. irreducible G a\" by (fast elim: wfactorsE)\n  from bfs have birr: \"\\<forall>b \\<in> set bs. irreducible G b\" by (fast elim: wfactorsE)\n\n  have \"\\<exists>c cs. c \\<in> carrier G \\<and> set cs \\<subseteq> carrier G \\<and> wfactors G cs c \\<and> fmset G cs = fmset G bs - fmset G as\"\n  proof (intro mset_wfactorsEx, simp)\n    fix X\n    assume \"X \\<in># fmset G bs - fmset G as\"\n    then have \"X \\<in># fmset G bs\" by (rule in_diffD)\n    then have \"X \\<in> set (map (assocs G) bs)\" by (simp add: fmset_def)\n    then have \"\\<exists>x. x \\<in> set bs \\<and> X = assocs G x\" by (induct bs) auto\n    then obtain x where xbs: \"x \\<in> set bs\" and X: \"X = assocs G x\" by auto\n    with bscarr have xcarr: \"x \\<in> carrier G\" by fast\n    from xbs birr have xirr: \"irreducible G x\" by simp\n\n    from xcarr and xirr and X show \"\\<exists>x. x \\<in> carrier G \\<and> irreducible G x \\<and> X = assocs G x\"\n      by fast\n  qed\n  then obtain c cs\n    where ccarr: \"c \\<in> carrier G\"\n      and cscarr: \"set cs \\<subseteq> carrier G\"\n      and csf: \"wfactors G cs c\"\n      and csmset: \"fmset G cs = fmset G bs - fmset G as\" by auto\n\n  from csmset msubset\n  have \"fmset G bs = fmset G as + fmset G cs\"\n    by (simp add: multiset_eq_iff subseteq_mset_def)\n  then have basc: \"b \\<sim> a \\<otimes> c\"\n    by (rule fmset_wfactors_mult) fact+\n  then show ?thesis\n  proof (elim associatedE2)\n    fix u\n    assume \"u \\<in> Units G\"  \"b = a \\<otimes> c \\<otimes> u\"\n    with acarr ccarr show \"a divides b\"\n      by (fast intro: dividesI[of \"c \\<otimes> u\"] m_assoc)\n  qed (simp_all add: acarr bcarr ccarr)\nqed\n\nlemma (in factorial_monoid) divides_as_fmsubset:\n  assumes \"wfactors G as a\"\n    and \"wfactors G bs b\"\n    and \"a \\<in> carrier G\"\n    and \"b \\<in> carrier G\"\n    and \"set as \\<subseteq> carrier G\"\n    and \"set bs \\<subseteq> carrier G\"\n  shows \"a divides b = (fmset G as \\<le># fmset G bs)\"\n  using assms\n  by (blast intro: divides_fmsubset fmsubset_divides)\n\n\ntext \\<open>Proper factors on multisets\\<close>\n\nlemma (in factorial_monoid) fmset_properfactor:\n  assumes asubb: \"fmset G as \\<le># fmset G bs\"\n    and anb: \"fmset G as \\<noteq> fmset G bs\"\n    and \"wfactors G as a\"\n    and \"wfactors G bs b\"\n    and \"a \\<in> carrier G\"\n    and \"b \\<in> carrier G\"\n    and \"set as \\<subseteq> carrier G\"\n    and \"set bs \\<subseteq> carrier G\"\n  shows \"properfactor G a b\"\n  apply (rule properfactorI)\n   apply (rule fmsubset_divides[of as bs], fact+)\nproof\n  assume \"b divides a\"\n  then have \"fmset G bs \\<le># fmset G as\"\n    by (rule divides_fmsubset) fact+\n  with asubb have \"fmset G as = fmset G bs\"\n    by (rule subset_mset.antisym)\n  with anb show False ..\nqed\n\nlemma (in factorial_monoid) properfactor_fmset:\n  assumes pf: \"properfactor G a b\"\n    and \"wfactors G as a\"\n    and \"wfactors G bs b\"\n    and \"a \\<in> carrier G\"\n    and \"b \\<in> carrier G\"\n    and \"set as \\<subseteq> carrier G\"\n    and \"set bs \\<subseteq> carrier G\"\n  shows \"fmset G as \\<le># fmset G bs \\<and> fmset G as \\<noteq> fmset G bs\"\n  using pf\n  apply (elim properfactorE)\n  apply rule\n   apply (intro divides_fmsubset, assumption)\n        apply (rule assms)+\n  using assms(2,3,4,6,7) divides_as_fmsubset\n  apply auto\n  done\n\nsubsection \\<open>Irreducible Elements are Prime\\<close>\n\nlemma (in factorial_monoid) irreducible_prime:\n  assumes pirr: \"irreducible G p\"\n    and pcarr: \"p \\<in> carrier G\"\n  shows \"prime G p\"\n  using pirr\nproof (elim irreducibleE, intro primeI)\n  fix a b\n  assume acarr: \"a \\<in> carrier G\"  and bcarr: \"b \\<in> carrier G\"\n    and pdvdab: \"p divides (a \\<otimes> b)\"\n    and pnunit: \"p \\<notin> Units G\"\n  assume irreduc[rule_format]:\n    \"\\<forall>b. b \\<in> carrier G \\<and> properfactor G b p \\<longrightarrow> b \\<in> Units G\"\n  from pdvdab obtain c where ccarr: \"c \\<in> carrier G\" and abpc: \"a \\<otimes> b = p \\<otimes> c\"\n    by (rule dividesE)\n\n  from wfactors_exist [OF acarr]\n  obtain as where ascarr: \"set as \\<subseteq> carrier G\" and afs: \"wfactors G as a\"\n    by blast\n\n  from wfactors_exist [OF bcarr]\n  obtain bs where bscarr: \"set bs \\<subseteq> carrier G\" and bfs: \"wfactors G bs b\"\n    by auto\n\n  from wfactors_exist [OF ccarr]\n  obtain cs where cscarr: \"set cs \\<subseteq> carrier G\" and cfs: \"wfactors G cs c\"\n    by auto\n\n  note carr[simp] = pcarr acarr bcarr ccarr ascarr bscarr cscarr\n\n  from afs and bfs have abfs: \"wfactors G (as @ bs) (a \\<otimes> b)\"\n    by (rule wfactors_mult) fact+\n\n  from pirr cfs have pcfs: \"wfactors G (p # cs) (p \\<otimes> c)\"\n    by (rule wfactors_mult_single) fact+\n  with abpc have abfs': \"wfactors G (p # cs) (a \\<otimes> b)\"\n    by simp\n\n  from abfs' abfs have \"essentially_equal G (p # cs) (as @ bs)\"\n    by (rule wfactors_unique) simp+\n\n  then obtain ds where \"p # cs <~~> ds\" and dsassoc: \"ds [\\<sim>] (as @ bs)\"\n    by (fast elim: essentially_equalE)\n  then have \"p \\<in> set ds\"\n    by (simp add: perm_set_eq[symmetric])\n  with dsassoc obtain p' where \"p' \\<in> set (as@bs)\" and pp': \"p \\<sim> p'\"\n    unfolding list_all2_conv_all_nth set_conv_nth by force\n  then consider \"p' \\<in> set as\" | \"p' \\<in> set bs\" by auto\n  then show \"p divides a \\<or> p divides b\"\n  proof cases\n    case 1\n    with ascarr have [simp]: \"p' \\<in> carrier G\" by fast\n\n    note pp'\n    also from afs\n    have \"p' divides a\" by (rule wfactors_dividesI) fact+\n    finally have \"p divides a\" by simp\n    then show ?thesis ..\n  next\n    case 2\n    with bscarr have [simp]: \"p' \\<in> carrier G\" by fast\n\n    note pp'\n    also from bfs\n    have \"p' divides b\" by (rule wfactors_dividesI) fact+\n    finally have \"p divides b\" by simp\n    then show ?thesis ..\n  qed\nqed\n\n\n\\<comment>\"A version using @{const factors}, more complicated\"\nlemma (in factorial_monoid) factors_irreducible_prime:\n  assumes pirr: \"irreducible G p\"\n    and pcarr: \"p \\<in> carrier G\"\n  shows \"prime G p\"\n  using pirr\n  apply (elim irreducibleE, intro primeI)\n   apply assumption\nproof -\n  fix a b\n  assume acarr: \"a \\<in> carrier G\"\n    and bcarr: \"b \\<in> carrier G\"\n    and pdvdab: \"p divides (a \\<otimes> b)\"\n  assume irreduc[rule_format]: \"\\<forall>b. b \\<in> carrier G \\<and> properfactor G b p \\<longrightarrow> b \\<in> Units G\"\n  from pdvdab obtain c where ccarr: \"c \\<in> carrier G\" and abpc: \"a \\<otimes> b = p \\<otimes> c\"\n    by (rule dividesE)\n  note [simp] = pcarr acarr bcarr ccarr\n\n  show \"p divides a \\<or> p divides b\"\n  proof (cases \"a \\<in> Units G\")\n    case aunit: True\n\n    note pdvdab\n    also have \"a \\<otimes> b = b \\<otimes> a\" by (simp add: m_comm)\n    also from aunit have bab: \"b \\<otimes> a \\<sim> b\"\n      by (intro associatedI2[of \"a\"], simp+)\n    finally have \"p divides b\" by simp\n    then show ?thesis ..\n  next\n    case anunit: False\n    show ?thesis\n    proof (cases \"b \\<in> Units G\")\n      case bunit: True\n      note pdvdab\n      also from bunit\n      have baa: \"a \\<otimes> b \\<sim> a\"\n        by (intro associatedI2[of \"b\"], simp+)\n      finally have \"p divides a\" by simp\n      then show ?thesis ..\n    next\n      case bnunit: False\n      have cnunit: \"c \\<notin> Units G\"\n      proof\n        assume cunit: \"c \\<in> Units G\"\n        from bnunit have \"properfactor G a (a \\<otimes> b)\"\n          by (intro properfactorI3[of _ _ b], simp+)\n        also note abpc\n        also from cunit have \"p \\<otimes> c \\<sim> p\"\n          by (intro associatedI2[of c], simp+)\n        finally have \"properfactor G a p\" by simp\n        with acarr have \"a \\<in> Units G\" by (fast intro: irreduc)\n        with anunit show False ..\n      qed\n\n      have abnunit: \"a \\<otimes> b \\<notin> Units G\"\n      proof clarsimp\n        assume \"a \\<otimes> b \\<in> Units G\"\n        then have \"a \\<in> Units G\" by (rule unit_factor) fact+\n        with anunit show False ..\n      qed\n\n      from factors_exist [OF acarr anunit]\n      obtain as where ascarr: \"set as \\<subseteq> carrier G\" and afac: \"factors G as a\"\n        by blast\n\n      from factors_exist [OF bcarr bnunit]\n      obtain bs where bscarr: \"set bs \\<subseteq> carrier G\" and bfac: \"factors G bs b\"\n        by blast\n\n      from factors_exist [OF ccarr cnunit]\n      obtain cs where cscarr: \"set cs \\<subseteq> carrier G\" and cfac: \"factors G cs c\"\n        by auto\n\n      note [simp] = ascarr bscarr cscarr\n\n      from afac and bfac have abfac: \"factors G (as @ bs) (a \\<otimes> b)\"\n        by (rule factors_mult) fact+\n\n      from pirr cfac have pcfac: \"factors G (p # cs) (p \\<otimes> c)\"\n        by (rule factors_mult_single) fact+\n      with abpc have abfac': \"factors G (p # cs) (a \\<otimes> b)\"\n        by simp\n\n      from abfac' abfac have \"essentially_equal G (p # cs) (as @ bs)\"\n        by (rule factors_unique) (fact | simp)+\n      then obtain ds where \"p # cs <~~> ds\" and dsassoc: \"ds [\\<sim>] (as @ bs)\"\n        by (fast elim: essentially_equalE)\n      then have \"p \\<in> set ds\"\n        by (simp add: perm_set_eq[symmetric])\n      with dsassoc obtain p' where \"p' \\<in> set (as@bs)\" and pp': \"p \\<sim> p'\"\n        unfolding list_all2_conv_all_nth set_conv_nth by force\n      then consider \"p' \\<in> set as\" | \"p' \\<in> set bs\" by auto\n      then show \"p divides a \\<or> p divides b\"\n      proof cases\n        case 1\n        with ascarr have [simp]: \"p' \\<in> carrier G\" by fast\n\n        note pp'\n        also from afac 1 have \"p' divides a\" by (rule factors_dividesI) fact+\n        finally have \"p divides a\" by simp\n        then show ?thesis ..\n      next\n        case 2\n        with bscarr have [simp]: \"p' \\<in> carrier G\" by fast\n\n        note pp'\n        also from bfac\n        have \"p' divides b\" by (rule factors_dividesI) fact+\n        finally have \"p divides b\" by simp\n        then show ?thesis ..\n      qed\n    qed\n  qed\nqed\n\n\nsubsection \\<open>Greatest Common Divisors and Lowest Common Multiples\\<close>\n\nsubsubsection \\<open>Definitions\\<close>\n\ndefinition isgcd :: \"[('a,_) monoid_scheme, 'a, 'a, 'a] \\<Rightarrow> bool\"  (\"(_ gcdof\\<index> _ _)\" [81,81,81] 80)\n  where \"x gcdof\\<^bsub>G\\<^esub> a b \\<longleftrightarrow> x divides\\<^bsub>G\\<^esub> a \\<and> x divides\\<^bsub>G\\<^esub> b \\<and>\n    (\\<forall>y\\<in>carrier G. (y divides\\<^bsub>G\\<^esub> a \\<and> y divides\\<^bsub>G\\<^esub> b \\<longrightarrow> y divides\\<^bsub>G\\<^esub> x))\"\n\ndefinition islcm :: \"[_, 'a, 'a, 'a] \\<Rightarrow> bool\"  (\"(_ lcmof\\<index> _ _)\" [81,81,81] 80)\n  where \"x lcmof\\<^bsub>G\\<^esub> a b \\<longleftrightarrow> a divides\\<^bsub>G\\<^esub> x \\<and> b divides\\<^bsub>G\\<^esub> x \\<and>\n    (\\<forall>y\\<in>carrier G. (a divides\\<^bsub>G\\<^esub> y \\<and> b divides\\<^bsub>G\\<^esub> y \\<longrightarrow> x divides\\<^bsub>G\\<^esub> y))\"\n\ndefinition somegcd :: \"('a,_) monoid_scheme \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> 'a\"\n  where \"somegcd G a b = (SOME x. x \\<in> carrier G \\<and> x gcdof\\<^bsub>G\\<^esub> a b)\"\n\ndefinition somelcm :: \"('a,_) monoid_scheme \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> 'a\"\n  where \"somelcm G a b = (SOME x. x \\<in> carrier G \\<and> x lcmof\\<^bsub>G\\<^esub> a b)\"\n\ndefinition \"SomeGcd G A = inf (division_rel G) A\"\n\n\nlocale gcd_condition_monoid = comm_monoid_cancel +\n  assumes gcdof_exists: \"\\<lbrakk>a \\<in> carrier G; b \\<in> carrier G\\<rbrakk> \\<Longrightarrow> \\<exists>c. c \\<in> carrier G \\<and> c gcdof a b\"\n\nlocale primeness_condition_monoid = comm_monoid_cancel +\n  assumes irreducible_prime: \"\\<lbrakk>a \\<in> carrier G; irreducible G a\\<rbrakk> \\<Longrightarrow> prime G a\"\n\nlocale divisor_chain_condition_monoid = comm_monoid_cancel +\n  assumes division_wellfounded: \"wf {(x, y). x \\<in> carrier G \\<and> y \\<in> carrier G \\<and> properfactor G x y}\"\n\n\nsubsubsection \\<open>Connections to \\texttt{Lattice.thy}\\<close>\n\nlemma gcdof_greatestLower:\n  fixes G (structure)\n  assumes carr[simp]: \"a \\<in> carrier G\"  \"b \\<in> carrier G\"\n  shows \"(x \\<in> carrier G \\<and> x gcdof a b) = greatest (division_rel G) x (Lower (division_rel G) {a, b})\"\n  by (auto simp: isgcd_def greatest_def Lower_def elem_def)\n\nlemma lcmof_leastUpper:\n  fixes G (structure)\n  assumes carr[simp]: \"a \\<in> carrier G\"  \"b \\<in> carrier G\"\n  shows \"(x \\<in> carrier G \\<and> x lcmof a b) = least (division_rel G) x (Upper (division_rel G) {a, b})\"\n  by (auto simp: islcm_def least_def Upper_def elem_def)\n\nlemma somegcd_meet:\n  fixes G (structure)\n  assumes carr: \"a \\<in> carrier G\"  \"b \\<in> carrier G\"\n  shows \"somegcd G a b = meet (division_rel G) a b\"\n  by (simp add: somegcd_def meet_def inf_def gcdof_greatestLower[OF carr])\n\nlemma (in monoid) isgcd_divides_l:\n  assumes \"a divides b\"\n    and \"a \\<in> carrier G\"  \"b \\<in> carrier G\"\n  shows \"a gcdof a b\"\n  using assms unfolding isgcd_def by fast\n\nlemma (in monoid) isgcd_divides_r:\n  assumes \"b divides a\"\n    and \"a \\<in> carrier G\"  \"b \\<in> carrier G\"\n  shows \"b gcdof a b\"\n  using assms unfolding isgcd_def by fast\n\n\nsubsubsection \\<open>Existence of gcd and lcm\\<close>\n\nlemma (in factorial_monoid) gcdof_exists:\n  assumes acarr: \"a \\<in> carrier G\"\n    and bcarr: \"b \\<in> carrier G\"\n  shows \"\\<exists>c. c \\<in> carrier G \\<and> c gcdof a b\"\nproof -\n  from wfactors_exist [OF acarr]\n  obtain as where ascarr: \"set as \\<subseteq> carrier G\" and afs: \"wfactors G as a\"\n    by blast\n  from afs have airr: \"\\<forall>a \\<in> set as. irreducible G a\"\n    by (fast elim: wfactorsE)\n\n  from wfactors_exist [OF bcarr]\n  obtain bs where bscarr: \"set bs \\<subseteq> carrier G\" and bfs: \"wfactors G bs b\"\n    by blast\n  from bfs have birr: \"\\<forall>b \\<in> set bs. irreducible G b\"\n    by (fast elim: wfactorsE)\n\n  have \"\\<exists>c cs. c \\<in> carrier G \\<and> set cs \\<subseteq> carrier G \\<and> wfactors G cs c \\<and>\n    fmset G cs = fmset G as \\<inter># fmset G bs\"\n  proof (intro mset_wfactorsEx)\n    fix X\n    assume \"X \\<in># fmset G as \\<inter># fmset G bs\"\n    then have \"X \\<in># fmset G as\" by simp\n    then have \"X \\<in> set (map (assocs G) as)\"\n      by (simp add: fmset_def)\n    then have \"\\<exists>x. X = assocs G x \\<and> x \\<in> set as\"\n      by (induct as) auto\n    then obtain x where X: \"X = assocs G x\" and xas: \"x \\<in> set as\"\n      by blast\n    with ascarr have xcarr: \"x \\<in> carrier G\"\n      by blast\n    from xas airr have xirr: \"irreducible G x\"\n      by simp\n    from xcarr and xirr and X show \"\\<exists>x. (x \\<in> carrier G \\<and> irreducible G x) \\<and> X = assocs G x\"\n      by blast\n  qed\n  then obtain c cs\n    where ccarr: \"c \\<in> carrier G\"\n      and cscarr: \"set cs \\<subseteq> carrier G\"\n      and csirr: \"wfactors G cs c\"\n      and csmset: \"fmset G cs = fmset G as \\<inter># fmset G bs\"\n    by auto\n\n  have \"c gcdof a b\"\n  proof (simp add: isgcd_def, safe)\n    from csmset\n    have \"fmset G cs \\<le># fmset G as\"\n      by (simp add: multiset_inter_def subset_mset_def)\n    then show \"c divides a\" by (rule fmsubset_divides) fact+\n  next\n    from csmset have \"fmset G cs \\<le># fmset G bs\"\n      by (simp add: multiset_inter_def subseteq_mset_def, force)\n    then show \"c divides b\"\n      by (rule fmsubset_divides) fact+\n  next\n    fix y\n    assume \"y \\<in> carrier G\"\n    from wfactors_exist [OF this]\n    obtain ys where yscarr: \"set ys \\<subseteq> carrier G\" and yfs: \"wfactors G ys y\"\n      by blast\n\n    assume \"y divides a\"\n    then have ya: \"fmset G ys \\<le># fmset G as\"\n      by (rule divides_fmsubset) fact+\n\n    assume \"y divides b\"\n    then have yb: \"fmset G ys \\<le># fmset G bs\"\n      by (rule divides_fmsubset) fact+\n\n    from ya yb csmset have \"fmset G ys \\<le># fmset G cs\"\n      by (simp add: subset_mset_def)\n    then show \"y divides c\"\n      by (rule fmsubset_divides) fact+\n  qed\n  with ccarr show \"\\<exists>c. c \\<in> carrier G \\<and> c gcdof a b\"\n    by fast\nqed\n\nlemma (in factorial_monoid) lcmof_exists:\n  assumes acarr: \"a \\<in> carrier G\"\n    and bcarr: \"b \\<in> carrier G\"\n  shows \"\\<exists>c. c \\<in> carrier G \\<and> c lcmof a b\"\nproof -\n  from wfactors_exist [OF acarr]\n  obtain as where ascarr: \"set as \\<subseteq> carrier G\" and afs: \"wfactors G as a\"\n    by blast\n  from afs have airr: \"\\<forall>a \\<in> set as. irreducible G a\"\n    by (fast elim: wfactorsE)\n\n  from wfactors_exist [OF bcarr]\n  obtain bs where bscarr: \"set bs \\<subseteq> carrier G\" and bfs: \"wfactors G bs b\"\n    by blast\n  from bfs have birr: \"\\<forall>b \\<in> set bs. irreducible G b\"\n    by (fast elim: wfactorsE)\n\n  have \"\\<exists>c cs. c \\<in> carrier G \\<and> set cs \\<subseteq> carrier G \\<and> wfactors G cs c \\<and>\n    fmset G cs = (fmset G as - fmset G bs) + fmset G bs\"\n  proof (intro mset_wfactorsEx)\n    fix X\n    assume \"X \\<in># (fmset G as - fmset G bs) + fmset G bs\"\n    then have \"X \\<in># fmset G as \\<or> X \\<in># fmset G bs\"\n      by (auto dest: in_diffD)\n    then consider \"X \\<in> set_mset (fmset G as)\" | \"X \\<in> set_mset (fmset G bs)\"\n      by fast\n    then show \"\\<exists>x. (x \\<in> carrier G \\<and> irreducible G x) \\<and> X = assocs G x\"\n    proof cases\n      case 1\n      then have \"X \\<in> set (map (assocs G) as)\" by (simp add: fmset_def)\n      then have \"\\<exists>x. x \\<in> set as \\<and> X = assocs G x\" by (induct as) auto\n      then obtain x where xas: \"x \\<in> set as\" and X: \"X = assocs G x\" by auto\n      with ascarr have xcarr: \"x \\<in> carrier G\" by fast\n      from xas airr have xirr: \"irreducible G x\" by simp\n      from xcarr and xirr and X show ?thesis by fast\n    next\n      case 2\n      then have \"X \\<in> set (map (assocs G) bs)\" by (simp add: fmset_def)\n      then have \"\\<exists>x. x \\<in> set bs \\<and> X = assocs G x\" by (induct as) auto\n      then obtain x where xbs: \"x \\<in> set bs\" and X: \"X = assocs G x\" by auto\n      with bscarr have xcarr: \"x \\<in> carrier G\" by fast\n      from xbs birr have xirr: \"irreducible G x\" by simp\n      from xcarr and xirr and X show ?thesis by fast\n    qed\n  qed\n  then obtain c cs\n    where ccarr: \"c \\<in> carrier G\"\n      and cscarr: \"set cs \\<subseteq> carrier G\"\n      and csirr: \"wfactors G cs c\"\n      and csmset: \"fmset G cs = fmset G as - fmset G bs + fmset G bs\"\n    by auto\n\n  have \"c lcmof a b\"\n  proof (simp add: islcm_def, safe)\n    from csmset have \"fmset G as \\<le># fmset G cs\"\n      by (simp add: subseteq_mset_def, force)\n    then show \"a divides c\"\n      by (rule fmsubset_divides) fact+\n  next\n    from csmset have \"fmset G bs \\<le># fmset G cs\"\n      by (simp add: subset_mset_def)\n    then show \"b divides c\"\n      by (rule fmsubset_divides) fact+\n  next\n    fix y\n    assume \"y \\<in> carrier G\"\n    from wfactors_exist [OF this]\n    obtain ys where yscarr: \"set ys \\<subseteq> carrier G\" and yfs: \"wfactors G ys y\"\n      by blast\n\n    assume \"a divides y\"\n    then have ya: \"fmset G as \\<le># fmset G ys\"\n      by (rule divides_fmsubset) fact+\n\n    assume \"b divides y\"\n    then have yb: \"fmset G bs \\<le># fmset G ys\"\n      by (rule divides_fmsubset) fact+\n\n    from ya yb csmset have \"fmset G cs \\<le># fmset G ys\"\n      apply (simp add: subseteq_mset_def, clarify)\n      apply (case_tac \"count (fmset G as) a < count (fmset G bs) a\")\n       apply simp\n      apply simp\n      done\n    then show \"c divides y\"\n      by (rule fmsubset_divides) fact+\n  qed\n  with ccarr show \"\\<exists>c. c \\<in> carrier G \\<and> c lcmof a b\"\n    by fast\nqed\n\n\nsubsection \\<open>Conditions for Factoriality\\<close>\n\nsubsubsection \\<open>Gcd condition\\<close>\n\nlemma (in gcd_condition_monoid) division_weak_lower_semilattice [simp]:\n  \"weak_lower_semilattice (division_rel G)\"\nproof -\n  interpret weak_partial_order \"division_rel G\" ..\n  show ?thesis\n    apply (unfold_locales, simp_all)\n  proof -\n    fix x y\n    assume carr: \"x \\<in> carrier G\"  \"y \\<in> carrier G\"\n    from gcdof_exists [OF this] obtain z where zcarr: \"z \\<in> carrier G\" and isgcd: \"z gcdof x y\"\n      by blast\n    with carr have \"greatest (division_rel G) z (Lower (division_rel G) {x, y})\"\n      by (subst gcdof_greatestLower[symmetric], simp+)\n    then show \"\\<exists>z. greatest (division_rel G) z (Lower (division_rel G) {x, y})\"\n      by fast\n  qed\nqed\n\nlemma (in gcd_condition_monoid) gcdof_cong_l:\n  assumes a'a: \"a' \\<sim> a\"\n    and agcd: \"a gcdof b c\"\n    and a'carr: \"a' \\<in> carrier G\" and carr': \"a \\<in> carrier G\"  \"b \\<in> carrier G\"  \"c \\<in> carrier G\"\n  shows \"a' gcdof b c\"\nproof -\n  note carr = a'carr carr'\n  interpret weak_lower_semilattice \"division_rel G\" by simp\n  have \"a' \\<in> carrier G \\<and> a' gcdof b c\"\n    apply (simp add: gcdof_greatestLower carr')\n    apply (subst greatest_Lower_cong_l[of _ a])\n        apply (simp add: a'a)\n       apply (simp add: carr)\n      apply (simp add: carr)\n     apply (simp add: carr)\n    apply (simp add: gcdof_greatestLower[symmetric] agcd carr)\n    done\n  then show ?thesis ..\nqed\n\nlemma (in gcd_condition_monoid) gcd_closed [simp]:\n  assumes carr: \"a \\<in> carrier G\"  \"b \\<in> carrier G\"\n  shows \"somegcd G a b \\<in> carrier G\"\nproof -\n  interpret weak_lower_semilattice \"division_rel G\" by simp\n  show ?thesis\n    apply (simp add: somegcd_meet[OF carr])\n    apply (rule meet_closed[simplified], fact+)\n    done\nqed\n\nlemma (in gcd_condition_monoid) gcd_isgcd:\n  assumes carr: \"a \\<in> carrier G\"  \"b \\<in> carrier G\"\n  shows \"(somegcd G a b) gcdof a b\"\nproof -\n  interpret weak_lower_semilattice \"division_rel G\"\n    by simp\n  from carr have \"somegcd G a b \\<in> carrier G \\<and> (somegcd G a b) gcdof a b\"\n    apply (subst gcdof_greatestLower, simp, simp)\n    apply (simp add: somegcd_meet[OF carr] meet_def)\n    apply (rule inf_of_two_greatest[simplified], assumption+)\n    done\n  then show \"(somegcd G a b) gcdof a b\"\n    by simp\nqed\n\nlemma (in gcd_condition_monoid) gcd_exists:\n  assumes carr: \"a \\<in> carrier G\"  \"b \\<in> carrier G\"\n  shows \"\\<exists>x\\<in>carrier G. x = somegcd G a b\"\nproof -\n  interpret weak_lower_semilattice \"division_rel G\"\n    by simp\n  show ?thesis\n    by (metis carr(1) carr(2) gcd_closed)\nqed\n\nlemma (in gcd_condition_monoid) gcd_divides_l:\n  assumes carr: \"a \\<in> carrier G\"  \"b \\<in> carrier G\"\n  shows \"(somegcd G a b) divides a\"\nproof -\n  interpret weak_lower_semilattice \"division_rel G\"\n    by simp\n  show ?thesis\n    by (metis carr(1) carr(2) gcd_isgcd isgcd_def)\nqed\n\nlemma (in gcd_condition_monoid) gcd_divides_r:\n  assumes carr: \"a \\<in> carrier G\"  \"b \\<in> carrier G\"\n  shows \"(somegcd G a b) divides b\"\nproof -\n  interpret weak_lower_semilattice \"division_rel G\"\n    by simp\n  show ?thesis\n    by (metis carr gcd_isgcd isgcd_def)\nqed\n\nlemma (in gcd_condition_monoid) gcd_divides:\n  assumes sub: \"z divides x\"  \"z divides y\"\n    and L: \"x \\<in> carrier G\"  \"y \\<in> carrier G\"  \"z \\<in> carrier G\"\n  shows \"z divides (somegcd G x y)\"\nproof -\n  interpret weak_lower_semilattice \"division_rel G\"\n    by simp\n  show ?thesis\n    by (metis gcd_isgcd isgcd_def assms)\nqed\n\nlemma (in gcd_condition_monoid) gcd_cong_l:\n  assumes xx': \"x \\<sim> x'\"\n    and carr: \"x \\<in> carrier G\"  \"x' \\<in> carrier G\"  \"y \\<in> carrier G\"\n  shows \"somegcd G x y \\<sim> somegcd G x' y\"\nproof -\n  interpret weak_lower_semilattice \"division_rel G\"\n    by simp\n  show ?thesis\n    apply (simp add: somegcd_meet carr)\n    apply (rule meet_cong_l[simplified], fact+)\n    done\nqed\n\nlemma (in gcd_condition_monoid) gcd_cong_r:\n  assumes carr: \"x \\<in> carrier G\"  \"y \\<in> carrier G\"  \"y' \\<in> carrier G\"\n    and yy': \"y \\<sim> y'\"\n  shows \"somegcd G x y \\<sim> somegcd G x y'\"\nproof -\n  interpret weak_lower_semilattice \"division_rel G\" by simp\n  show ?thesis\n    apply (simp add: somegcd_meet carr)\n    apply (rule meet_cong_r[simplified], fact+)\n    done\nqed\n\n(*\nlemma (in gcd_condition_monoid) asc_cong_gcd_l [intro]:\n  assumes carr: \"b \\<in> carrier G\"\n  shows \"asc_cong (\\<lambda>a. somegcd G a b)\"\nusing carr\nunfolding CONG_def\nby clarsimp (blast intro: gcd_cong_l)\n\nlemma (in gcd_condition_monoid) asc_cong_gcd_r [intro]:\n  assumes carr: \"a \\<in> carrier G\"\n  shows \"asc_cong (\\<lambda>b. somegcd G a b)\"\nusing carr\nunfolding CONG_def\nby clarsimp (blast intro: gcd_cong_r)\n\nlemmas (in gcd_condition_monoid) asc_cong_gcd_split [simp] =\n    assoc_split[OF _ asc_cong_gcd_l] assoc_split[OF _ asc_cong_gcd_r]\n*)\n\nlemma (in gcd_condition_monoid) gcdI:\n  assumes dvd: \"a divides b\"  \"a divides c\"\n    and others: \"\\<forall>y\\<in>carrier G. y divides b \\<and> y divides c \\<longrightarrow> y divides a\"\n    and acarr: \"a \\<in> carrier G\" and bcarr: \"b \\<in> carrier G\" and ccarr: \"c \\<in> carrier G\"\n  shows \"a \\<sim> somegcd G b c\"\n  apply (simp add: somegcd_def)\n  apply (rule someI2_ex)\n   apply (rule exI[of _ a], simp add: isgcd_def)\n   apply (simp add: assms)\n  apply (simp add: isgcd_def assms, clarify)\n  apply (insert assms, blast intro: associatedI)\n  done\n\nlemma (in gcd_condition_monoid) gcdI2:\n  assumes \"a gcdof b c\" and \"a \\<in> carrier G\" and \"b \\<in> carrier G\" and \"c \\<in> carrier G\"\n  shows \"a \\<sim> somegcd G b c\"\n  using assms unfolding isgcd_def by (blast intro: gcdI)\n\nlemma (in gcd_condition_monoid) SomeGcd_ex:\n  assumes \"finite A\"  \"A \\<subseteq> carrier G\"  \"A \\<noteq> {}\"\n  shows \"\\<exists>x\\<in> carrier G. x = SomeGcd G A\"\nproof -\n  interpret weak_lower_semilattice \"division_rel G\"\n    by simp\n  show ?thesis\n    apply (simp add: SomeGcd_def)\n    apply (rule finite_inf_closed[simplified], fact+)\n    done\nqed\n\nlemma (in gcd_condition_monoid) gcd_assoc:\n  assumes carr: \"a \\<in> carrier G\"  \"b \\<in> carrier G\"  \"c \\<in> carrier G\"\n  shows \"somegcd G (somegcd G a b) c \\<sim> somegcd G a (somegcd G b c)\"\nproof -\n  interpret weak_lower_semilattice \"division_rel G\"\n    by simp\n  show ?thesis\n    apply (subst (2 3) somegcd_meet, (simp add: carr)+)\n    apply (simp add: somegcd_meet carr)\n    apply (rule weak_meet_assoc[simplified], fact+)\n    done\nqed\n\nlemma (in gcd_condition_monoid) gcd_mult:\n  assumes acarr: \"a \\<in> carrier G\" and bcarr: \"b \\<in> carrier G\" and ccarr: \"c \\<in> carrier G\"\n  shows \"c \\<otimes> somegcd G a b \\<sim> somegcd G (c \\<otimes> a) (c \\<otimes> b)\"\nproof - (* following Jacobson, Basic Algebra, p.140 *)\n  let ?d = \"somegcd G a b\"\n  let ?e = \"somegcd G (c \\<otimes> a) (c \\<otimes> b)\"\n  note carr[simp] = acarr bcarr ccarr\n  have dcarr: \"?d \\<in> carrier G\" by simp\n  have ecarr: \"?e \\<in> carrier G\" by simp\n  note carr = carr dcarr ecarr\n\n  have \"?d divides a\" by (simp add: gcd_divides_l)\n  then have cd'ca: \"c \\<otimes> ?d divides (c \\<otimes> a)\" by (simp add: divides_mult_lI)\n\n  have \"?d divides b\" by (simp add: gcd_divides_r)\n  then have cd'cb: \"c \\<otimes> ?d divides (c \\<otimes> b)\" by (simp add: divides_mult_lI)\n\n  from cd'ca cd'cb have cd'e: \"c \\<otimes> ?d divides ?e\"\n    by (rule gcd_divides) simp_all\n  then obtain u where ucarr[simp]: \"u \\<in> carrier G\" and e_cdu: \"?e = c \\<otimes> ?d \\<otimes> u\"\n    by blast\n\n  note carr = carr ucarr\n\n  have \"?e divides c \\<otimes> a\" by (rule gcd_divides_l) simp_all\n  then obtain x where xcarr: \"x \\<in> carrier G\" and ca_ex: \"c \\<otimes> a = ?e \\<otimes> x\"\n    by blast\n  with e_cdu have ca_cdux: \"c \\<otimes> a = c \\<otimes> ?d \\<otimes> u \\<otimes> x\"\n    by simp\n\n  from ca_cdux xcarr have \"c \\<otimes> a = c \\<otimes> (?d \\<otimes> u \\<otimes> x)\"\n    by (simp add: m_assoc)\n  then have \"a = ?d \\<otimes> u \\<otimes> x\"\n    by (rule l_cancel[of c a]) (simp add: xcarr)+\n  then have du'a: \"?d \\<otimes> u divides a\"\n    by (rule dividesI[OF xcarr])\n\n  have \"?e divides c \\<otimes> b\" by (intro gcd_divides_r) simp_all\n  then obtain x where xcarr: \"x \\<in> carrier G\" and cb_ex: \"c \\<otimes> b = ?e \\<otimes> x\"\n    by blast\n  with e_cdu have cb_cdux: \"c \\<otimes> b = c \\<otimes> ?d \\<otimes> u \\<otimes> x\"\n    by simp\n\n  from cb_cdux xcarr have \"c \\<otimes> b = c \\<otimes> (?d \\<otimes> u \\<otimes> x)\"\n    by (simp add: m_assoc)\n  with xcarr have \"b = ?d \\<otimes> u \\<otimes> x\"\n    by (intro l_cancel[of c b]) simp_all\n  then have du'b: \"?d \\<otimes> u divides b\"\n    by (intro dividesI[OF xcarr])\n\n  from du'a du'b carr have du'd: \"?d \\<otimes> u divides ?d\"\n    by (intro gcd_divides) simp_all\n  then have uunit: \"u \\<in> Units G\"\n  proof (elim dividesE)\n    fix v\n    assume vcarr[simp]: \"v \\<in> carrier G\"\n    assume d: \"?d = ?d \\<otimes> u \\<otimes> v\"\n    have \"?d \\<otimes> \\<one> = ?d \\<otimes> u \\<otimes> v\" by simp fact\n    also have \"?d \\<otimes> u \\<otimes> v = ?d \\<otimes> (u \\<otimes> v)\" by (simp add: m_assoc)\n    finally have \"?d \\<otimes> \\<one> = ?d \\<otimes> (u \\<otimes> v)\" .\n    then have i2: \"\\<one> = u \\<otimes> v\" by (rule l_cancel) simp_all\n    then have i1: \"\\<one> = v \\<otimes> u\" by (simp add: m_comm)\n    from vcarr i1[symmetric] i2[symmetric] show \"u \\<in> Units G\"\n      by (auto simp: Units_def)\n  qed\n\n  from e_cdu uunit have \"somegcd G (c \\<otimes> a) (c \\<otimes> b) \\<sim> c \\<otimes> somegcd G a b\"\n    by (intro associatedI2[of u]) simp_all\n  from this[symmetric] show \"c \\<otimes> somegcd G a b \\<sim> somegcd G (c \\<otimes> a) (c \\<otimes> b)\"\n    by simp\nqed\n\nlemma (in monoid) assoc_subst:\n  assumes ab: \"a \\<sim> b\"\n    and cP: \"\\<forall>a b. a \\<in> carrier G \\<and> b \\<in> carrier G \\<and> a \\<sim> b\n      \\<longrightarrow> f a \\<in> carrier G \\<and> f b \\<in> carrier G \\<and> f a \\<sim> f b\"\n    and carr: \"a \\<in> carrier G\"  \"b \\<in> carrier G\"\n  shows \"f a \\<sim> f b\"\n  using assms by auto\n\nlemma (in gcd_condition_monoid) relprime_mult:\n  assumes abrelprime: \"somegcd G a b \\<sim> \\<one>\"\n    and acrelprime: \"somegcd G a c \\<sim> \\<one>\"\n    and carr[simp]: \"a \\<in> carrier G\"  \"b \\<in> carrier G\"  \"c \\<in> carrier G\"\n  shows \"somegcd G a (b \\<otimes> c) \\<sim> \\<one>\"\nproof -\n  have \"c = c \\<otimes> \\<one>\" by simp\n  also from abrelprime[symmetric]\n  have \"\\<dots> \\<sim> c \\<otimes> somegcd G a b\"\n    by (rule assoc_subst) (simp add: mult_cong_r)+\n  also have \"\\<dots> \\<sim> somegcd G (c \\<otimes> a) (c \\<otimes> b)\"\n    by (rule gcd_mult) fact+\n  finally have c: \"c \\<sim> somegcd G (c \\<otimes> a) (c \\<otimes> b)\"\n    by simp\n\n  from carr have a: \"a \\<sim> somegcd G a (c \\<otimes> a)\"\n    by (fast intro: gcdI divides_prod_l)\n\n  have \"somegcd G a (b \\<otimes> c) \\<sim> somegcd G a (c \\<otimes> b)\"\n    by (simp add: m_comm)\n  also from a have \"\\<dots> \\<sim> somegcd G (somegcd G a (c \\<otimes> a)) (c \\<otimes> b)\"\n    by (rule assoc_subst) (simp add: gcd_cong_l)+\n  also from gcd_assoc have \"\\<dots> \\<sim> somegcd G a (somegcd G (c \\<otimes> a) (c \\<otimes> b))\"\n    by (rule assoc_subst) simp+\n  also from c[symmetric] have \"\\<dots> \\<sim> somegcd G a c\"\n    by (rule assoc_subst) (simp add: gcd_cong_r)+\n  also note acrelprime\n  finally show \"somegcd G a (b \\<otimes> c) \\<sim> \\<one>\"\n    by simp\nqed\n\nlemma (in gcd_condition_monoid) primeness_condition: \"primeness_condition_monoid G\"\n  apply unfold_locales\n  apply (rule primeI)\n   apply (elim irreducibleE, assumption)\nproof -\n  fix p a b\n  assume pcarr: \"p \\<in> carrier G\" and acarr: \"a \\<in> carrier G\" and bcarr: \"b \\<in> carrier G\"\n    and pirr: \"irreducible G p\"\n    and pdvdab: \"p divides a \\<otimes> b\"\n  from pirr have pnunit: \"p \\<notin> Units G\"\n    and r[rule_format]: \"\\<forall>b. b \\<in> carrier G \\<and> properfactor G b p \\<longrightarrow> b \\<in> Units G\"\n    by (fast elim: irreducibleE)+\n\n  show \"p divides a \\<or> p divides b\"\n  proof (rule ccontr, clarsimp)\n    assume npdvda: \"\\<not> p divides a\"\n    with pcarr acarr have \"\\<one> \\<sim> somegcd G p a\"\n      apply (intro gcdI, simp, simp, simp)\n           apply (fast intro: unit_divides)\n          apply (fast intro: unit_divides)\n         apply (clarsimp simp add: Unit_eq_dividesone[symmetric])\n         apply (rule r, rule, assumption)\n         apply (rule properfactorI, assumption)\n    proof\n      fix y\n      assume ycarr: \"y \\<in> carrier G\"\n      assume \"p divides y\"\n      also assume \"y divides a\"\n      finally have \"p divides a\"\n        by (simp add: pcarr ycarr acarr)\n      with npdvda show False ..\n    qed simp_all\n    with pcarr acarr have pa: \"somegcd G p a \\<sim> \\<one>\"\n      by (fast intro: associated_sym[of \"\\<one>\"] gcd_closed)\n\n    assume npdvdb: \"\\<not> p divides b\"\n    with pcarr bcarr have \"\\<one> \\<sim> somegcd G p b\"\n      apply (intro gcdI, simp, simp, simp)\n           apply (fast intro: unit_divides)\n          apply (fast intro: unit_divides)\n         apply (clarsimp simp add: Unit_eq_dividesone[symmetric])\n         apply (rule r, rule, assumption)\n         apply (rule properfactorI, assumption)\n    proof\n      fix y\n      assume ycarr: \"y \\<in> carrier G\"\n      assume \"p divides y\"\n      also assume \"y divides b\"\n      finally have \"p divides b\" by (simp add: pcarr ycarr bcarr)\n      with npdvdb\n      show \"False\" ..\n    qed simp_all\n    with pcarr bcarr have pb: \"somegcd G p b \\<sim> \\<one>\"\n      by (fast intro: associated_sym[of \"\\<one>\"] gcd_closed)\n\n    from pcarr acarr bcarr pdvdab have \"p gcdof p (a \\<otimes> b)\"\n      by (fast intro: isgcd_divides_l)\n    with pcarr acarr bcarr have \"p \\<sim> somegcd G p (a \\<otimes> b)\"\n      by (fast intro: gcdI2)\n    also from pa pb pcarr acarr bcarr have \"somegcd G p (a \\<otimes> b) \\<sim> \\<one>\"\n      by (rule relprime_mult)\n    finally have \"p \\<sim> \\<one>\"\n      by (simp add: pcarr acarr bcarr)\n    with pcarr have \"p \\<in> Units G\"\n      by (fast intro: assoc_unit_l)\n    with pnunit show False ..\n  qed\nqed\n\nsublocale gcd_condition_monoid \\<subseteq> primeness_condition_monoid\n  by (rule primeness_condition)\n\n\nsubsubsection \\<open>Divisor chain condition\\<close>\n\nlemma (in divisor_chain_condition_monoid) wfactors_exist:\n  assumes acarr: \"a \\<in> carrier G\"\n  shows \"\\<exists>as. set as \\<subseteq> carrier G \\<and> wfactors G as a\"\nproof -\n  have r[rule_format]: \"a \\<in> carrier G \\<longrightarrow> (\\<exists>as. set as \\<subseteq> carrier G \\<and> wfactors G as a)\"\n  proof (rule wf_induct[OF division_wellfounded])\n    fix x\n    assume ih: \"\\<forall>y. (y, x) \\<in> {(x, y). x \\<in> carrier G \\<and> y \\<in> carrier G \\<and> properfactor G x y}\n                    \\<longrightarrow> y \\<in> carrier G \\<longrightarrow> (\\<exists>as. set as \\<subseteq> carrier G \\<and> wfactors G as y)\"\n\n    show \"x \\<in> carrier G \\<longrightarrow> (\\<exists>as. set as \\<subseteq> carrier G \\<and> wfactors G as x)\"\n      apply clarify\n      apply (cases \"x \\<in> Units G\")\n       apply (rule exI[of _ \"[]\"], simp)\n      apply (cases \"irreducible G x\")\n       apply (rule exI[of _ \"[x]\"], simp add: wfactors_def)\n    proof -\n      assume xcarr: \"x \\<in> carrier G\"\n        and xnunit: \"x \\<notin> Units G\"\n        and xnirr: \"\\<not> irreducible G x\"\n      then have \"\\<exists>y. y \\<in> carrier G \\<and> properfactor G y x \\<and> y \\<notin> Units G\"\n        apply -\n        apply (rule ccontr)\n        apply simp\n        apply (subgoal_tac \"irreducible G x\", simp)\n        apply (rule irreducibleI, simp, simp)\n        done\n      then obtain y where ycarr: \"y \\<in> carrier G\" and ynunit: \"y \\<notin> Units G\"\n        and pfyx: \"properfactor G y x\"\n        by blast\n\n      have ih': \"\\<And>y. \\<lbrakk>y \\<in> carrier G; properfactor G y x\\<rbrakk>\n          \\<Longrightarrow> \\<exists>as. set as \\<subseteq> carrier G \\<and> wfactors G as y\"\n        by (rule ih[rule_format, simplified]) (simp add: xcarr)+\n\n      from ih' [OF ycarr pfyx]\n      obtain ys where yscarr: \"set ys \\<subseteq> carrier G\" and yfs: \"wfactors G ys y\"\n        by blast\n\n      from pfyx have \"y divides x\" and nyx: \"\\<not> y \\<sim> x\"\n        by (fast elim: properfactorE2)+\n      then obtain z where zcarr: \"z \\<in> carrier G\" and x: \"x = y \\<otimes> z\"\n        by blast\n\n      from zcarr ycarr have \"properfactor G z x\"\n        apply (subst x)\n        apply (intro properfactorI3[of _ _ y])\n            apply (simp add: m_comm)\n           apply (simp add: ynunit)+\n        done\n      from ih' [OF zcarr this]\n      obtain zs where zscarr: \"set zs \\<subseteq> carrier G\" and zfs: \"wfactors G zs z\"\n        by blast\n      from yscarr zscarr have xscarr: \"set (ys@zs) \\<subseteq> carrier G\"\n        by simp\n      from yfs zfs ycarr zcarr yscarr zscarr have \"wfactors G (ys@zs) (y\\<otimes>z)\"\n        by (rule wfactors_mult)\n      then have \"wfactors G (ys@zs) x\"\n        by (simp add: x)\n      with xscarr show \"\\<exists>xs. set xs \\<subseteq> carrier G \\<and> wfactors G xs x\"\n        by fast\n    qed\n  qed\n  from acarr show ?thesis by (rule r)\nqed\n\n\nsubsubsection \\<open>Primeness condition\\<close>\n\nlemma (in comm_monoid_cancel) multlist_prime_pos:\n  assumes carr: \"a \\<in> carrier G\"  \"set as \\<subseteq> carrier G\"\n    and aprime: \"prime G a\"\n    and \"a divides (foldr (op \\<otimes>) as \\<one>)\"\n  shows \"\\<exists>i<length as. a divides (as!i)\"\nproof -\n  have r[rule_format]: \"set as \\<subseteq> carrier G \\<and> a divides (foldr (op \\<otimes>) as \\<one>)\n    \\<longrightarrow> (\\<exists>i. i < length as \\<and> a divides (as!i))\"\n    apply (induct as)\n     apply clarsimp defer 1\n     apply clarsimp defer 1\n  proof -\n    assume \"a divides \\<one>\"\n    with carr have \"a \\<in> Units G\"\n      by (fast intro: divides_unit[of a \\<one>])\n    with aprime show False\n      by (elim primeE, simp)\n  next\n    fix aa as\n    assume ih[rule_format]: \"a divides foldr op \\<otimes> as \\<one> \\<longrightarrow> (\\<exists>i<length as. a divides as ! i)\"\n      and carr': \"aa \\<in> carrier G\"  \"set as \\<subseteq> carrier G\"\n      and \"a divides aa \\<otimes> foldr op \\<otimes> as \\<one>\"\n    with carr aprime have \"a divides aa \\<or> a divides foldr op \\<otimes> as \\<one>\"\n      by (intro prime_divides) simp+\n    then show \"\\<exists>i<Suc (length as). a divides (aa # as) ! i\"\n    proof\n      assume \"a divides aa\"\n      then have p1: \"a divides (aa#as)!0\" by simp\n      have \"0 < Suc (length as)\" by simp\n      with p1 show ?thesis by fast\n    next\n      assume \"a divides foldr op \\<otimes> as \\<one>\"\n      from ih [OF this] obtain i where \"a divides as ! i\" and len: \"i < length as\" by auto\n      then have p1: \"a divides (aa#as) ! (Suc i)\" by simp\n      from len have \"Suc i < Suc (length as)\" by simp\n      with p1 show ?thesis by force\n   qed\n  qed\n  from assms show ?thesis\n    by (intro r) auto\nqed\n\nlemma (in primeness_condition_monoid) wfactors_unique__hlp_induct:\n  \"\\<forall>a as'. a \\<in> carrier G \\<and> set as \\<subseteq> carrier G \\<and> set as' \\<subseteq> carrier G \\<and>\n           wfactors G as a \\<and> wfactors G as' a \\<longrightarrow> essentially_equal G as as'\"\nproof (induct as)\n  case Nil\n  show ?case\n  proof auto\n    fix a as'\n    assume a: \"a \\<in> carrier G\"\n    assume \"wfactors G [] a\"\n    then obtain \"\\<one> \\<sim> a\" by (auto elim: wfactorsE)\n    with a have \"a \\<in> Units G\" by (auto intro: assoc_unit_r)\n    moreover assume \"wfactors G as' a\"\n    moreover assume \"set as' \\<subseteq> carrier G\"\n    ultimately have \"as' = []\" by (rule unit_wfactors_empty)\n    then show \"essentially_equal G [] as'\" by simp\n  qed\nnext\n  case (Cons ah as)\n  then show ?case\n  proof clarsimp\n    fix a as'\n    assume ih [rule_format]:\n      \"\\<forall>a as'. a \\<in> carrier G \\<and> set as' \\<subseteq> carrier G \\<and> wfactors G as a \\<and>\n        wfactors G as' a \\<longrightarrow> essentially_equal G as as'\"\n      and acarr: \"a \\<in> carrier G\" and ahcarr: \"ah \\<in> carrier G\"\n      and ascarr: \"set as \\<subseteq> carrier G\" and as'carr: \"set as' \\<subseteq> carrier G\"\n      and afs: \"wfactors G (ah # as) a\"\n      and afs': \"wfactors G as' a\"\n    then have ahdvda: \"ah divides a\"\n      by (intro wfactors_dividesI[of \"ah#as\" \"a\"]) simp_all\n    then obtain a' where a'carr: \"a' \\<in> carrier G\" and a: \"a = ah \\<otimes> a'\"\n      by blast\n    have a'fs: \"wfactors G as a'\"\n      apply (rule wfactorsE[OF afs], rule wfactorsI, simp)\n      apply (simp add: a)\n      apply (insert ascarr a'carr)\n      apply (intro assoc_l_cancel[of ah _ a'] multlist_closed ahcarr, assumption+)\n      done\n    from afs have ahirr: \"irreducible G ah\"\n      by (elim wfactorsE) simp\n    with ascarr have ahprime: \"prime G ah\"\n      by (intro irreducible_prime ahcarr)\n\n    note carr [simp] = acarr ahcarr ascarr as'carr a'carr\n\n    note ahdvda\n    also from afs' have \"a divides (foldr (op \\<otimes>) as' \\<one>)\"\n      by (elim wfactorsE associatedE, simp)\n    finally have \"ah divides (foldr (op \\<otimes>) as' \\<one>)\"\n      by simp\n    with ahprime have \"\\<exists>i<length as'. ah divides as'!i\"\n      by (intro multlist_prime_pos) simp_all\n    then obtain i where len: \"i<length as'\" and ahdvd: \"ah divides as'!i\"\n      by blast\n    from afs' carr have irrasi: \"irreducible G (as'!i)\"\n      by (fast intro: nth_mem[OF len] elim: wfactorsE)\n    from len carr have asicarr[simp]: \"as'!i \\<in> carrier G\"\n      unfolding set_conv_nth by force\n    note carr = carr asicarr\n\n    from ahdvd obtain x where \"x \\<in> carrier G\" and asi: \"as'!i = ah \\<otimes> x\"\n      by blast\n    with carr irrasi[simplified asi] have asiah: \"as'!i \\<sim> ah\"\n      apply -\n      apply (elim irreducible_prodE[of \"ah\" \"x\"], assumption+)\n       apply (rule associatedI2[of x], assumption+)\n      apply (rule irreducibleE[OF ahirr], simp)\n      done\n\n    note setparts = set_take_subset[of i as'] set_drop_subset[of \"Suc i\" as']\n    note partscarr [simp] = setparts[THEN subset_trans[OF _ as'carr]]\n    note carr = carr partscarr\n\n    have \"\\<exists>aa_1. aa_1 \\<in> carrier G \\<and> wfactors G (take i as') aa_1\"\n      apply (intro wfactors_prod_exists)\n      using setparts afs'\n       apply (fast elim: wfactorsE)\n      apply simp\n      done\n    then obtain aa_1 where aa1carr: \"aa_1 \\<in> carrier G\" and aa1fs: \"wfactors G (take i as') aa_1\"\n      by auto\n\n    have \"\\<exists>aa_2. aa_2 \\<in> carrier G \\<and> wfactors G (drop (Suc i) as') aa_2\"\n      apply (intro wfactors_prod_exists)\n      using setparts afs'\n       apply (fast elim: wfactorsE)\n      apply simp\n      done\n    then obtain aa_2 where aa2carr: \"aa_2 \\<in> carrier G\"\n      and aa2fs: \"wfactors G (drop (Suc i) as') aa_2\"\n      by auto\n\n    note carr = carr aa1carr[simp] aa2carr[simp]\n\n    from aa1fs aa2fs\n    have v1: \"wfactors G (take i as' @ drop (Suc i) as') (aa_1 \\<otimes> aa_2)\"\n      by (intro wfactors_mult, simp+)\n    then have v1': \"wfactors G (as'!i # take i as' @ drop (Suc i) as') (as'!i \\<otimes> (aa_1 \\<otimes> aa_2))\"\n      apply (intro wfactors_mult_single)\n      using setparts afs'\n          apply (fast intro: nth_mem[OF len] elim: wfactorsE)\n         apply simp_all\n      done\n\n    from aa2carr carr aa1fs aa2fs have \"wfactors G (as'!i # drop (Suc i) as') (as'!i \\<otimes> aa_2)\"\n      by (metis irrasi wfactors_mult_single)\n    with len carr aa1carr aa2carr aa1fs\n    have v2: \"wfactors G (take i as' @ as'!i # drop (Suc i) as') (aa_1 \\<otimes> (as'!i \\<otimes> aa_2))\"\n      apply (intro wfactors_mult)\n           apply fast\n          apply (simp, (fast intro: nth_mem[OF len])?)+\n      done\n\n    from len have as': \"as' = (take i as' @ as'!i # drop (Suc i) as')\"\n      by (simp add: Cons_nth_drop_Suc)\n    with carr have eer: \"essentially_equal G (take i as' @ as'!i # drop (Suc i) as') as'\"\n      by simp\n    with v2 afs' carr aa1carr aa2carr nth_mem[OF len] have \"aa_1 \\<otimes> (as'!i \\<otimes> aa_2) \\<sim> a\"\n      by (metis as' ee_wfactorsD m_closed)\n    then have t1: \"as'!i \\<otimes> (aa_1 \\<otimes> aa_2) \\<sim> a\"\n      by (metis aa1carr aa2carr asicarr m_lcomm)\n    from carr asiah have \"ah \\<otimes> (aa_1 \\<otimes> aa_2) \\<sim> as'!i \\<otimes> (aa_1 \\<otimes> aa_2)\"\n      by (metis associated_sym m_closed mult_cong_l)\n    also note t1\n    finally have \"ah \\<otimes> (aa_1 \\<otimes> aa_2) \\<sim> a\" by simp\n\n    with carr aa1carr aa2carr a'carr nth_mem[OF len] have a': \"aa_1 \\<otimes> aa_2 \\<sim> a'\"\n      by (simp add: a, fast intro: assoc_l_cancel[of ah _ a'])\n\n    note v1\n    also note a'\n    finally have \"wfactors G (take i as' @ drop (Suc i) as') a'\"\n      by simp\n\n    from a'fs this carr have \"essentially_equal G as (take i as' @ drop (Suc i) as')\"\n      by (intro ih[of a']) simp\n    then have ee1: \"essentially_equal G (ah # as) (ah # take i as' @ drop (Suc i) as')\"\n      by (elim essentially_equalE) (fastforce intro: essentially_equalI)\n\n    from carr have ee2: \"essentially_equal G (ah # take i as' @ drop (Suc i) as')\n      (as' ! i # take i as' @ drop (Suc i) as')\"\n    proof (intro essentially_equalI)\n      show \"ah # take i as' @ drop (Suc i) as' <~~> ah # take i as' @ drop (Suc i) as'\"\n        by simp\n    next\n      show \"ah # take i as' @ drop (Suc i) as' [\\<sim>] as' ! i # take i as' @ drop (Suc i) as'\"\n        by (simp add: list_all2_append) (simp add: asiah[symmetric])\n    qed\n\n    note ee1\n    also note ee2\n    also have \"essentially_equal G (as' ! i # take i as' @ drop (Suc i) as')\n      (take i as' @ as' ! i # drop (Suc i) as')\"\n      apply (intro essentially_equalI)\n       apply (subgoal_tac \"as' ! i # take i as' @ drop (Suc i) as' <~~>\n          take i as' @ as' ! i # drop (Suc i) as'\")\n        apply simp\n       apply (rule perm_append_Cons)\n      apply simp\n      done\n    finally have \"essentially_equal G (ah # as) (take i as' @ as' ! i # drop (Suc i) as')\"\n      by simp\n    then show \"essentially_equal G (ah # as) as'\"\n      by (subst as')\n  qed\nqed\n\nlemma (in primeness_condition_monoid) wfactors_unique:\n  assumes \"wfactors G as a\"  \"wfactors G as' a\"\n    and \"a \\<in> carrier G\"  \"set as \\<subseteq> carrier G\"  \"set as' \\<subseteq> carrier G\"\n  shows \"essentially_equal G as as'\"\n  by (rule wfactors_unique__hlp_induct[rule_format, of a]) (simp add: assms)\n\n\nsubsubsection \\<open>Application to factorial monoids\\<close>\n\ntext \\<open>Number of factors for wellfoundedness\\<close>\n\ndefinition factorcount :: \"_ \\<Rightarrow> 'a \\<Rightarrow> nat\"\n  where \"factorcount G a =\n    (THE c. \\<forall>as. set as \\<subseteq> carrier G \\<and> wfactors G as a \\<longrightarrow> c = length as)\"\n\nlemma (in monoid) ee_length:\n  assumes ee: \"essentially_equal G as bs\"\n  shows \"length as = length bs\"\n  by (rule essentially_equalE[OF ee]) (metis list_all2_conv_all_nth perm_length)\n\nlemma (in factorial_monoid) factorcount_exists:\n  assumes carr[simp]: \"a \\<in> carrier G\"\n  shows \"\\<exists>c. \\<forall>as. set as \\<subseteq> carrier G \\<and> wfactors G as a \\<longrightarrow> c = length as\"\nproof -\n  have \"\\<exists>as. set as \\<subseteq> carrier G \\<and> wfactors G as a\"\n    by (intro wfactors_exist) simp\n  then obtain as where ascarr[simp]: \"set as \\<subseteq> carrier G\" and afs: \"wfactors G as a\"\n    by (auto simp del: carr)\n  have \"\\<forall>as'. set as' \\<subseteq> carrier G \\<and> wfactors G as' a \\<longrightarrow> length as = length as'\"\n    by (metis afs ascarr assms ee_length wfactors_unique)\n  then show \"\\<exists>c. \\<forall>as'. set as' \\<subseteq> carrier G \\<and> wfactors G as' a \\<longrightarrow> c = length as'\" ..\nqed\n\nlemma (in factorial_monoid) factorcount_unique:\n  assumes afs: \"wfactors G as a\"\n    and acarr[simp]: \"a \\<in> carrier G\" and ascarr[simp]: \"set as \\<subseteq> carrier G\"\n  shows \"factorcount G a = length as\"\nproof -\n  have \"\\<exists>ac. \\<forall>as. set as \\<subseteq> carrier G \\<and> wfactors G as a \\<longrightarrow> ac = length as\"\n    by (rule factorcount_exists) simp\n  then obtain ac where alen: \"\\<forall>as. set as \\<subseteq> carrier G \\<and> wfactors G as a \\<longrightarrow> ac = length as\"\n    by auto\n  have ac: \"ac = factorcount G a\"\n    apply (simp add: factorcount_def)\n    apply (rule theI2)\n      apply (rule alen)\n     apply (metis afs alen ascarr)+\n    done\n  from ascarr afs have \"ac = length as\"\n    by (iprover intro: alen[rule_format])\n  with ac show ?thesis\n    by simp\nqed\n\nlemma (in factorial_monoid) divides_fcount:\n  assumes dvd: \"a divides b\"\n    and acarr: \"a \\<in> carrier G\"\n    and bcarr:\"b \\<in> carrier G\"\n  shows \"factorcount G a \\<le> factorcount G b\"\nproof (rule dividesE[OF dvd])\n  fix c\n  from assms have \"\\<exists>as. set as \\<subseteq> carrier G \\<and> wfactors G as a\"\n    by blast\n  then obtain as where ascarr: \"set as \\<subseteq> carrier G\" and afs: \"wfactors G as a\"\n    by blast\n  with acarr have fca: \"factorcount G a = length as\"\n    by (intro factorcount_unique)\n\n  assume ccarr: \"c \\<in> carrier G\"\n  then have \"\\<exists>cs. set cs \\<subseteq> carrier G \\<and> wfactors G cs c\"\n    by blast\n  then obtain cs where cscarr: \"set cs \\<subseteq> carrier G\" and cfs: \"wfactors G cs c\"\n    by blast\n\n  note [simp] = acarr bcarr ccarr ascarr cscarr\n\n  assume b: \"b = a \\<otimes> c\"\n  from afs cfs have \"wfactors G (as@cs) (a \\<otimes> c)\"\n    by (intro wfactors_mult) simp_all\n  with b have \"wfactors G (as@cs) b\"\n    by simp\n  then have \"factorcount G b = length (as@cs)\"\n    by (intro factorcount_unique) simp_all\n  then have \"factorcount G b = length as + length cs\"\n    by simp\n  with fca show ?thesis\n    by simp\nqed\n\nlemma (in factorial_monoid) associated_fcount:\n  assumes acarr: \"a \\<in> carrier G\"\n    and bcarr: \"b \\<in> carrier G\"\n    and asc: \"a \\<sim> b\"\n  shows \"factorcount G a = factorcount G b\"\n  apply (rule associatedE[OF asc])\n  apply (drule divides_fcount[OF _ acarr bcarr])\n  apply (drule divides_fcount[OF _ bcarr acarr])\n  apply simp\n  done\n\nlemma (in factorial_monoid) properfactor_fcount:\n  assumes acarr: \"a \\<in> carrier G\" and bcarr:\"b \\<in> carrier G\"\n    and pf: \"properfactor G a b\"\n  shows \"factorcount G a < factorcount G b\"\nproof (rule properfactorE[OF pf], elim dividesE)\n  fix c\n  from assms have \"\\<exists>as. set as \\<subseteq> carrier G \\<and> wfactors G as a\"\n    by blast\n  then obtain as where ascarr: \"set as \\<subseteq> carrier G\" and afs: \"wfactors G as a\"\n    by blast\n  with acarr have fca: \"factorcount G a = length as\"\n    by (intro factorcount_unique)\n\n  assume ccarr: \"c \\<in> carrier G\"\n  then have \"\\<exists>cs. set cs \\<subseteq> carrier G \\<and> wfactors G cs c\"\n    by blast\n  then obtain cs where cscarr: \"set cs \\<subseteq> carrier G\" and cfs: \"wfactors G cs c\"\n    by blast\n\n  assume b: \"b = a \\<otimes> c\"\n\n  have \"wfactors G (as@cs) (a \\<otimes> c)\"\n    by (rule wfactors_mult) fact+\n  with b have \"wfactors G (as@cs) b\"\n    by simp\n  with ascarr cscarr bcarr have \"factorcount G b = length (as@cs)\"\n    by (simp add: factorcount_unique)\n  then have fcb: \"factorcount G b = length as + length cs\"\n    by simp\n\n  assume nbdvda: \"\\<not> b divides a\"\n  have \"c \\<notin> Units G\"\n  proof\n    assume cunit:\"c \\<in> Units G\"\n    have \"b \\<otimes> inv c = a \\<otimes> c \\<otimes> inv c\"\n      by (simp add: b)\n    also from ccarr acarr cunit have \"\\<dots> = a \\<otimes> (c \\<otimes> inv c)\"\n      by (fast intro: m_assoc)\n    also from ccarr cunit have \"\\<dots> = a \\<otimes> \\<one>\" by simp\n    also from acarr have \"\\<dots> = a\" by simp\n    finally have \"a = b \\<otimes> inv c\" by simp\n    with ccarr cunit have \"b divides a\"\n      by (fast intro: dividesI[of \"inv c\"])\n    with nbdvda show False by simp\n  qed\n  with cfs have \"length cs > 0\"\n    apply -\n    apply (rule ccontr, simp)\n    apply (metis Units_one_closed ccarr cscarr l_one one_closed properfactorI3 properfactor_fmset unit_wfactors)\n    done\n  with fca fcb show ?thesis\n    by simp\nqed\n\nsublocale factorial_monoid \\<subseteq> divisor_chain_condition_monoid\n  apply unfold_locales\n  apply (rule wfUNIVI)\n  apply (rule measure_induct[of \"factorcount G\"])\n  apply simp\n  apply (metis properfactor_fcount)\n  done\n\nsublocale factorial_monoid \\<subseteq> primeness_condition_monoid\n  by standard (rule irreducible_prime)\n\n\nlemma (in factorial_monoid) primeness_condition: \"primeness_condition_monoid G\" ..\n\nlemma (in factorial_monoid) gcd_condition [simp]: \"gcd_condition_monoid G\"\n  by standard (rule gcdof_exists)\n\nsublocale factorial_monoid \\<subseteq> gcd_condition_monoid\n  by standard (rule gcdof_exists)\n\nlemma (in factorial_monoid) division_weak_lattice [simp]: \"weak_lattice (division_rel G)\"\nproof -\n  interpret weak_lower_semilattice \"division_rel G\"\n    by simp\n  show \"weak_lattice (division_rel G)\"\n  proof (unfold_locales, simp_all)\n    fix x y\n    assume carr: \"x \\<in> carrier G\"  \"y \\<in> carrier G\"\n    from lcmof_exists [OF this] obtain z where zcarr: \"z \\<in> carrier G\" and isgcd: \"z lcmof x y\"\n      by blast\n    with carr have \"least (division_rel G) z (Upper (division_rel G) {x, y})\"\n      by (simp add: lcmof_leastUpper[symmetric])\n    then show \"\\<exists>z. least (division_rel G) z (Upper (division_rel G) {x, y})\"\n      by blast\n  qed\nqed\n\n\nsubsection \\<open>Factoriality Theorems\\<close>\n\ntheorem factorial_condition_one: (* Jacobson theorem 2.21 *)\n  \"divisor_chain_condition_monoid G \\<and> primeness_condition_monoid G \\<longleftrightarrow> factorial_monoid G\"\nproof (rule iffI, clarify)\n  assume dcc: \"divisor_chain_condition_monoid G\"\n    and pc: \"primeness_condition_monoid G\"\n  interpret divisor_chain_condition_monoid \"G\" by (rule dcc)\n  interpret primeness_condition_monoid \"G\" by (rule pc)\n  show \"factorial_monoid G\"\n    by (fast intro: factorial_monoidI wfactors_exist wfactors_unique)\nnext\n  assume \"factorial_monoid G\"\n  then interpret factorial_monoid \"G\" .\n  show \"divisor_chain_condition_monoid G \\<and> primeness_condition_monoid G\"\n    by rule unfold_locales\nqed\n\ntheorem factorial_condition_two: (* Jacobson theorem 2.22 *)\n  \"divisor_chain_condition_monoid G \\<and> gcd_condition_monoid G \\<longleftrightarrow> factorial_monoid G\"\nproof (rule iffI, clarify)\n  assume dcc: \"divisor_chain_condition_monoid G\"\n    and gc: \"gcd_condition_monoid G\"\n  interpret divisor_chain_condition_monoid \"G\" by (rule dcc)\n  interpret gcd_condition_monoid \"G\" by (rule gc)\n  show \"factorial_monoid G\"\n    by (simp add: factorial_condition_one[symmetric], rule, unfold_locales)\nnext\n  assume \"factorial_monoid G\"\n  then interpret factorial_monoid \"G\" .\n  show \"divisor_chain_condition_monoid G \\<and> gcd_condition_monoid G\"\n    by rule unfold_locales\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/Algebra/Divisibility.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527906914787, "lm_q2_score": 0.828938806208442, "lm_q1q2_score": 0.706216729261745}}
{"text": "theory ScottVariant imports HOML MFilter BaseDefs\nbegin  \n(*Axioms of Scott's variant*)\naxiomatization where \n A1: \"\\<lfloor>\\<^bold>\\<forall>X.((\\<^bold>\\<not>(\\<P> X)) \\<^bold>\\<leftrightarrow> (\\<P>(\\<^bold>\\<rightharpoondown>X)))\\<rfloor>\" and\n A2: \"\\<lfloor>\\<^bold>\\<forall>X Y.(((\\<P> X) \\<^bold>\\<and> (X\\<Rrightarrow>Y)) \\<^bold>\\<rightarrow> (\\<P> Y))\\<rfloor>\" and\n A3: \"\\<lfloor>\\<^bold>\\<forall>\\<Z>.((\\<P>\\<o>\\<s> \\<Z>) \\<^bold>\\<rightarrow> (\\<^bold>\\<forall>X.((X\\<Sqinter>\\<Z>) \\<^bold>\\<rightarrow> (\\<P> X))))\\<rfloor>\" and\n A4: \"\\<lfloor>\\<^bold>\\<forall>X.((\\<P> X) \\<^bold>\\<rightarrow> \\<^bold>\\<box>(\\<P> X))\\<rfloor>\" and\n A5: \"\\<lfloor>\\<P> \\<N>\\<E>\\<rfloor>\" and\n B:  \"\\<lfloor>\\<^bold>\\<forall>\\<phi>.(\\<phi> \\<^bold>\\<rightarrow> \\<^bold>\\<box>\\<^bold>\\<diamond>\\<phi>)\\<rfloor>\" (*Logic KB*)\n\nlemma B': \"\\<forall>x y. \\<not>(x\\<^bold>ry) \\<or> (y\\<^bold>rx)\" using B by fastforce\n\n(*Necessary existence of a Godlike entity*)\ntheorem T6: \"\\<lfloor>\\<^bold>\\<box>(\\<^bold>\\<exists>\\<^sup>E \\<G>)\\<rfloor>\" \nproof -\n have T1: \"\\<lfloor>\\<^bold>\\<forall>X.((\\<P> X) \\<^bold>\\<rightarrow> \\<^bold>\\<diamond>(\\<^bold>\\<exists>\\<^sup>E X))\\<rfloor>\" \n          using A1 A2 by blast\n have T2: \"\\<lfloor>\\<P> \\<G>\\<rfloor>\" by (metis A3 G_def)\n have T3: \"\\<lfloor>\\<^bold>\\<diamond>(\\<^bold>\\<exists>\\<^sup>E \\<G>)\\<rfloor>\" using T1 T2 by simp\n have T4: \"\\<lfloor>\\<^bold>\\<forall>\\<^sup>Ex.((\\<G> x)\\<^bold>\\<rightarrow>(\\<E> \\<G> x))\\<rfloor>\" \n          by (metis A1 A4 G_def E_def)\n have T5: \"\\<lfloor>(\\<^bold>\\<diamond>(\\<^bold>\\<exists>\\<^sup>E\\<G>))\\<^bold>\\<rightarrow> \\<^bold>\\<box>(\\<^bold>\\<exists>\\<^sup>E\\<G>)\\<rfloor>\" \n          by (smt A5 G_def B' NE_def T4)\n thus ?thesis using T3 by blast qed\n\n(*Existence of a Godlike entity*)\nlemma \"\\<lfloor>\\<^bold>\\<exists>\\<^sup>E \\<G>\\<rfloor>\" using A1 A2 B' T6 by blast\n\n(*Consistency*) \nlemma True nitpick[satisfy] oops (*Model found*)\n\n(*Modal collapse: holds*)\nlemma MC: \"\\<lfloor>\\<^bold>\\<forall>\\<Phi>.(\\<Phi> \\<^bold>\\<rightarrow> \\<^bold>\\<box>\\<Phi>)\\<rfloor>\" \nproof - {fix w fix Q\n have 1: \"\\<forall>x.((\\<G> x w) \\<longrightarrow>\n           (\\<^bold>\\<forall>Z.((Z x) \\<^bold>\\<rightarrow> \\<^bold>\\<box>(\\<^bold>\\<forall>\\<^sup>Ez.((\\<G> z) \\<^bold>\\<rightarrow> (Z z))))) w)\" \n         by (metis A1 A4 G_def)\n have 2: \"(\\<exists>x. \\<G> x w)\\<longrightarrow>((Q \\<^bold>\\<rightarrow> \\<^bold>\\<box>(\\<^bold>\\<forall>\\<^sup>Ez.((\\<G> z) \\<^bold>\\<rightarrow> Q))) w)\" \n         using 1 by force\n have 3: \"(Q \\<^bold>\\<rightarrow> \\<^bold>\\<box>Q) w\" using B' T6 2 by blast} \n thus ?thesis by auto qed\n\n(*Analysis of positive properties using ultrafilters*)\ntheorem U1: \"\\<lfloor>UFilter \\<P>\\<rfloor>\" sledgehammer (*Proof found*)\nproof - \n have 1: \"\\<lfloor>(\\<^bold>U\\<^bold>\\<in>\\<P>) \\<^bold>\\<and> \\<^bold>\\<not>(\\<^bold>\\<emptyset>\\<^bold>\\<in>\\<P>)\\<rfloor>\" \n          using A1 A2 by blast\n have 2: \"\\<lfloor>\\<^bold>\\<forall>\\<phi> \\<psi>.(((\\<phi>\\<^bold>\\<in>\\<P>)\\<^bold>\\<and>(\\<phi>\\<^bold>\\<subseteq>\\<psi>))\\<^bold>\\<rightarrow>(\\<psi>\\<^bold>\\<in>\\<P>))\\<rfloor>\" \n         by (smt A2 B' MC)\n have 3: \"\\<lfloor>\\<^bold>\\<forall>\\<phi> \\<psi>.(((\\<phi>\\<^bold>\\<in>\\<P>)\\<^bold>\\<and>(\\<psi>\\<^bold>\\<in>\\<P>))\\<^bold>\\<rightarrow>((\\<phi>\\<^bold>\\<sqinter>\\<psi>)\\<^bold>\\<in>\\<P>))\\<rfloor>\" \n         by (metis A1 A2 G_def B' T6)\n have 4: \"\\<lfloor>\\<^bold>\\<forall>\\<phi>.((\\<phi>\\<^bold>\\<in>\\<P>) \\<^bold>\\<or> ((\\<inverse>\\<phi>)\\<^bold>\\<in>\\<P>))\\<rfloor>\" \n         using A1 by blast\n thus ?thesis using 1 2 3 4 by simp qed\n\nlemma L1: \"\\<lfloor>\\<^bold>\\<forall>X Y.((X\\<Rrightarrow>Y) \\<^bold>\\<rightarrow> (X\\<^bold>\\<sqsubseteq>Y))\\<rfloor>\" \n          by (metis A1 A2 MC)\nlemma L2: \"\\<lfloor>\\<^bold>\\<forall>X Y.(((\\<P> X) \\<^bold>\\<and> (X\\<^bold>\\<sqsubseteq>Y)) \\<^bold>\\<rightarrow> (\\<P> Y))\\<rfloor>\" \n          by (smt A2 B' MC)\n\n(*Set of supersets of X, we call this HF X*)\nabbreviation HF where \"HF X \\<equiv> \\<lambda>Y.(X\\<^bold>\\<sqsubseteq>Y)\"\n\n(*HF \\<G> is a filter; hence, HF \\<G> is Hauptfilter of \\<G>*) \nlemma F1: \"\\<lfloor>Filter (HF \\<G>)\\<rfloor>\" by (metis A2 B' T6 U1)\nlemma F2: \"\\<lfloor>UFilter (HF \\<G>)\\<rfloor>\" by (smt A1 F1 G_def)\n\n(*T6 follows directly from F1*) \ntheorem T6again: \"\\<lfloor>\\<^bold>\\<box>(\\<^bold>\\<exists>\\<^sup>E \\<G>)\\<rfloor>\" using F1 by simp \nend\n\n\n\n\n(*\n(*The simplified version in appendix C is implied*) \nlemma  A1':  \"\\<lfloor>\\<P>(\\<lambda>x. x\\<^bold>=x) \\<^bold>\\<and> \\<^bold>\\<not>\\<P>(\\<lambda>x. x\\<^bold>\\<noteq>x)\\<rfloor>\" using A1 A2 by blast\nlemma A2'': \"\\<lfloor>\\<^bold>\\<forall>X Y. (\\<P> X \\<^bold>\\<and> (X\\<^bold>\\<sqsubseteq>Y)) \\<^bold>\\<rightarrow> \\<P> Y\\<rfloor>\" by (metis A1 A2 B G_def T6)\nlemma T2:   \"\\<lfloor>\\<P> \\<G>\\<rfloor>\" by (metis A3 G_def)\n*)\n\n(*\ntheorem T6again: \"\\<lfloor>\\<^bold>\\<box>(\\<^bold>\\<exists>\\<^sup>E \\<G>)\\<rfloor>\"  \nproof -\n have L1: \"\\<lfloor>(\\<^bold>\\<exists>X. \\<P> X \\<^bold>\\<and> \\<^bold>\\<not>(\\<^bold>\\<exists>\\<^sup>E X)) \\<^bold>\\<rightarrow> \\<P>(\\<lambda>x. x\\<^bold>\\<noteq>x)\\<rfloor>\" \n   by (metis A2 B G_def T6)\n have L2: \"\\<lfloor>\\<^bold>\\<not>(\\<^bold>\\<exists>X. \\<P> X \\<^bold>\\<and> \\<^bold>\\<not>(\\<^bold>\\<exists>\\<^sup>E X))\\<rfloor>\" \n   using A1 A2 L1 by blast \n have T1': \"\\<lfloor>\\<^bold>\\<forall>X. \\<P> X \\<^bold>\\<rightarrow> (\\<^bold>\\<exists>\\<^sup>E X)\\<rfloor>\" by (metis L2)  \n have T3': \"\\<lfloor>\\<^bold>\\<exists>\\<^sup>E \\<G>\\<rfloor>\"\n   by (metis A2 A5 B L2 T6)\n have T3: \"\\<lfloor>\\<^bold>\\<diamond>(\\<^bold>\\<exists>\\<^sup>E \\<G>)\\<rfloor>\" \n   using A1 A2 T3' by blast (*not needed*)\n have T6: \"\\<lfloor>\\<^bold>\\<box>(\\<^bold>\\<exists>\\<^sup>E \\<G>)\\<rfloor>\" by (metis T3') \n thus ?thesis by simp qed\n*)", "meta": {"author": "cbenzmueller", "repo": "LogiKEy", "sha": "5c16bdeb68bf8131e24ba9c8d774d4af663cb2cf", "save_path": "github-repos/isabelle/cbenzmueller-LogiKEy", "path": "github-repos/isabelle/cbenzmueller-LogiKEy/LogiKEy-5c16bdeb68bf8131e24ba9c8d774d4af663cb2cf/Computational-Metaphysics/2020-KR/ScottVariant.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094117351309, "lm_q2_score": 0.7905303211371898, "lm_q1q2_score": 0.7061881761338471}}
{"text": "theory Isar_Induction_Demo\nimports Main\nbegin\n\nsection \"Case distinction and induction\"\n\nsubsection \"Case distinction\"\n\ntext \\<open>Explicit:\\<close>\n\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\"\n  thus ?thesis by simp\nqed\n\ntext \\<open>Implicit:\\<close>\n\nlemma \"length(tl xs) = length xs - 1\"\nproof (cases xs)\nprint_cases\n  case Nil\nthm Nil\n  thus ?thesis by simp\nnext\n  case (Cons y ys)\nthm Cons\n  thus ?thesis by simp\nqed\n\n\nsubsection \\<open>Structural induction for type @{typ nat}\\<close>\n\ntext \\<open>Explicit:\\<close>\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\ntext \\<open>In more detail:\\<close>\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 IH: \"?P n\"\n  have \"\\<Sum>{0..Suc n} = \\<Sum>{0..n} + Suc n\" by simp\n  also have \"\\<dots> = n*(n+1) div 2 + Suc n\" using IH by simp\n  also have \"\\<dots> = (Suc n)*((Suc n)+1) div 2\" by simp\n  finally show \"?P(Suc n)\" .\nqed\n\ntext \\<open>Implicit:\\<close>\n\nlemma \"\\<Sum>{0..n::nat} = n*(n+1) div 2\"\nproof (induction n)\nprint_cases\n  case 0\n  show ?case by simp\nnext\n  case (Suc n)\nthm Suc\n  thus ?case by simp\nqed\n\ntext \\<open>Induction with \\<open>\\<Longrightarrow>\\<close>:\\<close>\n\nlemma split_list: \"x : set xs \\<Longrightarrow> \\<exists>ys zs. xs = ys @ x # zs\"\nproof (induction xs)\n  case Nil thus ?case by simp\nnext\n  case (Cons a xs)\nthm Cons.IH (* Induction hypothesis *)\nthm Cons.prems (* Premises of the step case *)\nthm Cons\n  from Cons.prems have \"x = a \\<or> x : set xs\" by simp\n  thus ?case\n  proof\n    assume \"x = a\"\n    hence \"a#xs = [] @ x # xs\" by simp\n    thus ?thesis by blast\n  next\n    assume \"x : set xs\"\n    then obtain ys zs where \"xs = ys @ x # zs\" using Cons.IH by auto\n    hence \"a#xs = (a#ys) @ x # zs\" by simp\n    thus ?thesis by blast\n  qed\nqed\n\n\nsubsection \"Computation induction\"\n\nfun div2 :: \"nat \\<Rightarrow> nat\" where\n\"div2 0 = 0\" |\n\"div2 (Suc 0) = 0\" |\n\"div2 (Suc(Suc n)) = div2 n + 1\"\n\nlemma \"2 * div2 n \\<le> n\"\nproof(induction n rule: div2.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 \"2 * div2 (Suc(Suc n)) = 2 * div2 n + 2\" by simp\n  also have \"\\<dots> \\<le> n + 2\" using \"3.IH\" by simp\n  also have \"\\<dots> = Suc(Suc n)\" by simp\n  finally show ?case .\nqed\n\ntext \\<open>Note that \\<open>3.IH\\<close> is not a valid name, it needs double quotes: \\<open>\"3.IH\"\\<close>.\\<close>\n\n\nfun sep :: \"'a \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where\n\"sep a (x # y # zs) = x # a # sep a (y # zs)\" |\n\"sep a xs = xs\"\n\nthm sep.simps\n\nlemma \"map f (sep a xs) = sep (f a) (map f xs)\"\nproof (induction a xs rule: sep.induct)\nprint_cases\n  case (1 a x y zs)\n  thus ?case by simp\nnext\n  case (\"2_1\" a)\n  show ?case by simp\nnext\n  case (\"2_2\" a v)\n  show ?case by simp\nqed\n\n\n\nsubsection \"Rule induction\"\n\n\ninductive ev :: \"nat => bool\" where\nev0:  \"ev 0\" |\nevSS:  \"ev n \\<Longrightarrow> ev(Suc(Suc n))\"\n\ndeclare ev.intros [simp]\n\n\nlemma \"ev n \\<Longrightarrow> \\<exists>k. n = 2*k\"\nproof (induction rule: ev.induct)\n  case ev0 show ?case by simp\nnext\n  case evSS thus ?case by arith\nqed\n\n\nlemma \"ev n \\<Longrightarrow> \\<exists>k. n = 2*k\"\nproof (induction rule: ev.induct)\n  case ev0 show ?case by simp\nnext\n  case (evSS m)\nthm evSS\nthm evSS.IH\nthm evSS.hyps\n  from evSS.IH obtain k where \"m = 2*k\" by blast\n  hence \"Suc(Suc m) = 2*(k+1)\" by simp\n  thus \"\\<exists>k. Suc(Suc m) = 2*k\" by blast\nqed\n\n\nsubsection \"Inductive definition of the reflexive transitive closure\"\n\nconsts step :: \"'a \\<Rightarrow> 'a \\<Rightarrow> bool\" (infix \"\\<rightarrow>\" 55)\n\ninductive steps :: \"'a \\<Rightarrow> 'a \\<Rightarrow> bool\" (infix \"\\<rightarrow>*\" 55) where\nrefl: \"x \\<rightarrow>* x\" |\nstep: \"\\<lbrakk> x \\<rightarrow> y; y \\<rightarrow>* z \\<rbrakk> \\<Longrightarrow> x \\<rightarrow>* z\"\n\ndeclare refl[simp, intro]\n\ntext \"Explicit and by hand:\"\n\nlemma \"x \\<rightarrow>* y  \\<Longrightarrow>  y \\<rightarrow>* z \\<Longrightarrow> x \\<rightarrow>* z\"\nproof(induction rule: steps.induct)\n  fix x assume \"x \\<rightarrow>* z\"\n  thus \"x \\<rightarrow>* z\" . (* by assumption *)\nnext\n  fix x' x y :: 'a\n  assume \"x' \\<rightarrow> x\" and \"x \\<rightarrow>* y\"\n  assume IH: \"y \\<rightarrow>* z \\<Longrightarrow> x \\<rightarrow>* z\"\n  assume \"y \\<rightarrow>* z\"\n  show \"x' \\<rightarrow>* z\" by(rule step[OF `x' \\<rightarrow> x` IH[OF `y\\<rightarrow>*z`]])\nqed\n\ntext \\<open>Implicit and automatic:\\<close>\n\nlemma \"x \\<rightarrow>* y  \\<Longrightarrow>  y \\<rightarrow>* z \\<Longrightarrow> x \\<rightarrow>* z\"\nproof(induction rule: steps.induct)\n  case refl thus ?case .\nnext\n  case (step x' x y)\n  (* x' x y not used in proof text, just for demo *)\nthm step\nthm step.IH\nthm step.hyps\nthm step.prems\n  show ?case\n    by (metis step.hyps(1) step.IH step.prems steps.step)\nqed\n\n\nsubsection \"Rule inversion\"\n\n\nlemma assumes \"ev n\" shows \"ev(n - 2)\"\nproof-\n  from `ev n` show \"ev(n - 2)\"\n  proof cases\n    case ev0\nthm ev0\n    then show ?thesis by simp\n  next\n    case (evSS k)\nthm evSS\n    then show ?thesis by simp\n  qed\nqed\n\n\ntext \\<open>Impossible cases are proved automatically:\\<close>\n\nlemma \"\\<not> ev(Suc 0)\"\nproof\n  assume \"ev(Suc 0)\"\n  then show False\n  proof cases\n  qed\nqed\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/Isar_Induction_Demo.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.8933094039240554, "lm_q1q2_score": 0.7061881677547007}}
{"text": "(* Author: Tobias Nipkow *)\n\nsection \"Abstract Interpretation\"\n\nsubsection \"Complete Lattice\"\n\ntheory Complete_Lattice\nimports MainRLT\nbegin\n\nlocale Complete_Lattice =\nfixes L :: \"'a::order set\" and Glb :: \"'a set \\<Rightarrow> 'a\"\nassumes Glb_lower: \"A \\<subseteq> L \\<Longrightarrow> a \\<in> A \\<Longrightarrow> Glb A \\<le> a\"\nand Glb_greatest: \"b \\<in> L \\<Longrightarrow> \\<forall>a\\<in>A. b \\<le> a \\<Longrightarrow> b \\<le> Glb A\"\nand Glb_in_L: \"A \\<subseteq> L \\<Longrightarrow> Glb A \\<in> L\"\nbegin\n\ndefinition lfp :: \"('a \\<Rightarrow> 'a) \\<Rightarrow> 'a\" where\n\"lfp f = Glb {a : L. f a \\<le> a}\"\n\nlemma index_lfp: \"lfp f \\<in> L\"\nby(auto simp: lfp_def intro: Glb_in_L)\n\nlemma lfp_lowerbound:\n  \"\\<lbrakk> a \\<in> L;  f a \\<le> a \\<rbrakk> \\<Longrightarrow> lfp f \\<le> a\"\nby (auto simp add: lfp_def intro: Glb_lower)\n\nlemma lfp_greatest:\n  \"\\<lbrakk> a \\<in> L;  \\<And>u. \\<lbrakk> u \\<in> L; f u \\<le> u\\<rbrakk> \\<Longrightarrow> a \\<le> u \\<rbrakk> \\<Longrightarrow> a \\<le> lfp f\"\nby (auto simp add: lfp_def intro: Glb_greatest)\n\n\n\nend\n\nend\n\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/Complete_Lattice.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8962513731336202, "lm_q2_score": 0.78793120560257, "lm_q1q2_score": 0.7061844249561322}}
{"text": "header {* Conjunctive and Disjunctive Functions *}\n\n(*\n    Author: Viorel Preoteasa\n*)\n\ntheory Conj_Disj\nimports Main\nbegin\n\ntext{*\nThis theory introduces the definitions and some properties for \nconjunctive, disjunctive, universally conjunctive, and universally \ndisjunctive functions.\n*}\n\nlocale conjunctive =\n  fixes inf_b :: \"'b \\<Rightarrow> 'b \\<Rightarrow> 'b\"\n  and inf_c :: \"'c \\<Rightarrow> 'c \\<Rightarrow> 'c\"\n  and times_abc :: \"'a \\<Rightarrow> 'b \\<Rightarrow> 'c\"\nbegin\n\ndefinition\n  \"conjunctive = {x . (\\<forall> y z . times_abc x (inf_b y z) = inf_c (times_abc x y) (times_abc x z))}\"\n\nlemma conjunctiveD: \"x \\<in> conjunctive \\<Longrightarrow> times_abc x (inf_b y z) = inf_c (times_abc x y) (times_abc x z)\"\n  by (simp add: conjunctive_def)\n\nend\n\ninterpretation Apply: conjunctive \"inf::'a::semilattice_inf \\<Rightarrow> 'a \\<Rightarrow> 'a\"\n  \"inf::'b::semilattice_inf \\<Rightarrow> 'b \\<Rightarrow> 'b\" \"\\<lambda> f . f\"\n  done\n\ninterpretation Comp: conjunctive \"inf::('a::lattice \\<Rightarrow> 'a) \\<Rightarrow> ('a \\<Rightarrow> 'a) \\<Rightarrow> ('a \\<Rightarrow> 'a)\" \n  \"inf::('a::lattice \\<Rightarrow> 'a) \\<Rightarrow> ('a \\<Rightarrow> 'a) \\<Rightarrow> ('a \\<Rightarrow> 'a)\" \"(op o)\"\n  done\n\nlemma \"Apply.conjunctive = Comp.conjunctive\"\n  apply (simp add: Apply.conjunctive_def Comp.conjunctive_def)\n  apply safe\n  apply (simp_all add: fun_eq_iff inf_fun_def)\n  apply (drule_tac x = \"\\<lambda> u . y\" in spec)\n  apply (drule_tac x = \"\\<lambda> u . z\" in spec)\n  by simp\n\nlocale disjunctive =\n  fixes sup_b :: \"'b \\<Rightarrow> 'b \\<Rightarrow> 'b\"\n  and sup_c :: \"'c \\<Rightarrow> 'c \\<Rightarrow> 'c\"\n  and times_abc :: \"'a \\<Rightarrow> 'b \\<Rightarrow> 'c\"\nbegin\n\ndefinition\n  \"disjunctive = {x . (\\<forall> y z . times_abc x (sup_b y z) = sup_c (times_abc x y) (times_abc x z))}\"\n\nlemma disjunctiveD: \"x \\<in> disjunctive \\<Longrightarrow> times_abc x (sup_b y z) = sup_c (times_abc x y) (times_abc x z)\"\n  by (simp add: disjunctive_def)\n\nend\n\ninterpretation Apply: disjunctive \"sup::'a::semilattice_sup \\<Rightarrow> 'a \\<Rightarrow> 'a\"\n  \"sup::'b::semilattice_sup \\<Rightarrow> 'b \\<Rightarrow> 'b\" \"\\<lambda> f . f\"\n  done\n\ninterpretation Comp: disjunctive \"sup::('a::lattice \\<Rightarrow> 'a) \\<Rightarrow> ('a \\<Rightarrow> 'a) \\<Rightarrow> ('a \\<Rightarrow> 'a)\" \n  \"sup::('a::lattice \\<Rightarrow> 'a) \\<Rightarrow> ('a \\<Rightarrow> 'a) \\<Rightarrow> ('a \\<Rightarrow> 'a)\" \"(op o)\"\n  done\n\nlemma apply_comp_disjunctive: \"Apply.disjunctive = Comp.disjunctive\"\n  apply (simp add: Apply.disjunctive_def Comp.disjunctive_def)\n  apply safe\n  apply (simp_all add: fun_eq_iff sup_fun_def)\n  apply (drule_tac x = \"\\<lambda> u . y\" in spec)\n  apply (drule_tac x = \"\\<lambda> u . z\" in spec)\n  by simp\n\nlocale Conjunctive =\n  fixes Inf_b :: \"'b set \\<Rightarrow> 'b\"\n  and Inf_c :: \"'c set \\<Rightarrow> 'c\"\n  and times_abc :: \"'a \\<Rightarrow> 'b \\<Rightarrow> 'c\"\nbegin\n\ndefinition\n  \"Conjunctive = {x . (\\<forall> X . times_abc x (Inf_b X) = Inf_c ((times_abc x) ` X) )}\"\nend\n\ninterpretation Apply: Conjunctive Inf Inf \"\\<lambda> f . f\"\n  done\n\ninterpretation Comp: Conjunctive \"Inf::(('a::complete_lattice \\<Rightarrow> 'a) set) \\<Rightarrow> ('a \\<Rightarrow> 'a)\" \n  \"Inf::(('a::complete_lattice \\<Rightarrow> 'a) set) \\<Rightarrow> ('a \\<Rightarrow> 'a)\" \"(op o)\"\n  done\n\nlemma fun_eq: \"x = y \\<Longrightarrow> f x = f y\"\n  by simp\n\nlemma \"Apply.Conjunctive = Comp.Conjunctive\"\n  apply (simp add: Apply.Conjunctive_def Comp.Conjunctive_def)\n  apply safe\n  apply (simp add: fun_eq_iff  Inf_fun_def comp_def image_def)\n  apply (simp only: INF_def)\n  apply safe\n  apply (rule_tac f = Inf in fun_eq)\n  apply auto\n  apply (drule_tac x = \"{x . \\<exists> y \\<in> X . x = (\\<lambda> u . y)}\" in spec)\n  apply (simp add: fun_eq_iff  Inf_fun_def comp_def image_def)\n  apply (drule_tac x = \"bot\" in spec)\n  apply (subgoal_tac \"{y\\<Colon>'a. \\<exists>f . (\\<exists>y \\<in> X. \\<forall>x::'a . f x = y) \\<and> y = f bot} = X \\<and> \n      {y\\<Colon>'a. \\<exists>f. (\\<exists>xa. (\\<exists>y \\<in> X. \\<forall>x\\<Colon>'a. xa x = y) \\<and> \n      (\\<forall>xb\\<Colon>'a. f xb = x (xa xb))) \\<and> y = f bot} = {y\\<Colon>'a. \\<exists>xa\\<Colon>'a\\<in>X. y = x xa}\")\n  apply (simp add: INF_def image_def, safe)\n  apply simp_all\n  apply auto\n  apply (metis (full_types) Collect_const UNIV_I mem_Collect_eq)\n  apply (rule_tac x = \"\\<lambda> u . x xaa\" in exI)\n  by auto\n\nlocale Disjunctive =\n  fixes Sup_b :: \"'b set \\<Rightarrow> 'b\"\n  and Sup_c :: \"'c set \\<Rightarrow> 'c\"\n  and times_abc :: \"'a \\<Rightarrow> 'b \\<Rightarrow> 'c\"\nbegin\n\ndefinition\n  \"Disjunctive = {x . (\\<forall> X . times_abc x (Sup_b X) = Sup_c ((times_abc x) ` X) )}\"\n\nlemma DisjunctiveD: \"x \\<in> Disjunctive \\<Longrightarrow> times_abc x (Sup_b X) = Sup_c ((times_abc x) ` X)\"\n  by (simp add: Disjunctive_def)\n\nend\n\ninterpretation Apply: Disjunctive Sup Sup \"\\<lambda> f . f\"\n  done\n\ninterpretation Comp: Disjunctive \"Sup::(('a::complete_lattice \\<Rightarrow> 'a) set) \\<Rightarrow> ('a \\<Rightarrow> 'a)\" \n  \"Sup::(('a::complete_lattice \\<Rightarrow> 'a) set) \\<Rightarrow> ('a \\<Rightarrow> 'a)\" \"(op o)\"\n  done\n\nlemma apply_comp_Disjunctive: \"Apply.Disjunctive = Comp.Disjunctive\"\n  apply (simp add: Apply.Disjunctive_def Comp.Disjunctive_def)\n  apply safe\n  apply (simp add: fun_eq_iff  Sup_fun_def comp_def image_def)\n  apply (simp only: SUP_def)\n  apply safe\n  apply (rule_tac f = Sup in fun_eq)\n  apply auto\n  apply (drule_tac x = \"{x . \\<exists> y \\<in> X . x = (\\<lambda> u . y)}\" in spec)\n  apply (simp add: fun_eq_iff  Sup_fun_def comp_def image_def)\n  apply (drule_tac x = \"bot\" in spec)\n  apply (subgoal_tac \"{y. \\<exists>f::'a \\<Rightarrow> 'a. (\\<exists>y\\<in>X. \\<forall>x. f x = y) \\<and> y = f bot} = X \n    \\<and> {y. \\<exists>f::'a \\<Rightarrow> 'a. (\\<exists>xa. (\\<exists>y\\<in>X. \\<forall>x. xa x = y) \\<and> (\\<forall>xb. f xb = x (xa xb))) \\<and> y = f bot} = {y. \\<exists>xa\\<in>X. y = x xa}\")\n  apply (simp add: SUP_def image_def, safe)\n  apply auto\n  apply (metis (full_types) Collect_const UNIV_I mem_Collect_eq)\n  apply (rule_tac x = \"\\<lambda> u . x xaa\" in exI)\n  by auto\n\n\n\nlemma [simp]: \"F \\<in> Apply.conjunctive \\<Longrightarrow> mono F\"\n  apply (simp add: Apply.conjunctive_def mono_def)\n  apply safe\n  apply (drule_tac x = \"x\" in spec)\n  apply (drule_tac x = \"y\" in spec)\n  apply (subgoal_tac \"inf x y = x\")\n  apply simp\n  apply (subgoal_tac \"inf (F x) (F y) \\<le> F y\")\n  apply simp\n  apply (rule inf_le2)\n  apply (rule antisym)\n  by simp_all\n\nlemma [simp]: \"(F::'a::complete_lattice \\<Rightarrow> 'b::complete_lattice) \\<in> Apply.Conjunctive \\<Longrightarrow> F top = top\"\n  apply (simp add: Apply.Conjunctive_def)\n  apply (drule_tac x=\"{}\" in spec)\n  by simp\n\nlemma [simp]: \"(F::'a::complete_lattice \\<Rightarrow> 'b::complete_lattice) \\<in> Apply.Disjunctive \\<Longrightarrow> F \\<in> Apply.disjunctive\"\n  apply (simp add: Apply.Disjunctive_def Apply.disjunctive_def)\n  apply safe\n  apply (drule_tac x = \"{y, z}\" in spec)\n  by simp\n\nlemma [simp]: \"F \\<in> Apply.disjunctive \\<Longrightarrow> mono F\"\n  apply (simp add: Apply.disjunctive_def mono_def)\n  apply safe\n  apply (drule_tac x = \"x\" in spec)\n  apply (drule_tac x = \"y\" in spec)\n  apply (subgoal_tac \"sup x y = y\")\n  apply simp\n  apply (subgoal_tac \"F x \\<le> sup (F x) (F y)\")\n  apply simp\n  apply (rule sup_ge1)\n  apply (rule antisym)\n  apply simp\n  by (rule sup_ge2)\n\nlemma [simp]: \"(F::'a::complete_lattice \\<Rightarrow> 'b::complete_lattice) \\<in> Apply.Disjunctive \\<Longrightarrow> F bot = bot\"\n  apply (simp add: Apply.Disjunctive_def)\n  apply (drule_tac x=\"{}\" in spec)\n  by simp\n\nlemma weak_fusion: \"h \\<in> Apply.Disjunctive \\<Longrightarrow> mono f \\<Longrightarrow> mono g \\<Longrightarrow> \n    h o f \\<le> g o h \\<Longrightarrow> h (lfp f) \\<le> lfp g\"\n  apply (rule_tac P = \"\\<lambda> x . h x \\<le> lfp g\" in lfp_ordinal_induct, simp_all)\n  apply (rule_tac y = \"g (h S)\" in order_trans)\n  apply (simp add: le_fun_def)\n  apply (rule_tac y = \"g (lfp g)\" in order_trans)\n  apply (rule_tac f = g in monoD, simp_all)\n  apply (rule lfp_lemma2, simp)\n  apply (simp add: Apply.DisjunctiveD)\n  by (rule SUP_least, blast)\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/LatticeProperties/Conj_Disj.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009549929797, "lm_q2_score": 0.7718434978390746, "lm_q1q2_score": 0.7061603532780912}}
{"text": "theory Permutation\n  imports Main\nbegin\n\n(* Some theorems about permutation were copied from HOL/HOL-NSA-Examples/Permutation *)\ninductive perm :: \"'a list => 'a list => bool\"  (\"_ <~~> _\"  [50, 50] 50) \nwhere\n  Nil [intro!]: \"[] <~~> []\"\n| swap [intro!]: \"y # x # l <~~> x # y # l\"\n| Cons [intro!]: \"xs <~~> ys ==> z # xs <~~> z # ys\"\n| trans [intro]: \"xs <~~> ys ==> ys <~~> zs ==> xs <~~> zs\"\n\nlemma perm_refl [iff]: \"l <~~> l\"\n  by (induct l) auto\n\n\n\nlemma xperm_empty_imp: \"[] <~~> ys ==> ys = []\"\n  by (induct xs == \"[]::'a list\" ys pred: perm) simp_all\n\nlemma perm_length: \"xs <~~> ys ==> length xs = length ys\"\n  by (induct pred: perm) simp_all\n\nlemma perm_sym: \"xs <~~> ys ==> ys <~~> xs\"\n  by (induct pred: perm) auto\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 ==> l @ xs <~~> l @ ys\"\n  by (induct l) auto\n\nlemma perm_append2: \"xs <~~> ys ==> xs @ l <~~> ys @ l\"\n  by (blast intro!: perm_append_swap perm_append1)\n\nlemma perm_swap: \"xs @ y # x # ys <~~> xs @ x # y # ys\"\n  apply (induct xs)\n  by auto\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/HL/Permutation.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.879146780175245, "lm_q2_score": 0.8031738034238806, "lm_q1q2_score": 0.7061076632012098}}
{"text": "\\<^marker>\\<open>creator \"Alexander Krauss\"\\<close>\n\\<^marker>\\<open>creator \"Kevin Kappelmann\"\\<close>\n\\<^marker>\\<open>creator \"Larry Paulson\"\\<close>\nsection \\<open>Union and Intersection\\<close>\ntheory Union_Intersection\n  imports Comprehension\nbegin\n\ndefinition \"inter A \\<equiv> {x \\<in> \\<Union>A | \\<forall>y \\<in> A. x \\<in> y}\"\n\nbundle hotg_inter_syntax begin notation inter (\"\\<Inter>_\" [90] 90) end\nbundle no_hotg_inter_syntax begin no_notation inter (\"\\<Inter>_\" [90] 90) end\nunbundle hotg_inter_syntax\n\ntext \\<open>Intersection is well-behaved only if the family is non-empty!\\<close>\n\nlemma mem_inter_iff [iff]: \"A \\<in> \\<Inter>C \\<longleftrightarrow> C \\<noteq> {} \\<and> (\\<forall>x \\<in> C. A \\<in> x)\"\n  unfolding inter_def by auto\n\n(*LP: A \"destruct\" rule: every B in C contains A as an element, but A \\<in> B can\n  hold when B \\<in> C does not! This rule is analogous to \"spec\".*)\nlemma interD [dest]: \"\\<lbrakk>A \\<in> \\<Inter>C; B \\<in> C\\<rbrakk> \\<Longrightarrow> A \\<in> B\" by auto\n\nlemma union_empty_eq [iff]: \"\\<Union>{} = {}\" by auto\n\nlemma inter_empty_eq [iff]: \"\\<Inter>{} = {}\" by auto\n\nlemma union_eq_empty_iff: \"\\<Union>A = {} \\<longleftrightarrow> A = {} \\<or> A = {{}}\"\nproof\n  assume \"\\<Union>A = {}\"\n  show \"A = {} \\<or> A = {{}}\"\n  proof (rule or_if_not_imp)\n    assume \"A \\<noteq> {}\"\n    then obtain x where \"x \\<in> A\" by auto\n    from \\<open>\\<Union>A = {}\\<close> have [simp]: \"\\<And>x. x \\<in> A \\<Longrightarrow> x = {}\" by auto\n    with \\<open>x \\<in> A\\<close> have \"x = {}\" by simp\n    with \\<open>x \\<in> A\\<close> have [simp]: \"{} \\<in> A\" by simp\n    show \"A = {{}}\" by auto\n  qed\nqed auto\n\nlemma union_eq_empty_iff': \"\\<Union>A = {} \\<longleftrightarrow> (\\<forall>B \\<in> A. B = {})\" by auto\n\nlemma union_singleton_eq [simp]: \"\\<Union>{b} = b\" by auto\n\nlemma inter_singleton_eq [simp]: \"\\<Inter>{b} = b\" by auto\n\nlemma subset_union_if_mem: \"B \\<in> A \\<Longrightarrow> B \\<subseteq> \\<Union>A\" by blast\n\nlemma inter_subset_if_mem: \"B \\<in> A \\<Longrightarrow> \\<Inter>A \\<subseteq> B\" by blast\n\nlemma union_subset_iff: \"\\<Union>A \\<subseteq> C \\<longleftrightarrow> (\\<forall>x \\<in> A. x \\<subseteq> C)\" by blast\n\nlemma subset_inter_iff_all_mem_subset_if_ne_empty:\n  \"A \\<noteq> {} \\<Longrightarrow> C \\<subseteq> \\<Inter>A \\<longleftrightarrow> (\\<forall>x \\<in> A. C \\<subseteq> x)\"\n  by blast\n\nlemma union_subset_if_all_mem_subset: \"(\\<And>x. x \\<in> A \\<Longrightarrow> x \\<subseteq> C) \\<Longrightarrow> \\<Union>A \\<subseteq> C\" by blast\n\nlemma subset_inter_if_all_mem_subset_if_ne_empty:\n  \"\\<lbrakk>A \\<noteq> {}; \\<And>x. x \\<in> A \\<Longrightarrow> C \\<subseteq> x\\<rbrakk> \\<Longrightarrow> C \\<subseteq> \\<Inter>A\"\n  using subset_inter_iff_all_mem_subset_if_ne_empty by auto\n\nlemma mono_union: \"mono union\"\n  by (intro monoI) auto\n\nlemma antimono_inter: \"A \\<noteq> {} \\<Longrightarrow> A \\<subseteq> A' \\<Longrightarrow> \\<Inter>A' \\<subseteq> \\<Inter>A\"\n  by auto\n\n\nsubsection \\<open>Indexed Union and Intersection:\\<close>\n\nbundle hotg_idx_union_inter_syntax\nbegin\nsyntax\n  \"_idx_union\" :: \\<open>[pttrn, set, set \\<Rightarrow> set] => set\\<close> (\"(3\\<Union>_ \\<in> _./ _)\" [0, 0, 10] 10)\n  \"_idx_inter\" :: \\<open>[pttrn, set, set \\<Rightarrow> set] => set\\<close> (\"(3\\<Inter>_ \\<in> _./ _)\" [0, 0, 10] 10)\nend\nbundle no_hotg_idx_union_inter_syntax\nbegin\nno_syntax\n  \"_idx_union\" :: \\<open>[pttrn, set, set \\<Rightarrow> set] => set\\<close> (\"(3\\<Union>_ \\<in> _./ _)\" [0, 0, 10] 10)\n  \"_idx_inter\" :: \\<open>[pttrn, set, set \\<Rightarrow> set] => set\\<close> (\"(3\\<Inter>_ \\<in> _./ _)\" [0, 0, 10] 10)\nend\nunbundle hotg_idx_union_inter_syntax\n\ntranslations\n  \"\\<Union>x \\<in> A. B\" \\<rightleftharpoons> \"\\<Union>{B | x \\<in> A}\"\n  \"\\<Inter>x \\<in> A. B\" \\<rightleftharpoons> \"\\<Inter>{B | x \\<in> A}\"\n\n\nlemma mem_idx_unionE [elim!]:\n  assumes \"b \\<in> (\\<Union>x \\<in> A. B x)\"\n  obtains x where \"x \\<in> A\" and \"b \\<in> B x\"\n  using assms by blast\n\nlemma mem_idx_interD:\n  assumes \"b \\<in> (\\<Inter>x \\<in> A. B x)\" and \"x \\<in> A\"\n  shows \"b \\<in> B x\"\n  using assms by blast\n\nlemma idx_union_cong [cong]:\n  \"\\<lbrakk>A = B; \\<And>x. x \\<in> B \\<Longrightarrow> C x = D x\\<rbrakk> \\<Longrightarrow> (\\<Union>x \\<in> A. C x) = (\\<Union>x \\<in> B. D x)\"\n  by simp\n\nlemma idx_inter_cong [cong]:\n  \"\\<lbrakk>A = B; \\<And>x. x \\<in> B \\<Longrightarrow> C x = D x\\<rbrakk> \\<Longrightarrow> (\\<Inter>x \\<in> A. C x) = (\\<Inter>x \\<in> B. D x)\"\n  by simp\n\nlemma idx_union_const_eq_if_ne_empty: \"A \\<noteq> {} \\<Longrightarrow> (\\<Union>x \\<in> A. B) = B\"\n  by (rule eq_if_subset_if_subset) auto\n\nlemma idx_inter_const_eq_if_ne_empty: \"A \\<noteq> {} \\<Longrightarrow> (\\<Inter>x \\<in> A. B) = B\"\n  by (rule eq_if_subset_if_subset) auto\n\nlemma idx_union_empty_dom_eq [simp]: \"(\\<Union>x \\<in> {}. B x) = {}\" by auto\n\nlemma idx_inter_empty_dom_eq [simp]: \"(\\<Inter>x \\<in> {}. B x) = {}\" by auto\n\nlemma idx_union_empty_eq [simp]: \"(\\<Union>x \\<in> A. {}) = {}\" by auto\n\nlemma idx_inter_empty_eq [simp]: \"(\\<Inter>x \\<in> A. {}) = {}\" by blast\n\nlemma idx_union_eq_union [simp]: \"(\\<Union>x \\<in> A. x) = \\<Union>A\" by auto\n\nlemma idx_inter_eq_inter [simp]: \"(\\<Inter>x \\<in> A. x) = \\<Inter>A\" by auto\n\nlemma idx_union_subset_iff: \"(\\<Union>x \\<in> A. B x) \\<subseteq> C \\<longleftrightarrow> (\\<forall>x \\<in> A. B x \\<subseteq> C)\" by blast\n\nlemma subset_idx_inter_iff_if_ne_empty:\n  \"C \\<noteq> {} \\<Longrightarrow> C \\<subseteq> (\\<Inter>x \\<in> A. B x) \\<longleftrightarrow> (A \\<noteq> {} \\<and> (\\<forall>x \\<in> A. C \\<subseteq> B x))\"\n  by auto\n\nlemma subset_idx_union_if_mem: \"x \\<in> A \\<Longrightarrow> B x \\<subseteq> (\\<Union>x \\<in> A. B x)\" by blast\n\nlemma idx_inter_subset_if_mem: \"x \\<in> A \\<Longrightarrow> (\\<Inter>x \\<in> A. B x) \\<subseteq> B x\" by blast\n\nlemma idx_union_subset_if_all_mem_app_subset:\n  \"(\\<And>x. x \\<in> A \\<Longrightarrow> B x \\<subseteq> C) \\<Longrightarrow> (\\<Union>x \\<in> A. B x) \\<subseteq> C\"\n  by blast\n\nlemma subset_idx_inter_if_all_mem_subset_app_if_ne_empty:\n  \"\\<lbrakk>A \\<noteq> {}; \\<And>x. x \\<in> A \\<Longrightarrow> C \\<subseteq> B x\\<rbrakk> \\<Longrightarrow> C \\<subseteq> (\\<Inter>x \\<in> A. B x)\"\n  by blast\n\nlemma idx_union_singleton_eq [simp]: \"(\\<Union>x \\<in> A. {x}) = A\"\n  by (rule eq_if_subset_if_subset) auto\n\nlemma idx_union_flatten [simp]:\n  \"(\\<Union>x \\<in> (\\<Union>y \\<in> A. B y). C x) = (\\<Union>y \\<in> A. \\<Union>x \\<in> B y. C x)\"\n  by (rule eq_if_subset_if_subset) auto\n\nlemma idx_union_const [simp]: \"(\\<Union>y \\<in> A. c) = (if A = {} then {} else c)\"\n  by (rule eq_if_subset_if_subset) auto\n\nlemma idx_inter_const [simp]: \"(\\<Inter>y \\<in> A. c) = (if A = {} then {} else c)\"\n  by (rule eq_if_subset_if_subset) auto\n\nlemma idx_union_repl [simp]: \"(\\<Union>y \\<in> {f x | x \\<in> A}. B y) = (\\<Union>x \\<in> A. B (f x))\"\n  by (rule eq_if_subset_if_subset) auto\n\nlemma idx_inter_repl [simp]: \"(\\<Inter>x \\<in> {f x | x \\<in> A}. B x) = (\\<Inter>a \\<in> A. B(f a))\"\n  by auto\n\nlemma idx_inter_union_eq_idx_inter_idx_inter:\n  \"{} \\<notin> A \\<Longrightarrow> (\\<Inter>x \\<in> \\<Union>A. B x) = (\\<Inter>y \\<in> A. \\<Inter>x \\<in> y. B x)\"\n  by (auto iff: union_eq_empty_iff)\n\nlemma idx_inter_idx_union_eq_idx_inter_idx_inter:\n  assumes \"\\<And>x. (x \\<in> A \\<Longrightarrow> B x \\<noteq> {})\"\n  shows \"(\\<Inter>z \\<in> (\\<Union>x \\<in> A. B x). C z) = (\\<Inter>x \\<in> A. \\<Inter>z \\<in> B x. C z)\"\nproof (rule eqI)\n  fix x assume \"x \\<in> (\\<Inter>z \\<in> (\\<Union>x \\<in> A. B x). C z)\"\n  with assms show \"x \\<in> (\\<Inter>x \\<in> A. \\<Inter>z \\<in> B x. C z)\" by (auto 5 0)\nnext\n  fix x assume x_mem: \"x \\<in> (\\<Inter>x \\<in> A. \\<Inter>z \\<in> B x. C z)\"\n  then have \"A \\<noteq> {}\" by auto\n  then obtain y where \"y \\<in> A\" by auto\n  with assms have \"B y \\<noteq> {}\" by auto\n  with \\<open>y \\<in> A\\<close> have \"{B x | x \\<in> A} \\<noteq> {{}}\" by auto\n  with x_mem show \"x \\<in> (\\<Inter>z \\<in> (\\<Union>x \\<in> A. B x). C z)\"\n    by (auto simp: union_eq_empty_iff)\nqed\n\nlemma mono_idx_union:\n  assumes \"A \\<subseteq> A'\"\n  and \"\\<And>x. x \\<in> A \\<Longrightarrow> B x \\<subseteq> B' x\"\n  shows \"(\\<Union>x \\<in> A. B x) \\<subseteq> (\\<Union>x \\<in> A'. B' x)\"\n  using assms by auto\n\nlemma mono_antimono_idx_inter:\n  assumes \"A \\<noteq> {}\"\n  and \"A \\<subseteq> A'\"\n  and \"\\<And>x. x \\<in> A \\<Longrightarrow> B' x \\<subseteq> B x\"\n  shows \"(\\<Inter>x \\<in> A'. B' x) \\<subseteq> (\\<Inter>x \\<in> A. B x)\"\n  using assms by (intro subsetI) auto\n\n\nsubsection \\<open>Binary Union and Intersection\\<close>\n\ndefinition \"bin_union A B \\<equiv> \\<Union>{A, B}\"\n\nbundle hotg_bin_union_syntax begin notation bin_union (infixl \"\\<union>\" 70) end\nbundle no_hotg_bin_union_syntax begin no_notation bin_union (infixl \"\\<union>\" 70) end\nunbundle hotg_bin_union_syntax\n\ndefinition \"bin_inter A B \\<equiv> \\<Inter>{A, B}\"\n\nbundle hotg_bin_inter_syntax begin notation bin_inter (infixl \"\\<inter>\" 70) end\nbundle no_hotg_bin_inter_syntax begin no_notation bin_inter (infixl \"\\<inter>\" 70) end\nunbundle hotg_bin_inter_syntax\n\nlemma mem_bin_union_iff [iff]: \"x \\<in> A \\<union> B \\<longleftrightarrow> x \\<in> A \\<or> x \\<in> B\"\n  unfolding bin_union_def by auto\n\nlemma mem_bin_inter_iff [iff]: \"x \\<in> A \\<inter> B \\<longleftrightarrow> x \\<in> A \\<and> x \\<in> B\"\n  unfolding bin_inter_def by auto\n\n\nparagraph\\<open>Binary Union\\<close>\n\nlemma mem_bin_union_if_mem_left [elim?]: \"c \\<in> A \\<Longrightarrow> c \\<in> A \\<union> B\"\n  by simp\n\nlemma mem_bin_union_if_mem_right [elim?]: \"c \\<in> B \\<Longrightarrow> c \\<in> A \\<union> B\"\n  by simp\n\nlemma bin_unionE [elim!]:\n  assumes \"c \\<in> A \\<union> B\"\n  obtains (mem_left) \"c \\<in> A\" | (mem_right) \"c \\<in> B\"\n  using assms by auto\n\n(*stronger version of above rule*)\nlemma bin_unionE' [elim!]:\n  assumes \"c \\<in> A \\<union> B\"\n  obtains (mem_left) \"c \\<in> A\" | (mem_right) \"c \\<in> B\" and \"c \\<notin> A\"\n  using assms by auto\n\n(*LP: Classical introduction rule: no commitment to A vs B*)\nlemma mem_bin_union_if_mem_if_not_mem: \"(c \\<notin> B \\<Longrightarrow> c \\<in> A) \\<Longrightarrow> c \\<in> A \\<union> B\"\n  by auto\n\nlemma bin_union_comm: \"A \\<union> B = B \\<union> A\"\n  by (rule eq_if_subset_if_subset) auto\n\nlemma bin_union_assoc: \"(A \\<union> B) \\<union> C = A \\<union> (B \\<union> C)\"\n  by (rule eq_if_subset_if_subset) auto\n\nlemma bin_union_comm_left: \"A \\<union> (B \\<union> C) = B \\<union> (A \\<union> C)\" by auto\n\nlemmas bin_union_AC_rules = bin_union_comm bin_union_assoc bin_union_comm_left\n\nlemma empty_bin_union_eq [iff]: \"{} \\<union> A = A\"\n  by (rule eq_if_subset_if_subset) auto\n\nlemma bin_union_empty_eq [iff]: \"A \\<union> {} = A\"\n  by (rule eq_if_subset_if_subset) auto\n\nlemma singleton_bin_union_absorb [simp]: \"a \\<in> A \\<Longrightarrow> {a} \\<union> A = A\"\n  by auto\n\nlemma singleton_bin_union_eq_insert: \"{x} \\<union> A = insert x A\"\n  by (rule eq_if_subset_if_subset) auto\n\nlemma bin_union_singleton_eq_insert: \"A \\<union> {x} = insert x A\"\n  using singleton_bin_union_eq_insert by (subst bin_union_comm)\n\nlemma mem_singleton_bin_union [iff]: \"a \\<in> {a} \\<union> B\" by auto\n\nlemma mem_bin_union_singleton [iff]: \"b \\<in> A \\<union> {b}\" by auto\n\nlemma bin_union_subset_iff [iff]: \"A \\<union> B \\<subseteq> C \\<longleftrightarrow> A \\<subseteq> C \\<and> B \\<subseteq> C\"\n  by blast\n\nlemma bin_union_eq_left_iff [iff]: \"A \\<union> B = A \\<longleftrightarrow> B \\<subseteq> A\"\n  using mem_bin_union_if_mem_right[of _ B A] by (auto simp only: sym[of \"A \\<union> B\"])\n\nlemma bin_union_eq_right_iff [iff]: \"A \\<union> B = B \\<longleftrightarrow> A \\<subseteq> B\"\n  by (subst bin_union_comm) (fact bin_union_eq_left_iff)\n\nlemma subset_bin_union_left: \"A \\<subseteq> A \\<union> B\" by blast\n\nlemma subset_bin_union_right: \"B \\<subseteq> A \\<union> B\"\n  by (subst bin_union_comm) (fact subset_bin_union_left)\n\nlemma bin_union_subset_if_subset_if_subset: \"\\<lbrakk>A \\<subseteq> C; B \\<subseteq> C\\<rbrakk> \\<Longrightarrow> A \\<union> B \\<subseteq> C\"\n  by blast\n\nlemma bin_union_self_eq_self [simp]: \"A \\<union> A = A\"\n  by (rule eq_if_subset_if_subset) auto\n\nlemma bin_union_absorb: \"A \\<union> (A \\<union> B) = A \\<union> B\"\n  by (rule eq_if_subset_if_subset) auto\n\nlemma bin_union_eq_right_if_subset: \"A \\<subseteq> B \\<Longrightarrow> A \\<union> B = B\"\n  by (rule eq_if_subset_if_subset) auto\n\nlemma bin_union_eq_left_if_subset: \"B \\<subseteq> A \\<Longrightarrow> A \\<union> B = A\"\n  by (rule eq_if_subset_if_subset) auto\n\nlemma bin_union_subset_bin_union_if_subset: \"B \\<subseteq> C \\<Longrightarrow> A \\<union> B \\<subseteq> A \\<union> C\"\n  by auto\n\nlemma bin_union_subset_bin_union_if_subset': \"A \\<subseteq> B \\<Longrightarrow> A \\<union> C \\<subseteq> B \\<union> C\"\n  by auto\n\nlemma bin_union_eq_empty_iff [iff]: \"(A \\<union> B = {}) \\<longleftrightarrow> (A = {} \\<and> B = {})\"\n  by auto\n\nlemma mono_bin_union_left: \"mono (\\<lambda>A. A \\<union> B)\"\n  by (intro monoI) auto\n\nlemma mono_bin_union_right: \"mono (\\<lambda>B. A \\<union> B)\"\n  by (intro monoI) auto\n\n\nparagraph \\<open>Binary Intersection\\<close>\n\nlemma mem_bin_inter_if_mem_if_mem [intro!]: \"\\<lbrakk>c \\<in> A; c \\<in> B\\<rbrakk> \\<Longrightarrow> c \\<in> A \\<inter> B\"\n  by simp\n\nlemma mem_bin_inter_if_mem_left: \"c \\<in> A \\<inter> B \\<Longrightarrow> c \\<in> A\"\n  by simp\n\nlemma mem_bin_inter_if_mem_right: \"c \\<in> A \\<inter> B \\<Longrightarrow> c \\<in> B\"\n  by simp\n\nlemma mem_bin_interE [elim!]:\n  assumes \"c \\<in> A \\<inter> B\"\n  obtains \"c \\<in> A\" and \"c \\<in> B\"\n  using assms by simp\n\nlemma bin_inter_empty_iff [iff]: \"A \\<inter> B = {} \\<longleftrightarrow> (\\<forall>a \\<in> A. a \\<notin> B)\"\n  by auto\n\nlemma bin_inter_comm: \"A \\<inter> B = B \\<inter> A\"\n  by auto\n\nlemma bin_inter_assoc: \"(A \\<inter> B) \\<inter> C = A \\<inter> (B \\<inter> C)\"\n  by auto\n\nlemma bin_inter_comm_left: \"A \\<inter> (B \\<inter> C) = B \\<inter> (A \\<inter> C)\"\n  by auto\n\nlemmas bin_inter_AC_rules = bin_inter_comm bin_inter_assoc bin_inter_comm_left\n\nlemma empty_bin_inter_eq_empty [iff]: \"{} \\<inter> B = {}\"\n  by auto\n\nlemma bin_inter_empty_eq_empty [iff]: \"A \\<inter> {} = {}\"\n  by auto\n\nlemma bin_inter_subset_iff [iff]: \"C \\<subseteq> A \\<inter> B \\<longleftrightarrow> C \\<subseteq> A \\<and> C \\<subseteq> B\"\n  by blast\n\nlemma bin_inter_subset_left [iff]: \"A \\<inter> B \\<subseteq> A\"\n  by blast\n\nlemma bin_inter_subset_right [iff]: \"A \\<inter> B \\<subseteq> B\"\n  by blast\n\nlemma subset_bin_inter_if_subset_if_subset: \"\\<lbrakk>C \\<subseteq> A; C \\<subseteq> B\\<rbrakk> \\<Longrightarrow> C \\<subseteq> A \\<inter> B\"\n  by blast\n\nlemma bin_inter_self_eq_self [iff]: \"A \\<inter> A = A\"\n  by (rule eq_if_subset_if_subset) auto\n\nlemma bin_inter_absorb [iff]: \"A \\<inter> (A \\<inter> B) = A \\<inter> B\"\n  by (rule eq_if_subset_if_subset) auto\n\nlemma bin_inter_eq_right_if_subset: \"B \\<subseteq> A \\<Longrightarrow> A \\<inter> B = B\"\n  by (rule eq_if_subset_if_subset) auto\n\nlemma bin_inter_eq_left_if_subset: \"A \\<subseteq> B \\<Longrightarrow> A \\<inter> B = A\"\n  by (subst bin_inter_comm) (fact bin_inter_eq_right_if_subset)\n\nlemma bin_inter_bin_union_distrib: \"(A \\<inter> B) \\<union> C = (A \\<union> C) \\<inter> (B \\<union> C)\"\n  by (rule eq_if_subset_if_subset) auto\n\nlemma bin_inter_bin_union_distrib': \"A \\<inter> (B \\<union> C) = (A \\<inter> B) \\<union> (A \\<inter> C)\"\n  by (rule eq_if_subset_if_subset) auto\n\nlemma bin_union_bin_inter_distrib: \"(A \\<union> B) \\<inter> C = (A \\<inter> C) \\<union> (B \\<inter> C)\"\n  by (rule eq_if_subset_if_subset) auto\n\nlemma bin_union_bin_inter_distrib': \"A \\<union> (B \\<inter> C) = (A \\<union> B) \\<inter> (A \\<union> C)\"\n  by (rule eq_if_subset_if_subset) auto\n\nlemma bin_inter_eq_left_iff_subset: \"A \\<subseteq> B \\<longleftrightarrow> A \\<inter> B = A\"\n  by auto\n\nlemma bin_inter_eq_right_iff_subset: \"A \\<subseteq> B \\<longleftrightarrow> B \\<inter> A = A\"\n  by auto\n\nlemma bin_inter_bin_union_assoc_iff:\n  \"(A \\<inter> B) \\<union> C = A \\<inter> (B \\<union> C) \\<longleftrightarrow> C \\<subseteq> A\"\n  by auto\n\nlemma bin_inter_bin_union_swap3:\n \"(A \\<inter> B) \\<union> (B \\<inter> C) \\<union> (C \\<inter> A) = (A \\<union> B) \\<inter> (B \\<union> C) \\<inter> (C \\<union> A)\"\n  by auto\n\nlemma mono_bin_inter_left: \"mono (\\<lambda>A. A \\<inter> B)\"\n  by (intro monoI) auto\n\nlemma mono_bin_inter_right: \"mono (\\<lambda>B. A \\<inter> B)\"\n  by (intro monoI) auto\n\n\nparagraph\\<open>Comprehension\\<close>\n\nlemma collect_eq_bin_inter [simp]: \"{a \\<in> A | a \\<in> A'} = A \\<inter> A'\" by auto\n\nlemma collect_bin_union_eq:\n  \"{x \\<in> A \\<union> B | P x} = {x \\<in> A | P x} \\<union> {x \\<in> B | P x}\"\n  by (rule eq_if_subset_if_subset) auto\n\nlemma collect_bin_inter_eq:\n  \"{x \\<in> A \\<inter> B | P x} = {x \\<in> A | P x} \\<inter> {x \\<in> B | P x}\"\n  by (rule eq_if_subset_if_subset) auto\n\nlemma bin_inter_collect_absorb [iff]:\n  \"A \\<inter> {x \\<in> A | P x} = {x \\<in> A | P x}\"\n  by (rule eq_if_subset_if_subset) auto\n\nlemma collect_idx_union_eq_union_collect [simp]:\n  \"{y \\<in> (\\<Union>x \\<in> A. B x) | P y} = (\\<Union>x \\<in> A. {y \\<in> B x | P y})\"\n  by (rule eq_if_subset_if_subset) auto\n\nlemma bin_inter_collect_left_eq_collect:\n  \"{x \\<in> A | P x} \\<inter> B = {x \\<in> A \\<inter> B | P x}\"\n  by (rule eq_if_subset_if_subset) auto\n\nlemma bin_inter_collect_right_eq_collect:\n  \"A \\<inter> {x \\<in> B | P x} = {x \\<in> A \\<inter> B | P x}\"\n  by (rule eq_if_subset_if_subset) auto\n\nlemma collect_and_eq_inter_collect:\n  \"{x \\<in> A | P x \\<and> Q x} = {x \\<in> A | P x} \\<inter> {x \\<in> A | Q x}\"\n  by (rule eq_if_subset_if_subset) auto\n\nlemma collect_or_eq_union_collect:\n  \"{x \\<in> A | P x \\<or> Q x} = {x \\<in> A | P x} \\<union> {x \\<in> A | Q x}\"\n  by (rule eq_if_subset_if_subset) auto\n\nlemma union_bin_union_eq_bin_union_union: \"\\<Union>(A \\<union> B) = \\<Union>A \\<union> \\<Union>B\"\n  by (rule eq_if_subset_if_subset) auto\n\nlemma union_bin_inter_subset_bin_inter_union: \"\\<Union>(A \\<inter> B) \\<subseteq> \\<Union>A \\<inter> \\<Union>B\"\n  by blast\n\nlemma union__disjoint_iff: \"\\<Union>C \\<inter> A = {} \\<longleftrightarrow> (\\<forall>B \\<in> C. B \\<inter> A = {})\"\n  by blast\n\nlemma subset_idx_union_iff_eq:\n  \"A \\<subseteq> (\\<Union>i \\<in> I. B i) \\<longleftrightarrow> A = (\\<Union>i \\<in> I. A \\<inter> B i)\" (is \"A \\<subseteq> ?lhs_union \\<longleftrightarrow> A = ?rhs_union\")\nproof\n  assume A_eq: \"A = ?rhs_union\"\n  show \"A \\<subseteq> ?lhs_union\"\n  proof (rule subsetI)\n    fix a assume \"a \\<in> A\"\n    with A_eq have \"a \\<in> ?rhs_union\" by simp\n    then obtain x where \"x \\<in> I\" and \"a \\<in> A \\<inter> B x\" by auto\n    then show \"a \\<in> ?lhs_union\" by auto\n  qed\nqed (auto 5 0 intro!: eqI)\n\nlemma bin_inter_union_eq_idx_union_inter: \"\\<Union>B \\<inter> A = (\\<Union>C \\<in> B. C \\<inter> A)\"\n  by (rule eq_if_subset_if_subset) auto\n\nlemma bin_union_inter_subset_inter_bin_inter:\n  \"\\<lbrakk>z \\<in> A; z \\<in> B\\<rbrakk> \\<Longrightarrow> \\<Inter>A \\<union> \\<Inter>B \\<subseteq> \\<Inter>(A \\<inter> B)\"\n  by blast\n\nlemma inter_bin_union_eq_bin_inter_inter:\n  \"\\<lbrakk>A \\<noteq> {}; B \\<noteq> {}\\<rbrakk> \\<Longrightarrow> \\<Inter>(A \\<union> B) = \\<Inter>A \\<inter> \\<Inter>B\"\n  by (rule eq_if_subset_if_subset) auto\n\nlemma idx_union_bin_union_dom_eq_bin_union_idx_union:\n  \"(\\<Union>i \\<in> A \\<union> B. C i) = (\\<Union>i \\<in> A. C i) \\<union> (\\<Union>i \\<in> B. C i)\"\n  by (rule eq_if_subset_if_subset) auto\n\nlemma idx_inter_bin_inter_dom_eq_bin_inter_idx_inter:\n  \"(\\<Inter>i \\<in> I \\<union> J. A i) = (\n    if I = {} then \\<Inter>j \\<in> J. A j\n    else if J = {} then \\<Inter>i \\<in> I. A i\n    else (\\<Inter>i \\<in> I. A i) \\<inter> (\\<Inter>j \\<in> J. A j)\n  )\"\n  by (rule eq_if_subset_if_subset) auto\n\n(*Halmos, Naive Set Theory, page 35*)\nlemma bin_inter_idx_union_eq_union_bin_inter:\n  \"B \\<inter> (\\<Union>i \\<in> I. A i) = (\\<Union>i \\<in> I. B \\<inter> A i)\"\n  by (rule eq_if_subset_if_subset) auto\n\nlemma bin_union_idx_inter_eq_inter_bin_union:\n  \"I \\<noteq> {} \\<Longrightarrow> B \\<union> (\\<Inter>i \\<in> I. A i) = (\\<Inter>i \\<in> I. B \\<union> A i)\"\n  by (rule eq_if_subset_if_subset) auto\n\nlemma bin_inter_idx_union_eq_idx_union_bin_inter:\n  \"(\\<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 (rule eq_if_subset_if_subset) auto\n\nlemma bin_union_idx_inter_eq_idx_inter_bin_union:\n  \"\\<lbrakk>I \\<noteq> {}; J \\<noteq> {}\\<rbrakk> \\<Longrightarrow>\n    (\\<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 (rule eq_if_subset_if_subset) auto\n\nlemma idx_union_bin_union_eq_bin_union_idx_union:\n  \"(\\<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 eq_if_subset_if_subset) auto\n\nlemma idx_inter_bin_inter_eq_bin_inter_idx_inter:\n  \"I \\<noteq> {} \\<Longrightarrow> (\\<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 eq_if_subset_if_subset) auto\n\nlemma idx_union_bin_inter_subset_bin_inter_idx_union:\n  \"(\\<Union>z \\<in> I \\<inter> J. A z) \\<subseteq> (\\<Union>z \\<in> I. A z) \\<inter> (\\<Union>z \\<in> J. A z)\"\n  by blast\n\n\nend", "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/HOTG/Union_Intersection.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8031738057795403, "lm_q2_score": 0.8791467770088163, "lm_q1q2_score": 0.7061076627289878}}
{"text": "theory ATC\nimports \"../FSM/FSM\"\nbegin\n\nsection \\<open> Adaptive test cases \\<close>\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>\\<open>\"hierons\"\\<close> 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 \\<open> Properties of ATC-reactions \\<close>\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 \\<open> Applicability \\<close>\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 \\<open> Application function IO \\<close>\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, opaque_lifting) 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 \\<open> R-distinguishability \\<close>\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 \\<open> Response sets \\<close>\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 \\<open> Characterizing sets \\<close>\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 \\<open> Reduction over ATCs \\<close>\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 \\<open> Reduction over ATCs applied after input sequences \\<close>\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, opaque_lifting) 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": "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/Adaptive_State_Counting/ATC/ATC.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8791467801752451, "lm_q2_score": 0.8031737892899222, "lm_q1q2_score": 0.7061076507753858}}
{"text": "theory Exercises2_07\n  imports Main\nbegin\n\n(*---------------- Exercise 2.7----------------*)\ndatatype 'a tree2 = Leaf 'a | Node \"'a tree2\" 'a \"'a tree2\"\n\n(* mirror function *)\nfun mirror :: \"'a tree2 \\<Rightarrow> 'a tree2\" where\n\"mirror (Leaf a) = Leaf a\" |\n\"mirror (Node l a r) = Node (mirror r) a (mirror l)\"\n\n(* pre-order function *)\nfun pre_order :: \"'a tree2 \\<Rightarrow> 'a list\" where\n\"pre_order (Leaf a) = [a]\" |\n\"pre_order (Node l a r) = [a]@(pre_order l)@(pre_order r)\"\n\n(* post-order function *)\nfun post_order :: \"'a tree2 \\<Rightarrow> 'a list\" where\n\"post_order (Leaf a) = [a]\" |\n\"post_order (Node l a r) = (post_order l)@(post_order r)@[a]\"\n\ntheorem pre_post : \"pre_order (mirror t) = rev (post_order t)\"\n  apply(induction t)\n  apply(auto)\n  done\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_07.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8791467675095294, "lm_q2_score": 0.8031737987125612, "lm_q1q2_score": 0.7061076488864976}}
{"text": "section \"Stack Proofs\"\n\ntheory Stack_Proof\nimports Stack Util\nbegin\n\nlemma push_list [simp]: \"list (push x stack) = x # list stack\"\n  by(cases stack) auto\n\nlemma pop_list [simp]: \"\\<not> is_empty stack \\<Longrightarrow> list (pop stack) = tl (list stack)\"\n  by(induction stack rule: pop.induct) auto\n\nlemma first_list [simp]: \"\\<not> is_empty stack \\<Longrightarrow> first stack = hd (list stack)\"\n  by(induction stack rule: first.induct) auto\n\nlemma list_empty: \"list stack = [] \\<longleftrightarrow> is_empty stack\"\n  by(induction stack rule: is_empty_stack.induct) auto\n\nlemma list_not_empty: \"list stack  \\<noteq> [] \\<longleftrightarrow> \\<not> is_empty stack\"\n  by(induction stack rule: is_empty_stack.induct) auto \n\nlemma list_empty_2 [simp]: \"\\<lbrakk>list stack \\<noteq> []; is_empty stack\\<rbrakk> \\<Longrightarrow> False\"\n  by (simp add: list_empty)\n\nlemma list_not_empty_2 [simp]:\"\\<lbrakk>list stack = []; \\<not> is_empty stack\\<rbrakk> \\<Longrightarrow> False\"\n  by (simp add: list_empty)\n\nlemma list_empty_size: \"list stack = [] \\<longleftrightarrow> size stack = 0\"\n  by(induction stack) auto \n\nlemma list_not_empty_size:\"list stack \\<noteq> [] \\<longleftrightarrow> 0 < size stack\"\n  by(induction stack) auto\n\nlemma list_empty_size_2 [simp]: \"\\<lbrakk>list stack \\<noteq> []; size stack = 0\\<rbrakk> \\<Longrightarrow> False\"\n  by (simp add: list_empty_size) \n\nlemma list_not_empty_size_2 [simp]:\"\\<lbrakk>list stack = []; 0 < size stack\\<rbrakk> \\<Longrightarrow> False\"\n  by (simp add: list_empty_size)\n\nlemma size_push [simp]: \"size (push x stack) = Suc (size stack)\"\n  by(cases stack) auto\n\nlemma size_pop [simp]: \"size (pop stack) = size stack - Suc 0\"\n  by(induction stack rule: pop.induct) auto\n\nlemma size_empty: \"size (stack :: 'a stack) = 0 \\<longleftrightarrow> is_empty stack\"\n  by(induction stack rule: is_empty_stack.induct) auto\n\nlemma size_not_empty: \"size (stack :: 'a stack) > 0 \\<longleftrightarrow> \\<not> is_empty stack\"\n  by(induction stack rule: is_empty_stack.induct) auto\n\nlemma size_empty_2[simp]: \"\\<lbrakk>size (stack :: 'a stack) = 0; \\<not>is_empty stack\\<rbrakk> \\<Longrightarrow> False\"\n  by (simp add: size_empty)\n\nlemma size_not_empty_2[simp]: \"\\<lbrakk>0 < size (stack :: 'a stack); is_empty stack\\<rbrakk> \\<Longrightarrow> False\"\n  by (simp add: size_not_empty)\n\nlemma size_list_length [simp]: \"length (list stack) = size stack\"\n  by(cases stack) auto\n\nlemma first_pop [simp]: \"\\<not> is_empty stack \\<Longrightarrow> first stack # list (pop stack) = list stack\"\n  by(induction stack rule: pop.induct) auto\n\nlemma push_not_empty [simp]: \"\\<lbrakk>\\<not> is_empty stack; is_empty (push x stack)\\<rbrakk> \\<Longrightarrow> False\"\n  by(induction x stack rule: push.induct) auto\n\nlemma pop_list_length [simp]: \"\\<not> is_empty stack\n   \\<Longrightarrow> Suc (length (list (pop stack))) = length (list stack)\"\n  by(induction stack rule: pop.induct) auto\n\nlemma first_take: \"\\<not>is_empty stack \\<Longrightarrow> [first stack] = take 1 (Stack.list stack)\"\n  by (simp add: list_empty)\n\nlemma first_take_tl [simp]: \"0 < size big\n   \\<Longrightarrow> (first big # take count (tl (list big))) = take (Suc count) (list big)\"\n  by(induction big rule: Stack.first.induct) auto\n\nlemma first_take_pop [simp]: \"\\<lbrakk>\\<not>is_empty stack; 0 < x\\<rbrakk>\n   \\<Longrightarrow> first stack # take (x - Suc 0) (list (pop stack)) = take x (list stack)\"\n  by(induction stack rule: pop.induct) (auto simp: take_Cons')\n\n\n\nlemma first_hd: \"Stack.first stack = hd (Stack.list stack)\"\n  by(induction stack rule: first.induct)(auto simp: hd_def)\n\nlemma pop_tl [simp]: \"list (pop stack) = tl (list stack)\" \n  by(induction stack rule: pop.induct) auto\n\nlemma pop_drop: \"list (pop stack) = drop 1 (list stack)\" \n  by (simp add: drop_Suc)\n\nlemma popN_drop [simp]: \"list ((pop ^^ n) stack) = drop n (list stack)\" \n  by(induction n)(auto simp: drop_Suc tl_drop)\n\nlemma popN_size [simp]: \"size ((pop ^^ n) stack) = (size stack) - n\"\n by(induction n) auto\n\nlemma take_first: \"\\<lbrakk>0 < size s1; 0 < size s2; take (size s1) (list s2) = take (size s2) (list s1)\\<rbrakk>\n    \\<Longrightarrow> first s1 = first s2\"\n  by(induction s1 rule: first.induct; induction s2 rule: first.induct) auto\n\nend", "meta": {"author": "balazstothofficial", "repo": "Real-Time-Deque", "sha": "f43e0337347cee0519e6b8a38299f987871103f4", "save_path": "github-repos/isabelle/balazstothofficial-Real-Time-Deque", "path": "github-repos/isabelle/balazstothofficial-Real-Time-Deque/Real-Time-Deque-f43e0337347cee0519e6b8a38299f987871103f4/Stack_Proof.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942261220291, "lm_q2_score": 0.7931059487389966, "lm_q1q2_score": 0.7060976468653627}}
{"text": "(* Title: Design_Isomorphisms\n   Author: Chelsea Edmonds \n*)\n\nsection \\<open>Design Isomorphisms\\<close>\n\ntheory Design_Isomorphisms imports Design_Basics Sub_Designs\nbegin\n\nsubsection \\<open>Images of Set Systems\\<close>\n\ntext \\<open>We loosely define the concept of taking the \"image\" of a set system, as done in isomorphisms. \nNote that this is not based off mathematical theory, but is for ease of notation\\<close>\ndefinition blocks_image :: \"'a set multiset \\<Rightarrow> ('a \\<Rightarrow> 'b) \\<Rightarrow> 'b set multiset\" where\n\"blocks_image B f \\<equiv> image_mset ((`) f) B\"\n\nlemma image_block_set_constant_size: \"size (B) = size (blocks_image B f)\"\n  by (simp add: blocks_image_def)\n\nlemma (in incidence_system) image_set_system_wellformed: \n  \"incidence_system (f ` \\<V>) (blocks_image \\<B> f)\"\n  by (unfold_locales, auto simp add: blocks_image_def) (meson image_eqI wf_invalid_point)\n\nlemma (in finite_incidence_system) image_set_system_finite: \n  \"finite_incidence_system (f ` \\<V>) (blocks_image \\<B> f)\"\n  using image_set_system_wellformed finite_sets \n  by (intro_locales) (simp_all add: blocks_image_def finite_incidence_system_axioms.intro)\n\nsubsection \\<open>Incidence System Isomorphisms\\<close>\n\ntext \\<open>Isomorphism's are defined by the Handbook of Combinatorial Designs \n\\<^cite>\\<open>\"colbournHandbookCombinatorialDesigns2007\"\\<close>\\<close>\n\nlocale incidence_system_isomorphism = source: incidence_system \\<V> \\<B> + target: incidence_system \\<V>' \\<B>'\n  for \"\\<V>\" and \"\\<B>\" and \"\\<V>'\" and \"\\<B>'\" + fixes bij_map (\"\\<pi>\")\n  assumes bij: \"bij_betw \\<pi> \\<V> \\<V>'\"\n  assumes block_img: \"image_mset ((`) \\<pi>) \\<B> = \\<B>'\"\nbegin\n\nlemma iso_eq_order: \"card \\<V> = card \\<V>'\"\n  using bij bij_betw_same_card by auto\n\nlemma iso_eq_block_num: \"size \\<B> = size \\<B>'\"\n  using block_img by (metis size_image_mset) \n\nlemma iso_block_img_alt_rep: \"{# \\<pi> ` bl . bl \\<in># \\<B>#} = \\<B>'\"\n  using block_img by simp\n\nlemma inv_iso_block_img: \"image_mset ((`) (inv_into \\<V> \\<pi>)) \\<B>' = \\<B>\"\nproof - \n  have \"\\<And> x. x \\<in> \\<V> \\<Longrightarrow> ((inv_into \\<V> \\<pi>) \\<circ> \\<pi>) x = x\"\n    using bij bij_betw_inv_into_left comp_apply by fastforce  \n  then have \"\\<And> bl x . bl \\<in># \\<B> \\<Longrightarrow> x \\<in> bl  \\<Longrightarrow> ((inv_into \\<V> \\<pi>) \\<circ> \\<pi>) x = x\" \n    using source.wellformed by blast\n  then have img: \"\\<And> bl . bl \\<in># \\<B> \\<Longrightarrow> image ((inv_into \\<V> \\<pi>) \\<circ> \\<pi>) bl = bl\"\n    by simp \n  have \"image_mset ((`) (inv_into \\<V> \\<pi>)) \\<B>' = image_mset ((`) (inv_into \\<V> \\<pi>)) (image_mset ((`) \\<pi>) \\<B>)\" \n    using block_img by simp\n  then have \"image_mset ((`) (inv_into \\<V> \\<pi>)) \\<B>' = image_mset ((`) ((inv_into \\<V> \\<pi>) \\<circ> \\<pi>)) \\<B>\" \n    by (metis (no_types, opaque_lifting) block_img comp_apply image_comp multiset.map_comp multiset.map_cong0)\n  thus ?thesis using img by simp\nqed\n\nlemma inverse_incidence_sys_iso: \"incidence_system_isomorphism \\<V>' \\<B>' \\<V> \\<B> (inv_into \\<V> \\<pi>)\"\n  using bij bij_betw_inv_into inv_iso_block_img by (unfold_locales) simp\n\nlemma iso_points_map: \"\\<pi> ` \\<V> = \\<V>'\"\n  using bij by (simp add: bij_betw_imp_surj_on)\n\nlemma iso_points_inv_map: \"(inv_into \\<V> \\<pi>) `  \\<V>' = \\<V>\"\n  using incidence_system_isomorphism.iso_points_map inverse_incidence_sys_iso by blast\n\nlemma iso_points_ss_card: \n  assumes \"ps \\<subseteq> \\<V>\"\n  shows \"card ps = card (\\<pi> ` ps)\"\n  using assms bij bij_betw_same_card bij_betw_subset by blast\n\nlemma iso_block_in: \"bl \\<in># \\<B> \\<Longrightarrow> (\\<pi> ` bl) \\<in># \\<B>'\"\n  using iso_block_img_alt_rep\n  by (metis image_eqI in_image_mset)\n\nlemma iso_inv_block_in: \"x \\<in># \\<B>' \\<Longrightarrow> x \\<in> (`) \\<pi> ` set_mset \\<B>\"\n  by (metis block_img in_image_mset)\n\nlemma iso_img_block_orig_exists: \"x \\<in># \\<B>' \\<Longrightarrow> \\<exists> bl . bl \\<in># \\<B> \\<and> x = \\<pi> ` bl\"\n  using iso_inv_block_in by blast\n\nlemma iso_blocks_map_inj: \"x \\<in># \\<B> \\<Longrightarrow> y \\<in># \\<B> \\<Longrightarrow> \\<pi> ` x = \\<pi> ` y \\<Longrightarrow> x = y\"\n  using image_inv_into_cancel incidence_system.wellformed iso_points_inv_map iso_points_map\n  by (metis (no_types, lifting) source.incidence_system_axioms subset_image_iff)\n\nlemma iso_bij_betwn_block_sets: \"bij_betw ((`) \\<pi>) (set_mset \\<B>) (set_mset \\<B>')\"\n  apply ( simp add: bij_betw_def inj_on_def)\n  using iso_block_in iso_inv_block_in iso_blocks_map_inj by auto \n\nlemma iso_bij_betwn_block_sets_inv: \"bij_betw ((`) (inv_into \\<V> \\<pi>)) (set_mset \\<B>') (set_mset \\<B>)\"\n  using incidence_system_isomorphism.iso_bij_betwn_block_sets inverse_incidence_sys_iso by blast \n\nlemma iso_bij_betw_individual_blocks: \"bl \\<in># \\<B> \\<Longrightarrow> bij_betw \\<pi> bl (\\<pi> ` bl)\"\n  using bij bij_betw_subset source.wellformed by blast \n\nlemma iso_bij_betw_individual_blocks_inv: \"bl \\<in># \\<B> \\<Longrightarrow> bij_betw (inv_into \\<V> \\<pi>) (\\<pi> ` bl) bl\"\n  using bij bij_betw_subset source.wellformed bij_betw_inv_into_subset by fastforce \n\nlemma iso_bij_betw_individual_blocks_inv_alt: \n    \"bl \\<in># \\<B>' \\<Longrightarrow> bij_betw (inv_into \\<V> \\<pi>) bl ((inv_into \\<V> \\<pi>) ` bl)\"\n  using incidence_system_isomorphism.iso_bij_betw_individual_blocks inverse_incidence_sys_iso\n  by blast \n  \nlemma iso_inv_block_in_alt:  \"(\\<pi> ` bl) \\<in># \\<B>' \\<Longrightarrow> bl \\<subseteq> \\<V> \\<Longrightarrow> bl \\<in># \\<B>\"\n  using image_eqI image_inv_into_cancel inv_iso_block_img iso_points_inv_map\n  by (metis (no_types, lifting) iso_points_map multiset.set_map subset_image_iff)\n\nlemma iso_img_block_not_in: \n  assumes \"x \\<notin># \\<B>\"\n  assumes \"x \\<subseteq> \\<V>\"\n  shows \"(\\<pi> ` x) \\<notin># \\<B>'\"\nproof (rule ccontr)\n  assume a: \"\\<not> \\<pi> ` x \\<notin># \\<B>'\"\n  then have a: \"\\<pi> ` x \\<in># \\<B>'\" by simp\n  then have \"\\<And> y . y \\<in> (\\<pi> ` x) \\<Longrightarrow> (inv_into \\<V> \\<pi>) y \\<in> \\<V>\"\n    using target.wf_invalid_point iso_points_inv_map by auto \n  then have \"((`) (inv_into \\<V> \\<pi>)) (\\<pi> ` x) \\<in># \\<B>\" \n    using iso_bij_betwn_block_sets_inv by (meson a bij_betw_apply) \n  thus False\n    using a assms(1) assms(2) iso_inv_block_in_alt by blast \nqed\n\nlemma iso_block_multiplicity:\n  assumes  \"bl \\<subseteq> \\<V>\" \n  shows \"source.multiplicity bl = target.multiplicity (\\<pi> ` bl)\"\nproof (cases \"bl \\<in># \\<B>\")\n  case True\n  have \"inj_on ((`) \\<pi>) (set_mset \\<B>)\"\n    using bij_betw_imp_inj_on iso_bij_betwn_block_sets by auto \n  then have \"count \\<B> bl = count \\<B>' (\\<pi> ` bl)\" \n    using count_image_mset_le_count_inj_on count_image_mset_ge_count True block_img inv_into_f_f \n      less_le_not_le order.not_eq_order_implies_strict by metis  \n  thus ?thesis by simp\nnext\n  case False\n  have s_mult: \"source.multiplicity bl = 0\"\n    by (simp add: False count_eq_zero_iff) \n  then have \"target.multiplicity (\\<pi> ` bl) = 0\"\n    using False count_inI iso_inv_block_in_alt\n    by (metis assms) \n  thus ?thesis\n    using s_mult by simp\nqed\n\nlemma iso_point_in_block_img_iff: \"p \\<in> \\<V> \\<Longrightarrow> bl \\<in># \\<B> \\<Longrightarrow> p \\<in> bl \\<longleftrightarrow> (\\<pi> p) \\<in> (\\<pi> ` bl)\"\n  by (metis bij bij_betw_imp_surj_on iso_bij_betw_individual_blocks_inv bij_betw_inv_into_left imageI)\n\nlemma iso_point_subset_block_iff: \"p \\<subseteq> \\<V> \\<Longrightarrow> bl \\<in># \\<B> \\<Longrightarrow> p \\<subseteq> bl \\<longleftrightarrow> (\\<pi> ` p) \\<subseteq> (\\<pi> ` bl)\"\n  apply auto\n  using image_subset_iff iso_point_in_block_img_iff subset_iff by metis\n\nlemma iso_is_image_block: \"\\<B>' = blocks_image \\<B> \\<pi>\"\n  unfolding blocks_image_def by (simp add: block_img iso_points_map)\n\nend\n\nsubsection \\<open>Design Isomorphisms\\<close>\ntext \\<open>Apply the concept of isomorphisms to designs only\\<close>\n\nlocale design_isomorphism = incidence_system_isomorphism \\<V> \\<B> \\<V>' \\<B>' \\<pi> + source: design \\<V> \\<B> + \n  target: design \\<V>' \\<B>' for \\<V> and \\<B> and \\<V>' and \\<B>' and bij_map (\"\\<pi>\")\n  \ncontext design_isomorphism\nbegin\n\nlemma inverse_design_isomorphism: \"design_isomorphism \\<V>' \\<B>' \\<V> \\<B> (inv_into \\<V> \\<pi>)\"\n  using inverse_incidence_sys_iso source.wf_design target.wf_design\n  by (simp add: design_isomorphism.intro) \n\nend\n\nsubsubsection \\<open>Isomorphism Operation\\<close>\ntext \\<open>Define the concept of isomorphic designs outside the scope of locale\\<close>\n\ndefinition isomorphic_designs (infixl \"\\<cong>\\<^sub>D\" 50) where\n\"\\<D> \\<cong>\\<^sub>D \\<D>' \\<longleftrightarrow> (\\<exists> \\<pi> . design_isomorphism (fst \\<D>) (snd \\<D>) (fst \\<D>') (snd \\<D>') \\<pi>)\"\n\nlemma isomorphic_designs_symmetric: \"(\\<V>, \\<B>) \\<cong>\\<^sub>D (\\<V>', \\<B>') \\<Longrightarrow> (\\<V>', \\<B>') \\<cong>\\<^sub>D (\\<V>, \\<B>)\"\n  using isomorphic_designs_def design_isomorphism.inverse_design_isomorphism\n  by metis\n\nlemma isomorphic_designs_implies_bij: \"(\\<V>, \\<B>) \\<cong>\\<^sub>D (\\<V>', \\<B>') \\<Longrightarrow> \\<exists> \\<pi> . bij_betw \\<pi> \\<V> \\<V>'\"\n  using incidence_system_isomorphism.bij isomorphic_designs_def\n  by (metis design_isomorphism.axioms(1) fst_conv)\n\nlemma isomorphic_designs_implies_block_map: \"(\\<V>, \\<B>) \\<cong>\\<^sub>D (\\<V>', \\<B>') \\<Longrightarrow> \\<exists> \\<pi> . image_mset ((`) \\<pi>) \\<B> = \\<B>'\"\n  using incidence_system_isomorphism.block_img isomorphic_designs_def\n  using design_isomorphism.axioms(1) by fastforce\n\ncontext design\nbegin \n\nlemma isomorphic_designsI [intro]: \"design \\<V>' \\<B>' \\<Longrightarrow> bij_betw \\<pi> \\<V> \\<V>' \\<Longrightarrow> image_mset ((`) \\<pi>) \\<B> = \\<B>' \n    \\<Longrightarrow> (\\<V>, \\<B>) \\<cong>\\<^sub>D (\\<V>', \\<B>')\"\n  using design_isomorphism.intro isomorphic_designs_def wf_design image_set_system_wellformed\n  by (metis bij_betw_imp_surj_on blocks_image_def fst_conv incidence_system_axioms \n      incidence_system_isomorphism.intro incidence_system_isomorphism_axioms_def snd_conv)\n\nlemma eq_designs_isomorphic: \n  assumes \"\\<V> = \\<V>'\"\n  assumes \"\\<B> = \\<B>'\"\n  shows \"(\\<V>, \\<B>) \\<cong>\\<^sub>D (\\<V>', \\<B>')\" \nproof -\n  interpret d1: design \\<V> \\<B> using assms\n    using wf_design by auto \n  interpret d2: design \\<V>' \\<B>' using assms\n    using wf_design by blast \n  have \"design_isomorphism \\<V> \\<B> \\<V>' \\<B>' id\" using assms by (unfold_locales) simp_all\n  thus ?thesis unfolding isomorphic_designs_def by auto\nqed\n\nend\n\ncontext design_isomorphism\nbegin\n\nsubsubsection \\<open>Design Properties/Operations under Isomorphism\\<close>\n\nlemma design_iso_point_rep_num_eq: \n  assumes \"p \\<in> \\<V>\"\n  shows \"\\<B> rep p = \\<B>' rep (\\<pi> p)\"\nproof -\n  have \"{#b \\<in># \\<B> . p \\<in> b#} = {#b \\<in># \\<B> . \\<pi> p \\<in> \\<pi> ` b#}\" \n    using assms filter_mset_cong iso_point_in_block_img_iff assms by force\n  then have \"{#b \\<in># \\<B>' . \\<pi> p \\<in> b#} = image_mset ((`) \\<pi>) {#b \\<in># \\<B> . p \\<in> b#}\"\n    by (simp add: image_mset_filter_swap block_img)\n  thus ?thesis\n    by (simp add: point_replication_number_def) \nqed\n\nlemma design_iso_rep_numbers_eq: \"source.replication_numbers = target.replication_numbers\"\n  apply (simp add: source.replication_numbers_def target.replication_numbers_def)\n  using  design_iso_point_rep_num_eq design_isomorphism.design_iso_point_rep_num_eq iso_points_map\n  by (metis (no_types, lifting) inverse_design_isomorphism iso_points_inv_map rev_image_eqI)\n\nlemma design_iso_block_size_eq: \"bl \\<in># \\<B> \\<Longrightarrow> card bl = card (\\<pi> ` bl)\"\n  using card_image_le finite_subset_image image_inv_into_cancel\n  by (metis iso_points_inv_map iso_points_map le_antisym source.finite_blocks source.wellformed)\n  \nlemma design_iso_block_sizes_eq: \"source.sys_block_sizes = target.sys_block_sizes\"\n  apply (simp add: source.sys_block_sizes_def target.sys_block_sizes_def)\n  by (metis (no_types, lifting) design_iso_block_size_eq iso_block_in iso_img_block_orig_exists)\n\nlemma design_iso_points_index_eq: \n  assumes \"ps \\<subseteq> \\<V>\" \n  shows \"\\<B> index ps = \\<B>' index (\\<pi> ` ps)\"\nproof - \n  have \"\\<And> b . b \\<in># \\<B> \\<Longrightarrow> ((ps \\<subseteq> b) = ((\\<pi> ` ps) \\<subseteq> \\<pi> ` b))\" \n    using iso_point_subset_block_iff assms by blast\n  then have \"{#b \\<in># \\<B> . ps \\<subseteq> b#} = {#b \\<in># \\<B> . (\\<pi> ` ps) \\<subseteq> (\\<pi> ` b)#}\" \n    using assms filter_mset_cong by force  \n  then have \"{#b \\<in># \\<B>' . \\<pi> ` ps \\<subseteq> b#} = image_mset ((`) \\<pi>) {#b \\<in># \\<B> . ps \\<subseteq> b#}\"\n    by (simp add: image_mset_filter_swap block_img)\n  thus ?thesis\n    by (simp add: points_index_def)\nqed\n\nlemma design_iso_points_indices_imp: \n  assumes \"x \\<in> source.point_indices t\"\n  shows \"x \\<in> target.point_indices t\"\nproof - \n  obtain ps where t: \"card ps = t\" and ss: \"ps \\<subseteq> \\<V>\" and x: \"\\<B> index ps = x\" using assms\n    by (auto simp add: source.point_indices_def)\n  then have x_val: \"x = \\<B>' index (\\<pi> ` ps)\" using design_iso_points_index_eq by auto\n  have x_img: \" (\\<pi> ` ps) \\<subseteq> \\<V>'\" \n    using ss bij iso_points_map by fastforce \n  then have \"card (\\<pi> ` ps) = t\" using t ss iso_points_ss_card by auto\n  then show ?thesis using target.point_indices_elem_in x_img x_val by blast \nqed\n\nlemma design_iso_points_indices_eq: \"source.point_indices t = target.point_indices t\"\n  using inverse_design_isomorphism design_isomorphism.design_iso_points_indices_imp\n    design_iso_points_indices_imp by blast \n\nlemma design_iso_block_intersect_num_eq: \n  assumes \"b1 \\<in># \\<B>\"\n  assumes \"b2 \\<in># \\<B>\"\n  shows \"b1 |\\<inter>| b2 = (\\<pi> ` b1) |\\<inter>| (\\<pi> ` b2)\"\nproof -\n  have split: \"\\<pi> ` (b1 \\<inter> b2) = (\\<pi> ` b1) \\<inter> (\\<pi> ` b2)\" using assms bij bij_betw_inter_subsets\n    by (metis source.wellformed) \n  thus ?thesis using source.wellformed\n    by (simp add: intersection_number_def iso_points_ss_card split assms(2) inf.coboundedI2) \nqed\n\nlemma design_iso_inter_numbers_imp: \n  assumes \"x \\<in> source.intersection_numbers\" \n  shows \"x \\<in> target.intersection_numbers\"\nproof - \n  obtain b1 b2 where 1: \"b1 \\<in># \\<B>\" and 2: \"b2 \\<in># (remove1_mset b1 \\<B>)\" and xval: \"x = b1 |\\<inter>| b2\" \n    using assms by (auto simp add: source.intersection_numbers_def)\n  then have pi1: \"\\<pi> ` b1 \\<in># \\<B>'\" by (simp add: iso_block_in)\n  have pi2: \"\\<pi> ` b2 \\<in># (remove1_mset (\\<pi> ` b1) \\<B>')\" using iso_block_in 2\n    by (metis (no_types, lifting) \"1\" block_img image_mset_remove1_mset_if in_remove1_mset_neq \n        iso_blocks_map_inj more_than_one_mset_mset_diff multiset.set_map)\n  have \"x = (\\<pi> ` b1) |\\<inter>| (\\<pi> ` b2)\" using 1 2 design_iso_block_intersect_num_eq\n    by (metis in_diffD xval)\n  then have \"x \\<in> {b1 |\\<inter>| b2 | b1 b2 . b1 \\<in># \\<B>' \\<and> b2 \\<in># (\\<B>' - {#b1#})}\" \n    using pi1 pi2 by blast\n  then show ?thesis by (simp add: target.intersection_numbers_def) \nqed\n\nlemma design_iso_intersection_numbers: \"source.intersection_numbers = target.intersection_numbers\"\n  using inverse_design_isomorphism design_isomorphism.design_iso_inter_numbers_imp \n      design_iso_inter_numbers_imp by blast\n\nlemma design_iso_n_intersect_num: \n  assumes \"b1 \\<in># \\<B>\" \n  assumes \"b2 \\<in># \\<B>\" \n  shows \"b1 |\\<inter>|\\<^sub>n b2 = ((\\<pi> ` b1) |\\<inter>|\\<^sub>n (\\<pi> ` b2))\"\nproof -\n  let ?A = \"{x . x \\<subseteq> b1 \\<and> x \\<subseteq> b2 \\<and> card x = n}\"\n  let ?B = \"{y . y \\<subseteq> (\\<pi> ` b1) \\<and> y \\<subseteq> (\\<pi> ` b2) \\<and> card y = n}\"\n  have b1v: \"b1 \\<subseteq> \\<V>\"  by (simp add: assms(1) source.wellformed) \n  have b2v: \"b2 \\<subseteq> \\<V>\"  by (simp add: assms(2) source.wellformed) \n  then have \"\\<And>x y . x \\<subseteq> b1 \\<Longrightarrow> x \\<subseteq> b2 \\<Longrightarrow> y \\<subseteq> b1 \\<Longrightarrow> y \\<subseteq> b2 \\<Longrightarrow>  \\<pi> ` x = \\<pi> ` y \\<Longrightarrow> x = y\"\n    using b1v bij by (metis bij_betw_imp_surj_on bij_betw_inv_into_subset dual_order.trans)\n  then have inj: \"inj_on ((`) \\<pi>) ?A\" by (simp add: inj_on_def)\n  have eqcard: \"\\<And>xa. xa \\<subseteq> b1 \\<Longrightarrow> xa \\<subseteq> b2 \\<Longrightarrow> card (\\<pi> ` xa) = card xa\" using b1v b2v bij\n    using iso_points_ss_card by auto \n  have surj: \"\\<And>x. x \\<subseteq> \\<pi> ` b1 \\<Longrightarrow> x \\<subseteq> \\<pi> ` b2  \\<Longrightarrow> \n                x \\<in> {(\\<pi> ` xa) | xa . xa \\<subseteq> b1 \\<and> xa \\<subseteq> b2 \\<and> card xa = card x}\"\n  proof - \n    fix x\n    assume x1: \"x \\<subseteq> \\<pi> ` b1\" and x2: \"x \\<subseteq> \\<pi> ` b2\" \n    then obtain xa where eq_x: \"\\<pi> ` xa = x\" and ss: \"xa \\<subseteq> \\<V>\"\n      by (metis b1v dual_order.trans subset_imageE)\n    then have f1: \"xa \\<subseteq> b1\" by (simp add: x1 assms(1) iso_point_subset_block_iff) \n    then have f2: \"xa \\<subseteq> b2\" by (simp add: eq_x ss assms(2) iso_point_subset_block_iff x2) \n    then have f3: \"card xa = card x\" using bij by (simp add: eq_x ss iso_points_ss_card)\n    then show \"x \\<in> {(\\<pi> ` xa) | xa . xa \\<subseteq> b1 \\<and> xa \\<subseteq> b2 \\<and> card xa = card x}\" \n      using f1 f2 f3 \\<open>\\<pi> ` xa = x\\<close> by auto\n  qed\n  have \"bij_betw ( (`) \\<pi>) ?A ?B\"\n  proof (auto simp add: bij_betw_def)\n    show \"inj_on ((`) \\<pi>) {x. x \\<subseteq> b1 \\<and> x \\<subseteq> b2 \\<and> card x = n}\" using inj by simp\n    show \"\\<And>xa. xa \\<subseteq> b1 \\<Longrightarrow> xa \\<subseteq> b2 \\<Longrightarrow> n = card xa \\<Longrightarrow> card (\\<pi> ` xa) = card xa\" \n      using eqcard by simp\n    show \"\\<And>x. x \\<subseteq> \\<pi> ` b1 \\<Longrightarrow> x \\<subseteq> \\<pi> ` b2 \\<Longrightarrow> n = card x \\<Longrightarrow> \n            x \\<in> (`) \\<pi> ` {xa. xa \\<subseteq> b1 \\<and> xa \\<subseteq> b2 \\<and> card xa = card x}\" \n      using surj by (simp add: setcompr_eq_image)\n  qed\n  thus ?thesis\n    using bij_betw_same_card by (auto simp add: n_intersect_number_def)\nqed\n\nlemma subdesign_iso_implies:\n  assumes \"sub_set_system V B \\<V> \\<B>\"\n  shows \"sub_set_system (\\<pi> ` V) (blocks_image B \\<pi>) \\<V>' \\<B>'\"\nproof (unfold_locales)\n  show \"\\<pi> ` V \\<subseteq> \\<V>'\" \n    by (metis assms image_mono iso_points_map sub_set_system.points_subset) \n  show \"blocks_image B \\<pi> \\<subseteq># \\<B>'\"\n    by (metis assms block_img blocks_image_def image_mset_subseteq_mono sub_set_system.blocks_subset) \nqed\n\nlemma subdesign_image_is_design: \n  assumes \"sub_set_system V B \\<V> \\<B>\"\n  assumes \"design V B\"\n  shows \"design (\\<pi> ` V) (blocks_image B \\<pi>)\"\nproof -\n  interpret fin: finite_incidence_system \"(\\<pi> ` V)\" \"(blocks_image B \\<pi>)\" using assms(2)\n    by (simp add: design.axioms(1) finite_incidence_system.image_set_system_finite)\n  interpret des: sub_design V B \\<V> \\<B> using assms design.wf_design_iff\n    by (unfold_locales, auto simp add: sub_set_system.points_subset sub_set_system.blocks_subset)\n  have bl_img: \"blocks_image B \\<pi> \\<subseteq># \\<B>'\"\n    by (simp add: blocks_image_def des.blocks_subset image_mset_subseteq_mono iso_is_image_block)  \n  then show ?thesis \n  proof (unfold_locales, auto)\n    show \"{} \\<in># blocks_image B \\<pi> \\<Longrightarrow> False\" \n      using assms subdesign_iso_implies target.blocks_nempty bl_img by auto\n  qed\nqed\n\nlemma sub_design_isomorphism: \n  assumes \"sub_set_system V B \\<V> \\<B>\"\n  assumes \"design V B\"\n  shows \"design_isomorphism V B (\\<pi> ` V) (blocks_image B \\<pi>) \\<pi>\"\nproof -\n  interpret design \"(\\<pi> ` V)\" \"(blocks_image B \\<pi>)\"\n    by (simp add: assms(1) assms(2) subdesign_image_is_design)\n  interpret des: design V B by fact\n  show ?thesis\n  proof (unfold_locales)\n    show \"bij_betw \\<pi> V (\\<pi> ` V)\" using bij\n      by (metis assms(1) bij_betw_subset sub_set_system.points_subset) \n    show \"image_mset ((`) \\<pi>) B = blocks_image B \\<pi>\" by (simp add: blocks_image_def)\n  qed\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/Design_Isomorphisms.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8539127678225575, "lm_q2_score": 0.8267117940706734, "lm_q1q2_score": 0.7059397562664409}}
{"text": "theory SMLanguage\n  imports Language\nbegin\n\nsection {* Stutter/mumble closure *}\n\nsubsection {* List monoid *}\n\ninstantiation list :: (type) monoid_add\nbegin\n  definition plus_list :: \"'a list \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where\n    \"plus_list \\<equiv> op @\"\n\n  definition zero_list :: \"'a list\" where \"zero_list \\<equiv> []\"\n\n  instance by default (auto simp add: plus_list_def zero_list_def)\nend\n\nsubsection {* Definition of stutter/mumble closure *}\n\ntext {*\nDefine a \\textit{monoidal language} as a language $L$ over an alphabet\n$\\Sigma$ with a binary operator $+$ and unital element $0 \\in\n\\Sigma$, such that $(\\Sigma, +, 0)$ is a monoid. For these\nlanguages we can define closure operators inspired by Brookes's work\non full abstraction~\\cite{} and futher work by Dingel~\\cite{}. The\nstutter/mumble language $\\gamma^\\ddagger$ for a word $\\gamma$ in such a\nlanguage is inductively generated as follows, assuming $x,y,z \\in\n\\Sigma$ and $\\alpha,\\beta,\\gamma \\in \\Sigma^*$: Firstly, $0\\gamma \\in\n\\gamma^\\ddagger$. Secondly, if $\\alpha x \\beta \\in \\gamma^\\ddagger$\nthen $\\alpha 0x\\beta \\in \\gamma^\\ddagger$ and $\\alpha x0\\beta \\in\n\\gamma^\\ddagger$ (\\textit{stuttering}). Thirdly, if $\\alpha xy\\beta\n\\in \\gamma^\\ddagger$ then $\\alpha(x + y)\\beta \\in\n\\gamma^\\ddagger$ (\\textit{mumbling}). The stutter/mumble closure for a\nlanguage $X$ is then simply defined as $X^\\ddagger =\n\\bigcup\\{\\alpha^\\ddagger|\\alpha \\in X\\}$.\n*}\n\ninductive_set sm_set :: \"'a::monoid_add list \\<Rightarrow> 'a::monoid_add lan\" for T where\n  self [intro!]: \"0 # T \\<in> sm_set T\"\n| stutter: \"as @ bs \\<in> sm_set T \\<Longrightarrow> as @ [0] @ bs \\<in> sm_set T\"\n| mumble: \"as @ [bs] @ [cs] @ ds \\<in> sm_set T \\<Longrightarrow> as @ [bs + cs] @ ds \\<in> sm_set T\"\n\ntext {*\nThe reason why we have $0\\gamma \\in \\gamma^\\ddagger$, rather than $\\gamma \\in \\gamma^\\ddagger$\nis that this rule ensures that no stutter/mumble closed language contains the empty word.\nThe reason for this is as follows; If stutter/mumble closed languages are allowed to contain the empty word,\none ends up with two distinct units for shuffle and language product, $\\{\\epsilon,0,00,000,\\dots\\}$ and $\\{0,00,000,\\dots\\}$.\nUnfortunately this means the extensiveness property $X \\subseteq X^\\ddagger$ no longer holds for arbitrary languages,\nbut only those without the empty word property. The restriction on this property makes certain proofs more complicated,\nbut the problems caused by having two distinct units makes the tradeoff worthwhile.\n*}\n\ndefinition sm_closure :: \"'a::monoid_add lan \\<Rightarrow> 'a::monoid_add lan\" (\"_\\<^sup>\\<ddagger>\" [101] 100) where\n  \"X\\<^sup>\\<ddagger> \\<equiv> \\<Union>(sm_set ` X)\"\n\nlemma sm_set_append: \"xs \\<in> sm_set xs' \\<Longrightarrow> ys \\<in> sm_set ys' \\<Longrightarrow> (xs @ ys) \\<in> sm_set (xs' @ ys')\"\n  apply (induct xs rule: sm_set.induct)\n  apply (induct ys rule: sm_set.induct)\n  apply auto\n  apply (metis (full_types) append_Cons append_Nil sm_set.self sm_set.stutter)\n  apply (metis append_Cons append_Nil append_assoc sm_set.stutter)\n  apply (metis append_Cons append_Nil append_assoc sm_set.mumble)\n  apply (metis append_Cons eq_Nil_appendI sm_set.stutter)\n  by (metis append_Cons eq_Nil_appendI sm_set.mumble)\n\nlemma sm_set_self_var: \"x # xs \\<in> sm_set (x # xs)\"\nproof -\n  have \"0 # x # xs \\<in> sm_set (x # xs)\"\n    by (metis sm_set.self)\n  hence \"[] @ [0] @ [x] @ xs \\<in> sm_set (x # xs)\"\n    by simp\n  hence \"[] @ [0 + x] @ xs \\<in> sm_set (x # xs)\"\n    by (rule sm_set.mumble)\n  thus \"x # xs \\<in> sm_set (x # xs)\"\n    by simp\nqed\n\nlemma sm_set_cons: \"xs \\<in> sm_set ys \\<Longrightarrow> (x#xs) \\<in> sm_set (x#ys)\"\n  by (metis (hide_lams, no_types) Cons_eq_appendI append_Nil sm_set_self_var sm_set_append)\n\nlemma sm_set_self_rev [intro]: \"xs @ [0] \\<in> sm_set xs\"\nproof -\n  have \"0 # xs \\<in> sm_set xs\"\n    by (metis sm_set.self)\n  thus ?thesis\n    apply (induct xs)\n    apply auto\n    by (metis sm_set.self sm_set_cons)\nqed\n\nlemma sm_set_pair: \"[x + y] \\<in> sm_set [x, y]\"\n  by (metis append_Cons append_Nil sm_set.mumble sm_set_self_var)\n\nlemma sm_set_trans: \"xs \\<in> sm_set ys \\<Longrightarrow> ys \\<in> sm_set zs \\<Longrightarrow> xs \\<in> sm_set zs\"\n  apply (induct xs rule: sm_set.induct)\n  apply auto\n  apply (metis (full_types) append_Cons append_Nil sm_set.stutter)\n  apply (metis append_Cons eq_Nil_appendI sm_set.stutter)\n  by (metis append_Cons eq_Nil_appendI sm_set.mumble)\n\nlemma sm_set_empty [intro]: \"[] \\<notin> sm_set xs\"\nproof -\n  {\n    fix ys\n    assume \"ys \\<in> sm_set xs\" hence \"ys \\<noteq> []\"\n      by (induct ys rule: sm_set.induct) auto\n  }\n  thus ?thesis by auto\nqed\n\n\n\nlemma [simp]: \"listsum (xs @ (y + y') # ys) = listsum (xs @ y # y' # ys)\"\n  by (induct xs) (auto intro: add_assoc)\n\nlemma sm_set_listsum: \"xs \\<in> sm_set ys \\<Longrightarrow> [listsum xs] \\<in> sm_set [listsum ys]\"\n  apply (induct xs rule: sm_set.induct)\n  apply auto\n  apply (metis sm_set_self_var)\n  by (metis add_assoc)\n\nlemma sm_set_cons_unit: \"xs \\<in> sm_set ys \\<Longrightarrow> xs \\<in> sm_set (0 # ys)\"\n  apply (induct xs rule: sm_set.induct)\n  apply (rule sm_set_self_var)\n  apply (rule stutter)\n  apply assumption\n  apply (rule mumble)\n  apply assumption\n  done\n\nsubsection {* Mumbling sequences of symbols *}\n\nlemma mumble_many': \"length bs = n \\<and> as @ bs @ cs \\<in> sm_set T \\<longrightarrow> as @ [listsum bs] @ cs \\<in> sm_set T\"\n  apply (induct n arbitrary: as bs cs)\n  apply (metis append_Nil length_0_conv listsum_simps(1) sm_set.stutter)\nproof\n  fix n as bs cs\n  assume \"\\<And>as bs cs. length bs = n \\<and> as @ bs @ cs \\<in> sm_set T \\<longrightarrow> as @ [listsum bs] @ cs \\<in> sm_set T\"\n  and \"length bs = Suc n \\<and> as @ bs @ cs \\<in> sm_set T\"\n  then moreover obtain z and zs where \"bs = z#zs\" by (metis Suc_length_conv)\n  ultimately have \"(as @ [z]) @ [listsum zs] @ cs \\<in> sm_set T\"\n    by (metis append_Cons append_Nil append_assoc diff_Suc_1 drop_1_Cons length_drop)\n  hence \"as @ [listsum (z#zs)] @ cs \\<in> sm_set T\"\n    by (simp only: listsum_simps(2)) (metis mumble append_assoc)\n  thus \"as @ [listsum bs] @ cs \\<in> sm_set T\"\n    by (metis `bs = z # zs`)\nqed\n\nlemma mumble_many: \"as @ bs @ cs \\<in> sm_set T \\<Longrightarrow> as @ [listsum bs] @ cs \\<in> sm_set T\"\n  by (metis mumble_many')\n\nhide_fact mumble_many'\n\nsubsection {* Lifted operators and properties *}\n\ntext {*\nThe definitions below lift the shuffle and language product operations to stutter/mumble closed\nlanguages. Most of the following properties show that $(\\mathcal{P}(\\Sigma^*)^\\ddagger, \\cup, \\cdot^\\ddagger, \\|^\\ddagger,\\emptyset,\\mathbf{1})$ is\na concurrent Kleene algebra.\n*}\n\ndefinition sm_shuffle :: \"'a::monoid_add lan \\<Rightarrow> 'a::monoid_add lan \\<Rightarrow> 'a::monoid_add lan\" (infixl \"\\<parallel>\\<^sup>\\<ddagger>\" 75) where\n  \"X \\<parallel>\\<^sup>\\<ddagger> Y \\<equiv> (X \\<parallel> Y)\\<^sup>\\<ddagger>\"\n\ndefinition sm_l_prod :: \"'a::monoid_add lan \\<Rightarrow> 'a::monoid_add lan \\<Rightarrow> 'a::monoid_add lan\" (infixl \"\\<cdot>\\<^sup>\\<ddagger>\" 75) where\n  \"X \\<cdot>\\<^sup>\\<ddagger> Y \\<equiv> (X \\<cdot> Y)\\<^sup>\\<ddagger>\"\n\ndefinition sm_one :: \"'a::monoid_add lan\" (\"\\<one>\") where\n  \"sm_one = {[]}\\<^sup>\\<ddagger>\"\n\ndefinition atomic :: \"'a::monoid_add list set \\<Rightarrow> 'a::monoid_add list set\" (\"\\<langle>_\\<rangle>\" [0] 1000) where\n  \"atomic X = {[listsum xs]|xs. xs \\<in> X}\\<^sup>\\<ddagger>\"\n\ntext {* It is straightforward to show that $^\\ddagger$ is a closure operator on the set of languages \nwithout the empty word. *}\n\nlemma sm_ewp: \"\\<not> ewp (X\\<^sup>\\<ddagger>)\"\n  by (simp add: sm_closure_def ewp_def sm_set_empty)\n\nlemma sm_closure_extensive [intro]: \"\\<not> ewp X \\<Longrightarrow> X \\<subseteq> X\\<^sup>\\<ddagger>\"\n  apply (auto simp add: sm_closure_def)\n  apply (rule_tac x = x in bexI)\n  apply auto\n  by (metis (full_types) ewp_def neq_Nil_conv sm_set_self_var)\n\nlemma sm_closure_iso: \"X \\<subseteq> Y \\<Longrightarrow> X\\<^sup>\\<ddagger> \\<subseteq> Y\\<^sup>\\<ddagger>\"\n  by (auto simp add: sm_closure_def)\n\nlemma sm_closure_idem: \"(X\\<^sup>\\<ddagger>)\\<^sup>\\<ddagger> = X\\<^sup>\\<ddagger>\"\n  apply default\n  defer\n  apply (metis sm_closure_extensive sm_ewp)\n  apply (auto simp add: sm_closure_def)\n  apply (rule_tac x = xa in bexI)\n  by (auto intro: sm_set_trans)\n\nlemma sm_closure_closure: \"\\<not> ewp X \\<Longrightarrow> X \\<subseteq> Y\\<^sup>\\<ddagger> \\<longleftrightarrow> X\\<^sup>\\<ddagger> \\<subseteq> Y\\<^sup>\\<ddagger>\"\n  by (metis sm_closure_extensive sm_closure_idem sm_closure_iso subset_trans)\n\ntext {* The atomicity brackets are an interior (or coclosure) operator on the set of stutter/mumble\nclosed languages. *}\n\nlemma atomic_ewp: \"\\<not> ewp \\<langle>X\\<rangle>\"\n  by (simp add: atomic_def sm_ewp)\n\nlemma atomic_coextensive: \"\\<langle>X\\<^sup>\\<ddagger>\\<rangle> \\<subseteq> X\\<^sup>\\<ddagger>\"\nproof -\n  have \"{[listsum x]|x. x \\<in> X\\<^sup>\\<ddagger>} \\<subseteq> X\\<^sup>\\<ddagger>\"\n    apply (simp add: sm_closure_def atomic_def)\n    apply auto\n    apply (rule_tac x = xb in bexI)\n    apply (metis append_Nil append_Nil2 mumble_many)\n    by auto\n  thus ?thesis\n    apply (simp add: atomic_def)\n    apply (subst sm_closure_closure[symmetric])\n    by (auto simp add: ewp_def)\nqed\n\nlemma atomic_iso: \"X \\<subseteq> Y \\<Longrightarrow> \\<langle>X\\<rangle> \\<subseteq> \\<langle>Y\\<rangle>\"\n  by (simp add: atomic_def, rule sm_closure_iso, auto)\n\nlemma atomic_closure: \"\\<langle>X\\<rangle> = \\<langle>X\\<rangle>\\<^sup>\\<ddagger>\"\n  by (simp add: atomic_def sm_closure_idem)\n\nlemma atomic_idem: \"\\<langle>\\<langle>X\\<rangle>\\<rangle> = \\<langle>X\\<rangle>\"\n  apply (simp add: atomic_def)\n  apply default\n  apply (metis (mono_tags) atomic_coextensive atomic_def)\n  apply (rule sm_closure_iso)\n  apply (auto simp add: sm_closure_def)\n  by (metis append_Nil2 listsum_append listsum_simps(2) sm_set_self_var)\n\nlemma atomic_interior: \"\\<langle>X\\<^sup>\\<ddagger>\\<rangle> \\<subseteq> Y\\<^sup>\\<ddagger> \\<longleftrightarrow> \\<langle>X\\<^sup>\\<ddagger>\\<rangle> \\<subseteq> \\<langle>Y\\<^sup>\\<ddagger>\\<rangle>\"\n  by (metis atomic_coextensive atomic_idem atomic_iso subset_trans)\n\nlemma \"{}\\<^sup>\\<ddagger> = {}\"\n  by (auto simp add: sm_closure_def)\n\nlemma sm_one_closed: \"\\<one>\\<^sup>\\<ddagger> = \\<one>\"\n  by (metis sm_closure_idem sm_one_def)\n\nlemma sm_union: \"(X \\<union> Y)\\<^sup>\\<ddagger> = X\\<^sup>\\<ddagger> \\<union> Y\\<^sup>\\<ddagger>\"\n  by (simp add: sm_closure_def)\n\nlemma ewp_sm_one:\n  assumes ewp_X: \"ewp X\"\n  shows \"X\\<^sup>\\<ddagger> = \\<one> \\<union> (X - {[]})\\<^sup>\\<ddagger>\"\nproof -\n  have \"X\\<^sup>\\<ddagger> = ({[]} \\<union> (X - {[]}))\\<^sup>\\<ddagger>\"\n    by (metis ewp_X ewp_def insert_Diff_single insert_absorb insert_is_Un)\n  also have \"... = {[]}\\<^sup>\\<ddagger> \\<union> (X - {[]})\\<^sup>\\<ddagger>\"\n    by (metis sm_union)\n  also have \"... = \\<one> \\<union> (X - {[]})\\<^sup>\\<ddagger>\"\n    by (metis sm_one_def)\n  finally show ?thesis .\nqed\n\nlemma sm_set_one: \"\\<one> = sm_set []\"\n  by (auto simp add: sm_one_def sm_closure_def)\n\nlemma atomic_sm_set: \"\\<langle>sm_set xs\\<rangle> = {[listsum xs]}\\<^sup>\\<ddagger>\"\n  by (auto simp add: atomic_def sm_closure_def) (metis sm_set_listsum sm_set_trans)\n\nlemma \"\\<langle>{}\\<rangle> = {}\"\n  by (simp add: atomic_def sm_closure_def)\n\nlemma inits_last [simp]: \"rev (tl (rev (x#xs))) @ [hd (rev (x#xs))] = x#xs\"\n  by (metis Nil_is_append_conv hd.simps list.exhaust rev.simps(2) rev_rev_ident tl.simps(2))\n\nlemma sm_set_unit: \"xs \\<in> sm_set (ys @ zs) \\<Longrightarrow> xs \\<in> sm_set (ys @ 0 # zs)\"\nproof (induct xs rule: sm_set.induct)\n  have \"0 # (ys @ 0 # zs) \\<in> sm_set (ys @ 0 # zs)\"\n    by (metis sm_set.self)\n  hence \"(0 # ys) @ [0] @ zs \\<in> sm_set (ys @ 0 # zs)\"\n    by (metis append_Cons append_Nil)\n  hence \"(rev (tl (rev (0 # ys))) @ [hd (rev (0 # ys))]) @ [0] @ zs \\<in> sm_set (ys @ 0 # zs)\"\n    by (simp only: inits_last)\n  hence \"rev (tl (rev (0 # ys))) @ [hd (rev (0 # ys))] @ [0] @ zs \\<in> sm_set (ys @ 0 # zs)\"\n    by (metis append_Cons append_Nil append_assoc)\n  hence \"rev (tl (rev (0 # ys))) @ [hd (rev (0 # ys))] @ zs \\<in> sm_set (ys @ 0 # zs)\"\n    by (metis monoid_add_class.add.right_neutral sm_set.simps)\n  hence \"(rev (tl (rev (0 # ys))) @ [hd (rev (0 # ys))]) @ zs \\<in> sm_set (ys @ 0 # zs)\"\n    by (metis append_Cons append_Nil append_assoc)\n  hence \"(0 # ys) @ zs \\<in> sm_set (ys @ 0 # zs)\"\n    by (simp only: inits_last)\n  thus \"0 # ys @ zs \\<in> sm_set (ys @ 0 # zs)\"\n    by simp\nqed (metis stutter, metis mumble)\n\nhide_fact inits_last\n\nlemma sm_l_prodl: \"(X \\<cdot> Y)\\<^sup>\\<ddagger> \\<subseteq> (X \\<cdot> Y\\<^sup>\\<ddagger>)\\<^sup>\\<ddagger>\"\n  apply (simp add: sm_closure_def l_prod_def complex_product_def)\n  apply auto\n  apply (rule_tac x = \"xb @ 0 # y\" in exI)\n  apply auto\n  by (metis sm_set_unit)\n\nlemma sm_l_prodr: \"(X \\<cdot> Y)\\<^sup>\\<ddagger> \\<subseteq> (X\\<^sup>\\<ddagger> \\<cdot> Y)\\<^sup>\\<ddagger>\"\n  apply (simp add: sm_closure_def l_prod_def complex_product_def)\n  apply auto\n  apply (rule_tac x = \"xb @ 0 # y\" in exI)\n  apply auto\n  apply (rule_tac x = \"xb @ [0]\" in exI)\n  apply auto\n  by (metis sm_set_unit)\n\nlemma sm_l_prod_closure: \"X\\<^sup>\\<ddagger> \\<cdot>\\<^sup>\\<ddagger> Y\\<^sup>\\<ddagger> = X \\<cdot>\\<^sup>\\<ddagger> Y\"\nproof (simp add: sm_l_prod_def, default)\n  show \"(X \\<cdot> Y)\\<^sup>\\<ddagger> \\<subseteq> (X\\<^sup>\\<ddagger> \\<cdot> Y\\<^sup>\\<ddagger>)\\<^sup>\\<ddagger>\"\n    by (metis order_trans sm_l_prodl sm_l_prodr)\nnext\n  {\n    fix xs\n    assume \"xs \\<in> (X\\<^sup>\\<ddagger> \\<cdot> Y\\<^sup>\\<ddagger>)\\<^sup>\\<ddagger>\"\n    hence \"xs \\<in> (X \\<cdot> Y)\\<^sup>\\<ddagger>\"\n      apply (auto simp add: sm_closure_def complex_product_def l_prod_def)\n      apply (rule_tac x = \"xb @ xc\" in exI)\n      apply auto\n      by (metis sm_set_append sm_set_trans)\n  }\n  thus \"(X\\<^sup>\\<ddagger> \\<cdot> Y\\<^sup>\\<ddagger>)\\<^sup>\\<ddagger> \\<subseteq> (X \\<cdot> Y)\\<^sup>\\<ddagger>\" by auto\nqed\n\nlemma sm_l_prod_isol: \"X \\<subseteq> Y \\<Longrightarrow> X \\<cdot>\\<^sup>\\<ddagger> Z \\<subseteq> Y \\<cdot>\\<^sup>\\<ddagger> Z\"\n  by (metis l_prod_isol sm_closure_iso sm_l_prod_def)\n\nlemma sm_l_prod_isor: \"X \\<subseteq> Y \\<Longrightarrow> Z \\<cdot>\\<^sup>\\<ddagger> X \\<subseteq> Z \\<cdot>\\<^sup>\\<ddagger> Y\"\n  by (metis l_prod_isor sm_closure_iso sm_l_prod_def)\n\nlemma tshuffle_sm: \"\\<Union>{map \\<langle>id,id\\<rangle> ` (xs' \\<sha> ys)|xs'. xs' \\<in> sm_set xs} \\<subseteq> (map \\<langle>id,id\\<rangle> ` (xs \\<sha> ys))\\<^sup>\\<ddagger>\"\nproof (auto simp add: sm_closure_def)\n  fix xs' zs'\n\n  assume \"xs' \\<in> sm_set xs\" and \"zs' \\<in> xs' \\<sha> ys\"\n\n  thus \"\\<exists>zs\\<in>xs \\<sha> ys. map \\<langle>id,id\\<rangle> zs' \\<in> sm_set (map \\<langle>id,id\\<rangle> zs)\"\n  proof (induct xs' arbitrary: zs' rule: sm_set.induct)\n    fix zs' :: \"('a, 'a) sum list\"\n    assume zs'_set: \"zs' \\<in> (0 # xs) \\<sha> ys\"\n\n    thus \"\\<exists>zs\\<in>xs \\<sha> ys. map \\<langle>id,id\\<rangle> zs' \\<in> sm_set (map \\<langle>id,id\\<rangle> zs)\"\n    proof (cases \"ys = []\", simp, metis sm_set.self)\n      assume ys_not_empty: \"ys \\<noteq> []\"\n\n      from zs'_set\n      have zs'_lefts: \"\\<ll> zs' = 0 # xs\"\n      and zs'_rights: \"\\<rr> zs' = ys\"\n        by (metis (lifting, full_types) mem_Collect_eq tshuffle_words_def)+\n\n      hence delete_left_non_empty: \"delete_left 0 zs' \\<noteq> []\"\n      proof -\n        have \"\\<rr> zs' \\<noteq> []\"\n          by (metis `\\<rr> zs' = ys` ys_not_empty)\n        hence \"\\<rr> (delete_left 0 zs') \\<noteq> []\"\n          by (induct zs' rule: sum_list_induct) auto\n        hence \"\\<not> (\\<ll> (delete_left 0 zs') = [] \\<and> \\<rr> (delete_left 0 zs') = [])\"\n          by blast\n        thus ?thesis\n          by simp\n      qed\n\n      have zs'_split: \"zs' = take_left 0 zs' @ [Inl 0] @ tl (drop_left 0 zs')\"\n        by (rule lefts_insert) (auto intro: zs'_lefts)\n\n      from delete_left_non_empty\n      have \"map \\<langle>id,id\\<rangle> (delete_left 0 zs') \\<in> sm_set (map \\<langle>id,id\\<rangle> (delete_left 0 zs'))\"\n        by (metis (full_types) Nil_is_map_conv neq_Nil_conv sm_set_self_var)\n\n      hence \"map \\<langle>id,id\\<rangle> (take_left 0 zs') @ map \\<langle>id,id\\<rangle> (tl (drop_left 0 zs')) \\<in> sm_set (map \\<langle>id,id\\<rangle> (delete_left 0 zs'))\"\n        by (metis delete_left_def map_append)\n\n      hence \"map \\<langle>id,id\\<rangle> (take_left 0 zs') @ [0] @ map \\<langle>id,id\\<rangle> (tl (drop_left 0 zs')) \\<in> sm_set (map \\<langle>id,id\\<rangle> (delete_left 0 zs'))\"\n        by (metis Cons_eq_appendI eq_Nil_appendI sm_set.stutter)\n\n      hence \"map \\<langle>id,id\\<rangle> (take_left 0 zs' @ [Inl 0] @ tl (drop_left 0 zs')) \\<in> sm_set (map \\<langle>id,id\\<rangle> (delete_left 0 zs'))\"\n        by (metis left_singleton map_append)\n\n      hence \"map \\<langle>id,id\\<rangle> zs' \\<in> sm_set (map \\<langle>id,id\\<rangle> (delete_left 0 zs'))\"\n        by (subst zs'_split, assumption)\n\n      thus \"\\<exists>zs\\<in>xs \\<sha> ys. map \\<langle>id,id\\<rangle> zs' \\<in> sm_set (map \\<langle>id,id\\<rangle> zs)\"\n        by (rule_tac x = \"delete_left 0 zs'\" in bexI) (auto simp add: tshuffle_words_def zs'_rights zs'_lefts)\n    qed\n  next\n    fix as :: \"'a list\" and bs :: \"'a list\" and zs' :: \"('a, 'a) sum list\"\n\n    assume \"as @ bs \\<in> sm_set xs\"\n    and ih: \"\\<And>zs'. zs' \\<in> (as @ bs) \\<sha> ys \\<Longrightarrow> \\<exists>zs\\<in>xs \\<sha> ys. map \\<langle>id,id\\<rangle> zs' \\<in> sm_set (map \\<langle>id,id\\<rangle> zs)\"\n    and zs'_set: \"zs' \\<in> (as @ [0] @ bs) \\<sha> ys\"\n\n    have zs'_split: \"zs' = take_left (length as) zs' @ [Inl 0] @ tl (drop_left (length as) zs')\"\n      by (rule lefts_insert, insert zs'_set, simp_all add: tshuffle_words_def)\n\n    from zs'_set have \"delete_left (length as) zs' \\<in> (as @ bs) \\<sha> ys\"\n      by (auto simp add: tshuffle_words_def intro: delete_left_lefts)\n\n    then obtain zs where zs_set: \"zs \\<in> xs \\<sha> ys\"\n    and \"map \\<langle>id,id\\<rangle> (delete_left (length as) zs') \\<in> sm_set (map \\<langle>id,id\\<rangle> zs)\"\n      by (metis ih)\n\n    hence \"map \\<langle>id,id\\<rangle> (take_left (length as) zs') @ map \\<langle>id,id\\<rangle> (tl (drop_left (length as) zs')) \\<in> sm_set (map \\<langle>id,id\\<rangle> zs)\"\n      by (metis delete_left_def map_append)\n\n    hence \"map \\<langle>id,id\\<rangle> (take_left (length as) zs') @ [0] @ map \\<langle>id,id\\<rangle> (tl (drop_left (length as) zs')) \\<in> sm_set (map \\<langle>id,id\\<rangle> zs)\"\n      by (metis sm_set.stutter)\n\n    hence \"map \\<langle>id,id\\<rangle> (take_left (length as) zs' @ [Inl 0] @ tl (drop_left (length as) zs')) \\<in> sm_set (map \\<langle>id,id\\<rangle> zs)\"\n      by simp\n\n    hence \"map \\<langle>id,id\\<rangle> zs' \\<in> sm_set (map \\<langle>id,id\\<rangle> zs)\"\n      by (metis zs'_split)\n\n    thus \"\\<exists>zs\\<in>xs \\<sha> ys. map \\<langle>id,id\\<rangle> zs' \\<in> sm_set (map \\<langle>id,id\\<rangle> zs)\"\n      by (metis zs_set)\n  next\n    fix as :: \"'a::monoid_add list\" and b :: \"'a\" and c :: \"'a\" and ds :: \"'a list\"\n    and zs' :: \"('a, 'a) sum list\"\n\n    assume ih: \"\\<And>zs'. zs' \\<in> (as @ [b] @ [c] @ ds) \\<sha> ys \\<Longrightarrow> \\<exists>zs\\<in>xs \\<sha> ys. map \\<langle>id,id\\<rangle> zs' \\<in> sm_set (map \\<langle>id,id\\<rangle> zs)\"\n    and zs'_set: \"zs' \\<in> (as @ [b + c] @ ds) \\<sha> ys\"\n\n    have zs'_split: \"zs' = take_left (length as) zs' @ [Inl (b + c)] @ tl (drop_left (length as) zs')\"\n      by (rule lefts_insert, insert zs'_set, simp_all add: tshuffle_words_def)\n\n    from zs'_set have \"take_left (length as) zs' @ [Inl b] @ [Inl c] @ tl (drop_left (length as) zs') \\<in> (as @ [b] @ [c] @ ds) \\<sha> ys\"\n      apply (auto simp add: tshuffle_words_def)\n      apply (metis drop_lefts_is_append take_lefts_is_append)\n      by (metis delete_left_def delete_left_rights right_append)\n\n    then obtain zs where zs_set: \"zs \\<in> xs \\<sha> ys\"\n    and \"map \\<langle>id,id\\<rangle> (take_left (length as) zs' @ [Inl b] @ [Inl c] @ tl (drop_left (length as) zs')) \\<in> sm_set (map \\<langle>id,id\\<rangle> zs)\"\n      by (metis ih)\n\n    hence \"map \\<langle>id,id\\<rangle> (take_left (length as) zs') @ [b] @ [c] @ map \\<langle>id,id\\<rangle> (tl (drop_left (length as) zs')) \\<in> sm_set (map \\<langle>id,id\\<rangle> zs)\"\n      by simp\n\n    hence \"map \\<langle>id,id\\<rangle> (take_left (length as) zs') @ [b + c] @ map \\<langle>id,id\\<rangle> (tl (drop_left (length as) zs')) \\<in> sm_set (map \\<langle>id,id\\<rangle> zs)\"\n      by (metis sm_set.mumble)\n\n    hence \"map \\<langle>id,id\\<rangle> (take_left (length as) zs' @ [Inl (b + c)] @ tl (drop_left (length as) zs')) \\<in> sm_set (map \\<langle>id,id\\<rangle> zs)\"\n      by simp\n\n    hence \"map \\<langle>id,id\\<rangle> zs' \\<in> sm_set (map \\<langle>id,id\\<rangle> zs)\"\n      by (metis zs'_split)\n\n    thus \"\\<exists>zs\\<in>xs \\<sha> ys. map \\<langle>id,id\\<rangle> zs' \\<in> sm_set (map \\<langle>id,id\\<rangle> zs)\"\n      by (metis zs_set)\n  qed\nqed\n\nlemma shuffle_sm: \"X\\<^sup>\\<ddagger> \\<parallel> Y \\<subseteq> (X \\<parallel> Y)\\<^sup>\\<ddagger>\"\nproof -\n  have \"X\\<^sup>\\<ddagger> \\<parallel> Y = \\<Union>sm_set ` X \\<parallel> Y\"\n    by (simp add: sm_closure_def)\n  also have \"... = \\<Union>{sm_set xs \\<parallel> Y|xs. xs \\<in> X}\"\n    by (subst shuffle_inf_distr) (auto simp add: image_def)\n  also have \"... = \\<Union>{\\<Union>{map \\<langle>id,id\\<rangle> ` (xs' \\<sha> ys) |xs' ys. xs' \\<in> sm_set xs \\<and> ys \\<in> Y}|xs. xs \\<in> X}\"\n    by (simp add: shuffle_def)\n  also have \"... = \\<Union>{\\<Union>{map \\<langle>id,id\\<rangle> ` (xs' \\<sha> ys) |xs'. xs' \\<in> sm_set xs}|xs ys. xs \\<in> X \\<and> ys \\<in> Y}\"\n    by blast\n  also have \"... \\<subseteq> \\<Union>{(map \\<langle>id,id\\<rangle> ` (xs \\<sha> ys))\\<^sup>\\<ddagger>|xs ys. xs \\<in> X \\<and> ys \\<in> Y}\"\n    by (insert tshuffle_sm) blast\n  also have \"... = \\<Union>{\\<Union>zs\\<in>xs \\<sha> ys. sm_set (map \\<langle>id,id\\<rangle> zs)|xs ys. xs \\<in> X \\<and> ys \\<in> Y}\"\n    by (simp add: sm_closure_def)\n  also have \"... = (X \\<parallel> Y)\\<^sup>\\<ddagger>\"\n    by (auto simp add: shuffle_def sm_closure_def)\n  finally show ?thesis .\nqed\n\nlemma tshuffle_sm2: \"(map \\<langle>id,id\\<rangle> ` (xs \\<sha> ys))\\<^sup>\\<ddagger> \\<subseteq> (\\<Union>{map \\<langle>id,id\\<rangle> ` (xs \\<sha> ys')|ys'. ys' \\<in> sm_set ys})\\<^sup>\\<ddagger>\"\nproof -\n  have  \"(map \\<langle>id,id\\<rangle> ` (xs \\<sha> []))\\<^sup>\\<ddagger> \\<subseteq> (\\<Union>{map \\<langle>id,id\\<rangle> ` (xs \\<sha> ys')|ys'. ys' \\<in> sm_set []})\\<^sup>\\<ddagger>\"\n    apply (auto simp add: sm_closure_def)\n    apply (rule_tac x = \"map \\<langle>id,id\\<rangle> ` (xs \\<sha> [0])\" in exI)\n    apply (intro conjI)\n    defer\n    apply (rule_tac x = \"map \\<langle>id,id\\<rangle> (Inr 0 # map Inl xs)\" in bexI)\n    apply simp\n    apply (metis sm_set_cons_unit)\n    defer\n    apply (rule_tac x = \"[0]\" in exI)\n    apply simp\n    apply (metis sm_set.self)\n    apply (auto simp add: tshuffle_words_def image_def)\n    apply (rule_tac x = \"Inr 0 # map Inl xs\" in exI)\n    by simp\n\n  moreover {\n    fix y ys\n    have \"(map \\<langle>id,id\\<rangle> ` (xs \\<sha> (y#ys)))\\<^sup>\\<ddagger> \\<subseteq> (\\<Union>{map \\<langle>id,id\\<rangle> ` (xs \\<sha> ys')|ys'. ys' \\<in> sm_set (y#ys)})\\<^sup>\\<ddagger>\"\n      apply (auto simp add: sm_closure_def)\n      apply (rule_tac x = \"map \\<langle>id,id\\<rangle> ` (xs \\<sha> (y#ys))\" in exI)\n      apply (intro conjI)\n      defer\n      apply (rule_tac x = \"map \\<langle>id,id\\<rangle> a\" in bexI)\n      apply simp\n      apply (metis image_iff)\n      apply (rule_tac x = \"y#ys\" in exI)\n      apply simp\n      by (metis sm_set_self_var)\n  }\n\n  ultimately show ?thesis\n    by (cases ys) auto\nqed\n\nlemma shuffle_sm_var: \"(X \\<parallel> Y)\\<^sup>\\<ddagger> \\<subseteq> (X \\<parallel> Y\\<^sup>\\<ddagger>)\\<^sup>\\<ddagger>\"\nproof -\n  have \"(X \\<parallel> Y)\\<^sup>\\<ddagger> = \\<Union>sm_set ` (X \\<parallel> Y)\"\n    by (simp add: sm_closure_def)\n  also have \"... = \\<Union>sm_set ` \\<Union>{map \\<langle>id,id\\<rangle> ` (xs \\<sha> ys)|xs ys. xs \\<in> X \\<and> ys \\<in> Y}\"\n    by (simp add: shuffle_def)\n  also have \"... = \\<Union>{\\<Union>sm_set ` map \\<langle>id,id\\<rangle> ` (xs \\<sha> ys)|xs ys. xs \\<in> X \\<and> ys \\<in> Y}\"\n    by (auto simp add: image_def)\n  also have \"... = \\<Union>{(map \\<langle>id,id\\<rangle> ` (xs \\<sha> ys))\\<^sup>\\<ddagger>|xs ys. xs \\<in> X \\<and> ys \\<in> Y}\"\n    by (auto simp add: sm_closure_def)\n  also have \"... \\<subseteq> \\<Union>{(\\<Union>{map \\<langle>id,id\\<rangle> ` (xs \\<sha> ys')|ys'. ys' \\<in> sm_set ys})\\<^sup>\\<ddagger>|xs ys. xs \\<in> X \\<and> ys \\<in> Y}\"\n    by (insert tshuffle_sm2) blast\n  also have \"... = \\<Union>{\\<Union>sm_set ` \\<Union>{map \\<langle>id,id\\<rangle> ` (xs \\<sha> ys') |ys'. ys' \\<in> sm_set ys} |xs ys. xs \\<in> X \\<and> ys \\<in> Y}\"\n    by (simp only: sm_closure_def)\n  also have \"... = \\<Union>sm_set ` \\<Union>{map \\<langle>id,id\\<rangle> ` (xs \\<sha> ys)|xs ys. xs \\<in> X \\<and> ys \\<in> \\<Union>(sm_set ` Y)}\"\n    by (simp add: image_def) blast\n  also have \"... = (\\<Union>{map \\<langle>id,id\\<rangle> ` (xs \\<sha> ys)|xs ys. xs \\<in> X \\<and> ys \\<in> Y\\<^sup>\\<ddagger>})\\<^sup>\\<ddagger>\"\n    by (simp add: sm_closure_def)\n  also have \"... = (X \\<parallel> Y\\<^sup>\\<ddagger>)\\<^sup>\\<ddagger>\"\n    by (simp add: shuffle_def)\n  finally show ?thesis .\nqed\n\nlemma shuffle_closure: \"X \\<parallel>\\<^sup>\\<ddagger> Y = X\\<^sup>\\<ddagger> \\<parallel>\\<^sup>\\<ddagger> Y\\<^sup>\\<ddagger>\"\n  by (metis (hide_lams, no_types) shuffle_comm shuffle_sm shuffle_sm_var sm_closure_idem sm_closure_iso sm_shuffle_def subset_antisym)\n\nlemma sm_shuffle_assoc: \"(X \\<parallel>\\<^sup>\\<ddagger> Y) \\<parallel>\\<^sup>\\<ddagger> Z = X \\<parallel>\\<^sup>\\<ddagger> (Y \\<parallel>\\<^sup>\\<ddagger> Z)\"\n  by (metis (hide_lams, no_types) shuffle_assoc shuffle_closure sm_closure_idem sm_shuffle_def)\n\nlemma sm_shuffle_comm: \"X \\<parallel>\\<^sup>\\<ddagger> Y = Y \\<parallel>\\<^sup>\\<ddagger> X\"\n  by (metis sm_shuffle_def shuffle_comm)\n\nlemma sm_exchange: \"(A \\<parallel>\\<^sup>\\<ddagger> B) \\<cdot>\\<^sup>\\<ddagger> (C \\<parallel>\\<^sup>\\<ddagger> D) \\<subseteq> (B \\<cdot>\\<^sup>\\<ddagger> C) \\<parallel>\\<^sup>\\<ddagger> (A \\<cdot>\\<^sup>\\<ddagger> D)\"\n  by (metis (hide_lams, no_types) exchange shuffle_closure sm_closure_iso sm_l_prod_closure sm_l_prod_def sm_shuffle_def)\n\nlemma sm_par_iso: \"X \\<subseteq> Y \\<Longrightarrow> X \\<parallel>\\<^sup>\\<ddagger> Z \\<subseteq> Y \\<parallel>\\<^sup>\\<ddagger> Z\"\n  by (metis sm_shuffle_def sm_closure_iso shuffle_iso)\n\nlemma atomic_sm_closure: \"\\<langle>X\\<rangle> = \\<langle>X\\<^sup>\\<ddagger>\\<rangle>\"\n  apply (auto simp add: atomic_def sm_closure_def)\n  apply (metis listsum_simps(2) monoid_add_class.add.left_neutral sm_set.self)\n  by (metis sm_set_listsum sm_set_trans)\n\nlemma atomic_l_prod: \"\\<langle>X \\<cdot> Y\\<rangle> = \\<langle>X \\<cdot>\\<^sup>\\<ddagger> Y\\<rangle>\"\n  by (metis atomic_sm_closure sm_l_prod_def)\n\nlemma atomic_split_l_prod: \"\\<langle>X \\<cdot> Y\\<rangle> \\<subseteq> \\<langle>X\\<rangle> \\<cdot>\\<^sup>\\<ddagger> \\<langle>Y\\<rangle>\"\nproof -\n  have \"\\<langle>X \\<cdot> Y\\<rangle> = {[listsum (x @ y)]|x y. x \\<in> X \\<and> y \\<in> Y}\\<^sup>\\<ddagger>\"\n    apply (simp add: l_prod_def complex_product_def atomic_def)\n    apply (rule arg_cong) back\n    by (auto, metis, metis listsum_append)\n  also have \"... \\<subseteq> {[listsum x] @ [listsum y]|x y. x \\<in> X \\<and> y \\<in> Y}\\<^sup>\\<ddagger>\"\n  proof (auto simp add: sm_closure_def)\n    fix x y z\n    assume \"z \\<in> sm_set [listsum x + listsum y]\" and xX: \"x \\<in> X\" and yY: \"y \\<in> Y\"\n    hence \"z \\<in> sm_set [listsum (x @ y)]\"\n      by (metis listsum_append)\n    hence \"z \\<in> sm_set ([listsum x, listsum y])\"\n      apply (induct z rule: sm_set.induct)\n      apply (metis listsum_append sm_set.self sm_set_pair sm_set_trans)\n      apply (metis sm_set.stutter)\n      by (metis sm_set.mumble)\n    thus \"\\<exists>z'. (\\<exists>x y. z' = [listsum x, listsum y] \\<and> x \\<in> X \\<and> y \\<in> Y) \\<and> z \\<in> sm_set z'\"\n      by (metis xX yY)\n  qed\n  also have \"... = {x @ y |x y. x \\<in> {[listsum x] |x. x \\<in> X} \\<and> y \\<in> {[listsum x] |x. x \\<in> Y}}\\<^sup>\\<ddagger>\"\n    by (rule arg_cong, blast)\n  also have \"... \\<subseteq> \\<langle>X\\<rangle> \\<cdot>\\<^sup>\\<ddagger> \\<langle>Y\\<rangle>\"\n    by (simp only: atomic_def) (metis (no_types) complex_product_def eq_iff l_prod_def sm_l_prod_closure sm_l_prod_def)\n  finally show ?thesis .\nqed\n\nlemma atomic_l_prod_idem: \"\\<langle>X \\<cdot> \\<langle>Y\\<rangle> \\<cdot> Z\\<rangle> = \\<langle>X \\<cdot> Y \\<cdot> Z\\<rangle>\"\nproof\n  have \"\\<langle>X \\<cdot> \\<langle>Y\\<rangle> \\<cdot> Z\\<rangle> \\<subseteq> \\<langle>X \\<cdot> Y\\<^sup>\\<ddagger> \\<cdot> Z\\<rangle>\"\n    by (metis atomic_sm_closure atomic_iso l_prod_isol l_prod_isor atomic_coextensive)\n  also have \"... =  \\<langle>X \\<cdot> Y \\<cdot> Z\\<rangle>\"\n    by (metis (hide_lams, no_types) atomic_l_prod sm_closure_idem sm_l_prod_closure sm_l_prod_def)\n  finally show \"\\<langle>X \\<cdot> \\<langle>Y\\<rangle> \\<cdot> Z\\<rangle> \\<subseteq> \\<langle>X \\<cdot> Y \\<cdot> Z\\<rangle>\" .\n\n  have \"\\<langle>X \\<cdot> Y \\<cdot> Z\\<rangle> = \\<langle>\\<langle>X \\<cdot> Y \\<cdot> Z\\<rangle>\\<rangle>\"\n    by (metis atomic_idem)\n  also have \"... = \\<langle>\\<langle>X\\<^sup>\\<ddagger> \\<cdot> Y\\<^sup>\\<ddagger> \\<cdot> Z\\<^sup>\\<ddagger>\\<rangle>\\<rangle>\"\n    by (metis (hide_lams, no_types) atomic_sm_closure sm_closure_idem sm_l_prod_closure sm_l_prod_def)\n  also have \"... \\<subseteq> \\<langle>\\<langle>X\\<^sup>\\<ddagger> \\<cdot> Y\\<^sup>\\<ddagger>\\<rangle> \\<cdot>\\<^sup>\\<ddagger> \\<langle>Z\\<^sup>\\<ddagger>\\<rangle>\\<rangle>\"\n    by (metis atomic_iso atomic_split_l_prod)\n  also have \"... \\<subseteq> \\<langle>\\<langle>X\\<^sup>\\<ddagger>\\<rangle> \\<cdot>\\<^sup>\\<ddagger> \\<langle>Y\\<^sup>\\<ddagger>\\<rangle> \\<cdot>\\<^sup>\\<ddagger> \\<langle>Z\\<^sup>\\<ddagger>\\<rangle>\\<rangle>\"\n    by (metis (mono_tags) atomic_iso atomic_sm_closure atomic_split_l_prod l_prod_isol sm_l_prod_def)\n  also have \"... = \\<langle>\\<langle>X\\<^sup>\\<ddagger>\\<rangle> \\<cdot> \\<langle>Y\\<^sup>\\<ddagger>\\<rangle> \\<cdot> \\<langle>Z\\<^sup>\\<ddagger>\\<rangle>\\<rangle>\"\n    by (metis (hide_lams, no_types) atomic_sm_closure sm_closure_idem sm_l_prod_closure sm_l_prod_def)\n  also have \"... \\<subseteq> \\<langle>X\\<^sup>\\<ddagger> \\<cdot> \\<langle>Y\\<^sup>\\<ddagger>\\<rangle> \\<cdot> Z\\<^sup>\\<ddagger>\\<rangle>\"\n    by (metis (hide_lams, no_types) atomic_coextensive atomic_iso l_prod_isol l_prod_isor order_trans)\n  also have \"... = \\<langle>X \\<cdot> \\<langle>Y\\<rangle> \\<cdot> Z\\<rangle>\"\n    by (metis (hide_lams, no_types) atomic_sm_closure sm_closure_idem sm_l_prod_closure sm_l_prod_def)\n  finally show \"\\<langle>X \\<cdot> Y \\<cdot> Z\\<rangle> \\<subseteq> \\<langle>X \\<cdot> \\<langle>Y\\<rangle> \\<cdot> Z\\<rangle>\" .\nqed\n\nlemma atomic_union: \"\\<langle>X \\<union> Y\\<rangle> = \\<langle>X\\<rangle> \\<union> \\<langle>Y\\<rangle>\"\n  by (auto simp add: atomic_def sm_closure_def)\n\nlemma sm_join_preserving: \"\\<Union>{X\\<^sup>\\<ddagger>|X. X \\<in> \\<XX>} = (\\<Union>\\<XX>)\\<^sup>\\<ddagger>\"\n  by (auto simp add: sm_closure_def)\n\nlemma sm_join_preserving_var: \"\\<Union>{(f X)\\<^sup>\\<ddagger>|X. X \\<in> \\<XX>} = (\\<Union>f`\\<XX>)\\<^sup>\\<ddagger>\"\n  by (auto simp add: sm_closure_def)\n\nlemma sm_shuffle_inf_distl: \"X \\<parallel>\\<^sup>\\<ddagger> \\<Union>\\<YY> = \\<Union>{X \\<parallel>\\<^sup>\\<ddagger> Y|Y. Y \\<in> \\<YY>}\"\nproof -\n  have \"X \\<parallel>\\<^sup>\\<ddagger> \\<Union>\\<YY> = (\\<Union>{X \\<parallel> Y|Y. Y \\<in> \\<YY>})\\<^sup>\\<ddagger>\"\n    by (metis shuffle_inf_distl sm_shuffle_def)\n  also have \"... = \\<Union>{X \\<parallel>\\<^sup>\\<ddagger> Y|Y. Y \\<in> \\<YY>}\"\n    by (simp add: sm_shuffle_def sm_join_preserving_var, rule arg_cong, blast)\n  finally show ?thesis .\nqed\n\nlemma sm_shuffle_inf_distr: \"\\<Union>\\<XX> \\<parallel>\\<^sup>\\<ddagger> Y = \\<Union>{X \\<parallel>\\<^sup>\\<ddagger> Y|X. X \\<in> \\<XX>}\"\n  by (subst sm_shuffle_comm, subst sm_shuffle_comm, rule sm_shuffle_inf_distl)\n\nlemma sm_l_prod_inf_distl: \"X \\<cdot>\\<^sup>\\<ddagger> \\<Union>\\<YY> = \\<Union>{X \\<cdot>\\<^sup>\\<ddagger> Y|Y. Y \\<in> \\<YY>}\"\nproof -\n  have \"X \\<cdot>\\<^sup>\\<ddagger> \\<Union>\\<YY> = (\\<Union>{X \\<cdot> Y|Y. Y \\<in> \\<YY>})\\<^sup>\\<ddagger>\"\n    by (metis l_prod_inf_distl sm_l_prod_def)\n  also have \"... = \\<Union>{X \\<cdot>\\<^sup>\\<ddagger> Y|Y. Y \\<in> \\<YY>}\"\n    by (simp add: sm_l_prod_def sm_join_preserving_var, rule arg_cong, blast)\n  finally show ?thesis .\nqed\n\nlemma sm_l_prod_inf_distr: \"\\<Union>\\<XX> \\<cdot>\\<^sup>\\<ddagger> Y = \\<Union>{X \\<cdot>\\<^sup>\\<ddagger> Y|X. X \\<in> \\<XX>}\"\nproof -\n  have \"\\<Union>\\<XX> \\<cdot>\\<^sup>\\<ddagger> Y = (\\<Union>{X \\<cdot> Y|X. X \\<in> \\<XX>})\\<^sup>\\<ddagger>\"\n    by (metis l_prod_inf_distr sm_l_prod_def)\n  also have \"... = \\<Union>{X \\<cdot>\\<^sup>\\<ddagger> Y|X. X \\<in> \\<XX>}\"\n    by (simp add: sm_l_prod_def sm_join_preserving_var, rule arg_cong, blast)\n  finally show ?thesis .\nqed\n\nlemma sm_shuffle_one [simp]: shows \"\\<one> \\<parallel>\\<^sup>\\<ddagger> X = X\\<^sup>\\<ddagger>\" and \"X \\<parallel>\\<^sup>\\<ddagger> \\<one> = X\\<^sup>\\<ddagger>\"\nproof -\n  have \"\\<one> \\<parallel>\\<^sup>\\<ddagger> X = ({[]}\\<^sup>\\<ddagger> \\<parallel> X)\\<^sup>\\<ddagger>\"\n    by (simp add: sm_shuffle_def sm_one_def)\n  also have \"... = ({[]} \\<parallel> X)\\<^sup>\\<ddagger>\"\n    by (metis (hide_lams, no_types) shuffle_closure sm_closure_idem sm_shuffle_def)\n  also have \"... = X\\<^sup>\\<ddagger>\"\n    by (metis shuffle_one(2))\n  finally show \"\\<one> \\<parallel>\\<^sup>\\<ddagger> X = X\\<^sup>\\<ddagger>\" . \n\n  thus \"X \\<parallel>\\<^sup>\\<ddagger> \\<one> = X\\<^sup>\\<ddagger>\"\n    by (metis sm_shuffle_comm)\nqed\n\nlemma sm_zero [simp]: \"{}\\<^sup>\\<ddagger> = {}\"\n  by (auto simp add: sm_closure_def)\n\nlemma sm_shuffle_zero [simp]: shows \"{} \\<parallel>\\<^sup>\\<ddagger> X = {}\" and \"X \\<parallel>\\<^sup>\\<ddagger> {} = {}\"\nproof -\n  show \"{} \\<parallel>\\<^sup>\\<ddagger> X = {}\"\n    by (simp add: sm_shuffle_def)\n\n  thus \"X \\<parallel>\\<^sup>\\<ddagger> {} = {}\"\n    by (metis sm_shuffle_comm)\nqed\n\nlemma atomic_one [simp]: \"\\<langle>\\<one>\\<rangle> = \\<one>\"\nproof -\n  have \"\\<one> \\<subseteq> \\<langle>\\<one>\\<rangle>\"\n    apply (auto simp add: atomic_def sm_one_def sm_closure_def)\n    apply (rule_tac x = \"[0]\" in exI)\n    apply auto\n    apply (rule_tac x = \"[0]\" in exI)\n    apply (metis append_Nil listsum_append listsum_simps(1) listsum_simps(2) sm_set.self)\n    by (metis sm_set_cons_unit)\n\n  thus \"\\<langle>\\<one>\\<rangle> = \\<one>\"\n    by (metis atomic_coextensive sm_one_def subset_antisym)\nqed\n\nlemma sm_set_self_replicate [intro]: \"replicate (Suc n) 0 @ xs \\<in> sm_set xs\"\n  by (induct n, auto) (metis sm_set.self sm_set_trans)\n\nlemma sm_set_self_replicate_rev [intro]: \"xs @ replicate (Suc n) 0 \\<in> sm_set xs\"\n  by (induct n, auto) (metis append_Cons eq_Nil_appendI sm_set.stutter)\n\nlemma replicate_range: \"xs \\<in> range (\\<lambda>n. replicate (f n) x) \\<Longrightarrow> xs = replicate (length xs) x\"\n  by (metis (mono_tags) length_replicate rangeE)\n\nlemma replicate_head: \"x # xs = replicate n y \\<Longrightarrow> x = y\"\n  by (metis hd.simps hd_replicate list.distinct(1) replicate_0)\n\nlemma replicate_rev: \"x # xs = replicate n y \\<Longrightarrow> x # xs = xs @ [x]\"\n  apply (induct xs)\n  apply auto\n  by (metis Cons_eq_appendI append_Nil2 hd.simps replicate_app_Cons_same tl.simps(2))\n\nlemma replicate_append_rev: \"xs @ ys = replicate n x \\<Longrightarrow> xs @ ys = ys @ xs\"\n  apply (induct xs arbitrary: ys)\n  apply auto\n  by (metis append_Cons append_assoc eq_Nil_appendI replicate_rev)\n\nlemma sm_set_empty_def: \"sm_set [] = range (\\<lambda>n. replicate (Suc n) 0)\"\nproof (auto simp del: replicate_Suc)\n  fix xs :: \"'a list\"\n  assume \"xs \\<in> sm_set []\"\n  thus \"xs \\<in> range (\\<lambda>n. replicate (Suc n) 0)\"\n  proof (induct xs rule: sm_set.induct)\n    show \"[0] \\<in> range (\\<lambda>n. replicate (Suc n) 0)\"\n      by simp\n  next\n    fix as bs :: \"'a list\"\n    assume \"as @ bs \\<in> range (\\<lambda>n. replicate (Suc n) 0)\"\n    hence \"as @ bs = replicate (length (as @ bs)) 0\"\n      by (induct as, auto) (metis length_append length_replicate)\n    hence \"as = replicate (length as) 0 \\<and> bs = replicate (length bs) 0\"\n      by (simp add: replicate_add)\n    thus \"as @ [0] @ bs \\<in> range (\\<lambda>n. replicate (Suc n) 0)\"\n      apply simp\n      apply clarify\n      apply (erule ssubst)+\n      apply (subst replicate_Suc[symmetric])\n      apply (subst replicate_add[symmetric])\n      by auto\n  next\n    fix bs cs :: 'a and as ds :: \"'a list\"\n    assume \"as @ [bs] @ [cs] @ ds \\<in> range (\\<lambda>n. replicate (Suc n) 0)\"\n    hence rep: \"as @ [bs] @ [cs] @ ds = replicate (length (as @ [bs] @ [cs] @ ds)) 0\"\n      by (metis replicate_range)\n    {\n      from rep have \"as @ [bs] @ [cs] @ ds = ([bs] @ [cs] @ ds) @ as\"\n        by (metis replicate_append_rev)\n      also have \"... = [bs] @ [cs] @ ds @ as\"\n        by (metis append_assoc)\n      finally have \"as @ [bs] @ [cs] @ ds = [bs] @ [cs] @ ds @ as\" .\n      moreover from rep and this have \"... = [bs] @ [cs] @ as @ ds\"\n        apply (subgoal_tac \"as @ ds = replicate (length (as @ ds)) 0\")\n        apply simp\n        apply simp\n        apply clarify\n        by (metis replicate_append_rev)\n      ultimately have \"[bs] @ [cs] @ as @ ds = replicate (length (as @ [bs] @ [cs] @ ds)) 0\" using rep\n        by metis\n    }\n    hence \"as = replicate (length as) 0 \\<and> bs = 0 \\<and> cs = 0 \\<and> ds = replicate (length ds) 0\"\n      by (simp add: replicate_add)\n    thus \"as @ [bs + cs] @ ds \\<in> range (\\<lambda>n. replicate (Suc n) 0)\"\n      apply clarify\n      apply (erule ssubst)+\n      apply simp\n      apply (subst replicate_Suc[symmetric])\n      apply (subst replicate_add[symmetric])\n      by auto\n  qed\nnext\n  fix n\n  show \"replicate (Suc n) 0 \\<in> sm_set []\"\n    by (induct n, auto) (metis sm_set.self sm_set_trans)\nqed\n\nhide_fact replicate_range replicate_head replicate_rev replicate_append_rev\n\nlemmas sm_one_replicate = trans[OF sm_set_one sm_set_empty_def]\n\nlemma sm_l_prod_one [simp]: shows \"\\<one> \\<cdot>\\<^sup>\\<ddagger> X = X\\<^sup>\\<ddagger>\" and \"X \\<cdot>\\<^sup>\\<ddagger> \\<one> = X\\<^sup>\\<ddagger>\"\nproof -\n  have \"\\<one> \\<cdot>\\<^sup>\\<ddagger> X = (range (\\<lambda>n. replicate (Suc n) 0) \\<cdot> X)\\<^sup>\\<ddagger>\"\n    by (simp add: sm_l_prod_def sm_one_replicate)\n  also have \"... = {u @ xs|u xs. u \\<in> range (\\<lambda>n. replicate (Suc n) 0) \\<and> xs \\<in> X}\\<^sup>\\<ddagger>\"\n    by (simp add: l_prod_def complex_product_def)\n  also have \"... = {replicate (Suc n) 0 @ xs|n xs. n \\<in> UNIV \\<and> xs \\<in> X}\\<^sup>\\<ddagger>\"\n    by (metis (lifting) UNIV_I rangeE rev_image_eqI)\n  finally have \"\\<one> \\<cdot>\\<^sup>\\<ddagger> X = {replicate (Suc n) 0 @ xs|n xs. n \\<in> UNIV \\<and> xs \\<in> X}\\<^sup>\\<ddagger>\" .\n\n  moreover have \"{replicate (Suc n) 0 @ xs|n xs. n \\<in> UNIV \\<and> xs \\<in> X}\\<^sup>\\<ddagger> \\<subseteq> X\\<^sup>\\<ddagger>\"\n    by (auto simp add: sm_closure_def) (metis append_Cons replicate_Suc sm_set_self_replicate sm_set_trans)\n  moreover have \"X\\<^sup>\\<ddagger> \\<subseteq> {replicate (Suc n) 0 @ xs|n xs. n \\<in> UNIV \\<and> xs \\<in> X}\\<^sup>\\<ddagger>\"\n    by (auto simp add: sm_closure_def) (metis append_self_conv2 replicate_0 sm_set_cons_unit)\n  ultimately show \"\\<one> \\<cdot>\\<^sup>\\<ddagger> X = X\\<^sup>\\<ddagger>\"\n    by auto\n\n  have \"X \\<cdot>\\<^sup>\\<ddagger> \\<one> = (X \\<cdot> range (\\<lambda>n. replicate (Suc n) 0))\\<^sup>\\<ddagger>\"\n    by (simp add: sm_l_prod_def sm_one_replicate)\n  also have \"... = {xs @ u|xs u. xs \\<in> X \\<and> u \\<in> range (\\<lambda>n. replicate (Suc n) 0)}\\<^sup>\\<ddagger>\"\n    by (simp add: l_prod_def complex_product_def)\n  also have \"... = {xs @ replicate (Suc n) 0|xs n. xs \\<in> X \\<and> n \\<in> UNIV}\\<^sup>\\<ddagger>\"\n    by (metis (lifting) UNIV_I rangeE rev_image_eqI)\n  finally have \"X \\<cdot>\\<^sup>\\<ddagger> \\<one> = {xs @ replicate (Suc n) 0|xs n. xs \\<in> X \\<and> n \\<in> UNIV}\\<^sup>\\<ddagger>\" .\n\n  moreover have \"{xs @ replicate (Suc n) 0|xs n. xs \\<in> X \\<and> n \\<in> UNIV}\\<^sup>\\<ddagger> \\<subseteq> X\\<^sup>\\<ddagger>\"\n    by (auto simp add: sm_closure_def) (metis replicate_Suc sm_set_self_replicate_rev sm_set_trans)\n  moreover have \"X\\<^sup>\\<ddagger> \\<subseteq> {xs @ replicate (Suc n) 0|xs n. xs \\<in> X \\<and> n \\<in> UNIV}\\<^sup>\\<ddagger>\"\n    by (auto simp add: sm_closure_def) (metis append_Nil2 replicate_0 sm_set_unit)\n  ultimately show \"X \\<cdot>\\<^sup>\\<ddagger> \\<one> = X\\<^sup>\\<ddagger>\"\n    by auto\nqed\n\n\nsubsection {* Star for stutter/mumble closed languages *}\n\nprimrec sm_l_power :: \"'a::monoid_add lan \\<Rightarrow> nat \\<Rightarrow> 'a lan\" where\n  \"sm_l_power X 0 = \\<one>\"\n| \"sm_l_power X (Suc n) = X \\<cdot>\\<^sup>\\<ddagger> X\\<^bsup>n\\<^esup>\"\n\nlemma sm_l_power_to_l_power: \"sm_l_power X n = (X\\<^bsup>n\\<^esup>)\\<^sup>\\<ddagger>\"\n  by (induct n) (simp_all add: sm_one_def sm_l_prod_def)\n\nlemma sm_l_star_to_l_star: \"\\<Union>range (sm_l_power X) = (X\\<^sup>*)\\<^sup>\\<ddagger>\"\n  by (simp add: l_star_def sm_l_power_to_l_power sm_closure_def)\n\nlemma sm_l_star_unfoldl: \"\\<one> \\<union> X\\<cdot>\\<^sup>\\<ddagger>(X\\<^sup>*)\\<^sup>\\<ddagger> \\<subseteq> (X\\<^sup>*)\\<^sup>\\<ddagger>\"\n  by (metis (hide_lams, no_types) l_star_unfoldl le_sup_iff sm_closure_idem sm_closure_iso sm_l_prod_closure sm_l_prod_def sm_one_def)\n\nlemma sm_l_star_unfoldr: \"\\<one> \\<union> (X\\<^sup>*)\\<^sup>\\<ddagger>\\<cdot>\\<^sup>\\<ddagger>X \\<subseteq> (X\\<^sup>*)\\<^sup>\\<ddagger>\"\n  by (metis (hide_lams, no_types) l_star_unfoldr le_sup_iff sm_closure_idem sm_closure_iso sm_l_prod_closure sm_l_prod_def sm_one_def)\n\nlemma sm_l_power_inductl: \"Z\\<^sup>\\<ddagger> \\<union> X\\<cdot>\\<^sup>\\<ddagger>Y \\<subseteq> Y\\<^sup>\\<ddagger> \\<Longrightarrow> X\\<^bsup>n\\<^esup>\\<cdot>\\<^sup>\\<ddagger>Z \\<subseteq> Y\\<^sup>\\<ddagger>\"\nproof (induct n arbitrary: Z, simp_all add: sm_l_prod_def l_power_def_var del: l_power.simps(2))\n  fix n Z\n  assume ih: \"\\<And>Z. Z\\<^sup>\\<ddagger> \\<subseteq> Y\\<^sup>\\<ddagger> \\<Longrightarrow> (X\\<^bsup>n\\<^esup> \\<cdot> Z)\\<^sup>\\<ddagger> \\<subseteq> Y\\<^sup>\\<ddagger>\"\n  and asm: \"Z\\<^sup>\\<ddagger> \\<subseteq> Y\\<^sup>\\<ddagger> \\<and> (X \\<cdot> Y)\\<^sup>\\<ddagger> \\<subseteq> Y\\<^sup>\\<ddagger>\"\n  hence \"(X \\<cdot> Z)\\<^sup>\\<ddagger> = (X\\<^sup>\\<ddagger> \\<cdot> Z\\<^sup>\\<ddagger>)\\<^sup>\\<ddagger>\"\n    by (metis sm_l_prod_closure sm_l_prod_def)\n  also have \"... \\<subseteq> (X\\<^sup>\\<ddagger> \\<cdot> Y\\<^sup>\\<ddagger>)\\<^sup>\\<ddagger>\"\n    by (metis asm l_prod_isor sm_closure_iso)\n  also have \"... = (X \\<cdot> Y)\\<^sup>\\<ddagger>\"\n    by (metis sm_l_prod_closure sm_l_prod_def)\n  also have \"... \\<subseteq> Y\\<^sup>\\<ddagger>\"\n    by (metis asm)\n  finally show \"(X\\<^bsup>n\\<^esup> \\<cdot> X \\<cdot> Z)\\<^sup>\\<ddagger> \\<subseteq> Y\\<^sup>\\<ddagger>\"\n    by (metis ih l_prod_assoc)\nqed\n\nlemma sm_l_star_inductl: \"Z\\<^sup>\\<ddagger> \\<union> X\\<cdot>\\<^sup>\\<ddagger>Y \\<subseteq> Y\\<^sup>\\<ddagger> \\<Longrightarrow> X\\<^sup>*\\<cdot>\\<^sup>\\<ddagger>Z \\<subseteq> Y\\<^sup>\\<ddagger>\"\nproof -\n  assume asm: \"Z\\<^sup>\\<ddagger> \\<union> X\\<cdot>\\<^sup>\\<ddagger>Y \\<subseteq> Y\\<^sup>\\<ddagger>\"\n  have \"\\<Union>range (\\<lambda>n. X\\<^bsup>n\\<^esup> \\<cdot>\\<^sup>\\<ddagger> Z) \\<subseteq> Y\\<^sup>\\<ddagger>\"\n    by (auto, metis asm in_mono sm_l_power_inductl)\n  moreover\n  {\n    have \"\\<Union>range (\\<lambda>n. X\\<^bsup>n\\<^esup> \\<cdot>\\<^sup>\\<ddagger> Z) = (\\<Union>range (\\<lambda>n. X\\<^bsup>n\\<^esup> \\<cdot> Z))\\<^sup>\\<ddagger>\"\n      by (auto simp only: sm_join_preserving[symmetric] sm_l_prod_def)\n    also have \"... = (\\<Union>range (l_power X) \\<cdot> Z)\\<^sup>\\<ddagger>\"\n      by (rule arg_cong, auto simp add: l_prod_def complex_product_def)\n    finally have \"\\<Union>range (\\<lambda>n. X\\<^bsup>n\\<^esup> \\<cdot>\\<^sup>\\<ddagger> Z) = X\\<^sup>*\\<cdot>\\<^sup>\\<ddagger>Z\"\n      by (metis l_star_def sm_l_prod_def)\n  }\n  ultimately show ?thesis by auto\nqed\n\nlemma sm_l_power_inductr: \"Z\\<^sup>\\<ddagger> \\<union> Y\\<cdot>\\<^sup>\\<ddagger>X \\<subseteq> Y\\<^sup>\\<ddagger> \\<Longrightarrow> Z\\<cdot>\\<^sup>\\<ddagger>X\\<^bsup>n\\<^esup> \\<subseteq> Y\\<^sup>\\<ddagger>\"\nproof (induct n arbitrary: Z, simp_all add: sm_l_prod_def)\n  fix n Z\n  assume ih: \"\\<And>Z. Z\\<^sup>\\<ddagger> \\<subseteq> Y\\<^sup>\\<ddagger> \\<Longrightarrow> (Z \\<cdot> X\\<^bsup>n\\<^esup>)\\<^sup>\\<ddagger> \\<subseteq> Y\\<^sup>\\<ddagger>\"\n  and asm: \"Z\\<^sup>\\<ddagger> \\<subseteq> Y\\<^sup>\\<ddagger> \\<and> (Y \\<cdot> X)\\<^sup>\\<ddagger> \\<subseteq> Y\\<^sup>\\<ddagger>\"\n  hence \"(Z \\<cdot> X)\\<^sup>\\<ddagger> = (Z\\<^sup>\\<ddagger> \\<cdot> X\\<^sup>\\<ddagger>)\\<^sup>\\<ddagger>\"\n    by (metis sm_l_prod_closure sm_l_prod_def)\n  also have \"... \\<subseteq> (Y\\<^sup>\\<ddagger> \\<cdot> X\\<^sup>\\<ddagger>)\\<^sup>\\<ddagger>\"\n    by (metis asm l_prod_isol sm_closure_iso)\n  also have \"... = (Y \\<cdot> X)\\<^sup>\\<ddagger>\"\n    by (metis sm_l_prod_closure sm_l_prod_def)\n  also have \"... \\<subseteq> Y\\<^sup>\\<ddagger>\"\n    by (metis asm)\n  finally show \"(Z \\<cdot> (X \\<cdot> X\\<^bsup>n\\<^esup>))\\<^sup>\\<ddagger> \\<subseteq> Y\\<^sup>\\<ddagger>\"\n    by (metis ih l_prod_assoc)\nqed\n\nlemma sm_l_star_inductr: \"Z\\<^sup>\\<ddagger> \\<union> Y\\<cdot>\\<^sup>\\<ddagger>X \\<subseteq> Y\\<^sup>\\<ddagger> \\<Longrightarrow> Z\\<cdot>\\<^sup>\\<ddagger>X\\<^sup>* \\<subseteq> Y\\<^sup>\\<ddagger>\"\nproof -\n  assume asm: \"Z\\<^sup>\\<ddagger> \\<union> Y\\<cdot>\\<^sup>\\<ddagger>X \\<subseteq> Y\\<^sup>\\<ddagger>\"\n  have \"\\<Union>range (\\<lambda>n. Z \\<cdot>\\<^sup>\\<ddagger> X\\<^bsup>n\\<^esup>) \\<subseteq> Y\\<^sup>\\<ddagger>\"\n    by (auto, metis asm in_mono sm_l_power_inductr)\n  moreover\n  {\n    have \"\\<Union>range (\\<lambda>n. Z \\<cdot>\\<^sup>\\<ddagger> X\\<^bsup>n\\<^esup>) = (\\<Union>range (\\<lambda>n. Z \\<cdot> X\\<^bsup>n\\<^esup>))\\<^sup>\\<ddagger>\"\n      by (auto simp only: sm_join_preserving[symmetric] sm_l_prod_def)\n    also have \"... = (Z \\<cdot> \\<Union>range (l_power X))\\<^sup>\\<ddagger>\"\n      by (rule arg_cong, auto simp add: l_prod_def complex_product_def)\n    finally have \"\\<Union>range (\\<lambda>n. Z \\<cdot>\\<^sup>\\<ddagger> X\\<^bsup>n\\<^esup>) = Z\\<cdot>\\<^sup>\\<ddagger>X\\<^sup>*\"\n      by (metis l_star_def sm_l_prod_def)\n  }\n  ultimately show ?thesis by auto\nqed\n\n\nsubsection {* Shuffle star for stutter/mumble closed languages *}\n\nprimrec sm_spawn :: \"'a::monoid_add lan \\<Rightarrow> nat \\<Rightarrow> 'a lan\" where\n  \"sm_spawn X 0 = \\<one>\"\n| \"sm_spawn X (Suc n) = X \\<parallel>\\<^sup>\\<ddagger> sm_spawn X n\"\n\nlemma sm_spawn_closure: \"sm_spawn X n = (spawn X n)\\<^sup>\\<ddagger>\"\n  apply (induct n)\n  apply (simp_all add: sm_one_def sm_shuffle_def)\n  by (metis shuffle_closure sm_closure_idem sm_shuffle_def)\n\nlemma sm_shuffle_star: \"\\<Union>range (sm_spawn X) = (X\\<^sup>\\<parallel>)\\<^sup>\\<ddagger>\"\n  apply (simp only: shuffle_star_def sm_join_preserving[symmetric])\n  by (auto simp add: sm_spawn_closure)\n\nlemma [intro]: \"sm_spawn X n \\<subseteq> (X\\<^sup>\\<parallel>)\\<^sup>\\<ddagger>\"\n  by (auto simp add: sm_shuffle_star[symmetric])\n\nlemma [simp]: \"(\\<Union>{X \\<parallel> Y|Y. Y \\<in> range (sm_spawn X)})\\<^sup>\\<ddagger> = \\<Union>range (\\<lambda>n. sm_spawn X (Suc n))\"\n  by (simp only: sm_join_preserving[symmetric], auto simp add: sm_shuffle_def)\n\nlemma sm_shuffle_star_unfoldl: \"\\<one> \\<union> X\\<parallel>\\<^sup>\\<ddagger>(X\\<^sup>\\<parallel>)\\<^sup>\\<ddagger> \\<subseteq> (X\\<^sup>\\<parallel>)\\<^sup>\\<ddagger>\"\n  apply (simp add: sm_shuffle_def)\n  apply (rule conjI)\n  apply (rule order_trans[where y = \"sm_spawn X 0\"])\n  apply simp\n  apply rule back\n  apply (simp only: sm_shuffle_star[symmetric] shuffle_inf_distl)\n  apply auto\n  apply (rule_tac x = \"Suc xa\" in exI)\n  by auto\n\nlemma sm_spawn_induct: \"Z\\<^sup>\\<ddagger> \\<union> X \\<parallel>\\<^sup>\\<ddagger> Y \\<subseteq> Y\\<^sup>\\<ddagger> \\<Longrightarrow> spawn X n \\<parallel>\\<^sup>\\<ddagger> Z \\<subseteq> Y\\<^sup>\\<ddagger>\"\nproof (induct n arbitrary: Z, simp_all add: sm_shuffle_def)\n  fix n Z\n  assume ih: \"\\<And>Z. Z\\<^sup>\\<ddagger> \\<subseteq> Y\\<^sup>\\<ddagger> \\<Longrightarrow> (spawn X n \\<parallel> Z)\\<^sup>\\<ddagger> \\<subseteq> Y\\<^sup>\\<ddagger>\"\n  and asm: \"Z\\<^sup>\\<ddagger> \\<subseteq> Y\\<^sup>\\<ddagger> \\<and> (X \\<parallel> Y)\\<^sup>\\<ddagger> \\<subseteq> Y\\<^sup>\\<ddagger>\"\n  hence \"(X \\<parallel> Z)\\<^sup>\\<ddagger> = (X\\<^sup>\\<ddagger> \\<parallel> Z\\<^sup>\\<ddagger>)\\<^sup>\\<ddagger>\"\n    by (metis shuffle_closure sm_shuffle_def)\n  also have \"... \\<subseteq> (X\\<^sup>\\<ddagger> \\<parallel> Y\\<^sup>\\<ddagger>)\\<^sup>\\<ddagger>\"\n    by (metis asm shuffle_comm shuffle_iso sm_closure_iso)\n  also have \"... = (X \\<parallel> Y)\\<^sup>\\<ddagger>\"\n    by (metis shuffle_closure sm_shuffle_def)\n  also have \"... \\<subseteq> Y\\<^sup>\\<ddagger>\"\n    by (metis asm)\n  finally show \"(X \\<parallel> spawn X n \\<parallel> Z)\\<^sup>\\<ddagger> \\<subseteq> Y\\<^sup>\\<ddagger>\"\n    by (metis (hide_lams, no_types) ih shuffle_assoc shuffle_comm)\nqed\n\nlemma sm_shuffle_star_inductl: \"Z\\<^sup>\\<ddagger> \\<union> X \\<parallel>\\<^sup>\\<ddagger> Y \\<subseteq> Y\\<^sup>\\<ddagger> \\<Longrightarrow> X\\<^sup>\\<parallel> \\<parallel>\\<^sup>\\<ddagger> Z \\<subseteq> Y\\<^sup>\\<ddagger>\"\nproof -\n  assume asm: \"Z\\<^sup>\\<ddagger> \\<union> X \\<parallel>\\<^sup>\\<ddagger> Y \\<subseteq> Y\\<^sup>\\<ddagger>\"\n  have \"\\<Union>range (\\<lambda>n. spawn X n \\<parallel>\\<^sup>\\<ddagger> Z) \\<subseteq> Y\\<^sup>\\<ddagger>\"\n    by (auto, metis asm in_mono sm_spawn_induct)\n  moreover\n  {\n    have \"\\<Union>range (\\<lambda>n. spawn X n \\<parallel>\\<^sup>\\<ddagger> Z) = (\\<Union>range (\\<lambda>n. spawn X n \\<parallel> Z))\\<^sup>\\<ddagger>\"\n      by (auto simp only: sm_join_preserving[symmetric] sm_shuffle_def)\n    also have \"... = (\\<Union>range (spawn X) \\<parallel> Z)\\<^sup>\\<ddagger>\"\n      by (simp only: shuffle_inf_distr, rule arg_cong, blast)\n    finally have \"\\<Union>range (\\<lambda>n. spawn X n \\<parallel>\\<^sup>\\<ddagger> Z) = X\\<^sup>\\<parallel> \\<parallel>\\<^sup>\\<ddagger> Z\"\n      by (metis shuffle_star_def sm_shuffle_def)\n  }\n  ultimately show ?thesis by auto\nqed\n\nlemma [simp]: \"listsum (map (\\<lambda>x. [x]) xs) = xs\"\n  by (induct xs) (auto simp add: zero_list_def plus_list_def)\n\nlemma sm_set_free_self [intro]: \"[xs] \\<in> sm_set (map (\\<lambda>x. [x]) xs)\"\nproof (induct xs, simp_all)\n  show \"[[]] \\<in> sm_set []\"\n    by (metis sm_set.self zero_list_def)\nnext\n  fix x and xs :: \"'a list\"\n  assume ih: \"[xs] \\<in> sm_set (map (\\<lambda>x. [x]) xs)\"\n  have \"[x] # [xs] \\<in> sm_set ([x] # map (\\<lambda>x. [x]) xs)\"\n    by (rule sm_set_cons[OF ih])\n  hence \"[[x]] @ [xs] \\<in> sm_set ([x] # map (\\<lambda>x. [x]) xs)\"\n    by simp\n  hence \"[[x] @ xs] \\<in> sm_set ([x] # map (\\<lambda>x. [x]) xs)\"\n    apply (simp only: plus_list_def[symmetric])\n    apply (rule mumble[of \"[]\" _ _ \"[]\", simplified])\n    by (simp add: plus_list_def)\n  thus \"[x # xs] \\<in> sm_set ([x] # map (\\<lambda>x. [x]) xs)\"\n    by simp\nqed\n\nsection {* Stutter/mumble closure in the free monoid *}\n\ntext {*\nIf the monoid we are using is the free monoid (i.e. lists), then @{term sm_set} has an equivalent, non inductive definition.\n*}\n\nlemma sm_set_non_ind: \"sm_set (map (\\<lambda>x. [x]) xs) = {zs. xs = concat zs \\<and> zs \\<noteq> []}\"\nproof\n  show \"sm_set (map (\\<lambda>x. [x]) xs) \\<subseteq> {zs. xs = concat zs \\<and> zs \\<noteq> []}\"\n  proof auto\n    fix ys\n    assume \"ys \\<in> sm_set (map (\\<lambda>x. [x]) xs)\"\n    thus \"xs = concat ys\"\n      by (induct ys) (auto simp add: zero_list_def plus_list_def)\n  next\n    fix x assume \"[] \\<in> sm_set (map (\\<lambda>x. [x]) xs)\"\n    from this and sm_set_empty show False by auto\n  qed\n  moreover\n  {\n    fix x :: \"'a list\" and xs :: \"'a list list\"\n    have \"x # xs \\<in> sm_set (map (\\<lambda>x. [x]) (concat (x # xs)))\"\n    proof (induct xs arbitrary: x)\n      fix x :: \"'a list\" show \"[x] \\<in> sm_set (map (\\<lambda>x. [x]) (concat [x]))\"\n        by auto\n    next\n      fix x and x' and xs :: \"'a list list\"\n      assume ih: \"\\<And>x. x # xs \\<in> sm_set (map (\\<lambda>x. [x]) (concat (x # xs)))\"\n      have \"[0,x] @ x' # xs \\<in> sm_set (map (\\<lambda>x. [x]) x @ map (\\<lambda>x. [x]) (concat (x' # xs)))\"\n        by (rule sm_set_append, metis sm_set.self sm_set_free_self sm_set_trans, metis ih)\n      hence \"[] @ [0] @ [x] @ x' # xs \\<in> sm_set (map (\\<lambda>x. [x]) x @ map (\\<lambda>x. [x]) (concat (x' # xs)))\"\n        by simp\n      hence \"[] @ [0 + x] @ x' # xs \\<in> sm_set (map (\\<lambda>x. [x]) x @ map (\\<lambda>x. [x]) (concat (x' # xs)))\"\n        by (rule mumble)\n      hence \"[] @ [x] @ x' # xs \\<in> sm_set (map (\\<lambda>x. [x]) x @ map (\\<lambda>x. [x]) (concat (x' # xs)))\"\n        by simp\n      thus \"x # x' # xs \\<in> sm_set (map (\\<lambda>x. [x]) (concat (x # x' # xs)))\"\n        by simp\n    qed\n  }\n  thus \"{zs. xs = concat zs \\<and> zs \\<noteq> []} \\<subseteq> sm_set (map (\\<lambda>x. [x]) xs)\"\n    by (safe, metis neq_Nil_conv)\nqed\n\nprimrec unfree :: \"('a \\<Rightarrow> 'b::monoid_add) \\<Rightarrow> 'a list list \\<Rightarrow> 'b list\" where\n  \"unfree f [] = []\"\n| \"unfree f (x#xs) = listsum (map f x) # unfree f xs\"\n\nlemma unfree_append: \"unfree id (xs @ ys) = unfree id xs @ unfree id ys\"\n  by (induct xs) auto\n\nlemma [simp]: \"unfree id (map (\\<lambda>x. [x]) xs) = xs\"\n  by (induct xs) simp_all\n\nlemma unfree_exists: \"\\<exists>ys. xs = unfree id ys\"\n  apply (rule_tac x = \"map (\\<lambda>x. [x]) xs\" in exI)\n  apply (induct xs)\n  by auto\n\nlemma unfree_split1:\n  \"as @ bs = unfree id cs \\<Longrightarrow> \\<exists>csa csb. as = unfree id csa \\<and> bs = unfree id csb \\<and> csa @ csb = cs\"\nproof (induct cs arbitrary: as bs, simp_all)\n  fix c :: \"'a list\" and cs as bs\n  assume ih: \"\\<And>as bs. as @ bs = unfree id cs \\<Longrightarrow> \\<exists>csa. as = unfree id csa \\<and> (\\<exists>csb. bs = unfree id csb \\<and> csa @ csb = cs)\"\n  and \"as @ bs = listsum c # unfree id cs\"\n  note assumptions = this\n  show \"\\<exists>csa. as = unfree id csa \\<and> (\\<exists>csb. bs = unfree id csb \\<and> csa @ csb = c # cs)\"\n  proof (rule list.exhaust[of as], insert assumptions, rule_tac x = \"[]\" in exI, simp_all)\n    fix a as\n    assume \"a = listsum c \\<and> as @ bs = unfree id cs\"\n    hence a: \"a = listsum c\" and b: \"as @ bs = unfree id cs\"\n      by auto\n    thus \"\\<exists>csa. listsum c # as = unfree id csa \\<and> (\\<exists>csb. bs = unfree id csb \\<and> csa @ csb = c # cs)\"\n      apply (insert ih[OF b])\n      by (metis List.map.id append_Cons id_apply unfree.simps(2))\n  qed\nqed\n\nlemma unfree_length: \"xs = unfree id ys \\<Longrightarrow> length xs = length ys\"\n  by (induct ys arbitrary: xs) auto\n\nlemma unfree_take: \"as @ bs = unfree id cs \\<Longrightarrow> as = unfree id (take (length as) cs)\"\nproof (induct cs arbitrary: as, simp_all)\n  fix c :: \"'a list\" and cs as\n  assume ih: \"\\<And>as. as @ bs = unfree id cs \\<Longrightarrow> as = unfree id (take (length as) cs)\"\n  and asm: \"as @ bs = listsum c # unfree id cs\"\n  show \"as = unfree id (take (length as) (c # cs))\"\n    by (rule list.exhaust[of as], simp_all, metis Cons_eq_appendI asm ih list.inject)\nqed\n\nlemma unfree_drop: \"as @ bs = unfree id cs \\<Longrightarrow> bs = unfree id (drop (length as) cs)\"\nproof (induct cs arbitrary: as bs, simp_all)\n  fix c :: \"'a list\" and cs as bs\n  assume ih: \"\\<And>as bs. as @ bs = unfree id cs \\<Longrightarrow> bs = unfree id (drop (length as) cs)\"\n  and asm: \"as @ bs = listsum c # unfree id cs\"\n  show \"bs = unfree id (drop (length as) (c # cs))\"\n    apply (rule list.exhaust[of as])\n    apply simp\n    apply (metis append_Nil asm)\n    apply simp\n    by (metis append_Cons asm ih list.inject)\nqed\n\nlemma unfree_cons: \"x # xs = unfree id ys \\<Longrightarrow> xs = unfree id (drop 1 ys)\"\n  by (induct ys) auto\n\nlemma unfree_hd: \"x # xs = unfree id ys \\<Longrightarrow> x = listsum (hd ys)\"\n  by (induct ys) auto\n\nlemma drop_hd: \"length xs > n \\<Longrightarrow> drop n xs = hd (drop n xs) # drop (Suc n) xs\"\n  apply (induct xs arbitrary: n)\n  apply auto\n  by (metis drop_Suc_Cons drop_Suc_conv_tl hd_drop_conv_nth length_Suc_conv)\n\nlemma unfree_split2:\n  \"as @ [b] @ [c] @ ds = unfree id zs \\<Longrightarrow>\n  \\<exists>zsa zb zc zsd. as = unfree id zsa \\<and> b = listsum zb \\<and> c = listsum zc \\<and> ds = unfree id zsd \\<and> zsa @ [zb] @ [zc] @ zsd = zs\"\nproof (intro exI conjI)\n  assume asm: \"as @ [b] @ [c] @ ds = unfree id zs\"\n\n  let ?zsa = \"take (length as) zs\"\n  from asm show \"as = unfree id ?zsa\"\n    by (metis unfree_take)\n\n  let ?zb = \"hd (drop (length as) zs)\"\n  show \"b = listsum ?zb\"\n    by (rule unfree_hd[OF unfree_drop[OF asm, simplified]])\n\n  let ?zc = \"hd (drop (Suc (length as)) zs)\"\n  show \"c = listsum ?zc\"\n    by (rule unfree_hd[OF unfree_cons[OF unfree_drop[OF asm, simplified]], simplified])\n\n  let ?zsd = \"drop (Suc (Suc (length as))) zs\"\n  show \"ds = unfree id ?zsd\"\n    by (rule unfree_cons[OF unfree_cons[OF unfree_drop[OF asm, simplified]], simplified])\n\n  from asm have zs_len: \"length zs = Suc (Suc (length as + length ds))\"\n    by (insert unfree_length[OF asm], simp)\n\n  show \"?zsa @ [?zb] @ [?zc] @ ?zsd = zs\"\n    apply (simp)\n    apply (subst append_take_drop_id[of \"length as\" \"zs\", symmetric])\n    back back back back\n    apply (rule arg_cong) back\n    apply (subst drop_hd[symmetric])\n    apply (metis add_Suc_right add_Suc_shift less_add_Suc1 zs_len)\n    apply (subst drop_hd[symmetric])\n    apply (metis (full_types) Suc_lessD length_append lessI nat_neq_iff not_add_less1 zs_len)\n    by auto\nqed\n\nlemma unfree_replicate [simp]: \"unfree id (replicate n []) = replicate n 0\"\n  by (induct n) auto\n\ntext {*\nIt is always possible to perform the stutter/mumble closure in the free monoid, and then map back down into an arbitrary monoid.\n*}\n\nlemma free_sm_set: \"sm_set xs = unfree id ` sm_set (map (\\<lambda>x. [x]) xs)\"\nproof -\n  have \"sm_set [] = unfree id ` sm_set (map (\\<lambda>x. [x]) [])\"\n    apply (auto simp add: sm_set_empty_def image_def)\n    apply (simp_all add: zero_list_def)\n    apply (rule_tac x = \"replicate (Suc xa) []\" in exI)\n    by (simp_all add: zero_list_def)\n\n  moreover\n  {\n    fix x and xs :: \"'a list\"\n    have \"sm_set (x # xs) = unfree id ` sm_set (map (\\<lambda>x. [x]) (x # xs))\"\n    proof (auto simp add: image_def sm_set_non_ind simp del: map.simps)\n      fix ys\n      show \"ys \\<in> sm_set (x # xs) \\<Longrightarrow> \\<exists>zs. x # xs = concat zs \\<and> zs \\<noteq> [] \\<and> ys = unfree id zs\"\n      proof (induct ys rule: sm_set.induct, intro exI conjI)\n        show \"x # xs = concat ([[]] @ map (\\<lambda>x. [x]) (x # xs))\"\n        and \"[[]] @ map (\\<lambda>x. [x]) (x # xs) \\<noteq> []\"\n        and \"0 # x # xs = unfree id ([[]] @ map (\\<lambda>x. [x]) (x # xs))\"\n          by (induct xs) auto\n      next\n        fix as bs\n        assume \"as @ bs \\<in> sm_set (x # xs)\"\n        and \"\\<exists>zs. (x # xs) = concat zs \\<and> zs \\<noteq> [] \\<and> as @ bs = unfree id zs\"\n        then obtain zs where \"(x # xs) = concat zs\" and \"zs \\<noteq> []\" and \"as @ bs = unfree id zs\" by auto\n        then moreover obtain zsa and zsb where \"as = unfree id zsa\" and \"bs = unfree id zsb\" and \"zsa @ zsb = zs\"\n          by (metis unfree_split1)\n        ultimately show \"\\<exists>zs. (x # xs) = concat zs \\<and> zs \\<noteq> [] \\<and> as @ [0] @ bs = unfree id zs\"\n          apply (rule_tac x = \"zsa @ [0] @ zsb\" in exI)\n          by (auto simp add: zero_list_def unfree_append)\n      next\n        fix as bs cs ds\n        assume \"as @ [bs] @ [cs] @ ds \\<in> sm_set (x # xs)\"\n        and \"\\<exists>zs. (x # xs) = concat zs \\<and> zs \\<noteq> [] \\<and> as @ [bs] @ [cs] @ ds = unfree id zs\"\n        then obtain zs where \"(x # xs) = concat zs \\<and> as @ [bs] @ [cs] @ ds = unfree id zs\" by auto\n        then moreover obtain zsa and zb and zc and zsd\n        where \"as = unfree id zsa\" and \"bs = listsum zb\" and \"cs = listsum zc\" and \"ds = unfree id zsd\" and \"zsa @ [zb] @ [zc] @ zsd = zs\"\n          by (metis unfree_split2)\n        ultimately show \"\\<exists>zs. (x # xs) = concat zs \\<and> zs \\<noteq> [] \\<and> as @ [bs + cs] @ ds = unfree id zs\"\n          apply (rule_tac x = \"zsa @ [zb @ zc] @ zsd\" in exI)\n          by (auto simp add: plus_list_def unfree_append)\n      qed\n    next\n      fix ys :: \"'a list list\"\n      assume \"x # xs = concat ys\" and \"ys \\<noteq> []\"\n      then obtain z and zs where ys_def: \"ys = (z # zs)\"\n        by (metis neq_Nil_conv)\n      have \"[listsum z] @ unfree id zs \\<in> sm_set (z @ concat zs)\"\n        apply (induct zs arbitrary: z)\n        apply simp\n        apply (metis append_Nil append_Nil2 listsum_simps(1) mumble_many neq_Nil_conv sm_set.self sm_set_self_var)\n        apply (rule sm_set_append)\n        apply (metis append_Nil append_Nil2 listsum_simps(1) mumble_many neq_Nil_conv sm_set.self sm_set_self_var)\n        by simp\n      hence \"unfree id (z # zs) \\<in> sm_set (concat (z # zs))\"\n        by (simp)\n      thus \"unfree id ys \\<in> sm_set (concat ys)\"\n        by (metis ys_def)\n    qed\n  }\n  ultimately show ?thesis\n    by (metis list.exhaust)\nqed\n\nhide_fact unfree_split1 unfree_split2\n\ndefinition sm_pow_inv :: \"'a::monoid_add set \\<Rightarrow> 'a lan\" where\n  \"sm_pow_inv I \\<equiv> (pow_inv I)\\<^sup>\\<ddagger>\"\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/Finite/SMLanguage.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8267117940706735, "lm_q2_score": 0.8539127548105611, "lm_q1q2_score": 0.7059397455092701}}
{"text": "(*  Title:      ZF/Constructible/Normal.thy\n    Author:     Lawrence C Paulson, Cambridge University Computer Laboratory\n*)\n\nsection {*Closed Unbounded Classes and Normal Functions*}\n\ntheory Normal imports Main begin\n\ntext{*\nOne source is the book\n\nFrank R. Drake.\n\\emph{Set Theory: An Introduction to Large Cardinals}.\nNorth-Holland, 1974.\n*}\n\n\nsubsection {*Closed and Unbounded (c.u.) Classes of Ordinals*}\n\ndefinition\n  Closed :: \"(i=>o) => o\" where\n    \"Closed(P) == \\<forall>I. I \\<noteq> 0 \\<longrightarrow> (\\<forall>i\\<in>I. Ord(i) \\<and> P(i)) \\<longrightarrow> P(\\<Union>(I))\"\n\ndefinition\n  Unbounded :: \"(i=>o) => o\" where\n    \"Unbounded(P) == \\<forall>i. Ord(i) \\<longrightarrow> (\\<exists>j. i<j \\<and> P(j))\"\n\ndefinition\n  Closed_Unbounded :: \"(i=>o) => o\" where\n    \"Closed_Unbounded(P) == Closed(P) \\<and> Unbounded(P)\"\n\n\nsubsubsection{*Simple facts about c.u. classes*}\n\nlemma ClosedI:\n     \"[| !!I. [| I \\<noteq> 0; \\<forall>i\\<in>I. Ord(i) \\<and> P(i) |] ==> P(\\<Union>(I)) |] \n      ==> Closed(P)\"\nby (simp add: Closed_def)\n\nlemma ClosedD:\n     \"[| Closed(P); I \\<noteq> 0; !!i. i\\<in>I ==> Ord(i); !!i. i\\<in>I ==> P(i) |] \n      ==> P(\\<Union>(I))\"\nby (simp add: Closed_def)\n\nlemma UnboundedD:\n     \"[| Unbounded(P);  Ord(i) |] ==> \\<exists>j. i<j \\<and> P(j)\"\nby (simp add: Unbounded_def)\n\nlemma Closed_Unbounded_imp_Unbounded: \"Closed_Unbounded(C) ==> Unbounded(C)\"\nby (simp add: Closed_Unbounded_def) \n\n\ntext{*The universal class, V, is closed and unbounded.\n      A bit odd, since C. U. concerns only ordinals, but it's used below!*}\ntheorem Closed_Unbounded_V [simp]: \"Closed_Unbounded(\\<lambda>x. True)\"\nby (unfold Closed_Unbounded_def Closed_def Unbounded_def, blast)\n\ntext{*The class of ordinals, @{term Ord}, is closed and unbounded.*}\ntheorem Closed_Unbounded_Ord   [simp]: \"Closed_Unbounded(Ord)\"\nby (unfold Closed_Unbounded_def Closed_def Unbounded_def, blast)\n\ntext{*The class of limit ordinals, @{term Limit}, is closed and unbounded.*}\ntheorem Closed_Unbounded_Limit [simp]: \"Closed_Unbounded(Limit)\"\napply (simp add: Closed_Unbounded_def Closed_def Unbounded_def Limit_Union, \n       clarify)\napply (rule_tac x=\"i++nat\" in exI)  \napply (blast intro: oadd_lt_self oadd_LimitI Limit_nat Limit_has_0) \ndone\n\ntext{*The class of cardinals, @{term Card}, is closed and unbounded.*}\ntheorem Closed_Unbounded_Card  [simp]: \"Closed_Unbounded(Card)\"\napply (simp add: Closed_Unbounded_def Closed_def Unbounded_def Card_Union)\napply (blast intro: lt_csucc Card_csucc)\ndone\n\n\nsubsubsection{*The intersection of any set-indexed family of c.u. classes is\n      c.u.*}\n\ntext{*The constructions below come from Kunen, \\emph{Set Theory}, page 78.*}\nlocale cub_family =\n  fixes P and A\n  fixes next_greater -- \"the next ordinal satisfying class @{term A}\"\n  fixes sup_greater  -- \"sup of those ordinals over all @{term A}\"\n  assumes closed:    \"a\\<in>A ==> Closed(P(a))\"\n      and unbounded: \"a\\<in>A ==> Unbounded(P(a))\"\n      and A_non0: \"A\\<noteq>0\"\n  defines \"next_greater(a,x) == \\<mu> y. x<y \\<and> P(a,y)\"\n      and \"sup_greater(x) == \\<Union>a\\<in>A. next_greater(a,x)\"\n \n\ntext{*Trivial that the intersection is closed.*}\nlemma (in cub_family) Closed_INT: \"Closed(\\<lambda>x. \\<forall>i\\<in>A. P(i,x))\"\nby (blast intro: ClosedI ClosedD [OF closed])\n\ntext{*All remaining effort goes to show that the intersection is unbounded.*}\n\nlemma (in cub_family) Ord_sup_greater:\n     \"Ord(sup_greater(x))\"\nby (simp add: sup_greater_def next_greater_def)\n\nlemma (in cub_family) Ord_next_greater:\n     \"Ord(next_greater(a,x))\"\nby (simp add: next_greater_def Ord_Least)\n\ntext{*@{term next_greater} works as expected: it returns a larger value\nand one that belongs to class @{term \"P(a)\"}. *}\nlemma (in cub_family) next_greater_lemma:\n     \"[| Ord(x); a\\<in>A |] ==> P(a, next_greater(a,x)) \\<and> x < next_greater(a,x)\"\napply (simp add: next_greater_def)\napply (rule exE [OF UnboundedD [OF unbounded]])\n  apply assumption+\napply (blast intro: LeastI2 lt_Ord2) \ndone\n\nlemma (in cub_family) next_greater_in_P:\n     \"[| Ord(x); a\\<in>A |] ==> P(a, next_greater(a,x))\"\nby (blast dest: next_greater_lemma)\n\nlemma (in cub_family) next_greater_gt:\n     \"[| Ord(x); a\\<in>A |] ==> x < next_greater(a,x)\"\nby (blast dest: next_greater_lemma)\n\nlemma (in cub_family) sup_greater_gt:\n     \"Ord(x) ==> x < sup_greater(x)\"\napply (simp add: sup_greater_def)\napply (insert A_non0)\napply (blast intro: UN_upper_lt next_greater_gt Ord_next_greater)\ndone\n\nlemma (in cub_family) next_greater_le_sup_greater:\n     \"a\\<in>A ==> next_greater(a,x) \\<le> sup_greater(x)\"\napply (simp add: sup_greater_def) \napply (blast intro: UN_upper_le Ord_next_greater)\ndone\n\nlemma (in cub_family) omega_sup_greater_eq_UN:\n     \"[| Ord(x); a\\<in>A |] \n      ==> sup_greater^\\<omega> (x) = \n          (\\<Union>n\\<in>nat. next_greater(a, sup_greater^n (x)))\"\napply (simp add: iterates_omega_def)\napply (rule le_anti_sym)\napply (rule le_implies_UN_le_UN) \napply (blast intro: leI next_greater_gt Ord_iterates Ord_sup_greater)  \ntxt{*Opposite bound:\n@{subgoals[display,indent=0,margin=65]}\n*}\napply (rule UN_least_le) \napply (blast intro: Ord_UN Ord_iterates Ord_sup_greater)  \napply (rule_tac a=\"succ(n)\" in UN_upper_le)\napply (simp_all add: next_greater_le_sup_greater) \napply (blast intro: Ord_UN Ord_iterates Ord_sup_greater)  \ndone\n\nlemma (in cub_family) P_omega_sup_greater:\n     \"[| Ord(x); a\\<in>A |] ==> P(a, sup_greater^\\<omega> (x))\"\napply (simp add: omega_sup_greater_eq_UN)\napply (rule ClosedD [OF closed]) \napply (blast intro: ltD, auto)\napply (blast intro: Ord_iterates Ord_next_greater Ord_sup_greater)\napply (blast intro: next_greater_in_P Ord_iterates Ord_sup_greater)\ndone\n\nlemma (in cub_family) omega_sup_greater_gt:\n     \"Ord(x) ==> x < sup_greater^\\<omega> (x)\"\napply (simp add: iterates_omega_def)\napply (rule UN_upper_lt [of 1], simp_all) \n apply (blast intro: sup_greater_gt) \napply (blast intro: Ord_UN Ord_iterates Ord_sup_greater)\ndone\n\nlemma (in cub_family) Unbounded_INT: \"Unbounded(\\<lambda>x. \\<forall>a\\<in>A. P(a,x))\"\napply (unfold Unbounded_def)  \napply (blast intro!: omega_sup_greater_gt P_omega_sup_greater) \ndone\n\nlemma (in cub_family) Closed_Unbounded_INT: \n     \"Closed_Unbounded(\\<lambda>x. \\<forall>a\\<in>A. P(a,x))\"\nby (simp add: Closed_Unbounded_def Closed_INT Unbounded_INT)\n\n\ntheorem Closed_Unbounded_INT:\n    \"(!!a. a\\<in>A ==> Closed_Unbounded(P(a)))\n     ==> Closed_Unbounded(\\<lambda>x. \\<forall>a\\<in>A. P(a, x))\"\napply (case_tac \"A=0\", simp)\napply (rule cub_family.Closed_Unbounded_INT [OF cub_family.intro])\napply (simp_all add: Closed_Unbounded_def)\ndone\n\nlemma Int_iff_INT2:\n     \"P(x) \\<and> Q(x)  \\<longleftrightarrow>  (\\<forall>i\\<in>2. (i=0 \\<longrightarrow> P(x)) \\<and> (i=1 \\<longrightarrow> Q(x)))\"\nby auto\n\ntheorem Closed_Unbounded_Int:\n     \"[| Closed_Unbounded(P); Closed_Unbounded(Q) |] \n      ==> Closed_Unbounded(\\<lambda>x. P(x) \\<and> Q(x))\"\napply (simp only: Int_iff_INT2)\napply (rule Closed_Unbounded_INT, auto) \ndone\n\n\nsubsection {*Normal Functions*} \n\ndefinition\n  mono_le_subset :: \"(i=>i) => o\" where\n    \"mono_le_subset(M) == \\<forall>i j. i\\<le>j \\<longrightarrow> M(i) \\<subseteq> M(j)\"\n\ndefinition\n  mono_Ord :: \"(i=>i) => o\" where\n    \"mono_Ord(F) == \\<forall>i j. i<j \\<longrightarrow> F(i) < F(j)\"\n\ndefinition\n  cont_Ord :: \"(i=>i) => o\" where\n    \"cont_Ord(F) == \\<forall>l. Limit(l) \\<longrightarrow> F(l) = (\\<Union>i<l. F(i))\"\n\ndefinition\n  Normal :: \"(i=>i) => o\" where\n    \"Normal(F) == mono_Ord(F) \\<and> cont_Ord(F)\"\n\n\nsubsubsection{*Immediate properties of the definitions*}\n\nlemma NormalI:\n     \"[|!!i j. i<j ==> F(i) < F(j);  !!l. Limit(l) ==> F(l) = (\\<Union>i<l. F(i))|]\n      ==> Normal(F)\"\nby (simp add: Normal_def mono_Ord_def cont_Ord_def)\n\nlemma mono_Ord_imp_Ord: \"[| Ord(i); mono_Ord(F) |] ==> Ord(F(i))\"\napply (auto simp add: mono_Ord_def)\napply (blast intro: lt_Ord) \ndone\n\nlemma mono_Ord_imp_mono: \"[| i<j; mono_Ord(F) |] ==> F(i) < F(j)\"\nby (simp add: mono_Ord_def)\n\nlemma Normal_imp_Ord [simp]: \"[| Normal(F); Ord(i) |] ==> Ord(F(i))\"\nby (simp add: Normal_def mono_Ord_imp_Ord) \n\nlemma Normal_imp_cont: \"[| Normal(F); Limit(l) |] ==> F(l) = (\\<Union>i<l. F(i))\"\nby (simp add: Normal_def cont_Ord_def)\n\nlemma Normal_imp_mono: \"[| i<j; Normal(F) |] ==> F(i) < F(j)\"\nby (simp add: Normal_def mono_Ord_def)\n\nlemma Normal_increasing:\n  assumes i: \"Ord(i)\" and F: \"Normal(F)\" shows\"i \\<le> F(i)\"\nusing i\nproof (induct i rule: trans_induct3)\n  case 0 thus ?case by (simp add: subset_imp_le F)\nnext\n  case (succ i) \n  hence \"F(i) < F(succ(i))\" using F\n    by (simp add: Normal_def mono_Ord_def)\n  thus ?case using succ.hyps\n    by (blast intro: lt_trans1)\nnext\n  case (limit l) \n  hence \"l = (\\<Union>y<l. y)\" \n    by (simp add: Limit_OUN_eq)\n  also have \"... \\<le> (\\<Union>y<l. F(y))\" using limit\n    by (blast intro: ltD le_implies_OUN_le_OUN)\n  finally have \"l \\<le> (\\<Union>y<l. F(y))\" .\n  moreover have \"(\\<Union>y<l. F(y)) \\<le> F(l)\" using limit F\n    by (simp add: Normal_imp_cont lt_Ord)\n  ultimately show ?case\n    by (blast intro: le_trans) \nqed\n\n\nsubsubsection{*The class of fixedpoints is closed and unbounded*}\n\ntext{*The proof is from Drake, pages 113--114.*}\n\nlemma mono_Ord_imp_le_subset: \"mono_Ord(F) ==> mono_le_subset(F)\"\napply (simp add: mono_le_subset_def, clarify)\napply (subgoal_tac \"F(i)\\<le>F(j)\", blast dest: le_imp_subset) \napply (simp add: le_iff) \napply (blast intro: lt_Ord2 mono_Ord_imp_Ord mono_Ord_imp_mono) \ndone\n\ntext{*The following equation is taken for granted in any set theory text.*}\nlemma cont_Ord_Union:\n     \"[| cont_Ord(F); mono_le_subset(F); X=0 \\<longrightarrow> F(0)=0; \\<forall>x\\<in>X. Ord(x) |] \n      ==> F(\\<Union>(X)) = (\\<Union>y\\<in>X. F(y))\"\napply (frule Ord_set_cases)\napply (erule disjE, force) \napply (thin_tac \"X=0 \\<longrightarrow> ?Q\", auto)\n txt{*The trival case of @{term \"\\<Union>X \\<in> X\"}*}\n apply (rule equalityI, blast intro: Ord_Union_eq_succD) \n apply (simp add: mono_le_subset_def UN_subset_iff le_subset_iff) \n apply (blast elim: equalityE)\ntxt{*The limit case, @{term \"Limit(\\<Union>X)\"}:\n@{subgoals[display,indent=0,margin=65]}\n*}\napply (simp add: OUN_Union_eq cont_Ord_def)\napply (rule equalityI) \ntxt{*First inclusion:*}\n apply (rule UN_least [OF OUN_least])\n apply (simp add: mono_le_subset_def, blast intro: leI) \ntxt{*Second inclusion:*}\napply (rule UN_least) \napply (frule Union_upper_le, blast, blast intro: Ord_Union)\napply (erule leE, drule ltD, elim UnionE)\n apply (simp add: OUnion_def)\n apply blast+\ndone\n\nlemma Normal_Union:\n     \"[| X\\<noteq>0; \\<forall>x\\<in>X. Ord(x); Normal(F) |] ==> F(\\<Union>(X)) = (\\<Union>y\\<in>X. F(y))\"\napply (simp add: Normal_def) \napply (blast intro: mono_Ord_imp_le_subset cont_Ord_Union) \ndone\n\nlemma Normal_imp_fp_Closed: \"Normal(F) ==> Closed(\\<lambda>i. F(i) = i)\"\napply (simp add: Closed_def ball_conj_distrib, clarify)\napply (frule Ord_set_cases)\napply (auto simp add: Normal_Union)\ndone\n\n\nlemma iterates_Normal_increasing:\n     \"[| n\\<in>nat;  x < F(x);  Normal(F) |] \n      ==> F^n (x) < F^(succ(n)) (x)\"  \napply (induct n rule: nat_induct)\napply (simp_all add: Normal_imp_mono)\ndone\n\nlemma Ord_iterates_Normal:\n     \"[| n\\<in>nat;  Normal(F);  Ord(x) |] ==> Ord(F^n (x))\"  \nby (simp add: Ord_iterates) \n\ntext{*THIS RESULT IS UNUSED*}\nlemma iterates_omega_Limit:\n     \"[| Normal(F);  x < F(x) |] ==> Limit(F^\\<omega> (x))\"  \napply (frule lt_Ord) \napply (simp add: iterates_omega_def)\napply (rule increasing_LimitI) \n   --\"this lemma is @{thm increasing_LimitI [no_vars]}\"\n apply (blast intro: UN_upper_lt [of \"1\"]   Normal_imp_Ord\n                     Ord_UN Ord_iterates lt_imp_0_lt\n                     iterates_Normal_increasing, clarify)\napply (rule bexI) \n apply (blast intro: Ord_in_Ord [OF Ord_iterates_Normal]) \napply (rule UN_I, erule nat_succI) \napply (blast intro:  iterates_Normal_increasing Ord_iterates_Normal\n                     ltD [OF lt_trans1, OF succ_leI, OF ltI]) \ndone\n\nlemma iterates_omega_fixedpoint:\n     \"[| Normal(F); Ord(a) |] ==> F(F^\\<omega> (a)) = F^\\<omega> (a)\" \napply (frule Normal_increasing, assumption)\napply (erule leE) \n apply (simp_all add: iterates_omega_triv [OF sym])  (*for subgoal 2*)\napply (simp add:  iterates_omega_def Normal_Union) \napply (rule equalityI, force simp add: nat_succI) \ntxt{*Opposite inclusion:\n@{subgoals[display,indent=0,margin=65]}\n*}\napply clarify\napply (rule UN_I, assumption) \napply (frule iterates_Normal_increasing, assumption, assumption, simp)\napply (blast intro: Ord_trans ltD Ord_iterates_Normal Normal_imp_Ord [of F]) \ndone\n\nlemma iterates_omega_increasing:\n     \"[| Normal(F); Ord(a) |] ==> a \\<le> F^\\<omega> (a)\"   \napply (unfold iterates_omega_def)\napply (rule UN_upper_le [of 0], simp_all)\ndone\n\nlemma Normal_imp_fp_Unbounded: \"Normal(F) ==> Unbounded(\\<lambda>i. F(i) = i)\"\napply (unfold Unbounded_def, clarify)\napply (rule_tac x=\"F^\\<omega> (succ(i))\" in exI)\napply (simp add: iterates_omega_fixedpoint) \napply (blast intro: lt_trans2 [OF _ iterates_omega_increasing])\ndone\n\n\ntheorem Normal_imp_fp_Closed_Unbounded: \n     \"Normal(F) ==> Closed_Unbounded(\\<lambda>i. F(i) = i)\"\nby (simp add: Closed_Unbounded_def Normal_imp_fp_Closed\n              Normal_imp_fp_Unbounded)\n\n\nsubsubsection{*Function @{text normalize}*}\n\ntext{*Function @{text normalize} maps a function @{text F} to a \n      normal function that bounds it above.  The result is normal if and\n      only if @{text F} is continuous: succ is not bounded above by any \n      normal function, by @{thm [source] Normal_imp_fp_Unbounded}.\n*}\ndefinition\n  normalize :: \"[i=>i, i] => i\" where\n    \"normalize(F,a) == transrec2(a, F(0), \\<lambda>x r. F(succ(x)) \\<union> succ(r))\"\n\n\nlemma Ord_normalize [simp, intro]:\n     \"[| Ord(a); !!x. Ord(x) ==> Ord(F(x)) |] ==> Ord(normalize(F, a))\"\napply (induct a rule: trans_induct3)\napply (simp_all add: ltD def_transrec2 [OF normalize_def])\ndone\n\nlemma normalize_increasing:\n  assumes ab: \"a < b\" and F: \"!!x. Ord(x) ==> Ord(F(x))\"\n  shows \"normalize(F,a) < normalize(F,b)\"\nproof -\n  { fix x\n    have \"Ord(b)\" using ab by (blast intro: lt_Ord2) \n    hence \"x < b \\<Longrightarrow> normalize(F,x) < normalize(F,b)\"\n    proof (induct b arbitrary: x rule: trans_induct3)\n      case 0 thus ?case by simp\n    next\n      case (succ b)\n      thus ?case\n        by (auto simp add: le_iff def_transrec2 [OF normalize_def] intro: Un_upper2_lt F)\n    next\n      case (limit l)\n      hence sc: \"succ(x) < l\" \n        by (blast intro: Limit_has_succ) \n      hence \"normalize(F,x) < normalize(F,succ(x))\" \n        by (blast intro: limit elim: ltE) \n      hence \"normalize(F,x) < (\\<Union>j<l. normalize(F,j))\"\n        by (blast intro: OUN_upper_lt lt_Ord F sc) \n      thus ?case using limit\n        by (simp add: def_transrec2 [OF normalize_def])\n    qed\n  } thus ?thesis using ab .\nqed\n\ntheorem Normal_normalize:\n     \"(!!x. Ord(x) ==> Ord(F(x))) ==> Normal(normalize(F))\"\napply (rule NormalI) \napply (blast intro!: normalize_increasing)\napply (simp add: def_transrec2 [OF normalize_def])\ndone\n\ntheorem le_normalize:\n  assumes a: \"Ord(a)\" and coF: \"cont_Ord(F)\" and F: \"!!x. Ord(x) ==> Ord(F(x))\"\n  shows \"F(a) \\<le> normalize(F,a)\"\nusing a\nproof (induct a rule: trans_induct3)\n  case 0 thus ?case by (simp add: F def_transrec2 [OF normalize_def])\nnext\n  case (succ a)\n  thus ?case\n    by (simp add: def_transrec2 [OF normalize_def] Un_upper1_le F )\nnext\n  case (limit l) \n  thus ?case using F coF [unfolded cont_Ord_def]\n    by (simp add: def_transrec2 [OF normalize_def] le_implies_OUN_le_OUN ltD) \nqed\n\n\nsubsection {*The Alephs*}\ntext {*This is the well-known transfinite enumeration of the cardinal \nnumbers.*}\n\ndefinition\n  Aleph :: \"i => i\" where\n    \"Aleph(a) == transrec2(a, nat, \\<lambda>x r. csucc(r))\"\n\nnotation (xsymbols)\n  Aleph  (\"\\<aleph>_\" [90] 90)\n\nlemma Card_Aleph [simp, intro]:\n     \"Ord(a) ==> Card(Aleph(a))\"\napply (erule trans_induct3) \napply (simp_all add: Card_csucc Card_nat Card_is_Ord\n                     def_transrec2 [OF Aleph_def])\ndone\n\nlemma Aleph_increasing:\n  assumes ab: \"a < b\" shows \"Aleph(a) < Aleph(b)\"\nproof -\n  { fix x\n    have \"Ord(b)\" using ab by (blast intro: lt_Ord2) \n    hence \"x < b \\<Longrightarrow> Aleph(x) < Aleph(b)\"\n    proof (induct b arbitrary: x rule: trans_induct3)\n      case 0 thus ?case by simp\n    next\n      case (succ b)\n      thus ?case\n        by (force simp add: le_iff def_transrec2 [OF Aleph_def] \n                  intro: lt_trans lt_csucc Card_is_Ord)\n    next\n      case (limit l)\n      hence sc: \"succ(x) < l\" \n        by (blast intro: Limit_has_succ) \n      hence \"\\<aleph> x < (\\<Union>j<l. \\<aleph>j)\" using limit\n        by (blast intro: OUN_upper_lt Card_is_Ord ltD lt_Ord)\n      thus ?case using limit\n        by (simp add: def_transrec2 [OF Aleph_def])\n    qed\n  } thus ?thesis using ab .\nqed\n\ntheorem Normal_Aleph: \"Normal(Aleph)\"\napply (rule NormalI) \napply (blast intro!: Aleph_increasing)\napply (simp add: def_transrec2 [OF Aleph_def])\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/Constructible/Normal.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127455162773, "lm_q2_score": 0.8267118004748677, "lm_q1q2_score": 0.7059397432941991}}
{"text": "(*  Author: Lukas Bulwahn <lukas.bulwahn-at-gmail.com> *)\n\nsection \\<open>Surjections from A to B up to a Permutation on B\\<close>\n\ntheory Twelvefold_Way_Entry9\nimports Twelvefold_Way_Entry7\nbegin\n\nsubsection \\<open>Properties for Bijections\\<close>\n\nlemma surjective_on_implies_card_eq:\n  assumes \"f ` A = B\"\n  shows \"card ((\\<lambda>b. {x \\<in> A. f x = b}) ` B - {{}}) = card B\"\nproof -\n  from \\<open>f ` A = B\\<close> have \"{} \\<notin> (\\<lambda>b. {x \\<in> A. f x = b}) ` B\" by auto\n  from \\<open>f ` A = B\\<close> have \"inj_on (\\<lambda>b. {x \\<in> A. f x = b}) B\" by (fastforce intro: inj_onI)\n  have \"card ((\\<lambda>b. {x \\<in> A. f x = b}) ` B - {{}}) = card ((\\<lambda>b. {x \\<in> A. f x = b}) ` B)\"\n    using \\<open>{} \\<notin> (\\<lambda>b. {x \\<in> A. f x = b}) ` B\\<close> by simp\n  also have \"\\<dots> = card B\"\n    using \\<open>inj_on (\\<lambda>b. {x \\<in> A. f x = b}) B\\<close> by (rule card_image)\n  finally show ?thesis .\nqed\n\nlemma card_eq_implies_surjective_on:\n  assumes \"finite B\" \"f \\<in> A \\<rightarrow>\\<^sub>E B\"\n  assumes card_eq: \"card ((\\<lambda>b. {x \\<in> A. f x = b}) ` B - {{}}) = card B\"\n  shows \"f ` A = B\"\nproof\n  from \\<open>f \\<in> A \\<rightarrow>\\<^sub>E B\\<close> show \"f ` A \\<subseteq> B\" by auto\nnext\n  show \"B \\<subseteq> f ` A\"\n  proof\n    fix x\n    assume \"x \\<in> B\"\n    have \"{} \\<notin> (\\<lambda>b. {x \\<in> A. f x = b}) ` B\"\n    proof (cases \"card B \\<ge> 1\")\n      assume \"\\<not> card B \\<ge> 1\"\n      from this have \"card B = 0\" by simp\n      from this \\<open>finite B\\<close> have \"B = {}\" by simp\n      from this show ?thesis by simp\n    next\n      assume \"card B \\<ge> 1\"\n      show ?thesis\n      proof (rule ccontr)\n        assume \"\\<not> {} \\<notin> (\\<lambda>b. {x \\<in> A. f x = b}) ` B\"\n        from this have \"{} \\<in> (\\<lambda>b. {x \\<in> A. f x = b}) ` B\" by simp\n        moreover have \"card ((\\<lambda>b. {x \\<in> A. f x = b}) ` B) \\<le> card B\"\n          using \\<open>finite B\\<close> card_image_le by blast\n        moreover have \"finite ((\\<lambda>b. {x \\<in> A. f x = b}) ` B)\"\n          using \\<open>finite B\\<close> by auto\n        ultimately have \"card ((\\<lambda>b. {x \\<in> A. f x = b}) ` B - {{}}) \\<le> card B - 1\"\n          by (auto simp add: card_Diff_singleton)\n        from this card_eq \\<open>card B \\<ge> 1\\<close> show False by auto\n      qed\n    qed\n    from this \\<open>x \\<in> B\\<close> show \"x \\<in> f ` A\" by force\n  qed\nqed\n\n\n\nlemma functions_of_is_surj_on:\n  assumes \"finite A\" \"finite B\"\n  assumes \"partition_on A P\" \"card P = card B\"\n  shows \"univ (\\<lambda>f. f ` A = B) (functions_of P A B)\"\nproof -\n  have \"functions_of P A B \\<in> (A \\<rightarrow>\\<^sub>E B) // range_permutation A B\"\n    using functions_of \\<open>finite A\\<close> \\<open>finite B\\<close> \\<open>partition_on A P\\<close> \\<open>card P = card B\\<close> by fastforce\n  from this obtain f where eq_f: \"functions_of P A B = range_permutation A B `` {f}\" and \"f \\<in> A \\<rightarrow>\\<^sub>E B\"\n    using quotientE by blast\n  from eq_f have \"f \\<in> functions_of P A B\"\n    using \\<open>f \\<in> A \\<rightarrow>\\<^sub>E B\\<close> equiv_range_permutation equiv_class_self by fastforce\n  from \\<open>f \\<in> functions_of P A B\\<close> have eq: \"(\\<lambda>b. {x \\<in> A. f x = b}) ` B - {{}} = P\"\n    unfolding functions_of_def by auto\n  from this have \"card ((\\<lambda>b. {x \\<in> A. f x = b}) ` B - {{}}) = card B\"\n    using \\<open>card P = card B\\<close> by simp\n  from \\<open>finite B\\<close> \\<open>f \\<in> A \\<rightarrow>\\<^sub>E B\\<close> this have \"f ` A = B\"\n    using card_eq_implies_surjective_on by blast\n  from this show ?thesis\n    unfolding eq_f using equiv_range_permutation surj_on_respects_range_permutation \\<open>f \\<in> A \\<rightarrow>\\<^sub>E B\\<close>\n    by (subst univ_commute') assumption+\nqed\n\nsubsection \\<open>Bijections\\<close>\n\nlemma bij_betw_partitions_of:\n  assumes \"finite A\" \"finite B\"\n  shows \"bij_betw (partitions_of A B) ({f \\<in> A \\<rightarrow>\\<^sub>E B. f ` A = B} // range_permutation A B) {P. partition_on A P \\<and> card P = card B}\"\nproof (rule bij_betw_byWitness[where f'=\"\\<lambda>P. functions_of P A B\"])\n  have quotient_eq: \"{f \\<in> A \\<rightarrow>\\<^sub>E B. f ` A = B} // range_permutation A B = {F \\<in> ((A \\<rightarrow>\\<^sub>E B) // range_permutation A B). univ (\\<lambda>f. f ` A = B) F}\"\n  using equiv_range_permutation[of A B] surj_on_respects_range_permutation[of A B] by (simp only: univ_preserves_predicate)\n  show \"\\<forall>F\\<in>{f \\<in> A \\<rightarrow>\\<^sub>E B. f ` A = B} // range_permutation A B. functions_of (partitions_of A B F) A B = F\"\n    using \\<open>finite B\\<close> by (simp add: functions_of_partitions_of quotient_eq)\n  show \"\\<forall>P\\<in>{P. partition_on A P \\<and> card P = card B}. partitions_of A B (functions_of P A B) = P\"\n    using \\<open>finite A\\<close> \\<open>finite B\\<close> by (auto simp add: partitions_of_functions_of)\n  show \"partitions_of A B ` ({f \\<in> A \\<rightarrow>\\<^sub>E B. f ` A = B} // range_permutation A B) \\<subseteq> {P. partition_on A P \\<and> card P = card B}\"\n    using \\<open>finite B\\<close> quotient_eq card_partitions_of partitions_of by fastforce\n  show \"(\\<lambda>P. functions_of P A B) ` {P. partition_on A P \\<and> card P = card B} \\<subseteq> {f \\<in> A \\<rightarrow>\\<^sub>E B. f ` A = B} // range_permutation A B\"\n    using \\<open>finite A\\<close> \\<open>finite B\\<close> by (auto simp add: quotient_eq intro: functions_of functions_of_is_surj_on)\nqed\n\nsubsection \\<open>Cardinality\\<close>\n\nlemma card_surjective_functions_range_permutation:\n  assumes \"finite A\" \"finite B\"\n  shows \"card ({f \\<in> A \\<rightarrow>\\<^sub>E B. f ` A = B} // range_permutation A B) = Stirling (card A) (card B)\"\nproof -\n  have \"bij_betw (partitions_of A B) ({f \\<in> A \\<rightarrow>\\<^sub>E B. f ` A = B} // range_permutation A B) {P. partition_on A P \\<and> card P = card B}\"\n    using \\<open>finite A\\<close> \\<open>finite B\\<close> by (rule bij_betw_partitions_of)\n  from this have \"card ({f \\<in> A \\<rightarrow>\\<^sub>E B. f ` A = B} // range_permutation A B) = card {P. partition_on A P \\<and> card P = card B}\"\n    by (rule bij_betw_same_card)\n  also have \"card {P. partition_on A P \\<and> card P = card B} = Stirling (card A) (card B)\"\n    using \\<open>finite A\\<close> by (rule card_partition_on)\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/Twelvefold_Way/Twelvefold_Way_Entry9.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127455162773, "lm_q2_score": 0.8267118004748677, "lm_q1q2_score": 0.7059397432941991}}
{"text": "(*<*)\ntheory Nested imports ABexpr begin\n(*>*)\n\ntext\\<open>\n\\index{datatypes!and nested recursion}%\nSo far, all datatypes had the property that on the right-hand side of their\ndefinition they occurred only at the top-level: directly below a\nconstructor. Now we consider \\emph{nested recursion}, where the recursive\ndatatype occurs nested in some other datatype (but not inside itself!).\nConsider the following model of terms\nwhere function symbols can be applied to a list of arguments:\n\\<close>\n(*<*)hide_const Var(*>*)\ndatatype ('v,'f)\"term\" = Var 'v | App 'f \"('v,'f)term list\"\n\ntext\\<open>\\noindent\nNote that we need to quote \\<open>term\\<close> on the left to avoid confusion with\nthe Isabelle command \\isacommand{term}.\nParameter \\<^typ>\\<open>'v\\<close> is the type of variables and \\<^typ>\\<open>'f\\<close> the type of\nfunction symbols.\nA mathematical term like $f(x,g(y))$ becomes \\<^term>\\<open>App f [Var x, App g\n  [Var y]]\\<close>, where \\<^term>\\<open>f\\<close>, \\<^term>\\<open>g\\<close>, \\<^term>\\<open>x\\<close>, \\<^term>\\<open>y\\<close> are\nsuitable values, e.g.\\ numbers or strings.\n\nWhat complicates the definition of \\<open>term\\<close> is the nested occurrence of\n\\<open>term\\<close> inside \\<open>list\\<close> on the right-hand side. In principle,\nnested recursion can be eliminated in favour of mutual recursion by unfolding\nthe offending datatypes, here \\<open>list\\<close>. The result for \\<open>term\\<close>\nwould be something like\n\\medskip\n\n\\input{unfoldnested.tex}\n\\medskip\n\n\\noindent\nAlthough we do not recommend this unfolding to the user, it shows how to\nsimulate nested recursion by mutual recursion.\nNow we return to the initial definition of \\<open>term\\<close> using\nnested recursion.\n\nLet us define a substitution function on terms. Because terms involve term\nlists, we need to define two substitution functions simultaneously:\n\\<close>\n\nprimrec\nsubst :: \"('v\\<Rightarrow>('v,'f)term) \\<Rightarrow> ('v,'f)term      \\<Rightarrow> ('v,'f)term\" and\nsubsts:: \"('v\\<Rightarrow>('v,'f)term) \\<Rightarrow> ('v,'f)term list \\<Rightarrow> ('v,'f)term list\"\nwhere\n\"subst s (Var x) = s x\" |\n  subst_App:\n\"subst s (App f ts) = App f (substs s ts)\" |\n\n\"substs s [] = []\" |\n\"substs s (t # ts) = subst s t # substs s ts\"\n\ntext\\<open>\\noindent\nIndividual equations in a \\commdx{primrec} definition may be\nnamed as shown for @{thm[source]subst_App}.\nThe significance of this device will become apparent below.\n\nSimilarly, when proving a statement about terms inductively, we need\nto prove a related statement about term lists simultaneously. For example,\nthe fact that the identity substitution does not change a term needs to be\nstrengthened and proved as follows:\n\\<close>\n\nlemma subst_id(*<*)(*referred to from ABexpr*)(*>*): \"subst  Var t  = (t ::('v,'f)term)  \\<and>\n                  substs Var ts = (ts::('v,'f)term list)\"\napply(induct_tac t and ts rule: subst.induct substs.induct, simp_all)\ndone\n\ntext\\<open>\\noindent\nNote that \\<^term>\\<open>Var\\<close> is the identity substitution because by definition it\nleaves variables unchanged: \\<^prop>\\<open>subst Var (Var x) = Var x\\<close>. Note also\nthat the type annotations are necessary because otherwise there is nothing in\nthe goal to enforce that both halves of the goal talk about the same type\nparameters \\<open>('v,'f)\\<close>. As a result, induction would fail\nbecause the two halves of the goal would be unrelated.\n\n\\begin{exercise}\nThe fact that substitution distributes over composition can be expressed\nroughly as follows:\n@{text[display]\"subst (f \\<circ> g) t = subst f (subst g t)\"}\nCorrect this statement (you will find that it does not type-check),\nstrengthen it, and prove it. (Note: \\<open>\\<circ>\\<close> is function composition;\nits definition is found in theorem @{thm[source]o_def}).\n\\end{exercise}\n\\begin{exercise}\\label{ex:trev-trev}\n  Define a function \\<^term>\\<open>trev\\<close> of type \\<^typ>\\<open>('v,'f)term => ('v,'f)term\\<close>\nthat recursively reverses the order of arguments of all function symbols in a\n  term. Prove that \\<^prop>\\<open>trev(trev t) = t\\<close>.\n\\end{exercise}\n\nThe experienced functional programmer may feel that our definition of\n\\<^term>\\<open>subst\\<close> is too complicated in that \\<^const>\\<open>substs\\<close> is\nunnecessary. The \\<^term>\\<open>App\\<close>-case can be defined directly as\n@{term[display]\"subst s (App f ts) = App f (map (subst s) ts)\"}\nwhere \\<^term>\\<open>map\\<close> is the standard list function such that\n\\<open>map f [x1,...,xn] = [f x1,...,f xn]\\<close>. This is true, but Isabelle\ninsists on the conjunctive format. Fortunately, we can easily \\emph{prove}\nthat the suggested equation holds:\n\\<close>\n(*<*)\n(* Exercise 1: *)\nlemma \"subst  ((subst f) \\<circ> g) t  = subst  f (subst g t) \\<and>\n       substs ((subst f) \\<circ> g) ts = substs f (substs g ts)\"\napply (induct_tac t and ts rule: subst.induct substs.induct)\napply (simp_all)\ndone\n\n(* Exercise 2: *)\n\nprimrec trev :: \"('v,'f) term \\<Rightarrow> ('v,'f) term\"\n  and trevs:: \"('v,'f) term list \\<Rightarrow> ('v,'f) term list\"\nwhere\n  \"trev (Var v)    = Var v\"\n| \"trev (App f ts) = App f (trevs ts)\"\n| \"trevs [] = []\"\n| \"trevs (t#ts) = (trevs ts) @ [(trev t)]\" \n\n\n\nlemma \"trev (trev t) = (t::('v,'f)term) \\<and> \n       trevs (trevs ts) = (ts::('v,'f)term list)\"\napply (induct_tac t and ts rule: trev.induct trevs.induct, simp_all)\ndone\n(*>*)\n\nlemma [simp]: \"subst s (App f ts) = App f (map (subst s) ts)\"\napply(induct_tac ts, simp_all)\ndone\n\ntext\\<open>\\noindent\nWhat is more, we can now disable the old defining equation as a\nsimplification rule:\n\\<close>\n\ndeclare subst_App [simp del]\n\ntext\\<open>\\noindent The advantage is that now we have replaced \\<^const>\\<open>substs\\<close> by \\<^const>\\<open>map\\<close>, we can profit from the large number of\npre-proved lemmas about \\<^const>\\<open>map\\<close>.  Unfortunately, inductive proofs\nabout type \\<open>term\\<close> are still awkward because they expect a\nconjunction. One could derive a new induction principle as well (see\n\\S\\ref{sec:derive-ind}), but simpler is to stop using\n\\isacommand{primrec} and to define functions with \\isacommand{fun}\ninstead.  Simple uses of \\isacommand{fun} are described in\n\\S\\ref{sec:fun} below.  Advanced applications, including functions\nover nested datatypes like \\<open>term\\<close>, are discussed in a\nseparate tutorial~\\<^cite>\\<open>\"isabelle-function\"\\<close>.\n\nOf course, you may also combine mutual and nested recursion of datatypes. For example,\nconstructor \\<open>Sum\\<close> in \\S\\ref{sec:datatype-mut-rec} could take a list of\nexpressions as its argument: \\<open>Sum\\<close>~@{typ[quotes]\"'a aexp list\"}.\n\\<close>\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/Datatype/Nested.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8267117940706735, "lm_q2_score": 0.853912747375134, "lm_q1q2_score": 0.7059397393623148}}
{"text": "(* Author: Tobias Nipkow, TU Muenchen *)\n\nsection \\<open>Sum and product over lists\\<close>\n\ntheory Groups_List\nimports List\nbegin\n\nlocale monoid_list = monoid\nbegin\n \ndefinition F :: \"'a list \\<Rightarrow> 'a\"\nwhere\n  eq_foldr [code]: \"F xs = foldr f xs \\<^bold>1\"\n \nlemma Nil [simp]:\n  \"F [] = \\<^bold>1\"\n  by (simp add: eq_foldr)\n \nlemma Cons [simp]:\n  \"F (x # xs) = x \\<^bold>* F xs\"\n  by (simp add: eq_foldr)\n \nlemma append [simp]:\n  \"F (xs @ ys) = F xs \\<^bold>* F ys\"\n  by (induct xs) (simp_all add: assoc)\n \nend\n\nlocale comm_monoid_list = comm_monoid + monoid_list\nbegin\n \nlemma rev [simp]:\n  \"F (rev xs) = F xs\"\n  by (simp add: eq_foldr foldr_fold  fold_rev fun_eq_iff assoc left_commute)\n \nend\n \nlocale comm_monoid_list_set = list: comm_monoid_list + set: comm_monoid_set\nbegin\n\nlemma distinct_set_conv_list:\n  \"distinct xs \\<Longrightarrow> set.F g (set xs) = list.F (map g xs)\"\n  by (induct xs) simp_all\n\nlemma set_conv_list [code]:\n  \"set.F g (set xs) = list.F (map g (remdups xs))\"\n  by (simp add: distinct_set_conv_list [symmetric])\n\nend\n\n\nsubsection \\<open>List summation\\<close>\n\ncontext monoid_add\nbegin\n\nsublocale sum_list: monoid_list plus 0\ndefines\n  sum_list = sum_list.F ..\n \nend\n\ncontext comm_monoid_add\nbegin\n\nsublocale sum_list: comm_monoid_list plus 0\nrewrites\n  \"monoid_list.F plus 0 = sum_list\"\nproof -\n  show \"comm_monoid_list plus 0\" ..\n  then interpret sum_list: comm_monoid_list plus 0 .\n  from sum_list_def show \"monoid_list.F plus 0 = sum_list\" by simp\nqed\n\nsublocale sum: comm_monoid_list_set plus 0\nrewrites\n  \"monoid_list.F plus 0 = sum_list\"\n  and \"comm_monoid_set.F plus 0 = sum\"\nproof -\n  show \"comm_monoid_list_set plus 0\" ..\n  then interpret sum: comm_monoid_list_set plus 0 .\n  from sum_list_def show \"monoid_list.F plus 0 = sum_list\" by simp\n  from sum_def show \"comm_monoid_set.F plus 0 = sum\" by (auto intro: sym)\nqed\n\nend\n\ntext \\<open>Some syntactic sugar for summing a function over a list:\\<close>\nsyntax (ASCII)\n  \"_sum_list\" :: \"pttrn => 'a list => 'b => 'b\"    (\"(3SUM _<-_. _)\" [0, 51, 10] 10)\nsyntax\n  \"_sum_list\" :: \"pttrn => 'a list => 'b => 'b\"    (\"(3\\<Sum>_\\<leftarrow>_. _)\" [0, 51, 10] 10)\ntranslations \\<comment> \\<open>Beware of argument permutation!\\<close>\n  \"\\<Sum>x\\<leftarrow>xs. b\" == \"CONST sum_list (CONST map (\\<lambda>x. b) xs)\"\n\ntext \\<open>TODO duplicates\\<close>\nlemmas sum_list_simps = sum_list.Nil sum_list.Cons\nlemmas sum_list_append = sum_list.append\nlemmas sum_list_rev = sum_list.rev\n\nlemma (in monoid_add) fold_plus_sum_list_rev:\n  \"fold plus xs = plus (sum_list (rev xs))\"\nproof\n  fix x\n  have \"fold plus xs x = sum_list (rev xs @ [x])\"\n    by (simp add: foldr_conv_fold sum_list.eq_foldr)\n  also have \"\\<dots> = sum_list (rev xs) + x\"\n    by simp\n  finally show \"fold plus xs x = sum_list (rev xs) + x\"\n    .\nqed\n\nlemma (in comm_monoid_add) sum_list_map_remove1:\n  \"x \\<in> set xs \\<Longrightarrow> sum_list (map f xs) = f x + sum_list (map f (remove1 x xs))\"\n  by (induct xs) (auto simp add: ac_simps)\n\nlemma (in monoid_add) size_list_conv_sum_list:\n  \"size_list f xs = sum_list (map f xs) + size xs\"\n  by (induct xs) auto\n\nlemma (in monoid_add) length_concat:\n  \"length (concat xss) = sum_list (map length xss)\"\n  by (induct xss) simp_all\n\nlemma (in monoid_add) length_product_lists:\n  \"length (product_lists xss) = foldr op * (map length xss) 1\"\nproof (induct xss)\n  case (Cons xs xss) then show ?case by (induct xs) (auto simp: length_concat o_def)\nqed simp\n\nlemma (in monoid_add) sum_list_map_filter:\n  assumes \"\\<And>x. x \\<in> set xs \\<Longrightarrow> \\<not> P x \\<Longrightarrow> f x = 0\"\n  shows \"sum_list (map f (filter P xs)) = sum_list (map f xs)\"\n  using assms by (induct xs) auto\n\nlemma (in comm_monoid_add) distinct_sum_list_conv_Sum:\n  \"distinct xs \\<Longrightarrow> sum_list xs = Sum (set xs)\"\n  by (induct xs) simp_all\n\nlemma sum_list_upt[simp]:\n  \"m \\<le> n \\<Longrightarrow> sum_list [m..<n] = \\<Sum> {m..<n}\"\nby(simp add: distinct_sum_list_conv_Sum)\n\nlemma sum_list_eq_0_nat_iff_nat [simp]:\n  \"sum_list ns = (0::nat) \\<longleftrightarrow> (\\<forall>n \\<in> set ns. n = 0)\"\n  by (induct ns) simp_all\n\nlemma member_le_sum_list_nat:\n  \"(n :: nat) \\<in> set ns \\<Longrightarrow> n \\<le> sum_list ns\"\n  by (induct ns) auto\n\nlemma elem_le_sum_list_nat:\n  \"k < size ns \\<Longrightarrow> ns ! k \\<le> sum_list (ns::nat list)\"\n  by (rule member_le_sum_list_nat) simp\n\nlemma sum_list_update_nat:\n  \"k < size ns \\<Longrightarrow> sum_list (ns[k := (n::nat)]) = sum_list ns + n - ns ! k\"\napply(induct ns arbitrary:k)\n apply (auto split:nat.split)\napply(drule elem_le_sum_list_nat)\napply arith\ndone\n\nlemma (in monoid_add) sum_list_triv:\n  \"(\\<Sum>x\\<leftarrow>xs. r) = of_nat (length xs) * r\"\n  by (induct xs) (simp_all add: distrib_right)\n\nlemma (in monoid_add) sum_list_0 [simp]:\n  \"(\\<Sum>x\\<leftarrow>xs. 0) = 0\"\n  by (induct xs) (simp_all add: distrib_right)\n\ntext\\<open>For non-Abelian groups \\<open>xs\\<close> needs to be reversed on one side:\\<close>\nlemma (in ab_group_add) uminus_sum_list_map:\n  \"- sum_list (map f xs) = sum_list (map (uminus \\<circ> f) xs)\"\n  by (induct xs) simp_all\n\nlemma (in comm_monoid_add) sum_list_addf:\n  \"(\\<Sum>x\\<leftarrow>xs. f x + g x) = sum_list (map f xs) + sum_list (map g xs)\"\n  by (induct xs) (simp_all add: algebra_simps)\n\nlemma (in ab_group_add) sum_list_subtractf:\n  \"(\\<Sum>x\\<leftarrow>xs. f x - g x) = sum_list (map f xs) - sum_list (map g xs)\"\n  by (induct xs) (simp_all add: algebra_simps)\n\nlemma (in semiring_0) sum_list_const_mult:\n  \"(\\<Sum>x\\<leftarrow>xs. c * f x) = c * (\\<Sum>x\\<leftarrow>xs. f x)\"\n  by (induct xs) (simp_all add: algebra_simps)\n\nlemma (in semiring_0) sum_list_mult_const:\n  \"(\\<Sum>x\\<leftarrow>xs. f x * c) = (\\<Sum>x\\<leftarrow>xs. f x) * c\"\n  by (induct xs) (simp_all add: algebra_simps)\n\nlemma (in ordered_ab_group_add_abs) sum_list_abs:\n  \"\\<bar>sum_list xs\\<bar> \\<le> sum_list (map abs xs)\"\n  by (induct xs) (simp_all add: order_trans [OF abs_triangle_ineq])\n\nlemma sum_list_mono:\n  fixes f g :: \"'a \\<Rightarrow> 'b::{monoid_add, ordered_ab_semigroup_add}\"\n  shows \"(\\<And>x. x \\<in> set xs \\<Longrightarrow> f x \\<le> g x) \\<Longrightarrow> (\\<Sum>x\\<leftarrow>xs. f x) \\<le> (\\<Sum>x\\<leftarrow>xs. g x)\"\n  by (induct xs) (simp, simp add: add_mono)\n\nlemma (in monoid_add) sum_list_distinct_conv_sum_set:\n  \"distinct xs \\<Longrightarrow> sum_list (map f xs) = sum f (set xs)\"\n  by (induct xs) simp_all\n\nlemma (in monoid_add) interv_sum_list_conv_sum_set_nat:\n  \"sum_list (map f [m..<n]) = sum f (set [m..<n])\"\n  by (simp add: sum_list_distinct_conv_sum_set)\n\nlemma (in monoid_add) interv_sum_list_conv_sum_set_int:\n  \"sum_list (map f [k..l]) = sum f (set [k..l])\"\n  by (simp add: sum_list_distinct_conv_sum_set)\n\ntext \\<open>General equivalence between @{const sum_list} and @{const sum}\\<close>\nlemma (in monoid_add) sum_list_sum_nth:\n  \"sum_list xs = (\\<Sum> i = 0 ..< length xs. xs ! i)\"\n  using interv_sum_list_conv_sum_set_nat [of \"op ! xs\" 0 \"length xs\"] by (simp add: map_nth)\n\nlemma sum_list_map_eq_sum_count:\n  \"sum_list (map f xs) = sum (\\<lambda>x. count_list xs x * f x) (set xs)\"\nproof(induction xs)\n  case (Cons x xs)\n  show ?case (is \"?l = ?r\")\n  proof cases\n    assume \"x \\<in> set xs\"\n    have \"?l = f x + (\\<Sum>x\\<in>set xs. count_list xs x * f x)\" by (simp add: Cons.IH)\n    also have \"set xs = insert x (set xs - {x})\" using \\<open>x \\<in> set xs\\<close>by blast\n    also have \"f x + (\\<Sum>x\\<in>insert x (set xs - {x}). count_list xs x * f x) = ?r\"\n      by (simp add: sum.insert_remove eq_commute)\n    finally show ?thesis .\n  next\n    assume \"x \\<notin> set xs\"\n    hence \"\\<And>xa. xa \\<in> set xs \\<Longrightarrow> x \\<noteq> xa\" by blast\n    thus ?thesis by (simp add: Cons.IH \\<open>x \\<notin> set xs\\<close>)\n  qed\nqed simp\n\nlemma sum_list_map_eq_sum_count2:\nassumes \"set xs \\<subseteq> X\" \"finite X\"\nshows \"sum_list (map f xs) = sum (\\<lambda>x. count_list xs x * f x) X\"\nproof-\n  let ?F = \"\\<lambda>x. count_list xs x * f x\"\n  have \"sum ?F X = sum ?F (set xs \\<union> (X - set xs))\"\n    using Un_absorb1[OF assms(1)] by(simp)\n  also have \"\\<dots> = sum ?F (set xs)\"\n    using assms(2)\n    by(simp add: sum.union_disjoint[OF _ _ Diff_disjoint] del: Un_Diff_cancel)\n  finally show ?thesis by(simp add:sum_list_map_eq_sum_count)\nqed\n\nlemma sum_list_nonneg: \n    \"(\\<And>x. x \\<in> set xs \\<Longrightarrow> (x :: 'a :: ordered_comm_monoid_add) \\<ge> 0) \\<Longrightarrow> sum_list xs \\<ge> 0\"\n  by (induction xs) simp_all\n\nlemma (in monoid_add) sum_list_map_filter':\n  \"sum_list (map f (filter P xs)) = sum_list (map (\\<lambda>x. if P x then f x else 0) xs)\"\n  by (induction xs) simp_all\n\nlemma sum_list_cong [fundef_cong]:\n  assumes \"xs = ys\"\n  assumes \"\\<And>x. x \\<in> set xs \\<Longrightarrow> f x = g x\"\n  shows    \"sum_list (map f xs) = sum_list (map g ys)\"\nproof -\n  from assms(2) have \"sum_list (map f xs) = sum_list (map g xs)\"\n    by (induction xs) simp_all\n  with assms(1) show ?thesis by simp\nqed\n\n\nsubsection \\<open>Further facts about @{const List.n_lists}\\<close>\n\nlemma length_n_lists: \"length (List.n_lists n xs) = length xs ^ n\"\n  by (induct n) (auto simp add: comp_def length_concat sum_list_triv)\n\nlemma distinct_n_lists:\n  assumes \"distinct xs\"\n  shows \"distinct (List.n_lists n xs)\"\nproof (rule card_distinct)\n  from assms have card_length: \"card (set xs) = length xs\" by (rule distinct_card)\n  have \"card (set (List.n_lists n xs)) = card (set xs) ^ n\"\n  proof (induct n)\n    case 0 then show ?case by simp\n  next\n    case (Suc n)\n    moreover have \"card (\\<Union>ys\\<in>set (List.n_lists n xs). (\\<lambda>y. y # ys) ` set xs)\n      = (\\<Sum>ys\\<in>set (List.n_lists n xs). card ((\\<lambda>y. y # ys) ` set xs))\"\n      by (rule card_UN_disjoint) auto\n    moreover have \"\\<And>ys. card ((\\<lambda>y. y # ys) ` set xs) = card (set xs)\"\n      by (rule card_image) (simp add: inj_on_def)\n    ultimately show ?case by auto\n  qed\n  also have \"\\<dots> = length xs ^ n\" by (simp add: card_length)\n  finally show \"card (set (List.n_lists n xs)) = length (List.n_lists n xs)\"\n    by (simp add: length_n_lists)\nqed\n\n\nsubsection \\<open>Tools setup\\<close>\n\nlemmas sum_code = sum.set_conv_list\n\nlemma sum_set_upto_conv_sum_list_int [code_unfold]:\n  \"sum f (set [i..j::int]) = sum_list (map f [i..j])\"\n  by (simp add: interv_sum_list_conv_sum_set_int)\n\nlemma sum_set_upt_conv_sum_list_nat [code_unfold]:\n  \"sum f (set [m..<n]) = sum_list (map f [m..<n])\"\n  by (simp add: interv_sum_list_conv_sum_set_nat)\n\nlemma sum_list_transfer[transfer_rule]:\n  includes lifting_syntax\n  assumes [transfer_rule]: \"A 0 0\"\n  assumes [transfer_rule]: \"(A ===> A ===> A) op + op +\"\n  shows \"(list_all2 A ===> A) sum_list sum_list\"\n  unfolding sum_list.eq_foldr [abs_def]\n  by transfer_prover\n\n\nsubsection \\<open>List product\\<close>\n\ncontext monoid_mult\nbegin\n\nsublocale prod_list: monoid_list times 1\ndefines\n  prod_list = prod_list.F ..\n\nend\n\ncontext comm_monoid_mult\nbegin\n\nsublocale prod_list: comm_monoid_list times 1\nrewrites\n  \"monoid_list.F times 1 = prod_list\"\nproof -\n  show \"comm_monoid_list times 1\" ..\n  then interpret prod_list: comm_monoid_list times 1 .\n  from prod_list_def show \"monoid_list.F times 1 = prod_list\" by simp\nqed\n\nsublocale prod: comm_monoid_list_set times 1\nrewrites\n  \"monoid_list.F times 1 = prod_list\"\n  and \"comm_monoid_set.F times 1 = prod\"\nproof -\n  show \"comm_monoid_list_set times 1\" ..\n  then interpret prod: comm_monoid_list_set times 1 .\n  from prod_list_def show \"monoid_list.F times 1 = prod_list\" by simp\n  from prod_def show \"comm_monoid_set.F times 1 = prod\" by (auto intro: sym)\nqed\n\nend\n\nlemma prod_list_cong [fundef_cong]:\n  assumes \"xs = ys\"\n  assumes \"\\<And>x. x \\<in> set xs \\<Longrightarrow> f x = g x\"\n  shows    \"prod_list (map f xs) = prod_list (map g ys)\"\nproof -\n  from assms(2) have \"prod_list (map f xs) = prod_list (map g xs)\"\n    by (induction xs) simp_all\n  with assms(1) show ?thesis by simp\nqed\n\nlemma prod_list_zero_iff: \n  \"prod_list xs = 0 \\<longleftrightarrow> (0 :: 'a :: {semiring_no_zero_divisors, semiring_1}) \\<in> set xs\"\n  by (induction xs) simp_all\n\ntext \\<open>Some syntactic sugar:\\<close>\n\nsyntax (ASCII)\n  \"_prod_list\" :: \"pttrn => 'a list => 'b => 'b\"    (\"(3PROD _<-_. _)\" [0, 51, 10] 10)\nsyntax\n  \"_prod_list\" :: \"pttrn => 'a list => 'b => 'b\"    (\"(3\\<Prod>_\\<leftarrow>_. _)\" [0, 51, 10] 10)\ntranslations \\<comment> \\<open>Beware of argument permutation!\\<close>\n  \"\\<Prod>x\\<leftarrow>xs. b\" \\<rightleftharpoons> \"CONST prod_list (CONST map (\\<lambda>x. b) xs)\"\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/Groups_List.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127455162774, "lm_q2_score": 0.8267117919359419, "lm_q1q2_score": 0.7059397360027017}}
{"text": "\ntheory Boolean_functions\n  imports\n    Main\n    \"Jordan_Normal_Form.Matrix\"\nbegin\n\nsection\\<open>Boolean functions\\<close>\n\ntext\\<open>Definition of monotonicity\\<close>\n\ntext\\<open>We consider (monotone) Boolean\n  functions over vectors of length $n$, so that we can later\n  prove that those are isomorphic to\n  simplicial complexes of dimension $n$ (in $n$ vertexes).\\<close>\n\nlocale boolean_functions\n  = fixes n::\"nat\"\nbegin\n\ndefinition bool_fun_dim_n :: \"(bool vec => bool) set\"\n  where \"bool_fun_dim_n = {f. f \\<in> carrier_vec n \\<rightarrow> (UNIV::bool set)}\"\n\ndefinition monotone_bool_fun :: \"(bool vec => bool) => bool\"\n  where \"monotone_bool_fun \\<equiv> (mono_on (carrier_vec n))\"\n\ndefinition monotone_bool_fun_set :: \"(bool vec => bool) set\"\n  where \"monotone_bool_fun_set = (Collect monotone_bool_fun)\"\n\ntext\\<open>Some examples of Boolean functions\\<close>\n\ndefinition bool_fun_top :: \"bool vec => bool\"\n  where \"bool_fun_top f = True\"\n\ndefinition bool_fun_bot :: \"bool vec => bool\"\n  where \"bool_fun_bot f = False\"\n\nend\n\nsection\\<open>Threshold function\\<close>\n\ndefinition count_true :: \"bool vec => nat\"\n  where \"count_true v = sum (\\<lambda>i. if vec_index v i then 1 else 0::nat) {0..<dim_vec v}\"\n\nlemma \"vec_index (vec (5::nat) (\\<lambda>i. False)) 2 = False\"\n  by simp\n\nlemma \"vec_index (vec (5::nat) (\\<lambda>i. True)) 3 = True\"\n  by simp\n\nlemma \"count_true (vec (1::nat) (\\<lambda>i. True)) = 1\"\n  unfolding count_true_def by simp\n\nlemma \"count_true (vec (2::nat) (\\<lambda>i. True)) = 2\"\n  unfolding count_true_def by simp\n\nlemma \"count_true (vec (5::nat) (\\<lambda>i. True)) = 5\"\n  unfolding count_true_def by simp\n\ntext\\<open>The threshold function is a Boolean function\n  which also satisfies the condition of being \\emph{evasive}.\n  We follow the definition by Scoville~\\<^cite>\\<open>\\<open>Problem 6.5\\<close> in \"SC19\"\\<close>.\\<close>\n\ndefinition bool_fun_threshold :: \"nat => (bool vec => bool)\"\n  where \"bool_fun_threshold i = (\\<lambda>v. if i \\<le> count_true v then True else False)\"\n\ncontext boolean_functions\nbegin\n\nlemma \"mono_on UNIV bool_fun_top\"\n  by (simp add: bool_fun_top_def mono_onI monotone_bool_fun_def)\n\nlemma \"monotone_bool_fun bool_fun_top\"\n  by (simp add: bool_fun_top_def mono_onI monotone_bool_fun_def)\n\nlemma \"mono_on UNIV bool_fun_bot\"\n  by (simp add: bool_fun_bot_def mono_onI monotone_bool_fun_def)\n\nlemma \"monotone_bool_fun bool_fun_bot\"\n  by (simp add: bool_fun_bot_def mono_onI monotone_bool_fun_def)\n\nlemma\n  monotone_count_true:\n  assumes ulev: \"(u::bool vec) \\<le> v\"\n  shows \"count_true u \\<le> count_true v\"\n  unfolding count_true_def\n  using Groups_Big.ordered_comm_monoid_add_class.sum_mono\n    [of \"{0..<dim_vec u}\"\n      \"(\\<lambda>i. if vec_index u i then 1 else 0)\"\n      \"(\\<lambda>i. if vec_index v i then 1 else 0)\"]\n  using ulev\n  unfolding Matrix.less_eq_vec_def\n  by fastforce\n\ntext\\<open>The threshold function is monotone.\\<close>\n\nlemma\n  monotone_threshold:\n  assumes ulev: \"(u::bool vec) \\<le> v\"\n  shows \"bool_fun_threshold n u \\<le> bool_fun_threshold n v\"\n  unfolding bool_fun_threshold_def\n  using monotone_count_true [OF ulev] by simp\n\nlemma\n  assumes \"(u::bool vec) \\<le> v\"\n  and \"n < dim_vec u\"\n  shows \"bool_fun_threshold n u \\<le> bool_fun_threshold n v\"\n  using monotone_threshold [OF assms(1)] .\n\nlemma \"mono_on UNIV (bool_fun_threshold n)\"\n  by (meson mono_onI monotone_bool_fun_def monotone_threshold)\n\nlemma \"monotone_bool_fun (bool_fun_threshold n)\"\n  unfolding monotone_bool_fun_def\n  by (meson boolean_functions.monotone_threshold mono_onI)\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/Boolean_functions.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045877523148, "lm_q2_score": 0.7956581000631542, "lm_q1q2_score": 0.7059115166583207}}
{"text": "theory Supplementary_Ring_Facts\nimports \"HOL-Algebra.Ring\" \n        \"HOL-Algebra.UnivPoly\"\n        \"HOL-Algebra.Subrings\"\n\nbegin\n\nsection\\<open>Supplementary Ring Facts\\<close>\n\ntext\\<open>The nonzero elements of a ring.\\<close>\n\ndefinition nonzero :: \"('a, 'b) ring_scheme \\<Rightarrow> 'a set\" where\n\"nonzero R = {a \\<in> carrier R. a \\<noteq> \\<zero>\\<^bsub>R\\<^esub>}\"\n\n\nlemma zero_not_in_nonzero:\n\"\\<zero>\\<^bsub>R\\<^esub> \\<notin> nonzero R\"\n  unfolding nonzero_def by blast \n\nlemma(in domain) nonzero_memI:\n  assumes \"a \\<in> carrier R\"\n  assumes \"a \\<noteq> \\<zero>\"\n  shows \"a \\<in> nonzero R\"\n  using assms by(simp add: nonzero_def)\n\nlemma(in domain) nonzero_memE:\n  assumes \"a \\<in> nonzero R\"\n  shows \"a \\<in> carrier R\" \"a \\<noteq>\\<zero>\"\n  using assms by(auto simp: nonzero_def)\n\nlemma(in domain) not_nonzero_memE:\n  assumes \"a \\<notin> nonzero R\"\n  assumes \"a \\<in> carrier R\"\n  shows \"a = \\<zero>\"\n  using assms \n  by (simp add: nonzero_def)\n\nlemma(in domain) not_nonzero_memI:\n  assumes \"a = \\<zero>\"\n  shows \"a \\<notin> nonzero R\"\n  using assms nonzero_memE(2) by auto\n\nlemma(in domain) nonzero_closed:\n  assumes \"a \\<in> nonzero R\"\n  shows \"a \\<in> carrier R\"\n  using assms \n  by (simp add: nonzero_def)\n\nlemma(in domain) nonzero_mult_in_car:\n  assumes \"a \\<in> nonzero R\"\n  assumes \"b \\<in> nonzero R\"\n  shows \"a \\<otimes> b \\<in> carrier R\"\n  using assms \n  by (simp add: nonzero_def)\n\nlemma(in domain) nonzero_mult_closed:\n  assumes \"a \\<in> nonzero R\"\n  assumes \"b \\<in> nonzero R\"\n  shows \"a \\<otimes> b \\<in> nonzero R\"\n  apply(rule nonzero_memI)\n  using assms nonzero_memE apply blast\n    using assms nonzero_memE \n    by (simp add: integral_iff)    \n\nlemma(in domain) nonzero_one_closed:\n\"\\<one> \\<in> nonzero R\"\n  by (simp add: nonzero_def)\n\nlemma(in domain) one_nonzero:\n\"\\<one> \\<in> nonzero R\"\n  by (simp add: nonzero_one_closed)\n\nlemma(in domain) nat_pow_nonzero:\n  assumes \"x \\<in>nonzero R\"\n  shows \"x[^](n::nat) \\<in> nonzero R\"\n  unfolding nonzero_def \n  apply(induction n)\n  using assms integral_iff nonzero_closed zero_not_in_nonzero by auto\n\nlemma(in monoid) Units_int_pow_closed:\n  assumes \"x \\<in> Units G\"\n  shows \"x[^](n::int) \\<in> Units G\"\n  by (metis Units_pow_closed assms int_pow_def2 monoid.Units_inv_Units monoid_axioms)\n\nlemma(in comm_monoid) UnitsI:\n  assumes \"a \\<in> carrier G\"\n  assumes \"b \\<in> carrier G\"\n  assumes \"a \\<otimes> b = \\<one>\"\n  shows \"a \\<in> Units G\" \"b \\<in> Units G\" \n  unfolding Units_def using comm_monoid_axioms_def assms m_comm[of a b] \n  by auto \n\nlemma(in comm_monoid) is_invI:\n  assumes \"a \\<in> carrier G\"\n  assumes \"b \\<in> carrier G\"\n  assumes \"a \\<otimes> b = \\<one>\"\n  shows \"inv\\<^bsub>G\\<^esub> b = a\" \"inv\\<^bsub>G\\<^esub> a = b\"\n  using assms inv_char m_comm \n  by auto\n\nlemma(in ring) ring_in_Units_imp_not_zero:\n  assumes \"\\<one> \\<noteq> \\<zero>\"\n  assumes \"a \\<in> Units R\"\n  shows \"a \\<noteq> \\<zero>\"\n  using assms monoid.Units_l_cancel\n  by (metis l_null  monoid_axioms one_closed zero_closed)\n\nlemma(in ring) Units_nonzero:\n  assumes \"u \\<in> Units R\"\n  assumes \"\\<one>\\<^bsub>R\\<^esub> \\<noteq> \\<zero>\\<^bsub>R\\<^esub>\"\n  shows \"u \\<in> nonzero R\"\nproof-\n  have \"u \\<in>carrier R\" \n    using Units_closed assms by auto\n  have \"u \\<noteq>\\<zero>\" \n    using Units_r_inv_ex assms(1) assms(2) \n    by force \n  thus ?thesis \n    by (simp add: \\<open>u \\<in> carrier R\\<close> nonzero_def)\nqed\n\n\nlemma(in ring) Units_inverse:\n  assumes \"u \\<in> Units R\"\n  shows \"inv u \\<in> Units R\"\n  by (simp add: assms)\n\nlemma(in cring) invI:  \n  assumes \"x \\<in> carrier R\"\n  assumes \"y \\<in> carrier R\"\n  assumes \"x \\<otimes>\\<^bsub>R\\<^esub> y = \\<one>\\<^bsub>R\\<^esub>\"\n  shows \"y = inv \\<^bsub>R\\<^esub> x\"\n        \"x = inv \\<^bsub>R\\<^esub> y\"\n  using assms(1) assms(2) assms(3) is_invI \n  by auto \n\nlemma(in cring) inv_cancelR:\n  assumes \"x \\<in> Units R\"\n  assumes \"y \\<in> carrier R\"\n  assumes \"z \\<in> carrier R\"\n  assumes \"y = x \\<otimes>\\<^bsub>R\\<^esub> z\"\n  shows \"inv\\<^bsub>R\\<^esub> x \\<otimes>\\<^bsub>R\\<^esub> y = z\"\n        \"y \\<otimes>\\<^bsub>R\\<^esub> (inv\\<^bsub>R\\<^esub> x)  = z\"\n  apply (metis Units_closed assms(1) assms(3) assms(4) cring.cring_simprules(12) \n    is_cring m_assoc monoid.Units_inv_closed monoid.Units_l_inv monoid_axioms)\n  by (metis Units_closed assms(1) assms(3) assms(4) m_assoc m_comm monoid.Units_inv_closed \n      monoid.Units_r_inv monoid.r_one monoid_axioms)\n   \nlemma(in cring) inv_cancelL:\n  assumes \"x \\<in> Units R\"\n  assumes \"y \\<in> carrier R\"\n  assumes \"z \\<in> carrier R\"\n  assumes \"y = z \\<otimes>\\<^bsub>R\\<^esub> x\"\n  shows \"inv\\<^bsub>R\\<^esub> x \\<otimes>\\<^bsub>R\\<^esub> y = z\"\n        \"y \\<otimes>\\<^bsub>R\\<^esub> (inv\\<^bsub>R\\<^esub> x)  = z\"\n  apply (simp add: Units_closed assms(1) assms(3) assms(4) m_lcomm)\n  by (simp add: Units_closed assms(1) assms(3) assms(4) m_assoc)\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_Ints/Supplementary_Ring_Facts.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8872045877523146, "lm_q2_score": 0.7956580927949807, "lm_q1q2_score": 0.7059115102099637}}
{"text": "(*  Title:     Sensors.thy\n    Author:     Sven Linker\n\nDefines perfect sensors for cars. Cars can perceive both\nthe physical size and braking distance of all other cars.\n*)\n\nsection\\<open> Sensors for Cars\\<close>\ntext\\<open>\nThis section presents the abstract definition of a function\ndetermining the sensor capabilities of cars. Such a function\ntakes a car \\(e\\), a traffic snapshot \\(ts\\) and another\ncar \\(c\\), and returns the length of \\(c\\) as perceived\nby \\(e\\) at the situation determined by \\(ts\\). The \nonly restriction we impose is that this length is always\ngreater than zero.\n\nWith such a function, we define a derived notion of the\n\\emph{space} the car \\(c\\) occupies as perceived by \\(e\\).\nHowever, this does not define the lanes \\(c\\) occupies, but\nonly a continuous interval. The lanes occupied by \\(c\\) \nare given by the reservation and claim functions of \nthe traffic snapshot \\(ts\\).\n\\<close>\n  \ntheory Sensors\n  imports \"Traffic\" \"Views\"\nbegin \n\nlocale sensors = traffic + view +\n  fixes sensors::\"(cars) \\<Rightarrow> traffic \\<Rightarrow> (cars) \\<Rightarrow> real\" \n  assumes sensors_ge:\"(sensors e ts c) > 0\"\nbegin\n  \ndefinition space ::\" traffic \\<Rightarrow> view \\<Rightarrow> cars \\<Rightarrow> real_int\"\n  where \"space ts v c \\<equiv> stretch (pos ts c)  ( sensors (own v) ts c)\"\n    \nlemma left_space: \"left (space ts v c) = pos ts c\" \n  using sensors_ge space_def stretch_left \n  by (simp add: less_eq_real_def)\n  \nlemma right_space: \"right (space ts v c) =   pos ts c + sensors (own v) ts c\"\n  using sensors_ge space_def stretch_right \n  by (simp add: less_eq_real_def)\n  \nlemma space_nonempty:\"left (space ts v c ) < right (space ts v c)\" \n  using left_space right_space sensors_ge by simp\n    \nend\nend\n", "meta": {"author": "svenlinker", "repo": "HMLSL", "sha": "ef3a68683db42f2eebd5f0f45cbebdf73da78571", "save_path": "github-repos/isabelle/svenlinker-HMLSL", "path": "github-repos/isabelle/svenlinker-HMLSL/HMLSL-ef3a68683db42f2eebd5f0f45cbebdf73da78571/Sensors.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8872045877523147, "lm_q2_score": 0.7956580903722561, "lm_q1q2_score": 0.7059115080605114}}
{"text": "theory ValuesFSet\n  imports Main Lambda \"HOL-Library.FSet\" \nbegin\n\ndatatype val = VNat nat | VFun \"(val \\<times> val) fset\" | VPair val val\n\ntype_synonym func = \"(val \\<times> val) fset\"\n\ninductive val_le :: \"val \\<Rightarrow> val \\<Rightarrow> bool\" (infix \"\\<sqsubseteq>\" 52) where\n  vnat_le[intro!]: \"(VNat n) \\<sqsubseteq> (VNat n)\" |\n  vfun_le[intro!]: \"fset t1 \\<subseteq> fset t2 \\<Longrightarrow> (VFun t1) \\<sqsubseteq> (VFun t2)\" |\n  vpair_le[intro!]: \"v1 \\<sqsubseteq> v1' \\<and> v2 \\<sqsubseteq> v2' \\<Longrightarrow> (VPair v1 v2) \\<sqsubseteq> (VPair v1' v2')\"\n\ntype_synonym env = \"((name \\<times> val) list)\"\n\ndefinition env_le :: \"env \\<Rightarrow> env \\<Rightarrow> bool\" (infix \"\\<sqsubseteq>\" 52) where \n  \"\\<rho> \\<sqsubseteq> \\<rho>' \\<equiv> \\<forall> x v. lookup \\<rho> x = Some v \\<longrightarrow> (\\<exists> v'. lookup \\<rho>' x = Some v' \\<and> v \\<sqsubseteq> v')\" \n\ndefinition env_eq :: \"env \\<Rightarrow> env \\<Rightarrow> bool\" (infix \"\\<approx>\" 50) where\n  \"\\<rho> \\<approx> \\<rho>' \\<equiv> (\\<forall> x. lookup \\<rho> x = lookup \\<rho>' x)\"\n\nfun vadd :: \"(val \\<times> nat) \\<times> (val \\<times> nat) \\<Rightarrow> nat \\<Rightarrow> nat\" where\n  \"vadd ((_,v),(_,u)) r = v + u + r\"\n  \nprimrec vsize :: \"val \\<Rightarrow> nat\" where\n\"vsize (VNat n) = 1\" |\n\"vsize (VPair v1 v2) = 1 + (vsize v1) + (vsize v2)\" |\n\"vsize (VFun t) = 1 + ffold vadd 0\n                            (fimage (map_prod (\\<lambda> v. (v,vsize v)) (\\<lambda> v. (v,vsize v))) t)\"\n\nabbreviation vprod_size :: \"val \\<times> val \\<Rightarrow> (val \\<times> nat) \\<times> (val \\<times> nat)\" where\n  \"vprod_size \\<equiv> map_prod (\\<lambda> v. (v,vsize v)) (\\<lambda> v. (v,vsize v))\"\n\nabbreviation fsize :: \"func \\<Rightarrow> nat\" where\n  \"fsize t \\<equiv> 1 + ffold vadd 0 (fimage vprod_size t)\"\n\ninterpretation vadd_vprod: comp_fun_commute \"vadd \\<circ> vprod_size\"\n  unfolding comp_fun_commute_def by auto  \n\nlemma vprod_size_inj: \"inj_on vprod_size (fset A)\"\n  unfolding inj_on_def by auto\n  \nlemma fsize_def2: \"fsize t = 1 + ffold (vadd \\<circ> vprod_size) 0 t\"\n  using vprod_size_inj[of t] ffold_fimage[of vprod_size t vadd 0] by simp\n\nlemma fsize_finsert_in[simp]:\n  assumes v12_t: \"(v1,v2) |\\<in>| t\" shows \"fsize (finsert (v1,v2) t) = fsize t\"\nproof -\n  from v12_t have \"finsert (v1,v2) t = t\" by auto\n  from this show ?thesis by simp\nqed\n \nlemma fsize_finsert_notin[simp]: \n  assumes v12_t: \"(v1,v2) |\\<notin>| t\"\n  shows \"fsize (finsert (v1,v2) t) = vsize v1 + vsize v2 + fsize t\"\nproof -\n  let ?f = \"vadd \\<circ> vprod_size\"\n  have \"fsize (finsert (v1,v2) t) = 1 + ffold ?f 0 (finsert (v1,v2) t)\"\n    using fsize_def2[of \"finsert (v1,v2) t\"] by simp\n  also from v12_t have \"... = 1 + ?f (v1,v2) (ffold ?f 0 t)\" by simp\n  finally have \"fsize (finsert (v1,v2) t) = 1 + ?f (v1,v2) (ffold ?f 0 t)\" .\n  from this show ?thesis using fsize_def2[of t] by simp\nqed\n    \nend\n  ", "meta": {"author": "cderici", "repo": "denotational-semantics-LC-with-pairs", "sha": "23081a67ee7d9035b62052d9206cd5e97d3e141f", "save_path": "github-repos/isabelle/cderici-denotational-semantics-LC-with-pairs", "path": "github-repos/isabelle/cderici-denotational-semantics-LC-with-pairs/denotational-semantics-LC-with-pairs-23081a67ee7d9035b62052d9206cd5e97d3e141f/Decl_Sem_Fun_PL-with-pairs/ValuesFSet.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206712569267, "lm_q2_score": 0.782662489091802, "lm_q1q2_score": 0.7058994775292952}}
{"text": "theory Imp\n  imports Basics\nbegin\n\ndatatype aexp = ANum nat |\n                APlus aexp aexp |\n                AMinus aexp aexp |\n                AMult aexp aexp\n\ndatatype bexp = BTrue |\n                BFalse |\n                BEq aexp aexp |\n                BLe aexp aexp |\n                BNot bexp |\n                BAnd bexp bexp\n\nsection {* Evaluation *}\n\nfun aeval :: \"aexp \\<Rightarrow> nat\" where\n  \"aeval (ANum n) = n\"\n| \"aeval (APlus a1 a2) = (aeval a1) + (aeval a2)\"\n| \"aeval (AMinus a1 a2) = (aeval a1) - (aeval a2)\"\n| \"aeval (AMult a1 a2) = (aeval a1) * (aeval a2)\"\n\nlemma test_aeval: \"aeval (APlus (ANum 2) (ANum 2)) = 4\"\n  apply (simp)\n  done\n\nfun beval :: \"bexp \\<Rightarrow> bool\" where\n  \"beval BTrue = True\"\n| \"beval BFalse = False\"\n| \"beval (BEq a1 a2) = beq_nat (aeval a1) (aeval a2)\"\n| \"beval (BLe a1 a2) = leb (aeval a1) (aeval a2)\"\n| \"beval (BNot b1) = negb (beval b1)\"\n| \"beval (BAnd b1 b2) = andb (beval b1) (beval b2)\"\n\nsection {* Optimization *}\n\nfun optimize_0plus :: \"aexp \\<Rightarrow> aexp\" where\n  \"optimize_0plus (ANum n) = ANum n\"\n| \"optimize_0plus (APlus (ANum 0) e2) = e2\"\n| \"optimize_0plus (APlus e1 e2) = APlus (optimize_0plus e1) (optimize_0plus e2)\"\n| \"optimize_0plus (AMinus e1 e2) = AMinus (optimize_0plus e1) (optimize_0plus e2)\"\n| \"optimize_0plus (AMult e1 e2) = AMult (optimize_0plus e1) (optimize_0plus e2)\"\n\nlemma test_optimize_0plus:\n  \"(beval (BEq (optimize_0plus (APlus (ANum (Suc 1)) (APlus (ANum 0) (APlus (ANum 0) (ANum 1)))))\n           (APlus (ANum (Suc 1)) (ANum 1)))) = True\"\n  apply (simp)\n  done\n\ntheorem optimize_0plus_sound: \"aeval (optimize_0plus a) = aeval a\"\n  apply (induction a)\n     apply (simp) (* ANum *)\n    apply (cases a) (* APlus *)\n       apply (simp)\n  oops\n\nsection {* Expression with variables *}\n\ndatatype aexpr = ANum nat |\n                 AId string |\n                 APlus aexpr aexpr |\n                 AMinus aexpr aexpr |\n                AMult aexpr aexpr\n\ndefinition W :: string where \"W = ''W''\"\ndefinition X :: string where \"X = ''X''\"\ndefinition Y :: string where \"Y = ''Y''\"\ndefinition Z :: string where \"Z = ''Z''\"\n\ndatatype bexpr = BTrue |\n                BFalse |\n                BEq aexpr aexpr |\n                BLe aexpr aexpr |\n                BNot bexpr |\n                BAnd bexpr bexpr\n\ntype_synonym state = \"string \\<Rightarrow> nat\"\n\nfun aval :: \"state \\<Rightarrow> aexpr \\<Rightarrow> nat\" where\n  \"aval _ (ANum n) = n\"\n| \"aval st (AId x) = st x\"\n| \"aval st (APlus a1 a2) = (aval st a1) + (aval st a2)\"\n| \"aval st (AMinus a1 a2) = (aval st a1) - (aval st a2)\"\n| \"aval st (AMult a1 a2) = (aval st a1) * (aval st a2)\"\n\nfun bval :: \"state \\<Rightarrow> bexpr \\<Rightarrow> bool\" where\n  \"bval _ BTrue = True\"\n| \"bval _ BFalse = False\"\n| \"bval st (BEq a1 a2) = beq_nat (aval st a1) (aval st a2)\"\n| \"bval st (BLe a1 a2) = leb (aval st a1) (aval st a2)\"\n| \"bval st (BNot b1) = negb (bval st b1)\"\n| \"bval st (BAnd b1 b2) = andb (bval st b1) (bval st b2)\"\n\nvalue \"aval (\\<lambda> x. 0) (APlus (ANum 3) (AId ''v''))\"\n\nsubsection {* Notation *}\n\ndefinition bool_to_bexpr :: \"Basics.bool \\<Rightarrow> bexpr\" where\n  \"bool_to_bexpr b = (if b = True then BTrue else BFalse)\"\n\nsection {* Command *}\n\ndatatype com = CSkip (\"SKIP\") |\n               CAss string aexpr (\"_ ::= _\" [1000, 61] 61) |\n               CSeq com com (\"_;;/ _\" [60, 61] 60) |\n               CIf bexpr com com (\"(IFB _/ THEN _/ ELSE _/ FI)\" [0, 0, 61] 60) |\n               CWhile bexpr com com (\"(WHILE _/ DO _/ END)\" [0, 61] 61)\n\nvalue \"SKIP\"\nvalue \"IFB BTrue THEN SKIP ELSE SKIP FI\"\n\n(*\ndefinition fact_in_isabelle :: com where\n \"fact_in_isabelle =\n    Z ::= AId X;;\n    Y ::= ANum 1;;\n    WHILE BNot (BEq (AId Z) (ANum 0)) DO (\n      Y ::= AMult (AId Y) (AId Z);;\n      Z ::= AMinus (AId Z) (ANum 1)\n    ) END\n\"\n*)\n\ndefinition plus2 :: com where \"plus2 = X ::= (APlus (AId X) (ANum 2))\"\ndefinition XtimesYinZ :: com where \"XtimesYinZ = Z ::= (AMult (AId X) (AId Y))\"\ndefinition subtract_slowly_body :: com where\n  \"subtract_slowly_body =\n     Z ::= AMinus (AId Z) (ANum 1);;\n     X ::= AMinus (AId X) (ANum 1)\n\"\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/Imp.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206844384594, "lm_q2_score": 0.7826624738835052, "lm_q1q2_score": 0.7058994741293089}}
{"text": "(*  \n    Author:      Salomon Sickert\n    License:     BSD\n*)\n\nsection \\<open>Auxiliary Facts\\<close>\n\ntheory Preliminaries2\n  imports Main \"HOL-Library.Infinite_Set\"\nbegin\n\nsubsection \\<open>Finite and Infinite Sets\\<close>\n\nlemma finite_product:\n  assumes fst: \"finite (fst ` A)\"\n  and     snd: \"finite (snd ` A)\"\n  shows   \"finite A\"\nproof -\n  have \"A \\<subseteq> (fst ` A) \\<times> (snd ` A)\"\n    by force\n  thus ?thesis\n    using snd fst finite_subset by blast\nqed\n\nsubsection \\<open>Cofinite Filters\\<close>\n\nlemma almost_all_commutative:\n  \"finite S \\<Longrightarrow> (\\<forall>x \\<in> S. \\<forall>\\<^sub>\\<infinity>i. P x (i::nat)) = (\\<forall>\\<^sub>\\<infinity>i. \\<forall>x \\<in> S. P x i)\"\nproof (induction rule: finite_induct) \n  case (insert x S)\n    {\n      assume \"\\<forall>x \\<in> insert x S. \\<forall>\\<^sub>\\<infinity>i. P x i\"\n      hence \"\\<forall>\\<^sub>\\<infinity>i. \\<forall>x \\<in> S. P x i\" and \"\\<forall>\\<^sub>\\<infinity>i. P x i\"\n        using insert by simp+\n      then obtain i\\<^sub>1 i\\<^sub>2 where \"\\<And>j. j \\<ge> i\\<^sub>1 \\<Longrightarrow> \\<forall>x \\<in> S. P x j\"\n        and \"\\<And>j. j \\<ge> i\\<^sub>2 \\<Longrightarrow> P x j\"\n        unfolding MOST_nat_le by auto\n      hence \"\\<And>j. j \\<ge> max i\\<^sub>1 i\\<^sub>2 \\<Longrightarrow> \\<forall>x \\<in> S \\<union> {x}. P x j\"\n        by simp\n      hence \"\\<forall>\\<^sub>\\<infinity>i. \\<forall>x \\<in> insert x S. P x i\"\n        unfolding MOST_nat_le by blast\n    }\n    moreover\n    have \"\\<forall>\\<^sub>\\<infinity>i. \\<forall>x \\<in> insert x S. P x i \\<Longrightarrow> \\<forall>x \\<in> insert x S. \\<forall>\\<^sub>\\<infinity>i. P x i\"\n      unfolding MOST_nat_le by auto\n    ultimately\n    show ?case \n      by blast\nqed simp\n\nlemma almost_all_commutative':\n  \"finite S \\<Longrightarrow> (\\<And>x. x \\<in> S \\<Longrightarrow> \\<forall>\\<^sub>\\<infinity>i. P x (i::nat)) \\<Longrightarrow> (\\<forall>\\<^sub>\\<infinity>i. \\<forall>x \\<in> S. P x i)\"\n  using almost_all_commutative by blast\n\nfun index\nwhere\n  \"index P = (if \\<forall>\\<^sub>\\<infinity>i. P i then Some (LEAST i. \\<forall>j \\<ge> i. P j) else None)\"\n\nlemma index_properties: \n  fixes i :: nat\n  shows \"index P = Some i \\<Longrightarrow> 0 < i \\<Longrightarrow> \\<not> P (i - 1)\"\n    and \"index P = Some i \\<Longrightarrow> j \\<ge> i \\<Longrightarrow> P j\"\nproof -\n  assume \"index P = Some i\"\n  moreover\n  hence i_def: \"i = (LEAST i. \\<forall>j \\<ge> i. P j)\" and \"\\<forall>\\<^sub>\\<infinity>i. P i\"\n    unfolding index.simps using option.distinct(2) option.sel \n    by (metis (erased, lifting))+\n  then obtain i' where \"\\<forall>j \\<ge> i'.  P j\"\n    unfolding MOST_nat_le by blast\n  ultimately\n  show \"\\<And>j. j \\<ge> i \\<Longrightarrow> P j\"\n    using LeastI[of \"\\<lambda>i. \\<forall>j \\<ge> i. P j\"] by (metis i_def) \n  {\n    assume \"0 < i\"\n    then obtain j where \"i = Suc j\" and \"j < i\"\n      using lessE by blast\n    hence \"\\<And>j'. j' > j \\<Longrightarrow> P j'\"\n      using \\<open>\\<And>j. j \\<ge> i \\<Longrightarrow> P j\\<close> by force\n    hence \"\\<not> P j\"\n      using not_less_Least[OF \\<open>j < i\\<close>[unfolded i_def]] by (metis leI le_antisym)\n    thus \"\\<not> P (i - 1)\"\n      unfolding \\<open>i = Suc j\\<close> by simp\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/LTL_to_DRA/Auxiliary/Preliminaries2.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.863391617003942, "lm_q2_score": 0.8175744850834649, "lm_q1q2_score": 0.705886956697378}}
{"text": "(*  Title:      HOL/Metis_Examples/Trans_Closure.thy\n    Author:     Lawrence C. Paulson, Cambridge University Computer Laboratory\n    Author:     Jasmin Blanchette, TU Muenchen\n\nMetis example featuring the transitive closure.\n*)\n\nsection \\<open>Metis Example Featuring the Transitive Closure\\<close>\n\ntheory Trans_Closure\nimports Main\nbegin\n\ndeclare [[metis_new_skolem]]\n\ntype_synonym addr = nat\n\ndatatype val\n  = Unit        \\<comment> \\<open>dummy result value of void expressions\\<close>\n  | Null        \\<comment> \\<open>null reference\\<close>\n  | Bool bool   \\<comment> \\<open>Boolean value\\<close>\n  | Intg int    \\<comment> \\<open>integer value\\<close>\n  | Addr addr   \\<comment> \\<open>addresses of objects in the heap\\<close>\n\nconsts R :: \"(addr \\<times> addr) set\"\n\nconsts f :: \"addr \\<Rightarrow> val\"\n\nlemma \"\\<lbrakk>f c = Intg x; \\<forall>y. f b = Intg y \\<longrightarrow> y \\<noteq> x; (a, b) \\<in> R\\<^sup>*; (b, c) \\<in> R\\<^sup>*\\<rbrakk>\n       \\<Longrightarrow> \\<exists>c. (b, c) \\<in> R \\<and> (a, c) \\<in> R\\<^sup>*\"\n(* sledgehammer *)\nproof -\n  assume A1: \"f c = Intg x\"\n  assume A2: \"\\<forall>y. f b = Intg y \\<longrightarrow> y \\<noteq> x\"\n  assume A3: \"(a, b) \\<in> R\\<^sup>*\"\n  assume A4: \"(b, c) \\<in> R\\<^sup>*\"\n  have F1: \"f c \\<noteq> f b\" using A2 A1 by metis\n  have F2: \"\\<forall>u. (b, u) \\<in> R \\<longrightarrow> (a, u) \\<in> R\\<^sup>*\" using A3 by (metis transitive_closure_trans(6))\n  have F3: \"\\<exists>x. (b, x b c R) \\<in> R \\<or> c = b\" using A4 by (metis converse_rtranclE)\n  have \"c \\<noteq> b\" using F1 by metis\n  hence \"\\<exists>u. (b, u) \\<in> R\" using F3 by metis\n  thus \"\\<exists>c. (b, c) \\<in> R \\<and> (a, c) \\<in> R\\<^sup>*\" using F2 by metis\nqed\n\nlemma \"\\<lbrakk>f c = Intg x; \\<forall>y. f b = Intg y \\<longrightarrow> y \\<noteq> x; (a, b) \\<in> R\\<^sup>*; (b,c) \\<in> R\\<^sup>*\\<rbrakk>\n       \\<Longrightarrow> \\<exists>c. (b, c) \\<in> R \\<and> (a, c) \\<in> R\\<^sup>*\"\n(* sledgehammer [isar_proofs, compress = 2] *)\nproof -\n  assume A1: \"f c = Intg x\"\n  assume A2: \"\\<forall>y. f b = Intg y \\<longrightarrow> y \\<noteq> x\"\n  assume A3: \"(a, b) \\<in> R\\<^sup>*\"\n  assume A4: \"(b, c) \\<in> R\\<^sup>*\"\n  have \"b \\<noteq> c\" using A1 A2 by metis\n  hence \"\\<exists>x\\<^sub>1. (b, x\\<^sub>1) \\<in> R\" using A4 by (metis converse_rtranclE)\n  thus \"\\<exists>c. (b, c) \\<in> R \\<and> (a, c) \\<in> R\\<^sup>*\" using A3 by (metis transitive_closure_trans(6))\nqed\n\nlemma \"\\<lbrakk>f c = Intg x; \\<forall>y. f b = Intg y \\<longrightarrow> y \\<noteq> x; (a, b) \\<in> R\\<^sup>*; (b, c) \\<in> R\\<^sup>*\\<rbrakk>\n       \\<Longrightarrow> \\<exists>c. (b, c) \\<in> R \\<and> (a, c) \\<in> R\\<^sup>*\"\napply (erule_tac x = b in converse_rtranclE)\n apply metis\nby (metis transitive_closure_trans(6))\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/Trans_Closure.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916064586998, "lm_q2_score": 0.8175744761936437, "lm_q1q2_score": 0.7058869404004601}}
{"text": "(* author: wzh*)\n\ntheory MyAdd\n  imports 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\nlemma add_02: \"add m 0 = m\"\n  apply (induction m)\n  apply (auto)\n  done\n\nthm add_02\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/MyAdd.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9111797027760039, "lm_q2_score": 0.7745833841649233, "lm_q1q2_score": 0.7057846577586261}}
{"text": "theory CS_Chap3\n\nimports Main\n  \"~~/src/HOL/IMP/BExp\"\n\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\n(* \n  Given an expression and a state (variable value) it evaluates the primer\n  giving the expression final value\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\n(*\n  Performs constant folding, i.e., reduces the expression, resolving\n  trivial Plus operations\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\n(*\n  Plus operation optimization, intended to eliminate 0 and\n  simplify trivial summations\n*)\nfun plus :: \"aexp \\<Rightarrow> aexp \\<Rightarrow> aexp\" where\n  \"plus (N i1) (N i2) = N (i1 + i2)\" |\n  \"plus a (N i) = (if i=0 then a else Plus a (N i))\" |\n  \"plus (N i) a = (if i=0 then a else Plus (N i) a)\" |\n  \"plus a1 a2 = Plus a1 a2\"\n\nlemma aval_plus [simp] : \"aval (plus a1 a2) s = aval a1 s + aval a2 s\"\n  apply (induction rule: plus.induct)\n  apply (auto)\n  done\n\n(* Function for simplify expressions using the plus function *)\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)\n  done\n\n(* EXERCISE 3.1 *)\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) \\<and> (optimal a2))\"\n\ntheorem \"optimal (asimp_const a)\"\n  apply (induction a)\n  apply (auto split: aexp.split)\n  done\n\n\n(* EXERCISE 3.2 *)\n(* Return the total summation of all constants in an expression *)\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)))\" (* It works! *)\n\n(* Giving an expression, return it with all constants replaced by zero *)\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\nvalue \"zeroN (Plus (N 1) (Plus (V x) (N 2)))\" (* It works! *)\n\n(* Transform a given expression in an addition of the sumN and zeroN of that expression*)\nfun sepN :: \"aexp \\<Rightarrow> aexp\" where\n  \"sepN a = Plus (N (sumN a)) (zeroN a)\"\n\nvalue \"sepN (Plus (N 1) (Plus (V x) (N 2)))\" (* It works! *)\n\nlemma aval_sepN [simp] : \"aval (sepN a) s = aval a s\"\n  apply (induction a)\n  apply (auto)\n  done\n\n(* \n  Finally, for performing the full_asimp, we just simplify the expression as we can\n  and then apply the sepN function, transforming it in an addition of the variable\n  and resulting constant.\n *)\nfun full_asimp :: \"aexp \\<Rightarrow> aexp\" where\n  \"full_asimp a = asimp (sepN a)\"\n\nvalue \"full_asimp (Plus (N 1) (Plus (V x) (N 2)))\" (* It works *)\n\nlemma aval_full_asimp: \"aval (full_asimp a) s = aval a s\"\n  apply (induction a)\n  apply (auto)\n  done\n\n\n(* EXERCISE 3.3 *)\nfun subst :: \"vname \\<Rightarrow> aexp \\<Rightarrow> aexp \\<Rightarrow> aexp\" where\n  \"subst x a (V v) = (if x = v then a else (V v))\" |\n  \"subst x a (N n) = (N n)\" |\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''))\" (* It works! *)\n\nlemma substitution_\n\ntheorem \"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\n(* EXERCISE 3.4 *)\n(*\n  Instead of important and extending the AExp theory, let's just create\n  our own types,  adding the letter t, of times, at the end\n  of our constructors. Seems more portable.\n*)\ndatatype aexpt = Nt int \n  | Vt vname \n  | Plust aexpt aexpt\n  | Times aexpt aexpt\n\n(* We have now the Times case. Pretty trivial! *)\nfun avalt :: \"aexpt \\<Rightarrow> state \\<Rightarrow> val\" where\n  \"avalt (Nt n) s = n\" |\n  \"avalt (Vt x) s = s x\" |\n  \"avalt (Plust a1 a2) s = avalt a1 s + avalt a2 s\" |\n  \"avalt (Times a1 a2) s = avalt a1 s * avalt a2 s \"\n\n(* plust definition follows equal as our previous plus function *)\nfun plust :: \"aexpt \\<Rightarrow> aexpt \\<Rightarrow> aexpt\" where\n  \"plust (Nt n1) (Nt n2) = Nt (n1 + n2)\" |\n  \"plust (Nt n) a = (if n = 0 then a else Plust (Nt n) a)\" |\n  \"plust a (Nt n) = (if n = 0 then a else Plust a (Nt n))\" |\n  \"plust a1 a2 = Plust a1 a2\"\n\n(* In multiplication, we have 2 special cases: null factor (zero) and neutral factor (one) *)\nfun times :: \"aexpt \\<Rightarrow> aexpt \\<Rightarrow> aexpt\" where\n  \"times (Nt n1) (Nt n2) = Nt (n1 * n2)\" |\n  \"times (Nt n) a = \n    (if n = 0 then (Nt 0) else\n    if n = 1 then a else\n    Times (Nt n) a)\" |\n  \"times a (Nt n) =  \n    (if n = 0 then (Nt 0) else\n    if n = 1 then a else\n    Times a (Nt n))\" |\n  \"times a1 a2 = Times a1 a2\"\n\n(* Let's test times *)\nvalue \"times (Nt 3) (Nt 4)\" (* = 12 | Ok*)\nvalue \"times (Nt 3) (Nt 0)\" (* = 0 | Ok*)\nvalue \"times (Nt 3) (Nt 1)\" (* = 3 | Ok*)\nvalue \"times (Nt 0) (Nt 4)\" (* = 0 | Ok*)\nvalue \"times (Nt 1) (Nt 4)\" (* = 4 | Ok*)\nvalue \"times (Add (Nt 3) (Nt 2)) (Nt 4)\" (* = aexpt | Ok*)\nvalue \"times (Nt 4) (Add (Nt 3) (Nt 2))\" (* = aexpt | Ok*)\nvalue \"times (Add (Nt 3) (Nt 2)) (Add (Nt 3) (Nt 2))\" (* = aexpt | Ok*)\n\n(* Times case is added to our simplification function *)\nfun asimpt :: \"aexpt \\<Rightarrow> aexpt\" where\n  \"asimpt (Nt n) = Nt n\" |\n  \"asimpt (Vt v) = Vt v\" |\n  \"asimpt (Plust a1 a2) = plust (asimpt a1) (asimpt a2)\" |\n  \"asimpt (Times a1 a2) = times (asimpt a1) (asimpt a2)\"\n\n(* Proving that plust function has distributive properties *)\nlemma avalt_plust [simp] : \"avalt (plust a1 a2) s = avalt a1 s + avalt a2 s\"\n  apply (induction a1 a2 rule: plust.induct)\n  apply (simp_all)\n  done\n\n(* Proving that times function has distributive properties *)\nlemma avalt_times [simp] : \"avalt (times a1 a2) s = avalt a1 s * avalt a2 s\"\n  apply (induction a1 a2 rule: times.induct)\n  apply (auto)\n  done\n\n(* Finally, proving that our simplification function is correct *)\ntheorem \"avalt (asimpt a) s = avalt a s\"\n  apply (induction a)\n  apply (auto)\n  done\n\n\n(* EXERCISE 3.5 *)\ndatatype aexp2 = N2 int \n  | V2 vname \n  | Plus2 aexp2 aexp2\n  | PostPlus vname\n  | Times2 aexp2 aexp2\n  | Div2 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 a1 a2) s = (fst (aval2 a1 s) + fst (aval2 a2 s), \n    (\\<lambda> x. (snd (aval2 a1 s) x) + (snd (aval2 a2 s) x) - (s x)))\" |\n  \"aval2 (Times2 a1 a2) s = (fst (aval2 a1 s) * fst (aval2 a2 s), \n    (\\<lambda> x. (snd (aval2 a1 s) x) * (snd (aval2 a2 s) x) - (s x)))\" |\n  \"aval2 (Div2 a1 a2) s = (fst (aval2 a1 s) div fst (aval2 a2 s), \n    (\\<lambda> x. (snd (aval2 a1 s) x) div (snd (aval2 a2 s) x) - (s x)))\" |\n  \"aval2 (PostPlus x) s = (s x, s(x:= 1 + s x))\"\n\n\n(* EXERCISE 3.6 *)\ndatatype lexp = Nl int\n  | Vl vname\n  | Plusl lexp lexp\n  | LET vname lexp lexp\n\n(* \n  Now, for a proper avaliation, we need to implement the LET aval. \n  Basically, this means that we need to replace the ocurrence of \n  variable x in a2 by expression a1.\n*)\nfun lval :: \"lexp \\<Rightarrow> state \\<Rightarrow> int\" where\n  \"lval (Nl n) s = n\" |\n  \"lval (Vl x) s = s x\" |\n  \"lval (Plusl a1 a2) s = lval a1 s + lval a2 s\" |\n  \"lval (LET x a1 a2) s = lval a2 (s(x := lval a1 s))\"\n\nvalue \"lval (Vl x) (s 5)\" \nvalue \"lval (LET v (Plusl (Nl 1) (Nl 2)) (Plusl (Nl 5) (Vl v))) s\" (* It works *)\n\n(*\n  Here we want to transform an lexp expression into an aexp one.\n  Pretty straighforward for int and variables. Addition is done\n  recursively. For the LET constructor, we just use our subst function,\n  which already apply the variable value over an aexp expression, with\n  recursion over the expression parameters.\n  Piece of cake!\n*)\nfun inline :: \"lexp \\<Rightarrow> aexp\" where\n  \"inline (Nl n) = N n\" | \n  \"inline (Vl x) = V x\" | \n  \"inline (Plusl a1 a2) = Plus (inline a1) (inline a2)\" | \n  \"inline (LET x a1 a2) = subst x (inline a1) (inline a2)\" \n\n(* \n  Proving that inline function is correct is proving that we \n  can correctly evaluate the resulting expression. \n*)\ntheorem inline_correctness : \"lval l s = aval (inline l) s\"\n  apply (induction l arbitrary: s)\n  apply auto\n  done\n\n\n(* EXERCISE 3.7 *)\n(* Extensions can be done with definitions *)\ndefinition Le :: \"AExp.aexp \\<Rightarrow> AExp.aexp \\<Rightarrow> bexp\" where\n  \"Le a1 a2 = Not (Less a2 a1)\"\n\ndefinition Eq :: \"AExp.aexp \\<Rightarrow> AExp.aexp \\<Rightarrow> bexp\" where\n  \"Eq a1 a2 = And (Not (Less a1 a2)) (Not (Less a2 a1))\"\n\n(* Correctness of both operations is easy over definitions *)\ntheorem Le_correctness : \"bval (Le a1 a2) s = (AExp.aval a1 s \\<le> AExp.aval a2 s)\"\n  apply (auto simp add: Le_def)\n  done\n\ntheorem Eq_correctness : \"bval (Eq a1 a2) s = (AExp.aval a1 s = AExp.aval a2 s)\"\n  apply (auto simp add: Eq_def)\n  done\n\n\n(* EXERCISE 3.8 *)\ndatatype ifexp = Bi bool \n  | If ifexp ifexp ifexp \n  | Less2 AExp.aexp AExp.aexp\n\n(* \n  The If statement should evaluate the first parameter and, based on that\n  give the evaluation of the second or the third.\n*)\nfun ifval :: \"ifexp \\<Rightarrow> state \\<Rightarrow> bool\" where\n  \"ifval (Bi 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 = (AExp.aval a1 s < AExp.aval a2 s)\"\n\nfun b2ifexp :: \"bexp \\<Rightarrow> ifexp\" where\n  \"b2ifexp (Bc v) = Bi v\" |\n  \"b2ifexp (Not b) = If (b2ifexp b) (Bi False) (Bi True)\" |\n  \"b2ifexp (And b1 b2) = If (b2ifexp b1) (b2ifexp b2) (Bi False)\" |\n  \"b2ifexp (Less a1 a2) = Less2 a1 a2\" \n\n(* \n  What does If a b c means? (a \\<and> b) \\<or> (\\<not>a \\<and> c), right?\n  But we need to get rid of that disjunction, since we don't have it.\n  So we negate two times! \\<not>\\<not>((a \\<and> b) \\<or> (\\<not>a \\<and> c)), leading to:\n  \\<not>(\\<not>(a \\<and> b) \\<and> \\<not>(\\<not>a \\<and> c))\n  \n*)\nfun if2bexp :: \"ifexp \\<Rightarrow> bexp\" where\n  \"if2bexp (Bi v) = Bc v\" |\n  \"if2bexp (If a b c) = Not( And \n    (Not ((And (if2bexp a) (if2bexp b)))) \n    (Not ((And (Not (if2bexp a)) (if2bexp c))))\n  )\" |\n  \"if2bexp (Less2 a1 a2) = Less a1 a2\"\n\n(* Proving correctness is proving that the resulting expression evaluates right *)\ntheorem b2ifexp_correctness : \"ifval (b2ifexp e) s = bval e s\"\n  apply (induction e)\n  apply auto\n  done\n\ntheorem if2bexp_correctness : \"bval (if2bexp e) s = ifval e s\"\n  apply (induction e)\n  apply auto\n  done\n\n\n(* EXERCISE 3.9 *)\ndatatype pbexp = VAR vname\n  | NOT pbexp\n  | AND pbexp pbexp\n  | OR pbexp pbexp\n\n(* Evaluates an expression *)\nfun pbval :: \"pbexp \\<Rightarrow> (vname \\<Rightarrow> bool) \\<Rightarrow> bool\" where\n  \"pbval (VAR v) s = s v\" |\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\n(* Tells if the boolean expression is in the negative normal formula *)\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 b1 b2) = (is_nnf b1 \\<and> is_nnf b2)\" |\n  \"is_nnf (OR b1 b2) = (is_nnf b1 \\<and> is_nnf b2)\" \n\nvalue \"is_nnf (AND (VAR a) (NOT (VAR B)))\" (* = True *)\nvalue \"is_nnf (OR (VAR a) (NOT (VAR B)))\" (* = True *)\nvalue \"is_nnf (NOT (OR (VAR a) (NOT (VAR B))))\" (* = False *)\nvalue \"is_nnf (NOT (AND (VAR a) (VAR B)))\" (* = False *)\n\nfun nnf :: \"pbexp \\<Rightarrow> pbexp\" where\n  \"nnf (VAR v) = VAR v\" |\n  \"nnf (NOT (VAR v)) = NOT (VAR v)\" |\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\nvalue \"nnf (NOT (OR (VAR a) (VAR B)))\" (* It works! *)\n\n(* \n  Lemma nnf_correctness raises a subgoal, requiring that\n  we prove that the NOT operator properly negate an expression.\n  So we prove it.  \n*)\nlemma negation_correctness [simp] : \"pbval (nnf (NOT b)) s = (\\<not> (pbval (nnf b) s))\"\n  apply (induction b)\n  apply auto\n  done\n\n(* Here, the correctness follows easily. Induction is enough. *)\ntheorem nnf_correctness : \"pbval (nnf b) s = pbval b s\"\n  apply (induction b)\n  apply auto\n  done\n\n(* TODO: explain the induct rule *)\ntheorem is_nff_correctness : \"is_nnf (nnf b)\"\n  apply (induction b rule: nnf.induct)\n  apply auto\n  done\n\nfun is_not_or :: \"pbexp \\<Rightarrow> bool\" where\n  \"is_not_or (OR b1 b2) = False\" |\n  \"is_not_or (AND b1 b2) = (is_not_or b1 \\<and> is_not_or b2)\" |\n  \"is_not_or b = True\"\n\nfun is_dnf :: \"pbexp \\<Rightarrow> bool\" where\n  \"is_dnf (VAR _) = True\" |\n  \"is_dnf (NOT _) = True\" |\n  \"is_dnf (AND b1 b2) = ((is_not_or b1) \\<and> (is_not_or b2))\" |\n  \"is_dnf (OR b1 b2) = (is_dnf b1 \\<and> is_dnf b2)\"\n  \n\n(* As the exercise hinted, let's make a distribution function for the AND operator *)\nfun distribute_and :: \"pbexp \\<Rightarrow> pbexp \\<Rightarrow> pbexp\" where\n  \"distribute_and x (OR b1 b2) = OR (distribute_and x b1) (distribute_and x b2)\" |\n  \"distribute_and (OR b1 b2) x = OR (distribute_and b1 x) (distribute_and b2 x)\" |\n  \"distribute_and b1 b2 = AND b1 b2\"\n\n(* Before defining dnf_of_nnf, let's prove that distribute_and is correct! *)\n(* First, checking it preserves the expression value... *)\nlemma distribution_preserves [simp] : \"pbval (distribute_and b1 b2) s = pbval (AND b1 b2) s\"\n  apply (induction b1 b2 rule: distribute_and.induct)\n  apply (auto)\n  done\n\n(* Then, applied at two dnf expressions, its result still is a dnf *)\nlemma distribution_correctness [simp] : \n    \"\\<lbrakk>is_dnf b1; is_dnf b2\\<rbrakk> \\<Longrightarrow> is_dnf (distribute_and b1 b2)\"\n  apply (induction b1 b2 rule: distribute_and.induct)\n  apply (auto)\n  done\n\n(* Ok, now let's define dnf_of_nnf *)\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 (OR b1 b2) = OR (dnf_of_nnf b1) (dnf_of_nnf b2)\" |\n  \"dnf_of_nnf (AND b1 b2) = distribute_and (dnf_of_nnf b1) (dnf_of_nnf b2)\"\n\n(* Here, simple induction is enough *)\ntheorem dnf_of_nnf_preserves : \"pbval (dnf_of_nnf b) s = pbval b s\"\n  apply (induction b rule: dnf_of_nnf.induct)\n  apply (auto)\n  done\n\n(* \n  In prior tries, I needed this lemma. In this one, it is not necessary,\n  but I found interesting to leave it here. We are just proving that negation\n  is still preserved.\n*)\nlemma dnf_of_nnf_negation [simp] : \"is_nnf (NOT b) \\<Longrightarrow> is_dnf (NOT b)\"\n  apply (induction b)\n  apply (auto)\n  done\n\n(* Simple induction, as always. *)\ntheorem dnf_to_nnf_correctness : \"is_nnf b \\<Longrightarrow> is_dnf (dnf_of_nnf b)\"\n  apply (induction b rule: dnf_of_nnf.induct)\n  apply (auto)\n  done\n\n(* Fuck, that was long... *)\n\n\n(* EXERCISE 3.10 *)\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 v) s stk = Some (s(v) # stk)\" |\n  \"exec1 ADD s [] = None\" |\n  \"exec1 ADD s [x] = None\" |\n  \"exec1 ADD s (x # y # stk) = Some((x+y) # 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    None \\<Rightarrow> None |\n    Some stkx \\<Rightarrow> exec is s stkx\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\nlemma exec_appending [simp] : \n  \"exec is1 s stk = Some stk2 \\<Longrightarrow> exec (is1 @ is2) s stk = exec is2 s stk2\"\n  apply (induction is1 arbitrary: stk)\n  apply (auto)\n  by (metis option.case_eq_if option.distinct(1))\n\ntheorem \"exec (comp a) s stk = Some (aval a s # stk)\"\n  apply (induction a arbitrary: stk)\n  apply (auto)\n  done\n\n\n(* EXERCISE 3.11 *)\ntype_synonym reg = nat\ndatatype instrr = LDI int reg | LD vname reg | ADD reg reg\n\ntype_synonym regstate = \"reg \\<Rightarrow> int\"\n\nfun execr1 :: \"instrr \\<Rightarrow> state \\<Rightarrow> regstate \\<Rightarrow> regstate\" where\n  \"execr1 (LDI n r) _ rs = rs(r := n)\" |\n  \"execr1 (LD v r) s rs = rs(r := s v)\" |\n  \"execr1 (ADD r1 r2) _ rs = rs(r1 := rs r1 + rs r2)\"\n\nfun execr :: \"instrr list \\<Rightarrow> state \\<Rightarrow> regstate \\<Rightarrow> regstate\" where\n  \"execr [] _ rs = rs\" |\n  \"execr (i # is) s rs = execr is s (execr1 i s rs)\"\n\nfun compr :: \"aexp \\<Rightarrow> reg \\<Rightarrow> instrr list\" where\n  \"compr (N n) r = [LDI n r]\" |\n  \"compr (V x) r = [LD x r]\" |\n  \"compr (Plus e1 e2) r = compr e1 r @ compr e2 (r+1) @ [ADD r (r+1)]\"\n\nlemma execr_appending [simp] : \"execr (xs @ ys) s rs = execr ys s (execr xs s rs)\"\n  apply (induction xs arbitrary: rs)\n  apply (auto)\n  done\n\nlemma [simp] : \"r1 < r2 \\<Longrightarrow> execr (compr e r2) s rs r1 = rs r1\"\n  apply (induction e arbitrary: rs r1 r2)\n  apply (auto)\n  done\n\ntheorem \"execr (compr a r) s rs r = aval a s\"\n  apply (induction a arbitrary: rs r)\n  apply (auto)\n  done\n\n\n(* EXERCISE 3.12 *)\ndatatype instr0 = LDI0 val | LD0 vname | MV0 reg | ADD0 reg\n\nfun exec01 :: \"instr0 \\<Rightarrow> state \\<Rightarrow> regstate \\<Rightarrow> regstate\" where\n  \"exec01 (LDI0 n) _ 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) _ rs = rs(0 := rs 0 + rs r)\"\n\nfun exec0 :: \"instr0 list \\<Rightarrow> state \\<Rightarrow> regstate \\<Rightarrow> regstate\" where\n  \"exec0 [] _ rs = rs\" |\n  \"exec0 (i # is) s rs = exec0 is s (exec01 i 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 e1 e2) r = comp0 e1 (r+1) @ [MV0 (r+1)] @ comp0 e2 (r+2) @ [ADD0 (r+1)]\"\n\nlemma exec0_appending [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 < r1) \\<and> (r1 \\<le> r2) \\<Longrightarrow> exec0 (comp0 e r2) s rs r1 = rs r1\"\n  apply (induction e arbitrary: rs r1 r2)\n  apply (auto)\n  done\n\ntheorem \"exec0 (comp0 e r) s rs 0 = aval e s\"\n  apply (induction e arbitrary: r rs)\n  apply (auto)\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_Chap3.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867681382279, "lm_q2_score": 0.8840392817460332, "lm_q1q2_score": 0.7056284572041065}}
{"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 \"\\<rightarrow>\" 60)\n  where \"A \\<rightarrow> B \\<equiv> Pi A (\\<lambda>_. B)\"\n\nsyntax (ASCII)\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\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: \"f i \\<in> A (n i) i\" if \"i \\<in> I\" for i\n    by auto\n  obtain k where k: \"n i \\<le> k\" if \"i \\<in> I\" for i\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: if_split_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_cong: \"I = J \\<Longrightarrow> (\\<And>i. i \\<in> J =simp=> f i = g i) \\<Longrightarrow> restrict f I = restrict g J\"\n  by (auto simp: restrict_def fun_eq_iff simp_implies_def)\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 \\<open>Fun.thy\\<close>, 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 (ASCII)\n  \"_PiE\" :: \"pttrn \\<Rightarrow> 'a set \\<Rightarrow> 'b set \\<Rightarrow> ('a \\<Rightarrow> 'b) set\"  (\"(3PIE _:_./ _)\" 10)\nsyntax\n  \"_PiE\" :: \"pttrn \\<Rightarrow> 'a set \\<Rightarrow> 'b set \\<Rightarrow> ('a \\<Rightarrow> 'b) set\"  (\"(3\\<Pi>\\<^sub>E _\\<in>_./ _)\" 10)\ntranslations\n  \"\\<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 \"\\<rightarrow>\\<^sub>E\" 60)\n  where \"A \\<rightarrow>\\<^sub>E B \\<equiv> (\\<Pi>\\<^sub>E i\\<in>A. B)\"\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: \"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\" \"x \\<notin> S\"\n    then 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  moreover\n  {\n    fix f assume \"f \\<in> PiE (insert x S) T\" \"x \\<in> S\"\n    then 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)\"] intro: fun_upd_in_PiE PiE_mem simp: insert_absorb)\n  }\n  ultimately show ?thesis\n    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: if_split_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: if_split_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": "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/FuncSet.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.855851135937125, "lm_q2_score": 0.8244619263765707, "lm_q1q2_score": 0.7056166762262983}}
{"text": "(*  Title:      HOL/Library/Product_Order.thy\n    Author:     Brian Huffman\n*)\n\nsection {* Pointwise order on product types *}\n\ntheory Product_Order\nimports Product_plus Conditionally_Complete_Lattices\nbegin\n\nsubsection {* Pointwise ordering *}\n\ninstantiation prod :: (ord, ord) ord\nbegin\n\ndefinition\n  \"x \\<le> y \\<longleftrightarrow> fst x \\<le> fst y \\<and> snd x \\<le> snd y\"\n\ndefinition\n  \"(x::'a \\<times> 'b) < y \\<longleftrightarrow> x \\<le> y \\<and> \\<not> y \\<le> x\"\n\ninstance ..\n\nend\n\nlemma fst_mono: \"x \\<le> y \\<Longrightarrow> fst x \\<le> fst y\"\n  unfolding less_eq_prod_def by simp\n\nlemma snd_mono: \"x \\<le> y \\<Longrightarrow> snd x \\<le> snd y\"\n  unfolding less_eq_prod_def by simp\n\nlemma Pair_mono: \"x \\<le> x' \\<Longrightarrow> y \\<le> y' \\<Longrightarrow> (x, y) \\<le> (x', y')\"\n  unfolding less_eq_prod_def by simp\n\nlemma Pair_le [simp]: \"(a, b) \\<le> (c, d) \\<longleftrightarrow> a \\<le> c \\<and> b \\<le> d\"\n  unfolding less_eq_prod_def by simp\n\ninstance prod :: (preorder, preorder) preorder\nproof\n  fix x y z :: \"'a \\<times> 'b\"\n  show \"x < y \\<longleftrightarrow> x \\<le> y \\<and> \\<not> y \\<le> x\"\n    by (rule less_prod_def)\n  show \"x \\<le> x\"\n    unfolding less_eq_prod_def\n    by fast\n  assume \"x \\<le> y\" and \"y \\<le> z\" thus \"x \\<le> z\"\n    unfolding less_eq_prod_def\n    by (fast elim: order_trans)\nqed\n\ninstance prod :: (order, order) order\n  by default auto\n\n\nsubsection {* Binary infimum and supremum *}\n\ninstantiation prod :: (inf, inf) inf\nbegin\n\ndefinition\n  \"inf x y = (inf (fst x) (fst y), inf (snd x) (snd y))\"\n\nlemma inf_Pair_Pair [simp]: \"inf (a, b) (c, d) = (inf a c, inf b d)\"\n  unfolding inf_prod_def by simp\n\nlemma fst_inf [simp]: \"fst (inf x y) = inf (fst x) (fst y)\"\n  unfolding inf_prod_def by simp\n\nlemma snd_inf [simp]: \"snd (inf x y) = inf (snd x) (snd y)\"\n  unfolding inf_prod_def by simp\n\ninstance proof qed\nend\n\ninstance prod :: (semilattice_inf, semilattice_inf) semilattice_inf\n  by default auto\n\n\ninstantiation prod :: (sup, sup) sup\nbegin\n\ndefinition\n  \"sup x y = (sup (fst x) (fst y), sup (snd x) (snd y))\"\n\nlemma sup_Pair_Pair [simp]: \"sup (a, b) (c, d) = (sup a c, sup b d)\"\n  unfolding sup_prod_def by simp\n\nlemma fst_sup [simp]: \"fst (sup x y) = sup (fst x) (fst y)\"\n  unfolding sup_prod_def by simp\n\nlemma snd_sup [simp]: \"snd (sup x y) = sup (snd x) (snd y)\"\n  unfolding sup_prod_def by simp\n\ninstance proof qed\nend\n\ninstance prod :: (semilattice_sup, semilattice_sup) semilattice_sup\n  by default auto\n\ninstance prod :: (lattice, lattice) lattice ..\n\ninstance prod :: (distrib_lattice, distrib_lattice) distrib_lattice\n  by default (auto simp add: sup_inf_distrib1)\n\n\nsubsection {* Top and bottom elements *}\n\ninstantiation prod :: (top, top) top\nbegin\n\ndefinition\n  \"top = (top, top)\"\n\ninstance ..\n\nend\n\nlemma fst_top [simp]: \"fst top = top\"\n  unfolding top_prod_def by simp\n\nlemma snd_top [simp]: \"snd top = top\"\n  unfolding top_prod_def by simp\n\nlemma Pair_top_top: \"(top, top) = top\"\n  unfolding top_prod_def by simp\n\ninstance prod :: (order_top, order_top) order_top\n  by default (auto simp add: top_prod_def)\n\ninstantiation prod :: (bot, bot) bot\nbegin\n\ndefinition\n  \"bot = (bot, bot)\"\n\ninstance ..\n\nend\n\nlemma fst_bot [simp]: \"fst bot = bot\"\n  unfolding bot_prod_def by simp\n\nlemma snd_bot [simp]: \"snd bot = bot\"\n  unfolding bot_prod_def by simp\n\nlemma Pair_bot_bot: \"(bot, bot) = bot\"\n  unfolding bot_prod_def by simp\n\ninstance prod :: (order_bot, order_bot) order_bot\n  by default (auto simp add: bot_prod_def)\n\ninstance prod :: (bounded_lattice, bounded_lattice) bounded_lattice ..\n\ninstance prod :: (boolean_algebra, boolean_algebra) boolean_algebra\n  by default (auto simp add: prod_eqI inf_compl_bot sup_compl_top diff_eq)\n\n\nsubsection {* Complete lattice operations *}\n\ninstantiation prod :: (Inf, Inf) Inf\nbegin\n\ndefinition\n  \"Inf A = (INF x:A. fst x, INF x:A. snd x)\"\n\ninstance proof qed\nend\n\ninstantiation prod :: (Sup, Sup) Sup\nbegin\n\ndefinition\n  \"Sup A = (SUP x:A. fst x, SUP x:A. snd x)\"\n\ninstance proof qed\nend\n\ninstance prod :: (conditionally_complete_lattice, conditionally_complete_lattice)\n    conditionally_complete_lattice\n  by default (force simp: less_eq_prod_def Inf_prod_def Sup_prod_def bdd_below_def bdd_above_def\n    INF_def SUP_def simp del: Inf_image_eq Sup_image_eq intro!: cInf_lower cSup_upper cInf_greatest cSup_least)+\n\ninstance prod :: (complete_lattice, complete_lattice) complete_lattice\n  by default (simp_all add: less_eq_prod_def Inf_prod_def Sup_prod_def\n    INF_lower SUP_upper le_INF_iff SUP_le_iff bot_prod_def top_prod_def)\n\nlemma fst_Sup: \"fst (Sup A) = (SUP x:A. fst x)\"\n  unfolding Sup_prod_def by simp\n\nlemma snd_Sup: \"snd (Sup A) = (SUP x:A. snd x)\"\n  unfolding Sup_prod_def by simp\n\nlemma fst_Inf: \"fst (Inf A) = (INF x:A. fst x)\"\n  unfolding Inf_prod_def by simp\n\nlemma snd_Inf: \"snd (Inf A) = (INF x:A. snd x)\"\n  unfolding Inf_prod_def by simp\n\nlemma fst_SUP: \"fst (SUP x:A. f x) = (SUP x:A. fst (f x))\"\n  using fst_Sup [of \"f ` A\", symmetric] by (simp add: comp_def)\n\nlemma snd_SUP: \"snd (SUP x:A. f x) = (SUP x:A. snd (f x))\"\n  using snd_Sup [of \"f ` A\", symmetric] by (simp add: comp_def)\n\nlemma fst_INF: \"fst (INF x:A. f x) = (INF x:A. fst (f x))\"\n  using fst_Inf [of \"f ` A\", symmetric] by (simp add: comp_def)\n\nlemma snd_INF: \"snd (INF x:A. f x) = (INF x:A. snd (f x))\"\n  using snd_Inf [of \"f ` A\", symmetric] by (simp add: comp_def)\n\nlemma SUP_Pair: \"(SUP x:A. (f x, g x)) = (SUP x:A. f x, SUP x:A. g x)\"\n  unfolding SUP_def Sup_prod_def by (simp add: comp_def)\n\nlemma INF_Pair: \"(INF x:A. (f x, g x)) = (INF x:A. f x, INF x:A. g x)\"\n  unfolding INF_def Inf_prod_def by (simp add: comp_def)\n\n\ntext {* Alternative formulations for set infima and suprema over the product\nof two complete lattices: *}\n\nlemma INF_prod_alt_def:\n  \"INFIMUM A f = (INFIMUM A (fst o f), INFIMUM A (snd o f))\"\n  unfolding INF_def Inf_prod_def by simp\n\nlemma SUP_prod_alt_def:\n  \"SUPREMUM A f = (SUPREMUM A (fst o f), SUPREMUM A (snd o f))\"\n  unfolding SUP_def Sup_prod_def by simp\n\n\nsubsection {* Complete distributive lattices *}\n\n(* Contribution: Alessandro Coglio *)\n\ninstance prod ::\n  (complete_distrib_lattice, complete_distrib_lattice) complete_distrib_lattice\nproof\n  case goal1 thus ?case\n    by (auto simp: sup_prod_def Inf_prod_def INF_prod_alt_def sup_Inf sup_INF comp_def)\nnext\n  case goal2 thus ?case\n    by (auto simp: inf_prod_def Sup_prod_def SUP_prod_alt_def inf_Sup inf_SUP comp_def)\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/Product_Order.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972717658209, "lm_q2_score": 0.8104789018037399, "lm_q1q2_score": 0.7056007207340946}}
{"text": "(* Title: Verification Component Based on KAD for Forward Reasoning: Examples\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\nsubsubsection\\<open>Verification Examples\\<close>\n\ntheory VC_KAD_dual_Examples\nimports VC_KAD_dual\n\nbegin\n\ntext\\<open>The proofs are essentially the same as with forward boxes.\\<close>\n\nlemma euclid:\n  \"FPRE (\\<lambda>s::nat store. s ''x'' = x \\<and> s ''y'' = y)\n   (WHILE (\\<lambda>s. s ''y'' \\<noteq> 0) INV (\\<lambda>s. gcd (s ''x'') (s ''y'') = gcd x y) \n    DO\n     (''z'' ::= (\\<lambda>s. s ''y''));\n     (''y'' ::= (\\<lambda>s. s ''x'' mod s ''y''));\n     (''x'' ::= (\\<lambda>s. s ''z''))\n    OD)\n   POST (\\<lambda>s. s ''x'' = gcd x y)\"\n  by (rule rel_modal_kleene_algebra.bdia_whilei, auto simp: gcd_non_0_nat)\n\nlemma euclid_diff: \n   \"FPRE (\\<lambda>s::nat store. s ''x'' = x \\<and> s ''y'' = y \\<and> x > 0 \\<and> y > 0)\n    (WHILE (\\<lambda>s. s ''x''\\<noteq> s ''y'') INV (\\<lambda>s. gcd (s ''x'') (s ''y'') = gcd x y) \n     DO\n        (IF (\\<lambda>s. s ''x'' >  s ''y'')\n         THEN (''x'' ::= (\\<lambda>s. s ''x'' - s ''y''))\n         ELSE (''y'' ::= (\\<lambda>s. s ''y'' - s ''x''))\n         FI)\n    OD)\n    POST (\\<lambda>s. s ''x'' = gcd x y)\"\n  apply (rule rel_modal_kleene_algebra.bdia_whilei, simp_all)\n  apply auto[1]\n  by (metis gcd.commute gcd_diff1_nat le_cases nat_less_le)\n\nlemma varible_swap:\n  \"FPRE (\\<lambda>s. s ''x'' = a \\<and> s ''y'' = b)   \n    (''z'' ::= (\\<lambda>s. s ''x''));\n    (''x'' ::= (\\<lambda>s. s ''y''));\n    (''y'' ::= (\\<lambda>s. s ''z''))\n   POST (\\<lambda>s. s ''x'' = b \\<and> s ''y'' = a)\"\n  by simp\n\nlemma maximum: \n  \"FPRE (\\<lambda>s:: nat store. True) \n   (IF (\\<lambda>s. s ''x'' \\<ge> s ''y'') \n    THEN (''z'' ::= (\\<lambda>s. s ''x''))\n    ELSE (''z'' ::= (\\<lambda>s. s ''y''))\n    FI)\n   POST (\\<lambda>s. s ''z'' = max (s ''x'') (s ''y''))\"\n  by auto\n\nlemma integer_division: \n  \"FPRE (\\<lambda>s::nat store. x \\<ge> 0)\n    (''q'' ::= (\\<lambda>s. 0)); \n    (''r'' ::= (\\<lambda>s. x));\n    (WHILE (\\<lambda>s. y \\<le> s ''r'') INV (\\<lambda>s. x = s ''q'' * y + s ''r'' \\<and> s ''r'' \\<ge> 0)\n     DO\n      (''q'' ::= (\\<lambda>s. s ''q'' + 1));\n      (''r'' ::= (\\<lambda>s. s ''r'' - y))\n      OD)\n   POST (\\<lambda>s. x = s ''q'' * y + s ''r'' \\<and> s ''r'' \\<ge> 0 \\<and> s ''r'' < y)\"\n  by (rule rel_modal_kleene_algebra.bdia_whilei_break, simp_all, auto simp: p2r_def)\n\nlemma factorial:\n  \"FPRE (\\<lambda>s::nat store. True)\n   (''x'' ::= (\\<lambda>s. 0));\n   (''y'' ::= (\\<lambda>s. 1));\n   (WHILE (\\<lambda>s. s ''x'' \\<noteq> x0) INV (\\<lambda>s. s ''y'' = fact (s ''x''))\n   DO\n     (''x'' ::= (\\<lambda>s. s ''x'' + 1));\n     (''y'' ::= (\\<lambda>s. s ''y'' \\<cdot> s ''x''))\n   OD)\n   POST (\\<lambda>s. s ''y'' = fact x0)\"\n  by (rule rel_modal_kleene_algebra.bdia_whilei_break, simp_all, auto simp: p2r_def)\n \nlemma my_power:\n  \"FPRE (\\<lambda>s::nat store. True)\n   (''i'' ::= (\\<lambda>s. 0));\n   (''y'' ::= (\\<lambda>s. 1));\n   (WHILE (\\<lambda>s. s ''i'' < n) INV (\\<lambda>s. s ''y'' = x ^ (s ''i'') \\<and> s ''i'' \\<le> n)\n     DO\n       (''y'' ::= (\\<lambda>s. (s ''y'') * x));\n       (''i'' ::= (\\<lambda>s. s ''i'' + 1))\n     OD)\n   POST (\\<lambda>s. s ''y'' = x ^ n)\"\n  by (rule rel_modal_kleene_algebra.bdia_whilei_break, simp_all, auto simp add: p2r_def)\n\nlemma imp_reverse:\n  \"FPRE (\\<lambda>s:: 'a list store. s ''x'' = X)\n   (''y'' ::= (\\<lambda>s. []));\n   (WHILE (\\<lambda>s. s ''x'' \\<noteq> []) INV (\\<lambda>s. rev (s ''x'') @ s ''y'' = rev X)\n    DO \n     (''y'' ::= (\\<lambda>s. hd (s ''x'') # s ''y'')); \n     (''x'' ::= (\\<lambda>s. tl (s ''x'')))\n    OD) \n   POST (\\<lambda>s. s ''y''= rev X )\"\n  apply (rule rel_modal_kleene_algebra.bdia_whilei_break, simp_all)\n  apply auto[1]\n  by (safe, metis append.simps append_assoc hd_Cons_tl rev.simps(2))\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/AVC_KAD/VC_KAD_dual_Examples.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8757869948899666, "lm_q2_score": 0.8056321936479701, "lm_q1q2_score": 0.7055621978615674}}
{"text": "theory QuantK_Sqrt \nimports QuantK_VCG \"HOL-Library.Discrete\"\nbegin \n     \nsubsection \\<open>Example: discrete square root in the quantitative Hoare logic\\<close>  \n  \n  \ntext \\<open>As an example, consider the following program that computes the discrete square root:\\<close>  \n     \ndefinition c :: com where \"c= \n         ''l''::= N 0 ;;\n         ''m'' ::= N 0 ;;\n         ''r''::= Plus (N 1) (V ''x'');;\n         (WHILE (Less (Plus (N 1) (V ''l'')) (V ''r'')) \n              DO (''m'' ::= (Div (Plus (V ''l'') (V ''r'')) (N 2)) ;; \n                 (IF Not (Less (Times (V ''m'') (V ''m'')) (V ''x'')) \n                    THEN ''l'' ::= V ''m''\n                    ELSE ''r'' ::= V ''m'');;\n                 ''m'' ::= N 0))\" \n \ntext \\<open>In this theory we will show that its running time is in the order of magnitude of the\n      logarithm of the variable ''x''\\<close>  \n     \n\ntext \\<open>a little lemma we need later for bounding the running time:\\<close>\n  \nlemma absch: \"\\<And>s k. 1 + s ''x'' = 2 ^ k \\<Longrightarrow> 5 * k \\<le> 96 + 100 * Discrete.log (nat (s ''x''))\"  \nproof -\n  fix s :: state and  k :: nat \n  assume F: \" 1 + s ''x'' = 2 ^ k \" \n  then have i: \"nat (1 + s ''x'') =  2 ^ k\" and nn: \"s ''x''\\<ge> 0\"  apply (auto simp: nat_power_eq)\n    by (smt one_le_power)          \n  have F: \"1 + nat (s ''x'') = 2 ^k\" unfolding i[symmetric] using nn by auto\n  show \"5 * k \\<le> 96 + 100 * Discrete.log (nat (s ''x''))\"\n  proof (cases \"s ''x'' \\<ge> 1\")\n    case True\n    have \"5 * k = 5 * (Discrete.log (2^k))\"     by auto\n    also have \"\\<dots> = 5 * Discrete.log (1 + nat (s ''x''))\" by(simp only: F[symmetric])\n    also have \"\\<dots> \\<le> 5 * Discrete.log (nat (s ''x'' + s ''x''))\" using True\n      apply auto apply(rule monoD[OF log_mono]) by auto\n    also have \"\\<dots> = 5 *  Discrete.log (2 * nat (s ''x''))\" by (auto simp: nat_mult_distrib) \n    also have \"\\<dots> = 5 + 5 * (Discrete.log (nat (s ''x'')))\" using True by auto\n    also have \"\\<dots> \\<le> 96 + 100 * Discrete.log (nat (s ''x''))\" by simp\n    finally show ?thesis .\n  next\n    case False\n    with nn have gt1: \"s ''x'' = 0\" by auto\n    from F[unfolded gt1] have \"2 ^ k = (1::int)\" using log_Suc_zero by auto \n    then have \"k=0\"\n      by (metis One_nat_def add.right_neutral gt1 i n_not_Suc_n nat_numeral nat_power_eq_Suc_0_iff numeral_2_eq_2 numeral_One) \n    then show ?thesis by(simp add: gt1)\n  qed \nqed\n    \n  \ntext \\<open>For simplicity we assume, that during the process all segments between ''l'' and ''r'' have\n      as length a power of two. This simplifies the analysis.\n      To obtain this we choose the prepotential P accordingly.\n\n      Now lets show the correctness of our time complexity: the binary search is in O(log ''x'') \\<close>\n    \nlemma \n  assumes   \n    P: \"P  = (\\<lambda>s. \\<up> (  (\\<exists>k. 1 + s ''x''  = 2 ^ k)) + (Discrete.log (nat ( s ''x'')) + 1))\" and\n      Q[simp]: \"Q = (\\<lambda>_. 0)\" \n  shows \" \\<turnstile>\\<^sub>2\\<^sub>' {P} c {Q}\"\nproof -\n  \\<comment> \\<open>first we create an annotated command\\<close>\n  let ?lb = \"''m'' ::= \n              (Div (Plus (V ''l'') (V ''r'')) (N 2)) ;; \n              (IF Not (Less (Times (V ''m'') (V ''m'')) (V ''x'')) \n                THEN ''l'' ::= V ''m''\n                ELSE ''r'' ::= V ''m'');;\n              (''m'' ::= N 0)::acom\"\n  \\<comment> \\<open>with an invariant potential\\<close>\n  define I   where \"I \\<equiv> (\\<lambda>s::state. (( emb (  s ''l''\\<ge>0   \\<and> ( \\<exists>k. s ''r'' - s ''l'' = 2 ^ k) ) + 5 * Discrete.log (nat (s ''r'') - nat (s ''l'')))::enat) )\"\n  let ?C = \" ((''l''::= N 0) :: acom) ;; (''m'' ::= N 0) ;; ''r''::= Plus (N 1) (V ''x'');; ({I} WHILE (Less (Plus (N 1) (V ''l'')) (V ''r'')) DO ?lb)\"\n  \n  \\<comment> \\<open>we show that the annotated command corresponds to the command we are interested in\\<close>\n  have s: \"strip ?C = c\" unfolding c_def by auto\n    \n  \\<comment> \\<open>now we show that the annotated command is correct; here we use the VCG for the QuantK logic\\<close>\n  have v: \"\\<turnstile>\\<^sub>2\\<^sub>' {P} strip ?C {Q}\"\n  proof (rule vc_sound'', safe) \n    \n    \\<comment> \\<open>A) first lets show the verification conditions:\\<close>\n    show \"vc ?C Q\" apply auto \n      unfolding I_def\n      subgoal for s\n        apply(cases \"(\\<exists>k. s ''r''  - s ''l'' = 2 ^ k)\") apply auto\n        apply(cases \"(1 + s ''l'' < s ''r'')\") apply auto\n        apply(cases \"0 \\<le> s ''l''\") apply auto \n      proof (goal_cases)\n        case (1 k)\n        then have \"k>0\" using gr0I by force \n        then obtain k' where k': \"k=k'+1\" by (metis Suc_eq_plus1 Suc_pred)  \n        from 1 k' have R: \" s ''r'' - (s ''l'' + s ''r'') div 2 = 2 ^ k'\" by auto\n        have gN: \"s ''l''\\<le>s ''r''\"  \"s ''l''\\<ge>0\" \"s ''r'' \\<ge> 0\" using 1 by auto\n        have n: \"nat ( s ''r'' - (s ''l'' + s ''r'') div 2 ) =  nat (s ''r'') - nat ((s ''l'' + s ''r'') div 2)\"\n          using gN  apply(simp add: nat_diff_distrib nat_div_distrib) done\n            \n        have R': \"nat (s ''r'') -  nat ((s ''l'' + s ''r'') div 2) = 2 ^ k'\"\n          apply(simp only: n[symmetric] R nat_power_eq) by auto \n        have S': \"nat (s ''r'') - nat (s ''l'') = 2 ^ k\"\n          using gN apply(simp only: nat_diff_distrib[symmetric] 1(2) nat_power_eq) by auto\n        have N: \"0 \\<le> (s ''l'' + s ''r'') div 2\" using gN by auto     \n            \n        from N  show ?case apply (simp ) apply (simp only : R R' S' k') by (auto simp: eSuc_enat plus_1_eSuc(2))    \n      qed \n      subgoal for s \n        apply(cases \"\\<exists>k. s ''r''  - s ''l'' = 2 ^ k\") apply auto\n        apply (cases \"(1 + s ''l'' < s ''r'')\") apply auto\n        apply(cases \"0 \\<le> s ''l''\") apply auto \n      proof (goal_cases)\n        case (1 k)\n        from 1(2,3) have \"k>0\" using gr0I by force \n        then obtain k' where k': \"k=k'+1\" by (metis Suc_eq_plus1 Suc_pred)            \n        from 1 k' have R: \" (s ''l'' + s ''r'') div 2 - s ''l'' = 2 ^ k'\" by auto \n        have gN: \"s ''l''\\<le>s ''r''\"  \"s ''l''\\<ge>0\" \"s ''r'' \\<ge> 0\" using 1 by auto\n        have n: \"nat ((s ''l'' + s ''r'') div 2 - s ''l'') =  nat ( (s ''l'' + s ''r'') div 2) - nat (s ''l'')\"\n          using gN  apply(simp add: nat_diff_distrib nat_div_distrib) done\n            \n        have R': \"nat ( (s ''l'' + s ''r'') div 2) - nat (s ''l'') = 2 ^ k'\"\n          apply(simp only: n[symmetric] R nat_power_eq) by auto \n        have S': \"nat (s ''r'') - nat (s ''l'') = 2 ^ k\"\n          using gN apply(simp only: nat_diff_distrib[symmetric] 1(2) nat_power_eq) by auto \n            \n        show ?case   apply (simp only : R R' S' k') by (auto simp: eSuc_enat plus_1_eSuc(2))        \n      qed done        \n  next\n    \\<comment> \\<open>B) lets show that the precondition implies the weakest precondition, and that the\n            time bound of C can be bounded by log ''x''\\<close>\n    fix s\n    show \"pre ?C Q s \\<le> enat 100 * P s\" unfolding  I_def apply(simp only: P)  apply auto apply(cases \"(\\<exists>k. 1 + s ''x''   = 2 ^ k)\") \n       apply (auto simp: eSuc_enat plus_1_eSuc(2) nat_power_eq) \n        using absch by force\n  qed auto\n    \n  from s v show ?thesis 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/Hoare_Time/QuantK_Sqrt.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8757869948899665, "lm_q2_score": 0.805632181981183, "lm_q1q2_score": 0.7055621876439468}}
{"text": "theory sample5\n  imports Main begin\n\ninductive star :: \"('a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> bool\" \n  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\nthm star.induct\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 add:refl) *)\n  (* for subgoal 1. The first one is P x x,\n   the result of case refl*)\n   apply(assumption)\n  apply(metis step)\n  done\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/sample5.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8757869916479466, "lm_q2_score": 0.805632181981183, "lm_q1q2_score": 0.7055621850320714}}
{"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_ISortPermutes\nimports \"../../Test_Base\"\nbegin\n\ndatatype 'a list = nil2 | cons2 \"'a\" \"'a list\"\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\nfun elem :: \"'a => 'a list => bool\" where\n\"elem x (nil2) = False\"\n| \"elem x (cons2 z xs) = ((z = x) | (elem x xs))\"\n\nfun deleteBy :: \"('a => ('a => bool)) => 'a => 'a list =>\n                 'a list\" where\n\"deleteBy x y (nil2) = nil2\"\n| \"deleteBy x y (cons2 y2 ys) =\n     (if (x y) y2 then ys else cons2 y2 (deleteBy x y ys))\"\n\nfun isPermutation :: \"'a list => 'a list => bool\" where\n\"isPermutation (nil2) (nil2) = True\"\n| \"isPermutation (nil2) (cons2 z x2) = False\"\n| \"isPermutation (cons2 x3 xs) y =\n     ((elem x3 y) &\n        (isPermutation\n           xs (deleteBy (% (x4 :: 'a) => % (x5 :: 'a) => (x4 = x5)) x3 y)))\"\n\ntheorem property0 :\n  \"isPermutation (isort 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_sort_ISortPermutes.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869786798663, "lm_q2_score": 0.8056321913146127, "lm_q1q2_score": 0.7055621827586647}}
{"text": "theory ex2_03 imports Main begin\n\nfun count :: \"'a \\<Rightarrow> 'a list \\<Rightarrow> nat\" where\n\"count y Nil = 0\" |\n\"count y (x#xs) = (if x = y then 1+(count y xs) else count y xs)\"\n\n(* I cannot understand why the value is not 1*)\nvalue \"count 1 (1#2#3#[])\"\n\ntheorem \"count x xs \\<le> length xs\"\napply(induction xs)\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_03.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9173026573249611, "lm_q2_score": 0.7690802370707281, "lm_q1q2_score": 0.70547934516109}}
{"text": "(* Author: Ujkan Sulejmani *)\n\nsection \\<open>Center Selection\\<close>\n\ntheory Center_Selection\n  imports Complex_Main \"HOL-Hoare.Hoare_Logic\"\nbegin\n\ntext \\<open>The Center Selection (or metric k-center) problem. Given a set of \\textit{sites} \\<open>S\\<close>\nin a metric space, find a subset \\<open>C \\<subseteq> S\\<close> that minimizes the maximal distance from any \\<open>s \\<in> S\\<close>\nto some \\<open>c \\<in> C\\<close>. This theory presents a verified 2-approximation algorithm.\nIt is based on Section 11.2 in the book by Kleinberg and Tardos \\<^cite>\\<open>\"KleinbergT06\"\\<close>.\nIn contrast to the proof in the book, our proof is a standard invariant proof.\\<close>\n\nlocale Center_Selection =\n  fixes S :: \"('a :: metric_space) set\"\n    and k :: nat\n  assumes finite_sites: \"finite S\"\n  and     non_empty_sites: \"S \\<noteq> {}\"\nand       non_zero_k: \"k > 0\"\nbegin\n\ndefinition distance :: \"('a::metric_space) set \\<Rightarrow> ('a::metric_space) \\<Rightarrow> real\" where\n\"distance C s = Min (dist s ` C)\"\n\ndefinition radius :: \"('a :: metric_space) set \\<Rightarrow> real\" where\n\"radius C = Max (distance C ` S)\"\n\nlemma distance_mono:\nassumes \"C\\<^sub>1 \\<subseteq> C\\<^sub>2\" and \"C\\<^sub>1 \\<noteq> {}\" and \"finite C\\<^sub>2\"\nshows \"distance C\\<^sub>1 s \\<ge> distance C\\<^sub>2 s\"\nby (simp add: Min.subset_imp assms distance_def image_mono)\n\nlemma finite_distances: \"finite (distance C ` S)\"\n  using finite_sites by simp\n\nlemma non_empty_distances: \"distance C ` S \\<noteq> {}\"\n  using non_empty_sites by simp\n\nlemma radius_contained: \"radius C \\<in> distance C ` S\"\n  using finite_distances non_empty_distances Max_in radius_def by simp\n\nlemma radius_def2: \"\\<exists>s \\<in> S. distance C s = radius C\"\n  using radius_contained image_iff by metis\n\nlemma dist_lemmas_aux:\n  assumes  \"finite C\"\n      and  \"C \\<noteq> {}\"\n  shows  \"finite (dist s ` C)\"\n    and \"finite (dist s ` C) \\<Longrightarrow> distance C s \\<in> dist s ` C\"\n    and \"distance C s \\<in> dist s ` C \\<Longrightarrow> \\<exists>c \\<in> C. dist s c = distance C s\"\nand \"\\<exists>c \\<in> C. dist s c = distance C s \\<Longrightarrow> distance C s \\<ge> 0\"\nproof\n  show \"finite C\" using assms(1) by simp\nnext\n  assume \"finite (dist s ` C)\"\n  then show \"distance C s \\<in> dist s ` C\" using distance_def eq_Min_iff assms(2) by blast\nnext\n  assume \"distance C s \\<in> dist s ` C\" \n  then show \"\\<exists>c \\<in> C. dist s c = distance C s\" by auto\nnext\n  assume \"\\<exists>c \\<in> C. dist s c = distance C s\"\n  then show \"distance C s \\<ge> 0\" by (metis zero_le_dist)\nqed\n\nlemma dist_lemmas:\n  assumes \"finite C\"\n      and \"C \\<noteq> {}\"\n  shows \"finite (dist s ` C)\"\n    and \"distance C s \\<in> dist s ` C\"\n    and \"\\<exists>c \\<in> C. dist s c = distance C s\"\n    and \"distance C s \\<ge> 0\"\n  using dist_lemmas_aux assms by auto\n\nlemma radius_max_prop: \"(\\<forall>s \\<in> S. distance C s \\<le> r) \\<Longrightarrow> (radius C \\<le> r)\"\n  by (metis image_iff radius_contained)\n\nlemma dist_ins:\nassumes \"\\<forall>c\\<^sub>1 \\<in> C. \\<forall>c\\<^sub>2 \\<in> C. c\\<^sub>1 \\<noteq> c\\<^sub>2 \\<longrightarrow> x < dist c\\<^sub>1 c\\<^sub>2\"\nand \"distance C s > x\"\nand \"finite C\"\nand \"C \\<noteq> {}\"\nshows \"\\<forall>c\\<^sub>1 \\<in> (C \\<union> {s}). \\<forall>c\\<^sub>2 \\<in> (C \\<union> {s}). c\\<^sub>1 \\<noteq> c\\<^sub>2 \\<longrightarrow> x < dist c\\<^sub>1 c\\<^sub>2\"\nproof (rule+)\n  fix c\\<^sub>1 c\\<^sub>2\n  assume local_assms: \"c\\<^sub>1\\<in>C \\<union> {s}\" \"c\\<^sub>2\\<in>C \\<union> {s}\" \"c\\<^sub>1 \\<noteq> c\\<^sub>2\"\n  then have \"c\\<^sub>1 \\<in> C  \\<and> c\\<^sub>2 \\<in> C  \\<or> c\\<^sub>1 \\<in>C  \\<and> c\\<^sub>2\\<in> {s} \\<or> c\\<^sub>2\\<in>C  \\<and> c\\<^sub>1 \\<in> {s} \\<or> c\\<^sub>1 \\<in> {s} \\<and> c\\<^sub>2\\<in> {s}\" by auto\n  then show \"x < dist c\\<^sub>1 c\\<^sub>2\"\n  proof (elim disjE)\n    assume \"c\\<^sub>1 \\<in>C  \\<and> c\\<^sub>2\\<in>C\"\n    then show ?thesis using assms(1) local_assms(3) by simp\n  next\n    assume case_assm: \"c\\<^sub>1 \\<in> C \\<and> c\\<^sub>2 \\<in> {s}\"\n    have \"x < distance C c\\<^sub>2\" using assms(2) case_assm by simp\n    also have \" ... \\<le> dist c\\<^sub>2 c\\<^sub>1\"\n      using Min.coboundedI distance_def assms(3,4) dist_lemmas(1, 2) case_assm by simp\n    also have \" ... = dist c\\<^sub>1 c\\<^sub>2\" using dist_commute by metis\n    finally show ?thesis .\n  next\n    assume case_assm: \"c\\<^sub>2 \\<in> C \\<and> c\\<^sub>1 \\<in> {s}\"\n    have \"x < distance C c\\<^sub>1\" using assms(2) case_assm by simp\n    also have \" ... \\<le> dist c\\<^sub>1 c\\<^sub>2\"\n      using Min.coboundedI distance_def assms(3,4) dist_lemmas(1, 2) case_assm by simp\n    finally show ?thesis .\n  next\n    assume \"c\\<^sub>1 \\<in> {s} \\<and> c\\<^sub>2 \\<in> {s}\" \n    then have False using local_assms by simp\n    then show ?thesis by simp\n  qed\nqed\n\nsubsection \\<open>A Preliminary Algorithm and Proof\\<close>\n\ntext \\<open>This subsection verifies an auxiliary algorithm by Kleinberg and Tardos.\nOur proof of the main algorithm does not does not rely on this auxiliary algorithm at all\nbut we do reuse part off its invariant proof later on.\\<close>\n\ndefinition inv :: \"('a :: metric_space) set \\<Rightarrow> ('a :: metric_space set) \\<Rightarrow> real \\<Rightarrow> bool\" where\n\"inv S' C r =\n  ((\\<forall>s \\<in> (S - S'). distance C s \\<le> 2*r) \\<and> S' \\<subseteq> S \\<and> C \\<subseteq> S \\<and>\n   (\\<forall>c \\<in> C. \\<forall>s \\<in> S'. S' \\<noteq> {} \\<longrightarrow> dist c s > 2 * r) \\<and> (S' = S \\<or> C \\<noteq> {}) \\<and>\n   (\\<forall>c\\<^sub>1 \\<in> C. \\<forall>c\\<^sub>2 \\<in> C. c\\<^sub>1 \\<noteq> c\\<^sub>2 \\<longrightarrow> dist c\\<^sub>1 c\\<^sub>2 > 2 * r))\" \n\nlemma inv_init: \"inv S {} r\"\n  unfolding inv_def non_empty_sites by simp\nlemma inv_step:\n  assumes \"S' \\<noteq> {}\"\nand IH: \"inv S' C r\"\ndefines[simp]: \"s \\<equiv> (SOME s. s \\<in> S')\"\nshows \"inv (S' - {s' . s' \\<in> S' \\<and> dist s s' \\<le> 2*r}) (C \\<union> {s}) r\"\nproof -\n  have s_def: \"s \\<in> S'\" using assms(1) some_in_eq by auto\n\n  have \"finite (C \\<union> {s})\" using IH finite_subset[OF _ finite_sites] by (simp add: inv_def)\n\n  moreover\n\n  have \"(\\<forall>s' \\<in> (S - (S' - {s' . s' \\<in> S' \\<and> dist s s' \\<le> 2*r})). distance (C \\<union> {s}) s' \\<le> 2*r)\"\n  proof \n    fix s''\n    assume \"s'' \\<in> S - (S' - {s' . s' \\<in> S' \\<and> dist s s' \\<le> 2*r})\"\n    then have \"s'' \\<in> S - S' \\<or> s'' \\<in> {s' . s' \\<in> S' \\<and> dist s s' \\<le> 2*r}\" by simp\n    then show \"distance (C \\<union> {s}) s'' \\<le> 2 * r\"\n    proof (elim disjE)\n      assume local_assm: \"s'' \\<in> S - S'\"\n      have \"S' = S \\<or> C \\<noteq> {}\" using IH by (simp add: inv_def)\n      then show ?thesis\n      proof (elim disjE)\n        assume \"S' = S\"\n        then have \"s'' \\<in> {}\" using local_assm by simp\n        then show ?thesis by simp\n      next\n        assume C_not_empty: \"C \\<noteq> {}\"\n        have \"finite C\" using IH finite_subset[OF _ finite_sites] by (simp add: inv_def)\n        then have \"distance (C \\<union> {s}) s'' \\<le> distance C s''\"\n          using distance_mono C_not_empty by (meson Un_upper1 calculation)\n        also have \" ...  \\<le> 2 * r\" using IH local_assm inv_def by simp\n        finally show ?thesis .\n      qed\n    next\n      assume local_assm: \"s'' \\<in> {s' . s' \\<in> S' \\<and> dist s s' \\<le> 2*r}\"\n      then have \"distance (C \\<union> {s}) s'' \\<le> dist s'' s\"\n        using Min.coboundedI distance_def dist_lemmas calculation by auto\n      also have \" ... \\<le> 2 * r\" using local_assm by (smt dist_self dist_triangle2 mem_Collect_eq)\n      finally show ?thesis .\n    qed\n  qed\n\n  moreover\n\n  have \"S' - {s' . s' \\<in> S' \\<and> dist s s' \\<le> 2*r} \\<subseteq> S\" using IH by (auto simp: inv_def)\n\n  moreover\n  {\n    have \"s \\<in> S\" using IH inv_def s_def by auto\n    then have \"C \\<union> {s} \\<subseteq> S\" using IH by (simp add: inv_def)\n  }\n  moreover\n\n  have \"(\\<forall>c\\<in>C \\<union> {s}. \\<forall>c\\<^sub>2\\<in>C \\<union> {s}. c \\<noteq> c\\<^sub>2 \\<longrightarrow> 2 * r < dist c c\\<^sub>2)\"\n  proof (rule+)\n    fix c\\<^sub>1 c\\<^sub>2\n    assume local_assms: \"c\\<^sub>1 \\<in> C \\<union> {s}\" \"c\\<^sub>2 \\<in> C \\<union> {s}\" \"c\\<^sub>1 \\<noteq> c\\<^sub>2\"\n    then have \"(c\\<^sub>1 \\<in> C \\<and> c\\<^sub>2 \\<in> C) \\<or> (c\\<^sub>1 = s \\<and> c\\<^sub>2 \\<in> C) \\<or> (c\\<^sub>1 \\<in> C \\<and> c\\<^sub>2 = s) \\<or> (c\\<^sub>1 = s \\<and> c\\<^sub>2 = s)\"\n      using assms by auto\n    then show \"2 * r < dist c\\<^sub>1 c\\<^sub>2\"\n    proof (elim disjE)\n      assume \"c\\<^sub>1 \\<in> C \\<and> c\\<^sub>2 \\<in> C\"\n      then show \"2 * r < dist c\\<^sub>1 c\\<^sub>2\" using IH inv_def local_assms by simp\n    next\n      assume case_assm: \"c\\<^sub>1 = s \\<and> c\\<^sub>2 \\<in> C\"\n      have \"(\\<forall>c \\<in> C. \\<forall>s\\<in>S'. S' \\<noteq> {} \\<longrightarrow> 2 * r < dist c s)\" using IH inv_def by simp\n      then show ?thesis by (smt case_assm s_def assms(1) dist_self dist_triangle3 singletonD)\n    next\n      assume case_assm: \"c\\<^sub>1 \\<in> C \\<and> c\\<^sub>2 = s\"\n      have \"(\\<forall>c \\<in> C. \\<forall>s\\<in>S'. S' \\<noteq> {} \\<longrightarrow> 2 * r < dist c s)\" using IH inv_def by simp\n      then show ?thesis by (smt case_assm s_def assms(1) dist_self dist_triangle3 singletonD)\n    next\n      assume \"c\\<^sub>1 = s \\<and> c\\<^sub>2 = s\"\n      then have False using local_assms(3) by simp\n      then show ?thesis by simp\n    qed\n  qed\n\n  moreover\n\n  have \"(\\<forall>c\\<in>C \\<union> {s}. \\<forall>s'' \\<in> S' - {s' \\<in> S'. dist s s' \\<le> 2 * r}.\n           S' - {s' \\<in> S'. dist s s' \\<le> 2 * r} \\<noteq> {} \\<longrightarrow> 2 * r < dist c s'')\"\n    using IH inv_def by fastforce\n\n  moreover\n\n  have \"(S' - {s' \\<in> S'. dist s s' \\<le> 2 * r} = S \\<or> C \\<union> {s} \\<noteq> {})\" by simp\n\n  ultimately show ?thesis unfolding inv_def by blast\nqed\n\nlemma inv_last_1: \n  assumes \"\\<forall>s \\<in> (S - S'). distance C s \\<le> 2*r\"\n    and \"S' = {}\"\n  shows \"radius C \\<le> 2*r\"\n  by (metis Diff_empty assms image_iff radius_contained)\n\nlemma inv_last_2: \n  assumes \"finite C\"\n  and \"card C > n\"\n  and \"C \\<subseteq> S\"\n  and \"\\<forall>c\\<^sub>1 \\<in> C. \\<forall>c\\<^sub>2 \\<in> C. c\\<^sub>1 \\<noteq> c\\<^sub>2 \\<longrightarrow> dist c\\<^sub>1 c\\<^sub>2 > 2*r\"\n  shows \"\\<forall>C'. card C' \\<le> n \\<and> card C' > 0 \\<longrightarrow> radius C' > r\" (is ?P)\nproof (rule ccontr)\n  assume \"\\<not> ?P\"\n  then obtain C' where card_C': \"card C' \\<le> n \\<and> card C' > 0\" and radius_C': \"radius C' \\<le> r\" by auto\n  have \"\\<forall>c \\<in> C. (\\<exists>c'. c' \\<in> C' \\<and> dist c c' \\<le> r)\"\n  proof\n    fix c\n    assume \"c \\<in> C\"\n    then have \"c \\<in> S\" using assms(3) by blast\n    then have \"distance C' c \\<le> radius C'\" using finite_distances by (simp add: radius_def)\n    then have \"distance C' c \\<le> r\" using radius_C' by simp\n    then show \"\\<exists>c'. c' \\<in> C' \\<and> dist c c' \\<le> r\" using dist_lemmas\n      by (metis card_C' card_gt_0_iff)\n  qed\n  then obtain f where f: \"\\<forall>c\\<in>C. f c \\<in> C' \\<and> dist c (f c) \\<le> r\" by metis\n  have \"\\<not>inj_on f C\"\n  proof\n    assume \"inj_on f C\"\n    then have \"card C' \\<ge> card C\" using \\<open>inj_on f C\\<close> card_inj_on_le card_ge_0_finite card_C' f by blast\n    then show False using card_C' \\<open>n < card C\\<close> by linarith\n  qed\n  then obtain c1 c2 where defs: \"c1 \\<in> C \\<and> c2 \\<in> C \\<and> c1 \\<noteq> c2 \\<and> f c1 = f c2\" using inj_on_def by blast\n  then have *: \"dist c1 (f c1) \\<le> r \\<and> dist c2 (f c1) \\<le> r\" using f by auto\n\n  have \"2 * r < dist c1 c2\" using assms defs by simp\n  also have \" ... \\<le> dist c1 (f c1) + dist (f c1) c2\" by(rule dist_triangle)\n  also have \" ... = dist c1 (f c1) + dist c2 (f c1)\" using dist_commute by simp\n  also have \" ... \\<le> 2 * r\" using * by simp\n  finally show False by simp\nqed\n\nlemma inv_last:\n  assumes \"inv {} C r\"\n  shows \"(card C \\<le> k \\<longrightarrow> radius C \\<le> 2*r) \\<and> (card C > k \\<longrightarrow> (\\<forall>C'. card C' > 0 \\<and> card C' \\<le> k \\<longrightarrow> radius C' > r))\"\n  using assms inv_def inv_last_1 inv_last_2 finite_subset[OF _ finite_sites] by auto\n\ntheorem Center_Selection_r:\n  \"VARS (S' :: ('a :: metric_space) set) (C :: ('a :: metric_space) set) (r :: real) (s :: 'a)\n  {True}\n  S' := S;\n  C := {};\n  WHILE S' \\<noteq> {} INV {inv S' C r} DO\n    s := (SOME s. s \\<in> S');\n    C := C \\<union> {s};\n    S' := S' - {s' . s' \\<in> S' \\<and> dist s s' \\<le> 2*r}\n    OD\n  {(card C \\<le> k \\<longrightarrow> radius C \\<le> 2*r) \\<and> (card C > k \\<longrightarrow> (\\<forall>C'. card C' > 0 \\<and> card C' \\<le> k \\<longrightarrow> radius C' > r))}\"\nproof (vcg, goal_cases)\n  case (1 S' C r)\n  then show ?case using inv_init by simp\nnext\n  case (2 S' C r)\n  then show ?case using inv_step by simp\nnext\n  case (3 S' C r)\n  then show ?case using inv_last by blast\nqed\n\n\nsubsection \\<open>The Main Algorithm\\<close>\n\ndefinition invar :: \"('a :: metric_space) set \\<Rightarrow> bool\" where\n\"invar C = (C \\<noteq> {} \\<and> card C \\<le> k \\<and> C \\<subseteq> S \\<and>\n  (\\<forall>C'. (\\<forall>c\\<^sub>1 \\<in> C. \\<forall>c\\<^sub>2 \\<in> C. c\\<^sub>1 \\<noteq> c\\<^sub>2 \\<longrightarrow> dist c\\<^sub>1 c\\<^sub>2 > 2 * radius C')\n        \\<or> (\\<forall>s \\<in> S. distance C s \\<le> 2 * radius C')))\"\n\nabbreviation some where \"some A \\<equiv> (SOME s. s \\<in> A)\"\n\nlemma invar_init: \"invar {some S}\"\nproof -\n  let ?s = \"some S\"\n  have s_in_S: \"?s \\<in> S\" using some_in_eq non_empty_sites by blast\n\n  have \"{?s} \\<noteq> {}\" by simp\n\n  moreover\n\n  have \"{SOME s. s \\<in> S} \\<subseteq> S\" using s_in_S by simp\n\n  moreover\n\n  have \"card {SOME s. s \\<in> S} \\<le> k\" using non_zero_k by simp\n\n  ultimately show ?thesis by (auto simp: invar_def)\nqed\n\nabbreviation furthest_from where\n\"furthest_from C \\<equiv> (SOME s. s \\<in> S \\<and> distance C s = Max (distance C ` S))\" \n\n\n\n  have \"C \\<union> {furthest_from C} \\<noteq> {}\" by simp\n\n  moreover\n\n  have \"(C \\<union> {furthest_from C}) \\<subseteq> S\" using assms(1) furthest_from_C_props unfolding invar_def by simp\n\n  moreover\n\n  have \"\\<forall>C'. (\\<forall>s \\<in> S. distance (C \\<union> {furthest_from C}) s \\<le> 2 * radius C')\n          \\<or> (\\<forall>c\\<^sub>1 \\<in> C \\<union> {furthest_from C}. \\<forall>c\\<^sub>2 \\<in> C \\<union> {furthest_from C}. c\\<^sub>1 \\<noteq> c\\<^sub>2 \\<longrightarrow> 2 * radius C' < dist c\\<^sub>1 c\\<^sub>2)\"\n  proof \n    fix C'\n    have \"distance C (furthest_from C) > 2 * radius C' \\<or> distance C (furthest_from C) \\<le> 2 * radius C'\" by auto\n    then show \"(\\<forall>s \\<in> S. distance (C \\<union> {furthest_from C}) s \\<le> 2 * radius C')\n               \\<or> (\\<forall>c\\<^sub>1 \\<in> C \\<union> {furthest_from C}. \\<forall>c\\<^sub>2 \\<in> C \\<union> {furthest_from C}. c\\<^sub>1 \\<noteq> c\\<^sub>2 \\<longrightarrow> 2 * radius C' < dist c\\<^sub>1 c\\<^sub>2)\"\n    proof (elim disjE)\n      assume asm: \"distance C (furthest_from C) > 2 * radius C'\"\n      then have \"\\<not>(\\<forall>s \\<in> S. distance C s \\<le> 2 * radius C')\" using furthest_from_C_props by force\n      then have IH: \"\\<forall>c\\<^sub>1 \\<in> C. \\<forall>c\\<^sub>2 \\<in> C. c\\<^sub>1 \\<noteq> c\\<^sub>2 \\<longrightarrow> 2 * radius C' < dist c\\<^sub>1 c\\<^sub>2\"\n        using assms(1) unfolding invar_def by blast\n      have \"(\\<forall>c\\<^sub>1 \\<in> C \\<union> {furthest_from C}. (\\<forall>c\\<^sub>2 \\<in> C \\<union> {furthest_from C}. c\\<^sub>1 \\<noteq> c\\<^sub>2 \\<longrightarrow> 2 * radius C' < dist c\\<^sub>1 c\\<^sub>2))\"\n        using dist_ins[of \"C\" \"2 * radius C'\" \"furthest_from C\"] IH C_props asm by simp\n      then show ?thesis by simp\n    next\n      assume main_assm: \"2 * radius C' \\<ge> distance C (furthest_from C)\"\n      have \"(\\<forall>s \\<in> S. distance (C \\<union> {furthest_from C}) s \\<le> 2 * radius C')\"\n      proof\n        fix s\n        assume local_assm: \"s \\<in> S\"\n        then show \"distance (C \\<union> {furthest_from C}) s \\<le> 2 * radius C'\"\n        proof -\n          have \"distance (C \\<union> {furthest_from C}) s \\<le> distance C s\"\n            using distance_mono[of C \"C \\<union> {furthest_from C}\"] C_props by auto\n          also have \" ... \\<le> distance C (furthest_from C)\"\n            using Max.coboundedI local_assm finite_distances radius_def furthest_from_C_props by auto\n          also have \" ... \\<le> 2 * radius C'\" using main_assm by simp\n          finally show ?thesis .\n        qed\n      qed\n      then show ?thesis by blast\n    qed\n  qed\n\n  ultimately show ?thesis unfolding invar_def by blast\nqed\n\nlemma invar_last:\nassumes \"invar C\" and \"\\<not>card C < k\"\nshows \"card C = k\" and \"card C' > 0 \\<and> card C' \\<le> k \\<longrightarrow> radius C \\<le> 2 * radius C'\"\nproof -\n  show \"card C = k\" using assms(1, 2) unfolding invar_def by simp\nnext\n  have C_props: \"finite C \\<and> C \\<noteq> {}\" using finite_sites assms(1) unfolding invar_def by (meson finite_subset)\n  show \"card C' > 0 \\<and> card C' \\<le> k \\<longrightarrow> radius C \\<le> 2 * radius C'\"\n  proof (rule impI)\n    assume C'_assms: \"0 < card (C' :: 'a set) \\<and> card C' \\<le> k\"\n    let ?r = \"radius C'\"\n    have \"(\\<forall>c\\<^sub>1 \\<in> C. \\<forall>c\\<^sub>2 \\<in> C. c\\<^sub>1 \\<noteq> c\\<^sub>2 \\<longrightarrow> 2 * ?r < dist c\\<^sub>1 c\\<^sub>2) \\<or> (\\<forall>s \\<in> S. distance C s \\<le> 2 * ?r)\"\n      using assms(1) unfolding invar_def by simp\n    then show \"radius C \\<le> 2 * ?r\"\n    proof\n      assume case_assm: \"\\<forall>c\\<^sub>1\\<in>C. \\<forall>c\\<^sub>2\\<in>C. c\\<^sub>1 \\<noteq> c\\<^sub>2 \\<longrightarrow> 2 * ?r < dist c\\<^sub>1 c\\<^sub>2\"\n      obtain s where s_def: \"radius C = distance C s \\<and> s \\<in> S\" using radius_def2 by metis\n      show ?thesis\n      proof (rule ccontr)\n        assume contr_assm: \"\\<not> radius C \\<le> 2 * ?r\"\n        then have s_prop: \"distance C s > 2 * ?r\" using s_def by simp\n        then have \\<open>\\<forall>c\\<^sub>1 \\<in> C \\<union> {s}. \\<forall>c\\<^sub>2 \\<in> C \\<union> {s}. c\\<^sub>1 \\<noteq> c\\<^sub>2 \\<longrightarrow> dist c\\<^sub>1 c\\<^sub>2 > 2 * ?r\\<close>\n          using C_props dist_ins[of \"C\" \"2*?r\" \"s\"] case_assm by blast\n        moreover\n        {\n          have \"s \\<notin> C\"\n          proof\n            assume \"s \\<in> C\"\n            then have \"distance C s \\<le> dist s s\" using Min.coboundedI[of \"distance C ` S\" \"dist s s\"] \n              by (simp add: distance_def C_props)\n            also have \" ... = 0\" by simp\n            finally have \"distance C s = 0\" using dist_lemmas(4) by (smt C_props)\n            then have radius_le_zero: \"2 * ?r < 0\" using contr_assm s_def by simp\n            obtain x where x_def: \"?r = distance C' x\" using radius_def2 by metis\n            obtain l where l_def: \"distance C' x = dist x l\" using dist_lemmas(3) by (metis C'_assms card_gt_0_iff)\n            then have \"dist x l = ?r\" by (simp add: x_def)\n            also have \"...  < 0\" using C'_assms radius_le_zero by simp\n            finally show False by simp\n          qed\n          then have \"card (C \\<union> {s}) > k\" using assms(1,2) C_props unfolding invar_def by simp\n        }\n        moreover\n          have \"C \\<union> {s} \\<subseteq> S\" using assms(1) s_def unfolding invar_def by simp\n        moreover\n          have \"finite (C \\<union> {s})\" using calculation(3) finite_subset finite_sites by auto\n        ultimately have \"\\<forall>C. card C \\<le> k \\<and> card C > 0 \\<longrightarrow> radius C > ?r\" using inv_last_2 by metis\n        then have \"?r > ?r\" using C'_assms by blast\n        then show False by simp\n      qed\n    next\n      assume \"\\<forall>s\\<in>S. distance C s \\<le> 2 * radius C'\"\n      then show ?thesis by (metis image_iff radius_contained)\n    qed\n  qed\nqed\n\ntheorem Center_Selection: \n\"VARS (C :: ('a :: metric_space) set) (s :: ('a :: metric_space))\n  {k \\<le> card S}\n  C := {some S};\n  WHILE card C < k INV {invar C} DO\n    C := C \\<union> {furthest_from C}\n  OD\n  {card C = k \\<and> (\\<forall>C'. card C' > 0 \\<and> card C' \\<le> k \\<longrightarrow> radius C \\<le> 2 * radius C')}\"\nproof (vcg, goal_cases)\n  case (1 C s)\n  show ?case using invar_init by simp\nnext\n  case (2 C s)\n  then show ?case using invar_step by blast\nnext\n  case (3 C s)\n  then show ?case using invar_last by blast\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/Approximation_Algorithms/Center_Selection.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8652240860523328, "lm_q2_score": 0.8152324960856175, "lm_q1q2_score": 0.7053587913458405}}
{"text": "(*  Title:      HOL/Induct/Sigma_Algebra.thy\n    Author:     Markus Wenzel, TU Muenchen\n*)\n\nsection {* Sigma algebras *}\n\ntheory Sigma_Algebra\nimports Main\nbegin\n\ntext {*\n  This is just a tiny example demonstrating the use of inductive\n  definitions in classical mathematics.  We define the least @{text\n  \\<sigma>}-algebra over a given set of sets.\n*}\n\ninductive_set \\<sigma>_algebra :: \"'a set set => 'a set set\" for A :: \"'a set set\"\nwhere\n  basic: \"a \\<in> A ==> a \\<in> \\<sigma>_algebra A\"\n| UNIV: \"UNIV \\<in> \\<sigma>_algebra A\"\n| complement: \"a \\<in> \\<sigma>_algebra A ==> -a \\<in> \\<sigma>_algebra A\"\n| Union: \"(!!i::nat. a i \\<in> \\<sigma>_algebra A) ==> (\\<Union>i. a i) \\<in> \\<sigma>_algebra A\"\n\ntext {*\n  The following basic facts are consequences of the closure properties\n  of any @{text \\<sigma>}-algebra, merely using the introduction rules, but\n  no induction nor cases.\n*}\n\ntheorem sigma_algebra_empty: \"{} \\<in> \\<sigma>_algebra A\"\nproof -\n  have \"UNIV \\<in> \\<sigma>_algebra A\" by (rule \\<sigma>_algebra.UNIV)\n  then have \"-UNIV \\<in> \\<sigma>_algebra A\" by (rule \\<sigma>_algebra.complement)\n  also have \"-UNIV = {}\" by simp\n  finally show ?thesis .\nqed\n\ntheorem sigma_algebra_Inter:\n  \"(!!i::nat. a i \\<in> \\<sigma>_algebra A) ==> (\\<Inter>i. a i) \\<in> \\<sigma>_algebra A\"\nproof -\n  assume \"!!i::nat. a i \\<in> \\<sigma>_algebra A\"\n  then have \"!!i::nat. -(a i) \\<in> \\<sigma>_algebra A\" by (rule \\<sigma>_algebra.complement)\n  then have \"(\\<Union>i. -(a i)) \\<in> \\<sigma>_algebra A\" by (rule \\<sigma>_algebra.Union)\n  then have \"-(\\<Union>i. -(a i)) \\<in> \\<sigma>_algebra A\" by (rule \\<sigma>_algebra.complement)\n  also have \"-(\\<Union>i. -(a i)) = (\\<Inter>i. a i)\" by simp\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/Induct/Sigma_Algebra.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681195338728, "lm_q2_score": 0.8221891370573386, "lm_q1q2_score": 0.7052476299948509}}
{"text": "(*  Title:      Well-Quasi-Orders\n    Author:     Christian Sternagel <c.sternagel@gmail.com>\n    Maintainer: Christian Sternagel\n    License:    LGPL\n*)\n\nsection \\<open>Minimal elements of sets w.r.t. a well-founded and transitive relation\\<close>\n\ntheory Minimal_Elements\nimports\n  Infinite_Sequences\n  Open_Induction.Restricted_Predicates\nbegin\n\nlocale minimal_element =\n  fixes P A\n  assumes po: \"po_on P A\"\n    and wf: \"wfp_on P A\"\nbegin\n\ndefinition \"min_elt B = (SOME x. x \\<in> B \\<and> (\\<forall>y \\<in> A. P y x \\<longrightarrow> y \\<notin> B))\"\n\nlemma minimal:\n  assumes \"x \\<in> A\" and \"Q x\"\n  shows \"\\<exists>y \\<in> A. P\\<^sup>=\\<^sup>= y x \\<and> Q y \\<and> (\\<forall>z \\<in> A. P z y \\<longrightarrow> \\<not> Q z)\"\nusing wf and assms\nproof (induction rule: wfp_on_induct)\n  case (less x)\n  then show ?case\n  proof (cases \"\\<forall>y \\<in> A. P y x \\<longrightarrow> \\<not> Q y\")\n    case True\n    with less show ?thesis by blast\n  next\n    case False\n    then obtain y where \"y \\<in> A\" and \"P y x\" and \"Q y\" by blast\n    with less show ?thesis\n      using po [THEN po_on_imp_transp_on, unfolded transp_on_def, rule_format, of _ y x] by blast\n  qed\nqed\n\nlemma min_elt_ex:\n  assumes \"B \\<subseteq> A\" and \"B \\<noteq> {}\"\n  shows \"\\<exists>x. x \\<in> B \\<and> (\\<forall>y \\<in> A. P y x \\<longrightarrow> y \\<notin> B)\"\nusing assms using minimal [of _ \"\\<lambda>x. x \\<in> B\"] by auto\n\nlemma min_elt_mem:\n  assumes \"B \\<subseteq> A\" and \"B \\<noteq> {}\"\n  shows \"min_elt B \\<in> B\"\nusing someI_ex [OF min_elt_ex [OF assms]] by (auto simp: min_elt_def)\n\nlemma min_elt_minimal:\n  assumes *: \"B \\<subseteq> A\" \"B \\<noteq> {}\"\n  assumes \"y \\<in> A\" and \"P y (min_elt B)\"\n  shows \"y \\<notin> B\"\nusing someI_ex [OF min_elt_ex [OF *]] and assms by (auto simp: min_elt_def)\n\ntext \\<open>A lexicographically minimal sequence w.r.t.\\ a given set of sequences \\<open>C\\<close>\\<close>\nfun lexmin\nwhere\n  lexmin: \"lexmin C i = min_elt (ith (eq_upto C (lexmin C) i) i)\"\ndeclare lexmin [simp del]\n\nlemma eq_upto_lexmin_non_empty:\n  assumes \"C \\<subseteq> SEQ A\" and \"C \\<noteq> {}\"\n  shows \"eq_upto C (lexmin C) i \\<noteq> {}\"\nproof (induct i)\n  case 0\n  show ?case using assms by auto\nnext\n  let ?A = \"\\<lambda>i. ith (eq_upto C (lexmin C) i) i\"\n  case (Suc i)\n  then have \"?A i \\<noteq> {}\" by force\n  moreover have \"eq_upto C (lexmin C) i \\<subseteq> eq_upto C (lexmin C) 0\" by auto\n  ultimately have \"?A i \\<subseteq> A\" and \"?A i \\<noteq> {}\" using assms by (auto simp: ith_def)\n  from min_elt_mem [OF this, folded lexmin]\n    obtain f where \"f \\<in> eq_upto C (lexmin C) (Suc i)\" by (auto dest: eq_upto_Suc)\n  then show ?case by blast\nqed\n\nlemma lexmin_SEQ_mem:\n  assumes \"C \\<subseteq> SEQ A\" and \"C \\<noteq> {}\"\n  shows \"lexmin C \\<in> SEQ A\"\nproof -\n  { fix i\n    let ?X = \"ith (eq_upto C (lexmin C) i) i\"\n    have \"?X \\<subseteq> A\" using assms by (auto simp: ith_def)\n    moreover have \"?X \\<noteq> {}\" using eq_upto_lexmin_non_empty [OF assms] by auto\n    ultimately have \"lexmin C i \\<in> A\" using min_elt_mem [of ?X] by (subst lexmin) blast }\n  then show ?thesis by auto\nqed\n\nlemma non_empty_ith:\n  assumes \"C \\<subseteq> SEQ A\" and \"C \\<noteq> {}\"\n  shows \"ith (eq_upto C (lexmin C) i) i \\<subseteq> A\"\n  and \"ith (eq_upto C (lexmin C) i) i \\<noteq> {}\"\nusing eq_upto_lexmin_non_empty [OF assms, of i] and assms by (auto simp: ith_def)\n\nlemma lexmin_minimal:\n  \"C \\<subseteq> SEQ A \\<Longrightarrow> C \\<noteq> {} \\<Longrightarrow> y \\<in> A \\<Longrightarrow> P y (lexmin C i) \\<Longrightarrow> y \\<notin> ith (eq_upto C (lexmin C) i) i\"\nusing min_elt_minimal [OF non_empty_ith, folded lexmin] .\n\nlemma lexmin_mem:\n  \"C \\<subseteq> SEQ A \\<Longrightarrow> C \\<noteq> {} \\<Longrightarrow> lexmin C i \\<in> ith (eq_upto C (lexmin C) i) i\"\nusing min_elt_mem [OF non_empty_ith, folded lexmin] .\n\nlemma LEX_chain_on_eq_upto_imp_ith_chain_on:\n  assumes \"chain_on (LEX P) (eq_upto C f i) (SEQ A)\"\n  shows \"chain_on P (ith (eq_upto C f i) i) A\"\nusing assms\nproof -\n  { fix x y assume \"x \\<in> ith (eq_upto C f i) i\" and \"y \\<in> ith (eq_upto C f i) i\"\n      and \"\\<not> P x y\" and \"y \\<noteq> x\"\n    then obtain g h where *: \"g \\<in> eq_upto C f i\" \"h \\<in> eq_upto C f i\"\n      and [simp]: \"x = g i\" \"y = h i\" and eq: \"\\<forall>j<i. g j = f j \\<and> h j = f j\"\n      by (auto simp: ith_def eq_upto_def)\n    with assms and \\<open>y \\<noteq> x\\<close> consider \"LEX P g h\" | \"LEX P h g\" by (force simp: chain_on_def)\n    then have \"P y x\"\n    proof (cases)\n      assume \"LEX P g h\"\n      with eq and \\<open>y \\<noteq> x\\<close> have \"P x y\" using assms and *\n        by (auto simp: LEX_def)\n           (metis SEQ_iff chain_on_imp_subset linorder_neqE_nat minimal subsetCE)\n      with \\<open>\\<not> P x y\\<close> show \"P y x\" ..\n    next\n      assume \"LEX P h g\"\n      with eq and \\<open>y \\<noteq> x\\<close> show \"P y x\" using assms and *\n        by (auto simp: LEX_def)\n           (metis SEQ_iff chain_on_imp_subset linorder_neqE_nat minimal subsetCE)\n    qed }\n  then show ?thesis using assms by (auto simp: chain_on_def) blast\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/Well_Quasi_Orders/Minimal_Elements.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891305219504, "lm_q2_score": 0.857768108626046, "lm_q1q2_score": 0.7052476154207067}}
{"text": "(* Title:      Models of Kleene Algebra\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>Models of Kleene Algebras\\<close>\n\ntheory Kleene_Algebra_Models\nimports Kleene_Algebra Dioid_Models\nbegin\n\ntext \\<open>We now show that most of the models considered for dioids are\nalso Kleene algebras. Some of the dioid models cannot be expanded, for\ninstance max-plus and min-plus semirings, but we do not formalise this\nfact. We also currently do not show that formal powerseries and\nmatrices form Kleene algebras.\n\nThe interpretation proofs for some of the following models are quite\nsimilar. One could, perhaps, abstract out common reasoning in the\nfuture.\\<close>\n\nsubsection \\<open>Preliminary Lemmas\\<close>\n\ntext \\<open>We first prove two induction-style statements for dioids that\nare useful for establishing the full induction laws. In the future\nthese will live in a theory file on finite sums for Kleene\nalgebras.\\<close>\n\ncontext dioid_one_zero\nbegin\n\nlemma power_inductl: \"z + x \\<cdot> y \\<le> y \\<Longrightarrow> (x ^ n) \\<cdot> z \\<le> y\"\nproof (induct n)\n  case 0 show ?case\n    using \"0.prems\" by auto\n  case Suc thus ?case\n    by (auto, metis mult.assoc mult_isol order_trans)\nqed\n\nlemma power_inductr: \"z + y \\<cdot> x \\<le> y \\<Longrightarrow> z \\<cdot> (x ^ n) \\<le> y\"\nproof (induct n)\n  case 0 show ?case\n    using \"0.prems\" by auto\n  case Suc\n  {\n    fix n\n    assume \"z + y \\<cdot> x \\<le> y \\<Longrightarrow> z \\<cdot> x ^ n \\<le> y\"\n      and \"z + y \\<cdot> x \\<le> y\"\n    hence \"z \\<cdot> x ^ n \\<le> y\"\n      by auto\n    also have \"z \\<cdot> x ^ Suc n = z \\<cdot> x \\<cdot> x ^ n\"\n      by (metis mult.assoc power_Suc)\n    moreover have \"... = (z \\<cdot> x ^ n) \\<cdot> x\"\n      by (metis mult.assoc power_commutes)\n    moreover have \"... \\<le> y \\<cdot> x\"\n      by (metis calculation(1) mult_isor)\n    moreover have \"... \\<le> y\"\n      using \\<open>z + y \\<cdot> x \\<le> y\\<close> by auto\n    ultimately have \"z \\<cdot> x ^ Suc n \\<le> y\" by auto\n  }\n  thus ?case\n    by (metis Suc)\nqed\n\nend (* dioid_one_zero *)\n\n\nsubsection \\<open>The Powerset Kleene Algebra over a Monoid\\<close>\n\ntext \\<open>We now show that the powerset dioid forms a Kleene\nalgebra. The Kleene star is defined as in language theory.\\<close>\n\nlemma Un_0_Suc: \"(\\<Union>n. f n) = f 0 \\<union> (\\<Union>n. f (Suc n))\"\nby auto (metis not0_implies_Suc)\n\ninstantiation set :: (monoid_mult) kleene_algebra\nbegin\n\n  definition star_def: \"X\\<^sup>\\<star> = (\\<Union>n. X ^ n)\"\n\n  lemma star_elim: \"x \\<in> X\\<^sup>\\<star> \\<longleftrightarrow> (\\<exists>k. x \\<in> X ^ k)\"\n  by (simp add: star_def)\n\n  lemma star_contl: \"X \\<cdot> Y\\<^sup>\\<star> = (\\<Union>n. X \\<cdot> Y ^ n)\"\n  by (auto simp add: star_elim c_prod_def)\n\n  lemma star_contr: \"X\\<^sup>\\<star> \\<cdot> Y = (\\<Union>n. X ^ n \\<cdot> Y)\"\n  by (auto simp add: star_elim c_prod_def)\n\n  instance\n  proof\n    fix X Y Z :: \"'a set\"\n    show \"1 + X \\<cdot> X\\<^sup>\\<star> \\<subseteq> X\\<^sup>\\<star>\"\n    proof -\n      have \"1 + X \\<cdot> X\\<^sup>\\<star> = (X ^ 0) \\<union> (\\<Union>n. X ^ (Suc n))\"\n        by (auto simp add: star_def c_prod_def plus_set_def one_set_def)\n      also have \"... = (\\<Union>n. X ^ n)\"\n        by (metis Un_0_Suc)\n      also have \"... = X\\<^sup>\\<star>\"\n        by (simp only: star_def)\n      finally show ?thesis\n        by (metis subset_refl)\n    qed\n  next\n    fix X Y Z :: \"'a set\"\n    assume hyp: \"Z + X \\<cdot> Y \\<subseteq> Y\"\n    show  \"X\\<^sup>\\<star> \\<cdot> Z \\<subseteq> Y\"\n      by (simp add: star_contr SUP_le_iff) (meson hyp dioid_one_zero_class.power_inductl)\n  next\n    fix X Y Z :: \"'a set\"\n    assume hyp: \"Z + Y \\<cdot> X \\<subseteq> Y\"\n    show  \"Z \\<cdot> X\\<^sup>\\<star> \\<subseteq> Y\"\n      by (simp add: star_contl SUP_le_iff) (meson dioid_one_zero_class.power_inductr hyp) \n  qed\n\nend (* instantiation *)\n\n\nsubsection \\<open>Language Kleene Algebras\\<close>\n\ntext \\<open>We now specialise this fact to languages.\\<close>\n\ninterpretation lan_kleene_algebra: kleene_algebra \"(+)\" \"(\\<cdot>)\" \"1::'a lan\" \"0\" \"(\\<subseteq>)\" \"(\\<subset>)\" star ..\n\n\nsubsection \\<open>Regular Languages\\<close>\n\ntext \\<open>{\\ldots} and further to regular languages. For the sake of\nsimplicity we just copy in the axiomatisation of regular expressions\nby Krauss and Nipkow~\\cite{krauss12regular}.\\<close>\n\ndatatype 'a rexp =\n  Zero\n| One\n| Atom 'a\n| Plus \"'a rexp\" \"'a rexp\"\n| Times \"'a rexp\" \"'a rexp\"\n| Star \"'a rexp\"\n\ntext \\<open>The interpretation map that induces regular languages as the\nimages of regular expressions in the set of languages has also been\nadapted from there.\\<close>\n\nfun lang :: \"'a rexp \\<Rightarrow> 'a lan\" where\n  \"lang Zero = 0\"  \\<comment> \\<open>{}\\<close>\n| \"lang One = 1\"  \\<comment> \\<open>{[]}\\<close>\n| \"lang (Atom a) = {[a]}\"\n| \"lang (Plus x y) = lang x + lang y\"\n| \"lang (Times x y) = lang x \\<cdot> lang y\"\n| \"lang (Star x) = (lang x)\\<^sup>\\<star>\"\n\ntypedef 'a reg_lan = \"range lang :: 'a lan set\"\n  by auto\n\nsetup_lifting type_definition_reg_lan\n\ninstantiation reg_lan :: (type) kleene_algebra\nbegin\n\n  lift_definition star_reg_lan :: \"'a reg_lan \\<Rightarrow> 'a reg_lan\"\n    is star\n    by (metis (hide_lams, no_types) image_iff lang.simps(6) rangeI)\n\n  lift_definition zero_reg_lan :: \"'a reg_lan\"\n    is 0\n    by (metis lang.simps(1) rangeI)\n\n  lift_definition one_reg_lan :: \"'a reg_lan\"\n    is 1\n    by (metis lang.simps(2) rangeI)\n\n  lift_definition less_eq_reg_lan :: \"'a reg_lan \\<Rightarrow> 'a reg_lan \\<Rightarrow> bool\"\n    is less_eq .\n\n  lift_definition less_reg_lan :: \"'a reg_lan \\<Rightarrow> 'a reg_lan \\<Rightarrow> bool\"\n    is less .\n\n  lift_definition plus_reg_lan :: \"'a reg_lan \\<Rightarrow> 'a reg_lan \\<Rightarrow> 'a reg_lan\"\n    is plus\n    by (metis (hide_lams, no_types) image_iff lang.simps(4) rangeI)\n\n  lift_definition times_reg_lan :: \"'a reg_lan \\<Rightarrow> 'a reg_lan \\<Rightarrow> 'a reg_lan\"\n    is times\n    by (metis (hide_lams, no_types) image_iff lang.simps(5) rangeI)\n\n  instance\n  proof\n    fix x y z :: \"'a reg_lan\"\n    show \"x + y + z = x + (y + z)\"\n      by transfer (metis join_semilattice_class.add_assoc')\n    show \"x + y = y + x\"\n      by transfer (metis join_semilattice_class.add_comm)\n    show \"x \\<cdot> y \\<cdot> z = x \\<cdot> (y \\<cdot> z)\"\n      by transfer (metis semigroup_mult_class.mult.assoc)\n    show \"(x + y) \\<cdot> z = x \\<cdot> z + y \\<cdot> z\"\n      by transfer (metis semiring_class.distrib_right)\n    show \"1 \\<cdot> x = x\"\n      by transfer (metis monoid_mult_class.mult_1_left)\n    show \"x \\<cdot> 1 = x\"\n      by transfer (metis monoid_mult_class.mult_1_right)\n    show \"0 + x = x\"\n      by transfer (metis join_semilattice_zero_class.add_zero_l)\n    show \"0 \\<cdot> x = 0\"\n      by transfer (metis ab_near_semiring_one_zerol_class.annil)\n    show \"x \\<cdot> 0 = 0\"\n      by transfer (metis ab_near_semiring_one_zero_class.annir)\n    show \"x \\<le> y \\<longleftrightarrow> x + y = y\"\n      by transfer (metis plus_ord_class.less_eq_def)\n    show \"x < y \\<longleftrightarrow> x \\<le> y \\<and> x \\<noteq> y\"\n      by transfer (metis plus_ord_class.less_def)\n    show \"x + x = x\"\n      by transfer (metis join_semilattice_class.add_idem)\n    show \"x \\<cdot> (y + z) = x \\<cdot> y + x \\<cdot> z\"\n      by transfer (metis semiring_class.distrib_left)\n    show \"z \\<cdot> x \\<le> z \\<cdot> (x + y)\"\n      by transfer (metis pre_dioid_class.subdistl)\n    show \"1 + x \\<cdot> x\\<^sup>\\<star> \\<le> x\\<^sup>\\<star>\"\n      by transfer (metis star_unfoldl)\n    show \"z + x \\<cdot> y \\<le> y \\<Longrightarrow> x\\<^sup>\\<star> \\<cdot> z \\<le> y\"\n      by transfer (metis star_inductl)\n    show \"z + y \\<cdot> x \\<le> y \\<Longrightarrow> z \\<cdot> x\\<^sup>\\<star> \\<le> y\"\n      by transfer (metis star_inductr)\n  qed\n\nend  (* instantiation *)\n\ninterpretation reg_lan_kleene_algebra: kleene_algebra \"(+)\" \"(\\<cdot>)\" \"1::'a reg_lan\" 0 \"(\\<le>)\" \"(<)\" star ..\n\n\nsubsection \\<open>Relation Kleene Algebras\\<close>\n\ntext \\<open>We now show that binary relations form Kleene algebras. While\nwe could have used the reflexive transitive closure operation as the\nKleene star, we prefer the equivalent definition of the star as the\nsum of powers. This essentially allows us to copy previous proofs.\\<close>\n\nlemma power_is_relpow: \"rel_dioid.power X n = X ^^ n\"\nproof (induct n)\n  case 0 show ?case\n    by (metis rel_dioid.power_0 relpow.simps(1))\n  case Suc thus ?case\n    by (metis rel_dioid.power_Suc2 relpow.simps(2))\nqed\n\nlemma rel_star_def: \"X^* = (\\<Union>n. rel_dioid.power X n)\"\n  by (simp add: power_is_relpow rtrancl_is_UN_relpow)\n\nlemma rel_star_contl: \"X O Y^* = (\\<Union>n. X O rel_dioid.power Y n)\"\nby (metis rel_star_def relcomp_UNION_distrib)\n\nlemma rel_star_contr: \"X^* O Y = (\\<Union>n. (rel_dioid.power X n) O Y)\"\nby (metis rel_star_def relcomp_UNION_distrib2)\n\ninterpretation rel_kleene_algebra: kleene_algebra \"(\\<union>)\" \"(O)\" Id \"{}\" \"(\\<subseteq>)\" \"(\\<subset>)\" rtrancl\nproof\n  fix x y z :: \"'a rel\"\n  show \"Id \\<union> x O x\\<^sup>* \\<subseteq> x\\<^sup>*\"\n    by (metis order_refl r_comp_rtrancl_eq rtrancl_unfold)\nnext\n  fix x y z :: \"'a rel\"\n  assume \"z \\<union> x O y \\<subseteq> y\"\n  thus \"x\\<^sup>* O z \\<subseteq> y\"\n    by (simp only: rel_star_contr, metis (lifting) SUP_le_iff rel_dioid.power_inductl)\nnext\n  fix x y z :: \"'a rel\"\n  assume \"z \\<union> y O x \\<subseteq> y\"\n  thus \"z O x\\<^sup>* \\<subseteq> y\"\n    by (simp only: rel_star_contl, metis (lifting) SUP_le_iff rel_dioid.power_inductr)\nqed\n\nsubsection \\<open>Trace Kleene Algebras\\<close>\n\ntext \\<open>Again, the proof that sets of traces form Kleene algebras\nfollows the same schema.\\<close>\n\ndefinition t_star :: \"('p, 'a) trace set \\<Rightarrow> ('p, 'a) trace set\" where\n  \"t_star X \\<equiv> \\<Union>n. trace_dioid.power X n\"\n\nlemma t_star_elim: \"x \\<in> t_star X \\<longleftrightarrow> (\\<exists>n. x \\<in> trace_dioid.power X n)\"\n  by (simp add: t_star_def)\n\nlemma t_star_contl: \"t_prod X (t_star Y) = (\\<Union>n. t_prod X (trace_dioid.power Y n))\"\n  by (auto simp add: t_star_elim t_prod_def)\n\nlemma t_star_contr: \"t_prod (t_star X) Y = (\\<Union>n. t_prod (trace_dioid.power X n) Y)\"\n  by (auto simp add: t_star_elim t_prod_def)\n\ninterpretation trace_kleene_algebra: kleene_algebra \"(\\<union>)\" t_prod t_one t_zero \"(\\<subseteq>)\" \"(\\<subset>)\" t_star\nproof\n  fix X Y Z :: \"('a, 'b) trace set\"\n  show \"t_one \\<union> t_prod X (t_star X) \\<subseteq> t_star X\"\n    proof -\n      have \"t_one \\<union> t_prod X (t_star X) = (trace_dioid.power X 0) \\<union> (\\<Union>n. trace_dioid.power X (Suc n))\"\n        by (auto simp add: t_star_def t_prod_def)\n      also have \"... = (\\<Union>n. trace_dioid.power X n)\"\n        by (metis Un_0_Suc)\n      also have \"... = t_star X\"\n        by (metis t_star_def)\n      finally show ?thesis\n        by (metis subset_refl)\n    qed\n  show \"Z \\<union> t_prod X Y \\<subseteq> Y \\<Longrightarrow> t_prod (t_star X) Z \\<subseteq> Y\"\n    by (simp only: ball_UNIV t_star_contr SUP_le_iff) (metis trace_dioid.power_inductl)\n  show \"Z \\<union> t_prod Y X \\<subseteq> Y \\<Longrightarrow> t_prod Z (t_star X) \\<subseteq> Y\"\n    by (simp only: ball_UNIV t_star_contl SUP_le_iff) (metis trace_dioid.power_inductr)\nqed\n\n\nsubsection \\<open>Path Kleene Algebras\\<close>\n\ntext \\<open>We start with paths that include the empty path.\\<close>\n\ndefinition p_star :: \"'a path set \\<Rightarrow> 'a path set\" where\n  \"p_star X \\<equiv> \\<Union>n. path_dioid.power X n\"\n\nlemma p_star_elim: \"x \\<in> p_star X \\<longleftrightarrow> (\\<exists>n. x \\<in> path_dioid.power X n)\"\nby (simp add: p_star_def)\n\nlemma p_star_contl: \"p_prod X (p_star Y) = (\\<Union>n. p_prod X (path_dioid.power Y n))\"\napply (auto simp add: p_prod_def p_star_elim)\n   apply (metis p_fusion.simps(1))\n  apply metis\n apply (metis p_fusion.simps(1) p_star_elim)\napply (metis p_star_elim)\ndone\n\nlemma p_star_contr: \"p_prod (p_star X) Y = (\\<Union>n. p_prod (path_dioid.power X n) Y)\"\napply (auto simp add: p_prod_def p_star_elim)\n   apply (metis p_fusion.simps(1))\n  apply metis\n apply (metis p_fusion.simps(1) p_star_elim)\napply (metis p_star_elim)\ndone\n\ninterpretation path_kleene_algebra: kleene_algebra \"(\\<union>)\" p_prod p_one \"{}\" \"(\\<subseteq>)\" \"(\\<subset>)\" p_star\nproof\n  fix X Y Z :: \"'a path set\"\n  show \"p_one \\<union> p_prod X (p_star X) \\<subseteq> p_star X\"\n    proof -\n      have \"p_one \\<union> p_prod X (p_star X) = (path_dioid.power X 0) \\<union> (\\<Union>n. path_dioid.power X (Suc n))\"\n        by (auto simp add: p_star_def p_prod_def)\n      also have \"... = (\\<Union>n. path_dioid.power X n)\"\n        by (metis Un_0_Suc)\n      also have \"... = p_star X\"\n        by (metis p_star_def)\n      finally show ?thesis\n        by (metis subset_refl)\n    qed\n  show \"Z \\<union> p_prod X Y \\<subseteq> Y \\<Longrightarrow> p_prod (p_star X) Z \\<subseteq> Y\"\n    by (simp only: ball_UNIV p_star_contr SUP_le_iff) (metis path_dioid.power_inductl)\n  show \"Z \\<union> p_prod Y X \\<subseteq> Y \\<Longrightarrow> p_prod Z (p_star X) \\<subseteq> Y\"\n    by (simp only: ball_UNIV p_star_contl SUP_le_iff) (metis path_dioid.power_inductr)\nqed\n\ntext \\<open>We now consider a notion of paths that does not include the\nempty path.\\<close>\n\ndefinition pp_star :: \"'a ppath set \\<Rightarrow> 'a ppath set\" where\n  \"pp_star X \\<equiv> \\<Union>n. ppath_dioid.power X n\"\n\nlemma pp_star_elim: \"x \\<in> pp_star X \\<longleftrightarrow> (\\<exists>n. x \\<in> ppath_dioid.power X n)\"\nby (simp add: pp_star_def)\n\nlemma pp_star_contl: \"pp_prod X (pp_star Y) = (\\<Union>n. pp_prod X (ppath_dioid.power Y n))\"\nby (auto simp add: pp_prod_def pp_star_elim)\n\nlemma pp_star_contr: \"pp_prod (pp_star X) Y = (\\<Union>n. pp_prod (ppath_dioid.power X n) Y)\"\nby (auto simp add: pp_prod_def pp_star_elim)\n\ninterpretation ppath_kleene_algebra: kleene_algebra \"(\\<union>)\" pp_prod pp_one \"{}\" \"(\\<subseteq>)\" \"(\\<subset>)\" pp_star\nproof\n  fix X Y Z :: \"'a ppath set\"\n  show \"pp_one \\<union> pp_prod X (pp_star X) \\<subseteq> pp_star X\"\n    proof -\n      have \"pp_one \\<union> pp_prod X (pp_star X) = (ppath_dioid.power X 0) \\<union> (\\<Union>n. ppath_dioid.power X (Suc n))\"\n        by (auto simp add: pp_star_def pp_prod_def)\n      also have \"... = (\\<Union>n. ppath_dioid.power X n)\"\n        by (metis Un_0_Suc)\n      also have \"... = pp_star X\"\n        by (metis pp_star_def)\n      finally show ?thesis\n        by (metis subset_refl)\n    qed\n  show \"Z \\<union> pp_prod X Y \\<subseteq> Y \\<Longrightarrow> pp_prod (pp_star X) Z \\<subseteq> Y\"\n    by (simp only: ball_UNIV pp_star_contr SUP_le_iff) (metis ppath_dioid.power_inductl)\n  show \"Z \\<union> pp_prod Y X \\<subseteq> Y \\<Longrightarrow> pp_prod Z (pp_star X) \\<subseteq> Y\"\n    by (simp only: ball_UNIV pp_star_contl SUP_le_iff) (metis ppath_dioid.power_inductr)\nqed\n\n\nsubsection \\<open>The Distributive Lattice Kleene Algebra\\<close>\n\ntext \\<open>In the case of bounded distributive lattices, the star maps\nall elements to to the maximal element.\\<close>\n\ndefinition (in bounded_distributive_lattice) bdl_star :: \"'a \\<Rightarrow> 'a\" where\n  \"bdl_star x = top\"\n\nsublocale bounded_distributive_lattice \\<subseteq> kleene_algebra sup inf top bot less_eq less bdl_star\nproof\n  fix x y z :: 'a\n  show \"sup top (inf x (bdl_star x)) \\<le> bdl_star x\"\n    by (simp add: bdl_star_def)\n  show \"sup z (inf x y) \\<le> y \\<Longrightarrow> inf (bdl_star x) z \\<le> y\"\n    by (simp add: bdl_star_def)\n  show \"sup z (inf y x) \\<le> y \\<Longrightarrow> inf z (bdl_star x) \\<le> y\"\n    by (simp add: bdl_star_def)\nqed\n\n\nsubsection \\<open>The Min-Plus Kleene Algebra\\<close>\n\ntext \\<open>One cannot define a Kleene star for max-plus and min-plus\nalgebras that range over the real numbers. Here we define the star for\na min-plus algebra restricted to natural numbers and~$+\\infty$. The\nresulting Kleene algebra is commutative. Similar variants can be\nobtained for max-plus algebras and other algebras ranging over the\npositive or negative integers.\\<close>\n\ninstantiation pnat :: commutative_kleene_algebra\nbegin\n\n  definition star_pnat where\n    \"x\\<^sup>\\<star> \\<equiv> (1::pnat)\"\n\n  instance\n  proof\n    fix x y z :: pnat\n    show \"1 + x \\<cdot> x\\<^sup>\\<star> \\<le> x\\<^sup>\\<star>\"\n      by (metis star_pnat_def zero_pnat_top)\n    show \"z + x \\<cdot> y \\<le> y \\<Longrightarrow> x\\<^sup>\\<star> \\<cdot> z \\<le> y\"\n      by (simp add: star_pnat_def)\n    show \"z + y \\<cdot> x \\<le> y \\<Longrightarrow> z \\<cdot> x\\<^sup>\\<star> \\<le> y\"\n      by (simp add: star_pnat_def)\n    show \"x \\<cdot> y = y \\<cdot> x\"\n      unfolding times_pnat_def by (cases x, cases y, simp_all)\n  qed\n\nend (* instantiation *)\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/Kleene_Algebra_Models.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8221891305219504, "lm_q2_score": 0.8577681013541613, "lm_q1q2_score": 0.7052476094418421}}
{"text": "(*    Title:              SATSolver/CNF.thy\n      Author:             Filip Maric\n      Maintainer:         Filip Maric <filip at matf.bg.ac.yu>\n*)\n\nsection \\<open>CNF\\<close>\ntheory CNF\nimports MoreList\nbegin\ntext\\<open>Theory describing formulae in Conjunctive Normal Form.\\<close>\n\n\n(********************************************************************)\nsubsection\\<open>Syntax\\<close>\n(********************************************************************)\n\n(*------------------------------------------------------------------*)\nsubsubsection\\<open>Basic datatypes\\<close>\ntype_synonym Variable  = nat\ndatatype Literal = Pos Variable | Neg Variable\ntype_synonym Clause = \"Literal list\"\ntype_synonym Formula = \"Clause list\"\n\ntext\\<open>Notice that instead of set or multisets, lists are used in\ndefinitions of clauses and formulae. This is done because SAT solver\nimplementation usually use list-like data structures for representing\nthese datatypes.\\<close>\n\n(*------------------------------------------------------------------*)\nsubsubsection\\<open>Membership\\<close>\n\ntext\\<open>Check if the literal is member of a clause, clause is a member \n  of a formula or the literal is a member of a formula\\<close>\nconsts member  :: \"'a \\<Rightarrow> 'b \\<Rightarrow> bool\" (infixl \"el\" 55)\n\noverloading literalElClause \\<equiv> \"member :: Literal \\<Rightarrow> Clause \\<Rightarrow> bool\"\nbegin\n  definition [simp]: \"((literal::Literal) el (clause::Clause)) == literal \\<in> set clause\"\nend\n\noverloading clauseElFormula \\<equiv> \"member :: Clause \\<Rightarrow> Formula \\<Rightarrow> bool\"\nbegin\n  definition [simp]: \"((clause::Clause) el (formula::Formula)) == clause \\<in> set formula\"\nend\n\noverloading el_literal \\<equiv> \"(el) :: Literal \\<Rightarrow> Formula \\<Rightarrow> bool\"\nbegin\n\nprimrec el_literal where\n\"(literal::Literal) el ([]::Formula) = False\" |\n\"((literal::Literal) el ((clause # formula)::Formula)) = ((literal el clause) \\<or> (literal el formula))\"\n\nend\n\nlemma literalElFormulaCharacterization:\n  fixes literal :: Literal and formula :: Formula\n  shows \"(literal el formula) = (\\<exists> (clause::Clause). clause el formula \\<and> literal el clause)\"\nby (induct formula) auto\n\n\n(*------------------------------------------------------------------*)\nsubsubsection\\<open>Variables\\<close>\n\ntext\\<open>The variable of a given literal\\<close>\nprimrec \nvar      :: \"Literal \\<Rightarrow> Variable\"\nwhere \n  \"var (Pos v) = v\"\n| \"var (Neg v) = v\"\n\ntext\\<open>Set of variables of a given clause, formula or valuation\\<close>\nprimrec\nvarsClause :: \"(Literal list) \\<Rightarrow> (Variable set)\"\nwhere\n  \"varsClause [] = {}\"\n| \"varsClause (literal # list) = {var literal} \\<union> (varsClause list)\"\n\nprimrec\nvarsFormula :: \"Formula \\<Rightarrow> (Variable set)\"\nwhere\n  \"varsFormula [] = {}\"\n| \"varsFormula (clause # formula) = (varsClause clause) \\<union> (varsFormula formula)\"\n\nconsts vars :: \"'a \\<Rightarrow> Variable set\"\n\noverloading vars_clause \\<equiv> \"vars :: Clause \\<Rightarrow> Variable set\"\nbegin\n  definition [simp]: \"vars (clause::Clause) == varsClause clause\"\nend\n\noverloading vars_formula \\<equiv> \"vars :: Formula \\<Rightarrow> Variable set\"\nbegin\n  definition [simp]: \"vars (formula::Formula) == varsFormula formula\"\nend\n\noverloading vars_set \\<equiv> \"vars :: Literal set \\<Rightarrow> Variable set\"\nbegin\n  definition [simp]: \"vars (s::Literal set) == {vbl. \\<exists> l. l \\<in> s \\<and> var l = vbl}\"\nend\n\nlemma clauseContainsItsLiteralsVariable: \n  fixes literal :: Literal and clause :: Clause\n  assumes \"literal el clause\"\n  shows \"var literal \\<in> vars clause\"\nusing assms\nby (induct clause) auto\n\nlemma formulaContainsItsLiteralsVariable:\n  fixes literal :: Literal and formula::Formula\n  assumes \"literal el formula\" \n  shows \"var literal \\<in> vars formula\"\nusing assms\nproof (induct formula)\n  case Nil\n  thus ?case \n    by simp\nnext\n  case (Cons clause formula)\n  thus ?case\n  proof (cases \"literal el clause\")\n    case True\n    with clauseContainsItsLiteralsVariable\n    have \"var literal \\<in> vars clause\" \n      by simp\n    thus ?thesis \n      by simp\n  next\n    case False\n    with Cons\n    show ?thesis \n      by simp\n  qed\nqed\n\nlemma formulaContainsItsClausesVariables:\n  fixes clause :: Clause and formula :: Formula\n  assumes \"clause el formula\"\n  shows \"vars clause \\<subseteq> vars formula\"\nusing assms\nby (induct formula) auto\n\nlemma varsAppendFormulae:\n  fixes formula1 :: Formula and formula2 :: Formula\n  shows \"vars (formula1 @ formula2) = vars formula1 \\<union> vars formula2\"\nby (induct formula1) auto\n\nlemma varsAppendClauses:\n  fixes clause1 :: Clause and clause2 :: Clause\n  shows \"vars (clause1 @ clause2) = vars clause1 \\<union> vars clause2\"\nby (induct clause1) auto\n\nlemma varsRemoveLiteral:\n  fixes literal :: Literal and clause :: Clause\n  shows \"vars (removeAll literal clause) \\<subseteq> vars clause\"\nby (induct clause) auto\n\nlemma varsRemoveLiteralSuperset:\n  fixes literal :: Literal and clause :: Clause\n  shows \"vars clause - {var literal}  \\<subseteq> vars (removeAll literal clause)\"\nby (induct clause) auto\n\nlemma varsRemoveAllClause:\n  fixes clause :: Clause and formula :: Formula\n  shows \"vars (removeAll clause formula) \\<subseteq> vars formula\"\nby (induct formula) auto\n\nlemma varsRemoveAllClauseSuperset:\n  fixes clause :: Clause and formula :: Formula\n  shows \"vars formula - vars clause \\<subseteq> vars (removeAll clause formula)\"\nby (induct formula) auto\n\nlemma varInClauseVars:\n  fixes variable :: Variable and clause :: Clause\n  shows \"variable \\<in> vars clause = (\\<exists> literal. literal el clause \\<and> var literal = variable)\"\nby (induct clause) auto\n\nlemma varInFormulaVars: \n  fixes variable :: Variable and formula :: Formula\n  shows \"variable \\<in> vars formula = (\\<exists> literal. literal el formula \\<and> var literal = variable)\" (is \"?lhs formula = ?rhs formula\")\nproof (induct formula)\n  case Nil\n  show ?case \n    by simp\nnext\n  case (Cons clause formula)\n  show ?case\n  proof\n    assume P: \"?lhs (clause # formula)\"\n    thus \"?rhs (clause # formula)\"\n    proof (cases \"variable \\<in> vars clause\")\n      case True\n      with varInClauseVars \n      have \"\\<exists> literal. literal el clause \\<and> var literal = variable\" \n        by simp\n      thus ?thesis \n        by auto\n    next\n      case False\n      with P \n      have \"variable \\<in> vars formula\" \n        by simp\n      with Cons\n      show ?thesis \n        by auto\n    qed\n  next\n    assume \"?rhs (clause # formula)\"\n    then obtain l \n      where lEl: \"l el clause # formula\" and varL:\"var l = variable\" \n      by auto\n    from lEl formulaContainsItsLiteralsVariable [of \"l\" \"clause # formula\"] \n    have \"var l \\<in> vars (clause # formula)\" \n      by auto\n    with varL \n    show \"?lhs (clause # formula)\" \n      by simp\n  qed\nqed\n\nlemma varsSubsetFormula:\n  fixes F :: Formula and F' :: Formula\n  assumes \"\\<forall> c::Clause. c el F \\<longrightarrow> c el F'\"\n  shows \"vars F \\<subseteq> vars F'\"\nusing assms\nproof (induct F)\n  case Nil\n  thus ?case\n    by simp\nnext\n  case (Cons c' F'')\n  thus ?case\n    using formulaContainsItsClausesVariables[of \"c'\" \"F'\"]\n    by simp\nqed\n\nlemma varsClauseVarsSet:\nfixes \n  clause :: Clause\nshows\n  \"vars clause = vars (set clause)\"\nby (induct clause) auto\n\n\n(*------------------------------------------------------------------*)\nsubsubsection\\<open>Opposite literals\\<close>\n\nprimrec\nopposite :: \"Literal \\<Rightarrow> Literal\"\nwhere\n  \"opposite (Pos v) = (Neg v)\"\n| \"opposite (Neg v) = (Pos v)\"\n\nlemma oppositeIdempotency [simp]:\n  fixes literal::Literal\n  shows \"opposite (opposite literal) = literal\"\nby (induct literal) auto\n\nlemma oppositeSymmetry [simp]:\n  fixes literal1::Literal and literal2::Literal\n  shows \"(opposite literal1 = literal2) = (opposite literal2 = literal1)\"\nby auto\n\nlemma oppositeUniqueness [simp]:\n  fixes literal1::Literal and literal2::Literal\n  shows \"(opposite literal1 = opposite literal2) = (literal1 = literal2)\"\nproof\n  assume \"opposite literal1 = opposite literal2\"\n  hence \"opposite (opposite literal1) = opposite (opposite literal2)\" \n    by simp\n  thus \"literal1 = literal2\" \n    by simp \nqed simp\n\nlemma oppositeIsDifferentFromLiteral [simp]:\n  fixes literal::Literal\n  shows \"opposite literal \\<noteq> literal\"\nby (induct literal) auto\n\nlemma oppositeLiteralsHaveSameVariable [simp]:\n  fixes literal::Literal\n  shows \"var (opposite literal) = var literal\"\nby (induct literal) auto\n\nlemma literalsWithSameVariableAreEqualOrOpposite:\n  fixes literal1::Literal and literal2::Literal\n  shows \"(var literal1 = var literal2) = (literal1 = literal2 \\<or> opposite literal1 = literal2)\" (is \"?lhs = ?rhs\")\nproof\n  assume ?lhs\n  show ?rhs\n  proof (cases literal1)\n    case \"Pos\"\n    note Pos1 = this\n    show ?thesis\n    proof (cases literal2)\n      case \"Pos\"\n      with \\<open>?lhs\\<close> Pos1 show ?thesis \n        by simp\n    next\n      case \"Neg\"\n      with \\<open>?lhs\\<close> Pos1 show ?thesis \n        by simp\n    qed\n  next\n    case \"Neg\"\n    note Neg1 = this\n    show ?thesis\n    proof (cases literal2)\n      case \"Pos\"\n      with \\<open>?lhs\\<close> Neg1 show ?thesis \n        by simp\n    next\n      case \"Neg\"\n      with \\<open>?lhs\\<close> Neg1 show ?thesis \n        by simp\n    qed\n  qed\nnext\n  assume ?rhs\n  thus ?lhs \n    by auto\nqed\n\ntext\\<open>The list of literals obtained by negating all literals of a\nliteral list (clause, valuation). Notice that this is not a negation \nof a clause, because the negation of a clause is a conjunction and \nnot a disjunction.\\<close>\ndefinition\noppositeLiteralList :: \"Literal list \\<Rightarrow> Literal list\"\nwhere\n\"oppositeLiteralList clause == map opposite clause\"\n\nlemma literalElListIffOppositeLiteralElOppositeLiteralList: \n  fixes literal :: Literal and literalList :: \"Literal list\"\n  shows \"literal el literalList = (opposite literal) el (oppositeLiteralList literalList)\"\nunfolding oppositeLiteralList_def\nproof (induct literalList)\n  case Nil\n  thus ?case\n    by simp\nnext\n  case (Cons l literalLlist')\n  show ?case\n  proof (cases \"l = literal\")\n    case True\n    thus ?thesis\n      by simp\n  next\n    case False\n    thus ?thesis\n      by auto\n  qed\nqed\n\nlemma oppositeLiteralListIdempotency [simp]: \n  fixes literalList :: \"Literal list\"\n  shows \"oppositeLiteralList (oppositeLiteralList literalList) = literalList\"\nunfolding oppositeLiteralList_def\nby (induct literalList) auto\n\nlemma oppositeLiteralListRemove: \n  fixes literal :: Literal and literalList :: \"Literal list\"\n  shows \"oppositeLiteralList (removeAll literal literalList) = removeAll (opposite literal) (oppositeLiteralList literalList)\"\nunfolding oppositeLiteralList_def\nby (induct literalList) auto\n\nlemma oppositeLiteralListNonempty:\n  fixes literalList :: \"Literal list\"\n  shows \"(literalList \\<noteq> []) = ((oppositeLiteralList literalList) \\<noteq> [])\"\nunfolding oppositeLiteralList_def\nby (induct literalList) auto\n\nlemma varsOppositeLiteralList:\nshows \"vars (oppositeLiteralList clause) = vars clause\"\nunfolding oppositeLiteralList_def\nby (induct clause) auto\n\n\n(*------------------------------------------------------------------*)\nsubsubsection\\<open>Tautological clauses\\<close>\n\ntext\\<open>Check if the clause contains both a literal and its opposite\\<close>\nprimrec\nclauseTautology :: \"Clause \\<Rightarrow> bool\"\nwhere\n  \"clauseTautology [] = False\"\n| \"clauseTautology (literal # clause) = (opposite literal el clause \\<or> clauseTautology clause)\"\n\nlemma clauseTautologyCharacterization: \n  fixes clause :: Clause\n  shows \"clauseTautology clause = (\\<exists> literal. literal el clause \\<and> (opposite literal) el clause)\"\nby (induct clause) auto\n\n\n(********************************************************************)\nsubsection\\<open>Semantics\\<close>\n(********************************************************************)\n\n(*------------------------------------------------------------------*)\nsubsubsection\\<open>Valuations\\<close>\n\ntype_synonym Valuation = \"Literal list\"\n\nlemma valuationContainsItsLiteralsVariable: \n  fixes literal :: Literal and valuation :: Valuation\n  assumes \"literal el valuation\"\n  shows \"var literal \\<in> vars valuation\"\nusing assms\nby (induct valuation) auto\n\nlemma varsSubsetValuation: \n  fixes valuation1 :: Valuation and valuation2 :: Valuation\n  assumes \"set valuation1  \\<subseteq> set valuation2\"\n  shows \"vars valuation1 \\<subseteq> vars valuation2\"\nusing assms\nproof (induct valuation1)\n  case Nil\n  show ?case \n    by simp\nnext\n  case (Cons literal valuation)\n  note caseCons = this\n  hence \"literal el valuation2\" \n    by auto\n  with valuationContainsItsLiteralsVariable [of \"literal\" \"valuation2\"]\n  have \"var literal \\<in> vars valuation2\" .\n  with caseCons \n  show ?case \n    by simp\nqed\n\nlemma varsAppendValuation:\n  fixes valuation1 :: Valuation and valuation2 :: Valuation\n  shows \"vars (valuation1 @ valuation2) = vars valuation1 \\<union> vars valuation2\"\nby (induct valuation1) auto\nlemma varsPrefixValuation:\n  fixes valuation1 :: Valuation and valuation2 :: Valuation\n  assumes \"isPrefix valuation1 valuation2\"\n  shows \"vars valuation1 \\<subseteq> vars valuation2\"\nproof-\n  from assms \n  have \"set valuation1 \\<subseteq> set valuation2\"\n    by (auto simp add:isPrefix_def)\n  thus ?thesis\n    by (rule varsSubsetValuation)\nqed\n\n(*------------------------------------------------------------------*)\nsubsubsection\\<open>True/False literals\\<close>\n\ntext\\<open>Check if the literal is contained in the given valuation\\<close>\ndefinition literalTrue     :: \"Literal \\<Rightarrow> Valuation \\<Rightarrow> bool\"\nwhere\nliteralTrue_def [simp]: \"literalTrue literal valuation == literal el valuation\"\n\ntext\\<open>Check if the opposite literal is contained in the given valuation\\<close>\ndefinition literalFalse    :: \"Literal \\<Rightarrow> Valuation \\<Rightarrow> bool\"\nwhere\nliteralFalse_def [simp]: \"literalFalse literal valuation == opposite literal el valuation\"\n\n\nlemma variableDefinedImpliesLiteralDefined:\n  fixes literal :: Literal and valuation :: Valuation\n  shows \"var literal \\<in> vars valuation = (literalTrue literal valuation \\<or> literalFalse literal valuation)\" \n    (is \"(?lhs valuation) = (?rhs valuation)\")\nproof\n  assume \"?rhs valuation\"\n  thus \"?lhs valuation\" \n  proof\n    assume \"literalTrue literal valuation\"\n    hence \"literal el valuation\" \n      by simp\n    thus ?thesis\n      using valuationContainsItsLiteralsVariable[of \"literal\" \"valuation\"] \n      by simp\n  next\n    assume \"literalFalse literal valuation\"\n    hence \"opposite literal el valuation\" \n      by simp\n    thus ?thesis\n      using valuationContainsItsLiteralsVariable[of \"opposite literal\" \"valuation\"] \n      by simp\n  qed\nnext\n  assume \"?lhs valuation\" \n  thus \"?rhs valuation\"\n  proof (induct valuation)\n    case Nil\n    thus ?case \n      by simp\n  next\n    case (Cons literal' valuation')\n    note ih=this\n    show ?case\n    proof (cases \"var literal \\<in> vars valuation'\")\n      case True\n      with ih \n      show \"?rhs (literal' # valuation')\" \n        by auto\n    next\n      case False\n      with ih \n      have \"var literal' = var literal\" \n        by simp\n      hence \"literal' = literal \\<or> opposite literal' = literal\"\n        by (simp add:literalsWithSameVariableAreEqualOrOpposite)\n      thus \"?rhs (literal' # valuation')\" \n        by auto\n    qed\n  qed\nqed\n\n(*------------------------------------------------------------------*)\nsubsubsection\\<open>True/False clauses\\<close>\n\ntext\\<open>Check if there is a literal from the clause which is true in the given valuation\\<close>\nprimrec\nclauseTrue      :: \"Clause \\<Rightarrow> Valuation \\<Rightarrow> bool\"\nwhere\n  \"clauseTrue [] valuation = False\"\n| \"clauseTrue (literal # clause) valuation = (literalTrue literal valuation \\<or> clauseTrue clause valuation)\"\n\ntext\\<open>Check if all the literals from the clause are false in the given valuation\\<close>\nprimrec\nclauseFalse     :: \"Clause \\<Rightarrow> Valuation \\<Rightarrow> bool\"\nwhere\n  \"clauseFalse [] valuation = True\"\n| \"clauseFalse (literal # clause) valuation = (literalFalse literal valuation \\<and> clauseFalse clause valuation)\"\n\n\nlemma clauseTrueIffContainsTrueLiteral: \n  fixes clause :: Clause and valuation :: Valuation  \n  shows \"clauseTrue clause valuation = (\\<exists> literal. literal el clause \\<and> literalTrue literal valuation)\"\nby (induct clause) auto\n\nlemma clauseFalseIffAllLiteralsAreFalse:\n  fixes clause :: Clause and valuation :: Valuation  \n  shows \"clauseFalse clause valuation = (\\<forall> literal. literal el clause \\<longrightarrow> literalFalse literal valuation)\"\nby (induct clause) auto\n\nlemma clauseFalseRemove:\n  assumes \"clauseFalse clause valuation\"\n  shows \"clauseFalse (removeAll literal clause) valuation\"\nproof-\n  {\n    fix l::Literal\n    assume \"l el removeAll literal clause\"\n    hence \"l el clause\"\n      by simp\n   with \\<open>clauseFalse clause valuation\\<close> \n   have \"literalFalse l valuation\"\n     by (simp add:clauseFalseIffAllLiteralsAreFalse)\n  }\n  thus ?thesis\n    by (simp add:clauseFalseIffAllLiteralsAreFalse)\nqed\n\nlemma clauseFalseAppendValuation: \n  fixes clause :: Clause and valuation :: Valuation and valuation' :: Valuation\n  assumes \"clauseFalse clause valuation\"\n  shows \"clauseFalse clause (valuation @ valuation')\"\nusing assms\nby (induct clause) auto\n\nlemma clauseTrueAppendValuation:\n  fixes clause :: Clause and valuation :: Valuation and valuation' :: Valuation\n  assumes \"clauseTrue clause valuation\"\n  shows \"clauseTrue clause (valuation @ valuation')\"\nusing assms\nby (induct clause) auto\n\nlemma emptyClauseIsFalse:\n  fixes valuation :: Valuation\n  shows \"clauseFalse [] valuation\"\nby auto\n\nlemma emptyValuationFalsifiesOnlyEmptyClause:\n  fixes clause :: Clause\n  assumes \"clause \\<noteq> []\"\n  shows \"\\<not>  clauseFalse clause []\"\nusing assms\nby (induct clause) auto\n  \n\nlemma valuationContainsItsFalseClausesVariables:\n  fixes clause::Clause and valuation::Valuation\n  assumes \"clauseFalse clause valuation\"\n  shows \"vars clause \\<subseteq> vars valuation\"\nproof\n  fix v::Variable\n  assume \"v \\<in> vars clause\"\n  hence \"\\<exists> l. var l = v \\<and> l el clause\"\n    by (induct clause) auto\n  then obtain l \n    where \"var l = v\" \"l el clause\"\n    by auto\n  from \\<open>l el clause\\<close> \\<open>clauseFalse clause valuation\\<close>\n  have \"literalFalse l valuation\"\n    by (simp add: clauseFalseIffAllLiteralsAreFalse)\n  with \\<open>var l = v\\<close> \n  show \"v \\<in> vars valuation\"\n    using valuationContainsItsLiteralsVariable[of \"opposite l\"]\n    by simp\nqed\n  \n\n(*------------------------------------------------------------------*)\nsubsubsection\\<open>True/False formulae\\<close>\n\ntext\\<open>Check if all the clauses from the formula are false in the given valuation\\<close>\nprimrec\nformulaTrue     :: \"Formula \\<Rightarrow> Valuation \\<Rightarrow> bool\"\nwhere\n  \"formulaTrue [] valuation = True\"\n| \"formulaTrue (clause # formula) valuation = (clauseTrue clause valuation \\<and> formulaTrue formula valuation)\"\n\ntext\\<open>Check if there is a clause from the formula which is false in the given valuation\\<close>\nprimrec\nformulaFalse    :: \"Formula \\<Rightarrow> Valuation \\<Rightarrow> bool\"\nwhere\n  \"formulaFalse [] valuation = False\"\n| \"formulaFalse (clause # formula) valuation = (clauseFalse clause valuation \\<or> formulaFalse formula valuation)\"\n\n\nlemma formulaTrueIffAllClausesAreTrue: \n  fixes formula :: Formula and valuation :: Valuation\n  shows \"formulaTrue formula valuation = (\\<forall> clause. clause el formula \\<longrightarrow> clauseTrue clause valuation)\"\nby (induct formula) auto\n\nlemma formulaFalseIffContainsFalseClause: \n  fixes formula :: Formula and valuation :: Valuation\n  shows \"formulaFalse formula valuation = (\\<exists> clause. clause el formula \\<and> clauseFalse clause valuation)\"\nby (induct formula) auto\n\nlemma formulaTrueAssociativity:\n  fixes f1 :: Formula and f2 :: Formula and f3 :: Formula and valuation :: Valuation\n  shows \"formulaTrue ((f1 @ f2) @ f3) valuation = formulaTrue (f1 @ (f2 @ f3)) valuation\"\nby (auto simp add:formulaTrueIffAllClausesAreTrue)\n\nlemma formulaTrueCommutativity:\n  fixes f1 :: Formula and f2 :: Formula and valuation :: Valuation\n  shows \"formulaTrue (f1 @ f2) valuation = formulaTrue (f2 @ f1) valuation\"\nby (auto simp add:formulaTrueIffAllClausesAreTrue)\n\nlemma formulaTrueSubset:\n  fixes formula :: Formula and formula' :: Formula and valuation :: Valuation\n  assumes \n  formulaTrue: \"formulaTrue formula valuation\" and\n  subset: \"\\<forall> (clause::Clause). clause el formula' \\<longrightarrow> clause el formula\"\n  shows \"formulaTrue formula' valuation\"\nproof -\n  {\n    fix clause :: Clause\n    assume \"clause el formula'\"\n    with formulaTrue subset \n    have \"clauseTrue clause valuation\"\n      by (simp add:formulaTrueIffAllClausesAreTrue)\n  }\n  thus ?thesis\n    by (simp add:formulaTrueIffAllClausesAreTrue)\nqed\n\nlemma formulaTrueAppend:\n  fixes formula1 :: Formula and formula2 :: Formula and valuation :: Valuation\n  shows \"formulaTrue (formula1 @ formula2) valuation = (formulaTrue formula1 valuation \\<and> formulaTrue formula2 valuation)\"\nby (induct formula1) auto\n\nlemma formulaTrueRemoveAll:\n  fixes formula :: Formula and clause :: Clause and valuation :: Valuation    \n  assumes \"formulaTrue formula valuation\"\n  shows \"formulaTrue (removeAll clause formula) valuation\"\nusing assms\nby (induct formula) auto\n\nlemma formulaFalseAppend: \n  fixes formula :: Formula and formula' :: Formula and valuation :: Valuation  \n  assumes \"formulaFalse formula valuation\"\n  shows \"formulaFalse (formula @ formula') valuation\"\nusing assms \nby (induct formula) auto\n\nlemma formulaTrueAppendValuation: \n  fixes formula :: Formula and valuation :: Valuation and valuation' :: Valuation\n  assumes \"formulaTrue formula valuation\"\n  shows \"formulaTrue formula (valuation @ valuation')\"\nusing assms\nby (induct formula) (auto simp add:clauseTrueAppendValuation)\n\nlemma formulaFalseAppendValuation: \n  fixes formula :: Formula and valuation :: Valuation and valuation' :: Valuation\n  assumes \"formulaFalse formula valuation\"\n  shows \"formulaFalse formula (valuation @ valuation')\"\nusing assms\nby (induct formula) (auto simp add:clauseFalseAppendValuation)\n\nlemma trueFormulaWithSingleLiteralClause:\n  fixes formula :: Formula and literal :: Literal and valuation :: Valuation\n  assumes \"formulaTrue (removeAll [literal] formula) (valuation @ [literal])\"\n  shows \"formulaTrue formula (valuation @ [literal])\"\nproof -\n  {\n    fix clause :: Clause\n    assume \"clause el formula\"\n    with assms \n    have \"clauseTrue clause (valuation @ [literal])\"\n    proof (cases \"clause = [literal]\")\n      case True\n      thus ?thesis\n        by simp\n    next\n      case False\n      with \\<open>clause el formula\\<close>\n      have \"clause el (removeAll [literal] formula)\"\n        by simp\n      with \\<open>formulaTrue (removeAll [literal] formula) (valuation @ [literal])\\<close> \n      show ?thesis\n        by (simp add: formulaTrueIffAllClausesAreTrue)\n    qed\n  }\n  thus ?thesis\n    by (simp add: formulaTrueIffAllClausesAreTrue)\nqed\n\n(*------------------------------------------------------------------*)\nsubsubsection\\<open>Valuation viewed as a formula\\<close>\n\ntext\\<open>Converts a valuation (the list of literals) into formula (list of single member lists of literals)\\<close>\nprimrec\nval2form    :: \"Valuation \\<Rightarrow> Formula\"\nwhere\n  \"val2form [] = []\"\n| \"val2form (literal # valuation) = [literal] # val2form valuation\"\n\nlemma val2FormEl: \n  fixes literal :: Literal and valuation :: Valuation \n  shows \"literal el valuation = [literal] el val2form valuation\"\nby (induct valuation) auto\n\nlemma val2FormAreSingleLiteralClauses: \n  fixes clause :: Clause and valuation :: Valuation\n  shows \"clause el val2form valuation \\<longrightarrow> (\\<exists> literal. clause = [literal] \\<and> literal el valuation)\"\nby (induct valuation) auto\n\n\n\nlemma val2FormRemoveAll: \n  fixes literal :: Literal and valuation :: Valuation \n  shows \"removeAll [literal] (val2form valuation) = val2form (removeAll literal valuation)\"\nby (induct valuation) auto\n\nlemma val2formAppend: \n  fixes valuation1 :: Valuation and valuation2 :: Valuation\n  shows \"val2form (valuation1 @ valuation2) = (val2form valuation1 @ val2form valuation2)\"\nby (induct valuation1) auto\n\nlemma val2formFormulaTrue: \n  fixes valuation1 :: Valuation and valuation2 :: Valuation\n  shows \"formulaTrue (val2form valuation1) valuation2 = (\\<forall> (literal :: Literal). literal el valuation1 \\<longrightarrow> literal el valuation2)\"\nby (induct valuation1) auto\n\n\n(*------------------------------------------------------------------*)\nsubsubsection\\<open>Consistency of valuations\\<close>\n\ntext\\<open>Valuation is inconsistent if it contains both a literal and its opposite.\\<close>\nprimrec\ninconsistent   :: \"Valuation \\<Rightarrow> bool\"\nwhere\n  \"inconsistent [] = False\"\n| \"inconsistent (literal # valuation) = (opposite literal el valuation \\<or> inconsistent valuation)\"\ndefinition [simp]: \"consistent valuation == \\<not> inconsistent valuation\"\n\nlemma inconsistentCharacterization: \n  fixes valuation :: Valuation\n  shows \"inconsistent valuation = (\\<exists> literal. literalTrue literal valuation \\<and> literalFalse literal valuation)\"\nby (induct valuation) auto\n\nlemma clauseTrueAndClauseFalseImpliesInconsistent: \n  fixes clause :: Clause and valuation :: Valuation\n  assumes \"clauseTrue clause valuation\" and \"clauseFalse clause valuation\"\n  shows \"inconsistent valuation\"\nproof -\n  from \\<open>clauseTrue clause valuation\\<close> obtain literal :: Literal \n    where \"literal el clause\" and \"literalTrue literal valuation\"\n    by (auto simp add: clauseTrueIffContainsTrueLiteral)\n  with \\<open>clauseFalse clause valuation\\<close> \n  have \"literalFalse literal valuation\" \n    by (auto simp add: clauseFalseIffAllLiteralsAreFalse)\n  from \\<open>literalTrue literal valuation\\<close> \\<open>literalFalse literal valuation\\<close> \n  show ?thesis \n    by (auto simp add: inconsistentCharacterization)\nqed\n\nlemma formulaTrueAndFormulaFalseImpliesInconsistent: \n  fixes formula :: Formula and valuation :: Valuation\n  assumes \"formulaTrue formula valuation\" and \"formulaFalse formula valuation\"\n  shows \"inconsistent valuation\"\nproof -\n  from \\<open>formulaFalse formula valuation\\<close> obtain clause :: Clause \n    where \"clause el formula\" and \"clauseFalse clause valuation\"\n    by (auto simp add: formulaFalseIffContainsFalseClause)\n  with \\<open>formulaTrue formula valuation\\<close> \n  have \"clauseTrue clause valuation\" \n    by (auto simp add: formulaTrueIffAllClausesAreTrue)\n  from \\<open>clauseTrue clause valuation\\<close> \\<open>clauseFalse clause valuation\\<close> \n  show ?thesis \n    by (auto simp add: clauseTrueAndClauseFalseImpliesInconsistent)\nqed\n\nlemma inconsistentAppend:\n  fixes valuation1 :: Valuation and valuation2 :: Valuation\n  assumes \"inconsistent (valuation1 @ valuation2)\"\n  shows \"inconsistent valuation1 \\<or> inconsistent valuation2 \\<or> (\\<exists> literal. literalTrue literal valuation1 \\<and> literalFalse literal valuation2)\"\nusing assms\nproof (cases \"inconsistent valuation1\")\n  case True\n  thus ?thesis \n    by simp\nnext\n  case False\n  thus ?thesis\n  proof (cases \"inconsistent valuation2\")\n    case True\n    thus ?thesis \n      by simp\n  next\n    case False\n    from \\<open>inconsistent (valuation1 @ valuation2)\\<close> obtain literal :: Literal \n      where \"literalTrue literal (valuation1 @ valuation2)\" and \"literalFalse literal (valuation1 @ valuation2)\"\n      by (auto simp add:inconsistentCharacterization)\n    hence \"(\\<exists> literal. literalTrue literal valuation1 \\<and> literalFalse literal valuation2)\"\n    proof (cases \"literalTrue literal valuation1\")\n      case True\n      with \\<open>\\<not> inconsistent valuation1\\<close> \n      have \"\\<not> literalFalse literal valuation1\" \n        by (auto simp add:inconsistentCharacterization)\n      with \\<open>literalFalse literal (valuation1 @ valuation2)\\<close> \n      have \"literalFalse literal valuation2\" \n        by auto\n      with True \n      show ?thesis \n        by auto\n    next\n      case False\n      with \\<open>literalTrue literal (valuation1 @ valuation2)\\<close> \n      have \"literalTrue literal valuation2\"\n        by auto\n      with \\<open>\\<not> inconsistent valuation2\\<close> \n      have \"\\<not> literalFalse literal valuation2\"\n        by (auto simp add:inconsistentCharacterization)\n      with \\<open>literalFalse literal (valuation1 @ valuation2)\\<close> \n      have \"literalFalse literal valuation1\"\n        by auto\n      with \\<open>literalTrue literal valuation2\\<close>\n      show ?thesis \n        by auto\n    qed\n    thus ?thesis \n      by simp\n  qed\nqed\n\nlemma consistentAppendElement:\nassumes \"consistent v\" and \"\\<not> literalFalse l v\"\nshows \"consistent (v @ [l])\"\nproof-\n  {\n    assume \"\\<not> ?thesis\"\n    with \\<open>consistent v\\<close>\n    have \"(opposite l) el v\"\n      using inconsistentAppend[of \"v\" \"[l]\"]\n      by auto\n    with \\<open>\\<not> literalFalse l v\\<close>\n    have False\n      by simp\n  }\n  thus ?thesis\n    by auto\nqed\n\nlemma inconsistentRemoveAll:\n  fixes literal :: Literal and valuation :: Valuation\n  assumes \"inconsistent (removeAll literal valuation)\" \n  shows \"inconsistent valuation\"\nusing assms\nproof -\n  from \\<open>inconsistent (removeAll literal valuation)\\<close> obtain literal' :: Literal \n    where l'True: \"literalTrue literal' (removeAll literal valuation)\" and l'False: \"literalFalse literal' (removeAll literal valuation)\"\n    by (auto simp add:inconsistentCharacterization)\n  from l'True \n  have \"literalTrue literal' valuation\"\n    by simp\n  moreover\n  from l'False \n  have \"literalFalse literal' valuation\"\n    by simp\n  ultimately\n  show ?thesis \n    by (auto simp add:inconsistentCharacterization)\nqed\n\nlemma inconsistentPrefix: \n  assumes \"isPrefix valuation1 valuation2\" and \"inconsistent valuation1\"\n  shows \"inconsistent valuation2\"\nusing assms\nby (auto simp add:inconsistentCharacterization isPrefix_def)\n\nlemma consistentPrefix:\n  assumes \"isPrefix valuation1 valuation2\" and \"consistent valuation2\"\n  shows \"consistent valuation1\"\nusing assms\nby (auto simp add:inconsistentCharacterization isPrefix_def)\n\n\n(*------------------------------------------------------------------*)\nsubsubsection\\<open>Totality of valuations\\<close>\n\ntext\\<open>Checks if the valuation contains all the variables from the given set of variables\\<close>\ndefinition total where\n[simp]: \"total valuation variables == variables \\<subseteq> vars valuation\"\n\nlemma totalSubset: \n  fixes A :: \"Variable set\" and B :: \"Variable set\" and valuation :: \"Valuation\"\n  assumes \"A \\<subseteq> B\" and \"total valuation B\"\n  shows \"total valuation A\"\nusing assms\nby auto\n\nlemma totalFormulaImpliesTotalClause:\n  fixes clause :: Clause and formula :: Formula and valuation :: Valuation\n  assumes clauseEl: \"clause el formula\" and totalFormula: \"total valuation (vars formula)\"\n  shows totalClause: \"total valuation (vars clause)\"\nproof -\n  from clauseEl \n  have \"vars clause \\<subseteq> vars formula\" \n    using formulaContainsItsClausesVariables [of \"clause\" \"formula\"] \n    by simp\n  with totalFormula \n  show ?thesis \n    by (simp add: totalSubset)\nqed\n\nlemma totalValuationForClauseDefinesAllItsLiterals:\n  fixes clause :: Clause and valuation :: Valuation and literal :: Literal\n  assumes \n  totalClause: \"total valuation (vars clause)\" and\n  literalEl: \"literal el clause\"\n  shows trueOrFalse: \"literalTrue literal valuation \\<or> literalFalse literal valuation\"\nproof -\n  from literalEl \n  have \"var literal \\<in> vars clause\"\n    using clauseContainsItsLiteralsVariable \n    by auto\n  with totalClause \n  have \"var literal \\<in> vars valuation\" \n    by auto\n  thus ?thesis \n    using  variableDefinedImpliesLiteralDefined [of \"literal\" \"valuation\"] \n    by simp\nqed\n\nlemma totalValuationForClauseDefinesItsValue:\n  fixes clause :: Clause and valuation :: Valuation\n  assumes totalClause: \"total valuation (vars clause)\"\n  shows \"clauseTrue clause valuation \\<or> clauseFalse clause valuation\"\nproof (cases \"clauseFalse clause valuation\")\n  case True\n  thus ?thesis \n    by (rule disjI2)\nnext\n  case False\n  hence \"\\<not> (\\<forall> l. l el clause \\<longrightarrow> literalFalse l valuation)\" \n    by (auto simp add:clauseFalseIffAllLiteralsAreFalse)\n  then obtain l :: Literal \n    where \"l el clause\" and \"\\<not> literalFalse l valuation\" \n    by auto\n  with totalClause \n  have \"literalTrue l valuation \\<or> literalFalse l valuation\"\n    using totalValuationForClauseDefinesAllItsLiterals [of \"valuation\" \"clause\" \"l\"] \n    by auto\n  with \\<open>\\<not> literalFalse l valuation\\<close> \n  have \"literalTrue l valuation\" \n    by simp\n  with \\<open>l el clause\\<close> \n  have \"(clauseTrue clause valuation)\" \n    by (auto simp add:clauseTrueIffContainsTrueLiteral)\n  thus ?thesis \n    by (rule disjI1) \nqed\n\nlemma totalValuationForFormulaDefinesAllItsLiterals: \n  fixes formula::Formula and valuation::Valuation\n  assumes totalFormula: \"total valuation (vars formula)\" and\n  literalElFormula: \"literal el formula\"\n  shows \"literalTrue literal valuation \\<or> literalFalse literal valuation\"\nproof -\n  from literalElFormula \n  have \"var literal \\<in> vars formula\" \n    by (rule formulaContainsItsLiteralsVariable)\n  with totalFormula \n  have \"var literal \\<in> vars valuation\" \n    by auto\n  thus ?thesis using variableDefinedImpliesLiteralDefined [of \"literal\" \"valuation\"] \n    by simp\nqed\n\nlemma totalValuationForFormulaDefinesAllItsClauses:\n  fixes formula :: Formula and valuation :: Valuation and clause :: Clause\n  assumes totalFormula: \"total valuation (vars formula)\" and \n  clauseElFormula: \"clause el formula\" \n  shows \"clauseTrue clause valuation \\<or> clauseFalse clause valuation\"\nproof -\n  from clauseElFormula totalFormula \n  have \"total valuation (vars clause)\"\n    by (rule totalFormulaImpliesTotalClause)\n  thus ?thesis\n    by (rule totalValuationForClauseDefinesItsValue)\nqed\n\nlemma totalValuationForFormulaDefinesItsValue:\n  assumes totalFormula: \"total valuation (vars formula)\"\n  shows \"formulaTrue formula valuation \\<or> formulaFalse formula valuation\"\nproof (cases \"formulaTrue formula valuation\")\n  case True\n  thus ?thesis\n    by simp\nnext\n  case False\n  then obtain clause :: Clause \n    where clauseElFormula: \"clause el formula\" and notClauseTrue: \"\\<not> clauseTrue clause valuation\" \n    by (auto simp add: formulaTrueIffAllClausesAreTrue)\n  from clauseElFormula totalFormula\n  have \"total valuation (vars clause)\"\n    using totalFormulaImpliesTotalClause [of \"clause\" \"formula\" \"valuation\"]\n    by simp\n  with notClauseTrue \n  have \"clauseFalse clause valuation\" \n    using totalValuationForClauseDefinesItsValue [of \"valuation\" \"clause\"]\n    by simp\n  with clauseElFormula \n  show ?thesis \n    by (auto simp add:formulaFalseIffContainsFalseClause)\nqed\n\nlemma totalRemoveAllSingleLiteralClause:\n  fixes literal :: Literal and valuation :: Valuation and formula :: Formula\n  assumes varLiteral: \"var literal \\<in> vars valuation\" and totalRemoveAll: \"total valuation (vars (removeAll [literal] formula))\"\n  shows \"total valuation (vars formula)\"\nproof -\n  have \"vars formula - vars [literal] \\<subseteq> vars (removeAll [literal] formula)\"\n    by (rule varsRemoveAllClauseSuperset)\n  with assms \n  show ?thesis \n    by auto\nqed\n\n\n(*------------------------------------------------------------------*)\nsubsubsection\\<open>Models and satisfiability\\<close>\n\ntext\\<open>Model of a formula is a consistent valuation under which formula/clause is true\\<close>\nconsts model :: \"Valuation \\<Rightarrow> 'a \\<Rightarrow> bool\"\n\noverloading modelFormula \\<equiv> \"model :: Valuation \\<Rightarrow> Formula \\<Rightarrow> bool\"\nbegin\n  definition [simp]: \"model valuation (formula::Formula) ==\n    consistent valuation \\<and> (formulaTrue formula valuation)\"\nend\n\noverloading modelClause \\<equiv> \"model :: Valuation \\<Rightarrow> Clause \\<Rightarrow> bool\"\nbegin\n  definition [simp]: \"model valuation (clause::Clause) ==\n    consistent valuation \\<and> (clauseTrue clause valuation)\"\nend\n\ntext\\<open>Checks if a formula has a model\\<close>\ndefinition satisfiable :: \"Formula \\<Rightarrow> bool\"\nwhere\n\"satisfiable formula == \\<exists> valuation. model valuation formula\"\n\nlemma formulaWithEmptyClauseIsUnsatisfiable:\n  fixes formula :: Formula\n  assumes \"([]::Clause) el formula\"\n  shows \"\\<not> satisfiable formula\"\nusing assms\nby (auto simp add: satisfiable_def formulaTrueIffAllClausesAreTrue)\n\nlemma satisfiableSubset: \n  fixes formula0 :: Formula and formula :: Formula\n  assumes subset: \"\\<forall> (clause::Clause). clause el formula0 \\<longrightarrow> clause el formula\"\n  shows  \"satisfiable formula \\<longrightarrow> satisfiable formula0\"\nproof\n  assume \"satisfiable formula\"\n  show \"satisfiable formula0\"\n  proof -\n    from \\<open>satisfiable formula\\<close> obtain valuation :: Valuation\n      where \"model valuation formula\" \n      by (auto simp add: satisfiable_def)\n    {\n      fix clause :: Clause\n      assume \"clause el formula0\"\n      with subset \n      have \"clause el formula\" \n        by simp\n      with \\<open>model valuation formula\\<close> \n      have \"clauseTrue clause valuation\" \n        by (simp add: formulaTrueIffAllClausesAreTrue)\n    } hence \"formulaTrue formula0 valuation\" \n      by (simp add: formulaTrueIffAllClausesAreTrue)\n    with \\<open>model valuation formula\\<close> \n    have \"model valuation formula0\" \n      by simp\n    thus ?thesis \n      by (auto simp add: satisfiable_def)\n  qed\nqed\n\nlemma satisfiableAppend: \n  fixes formula1 :: Formula and formula2 :: Formula\n  assumes \"satisfiable (formula1 @ formula2)\" \n  shows \"satisfiable formula1\" \"satisfiable formula2\"\nusing assms\nunfolding satisfiable_def\nby (auto simp add:formulaTrueAppend)\n\nlemma modelExpand: \n  fixes formula :: Formula and literal :: Literal and valuation :: Valuation\n  assumes \"model valuation formula\" and \"var literal \\<notin> vars valuation\"\n  shows \"model (valuation @ [literal]) formula\"\nproof -\n  from \\<open>model valuation formula\\<close> \n  have \"formulaTrue formula (valuation @ [literal])\"\n    by (simp add:formulaTrueAppendValuation)\n  moreover\n  from \\<open>model valuation formula\\<close> \n  have \"consistent valuation\" \n    by simp\n  with \\<open>var literal \\<notin> vars valuation\\<close> \n  have \"consistent (valuation @ [literal])\"\n  proof (cases \"inconsistent (valuation @ [literal])\")\n    case True\n    hence \"inconsistent valuation \\<or> inconsistent [literal] \\<or> (\\<exists> l. literalTrue l valuation \\<and> literalFalse l [literal])\"\n      by (rule inconsistentAppend)\n    with \\<open>consistent valuation\\<close> \n    have \"\\<exists> l. literalTrue l valuation \\<and> literalFalse l [literal]\"\n      by auto\n    hence \"literalFalse literal valuation\" \n      by auto\n    hence \"var (opposite literal) \\<in> (vars valuation)\"\n      using valuationContainsItsLiteralsVariable [of \"opposite literal\" \"valuation\"]\n      by simp\n    with \\<open>var literal \\<notin> vars valuation\\<close> \n    have \"False\"\n      by simp\n    thus ?thesis ..\n  qed simp\n  ultimately \n  show ?thesis \n    by auto\nqed\n\n\n\n(*--------------------------------------------------------------------------------*)\nsubsubsection\\<open>Tautological clauses\\<close>\n\nlemma tautologyNotFalse:\n  fixes clause :: Clause and valuation :: Valuation\n  assumes \"clauseTautology clause\" \"consistent valuation\"\n  shows \"\\<not> clauseFalse clause valuation\"\nusing assms\n  clauseTautologyCharacterization[of \"clause\"]\n  clauseFalseIffAllLiteralsAreFalse[of \"clause\" \"valuation\"]\n  inconsistentCharacterization\nby auto\n  \n\nlemma tautologyInTotalValuation:\nassumes \n  \"clauseTautology clause\"\n  \"vars clause \\<subseteq> vars valuation\"\nshows\n  \"clauseTrue clause valuation\"\nproof-\n  from \\<open>clauseTautology clause\\<close>\n  obtain literal\n    where \"literal el clause\" \"opposite literal el clause\"\n    by (auto simp add: clauseTautologyCharacterization)\n  hence \"var literal \\<in> vars clause\"\n    using clauseContainsItsLiteralsVariable[of \"literal\" \"clause\"]\n    using clauseContainsItsLiteralsVariable[of \"opposite literal\" \"clause\"]\n    by simp\n  hence \"var literal \\<in> vars valuation\"\n    using \\<open>vars clause \\<subseteq> vars valuation\\<close>\n    by auto\n  hence \"literalTrue literal valuation \\<or> literalFalse literal valuation\"\n    using varInClauseVars[of \"var literal\" \"valuation\"]\n    using varInClauseVars[of \"var (opposite literal)\" \"valuation\"]\n    using literalsWithSameVariableAreEqualOrOpposite\n    by auto\n  thus ?thesis\n    using \\<open>literal el clause\\<close> \\<open>opposite literal el clause\\<close>\n    by (auto simp add: clauseTrueIffContainsTrueLiteral)\nqed\n\nlemma modelAppendTautology:\nassumes\n  \"model valuation F\" \"clauseTautology c\"\n  \"vars valuation \\<supseteq> vars F \\<union> vars c\"\nshows\n  \"model valuation (F @ [c])\"\nusing assms\nusing tautologyInTotalValuation[of \"c\" \"valuation\"]\nby (auto simp add: formulaTrueAppend)\n\nlemma satisfiableAppendTautology:\nassumes \n  \"satisfiable F\" \"clauseTautology c\"\nshows\n  \"satisfiable (F @ [c])\"\nproof-\n  from \\<open>clauseTautology c\\<close> \n  obtain l \n    where \"l el c\" \"opposite l el c\"\n    by (auto simp add: clauseTautologyCharacterization)\n  from \\<open>satisfiable F\\<close>\n  obtain valuation\n    where \"consistent valuation\" \"formulaTrue F valuation\"\n    unfolding satisfiable_def\n    by auto\n  show ?thesis\n  proof (cases \"var l \\<in> vars valuation\")\n    case True\n    hence \"literalTrue l valuation \\<or> literalFalse l valuation\"\n      using varInClauseVars[of \"var l\" \"valuation\"]\n      by (auto simp add: literalsWithSameVariableAreEqualOrOpposite)\n    hence \"clauseTrue c valuation\"\n      using \\<open>l el c\\<close> \\<open>opposite l el c\\<close>\n      by (auto simp add: clauseTrueIffContainsTrueLiteral)\n    thus ?thesis\n      using \\<open>consistent valuation\\<close> \\<open>formulaTrue F valuation\\<close>\n      unfolding satisfiable_def\n      by (auto simp add: formulaTrueIffAllClausesAreTrue)\n  next\n    case False\n    let ?valuation' = \"valuation @ [l]\"\n    have \"model ?valuation' F\"\n      using \\<open>var l \\<notin> vars valuation\\<close>\n      using \\<open>formulaTrue F valuation\\<close> \\<open>consistent valuation\\<close>\n      using modelExpand[of \"valuation\" \"F\" \"l\"]\n      by simp\n    moreover\n    have \"formulaTrue [c] ?valuation'\"\n      using \\<open>l el c\\<close>\n      using clauseTrueIffContainsTrueLiteral[of \"c\" \"?valuation'\"]\n      using formulaTrueIffAllClausesAreTrue[of \"[c]\" \"?valuation'\"]\n      by auto\n    ultimately\n    show ?thesis\n      unfolding satisfiable_def\n      by (auto simp add: formulaTrueAppend)\n  qed\nqed\n\nlemma modelAppendTautologicalFormula:\nfixes\n  F :: Formula and F' :: Formula\nassumes\n  \"model valuation F\" \"\\<forall> c. c el F' \\<longrightarrow> clauseTautology c\"\n  \"vars valuation \\<supseteq> vars F \\<union> vars F'\"\nshows\n  \"model valuation (F @ F')\"\nusing assms\nproof (induct F')\n  case Nil\n  thus ?case\n    by simp\nnext\n  case (Cons c F'')\n  hence \"model valuation (F @ F'')\"\n    by simp\n  hence \"model valuation ((F @ F'') @ [c])\"\n    using Cons(3)\n    using Cons(4)\n    using modelAppendTautology[of \"valuation\" \"F @ F''\" \"c\"]\n    using varsAppendFormulae[of \"F\" \"F''\"]\n    by simp\n  thus ?case\n    by (simp add: formulaTrueAppend)\nqed\n\n\nlemma satisfiableAppendTautologicalFormula:\nassumes \n  \"satisfiable F\" \"\\<forall> c. c el F' \\<longrightarrow> clauseTautology c\"\nshows\n  \"satisfiable (F @ F')\"\nusing assms\nproof (induct F')\n  case Nil\n  thus ?case\n    by simp\nnext\n  case (Cons c F'')\n  hence \"satisfiable (F @ F'')\"\n    by simp\n  thus ?case\n    using Cons(3)\n    using satisfiableAppendTautology[of \"F @ F''\" \"c\"]\n    unfolding satisfiable_def\n    by (simp add: formulaTrueIffAllClausesAreTrue)\nqed\n\nlemma satisfiableFilterTautologies:\nshows \"satisfiable F = satisfiable (filter (% c. \\<not> clauseTautology c) F)\"\nproof (induct F)\n  case Nil\n  thus ?case\n    by simp\nnext\n  case (Cons c' F')\n  let ?filt  = \"\\<lambda> F. filter (% c. \\<not> clauseTautology c) F\"\n  let ?filt'  = \"\\<lambda> F. filter (% c. clauseTautology c) F\"\n  show ?case\n  proof\n    assume \"satisfiable (c' # F')\"\n    thus \"satisfiable (?filt (c' # F'))\"\n      unfolding satisfiable_def\n      by (auto simp add: formulaTrueIffAllClausesAreTrue)\n  next\n    assume \"satisfiable (?filt (c' # F'))\"\n    thus \"satisfiable (c' # F')\"\n    proof (cases \"clauseTautology c'\")\n      case True\n      hence \"?filt (c' # F') = ?filt F'\"\n        by auto\n      hence \"satisfiable (?filt F')\"\n        using \\<open>satisfiable (?filt (c' # F'))\\<close>\n        by simp\n      hence \"satisfiable F'\"\n        using Cons\n        by simp\n      thus ?thesis\n        using satisfiableAppendTautology[of \"F'\" \"c'\"]\n        using \\<open>clauseTautology c'\\<close>\n        unfolding satisfiable_def\n        by (auto simp add: formulaTrueIffAllClausesAreTrue)\n    next\n      case False\n      hence \"?filt (c' # F') = c' # ?filt F'\"\n        by auto   \n      hence \"satisfiable (c' # ?filt F')\"\n        using \\<open>satisfiable (?filt (c' # F'))\\<close>\n        by simp\n      moreover\n      have \"\\<forall> c. c el ?filt' F' \\<longrightarrow> clauseTautology c\"\n        by simp\n      ultimately\n      have \"satisfiable ((c' # ?filt F') @ ?filt' F')\"\n        using satisfiableAppendTautologicalFormula[of \"c' # ?filt F'\" \"?filt' F'\"]\n        by (simp (no_asm_use))\n      thus ?thesis\n        unfolding satisfiable_def\n        by (auto simp add: formulaTrueIffAllClausesAreTrue)\n    qed\n  qed\nqed\n\nlemma modelFilterTautologies:\nassumes \n  \"model valuation (filter (% c. \\<not> clauseTautology c) F)\" \n  \"vars F \\<subseteq> vars valuation\"\nshows \"model valuation F\"\nusing assms\nproof (induct F)\n  case Nil\n  thus ?case\n    by simp\nnext\n  case (Cons c' F')\n  let ?filt  = \"\\<lambda> F. filter (% c. \\<not> clauseTautology c) F\"\n  let ?filt'  = \"\\<lambda> F. filter (% c. clauseTautology c) F\"\n  show ?case\n  proof (cases \"clauseTautology c'\")\n    case True\n    thus ?thesis\n      using Cons\n      using tautologyInTotalValuation[of \"c'\" \"valuation\"]\n      by auto\n  next\n    case False\n    hence \"?filt (c' # F') = c' # ?filt F'\"\n      by auto   \n    hence \"model valuation (c' # ?filt F')\"\n      using \\<open>model valuation (?filt (c' # F'))\\<close>\n      by simp\n    moreover\n    have \"\\<forall> c. c el ?filt' F' \\<longrightarrow> clauseTautology c\"\n      by simp\n    moreover \n    have \"vars ((c' # ?filt F') @ ?filt' F') \\<subseteq> vars valuation\"\n      using varsSubsetFormula[of \"?filt F'\" \"F'\"]\n      using varsSubsetFormula[of \"?filt' F'\" \"F'\"]\n      using varsAppendFormulae[of \"c' # ?filt F'\" \"?filt' F'\"]\n      using Cons(3)\n      using formulaContainsItsClausesVariables[of _ \"?filt F'\"]\n      by auto\n    ultimately\n    have \"model valuation ((c' # ?filt F') @ ?filt' F')\"\n      using modelAppendTautologicalFormula[of \"valuation\" \"c' # ?filt F'\" \"?filt' F'\"]\n      using varsAppendFormulae[of \"c' # ?filt F'\" \"?filt' F'\"]\n      by (simp (no_asm_use)) (blast)\n    thus ?thesis\n      using formulaTrueAppend[of \"?filt F'\" \"?filt' F'\" \"valuation\"]\n      using formulaTrueIffAllClausesAreTrue[of \"?filt F'\" \"valuation\"]\n      using formulaTrueIffAllClausesAreTrue[of \"?filt' F'\" \"valuation\"]\n      using formulaTrueIffAllClausesAreTrue[of \"F'\" \"valuation\"]      \n      by auto\n  qed\nqed\n\n(*------------------------------------------------------------------*)\nsubsubsection\\<open>Entailment\\<close>\n\ntext\\<open>Formula entails literal if it is true in all its models\\<close>\ndefinition formulaEntailsLiteral :: \"Formula \\<Rightarrow> Literal \\<Rightarrow> bool\"\nwhere\n\"formulaEntailsLiteral formula literal == \n  \\<forall> (valuation::Valuation). model valuation formula \\<longrightarrow> literalTrue literal valuation\"\n\ntext\\<open>Clause implies literal if it is true in all its models\\<close>\ndefinition clauseEntailsLiteral  :: \"Clause \\<Rightarrow> Literal \\<Rightarrow> bool\"\nwhere\n\"clauseEntailsLiteral clause literal == \n  \\<forall> (valuation::Valuation). model valuation clause \\<longrightarrow> literalTrue literal valuation\"\n\ntext\\<open>Formula entails clause if it is true in all its models\\<close>\ndefinition formulaEntailsClause  :: \"Formula \\<Rightarrow> Clause \\<Rightarrow> bool\"\nwhere\n\"formulaEntailsClause formula clause == \n  \\<forall> (valuation::Valuation). model valuation formula \\<longrightarrow> model valuation clause\"\n\ntext\\<open>Formula entails valuation if it entails its every literal\\<close>\ndefinition formulaEntailsValuation :: \"Formula \\<Rightarrow> Valuation \\<Rightarrow> bool\"\nwhere\n\"formulaEntailsValuation formula valuation ==\n    \\<forall> literal. literal el valuation \\<longrightarrow> formulaEntailsLiteral formula literal\"\n\ntext\\<open>Formula entails formula if it is true in all its models\\<close>\ndefinition formulaEntailsFormula  :: \"Formula \\<Rightarrow> Formula \\<Rightarrow> bool\"\nwhere\nformulaEntailsFormula_def: \"formulaEntailsFormula formula formula' == \n  \\<forall> (valuation::Valuation). model valuation formula \\<longrightarrow> model valuation formula'\"\n\nlemma singleLiteralClausesEntailItsLiteral: \n  fixes clause :: Clause and literal :: Literal\n  assumes \"length clause = 1\" and \"literal el clause\"\n  shows \"clauseEntailsLiteral clause literal\"\nproof -\n  from assms \n  have onlyLiteral: \"\\<forall> l. l el clause \\<longrightarrow> l = literal\" \n    using lengthOneImpliesOnlyElement[of \"clause\" \"literal\"]\n    by simp\n  {\n    fix valuation :: Valuation\n    assume \"clauseTrue clause valuation\"\n    with onlyLiteral  \n    have \"literalTrue literal valuation\" \n      by (auto simp add:clauseTrueIffContainsTrueLiteral)\n  }\n  thus ?thesis \n    by (simp add:clauseEntailsLiteral_def)\nqed\n\nlemma clauseEntailsLiteralThenFormulaEntailsLiteral:\n  fixes clause :: Clause and formula :: Formula and literal :: Literal\n  assumes \"clause el formula\" and \"clauseEntailsLiteral clause literal\"\n  shows \"formulaEntailsLiteral formula literal\"\nproof -\n  {\n    fix valuation :: Valuation\n    assume modelFormula: \"model valuation formula\"\n\n    with \\<open>clause el formula\\<close> \n    have \"clauseTrue clause valuation\"\n      by (simp add:formulaTrueIffAllClausesAreTrue)\n    with modelFormula \\<open>clauseEntailsLiteral clause literal\\<close> \n    have \"literalTrue literal valuation\"\n      by (auto simp add: clauseEntailsLiteral_def)\n  }\n  thus ?thesis \n    by (simp add:formulaEntailsLiteral_def)\nqed\n\nlemma formulaEntailsLiteralAppend: \n  fixes formula :: Formula and formula' :: Formula and literal :: Literal\n  assumes \"formulaEntailsLiteral formula literal\"\n  shows  \"formulaEntailsLiteral (formula @ formula') literal\"\nproof -\n  {\n    fix valuation :: Valuation\n    assume modelFF': \"model valuation (formula @ formula')\"\n\n    hence \"formulaTrue formula valuation\" \n      by (simp add: formulaTrueAppend)\n    with modelFF' and \\<open>formulaEntailsLiteral formula literal\\<close> \n    have \"literalTrue literal valuation\" \n      by (simp add: formulaEntailsLiteral_def)\n  }\n  thus ?thesis \n    by (simp add: formulaEntailsLiteral_def)\nqed\n\nlemma formulaEntailsLiteralSubset: \n  fixes formula :: Formula and formula' :: Formula and literal :: Literal\n  assumes \"formulaEntailsLiteral formula literal\" and \"\\<forall> (c::Clause) . c el formula \\<longrightarrow> c el formula'\"\n  shows \"formulaEntailsLiteral formula' literal\"\nproof -\n  {\n    fix valuation :: Valuation\n    assume modelF': \"model valuation formula'\"\n    with \\<open>\\<forall> (c::Clause) . c el formula \\<longrightarrow> c el formula'\\<close> \n    have \"formulaTrue formula valuation\"\n      by (auto simp add: formulaTrueIffAllClausesAreTrue)\n    with modelF' \\<open>formulaEntailsLiteral formula literal\\<close> \n    have \"literalTrue literal valuation\"\n      by (simp add: formulaEntailsLiteral_def)\n  }\n  thus ?thesis \n    by (simp add:formulaEntailsLiteral_def)\nqed\n\n\nlemma formulaEntailsLiteralRemoveAll:\n  fixes formula :: Formula and clause :: Clause and literal :: Literal\n  assumes \"formulaEntailsLiteral (removeAll clause formula) literal\"\n  shows \"formulaEntailsLiteral formula literal\"\nproof -\n  {\n    fix valuation :: Valuation\n    assume modelF: \"model valuation formula\"\n    hence \"formulaTrue (removeAll clause formula) valuation\" \n      by (auto simp add:formulaTrueRemoveAll)\n    with modelF \\<open>formulaEntailsLiteral (removeAll clause formula) literal\\<close> \n    have \"literalTrue literal valuation\"\n      by (auto simp add:formulaEntailsLiteral_def)\n  }\n  thus ?thesis \n    by (simp add:formulaEntailsLiteral_def)\nqed\n\nlemma formulaEntailsLiteralRemoveAllAppend:\n  fixes formula1 :: Formula and formula2 :: Formula and clause :: Clause and valuation :: Valuation\n  assumes \"formulaEntailsLiteral ((removeAll clause formula1) @ formula2) literal\" \n  shows \"formulaEntailsLiteral (formula1 @ formula2) literal\"\nproof -\n  {\n    fix valuation :: Valuation\n    assume modelF: \"model valuation (formula1 @ formula2)\"\n    hence \"formulaTrue ((removeAll clause formula1) @ formula2) valuation\" \n      by (auto simp add:formulaTrueRemoveAll formulaTrueAppend)\n    with modelF \\<open>formulaEntailsLiteral ((removeAll clause formula1) @ formula2) literal\\<close> \n    have \"literalTrue literal valuation\"\n      by (auto simp add:formulaEntailsLiteral_def)\n  }\n  thus ?thesis \n    by (simp add:formulaEntailsLiteral_def)\nqed\n\nlemma formulaEntailsItsClauses: \n  fixes clause :: Clause and formula :: Formula\n  assumes \"clause el formula\"\n  shows \"formulaEntailsClause formula clause\"\nusing assms\nby (simp add: formulaEntailsClause_def formulaTrueIffAllClausesAreTrue)\n\nlemma formulaEntailsClauseAppend: \n  fixes clause :: Clause and formula :: Formula and formula' :: Formula\n  assumes \"formulaEntailsClause formula clause\"\n  shows \"formulaEntailsClause (formula @ formula') clause\"\nproof -\n  { \n    fix valuation :: Valuation\n    assume \"model valuation (formula @ formula')\"\n    hence \"model valuation formula\"\n      by (simp add:formulaTrueAppend)\n    with \\<open>formulaEntailsClause formula clause\\<close> \n    have \"clauseTrue clause valuation\"\n      by (simp add:formulaEntailsClause_def)\n  }\n  thus ?thesis \n    by (simp add: formulaEntailsClause_def)\nqed\n\nlemma formulaUnsatIffImpliesEmptyClause: \n  fixes formula :: Formula\n  shows \"formulaEntailsClause formula [] = (\\<not> satisfiable formula)\"\nby (auto simp add: formulaEntailsClause_def satisfiable_def)\n\nlemma formulaTrueExtendWithEntailedClauses:\n  fixes formula :: Formula and formula0 :: Formula and valuation :: Valuation\n  assumes formulaEntailed: \"\\<forall> (clause::Clause). clause el formula \\<longrightarrow> formulaEntailsClause formula0 clause\" and \"consistent valuation\"\n  shows \"formulaTrue formula0 valuation \\<longrightarrow> formulaTrue formula valuation\"\nproof\n  assume \"formulaTrue formula0 valuation\"\n  {\n    fix clause :: Clause\n    assume \"clause el formula\"\n    with formulaEntailed \n    have \"formulaEntailsClause formula0 clause\"\n      by simp\n    with \\<open>formulaTrue formula0 valuation\\<close> \\<open>consistent valuation\\<close> \n    have \"clauseTrue clause valuation\"\n      by (simp add:formulaEntailsClause_def)\n  }\n  thus \"formulaTrue formula valuation\"\n    by (simp add:formulaTrueIffAllClausesAreTrue)\nqed\n\n\nlemma formulaEntailsFormulaIffEntailsAllItsClauses: \n  fixes formula :: Formula and formula' :: Formula\n  shows \"formulaEntailsFormula formula formula' = (\\<forall> clause::Clause. clause el formula' \\<longrightarrow> formulaEntailsClause formula clause)\"\n     (is \"?lhs = ?rhs\")\nproof\n  assume ?lhs\n  show ?rhs\n  proof\n    fix clause :: Clause\n    show \"clause el formula' \\<longrightarrow> formulaEntailsClause formula clause\"\n    proof\n      assume \"clause el formula'\"\n      show \"formulaEntailsClause formula clause\"\n      proof -\n        {\n          fix valuation :: Valuation\n          assume \"model valuation formula\"\n          with \\<open>?lhs\\<close> \n          have \"model valuation formula'\"\n            by (simp add:formulaEntailsFormula_def)\n          with \\<open>clause el formula'\\<close> \n          have \"clauseTrue clause valuation\"\n            by (simp add:formulaTrueIffAllClausesAreTrue)\n        }\n        thus ?thesis \n          by (simp add:formulaEntailsClause_def)\n      qed\n    qed\n  qed\nnext\n  assume ?rhs\n  thus ?lhs\n  proof -\n    {\n      fix valuation :: Valuation\n      assume \"model valuation formula\"\n      {\n        fix clause :: Clause\n        assume \"clause el formula'\"\n        with \\<open>?rhs\\<close> \n        have \"formulaEntailsClause formula clause\"\n          by auto\n        with \\<open>model valuation formula\\<close> \n        have \"clauseTrue clause valuation\"\n          by (simp add:formulaEntailsClause_def)\n      }\n      hence \"(formulaTrue formula' valuation)\"\n        by (simp add:formulaTrueIffAllClausesAreTrue)\n    }\n    thus ?thesis\n      by (simp add:formulaEntailsFormula_def)\n  qed\nqed\n\nlemma formulaEntailsFormulaThatEntailsClause: \n  fixes formula1 :: Formula and formula2 :: Formula and clause :: Clause\n  assumes \"formulaEntailsFormula formula1 formula2\" and \"formulaEntailsClause formula2 clause\"\n  shows \"formulaEntailsClause formula1 clause\"\nusing assms\nby (simp add: formulaEntailsClause_def formulaEntailsFormula_def)\n\n\nlemma \n  fixes formula1 :: Formula and formula2 :: Formula and formula1' :: Formula and literal :: Literal\n  assumes \"formulaEntailsLiteral (formula1 @ formula2) literal\" and \"formulaEntailsFormula formula1' formula1\"\n  shows \"formulaEntailsLiteral (formula1' @ formula2) literal\"\nproof -\n  {\n    fix valuation :: Valuation\n    assume \"model valuation (formula1' @ formula2)\"\n    hence \"consistent valuation\" and \"formulaTrue formula1' valuation\"  \"formulaTrue formula2 valuation\"\n      by (auto simp add: formulaTrueAppend)\n    with \\<open>formulaEntailsFormula formula1' formula1\\<close> \n    have \"model valuation formula1\"\n      by (simp add:formulaEntailsFormula_def)\n    with \\<open>formulaTrue formula2 valuation\\<close> \n    have \"model valuation (formula1 @ formula2)\"\n      by (simp add: formulaTrueAppend)\n    with \\<open>formulaEntailsLiteral (formula1 @ formula2) literal\\<close> \n    have \"literalTrue literal valuation\"\n      by (simp add:formulaEntailsLiteral_def)\n  }\n  thus ?thesis\n    by (simp add:formulaEntailsLiteral_def)\nqed\n\n\nlemma formulaFalseInEntailedValuationIsUnsatisfiable: \n  fixes formula :: Formula and valuation :: Valuation\n  assumes \"formulaFalse formula valuation\" and \n          \"formulaEntailsValuation formula valuation\"\n  shows \"\\<not> satisfiable formula\"\nproof -\n  from \\<open>formulaFalse formula valuation\\<close> obtain clause :: Clause\n    where \"clause el formula\" and \"clauseFalse clause valuation\"\n    by (auto simp add:formulaFalseIffContainsFalseClause)\n  {\n    fix valuation' :: Valuation\n    assume modelV': \"model valuation' formula\"\n    with \\<open>clause el formula\\<close> obtain literal :: Literal \n      where \"literal el clause\" and \"literalTrue literal valuation'\"\n      by (auto simp add: formulaTrueIffAllClausesAreTrue clauseTrueIffContainsTrueLiteral)\n    with \\<open>clauseFalse clause valuation\\<close> \n    have \"literalFalse literal valuation\"\n      by (auto simp add:clauseFalseIffAllLiteralsAreFalse)\n    with \\<open>formulaEntailsValuation formula valuation\\<close> \n    have \"formulaEntailsLiteral formula (opposite literal)\"\n      unfolding formulaEntailsValuation_def\n      by simp\n    with modelV' \n    have \"literalFalse literal valuation'\"\n      by (auto simp add:formulaEntailsLiteral_def)\n    from \\<open>literalTrue literal valuation'\\<close> \\<open>literalFalse literal valuation'\\<close> modelV' \n    have \"False\"\n      by (simp add:inconsistentCharacterization)\n  }\n  thus ?thesis\n    by (auto simp add:satisfiable_def)\nqed\n\nlemma formulaFalseInEntailedOrPureValuationIsUnsatisfiable: \n  fixes formula :: Formula and valuation :: Valuation\n  assumes \"formulaFalse formula valuation\" and \n  \"\\<forall> literal'. literal' el valuation \\<longrightarrow> formulaEntailsLiteral formula literal' \\<or>  \\<not> opposite literal' el formula\"\n  shows \"\\<not> satisfiable formula\"\nproof -\n  from \\<open>formulaFalse formula valuation\\<close> obtain clause :: Clause\n    where \"clause el formula\" and \"clauseFalse clause valuation\"\n    by (auto simp add:formulaFalseIffContainsFalseClause)\n  {\n    fix valuation' :: Valuation\n    assume modelV': \"model valuation' formula\"\n    with \\<open>clause el formula\\<close> obtain literal :: Literal \n      where \"literal el clause\" and \"literalTrue literal valuation'\"\n      by (auto simp add: formulaTrueIffAllClausesAreTrue clauseTrueIffContainsTrueLiteral)\n    with \\<open>clauseFalse clause valuation\\<close> \n    have \"literalFalse literal valuation\"\n      by (auto simp add:clauseFalseIffAllLiteralsAreFalse)\n    with \\<open>\\<forall> literal'. literal' el valuation \\<longrightarrow> formulaEntailsLiteral formula literal' \\<or>  \\<not> opposite literal' el formula\\<close> \n    have \"formulaEntailsLiteral formula (opposite literal) \\<or> \\<not> literal el formula\"\n      by auto\n    moreover\n    {\n      assume \"formulaEntailsLiteral formula (opposite literal)\"\n      with modelV' \n      have \"literalFalse literal valuation'\"\n        by (auto simp add:formulaEntailsLiteral_def)\n      from \\<open>literalTrue literal valuation'\\<close> \\<open>literalFalse literal valuation'\\<close> modelV' \n      have \"False\"\n        by (simp add:inconsistentCharacterization)\n    }\n    moreover\n    {\n      assume \"\\<not> literal el formula\"\n      with \\<open>clause el formula\\<close> \\<open>literal el clause\\<close>\n      have \"False\"\n        by (simp add:literalElFormulaCharacterization)\n    }\n    ultimately\n    have \"False\"\n      by auto\n  }\n  thus ?thesis\n    by (auto simp add:satisfiable_def)\nqed\n\n\nlemma unsatisfiableFormulaWithSingleLiteralClause:\n  fixes formula :: Formula and literal :: Literal\n  assumes \"\\<not> satisfiable formula\" and \"[literal] el formula\"\n  shows \"formulaEntailsLiteral (removeAll [literal] formula) (opposite literal)\"\nproof -\n  {\n    fix valuation :: Valuation\n    assume \"model valuation (removeAll [literal] formula)\"\n    hence \"literalFalse literal valuation\"\n    proof (cases \"var literal \\<in> vars valuation\")\n      case True\n      {\n        assume \"literalTrue literal valuation\"\n        with \\<open>model valuation (removeAll [literal] formula)\\<close> \n        have \"model valuation formula\"\n          by (auto simp add:formulaTrueIffAllClausesAreTrue)\n        with \\<open>\\<not> satisfiable formula\\<close> \n        have \"False\"\n          by (auto simp add:satisfiable_def)\n      }\n      with True \n      show ?thesis \n        using variableDefinedImpliesLiteralDefined [of \"literal\" \"valuation\"]\n        by auto\n    next\n      case False\n      with \\<open>model valuation (removeAll [literal] formula)\\<close> \n      have \"model (valuation @ [literal]) (removeAll [literal] formula)\"\n        by (rule modelExpand)\n      hence \n        \"formulaTrue (removeAll [literal] formula) (valuation @ [literal])\" and \"consistent (valuation @ [literal])\"\n        by auto\n      from \\<open>formulaTrue (removeAll [literal] formula) (valuation @ [literal])\\<close> \n      have \"formulaTrue formula (valuation @ [literal])\"\n        by (rule trueFormulaWithSingleLiteralClause)\n      with \\<open>consistent (valuation @ [literal])\\<close> \n      have \"model (valuation @ [literal]) formula\"\n        by simp\n      with \\<open>\\<not> satisfiable formula\\<close> \n      have \"False\"\n        by (auto simp add:satisfiable_def)\n      thus ?thesis ..\n    qed\n  }\n  thus ?thesis \n    by (simp add:formulaEntailsLiteral_def)\nqed\n\nlemma unsatisfiableFormulaWithSingleLiteralClauses:\n  fixes F::Formula and c::Clause\n  assumes \"\\<not> satisfiable (F @ val2form (oppositeLiteralList c))\" \"\\<not> clauseTautology c\"\n  shows \"formulaEntailsClause F c\"\nproof-\n  {\n    fix v::Valuation\n    assume \"model v F\"\n    with \\<open>\\<not> satisfiable (F @ val2form (oppositeLiteralList c))\\<close>\n    have \"\\<not> formulaTrue (val2form (oppositeLiteralList c)) v\"\n      unfolding satisfiable_def\n      by (auto simp add: formulaTrueAppend)\n    have \"clauseTrue c v\"\n    proof (cases \"\\<exists> l. l el c \\<and> (literalTrue l v)\")\n      case True\n      thus ?thesis\n        using clauseTrueIffContainsTrueLiteral\n        by simp\n    next\n      case False\n      let ?v' = \"v @ (oppositeLiteralList c)\"\n\n      have \"\\<not> inconsistent (oppositeLiteralList c)\"\n      proof-\n        {\n          assume \"\\<not> ?thesis\"\n          then obtain l::Literal\n            where \"l el (oppositeLiteralList c)\" \"opposite l el (oppositeLiteralList c)\"\n            using inconsistentCharacterization [of \"oppositeLiteralList c\"]\n            by auto\n          hence \"(opposite l) el c\" \"l el c\"\n            using literalElListIffOppositeLiteralElOppositeLiteralList[of \"l\" \"c\"]\n            using literalElListIffOppositeLiteralElOppositeLiteralList[of \"opposite l\" \"c\"]\n            by auto\n          hence \"clauseTautology c\"\n            using clauseTautologyCharacterization[of \"c\"]\n            by auto\n          with \\<open>\\<not> clauseTautology c\\<close>\n          have \"False\"\n            by simp\n        }\n        thus ?thesis\n          by auto\n      qed\n      with False \\<open>model v F\\<close>\n      have \"consistent ?v'\"\n        using inconsistentAppend[of \"v\" \"oppositeLiteralList c\"]\n        unfolding consistent_def\n        using literalElListIffOppositeLiteralElOppositeLiteralList\n        by auto\n      moreover\n      from \\<open>model v F\\<close>\n      have \"formulaTrue F ?v'\"\n        using formulaTrueAppendValuation\n        by simp\n      moreover\n      have \"formulaTrue (val2form (oppositeLiteralList c)) ?v'\"\n        using val2formFormulaTrue[of \"oppositeLiteralList c\" \"v @ oppositeLiteralList c\"]\n        by simp\n      ultimately\n      have \"model ?v' (F @ val2form (oppositeLiteralList c))\"\n        by (simp add: formulaTrueAppend)\n      with \\<open>\\<not> satisfiable (F @ val2form (oppositeLiteralList c))\\<close>\n      have \"False\"\n        unfolding satisfiable_def\n        by auto\n      thus ?thesis\n        by simp\n    qed\n  }\n  thus ?thesis\n    unfolding formulaEntailsClause_def\n    by simp\nqed\n\nlemma satisfiableEntailedFormula:\n  fixes formula0 :: Formula and formula :: Formula\n  assumes \"formulaEntailsFormula formula0 formula\"\n  shows \"satisfiable formula0 \\<longrightarrow> satisfiable formula\"\nproof\n  assume \"satisfiable formula0\"\n  show \"satisfiable formula\"\n  proof -\n    from \\<open>satisfiable formula0\\<close> obtain valuation :: Valuation\n      where \"model valuation formula0\" \n      by (auto simp add: satisfiable_def)\n    with \\<open>formulaEntailsFormula formula0 formula\\<close> \n    have \"model valuation formula\" \n      by (simp add: formulaEntailsFormula_def)\n    thus ?thesis \n      by (auto simp add: satisfiable_def)\n  qed\nqed\n\nlemma val2formIsEntailed:\nshows \"formulaEntailsValuation (F' @ val2form valuation @ F'') valuation\"\nproof-\n  {\n    fix l::Literal\n    assume \"l el valuation\"\n    hence \"[l] el val2form valuation\"\n      by (induct valuation) (auto)\n\n    have \"formulaEntailsLiteral (F' @ val2form valuation @ F'') l\"\n    proof-\n      {\n        fix valuation'::Valuation\n        assume \"formulaTrue (F' @ val2form valuation @ F'') valuation'\"\n        hence \"literalTrue l valuation'\"\n          using \\<open>[l] el val2form valuation\\<close>\n          using formulaTrueIffAllClausesAreTrue[of \"F' @ val2form valuation @ F''\" \"valuation'\"]\n          by (auto simp add: clauseTrueIffContainsTrueLiteral)\n      } thus ?thesis\n        unfolding formulaEntailsLiteral_def\n        by simp\n    qed\n  }\n  thus ?thesis\n    unfolding formulaEntailsValuation_def\n    by simp\nqed\n\n\n(*------------------------------------------------------------------*)\nsubsubsection\\<open>Equivalency\\<close>\n\ntext\\<open>Formulas are equivalent if they have same models.\\<close>\ndefinition equivalentFormulae :: \"Formula \\<Rightarrow> Formula \\<Rightarrow> bool\"\nwhere\n\"equivalentFormulae formula1 formula2 ==\n  \\<forall> (valuation::Valuation). model valuation formula1 = model valuation formula2\"\n\nlemma equivalentFormulaeIffEntailEachOther:\n  fixes formula1 :: Formula and formula2 :: Formula\n  shows \"equivalentFormulae formula1 formula2 = (formulaEntailsFormula formula1 formula2 \\<and> formulaEntailsFormula formula2 formula1)\"\nby (auto simp add:formulaEntailsFormula_def equivalentFormulae_def)\n\nlemma equivalentFormulaeReflexivity: \n  fixes formula :: Formula\n  shows \"equivalentFormulae formula formula\"\nunfolding equivalentFormulae_def\nby auto\n\nlemma equivalentFormulaeSymmetry: \n  fixes formula1 :: Formula and formula2 :: Formula\n  shows \"equivalentFormulae formula1 formula2 = equivalentFormulae formula2 formula1\"\nunfolding equivalentFormulae_def\nby auto\n\nlemma equivalentFormulaeTransitivity: \n  fixes formula1 :: Formula and formula2 :: Formula and formula3 :: Formula\n  assumes \"equivalentFormulae formula1 formula2\" and \"equivalentFormulae formula2 formula3\"\n  shows \"equivalentFormulae formula1 formula3\"\nusing assms\nunfolding equivalentFormulae_def\nby auto\n\nlemma equivalentFormulaeAppend: \n  fixes formula1 :: Formula and formula1' :: Formula and formula2 :: Formula\n  assumes \"equivalentFormulae formula1 formula1'\"\n  shows \"equivalentFormulae (formula1 @ formula2) (formula1' @ formula2)\"\nusing assms\nunfolding equivalentFormulae_def\nby (auto simp add: formulaTrueAppend)\n\nlemma satisfiableEquivalent: \n  fixes formula1 :: Formula and formula2 :: Formula\n  assumes \"equivalentFormulae formula1 formula2\"\n  shows \"satisfiable formula1 = satisfiable formula2\"\nusing assms\nunfolding equivalentFormulae_def\nunfolding satisfiable_def\nby auto\n\nlemma satisfiableEquivalentAppend: \n  fixes formula1 :: Formula and formula1' :: Formula and formula2 :: Formula\n  assumes \"equivalentFormulae formula1 formula1'\" and \"satisfiable (formula1 @ formula2)\"\n  shows \"satisfiable (formula1' @ formula2)\"\nusing assms\nproof -\n  from \\<open>satisfiable (formula1 @ formula2)\\<close> obtain valuation::Valuation\n    where \"consistent valuation\" \"formulaTrue formula1 valuation\" \"formulaTrue formula2 valuation\"\n    unfolding satisfiable_def\n    by (auto simp add: formulaTrueAppend)\n  from \\<open>equivalentFormulae formula1 formula1'\\<close> \\<open>consistent valuation\\<close> \\<open>formulaTrue formula1 valuation\\<close> \n  have \"formulaTrue formula1' valuation\"\n    unfolding equivalentFormulae_def\n    by auto\n  show ?thesis\n    using \\<open>consistent valuation\\<close> \\<open>formulaTrue formula1' valuation\\<close> \\<open>formulaTrue formula2 valuation\\<close>\n    unfolding satisfiable_def\n    by (auto simp add: formulaTrueAppend)\nqed\n\n\nlemma replaceEquivalentByEquivalent:\n  fixes formula :: Formula and formula' :: Formula and formula1 :: Formula and formula2 :: Formula\n  assumes \"equivalentFormulae formula formula'\" \n  shows \"equivalentFormulae (formula1 @ formula @ formula2) (formula1 @ formula' @ formula2)\"\nunfolding equivalentFormulae_def\nproof\n  fix v :: Valuation\n  show \"model v (formula1 @ formula @ formula2) = model v (formula1 @ formula' @ formula2)\"\n  proof\n    assume \"model v (formula1 @ formula @ formula2)\"\n    hence *: \"consistent v\" \"formulaTrue formula1 v\" \"formulaTrue formula v\" \"formulaTrue formula2 v\"\n      by (auto simp add: formulaTrueAppend)\n    from \\<open>consistent v\\<close> \\<open>formulaTrue formula v\\<close> \\<open>equivalentFormulae formula formula'\\<close>\n    have \"formulaTrue formula' v\"\n      unfolding equivalentFormulae_def\n      by auto\n    thus \"model v (formula1 @ formula' @ formula2)\"\n      using *\n      by (simp add: formulaTrueAppend)\n  next\n    assume \"model v (formula1 @ formula' @ formula2)\"\n    hence *: \"consistent v\" \"formulaTrue formula1 v\" \"formulaTrue formula' v\" \"formulaTrue formula2 v\"\n      by (auto simp add: formulaTrueAppend)\n    from \\<open>consistent v\\<close> \\<open>formulaTrue formula' v\\<close> \\<open>equivalentFormulae formula formula'\\<close>\n    have \"formulaTrue formula v\"\n      unfolding equivalentFormulae_def\n      by auto\n    thus \"model v (formula1 @ formula @ formula2)\"\n      using *\n      by (simp add: formulaTrueAppend)\n  qed\nqed\n\nlemma clauseOrderIrrelevant:\n  shows \"equivalentFormulae (F1 @ F @ F' @ F2) (F1 @ F' @ F @ F2)\"\nunfolding equivalentFormulae_def\nby (auto simp add: formulaTrueIffAllClausesAreTrue)\n\nlemma extendEquivalentFormulaWithEntailedClause:\n  fixes formula1 :: Formula and formula2 :: Formula and clause :: Clause\n  assumes \"equivalentFormulae formula1 formula2\" and \"formulaEntailsClause formula2 clause\"\n  shows \"equivalentFormulae formula1 (formula2 @ [clause])\"\n  unfolding equivalentFormulae_def\nproof\n  fix valuation :: Valuation\n  show \"model valuation formula1 = model valuation (formula2 @ [clause])\"\n  proof\n    assume \"model valuation formula1\"\n    hence \"consistent valuation\"\n      by simp\n    from \\<open>model valuation formula1\\<close> \\<open>equivalentFormulae formula1 formula2\\<close>\n    have \"model valuation formula2\"\n      unfolding equivalentFormulae_def\n      by simp\n    moreover\n    from \\<open>model valuation formula2\\<close> \\<open>formulaEntailsClause formula2 clause\\<close>\n    have \"clauseTrue clause valuation\"\n      unfolding formulaEntailsClause_def\n      by simp\n    ultimately show\n      \"model valuation (formula2 @ [clause])\"\n      by (simp add: formulaTrueAppend)\n  next\n    assume \"model valuation (formula2 @ [clause])\"\n    hence \"consistent valuation\"\n      by simp\n    from \\<open>model valuation (formula2 @ [clause])\\<close>\n    have \"model valuation formula2\"\n      by (simp add:formulaTrueAppend)\n    with \\<open>equivalentFormulae formula1 formula2\\<close>\n    show \"model valuation formula1\"\n      unfolding equivalentFormulae_def\n      by auto\n  qed\nqed\n\nlemma entailsLiteralRelpacePartWithEquivalent:\n  assumes \"equivalentFormulae F F'\" and \"formulaEntailsLiteral (F1 @ F @ F2) l\"\n  shows \"formulaEntailsLiteral (F1 @ F' @ F2) l\"\nproof-\n  {\n    fix v::Valuation\n    assume \"model v (F1 @ F' @ F2)\"\n    hence \"consistent v\" and \"formulaTrue F1 v\" and \"formulaTrue F' v\" and \"formulaTrue F2 v\"\n      by (auto simp add:formulaTrueAppend)\n    with \\<open>equivalentFormulae F F'\\<close>\n    have \"formulaTrue F v\"\n      unfolding equivalentFormulae_def\n      by auto\n    with \\<open>consistent v\\<close> \\<open>formulaTrue F1 v\\<close> \\<open>formulaTrue F2 v\\<close>\n    have \"model v (F1 @ F @ F2)\"\n      by (auto simp add:formulaTrueAppend)\n    with \\<open>formulaEntailsLiteral (F1 @ F @ F2) l\\<close>\n    have \"literalTrue l v\"\n      unfolding formulaEntailsLiteral_def\n      by auto\n  }\n  thus ?thesis\n    unfolding formulaEntailsLiteral_def\n    by auto\nqed\n\n\n\n(*--------------------------------------------------------------------------------*)\nsubsubsection\\<open>Remove false and duplicate literals of a clause\\<close>\n\ndefinition\nremoveFalseLiterals :: \"Clause \\<Rightarrow> Valuation \\<Rightarrow> Clause\"\nwhere\n\"removeFalseLiterals clause valuation = filter (\\<lambda> l. \\<not> literalFalse l valuation) clause\"\n\nlemma clauseTrueRemoveFalseLiterals:\n  assumes \"consistent v\"\n  shows \"clauseTrue c v = clauseTrue (removeFalseLiterals c v) v\"\nusing assms\nunfolding removeFalseLiterals_def\nby (auto simp add: clauseTrueIffContainsTrueLiteral inconsistentCharacterization)\n\nlemma clauseTrueRemoveDuplicateLiterals:\n  shows \"clauseTrue c v = clauseTrue (remdups c) v\"\nby (induct c) (auto simp add: clauseTrueIffContainsTrueLiteral)\n\nlemma removeDuplicateLiteralsEquivalentClause:\n  shows \"equivalentFormulae [remdups clause] [clause]\"\nunfolding equivalentFormulae_def\nby (auto simp add: formulaTrueIffAllClausesAreTrue clauseTrueIffContainsTrueLiteral)\n\nlemma falseLiteralsCanBeRemoved:\n(* val2form v - some single literal clauses *)\nfixes F::Formula and F'::Formula and v::Valuation\nassumes \"equivalentFormulae (F1 @ val2form v @ F2) F'\"\nshows \"equivalentFormulae (F1 @ val2form v @ [removeFalseLiterals c v] @ F2) (F' @ [c])\" \n            (is \"equivalentFormulae ?lhs ?rhs\")\nunfolding equivalentFormulae_def\nproof\n  fix v' :: Valuation\n  show \"model v' ?lhs = model v' ?rhs\"\n  proof\n    assume \"model v' ?lhs\"\n    hence \"consistent v'\" and  \n      \"formulaTrue (F1 @ val2form v @ F2) v'\" and \n      \"clauseTrue (removeFalseLiterals c v) v'\"\n      by (auto simp add: formulaTrueAppend formulaTrueIffAllClausesAreTrue)\n\n    from \\<open>consistent v'\\<close> \\<open>formulaTrue (F1 @ val2form v @ F2) v'\\<close> \\<open>equivalentFormulae (F1 @ val2form v @ F2) F'\\<close>\n    have \"model v' F'\"\n      unfolding equivalentFormulae_def\n      by auto\n    moreover\n    from \\<open>clauseTrue (removeFalseLiterals c v) v'\\<close>\n    have \"clauseTrue c v'\"\n      unfolding removeFalseLiterals_def\n      by (auto simp add: clauseTrueIffContainsTrueLiteral)\n    ultimately\n    show \"model v' ?rhs\"\n      by (simp add: formulaTrueAppend)\n  next\n    assume \"model v' ?rhs\"\n    hence \"consistent v'\" and \"formulaTrue F' v'\" and \"clauseTrue c v'\"\n      by (auto simp add: formulaTrueAppend formulaTrueIffAllClausesAreTrue)\n\n    from \\<open>consistent v'\\<close> \\<open>formulaTrue F' v'\\<close> \\<open>equivalentFormulae (F1 @ val2form v @ F2) F'\\<close>\n    have \"model v' (F1 @ val2form v @ F2)\"\n      unfolding equivalentFormulae_def\n      by auto\n    moreover\n    have \"clauseTrue (removeFalseLiterals c v) v'\"\n    proof-\n      from \\<open>clauseTrue c v'\\<close> \n      obtain l :: Literal\n        where \"l el c\" and \"literalTrue l v'\"\n        by (auto simp add: clauseTrueIffContainsTrueLiteral)\n      have \"\\<not> literalFalse l v\"\n      proof-\n        {\n          assume \"\\<not> ?thesis\"\n          hence \"opposite l el v\"\n            by simp\n          with \\<open>model v' (F1 @ val2form v @ F2)\\<close>\n          have \"opposite l el v'\"\n            using val2formFormulaTrue[of \"v\" \"v'\"]\n            by auto (simp add: formulaTrueAppend)\n          with \\<open>literalTrue l v'\\<close> \\<open>consistent v'\\<close>\n          have \"False\"\n            by (simp add: inconsistentCharacterization)\n        }\n        thus ?thesis\n          by auto\n      qed\n      with \\<open>l el c\\<close>\n      have  \"l el (removeFalseLiterals c v)\"\n        unfolding removeFalseLiterals_def\n        by simp\n      with \\<open>literalTrue l v'\\<close>\n      show ?thesis\n        by (auto simp add: clauseTrueIffContainsTrueLiteral)\n    qed\n    ultimately\n    show \"model v' ?lhs\"\n      by (simp add: formulaTrueAppend)\n  qed\nqed\n\nlemma falseAndDuplicateLiteralsCanBeRemoved:\n(* val2form v - some single literal clauses *)\nassumes \"equivalentFormulae (F1 @ val2form v @ F2) F'\"\nshows \"equivalentFormulae (F1 @ val2form v @ [remdups (removeFalseLiterals c v)] @ F2) (F' @ [c])\" \n  (is \"equivalentFormulae ?lhs ?rhs\")\nproof-\n  from \\<open>equivalentFormulae (F1 @ val2form v @ F2) F'\\<close> \n  have \"equivalentFormulae (F1 @ val2form v @ [removeFalseLiterals c v] @ F2) (F' @ [c])\"\n    using falseLiteralsCanBeRemoved\n    by simp\n  have \"equivalentFormulae [remdups (removeFalseLiterals c v)] [removeFalseLiterals c v]\"\n    using removeDuplicateLiteralsEquivalentClause\n    by simp\n  hence \"equivalentFormulae (F1 @ val2form v @ [remdups (removeFalseLiterals c v)] @ F2)\n    (F1 @ val2form v @ [removeFalseLiterals c v] @ F2)\"\n    using replaceEquivalentByEquivalent\n    [of \"[remdups (removeFalseLiterals c v)]\" \"[removeFalseLiterals c v]\" \"F1 @ val2form v\" \"F2\"]\n    by auto\n  thus ?thesis\n    using \\<open>equivalentFormulae (F1 @ val2form v @ [removeFalseLiterals c v] @ F2) (F' @ [c])\\<close>\n    using equivalentFormulaeTransitivity[of \n              \"(F1 @ val2form v @ [remdups (removeFalseLiterals c v)] @ F2)\"\n              \"(F1 @ val2form v @ [removeFalseLiterals c v] @ F2)\" \n              \"F' @ [c]\"]\n    by simp\nqed\n\n\n\nlemma formulaEntailsClauseRemoveEntailedLiteralOpposites:\nassumes\n  \"formulaEntailsClause F clause\"\n  \"formulaEntailsValuation F valuation\"\nshows\n  \"formulaEntailsClause F (list_diff clause (oppositeLiteralList valuation))\"\nproof-\n  {\n    fix valuation'\n    assume \"model valuation' F\"\n    hence \"consistent valuation'\" \"formulaTrue F valuation'\"\n      by (auto simp add: formulaTrueAppend)\n\n    have \"model valuation' clause\"\n      using \\<open>consistent valuation'\\<close>\n      using \\<open>formulaTrue F valuation'\\<close>\n      using \\<open>formulaEntailsClause F clause\\<close>\n      unfolding formulaEntailsClause_def\n      by simp\n\n    then obtain l::Literal\n      where \"l el clause\" \"literalTrue l valuation'\"\n      by (auto simp add: clauseTrueIffContainsTrueLiteral)\n    moreover\n    hence \"\\<not> l el (oppositeLiteralList valuation)\"\n    proof-\n      {\n        assume \"l el (oppositeLiteralList valuation)\"\n        hence \"(opposite l) el valuation\"\n          using literalElListIffOppositeLiteralElOppositeLiteralList[of \"l\" \"oppositeLiteralList valuation\"]\n          by simp\n        hence \"formulaEntailsLiteral F (opposite l)\"\n          using \\<open>formulaEntailsValuation F valuation\\<close>\n          unfolding formulaEntailsValuation_def\n          by simp\n        hence \"literalFalse l valuation'\"\n          using \\<open>consistent valuation'\\<close>\n          using \\<open>formulaTrue F valuation'\\<close>\n          unfolding formulaEntailsLiteral_def\n          by simp\n        with \\<open>literalTrue l valuation'\\<close>\n          \\<open>consistent valuation'\\<close>\n        have False\n          by (simp add: inconsistentCharacterization)\n      } thus ?thesis\n        by auto\n    qed\n    ultimately\n    have \"model valuation' (list_diff clause (oppositeLiteralList valuation))\"\n      using \\<open>consistent valuation'\\<close>\n      using listDiffIff[of \"l\" \"clause\" \"oppositeLiteralList valuation\"]\n      by (auto simp add: clauseTrueIffContainsTrueLiteral)\n  } thus ?thesis\n    unfolding formulaEntailsClause_def\n    by simp\nqed\n\n\n\n(*--------------------------------------------------------------------------------*)\nsubsubsection\\<open>Resolution\\<close>\n\ndefinition\n\"resolve clause1 clause2 literal == removeAll literal clause1 @ removeAll (opposite literal) clause2\"\n\nlemma resolventIsEntailed: \n  fixes clause1 :: Clause and clause2 :: Clause and literal :: Literal\n  shows \"formulaEntailsClause [clause1, clause2] (resolve clause1 clause2 literal)\"\nproof -\n  {\n    fix valuation :: Valuation\n    assume \"model valuation [clause1, clause2]\"\n    from \\<open>model valuation [clause1, clause2]\\<close> obtain l1 :: Literal\n      where \"l1 el clause1\" and \"literalTrue l1 valuation\"\n      by (auto simp add: formulaTrueIffAllClausesAreTrue clauseTrueIffContainsTrueLiteral)\n    from \\<open>model valuation [clause1, clause2]\\<close> obtain l2 :: Literal\n      where \"l2 el clause2\" and \"literalTrue l2 valuation\"\n      by (auto simp add: formulaTrueIffAllClausesAreTrue clauseTrueIffContainsTrueLiteral)\n    have \"clauseTrue (resolve clause1 clause2 literal) valuation\"\n    proof (cases \"literal = l1\")\n      case False\n      with \\<open>l1 el clause1\\<close> \n      have \"l1 el (resolve clause1 clause2 literal)\" \n        by (auto simp add:resolve_def)\n      with \\<open>literalTrue l1 valuation\\<close> \n      show ?thesis \n        by (auto simp add: clauseTrueIffContainsTrueLiteral)\n    next\n      case True\n      from \\<open>model valuation [clause1, clause2]\\<close> \n      have \"consistent valuation\" \n        by simp\n      from True \\<open>literalTrue l1 valuation\\<close> \\<open>literalTrue l2 valuation\\<close> \\<open>consistent valuation\\<close> \n      have \"literal \\<noteq> opposite l2\"\n        by (auto simp add:inconsistentCharacterization)\n      with \\<open>l2 el clause2\\<close> \n      have \"l2 el (resolve clause1 clause2 literal)\"\n        by (auto simp add:resolve_def)\n      with \\<open>literalTrue l2 valuation\\<close> \n      show ?thesis\n        by (auto simp add: clauseTrueIffContainsTrueLiteral)\n    qed\n  } \n  thus ?thesis \n    by (simp add: formulaEntailsClause_def)\nqed\n\nlemma formulaEntailsResolvent:\n  fixes formula :: Formula and clause1 :: Clause and clause2 :: Clause\n  assumes \"formulaEntailsClause formula clause1\" and \"formulaEntailsClause formula clause2\"\n  shows \"formulaEntailsClause formula (resolve clause1 clause2 literal)\"\nproof -\n  {\n    fix valuation :: Valuation\n    assume \"model valuation formula\"\n    hence \"consistent valuation\" \n      by simp\n    from \\<open>model valuation formula\\<close> \\<open>formulaEntailsClause formula clause1\\<close> \n    have \"clauseTrue clause1 valuation\"\n      by (simp add:formulaEntailsClause_def)\n    from \\<open>model valuation formula\\<close> \\<open>formulaEntailsClause formula clause2\\<close> \n    have \"clauseTrue clause2 valuation\"\n      by (simp add:formulaEntailsClause_def)\n    from \\<open>clauseTrue clause1 valuation\\<close> \\<open>clauseTrue clause2 valuation\\<close> \\<open>consistent valuation\\<close> \n    have \"clauseTrue (resolve clause1 clause2 literal) valuation\" \n      using resolventIsEntailed\n      by (auto simp add: formulaEntailsClause_def)\n    with \\<open>consistent valuation\\<close> \n    have \"model valuation (resolve clause1 clause2 literal)\"\n      by simp\n  }\n  thus ?thesis\n    by (simp add: formulaEntailsClause_def)\nqed\n\nlemma resolveFalseClauses:\n  fixes literal :: Literal and clause1 :: Clause and clause2 :: Clause and valuation :: Valuation\n  assumes \n  \"clauseFalse (removeAll literal clause1) valuation\" and\n  \"clauseFalse (removeAll (opposite literal) clause2) valuation\"\n  shows \"clauseFalse (resolve clause1 clause2 literal) valuation\"\nproof -\n  {\n    fix l :: Literal\n    assume \"l el (resolve clause1 clause2 literal)\"\n    have \"literalFalse l valuation\"\n    proof-\n      from \\<open>l el (resolve clause1 clause2 literal)\\<close> \n      have \"l el (removeAll literal clause1) \\<or> l el (removeAll (opposite literal) clause2)\"\n        unfolding resolve_def\n        by simp\n      thus ?thesis \n      proof\n        assume \"l el (removeAll literal clause1)\"\n        thus \"literalFalse l valuation\"\n          using \\<open>clauseFalse (removeAll literal clause1) valuation\\<close>\n          by (simp add: clauseFalseIffAllLiteralsAreFalse)\n      next\n        assume \"l el (removeAll (opposite literal) clause2)\"\n        thus \"literalFalse l valuation\"\n          using \\<open>clauseFalse (removeAll (opposite literal) clause2) valuation\\<close>\n          by (simp add: clauseFalseIffAllLiteralsAreFalse)\n      qed\n    qed\n  }\n  thus ?thesis\n    by (simp add: clauseFalseIffAllLiteralsAreFalse)\nqed\n\n(*--------------------------------------------------------------------------------*)\nsubsubsection\\<open>Unit clauses\\<close>\n\ntext\\<open>Clause is unit in a valuation if all its literals but one are false, and that one is undefined.\\<close>\ndefinition isUnitClause :: \"Clause \\<Rightarrow> Literal \\<Rightarrow> Valuation \\<Rightarrow> bool\"\nwhere\n\"isUnitClause uClause uLiteral valuation == \n   uLiteral el uClause \\<and> \n   \\<not> (literalTrue uLiteral valuation) \\<and> \n   \\<not> (literalFalse uLiteral valuation) \\<and> \n   (\\<forall> literal. literal el uClause \\<and> literal \\<noteq> uLiteral \\<longrightarrow> literalFalse literal valuation)\"\n\n\nlemma unitLiteralIsEntailed:\n  fixes uClause :: Clause and uLiteral :: Literal and formula :: Formula and valuation :: Valuation\n  assumes \"isUnitClause uClause uLiteral valuation\" and \"formulaEntailsClause formula uClause\"\n  shows \"formulaEntailsLiteral (formula @ val2form valuation) uLiteral\"\nproof -\n  {\n    fix valuation'\n    assume \"model valuation' (formula @ val2form valuation)\"\n    hence \"consistent valuation'\"\n      by simp\n    from \\<open>model valuation' (formula @ val2form valuation)\\<close> \n    have \"formulaTrue formula valuation'\" and \"formulaTrue (val2form valuation) valuation'\"\n      by (auto simp add:formulaTrueAppend)\n    from \\<open>formulaTrue formula valuation'\\<close> \\<open>consistent valuation'\\<close> \\<open>formulaEntailsClause formula uClause\\<close> \n    have \"clauseTrue uClause valuation'\"\n      by (simp add:formulaEntailsClause_def)\n    then obtain l :: Literal\n      where \"l el uClause\" \"literalTrue l valuation'\"\n      by (auto simp add: clauseTrueIffContainsTrueLiteral)\n    hence \"literalTrue uLiteral valuation'\" \n    proof (cases \"l = uLiteral\")\n      case True\n      with \\<open>literalTrue l valuation'\\<close> \n      show ?thesis\n        by simp\n    next\n      case False\n      with \\<open>l el uClause\\<close> \\<open>isUnitClause uClause uLiteral valuation\\<close> \n      have \"literalFalse l valuation\"\n        by (simp add: isUnitClause_def)\n      from \\<open>formulaTrue (val2form valuation) valuation'\\<close> \n      have \"\\<forall> literal :: Literal. literal el valuation \\<longrightarrow> literal el valuation'\"\n        using val2formFormulaTrue [of \"valuation\" \"valuation'\"]\n        by simp\n      with \\<open>literalFalse l valuation\\<close> \n      have \"literalFalse l valuation'\"\n        by auto\n      with \\<open>literalTrue l valuation'\\<close> \\<open>consistent valuation'\\<close> \n      have \"False\"\n        by (simp add:inconsistentCharacterization)\n      thus ?thesis ..\n    qed\n  }\n  thus ?thesis\n    by (simp add: formulaEntailsLiteral_def)\nqed\n\nlemma isUnitClauseRemoveAllUnitLiteralIsFalse: \n  fixes uClause :: Clause and uLiteral :: Literal and valuation :: Valuation\n  assumes \"isUnitClause uClause uLiteral valuation\"\n  shows \"clauseFalse (removeAll uLiteral uClause) valuation\"\nproof -\n  {\n    fix literal :: Literal\n    assume \"literal el (removeAll uLiteral uClause)\"\n    hence \"literal el uClause\" and \"literal \\<noteq> uLiteral\"\n      by auto\n    with \\<open>isUnitClause uClause uLiteral valuation\\<close> \n    have \"literalFalse literal valuation\"\n      by (simp add: isUnitClause_def)\n  }\n  thus ?thesis \n    by (simp add: clauseFalseIffAllLiteralsAreFalse)\nqed\n\nlemma isUnitClauseAppendValuation:\n  assumes \"isUnitClause uClause uLiteral valuation\" \"l \\<noteq> uLiteral\" \"l \\<noteq> opposite uLiteral\"\n  shows \"isUnitClause uClause uLiteral (valuation @ [l])\"\nusing assms\nunfolding isUnitClause_def\nby auto\n\nlemma containsTrueNotUnit:\nassumes\n  \"l el c\" and \"literalTrue l v\" and \"consistent v\"\nshows\n  \"\\<not> (\\<exists> ul. isUnitClause c ul v)\"\nusing assms\nunfolding isUnitClause_def\nby (auto simp add: inconsistentCharacterization)\n\nlemma unitBecomesFalse:\nassumes\n  \"isUnitClause uClause uLiteral valuation\" \nshows\n  \"clauseFalse uClause (valuation @ [opposite uLiteral])\"\nusing assms\nusing isUnitClauseRemoveAllUnitLiteralIsFalse[of \"uClause\" \"uLiteral\" \"valuation\"]\nby (auto simp add: clauseFalseIffAllLiteralsAreFalse)\n\n\n(*--------------------------------------------------------------------------------*)\nsubsubsection\\<open>Reason clauses\\<close>\n\ntext\\<open>A clause is @{term reason} for unit propagation of a given literal if it was a unit clause before it \n  is asserted, and became true when it is asserted.\\<close>\n  \ndefinition\nisReason::\"Clause \\<Rightarrow> Literal \\<Rightarrow> Valuation \\<Rightarrow> bool\"\nwhere\n\"(isReason clause literal valuation) ==\n  (literal el clause) \\<and> \n  (clauseFalse (removeAll literal clause) valuation) \\<and>\n  (\\<forall> literal'. literal' el (removeAll literal clause) \n       \\<longrightarrow> precedes (opposite literal') literal valuation \\<and> opposite literal' \\<noteq> literal)\"\n\nlemma isReasonAppend: \n  fixes clause :: Clause and literal :: Literal and valuation :: Valuation and valuation' :: Valuation\n  assumes \"isReason clause literal valuation\" \n  shows \"isReason clause literal (valuation @ valuation')\"\nproof -\n  from assms \n  have \"literal el clause\" and \n    \"clauseFalse (removeAll literal clause) valuation\" (is \"?false valuation\") and\n    \"\\<forall> literal'. literal' el (removeAll literal clause) \\<longrightarrow> \n          precedes (opposite literal') literal valuation \\<and> opposite literal' \\<noteq> literal\" (is \"?precedes valuation\")\n    unfolding isReason_def\n    by auto\n  moreover\n  from  \\<open>?false valuation\\<close> \n  have \"?false (valuation @ valuation')\"\n    by (rule clauseFalseAppendValuation)\n  moreover\n  from  \\<open>?precedes valuation\\<close> \n  have \"?precedes (valuation @ valuation')\"\n    by (simp add:precedesAppend)\n  ultimately \n  show ?thesis\n    unfolding isReason_def\n    by auto\nqed\n\nlemma isUnitClauseIsReason: \n  fixes uClause :: Clause and uLiteral :: Literal and valuation :: Valuation\n  assumes \"isUnitClause uClause uLiteral valuation\" \"uLiteral el valuation'\"\n  shows \"isReason uClause uLiteral (valuation @ valuation')\"\nproof -\n  from assms \n  have \"uLiteral el uClause\" and \"\\<not> literalTrue uLiteral valuation\" and \"\\<not> literalFalse uLiteral valuation\"\n    and \"\\<forall> literal. literal el uClause \\<and> literal \\<noteq> uLiteral \\<longrightarrow> literalFalse literal valuation\"\n    unfolding isUnitClause_def\n    by auto\n  hence \"clauseFalse (removeAll uLiteral uClause) valuation\" \n    by (simp add: clauseFalseIffAllLiteralsAreFalse)\n  hence \"clauseFalse (removeAll uLiteral uClause) (valuation @ valuation')\"\n    by (simp add: clauseFalseAppendValuation)\n  moreover\n  have \"\\<forall> literal'. literal' el (removeAll uLiteral uClause) \\<longrightarrow> \n    precedes (opposite literal') uLiteral (valuation @ valuation') \\<and> (opposite literal') \\<noteq> uLiteral\"\n  proof -\n    {\n      fix literal' :: Literal\n      assume \"literal' el (removeAll uLiteral uClause)\"\n      with \\<open>clauseFalse (removeAll uLiteral uClause) valuation\\<close> \n      have \"literalFalse literal' valuation\"\n        by (simp add:clauseFalseIffAllLiteralsAreFalse)\n      with \\<open>\\<not> literalTrue uLiteral valuation\\<close> \\<open>\\<not> literalFalse uLiteral valuation\\<close>\n      have \"precedes (opposite literal') uLiteral (valuation @ valuation') \\<and> (opposite literal') \\<noteq> uLiteral\"\n        using \\<open>uLiteral el valuation'\\<close>\n        using precedesMemberHeadMemberTail [of \"opposite literal'\" \"valuation\" \"uLiteral\" \"valuation'\"]\n        by auto\n    }\n    thus ?thesis \n      by simp\n  qed\n  ultimately\n  show ?thesis using \\<open>uLiteral el uClause\\<close>\n    by (auto simp add: isReason_def)\nqed\n\nlemma isReasonHoldsInPrefix: \n  fixes prefix :: Valuation and valuation :: Valuation and clause :: Clause and literal :: Literal\n  assumes \n  \"literal el prefix\" and \n  \"isPrefix prefix valuation\" and \n  \"isReason clause literal valuation\"\n  shows \n  \"isReason clause literal prefix\"\nproof -\n  from \\<open>isReason clause literal valuation\\<close> \n  have\n    \"literal el clause\" and \n    \"clauseFalse (removeAll literal clause) valuation\" (is \"?false valuation\") and\n    \"\\<forall> literal'. literal' el (removeAll literal clause) \\<longrightarrow> \n         precedes (opposite literal') literal valuation \\<and> opposite literal' \\<noteq> literal\" (is \"?precedes valuation\")\n    unfolding isReason_def\n    by auto\n  {\n    fix literal' :: Literal\n    assume \"literal' el (removeAll literal clause)\"\n    with \\<open>?precedes valuation\\<close> \n    have \"precedes (opposite literal') literal valuation\" \"(opposite literal') \\<noteq> literal\"\n      by auto\n    with \\<open>literal el prefix\\<close> \\<open>isPrefix prefix valuation\\<close>\n    have \"precedes (opposite literal') literal prefix \\<and> (opposite literal') \\<noteq> literal\" \n      using laterInPrefixRetainsPrecedes [of \"prefix\" \"valuation\" \"opposite literal'\" \"literal\"]\n      by auto\n  } \n  note * = this\n  hence \"?precedes prefix\"\n    by auto\n  moreover\n  have \"?false prefix\" \n  proof -\n    {\n      fix literal' :: Literal\n      assume \"literal' el (removeAll literal clause)\"\n      from \\<open>literal' el (removeAll literal clause)\\<close> * \n      have \"precedes (opposite literal') literal prefix\"\n        by simp\n      with \\<open>literal el prefix\\<close> \n      have \"literalFalse literal' prefix\"\n        unfolding precedes_def\n        by (auto split: if_split_asm)\n    }\n    thus ?thesis\n      by (auto simp add:clauseFalseIffAllLiteralsAreFalse)\n  qed\n  ultimately\n  show ?thesis using \\<open>literal el clause\\<close>\n    unfolding isReason_def\n    by auto\nqed\n\n\n(*--------------------------------------------------------------------------------*)\nsubsubsection\\<open>Last asserted literal of a list\\<close>\n\ntext\\<open>@{term lastAssertedLiteral} from a list is the last literal from a clause that is asserted in \n  a valuation.\\<close>\ndefinition \nisLastAssertedLiteral::\"Literal \\<Rightarrow> Literal list \\<Rightarrow> Valuation \\<Rightarrow> bool\"\nwhere\n\"isLastAssertedLiteral literal clause valuation ==\n  literal el clause \\<and> \n  literalTrue literal valuation \\<and> \n  (\\<forall> literal'. literal' el clause \\<and> literal' \\<noteq> literal \\<longrightarrow> \\<not> precedes literal literal' valuation)\"\n\ntext\\<open>Function that gets the last asserted literal of a list - specified only by its postcondition.\\<close>\ndefinition\ngetLastAssertedLiteral :: \"Literal list \\<Rightarrow> Valuation \\<Rightarrow> Literal\"\nwhere\n\"getLastAssertedLiteral clause valuation == \n   last (filter (\\<lambda> l::Literal. l el clause) valuation)\"\n\nlemma getLastAssertedLiteralCharacterization:\nassumes\n  \"clauseFalse clause valuation\"\n  \"clause \\<noteq> []\"\n  \"uniq valuation\"\nshows\n  \"isLastAssertedLiteral (getLastAssertedLiteral (oppositeLiteralList clause) valuation) (oppositeLiteralList clause) valuation\"\nproof-\n  let ?oppc = \"oppositeLiteralList clause\"\n  let ?l = \"getLastAssertedLiteral ?oppc valuation\"\n  let ?f = \"filter (\\<lambda> l. l el ?oppc) valuation\"\n\n  have \"?oppc \\<noteq> []\" \n    using \\<open>clause \\<noteq> []\\<close>\n    using oppositeLiteralListNonempty[of \"clause\"]\n    by simp\n  then obtain l'::Literal\n    where \"l' el ?oppc\"\n    by force\n  \n  have \"\\<forall> l::Literal. l el ?oppc \\<longrightarrow> l el valuation\"\n  proof\n    fix l::Literal\n    show \"l el ?oppc \\<longrightarrow> l el valuation\"\n    proof\n      assume \"l el ?oppc\"\n      hence \"opposite l el clause\"\n        using literalElListIffOppositeLiteralElOppositeLiteralList[of \"l\" \"?oppc\"]\n        by simp\n      thus \"l el valuation\"\n        using \\<open>clauseFalse clause valuation\\<close>\n        using clauseFalseIffAllLiteralsAreFalse[of \"clause\" \"valuation\"]\n        by auto\n    qed\n  qed\n  hence \"l' el valuation\"\n    using \\<open>l' el ?oppc\\<close>\n    by simp\n  hence \"l' el ?f\"\n    using \\<open>l' el ?oppc\\<close>\n    by simp\n  hence \"?f \\<noteq> []\"\n    using set_empty[of \"?f\"]\n    by auto\n  hence \"last ?f el ?f\"\n    using last_in_set[of \"?f\"]\n    by simp\n  hence \"?l el ?oppc\" \"literalTrue ?l valuation\"\n    unfolding getLastAssertedLiteral_def\n    by auto\n  moreover\n  have \"\\<forall>literal'. literal' el ?oppc \\<and> literal' \\<noteq> ?l \\<longrightarrow>\n                    \\<not> precedes ?l literal' valuation\"\n  proof\n    fix literal'\n    show \"literal' el ?oppc \\<and> literal' \\<noteq> ?l \\<longrightarrow> \\<not> precedes ?l literal' valuation\"\n    proof\n      assume \"literal' el ?oppc \\<and> literal' \\<noteq> ?l\"\n      show \"\\<not> precedes ?l literal' valuation\"\n      proof (cases \"literalTrue literal' valuation\")\n        case False\n        thus ?thesis\n          unfolding precedes_def\n          by simp\n      next\n        case True\n        with \\<open>literal' el ?oppc \\<and> literal' \\<noteq> ?l\\<close>\n        have \"literal' el ?f\"\n          by simp\n        have \"uniq ?f\"\n          using \\<open>uniq valuation\\<close>\n          by (simp add: uniqDistinct)\n        hence \"\\<not> precedes ?l literal' ?f\"\n          using lastPrecedesNoElement[of \"?f\"]\n          using \\<open>literal' el ?oppc \\<and> literal' \\<noteq> ?l\\<close>\n          unfolding getLastAssertedLiteral_def\n          by auto\n        thus ?thesis\n          using precedesFilter[of \"?l\" \"literal'\" \"valuation\" \"\\<lambda> l. l el ?oppc\"]\n          using \\<open>literal' el ?oppc \\<and> literal' \\<noteq> ?l\\<close>\n          using \\<open>?l el ?oppc\\<close>\n          by auto\n      qed\n    qed\n  qed\n  ultimately\n  show ?thesis\n    unfolding isLastAssertedLiteral_def\n    by simp\nqed\n\nlemma lastAssertedLiteralIsUniq: \n  fixes literal :: Literal and literal' :: Literal and literalList :: \"Literal list\" and valuation :: Valuation\n  assumes \n  lastL: \"isLastAssertedLiteral literal  literalList valuation\" and\n  lastL': \"isLastAssertedLiteral literal' literalList valuation\"\n  shows \"literal = literal'\"\nusing assms\nproof -\n  from lastL have *: \n    \"literal el literalList\"  \n    \"\\<forall> l. l el literalList \\<and> l \\<noteq> literal \\<longrightarrow> \\<not>  precedes literal l valuation\" \n    and\n    \"literalTrue literal valuation\"  \n    by (auto simp add: isLastAssertedLiteral_def)\n  from lastL' have **: \n    \"literal' el literalList\"\n    \"\\<forall> l. l el literalList \\<and> l \\<noteq> literal' \\<longrightarrow> \\<not>  precedes literal' l valuation\"\n    and\n    \"literalTrue literal' valuation\"\n    by (auto simp add: isLastAssertedLiteral_def)\n  {\n    assume \"literal' \\<noteq> literal\"\n    with * ** have \"\\<not> precedes literal literal' valuation\" and \"\\<not> precedes literal' literal valuation\"\n      by auto\n    with \\<open>literalTrue literal valuation\\<close> \\<open>literalTrue literal' valuation\\<close> \n    have \"False\"\n      using precedesTotalOrder[of \"literal\" \"valuation\" \"literal'\"]\n      unfolding precedes_def\n      by simp\n  }\n  thus ?thesis\n    by auto\nqed\n\nlemma isLastAssertedCharacterization: \n  fixes literal :: Literal and literalList :: \"Literal list\" and v :: Valuation\n  assumes \"isLastAssertedLiteral literal (oppositeLiteralList literalList) valuation\"\n  shows \"opposite literal el literalList\" and \"literalTrue literal valuation\"\nproof -\n  from assms have\n    *: \"literal el (oppositeLiteralList literalList)\" and **: \"literalTrue literal valuation\"  \n    by (auto simp add: isLastAssertedLiteral_def)\n  from * show \"opposite literal el literalList\"\n    using literalElListIffOppositeLiteralElOppositeLiteralList [of \"literal\" \"oppositeLiteralList literalList\"]\n    by simp\n  from ** show \"literalTrue literal valuation\" \n    by simp\nqed\n\nlemma isLastAssertedLiteralSubset:\nassumes\n  \"isLastAssertedLiteral l c M\"\n  \"set c' \\<subseteq> set c\"\n  \"l el c'\"\nshows\n  \"isLastAssertedLiteral l c' M\"\nusing assms\nunfolding isLastAssertedLiteral_def\nby auto\n\nlemma lastAssertedLastInValuation: \n  fixes literal :: Literal and literalList :: \"Literal list\" and valuation :: Valuation\n  assumes \"literal el literalList\" and \"\\<not> literalTrue literal valuation\" \n  shows \"isLastAssertedLiteral literal literalList (valuation @ [literal])\"\nproof -\n  have \"literalTrue literal [literal]\" \n    by simp\n  hence \"literalTrue literal (valuation @ [literal])\"\n    by simp\n  moreover\n  have \"\\<forall> l. l el literalList \\<and> l \\<noteq> literal \\<longrightarrow> \\<not>  precedes literal l (valuation @ [literal])\"\n  proof -\n    {\n      fix l\n      assume \"l el literalList\" \"l \\<noteq> literal\"\n      have \"\\<not> precedes literal l (valuation @ [literal])\" \n      proof (cases \"literalTrue l valuation\")\n        case False\n        with \\<open>l \\<noteq> literal\\<close> \n        show ?thesis\n          unfolding precedes_def\n          by simp\n      next\n        case True\n        from \\<open>\\<not> literalTrue literal valuation\\<close> \\<open>literalTrue literal [literal]\\<close> \\<open>literalTrue l valuation\\<close> \n        have \"precedes l literal (valuation @ [literal])\"\n          using precedesMemberHeadMemberTail[of \"l\" \"valuation\" \"literal\" \"[literal]\"]\n          by auto\n        with \\<open>l \\<noteq> literal\\<close> \\<open>literalTrue l valuation\\<close> \\<open>literalTrue literal [literal]\\<close>\n        show ?thesis\n          using precedesAntisymmetry[of \"l\" \"valuation @ [literal]\" \"literal\"]\n          unfolding precedes_def\n          by auto\n      qed\n    } thus ?thesis \n      by simp\n  qed\n  ultimately\n  show ?thesis using \\<open>literal el literalList\\<close>\n    by (simp add:isLastAssertedLiteral_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/SATSolverVerification/CNF.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8577680977182187, "lm_q2_score": 0.8221891305219504, "lm_q1q2_score": 0.7052476064524097}}
{"text": "section \\<open> Expression Type Class Instantiations \\<close>\n\ntheory utp_expr_insts\n  imports utp_expr\nbegin\n\ntext \\<open> It should be noted that instantiating the unary minus class, @{class uminus}, will also \n  provide negation UTP predicates later. \\<close>\n\ninstantiation uexpr :: (uminus, type) uminus\nbegin\n  definition uminus_uexpr_def [uexpr_defs]: \"- u = uop uminus u\"\ninstance ..\nend\n\ninstantiation uexpr :: (minus, type) minus\nbegin\n  definition minus_uexpr_def [uexpr_defs]: \"u - v = bop (-) u v\"\ninstance ..\nend\n\ninstantiation uexpr :: (times, type) times\nbegin\n  definition times_uexpr_def [uexpr_defs]: \"u * v = bop times u v\"\ninstance ..\nend\n\ninstance uexpr :: (Rings.dvd, type) Rings.dvd ..\n\ninstantiation uexpr :: (divide, type) divide\nbegin\n  definition divide_uexpr :: \"('a, 'b) uexpr \\<Rightarrow> ('a, 'b) uexpr \\<Rightarrow> ('a, 'b) uexpr\" where\n  [uexpr_defs]: \"divide_uexpr u v = bop divide u v\"\ninstance ..\nend\n\ninstantiation uexpr :: (inverse, type) inverse\nbegin\n  definition inverse_uexpr :: \"('a, 'b) uexpr \\<Rightarrow> ('a, 'b) uexpr\"\n  where [uexpr_defs]: \"inverse_uexpr u = uop inverse u\"\ninstance ..\nend\n\ninstantiation uexpr :: (modulo, type) modulo\nbegin\n  definition mod_uexpr_def [uexpr_defs]: \"u mod v = bop (mod) u v\"\ninstance ..\nend\n\ninstantiation uexpr :: (sgn, type) sgn\nbegin\n  definition sgn_uexpr_def [uexpr_defs]: \"sgn u = uop sgn u\"\ninstance ..\nend\n\ninstantiation uexpr :: (abs, type) abs\nbegin\n  definition abs_uexpr_def [uexpr_defs]: \"abs u = uop abs u\"\ninstance ..\nend\n\ntext \\<open> Once we've set up all the core constructs for arithmetic, we can also instantiate the \n  type classes for various algebras, including groups and rings. The proofs are done by \n  definitional expansion, the \\emph{transfer} tactic, and then finally the theorems of the underlying\n  HOL operators. This is mainly routine, so we don't comment further. \\<close>\n  \ninstance uexpr :: (semigroup_mult, type) semigroup_mult\n  by (intro_classes) (simp add: times_uexpr_def one_uexpr_def, transfer, simp add: mult.assoc)+\n\ninstance uexpr :: (monoid_mult, type) monoid_mult\n  by (intro_classes) (simp add: times_uexpr_def one_uexpr_def, transfer, simp)+\n\ninstance uexpr :: (monoid_add, type) monoid_add\n  by (intro_classes) (simp add: plus_uexpr_def zero_uexpr_def, transfer, simp)+\n\ninstance uexpr :: (ab_semigroup_add, type) ab_semigroup_add\n  by (intro_classes) (simp add: plus_uexpr_def, transfer, simp add: add.commute)+\n\ninstance uexpr :: (cancel_semigroup_add, type) cancel_semigroup_add\n  by (intro_classes) (simp add: plus_uexpr_def, transfer, simp add: fun_eq_iff)+\n\ninstance uexpr :: (cancel_ab_semigroup_add, type) cancel_ab_semigroup_add\n  by (intro_classes, (simp add: plus_uexpr_def minus_uexpr_def, transfer, simp add: fun_eq_iff add.commute cancel_ab_semigroup_add_class.diff_diff_add)+)\n\ninstance uexpr :: (group_add, type) group_add\n  by (intro_classes)\n     (simp add: plus_uexpr_def uminus_uexpr_def minus_uexpr_def zero_uexpr_def, transfer, simp)+\n\ninstance uexpr :: (ab_group_add, type) ab_group_add\n  by (intro_classes)\n     (simp add: plus_uexpr_def uminus_uexpr_def minus_uexpr_def zero_uexpr_def, transfer, simp)+\n\ninstance uexpr :: (semiring, type) semiring\n  by (intro_classes) (simp add: plus_uexpr_def times_uexpr_def, transfer, simp add: fun_eq_iff add.commute semiring_class.distrib_right semiring_class.distrib_left)+\n\ninstance uexpr :: (ring_1, type) ring_1\n  by (intro_classes) (simp add: plus_uexpr_def uminus_uexpr_def minus_uexpr_def times_uexpr_def zero_uexpr_def one_uexpr_def, transfer, simp add: fun_eq_iff)+\n\ntext \\<open> We also lift the properties from certain ordered groups. \\<close>\n  \ninstance uexpr :: (ordered_ab_group_add, type) ordered_ab_group_add\n  by (intro_classes) (simp add: plus_uexpr_def, transfer, simp)\n\ninstance uexpr :: (ordered_ab_group_add_abs, type) ordered_ab_group_add_abs\n  apply (intro_classes)\n      apply (simp add: abs_uexpr_def zero_uexpr_def plus_uexpr_def uminus_uexpr_def, transfer, simp add: abs_ge_self abs_le_iff abs_triangle_ineq)+\n  apply (metis ab_group_add_class.ab_diff_conv_add_uminus abs_ge_minus_self abs_ge_self add_mono_thms_linordered_semiring(1))\n  done\n\ntext \\<open> The next theorem lifts powers. \\<close>\n\nlemma power_rep_eq [ueval]: \"\\<lbrakk>P ^ n\\<rbrakk>\\<^sub>e = (\\<lambda> b. \\<lbrakk>P\\<rbrakk>\\<^sub>e b ^ n)\"\n  by (induct n, simp_all add: lit.rep_eq one_uexpr_def bop.rep_eq times_uexpr_def)\n\nlemma of_nat_uexpr_rep_eq [ueval]: \"\\<lbrakk>of_nat x\\<rbrakk>\\<^sub>e b = of_nat x\"\n  by (induct x, simp_all add: uexpr_defs ueval)\n\nlemma lit_uminus [lit_simps]: \"\\<guillemotleft>- x\\<guillemotright> = - \\<guillemotleft>x\\<guillemotright>\" by (simp add: uexpr_defs, transfer, simp)\nlemma lit_minus [lit_simps]: \"\\<guillemotleft>x - y\\<guillemotright> = \\<guillemotleft>x\\<guillemotright> - \\<guillemotleft>y\\<guillemotright>\" by (simp add: uexpr_defs, transfer, simp)\nlemma lit_times [lit_simps]: \"\\<guillemotleft>x * y\\<guillemotright> = \\<guillemotleft>x\\<guillemotright> * \\<guillemotleft>y\\<guillemotright>\" by (simp add: uexpr_defs, transfer, simp)\nlemma lit_divide [lit_simps]: \"\\<guillemotleft>x / y\\<guillemotright> = \\<guillemotleft>x\\<guillemotright> / \\<guillemotleft>y\\<guillemotright>\" by (simp add: uexpr_defs, transfer, simp)\nlemma lit_div [lit_simps]: \"\\<guillemotleft>x div y\\<guillemotright> = \\<guillemotleft>x\\<guillemotright> div \\<guillemotleft>y\\<guillemotright>\" by (simp add: uexpr_defs, transfer, simp)\nlemma lit_power [lit_simps]: \"\\<guillemotleft>x ^ n\\<guillemotright> = \\<guillemotleft>x\\<guillemotright> ^ n\" by (simp add: lit.rep_eq power_rep_eq uexpr_eq_iff)\n\nsubsection \\<open> Expression construction from HOL terms \\<close>\n\ntext \\<open> Sometimes it is convenient to cast HOL terms to UTP expressions, and these simplifications\n  automate this process. \\<close>\n\nnamed_theorems mkuexpr\n\nlemma mkuexpr_lens_get [mkuexpr]: \"mk\\<^sub>e get\\<^bsub>x\\<^esub> = &x\"\n  by (transfer, simp add: pr_var_def)\n\nlemma mkuexpr_zero [mkuexpr]: \"mk\\<^sub>e (\\<lambda> s. 0) = 0\"\n  by (simp add: zero_uexpr_def, transfer, simp)\n\nlemma mkuexpr_one [mkuexpr]: \"mk\\<^sub>e (\\<lambda> s. 1) = 1\"\n  by (simp add: one_uexpr_def, transfer, simp)\n\nlemma mkuexpr_numeral [mkuexpr]: \"mk\\<^sub>e (\\<lambda> s. numeral n) = numeral n\"\n  using lit_numeral_2 by blast\n\nlemma mkuexpr_lit [mkuexpr]: \"mk\\<^sub>e (\\<lambda> s. k) = \\<guillemotleft>k\\<guillemotright>\"\n  by (transfer, simp)\n\nlemma mkuexpr_pair [mkuexpr]: \"mk\\<^sub>e (\\<lambda>s. (f s, g s)) = (mk\\<^sub>e f, mk\\<^sub>e g)\\<^sub>u\"\n  by (transfer, simp)\n\nlemma mkuexpr_plus [mkuexpr]: \"mk\\<^sub>e (\\<lambda> s. f s + g s) = mk\\<^sub>e f + mk\\<^sub>e g\"\n  by (simp add: plus_uexpr_def, transfer, simp)\n\nlemma mkuexpr_uminus [mkuexpr]: \"mk\\<^sub>e (\\<lambda> s. - f s) = - mk\\<^sub>e f\"\n  by (simp add: uminus_uexpr_def, transfer, simp)\n\nlemma mkuexpr_minus [mkuexpr]: \"mk\\<^sub>e (\\<lambda> s. f s - g s) = mk\\<^sub>e f - mk\\<^sub>e g\"\n  by (simp add: minus_uexpr_def, transfer, simp)\n\nlemma mkuexpr_times [mkuexpr]: \"mk\\<^sub>e (\\<lambda> s. f s * g s) = mk\\<^sub>e f * mk\\<^sub>e g\"\n  by (simp add: times_uexpr_def, transfer, simp)\n\nlemma mkuexpr_divide [mkuexpr]: \"mk\\<^sub>e (\\<lambda> s. f s / g s) = mk\\<^sub>e f / mk\\<^sub>e g\"\n  by (simp add: divide_uexpr_def, transfer, simp)\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/utp/utp_expr_insts.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8807970873650401, "lm_q2_score": 0.8006920092299293, "lm_q1q2_score": 0.7052471896061836}}
{"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_SSortSorts\n  imports \"../../Test_Base\"\nbegin\n\ndatatype 'a list = nil2 | cons2 \"'a\" \"'a list\"\n\nfun ssortminimum1 :: \"int => int list => int\" where\n  \"ssortminimum1 x (nil2) = x\"\n| \"ssortminimum1 x (cons2 y1 ys1) =\n     (if y1 <= x then ssortminimum1 y1 ys1 else ssortminimum1 x ys1)\"\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 deleteBy :: \"('a => ('a => bool)) => 'a => 'a list =>\n                 'a list\" where\n  \"deleteBy x y (nil2) = nil2\"\n| \"deleteBy x y (cons2 y2 ys) =\n     (if (x y) y2 then ys else cons2 y2 (deleteBy x y ys))\"\n\n(*fun did not finish the proof*)\nfunction ssort :: \"int list => int list\" where\n  \"ssort (nil2) = nil2\"\n| \"ssort (cons2 y ys) =\n     (let m :: int = ssortminimum1 y ys\n     in cons2\n          m\n          (ssort\n             (deleteBy\n                (% (z :: int) => % (x2 :: int) => (z = x2)) m (cons2 y ys))))\"\n  by pat_completeness auto\n\ntheorem property0 :\n  \"ordered (ssort 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_SSortSorts.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970904940926, "lm_q2_score": 0.8006920044739461, "lm_q1q2_score": 0.7052471879225347}}
{"text": "(*  Title:      ZF/Nat.thy\n    Author:     Lawrence C Paulson, Cambridge University Computer Laboratory\n    Copyright   1994  University of Cambridge\n*)\n\nsection\\<open>The Natural numbers As a Least Fixed Point\\<close>\n\ntheory Nat imports OrdQuant Bool begin\n\ndefinition\n  nat :: i  where\n    \"nat \\<equiv> lfp(Inf, \\<lambda>X. {0} \\<union> {succ(i). i \\<in> X})\"\n\ndefinition\n  quasinat :: \"i \\<Rightarrow> o\"  where\n    \"quasinat(n) \\<equiv> n=0 | (\\<exists>m. n = succ(m))\"\n\ndefinition\n  (*Has an unconditional succ case, which is used in \"recursor\" below.*)\n  nat_case :: \"[i, i\\<Rightarrow>i, i]\\<Rightarrow>i\"  where\n    \"nat_case(a,b,k) \\<equiv> THE y. k=0 \\<and> y=a | (\\<exists>x. k=succ(x) \\<and> y=b(x))\"\n\ndefinition\n  nat_rec :: \"[i, i, [i,i]\\<Rightarrow>i]\\<Rightarrow>i\"  where\n    \"nat_rec(k,a,b) \\<equiv>\n          wfrec(Memrel(nat), k, \\<lambda>n f. nat_case(a, \\<lambda>m. b(m, f`m), n))\"\n\n  (*Internalized relations on the naturals*)\n\ndefinition\n  Le :: i  where\n    \"Le \\<equiv> {\\<langle>x,y\\<rangle>:nat*nat. x \\<le> y}\"\n\ndefinition\n  Lt :: i  where\n    \"Lt \\<equiv> {\\<langle>x, y\\<rangle>:nat*nat. x < y}\"\n\ndefinition\n  Ge :: i  where\n    \"Ge \\<equiv> {\\<langle>x,y\\<rangle>:nat*nat. y \\<le> x}\"\n\ndefinition\n  Gt :: i  where\n    \"Gt \\<equiv> {\\<langle>x,y\\<rangle>:nat*nat. y < x}\"\n\ndefinition\n  greater_than :: \"i\\<Rightarrow>i\"  where\n    \"greater_than(n) \\<equiv> {i \\<in> nat. n < i}\"\n\ntext\\<open>No need for a less-than operator: a natural number is its list of\npredecessors!\\<close>\n\n\nlemma nat_bnd_mono: \"bnd_mono(Inf, \\<lambda>X. {0} \\<union> {succ(i). i \\<in> X})\"\napply (rule bnd_monoI)\napply (cut_tac infinity, blast, blast)\ndone\n\n(* @{term\"nat = {0} \\<union> {succ(x). x \\<in> nat}\"} *)\nlemmas nat_unfold = nat_bnd_mono [THEN nat_def [THEN def_lfp_unfold]]\n\n(** Type checking of 0 and successor **)\n\nlemma nat_0I [iff,TC]: \"0 \\<in> nat\"\napply (subst nat_unfold)\napply (rule singletonI [THEN UnI1])\ndone\n\nlemma nat_succI [intro!,TC]: \"n \\<in> nat \\<Longrightarrow> succ(n) \\<in> nat\"\napply (subst nat_unfold)\napply (erule RepFunI [THEN UnI2])\ndone\n\nlemma nat_1I [iff,TC]: \"1 \\<in> nat\"\nby (rule nat_0I [THEN nat_succI])\n\nlemma nat_2I [iff,TC]: \"2 \\<in> nat\"\nby (rule nat_1I [THEN nat_succI])\n\nlemma bool_subset_nat: \"bool \\<subseteq> nat\"\nby (blast elim!: boolE)\n\nlemmas bool_into_nat = bool_subset_nat [THEN subsetD]\n\n\nsubsection\\<open>Injectivity Properties and Induction\\<close>\n\n(*Mathematical induction*)\nlemma nat_induct [case_names 0 succ, induct set: nat]:\n    \"\\<lbrakk>n \\<in> nat;  P(0);  \\<And>x. \\<lbrakk>x \\<in> nat;  P(x)\\<rbrakk> \\<Longrightarrow> P(succ(x))\\<rbrakk> \\<Longrightarrow> P(n)\"\nby (erule def_induct [OF nat_def nat_bnd_mono], blast)\n\nlemma natE:\n assumes \"n \\<in> nat\"\n obtains (\"0\") \"n=0\" | (succ) x where \"x \\<in> nat\" \"n=succ(x)\"\nusing assms\nby (rule nat_unfold [THEN equalityD1, THEN subsetD, THEN UnE]) auto\n\nlemma nat_into_Ord [simp]: \"n \\<in> nat \\<Longrightarrow> Ord(n)\"\nby (erule nat_induct, auto)\n\n(* @{term\"i \\<in> nat \\<Longrightarrow> 0 \\<le> i\"}; same thing as @{term\"0<succ(i)\"}  *)\nlemmas nat_0_le = nat_into_Ord [THEN Ord_0_le]\n\n(* @{term\"i \\<in> nat \\<Longrightarrow> i \\<le> i\"}; same thing as @{term\"i<succ(i)\"}  *)\nlemmas nat_le_refl = nat_into_Ord [THEN le_refl]\n\nlemma Ord_nat [iff]: \"Ord(nat)\"\napply (rule OrdI)\napply (erule_tac [2] nat_into_Ord [THEN Ord_is_Transset])\n  unfolding Transset_def\napply (rule ballI)\napply (erule nat_induct, auto)\ndone\n\nlemma Limit_nat [iff]: \"Limit(nat)\"\n  unfolding Limit_def\napply (safe intro!: ltI Ord_nat)\napply (erule ltD)\ndone\n\nlemma naturals_not_limit: \"a \\<in> nat \\<Longrightarrow> \\<not> Limit(a)\"\nby (induct a rule: nat_induct, auto)\n\nlemma succ_natD: \"succ(i): nat \\<Longrightarrow> i \\<in> nat\"\nby (rule Ord_trans [OF succI1], auto)\n\nlemma nat_succ_iff [iff]: \"succ(n): nat \\<longleftrightarrow> n \\<in> nat\"\nby (blast dest!: succ_natD)\n\nlemma nat_le_Limit: \"Limit(i) \\<Longrightarrow> nat \\<le> i\"\napply (rule subset_imp_le)\napply (simp_all add: Limit_is_Ord)\napply (rule subsetI)\napply (erule nat_induct)\n apply (erule Limit_has_0 [THEN ltD])\napply (blast intro: Limit_has_succ [THEN ltD] ltI Limit_is_Ord)\ndone\n\n(* \\<lbrakk>succ(i): k;  k \\<in> nat\\<rbrakk> \\<Longrightarrow> i \\<in> k *)\nlemmas succ_in_naturalD = Ord_trans [OF succI1 _ nat_into_Ord]\n\nlemma lt_nat_in_nat: \"\\<lbrakk>m<n;  n \\<in> nat\\<rbrakk> \\<Longrightarrow> m \\<in> nat\"\napply (erule ltE)\napply (erule Ord_trans, assumption, simp)\ndone\n\nlemma le_in_nat: \"\\<lbrakk>m \\<le> n; n \\<in> nat\\<rbrakk> \\<Longrightarrow> m \\<in> nat\"\nby (blast dest!: lt_nat_in_nat)\n\n\nsubsection\\<open>Variations on Mathematical Induction\\<close>\n\n(*complete induction*)\n\nlemmas complete_induct = Ord_induct [OF _ Ord_nat, case_names less, consumes 1]\n\nlemma complete_induct_rule [case_names less, consumes 1]:\n  \"i \\<in> nat \\<Longrightarrow> (\\<And>x. x \\<in> nat \\<Longrightarrow> (\\<And>y. y \\<in> x \\<Longrightarrow> P(y)) \\<Longrightarrow> P(x)) \\<Longrightarrow> P(i)\"\n  using complete_induct [of i P] by simp\n\n(*Induction starting from m rather than 0*)\nlemma nat_induct_from:\n  assumes \"m \\<le> n\" \"m \\<in> nat\" \"n \\<in> nat\"\n    and \"P(m)\"\n    and \"\\<And>x. \\<lbrakk>x \\<in> nat;  m \\<le> x;  P(x)\\<rbrakk> \\<Longrightarrow> P(succ(x))\"\n  shows \"P(n)\"\nproof -\n  from assms(3) have \"m \\<le> n \\<longrightarrow> P(m) \\<longrightarrow> P(n)\"\n    by (rule nat_induct) (use assms(5) in \\<open>simp_all add: distrib_simps le_succ_iff\\<close>)\n  with assms(1,2,4) show ?thesis by blast\nqed\n\n(*Induction suitable for subtraction and less-than*)\nlemma diff_induct [case_names 0 0_succ succ_succ, consumes 2]:\n    \"\\<lbrakk>m \\<in> nat;  n \\<in> nat;\n        \\<And>x. x \\<in> nat \\<Longrightarrow> P(x,0);\n        \\<And>y. y \\<in> nat \\<Longrightarrow> P(0,succ(y));\n        \\<And>x y. \\<lbrakk>x \\<in> nat;  y \\<in> nat;  P(x,y)\\<rbrakk> \\<Longrightarrow> P(succ(x),succ(y))\\<rbrakk>\n     \\<Longrightarrow> P(m,n)\"\napply (erule_tac x = m in rev_bspec)\napply (erule nat_induct, simp)\napply (rule ballI)\napply (rename_tac i j)\napply (erule_tac n=j in nat_induct, auto)\ndone\n\n\n(** Induction principle analogous to trancl_induct **)\n\nlemma succ_lt_induct_lemma [rule_format]:\n     \"m \\<in> nat \\<Longrightarrow> P(m,succ(m)) \\<longrightarrow> (\\<forall>x\\<in>nat. P(m,x) \\<longrightarrow> P(m,succ(x))) \\<longrightarrow>\n                 (\\<forall>n\\<in>nat. m<n \\<longrightarrow> P(m,n))\"\napply (erule nat_induct)\n apply (intro impI, rule nat_induct [THEN ballI])\n   prefer 4 apply (intro impI, rule nat_induct [THEN ballI])\napply (auto simp add: le_iff)\ndone\n\nlemma succ_lt_induct:\n    \"\\<lbrakk>m<n;  n \\<in> nat;\n        P(m,succ(m));\n        \\<And>x. \\<lbrakk>x \\<in> nat;  P(m,x)\\<rbrakk> \\<Longrightarrow> P(m,succ(x))\\<rbrakk>\n     \\<Longrightarrow> P(m,n)\"\nby (blast intro: succ_lt_induct_lemma lt_nat_in_nat)\n\nsubsection\\<open>quasinat: to allow a case-split rule for \\<^term>\\<open>nat_case\\<close>\\<close>\n\ntext\\<open>True if the argument is zero or any successor\\<close>\n\n\nlemma [iff]: \"quasinat(succ(x))\"\nby (simp add: quasinat_def)\n\nlemma nat_imp_quasinat: \"n \\<in> nat \\<Longrightarrow> quasinat(n)\"\nby (erule natE, simp_all)\n\nlemma non_nat_case: \"\\<not> quasinat(x) \\<Longrightarrow> nat_case(a,b,x) = 0\"\nby (simp add: quasinat_def nat_case_def)\n\nlemma nat_cases_disj: \"k=0 | (\\<exists>y. k = succ(y)) | \\<not> quasinat(k)\"\napply (case_tac \"k=0\", simp)\napply (case_tac \"\\<exists>m. k = succ(m)\")\napply (simp_all add: quasinat_def)\ndone\n\nlemma nat_cases:\n     \"\\<lbrakk>k=0 \\<Longrightarrow> P;  \\<And>y. k = succ(y) \\<Longrightarrow> P; \\<not> quasinat(k) \\<Longrightarrow> P\\<rbrakk> \\<Longrightarrow> P\"\nby (insert nat_cases_disj [of k], blast)\n\n(** nat_case **)\n\nlemma nat_case_0 [simp]: \"nat_case(a,b,0) = a\"\nby (simp add: nat_case_def)\n\nlemma nat_case_succ [simp]: \"nat_case(a,b,succ(n)) = b(n)\"\nby (simp add: nat_case_def)\n\nlemma nat_case_type [TC]:\n    \"\\<lbrakk>n \\<in> nat;  a \\<in> C(0);  \\<And>m. m \\<in> nat \\<Longrightarrow> b(m): C(succ(m))\\<rbrakk>\n     \\<Longrightarrow> nat_case(a,b,n) \\<in> C(n)\"\nby (erule nat_induct, auto)\n\nlemma split_nat_case:\n  \"P(nat_case(a,b,k)) \\<longleftrightarrow>\n   ((k=0 \\<longrightarrow> P(a)) \\<and> (\\<forall>x. k=succ(x) \\<longrightarrow> P(b(x))) \\<and> (\\<not> quasinat(k) \\<longrightarrow> P(0)))\"\napply (rule nat_cases [of k])\napply (auto simp add: non_nat_case)\ndone\n\n\nsubsection\\<open>Recursion on the Natural Numbers\\<close>\n\n(** nat_rec is used to define eclose and transrec, then becomes obsolete.\n    The operator rec, from arith.thy, has fewer typing conditions **)\n\nlemma nat_rec_0: \"nat_rec(0,a,b) = a\"\napply (rule nat_rec_def [THEN def_wfrec, THEN trans])\n apply (rule wf_Memrel)\napply (rule nat_case_0)\ndone\n\nlemma nat_rec_succ: \"m \\<in> nat \\<Longrightarrow> nat_rec(succ(m),a,b) = b(m, nat_rec(m,a,b))\"\napply (rule nat_rec_def [THEN def_wfrec, THEN trans])\n apply (rule wf_Memrel)\napply (simp add: vimage_singleton_iff)\ndone\n\n(** The union of two natural numbers is a natural number -- their maximum **)\n\nlemma Un_nat_type [TC]: \"\\<lbrakk>i \\<in> nat; j \\<in> nat\\<rbrakk> \\<Longrightarrow> i \\<union> j \\<in> nat\"\napply (rule Un_least_lt [THEN ltD])\napply (simp_all add: lt_def)\ndone\n\nlemma Int_nat_type [TC]: \"\\<lbrakk>i \\<in> nat; j \\<in> nat\\<rbrakk> \\<Longrightarrow> i \\<inter> j \\<in> nat\"\napply (rule Int_greatest_lt [THEN ltD])\napply (simp_all add: lt_def)\ndone\n\n(*needed to simplify unions over nat*)\nlemma nat_nonempty [simp]: \"nat \\<noteq> 0\"\nby blast\n\ntext\\<open>A natural number is the set of its predecessors\\<close>\nlemma nat_eq_Collect_lt: \"i \\<in> nat \\<Longrightarrow> {j\\<in>nat. j<i} = i\"\napply (rule equalityI)\napply (blast dest: ltD)\napply (auto simp add: Ord_mem_iff_lt)\napply (blast intro: lt_trans)\ndone\n\nlemma Le_iff [iff]: \"\\<langle>x,y\\<rangle> \\<in> Le \\<longleftrightarrow> x \\<le> y \\<and> x \\<in> nat \\<and> y \\<in> nat\"\nby (force simp add: Le_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/ZF/Nat.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8807970873650403, "lm_q2_score": 0.8006920068519376, "lm_q1q2_score": 0.7052471875116555}}
{"text": "theory Exercise5\n  imports 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\ninductive iter :: \"('a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> nat \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> bool\" for r where\nrefli: \"iter r 0 x x\" |\nstepi: \"r x y \\<Longrightarrow> iter r n y z \\<Longrightarrow> iter r (Suc n) x z\"\n\ntheorem \"iter r n x y \\<Longrightarrow> star r x y\"\nproof (induction rule: iter.induct)\n  case (refli x)\n  thus ?case by (rule star.refl)\nnext\n  case (stepi x y n z)\n  thus ?case by (auto intro: star.step)\nqed\n\nend\n", "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/ch5/Exercise5.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8807970779778825, "lm_q2_score": 0.8006920020959544, "lm_q1q2_score": 0.7052471758063772}}
{"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.*)\n  theory TIP_prop_38\n  imports \"../../Test_Base\"\nbegin\n\ndatatype 'a list = nil2 | cons2 \"'a\" \"'a list\"\n\ndatatype Nat = Z | S \"Nat\"\n\nfun z :: \"'a list => 'a list => 'a list\" where\n  \"z (nil2) y2 = y2\"\n| \"z (cons2 z2 xs) y2 = cons2 z2 (z xs y2)\"\n\nfun y :: \"Nat => Nat => bool\" where\n  \"y (Z) (Z) = True\"\n| \"y (Z) (S z2) = False\"\n| \"y (S x22) (Z) = False\"\n| \"y (S x22) (S y22) = y x22 y22\"\n\nfun x :: \"bool => bool => bool\" where\n  \"x True y2 = True\"\n| \"x False y2 = y2\"\n\nfun elem :: \"Nat => Nat list => bool\" where\n  \"elem x2 (nil2) = False\"\n| \"elem x2 (cons2 z2 xs) = x (y x2 z2) (elem x2 xs)\"\n\ntheorem property0 :\n  \"((elem x2 y2) ==> ((elem x2 z2) ==> (elem x2 (z y2 z2))))\"\n  apply(induction y2, auto)\n  apply(case_tac \"y x2 x1\", auto)\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_38.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.880797071719777, "lm_q2_score": 0.8006920044739461, "lm_q1q2_score": 0.7052471728900902}}
{"text": "theory Metric_Arith_Examples\nimports \"HOL-Analysis.Elementary_Metric_Spaces\"\nbegin\n\n\ntext \\<open>simple examples\\<close>\n\nlemma \"\\<exists>x::'a::metric_space. x=x\"\n  by metric\nlemma \"\\<forall>(x::'a::metric_space). \\<exists>y. x = y\"\n  by metric\n\n\ntext \\<open>reasoning with \"dist x y = 0 \\<longleftrightarrow> x = y\"\\<close>\n\nlemma \"\\<exists>x y. dist x y = 0\"\n  by metric\n\nlemma \"\\<exists>y. dist x y = 0\"\n  by metric\n\nlemma \"0 = dist x y \\<Longrightarrow> x = y\"\n  by metric\n\nlemma \"x \\<noteq> y \\<Longrightarrow> dist x y \\<noteq> 0\"\n  by metric\n\nlemma \"\\<exists>y. dist x y \\<noteq> 1\"\n  by metric\n\nlemma \"x = y \\<longleftrightarrow> dist x x = dist y x \\<and> dist x y = dist y y\"\n  by metric\n\nlemma \"dist a b \\<noteq> dist a c \\<Longrightarrow> b \\<noteq> c\"\n  by metric\n\ntext \\<open>reasoning with positive semidefiniteness\\<close>\n\nlemma \"dist y x + c \\<ge> c\"\n  by metric\n\nlemma \"dist x y + dist x z \\<ge> 0\"\n  by metric\n\nlemma \"dist x y \\<ge> v \\<Longrightarrow> dist x y + dist (a::'a) b \\<ge> v\" for x::\"('a::metric_space)\"\n  by metric\n\nlemma \"dist x y < 0 \\<longrightarrow> P\"\n  by metric\n\ntext \\<open>reasoning with the triangle inequality\\<close>\n\nlemma \"dist a d \\<le> dist a b + dist b c + dist c d\"\n  by metric\n\nlemma \"dist a e \\<le> dist a b + dist b c + dist c d + dist d e\"\n  by metric\n\nlemma \"max (dist x y) \\<bar>dist x z - dist z y\\<bar> = dist x y\"\n  by metric\n\nlemma\n  \"dist w x < e/3 \\<Longrightarrow> dist x y < e/3 \\<Longrightarrow> dist y z < e/3 \\<Longrightarrow> dist w x < e\"\n  by metric\n\nlemma \"dist w x < e/4 \\<Longrightarrow> dist x y < e/4 \\<Longrightarrow> dist y z < e/2 \\<Longrightarrow> dist w z < e\"\n  by metric\n\n\ntext \\<open>more complex examples\\<close>\n\nlemma \"dist x y \\<le> e \\<Longrightarrow> dist x z \\<le> e \\<Longrightarrow> dist y z \\<le> e\n  \\<Longrightarrow> p \\<in> (cball x e \\<union> cball y e \\<union> cball z e) \\<Longrightarrow> dist p x \\<le> 2*e\"\n  by metric\n\nlemma hol_light_example:\n  \"\\<not> disjnt (ball x r) (ball y s) \\<longrightarrow>\n    (\\<forall>p q. p \\<in> ball x r \\<union> ball y s \\<and> q \\<in> ball x r \\<union> ball y s \\<longrightarrow> dist p q < 2 * (r + s))\"\n  unfolding disjnt_iff\n  by metric\n\nlemma \"dist x y \\<le> e \\<Longrightarrow> z \\<in> ball x f \\<Longrightarrow> dist z y < e + f\"\n  by metric\n\nlemma \"dist x y = r / 2 \\<Longrightarrow> (\\<forall>z. dist x z < r / 4 \\<longrightarrow> dist y z \\<le> 3 * r / 4)\"\n  by metric\n\nlemma \"s \\<ge> 0 \\<Longrightarrow> t \\<ge> 0 \\<Longrightarrow> z \\<in> (ball x s) \\<union> (ball y t) \\<Longrightarrow> dist z y \\<le> dist x y + s + t\"\n  by metric\n\nlemma \"0 < r \\<Longrightarrow> ball x r \\<subseteq> ball y s \\<Longrightarrow> ball x r \\<subseteq> ball z t \\<Longrightarrow> dist y z \\<le> s + t\"\n  by metric\n\n\ntext \\<open>non-trivial quantifier structure\\<close>\n\nlemma \"\\<exists>x. \\<forall>r\\<le>0. \\<exists>z. dist x z \\<ge> r\"\n  by metric\n\nlemma \"\\<And>a r x y. dist x a + dist a y = r \\<Longrightarrow> \\<forall>z. r \\<le> dist x z + dist z y \\<Longrightarrow> dist x y = r\"\n  by metric\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/ex/Metric_Arith_Examples.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970685907242, "lm_q2_score": 0.800691997339971, "lm_q1q2_score": 0.7052471641010983}}
{"text": "theory ExF006\n  imports Main\nbegin\n  \n  \nlemma \"(\\<exists>x. \\<forall>y. P x y) \\<longrightarrow> (\\<forall>y. \\<exists>x. P x y)\" \nproof -\n  {\n    assume \"\\<exists>x. \\<forall>y. P x y\" \n    { \n      fix b\n      {\n        fix a           \n        assume \"\\<forall>y .P a y\"\n        hence \"P a b\" by (rule allE)\n        hence \"\\<exists>x. P x b\" by (rule exI)\n      } \n      with  \\<open>\\<exists>x. \\<forall>y. P x y\\<close> have \"\\<exists>x. P x b\" by (rule exE)\n    }\n    hence \"\\<forall>y. \\<exists>x. P x y\" by (rule allI)\n  }\n  thus ?thesis by (rule impI)\nqed\n  \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/FOL/ExF006.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9136765281148513, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.7052152921488059}}
{"text": "\\<^marker>\\<open>creator \"Kevin Kappelmann\"\\<close>\nparagraph \\<open>Antisymmetric\\<close>\ntheory Binary_Relations_Antisymmetric\n  imports\n    Binary_Relation_Functions\n    HOL_Syntax_Bundles_Lattices\nbegin\n\nconsts antisymmetric_on :: \"'a \\<Rightarrow> ('b \\<Rightarrow> 'b \\<Rightarrow> bool) \\<Rightarrow> bool\"\n\noverloading\n  antisymmetric_on_pred \\<equiv> \"antisymmetric_on :: ('a \\<Rightarrow> bool) \\<Rightarrow> ('a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> bool\"\nbegin\n  definition \"antisymmetric_on_pred P R \\<equiv> \\<forall>x y. P x \\<and> P y \\<and> R x y \\<and> R y x \\<longrightarrow> x = y\"\nend\n\nlemma antisymmetric_onI [intro]:\n  assumes \"\\<And>x y. P x \\<Longrightarrow> P y \\<Longrightarrow> R x y \\<Longrightarrow> R y x \\<Longrightarrow> x = y\"\n  shows \"antisymmetric_on P R\"\n  unfolding antisymmetric_on_pred_def using assms by blast\n\nlemma antisymmetric_onD:\n  assumes \"antisymmetric_on P R\"\n  and \"P x\" \"P y\"\n  and \"R x y\" \"R y x\"\n  shows \"x = y\"\n  using assms unfolding antisymmetric_on_pred_def by blast\n\ndefinition \"antisymmetric (R :: 'a \\<Rightarrow> _) \\<equiv> antisymmetric_on (\\<top> :: 'a \\<Rightarrow> bool) R\"\n\nlemma antisymmetric_eq_antisymmetric_on:\n  \"antisymmetric (R :: 'a \\<Rightarrow> _) = antisymmetric_on (\\<top> :: 'a \\<Rightarrow> bool) R\"\n  unfolding antisymmetric_def ..\n\nlemma antisymmetricI [intro]:\n  assumes \"\\<And>x y. R x y \\<Longrightarrow> R y x \\<Longrightarrow> x = y\"\n  shows \"antisymmetric R\"\n  unfolding antisymmetric_eq_antisymmetric_on using assms\n  by (intro antisymmetric_onI)\n\nlemma antisymmetricD:\n  assumes \"antisymmetric R\"\n  and \"R x y\" \"R y x\"\n  shows \"x = y\"\n  using assms unfolding antisymmetric_eq_antisymmetric_on\n  by (auto dest: antisymmetric_onD)\n\nlemma antisymmetric_on_if_antisymmetric:\n  fixes P :: \"'a \\<Rightarrow> bool\" and R :: \"'a \\<Rightarrow> _\"\n  assumes \"antisymmetric R\"\n  shows \"antisymmetric_on P R\"\n  using assms by (intro antisymmetric_onI) (blast dest: antisymmetricD)\n\nlemma antisymmetric_if_antisymmetric_on_in_field:\n  assumes \"antisymmetric_on (in_field R) R\"\n  shows \"antisymmetric R\"\n  using assms by (intro antisymmetricI) (blast dest: antisymmetric_onD)\n\ncorollary antisymmetric_on_in_field_iff_antisymmetric [simp]:\n  \"antisymmetric_on (in_field R) R \\<longleftrightarrow> antisymmetric R\"\n  using antisymmetric_if_antisymmetric_on_in_field antisymmetric_on_if_antisymmetric\n  by blast\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_Antisymmetric.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339676722393, "lm_q2_score": 0.8397339596505965, "lm_q1q2_score": 0.7051531297265154}}
{"text": "section \\<open>The Decomposition Theorem\\<close>\n\ntext \\<open>This theory contains a proof of the fact, that every polyhedron can be decomposed\n  into a convex hull of a finite set of points + a finitely generated cone, including bounds\n  on the numbers that are required in the decomposition.\n  We further prove the inverse direction of this theorem (without bounds) and\n  as a corollary, we derive that a polyhedron is bounded iff it is the convex hull\n  of finitely many points, i.e., a polytope.\\<close>\n\ntheory Decomposition_Theorem\n  imports\n    Farkas_Minkowsky_Weyl\n    Convex_Hull\nbegin\n\ncontext gram_schmidt\nbegin\n\ndefinition \"polytope P = (\\<exists> V. V \\<subseteq> carrier_vec n \\<and> finite V \\<and> P = convex_hull V)\"\n\ndefinition \"polyhedron A b = {x \\<in> carrier_vec n. A *\\<^sub>v x \\<le> b}\"\n\nlemma polyhedra_are_convex:\n  assumes A: \"A \\<in> carrier_mat nr n\"\n    and b: \"b \\<in> carrier_vec nr\"\n    and P: \"P = polyhedron A b\"\n  shows \"convex P\"\nproof (intro convexI)\n  show Pcarr: \"P \\<subseteq> carrier_vec n\" using assms unfolding polyhedron_def by auto\n  fix a :: 'a and x y\n  assume xy: \"x \\<in> P\" \"y \\<in> P\" and a: \"0 \\<le> a\" \"a \\<le> 1\"\n  from xy[unfolded P polyhedron_def]\n  have x: \"x \\<in> carrier_vec n\" and y: \"y \\<in> carrier_vec n\" and le: \"A *\\<^sub>v x \\<le> b\" \"A *\\<^sub>v y \\<le> b\" by auto\n  show \"a \\<cdot>\\<^sub>v x + (1 - a) \\<cdot>\\<^sub>v y \\<in> P\" unfolding P polyhedron_def\n  proof (intro CollectI conjI)\n    from x have ax: \"a \\<cdot>\\<^sub>v x \\<in> carrier_vec n\" by auto\n    from y have ay: \"(1 - a) \\<cdot>\\<^sub>v y \\<in> carrier_vec n\" by auto\n    show \"a \\<cdot>\\<^sub>v x + (1 - a) \\<cdot>\\<^sub>v y \\<in> carrier_vec n\" using ax ay by auto\n    show \"A *\\<^sub>v (a \\<cdot>\\<^sub>v x + (1 - a) \\<cdot>\\<^sub>v y) \\<le> b\"\n    proof (intro lesseq_vecI[OF _ b])\n      show \"A *\\<^sub>v (a \\<cdot>\\<^sub>v x + (1 - a) \\<cdot>\\<^sub>v y) \\<in> carrier_vec nr\" using A x y by auto\n      fix i\n      assume i: \"i < nr\"\n      from lesseq_vecD[OF b le(1) i] lesseq_vecD[OF b le(2) i]\n      have le: \"(A *\\<^sub>v x) $ i \\<le> b $ i\" \"(A *\\<^sub>v y) $ i \\<le> b $ i\" by auto\n      have \"(A *\\<^sub>v (a \\<cdot>\\<^sub>v x + (1 - a) \\<cdot>\\<^sub>v y)) $ i = a * (A *\\<^sub>v x) $ i + (1 - a) * (A *\\<^sub>v y) $ i\"\n        using A x y i by (auto simp: scalar_prod_add_distrib[of _ n])\n      also have \"\\<dots> \\<le> a * b $ i + (1 - a) * b $ i\"\n        by (rule add_mono; rule mult_left_mono, insert le a, auto)\n      also have \"\\<dots> = b $ i\" by (auto simp: field_simps)\n      finally show \"(A *\\<^sub>v (a \\<cdot>\\<^sub>v x + (1 - a) \\<cdot>\\<^sub>v y)) $ i \\<le> b $ i\" .\n    qed\n  qed\nqed\n\nend\n\n\n\nlocale gram_schmidt_m = n: gram_schmidt n f_ty + m: gram_schmidt m f_ty\n  for n m :: nat and f_ty\nbegin\n\nlemma vec_first_lincomb_list:\n  assumes Xs: \"set Xs \\<subseteq> carrier_vec n\"\n    and nm: \"m \\<le> n\"\n  shows \"vec_first (n.lincomb_list c Xs) m =\n       m.lincomb_list c (map (\\<lambda> v. vec_first v m) Xs)\"\n  using Xs\nproof (induction Xs arbitrary: c)\n  case Nil\n  show ?case by (simp add: nm)\nnext\n  case (Cons x Xs)\n  from Cons.prems have x: \"x \\<in> carrier_vec n\" and Xs: \"set Xs \\<subseteq> carrier_vec n\" by auto\n\n  have \"vec_first (n.lincomb_list c (x # Xs)) m =\n          vec_first (c 0 \\<cdot>\\<^sub>v x + n.lincomb_list (c \\<circ> Suc) Xs) m\" by auto\n  also have \"\\<dots> = vec_first (c 0 \\<cdot>\\<^sub>v x) m + vec_first (n.lincomb_list (c \\<circ> Suc) Xs) m\"\n    using vec_first_add[of m \"c 0 \\<cdot>\\<^sub>v x\"] x n.lincomb_list_carrier[OF Xs, of \"c \\<circ> Suc\"] nm\n    by simp\n  also have \"vec_first (c 0 \\<cdot>\\<^sub>v x) m = c 0 \\<cdot>\\<^sub>v vec_first x m\"\n    using vec_first_smult[OF nm, of x \"c 0\"] Cons.prems by auto\n  also have \"vec_first (n.lincomb_list (c \\<circ> Suc) Xs) m =\n               m.lincomb_list (c \\<circ> Suc) (map (\\<lambda> v. vec_first v m) Xs)\"\n    using Cons by simp\n  also have \"c 0 \\<cdot>\\<^sub>v vec_first x m + \\<dots> =\n               m.lincomb_list c (map (\\<lambda> v. vec_first v m) (x # Xs))\"\n    by simp\n  finally show ?case by auto\nqed\n\nlemma convex_hull_next_dim:\n  assumes \"n = m + 1\"\n    and X: \"X \\<subseteq> carrier_vec n\"\n    and \"finite X\"\n    and Xm1: \"\\<forall> y \\<in> X. y $ m = 1\"\n    and y_dim: \"y \\<in> carrier_vec n\"\n    and y: \"y $ m = 1\"\n  shows \"(vec_first y m \\<in> m.convex_hull {vec_first y m | y. y \\<in> X}) = (y \\<in> n.cone X)\"\nproof -\n  from `finite X` obtain Xs where Xs: \"X = set Xs\" using finite_list by auto\n  let ?Y = \"{vec_first y m | y. y \\<in> X}\"\n  let ?Ys = \"map (\\<lambda> y. vec_first y m) Xs\"\n  have Ys: \"?Y = set ?Ys\" using Xs by auto\n\n  define x where \"x = vec_first y m\"\n  {\n    have \"y = vec_first y m @\\<^sub>v vec_last y 1\"\n      using `n = m + 1` vec_first_last_append y_dim by auto\n    also have \"vec_last y 1 = vec_of_scal (vec_last y 1 $ 0)\"\n      using vec_of_scal_dim_1[of \"vec_last y 1\"] by simp\n    also have \"vec_last y 1 $ 0 = y $ m\"\n      using y_dim `n = m + 1` vec_last_index[of y m 1 0] by auto\n    finally have \"y = x @\\<^sub>v vec_of_scal 1\" unfolding x_def using y by simp\n  } note xy = this\n  {\n    assume \"y \\<in> n.cone X\"\n    then obtain c where x: \"n.nonneg_lincomb c X y\"\n      using n.cone_iff_finite_cone[OF X] `finite X`\n      unfolding n.finite_cone_def by auto\n\n    have \"1 = y $ m\" by (simp add: y)\n    also have \"y = n.lincomb c X\"\n      using x unfolding n.nonneg_lincomb_def by simp\n    also have \"\\<dots> $ m = (\\<Sum>x\\<in>X. c x * x $ m)\"\n      using n.lincomb_index[OF _ X] `n = m + 1` by simp\n    also have \"\\<dots> = sum c X\"\n      by (rule n.R.finsum_restrict, auto, rule restrict_ext, simp add: Xm1)\n    finally have \"y \\<in> n.convex_hull X\"\n      unfolding n.convex_hull_def n.convex_lincomb_def\n      using `finite X` x by auto\n  }\n  moreover have \"n.convex_hull X \\<subseteq> n.cone X\"\n    unfolding n.convex_hull_def n.convex_lincomb_def n.finite_cone_def n.cone_def\n    using `finite X` by auto\n  moreover have \"n.convex_hull X = n.convex_hull_list Xs\"\n    by (rule n.finite_convex_hull_iff_convex_hull_list[OF X Xs])\n  moreover {\n    assume \"y \\<in> n.convex_hull_list Xs\"\n    then obtain c where c: \"n.lincomb_list c Xs = y\"\n      and c0: \"\\<forall> i < length Xs. c i \\<ge> 0\" and c1: \"sum c {0..<length Xs} = 1\"\n      unfolding n.convex_hull_list_def n.convex_lincomb_list_def\n        n.nonneg_lincomb_list_def by fast\n    have \"m.lincomb_list c ?Ys = vec_first y m\"\n      using c vec_first_lincomb_list[of Xs c] X Xs `n = m + 1` by simp\n    hence \"x \\<in> m.convex_hull_list ?Ys\"\n      unfolding m.convex_hull_list_def m.convex_lincomb_list_def\n        m.nonneg_lincomb_list_def\n      using x_def c0 c1 x_def by auto\n  } moreover {\n    assume \"x \\<in> m.convex_hull_list ?Ys\"\n    then obtain c where x: \"m.lincomb_list c ?Ys = x\"\n      and c0: \"\\<forall> i < length Xs. c i \\<ge> 0\"\n      and c1: \"sum c {0..<length Xs} = 1\"\n      unfolding m.convex_hull_list_def m.convex_lincomb_list_def\n        m.nonneg_lincomb_list_def by auto\n\n    have \"n.lincomb_list c Xs $ m = (\\<Sum>j = 0..<length Xs. c j * Xs ! j $ m)\"\n      using n.lincomb_list_index[of m Xs c] `n = m + 1` Xs X by fastforce\n    also have \"\\<dots> = sum c {0..<length Xs}\"\n      apply(rule n.R.finsum_restrict, auto, rule restrict_ext)\n      by (simp add: Xm1 Xs)\n    also have \"\\<dots> = 1\" by (rule c1)\n    finally have \"vec_last (n.lincomb_list c Xs) 1 $ 0 = 1\"\n      using vec_of_scal_dim_1 vec_last_index[of \"n.lincomb_list c Xs\" m 1 0]\n        n.lincomb_list_carrier Xs X `n = m + 1` by simp\n    hence \"vec_last (n.lincomb_list c Xs) 1 = vec_of_scal 1\"\n      using vec_of_scal_dim_1 by auto\n\n    moreover have \"vec_first (n.lincomb_list c Xs) m = x\"\n      using vec_first_lincomb_list `n = m + 1` Xs X x by auto\n\n    moreover have \"n.lincomb_list c Xs =\n                   vec_first (n.lincomb_list c Xs) m @\\<^sub>v vec_last (n.lincomb_list c Xs) 1\"\n      using vec_first_last_append Xs X n.lincomb_list_carrier `n = m + 1` by auto\n\n    ultimately have \"n.lincomb_list c Xs = y\" using xy by simp\n\n    hence \"y \\<in> n.convex_hull_list Xs\"\n      unfolding n.convex_hull_list_def n.convex_lincomb_list_def\n        n.nonneg_lincomb_list_def using c0 c1 by blast\n  }\n  moreover have \"m.convex_hull ?Y = m.convex_hull_list ?Ys\"\n    using m.finite_convex_hull_iff_convex_hull_list[OF _ Ys] by fastforce\n  ultimately show ?thesis unfolding x_def by blast\nqed\n\nlemma cone_next_dim:\n  assumes \"n = m + 1\"\n    and X: \"X \\<subseteq> carrier_vec n\"\n    and \"finite X\"\n    and Xm0: \"\\<forall> y \\<in> X. y $ m = 0\"\n    and y_dim: \"y \\<in> carrier_vec n\"\n    and y: \"y $ m = 0\"\n  shows \"(vec_first y m \\<in> m.cone {vec_first y m | y. y \\<in> X}) = (y \\<in> n.cone X)\"\nproof -\n  from `finite X` obtain Xs where Xs: \"X = set Xs\" using finite_list by auto\n  let ?Y = \"{vec_first y m | y. y \\<in> X}\"\n  let ?Ys = \"map (\\<lambda> y. vec_first y m) Xs\"\n  have Ys: \"?Y = set ?Ys\" using Xs by auto\n\n  define x where \"x = vec_first y m\"\n  {\n    have \"y = vec_first y m @\\<^sub>v vec_last y 1\"\n      using `n = m + 1` vec_first_last_append y_dim by auto\n    also have \"vec_last y 1 = vec_of_scal (vec_last y 1 $ 0)\"\n      using vec_of_scal_dim_1[of \"vec_last y 1\"] by simp\n    also have \"vec_last y 1 $ 0 = y $ m\"\n      using y_dim `n = m + 1` vec_last_index[of y m 1 0] by auto\n    finally have \"y = x @\\<^sub>v vec_of_scal 0\" unfolding x_def using y by simp\n  } note xy = this\n\n  have \"n.cone X = n.cone_list Xs\"\n    using n.cone_iff_finite_cone[OF X `finite X`] n.finite_cone_iff_cone_list[OF X Xs]\n    by simp\n  moreover {\n    assume \"y \\<in> n.cone_list Xs\"\n    then obtain c where y: \"n.lincomb_list c Xs = y\" and c: \"\\<forall> i < length Xs. c i \\<ge> 0\"\n      unfolding n.cone_list_def n.nonneg_lincomb_list_def by blast\n    from y have \"m.lincomb_list c ?Ys = x\"\n      unfolding x_def\n      using vec_first_lincomb_list Xs X `n = m + 1` by auto\n    hence \"x \\<in> m.cone_list ?Ys\" using c\n      unfolding m.cone_list_def m.nonneg_lincomb_list_def by auto\n  } moreover {\n    assume \"x \\<in> m.cone_list ?Ys\"\n    then obtain c where x: \"m.lincomb_list c ?Ys = x\" and c: \"\\<forall> i < length Xs. c i \\<ge> 0\"\n      unfolding m.cone_list_def m.nonneg_lincomb_list_def by auto\n\n    have \"vec_last (n.lincomb_list c Xs) 1 $ 0 = n.lincomb_list c Xs $ m\"\n      using `n = m + 1` n.lincomb_list_carrier X Xs vec_last_index[of _ m 1 0]\n      by auto\n    also have \"\\<dots> = 0\"\n      using n.lincomb_list_index[of m Xs c] Xs X `n = m + 1` Xm0 by simp\n    also have \"\\<dots> = vec_last y 1 $ 0\"\n      using y y_dim `n = m + 1` vec_last_index[of y m 1 0] by auto\n    finally have \"vec_last (n.lincomb_list c Xs) 1 = vec_last y 1\" by fastforce\n\n    moreover have \"vec_first (n.lincomb_list c Xs) m = x\"\n      using vec_first_lincomb_list[of Xs c] x X Xs `n = m + 1`\n      unfolding x_def by simp\n\n    ultimately have \"n.lincomb_list c Xs = y\" unfolding x_def\n      using vec_first_last_append[of _ m 1] `n = m + 1` y_dim\n        n.lincomb_list_carrier[of Xs c] Xs X\n      by metis\n    hence \"y \\<in> n.cone_list Xs\"\n      unfolding n.cone_list_def n.nonneg_lincomb_list_def using c by blast\n  }\n  moreover have \"m.cone_list ?Ys = m.cone ?Y\"\n    using m.finite_cone_iff_cone_list[OF _ Ys] m.cone_iff_finite_cone[of ?Y]\n      `finite X` by force\n  ultimately show ?thesis unfolding x_def by blast\nqed\n\nend\n\ncontext gram_schmidt\nbegin\n\nlemma decomposition_theorem_polyhedra_1:\n  assumes A: \"A \\<in> carrier_mat nr n\"\n    and b: \"b \\<in> carrier_vec nr\"\n    and P: \"P = polyhedron A b\"\n  shows \"\\<exists> Q X. X \\<subseteq> carrier_vec n \\<and> finite X \\<and>\n    Q \\<subseteq> carrier_vec n \\<and> finite Q \\<and>\n    P = convex_hull Q + cone X \\<and>\n    (A \\<in> \\<int>\\<^sub>m \\<inter> Bounded_mat Bnd \\<longrightarrow> b \\<in> \\<int>\\<^sub>v \\<inter> Bounded_vec Bnd \\<longrightarrow>\n      X \\<subseteq> \\<int>\\<^sub>v \\<inter> Bounded_vec (det_bound n (max 1 Bnd))\n    \\<and> Q \\<subseteq> Bounded_vec (det_bound n (max 1 Bnd)))\"\nproof -\n  interpret next_dim: gram_schmidt \"n + 1\" \"TYPE ('a)\".\n  interpret gram_schmidt_m \"n + 1\" n \"TYPE('a)\".\n\n  from P[unfolded polyhedron_def] have \"P \\<subseteq> carrier_vec n\" by auto\n\n  have mcb: \"mat_of_col (-b) \\<in> carrier_mat nr 1\" using b by auto\n  define M where \"M = (A @\\<^sub>c mat_of_col (-b)) @\\<^sub>r (0\\<^sub>m 1 n @\\<^sub>c -1\\<^sub>m 1)\"\n  have M_top: \"A @\\<^sub>c mat_of_col (- b) \\<in> carrier_mat nr (n + 1)\"\n    by (rule carrier_append_cols[OF A mcb])\n  have M_bottom: \"(0\\<^sub>m 1 n @\\<^sub>c -1\\<^sub>m 1) \\<in> carrier_mat 1 (n + 1)\"\n    by (rule carrier_append_cols, auto)\n  have M_dim: \"M \\<in> carrier_mat (nr + 1) (n + 1)\"\n    unfolding M_def\n    by (rule carrier_append_rows[OF M_top M_bottom])\n\n  {\n    fix x :: \"'a vec\" fix t assume x: \"x \\<in> carrier_vec n\"\n    have \"x @\\<^sub>v vec_of_scal t \\<in> next_dim.polyhedral_cone M =\n          (A *\\<^sub>v x - t \\<cdot>\\<^sub>v b \\<le> 0\\<^sub>v nr \\<and> t \\<ge> 0)\"\n    proof -\n      let ?y = \"x @\\<^sub>v vec_of_scal t\"\n      have y: \"?y \\<in> carrier_vec (n + 1)\" using x by(simp del: One_nat_def)\n      have \"?y \\<in> next_dim.polyhedral_cone M =\n            (M *\\<^sub>v ?y \\<le> 0\\<^sub>v (nr + 1))\"\n        unfolding next_dim.polyhedral_cone_def using y M_dim by auto\n      also have \"0\\<^sub>v (nr + 1) = 0\\<^sub>v nr @\\<^sub>v 0\\<^sub>v 1\" by auto\n      also have \"M *\\<^sub>v ?y \\<le> 0\\<^sub>v nr @\\<^sub>v 0\\<^sub>v 1 =\n                   ((A @\\<^sub>c mat_of_col (-b)) *\\<^sub>v ?y \\<le> 0\\<^sub>v nr \\<and>\n                   (0\\<^sub>m 1 n @\\<^sub>c -1\\<^sub>m 1) *\\<^sub>v ?y \\<le> 0\\<^sub>v 1)\"\n        unfolding M_def\n        by (intro append_rows_le[OF M_top M_bottom _ y], auto)\n      also have \"(A @\\<^sub>c mat_of_col(-b)) *\\<^sub>v ?y =\n                 A *\\<^sub>v x + mat_of_col(-b) *\\<^sub>v vec_of_scal t\"\n        by (rule mat_mult_append_cols[OF A _ x],\n            auto simp add: b simp del: One_nat_def)\n      also have \"mat_of_col(-b) *\\<^sub>v vec_of_scal t = t \\<cdot>\\<^sub>v (-b)\"\n        by(rule mult_mat_of_row_vec_of_scal)\n      also have \"A *\\<^sub>v x + t \\<cdot>\\<^sub>v (-b) = A *\\<^sub>v x - t \\<cdot>\\<^sub>v b\" by auto\n      also have \"(0\\<^sub>m 1 n @\\<^sub>c - 1\\<^sub>m 1) *\\<^sub>v (x @\\<^sub>v vec_of_scal t) =\n                 0\\<^sub>m 1 n *\\<^sub>v x + - 1\\<^sub>m 1 *\\<^sub>v vec_of_scal t\"\n        by(rule mat_mult_append_cols, auto simp add: x simp del: One_nat_def)\n      also have \"\\<dots> = - vec_of_scal t\" using x by (auto simp del: One_nat_def)\n      also have \"(\\<dots> \\<le> 0\\<^sub>v 1) = (t \\<ge> 0)\" unfolding less_eq_vec_def by auto\n      finally show \"(?y \\<in> next_dim.polyhedral_cone M) =\n                    (A *\\<^sub>v x - t \\<cdot>\\<^sub>v b \\<le> 0\\<^sub>v nr \\<and> t \\<ge> 0)\" by auto\n    qed\n  } note M_cone_car = this\n  from next_dim.farkas_minkowsky_weyl_theorem_2[OF M_dim, of \"max 1 Bnd\"]\n  obtain X where X: \"next_dim.polyhedral_cone M = next_dim.cone X\" and\n    fin_X: \"finite X\" and X_carrier: \"X \\<subseteq> carrier_vec (n+1)\"\n    and Bnd: \"M \\<in> \\<int>\\<^sub>m \\<inter> Bounded_mat (max 1 Bnd) \\<Longrightarrow>\n          X \\<subseteq> \\<int>\\<^sub>v \\<inter> Bounded_vec (det_bound n (max 1 Bnd))\"\n    by auto\n  let ?f = \"\\<lambda> x. if x $ n = 0 then 1 else 1 / (x $ n)\"\n  define Y where \"Y = {?f x \\<cdot>\\<^sub>v x | x. x \\<in> X}\"\n  have \"finite Y\" unfolding Y_def using fin_X by auto\n  have Y_carrier: \"Y \\<subseteq> carrier_vec (n+1)\" unfolding Y_def using X_carrier by auto\n  have \"?f ` X \\<subseteq> {y. y > 0}\"\n  proof\n    fix y\n    assume \"y \\<in> ?f ` X\"\n    then obtain x where x: \"x \\<in> X\" and y: \"y = ?f x\" by auto\n    show \"y \\<in> {y. y > 0}\"\n    proof cases\n      assume \"x $ n = 0\"\n      thus \"y \\<in> {y. y > 0}\" using y by auto\n    next\n      assume P: \"x $ n \\<noteq> 0\"\n      have \"x = vec_first x n @\\<^sub>v vec_last x 1\"\n        using x X_carrier vec_first_last_append by auto\n      also have \"vec_last x 1 = vec_of_scal (vec_last x 1 $ 0)\" by auto\n      also have \"vec_last x 1 $ 0 = x $ n\"\n        using x X_carrier unfolding vec_last_def by auto\n      finally have \"x = vec_first x n @\\<^sub>v vec_of_scal (x $ n)\" by auto\n      moreover have \"x \\<in> next_dim.polyhedral_cone M\"\n        using x X X_carrier next_dim.set_in_cone by auto\n      ultimately have \"x $ n \\<ge> 0\" using M_cone_car vec_first_carrier by metis\n      hence \"x $ n > 0\" using P by auto\n      thus \"y \\<in> {y. y > 0}\" using y by auto\n    qed\n  qed\n  hence Y: \"next_dim.cone Y = next_dim.polyhedral_cone M\" unfolding Y_def\n    using next_dim.cone_smult_basis[OF X_carrier] X by auto\n  define Y0 where \"Y0 = {v \\<in> Y. v $ n = 0}\"\n  define Y1 where \"Y1 = Y - Y0\"\n  have Y0_carrier: \"Y0 \\<subseteq> carrier_vec (n + 1)\" and Y1_carrier: \"Y1 \\<subseteq> carrier_vec (n + 1)\"\n    unfolding Y0_def Y1_def using Y_carrier by auto\n  have \"finite Y0\" and \"finite Y1\"\n    unfolding Y0_def Y1_def using `finite Y` by auto\n\n  have Y1: \"\\<And> y. y \\<in> Y1 \\<Longrightarrow> y $ n = 1\"\n  proof -\n    fix y assume y: \"y \\<in> Y1\"\n    hence \"y \\<in> Y\" unfolding Y1_def by auto\n    then obtain x where \"x \\<in> X\" and x: \"y = ?f x \\<cdot>\\<^sub>v x\" unfolding Y_def by auto\n    then have \"x $ n \\<noteq> 0\" using x y Y1_def Y0_def by auto\n    then have \"y = 1 / (x $ n) \\<cdot>\\<^sub>v x\" using x by auto\n    then have \"y $ n = 1 / (x $ n) * x $ n\" using X_carrier `x \\<in> X` by auto\n    thus \"y $ n = 1\" using `x $ n \\<noteq> 0` by auto\n  qed\n\n  let ?Z0 = \"{vec_first y n | y. y \\<in> Y0}\"\n  let ?Z1 = \"{vec_first y n | y. y \\<in> Y1}\"\n  show ?thesis\n  proof (intro exI conjI impI)\n    show \"?Z0 \\<subseteq> carrier_vec n\" by auto\n    show \"?Z1 \\<subseteq> carrier_vec n\" by auto\n    show \"finite ?Z0\" using `finite Y0` by auto\n    show \"finite ?Z1\" using `finite Y1` by auto\n    show \"P = convex_hull ?Z1 + cone ?Z0\"\n    proof -\n      {\n        fix x\n        assume \"x \\<in> P\"\n        hence xn: \"x \\<in> carrier_vec n\" and \"A *\\<^sub>v x \\<le> b\"\n          using P unfolding polyhedron_def by auto\n        hence \"A *\\<^sub>v x - 1 \\<cdot>\\<^sub>v b \\<le> 0\\<^sub>v nr\"\n          using vec_le_iff_diff_le_0 A b carrier_vecD mult_mat_vec_carrier one_smult_vec\n          by metis\n        hence \"x @\\<^sub>v vec_of_scal 1 \\<in> next_dim.polyhedral_cone M\"\n          using M_cone_car[OF xn] by auto\n        hence \"x @\\<^sub>v vec_of_scal 1 \\<in> next_dim.cone Y\" using Y by auto\n        hence \"x @\\<^sub>v vec_of_scal 1 \\<in> next_dim.finite_cone Y\"\n          using next_dim.cone_iff_finite_cone[OF Y_carrier `finite Y`] by auto\n        then obtain c where c: \"next_dim.nonneg_lincomb c Y (x @\\<^sub>v vec_of_scal 1)\"\n          unfolding next_dim.finite_cone_def using `finite Y` by auto\n        let ?y = \"next_dim.lincomb c Y1\"\n        let ?z = \"next_dim.lincomb c Y0\"\n        have y_dim: \"?y \\<in> carrier_vec (n + 1)\" and z_dim: \"?z \\<in> carrier_vec (n + 1)\"\n          unfolding next_dim.nonneg_lincomb_def\n          using Y0_carrier Y1_carrier next_dim.lincomb_closed by simp_all\n        hence yz_dim: \"?y + ?z \\<in> carrier_vec (n + 1)\" by auto\n        have \"x @\\<^sub>v vec_of_scal 1 = next_dim.lincomb c Y\"\n          using c unfolding next_dim.nonneg_lincomb_def by auto\n        also have \"Y = Y1 \\<union> Y0\" unfolding Y1_def using Y0_def by blast\n        also have \"next_dim.lincomb c (Y1 \\<union> Y0) = ?y + ?z\"\n          using next_dim.lincomb_union2[of Y1 Y0]\n            `finite Y0` `finite Y` Y0_carrier Y_carrier\n          unfolding Y1_def by fastforce\n        also have \"?y + ?z = vec_first (?y + ?z) n @\\<^sub>v vec_last (?y + ?z) 1\"\n          using vec_first_last_append[of \"?y + ?z\" n 1] add_carrier_vec yz_dim\n          by simp\n        also have \"vec_last (?y + ?z) 1 = vec_of_scal ((?y + ?z) $ n)\"\n          using vec_of_scal_dim_1 vec_last_index[OF yz_dim, of 0] by auto\n        finally have \"x @\\<^sub>v vec_of_scal 1 =\n                     vec_first (?y + ?z) n @\\<^sub>v vec_of_scal ((?y + ?z) $ n)\" by auto\n        hence \"x = vec_first (?y + ?z) n\" and\n          yz_last: \"vec_of_scal 1 = vec_of_scal ((?y + ?z) $ n)\"\n          using append_vec_eq yz_dim xn by auto\n        hence xyz: \"x = vec_first ?y n + vec_first ?z n\"\n          using vec_first_add[of n ?y ?z] y_dim z_dim by simp\n\n        have \"1 = ((?y + ?z) $ n)\" using yz_last index_vec_of_scal\n          by (metis (no_types, lifting))\n        hence \"1 = ?y $ n + ?z $ n\" using y_dim z_dim by auto\n        moreover have zn0: \"?z $ n = 0\"\n          using next_dim.lincomb_index[OF _ Y0_carrier] Y0_def by auto\n        ultimately have yn1: \"1 = ?y $ n\" by auto\n        have \"next_dim.nonneg_lincomb c Y1 ?y\"\n          using c Y1_def\n          unfolding next_dim.nonneg_lincomb_def by auto\n        hence \"?y \\<in> next_dim.cone Y1\"\n          using next_dim.cone_iff_finite_cone[OF Y1_carrier] `finite Y1`\n          unfolding next_dim.finite_cone_def by auto\n        hence y: \"vec_first ?y n \\<in> convex_hull ?Z1\"\n          using convex_hull_next_dim[OF _ Y1_carrier `finite Y1` _ y_dim] Y1 yn1\n          by simp\n\n        have \"next_dim.nonneg_lincomb c Y0 ?z\" using c Y0_def\n          unfolding next_dim.nonneg_lincomb_def by blast\n        hence \"?z \\<in> next_dim.cone Y0\"\n          using `finite Y0` next_dim.cone_iff_finite_cone[OF Y0_carrier `finite Y0`]\n          unfolding next_dim.finite_cone_def\n          by fastforce\n        hence z: \"vec_first ?z n \\<in> cone ?Z0\"\n          using cone_next_dim[OF _ Y0_carrier `finite Y0` _ _ zn0] Y0_def\n            next_dim.lincomb_closed[OF Y0_carrier] by blast\n\n        from xyz y z have \"x \\<in> convex_hull ?Z1 + cone ?Z0\" by blast\n      } moreover {\n        fix x\n        assume \"x \\<in> convex_hull ?Z1 + cone ?Z0\"\n        then obtain y z where \"x = y + z\" and y: \"y \\<in> convex_hull ?Z1\"\n          and z: \"z \\<in> cone ?Z0\" by (auto elim: set_plus_elim)\n\n        have yn: \"y \\<in> carrier_vec n\"\n          using y convex_hull_carrier[OF `?Z1 \\<subseteq> carrier_vec n`] by blast\n        hence \"y @\\<^sub>v vec_of_scal 1 \\<in> carrier_vec (n + 1)\"\n          using vec_of_scal_dim(2) by fast\n        moreover have \"vec_first (y @\\<^sub>v vec_of_scal 1) n \\<in> convex_hull ?Z1\"\n          using vec_first_append[OF yn] y by auto\n        moreover have \"(y @\\<^sub>v vec_of_scal 1) $ n = 1\" using yn by simp\n        ultimately have \"y @\\<^sub>v vec_of_scal 1 \\<in> next_dim.cone Y1\"\n          using convex_hull_next_dim[OF _ Y1_carrier `finite Y1`] Y1 by blast\n        hence y_cone: \"y @\\<^sub>v vec_of_scal 1 \\<in> next_dim.cone Y\"\n          using next_dim.cone_mono[of Y1 Y] Y1_def by blast\n\n        have zn: \"z \\<in> carrier_vec n\" using z cone_carrier[of ?Z0] by fastforce\n        hence \"z @\\<^sub>v vec_of_scal 0 \\<in> carrier_vec (n + 1)\"\n          using vec_of_scal_dim(2) by fast\n        moreover have \"vec_first (z @\\<^sub>v vec_of_scal 0) n \\<in> cone ?Z0\"\n          using vec_first_append[OF zn] z by auto\n        moreover have \"(z @\\<^sub>v vec_of_scal 0) $ n = 0\" using zn by simp\n        ultimately have \"z @\\<^sub>v vec_of_scal 0 \\<in> next_dim.cone Y0\"\n          using cone_next_dim[OF _ Y0_carrier `finite Y0`] Y0_def by blast\n        hence z_cone: \"z @\\<^sub>v vec_of_scal 0 \\<in> next_dim.cone Y\"\n          using Y0_def next_dim.cone_mono[of Y0 Y] by blast\n\n        have xn: \"x \\<in> carrier_vec n\" using `x = y + z` yn zn by blast\n        have \"x @\\<^sub>v vec_of_scal 1 = (y @\\<^sub>v vec_of_scal 1) + (z @\\<^sub>v vec_of_scal 0)\"\n          using `x = y + z` append_vec_add[OF yn zn]\n          unfolding vec_of_scal_def by auto\n        hence \"x @\\<^sub>v vec_of_scal 1 \\<in> next_dim.cone Y\"\n          using next_dim.cone_elem_sum[OF Y_carrier y_cone z_cone] by simp\n        hence \"A *\\<^sub>v x - b \\<le> 0\\<^sub>v nr\" using M_cone_car[OF xn] Y by simp\n        hence \"A *\\<^sub>v x \\<le> b\" using vec_le_iff_diff_le_0[of \"A *\\<^sub>v x\" b]\n            dim_mult_mat_vec[of A x] A by simp\n        hence \"x \\<in> P\" using P xn unfolding polyhedron_def by blast\n      }\n      ultimately show \"P = convex_hull ?Z1 + cone ?Z0\" by blast\n    qed\n\n    let ?Bnd = \"det_bound n (max 1 Bnd)\"\n    assume \"A \\<in> \\<int>\\<^sub>m \\<inter> Bounded_mat Bnd\"\n      \"b \\<in> \\<int>\\<^sub>v \\<inter> Bounded_vec Bnd\"\n    hence *: \"A \\<in> \\<int>\\<^sub>m\" \"A \\<in> Bounded_mat Bnd\" \"b \\<in> \\<int>\\<^sub>v\" \"b \\<in> Bounded_vec Bnd\" by auto\n    have \"elements_mat M \\<subseteq> elements_mat A \\<union> vec_set (-b) \\<union> {0,-1}\"\n      unfolding M_def\n      unfolding elements_mat_append_rows[OF M_top M_bottom]\n      unfolding elements_mat_append_cols[OF A mcb]\n      by (subst elements_mat_append_cols, auto)\n    also have \"\\<dots> \\<subseteq> \\<int> \\<inter> ({x. abs x \\<le> Bnd} \\<union> {0,-1})\"\n      using *[unfolded Bounded_mat_elements_mat Ints_mat_elements_mat\n          Bounded_vec_vec_set Ints_vec_vec_set] by auto\n    also have \"\\<dots> \\<subseteq> \\<int> \\<inter> ({x. abs x \\<le> max 1 Bnd})\" by auto\n    finally have \"M \\<in> \\<int>\\<^sub>m\" \"M \\<in> Bounded_mat (max 1 Bnd)\"\n      unfolding Bounded_mat_elements_mat Ints_mat_elements_mat by auto\n    hence \"M \\<in> \\<int>\\<^sub>m \\<inter> Bounded_mat (max 1 Bnd)\" by blast\n    from Bnd[OF this]\n    have XBnd: \"X \\<subseteq> \\<int>\\<^sub>v \\<inter> Bounded_vec ?Bnd\" .\n    {\n      fix y\n      assume y: \"y \\<in> Y\"\n      then obtain x where y: \"y = ?f x \\<cdot>\\<^sub>v x\" and xX: \"x \\<in> X\" unfolding Y_def by auto\n      with \\<open>X \\<subseteq> carrier_vec (n+1)\\<close> have x: \"x \\<in> carrier_vec (n+1)\" by auto\n      from XBnd xX have xI: \"x \\<in> \\<int>\\<^sub>v\" and xB: \"x \\<in> Bounded_vec ?Bnd\" by auto\n      {\n        assume \"y $ n = 0\"\n        hence \"y = x\" unfolding y using x by auto\n        hence \"y \\<in> \\<int>\\<^sub>v \\<inter> Bounded_vec ?Bnd\" using xI xB by auto\n      } note y0 = this\n      {\n        assume \"y $ n \\<noteq> 0\"\n        hence x0: \"x $ n \\<noteq> 0\" using x unfolding y by auto\n        from x xI have \"x $ n \\<in> \\<int>\" unfolding Ints_vec_def by auto\n        with x0 have \"abs (x $ n) \\<ge> 1\" by (meson Ints_nonzero_abs_ge1)\n        hence abs: \"abs (1 / (x $ n)) \\<le> 1\" by simp\n        {\n          fix a\n          have \"abs ((1 / (x $ n)) * a) = abs (1 / (x $ n)) * abs a\"\n            by simp\n          also have \"\\<dots> \\<le> 1 * abs a\"\n            by (rule mult_right_mono[OF abs], auto)\n          finally have \"abs ((1 / (x $ n)) * a) \\<le> abs a\" by auto\n        } note abs = this\n        from x0 have y: \"y = (1 / (x $ n)) \\<cdot>\\<^sub>v x\" unfolding y by auto\n        have vy: \"vec_set y = (\\<lambda> a. (1 / (x $ n)) * a) ` vec_set x\"\n          unfolding y by (auto simp: vec_set_def)\n        have \"y \\<in> Bounded_vec ?Bnd\" using xB abs\n          unfolding Bounded_vec_vec_set vy\n          by (smt imageE max.absorb2 max.bounded_iff)\n      } note yn0 = this\n      note y0 yn0\n    } note BndY = this\n    from \\<open>Y \\<subseteq> carrier_vec (n+1)\\<close>\n    have setvY: \"y \\<in> Y \\<Longrightarrow> set\\<^sub>v (vec_first y n) \\<subseteq> set\\<^sub>v y\" for y\n      unfolding vec_first_def vec_set_def by auto\n    from BndY(1) setvY\n    show \"?Z0 \\<subseteq> \\<int>\\<^sub>v \\<inter> Bounded_vec (det_bound n (max 1 Bnd))\"\n      by (force simp: Bounded_vec_vec_set Ints_vec_vec_set Y0_def)\n    from BndY(2) setvY\n    show \"?Z1 \\<subseteq> Bounded_vec (det_bound n (max 1 Bnd))\"\n      by (force simp: Bounded_vec_vec_set Ints_vec_vec_set Y0_def Y1_def)\n  qed\nqed\n\nlemma decomposition_theorem_polyhedra_2:\n  assumes Q: \"Q \\<subseteq> carrier_vec n\" and fin_Q: \"finite Q\"\n    and X: \"X \\<subseteq> carrier_vec n\" and fin_X: \"finite X\"\n    and P: \"P = convex_hull Q + cone X\"\n  shows \"\\<exists>A b nr. A \\<in> carrier_mat nr n \\<and> b \\<in> carrier_vec nr \\<and> P = polyhedron A b\"\nproof -\n  interpret next_dim: gram_schmidt \"n + 1\" \"TYPE ('a)\".\n  interpret gram_schmidt_m \"n + 1\" n \"TYPE('a)\".\n\n  from fin_Q obtain Qs where Qs: \"Q = set Qs\" using finite_list by auto\n  from fin_X obtain Xs where Xs: \"X = set Xs\" using finite_list by auto\n  define Y where \"Y = {x @\\<^sub>v vec_of_scal 1 | x. x \\<in> Q}\"\n  define Z where \"Z = {x @\\<^sub>v vec_of_scal 0 | x. x \\<in> X}\"\n  have fin_Y: \"finite Y\" unfolding Y_def using fin_Q by simp\n  have fin_Z: \"finite Z\" unfolding Z_def using fin_X by simp\n  have Y_dim: \"Y \\<subseteq> carrier_vec (n + 1)\"\n    unfolding Y_def using Q append_carrier_vec[OF _ vec_of_scal_dim(2)[of 1]]\n    by blast\n  have Z_dim: \"Z \\<subseteq> carrier_vec (n + 1)\"\n    unfolding Z_def using X append_carrier_vec[OF _ vec_of_scal_dim(2)[of 0]]\n    by blast\n  have Y_car: \"Q = {vec_first x n | x. x \\<in> Y}\"\n  proof (intro equalityI subsetI)\n    fix x assume x: \"x \\<in> Q\"\n    hence \"x @\\<^sub>v vec_of_scal 1 \\<in> Y\" unfolding Y_def by blast\n    thus \"x \\<in> {vec_first x n | x. x \\<in> Y}\"\n      using Q vec_first_append[of x n \"vec_of_scal 1\"] x by force\n  next\n    fix x assume \"x \\<in> {vec_first x n | x. x \\<in> Y}\"\n    then obtain y where \"y \\<in> Q\" and \"x = vec_first (y @\\<^sub>v vec_of_scal 1) n\"\n      unfolding Y_def by blast\n    thus \"x \\<in> Q\" using Q vec_first_append[of y] by auto\n  qed\n  have Z_car: \"X = {vec_first x n | x. x \\<in> Z}\"\n  proof (intro equalityI subsetI)\n    fix x assume x: \"x \\<in> X\"\n    hence \"x @\\<^sub>v vec_of_scal 0 \\<in> Z\" unfolding Z_def by blast\n    thus \"x \\<in> {vec_first x n | x. x \\<in> Z}\"\n      using X vec_first_append[of x n \"vec_of_scal 0\"] x by force\n  next\n    fix x assume \"x \\<in> {vec_first x n | x. x \\<in> Z}\"\n    then obtain y where \"y \\<in> X\" and \"x = vec_first (y @\\<^sub>v vec_of_scal 0) n\"\n      unfolding Z_def by blast\n    thus \"x \\<in> X\" using X vec_first_append[of y] by auto\n  qed\n  have Y_last: \"\\<forall> x \\<in> Y. x $ n = 1\" unfolding Y_def using Q by auto\n  have Z_last: \"\\<forall> x \\<in> Z. x $ n = 0\" unfolding Z_def using X by auto\n\n  have \"finite (Y \\<union> Z)\" using fin_Y fin_Z by blast\n  moreover have \"Y \\<union> Z \\<subseteq> carrier_vec (n + 1)\" using Y_dim Z_dim by blast\n  ultimately obtain B nr\n    where B: \"next_dim.cone (Y \\<union> Z) = next_dim.polyhedral_cone B\"\n      and B_carrier: \"B \\<in> carrier_mat nr (n + 1)\"\n    using next_dim.farkas_minkowsky_weyl_theorem[of \"next_dim.cone (Y \\<union> Z)\"]\n    by blast\n  define A where \"A = mat_col_first B n\"\n  define b where \"b = col B n\"\n  have B_blocks: \"B = A @\\<^sub>c mat_of_col b\"\n    unfolding A_def b_def\n    using mat_col_first_last_append[of B n 1] B_carrier\n      mat_of_col_dim_col_1[of \"mat_col_last B 1\"] by auto\n  have A_carrier: \"A \\<in> carrier_mat nr n\" unfolding A_def using B_carrier by force\n  have b_carrier: \"b \\<in> carrier_vec nr\" unfolding b_def using B_carrier by force\n\n  {\n    fix x assume \"x \\<in> P\"\n    then obtain y z where x: \"x = y + z\" and y: \"y \\<in> convex_hull Q\" and z: \"z \\<in> cone X\"\n      using P by (auto elim: set_plus_elim)\n\n    have yn: \"y \\<in> carrier_vec n\" using y convex_hull_carrier[OF Q] by blast\n    moreover have zn: \"z \\<in> carrier_vec n\" using z cone_carrier[OF X] by blast\n    ultimately have xn: \"x \\<in> carrier_vec n\" using x by blast\n\n    have yn1: \"y @\\<^sub>v vec_of_scal 1 \\<in> carrier_vec (n + 1)\"\n      using append_carrier_vec[OF yn] vec_of_scal_dim by fast\n    have y_last: \"(y @\\<^sub>v vec_of_scal 1) $ n = 1\" using yn by force\n    have \"vec_first (y @\\<^sub>v vec_of_scal 1) n = y\"\n      using vec_first_append[OF yn] by simp\n    hence \"y @\\<^sub>v vec_of_scal 1 \\<in> next_dim.cone Y\"\n      using convex_hull_next_dim[OF _ Y_dim fin_Y Y_last yn1 y_last] Y_car y by argo\n    hence y_cone: \"y @\\<^sub>v vec_of_scal 1 \\<in> next_dim.cone (Y \\<union> Z)\"\n      using next_dim.cone_mono[of Y \"Y \\<union> Z\"] by blast\n\n    have zn1: \"z @\\<^sub>v vec_of_scal 0 \\<in> carrier_vec (n + 1)\"\n      using append_carrier_vec[OF zn] vec_of_scal_dim by fast\n    have z_last: \"(z @\\<^sub>v vec_of_scal 0) $ n = 0\" using zn by force\n    have \"vec_first (z @\\<^sub>v vec_of_scal 0) n = z\"\n      using vec_first_append[OF zn] by simp\n    hence \"z @\\<^sub>v vec_of_scal 0 \\<in> next_dim.cone Z\"\n      using cone_next_dim[OF _ Z_dim fin_Z Z_last zn1 z_last] Z_car z by argo\n    hence z_cone: \"z @\\<^sub>v vec_of_scal 0 \\<in> next_dim.cone (Y \\<union> Z)\"\n      using next_dim.cone_mono[of Z \"Y \\<union> Z\"] by blast\n\n    from `x = y + z`\n    have \"x @\\<^sub>v vec_of_scal 1 = (y @\\<^sub>v vec_of_scal 1) + (z @\\<^sub>v vec_of_scal 0)\"\n      using append_vec_add[OF yn zn] vec_of_scal_dim_1\n      unfolding vec_of_scal_def by auto\n    hence \"x @\\<^sub>v vec_of_scal 1 \\<in> next_dim.cone (Y \\<union> Z) \\<and> x \\<in> carrier_vec n\"\n      using next_dim.cone_elem_sum[OF _ y_cone z_cone] Y_dim Z_dim xn by auto\n  } moreover {\n    fix x assume \"x @\\<^sub>v vec_of_scal 1 \\<in> next_dim.cone (Y \\<union> Z)\"\n    then obtain c where x: \"next_dim.lincomb c (Y \\<union> Z) = x @\\<^sub>v vec_of_scal 1\"\n      and c: \"c ` (Y \\<union> Z) \\<subseteq> {t. t \\<ge> 0}\"\n      using next_dim.cone_iff_finite_cone Y_dim Z_dim fin_Y fin_Z\n      unfolding next_dim.finite_cone_def next_dim.nonneg_lincomb_def by auto\n\n    let ?y = \"next_dim.lincomb c Y\"\n    let ?z = \"next_dim.lincomb c Z\"\n    have xyz: \"x @\\<^sub>v vec_of_scal 1 = ?y + ?z\"\n      using x next_dim.lincomb_union[OF Y_dim Z_dim _ fin_Y fin_Z] Y_last Z_last\n      by fastforce\n\n    have y_dim: \"?y \\<in> carrier_vec (n + 1)\" using next_dim.lincomb_closed[OF Y_dim]\n      by blast\n    have z_dim: \"?z \\<in> carrier_vec (n + 1)\" using next_dim.lincomb_closed[OF Z_dim]\n      by blast\n    have \"x @\\<^sub>v vec_of_scal 1 \\<in> carrier_vec (n + 1)\"\n      using xyz add_carrier_vec[OF y_dim z_dim] by argo\n    hence x_dim: \"x \\<in> carrier_vec n\"\n      using carrier_dim_vec[of x n] carrier_dim_vec[of _ \"n + 1\"]\n      by force\n\n    have z_last: \"?z $ n = 0\" using Z_last next_dim.lincomb_index[OF _ Z_dim, of n]\n      by force\n    have \"?y $ n + ?z $ n = (x @\\<^sub>v vec_of_scal 1) $ n\"\n      using xyz index_add_vec(1) z_dim by simp\n    also have \"\\<dots> = 1\" using x_dim by auto\n    finally have y_last: \"?y $ n = 1\" using z_last by algebra\n\n    have \"?y \\<in> next_dim.cone Y\"\n      using next_dim.cone_iff_finite_cone[OF Y_dim] fin_Y c\n      unfolding next_dim.finite_cone_def next_dim.nonneg_lincomb_def by auto\n    hence y_cone: \"vec_first ?y n \\<in> convex_hull Q\"\n      using convex_hull_next_dim[OF _ Y_dim fin_Y Y_last y_dim y_last] Y_car\n      by blast\n\n    have \"?z \\<in> next_dim.cone Z\"\n      using next_dim.cone_iff_finite_cone[OF Z_dim] fin_Z c\n      unfolding next_dim.finite_cone_def next_dim.nonneg_lincomb_def by auto\n    hence z_cone: \"vec_first ?z n \\<in> cone X\"\n      using cone_next_dim[OF _ Z_dim fin_Z Z_last z_dim z_last] Z_car\n      by blast\n\n    have \"x = vec_first (x @\\<^sub>v vec_of_scal 1) n\" using vec_first_append[OF x_dim] by simp\n    also have \"\\<dots> = vec_first ?y n + vec_first ?z n\"\n      using xyz vec_first_add[of n ?y ?z] y_dim z_dim carrier_dim_vec by auto\n    finally have \"x \\<in> P\"\n      using y_cone z_cone P by blast\n  } moreover {\n    fix x :: \"'a vec\"\n    assume xn: \"x \\<in> carrier_vec n\"\n    hence \"(x @\\<^sub>v vec_of_scal 1 \\<in> next_dim.polyhedral_cone B) =\n          (B *\\<^sub>v (x @\\<^sub>v vec_of_scal 1) \\<le> 0\\<^sub>v nr)\"\n      unfolding next_dim.polyhedral_cone_def using B_carrier\n      using append_carrier_vec[OF _ vec_of_scal_dim(2)[of 1]] by auto\n    also have \"\\<dots> = ((A @\\<^sub>c mat_of_col b) *\\<^sub>v (x @\\<^sub>v vec_of_scal 1) \\<le> 0\\<^sub>v nr)\"\n      using B_blocks by blast\n    also have \"(A @\\<^sub>c mat_of_col b) *\\<^sub>v (x @\\<^sub>v vec_of_scal 1) =\n               A *\\<^sub>v x + mat_of_col b *\\<^sub>v vec_of_scal 1\"\n      by (rule mat_mult_append_cols, insert A_carrier b_carrier xn, auto simp del: One_nat_def)\n    also have \"mat_of_col b *\\<^sub>v vec_of_scal 1 = b\"\n      using mult_mat_of_row_vec_of_scal[of b 1] by simp\n    also have \"A *\\<^sub>v x + b = A *\\<^sub>v x - -b\" by auto\n    finally have \"(x @\\<^sub>v vec_of_scal 1 \\<in> next_dim.polyhedral_cone B) = (A *\\<^sub>v x \\<le> -b)\"\n      using vec_le_iff_diff_le_0[of \"A *\\<^sub>v x\" \"-b\"] A_carrier by simp\n  }\n  ultimately have \"P = polyhedron A (-b)\"\n    unfolding polyhedron_def using B by blast\n  moreover have \"-b \\<in> carrier_vec nr\" using b_carrier by simp\n  ultimately show ?thesis using A_carrier by blast\nqed\n\nlemma decomposition_theorem_polyhedra:\n  \"(\\<exists> A b nr. A \\<in> carrier_mat nr n \\<and> b \\<in> carrier_vec nr \\<and> P = polyhedron A b) \\<longleftrightarrow>\n   (\\<exists> Q X. Q \\<union> X \\<subseteq> carrier_vec n \\<and> finite (Q \\<union> X) \\<and> P = convex_hull Q + cone X)\" (is \"?l = ?r\")\nproof\n  assume ?l\n  then obtain A b nr where A: \"A \\<in> carrier_mat nr n\"\n    and b: \"b \\<in> carrier_vec nr\" and P: \"P = polyhedron A b\" by auto\n  from decomposition_theorem_polyhedra_1[OF this] obtain Q X\n    where *: \"X \\<subseteq> carrier_vec n\" \"finite X\" \"Q \\<subseteq> carrier_vec n\" \"finite Q\" \"P = convex_hull Q + cone X\"\n    by meson\n  show ?r\n    by (rule exI[of _ Q], rule exI[of _ X], insert *, auto simp: polytope_def)\nnext\n  assume ?r\n  then obtain Q X where QX_carrier: \"Q \\<union> X \\<subseteq> carrier_vec n\"\n    and QX_fin: \"finite (Q \\<union> X)\"\n    and P: \"P = convex_hull Q + cone X\" by blast\n  from QX_carrier have Q: \"Q \\<subseteq> carrier_vec n\" and X: \"X \\<subseteq> carrier_vec n\" by simp_all\n  from QX_fin have fin_Q: \"finite Q\" and fin_X: \"finite X\" by simp_all\n  show ?l using decomposition_theorem_polyhedra_2[OF Q fin_Q X fin_X P] by blast\nqed\n\nlemma polytope_equiv_bounded_polyhedron:\n  \"polytope P \\<longleftrightarrow>\n  (\\<exists>A b nr bnd. A \\<in> carrier_mat nr n \\<and> b \\<in> carrier_vec nr \\<and> P = polyhedron A b \\<and> P \\<subseteq> Bounded_vec bnd)\"\nproof\n  assume polyP: \"polytope P\"\n  from this obtain Q where Qcarr: \"Q \\<subseteq> carrier_vec n\" and finQ: \"finite Q\"\n    and PconvhQ: \"P = convex_hull Q\" unfolding polytope_def by auto\n  let ?X = \"{}\"\n  have \"convex_hull Q + {0\\<^sub>v n} = convex_hull Q\" using Qcarr add_0_right_vecset[of \"convex_hull Q\"]\n    by (simp add: convex_hull_carrier)\n  hence \"P = convex_hull Q + cone ?X\" using PconvhQ by simp\n  hence \"Q \\<union> ?X \\<subseteq> carrier_vec n \\<and> finite (Q \\<union> ?X) \\<and> P = convex_hull Q + cone ?X\"\n    using Qcarr finQ PconvhQ by simp\n  hence \"\\<exists> A b nr. A \\<in> carrier_mat nr n \\<and> b \\<in> carrier_vec nr \\<and> P = polyhedron A b\"\n    using decomposition_theorem_polyhedra by blast\n  hence Ppolyh: \"\\<exists>A b nr. A \\<in> carrier_mat nr n \\<and> b \\<in> carrier_vec nr \\<and> P = polyhedron A b\" by blast\n  from finite_Bounded_vec_Max[OF Qcarr finQ] obtain bnd where \"Q \\<subseteq> Bounded_vec bnd\" by auto\n  hence Pbnd: \"P \\<subseteq> Bounded_vec bnd\" using convex_hull_bound PconvhQ Qcarr by auto\n  from Ppolyh Pbnd show \"\\<exists>A b nr bnd. A \\<in> carrier_mat nr n \\<and> b \\<in> carrier_vec nr\n    \\<and> P = polyhedron A b \\<and> P \\<subseteq> Bounded_vec bnd\" by auto\nnext\n  assume \"\\<exists>A b nr bnd. A \\<in> carrier_mat nr n \\<and> b \\<in> carrier_vec nr \\<and> P = polyhedron A b\n    \\<and> P \\<subseteq> Bounded_vec bnd\"\n  from this obtain A b nr bnd where Adim: \"A \\<in> carrier_mat nr n\" and bdim: \"b \\<in> carrier_vec nr\"\n    and Ppolyh: \"P = polyhedron A b\" and Pbnd: \"P \\<subseteq> Bounded_vec bnd\" by auto\n  have \"\\<exists> A b nr. A \\<in> carrier_mat nr n \\<and> b \\<in> carrier_vec nr \\<and> P = polyhedron A b\"\n    using Adim bdim Ppolyh by blast\n  hence \"\\<exists> Q X. Q \\<union> X \\<subseteq> carrier_vec n \\<and> finite (Q \\<union> X) \\<and> P = convex_hull Q + cone X\"\n    using decomposition_theorem_polyhedra by simp\n  from this obtain Q X where QXcarr: \"Q \\<union> X \\<subseteq> carrier_vec n\"\n    and finQX: \"finite (Q \\<union> X)\" and Psum: \"P = convex_hull Q + cone X\" by auto\n  from QXcarr have Qcarr: \"convex_hull Q \\<subseteq> carrier_vec n\" by (simp add: convex_hull_carrier)\n  from QXcarr have Xcarr: \"cone X \\<subseteq> carrier_vec n\" by (simp add: gram_schmidt.cone_carrier)\n  from Pbnd have Pcarr: \"P \\<subseteq> carrier_vec n\" using Ppolyh unfolding polyhedron_def by simp\n  have \"P = convex_hull Q\"\n  proof(cases \"Q = {}\")\n    case True\n    then show \"P = convex_hull Q\" unfolding Psum by (auto simp: set_plus_def)\n  next\n    case False\n    hence convnotempty: \"convex_hull Q \\<noteq> {}\" using QXcarr by simp\n    have Pbndex: \"\\<exists>bnd. P \\<subseteq> Bounded_vec bnd\" using Pbnd\n      using QXcarr by auto\n    from False have \"(\\<exists> bndc. cone X \\<subseteq> Bounded_vec bndc)\"\n      using bounded_vecset_sum[OF Qcarr Xcarr Psum Pbndex] False convnotempty by blast\n    hence \"cone X = {0\\<^sub>v n}\" using bounded_cone_is_zero QXcarr by auto\n    thus ?thesis unfolding Psum using Qcarr by (auto simp: add_0_right_vecset)\n  qed\n  thus \"polytope P\" using finQX QXcarr unfolding polytope_def by auto\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/Decomposition_Theorem.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339516289534, "lm_q2_score": 0.8397339616560072, "lm_q1q2_score": 0.7051531179384349}}
{"text": "(* Authors:  Ren\u00e9 Neumann and Florian Haftmann, TU Muenchen *)\n\nheader {* Functional Binomial Queues *}\n\ntheory Binomial_Queue\nimports PQ\nbegin\n\nsubsection {* Type definition and projections *}\n\ndatatype ('a, 'b) bintree = Node \"'a\" \"'b\" \"('a, 'b) bintree list\"\n\nprimrec priority :: \"('a, 'b) bintree \\<Rightarrow> 'a\" where\n  \"priority (Node a _ _) = a\"\n\nprimrec val :: \"('a, 'b) bintree \\<Rightarrow> 'b\" where\n  \"val (Node _ v _) = v\"\n\nprimrec children :: \"('a, 'b) bintree \\<Rightarrow> ('a, 'b) bintree list\" where\n  \"children (Node _ _ ts) = ts\"\n\ntype_synonym ('a, 'b) binqueue = \"('a, 'b) bintree option list\"\n\nlemma binqueue_induct [case_names Empty None Some, induct type: binqueue]:\n  assumes \"P []\"\n  and \"\\<And>xs. P xs \\<Longrightarrow> P (None # xs)\"\n  and \"\\<And>x xs. P xs \\<Longrightarrow> P (Some x # xs)\"\n  shows \"P xs\"\nusing assms proof (induct xs)\n  case (Cons x xs) thus ?case by (cases x) simp_all\nqed simp\n\ntext {*\n  \\noindent Terminology:\n\n  \\begin{itemize}\n\n    \\item values @{text \"v, w\"} or @{text \"v1, v2\"}\n\n    \\item priorities @{text \"a, b\"} or @{text \"a1, a2\"}\n\n    \\item bintrees @{text \"t, r\"} or @{text \"t1, t2\"}\n\n    \\item bintree lists @{text \"ts, rs\"} or @{text \"ts1, ts2\"}\n\n    \\item binqueue element @{text \"x, y\"} or @{text \"x1, x2\"}\n\n    \\item binqueues = binqueue element lists @{text \"xs, ys\"} or @{text \"xs1, xs2\"}\n\n    \\item abstract priority queues @{text \"q, p\"} or @{text \"q1, q2\"}\n\n  \\end{itemize}\n*}\n\n\nsubsection {* Binomial queue properties *}\n\nsubsubsection {* Binomial tree property *}\n\ninductive is_bintree_list :: \"nat \\<Rightarrow> ('a, 'b) bintree list \\<Rightarrow> bool\" where\n  is_bintree_list_Nil [simp]: \"is_bintree_list 0 []\"\n| is_bintree_list_Cons: \"is_bintree_list l ts \\<Longrightarrow> is_bintree_list l (children t)\n    \\<Longrightarrow> is_bintree_list (Suc l) (t # ts)\"\n\nabbreviation (input) \"is_bintree k t \\<equiv> is_bintree_list k (children t)\"\n\nlemma is_bintree_list_triv [simp]:\n  \"is_bintree_list 0 ts \\<longleftrightarrow> ts = []\"\n  \"is_bintree_list l [] \\<longleftrightarrow> l = 0\"\n  by (auto intro: is_bintree_list.intros elim: is_bintree_list.cases)\n\nlemma is_bintree_list_simp [simp]:\n  \"is_bintree_list (Suc l) (t # ts) \\<longleftrightarrow>\n    is_bintree_list l (children t) \\<and> is_bintree_list l ts\"\n  by (auto intro: is_bintree_list.intros elim: is_bintree_list.cases)\n\nlemma is_bintree_list_length [simp]:\n  \"is_bintree_list l ts \\<Longrightarrow> length ts = l\"\n  by (erule is_bintree_list.induct) simp_all\n\nlemma is_bintree_list_children_last:\n  assumes \"is_bintree_list l ts\" and \"ts \\<noteq> []\"\n  shows \"children (last ts) = []\"\n  using assms by induct auto\n\nlemma is_bintree_children_length_desc:\n  assumes \"is_bintree_list l ts\"\n  shows \"map (length \\<circ> children) ts = rev [0..<l]\"\n  using assms by (induct ts) simp_all\n\n\nsubsubsection {* Heap property *}\n\ninductive is_heap_list :: \"'a::linorder \\<Rightarrow> ('a, 'b) bintree list \\<Rightarrow> bool\" where\n  is_heap_list_Nil: \"is_heap_list h []\"\n| is_heap_list_Cons: \"is_heap_list h ts \\<Longrightarrow> is_heap_list (priority t) (children t)\n    \\<Longrightarrow> (priority t) \\<ge> h \\<Longrightarrow> is_heap_list h (t # ts)\"\n\nabbreviation (input) \"is_heap t \\<equiv> is_heap_list (priority t) (children t)\"\n\nlemma is_heap_list_simps [simp]:\n  \"is_heap_list h [] \\<longleftrightarrow> True\"\n  \"is_heap_list h (t # ts) \\<longleftrightarrow>\n    is_heap_list h ts \\<and> is_heap_list (priority t) (children t) \\<and> priority t \\<ge> h\"\n  by (auto intro: is_heap_list.intros elim: is_heap_list.cases)\n\nlemma is_heap_list_append_dest [dest]:\n  \"is_heap_list l (ts@rs) \\<Longrightarrow> is_heap_list l ts\"\n  \"is_heap_list l (ts@rs) \\<Longrightarrow> is_heap_list l rs\"\n  by (induct ts) (auto intro: is_heap_list.intros elim: is_heap_list.cases)\n\nlemma is_heap_list_rev:\n  \"is_heap_list l ts \\<Longrightarrow> is_heap_list l (rev ts)\"\n  by (induct ts rule: rev_induct) auto\n\nlemma is_heap_children_larger:\n  \"is_heap t \\<Longrightarrow> \\<forall> x \\<in> set (children t). priority x \\<ge> priority t\"\n  by (erule is_heap_list.induct) simp_all\n\nlemma is_heap_Min_children_larger:\n  \"is_heap t \\<Longrightarrow> children t \\<noteq> [] \\<Longrightarrow> \n   priority t \\<le> Min (priority ` set (children t))\"\n  by (simp add: is_heap_children_larger)\n\n\nsubsubsection {* Combination of both: binqueue property *}\n\ninductive is_binqueue :: \"nat \\<Rightarrow> ('a::linorder, 'b) binqueue \\<Rightarrow> bool\" where\n  Empty: \"is_binqueue l []\"\n| None: \"is_binqueue (Suc l) xs \\<Longrightarrow> is_binqueue l (None # xs)\"\n| Some: \"is_binqueue (Suc l) xs \\<Longrightarrow> is_bintree l t\n    \\<Longrightarrow> is_heap t \\<Longrightarrow> is_binqueue l (Some t # xs)\"\n\nlemma is_binqueue_simp [simp]:\n  \"is_binqueue l [] \\<longleftrightarrow> True\"\n  \"is_binqueue l (Some t # xs) \\<longleftrightarrow>\n    is_bintree l t \\<and> is_heap t \\<and> is_binqueue (Suc l) xs\"\n  \"is_binqueue l (None # xs) \\<longleftrightarrow> is_binqueue (Suc l) xs\"\n  by (auto intro: is_binqueue.intros elim: is_binqueue.cases)\n\nlemma is_binqueue_trans:\n  \"is_binqueue l (x#xs) \\<Longrightarrow> is_binqueue (Suc l) xs\"\n  by (cases x) simp_all\n\nlemma is_binqueue_head:\n  \"is_binqueue l (x#xs) \\<Longrightarrow> is_binqueue l [x]\"\n  by (cases x) simp_all\n\nlemma is_binqueue_append:\n  \"is_binqueue l xs \\<Longrightarrow> is_binqueue (length xs + l) ys \\<Longrightarrow> is_binqueue l (xs @ ys)\"\n  by (induct xs arbitrary: l) (auto intro: is_binqueue.intros elim: is_binqueue.cases)\n\nlemma is_binqueue_append_dest [dest]:\n  \"is_binqueue l (xs @ ys) \\<Longrightarrow> is_binqueue l xs\"\n  by (induct xs arbitrary: l) (auto intro: is_binqueue.intros elim: is_binqueue.cases)\n\nlemma is_binqueue_children:\n  assumes \"is_bintree_list l ts\"\n  and \"is_heap_list t ts\"\n  shows \"is_binqueue 0 (map Some (rev ts))\"\n  using assms by (induct ts) (auto simp add: is_binqueue_append)\n\nlemma is_binqueue_select:\n  \"is_binqueue l xs \\<Longrightarrow> Some t \\<in> set xs \\<Longrightarrow> \\<exists>k. is_bintree k t \\<and> is_heap t\"\n  by (induct xs arbitrary: l) (auto intro: is_binqueue.intros elim: is_binqueue.cases)\n\n\nsubsubsection {* Normalized representation *}\n\ninductive normalized :: \"('a, 'b) binqueue \\<Rightarrow> bool\" where\n  normalized_Nil: \"normalized []\"\n| normalized_single: \"normalized [Some t]\"\n| normalized_append: \"xs \\<noteq> [] \\<Longrightarrow> normalized xs \\<Longrightarrow> normalized (ys @ xs)\"\n\n\n\nlemma normalized_simps [simp]:\n  \"normalized [] \\<longleftrightarrow> True\"\n  \"normalized (Some t # xs) \\<longleftrightarrow> normalized xs\"\n  \"normalized (None # xs) \\<longleftrightarrow> xs \\<noteq> [] \\<and> normalized xs\"\n  by (simp_all add: normalized_last_not_None)\n\nlemma normalized_map_Some [simp]:\n  \"normalized (map Some xs)\"\n  by (induct xs) simp_all\n\nlemma normalized_Cons:\n  \"normalized (x#xs) \\<Longrightarrow> normalized xs\"\n  by (auto simp add: normalized_last_not_None)\n\nlemma normalized_append:\n  \"normalized xs \\<Longrightarrow> normalized ys \\<Longrightarrow> normalized (xs@ys)\"\n  by (cases ys) (simp_all add: normalized_last_not_None)\n\nlemma normalized_not_None:\n  \"normalized xs \\<Longrightarrow> set xs \\<noteq> {None}\"\n  by (induct xs) (auto simp add: normalized_Cons [of _ ts] dest: subset_singletonD) \n\nprimrec normalize' :: \"('a, 'b) binqueue \\<Rightarrow> ('a, 'b) binqueue\" where\n  \"normalize' [] = []\"\n| \"normalize' (x # xs) =\n    (case x of None \\<Rightarrow> normalize' xs | Some t \\<Rightarrow> (x # xs))\"\n\ndefinition normalize :: \"('a, 'b) binqueue \\<Rightarrow> ('a, 'b) binqueue\" where\n  \"normalize xs = rev (normalize' (rev xs))\"\n\nlemma normalized_normalize:\n  \"normalized (normalize xs)\"\nproof (induct xs rule: rev_induct)\n  case (snoc y ys) then show ?case \n    by (cases y) (simp_all add: normalized_last_not_None normalize_def)\nqed (simp add: normalize_def)\n\nlemma is_binqueue_normalize:\n  \"is_binqueue l xs \\<Longrightarrow> is_binqueue l (normalize xs)\"\n  unfolding normalize_def\n    by (induct xs arbitrary: l rule: rev_induct) (auto split: option.split)\n\n\nsubsection {* Operations *}\n\nsubsubsection {* Adding data *}\n\ndefinition merge :: \"('a::linorder, 'b) bintree \\<Rightarrow> ('a, 'b) bintree \\<Rightarrow> ('a, 'b) bintree\" where\n  \"merge t1 t2 = (if priority t1 < priority t2\n    then Node (priority t1) (val t1) (t2 # children t1) \n    else Node (priority t2) (val t2) (t1 # children t2))\"\n\nlemma is_bintree_list_merge:\n  assumes \"is_bintree l t1\" \"is_bintree l t2\"\n  shows \"is_bintree (Suc l) (merge t1 t2)\"\n  using assms by (simp add: merge_def)\n\nlemma is_heap_merge:\n  assumes \"is_heap t1\" \"is_heap t2\"\n  shows \"is_heap (merge t1 t2)\"\n  using assms by (auto simp add: merge_def)\n\nfun\n  add :: \"('a::linorder, 'b) bintree option \\<Rightarrow> ('a, 'b) binqueue \\<Rightarrow> ('a, 'b) binqueue\"\nwhere\n  \"add None xs = xs\"\n| \"add (Some t) [] = [Some t]\"\n| \"add (Some t) (None # xs) = Some t # xs\"\n| \"add (Some t) (Some r # xs) = None # add (Some (merge t r)) xs\"\n\nlemma add_Some_not_Nil [simp]:\n  \"add (Some t) xs \\<noteq> []\"\n  by (induct \"Some t\" xs rule: add.induct) simp_all\n\nlemma normalized_add:\n  assumes \"normalized xs\"\n  shows \"normalized (add x xs)\"\n  using assms by (induct xs rule: add.induct) simp_all\n\nlemma is_binqueue_add_None:\n  assumes \"is_binqueue l xs\"\n  shows \"is_binqueue l (add None xs)\"\n  using assms by simp\n\nlemma is_binqueue_add_Some:\n  assumes \"is_binqueue l xs\"\n  and     \"is_bintree l t\"\n  and     \"is_heap t\"\n  shows \"is_binqueue l (add (Some t) xs)\"\n  using assms by (induct xs arbitrary: t) (simp_all add: is_bintree_list_merge is_heap_merge)\n\nfunction\n  meld :: \"('a::linorder, 'b) binqueue \\<Rightarrow> ('a, 'b) binqueue \\<Rightarrow> ('a, 'b) binqueue\"\nwhere\n  \"meld [] ys = ys\"\n| \"meld xs [] = xs\"\n| \"meld (None # xs) (y # ys) = y # meld xs ys\"\n| \"meld (x # xs) (None # ys) = x # meld xs ys\"\n| \"meld (Some t # xs) (Some r # ys) =\n    None # add (Some (merge t r)) (meld xs ys)\"\n  by pat_completeness auto termination by lexicographic_order\n\nlemma meld_singleton_add [simp]:\n  \"meld [Some t] xs = add (Some t) xs\"\n  by (induct \"Some t\" xs rule: add.induct) simp_all\n\nlemma nonempty_meld [simp]:\n  \"xs \\<noteq> [] \\<Longrightarrow> meld xs ys \\<noteq> []\"\n  \"ys \\<noteq> [] \\<Longrightarrow> meld xs ys \\<noteq> []\"\n  by (induct xs ys rule: meld.induct) auto\n\nlemma nonempty_meld_commute:\n  \"meld xs ys \\<noteq> [] \\<Longrightarrow> meld xs ys \\<noteq> []\"\n  by (induct xs ys rule: meld.induct) auto\n\nlemma is_binqueue_meld:\n  assumes \"is_binqueue l xs\"\n  and     \"is_binqueue l ys\"\n  shows \"is_binqueue l (meld xs ys)\"\nusing assms\nproof (induct xs ys arbitrary: l rule: meld.induct)\n  fix xs ys :: \"('a, 'b) binqueue\"\n  fix y :: \"('a, 'b) bintree option\"\n  fix l :: nat\n  assume \"\\<And> l. is_binqueue l xs \\<Longrightarrow> is_binqueue l ys\n      \\<Longrightarrow> is_binqueue l (meld xs ys)\"\n    and \"is_binqueue l (None # xs)\"\n    and \"is_binqueue l (y # ys)\"\n  then show \"is_binqueue l (meld (None # xs) (y # ys))\" by (cases y) simp_all\nnext\n  fix xs ys :: \"('a, 'b) binqueue\"\n  fix x :: \"('a, 'b) bintree option\"\n  fix l :: nat\n  assume \"\\<And> l. is_binqueue l xs \\<Longrightarrow> is_binqueue l ys\n      \\<Longrightarrow> is_binqueue l (meld xs ys)\"\n    and \"is_binqueue l (x # xs)\"\n    and \"is_binqueue l (None # ys)\"\n  then show \"is_binqueue l (meld (x # xs) (None # ys))\" by (cases x) simp_all\nqed (simp_all add: is_bintree_list_merge is_heap_merge is_binqueue_add_Some)\n\nlemma normalized_meld:\n  assumes \"normalized xs\"\n  and     \"normalized ys\"\n  shows   \"normalized (meld xs ys)\"\nusing assms\nproof (induct xs ys rule: meld.induct)\n  fix xs ys :: \"('a, 'b) binqueue\"\n  fix y :: \"('a, 'b) bintree option\"\n  assume \"normalized xs \\<Longrightarrow> normalized ys \\<Longrightarrow> normalized (meld xs ys)\"\n    and  \"normalized (None # xs)\"\n    and  \"normalized (y # ys)\"\n  then show \"normalized (meld (None # xs) (y # ys))\" by (cases y) simp_all\nnext\n  fix xs ys :: \"('a, 'b) binqueue\"\n  fix x :: \"('a, 'b) bintree option\"\n  assume \"normalized xs \\<Longrightarrow> normalized ys \\<Longrightarrow> normalized (meld xs ys)\"\n    and  \"normalized (x # xs)\"\n    and  \"normalized (None # ys)\"\n  then show \"normalized (meld (x # xs) (None # ys))\" by (cases x) simp_all\nqed (simp_all add: normalized_add)\n\nlemma normalized_meld_weak:\n  assumes \"normalized xs\"\n  and \"length ys \\<le> length xs\"\n  shows \"normalized (meld xs ys)\"\nusing assms\nproof (induct xs ys rule: meld.induct)\n  fix xs ys :: \"('a, 'b) binqueue\"\n  fix y :: \"('a, 'b) bintree option\"\n  assume \"normalized xs \\<Longrightarrow> length ys \\<le> length xs \\<Longrightarrow> normalized (meld xs ys)\"\n    and  \"normalized (None # xs)\"\n    and  \"length (y # ys) \\<le> length (None # xs)\"\n  then show \"normalized (meld (None # xs) (y # ys))\" by (cases y) simp_all\nnext\n  fix xs ys :: \"('a, 'b) binqueue\"\n  fix x :: \"('a, 'b) bintree option\"\n  assume \"normalized xs \\<Longrightarrow> length ys \\<le> length xs \\<Longrightarrow> normalized (meld xs ys)\"\n    and  \"normalized (x # xs)\"\n    and  \"length (None # ys) \\<le> length (x # xs)\"\n  then show \"normalized (meld (x # xs) (None # ys))\" by (cases x) simp_all\nqed (simp_all add: normalized_add)\n\ndefinition least :: \"'a::linorder option \\<Rightarrow> 'a option \\<Rightarrow> 'a option\" where\n  \"least x y = (case x of\n      None \\<Rightarrow> y\n    | Some x' \\<Rightarrow> (case y of\n           None \\<Rightarrow> x\n         | Some y' \\<Rightarrow> if x' \\<le> y' then x else y))\"\n\nlemma least_simps [simp, code]:\n  \"least None x = x\"\n  \"least x None = x\"\n  \"least (Some x') (Some y') = (if x' \\<le> y' then Some x' else Some y')\"\n  unfolding least_def by (simp_all) (cases x, simp_all)\n\nlemma least_split:\n  assumes \"least x y = Some z\"\n  shows \"x = Some z \\<or> y = Some z\"\nusing assms proof (cases x)\n  case (Some x') with assms show ?thesis by (cases y) (simp_all add: eq_commute)\nqed simp\n\ninterpretation least!: semilattice least proof\nqed (auto simp add: least_def split: option.split)\n\ndefinition min :: \"('a::linorder, 'b) binqueue \\<Rightarrow> 'a option\" where\n  \"min xs = fold least (map (map_option priority) xs) None\"\n\nlemma min_simps [simp]:\n  \"min [] = None\"\n  \"min (None # xs) = min xs\"\n  \"min (Some t # xs) = least (Some (priority t)) (min xs)\"\n  by (simp_all add: min_def fold_commute_apply [symmetric]\n    fun_eq_iff least.left_commute del: least_simps)\n\n\n\nlemma min_single:\n  \"min [x] = Some a \\<Longrightarrow> priority (the x) = a\"\n  \"min [x] = None \\<Longrightarrow> x = None\"\n  by (auto simp add: min_def)\n\nlemma min_Some_not_None:\n  \"min (Some t # xs) \\<noteq> None\"\n  by (cases \"min xs\") simp_all\n\nlemma min_None_trans:\n  assumes \"min (x#xs) = None\"\n  shows \"min xs = None\"\nusing assms proof (cases x)\n  case None with assms show ?thesis by simp\nnext\n  case (Some t) with assms show ?thesis by (simp only: min_Some_not_None)\nqed\n\nlemma min_None_None:\n  \"min xs = None \\<longleftrightarrow> xs = [] \\<or> set xs = {None}\"\nproof (rule iffI)\n  have splitQ: \"\\<And> xs. xs \\<subseteq> {None} \\<Longrightarrow> xs = {} \\<or> xs = {None}\" by auto\n\n  assume \"min xs = None\"\n  then have \"set xs \\<subseteq> {None}\"\n  proof (induct xs)\n    case (None ys) thus ?case using min_None_trans[of _ ys] by simp_all\n  next\n    case (Some t ys) thus ?case using min_Some_not_None[of t ys] by simp \n  qed simp\n \n  with splitQ show \"xs = [] \\<or> set xs = {None}\" by auto\nnext\n  show \"xs = [] \\<or> set xs = {None} \\<Longrightarrow> min xs = None\"\n    by (induct xs) (auto dest: subset_singletonD)\nqed\n\nlemma normalized_min_not_None:\n  \"normalized xs \\<Longrightarrow> xs \\<noteq> [] \\<Longrightarrow> min xs \\<noteq> None\"\n  by (simp add: min_None_None normalized_not_None)\n\nlemma min_is_min:\n  assumes \"normalized xs\"\n  and \"xs \\<noteq> []\"\n  and \"min xs = Some a\"\n  shows \"\\<forall>x \\<in> set xs. x = None \\<or> a \\<le> priority (the x)\"\nusing assms proof (induct xs arbitrary: a rule: binqueue_induct)\n  case (Some t ys) thus ?case\n  proof (cases \"ys = []\")\n    case False\n    with Some have N: \"normalized ys\" using normalized_Cons[of _ ys] by simp\n    with `ys \\<noteq> []` have \"min ys \\<noteq> None\"\n      by (simp add: normalized_min_not_None)\n    then obtain a' where oa': \"min ys = Some a'\" by auto\n    with Some N False\n      have \"\\<forall>y \\<in> set ys. y = None \\<or> a' \\<le> priority (the y)\" by simp\n\n    with Some oa' show ?thesis\n      by (cases \"a' \\<le> priority t\") (auto simp add: least.commute)\n  qed simp\nqed simp_all\n\nlemma min_exists:\n  assumes \"min xs = Some a\"\n  shows \"Some a \\<in> map_option priority ` set xs\"\nproof (rule ccontr)\n  assume \"Some a \\<notin> map_option priority ` set xs\"\n  then have \"\\<forall>x \\<in> set xs. x = None \\<or> priority (the x) \\<noteq> a\" by (induct xs) auto\n  then have \"min xs \\<noteq> Some a\"  \n  proof (induct xs arbitrary: a)\n    case (Some t ys) \n    hence \"priority t \\<noteq> a\" and \"min ys \\<noteq> Some a\" by simp_all\n    show ?case\n    proof (rule ccontr, simp)\n      assume \"least (Some (priority t)) (min ys) = Some a\"\n      hence \"Some (priority t) = Some a \\<or> min ys = Some a\" by (rule least_split)\n      with `min ys \\<noteq> Some a` have \"priority t = a\" by simp\n      with `priority t \\<noteq> a` show False by simp\n    qed\n  qed simp_all\n  with assms show False by simp\nqed\n\nprimrec find :: \"'a::linorder \\<Rightarrow> ('a, 'b) binqueue \\<Rightarrow> ('a, 'b) bintree option\" where\n  \"find a [] = None\"\n| \"find a (x#xs) = (case x of None \\<Rightarrow> find a xs\n    | Some t \\<Rightarrow> if priority t = a then Some t else find a xs)\"\n\ndeclare find.simps [simp del]\n\nlemma find_simps [simp, code]:\n  \"find a [] = None\"\n  \"find a (None # xs) = find a xs\"\n  \"find a (Some t # xs) = (if priority t = a then Some t else find a xs)\"\n  by (simp_all add: find_def)\n\nlemma find_works:\n  assumes \"Some a \\<in> set (map (map_option priority) xs)\"\n  shows \"\\<exists>t. find a xs = Some t \\<and> priority t = a\"\n  using assms by (induct xs) auto\n\nlemma find_works_not_None:\n  \"Some a \\<in> set (map (map_option priority) xs) \\<Longrightarrow> find a xs \\<noteq> None\"\n  by (drule find_works) auto\n\nlemma find_None:\n  \"find a xs = None \\<Longrightarrow> Some a \\<notin> set (map (map_option priority) xs)\"\n  by (auto simp add: find_works_not_None)\n\nlemma find_exist:\n  \"find a xs = Some t \\<Longrightarrow> Some t \\<in> set xs\"\n  by (induct xs) (simp_all add: eq_commute)\n\ndefinition find_min :: \"('a::linorder, 'b) binqueue \\<Rightarrow> ('a, 'b) bintree option\" where\n  \"find_min xs = (case min xs of None \\<Rightarrow> None | Some a \\<Rightarrow> find a xs)\"\n\nlemma find_min_simps [simp]:\n  \"find_min [] = None\"\n  \"find_min (None # xs) = find_min xs\"\n  by (auto simp add: find_min_def split: option.split)\n\nlemma find_min_single:\n  \"find_min [x] = x\"\n  by (cases x) (auto simp add: find_min_def)\n\nlemma min_eq_find_min_None:\n  \"min xs = None \\<longleftrightarrow> find_min xs = None\"\nproof (rule iffI)\n  show \"min xs = None \\<Longrightarrow> find_min xs = None\"\n    by (simp add: find_min_def)\nnext\n  assume *: \"find_min xs = None\"\n  show \"min xs = None\"\n  proof (rule ccontr)\n    assume \"min xs \\<noteq> None\"\n    \n    then obtain a where \"min xs = Some a\" by auto\n    hence \"find_min xs \\<noteq> None\"\n      by (simp add: find_min_def min_exists find_works_not_None)\n    with * show False by simp\n  qed\nqed\n\nlemma min_eq_find_min_Some:\n  \"min xs = Some a \\<longleftrightarrow> (\\<exists> t. find_min xs = Some t \\<and> priority t = a)\"\nproof (rule iffI)\n  show D1: \"\\<And>a. min xs = Some a\n    \\<Longrightarrow> (\\<exists> t. find_min xs = Some t \\<and> priority t = a)\"\n    by (simp add: find_min_def find_works min_exists)\n  (* no 'next' here to keep D1 in scope as it is needed in the other part *)\n  assume *: \"\\<exists> t. find_min xs = Some t \\<and> priority t = a\"\n  show \"min xs = Some a\"\n  proof (rule ccontr)\n    assume \"min xs \\<noteq> Some a\" thus False\n    proof (cases \"min xs\")\n      case None \n      hence \"find_min xs = None\" by (simp only: min_eq_find_min_None)\n      with * show False by simp\n    next\n      case (Some b) \n      with `min xs \\<noteq> Some a` have \"a \\<noteq> b\" by simp\n      with * Some show False using D1 by auto\n    qed\n  qed\nqed\n\nlemma find_min_exist:\n  assumes \"find_min xs = Some t\"\n  shows \"Some t \\<in> set xs\"\nproof -\n  from assms have \"min xs \\<noteq> None\" by (simp add: min_eq_find_min_None)\n  with assms show ?thesis by (auto simp add: find_min_def find_exist)\nqed\n\nlemma find_min_is_min:\n  assumes \"normalized xs\"\n  and \"xs \\<noteq> []\"\n  and \"find_min xs = Some t\"\n  shows \"\\<forall>x \\<in> set xs. x = None \\<or> (priority t) \\<le> priority (the x)\"\n  using assms by (simp add: min_eq_find_min_Some min_is_min)\n\nlemma normalized_find_min_exists:\n  \"normalized xs \\<Longrightarrow> xs \\<noteq> [] \\<Longrightarrow> \\<exists>t. find_min xs = Some t\"\nby (drule normalized_min_not_None) (simp_all add: min_eq_find_min_None)\n\nprimrec\n  match :: \"'a::linorder \\<Rightarrow> ('a, 'b) bintree option \\<Rightarrow> ('a, 'b) bintree option\"\nwhere\n  \"match a None = None\"\n| \"match a (Some t) = (if priority t = a then None else Some t)\"\n\ndefinition delete_min :: \"('a::linorder, 'b) binqueue \\<Rightarrow> ('a, 'b) binqueue\" where\n  \"delete_min xs = (case find_min xs\n    of Some (Node a v ts) \\<Rightarrow>\n         normalize (meld (map Some (rev ts)) (map (match a) xs)) \n     | None \\<Rightarrow> [])\"\n\nlemma delete_min_empty [simp]:\n  \"delete_min [] = []\"\n  by (simp add: delete_min_def)\n\nlemma delete_min_nonempty [simp]:\n  \"normalized xs \\<Longrightarrow> xs \\<noteq> [] \\<Longrightarrow> find_min xs = Some t\n    \\<Longrightarrow> delete_min xs = normalize\n      (meld (map Some (rev (children t))) (map (match (priority t)) xs))\"\n  unfolding delete_min_def by (cases t) simp\n\nlemma is_binqueue_delete_min:\n  assumes \"is_binqueue 0 xs\"\n  shows \"is_binqueue 0 (delete_min xs)\"\nproof (cases \"find_min xs\")\n  case (Some t)\n  from assms have \"is_binqueue 0 (map (match (priority t)) xs)\"\n    by (induct xs) simp_all\n\n  moreover\n  from Some have \"Some t \\<in> set xs\" by (rule find_min_exist)\n  with assms have \"\\<exists>l. is_bintree l t\" and \"is_heap t\"\n    using is_binqueue_select[of 0 xs t] by auto\n  with assms have \"is_binqueue 0 (map Some (rev (children t)))\"\n    by (auto simp add: is_binqueue_children)\n  \n  ultimately show ?thesis using Some\n    by (auto simp add: is_binqueue_meld delete_min_def is_binqueue_normalize\n      split: bintree.split)\nqed (simp add: delete_min_def)\n\nlemma normalized_delete_min:\n  \"normalized (delete_min xs)\"\n  by (cases \"find_min xs\")\n    (auto simp add: delete_min_def normalized_normalize split: bintree.split)\n\n\nsubsubsection {* Dedicated grand unified operation for generated program *}\n\ndefinition\n  meld' :: \"('a, 'b) bintree option \\<Rightarrow> ('a::linorder, 'b) binqueue\n    \\<Rightarrow> ('a, 'b) binqueue \\<Rightarrow> ('a, 'b) binqueue\"\nwhere\n  \"meld' z xs ys = add z (meld xs ys)\"\n\nlemma [code]:\n  \"add z xs = meld' z [] xs\"\n  \"meld xs ys = meld' None xs ys\"\n  by (simp_all add: meld'_def)\n\nlemma [code]:\n  \"meld' z (Some t # xs) (Some r # ys) =\n    z # (meld' (Some (merge t r)) xs ys)\"\n  \"meld' (Some t) (Some r # xs) (None # ys) =\n    None # (meld' (Some (merge t r)) xs ys)\"\n  \"meld' (Some t) (None # xs) (Some r # ys) =\n    None # (meld' (Some (merge t r)) xs ys)\"\n  \"meld' None (x # xs) (None # ys) = x # (meld' None xs ys)\"\n  \"meld' None (None # xs) (y # ys) = y # (meld' None xs ys)\"\n  \"meld' z (None # xs) (None # ys) = z # (meld' None xs ys)\"\n  \"meld' z xs [] = meld' z [] xs\"\n  \"meld' z [] (y # ys) = meld' None [z] (y # ys)\"\n  \"meld' (Some t) [] ys = meld' None [Some t] ys\"\n  \"meld' None [] ys = ys\"\n  by (simp add: meld'_def | cases z)+\n\n\nsubsubsection {* Interface operations *}\n\nabbreviation (input) empty :: \"('a,'b) binqueue\" where\n  \"empty \\<equiv> []\"\n\ndefinition\n  insert :: \"'a::linorder \\<Rightarrow> 'b \\<Rightarrow> ('a, 'b) binqueue \\<Rightarrow> ('a, 'b) binqueue\"\nwhere\n  \"insert a v xs = add (Some (Node a v [])) xs\"\n\nlemma insert_simps [simp]:\n  \"insert a v [] = [Some (Node a v [])]\"\n  \"insert a v (None # xs) = Some (Node a v []) # xs\"\n  \"insert a v (Some t # xs) = None # add (Some (merge (Node a v []) t)) xs\"\n  by (simp_all add: insert_def)\n\nlemma is_binqueue_insert:\n  \"is_binqueue 0 xs \\<Longrightarrow> is_binqueue 0 (insert a v xs)\"\n  by (simp add: is_binqueue_add_Some insert_def)\n\nlemma normalized_insert:\n  \"normalized xs \\<Longrightarrow> normalized (insert a v xs)\"\n  by (simp add: normalized_add insert_def)\n\ndefinition\n  pop :: \"('a::linorder, 'b) binqueue \\<Rightarrow> (('b \\<times> 'a) option \\<times> ('a, 'b) binqueue)\"\nwhere\n  \"pop xs = (case find_min xs of \n      None \\<Rightarrow> (None, xs) \n    | Some t  \\<Rightarrow> (Some (val t, priority t), delete_min xs))\"\n\nlemma pop_empty [simp]:\n  \"pop empty = (None, empty)\"\n  by (simp add: pop_def empty_def)\n\nlemma pop_nonempty [simp]:\n  \"normalized xs \\<Longrightarrow> xs \\<noteq> [] \\<Longrightarrow> find_min xs = Some t\n    \\<Longrightarrow> pop xs = (Some (val t, priority t), normalize\n      (meld (map Some (rev (children t))) (map (match (priority t)) xs)))\"\n  by (simp add: pop_def)\n\nlemma pop_code [code]:\n  \"pop xs = (case find_min xs of \n      None \\<Rightarrow> (None, xs) \n    | Some t  \\<Rightarrow> (Some (val t, priority t), normalize\n       (meld (map Some (rev (children t))) (map (match (priority t)) xs))))\"\n  by (cases \"find_min xs\") (simp_all add: pop_def delete_min_def split: bintree.split)\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-Queues/Binomial_Queue.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8376199714402812, "lm_q2_score": 0.8418256492357358, "lm_q1q2_score": 0.7051299762705332}}
{"text": "(*  Title:      ZF/equalities.thy\n    Author:     Lawrence C Paulson, Cambridge University Computer Laboratory\n    Copyright   1992  University of Cambridge\n*)\n\nsection\\<open>Basic Equalities and Inclusions\\<close>\n\ntheory equalities imports pair begin\n\ntext\\<open>These cover union, intersection, converse, domain, range, etc.  Philippe\nde Groote proved many of the inclusions.\\<close>\n\nlemma in_mono: \"A\\<subseteq>B \\<Longrightarrow> x\\<in>A \\<longrightarrow> x\\<in>B\"\nby blast\n\nlemma the_eq_0 [simp]: \"(THE x. False) = 0\"\nby (blast intro: the_0)\n\nsubsection\\<open>Bounded Quantifiers\\<close>\ntext \\<open>\\medskip\n\n  The following are not added to the default simpset because\n  (a) they duplicate the body and (b) there are no similar rules for \\<open>Int\\<close>.\\<close>\n\nlemma ball_Un: \"(\\<forall>x \\<in> A\\<union>B. P(x)) \\<longleftrightarrow> (\\<forall>x \\<in> A. P(x)) \\<and> (\\<forall>x \\<in> B. P(x))\"\n  by blast\n\nlemma bex_Un: \"(\\<exists>x \\<in> A\\<union>B. P(x)) \\<longleftrightarrow> (\\<exists>x \\<in> A. P(x)) | (\\<exists>x \\<in> B. P(x))\"\n  by blast\n\nlemma ball_UN: \"(\\<forall>z \\<in> (\\<Union>x\\<in>A. B(x)). 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>x\\<in>A. B(x)). P(z)) \\<longleftrightarrow> (\\<exists>x\\<in>A. \\<exists>z\\<in>B(x). P(z))\"\n  by blast\n\nsubsection\\<open>Converse of a Relation\\<close>\n\nlemma converse_iff [simp]: \"\\<langle>a,b\\<rangle>\\<in> converse(r) \\<longleftrightarrow> \\<langle>b,a\\<rangle>\\<in>r\"\nby (unfold converse_def, blast)\n\nlemma converseI [intro!]: \"\\<langle>a,b\\<rangle>\\<in>r \\<Longrightarrow> \\<langle>b,a\\<rangle>\\<in>converse(r)\"\nby (unfold converse_def, blast)\n\nlemma converseD: \"\\<langle>a,b\\<rangle> \\<in> converse(r) \\<Longrightarrow> \\<langle>b,a\\<rangle> \\<in> r\"\nby (unfold converse_def, blast)\n\nlemma converseE [elim!]:\n    \"\\<lbrakk>yx \\<in> converse(r);\n        \\<And>x y. \\<lbrakk>yx=\\<langle>y,x\\<rangle>;  \\<langle>x,y\\<rangle>\\<in>r\\<rbrakk> \\<Longrightarrow> P\\<rbrakk>\n     \\<Longrightarrow> P\"\nby (unfold converse_def, blast)\n\nlemma converse_converse: \"r\\<subseteq>Sigma(A,B) \\<Longrightarrow> converse(converse(r)) = r\"\nby blast\n\nlemma converse_type: \"r\\<subseteq>A*B \\<Longrightarrow> converse(r)\\<subseteq>B*A\"\nby blast\n\nlemma converse_prod [simp]: \"converse(A*B) = B*A\"\nby blast\n\nlemma converse_empty [simp]: \"converse(0) = 0\"\nby blast\n\nlemma converse_subset_iff:\n     \"A \\<subseteq> Sigma(X,Y) \\<Longrightarrow> converse(A) \\<subseteq> converse(B) \\<longleftrightarrow> A \\<subseteq> B\"\nby blast\n\n\nsubsection\\<open>Finite Set Constructions Using \\<^term>\\<open>cons\\<close>\\<close>\n\nlemma cons_subsetI: \"\\<lbrakk>a\\<in>C; B\\<subseteq>C\\<rbrakk> \\<Longrightarrow> cons(a,B) \\<subseteq> C\"\nby blast\n\nlemma subset_consI: \"B \\<subseteq> cons(a,B)\"\nby blast\n\nlemma cons_subset_iff [iff]: \"cons(a,B)\\<subseteq>C \\<longleftrightarrow> a\\<in>C \\<and> B\\<subseteq>C\"\nby blast\n\n(*A safe special case of subset elimination, adding no new variables\n  \\<lbrakk>cons(a,B) \\<subseteq> C; \\<lbrakk>a \\<in> C; B \\<subseteq> C\\<rbrakk> \\<Longrightarrow> R\\<rbrakk> \\<Longrightarrow> R *)\nlemmas cons_subsetE = cons_subset_iff [THEN iffD1, THEN conjE]\n\nlemma subset_empty_iff: \"A\\<subseteq>0 \\<longleftrightarrow> A=0\"\nby blast\n\nlemma subset_cons_iff: \"C\\<subseteq>cons(a,B) \\<longleftrightarrow> C\\<subseteq>B | (a\\<in>C \\<and> C-{a} \\<subseteq> B)\"\nby blast\n\n(* cons_def refers to Upair; reversing the equality LOOPS in rewriting!*)\nlemma cons_eq: \"{a} \\<union> B = cons(a,B)\"\nby blast\n\nlemma cons_commute: \"cons(a, cons(b, C)) = cons(b, cons(a, C))\"\nby blast\n\nlemma cons_absorb: \"a: B \\<Longrightarrow> cons(a,B) = B\"\nby blast\n\nlemma cons_Diff: \"a: B \\<Longrightarrow> cons(a, B-{a}) = B\"\nby blast\n\nlemma Diff_cons_eq: \"cons(a,B) - C = (if a\\<in>C then B-C else cons(a,B-C))\"\nby auto\n\nlemma equal_singleton: \"\\<lbrakk>a: C;  \\<And>y. y \\<in>C \\<Longrightarrow> y=b\\<rbrakk> \\<Longrightarrow> C = {b}\"\nby blast\n\n\n\n(** singletons **)\n\nlemma singleton_subsetI: \"a\\<in>C \\<Longrightarrow> {a} \\<subseteq> C\"\nby blast\n\nlemma singleton_subsetD: \"{a} \\<subseteq> C  \\<Longrightarrow>  a\\<in>C\"\nby blast\n\n\n(** succ **)\n\nlemma subset_succI: \"i \\<subseteq> succ(i)\"\nby blast\n\n(*But if j is an ordinal or is transitive, then @{term\"i\\<in>j\"} implies @{term\"i\\<subseteq>j\"}!\n  See @{text\"Ord_succ_subsetI}*)\nlemma succ_subsetI: \"\\<lbrakk>i\\<in>j;  i\\<subseteq>j\\<rbrakk> \\<Longrightarrow> succ(i)\\<subseteq>j\"\nby (unfold succ_def, blast)\n\nlemma succ_subsetE:\n    \"\\<lbrakk>succ(i) \\<subseteq> j;  \\<lbrakk>i\\<in>j;  i\\<subseteq>j\\<rbrakk> \\<Longrightarrow> P\\<rbrakk> \\<Longrightarrow> P\"\nby (unfold succ_def, blast)\n\nlemma succ_subset_iff: \"succ(a) \\<subseteq> B \\<longleftrightarrow> (a \\<subseteq> B \\<and> a \\<in> B)\"\nby (unfold succ_def, blast)\n\n\nsubsection\\<open>Binary Intersection\\<close>\n\n(** Intersection is the greatest lower bound of two sets **)\n\nlemma Int_subset_iff: \"C \\<subseteq> A \\<inter> B \\<longleftrightarrow> C \\<subseteq> A \\<and> C \\<subseteq> B\"\nby blast\n\nlemma Int_lower1: \"A \\<inter> B \\<subseteq> A\"\nby blast\n\nlemma Int_lower2: \"A \\<inter> B \\<subseteq> B\"\nby blast\n\nlemma Int_greatest: \"\\<lbrakk>C\\<subseteq>A;  C\\<subseteq>B\\<rbrakk> \\<Longrightarrow> C \\<subseteq> A \\<inter> B\"\nby blast\n\nlemma Int_cons: \"cons(a,B) \\<inter> C \\<subseteq> cons(a, B \\<inter> C)\"\nby blast\n\nlemma Int_absorb [simp]: \"A \\<inter> A = A\"\nby blast\n\nlemma Int_left_absorb: \"A \\<inter> (A \\<inter> B) = A \\<inter> B\"\nby blast\n\nlemma Int_commute: \"A \\<inter> B = B \\<inter> A\"\nby blast\n\nlemma Int_left_commute: \"A \\<inter> (B \\<inter> C) = B \\<inter> (A \\<inter> C)\"\nby blast\n\nlemma Int_assoc: \"(A \\<inter> B) \\<inter> C  =  A \\<inter> (B \\<inter> C)\"\nby blast\n\n(*Intersection is an AC-operator*)\nlemmas Int_ac= Int_assoc Int_left_absorb Int_commute Int_left_commute\n\nlemma Int_absorb1: \"B \\<subseteq> A \\<Longrightarrow> A \\<inter> B = B\"\n  by blast\n\nlemma Int_absorb2: \"A \\<subseteq> B \\<Longrightarrow> A \\<inter> B = A\"\n  by blast\n\nlemma Int_Un_distrib: \"A \\<inter> (B \\<union> C) = (A \\<inter> B) \\<union> (A \\<inter> C)\"\nby blast\n\nlemma Int_Un_distrib2: \"(B \\<union> C) \\<inter> A = (B \\<inter> A) \\<union> (C \\<inter> A)\"\nby blast\n\nlemma subset_Int_iff: \"A\\<subseteq>B \\<longleftrightarrow> A \\<inter> B = A\"\nby (blast elim!: equalityE)\n\nlemma subset_Int_iff2: \"A\\<subseteq>B \\<longleftrightarrow> B \\<inter> A = A\"\nby (blast elim!: equalityE)\n\nlemma Int_Diff_eq: \"C\\<subseteq>A \\<Longrightarrow> (A-B) \\<inter> C = C-B\"\nby blast\n\nlemma Int_cons_left:\n     \"cons(a,A) \\<inter> B = (if a \\<in> B then cons(a, A \\<inter> B) else A \\<inter> B)\"\nby auto\n\nlemma Int_cons_right:\n     \"A \\<inter> cons(a, B) = (if a \\<in> A then cons(a, A \\<inter> B) else A \\<inter> B)\"\nby auto\n\nlemma cons_Int_distrib: \"cons(x, A \\<inter> B) = cons(x, A) \\<inter> cons(x, B)\"\nby auto\n\nsubsection\\<open>Binary Union\\<close>\n\n(** Union is the least upper bound of two sets *)\n\nlemma Un_subset_iff: \"A \\<union> B \\<subseteq> C \\<longleftrightarrow> A \\<subseteq> C \\<and> B \\<subseteq> C\"\nby blast\n\nlemma Un_upper1: \"A \\<subseteq> A \\<union> B\"\nby blast\n\nlemma Un_upper2: \"B \\<subseteq> A \\<union> B\"\nby blast\n\nlemma Un_least: \"\\<lbrakk>A\\<subseteq>C;  B\\<subseteq>C\\<rbrakk> \\<Longrightarrow> A \\<union> B \\<subseteq> C\"\nby blast\n\nlemma Un_cons: \"cons(a,B) \\<union> C = cons(a, B \\<union> C)\"\nby blast\n\nlemma Un_absorb [simp]: \"A \\<union> A = A\"\nby blast\n\nlemma Un_left_absorb: \"A \\<union> (A \\<union> B) = A \\<union> B\"\nby blast\n\nlemma Un_commute: \"A \\<union> B = B \\<union> A\"\nby blast\n\nlemma Un_left_commute: \"A \\<union> (B \\<union> C) = B \\<union> (A \\<union> C)\"\nby blast\n\nlemma Un_assoc: \"(A \\<union> B) \\<union> C  =  A \\<union> (B \\<union> C)\"\nby blast\n\n(*Union is an AC-operator*)\nlemmas Un_ac = Un_assoc Un_left_absorb Un_commute Un_left_commute\n\nlemma Un_absorb1: \"A \\<subseteq> B \\<Longrightarrow> A \\<union> B = B\"\n  by blast\n\nlemma Un_absorb2: \"B \\<subseteq> A \\<Longrightarrow> A \\<union> B = A\"\n  by blast\n\nlemma Un_Int_distrib: \"(A \\<inter> B) \\<union> C  =  (A \\<union> C) \\<inter> (B \\<union> C)\"\nby blast\n\nlemma subset_Un_iff: \"A\\<subseteq>B \\<longleftrightarrow> A \\<union> B = B\"\nby (blast elim!: equalityE)\n\nlemma subset_Un_iff2: \"A\\<subseteq>B \\<longleftrightarrow> B \\<union> A = B\"\nby (blast elim!: equalityE)\n\nlemma Un_empty [iff]: \"(A \\<union> B = 0) \\<longleftrightarrow> (A = 0 \\<and> B = 0)\"\nby blast\n\nlemma Un_eq_Union: \"A \\<union> B = \\<Union>({A, B})\"\nby blast\n\nsubsection\\<open>Set Difference\\<close>\n\nlemma Diff_subset: \"A-B \\<subseteq> A\"\nby blast\n\nlemma Diff_contains: \"\\<lbrakk>C\\<subseteq>A;  C \\<inter> B = 0\\<rbrakk> \\<Longrightarrow> C \\<subseteq> A-B\"\nby blast\n\nlemma subset_Diff_cons_iff: \"B \\<subseteq> A - cons(c,C)  \\<longleftrightarrow>  B\\<subseteq>A-C \\<and> c \\<notin> B\"\nby blast\n\nlemma Diff_cancel: \"A - A = 0\"\nby blast\n\nlemma Diff_triv: \"A  \\<inter> B = 0 \\<Longrightarrow> A - B = A\"\nby blast\n\nlemma empty_Diff [simp]: \"0 - A = 0\"\nby blast\n\nlemma Diff_0 [simp]: \"A - 0 = A\"\nby blast\n\nlemma Diff_eq_0_iff: \"A - B = 0 \\<longleftrightarrow> A \\<subseteq> B\"\nby (blast elim: equalityE)\n\n(*NOT SUITABLE FOR REWRITING since {a} \\<equiv> cons(a,0)*)\nlemma Diff_cons: \"A - cons(a,B) = A - B - {a}\"\nby blast\n\n(*NOT SUITABLE FOR REWRITING since {a} \\<equiv> cons(a,0)*)\nlemma Diff_cons2: \"A - cons(a,B) = A - {a} - B\"\nby blast\n\nlemma Diff_disjoint: \"A \\<inter> (B-A) = 0\"\nby blast\n\nlemma Diff_partition: \"A\\<subseteq>B \\<Longrightarrow> A \\<union> (B-A) = B\"\nby blast\n\nlemma subset_Un_Diff: \"A \\<subseteq> B \\<union> (A - B)\"\nby blast\n\nlemma double_complement: \"\\<lbrakk>A\\<subseteq>B; B\\<subseteq>C\\<rbrakk> \\<Longrightarrow> B-(C-A) = A\"\nby blast\n\nlemma double_complement_Un: \"(A \\<union> B) - (B-A) = A\"\nby blast\n\nlemma Un_Int_crazy:\n \"(A \\<inter> B) \\<union> (B \\<inter> C) \\<union> (C \\<inter> A) = (A \\<union> B) \\<inter> (B \\<union> C) \\<inter> (C \\<union> A)\"\napply blast\ndone\n\nlemma Diff_Un: \"A - (B \\<union> C) = (A-B) \\<inter> (A-C)\"\nby blast\n\nlemma Diff_Int: \"A - (B \\<inter> C) = (A-B) \\<union> (A-C)\"\nby blast\n\nlemma Un_Diff: \"(A \\<union> B) - C = (A - C) \\<union> (B - C)\"\nby blast\n\nlemma Int_Diff: \"(A \\<inter> B) - C = A \\<inter> (B - C)\"\nby blast\n\nlemma Diff_Int_distrib: \"C \\<inter> (A-B) = (C \\<inter> A) - (C \\<inter> B)\"\nby blast\n\nlemma Diff_Int_distrib2: \"(A-B) \\<inter> C = (A \\<inter> C) - (B \\<inter> C)\"\nby blast\n\n(*Halmos, Naive Set Theory, page 16.*)\nlemma Un_Int_assoc_iff: \"(A \\<inter> B) \\<union> C = A \\<inter> (B \\<union> C)  \\<longleftrightarrow>  C\\<subseteq>A\"\nby (blast elim!: equalityE)\n\n\nsubsection\\<open>Big Union and Intersection\\<close>\n\n(** Big Union is the least upper bound of a set  **)\n\nlemma Union_subset_iff: \"\\<Union>(A) \\<subseteq> C \\<longleftrightarrow> (\\<forall>x\\<in>A. x \\<subseteq> C)\"\nby blast\n\nlemma Union_upper: \"B\\<in>A \\<Longrightarrow> B \\<subseteq> \\<Union>(A)\"\nby blast\n\nlemma Union_least: \"\\<lbrakk>\\<And>x. x\\<in>A \\<Longrightarrow> x\\<subseteq>C\\<rbrakk> \\<Longrightarrow> \\<Union>(A) \\<subseteq> C\"\nby blast\n\nlemma Union_cons [simp]: \"\\<Union>(cons(a,B)) = a \\<union> \\<Union>(B)\"\nby blast\n\nlemma Union_Un_distrib: \"\\<Union>(A \\<union> B) = \\<Union>(A) \\<union> \\<Union>(B)\"\nby blast\n\nlemma Union_Int_subset: \"\\<Union>(A \\<inter> B) \\<subseteq> \\<Union>(A) \\<inter> \\<Union>(B)\"\nby blast\n\nlemma Union_disjoint: \"\\<Union>(C) \\<inter> A = 0 \\<longleftrightarrow> (\\<forall>B\\<in>C. B \\<inter> A = 0)\"\nby (blast elim!: equalityE)\n\nlemma Union_empty_iff: \"\\<Union>(A) = 0 \\<longleftrightarrow> (\\<forall>B\\<in>A. B=0)\"\nby blast\n\nlemma Int_Union2: \"\\<Union>(B) \\<inter> A = (\\<Union>C\\<in>B. C \\<inter> A)\"\nby blast\n\n(** Big Intersection is the greatest lower bound of a nonempty set **)\n\nlemma Inter_subset_iff: \"A\\<noteq>0  \\<Longrightarrow>  C \\<subseteq> \\<Inter>(A) \\<longleftrightarrow> (\\<forall>x\\<in>A. C \\<subseteq> x)\"\nby blast\n\nlemma Inter_lower: \"B\\<in>A \\<Longrightarrow> \\<Inter>(A) \\<subseteq> B\"\nby blast\n\nlemma Inter_greatest: \"\\<lbrakk>A\\<noteq>0;  \\<And>x. x\\<in>A \\<Longrightarrow> C\\<subseteq>x\\<rbrakk> \\<Longrightarrow> C \\<subseteq> \\<Inter>(A)\"\nby blast\n\n(** Intersection of a family of sets  **)\n\nlemma INT_lower: \"x\\<in>A \\<Longrightarrow> (\\<Inter>x\\<in>A. B(x)) \\<subseteq> B(x)\"\nby blast\n\nlemma INT_greatest: \"\\<lbrakk>A\\<noteq>0;  \\<And>x. x\\<in>A \\<Longrightarrow> C\\<subseteq>B(x)\\<rbrakk> \\<Longrightarrow> C \\<subseteq> (\\<Inter>x\\<in>A. B(x))\"\nby force\n\nlemma Inter_0 [simp]: \"\\<Inter>(0) = 0\"\nby (unfold Inter_def, blast)\n\nlemma Inter_Un_subset:\n     \"\\<lbrakk>z\\<in>A; z\\<in>B\\<rbrakk> \\<Longrightarrow> \\<Inter>(A) \\<union> \\<Inter>(B) \\<subseteq> \\<Inter>(A \\<inter> B)\"\nby blast\n\n(* A good challenge: Inter is ill-behaved on the empty set *)\nlemma Inter_Un_distrib:\n     \"\\<lbrakk>A\\<noteq>0;  B\\<noteq>0\\<rbrakk> \\<Longrightarrow> \\<Inter>(A \\<union> B) = \\<Inter>(A) \\<inter> \\<Inter>(B)\"\nby blast\n\nlemma Union_singleton: \"\\<Union>({b}) = b\"\nby blast\n\nlemma Inter_singleton: \"\\<Inter>({b}) = b\"\nby blast\n\nlemma Inter_cons [simp]:\n     \"\\<Inter>(cons(a,B)) = (if B=0 then a else a \\<inter> \\<Inter>(B))\"\nby force\n\nsubsection\\<open>Unions and Intersections of Families\\<close>\n\nlemma subset_UN_iff_eq: \"A \\<subseteq> (\\<Union>i\\<in>I. B(i)) \\<longleftrightarrow> A = (\\<Union>i\\<in>I. A \\<inter> B(i))\"\nby (blast elim!: equalityE)\n\nlemma UN_subset_iff: \"(\\<Union>x\\<in>A. B(x)) \\<subseteq> C \\<longleftrightarrow> (\\<forall>x\\<in>A. B(x) \\<subseteq> C)\"\nby blast\n\nlemma UN_upper: \"x\\<in>A \\<Longrightarrow> B(x) \\<subseteq> (\\<Union>x\\<in>A. B(x))\"\nby (erule RepFunI [THEN Union_upper])\n\nlemma UN_least: \"\\<lbrakk>\\<And>x. x\\<in>A \\<Longrightarrow> B(x)\\<subseteq>C\\<rbrakk> \\<Longrightarrow> (\\<Union>x\\<in>A. B(x)) \\<subseteq> C\"\nby blast\n\nlemma Union_eq_UN: \"\\<Union>(A) = (\\<Union>x\\<in>A. x)\"\nby blast\n\nlemma Inter_eq_INT: \"\\<Inter>(A) = (\\<Inter>x\\<in>A. x)\"\nby (unfold Inter_def, blast)\n\nlemma UN_0 [simp]: \"(\\<Union>i\\<in>0. A(i)) = 0\"\nby blast\n\nlemma UN_singleton: \"(\\<Union>x\\<in>A. {x}) = A\"\nby blast\n\nlemma UN_Un: \"(\\<Union>i\\<in> A \\<union> B. C(i)) = (\\<Union>i\\<in> A. C(i)) \\<union> (\\<Union>i\\<in>B. C(i))\"\nby blast\n\nlemma INT_Un: \"(\\<Inter>i\\<in>I \\<union> J. A(i)) =\n               (if I=0 then \\<Inter>j\\<in>J. A(j)\n                       else if J=0 then \\<Inter>i\\<in>I. A(i)\n                       else ((\\<Inter>i\\<in>I. A(i)) \\<inter>  (\\<Inter>j\\<in>J. A(j))))\"\nby (simp, blast intro!: equalityI)\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))\"\nby blast\n\n(*Halmos, Naive Set Theory, page 35.*)\nlemma Int_UN_distrib: \"B \\<inter> (\\<Union>i\\<in>I. A(i)) = (\\<Union>i\\<in>I. B \\<inter> A(i))\"\nby blast\n\nlemma Un_INT_distrib: \"I\\<noteq>0 \\<Longrightarrow> B \\<union> (\\<Inter>i\\<in>I. A(i)) = (\\<Inter>i\\<in>I. B \\<union> A(i))\"\nby auto\n\nlemma Int_UN_distrib2:\n     \"(\\<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))\"\nby blast\n\nlemma Un_INT_distrib2: \"\\<lbrakk>I\\<noteq>0;  J\\<noteq>0\\<rbrakk> \\<Longrightarrow>\n      (\\<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))\"\nby auto\n\nlemma UN_constant [simp]: \"(\\<Union>y\\<in>A. c) = (if A=0 then 0 else c)\"\nby force\n\nlemma INT_constant [simp]: \"(\\<Inter>y\\<in>A. c) = (if A=0 then 0 else c)\"\nby force\n\nlemma UN_RepFun [simp]: \"(\\<Union>y\\<in> RepFun(A,f). B(y)) = (\\<Union>x\\<in>A. B(f(x)))\"\nby blast\n\nlemma INT_RepFun [simp]: \"(\\<Inter>x\\<in>RepFun(A,f). B(x))    = (\\<Inter>a\\<in>A. B(f(a)))\"\nby (auto simp add: Inter_def)\n\nlemma INT_Union_eq:\n     \"0 \\<notin> A \\<Longrightarrow> (\\<Inter>x\\<in> \\<Union>(A). B(x)) = (\\<Inter>y\\<in>A. \\<Inter>x\\<in>y. B(x))\"\napply (subgoal_tac \"\\<forall>x\\<in>A. x\\<noteq>0\")\n   prefer 2 apply blast\napply (force simp add: Inter_def ball_conj_distrib)\ndone\n\nlemma INT_UN_eq:\n     \"(\\<forall>x\\<in>A. B(x) \\<noteq> 0)\n      \\<Longrightarrow> (\\<Inter>z\\<in> (\\<Union>x\\<in>A. B(x)). C(z)) = (\\<Inter>x\\<in>A. \\<Inter>z\\<in> B(x). C(z))\"\napply (subst INT_Union_eq, blast)\napply (simp add: Inter_def)\ndone\n\n\n(** Devlin, Fundamentals of Contemporary Set Theory, page 12, exercise 5:\n    Union of a family of unions **)\n\nlemma UN_Un_distrib:\n     \"(\\<Union>i\\<in>I. A(i) \\<union> B(i)) = (\\<Union>i\\<in>I. A(i))  \\<union>  (\\<Union>i\\<in>I. B(i))\"\nby blast\n\nlemma INT_Int_distrib:\n     \"I\\<noteq>0 \\<Longrightarrow> (\\<Inter>i\\<in>I. A(i) \\<inter> B(i)) = (\\<Inter>i\\<in>I. A(i)) \\<inter> (\\<Inter>i\\<in>I. B(i))\"\nby (blast elim!: not_emptyE)\n\nlemma UN_Int_subset:\n     \"(\\<Union>z\\<in>I \\<inter> J. A(z)) \\<subseteq> (\\<Union>z\\<in>I. A(z)) \\<inter> (\\<Union>z\\<in>J. A(z))\"\nby blast\n\n(** Devlin, page 12, exercise 5: Complements **)\n\nlemma Diff_UN: \"I\\<noteq>0 \\<Longrightarrow> B - (\\<Union>i\\<in>I. A(i)) = (\\<Inter>i\\<in>I. B - A(i))\"\nby (blast elim!: not_emptyE)\n\nlemma Diff_INT: \"I\\<noteq>0 \\<Longrightarrow> B - (\\<Inter>i\\<in>I. A(i)) = (\\<Union>i\\<in>I. B - A(i))\"\nby (blast elim!: not_emptyE)\n\n\n(** Unions and Intersections with General Sum **)\n\n(*Not suitable for rewriting: LOOPS!*)\nlemma Sigma_cons1: \"Sigma(cons(a,B), C) = ({a}*C(a)) \\<union> Sigma(B,C)\"\nby blast\n\n(*Not suitable for rewriting: LOOPS!*)\nlemma Sigma_cons2: \"A * cons(b,B) = A*{b} \\<union> A*B\"\nby blast\n\nlemma Sigma_succ1: \"Sigma(succ(A), B) = ({A}*B(A)) \\<union> Sigma(A,B)\"\nby blast\n\nlemma Sigma_succ2: \"A * succ(B) = A*{B} \\<union> A*B\"\nby blast\n\nlemma SUM_UN_distrib1:\n     \"(\\<Sum>x \\<in> (\\<Union>y\\<in>A. C(y)). B(x)) = (\\<Union>y\\<in>A. \\<Sum>x\\<in>C(y). B(x))\"\nby blast\n\nlemma SUM_UN_distrib2:\n     \"(\\<Sum>i\\<in>I. \\<Union>j\\<in>J. C(i,j)) = (\\<Union>j\\<in>J. \\<Sum>i\\<in>I. C(i,j))\"\nby blast\n\nlemma SUM_Un_distrib1:\n     \"(\\<Sum>i\\<in>I \\<union> J. C(i)) = (\\<Sum>i\\<in>I. C(i)) \\<union> (\\<Sum>j\\<in>J. C(j))\"\nby blast\n\nlemma SUM_Un_distrib2:\n     \"(\\<Sum>i\\<in>I. A(i) \\<union> B(i)) = (\\<Sum>i\\<in>I. A(i)) \\<union> (\\<Sum>i\\<in>I. B(i))\"\nby blast\n\n(*First-order version of the above, for rewriting*)\nlemma prod_Un_distrib2: \"I * (A \\<union> B) = I*A \\<union> I*B\"\nby (rule SUM_Un_distrib2)\n\nlemma SUM_Int_distrib1:\n     \"(\\<Sum>i\\<in>I \\<inter> J. C(i)) = (\\<Sum>i\\<in>I. C(i)) \\<inter> (\\<Sum>j\\<in>J. C(j))\"\nby blast\n\nlemma SUM_Int_distrib2:\n     \"(\\<Sum>i\\<in>I. A(i) \\<inter> B(i)) = (\\<Sum>i\\<in>I. A(i)) \\<inter> (\\<Sum>i\\<in>I. B(i))\"\nby blast\n\n(*First-order version of the above, for rewriting*)\nlemma prod_Int_distrib2: \"I * (A \\<inter> B) = I*A \\<inter> I*B\"\nby (rule SUM_Int_distrib2)\n\n(*Cf Aczel, Non-Well-Founded Sets, page 115*)\nlemma SUM_eq_UN: \"(\\<Sum>i\\<in>I. A(i)) = (\\<Union>i\\<in>I. {i} * A(i))\"\nby blast\n\nlemma times_subset_iff:\n     \"(A'*B' \\<subseteq> A*B) \\<longleftrightarrow> (A' = 0 | B' = 0 | (A'\\<subseteq>A) \\<and> (B'\\<subseteq>B))\"\nby blast\n\nlemma Int_Sigma_eq:\n     \"(\\<Sum>x \\<in> A'. B'(x)) \\<inter> (\\<Sum>x \\<in> A. B(x)) = (\\<Sum>x \\<in> A' \\<inter> A. B'(x) \\<inter> B(x))\"\nby blast\n\n(** Domain **)\n\nlemma domain_iff: \"a: domain(r) \\<longleftrightarrow> (\\<exists>y. \\<langle>a,y\\<rangle>\\<in> r)\"\nby (unfold domain_def, blast)\n\nlemma domainI [intro]: \"\\<langle>a,b\\<rangle>\\<in> r \\<Longrightarrow> a: domain(r)\"\nby (unfold domain_def, blast)\n\nlemma domainE [elim!]:\n    \"\\<lbrakk>a \\<in> domain(r);  \\<And>y. \\<langle>a,y\\<rangle>\\<in> r \\<Longrightarrow> P\\<rbrakk> \\<Longrightarrow> P\"\nby (unfold domain_def, blast)\n\nlemma domain_subset: \"domain(Sigma(A,B)) \\<subseteq> A\"\nby blast\n\nlemma domain_of_prod: \"b\\<in>B \\<Longrightarrow> domain(A*B) = A\"\nby blast\n\nlemma domain_0 [simp]: \"domain(0) = 0\"\nby blast\n\nlemma domain_cons [simp]: \"domain(cons(\\<langle>a,b\\<rangle>,r)) = cons(a, domain(r))\"\nby blast\n\nlemma domain_Un_eq [simp]: \"domain(A \\<union> B) = domain(A) \\<union> domain(B)\"\nby blast\n\nlemma domain_Int_subset: \"domain(A \\<inter> B) \\<subseteq> domain(A) \\<inter> domain(B)\"\nby blast\n\nlemma domain_Diff_subset: \"domain(A) - domain(B) \\<subseteq> domain(A - B)\"\nby blast\n\nlemma domain_UN: \"domain(\\<Union>x\\<in>A. B(x)) = (\\<Union>x\\<in>A. domain(B(x)))\"\nby blast\n\nlemma domain_Union: \"domain(\\<Union>(A)) = (\\<Union>x\\<in>A. domain(x))\"\nby blast\n\n\n(** Range **)\n\nlemma rangeI [intro]: \"\\<langle>a,b\\<rangle>\\<in> r \\<Longrightarrow> b \\<in> range(r)\"\n  unfolding range_def\napply (erule converseI [THEN domainI])\ndone\n\nlemma rangeE [elim!]: \"\\<lbrakk>b \\<in> range(r);  \\<And>x. \\<langle>x,b\\<rangle>\\<in> r \\<Longrightarrow> P\\<rbrakk> \\<Longrightarrow> P\"\nby (unfold range_def, blast)\n\nlemma range_subset: \"range(A*B) \\<subseteq> B\"\n  unfolding range_def\napply (subst converse_prod)\napply (rule domain_subset)\ndone\n\nlemma range_of_prod: \"a\\<in>A \\<Longrightarrow> range(A*B) = B\"\nby blast\n\nlemma range_0 [simp]: \"range(0) = 0\"\nby blast\n\nlemma range_cons [simp]: \"range(cons(\\<langle>a,b\\<rangle>,r)) = cons(b, range(r))\"\nby blast\n\nlemma range_Un_eq [simp]: \"range(A \\<union> B) = range(A) \\<union> range(B)\"\nby blast\n\nlemma range_Int_subset: \"range(A \\<inter> B) \\<subseteq> range(A) \\<inter> range(B)\"\nby blast\n\nlemma range_Diff_subset: \"range(A) - range(B) \\<subseteq> range(A - B)\"\nby blast\n\nlemma domain_converse [simp]: \"domain(converse(r)) = range(r)\"\nby blast\n\nlemma range_converse [simp]: \"range(converse(r)) = domain(r)\"\nby blast\n\n\n(** Field **)\n\nlemma fieldI1: \"\\<langle>a,b\\<rangle>\\<in> r \\<Longrightarrow> a \\<in> field(r)\"\nby (unfold field_def, blast)\n\nlemma fieldI2: \"\\<langle>a,b\\<rangle>\\<in> r \\<Longrightarrow> b \\<in> field(r)\"\nby (unfold field_def, blast)\n\nlemma fieldCI [intro]:\n    \"(\\<not> \\<langle>c,a\\<rangle>\\<in>r \\<Longrightarrow> \\<langle>a,b\\<rangle>\\<in> r) \\<Longrightarrow> a \\<in> field(r)\"\napply (unfold field_def, blast)\ndone\n\nlemma fieldE [elim!]:\n     \"\\<lbrakk>a \\<in> field(r);\n         \\<And>x. \\<langle>a,x\\<rangle>\\<in> r \\<Longrightarrow> P;\n         \\<And>x. \\<langle>x,a\\<rangle>\\<in> r \\<Longrightarrow> P\\<rbrakk> \\<Longrightarrow> P\"\nby (unfold field_def, blast)\n\nlemma field_subset: \"field(A*B) \\<subseteq> A \\<union> B\"\nby blast\n\nlemma domain_subset_field: \"domain(r) \\<subseteq> field(r)\"\n  unfolding field_def\napply (rule Un_upper1)\ndone\n\nlemma range_subset_field: \"range(r) \\<subseteq> field(r)\"\n  unfolding field_def\napply (rule Un_upper2)\ndone\n\nlemma domain_times_range: \"r \\<subseteq> Sigma(A,B) \\<Longrightarrow> r \\<subseteq> domain(r)*range(r)\"\nby blast\n\nlemma field_times_field: \"r \\<subseteq> Sigma(A,B) \\<Longrightarrow> r \\<subseteq> field(r)*field(r)\"\nby blast\n\nlemma relation_field_times_field: \"relation(r) \\<Longrightarrow> r \\<subseteq> field(r)*field(r)\"\nby (simp add: relation_def, blast)\n\nlemma field_of_prod: \"field(A*A) = A\"\nby blast\n\nlemma field_0 [simp]: \"field(0) = 0\"\nby blast\n\nlemma field_cons [simp]: \"field(cons(\\<langle>a,b\\<rangle>,r)) = cons(a, cons(b, field(r)))\"\nby blast\n\nlemma field_Un_eq [simp]: \"field(A \\<union> B) = field(A) \\<union> field(B)\"\nby blast\n\nlemma field_Int_subset: \"field(A \\<inter> B) \\<subseteq> field(A) \\<inter> field(B)\"\nby blast\n\nlemma field_Diff_subset: \"field(A) - field(B) \\<subseteq> field(A - B)\"\nby blast\n\nlemma field_converse [simp]: \"field(converse(r)) = field(r)\"\nby blast\n\n(** The Union of a set of relations is a relation -- Lemma for fun_Union **)\nlemma rel_Union: \"(\\<forall>x\\<in>S. \\<exists>A B. x \\<subseteq> A*B) \\<Longrightarrow>\n                  \\<Union>(S) \\<subseteq> domain(\\<Union>(S)) * range(\\<Union>(S))\"\nby blast\n\n(** The Union of 2 relations is a relation (Lemma for fun_Un)  **)\nlemma rel_Un: \"\\<lbrakk>r \\<subseteq> A*B;  s \\<subseteq> C*D\\<rbrakk> \\<Longrightarrow> (r \\<union> s) \\<subseteq> (A \\<union> C) * (B \\<union> D)\"\nby blast\n\nlemma domain_Diff_eq: \"\\<lbrakk>\\<langle>a,c\\<rangle> \\<in> r; c\\<noteq>b\\<rbrakk> \\<Longrightarrow> domain(r-{\\<langle>a,b\\<rangle>}) = domain(r)\"\nby blast\n\nlemma range_Diff_eq: \"\\<lbrakk>\\<langle>c,b\\<rangle> \\<in> r; c\\<noteq>a\\<rbrakk> \\<Longrightarrow> range(r-{\\<langle>a,b\\<rangle>}) = range(r)\"\nby blast\n\n\nsubsection\\<open>Image of a Set under a Function or Relation\\<close>\n\nlemma image_iff: \"b \\<in> r``A \\<longleftrightarrow> (\\<exists>x\\<in>A. \\<langle>x,b\\<rangle>\\<in>r)\"\nby (unfold image_def, blast)\n\nlemma image_singleton_iff: \"b \\<in> r``{a} \\<longleftrightarrow> \\<langle>a,b\\<rangle>\\<in>r\"\nby (rule image_iff [THEN iff_trans], blast)\n\nlemma imageI [intro]: \"\\<lbrakk>\\<langle>a,b\\<rangle>\\<in> r;  a\\<in>A\\<rbrakk> \\<Longrightarrow> b \\<in> r``A\"\nby (unfold image_def, blast)\n\nlemma imageE [elim!]:\n    \"\\<lbrakk>b: r``A;  \\<And>x.\\<lbrakk>\\<langle>x,b\\<rangle>\\<in> r;  x\\<in>A\\<rbrakk> \\<Longrightarrow> P\\<rbrakk> \\<Longrightarrow> P\"\nby (unfold image_def, blast)\n\nlemma image_subset: \"r \\<subseteq> A*B \\<Longrightarrow> r``C \\<subseteq> B\"\nby blast\n\nlemma image_0 [simp]: \"r``0 = 0\"\nby blast\n\nlemma image_Un [simp]: \"r``(A \\<union> B) = (r``A) \\<union> (r``B)\"\nby blast\n\nlemma image_UN: \"r `` (\\<Union>x\\<in>A. B(x)) = (\\<Union>x\\<in>A. r `` B(x))\"\nby blast\n\nlemma Collect_image_eq:\n     \"{z \\<in> Sigma(A,B). P(z)} `` C = (\\<Union>x \\<in> A. {y \\<in> B(x). x \\<in> C \\<and> P(\\<langle>x,y\\<rangle>)})\"\nby blast\n\nlemma image_Int_subset: \"r``(A \\<inter> B) \\<subseteq> (r``A) \\<inter> (r``B)\"\nby blast\n\nlemma image_Int_square_subset: \"(r \\<inter> A*A)``B \\<subseteq> (r``B) \\<inter> A\"\nby blast\n\nlemma image_Int_square: \"B\\<subseteq>A \\<Longrightarrow> (r \\<inter> A*A)``B = (r``B) \\<inter> A\"\nby blast\n\n\n(*Image laws for special relations*)\nlemma image_0_left [simp]: \"0``A = 0\"\nby blast\n\nlemma image_Un_left: \"(r \\<union> s)``A = (r``A) \\<union> (s``A)\"\nby blast\n\nlemma image_Int_subset_left: \"(r \\<inter> s)``A \\<subseteq> (r``A) \\<inter> (s``A)\"\nby blast\n\n\nsubsection\\<open>Inverse Image of a Set under a Function or Relation\\<close>\n\nlemma vimage_iff:\n    \"a \\<in> r-``B \\<longleftrightarrow> (\\<exists>y\\<in>B. \\<langle>a,y\\<rangle>\\<in>r)\"\nby (unfold vimage_def image_def converse_def, blast)\n\nlemma vimage_singleton_iff: \"a \\<in> r-``{b} \\<longleftrightarrow> \\<langle>a,b\\<rangle>\\<in>r\"\nby (rule vimage_iff [THEN iff_trans], blast)\n\nlemma vimageI [intro]: \"\\<lbrakk>\\<langle>a,b\\<rangle>\\<in> r;  b\\<in>B\\<rbrakk> \\<Longrightarrow> a \\<in> r-``B\"\nby (unfold vimage_def, blast)\n\nlemma vimageE [elim!]:\n    \"\\<lbrakk>a: r-``B;  \\<And>x.\\<lbrakk>\\<langle>a,x\\<rangle>\\<in> r;  x\\<in>B\\<rbrakk> \\<Longrightarrow> P\\<rbrakk> \\<Longrightarrow> P\"\napply (unfold vimage_def, blast)\ndone\n\nlemma vimage_subset: \"r \\<subseteq> A*B \\<Longrightarrow> r-``C \\<subseteq> A\"\n  unfolding vimage_def\napply (erule converse_type [THEN image_subset])\ndone\n\nlemma vimage_0 [simp]: \"r-``0 = 0\"\nby blast\n\nlemma vimage_Un [simp]: \"r-``(A \\<union> B) = (r-``A) \\<union> (r-``B)\"\nby blast\n\nlemma vimage_Int_subset: \"r-``(A \\<inter> B) \\<subseteq> (r-``A) \\<inter> (r-``B)\"\nby blast\n\n(*NOT suitable for rewriting*)\nlemma vimage_eq_UN: \"f -``B = (\\<Union>y\\<in>B. f-``{y})\"\nby blast\n\nlemma function_vimage_Int:\n     \"function(f) \\<Longrightarrow> f-``(A \\<inter> B) = (f-``A)  \\<inter>  (f-``B)\"\nby (unfold function_def, blast)\n\nlemma function_vimage_Diff: \"function(f) \\<Longrightarrow> f-``(A-B) = (f-``A) - (f-``B)\"\nby (unfold function_def, blast)\n\nlemma function_image_vimage: \"function(f) \\<Longrightarrow> f `` (f-`` A) \\<subseteq> A\"\nby (unfold function_def, blast)\n\nlemma vimage_Int_square_subset: \"(r \\<inter> A*A)-``B \\<subseteq> (r-``B) \\<inter> A\"\nby blast\n\nlemma vimage_Int_square: \"B\\<subseteq>A \\<Longrightarrow> (r \\<inter> A*A)-``B = (r-``B) \\<inter> A\"\nby blast\n\n\n\n(*Invese image laws for special relations*)\nlemma vimage_0_left [simp]: \"0-``A = 0\"\nby blast\n\nlemma vimage_Un_left: \"(r \\<union> s)-``A = (r-``A) \\<union> (s-``A)\"\nby blast\n\nlemma vimage_Int_subset_left: \"(r \\<inter> s)-``A \\<subseteq> (r-``A) \\<inter> (s-``A)\"\nby blast\n\n\n(** Converse **)\n\nlemma converse_Un [simp]: \"converse(A \\<union> B) = converse(A) \\<union> converse(B)\"\nby blast\n\nlemma converse_Int [simp]: \"converse(A \\<inter> B) = converse(A) \\<inter> converse(B)\"\nby blast\n\nlemma converse_Diff [simp]: \"converse(A - B) = converse(A) - converse(B)\"\nby blast\n\nlemma converse_UN [simp]: \"converse(\\<Union>x\\<in>A. B(x)) = (\\<Union>x\\<in>A. converse(B(x)))\"\nby blast\n\n(*Unfolding Inter avoids using excluded middle on A=0*)\nlemma converse_INT [simp]:\n     \"converse(\\<Inter>x\\<in>A. B(x)) = (\\<Inter>x\\<in>A. converse(B(x)))\"\napply (unfold Inter_def, blast)\ndone\n\n\nsubsection\\<open>Powerset Operator\\<close>\n\nlemma Pow_0 [simp]: \"Pow(0) = {0}\"\nby blast\n\nlemma Pow_insert: \"Pow (cons(a,A)) = Pow(A) \\<union> {cons(a,X) . X: Pow(A)}\"\napply (rule equalityI, safe)\napply (erule swap)\napply (rule_tac a = \"x-{a}\" in RepFun_eqI, auto)\ndone\n\nlemma Un_Pow_subset: \"Pow(A) \\<union> Pow(B) \\<subseteq> Pow(A \\<union> B)\"\nby blast\n\nlemma UN_Pow_subset: \"(\\<Union>x\\<in>A. Pow(B(x))) \\<subseteq> Pow(\\<Union>x\\<in>A. B(x))\"\nby blast\n\nlemma subset_Pow_Union: \"A \\<subseteq> Pow(\\<Union>(A))\"\nby blast\n\nlemma Union_Pow_eq [simp]: \"\\<Union>(Pow(A)) = A\"\nby blast\n\nlemma Union_Pow_iff: \"\\<Union>(A) \\<in> Pow(B) \\<longleftrightarrow> A \\<in> Pow(Pow(B))\"\nby blast\n\nlemma Pow_Int_eq [simp]: \"Pow(A \\<inter> B) = Pow(A) \\<inter> Pow(B)\"\nby blast\n\nlemma Pow_INT_eq: \"A\\<noteq>0 \\<Longrightarrow> Pow(\\<Inter>x\\<in>A. B(x)) = (\\<Inter>x\\<in>A. Pow(B(x)))\"\nby (blast elim!: not_emptyE)\n\n\nsubsection\\<open>RepFun\\<close>\n\nlemma RepFun_subset: \"\\<lbrakk>\\<And>x. x\\<in>A \\<Longrightarrow> f(x) \\<in> B\\<rbrakk> \\<Longrightarrow> {f(x). x\\<in>A} \\<subseteq> B\"\nby blast\n\nlemma RepFun_eq_0_iff [simp]: \"{f(x).x\\<in>A}=0 \\<longleftrightarrow> A=0\"\nby blast\n\nlemma RepFun_constant [simp]: \"{c. x\\<in>A} = (if A=0 then 0 else {c})\"\nby force\n\n\nsubsection\\<open>Collect\\<close>\n\nlemma Collect_subset: \"Collect(A,P) \\<subseteq> A\"\nby blast\n\nlemma Collect_Un: \"Collect(A \\<union> B, P) = Collect(A,P) \\<union> Collect(B,P)\"\nby blast\n\nlemma Collect_Int: \"Collect(A \\<inter> B, P) = Collect(A,P) \\<inter> Collect(B,P)\"\nby blast\n\nlemma Collect_Diff: \"Collect(A - B, P) = Collect(A,P) - Collect(B,P)\"\nby blast\n\nlemma Collect_cons: \"{x\\<in>cons(a,B). P(x)} =\n      (if P(a) then cons(a, {x\\<in>B. P(x)}) else {x\\<in>B. P(x)})\"\nby (simp, blast)\n\nlemma Int_Collect_self_eq: \"A \\<inter> Collect(A,P) = Collect(A,P)\"\nby blast\n\nlemma Collect_Collect_eq [simp]:\n     \"Collect(Collect(A,P), Q) = Collect(A, \\<lambda>x. P(x) \\<and> Q(x))\"\nby blast\n\nlemma Collect_Int_Collect_eq:\n     \"Collect(A,P) \\<inter> Collect(A,Q) = Collect(A, \\<lambda>x. P(x) \\<and> Q(x))\"\nby blast\n\nlemma Collect_Union_eq [simp]:\n     \"Collect(\\<Union>x\\<in>A. B(x), P) = (\\<Union>x\\<in>A. Collect(B(x), P))\"\nby blast\n\nlemma Collect_Int_left: \"{x\\<in>A. P(x)} \\<inter> B = {x \\<in> A \\<inter> B. P(x)}\"\nby blast\n\nlemma Collect_Int_right: \"A \\<inter> {x\\<in>B. P(x)} = {x \\<in> A \\<inter> B. P(x)}\"\nby blast\n\nlemma Collect_disj_eq: \"{x\\<in>A. P(x) | Q(x)} = Collect(A, P) \\<union> Collect(A, Q)\"\nby blast\n\nlemma Collect_conj_eq: \"{x\\<in>A. P(x) \\<and> Q(x)} = Collect(A, P) \\<inter> Collect(A, Q)\"\nby blast\n\nlemmas subset_SIs = subset_refl cons_subsetI subset_consI\n                    Union_least UN_least Un_least\n                    Inter_greatest Int_greatest RepFun_subset\n                    Un_upper1 Un_upper2 Int_lower1 Int_lower2\n\nML \\<open>\nval subset_cs =\n  claset_of (\\<^context>\n    delrules [@{thm subsetI}, @{thm subsetCE}]\n    addSIs @{thms subset_SIs}\n    addIs  [@{thm Union_upper}, @{thm Inter_lower}]\n    addSEs [@{thm cons_subsetE}]);\n\nval ZF_cs = claset_of (\\<^context> delrules [@{thm equalityI}]);\n\\<close>\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/ZF/equalities.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199633332893, "lm_q2_score": 0.8418256532040708, "lm_q1q2_score": 0.705129972769816}}
{"text": "(*\n  File:     Ramanujan_Sums.thy\n  Authors:  Rodrigo Raya, EPFL; Manuel Eberl, TUM\n\n  Ramanujan sums and generalised Ramanujan sums\n*)\nsection \\<open>Ramanujan sums\\<close>\ntheory Ramanujan_Sums\nimports\n  Dirichlet_Series.Moebius_Mu\n  Gauss_Sums_Auxiliary\n  Finite_Fourier_Series\nbegin\n\nsubsection \\<open>Basic sums\\<close>\n\ndefinition ramanujan_sum :: \"nat \\<Rightarrow> nat \\<Rightarrow> complex\"\n  where \"ramanujan_sum k n = (\\<Sum>m | m \\<in> {1..k} \\<and> coprime m k. unity_root k (m*n))\"\n\nnotation ramanujan_sum (\"c\")\n\nlemma ramanujan_sum_0_n [simp]: \"c 0 n = 0\"\n  unfolding ramanujan_sum_def by simp\n\nlemma sum_coprime_conv_dirichlet_prod_moebius_mu:\n  fixes F S :: \"nat \\<Rightarrow> complex\" and f :: \"nat \\<Rightarrow> nat \\<Rightarrow> complex\"\n  defines \"F \\<equiv> (\\<lambda>n. (\\<Sum>k \\<in> {1..n}. f k n))\"\n  defines \"S \\<equiv> (\\<lambda>n. (\\<Sum>k | k \\<in> {1..n} \\<and> coprime k n . f k n))\"\n  assumes \"\\<And>a b d. d dvd a \\<Longrightarrow> d dvd b \\<Longrightarrow> f (a div d) (b div d) = f a b\" \n  shows \"S n = dirichlet_prod moebius_mu F n\"\nproof (cases \"n = 0\")\n  case True\n  then show ?thesis \n    using assms(2) unfolding dirichlet_prod_def by fastforce\nnext\n  case False\n  have \"S(n) = (\\<Sum>k | k \\<in> {1..n} \\<and> coprime k n . (f k n))\"\n    using assms by blast\n  also have \"\\<dots> = (\\<Sum>k \\<in> {1..n}. (f k n)* dirichlet_prod_neutral (gcd k n))\"\n    using dirichlet_prod_neutral_intro by blast\n  also have \"\\<dots> = (\\<Sum>k \\<in> {1..n}. (f k n)* (\\<Sum>d | d dvd (gcd k n). moebius_mu d))\"\n  proof -\n    {\n      fix k\n      have \"dirichlet_prod_neutral (gcd k n) = (if gcd k n = 1 then 1 else 0)\"\n        using dirichlet_prod_neutral_def[of \"gcd k n\"] by blast\n      also have \"\\<dots> = (\\<Sum>d | d dvd gcd k n. moebius_mu d)\"\n        using sum_moebius_mu_divisors'[of \"gcd k n\"] by auto\n      finally have \"dirichlet_prod_neutral (gcd k n) = (\\<Sum>d | d dvd gcd k n. moebius_mu d)\" \n        by auto\n    } note summand = this\n    then show ?thesis by (simp add: summand)\n  qed\n  also have \"\\<dots> = (\\<Sum>k = 1..n. (\\<Sum>d | d dvd gcd k n. (f k n) *  moebius_mu d))\"\n    by (simp add: sum_distrib_left)\n  also have \"\\<dots> = (\\<Sum>k = 1..n. (\\<Sum>d | d dvd gcd n k. (f k n) *  moebius_mu d))\"\n    using gcd.commute[of _ n] by simp\n  also have \"\\<dots> = (\\<Sum>d | d dvd n. \\<Sum>k | k \\<in> {1..n} \\<and> d dvd k. (f k n) * moebius_mu d)\"\n    using sum.swap_restrict[of \"{1..n}\" \"{d. d dvd n}\"\n             \"\\<lambda>k d. (f k n)*moebius_mu d\" \"\\<lambda>k d. d dvd k\"] False by auto\n  also have \"\\<dots> = (\\<Sum>d | d dvd n. moebius_mu d * (\\<Sum>k | k \\<in> {1..n} \\<and> d dvd k. (f k n)))\" \n    by (simp add: sum_distrib_left mult.commute)\n  also have \"\\<dots> = (\\<Sum>d | d dvd n. moebius_mu d * (\\<Sum>q \\<in> {1..n div d}. (f q (n div d))))\"\n  proof - \n    have st: \"\n      (\\<Sum>k | k \\<in> {1..n} \\<and> d dvd k. (f k n)) =\n        (\\<Sum>q \\<in> {1..n div d}. (f q (n div d)))\" \n      if \"d dvd n\" \"d > 0\" for d :: nat\n      by (rule sum.reindex_bij_witness[of _ \"\\<lambda>k. k * d\" \"\\<lambda>k. k div d\"])\n         (use assms(3) that in \\<open>fastforce simp: div_le_mono\\<close>)+\n    show ?thesis \n      by (intro sum.cong) (use st False in fastforce)+\n  qed\n  also have \"\\<dots> = (\\<Sum>d | d dvd n. moebius_mu d * F(n div d))\"\n  proof - \n    have \"F (n div d) = (\\<Sum>q \\<in> {1..n div d}. (f q (n div d)))\" \n      if \"d dvd n\" for d\n        by (simp add: F_def real_of_nat_div that)\n     then show ?thesis by auto\n  qed\n  also have \"\\<dots> = dirichlet_prod moebius_mu F n\"\n    by (simp add: dirichlet_prod_def)\n  finally show ?thesis by simp\nqed\n\nlemma dirichlet_prod_neutral_sum:\n  \"dirichlet_prod_neutral n = (\\<Sum>k = 1..n. unity_root n k)\" for n :: nat\nproof (cases \"n = 0\")\n  case True then show ?thesis unfolding dirichlet_prod_neutral_def by simp\nnext\n  case False\n  have 1: \"unity_root n 0 = 1\" by simp\n  have 2: \"unity_root n n = 1\" \n    using unity_periodic_arithmetic[of n] add.left_neutral\n  proof -\n    have \"1 = unity_root n (int 0)\"\n       using 1 by auto\n    also have \"unity_root n (int 0) = unity_root n (int (0 + n))\"\n      using unity_periodic_arithmetic[of n] periodic_arithmetic_def by algebra\n    also have \"\\<dots> = unity_root n (int n)\" by simp\n    finally show ?thesis by auto \n  qed\n  have \"(\\<Sum>k = 1..n. unity_root n k) = (\\<Sum>k = 0..n. unity_root n k) - 1\"\n    by (simp add: sum.atLeast_Suc_atMost sum.atLeast0_atMost_Suc_shift 1)\n  also have \"\\<dots> = ((\\<Sum>k = 0..n-1. unity_root n k)+1) - 1\"\n    using sum.atLeast0_atMost_Suc[of \"(\\<lambda>k. unity_root n k)\" \"n-1\"] False \n    by (simp add: 2)\n  also have \"\\<dots> = (\\<Sum>k = 0..n-1. unity_root n k)\"\n    by simp\n  also have \"\\<dots> = unity_root_sum n 1\"\n    unfolding unity_root_sum_def using \\<open>n \\<noteq> 0\\<close> by (intro sum.cong) auto\n  also have \"\\<dots> = dirichlet_prod_neutral n\"\n    using unity_root_sum[of n 1] False\n    by (cases \"n = 1\",auto simp add: False dirichlet_prod_neutral_def)\n  finally have 3: \"dirichlet_prod_neutral n = (\\<Sum>k = 1..n. unity_root n k)\" by auto\n  then show ?thesis by blast \nqed\n\nlemma moebius_coprime_sum:\n  \"moebius_mu n = (\\<Sum>k | k \\<in> {1..n} \\<and> coprime k n . unity_root n (int k))\"\nproof -\n  let ?f = \"(\\<lambda>k n. unity_root n k)\"\n  from div_dvd_div have \" \n      d dvd a \\<Longrightarrow> d dvd b \\<Longrightarrow>\n      unity_root (a div d) (b div d) = \n      unity_root a b\" for a b d :: nat\n    using unity_root_def real_of_nat_div by fastforce\n  then have \"(\\<Sum>k | k \\<in> {1..n} \\<and> coprime k n. ?f k n) =\n        dirichlet_prod moebius_mu (\\<lambda>n. \\<Sum>k = 1..n. ?f k n) n\"\n    using sum_coprime_conv_dirichlet_prod_moebius_mu[of ?f n] by blast\n  also have \"\\<dots> = dirichlet_prod moebius_mu dirichlet_prod_neutral n\"\n    by (simp add: dirichlet_prod_neutral_sum)\n  also have \"\\<dots> = moebius_mu n\" \n    by (cases \"n = 0\") (simp_all add: dirichlet_prod_neutral_right_neutral)\n  finally have \"moebius_mu n = (\\<Sum>k | k \\<in> {1..n} \\<and> coprime k n. ?f k n)\"\n    by argo\n  then show ?thesis by blast\nqed\n\ncorollary ramanujan_sum_1_right [simp]: \"c k (Suc 0) = moebius_mu k\"\n  unfolding ramanujan_sum_def using moebius_coprime_sum[of k] by simp\n\nlemma ramanujan_sum_dvd_eq_totient:\n  assumes \"k dvd n\"\n    shows \"c k n = totient k\"\n  unfolding ramanujan_sum_def\nproof - \n  have \"unity_root k (m*n) = 1\" for m\n    using assms by (cases \"k = 0\") (auto simp: unity_root_eq_1_iff_int)\n  then have \"(\\<Sum>m | m \\<in> {1..k} \\<and> coprime m k. unity_root k (m * n)) = \n               (\\<Sum>m | m \\<in> {1..k} \\<and> coprime m k. 1)\" by simp\n  also have \"\\<dots> = card {m. m \\<in> {1..k} \\<and> coprime m k}\" by simp\n  also have \"\\<dots> = totient k\"\n   unfolding totient_def totatives_def \n  proof -\n    have \"{1..k} = {0<..k}\" by auto\n    then show \" of_nat (card {m \\<in> {1..k}. coprime m k}) =\n              of_nat (card {ka \\<in> {0<..k}. coprime ka k})\" by auto\n  qed\n  finally show \"(\\<Sum>m | m \\<in> {1..k} \\<and> coprime m k. unity_root k (m * n)) = totient k\" \n    by auto\nqed\n\nsubsection \\<open>Generalised sums\\<close>\n\ndefinition gen_ramanujan_sum :: \"(nat \\<Rightarrow> complex) \\<Rightarrow> (nat \\<Rightarrow> complex) \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> complex\" where\n  \"gen_ramanujan_sum f g = (\\<lambda>k n. \\<Sum>d | d dvd gcd n k. f d * g (k div d))\"\n\nnotation gen_ramanujan_sum (\"s\")\n\nlemma gen_ramanujan_sum_k_1: \"s f g k 1 = f 1 * g k\"\n  unfolding gen_ramanujan_sum_def by auto\n\nlemma gen_ramanujan_sum_1_n: \"s f g 1 n = f 1 * g 1\"\n  unfolding gen_ramanujan_sum_def by simp\n\n\n\ntext \\<open>Theorem 8.5\\<close>\ntheorem gen_ramanujan_sum_fourier_expansion:\n  fixes f g :: \"nat \\<Rightarrow> complex\" and a :: \"nat \\<Rightarrow> nat \\<Rightarrow> complex\"\n  assumes \"k > 0\" \n  defines \"a \\<equiv> (\\<lambda>k m. (1/k) * (\\<Sum>d| d dvd (gcd m k). g d * f (k div d) * d))\"\n  shows \"s f g k n = (\\<Sum>m\\<le>k-1. a k m * unity_root k (m*n))\"\nproof -\n  let ?g = \"(\\<lambda>x. 1 / of_nat k * (\\<Sum>m<k. s f g k m * unity_root k (-x*m)))\"\n  {fix m :: nat\n  let ?h = \"\\<lambda>n d. f d * g (k div d) * unity_root k (- m * int n)\"\n  have \"(\\<Sum>l<k. s f g k l * unity_root k (-m*l)) =\n               (\\<Sum>l \\<in> {0..k-1}. s f g k l * unity_root k (-m*l))\"\n    using \\<open>k > 0\\<close> by (intro sum.cong) auto\n  also have \"\\<dots> = (\\<Sum>l \\<in> {1..k}. s f g k l * unity_root k (-m*l))\"\n  proof -\n    have \"periodic_arithmetic (\\<lambda>l. unity_root k (-m*l)) k\"\n      using unity_periodic_arithmetic_mult by blast\n    then have \"periodic_arithmetic (\\<lambda>l. s f g k l * unity_root k (-m*l)) k\"\n      using gen_ramanujan_sum_periodic mult_periodic_arithmetic by blast\n    from this periodic_arithmetic_sum_periodic_arithmetic_shift[of _ k 1  ]\n    have \"sum (\\<lambda>l. s f g k l * unity_root k (-m*l)) {0..k - 1} = \n          sum (\\<lambda>l. s f g k l * unity_root k (-m*l)) {1..k}\"\n      using assms(1) zero_less_one by simp\n    then show ?thesis by argo\n  qed\n  also have \"\\<dots> = (\\<Sum>n\\<in>{1..k}. (\\<Sum>d | d dvd (gcd n k). f(d) * g(k div d)) * unity_root k (-m*n))\"\n    by (simp add: gen_ramanujan_sum_def)\n  also have \"\\<dots> = (\\<Sum>n\\<in>{1..k}. (\\<Sum>d | d dvd (gcd n k). f(d) * g(k div d) * unity_root k (-m*n)))\"\n    by (simp add: sum_distrib_right)\n  also have \"\\<dots> = (\\<Sum>d | d dvd k. \\<Sum>n | n \\<in> {1..k} \\<and> d dvd n. ?h n d)\"\n  proof -\n    have \"(\\<Sum>n = 1..k. \\<Sum>d | d dvd gcd n k. ?h n d) =\n          (\\<Sum>n = 1..k. \\<Sum>d | d dvd k \\<and> d dvd n . ?h n d)\"\n      using gcd.commute[of _ k] by simp\n    also have \"\\<dots> = (\\<Sum>d | d dvd k. \\<Sum>n | n \\<in> {1..k} \\<and> d dvd n. ?h n d)\"\n      using sum.swap_restrict[of \"{1..k}\" \"{d. d dvd k}\"\n                            _ \"\\<lambda>n d. d dvd n\"] assms by fastforce\n    finally have \"\n      (\\<Sum>n = 1..k. \\<Sum>d | d dvd gcd n k. ?h n d) = \n      (\\<Sum>d | d dvd k. \\<Sum>n | n \\<in> {1..k} \\<and> d dvd n. ?h n d)\" by blast\n    then show ?thesis by simp\n  qed\n  also have \"\\<dots> = (\\<Sum>d | d dvd k. f(d)*g(k div d)*\n             (\\<Sum>n | n \\<in> {1..k} \\<and> d dvd n. unity_root k (- m * int n)))\"\n    by (simp add: sum_distrib_left)\n  also have \"\\<dots> = (\\<Sum>d | d dvd k. f(d)*g(k div d)*\n             (\\<Sum>e \\<in> {1..k div d}. unity_root k (- m * (e*d))))\"\n    using assms(1) sum_div_reduce div_greater_zero_iff dvd_div_gt0 by auto\n  also have \"\\<dots> = (\\<Sum>d | d dvd k. f(d)*g(k div d)*\n             (\\<Sum>e \\<in> {1..k div d}. unity_root (k div d) (- m * e)))\"\n  proof -\n    {\n      fix d e\n      assume \"d dvd k\"\n      hence \"2 * pi * real_of_int (- int m * int (e * d)) / real k =\n              2 * pi * real_of_int (- int m * int e) / real (k div d)\" by auto\n      hence \"unity_root k (- m * (e * d)) = unity_root (k div d) (- m * e)\"\n        unfolding unity_root_def by simp\n    }\n    then show ?thesis by simp\n  qed\n  also have \"\\<dots> = dirichlet_prod (\\<lambda>d. f(d)*g(k div d))\n                    (\\<lambda>d. (\\<Sum>e \\<in> {1..d}. unity_root d (- m * e))) k\"\n    unfolding dirichlet_prod_def by blast\n  also have \"\\<dots> = dirichlet_prod (\\<lambda>d. (\\<Sum>e \\<in> {1..d}. unity_root d (- m * e)))\n                    (\\<lambda>d. f(d)*g(k div d)) k\"\n    using dirichlet_prod_commutes[of \n            \"(\\<lambda>d. f(d)*g(k div d))\"\n            \"(\\<lambda>d. (\\<Sum>e \\<in> {1..d}. unity_root d (- m * e)))\"] by argo\n  also have \"\\<dots> = (\\<Sum>d | d dvd k.\n             (\\<Sum>e \\<in> {1..(d::nat)}. unity_root d (- m * e))*(f(k div d)*g(k div (k div d))))\"  \n    unfolding dirichlet_prod_def by blast \n  also have \"\\<dots> = (\\<Sum>d | d dvd k. (\\<Sum>e \\<in> {1..(d::nat)}.\n                      unity_root d (- m * e))*(f(k div d)*g(d)))\"  \n  proof -\n    {\n      fix d :: nat\n      assume \"d dvd k\"\n      then have \"k div (k div d) = d\"\n        by (simp add: assms(1) div_div_eq_right)\n    }\n    then show ?thesis by simp\n  qed\n  also have \"\\<dots> = (\\<Sum>(d::nat) | d dvd k \\<and> d dvd m. d*(f(k div d)*g(d)))\"  \n  proof -\n    {\n      fix d\n      assume \"d dvd k\"\n      with assms have \"d > 0\" by (intro Nat.gr0I) auto\n      have \"periodic_arithmetic (\\<lambda>x. unity_root d (- m * int x)) d\"\n        using unity_periodic_arithmetic_mult by blast\n      then have \"(\\<Sum>e \\<in> {1..d}. unity_root d (- m * e)) = \n            (\\<Sum>e \\<in> {0..d-1}. unity_root d (- m * e))\"\n        using periodic_arithmetic_sum_periodic_arithmetic_shift[of \"\\<lambda>e. unity_root d (- m * e)\"  d 1] assms \\<open>d dvd k\\<close>\n        by fastforce\n      also have \"\\<dots> = unity_root_sum d (-m)\" \n        unfolding unity_root_sum_def using \\<open>d > 0\\<close> by (intro sum.cong) auto\n      finally have \n        \"(\\<Sum>e \\<in> {1..d}. unity_root d (- m * e)) = unity_root_sum d (-m)\"\n        by argo\n    }\n    then have \"\n      (\\<Sum>d | d dvd k. (\\<Sum>e = 1..d. unity_root d (- m * int e)) * (f (k div d) * g d)) = \n      (\\<Sum>d | d dvd k. unity_root_sum d (-m) * (f (k div d) * g d))\" by simp\n    also have \"\\<dots> = (\\<Sum>d | d dvd k \\<and> d dvd m. unity_root_sum d (-m) * (f (k div d) * g d))\"\n    proof (intro sum.mono_neutral_right,simp add: \\<open>k > 0\\<close>,blast,standard)\n      fix i\n      assume as: \"i \\<in> {d. d dvd k} - {d. d dvd k \\<and> d dvd m}\"\n      then have \"i \\<ge> 1\" using \\<open>k > 0\\<close> by auto\n      have \"k \\<ge> 1\" using \\<open>k > 0\\<close> by auto  \n      have \"\\<not> i dvd (-m)\" using as by auto\n      thus \"unity_root_sum i (- int m) * (f (k div i) * g i) = 0\" \n        using \\<open>i \\<ge> 1\\<close> by (subst unity_root_sum(2)) auto\n    qed   \n    also have \"\\<dots> = (\\<Sum>d | d dvd k \\<and> d dvd m. d * (f (k div d) * g d))\"\n    proof - \n      {fix d :: nat\n        assume 1: \"d dvd m\" \n        assume 2: \"d dvd k\"\n        then have \"unity_root_sum d (-m) = d\"\n          using unity_root_sum[of d \"(-m)\"] assms(1) 1 2\n          by auto}\n      then show ?thesis by auto\n    qed\n    finally show ?thesis by argo\n  qed\n  also have \"\\<dots> = (\\<Sum>d | d dvd gcd m k. of_nat d * (f (k div d) * g d))\" \n    by (simp add: gcd.commute)\n  also have \"\\<dots> = (\\<Sum>d | d dvd gcd m k. g d * f (k div d) * d)\" \n    by (simp add: algebra_simps sum_distrib_left)\n  also have \"1 / k * \\<dots> = a k m\" using a_def by auto\n  finally have \"?g m = a k m\" by simp}\n  note a_eq_g = this\n  {\n    fix m\n    from fourier_expansion_periodic_arithmetic(2)[of k \"s f g k\" ] gen_ramanujan_sum_periodic assms(1) \n    have \"s f g k m = (\\<Sum>n<k. ?g n * unity_root k (int m * n))\"\n      by blast\n    also have \"\\<dots> = (\\<Sum>n<k. a k n * unity_root k (int m * n))\"\n      using a_eq_g by simp\n    also have \"\\<dots> = (\\<Sum>n\\<le>k-1. a k n * unity_root k (int m * n))\"\n      using \\<open>k > 0\\<close> by (intro sum.cong) auto\n    finally have \"s f g k m =\n      (\\<Sum>n\\<le>k - 1. a k n * unity_root k (int n * int m))\"\n      by (simp add: algebra_simps)\n  }\n  then show ?thesis by blast\nqed\n\ntext \\<open>Theorem 8.6\\<close>\ntheorem ramanujan_sum_dirichlet_form:\n  fixes k n :: nat\n  assumes \"k > 0\"\n  shows \"c k n = (\\<Sum>d | d dvd gcd n k. d * moebius_mu (k div d))\"\nproof -\n  define a :: \"nat \\<Rightarrow> nat \\<Rightarrow> complex\" \n    where \"a  =  (\\<lambda>k m.\n   1 / of_nat k * (\\<Sum>d | d dvd gcd m k. moebius_mu d * of_nat (k div d) * of_nat d))\"\n\n  {fix m\n  have \"a k m = (if gcd m k = 1 then 1 else 0)\"\n  proof -\n   have \"a k m = 1 / of_nat k * (\\<Sum>d | d dvd gcd m k. moebius_mu d * of_nat (k div d) * of_nat d)\"\n      unfolding a_def by blast\n   also have 2: \"\\<dots> = 1 / of_nat k * (\\<Sum>d | d dvd gcd m k. moebius_mu d * of_nat k)\"\n   proof -\n     {fix d :: nat\n     assume dvd: \"d dvd gcd m k\"\n     have \"moebius_mu d * of_nat (k div d) * of_nat d = moebius_mu d * of_nat k\"\n     proof -\n       have \"(k div d) * d = k\" using dvd by auto\n       then show \"moebius_mu d * of_nat (k div d) * of_nat d = moebius_mu d * of_nat k\"  \n         by (simp add: algebra_simps,subst of_nat_mult[symmetric],simp)\n     qed} note eq = this\n     show ?thesis using sum.cong by (simp add: eq)\n   qed\n\n   also have 3: \"\\<dots> = (\\<Sum>d | d dvd gcd m k. moebius_mu d)\"\n     by (simp add: sum_distrib_left assms) \n   also have 4: \"\\<dots> =  (if gcd m k = 1 then 1 else 0)\"\n     using sum_moebius_mu_divisors' by blast\n   finally show \"a k m  = (if gcd m k = 1 then 1 else 0)\" \n     using coprime_def by blast\n qed} note a_expr = this\n\n  let ?f = \"(\\<lambda>m. (if gcd m k = 1 then 1 else 0) *\n                 unity_root k (int m * n))\"\n  from gen_ramanujan_sum_fourier_expansion[of k id moebius_mu n] assms\n  have \"s (\\<lambda>x. of_nat (id x)) moebius_mu k n =\n  (\\<Sum>m\\<le>k - 1.\n      1 / of_nat k *\n      (\\<Sum>d | d dvd gcd m k.\n         moebius_mu d * of_nat (k div d) * of_nat d) *\n      unity_root k (int m * n))\" by simp\n  also have \"\\<dots> = (\\<Sum>m\\<le>k - 1.\n      a k m *\n      unity_root k (int m * n))\" using a_def by blast\n  also have \"\\<dots> = (\\<Sum>m\\<le>k - 1.\n      (if gcd m k = 1 then 1 else 0) *\n      unity_root k (int m * n))\" using a_expr by auto\n  also have \"\\<dots> = (\\<Sum>m \\<in> {1..k}.\n      (if gcd m k = 1 then 1 else 0) *\n      unity_root k (int m * n))\"\n  proof -    \n    have \"periodic_arithmetic (\\<lambda>m. (if gcd m k = 1 then 1 else 0) *\n                 unity_root k (int m * n)) k\"\n    proof -\n      have \"periodic_arithmetic (\\<lambda>m. if gcd m k = 1 then 1 else 0) k\"\n        by (simp add: periodic_arithmetic_def)\n      moreover have \"periodic_arithmetic (\\<lambda>m. unity_root k (int m * n)) k\" \n        using unity_periodic_arithmetic_mult[of k n]\n        by (subst mult.commute,simp) \n      ultimately show \"periodic_arithmetic ?f k\"\n        using mult_periodic_arithmetic by simp\n    qed\n    then have \"sum ?f {0..k - 1} = sum ?f {1..k}\"\n      using periodic_arithmetic_sum_periodic_arithmetic_shift[of ?f k 1] by force\n    then show ?thesis by (simp add: atMost_atLeast0)    \n  qed  \n  also have \"\\<dots> = (\\<Sum>m | m \\<in> {1..k} \\<and> gcd m k = 1.\n                  (if gcd m k = 1 then 1 else 0) *     \n                  unity_root k (int m * int n))\"\n    by (intro sum.mono_neutral_right,auto)\n  also have \"\\<dots> = (\\<Sum>m | m \\<in> {1..k} \\<and> gcd m k = 1.\n                  unity_root k (int m * int n))\" by simp    \n  also have \"\\<dots> = (\\<Sum>m | m \\<in> {1..k} \\<and> coprime m k.\n                  unity_root k (int m * int n))\"\n    using coprime_iff_gcd_eq_1 by presburger\n  also have \"\\<dots> = c k n\" unfolding ramanujan_sum_def by simp\n  finally show ?thesis unfolding gen_ramanujan_sum_def by auto\nqed\n\ncorollary ramanujan_sum_conv_gen_ramanujan_sum:\n \"k > 0 \\<Longrightarrow> c k n = s id moebius_mu k n\"\n  using ramanujan_sum_dirichlet_form unfolding gen_ramanujan_sum_def by simp\n\ntext \\<open>Theorem 8.7\\<close>\ntheorem gen_ramanujan_sum_distrib:\n  fixes f g :: \"nat \\<Rightarrow> complex\"\n  assumes \"a > 0\" \"b > 0\" \"m > 0\" \"k > 0\" (* remove cond. on m,n *)\n  assumes \"coprime a k\" \"coprime b m\" \"coprime k m\"\n  assumes \"multiplicative_function f\" and \n          \"multiplicative_function g\"\n  shows \"s f g (m*k) (a*b) = s f g m a * s f g k b\"\nproof -\n  from assms(1-6) have eq: \"gcd (m*k) (a*b) = gcd a m * gcd k b\"\n   by (simp add: linear_gcd  gcd.commute mult.commute)\n  have \"s f g (m*k) (a*b) = \n        (\\<Sum>d | d dvd gcd (m*k) (a*b). f(d) * g((m*k) div d))\"\n    unfolding gen_ramanujan_sum_def by (rule sum.cong, simp add: gcd.commute,blast) \n  also have \"\\<dots> = \n     (\\<Sum>d | d dvd gcd a m * gcd k b. f(d) * g((m*k) div d))\"\n    using eq by simp\n  also have \"\\<dots> = \n     (\\<Sum>(d1,d2) | d1 dvd gcd a m \\<and>  d2 dvd gcd k b. \n          f(d1*d2) * g((m*k) div (d1*d2)))\" \n  proof -\n    have b: \"bij_betw (\\<lambda>(d1, d2). d1 * d2)\n   {(d1, d2). d1 dvd gcd a m \\<and> d2 dvd gcd k b}\n   {d. d dvd gcd a m * gcd k b}\" \n      using assms(5) reindex_product_bij by blast\n    have \"(\\<Sum>(d1, d2) | d1 dvd gcd a m \\<and> d2 dvd gcd k b.\n     f (d1 * d2) * g (m * k div (d1 * d2))) = \n      (\\<Sum>x\\<in>{(d1, d2). d1 dvd gcd a m \\<and> d2 dvd gcd k b}.\n     f (case x of (d1, d2) \\<Rightarrow> d1 * d2)*\n       g (m * k div (case x of (d1, d2) \\<Rightarrow> d1 * d2)))\"\n        by (rule sum.cong,auto)\n      also have \"\\<dots> = (\\<Sum>d | d dvd gcd a m * gcd k b. f d * g (m * k div d))\"\n        using b by (rule sum.reindex_bij_betw[of \"\\<lambda>(d1,d2). d1*d2\" ])\n      finally show ?thesis by argo     \n    qed \n  also have \"\\<dots> = (\\<Sum>d1 | d1 dvd gcd a m. \\<Sum>d2 | d2 dvd gcd k b. \n                     f (d1*d2) * g ((m*k) div (d1*d2)))\"\n      by (simp add: sum.cartesian_product) (rule sum.cong,auto) \n    also have \"\\<dots> = (\\<Sum>d1 | d1 dvd gcd a m. \\<Sum>d2 | d2 dvd gcd k b. \n                      f d1 * f d2 * g ((m*k) div (d1*d2)))\"\n      using assms(5) assms(8) multiplicative_function.mult_coprime\n      by (intro sum.cong refl) fastforce+\n    also have \"\\<dots> = (\\<Sum>d1 | d1 dvd gcd a m. \\<Sum>d2 | d2 dvd gcd k b.\n                      f d1 * f d2* g (m div d1) * g (k div d2))\"\n    proof (intro sum.cong refl, clarify, goal_cases)\n      case (1 d1 d2)\n      hence \"g (m * k div (d1 * d2)) = g (m div d1) * g (k div d2)\" \n        using assms(7,9) multipl_div\n        by (meson coprime_commute dvd_gcdD1 dvd_gcdD2)\n      thus ?case by simp\n    qed\n    also have \"\\<dots> = (\\<Sum>i\\<in>{d1. d1 dvd gcd a m}. \\<Sum>j\\<in>{d2. d2 dvd gcd k b}.\n                      f i * g (m div i) * (f j * g (k div j)))\"\n      by (rule sum.cong,blast,rule sum.cong,blast,simp)   \n    also have \"\\<dots> = (\\<Sum>d1 | d1 dvd gcd a m. f d1 * g (m div d1)) *\n                      (\\<Sum>d2 | d2 dvd gcd k b. f d2 * g (k div d2))\"\n      by (simp add: sum_product)\n    also have \"\\<dots> = s f g m a * s f g k b\"\n      unfolding gen_ramanujan_sum_def by (simp add: gcd.commute)\n    finally show ?thesis by blast\nqed\n\ncorollary gen_ramanujan_sum_distrib_right:\n fixes f g :: \"nat \\<Rightarrow> complex\"\n assumes \"a > 0\" and \"b > 0\" and \"m > 0\" (* TODO: remove cond. on m,n *)\n assumes \"coprime b m\"\n assumes \"multiplicative_function f\" and \n         \"multiplicative_function g\"\n shows \"s f g m (a * b) = s f g m a\"\nproof -\n  have \"s f g m (a*b) = s f g m a * s f g 1 b\"\n    using assms gen_ramanujan_sum_distrib[of a b m 1 f g] by simp\n  also have \"\\<dots> = s f g m a * f 1 * g 1\"\n    using gen_ramanujan_sum_1_n by auto\n  also have \"\\<dots> = s f g m a\"\n    using  assms(5-6) \n    by (simp add: multiplicative_function_def)\n  finally show \"s f g m (a*b) = s f g m a\" by blast\nqed\n\ncorollary gen_ramanujan_sum_distrib_left:\n fixes f g :: \"nat \\<Rightarrow> complex\"\n assumes \"a > 0\" and \"k > 0\" and \"m > 0\" (* TODO: remove cond. on m,n *)\n assumes \"coprime a k\" and \"coprime k m\"\n assumes \"multiplicative_function f\" and \n         \"multiplicative_function g\"\n shows \"s f g (m*k) a = s f g m a * g k\"\nproof -\n  have \"s f g (m*k) a = s f g m a * s f g k 1\"\n    using assms gen_ramanujan_sum_distrib[of a 1 m k f g] by simp\n  also have \"\\<dots> = s f g m a * f(1) * g(k)\" \n    using gen_ramanujan_sum_k_1 by auto\n  also have \"\\<dots> = s f g m a *  g k\" \n    using assms(6)\n    by (simp add: multiplicative_function_def)\n  finally show ?thesis by blast\nqed\n\ncorollary ramanujan_sum_distrib:\n assumes \"a > 0\" and \"k > 0\" and \"m > 0\" and \"b > 0\" (* TODO: remove cond. on m,n *)\n assumes \"coprime a k\" \"coprime b m\" \"coprime m k\"\n shows \"c (m*k) (a*b) = c m a * c k b\"\nproof -\n  have \"c (m*k) (a*b) = s id moebius_mu (m*k) (a*b)\" \n    using ramanujan_sum_conv_gen_ramanujan_sum assms(2,3) by simp\n  \n  also have \"\\<dots> = (s id moebius_mu m a) * (s id moebius_mu k b)\"\n    using gen_ramanujan_sum_distrib[of a b m k id moebius_mu]\n          assms mult_id mult_moebius mult_of_nat         \n          coprime_commute[of m k] by auto\n  also have \"\\<dots> = c m a * c k b\" using ramanujan_sum_conv_gen_ramanujan_sum assms by simp\n  finally show ?thesis by simp\nqed\n\ncorollary ramanujan_sum_distrib_right:\n assumes \"a > 0\" and \"k > 0\" and \"m > 0\" and \"b > 0\" (* remove cond. on m,n *)\n assumes \"coprime b m\" \n shows \"c m (a*b) = c m a\"\n  using assms ramanujan_sum_conv_gen_ramanujan_sum mult_id mult_moebius \n        mult_of_nat gen_ramanujan_sum_distrib_right by auto\n\ncorollary ramanujan_sum_distrib_left:\n assumes \"a > 0\" \"k > 0\" \"m > 0\"  (* remove cond. on m,n *)\n assumes \"coprime a k\" \"coprime m k\" \n shows \"c (m*k) a = c m a * moebius_mu k\"\n  using assms\n  by (simp add: ramanujan_sum_conv_gen_ramanujan_sum, subst gen_ramanujan_sum_distrib_left)\n     (auto simp: coprime_commute mult_of_nat mult_moebius)\n\nlemma dirichlet_prod_completely_multiplicative_left:\n  fixes f h :: \"nat \\<Rightarrow> complex\" and k :: nat\n  defines \"g \\<equiv> (\\<lambda>k. moebius_mu k * h k)\" \n  defines \"F \\<equiv> dirichlet_prod f g\"\n  assumes \"k > 0\"\n  assumes \"completely_multiplicative_function f\" \n          \"multiplicative_function h\" \n  assumes \"\\<And>p. prime p \\<Longrightarrow> f(p) \\<noteq> 0 \\<and> f(p) \\<noteq> h(p)\" \n  shows \"F k = f k * (\\<Prod>p\\<in>prime_factors k. 1 - h p / f p)\"\nproof -\n  have 1: \"multiplicative_function (\\<lambda>p. h(p) div f(p))\"\n    using multiplicative_function_divide\n          comp_to_mult assms(4,5) by blast\n  have \"F k = dirichlet_prod g f k\"\n    unfolding F_def using dirichlet_prod_commutes[of f g] by auto\n  also have \"\\<dots> = (\\<Sum>d | d dvd k. moebius_mu d * h d * f(k div d))\"\n    unfolding g_def dirichlet_prod_def by blast\n  also have \"\\<dots> = (\\<Sum>d | d dvd k. moebius_mu d * h d * (f(k) div f(d)))\"\n    using multipl_div_mono[of f _ k] assms(4,6) \n    by (intro sum.cong,auto,force)  \n  also have \"\\<dots> = f k * (\\<Sum>d | d dvd k. moebius_mu d * (h d div f(d)))\"\n    by (simp add: sum_distrib_left algebra_simps)\n  also have \"\\<dots> = f k * (\\<Prod>p\\<in>prime_factors k. 1 - (h p div f p))\"\n    using sum_divisors_moebius_mu_times_multiplicative[of \"\\<lambda>p. h p div f p\" k] 1\n          assms(3) by simp\n  finally show F_eq: \"F k = f k * (\\<Prod>p\\<in>prime_factors k. 1 - (h p div f p))\"\n    by blast\nqed\n\ntext \\<open>Theorem 8.8\\<close>\ntheorem gen_ramanujan_sum_dirichlet_expr:\n  fixes f h :: \"nat \\<Rightarrow> complex\" and n k :: nat\n  defines \"g \\<equiv> (\\<lambda>k. moebius_mu k * h k)\" \n  defines \"F \\<equiv> dirichlet_prod f g\"\n  defines \"N \\<equiv> k div gcd n k\" \n  assumes \"completely_multiplicative_function f\" \n          \"multiplicative_function h\" \n  assumes \"\\<And>p. prime p \\<Longrightarrow> f(p) \\<noteq> 0 \\<and> f(p) \\<noteq> h(p)\" \n  assumes \"k > 0\" \"n > 0\"  \n  shows \"s f g k n = (F(k)*g(N)) div (F(N))\"\nproof -\n  define a where \"a \\<equiv> gcd n k\" \n  have 2: \"k = a*N\" unfolding a_def N_def by auto\n  have 3: \"a > 0\" using a_def assms(7,8) by simp\n  have Ngr0: \"N > 0\" using assms(7,8) 2 N_def by fastforce\n  have f_k_not_z: \"f k \\<noteq> 0\" \n    using completely_multiplicative_nonzero assms(4,6,7) by blast\n  have f_N_not_z: \"f N \\<noteq> 0\" \n      using completely_multiplicative_nonzero assms(4,6) Ngr0 by blast\n  have bij: \"bij_betw (\\<lambda>d. a div d) {d. d dvd a} {d. d dvd a}\"\n    unfolding bij_betw_def\n  proof\n    show inj: \"inj_on (\\<lambda>d. a div d) {d. d dvd a}\"\n      using inj_on_def \"3\" dvd_div_eq_2 by blast\n    show surj: \"(\\<lambda>d. a div d) ` {d. d dvd a} = {d. d dvd a}\"\n      unfolding image_def \n    proof \n      show \" {y. \\<exists>x\\<in>{d. d dvd a}. y = a div x} \\<subseteq> {d. d dvd a}\"\n        by auto\n      show \"{d. d dvd a} \\<subseteq> {y. \\<exists>x\\<in>{d. d dvd a}. y = a div x}\"\n      proof \n        fix d\n        assume a: \"d \\<in> {d. d dvd a}\"\n        from a have 1: \"(a div d) \\<in> {d. d dvd a}\" by auto\n        from a have 2: \"d = a div (a div d)\" using 3 by auto\n        from 1 2 show \"d \\<in> {y. \\<exists>x\\<in>{d. d dvd a}. y = a div x} \" by blast        \n      qed\n    qed\n  qed\n  \n  have \"s f g k n = (\\<Sum>d | d dvd a. f(d)*moebius_mu(k div d)*h(k div d))\"\n    unfolding gen_ramanujan_sum_def g_def a_def by (simp add: mult.assoc)\n  also have \"\\<dots> = (\\<Sum>d | d dvd a. f(d) * moebius_mu(a*N div d)*h(a*N div d))\"\n    using 2 by blast\n  also have \"\\<dots> = (\\<Sum>d | d dvd a. f(a div d) * moebius_mu(N*d)*h(N*d))\"\n    (is \"?a = ?b\")\n  proof -\n    define f_aux where \"f_aux \\<equiv> (\\<lambda>d. f d * moebius_mu (a * N div d) * h (a * N div d))\"\n    have 1: \"?a = (\\<Sum>d | d dvd a. f_aux d)\" using f_aux_def by blast\n    {fix d :: nat\n    assume \"d dvd a\"\n    then have \"N * a div (a div d) = N * d\" \n      using 3 by force}\n    then have 2: \"?b = (\\<Sum>d | d dvd a. f_aux (a div d))\" \n      unfolding f_aux_def by (simp add: algebra_simps)\n    show \"?a = ?b\" \n      using bij 1 2\n      by (simp add: sum.reindex_bij_betw[of \"((div) a)\" \"{d. d dvd a}\" \"{d. d dvd a}\"])\n  qed\n  also have \"\\<dots> = moebius_mu N * h N * f a * (\\<Sum>d | d dvd a \\<and> coprime N d. moebius_mu d * (h d div f d))\"\n   (is \"?a = ?b\")\n  proof -\n    have \"?a = (\\<Sum>d | d dvd a \\<and> coprime N d. f(a div d) * moebius_mu (N*d) * h (N*d))\"\n      by (rule sum.mono_neutral_right)(auto simp add: moebius_prod_not_coprime 3)\n    also have \"\\<dots> = (\\<Sum>d | d dvd a \\<and> coprime N d. moebius_mu N * h N * f(a div d) * moebius_mu d * h d)\"\n    proof (rule sum.cong,simp)\n      fix d\n      assume a: \"d \\<in> {d. d dvd a \\<and> coprime N d}\"\n      then have 1: \"moebius_mu (N*d) = moebius_mu N * moebius_mu d\"\n        using mult_moebius unfolding multiplicative_function_def \n        by (simp add: moebius_mu.mult_coprime)\n      from a have 2: \"h (N*d) = h N * h d\"\n         using assms(5) unfolding multiplicative_function_def \n         by (simp add: assms(5) multiplicative_function.mult_coprime)\n      show \"f (a div d) * moebius_mu (N * d) * h (N * d) =\n         moebius_mu N * h N * f (a div d) * moebius_mu d * h d\"\n       by (simp add: divide_simps 1 2)\n    qed\n    also have \"\\<dots> = (\\<Sum>d | d dvd a \\<and> coprime N d. moebius_mu N * h N * (f a div f d) * moebius_mu d * h d)\"\n      by (intro sum.cong refl) (use multipl_div_mono[of f _ a] assms(4,6-8) 3 in force)\n    also have \"\\<dots> = moebius_mu N * h N * f a * (\\<Sum>d | d dvd a \\<and> coprime N d. moebius_mu d * (h d div f d))\"\n      by (simp add: sum_distrib_left algebra_simps)\n    finally show ?thesis by blast\n  qed\n  also have \"\\<dots> =\n           moebius_mu N * h N * f a * (\\<Prod>p\\<in>{p. p \\<in> prime_factors a \\<and> \\<not> (p dvd N)}. 1 - (h p div f p))\"\n   proof -\n     have \"multiplicative_function (\\<lambda>d. h d div f d)\" \n       using multiplicative_function_divide \n             comp_to_mult \n             assms(4,5) by blast\n     then have \"(\\<Sum>d | d dvd a \\<and> coprime N d. moebius_mu d * (h d div f d)) =\n    (\\<Prod>p\\<in>{p. p \\<in> prime_factors a \\<and> \\<not> (p dvd N)}. 1 - (h p div f p))\"\n       using sum_divisors_moebius_mu_times_multiplicative_revisited[\n         of \"(\\<lambda>d. h d div f d)\" a N]         \n           assms(8) Ngr0 3 by blast \n    then show ?thesis by argo\n  qed    \n  also have \"\\<dots> = f(a) * moebius_mu(N) * h(N) * \n     ((\\<Prod>p\\<in>{p. p \\<in> prime_factors (a*N)}. 1 - (h p div f p)) div\n     (\\<Prod>p\\<in>{p. p \\<in> prime_factors N}. 1 - (h p div f p)))\"\n  proof -\n    have \"{p. p \\<in>prime_factors a \\<and> \\<not> p dvd N} = \n          ({p. p \\<in>prime_factors (a*N)} - {p. p \\<in>prime_factors N})\"\n      using p_div_set[of a N] by blast\n    then have eq2: \"(\\<Prod>p\\<in>{p. p \\<in>prime_factors a \\<and> \\<not> p dvd N}. 1 - h p / f p) = \n          prod (\\<lambda>p. 1 - h p / f p) ({p. p \\<in>prime_factors (a*N)} - {p. p \\<in>prime_factors N})\"\n      by auto\n    also have eq: \"\\<dots> = prod (\\<lambda>p. 1 - h p / f p) {p. p \\<in>prime_factors (a*N)} div\n                     prod (\\<lambda>p. 1 - h p / f p) {p. p \\<in>prime_factors N}\"\n    proof (intro prod_div_sub,simp,simp,simp add: \"3\" Ngr0 dvd_prime_factors,simp,standard)\n      fix b\n      assume \"b \\<in># prime_factorization N\"\n      then have p_b: \"prime b\" using in_prime_factors_iff by blast\n      then show \"f b = 0 \\<or> h b \\<noteq> f b\" using assms(6)[OF p_b] by auto\n    qed\n    also have \"\\<dots> = (\\<Prod>p\\<in>{p. p \\<in> prime_factors (a*N)}. 1 - (h p div f p)) div\n     (\\<Prod>p\\<in>{p. p \\<in> prime_factors N}. 1 - (h p div f p))\" by blast\n    finally have \"(\\<Prod>p\\<in>{p. p \\<in>prime_factors a \\<and> \\<not> p dvd N}. 1 - h p / f p) = \n        (\\<Prod>p\\<in>{p. p \\<in> prime_factors (a*N)}. 1 - (h p div f p)) div\n     (\\<Prod>p\\<in>{p. p \\<in> prime_factors N}. 1 - (h p div f p))\" \n      using eq eq2 by auto\n    then show ?thesis by simp\n  qed\n  also have \"\\<dots> = f(a) * moebius_mu(N) * h(N) * (F(k) div f(k)) * (f(N) div F(N))\"\n   (is \"?a = ?b\")\n  proof -\n    have \"F(N) = (f N) *(\\<Prod>p\\<in> prime_factors N. 1 - (h p div f p))\"\n      unfolding F_def g_def\n      by (intro dirichlet_prod_completely_multiplicative_left) (auto simp add: Ngr0 assms(4-6))\n    then have eq_1: \"(\\<Prod>p\\<in> prime_factors N. 1 - (h p div f p)) = \n               F N div f N\" using 2 f_N_not_z by simp\n    have \"F(k) = (f k) * (\\<Prod>p\\<in> prime_factors k. 1 - (h p div f p))\"\n      unfolding F_def g_def\n      by (intro dirichlet_prod_completely_multiplicative_left) (auto simp add: assms(4-7))\n    then have eq_2: \"(\\<Prod>p\\<in> prime_factors k. 1 - (h p div f p)) = \n               F k div f k\" using 2 f_k_not_z by simp\n\n    have \"?a = f a * moebius_mu N * h N * \n           ((\\<Prod>p\\<in> prime_factors k. 1 - (h p div f p)) div\n           (\\<Prod>p\\<in> prime_factors N. 1 - (h p div f p)))\"\n      using 2 by (simp add: algebra_simps) \n    also have  \"\\<dots> = f a * moebius_mu N * h N * ((F k div f k) div (F N div f N))\"\n      by (simp add: eq_1 eq_2)\n    finally show ?thesis by simp\n  qed\n  also have \"\\<dots> = moebius_mu N * h N * ((F k * f a * f N) div (F N * f k))\"\n    by (simp add: algebra_simps) \n  also have \"\\<dots> = moebius_mu N * h N * ((F k * f(a*N)) div (F N * f k))\"\n  proof -\n    have \"f a * f N = f (a*N)\" \n    proof (cases \"a = 1 \\<or> N = 1\")\n      case True\n      then show ?thesis  \n        using assms(4) completely_multiplicative_function_def[of f] \n        by auto\n    next\n      case False\n      then show ?thesis \n        using 2 assms(4) completely_multiplicative_function_def[of f] \n             Ngr0 3 by auto\n    qed\n    then show ?thesis by simp\n  qed \n  also have \"\\<dots> = moebius_mu N * h N * ((F k * f(k)) div (F N * f k))\"\n    using 2 by blast\n  also have \"\\<dots> = g(N) * (F k div F N)\"\n    using f_k_not_z g_def by simp\n  also have \"\\<dots> = (F(k)*g(N)) div (F(N))\" by auto\n  finally show ?thesis by simp\nqed\n\n(*TODO remove this and substitute \n the theorem totient_conv_moebius_mu in More_totient by \n this version: int \\<rightarrow> of_nat*)\nlemma totient_conv_moebius_mu_of_nat:\n  \"of_nat (totient n) = dirichlet_prod moebius_mu of_nat n\"\nproof (cases \"n = 0\")\n  case False\n  show ?thesis\n    by (rule moebius_inversion)\n       (insert False, simp_all add: of_nat_sum [symmetric] totient_divisor_sum del: of_nat_sum)\nqed simp_all\n\ncorollary ramanujan_sum_k_n_dirichlet_expr:\n fixes k n :: nat\n assumes \"k > 0\" \"n > 0\" \n shows \"c k n = of_nat (totient k) * \n                moebius_mu (k div gcd n k) div \n                of_nat (totient (k div gcd n k))\" \nproof -\n  define f :: \"nat \\<Rightarrow> complex\" \n    where \"f \\<equiv> of_nat\"\n  define F :: \"nat \\<Rightarrow> complex\"\n    where \"F \\<equiv> (\\<lambda>d. dirichlet_prod f moebius_mu d)\"\n  define g :: \"nat \\<Rightarrow> complex \"\n    where \"g \\<equiv> (\\<lambda>l. moebius_mu l)\" \n  define N where \"N \\<equiv> k div gcd n k\" \n  define h :: \"nat \\<Rightarrow> complex\"\n    where \"h \\<equiv> (\\<lambda>x. (if x = 0 then 0 else 1))\" \n  \n  have F_is_totient_k: \"F k = totient k\"\n    by (simp add: F_def f_def dirichlet_prod_commutes totient_conv_moebius_mu_of_nat[of k])\n  have F_is_totient_N: \"F N = totient N\"\n    by (simp add: F_def f_def dirichlet_prod_commutes totient_conv_moebius_mu_of_nat[of N])\n\n  have \"c k n = s id moebius_mu k n\"\n    using ramanujan_sum_conv_gen_ramanujan_sum assms by blast\n  also have \"\\<dots> =  s f g k n\" \n    unfolding f_def g_def by auto\n  also have \"g = (\\<lambda>k. moebius_mu k * h k)\"\n    by (simp add: fun_eq_iff h_def g_def)\n  also have \"multiplicative_function h\"\n    unfolding h_def by standard auto\n  hence \"s f (\\<lambda>k. moebius_mu k * h k) k n =\n           dirichlet_prod of_nat (\\<lambda>k. moebius_mu k * h k) k *\n           (moebius_mu (k div gcd n k) * h (k div gcd n k)) /\n           dirichlet_prod of_nat (\\<lambda>k. moebius_mu k * h k) (k div gcd n k)\" \n    unfolding f_def using assms mult_of_nat_c\n    by (intro gen_ramanujan_sum_dirichlet_expr) (auto simp: h_def)\n  also have \"\\<dots> = of_nat (totient k) * moebius_mu (k div gcd n k) / of_nat (totient (k div gcd n k))\"\n    using F_is_totient_k F_is_totient_N by (auto simp: h_def F_def N_def f_def)\n  finally show ?thesis .\nqed\n\nno_notation ramanujan_sum (\"c\")\nno_notation gen_ramanujan_sum (\"s\")\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/Ramanujan_Sums.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8376199633332891, "lm_q2_score": 0.8418256472515683, "lm_q1q2_score": 0.705129967783881}}
{"text": "section{*\\label{sec_Refinement}Refinement Calculus and Monotonic Predicate Transformers*}\n\ntheory Refinement imports Main\nbegin\ntext{*\n  In this section we introduce the basics of refinement calculus \\cite{back-wright-98}.\n  Part of this theory is a reformulation of some definitions from \\cite{preoteasa:back:2010a},\n  but here they are given for predicates, while \\cite{preoteasa:back:2010a} uses\n  sets.\n*}\n \nnotation\n    bot (\"\\<bottom>\") and\n    top (\"\\<top>\") and\n    inf (infixl \"\\<sqinter>\" 70)\n    and sup (infixl \"\\<squnion>\" 65)\n\nsubsection{*Basic predicate transformers*}\n\ndefinition\n    demonic :: \"('a => 'b::lattice) => 'b => 'a \\<Rightarrow> bool\" (\"[: _ :]\" [0] 1000) where\n    \"[:Q:] p s = (Q s \\<le> p)\"\n\ndefinition\n    assert::\"'a::semilattice_inf => 'a => 'a\" (\"{. _ .}\" [0] 1000) where\n    \"{.p.} q \\<equiv>  p \\<sqinter> q\"\n\ndefinition\n    \"assume\"::\"('a::boolean_algebra) => 'a => 'a\" (\"[. _ .]\" [0] 1000) where\n    \"[.p.] q \\<equiv>  (-p \\<squnion> q)\"\n\ndefinition\n    angelic :: \"('a \\<Rightarrow> 'b::{semilattice_inf,order_bot}) \\<Rightarrow> 'b \\<Rightarrow> 'a \\<Rightarrow> bool\" (\"{: _ :}\" [0] 1000) where\n    \"{:Q:} p s = (Q s \\<sqinter> p \\<noteq> \\<bottom>)\"\n\n\nsyntax\n    \"_assert\" :: \"patterns => logic => logic\"    (\"(1{._._.})\")\ntranslations\n    \"_assert x P\" == \"CONST assert (_abs x P)\"\n\nsyntax \n    \"_demonic\" :: \"patterns => patterns => logic => logic\" (\"([:_\\<leadsto>_._:])\")\ntranslations\n    \"_demonic x y t\" == \"(CONST demonic (_abs x (_abs y t)))\"\n\nsyntax \n    \"_angelic\" :: \"patterns => patterns => logic => logic\" (\"({:_ \\<leadsto> _._:})\")\ntranslations\n    \"_angelic x y t\" == \"(CONST angelic (_abs x (_abs y t)))\"\n\nlemma assert_o_def: \"{.f o g.} = {.(\\<lambda> x . f (g x)).}\"\n  by (simp add: o_def)\n\nlemma demonic_demonic: \"[:r:] o [:r':] = [:r OO r':]\"\n  by (simp add: fun_eq_iff le_fun_def demonic_def, auto)\n\nlemma assert_demonic_comp: \"{.p.} o [:r:] o {.p'.} o [:r':] = \n      {.x . p x \\<and> (\\<forall> y . r x y \\<longrightarrow> p' y).} o [:r OO r':]\"\n  by (auto simp add: fun_eq_iff le_fun_def assert_def demonic_def)\n\nlemma demonic_assert_comp: \"[:r:] o {.p.} = {.x.(\\<forall> y . r x y \\<longrightarrow> p y).} o [:r:]\"\n  by (auto simp add: fun_eq_iff le_fun_def assert_def demonic_def)\n\nlemma assert_assert_comp: \"{.p::'a::lattice.} o {.p'.} = {.p \\<sqinter> p'.}\"\n  by (simp add: fun_eq_iff le_fun_def assert_def demonic_def inf_assoc)\n\nlemma assert_assert_comp_pred: \"{.p.} o {.p'.} = {.x . p x \\<and> p' x.}\"\n  by (simp add: fun_eq_iff le_fun_def assert_def demonic_def inf_assoc)\n    \nlemma demonic_refinement: \"r' \\<le> r \\<Longrightarrow> [:r:] \\<le> [:r':]\"\n  apply (simp add: le_fun_def demonic_def)\n  using order_trans by blast\n\n  \ndefinition \"inpt r x = (\\<exists> y . r x y)\"\n\n\n\ndefinition trs ::  \"('a => 'b \\<Rightarrow> bool) => ('b \\<Rightarrow> bool) => 'a \\<Rightarrow> bool\" (\"{: _ :]\" [0] 1000) where\n  \"trs r = {. inpt r.} o [:r:]\"\n\nsyntax \n    \"_trs\" :: \"patterns => patterns => logic => logic\" (\"({:_\\<leadsto>_._:])\")\ntranslations\n    \"_trs x y t\" == \"(CONST trs (_abs x (_abs y t)))\"\n\n\nlemma assert_demonic_prop: \"{.p.} o [:r:] = {.p.} o [:(\\<lambda> x y . p x) \\<sqinter> r:]\"\n  by (auto simp add: fun_eq_iff assert_def demonic_def)\n\nlemma trs_trs: \"(trs r) o (trs r') \n  = trs ((\\<lambda> s t. (\\<forall> s' . r s s' \\<longrightarrow> (inpt r' s'))) \\<sqinter> (r OO r'))\" (is \"?S = ?T\")\n  by (simp add: trs_def inpt_def fun_eq_iff demonic_def assert_def le_fun_def, blast)\n\nlemma prec_inpt_equiv: \"p \\<le> inpt r \\<Longrightarrow> r' = (\\<lambda> x y . p x \\<and> r x y) \\<Longrightarrow> {.p.} o [:r:] = {:r':]\"\n  by (simp add: fun_eq_iff demonic_def assert_def le_fun_def inpt_def trs_def, auto)\n\nlemma assert_demonic_refinement: \"({.p.} o [:r:] \\<le> {.p'.} o [:r':]) = (p \\<le> p' \\<and> (\\<forall> x . p x \\<longrightarrow> r' x \\<le> r x))\"\n  by  (auto simp add: le_fun_def assert_def demonic_def)\n    \nlemma spec_demonic_refinement: \"({.p.} o [:r:] \\<le> [:r':]) = (\\<forall> x . p x \\<longrightarrow> r' x \\<le> r x)\"\n  by  (auto simp add: le_fun_def assert_def demonic_def)    \n\nlemma trs_refinement: \"(trs r \\<le> trs r') = ((\\<forall> x . inpt r x \\<longrightarrow> inpt r' x) \\<and> (\\<forall> x . inpt r x \\<longrightarrow> r' x \\<le> r x))\"\n  by (simp add: trs_def assert_demonic_refinement, simp add: le_fun_def)\n\nlemma demonic_choice: \"[:r:] \\<sqinter> [:r':] = [:r \\<squnion> r':]\"\n  by (simp add: fun_eq_iff demonic_def)\n\nlemma spec_demonic_choice: \"({.p.} o [:r:]) \\<sqinter> ({.p'.} o [:r':]) = ({.p \\<sqinter> p'.} o [:r \\<squnion> r':])\"\n  by (auto simp add: fun_eq_iff demonic_def assert_def)\n\nlemma trs_demonic_choice: \"trs r \\<sqinter> trs r' = trs ((\\<lambda> x y . inpt r x \\<and> inpt r' x) \\<sqinter> (r \\<squnion> r'))\"\n  by (simp add: trs_def inpt_def fun_eq_iff demonic_def assert_def le_fun_def, blast)\n\nlemma spec_angelic: \"p \\<sqinter> p' = \\<bottom> \\<Longrightarrow> ({.p.} o [:r:]) \\<squnion> ({.p'.} o [:r':]) \n    = {.p \\<squnion> p'.} o [:(\\<lambda> x y . p x \\<longrightarrow> r x y) \\<sqinter> ((\\<lambda> x y . p' x \\<longrightarrow> r' x y)):]\"\n  by (simp add: fun_eq_iff assert_def demonic_def, auto)\n\n  subsection{*Conjunctive predicate transformers*}\n\ndefinition \"conjunctive (S::'a::complete_lattice \\<Rightarrow> 'b::complete_lattice) = (\\<forall> Q . S (Inf Q) = INFIMUM Q S)\"\n  \ndefinition \"sconjunctive (S::'a::complete_lattice \\<Rightarrow> 'b::complete_lattice) = (\\<forall> Q . (\\<exists> x . x \\<in> Q) \\<longrightarrow> S (Inf Q) = INFIMUM Q S)\"\n  \n\nlemma conjunctive_sconjunctive[simp]: \"conjunctive S \\<Longrightarrow> sconjunctive S\"\n  by (simp add: conjunctive_def sconjunctive_def)\n\n\n\nlemma conjuncive_demonic [simp]: \"conjunctive [:r:]\"\n  apply (simp add: conjunctive_def demonic_def fun_eq_iff)\n  using le_Inf_iff by blast\n\nlemma sconjunctive_assert [simp]: \"sconjunctive {.p.}\"\n  apply (simp add: sconjunctive_def assert_def, safe)\n  apply (rule antisym)\n   apply (meson inf_le1 inf_le2 le_INF_iff le_Inf_iff le_infI)\n  by (metis (mono_tags, lifting) Inf_greatest le_INF_iff le_inf_iff order_refl)\n\nlemma sconjunctive_simp: \"x \\<in> Q \\<Longrightarrow> sconjunctive S \\<Longrightarrow> S (Inf Q) = INFIMUM Q S\"\n  by (auto simp add: sconjunctive_def)\n\nlemma sconjunctive_INF_simp: \"x \\<in> X \\<Longrightarrow> sconjunctive S \\<Longrightarrow> S (INFIMUM X Q) = INFIMUM (Q`X) S\"\n  by (cut_tac x = \"Q x\" and Q = \"Q ` X\" in sconjunctive_simp, auto)\n\nlemma demonic_comp [simp]: \"sconjunctive S \\<Longrightarrow> sconjunctive S' \\<Longrightarrow> sconjunctive (S o S')\"\nproof (subst sconjunctive_def, safe)\n  fix X :: \"'c set\"\n  fix a :: 'c\n  assume [simp]: \"sconjunctive S\"\n  assume [simp]: \"sconjunctive S'\"\n  assume [simp]: \"a \\<in> X\"\n  have A: \"S' (Inf X) = INFIMUM X S'\"\n    by (rule_tac x = a in sconjunctive_simp, auto)\n  also have B: \"S (INFIMUM X S') = INFIMUM (S' ` X) S\"\n    by (rule_tac x = \"S' a\" in sconjunctive_simp, auto)\n  finally show \"(S o S') (Inf X) = INFIMUM X (S \\<circ> S')\" by simp\nqed\n\nlemma conjunctive_INF[simp]:\"conjunctive S \\<Longrightarrow> S (INFIMUM X Q) = (INFIMUM X (S o Q))\"\n  by (metis INF_image conjunctive_def)\n\nlemma conjunctive_simp: \"conjunctive S \\<Longrightarrow>  S (Inf Q) = INFIMUM Q S\"\n  by (metis conjunctive_def)\n\nlemma conjunctive_monotonic [simp]: \"sconjunctive S \\<Longrightarrow> mono S\"\n  proof (rule monoI)\n    fix a b :: 'a\n    assume [simp]: \"a \\<le> b\"\n    assume [simp]: \"sconjunctive S\"\n    have [simp]: \"a \\<sqinter> b = a\"\n      by (rule antisym, auto)\n    have A: \"S a = S a \\<sqinter> S b\"\n      by (cut_tac S = S and x = a and Q = \"{a, b}\" in sconjunctive_simp, auto )\n    show \"S a \\<le> S b\"\n      by (subst A, simp)\n  qed\n\ndefinition \"grd S = - S \\<bottom>\"\n\nlemma grd_demonic: \"grd [:r:] = inpt r\"\n  by (simp add: fun_eq_iff grd_def demonic_def le_fun_def inpt_def)\n      \nlemma \"(S::'a::bot \\<Rightarrow> 'b::boolean_algebra) \\<le> S' \\<Longrightarrow> grd S' \\<le> grd S\"\n  by (simp add: grd_def le_fun_def)\n\nlemma [simp]: \"inpt (\\<lambda>x y. p x \\<and> r x y) = p \\<sqinter> inpt r\"\n  by (simp add: fun_eq_iff inpt_def)\n\n(*to remove*)\nlemma [simp]: \"p \\<le> inpt r \\<Longrightarrow> p \\<sqinter> inpt r = p\"\n  by (simp add: fun_eq_iff le_fun_def, auto)\n\nlemma grd_spec: \"grd ({.p.} o [:r:]) = -p \\<squnion> inpt r\"\n  by (simp add: grd_def fun_eq_iff demonic_def assert_def le_fun_def inpt_def)\n\n\ndefinition \"fail S = -(S \\<top>)\"\ndefinition \"term S = (S \\<top>)\"\ndefinition \"prec S = - (fail S)\"\ndefinition \"rel S = (\\<lambda> x y . \\<not> S (\\<lambda> z . y \\<noteq> z) x)\"\n\nlemma rel_spec: \"rel ({.p.} o [:r:]) x y = (p x \\<longrightarrow> r x y)\"\n  by (simp add: rel_def demonic_def assert_def le_fun_def)\n\nlemma prec_spec: \"prec ({.p.} o [:r::'a\\<Rightarrow>'b\\<Rightarrow>bool:]) = p\"\n  by (auto simp add: prec_def fail_def demonic_def assert_def le_fun_def fun_eq_iff)\n\nlemma fail_spec: \"fail ({.p.} o [:(r::'a\\<Rightarrow>'b::boolean_algebra):]) = -p\"\n  by (simp add: fail_def fun_eq_iff assert_def demonic_def le_fun_def top_fun_def)\n\nlemma [simp]: \"prec ({.p.} o [:(r::'a\\<Rightarrow>'b::boolean_algebra):]) = p\"\n  by (simp add: prec_def fail_spec)\n\nlemma [simp]: \"prec (T::('a::boolean_algebra \\<Rightarrow> 'b::boolean_algebra)) = \\<top> \\<Longrightarrow> prec (S o T) = prec S\"\n  by (simp add: prec_def fail_def)\n\nlemma [simp]: \"prec [:r::'a \\<Rightarrow> 'b::boolean_algebra:] = \\<top>\"\n  by (simp add: demonic_def prec_def fail_def fun_eq_iff)\n\nlemma prec_rel: \"{. p .} \\<circ> [: \\<lambda>x y. p x \\<and> r x y :] = {.p.} o [:r:]\"\n  by (simp add: fun_eq_iff le_fun_def demonic_def assert_def, auto)\n\ndefinition \"Fail = \\<bottom>\"\n\nlemma Fail_assert_demonic: \"Fail = {.\\<bottom>.} o [:r:]\"\n  by (simp add: fun_eq_iff Fail_def assert_def)\n\nlemma Fail_assert: \"Fail = {.\\<bottom>.} o [:\\<bottom>:]\"\n  by (rule Fail_assert_demonic)\n\nlemma fail_comp[simp]: \"\\<bottom> o S = \\<bottom>\"\n  by (simp add: fun_eq_iff)\n\nlemma Fail_fail: \"mono (S::'a::boolean_algebra \\<Rightarrow> 'b::boolean_algebra) \\<Longrightarrow> (S = Fail) = (fail S = \\<top>)\"\nproof auto\n  show \"fail (Fail::'a \\<Rightarrow> 'b) = \\<top>\"\n    by (metis Fail_def bot_apply compl_bot_eq fail_def)\nnext\n  assume A: \"mono S\"\n  assume B: \"fail S = \\<top>\"\n  show \"S = Fail\"\n  proof (rule antisym)\n    show \"S \\<le> Fail\"\n      by (metis (hide_lams, no_types) A B bot.extremum_unique compl_le_compl_iff fail_def le_fun_def monoD top_greatest)\n    next\n      show \"Fail \\<le> S\"\n        by (metis Fail_def bot.extremum)\n  qed\nqed\n    \nlemma sconjunctive_spec: \"sconjunctive S \\<Longrightarrow> S = {.prec S.} o [:rel S:]\"\nproof (simp add: fun_eq_iff assert_def rel_def demonic_def prec_def fail_def le_fun_def, safe)\n  fix x xa\n  assume  \"sconjunctive S\"\n  from this have mono: \"mono S\"\n    by (rule conjunctive_monotonic)\n  from this have A: \"S x \\<le> S \\<top>\"\n    by (simp add: monoD)\n  assume C: \"S x xa\"\n  from this and A show \"S \\<top> xa\"\n    by blast\n  fix xb\n  from mono have B: \"\\<not> x xb \\<Longrightarrow> S x \\<le> S ((\\<noteq>) xb)\"\n    by (rule monoD, blast)\n  assume \"\\<not> S ((\\<noteq>) xb) xa\"\n  from this B C show \"x xb\"\n    by blast\nnext\n  fix xa x\n  assume  sconj: \"sconjunctive S\"\n  assume B: \"S \\<top> xa\"\n  assume D: \"\\<forall>xb. \\<not> S ((\\<noteq>) xb) xa \\<longrightarrow> x xb\"\n  define Q where \"Q = { (\\<noteq>) b | b . \\<not> x b}\"\n  from sconj have A: \"(\\<exists>x. x \\<in> Q) \\<Longrightarrow> S (Inf Q) = (INF x:Q. S x)\"\n    by (simp add: sconjunctive_def)\n  have C: \"Inf Q = x\"\n    apply (simp add: Q_def fun_eq_iff, safe)\n    by (drule_tac x = \"(\\<noteq>) xa\" in spec, auto)\n  show \"S x xa\"\n  proof cases\n    assume \"x = \\<top>\"\n    from this B show ?thesis by simp\n  next\n    assume \"x \\<noteq> \\<top>\"\n    from this have [simp]: \"S x = (INF x:Q. S x)\"\n      apply (unfold C [symmetric])\n      by (rule A, blast)\n    show ?thesis\n      apply simp\n      using D by (simp add: Q_def, blast)\n  qed\nqed\n  \ndefinition \"non_magic S = (S \\<bottom> = \\<bottom>)\"\n  \n\nlemma non_magic_spec: \"non_magic ({.p.} o [:r:]) = (p \\<le> inpt r)\"\n  by (simp add: non_magic_def fun_eq_iff inpt_def demonic_def assert_def le_fun_def)\n    \n\nlemma sconjunctive_non_magic: \"sconjunctive S \\<Longrightarrow> non_magic S = (prec S \\<le> inpt (rel S))\"\n  apply (subst non_magic_spec [THEN sym])\n  apply (subst sconjunctive_spec [THEN sym])\n  by simp_all\n  \ndefinition \"implementable S = (sconjunctive S \\<and> non_magic S)\"\n\nlemma implementable_spec: \"implementable S \\<Longrightarrow> \\<exists> p r . S = {.p.} o [:r:] \\<and> p \\<le> inpt r\"\n  apply (simp add: implementable_def)\n  apply (rule_tac x = \"prec S\" in exI)\n  apply (rule_tac x = \"rel S\" in exI, safe)\n  apply (rule sconjunctive_spec, simp)\n  by (drule sconjunctive_non_magic, auto)\n\n\ndefinition \"Skip = (id:: ('a \\<Rightarrow> bool) \\<Rightarrow> ('a \\<Rightarrow> bool))\"\n\nlemma assert_true_skip: \"{.\\<top>::'a \\<Rightarrow> bool.} = Skip\"\n  by (simp add: fun_eq_iff assert_def Skip_def)\n\nlemma skip_comp [simp]: \"Skip o S = S\"\n  by (simp add: fun_eq_iff assert_def Skip_def)\n\nlemma comp_skip[simp]:\"S o Skip = S\"\n  by (simp add: fun_eq_iff assert_def Skip_def)\n\nlemma assert_rel_skip[simp]: \"{. \\<lambda> (x, y) . True .} = Skip\"\n  by (simp add: fun_eq_iff Skip_def assert_def)\n\nlemma [simp]: \"mono S \\<Longrightarrow> mono S' \\<Longrightarrow> mono (S o S')\"\n  by (simp add: mono_def)\n\nlemma [simp]: \"mono {.p::('a \\<Rightarrow> bool).}\"\n  by simp\n\nlemma [simp]: \"mono [:r::('a \\<Rightarrow> 'b \\<Rightarrow> bool):]\"\n  by simp\n\nlemma assert_true_skip_a: \"{. x . True .} = Skip\"\n  by (simp add: fun_eq_iff assert_def Skip_def)\n    \nlemma assert_false_fail: \"{.\\<bottom>::'a::boolean_algebra.}  = \\<bottom>\"\n  by (simp add: fun_eq_iff assert_def)\n    \n\nlemma magoc_comp[simp]: \"\\<top> o S = \\<top>\"\n  by (simp add: fun_eq_iff)\n\nlemma left_comp: \"T o U = T' o U' \\<Longrightarrow> S o T o U = S o T' o U'\"\n  by (simp add: comp_assoc)\n\nlemma assert_demonic: \"{.p.} o [:r:] = {.p.} o [:x  \\<leadsto> y . p x \\<and> r x y:]\"\n  by (auto simp add: fun_eq_iff assert_def demonic_def le_fun_def)\n\nlemma \"trs r \\<sqinter> trs r' = trs (\\<lambda> x y . inpt r x \\<and> inpt r' x \\<and> (r x y \\<or> r' x y))\"\n  by (auto simp add: fun_eq_iff trs_def assert_def demonic_def inpt_def)\n\n\nlemma mono_assert[simp]: \"mono {.p.}\"\n  by (metis (no_types, lifting) assert_def inf.cobounded1 inf_le2 le_infI monoI order_trans)\n\nlemma mono_assume[simp]: \"mono [.p.]\"\n  by (metis assume_def monoI sup.orderI sup_idem sup_mono)\n\nlemma mono_demonic[simp]: \"mono [:r:]\"\n  by  (auto simp add: mono_def demonic_def le_fun_def)\n\nlemma mono_comp_a[simp]: \"mono S \\<Longrightarrow> mono T \\<Longrightarrow> mono (S o T)\"\n  by simp\n\nlemma mono_demonic_choice[simp]: \"mono S \\<Longrightarrow> mono T \\<Longrightarrow> mono (S \\<sqinter> T)\"\n  apply (simp add: mono_def)\n  apply auto\n   apply (rule_tac y = \"S x\" in order_trans, simp_all)\n  by (rule_tac y = \"T x\" in order_trans, simp_all)\n\nlemma mono_Skip[simp]: \"mono Skip\"\n  by (simp add: mono_def Skip_def)\n\nlemma mono_comp: \"mono S \\<Longrightarrow> S \\<le> S' \\<Longrightarrow> T \\<le> T' \\<Longrightarrow> S o T \\<le> S' o T'\"\n  proof (simp add: le_fun_def, safe)\n    fix x\n    assume A: \"mono S\"\n    assume B: \"\\<forall>x. S x \\<le> S' x\"\n    assume \"\\<forall>x. T x \\<le> T' x\"\n    from this have \"T x \\<le> T' x\" by simp\n    from A and this have C: \"S (T x) \\<le> S (T' x)\"\n      by (simp add: mono_def)\n    from B also have \"... \\<le> S' (T' x)\" by simp\n    from C and this show \"S (T x) \\<le> S' (T' x)\" by (rule order_trans)\n  qed\n\nlemma sconjunctive_simp_a: \"sconjunctive S \\<Longrightarrow> prec S = p \\<Longrightarrow> rel S = r \\<Longrightarrow> S = {.p.} o [:r:]\"\n  by (subst sconjunctive_spec, simp_all)\n\nlemma sconjunctive_simp_b: \"sconjunctive S \\<Longrightarrow> prec S = \\<top> \\<Longrightarrow> rel S = r \\<Longrightarrow> S = [:r:]\"\n  by (subst sconjunctive_spec, simp_all add: assert_true_skip)\n\nlemma sconj_Fail[simp]: \"sconjunctive Fail\"\n  by (metis Fail_def INF_eq_const all_not_in_conv bot_apply sconjunctive_def)\n\nlemma sconjunctive_simp_c: \"sconjunctive (S::('a \\<Rightarrow> bool) \\<Rightarrow> 'b \\<Rightarrow> bool) \\<Longrightarrow> prec S = \\<bottom> \\<Longrightarrow> S = Fail\"\n  by (drule sconjunctive_spec, simp add: Fail_assert_demonic [THEN sym])\n\nlemma demonic_eq_skip: \"[: (=) :] = Skip\"\n  apply (simp add: fun_eq_iff)\n  by (metis (mono_tags) Skip_def demonic_def id_apply predicate1D predicate1I)\n\ndefinition \"Havoc = [:\\<top>:]\"\n\ndefinition \"Magic = [:\\<bottom>::'a \\<Rightarrow> 'b::boolean_algebra:]\"\n\nlemma Magic_top: \"Magic = \\<top>\"\n  by (simp add: fun_eq_iff Magic_def demonic_def)\n    \nlemma [simp]: \"Magic \\<noteq> Fail\"\n  by (simp add: Magic_top Fail_def fun_eq_iff)\n      \nlemma Havoc_Fail[simp]: \"Havoc o (Fail::'a \\<Rightarrow> 'b \\<Rightarrow> bool) = Fail\"\n  by (simp add: Havoc_def fun_eq_iff Fail_def demonic_def le_fun_def)\n\nlemma demonic_havoc: \"[: \\<lambda>x (x', y). True :] = Havoc\"\n  by (simp add: fun_eq_iff demonic_def le_fun_def top_fun_def Havoc_def)\n\nlemma [simp]: \"mono Magic\"\n  by (simp add: Magic_def)\n\nlemma demonic_false_magic: \"[: \\<lambda>(x, y) (u, v). False :] = Magic\"\n  by (simp add: fun_eq_iff demonic_def le_fun_def top_fun_def Magic_def)\n\nlemma demonic_magic[simp]: \"[:r:] o Magic = Magic\"\n  by (simp add:  fun_eq_iff demonic_def le_fun_def top_fun_def bot_fun_def Magic_def product_def Skip_def)\n\nlemma magic_comp[simp]: \"Magic o S = Magic\"\n  by (simp add:  fun_eq_iff demonic_def le_fun_def top_fun_def Magic_def product_def Skip_def)\n    \nlemma hvoc_magic[simp]: \"Havoc \\<circ> Magic = Magic\"\n  by (simp add: Havoc_def)\n\nlemma \"Havoc \\<top> = \\<top>\"\n  by (simp add: Havoc_def fun_eq_iff demonic_def le_fun_def top_fun_def)\n    \nlemma Skip_id[simp]: \"Skip p = p\"\n  by (simp add: Skip_def)\n\n\nlemma demonic_pair_skip: \"[: x, y \\<leadsto> u, v. x = u \\<and> y = v :] = Skip\"\n  by (simp add: fun_eq_iff demonic_def Skip_def le_fun_def)\n\nlemma comp_demonic_demonic: \"S o [:r:] o [:r':] = S o [:r OO r':]\"\n  by (simp add: comp_assoc demonic_demonic)\n\nlemma comp_demonic_assert: \"S o [:r:] o {.p.} = S o {. x. \\<forall>y . r x y \\<longrightarrow> p y .} o [:r:]\"\n  by (simp add: comp_assoc demonic_assert_comp)\n\nlemma assert_demonic_eq_demonic: \"({.p.} o [:r::'a \\<Rightarrow> 'b \\<Rightarrow> bool:] = [:r:]) = (\\<forall> x . p x)\"\n  by (simp add: fun_eq_iff demonic_def assert_def le_fun_def, blast)\n\nlemma trs_inpt_top: \"inpt r = \\<top> \\<Longrightarrow> trs r = [:r:]\"\n  by (simp add: trs_def assert_true_skip)\n\nsubsection{*Product and Fusion of predicate transformers*}\n  \n  text{*\n  In this section we define the fusion and product operators from \\cite{back:butler:1995}. \n  The fusion of two programs $S$ and $T$ is intuitively equivalent with the parallel execution \n  of the two programs. If $S$ and $T$ assign nondeterministically some value to some program \n  variable $x$, then the fusion of $S$ and $T$ will assign a value to $x$ which can be assigned \n  by both $S$ and $T$.\n*}\n\ndefinition fusion :: \"(('a \\<Rightarrow> bool) \\<Rightarrow> ('b \\<Rightarrow> bool)) \\<Rightarrow> (('a \\<Rightarrow> bool) \\<Rightarrow> ('b \\<Rightarrow> bool)) \\<Rightarrow> (('a \\<Rightarrow> bool) \\<Rightarrow> ('b \\<Rightarrow> bool))\" (infixl \"\\<parallel>\" 70) where\n  \"(S \\<parallel> S') q x = (\\<exists> (p::'a\\<Rightarrow>bool) p' . p \\<sqinter> p' \\<le> q \\<and> S p x \\<and> S' p' x)\"\n\nlemma fusion_demonic: \"[:r:] \\<parallel> [:r':] = [:r \\<sqinter> r':]\"\n  by (auto simp add: fun_eq_iff fusion_def demonic_def le_fun_def)\n\nlemma fusion_spec: \"({.p.} \\<circ> [:r:]) \\<parallel> ({.p'.} \\<circ> [:r':]) = ({.p \\<sqinter> p'.} \\<circ> [:r \\<sqinter> r':])\"\n  by (auto simp add: fun_eq_iff fusion_def assert_def demonic_def le_fun_def)\n\nlemma fusion_assoc: \"S \\<parallel> (T \\<parallel> U) = (S \\<parallel> T) \\<parallel> U\"\nproof (rule antisym, auto simp add: fusion_def)\n  fix p p' q s s' :: \"'a \\<Rightarrow> bool\"\n  fix a\n  assume A: \"p \\<sqinter> p' \\<le> q\" and B: \"s \\<sqinter> s' \\<le> p'\"\n  assume C: \"S p a\" and D: \"T s a\" and E: \"U s' a\"\n  from A and B  have F: \"(p \\<sqinter> s) \\<sqinter> s' \\<le> q\"\n    by (simp add: le_fun_def)\n  have \"(\\<exists>v v'. v \\<sqinter> v' \\<le> (p \\<sqinter> s) \\<and> S v a \\<and> T v' a)\"\n    by (metis C D order_refl)\n  show \"\\<exists>u u' . u \\<sqinter> u' \\<le> q \\<and> (\\<exists>v v'. v \\<sqinter> v' \\<le> u \\<and> S v a \\<and> T v' a) \\<and> U u' a\"\n    by (metis F C D E order_refl)\nnext\n  fix p p' q s s' :: \"'a \\<Rightarrow> bool\"\n  fix a\n  assume A: \"p \\<sqinter> p' \\<le> q\" and B: \"s \\<sqinter> s' \\<le> p\"\n  assume C: \"S s a\" and D: \"T s' a\" and E: \"U p' a\"\n  from A and B  have F: \"s \\<sqinter> (s' \\<sqinter> p')  \\<le> q\"\n    by (simp add: le_fun_def)\n  have \"(\\<exists>v v'. v \\<sqinter> v' \\<le> s' \\<sqinter> p' \\<and> T v a \\<and> U v' a)\"\n    by (metis D E eq_iff)\n  show \"\\<exists>u u'. u \\<sqinter> u' \\<le> q \\<and> S u a \\<and> (\\<exists>v v'. v \\<sqinter> v' \\<le> u' \\<and> T v a \\<and> U v' a)\"\n    by (metis F C D E order_refl)\nqed\n\nlemma fusion_refinement: \"S \\<le> T \\<Longrightarrow> S' \\<le> T' \\<Longrightarrow> S \\<parallel> S' \\<le> T \\<parallel> T'\"\n  by (simp add: le_fun_def fusion_def, metis)\n\nlemma \"conjunctive S \\<Longrightarrow> S \\<parallel> \\<top> = \\<top>\"\n  by (auto simp add: fun_eq_iff fusion_def le_fun_def conjunctive_def)\n\nlemma fusion_spec_local: \"a \\<in> init \\<Longrightarrow> ([: x \\<leadsto> u, y . u \\<in> init \\<and> x = y :] \\<circ> {.p.} \\<circ> [:r:]) \\<parallel> ({.p'.} \\<circ> [:r':]) \n    = [: x \\<leadsto> u, y . u \\<in> init \\<and> x = y :] \\<circ> {.u,x . p (u, x) \\<and> p' x.} \\<circ> [:u, x \\<leadsto> y . r (u, x) y \\<and> r' x y:]\" (is \"?p \\<Longrightarrow> ?S = ?T\")\nproof -\n  assume \"?p\"\n  from this have [simp]: \"(\\<lambda>x. \\<forall>a. a \\<in> init \\<longrightarrow> p (a, x) \\<and> p' x) = (\\<lambda>x. \\<forall>a. a \\<in> init \\<longrightarrow> p (a, x)) \\<sqinter> p'\"\n     by auto\n  have [simp]: \"(\\<lambda>x (u, y). u \\<in> init \\<and> x = y) OO (\\<lambda>(u, x) y. r (u, x) y \\<and> r' x y) = (\\<lambda>x (u, y). u \\<in> init \\<and> x = y) OO r \\<sqinter> r'\"\n    by auto\n  have \"?S = \n    ({. \\<lambda>x. \\<forall>a. a \\<in> init \\<longrightarrow> p (a, x) .} \\<circ> [: \\<lambda>x (u, y). u \\<in> init \\<and> x = y :] \\<circ> [: r :]) \\<parallel> ({. p' .} \\<circ> [: r' :])\"\n    by (simp add: demonic_assert_comp)\n  also have \"... =  {. (\\<lambda>x. \\<forall>a. a \\<in> init \\<longrightarrow> p (a, x)) \\<sqinter> p' .} \\<circ> [: (\\<lambda>x (u, y). u \\<in> init \\<and> x = y) OO r \\<sqinter> r' :]\"\n    by (simp add: comp_assoc demonic_demonic fusion_spec)\n  also have \"... = ?T\"\n    by (simp add: demonic_assert_comp comp_assoc demonic_demonic fusion_spec)\n  finally show ?thesis by simp\nqed\n  \nlemma fusion_demonic_idemp [simp]: \"[:r:] \\<parallel> [:r:] = [:r:]\"\n  by (simp add: fusion_demonic)\n\n\nlemma fusion_spec_local_a: \"a \\<in> init \\<Longrightarrow> ([:x \\<leadsto> u, y . u \\<in> init \\<and> x = y:] \\<circ> {.p.} \\<circ> [:r:]) \\<parallel> [:r':] \n    = ([:x \\<leadsto> u, y . u \\<in> init \\<and> x = y:] \\<circ> {.p.} \\<circ> [:u, x \\<leadsto> y . r (u, x) y \\<and> r' x y:])\"\n  by (cut_tac p' = \"\\<top>\" and init = init and p = p and r = r and r' = r' in fusion_spec_local, auto simp add:  assert_true_skip)\n\nlemma fusion_local_refinement:\n  \"a \\<in> init \\<Longrightarrow> (\\<And> x u y . u \\<in> init \\<Longrightarrow> p' x \\<Longrightarrow> r (u, x) y \\<Longrightarrow> r' x y) \\<Longrightarrow> \n    {.p'.} o (([:x \\<leadsto> u, y . u \\<in> init \\<and> x = y:] \\<circ> {.p.} \\<circ> [:r:]) \\<parallel> [:r':]) \\<le> [:x \\<leadsto> u, y . u \\<in> init \\<and> x = y:] \\<circ> {.p.} \\<circ> [:r:]\"\nproof -\n assume A: \"a \\<in> init\"\n assume [simp]: \"(\\<And> x u y . u \\<in> init \\<Longrightarrow> p' x \\<Longrightarrow> r (u, x) y \\<Longrightarrow> r' x y)\"\n have \" {. x. p' x \\<and> (\\<forall>a. a \\<in> init \\<longrightarrow> p (a, x)) .} \\<circ> [: (\\<lambda>x (u, y). u \\<in> init \\<and> x = y) OO (\\<lambda>(u, x) y. r (u, x) y \\<and> r' x y) :]\n          \\<le> {. \\<lambda>x. \\<forall>a. a \\<in> init \\<longrightarrow> p (a, x) .} \\<circ> [: (\\<lambda>x (u, y). u \\<in> init \\<and> x = y) OO r :]\"\n  by (auto simp add: assert_demonic_refinement)\nfrom this have \" {. x. p' x \\<and> (\\<forall>a. a \\<in> init \\<longrightarrow> p (a, x)) .} \\<circ> [: (\\<lambda>x (u, y). u \\<in> init \\<and> x = y) OO (\\<lambda>(u, x) y. r (u, x) y \\<and> r' x y) :]\n        \\<le> {. \\<lambda>x. \\<forall>a. a \\<in> init \\<longrightarrow> p (a, x) .} \\<circ> [: \\<lambda>x (u, y). u \\<in> init \\<and> x = y :] \\<circ> [: r :]\"\n  by (simp add: comp_assoc demonic_demonic)\nfrom this have \"{. p' .} \\<circ> [: \\<lambda>x (u, y). u \\<in> init \\<and> x = y :] \\<circ> {. p .} \\<circ> [: \\<lambda>(u, x) y. r (u, x) y \\<and> r' x y :] \n        \\<le> [: x \\<leadsto> u, y. u \\<in> init \\<and> x = y :] \\<circ> {. p .} \\<circ> [: r :]\"\n  by (simp add: demonic_assert_comp assert_demonic_comp)\nfrom this have \"{. p' .} \\<circ> ([: x \\<leadsto> (u, y) . u \\<in> init \\<and> x = y :] \\<circ> {. p .} \\<circ> [: (u, x) \\<leadsto> y . r (u, x) y \\<and> r' x y :]) \n      \\<le> [: x \\<leadsto> (u, y) . u \\<in> init \\<and> x = y :] \\<circ> {. p .} \\<circ> [: r :]\"\n  by (simp add: comp_assoc [THEN sym])\nfrom A and this show ?thesis \n  by  (unfold fusion_spec_local_a, simp)\nqed\n\nlemma fusion_spec_demonic: \"({.p.} o [:r:]) \\<parallel> [:r':] = {.p.} o [:r \\<sqinter> r':]\"\n  by (cut_tac p = p and p' = \\<top> and r = r and r' = r' in fusion_spec, simp add: assert_true_skip)\n\ndefinition Fusion :: \"('c \\<Rightarrow> (('a \\<Rightarrow> bool) \\<Rightarrow> ('b \\<Rightarrow> bool))) \\<Rightarrow> (('a \\<Rightarrow> bool) \\<Rightarrow> ('b \\<Rightarrow> bool))\" where\n   \"Fusion S q x = (\\<exists> (p::'c \\<Rightarrow> 'a \\<Rightarrow> bool) . (INF c . p c) \\<le> q \\<and> (\\<forall> c . (S c) (p c) x))\"\n\n\nlemma Fusion_spec: \"Fusion (\\<lambda> n . {.p n.} \\<circ> [:r n:]) = ({.INFIMUM UNIV p.} \\<circ> [:INFIMUM UNIV r:])\"\n  apply (simp add: fun_eq_iff Fusion_def assert_def demonic_def le_fun_def)\n  apply safe\n  apply blast\n  apply blast\n  by (rule_tac x = \"\\<lambda> x y . r x xa y\" in exI, auto)\n  \nlemma Fusion_demonic: \"Fusion (\\<lambda> n . [:r n:]) = [:INF n . r n:]\"\n  apply (cut_tac r = r and p = \\<top> in Fusion_spec)\n  by (simp add: assert_true_skip)\n\nlemma Fusion_refinement: \"(\\<And> i . S i \\<le> T i) \\<Longrightarrow> Fusion S \\<le> Fusion T\"\n  apply (simp add: le_fun_def Fusion_def, safe)\n  by (rule_tac x = p in exI, auto)\n\nlemma mono_fusion[simp]: \"mono (S \\<parallel> T)\"\n  apply (auto simp add: mono_def fusion_def)\n  using order_trans by auto\n    \nlemma mono_Fusion: \"mono (Fusion S)\"\n  by (simp add: mono_def Fusion_def le_fun_def, auto)\n\ndefinition \"prod_pred A B = (\\<lambda>(a, b). A a \\<and> B b)\"\ndefinition Prod :: \"(('a \\<Rightarrow> bool) \\<Rightarrow> ('b \\<Rightarrow> bool)) \\<Rightarrow> (('c \\<Rightarrow> bool) \\<Rightarrow> ('d \\<Rightarrow> bool)) \\<Rightarrow> (('a \\<times> 'c \\<Rightarrow> bool) \\<Rightarrow> ('b \\<times> 'd \\<Rightarrow> bool))\"\n   (infixr \"**\" 70)\n  where\n  \"(S ** T) q = (\\<lambda> (x, y) . \\<exists> p p' . prod_pred p p' \\<le> q \\<and> S p x \\<and> T p' y)\" \n\nlemma mono_prod[simp]: \"mono (S ** T)\"\n  by (auto simp add: mono_def Prod_def)\n\nlemma Prod_spec: \"({.p.} o [:r:]) ** ({.p'.} o [:r':]) = {.x,y . p x \\<and> p' y.} o [:x, y \\<leadsto> u, v . r x u \\<and> r' y v:]\"\n  apply (simp add: Prod_def fun_eq_iff prod_pred_def demonic_def assert_def le_fun_def)\n  apply safe\n  apply metis\n  by metis\n\nlemma Prod_demonic: \"[:r:] ** [:r':] = [:x, y \\<leadsto> u, v . r x u \\<and> r' y v:]\"\n  apply (simp add: Prod_def fun_eq_iff prod_pred_def demonic_def le_fun_def)\n  apply safe\n  apply metis\n  by metis\n\nlemma Prod_spec_Skip: \"({.p.} o [:r:]) ** Skip = {.x,y . p x.} o [:x, y \\<leadsto> u, v . r x u \\<and> v = y:]\"\n  apply (cut_tac p = p and r = r and p' = \\<top> and r' = \"\\<lambda> (x::'b) y . x = y\" in Prod_spec)\n  apply auto\n  apply (subgoal_tac \"(\\<lambda>(x::'c, y::'b) (u::'a, v::'b). r x u \\<and> y = v)\n     = (\\<lambda>(x::'c, y::'b) (u::'a, v::'b). r x u \\<and> v = y)\")\n  by (auto simp add: fun_eq_iff assert_true_skip demonic_eq_skip)\n\nlemma Prod_Skip_spec: \"Skip ** ({.p.} o [:r:]) = {.x,y . p y.} o [:x, y \\<leadsto> u, v . x = u \\<and> r y v:]\"\n  apply (cut_tac p = \\<top> and r = \"\\<lambda> (x::'a) y . x = y\" and p' = p and r' = r in Prod_spec)\n  by (auto simp add:assert_true_skip demonic_eq_skip)\n\n lemma Prod_skip_demonic: \"Skip ** [:r:] = [:x, y \\<leadsto> u, v . x = u \\<and> r y v:]\"\n  by (cut_tac r = \"(=)\" and r' = r in Prod_demonic, simp add: demonic_eq_skip)    \n\n lemma Prod_demonic_skip: \"[:r:] ** Skip = [:x, y \\<leadsto> u, v . r x u \\<and>  y = v:]\"\n  by (cut_tac r' = \"(=)\" and r = r in Prod_demonic, simp add: demonic_eq_skip)\n\nlemma Prod_spec_demonic: \"({.p.} o [:r:]) **  [:r':] = {.x, y . p x.} o [:x, y \\<leadsto> u, v . r x u \\<and> r' y v:]\"\n  by (cut_tac p = p and p' = \\<top> and r = r and r' = r' in Prod_spec, simp add: assert_true_skip)\n\nlemma Prod_demonic_spec: \"[:r:] ** ({.p.} o [:r':]) = {.x, y . p y.} o [:x, y \\<leadsto> u, v . r x u \\<and> r' y v:]\"\n  by (cut_tac p = \\<top> and p' = p and r = r and r' = r' in Prod_spec, simp add: assert_true_skip)\n\nlemma pair_eq_demonic_skip: \"[: \\<lambda>(x, y) (u, v). x = u \\<and> v = y :] = Skip\"\n  by (simp add: fun_eq_iff demonic_def le_fun_def assert_def)\n\nlemma Prod_assert_skip: \"{.p.} ** Skip = {.x,y . p x.}\"\n  apply (cut_tac p = p and  r = \"(=)\" in Prod_spec_Skip)\n  by (simp add: demonic_eq_skip pair_eq_demonic_skip)\n\nlemma Prod_skip_assert: \"Skip ** {.p.} = {.x,y . p y.}\"\n  apply (cut_tac p = p and  r = \"(=)\" in Prod_Skip_spec)\n  by (simp add: demonic_eq_skip demonic_pair_skip)\n    \nlemma fusion_comute: \"S \\<parallel> T = T \\<parallel> S\"\n  by (simp add: fusion_def fun_eq_iff, metis inf_commute)\n\nlemma fusion_mono1: \"S \\<le> S' \\<Longrightarrow> S \\<parallel> T \\<le> S' \\<parallel> T\"\n  by (auto simp add: le_fun_def fusion_def)\n\nlemma prod_mono1: \"S \\<le> S' \\<Longrightarrow> S ** T \\<le> S' ** T\"\n  by (auto simp add: Prod_def le_fun_def)\n\nlemma prod_mono2: \"S \\<le> S' \\<Longrightarrow> T ** S \\<le> T ** S'\"\n  by (auto simp add: Prod_def le_fun_def)\n\nlemma Prod_fusion: \"S ** T = ([:x,y \\<leadsto> x' . x = x':] o S o [:x \\<leadsto> x', y . x = x':]) \\<parallel> ([:x, y \\<leadsto> y' . y = y':] o T o [:y \\<leadsto> x, y' . y = y':])\"\nproof (simp add: fun_eq_iff Prod_def prod_pred_def fusion_def demonic_def le_fun_def, safe)\n  fix x::\"'a \\<times> 'b \\<Rightarrow> bool\" fix a :: 'c fix b::'d fix p::\"'a \\<Rightarrow> bool\" fix p' :: \"'b \\<Rightarrow> bool\"\n  assume [simp]: \"\\<forall>a b. p a \\<and> p' b \\<longrightarrow> x (a, b)\"\n  assume [simp]: \"S p a\"\n  assume [simp]: \"T p' b\"\n  have [simp]: \"[:x\\<leadsto>(x', y).x = x':] (\\<lambda>x. p (fst x)) = p\"\n    by (simp add: fun_eq_iff demonic_def, auto)\n  have [simp]: \"[:y\\<leadsto>(x, ya).y = ya:] (\\<lambda>x. p' (snd x)) = p'\"\n    by (simp add: fun_eq_iff demonic_def, auto)\n  show \"\\<exists>p p'. (\\<forall>a b. p (a, b) \\<and> p' (a, b) \\<longrightarrow> x (a, b)) \\<and> S ([:x\\<leadsto>(x', y).x = x':] p) a \\<and> T ([:y\\<leadsto>(x, ya).y = ya:] p') b\"\n    apply (rule_tac x = \"\\<lambda> x . p (fst x)\" in exI)\n    apply (rule_tac x = \"\\<lambda> x . p' (snd x)\" in exI)\n    by simp\nnext\n  fix x::\"'a \\<times> 'b \\<Rightarrow> bool\" fix a :: 'c fix b::'d fix p::\"'a \\<times> 'b \\<Rightarrow> bool\" fix p' :: \"'a \\<times> 'b \\<Rightarrow> bool\"\n  assume [simp]: \"  \\<forall>a b. p (a, b) \\<and> p' (a, b) \\<longrightarrow> x (a, b)\"\n  assume [simp]: \"S ([:x\\<leadsto>(x', y).x = x':] p) a\"\n  assume [simp]: \" T ([:y\\<leadsto>(x, ya).y = ya:] p') b\"\n  have [simp]: \"(\\<lambda>a. \\<forall>b. p (a, b)) = [:x\\<leadsto>(x', y).x = x':] p\"\n    by (simp add: fun_eq_iff demonic_def, auto)\n  have [simp]: \"(\\<lambda>b. \\<forall>a. p' (a, b)) = [:y\\<leadsto>(x, ya).y = ya:] p'\"\n    by (simp add: fun_eq_iff demonic_def, auto)\n  show \"\\<exists>p p'. (\\<forall>a b. p a \\<and> p' b \\<longrightarrow> x (a, b)) \\<and> S p a \\<and> T p' b\"  \n    apply (rule_tac x = \"\\<lambda> a . \\<forall> b . p (a, b)\" in exI)\n    apply (rule_tac x = \"\\<lambda> b . \\<forall> a . p' (a, b)\" in exI)\n    by simp\nqed\n\nlemma refin_comp_right: \"(S::'a \\<Rightarrow> 'b::order) \\<le> T \\<Longrightarrow> S o X \\<le> T o X\"\n  by (simp add: le_fun_def)\n\nlemma refin_comp_left: \"mono X \\<Longrightarrow> (S::'a \\<Rightarrow> 'b::order) \\<le> T \\<Longrightarrow> X o S  \\<le> X o T\"\n  apply (simp add: le_fun_def)\n  by (simp add: monoD)\n\nlemma mono_angelic[simp]: \"mono {:r:}\"\n  apply (simp add: angelic_def mono_def le_fun_def)\n  by (metis bot.extremum_uniqueI inf.absorb1 inf_le1 inf_left_commute)\n\nlemma [simp]: \"Skip ** Magic = Magic\"\n  by (auto simp add: fun_eq_iff demonic_def le_fun_def top_fun_def Magic_def Prod_def prod_pred_def Skip_def)\n\nlemma [simp]: \"S ** Fail = Fail\"\n  by (auto simp add: fun_eq_iff Prod_def prod_pred_def Fail_def)\n\nlemma [simp]: \"Fail ** S = Fail\"\n  by (auto simp add: fun_eq_iff  Prod_def prod_pred_def Fail_def)\n\nlemma demonic_conj: \"[:(r::'a \\<Rightarrow> 'b \\<Rightarrow> bool):] o (S \\<sqinter> S') = ([:r:] o S) \\<sqinter> ([:r:] o  S')\"\n  by (simp add: fun_eq_iff demonic_def product_def Skip_def prod_pred_def le_fun_def assert_def, auto)\n\n lemma demonic_assume: \"[:r:] o [.p.] = [:x \\<leadsto> y . r x y \\<and> p y:]\"\n    by (simp add: fun_eq_iff demonic_def product_def Skip_def le_fun_def assume_def, auto)\n  \nlemma assume_demonic: \"[.p.] o [:r:] = [:x \\<leadsto> y . p x \\<and> r x y:]\"\n  by (simp add: fun_eq_iff demonic_def product_def Skip_def le_fun_def assume_def, auto)\n\nlemma [simp]: \"(Fail::'a::boolean_algebra) \\<le> S\"\n  by (simp add: Fail_def)\n\nlemma prod_skip_skip[simp]: \"Skip ** Skip = Skip\"\n  apply (cut_tac r = \"(=)\" and r' = \"(=)\" in Prod_demonic)\n  by (simp add: demonic_eq_skip demonic_pair_skip)\n\nlemma fusion_prod: \"S \\<parallel> T = [:x \\<leadsto> y, z . x = y \\<and> x = z:] o Prod S T o [:y , z \\<leadsto> x . y = x \\<and> z = x:]\"\n  by (simp add: fun_eq_iff fusion_def Prod_def demonic_def prod_pred_def le_fun_def)\n\nlemma [simp]: \"prec S = \\<top> \\<Longrightarrow> prec T = \\<top> \\<Longrightarrow> prec (S ** T) = \\<top>\"\n  apply (simp add: prec_def fail_def Prod_def fun_eq_iff, safe)\n  apply (rule_tac x = \\<top> in exI, simp)\n  by (rule_tac x = \\<top> in exI, simp)\n\nlemma prec_skip[simp]: \"prec Skip = (\\<top>::'a\\<Rightarrow>bool)\"\n  by (simp add: fun_eq_iff prec_def fail_def Skip_def)\n\nlemma [simp]: \"prec S = \\<top> \\<Longrightarrow> prec T = \\<top> \\<Longrightarrow> prec (S \\<parallel> T) = \\<top>\"\n  by (simp add: fusion_prod)\n\nsubsection{*Functional Update*}\n  \n\ndefinition update :: \"('a \\<Rightarrow> 'b) \\<Rightarrow> ('b \\<Rightarrow> bool) \\<Rightarrow> 'a \\<Rightarrow> bool\" (\"[-_-]\") where\n    \"[-f-] = [:x \\<leadsto> y . y = f x:]\"\nsyntax\n    \"_update\" :: \"patterns \\<Rightarrow> tuple_args \\<Rightarrow> logic\"    (\"(1[- _ \\<leadsto> _ -])\")\ntranslations\n    \"_update x (_tuple_args f F)\" == \"CONST update ((_abs x (_tuple f F)))\"\n    \"_update x (_tuple_arg F)\" == \"CONST update (_abs x F)\"\n    \nlemma update_o_def: \"[-f o g-] = [-x \\<leadsto> f (g x)-]\"\n  by (simp add: o_def)\n    \nlemma update_simp: \"[-f-] q = (\\<lambda> x . q (f x))\"\n  by (simp add: demonic_def update_def fun_eq_iff, auto)\n    \n\nlemma update_assert_comp: \"[-f-] o {.p.} = {.p o f.} o [-f-]\"\n  by (simp add: fun_eq_iff update_def demonic_def assert_def le_fun_def)\n\n\n\nlemma update_demonic_comp: \"[-f-] o [:r:] = [:x \\<leadsto> y . r (f x) y:]\"\n  by (simp add: fun_eq_iff update_def demonic_def le_fun_def)    \n    \nlemma demonic_update_comp: \"[:r:] o [-f-] = [:x \\<leadsto> y . \\<exists> z . r x z \\<and> y = f z:]\"\n  by (simp add: fun_eq_iff update_def demonic_def le_fun_def, auto)    \n\nlemma comp_update_demonic: \"S o [-f-] o [:r:] = S o [:x \\<leadsto> y . r (f x) y:]\"\n  by (simp add: comp_assoc update_demonic_comp)\n\nlemma comp_demonic_update: \"S o [:r:] o [-f-] = S o [:x \\<leadsto> y . \\<exists> z . r x z \\<and> y = f z:]\"\n  by (simp add: comp_assoc demonic_update_comp)\n        \nlemma convert: \"(\\<lambda> x y . (S::('a \\<Rightarrow> bool) \\<Rightarrow> ('b \\<Rightarrow> bool)) x (f y)) = [-f-] o S\"\n  by (simp add: fun_eq_iff update_def demonic_def le_fun_def)\n\nlemma prod_update: \"[-f-] ** [-g-] = [-x, y \\<leadsto> f x, g y -]\"\n  apply (simp add: update_def Prod_demonic)\n  apply (rule_tac f = demonic in  HOL.arg_cong)\n  by fast\n\nlemma prod_update_skip: \"[-f-] ** Skip = [- x, y \\<leadsto> f x, y-]\"\n  apply (simp add: update_def Prod_demonic_skip)\n  apply (rule_tac f = demonic in  HOL.arg_cong)\n  by fast\n\nlemma prod_skip_update: \"Skip ** [-f-] = [- x, y \\<leadsto> x, f y-]\"\n  apply (simp add: update_def Prod_skip_demonic)\n  apply (rule_tac f = demonic in  HOL.arg_cong)\n  by fast\n\nlemma prod_assert_update_skip: \"({.p.} o [-f-]) ** Skip = {.x,y . p x.} o [- x, y \\<leadsto> f x, y-]\"\n  apply (simp add: update_def Prod_spec_Skip)\n  apply (rule_tac f = \"(o)  {. \\<lambda>(x, y). p x .}\" in  HOL.arg_cong)\n  apply (rule_tac f = \"demonic\" in  HOL.arg_cong)\n  by fast\n\nlemma prod_skip_assert_update: \"Skip ** ({.p.} o [-f-]) = {.x,y . p y.} o [-\\<lambda> (x, y) . (x, f y)-]\"\n  apply (simp add: update_def Prod_Skip_spec)\n  apply (rule_tac f = \"(o)  {. \\<lambda>(x, y). p y .}\" in  HOL.arg_cong)\n  apply (rule_tac f = \"demonic\" in  HOL.arg_cong)\n  by fast\n\nlemma prod_assert_update: \"({.p.} o [-f-]) ** ({.p'.} o [-f'-]) = {.x,y . p x \\<and> p' y.} o [-\\<lambda> (x, y) . (f x, f' y)-]\"\n  apply (simp add: update_def Prod_spec)\n  apply (rule_tac f = \"(o)  {. \\<lambda>(x, y). p x \\<and> p' y .}\" in  HOL.arg_cong)\n  apply (rule_tac f = \"demonic\" in  HOL.arg_cong)\n  by (simp add: fun_eq_iff)\n\nlemma update_id_Skip: \"[-id-] = Skip\"\n  by (simp add: update_def fun_eq_iff demonic_def le_fun_def)\n\nlemma prod_assert_assert_update: \"{.p.} ** ({.p'.} o [-f-]) = {.x,y . p x \\<and> p' y.} o [- x, y \\<leadsto> x, f y-]\"\n  apply (cut_tac p = p and p' = p' and f = id and f' = f in prod_assert_update)\n  by (simp add: update_id_Skip)\n\nlemma prod_assert_update_assert: \"({.p.} o [-f-])** {.p'.} = {.x,y . p x \\<and> p' y.} o [- x, y \\<leadsto> f x, y-]\"\n  apply (cut_tac p = p and p' = p' and f = f and f' = id in prod_assert_update)\n  by (simp add: update_id_Skip)\n\nlemma prod_update_assert_update: \"[-f-] ** ({.p.} o [-f'-]) = {.x,y . p y.} o [-x, y \\<leadsto> f x, f' y-]\"\n  apply (cut_tac p = \\<top> and p' = p and f = f and f' = f' in prod_assert_update)\n  by (simp add: assert_true_skip)\n\nlemma prod_assert_update_update: \"({.p.} o [-f-])** [-f'-] = {.x,y . p x .} o [- x, y \\<leadsto> f x, f' y-]\"\n  apply (cut_tac p = p and p' = \\<top> and f = f and f' = f' in prod_assert_update)\n  by (simp add: assert_true_skip)\n\nlemma Fail_assert_update: \"Fail = {.\\<bottom>.} o [- (Eps \\<top>) -]\"\n  by (simp add: fun_eq_iff Fail_def assert_def)\n\nlemma fail_assert_update: \"\\<bottom> = {.\\<bottom>.} o [- (Eps \\<top>) -]\"\n  by (simp add: fun_eq_iff assert_def)\n\nlemma update_fail: \"[-f-] o \\<bottom> = \\<bottom>\"\n  by (simp add: update_def demonic_def fun_eq_iff le_fun_def)\n\nlemma fail_assert_demonic: \"\\<bottom> = {.\\<bottom>.} o [:\\<bottom>:]\"\n  by (simp add: fun_eq_iff assert_def)\n\nlemma false_update_fail: \"{.\\<lambda>x. False.} o [-f-] = \\<bottom>\"\n  by (simp add: fail_assert_update fun_eq_iff assert_def)\n\nlemma comp_update_update: \"S \\<circ> [-f-] \\<circ> [-f'-] = S \\<circ> [- f' o f -]\"\n  by (simp add: comp_assoc update_comp)\n\nlemma comp_update_assert: \"S \\<circ> [-f-] \\<circ> {.p.} = S \\<circ> {.p o f.} o [-f-]\"\n  by (simp add: comp_assoc update_assert_comp)\n\nlemma prod_fail: \"\\<bottom> ** S = \\<bottom>\"\n  by (simp add: fun_eq_iff Prod_def prod_pred_def)\n\nlemma fail_prod: \"S ** \\<bottom> = \\<bottom>\"\n  by (simp add: fun_eq_iff Prod_def prod_pred_def)\n\nlemma assert_fail: \"{.p::'a::boolean_algebra.} o \\<bottom> = \\<bottom>\"\n  by (simp add: assert_def fun_eq_iff)\n\nlemma angelic_assert: \"{:r:} o {.p.} = {:x \\<leadsto> y . r x y \\<and> p y:}\"\n  by (simp add: fun_eq_iff angelic_def demonic_def assert_def)\n\nlemma Prod_Skip_angelic_demonic: \"Skip ** ({:r:} o [:r':]) = {:s,x \\<leadsto> s',y . r x y \\<and> s' = s:} o [:s,x \\<leadsto> s',y . r' x y \\<and> s' = s:]\"\n  apply (simp add: fun_eq_iff Prod_def Skip_def angelic_def demonic_def le_fun_def prod_pred_def)\n  apply safe\n  apply metis\n  apply (rule_tac x = \"\\<lambda> x . x = a\" in exI)\n  apply (rule_tac x = \"\\<lambda> b . x (a, b)\" in exI)\n  by metis\n\nlemma Prod_angelic_demonic_Skip: \"({:r:} o [:r':]) ** Skip = {:x, u \\<leadsto> y, u' . r x y \\<and> u = u':} o  [:x, u \\<leadsto> y, u' . r' x y \\<and> u = u':]\"\n  apply (simp add: fun_eq_iff demonic_def angelic_def le_fun_def Skip_def Prod_def prod_pred_def, auto)\n  apply (rule_tac x = \"\\<lambda> a . r' aa a\" in exI)\n  apply (rule_tac x = \"\\<lambda> a . a = b\" in exI, simp_all)\n  by metis\n\nlemma prec_rel_eq: \"p = p' \\<Longrightarrow> r = r' \\<Longrightarrow> {.p.} o [:r:] = {.p'.} o [:r':]\"\n  by simp\n\nlemma prec_rel_le: \"p \\<le> p' \\<Longrightarrow> (\\<And> x . p x \\<Longrightarrow> r' x \\<le> r x) \\<Longrightarrow> {.p.} o [:r:] \\<le> {.p'.} o [:r':]\"\n  apply (simp add: le_fun_def demonic_def assert_def, auto)\n  by (rule_tac y = \"r xa\" in order_trans, simp_all)\n\n\nlemma assert_update_eq: \"({.p.} o [-f-] = {.p'.} o [-f'-]) = (p = p' \\<and> (\\<forall> x. p x \\<longrightarrow> f x = f' x))\"\n  apply (simp add: fun_eq_iff assert_def demonic_def update_def le_fun_def)\n  by auto\n\nlemma update_eq: \"([-f-] = [-f'-]) = (f = f')\"\n  apply (simp add: fun_eq_iff assert_def demonic_def update_def le_fun_def)\n  by auto\n\nlemma spec_eq_iff: \n  shows spec_eq_iff_1: \"p = p' \\<Longrightarrow> f = f' \\<Longrightarrow> {.p.} o [-f-] = {.p'.} o [-f'-]\" \n  and spec_eq_iff_2: \"f = f' \\<Longrightarrow> [-f-] = [-f'-]\"\n  and spec_eq_iff_3: \"p = (\\<lambda> x . True) \\<Longrightarrow> f = f' \\<Longrightarrow> {.p.} o [-f-] = [-f'-]\"\n  and spec_eq_iff_4: \"p = (\\<lambda> x . True) \\<Longrightarrow> f = f' \\<Longrightarrow> [-f-] = {.p.} o [-f'-]\"\n  by (simp_all add: assert_true_skip_a)\n\nlemma spec_eq_iff_a: \n  shows\"(\\<And> x . p x = p' x) \\<Longrightarrow> (\\<And> x . f x = f' x) \\<Longrightarrow> {.p.} o [-f-] = {.p'.} o [-f'-]\" \n  and \"(\\<And> x . f x = f' x) \\<Longrightarrow> [-f-] = [-f'-]\"\n  and \"(\\<And> x . p x) \\<Longrightarrow> (\\<And> x . f x = f' x) \\<Longrightarrow> {.p.} o [-f-] = [-f'-]\"\n  and \"(\\<And> x . p x) \\<Longrightarrow>(\\<And> x . f x = f' x) \\<Longrightarrow> [-f-] = {.p.} o [-f'-]\"\n  apply (subgoal_tac \"p = p' \\<and> f = f'\")\n  apply simp\n  apply (simp add: fun_eq_iff)\n  apply (subgoal_tac \"f = f'\")\n  apply simp\n  apply (simp add: fun_eq_iff)\n\n  apply (subgoal_tac \"p = (\\<lambda> x. True) \\<and> f = f'\")\n  apply (simp add: assert_true_skip_a)\n  apply (simp add: fun_eq_iff)\n  apply (subgoal_tac \"p = (\\<lambda> x. True) \\<and> f = f'\")\n  apply (simp add: assert_true_skip_a)\n  by (simp add: fun_eq_iff)\n\nlemma spec_eq_iff_prec: \"p = p' \\<Longrightarrow> (\\<And> x . p x \\<Longrightarrow> f x = f' x) \\<Longrightarrow> {.p.} o [-f-] = {.p'.} o [-f'-]\"\n  by (simp add: update_def fun_eq_iff assert_def demonic_def le_fun_def, auto)\n\n\nlemma trs_prod: \"trs r ** trs r' = trs (\\<lambda> (x,x') (y,y') . r x y \\<and> r' x' y')\"\n  apply (simp add: trs_def)\n  apply (simp add: Prod_spec)\n  apply (subgoal_tac \"(\\<lambda> (x, y).inpt r x \\<and> inpt r' y) = ( inpt (\\<lambda>(x, x') (y, y'). r x y \\<and> r' x' y'))\")\n  apply (simp_all)\n  by (simp add: fun_eq_iff inpt_def)\n\nlemma sconjunctiveE: \"sconjunctive S \\<Longrightarrow> (\\<exists> p r . S = {. p .} o [: r ::'a \\<Rightarrow> 'b \\<Rightarrow> bool:])\"\n  by (drule sconjunctive_spec, blast)\n\nlemma sconjunctive_prod [simp]: \"sconjunctive S \\<Longrightarrow> sconjunctive S' \\<Longrightarrow> sconjunctive (S ** S')\"\n  apply (drule sconjunctiveE)\n  apply (drule sconjunctiveE)\n  apply safe\n  by (simp add: Prod_spec)\n\nlemma nonmagic_prod [simp]: \"non_magic S \\<Longrightarrow> non_magic S' \\<Longrightarrow> non_magic (S ** S')\"\n  apply (simp add: non_magic_def)\n  apply (simp add: Prod_def)\n  apply (simp add: fun_eq_iff prod_pred_def le_fun_def, safe)\n  apply (case_tac \"p = \\<bottom>\", simp_all)\n  apply (simp add: fun_eq_iff)\n  apply (case_tac \"p' = \\<bottom>\", simp_all)\n  by (simp add: fun_eq_iff)\n\nlemma non_magic_comp [simp]: \"non_magic S \\<Longrightarrow> non_magic S' \\<Longrightarrow> non_magic (S o S')\"\n  by (simp add: non_magic_def)\n\nlemma implementable_pred [simp]: \"implementable S \\<Longrightarrow> implementable S' \\<Longrightarrow> implementable (S ** S')\"\n  by (simp add: implementable_def)\n\nlemma implementable_comp[simp]: \"implementable S \\<Longrightarrow> implementable S' \\<Longrightarrow> implementable (S o S')\"\n  by (simp add: implementable_def)\n\nlemma nonmagic_assert: \"non_magic {.p::'a::boolean_algebra.}\"\n  by (simp add: non_magic_def assert_def)\n    \nsubsection {*Control Statements*}\n  \ndefinition \"if_stm p S T = ([.p.] o S) \\<sqinter> ([.-p.] o T)\"\n  \ndefinition \"while_stm p S = lfp (\\<lambda> X . if_stm p (S o X) Skip)\"\n  \ndefinition \"Sup_less x (w::'b::wellorder) = Sup {(x v)::'a::complete_lattice | v . v < w}\"\n  \nlemma Sup_less_upper: \"v < w \\<Longrightarrow> P v \\<le> Sup_less P w\"\n  by (simp add: Sup_less_def, rule Sup_upper, blast)\n\nlemma Sup_less_least: \"(\\<And> v . v < w \\<Longrightarrow> P v \\<le> Q) \\<Longrightarrow> Sup_less P w \\<le> Q\"\n  by (simp add: Sup_less_def, rule Sup_least, blast)\n\ntheorem fp_wf_induction:\n  \"f x  = x \\<Longrightarrow> mono f \\<Longrightarrow> (\\<forall> w . (y w) \\<le> f (Sup_less y w)) \\<Longrightarrow> Sup (range y) \\<le> x\"\n  apply (rule Sup_least)\n  apply (simp add: image_def, safe, simp)\n  apply (rule less_induct, simp_all)\n  apply (rule_tac y = \"f (Sup_less y xa)\" in order_trans, simp)\n  apply (drule_tac x = \"Sup_less y xa\" and y = \"x\" in monoD)\n  by (simp add: Sup_less_least, auto)\n\ntheorem lfp_wf_induction: \"mono f \\<Longrightarrow> (\\<forall> w . (p w) \\<le> f (Sup_less p w)) \\<Longrightarrow> Sup (range p) \\<le> lfp f\"\n  apply (rule fp_wf_induction, simp_all)\n  by (drule lfp_unfold, simp)\n \ntheorem lfp_wf_induction_a: \"mono f \\<Longrightarrow> (\\<forall> w . (p w) \\<le> f (Sup_less p w)) \\<Longrightarrow> (SUP a. p a) \\<le> lfp f\"\n  apply (rule fp_wf_induction, simp_all)\n  by (drule lfp_unfold, simp)\n\ntheorem lfp_wf_induction_b: \"mono f \\<Longrightarrow> (\\<forall> w . (p w) \\<le> f (Sup_less p w)) \\<Longrightarrow> S \\<le> (SUP a. p a) \\<Longrightarrow> S \\<le> lfp f\"\n  apply (rule_tac y = \"(SUP a. p a)\" in order_trans)\n   apply simp\n    by (rule lfp_wf_induction, simp_all)\n\nlemma [simp]: \"mono S \\<Longrightarrow> mono (\\<lambda>X. if_stm b (S \\<circ> X) T)\"\n  apply (simp add: if_stm_def mono_def le_fun_def)\n  apply auto\n  by (metis (no_types, lifting) assume_def dual_order.trans inf.coboundedI1 le_supI sup_ge1 sup_ge2)\n  \n    \ndefinition  \"mono_mono F = (mono F \\<and> (\\<forall> f . mono f \\<longrightarrow> mono (F f)))\"\n\ntheorem lfp_mono [simp]:\n  \"mono_mono F \\<Longrightarrow> mono (lfp F)\"\n  apply (simp add: mono_mono_def)\n  apply (rule_tac f=\"F\" and P = \"mono\" in lfp_ordinal_induct)\n  apply (simp_all add: mono_def)\n  apply (intro allI impI SUP_least)\n  apply (rule_tac y = \"f y\" in order_trans)\n  apply (auto intro: SUP_upper)\n  done\n    \nlemma if_mono[simp]: \"mono S \\<Longrightarrow> mono T \\<Longrightarrow> mono (if_stm b S T)\"\n  by (simp add: if_stm_def)\n\nsubsection{*Hoare Total Correctness Rules*}\n\ndefinition \"Hoare p S q = (p \\<le> S q)\"\n\ndefinition \"post_fun (p::'a::order) q = (if p \\<le> q then \\<top> else \\<bottom>)\"\n\nlemma post_mono [simp]: \"mono (post_fun p :: (_::{order_bot,order_top}))\"\n   apply (simp add: post_fun_def  mono_def, safe)\n   apply (subgoal_tac \"p \\<le> y\", simp)\n   by (rule_tac y = x in order_trans, simp_all)\n\nlemma post_refin [simp]: \"mono S \\<Longrightarrow> ((S p)::'a::bounded_lattice) \\<sqinter> (post_fun p) x \\<le> S x\"\n  apply (simp add: le_fun_def post_fun_def, safe)\n  by (rule_tac f = S in monoD, simp_all)\n\n\n\n  lemma Sup_range_comp: \"(Sup (range p)) o S = Sup (range (\\<lambda> w . ((p w) o S)))\"\n    by (simp add: fun_eq_iff)\n\n \nlemma Sup_less_comp: \"(Sup_less P) w o S = Sup_less (\\<lambda> w . ((P w) o S)) w\"\n  apply (simp add: Sup_less_def fun_eq_iff, safe)\n  apply (rule antisym)\n   apply (rule SUP_least, safe, simp)\n    apply (rule_tac i = \"\\<lambda> x . f (S x)\" in SUP_upper2, blast, simp)\n   apply (rule SUP_least, safe, simp)\n  by (rule_tac i = \"P v\" in SUP_upper2, auto)\n\n  lemma assert_Sup: \"{.Sup (X::'a::complete_distrib_lattice set).} = Sup (assert ` X)\"\n    by (simp add: fun_eq_iff assert_def Sup_inf)\n\nlemma Sup_less_assert: \"Sup_less (\\<lambda>w. {. (p w)::'a::complete_distrib_lattice .}) w = {.Sup_less p w.}\"\n  apply (simp add: Sup_less_def assert_Sup image_def)\n  by (simp add: setcompr_eq_image)\n\n\nlemma [simp]: \"Sup_less (\\<lambda>n x. t x = n) n = (\\<lambda> x . (t x < n))\"\n  by (simp add: Sup_less_def, auto)\n    \nlemma [simp]: \"Sup_less (\\<lambda>n. {.x. t x = n.} \\<circ> S) n = {.x. t x < n.} \\<circ> S\"\n  apply (simp add: Sup_less_comp [THEN sym])\n  by (simp add: Sup_less_assert)\n\nlemma [simp]: \"(SUP a. {.x .t x = a.} \\<circ> S) = S\"\n  by (simp add: fun_eq_iff assert_def)\n\n \ntheorem hoare_fixpoint:\n  \"mono_mono F \\<Longrightarrow> \n     (\\<forall> f w . mono f \\<longrightarrow> (Hoare (Sup_less p w) f y \\<longrightarrow> Hoare ((p w)::'a \\<Rightarrow> bool) (F f) y)) \\<Longrightarrow> Hoare(Sup (range p)) (lfp F) y\"\n  apply (simp add: mono_mono_def hoare_refinement_post assert_Sup_range Sup_range_comp del: )\n  apply (rule lfp_wf_induction)\n  apply auto\n  apply (simp add: Sup_less_comp [THEN sym])\n  apply (simp add: Sup_less_assert)\n  apply (drule_tac x = \"{. Sup_less p w .} \\<circ> post_fun y\" in spec, safe)\n  apply simp_all\n  apply (drule_tac x = \"w\" in spec, safe)\n  by (simp add: le_fun_def)\n\n\n  theorem hoare_sequential:\n    \"mono S \\<Longrightarrow> (Hoare p (S o T) r) = ( (\\<exists> q. Hoare p S q \\<and> Hoare q T r))\"\n    by (metis (no_types) Hoare_def monoD o_def order_refl order_trans)\n\n  theorem hoare_choice:\n    \"Hoare  p (S \\<sqinter> T) q = (Hoare p S q \\<and> Hoare p T q)\"\n    by (simp_all add: Hoare_def inf_fun_def)\n\n  theorem hoare_assume:\n    \"(Hoare P [.R.] Q) = (P \\<sqinter> R \\<le> Q)\"\n    apply (simp add: Hoare_def assume_def)\n    apply safe\n    apply (case_tac \"(inf P R) \\<le> (inf (sup (- R) Q) R)\")\n    apply (simp add: inf_sup_distrib2)\n    apply (simp add: le_infI1)\n    apply (case_tac \"(sup (-R) (inf P R)) \\<le> sup (- R) Q\")\n    apply (simp add: sup_inf_distrib1)\n    by (simp add: le_supI2) \n\n  lemma hoare_if: \"mono S \\<Longrightarrow> mono T \\<Longrightarrow> Hoare (p \\<sqinter> b) S q \\<Longrightarrow> Hoare (p \\<sqinter> -b) T q \\<Longrightarrow> Hoare p (if_stm b S T) q\"\n    apply (simp add: if_stm_def)\n    apply (simp add: hoare_choice, safe)\n    apply (simp_all add:  hoare_sequential)\n    apply (rule_tac x = \" (p \\<sqinter> b)\" in exI, simp)\n    apply (simp add: hoare_assume) \n    apply (rule_tac x = \" (p \\<sqinter> -b)\" in exI, simp)\n    by (simp add: hoare_assume)\n      \nlemma [simp]: \"mono x \\<Longrightarrow> mono_mono (\\<lambda>X . if_stm b (x \\<circ> X) Skip)\"\n  by (simp add: mono_mono_def)\n\n\n  lemma hoare_while:\n      \"mono x \\<Longrightarrow> (\\<forall> w . Hoare ((p w) \\<sqinter> b) x (Sup_less p w)) \\<Longrightarrow>  Hoare  (Sup (range p)) (while_stm b x) ((Sup (range p)) \\<sqinter> -b)\"\n    apply (cut_tac y = \" ((SUP x. p x) \\<sqinter> - b)\" and p = p and F = \"\\<lambda> X . if_stm b (x o X) Skip\" in hoare_fixpoint, simp_all)\n      apply safe\n    apply (rule hoare_if, simp_all)\n    apply (simp_all add:  hoare_sequential)\n    apply (rule_tac x = \" (Sup_less p w)\" in exI, simp_all)\n    apply (simp add: Hoare_def Skip_def, auto)\n    by (simp add: while_stm_def)\n\n  lemma hoare_prec_post: \"mono S \\<Longrightarrow> p \\<le> p' \\<Longrightarrow> q' \\<le> q \\<Longrightarrow> Hoare p' S q' \\<Longrightarrow> Hoare p S q\"\n    apply (simp add: Hoare_def)\n    apply (rule_tac y = p' in order_trans, simp_all)\n    apply (rule_tac y = \"S q'\" in order_trans, simp_all)\n    using monoD by auto\n\n  lemma [simp]: \"mono x \\<Longrightarrow>  mono (while_stm b x)\"\n    by (simp add: while_stm_def)\n\n  lemma hoare_while_a:\n    \"mono x \\<Longrightarrow> (\\<forall> w . Hoare ((p w) \\<sqinter> b) x (Sup_less p w)) \\<Longrightarrow> p' \\<le>  (Sup (range p)) \\<Longrightarrow> ((Sup (range p)) \\<sqinter> -b) \\<le> q \n      \\<Longrightarrow>  Hoare p' (while_stm b x) q\"\n    apply (rule hoare_prec_post, simp_all)\n    by (drule hoare_while, simp_all)\n\n  lemma hoare_update: \"p \\<le> q o f \\<Longrightarrow> Hoare p [-f-] q\"\n    by (simp add: Hoare_def update_def demonic_def le_fun_def)\n\n  lemma hoare_demonic: \"(\\<And> x y . p x \\<Longrightarrow> r x y \\<Longrightarrow> q y) \\<Longrightarrow> Hoare p [:r:] q\"\n    by (simp add: Hoare_def demonic_def le_fun_def)\n      \nlemma refinement_hoare: \"S \\<le> T \\<Longrightarrow> Hoare (p::'a::order) S (q) \\<Longrightarrow> Hoare p T q\"\n  apply (simp add: Hoare_def le_fun_def)\n  by (rule_tac y = \"S q\" in order_trans, simp_all)\n\nlemma refinement_hoare_iff: \"(S \\<le> T) = (\\<forall> p q . Hoare (p::'a::order) S (q) \\<longrightarrow> Hoare p T q)\"\n  apply safe\n   apply (rule refinement_hoare, simp_all)\n  by (simp add: Hoare_def le_fun_def)\n    \nsubsection{*Data Refinement*}\n  \nlemma data_refinement: \"mono S' \\<Longrightarrow> (\\<forall> x a . \\<exists> u . R x a u) \\<Longrightarrow>\n    {:x, a \\<leadsto> x', u . x = x' \\<and> R x a u:} o S \\<le> S' o {:y, b \\<leadsto> y', v . y = y' \\<and> R' y b v:} \\<Longrightarrow> \n    [:x \\<leadsto> x', u . x = x':] o S o [:y, v \\<leadsto> y' . y = y' :] \n    \\<le> [:x \\<leadsto> x', a . x = x':] o S' o [:y, b \\<leadsto> y' . y = y' :]\"\nproof (simp add: fun_eq_iff demonic_def le_fun_def, safe)\n  fix x xa b\n  assume A: \"\\<forall>x a. \\<exists>u. R x a u\"\n  assume B: \"\\<forall>b. S ([: \\<lambda>(y, v). (=) y :] x) (xa, b)\"\n  assume \"\\<forall>x a b. {:(x, a) \\<leadsto> (x', u).x = x' \\<and> R x a u:} (S x) (a, b) \\<longrightarrow>\n                      S' ({:(y, b) \\<leadsto> (y', v).y = y' \\<and> R' y b v:} x) (a, b)\"\n      \n  from this have C: \"{:(x, a) \\<leadsto> (x', u).x = x' \\<and> R x a u:} (S ([: \\<lambda>(y, v). (=) y :] x)) (xa, b) \\<Longrightarrow>\n                      S' ({:(y, b) \\<leadsto> (y', v).y = y' \\<and> R' y b v:} ([: \\<lambda>(y, v). (=) y :] x)) (xa, b)\"\n        \n    by simp\n  from A obtain u where \"R xa b u\"\n    by blast\n    \n  from this and B have \"{:(x, a) \\<leadsto> (x', u).x = x' \\<and> R x a u:} (S ([: \\<lambda>(y, v). (=) y :] x)) (xa, b)\"\n    apply (simp add: angelic_def fun_eq_iff)\n    by blast\n      \n  from this and C have D: \"S' ({:(y, b) \\<leadsto> (y', v).y = y' \\<and> R' y b v:} ([: \\<lambda>(y, v). (=) y :] x)) (xa, b)\"\n    by simp\n      \n  have [simp]: \"\\<And> s t . {:(y, b) \\<leadsto> (y', v).y = y' \\<and> R' y b v:} ([: \\<lambda>(y, v). (=) y :] x) (s,t) \n    \\<Longrightarrow> [: \\<lambda>(y, b). (=) y :] x (s, t)\"\n    by (simp add: le_fun_def demonic_def angelic_def fun_eq_iff)\n        \n  assume \"mono S'\"\n  from this have \"S' ({:(y, b) \\<leadsto> (y', v).y = y' \\<and> R' y b v:} ([: \\<lambda>(y, v). (=) y :] x)) \\<le> S' ([: \\<lambda>(y, b). (=) y :] x)\"\n    by (rule monoD, simp add: le_fun_def)\n    \n  from D and this show \"S' ([: \\<lambda>(y, b). (=) y :] x) (xa, b)\"\n    by (simp add: le_fun_def)\nqed\n\nlemma mono_update[simp]: \"mono [- f -]\"\n  by (simp add: update_def)\n  \nend\n", "meta": {"author": "hbd-translation", "repo": "TranslateHBD", "sha": "c040d1ce04e4eb163832adea9a7f66566519ffd9", "save_path": "github-repos/isabelle/hbd-translation-TranslateHBD", "path": "github-repos/isabelle/hbd-translation-TranslateHBD/TranslateHBD-c040d1ce04e4eb163832adea9a7f66566519ffd9/Refinement.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256313782276, "lm_q2_score": 0.837619961306541, "lm_q1q2_score": 0.7051299527818855}}
{"text": "(* Author: Alexander Maletzky *)\n\nsection \\<open>Integer Binomial Coefficients\\<close>\n\ntheory Binomial_Int\n  imports Complex_Main\nbegin\n\nlemma upper_le_binomial:\n  assumes \"0 < k\" and \"k < n\"\n  shows \"n \\<le> n choose k\"\nproof -\n  from assms have \"1 \\<le> n\" by simp\n  define k' where \"k' = (if n div 2 \\<le> k then k else n - k)\"\n  from assms have 1: \"k' \\<le> n - 1\" and 2: \"n div 2 \\<le> k'\" by (auto simp: k'_def)\n  from assms(2) have \"k \\<le> n\" by simp\n  have \"n choose k = n choose k'\" by (simp add: k'_def binomial_symmetric[OF \\<open>k \\<le> n\\<close>])\n  have \"n = n choose 1\" by (simp only: choose_one)\n  also from \\<open>1 \\<le> n\\<close> have \"\\<dots> = n choose (n - 1)\" by (rule binomial_symmetric)\n  also from 1 2 have \"\\<dots> \\<le> n choose k'\" by (rule binomial_antimono) simp\n  also have \"\\<dots> = n choose k\" by (simp add: k'_def binomial_symmetric[OF \\<open>k \\<le> n\\<close>])\n  finally show ?thesis .\nqed\n\ntext \\<open>Restore original sort constraints:\\<close>\nsetup \\<open>Sign.add_const_constraint (@{const_name gbinomial}, SOME @{typ \"'a::{semidom_divide,semiring_char_0} \\<Rightarrow> nat \\<Rightarrow> 'a\"})\\<close>\n\nlemma gbinomial_0_left: \"0 gchoose k = (if k = 0 then 1 else 0)\"\n  by (cases k) simp_all\n\nlemma gbinomial_eq_0_int:\n  assumes \"n < k\"\n  shows \"(int n) gchoose k = 0\"\nproof -\n  have \"\\<exists>a\\<in>{0..<k}. int n - int a = 0\"\n  proof\n    show \"int n - int n = 0\" by simp\n  next\n    from assms show \"n \\<in> {0..<k}\" by simp\n  qed\n  with finite_atLeastLessThan have eq: \"prod (\\<lambda>i. int n - int i) {0..<k} = 0\" by (rule prod_zero)\n  show ?thesis by (simp add: gbinomial_prod_rev eq)\nqed\n\ncorollary gbinomial_eq_0: \"0 \\<le> a \\<Longrightarrow> a < int k \\<Longrightarrow> a gchoose k = 0\"\n  by (metis nat_eq_iff2 nat_less_iff gbinomial_eq_0_int)\n\nlemma int_binomial: \"int (n choose k) = (int n) gchoose k\"\nproof (cases \"k \\<le> n\")\n  case True\n  from refl have eq: \"(\\<Prod>i = 0..<k. int (n - i)) = (\\<Prod>i = 0..<k. int n - int i)\"\n  proof (rule prod.cong)\n    fix i\n    assume \"i \\<in> {0..<k}\"\n    with True show \"int (n - i) = int n - int i\" by simp\n  qed\n  show ?thesis\n    by (simp add: gbinomial_binomial[symmetric] gbinomial_prod_rev zdiv_int eq)\nnext\n  case False\n  thus ?thesis by (simp add: gbinomial_eq_0_int)\nqed\n\nlemma falling_fact_pochhammer: \"prod (\\<lambda>i. a - int i) {0..<k} = (- 1) ^ k * pochhammer (- a) k\"\nproof -\n  have eq: \"z ^ Suc n * prod f {0..n} = prod (\\<lambda>x. z * f x) {0..n}\" for z::int and n f\n    by (induct n) (simp_all add: ac_simps)\n  show ?thesis\n  proof (cases k)\n    case 0\n    thus ?thesis by (simp add: pochhammer_minus)\n  next\n    case (Suc n)\n    thus ?thesis\n      by (simp only: pochhammer_prod atLeastLessThanSuc_atLeastAtMost\n          prod.atLeast_Suc_atMost_Suc_shift eq flip: power_mult_distrib) (simp add: of_nat_diff)\n  qed\nqed\n\nlemma falling_fact_pochhammer': \"prod (\\<lambda>i. a - int i) {0..<k} = pochhammer (a - int k + 1) k\"\n  by (simp add: falling_fact_pochhammer pochhammer_minus')\n\nlemma gbinomial_int_pochhammer: \"(a::int) gchoose k = (- 1) ^ k * pochhammer (- a) k div fact k\"\n  by (simp only: gbinomial_prod_rev falling_fact_pochhammer)\n\nlemma gbinomial_int_pochhammer': \"a gchoose k = pochhammer (a - int k + 1) k div fact k\"\n  by (simp only: gbinomial_prod_rev falling_fact_pochhammer')\n\nlemma fact_dvd_pochhammer: \"fact k dvd pochhammer (a::int) k\"\nproof -\n  have dvd: \"y \\<noteq> 0 \\<Longrightarrow> ((of_int (x div y))::'a::field_char_0) = of_int x / of_int y \\<Longrightarrow> y dvd x\"\n    for x y :: int\n    by (smt dvd_triv_left mult.commute nonzero_eq_divide_eq of_int_eq_0_iff of_int_eq_iff of_int_mult)\n  show ?thesis\n  proof (cases \"0 < a\")\n    case True\n    moreover define n where \"n = nat (a - 1) + k\"\n    ultimately have a: \"a = int n - int k + 1\" by simp\n    from fact_nonzero show ?thesis unfolding a\n    proof (rule dvd)\n      have \"of_int (pochhammer (int n - int k + 1) k div fact k) = (of_int (int n gchoose k)::rat)\"\n        by (simp only: gbinomial_int_pochhammer')\n      also have \"\\<dots> = of_int (int (n choose k))\" by (simp only: int_binomial)\n      also have \"\\<dots> = of_nat (n choose k)\" by simp\n      also have \"\\<dots> = (of_nat n) gchoose k\" by (fact binomial_gbinomial)\n      also have \"\\<dots> = pochhammer (of_nat n - of_nat k + 1) k / fact k\"\n        by (fact gbinomial_pochhammer')\n      also have \"\\<dots> = pochhammer (of_int (int n - int k + 1)) k / fact k\" by simp\n      also have \"\\<dots> = (of_int (pochhammer (int n - int k + 1) k)) / (of_int (fact k))\"\n        by (simp only: of_int_fact pochhammer_of_int)\n      finally show \"of_int (pochhammer (int n - int k + 1) k div fact k) =\n                      of_int (pochhammer (int n - int k + 1) k) / rat_of_int (fact k)\" .\n    qed\n  next\n    case False\n    moreover define n where \"n = nat (- a)\"\n    ultimately have a: \"a = - int n\" by simp\n    from fact_nonzero have \"fact k dvd (-1)^k * pochhammer (- int n) k\"\n    proof (rule dvd)\n      have \"of_int ((-1)^k * pochhammer (- int n) k div fact k) = (of_int (int n gchoose k)::rat)\"\n        by (simp only: gbinomial_int_pochhammer)\n      also have \"\\<dots> = of_int (int (n choose k))\" by (simp only: int_binomial)\n      also have \"\\<dots> = of_nat (n choose k)\" by simp\n      also have \"\\<dots> = (of_nat n) gchoose k\" by (fact binomial_gbinomial)\n      also have \"\\<dots> = (-1)^k * pochhammer (- of_nat n) k / fact k\"\n        by (fact gbinomial_pochhammer)\n      also have \"\\<dots> = (-1)^k * pochhammer (of_int (- int n)) k / fact k\" by simp\n      also have \"\\<dots> = (-1)^k * (of_int (pochhammer (- int n) k)) / (of_int (fact k))\"\n        by (simp only: of_int_fact pochhammer_of_int)\n      also have \"\\<dots> = (of_int ((-1)^k * pochhammer (- int n) k)) / (of_int (fact k))\" by simp\n      finally show \"of_int ((- 1) ^ k * pochhammer (- int n) k div fact k) =\n                    of_int ((- 1) ^ k * pochhammer (- int n) k) / rat_of_int (fact k)\" .\n    qed\n    thus ?thesis unfolding a by (metis dvdI dvd_mult_unit_iff' minus_one_mult_self)\n  qed\nqed\n\nlemma gbinomial_int_negated_upper: \"(a gchoose k) = (-1) ^ k * ((int k - a - 1) gchoose k)\"\n  by (simp add: gbinomial_int_pochhammer pochhammer_minus algebra_simps fact_dvd_pochhammer div_mult_swap)\n\nlemma gbinomial_int_mult_fact: \"fact k * (a gchoose k) = (\\<Prod>i = 0..<k. a - int i)\"\n  by (simp only: gbinomial_int_pochhammer' fact_dvd_pochhammer dvd_mult_div_cancel falling_fact_pochhammer')\n\ncorollary gbinomial_int_mult_fact': \"(a gchoose k) * fact k = (\\<Prod>i = 0..<k. a - int i)\"\n  using gbinomial_int_mult_fact[of k a] by (simp add: ac_simps)\n\nlemma gbinomial_int_binomial:\n  \"a gchoose k = (if 0 \\<le> a then int ((nat a) choose k) else (-1::int)^k * int ((k + (nat (- a)) - 1) choose k))\"\n  by (auto simp: int_binomial gbinomial_int_negated_upper[of a] int_ops(6))\n\ncorollary gbinomial_nneg: \"0 \\<le> a \\<Longrightarrow> a gchoose k = int ((nat a) choose k)\"\n  by (simp add: gbinomial_int_binomial)\n\ncorollary gbinomial_neg: \"a < 0 \\<Longrightarrow> a gchoose k = (-1::int)^k * int ((k + (nat (- a)) - 1) choose k)\"\n  by (simp add: gbinomial_int_binomial)\n\nlemma of_int_gbinomial: \"of_int (a gchoose k) = (of_int a :: 'a::field_char_0) gchoose k\"\nproof -\n  have of_int_div: \"y dvd x \\<Longrightarrow> of_int (x div y) = of_int x / (of_int y :: 'a)\" for x y :: int by auto\n  show ?thesis\n    by (simp add: gbinomial_int_pochhammer' gbinomial_pochhammer' of_int_div fact_dvd_pochhammer\n        pochhammer_of_int[symmetric])\nqed\n\nlemma uminus_one_gbinomial [simp]: \"(- 1::int) gchoose k = (- 1) ^ k\"\n  by (simp add: gbinomial_int_binomial)\n\nlemma gbinomial_int_Suc_Suc: \"(x + 1::int) gchoose (Suc k) = (x gchoose k) + (x gchoose (Suc k))\"\nproof (rule linorder_cases)\n  assume 1: \"x + 1 < 0\"\n  hence 2: \"x < 0\" by simp\n  then obtain n where 3: \"nat (- x) = Suc n\" using not0_implies_Suc by fastforce\n  hence 4: \"nat (- x - 1) = n\" by simp\n  show ?thesis\n  proof (cases k)\n    case 0\n    show ?thesis by (simp add: \\<open>k = 0\\<close>)\n  next\n    case (Suc k')\n    from 1 2 3 4 show ?thesis by (simp add: \\<open>k = Suc k'\\<close> gbinomial_int_binomial int_distrib(2))\n  qed\nnext\n  assume \"x + 1 = 0\"\n  hence \"x = - 1\" by simp\n  thus ?thesis by simp\nnext\n  assume \"0 < x + 1\"\n  hence \"0 \\<le> x + 1\" and \"0 \\<le> x\" and \"nat (x + 1) = Suc (nat x)\" by simp_all\n  thus ?thesis by (simp add: gbinomial_int_binomial)\nqed\n\ncorollary plus_Suc_gbinomial:\n  \"(x + (1 + int k)) gchoose (Suc k) = ((x + int k) gchoose k) + ((x + int k) gchoose (Suc k))\"\n    (is \"?l = ?r\")\nproof -\n  have \"?l = (x + int k + 1) gchoose (Suc k)\" by (simp only: ac_simps)\n  also have \"\\<dots> = ?r\" by (fact gbinomial_int_Suc_Suc)\n  finally show ?thesis .\nqed\n\nlemma gbinomial_int_n_n [simp]: \"(int n) gchoose n = 1\"\nproof (induct n)\n  case 0\n  show ?case by simp\nnext\n  case (Suc n)\n  have \"int (Suc n) gchoose Suc n = (int n + 1) gchoose Suc n\" by (simp add: add.commute)\n  also have \"\\<dots> = (int n gchoose n) + (int n gchoose (Suc n))\" by (fact gbinomial_int_Suc_Suc)\n  finally show ?case by (simp add: Suc gbinomial_eq_0)\nqed\n\nlemma gbinomial_int_Suc_n [simp]: \"(1 + int n) gchoose n = 1 + int n\"\nproof (induct n)\n  case 0\n  show ?case by simp\nnext\n  case (Suc n)\n  have \"1 + int (Suc n) gchoose Suc n = (1 + int n) + 1 gchoose Suc n\" by simp\n  also have \"\\<dots> = (1 + int n gchoose n) + (1 + int n gchoose (Suc n))\" by (fact gbinomial_int_Suc_Suc)\n  also have \"\\<dots> = 1 + int n + (int (Suc n) gchoose (Suc n))\" by (simp add: Suc)\n  also have \"\\<dots> = 1 + int (Suc n)\" by (simp only: gbinomial_int_n_n)\n  finally show ?case .\nqed\n\nlemma zbinomial_eq_0_iff [simp]: \"a gchoose k = 0 \\<longleftrightarrow> (0 \\<le> a \\<and> a < int k)\"\nproof\n  assume a: \"a gchoose k = 0\"\n  have 1: \"b < int k\" if \"b gchoose k = 0\" for b\n  proof (rule ccontr)\n    assume \"\\<not> b < int k\"\n    hence \"0 \\<le> b\" and \"k \\<le> nat b\" by simp_all\n    from this(1) have \"int ((nat b) choose k) = b gchoose k\" by (simp add: gbinomial_int_binomial)\n    also have \"\\<dots> = 0\" by (fact that)\n    finally show False using \\<open>k \\<le> nat b\\<close> by simp\n  qed\n  show \"0 \\<le> a \\<and> a < int k\"\n  proof\n    show \"0 \\<le> a\"\n    proof (rule ccontr)\n      assume \"\\<not> 0 \\<le> a\"\n      hence \"(-1) ^ k * ((int k - a - 1) gchoose k) = a gchoose k\"\n        by (simp add: gbinomial_int_negated_upper[of a])\n      also have \"\\<dots> = 0\" by (fact a)\n      finally have \"(int k - a - 1) gchoose k = 0\" by simp\n      hence \"int k - a - 1 < int k\" by (rule 1)\n      with \\<open>\\<not> 0 \\<le> a\\<close> show False by simp\n    qed\n  next\n    from a show \"a < int k\" by (rule 1)\n  qed\nqed (auto intro: gbinomial_eq_0)\n\nsubsection \\<open>Sums\\<close>\n\nlemma gchoose_rising_sum_nat: \"(\\<Sum>j\\<le>n. int j + int k gchoose k) = (int n + int k + 1) gchoose (Suc k)\"\nproof -\n  have \"(\\<Sum>j\\<le>n. int j + int k gchoose k) = int (\\<Sum>j\\<le>n. k + j choose k)\"\n    by (simp add: int_binomial add.commute)\n  also have \"(\\<Sum>j\\<le>n. k + j choose k) = (k + n + 1) choose (k + 1)\" by (fact choose_rising_sum(1))\n  also have \"int \\<dots> = (int n + int k + 1) gchoose (Suc k)\"\n    by (simp add: int_binomial ac_simps del: binomial_Suc_Suc)\n  finally show ?thesis .\nqed\n\nlemma gchoose_rising_sum:\n  assumes \"0 \\<le> n\"   \\<comment>\\<open>Necessary condition.\\<close>\n  shows \"(\\<Sum>j=0..n. j + int k gchoose k) = (n + int k + 1) gchoose (Suc k)\"\nproof -\n  from _ refl have \"(\\<Sum>j=0..n. j + int k gchoose k) = (\\<Sum>j\\<in>int ` {0..nat n}. j + int k gchoose k)\"\n  proof (rule sum.cong)\n    from assms show \"{0..n} = int ` {0..nat n}\" by (simp add: image_int_atLeastAtMost)\n  qed\n  also have \"\\<dots> = (\\<Sum>j\\<le>nat n. int j + int k gchoose k)\" by (simp add: sum.reindex atMost_atLeast0)\n  also have \"\\<dots> = (int (nat n) + int k + 1) gchoose (Suc k)\" by (fact gchoose_rising_sum_nat)\n  also from assms have \"\\<dots> = (n + int k + 1) gchoose (Suc k)\" by (simp add: add.assoc add.commute)\n  finally show ?thesis .\nqed\n\nsubsection \\<open>Inequalities\\<close>\n\nlemma binomial_mono:\n  assumes \"m \\<le> n\"\n  shows \"m choose k \\<le> n choose k\"\nproof -\n  define l where \"l = n - m\"\n  with assms have n: \"n = m + l\" by simp\n  have \"m choose k \\<le> (m + l) choose k\"\n  proof (induct l)\n    case 0\n    show ?case by simp\n  next\n    case *: (Suc l)\n    show ?case\n    proof (cases k)\n      case 0\n      thus ?thesis by simp\n    next\n      case k: (Suc k0)\n      note *\n      also have \"m + l choose k \\<le> m + l choose k + (m + l choose k0)\" by simp\n      also have \"\\<dots> = m + Suc l choose k\" by (simp add: k)\n      finally show ?thesis .\n    qed\n  qed\n  thus ?thesis by (simp only: n)\nqed\n\nlemma binomial_plus_le:\n  assumes \"0 < k\"\n  shows \"(m choose k) + (n choose k) \\<le> (m + n) choose k\"\nproof -\n  define k0 where \"k0 = k - 1\"\n  with assms have k: \"k = Suc k0\" by simp\n  show ?thesis unfolding k\n  proof (induct n)\n    case 0\n    show ?case by simp\n  next\n    case (Suc n)\n    have \"m choose Suc k0 + (Suc n choose Suc k0) = m choose Suc k0 + (n choose Suc k0) + (n choose k0)\"\n      by (simp only: binomial_Suc_Suc)\n    also from Suc have \"\\<dots> \\<le> (m + n) choose Suc k0 + ((m + n) choose k0)\"\n    proof (rule add_mono)\n      have \"n \\<le> m + n\" by simp\n      thus \"n choose k0 \\<le> m + n choose k0\" by (rule binomial_mono)\n    qed\n    also have \"\\<dots> = m + Suc n choose Suc k0\" by simp\n    finally show ?case .\n  qed\nqed\n\n\n\nlemma gbinomial_int_nonneg:\n  assumes \"0 \\<le> (x::int)\"\n  shows \"0 \\<le> x gchoose k\"\nproof -\n  have \"0 \\<le> int (nat x choose k)\" by simp\n  also from assms have \"\\<dots> = x gchoose k\" by (simp add: int_binomial)\n  finally show ?thesis .\nqed\n\nlemma gbinomial_int_mono:\n  assumes \"0 \\<le> x\" and \"x \\<le> (y::int)\"\n  shows \"x gchoose k \\<le> y gchoose k\"\nproof -\n  from assms have \"nat x \\<le> nat y\" by simp\n  hence \"nat x choose k \\<le> nat y choose k\" by (rule binomial_mono)\n  hence \"int (nat x choose k) \\<le> int (nat y choose k)\" by (simp only: zle_int)\n  hence \"int (nat x) gchoose k \\<le> int (nat y) gchoose k\" by (simp only: int_binomial)\n  with assms show ?thesis by simp\nqed\n\nlemma gbinomial_int_plus_le:\n  assumes \"0 < k\" and \"0 \\<le> x\" and \"0 \\<le> (y::int)\"\n  shows \"(x gchoose k) + (y gchoose k) \\<le> (x + y) gchoose k\"\nproof -\n  from assms(1) have \"nat x choose k + (nat y choose k) \\<le> nat x + nat y choose k\"\n    by (rule binomial_plus_le)\n  hence \"int (nat x choose k + (nat y choose k)) \\<le> int (nat x + nat y choose k)\"\n    by (simp only: zle_int)\n  hence \"int (nat x) gchoose k + (int (nat y) gchoose k) \\<le> int (nat x) + int (nat y) gchoose k\"\n    by (simp only: int_plus int_binomial)\n  with assms(2, 3) show ?thesis by simp\nqed\n\nlemma binomial_int_ineq_1:\n  assumes \"0 \\<le> x\" and \"0 \\<le> (y::int)\"\n  shows \"2 * (x + y gchoose k) \\<le> x gchoose k + ((x + 2 * y) gchoose k)\"\nproof -\n  from binomial_ineq_1[of \"nat x\" \"nat y\" k]\n  have \"int (2 * (nat x + nat y choose k)) \\<le> int (nat x choose k + (nat x + 2 * nat y choose k))\"\n    by (simp only: zle_int)\n  hence \"2 * (int (nat x) + int (nat y) gchoose k) \\<le> int (nat x) gchoose k + (int (nat x) + 2 * int (nat y) gchoose k)\"\n    by (simp only: int_binomial int_plus int_ops(7)) simp\n  with assms show ?thesis by simp\nqed\n\ncorollary binomial_int_ineq_2:\n  assumes \"0 \\<le> y\" and \"y \\<le> (x::int)\"\n  shows \"2 * (x gchoose k) \\<le> x - y gchoose k + (x + y gchoose k)\"\nproof -\n  from assms(2) have \"0 \\<le> x - y\" by simp\n  hence \"2 * ((x - y) + y gchoose k) \\<le> x - y gchoose k + ((x - y + 2 * y) gchoose k)\"\n    using assms(1) by (rule binomial_int_ineq_1)\n  thus ?thesis by smt\nqed\n\ncorollary binomial_int_ineq_3:\n  assumes \"0 \\<le> y\" and \"y \\<le> 2 * (x::int)\"\n  shows \"2 * (x gchoose k) \\<le> y gchoose k + (2 * x - y gchoose k)\"\nproof (cases \"y \\<le> x\")\n  case True\n  hence \"0 \\<le> x - y\" by simp\n  moreover from assms(1) have \"x - y \\<le> x\" by simp\n  ultimately have \"2 * (x gchoose k) \\<le> x - (x - y) gchoose k + (x + (x - y) gchoose k)\"\n    by (rule binomial_int_ineq_2)\n  thus ?thesis by simp\nnext\n  case False\n  hence \"0 \\<le> y - x\" by simp\n  moreover from assms(2) have \"y - x \\<le> x\" by simp\n  ultimately have \"2 * (x gchoose k) \\<le> x - (y - x) gchoose k + (x + (y - x) gchoose k)\"\n    by (rule binomial_int_ineq_2)\n  thus ?thesis by simp\nqed\n\nsubsection \\<open>Backward Difference Operator\\<close>\n\ndefinition bw_diff :: \"('a \\<Rightarrow> 'a) \\<Rightarrow> 'a \\<Rightarrow> 'a::{ab_group_add,one}\"\n  where \"bw_diff f x = f x - f (x - 1)\"\n\nlemma bw_diff_const [simp]: \"bw_diff (\\<lambda>_. c) = (\\<lambda>_. 0)\"\n  by (rule ext) (simp add: bw_diff_def)\n\nlemma bw_diff_id [simp]: \"bw_diff (\\<lambda>x. x) = (\\<lambda>_. 1)\"\n  by (rule ext) (simp add: bw_diff_def)\n\nlemma bw_diff_plus [simp]: \"bw_diff (\\<lambda>x. f x + g x) = (\\<lambda>x. bw_diff f x + bw_diff g x)\"\n  by (rule ext) (simp add: bw_diff_def)\n\nlemma bw_diff_uminus [simp]: \"bw_diff (\\<lambda>x. - f x) = (\\<lambda>x. - bw_diff f x)\"\n  by (rule ext) (simp add: bw_diff_def)\n\nlemma bw_diff_minus [simp]: \"bw_diff (\\<lambda>x. f x - g x) = (\\<lambda>x. bw_diff f x - bw_diff g x)\"\n  by (rule ext) (simp add: bw_diff_def)\n\nlemma bw_diff_const_pow: \"(bw_diff ^^ k) (\\<lambda>_. c) = (if k = 0 then \\<lambda>_. c else (\\<lambda>_. 0))\"\n  by (induct k, simp_all)\n\nlemma bw_diff_id_pow:\n  \"(bw_diff ^^ k) (\\<lambda>x. x) = (if k = 0 then (\\<lambda>x. x) else if k = 1 then (\\<lambda>_. 1) else (\\<lambda>_. 0))\"\n  by (induct k, simp_all)\n\nlemma bw_diff_plus_pow [simp]:\n  \"(bw_diff ^^ k) (\\<lambda>x. f x + g x) = (\\<lambda>x. (bw_diff ^^ k) f x + (bw_diff ^^ k) g x)\"\n  by (induct k, simp_all)\n\nlemma bw_diff_uminus_pow [simp]: \"(bw_diff ^^ k) (\\<lambda>x. - f x) = (\\<lambda>x. - (bw_diff ^^ k) f x)\"\n  by (induct k, simp_all)\n\nlemma bw_diff_minus_pow [simp]:\n  \"(bw_diff ^^ k) (\\<lambda>x. f x - g x) = (\\<lambda>x. (bw_diff ^^ k) f x - (bw_diff ^^ k) g x)\"\n  by (induct k, simp_all)\n\nlemma bw_diff_sum_pow [simp]:\n  \"(bw_diff ^^ k) (\\<lambda>x. (\\<Sum>i\\<in>I. f i x)) = (\\<lambda>x. (\\<Sum>i\\<in>I. (bw_diff ^^ k) (f i) x))\"\n  by (induct I rule: infinite_finite_induct, simp_all add: bw_diff_const_pow)\n\nlemma bw_diff_gbinomial:\n  assumes \"0 < k\"\n  shows \"bw_diff (\\<lambda>x::int. (x + n) gchoose k) = (\\<lambda>x. (x + n - 1) gchoose (k - 1))\"\nproof (rule ext)\n  fix x::int\n  from assms have eq: \"Suc (k - Suc 0) = k\" by simp\n  have \"x + n gchoose k = (x + n - 1) + 1 gchoose (Suc (k - 1))\" by (simp add: eq)\n  also have \"\\<dots> = (x + n - 1) gchoose (k - 1) + ((x + n - 1) gchoose (Suc (k - 1)))\"\n    by (fact gbinomial_int_Suc_Suc)\n  finally show \"bw_diff (\\<lambda>x. x + n gchoose k) x = x + n - 1 gchoose (k - 1)\"\n    by (simp add: eq bw_diff_def algebra_simps)\nqed\n\nlemma bw_diff_gbinomial_pow:\n  \"(bw_diff ^^ l) (\\<lambda>x::int. (x + n) gchoose k) =\n      (if l \\<le> k then (\\<lambda>x. (x + n - int l) gchoose (k - l)) else (\\<lambda>_. 0))\"\nproof -\n  have *: \"l0 \\<le> k \\<Longrightarrow> (bw_diff ^^ l0) (\\<lambda>x::int. (x + n) gchoose k) = (\\<lambda>x. (x + n - int l0) gchoose (k - l0))\"\n    for l0\n  proof (induct l0)\n    case 0\n    show ?case by simp\n  next\n    case (Suc l0)\n    from Suc.prems have \"0 < k - l0\" and \"l0 \\<le> k\" by simp_all\n    from this(2) have eq: \"(bw_diff ^^ l0) (\\<lambda>x. x + n gchoose k) = (\\<lambda>x. x + n - int l0 gchoose (k - l0))\"\n      by (rule Suc.hyps)\n    have \"(bw_diff ^^ Suc l0) (\\<lambda>x. x + n gchoose k) = bw_diff (\\<lambda>x. x + (n - int l0) gchoose (k - l0))\"\n      by (simp add: eq algebra_simps)\n    also from \\<open>0 < k - l0\\<close> have \"\\<dots> = (\\<lambda>x. (x + (n - int l0) - 1) gchoose (k - l0 - 1))\"\n      by (rule bw_diff_gbinomial)\n    also have \"\\<dots> = (\\<lambda>x. x + n - int (Suc l0) gchoose (k - Suc l0))\" by (simp add: algebra_simps)\n    finally show ?case .\n  qed\n  show ?thesis\n  proof (simp add: * split: if_split, intro impI)\n    assume \"\\<not> l \\<le> k\"\n    hence \"(l - k) + k = l\" and \"l - k \\<noteq> 0\" by simp_all\n    hence \"(bw_diff ^^ l) (\\<lambda>x. x + n gchoose k) = (bw_diff ^^ ((l - k) + k)) (\\<lambda>x. x + n gchoose k)\"\n      by (simp only:)\n    also have \"\\<dots> = (bw_diff ^^ (l - k)) (\\<lambda>_. 1)\" by (simp add: * funpow_add)\n    also from \\<open>l - k \\<noteq> 0\\<close> have \"\\<dots> = (\\<lambda>_. 0)\" by (simp add: bw_diff_const_pow)\n    finally show \"(bw_diff ^^ l) (\\<lambda>x. x + n gchoose k) = (\\<lambda>_. 0)\" .\n  qed\nqed\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/Groebner_Macaulay/Binomial_Int.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951064805861, "lm_q2_score": 0.8354835309589074, "lm_q1q2_score": 0.7050604633213432}}
{"text": "(*  Title:      HOL/Library/Inner_Product.thy\n    Author:     Brian Huffman\n*)\n\nsection {* Inner Product Spaces and the Gradient Derivative *}\n\ntheory Inner_Product\nimports \"~~/src/HOL/Complex_Main\"\nbegin\n\nsubsection {* Real inner product spaces *}\n\ntext {*\n  Temporarily relax type constraints for @{term \"open\"},\n  @{term dist}, and @{term norm}.\n*}\n\nsetup {* Sign.add_const_constraint\n  (@{const_name \"open\"}, SOME @{typ \"'a::open set \\<Rightarrow> bool\"}) *}\n\nsetup {* Sign.add_const_constraint\n  (@{const_name dist}, SOME @{typ \"'a::dist \\<Rightarrow> 'a \\<Rightarrow> real\"}) *}\n\nsetup {* Sign.add_const_constraint\n  (@{const_name norm}, SOME @{typ \"'a::norm \\<Rightarrow> real\"}) *}\n\nclass real_inner = real_vector + sgn_div_norm + dist_norm + open_dist +\n  fixes inner :: \"'a \\<Rightarrow> 'a \\<Rightarrow> real\"\n  assumes inner_commute: \"inner x y = inner y x\"\n  and inner_add_left: \"inner (x + y) z = inner x z + inner y z\"\n  and inner_scaleR_left [simp]: \"inner (scaleR r x) y = r * (inner x y)\"\n  and inner_ge_zero [simp]: \"0 \\<le> inner x x\"\n  and inner_eq_zero_iff [simp]: \"inner x x = 0 \\<longleftrightarrow> x = 0\"\n  and norm_eq_sqrt_inner: \"norm x = sqrt (inner x x)\"\nbegin\n\nlemma inner_zero_left [simp]: \"inner 0 x = 0\"\n  using inner_add_left [of 0 0 x] by simp\n\nlemma inner_minus_left [simp]: \"inner (- x) y = - inner x y\"\n  using inner_add_left [of x \"- x\" y] by simp\n\nlemma inner_diff_left: \"inner (x - y) z = inner x z - inner y z\"\n  using inner_add_left [of x \"- y\" z] by simp\n\nlemma inner_setsum_left: \"inner (\\<Sum>x\\<in>A. f x) y = (\\<Sum>x\\<in>A. inner (f x) y)\"\n  by (cases \"finite A\", induct set: finite, simp_all add: inner_add_left)\n\ntext {* Transfer distributivity rules to right argument. *}\n\nlemma inner_add_right: \"inner x (y + z) = inner x y + inner x z\"\n  using inner_add_left [of y z x] by (simp only: inner_commute)\n\nlemma inner_scaleR_right [simp]: \"inner x (scaleR r y) = r * (inner x y)\"\n  using inner_scaleR_left [of r y x] by (simp only: inner_commute)\n\nlemma inner_zero_right [simp]: \"inner x 0 = 0\"\n  using inner_zero_left [of x] by (simp only: inner_commute)\n\nlemma inner_minus_right [simp]: \"inner x (- y) = - inner x y\"\n  using inner_minus_left [of y x] by (simp only: inner_commute)\n\nlemma inner_diff_right: \"inner x (y - z) = inner x y - inner x z\"\n  using inner_diff_left [of y z x] by (simp only: inner_commute)\n\nlemma inner_setsum_right: \"inner x (\\<Sum>y\\<in>A. f y) = (\\<Sum>y\\<in>A. inner x (f y))\"\n  using inner_setsum_left [of f A x] by (simp only: inner_commute)\n\nlemmas inner_add [algebra_simps] = inner_add_left inner_add_right\nlemmas inner_diff [algebra_simps]  = inner_diff_left inner_diff_right\nlemmas inner_scaleR = inner_scaleR_left inner_scaleR_right\n\ntext {* Legacy theorem names *}\nlemmas inner_left_distrib = inner_add_left\nlemmas inner_right_distrib = inner_add_right\nlemmas inner_distrib = inner_left_distrib inner_right_distrib\n\nlemma inner_gt_zero_iff [simp]: \"0 < inner x x \\<longleftrightarrow> x \\<noteq> 0\"\n  by (simp add: order_less_le)\n\nlemma power2_norm_eq_inner: \"(norm x)\\<^sup>2 = inner x x\"\n  by (simp add: norm_eq_sqrt_inner)\n\n\n\nlemma Cauchy_Schwarz_ineq2:\n  \"\\<bar>inner x y\\<bar> \\<le> norm x * norm y\"\nproof (rule power2_le_imp_le)\n  have \"(inner x y)\\<^sup>2 \\<le> inner x x * inner y y\"\n    using Cauchy_Schwarz_ineq .\n  thus \"\\<bar>inner x y\\<bar>\\<^sup>2 \\<le> (norm x * norm y)\\<^sup>2\"\n    by (simp add: power_mult_distrib power2_norm_eq_inner)\n  show \"0 \\<le> norm x * norm y\"\n    unfolding norm_eq_sqrt_inner\n    by (intro mult_nonneg_nonneg real_sqrt_ge_zero inner_ge_zero)\nqed\n\nlemma norm_cauchy_schwarz: \"inner x y \\<le> norm x * norm y\"\n  using Cauchy_Schwarz_ineq2 [of x y] by auto\n\nsubclass real_normed_vector\nproof\n  fix a :: real and x y :: 'a\n  show \"norm x = 0 \\<longleftrightarrow> x = 0\"\n    unfolding norm_eq_sqrt_inner by simp\n  show \"norm (x + y) \\<le> norm x + norm y\"\n    proof (rule power2_le_imp_le)\n      have \"inner x y \\<le> norm x * norm y\"\n        by (rule norm_cauchy_schwarz)\n      thus \"(norm (x + y))\\<^sup>2 \\<le> (norm x + norm y)\\<^sup>2\"\n        unfolding power2_sum power2_norm_eq_inner\n        by (simp add: inner_add inner_commute)\n      show \"0 \\<le> norm x + norm y\"\n        unfolding norm_eq_sqrt_inner by simp\n    qed\n  have \"sqrt (a\\<^sup>2 * inner x x) = \\<bar>a\\<bar> * sqrt (inner x x)\"\n    by (simp add: real_sqrt_mult_distrib)\n  then show \"norm (a *\\<^sub>R x) = \\<bar>a\\<bar> * norm x\"\n    unfolding norm_eq_sqrt_inner\n    by (simp add: power2_eq_square mult.assoc)\nqed\n\nend\n\ntext {*\n  Re-enable constraints for @{term \"open\"},\n  @{term dist}, and @{term norm}.\n*}\n\nsetup {* Sign.add_const_constraint\n  (@{const_name \"open\"}, SOME @{typ \"'a::topological_space set \\<Rightarrow> bool\"}) *}\n\nsetup {* Sign.add_const_constraint\n  (@{const_name dist}, SOME @{typ \"'a::metric_space \\<Rightarrow> 'a \\<Rightarrow> real\"}) *}\n\nsetup {* Sign.add_const_constraint\n  (@{const_name norm}, SOME @{typ \"'a::real_normed_vector \\<Rightarrow> real\"}) *}\n\nlemma bounded_bilinear_inner:\n  \"bounded_bilinear (inner::'a::real_inner \\<Rightarrow> 'a \\<Rightarrow> real)\"\nproof\n  fix x y z :: 'a and r :: real\n  show \"inner (x + y) z = inner x z + inner y z\"\n    by (rule inner_add_left)\n  show \"inner x (y + z) = inner x y + inner x z\"\n    by (rule inner_add_right)\n  show \"inner (scaleR r x) y = scaleR r (inner x y)\"\n    unfolding real_scaleR_def by (rule inner_scaleR_left)\n  show \"inner x (scaleR r y) = scaleR r (inner x y)\"\n    unfolding real_scaleR_def by (rule inner_scaleR_right)\n  show \"\\<exists>K. \\<forall>x y::'a. norm (inner x y) \\<le> norm x * norm y * K\"\n  proof\n    show \"\\<forall>x y::'a. norm (inner x y) \\<le> norm x * norm y * 1\"\n      by (simp add: Cauchy_Schwarz_ineq2)\n  qed\nqed\n\nlemmas tendsto_inner [tendsto_intros] =\n  bounded_bilinear.tendsto [OF bounded_bilinear_inner]\n\nlemmas isCont_inner [simp] =\n  bounded_bilinear.isCont [OF bounded_bilinear_inner]\n\nlemmas has_derivative_inner [derivative_intros] =\n  bounded_bilinear.FDERIV [OF bounded_bilinear_inner]\n\nlemmas bounded_linear_inner_left =\n  bounded_bilinear.bounded_linear_left [OF bounded_bilinear_inner]\n\nlemmas bounded_linear_inner_right =\n  bounded_bilinear.bounded_linear_right [OF bounded_bilinear_inner]\n\nlemmas has_derivative_inner_right [derivative_intros] =\n  bounded_linear.has_derivative [OF bounded_linear_inner_right]\n\nlemmas has_derivative_inner_left [derivative_intros] =\n  bounded_linear.has_derivative [OF bounded_linear_inner_left]\n\nlemma differentiable_inner [simp]:\n  \"f differentiable (at x within s) \\<Longrightarrow> g differentiable at x within s \\<Longrightarrow> (\\<lambda>x. inner (f x) (g x)) differentiable at x within s\"\n  unfolding differentiable_def by (blast intro: has_derivative_inner)\n\nsubsection {* Class instances *}\n\ninstantiation real :: real_inner\nbegin\n\ndefinition inner_real_def [simp]: \"inner = op *\"\n\ninstance proof\n  fix x y z r :: real\n  show \"inner x y = inner y x\"\n    unfolding inner_real_def by (rule mult.commute)\n  show \"inner (x + y) z = inner x z + inner y z\"\n    unfolding inner_real_def by (rule distrib_right)\n  show \"inner (scaleR r x) y = r * inner x y\"\n    unfolding inner_real_def real_scaleR_def by (rule mult.assoc)\n  show \"0 \\<le> inner x x\"\n    unfolding inner_real_def by simp\n  show \"inner x x = 0 \\<longleftrightarrow> x = 0\"\n    unfolding inner_real_def by simp\n  show \"norm x = sqrt (inner x x)\"\n    unfolding inner_real_def by simp\nqed\n\nend\n\ninstantiation complex :: real_inner\nbegin\n\ndefinition inner_complex_def:\n  \"inner x y = Re x * Re y + Im x * Im y\"\n\ninstance proof\n  fix x y z :: complex and r :: real\n  show \"inner x y = inner y x\"\n    unfolding inner_complex_def by (simp add: mult.commute)\n  show \"inner (x + y) z = inner x z + inner y z\"\n    unfolding inner_complex_def by (simp add: distrib_right)\n  show \"inner (scaleR r x) y = r * inner x y\"\n    unfolding inner_complex_def by (simp add: distrib_left)\n  show \"0 \\<le> inner x x\"\n    unfolding inner_complex_def by simp\n  show \"inner x x = 0 \\<longleftrightarrow> x = 0\"\n    unfolding inner_complex_def\n    by (simp add: add_nonneg_eq_0_iff complex_Re_Im_cancel_iff)\n  show \"norm x = sqrt (inner x x)\"\n    unfolding inner_complex_def complex_norm_def\n    by (simp add: power2_eq_square)\nqed\n\nend\n\nlemma complex_inner_1 [simp]: \"inner 1 x = Re x\"\n  unfolding inner_complex_def by simp\n\nlemma complex_inner_1_right [simp]: \"inner x 1 = Re x\"\n  unfolding inner_complex_def by simp\n\nlemma complex_inner_ii_left [simp]: \"inner ii x = Im x\"\n  unfolding inner_complex_def by simp\n\nlemma complex_inner_ii_right [simp]: \"inner x ii = Im x\"\n  unfolding inner_complex_def by simp\n\n\nsubsection {* Gradient derivative *}\n\ndefinition\n  gderiv ::\n    \"['a::real_inner \\<Rightarrow> real, 'a, 'a] \\<Rightarrow> bool\"\n          (\"(GDERIV (_)/ (_)/ :> (_))\" [1000, 1000, 60] 60)\nwhere\n  \"GDERIV f x :> D \\<longleftrightarrow> FDERIV f x :> (\\<lambda>h. inner h D)\"\n\nlemma gderiv_deriv [simp]: \"GDERIV f x :> D \\<longleftrightarrow> DERIV f x :> D\"\n  by (simp only: gderiv_def has_field_derivative_def inner_real_def mult_commute_abs)\n\nlemma GDERIV_DERIV_compose:\n    \"\\<lbrakk>GDERIV f x :> df; DERIV g (f x) :> dg\\<rbrakk>\n     \\<Longrightarrow> GDERIV (\\<lambda>x. g (f x)) x :> scaleR dg df\"\n  unfolding gderiv_def has_field_derivative_def\n  apply (drule (1) has_derivative_compose)\n  apply (simp add: ac_simps)\n  done\n\nlemma has_derivative_subst: \"\\<lbrakk>FDERIV f x :> df; df = d\\<rbrakk> \\<Longrightarrow> FDERIV f x :> d\"\n  by simp\n\nlemma GDERIV_subst: \"\\<lbrakk>GDERIV f x :> df; df = d\\<rbrakk> \\<Longrightarrow> GDERIV f x :> d\"\n  by simp\n\nlemma GDERIV_const: \"GDERIV (\\<lambda>x. k) x :> 0\"\n  unfolding gderiv_def inner_zero_right by (rule has_derivative_const)\n\nlemma GDERIV_add:\n    \"\\<lbrakk>GDERIV f x :> df; GDERIV g x :> dg\\<rbrakk>\n     \\<Longrightarrow> GDERIV (\\<lambda>x. f x + g x) x :> df + dg\"\n  unfolding gderiv_def inner_add_right by (rule has_derivative_add)\n\nlemma GDERIV_minus:\n    \"GDERIV f x :> df \\<Longrightarrow> GDERIV (\\<lambda>x. - f x) x :> - df\"\n  unfolding gderiv_def inner_minus_right by (rule has_derivative_minus)\n\nlemma GDERIV_diff:\n    \"\\<lbrakk>GDERIV f x :> df; GDERIV g x :> dg\\<rbrakk>\n     \\<Longrightarrow> GDERIV (\\<lambda>x. f x - g x) x :> df - dg\"\n  unfolding gderiv_def inner_diff_right by (rule has_derivative_diff)\n\nlemma GDERIV_scaleR:\n    \"\\<lbrakk>DERIV f x :> df; GDERIV g x :> dg\\<rbrakk>\n     \\<Longrightarrow> GDERIV (\\<lambda>x. scaleR (f x) (g x)) x\n      :> (scaleR (f x) dg + scaleR df (g x))\"\n  unfolding gderiv_def has_field_derivative_def inner_add_right inner_scaleR_right\n  apply (rule has_derivative_subst)\n  apply (erule (1) has_derivative_scaleR)\n  apply (simp add: ac_simps)\n  done\n\nlemma GDERIV_mult:\n    \"\\<lbrakk>GDERIV f x :> df; GDERIV g x :> dg\\<rbrakk>\n     \\<Longrightarrow> GDERIV (\\<lambda>x. f x * g x) x :> scaleR (f x) dg + scaleR (g x) df\"\n  unfolding gderiv_def\n  apply (rule has_derivative_subst)\n  apply (erule (1) has_derivative_mult)\n  apply (simp add: inner_add ac_simps)\n  done\n\nlemma GDERIV_inverse:\n    \"\\<lbrakk>GDERIV f x :> df; f x \\<noteq> 0\\<rbrakk>\n     \\<Longrightarrow> GDERIV (\\<lambda>x. inverse (f x)) x :> - (inverse (f x))\\<^sup>2 *\\<^sub>R df\"\n  apply (erule GDERIV_DERIV_compose)\n  apply (erule DERIV_inverse [folded numeral_2_eq_2])\n  done\n\nlemma GDERIV_norm:\n  assumes \"x \\<noteq> 0\" shows \"GDERIV (\\<lambda>x. norm x) x :> sgn x\"\nproof -\n  have 1: \"FDERIV (\\<lambda>x. inner x x) x :> (\\<lambda>h. inner x h + inner h x)\"\n    by (intro has_derivative_inner has_derivative_ident)\n  have 2: \"(\\<lambda>h. inner x h + inner h x) = (\\<lambda>h. inner h (scaleR 2 x))\"\n    by (simp add: fun_eq_iff inner_commute)\n  have \"0 < inner x x\" using `x \\<noteq> 0` by simp\n  then have 3: \"DERIV sqrt (inner x x) :> (inverse (sqrt (inner x x)) / 2)\"\n    by (rule DERIV_real_sqrt)\n  have 4: \"(inverse (sqrt (inner x x)) / 2) *\\<^sub>R 2 *\\<^sub>R x = sgn x\"\n    by (simp add: sgn_div_norm norm_eq_sqrt_inner)\n  show ?thesis\n    unfolding norm_eq_sqrt_inner\n    apply (rule GDERIV_subst [OF _ 4])\n    apply (rule GDERIV_DERIV_compose [where g=sqrt and df=\"scaleR 2 x\"])\n    apply (subst gderiv_def)\n    apply (rule has_derivative_subst [OF _ 2])\n    apply (rule 1)\n    apply (rule 3)\n    done\nqed\n\nlemmas has_derivative_norm = GDERIV_norm [unfolded gderiv_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/Library/Inner_Product.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8438950947024555, "lm_q2_score": 0.8354835289107307, "lm_q1q2_score": 0.7050604517524628}}
{"text": "theory WordInterval_Lists\nimports \"../../IP_Addresses/WordInterval\"\n  Negation_Type\nbegin\n\n\nfun l2wi_negation_type_union :: \"('a::len word \\<times> 'a::len word) negation_type list \\<Rightarrow> 'a::len wordinterval\" where\n  \"l2wi_negation_type_union [] = Empty_WordInterval\" |\n  \"l2wi_negation_type_union ((Pos (s,e))#ls) = wordinterval_union (WordInterval s e) (l2wi_negation_type_union ls)\" |\n  \"l2wi_negation_type_union ((Neg (s,e))#ls) = wordinterval_union (wordinterval_invert (WordInterval s e)) (l2wi_negation_type_union ls)\"\n\nlemma l2wi_negation_type_union: \"wordinterval_to_set (l2wi_negation_type_union l) = \n                      (\\<Union> (i,j) \\<in> set (getPos l). {i .. j}) \\<union> (\\<Union> (i,j) \\<in> set (getNeg l). - {i .. j})\"\napply(simp add: l2wi)\napply(induction l rule: l2wi_negation_type_union.induct)\n  apply(simp_all)\n apply fast+\ndone\n\n\ndefinition l2wi_intersect :: \"('a::len word \\<times> 'a::len word) list \\<Rightarrow> 'a::len wordinterval\" where\n  \"l2wi_intersect = foldl (\\<lambda> acc (s,e). wordinterval_intersection (WordInterval s e) acc) wordinterval_UNIV\"\n\nlemma l2wi_intersect: \"wordinterval_to_set (l2wi_intersect l) = (\\<Inter> (i,j) \\<in> set l. {i .. j})\"\n  proof -\n  { fix U --\\<open>@{const wordinterval_UNIV} generalized\\<close>\n    have \"wordinterval_to_set (foldl (\\<lambda>acc (s, e). wordinterval_intersection (WordInterval s e) acc) U l) = (wordinterval_to_set U) \\<inter> (\\<Inter>(i, j)\\<in>set l. {i..j})\"\n        apply(induction l arbitrary: U)\n         apply(simp)\n        by force\n  } thus ?thesis\n    unfolding l2wi_intersect_def by simp\n  qed\n\n\nfun l2wi_negation_type_intersect :: \"('a::len word \\<times> 'a::len word) negation_type list \\<Rightarrow> 'a::len wordinterval\" where\n  \"l2wi_negation_type_intersect [] = wordinterval_UNIV\" |\n  \"l2wi_negation_type_intersect ((Pos (s,e))#ls) = wordinterval_intersection (WordInterval s e) (l2wi_negation_type_intersect ls)\" |\n  \"l2wi_negation_type_intersect ((Neg (s,e))#ls) = wordinterval_intersection (wordinterval_invert (WordInterval s e)) (l2wi_negation_type_intersect ls)\"\n\nlemma l2wi_negation_type_intersect_alt: \"wordinterval_to_set (l2wi_negation_type_intersect l) = \n                wordinterval_to_set (wordinterval_setminus (l2wi_intersect (getPos l)) (l2wi (getNeg l)))\"\n  apply(simp add: l2wi_intersect l2wi)\n  apply(induction l rule :l2wi_negation_type_intersect.induct)\n     apply(simp_all)\n    apply(fast)+\n  done\n\nlemma l2wi_negation_type_intersect: \"wordinterval_to_set (l2wi_negation_type_intersect l) = \n                      (\\<Inter> (i,j) \\<in> set (getPos l). {i .. j}) - (\\<Union> (i,j) \\<in> set (getNeg l). {i .. j})\"\n  by(simp add: l2wi_negation_type_intersect_alt l2wi_intersect l2wi)\n\nend\n", "meta": {"author": "diekmann", "repo": "Iptables_Semantics", "sha": "e0a2516bd885708fce875023b474ae341cbdee29", "save_path": "github-repos/isabelle/diekmann-Iptables_Semantics", "path": "github-repos/isabelle/diekmann-Iptables_Semantics/Iptables_Semantics-e0a2516bd885708fce875023b474ae341cbdee29/thy/Iptables_Semantics/Common/WordInterval_Lists.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894576856559, "lm_q2_score": 0.78793120560257, "lm_q1q2_score": 0.7050325361547286}}
{"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_ISortPermutes\nimports \"../../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 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 elem :: \"'a => 'a list => bool\" where\n\"elem x (nil2) = False\"\n| \"elem x (cons2 z xs) = ((z = x) | (elem x xs))\"\n\nfun deleteBy :: \"('a => ('a => bool)) => 'a => 'a list =>\n                 'a list\" where\n\"deleteBy x y (nil2) = nil2\"\n| \"deleteBy x y (cons2 y2 ys) =\n     (if (x y) y2 then ys else cons2 y2 (deleteBy x y ys))\"\n\nfun isPermutation :: \"'a list => 'a list => bool\" where\n\"isPermutation (nil2) (nil2) = True\"\n| \"isPermutation (nil2) (cons2 z x2) = False\"\n| \"isPermutation (cons2 x3 xs) y =\n     ((elem x3 y) &\n        (isPermutation\n           xs (deleteBy (% (x4 :: 'a) => % (x5 :: 'a) => (x4 = x5)) x3 y)))\"\n\ntheorem property0 :\n  \"isPermutation (isort 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_sort_nat_ISortPermutes.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894520743981, "lm_q2_score": 0.7879312031126512, "lm_q1q2_score": 0.7050325295054904}}
{"text": "theory MinimalHEAP0\nimports Nat Finite_Set Set_Interval \nbegin\n\ntype_synonym Loc = nat\ntype_synonym F0 = \"Loc set\"\n\ndefinition \n  nat1 :: \"nat \\<Rightarrow> bool\"\nwhere\n  (*<*) [iff]: (*>*) \"nat1 n \\<equiv> n > 0\"\n\ndefinition \n  locs_of :: \"Loc \\<Rightarrow> nat \\<Rightarrow> (Loc set)\"\nwhere\n  (*\"locs_of l n \\<equiv> (if nat1 n then { i. i \\<ge> l \\<and> i < (l + n) } else undefined)\"*)  \n  \"locs_of l n \\<equiv> (if nat1 n then {l ..< l+n} else undefined)\"\n\ndefinition \n  is_block :: \"Loc \\<Rightarrow> nat \\<Rightarrow> (Loc set) \\<Rightarrow> bool\"\nwhere\n\t\"is_block l n ls \\<equiv> nat1 n \\<and> locs_of l n \\<subseteq> ls\"\n\ndefinition \n  F0_inv :: \"F0 \\<Rightarrow> bool\" \nwhere\n  [intro!]: \"F0_inv f \\<equiv> finite f\"\n\ndefinition \n  new0_pre :: \"F0 \\<Rightarrow> nat \\<Rightarrow> bool\"\nwhere\n  \"new0_pre f s \\<equiv> (\\<exists> l. (is_block l s f))\"\n\ndefinition\n   new0_post :: \"F0 \\<Rightarrow> nat \\<Rightarrow> F0 \\<Rightarrow> Loc \\<Rightarrow> bool\"\nwhere\n   \"new0_post f s f' r \\<equiv> (is_block r s f) \\<and> f' = f - (locs_of r s)\"\n\ndefinition \n   dispose0_pre :: \"F0 \\<Rightarrow> Loc \\<Rightarrow> nat \\<Rightarrow> bool\"\nwhere\n  \"dispose0_pre f d s \\<equiv> locs_of d s \\<inter> f = {}\"\n\ndefinition \n   dispose0_post :: \"F0 \\<Rightarrow> Loc \\<Rightarrow> nat \\<Rightarrow> F0 \\<Rightarrow> bool\"\nwhere\n   \"dispose0_post f d s f' \\<equiv> f' = f \\<union> locs_of d s\"\n\ndefinition \n  PO_new0_fsb :: \"bool\"\nwhere\n  \"PO_new0_fsb \\<equiv> (\\<forall> f s . F0_inv f \\<and> nat1 s \\<and> new0_pre f s \\<longrightarrow> \n                        (\\<exists> f' r' . new0_post f s f' r' \\<and> F0_inv f'))\"\n\ndefinition\n  PO_dispose0_fsb :: \"bool\"\nwhere\n  \"PO_dispose0_fsb \\<equiv> (\\<forall> f d s . F0_inv f \\<and> nat1 s \\<and> dispose0_pre f d s \\<longrightarrow> \n                        (\\<exists> f' . dispose0_post f d s f' \\<and> F0_inv f'))\"\n\n(*********************************************************************)\nsection {* Voila! Translate to Haskell please! *}\n\n(*\nexport_code nat1 locs_of is_block (*F0_inv*) in Haskell module_name MinimalHEAP0 file \"haskell/\"\n*)\n\nlemma \"PO_new0_fsb\"\nunfolding PO_new0_fsb_def\n(* (prov_test FEAS new0) and \\<not> (prov_test EXPOSE_POST new0) *)\nunfolding new0_post_def\n(* (prov_test EXPOSE_POST new0) and \\<not> (prov_test FULLY_WITNESSED new0) *)\napply simp\n(* ONE_POINT_WITNESS? *)\n(* INV_BREAK_DOWN? + ONE_POINT_WITNESS *)\nunfolding F0_inv_def\napply simp\n(* STRUCTURAL_BREAK_DOWN + FULLY_WITNESSED *)\nunfolding is_block_def \napply simp\napply (intro allI impI, elim conjE)\noops\n\nlemma \"PO_new0_fsb\"\nunfolding PO_new0_fsb_def\n(* (prov_test FEAS new0) and \\<not> (prov_test EXPOSE_POST new0) *)\nunfolding new0_post_def\n(* (prov_test EXPOSE_POST new0) and \\<not> (prov_test FULLY_WITNESSED new0) *)\napply simp\n(* ONE_POINT_WITNESS? *)\n(* INV_BREAK_DOWN? + ONE_POINT_WITNESS *)\nunfolding F0_inv_def\napply simp\n(* EXPOSE_PRE + STRUCTURAL_BREAKDOWN *)\nunfolding new0_pre_def \napply (intro allI impI, elim conjE exE)\n(* FULLY_WITNESSED *)\napply (intro exI)\napply simp\ndone\n\nend\n", "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/experiments/vdm/Heap/isa/MinimalHEAP0.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8976952975813454, "lm_q2_score": 0.7853085909370422, "lm_q1q2_score": 0.7049678292344151}}
{"text": "(*  Title:       More about Multisets\n    Author:      Mathias Fleury <mathias.fleury at mpi-inf.mpg.de>, 2015\n    Author:      Jasmin Blanchette <blanchette at in.tum.de>, 2014, 2015\n    Author:      Anders Schlichtkrull <andschl at dtu.dk>, 2017\n    Author:      Dmitriy Traytel <traytel at in.tum.de>, 2014\n    Maintainer:  Mathias Fleury <mathias.fleury at mpi-inf.mpg.de>\n*)\n\nsection \\<open>More about Multisets\\<close>\n\ntheory Multiset_More\n  imports\n    \"HOL-Library.Multiset_Order\"\n    \"HOL-Library.Sublist\"\nbegin\n\ntext \\<open>\nIsabelle's theory of finite multisets is not as developed as other areas, such as lists and sets.\nThe present theory introduces some missing concepts and lemmas. Some of it is expected to move to\nIsabelle's library.\n\\<close>\n\n\nsubsection \\<open>Basic Setup\\<close>\n\ndeclare\n  diff_single_trivial [simp]\n  in_image_mset [iff]\n  image_mset.compositionality [simp]\n\n  (*To have the same rules as the set counter-part*)\n  mset_subset_eqD[dest, intro?] (*@{thm subsetD}*)\n\n  Multiset.in_multiset_in_set[simp]\n  inter_add_left1[simp]\n  inter_add_left2[simp]\n  inter_add_right1[simp]\n  inter_add_right2[simp]\n\n  sum_mset_sum_list[simp]\n\n\nsubsection \\<open>Lemmas about Intersection, Union and Pointwise Inclusion\\<close>\n\nlemma subset_mset_imp_subset_add_mset: \"A \\<subseteq># B \\<Longrightarrow> A \\<subseteq># add_mset x B\"\n  by (auto simp add: subseteq_mset_def le_SucI)\n\nlemma subset_add_mset_notin_subset_mset: \\<open>A \\<subseteq># add_mset b B \\<Longrightarrow> b \\<notin># A \\<Longrightarrow> A \\<subseteq># B\\<close>\n  by (simp add: subset_mset.le_iff_sup)\n\nlemma subset_msetE: \"\\<lbrakk>A \\<subset># B; \\<lbrakk>A \\<subseteq># B; \\<not> B \\<subseteq># A\\<rbrakk> \\<Longrightarrow> R\\<rbrakk> \\<Longrightarrow> R\"\n  by (simp add: subset_mset.less_le_not_le)\n\nlemma Diff_triv_mset: \"M \\<inter># N = {#} \\<Longrightarrow> M - N = M\"\n  by (metis diff_intersect_left_idem diff_zero)\n\nlemma diff_intersect_sym_diff: \"(A - B) \\<inter># (B - A) = {#}\"\n  by (rule multiset_eqI) simp\n\ndeclare subset_msetE [elim!]\n\nlemma subseq_mset_subseteq_mset: \"subseq xs ys \\<Longrightarrow> mset xs \\<subseteq># mset ys\"\nproof (induct xs arbitrary: ys)\n  case (Cons x xs)\n  note Outer_Cons = this\n  then show ?case\n  proof (induct ys)\n    case (Cons y ys)\n    have \"subseq xs ys\"\n      by (metis Cons.prems(2) subseq_Cons' subseq_Cons2_iff)\n    then show ?case\n      using Cons by (metis mset.simps(2) mset_subset_eq_add_mset_cancel subseq_Cons2_iff\n          subset_mset_imp_subset_add_mset)\n  qed simp\nqed simp\n\nlemma finite_mset_set_inter:\n  \\<open>finite A \\<Longrightarrow> finite B \\<Longrightarrow> mset_set (A \\<inter> B) = mset_set A \\<inter># mset_set B\\<close>\n  apply (induction A rule: finite_induct)\n  subgoal by auto\n  subgoal for a A\n    by (cases \\<open>a \\<in> B\\<close>; cases \\<open>a \\<in># mset_set B\\<close>)\n      (use multi_member_split[of a \\<open>mset_set B\\<close>] in\n        \\<open>auto simp: mset_set.insert_remove\\<close>)\n  done\n\n\nsubsection \\<open>Lemmas about Filter and Image\\<close>\n\nlemma count_image_mset_ge_count: \"count (image_mset f A) (f b) \\<ge> count A b\"\n  by (induction A) auto\n\nlemma count_image_mset_inj:\n  assumes \\<open>inj f\\<close>\n  shows \\<open>count (image_mset f M) (f x) = count M x\\<close>\n  by (induct M) (use assms in \\<open>auto simp: inj_on_def\\<close>)\n\nlemma count_image_mset_le_count_inj_on:\n  \"inj_on f (set_mset M) \\<Longrightarrow> count (image_mset f M) y \\<le> count M (inv_into (set_mset M) f y)\"\nproof (induct M)\n  case (add x M)\n  note ih = this(1) and inj_xM = this(2)\n\n  have inj_M: \"inj_on f (set_mset M)\"\n    using inj_xM by simp\n\n  show ?case\n  proof (cases \"x \\<in># M\")\n    case x_in_M: True\n    show ?thesis\n    proof (cases \"y = f x\")\n      case y_eq_fx: True\n      show ?thesis\n        using x_in_M ih[OF inj_M] unfolding y_eq_fx by (simp add: inj_M insert_absorb)\n    next\n      case y_ne_fx: False\n      show ?thesis\n        using x_in_M ih[OF inj_M] y_ne_fx insert_absorb by fastforce\n    qed\n  next\n    case x_ni_M: False\n    show ?thesis\n    proof (cases \"y = f x\")\n      case y_eq_fx: True\n      have \"f x \\<notin># image_mset f M\"\n        using x_ni_M inj_xM by force\n      thus ?thesis\n        unfolding y_eq_fx\n        by (metis (no_types) inj_xM count_add_mset count_greater_eq_Suc_zero_iff count_inI\n          image_mset_add_mset inv_into_f_f union_single_eq_member)\n    next\n      case y_ne_fx: False\n      show ?thesis\n      proof (rule ccontr)\n        assume neg_conj: \"\\<not> count (image_mset f (add_mset x M)) y\n          \\<le> count (add_mset x M) (inv_into (set_mset (add_mset x M)) f y)\"\n\n        have cnt_y: \"count (add_mset (f x) (image_mset f M)) y = count (image_mset f M) y\"\n          using y_ne_fx by simp\n\n        have \"inv_into (set_mset M) f y \\<in># add_mset x M \\<Longrightarrow>\n          inv_into (set_mset (add_mset x M)) f (f (inv_into (set_mset M) f y)) =\n          inv_into (set_mset M) f y\"\n          by (meson inj_xM inv_into_f_f)\n        hence \"0 < count (image_mset f (add_mset x M)) y \\<Longrightarrow>\n          count M (inv_into (set_mset M) f y) = 0 \\<or> x = inv_into (set_mset M) f y\"\n          using neg_conj cnt_y ih[OF inj_M]\n          by (metis (no_types) count_add_mset count_greater_zero_iff count_inI f_inv_into_f\n            image_mset_add_mset set_image_mset)\n        thus False\n          using neg_conj cnt_y x_ni_M ih[OF inj_M]\n          by (metis (no_types) count_greater_zero_iff count_inI eq_iff image_mset_add_mset\n            less_imp_le)\n      qed\n    qed\n  qed\nqed simp\n\nlemma mset_filter_compl: \"mset (filter p xs) + mset (filter (Not \\<circ> p) xs) = mset xs\"\n  by (induction xs) (auto simp: ac_simps)\n\ntext \\<open>Near duplicate of @{thm [source] filter_eq_replicate_mset}: @{thm filter_eq_replicate_mset}.\\<close>\n\nlemma filter_mset_eq: \"filter_mset ((=) L) A = replicate_mset (count A L) L\"\n  by (auto simp: multiset_eq_iff)\n\nlemma filter_mset_cong[fundef_cong]:\n  assumes \"M = M'\" \"\\<And>a. a \\<in># M \\<Longrightarrow> P a = Q a\"\n  shows \"filter_mset P M = filter_mset Q M\"\nproof -\n  have \"M - filter_mset Q M = filter_mset (\\<lambda>a. \\<not>Q a) M\"\n    by (metis multiset_partition add_diff_cancel_left')\n  then show ?thesis\n    by (auto simp: filter_mset_eq_conv assms)\nqed\n\nlemma image_mset_filter_swap: \"image_mset f {# x \\<in># M. P (f x)#} = {# x \\<in># image_mset f M. P x#}\"\n  by (induction M) auto\n\nlemma image_mset_cong2:\n  \"(\\<And>x. x \\<in># M \\<Longrightarrow> f x = g x) \\<Longrightarrow> M = N \\<Longrightarrow> image_mset f M = image_mset g N\"\n  by (hypsubst, rule image_mset_cong)\n\nlemma filter_mset_empty_conv: \\<open>(filter_mset P M = {#}) = (\\<forall>L\\<in>#M. \\<not> P L)\\<close>\n  by (induction M) auto\n\nlemma multiset_filter_mono2: \\<open>filter_mset P A \\<subseteq># filter_mset Q A \\<longleftrightarrow> (\\<forall>a\\<in>#A. P a \\<longrightarrow> Q a)\\<close>\n  by (induction A) (auto intro: subset_mset.trans)\n\nlemma image_filter_cong:\n  assumes \\<open>\\<And>C. C \\<in># M \\<Longrightarrow> P C \\<Longrightarrow> f C = g C\\<close>\n  shows \\<open>{#f C. C \\<in># {#C \\<in># M. P C#}#} = {#g C | C\\<in># M. P C#}\\<close>\n  using assms by (induction M) auto\n\nlemma image_mset_filter_swap2: \\<open>{#C \\<in># {#P x. x \\<in># D#}. Q C #} = {#P x. x \\<in># {#C| C \\<in># D. Q (P C)#}#}\\<close>\n  by (simp add: image_mset_filter_swap)\n\ndeclare image_mset_cong2 [cong]\n\nlemma filter_mset_empty_if_finite_and_filter_set_empty:\n  assumes\n    \"{x \\<in> X. P x} = {}\" and\n    \"finite X\"\n  shows \"{#x \\<in># mset_set X. P x#} = {#}\"\nproof -\n  have empty_empty: \"\\<And>Y. set_mset Y = {} \\<Longrightarrow> Y = {#}\"\n    by auto\n  from assms have \"set_mset {#x \\<in># mset_set X. P x#} = {}\"\n    by auto\n  then show ?thesis\n    by (rule empty_empty)\nqed\n\n\nsubsection \\<open>Lemmas about Sum\\<close>\n\nlemma sum_image_mset_sum_map[simp]: \"sum_mset (image_mset f (mset xs)) = sum_list (map f xs)\"\n  by (metis mset_map sum_mset_sum_list)\n\nlemma sum_image_mset_mono:\n  fixes f :: \"'a \\<Rightarrow> 'b::canonically_ordered_monoid_add\"\n  assumes sub: \"A \\<subseteq># B\"\n  shows \"(\\<Sum>m \\<in># A. f m) \\<le> (\\<Sum>m \\<in># B. f m)\"\n  by (metis image_mset_union le_iff_add sub subset_mset.add_diff_inverse sum_mset.union)\n\nlemma sum_image_mset_mono_mem:\n  \"n \\<in># M \\<Longrightarrow> f n \\<le> (\\<Sum>m \\<in># M. f m)\" for f :: \"'a \\<Rightarrow> 'b::canonically_ordered_monoid_add\"\n  using le_iff_add multi_member_split by fastforce\n\nlemma count_sum_mset_if_1_0: \\<open>count M a = (\\<Sum>x\\<in>#M. if x = a then 1 else 0)\\<close>\n  by (induction M) auto\n\nlemma sum_mset_dvd:\n  fixes k :: \"'a::comm_semiring_1_cancel\"\n  assumes \"\\<forall>m \\<in># M. k dvd f m\"\n  shows \"k dvd (\\<Sum>m \\<in># M. f m)\"\n  using assms by (induct M) auto\n\n\n\n\nsubsection \\<open>Lemmas about Remove\\<close>\n\nlemma set_mset_minus_replicate_mset[simp]:\n  \"n \\<ge> count A a \\<Longrightarrow> set_mset (A - replicate_mset n a) = set_mset A - {a}\"\n  \"n < count A a \\<Longrightarrow> set_mset (A - replicate_mset n a) = set_mset A\"\n  unfolding set_mset_def by (auto split: if_split simp: not_in_iff)\n\nabbreviation removeAll_mset :: \"'a \\<Rightarrow> 'a multiset \\<Rightarrow> 'a multiset\" where\n  \"removeAll_mset C M \\<equiv> M - replicate_mset (count M C) C\"\n\nlemma mset_removeAll[simp, code]: \"removeAll_mset C (mset L) = mset (removeAll C L)\"\n  by (induction L) (auto simp: ac_simps multiset_eq_iff split: if_split_asm)\n\nlemma removeAll_mset_filter_mset: \"removeAll_mset C M = filter_mset ((\\<noteq>) C) M\"\n  by (induction M) (auto simp: ac_simps multiset_eq_iff)\n\nabbreviation remove1_mset :: \"'a \\<Rightarrow> 'a multiset \\<Rightarrow> 'a multiset\" where\n  \"remove1_mset C M \\<equiv> M - {#C#}\"\n\nlemma removeAll_subseteq_remove1_mset: \"removeAll_mset x M \\<subseteq># remove1_mset x M\"\n  by (auto simp: subseteq_mset_def)\n\nlemma in_remove1_mset_neq:\n  assumes ab: \"a \\<noteq> b\"\n  shows \"a \\<in># remove1_mset b C \\<longleftrightarrow> a \\<in># C\"\n  by (metis assms diff_single_trivial in_diffD insert_DiffM insert_noteq_member)\n\nlemma size_mset_removeAll_mset_le_iff: \"size (removeAll_mset x M) < size M \\<longleftrightarrow> x \\<in># M\"\n  by (auto intro: count_inI mset_subset_size simp: subset_mset_def multiset_eq_iff)\n\nlemma size_remove1_mset_If: \\<open>size (remove1_mset x M) = size M - (if x \\<in># M then 1 else 0)\\<close>\n  by (auto simp: size_Diff_subset_Int)\n\nlemma size_mset_remove1_mset_le_iff: \"size (remove1_mset x M) < size M \\<longleftrightarrow> x \\<in># M\"\n  using less_irrefl\n  by (fastforce intro!: mset_subset_size elim: in_countE simp: subset_mset_def multiset_eq_iff)\n\nlemma remove_1_mset_id_iff_notin: \"remove1_mset a M = M \\<longleftrightarrow> a \\<notin># M\"\n  by (meson diff_single_trivial multi_drop_mem_not_eq)\n\nlemma id_remove_1_mset_iff_notin: \"M = remove1_mset a M \\<longleftrightarrow> a \\<notin># M\"\n  using remove_1_mset_id_iff_notin by metis\n\nlemma remove1_mset_eqE:\n  \"remove1_mset L x1 = M \\<Longrightarrow>\n    (L \\<in># x1 \\<Longrightarrow> x1 = M + {#L#} \\<Longrightarrow> P) \\<Longrightarrow>\n    (L \\<notin># x1 \\<Longrightarrow> x1 = M \\<Longrightarrow> P) \\<Longrightarrow>\n  P\"\n  by (cases \"L \\<in># x1\") auto\n\nlemma image_filter_ne_mset[simp]:\n  \"image_mset f {#x \\<in># M. f x \\<noteq> y#} = removeAll_mset y (image_mset f M)\"\n  by (induction M) simp_all\n\nlemma image_mset_remove1_mset_if:\n  \"image_mset f (remove1_mset a M) =\n   (if a \\<in># M then remove1_mset (f a) (image_mset f M) else image_mset f M)\"\n  by (auto simp: image_mset_Diff)\n\nlemma filter_mset_neq: \"{#x \\<in># M. x \\<noteq> y#} = removeAll_mset y M\"\n  by (metis add_diff_cancel_left' filter_eq_replicate_mset multiset_partition)\n\nlemma filter_mset_neq_cond: \"{#x \\<in># M. P x \\<and> x \\<noteq> y#} = removeAll_mset y {# x\\<in>#M. P x#}\"\n  by (metis filter_filter_mset filter_mset_neq)\n\nlemma remove1_mset_add_mset_If:\n  \"remove1_mset L (add_mset L' C) = (if L = L' then C else remove1_mset L C + {#L'#})\"\n  by (auto simp: multiset_eq_iff)\n\nlemma minus_remove1_mset_if:\n  \"A - remove1_mset b B = (if b \\<in># B \\<and> b \\<in># A \\<and> count A b \\<ge> count B b then {#b#} + (A - B) else A - B)\"\n  by (auto simp: multiset_eq_iff count_greater_zero_iff[symmetric]\n    simp del: count_greater_zero_iff)\n\nlemma add_mset_eq_add_mset_ne:\n  \"a \\<noteq> b \\<Longrightarrow> add_mset a A = add_mset b B \\<longleftrightarrow> a \\<in># B \\<and> b \\<in># A \\<and> A = add_mset b (B - {#a#})\"\n  by (metis (no_types, lifting) diff_single_eq_union diff_union_swap multi_self_add_other_not_self\n    remove_1_mset_id_iff_notin union_single_eq_diff)\n\nlemma add_mset_eq_add_mset: \\<open>add_mset a M = add_mset b M' \\<longleftrightarrow>\n  (a = b \\<and> M = M') \\<or> (a \\<noteq> b \\<and> b \\<in># M \\<and> add_mset a (M - {#b#}) = M')\\<close>\n  by (metis add_mset_eq_add_mset_ne add_mset_remove_trivial union_single_eq_member)\n\n(* TODO move to Multiset: could replace add_mset_remove_trivial_eq? *)\nlemma add_mset_remove_trivial_iff: \\<open>N = add_mset a (N - {#b#}) \\<longleftrightarrow> a \\<in># N \\<and> a = b\\<close>\n  by (metis add_left_cancel add_mset_remove_trivial insert_DiffM2 single_eq_single\n      size_mset_remove1_mset_le_iff union_single_eq_member)\n\nlemma trivial_add_mset_remove_iff: \\<open>add_mset a (N - {#b#}) = N \\<longleftrightarrow> a \\<in># N \\<and> a = b\\<close>\n  by (subst eq_commute) (fact add_mset_remove_trivial_iff)\n\nlemma remove1_single_empty_iff[simp]: \\<open>remove1_mset L {#L'#} = {#} \\<longleftrightarrow> L = L'\\<close>\n  using add_mset_remove_trivial_iff by fastforce\n\nlemma add_mset_less_imp_less_remove1_mset:\n  assumes xM_lt_N: \"add_mset x M < N\"\n  shows \"M < remove1_mset x N\"\nproof -\n  have \"M < N\"\n    using assms le_multiset_right_total mset_le_trans by blast\n  then show ?thesis\n    by (metis add_less_cancel_right add_mset_add_single diff_single_trivial insert_DiffM2 xM_lt_N)\nqed\n\nlemma remove_diff_multiset[simp]: \\<open>x13 \\<notin># A \\<Longrightarrow> A - add_mset x13 B = A - B\\<close>\n  by (metis diff_intersect_left_idem inter_add_right1)\n\nlemma removeAll_notin: \\<open>a \\<notin># A \\<Longrightarrow> removeAll_mset a A = A\\<close>\n  using count_inI by force\n\nlemma mset_drop_upto: \\<open>mset (drop a N) = {#N!i. i \\<in># mset_set {a..<length N}#}\\<close>\nproof (induction N arbitrary: a)\n  case Nil\n  then show ?case by simp\nnext\n  case (Cons c N)\n  have upt: \\<open>{0..<Suc (length N)} = insert 0 {1..<Suc (length N)}\\<close>\n    by auto\n  then have H: \\<open>mset_set {0..<Suc (length N)} = add_mset 0 (mset_set {1..<Suc (length N)})\\<close>\n    unfolding upt by auto\n  have mset_case_Suc: \\<open>{#case x of 0 \\<Rightarrow> c | Suc x \\<Rightarrow> N ! x . x \\<in># mset_set {Suc a..<Suc b}#} =\n    {#N ! (x-1) . x \\<in># mset_set {Suc a..<Suc b}#}\\<close> for a b\n    by (rule image_mset_cong) (auto split: nat.splits)\n  have Suc_Suc: \\<open>{Suc a..<Suc b} = Suc ` {a..<b}\\<close> for a b\n    by auto\n  then have mset_set_Suc_Suc: \\<open>mset_set {Suc a..<Suc b} = {#Suc n. n \\<in># mset_set {a..<b}#}\\<close> for a b\n    unfolding Suc_Suc by (subst image_mset_mset_set[symmetric]) auto\n  have *: \\<open>{#N ! (x-Suc 0) . x \\<in># mset_set {Suc a..<Suc b}#} = {#N ! x . x \\<in># mset_set {a..<b}#}\\<close>\n    for a b\n    by (auto simp add: mset_set_Suc_Suc)\n  show ?case\n    apply (cases a)\n    using Cons[of 0] Cons by (auto simp: nth_Cons drop_Cons H mset_case_Suc *)\nqed\n\n\nsubsection \\<open>Lemmas about Replicate\\<close>\n\nlemma replicate_mset_minus_replicate_mset_same[simp]:\n  \"replicate_mset m x - replicate_mset n x = replicate_mset (m - n) x\"\n  by (induct m arbitrary: n, simp, metis left_diff_repeat_mset_distrib' repeat_mset_replicate_mset)\n\nlemma replicate_mset_subset_iff_lt[simp]: \"replicate_mset m x \\<subset># replicate_mset n x \\<longleftrightarrow> m < n\"\n  by (induct n m rule: diff_induct) (auto intro: subset_mset.gr_zeroI)\n\nlemma replicate_mset_subseteq_iff_le[simp]: \"replicate_mset m x \\<subseteq># replicate_mset n x \\<longleftrightarrow> m \\<le> n\"\n  by (induct n m rule: diff_induct) auto\n\nlemma replicate_mset_lt_iff_lt[simp]: \"replicate_mset m x < replicate_mset n x \\<longleftrightarrow> m < n\"\n  by (induct n m rule: diff_induct) (auto intro: subset_mset.gr_zeroI gr_zeroI)\n\nlemma replicate_mset_le_iff_le[simp]: \"replicate_mset m x \\<le> replicate_mset n x \\<longleftrightarrow> m \\<le> n\"\n  by (induct n m rule: diff_induct) auto\n\nlemma replicate_mset_eq_iff[simp]:\n  \"replicate_mset m x = replicate_mset n y \\<longleftrightarrow> m = n \\<and> (m \\<noteq> 0 \\<longrightarrow> x = y)\"\n  by (cases m; cases n; simp)\n    (metis in_replicate_mset insert_noteq_member size_replicate_mset union_single_eq_diff)\n\nlemma replicate_mset_plus: \"replicate_mset (a + b) C = replicate_mset a C + replicate_mset b C\"\n  by (induct a) (auto simp: ac_simps)\n\nlemma mset_replicate_replicate_mset: \"mset (replicate n L) = replicate_mset n L\"\n  by (induction n) auto\n\nlemma set_mset_single_iff_replicate_mset: \"set_mset U = {a} \\<longleftrightarrow> (\\<exists>n > 0. U = replicate_mset n a)\"\n  by (rule, metis count_greater_zero_iff count_replicate_mset insertI1 multi_count_eq singletonD\n    zero_less_iff_neq_zero, force)\n\nlemma ex_replicate_mset_if_all_elems_eq:\n  assumes \"\\<forall>x \\<in># M. x = y\"\n  shows \"\\<exists>n. M = replicate_mset n y\"\n  using assms by (metis count_replicate_mset mem_Collect_eq multiset_eqI neq0_conv set_mset_def)\n\n\nsubsection \\<open>Multiset and Set Conversions\\<close>\n\nlemma count_mset_set_if: \"count (mset_set A) a = (if a \\<in> A \\<and> finite A then 1 else 0)\"\n  by auto\n\nlemma mset_set_set_mset_empty_mempty[iff]: \"mset_set (set_mset D) = {#} \\<longleftrightarrow> D = {#}\"\n  by (simp add: mset_set_empty_iff)\n\nlemma count_mset_set_le_one: \"count (mset_set A) x \\<le> 1\"\n  by (simp add: count_mset_set_if)\n\nlemma mset_set_set_mset_subseteq[simp]: \"mset_set (set_mset A) \\<subseteq># A\"\n  by (simp add: mset_set_set_mset_msubset)\n\nlemma mset_sorted_list_of_set[simp]: \"mset (sorted_list_of_set A) = mset_set A\"\n  by (metis mset_sorted_list_of_multiset sorted_list_of_mset_set)\n\n\n\nlemma mset_take_subseteq: \"mset (take n xs) \\<subseteq># mset xs\"\n  apply (induct xs arbitrary: n)\n   apply simp\n  by (case_tac n) simp_all\n\nlemma sorted_list_of_multiset_eq_Nil[simp]: \"sorted_list_of_multiset M = [] \\<longleftrightarrow> M = {#}\"\n  by (metis mset_sorted_list_of_multiset sorted_list_of_multiset_empty)\n\n\nsubsection \\<open>Duplicate Removal\\<close>\n\n(* TODO: use abbreviation? *)\ndefinition remdups_mset :: \"'v multiset \\<Rightarrow> 'v multiset\" where\n  \"remdups_mset S = mset_set (set_mset S)\"\n\nlemma set_mset_remdups_mset[simp]: \\<open>set_mset (remdups_mset A) = set_mset A\\<close>\n  unfolding remdups_mset_def by auto\n\nlemma count_remdups_mset_eq_1: \"a \\<in># remdups_mset A \\<longleftrightarrow> count (remdups_mset A) a = 1\"\n  unfolding remdups_mset_def by (auto simp: count_eq_zero_iff intro: count_inI)\n\nlemma remdups_mset_empty[simp]: \"remdups_mset {#} = {#}\"\n  unfolding remdups_mset_def by auto\n\nlemma remdups_mset_singleton[simp]: \"remdups_mset {#a#} = {#a#}\"\n  unfolding remdups_mset_def by auto\n\nlemma remdups_mset_eq_empty[iff]: \"remdups_mset D = {#} \\<longleftrightarrow> D = {#}\"\n  unfolding remdups_mset_def by blast\n\nlemma remdups_mset_singleton_sum[simp]:\n  \"remdups_mset (add_mset a A) = (if a \\<in># A then remdups_mset A else add_mset a (remdups_mset A))\"\n  unfolding remdups_mset_def by (simp_all add: insert_absorb)\n\nlemma mset_remdups_remdups_mset[simp]: \"mset (remdups D) = remdups_mset (mset D)\"\n  by (induction D) (auto simp add: ac_simps)\n\ndeclare mset_remdups_remdups_mset[symmetric, code]\n\nlemma count_remdups_mset_If: \\<open>count (remdups_mset A) a = (if a \\<in># A then 1 else 0)\\<close>\n  unfolding remdups_mset_def by auto\n\nlemma notin_add_mset_remdups_mset:\n  \\<open>a \\<notin># A \\<Longrightarrow> add_mset a (remdups_mset A) = remdups_mset (add_mset a A)\\<close>\n  by auto\n\n\nsubsection \\<open>Repeat Operation\\<close>\n\nlemma repeat_mset_compower: \"repeat_mset n A = (((+) A) ^^ n) {#}\"\n  by (induction n) auto\n\nlemma repeat_mset_prod: \"repeat_mset (m * n) A = (((+) (repeat_mset n A)) ^^ m) {#}\"\n  by (induction m) (auto simp: repeat_mset_distrib)\n\n\nsubsection \\<open>Cartesian Product\\<close>\n\ntext \\<open>Definition of the cartesian products over multisets. The construction mimics of the cartesian\n  product on sets and use the same theorem names (adding only the suffix \\<open>_mset\\<close> to Sigma\n  and Times). See file @{file \\<open>~~/src/HOL/Product_Type.thy\\<close>}\\<close>\n\ndefinition Sigma_mset :: \"'a multiset \\<Rightarrow> ('a \\<Rightarrow> 'b multiset) \\<Rightarrow> ('a \\<times> 'b) multiset\" where\n  \"Sigma_mset A B \\<equiv> \\<Sum>\\<^sub># {#{#(a, b). b \\<in># B a#}. a \\<in># A #}\"\n\nabbreviation Times_mset :: \"'a multiset \\<Rightarrow> 'b multiset \\<Rightarrow> ('a \\<times> 'b) multiset\" (infixr \"\\<times>#\" 80) where\n  \"Times_mset A B \\<equiv> Sigma_mset A (\\<lambda>_. B)\"\n\nhide_const (open) Times_mset\n\ntext \\<open>Contrary to the set version @{term \\<open>SIGMA x:A. B\\<close>}, we use the non-ASCII symbol \\<open>\\<in>#\\<close>.\\<close>\n\nsyntax\n  \"_Sigma_mset\" :: \"[pttrn, 'a multiset, 'b multiset] => ('a * 'b) multiset\"\n  (\"(3SIGMAMSET _\\<in>#_./ _)\" [0, 0, 10] 10)\ntranslations\n  \"SIGMAMSET x\\<in>#A. B\" == \"CONST Sigma_mset A (\\<lambda>x. B)\"\n\ntext \\<open>Link between the multiset and the set cartesian product:\\<close>\n\nlemma Times_mset_Times: \"set_mset (A \\<times># B) = set_mset A \\<times> set_mset B\"\n  unfolding Sigma_mset_def by auto\n\nlemma Sigma_msetI [intro!]: \"\\<lbrakk>a \\<in># A; b \\<in># B a\\<rbrakk> \\<Longrightarrow> (a, b) \\<in># Sigma_mset A B\"\n  by (unfold Sigma_mset_def) auto\n\nlemma Sigma_msetE[elim!]: \"\\<lbrakk>c \\<in># Sigma_mset A B; \\<And>x y. \\<lbrakk>x \\<in># A; y \\<in># B x; c = (x, y)\\<rbrakk> \\<Longrightarrow> P\\<rbrakk> \\<Longrightarrow> P\"\n  by (unfold Sigma_mset_def) auto\n\ntext \\<open>Elimination of @{term \"(a, b) \\<in># A \\<times># B\"} -- introduces no eigenvariables.\\<close>\n\nlemma Sigma_msetD1: \"(a, b) \\<in># Sigma_mset A B \\<Longrightarrow> a \\<in># A\"\n  by blast\n\nlemma Sigma_msetD2: \"(a, b) \\<in># Sigma_mset A B \\<Longrightarrow> b \\<in># B a\"\n  by blast\n\nlemma Sigma_msetE2: \"\\<lbrakk>(a, b) \\<in># Sigma_mset A B; \\<lbrakk>a \\<in># A; b \\<in># B a\\<rbrakk> \\<Longrightarrow> P\\<rbrakk> \\<Longrightarrow> P\"\n  by blast\n\nlemma Sigma_mset_cong:\n  \"\\<lbrakk>A = B; \\<And>x. x \\<in># B \\<Longrightarrow> C x = D x\\<rbrakk> \\<Longrightarrow> (SIGMAMSET x \\<in># A. C x) = (SIGMAMSET x \\<in># B. D x)\"\n  by (metis (mono_tags, lifting) Sigma_mset_def image_mset_cong)\n\nlemma count_sum_mset: \"count (\\<Sum>\\<^sub># M) b = (\\<Sum>P \\<in># M. count P b)\"\n  by (induction M) auto\n\nlemma Sigma_mset_plus_distrib1[simp]: \"Sigma_mset (A + B) C = Sigma_mset A C + Sigma_mset B C\"\n  unfolding Sigma_mset_def by auto\n\nlemma Sigma_mset_plus_distrib2[simp]:\n  \"Sigma_mset A (\\<lambda>i. B i + C i) = Sigma_mset A B + Sigma_mset A C\"\n  unfolding Sigma_mset_def by (induction A) (auto simp: multiset_eq_iff)\n\nlemma Times_mset_single_left: \"{#a#} \\<times># B = image_mset (Pair a) B\"\n  unfolding Sigma_mset_def by auto\n\nlemma Times_mset_single_right: \"A \\<times># {#b#} = image_mset (\\<lambda>a. Pair a b) A\"\n  unfolding Sigma_mset_def by (induction A) auto\n\nlemma Times_mset_single_single[simp]: \"{#a#} \\<times># {#b#} = {#(a, b)#}\"\n  unfolding Sigma_mset_def by simp\n\nlemma count_image_mset_Pair:\n  \"count (image_mset (Pair a) B) (x, b) = (if x = a then count B b else 0)\"\n  by (induction B) auto\n\nlemma count_Sigma_mset: \"count (Sigma_mset A B) (a, b) = count A a * count (B a) b\"\n  by (induction A) (auto simp: Sigma_mset_def count_image_mset_Pair)\n\nlemma Sigma_mset_empty1[simp]: \"Sigma_mset {#} B = {#}\"\n  unfolding Sigma_mset_def by auto\n\nlemma Sigma_mset_empty2[simp]: \"A \\<times># {#} = {#}\"\n  by (auto simp: multiset_eq_iff count_Sigma_mset)\n\nlemma Sigma_mset_mono:\n  assumes \"A \\<subseteq># C\" and \"\\<And>x. x \\<in># A \\<Longrightarrow> B x \\<subseteq># D x\"\n  shows \"Sigma_mset A B \\<subseteq># Sigma_mset C D\"\nproof -\n  have \"count A a * count (B a) b \\<le> count C a * count (D a) b\" for a b\n    using assms unfolding subseteq_mset_def by (metis count_inI eq_iff mult_eq_0_iff mult_le_mono)\n  then show ?thesis\n    by (auto simp: subseteq_mset_def count_Sigma_mset)\nqed\n\nlemma mem_Sigma_mset_iff[iff]: \"((a,b) \\<in># Sigma_mset A B) = (a \\<in># A \\<and> b \\<in># B a)\"\n  by blast\n\n\n\nlemma Sigma_mset_empty_iff: \"(SIGMAMSET i\\<in>#I. X i) = {#} \\<longleftrightarrow> (\\<forall>i\\<in>#I. X i = {#})\"\n  by (auto simp: Sigma_mset_def)\n\nlemma Times_mset_subset_mset_cancel1: \"x \\<in># A \\<Longrightarrow> (A \\<times># B \\<subseteq># A \\<times># C) = (B \\<subseteq># C)\"\n  by (auto simp: subseteq_mset_def count_Sigma_mset)\n\nlemma Times_mset_subset_mset_cancel2: \"x \\<in># C \\<Longrightarrow> (A \\<times># C \\<subseteq># B \\<times># C) = (A \\<subseteq># B)\"\n  by (auto simp: subseteq_mset_def count_Sigma_mset)\n\nlemma Times_mset_eq_cancel2: \"x \\<in># C \\<Longrightarrow> (A \\<times># C = B \\<times># C) = (A = B)\"\n  by (auto simp: multiset_eq_iff count_Sigma_mset dest!: in_countE)\n\nlemma split_paired_Ball_mset_Sigma_mset[simp]:\n  \"(\\<forall>z\\<in>#Sigma_mset A B. P z) \\<longleftrightarrow> (\\<forall>x\\<in>#A. \\<forall>y\\<in>#B x. P (x, y))\"\n  by blast\n\nlemma split_paired_Bex_mset_Sigma_mset[simp]:\n  \"(\\<exists>z\\<in>#Sigma_mset A B. P z) \\<longleftrightarrow> (\\<exists>x\\<in>#A. \\<exists>y\\<in>#B x. P (x, y))\"\n  by blast\n\nlemma sum_mset_if_eq_constant:\n  \"(\\<Sum>x\\<in>#M. if a = x then (f x) else 0) = (((+) (f a)) ^^ (count M a)) 0\"\n  by (induction M) (auto simp: ac_simps)\n\nlemma iterate_op_plus: \"(((+) k) ^^ m) 0 = k * m\"\n  by (induction m) auto\n\nlemma untion_image_mset_Pair_distribute:\n  \"\\<Sum>\\<^sub>#{#image_mset (Pair x) (C x). x \\<in># J - I#} =\n   \\<Sum>\\<^sub># {#image_mset (Pair x) (C x). x \\<in># J#} - \\<Sum>\\<^sub>#{#image_mset (Pair x) (C x). x \\<in># I#}\"\n  by (auto simp: multiset_eq_iff count_sum_mset count_image_mset_Pair sum_mset_if_eq_constant\n    iterate_op_plus diff_mult_distrib2)\n\nlemma Sigma_mset_Un_distrib1: \"Sigma_mset (I \\<union># J) C = Sigma_mset I C \\<union># Sigma_mset J C\"\n  by (auto simp add: Sigma_mset_def union_mset_def untion_image_mset_Pair_distribute)\n\nlemma Sigma_mset_Un_distrib2: \"(SIGMAMSET i\\<in>#I. A i \\<union># B i) = Sigma_mset I A \\<union># Sigma_mset I B\"\n  by (auto simp: multiset_eq_iff count_sum_mset count_image_mset_Pair sum_mset_if_eq_constant\n    Sigma_mset_def diff_mult_distrib2 iterate_op_plus max_def not_in_iff)\n\nlemma Sigma_mset_Int_distrib1: \"Sigma_mset (I \\<inter># J) C = Sigma_mset I C \\<inter># Sigma_mset J C\"\n  by (auto simp: multiset_eq_iff count_sum_mset count_image_mset_Pair sum_mset_if_eq_constant\n    Sigma_mset_def iterate_op_plus min_def not_in_iff)\n\nlemma Sigma_mset_Int_distrib2: \"(SIGMAMSET i\\<in>#I. A i \\<inter># B i) = Sigma_mset I A \\<inter># Sigma_mset I B\"\n  by (auto simp: multiset_eq_iff count_sum_mset count_image_mset_Pair sum_mset_if_eq_constant\n    Sigma_mset_def iterate_op_plus min_def not_in_iff)\n\nlemma Sigma_mset_Diff_distrib1: \"Sigma_mset (I - J) C = Sigma_mset I C - Sigma_mset J C\"\n  by (auto simp: multiset_eq_iff count_sum_mset count_image_mset_Pair sum_mset_if_eq_constant\n    Sigma_mset_def iterate_op_plus min_def not_in_iff diff_mult_distrib2)\n\nlemma Sigma_mset_Diff_distrib2: \"(SIGMAMSET i\\<in>#I. A i - B i) = Sigma_mset I A - Sigma_mset I B\"\n  by (auto simp: multiset_eq_iff count_sum_mset count_image_mset_Pair sum_mset_if_eq_constant\n    Sigma_mset_def iterate_op_plus min_def not_in_iff diff_mult_distrib)\n\nlemma Sigma_mset_Union: \"Sigma_mset (\\<Sum>\\<^sub>#X) B = (\\<Sum>\\<^sub># (image_mset (\\<lambda>A. Sigma_mset A B) X))\"\n  by (auto simp: multiset_eq_iff count_sum_mset count_image_mset_Pair sum_mset_if_eq_constant\n    Sigma_mset_def iterate_op_plus min_def not_in_iff sum_mset_distrib_left)\n\nlemma Times_mset_Un_distrib1: \"(A \\<union># B) \\<times># C = A \\<times># C \\<union># B \\<times># C\"\n  by (fact Sigma_mset_Un_distrib1)\n\nlemma Times_mset_Int_distrib1: \"(A \\<inter># B) \\<times># C = A \\<times># C \\<inter># B \\<times># C\"\n  by (fact Sigma_mset_Int_distrib1)\n\nlemma Times_mset_Diff_distrib1: \"(A - B) \\<times># C = A \\<times># C - B \\<times># C\"\n  by (fact Sigma_mset_Diff_distrib1)\n\nlemma Times_mset_empty[simp]: \"A \\<times># B = {#} \\<longleftrightarrow> A = {#} \\<or> B = {#}\"\n  by (auto simp: Sigma_mset_empty_iff)\n\nlemma Times_insert_left: \"A \\<times># add_mset x B = A \\<times># B + image_mset (\\<lambda>a. Pair a x) A\"\n  unfolding add_mset_add_single[of x B] Sigma_mset_plus_distrib2\n  by (simp add: Times_mset_single_right)\n\nlemma Times_insert_right: \"add_mset a A \\<times># B = A \\<times># B + image_mset (Pair a) B\"\n  unfolding add_mset_add_single[of a A] Sigma_mset_plus_distrib1\n  by (simp add: Times_mset_single_left)\n\nlemma fst_image_mset_times_mset [simp]:\n  \"image_mset fst (A \\<times># B) = (if B = {#} then {#} else repeat_mset (size B) A)\"\n  by (induct B) (auto simp: Times_mset_single_right ac_simps Times_insert_left)\n\nlemma snd_image_mset_times_mset [simp]:\n  \"image_mset snd (A \\<times># B) = (if A = {#} then {#} else repeat_mset (size A) B)\"\n  by (induct B) (auto simp add: Times_mset_single_right Times_insert_left image_mset_const_eq)\n\nlemma product_swap_mset: \"image_mset prod.swap (A \\<times># B) = B \\<times># A\"\n  by (induction A) (auto simp add: Times_mset_single_left Times_mset_single_right\n      Times_insert_right Times_insert_left)\n\ncontext\nbegin\n\nqualified definition product_mset :: \"'a multiset \\<Rightarrow> 'b multiset \\<Rightarrow> ('a \\<times> 'b) multiset\" where\n  [code_abbrev]: \"product_mset A B = A \\<times># B\"\n\nlemma member_product_mset: \"x \\<in># product_mset A B \\<longleftrightarrow> x \\<in># A \\<times># B\"\n  by (simp add: Multiset_More.product_mset_def)\n\nend\n\nlemma count_Sigma_mset_abs_def: \"count (Sigma_mset A B) = (\\<lambda>(a, b) \\<Rightarrow> count A a * count (B a) b)\"\n  by (auto simp: fun_eq_iff count_Sigma_mset)\n\nlemma Times_mset_image_mset1: \"image_mset f A \\<times># B = image_mset (\\<lambda>(a, b). (f a, b)) (A \\<times># B)\"\n  by (induct B) (auto simp: Times_insert_left)\n\nlemma Times_mset_image_mset2: \"A \\<times># image_mset f B = image_mset (\\<lambda>(a, b). (a, f b)) (A \\<times># B)\"\n  by (induct A) (auto simp: Times_insert_right)\n\nlemma sum_le_singleton: \"A \\<subseteq> {x} \\<Longrightarrow> sum f A = (if x \\<in> A then f x else 0)\"\n  by (auto simp: subset_singleton_iff elim: finite_subset)\n\nlemma Times_mset_assoc: \"(A \\<times># B) \\<times># C = image_mset (\\<lambda>(a, b, c). ((a, b), c)) (A \\<times># B \\<times># C)\"\n  by (auto simp: multiset_eq_iff count_Sigma_mset count_image_mset vimage_def Times_mset_Times\n      Int_commute count_eq_zero_iff intro!: trans[OF _ sym[OF sum_le_singleton[of _ \"(_, _, _)\"]]]\n      cong: sum.cong if_cong)\n\n\nsubsection \\<open>Transfer Rules\\<close>\n\nlemma plus_multiset_transfer[transfer_rule]:\n  \"(rel_fun (rel_mset R) (rel_fun (rel_mset R) (rel_mset R))) (+) (+)\"\n  by (unfold rel_fun_def rel_mset_def)\n    (force dest: list_all2_appendI intro: exI[of _ \"_ @ _\"] conjI[rotated])\n\nlemma minus_multiset_transfer[transfer_rule]:\n  assumes [transfer_rule]: \"bi_unique R\"\n  shows \"(rel_fun (rel_mset R) (rel_fun (rel_mset R) (rel_mset R))) (-) (-)\"\nproof (unfold rel_fun_def rel_mset_def, safe)\n  fix xs ys xs' ys'\n  assume [transfer_rule]: \"list_all2 R xs ys\" \"list_all2 R xs' ys'\"\n  have \"list_all2 R (fold remove1 xs' xs) (fold remove1 ys' ys)\"\n    by transfer_prover\n  moreover have \"mset (fold remove1 xs' xs) = mset xs - mset xs'\"\n    by (induct xs' arbitrary: xs) auto\n  moreover have \"mset (fold remove1 ys' ys) = mset ys - mset ys'\"\n    by (induct ys' arbitrary: ys) auto\n  ultimately show \"\\<exists>xs'' ys''.\n    mset xs'' = mset xs - mset xs' \\<and> mset ys'' = mset ys - mset ys' \\<and> list_all2 R xs'' ys''\"\n    by blast\nqed\n\ndeclare rel_mset_Zero[transfer_rule]\n\nlemma count_transfer[transfer_rule]:\n  assumes \"bi_unique R\"\n  shows \"(rel_fun (rel_mset R) (rel_fun R (=))) count count\"\nunfolding rel_fun_def rel_mset_def proof safe\n  fix x y xs ys\n  assume \"list_all2 R xs ys\" \"R x y\"\n  then show \"count (mset xs) x = count (mset ys) y\"\n  proof (induct xs ys rule: list.rel_induct)\n    case (Cons x' xs y' ys)\n    then show ?case\n      using assms unfolding bi_unique_alt_def2 by (auto simp: rel_fun_def)\n  qed simp\nqed\n\nlemma subseteq_multiset_transfer[transfer_rule]:\n  assumes [transfer_rule]: \"bi_unique R\" \"right_total R\"\n  shows \"(rel_fun (rel_mset R) (rel_fun (rel_mset R) (=)))\n    (\\<lambda>M N. filter_mset (Domainp R) M \\<subseteq># filter_mset (Domainp R) N) (\\<subseteq>#)\"\nproof -\n  have count_filter_mset_less:\n    \"(\\<forall>a. count (filter_mset (Domainp R) M) a \\<le> count (filter_mset (Domainp R) N) a) \\<longleftrightarrow>\n     (\\<forall>a \\<in> {x. Domainp R x}. count M a \\<le> count N a)\" for M and N by auto\n  show ?thesis unfolding subseteq_mset_def count_filter_mset_less\n    by transfer_prover\nqed\n\nlemma sum_mset_transfer[transfer_rule]:\n  \"R 0 0 \\<Longrightarrow> rel_fun R (rel_fun R R) (+) (+) \\<Longrightarrow> (rel_fun (rel_mset R) R) sum_mset sum_mset\"\n  using sum_list_transfer[of R] unfolding rel_fun_def rel_mset_def by auto\n\nlemma Sigma_mset_transfer[transfer_rule]:\n  \"(rel_fun (rel_mset R) (rel_fun (rel_fun R (rel_mset S)) (rel_mset (rel_prod R S))))\n     Sigma_mset Sigma_mset\"\n  by (unfold Sigma_mset_def) transfer_prover\n\n\nsubsection \\<open>Even More about Multisets\\<close>\n\nsubsubsection \\<open>Multisets and Functions\\<close>\n\nlemma range_image_mset:\n  assumes \"set_mset Ds \\<subseteq> range f\"\n  shows \"Ds \\<in> range (image_mset f)\"\nproof -\n  have \"\\<forall>D. D \\<in># Ds \\<longrightarrow> (\\<exists>C. f C = D)\"\n    using assms by blast\n  then obtain f_i where\n    f_p: \"\\<forall>D. D \\<in># Ds \\<longrightarrow> (f (f_i D) = D)\"\n    by metis\n  define Cs where\n    \"Cs \\<equiv> image_mset f_i Ds\"\n  from f_p Cs_def have \"image_mset f Cs = Ds\"\n    by auto\n  then show ?thesis\n    by blast\nqed\n\n\nsubsubsection \\<open>Multisets and Lists\\<close>\n\nlemma length_sorted_list_of_multiset[simp]: \"length (sorted_list_of_multiset A) = size A\"\n  by (metis mset_sorted_list_of_multiset size_mset)\n\ndefinition list_of_mset :: \"'a multiset \\<Rightarrow> 'a list\" where\n  \"list_of_mset m = (SOME l. m = mset l)\"\n\n\n\nlemma mset_list_of_mset[simp]: \"mset (list_of_mset m) = m\"\n  by (metis (mono_tags, lifting) ex_mset list_of_mset_def someI_ex)\n\nlemma length_list_of_mset[simp]: \"length (list_of_mset A) = size A\"\n  unfolding list_of_mset_def by (metis (mono_tags) ex_mset size_mset someI_ex)\n\nlemma range_mset_map:\n  assumes \"set_mset Ds \\<subseteq> range f\"\n  shows \"Ds \\<in> range (\\<lambda>Cl. mset (map f Cl))\"\nproof -\n  have \"Ds \\<in> range (image_mset f)\"\n    by (simp add: assms range_image_mset)\n  then obtain Cs where Cs_p: \"image_mset f Cs = Ds\"\n    by auto\n  define Cl where \"Cl = list_of_mset Cs\"\n  then have \"mset Cl = Cs\"\n    by auto\n  then have \"image_mset f (mset Cl) = Ds\"\n    using Cs_p by auto\n  then have \"mset (map f Cl) = Ds\"\n    by auto\n  then show ?thesis\n    by auto\nqed\n\nlemma list_of_mset_empty[iff]: \"list_of_mset m = [] \\<longleftrightarrow> m = {#}\"\n  by (metis (mono_tags, lifting) ex_mset list_of_mset_def mset_zero_iff_right someI_ex)\n\nlemma in_mset_conv_nth: \"(x \\<in># mset xs) = (\\<exists>i<length xs. xs ! i = x)\"\n  by (auto simp: in_set_conv_nth)\n\nlemma in_mset_sum_list:\n  assumes \"L \\<in># LL\"\n  assumes \"LL \\<in> set Ci\"\n  shows \"L \\<in># sum_list Ci\"\n  using assms by (induction Ci) auto\n\nlemma in_mset_sum_list2:\n  assumes \"L \\<in># sum_list Ci\"\n  obtains LL where\n    \"LL \\<in> set Ci\"\n    \"L \\<in># LL\"\n  using assms by (induction Ci) auto\n\n(* TODO: Make [simp]. *)\nlemma in_mset_sum_list_iff: \"a \\<in># sum_list \\<A> \\<longleftrightarrow> (\\<exists>A \\<in> set \\<A>. a \\<in># A)\"\n  by (metis in_mset_sum_list in_mset_sum_list2)\n\nlemma subseteq_list_Union_mset:\n  assumes \"length Ci = n\"\n  assumes \"length CAi = n\"\n  assumes \"\\<forall>i<n.  Ci ! i \\<subseteq># CAi ! i \"\n  shows \"\\<Sum>\\<^sub># (mset Ci) \\<subseteq># \\<Sum>\\<^sub># (mset CAi)\"\n  using assms proof (induction n arbitrary: Ci CAi)\n  case 0\n  then show ?case by auto\nnext\n  case (Suc n)\n  from Suc have \"\\<forall>i<n. tl Ci ! i \\<subseteq># tl CAi ! i\"\n    by (simp add: nth_tl)\n  hence \"\\<Sum>\\<^sub>#(mset (tl Ci)) \\<subseteq># \\<Sum>\\<^sub>#(mset (tl CAi))\" using Suc by auto\n  moreover\n  have \"hd Ci \\<subseteq># hd CAi\" using Suc\n    by (metis hd_conv_nth length_greater_0_conv zero_less_Suc)\n  ultimately\n  show \"\\<Sum>\\<^sub>#(mset Ci) \\<subseteq># \\<Sum>\\<^sub>#(mset CAi)\"\n    using Suc by (cases Ci; cases CAi) (auto intro: subset_mset.add_mono)\nqed\n\nlemma same_mset_distinct_iff:\n  \\<open>mset M = mset M' \\<Longrightarrow> distinct M \\<longleftrightarrow> distinct M'\\<close>\n  by (fact mset_eq_imp_distinct_iff)\n\n\nsubsubsection \\<open>More on Multisets and Functions\\<close>\n\nlemma subseteq_mset_size_eql: \"X \\<subseteq># Y \\<Longrightarrow> size Y = size X \\<Longrightarrow> X = Y\"\n  using mset_subset_size subset_mset_def by fastforce\n\nlemma image_mset_of_subset_list:\n  assumes \"image_mset \\<eta> C' = mset lC\"\n  shows \"\\<exists>qC'. map \\<eta> qC' = lC \\<and> mset qC' = C'\"\n  using assms apply (induction lC arbitrary: C')\n  subgoal by simp\n  subgoal by (fastforce dest!: msed_map_invR intro: exI[of _ \\<open>_ # _\\<close>])\n  done\n\nlemma image_mset_of_subset:\n  assumes \"A \\<subseteq># image_mset \\<eta> C'\"\n  shows \"\\<exists>A'. image_mset \\<eta> A' = A \\<and> A' \\<subseteq># C'\"\nproof -\n  define C where \"C = image_mset \\<eta> C'\"\n\n  define lA where \"lA = list_of_mset A\"\n  define lD where \"lD = list_of_mset (C-A)\"\n  define lC where \"lC = lA @ lD\"\n\n  have \"mset lC = C\"\n    using C_def assms unfolding lD_def lC_def lA_def by auto\n  then have \"\\<exists>qC'. map \\<eta> qC' = lC \\<and> mset qC' = C'\"\n    using assms image_mset_of_subset_list unfolding C_def by metis\n  then obtain qC' where qC'_p: \"map \\<eta> qC' = lC \\<and> mset qC' = C'\"\n    by auto\n  let ?lA' = \"take (length lA) qC'\"\n  have m: \"map \\<eta> ?lA' = lA\"\n    using qC'_p lC_def\n    by (metis append_eq_conv_conj take_map)\n  let ?A' = \"mset ?lA'\"\n\n  have \"image_mset \\<eta> ?A' = A\"\n    using m using lA_def\n    by (metis (full_types) ex_mset list_of_mset_def mset_map someI_ex)\n  moreover have \"?A' \\<subseteq># C'\"\n    using qC'_p unfolding lA_def\n    using mset_take_subseteq by blast\n  ultimately show ?thesis by blast\nqed\n\n\n\nlemma Melem_subseteq_Union_mset[simp]:\n  assumes \"x \\<in># T\"\n  shows \"x \\<subseteq># \\<Sum>\\<^sub>#T\"\n  using assms sum_mset.remove by force\n\nlemma Melem_subset_eq_sum_list[simp]:\n  assumes \"x \\<in># mset T\"\n  shows \"x \\<subseteq># sum_list T\"\n  using assms by (metis mset_subset_eq_add_left sum_mset.remove sum_mset_sum_list)\n\nlemma less_subset_eq_Union_mset[simp]:\n  assumes \"i < length CAi\"\n  shows \"CAi ! i \\<subseteq># \\<Sum>\\<^sub>#(mset CAi)\"\nproof -\n  from assms have \"CAi ! i \\<in># mset CAi\"\n    by auto\n  then show ?thesis\n    by auto\nqed\n\nlemma less_subset_eq_sum_list[simp]:\n  assumes \"i < length CAi\"\n  shows \"CAi ! i \\<subseteq># sum_list CAi\"\nproof -\n  from assms have \"CAi ! i \\<in># mset CAi\"\n    by auto\n  then show ?thesis\n    by auto\nqed\n\n\nsubsubsection \\<open>More on Multiset Order\\<close>\n\nlemma less_multiset_doubletons:\n  assumes\n    \"y < t \\<or> y < s\"  \n    \"x < t \\<or> x < s\" \n  shows \n    \"{#y, x#} < {#t, s#}\" \n  unfolding less_multiset\\<^sub>D\\<^sub>M\nproof (intro exI)\n  let ?X = \"{#t, s#}\"\n  let ?Y = \"{#y, x#}\"\n  show \"?X \\<noteq> {#} \\<and> ?X \\<subseteq># {#t, s#} \\<and> {#y, x#} = {#t, s#} - ?X + ?Y\n    \\<and> (\\<forall>k. k \\<in># ?Y \\<longrightarrow> (\\<exists>a. a \\<in># ?X \\<and> k < a))\"\n    using add_eq_conv_diff assms by auto\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/Nested_Multisets_Ordinals/Multiset_More.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8333245870332531, "lm_q2_score": 0.8459424431344437, "lm_q1q2_score": 0.7049446370789114}}
{"text": "(* Author: Tobias Nipkow *)\n\nsection \\<open>Creating Balanced Trees\\<close>\n\ntheory Balance\nimports\n  Complex_Main\n  \"~~/src/HOL/Library/Tree\"\nbegin\n\n(* mv *)\n\ntext \\<open>The lemmas about \\<open>floor\\<close> and \\<open>ceiling\\<close> of \\<open>log 2\\<close> should be generalized\nfrom 2 to \\<open>n\\<close> and should be made executable. In the end they should be moved\nto theory \\<open>Log_Nat\\<close> and \\<open>floorlog\\<close> should be replaced.\\<close>\n\nlemma floor_log_nat_ivl: fixes b n k :: nat\nassumes \"b \\<ge> 2\" \"b^n \\<le> k\" \"k < b^(n+1)\"\nshows \"floor (log b (real k)) = int(n)\"\nproof -\n  have \"k \\<ge> 1\"\n    using assms(1,2) one_le_power[of b n] by linarith\n  show ?thesis\n  proof(rule floor_eq2)\n    show \"int n \\<le> log b k\"\n      using assms(1,2) \\<open>k \\<ge> 1\\<close>\n      by(simp add: powr_realpow le_log_iff of_nat_power[symmetric] del: of_nat_power)\n  next\n    have \"real k < b powr (real(n + 1))\" using assms(1,3)\n      by (simp only: powr_realpow) (metis of_nat_less_iff of_nat_power)\n    thus \"log b k < real_of_int (int n) + 1\"\n      using assms(1) \\<open>k \\<ge> 1\\<close> by(simp add: log_less_iff add_ac)\n  qed\nqed\n\nlemma ceil_log_nat_ivl: fixes b n k :: nat\nassumes \"b \\<ge> 2\" \"b^n < k\" \"k \\<le> b^(n+1)\"\nshows \"ceiling (log b (real k)) = int(n)+1\"\nproof(rule ceiling_eq)\n  show \"int n < log b k\"\n    using assms(1,2)\n    by(simp add: powr_realpow less_log_iff of_nat_power[symmetric] del: of_nat_power)\nnext\n  have \"real k \\<le> b powr (real(n + 1))\"\n    using assms(1,3)\n    by (simp only: powr_realpow) (metis of_nat_le_iff of_nat_power)\n  thus \"log b k \\<le> real_of_int (int n) + 1\"\n    using assms(1,2) by(simp add: log_le_iff add_ac)\nqed\n\nlemma ceil_log2_div2: assumes \"n \\<ge> 2\"\nshows \"ceiling(log 2 (real n)) = ceiling(log 2 ((n-1) div 2 + 1)) + 1\"\nproof cases\n  assume \"n=2\"\n  thus ?thesis by simp\nnext\n  let ?m = \"(n-1) div 2 + 1\"\n  assume \"n\\<noteq>2\"\n  hence \"2 \\<le> ?m\"\n    using assms by arith\n  then obtain i where i: \"2 ^ i < ?m\" \"?m \\<le> 2 ^ (i + 1)\"\n    using ex_power_ivl2[of 2 ?m] by auto\n  have \"n \\<le> 2*?m\"\n    by arith\n  also have \"2*?m \\<le> 2 ^ ((i+1)+1)\"\n    using i(2) by simp\n  finally have *: \"n \\<le> \\<dots>\" .\n  have \"2^(i+1) < n\"\n    using i(1) by (auto simp add: less_Suc_eq_0_disj)\n  from ceil_log_nat_ivl[OF _ this *] ceil_log_nat_ivl[OF _ i]\n  show ?thesis by simp\nqed\n\nlemma floor_log2_div2: fixes n :: nat assumes \"n \\<ge> 2\"\nshows \"floor(log 2 n) = floor(log 2 (n div 2)) + 1\"\nproof cases\n  assume \"n=2\"\n  thus ?thesis by simp\nnext\n  let ?m = \"n div 2\"\n  assume \"n\\<noteq>2\"\n  hence \"1 \\<le> ?m\"\n    using assms by arith\n  then obtain i where i: \"2 ^ i \\<le> ?m\" \"?m < 2 ^ (i + 1)\"\n    using ex_power_ivl1[of 2 ?m] by auto\n  have \"2^(i+1) \\<le> 2*?m\"\n    using i(1) by simp\n  also have \"2*?m \\<le> n\"\n    by arith\n  finally have *: \"2^(i+1) \\<le> \\<dots>\" .\n  have \"n < 2^(i+1+1)\"\n    using i(2) by simp\n  from floor_log_nat_ivl[OF _ * this] floor_log_nat_ivl[OF _ i]\n  show ?thesis by simp\nqed\n\n(* end of mv *)\n\nfun bal :: \"'a list \\<Rightarrow> nat \\<Rightarrow> 'a tree * 'a list\" where\n\"bal xs n = (if n=0 then (Leaf,xs) else\n (let m = n div 2;\n      (l, ys) = bal xs m;\n      (r, zs) = bal (tl ys) (n-1-m)\n  in (Node l (hd ys) r, zs)))\"\n\ndeclare bal.simps[simp del]\n\ndefinition balance_list :: \"'a list \\<Rightarrow> 'a tree\" where\n\"balance_list xs = fst (bal xs (length xs))\"\n\ndefinition balance_tree :: \"'a tree \\<Rightarrow> 'a tree\" where\n\"balance_tree = balance_list o inorder\"\n\nlemma bal_simps:\n  \"bal xs 0 = (Leaf, xs)\"\n  \"n > 0 \\<Longrightarrow>\n   bal xs n =\n  (let m = n div 2;\n      (l, ys) = bal xs m;\n      (r, zs) = bal (tl ys) (n-1-m)\n  in (Node l (hd ys) r, zs))\"\nby(simp_all add: bal.simps)\n\ntext\\<open>The following lemmas take advantage of the fact\nthat \\<open>bal xs n\\<close> yields a result even if \\<open>n > length xs\\<close>.\\<close>\n  \nlemma size_bal: \"bal xs n = (t,ys) \\<Longrightarrow> size t = n\"\nproof(induction xs n arbitrary: t ys rule: bal.induct)\n  case (1 xs n)\n  thus ?case\n    by(cases \"n=0\")\n      (auto simp add: bal_simps Let_def split: prod.splits)\nqed\n\nlemma bal_inorder:\n  \"\\<lbrakk> bal xs n = (t,ys); n \\<le> length xs \\<rbrakk>\n  \\<Longrightarrow> inorder t = take n xs \\<and> ys = drop n xs\"\nproof(induction xs n arbitrary: t ys rule: bal.induct)\n  case (1 xs n) show ?case\n  proof cases\n    assume \"n = 0\" thus ?thesis using 1 by (simp add: bal_simps)\n  next\n    assume [arith]: \"n \\<noteq> 0\"\n    let ?n1 = \"n div 2\" let ?n2 = \"n - 1 - ?n1\"\n    from \"1.prems\" obtain l r xs' where\n      b1: \"bal xs ?n1 = (l,xs')\" and\n      b2: \"bal (tl xs') ?n2 = (r,ys)\" and\n      t: \"t = \\<langle>l, hd xs', r\\<rangle>\"\n      by(auto simp: Let_def bal_simps split: prod.splits)\n    have IH1: \"inorder l = take ?n1 xs \\<and> xs' = drop ?n1 xs\"\n      using b1 \"1.prems\" by(intro \"1.IH\"(1)) auto\n    have IH2: \"inorder r = take ?n2 (tl xs') \\<and> ys = drop ?n2 (tl xs')\"\n      using b1 b2 IH1 \"1.prems\" by(intro \"1.IH\"(2)) auto\n    have \"drop (n div 2) xs \\<noteq> []\" using \"1.prems\"(2) by simp\n    hence \"hd (drop ?n1 xs) # take ?n2 (tl (drop ?n1 xs)) = take (?n2 + 1) (drop ?n1 xs)\"\n      by (metis Suc_eq_plus1 take_Suc)\n    hence *: \"inorder t = take n xs\" using t IH1 IH2\n      using take_add[of ?n1 \"?n2+1\" xs] by(simp)\n    have \"n - n div 2 + n div 2 = n\" by simp\n    hence \"ys = drop n xs\" using IH1 IH2 by (simp add: drop_Suc[symmetric])\n    thus ?thesis using * by blast\n  qed\nqed\n\ncorollary inorder_balance_list: \"inorder(balance_list xs) = xs\"\nusing bal_inorder[of xs \"length xs\"]\nby (metis balance_list_def order_refl prod.collapse take_all)\n\ncorollary inorder_balance_tree[simp]: \"inorder(balance_tree t) = inorder t\"\nby(simp add: balance_tree_def inorder_balance_list)\n\ncorollary size_balance_list[simp]: \"size(balance_list xs) = length xs\"\nby (metis inorder_balance_list length_inorder)\n\ncorollary size_balance_tree[simp]: \"size(balance_tree t) = size t\"\nby(simp add: balance_tree_def inorder_balance_list)\n\nlemma min_height_bal:\n  \"bal xs n = (t,ys) \\<Longrightarrow> min_height t = nat(floor(log 2 (n + 1)))\"\nproof(induction xs n arbitrary: t ys rule: bal.induct)\n  case (1 xs n) show ?case\n  proof cases\n    assume \"n = 0\" thus ?thesis\n      using \"1.prems\" by (simp add: bal_simps)\n  next\n    assume [arith]: \"n \\<noteq> 0\"\n    from \"1.prems\" obtain l r xs' where\n      b1: \"bal xs (n div 2) = (l,xs')\" and\n      b2: \"bal (tl xs') (n - 1 - n div 2) = (r,ys)\" and\n      t: \"t = \\<langle>l, hd xs', r\\<rangle>\"\n      by(auto simp: bal_simps Let_def split: prod.splits)\n    let ?log1 = \"nat (floor(log 2 (n div 2 + 1)))\"\n    let ?log2 = \"nat (floor(log 2 (n - 1 - n div 2 + 1)))\"\n    have IH1: \"min_height l = ?log1\" using \"1.IH\"(1) b1 by simp\n    have IH2: \"min_height r = ?log2\" using \"1.IH\"(2) b1 b2 by simp\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 \"n - 1 - n div 2 + 1 \\<le> n div 2 + 1\" by arith\n    hence le: \"?log2 \\<le> ?log1\"\n      by(simp add: nat_mono floor_mono)\n    have \"min_height t = min ?log1 ?log2 + 1\" by (simp add: t IH1 IH2)\n    also have \"\\<dots> = ?log2 + 1\" using le by (simp add: min_absorb2)\n    also have \"n - 1 - n div 2 + 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  \"bal xs n = (t,ys) \\<Longrightarrow> height t = nat \\<lceil>log 2 (n + 1)\\<rceil>\"\nproof(induction xs n arbitrary: t ys rule: bal.induct)\n  case (1 xs n) show ?case\n  proof cases\n    assume \"n = 0\" thus ?thesis\n      using \"1.prems\" by (simp add: bal_simps)\n  next\n    assume [arith]: \"n \\<noteq> 0\"\n    from \"1.prems\" obtain l r xs' where\n      b1: \"bal xs (n div 2) = (l,xs')\" and\n      b2: \"bal (tl xs') (n - 1 - n div 2) = (r,ys)\" and\n      t: \"t = \\<langle>l, hd xs', r\\<rangle>\"\n      by(auto simp: bal_simps Let_def split: prod.splits)\n    let ?log1 = \"nat \\<lceil>log 2 (n div 2 + 1)\\<rceil>\"\n    let ?log2 = \"nat \\<lceil>log 2 (n - 1 - n div 2 + 1)\\<rceil>\"\n    have IH1: \"height l = ?log1\" using \"1.IH\"(1) b1 by simp\n    have IH2: \"height r = ?log2\" using \"1.IH\"(2) b1 b2 by simp\n    have 0: \"log 2 (n div 2 + 1) \\<ge> 0\" by auto\n    have \"n - 1 - n div 2 + 1 \\<le> n div 2 + 1\" by arith\n    hence le: \"?log2 \\<le> ?log1\"\n      by(simp add: nat_mono ceiling_mono del: nat_ceiling_le_eq)\n    have \"height t = max ?log1 ?log2 + 1\" by (simp add: t IH1 IH2)\n    also have \"\\<dots> = ?log1 + 1\" using le by (simp add: max_absorb1)\n    also have \"\\<dots> = nat \\<lceil>log 2 (n div 2 + 1) + 1\\<rceil>\" using 0 by linarith\n    also have \"\\<dots> = nat \\<lceil>log 2 (n + 1)\\<rceil>\"\n      using ceil_log2_div2[of \"n+1\"] by (simp)\n    finally show ?thesis .\n  qed\nqed\n\nlemma balanced_bal:\n  assumes \"bal xs n = (t,ys)\" shows \"balanced t\"\nunfolding balanced_def\nusing height_bal[OF assms] min_height_bal[OF assms]\nby linarith\n\nlemma height_balance_list:\n  \"height (balance_list xs) = nat \\<lceil>log 2 (length xs + 1)\\<rceil>\"\nby (metis balance_list_def height_bal prod.collapse)\n\ncorollary height_balance_tree:\n  \"height (balance_tree t) = nat(ceiling(log 2 (size t + 1)))\"\nby(simp add: balance_tree_def height_balance_list)\n\ncorollary balanced_balance_list[simp]: \"balanced (balance_list xs)\"\nby (metis balance_list_def balanced_bal prod.collapse)\n\ncorollary balanced_balance_tree[simp]: \"balanced (balance_tree t)\"\nby (simp add: balance_tree_def)\n\nlemma wbalanced_bal: \"bal xs n = (t,ys) \\<Longrightarrow> wbalanced t\"\nproof(induction xs n arbitrary: t ys rule: bal.induct)\n  case (1 xs n)\n  show ?case\n  proof cases\n    assume \"n = 0\"\n    thus ?thesis\n      using \"1.prems\" by(simp add: bal_simps)\n  next\n    assume \"n \\<noteq> 0\"\n    with \"1.prems\" obtain l ys r zs where\n      rec1: \"bal xs (n div 2) = (l, ys)\" and\n      rec2: \"bal (tl ys) (n - 1 - n div 2) = (r, zs)\" and\n      t: \"t = \\<langle>l, hd ys, r\\<rangle>\"\n      by(auto simp add: bal_simps Let_def split: prod.splits)\n    have l: \"wbalanced l\" using \"1.IH\"(1)[OF \\<open>n\\<noteq>0\\<close> refl rec1] .\n    have \"wbalanced r\" using \"1.IH\"(2)[OF \\<open>n\\<noteq>0\\<close> refl rec1[symmetric] refl rec2] .\n    with l t size_bal[OF rec1] size_bal[OF rec2]\n    show ?thesis by auto\n  qed\nqed\n\nlemma wbalanced_balance_tree: \"wbalanced (balance_tree t)\"\nby(simp add: balance_tree_def balance_list_def)\n  (metis prod.collapse wbalanced_bal)\n\nhide_const (open) bal\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/Balance.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424373085145, "lm_q2_score": 0.8333245911726382, "lm_q1q2_score": 0.704944635725703}}
{"text": "(*  Author: Lukas Bulwahn <lukas.bulwahn-at-gmail.com> *)\n\nsection \\<open>Cardinality of Number Partitions\\<close>\n\ntheory Card_Number_Partitions\nimports Number_Partition\nbegin\n\nsubsection \\<open>The Partition Function\\<close>\n\nfun Partition :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\"\nwhere\n  \"Partition 0 0 = 1\"\n| \"Partition 0 (Suc k) = 0\"\n| \"Partition (Suc m) 0 = 0\"\n| \"Partition (Suc m) (Suc k) = Partition m k + Partition (m - k) (Suc k)\"\n\nlemma Partition_less:\n  assumes \"m < k\"\n  shows \"Partition m k = 0\"\nusing assms by (induct m k rule: Partition.induct) auto\n\nlemma Partition_sum_Partition_diff:\n  assumes \"k \\<le> m\"\n  shows \"Partition m k = (\\<Sum>i\\<le>k. Partition (m - k) i)\"\nusing assms by (induct m k rule: Partition.induct) auto\n\nlemma Partition_parts1:\n  \"Partition (Suc m) (Suc 0) = 1\"\nby (induct m) auto\n\nlemma Partition_diag:\n  \"Partition (Suc m) (Suc m) = 1\"\nby (induct m) auto\n\nlemma Partition_diag1:\n  \"Partition (Suc (Suc m)) (Suc m) = 1\"\nby (induct m) auto\n\nlemma Partition_parts2:\n  shows \"Partition m 2 = m div 2\"\nproof (induct m rule: nat_less_induct)\n  fix m\n  assume hypothesis: \"\\<forall>n<m. Partition n 2 = n div 2\"\n  have \"(m = 0 \\<or> m = 1) \\<or> m \\<ge> 2\" by auto\n  from this show \"Partition m 2 = m div 2\"\n  proof\n    assume \"m = 0 \\<or> m = 1\"\n    from this show ?thesis by (auto simp add: numerals(2))\n  next\n    assume \"2 \\<le> m\"\n    from this obtain m' where m': \"m = Suc (Suc m')\" by (metis add_2_eq_Suc le_Suc_ex)\n    from hypothesis this have \"Partition m' 2 = m' div 2\" by simp\n    from this m' show ?thesis\n      using Partition_parts1 Partition.simps(4)[of \"Suc m'\" \"Suc 0\"] div2_Suc_Suc\n      by (simp add: numerals(2) del: Partition.simps)\n  qed\nqed\n\nsubsection \\<open>Cardinality of Number Partitions\\<close>\n\nlemma set_rewrite1:\n  \"{p. p partitions Suc m \\<and> sum p {..Suc m} = Suc k \\<and> p 1 \\<noteq> 0}\n    = (\\<lambda>p. p(1 := p 1 + 1)) ` {p. p partitions m \\<and> sum p {..m} = k}\" (is \"?S = ?T\")\nproof\n  {\n    fix p\n    assume assms: \"p partitions Suc m\" \"sum p {..Suc m} = Suc k\" \"0 < p 1\"\n    have \"p(1 := p 1 - 1) partitions m\"\n      using assms by (metis partitions_remove1 diff_Suc_1)\n    moreover have \"(\\<Sum>i\\<le>m. (p(1 := p 1 - 1)) i) = k\"\n      using assms by (metis count_remove1 diff_Suc_1)\n    ultimately have \"p(1 := p 1 - 1) \\<in> {p. p partitions m \\<and> sum p {..m} = k}\" by simp\n    moreover have \"p = p(1 := p 1 - 1, 1 := (p(1 := p 1 - 1)) 1 + 1)\"\n      using \\<open>0 < p 1\\<close> by auto\n    ultimately have \"p \\<in> (\\<lambda>p. p(1 := p 1 + 1)) ` {p. p partitions m \\<and> sum p {..m} = k}\" by blast\n  }\n  from this show \"?S \\<subseteq> ?T\" by blast\nnext\n  {\n    fix p\n    assume assms: \"p partitions m\" \"sum p {..m} = k\"\n    have \"(p(1 := p 1 + 1)) partitions Suc m\" (is ?g1)\n      using assms by (metis partitions_insert1 Suc_eq_plus1 zero_less_one)\n    moreover have \"sum (p(1 := p 1 + 1)) {..Suc m} = Suc k\" (is ?g2)\n      using assms by (metis count_insert1 Suc_eq_plus1)\n    moreover have \"(p(1 := p 1 + 1)) 1 \\<noteq> 0\" (is ?g3) by auto\n    ultimately have \"?g1 \\<and> ?g2 \\<and> ?g3\" by simp\n  }\n  from this show \"?T \\<subseteq> ?S\" by auto\nqed\n\nlemma set_rewrite2:\n  \"{p. p partitions m \\<and> sum p {..m} = k \\<and> p 1 = 0}\n    = (\\<lambda>p. (\\<lambda>i. p (i - 1))) ` {p. p partitions (m - k) \\<and> sum p {..m - k} = k}\"\n  (is \"?S = ?T\")\nproof\n  {\n    fix p\n    assume assms: \"p partitions m\" \"sum p {..m} = k\" \"p 1 = 0\"\n    have \"(\\<lambda>i. p (i + 1)) partitions m - k\"\n      using assms partitions_decrease1 by blast\n    moreover from assms have \"sum (\\<lambda>i. p (i + 1)) {..m - k} = k\"\n      using assms count_decrease1 by blast\n    ultimately have \"(\\<lambda>i. p (i + 1)) \\<in> {p. p partitions m - k \\<and> sum p {..m - k} = k}\" by simp\n    moreover have \"p = (\\<lambda>i. p ((i - 1) + 1))\"\n    proof (rule ext)\n      fix i show \"p i = p (i - 1 + 1)\"\n        using assms by (cases i) (auto elim!: partitionsE)\n    qed\n    ultimately have \"p \\<in> (\\<lambda>p. (\\<lambda>i. p (i - 1))) ` {p. p partitions m - k \\<and> sum p {..m - k} = k}\" by auto\n  }\n  from this show \"?S \\<subseteq> ?T\" by auto\nnext\n   {\n     fix p\n     assume assms: \"p partitions m - k\" \"sum p {..m - k} = k\"\n     from assms have \"(\\<lambda>i. p (i - 1)) partitions m\" (is ?g1)\n       using partitions_increase1 by blast\n     moreover from assms have \"(\\<Sum>i\\<le>m. p (i - 1)) = k\" (is ?g2)\n       using count_increase1 by blast\n     moreover from assms have \"p 0 = 0\" (is ?g3)\n       by (auto elim!: partitionsE)\n     ultimately have \"?g1 \\<and> ?g2 \\<and> ?g3\" by simp\n   }\n   from this show \"?T \\<subseteq> ?S\" by auto\nqed\n\ntheorem card_partitions_k_parts:\n  \"card {p. p partitions n \\<and> (\\<Sum>i\\<le>n. p i) = k} = Partition n k\"\nproof (induct n k rule: Partition.induct)\n  case 1\n  have eq: \"{p. p = (\\<lambda>x. 0) \\<and> p 0 = 0} = {(\\<lambda>x. 0)}\" by auto\n  show \"card {p. p partitions 0 \\<and> sum p {..0} = 0} = Partition 0 0\"\n    by (simp add: partitions_zero eq)\nnext\n  case (2 k)\n  have eq: \"{p. p = (\\<lambda>x. 0) \\<and> p 0 = Suc k} = {}\" by auto\n  show \"card {p. p partitions 0 \\<and> sum p {..0} = Suc k} = Partition 0 (Suc k)\"\n    by (simp add: partitions_zero eq)\nnext\n  case (3 m)\n  have eq: \"{p. p partitions Suc m \\<and> sum p {..Suc m} = 0} = {}\"\n    by (fastforce elim!: partitionsE simp add: le_Suc_eq)\n  from this show \"card {p. p partitions Suc m \\<and> sum p {..Suc m} = 0} = Partition (Suc m) 0\"\n    by (simp only: Partition.simps card_empty)\nnext\n  case (4 m k)\n  let ?set1 = \"{p. p partitions Suc m \\<and> sum p {..Suc m} = Suc k \\<and> p 1 \\<noteq> 0}\"\n  let ?set2 = \"{p. p partitions Suc m \\<and> sum p {..Suc m} = Suc k \\<and> p 1 = 0}\"\n  have \"finite {p. p partitions Suc m}\"\n    by (simp add: finite_partitions)\n  from this have finite_sets: \"finite ?set1\" \"finite ?set2\" by simp+\n  have set_eq: \"{p. p partitions Suc m \\<and> sum p {..Suc m} = Suc k} = ?set1 \\<union> ?set2\" by auto\n  have disjoint: \"?set1 \\<inter> ?set2 = {}\" by auto\n  have inj1: \"inj_on (\\<lambda>p. p(1 := p 1 + 1)) {p. p partitions m \\<and> sum p {..m} = k}\"\n    by (auto intro!: inj_onI) (metis diff_Suc_1 fun_upd_idem_iff fun_upd_upd)\n  have inj2: \"inj_on (\\<lambda>p i. p (i - 1)) {p. p partitions m - k \\<and> sum p {..m - k} = Suc k}\"\n    by (auto intro!: inj_onI simp add: fun_eq_iff) (metis add_diff_cancel_right')\n  have card1: \"card ?set1 = Partition m k\"\n    using inj1 4(1) by (simp only: set_rewrite1 card_image)\n  have card2: \"card ?set2 = Partition (m - k) (Suc k)\"\n    using inj2 4(2) by (simp only: set_rewrite2 card_image diff_Suc_Suc)\n  have \"card {p. p partitions Suc m \\<and> sum p {..Suc m} = Suc k} = Partition m k + Partition (m - k) (Suc k)\"\n    using finite_sets disjoint by (simp only: set_eq card_Un_disjoint card1 card2)\n  from this show \"card {p. p partitions Suc m \\<and> sum p {..Suc m} = Suc k} = Partition (Suc m) (Suc k)\"\n    by auto\nqed\n\ntheorem card_partitions:\n  \"card {p. p partitions n} = (\\<Sum>k\\<le>n. Partition n k)\"\nproof -\n  have seteq: \"{p. p partitions n} = \\<Union>((\\<lambda>k. {p. p partitions n \\<and> (\\<Sum>i\\<le>n. p i) = k}) ` {..n})\"\n    by (auto intro: partitions_parts_bounded)\n  have finite: \"\\<And>k. finite {p. p partitions n \\<and> sum p {..n} = k}\"\n    by (simp add: finite_partitions)\n  have \"card {p. p partitions n} = card (\\<Union>((\\<lambda>k. {p. p partitions n \\<and> (\\<Sum>i\\<le>n. p i) = k}) ` {..n}))\"\n    using finite by (simp add: seteq)\n  also have \"... = (\\<Sum>x\\<le>n. card {p. p partitions n \\<and> sum p {..n} = x})\"\n    using finite by (subst card_UN_disjoint) auto\n  also have \"... = (\\<Sum>k\\<le>n. Partition n k)\"\n    by (simp add: card_partitions_k_parts)\n  finally show ?thesis .\nqed\n\nlemma card_partitions_atmost_k_parts:\n  \"card {p. p partitions n \\<and> sum p {..n} \\<le> k} = Partition (n + k) k\"\nproof -\n  have \"card {p. p partitions n \\<and> sum p {..n} \\<le> k} =\n    card (\\<Union>((\\<lambda>k'. {p. p partitions n \\<and> sum p {..n} = k'}) ` {..k}))\"\n  proof -\n    have \"{p. p partitions n \\<and> sum p {..n} \\<le> k} =\n      (\\<Union>k'\\<le>k. {p. p partitions n \\<and> sum p {..n} = k'})\" by auto\n    from this show ?thesis by simp\n  qed\n  also have \"card (\\<Union>((\\<lambda>k'. {p. p partitions n \\<and> sum p {..n} = k'}) ` {..k})) =\n    sum (\\<lambda>k'. card {p. p partitions n \\<and> sum p {..n} = k'}) {..k}\"\n    using finite_partitions_k_parts by (subst card_UN_disjoint) auto\n  also have \"\\<dots> = sum (\\<lambda>k'. Partition n k') {..k}\"\n    using card_partitions_k_parts by simp\n  also have \"\\<dots> = Partition (n + k) k\"\n    using Partition_sum_Partition_diff by simp\n  finally show ?thesis .\nqed\n\nsubsection \\<open>Cardinality of Number Partitions as Multisets of Natural Numbers\\<close>\n\nlemma bij_betw_multiset_number_partition_with_size:\n  \"bij_betw count {N. number_partition n N \\<and> size N = k} {p. p partitions n \\<and> sum p {..n} = k}\"\nproof (rule bij_betw_byWitness[where f'=\"Abs_multiset\"])\n  show \"\\<forall>N\\<in>{N. number_partition n N \\<and> size N = k}. Abs_multiset (count N) = N\"\n    using count_inverse by blast\n  show \"\\<forall>p\\<in>{p. p partitions n \\<and> sum p {..n} = k}. count (Abs_multiset p) = p\"\n    by (auto simp add: multiset_def partitions_imp_finite_elements)\n  show \"count ` {N. number_partition n N \\<and> size N = k} \\<subseteq> {p. p partitions n \\<and> sum p {..n} = k}\"\n    by (auto simp add: count_partitions_iff size_nat_multiset_eq) \n  show \"Abs_multiset ` {p. p partitions n \\<and> sum p {..n} = k} \\<subseteq> {N. number_partition n N \\<and> size N = k}\"\n    using partitions_iff_Abs_multiset size_nat_multiset_eq partitions_imp_multiset by fastforce\nqed\n\nlemma bij_betw_multiset_number_partition_with_atmost_size:\n  \"bij_betw count {N. number_partition n N \\<and> size N \\<le> k} {p. p partitions n \\<and> sum p {..n} \\<le> k}\"\nproof (rule bij_betw_byWitness[where f'=\"Abs_multiset\"])\n  show \"\\<forall>N\\<in>{N. number_partition n N \\<and> size N \\<le> k}. Abs_multiset (count N) = N\"\n    using count_inverse by blast\n  show \"\\<forall>p\\<in>{p. p partitions n \\<and> sum p {..n} \\<le> k}. count (Abs_multiset p) = p\"\n    by (auto simp add: multiset_def partitions_imp_finite_elements)\n  show \"count ` {N. number_partition n N \\<and> size N \\<le> k} \\<subseteq> {p. p partitions n \\<and> sum p {..n} \\<le> k}\"\n    by (auto simp add: count_partitions_iff size_nat_multiset_eq)\n  show \"Abs_multiset ` {p. p partitions n \\<and> sum p {..n} \\<le> k} \\<subseteq> {N. number_partition n N\\<and> size N \\<le> k}\"\n    using partitions_iff_Abs_multiset size_nat_multiset_eq partitions_imp_multiset by fastforce\nqed\n\ntheorem card_number_partitions_with_atmost_k_parts:\n  shows \"card {N. number_partition n N \\<and> size N \\<le> x} = Partition (n + x) x\"\nproof -\n  have \"bij_betw count {N. number_partition n N \\<and> size N \\<le> x} {p. p partitions n \\<and> sum p {..n} \\<le> x}\"\n    by (rule bij_betw_multiset_number_partition_with_atmost_size)\n  from this have \"card {N. number_partition n N \\<and> size N \\<le> x} = card {p. p partitions n \\<and> sum p {..n} \\<le> x}\"\n    by (rule bij_betw_same_card)\n  also have \"card {p. p partitions n \\<and> sum p {..n} \\<le> x} = Partition (n + x) x\"\n    by (rule card_partitions_atmost_k_parts)\n  finally show ?thesis .\nqed\n\ntheorem card_partitions_with_k_parts:\n  \"card {N. number_partition n N \\<and> size N = k} = Partition n k\"\nproof -\n  have \"bij_betw count {N. number_partition n N \\<and> size N = k} {p. p partitions n \\<and> sum p {..n} = k}\"\n    by (rule bij_betw_multiset_number_partition_with_size)\n  from this have \"card {N. number_partition n N \\<and> size N = k} = card {p. p partitions n \\<and> sum p {..n} = k}\"\n    by (rule bij_betw_same_card)\n  also have \"\\<dots> = Partition n k\" by (rule card_partitions_k_parts)\n  finally show ?thesis .\nqed\n\nsubsection \\<open>Cardinality of Number Partitions with only 1-parts\\<close>\n\nlemma number_partition1_eq_replicate_mset:\n  \"{N. (\\<forall>n. n\\<in># N \\<longrightarrow> n = 1) \\<and> number_partition n N} = {replicate_mset n 1}\"\nproof\n  show \"{N. (\\<forall>n. n \\<in># N \\<longrightarrow> n = 1) \\<and> number_partition n N} \\<subseteq> {replicate_mset n 1}\"\n  proof\n    fix N\n    assume N: \"N \\<in> {N. (\\<forall>n. n \\<in># N \\<longrightarrow> n = 1) \\<and> number_partition n N}\"\n    have \"N = replicate_mset n 1\"\n    proof (rule multiset_eqI)\n      fix i\n      have \"count N 1 = sum_mset N\"\n      proof cases\n        assume \"N = {#}\"\n        from this show ?thesis by auto\n      next\n        assume \"N \\<noteq> {#}\"\n        from this N have \"1 \\<in># N\" by blast\n        from this N show ?thesis\n          by (auto simp add: sum_mset_sum_count sum.remove[where x=\"1\"] simp del: One_nat_def)\n      qed\n      from N this show \"count N i = count (replicate_mset n 1) i\"\n        unfolding number_partition_def by (auto intro: count_inI)\n    qed\n    from this show \"N \\<in> {replicate_mset n 1}\" by simp\n  qed\nnext\n  show \"{replicate_mset n 1} \\<subseteq> {N. (\\<forall>n. n \\<in># N \\<longrightarrow> n = 1) \\<and> number_partition n N}\"\n    unfolding number_partition_def by auto\nqed\n\n\n\nlemma card_number_partitions_with_only_parts_1_eq_0:\n  assumes \"x < n\"\n  shows \"card {N. (\\<forall>n. n\\<in># N \\<longrightarrow> n = 1) \\<and> number_partition n N \\<and> size N \\<le> x} = 0\" (is \"card ?N = _\")\nproof -\n  have \"\\<forall>N \\<in> {N. (\\<forall>n. n \\<in># N \\<longrightarrow> n = 1) \\<and> number_partition n N}. size N = n\"\n    unfolding number_partition1_eq_replicate_mset by simp\n  from this number_partition1_eq_replicate_mset\\<open>x < n\\<close> have \"?N = {}\" by auto\n  from this show ?thesis by (simp only: card_empty)\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_Number_Partitions/Card_Number_Partitions.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424373085146, "lm_q2_score": 0.8333245891029456, "lm_q1q2_score": 0.7049446339748623}}
{"text": "\nsection \\<open>lr-Multisemigroups\\<close>\n\ntheory LR_Multisemigroup\n  imports Main\n\nbegin\n\ntext \\<open>A multimagma is a set equipped with a multioperation. Multioperations are nothing but ternary relations.\\<close>\n\nclass multimagma = \n  fixes mcomp :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a set\" (infixl \"\\<odot>\" 70) \n\nbegin\n\ntext \\<open>We define left and right units.\\<close>\n\ndefinition \"munitl e = ((\\<exists>x. x \\<in> e \\<odot> x) \\<and> (\\<forall>x y. y \\<in> e \\<odot> x \\<longrightarrow> y = x))\"\n\ndefinition \"munitr e = ((\\<exists>x. x \\<in> x \\<odot> e) \\<and> (\\<forall>x y. y \\<in> x \\<odot> e \\<longrightarrow> y = x))\"\n\nabbreviation \"munit e \\<equiv> (munitl e \\<or> munitr e)\"\n\ntext \\<open>We lift the multioperation to powersets\\<close>\n\ndefinition conv :: \"'a set \\<Rightarrow> 'a set \\<Rightarrow> 'a set\" (infixl \"\\<odot>\\<^sub>l\" 70) where\n  \"X \\<odot>\\<^sub>l Y = \\<Union>{x \\<odot> y |x y. x \\<in> X \\<and> y \\<in> Y}\"\n\nlemma conv_exp: \"X \\<odot>\\<^sub>l Y = {z. \\<exists>x y. z \\<in> x \\<odot> y \\<and> x \\<in> X \\<and> y \\<in> Y}\"\n  unfolding conv_def by fastforce\n\nlemma conv_distl: \"X \\<odot>\\<^sub>l \\<Union>\\<Y> = \\<Union>{X \\<odot>\\<^sub>l Y |Y. Y \\<in> \\<Y>}\"\n  unfolding conv_def by blast\n\nlemma conv_distr: \"\\<Union>\\<X> \\<odot>\\<^sub>l Y  = \\<Union>{X \\<odot>\\<^sub>l Y |X. X \\<in> \\<X>}\"\n  unfolding conv_def by blast\n\nend\n\ntext \\<open>A multimagma is unital if every element has a left and a right unit.\\<close>\n\nclass unital_multimagma_var = multimagma + \n  assumes munitl_ex: \"\\<forall>x.\\<exists>e. munitl e \\<and> e \\<odot> x \\<noteq> {}\"\n  assumes munitr_ex: \"\\<forall>x.\\<exists>e. munitr e \\<and> x \\<odot> e \\<noteq> {}\"\n\nbegin\n\nlemma munitl_ex_var: \"\\<forall>x.\\<exists>e. munitl e \\<and> x \\<in> e \\<odot> x\"\n  by (metis equals0I local.munitl_def local.munitl_ex)\n\nlemma unitl: \"\\<Union>{e \\<odot> x |e. munitl e} = {x}\"\n  apply safe\n  apply (simp add: multimagma.munitl_def)\n  apply simp\n  by (metis munitl_ex_var)\n\nlemma munitr_ex_var: \"\\<forall>x.\\<exists>e. munitr e \\<and> x \\<in> x \\<odot> e\"\n  by (metis equals0I local.munitr_def local.munitr_ex)\n\nlemma unitr: \"\\<Union>{x \\<odot> e |e. munitr e} = {x}\"\n  apply safe\n  apply (simp add: multimagma.munitr_def)\n  apply simp\n  by (metis munitr_ex_var)\n\ntext \\<open>In a unital multimagma, elements can have several left or right units.\\<close>\n\nlemma \"\\<forall>x.\\<exists>!e. munit e \\<and> e \\<odot> x = {x}\"\n  nitpick\n  oops\n\nlemma \"\\<forall>x.\\<exists>!e. munit e \\<and> x \\<odot> e = {x}\"\n  nitpick \n  oops\n\nend\n\ntext \\<open>Here is an alternative definition.\\<close>\n\nclass unital_multimagma = multimagma + \n  fixes E :: \"'a set\"\n  assumes El: \"\\<Union>{e \\<odot> x |e. e \\<in> E} = {x}\"\n  and Er: \"\\<Union>{x \\<odot> e |e. e \\<in> E} = {x}\"\n \nbegin\n\nlemma E1: \"\\<forall>e \\<in> E. (\\<forall>x y. y \\<in> e \\<odot> x \\<longrightarrow> y = x)\"\n  using local.El by fastforce\n\nlemma E2: \"\\<forall>e \\<in> E. (\\<forall>x y. y \\<in> x \\<odot> e \\<longrightarrow> y = x)\"\n  using local.Er by fastforce\n\ntext \\<open>Units are \"orthogonal\" idempotents.\\<close>\n\nlemma unit_id: \"\\<forall>e \\<in> E. e \\<in> e \\<odot> e\"\n  using E1 local.Er by fastforce\n\nlemma unit_id_eq: \"\\<forall>e \\<in> E. e \\<odot> e = {e}\"\n  by (simp add: E1 equalityI subsetI unit_id)\n\nlemma unit_comp: \"e\\<^sub>1 \\<in> E \\<Longrightarrow> e\\<^sub>2 \\<in> E \\<Longrightarrow>  e\\<^sub>1 \\<odot> e\\<^sub>2 \\<noteq> {} \\<Longrightarrow> e\\<^sub>1 = e\\<^sub>2\"\n  using E1 E2 by blast\n\nlemma unit_comp_iff: \"e\\<^sub>1 \\<in> E \\<Longrightarrow> e\\<^sub>2 \\<in> E \\<Longrightarrow> ((e\\<^sub>1 \\<odot> e\\<^sub>2 \\<noteq> {}) = (e\\<^sub>1 = e\\<^sub>2))\"\n  using unit_comp unit_id by auto\n\nlemma El11: \"\\<forall>x.\\<exists>e \\<in> E. x \\<in> e \\<odot> x\"\n  using local.El by auto\n\nlemma El12: \"\\<forall>x.\\<exists>e \\<in> E. e \\<odot> x = {x}\"\n  using E1 El11 by fastforce\n\nlemma Er11: \"\\<forall>x.\\<exists>e \\<in> E. x \\<in> x \\<odot> e\"\n  using local.Er by auto\n\nlemma Er12: \"\\<forall>x.\\<exists>e \\<in> E. x \\<odot> e = {x}\"\n  using Er Er11 by fastforce\n\nlemma \"\\<forall>e \\<in> E.\\<exists>x. x \\<in> e \\<odot> x\"\n  using unit_id by blast\n\nlemma \"\\<forall>e \\<in> E.\\<exists>x. x \\<in> x \\<odot> e\"\n  using unit_id by blast\n\nsublocale unital_multimagma_var\n  apply unfold_locales\n  unfolding munitl_def munitr_def\n  using E1 El11 apply fastforce\n  using E2 Er11 by fastforce\n\ntext \\<open>Now we know that the two definitions are equivalent.\\<close>\n\ntext \\<open>The next two lemmas show that the set of units is a left and right unit of composition at powerset level.\\<close>\n\nlemma conv_unl: \"E \\<odot>\\<^sub>l X = X\"\n  unfolding conv_def\n  apply safe\n  using E1 apply blast\n  using El12 by fastforce\n\nlemma conv_unr: \"X \\<odot>\\<^sub>l E = X\"\n  unfolding conv_def\n  apply safe\n  using E2 apply blast\n  using Er12 by fastforce\n\nend\n\ntext \\<open>A multisemigroup is an associative multimagma.\\<close>\n\nclass multisemigroup = multimagma +\n  assumes assoc: \"\\<Union>{x \\<odot> v |v. v \\<in> y \\<odot> z} = \\<Union>{v \\<odot> z |v. v \\<in> x \\<odot> y}\"\n\nbegin\n\nlemma assoc_exp: \"(\\<exists>v. w \\<in> x \\<odot> v \\<and> v \\<in> y \\<odot> z) = (\\<exists>v. v \\<in> x \\<odot> y \\<and> w \\<in> v \\<odot> z)\" \nproof-\n  have \"(\\<exists>v. w \\<in> x \\<odot> v \\<and> v \\<in> y \\<odot> z) = (w \\<in> \\<Union>{x \\<odot> v |v. v \\<in> y \\<odot> z})\"\n    by blast\n  also have \"\\<dots> = (w \\<in> \\<Union>{v \\<odot> z |v. v \\<in> x \\<odot> y})\"\n    using local.assoc by auto\n  finally show ?thesis\n    by blast\nqed\n\nlemma assoc_var: \"{x} \\<odot>\\<^sub>l (y \\<odot> z) = (x \\<odot> y) \\<odot>\\<^sub>l {z}\"\n  unfolding conv_def assoc_exp\n  using local.assoc by force\n\ntext \\<open>Associativity lifts to powersets.\\<close>\n\nlemma conv_assoc: \"X \\<odot>\\<^sub>l (Y \\<odot>\\<^sub>l Z) = (X \\<odot>\\<^sub>l Y) \\<odot>\\<^sub>l Z\"\n  unfolding conv_exp\n  apply clarsimp\n  using assoc_exp by blast\n\nend\n\ntext \\<open>A multimonoid is a unital multisemigroup.\\<close>\n\nclass multimonoid = multisemigroup + unital_multimagma\n\nbegin\n\ntext \\<open>In a multimonoid, left and right units are unique for each element.\\<close>\n\nlemma munits_uniquel: \"\\<forall>x.\\<exists>!e. munit e \\<and> e \\<odot> x = {x}\"\n  apply safe\n  using local.E1 local.El12 local.munitr_ex_var apply blast\n  apply (metis insertI1 local.Er11 local.assoc_exp local.unit_comp_iff multimagma.munitl_def)\n  apply (metis insertI1 local.assoc_exp multimagma.munitl_def multimagma.munitr_def)\n  apply (metis insertI1 local.assoc_exp multimagma.munitl_def multimagma.munitr_def)\n  by (metis insertI1 local.El11 local.assoc_exp local.unit_comp multimagma.munitr_def)\n\nlemma munits_uniquer: \"\\<forall>x.\\<exists>!e. munit e \\<and> x \\<odot> e = {x}\"\n  apply safe\n  using local.E1 local.Er12 local.munitr_ex_var apply blast\n  apply (metis insertI1 local.assoc_exp local.munitr_ex_var multimagma.munitl_def multimagma.munitr_def)\n  apply (metis insertI1 local.assoc_exp local.munitl_def multimagma.munitr_def)\n  apply (metis insertI1 local.assoc_exp local.munitl_def multimagma.munitr_def)\n  by (metis insertI1 local.El11 local.assoc_exp local.unit_comp_iff multimagma.munitr_def)\n\ntext \\<open>In a monoid, there is of course one single unit, and our definition of many units reduces to this one.\\<close>\n\nlemma units_unique: \"(\\<forall>x y. x \\<odot> y \\<noteq> {}) \\<Longrightarrow> \\<exists>!e. munit e\"\n  apply safe\n  using local.munitl_ex_var apply blast\n  apply (metis local.Er11 local.unit_comp multimagma.munitl_def)\n  apply (metis local.Er11 local.munitl_ex_var local.unit_comp multimagma.munitl_def multimagma.munitr_def)\n  apply (metis local.Er11 local.munitl_ex_var local.unit_comp multimagma.munitl_def multimagma.munitr_def)\n  by (metis local.El11 local.unit_comp multimagma.munitr_def)\n\nlemma \"x \\<odot> x = {x} \\<Longrightarrow> x \\<in> E\"\n  nitpick\n  oops\n\nend\n\n\n\ntext \\<open>Next we define lr-multisemigroups with source and target maps.\\<close>\n\nclass lr_multimagma = multimagma + \nfixes ll :: \"'a \\<Rightarrow> 'a\"\n  and rr :: \"'a \\<Rightarrow> 'a\"\n  assumes Dlr: \"x \\<odot> y \\<noteq> {} \\<Longrightarrow> rr x = ll y\"\n  and l_absorb [simp]: \"ll x \\<odot> x = {x}\" \n  and r_absorb [simp]: \"x \\<odot> rr x = {x}\"\n\nbegin\n\nlemma rl_compat [simp]: \"rr (ll x) = ll x\"\n  by (simp add: local.Dlr)\n\nlemma lr_compat [simp]: \"ll (rr x) = rr x\"\n  by (metis insert_not_empty local.Dlr local.r_absorb)\n\nlemma ll_retract [simp]: \"ll (ll x) = ll x\"\n  by (metis lr_compat rl_compat)\n\nlemma rr_retract [simp]: \"rr (rr x) = rr x\"\n  by (metis lr_compat rl_compat)\n\nlemma lr_fix: \"(rr x = x) = (ll x = x)\"\n  by (metis lr_compat rl_compat)\n\ndefinition lfix :: \"'a set\" where\n  \"lfix = {x. ll x = x}\"\n\ndefinition rfix :: \"'a set\" where\n  \"rfix = {x. rr x = x}\"\n\nlemma lr_fix_set: \"{x. ll x = x} = {x. rr x = x}\"\n  using lr_fix by simp\n\nlemma lrfix_set: \"lfix = rfix\"\n  by (simp add: lfix_def rfix_def lr_fix_set)\n\nlemma l_idem [simp]: \"ll x \\<odot> ll x = {ll x}\"\n  by (metis local.r_absorb rl_compat)\n\nlemma r_idem [simp]:  \"rr x \\<odot> rr x = {rr x}\"\n  by (metis local.l_absorb lr_compat)\n\nlemma lr_comm: \"rr x \\<odot> ll y = ll y \\<odot> rr x\"\n  using local.Dlr by fastforce\n\nlemma l_weak_twisted: \"\\<Union>{ll u \\<odot> x |u. u \\<in> x \\<odot> y} \\<subseteq> x \\<odot> ll y\"\n  apply (clarsimp simp:  Sup_least) \n  by (metis equals0D local.Dlr local.l_absorb local.r_absorb rl_compat)\n\nlemma \"\\<Union>{ll u \\<odot> x |u. u \\<in> x \\<odot> y} = x \\<odot> ll y\"\n  nitpick\n  oops\n\nlemma r_weak_twisted: \"\\<Union>{x \\<odot> rr u |u. u \\<in> y \\<odot> x} \\<subseteq> rr y \\<odot> x\"\n  apply (clarsimp simp: Sup_least)\n  by (metis empty_iff local.Dlr local.l_absorb local.r_absorb lr_compat)\n\nlemma \"\\<Union>{x \\<odot> rr u |u. u \\<in> y \\<odot> x} = rr y \\<odot> x\"\n  nitpick\n  oops\n\nlemma l_comm: \"ll x \\<odot> ll y = ll y \\<odot> ll x\"\n  using local.Dlr by force\n\nlemma r_comm: \"rr x \\<odot> rr y = rr y \\<odot> rr x\"\n  using local.Dlr by fastforce\n\nlemma l_export: \"ll ` (ll x \\<odot> y) = ll x \\<odot> ll y\"\n  using local.Dlr by force\n\nlemma r_export: \"rr ` (x \\<odot> rr y) = rr x \\<odot> rr y\"\n  by (metis image_empty image_insert local.Dlr local.r_absorb lr_compat r_idem)\n\nlemma lr_prop: \"(rr x = ll y) = (rr x \\<odot> ll y \\<noteq> {})\"\n  by (metis empty_not_insert l_idem local.Dlr lr_compat rl_compat)\n  \nlemma weak_local_var: \"rr x \\<odot> ll y = {} \\<Longrightarrow> x \\<odot> y = {}\"\n  using local.Dlr lr_prop by blast\n\nlemma \"x \\<odot> y = {} \\<Longrightarrow> rr x \\<odot> ll y = {}\"\n  nitpick\n  oops\n\nlemma \"(ll x \\<odot> ll y \\<noteq> {}) = (ll x = ll y)\"\n  using local.Dlr by fastforce\n\nlemma \"(rr x \\<odot> rr y \\<noteq> {}) = (rr x = rr y)\"\n  using local.Dlr by fastforce\n\ntext \\<open>The set of all sources (and targets) are units at powerset level.\\<close>\n\nlemma conv_unl: \"lfix \\<odot>\\<^sub>l X = X\"\n  unfolding conv_def lfix_def\n  apply safe \n   apply (metis empty_iff insert_iff local.Dlr local.l_absorb)\n  apply simp \n  using ll_retract local.l_absorb by blast\n\nlemma conv_unr: \"X \\<odot>\\<^sub>l rfix = X\" \n  unfolding conv_exp rfix_def\n  apply safe\n   apply (metis empty_iff insert_iff local.Dlr local.r_absorb)\n  apply simp\n  using local.r_absorb by fastforce\n\ntext \\<open>We lift source and target maps to the powerset level and prove laws of modal powerset quantales.\\<close>\n\ndefinition LL :: \"'a set \\<Rightarrow> 'a set\" where\n  \"LL = image ll\"\n\ndefinition RR :: \"'a set \\<Rightarrow> 'a set\" where\n  \"RR = image rr\"\n\nlemma LR_compat [simp]: \"LL (RR X) = RR X\"\n  by (metis LL_def RR_def image_cong image_image lr_compat)\n\nlemma RL_compat [simp]: \"RR (LL X) = LL X\"\n  by (metis LL_def RR_def image_cong image_image rl_compat)\n\nlemma LL_absorp: \"LL X \\<odot>\\<^sub>l X = X\"\n  unfolding conv_exp LL_def\n  apply safe\n  using local.Dlr apply fastforce\n  by (metis imageI insertI1 local.l_absorb)\n\nlemma RR_absorp: \"X \\<odot>\\<^sub>l RR X = X\"\n  unfolding conv_exp RR_def\n  apply safe\n  apply (metis empty_iff local.Dlr local.r_absorb lr_compat singletonD)\n  by force\n\nlemma LL_Sup_pres: \"LL (\\<Union>\\<X>) = \\<Union>{LL X |X. X \\<in> \\<X>}\"\n  unfolding LL_def by blast\n\nlemma RR_Sup_pres: \"RR (\\<Union>\\<X>) = \\<Union>{RR X |X. X \\<in> \\<X>}\"\n  unfolding RR_def by blast\n\nlemma LR_comm: \"LL X \\<odot>\\<^sub>l RR Y = RR Y \\<odot>\\<^sub>l LL X\"\n  unfolding LL_def RR_def conv_exp\n  by (metis (no_types, lifting) empty_iff imageE local.Dlr lr_compat rl_compat)\n\nlemma LL_comm: \"LL X \\<odot>\\<^sub>l LL Y = LL Y \\<odot>\\<^sub>l LL X\"\n  by (metis LR_comm RL_compat)\n\nlemma LL_comm: \"RR X \\<odot>\\<^sub>l RR Y = RR Y \\<odot>\\<^sub>l RR X\"\n  by (metis LR_comm LR_compat)\n\nlemma RR_subid: \"LL X \\<subseteq> lfix\"\n  by (simp add: LL_def image_subsetI lfix_def)\n\nlemma RR_subid: \"RR X \\<subseteq> rfix\"\n  by (simp add: RR_def image_subsetI rfix_def)\n\nlemma LL_export: \"LL (LL X \\<odot>\\<^sub>l Y) = LL X \\<odot>\\<^sub>l LL Y\"\n  unfolding conv_exp LL_def\n  apply safe\n  apply (metis empty_iff image_eqI local.Dlr local.l_absorb local.r_absorb singletonD singletonI)\n  using l_export by fastforce\n\nlemma RR_export: \"RR (X \\<odot>\\<^sub>l RR Y) = RR X \\<odot>\\<^sub>l RR Y\"\n  unfolding conv_exp RR_def\n  apply safe\n  apply (metis empty_iff image_eqI local.Dlr local.r_absorb r_idem singletonD singletonI)\n  using r_export by fastforce\n\nend\n\nclass lr_multisemigroup = lr_multimagma + multisemigroup\n\nbegin\n\nlemma l_comp_aux: \"v \\<in> x \\<odot> y \\<Longrightarrow> ll v = ll x\"\nproof-\n  assume hyp: \"v \\<in> x \\<odot> y\"\n  hence \"v \\<in> ll v \\<odot> v \\<and> v \\<in> x \\<odot> y\"\n    by simp\n  hence \"\\<exists>w. w \\<in> ll v \\<odot> x \\<and> v \\<in> w \\<odot> y\"\n    using local.assoc by blast\n  hence \"rr (ll v) = ll x\"\n    using local.Dlr by fastforce\n  thus ?thesis\n    by simp\nqed\n\nlemma l_comp: \"LL (x \\<odot> y) \\<subseteq> {ll x}\"\n  by (simp add: LL_def image_subsetI l_comp_aux)\n\nlemma l_comp_cond: \"x \\<odot> y \\<noteq> {} \\<Longrightarrow> LL (x \\<odot> y) = {ll x}\"\n  by (metis empty_is_image l_comp local.LL_def subset_singleton_iff)\n \nlemma r_comp_aux: \"v \\<in> x \\<odot> y \\<Longrightarrow> rr v = rr y\"\nproof-\n  assume hyp: \"v \\<in> x \\<odot> y\"\n  hence \"v \\<in> v \\<odot> rr v \\<and> v \\<in> x \\<odot> y\"\n    by simp\n  hence \"\\<exists>w. w \\<in> y \\<odot> rr v \\<and> v \\<in> x \\<odot> w\"\n    using local.assoc by blast\n  hence \"ll (rr v) = rr y\"\n    using local.Dlr by fastforce\n  thus ?thesis\n    by simp\nqed\n\nlemma r_comp: \"RR (x \\<odot> y) \\<subseteq> {rr y}\"\n  by (simp add: RR_def image_subsetI r_comp_aux)\n\nlemma r_comp_cond: \"x \\<odot> y \\<noteq> {} \\<Longrightarrow> RR (x \\<odot> y) = {rr y}\"\n  by (metis empty_is_image local.RR_def r_comp subset_singleton_iff)\n\nlemma l_weak_local:  \"LL (x \\<odot> y) \\<subseteq> LL (x \\<odot> ll y)\"\n  by (metis insert_not_empty l_comp l_comp_cond local.Dlr local.r_absorb order_class.order.eq_iff)\n\nlemma l_local_cond:  \"x \\<odot> y \\<noteq> {} \\<Longrightarrow> LL (x \\<odot> y) = LL (x \\<odot> ll y)\"\n  by (metis insert_not_empty l_comp_cond local.Dlr local.r_absorb)\n\nlemma r_weak_local:  \"RR (x \\<odot> y) \\<subseteq> RR (rr x \\<odot> y)\"\n  using RR_def local.Dlr r_comp_cond by fastforce\n\nlemma r_local_cond:  \"x \\<odot> y \\<noteq> {} \\<Longrightarrow> RR (x \\<odot> y) = RR (rr x \\<odot> y)\"\n  using r_comp r_comp_cond r_weak_local by fastforce\n\nlemma r_twisted_aux: \"u \\<in> x \\<odot> y \\<Longrightarrow> (rr x \\<odot> y = y \\<odot> rr u)\"\n  using local.Dlr r_comp_aux by fastforce\n\nlemma r_twisted_cond: \"x \\<odot> y \\<noteq> {} \\<Longrightarrow> rr x \\<odot> y = \\<Union>{y \\<odot> rr u |u. u \\<in> x \\<odot> y}\"\n  by (simp add: Setcompr_eq_image local.Dlr r_comp_aux)\n\nlemma l_twisted_aux: \"u \\<in> x \\<odot> y \\<Longrightarrow> (x \\<odot> ll y = ll u \\<odot> x)\"\n  by (metis l_comp_aux local.Dlr local.l_absorb local.r_absorb)\n\nlemma l_twisted_cond: \"x \\<odot> y \\<noteq> {} \\<Longrightarrow> x \\<odot> ll y = \\<Union>{ll u \\<odot> x |u. u \\<in> x \\<odot> y}\"\n  apply standard\n  using l_twisted_aux apply fastforce\n  by (simp add: local.l_weak_twisted)\n\nlemma \"x \\<in> y \\<odot> z \\<Longrightarrow> x' \\<in> y \\<odot> z \\<Longrightarrow> ll x = ll x'\"\n  by (simp add: l_comp_aux)\n\nlemma coherence_iff: \"(\\<forall>x y. (x \\<odot> y \\<noteq> {}) = (rr x = ll y)) = (\\<forall>v x y z. v \\<in> x \\<odot> y \\<longrightarrow> y \\<odot> z \\<noteq> {} \\<longrightarrow> v \\<odot> z \\<noteq> {})\"\n  by (metis (full_types) insert_not_empty local.Dlr local.l_absorb local.r_absorb r_comp_aux singletonI)\n\nlemma \"LL (x \\<odot> y) = LL (x \\<odot> ll y)\"\n  nitpick\n  oops\n\nlemma r_local:  \"RR (x \\<odot> y) = RR (rr x \\<odot> y)\"\n  nitpick \n  oops\n\n  text \\<open>Again we can lift to properties of modal semirings.\\<close>\n\nlemma LL_weak_local: \"LL (X \\<odot>\\<^sub>l Y) \\<subseteq> LL (X \\<odot>\\<^sub>l LL Y)\"\n  unfolding conv_exp LL_def image_def\n  using l_comp_aux local.Dlr local.r_absorb by blast\n\nlemma RR_weak_local: \"RR (X \\<odot>\\<^sub>l  Y) \\<subseteq> RR (RR X \\<odot>\\<^sub>l Y)\"\n  unfolding conv_exp RR_def image_def\n  using r_comp_aux r_twisted_aux by fastforce\n\nend\n\nclass coherent_lr_multisemigroup = lr_multisemigroup +\n  assumes coherence: \"(x \\<odot> y \\<noteq> {}) = (rr x = ll y)\"\n\nbegin\n\ntext \\<open>Coherence implies locality.\\<close>\n\nlemma l_local:  \"LL (x \\<odot> y) = LL (x \\<odot> ll y)\"\n  by (metis local.coherence local.l_local_cond local.ll_retract)\n\nlemma r_local:  \"RR (x \\<odot> y) = RR (rr x \\<odot> y)\"\n  by (metis local.coherence local.r_local_cond local.rr_retract)\n\nlemma r_twisted: \"rr x \\<odot> y = \\<Union>{y \\<odot> rr u |u. u \\<in> x \\<odot> y}\"\n  by (metis Setcompr_eq_image Union_empty image_empty local.coherence local.r_twisted_cond local.rr_retract)\n\nlemma l_twisted: \"x \\<odot> ll y = \\<Union>{ll u \\<odot> x |u. u \\<in> x \\<odot> y}\"\n  by (metis Setcompr_eq_image Union_empty image_empty local.coherence local.l_twisted_cond local.ll_retract)\n\nlemma \"LL (x \\<odot> y) = {ll x}\"\n  nitpick\n  oops\n\nlemma \"RR (x \\<odot> y) = {rr x}\"\n  nitpick\n  oops\n\nlemma local_var: \"x \\<odot> y = {} \\<Longrightarrow> rr x \\<odot> ll y = {}\"\n  by (metis local.coherence local.ll_retract local.rr_retract)\n\nlemma local_var_eq: \"(x \\<odot> y = {}) = (rr x \\<odot> ll y = {})\"\n  by (meson local.weak_local_var local_var)\n\nlemma LL_local: \"LL (X \\<odot>\\<^sub>l Y) = LL (X \\<odot>\\<^sub>l LL Y)\"\n  apply (rule antisym)\n  apply (simp add: local.LL_weak_local)\n  unfolding conv_exp LL_def image_def\n  using l_twisted local.l_comp_aux by fastforce\n\nlemma RR_local: \"RR (X \\<odot>\\<^sub>l Y) = RR (RR X \\<odot>\\<^sub>l Y)\"\n  apply (rule antisym)\n  apply (simp add: local.RR_weak_local)\n  unfolding conv_exp RR_def image_def\n  apply clarsimp\n  using local.r_comp_aux r_twisted by fastforce\n\nend\n\ntext \\<open>Next we define local lr-multimagmas\\<close>\n\nclass local_lr_multimagma = lr_multimagma +\n  assumes l_local: \"LL (x \\<odot> ll y) \\<subseteq> LL (x \\<odot> y)\"\n  and r_local: \"LL (rr x \\<odot> y) \\<subseteq>  LL (x \\<odot> y)\"\n\nbegin\n\ntext \\<open>Locality implies coherence, which is the composition pattern of categories.\\<close>\n\nlemma  coherence: \"(x \\<odot> y \\<noteq> {}) = (rr x = ll y)\"\n  apply standard\n  apply (simp add: local.Dlr)\n  by (metis image_empty local.LL_def local.l_export local.l_idem local.lr_prop local.r_local singleton_insert_inj_eq subset_antisym)\n\nend\n\ntext \\<open>Finally, we try to derive the implication used in the definition of lr-multisemigroups, but can't.\\<close>\n\nclass st_multimagma = multimagma + \n  fixes \\<sigma> :: \"'a \\<Rightarrow> 'a\"\n  and \\<tau> :: \"'a \\<Rightarrow> 'a\"\n  assumes st_compat [simp]: \"\\<sigma> (\\<tau> x) = \\<tau> x\"\n  and ts_compat [simp]: \"\\<tau> (\\<sigma> x) = \\<sigma> x\"\n  and s_absorb [simp]: \"\\<sigma> x \\<odot> x = {x}\" \n  and t_absorb [simp]: \"x \\<odot> \\<tau> x = {x}\"\n  and st_comm: \"\\<sigma> x \\<odot> \\<tau> y = \\<tau> y \\<odot> \\<sigma> x\"\n  and s_weak_local: \"\\<sigma> ` (x \\<odot> y) \\<subseteq> \\<sigma> ` (x \\<odot> \\<sigma> y)\"\n  and t_weak_local: \"\\<tau> ` (x \\<odot> y) \\<subseteq> \\<sigma> ` (\\<tau> x \\<odot> y)\"\nand l_export: \"\\<sigma> ` (\\<sigma> x \\<odot> y) = \\<sigma> x \\<odot> \\<sigma> y\"\nand  r_export: \"\\<tau> ` (x \\<odot> \\<tau> y) = \\<tau> x \\<odot> \\<tau> y\"\n \nbegin\n\nlemma \"x \\<odot> y \\<noteq> {} \\<Longrightarrow> \\<tau> x \\<odot> \\<sigma> y \\<noteq> {}\"\n  by (metis empty_is_image empty_subsetI local.s_weak_local local.t_weak_local subset_antisym)\n\nlemma \"x \\<odot> y = {} \\<Longrightarrow> \\<tau> x \\<odot> \\<sigma> y = {}\"\n  nitpick\n  oops\n\nlemma \"x \\<odot> y \\<noteq> {} \\<Longrightarrow> \\<tau> x = \\<sigma> y\"\n  nitpick\n  oops\n\nlemma lr_prop: \"(\\<tau> x = \\<sigma> y) \\<Longrightarrow> (\\<tau> x \\<odot> \\<sigma> y \\<noteq> {})\"\n  by (metis empty_not_insert local.t_absorb local.ts_compat)\n\nlemma lr_prop: \"(\\<tau> x = \\<sigma> y) = (\\<tau> x \\<odot> \\<sigma> y \\<noteq> {})\"\n  nitpick \n  oops\n\n\nlemma s_retract [simp]: \"\\<sigma> (\\<sigma> x) = \\<sigma> x\"\n  by (metis local.st_compat local.ts_compat)\n\nlemma t_retract [simp]: \"\\<tau> (\\<tau> x) = \\<tau> x\"\n  by (metis local.st_compat local.ts_compat)\n\nlemma st_fix: \"(\\<tau> x = x) = (\\<sigma> x = x)\"\n  by (metis local.st_compat local.ts_compat)\n\nlemma s_idem [simp]: \"\\<sigma> x \\<odot> \\<sigma> x = {\\<sigma> x}\"\n  by (metis local.s_absorb s_retract)\n\nlemma t_idem [simp]:  \"\\<tau> x \\<odot> \\<tau> x = {\\<tau> x}\"\n  by (metis local.t_absorb t_retract)\n\nlemma s_weak_twisted: \"\\<Union>{\\<sigma> u \\<odot> x |u. u \\<in> x \\<odot> y} \\<subseteq> x \\<odot> \\<sigma> y\"\n  apply (clarsimp simp:  Sup_least) \n  nitpick\n  oops\n\nlemma t_weak_twisted: \"\\<Union>{x \\<odot> \\<tau> u |u. u \\<in> y \\<odot> x} \\<subseteq> \\<tau> y \\<odot> x\"\n  apply (clarsimp simp: Sup_least)\n  nitpick\n  oops\n\nlemma s_comm: \"\\<sigma> x \\<odot> \\<sigma> y = \\<sigma> y \\<odot> \\<sigma> x\"\n  by (metis local.st_comm local.ts_compat)\n\nlemma t_comm: \"\\<tau> x \\<odot> \\<tau> y = \\<tau> y \\<odot> \\<tau> x\"\n  by (metis local.st_comm local.st_compat)\n\n\nend\n\nclass st_multisemigroup = st_multimagma + multisemigroup\n\nbegin\n\nlemma \"x \\<odot> y = {} \\<Longrightarrow> \\<tau> x \\<odot> \\<sigma> y = {}\"\n  nitpick\n  oops\n\nlemma \"x \\<odot> y \\<noteq> {} \\<Longrightarrow> \\<tau> x = \\<sigma> y\"\n  nitpick\n  oops\n\nlemma lr_prop: \"(\\<tau> x = \\<sigma> y) \\<Longrightarrow> (\\<tau> x \\<odot> \\<sigma> y \\<noteq> {})\"\n  by (metis empty_not_insert local.t_absorb local.ts_compat)\n\nlemma lr_prop: \"(\\<tau> x = \\<sigma> y) = (\\<tau> x \\<odot> \\<sigma> y \\<noteq> {})\"\n  nitpick \n  oops\n\nend\n\nclass local_st_multisemigroup = st_multisemigroup +\n  assumes s_local: \"\\<sigma> ` (x \\<odot> \\<sigma> y) \\<subseteq> \\<sigma> ` (x \\<odot> y)\"\n  and t_local: \" \\<sigma> ` (\\<tau> x \\<odot> y) \\<subseteq> \\<tau> ` (x \\<odot> y)\"\n\nbegin\n\nlemma \"x \\<odot> y = {} \\<Longrightarrow> \\<tau> x \\<odot> \\<sigma> y = {}\"\n  by (metis image_empty local.l_export local.st_compat local.t_local subset_empty)\n\nlemma \"(x \\<odot> y = {}) = (\\<tau> x \\<odot> \\<sigma> y = {})\"\n  by (metis empty_is_image local.l_export local.st_compat local.t_local local.t_weak_local subset_antisym)\n\nlemma \"\\<tau> x \\<odot> \\<sigma> y \\<noteq> {} \\<Longrightarrow> \\<tau> x = \\<sigma> y\"\n  nitpick\n  oops\n\nend\n\nend\n\n\n\n", "meta": {"author": "gstruth", "repo": "lr-multisemigroups", "sha": "bf73bba23427fcca34352e96dee88a8e9efc2a52", "save_path": "github-repos/isabelle/gstruth-lr-multisemigroups", "path": "github-repos/isabelle/gstruth-lr-multisemigroups/lr-multisemigroups-bf73bba23427fcca34352e96dee88a8e9efc2a52/LR_Multisemigroup.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.872347368040789, "lm_q2_score": 0.8080672227971212, "lm_q1q2_score": 0.7049153150070986}}
{"text": "(* Title:      Residuated Boolean Algebras\n   Author:     Victor Gomes <vborgesferreiragomes1 at sheffield.ac.uk>\n   Maintainer: Georg Struth <g.struth@sheffield.ac.uk> \n*)\n\nsection \\<open>Residuated Boolean Algebras\\<close>\n\ntheory Residuated_Boolean_Algebras\n  imports Residuated_Lattices\nbegin\n\nsubsection \\<open>Conjugation on Boolean Algebras\\<close>\n\ntext \\<open>\n  Similarly, as in the previous section, we define the conjugation for\n  arbitrary residuated functions on boolean algebras.\n\\<close>\n\ncontext boolean_algebra\nbegin\n\nlemma inf_bot_iff_le: \"x \\<sqinter> y = \\<bottom> \\<longleftrightarrow> x \\<le> -y\"\n  by (metis le_iff_inf inf_sup_distrib1 inf_top_right sup_bot.left_neutral sup_compl_top compl_inf_bot inf.assoc inf_bot_right)\n\nlemma le_iff_inf_bot: \"x \\<le> y \\<longleftrightarrow> x \\<sqinter> -y = \\<bottom>\"\n  by (metis inf_bot_iff_le compl_le_compl_iff inf_commute)\n  \nlemma indirect_eq: \"(\\<And>z. x \\<le> z \\<longleftrightarrow> y \\<le> z) \\<Longrightarrow> x = y\"\n  by (metis order.eq_iff)\n\ntext \\<open>\n  Let $B$ be a boolean algebra. The maps $f$ and $g$ on $B$ are\n  a pair of conjugates if and only if for all $x, y \\in B$,\n  $f(x) \\sqcap y = \\bot \\Leftrightarrow x \\sqcap g(t) = \\bot$.\n\\<close>\n  \ndefinition conjugation_pair :: \"('a \\<Rightarrow> 'a) \\<Rightarrow> ('a \\<Rightarrow> 'a) \\<Rightarrow> bool\" where\n  \"conjugation_pair f g \\<equiv> \\<forall>x y. f(x) \\<sqinter> y = \\<bottom> \\<longleftrightarrow> x \\<sqinter> g(y) = \\<bottom>\"\n\nlemma conjugation_pair_commute: \"conjugation_pair f g \\<Longrightarrow> conjugation_pair g f\"\n  by (auto simp: conjugation_pair_def inf_commute)\n  \nlemma conjugate_iff_residuated: \"conjugation_pair f g = residuated_pair f (\\<lambda>x. -g(-x))\"\n  apply (clarsimp simp: conjugation_pair_def residuated_pair_def inf_bot_iff_le)\n  by (metis double_compl)\n\nlemma conjugate_residuated: \"conjugation_pair f g \\<Longrightarrow> residuated_pair f (\\<lambda>x. -g(-x))\"\n  by (metis conjugate_iff_residuated)\n  \nlemma residuated_iff_conjugate: \"residuated_pair f g = conjugation_pair f (\\<lambda>x. -g(-x))\"\n  apply (clarsimp simp: conjugation_pair_def residuated_pair_def inf_bot_iff_le)\n  by (metis double_compl)\n\ntext \\<open>\n  A map $f$ has a conjugate pair if and only if it is residuated.\n\\<close>\n  \nlemma conj_residuatedI1: \"\\<exists>g. conjugation_pair f g \\<Longrightarrow> residuated f\"\n  by (metis conjugate_iff_residuated residuated_def)\n  \nlemma conj_residuatedI2: \"\\<exists>g. conjugation_pair g f \\<Longrightarrow> residuated f\"\n  by (metis conj_residuatedI1 conjugation_pair_commute)\n  \nlemma exist_conjugateI[intro]: \"residuated f \\<Longrightarrow> \\<exists>g. conjugation_pair f g\"\n  by (metis residuated_def residuated_iff_conjugate)\n  \nlemma exist_conjugateI2[intro]: \"residuated f \\<Longrightarrow> \\<exists>g. conjugation_pair g f\"\n  by (metis exist_conjugateI conjugation_pair_commute)\n\ntext \\<open>\n  The conjugate of a residuated function $f$ is unique.\n\\<close>\n\nlemma unique_conjugate[intro]: \"residuated f \\<Longrightarrow> \\<exists>!g. conjugation_pair f g\"\nproof - \n  {\n    fix g h x assume \"conjugation_pair f g\" and \"conjugation_pair f h\"\n    hence \"g = h\"\n      apply (unfold conjugation_pair_def)\n      apply (rule ext)\n      apply (rule order.antisym)\n      by (metis le_iff_inf_bot inf_commute inf_compl_bot)+\n  } \n  moreover assume \"residuated f\"\n  ultimately show ?thesis by force\nqed\n  \nlemma unique_conjugate2[intro]: \"residuated f \\<Longrightarrow> \\<exists>!g. conjugation_pair g f\"\n  by (metis unique_conjugate conjugation_pair_commute)\n\ntext \\<open>\n  Since the conjugate of a residuated map is unique, we define a\n  conjugate operation.\n\\<close>\n  \ndefinition conjugate :: \"('a \\<Rightarrow> 'a) \\<Rightarrow> ('a \\<Rightarrow> 'a)\" where\n  \"conjugate f \\<equiv> THE g. conjugation_pair g f\"\n\nlemma conjugate_iff_def: \"residuated f \\<Longrightarrow> f(x) \\<sqinter> y = \\<bottom> \\<longleftrightarrow> x \\<sqinter> conjugate f y = \\<bottom>\"\n  apply (clarsimp simp: conjugate_def dest!: unique_conjugate)\n  apply (subgoal_tac \"(THE g. conjugation_pair g f) = g\")\n  apply (clarsimp simp add: conjugation_pair_def)\n  apply (rule the1_equality)\n  by (auto intro: conjugation_pair_commute)\n    \nlemma conjugateI1: \"residuated f \\<Longrightarrow> f(x) \\<sqinter> y = \\<bottom> \\<Longrightarrow> x \\<sqinter> conjugate f y = \\<bottom>\"\n  by (metis conjugate_iff_def)\n  \nlemma conjugateI2: \"residuated f \\<Longrightarrow> x \\<sqinter> conjugate f y = \\<bottom> \\<Longrightarrow> f(x) \\<sqinter> y = \\<bottom>\"\n  by (metis conjugate_iff_def)\n\ntext \\<open>\n  Few more lemmas about conjugation follow.\n\\<close>\n  \nlemma residuated_conj1: \"residuated f \\<Longrightarrow> conjugation_pair f (conjugate f)\"\n  using conjugateI1 conjugateI2 conjugation_pair_def by auto\n  \nlemma residuated_conj2: \"residuated f \\<Longrightarrow> conjugation_pair (conjugate f) f\"\n  using conjugateI1 conjugateI2 conjugation_pair_def inf_commute by auto\n  \nlemma conj_residuated: \"residuated f \\<Longrightarrow> residuated (conjugate f)\"\n  by (force dest!: residuated_conj2 intro: conj_residuatedI1)\n  \nlemma conj_involution: \"residuated f \\<Longrightarrow> conjugate (conjugate f) = f\"\n  by (metis conj_residuated residuated_conj1 residuated_conj2 unique_conjugate)\n  \nlemma residual_conj_eq: \"residuated f \\<Longrightarrow> residual (conjugate f) = (\\<lambda>x. -f(-x))\"\n  apply (unfold residual_def)\n  apply (rule the1_equality)\n  apply (rule residual_unique)\n  apply (auto intro: conj_residuated conjugate_residuated residuated_conj2)\ndone\n  \nlemma residual_conj_eq_ext: \"residuated f \\<Longrightarrow> residual (conjugate f) x = -f(-x)\"\n  by (metis residual_conj_eq)\n  \nlemma conj_iso: \"residuated f \\<Longrightarrow> x \\<le> y \\<Longrightarrow> conjugate f x \\<le> conjugate f y\"\n  by (metis conj_residuated res_iso)\n  \nlemma conjugate_strict: \"residuated f \\<Longrightarrow> conjugate f \\<bottom> = \\<bottom>\"\n  by (metis conj_residuated residuated_strict)\n\nlemma conjugate_sup: \"residuated f \\<Longrightarrow> conjugate f (x \\<squnion> y) = conjugate f x \\<squnion> conjugate f y\"\n  by (metis conj_residuated residuated_sup)\n\nlemma conjugate_subinf: \"residuated f \\<Longrightarrow> conjugate f (x \\<sqinter> y) \\<le> conjugate f x \\<sqinter> conjugate f y\"\n  by (auto simp: conj_iso)\n \ntext \\<open>\n  Next we prove some lemmas from Maddux's article. Similar lemmas have been proved in AFP entry\n  for relation algebras. They should be consolidated in the future.\n\\<close>\n\nlemma maddux1: \"residuated f \\<Longrightarrow> f(x \\<sqinter> - conjugate f(y)) \\<le> f(x) \\<sqinter> -y\"\nproof -\n  assume assm: \"residuated f\"\n  hence \"f(x \\<sqinter> - conjugate f(y)) \\<le> f x\"\n    by (metis inf_le1 res_iso)\n  moreover have \"f(x \\<sqinter> - conjugate f (y)) \\<sqinter> y = \\<bottom>\"\n    by (metis assm conjugateI2 inf_bot_iff_le inf_le2)\n  ultimately show ?thesis\n    by (metis inf_bot_iff_le le_inf_iff)\nqed\n\nlemma maddux1': \"residuated f \\<Longrightarrow> conjugate f(x \\<sqinter> -f(y)) \\<le> conjugate f(x) \\<sqinter> -y\"\n  by (metis conj_involution conj_residuated maddux1)\n  \nlemma maddux2: \"residuated f \\<Longrightarrow> f(x) \\<sqinter> y \\<le> f(x \\<sqinter> conjugate f y)\"\nproof -\n  assume resf: \"residuated f\"\n  obtain z where z_def: \"z = f(x \\<sqinter> conjugate f y)\" by auto\n  hence \"f(x \\<sqinter> conjugate f y) \\<sqinter> -z = \\<bottom>\"\n    by (metis inf_compl_bot)\n  hence \"x \\<sqinter> conjugate f y \\<sqinter> conjugate f (-z) = \\<bottom>\"\n    by (metis conjugate_iff_def resf)\n  hence \"x \\<sqinter> conjugate f (y \\<sqinter> -z) = \\<bottom>\"\n    apply (subgoal_tac \"conjugate f (y \\<sqinter> -z) \\<le> conjugate f y \\<sqinter> conjugate f (-z)\")\n    apply (metis (no_types, hide_lams) dual_order.trans inf.commute inf_bot_iff_le inf_left_commute)\n    by (metis conj_iso inf_le2 inf_top.left_neutral le_inf_iff resf)\n  hence \"f(x) \\<sqinter> y \\<sqinter> -z = \\<bottom>\"\n    by (metis conjugateI2 inf.assoc resf)\n  thus ?thesis\n    by (metis double_compl inf_bot_iff_le z_def)\nqed\n\nlemma maddux2': \"residuated f \\<Longrightarrow> conjugate f(x) \\<sqinter> y \\<le> conjugate f(x \\<sqinter> f y)\"\n  by (metis conj_involution conj_residuated maddux2)\n  \nlemma residuated_conjugate_ineq: \"residuated f \\<Longrightarrow> conjugate f x \\<le> y \\<longleftrightarrow> x \\<le> -f(-y)\"\n  by (metis conj_residuated residual_galois residual_conj_eq)\n\nlemma residuated_comp_closed: \"residuated f \\<Longrightarrow> residuated g \\<Longrightarrow> residuated (f o g)\"\n  by (auto simp add: residuated_def residuated_pair_def)\n  \nlemma conjugate_comp: \"residuated f \\<Longrightarrow> residuated g \\<Longrightarrow> conjugate (f o g) = conjugate g o conjugate f\"\nproof (rule ext, rule indirect_eq)\n  fix x y\n  assume assms: \"residuated f\" \"residuated g\" \n  have \"conjugate (f o g) x \\<le> y \\<longleftrightarrow> x \\<le> -f(g(-y))\"\n    apply (subst residuated_conjugate_ineq)\n    using assms by (auto intro!: residuated_comp_closed)\n  also have \"... \\<longleftrightarrow> conjugate g (conjugate f x) \\<le> y\"\n    using assms by (simp add: residuated_conjugate_ineq)\n  finally show \"(conjugate (f \\<circ> g) x \\<le> y) = ((conjugate g \\<circ> conjugate f) x \\<le> y)\"   \n    by auto\nqed \n\nlemma conjugate_comp_ext: \"residuated f \\<Longrightarrow> residuated g \\<Longrightarrow> conjugate (\\<lambda>x. f (g x)) x = conjugate g (conjugate f x)\"\n  using conjugate_comp by (simp add: comp_def)\n  \nend (* boolean_algebra *)\n\ncontext complete_boolean_algebra begin\n\ntext \\<open>\n  On a complete boolean algebra, it is possible to give an explicit\n  definition of conjugation.\n\\<close>\n\nlemma conjugate_eq: \"residuated f \\<Longrightarrow> conjugate f y = \\<Sqinter>{x. y \\<le> -f(-x)}\"\nproof -\n  assume assm: \"residuated f\" obtain g where g_def: \"g = conjugate f\" by auto\n  have \"g y = \\<Sqinter>{x. x \\<ge> g y}\"\n    by (auto intro!: order.antisym Inf_lower Inf_greatest)\n  also have \"... = \\<Sqinter>{x. -x \\<sqinter> g y = \\<bottom>}\"\n    by (simp add: inf_bot_iff_le)\n  also have \"... = \\<Sqinter>{x. f(-x) \\<sqinter> y = \\<bottom>}\"\n    by (metis conjugate_iff_def assm g_def)\n  finally show ?thesis\n    by (simp add: g_def le_iff_inf_bot inf_commute)\nqed\n\nend (* complete_boolean_algebra *)\n\nsubsection \\<open>Residuated Boolean Structures\\<close>\n\ntext \\<open>\n  In this section, we present various residuated structures based on\n  boolean algebras.\n  The left and right conjugation of the multiplicative operation is\n  defined, and a number of facts is derived.\n\\<close>\n\nclass residuated_boolean_algebra = boolean_algebra + residuated_pogroupoid\nbegin\n\nsubclass residuated_lgroupoid ..\n\ndefinition conjugate_l :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a\" (infixl \"\\<lhd>\" 60) where\n  \"x \\<lhd> y \\<equiv> -(-x \\<leftarrow> y)\"\n\ndefinition conjugate_r :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a\" (infixl \"\\<rhd>\" 60) where\n  \"x \\<rhd> y \\<equiv> -(x \\<rightarrow> -y)\"\n  \nlemma residual_conjugate_r: \"x \\<rightarrow> y = -(x \\<rhd> -y)\"\n  by (metis conjugate_r_def double_compl)\n  \nlemma residual_conjugate_l: \"x \\<leftarrow> y = -(-x \\<lhd> y)\"\n  by (metis conjugate_l_def double_compl)\n  \nlemma conjugation_multl: \"x\\<cdot>y \\<sqinter> z = \\<bottom> \\<longleftrightarrow> x \\<sqinter> (z \\<lhd> y) = \\<bottom>\"\n  by (metis conjugate_l_def double_compl le_iff_inf_bot resl_galois)\n\nlemma conjugation_multr: \"x\\<cdot>y \\<sqinter> z = \\<bottom> \\<longleftrightarrow> y \\<sqinter> (x \\<rhd> z) = \\<bottom>\"\n  by (metis conjugate_r_def inf_bot_iff_le le_iff_inf_bot resr_galois)\n  \nlemma conjugation_conj: \"(x \\<lhd> y) \\<sqinter> z = \\<bottom> \\<longleftrightarrow> y \\<sqinter> (z \\<rhd> x) = \\<bottom>\"\n  by (metis inf_commute conjugation_multr conjugation_multl)\n\nlemma conjugation_pair_multl [simp]: \"conjugation_pair (\\<lambda>x. x\\<cdot>y) (\\<lambda>x. x \\<lhd> y)\"\n  by (simp add: conjugation_pair_def conjugation_multl)\n  \nlemma conjugation_pair_multr [simp]: \"conjugation_pair (\\<lambda>x. y\\<cdot>x) (\\<lambda>x. y \\<rhd> x)\"\n  by (simp add: conjugation_pair_def conjugation_multr)\n  \nlemma conjugation_pair_conj [simp]: \"conjugation_pair (\\<lambda>x. y \\<lhd> x) (\\<lambda>x. x \\<rhd> y)\"\n  by (simp add: conjugation_pair_def conjugation_conj)\n  \nlemma residuated_conjl1 [simp]: \"residuated (\\<lambda>x. x \\<lhd> y)\" \n  by (metis conj_residuatedI2 conjugation_pair_multl)\n  \nlemma residuated_conjl2 [simp]: \"residuated (\\<lambda>x. y \\<lhd> x)\" \n  by (metis conj_residuatedI1 conjugation_pair_conj)\n  \nlemma residuated_conjr1 [simp]: \"residuated (\\<lambda>x. y \\<rhd> x)\" \n  by (metis conj_residuatedI2 conjugation_pair_multr)\n  \nlemma residuated_conjr2 [simp]: \"residuated (\\<lambda>x. x \\<rhd> y)\" \n  by (metis conj_residuatedI2 conjugation_pair_conj)\n  \nlemma conjugate_multr [simp]: \"conjugate (\\<lambda>x. y\\<cdot>x) = (\\<lambda>x. y \\<rhd> x)\"\n  by (metis conjugation_pair_multr residuated_conj1 residuated_multr unique_conjugate)\n  \nlemma conjugate_conjr1 [simp]: \"conjugate (\\<lambda>x. y \\<rhd> x) = (\\<lambda>x. y\\<cdot>x)\"\n  by (metis conjugate_multr conj_involution residuated_multr)\n  \nlemma conjugate_multl [simp]: \"conjugate (\\<lambda>x. x\\<cdot>y) = (\\<lambda>x. x \\<lhd> y)\"\n  by (metis conjugation_pair_multl residuated_conj1 residuated_multl unique_conjugate)\n \nlemma conjugate_conjl1 [simp]: \"conjugate (\\<lambda>x. x \\<lhd> y) = (\\<lambda>x. x\\<cdot>y)\"\nproof -\n  have \"conjugate (conjugate (\\<lambda>x. x\\<cdot>y)) = conjugate (\\<lambda>x. x \\<lhd> y)\" by simp\n  thus ?thesis\n    by (metis conj_involution[OF residuated_multl])\nqed\n\nlemma conjugate_conjl2[simp]: \"conjugate (\\<lambda>x. y \\<lhd> x) = (\\<lambda>x. x \\<rhd> y)\"\n  by (metis conjugation_pair_conj unique_conjugate residuated_conj1 residuated_conjl2)\n\nlemma conjugate_conjr2[simp]: \"conjugate (\\<lambda>x. x \\<rhd> y) = (\\<lambda>x. y \\<lhd> x)\"\nproof -\n  have \"conjugate (conjugate (\\<lambda>x. y \\<lhd> x)) = conjugate (\\<lambda>x. x \\<rhd> y)\" by simp\n  thus ?thesis\n    by (metis conj_involution[OF residuated_conjl2])\nqed\n\nlemma conjl1_iso: \"x \\<le> y \\<Longrightarrow> x \\<lhd> z \\<le> y \\<lhd> z\"\n  by (metis conjugate_l_def compl_mono resl_iso)\n\nlemma conjl2_iso: \"x \\<le> y \\<Longrightarrow> z \\<lhd> x \\<le> z \\<lhd> y\"\n  by (metis res_iso residuated_conjl2)\n\nlemma conjr1_iso: \"x \\<le> y \\<Longrightarrow> z \\<rhd> x \\<le> z \\<rhd> y\"\n  by (metis res_iso residuated_conjr1)\n\nlemma conjr2_iso: \"x \\<le> y \\<Longrightarrow> x \\<rhd> z \\<le> y \\<rhd> z\"\n  by (metis conjugate_r_def compl_mono resr_antitonel)\n\nlemma conjl1_sup: \"z \\<lhd> (x \\<squnion> y) = (z \\<lhd> x) \\<squnion> (z \\<lhd> y)\"\n  by (metis conjugate_l_def compl_inf resl_distr)\n\nlemma conjl2_sup: \"(x \\<squnion> y) \\<lhd> z = (x \\<lhd> z) \\<squnion> (y \\<lhd> z)\"\n  by (metis (poly_guards_query) residuated_sup residuated_conjl1)\n\nlemma conjr1_sup: \"z \\<rhd> (x \\<squnion> y) = (z \\<rhd> x) \\<squnion> (z \\<rhd> y)\"\n  by (metis residuated_sup residuated_conjr1)\n\nlemma conjr2_sup: \"(x \\<squnion> y) \\<rhd> z = (x \\<rhd> z) \\<squnion> (y \\<rhd> z)\"\n  by (metis conjugate_r_def compl_inf resr_distl)\n\nlemma conjl1_strict: \"\\<bottom> \\<lhd> x = \\<bottom>\"\n  by (metis residuated_strict residuated_conjl1)\n\nlemma conjl2_strict: \"x \\<lhd> \\<bottom> = \\<bottom>\"\n  by (metis residuated_strict residuated_conjl2)\n\nlemma conjr1_strict: \"\\<bottom> \\<rhd> x = \\<bottom>\"\n  by (metis residuated_strict residuated_conjr2)\n\nlemma conjr2_strict: \"x \\<rhd> \\<bottom> = \\<bottom>\"\n  by (metis residuated_strict residuated_conjr1)\n\nlemma conjl1_iff: \"x \\<lhd> y \\<le> z \\<longleftrightarrow> x \\<le> -(-z\\<cdot>y)\"\n  by (metis conjugate_l_def compl_le_swap1 compl_le_swap2 resl_galois)\n\nlemma conjl2_iff: \"x \\<lhd> y \\<le> z \\<longleftrightarrow> y \\<le> -(-z \\<rhd> x)\"\n  by (metis conjl1_iff conjugate_r_def compl_le_swap2 double_compl resr_galois)\n\nlemma conjr1_iff: \"x \\<rhd> y \\<le> z \\<longleftrightarrow> y \\<le> -(x\\<cdot>-z)\"\n  by (metis conjugate_r_def compl_le_swap1 double_compl resr_galois)\n\nlemma conjr2_iff: \"x \\<rhd> y \\<le> z \\<longleftrightarrow> x \\<le> -(y \\<lhd> -z)\"\n  by (metis conjugation_conj double_compl inf.commute le_iff_inf_bot)\n\ntext \\<open>\n  We apply Maddux's lemmas regarding conjugation of an arbitrary residuated function \n  for each of the 6 functions.\n\\<close>\n  \nlemma maddux1a: \"a\\<cdot>(x \\<sqinter> -(a \\<rhd> y)) \\<le> a\\<cdot>x\"\n  by (insert maddux1 [of \"\\<lambda>x. a\\<cdot>x\"]) simp\n  \nlemma maddux1a': \"a\\<cdot>(x \\<sqinter> -(a \\<rhd> y)) \\<le> -y\"\n  by (insert maddux1 [of \"\\<lambda>x. a\\<cdot>x\"]) simp\n  \nlemma maddux1b: \"(x \\<sqinter> -(y \\<lhd> a))\\<cdot>a \\<le> x\\<cdot>a\"\n  by (insert maddux1 [of \"\\<lambda>x. x\\<cdot>a\"]) simp\n  \nlemma maddux1b': \"(x \\<sqinter> -(y \\<lhd> a))\\<cdot>a \\<le> -y\"\n  by (insert maddux1 [of \"\\<lambda>x. x\\<cdot>a\"]) simp\n  \nlemma maddux1c: \" a \\<lhd> x \\<sqinter> -(y \\<rhd> a) \\<le> a \\<lhd> x\"\n  by (insert maddux1 [of \"\\<lambda>x. a \\<lhd> x\"]) simp\n  \nlemma maddux1c': \"a \\<lhd> x \\<sqinter> -(y \\<rhd> a) \\<le> -y\"\n  by (insert maddux1 [of \"\\<lambda>x. a \\<lhd> x\"]) simp\n  \nlemma maddux1d: \"a \\<rhd> x \\<sqinter> -(a\\<cdot>y) \\<le> a \\<rhd> x\"\n  by (insert maddux1 [of \"\\<lambda>x. a \\<rhd> x\"]) simp\n  \nlemma maddux1d': \"a \\<rhd> x \\<sqinter> -(a\\<cdot>y) \\<le> -y\"\n  by (insert maddux1 [of \"\\<lambda>x. a \\<rhd> x\"]) simp\n\nlemma maddux1e: \"x \\<sqinter> -(y\\<cdot>a) \\<lhd> a \\<le> x \\<lhd> a\"\n  by (insert maddux1 [of \"\\<lambda>x. x \\<lhd> a\"]) simp\n  \nlemma maddux1e': \"x \\<sqinter> -(y\\<cdot>a) \\<lhd> a \\<le> -y\"\n  by (insert maddux1 [of \"\\<lambda>x. x \\<lhd> a\"]) simp\n  \nlemma maddux1f: \"x \\<sqinter> -(a \\<lhd> y) \\<rhd> a \\<le> x \\<rhd> a\"\n  by (insert maddux1 [of \"\\<lambda>x. x \\<rhd> a\"]) simp\n  \nlemma maddux1f': \"x \\<sqinter> -(a \\<lhd> y) \\<rhd> a \\<le> -y\"\n  by (insert maddux1 [of \"\\<lambda>x. x \\<rhd> a\"]) simp\n\nlemma maddux2a: \"a\\<cdot>x \\<sqinter> y \\<le> a\\<cdot>(x \\<sqinter> (a \\<rhd> y))\"\n  by (insert maddux2 [of \"\\<lambda>x. a\\<cdot>x\"]) simp\n  \nlemma maddux2b: \"x\\<cdot>a \\<sqinter> y \\<le> (x \\<sqinter> (y \\<lhd> a))\\<cdot>a\"\n  by (insert maddux2 [of \"\\<lambda>x. x\\<cdot>a\"]) simp\n  \nlemma maddux2c: \"(a \\<lhd> x) \\<sqinter> y \\<le> a \\<lhd> (x \\<sqinter> (y \\<rhd> a))\"\n  by (insert maddux2 [of \"\\<lambda>x. a \\<lhd> x\"]) simp\n  \nlemma maddux2d: \"(a \\<rhd> x) \\<sqinter> y \\<le> a \\<rhd> (x \\<sqinter> a\\<cdot>y)\"\n  by (insert maddux2 [of \"\\<lambda>x. a \\<rhd> x\"]) simp\n\nlemma maddux2e: \"(x \\<lhd> a) \\<sqinter> y \\<le> (x \\<sqinter> y\\<cdot>a) \\<lhd> a\"\n  by (insert maddux2 [of \"\\<lambda>x. x \\<lhd> a\"]) simp\n  \nlemma maddux2f: \"(x \\<rhd> a) \\<sqinter> y \\<le> (x \\<sqinter> (a \\<lhd> y)) \\<rhd> a\"\n  by (insert maddux2 [of \"\\<lambda>x. x \\<rhd> a\"]) simp\n  \ntext \\<open>\n  The multiplicative operation $\\cdot$ on a residuated boolean algebra is generally not\n  associative. We prove some equivalences related to associativity.\n\\<close>\n\nlemma res_assoc_iff1: \"(\\<forall>x y z. x\\<cdot>(y\\<cdot>z) = (x\\<cdot>y)\\<cdot>z) \\<longleftrightarrow> (\\<forall>x y z. x \\<rhd> (y \\<rhd> z) = y\\<cdot>x \\<rhd> z)\"\nproof safe\n  fix x y z assume \"\\<forall>x y z. x\\<cdot>(y\\<cdot>z) = (x\\<cdot>y)\\<cdot>z\"\n  thus \"x \\<rhd> (y \\<rhd> z) = y \\<cdot> x \\<rhd> z\"\n    using conjugate_comp_ext[of \"\\<lambda>z. y\\<cdot>z\" \"\\<lambda>z. x\\<cdot>z\"] by auto\nnext\n  fix x y z assume \"\\<forall>x y z. x \\<rhd> (y \\<rhd> z) = y\\<cdot>x \\<rhd> z\"\n  thus \"x\\<cdot>(y\\<cdot>z) = (x\\<cdot>y)\\<cdot>z\"\n    using conjugate_comp_ext[of \"\\<lambda>z. y \\<rhd> z\" \"\\<lambda>z. x \\<rhd> z\"] by auto\nqed\n\nlemma res_assoc_iff2: \"(\\<forall>x y z. x\\<cdot>(y\\<cdot>z) = (x\\<cdot>y)\\<cdot>z) \\<longleftrightarrow> (\\<forall>x y z. x \\<lhd> (y \\<cdot> z) = (x \\<lhd> z) \\<lhd> y)\"\nproof safe\n  fix x y z assume \"\\<forall>x y z. x\\<cdot>(y\\<cdot>z) = (x\\<cdot>y)\\<cdot>z\"\n  hence \"\\<forall>x y z. (x\\<cdot>y)\\<cdot>z = x\\<cdot>(y\\<cdot>z)\" by simp\n  thus \"x \\<lhd> (y \\<cdot> z) = (x \\<lhd> z) \\<lhd> y\"\n    using conjugate_comp_ext[of \"\\<lambda>x. x\\<cdot>z\" \"\\<lambda>x. x\\<cdot>y\"] by auto\nnext\n  fix x y z assume \"\\<forall>x y z. x \\<lhd> (y \\<cdot> z) = (x \\<lhd> z) \\<lhd> y\"\n  hence \"\\<forall>x y z. (x \\<lhd> z) \\<lhd> y = x \\<lhd> (y \\<cdot> z)\" by simp\n  thus \"x\\<cdot>(y\\<cdot>z) = (x\\<cdot>y)\\<cdot>z\" \n    using conjugate_comp_ext[of \"\\<lambda>z. z \\<lhd> y\" \"\\<lambda>x. x \\<lhd> z\"] by auto\nqed\n  \nlemma res_assoc_iff3: \"(\\<forall>x y z. x\\<cdot>(y\\<cdot>z) = (x\\<cdot>y)\\<cdot>z) \\<longleftrightarrow> (\\<forall>x y z. (x \\<rhd> y) \\<lhd> z = x \\<rhd> (y \\<lhd> z))\"\nproof safe\n  fix x y z assume \"\\<forall>x y z. x\\<cdot>(y\\<cdot>z) = (x\\<cdot>y)\\<cdot>z\"\n  thus \"(x \\<rhd> y) \\<lhd> z = x \\<rhd> (y \\<lhd> z)\"\n    using conjugate_comp_ext[of \"\\<lambda>u. x\\<cdot>u\" \"\\<lambda>u. u\\<cdot>z\"] and\n    conjugate_comp_ext[of \"\\<lambda>u. u\\<cdot>z\" \"\\<lambda>u. x\\<cdot>u\", symmetric]\n    by auto\nnext\n  fix x y z assume \"\\<forall>x y z. (x \\<rhd> y) \\<lhd> z = x \\<rhd> (y \\<lhd> z)\"\n  thus \"x\\<cdot>(y\\<cdot>z) = (x\\<cdot>y)\\<cdot>z\"\n    using conjugate_comp_ext[of \"\\<lambda>u. x \\<rhd> u\" \"\\<lambda>u. u \\<lhd> z\"] and\n    conjugate_comp_ext[of \"\\<lambda>u. u \\<lhd> z\" \"\\<lambda>u. x \\<rhd> u\", symmetric]\n    by auto\nqed\n\nend (* residuated_boolean_algebra *)\n\nclass unital_residuated_boolean = residuated_boolean_algebra + one +\n  assumes mult_onel [simp]: \"x\\<cdot>1 = x\"\n  and mult_oner [simp]: \"1\\<cdot>x = x\"\nbegin\n\ntext \\<open>\n  The following equivalences are taken from J{\\'o}sson and Tsinakis.\n\\<close>\n\nlemma jonsson1a: \"(\\<exists>f. \\<forall>x y. x \\<rhd> y = f(x)\\<cdot>y) \\<longleftrightarrow> (\\<forall>x y. x \\<rhd> y = (x \\<rhd> 1)\\<cdot>y)\"\n  apply standard\n  apply force\n  apply (rule_tac x=\"\\<lambda>x. x \\<rhd> 1\" in exI)\n  apply force\n  done\n  \nlemma jonsson1b: \"(\\<forall>x y. x \\<rhd> y = (x \\<rhd> 1)\\<cdot>y) \\<longleftrightarrow> (\\<forall>x y. x\\<cdot>y = (x \\<rhd> 1) \\<rhd> y)\"\nproof safe\n  fix x y\n  assume \"\\<forall>x y. x \\<rhd> y = (x \\<rhd> 1)\\<cdot>y\"\n  hence \"conjugate (\\<lambda>y. x \\<rhd> y) = conjugate (\\<lambda>y. (x \\<rhd> 1)\\<cdot>y)\" by metis\n  thus \"x\\<cdot>y = (x \\<rhd> 1) \\<rhd> y\" by simp\nnext\n  fix x y\n  assume \"\\<forall>x y. x \\<cdot> y = x \\<rhd> 1 \\<rhd> y\"\n  thus \"x \\<rhd> y = (x \\<rhd> 1) \\<cdot> y\"\n    by (metis mult_onel)\nqed\n\nlemma jonsson1c: \"(\\<forall>x y. x \\<rhd> y = (x \\<rhd> 1)\\<cdot>y) \\<longleftrightarrow> (\\<forall>x y. y \\<lhd> x = 1 \\<lhd> (x \\<lhd> y))\"\nproof safe\n  fix x y\n  assume \"\\<forall>x y. x \\<rhd> y = (x \\<rhd> 1)\\<cdot>y\"\n  hence \"(\\<lambda>x. x \\<rhd> y) = (\\<lambda>x. (x \\<rhd> 1)\\<cdot>y)\" by metis\n  hence \"(\\<lambda>x. x \\<rhd> y) = (\\<lambda>x. x\\<cdot>y) o (\\<lambda>x. x \\<rhd> 1)\" by force\n  hence \"conjugate (\\<lambda>x. y \\<lhd> x) = (\\<lambda>x. x\\<cdot>y) o conjugate (\\<lambda>x. 1 \\<lhd> x)\" by simp\n  hence \"conjugate (conjugate (\\<lambda>x. y \\<lhd> x)) = conjugate ((\\<lambda>x. x\\<cdot>y) o conjugate (\\<lambda>x. 1 \\<lhd> x))\" by simp\n  hence \"(\\<lambda>x. y \\<lhd> x) = conjugate ((\\<lambda>x. x\\<cdot>y) o conjugate (\\<lambda>x. 1 \\<lhd> x))\" by simp\n  also have \"... = conjugate (conjugate (\\<lambda>x. 1 \\<lhd> x)) o conjugate (\\<lambda>x. x\\<cdot>y)\"\n    by (subst conjugate_comp[symmetric]) simp_all\n  finally show \"y \\<lhd> x = 1 \\<lhd> (x \\<lhd> y)\" by simp\nnext\n  fix x y\n  assume \"\\<forall>x y. y \\<lhd> x = 1 \\<lhd> (x \\<lhd> y)\"\n  hence \"(\\<lambda>x. y \\<lhd> x) = (\\<lambda>x. 1 \\<lhd> (x \\<lhd> y))\" by metis\n  hence \"(\\<lambda>x. y \\<lhd> x) = (\\<lambda>x. 1 \\<lhd> x) o conjugate (\\<lambda>x. x\\<cdot>y)\" by force\n  hence \"conjugate (\\<lambda>x. y \\<lhd> x) = conjugate ((\\<lambda>x. 1 \\<lhd> x) o conjugate (\\<lambda>x. x\\<cdot>y))\" by metis\n  also have \"... = conjugate (conjugate (\\<lambda>x. x\\<cdot>y)) o conjugate (\\<lambda>x. 1 \\<lhd> x)\"\n    by (subst conjugate_comp[symmetric]) simp_all\n  finally have \"(\\<lambda>x. x \\<rhd> y) = (\\<lambda>x. x\\<cdot>y) o (\\<lambda>x. x \\<rhd> 1)\" by simp\n  hence \"(\\<lambda>x. x \\<rhd> y) = (\\<lambda>x. (x \\<rhd> 1) \\<cdot> y)\" by (simp add: comp_def)\n  thus \"x \\<rhd> y = (x \\<rhd> 1) \\<cdot> y\" by metis\nqed\n\nlemma jonsson2a: \"(\\<exists>g. \\<forall>x y. x \\<lhd> y = x\\<cdot>g(y)) \\<longleftrightarrow> (\\<forall>x y. x \\<lhd> y = x\\<cdot>(1 \\<lhd> y))\"\n  apply standard\n  apply force\n  apply (rule_tac x=\"\\<lambda>x. 1 \\<lhd> x\" in exI)\n  apply force\n  done\n  \nlemma jonsson2b: \"(\\<forall>x y. x \\<lhd> y = x\\<cdot>(1 \\<lhd> y)) \\<longleftrightarrow> (\\<forall>x y. x\\<cdot>y = x \\<lhd> (1 \\<lhd> y))\"\nproof safe\n  fix x y\n  assume \"\\<forall>x y. x \\<lhd> y = x\\<cdot>(1 \\<lhd> y)\"\n  hence \"conjugate (\\<lambda>x. x \\<lhd> y) = conjugate (\\<lambda>x. x\\<cdot>(1 \\<lhd> y))\" by metis\n  thus \"x\\<cdot>y = x \\<lhd> (1 \\<lhd> y)\" by simp metis\nnext\n  fix x y\n  assume \"\\<forall>x y. x\\<cdot>y = x \\<lhd> (1 \\<lhd> y)\"\n  hence \"(\\<lambda>x. x\\<cdot>y) = (\\<lambda>x. x \\<lhd> (1 \\<lhd> y))\" by metis\n  hence \"conjugate (\\<lambda>x. x\\<cdot>y) = conjugate (\\<lambda>x. x \\<lhd> (1 \\<lhd> y))\" by metis\n  thus \"x \\<lhd> y = x \\<cdot> (1 \\<lhd> y)\" by simp metis\nqed\n\nlemma jonsson2c: \"(\\<forall>x y. x \\<lhd> y = x\\<cdot>(1 \\<lhd> y)) \\<longleftrightarrow> (\\<forall>x y. y \\<rhd> x = (x \\<rhd> y) \\<rhd> 1)\"\nproof safe\n  fix x y\n  assume \"\\<forall>x y. x \\<lhd> y = x\\<cdot>(1 \\<lhd> y)\"\n  hence \"(\\<lambda>y. x \\<lhd> y) = (\\<lambda>y. x\\<cdot>(1 \\<lhd> y))\" by metis\n  hence \"(\\<lambda>y. x \\<lhd> y) = (\\<lambda>y. x\\<cdot>y) o (\\<lambda>y. 1 \\<lhd> y)\" by force\n  hence \"conjugate (\\<lambda>y. y \\<rhd> x) = (\\<lambda>y. x\\<cdot>y) o conjugate (\\<lambda>y. y \\<rhd> 1)\" by force\n  hence \"conjugate (conjugate (\\<lambda>y. y \\<rhd> x)) = conjugate ((\\<lambda>y. x\\<cdot>y) o conjugate (\\<lambda>y. y \\<rhd> 1))\" by metis\n  hence \"(\\<lambda>y. y \\<rhd> x) = conjugate ((\\<lambda>y. x\\<cdot>y) o conjugate (\\<lambda>y. y \\<rhd> 1))\" by simp\n  also have \"... = conjugate (conjugate (\\<lambda>y. y \\<rhd> 1)) o conjugate (\\<lambda>y. x\\<cdot>y)\"\n    by (subst conjugate_comp[symmetric]) simp_all\n  finally have \"(\\<lambda>y. y \\<rhd> x) = (\\<lambda>y. x \\<rhd> y \\<rhd> 1)\" by (simp add: comp_def)\n  thus \"y \\<rhd> x = x \\<rhd> y \\<rhd> 1\" by metis \nnext\n  fix x y\n  assume \"\\<forall>x y. y \\<rhd> x = x \\<rhd> y \\<rhd> 1\"\n  hence \"(\\<lambda>y. y \\<rhd> x) = (\\<lambda>y. x \\<rhd> y \\<rhd> 1)\" by force\n  hence \"(\\<lambda>y. y \\<rhd> x) = (\\<lambda>y. y \\<rhd> 1) o conjugate (\\<lambda>y. x\\<cdot>y)\" by force\n  hence \"conjugate (\\<lambda>y. y \\<rhd> x) = conjugate ((\\<lambda>y. y \\<rhd> 1) o conjugate (\\<lambda>y. x\\<cdot>y))\" by metis\n  also have \"... = conjugate (conjugate (\\<lambda>y. x\\<cdot>y)) o conjugate (\\<lambda>y. y \\<rhd> 1)\"\n    by (subst conjugate_comp[symmetric]) simp_all\n  finally have \"(\\<lambda>y. x \\<lhd> y) = (\\<lambda>y. x\\<cdot>y) o (\\<lambda>y. 1 \\<lhd> y)\"\n    by (metis conjugate_conjr1 conjugate_conjr2 conjugate_multr)\n  thus \"x \\<lhd> y = x \\<cdot> (1 \\<lhd> y)\" by (simp add: comp_def)\nqed\n\nlemma jonsson3a: \"(\\<forall>x. (x \\<rhd> 1) \\<rhd> 1 = x) \\<longleftrightarrow> (\\<forall>x. 1 \\<lhd> (1 \\<lhd> x) = x)\"\nproof safe\n  fix x assume \"\\<forall>x. x \\<rhd> 1 \\<rhd> 1 = x\"\n  thus \"1 \\<lhd> (1 \\<lhd> x) = x\"\n    by (metis compl_le_swap1 compl_le_swap2 conjr2_iff order.eq_iff)\nnext\n  fix x assume \"\\<forall>x. 1 \\<lhd> (1 \\<lhd> x) = x\"\n  thus \"x \\<rhd> 1 \\<rhd> 1 = x\"\n    by (metis conjugate_l_def conjugate_r_def double_compl jipsen2r)\nqed\n\nlemma jonsson3b: \"(\\<forall>x. (x \\<rhd> 1) \\<rhd> 1 = x) \\<Longrightarrow> (x \\<sqinter> y) \\<rhd> 1 = (x \\<rhd> 1) \\<sqinter> (y \\<rhd> 1)\"\nproof (rule order.antisym, auto simp: conjr2_iso)\n  assume assm: \"\\<forall>x. (x \\<rhd> 1) \\<rhd> 1 = x\"\n  hence \"(x \\<rhd> 1) \\<sqinter> (y \\<rhd> 1) \\<rhd> 1 = x \\<sqinter> (((x \\<rhd> 1) \\<sqinter> (y \\<rhd> 1) \\<rhd> 1) \\<sqinter> y)\"\n    by (metis (no_types) conjr2_iso inf.cobounded2 inf.commute inf.orderE)\n  hence \"(x \\<rhd> 1) \\<sqinter> (y \\<rhd> 1) \\<rhd> 1 \\<le> x \\<sqinter> y\" \n    using inf.orderI inf_left_commute by presburger\n  thus \"(x \\<rhd> 1) \\<sqinter> (y \\<rhd> 1) \\<le> x \\<sqinter> y \\<rhd> 1\" \n    using assm by (metis (no_types) conjr2_iso)\nqed\n\nlemma jonsson3c: \"\\<forall>x. (x \\<rhd> 1) \\<rhd> 1 = x \\<Longrightarrow> x \\<rhd> 1 = 1 \\<lhd> x\"\nproof (rule indirect_eq)\n  fix z\n  assume assms: \"\\<forall>x. (x \\<rhd> 1) \\<rhd> 1 = x\"\n  hence \"(x \\<rhd> 1) \\<sqinter> -z = \\<bottom> \\<longleftrightarrow> ((x \\<rhd> 1) \\<sqinter> -z) \\<rhd> 1 = \\<bottom>\"\n    by (metis compl_sup conjugation_conj double_compl inf_bot_right sup_bot.left_neutral)\n  also have \"... \\<longleftrightarrow> -z\\<cdot>x \\<sqinter> 1 = \\<bottom>\"\n    by (metis assms jonsson3b conjugation_multr)\n  finally have \"(x \\<rhd> 1) \\<sqinter> -z = \\<bottom> \\<longleftrightarrow> (1 \\<lhd> x) \\<sqinter> -z = \\<bottom>\"\n    by (metis conjugation_multl inf.commute)\n  thus \"(x \\<rhd> 1 \\<le> z) \\<longleftrightarrow> (1 \\<lhd> x \\<le> z)\"\n    by (metis le_iff_inf_bot)\nqed \n\nend (* unital_residuated_boolean *)\n\nclass residuated_boolean_semigroup = residuated_boolean_algebra + semigroup_mult\nbegin\n\nsubclass residuated_boolean_algebra ..\n\ntext \\<open>\n  The following lemmas hold trivially, since they are equivalent to associativity.\n\\<close>\n\nlemma res_assoc1: \"x \\<rhd> (y \\<rhd> z) = y\\<cdot>x \\<rhd> z\"\n  by (metis res_assoc_iff1 mult_assoc)\n\nlemma res_assoc2: \"x \\<lhd> (y \\<cdot> z) = (x \\<lhd> z) \\<lhd> y\"\n  by (metis res_assoc_iff2 mult_assoc)\n\nlemma res_assoc3: \"(x \\<rhd> y) \\<lhd> z = x \\<rhd> (y \\<lhd> z)\"\n  by (metis res_assoc_iff3 mult_assoc)\n\nend (*residuated_boolean_semigroup *)\n\nclass residuated_boolean_monoid = residuated_boolean_algebra + monoid_mult\nbegin\n\nsubclass unital_residuated_boolean\n  by standard auto\n\nsubclass residuated_lmonoid ..\n\nlemma jonsson4: \"(\\<forall>x y. x \\<lhd> y = x\\<cdot>(1 \\<lhd> y)) \\<longleftrightarrow> (\\<forall>x y. x \\<rhd> y = (x \\<rhd> 1)\\<cdot>y)\"\nproof safe\n  fix x y assume assms: \"\\<forall>x y. x \\<lhd> y = x\\<cdot>(1 \\<lhd> y)\"\n  have \"x \\<rhd> y = (y \\<rhd> x) \\<rhd> 1\"\n    by (metis assms jonsson2c)\n  also have \"... = (y \\<rhd> ((x \\<rhd> 1) \\<rhd> 1)) \\<rhd> 1\"\n    by (metis assms jonsson2b jonsson3a mult_oner)\n  also have \"... = (((x \\<rhd> 1)\\<cdot>y) \\<rhd> 1) \\<rhd> 1\"\n    by (metis conjugate_r_def double_compl resr3)\n  also have \"... = (x \\<rhd> 1)\\<cdot>y\"\n    by (metis assms jonsson2b jonsson3a mult_oner)\n  finally show \"x \\<rhd> y = (x \\<rhd> 1)\\<cdot>y\" .\nnext\n  fix x y assume assms: \"\\<forall>x y. x \\<rhd> y = (x \\<rhd> 1)\\<cdot>y\"\n  have \"y \\<lhd> x = 1 \\<lhd> (x \\<lhd> y)\"\n    by (metis assms jonsson1c)\n  also have \"... = 1 \\<lhd> ((1 \\<lhd> (1 \\<lhd> x)) \\<lhd> y)\"\n    by (metis assms conjugate_l_def double_compl jonsson1c mult_1_right resl3)\n  also have \"... = 1 \\<lhd> (1 \\<lhd> (y\\<cdot>(1 \\<lhd> x)))\"\n    by (metis conjugate_l_def double_compl resl3)\n  also have \"... = y\\<cdot>(1 \\<lhd> x)\"\n    by (metis assms jonsson1b jonsson1c jonsson3c mult_onel)\n  finally show \"y \\<lhd> x = y\\<cdot>(1 \\<lhd> x)\".\nqed\n\nend (* residuated_boolean_monoid *)\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/Residuated_Lattices/Residuated_Boolean_Algebras.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473647220786, "lm_q2_score": 0.8080672158638527, "lm_q1q2_score": 0.7049153062771389}}
{"text": "theory poly_sub\nimports \"~~/src/HOL/Algebra/UnivPoly\" cring_poly\nbegin\n\n(**************************************************************************************************)\n(**************************************************************************************************)\n(**********************************    Polynomial Substitution   **********************************)\n(**************************************************************************************************)\n\n(*Inclusion of R into P*)\n\ndefinition to_polynomial where\n\"to_polynomial R  =  (\\<lambda>a. monom (UP R) a 0)\"\n\nabbreviation(in UP_ring) to_poly where\n\"to_poly  \\<equiv> to_polynomial R \"\n\n(**************************************************************************************************)\ncontext UP_domain\nbegin \n\n\nlemma to_poly_inverse:\n  assumes \"f \\<in> carrier P\"\n  assumes \"degree f = 0\"\n  shows \"f = to_poly (f 0)\"\n  using P_def assms(1) assms(2) coeff_simp1 deg_zero_impl_monom \n  by (simp add: to_polynomial_def)\n\nlemma to_poly_is_poly:\n  assumes \"a \\<in> carrier R\"\n  shows \"to_poly a \\<in> carrier P\"\n  by (metis P_def assms monom_closed to_polynomial_def)\n\nlemma degree_to_poly[simp]:\n  assumes \"a \\<in> carrier R\"\n  shows \"degree (to_poly a) = 0\"\n  by (metis P_def assms deg_const to_polynomial_def)\n\nlemma(in UP_ring) to_poly_is_ring_hom:\n\"to_poly \\<in> ring_hom R P\"\n  unfolding to_polynomial_def\n  unfolding P_def\n  using UP_ring.const_ring_hom[of R]\n  UP_ring_axioms by simp \n\nlemma(in UP_ring) to_poly_add[simp]:\n  assumes \"a \\<in> carrier R\"\n  assumes \"b \\<in> carrier R\"\n  shows \"to_poly (a \\<oplus> b) = to_poly a \\<oplus>\\<^bsub>P\\<^esub> to_poly b\"\n  by (simp add: assms(1) assms(2) ring_hom_add to_poly_is_ring_hom)\n\nlemma(in UP_ring) to_poly_mult[simp]:\n  assumes \"a \\<in> carrier R\"\n  assumes \"b \\<in> carrier R\"\n  shows \"to_poly (a \\<otimes> b) = to_poly a \\<otimes>\\<^bsub>P\\<^esub> to_poly b\"\n  by (simp add: assms(1) assms(2) ring_hom_mult to_poly_is_ring_hom)\n\nlemma(in UP_ring) to_poly_minus[simp]:\n  assumes \"a \\<in> carrier R\"\n  assumes \"b \\<in> carrier R\"\n  shows \"to_poly (a \\<ominus> b) = to_poly a \\<ominus>\\<^bsub>P\\<^esub> to_poly b\"\n  by (metis P.minus_eq P_def R.add.inv_closed R.ring_axioms UP_ring.monom_add \n      UP_ring_axioms assms(1) assms(2) monom_a_inv ring.ring_simprules(14) to_polynomial_def)\n\nlemma(in UP_ring) to_poly_ominus[simp]:\n  assumes \"a \\<in> carrier R\"\n  shows \"to_poly (\\<ominus> a) =  \\<ominus>\\<^bsub>P\\<^esub> to_poly a\"\n  by (metis P_def assms monom_a_inv to_polynomial_def)\n\nend\n(*Substitution of one polynomial into another*)\n\n\n\ndefinition compose where\n\"compose R f g = eval R (UP R) (to_polynomial R) g f\"\n\nabbreviation(in UP_ring) sub  (infixl \"of\" 70) where\n\"sub f g \\<equiv> compose R f g\"\n\n\ndefinition rev_compose  where\n\"rev_compose R = eval R (UP R) (to_polynomial R)\"\n\nabbreviation(in UP_ring) rev_sub  where\n\"rev_sub \\<equiv> rev_compose R\"\n\n\ncontext UP_domain\nbegin\n\nlemma(in UP_ring) sub_rev_sub:\n\"sub f g = rev_sub g f\"\n  unfolding compose_def rev_compose_def by simp\n\nlemma(in UP_cring) to_poly_UP_pre_univ_prop:\n\"UP_pre_univ_prop R P to_poly\"\nproof \n  show \"to_poly \\<in> ring_hom R P\" \n    by (simp add: to_poly_is_ring_hom)\nqed\n\nlemma rev_sub_is_hom:\n  assumes \"g \\<in> carrier P\"\n  shows \"rev_sub g \\<in> ring_hom P P\"\n  unfolding rev_compose_def\n  using to_poly_UP_pre_univ_prop assms(1) UP_pre_univ_prop.eval_ring_hom[of R P to_poly g] \n  unfolding P_def apply auto \n  done\n\nlemma rev_sub_closed:\n  assumes \"p \\<in> carrier P\"\n  assumes \"q \\<in> carrier P\"\n  shows \"rev_sub q p \\<in> carrier P\"\n  using rev_sub_is_hom[of q] assms ring_hom_closed[of \"rev_sub q\" P P p] by auto  \n\nlemma sub_closed:\n  assumes \"p \\<in> carrier P\"\n  assumes \"q \\<in> carrier P\"\n  shows \"sub q p \\<in> carrier P\"\n  by (simp add: assms(1) assms(2) rev_sub_closed sub_rev_sub)\n\nlemma rev_sub_add:\n  assumes \"g \\<in> carrier P\"\n  assumes \"f \\<in> carrier P\"\n  assumes \"h \\<in>carrier P\"\n  shows \"rev_sub g (f \\<oplus>\\<^bsub>P\\<^esub> h) = (rev_sub g f) \\<oplus>\\<^bsub>P\\<^esub> (rev_sub g h)\"\n  using rev_sub_is_hom assms ring_hom_add by fastforce\n\nlemma sub_add: \n  assumes \"g \\<in> carrier P\"\n  assumes \"f \\<in> carrier P\"\n  assumes \"h \\<in>carrier P\"\n  shows \"((f \\<oplus>\\<^bsub>P\\<^esub> h) of g) = ((f of g) \\<oplus>\\<^bsub>P\\<^esub> (h of g))\"\n  by (simp add: assms(1) assms(2) assms(3) rev_sub_add sub_rev_sub)\n\nlemma rev_sub_mult:\n  assumes \"g \\<in> carrier P\"\n  assumes \"f \\<in> carrier P\"\n  assumes \"h \\<in>carrier P\"\n  shows \"rev_sub g (f \\<otimes>\\<^bsub>P\\<^esub> h) = (rev_sub g f) \\<otimes>\\<^bsub>P\\<^esub> (rev_sub g h)\"\n  using rev_sub_is_hom assms ring_hom_mult  by fastforce\n\nlemma sub_mult: \n  assumes \"g \\<in> carrier P\"\n  assumes \"f \\<in> carrier P\"\n  assumes \"h \\<in>carrier P\"\n  shows \"((f \\<otimes>\\<^bsub>P\\<^esub> h) of g) = ((f of g) \\<otimes>\\<^bsub>P\\<^esub> (h of g))\"\n  by (simp add: assms(1) assms(2) assms(3) rev_sub_mult sub_rev_sub)\n\n(*Subbing into a constant does nothing*)\nlemma rev_sub_to_poly:\n  assumes \"g \\<in> carrier P\"\n  assumes \"a \\<in> carrier R\"\n  shows \"rev_sub g (to_poly a) = to_poly a\"\n  unfolding to_polynomial_def rev_compose_def\n  using to_poly_UP_pre_univ_prop \n  unfolding to_polynomial_def \n     using P_def UP_pre_univ_prop.eval_const assms(1) assms(2) by fastforce\n\nlemma sub_to_poly[simp]:\n  assumes \"g \\<in> carrier P\"\n  assumes \"a \\<in> carrier R\"\n  shows \"(to_poly a) of g  = to_poly a\"\n  by (simp add: assms(1) assms(2) rev_sub_to_poly sub_rev_sub)\n\nlemma sub_const[simp]:\n  assumes \"g \\<in> carrier P\"\n  assumes \"f \\<in> carrier P\"\n  assumes \"degree f = 0\"\n  shows \"f of g = f\"\nproof-\n  obtain a where a_def: \"a \\<in> carrier R \\<and> f = to_poly a\"\n    using assms(2) assms(3) deg_zero_impl_monom to_polynomial_def \n    by (metis P_def lcoeff_closed)\n  then show ?thesis \n    by (simp add: assms(1))\nqed\n\nend\n\n(*Function which truncates a polynomial by removing the leading term*)\ndefinition truncate where\n\"truncate R f = f \\<ominus>\\<^bsub>(UP R)\\<^esub> (leading_term R f)\"\n\n\ncontext UP_domain\nbegin \n\nabbreviation trunc where\n\"trunc \\<equiv> truncate R\"\n\nlemma trunc_simps:\n  assumes \"f \\<in> carrier P\"\n  shows \"f = (trunc f) \\<oplus>\\<^bsub>P\\<^esub> (lt f)\"\n        \"f \\<ominus>\\<^bsub>P\\<^esub> (trunc f) = lt f\"   \n        \"trunc f \\<in> carrier P\"\n  unfolding truncate_def\n  apply (metis P.add.inv_solve_right P.minus_closed P_def a_minus_def assms lt_in_car)\n  apply (metis (no_types, hide_lams) P.add.inv_solve_right \n        P.minus_closed P_def UP_a_comm a_minus_def assms lt_in_car)\n  using P.minus_closed P_def assms lt_in_car by blast\n\n\n\nlemma trunc_zero:\n  assumes \"f \\<in> carrier P\"\n  assumes \"degree f = 0\"\n  shows \"trunc f = \\<zero>\\<^bsub>P\\<^esub>\"\n  unfolding truncate_def \n  using assms lt_deg_0[of f] \n  by (metis P.r_neg P_def a_minus_def)\n\nlemma trunc_degree:\n  assumes \"f \\<in> carrier P\"\n  assumes \"degree f > 0\"\n  shows \"degree (trunc f) < degree f\"\n  unfolding truncate_def using assms \n  by (metis P.add.inv_solve_right P_def a_minus_def lt_decomp lt_in_car)\n\n(*leading term is multiplicative*)\n\nlemma lt_id:\n  assumes \"q \\<in> carrier P\"\n  assumes \"a \\<in> carrier R\"\n  assumes \"a \\<noteq>\\<zero>\"\n  assumes \"degree q < n\"\n  assumes \"p = q \\<oplus>\\<^bsub>P\\<^esub> (monom P a n)\"\n  shows \"lt p =  (monom P a n)\"\nproof-\n  have 0: \"degree  (monom P a n) = n\" \n    by (simp add: assms(2) assms(3))\n  have 1: \"(monom P a n) \\<in> carrier P\"\n    using assms(2) by auto\n  have 2: \"lt ((monom P a n) \\<oplus>\\<^bsub>P\\<^esub> q) = lt (monom P a n)\"\n    using assms lt_of_sum_diff_degree[of \"(monom P a n)\" q] 1  \"0\" by linarith\n  then show ?thesis \n    using UP_a_comm assms(1) assms(2) assms(5) lt_monom by auto\nqed\n\nlemma lt_smult:\n  assumes \"p \\<in> carrier P\"\n  assumes \"a \\<in> carrier R\"\n  shows \"lt (a \\<odot>\\<^bsub>P\\<^esub>p) = a\\<odot>\\<^bsub>P\\<^esub>(lt p)\"\nproof(cases \"a = \\<zero>\")\n  case True\n  then show ?thesis \n    by (metis P_def UP_smult_zero UP_zero_closed assms(1)\n        coeff_simp1 deg_nzero_nzero deg_zero_impl_monom leading_term_def lt_in_car)\nnext\n  case False\n  show ?thesis \n  proof(cases \"degree p = 0\")\n    case True\n    then show ?thesis \n      by (simp add: assms(1) assms(2))\n  next\n    case F: False\n    then show ?thesis \n    proof-\n      have P0: \"(a \\<odot>\\<^bsub>P\\<^esub>p) = (trunc (a \\<odot>\\<^bsub>P\\<^esub>p)) \\<oplus>\\<^bsub>P\\<^esub> lt (a \\<odot>\\<^bsub>P\\<^esub>p)\"\n        by (simp add: assms(1) assms(2) trunc_simps(1))\n      have P1: \"(a \\<odot>\\<^bsub>P\\<^esub>p) = (a \\<odot>\\<^bsub>P\\<^esub> ((trunc p) \\<oplus>\\<^bsub>P\\<^esub> lt p))\"\n        using assms(1) trunc_simps(1) by auto\n      have P2: \"(a \\<odot>\\<^bsub>P\\<^esub>p) = (a \\<odot>\\<^bsub>P\\<^esub>(trunc p)) \\<oplus>\\<^bsub>P\\<^esub> (a \\<odot>\\<^bsub>P\\<^esub>(lt p))\"\n        by (simp add: P1 assms(1) assms(2) lt_in_car smult_r_distr trunc_simps(3))\n      have P3: \"degree (lt (a \\<odot>\\<^bsub>P\\<^esub>p)) = degree (a \\<odot>\\<^bsub>P\\<^esub>(lt p))\" \n        using assms(1) assms(2)  degree_lt lt_in_car by auto\n      have P4: \"degree (a \\<odot>\\<^bsub>P\\<^esub>(lt p)) = degree p\"\n        by (metis False P3 assms(1) assms(2) deg_smult  degree_lt smult_closed)\n      have P5: \"degree (a \\<odot>\\<^bsub>P\\<^esub>(trunc p)) = degree (trunc p)\"\n        using False by (simp add: assms(1) assms(2)  trunc_simps(3))\n      have P6: \"degree (a \\<odot>\\<^bsub>P\\<^esub>(trunc p)) < degree (a \\<odot>\\<^bsub>P\\<^esub>(lt p))\"\n        using F P4 P5 P_def UP_domain.trunc_degree UP_domain_axioms assms(1) by auto\n      have  P7: \"(a \\<odot>\\<^bsub>P\\<^esub>(lt p)) = monom P (a \\<otimes> (p (degree p))) (degree p)\" \n        unfolding leading_term_def \n        using P_def P_fact0 assms(1) assms(2) monom_mult_smult by auto\n      have P8: \"(a \\<otimes> (p (degree p))) \\<noteq>\\<zero>\" \n        using F P4 P_def P_fact0 R.integral assms(1) assms(2) coeff_simp1 deg_smult\n          deg_zero  lcoeff_nonzero2 lt_in_car by fastforce\n      show ?thesis \n        using P6 P2 P7 P8 lt_id  P4 P_fact0 assms(1) assms(2) trunc_simps(3) by auto\n    qed\n  qed\nqed\n\nlemma lt_mult:\n  assumes \"p \\<in> carrier P\"\n  assumes \"q \\<in> carrier P\"\n  shows \"lt (p \\<otimes>\\<^bsub>P\\<^esub> q) = (lt p) \\<otimes>\\<^bsub>P\\<^esub> (lt q)\"\nproof(cases \"degree p = 0 \\<or> degree q = 0\")\n  case True\n  then show ?thesis\n  proof(cases \"degree p = 0\")\n    case True\n    then have L: \"p = lt p\"\n      by (simp add: assms(1))\n    have LHS: \"lt (p \\<otimes>\\<^bsub>P\\<^esub> q) = lt( (p 0) \\<odot>\\<^bsub>P\\<^esub>q)\"\n      using L True \n      by (metis P_def P_fact0 assms(1) assms(2) coeff_simp1\n          deg_zero_impl_monom monom_mult_is_smult)\n    have RHS: \"(lt p) \\<otimes>\\<^bsub>P\\<^esub> (lt q) = (p 0) \\<odot>\\<^bsub>P\\<^esub> (lt q)\"\n      using L True P_fact0 assms(1) assms(2) leading_term_def lt_in_car monom_mult_is_smult \n      by (metis P_def)\n    then show ?thesis using LHS RHS lt_smult  P_fact0 assms(1) assms(2) by auto\n  next\n    case False\n    then have \"degree q = 0\" \n      using True by linarith\n    then show ?thesis \n      by (metis P.m_comm P_def P_fact0 UP_domain.lt_smult UP_domain_axioms assms(1)\n          assms(2) leading_term_def lt_deg_0 lt_in_car monom_mult_is_smult)\n  qed\nnext\n  case False\n  then show ?thesis \n  proof-\n    obtain q0 where q0_def: \"q0 = trunc q\" \n      by simp\n    obtain p0 where p0_def: \"p0 = trunc p\" \n      by simp\n    have Pq: \"degree q0 < degree q\"\n      using False P_def UP_domain.trunc_degree UP_domain_axioms assms(2) q0_def by blast\n    have Pp: \"degree p0 < degree p\"\n      using False P_def UP_domain.trunc_degree UP_domain_axioms assms(1) p0_def by blast\n    have \"p \\<otimes>\\<^bsub>P\\<^esub> q = (p0 \\<oplus>\\<^bsub>P\\<^esub> lt(p)) \\<otimes>\\<^bsub>P \\<^esub>(q0 \\<oplus>\\<^bsub>P\\<^esub> lt(q))\"\n      using assms(1) assms(2) p0_def q0_def trunc_simps(1) by auto\n    then have P0: \"p \\<otimes>\\<^bsub>P\\<^esub> q = ((p0 \\<oplus>\\<^bsub>P\\<^esub> lt(p)) \\<otimes>\\<^bsub>P \\<^esub>q0) \\<oplus>\\<^bsub>P\\<^esub> ((p0 \\<oplus>\\<^bsub>P\\<^esub> lt(p))\\<otimes>\\<^bsub>P \\<^esub>lt(q))\"\n      by (simp add: P.r_distr assms(1) assms(2) lt_in_car p0_def q0_def trunc_simps(3))\n    have P1: \"degree ((p0 \\<oplus>\\<^bsub>P\\<^esub> lt(p)) \\<otimes>\\<^bsub>P \\<^esub>q0) < degree ((p0 \\<oplus>\\<^bsub>P\\<^esub> lt(p))\\<otimes>\\<^bsub>P \\<^esub>lt(q))\"\n    proof-\n      have LHS: \"degree ((p0 \\<oplus>\\<^bsub>P\\<^esub> lt(p)) \\<otimes>\\<^bsub>P \\<^esub>q0) \\<le> degree p + degree q0 \"\n      proof(cases \"q0 = \\<zero>\\<^bsub>P\\<^esub>\")\n        case True\n        then show ?thesis \n          using assms(1) p0_def trunc_simps(1) by auto\n      next\n        case False\n        then show ?thesis \n          using assms(1) assms(2) deg_mult_ring  p0_def \n            q0_def trunc_simps(1) trunc_simps(3) by auto\n      qed\n      have RHS: \"degree ((p0 \\<oplus>\\<^bsub>P\\<^esub> lt(p))\\<otimes>\\<^bsub>P \\<^esub>lt(q)) = degree p + degree q\"\n        by (metis False assms(1) assms(2) deg_mult deg_zero \n            degree_lt lt_in_car p0_def trunc_simps(1))\n      then show ?thesis using RHS LHS \n        using Pq by linarith\n    qed\n    then have P2: \"lt (p \\<otimes>\\<^bsub>P\\<^esub> q) = lt ((p0 \\<oplus>\\<^bsub>P\\<^esub> lt(p))\\<otimes>\\<^bsub>P \\<^esub>lt(q))\"\n      using P0 P1  \n      by (simp add: UP_a_comm assms(1) assms(2) lt_in_car \n          lt_of_sum_diff_degree p0_def q0_def trunc_simps(3))\n    have P3: \" lt ((p0 \\<oplus>\\<^bsub>P\\<^esub> lt(p))\\<otimes>\\<^bsub>P \\<^esub>lt(q)) = lt p \\<otimes>\\<^bsub>P\\<^esub> lt q\"\n    proof-\n      have Q0: \"((p0 \\<oplus>\\<^bsub>P\\<^esub> lt(p))\\<otimes>\\<^bsub>P \\<^esub>lt(q)) = (p0 \\<otimes>\\<^bsub>P \\<^esub>lt(q)) \\<oplus>\\<^bsub>P\\<^esub>  (lt(p))\\<otimes>\\<^bsub>P \\<^esub>lt(q)\"\n        by (simp add: P.l_distr assms(1) assms(2) lt_in_car p0_def trunc_simps(3))\n      have Q1: \"degree ((p0 \\<otimes>\\<^bsub>P \\<^esub>lt(q)) ) < degree ((lt(p))\\<otimes>\\<^bsub>P \\<^esub>lt(q))\"\n      proof(cases \"p0 = \\<zero>\\<^bsub>P\\<^esub>\")\n        case True\n        then show ?thesis \n          using P1 assms(1) assms(2)  lt_in_car by auto\n      next\n        case F: False\n        then show ?thesis\n          proof-\n            have LHS: \"degree ((p0 \\<otimes>\\<^bsub>P \\<^esub>lt(q))) < degree p + degree q\"\n              using False F deg_mult Pp assms(1) assms(2) deg_nzero_nzero \n                 degree_lt lt_in_car p0_def trunc_simps(3) by auto\n            have RHS: \"degree ((lt(p))\\<otimes>\\<^bsub>P \\<^esub>lt(q)) = degree p + degree q\" \n               by (metis False  assms(1) assms(2) deg_mult deg_zero \n                     degree_lt lt_in_car)\n            then show ?thesis using LHS RHS by auto \n        qed\n      qed\n      have Q2: \"lt ((p0 \\<oplus>\\<^bsub>P\\<^esub> lt(p))\\<otimes>\\<^bsub>P \\<^esub>lt(q)) = lt ((lt(p))\\<otimes>\\<^bsub>P \\<^esub>lt(q))\" \n        using Q0 Q1 by (simp add: UP_a_comm assms(1) assms(2) \n            lt_in_car lt_of_sum_diff_degree p0_def trunc_simps(3))\n      show ?thesis using lt_prod_lt Q0 Q1 Q2 \n        by (simp add: assms(1) assms(2))\n    qed\n    then show ?thesis \n      by (simp add: P2)\n  qed\nqed\n\nlemma lc_deg_0:\n  assumes \"degree p = 0\"\n  assumes \"p \\<in> carrier P\"\n  assumes \"q \\<in> carrier P\"\n  shows \"(p \\<otimes>\\<^bsub>P\\<^esub> q) = (lc p)\\<odot>\\<^bsub>P\\<^esub>q\" \n  using P_def assms(1) assms(2) assms(3) coeff_simp1 deg_zero_impl_monom \n    leading_coefficient_def lcoeff_closed monom_mult_is_smult \n     by (metis P_fact0 coeff_simp0)\n\n(*leading term powers*)\n\nlemma (in domain) nonzero_pow_nonzero:\n  assumes \"a \\<in> carrier R\"\n  assumes \"a \\<noteq>\\<zero>\"\n  shows \"a[^](n::nat) \\<noteq> \\<zero>\"  \nproof(induction n)\n  case 0\n  then show ?case \n    by auto\nnext\n  case (Suc n)\n  fix n::nat\n  assume IH: \"a[^] n \\<noteq> \\<zero>\" \n  show \"a[^] (Suc n) \\<noteq> \\<zero>\" \n  proof-\n    have \"a[^] (Suc n) = a[^] n \\<otimes> a\"\n      by simp\n    then show ?thesis using assms IH \n      using IH assms(1) assms(2) local.integral by auto\n  qed\nqed\n\nlemma monom_degree:\n  assumes \"a \\<noteq>\\<zero>\"\n  assumes \"a \\<in> (carrier R)\"\n  assumes \"p = monom P a m\"\n  shows \"degree (p[^]\\<^bsub>P\\<^esub> n) = n*m\"\n  using P_def R.nonzero_pow_nonzero UP_cring.monom_pow \n    UP_cring_axioms assms(1) assms(2) assms(3) deg_monom  by fastforce\n\nlemma pow_sum0:\n\"\\<And> p q. p \\<in> carrier P \\<Longrightarrow> q \\<in> carrier P \\<Longrightarrow> degree q < degree p \\<Longrightarrow> degree ((p \\<oplus>\\<^bsub>P\\<^esub> q )[^]\\<^bsub>P\\<^esub>n) = (degree p)*n\"\nproof(induction n)\n  case 0\n  then show ?case \n    by (metis P_def UP_domain_axioms UP_domain_def UP_ring.UP_ring UP_ring.intro coeff_simp1 \n        cring_def deg_nzero_nzero  domain_def lcoeff_closed lcoeff_nonzero2 \n        less_nat_zero_code monoid.nat_pow_0 monom_degree mult_zero_left mult_zero_right ring_def )\nnext\n  case (Suc n)\n  fix n\n  assume IH: \"\\<And> p q. p \\<in> carrier P \\<Longrightarrow> q \\<in> carrier P \\<Longrightarrow> \n              degree q < degree p \\<Longrightarrow> degree ((p \\<oplus>\\<^bsub>P\\<^esub> q )[^]\\<^bsub>P\\<^esub>n) = (degree p)*n\"\n  then show \"\\<And> p q. p \\<in> carrier P \\<Longrightarrow> q \\<in> carrier P \\<Longrightarrow> \n             degree q < degree p \\<Longrightarrow> degree ((p \\<oplus>\\<^bsub>P\\<^esub> q )[^]\\<^bsub>P\\<^esub>(Suc n)) = (degree p)*(Suc n)\"\n  proof-\n    fix p q\n    assume A0: \"p \\<in> carrier P\" and \n           A1: \"q \\<in> carrier P\" and \n           A2:  \"degree q < degree p\"\n    show \"degree ((p \\<oplus>\\<^bsub>P\\<^esub> q )[^]\\<^bsub>P\\<^esub>(Suc n)) = (degree p)*(Suc n)\"\n    proof(cases \"q = \\<zero>\\<^bsub>P\\<^esub>\")\n      case True\n      then show ?thesis \n        by (metis A0 A1 A2 IH P.nat_pow_Suc2 P.nat_pow_closed P.r_zero deg_mult \n            domain.nonzero_pow_nonzero local.domain_axioms mult_Suc_right nat_neq_iff)\n    next\n      case False\n      then show ?thesis \n      proof-\n        have P0: \"degree ((p \\<oplus>\\<^bsub>P\\<^esub> q )[^]\\<^bsub>P\\<^esub>n) = (degree p)*n\" \n          using A0 A1 A2 IH by auto \n        have P1: \"(p \\<oplus>\\<^bsub>P\\<^esub> q )[^]\\<^bsub>P\\<^esub>(Suc n) = ((p \\<oplus>\\<^bsub>P\\<^esub> q )[^]\\<^bsub>P\\<^esub>n) \\<otimes>\\<^bsub>P\\<^esub> (p \\<oplus>\\<^bsub>P\\<^esub> q )\"\n          by simp\n        then have P2: \"(p \\<oplus>\\<^bsub>P\\<^esub> q )[^]\\<^bsub>P\\<^esub>(Suc n) = (((p \\<oplus>\\<^bsub>P\\<^esub> q )[^]\\<^bsub>P\\<^esub>n) \\<otimes>\\<^bsub>P\\<^esub> p) \\<oplus>\\<^bsub>P\\<^esub> (((p \\<oplus>\\<^bsub>P\\<^esub> q )[^]\\<^bsub>P\\<^esub>n) \\<otimes>\\<^bsub>P\\<^esub> q)\"\n          by (simp add: A0 A1 UP_r_distr)\n        have P3: \"degree (((p \\<oplus>\\<^bsub>P\\<^esub> q )[^]\\<^bsub>P\\<^esub>n) \\<otimes>\\<^bsub>P\\<^esub> p) = (degree p)*n + (degree p)\" \n          using P0 A0 A1 A2 deg_nzero_nzero  degree_of_sum_diff_degree local.nonzero_pow_nonzero by auto\n        have P4: \"degree (((p \\<oplus>\\<^bsub>P\\<^esub> q )[^]\\<^bsub>P\\<^esub>n) \\<otimes>\\<^bsub>P\\<^esub> q) = (degree p)*n + (degree q)\" \n          using P0 A0 A1 A2 deg_nzero_nzero  degree_of_sum_diff_degree local.nonzero_pow_nonzero False deg_mult \n          by simp\n        have P5: \"degree (((p \\<oplus>\\<^bsub>P\\<^esub> q )[^]\\<^bsub>P\\<^esub>n) \\<otimes>\\<^bsub>P\\<^esub> p) > degree (((p \\<oplus>\\<^bsub>P\\<^esub> q )[^]\\<^bsub>P\\<^esub>n) \\<otimes>\\<^bsub>P\\<^esub> q)\"\n          using P3 P4 A2 by auto \n        then show ?thesis using P5 P3 P2 \n          by (simp add: A0 A1 degree_of_sum_diff_degree)\n      qed\n    qed\n  qed\nqed\n\nlemma pow_sum:\n  assumes \"p \\<in> carrier P\" \n  assumes \"q \\<in> carrier P\"\n  assumes \"degree q < degree p\"\n  shows \"degree ((p \\<oplus>\\<^bsub>P\\<^esub> q )[^]\\<^bsub>P\\<^esub>n) = (degree p)*n\"\n  using assms(1) assms(2) assms(3) pow_sum0 by blast\n\nlemma deg_pow0:\n \"\\<And> p. p \\<in> carrier P \\<Longrightarrow> n \\<ge> degree p \\<Longrightarrow> degree (p [^]\\<^bsub>P\\<^esub> m) = m*(degree p)\"\nproof(induction n)\n  case 0\n  show \"p \\<in> carrier P \\<Longrightarrow> 0 \\<ge> degree p \\<Longrightarrow> degree (p [^]\\<^bsub>P\\<^esub> m) = m*(degree p)\"\n  proof-\n    assume B0:\"p \\<in> carrier P\"\n    assume B1: \"0 \\<ge> degree p\"\n    then obtain a where a_def: \"a \\<in> carrier R \\<and> p = monom P a 0\"\n      using B0 deg_zero_impl_monom  by fastforce\n    show \"degree (p [^]\\<^bsub>P\\<^esub> m) = m*(degree p)\"  using UP_cring.monom_pow \n      by (metis P_def R.nat_pow_closed UP_cring_axioms a_def deg_const  \n        mult_0_right mult_zero_left)\n  qed\nnext\n  case (Suc n)\n  fix n\n  assume IH: \"\\<And>p. (p \\<in> carrier P \\<Longrightarrow> n \\<ge>degree p \\<Longrightarrow> degree (p [^]\\<^bsub>P\\<^esub> m) = m * (degree p))\"\n  show \"p \\<in> carrier P \\<Longrightarrow> Suc n \\<ge> degree p \\<Longrightarrow> degree (p [^]\\<^bsub>P\\<^esub> m) = m * (degree p)\"\n  proof-\n    assume A0: \"p \\<in> carrier P\"\n    assume A1: \"Suc n \\<ge> degree p\"\n    show \"degree (p [^]\\<^bsub>P\\<^esub> m) = m * (degree p)\"\n    proof(cases \"Suc n > degree p\")\n      case True\n      then show ?thesis using IH A0 by simp\n    next\n      case False\n      then show ?thesis \n      proof-\n        obtain q where q_def: \"q = trunc p\"\n          by simp\n        obtain k where k_def: \"k = degree q\"\n          by simp\n        have q_is_poly: \"q \\<in> carrier P\" \n          by (simp add: A0 q_def trunc_simps(3))\n        have k_bound0: \"k <degree p\" \n          using k_def q_def trunc_degree[of p] A0 False by auto\n        have k_bound1: \"k \\<le> n\" \n          using k_bound0 A0 A1 by auto  \n        have P_q:\"degree (q [^]\\<^bsub>P\\<^esub> m) = m * k\" \n          using IH[of \"q\"] k_bound1 k_def q_is_poly by auto  \n        have P_lt: \"degree ((lt p) [^]\\<^bsub>P\\<^esub> m) = m*(degree p)\"\n        proof-\n          have \"degree p = degree (lt p)\" \n            by (simp add: A0)\n          then show ?thesis using monom_degree \n            using A0 P_def coeff_simp1 deg_nzero_nzero \n              k_bound0 lcoeff_closed lcoeff_nonzero2 leading_term_def \n               by (metis k_def nat_neq_iff q_def trunc_zero)\n        qed\n        have \"p = q \\<oplus>\\<^bsub>P\\<^esub> (lt p)\" \n          by (simp add: A0 q_def trunc_simps(1))\n        then show ?thesis \n          using P_q pow_sum[of \"(lt p)\" q m] A0 UP_a_comm \n            degree_lt k_bound0 k_def lt_in_car q_is_poly by auto\n      qed\n    qed\n  qed\nqed\n\nlemma deg_pow:\n  assumes \"p \\<in> carrier P\"\n  shows \"degree (p [^]\\<^bsub>P\\<^esub> m) = m*(degree p)\"\n  using deg_pow0 assms by blast\n\nlemma lt_pow0:\n\"\\<And>f. f \\<in> carrier P \\<Longrightarrow> lt (f [^]\\<^bsub>P\\<^esub> (n::nat)) = (lt f) [^]\\<^bsub>P\\<^esub> n\"\nproof(induction n)\n  case 0\n  then show ?case \n    by (metis P.nat_pow_0 P_def R.one_closed R_cring UP_cring.monom_pow \n        UP_cring_axioms cring_def lt_monom monoid.nat_pow_0 ring_def)\nnext\n  case (Suc n)\n  fix n::nat\n  assume IH: \"\\<And>f. f \\<in> carrier P \\<Longrightarrow> lt (f [^]\\<^bsub>P\\<^esub> n) = (lt f) [^]\\<^bsub>P\\<^esub> n\"\n  then show \"\\<And>f. f \\<in> carrier P \\<Longrightarrow> lt (f [^]\\<^bsub>P\\<^esub> (Suc n)) = (lt f) [^]\\<^bsub>P\\<^esub> (Suc n)\"\n  proof-\n    fix f\n    assume A: \"f \\<in> carrier P\"\n    show \" lt (f [^]\\<^bsub>P\\<^esub> (Suc n)) = (lt f) [^]\\<^bsub>P\\<^esub> (Suc n)\"\n    proof-\n      have 0: \"lt (f [^]\\<^bsub>P\\<^esub> n) = (lt f) [^]\\<^bsub>P\\<^esub> n\" \n        using A IH  by blast\n      have 1: \"lt (f [^]\\<^bsub>P\\<^esub> (Suc n)) = lt ((f [^]\\<^bsub>P\\<^esub> n)\\<otimes>\\<^bsub>P\\<^esub> f)\" \n        by auto then \n      show ?thesis using lt_mult 0 1 \n        by (simp add: A)\n    qed\n  qed\nqed\n\nlemma lt_pow:\n  assumes \"f \\<in> carrier P\"\n  shows \" lt (f [^]\\<^bsub>P\\<^esub> (n::nat)) = (lt f) [^]\\<^bsub>P\\<^esub> n\"\n  using assms lt_pow0 by blast\n\n(*Substitution into a monomial*)\n\nlemma sub_monom:\n  assumes \"a \\<in> carrier R\"\n  assumes \"a \\<noteq>\\<zero>\"\n  assumes \"f = monom P a n\"\n  assumes \"g \\<in> carrier P\"\n  shows \"degree (f of g) = n*(degree g)\"\nproof-\n  have \"f of g = (to_poly a) \\<otimes>\\<^bsub>P\\<^esub> (g[^]\\<^bsub>P\\<^esub>n)\"\n    unfolding compose_def\n    using assms UP_pre_univ_prop.eval_monom[of R P to_poly a g] to_poly_UP_pre_univ_prop \n    unfolding P_def  \n    by blast\n  then show ?thesis using deg_pow deg_mult \n    by (metis P.nat_pow_closed P_def assms(1) assms(2) \n        assms(4) deg_smult monom_mult_is_smult to_polynomial_def)\nqed\n\n(*Subbing a constant into a polynomial yields a constant*)\nlemma sub_in_const:\n  assumes \"g \\<in> carrier P\"\n  assumes \"f \\<in> carrier P\"\n  assumes \"degree g = 0\"\n  shows \"degree (f of g) = 0\"\nproof-\n  have \"\\<And>n. (\\<And>p. p \\<in> carrier P \\<Longrightarrow> degree p \\<le> n \\<Longrightarrow> degree (p of g) = 0)\"\n  proof-\n    fix n\n    show \"\\<And>p. p \\<in> carrier P \\<Longrightarrow> degree p \\<le> n \\<Longrightarrow> degree (p of g) = 0\"\n    proof(induction n)\n      case 0\n      then show ?case \n        by (simp add: assms(1))\n    next\n      case (Suc n)\n      fix n\n      assume IH: \"\\<And>p. p \\<in> carrier P \\<Longrightarrow> degree p \\<le> n \\<Longrightarrow> degree (p of g) = 0\"\n      show  \"\\<And>p. p \\<in> carrier P \\<Longrightarrow> degree p \\<le> (Suc n) \\<Longrightarrow> degree (p of g) = 0\"\n      proof-\n        fix p\n        assume A0: \"p \\<in> carrier P\"\n        assume A1: \"degree p \\<le> (Suc n)\"\n        show \"degree (p of g) = 0\"\n        proof(cases \"degree p < Suc n\")\n          case True\n          then show ?thesis using IH \n            using A0 by auto\n        next\n          case False\n          then have D: \"degree p = Suc n\" \n            by (simp add: A1 nat_less_le)\n          show ?thesis\n          proof-\n            have P0: \"degree ((trunc p) of g) = 0\" using IH \n              by (metis A0 D less_Suc_eq_le trunc_degree trunc_simps(3) zero_less_Suc)\n            have P1: \"degree ((lt p) of g) = 0\" \n              by (metis A0 D P_def UP_domain.sub_monom UP_domain_axioms assms(1) assms(3) \n                coeff_simp1 deg_nzero_nzero  lcoeff_closed lcoeff_nonzero2 \n                leading_term_def mult_is_0 nat_less_le zero_less_Suc)\n            have P2: \"p of g = (trunc p of g) \\<oplus>\\<^bsub>P\\<^esub> ((lt p) of g)\"\n              by (metis A0 assms(1) lt_in_car sub_add trunc_simps(1) trunc_simps(3))\n            then show ?thesis \n              using P0 P1 P2 deg_add[of \"trunc p of g\" \"lt p of g\"] \n              by (simp add: A0 assms(1) lt_in_car sub_closed trunc_simps(3))\n          qed\n        qed\n      qed\n    qed\n  qed\n  then show ?thesis \n    using assms(2) by blast\nqed\n\nlemma sub_deg0:\n  assumes \"g \\<in> carrier P\"\n  assumes \"f \\<in> carrier P\"\n  assumes \"g \\<noteq> \\<zero>\\<^bsub>P\\<^esub>\"\n  assumes \"f \\<noteq> \\<zero>\\<^bsub>P\\<^esub>\"\n  shows \"degree (f of g) = degree f * degree g\"\nproof-\n  have \"\\<And>n. \\<And> p. p \\<in> carrier P \\<Longrightarrow> (degree p) \\<le> n \\<Longrightarrow> degree (p of g) = degree p * degree g\"\n  proof-\n    fix n::nat\n    show \"\\<And> p. p \\<in> carrier P \\<Longrightarrow> (degree p) \\<le> n \\<Longrightarrow> degree (p of g) = degree p * degree g\"\n    proof(induction n)\n      case 0\n      then have B0: \"degree p = 0\" by auto \n      then show ?case using sub_const[of g p] \n        by (simp add: \"0.prems\"(1) assms(1))\n    next\n      case (Suc n)\n      fix n\n      assume IH: \"(\\<And>p. p \\<in> carrier P \\<Longrightarrow> degree p \\<le> n \\<Longrightarrow> degree (p of g) = degree p * degree g)\"\n      show \" p \\<in> carrier P \\<Longrightarrow> degree p \\<le> Suc n \\<Longrightarrow> degree (p of g) = degree p * degree g\"\n      proof-\n        assume A0: \"p \\<in> carrier P\"\n        assume A1: \"degree p \\<le> Suc n\"\n        show ?thesis \n        proof(cases \"degree p < Suc n\")\n          case True\n          then show ?thesis using IH \n            by (simp add: A0)\n        next\n          case False\n          then have D: \"degree p = Suc n\" \n            using A1 by auto  \n          have P0: \"(p of g) = ((trunc p) of g) \\<oplus>\\<^bsub>P\\<^esub> ((lt p) of g)\"\n            by (metis A0 assms(1) lt_in_car sub_add trunc_simps(1) trunc_simps(3))\n          have P1: \"degree ((trunc p) of g) = (degree (trunc p))*(degree g)\"\n            using IH  by (metis A0 D less_Suc_eq_le trunc_degree trunc_simps(3) zero_less_Suc)\n          have P2: \"degree ((lt p) of g) = (degree p) * degree g\"\n            using A0 D P_def UP_domain.sub_monom UP_domain_axioms assms(1) coeff_simp1\n              deg_zero  lcoeff_closed lcoeff_nonzero2 leading_term_def \n              by (metis False less_Suc_eq_0_disj)\n          then show ?thesis\n            proof(cases \"degree g = 0\")\n              case True\n              then show ?thesis \n                by (simp add: Suc(2) assms(1) sub_in_const)\n            next\n              case False\n              then show ?thesis \n              proof-\n                have P3: \"degree ((trunc p) of g) < degree ((lt p) of g)\"\n                  using False D  P1 P2  \n                  by (metis (no_types, lifting) A0 mult.commute mult_right_cancel \n                      nat_less_le nat_mult_le_cancel_disj trunc_degree zero_less_Suc)\n                then show ?thesis \n                  by (simp add: A0 P0 P2 UP_a_comm assms(1) degree_of_sum_diff_degree \n                    lt_in_car sub_closed trunc_simps(3))\n              qed\n            qed\n          qed\n        qed\n      qed\n    qed\n    then show ?thesis \n      using assms(2) by blast\n  qed\n\nlemma sub_deg:\n  assumes \"g \\<in> carrier P\"\n  assumes \"f \\<in> carrier P\"\n  assumes \"g \\<noteq> \\<zero>\\<^bsub>P\\<^esub>\"\n  shows \"degree (f of g) = degree f * degree g\"\nproof(cases \"f = \\<zero>\\<^bsub>P\\<^esub>\")\n  case True\n  then show ?thesis \n    using assms(1)  sub_const by auto\nnext\n  case False\n  then show ?thesis \n    by (simp add: assms(1) assms(2) assms(3) sub_deg0)\nqed\n\nlemma lt_sub:\n  assumes \"g \\<in> carrier P\"\n  assumes \"f \\<in> carrier P\"\n  assumes \"g \\<noteq> \\<zero>\\<^bsub>P\\<^esub>\"\n  assumes \"degree g \\<noteq> 0\"\n  shows \"lt (f of g) = lt ((lt f) of g)\"\nproof-\n  have P0: \"degree (f of g) = degree ((lt f) of g)\"\n    using sub_deg \n    by (simp add: assms(1) assms(2) assms(3)  lt_in_car)\n  have P1: \"f of g = ((trunc f) of g) \\<oplus>\\<^bsub>P\\<^esub>((lt f) of g)\"\n    by (metis assms(1) assms(2) lt_in_car rev_sub_add sub_rev_sub trunc_simps(1) trunc_simps(3))\n  then show ?thesis\n  proof(cases \"degree f = 0\")\n    case True\n    then show ?thesis \n      by (simp add: assms(2))\n  next\n    case False\n    then have P2: \"degree ((trunc f) of g) < degree ((lt f) of g)\"\n      using sub_deg \n      by (metis P0 assms(1) assms(2) assms(3) assms(4) mult_less_cancel2 neq0_conv trunc_degree trunc_simps(3))\n    then show ?thesis using P0 P1 P2 \n      by (simp add: UP_a_comm assms(1) assms(2) lt_in_car lt_of_sum_diff_degree sub_closed trunc_simps(3))\n  qed\nqed\n\n(*lemma on the leading coefficient*)\nlemma lc_eq:\n  assumes \"f \\<in> carrier P\"\n  shows \"lc f = lc (lt f)\"\n  unfolding leading_coefficient_def\n  using lt_deg_0 apply(auto simp: assms)\n  by (simp add: assms lt_coeffs)\n\nlemma lc_eq_deg_eq_imp_lt_eq:\n  assumes \"p \\<in> carrier P\"\n  assumes \"q \\<in> carrier P\"\n  assumes \"degree p > 0\"\n  assumes \"degree p = degree q\"\n  assumes \"lc p = lc q\"\n  shows \"lt p = lt q\"\n  using assms(4) assms(5) leading_coefficient_def \n  by (simp add: lc_lt)\n\nlemma lt_eq_imp_lc_eq:\n  assumes \"p \\<in> carrier P\"\n  assumes \"q \\<in> carrier P\"\n  assumes \"lt p = lt q\"\n  shows \"lc p = lc q\"\n  by (simp add: assms(1) assms(2) assms(3) lc_eq)\n\nlemma lt_eq_imp_deg_drop:\n  assumes \"p \\<in> carrier P\"\n  assumes \"q \\<in> carrier P\"\n  assumes \"lt p = lt q\"\n  assumes \"degree p >0\"\n  shows \"degree (p \\<ominus>\\<^bsub>P\\<^esub> q) < degree p\"\nproof-\n  have P0: \"degree p = degree q\"\n    by (metis assms(1) assms(2) assms(3) degree_lt)\n  then have P1: \"degree (p \\<ominus>\\<^bsub>P\\<^esub> q) \\<le> degree p\"\n    by (metis P.add.inv_solve_right P.minus_closed P.minus_eq assms(1)\n        assms(2) degree_of_sum_diff_degree neqE order.strict_implies_order order_refl)\n  have \"degree (p \\<ominus>\\<^bsub>P\\<^esub> q) \\<noteq> degree p\"\n  proof\n    assume A: \"degree (p \\<ominus>\\<^bsub>P\\<^esub> q) = degree p\"\n    have Q0: \"p \\<ominus>\\<^bsub>P\\<^esub> q = ((trunc p) \\<oplus>\\<^bsub>P\\<^esub> (lt p)) \\<ominus>\\<^bsub>P\\<^esub> ((trunc q) \\<oplus>\\<^bsub>P\\<^esub> (lt p))\"\n      using assms(1) assms(2) assms(3) trunc_simps(1) by force\n    have Q1: \"p \\<ominus>\\<^bsub>P\\<^esub> q = (trunc p)  \\<ominus>\\<^bsub>P\\<^esub> (trunc q)\" \n    proof-\n      have \"p \\<ominus>\\<^bsub>P\\<^esub> q = ((trunc p) \\<oplus>\\<^bsub>P\\<^esub> (lt p)) \\<ominus>\\<^bsub>P\\<^esub> (trunc q) \\<ominus> \\<^bsub>P\\<^esub> (lt p)\"\n        using Q0 \n        by (simp add: P.minus_add P.minus_eq UP_a_assoc assms(1) assms(2) lt_in_car trunc_simps(3))\n      then show ?thesis \n        by (metis (no_types, lifting) P.add.inv_mult_group P.minus_eq P_def UP_a_assoc assms(1)\n            assms(2) assms(3) carrier_is_submodule lt_in_car poly_sub.truncate_def submoduleE(3) \n            trunc_simps(1) trunc_simps(3))\n    qed\n    have Q2: \"degree (trunc p) < degree p\" \n      by (simp add: assms(1) assms(4) trunc_degree)\n    have Q3: \"degree (trunc q) < degree q\" \n      using P0 assms(2) assms(4) trunc_degree by auto\n    then show False  using A Q1 Q2 Q3 by (simp add: P.add.inv_solve_right\n          P.minus_eq P0 assms(1) assms(2) degree_of_sum_diff_degree trunc_simps(3))\n  qed\n  then show ?thesis \n    using P1 by auto\nqed\n\nlemma lc_scalar_mult:\n  assumes \"p \\<in> carrier P\"\n  assumes \"a \\<in> carrier R\"\n  shows \"lc (a \\<odot>\\<^bsub>P\\<^esub> p) = a \\<otimes> (lc p)\"\nproof-\n  have \"lc (a \\<odot>\\<^bsub>P\\<^esub> p) = lc (lt (a \\<odot>\\<^bsub>P\\<^esub> p))\"\n    by (simp add: assms(1) assms(2) lc_eq)\n  then have \"lc (a \\<odot>\\<^bsub>P\\<^esub> p) = lc (a \\<odot>\\<^bsub>P\\<^esub> (lt p))\"\n    by (simp add: assms(1) assms(2) lt_smult)\n  then show ?thesis \n    unfolding leading_term_def leading_coefficient_def\n    by (metis P.m_comm P.r_null P_def UP_zero_closed assms(1) assms(2) \n        coeff_monom coeff_simp1 coeff_smult deg_smult  monom_mult_is_smult\n        monom_zero smult_closed)\nqed\n\nlemma lc_monom:\n  assumes \"a \\<in> carrier R\"\n  assumes \"f = monom P a n\"\n  shows \"lc f = a\"\n  by (metis P_def assms(1) assms(2) coeff_monom coeff_simp1 deg_monom  leading_coefficient_def monom_closed)\n\nlemma lc_monom_simp[simp]:\n  assumes \"a \\<in> carrier R\"\n  shows \"lc (monom P a n) = a\"\n  by (simp add: assms lc_monom)\n\nlemma lc_mult:\n  assumes \"p \\<in> carrier P\"\n  assumes \"q \\<in> carrier P\"\n  shows \"lc (p \\<otimes>\\<^bsub>P\\<^esub> q) = (lc p) \\<otimes> (lc q)\"\nproof-\n  have P0: \"lt (p \\<otimes>\\<^bsub>P\\<^esub> q) = (lt p) \\<otimes>\\<^bsub>P\\<^esub> (lt q)\"\n    using assms lt_mult by auto \n  obtain a where a_def: \"a \\<in> carrier R \\<and> (lt p) = monom P a (degree p)\"\n    using P_fact0 assms(1)   by (metis P_def leading_term_def)\n  obtain b where b_def: \"b \\<in> carrier R \\<and> (lt q) = monom P b (degree q)\"\n    using P_fact0 assms(2) leading_term_def  P_def by blast\n  have P1: \"a = lc p\" using a_def \n    by (metis P_def assms(1) coeff_monom coeff_simp1 leading_coefficient_def lt_coeffs monom_closed)\n  have P2: \"b = lc q\" using b_def \n    by (metis P_def assms(2) coeff_monom coeff_simp1 leading_coefficient_def lt_coeffs monom_closed)\n  have P3: \"(lt p) \\<otimes>\\<^bsub>P\\<^esub> (lt q) =  monom P (a \\<otimes> b) ((degree p) + (degree q))\"\n    using a_def b_def  by simp\n  then have P4: \"lc ((lt p) \\<otimes>\\<^bsub>P\\<^esub> (lt q)) = a \\<otimes>b\"\n    using R.m_closed a_def b_def lc_monom by blast\n  show ?thesis using P0 P1 P2 P4 \n    by (simp add: assms(1) assms(2) lc_eq)\nqed\n\nlemma lc_pow:\n  assumes \"p \\<in> carrier P\"\n  shows \"lc (p[^]\\<^bsub>P\\<^esub>(n::nat)) = (lc p)[^]n\"\nproof-\n  show ?thesis \n  proof(induction n)\n    case 0\n    then show ?case \n      by (metis (no_types, lifting) P.nat_pow_0 P_def R.nat_pow_0 R.one_closed\n          UP_domain.lc_monom UP_domain_axioms UP_pre_univ_prop.axioms(1) \n          ring_hom_cring.hom_pow to_poly_UP_pre_univ_prop to_polynomial_def)\n  next\n    case (Suc n)\n    fix n\n    assume IH: \"lc (p[^]\\<^bsub>P\\<^esub>(n::nat)) = (lc p)[^]n\"\n    show \"lc (p[^]\\<^bsub>P\\<^esub>(Suc n)) = (lc p)[^](Suc n)\"\n    proof-\n      have \"lc (p[^]\\<^bsub>P\\<^esub>(Suc n)) = lc ((p[^]\\<^bsub>P\\<^esub>n) \\<otimes>\\<^bsub>P\\<^esub>p)\"\n        by simp\n      then have \"lc (p[^]\\<^bsub>P\\<^esub>(Suc n)) = (lc p)[^]n \\<otimes> (lc p)\"\n        by (simp add: IH assms lc_mult)\n      then show ?thesis by auto \n    qed\n  qed\nqed\n\nlemma lc_of_sub_in_lt:\n  assumes \"g \\<in> carrier P\"\n  assumes \"f \\<in> carrier P\"\n  assumes \"degree f = n\"\n  assumes \"g \\<noteq> \\<zero>\\<^bsub>P\\<^esub>\"\n  assumes \"degree g \\<noteq> 0\"\n  shows \"lc ((lt f) of g) = (lc f) \\<otimes> ((lc g)[^]n)\"\nproof(cases \"degree f = 0\")\n  case True\n  then show ?thesis \n    by (metis P_def UP_cring_axioms UP_cring_def assms(1) assms(2) assms(3) coeff_simp1 \n        cring_def  leading_coefficient_def lcoeff_closed lt_deg_0 monoid.nat_pow_0\n        monoid.r_one ring_def sub_const)\nnext\n  case False\n  then show ?thesis \n  proof-\n    have P0: \"(lt f) of g = (to_poly (lc f)) \\<otimes>\\<^bsub>P\\<^esub> (g[^]\\<^bsub>P\\<^esub>n)\"\n      unfolding compose_def\n      using assms UP_pre_univ_prop.eval_monom[of R P to_poly \"(lc f)\" g n] to_poly_UP_pre_univ_prop \n      unfolding P_def  \n      using P_def coeff_simp1  leading_coefficient_def lc_lt lcoeff_closed \n      by (simp add: leading_coefficient_def P_fact0)\n    have P1: \"(lt f) of g = (lc f) \\<odot>\\<^bsub>P\\<^esub>(g[^]\\<^bsub>P\\<^esub>n)\"\n      using P0 P.nat_pow_closed \n      by (metis P_def assms(1) assms(2) coeff_simp1 leading_coefficient_def \n          lcoeff_closed monom_mult_is_smult to_polynomial_def)\n\n    have P2: \"lt ((lt f) of g) = (lt (to_poly (lc f))) \\<otimes>\\<^bsub>P\\<^esub> (lt (g[^]\\<^bsub>P\\<^esub>n))\"\n      using P0 lt_mult P.nat_pow_closed P_def assms(1) assms(2) coeff_simp1 \n         leading_coefficient_def lcoeff_closed to_poly_is_poly \n      by (simp add: leading_coefficient_def)\n    have P3: \"lt ((lt f) of g) =  (to_poly (lc f)) \\<otimes>\\<^bsub>P\\<^esub> (lt (g[^]\\<^bsub>P\\<^esub>n))\"\n      using P2  by (simp add: P_fact0 assms(2)  leading_coefficient_def to_poly_is_poly)\n    have P4: \"lt ((lt f) of g) = (lc f) \\<odot>\\<^bsub>P\\<^esub> ((lt g)[^]\\<^bsub>P\\<^esub>n)\"\n      using P.nat_pow_closed P1 P_def assms(1) assms(2) coeff_simp1 \n         leading_coefficient_def lcoeff_closed lt_pow0 lt_smult \n        by (simp add: leading_coefficient_def)\n    have P5: \"lc ((lt f) of g) = (lc f) \\<otimes> (lc ((lt g)[^]\\<^bsub>P\\<^esub>n))\"\n      using lc_scalar_mult P4  by (metis P.nat_pow_closed P1 P_fact0 \n          UP_smult_closed assms(1) assms(2) assms(3) leading_coefficient_def lc_eq lt_in_car sub_rev_sub)\n    show ?thesis\n      using P5 lt_pow lc_pow assms(1) lc_eq lt_in_car by presburger\n  qed\nqed\n\nlemma lt_of_sub_in_lt:\n  assumes \"g \\<in> carrier P\"\n  assumes \"f \\<in> carrier P\"\n  assumes \"degree f = n\"\n  assumes \"g \\<noteq> \\<zero>\\<^bsub>P\\<^esub>\"\n  assumes \"degree g \\<noteq> 0\"\n  shows \"lt ((lt f) of g) = (lc f) \\<odot>\\<^bsub>P\\<^esub> ((lt g)[^]\\<^bsub>P\\<^esub>n)\"\nproof-\n  have \"lt f = (monom P (lc f) (degree f))\"\n    by (simp add: lc_lt)\n  then have \"lt f = (lc f) \\<odot>\\<^bsub>P\\<^esub>  (monom P \\<one> (degree f))\"\n    by (metis P.r_one P_def R.one_closed UP_domain.lc_mult UP_domain_axioms \n        UP_one_closed assms(2) coeff_simp1 lc_monom lcoeff_closed \n        leading_coefficient_def monom_mult_smult monom_one)\n  then have 0:\"lt f = (lc f) \\<odot>\\<^bsub>P\\<^esub>  (monom P \\<one> n)\" \n    using assms(3) by simp\n  then have 1: \"lt f = to_poly (lc f) \\<otimes>\\<^bsub>P\\<^esub>  (monom P \\<one> n)\" \n    by (metis P_def R.one_closed assms(2) coeff_simp1 lcoeff_closed \n        leading_coefficient_def monom_closed monom_mult_is_smult to_polynomial_def)\n  have 2:\"(monom P \\<one> n)of g = (g[^]\\<^bsub>P\\<^esub>n) \" \n    by (metis (no_types, lifting) P.m_lcomm P.nat_pow_closed P.r_one P_def \n        R.one_closed UP_one_closed UP_pre_univ_prop.eval_monom assms(1) \n        monom_one poly_sub.compose_def to_poly_UP_pre_univ_prop to_polynomial_def)\n  have 3: \" ((lt f) of g) =  (to_poly (lc f) \\<otimes>\\<^bsub>P\\<^esub>  (g[^]\\<^bsub>P\\<^esub>n))\" using 1 2  \n    by (metis (no_types, lifting) P_def UP_pre_univ_prop.eval_monom\n        \\<open>lt f = monom P (lc f) (degree f)\\<close> assms(1) assms(2) assms(3) coeff_simp1 lcoeff_closed\n        leading_coefficient_def poly_sub.compose_def to_poly_UP_pre_univ_prop)\n  have 4: \" (to_poly (lc f) \\<otimes>\\<^bsub>P\\<^esub>  (g[^]\\<^bsub>P\\<^esub>n)) =  ((lc f) \\<odot>\\<^bsub>P\\<^esub>  (g[^]\\<^bsub>P\\<^esub>n))\" \n    using  P_def R.one_closed assms(2) coeff_simp1 lcoeff_closed \n        leading_coefficient_def monom_closed monom_mult_is_smult \n        by (metis P.nat_pow_closed assms(1) to_polynomial_def)\n  have 5: \" ((lt f) of g) =  ((lc f) \\<odot>\\<^bsub>P\\<^esub>  (g[^]\\<^bsub>P\\<^esub>n))\" \n    using 3 4  by simp\n  have \"degree  ((lc f) \\<odot>\\<^bsub>P\\<^esub>  (g[^]\\<^bsub>P\\<^esub>n)) = degree ((lc f) \\<odot>\\<^bsub>P\\<^esub> ((lt g)[^]\\<^bsub>P\\<^esub>n))\"\n    by (simp add: P_fact0 assms(1) assms(2) deg_pow leading_coefficient_def lt_in_car)\n  then have P0: \"degree ((lt f) of g) = degree ((lc f) \\<odot>\\<^bsub>P\\<^esub> ((lt g)[^]\\<^bsub>P\\<^esub>n))\" \n    using 5 by simp\n  have P1: \"lc ((lt f) of g) = lc ((lc f) \\<odot>\\<^bsub>P\\<^esub> ((lt g)[^]\\<^bsub>P\\<^esub>n))\" \n  proof-\n    have A0: \"lc ((lt f) of g) = (lc f) \\<otimes> ((lc g)[^]n)\" \n      using assms(1) assms(2) assms(3) assms(4) assms(5) lc_of_sub_in_lt by blast\n    have A1: \"lc ((lc f) \\<odot>\\<^bsub>P\\<^esub> ((lt g)[^]\\<^bsub>P\\<^esub>n)) = (lc f) \\<otimes> (lc ((lt g)[^]\\<^bsub>P\\<^esub>n))\"\n      using P_fact0 assms(1) assms(2) leading_coefficient_def lc_scalar_mult lt_in_car \n      by (simp add: leading_coefficient_def)\n    then show ?thesis \n      using A0 A1 lc_pow assms  by (metis lc_eq lt_in_car)\n  qed\n  have P2: \"lt ((lt f) of g) = lt ((lc f) \\<odot>\\<^bsub>P\\<^esub> ((lt g)[^]\\<^bsub>P\\<^esub>n))\" \n    using P0 P1   by (simp add: lc_lt)\n  then show ?thesis \n    using P.nat_pow_closed P_def assms(1) assms(2) coeff_simp1 \n       leading_coefficient_def lcoeff_closed lt_in_car lt_pow0 lt_smult \n        by (simp add: P2 leading_coefficient_def)\nqed\n\n(*formula for the leading term of f \\<circ> g *)\nlemma lt_of_sub:\n  assumes \"g \\<in> carrier P\"\n  assumes \"f \\<in> carrier P\"\n  assumes \"degree f = n\"\n  assumes \"g \\<noteq> \\<zero>\\<^bsub>P\\<^esub>\"\n  assumes \"degree g \\<noteq> 0\"\n  shows \"lt (f of g) = (lc f) \\<odot>\\<^bsub>P\\<^esub> ((lt g)[^]\\<^bsub>P\\<^esub>n)\"\n  using assms lt_sub lt_of_sub_in_lt apply auto \n  done\n(*subtitution is associative*)\n\nlemma sub_assoc_monom:\n  assumes \"f \\<in> carrier P\"\n  assumes \"q \\<in> carrier P\"\n  assumes \"r \\<in> carrier P\"\n  shows \"(lt f) of (q of r) = ((lt f) of q) of r\"\nproof-\n  obtain n where n_def: \"n = degree f\"\n    by simp\n  obtain a where a_def: \"a \\<in> carrier R \\<and> (lt f) = monom P a n\"\n    using P_fact0 assms(1) leading_coefficient_def lc_lt n_def  by metis\n  have LHS: \"(lt f) of (q of r) = a \\<odot>\\<^bsub>P\\<^esub> (q of r)[^]\\<^bsub>P\\<^esub> n\"\n    by (metis P.nat_pow_closed P_def UP_pre_univ_prop.eval_monom a_def assms(2)\n        assms(3) compose_def monom_mult_is_smult sub_closed to_poly_UP_pre_univ_prop to_polynomial_def)\n  have RHS0: \"((lt f) of q) of r = (a \\<odot>\\<^bsub>P\\<^esub> q[^]\\<^bsub>P\\<^esub> n)of r\"\n    by (metis P.nat_pow_closed P_def UP_pre_univ_prop.eval_monom a_def \n        assms(2) compose_def monom_mult_is_smult to_poly_UP_pre_univ_prop to_polynomial_def)\n  have RHS1: \"((lt f) of q) of r = ((to_poly a) \\<otimes>\\<^bsub>P\\<^esub> q[^]\\<^bsub>P\\<^esub> n)of r\"\n    using RHS0  by (metis P.nat_pow_closed P_def a_def \n        assms(2) monom_mult_is_smult to_polynomial_def)\n  have RHS2: \"((lt f) of q) of r = ((to_poly a) of r) \\<otimes>\\<^bsub>P\\<^esub> (q[^]\\<^bsub>P\\<^esub> n of r)\"\n    using RHS1 a_def assms(2) assms(3) sub_mult to_poly_is_poly by auto\n  have RHS3: \"((lt f) of q) of r = (to_poly a) \\<otimes>\\<^bsub>P\\<^esub> (q[^]\\<^bsub>P\\<^esub> n of r)\"\n    using RHS2 a_def assms(3) sub_to_poly by auto\n  have RHS4: \"((lt f) of q) of r = a \\<odot>\\<^bsub>P\\<^esub> ((q[^]\\<^bsub>P\\<^esub> n)of r)\"\n    using RHS3 \n    by (metis P.nat_pow_closed P_def a_def assms(2) assms(3) \n        monom_mult_is_smult sub_closed to_polynomial_def)\n  have \"(q of r)[^]\\<^bsub>P\\<^esub> n = ((q[^]\\<^bsub>P\\<^esub> n)of r)\" \n    apply(induction n) apply(auto) apply (simp add: assms(3))\n    using assms sub_mult  by simp\n  then show ?thesis using RHS4 LHS by simp\nqed\n\nlemma sub_assoc:\n  assumes \"f \\<in> carrier P\"\n  assumes \"q \\<in> carrier P\"\n  assumes \"r \\<in> carrier P\"\n  shows \"f of (q of r) = (f of q) of r\"\nproof-\n  have \"\\<And> n. \\<And> p. p \\<in> carrier P \\<Longrightarrow> degree p \\<le> n \\<Longrightarrow> p of (q of r) = (p of q) of r\"\n  proof-\n    fix n\n    show \"\\<And> p. p \\<in> carrier P \\<Longrightarrow> degree p \\<le> n \\<Longrightarrow> p of (q of r) = (p of q) of r\"\n    proof(induction n)\n      case 0\n      then have \"degree p = 0\"\n        by blast\n      then have B0: \"p of (q of r) = p\"\n        using sub_const[of \"q of r\" p] assms  \"0.prems\"(1) sub_closed by blast\n      have B1: \"(p of q) of r = p\"\n      proof-\n        have \"p of q = p\"\n          by (simp add: \"0.prems\"(1) \\<open>degree p = 0\\<close> assms(2))\n        then show ?thesis \n          by (simp add: \"0.prems\"(1) \\<open>degree p = 0\\<close> assms(3))\n      qed\n      then show \"p of (q of r) = (p of q) of r\" using B0 B1 by auto \n    next\n      case (Suc n)\n      fix n\n      assume IH: \"\\<And> p. p \\<in> carrier P \\<Longrightarrow> degree p \\<le> n \\<Longrightarrow> p of (q of r) = (p of q) of r\"\n      then show \"\\<And> p. p \\<in> carrier P \\<Longrightarrow> degree p \\<le> Suc n \\<Longrightarrow> p of (q of r) = (p of q) of r\"\n      proof-\n        fix p\n        assume A0: \" p \\<in> carrier P \"\n        assume A1: \"degree p \\<le> Suc n\"\n        show \"p of (q of r) = (p of q) of r\"\n        proof(cases \"degree p < Suc n\")\n          case True\n          then show ?thesis using A0 A1 IH by auto \n        next\n          case False\n          then have \"degree p = Suc n\"\n            using A1 by auto \n          have I0: \"p of (q of r) = ((trunc p) \\<oplus>\\<^bsub>P\\<^esub> (lt p)) of (q of r)\"\n            using A0 trunc_simps(1) by auto\n          have I1: \"p of (q of r) = ((trunc p)  of (q of r)) \\<oplus>\\<^bsub>P\\<^esub> ((lt p)  of (q of r))\"\n            using I0 sub_add \n            by (simp add: A0 assms(2) assms(3) lt_in_car rev_sub_closed sub_rev_sub trunc_simps(3))\n          have I2: \"p of (q of r) = (((trunc p)  of q) of r) \\<oplus>\\<^bsub>P\\<^esub> (((lt p)  of q) of r)\"\n            using IH[of \"trunc p\"] sub_assoc_monom[of p q r] \n            by (metis A0 I1 \\<open>degree p = Suc n\\<close> assms(2) assms(3) \n                less_Suc_eq_le trunc_degree trunc_simps(3) zero_less_Suc)\n          have I3: \"p of (q of r) = (((trunc p)  of q) \\<oplus>\\<^bsub>P\\<^esub> ((lt p)  of q)) of r\"\n            using sub_add trunc_simps(1) assms   \n            by (simp add: A0 I2 lt_in_car sub_closed trunc_simps(3))\n          have I4: \"p of (q of r) = (((trunc p)\\<oplus>\\<^bsub>P\\<^esub>(lt p))   of q)  of r\"\n            using sub_add trunc_simps(1) assms   \n            by (simp add: trunc_simps(1) A0 I3 lt_in_car trunc_simps(3))\n          then show ?thesis \n            using A0 trunc_simps(1) by auto\n        qed\n      qed\n    qed\n  qed\n  then show ?thesis \n    using assms(1) by blast\nqed\n\nlemma sub_smult:\n  assumes \"f \\<in> carrier P\"\n  assumes \"q \\<in> carrier P\"\n  assumes \"a \\<in> carrier R\"\n  shows \"(a\\<odot>\\<^bsub>P\\<^esub>f ) of q = a\\<odot>\\<^bsub>P\\<^esub>(f of q)\"\nproof-\n  have \"(a\\<odot>\\<^bsub>P\\<^esub>f ) of q = ((to_poly a) \\<otimes>\\<^bsub>P\\<^esub>f) of q\"\n    using assms  by (metis P_def monom_mult_is_smult to_polynomial_def)\n    then have \"(a\\<odot>\\<^bsub>P\\<^esub>f ) of q = ((to_poly a) of q) \\<otimes>\\<^bsub>P\\<^esub>(f of q)\"\n      by (simp add: assms(1) assms(2) assms(3) sub_mult to_poly_is_poly)\n      then have \"(a\\<odot>\\<^bsub>P\\<^esub>f ) of q = (to_poly a) \\<otimes>\\<^bsub>P\\<^esub>(f of q)\"\n        by (simp add: assms(2) assms(3))\n        then show ?thesis \n          by (metis P_def assms(1) assms(2) assms(3) \n              monom_mult_is_smult sub_closed to_polynomial_def)\n      qed\nend\n(**************************************************************************************************)\n(**************************************************************************************************)\n(***************************  Constructor for monic linear polynomials  ***************************)\n(**************************************************************************************************)\n(**************************************************************************************************)\n\n(*The polynomial representing the variable X*)\n\ndefinition X_poly where\n\"X_poly R= monom (UP R) \\<one>\\<^bsub>R\\<^esub> 1\"\n\n\ncontext UP_domain\nbegin\n\nabbreviation X where\n\"X \\<equiv> X_poly R\"\n\nlemma X_is_poly:\n\"X \\<in> carrier P\"\n  unfolding X_poly_def \n  using P_def monom_closed by blast\n\nlemma degree_X:\n\"degree X = 1\" \n  unfolding X_poly_def \n  using P_def deg_monom  by auto\n\nlemma X_not_zero:\n\"X \\<noteq> \\<zero>\\<^bsub>P\\<^esub>\"\n  using degree_X  by fastforce\n\n\nlemma X_sub0[simp]:\n  assumes \"p \\<in> carrier P\"\n  shows \"X of p = p\"\n  unfolding X_poly_def\n  using P_def UP_pre_univ_prop.eval_monom1 assms compose_def to_poly_UP_pre_univ_prop \n  by metis\n\nlemma X_sub[simp]:\n  assumes \"p \\<in> carrier P\"\n  shows \"p of X = p\"\nproof-\n  have \"\\<And>n. \\<And>f. f \\<in> carrier P \\<Longrightarrow> degree f \\<le>n \\<Longrightarrow> f of X = f\"\n  proof-\n    fix n\n    show \" \\<And>f. f \\<in> carrier P \\<Longrightarrow> degree f \\<le>n \\<Longrightarrow> f of X = f\"\n    proof(induction n)\n      case 0\n      then show ?case \n        by (simp add: X_is_poly)\n    next\n      case (Suc n)\n      fix n\n      assume IH: \" \\<And>f. f \\<in> carrier P \\<Longrightarrow> degree f \\<le>n \\<Longrightarrow> f of X = f\"\n      fix f\n      show \"f \\<in> carrier P \\<Longrightarrow> degree f \\<le>(Suc n) \\<Longrightarrow> f of X = f\"\n      proof-\n        assume A0: \"f \\<in> carrier P\"\n        assume A1: \"degree f \\<le>(Suc n)\"\n        show \" f of X = f\"\n        proof(cases \"degree f < Suc n\")\n          case True\n          then show ?thesis using IH A0 A1 \n            using Suc_leI by blast\n        next\n          case False\n          have D: \"degree f = Suc n\"\n            using A1 False nat_less_le by blast\n          have \"f of X = (trunc f) of X \\<oplus>\\<^bsub>P\\<^esub> (lt f) of X\"\n            by (metis A0 P_def UP_domain.trunc_simps(1) UP_domain_axioms X_is_poly lt_in_car sub_add trunc_simps(3))\n          then have P: \"f of X = (trunc f) \\<oplus>\\<^bsub>P\\<^esub> ((lt f) of X)\"\n            using D IH[of \"trunc f\"] \n            by (metis A0 P_def UP_domain.trunc_simps(3) UP_domain_axioms \n                less_Suc_eq_le trunc_degree zero_less_Suc)\n          have \"lt f =  ((lt f) of X)\"\n          proof-\n            have 0: \"lt f = (lc f) \\<odot>\\<^bsub>P\\<^esub> (monom P \\<one> (degree f))\"\n              by (metis A0 D P_fact0 R.l_one R.m_comm R.one_closed \n                  leading_coefficient_def lc_lt monom_mult_smult)\n            then have 1: \"((lt f) of X) = (lc f) \\<odot>\\<^bsub>P\\<^esub> (monom P \\<one> (degree f)) of X\"\n              by simp\n            then have 2: \"((lt f) of X) = (lc f) \\<odot>\\<^bsub>P\\<^esub> (monom P \\<one> (degree f) of X)\"\n              using A0 P_def X_is_poly coeff_simp1  leading_coefficient_def\n                lcoeff_closed monom_closed sub_smult \n              by (simp add: leading_coefficient_def)\n            have 3: \"((lt f) of X) = (lc f) \\<odot>\\<^bsub>P\\<^esub> (X[^]\\<^bsub>P\\<^esub>(degree f))\" \n              using \"2\" P.nat_pow_closed P_def R.one_closed R_cring  UP_pre_univ_prop.eval_monom \n                  X_is_poly compose_def monom_one   to_poly_UP_pre_univ_prop  \n              by (metis (no_types, lifting) UP_one_closed UP_ring.UP_ring \n                  UP_ring.intro cring_def deg_one leading_coefficient_def \n                  lc_monom monoid.l_one ring_def to_poly_inverse)\n            then show ?thesis unfolding X_poly_def P_def using 0  \n              using P_def monom_pow by auto\n          qed\n          then show ?thesis using P \n            using A0 P_def UP_domain.trunc_simps(1) UP_domain_axioms by fastforce\n        qed\n      qed\n    qed\n  qed\n  then show ?thesis \n    using assms by blast\nqed\n\n(*representation of monomials as scalar multiples of powers of X*)\nlemma monom_rep_X_pow:\n  assumes \"a \\<in> carrier R\"\n  shows \"monom P a n = a\\<odot>\\<^bsub>P\\<^esub>(X[^]\\<^bsub>P\\<^esub>n)\"\nproof-\n  have \"monom P a n = a\\<odot>\\<^bsub>P\\<^esub>monom P \\<one> n\"\n    by (metis R.one_closed R.r_one assms monom_mult_smult)\n  then show ?thesis \n    unfolding X_poly_def \n    using monom_pow \n    by (simp add: P_def)\nqed\n\nlemma lt_rep_X_pow:\n  assumes \"p \\<in> carrier P\"\n  shows \"lt p = (lc p)\\<odot>\\<^bsub>P\\<^esub>(X[^]\\<^bsub>P\\<^esub>(degree p))\"\nproof-\n  have \"lt p =  monom P (lc p) (degree p)\"\n    using assms unfolding leading_term_def leading_coefficient_def by (simp add: P_def)\n  then show ?thesis \n    using monom_rep_X_pow P_def assms coeff_simp1  leading_coefficient_def lcoeff_closed \n    by (simp add: leading_coefficient_def)\nqed\nend\n(*monic linear polynomials*)\n\ndefinition X_poly_plus where\n\"X_poly_plus R a = (X_poly R) \\<oplus>\\<^bsub>(UP R)\\<^esub> to_polynomial R a\"\n\ndefinition X_poly_minus where\n\"X_poly_minus R a = (X_poly R) \\<ominus>\\<^bsub>(UP R)\\<^esub> to_polynomial R a\"\n\ncontext UP_domain\nbegin\n\nabbreviation X_plus where\n\"X_plus \\<equiv> X_poly_plus R\"\n\nabbreviation X_minus where\n\"X_minus \\<equiv> X_poly_minus R\"\n\nlemma X_plus_is_poly:\n  assumes \"a \\<in> carrier R\"\n  shows \"(X_plus a) \\<in> carrier P\"\n  unfolding X_poly_plus_def using X_is_poly to_poly_is_poly \n  using P_def UP_a_closed assms by auto\n\nlemma X_minus_is_poly:\n  assumes \"a \\<in> carrier R\"\n  shows \"(X_minus a) \\<in> carrier P\"\n  unfolding X_poly_minus_def using X_is_poly to_poly_is_poly \n  by (simp add: P_def UP_ring.UP_ring UP_ring_axioms assms ring.ring_simprules(4))\n\nlemma X_minus_plus:\n  assumes \"a \\<in> carrier R\"\n  shows \"(X_minus a) = X_plus (\\<ominus>a)\"\n  using P_def UP_ring.UP_ring  UP_ring_axioms\n  by (simp add: UP_ring.UP_ring X_poly_minus_def X_poly_plus_def assms ring.ring_simprules(14))\n\nlemma degree_of_X_plus:\n  assumes \"a \\<in> carrier R\"\n  shows \"degree (X_plus a) = 1\"\nproof-\n  have 0:\"degree (X_plus a) \\<le> 1\"\n    using deg_add  P_def X_poly_plus_def \n      UP_domain_axioms X_is_poly assms degree_X to_poly_is_poly \n      by (metis UP_domain.degree_to_poly max_0_1(2))\n  have 1:\"degree (X_plus a) > 0\"\n    by (metis One_nat_def P_def R.one_closed R.r_zero X_poly_def \n        X_is_poly X_poly_plus_def X_plus_is_poly  assms  coeff_add coeff_monom deg_aboveD  \n        degree_X  gr0I lcoeff_nonzero_deg  lessI  n_not_Suc_n to_polynomial_def to_poly_is_poly)\n  then show ?thesis \n    using \"0\" by linarith\nqed\n\nlemma degree_of_X_minus:\n  assumes \"a \\<in> carrier R\"\n  shows \"degree (X_minus a) = 1\"\n  using degree_of_X_plus[of \"\\<ominus>a\"] X_minus_plus[simp] assms by auto  \n\nlemma lt_of_X:\n\"lt X = X\"\n  unfolding leading_term_def\n  by (metis P_def R.one_closed X_poly_def X_is_poly coeff_monom coeff_simp1 degree_X)\n\nlemma lt_of_X_plus:\n  assumes \"a \\<in> carrier R\"\n  shows \"lt (X_plus a) = X\"\n  unfolding X_poly_plus_def\n  using X_is_poly  assms  lt_of_sum_diff_degree[of X \"to_poly a\"]  \n    degree_to_poly[of a]  to_poly_is_poly[of a] degree_X lt_of_X \n    by (simp add: P_def)  \n\nlemma lt_of_X_minus:\n  assumes \"a \\<in> carrier R\"\n  shows \"lt (X_plus a) = X\"\n  using X_minus_plus[of a]  assms lt_of_X_plus by blast\n\n(*Linear substituions*)\n \n\ndefinition trans_left where\n\"trans_left f a = f of (X_minus a)\"\n\nlemma trans_left_is_poly:\n  assumes \"a \\<in> carrier R\"\n  assumes \"f \\<in> carrier P\"\n  shows \"trans_left f a \\<in> carrier P\"\n  unfolding trans_left_def using assms X_minus_is_poly[of a]\n  sub_closed by blast\n\nlemma trans_left_deg:\n  assumes \"a \\<in> carrier R\"\n  assumes \"f \\<in> carrier P\"\n  shows \"degree (trans_left f a) = degree f\" \n  unfolding trans_left_def \n  using assms sub_deg[of f \"X_minus a\"] \n        degree_of_X_minus[of a] \n        X_minus_is_poly[of a]\n  apply auto\n  using deg_nzero_nzero  sub_deg by auto\n\nlemma X_plus_sub_deg:\n  assumes \"a \\<in> carrier R\"\n  assumes \"f \\<in> carrier P\"\n  shows \"degree (f of (X_plus a)) = degree f\"\n  by (metis  X_plus_is_poly assms(1) assms(2) \n      deg_zero   degree_of_X_plus \n        mult.right_neutral  sub_deg zero_neq_one)\n\nlemma X_minus_sub_deg:\n  assumes \"a \\<in> carrier R\"\n  assumes \"f \\<in> carrier P\"\n  shows \"degree (f of (X_minus a)) = degree f\"\n  by (metis  X_minus_is_poly assms(1) assms(2) \n      deg_zero   degree_of_X_minus\n        mult.right_neutral  sub_deg zero_neq_one)\n\nend\n\n(*Taylor expansions of polynomials*)\n\ndefinition taylor_expansion where\n\"taylor_expansion R a p = compose R p (X_poly_plus R a)\"\n\ncontext UP_domain\nbegin\n\ndefinition Taylor (\"T\\<^bsub>_\\<^esub>\") where\n\"Taylor = taylor_expansion R\"\n\nlemma Taylor_deg:\n  assumes \"a \\<in> carrier R\"\n  assumes \"p \\<in> carrier P\"\n  shows \"degree (T\\<^bsub>a\\<^esub> p) = degree p\"\n  unfolding taylor_expansion_def using X_plus_sub_deg[of a p] assms \n  by (simp add: Taylor_def taylor_expansion_def)\n\nlemma plus_minus_sub[simp]:\n  assumes \" a \\<in> carrier R\"\n  shows \"X_plus a of X_minus a = X\"\n  unfolding X_poly_plus_def\nproof-\n  have \"(X \\<oplus>\\<^bsub>P\\<^esub> to_poly a) of X_minus a = (X  of X_minus a) \\<oplus>\\<^bsub>P\\<^esub> (to_poly a) of X_minus a\"\n    using sub_add \n    by (simp add: X_is_poly X_minus_is_poly assms to_poly_is_poly)\n  then have \"(X \\<oplus>\\<^bsub>P\\<^esub> to_poly a) of X_minus a = (X_minus a) \\<oplus>\\<^bsub>P\\<^esub> (to_poly a)\"\n    by (simp add: X_minus_is_poly assms)\n  then show \"(X \\<oplus>\\<^bsub>UP R\\<^esub> to_poly a) of X_minus a = X\" \n    unfolding to_polynomial_def X_poly_minus_def\n    by (metis P.add.inv_solve_right P.minus_eq P_def \n        X_is_poly X_poly_minus_def X_minus_is_poly assms monom_closed to_polynomial_def)\nqed\n\nlemma minus_plus_sub[simp]:\n  assumes \" a \\<in> carrier R\"\n  shows \"X_minus a of X_plus a = X\"\n  using plus_minus_sub[of \"\\<ominus>a\"]\n  unfolding X_poly_minus_def\n  unfolding X_poly_plus_def\n  using assms  apply simp\n  by (metis P_def R.add.inv_closed R.minus_minus a_minus_def to_poly_ominus)\n\nlemma Taylor_id:\n  assumes \"a \\<in> carrier R\"\n  assumes \"p \\<in> carrier P\"\n  shows \"p = (T\\<^bsub>a\\<^esub> p) of (X_minus a)\"\n  unfolding taylor_expansion_def \n  using assms sub_assoc[of p \"X_plus a\" \"X_minus a\"] X_plus_is_poly[of a]  X_minus_is_poly[of a]\n  by (metis P_def Taylor_def UP_domain.X_sub UP_domain.plus_minus_sub UP_domain_axioms taylor_expansion_def)\n\nend\n\n(*derivative function*)\n\ndefinition derivative where\n\"derivative R f a = (taylor_expansion R a f) 1\"\n\nabbreviation(in UP_domain) deriv where\n\"deriv \\<equiv> derivative R\"\n\n(*Constant term  and coefficient function*)\n\ndefinition zero_coefficient where\n\"zero_coefficient f = (f 0)\"\n\nabbreviation(in UP_domain) coeff_0 where\n\"coeff_0 \\<equiv> zero_coefficient\"\n\ndefinition constant_term where\n\"constant_term R f = to_polynomial R (f 0)\"\n\nabbreviation(in UP_domain) ct where\n\"ct \\<equiv> constant_term R\"\n\ncontext UP_domain\nbegin\n\nlemma ct_is_poly[simp]:\n  assumes \"p \\<in> carrier P\"\n  shows \"ct p \\<in> carrier P\"\n  by (simp add: P_fact0 assms constant_term_def to_poly_is_poly)\n\nlemma ct_degree:\n  assumes \"p \\<in> carrier P\"\n  shows \"degree (ct p) = 0\"\n  unfolding constant_term_def \n  by (simp add: P_fact0 assms)\n\n\nlemma ct_coeff_0[simp]:\nassumes \"f \\<in> carrier P\"\nassumes \"coeff_0 f = \\<zero>\"\nshows \"ct f = \\<zero>\\<^bsub>P\\<^esub>\"\n  using assms\n  unfolding constant_term_def\n            zero_coefficient_def\n            to_polynomial_def \n  apply simp \n  using P_def monom_zero by blast \n\nlemma coeff_0_degree_zero:\n  assumes \"f \\<in> carrier P\"\n  assumes \"degree f = 0\"\n  shows \"lc f = coeff_0 f\"\n  by (simp add: assms(2) zero_coefficient_def leading_coefficient_def)\n\nlemma coeff_0_zero_degree_zero:\n  assumes \"f \\<in> carrier P\"\n  assumes \"degree f = 0\"\n  assumes \"coeff_0 f = \\<zero>\"\n  shows \"f = \\<zero>\\<^bsub>P\\<^esub>\"\n  using coeff_0_degree_zero assms\n  by (metis P_def coeff_simp1 zero_coefficient_def  lcoeff_nonzero2)\n\nlemma coeff_0_ct[simp]:\n  assumes \"p \\<in> carrier P\"\n  shows \"coeff_0 (ct p) = coeff_0 p\"\n  unfolding zero_coefficient_def constant_term_def to_polynomial_def \n  by (metis P_def P_fact0 assms coeff_simp1 deg_const deg_zero_impl_monom lc_monom monom_closed)\n\n\nlemma ctrunc:\n  assumes \"p \\<in> carrier P\"\n  assumes \"degree p >0\"\n  shows \"coeff_0 (trunc p) = coeff_0 p\"\nproof-\n  have 0: \"(lt p) 0 = \\<zero>\"\n    using assms(1) assms(2) lt_coeffs by auto\n  have \"p = (trunc p) \\<oplus>\\<^bsub>P\\<^esub> (lt p)\"\n    using assms(1) trunc_simps(1) by auto\n  then have \"p 0 = (trunc p) 0 \\<oplus> (lt p) 0\"\n    by (metis assms(1) cf_add lt_in_car trunc_simps(3))\n  then show ?thesis using 0 \n    by (simp add: 0 P_fact0 assms(1) zero_coefficient_def trunc_simps(3))\nqed\n\n(**************************************************************************************************)\n(**************************************************************************************************)\n(**************************************************************************************************)\n(**************************************************************************************************)\n(**************************************************************************************************)\n(**************************************************************************************************)\n(**************************************************************************************************)\n\nlemma poly_induct:\n  assumes \"p \\<in> carrier P\"\n  assumes Deg_0: \"\\<And>p. p \\<in> carrier P \\<Longrightarrow> degree p = 0 \\<Longrightarrow> Q p\"\n  assumes IH: \"\\<And>p. (\\<And>q. q \\<in> carrier P \\<Longrightarrow> degree q < degree p \\<Longrightarrow> Q q) \\<Longrightarrow> p \\<in> carrier P \\<Longrightarrow> degree p > 0 \\<Longrightarrow> Q p\"\n  shows \"Q p\"\nproof-\n  have \"\\<And>n. \\<And>p. p \\<in> carrier P \\<Longrightarrow> degree p \\<le> n \\<Longrightarrow> Q p\"\n  proof-\n    fix n\n    show \"\\<And>p. p \\<in> carrier P \\<Longrightarrow>  degree p \\<le> n \\<Longrightarrow> Q p\"\n    proof(induction n)\n      case 0\n      then show ?case \n        using Deg_0  by simp\n    next\n      case (Suc n)\n      fix n \n      assume I:  \"\\<And>p. p \\<in> carrier P \\<Longrightarrow>  degree p \\<le> n \\<Longrightarrow> Q p\"\n      show  \"\\<And>p. p \\<in> carrier P \\<Longrightarrow>  degree p \\<le> (Suc n) \\<Longrightarrow> Q p\"\n      proof-\n        fix p\n        assume A0: \" p \\<in> carrier P \"\n        assume A1: \"degree p \\<le>Suc n\"\n        show \"Q p\"\n        proof(cases \"degree p < Suc n\")\n          case True\n          then show ?thesis \n            using I  A0 by auto\n        next\n          case False\n          then have D: \"degree p = Suc n\" \n            by (simp add: A1 nat_less_le)\n          then  have \"(\\<And>q. q \\<in> carrier P \\<Longrightarrow> degree q < degree p \\<Longrightarrow> Q q)\" \n              using I   by simp\n            then show \"Q p\" \n                  using IH D A0 A1 Deg_0 by blast\n        qed\n      qed\n    qed\n  qed\n  then show ?thesis using assms by blast \nqed\n \n(**************************************************************************************************)\n(**************************************************************************************************)\n(**************************************************************************************************)\n(**************************************************************************************************)\n(**************************************************************************************************)\n(**************************************************************************************************)\n\n(*Constant coefficient function is a ring homomorphism*)\nlemma coeff_0_to_poly[simp]:\n  assumes \"a \\<in> carrier R\"\n  shows \"coeff_0 (to_poly a) = a\"\n  by (metis P_def UP_domain.degree_to_poly UP_domain_axioms assms zero_coefficient_def\n      coeff_simp1 deg_zero_impl_monom lc_monom lcoeff_closed to_poly_is_poly to_polynomial_def)\n\nlemma coeff_0_add[simp]:\n  assumes \"p \\<in> carrier P\"\n  assumes \"q \\<in> carrier P\"\n  shows \"coeff_0 (p \\<oplus>\\<^bsub>P\\<^esub> q) = (coeff_0 p) \\<oplus> (coeff_0 q)\"\n  by (simp add: assms(1) assms(2) zero_coefficient_def)\n\nlemma coeff_lt[simp]:\n  assumes \"p \\<in> carrier P\"\n  assumes \"degree p > 0\"\n  shows \"coeff_0 (lt p) = \\<zero>\"\n  unfolding zero_coefficient_def leading_term_def \n  by (metis assms(1) assms(2) leading_term_def lt_coeffs nat_less_le)\n\nlemma coeff_lt_mult[simp]:\n  assumes \"p \\<in> carrier P\"\n  assumes \"q \\<in> carrier P\"\n  assumes \"degree p > 0\"\n  shows \"coeff_0 ((lt p) \\<otimes>\\<^bsub>P\\<^esub> q) = \\<zero>\"\n  apply(rule poly_induct[of q])\n  using assms(2) apply(simp)\nproof-\n  show B: \"\\<And>pa. pa \\<in> carrier P \\<Longrightarrow> degree pa = 0 \\<Longrightarrow> coeff_0 (lt p \\<otimes>\\<^bsub>P\\<^esub> pa) = \\<zero>\"\n  proof-\n    fix f\n    assume B0:\"f \\<in> carrier P\"\n    assume B1: \"degree f = 0\"\n    then show \"coeff_0 (lt p \\<otimes>\\<^bsub>P\\<^esub> f) = \\<zero>\"\n    proof(cases \"f = \\<zero>\\<^bsub>P\\<^esub>\")\n      case True\n      then show ?thesis \n        by (metis B0 zero_coefficient_def assms(1) assms(3) \n            coeff_0_ct ct_coeff_0 domain.integral_iff local.domain_axioms\n            lt_coeffs lt_in_car neq0_conv)\n    next\n      case False\n      then have \"p \\<otimes>\\<^bsub>P\\<^esub> f = (lc f) \\<odot>\\<^bsub>P\\<^esub>p\"\n        by (simp add: B0 B1 UP_m_comm assms(1) lc_deg_0)\n      then have \"coeff_0 (p \\<otimes>\\<^bsub>P\\<^esub> f) = coeff_0 ((lc f) \\<odot>\\<^bsub>P\\<^esub>p)\"\n        by simp\n      then show ?thesis \n        by (metis B0 B1 False P_def UP_domain.lt_mult UP_domain_axioms UP_mult_closed \n            \\<open>p \\<otimes>\\<^bsub>P\\<^esub> f = lc f \\<odot>\\<^bsub>P\\<^esub> p\\<close> assms(1) assms(3) coeff_0_degree_zero \n            coeff_0_zero_degree_zero coeff_lt coeff_simp1 deg_smult  \n            leading_coefficient_def lcoeff_closed lt_deg_0)\n    qed\n  qed\n  show \"\\<And>pa. (\\<And>q. q \\<in> carrier P \\<Longrightarrow> degree q < degree pa \\<Longrightarrow> coeff_0 (lt p \\<otimes>\\<^bsub>P\\<^esub> q) = \\<zero>)\n                 \\<Longrightarrow> pa \\<in> carrier P \\<Longrightarrow> 0 < degree pa \\<Longrightarrow> coeff_0 (lt p \\<otimes>\\<^bsub>P\\<^esub> pa) = \\<zero>\"\n  proof-\n    fix f\n    assume IH: \" (\\<And>q. q \\<in> carrier P \\<Longrightarrow> degree q < degree f \\<Longrightarrow> coeff_0 (lt p \\<otimes>\\<^bsub>P\\<^esub> q) = \\<zero>)\"\n    assume A: \"f \\<in> carrier P\" \" 0 < degree f \" \n    show \"coeff_0 (lt p \\<otimes>\\<^bsub>P\\<^esub> f) = \\<zero>\"\n    proof-\n      have 0: \"(lt p \\<otimes>\\<^bsub>P\\<^esub> f) = (lt p \\<otimes>\\<^bsub>P\\<^esub> trunc f) \\<oplus>\\<^bsub>P\\<^esub> (lt p \\<otimes>\\<^bsub>P\\<^esub> lt f)\"\n        by (metis A(1) P.r_distr assms(1) lt_in_car trunc_simps(1) trunc_simps(3))\n      then have 1:  \"coeff_0 (lt p \\<otimes>\\<^bsub>P\\<^esub> f) = coeff_0 (lt p \\<otimes>\\<^bsub>P\\<^esub> trunc f) \\<oplus> coeff_0  (lt p \\<otimes>\\<^bsub>P\\<^esub> lt f)\"\n        by (simp add: A(1) assms(1) lt_in_car trunc_simps(3))\n      have 2: \" coeff_0 (lt p \\<otimes>\\<^bsub>P\\<^esub> trunc f) = \\<zero>\" \n        using A IH  by (simp add: trunc_degree trunc_simps(3))\n      have 3: \"coeff_0  (lt p \\<otimes>\\<^bsub>P\\<^esub> lt f) = \\<zero>\"\n      proof-\n        have \"degree (lt p \\<otimes>\\<^bsub>P\\<^esub> lt f) > 0\" using  deg_mult assms A \n          by (metis add_gr_0 deg_zero  degree_lt lt_in_car nat_less_le)\n        then have \"coeff_0 (lt (lt p \\<otimes>\\<^bsub>P\\<^esub> lt f)) = \\<zero>\"\n        by (meson A(1) UP_mult_closed assms(1) coeff_lt lt_in_car)\n        then show ?thesis \n          by (simp add: A(1) assms(1))\n      qed\n      then show ?thesis using 3 2 1 by auto \n    qed\n  qed\nqed\n\nlemma coeff_0_mult[simp]:\n  assumes \"p \\<in> carrier P\"\n  assumes \"q \\<in> carrier P\"\n  shows \"coeff_0 (p \\<otimes>\\<^bsub>P\\<^esub> q) = (coeff_0 p) \\<otimes> (coeff_0 q)\"\n  apply(rule poly_induct[of p])\n  apply(simp add: assms)\nproof-\n  show B:\" \\<And>p. p \\<in> carrier P \\<Longrightarrow> degree p = 0 \\<Longrightarrow> coeff_0 (p \\<otimes>\\<^bsub>P\\<^esub> q) = coeff_0 p \\<otimes> coeff_0 q\"\n  proof-\n    fix p\n    assume A0: \"p \\<in> carrier P\"\n    assume A1: \"degree p = 0\"\n    show \"coeff_0 (p \\<otimes>\\<^bsub>P\\<^esub> q) = coeff_0 p \\<otimes> coeff_0 q\"\n    proof-\n      have \"p \\<otimes>\\<^bsub>P\\<^esub> q = (lc p) \\<odot>\\<^bsub>P\\<^esub> q\"\n        using A0 A1  by (simp add: assms(2) lc_deg_0)\n      then have 0: \"coeff_0 (p \\<otimes>\\<^bsub>P\\<^esub> q) = (lc p) \\<otimes> coeff_0 q\"\n        by (metis A0 P_def UP_mult_closed assms(2) zero_coefficient_def\n            coeff_simp1 coeff_smult  leading_coefficient_def lcoeff_closed)\n      have 1: \"lc p = coeff_0 p\"\n        using A0   by (simp add: A1 coeff_0_degree_zero)\n      then show ?thesis using 0 1 by auto \n    qed\n  qed\n  show  \"\\<And>p. (\\<And>qa. qa \\<in> carrier P \\<Longrightarrow> degree qa < degree p \\<Longrightarrow> coeff_0 (qa \\<otimes>\\<^bsub>P\\<^esub> q) = coeff_0 qa \\<otimes> coeff_0 q) \\<Longrightarrow>\n         p \\<in> carrier P \\<Longrightarrow> degree p > 0 \\<Longrightarrow> coeff_0 (p \\<otimes>\\<^bsub>P\\<^esub> q) = coeff_0 p \\<otimes> coeff_0 q\"\n  proof-\n    fix p\n    assume IH: \"(\\<And>qa. qa \\<in> carrier P \\<Longrightarrow> degree qa < degree p \n                \\<Longrightarrow> coeff_0 (qa \\<otimes>\\<^bsub>P\\<^esub> q) = coeff_0 qa \\<otimes> coeff_0 q)\"\n    show \"p \\<in> carrier P \\<Longrightarrow> degree p > 0 \\<Longrightarrow> coeff_0 (p \\<otimes>\\<^bsub>P\\<^esub> q) = coeff_0 p \\<otimes> coeff_0 q\"\n    proof-\n      assume A0: \"p \\<in> carrier P\"\n      assume A1: \"degree p > 0\"\n      show \"coeff_0 (p \\<otimes>\\<^bsub>P\\<^esub> q) = coeff_0 p \\<otimes> coeff_0 q\"\n      proof- \n        have 0: \"coeff_0 (p \\<otimes>\\<^bsub>P\\<^esub> q) = coeff_0 ((trunc p) \\<otimes>\\<^bsub>P\\<^esub> q) \\<oplus> coeff_0 ((lt p) \\<otimes>\\<^bsub>P\\<^esub> q)\"\n          by (metis (no_types, hide_lams) A0 P.l_distr P.m_closed assms(2)\n              cf_add zero_coefficient_def lt_in_car trunc_simps(1) trunc_simps(3))\n        have 1: \"coeff_0 ((lt p) \\<otimes>\\<^bsub>P\\<^esub> q) = \\<zero>\"\n          by (simp add: A0 A1 assms(2))\n        have \"degree (trunc p) < degree p\" \n          using A0 A1  by (simp add: trunc_degree)\n        then have 2: \"coeff_0 ((trunc p) \\<otimes>\\<^bsub>P\\<^esub> q) = coeff_0 (trunc p) \\<otimes> coeff_0 q\"\n          using A0 IH  by (simp add: trunc_simps(3))\n        then have 3: \"coeff_0 (p \\<otimes>\\<^bsub>P\\<^esub> q) = coeff_0 (trunc p) \\<otimes> coeff_0 q\"\n          using 0 1 2 by (simp add: A0 P_fact0 assms(2) zero_coefficient_def trunc_simps(3))\n        show ?thesis \n          by (simp add: \"3\" A0 A1 ctrunc)\n      qed\n    qed\n  qed\nqed\n\nlemma coeff_0_zero[simp]:\n\"coeff_0 \\<zero>\\<^bsub>P\\<^esub> = \\<zero>\"\n  by (metis P_def UP_zero_closed coeff_simp1 coeff_zero zero_coefficient_def)\n\nlemma coeff_0_one[simp]:\n\"coeff_0 \\<one>\\<^bsub>P\\<^esub> = \\<one>\"\n  using coeff_0_to_poly \n  by (metis P_def R.one_closed monom_one to_polynomial_def)\n\nlemma coeff_0_is_ring_hom:\n\"coeff_0 \\<in> ring_hom P R\"\n  apply(rule ring_hom_memI)\n  apply(auto)\n  apply((simp add: P_fact0 zero_coefficient_def)) done\n\n(*if the constant term of f is 0, then f factors by X*)\nlemma coeff_0_eq_zero:\n  assumes \"f \\<in> carrier P\"\n  assumes \"coeff_0 f = \\<zero>\"\n  shows \"\\<exists> g. g \\<in> carrier P \\<and> (f = X \\<otimes>\\<^bsub>P\\<^esub> g)\"\nproof-\n  have \"\\<And>n. \\<And>p. p \\<in> carrier P \\<Longrightarrow> degree p \\<le> n \\<Longrightarrow> coeff_0 p = \\<zero> \\<Longrightarrow> (\\<exists> g. g \\<in> carrier P \\<and> (p = X \\<otimes>\\<^bsub>P\\<^esub> g))\"\n  proof-\n    fix n\n    show \"\\<And>p. p \\<in> carrier P \\<Longrightarrow> degree p \\<le> n \\<Longrightarrow> coeff_0 p = \\<zero> \\<Longrightarrow> (\\<exists> g. g \\<in> carrier P \\<and> (p = X \\<otimes>\\<^bsub>P\\<^esub> g))\"\n      proof(induction n)\n        case 0\n        then have \"degree p = 0\" \n          using \"0.prems\"(2) by blast\n        then have \"p = \\<zero>\\<^bsub>P\\<^esub>\" \n          by (simp add: \"0.prems\"  coeff_0_zero_degree_zero)\n        then have  \"p = X \\<otimes>\\<^bsub>P\\<^esub> \\<zero>\\<^bsub>P\\<^esub>\" \n          by (simp add: X_is_poly)\n        then show \" \\<exists>g. g \\<in> carrier P \\<and> p = X \\<otimes>\\<^bsub>P\\<^esub> g\"\n          by blast\n      next\n        case (Suc n)\n        fix n\n        assume IH: \"\\<And>p. p \\<in> carrier P \\<Longrightarrow> degree p \\<le> n \\<Longrightarrow> coeff_0 p = \\<zero> \\<Longrightarrow> (\\<exists> g. g \\<in> carrier P \\<and> (p = X \\<otimes>\\<^bsub>P\\<^esub> g))\"\n        show \"p \\<in> carrier P \\<Longrightarrow> degree p \\<le> Suc n \\<Longrightarrow> coeff_0 p = \\<zero> \\<Longrightarrow> \\<exists>g. g \\<in> carrier P \\<and> p = X \\<otimes>\\<^bsub>P\\<^esub> g\" \n        proof-\n          assume A0: \"p \\<in> carrier P\" and\n                 A1: \"degree p \\<le> Suc n\" and \n                 A2: \"coeff_0 p = \\<zero>\"\n          show \"\\<exists>g. g \\<in> carrier P \\<and> p = X \\<otimes>\\<^bsub>P\\<^esub> g\"\n          proof(cases \"degree p < Suc n\")\n          case True\n          then show ?thesis \n            using A0 A1 A2 IH by auto \n        next\n          case False\n          then have D: \"degree p = Suc n\" \n            using A2  A1 by auto\n          have C0:\"coeff_0 (trunc p) = \\<zero>\"\n            by (simp add: A0 A2 D ctrunc)\n          have C1: \"degree (trunc p) \\<le>n\"\n            using D A0 P_def UP_domain.trunc_degree UP_domain_axioms by fastforce\n          obtain g where g_def : \" g \\<in> carrier P \\<and> (trunc p) = X \\<otimes>\\<^bsub>P\\<^esub> g\" \n            using A0 IH C0 C1  trunc_simps(3) by auto\n          have LT0: \"lt p = (lc p) \\<odot>\\<^bsub>P\\<^esub> X[^]\\<^bsub>P\\<^esub> Suc n\"\n            by (simp add: A0 D lt_rep_X_pow)\n          then have LT1: \"lt p = X \\<otimes>\\<^bsub>P\\<^esub> ((lc p) \\<odot>\\<^bsub>P\\<^esub> X[^]\\<^bsub>P\\<^esub> n)\"\n            by (metis (no_types, lifting) A0 P.m_comm P.nat_pow_Suc P.nat_pow_closed \n                P_def X_is_poly algebra.smult_assoc2 algebra_axioms coeff_simp1 \n                 leading_coefficient_def lcoeff_closed smult_closed)\n          have \"p = (trunc p) \\<oplus>\\<^bsub>P\\<^esub> lt p\"\n            using trunc_simps A0 by auto \n          then have \"p =  X \\<otimes>\\<^bsub>P\\<^esub> g \\<oplus>\\<^bsub>P\\<^esub> X \\<otimes>\\<^bsub>P\\<^esub> ((lc p) \\<odot>\\<^bsub>P\\<^esub> X[^]\\<^bsub>P\\<^esub> n)\"\n            using g_def LT1 by auto \n          then have \"p = X \\<otimes>\\<^bsub>P\\<^esub> (g \\<oplus>\\<^bsub>P\\<^esub> ((lc p) \\<odot>\\<^bsub>P\\<^esub> X[^]\\<^bsub>P\\<^esub> n))\"\n            using A0 P.nat_pow_closed P.r_distr P_def X_is_poly coeff_simp1 \n               g_def leading_coefficient_def lcoeff_closed smult_closed by metis\n          then show ?thesis \n            by (metis A0 P.nat_pow_closed P_def UP_a_closed X_is_poly \n                coeff_simp1  g_def leading_coefficient_def lcoeff_closed smult_closed)\n        qed\n      qed\n    qed\n  qed\n  then show ?thesis \n    using assms(1) assms(2) by blast\nqed\n\n(*The factorization of f by X is unique*)\nlemma coeff_0_eq_zero_unique:\n  assumes \"f \\<in> carrier P\"\n  assumes \"g \\<in> carrier P \\<and> (f = X \\<otimes>\\<^bsub>P\\<^esub> g)\"\n  shows \"\\<And> h. h  \\<in> carrier P \\<and> (f = X \\<otimes>\\<^bsub>P\\<^esub> h) \\<Longrightarrow> h = g\"\nproof-\n  fix h\n  assume A: \"h  \\<in> carrier P \\<and> (f = X \\<otimes>\\<^bsub>P\\<^esub> h)\"\n  then have \" X \\<otimes>\\<^bsub>P\\<^esub> g =  X \\<otimes>\\<^bsub>P\\<^esub> h\"\n    using assms(2) by auto\n  then show \"h = g\" using assms \n    by (simp add: assms(2) A X_is_poly X_not_zero local.m_lcancel)\nqed\n\nlemma f_minus_ct:\n  assumes \"f \\<in> carrier P\"\n  shows \"coeff_0 (f \\<ominus>\\<^bsub>P\\<^esub> ct f) = \\<zero>\"\nproof-\n  have \"coeff_0 (f \\<ominus>\\<^bsub>P\\<^esub> ct f) = coeff_0 f \\<ominus> coeff_0  (ct f)\"\n    using assms coeff_0_is_ring_hom \n    by (metis P.minus_closed P_def zero_coefficient_def coeff_minus coeff_simp1 ct_is_poly)\n  then show ?thesis \n    using assms apply simp \n    by (metis R.ring_axioms abelian_group.r_neg\n        coeff_0_is_ring_hom ring.ring_simprules(14) ring_def ring_hom_closed)\nqed\n\nend\n\n\ndefinition polynomial_shift where\n\"polynomial_shift R f = (THE g. g \\<in> carrier (UP R) \\<and> f \\<ominus>\\<^bsub>(UP R)\\<^esub> (constant_term R) f = X_poly R \\<otimes>\\<^bsub>UP R\\<^esub> g)\"\n\n\ncontext UP_domain\nbegin\n\nabbreviation poly_shift where\n\"poly_shift \\<equiv> polynomial_shift R\"\n\nlemma poly_shift_prop:\n  assumes \"f \\<in> carrier P\"\n  assumes \"g = poly_shift f\"\n  shows \" g \\<in> carrier P \\<and> f \\<ominus>\\<^bsub>P\\<^esub> ct f = X \\<otimes>\\<^bsub>P\\<^esub> g\"\nproof-\n  obtain h where h_def: \"h \\<in> carrier P \\<and> f \\<ominus>\\<^bsub>P\\<^esub> ct f = X \\<otimes>\\<^bsub>P\\<^esub> h\"\n    using f_minus_ct coeff_0_eq_zero assms P.minus_closed ct_is_poly by presburger\n  have 0:\"(THE g. g \\<in> carrier P \\<and> f \\<ominus>\\<^bsub>P\\<^esub> ct f = X \\<otimes>\\<^bsub>P\\<^esub> g) = h\" \n  proof(rule the_equality)\n    show \"h \\<in> carrier P \\<and> f \\<ominus>\\<^bsub>P\\<^esub> ct f = X \\<otimes>\\<^bsub>P\\<^esub> h\" \n      using h_def apply auto done\n    show \"\\<And>g. g \\<in> carrier P \\<and> f \\<ominus>\\<^bsub>P\\<^esub> ct f = X \\<otimes>\\<^bsub>P\\<^esub> g \\<Longrightarrow> g = h\"\n    proof-\n      fix k\n      assume A: \"k \\<in> carrier P \\<and> f \\<ominus>\\<^bsub>P\\<^esub> ct f = X \\<otimes>\\<^bsub>P\\<^esub> k\"\n      show \"k = h\" \n        using coeff_0_eq_zero_unique[of \"f \\<ominus>\\<^bsub>P\\<^esub> ct f\"] h_def \n        by (metis A UP_mult_closed X_is_poly)\n    qed\n  qed\n  have \"g = (THE g. g \\<in> carrier P \\<and> f \\<ominus>\\<^bsub>P\\<^esub> ct f = X \\<otimes>\\<^bsub>P\\<^esub> g)\"\n    using assms(2) unfolding polynomial_shift_def P_def by auto   \n  then have \"h = g\"\n    using 0 assms by auto \n  then show ?thesis \n    using h_def by simp\nqed\n\nlemma poly_shift_is_poly[simp]:\n  assumes \"f \\<in> carrier P\"\n  assumes \"g = poly_shift f\"\n  shows \" g \\<in> carrier P\"\n  using assms poly_shift_prop by blast \n\nlemma poly_shift_id:\n  assumes \"f \\<in> carrier P\"\n  shows \"f \\<ominus>\\<^bsub>P\\<^esub> ct f = X \\<otimes>\\<^bsub>P\\<^esub> poly_shift f\"\n  using assms poly_shift_prop by blast \n\nlemma poly_shift_id':\n  assumes \"f \\<in> carrier P\"\n  shows \"f  = ct f \\<oplus>\\<^bsub>P\\<^esub> X \\<otimes>\\<^bsub>P\\<^esub> poly_shift f\"\nproof-\n  have  \"f \\<ominus>\\<^bsub>P\\<^esub> ct f = X \\<otimes>\\<^bsub>P\\<^esub> poly_shift f\" \n    using poly_shift_id assms by auto \n  then show ?thesis \n    by (metis P.add.inv_solve_right P.minus_closed P.minus_eq UP_a_comm assms(1) ct_is_poly)\nqed\n\nlemma poly_shift_degree_zero:\n  assumes \"p \\<in> carrier P\"\n  assumes \"degree p = 0\"\n  shows \"poly_shift p = \\<zero>\\<^bsub>P\\<^esub>\"\nproof-\n  have \"p \\<ominus>\\<^bsub>P\\<^esub> ct p = \\<zero>\\<^bsub>P\\<^esub>\" \n    using assms  by (metis P.minus_eq P.r_neg constant_term_def to_poly_inverse)\n  then have \"X \\<otimes>\\<^bsub>P\\<^esub> (poly_shift p) = \\<zero>\\<^bsub>P\\<^esub>\" \n    using assms poly_shift_id by auto \n  then show ?thesis \n    using X_is_poly X_not_zero assms(1) local.integral poly_shift_is_poly by blast\nqed\n\nlemma poly_shift_degree:\n  assumes \"p \\<in> carrier P\"\n  assumes \"degree p >0\"\n  shows \"degree (poly_shift p) = degree p - 1 \"\nproof-\n  have 0: \"degree (p \\<ominus>\\<^bsub>P\\<^esub> ct p) = degree p\"\n    using assms ct_degree  by (simp add: degree_of_difference_diff_degree)\n  have 1: \"p \\<ominus>\\<^bsub>P\\<^esub> ct p = X \\<otimes>\\<^bsub>P\\<^esub> poly_shift p\"\n    using assms poly_shift_id by auto\n  have 2: \"degree (X \\<otimes>\\<^bsub>P\\<^esub> poly_shift p) = 1 + degree(poly_shift p)\"\n    by (metis \"0\" \"1\" P.r_null X_is_poly X_not_zero assms(1) assms(2)\n        deg_mult deg_zero degree_X  nat_less_le poly_shift_is_poly)\n  show ?thesis using 0 1 2  by simp\nqed\n\nend \nend", "meta": {"author": "AaronCrighton", "repo": "Padics", "sha": "b451038d52193e2c351fe4a44c30c87586335656", "save_path": "github-repos/isabelle/AaronCrighton-Padics", "path": "github-repos/isabelle/AaronCrighton-Padics/Padics-b451038d52193e2c351fe4a44c30c87586335656/Garbage/poly_sub.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8887587993853654, "lm_q2_score": 0.7931059585194573, "lm_q1q2_score": 0.7048798994791323}}
{"text": "subsection \\<open>Simple Properties of Register Machines\\<close>\n\ntheory RegisterMachineProperties\n    imports \"RegisterMachineSpecification\"\nbegin\n\nlemma step_commutative: \"steps (step c p) p t = step (steps c p t) p\"\n  by (induction t; auto)\n\nlemma step_fetch_correct:\n  fixes t :: nat\n    and c :: configuration\n    and p :: program\n  assumes \"is_valid c p\"\n  defines \"ct \\<equiv> (steps c p t)\"\n  shows \"fst (steps (step c p) p t) = fetch (fst ct) p (read (snd ct) p (fst ct))\"\n  using ct_def step_commutative step_def by auto\n\nsubsubsection \\<open>From Configurations to a Protocol\\<close>\n\ntext \\<open>Register Values\\<close>\n\ndefinition R :: \"configuration \\<Rightarrow> program \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> nat\"\n  where \"R c p n t = (snd (steps c p t)) ! n\"\n\nfun RL :: \"configuration \\<Rightarrow> program \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> nat\"  where\n  \"RL c p b 0 l = ((snd c) ! l)\" |\n  \"RL c p b (Suc t) l = ((snd c) ! l) + b * (RL (step c p) p b t l)\"\n\nlemma RL_simp_aux:\n  \\<open>snd c ! l + b * RL (step c p) p b t l =\n    RL c p b t l + b * (b ^ t * snd (step (steps c p t) p) ! l)\\<close>\n  by (induction t arbitrary: c)\n    (auto simp: step_commutative algebra_simps)\n\ndeclare RL.simps[simp del]\nlemma RL_simp:\n  \"RL c p b (Suc t) l = (snd (steps c p (Suc t)) ! l) * b ^ (Suc t) + (RL c p b t l)\"\nproof (induction t arbitrary: p c b)\n  case 0\n  thus ?case by (auto simp: RL.simps)\nnext\n  case (Suc t p c b)\n  show ?case\n    by (subst RL.simps) (*  \\<open>unfold one level\\<close> *)\n      (auto simp: Suc step_commutative algebra_simps RL_simp_aux)\nqed\n\ntext \\<open>State Values\\<close>\n\ndefinition S :: \"configuration \\<Rightarrow> program \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> nat\"\n  where \"S c p k t = (if (fst (steps c p t) = k) then (Suc 0) else 0)\"\n\ndefinition S2 :: \"configuration \\<Rightarrow> nat \\<Rightarrow> nat\"\n  where \"S2 c k = (if (fst c) = k then 1 else 0)\"\n\nfun SK :: \"configuration \\<Rightarrow> program \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> nat\"\n  where \"SK c p b 0 k = (S2 c k)\" |\n   \"SK c p b (Suc t) k = (S2 c k) + b * (SK (step c p) p b t k)\"\n\nlemma SK_simp_aux:\n  \\<open>SK c p b (Suc (Suc t)) k =\n    S2 (steps c p (Suc (Suc t))) k * b ^ Suc (Suc t) + SK c p b (Suc t) k\\<close>\n   by (induction t arbitrary: c) (auto simp: step_commutative algebra_simps)\n\ndeclare SK.simps[simp del]\nlemma SK_simp:\n  \"SK c p b (Suc t) k = (S2 (steps c p (Suc t)) k) * b ^ (Suc t) + (SK c p b t k)\"\nproof (induction t arbitrary: p c b k)\n  case 0\n  thus ?case by (auto simp: SK.simps)\nnext\n  case (Suc t p c b k)\n  show ?case\n    by (auto simp: Suc algebra_simps step_commutative SK_simp_aux)\nqed\n\ntext \\<open>Zero-Indicator Values\\<close>\n \ndefinition Z :: \"configuration \\<Rightarrow> program \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> nat\"  where\n   \"Z c p n t = (if (R c p n t > 0) then 1 else 0)\"\n\ndefinition Z2 :: \"configuration \\<Rightarrow> nat \\<Rightarrow> nat\" where\n   \"Z2 c n = (if (snd c) ! n > 0 then 1 else 0)\"\n\nfun ZL :: \"configuration \\<Rightarrow> program \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> nat\"\n  where \"ZL c p b 0 l = (Z2 c l)\" |\n   \"ZL c p b (Suc t) l = (Z2 c l) +  b * (ZL (step c p) p b t l)\"\n\nlemma ZL_simp_aux:\n\"Z2 c l + b * ZL (step c p) p b t l =\n    ZL c p b t l + b * (b ^ t * Z2 (step (steps c p t) p) l)\"\n  by (induction t arbitrary: c) (auto simp: step_commutative algebra_simps)\n\ndeclare ZL.simps[simp del]\nlemma ZL_simp:\n  \"ZL c p b (Suc t) l = (Z2 (steps c p (Suc t)) l) * b ^ (Suc t) + (ZL c p b t l)\"\nproof (induction t arbitrary: p c b)\n  case 0\n  thus ?case by (auto simp: ZL.simps)\nnext\n  case (Suc t p c b)\n  show ?case\n    by (subst ZL.simps) (auto simp: Suc step_commutative algebra_simps ZL_simp_aux)\nqed\n\nsubsubsection \\<open>Protocol Properties\\<close>\n\nlemma Z_bounded: \"Z c p l t \\<le> 1\"\n  by (auto simp: Z_def)\n\nlemma S_bounded: \"S c p k t \\<le> 1\"\n  by (auto simp: S_def)\n\nlemma S_unique: \"\\<forall>k\\<le>length p. (k \\<noteq> fst (steps c p t) \\<longrightarrow> S c p k t = 0)\"\n  by (auto simp: S_def)\n\n\n(* takes c :: nat, the exponent defining the base b *)\nfun cells_bounded :: \"configuration \\<Rightarrow> program \\<Rightarrow> nat \\<Rightarrow> bool\" where\n  \"cells_bounded conf p c = ((\\<forall>l<(length (snd conf)). \\<forall>t. 2^c > R conf p l t)\n                          \\<and>  (\\<forall>k t. 2^c > S conf p k t)\n                          \\<and>  (\\<forall>l t. 2^c > Z conf p l t))\"\n\nlemma steps_tape_length_invar:  \"length (snd (steps c p t)) = length (snd c)\"\n  by (induction t; auto simp add: step_def update_def)\n\nlemma step_is_valid_invar: \"is_valid c p \\<Longrightarrow> is_valid (step c p) p\"\n  by (auto simp add: step_def update_def is_valid_def)\n\nfun fetch_old\n  where\n    \"(fetch_old p s (Add r next) _) = next\"\n  | \"(fetch_old p s (Sub r next nextalt) val) = (if val = 0 then nextalt else next)\"\n  | \"(fetch_old p s Halt _) = s\"\n\nlemma fetch_equiv:\n  assumes \"i = p!s\"\n  shows \"fetch s p v = fetch_old p s i v\"\n  by (cases i; auto simp: assms fetch_def)\n\n(* Corollary: All states have instructions in the program list *)\nlemma p_contains: \"is_valid_initial ic p a \\<Longrightarrow> (fst (steps ic p t)) < length p\"\nproof -\n  assume asm: \"is_valid_initial ic p a\"\n  hence \"fst ic = 0\" using is_valid_initial_def is_valid_def by blast\n  hence 0: \"ic = (0, snd ic)\" by (metis prod.collapse)\n  show ?thesis using 0 asm\n  apply (induct t) apply auto[1]\n  subgoal by (auto simp add: is_valid_initial_def is_valid_def)\n  apply (cases \"p ! fst (steps ic p t)\")\n  apply (auto simp add: list_all_length fetch_equiv step_def\n                is_valid_initial_def is_valid_def fetch_old.elims)\n  by (metis RegisterMachineSpecification.isc_add RegisterMachineSpecification.isc_sub \n      fetch_old.elims) +\nqed\n\nlemma steps_is_valid_invar: \"is_valid c p \\<Longrightarrow> is_valid (steps c p t) p\"\n  by (induction t; auto simp add: step_def update_def is_valid_def)\n\nlemma terminates_halt_state: \"terminates ic p q \\<Longrightarrow> is_valid_initial ic p a\n                               \\<Longrightarrow> ishalt (p ! (fst (steps ic p q)))\"\nproof -\n  assume terminate: \"terminates ic p q\"\n  assume is_val: \"is_valid_initial ic p a\"\n  have \"1 < length p\" using is_val is_valid_initial_def[of \"ic\" \"p\" \"a\"]\n    is_valid_def[of \"ic\" \"p\"] program_includes_halt.simps\n    by blast\n  hence \"p \\<noteq> []\" by auto\n  hence \"p ! (length p - 1) = last p\" using List.last_conv_nth[of \"p\"] by auto\n  thus ?thesis\n    using terminate terminates_def correct_halt_def is_val is_valid_def[of \"ic\" \"p\"] by auto\nqed\n\nlemma R_termination:\n  fixes l :: register and ic :: configuration\n  assumes is_val: \"is_valid ic p\" and terminate: \"terminates ic p q\" and l: \"l < length (snd ic)\"\n  shows \"\\<forall>t\\<ge>q. R ic p l t = 0\"\nproof -\n  have ishalt: \"ishalt (p ! fst (steps ic p q))\"\n    using terminate terminates_def correct_halt_def is_valid_def is_val by auto\n  have halt: \"ishalt (p ! fst (steps ic p (q + t)))\" for t\n    apply (induction t)\n    using terminate terminates_def ishalt step_def fetch_def by auto\n  have \"l<(length (snd ic)) \\<longrightarrow>R ic p l (q+t) = 0\" for t\n    apply (induction t arbitrary: l)\n    subgoal using terminate terminates_def correct_halt_def R_def by auto\n    subgoal using R_def step_def halt update_def by auto\n    done\n  thus ?thesis using le_Suc_ex l by force\nqed\n\nlemma terminate_c_exists: \"is_valid ic p \\<Longrightarrow> terminates ic p q \\<Longrightarrow> \\<exists>c>1. cells_bounded ic p c\"\nproof -\n  assume is_val: \"is_valid ic p\"\n  assume terminate: \"terminates ic p q\"\n  define n where \"n \\<equiv> length (snd ic)\"\n  define rmax where \"rmax \\<equiv> Max ({k. \\<exists>l<n. \\<exists>t<q. k = R ic p l t} \\<union> {2})\"\n  have  \"\\<forall>l<n. \\<forall>t<q. R ic p l t \\<in> {k. \\<exists>l<n. \\<exists>t<q. k = R ic p l t}\" by auto\n  hence \"\\<forall>t<q. \\<forall>l<n. R ic p l t \\<le> rmax\" using rmax_def by auto\n  moreover have \"\\<forall>t\\<ge>q. \\<forall>l<n. R ic p l t \\<le> rmax\"\n    using rmax_def R_termination terminate n_def is_val by auto\n  ultimately have r: \"\\<forall>l<n. \\<forall>t. R ic p l t \\<le> rmax\" using not_le_imp_less by blast\n  have gt2: \"rmax \\<ge> 2\" using rmax_def by auto\n  hence sz: \"(\\<forall>k t. rmax > S ic p k t) \\<and> (\\<forall>l t. rmax > Z ic p l t)\"\n    using S_bounded Z_bounded S_def Z_def by auto\n  have \"(\\<forall>l<n. \\<forall>t. R ic p l t < 2^rmax) \\<and> (\\<forall>k t. S ic p k t < 2^rmax) \n         \\<and> (\\<forall>l t. Z ic p l t < 2^rmax)\"\n    using less_exp[of \"rmax\"] r sz by (metis le_neq_implies_less dual_order.strict_trans)\n  moreover have \"rmax > 1\" using gt2 by auto\n  ultimately show ?thesis using n_def 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/DPRM_Theorem/Register_Machine/RegisterMachineProperties.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637577007393, "lm_q2_score": 0.8198933403143929, "lm_q1q2_score": 0.7048325898484821}}
{"text": "(*  Title:      HOL/Algebra/Generated_Fields.thy\n    Author:     Martin Baillon\n*)\n\ntheory Generated_Fields\nimports Generated_Rings Subrings Multiplicative_Group\nbegin\n\ninductive_set\n  generate_field :: \"('a, 'b) ring_scheme \\<Rightarrow> 'a set \\<Rightarrow> 'a set\"\n  for R and H where\n    one  : \"\\<one>\\<^bsub>R\\<^esub> \\<in> generate_field R H\"\n  | incl : \"h \\<in> H \\<Longrightarrow> h \\<in> generate_field R H\"\n  | a_inv: \"h \\<in> generate_field R H \\<Longrightarrow> \\<ominus>\\<^bsub>R\\<^esub> h \\<in> generate_field R H\"\n  | m_inv: \"\\<lbrakk> h \\<in> generate_field R H; h \\<noteq> \\<zero>\\<^bsub>R\\<^esub> \\<rbrakk> \\<Longrightarrow> inv\\<^bsub>R\\<^esub> h \\<in> generate_field R H\"\n  | eng_add : \"\\<lbrakk> h1 \\<in> generate_field R H; h2 \\<in> generate_field R H \\<rbrakk> \\<Longrightarrow> h1 \\<oplus>\\<^bsub>R\\<^esub> h2 \\<in> generate_field R H\"\n  | eng_mult: \"\\<lbrakk> h1 \\<in> generate_field R H; h2 \\<in> generate_field R H \\<rbrakk> \\<Longrightarrow> h1 \\<otimes>\\<^bsub>R\\<^esub> h2 \\<in> generate_field R H\"\n\n\nsubsection\\<open>Basic Properties of Generated Rings - First Part\\<close>\n\nlemma (in field) generate_field_in_carrier:\n  assumes \"H \\<subseteq> carrier R\"\n  shows \"h \\<in> generate_field R H \\<Longrightarrow> h \\<in> carrier R\"\n  apply (induction rule: generate_field.induct)\n  using assms field_Units\n  by blast+\n\nlemma (in field) generate_field_incl:\n  assumes \"H \\<subseteq> carrier R\"\n  shows \"generate_field R H \\<subseteq> carrier R\"\n  using generate_field_in_carrier[OF assms] by auto\n       \nlemma (in field) zero_in_generate: \"\\<zero>\\<^bsub>R\\<^esub> \\<in> generate_field R H\"\n  using one a_inv generate_field.eng_add one_closed r_neg\n  by metis\n\nlemma (in field) generate_field_is_subfield:\n  assumes \"H \\<subseteq> carrier R\"\n  shows \"subfield (generate_field R H) R\"\nproof (intro subfieldI', simp_all add: m_inv)\n  show \"subring (generate_field R H) R\"\n    by (auto intro: subringI[of \"generate_field R H\"]\n             simp add: eng_add a_inv eng_mult one generate_field_in_carrier[OF assms])\nqed\n\nlemma (in field) generate_field_is_add_subgroup:\n  assumes \"H \\<subseteq> carrier R\"\n  shows \"subgroup (generate_field R H) (add_monoid R)\"\n  using subring.axioms(1)[OF subfieldE(1)[OF generate_field_is_subfield[OF assms]]] .\n\nlemma (in field) generate_field_is_field :\n  assumes \"H \\<subseteq> carrier R\"\n  shows \"field (R \\<lparr> carrier := generate_field R H \\<rparr>)\"\n  using subfield_iff generate_field_is_subfield assms by simp\n\nlemma (in field) generate_field_min_subfield1:\n  assumes \"H \\<subseteq> carrier R\"\n    and \"subfield E R\" \"H \\<subseteq> E\"\n  shows \"generate_field R H \\<subseteq> E\"\nproof\n  fix h\n  assume h: \"h \\<in> generate_field R H\"\n  show \"h \\<in> E\"\n    using h and assms(3) and subfield_m_inv[OF assms(2)]\n    by (induct rule: generate_field.induct)\n       (auto simp add: subringE(3,5-7)[OF subfieldE(1)[OF assms(2)]])\nqed\n\nlemma (in field) generate_fieldI:\n  assumes \"H \\<subseteq> carrier R\"\n    and \"subfield E R\" \"H \\<subseteq> E\"\n    and \"\\<And>K. \\<lbrakk> subfield K R; H \\<subseteq> K \\<rbrakk> \\<Longrightarrow> E \\<subseteq> K\"\n  shows \"E = generate_field R H\"\nproof\n  show \"E \\<subseteq> generate_field R H\"\n    using assms generate_field_is_subfield generate_field.incl by (metis subset_iff)\n  show \"generate_field R H \\<subseteq> E\"\n    using generate_field_min_subfield1[OF assms(1-3)] by simp\nqed\n\nlemma (in field) generate_fieldE:\n  assumes \"H \\<subseteq> carrier R\" and \"E = generate_field R H\"\n  shows \"subfield E R\" and \"H \\<subseteq> E\" and \"\\<And>K. \\<lbrakk> subfield K R; H \\<subseteq> K \\<rbrakk> \\<Longrightarrow> E \\<subseteq> K\"\nproof -\n  show \"subfield E R\" using assms generate_field_is_subfield by simp\n  show \"H \\<subseteq> E\" using assms(2) by (simp add: generate_field.incl subsetI)\n  show \"\\<And>K. subfield K R  \\<Longrightarrow> H \\<subseteq> K \\<Longrightarrow> E \\<subseteq> K\"\n    using assms generate_field_min_subfield1 by auto\nqed\n\nlemma (in field) generate_field_min_subfield2:\n  assumes \"H \\<subseteq> carrier R\"\n  shows \"generate_field R H = \\<Inter>{K. subfield K R \\<and> H \\<subseteq> K}\"\nproof\n  have \"subfield (generate_field R H) R \\<and> H \\<subseteq> generate_field R H\"\n    by (simp add: assms generate_fieldE(2) generate_field_is_subfield)\n  thus \"\\<Inter>{K. subfield K R \\<and> H \\<subseteq> K} \\<subseteq> generate_field R H\" by blast\nnext\n  have \"\\<And>K. subfield K R \\<and> H \\<subseteq> K \\<Longrightarrow> generate_field R H \\<subseteq> K\"\n    by (simp add: assms generate_field_min_subfield1)\n  thus \"generate_field R H \\<subseteq> \\<Inter>{K. subfield K R \\<and> H \\<subseteq> K}\" by blast\nqed\n\nlemma (in field) mono_generate_field:\n  assumes \"I \\<subseteq> J\" and \"J \\<subseteq> carrier R\"\n  shows \"generate_field R I \\<subseteq> generate_field R J\"\nproof-\n  have \"I \\<subseteq> generate_field R J \"\n    using assms generate_fieldE(2) by blast\n  thus \"generate_field R I \\<subseteq> generate_field R J\"\n    using generate_field_min_subfield1[of I \"generate_field R J\"] assms generate_field_is_subfield[OF assms(2)]\n    by blast\nqed\n\n\nlemma (in field) subfield_gen_incl :\n  assumes \"subfield H R\"\n    and  \"subfield K R\"\n    and \"I \\<subseteq> H\"\n    and \"I \\<subseteq> K\"\n  shows \"generate_field (R\\<lparr>carrier := K\\<rparr>) I \\<subseteq> generate_field (R\\<lparr>carrier := H\\<rparr>) I\"\nproof\n  {fix J assume J_def : \"subfield J R\" \"I \\<subseteq> J\"\n    have \"generate_field (R \\<lparr> carrier := J \\<rparr>) I \\<subseteq> J\"\n      using field.mono_generate_field[of \"(R\\<lparr>carrier := J\\<rparr>)\" I J] subfield_iff(2)[OF J_def(1)]\n          field.generate_field_in_carrier[of \"R\\<lparr>carrier := J\\<rparr>\"]  field_axioms J_def\n      by auto}\n  note incl_HK = this\n  {fix x have \"x \\<in> generate_field (R\\<lparr>carrier := K\\<rparr>) I \\<Longrightarrow> x \\<in> generate_field (R\\<lparr>carrier := H\\<rparr>) I\" \n    proof (induction  rule : generate_field.induct)\n      case one\n        have \"\\<one>\\<^bsub>R\\<lparr>carrier := H\\<rparr>\\<^esub> \\<otimes> \\<one>\\<^bsub>R\\<lparr>carrier := K\\<rparr>\\<^esub> = \\<one>\\<^bsub>R\\<lparr>carrier := H\\<rparr>\\<^esub>\" by simp\n        moreover have \"\\<one>\\<^bsub>R\\<lparr>carrier := H\\<rparr>\\<^esub> \\<otimes> \\<one>\\<^bsub>R\\<lparr>carrier := K\\<rparr>\\<^esub> = \\<one>\\<^bsub>R\\<lparr>carrier := K\\<rparr>\\<^esub>\" by simp\n        ultimately show ?case using assms generate_field.one by metis\n    next\n      case (incl h) thus ?case using generate_field.incl by force\n    next\n      case (a_inv h)\n      note hyp = this\n      have \"a_inv (R\\<lparr>carrier := K\\<rparr>) h = a_inv R h\" \n        using assms group.m_inv_consistent[of \"add_monoid R\" K] a_comm_group incl_HK[of K] hyp\n               subring.axioms(1)[OF subfieldE(1)[OF assms(2)]]\n        unfolding comm_group_def a_inv_def by auto\n      moreover have \"a_inv (R\\<lparr>carrier := H\\<rparr>) h = a_inv R h\"\n        using assms group.m_inv_consistent[of \"add_monoid R\" H] a_comm_group incl_HK[of H] hyp\n               subring.axioms(1)[OF subfieldE(1)[OF assms(1)]]\n        unfolding  comm_group_def a_inv_def by auto\n      ultimately show ?case using generate_field.a_inv a_inv.IH by fastforce\n    next\n      case (m_inv h) \n      note hyp = this\n      have h_K : \"h \\<in> (K - {\\<zero>})\" using incl_HK[OF assms(2) assms(4)] hyp by auto\n      hence \"m_inv (R\\<lparr>carrier := K\\<rparr>) h = m_inv R h\" \n        using  field.m_inv_mult_of[OF subfield_iff(2)[OF assms(2)]]\n               group.m_inv_consistent[of \"mult_of R\" \"K - {\\<zero>}\"] field_mult_group units_of_inv\n               subgroup_mult_of subfieldE[OF assms(2)] unfolding mult_of_def apply simp\n        by (metis h_K mult_of_def mult_of_is_Units subgroup.mem_carrier units_of_carrier assms(2))\n      moreover have h_H : \"h \\<in> (H - {\\<zero>})\" using incl_HK[OF assms(1) assms(3)] hyp by auto\n      hence \"m_inv (R\\<lparr>carrier := H\\<rparr>) h = m_inv R h\"\n        using  field.m_inv_mult_of[OF subfield_iff(2)[OF assms(1)]]\n               group.m_inv_consistent[of \"mult_of R\" \"H - {\\<zero>}\"] field_mult_group \n               subgroup_mult_of[OF assms(1)]  unfolding mult_of_def apply simp\n        by (metis h_H field_Units m_inv_mult_of mult_of_is_Units subgroup.mem_carrier units_of_def)\n      ultimately show ?case using generate_field.m_inv m_inv.IH h_H by fastforce\n    next\n      case (eng_add h1 h2)\n      thus ?case using incl_HK assms generate_field.eng_add by force\n    next\n      case (eng_mult h1 h2)\n      thus ?case using generate_field.eng_mult by force\n    qed}\n  thus \"\\<And>x. x \\<in> generate_field (R\\<lparr>carrier := K\\<rparr>) I \\<Longrightarrow> x \\<in> generate_field (R\\<lparr>carrier := H\\<rparr>) I\"\n    by auto\nqed\n\nlemma (in field) subfield_gen_equality:\n  assumes \"subfield H R\" \"K \\<subseteq> H\"\n  shows \"generate_field R K = generate_field (R \\<lparr> carrier := H \\<rparr>) K\"\n  using subfield_gen_incl[OF assms(1) carrier_is_subfield assms(2)] assms subringE(1)\n        subfield_gen_incl[OF carrier_is_subfield assms(1) _ assms(2)] subfieldE(1)[OF assms(1)]\n  by force\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/Generated_Fields.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8596637433190939, "lm_q2_score": 0.8198933425148214, "lm_q1q2_score": 0.7048325799486953}}
{"text": "(*\n  File:      Randomised_BSTs.thy\n  Author:    Manuel Eberl (TU M\u00fcnchen)\n\n  A formalisation of the randomised binary search trees described by Mart\u00ednez & Roura.\n*)\nsection \\<open>Randomised Binary Search Trees\\<close>\ntheory Randomised_BSTs\n  imports \"Random_BSTs.Random_BSTs\" \"Monad_Normalisation.Monad_Normalisation\"\nbegin\n\nsubsection \\<open>Auxiliary facts\\<close>\n\ntext \\<open>\n  First of all, we need some fairly simple auxiliary lemmas.\n\\<close>\n\nlemma return_pmf_if: \"return_pmf (if P then a else b) = (if P then return_pmf a else return_pmf b)\"\n  by simp\n\ncontext\nbegin\n\ninterpretation pmf_as_function .\n\nlemma True_in_set_bernoulli_pmf_iff [simp]:\n  \"True \\<in> set_pmf (bernoulli_pmf p) \\<longleftrightarrow> p > 0\"\n  by transfer auto\n\nlemma False_in_set_bernoulli_pmf_iff [simp]:\n  \"False \\<in> set_pmf (bernoulli_pmf p) \\<longleftrightarrow> p < 1\"\n  by transfer auto\n\nend\n\nlemma in_set_pmf_of_setD: \"x \\<in> set_pmf (pmf_of_set A) \\<Longrightarrow> finite A \\<Longrightarrow> A \\<noteq> {} \\<Longrightarrow> x \\<in> A\"\n  by (subst (asm) set_pmf_of_set) auto\n\nlemma random_bst_reduce:\n  \"finite A \\<Longrightarrow> A \\<noteq> {} \\<Longrightarrow>\n     random_bst A = do {x \\<leftarrow> pmf_of_set A; l \\<leftarrow> random_bst {y\\<in>A. y < x};\n                        r \\<leftarrow> random_bst {y\\<in>A. y > x}; return_pmf \\<langle>l, x, r\\<rangle>}\"\n  by (subst random_bst.simps) auto\n\nlemma pmf_bind_bernoulli:\n  assumes \"x \\<in> {0..1}\"\n  shows   \"pmf (bernoulli_pmf x \\<bind> f) y = x * pmf (f True) y + (1 - x) * pmf (f False) y\"\n  using assms by (simp add: pmf_bind)\n\nlemma vimage_bool_pair:\n  \"f -` A = (\\<Union>x\\<in>{True, False}. \\<Union>y\\<in>{True, False}. if f (x, y) \\<in> A then {(x, y)} else {})\"\n  (is \"?lhs = ?rhs\") unfolding set_eq_iff\nproof\n  fix x :: \"bool \\<times> bool\"\n  obtain a b where [simp]: \"x = (a, b)\" by (cases x)\n  show \"x \\<in> ?lhs \\<longleftrightarrow> x \\<in> ?rhs\"\n    by (cases a; cases b) auto\nqed\n\nlemma Leaf_in_set_random_bst_iff [simp]:\n  \"Leaf \\<in> set_pmf (random_bst A) \\<longleftrightarrow> A = {} \\<or> \\<not>finite A\"\n  by (subst random_bst.simps) auto\n\nlemma bst_insert [intro]: \"bst t \\<Longrightarrow> bst (Tree_Set.insert x t)\"\n  by (simp add: bst_iff_sorted_wrt_less inorder_insert sorted_ins_list)\n\nlemma bst_bst_of_list [intro]: \"bst (bst_of_list xs)\"\nproof -\n  have \"bst (fold Tree_Set.insert xs t)\" if \"bst t\" for t\n    using that\n  proof (induction xs arbitrary: t)\n    case (Cons y xs)\n    show ?case by (auto intro!: Cons bst_insert)\n  qed auto\n  thus ?thesis by (simp add: bst_of_list_altdef)\nqed\n\nlemma bst_random_bst:\n  assumes \"t \\<in> set_pmf (random_bst A)\"\n  shows   \"bst t\"\nproof (cases \"finite A\")\n  case True\n  have \"random_bst A = map_pmf bst_of_list (pmf_of_set (permutations_of_set A))\"\n    by (rule random_bst_altdef) fact+\n  also have \"set_pmf \\<dots> = bst_of_list ` permutations_of_set A\"\n    using True by auto\n  finally show ?thesis using assms by auto\nnext\n  case False\n  hence \"random_bst A = return_pmf \\<langle>\\<rangle>\"\n    by (simp add: random_bst.simps)\n  with assms show ?thesis by simp\nqed\n\nlemma set_random_bst:\n  assumes \"t \\<in> set_pmf (random_bst A)\" \"finite A\"\n  shows   \"set_tree t = A\"\nproof -\n  have \"random_bst A = map_pmf bst_of_list (pmf_of_set (permutations_of_set A))\"\n    by (rule random_bst_altdef) fact+\n  also have \"set_pmf \\<dots> = bst_of_list ` permutations_of_set A\"\n    using assms by auto\n  finally show ?thesis using assms\n    by (auto simp: permutations_of_setD)\nqed\n\nlemma isin_bst:\n  assumes \"bst t\"\n  shows   \"isin t x \\<longleftrightarrow> x \\<in> set_tree t\"\n  using assms\n  by (subst isin_set) (auto simp: bst_iff_sorted_wrt_less)\n\nlemma isin_random_bst:\n  assumes \"finite A\" \"t \\<in> set_pmf (random_bst A)\"\n  shows   \"isin t x \\<longleftrightarrow> x \\<in> A\"\nproof -\n  from assms have \"bst t\" by (auto dest: bst_random_bst)\n  with assms show ?thesis by (simp add: isin_bst set_random_bst)\nqed\n\nlemma card_3way_split:\n  assumes \"x \\<in> (A :: 'a :: linorder set)\" \"finite A\"\n  shows   \"card A = card {y\\<in>A. y < x} + card {y\\<in>A. y > x} + 1\"\nproof -\n  from assms have \"A = insert x ({y\\<in>A. y < x} \\<union> {y\\<in>A. y > x})\"\n    by auto\n  also have \"card \\<dots> = card {y\\<in>A. y < x} + card {y\\<in>A. y > x} + 1\"\n    using assms by (subst card_insert_disjoint) (auto intro: card_Un_disjoint)\n  finally show ?thesis .\nqed\n\n\ntext \\<open>\n  The following theorem allows splitting a uniformly random choice from a union of two disjoint\n  sets to first tossing a coin to decide on one of the constituent sets and then chooing an \n  element from it uniformly at random.\n\\<close>\nlemma pmf_of_set_union_split:\n  assumes \"finite A\" \"finite B\" \"A \\<inter> B = {}\" \"A \\<union> B \\<noteq> {}\"\n  assumes \"p = card A / (card A + card B)\"\n  shows   \"do {b \\<leftarrow> bernoulli_pmf p; if b then pmf_of_set A else pmf_of_set B} = pmf_of_set (A \\<union> B)\"\n            (is \"?lhs = ?rhs\")\nproof (rule pmf_eqI)\n  fix x :: 'a\n  from assms have p: \"p \\<in> {0..1}\"\n    by (auto simp: divide_simps assms(5) split: if_splits)\n\n  have \"pmf ?lhs x = pmf (pmf_of_set A) x * p + pmf (pmf_of_set B) x * (1 - p)\"\n    unfolding pmf_bind using p by (subst integral_bernoulli_pmf) auto\n  also consider \"x \\<in> A\" \"B \\<noteq> {}\" | \"x \\<in> B\" \"A \\<noteq> {}\" | \"x \\<in> A\" \"B = {}\" | \"x \\<in> B\" \"A = {}\" |\n                \"x \\<notin> A\" \"x \\<notin> B\"\n    using assms by auto\n  hence \"pmf (pmf_of_set A) x * p + pmf (pmf_of_set B) x * (1 - p) = pmf ?rhs x\"\n  proof cases\n    assume \"x \\<notin> A\" \"x \\<notin> B\"\n    thus ?thesis using assms by (cases \"A = {}\"; cases \"B = {}\") auto\n  next\n    assume \"x \\<in> A\" and [simp]: \"B \\<noteq> {}\"\n    have \"pmf (pmf_of_set A) x * p + pmf (pmf_of_set B) x * (1 - p) = p / real (card A)\"\n      using \\<open>x \\<in> A\\<close> assms(1-4) by (subst (1 2) pmf_of_set) (auto simp: indicator_def)\n    also have \"\\<dots> = pmf ?rhs x\"\n      using assms \\<open>x \\<in> A\\<close> by (subst pmf_of_set) (auto simp: card_Un_disjoint)\n    finally show ?thesis .\n  next\n    assume \"x \\<in> B\" and [simp]: \"A \\<noteq> {}\"\n    from assms have *: \"card (A \\<union> B) > 0\" by (subst card_gt_0_iff) auto\n    have \"pmf (pmf_of_set A) x * p + pmf (pmf_of_set B) x * (1 - p) = (1 - p) / real (card B)\"\n      using \\<open>x \\<in> B\\<close> assms(1-4) by (subst (1 2) pmf_of_set) (auto simp: indicator_def)\n    also have \"\\<dots> = pmf ?rhs x\"\n      using assms \\<open>x \\<in> B\\<close> *\n      by (subst pmf_of_set) (auto simp: card_Un_disjoint assms(5) divide_simps)\n    finally show ?thesis .\n  qed (insert assms(1-4), auto simp: assms(5))\n  finally show \"pmf ?lhs x = pmf ?rhs x\" .\nqed\n\nlemma pmf_of_set_split_inter_diff:\n  assumes \"finite A\" \"finite B\" \"A \\<noteq> {}\" \"B \\<noteq> {}\"\n  assumes \"p = card (A \\<inter> B) / card B\"\n  shows   \"do {b \\<leftarrow> bernoulli_pmf p; if b then pmf_of_set (A \\<inter> B) else pmf_of_set (B - A)} =\n             pmf_of_set B\" (is \"?lhs = ?rhs\")\nproof -\n  have eq: \"B = (A \\<inter> B) \\<union> (B - A)\" by auto\n  have card_eq: \"card B = card (A \\<inter> B) + card (B - A)\"\n    using assms by (subst eq, subst card_Un_disjoint) auto\n  have \"?lhs = pmf_of_set ((A \\<inter> B) \\<union> (B - A))\"\n    using assms by (intro pmf_of_set_union_split) (auto simp: card_eq)\n  with eq show ?thesis by simp\nqed\n\ntext \\<open>\n  Similarly to the above rule, we can split up a uniformly random choice from the disjoint\n  union of three sets. This could be done with two coin flips, but it is more convenient to\n  choose a natural number uniformly at random instead and then do a case distinction on it.\n\\<close>\nlemma pmf_of_set_3way_split:\n  fixes f g h :: \"'a \\<Rightarrow> 'b pmf\"\n  assumes \"finite A\" \"A \\<noteq> {}\" \"A1 \\<inter> A2 = {}\" \"A1 \\<inter> A3 = {}\" \"A2 \\<inter> A3 = {}\" \"A1 \\<union> A2 \\<union> A3 = A\"\n  shows   \"do {x \\<leftarrow> pmf_of_set A; if x \\<in> A1 then f x else if x \\<in> A2 then g x else h x} =\n           do {i \\<leftarrow> pmf_of_set {..<card A};\n               if i < card A1 then pmf_of_set A1 \\<bind> f\n               else if i < card A1 + card A2 then pmf_of_set A2 \\<bind> g\n               else pmf_of_set A3 \\<bind> h}\" (is \"?lhs = ?rhs\")\nproof (intro pmf_eqI)\n  fix x :: 'b\n  define m n l where \"m = card A1\" and \"n = card A2\" and \"l = card A3\"\n  have [simp]: \"finite A1\" \"finite A2\" \"finite A3\"\n    by (rule finite_subset[of _ A]; use assms in force)+\n  from assms have card_pos: \"card A > 0\" by auto\n  have A_eq: \"A = A1 \\<union> A2 \\<union> A3\" using assms by simp\n  have card_A_eq: \"card A = card A1 + card A2 + card A3\"\n    using assms unfolding A_eq by (subst card_Un_disjoint, simp, simp, force)+ auto\n  have card_A_eq': \"{..<card A} = {..<m} \\<union> {m..<m + n} \\<union> {m + n..<card A}\"\n    by (auto simp: m_def n_def card_A_eq)\n  let ?M = \"\\<lambda>i. if i < m then pmf_of_set A1 \\<bind> f else if i < m + n then\n                  pmf_of_set A2 \\<bind> g else pmf_of_set A3 \\<bind> h\"\n\n  have card_times_pmf_of_set_bind:\n      \"card X * pmf (pmf_of_set X \\<bind> f) x = (\\<Sum>y\\<in>X. pmf (f y) x)\"\n      if \"finite X\" for X :: \"'a set\" and f :: \"'a \\<Rightarrow> 'b pmf\"\n    using that by (cases \"X = {}\") (auto simp: pmf_bind_pmf_of_set)  \n\n  have \"pmf ?rhs x = (\\<Sum>i<card A. pmf (?M i) x) / card A\"\n    (is \"_ = ?S / _\") using assms card_pos unfolding m_def n_def\n    by (subst pmf_bind_pmf_of_set) auto\n  also have \"?S = (real m * pmf (pmf_of_set A1 \\<bind> f) x +\n                   real n * pmf (pmf_of_set A2 \\<bind> g) x +\n                   real l * pmf (pmf_of_set A3 \\<bind> h) x)\" unfolding card_A_eq'\n    by (subst sum.union_disjoint, simp, simp, force)+ (auto simp: card_A_eq m_def n_def l_def)\n  also have \"\\<dots> = (\\<Sum>y\\<in>A1. pmf (f y) x) + (\\<Sum>y\\<in>A2. pmf (g y) x) + (\\<Sum>y\\<in>A3. pmf (h y) x)\"\n    unfolding m_def n_def l_def by (subst (1 2 3) card_times_pmf_of_set_bind) auto\n  also have \"\\<dots> = (\\<Sum>y\\<in>A1 \\<union> A2 \\<union> A3.\n                       pmf (if y \\<in> A1 then f y else if y \\<in> A2 then g y else h y) x)\"\n    using assms(1-5)\n    by (subst sum.union_disjoint, simp, simp, force)+\n       (intro arg_cong2[of _ _ _ _ \"(+)\"] sum.cong, auto)\n  also have \"\\<dots> / card A = pmf ?lhs x\"\n    using assms by (simp add: pmf_bind_pmf_of_set)\n  finally show \"pmf ?lhs x = pmf ?rhs x\"\n    unfolding m_def n_def l_def card_A_eq ..\nqed\n\n\nsubsection \\<open>Partitioning a BST\\<close>\n\ntext \\<open>\n  The split operation takes a search parameter \\<open>x\\<close> and partitions a BST into two BSTs\n  containing all the values that are smaller than \\<open>x\\<close> and those that are greater than \\<open>x\\<close>,\n  respectively. Note that \\<open>x\\<close> need not be an element of the tree.\n\\<close>\n\nfun split_bst :: \"'a :: linorder \\<Rightarrow> 'a tree \\<Rightarrow> 'a tree \\<times> 'a tree\" where\n  \"split_bst _ \\<langle>\\<rangle> = (\\<langle>\\<rangle>, \\<langle>\\<rangle>)\"\n| \"split_bst x \\<langle>l, y, r\\<rangle> =\n     (if y < x then\n        case split_bst x r of (t1, t2) \\<Rightarrow> (\\<langle>l, y, t1\\<rangle>, t2)\n      else if y > x then\n        case split_bst x l of (t1, t2) \\<Rightarrow> (t1, \\<langle>t2, y, r\\<rangle>)\n      else\n        (l, r))\"\n\nfun split_bst' :: \"'a :: linorder \\<Rightarrow> 'a tree \\<Rightarrow> bool \\<times> 'a tree \\<times> 'a tree\" where\n  \"split_bst' _ \\<langle>\\<rangle> = (False, \\<langle>\\<rangle>, \\<langle>\\<rangle>)\"\n| \"split_bst' x \\<langle>l, y, r\\<rangle> =\n     (if y < x then\n        case split_bst' x r of (b, t1, t2) \\<Rightarrow> (b, \\<langle>l, y, t1\\<rangle>, t2)\n      else if y > x then\n        case split_bst' x l of (b, t1, t2) \\<Rightarrow> (b, t1, \\<langle>t2, y, r\\<rangle>)\n      else\n        (True, l, r))\"\n\nlemma split_bst'_altdef: \"split_bst' x t = (isin t x, split_bst x t)\"\n  by (induction x t rule: split_bst.induct) (auto simp: case_prod_unfold)\n\nlemma fst_split_bst' [simp]: \"fst (split_bst' x t) = isin t x\"\n  and snd_split_bst' [simp]: \"snd (split_bst' x t) = split_bst x t\"\n  by (simp_all add: split_bst'_altdef)\n\n\nlemma size_fst_split_bst [termination_simp]: \"size (fst (split_bst x t)) \\<le> size t\"\n  by (induction t) (auto simp: case_prod_unfold)\n\nlemma size_snd_split_bst [termination_simp]: \"size (snd (split_bst x t)) \\<le> size t\"\n  by (induction t) (auto simp: case_prod_unfold)\n\nlemmas size_split_bst = size_fst_split_bst size_snd_split_bst\n\nlemma set_split_bst1: \"bst t \\<Longrightarrow> set_tree (fst (split_bst x t)) = {y \\<in> set_tree t. y < x}\"\n  by (induction t) (auto split: prod.splits)\n\nlemma set_split_bst2: \"bst t \\<Longrightarrow> set_tree (snd (split_bst x t)) = {y \\<in> set_tree t. y > x}\"\n  by (induction t) (auto split: prod.splits)\n\nlemma bst_split_bst1 [intro]: \"bst t \\<Longrightarrow> bst (fst (split_bst x t))\"\n  by (induction t) (auto simp: case_prod_unfold set_split_bst1)\n\nlemma bst_split_bst2 [intro]: \"bst t \\<Longrightarrow> bst (snd (split_bst x t))\"\n  by (induction t) (auto simp: case_prod_unfold set_split_bst2)\n\ntext \\<open>\n  Splitting a random BST produces two random BSTs:\n\\<close>\ntheorem split_random_bst:\n  assumes \"finite A\"\n  shows   \"map_pmf (split_bst x) (random_bst A) =\n             pair_pmf (random_bst {y\\<in>A. y < x}) (random_bst {y\\<in>A. y > x})\"\n  using assms\nproof (induction A rule: random_bst.induct)\n  case (1 A)\n  define A\\<^sub>1 A\\<^sub>2 where \"A\\<^sub>1 = {y\\<in>A. y < x}\" and \"A\\<^sub>2 = {y\\<in>A. y > x}\"\n  have [simp]: \"\\<not>x \\<in> A\\<^sub>2\" if \"x \\<in> A\\<^sub>1\" for x using that by (auto simp: A\\<^sub>1_def A\\<^sub>2_def)\n  from \\<open>finite A\\<close> have [simp]: \"finite A\\<^sub>1\" \"finite A\\<^sub>2\" by (auto simp: A\\<^sub>1_def A\\<^sub>2_def)\n  include monad_normalisation\n\n  show ?case\n  proof (cases \"A = {}\")\n    case True\n    thus ?thesis by (auto simp: pair_return_pmf1)\n  next\n    case False\n\n    have \"map_pmf (split_bst x) (random_bst A) =\n            do {y \\<leftarrow> pmf_of_set A;\n                if y < x then\n                  do {\n                    l \\<leftarrow> random_bst {z\\<in>A. z < y};\n                    (t1, t2) \\<leftarrow> map_pmf (split_bst x) (random_bst {z\\<in>A. z > y});\n                    return_pmf (\\<langle>l, y, t1\\<rangle>, t2)\n                  }\n                else if y > x then\n                  do {\n                    (t1, t2) \\<leftarrow> map_pmf (split_bst x) (random_bst {z\\<in>A. z < y});\n                    r \\<leftarrow> random_bst {z\\<in>A. z > y};\n                    return_pmf (t1, (\\<langle>t2, y, r\\<rangle>))\n                  }\n                else\n                  do {\n                    l \\<leftarrow> random_bst {z\\<in>A. z < y};\n                    r \\<leftarrow> random_bst {z\\<in>A. z > y};\n                    return_pmf (l, r)\n                  }\n               }\"\n      using \"1.prems\" False\n      by (subst random_bst.simps)\n         (simp add: map_bind_pmf bind_map_pmf return_pmf_if case_prod_unfold cong: if_cong)\n    also have \"\\<dots> = do {y \\<leftarrow> pmf_of_set A;\n                        if y < x then\n                          do {\n                            l \\<leftarrow> random_bst {z\\<in>A. z < y};\n                            (t1, t2) \\<leftarrow> pair_pmf (random_bst {z\\<in>{z\\<in>A. z > y}. z < x})\n                                                 (random_bst {z\\<in>{z\\<in>A. z > y}. z > x});\n                            return_pmf (\\<langle>l, y, t1\\<rangle>, t2)\n                          }\n                        else if y > x then\n                          do {\n                            (t1, t2) \\<leftarrow> pair_pmf (random_bst {z\\<in>{z\\<in>A. z < y}. z < x})\n                                                 (random_bst {z\\<in>{z\\<in>A. z < y}. z > x});\n                            r \\<leftarrow> random_bst {z\\<in>A. z > y};\n                            return_pmf (t1, (\\<langle>t2, y, r\\<rangle>))\n                          }\n                         else \n                           do {\n                             l \\<leftarrow> random_bst {z\\<in>A. z < y};\n                             r \\<leftarrow> random_bst {z\\<in>A. z > y};\n                             return_pmf (l, r)\n                           }\n                       }\"\n      using \\<open>finite A\\<close> and \\<open>A \\<noteq> {}\\<close> thm \"1.IH\"\n      by (intro bind_pmf_cong if_cong refl \"1.IH\") auto\n    also have \"\\<dots> = do {y \\<leftarrow> pmf_of_set A;\n                        if y < x then\n                          do {\n                            l \\<leftarrow> random_bst {z\\<in>A. z < y};\n                            t1 \\<leftarrow> random_bst {z\\<in>{z\\<in>A. z > y}. z < x};\n                            t2 \\<leftarrow> random_bst {z\\<in>{z\\<in>A. z > y}. z > x};\n                            return_pmf (\\<langle>l, y, t1\\<rangle>, t2)\n                          }\n                        else if y > x then\n                          do {\n                            t1 \\<leftarrow> random_bst {z\\<in>{z\\<in>A. z < y}. z < x};\n                            t2 \\<leftarrow> random_bst {z\\<in>{z\\<in>A. z < y}. z > x};\n                            r \\<leftarrow> random_bst {z\\<in>A. z > y};\n                            return_pmf (t1, (\\<langle>t2, y, r\\<rangle>))\n                          }\n                         else \n                           do {\n                             l \\<leftarrow> random_bst {z\\<in>A. z < y};\n                             r \\<leftarrow> random_bst {z\\<in>A. z > y};\n                             return_pmf (l, r)\n                           }\n                       }\"\n      by (simp add: pair_pmf_def cong: if_cong)\n    also have \"\\<dots> = do {y \\<leftarrow> pmf_of_set A;\n                        if y \\<in> A\\<^sub>1 then\n                          do {\n                            l \\<leftarrow> random_bst {z\\<in>A\\<^sub>1. z < y};\n                            t1 \\<leftarrow> random_bst {z\\<in>A\\<^sub>1. z > y};\n                            t2 \\<leftarrow> random_bst A\\<^sub>2;\n                            return_pmf (\\<langle>l, y, t1\\<rangle>, t2)\n                          }\n                        else if y \\<in> A\\<^sub>2 then\n                          do {\n                            t1 \\<leftarrow> random_bst A\\<^sub>1;\n                            t2 \\<leftarrow> random_bst {z\\<in>A\\<^sub>2. z < y};\n                            r \\<leftarrow> random_bst {z\\<in>A\\<^sub>2. z > y};\n                            return_pmf (t1, (\\<langle>t2, y, r\\<rangle>))\n                          }\n                         else\n                           pair_pmf (random_bst A\\<^sub>1) (random_bst A\\<^sub>2)\n                       }\"\n      using \\<open>finite A\\<close> \\<open>A \\<noteq> {}\\<close>\n      by (intro bind_pmf_cong refl if_cong arg_cong[of _ _ random_bst])\n         (auto simp: A\\<^sub>1_def A\\<^sub>2_def pair_pmf_def)\n    also have \"\\<dots> = do {i \\<leftarrow> pmf_of_set {..<card A};\n                        if i < card A\\<^sub>1 then\n                          do {\n                            y \\<leftarrow> pmf_of_set A\\<^sub>1;\n                            l \\<leftarrow> random_bst {z\\<in>A\\<^sub>1. z < y};\n                            t1 \\<leftarrow> random_bst {z\\<in>A\\<^sub>1. z > y};\n                            t2 \\<leftarrow> random_bst A\\<^sub>2;\n                            return_pmf (\\<langle>l, y, t1\\<rangle>, t2)\n                          }\n                        else if i < card A\\<^sub>1 + card A\\<^sub>2 then\n                          do {\n                            y \\<leftarrow> pmf_of_set A\\<^sub>2;\n                            t1 \\<leftarrow> random_bst A\\<^sub>1;\n                            t2 \\<leftarrow> random_bst {z\\<in>A\\<^sub>2. z < y};\n                            r \\<leftarrow> random_bst {z\\<in>A\\<^sub>2. z > y};\n                            return_pmf (t1, (\\<langle>t2, y, r\\<rangle>))\n                          }\n                         else do {\n                           y \\<leftarrow> pmf_of_set (if x \\<in> A then {x} else {});\n                           pair_pmf (random_bst A\\<^sub>1) (random_bst A\\<^sub>2)\n                         }\n                       }\" using \\<open>finite A\\<close> \\<open>A \\<noteq> {}\\<close>\n      by (intro pmf_of_set_3way_split) (auto simp: A\\<^sub>1_def A\\<^sub>2_def not_less_iff_gr_or_eq)\n    also have \"\\<dots> = do {i \\<leftarrow> pmf_of_set {..<card A};\n                        if i < card A\\<^sub>1 then\n                          pair_pmf (random_bst A\\<^sub>1) (random_bst A\\<^sub>2)\n                        else if i < card A\\<^sub>1 + card A\\<^sub>2 then\n                          pair_pmf (random_bst A\\<^sub>1) (random_bst A\\<^sub>2)\n                         else \n                          pair_pmf (random_bst A\\<^sub>1) (random_bst A\\<^sub>2)\n                       }\"\n      using \\<open>finite A\\<close> \\<open>A \\<noteq> {}\\<close>\n    proof (intro bind_pmf_cong refl if_cong, goal_cases)\n      case (1 i)\n      hence \"A\\<^sub>1 \\<noteq> {}\" by auto\n      thus ?case using \\<open>finite A\\<close> by (simp add: pair_pmf_def random_bst_reduce)\n    next\n      case (2 i)\n      hence \"A\\<^sub>2 \\<noteq> {}\" by auto\n      thus ?case using \\<open>finite A\\<close> by (simp add: pair_pmf_def random_bst_reduce)\n    qed auto\n    also have \"\\<dots> = pair_pmf (random_bst A\\<^sub>1) (random_bst A\\<^sub>2)\"\n      by (simp cong: if_cong)\n    finally show ?thesis by (simp add: A\\<^sub>1_def A\\<^sub>2_def)\n  qed\nqed\n\n\nsubsection \\<open>Joining\\<close>\n\ntext \\<open>\n  The ``join'' operation computes the union of two BSTs \\<open>l\\<close> and \\<open>r\\<close> where all the values in\n  \\<open>l\\<close> are stricly smaller than those in \\<open>r\\<close>.\n\\<close>\nfun mrbst_join :: \"'a tree \\<Rightarrow> 'a tree \\<Rightarrow> 'a tree pmf\" where\n  \"mrbst_join t1 t2 =\n     (if t1 = \\<langle>\\<rangle> then return_pmf t2\n      else if t2 = \\<langle>\\<rangle> then return_pmf t1\n      else do {\n        b \\<leftarrow> bernoulli_pmf (size t1 / (size t1 + size t2));\n        if b then\n          (case t1 of \\<langle>l, x, r\\<rangle> \\<Rightarrow> map_pmf (\\<lambda>r'. \\<langle>l, x, r'\\<rangle>) (mrbst_join r t2))\n        else\n          (case t2 of \\<langle>l, x, r\\<rangle> \\<Rightarrow> map_pmf (\\<lambda>l'. \\<langle>l', x, r\\<rangle>) (mrbst_join t1 l))\n      })\"\n\nlemma mrbst_join_Leaf_left [simp]: \"mrbst_join \\<langle>\\<rangle> = return_pmf\"\n  by (simp add: fun_eq_iff)\n\nlemma mrbst_join_Leaf_right [simp]: \"mrbst_join t \\<langle>\\<rangle> = return_pmf t\"\n  by (simp add: fun_eq_iff)\n\nlemma mrbst_join_reduce:\n  \"t1 \\<noteq> \\<langle>\\<rangle> \\<Longrightarrow> t2 \\<noteq> \\<langle>\\<rangle> \\<Longrightarrow> mrbst_join t1 t2 =\n     do {\n        b \\<leftarrow> bernoulli_pmf (size t1 / (size t1 + size t2));\n        if b then\n          (case t1 of \\<langle>l, x, r\\<rangle> \\<Rightarrow> map_pmf (\\<lambda>r'. \\<langle>l, x, r'\\<rangle>) (mrbst_join r t2))\n        else\n          (case t2 of \\<langle>l, x, r\\<rangle> \\<Rightarrow> map_pmf (\\<lambda>l'. \\<langle>l', x, r\\<rangle>) (mrbst_join t1 l))\n      }\"\n  by (subst mrbst_join.simps) auto\n\nlemmas [simp del] = mrbst_join.simps\n\nlemma\n  assumes \"t' \\<in> set_pmf (mrbst_join t1 t2)\" \"bst t1\" \"bst t2\"\n  assumes \"\\<And>x y. x \\<in> set_tree t1 \\<Longrightarrow> y \\<in> set_tree t2 \\<Longrightarrow> x < y\"\n  shows   bst_mrbst_join: \"bst t'\"\n    and   set_mrbst_join: \"set_tree t' = set_tree t1 \\<union> set_tree t2\"\nproof -\n  have \"bst t' \\<and> set_tree t' = set_tree t1 \\<union> set_tree t2\"\n  using assms\n  proof (induction \"size t1 + size t2\" arbitrary: t1 t2 t' rule: less_induct)\n    case (less t1 t2 t')\n    show ?case\n    proof (cases \"t1 = \\<langle>\\<rangle> \\<or> t2 = \\<langle>\\<rangle>\")\n      case False\n      hence \"t' \\<in> set_pmf (case t1 of \\<langle>l, x, r\\<rangle> \\<Rightarrow> map_pmf (Node l x) (mrbst_join r t2)) \\<or>\n             t' \\<in> set_pmf (case t2 of \\<langle>l, x, r\\<rangle> \\<Rightarrow> map_pmf (\\<lambda>l'. \\<langle>l', x, r\\<rangle>) (mrbst_join t1 l))\"\n        using less.prems by (subst (asm) mrbst_join_reduce) (auto split: if_splits)\n      thus ?thesis\n      proof\n        assume \"t' \\<in> set_pmf (case t1 of \\<langle>l, x, r\\<rangle> \\<Rightarrow> map_pmf (Node l x) (mrbst_join r t2))\"\n        then obtain l x r r'\n          where *: \"t1 = \\<langle>l, x, r\\<rangle>\" \"r' \\<in> set_pmf (mrbst_join r t2)\" \"t' = \\<langle>l, x, r'\\<rangle>\"\n          using False by (auto split: tree.splits)\n        from * and less.prems have \"bst r' \\<and> set_tree r' = set_tree r \\<union> set_tree t2\"\n          by (intro less) auto\n        with * and less.prems show ?thesis by auto\n      next\n        assume \"t' \\<in> set_pmf (case t2 of \\<langle>l, x, r\\<rangle> \\<Rightarrow> map_pmf (\\<lambda>l'. \\<langle>l', x, r\\<rangle>) (mrbst_join t1 l))\"\n        then obtain l x r l'\n          where *: \"t2 = \\<langle>l, x, r\\<rangle>\" \"l' \\<in> set_pmf (mrbst_join t1 l)\" \"t' = \\<langle>l', x, r\\<rangle>\"\n          using False by (auto split: tree.splits)\n        from * and less.prems have \"bst l' \\<and> set_tree l' = set_tree t1 \\<union> set_tree l\"\n          by (intro less) auto\n        with * and less.prems show ?thesis by auto\n      qed\n    qed (insert less.prems, auto)\n  qed\n  thus \"bst t'\" \"set_tree t' = set_tree t1 \\<union> set_tree t2\" by auto\nqed\n\ntext \\<open>\n  Joining two random BSTs that satisfy the necessary preconditions again yields a random BST.\n\\<close>\ntheorem mrbst_join_correct:\n  fixes A B :: \"'a :: linorder set\"\n  assumes \"finite A\" \"finite B\" \"\\<And>x y. x \\<in> A \\<Longrightarrow> y \\<in> B \\<Longrightarrow> x < y\"\n  shows   \"do {t1 \\<leftarrow> random_bst A; t2 \\<leftarrow> random_bst B; mrbst_join t1 t2} = random_bst (A \\<union> B)\"\nproof -\n  from assms have \"finite (A \\<union> B)\" by simp\n  from this and assms show ?thesis\n  proof (induction \"A \\<union> B\" arbitrary: A B rule: finite_psubset_induct)\n    case (psubset A B)\n    define m n where \"m = card A\" and \"n = card B\"\n    define p where \"p = m / (m + n)\"\n\n    include monad_normalisation\n    show ?case\n    proof (cases \"A = {} \\<or> B = {}\")\n      case True\n      thus ?thesis by auto\n    next\n      case False\n      have AB: \"A \\<noteq> {}\" \"B \\<noteq> {}\" \"finite A\" \"finite B\"\n        using False psubset.prems by auto\n      have p_pos: \"A \\<noteq> {}\" if \"p > 0\" using \\<open>finite A\\<close> that\n        using AB by (auto simp: p_def m_def n_def)\n      have p_lt1: \"B \\<noteq> {}\" if \"p < 1\"\n        using AB by (auto simp: p_def m_def n_def)\n\n      have \"do {t1 \\<leftarrow> random_bst A; t2 \\<leftarrow> random_bst B; mrbst_join t1 t2} =\n            do {t1 \\<leftarrow> random_bst A;\n                t2 \\<leftarrow> random_bst B;\n                b \\<leftarrow> bernoulli_pmf (size t1 / (size t1 + size t2));\n                if b then\n                  case t1 of \\<langle>l, x, r\\<rangle> \\<Rightarrow> map_pmf (\\<lambda>r'. \\<langle>l, x, r'\\<rangle>) (mrbst_join r t2)\n                else\n                  case t2 of \\<langle>l, x, r\\<rangle> \\<Rightarrow> map_pmf (\\<lambda>l'. \\<langle>l', x, r\\<rangle>) (mrbst_join t1 l)\n               }\"\n        using AB\n        by (intro bind_pmf_cong refl, subst mrbst_join_reduce) auto\n      also have \"\\<dots> = do {t1 \\<leftarrow> random_bst A;\n                          t2 \\<leftarrow> random_bst B;\n                          b \\<leftarrow> bernoulli_pmf p;\n                          if b then\n                            case t1 of \\<langle>l, x, r\\<rangle> \\<Rightarrow> map_pmf (\\<lambda>r'. \\<langle>l, x, r'\\<rangle>) (mrbst_join r t2)\n                          else\n                            case t2 of \\<langle>l, x, r\\<rangle> \\<Rightarrow> map_pmf (\\<lambda>l'. \\<langle>l', x, r\\<rangle>) (mrbst_join t1 l)\n                         }\"\n        using AB by (intro bind_pmf_cong refl arg_cong[of _ _ bernoulli_pmf])\n                    (auto simp: p_def m_def n_def size_random_bst)\n      also have \"\\<dots> = do {\n                        b \\<leftarrow> bernoulli_pmf p;\n                        if b then do {\n                          t1 \\<leftarrow> random_bst A;\n                          t2 \\<leftarrow> random_bst B;\n                          case t1 of \\<langle>l, x, r\\<rangle> \\<Rightarrow> map_pmf (\\<lambda>r'. \\<langle>l, x, r'\\<rangle>) (mrbst_join r t2)\n                        } else do {\n                          t1 \\<leftarrow> random_bst A;\n                          t2 \\<leftarrow> random_bst B;\n                          case t2 of \\<langle>l, x, r\\<rangle> \\<Rightarrow> map_pmf (\\<lambda>l'. \\<langle>l', x, r\\<rangle>) (mrbst_join t1 l)\n                        }\n                      }\"\n        by simp\n      also have \"\\<dots> = do {\n                        b \\<leftarrow> bernoulli_pmf p;\n                        if b then do {\n                          x \\<leftarrow> pmf_of_set A;\n                          l \\<leftarrow> random_bst {y\\<in>A \\<union> B. y < x};\n                          r \\<leftarrow> random_bst {y\\<in>A \\<union> B. y > x};\n                          return_pmf \\<langle>l, x, r\\<rangle>\n                        } else do {\n                          x \\<leftarrow> pmf_of_set B;\n                          l \\<leftarrow> random_bst {y\\<in>A \\<union> B. y < x};\n                          r \\<leftarrow> random_bst {y\\<in>A \\<union> B. y > x};\n                          return_pmf \\<langle>l, x, r\\<rangle>\n                        }\n                      }\"\n      proof (intro bind_pmf_cong refl if_cong, goal_cases)\n        case (1 b)\n        hence [simp]: \"A \\<noteq> {}\" using p_pos by auto\n        have \"do {t1 \\<leftarrow> random_bst A; t2 \\<leftarrow> random_bst B;\n                  case t1 of \\<langle>l, x, r\\<rangle> \\<Rightarrow> map_pmf (\\<lambda>r'. \\<langle>l, x, r'\\<rangle>) (mrbst_join r t2)} =\n              do {\n                x \\<leftarrow> pmf_of_set A;\n                l \\<leftarrow> random_bst {y\\<in>A. y < x};\n                r \\<leftarrow> do {r \\<leftarrow> random_bst {y\\<in>A. y > x}; t2 \\<leftarrow> random_bst B; mrbst_join r t2};\n                return_pmf \\<langle>l, x, r\\<rangle>\n              }\"\n          using AB by (subst random_bst_reduce) (auto simp: map_pmf_def)\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} \\<union> B);\n                          return_pmf \\<langle>l, x, r\\<rangle>\n                        }\"\n          using AB psubset.prems \n          by (intro bind_pmf_cong refl psubset arg_cong[of _ _ random_bst]) auto\n        also have \"\\<dots> = do {\n                          x \\<leftarrow> pmf_of_set A;\n                          l \\<leftarrow> random_bst {y\\<in>A \\<union> B. y < x};\n                          r \\<leftarrow> random_bst {y\\<in>A \\<union> B. y > x};\n                          return_pmf \\<langle>l, x, r\\<rangle>\n                        }\"\n          using AB psubset.prems\n          by (intro bind_pmf_cong refl arg_cong[of _ _ random_bst]; force)\n        finally show ?case .\n      next\n        case (2 b)\n        hence [simp]: \"B \\<noteq> {}\" using p_lt1 by auto\n        have \"do {t1 \\<leftarrow> random_bst A; t2 \\<leftarrow> random_bst B;\n                  case t2 of \\<langle>l, x, r\\<rangle> \\<Rightarrow> map_pmf (\\<lambda>l'. \\<langle>l', x, r\\<rangle>) (mrbst_join t1 l)} =\n              do {\n                x \\<leftarrow> pmf_of_set B;\n                l \\<leftarrow> do {t1 \\<leftarrow> random_bst A; l \\<leftarrow> random_bst {y\\<in>B. y < x}; mrbst_join t1 l};\n                r \\<leftarrow> random_bst {y\\<in>B. y > x};\n                return_pmf \\<langle>l, x, r\\<rangle>\n              }\"\n          using AB by (subst random_bst_reduce) (auto simp: map_pmf_def)\n        also have \"\\<dots> = do {\n                          x \\<leftarrow> pmf_of_set B;\n                          l \\<leftarrow> random_bst (A \\<union> {y\\<in>B. y < x});\n                          r \\<leftarrow> random_bst {y\\<in>B. y > x};\n                          return_pmf \\<langle>l, x, r\\<rangle>\n                        }\"\n          using AB psubset.prems \n          by (intro bind_pmf_cong refl psubset arg_cong[of _ _ random_bst]) auto\n        also have \"\\<dots> = do {\n                          x \\<leftarrow> pmf_of_set B;\n                          l \\<leftarrow> random_bst {y\\<in>A \\<union> B. y < x};\n                          r \\<leftarrow> random_bst {y\\<in>A \\<union> B. y > x};\n                          return_pmf \\<langle>l, x, r\\<rangle>\n                        }\"\n          using AB psubset.prems\n          by (intro bind_pmf_cong refl arg_cong[of _ _ random_bst]; force)\n        finally show ?case .\n      qed\n      also have \"\\<dots> = do {\n                        b \\<leftarrow> bernoulli_pmf p;\n                        x \\<leftarrow> (if b then pmf_of_set A else pmf_of_set B);\n                        l \\<leftarrow> random_bst {y\\<in>A \\<union> B. y < x};\n                        r \\<leftarrow> random_bst {y\\<in>A \\<union> B. y > x};\n                        return_pmf \\<langle>l, x, r\\<rangle>\n                      }\"\n        by (intro bind_pmf_cong) simp_all\n      also have \"\\<dots> = do {\n                        x \\<leftarrow> do {b \\<leftarrow> bernoulli_pmf p; if b then pmf_of_set A else pmf_of_set B};\n                        l \\<leftarrow> random_bst {y\\<in>A \\<union> B. y < x};\n                        r \\<leftarrow> random_bst {y\\<in>A \\<union> B. y > x};\n                        return_pmf \\<langle>l, x, r\\<rangle>\n                      }\"\n        by simp\n      also have \"do {b \\<leftarrow> bernoulli_pmf p; if b then pmf_of_set A else pmf_of_set B} =\n                   pmf_of_set (A \\<union> B)\"\n        using AB psubset.prems by (intro pmf_of_set_union_split) (auto simp: p_def m_def n_def) \n      also have \"do {\n                   x \\<leftarrow> pmf_of_set (A \\<union> B);\n                   l \\<leftarrow> random_bst {y\\<in>A \\<union> B. y < x};\n                   r \\<leftarrow> random_bst {y\\<in>A \\<union> B. y > x};\n                   return_pmf \\<langle>l, x, r\\<rangle>\n                 } = random_bst (A \\<union> B)\"\n        using AB by (intro random_bst_reduce [symmetric]) auto\n      finally show ?thesis .\n    qed\n  qed\nqed\n\n\nsubsection \\<open>Pushdown\\<close>\n\ntext \\<open>\n  The ``push down'' operation ``forgets'' information about the root of a tree in the following\n  sense: It takes a non-empty tree whose root is some known fixed value and whose children are\n  random BSTs and shuffles the root in such a way that the resulting tree is a random BST.\n\\<close>\nfun mrbst_push_down :: \"'a tree \\<Rightarrow> 'a \\<Rightarrow> 'a tree \\<Rightarrow> 'a tree pmf\" where\n  \"mrbst_push_down l x r =\n     do {\n       k \\<leftarrow> pmf_of_set {0..size l + size r};\n       if k < size l then\n         case l of\n           \\<langle>ll, y, lr\\<rangle> \\<Rightarrow> map_pmf (\\<lambda>r'. \\<langle>ll, y, r'\\<rangle>) (mrbst_push_down lr x r)\n       else if k < size l + size r then\n         case r of\n           \\<langle>rl, y, rr\\<rangle> \\<Rightarrow> map_pmf (\\<lambda>l'. \\<langle>l', y, rr\\<rangle>) (mrbst_push_down l x rl)\n       else\n         return_pmf \\<langle>l, x, r\\<rangle>\n     }\"\n\nlemmas [simp del] = mrbst_push_down.simps\n\nlemma\n  assumes \"t' \\<in> set_pmf (mrbst_push_down t1 x t2)\" \"bst t1\" \"bst t2\"\n  assumes \"\\<And>y. y \\<in> set_tree t1 \\<Longrightarrow> y < x\" \"\\<And>y. y \\<in> set_tree t2 \\<Longrightarrow> y > x\"\n  shows   bst_mrbst_push_down: \"bst t'\"\n    and   set_mrbst_push_down: \"set_tree t' = {x} \\<union> set_tree t1 \\<union> set_tree t2\"\nproof -\n  have \"bst t' \\<and> set_tree t' = {x} \\<union> set_tree t1 \\<union> set_tree t2\"\n  using assms\n  proof (induction \"size t1 + size t2\" arbitrary: t1 t2 t' rule: less_induct)\n    case (less t1 t2 t')\n    have \"t1 \\<noteq> \\<langle>\\<rangle> \\<and> t' \\<in> set_pmf (case t1 of \\<langle>l, y, r\\<rangle> \\<Rightarrow>\n                            map_pmf (Node l y) (mrbst_push_down r x t2)) \\<or>\n          t2 \\<noteq> \\<langle>\\<rangle> \\<and> t' \\<in> set_pmf (case t2 of \\<langle>l, y, r\\<rangle> \\<Rightarrow>\n                            map_pmf (\\<lambda>l'. \\<langle>l', y, r\\<rangle>) (mrbst_push_down t1 x l)) \\<or>\n          t' = \\<langle>t1, x, t2\\<rangle>\"\n      using less.prems by (subst (asm) mrbst_push_down.simps) (auto split: if_splits)\n    thus ?case\n    proof (elim disjE, goal_cases)\n      case 1\n      then obtain l y r r'\n        where *: \"t1 = \\<langle>l, y, r\\<rangle>\" \"r' \\<in> set_pmf (mrbst_push_down r x t2)\" \"t' = \\<langle>l, y, r'\\<rangle>\"\n        by (auto split: tree.splits)\n      from * and less.prems have \"bst r' \\<and> set_tree r' = {x} \\<union> set_tree r \\<union> set_tree t2\"\n        by (intro less) auto\n      with * and less.prems show ?case by force\n    next\n      case 2\n      then obtain l y r l'\n        where *: \"t2 = \\<langle>l, y, r\\<rangle>\" \"l' \\<in> set_pmf (mrbst_push_down t1 x l)\" \"t' = \\<langle>l', y, r\\<rangle>\"\n        by (auto split: tree.splits)\n      from * and less.prems have \"bst l' \\<and> set_tree l' = {x} \\<union> set_tree t1 \\<union> set_tree l\"\n        by (intro less) auto\n      with * and less.prems show ?case by force\n    qed (insert less.prems, auto)\n  qed\n  thus \"bst t'\" \"set_tree t' = {x} \\<union> set_tree t1 \\<union> set_tree t2\" by auto\nqed\n\ntheorem mrbst_push_down_correct:\n  fixes A B :: \"'a :: linorder set\"\n  assumes \"finite A\" \"finite B\" \"\\<And>y. y \\<in> A \\<Longrightarrow> y < x\" \"\\<And>y. y \\<in> B \\<Longrightarrow> x < y\"\n  shows   \"do {l \\<leftarrow> random_bst A; r \\<leftarrow> random_bst B; mrbst_push_down l x r} =\n             random_bst ({x} \\<union> A \\<union> B)\"\nproof -\n  from assms have \"finite (A \\<union> B)\" by simp\n  from this and assms show ?thesis\n  proof (induction \"A \\<union> B\" arbitrary: A B rule: finite_psubset_induct)\n    case (psubset A B)\n    define m n where \"m = card A\" and \"n = card B\"\n    have A_ne: \"A \\<noteq> {}\" if \"m > 0\"\n      using that by (auto simp: m_def)\n    have B_ne: \"B \\<noteq> {}\" if \"n > 0\"\n      using that by (auto simp: n_def)\n\n    include monad_normalisation\n    have \"do {l \\<leftarrow> random_bst A; r \\<leftarrow> random_bst B; mrbst_push_down l x r} =\n          do {l \\<leftarrow> random_bst A;\n              r \\<leftarrow> random_bst B;\n              k \\<leftarrow> pmf_of_set {0..m + n};\n              if k < m then\n                case l of \\<langle>ll, y, lr\\<rangle> \\<Rightarrow> map_pmf (\\<lambda>r'. \\<langle>ll, y, r'\\<rangle>) (mrbst_push_down lr x r)\n              else if k < m + n then\n                case r of \\<langle>rl, y, rr\\<rangle> \\<Rightarrow> map_pmf (\\<lambda>l'. \\<langle>l', y, rr\\<rangle>) (mrbst_push_down l x rl)\n              else\n                return_pmf \\<langle>l, x, r\\<rangle>\n             }\"\n      using psubset.prems\n      by (subst mrbst_push_down.simps, intro bind_pmf_cong refl)\n         (auto simp: size_random_bst m_def n_def)\n    also have \"\\<dots> = do {k \\<leftarrow> pmf_of_set {0..m + n};\n                        if k < m then do {\n                          l \\<leftarrow> random_bst A;\n                          r \\<leftarrow> random_bst B;\n                          case l of \\<langle>ll, y, lr\\<rangle> \\<Rightarrow> map_pmf (\\<lambda>r'. \\<langle>ll, y, r'\\<rangle>) (mrbst_push_down lr x r)\n                        } else if k < m + n then do {\n                          l \\<leftarrow> random_bst A;\n                          r \\<leftarrow> random_bst B;\n                          case r of \\<langle>rl, y, rr\\<rangle> \\<Rightarrow> map_pmf (\\<lambda>l'. \\<langle>l', y, rr\\<rangle>) (mrbst_push_down l x rl)\n                        } else do {\n                          l \\<leftarrow> random_bst A;\n                          r \\<leftarrow> random_bst B;\n                          return_pmf \\<langle>l, x, r\\<rangle>\n                        }\n                       }\"\n      by (simp cong: if_cong)\n    also have \"\\<dots> = do {k \\<leftarrow> pmf_of_set {0..m + n};\n                        if k < m then do {\n                          y \\<leftarrow> pmf_of_set A;\n                          ll \\<leftarrow> random_bst {z\\<in>A. z < y};\n                          r' \\<leftarrow> do {lr \\<leftarrow> random_bst {z\\<in>A. z > y};\n                                    r \\<leftarrow> random_bst B;\n                                    mrbst_push_down lr x r};\n                          return_pmf \\<langle>ll, y, r'\\<rangle>\n                        } else if k < m + n then do {\n                          y \\<leftarrow> pmf_of_set B;\n                          l' \\<leftarrow> do {l \\<leftarrow> random_bst A;\n                                    rl \\<leftarrow> random_bst {z\\<in>B. z < y};\n                                    mrbst_push_down l x rl};\n                          rr \\<leftarrow> random_bst {z\\<in>B. z > y};\n                          return_pmf \\<langle>l', y, rr\\<rangle>\n                        } else do {\n                          l \\<leftarrow> random_bst A;\n                          r \\<leftarrow> random_bst B;\n                          return_pmf \\<langle>l, x, r\\<rangle>\n                        }\n                       }\"\n    proof (intro bind_pmf_cong refl if_cong, goal_cases)\n      case (1 k)\n      hence \"A \\<noteq> {}\" by (auto simp: m_def)\n      with \\<open>finite A\\<close> show ?case by (simp add: random_bst_reduce map_pmf_def)\n    next\n      case (2 k)\n      hence \"B \\<noteq> {}\" by (auto simp: m_def n_def)\n      with \\<open>finite B\\<close> show ?case by (simp add: random_bst_reduce map_pmf_def)\n    qed\n    also have \"\\<dots> = do {k \\<leftarrow> pmf_of_set {0..m + n};\n                        if k < m then do {\n                          y \\<leftarrow> pmf_of_set A;\n                          ll \\<leftarrow> random_bst {z\\<in>A. z < y};\n                          r' \\<leftarrow> random_bst ({x} \\<union> {z\\<in>A. z > y} \\<union> B);\n                          return_pmf \\<langle>ll, y, r'\\<rangle>\n                        } else if k < m + n then do {\n                          y \\<leftarrow> pmf_of_set B;\n                          l' \\<leftarrow> random_bst ({x} \\<union> A \\<union> {z\\<in>B. z < y});\n                          rr \\<leftarrow> random_bst {z\\<in>B. z > y};\n                          return_pmf \\<langle>l', y, rr\\<rangle>\n                        } else do {\n                          l \\<leftarrow> random_bst A;\n                          r \\<leftarrow> random_bst B;\n                          return_pmf \\<langle>l, x, r\\<rangle>\n                        }\n                       }\"\n      using psubset.prems A_ne B_ne\n    proof (intro bind_pmf_cong refl if_cong psubset)\n      fix k y assume \"k < m\" \"y \\<in> set_pmf (pmf_of_set A)\"\n      thus \"{z\\<in>A. z > y} \\<union> B \\<subset> A \\<union> B\"\n        using psubset.prems A_ne by (fastforce dest!: in_set_pmf_of_setD)\n    next\n      fix k y assume \"\\<not>k < m\" \"k < m + n\" \"y \\<in> set_pmf (pmf_of_set B)\"\n      thus \"A \\<union> {z\\<in>B. z < y} \\<subset> A \\<union> B\"\n        using psubset.prems B_ne by (fastforce dest!: in_set_pmf_of_setD)\n    qed auto\n    also have \"\\<dots> = do {k \\<leftarrow> pmf_of_set {0..m + n};\n                        if k < m then do {\n                          y \\<leftarrow> pmf_of_set A;\n                          ll \\<leftarrow> random_bst {z\\<in>{x} \\<union> A \\<union> B. z < y};\n                          r' \\<leftarrow> random_bst {z\\<in>{x} \\<union> A \\<union> B. z > y};\n                          return_pmf \\<langle>ll, y, r'\\<rangle>\n                        } else if k < m + n then do {\n                          y \\<leftarrow> pmf_of_set B;\n                          l' \\<leftarrow> random_bst {z\\<in>{x} \\<union> A \\<union> B. z < y};\n                          rr \\<leftarrow> random_bst {z\\<in>{x} \\<union> A \\<union> B. z > y};\n                          return_pmf \\<langle>l', y, rr\\<rangle>\n                        } else do {\n                          l \\<leftarrow> random_bst {z\\<in>{x} \\<union> A \\<union> B. z < x};\n                          r \\<leftarrow> random_bst {z\\<in>{x} \\<union> A \\<union> B. z > x};\n                          return_pmf \\<langle>l, x, r\\<rangle>\n                        }\n                       }\"\n      using psubset.prems A_ne B_ne\n      by (intro bind_pmf_cong if_cong refl arg_cong[of _ _ random_bst];\n          force dest: psubset.prems(3,4))\n    also have \"\\<dots> = do {k \\<leftarrow> pmf_of_set {0..m + n};\n                        if k < m then do {\n                          y \\<leftarrow> pmf_of_set A;\n                          ll \\<leftarrow> random_bst {z\\<in>{x} \\<union> A \\<union> B. z < y};\n                          r' \\<leftarrow> random_bst {z\\<in>{x} \\<union> A \\<union> B. z > y};\n                          return_pmf \\<langle>ll, y, r'\\<rangle>\n                        } else if k < m + n then do {\n                          y \\<leftarrow> pmf_of_set B;\n                          l' \\<leftarrow> random_bst {z\\<in>{x} \\<union> A \\<union> B. z < y};\n                          rr \\<leftarrow> random_bst {z\\<in>{x} \\<union> A \\<union> B. z > y};\n                          return_pmf \\<langle>l', y, rr\\<rangle>\n                        } else do {\n                          y \\<leftarrow> pmf_of_set {x};\n                          l \\<leftarrow> random_bst {z\\<in>{x} \\<union> A \\<union> B. z < y};\n                          r \\<leftarrow> random_bst {z\\<in>{x} \\<union> A \\<union> B. z > y};\n                          return_pmf \\<langle>l, x, r\\<rangle>\n                        }\n                       }\" (is \"_ = ?X {0..m+n}\")\n      by (simp add: pmf_of_set_singleton cong: if_cong)\n    also have \"{0..m + n} = {..<card (A \\<union> B \\<union> {x})}\" using psubset.prems\n      by (subst card_Un_disjoint, simp, simp, force)+\n         (auto simp: m_def n_def)\n    also have \"?X \\<dots> = do {y \\<leftarrow> pmf_of_set ({x} \\<union> A \\<union> B);\n                           l \\<leftarrow> random_bst {z\\<in>{x} \\<union> A \\<union> B. z < y};\n                           r \\<leftarrow> random_bst {z\\<in>{x} \\<union> A \\<union> B. z > y};\n                           return_pmf \\<langle>l, y, r\\<rangle>}\"\n      unfolding m_def n_def using psubset.prems\n      by (subst pmf_of_set_3way_split [symmetric])\n         (auto dest!: psubset.prems(3,4) cong: if_cong intro: bind_pmf_cong)\n    also have \"\\<dots> = random_bst ({x} \\<union> A \\<union> B)\"\n      using psubset.prems by (simp add: random_bst_reduce)\n    finally show ?case .\n  qed\nqed\n\nlemma mrbst_push_down_correct':\n  assumes \"finite (A :: 'a :: linorder set)\" \"x \\<in> A\"\n  shows   \"do {l \\<leftarrow> random_bst {y\\<in>A. y < x}; r \\<leftarrow> random_bst {y\\<in>A. y > x}; mrbst_push_down l x r} =\n             random_bst A\" (is \"?lhs = ?rhs\")\nproof -\n  have \"?lhs = random_bst ({x} \\<union> {y\\<in>A. y < x} \\<union> {y\\<in>A. y > x})\"\n    using assms by (intro mrbst_push_down_correct) auto\n  also have \"{x} \\<union> {y\\<in>A. y < x} \\<union> {y\\<in>A. y > x} = A\"\n    using assms by auto\n  finally show ?thesis .\nqed\n\n\nsubsection \\<open>Intersection and Difference\\<close>\n\ntext \\<open>\n  The algorithms for intersection and difference of two trees are almost identical; the only\n  difference is that the ``if'' statement at the end of the recursive case is flipped. We\n  therefore introduce a generic intersection/difference operation first and prove its correctness\n  to avoid duplication.\n\\<close>\nfun mrbst_inter_diff where\n  \"mrbst_inter_diff _ \\<langle>\\<rangle> _ = return_pmf \\<langle>\\<rangle>\"\n| \"mrbst_inter_diff b \\<langle>l1, x, r1\\<rangle> t2 =\n     (case split_bst' x t2 of (sep, l2, r2) \\<Rightarrow>\n        do {\n          l \\<leftarrow> mrbst_inter_diff b l1 l2;\n          r \\<leftarrow> mrbst_inter_diff b r1 r2;\n          if sep = b then return_pmf \\<langle>l, x, r\\<rangle> else mrbst_join l r\n        })\"\n\nlemma mrbst_inter_diff_reduce:\n  \"mrbst_inter_diff b \\<langle>l1, x, r1\\<rangle> =\n     (\\<lambda>t2. case split_bst' x t2 of (sep, l2, r2) \\<Rightarrow>\n        do {\n           l \\<leftarrow> mrbst_inter_diff b l1 l2;\n           r \\<leftarrow> mrbst_inter_diff b r1 r2;\n           if sep = b then return_pmf \\<langle>l, x, r\\<rangle> else mrbst_join l r\n         })\"\n  by (rule ext) simp\n\nlemma mrbst_inter_diff_Leaf_left [simp]:\n  \"mrbst_inter_diff b \\<langle>\\<rangle> = (\\<lambda>_. return_pmf \\<langle>\\<rangle>)\"\n  by (simp add: fun_eq_iff)\n\nlemma mrbst_inter_diff_Leaf_right [simp]:\n  \"mrbst_inter_diff b (t1 :: 'a :: linorder tree) \\<langle>\\<rangle> = return_pmf (if b then \\<langle>\\<rangle> else t1)\"\n  by (induction t1) (auto simp: bind_return_pmf)\n\nlemma\n  fixes t1 t2 :: \"'a :: linorder tree\" and b :: bool\n  defines \"setop \\<equiv> (if b then (\\<inter>) else (-) :: 'a set \\<Rightarrow> _)\"\n  assumes \"t' \\<in> set_pmf (mrbst_inter_diff b t1 t2)\" \"bst t1\" \"bst t2\"\n  shows   bst_mrbst_inter_diff: \"bst t'\"\n    and   set_mrbst_inter_diff: \"set_tree t' = setop (set_tree t1) (set_tree t2)\"\nproof -\n  write setop (infixl \"\\<diamondop>\" 80)\n  have \"bst t' \\<and> set_tree t' = set_tree t1 \\<diamondop> set_tree t2\"\n  using assms(2-)\n  proof (induction t1 arbitrary: t2 t')\n    case (Node l1 x r1 t2)\n    note bst = \\<open>bst \\<langle>l1, x, r1\\<rangle>\\<close> \\<open>bst t2\\<close>\n    define l2 r2 where \"l2 = fst (split_bst x t2)\" and \"r2 = snd (split_bst x t2)\"\n    obtain l r\n      where lr: \"l \\<in> set_pmf (mrbst_inter_diff b l1 l2)\" \"r \\<in> set_pmf (mrbst_inter_diff b r1 r2)\"\n        and t': \"t' \\<in> (if x \\<in> set_tree t2 \\<longleftrightarrow> b then {\\<langle>l, x, r\\<rangle>} else set_pmf (mrbst_join l r))\"\n      using Node.prems by (force simp: case_prod_unfold l2_def r2_def isin_bst split: if_splits)\n    from lr have lr': \"bst l \\<and> set_tree l = set_tree l1 \\<diamondop> set_tree l2\"\n                      \"bst r \\<and> set_tree r = set_tree r1 \\<diamondop> set_tree r2\"\n      using Node.prems by (intro Node.IH; force simp: l2_def r2_def)+\n\n    have \"set_tree t' = set_tree l \\<union> set_tree r \\<union> (if x \\<in> set_tree t2 \\<longleftrightarrow> b then {x} else {})\"\n    proof (cases \"x \\<in> set_tree t2 \\<longleftrightarrow> b\")\n      case False\n      have \"x < y\" if \"x \\<in> set_tree l\" \"y \\<in> set_tree r\" for x y\n        using that lr' bst by (force simp: setop_def split: if_splits)\n      hence set_t': \"set_tree t' = set_tree l \\<union> set_tree r\"\n        using t' set_mrbst_join[of t' l r] False lr' by auto\n      with False show ?thesis by simp\n    qed (use t' in auto)\n    also have \"\\<dots> = set_tree \\<langle>l1, x, r1\\<rangle> \\<diamondop> set_tree t2\"\n      using lr' bst by (auto simp: setop_def l2_def r2_def set_split_bst1 set_split_bst2)\n    finally have \"set_tree t' = set_tree \\<langle>l1, x, r1\\<rangle> \\<diamondop> set_tree t2\" .\n    moreover from lr' t' bst have \"bst t'\"\n      by (force split: if_splits simp: setop_def intro!: bst_mrbst_join[of t' l r])\n    ultimately show ?case by auto\n  qed (auto simp: setop_def)\n  thus \"bst t'\" and \"set_tree t' = set_tree t1 \\<diamondop> set_tree t2\" by auto\nqed\n\ntheorem mrbst_inter_diff_correct:\n  fixes A B :: \"'a :: linorder set\" and b :: bool\n  defines \"setop \\<equiv> (if b then (\\<inter>) else (-) :: 'a set \\<Rightarrow> _)\"\n  assumes \"finite A\" \"finite B\"\n  shows   \"do {t1 \\<leftarrow> random_bst A; t2 \\<leftarrow> random_bst B; mrbst_inter_diff b t1 t2} =\n             random_bst (setop A B)\"\n  using assms(2-)\nproof (induction A arbitrary: B rule: finite_psubset_induct)\n  case (psubset A B)\n  write setop (infixl \"\\<diamondop>\" 80)\n  include monad_normalisation\n  show ?case\n  proof (cases \"A = {}\")\n    case True\n    thus ?thesis by (auto simp: setop_def)\n  next\n    case False\n    define R1 R2 where \"R1 = (\\<lambda>x. random_bst {y\\<in>A. y < x})\" \"R2 = (\\<lambda>x. random_bst {y\\<in>A. y > x})\"\n\n    have A_eq: \"A = (A \\<inter> B) \\<union> (A - B)\" by auto\n    have card_A_eq: \"card A = card (A \\<inter> B) + card (A - B)\"\n      using \\<open>finite A\\<close> \\<open>finite B\\<close> by (subst A_eq, subst card_Un_disjoint) auto\n    have eq: \"pmf_of_set A =\n                do {b \\<leftarrow> bernoulli_pmf (card (A \\<inter> B) / card A);\n                    if b then pmf_of_set (A \\<inter> B) else pmf_of_set (A - B)}\"\n      using psubset.prems False \\<open>finite A\\<close> A_eq card_A_eq\n      by (subst A_eq, intro pmf_of_set_union_split [symmetric]) auto\n    have \"card A > 0\"\n      using \\<open>finite A\\<close> \\<open>A \\<noteq> {}\\<close> by (subst card_gt_0_iff) auto\n    have not_subset: \"\\<not>A \\<subseteq> B\" if \"card (A \\<inter> B) < card A\"\n    proof\n      assume \"A \\<subseteq> B\"\n      hence \"A \\<inter> B = A\" by auto\n      with that show False by simp\n    qed\n\n    have \"do {t1 \\<leftarrow> random_bst A; t2 \\<leftarrow> random_bst B; mrbst_inter_diff b t1 t2} =\n          do {\n            x \\<leftarrow> pmf_of_set A;\n            l1 \\<leftarrow> random_bst {y\\<in>A. y < x};\n            r1 \\<leftarrow> random_bst {y\\<in>A. y > x};\n            t2 \\<leftarrow> random_bst B;\n            let (l2, r2) = split_bst x t2;\n            l \\<leftarrow> mrbst_inter_diff b l1 l2;\n            r \\<leftarrow> mrbst_inter_diff b r1 r2;\n            if isin t2 x = b then return_pmf \\<langle>l, x, r\\<rangle> else mrbst_join l r\n          }\"\n      using \\<open>finite A\\<close> \\<open>A \\<noteq> {}\\<close>\n      by (subst random_bst_reduce)\n         (auto simp: mrbst_inter_diff_reduce map_pmf_def split_bst'_altdef)\n    also have \"\\<dots> = do {\n                      x \\<leftarrow> pmf_of_set A;\n                      l1 \\<leftarrow> random_bst {y\\<in>A. y < x};\n                      r1 \\<leftarrow> random_bst {y\\<in>A. y > x};\n                      t2 \\<leftarrow> random_bst B;\n                      let (l2, r2) = split_bst x t2;\n                      l \\<leftarrow> mrbst_inter_diff b l1 l2;\n                      r \\<leftarrow> mrbst_inter_diff b r1 r2;\n                      if x \\<in> B = b then return_pmf \\<langle>l, x, r\\<rangle> else mrbst_join l r\n                    }\"\n      unfolding Let_def case_prod_unfold using \\<open>finite B\\<close>\n      by (intro bind_pmf_cong refl) (auto simp: isin_random_bst)\n    also have \"\\<dots> = do {\n                      x \\<leftarrow> pmf_of_set A;\n                      l1 \\<leftarrow> random_bst {y\\<in>A. y < x};\n                      r1 \\<leftarrow> random_bst {y\\<in>A. y > x};\n                      (l2, r2) \\<leftarrow> map_pmf (split_bst x) (random_bst B);\n                      l \\<leftarrow> mrbst_inter_diff b l1 l2;\n                      r \\<leftarrow> mrbst_inter_diff b r1 r2;\n                      if x \\<in> B = b then return_pmf \\<langle>l, x, r\\<rangle> else mrbst_join l r\n                    }\"\n      by (simp add: Let_def map_pmf_def)\n    also have \"\\<dots> = do {\n                      x \\<leftarrow> pmf_of_set A;\n                      l1 \\<leftarrow> random_bst {y\\<in>A. y < x};\n                      r1 \\<leftarrow> random_bst {y\\<in>A. y > x};\n                      (l2, r2) \\<leftarrow> pair_pmf (random_bst {y\\<in>B. y < x}) (random_bst {y\\<in>B. y > x});\n                      l \\<leftarrow> mrbst_inter_diff b l1 l2;\n                      r \\<leftarrow> mrbst_inter_diff b r1 r2;\n                      if x \\<in> B = b then return_pmf \\<langle>l, x, r\\<rangle> else mrbst_join l r\n                    }\"\n      by (intro bind_pmf_cong refl split_random_bst \\<open>finite B\\<close>)\n    also have \"\\<dots> = do {\n                      x \\<leftarrow> pmf_of_set A;\n                      l1 \\<leftarrow> R1 x;\n                      r1 \\<leftarrow> R2 x;\n                      l2 \\<leftarrow> random_bst {y\\<in>B. y < x};\n                      r2 \\<leftarrow> random_bst {y\\<in>B. y > x};\n                      l \\<leftarrow> mrbst_inter_diff b l1 l2;\n                      r \\<leftarrow> mrbst_inter_diff b r1 r2;\n                      if x \\<in> B = b then return_pmf \\<langle>l, x, r\\<rangle> else mrbst_join l r\n                    }\"\n      unfolding pair_pmf_def bind_assoc_pmf R1_R2_def by simp\n    also have \"\\<dots> = do {\n                      x \\<leftarrow> pmf_of_set A;\n                      l \\<leftarrow> do {l1 \\<leftarrow> R1 x; l2 \\<leftarrow> random_bst {y\\<in>B. y < x}; mrbst_inter_diff b l1 l2};\n                      r \\<leftarrow> do {r1 \\<leftarrow> R2 x; r2 \\<leftarrow> random_bst {y\\<in>B. y > x}; mrbst_inter_diff b r1 r2};\n                      if x \\<in> B = b then return_pmf \\<langle>l, x, r\\<rangle> else mrbst_join l r\n                    }\"\n      unfolding bind_assoc_pmf by (intro bind_pmf_cong[OF refl]) simp\n    also have \"\\<dots> = do {\n                      x \\<leftarrow> pmf_of_set A;\n                      l \\<leftarrow> random_bst ({y\\<in>A. y < x} \\<diamondop> {y\\<in>B. y < x});\n                      r \\<leftarrow> random_bst ({y\\<in>A. y > x} \\<diamondop> {y\\<in>B. y > x});\n                      if x \\<in> B = b then return_pmf \\<langle>l, x, r\\<rangle> else mrbst_join l r\n                    }\"\n      using \\<open>finite A\\<close> \\<open>finite B\\<close> \\<open>A \\<noteq> {}\\<close> unfolding R1_R2_def\n      by (intro bind_pmf_cong refl psubset.IH) auto\n    also have \"\\<dots> = do {\n                      x \\<leftarrow> pmf_of_set A;\n                      if x \\<in> B = b then do {\n                        l \\<leftarrow> random_bst ({y\\<in>A. y < x} \\<diamondop> {y\\<in>B. y < x});\n                        r \\<leftarrow> random_bst ({y\\<in>A. y > x} \\<diamondop> {y\\<in>B. y > x});\n                        return_pmf \\<langle>l, x, r\\<rangle>\n                      } else do {\n                        l \\<leftarrow> random_bst ({y\\<in>A. y < x} \\<diamondop> {y\\<in>B. y < x});\n                        r \\<leftarrow> random_bst ({y\\<in>A. y > x} \\<diamondop> {y\\<in>B. y > x});\n                        mrbst_join l r\n                      }\n                    }\"\n      by simp\n    also have \"\\<dots> = do {\n                      x \\<leftarrow> pmf_of_set A;\n                      if x \\<in> B = b then do {\n                        l \\<leftarrow> random_bst ({y\\<in>A. y < x} \\<diamondop> {y\\<in>B. y < x});\n                        r \\<leftarrow> random_bst ({y\\<in>A. y > x} \\<diamondop> {y\\<in>B. y > x});\n                        return_pmf \\<langle>l, x, r\\<rangle>\n                      } else do {\n                        random_bst ({y\\<in>A. y < x} \\<diamondop> {y\\<in>B. y < x} \\<union> {y\\<in>A. y > x} \\<diamondop> {y\\<in>B. y > x})\n                      }\n                    }\"\n      using \\<open>finite A\\<close> \\<open>finite B\\<close>\n      by (intro bind_pmf_cong refl mrbst_join_correct if_cong) (auto simp: setop_def)\n    also have \"\\<dots> = do {\n                      x \\<leftarrow> pmf_of_set A;\n                      if x \\<in> B = b then do {\n                        l \\<leftarrow> random_bst ({y\\<in>A \\<diamondop> B. y < x});\n                        r \\<leftarrow> random_bst ({y\\<in>A \\<diamondop> B. y > x});\n                        return_pmf \\<langle>l, x, r\\<rangle>\n                      } else do {\n                        random_bst (A \\<diamondop> B)\n                      }\n                    }\" (is \"_ = pmf_of_set A \\<bind> ?f\")\n      using \\<open>finite A\\<close> \\<open>A \\<noteq> {}\\<close>\n      by (intro bind_pmf_cong refl if_cong arg_cong[of _ _ random_bst])\n         (auto simp: order.strict_iff_order setop_def)\n    also have \"\\<dots> = do {\n                      b' \\<leftarrow> bernoulli_pmf (card (A \\<inter> B) / card A);\n                      x \\<leftarrow> (if b' then pmf_of_set (A \\<inter> B) else pmf_of_set (A - B));\n                      if b' = b then do {\n                        l \\<leftarrow> random_bst ({y\\<in>A \\<diamondop> B. y < x});\n                        r \\<leftarrow> random_bst ({y\\<in>A \\<diamondop> B. y > x});\n                        return_pmf \\<langle>l, x, r\\<rangle>\n                      } else do {\n                        random_bst (A \\<diamondop> B)\n                      }\n                    }\"\n      unfolding bind_assoc_pmf eq using \\<open>card A > 0\\<close> \\<open>finite A\\<close> \\<open>finite B\\<close> not_subset\n      by (intro bind_pmf_cong refl if_cong)\n         (auto intro: bind_pmf_cong split: if_splits simp: divide_simps card_gt_0_iff\n               dest!: in_set_pmf_of_setD)\n    also have \"\\<dots> = do {\n                      b' \\<leftarrow> bernoulli_pmf (card (A \\<inter> B) / card A);\n                      if b' = b then do {\n                        x \\<leftarrow> pmf_of_set (A \\<diamondop> B);\n                        l \\<leftarrow> random_bst ({y\\<in>A \\<diamondop> B. y < x});\n                        r \\<leftarrow> random_bst ({y\\<in>A \\<diamondop> B. y > x});\n                        return_pmf \\<langle>l, x, r\\<rangle>\n                      } else do {\n                        random_bst (A \\<diamondop> B)\n                      }\n                    }\"\n      by (intro bind_pmf_cong) (auto simp: setop_def)\n    also have \"\\<dots> = do {\n                      b' \\<leftarrow> bernoulli_pmf (card (A \\<inter> B) / card A);\n                      if b' = b then do {\n                        random_bst (A \\<diamondop> B)\n                      } else do {\n                        random_bst (A \\<diamondop> B)\n                      }\n                    }\"\n      using \\<open>finite A\\<close> \\<open>finite B\\<close> \\<open>A \\<noteq> {}\\<close> not_subset \\<open>card A > 0\\<close>\n      by (intro bind_pmf_cong refl if_cong random_bst_reduce [symmetric])\n         (auto simp: setop_def field_simps)\n    also have \"\\<dots> = random_bst (A \\<diamondop> B)\" by simp\n    finally show ?thesis .\n  qed\nqed\n\n\ntext \\<open>\n  We now derive the intersection and difference from the generic operation:\n\\<close>\n\nfun mrbst_inter where\n  \"mrbst_inter \\<langle>\\<rangle> _ = return_pmf \\<langle>\\<rangle>\"\n| \"mrbst_inter \\<langle>l1, x, r1\\<rangle> t2 =\n     (case split_bst' x t2 of (sep, l2, r2) \\<Rightarrow>\n        do {\n          l \\<leftarrow> mrbst_inter l1 l2;\n          r \\<leftarrow> mrbst_inter r1 r2;\n          if sep then return_pmf \\<langle>l, x, r\\<rangle> else mrbst_join l r\n        })\"\n\nlemma mrbst_inter_Leaf_left [simp]:\n  \"mrbst_inter \\<langle>\\<rangle> = (\\<lambda>_. return_pmf \\<langle>\\<rangle>)\"\n  by (simp add: fun_eq_iff)\n\nlemma mrbst_inter_Leaf_right [simp]:\n  \"mrbst_inter (t1 :: 'a :: linorder tree) \\<langle>\\<rangle> = return_pmf \\<langle>\\<rangle>\"\n  by (induction t1) (auto simp: bind_return_pmf)\n\nlemma mrbst_inter_reduce:\n  \"mrbst_inter \\<langle>l1, x, r1\\<rangle> =\n     (\\<lambda>t2. case split_bst' x t2 of (sep, l2, r2) \\<Rightarrow>\n        do {\n           l \\<leftarrow> mrbst_inter l1 l2;\n           r \\<leftarrow> mrbst_inter r1 r2;\n           if sep then return_pmf \\<langle>l, x, r\\<rangle> else mrbst_join l r\n         })\"\n  by (rule ext) simp\n\nlemma mrbst_inter_altdef: \"mrbst_inter = mrbst_inter_diff True\"\nproof (intro ext)\n  fix t1 t2 :: \"'a tree\"\n  show \"mrbst_inter t1 t2 = mrbst_inter_diff True t1 t2\"\n    by (induction t1 arbitrary: t2) auto\nqed\n\ncorollary\n  fixes t1 t2 :: \"'a :: linorder tree\"\n  assumes \"t' \\<in> set_pmf (mrbst_inter t1 t2)\" \"bst t1\" \"bst t2\"\n  shows   bst_mrbst_inter: \"bst t'\"\n    and   set_mrbst_inter: \"set_tree t' = set_tree t1 \\<inter> set_tree t2\"\n  using bst_mrbst_inter_diff[of t' True t1 t2] set_mrbst_inter_diff[of t' True t1 t2] assms\n  by (simp_all add: mrbst_inter_altdef)\n\ncorollary mrbst_inter_correct:\n  fixes A B :: \"'a :: linorder set\"\n  assumes \"finite A\" \"finite B\"\n  shows   \"do {t1 \\<leftarrow> random_bst A; t2 \\<leftarrow> random_bst B; mrbst_inter t1 t2} = random_bst (A \\<inter> B)\"\n  using assms unfolding mrbst_inter_altdef by (subst mrbst_inter_diff_correct) simp_all\n\n\nfun mrbst_diff where\n  \"mrbst_diff \\<langle>\\<rangle> _ = return_pmf \\<langle>\\<rangle>\"\n| \"mrbst_diff \\<langle>l1, x, r1\\<rangle> t2 =\n     (case split_bst' x t2 of (sep, l2, r2) \\<Rightarrow>\n        do {\n          l \\<leftarrow> mrbst_diff l1 l2;\n          r \\<leftarrow> mrbst_diff r1 r2;\n          if sep then mrbst_join l r else return_pmf \\<langle>l, x, r\\<rangle>\n        })\"\n\nlemma mrbst_diff_Leaf_left [simp]:\n  \"mrbst_diff \\<langle>\\<rangle> = (\\<lambda>_. return_pmf \\<langle>\\<rangle>)\"\n  by (simp add: fun_eq_iff)\n\nlemma mrbst_diff_Leaf_right [simp]:\n  \"mrbst_diff (t1 :: 'a :: linorder tree) \\<langle>\\<rangle> = return_pmf t1\"\n  by (induction t1) (auto simp: bind_return_pmf)\n\nlemma mrbst_diff_reduce:\n  \"mrbst_diff \\<langle>l1, x, r1\\<rangle> =\n     (\\<lambda>t2. case split_bst' x t2 of (sep, l2, r2) \\<Rightarrow>\n        do {\n           l \\<leftarrow> mrbst_diff l1 l2;\n           r \\<leftarrow> mrbst_diff r1 r2;\n           if sep then mrbst_join l r else return_pmf \\<langle>l, x, r\\<rangle>\n         })\"\n  by (rule ext) simp\n\nlemma If_not: \"(if \\<not>b then x else y) = (if b then y else x)\"\n  by auto\n\nlemma mrbst_diff_altdef: \"mrbst_diff = mrbst_inter_diff False\"\nproof (intro ext)\n  fix t1 t2 :: \"'a tree\"\n  show \"mrbst_diff t1 t2 = mrbst_inter_diff False t1 t2\"\n    by (induction t1 arbitrary: t2) (auto simp: If_not)\nqed\n\ncorollary\n  fixes t1 t2 :: \"'a :: linorder tree\"\n  assumes \"t' \\<in> set_pmf (mrbst_diff t1 t2)\" \"bst t1\" \"bst t2\"\n  shows   bst_mrbst_diff: \"bst t'\"\n    and   set_mrbst_diff: \"set_tree t' = set_tree t1 - set_tree t2\"\n  using bst_mrbst_inter_diff[of t' False t1 t2] set_mrbst_inter_diff[of t' False t1 t2] assms\n  by (simp_all add: mrbst_diff_altdef)\n\ncorollary mrbst_diff_correct:\n  fixes A B :: \"'a :: linorder set\"\n  assumes \"finite A\" \"finite B\"\n  shows   \"do {t1 \\<leftarrow> random_bst A; t2 \\<leftarrow> random_bst B; mrbst_diff t1 t2} = random_bst (A - B)\"\n  using assms unfolding mrbst_diff_altdef by (subst mrbst_inter_diff_correct) simp_all\n\n\nsubsection \\<open>Union\\<close>\n\ntext \\<open>\n  The algorithm for the union of two trees is by far the most complicated one. It involves a \n\\<close>\n\n(*<*)\ncontext\n  notes\n    case_prod_unfold [termination_simp]\n    if_splits [split]\nbegin\n(*>*)\n\nfun mrbst_union where\n  \"mrbst_union \\<langle>\\<rangle> t2 = return_pmf t2\"\n| \"mrbst_union t1 \\<langle>\\<rangle> = return_pmf t1\"\n| \"mrbst_union \\<langle>l1, x, r1\\<rangle> \\<langle>l2, y, r2\\<rangle> =\n     do {\n       let m = size \\<langle>l1, x, r1\\<rangle>; let n = size \\<langle>l2, y, r2\\<rangle>;\n       b \\<leftarrow> bernoulli_pmf (m / (m + n));\n       if b then do {\n         let (l2', r2') = split_bst x \\<langle>l2, y, r2\\<rangle>;\n         l \\<leftarrow> mrbst_union l1 l2';\n         r \\<leftarrow> mrbst_union r1 r2';\n         return_pmf \\<langle>l, x, r\\<rangle>\n       } else do {\n         let (sep, l1', r1') = split_bst' y \\<langle>l1, x, r1\\<rangle>;\n         l \\<leftarrow> mrbst_union l1' l2;\n         r \\<leftarrow> mrbst_union r1' r2;\n         if sep then\n           mrbst_push_down l y r\n         else\n           return_pmf \\<langle>l, y, r\\<rangle>\n       }\n     }\"\n\n(*<*)\nend\n(*>*)\n\nlemma mrbst_union_Leaf_left [simp]: \"mrbst_union \\<langle>\\<rangle> = return_pmf\"\n  by (rule ext) simp\n\nlemma mrbst_union_Leaf_right [simp]: \"mrbst_union t1 \\<langle>\\<rangle> = return_pmf t1\"\n  by (cases t1) simp_all\n\nlemma\n  fixes t1 t2 :: \"'a :: linorder tree\" and b :: bool\n  assumes \"t' \\<in> set_pmf (mrbst_union t1 t2)\" \"bst t1\" \"bst t2\"\n  shows   bst_mrbst_union: \"bst t'\"\n    and   set_mrbst_union: \"set_tree t' = set_tree t1 \\<union> set_tree t2\"\nproof -\n  have \"bst t' \\<and> set_tree t' = set_tree t1 \\<union> set_tree t2\"\n  using assms\n  proof (induction \"size t1 + size t2\" arbitrary: t1 t2 t' rule: less_induct)\n    case (less t1 t2 t')\n    show ?case\n    proof (cases \"t1 = \\<langle>\\<rangle> \\<or> t2 = \\<langle>\\<rangle>\")\n      case False\n      then obtain l1 x r1 l2 y r2 where t1: \"t1 = \\<langle>l1, x, r1\\<rangle>\" and t2: \"t2 = \\<langle>l2, y, r2\\<rangle>\"\n        by (cases t1; cases t2) auto\n      from less.prems consider l r where\n        \"l \\<in> set_pmf (mrbst_union l1 (fst (split_bst x t2)))\"\n        \"r \\<in> set_pmf (mrbst_union r1 (snd (split_bst x t2)))\"\n        \"t' = \\<langle>l, x, r\\<rangle>\"\n      | l r where\n        \"l \\<in> set_pmf (mrbst_union (fst (split_bst y t1)) l2)\"\n        \"r \\<in> set_pmf (mrbst_union (snd (split_bst y t1)) r2)\"\n        \"t' \\<in> (if isin \\<langle>l1, x, r1\\<rangle> y then set_pmf (mrbst_push_down l y r) else {\\<langle>l, y, r\\<rangle>})\"\n        by (auto simp: case_prod_unfold t1 t2 Let_def\n                 simp del: split_bst.simps split_bst'.simps isin.simps split: if_splits)\n      thus ?thesis\n      proof cases\n        case 1\n        hence lr: \"bst l \\<and> set_tree l = set_tree l1 \\<union> set_tree (fst (split_bst x t2))\"\n                  \"bst r \\<and> set_tree r = set_tree r1 \\<union> set_tree (snd (split_bst x t2))\"\n          using less.prems size_split_bst[of x t2]\n          by (intro less; force simp: t1)+\n        thus ?thesis\n          using 1 less.prems by (auto simp: t1 set_split_bst1 set_split_bst2)\n      next\n        case 2\n        hence lr: \"bst l \\<and> set_tree l = set_tree (fst (split_bst y t1)) \\<union> set_tree l2\"\n                  \"bst r \\<and> set_tree r = set_tree (snd (split_bst y t1)) \\<union> set_tree r2\"\n          using less.prems size_split_bst[of y t1]\n          by (intro less; force simp: t2)+\n        show ?thesis\n        proof (cases \"isin \\<langle>l1, x, r1\\<rangle> y\")\n          case False\n          thus ?thesis using 2 less.prems lr\n            by (auto simp del: isin.simps simp: t2 set_split_bst1 set_split_bst2)\n        next\n          case True\n          have bst': \"\\<forall>z\\<in>set_tree l. z < y\" \"\\<forall>z\\<in>set_tree r. z > y\"\n            using lr less.prems by (auto simp: set_split_bst1 set_split_bst2 t2)\n          from True and 2 have t': \"t' \\<in> set_pmf (mrbst_push_down l y r)\"\n            by (auto simp del: isin.simps)\n          from t' have \"bst t'\"\n            by (rule bst_mrbst_push_down) (use lr bst' in auto)\n          moreover from t' have \"set_tree t' = {y} \\<union> set_tree l \\<union> set_tree r\"\n            by (rule set_mrbst_push_down) (use lr bst' in auto)\n          ultimately show ?thesis using less.prems lr\n            by (auto simp del: isin.simps simp: t2 set_split_bst1 set_split_bst2)\n        qed\n      qed\n    qed (use less.prems in auto)\n  qed\n  thus \"bst t'\" and \"set_tree t' = set_tree t1 \\<union> set_tree t2\" by auto\nqed\n\n\n\n      have \"B - A = B - (A \\<inter> B)\" by auto\n      also have \"card \\<dots> = n - l\"\n        using AB unfolding n_def l_def by (intro card_Diff_subset) auto\n      finally have [simp]: \"card (B - A) = n - l\" .\n      from AB have \"l \\<le> n\" unfolding l_def n_def by (intro card_mono) auto\n\n      have \"p \\<le> 1 - (1 - p) * q\"\n        using mn \\<open>l \\<le> n\\<close> by (auto simp: p_def q_def divide_simps)\n      hence r_aux: \"(1 - p) * q \\<in> {0..1 - p}\"\n        using pq by auto\n\n      include monad_normalisation\n      define RA1 RA2 RB1 RB2\n        where \"RA1 = (\\<lambda>x. random_bst {z\\<in>A. z < x})\" and \"RA2 = (\\<lambda>x. random_bst {z\\<in>A. z > x})\"\n          and \"RB1 = (\\<lambda>x. random_bst {z\\<in>B. z < x})\" and \"RB2 = (\\<lambda>x. random_bst {z\\<in>B. z > x})\"\n\n      have \"do {t1 \\<leftarrow> random_bst A; t2 \\<leftarrow> random_bst B; mrbst_union t1 t2} =\n              do {\n                x \\<leftarrow> pmf_of_set A;\n                l1 \\<leftarrow> random_bst {z\\<in>A. z < x};\n                r1 \\<leftarrow> random_bst {z\\<in>A. z > x};\n                y \\<leftarrow> pmf_of_set B;\n                l2 \\<leftarrow> random_bst {z\\<in>B. z < y};\n                r2 \\<leftarrow> random_bst {z\\<in>B. z > y};\n                let m = size \\<langle>l1, x, r1\\<rangle>;\n                let n = size \\<langle>l2, y, r2\\<rangle>;\n                b \\<leftarrow> bernoulli_pmf (m / (m + n));\n                if b then do {\n                  l \\<leftarrow> mrbst_union l1 (fst (split_bst x \\<langle>l2, y, r2\\<rangle>));\n                  r \\<leftarrow> mrbst_union r1 (snd (split_bst x \\<langle>l2, y, r2\\<rangle>));\n                  return_pmf \\<langle>l, x, r\\<rangle>\n                } else do {\n                  l \\<leftarrow> mrbst_union (fst (split_bst y \\<langle>l1, x, r1\\<rangle>)) l2;\n                  r \\<leftarrow> mrbst_union (snd (split_bst y \\<langle>l1, x, r1\\<rangle>)) r2;\n                  if isin \\<langle>l1, x, r1\\<rangle> y then\n                    mrbst_push_down l y r\n                  else\n                    return_pmf \\<langle>l, y, r\\<rangle>\n                }\n              }\" using AB\n        by (simp add: random_bst_reduce split_bst'_altdef Let_def case_prod_unfold cong: if_cong)\n      also have \"\\<dots> = do {\n                        x \\<leftarrow> pmf_of_set A;\n                        l1 \\<leftarrow> random_bst {z\\<in>A. z < x};\n                        r1 \\<leftarrow> random_bst {z\\<in>A. z > x};\n                        y \\<leftarrow> pmf_of_set B;\n                        l2 \\<leftarrow> random_bst {z\\<in>B. z < y};\n                        r2 \\<leftarrow> random_bst {z\\<in>B. z > y};\n                        b \\<leftarrow> bernoulli_pmf p;\n                        if b then do {\n                          l \\<leftarrow> mrbst_union l1 (fst (split_bst x \\<langle>l2, y, r2\\<rangle>));\n                          r \\<leftarrow> mrbst_union r1 (snd (split_bst x \\<langle>l2, y, r2\\<rangle>));\n                          return_pmf \\<langle>l, x, r\\<rangle>\n                        } else do {\n                          l \\<leftarrow> mrbst_union (fst (split_bst y \\<langle>l1, x, r1\\<rangle>)) l2;\n                          r \\<leftarrow> mrbst_union (snd (split_bst y \\<langle>l1, x, r1\\<rangle>)) r2;\n                          if y \\<in> A then\n                            mrbst_push_down l y r\n                          else\n                            return_pmf \\<langle>l, y, r\\<rangle>\n                        }\n                      }\"\n        unfolding Let_def\n      proof (intro bind_pmf_cong refl if_cong)\n        fix l1 x r1 y\n        assume \"l1 \\<in> set_pmf (random_bst {z\\<in>A. z < x})\" \"r1 \\<in> set_pmf (random_bst {z\\<in>A. z > x})\"\n               \"x \\<in> set_pmf (pmf_of_set A)\"\n        thus \"isin \\<langle>l1, x, r1\\<rangle> y \\<longleftrightarrow> (y \\<in> A)\"\n          using AB by (subst isin_bst) (auto simp: bst_random_bst set_random_bst)\n      qed (insert AB,\n           auto simp: size_random_bst m_def n_def p_def isin_random_bst dest!: card_3way_split)\n      also have \"\\<dots> = do {\n                        b \\<leftarrow> bernoulli_pmf p;\n                        if b then do {\n                          x \\<leftarrow> pmf_of_set A;\n                          (l1, r1) \\<leftarrow> pair_pmf (random_bst {z\\<in>A. z < x}) (random_bst {z\\<in>A. z > x});\n                          (l2, r2) \\<leftarrow> map_pmf (split_bst x) (random_bst B);\n                          l \\<leftarrow> mrbst_union l1 l2;\n                          r \\<leftarrow> mrbst_union r1 r2;\n                          return_pmf \\<langle>l, x, r\\<rangle>\n                        } else do {\n                          y \\<leftarrow> pmf_of_set B;\n                          (l1, r1) \\<leftarrow> map_pmf (split_bst y) (random_bst A);\n                          (l2, r2) \\<leftarrow> pair_pmf (random_bst {z\\<in>B. z < y}) (random_bst {z\\<in>B. z > y});\n                          l \\<leftarrow> mrbst_union l1 l2;\n                          r \\<leftarrow> mrbst_union r1 r2;\n                          if y \\<in> A then\n                            mrbst_push_down l y r\n                          else\n                            return_pmf \\<langle>l, y, r\\<rangle>\n                        }\n                      }\" using AB\n        by (simp add: random_bst_reduce map_pmf_def case_prod_unfold pair_pmf_def cong: if_cong)\n      also have \"\\<dots> = do {\n                        b \\<leftarrow> bernoulli_pmf p;\n                        if b then do {\n                          x \\<leftarrow> pmf_of_set A;\n                          (l1, r1) \\<leftarrow> pair_pmf (RA1 x) (RA2 x);\n                          (l2, r2) \\<leftarrow> pair_pmf (RB1 x) (RB2 x);\n                          l \\<leftarrow> mrbst_union l1 l2;\n                          r \\<leftarrow> mrbst_union r1 r2;\n                          return_pmf \\<langle>l, x, r\\<rangle>\n                        } else do {\n                          y \\<leftarrow> pmf_of_set B;\n                          (l1, r1) \\<leftarrow> pair_pmf (RA1 y) (RA2 y);\n                          (l2, r2) \\<leftarrow> pair_pmf (RB1 y) (RB2 y);\n                          l \\<leftarrow> mrbst_union l1 l2;\n                          r \\<leftarrow> mrbst_union r1 r2;\n                          if y \\<in> A then\n                            mrbst_push_down l y r\n                          else\n                            return_pmf \\<langle>l, y, r\\<rangle>\n                        }\n                      }\"\n        unfolding case_prod_unfold RA1_def RA2_def RB1_def RB2_def\n        by (intro bind_pmf_cong refl if_cong split_random_bst AB)\n      also have \"\\<dots> = do {\n                        b \\<leftarrow> bernoulli_pmf p;\n                        if b then do {\n                          x \\<leftarrow> pmf_of_set A;\n                          l \\<leftarrow> do {l1 \\<leftarrow> RA1 x; l2 \\<leftarrow> RB1 x; mrbst_union l1 l2};\n                          r \\<leftarrow> do {r1 \\<leftarrow> RA2 x; r2 \\<leftarrow> RB2 x; mrbst_union r1 r2};\n                          return_pmf \\<langle>l, x, r\\<rangle>\n                        } else do {\n                          y \\<leftarrow> pmf_of_set B;\n                          l \\<leftarrow> do {l1 \\<leftarrow> RA1 y; l2 \\<leftarrow> RB1 y; mrbst_union l1 l2};\n                          r \\<leftarrow> do {r1 \\<leftarrow> RA2 y; r2 \\<leftarrow> RB2 y; mrbst_union r1 r2};\n                          if y \\<in> A then\n                            mrbst_push_down l y r\n                          else\n                            return_pmf \\<langle>l, y, r\\<rangle>\n                        }\n                      }\"\n        by (simp add: pair_pmf_def cong: if_cong)\n      also have \"\\<dots> = do {\n                        b \\<leftarrow> bernoulli_pmf p;\n                        if b then do {\n                          x \\<leftarrow> pmf_of_set A;\n                          l \\<leftarrow> random_bst ({z\\<in>A. z < x} \\<union> {z\\<in>B. z < x});\n                          r \\<leftarrow> random_bst ({z\\<in>A. z > x} \\<union> {z\\<in>B. z > x});\n                          return_pmf \\<langle>l, x, r\\<rangle>\n                        } else do {\n                          y \\<leftarrow> pmf_of_set B;\n                          l \\<leftarrow> random_bst ({z\\<in>A. z < y} \\<union> {z\\<in>B. z < y});\n                          r \\<leftarrow> random_bst ({z\\<in>A. z > y} \\<union> {z\\<in>B. z > y});\n                          if y \\<in> A then\n                            mrbst_push_down l y r\n                          else\n                            return_pmf \\<langle>l, y, r\\<rangle>\n                        }\n                      }\"\n        unfolding RA1_def RA2_def RB1_def RB2_def using AB\n        by (intro bind_pmf_cong if_cong refl psubset) auto\n      also have \"\\<dots> = do {\n                        b \\<leftarrow> bernoulli_pmf p;\n                        if b then do {\n                          x \\<leftarrow> pmf_of_set A;\n                          l \\<leftarrow> random_bst {z\\<in>A \\<union> B. z < x};\n                          r \\<leftarrow> random_bst {z\\<in>A \\<union> B. z > x};\n                          return_pmf \\<langle>l, x, r\\<rangle>\n                        } else do {\n                          y \\<leftarrow> pmf_of_set B;\n                          l \\<leftarrow> random_bst {z\\<in>A \\<union> B. z < y};\n                          r \\<leftarrow> random_bst {z\\<in>A \\<union> B. z > y};\n                          if y \\<in> A then\n                            mrbst_push_down l y r\n                          else\n                            return_pmf \\<langle>l, y, r\\<rangle>\n                        }\n                      }\"\n        by (intro bind_pmf_cong if_cong refl arg_cong[of _ _ random_bst]) auto\n      also have \"\\<dots> = do {\n                        b \\<leftarrow> bernoulli_pmf p;\n                        if b then do {\n                          x \\<leftarrow> pmf_of_set A;\n                          l \\<leftarrow> random_bst {z\\<in>A \\<union> B. z < x};\n                          r \\<leftarrow> random_bst {z\\<in>A \\<union> B. z > x};\n                          return_pmf \\<langle>l, x, r\\<rangle>\n                        } else do {\n                          b' \\<leftarrow> bernoulli_pmf q;\n                          if b' then do {\n                            y \\<leftarrow> pmf_of_set (A \\<inter> B);\n                            random_bst (A \\<union> B)\n                          } else do {\n                            y \\<leftarrow> pmf_of_set (B - A);\n                            l \\<leftarrow> random_bst {z\\<in>A \\<union> B. z < y};\n                            r \\<leftarrow> random_bst {z\\<in>A \\<union> B. z > y};\n                            return_pmf \\<langle>l, y, r\\<rangle>\n                          }\n                        }\n                      }\"\n      proof (intro bind_pmf_cong refl if_cong, goal_cases)\n        case (1 b)\n        have q_pos: \"A \\<inter> B \\<noteq> {}\" if \"q > 0\" using that by (auto simp: q_def l_def)\n        have q_lt1: \"B - A \\<noteq> {}\" if \"q < 1\"\n        proof\n          assume \"B - A = {}\"\n          hence \"A \\<inter> B = B\" by auto\n          thus False using that AB by (auto simp: q_def l_def n_def)\n        qed\n\n        have eq: \"pmf_of_set B = do {b' \\<leftarrow> bernoulli_pmf q;\n                                     if b' then pmf_of_set (A \\<inter> B) else pmf_of_set (B - A)}\"\n          using AB by (intro pmf_of_set_split_inter_diff [symmetric])\n                      (auto simp: q_def l_def n_def)\n        have \"do {y \\<leftarrow> pmf_of_set B;\n                  l \\<leftarrow> random_bst {z\\<in>A \\<union> B. z < y};\n                  r \\<leftarrow> random_bst {z\\<in>A \\<union> B. z > y};\n                  if y \\<in> A then\n                    mrbst_push_down l y r\n                  else\n                    return_pmf \\<langle>l, y, r\\<rangle>\n                 } =\n              do {\n                b' \\<leftarrow> bernoulli_pmf q;\n                y \\<leftarrow> (if b' then pmf_of_set (A \\<inter> B) else pmf_of_set (B - A));\n                l \\<leftarrow> random_bst {z\\<in>A \\<union> B. z < y};\n                r \\<leftarrow> random_bst {z\\<in>A \\<union> B. z > y};\n                if b' then\n                  mrbst_push_down l y r\n                else\n                  return_pmf \\<langle>l, y, r\\<rangle>\n              }\" unfolding eq bind_assoc_pmf using AB q_pos q_lt1\n          by (intro bind_pmf_cong refl if_cong) (auto split: if_splits)\n        also have \"\\<dots> = do {\n                          b' \\<leftarrow> bernoulli_pmf q;\n                          if b' then do {\n                            y \\<leftarrow> pmf_of_set (A \\<inter> B);\n                            do {l \\<leftarrow> random_bst {z\\<in>A \\<union> B. z < y};\n                                r \\<leftarrow> random_bst {z\\<in>A \\<union> B. z > y};\n                                mrbst_push_down l y r}\n                          } else do {\n                            y \\<leftarrow> pmf_of_set (B - A);\n                            l \\<leftarrow> random_bst {z\\<in>A \\<union> B. z < y};\n                            r \\<leftarrow> random_bst {z\\<in>A \\<union> B. z > y};\n                            return_pmf \\<langle>l, y, r\\<rangle>\n                          }\n                        }\" by (simp cong: if_cong)\n        also have \"\\<dots> = do {\n                          b' \\<leftarrow> bernoulli_pmf q;\n                          if b' then do {\n                            y \\<leftarrow> pmf_of_set (A \\<inter> B);\n                            random_bst (A \\<union> B)\n                          } else do {\n                            y \\<leftarrow> pmf_of_set (B - A);\n                            l \\<leftarrow> random_bst {z\\<in>A \\<union> B. z < y};\n                            r \\<leftarrow> random_bst {z\\<in>A \\<union> B. z > y};\n                            return_pmf \\<langle>l, y, r\\<rangle>\n                          }\n                        }\"\n          using AB q_pos by (intro bind_pmf_cong if_cong refl mrbst_push_down_correct') auto\n        finally show ?case .\n      qed\n      also have \"\\<dots> = do {\n                        b \\<leftarrow> bernoulli_pmf p;\n                        b' \\<leftarrow> bernoulli_pmf q;\n                        if b then do {\n                          x \\<leftarrow> pmf_of_set A;\n                          l \\<leftarrow> random_bst {z\\<in>A \\<union> B. z < x};\n                          r \\<leftarrow> random_bst {z\\<in>A \\<union> B. z > x};\n                          return_pmf \\<langle>l, x, r\\<rangle>\n                        } else if b' then do {\n                            random_bst (A \\<union> B)\n                        } else do {\n                          y \\<leftarrow> pmf_of_set (B - A);\n                          l \\<leftarrow> random_bst {z\\<in>A \\<union> B. z < y};\n                          r \\<leftarrow> random_bst {z\\<in>A \\<union> B. z > y};\n                          return_pmf \\<langle>l, y, r\\<rangle>\n                        }\n                      }\"\n        by (simp cong: if_cong)\n      also have \"\\<dots> = do {\n                        (b, b') \\<leftarrow> pair_pmf (bernoulli_pmf p) (bernoulli_pmf q);\n                        if b \\<or> \\<not>b' then do {\n                          x \\<leftarrow> (if b then pmf_of_set A else pmf_of_set (B - A));\n                          l \\<leftarrow> random_bst {z\\<in>A \\<union> B. z < x};\n                          r \\<leftarrow> random_bst {z\\<in>A \\<union> B. z > x};\n                          return_pmf \\<langle>l, x, r\\<rangle>\n                        } else do {\n                            random_bst (A \\<union> B)\n                        }\n                      }\" unfolding pair_pmf_def bind_assoc_pmf\n        by (intro bind_pmf_cong) auto\n      also have \"\\<dots> = do {\n                        (b, b') \\<leftarrow> map_pmf (\\<lambda>(b, b'). (b \\<or> \\<not>b', b))\n                                    (pair_pmf (bernoulli_pmf p) (bernoulli_pmf q));\n                        if b then do {\n                          x \\<leftarrow> (if b' then pmf_of_set A else pmf_of_set (B - A));\n                          l \\<leftarrow> random_bst {z\\<in>A \\<union> B. z < x};\n                          r \\<leftarrow> random_bst {z\\<in>A \\<union> B. z > x};\n                          return_pmf \\<langle>l, x, r\\<rangle>\n                        } else do {\n                            random_bst (A \\<union> B)\n                        }\n                      }\" (is \"_ = bind_pmf _ ?f\")\n        by (simp add: bind_map_pmf case_prod_unfold cong: if_cong)\n      also have \"map_pmf (\\<lambda>(b, b'). (b \\<or> \\<not>b', b))\n                   (pair_pmf (bernoulli_pmf p) (bernoulli_pmf q)) =\n                 do {\n                   b \\<leftarrow> bernoulli_pmf (1 - (1 - p) * q);\n                   b' \\<leftarrow> (if b then bernoulli_pmf r else return_pmf False);\n                   return_pmf (b, b')\n                 }\" (is \"?lhs = ?rhs\")\n      proof (intro pmf_eqI)\n        fix bb' :: \"bool \\<times> bool\" \n        obtain b b' where [simp]: \"bb' = (b, b')\" by (cases bb')\n        thus \"pmf ?lhs bb' = pmf ?rhs bb'\"\n          using pq r_aux \\<open>p > 0\\<close>\n          by (cases b; cases b')\n             (auto simp: pmf_map pmf_bind_bernoulli measure_measure_pmf_finite \n                         vimage_bool_pair pmf_pair r_def field_simps)\n      qed\n      also have \"\\<dots> \\<bind> ?f = do {\n                              b \\<leftarrow> bernoulli_pmf (1 - (1 - p) * q);\n                              if b then do {\n                                x \\<leftarrow> do {b' \\<leftarrow> bernoulli_pmf r;\n                                         if b' then pmf_of_set A else pmf_of_set (B - A)};\n                                l \\<leftarrow> random_bst {z\\<in>A \\<union> B. z < x};\n                                r \\<leftarrow> random_bst {z\\<in>A \\<union> B. z > x};\n                                return_pmf \\<langle>l, x, r\\<rangle>\n                              } else do {\n                                random_bst (A \\<union> B)\n                              }\n                            }\"\n        by (simp cong: if_cong)\n      also have \"\\<dots> = do {\n                        b \\<leftarrow> bernoulli_pmf (1 - (1 - p) * q);\n                        if b then do {\n                          x \\<leftarrow> pmf_of_set (A \\<union> (B - A));\n                          l \\<leftarrow> random_bst {z\\<in>A \\<union> B. z < x};\n                          r \\<leftarrow> random_bst {z\\<in>A \\<union> B. z > x};\n                          return_pmf \\<langle>l, x, r\\<rangle>\n                        } else do {\n                          random_bst (A \\<union> B)\n                        }\n                      }\" (is \"_ = ?f (A \\<union> (B - A))\")\n        using AB pq \\<open>l \\<le> n\\<close> mn\n        by (intro bind_pmf_cong if_cong refl pmf_of_set_union_split)\n           (auto simp: m_def [symmetric] n_def [symmetric] r_def p_def q_def divide_simps)\n      also have \"A \\<union> (B - A) = A \\<union> B\" by auto\n      also have \"?f \\<dots> = random_bst (A \\<union> B)\"\n        using AB by (simp add: random_bst_reduce cong: if_cong)\n      finally show ?thesis .\n    qed\n  qed\nqed\n\n\nsubsection \\<open>Insertion and Deletion\\<close>\n\ntext \\<open>\n  The insertion and deletion operations are simple special cases of the union\n  and difference operations where one of the trees is a singleton tree.\n\\<close>\nfun mrbst_insert where\n  \"mrbst_insert x \\<langle>\\<rangle> = return_pmf \\<langle>\\<langle>\\<rangle>, x, \\<langle>\\<rangle>\\<rangle>\"\n| \"mrbst_insert x \\<langle>l, y, r\\<rangle> =\n     do {\n       b \\<leftarrow> bernoulli_pmf (1 / real (size l + size r + 2));\n       if b then do {\n         let (l', r') = split_bst x \\<langle>l, y, r\\<rangle>;\n         return_pmf \\<langle>l', x, r'\\<rangle>\n       } else if x < y then do {\n         map_pmf (\\<lambda>l'. \\<langle>l', y, r\\<rangle>) (mrbst_insert x l)\n       } else if x > y then do {\n         map_pmf (\\<lambda>r'. \\<langle>l, y, r'\\<rangle>) (mrbst_insert x r)\n       } else do {\n         mrbst_push_down l y r\n       }\n     }\"\n\nlemma mrbst_insert_altdef: \"mrbst_insert x t = mrbst_union \\<langle>\\<langle>\\<rangle>, x, \\<langle>\\<rangle>\\<rangle> t\"\n  by (induction x t rule: mrbst_insert.induct)\n     (simp_all add: Let_def map_pmf_def bind_return_pmf case_prod_unfold cong: if_cong)\n\ncorollary\n  fixes t :: \"'a :: linorder tree\"\n  assumes \"t' \\<in> set_pmf (mrbst_insert x t)\" \"bst t\"\n  shows   bst_mrbst_insert: \"bst t'\"\n    and   set_mrbst_insert: \"set_tree t' = insert x (set_tree t)\"\n  using bst_mrbst_union[of t' \"\\<langle>\\<langle>\\<rangle>, x, \\<langle>\\<rangle>\\<rangle>\" t] set_mrbst_union[of t' \"\\<langle>\\<langle>\\<rangle>, x, \\<langle>\\<rangle>\\<rangle>\" t] assms\n  by (simp_all add: mrbst_insert_altdef)\n\ncorollary mrbst_insert_correct:\n  assumes \"finite A\"\n  shows   \"random_bst A \\<bind> mrbst_insert x = random_bst (insert x A)\"\n  using mrbst_union_correct[of \"{x}\" A] assms\n  by (simp add: mrbst_insert_altdef[abs_def] bind_return_pmf)\n\n\nfun mrbst_delete :: \"'a :: ord \\<Rightarrow> 'a tree \\<Rightarrow> 'a tree pmf\" where\n  \"mrbst_delete x \\<langle>\\<rangle> = return_pmf \\<langle>\\<rangle>\"\n| \"mrbst_delete x \\<langle>l, y, r\\<rangle> = (\n     if x < y then\n       map_pmf (\\<lambda>l'. \\<langle>l', y, r\\<rangle>) (mrbst_delete x l)\n     else if x > y then\n       map_pmf (\\<lambda>r'. \\<langle>l, y, r'\\<rangle>) (mrbst_delete x r)\n     else \n       mrbst_join l r)\"\n\nlemma mrbst_delete_altdef: \"mrbst_delete x t = mrbst_diff t \\<langle>\\<langle>\\<rangle>, x, \\<langle>\\<rangle>\\<rangle>\"\n  by (induction t) (auto simp: bind_return_pmf map_pmf_def)\n\ncorollary\n  fixes t :: \"'a :: linorder tree\"\n  assumes \"t' \\<in> set_pmf (mrbst_delete x t)\" \"bst t\"\n  shows   bst_mrbst_delete: \"bst t'\"\n    and   set_mrbst_delete: \"set_tree t' = set_tree t - {x}\"\n  using bst_mrbst_diff[of t' t \"\\<langle>\\<langle>\\<rangle>, x, \\<langle>\\<rangle>\\<rangle>\"] set_mrbst_diff[of t' t \"\\<langle>\\<langle>\\<rangle>, x, \\<langle>\\<rangle>\\<rangle>\"] assms\n  by (simp_all add: mrbst_delete_altdef)\n\ncorollary mrbst_delete_correct:\n  \"finite A \\<Longrightarrow> do {t \\<leftarrow> random_bst A; mrbst_delete x t} = random_bst (A - {x})\"\n  using mrbst_diff_correct[of A \"{x}\"] by (simp add: mrbst_delete_altdef bind_return_pmf)\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/Randomised_BSTs/Randomised_BSTs.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8128673223709251, "lm_q2_score": 0.8670357598021707, "lm_q1q2_score": 0.704785036470231}}
{"text": "section \"Binomial Heaps\"\n\ntheory BinomialHeap\nimports Main \"HOL-Library.Multiset\"\nbegin\n\nlocale BinomialHeapStruc_loc\nbegin\n\nsubsection \\<open>Datatype Definition\\<close>\n\ntext \\<open>Binomial heaps are lists of binomial trees.\\<close>\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 \\<open>Combine two binomial trees (of rank $r$) to one (of rank $r+1$).\\<close>\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 \\<open>Return a multiset with all (element, priority) pairs from a queue.\\<close>\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 \\<open>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\\<close>\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 \\<open>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\\<close>\n\ntext \\<open>First part: All trees of the queue satisfy the tree invariant:\\<close>\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 \\<open>Second part: Trees have distinct rank, and are ordered by \n  ascending rank:\\<close>\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 \\<open>Invariant for binomial queues:\\<close>\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)\n  case 0\n  then show ?case by simp\nnext\n  case (Suc r)\n  from Suc(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 Suc(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 Suc(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)\n  case Nil\n  then show ?case by (simp add: invar_def)\nnext\n  case (Cons a bq)\n  from \\<open>invar (a # bq)\\<close> have \"invar bq\" by (rule invar_cons_down)\n  with Cons have \"invar (bq @ [t'])\" by simp\n  with Cons show ?case by (cases bq) (simp_all add: invar_def)\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_mset(queue_to_multiset ts). a \\<le> snd x)\"\n\ntext \\<open>The invariant for trees implies heap order.\\<close>\nlemma tree_invar_heap_ordered:\n  assumes \"tree_invar t\"\n  shows \"heap_ordered t\"\nproof (cases t)\n  case (Node e a nat list)\n  with assms show ?thesis\n  proof (induct nat arbitrary: t e a list)\n    case 0\n    then show ?case by simp\n  next\n    case (Suc nat t)\n    then 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 Suc(1)[OF O(1) t1] Suc(1)[OF O(2) t2]\n    show ?case by (cases \"a1 \\<le> a2\") auto\n  qed\nqed\n\nsubsubsection \"Height and Length\"\ntext \\<open>\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\\<close>\n\ntext \\<open>Height of a tree and queue\\<close>\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\n  done\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\"\nproof (induct r arbitrary: e a ts)\n  case 0\n  then show ?case by simp\nnext\n  case (Suc r)\n  from Suc(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    Suc(1)[OF inv1] Suc(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\"\nproof (induct r arbitrary: e a ts)\n  case 0\n  then show ?case by simp\nnext\n  case (Suc r)\n  from Suc(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 Suc(1)[OF inv1] Suc(1)[OF inv2] Suc(2) show ?case\n    by (cases \"a1 \\<le> a2\") simp_all\nqed\n\ntext \\<open>A binomial tree of height $h$ contains exactly $2^{h}$ elements\\<close>\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  by (cases t) (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 [simp]: (Cons xxs xx)\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_sum_list: \n  \"size (queue_to_multiset bq) = sum_list (map (size \\<circ> tree_to_multiset) bq)\"\n  by (induct bq) simp_all\n\ntext \\<open>\n  A binomial heap of length $l$ contains at least $2^l - 1$ elements. \n\\<close>\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_sum_list)\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::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::nat) ^ length (xs @ [x]) = (2::nat) ^ (length xs) + (2::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 \\<open>Operations\\<close>\n\nsubsubsection \"Empty\"\nlemma empty_correct[simp]: \n  \"invar Nil\"\n  \"queue_to_multiset Nil = {#}\"\n  by (simp_all add: invar_def)\n  \ntext \\<open>The empty multiset is represented by exactly the empty queue\\<close>\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 \\<open>Inserts a binomial tree into a binomial queue, such that the queue \n  does not contain two trees of same rank.\\<close>\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 \\<open>Inserts an element with priority into the queue.\\<close>\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: \"queue_invar q \\<Longrightarrow>\n  queue_to_multiset (insert e a q) = queue_to_multiset q + {# (e,a) #}\"\nby(simp add: ins_mset union_ac insert_def)\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 [simp]: True\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 \\<open>tree_invar t\\<close> 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'))\"\n  apply(auto)\n  apply(induct bq arbitrary: t t')\n  apply(simp add: rank_link)\nproof goal_cases\n  case prems: (1 a bq t t')\n  thus ?case\n    apply(cases \"rank (link t' t) = rank a\")\n    apply(auto simp add: rank_link)\n  proof goal_cases\n    case 1\n    note * = this and \\<open>\\<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))\\<close>[of a \"(link t' t)\"] \n    show ?case\n    proof (cases \"rank (hd (ins (link (link t' t) a) bq)) = rank a\")\n      case True\n      with * show ?thesis by simp\n    next\n      case False\n      with * have \"rank a \\<le> rank (hd (ins (link (link t' t) a) bq))\" \n        by (simp add: rank_link)\n      with * show ?thesis 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> [])\"\n  apply(induct bq arbitrary: t)\n  apply(auto)\nproof goal_cases\n  case prems: (1 a bq t)\n  hence r: \"rank (link t a) = rank a + 1\" by (simp add: rank_link)\n  from prems r and prems(1)[of \"(link t a)\"] show ?case by (cases bq) auto\nqed\n\nlemma rank_invar_ins: \"rank_invar bq \\<Longrightarrow> rank_invar (ins t bq)\"\n  apply(induct bq arbitrary: t)\n  apply(simp)\n  apply(auto)\nproof goal_cases\n  case prems: (1 a bq t)\n  hence inv: \"rank_invar (ins t bq)\" by (cases bq) simp_all\n  from prems have hd: \"bq \\<noteq> [] \\<Longrightarrow> rank a < rank (hd bq)\"  \n    by (cases bq) auto\n  from prems 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 prems 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 prems and inv and hd show ?case by (auto simp add: rank_invar_hd_cons)\nnext\n  case prems: (2 a bq t)\n  hence inv: \"rank_invar bq\" by (cases bq) simp_all\n  with prems and prems(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 \\<open>Melds two queues.\\<close>\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)\n  case 1\n  then show ?case by simp\nnext\n  case 2\n  then show ?case by simp\nnext\n  case (3 t1 bq1 t2 bq2)\n  consider (lt) \"rank t1 < rank t2\" | (gt) \"rank t1 > rank t2\" | (eq) \"rank t1 = rank t2\"\n    by atomize_elim auto\n  then show ?case\n  proof cases\n    case lt\n    from 3(4) have inv_bq1: \"queue_invar bq1\" by simp\n    from 3(4) have inv_t1: \"tree_invar t1\" by simp\n    from 3(1)[OF lt inv_bq1 3(5)] inv_t1 lt\n    show ?thesis by simp\n  next\n    case gt\n    from 3(5) have inv_bq2: \"queue_invar bq2\" by simp\n    from 3(5) have inv_t2: \"tree_invar t2\" by simp\n    from gt have \"\\<not> rank t1 < rank t2\" by simp\n    from 3(2)[OF this gt 3(4) inv_bq2] inv_t2 gt\n    show ?thesis by simp\n  next\n    case eq\n    from 3(4) have inv_bq1: \"queue_invar bq1\" by simp\n    from 3(4) have inv_t1: \"tree_invar t1\" by simp\n    from 3(5) have inv_bq2: \"queue_invar bq2\" by simp\n    from 3(5) have inv_t2: \"tree_invar t2\" by simp\n    note inv_link = link_tree_invar[OF inv_t1 inv_t2 eq]\n    from eq have *: \"\\<not> rank t1 < rank t2\" \"\\<not> rank t2 < rank t1\" by simp_all\n    note inv_meld = 3(3)[OF * inv_bq1 inv_bq2]\n    from ins_queue_invar[OF inv_link inv_meld] *\n    show ?thesis by simp\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))\"\n  apply(induct bq arbitrary: t)\n  apply(auto)\nproof goal_cases\n  case prems: (1 a bq t)\n  hence inv: \"rank_invar bq\" by (cases bq) simp_all\n  from prems have r: \"rank (link t a) = rank a + 1\" by (simp add: rank_link)\n  with prems and inv and prems(1)[of \"(link t a)\"] show ?case by (cases bq) auto\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))\"\nproof (induct bq1 bq2 rule: meld.induct)\n  case 1\n  then show ?case by simp\nnext\n  case 2\n  then show ?case by simp\nnext\n  case (3 t1 bq1 t2 bq2)\n  from 3 have inv1: \"rank_invar bq1\" by (cases bq1) simp_all\n  from 3 have inv2: \"rank_invar bq2\" by (cases bq2) simp_all\n  \n  from inv1 and inv2 and 3 show ?case\n  proof (auto, goal_cases)\n    let ?t = \"t2\"\n    let ?bq = \"bq2\"\n    let ?meld = \"rank t2 < rank (hd (meld (t1 # bq1) bq2))\"\n    case prems: 1\n    hence \"?bq \\<noteq> [] \\<Longrightarrow> rank ?t < rank (hd ?bq)\" \n      by (simp add: rank_invar_not_empty_hd)\n    with prems have ne: \"?bq \\<noteq> [] \\<Longrightarrow> ?meld\" by simp\n    from prems have \"?bq = [] \\<Longrightarrow> ?meld\" by simp\n    with ne have \"?meld\" by (cases \"?bq = []\")\n    with prems show ?case by (simp add: rank_invar_hd_cons)\n  next \\<comment> \\<open>analog\\<close>\n    let ?t = \"t1\"\n    let ?bq = \"bq1\"\n    let ?meld = \"rank t1 < rank (hd (meld bq1 (t2 # bq2)))\"\n    case prems: 2\n    hence \"?bq \\<noteq> [] \\<Longrightarrow> rank ?t < rank (hd ?bq)\" \n      by (simp add: rank_invar_not_empty_hd)\n    with prems have ne: \"?bq \\<noteq> [] \\<Longrightarrow> ?meld\" by simp\n    from prems have \"?bq = [] \\<Longrightarrow> ?meld\" by simp\n    with ne have \"?meld\" by (cases \"?bq = []\")\n    with prems show ?case by (simp add: rank_invar_hd_cons)\n  next\n    case 3\n    thus ?case by (simp add: rank_invar_ins)\n  next\n    case prems: 4 (* Ab hier wirds h\u00e4sslich *)\n    then 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 prems\n    have mm: \"min (rank (hd bq1)) (rank (hd bq2)) \\<le> rank (hd (meld bq1 bq2))\"\n      by simp\n    from \\<open>rank_invar (t1 # bq1)\\<close> have \"bq1 \\<noteq> [] \\<Longrightarrow> rank t1 < rank (hd bq1)\" \n      by (simp add: rank_invar_not_empty_hd)\n    with prems have r1: \"bq1 \\<noteq> [] \\<Longrightarrow> rank t2 < rank (hd bq1)\" by simp\n    from \\<open>rank_invar (t2 # bq2)\\<close> \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 \\<open>rank_invar (meld bq1 bq2)\\<close> \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'\"\nby(induct q q' rule: meld.induct)\n  (auto simp add: link_tree_invar meld_queue_invar ins_mset union_ac)\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 \\<open>Finds the tree containing the minimal element.\\<close>\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)\n  case Nil\n  then show ?case by simp\nnext\n  case (Cons _ bq)\n  then show ?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_mset (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 goal_cases\n  case prems: (1 t v va ta)\n  thus ?case\n    apply (cases \"ta = t\")\n    apply auto[1] \n    apply (metis getMinTree_cons prems(1) prems(3) set_ConsD xt1(6))\n    done\nqed\n\nlemma getMinTree_min_prio:\n  assumes \"queue_invar bq\"\n    and \"y \\<in> set_mset (queue_to_multiset bq)\"\n  shows \"prio (getMinTree bq) \\<le> snd y\"\nproof -\n  from assms have \"bq \\<noteq> []\" by (cases bq) simp_all\n  with assms have \"\\<exists> t \\<in> set bq. (y \\<in> set_mset ((tree_to_multiset t)))\"\n  proof (induct bq)\n    case Nil\n    then show ?case by simp\n  next\n    case (Cons a bq)\n    thus ?case\n      apply(cases \"y \\<in> set_mset (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_mset (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 assms(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 ?thesis by simp\nqed\n\ntext \\<open>Finds the minimal Element in the queue.\\<close>\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_mset (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_mset (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 \\<open>Removes the first tree, which has the priority $a$ within his root.\\<close>\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 \\<open>Returns the queue without the minimal element.\\<close>\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 \\<subseteq># queue_to_multiset q\"\nproof(induct q)\n  case Nil\n  then show ?case by simp\nnext\n  case (Cons a q)\n  show ?case\n  proof (cases \"t = a\")\n    case True\n    then show ?thesis by simp\n  next\n    case False\n    with Cons have t_in_q: \"t \\<in> set q\" by simp\n    have \"queue_to_multiset q \\<subseteq># queue_to_multiset (a # q)\"\n      by simp\n    from subset_mset.order_trans[OF Cons(1)[OF t_in_q] this] show ?thesis .\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)\"\nproof (cases q)\n  case Nil\n  with assms show ?thesis by simp\nnext\n  case Cons\n  from NE and mintree_exists[of q] INV \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 INV, of \"getMinTree q\"]\n  from meld_queue_invar[OF inv_rev inv_rem] show ?thesis\n    by (simp add: deleteMin_def Let_def)\nqed\n\nlemma children_rank_less: \n  assumes \"tree_invar t\"\n  shows \"\\<forall>t' \\<in> set (children t). rank t' < rank t\"\nproof (cases t)\n  case (Node e a nat list)\n  with assms show ?thesis\n  proof (induct nat arbitrary: t e a list) \n    case 0\n    then show ?case by simp\n  next\n    case (Suc nat)\n    then obtain e1 a1 ts1 e2 a2 ts2 where \n      O: \"tree_invar (Node e1 a1 nat ts1)\" \"tree_invar (Node e2 a2 nat ts2)\"\n        \"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 Suc(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 Suc(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 Suc(3) p1 p2 ch_id show ?case by simp\n  qed\nqed\n\nlemma strong_rev_children:\n  assumes \"tree_invar t\"\n  shows \"invar (rev (children t))\"\n  unfolding invar_def\nproof (cases t)\n  case (Node e a nat list)\n  with assms show \"queue_invar (rev (children t)) \\<and> rank_invar (rev (children t))\"\n  proof (induct \"nat\" arbitrary: t e a list)\n    case 0\n    then show ?case by simp\n  next\n    case (Suc nat)\n    then obtain e1 a1 ts1 e2 a2 ts2 where \n      O: \"tree_invar (Node e1 a1 nat ts1)\" \"tree_invar (Node e2 a2 nat ts2)\"\n        \"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 Suc(1)[of \"Node e1 a1 nat ts1\" \"e1\" \"a1\" \"ts1\"]\n    have rev_ts1: \"invar (rev ts1)\" by (simp add: invar_def)\n    from O children_rank_less[of \"Node e1 a1 nat ts1\"]\n    have  \"\\<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 Suc(1)[of \"Node e2 a2 nat ts2\" \"e2\" \"a2\" \"ts2\"]\n    have rev_ts2: \"invar (rev ts2)\" by (simp add: invar_def)\n    from O children_rank_less[of \"Node e2 a2 nat ts2\"]\n    have \"\\<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) \n  case Nil\n  then show ?case by simp\nnext\n  case (Cons a bq) \n  show ?case \n  proof (cases \"t=a\")\n    case True\n    from Cons(2) have \"invar bq\" by (rule invar_cons_down)\n    with True show ?thesis by simp\n  next\n    case False\n    from Cons(2) have \"invar bq\" by (rule invar_cons_down)\n    with Cons(1)[of \"t\"] have si1: \"invar (remove1 t bq)\" .\n    from False have \"invar (remove1 t (a # bq)) = invar (a # (remove1 t bq))\"\n      by simp\n    show ?thesis\n    proof (cases \"remove1 t bq\")\n      case Nil\n      with si1 Cons(2) False show ?thesis by (simp add: invar_def)\n    next\n      case Cons': (Cons aa list)\n      from Cons have \"tree_invar a\" by (simp add: invar_def)\n      from Cons first_less[of \"a\" \"bq\"] have \"\\<forall>t \\<in> set (remove1 t bq). rank a < rank t\"\n        by (metis notin_set_remove1 invar_def) \n      with Cons' have \"rank a < rank aa\" by simp\n      with si1 Cons(2) False Cons' invar_cons_up[of \"aa\" \"list\" \"a\"] show ?thesis\n        by (simp add: invar_def)\n    qed\n  qed\nqed  \n\ntheorem deleteMin_invar:\n  assumes \"invar bq\"\n    and \"bq \\<noteq> []\"\n  shows \"invar (deleteMin bq)\"\nproof -\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 assms 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\"]\n  have m1: \"invar (rev (children (getMinTree bq)))\" .\n  from strong_remove1[of \"bq\" \"getMinTree bq\"] assms(1)\n  have 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 \"invar (meld (rev (children (getMinTree bq))) (remove1 (getMinTree bq) bq))\" .\n  with eq show ?thesis ..\nqed\n\nlemma children_mset: \"queue_to_multiset (children t) = \n  tree_to_multiset t - {# (val t, prio t) #}\"\nproof (cases t)\n  case (Node e a nat list)\n  thus ?thesis by (induct list) simp_all\nqed\n\nlemma deleteMin_mset:\n  assumes \"queue_invar q\"\n    and \"q \\<noteq> Nil\"\n  shows \"queue_to_multiset (deleteMin q) = queue_to_multiset q - {# (findMin q) #}\"\nproof -\n  from assms mintree_exists[of \"q\"] have min_in_q: \"getMinTree q \\<in> set q\" by auto\n  with assms(1) have inv_min: \"tree_invar (getMinTree q)\" \n    by (simp add: queue_invar_def)\n  from assms(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 assms(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)) #} \\<subseteq># ?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_subset_eq_multiset_union_diff_commute[OF min_subset_q, of \"?MT\"]\n  show ?thesis 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 (overloaded) ('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 \\<open>\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 \\<open>'a\\<close>.\n\\<close>\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_mset (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 \\<open>Correctness lemmas to be used with simplifier\\<close>\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 \\<open>\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} \\<open>BinomialHeap.empty_correct\\<close>:\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} \\<open>BinomialHeap.isEmpty_correct\\<close>:\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} \\<open>BinomialHeap.insert_correct\\<close>:\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} \\<open>BinomialHeap.findMin_correct\\<close>:\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} \\<open>BinomialHeap.deleteMin_correct\\<close>:\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} \\<open>BinomialHeap.meld_correct\\<close>:\n    @{thm [display] BinomialHeap.meld_correct[no_vars]}\n\n\\<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/Binomial-Heaps/BinomialHeap.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357632379241, "lm_q2_score": 0.8128673155708975, "lm_q1q2_score": 0.7047850333671757}}
{"text": "(*  Title:      HOL/Library/FSet.thy\n    Author:     Ondrej Kuncar, TU Muenchen\n    Author:     Cezary Kaliszyk and Christian Urban\n    Author:     Andrei Popescu, TU Muenchen\n*)\n\nsection {* Type of finite sets defined as a subtype of sets *}\n\ntheory FSet\nimports Conditionally_Complete_Lattices\nbegin\n\nsubsection {* Definition of the type *}\n\ntypedef 'a fset = \"{A :: 'a set. finite A}\"  morphisms fset Abs_fset\nby auto\n\nsetup_lifting type_definition_fset\n\n\nsubsection {* Basic operations and type class instantiations *}\n\n(* FIXME transfer and right_total vs. bi_total *)\ninstantiation fset :: (finite) finite\nbegin\ninstance by default (transfer, simp)\nend\n\ninstantiation fset :: (type) \"{bounded_lattice_bot, distrib_lattice, minus}\"\nbegin\n\ninterpretation lifting_syntax .\n\nlift_definition bot_fset :: \"'a fset\" is \"{}\" parametric empty_transfer by simp \n\nlift_definition less_eq_fset :: \"'a fset \\<Rightarrow> 'a fset \\<Rightarrow> bool\" is subset_eq parametric subset_transfer \n  .\n\ndefinition less_fset :: \"'a fset \\<Rightarrow> 'a fset \\<Rightarrow> bool\" where \"xs < ys \\<equiv> xs \\<le> ys \\<and> xs \\<noteq> (ys::'a fset)\"\n\nlemma less_fset_transfer[transfer_rule]:\n  assumes [transfer_rule]: \"bi_unique A\" \n  shows \"((pcr_fset A) ===> (pcr_fset A) ===> op =) op \\<subset> op <\"\n  unfolding less_fset_def[abs_def] psubset_eq[abs_def] by transfer_prover\n  \n\nlift_definition sup_fset :: \"'a fset \\<Rightarrow> 'a fset \\<Rightarrow> 'a fset\" is union parametric union_transfer\n  by simp\n\nlift_definition inf_fset :: \"'a fset \\<Rightarrow> 'a fset \\<Rightarrow> 'a fset\" is inter parametric inter_transfer\n  by simp\n\nlift_definition minus_fset :: \"'a fset \\<Rightarrow> 'a fset \\<Rightarrow> 'a fset\" is minus parametric Diff_transfer\n  by simp\n\ninstance\nby default (transfer, auto)+\n\nend\n\nabbreviation fempty :: \"'a fset\" (\"{||}\") where \"{||} \\<equiv> bot\"\nabbreviation fsubset_eq :: \"'a fset \\<Rightarrow> 'a fset \\<Rightarrow> bool\" (infix \"|\\<subseteq>|\" 50) where \"xs |\\<subseteq>| ys \\<equiv> xs \\<le> ys\"\nabbreviation fsubset :: \"'a fset \\<Rightarrow> 'a fset \\<Rightarrow> bool\" (infix \"|\\<subset>|\" 50) where \"xs |\\<subset>| ys \\<equiv> xs < ys\"\nabbreviation funion :: \"'a fset \\<Rightarrow> 'a fset \\<Rightarrow> 'a fset\" (infixl \"|\\<union>|\" 65) where \"xs |\\<union>| ys \\<equiv> sup xs ys\"\nabbreviation finter :: \"'a fset \\<Rightarrow> 'a fset \\<Rightarrow> 'a fset\" (infixl \"|\\<inter>|\" 65) where \"xs |\\<inter>| ys \\<equiv> inf xs ys\"\nabbreviation fminus :: \"'a fset \\<Rightarrow> 'a fset \\<Rightarrow> 'a fset\" (infixl \"|-|\" 65) where \"xs |-| ys \\<equiv> minus xs ys\"\n\ninstantiation fset :: (equal) equal\nbegin\ndefinition \"HOL.equal A B \\<longleftrightarrow> A |\\<subseteq>| B \\<and> B |\\<subseteq>| A\"\ninstance by intro_classes (auto simp add: equal_fset_def)\nend \n\ninstantiation fset :: (type) conditionally_complete_lattice\nbegin\n\ninterpretation lifting_syntax .\n\nlemma right_total_Inf_fset_transfer:\n  assumes [transfer_rule]: \"bi_unique A\" and [transfer_rule]: \"right_total A\"\n  shows \"(rel_set (rel_set A) ===> rel_set A) \n    (\\<lambda>S. if finite (Inter S \\<inter> Collect (Domainp A)) then Inter S \\<inter> Collect (Domainp A) else {}) \n      (\\<lambda>S. if finite (Inf S) then Inf S else {})\"\n    by transfer_prover\n\nlemma Inf_fset_transfer:\n  assumes [transfer_rule]: \"bi_unique A\" and [transfer_rule]: \"bi_total A\"\n  shows \"(rel_set (rel_set A) ===> rel_set A) (\\<lambda>A. if finite (Inf A) then Inf A else {}) \n    (\\<lambda>A. if finite (Inf A) then Inf A else {})\"\n  by transfer_prover\n\nlift_definition Inf_fset :: \"'a fset set \\<Rightarrow> 'a fset\" is \"\\<lambda>A. if finite (Inf A) then Inf A else {}\" \nparametric right_total_Inf_fset_transfer Inf_fset_transfer by simp\n\nlemma Sup_fset_transfer:\n  assumes [transfer_rule]: \"bi_unique A\"\n  shows \"(rel_set (rel_set A) ===> rel_set A) (\\<lambda>A. if finite (Sup A) then Sup A else {})\n  (\\<lambda>A. if finite (Sup A) then Sup A else {})\" by transfer_prover\n\nlift_definition Sup_fset :: \"'a fset set \\<Rightarrow> 'a fset\" is \"\\<lambda>A. if finite (Sup A) then Sup A else {}\"\nparametric Sup_fset_transfer by simp\n\nlemma finite_Sup: \"\\<exists>z. finite z \\<and> (\\<forall>a. a \\<in> X \\<longrightarrow> a \\<le> z) \\<Longrightarrow> finite (Sup X)\"\nby (auto intro: finite_subset)\n\nlemma transfer_bdd_below[transfer_rule]: \"(rel_set (pcr_fset op =) ===> op =) bdd_below bdd_below\"\n  by auto\n\ninstance\nproof \n  fix x z :: \"'a fset\"\n  fix X :: \"'a fset set\"\n  {\n    assume \"x \\<in> X\" \"bdd_below X\" \n    then show \"Inf X |\\<subseteq>| x\" by transfer auto\n  next\n    assume \"X \\<noteq> {}\" \"(\\<And>x. x \\<in> X \\<Longrightarrow> z |\\<subseteq>| x)\"\n    then show \"z |\\<subseteq>| Inf X\" by transfer (clarsimp, blast)\n  next\n    assume \"x \\<in> X\" \"bdd_above X\"\n    then obtain z where \"x \\<in> X\" \"(\\<And>x. x \\<in> X \\<Longrightarrow> x |\\<subseteq>| z)\"\n      by (auto simp: bdd_above_def)\n    then show \"x |\\<subseteq>| Sup X\"\n      by transfer (auto intro!: finite_Sup)\n  next\n    assume \"X \\<noteq> {}\" \"(\\<And>x. x \\<in> X \\<Longrightarrow> x |\\<subseteq>| z)\"\n    then show \"Sup X |\\<subseteq>| z\" by transfer (clarsimp, blast)\n  }\nqed\nend\n\ninstantiation fset :: (finite) complete_lattice \nbegin\n\nlift_definition top_fset :: \"'a fset\" is UNIV parametric right_total_UNIV_transfer UNIV_transfer by simp\n\ninstance by default (transfer, auto)+\nend\n\ninstantiation fset :: (finite) complete_boolean_algebra\nbegin\n\nlift_definition uminus_fset :: \"'a fset \\<Rightarrow> 'a fset\" is uminus \n  parametric right_total_Compl_transfer Compl_transfer by simp\n\ninstance by (default, simp_all only: INF_def SUP_def) (transfer, simp add: Compl_partition Diff_eq)+\n\nend\n\nabbreviation fUNIV :: \"'a::finite fset\" where \"fUNIV \\<equiv> top\"\nabbreviation fuminus :: \"'a::finite fset \\<Rightarrow> 'a fset\" (\"|-| _\" [81] 80) where \"|-| x \\<equiv> uminus x\"\n\ndeclare top_fset.rep_eq[simp]\n\n\nsubsection {* Other operations *}\n\nlift_definition finsert :: \"'a \\<Rightarrow> 'a fset \\<Rightarrow> 'a fset\" is insert parametric Lifting_Set.insert_transfer\n  by simp\n\nsyntax\n  \"_insert_fset\"     :: \"args => 'a fset\"  (\"{|(_)|}\")\n\ntranslations\n  \"{|x, xs|}\" == \"CONST finsert x {|xs|}\"\n  \"{|x|}\"     == \"CONST finsert x {||}\"\n\nlift_definition fmember :: \"'a \\<Rightarrow> 'a fset \\<Rightarrow> bool\" (infix \"|\\<in>|\" 50) is Set.member \n  parametric member_transfer .\n\nabbreviation notin_fset :: \"'a \\<Rightarrow> 'a fset \\<Rightarrow> bool\" (infix \"|\\<notin>|\" 50) where \"x |\\<notin>| S \\<equiv> \\<not> (x |\\<in>| S)\"\n\ncontext\nbegin\n\ninterpretation lifting_syntax .\n\nlift_definition ffilter :: \"('a \\<Rightarrow> bool) \\<Rightarrow> 'a fset \\<Rightarrow> 'a fset\" is Set.filter \n  parametric Lifting_Set.filter_transfer unfolding Set.filter_def by simp\n\nlift_definition fPow :: \"'a fset \\<Rightarrow> 'a fset fset\" is Pow parametric Pow_transfer \nby (simp add: finite_subset)\n\nlift_definition fcard :: \"'a fset \\<Rightarrow> nat\" is card parametric card_transfer .\n\nlift_definition fimage :: \"('a \\<Rightarrow> 'b) \\<Rightarrow> 'a fset \\<Rightarrow> 'b fset\" (infixr \"|`|\" 90) is image \n  parametric image_transfer by simp\n\nlift_definition fthe_elem :: \"'a fset \\<Rightarrow> 'a\" is the_elem .\n\nlift_definition fbind :: \"'a fset \\<Rightarrow> ('a \\<Rightarrow> 'b fset) \\<Rightarrow> 'b fset\" is Set.bind parametric bind_transfer \nby (simp add: Set.bind_def)\n\nlift_definition ffUnion :: \"'a fset fset \\<Rightarrow> 'a fset\" is Union parametric Union_transfer by simp\n\nlift_definition fBall :: \"'a fset \\<Rightarrow> ('a \\<Rightarrow> bool) \\<Rightarrow> bool\" is Ball parametric Ball_transfer .\nlift_definition fBex :: \"'a fset \\<Rightarrow> ('a \\<Rightarrow> bool) \\<Rightarrow> bool\" is Bex parametric Bex_transfer .\n\nlift_definition ffold :: \"('a \\<Rightarrow> 'b \\<Rightarrow> 'b) \\<Rightarrow> 'b \\<Rightarrow> 'a fset \\<Rightarrow> 'b\" is Finite_Set.fold .\n\n\nsubsection {* Transferred lemmas from Set.thy *}\n\nlemmas fset_eqI = set_eqI[Transfer.transferred]\nlemmas fset_eq_iff[no_atp] = set_eq_iff[Transfer.transferred]\nlemmas fBallI[intro!] = ballI[Transfer.transferred]\nlemmas fbspec[dest?] = bspec[Transfer.transferred]\nlemmas fBallE[elim] = ballE[Transfer.transferred]\nlemmas fBexI[intro] = bexI[Transfer.transferred]\nlemmas rev_fBexI[intro?] = rev_bexI[Transfer.transferred]\nlemmas fBexCI = bexCI[Transfer.transferred]\nlemmas fBexE[elim!] = bexE[Transfer.transferred]\nlemmas fBall_triv[simp] = ball_triv[Transfer.transferred]\nlemmas fBex_triv[simp] = bex_triv[Transfer.transferred]\nlemmas fBex_triv_one_point1[simp] = bex_triv_one_point1[Transfer.transferred]\nlemmas fBex_triv_one_point2[simp] = bex_triv_one_point2[Transfer.transferred]\nlemmas fBex_one_point1[simp] = bex_one_point1[Transfer.transferred]\nlemmas fBex_one_point2[simp] = bex_one_point2[Transfer.transferred]\nlemmas fBall_one_point1[simp] = ball_one_point1[Transfer.transferred]\nlemmas fBall_one_point2[simp] = ball_one_point2[Transfer.transferred]\nlemmas fBall_conj_distrib = ball_conj_distrib[Transfer.transferred]\nlemmas fBex_disj_distrib = bex_disj_distrib[Transfer.transferred]\nlemmas fBall_cong = ball_cong[Transfer.transferred]\nlemmas fBex_cong = bex_cong[Transfer.transferred]\nlemmas fsubsetI[intro!] = subsetI[Transfer.transferred]\nlemmas fsubsetD[elim, intro?] = subsetD[Transfer.transferred]\nlemmas rev_fsubsetD[no_atp,intro?] = rev_subsetD[Transfer.transferred]\nlemmas fsubsetCE[no_atp,elim] = subsetCE[Transfer.transferred]\nlemmas fsubset_eq[no_atp] = subset_eq[Transfer.transferred]\nlemmas contra_fsubsetD[no_atp] = contra_subsetD[Transfer.transferred]\nlemmas fsubset_refl = subset_refl[Transfer.transferred]\nlemmas fsubset_trans = subset_trans[Transfer.transferred]\nlemmas fset_rev_mp = set_rev_mp[Transfer.transferred]\nlemmas fset_mp = set_mp[Transfer.transferred]\nlemmas fsubset_not_fsubset_eq[code] = subset_not_subset_eq[Transfer.transferred]\nlemmas eq_fmem_trans = eq_mem_trans[Transfer.transferred]\nlemmas fsubset_antisym[intro!] = subset_antisym[Transfer.transferred]\nlemmas fequalityD1 = equalityD1[Transfer.transferred]\nlemmas fequalityD2 = equalityD2[Transfer.transferred]\nlemmas fequalityE = equalityE[Transfer.transferred]\nlemmas fequalityCE[elim] = equalityCE[Transfer.transferred]\nlemmas eqfset_imp_iff = eqset_imp_iff[Transfer.transferred]\nlemmas eqfelem_imp_iff = eqelem_imp_iff[Transfer.transferred]\nlemmas fempty_iff[simp] = empty_iff[Transfer.transferred]\nlemmas fempty_fsubsetI[iff] = empty_subsetI[Transfer.transferred]\nlemmas equalsffemptyI = equals0I[Transfer.transferred]\nlemmas equalsffemptyD = equals0D[Transfer.transferred]\nlemmas fBall_fempty[simp] = ball_empty[Transfer.transferred]\nlemmas fBex_fempty[simp] = bex_empty[Transfer.transferred]\nlemmas fPow_iff[iff] = Pow_iff[Transfer.transferred]\nlemmas fPowI = PowI[Transfer.transferred]\nlemmas fPowD = PowD[Transfer.transferred]\nlemmas fPow_bottom = Pow_bottom[Transfer.transferred]\nlemmas fPow_top = Pow_top[Transfer.transferred]\nlemmas fPow_not_fempty = Pow_not_empty[Transfer.transferred]\nlemmas finter_iff[simp] = Int_iff[Transfer.transferred]\nlemmas finterI[intro!] = IntI[Transfer.transferred]\nlemmas finterD1 = IntD1[Transfer.transferred]\nlemmas finterD2 = IntD2[Transfer.transferred]\nlemmas finterE[elim!] = IntE[Transfer.transferred]\nlemmas funion_iff[simp] = Un_iff[Transfer.transferred]\nlemmas funionI1[elim?] = UnI1[Transfer.transferred]\nlemmas funionI2[elim?] = UnI2[Transfer.transferred]\nlemmas funionCI[intro!] = UnCI[Transfer.transferred]\nlemmas funionE[elim!] = UnE[Transfer.transferred]\nlemmas fminus_iff[simp] = Diff_iff[Transfer.transferred]\nlemmas fminusI[intro!] = DiffI[Transfer.transferred]\nlemmas fminusD1 = DiffD1[Transfer.transferred]\nlemmas fminusD2 = DiffD2[Transfer.transferred]\nlemmas fminusE[elim!] = DiffE[Transfer.transferred]\nlemmas finsert_iff[simp] = insert_iff[Transfer.transferred]\nlemmas finsertI1 = insertI1[Transfer.transferred]\nlemmas finsertI2 = insertI2[Transfer.transferred]\nlemmas finsertE[elim!] = insertE[Transfer.transferred]\nlemmas finsertCI[intro!] = insertCI[Transfer.transferred]\nlemmas fsubset_finsert_iff = subset_insert_iff[Transfer.transferred]\nlemmas finsert_ident = insert_ident[Transfer.transferred]\nlemmas fsingletonI[intro!,no_atp] = singletonI[Transfer.transferred]\nlemmas fsingletonD[dest!,no_atp] = singletonD[Transfer.transferred]\nlemmas fsingleton_iff = singleton_iff[Transfer.transferred]\nlemmas fsingleton_inject[dest!] = singleton_inject[Transfer.transferred]\nlemmas fsingleton_finsert_inj_eq[iff,no_atp] = singleton_insert_inj_eq[Transfer.transferred]\nlemmas fsingleton_finsert_inj_eq'[iff,no_atp] = singleton_insert_inj_eq'[Transfer.transferred]\nlemmas fsubset_fsingletonD = subset_singletonD[Transfer.transferred]\nlemmas fminus_single_finsert = diff_single_insert[Transfer.transferred]\nlemmas fdoubleton_eq_iff = doubleton_eq_iff[Transfer.transferred]\nlemmas funion_fsingleton_iff = Un_singleton_iff[Transfer.transferred]\nlemmas fsingleton_funion_iff = singleton_Un_iff[Transfer.transferred]\nlemmas fimage_eqI[simp, intro] = image_eqI[Transfer.transferred]\nlemmas fimageI = imageI[Transfer.transferred]\nlemmas rev_fimage_eqI = rev_image_eqI[Transfer.transferred]\nlemmas fimageE[elim!] = imageE[Transfer.transferred]\nlemmas Compr_fimage_eq = Compr_image_eq[Transfer.transferred]\nlemmas fimage_funion = image_Un[Transfer.transferred]\nlemmas fimage_iff = image_iff[Transfer.transferred]\nlemmas fimage_fsubset_iff[no_atp] = image_subset_iff[Transfer.transferred]\nlemmas fimage_fsubsetI = image_subsetI[Transfer.transferred]\nlemmas fimage_ident[simp] = image_ident[Transfer.transferred]\nlemmas split_if_fmem1 = split_if_mem1[Transfer.transferred]\nlemmas split_if_fmem2 = split_if_mem2[Transfer.transferred]\nlemmas pfsubsetI[intro!,no_atp] = psubsetI[Transfer.transferred]\nlemmas pfsubsetE[elim!,no_atp] = psubsetE[Transfer.transferred]\nlemmas pfsubset_finsert_iff = psubset_insert_iff[Transfer.transferred]\nlemmas pfsubset_eq = psubset_eq[Transfer.transferred]\nlemmas pfsubset_imp_fsubset = psubset_imp_subset[Transfer.transferred]\nlemmas pfsubset_trans = psubset_trans[Transfer.transferred]\nlemmas pfsubsetD = psubsetD[Transfer.transferred]\nlemmas pfsubset_fsubset_trans = psubset_subset_trans[Transfer.transferred]\nlemmas fsubset_pfsubset_trans = subset_psubset_trans[Transfer.transferred]\nlemmas pfsubset_imp_ex_fmem = psubset_imp_ex_mem[Transfer.transferred]\nlemmas fimage_fPow_mono = image_Pow_mono[Transfer.transferred]\nlemmas fimage_fPow_surj = image_Pow_surj[Transfer.transferred]\nlemmas fsubset_finsertI = subset_insertI[Transfer.transferred]\nlemmas fsubset_finsertI2 = subset_insertI2[Transfer.transferred]\nlemmas fsubset_finsert = subset_insert[Transfer.transferred]\nlemmas funion_upper1 = Un_upper1[Transfer.transferred]\nlemmas funion_upper2 = Un_upper2[Transfer.transferred]\nlemmas funion_least = Un_least[Transfer.transferred]\nlemmas finter_lower1 = Int_lower1[Transfer.transferred]\nlemmas finter_lower2 = Int_lower2[Transfer.transferred]\nlemmas finter_greatest = Int_greatest[Transfer.transferred]\nlemmas fminus_fsubset = Diff_subset[Transfer.transferred]\nlemmas fminus_fsubset_conv = Diff_subset_conv[Transfer.transferred]\nlemmas fsubset_fempty[simp] = subset_empty[Transfer.transferred]\nlemmas not_pfsubset_fempty[iff] = not_psubset_empty[Transfer.transferred]\nlemmas finsert_is_funion = insert_is_Un[Transfer.transferred]\nlemmas finsert_not_fempty[simp] = insert_not_empty[Transfer.transferred]\nlemmas fempty_not_finsert = empty_not_insert[Transfer.transferred]\nlemmas finsert_absorb = insert_absorb[Transfer.transferred]\nlemmas finsert_absorb2[simp] = insert_absorb2[Transfer.transferred]\nlemmas finsert_commute = insert_commute[Transfer.transferred]\nlemmas finsert_fsubset[simp] = insert_subset[Transfer.transferred]\nlemmas finsert_inter_finsert[simp] = insert_inter_insert[Transfer.transferred]\nlemmas finsert_disjoint[simp,no_atp] = insert_disjoint[Transfer.transferred]\nlemmas disjoint_finsert[simp,no_atp] = disjoint_insert[Transfer.transferred]\nlemmas fimage_fempty[simp] = image_empty[Transfer.transferred]\nlemmas fimage_finsert[simp] = image_insert[Transfer.transferred]\nlemmas fimage_constant = image_constant[Transfer.transferred]\nlemmas fimage_constant_conv = image_constant_conv[Transfer.transferred]\nlemmas fimage_fimage = image_image[Transfer.transferred]\nlemmas finsert_fimage[simp] = insert_image[Transfer.transferred]\nlemmas fimage_is_fempty[iff] = image_is_empty[Transfer.transferred]\nlemmas fempty_is_fimage[iff] = empty_is_image[Transfer.transferred]\nlemmas fimage_cong = image_cong[Transfer.transferred]\nlemmas fimage_finter_fsubset = image_Int_subset[Transfer.transferred]\nlemmas fimage_fminus_fsubset = image_diff_subset[Transfer.transferred]\nlemmas finter_absorb = Int_absorb[Transfer.transferred]\nlemmas finter_left_absorb = Int_left_absorb[Transfer.transferred]\nlemmas finter_commute = Int_commute[Transfer.transferred]\nlemmas finter_left_commute = Int_left_commute[Transfer.transferred]\nlemmas finter_assoc = Int_assoc[Transfer.transferred]\nlemmas finter_ac = Int_ac[Transfer.transferred]\nlemmas finter_absorb1 = Int_absorb1[Transfer.transferred]\nlemmas finter_absorb2 = Int_absorb2[Transfer.transferred]\nlemmas finter_fempty_left = Int_empty_left[Transfer.transferred]\nlemmas finter_fempty_right = Int_empty_right[Transfer.transferred]\nlemmas disjoint_iff_fnot_equal = disjoint_iff_not_equal[Transfer.transferred]\nlemmas finter_funion_distrib = Int_Un_distrib[Transfer.transferred]\nlemmas finter_funion_distrib2 = Int_Un_distrib2[Transfer.transferred]\nlemmas finter_fsubset_iff[no_atp, simp] = Int_subset_iff[Transfer.transferred]\nlemmas funion_absorb = Un_absorb[Transfer.transferred]\nlemmas funion_left_absorb = Un_left_absorb[Transfer.transferred]\nlemmas funion_commute = Un_commute[Transfer.transferred]\nlemmas funion_left_commute = Un_left_commute[Transfer.transferred]\nlemmas funion_assoc = Un_assoc[Transfer.transferred]\nlemmas funion_ac = Un_ac[Transfer.transferred]\nlemmas funion_absorb1 = Un_absorb1[Transfer.transferred]\nlemmas funion_absorb2 = Un_absorb2[Transfer.transferred]\nlemmas funion_fempty_left = Un_empty_left[Transfer.transferred]\nlemmas funion_fempty_right = Un_empty_right[Transfer.transferred]\nlemmas funion_finsert_left[simp] = Un_insert_left[Transfer.transferred]\nlemmas funion_finsert_right[simp] = Un_insert_right[Transfer.transferred]\nlemmas finter_finsert_left = Int_insert_left[Transfer.transferred]\nlemmas finter_finsert_left_ifffempty[simp] = Int_insert_left_if0[Transfer.transferred]\nlemmas finter_finsert_left_if1[simp] = Int_insert_left_if1[Transfer.transferred]\nlemmas finter_finsert_right = Int_insert_right[Transfer.transferred]\nlemmas finter_finsert_right_ifffempty[simp] = Int_insert_right_if0[Transfer.transferred]\nlemmas finter_finsert_right_if1[simp] = Int_insert_right_if1[Transfer.transferred]\nlemmas funion_finter_distrib = Un_Int_distrib[Transfer.transferred]\nlemmas funion_finter_distrib2 = Un_Int_distrib2[Transfer.transferred]\nlemmas funion_finter_crazy = Un_Int_crazy[Transfer.transferred]\nlemmas fsubset_funion_eq = subset_Un_eq[Transfer.transferred]\nlemmas funion_fempty[iff] = Un_empty[Transfer.transferred]\nlemmas funion_fsubset_iff[no_atp, simp] = Un_subset_iff[Transfer.transferred]\nlemmas funion_fminus_finter = Un_Diff_Int[Transfer.transferred]\nlemmas fminus_finter2 = Diff_Int2[Transfer.transferred]\nlemmas funion_finter_assoc_eq = Un_Int_assoc_eq[Transfer.transferred]\nlemmas fBall_funion = ball_Un[Transfer.transferred]\nlemmas fBex_funion = bex_Un[Transfer.transferred]\nlemmas fminus_eq_fempty_iff[simp,no_atp] = Diff_eq_empty_iff[Transfer.transferred]\nlemmas fminus_cancel[simp] = Diff_cancel[Transfer.transferred]\nlemmas fminus_idemp[simp] = Diff_idemp[Transfer.transferred]\nlemmas fminus_triv = Diff_triv[Transfer.transferred]\nlemmas fempty_fminus[simp] = empty_Diff[Transfer.transferred]\nlemmas fminus_fempty[simp] = Diff_empty[Transfer.transferred]\nlemmas fminus_finsertffempty[simp,no_atp] = Diff_insert0[Transfer.transferred]\nlemmas fminus_finsert = Diff_insert[Transfer.transferred]\nlemmas fminus_finsert2 = Diff_insert2[Transfer.transferred]\nlemmas finsert_fminus_if = insert_Diff_if[Transfer.transferred]\nlemmas finsert_fminus1[simp] = insert_Diff1[Transfer.transferred]\nlemmas finsert_fminus_single[simp] = insert_Diff_single[Transfer.transferred]\nlemmas finsert_fminus = insert_Diff[Transfer.transferred]\nlemmas fminus_finsert_absorb = Diff_insert_absorb[Transfer.transferred]\nlemmas fminus_disjoint[simp] = Diff_disjoint[Transfer.transferred]\nlemmas fminus_partition = Diff_partition[Transfer.transferred]\nlemmas double_fminus = double_diff[Transfer.transferred]\nlemmas funion_fminus_cancel[simp] = Un_Diff_cancel[Transfer.transferred]\nlemmas funion_fminus_cancel2[simp] = Un_Diff_cancel2[Transfer.transferred]\nlemmas fminus_funion = Diff_Un[Transfer.transferred]\nlemmas fminus_finter = Diff_Int[Transfer.transferred]\nlemmas funion_fminus = Un_Diff[Transfer.transferred]\nlemmas finter_fminus = Int_Diff[Transfer.transferred]\nlemmas fminus_finter_distrib = Diff_Int_distrib[Transfer.transferred]\nlemmas fminus_finter_distrib2 = Diff_Int_distrib2[Transfer.transferred]\nlemmas fUNIV_bool[no_atp] = UNIV_bool[Transfer.transferred]\nlemmas fPow_fempty[simp] = Pow_empty[Transfer.transferred]\nlemmas fPow_finsert = Pow_insert[Transfer.transferred]\nlemmas funion_fPow_fsubset = Un_Pow_subset[Transfer.transferred]\nlemmas fPow_finter_eq[simp] = Pow_Int_eq[Transfer.transferred]\nlemmas fset_eq_fsubset = set_eq_subset[Transfer.transferred]\nlemmas fsubset_iff[no_atp] = subset_iff[Transfer.transferred]\nlemmas fsubset_iff_pfsubset_eq = subset_iff_psubset_eq[Transfer.transferred]\nlemmas all_not_fin_conv[simp] = all_not_in_conv[Transfer.transferred]\nlemmas ex_fin_conv = ex_in_conv[Transfer.transferred]\nlemmas fimage_mono = image_mono[Transfer.transferred]\nlemmas fPow_mono = Pow_mono[Transfer.transferred]\nlemmas finsert_mono = insert_mono[Transfer.transferred]\nlemmas funion_mono = Un_mono[Transfer.transferred]\nlemmas finter_mono = Int_mono[Transfer.transferred]\nlemmas fminus_mono = Diff_mono[Transfer.transferred]\nlemmas fin_mono = in_mono[Transfer.transferred]\nlemmas fthe_felem_eq[simp] = the_elem_eq[Transfer.transferred]\nlemmas fLeast_mono = Least_mono[Transfer.transferred]\nlemmas fbind_fbind = bind_bind[Transfer.transferred]\nlemmas fempty_fbind[simp] = empty_bind[Transfer.transferred]\nlemmas nonfempty_fbind_const = nonempty_bind_const[Transfer.transferred]\nlemmas fbind_const = bind_const[Transfer.transferred]\nlemmas ffmember_filter[simp] = member_filter[Transfer.transferred]\nlemmas fequalityI = equalityI[Transfer.transferred]\n\n\nsubsection {* Additional lemmas*}\n\nsubsubsection {* @{text fsingleton} *}\n\nlemmas fsingletonE = fsingletonD [elim_format]\n\n\nsubsubsection {* @{text femepty} *}\n\nlemma fempty_ffilter[simp]: \"ffilter (\\<lambda>_. False) A = {||}\"\nby transfer auto\n\n(* FIXME, transferred doesn't work here *)\nlemma femptyE [elim!]: \"a |\\<in>| {||} \\<Longrightarrow> P\"\n  by simp\n\n\nsubsubsection {* @{text fset} *}\n\nlemmas fset_simps[simp] = bot_fset.rep_eq finsert.rep_eq\n\nlemma finite_fset [simp]: \n  shows \"finite (fset S)\"\n  by transfer simp\n\nlemmas fset_cong = fset_inject\n\nlemma filter_fset [simp]:\n  shows \"fset (ffilter P xs) = Collect P \\<inter> fset xs\"\n  by transfer auto\n\nlemma notin_fset: \"x |\\<notin>| S \\<longleftrightarrow> x \\<notin> fset S\" by (simp add: fmember.rep_eq)\n\nlemmas inter_fset[simp] = inf_fset.rep_eq\n\nlemmas union_fset[simp] = sup_fset.rep_eq\n\nlemmas minus_fset[simp] = minus_fset.rep_eq\n\n\nsubsubsection {* @{text filter_fset} *}\n\nlemma subset_ffilter: \n  \"ffilter P A |\\<subseteq>| ffilter Q A = (\\<forall> x. x |\\<in>| A \\<longrightarrow> P x \\<longrightarrow> Q x)\"\n  by transfer auto\n\nlemma eq_ffilter: \n  \"(ffilter P A = ffilter Q A) = (\\<forall>x. x |\\<in>| A \\<longrightarrow> P x = Q x)\"\n  by transfer auto\n\nlemma pfsubset_ffilter:\n  \"(\\<And>x. x |\\<in>| A \\<Longrightarrow> P x \\<Longrightarrow> Q x) \\<Longrightarrow> (x |\\<in>| A & \\<not> P x & Q x) \\<Longrightarrow> \n    ffilter P A |\\<subset>| ffilter Q A\"\n  unfolding less_fset_def by (auto simp add: subset_ffilter eq_ffilter)\n\n\nsubsubsection {* @{text finsert} *}\n\n(* FIXME, transferred doesn't work here *)\nlemma set_finsert:\n  assumes \"x |\\<in>| A\"\n  obtains B where \"A = finsert x B\" and \"x |\\<notin>| B\"\nusing assms by transfer (metis Set.set_insert finite_insert)\n\nlemma mk_disjoint_finsert: \"a |\\<in>| A \\<Longrightarrow> \\<exists>B. A = finsert a B \\<and> a |\\<notin>| B\"\n  by (rule_tac x = \"A |-| {|a|}\" in exI, blast)\n\n\nsubsubsection {* @{text fimage} *}\n\nlemma subset_fimage_iff: \"(B |\\<subseteq>| f|`|A) = (\\<exists> AA. AA |\\<subseteq>| A \\<and> B = f|`|AA)\"\nby transfer (metis mem_Collect_eq rev_finite_subset subset_image_iff)\n\n\nsubsubsection {* bounded quantification *}\n\nlemma bex_simps [simp, no_atp]:\n  \"\\<And>A P Q. fBex A (\\<lambda>x. P x \\<and> Q) = (fBex A P \\<and> Q)\" \n  \"\\<And>A P Q. fBex A (\\<lambda>x. P \\<and> Q x) = (P \\<and> fBex A Q)\"\n  \"\\<And>P. fBex {||} P = False\" \n  \"\\<And>a B P. fBex (finsert a B) P = (P a \\<or> fBex B P)\"\n  \"\\<And>A P f. fBex (f |`| A) P = fBex A (\\<lambda>x. P (f x))\"\n  \"\\<And>A P. (\\<not> fBex A P) = fBall A (\\<lambda>x. \\<not> P x)\"\nby auto\n\nlemma ball_simps [simp, no_atp]:\n  \"\\<And>A P Q. fBall A (\\<lambda>x. P x \\<or> Q) = (fBall A P \\<or> Q)\"\n  \"\\<And>A P Q. fBall A (\\<lambda>x. P \\<or> Q x) = (P \\<or> fBall A Q)\"\n  \"\\<And>A P Q. fBall A (\\<lambda>x. P \\<longrightarrow> Q x) = (P \\<longrightarrow> fBall A Q)\"\n  \"\\<And>A P Q. fBall A (\\<lambda>x. P x \\<longrightarrow> Q) = (fBex A P \\<longrightarrow> Q)\"\n  \"\\<And>P. fBall {||} P = True\"\n  \"\\<And>a B P. fBall (finsert a B) P = (P a \\<and> fBall B P)\"\n  \"\\<And>A P f. fBall (f |`| A) P = fBall A (\\<lambda>x. P (f x))\"\n  \"\\<And>A P. (\\<not> fBall A P) = fBex A (\\<lambda>x. \\<not> P x)\"\nby auto\n\nlemma atomize_fBall:\n    \"(\\<And>x. x |\\<in>| A ==> P x) == Trueprop (fBall A (\\<lambda>x. P x))\"\napply (simp only: atomize_all atomize_imp)\napply (rule equal_intr_rule)\nby (transfer, simp)+\n\nend\n\n\nsubsubsection {* @{text fcard} *}\n\n(* FIXME: improve transferred to handle bounded meta quantification *)\n\nlemma fcard_fempty:\n  \"fcard {||} = 0\"\n  by transfer (rule card_empty)\n\nlemma fcard_finsert_disjoint:\n  \"x |\\<notin>| A \\<Longrightarrow> fcard (finsert x A) = Suc (fcard A)\"\n  by transfer (rule card_insert_disjoint)\n\nlemma fcard_finsert_if:\n  \"fcard (finsert x A) = (if x |\\<in>| A then fcard A else Suc (fcard A))\"\n  by transfer (rule card_insert_if)\n\nlemma card_0_eq [simp, no_atp]:\n  \"fcard A = 0 \\<longleftrightarrow> A = {||}\"\n  by transfer (rule card_0_eq)\n\nlemma fcard_Suc_fminus1:\n  \"x |\\<in>| A \\<Longrightarrow> Suc (fcard (A |-| {|x|})) = fcard A\"\n  by transfer (rule card_Suc_Diff1)\n\nlemma fcard_fminus_fsingleton:\n  \"x |\\<in>| A \\<Longrightarrow> fcard (A |-| {|x|}) = fcard A - 1\"\n  by transfer (rule card_Diff_singleton)\n\nlemma fcard_fminus_fsingleton_if:\n  \"fcard (A |-| {|x|}) = (if x |\\<in>| A then fcard A - 1 else fcard A)\"\n  by transfer (rule card_Diff_singleton_if)\n\nlemma fcard_fminus_finsert[simp]:\n  assumes \"a |\\<in>| A\" and \"a |\\<notin>| B\"\n  shows \"fcard (A |-| finsert a B) = fcard (A |-| B) - 1\"\nusing assms by transfer (rule card_Diff_insert)\n\nlemma fcard_finsert: \"fcard (finsert x A) = Suc (fcard (A |-| {|x|}))\"\nby transfer (rule card_insert)\n\nlemma fcard_finsert_le: \"fcard A \\<le> fcard (finsert x A)\"\nby transfer (rule card_insert_le)\n\nlemma fcard_mono:\n  \"A |\\<subseteq>| B \\<Longrightarrow> fcard A \\<le> fcard B\"\nby transfer (rule card_mono)\n\nlemma fcard_seteq: \"A |\\<subseteq>| B \\<Longrightarrow> fcard B \\<le> fcard A \\<Longrightarrow> A = B\"\nby transfer (rule card_seteq)\n\nlemma pfsubset_fcard_mono: \"A |\\<subset>| B \\<Longrightarrow> fcard A < fcard B\"\nby transfer (rule psubset_card_mono)\n\nlemma fcard_funion_finter: \n  \"fcard A + fcard B = fcard (A |\\<union>| B) + fcard (A |\\<inter>| B)\"\nby transfer (rule card_Un_Int)\n\nlemma fcard_funion_disjoint:\n  \"A |\\<inter>| B = {||} \\<Longrightarrow> fcard (A |\\<union>| B) = fcard A + fcard B\"\nby transfer (rule card_Un_disjoint)\n\nlemma fcard_funion_fsubset:\n  \"B |\\<subseteq>| A \\<Longrightarrow> fcard (A |-| B) = fcard A - fcard B\"\nby transfer (rule card_Diff_subset)\n\nlemma diff_fcard_le_fcard_fminus:\n  \"fcard A - fcard B \\<le> fcard(A |-| B)\"\nby transfer (rule diff_card_le_card_Diff)\n\nlemma fcard_fminus1_less: \"x |\\<in>| A \\<Longrightarrow> fcard (A |-| {|x|}) < fcard A\"\nby transfer (rule card_Diff1_less)\n\nlemma fcard_fminus2_less:\n  \"x |\\<in>| A \\<Longrightarrow> y |\\<in>| A \\<Longrightarrow> fcard (A |-| {|x|} |-| {|y|}) < fcard A\"\nby transfer (rule card_Diff2_less)\n\nlemma fcard_fminus1_le: \"fcard (A |-| {|x|}) \\<le> fcard A\"\nby transfer (rule card_Diff1_le)\n\nlemma fcard_pfsubset: \"A |\\<subseteq>| B \\<Longrightarrow> fcard A < fcard B \\<Longrightarrow> A < B\"\nby transfer (rule card_psubset)\n\n\nsubsubsection {* @{text ffold} *}\n\n(* FIXME: improve transferred to handle bounded meta quantification *)\n\ncontext comp_fun_commute\nbegin\n  lemmas ffold_empty[simp] = fold_empty[Transfer.transferred]\n\n  lemma ffold_finsert [simp]:\n    assumes \"x |\\<notin>| A\"\n    shows \"ffold f z (finsert x A) = f x (ffold f z A)\"\n    using assms by (transfer fixing: f) (rule fold_insert)\n\n  lemma ffold_fun_left_comm:\n    \"f x (ffold f z A) = ffold f (f x z) A\"\n    by (transfer fixing: f) (rule fold_fun_left_comm)\n\n  lemma ffold_finsert2:\n    \"x |\\<notin>| A \\<Longrightarrow> ffold f z (finsert x A) = ffold f (f x z) A\"\n    by (transfer fixing: f) (rule fold_insert2)\n\n  lemma ffold_rec:\n    assumes \"x |\\<in>| A\"\n    shows \"ffold f z A = f x (ffold f z (A |-| {|x|}))\"\n    using assms by (transfer fixing: f) (rule fold_rec)\n  \n  lemma ffold_finsert_fremove:\n    \"ffold f z (finsert x A) = f x (ffold f z (A |-| {|x|}))\"\n     by (transfer fixing: f) (rule fold_insert_remove)\nend\n\nlemma ffold_fimage:\n  assumes \"inj_on g (fset A)\"\n  shows \"ffold f z (g |`| A) = ffold (f \\<circ> g) z A\"\nusing assms by transfer' (rule fold_image)\n\nlemma ffold_cong:\n  assumes \"comp_fun_commute f\" \"comp_fun_commute g\"\n  \"\\<And>x. x |\\<in>| A \\<Longrightarrow> f x = g x\"\n    and \"s = t\" and \"A = B\"\n  shows \"ffold f s A = ffold g t B\"\nusing assms by transfer (metis Finite_Set.fold_cong)\n\ncontext comp_fun_idem\nbegin\n\n  lemma ffold_finsert_idem:\n    \"ffold f z (finsert x A) = f x (ffold f z A)\"\n    by (transfer fixing: f) (rule fold_insert_idem)\n  \n  declare ffold_finsert [simp del] ffold_finsert_idem [simp]\n  \n  lemma ffold_finsert_idem2:\n    \"ffold f z (finsert x A) = ffold f (f x z) A\"\n    by (transfer fixing: f) (rule fold_insert_idem2)\n\nend\n\n\nsubsection {* Choice in fsets *}\n\nlemma fset_choice: \n  assumes \"\\<forall>x. x |\\<in>| A \\<longrightarrow> (\\<exists>y. P x y)\"\n  shows \"\\<exists>f. \\<forall>x. x |\\<in>| A \\<longrightarrow> P x (f x)\"\n  using assms by transfer metis\n\n\nsubsection {* Induction and Cases rules for fsets *}\n\nlemma fset_exhaust [case_names empty insert, cases type: fset]:\n  assumes fempty_case: \"S = {||} \\<Longrightarrow> P\" \n  and     finsert_case: \"\\<And>x S'. S = finsert x S' \\<Longrightarrow> P\"\n  shows \"P\"\n  using assms by transfer blast\n\nlemma fset_induct [case_names empty insert]:\n  assumes fempty_case: \"P {||}\"\n  and     finsert_case: \"\\<And>x S. P S \\<Longrightarrow> P (finsert x S)\"\n  shows \"P S\"\nproof -\n  (* FIXME transfer and right_total vs. bi_total *)\n  note Domainp_forall_transfer[transfer_rule]\n  show ?thesis\n  using assms by transfer (auto intro: finite_induct)\nqed\n\nlemma fset_induct_stronger [case_names empty insert, induct type: fset]:\n  assumes empty_fset_case: \"P {||}\"\n  and     insert_fset_case: \"\\<And>x S. \\<lbrakk>x |\\<notin>| S; P S\\<rbrakk> \\<Longrightarrow> P (finsert x S)\"\n  shows \"P S\"\nproof -\n  (* FIXME transfer and right_total vs. bi_total *)\n  note Domainp_forall_transfer[transfer_rule]\n  show ?thesis\n  using assms by transfer (auto intro: finite_induct)\nqed\n\nlemma fset_card_induct:\n  assumes empty_fset_case: \"P {||}\"\n  and     card_fset_Suc_case: \"\\<And>S T. Suc (fcard S) = (fcard T) \\<Longrightarrow> P S \\<Longrightarrow> P T\"\n  shows \"P S\"\nproof (induct S)\n  case empty\n  show \"P {||}\" by (rule empty_fset_case)\nnext\n  case (insert x S)\n  have h: \"P S\" by fact\n  have \"x |\\<notin>| S\" by fact\n  then have \"Suc (fcard S) = fcard (finsert x S)\" \n    by transfer auto\n  then show \"P (finsert x S)\" \n    using h card_fset_Suc_case by simp\nqed\n\nlemma fset_strong_cases:\n  obtains \"xs = {||}\"\n    | ys x where \"x |\\<notin>| ys\" and \"xs = finsert x ys\"\nby transfer blast\n\nlemma fset_induct2:\n  \"P {||} {||} \\<Longrightarrow>\n  (\\<And>x xs. x |\\<notin>| xs \\<Longrightarrow> P (finsert x xs) {||}) \\<Longrightarrow>\n  (\\<And>y ys. y |\\<notin>| ys \\<Longrightarrow> P {||} (finsert y ys)) \\<Longrightarrow>\n  (\\<And>x xs y ys. \\<lbrakk>P xs ys; x |\\<notin>| xs; y |\\<notin>| ys\\<rbrakk> \\<Longrightarrow> P (finsert x xs) (finsert y ys)) \\<Longrightarrow>\n  P xsa ysa\"\n  apply (induct xsa arbitrary: ysa)\n  apply (induct_tac x rule: fset_induct_stronger)\n  apply simp_all\n  apply (induct_tac xa rule: fset_induct_stronger)\n  apply simp_all\n  done\n\n\nsubsection {* Setup for Lifting/Transfer *}\n\nsubsubsection {* Relator and predicator properties *}\n\nlift_definition rel_fset :: \"('a \\<Rightarrow> 'b \\<Rightarrow> bool) \\<Rightarrow> 'a fset \\<Rightarrow> 'b fset \\<Rightarrow> bool\" is rel_set\nparametric rel_set_transfer .\n\nlemma rel_fset_alt_def: \"rel_fset R = (\\<lambda>A B. (\\<forall>x.\\<exists>y. x|\\<in>|A \\<longrightarrow> y|\\<in>|B \\<and> R x y) \n  \\<and> (\\<forall>y. \\<exists>x. y|\\<in>|B \\<longrightarrow> x|\\<in>|A \\<and> R x y))\"\napply (rule ext)+\napply transfer'\napply (subst rel_set_def[unfolded fun_eq_iff]) \nby blast\n\nlemma finite_rel_set:\n  assumes fin: \"finite X\" \"finite Z\"\n  assumes R_S: \"rel_set (R OO S) X Z\"\n  shows \"\\<exists>Y. finite Y \\<and> rel_set R X Y \\<and> rel_set S Y Z\"\nproof -\n  obtain f where f: \"\\<forall>x\\<in>X. R x (f x) \\<and> (\\<exists>z\\<in>Z. S (f x) z)\"\n  apply atomize_elim\n  apply (subst bchoice_iff[symmetric])\n  using R_S[unfolded rel_set_def OO_def] by blast\n  \n  obtain g where g: \"\\<forall>z\\<in>Z. S (g z) z \\<and> (\\<exists>x\\<in>X. R x (g z))\"\n  apply atomize_elim\n  apply (subst bchoice_iff[symmetric])\n  using R_S[unfolded rel_set_def OO_def] by blast\n  \n  let ?Y = \"f ` X \\<union> g ` Z\"\n  have \"finite ?Y\" by (simp add: fin)\n  moreover have \"rel_set R X ?Y\"\n    unfolding rel_set_def\n    using f g by clarsimp blast\n  moreover have \"rel_set S ?Y Z\"\n    unfolding rel_set_def\n    using f g by clarsimp blast\n  ultimately show ?thesis by metis\nqed\n\nsubsubsection {* Transfer rules for the Transfer package *}\n\ntext {* Unconditional transfer rules *}\n\ncontext\nbegin\n\ninterpretation lifting_syntax .\n\nlemmas fempty_transfer [transfer_rule] = empty_transfer[Transfer.transferred]\n\nlemma finsert_transfer [transfer_rule]:\n  \"(A ===> rel_fset A ===> rel_fset A) finsert finsert\"\n  unfolding rel_fun_def rel_fset_alt_def by blast\n\nlemma funion_transfer [transfer_rule]:\n  \"(rel_fset A ===> rel_fset A ===> rel_fset A) funion funion\"\n  unfolding rel_fun_def rel_fset_alt_def by blast\n\nlemma ffUnion_transfer [transfer_rule]:\n  \"(rel_fset (rel_fset A) ===> rel_fset A) ffUnion ffUnion\"\n  unfolding rel_fun_def rel_fset_alt_def by transfer (simp, fast)\n\nlemma fimage_transfer [transfer_rule]:\n  \"((A ===> B) ===> rel_fset A ===> rel_fset B) fimage fimage\"\n  unfolding rel_fun_def rel_fset_alt_def by simp blast\n\nlemma fBall_transfer [transfer_rule]:\n  \"(rel_fset A ===> (A ===> op =) ===> op =) fBall fBall\"\n  unfolding rel_fset_alt_def rel_fun_def by blast\n\nlemma fBex_transfer [transfer_rule]:\n  \"(rel_fset A ===> (A ===> op =) ===> op =) fBex fBex\"\n  unfolding rel_fset_alt_def rel_fun_def by blast\n\n(* FIXME transfer doesn't work here *)\nlemma fPow_transfer [transfer_rule]:\n  \"(rel_fset A ===> rel_fset (rel_fset A)) fPow fPow\"\n  unfolding rel_fun_def\n  using Pow_transfer[unfolded rel_fun_def, rule_format, Transfer.transferred]\n  by blast\n\nlemma rel_fset_transfer [transfer_rule]:\n  \"((A ===> B ===> op =) ===> rel_fset A ===> rel_fset B ===> op =)\n    rel_fset rel_fset\"\n  unfolding rel_fun_def\n  using rel_set_transfer[unfolded rel_fun_def,rule_format, Transfer.transferred, where A = A and B = B]\n  by simp\n\nlemma bind_transfer [transfer_rule]:\n  \"(rel_fset A ===> (A ===> rel_fset B) ===> rel_fset B) fbind fbind\"\n  using assms unfolding rel_fun_def\n  using bind_transfer[unfolded rel_fun_def, rule_format, Transfer.transferred] by blast\n\ntext {* Rules requiring bi-unique, bi-total or right-total relations *}\n\nlemma fmember_transfer [transfer_rule]:\n  assumes \"bi_unique A\"\n  shows \"(A ===> rel_fset A ===> op =) (op |\\<in>|) (op |\\<in>|)\"\n  using assms unfolding rel_fun_def rel_fset_alt_def bi_unique_def by metis\n\nlemma finter_transfer [transfer_rule]:\n  assumes \"bi_unique A\"\n  shows \"(rel_fset A ===> rel_fset A ===> rel_fset A) finter finter\"\n  using assms unfolding rel_fun_def\n  using inter_transfer[unfolded rel_fun_def, rule_format, Transfer.transferred] by blast\n\nlemma fminus_transfer [transfer_rule]:\n  assumes \"bi_unique A\"\n  shows \"(rel_fset A ===> rel_fset A ===> rel_fset A) (op |-|) (op |-|)\"\n  using assms unfolding rel_fun_def\n  using Diff_transfer[unfolded rel_fun_def, rule_format, Transfer.transferred] by blast\n\nlemma fsubset_transfer [transfer_rule]:\n  assumes \"bi_unique A\"\n  shows \"(rel_fset A ===> rel_fset A ===> op =) (op |\\<subseteq>|) (op |\\<subseteq>|)\"\n  using assms unfolding rel_fun_def\n  using subset_transfer[unfolded rel_fun_def, rule_format, Transfer.transferred] by blast\n\nlemma fSup_transfer [transfer_rule]:\n  \"bi_unique A \\<Longrightarrow> (rel_set (rel_fset A) ===> rel_fset A) Sup Sup\"\n  using assms unfolding rel_fun_def\n  apply clarify\n  apply transfer'\n  using Sup_fset_transfer[unfolded rel_fun_def] by blast\n\n(* FIXME: add right_total_fInf_transfer *)\n\nlemma fInf_transfer [transfer_rule]:\n  assumes \"bi_unique A\" and \"bi_total A\"\n  shows \"(rel_set (rel_fset A) ===> rel_fset A) Inf Inf\"\n  using assms unfolding rel_fun_def\n  apply clarify\n  apply transfer'\n  using Inf_fset_transfer[unfolded rel_fun_def] by blast\n\nlemma ffilter_transfer [transfer_rule]:\n  assumes \"bi_unique A\"\n  shows \"((A ===> op=) ===> rel_fset A ===> rel_fset A) ffilter ffilter\"\n  using assms unfolding rel_fun_def\n  using Lifting_Set.filter_transfer[unfolded rel_fun_def, rule_format, Transfer.transferred] by blast\n\nlemma card_transfer [transfer_rule]:\n  \"bi_unique A \\<Longrightarrow> (rel_fset A ===> op =) fcard fcard\"\n  using assms unfolding rel_fun_def\n  using card_transfer[unfolded rel_fun_def, rule_format, Transfer.transferred] by blast\n\nend\n\nlifting_update fset.lifting\nlifting_forget fset.lifting\n\n\nsubsection {* BNF setup *}\n\ncontext\nincludes fset.lifting\nbegin\n\nlemma rel_fset_alt:\n  \"rel_fset R a b \\<longleftrightarrow> (\\<forall>t \\<in> fset a. \\<exists>u \\<in> fset b. R t u) \\<and> (\\<forall>t \\<in> fset b. \\<exists>u \\<in> fset a. R u t)\"\nby transfer (simp add: rel_set_def)\n\nlemma fset_to_fset: \"finite A \\<Longrightarrow> fset (the_inv fset A) = A\"\napply (rule f_the_inv_into_f[unfolded inj_on_def])\napply (simp add: fset_inject)\napply (rule range_eqI Abs_fset_inverse[symmetric] CollectI)+\n.\n\nlemma rel_fset_aux:\n\"(\\<forall>t \\<in> fset a. \\<exists>u \\<in> fset b. R t u) \\<and> (\\<forall>u \\<in> fset b. \\<exists>t \\<in> fset a. R t u) \\<longleftrightarrow>\n ((BNF_Def.Grp {a. fset a \\<subseteq> {(a, b). R a b}} (fimage fst))\\<inverse>\\<inverse> OO\n  BNF_Def.Grp {a. fset a \\<subseteq> {(a, b). R a b}} (fimage snd)) a b\" (is \"?L = ?R\")\nproof\n  assume ?L\n  def R' \\<equiv> \"the_inv fset (Collect (split R) \\<inter> (fset a \\<times> fset b))\" (is \"the_inv fset ?L'\")\n  have \"finite ?L'\" by (intro finite_Int[OF disjI2] finite_cartesian_product) (transfer, simp)+\n  hence *: \"fset R' = ?L'\" unfolding R'_def by (intro fset_to_fset)\n  show ?R unfolding Grp_def relcompp.simps conversep.simps\n  proof (intro CollectI case_prodI exI[of _ a] exI[of _ b] exI[of _ R'] conjI refl)\n    from * show \"a = fimage fst R'\" using conjunct1[OF `?L`]\n      by (transfer, auto simp add: image_def Int_def split: prod.splits)\n    from * show \"b = fimage snd R'\" using conjunct2[OF `?L`]\n      by (transfer, auto simp add: image_def Int_def split: prod.splits)\n  qed (auto simp add: *)\nnext\n  assume ?R thus ?L unfolding Grp_def relcompp.simps conversep.simps\n  apply (simp add: subset_eq Ball_def)\n  apply (rule conjI)\n  apply (transfer, clarsimp, metis snd_conv)\n  by (transfer, clarsimp, metis fst_conv)\nqed\n\nbnf \"'a fset\"\n  map: fimage\n  sets: fset \n  bd: natLeq\n  wits: \"{||}\"\n  rel: rel_fset\napply -\n          apply transfer' apply simp\n         apply transfer' apply force\n        apply transfer apply force\n       apply transfer' apply force\n      apply (rule natLeq_card_order)\n     apply (rule natLeq_cinfinite)\n    apply transfer apply (metis ordLess_imp_ordLeq finite_iff_ordLess_natLeq)\n   apply (fastforce simp: rel_fset_alt)\n apply (simp add: Grp_def relcompp.simps conversep.simps fun_eq_iff rel_fset_alt rel_fset_aux) \napply transfer apply simp\ndone\n\nlemma rel_fset_fset: \"rel_set \\<chi> (fset A1) (fset A2) = rel_fset \\<chi> A1 A2\"\n  by transfer (rule refl)\n\nend\n\nlemmas [simp] = fset.map_comp fset.map_id fset.set_map\n\n\nsubsection {* Size setup *}\n\ncontext includes fset.lifting begin\nlift_definition size_fset :: \"('a \\<Rightarrow> nat) \\<Rightarrow> 'a fset \\<Rightarrow> nat\" is \"\\<lambda>f. setsum (Suc \\<circ> f)\" .\nend\n\ninstantiation fset :: (type) size begin\ndefinition size_fset where\n  size_fset_overloaded_def: \"size_fset = FSet.size_fset (\\<lambda>_. 0)\"\ninstance ..\nend\n\nlemmas size_fset_simps[simp] =\n  size_fset_def[THEN meta_eq_to_obj_eq, THEN fun_cong, THEN fun_cong,\n    unfolded map_fun_def comp_def id_apply]\n\nlemmas size_fset_overloaded_simps[simp] =\n  size_fset_simps[of \"\\<lambda>_. 0\", unfolded add_0_left add_0_right,\n    folded size_fset_overloaded_def]\n\nlemma fset_size_o_map: \"inj f \\<Longrightarrow> size_fset g \\<circ> fimage f = size_fset (g \\<circ> f)\"\n  unfolding size_fset_def fimage_def\n  by (auto simp: Abs_fset_inverse setsum.reindex_cong[OF subset_inj_on[OF _ top_greatest]])\n\nsetup {*\nBNF_LFP_Size.register_size_global @{type_name fset} @{const_name size_fset}\n  @{thms size_fset_simps size_fset_overloaded_simps} @{thms fset_size_o_map}\n*}\n\n\nsubsection {* Advanced relator customization *}\n\n(* Set vs. sum relators: *)\n\nlemma rel_set_rel_sum[simp]: \n\"rel_set (rel_sum \\<chi> \\<phi>) A1 A2 \\<longleftrightarrow> \n rel_set \\<chi> (Inl -` A1) (Inl -` A2) \\<and> rel_set \\<phi> (Inr -` A1) (Inr -` A2)\"\n(is \"?L \\<longleftrightarrow> ?Rl \\<and> ?Rr\")\nproof safe\n  assume L: \"?L\"\n  show ?Rl unfolding rel_set_def Bex_def vimage_eq proof safe\n    fix l1 assume \"Inl l1 \\<in> A1\"\n    then obtain a2 where a2: \"a2 \\<in> A2\" and \"rel_sum \\<chi> \\<phi> (Inl l1) a2\"\n    using L unfolding rel_set_def by auto\n    then obtain l2 where \"a2 = Inl l2 \\<and> \\<chi> l1 l2\" by (cases a2, auto)\n    thus \"\\<exists> l2. Inl l2 \\<in> A2 \\<and> \\<chi> l1 l2\" using a2 by auto\n  next\n    fix l2 assume \"Inl l2 \\<in> A2\"\n    then obtain a1 where a1: \"a1 \\<in> A1\" and \"rel_sum \\<chi> \\<phi> a1 (Inl l2)\"\n    using L unfolding rel_set_def by auto\n    then obtain l1 where \"a1 = Inl l1 \\<and> \\<chi> l1 l2\" by (cases a1, auto)\n    thus \"\\<exists> l1. Inl l1 \\<in> A1 \\<and> \\<chi> l1 l2\" using a1 by auto\n  qed\n  show ?Rr unfolding rel_set_def Bex_def vimage_eq proof safe\n    fix r1 assume \"Inr r1 \\<in> A1\"\n    then obtain a2 where a2: \"a2 \\<in> A2\" and \"rel_sum \\<chi> \\<phi> (Inr r1) a2\"\n    using L unfolding rel_set_def by auto\n    then obtain r2 where \"a2 = Inr r2 \\<and> \\<phi> r1 r2\" by (cases a2, auto)\n    thus \"\\<exists> r2. Inr r2 \\<in> A2 \\<and> \\<phi> r1 r2\" using a2 by auto\n  next\n    fix r2 assume \"Inr r2 \\<in> A2\"\n    then obtain a1 where a1: \"a1 \\<in> A1\" and \"rel_sum \\<chi> \\<phi> a1 (Inr r2)\"\n    using L unfolding rel_set_def by auto\n    then obtain r1 where \"a1 = Inr r1 \\<and> \\<phi> r1 r2\" by (cases a1, auto)\n    thus \"\\<exists> r1. Inr r1 \\<in> A1 \\<and> \\<phi> r1 r2\" using a1 by auto\n  qed\nnext\n  assume Rl: \"?Rl\" and Rr: \"?Rr\"\n  show ?L unfolding rel_set_def Bex_def vimage_eq proof safe\n    fix a1 assume a1: \"a1 \\<in> A1\"\n    show \"\\<exists> a2. a2 \\<in> A2 \\<and> rel_sum \\<chi> \\<phi> a1 a2\"\n    proof(cases a1)\n      case (Inl l1) then obtain l2 where \"Inl l2 \\<in> A2 \\<and> \\<chi> l1 l2\"\n      using Rl a1 unfolding rel_set_def by blast\n      thus ?thesis unfolding Inl by auto\n    next\n      case (Inr r1) then obtain r2 where \"Inr r2 \\<in> A2 \\<and> \\<phi> r1 r2\"\n      using Rr a1 unfolding rel_set_def by blast\n      thus ?thesis unfolding Inr by auto\n    qed\n  next\n    fix a2 assume a2: \"a2 \\<in> A2\"\n    show \"\\<exists> a1. a1 \\<in> A1 \\<and> rel_sum \\<chi> \\<phi> a1 a2\"\n    proof(cases a2)\n      case (Inl l2) then obtain l1 where \"Inl l1 \\<in> A1 \\<and> \\<chi> l1 l2\"\n      using Rl a2 unfolding rel_set_def by blast\n      thus ?thesis unfolding Inl by auto\n    next\n      case (Inr r2) then obtain r1 where \"Inr r1 \\<in> A1 \\<and> \\<phi> r1 r2\"\n      using Rr a2 unfolding rel_set_def by blast\n      thus ?thesis unfolding Inr by auto\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/FSet.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357563664174, "lm_q2_score": 0.8128673201042493, "lm_q1q2_score": 0.7047850317121306}}
{"text": "(*  Author:  LCP, ported from HOL Light\n*)\n\nsection\\<open>Euclidean space and n-spheres, as subtopologies of n-dimensional space\\<close>\n\ntheory Abstract_Euclidean_Space\nimports Homotopy Locally\nbegin\n\nsubsection \\<open>Euclidean spaces as abstract topologies\\<close>\n\ndefinition Euclidean_space :: \"nat \\<Rightarrow> (nat \\<Rightarrow> real) topology\"\n  where \"Euclidean_space n \\<equiv> subtopology (powertop_real UNIV) {x. \\<forall>i\\<ge>n. x i = 0}\"\n\nlemma topspace_Euclidean_space:\n   \"topspace(Euclidean_space n) = {x. \\<forall>i\\<ge>n. x i = 0}\"\n  by (simp add: Euclidean_space_def)\n\nlemma nonempty_Euclidean_space: \"topspace(Euclidean_space n) \\<noteq> {}\"\n  by (force simp: topspace_Euclidean_space)\n\nlemma subset_Euclidean_space [simp]:\n   \"topspace(Euclidean_space m) \\<subseteq> topspace(Euclidean_space n) \\<longleftrightarrow> m \\<le> n\"\n  apply (simp add: topspace_Euclidean_space subset_iff, safe)\n   apply (drule_tac x=\"(\\<lambda>i. if i < m then 1 else 0)\" in spec)\n   apply auto\n  using not_less by fastforce\n\nlemma topspace_Euclidean_space_alt:\n  \"topspace(Euclidean_space n) = (\\<Inter>i \\<in> {n..}. {x. x \\<in> topspace(powertop_real UNIV) \\<and> x i \\<in> {0}})\"\n  by (auto simp: topspace_Euclidean_space)\n\nlemma closedin_Euclidean_space:\n  \"closedin (powertop_real UNIV) (topspace(Euclidean_space n))\"\nproof -\n  have \"closedin (powertop_real UNIV) {x. x i = 0}\" if \"n \\<le> i\" for i\n  proof -\n    have \"closedin (powertop_real UNIV) {x \\<in> topspace (powertop_real UNIV). x i \\<in> {0}}\"\n    proof (rule closedin_continuous_map_preimage)\n      show \"continuous_map (powertop_real UNIV) euclideanreal (\\<lambda>x. x i)\"\n        by (metis UNIV_I continuous_map_product_coordinates)\n      show \"closedin euclideanreal {0}\"\n        by simp\n    qed\n    then show ?thesis\n      by auto\n  qed\n  then show ?thesis\n    unfolding topspace_Euclidean_space_alt\n    by force\nqed\n\nlemma closedin_Euclidean_imp_closed: \"closedin (Euclidean_space m) S \\<Longrightarrow> closed S\"\n  by (metis Euclidean_space_def closed_closedin closedin_Euclidean_space closedin_closed_subtopology euclidean_product_topology topspace_Euclidean_space)\n\nlemma closedin_Euclidean_space_iff:\n  \"closedin (Euclidean_space m) S \\<longleftrightarrow> closed S \\<and> S \\<subseteq> topspace (Euclidean_space m)\"\n  (is \"?lhs \\<longleftrightarrow> ?rhs\")\nproof\n  show \"?lhs \\<Longrightarrow> ?rhs\"\n    using closedin_closed_subtopology topspace_Euclidean_space\n    by (fastforce simp: topspace_Euclidean_space_alt closedin_Euclidean_imp_closed)\n  show \"?rhs \\<Longrightarrow> ?lhs\"\n  apply (simp add: closedin_subtopology Euclidean_space_def)\n    by (metis (no_types) closed_closedin euclidean_product_topology inf.orderE)\nqed\n\nlemma continuous_map_componentwise_Euclidean_space:\n  \"continuous_map X (Euclidean_space n) (\\<lambda>x i. if i < n then f x i else 0) \\<longleftrightarrow>\n   (\\<forall>i < n. continuous_map X euclideanreal (\\<lambda>x. f x i))\"\nproof -\n  have *: \"continuous_map X euclideanreal (\\<lambda>x. if k < n then f x k else 0)\"\n    if \"\\<And>i. i<n \\<Longrightarrow> continuous_map X euclideanreal (\\<lambda>x. f x i)\" for k\n    by (intro continuous_intros that)\n  show ?thesis\n    unfolding Euclidean_space_def continuous_map_in_subtopology\n    by (fastforce simp: continuous_map_componentwise_UNIV * elim: continuous_map_eq)\nqed\n\nlemma continuous_map_Euclidean_space_add [continuous_intros]:\n   \"\\<lbrakk>continuous_map X (Euclidean_space n) f; continuous_map X (Euclidean_space n) g\\<rbrakk>\n    \\<Longrightarrow> continuous_map X (Euclidean_space n) (\\<lambda>x i. f x i + g x i)\"\n  unfolding Euclidean_space_def continuous_map_in_subtopology\n  by (fastforce simp add: continuous_map_componentwise_UNIV continuous_map_add)\n\nlemma continuous_map_Euclidean_space_diff [continuous_intros]:\n   \"\\<lbrakk>continuous_map X (Euclidean_space n) f; continuous_map X (Euclidean_space n) g\\<rbrakk>\n    \\<Longrightarrow> continuous_map X (Euclidean_space n) (\\<lambda>x i. f x i - g x i)\"\n  unfolding Euclidean_space_def continuous_map_in_subtopology\n  by (fastforce simp add: continuous_map_componentwise_UNIV continuous_map_diff)\n\nlemma continuous_map_Euclidean_space_iff:\n  \"continuous_map (Euclidean_space m) euclidean g\n   = continuous_on (topspace (Euclidean_space m)) g\"\nproof\n  assume \"continuous_map (Euclidean_space m) euclidean g\"\n  then have \"continuous_map (top_of_set {f. \\<forall>n\\<ge>m. f n = 0}) euclidean g\"\n    by (simp add: Euclidean_space_def euclidean_product_topology)\n  then show \"continuous_on (topspace (Euclidean_space m)) g\"\n    by (metis continuous_map_subtopology_eu subtopology_topspace topspace_Euclidean_space)\nnext\n  assume \"continuous_on (topspace (Euclidean_space m)) g\"\n  then have \"continuous_map (top_of_set {f. \\<forall>n\\<ge>m. f n = 0}) euclidean g\"\n    by (metis (lifting) continuous_map_into_fulltopology continuous_map_subtopology_eu order_refl topspace_Euclidean_space)\n  then show \"continuous_map (Euclidean_space m) euclidean g\"\n    by (simp add: Euclidean_space_def euclidean_product_topology)\nqed\n\nlemma cm_Euclidean_space_iff_continuous_on:\n  \"continuous_map (subtopology (Euclidean_space m) S) (Euclidean_space n) f\n   \\<longleftrightarrow> continuous_on (topspace (subtopology (Euclidean_space m) S)) f \\<and>\n       f ` (topspace (subtopology (Euclidean_space m) S)) \\<subseteq> topspace (Euclidean_space n)\"\n  (is \"?P \\<longleftrightarrow> ?Q \\<and> ?R\")\nproof -\n  have ?Q if ?P\n  proof -\n    have \"\\<And>n. Euclidean_space n = top_of_set {f. \\<forall>m\\<ge>n. f m = 0}\"\n      by (simp add: Euclidean_space_def euclidean_product_topology)\n    with that show ?thesis\n      by (simp add: subtopology_subtopology)\n  qed\n  moreover\n  have ?R if ?P\n    using that by (simp add: image_subset_iff continuous_map_def)\n  moreover\n  have ?P if ?Q ?R\n  proof -\n    have \"continuous_map (top_of_set (topspace (subtopology (subtopology (powertop_real UNIV) {f. \\<forall>n\\<ge>m. f n = 0}) S))) (top_of_set (topspace (subtopology (powertop_real UNIV) {f. \\<forall>na\\<ge>n. f na = 0}))) f\"\n      using Euclidean_space_def that by auto\n    then show ?thesis\n      by (simp add: Euclidean_space_def euclidean_product_topology subtopology_subtopology)\n  qed\n  ultimately show ?thesis\n    by auto\nqed\n\nlemma homeomorphic_Euclidean_space_product_topology:\n  \"Euclidean_space n homeomorphic_space product_topology (\\<lambda>i. euclideanreal) {..<n}\"\nproof -\n  have cm: \"continuous_map (product_topology (\\<lambda>i. euclideanreal) {..<n})\n          euclideanreal (\\<lambda>x. if k < n then x k else 0)\" for k\n    by (auto intro: continuous_map_if continuous_map_product_projection)\n  show ?thesis\n    unfolding homeomorphic_space_def homeomorphic_maps_def\n    apply (rule_tac x=\"\\<lambda>f. restrict f {..<n}\" in exI)\n    apply (rule_tac x=\"\\<lambda>f i. if i < n then f i else 0\" in exI)\n    apply (simp add: Euclidean_space_def continuous_map_in_subtopology)\n    apply (intro conjI continuous_map_from_subtopology)\n       apply (force simp: continuous_map_componentwise cm intro: continuous_map_product_projection)+\n    done\nqed\n\nlemma contractible_Euclidean_space [simp]: \"contractible_space (Euclidean_space n)\"\n  using homeomorphic_Euclidean_space_product_topology contractible_space_euclideanreal\n    contractible_space_product_topology homeomorphic_space_contractibility by blast\n\nlemma path_connected_Euclidean_space: \"path_connected_space (Euclidean_space n)\"\n  by (simp add: contractible_imp_path_connected_space)\n\nlemma connected_Euclidean_space: \"connected_space (Euclidean_space n)\"\n  by (simp add: contractible_imp_connected_space)\n\nlemma locally_path_connected_Euclidean_space:\n   \"locally_path_connected_space (Euclidean_space n)\"\n  apply (simp add: homeomorphic_locally_path_connected_space [OF homeomorphic_Euclidean_space_product_topology [of n]]\n                   locally_path_connected_space_product_topology)\n  using locally_path_connected_space_euclideanreal by auto\n\nlemma compact_Euclidean_space:\n   \"compact_space (Euclidean_space n) \\<longleftrightarrow> n = 0\"\n  by (auto simp: homeomorphic_compact_space [OF homeomorphic_Euclidean_space_product_topology] compact_space_product_topology)\n\n\nsubsection\\<open>n-dimensional spheres\\<close>\n\ndefinition nsphere where\n \"nsphere n \\<equiv> subtopology (Euclidean_space (Suc n)) { x. (\\<Sum>i\\<le>n. x i ^ 2) = 1 }\"\n\nlemma nsphere:\n   \"nsphere n = subtopology (powertop_real UNIV)\n                            {x. (\\<Sum>i\\<le>n. x i ^ 2) = 1 \\<and> (\\<forall>i>n. x i = 0)}\"\n  by (simp add: nsphere_def Euclidean_space_def subtopology_subtopology Suc_le_eq Collect_conj_eq Int_commute)\n\nlemma continuous_map_nsphere_projection: \"continuous_map (nsphere n) euclideanreal (\\<lambda>x. x k)\"\n  unfolding nsphere\n  by (blast intro: continuous_map_from_subtopology [OF continuous_map_product_projection])\n\nlemma in_topspace_nsphere: \"(\\<lambda>n. if n = 0 then 1 else 0) \\<in> topspace (nsphere n)\"\n  by (simp add: nsphere_def topspace_Euclidean_space power2_eq_square if_distrib [where f = \"\\<lambda>x. x * _\"] cong: if_cong)\n\nlemma nonempty_nsphere [simp]: \"~ (topspace(nsphere n) = {})\"\n  using in_topspace_nsphere by auto\n\nlemma subtopology_nsphere_equator:\n  \"subtopology (nsphere (Suc n)) {x. x(Suc n) = 0} = nsphere n\"\nproof -\n  have \"({x. (\\<Sum>i\\<le>n. (x i)\\<^sup>2) + (x (Suc n))\\<^sup>2 = 1 \\<and> (\\<forall>i>Suc n. x i = 0)} \\<inter> {x. x (Suc n) = 0})\n      = {x. (\\<Sum>i\\<le>n. (x i)\\<^sup>2) = 1 \\<and> (\\<forall>i>n. x i = (0::real))}\"\n    using Suc_lessI [of n] by (fastforce simp: set_eq_iff)\n  then show ?thesis\n    by (simp add: nsphere subtopology_subtopology)\nqed\n\nlemma topspace_nsphere_minus1:\n  assumes x: \"x \\<in> topspace (nsphere n)\" and \"x n = 0\"\n  shows \"x \\<in> topspace (nsphere (n - Suc 0))\"\nproof (cases \"n = 0\")\n  case True\n  then show ?thesis\n    using x by auto\nnext\n  case False\n  have subt_eq: \"nsphere (n - Suc 0) = subtopology (nsphere n) {x. x n = 0}\"\n    by (metis False Suc_pred le_zero_eq not_le subtopology_nsphere_equator)\n  with x show ?thesis\n    by (simp add: assms)\nqed\n\nlemma continuous_map_nsphere_reflection:\n  \"continuous_map (nsphere n) (nsphere n) (\\<lambda>x i. if i = k then -x i else x i)\"\nproof -\n  have cm: \"continuous_map (powertop_real UNIV) euclideanreal (\\<lambda>x. if j = k then - x j else x j)\" for j\n  proof (cases \"j=k\")\n    case True\n    then show ?thesis\n      by simp (metis UNIV_I continuous_map_product_projection)\n  next\n    case False\n    then show ?thesis\n      by (auto intro: continuous_map_product_projection)\n  qed\n  have eq: \"(if i = k then x k * x k else x i * x i) = x i * x i\" for i and x :: \"nat \\<Rightarrow> real\"\n    by simp\n  show ?thesis\n    apply (simp add: nsphere continuous_map_in_subtopology continuous_map_componentwise_UNIV\n                     continuous_map_from_subtopology cm)\n    apply (intro conjI allI impI continuous_intros continuous_map_from_subtopology continuous_map_product_projection)\n      apply (auto simp: power2_eq_square if_distrib [where f = \"\\<lambda>x. x * _\"] eq cong: if_cong)\n    done\nqed\n\n\nproposition contractible_space_upper_hemisphere:\n  assumes \"k \\<le> n\"\n  shows \"contractible_space(subtopology (nsphere n) {x. x k \\<ge> 0})\"\nproof -\n  define p:: \"nat \\<Rightarrow> real\" where \"p \\<equiv> \\<lambda>i. if i = k then 1 else 0\"\n  have \"p \\<in> topspace(nsphere n)\"\n    using assms\n    by (simp add: nsphere p_def power2_eq_square if_distrib [where f = \"\\<lambda>x. x * _\"] cong: if_cong)\n  let ?g = \"\\<lambda>x i. x i / sqrt(\\<Sum>j\\<le>n. x j ^ 2)\"\n  let ?h = \"\\<lambda>(t,q) i. (1 - t) * q i + t * p i\"\n  let ?Y = \"subtopology (Euclidean_space (Suc n)) {x. 0 \\<le> x k \\<and> (\\<exists>i\\<le>n. x i \\<noteq> 0)}\"\n  have \"continuous_map (prod_topology (top_of_set {0..1}) (subtopology (nsphere n) {x. 0 \\<le> x k}))\n                       (subtopology (nsphere n) {x. 0 \\<le> x k}) (?g \\<circ> ?h)\"\n  proof (rule continuous_map_compose)\n    have *: \"\\<lbrakk>0 \\<le> b k; (\\<Sum>i\\<le>n. (b i)\\<^sup>2) = 1; \\<forall>i>n. b i = 0; 0 \\<le> a; a \\<le> 1\\<rbrakk>\n           \\<Longrightarrow> \\<exists>i. (i = k \\<longrightarrow> (1 - a) * b k + a \\<noteq> 0) \\<and>\n                   (i \\<noteq> k \\<longrightarrow> i \\<le> n \\<and> a \\<noteq> 1 \\<and> b i \\<noteq> 0)\" for a::real and b\n      apply (cases \"a \\<noteq> 1 \\<and> b k = 0\"; simp)\n       apply (metis (no_types, lifting) atMost_iff sum.neutral zero_power2)\n      by (metis add.commute add_le_same_cancel2 diff_ge_0_iff_ge diff_zero less_eq_real_def mult_eq_0_iff mult_nonneg_nonneg not_le numeral_One zero_neq_numeral)\n    show \"continuous_map (prod_topology (top_of_set {0..1}) (subtopology (nsphere n) {x. 0 \\<le> x k})) ?Y ?h\"\n      using assms\n      apply (auto simp: * nsphere continuous_map_componentwise_UNIV\n               prod_topology_subtopology subtopology_subtopology case_prod_unfold\n               continuous_map_in_subtopology Euclidean_space_def p_def if_distrib [where f = \"\\<lambda>x. _ * x\"] cong: if_cong)\n      apply (intro continuous_map_prod_snd continuous_intros continuous_map_from_subtopology)\n        apply auto\n      done\n  next\n    have 1: \"\\<And>x i. \\<lbrakk> i \\<le> n; x i \\<noteq> 0\\<rbrakk> \\<Longrightarrow> (\\<Sum>i\\<le>n. (x i / sqrt (\\<Sum>j\\<le>n. (x j)\\<^sup>2))\\<^sup>2) = 1\"\n      by (force simp: sum_nonneg sum_nonneg_eq_0_iff field_split_simps simp flip: sum_divide_distrib)\n    have cm: \"continuous_map ?Y (nsphere n) (\\<lambda>x i. x i / sqrt (\\<Sum>j\\<le>n. (x j)\\<^sup>2))\"\n      unfolding Euclidean_space_def nsphere subtopology_subtopology continuous_map_in_subtopology\n    proof (intro continuous_intros conjI)\n      show \"continuous_map\n               (subtopology (powertop_real UNIV) ({x. \\<forall>i\\<ge>Suc n. x i = 0} \\<inter> {x. 0 \\<le> x k \\<and> (\\<exists>i\\<le>n. x i \\<noteq> 0)}))\n               (powertop_real UNIV) (\\<lambda>x i. x i / sqrt (\\<Sum>j\\<le>n. (x j)\\<^sup>2))\"\n        unfolding continuous_map_componentwise\n        by (intro continuous_intros conjI ballI) (auto simp: sum_nonneg_eq_0_iff)\n    qed (auto simp: 1)\n    show \"continuous_map ?Y (subtopology (nsphere n) {x. 0 \\<le> x k}) (\\<lambda>x i. x i / sqrt (\\<Sum>j\\<le>n. (x j)\\<^sup>2))\"\n      by (force simp: cm sum_nonneg continuous_map_in_subtopology if_distrib [where f = \"\\<lambda>x. _ * x\"] cong: if_cong)\n  qed\n  moreover have \"(?g \\<circ> ?h) (0, x) = x\"\n    if \"x \\<in> topspace (subtopology (nsphere n) {x. 0 \\<le> x k})\" for x\n    using that\n    by (simp add: assms nsphere)\n  moreover\n  have \"(?g \\<circ> ?h) (1, x) = p\"\n    if \"x \\<in> topspace (subtopology (nsphere n) {x. 0 \\<le> x k})\" for x\n    by (force simp: assms p_def power2_eq_square if_distrib [where f = \"\\<lambda>x. x * _\"] cong: if_cong)\n  ultimately\n  show ?thesis\n    apply (simp add: contractible_space_def homotopic_with)\n    apply (rule_tac x=p in exI)\n    apply (rule_tac x=\"?g \\<circ> ?h\" in exI, force)\n    done\nqed\n\n\ncorollary contractible_space_lower_hemisphere:\n  assumes \"k \\<le> n\"\n  shows \"contractible_space(subtopology (nsphere n) {x. x k \\<le> 0})\"\nproof -\n  have \"contractible_space (subtopology (nsphere n) {x. 0 \\<le> x k}) = ?thesis\"\n  proof (rule homeomorphic_space_contractibility)\n    show \"subtopology (nsphere n) {x. 0 \\<le> x k} homeomorphic_space subtopology (nsphere n) {x. x k \\<le> 0}\"\n      unfolding homeomorphic_space_def homeomorphic_maps_def\n      apply (rule_tac x=\"\\<lambda>x i. if i = k then -(x i) else x i\" in exI)+\n      apply (auto simp: continuous_map_in_subtopology continuous_map_from_subtopology\n                  continuous_map_nsphere_reflection)\n      done\n  qed\n  then show ?thesis\n    using contractible_space_upper_hemisphere [OF assms] by metis\nqed\n\n\nproposition nullhomotopic_nonsurjective_sphere_map:\n  assumes f: \"continuous_map (nsphere p) (nsphere p) f\"\n    and fim: \"f ` (topspace(nsphere p)) \\<noteq> topspace(nsphere p)\"\n  obtains a where \"homotopic_with (\\<lambda>x. True) (nsphere p) (nsphere p) f (\\<lambda>x. a)\"\nproof -\n  obtain a where a: \"a \\<in> topspace(nsphere p)\" \"a \\<notin> f ` (topspace(nsphere p))\"\n    using fim continuous_map_image_subset_topspace f by blast\n  then have a1: \"(\\<Sum>i\\<le>p. (a i)\\<^sup>2) = 1\" and a0: \"\\<And>i. i > p \\<Longrightarrow> a i = 0\"\n    by (simp_all add: nsphere)\n  have f1: \"(\\<Sum>j\\<le>p. (f x j)\\<^sup>2) = 1\" if \"x \\<in> topspace (nsphere p)\" for x\n  proof -\n    have \"f x \\<in> topspace (nsphere p)\"\n      using continuous_map_image_subset_topspace f that by blast\n    then show ?thesis\n      by (simp add: nsphere)\n  qed\n  show thesis\n  proof\n    let ?g = \"\\<lambda>x i. x i / sqrt(\\<Sum>j\\<le>p. x j ^ 2)\"\n    let ?h = \"\\<lambda>(t,x) i. (1 - t) * f x i - t * a i\"\n    let ?Y = \"subtopology (Euclidean_space(Suc p)) (- {\\<lambda>i. 0})\"\n    let ?T01 = \"top_of_set {0..1::real}\"\n    have 1: \"continuous_map (prod_topology ?T01 (nsphere p)) (nsphere p) (?g \\<circ> ?h)\"\n    proof (rule continuous_map_compose)\n      have \"continuous_map (prod_topology ?T01 (nsphere p)) euclideanreal ((\\<lambda>x. f x k) \\<circ> snd)\" for k\n        unfolding nsphere\n        apply (simp add: continuous_map_of_snd)\n        apply (rule continuous_map_compose [of _ \"nsphere p\" f, unfolded o_def])\n        using f apply (simp add: nsphere)\n        by (simp add: continuous_map_nsphere_projection)\n      then have \"continuous_map (prod_topology ?T01 (nsphere p)) euclideanreal (\\<lambda>r. ?h r k)\"\n        for k\n        unfolding case_prod_unfold o_def\n        by (intro continuous_map_into_fulltopology [OF continuous_map_fst] continuous_intros) auto\n      moreover have \"?h ` ({0..1} \\<times> topspace (nsphere p)) \\<subseteq> {x. \\<forall>i\\<ge>Suc p. x i = 0}\"\n        using continuous_map_image_subset_topspace [OF f]\n        by (auto simp: nsphere image_subset_iff a0)\n      moreover have \"(\\<lambda>i. 0) \\<notin> ?h ` ({0..1} \\<times> topspace (nsphere p))\"\n      proof clarify\n        fix t b\n        assume eq: \"(\\<lambda>i. 0) = (\\<lambda>i. (1 - t) * f b i - t * a i)\" and \"t \\<in> {0..1}\" and b: \"b \\<in> topspace (nsphere p)\"\n        have \"(1 - t)\\<^sup>2 = (\\<Sum>i\\<le>p. ((1 - t) * f b i)^2)\"\n          using f1 [OF b] by (simp add: power_mult_distrib flip: sum_distrib_left)\n        also have \"\\<dots> = (\\<Sum>i\\<le>p. (t * a i)^2)\"\n          using eq by (simp add: fun_eq_iff)\n        also have \"\\<dots> = t\\<^sup>2\"\n          using a1 by (simp add: power_mult_distrib flip: sum_distrib_left)\n        finally have \"1 - t = t\"\n          by (simp add: power2_eq_iff)\n        then have *: \"t = 1/2\"\n          by simp\n        have fba: \"f b \\<noteq> a\"\n          using a(2) b by blast\n        then show False\n          using eq unfolding * by (simp add: fun_eq_iff)\n      qed\n      ultimately show \"continuous_map (prod_topology ?T01 (nsphere p)) ?Y ?h\"\n        by (simp add: Euclidean_space_def continuous_map_in_subtopology continuous_map_componentwise_UNIV)\n    next\n      have *: \"\\<lbrakk>\\<forall>i\\<ge>Suc p. x i = 0; x \\<noteq> (\\<lambda>i. 0)\\<rbrakk> \\<Longrightarrow> (\\<Sum>j\\<le>p. (x j)\\<^sup>2) \\<noteq> 0\" for x :: \"nat \\<Rightarrow> real\"\n        by (force simp: fun_eq_iff not_less_eq_eq sum_nonneg_eq_0_iff)\n      show \"continuous_map ?Y (nsphere p) ?g\"\n        apply (simp add: Euclidean_space_def continuous_map_in_subtopology continuous_map_componentwise_UNIV\n                         nsphere continuous_map_componentwise subtopology_subtopology)\n        apply (intro conjI allI continuous_intros continuous_map_from_subtopology [OF continuous_map_product_projection])\n            apply (simp_all add: *)\n         apply (force simp: sum_nonneg fun_eq_iff not_less_eq_eq sum_nonneg_eq_0_iff power_divide simp flip: sum_divide_distrib)\n        done\n    qed\n    have 2: \"(?g \\<circ> ?h) (0, x) = f x\" if \"x \\<in> topspace (nsphere p)\" for x\n      using that f1 by simp\n    have 3: \"(?g \\<circ> ?h) (1, x) = (\\<lambda>i. - a i)\" for x\n      using a by (force simp: field_split_simps nsphere)\n    then show \"homotopic_with (\\<lambda>x. True) (nsphere p) (nsphere p) f (\\<lambda>x. (\\<lambda>i. - a i))\"\n      by (force simp: homotopic_with intro: 1 2 3)\n  qed\nqed\n\nlemma Hausdorff_Euclidean_space:\n   \"Hausdorff_space (Euclidean_space n)\"\n  unfolding Euclidean_space_def\n  by (rule Hausdorff_space_subtopology) (metis Hausdorff_space_euclidean Hausdorff_space_product_topology)\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/Abstract_Euclidean_Space.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.867035752930664, "lm_q2_score": 0.8128673133042217, "lm_q1q2_score": 0.7047850230234518}}
{"text": "(* Author: Tobias Nipkow *)\n\nsection \\<open>Function \\textit{lookup} for Tree2\\<close>\n\ntheory Lookup2\nimports\n  Tree2\n  Cmp\n  Map_Specs\nbegin\n\nfun lookup :: \"(('a::linorder * 'b) * 'c) tree \\<Rightarrow> 'a \\<Rightarrow> 'b option\" where\n\"lookup Leaf x = None\" |\n\"lookup (Node l ((a,b), _) r) x =\n  (case cmp x a of LT \\<Rightarrow> lookup l x | GT \\<Rightarrow> lookup r x | EQ \\<Rightarrow> Some b)\"\n\nlemma lookup_map_of:\n  \"sorted1(inorder t) \\<Longrightarrow> lookup t x = map_of (inorder t) x\"\nby(induction t rule: tree2_induct) (auto simp: map_of_simps split: option.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/Lookup2.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8670357460591569, "lm_q2_score": 0.8128673178375735, "lm_q1q2_score": 0.7047850213684064}}
{"text": "(*  Title:      HOL/Map.thy\n    Author:     Tobias Nipkow, based on a theory by David von Oheimb\n    Copyright   1997-2003 TU Muenchen\n\nThe datatype of \"maps\"; strongly resembles maps in VDM.\n*)\n\nsection \\<open>Maps\\<close>\n\ntheory Map\nimports List\nbegin\n\ntype_synonym ('a, 'b) \"map\" = \"'a \\<Rightarrow> 'b option\" (infixr \"\\<rightharpoonup>\" 0)\n\nabbreviation\n  empty :: \"'a \\<rightharpoonup> 'b\" where\n  \"empty \\<equiv> \\<lambda>x. None\"\n\ndefinition\n  map_comp :: \"('b \\<rightharpoonup> 'c) \\<Rightarrow> ('a \\<rightharpoonup> 'b) \\<Rightarrow> ('a \\<rightharpoonup> 'c)\"  (infixl \"\\<circ>\\<^sub>m\" 55) where\n  \"f \\<circ>\\<^sub>m g = (\\<lambda>k. case g k of None \\<Rightarrow> None | Some v \\<Rightarrow> f v)\"\n\ndefinition\n  map_add :: \"('a \\<rightharpoonup> 'b) \\<Rightarrow> ('a \\<rightharpoonup> 'b) \\<Rightarrow> ('a \\<rightharpoonup> 'b)\"  (infixl \"++\" 100) where\n  \"m1 ++ m2 = (\\<lambda>x. case m2 x of None \\<Rightarrow> m1 x | Some y \\<Rightarrow> Some y)\"\n\ndefinition\n  restrict_map :: \"('a \\<rightharpoonup> 'b) \\<Rightarrow> 'a set \\<Rightarrow> ('a \\<rightharpoonup> 'b)\"  (infixl \"|`\"  110) where\n  \"m|`A = (\\<lambda>x. if x \\<in> A then m x else None)\"\n\nnotation (latex output)\n  restrict_map  (\"_\\<restriction>\\<^bsub>_\\<^esub>\" [111,110] 110)\n\ndefinition\n  dom :: \"('a \\<rightharpoonup> 'b) \\<Rightarrow> 'a set\" where\n  \"dom m = {a. m a \\<noteq> None}\"\n\ndefinition\n  ran :: \"('a \\<rightharpoonup> 'b) \\<Rightarrow> 'b set\" where\n  \"ran m = {b. \\<exists>a. m a = Some b}\"\n\ndefinition\n  map_le :: \"('a \\<rightharpoonup> 'b) \\<Rightarrow> ('a \\<rightharpoonup> 'b) \\<Rightarrow> bool\"  (infix \"\\<subseteq>\\<^sub>m\" 50) where\n  \"(m\\<^sub>1 \\<subseteq>\\<^sub>m m\\<^sub>2) \\<longleftrightarrow> (\\<forall>a \\<in> dom m\\<^sub>1. m\\<^sub>1 a = m\\<^sub>2 a)\"\n\nnonterminal maplets and maplet\n\nsyntax\n  \"_maplet\"  :: \"['a, 'a] \\<Rightarrow> maplet\"             (\"_ /\\<mapsto>/ _\")\n  \"_maplets\" :: \"['a, 'a] \\<Rightarrow> maplet\"             (\"_ /[\\<mapsto>]/ _\")\n  \"\"         :: \"maplet \\<Rightarrow> maplets\"             (\"_\")\n  \"_Maplets\" :: \"[maplet, maplets] \\<Rightarrow> maplets\" (\"_,/ _\")\n  \"_MapUpd\"  :: \"['a \\<rightharpoonup> 'b, maplets] \\<Rightarrow> 'a \\<rightharpoonup> 'b\" (\"_/'(_')\" [900, 0] 900)\n  \"_Map\"     :: \"maplets \\<Rightarrow> 'a \\<rightharpoonup> 'b\"            (\"(1[_])\")\n\nsyntax (ASCII)\n  \"_maplet\"  :: \"['a, 'a] \\<Rightarrow> maplet\"             (\"_ /|->/ _\")\n  \"_maplets\" :: \"['a, 'a] \\<Rightarrow> maplet\"             (\"_ /[|->]/ _\")\n\ntranslations\n  \"_MapUpd m (_Maplets xy ms)\"  \\<rightleftharpoons> \"_MapUpd (_MapUpd m xy) ms\"\n  \"_MapUpd m (_maplet  x y)\"    \\<rightleftharpoons> \"m(x := CONST Some y)\"\n  \"_Map ms\"                     \\<rightleftharpoons> \"_MapUpd (CONST empty) ms\"\n  \"_Map (_Maplets ms1 ms2)\"     \\<leftharpoondown> \"_MapUpd (_Map ms1) ms2\"\n  \"_Maplets ms1 (_Maplets ms2 ms3)\" \\<leftharpoondown> \"_Maplets (_Maplets ms1 ms2) ms3\"\n\nprimrec map_of :: \"('a \\<times> 'b) list \\<Rightarrow> 'a \\<rightharpoonup> 'b\"\nwhere\n  \"map_of [] = empty\"\n| \"map_of (p # ps) = (map_of ps)(fst p \\<mapsto> snd p)\"\n\ndefinition map_upds :: \"('a \\<rightharpoonup> 'b) \\<Rightarrow> 'a list \\<Rightarrow> 'b list \\<Rightarrow> 'a \\<rightharpoonup> 'b\"\n  where \"map_upds m xs ys = m ++ map_of (rev (zip xs ys))\"\ntranslations\n  \"_MapUpd m (_maplets x y)\" \\<rightleftharpoons> \"CONST map_upds m x y\"\n\nlemma map_of_Cons_code [code]:\n  \"map_of [] k = None\"\n  \"map_of ((l, v) # ps) k = (if l = k then Some v else map_of ps k)\"\n  by simp_all\n\n\nsubsection \\<open>@{term [source] empty}\\<close>\n\nlemma empty_upd_none [simp]: \"empty(x := None) = empty\"\n  by (rule ext) simp\n\n\nsubsection \\<open>@{term [source] map_upd}\\<close>\n\nlemma map_upd_triv: \"t k = Some x \\<Longrightarrow> t(k\\<mapsto>x) = t\"\n  by (rule ext) simp\n\nlemma map_upd_nonempty [simp]: \"t(k\\<mapsto>x) \\<noteq> empty\"\nproof\n  assume \"t(k \\<mapsto> x) = empty\"\n  then have \"(t(k \\<mapsto> x)) k = None\" by simp\n  then show False by simp\nqed\n\nlemma map_upd_eqD1:\n  assumes \"m(a\\<mapsto>x) = n(a\\<mapsto>y)\"\n  shows \"x = y\"\nproof -\n  from assms have \"(m(a\\<mapsto>x)) a = (n(a\\<mapsto>y)) a\" by simp\n  then show ?thesis by simp\nqed\n\nlemma map_upd_Some_unfold:\n  \"((m(a\\<mapsto>b)) x = Some y) = (x = a \\<and> b = y \\<or> x \\<noteq> a \\<and> m x = Some y)\"\nby auto\n\nlemma image_map_upd [simp]: \"x \\<notin> A \\<Longrightarrow> m(x \\<mapsto> y) ` A = m ` A\"\nby auto\n\nlemma finite_range_updI: \"finite (range f) \\<Longrightarrow> finite (range (f(a\\<mapsto>b)))\"\nunfolding image_def\napply (simp (no_asm_use) add:full_SetCompr_eq)\napply (rule finite_subset)\n prefer 2 apply assumption\napply (auto)\ndone\n\n\nsubsection \\<open>@{term [source] map_of}\\<close>\n\nlemma map_of_eq_None_iff:\n  \"(map_of xys x = None) = (x \\<notin> fst ` (set xys))\"\nby (induct xys) simp_all\n\nlemma map_of_eq_Some_iff [simp]:\n  \"distinct(map fst xys) \\<Longrightarrow> (map_of xys x = Some y) = ((x,y) \\<in> set xys)\"\napply (induct xys)\n apply simp\napply (auto simp: map_of_eq_None_iff [symmetric])\ndone\n\nlemma Some_eq_map_of_iff [simp]:\n  \"distinct(map fst xys) \\<Longrightarrow> (Some y = map_of xys x) = ((x,y) \\<in> set xys)\"\nby (auto simp del: map_of_eq_Some_iff simp: map_of_eq_Some_iff [symmetric])\n\nlemma map_of_is_SomeI [simp]: \"\\<lbrakk> distinct(map fst xys); (x,y) \\<in> set xys \\<rbrakk>\n    \\<Longrightarrow> map_of xys x = Some y\"\napply (induct xys)\n apply simp\napply force\ndone\n\nlemma map_of_zip_is_None [simp]:\n  \"length xs = length ys \\<Longrightarrow> (map_of (zip xs ys) x = None) = (x \\<notin> set xs)\"\nby (induct rule: list_induct2) simp_all\n\nlemma map_of_zip_is_Some:\n  assumes \"length xs = length ys\"\n  shows \"x \\<in> set xs \\<longleftrightarrow> (\\<exists>y. map_of (zip xs ys) x = Some y)\"\nusing assms by (induct rule: list_induct2) simp_all\n\nlemma map_of_zip_upd:\n  fixes x :: 'a and xs :: \"'a list\" and ys zs :: \"'b list\"\n  assumes \"length ys = length xs\"\n    and \"length zs = length xs\"\n    and \"x \\<notin> set xs\"\n    and \"map_of (zip xs ys)(x \\<mapsto> y) = map_of (zip xs zs)(x \\<mapsto> z)\"\n  shows \"map_of (zip xs ys) = map_of (zip xs zs)\"\nproof\n  fix x' :: 'a\n  show \"map_of (zip xs ys) x' = map_of (zip xs zs) x'\"\n  proof (cases \"x = x'\")\n    case True\n    from assms True map_of_zip_is_None [of xs ys x']\n      have \"map_of (zip xs ys) x' = None\" by simp\n    moreover from assms True map_of_zip_is_None [of xs zs x']\n      have \"map_of (zip xs zs) x' = None\" by simp\n    ultimately show ?thesis by simp\n  next\n    case False from assms\n      have \"(map_of (zip xs ys)(x \\<mapsto> y)) x' = (map_of (zip xs zs)(x \\<mapsto> z)) x'\" by auto\n    with False show ?thesis by simp\n  qed\nqed\n\nlemma map_of_zip_inject:\n  assumes \"length ys = length xs\"\n    and \"length zs = length xs\"\n    and dist: \"distinct xs\"\n    and map_of: \"map_of (zip xs ys) = map_of (zip xs zs)\"\n  shows \"ys = zs\"\n  using assms(1) assms(2)[symmetric]\n  using dist map_of\nproof (induct ys xs zs rule: list_induct3)\n  case Nil show ?case by simp\nnext\n  case (Cons y ys x xs z zs)\n  from \\<open>map_of (zip (x#xs) (y#ys)) = map_of (zip (x#xs) (z#zs))\\<close>\n    have map_of: \"map_of (zip xs ys)(x \\<mapsto> y) = map_of (zip xs zs)(x \\<mapsto> z)\" by simp\n  from Cons have \"length ys = length xs\" and \"length zs = length xs\"\n    and \"x \\<notin> set xs\" by simp_all\n  then have \"map_of (zip xs ys) = map_of (zip xs zs)\" using map_of by (rule map_of_zip_upd)\n  with Cons.hyps \\<open>distinct (x # xs)\\<close> have \"ys = zs\" by simp\n  moreover from map_of have \"y = z\" by (rule map_upd_eqD1)\n  ultimately show ?case by simp\nqed\n\nlemma map_of_zip_map:\n  \"map_of (zip xs (map f xs)) = (\\<lambda>x. if x \\<in> set xs then Some (f x) else None)\"\n  by (induct xs) (simp_all add: fun_eq_iff)\n\nlemma finite_range_map_of: \"finite (range (map_of xys))\"\napply (induct xys)\n apply (simp_all add: image_constant)\napply (rule finite_subset)\n prefer 2 apply assumption\napply auto\ndone\n\nlemma map_of_SomeD: \"map_of xs k = Some y \\<Longrightarrow> (k, y) \\<in> set xs\"\n  by (induct xs) (auto split: if_splits)\n\nlemma map_of_mapk_SomeI:\n  \"inj f \\<Longrightarrow> map_of t k = Some x \\<Longrightarrow>\n   map_of (map (case_prod (\\<lambda>k. Pair (f k))) t) (f k) = Some x\"\nby (induct t) (auto simp: inj_eq)\n\nlemma weak_map_of_SomeI: \"(k, x) \\<in> set l \\<Longrightarrow> \\<exists>x. map_of l k = Some x\"\nby (induct l) auto\n\nlemma map_of_filter_in:\n  \"map_of xs k = Some z \\<Longrightarrow> P k z \\<Longrightarrow> map_of (filter (case_prod P) xs) k = Some z\"\nby (induct xs) auto\n\nlemma map_of_map:\n  \"map_of (map (\\<lambda>(k, v). (k, f v)) xs) = map_option f \\<circ> map_of xs\"\n  by (induct xs) (auto simp: fun_eq_iff)\n\nlemma dom_map_option:\n  \"dom (\\<lambda>k. map_option (f k) (m k)) = dom m\"\n  by (simp add: dom_def)\n\nlemma dom_map_option_comp [simp]:\n  \"dom (map_option g \\<circ> m) = dom m\"\n  using dom_map_option [of \"\\<lambda>_. g\" m] by (simp add: comp_def)\n\n\nsubsection \\<open>@{const map_option} related\\<close>\n\nlemma map_option_o_empty [simp]: \"map_option f o empty = empty\"\nby (rule ext) simp\n\nlemma map_option_o_map_upd [simp]:\n  \"map_option f o m(a\\<mapsto>b) = (map_option f o m)(a\\<mapsto>f b)\"\nby (rule ext) simp\n\n\nsubsection \\<open>@{term [source] map_comp} related\\<close>\n\nlemma map_comp_empty [simp]:\n  \"m \\<circ>\\<^sub>m empty = empty\"\n  \"empty \\<circ>\\<^sub>m m = empty\"\nby (auto simp: map_comp_def split: option.splits)\n\nlemma map_comp_simps [simp]:\n  \"m2 k = None \\<Longrightarrow> (m1 \\<circ>\\<^sub>m m2) k = None\"\n  \"m2 k = Some k' \\<Longrightarrow> (m1 \\<circ>\\<^sub>m m2) k = m1 k'\"\nby (auto simp: map_comp_def)\n\nlemma map_comp_Some_iff:\n  \"((m1 \\<circ>\\<^sub>m m2) k = Some v) = (\\<exists>k'. m2 k = Some k' \\<and> m1 k' = Some v)\"\nby (auto simp: map_comp_def split: option.splits)\n\nlemma map_comp_None_iff:\n  \"((m1 \\<circ>\\<^sub>m m2) k = None) = (m2 k = None \\<or> (\\<exists>k'. m2 k = Some k' \\<and> m1 k' = None)) \"\nby (auto simp: map_comp_def split: option.splits)\n\n\nsubsection \\<open>\\<open>++\\<close>\\<close>\n\nlemma map_add_empty[simp]: \"m ++ empty = m\"\nby(simp add: map_add_def)\n\nlemma empty_map_add[simp]: \"empty ++ m = m\"\nby (rule ext) (simp add: map_add_def split: option.split)\n\nlemma map_add_assoc[simp]: \"m1 ++ (m2 ++ m3) = (m1 ++ m2) ++ m3\"\nby (rule ext) (simp add: map_add_def split: option.split)\n\nlemma map_add_Some_iff:\n  \"((m ++ n) k = Some x) = (n k = Some x | n k = None & m k = Some x)\"\nby (simp add: map_add_def split: option.split)\n\nlemma map_add_SomeD [dest!]:\n  \"(m ++ n) k = Some x \\<Longrightarrow> n k = Some x \\<or> n k = None \\<and> m k = Some x\"\nby (rule map_add_Some_iff [THEN iffD1])\n\nlemma map_add_find_right [simp]: \"n k = Some xx \\<Longrightarrow> (m ++ n) k = Some xx\"\nby (subst map_add_Some_iff) fast\n\nlemma map_add_None [iff]: \"((m ++ n) k = None) = (n k = None & m k = None)\"\nby (simp add: map_add_def split: option.split)\n\nlemma map_add_upd[simp]: \"f ++ g(x\\<mapsto>y) = (f ++ g)(x\\<mapsto>y)\"\nby (rule ext) (simp add: map_add_def)\n\nlemma map_add_upds[simp]: \"m1 ++ (m2(xs[\\<mapsto>]ys)) = (m1++m2)(xs[\\<mapsto>]ys)\"\nby (simp add: map_upds_def)\n\nlemma map_add_upd_left: \"m\\<notin>dom e2 \\<Longrightarrow> e1(m \\<mapsto> u1) ++ e2 = (e1 ++ e2)(m \\<mapsto> u1)\"\nby (rule ext) (auto simp: map_add_def dom_def split: option.split)\n\nlemma map_of_append[simp]: \"map_of (xs @ ys) = map_of ys ++ map_of xs\"\nunfolding map_add_def\napply (induct xs)\n apply simp\napply (rule ext)\napply (simp split: option.split)\ndone\n\nlemma finite_range_map_of_map_add:\n  \"finite (range f) \\<Longrightarrow> finite (range (f ++ map_of l))\"\napply (induct l)\n apply (auto simp del: fun_upd_apply)\napply (erule finite_range_updI)\ndone\n\nlemma inj_on_map_add_dom [iff]:\n  \"inj_on (m ++ m') (dom m') = inj_on m' (dom m')\"\nby (fastforce simp: map_add_def dom_def inj_on_def split: option.splits)\n\nlemma map_upds_fold_map_upd:\n  \"m(ks[\\<mapsto>]vs) = foldl (\\<lambda>m (k, v). m(k \\<mapsto> v)) m (zip ks vs)\"\nunfolding map_upds_def proof (rule sym, rule zip_obtain_same_length)\n  fix ks :: \"'a list\" and vs :: \"'b list\"\n  assume \"length ks = length vs\"\n  then show \"foldl (\\<lambda>m (k, v). m(k\\<mapsto>v)) m (zip ks vs) = m ++ map_of (rev (zip ks vs))\"\n    by(induct arbitrary: m rule: list_induct2) simp_all\nqed\n\nlemma map_add_map_of_foldr:\n  \"m ++ map_of ps = foldr (\\<lambda>(k, v) m. m(k \\<mapsto> v)) ps m\"\n  by (induct ps) (auto simp: fun_eq_iff map_add_def)\n\n\nsubsection \\<open>@{term [source] restrict_map}\\<close>\n\nlemma restrict_map_to_empty [simp]: \"m|`{} = empty\"\nby (simp add: restrict_map_def)\n\nlemma restrict_map_insert: \"f |` (insert a A) = (f |` A)(a := f a)\"\nby (auto simp: restrict_map_def)\n\nlemma restrict_map_empty [simp]: \"empty|`D = empty\"\nby (simp add: restrict_map_def)\n\nlemma restrict_in [simp]: \"x \\<in> A \\<Longrightarrow> (m|`A) x = m x\"\nby (simp add: restrict_map_def)\n\nlemma restrict_out [simp]: \"x \\<notin> A \\<Longrightarrow> (m|`A) x = None\"\nby (simp add: restrict_map_def)\n\nlemma ran_restrictD: \"y \\<in> ran (m|`A) \\<Longrightarrow> \\<exists>x\\<in>A. m x = Some y\"\nby (auto simp: restrict_map_def ran_def split: if_split_asm)\n\nlemma dom_restrict [simp]: \"dom (m|`A) = dom m \\<inter> A\"\nby (auto simp: restrict_map_def dom_def split: if_split_asm)\n\nlemma restrict_upd_same [simp]: \"m(x\\<mapsto>y)|`(-{x}) = m|`(-{x})\"\nby (rule ext) (auto simp: restrict_map_def)\n\nlemma restrict_restrict [simp]: \"m|`A|`B = m|`(A\\<inter>B)\"\nby (rule ext) (auto simp: restrict_map_def)\n\nlemma restrict_fun_upd [simp]:\n  \"m(x := y)|`D = (if x \\<in> D then (m|`(D-{x}))(x := y) else m|`D)\"\nby (simp add: restrict_map_def fun_eq_iff)\n\nlemma fun_upd_None_restrict [simp]:\n  \"(m|`D)(x := None) = (if x \\<in> D then m|`(D - {x}) else m|`D)\"\nby (simp add: restrict_map_def fun_eq_iff)\n\nlemma fun_upd_restrict: \"(m|`D)(x := y) = (m|`(D-{x}))(x := y)\"\nby (simp add: restrict_map_def fun_eq_iff)\n\nlemma fun_upd_restrict_conv [simp]:\n  \"x \\<in> D \\<Longrightarrow> (m|`D)(x := y) = (m|`(D-{x}))(x := y)\"\nby (simp add: restrict_map_def fun_eq_iff)\n\nlemma map_of_map_restrict:\n  \"map_of (map (\\<lambda>k. (k, f k)) ks) = (Some \\<circ> f) |` set ks\"\n  by (induct ks) (simp_all add: fun_eq_iff restrict_map_insert)\n\nlemma restrict_complement_singleton_eq:\n  \"f |` (- {x}) = f(x := None)\"\n  by (simp add: restrict_map_def fun_eq_iff)\n\n\nsubsection \\<open>@{term [source] map_upds}\\<close>\n\nlemma map_upds_Nil1 [simp]: \"m([] [\\<mapsto>] bs) = m\"\nby (simp add: map_upds_def)\n\nlemma map_upds_Nil2 [simp]: \"m(as [\\<mapsto>] []) = m\"\nby (simp add:map_upds_def)\n\nlemma map_upds_Cons [simp]: \"m(a#as [\\<mapsto>] b#bs) = (m(a\\<mapsto>b))(as[\\<mapsto>]bs)\"\nby (simp add:map_upds_def)\n\nlemma map_upds_append1 [simp]: \"size xs < size ys \\<Longrightarrow>\n  m(xs@[x] [\\<mapsto>] ys) = m(xs [\\<mapsto>] ys)(x \\<mapsto> ys!size xs)\"\napply(induct xs arbitrary: ys m)\n apply (clarsimp simp add: neq_Nil_conv)\napply (case_tac ys)\n apply simp\napply simp\ndone\n\nlemma map_upds_list_update2_drop [simp]:\n  \"size xs \\<le> i \\<Longrightarrow> m(xs[\\<mapsto>]ys[i:=y]) = m(xs[\\<mapsto>]ys)\"\napply (induct xs arbitrary: m ys i)\n apply simp\napply (case_tac ys)\n apply simp\napply (simp split: nat.split)\ndone\n\nlemma map_upd_upds_conv_if:\n  \"(f(x\\<mapsto>y))(xs [\\<mapsto>] ys) =\n   (if x \\<in> set(take (length ys) xs) then f(xs [\\<mapsto>] ys)\n                                    else (f(xs [\\<mapsto>] ys))(x\\<mapsto>y))\"\napply (induct xs arbitrary: x y ys f)\n apply simp\napply (case_tac ys)\n apply (auto split: if_split simp: fun_upd_twist)\ndone\n\nlemma map_upds_twist [simp]:\n  \"a \\<notin> set as \\<Longrightarrow> m(a\\<mapsto>b)(as[\\<mapsto>]bs) = m(as[\\<mapsto>]bs)(a\\<mapsto>b)\"\nusing set_take_subset by (fastforce simp add: map_upd_upds_conv_if)\n\nlemma map_upds_apply_nontin [simp]:\n  \"x \\<notin> set xs \\<Longrightarrow> (f(xs[\\<mapsto>]ys)) x = f x\"\napply (induct xs arbitrary: ys)\n apply simp\napply (case_tac ys)\n apply (auto simp: map_upd_upds_conv_if)\ndone\n\nlemma fun_upds_append_drop [simp]:\n  \"size xs = size ys \\<Longrightarrow> m(xs@zs[\\<mapsto>]ys) = m(xs[\\<mapsto>]ys)\"\napply (induct xs arbitrary: m ys)\n apply simp\napply (case_tac ys)\n apply simp_all\ndone\n\nlemma fun_upds_append2_drop [simp]:\n  \"size xs = size ys \\<Longrightarrow> m(xs[\\<mapsto>]ys@zs) = m(xs[\\<mapsto>]ys)\"\napply (induct xs arbitrary: m ys)\n apply simp\napply (case_tac ys)\n apply simp_all\ndone\n\n\nlemma restrict_map_upds[simp]:\n  \"\\<lbrakk> length xs = length ys; set xs \\<subseteq> D \\<rbrakk>\n    \\<Longrightarrow> m(xs [\\<mapsto>] ys)|`D = (m|`(D - set xs))(xs [\\<mapsto>] ys)\"\napply (induct xs arbitrary: m ys)\n apply simp\napply (case_tac ys)\n apply simp\napply (simp add: Diff_insert [symmetric] insert_absorb)\napply (simp add: map_upd_upds_conv_if)\ndone\n\n\nsubsection \\<open>@{term [source] dom}\\<close>\n\nlemma dom_eq_empty_conv [simp]: \"dom f = {} \\<longleftrightarrow> f = empty\"\n  by (auto simp: dom_def)\n\nlemma domI: \"m a = Some b \\<Longrightarrow> a \\<in> dom m\"\n  by (simp add: dom_def)\n(* declare domI [intro]? *)\n\nlemma domD: \"a \\<in> dom m \\<Longrightarrow> \\<exists>b. m a = Some b\"\n  by (cases \"m a\") (auto simp add: dom_def)\n\nlemma domIff [iff, simp del]: \"a \\<in> dom m \\<longleftrightarrow> m a \\<noteq> None\"\n  by (simp add: dom_def)\n\nlemma dom_empty [simp]: \"dom empty = {}\"\n  by (simp add: dom_def)\n\nlemma dom_fun_upd [simp]:\n  \"dom(f(x := y)) = (if y = None then dom f - {x} else insert x (dom f))\"\n  by (auto simp: dom_def)\n\nlemma dom_if:\n  \"dom (\\<lambda>x. if P x then f x else g x) = dom f \\<inter> {x. P x} \\<union> dom g \\<inter> {x. \\<not> P x}\"\n  by (auto split: if_splits)\n\nlemma dom_map_of_conv_image_fst:\n  \"dom (map_of xys) = fst ` set xys\"\n  by (induct xys) (auto simp add: dom_if)\n\nlemma dom_map_of_zip [simp]: \"length xs = length ys \\<Longrightarrow> dom (map_of (zip xs ys)) = set xs\"\n  by (induct rule: list_induct2) (auto simp: dom_if)\n\nlemma finite_dom_map_of: \"finite (dom (map_of l))\"\n  by (induct l) (auto simp: dom_def insert_Collect [symmetric])\n\nlemma dom_map_upds [simp]:\n  \"dom(m(xs[\\<mapsto>]ys)) = set(take (length ys) xs) \\<union> dom m\"\napply (induct xs arbitrary: m ys)\n apply simp\napply (case_tac ys)\n apply auto\ndone\n\nlemma dom_map_add [simp]: \"dom (m ++ n) = dom n \\<union> dom m\"\n  by (auto simp: dom_def)\n\nlemma dom_override_on [simp]:\n  \"dom (override_on f g A) =\n    (dom f  - {a. a \\<in> A - dom g}) \\<union> {a. a \\<in> A \\<inter> dom g}\"\n  by (auto simp: dom_def override_on_def)\n\n\n\nlemma map_add_dom_app_simps:\n  \"m \\<in> dom l2 \\<Longrightarrow> (l1 ++ l2) m = l2 m\"\n  \"m \\<notin> dom l1 \\<Longrightarrow> (l1 ++ l2) m = l2 m\"\n  \"m \\<notin> dom l2 \\<Longrightarrow> (l1 ++ l2) m = l1 m\"\n  by (auto simp add: map_add_def split: option.split_asm)\n\nlemma dom_const [simp]:\n  \"dom (\\<lambda>x. Some (f x)) = UNIV\"\n  by auto\n\n(* Due to John Matthews - could be rephrased with dom *)\nlemma finite_map_freshness:\n  \"finite (dom (f :: 'a \\<rightharpoonup> 'b)) \\<Longrightarrow> \\<not> finite (UNIV :: 'a set) \\<Longrightarrow>\n   \\<exists>x. f x = None\"\n  by (bestsimp dest: ex_new_if_finite)\n\nlemma dom_minus:\n  \"f x = None \\<Longrightarrow> dom f - insert x A = dom f - A\"\n  unfolding dom_def by simp\n\nlemma insert_dom:\n  \"f x = Some y \\<Longrightarrow> insert x (dom f) = dom f\"\n  unfolding dom_def by auto\n\nlemma map_of_map_keys:\n  \"set xs = dom m \\<Longrightarrow> map_of (map (\\<lambda>k. (k, the (m k))) xs) = m\"\n  by (rule ext) (auto simp add: map_of_map_restrict restrict_map_def)\n\nlemma map_of_eqI:\n  assumes set_eq: \"set (map fst xs) = set (map fst ys)\"\n  assumes map_eq: \"\\<forall>k\\<in>set (map fst xs). map_of xs k = map_of ys k\"\n  shows \"map_of xs = map_of ys\"\nproof (rule ext)\n  fix k show \"map_of xs k = map_of ys k\"\n  proof (cases \"map_of xs k\")\n    case None\n    then have \"k \\<notin> set (map fst xs)\" by (simp add: map_of_eq_None_iff)\n    with set_eq have \"k \\<notin> set (map fst ys)\" by simp\n    then have \"map_of ys k = None\" by (simp add: map_of_eq_None_iff)\n    with None show ?thesis by simp\n  next\n    case (Some v)\n    then have \"k \\<in> set (map fst xs)\" by (auto simp add: dom_map_of_conv_image_fst [symmetric])\n    with map_eq show ?thesis by auto\n  qed\nqed\n\nlemma map_of_eq_dom:\n  assumes \"map_of xs = map_of ys\"\n  shows \"fst ` set xs = fst ` set ys\"\nproof -\n  from assms have \"dom (map_of xs) = dom (map_of ys)\" by simp\n  then show ?thesis by (simp add: dom_map_of_conv_image_fst)\nqed\n\nlemma finite_set_of_finite_maps:\n  assumes \"finite A\" \"finite B\"\n  shows \"finite {m. dom m = A \\<and> ran m \\<subseteq> B}\" (is \"finite ?S\")\nproof -\n  let ?S' = \"{m. \\<forall>x. (x \\<in> A \\<longrightarrow> m x \\<in> Some ` B) \\<and> (x \\<notin> A \\<longrightarrow> m x = None)}\"\n  have \"?S = ?S'\"\n  proof\n    show \"?S \\<subseteq> ?S'\" by (auto simp: dom_def ran_def image_def)\n    show \"?S' \\<subseteq> ?S\"\n    proof\n      fix m assume \"m \\<in> ?S'\"\n      hence 1: \"dom m = A\" by force\n      hence 2: \"ran m \\<subseteq> B\" using \\<open>m \\<in> ?S'\\<close> by (auto simp: dom_def ran_def)\n      from 1 2 show \"m \\<in> ?S\" by blast\n    qed\n  qed\n  with assms show ?thesis by(simp add: finite_set_of_finite_funs)\nqed\n\n\nsubsection \\<open>@{term [source] ran}\\<close>\n\nlemma ranI: \"m a = Some b \\<Longrightarrow> b \\<in> ran m\"\n  by (auto simp: ran_def)\n(* declare ranI [intro]? *)\n\nlemma ran_empty [simp]: \"ran empty = {}\"\n  by (auto simp: ran_def)\n\nlemma ran_map_upd [simp]: \"m a = None \\<Longrightarrow> ran(m(a\\<mapsto>b)) = insert b (ran m)\"\n  unfolding ran_def\napply auto\napply (subgoal_tac \"aa \\<noteq> a\")\n apply auto\ndone\n\nlemma ran_distinct:\n  assumes dist: \"distinct (map fst al)\"\n  shows \"ran (map_of al) = snd ` set al\"\n  using assms\nproof (induct al)\n  case Nil\n  then show ?case by simp\nnext\n  case (Cons kv al)\n  then have \"ran (map_of al) = snd ` set al\" by simp\n  moreover from Cons.prems have \"map_of al (fst kv) = None\"\n    by (simp add: map_of_eq_None_iff)\n  ultimately show ?case by (simp only: map_of.simps ran_map_upd) simp\nqed\n\nlemma ran_map_option: \"ran (\\<lambda>x. map_option f (m x)) = f ` ran m\"\n  by (auto simp add: ran_def)\n\n\nsubsection \\<open>\\<open>map_le\\<close>\\<close>\n\nlemma map_le_empty [simp]: \"empty \\<subseteq>\\<^sub>m g\"\n  by (simp add: map_le_def)\n\nlemma upd_None_map_le [simp]: \"f(x := None) \\<subseteq>\\<^sub>m f\"\n  by (force simp add: map_le_def)\n\nlemma map_le_upd[simp]: \"f \\<subseteq>\\<^sub>m g ==> f(a := b) \\<subseteq>\\<^sub>m g(a := b)\"\n  by (fastforce simp add: map_le_def)\n\nlemma map_le_imp_upd_le [simp]: \"m1 \\<subseteq>\\<^sub>m m2 \\<Longrightarrow> m1(x := None) \\<subseteq>\\<^sub>m m2(x \\<mapsto> y)\"\n  by (force simp add: map_le_def)\n\nlemma map_le_upds [simp]:\n  \"f \\<subseteq>\\<^sub>m g \\<Longrightarrow> f(as [\\<mapsto>] bs) \\<subseteq>\\<^sub>m g(as [\\<mapsto>] bs)\"\napply (induct as arbitrary: f g bs)\n apply simp\napply (case_tac bs)\n apply auto\ndone\n\nlemma map_le_implies_dom_le: \"(f \\<subseteq>\\<^sub>m g) \\<Longrightarrow> (dom f \\<subseteq> dom g)\"\n  by (fastforce simp add: map_le_def dom_def)\n\nlemma map_le_refl [simp]: \"f \\<subseteq>\\<^sub>m f\"\n  by (simp add: map_le_def)\n\nlemma map_le_trans[trans]: \"\\<lbrakk> m1 \\<subseteq>\\<^sub>m m2; m2 \\<subseteq>\\<^sub>m m3\\<rbrakk> \\<Longrightarrow> m1 \\<subseteq>\\<^sub>m m3\"\n  by (auto simp add: map_le_def dom_def)\n\nlemma map_le_antisym: \"\\<lbrakk> f \\<subseteq>\\<^sub>m g; g \\<subseteq>\\<^sub>m f \\<rbrakk> \\<Longrightarrow> f = g\"\nunfolding map_le_def\napply (rule ext)\napply (case_tac \"x \\<in> dom f\", simp)\napply (case_tac \"x \\<in> dom g\", simp, fastforce)\ndone\n\nlemma map_le_map_add [simp]: \"f \\<subseteq>\\<^sub>m g ++ f\"\n  by (fastforce simp: map_le_def)\n\nlemma map_le_iff_map_add_commute: \"f \\<subseteq>\\<^sub>m f ++ g \\<longleftrightarrow> f ++ g = g ++ f\"\n  by (fastforce simp: map_add_def map_le_def fun_eq_iff split: option.splits)\n\nlemma map_add_le_mapE: \"f ++ g \\<subseteq>\\<^sub>m h \\<Longrightarrow> g \\<subseteq>\\<^sub>m h\"\n  by (fastforce simp: map_le_def map_add_def dom_def)\n\nlemma map_add_le_mapI: \"\\<lbrakk> f \\<subseteq>\\<^sub>m h; g \\<subseteq>\\<^sub>m h \\<rbrakk> \\<Longrightarrow> f ++ g \\<subseteq>\\<^sub>m h\"\n  by (auto simp: map_le_def map_add_def dom_def split: option.splits)\n\nlemma map_add_subsumed1: \"f \\<subseteq>\\<^sub>m g \\<Longrightarrow> f++g = g\"\nby (simp add: map_add_le_mapI map_le_antisym)\n\nlemma map_add_subsumed2: \"f \\<subseteq>\\<^sub>m g \\<Longrightarrow> g++f = g\"\nby (metis map_add_subsumed1 map_le_iff_map_add_commute)\n\nlemma dom_eq_singleton_conv: \"dom f = {x} \\<longleftrightarrow> (\\<exists>v. f = [x \\<mapsto> v])\"\n  (is \"?lhs \\<longleftrightarrow> ?rhs\")\nproof\n  assume ?rhs\n  then show ?lhs by (auto split: if_split_asm)\nnext\n  assume ?lhs\n  then obtain v where v: \"f x = Some v\" by auto\n  show ?rhs\n  proof\n    show \"f = [x \\<mapsto> v]\"\n    proof (rule map_le_antisym)\n      show \"[x \\<mapsto> v] \\<subseteq>\\<^sub>m f\"\n        using v by (auto simp add: map_le_def)\n      show \"f \\<subseteq>\\<^sub>m [x \\<mapsto> v]\"\n        using \\<open>dom f = {x}\\<close> \\<open>f x = Some v\\<close> by (auto simp add: map_le_def)\n    qed\n  qed\nqed\n\n\nsubsection \\<open>Various\\<close>\n\nlemma set_map_of_compr:\n  assumes distinct: \"distinct (map fst xs)\"\n  shows \"set xs = {(k, v). map_of xs k = Some v}\"\n  using assms\nproof (induct xs)\n  case Nil\n  then show ?case by simp\nnext\n  case (Cons x xs)\n  obtain k v where \"x = (k, v)\" by (cases x) blast\n  with Cons.prems have \"k \\<notin> dom (map_of xs)\"\n    by (simp add: dom_map_of_conv_image_fst)\n  then have *: \"insert (k, v) {(k, v). map_of xs k = Some v} =\n    {(k', v'). (map_of xs(k \\<mapsto> v)) k' = Some v'}\"\n    by (auto split: if_splits)\n  from Cons have \"set xs = {(k, v). map_of xs k = Some v}\" by simp\n  with * \\<open>x = (k, v)\\<close> show ?case by simp\nqed\n\nlemma map_of_inject_set:\n  assumes distinct: \"distinct (map fst xs)\" \"distinct (map fst ys)\"\n  shows \"map_of xs = map_of ys \\<longleftrightarrow> set xs = set ys\" (is \"?lhs \\<longleftrightarrow> ?rhs\")\nproof\n  assume ?lhs\n  moreover from \\<open>distinct (map fst xs)\\<close> have \"set xs = {(k, v). map_of xs k = Some v}\"\n    by (rule set_map_of_compr)\n  moreover from \\<open>distinct (map fst ys)\\<close> have \"set ys = {(k, v). map_of ys k = Some v}\"\n    by (rule set_map_of_compr)\n  ultimately show ?rhs by simp\nnext\n  assume ?rhs show ?lhs\n  proof\n    fix k\n    show \"map_of xs k = map_of ys k\"\n    proof (cases \"map_of xs k\")\n      case None\n      with \\<open>?rhs\\<close> have \"map_of ys k = None\"\n        by (simp add: map_of_eq_None_iff)\n      with None show ?thesis by simp\n    next\n      case (Some v)\n      with distinct \\<open>?rhs\\<close> have \"map_of ys k = Some v\"\n        by simp\n      with Some show ?thesis by simp\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/Map.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8311430645886583, "lm_q2_score": 0.8479677583778258, "lm_q1q2_score": 0.704782521370521}}
{"text": "(*  Title:      HOL/Algebra/RingHom.thy\n    Author:     Stephan Hohe, TU Muenchen\n*)\n\ntheory RingHom\nimports Ideal\nbegin\n\nsection \\<open>Homomorphisms of Non-Commutative Rings\\<close>\n\ntext \\<open>Lifting existing lemmas in a \\<open>ring_hom_ring\\<close> locale\\<close>\nlocale ring_hom_ring = R?: ring R + S?: ring S\n    for R (structure) and S (structure) +\n  fixes h\n  assumes homh: \"h \\<in> ring_hom R S\"\n  notes hom_mult [simp] = ring_hom_mult [OF homh]\n    and hom_one [simp] = ring_hom_one [OF homh]\n\nsublocale ring_hom_cring \\<subseteq> ring: ring_hom_ring\n  by standard (rule homh)\n\nsublocale ring_hom_ring \\<subseteq> abelian_group?: abelian_group_hom R S\napply (rule abelian_group_homI)\n  apply (rule R.is_abelian_group)\n apply (rule S.is_abelian_group)\napply (intro group_hom.intro group_hom_axioms.intro)\n  apply (rule R.a_group)\n apply (rule S.a_group)\napply (insert homh, unfold hom_def ring_hom_def)\napply simp\ndone\n\nlemma (in ring_hom_ring) is_ring_hom_ring:\n  \"ring_hom_ring R S h\"\n  by (rule ring_hom_ring_axioms)\n\nlemma ring_hom_ringI:\n  fixes R (structure) and S (structure)\n  assumes \"ring R\" \"ring S\"\n  assumes (* morphism: \"h \\<in> carrier R \\<rightarrow> carrier S\" *)\n          hom_closed: \"!!x. x \\<in> carrier R ==> h x \\<in> carrier S\"\n      and compatible_mult: \"!!x y. [| x : carrier R; y : carrier R |] ==> h (x \\<otimes> y) = h x \\<otimes>\\<^bsub>S\\<^esub> h y\"\n      and compatible_add: \"!!x y. [| x : carrier R; y : carrier R |] ==> h (x \\<oplus> y) = h x \\<oplus>\\<^bsub>S\\<^esub> h y\"\n      and compatible_one: \"h \\<one> = \\<one>\\<^bsub>S\\<^esub>\"\n  shows \"ring_hom_ring R S h\"\nproof -\n  interpret ring R by fact\n  interpret ring S by fact\n  show ?thesis apply unfold_locales\napply (unfold ring_hom_def, safe)\n   apply (simp add: hom_closed Pi_def)\n  apply (erule (1) compatible_mult)\n apply (erule (1) compatible_add)\napply (rule compatible_one)\ndone\nqed\n\nlemma ring_hom_ringI2:\n  assumes \"ring R\" \"ring S\"\n  assumes h: \"h \\<in> ring_hom R S\"\n  shows \"ring_hom_ring R S h\"\nproof -\n  interpret R: ring R by fact\n  interpret S: ring S by fact\n  show ?thesis apply (intro ring_hom_ring.intro ring_hom_ring_axioms.intro)\n    apply (rule R.is_ring)\n    apply (rule S.is_ring)\n    apply (rule h)\n    done\nqed\n\nlemma ring_hom_ringI3:\n  fixes R (structure) and S (structure)\n  assumes \"abelian_group_hom R S h\" \"ring R\" \"ring S\" \n  assumes compatible_mult: \"!!x y. [| x : carrier R; y : carrier R |] ==> h (x \\<otimes> y) = h x \\<otimes>\\<^bsub>S\\<^esub> h y\"\n      and compatible_one: \"h \\<one> = \\<one>\\<^bsub>S\\<^esub>\"\n  shows \"ring_hom_ring R S h\"\nproof -\n  interpret abelian_group_hom R S h by fact\n  interpret R: ring R by fact\n  interpret S: ring S by fact\n  show ?thesis apply (intro ring_hom_ring.intro ring_hom_ring_axioms.intro, rule R.is_ring, rule S.is_ring)\n    apply (insert group_hom.homh[OF a_group_hom])\n    apply (unfold hom_def ring_hom_def, simp)\n    apply safe\n    apply (erule (1) compatible_mult)\n    apply (rule compatible_one)\n    done\nqed\n\nlemma ring_hom_cringI:\n  assumes \"ring_hom_ring R S h\" \"cring R\" \"cring S\"\n  shows \"ring_hom_cring R S h\"\nproof -\n  interpret ring_hom_ring R S h by fact\n  interpret R: cring R by fact\n  interpret S: cring S by fact\n  show ?thesis by (intro ring_hom_cring.intro ring_hom_cring_axioms.intro)\n    (rule R.is_cring, rule S.is_cring, rule homh)\nqed\n\n\nsubsection \\<open>The Kernel of a Ring Homomorphism\\<close>\n\n\\<comment>\"the kernel of a ring homomorphism is an ideal\"\nlemma (in ring_hom_ring) kernel_is_ideal:\n  shows \"ideal (a_kernel R S h) R\"\napply (rule idealI)\n   apply (rule R.is_ring)\n  apply (rule additive_subgroup.a_subgroup[OF additive_subgroup_a_kernel])\n apply (unfold a_kernel_def', simp+)\ndone\n\ntext \\<open>Elements of the kernel are mapped to zero\\<close>\nlemma (in abelian_group_hom) kernel_zero [simp]:\n  \"i \\<in> a_kernel R S h \\<Longrightarrow> h i = \\<zero>\\<^bsub>S\\<^esub>\"\nby (simp add: a_kernel_defs)\n\n\nsubsection \\<open>Cosets\\<close>\n\ntext \\<open>Cosets of the kernel correspond to the elements of the image of the homomorphism\\<close>\nlemma (in ring_hom_ring) rcos_imp_homeq:\n  assumes acarr: \"a \\<in> carrier R\"\n      and xrcos: \"x \\<in> a_kernel R S h +> a\"\n  shows \"h x = h a\"\nproof -\n  interpret ideal \"a_kernel R S h\" \"R\" by (rule kernel_is_ideal)\n\n  from xrcos\n      have \"\\<exists>i \\<in> a_kernel R S h. x = i \\<oplus> a\" by (simp add: a_r_coset_defs)\n  from this obtain i\n      where iker: \"i \\<in> a_kernel R S h\"\n        and x: \"x = i \\<oplus> a\"\n      by fast+\n  note carr = acarr iker[THEN a_Hcarr]\n\n  from x\n      have \"h x = h (i \\<oplus> a)\" by simp\n  also from carr\n      have \"\\<dots> = h i \\<oplus>\\<^bsub>S\\<^esub> h a\" by simp\n  also from iker\n      have \"\\<dots> = \\<zero>\\<^bsub>S\\<^esub> \\<oplus>\\<^bsub>S\\<^esub> h a\" by simp\n  also from carr\n      have \"\\<dots> = h a\" by simp\n  finally\n      show \"h x = h a\" .\nqed\n\nlemma (in ring_hom_ring) homeq_imp_rcos:\n  assumes acarr: \"a \\<in> carrier R\"\n      and xcarr: \"x \\<in> carrier R\"\n      and hx: \"h x = h a\"\n  shows \"x \\<in> a_kernel R S h +> a\"\nproof -\n  interpret ideal \"a_kernel R S h\" \"R\" by (rule kernel_is_ideal)\n \n  note carr = acarr xcarr\n  note hcarr = acarr[THEN hom_closed] xcarr[THEN hom_closed]\n\n  from hx and hcarr\n      have a: \"h x \\<oplus>\\<^bsub>S\\<^esub> \\<ominus>\\<^bsub>S\\<^esub>h a = \\<zero>\\<^bsub>S\\<^esub>\" by algebra\n  from carr\n      have \"h x \\<oplus>\\<^bsub>S\\<^esub> \\<ominus>\\<^bsub>S\\<^esub>h a = h (x \\<oplus> \\<ominus>a)\" by simp\n  from a and this\n      have b: \"h (x \\<oplus> \\<ominus>a) = \\<zero>\\<^bsub>S\\<^esub>\" by simp\n\n  from carr have \"x \\<oplus> \\<ominus>a \\<in> carrier R\" by simp\n  from this and b\n      have \"x \\<oplus> \\<ominus>a \\<in> a_kernel R S h\" \n      unfolding a_kernel_def'\n      by fast\n\n  from this and carr\n      show \"x \\<in> a_kernel R S h +> a\" by (simp add: a_rcos_module_rev)\nqed\n\ncorollary (in ring_hom_ring) rcos_eq_homeq:\n  assumes acarr: \"a \\<in> carrier R\"\n  shows \"(a_kernel R S h) +> a = {x \\<in> carrier R. h x = h a}\"\napply rule defer 1\napply clarsimp defer 1\nproof\n  interpret ideal \"a_kernel R S h\" \"R\" by (rule kernel_is_ideal)\n\n  fix x\n  assume xrcos: \"x \\<in> a_kernel R S h +> a\"\n  from acarr and this\n      have xcarr: \"x \\<in> carrier R\"\n      by (rule a_elemrcos_carrier)\n\n  from xrcos\n      have \"h x = h a\" by (rule rcos_imp_homeq[OF acarr])\n  from xcarr and this\n      show \"x \\<in> {x \\<in> carrier R. h x = h a}\" by fast\nnext\n  interpret ideal \"a_kernel R S h\" \"R\" by (rule kernel_is_ideal)\n\n  fix x\n  assume xcarr: \"x \\<in> carrier R\"\n     and hx: \"h x = h a\"\n  from acarr xcarr hx\n      show \"x \\<in> a_kernel R S h +> a\" by (rule homeq_imp_rcos)\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/Algebra/RingHom.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677699040321, "lm_q2_score": 0.8311430415844385, "lm_q1q2_score": 0.7047825114436106}}
{"text": "theory ConcreteSemantics9_1_Ex3\n  imports \"~~/src/HOL/IMP/Star\" Complex_Main\nbegin\nsection \"A Typed Language\"\n\ntheory Types imports Star Complex_Main begin\n\ntext \\<open>We build on \\<^theory>\\<open>Complex_Main\\<close> instead of \\<^theory>\\<open>Main\\<close> to access\nthe real numbers.\\<close>\n\nsubsection \"Arithmetic Expressions\"\n\ndatatype val = Iv int | Rv real\n\ntype_synonym vname = string\ntype_synonym state = \"vname \\<Rightarrow> val\"\n\ntext_raw\\<open>\\snip{aexptDef}{0}{2}{%\\<close>\ndatatype aexp =  Ic int | Rc real | V vname | Plus aexp aexp\ntext_raw\\<open>}%endsnip\\<close>\n\ninductive taval :: \"aexp \\<Rightarrow> state \\<Rightarrow> val \\<Rightarrow> bool\" where\n\"taval (Ic i) s (Iv i)\" |\n\"taval (Rc r) s (Rv r)\" |\n\"taval (V x) s (s x)\" |\n\"taval a1 s (Iv i1) \\<Longrightarrow> taval a2 s (Iv i2)\n \\<Longrightarrow> taval (Plus a1 a2) s (Iv(i1+i2))\" |\n\"taval a1 s (Rv r1) \\<Longrightarrow> taval a2 s (Rv r2)\n \\<Longrightarrow> taval (Plus a1 a2) s (Rv(r1+r2))\"\n\ninductive_cases [elim!]:\n  \"taval (Ic i) s v\"  \"taval (Rc i) s v\"\n  \"taval (V x) s v\"\n  \"taval (Plus a1 a2) s v\"\n\nsubsection \"Boolean Expressions\"\n\ndatatype bexp = Bc bool | Not bexp | And bexp bexp | Less aexp aexp\n\ninductive tbval :: \"bexp \\<Rightarrow> state \\<Rightarrow> bool \\<Rightarrow> bool\" where\n\"tbval (Bc v) s v\" |\n\"tbval b s bv \\<Longrightarrow> tbval (Not b) s (\\<not> bv)\" |\n\"tbval b1 s bv1 \\<Longrightarrow> tbval b2 s bv2 \\<Longrightarrow> tbval (And b1 b2) s (bv1 & bv2)\" |\n\"taval a1 s (Iv i1) \\<Longrightarrow> taval a2 s (Iv i2) \\<Longrightarrow> tbval (Less a1 a2) s (i1 < i2)\" |\n\"taval a1 s (Rv r1) \\<Longrightarrow> taval a2 s (Rv r2) \\<Longrightarrow> tbval (Less a1 a2) s (r1 < r2)\"\n\nsubsection \"Syntax of Commands\"\n(* a copy of Com.thy - keep in sync! *)\n\ndatatype\n  com = SKIP \n      | Assign vname aexp       (\"_ ::= _\" [1000, 61] 61)\n      | Seq    com  com         (\"_;; _\"  [60, 61] 60)\n      | If     bexp com com     (\"IF _ THEN _ ELSE _\"  [0, 0, 61] 61)\n      | While  bexp com         (\"WHILE _ DO _\"  [0, 61] 61)\n      | Repeat  com bexp         (\"(REPEAT _/ UNTIL _)\"  [0, 61] 61)\n\n\nsubsection \"Small-Step Semantics of Commands\"\n\ninductive\n  small_step :: \"(com \\<times> state) \\<Rightarrow> (com \\<times> state) \\<Rightarrow> bool\" (infix \"\\<rightarrow>\" 55)\nwhere\nAssign:  \"taval a s v \\<Longrightarrow> (x ::= a, s) \\<rightarrow> (SKIP, s(x := v))\" |\n\nSeq1:   \"(SKIP;;c,s) \\<rightarrow> (c,s)\" |\nSeq2:   \"(c1,s) \\<rightarrow> (c1',s') \\<Longrightarrow> (c1;;c2,s) \\<rightarrow> (c1';;c2,s')\" |\n\nIfTrue:  \"tbval b s True \\<Longrightarrow> (IF b THEN c1 ELSE c2,s) \\<rightarrow> (c1,s)\" |\nIfFalse: \"tbval b s False \\<Longrightarrow> (IF b THEN c1 ELSE c2,s) \\<rightarrow> (c2,s)\" |\n\nWhile:   \"(WHILE b DO c,s) \\<rightarrow> (IF b THEN c;; WHILE b DO c ELSE SKIP,s)\" |\nRepeat: \"(REPEAT c UNTIL b, s) \\<rightarrow> (c;; IF b THEN SKIP ELSE REPEAT c UNTIL b, s)\"\n\nlemmas small_step_induct = small_step.induct[split_format(complete)]\n\nsubsection \"The Type System\"\n\ndatatype ty = Ity | Rty\n\ntype_synonym tyenv = \"vname \\<Rightarrow> ty\"\n\ninductive atyping :: \"tyenv \\<Rightarrow> aexp \\<Rightarrow> ty \\<Rightarrow> bool\"\n  (\"(1_/ \\<turnstile>/ (_ :/ _))\" [50,0,50] 50)\nwhere\nIc_ty: \"\\<Gamma> \\<turnstile> Ic i : Ity\" |\nRc_ty: \"\\<Gamma> \\<turnstile> Rc r : Rty\" |\nV_ty: \"\\<Gamma> \\<turnstile> V x : \\<Gamma> x\" |\nPlus_ty: \"\\<Gamma> \\<turnstile> a1 : \\<tau> \\<Longrightarrow> \\<Gamma> \\<turnstile> a2 : \\<tau> \\<Longrightarrow> \\<Gamma> \\<turnstile> Plus a1 a2 : \\<tau>\"\n\ndeclare atyping.intros [intro!]\ninductive_cases [elim!]:\n  \"\\<Gamma> \\<turnstile> V x : \\<tau>\" \"\\<Gamma> \\<turnstile> Ic i : \\<tau>\" \"\\<Gamma> \\<turnstile> Rc r : \\<tau>\" \"\\<Gamma> \\<turnstile> Plus a1 a2 : \\<tau>\"\n\ntext\\<open>Warning: the ``:'' notation leads to syntactic ambiguities,\ni.e. multiple parse trees, because ``:'' also stands for set membership.\nIn most situations Isabelle's type system will reject all but one parse tree,\nbut will still inform you of the potential ambiguity.\\<close>\n\ninductive btyping :: \"tyenv \\<Rightarrow> bexp \\<Rightarrow> bool\" (infix \"\\<turnstile>\" 50)\nwhere\nB_ty: \"\\<Gamma> \\<turnstile> Bc v\" |\nNot_ty: \"\\<Gamma> \\<turnstile> b \\<Longrightarrow> \\<Gamma> \\<turnstile> Not b\" |\nAnd_ty: \"\\<Gamma> \\<turnstile> b1 \\<Longrightarrow> \\<Gamma> \\<turnstile> b2 \\<Longrightarrow> \\<Gamma> \\<turnstile> And b1 b2\" |\nLess_ty: \"\\<Gamma> \\<turnstile> a1 : \\<tau> \\<Longrightarrow> \\<Gamma> \\<turnstile> a2 : \\<tau> \\<Longrightarrow> \\<Gamma> \\<turnstile> Less a1 a2\"\n\ndeclare btyping.intros [intro!]\ninductive_cases [elim!]: \"\\<Gamma> \\<turnstile> Not b\" \"\\<Gamma> \\<turnstile> And b1 b2\" \"\\<Gamma> \\<turnstile> Less a1 a2\"\n\ninductive ctyping :: \"tyenv \\<Rightarrow> com \\<Rightarrow> bool\" (infix \"\\<turnstile>\" 50) where\nSkip_ty: \"\\<Gamma> \\<turnstile> SKIP\" |\nAssign_ty: \"\\<Gamma> \\<turnstile> a : \\<Gamma>(x) \\<Longrightarrow> \\<Gamma> \\<turnstile> x ::= a\" |\nSeq_ty: \"\\<Gamma> \\<turnstile> c1 \\<Longrightarrow> \\<Gamma> \\<turnstile> c2 \\<Longrightarrow> \\<Gamma> \\<turnstile> c1;;c2\" |\nIf_ty: \"\\<Gamma> \\<turnstile> b \\<Longrightarrow> \\<Gamma> \\<turnstile> c1 \\<Longrightarrow> \\<Gamma> \\<turnstile> c2 \\<Longrightarrow> \\<Gamma> \\<turnstile> IF b THEN c1 ELSE c2\" |\nWhile_ty: \"\\<Gamma> \\<turnstile> b \\<Longrightarrow> \\<Gamma> \\<turnstile> c \\<Longrightarrow> \\<Gamma> \\<turnstile> WHILE b DO c\" |\nRepeat_typ: \"\\<Gamma> \\<turnstile> b \\<Longrightarrow> \\<Gamma> \\<turnstile> c \\<Longrightarrow> \\<Gamma> \\<turnstile> REPEAT c UNTIL b\"\n\ndeclare ctyping.intros [intro!]\ninductive_cases [elim!]:\n  \"\\<Gamma> \\<turnstile> x ::= a\"  \"\\<Gamma> \\<turnstile> c1;;c2\"\n  \"\\<Gamma> \\<turnstile> IF b THEN c1 ELSE c2\"\n  \"\\<Gamma> \\<turnstile> WHILE b DO c\"\n  \"\\<Gamma> \\<turnstile> REPEAT c UNTIL b\"\n\nsubsection \"Well-typed Programs Do Not Get Stuck\"\n\nfun type :: \"val \\<Rightarrow> ty\" where\n\"type (Iv i) = Ity\" |\n\"type (Rv r) = Rty\"\n\nlemma type_eq_Ity[simp]: \"type v = Ity \\<longleftrightarrow> (\\<exists>i. v = Iv i)\"\nby (cases v) simp_all\n\nlemma type_eq_Rty[simp]: \"type v = Rty \\<longleftrightarrow> (\\<exists>r. v = Rv r)\"\nby (cases v) simp_all\n\ndefinition styping :: \"tyenv \\<Rightarrow> state \\<Rightarrow> bool\" (infix \"\\<turnstile>\" 50)\nwhere \"\\<Gamma> \\<turnstile> s  \\<longleftrightarrow>  (\\<forall>x. type (s x) = \\<Gamma> x)\"\n\nlemma apreservation:\n  \"\\<Gamma> \\<turnstile> a : \\<tau> \\<Longrightarrow> taval a s v \\<Longrightarrow> \\<Gamma> \\<turnstile> s \\<Longrightarrow> type v = \\<tau>\"\napply(induction arbitrary: v rule: atyping.induct)\napply (fastforce simp: styping_def)+\ndone\n\nlemma aprogress: \"\\<Gamma> \\<turnstile> a : \\<tau> \\<Longrightarrow> \\<Gamma> \\<turnstile> s \\<Longrightarrow> \\<exists>v. taval a s v\"\nproof(induction rule: atyping.induct)\n  case (Plus_ty \\<Gamma> a1 t a2)\n  then obtain v1 v2 where v: \"taval a1 s v1\" \"taval a2 s v2\" by blast\n  show ?case\n  proof (cases v1)\n    case Iv\n    with Plus_ty v show ?thesis\n      by(fastforce intro: taval.intros(4) dest!: apreservation)\n  next\n    case Rv\n    with Plus_ty v show ?thesis\n      by(fastforce intro: taval.intros(5) dest!: apreservation)\n  qed\nqed (auto intro: taval.intros)\n\nlemma bprogress: \"\\<Gamma> \\<turnstile> b \\<Longrightarrow> \\<Gamma> \\<turnstile> s \\<Longrightarrow> \\<exists>v. tbval b s v\"\nproof(induction rule: btyping.induct)\n  case (Less_ty \\<Gamma> a1 t a2)\n  then obtain v1 v2 where v: \"taval a1 s v1\" \"taval a2 s v2\"\n    by (metis aprogress)\n  show ?case\n  proof (cases v1)\n    case Iv\n    with Less_ty v show ?thesis\n      by (fastforce intro!: tbval.intros(4) dest!:apreservation)\n  next\n    case Rv\n    with Less_ty v show ?thesis\n      by (fastforce intro!: tbval.intros(5) dest!:apreservation)\n  qed\nqed (auto intro: tbval.intros)\n\ntheorem progress:\n  \"\\<Gamma> \\<turnstile> c \\<Longrightarrow> \\<Gamma> \\<turnstile> s \\<Longrightarrow> c \\<noteq> SKIP \\<Longrightarrow> \\<exists>cs'. (c,s) \\<rightarrow> cs'\"\nproof(induction rule: ctyping.induct)\n  case Skip_ty thus ?case by simp\nnext\n  case Assign_ty \n  thus ?case by (metis Assign aprogress)\nnext\n  case Seq_ty thus ?case by simp (metis Seq1 Seq2)\nnext\n  case (If_ty \\<Gamma> b c1 c2)\n  then obtain bv where \"tbval b s bv\" by (metis bprogress)\n  show ?case\n  proof(cases bv)\n    assume \"bv\"\n    with \\<open>tbval b s bv\\<close> show ?case by simp (metis IfTrue)\n  next\n    assume \"\\<not>bv\"\n    with \\<open>tbval b s bv\\<close> show ?case by simp (metis IfFalse)\n  qed\nnext\n  case While_ty show ?case by (metis While)\nnext\n  case (Repeat_typ \\<Gamma> b c)\n  then show ?case \n    using Repeat by blast\nqed\n\ntheorem styping_preservation:\n  \"(c,s) \\<rightarrow> (c',s') \\<Longrightarrow> \\<Gamma> \\<turnstile> c \\<Longrightarrow> \\<Gamma> \\<turnstile> s \\<Longrightarrow> \\<Gamma> \\<turnstile> s'\"\nproof(induction rule: small_step_induct)\n  case Assign thus ?case\n    by (auto simp: styping_def) (metis Assign(1,3) apreservation)\nqed auto\n\ntheorem ctyping_preservation:\n  \"(c,s) \\<rightarrow> (c',s') \\<Longrightarrow> \\<Gamma> \\<turnstile> c \\<Longrightarrow> \\<Gamma> \\<turnstile> c'\"\n  by (induct rule: small_step_induct) (auto simp: ctyping.intros)\n\nabbreviation small_steps :: \"com * state \\<Rightarrow> com * state \\<Rightarrow> bool\" (infix \"\\<rightarrow>*\" 55)\nwhere \"x \\<rightarrow>* y == star small_step x y\"\n\ntheorem type_sound:\n  \"(c,s) \\<rightarrow>* (c',s') \\<Longrightarrow> \\<Gamma> \\<turnstile> c \\<Longrightarrow> \\<Gamma> \\<turnstile> s \\<Longrightarrow> c' \\<noteq> SKIP\n   \\<Longrightarrow> \\<exists>cs''. (c',s') \\<rightarrow> cs''\"\napply(induction rule:star_induct)\napply (metis progress)\nby (metis styping_preservation ctyping_preservation)\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/ConcreteSemanticsChapter9/ConcreteSemantics9_1_Ex3.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.847967769904032, "lm_q2_score": 0.8311430415844384, "lm_q1q2_score": 0.7047825114436104}}
{"text": "(*  \n    Author:      Ren\u00e9 Thiemann \n                 Akihisa Yamada\n    License:     BSD\n*)\n(*TODO: Rename! *)\nsection \\<open>Gauss Lemma\\<close>\n\ntext \\<open>We formalized Gauss Lemma, that the content of a product of two polynomials $p$ and $q$\n  is the product of the contents of $p$ and $q$. As a corollary we provide an algorithm\n  to convert a rational factor of an integer polynomial into an integer factor.\n  \n  In contrast to the theory on unique factorization domains -- where Gauss Lemma is also proven \n   in a more generic setting --\n  we are here in an executable setting and do not use the unspecified $some-gcd$ function.\n  Moreover, there is a slight difference in the definition of content: in this theory it is only\n  defined for integer-polynomials, whereas in the UFD theory, the content is defined for \n  polynomials in the fraction field.\\<close>\n\ntheory Gauss_Lemma\nimports \n  \"HOL-Computational_Algebra.Primes\"\n  Polynomial_Interpolation.Ring_Hom_Poly\n  Missing_Polynomial_Factorial\nbegin\n\nlemma primitive_part_alt_def:\n  \"primitive_part p = sdiv_poly p (content p)\"\n  by (simp add: primitive_part_def sdiv_poly_def)\n\ndefinition common_denom :: \"rat list \\<Rightarrow> int \\<times> int list\" where\n  \"common_denom xs \\<equiv> let \n     nds = map quotient_of xs;\n     denom = list_lcm (map snd nds);\n     ints = map (\\<lambda> (n,d). n * denom div d) nds\n   in (denom, ints)\"\n\ndefinition rat_to_int_poly :: \"rat poly \\<Rightarrow> int \\<times> int poly\" where\n  \"rat_to_int_poly p \\<equiv> let\n     ais = coeffs p;\n     d = fst (common_denom ais)\n   in (d, map_poly (\\<lambda> x. case quotient_of x of (p,q) \\<Rightarrow> p * d div q) p)\"\n\ndefinition rat_to_normalized_int_poly :: \"rat poly \\<Rightarrow> rat \\<times> int poly\" where\n  \"rat_to_normalized_int_poly p \\<equiv> if p = 0 then (1,0) else case rat_to_int_poly p of (s,q)\n    \\<Rightarrow> (of_int (content q) / of_int s, primitive_part q)\"\n\nlemma rat_to_normalized_int_poly_code[code]:\n  \"rat_to_normalized_int_poly p = (if p = 0 then (1,0) else case rat_to_int_poly p of (s,q)\n    \\<Rightarrow> let c = content q in (of_int c / of_int s, sdiv_poly q c))\"\n    unfolding Let_def rat_to_normalized_int_poly_def primitive_part_alt_def ..\n\nlemma common_denom: assumes cd: \"common_denom xs = (dd,ys)\"\n  shows \"xs = map (\\<lambda> i. of_int i / of_int dd) ys\" \"dd > 0\"\n  \"\\<And>x. x \\<in> set xs \\<Longrightarrow> rat_of_int (case quotient_of x of (n, x) \\<Rightarrow> n * dd div x) / rat_of_int dd = x\"\nproof -\n  let ?nds = \"map quotient_of xs\"\n  define nds where \"nds = ?nds\"\n  let ?denom = \"list_lcm (map snd nds)\"\n  let ?ints = \"map (\\<lambda> (n,d). n * dd div d) nds\"\n  from cd[unfolded common_denom_def Let_def]\n  have dd: \"dd = ?denom\" and ys: \"ys = ?ints\" unfolding nds_def by auto\n  show dd0: \"dd > 0\" unfolding dd \n    by (intro list_lcm_pos(3), auto simp: nds_def quotient_of_nonzero)\n  {\n    fix x\n    assume x: \"x \\<in> set xs\"\n    obtain p q where quot: \"quotient_of x = (p,q)\" by force\n    from x have \"(p,q) \\<in> set nds\" unfolding nds_def using quot by force\n    hence \"q \\<in> set (map snd nds)\" by force\n    from list_lcm[OF this] have q: \"q dvd dd\" unfolding dd .\n    show \"rat_of_int (case quotient_of x of (n, x) \\<Rightarrow> n * dd div x) / rat_of_int dd = x\"\n      unfolding quot split unfolding quotient_of_div[OF quot]  \n    proof -\n      have f1: \"q * (dd div q) = dd\"\n        using dvd_mult_div_cancel q by blast\n      have \"rat_of_int (dd div q) \\<noteq> 0\"\n        using dd0 dvd_mult_div_cancel q by fastforce\n      thus \"rat_of_int (p * dd div q) / rat_of_int dd = rat_of_int p / rat_of_int q\"\n        using f1 by (metis (no_types) div_mult_swap mult_divide_mult_cancel_right of_int_mult q)\n    qed\n  } note main = this\n  show \"xs = map (\\<lambda> i. of_int i / of_int dd) ys\" unfolding ys map_map o_def nds_def\n    by (rule sym, rule map_idI, rule main)\nqed\n\nlemma rat_to_int_poly: assumes \"rat_to_int_poly p = (d,q)\"\n  shows \"p = smult (inverse (of_int d)) (map_poly of_int q)\" \"d > 0\"\nproof -\n  let ?f = \"\\<lambda> x. case quotient_of x of (pa, x) \\<Rightarrow> pa * d div x\"\n  define f where \"f = ?f\"\n  from assms[unfolded rat_to_int_poly_def Let_def] \n    obtain xs where cd: \"common_denom (coeffs p) = (d,xs)\"\n    and q: \"q = map_poly f p\" unfolding f_def by (cases \"common_denom (coeffs p)\", auto)\n  from common_denom[OF cd] have d: \"d > 0\"  and \n    id: \"\\<And> x. x \\<in> set (coeffs p) \\<Longrightarrow> rat_of_int (f x) / rat_of_int d = x\" \n    unfolding f_def by auto\n  have f0: \"f 0 = 0\" unfolding f_def by auto\n  have id: \"rat_of_int (f (coeff p n)) / rat_of_int d = coeff p n\" for n\n    using id[of \"coeff p n\"] f0 range_coeff by (cases \"coeff p n = 0\", auto)\n  show \"d > 0\" by fact\n  show \"p = smult (inverse (of_int d)) (map_poly of_int q)\"\n    unfolding q smult_as_map_poly using id f0\n    by (intro poly_eqI, auto simp: field_simps coeff_map_poly)\nqed\n\nlemma content_ge_0_int: \"content p \\<ge> (0 :: int)\"\n  unfolding content_def\n  by (cases \"coeffs p\", auto)\n\nlemma abs_content_int[simp]: fixes p :: \"int poly\"\n  shows \"abs (content p) = content p\" using content_ge_0_int[of p] by auto\n\nlemma content_smult_int: fixes p :: \"int poly\" \n  shows \"content (smult a p) = abs a * content p\" by simp\n\nlemma normalize_non_0_smult: \"\\<exists> a. (a :: 'a :: semiring_gcd) \\<noteq> 0 \\<and> smult a (primitive_part p) = p\"\n  by (cases \"p = 0\", rule exI[of _ 1], simp, rule exI[of _ \"content p\"], auto)\n\nlemma rat_to_normalized_int_poly: assumes \"rat_to_normalized_int_poly p = (d,q)\"\n  shows \"p = smult d (map_poly of_int q)\" \"d > 0\" \"p \\<noteq> 0 \\<Longrightarrow> content q = 1\" \"degree q = degree p\"\nproof -\n  have \"p = smult d (map_poly of_int q) \\<and> d > 0 \\<and> (p \\<noteq> 0 \\<longrightarrow> content q = 1)\"\n  proof (cases \"p = 0\")\n    case True\n    thus ?thesis using assms unfolding rat_to_normalized_int_poly_def\n      by (auto simp: eval_poly_def)\n  next\n    case False\n    hence p0: \"p \\<noteq> 0\" by auto\n    obtain s r where id: \"rat_to_int_poly p = (s,r)\" by force\n    let ?cr = \"rat_of_int (content r)\"\n    let ?s = \"rat_of_int s\"\n    let ?q = \"map_poly rat_of_int q\"\n    from rat_to_int_poly[OF id] have p: \"p = smult (inverse ?s) (map_poly of_int r)\"\n    and s: \"s > 0\" by auto\n    let ?q = \"map_poly rat_of_int q\"\n    from p0 assms[unfolded rat_to_normalized_int_poly_def id split]\n    have d: \"d = ?cr / ?s\" and q: \"q = primitive_part r\" by auto\n    from content_times_primitive_part[of r, folded q] have qr: \"smult (content r) q = r\" .\n    have \"smult d ?q = smult (?cr / ?s) ?q\"\n      unfolding d by simp\n    also have \"?cr / ?s = ?cr * inverse ?s\" by (rule divide_inverse)\n    also have \"\\<dots> = inverse ?s * ?cr\" by simp\n    also have \"smult (inverse ?s * ?cr) ?q = smult (inverse ?s) (smult ?cr ?q)\" by simp\n    also have \"smult ?cr ?q = map_poly of_int (smult (content r) q)\" by (simp add: hom_distribs)\n    also have \"\\<dots> = map_poly of_int r\" unfolding qr ..\n    finally have pq: \"p = smult d ?q\" unfolding p by simp\n    from p p0 have r0: \"r \\<noteq> 0\" by auto\n    from content_eq_zero_iff[of r] content_ge_0_int[of r] r0 have cr: \"?cr > 0\" by linarith\n    with s have d0: \"d > 0\" unfolding d by auto\n    from content_primitive_part[OF r0] have cq: \"content q = 1\" unfolding q .\n    from pq d0 cq show ?thesis by auto\n  qed\n  thus p: \"p = smult d (map_poly of_int q)\" and d: \"d > 0\" and \"p \\<noteq> 0 \\<Longrightarrow> content q = 1\" by auto\n  show \"degree q = degree p\" unfolding p smult_as_map_poly\n    by (rule sym, subst map_poly_map_poly, force+, rule degree_map_poly, insert d, auto)\nqed\n\nlemma content_dvd_1:\n  \"content g = 1\" if \"content f = (1 :: 'a :: semiring_gcd)\" \"g dvd f\" \nproof -\n  from \\<open>g dvd f\\<close> have \"content g dvd content f\"\n    by (rule content_dvd_contentI)\n  with \\<open>content f = 1\\<close> show ?thesis\n    by simp\nqed\n\nlemma dvd_smult_int: fixes c :: int assumes c: \"c \\<noteq> 0\"\n  and dvd: \"q dvd (smult c p)\"\n  shows \"primitive_part q dvd p\"\nproof (cases \"p = 0\")\n  case True thus ?thesis by auto\nnext\n  case False note p0 = this\n  let ?cp = \"smult c p\"\n  from p0 c have cp0: \"?cp \\<noteq> 0\" by auto\n  from dvd obtain r where prod: \"?cp = q * r\" unfolding dvd_def by auto\n  from prod cp0 have q0: \"q \\<noteq> 0\" and r0: \"r \\<noteq> 0\" by auto\n  let ?c = \"content :: int poly \\<Rightarrow> int\"\n  let ?n = \"primitive_part :: int poly \\<Rightarrow> int poly\"\n  let ?pn = \"\\<lambda> p. smult (?c p) (?n p)\"\n  have cq: \"(?c q = 0) = False\" using content_eq_zero_iff q0 by auto\n  from prod have id1: \"?cp = ?pn q * ?pn r\" unfolding content_times_primitive_part by simp\n  from arg_cong[OF this, of content, unfolded content_smult_int content_mult\n    content_primitive_part[OF r0] content_primitive_part[OF q0], symmetric]\n    p0[folded content_eq_zero_iff] c\n  have \"abs c dvd ?c q * ?c r\" unfolding dvd_def by auto\n  hence \"c dvd ?c q * ?c r\" by auto\n  then obtain d where id: \"?c q * ?c r = c * d\" unfolding dvd_def by auto\n  have \"?cp = ?pn q * ?pn r\" by fact\n  also have \"\\<dots> = smult (c * d) (?n q * ?n r)\" unfolding id [symmetric]\n    by (metis content_mult content_times_primitive_part primitive_part_mult)\n  finally have id: \"?cp = smult c (?n q * smult d (?n r))\" by (simp add: mult.commute)\n  interpret map_poly_inj_zero_hom \"(*) c\" using c by (unfold_locales, auto)\n  have \"p = ?n q * smult d (?n r)\" using id[unfolded smult_as_map_poly[of c]] by auto\n  thus dvd: \"?n q dvd p\" unfolding dvd_def by blast\nqed\n\nlemma irreducible\\<^sub>d_primitive_part:\n  fixes p :: \"int poly\" (* can be relaxed but primitive_part_mult has bad type constraint *)\n  shows \"irreducible\\<^sub>d (primitive_part p) \\<longleftrightarrow> irreducible\\<^sub>d p\" (is \"?l \\<longleftrightarrow> ?r\")\nproof (rule iffI, rule irreducible\\<^sub>dI)\n  assume l: ?l\n  show \"degree p > 0\" using l by auto\n  have dpp: \"degree (primitive_part p) = degree p\" by simp\n  fix q r\n  assume deg: \"degree q < degree p\" \"degree r < degree p\" and \"p = q * r\"\n  then have pp: \"primitive_part p = primitive_part q * primitive_part r\" by (simp add: primitive_part_mult)\n  have \"\\<not> irreducible\\<^sub>d (primitive_part p)\"\n    apply (intro reducible\\<^sub>dI, rule exI[of _ \"primitive_part q\"], rule exI[of _ \"primitive_part r\"], unfold dpp)\n    using deg pp by auto\n  with l show False by auto\nnext\n  show \"?r \\<Longrightarrow> ?l\" by (metis irreducible\\<^sub>d_smultI normalize_non_0_smult)\nqed\n\nlemma irreducible\\<^sub>d_smult_int:\n  fixes c :: int assumes c: \"c \\<noteq> 0\"\n  shows \"irreducible\\<^sub>d (smult c p) = irreducible\\<^sub>d p\" (is \"?l = ?r\")\n  using irreducible\\<^sub>d_primitive_part[of \"smult c p\", unfolded primitive_part_smult] c\n  apply (cases \"c < 0\", simp)\n  apply (metis add.inverse_inverse add.inverse_neutral c irreducible\\<^sub>d_smultI normalize_non_0_smult smult_1_left smult_minus_left)\n  apply (simp add: irreducible\\<^sub>d_primitive_part)\n  done\n\nlemma irreducible\\<^sub>d_as_irreducible:\n  fixes p :: \"int poly\"\n  shows \"irreducible\\<^sub>d p \\<longleftrightarrow> irreducible (primitive_part p)\"\n  using irreducible_primitive_connect[of \"primitive_part p\"]\n  by (cases \"p = 0\", auto simp: irreducible\\<^sub>d_primitive_part)\n\n\nlemma rat_to_int_factor_content_1: fixes p :: \"int poly\" \n  assumes cp: \"content p = 1\"\n  and pgh: \"map_poly rat_of_int p = g * h\"\n  and g: \"rat_to_normalized_int_poly g = (r,rg)\"\n  and h: \"rat_to_normalized_int_poly h = (s,sh)\"\n  and p: \"p \\<noteq> 0\"\n  shows \"p = rg * sh\"\nproof -\n  let ?r = \"rat_of_int\"\n  let ?rp = \"map_poly ?r\"\n  from p have rp0: \"?rp p \\<noteq> 0\" by simp\n  with pgh have g0: \"g \\<noteq> 0\" and h0: \"h \\<noteq> 0\" by auto\n  from rat_to_normalized_int_poly[OF g] g0 \n  have r: \"r > 0\" \"r \\<noteq> 0\" and g: \"g = smult r (?rp rg)\" and crg: \"content rg = 1\" by auto\n  from rat_to_normalized_int_poly[OF h] h0 \n  have s: \"s > 0\" \"s \\<noteq> 0\" and h: \"h = smult s (?rp sh)\" and csh: \"content sh = 1\" by auto\n  let ?irs = \"inverse (r * s)\"\n  from r s have irs0: \"?irs \\<noteq> 0\" by (auto simp: field_simps)\n  have \"?rp (rg * sh) = ?rp rg * ?rp sh\" by (simp add: hom_distribs)\n  also have \"\\<dots> = smult ?irs (?rp p)\" unfolding pgh g h using r s\n    by (simp add: field_simps)\n  finally have id: \"?rp (rg * sh) = smult ?irs (?rp p)\" by auto\n  have rsZ: \"?irs \\<in> \\<int>\"\n  proof (rule ccontr)\n    assume not: \"\\<not> ?irs \\<in> \\<int>\"\n    obtain n d where irs': \"quotient_of ?irs = (n,d)\" by force\n    from quotient_of_denom_pos[OF irs'] have \"d > 0\" .\n    from not quotient_of_div[OF irs'] have \"d \\<noteq> 1\" \"d \\<noteq> 0\" and irs: \"?irs = ?r n / ?r d\" by auto\n    with irs0 have n0: \"n \\<noteq> 0\" by auto\n    from \\<open>d > 0\\<close> \\<open>d \\<noteq> 1\\<close> have \"d \\<ge> 2\" and \"\\<not> d dvd 1\" by auto\n    with content_iff[of d p, unfolded cp] obtain c where \n      c: \"c \\<in> set (coeffs p)\" and dc: \"\\<not> d dvd c\" \n      by auto\n    from c range_coeff[of p] obtain i where \"c = coeff p i\" by auto \n    from arg_cong[OF id, of \"\\<lambda> p. coeff p i\", \n      unfolded coeff_smult of_int_hom.coeff_map_poly_hom this[symmetric] irs]\n    have \"?r n / ?r d * ?r c \\<in> \\<int>\" by (metis Ints_of_int)\n    also have \"?r n / ?r d * ?r c = ?r (n * c) / ?r d\" by simp\n    finally have inZ: \"?r (n * c) / ?r d \\<in> \\<int>\" .\n    have cop: \"coprime n d\" by (rule quotient_of_coprime[OF irs'])\n    (* now there comes tedious reasoning that `coprime n d` `\\<not> d dvd c` ` nc / d \\<in> \\<int>` yields a \n       contradiction *)\n    define prod where \"prod = ?r (n * c) / ?r d\"\n    obtain n' d' where quot: \"quotient_of prod = (n',d')\" by force\n    have qr: \"\\<And> x. quotient_of (?r x) = (x, 1)\"\n      using Rat.of_int_def quotient_of_int by auto\n    from quotient_of_denom_pos[OF quot] have \"d' > 0\" .\n    with quotient_of_div[OF quot] inZ[folded prod_def] have \"d' = 1\"\n      by (metis Ints_cases Rat.of_int_def old.prod.inject quot quotient_of_int)\n    with quotient_of_div[OF quot] have \"prod = ?r n'\" by auto\n    from arg_cong[OF this, of quotient_of, unfolded prod_def rat_divide_code qr Let_def split]\n    have \"Rat.normalize (n * c, d) = (n',1)\" by simp\n    from normalize_crossproduct[OF \\<open>d \\<noteq> 0\\<close>, of 1 \"n * c\" n', unfolded this]\n    have id: \"n * c = n' * d\" by auto \n    from quotient_of_coprime[OF irs'] have \"coprime n d\" .\n    with id have \"d dvd c\"\n      by (metis coprime_commute coprime_dvd_mult_right_iff dvd_triv_right)\n    with dc show False ..\n  qed\n  then obtain irs where irs: \"?irs = ?r irs\" unfolding Ints_def by blast\n  from id[unfolded irs, folded hom_distribs, unfolded of_int_poly_hom.eq_iff]\n  have p: \"rg * sh = smult irs p\" by auto\n  have \"content (rg * sh) = 1\" unfolding content_mult crg csh by auto\n  from this[unfolded p content_smult_int cp] have \"abs irs = 1\" by simp\n  hence \"abs ?irs = 1\" using irs by auto\n  with r s have \"?irs = 1\" by auto\n  with irs have \"irs = 1\" by auto\n  with p show p: \"p = rg * sh\" by auto\nqed\n\nlemma rat_to_int_factor_explicit: fixes p :: \"int poly\" \n  assumes pgh: \"map_poly rat_of_int p = g * h\"\n  and g: \"rat_to_normalized_int_poly g = (r,rg)\"\n  shows \"\\<exists> r. p = rg * smult (content p) r\"\nproof -\n  show ?thesis\n  proof (cases \"p = 0\")\n    case True\n    show ?thesis unfolding True\n      by (rule exI[of _ 0], auto simp: degree_monom_eq)\n  next\n    case False\n    hence p: \"p \\<noteq> 0\" by auto\n    let ?r = \"rat_of_int\"\n    let ?rp = \"map_poly ?r\"\n    define q where \"q = primitive_part p\"\n    from content_times_primitive_part[of p, folded q_def] content_eq_zero_iff[of p] p\n      obtain a where a: \"a \\<noteq> 0\" and pq: \"p = smult a q\" and acp: \"content p = a\" by metis\n    from a pq p have ra: \"?r a \\<noteq> 0\" and q0: \"q \\<noteq> 0\" by auto\n    from content_primitive_part[OF p, folded q_def] have cq: \"content q = 1\" by auto\n    obtain s sh where h: \"rat_to_normalized_int_poly (smult (inverse (?r a)) h) = (s,sh)\" by force\n    from arg_cong[OF pgh[unfolded pq], of \"smult (inverse (?r a))\"] ra\n    have \"?rp q = g * smult (inverse (?r a)) h\" by (auto simp: hom_distribs)\n    from rat_to_int_factor_content_1[OF cq this g h q0]\n    have qrs: \"q = rg * sh\" .\n    show ?thesis unfolding acp unfolding pq qrs \n      by (rule exI[of _ sh], auto)\n  qed\nqed\n\nlemma rat_to_int_factor: fixes p :: \"int poly\" \n  assumes pgh: \"map_poly rat_of_int p = g * h\"\n  shows \"\\<exists> g' h'. p = g' * h' \\<and> degree g' = degree g \\<and> degree h' = degree h\"\nproof(cases \"p = 0\")\n  case True\n  with pgh have \"g = 0 \\<or> h = 0\" by auto\n  then show ?thesis\n    by (metis True degree_0 mult_hom.hom_zero mult_zero_left rat_to_normalized_int_poly(4) surj_pair)\nnext\n  case False\n  obtain r rg where ri: \"rat_to_normalized_int_poly (smult (1 / of_int (content p)) g) = (r,rg)\" by force\n  obtain q qh where ri2: \"rat_to_normalized_int_poly h = (q,qh)\" by force\n  show ?thesis\n  proof (intro exI conjI)\n    have \"of_int_poly (primitive_part p) = smult (1 / of_int (content p)) (g * h)\"\n      apply (auto simp: primitive_part_def pgh[symmetric] smult_map_poly map_poly_map_poly o_def intro!: map_poly_cong)\n      by (metis (no_types, lifting) content_dvd_coeffs div_by_0 dvd_mult_div_cancel floor_of_int nonzero_mult_div_cancel_left of_int_hom.hom_zero of_int_mult)\n    also have \"\\<dots> = smult (1 / of_int (content p)) g * h\" by simp\n    finally have \"of_int_poly (primitive_part p) = \\<dots>\".\n    note main = rat_to_int_factor_content_1[OF _ this ri ri2, simplified, OF False]\n    show \"p = smult (content p) rg * qh\" by (simp add: main[symmetric])\n    from ri2 show \"degree qh = degree h\" by (fact rat_to_normalized_int_poly)\n    from rat_to_normalized_int_poly(4)[OF ri] False\n    show \"degree (smult (content p) rg) = degree g\" by auto\n  qed\nqed\n\nlemma rat_to_int_factor_normalized_int_poly: fixes p :: \"rat poly\" \n  assumes pgh: \"p = g * h\"\n  and p: \"rat_to_normalized_int_poly p = (i,ip)\"\n  shows \"\\<exists> g' h'. ip = g' * h' \\<and> degree g' = degree g\"\nproof -\n  from rat_to_normalized_int_poly[OF p]\n  have p: \"p = smult i (map_poly rat_of_int ip)\" and i: \"i \\<noteq> 0\" by auto\n  from arg_cong[OF p, of \"smult (inverse i)\", unfolded pgh] i\n  have \"map_poly rat_of_int ip = g * smult (inverse i) h\" by auto\n  from rat_to_int_factor[OF this] show ?thesis by auto\nqed\n\n(* TODO: move *)\nlemma irreducible_smult [simp]:\n  fixes c :: \"'a :: field\"\n  shows \"irreducible (smult c p) \\<longleftrightarrow> irreducible p \\<and> c \\<noteq> 0\"\n  using irreducible_mult_unit_left[of \"[:c:]\", simplified] by force\n\ntext \\<open>A polynomial with integer coefficients is\n   irreducible over the rationals, if it is irreducible over the integers.\\<close>\ntheorem irreducible\\<^sub>d_int_rat: fixes p :: \"int poly\" \n  assumes p: \"irreducible\\<^sub>d p\"\n  shows \"irreducible\\<^sub>d (map_poly rat_of_int p)\"\nproof (rule irreducible\\<^sub>dI)\n  from irreducible\\<^sub>dD[OF p]\n  have p: \"degree p \\<noteq> 0\" and irr: \"\\<And> q r. degree q < degree p \\<Longrightarrow> degree r < degree p \\<Longrightarrow> p \\<noteq> q * r\" by auto\n  let ?r = \"rat_of_int\"\n  let ?rp = \"map_poly ?r\"\n  from p show rp: \"degree (?rp p) > 0\" by auto\n  from p have p0: \"p \\<noteq> 0\" by auto\n  fix g h :: \"rat poly\"\n  assume deg: \"degree g > 0\" \"degree g < degree (?rp p)\" \"degree h > 0\" \"degree h < degree (?rp p)\" and pgh: \"?rp p = g * h\"\n  from rat_to_int_factor[OF pgh] obtain g' h' where p: \"p = g' * h'\" and dg: \"degree g' = degree g\" \"degree h' = degree h\"\n    by auto\n  from irr[of g' h'] deg[unfolded dg]\n  show False using degree_mult_eq[of g' h'] by (auto simp: p dg)\nqed\n\ncorollary irreducible\\<^sub>d_rat_to_normalized_int_poly: \n  assumes rp: \"rat_to_normalized_int_poly rp = (a, ip)\"\n  and ip: \"irreducible\\<^sub>d ip\"\n  shows \"irreducible\\<^sub>d rp\"\nproof -\n  from rat_to_normalized_int_poly[OF rp] \n  have rp: \"rp = smult a (map_poly rat_of_int ip)\" and a: \"a \\<noteq> 0\" by auto\n  with irreducible\\<^sub>d_int_rat[OF ip] show ?thesis by auto\nqed\n\nlemma dvd_content_dvd: assumes dvd: \"content f dvd content g\" \"primitive_part f dvd primitive_part g\"\n  shows \"f dvd g\" \nproof -\n  let ?cf = \"content f\" let ?nf = \"primitive_part f\" \n  let ?cg = \"content g\" let ?ng = \"primitive_part g\" \n  have \"f dvd g = (smult ?cf ?nf dvd smult ?cg ?ng)\" \n    unfolding content_times_primitive_part by auto\n  from dvd(1) obtain ch where cg: \"?cg = ?cf * ch\" unfolding dvd_def by auto\n  from dvd(2) obtain nh where ng: \"?ng = ?nf * nh\" unfolding dvd_def by auto\n  have \"f dvd g = (smult ?cf ?nf dvd smult ?cg ?ng)\" \n    unfolding content_times_primitive_part[of f] content_times_primitive_part[of g] by auto\n  also have \"\\<dots> = (smult ?cf ?nf dvd smult ?cf ?nf * smult ch nh)\" unfolding cg ng\n    by (metis mult.commute mult_smult_right smult_smult)\n  also have \"\\<dots>\" by (rule dvd_triv_left)\n  finally show ?thesis .\nqed\n\nlemma sdiv_poly_smult: \"c \\<noteq> 0 \\<Longrightarrow> sdiv_poly (smult c f) c = f\"\n  by (intro poly_eqI, unfold coeff_sdiv_poly coeff_smult, auto)\n\nlemma primitive_part_smult_int: fixes f :: \"int poly\" shows\n  \"primitive_part (smult d f) = smult (sgn d) (primitive_part f)\" \nproof (cases \"d = 0 \\<or> f = 0\")\n  case False\n  obtain cf where cf: \"content f = cf\" by auto\n  with False have 0: \"d \\<noteq> 0\" \"f \\<noteq> 0\" \"cf \\<noteq> 0\" by auto\n  show ?thesis \n  proof (rule poly_eqI, unfold primitive_part_alt_def coeff_sdiv_poly content_smult_int coeff_smult cf)\n    fix n\n    consider (pos) \"d > 0\" | (neg) \"d < 0\" using 0(1) by linarith\n    thus \"d * coeff f n div (\\<bar>d\\<bar> * cf) = sgn d * (coeff f n div cf)\"\n    proof cases\n      case neg\n      hence \"?thesis = (d * coeff f n div - (d * cf) = - (coeff f n div cf))\" by auto\n      also have \"d * coeff f n div - (d * cf) = - (d * coeff f n div (d * cf))\" \n        by (subst dvd_div_neg, insert 0(1), auto simp: cf[symmetric])\n      also have \"d * coeff f n div (d * cf) = coeff f n div cf\" using 0(1) by auto\n      finally show ?thesis by simp\n    qed auto\n  qed\nqed 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/Polynomial_Factorization/Gauss_Lemma.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8311430478583168, "lm_q2_score": 0.8479677622198946, "lm_q1q2_score": 0.7047825103770397}}
{"text": "(*  Title:      Cayley_Hamilton/Cayley_Hamilton.thy\n    Author:     Johannes H\u00f6lzl, TU M\u00fcnchen\n    Author:     Stefan Hetzl, TU Wien\n    Author:     Stephan Adelsberge, WU Wien\n    Author:     Florian Pollak, TU Wien\n*)\n\n(*<*)\ntheory Cayley_Hamilton\nimports\n  Square_Matrix\n  \"HOL-Computational_Algebra.Polynomial\"  \nbegin\n\ndefinition C :: \"'a \\<Rightarrow> 'a::ring_1 poly\" where \"C c = [:c:]\"\nabbreviation CC (\"\\<^bold>C\") where \"\\<^bold>C \\<equiv> map_sq_matrix C\"\n\nlemma degree_C[simp]: \"degree (C a) = 0\"\n  by (simp add: C_def)\n\nlemma coeff_C_0[simp]: \"coeff (C x) 0 = x\"\n  by (simp add: C_def)\n\nlemma coeff_C_gt0[simp]: \"0 < n \\<Longrightarrow> coeff (C x) n = 0\"\n  by (cases n) (simp_all add: C_def)\n\nlemma coeff_C_eq: \"coeff (C x) n = (if n = 0 then x else 0)\"\n  by simp\n\nlemma coeff_mult_C[simp]: \"coeff (a * C x) n = coeff a n * x\"\n  by (simp add: coeff_mult coeff_C_eq if_distrib[where f=\"\\<lambda>x. a * x\" for a] sum.If_cases)\n\nlemma coeff_C_mult[simp]: \"coeff (C x * a) n = x * coeff a n\"\n  by (simp add: coeff_mult coeff_C_eq if_distrib[where f=\"\\<lambda>x. x * a\" for a] sum.If_cases)\n\nlemma C_0[simp]: \"C 0 = 0\"\n  by (simp add: C_def) \n\nlemma C_1[simp]: \"C 1 = 1\"\n  by (simp add: C_def)\n\nlemma C_linear:\n  shows C_mult: \"C (a * b) = C b * C a\"\n    and C_add: \"C (a + b) = C a + C b\"\n    and C_minus: \"C (- a) = - C a\"\n    and C_diff: \"C (a - b) = C a - C b\"\n  by (simp_all add: C_def)\n\ndefinition X :: \"'a::ring_1 poly\" where \"X = [:0, 1:]\"\nabbreviation XX (\"\\<^bold>X\") where \"\\<^bold>X \\<equiv> diag X\"\n\nlemma degree_X[simp]: \"degree X = 1\"\n  by (simp add: X_def)\n\nlemma coeff_X_Suc_0[simp]: \"coeff X (Suc 0) = 1\"\n  by (auto simp: X_def)\n\nlemma coeff_X_mult[simp]: \"coeff (X * p) (Suc i) = coeff p i\"\n  by (auto simp: X_def)\n\nlemma coeff_mult_X[simp]: \"coeff (p * X) (Suc i) = coeff p i\"\n  by (auto simp: X_def)\n\nlemma coeff_X_mult_0[simp]: \"coeff (X * p) 0 = 0\"\n  by (auto simp: X_def)\n\nlemma coeff_mult_X_0[simp]: \"coeff (p * X) 0 = 0\"\n  by (auto simp: X_def)\n\nlemma coeff_X: \"coeff X i = (if i = 1 then 1 else 0)\"\n  by (cases i) (auto simp: X_def gr0_conv_Suc)\n\nlemma coeff_pow_X: \"coeff (X ^ i) n = (if i = n then 1 else 0)\"\nproof (induction i arbitrary: n)\n  case (Suc i) then show ?case\n    by (cases n) simp_all\nqed auto\n\nlemma coeff_pow_X_eq[simp]: \"coeff (X^i) i = 1\"\n  by (simp add: coeff_pow_X)\n\nlemma (in monoid_mult) power_ac: \"a * (a^n * x) = a^n * (a * x)\"\n  by (metis power_Suc2 power_Suc mult.assoc)\n\ntext\\<open>This theory contains auxiliary lemmas on polynomials.\\<close>\n\nlemma degree_prod_le: \"degree (\\<Prod>i\\<in>S. f i) \\<le> (\\<Sum>i\\<in>S. degree (f i))\"\n  by (induction S rule: infinite_finite_induct)\n     (simp_all, metis (lifting) degree_mult_le dual_order.trans nat_add_left_cancel_le)\n\nlemma coeff_mult_sum:\n  \"degree p \\<le> m \\<Longrightarrow> degree q \\<le> n \\<Longrightarrow> coeff (p * q) (m + n) = coeff p m * coeff q n\"\n  using degree_mult_le[of p q] by (auto simp add: le_less coeff_eq_0 coeff_mult_degree_sum)\n\nlemma coeff_mult_prod_sum:\n  \"coeff (\\<Prod>i\\<in>S. f i) (\\<Sum>i\\<in>S. degree (f i)) = (\\<Prod>i\\<in>S. coeff (f i) (degree (f i)))\"\n  by (induct rule: infinite_finite_induct)(simp_all add: coeff_mult_sum degree_prod_le)\n\nlemma degree_sum_less:\n  \"0 < n \\<Longrightarrow> (\\<And>x. x \\<in> A \\<Longrightarrow> degree (f x) < n) \\<Longrightarrow> degree (\\<Sum>x\\<in>A. f x) < n\" \n  by (induct rule: infinite_finite_induct) (simp_all add: degree_add_less)\n\nlemma degree_sum_le:\n  shows \"(\\<And>x. x \\<in> A \\<Longrightarrow> degree (f x) \\<le> n) \\<Longrightarrow> degree (\\<Sum>x\\<in>A. f x) \\<le> n\"\n  by (induct rule: infinite_finite_induct) (auto intro!: degree_add_le)\n\nlemma degree_sum_le_Max:\n  \"finite F \\<Longrightarrow> degree (sum f F) \\<le> Max ((\\<lambda>x. degree (f x))`F)\"\n  by (intro degree_sum_le) (auto intro!: Max.coboundedI)\n\nlemma poly_as_sum_of_monoms': assumes n: \"degree p \\<le> n\" shows \"(\\<Sum>i\\<le>n. X^i * C (coeff p i)) = p\"\nproof -\n  have eq: \"\\<And>i. {..n} \\<inter> {i} = (if i \\<le> n then {i} else {})\"\n    by auto\n  show ?thesis\n    using n\n    by (simp add: poly_eq_iff coeff_sum coeff_eq_0 sum.If_cases eq coeff_pow_X\n                  if_distrib[where f=\"\\<lambda>x. x * a\" for a])\nqed\n\nlemma poly_as_sum_of_monoms: \"(\\<Sum>i\\<le>degree p. X^i * C (coeff p i)) = p\"\n  by (intro poly_as_sum_of_monoms' order_refl)\n\nlemma degree_sum_unique':\n  assumes I: \"finite I\" \"i \\<notin> I\" \"\\<And>j. j \\<in> I \\<Longrightarrow> degree (p j) < degree (p i)\"\n  shows \"degree (\\<Sum>i\\<in>insert i I. p i) = degree (p i)\"\n  using I\nproof (induction I)\n  case (insert j I) then show ?case\n    by (subst insert_commute) (auto simp: degree_add_eq_right) \nqed simp\n\nlemma degree_sum_unique:\n  \"finite I \\<Longrightarrow> i \\<in> I \\<Longrightarrow> (\\<And>j. j \\<in> I \\<Longrightarrow> j \\<noteq> i \\<Longrightarrow> degree (p j) < degree (p i)) \\<Longrightarrow>\n    degree (\\<Sum>i\\<in>I. p i) = degree (p i)\"\n  using degree_sum_unique'[of \"I - {i}\" i p] by (auto simp: insert_absorb)\n\nlemma coeff_sum_unique:\n  fixes p :: \"'a \\<Rightarrow> 'b::semiring_0 poly\"\n  assumes I: \"finite I\" \"i \\<in> I\" \"\\<And>j. j \\<in> I \\<Longrightarrow> j \\<noteq> i \\<Longrightarrow> degree (p j) < degree (p i)\"\n  shows \"coeff (\\<Sum>i\\<in>I. p i) (degree (p i)) = coeff (p i) (degree (p i))\"\nproof -\n  have \"(\\<Sum>j\\<in>I. coeff (p j) (degree (p i))) = (\\<Sum>i\\<in>{i}. coeff (p i) (degree (p i)))\"\n    using I by (intro sum.mono_neutral_cong_right) (auto intro!: coeff_eq_0)\n  then show ?thesis\n    by (simp add: coeff_sum)\nqed\n\nlemma diag_coeff: \"diag (coeff x i) = map_sq_matrix (\\<lambda>x. coeff x i) (diag x)\"\n  by transfer' (simp add: vec_eq_iff)\n\nlemma smult_one: \"x *\\<^sub>S 1 = diag x\"\n  by transfer (simp add: fun_eq_iff)\n\nlemma sum_telescope_Ico: \"a \\<le> b \\<Longrightarrow> (\\<Sum>i=a ..< b. f i - f (Suc i) ::_::ab_group_add) = f a - f b\"\n  by (induction b rule: dec_induct) auto\n\nlemmas map_sq_matrix = map_sq_matrix_diff map_sq_matrix_add map_sq_matrix_smult map_sq_matrix_sum\n\nlemma sign_permut: \"degree (of_int (sign p) * q) = degree q\" \n  by (simp add: sign_def)\n\nlemma degree_det:\n  assumes \"\\<And>j. j permutes UNIV \\<Longrightarrow> j \\<noteq> id \\<Longrightarrow> degree (\\<Prod>i\\<in>UNIV. to_fun A i (j i)) < degree (\\<Prod>i\\<in>UNIV. to_fun A i i)\"\n  shows \"degree (det A) = degree (\\<Prod>i\\<in>UNIV. to_fun A i i)\"\n  unfolding det_eq\n  by (subst degree_sum_unique[where i=id])\n     (simp_all add: sign_permut permutes_id assms)\n\ndefinition max_degree :: \"'a::zero poly^^'n \\<Rightarrow> nat\" where\n  \"max_degree A = Max (range (\\<lambda>(i, j). degree (to_fun A i j)))\"\n\nlemma degree_le_max_degree: \"degree (to_fun A i j) \\<le> max_degree A\"\n  unfolding max_degree_def by (auto simp add: Max_ge_iff)\n\ndefinition \"charpoly A = det (\\<^bold>X - \\<^bold>C A)\"\n\nlemma degree_diff_cancel: \"degree q < degree p \\<Longrightarrow> degree (p - q::_::ab_group_add poly) = degree p\"\n  by (metis add_uminus_conv_diff degree_add_eq_left degree_minus)\n\nlemma\n  fixes A :: \"'a::comm_ring_1^^'n\"\n  shows degree_charpoly: \"degree (charpoly A) = CARD('n)\"\n    and coeff_charpoly: \"coeff (charpoly A) (degree (charpoly A)) = 1\"\nproof -\n  let ?B = \"diag X - map_sq_matrix C A\"\n  let ?f = \"\\<lambda>p. \\<Prod>i\\<in>UNIV. to_fun ?B i (p i)\"\n  let ?g = \"\\<lambda>p. of_int (sign p) * ?f p\"\n\n  have dB: \"\\<And>i j. degree (to_fun ?B i j) = (if i = j then 1 else 0)\"\n    by transfer' (simp add: degree_diff_cancel)\n  have cB: \"\\<And>i j. coeff (to_fun ?B i j) (Suc 0) = (if i = j then 1 else 0)\"\n    by transfer' simp\n\n  have degree_f_id: \"degree (?f (\\<lambda>i. i)) = CARD('n)\"\n    using coeff_mult_prod_sum[of \"\\<lambda>i. to_fun ?B i i\" UNIV]\n    by (intro antisym degree_prod_le[THEN order_trans] le_degree)\n       (simp_all add: dB cB)\n\n  have degree_less: \"\\<And>p. p \\<noteq> id \\<Longrightarrow> degree (?f p) < degree (?f (\\<lambda>i. i))\"\n    unfolding degree_f_id\n    by (rule le_less_trans[OF degree_prod_le])\n       (auto simp add: dB sum.If_cases set_eq_iff intro!: psubset_card_mono)\n\n  have degree_charpoly: \"degree (charpoly A) = degree (?f (\\<lambda>i. i))\"\n    using degree_less unfolding charpoly_def by (rule degree_det)\n\n  show degree_eq: \"degree (charpoly A) = CARD('n)\"\n    using degree_charpoly degree_f_id by simp\n\n  have \"coeff (\\<Sum>p | p permutes UNIV. ?g p) (degree (?g id)) = 1\"\n  proof (subst coeff_sum_unique)\n    show \"coeff (?g id) (degree (?g id)) = 1\"\n      using coeff_mult_prod_sum[of \"\\<lambda>i. to_fun ?B i i\" UNIV]\n      by (simp add: dB cB sign_id degree_f_id)\n  qed (auto simp: degree_less sign_permut permutes_id)\n\n  then show \"coeff (charpoly A) (degree (charpoly A)) = 1\"\n    unfolding degree_charpoly by (simp add: sign_permut charpoly_def det_eq)\nqed\n\ndefinition \"max_perm_degree A = Max ((\\<lambda>p. \\<Sum>i\\<in>UNIV. degree (to_fun A i (p i)))`{p. p permutes UNIV})\"\n\nlemma max_perm_degree_eqI:\n  \"(\\<And>p. p permutes (UNIV::'a::finite set) \\<Longrightarrow> (\\<Sum>i\\<in>UNIV. degree (to_fun A i (p i))) \\<le> x) \\<Longrightarrow>\n    (\\<exists>p. p permutes UNIV \\<and> (\\<Sum>i\\<in>UNIV. degree (to_fun A i (p i))) = x) \\<Longrightarrow>\n    max_perm_degree A = x\"\n  by (auto intro!: Max_eqI  simp: max_perm_degree_def)\n\nlemma degree_prod_le_max_perm_degree:\n  \"j permutes (UNIV::'a::finite set) \\<Longrightarrow> degree (\\<Prod>i\\<in>UNIV. to_fun A i (j i)) \\<le> max_perm_degree A\"\n  unfolding max_perm_degree_def by (rule order_trans[OF degree_prod_le]) auto\n\nlemma degree_le_max_perm_degree: \"degree (det A) \\<le> max_perm_degree A\"\n  unfolding det_eq\n  by (rule order_trans[OF degree_sum_le_Max])\n     (auto intro!: degree_prod_le_max_perm_degree Max_le_iff[THEN iffD2] permutes_id simp: sign_permut)\n\nlemma max_degree_adjugate:\n  fixes A :: \"_^^'n\"\n  shows \"max_degree (adjugate (\\<^bold>X - \\<^bold>C A)) = CARD('n) - 1\"\n    (is \"?R = _\")\nproof -\n  let ?M = \"minor (\\<^bold>X - \\<^bold>C A)\"\n  let ?D = \"\\<lambda>i j k l. degree (to_fun (?M i j) k l)\"\n\n  have M: \"\\<And>i j k l. to_fun (?M i j) k l = (if k = i \\<and> l = j then 1\n    else if k = i \\<or> l = j then 0\n    else if k = l then [: - to_fun A k l, 1 :] else [: - to_fun A k l :])\"\n    by transfer' (simp add: vec_eq_iff C_def X_def)\n\n  have \"?R = Max (range (\\<lambda>(i, j). degree (det (?M j i))))\" (is \"_ = Max ?Max\")\n    unfolding max_degree_def by (simp add: transpose.rep_eq cofactor_def adjugate_def of_fun_inverse)\n  also have \"\\<dots> = CARD('n) - 1\"\n  proof (rule antisym)\n    show \"Max ?Max \\<le> CARD('n) - 1\"\n    proof (safe intro!: Max.boundedI)\n      fix i j\n      have \"max_perm_degree (?M j i) = card (UNIV - {i, j})\"\n        by (intro max_perm_degree_eqI)\n           (auto simp: M sum.If_cases if_distrib[of degree] simp del: card_Diff_insert\n                 intro!: card_mono permutes_id arg_cong[where f=card])\n      then show \"degree (det (?M j i)) \\<le> CARD('n) - 1\"\n        using degree_le_max_perm_degree[of \"?M j i\"] by (cases \"i = j\") auto\n    qed auto\n  next\n    obtain x :: 'n where True by auto\n    let ?P = \"\\<lambda>j k p. \\<Prod>i\\<in>UNIV. to_fun (?M j k) i (p i)\"\n\n    have \"degree (det (?M x x)) = CARD('n) - 1\"\n    proof (subst degree_det)\n      have \"CARD('n) - 1 = (\\<Sum>i\\<in>UNIV. ?D x x i i)\"\n        by (simp add: M if_distrib[where f=\"degree\"] sum.If_cases Collect_neg_eq Compl_eq_Diff_UNIV)\n      also have \"\\<dots> = degree (?P x x id)\"\n        by (auto intro!: antisym degree_prod_le le_degree simp add: coeff_mult_prod_sum)\n           (simp add: M if_distrib[where f=\"\\<lambda>x. coeff x b\" for b] prod.If_cases)\n      finally show *: \"degree (?P x x (\\<lambda>x. x)) = CARD('n) - 1\"\n        by simp\n\n      fix p :: \"'n \\<Rightarrow> 'n\" assume \"p permutes UNIV\" \"p \\<noteq> id\"\n      then obtain i j where ij: \"i \\<noteq> j\" \"p i = j\"  and p: \"i \\<noteq> p i\" \"j \\<noteq> p j\"\n        unfolding id_def by simp (metis permutes_univ)\n      then have \"card {i,j} \\<le> CARD('n)\"\n        by (intro card_mono) auto\n      have \"degree (?P x x p) \\<le> card (UNIV - {i, j})\"\n        using degree_prod_le\n        by (rule order_trans)\n           (auto simp: M if_distrib[where f=\"degree\"] sum.If_cases Collect_neg_eq Compl_eq_Diff_UNIV p intro!: card_mono)\n      also have \"\\<dots> < CARD('n) - 1\"\n        using \\<open>card {i, j} \\<le> CARD('n)\\<close> ij by auto\n      finally show \"degree (?P x x p) < degree (?P x x (\\<lambda>x. x))\"\n        using * by simp\n    qed\n    then show \"CARD('n) - 1 \\<le> Max ?Max\"\n      by (auto simp add: Max_ge_iff intro!: exI[of _ x])\n  qed\n  finally show ?thesis .\nqed\n\ndefinition poly_mat :: \"'a::ring_1 poly \\<Rightarrow> 'a^^'n \\<Rightarrow> 'a^^'n\" where\n  \"poly_mat p A = (\\<Sum>i\\<le>degree p. coeff p i *\\<^sub>S A^i)\"\n\nlemma zero_smult[simp]: \"0 *\\<^sub>S M = (0::'a::semiring_1^^'n)\"\n  by transfer (simp add: vec_eq_iff)\n\nlemma smult_smult: \"a *\\<^sub>S b *\\<^sub>S M = (a * b::'a::monoid_mult) *\\<^sub>S M\"\n  by transfer (simp add: mult_ac)\n\nlemma map_sq_matrix_mult_eq_smult[simp]: \"map_sq_matrix ((*) a) M = a *\\<^sub>S M\"\n  by transfer rule\n\nlemma coeff_smult_1: \"coeff p i *\\<^sub>S m = m * map_sq_matrix (\\<lambda>p. coeff p i) (p *\\<^sub>S 1::_::comm_ring_1 ^^ 'n)\"\n  by (simp add: smult_one mult_diag)\n\nlemma map_sq_matrix_if_distrib[simp]:\n  \"map_sq_matrix (\\<lambda>x. if P then f x else g x) = (if P then map_sq_matrix f else map_sq_matrix g)\"\n  by simp\n(*>*)\n\ntheorem Cayley_Hamilton:\n  fixes A :: \"'a::comm_ring_1 ^^ 'n\"\n  shows \"poly_mat (charpoly A) A = 0\"\nproof -\ntext %visible \\<open>\\hrulefill ~~ Part 1 ~~ \\hrulefill\\<close>\n  define n where \"n = CARD('n) - 1\"\n  then have d_charpoly: \"n + 1 = degree (charpoly A)\" and \n      d_adj: \"n = max_degree (adjugate (\\<^bold>X - \\<^bold>C A))\"\n    by %invisible (simp_all add: degree_charpoly n_def max_degree_adjugate monom_0 diag_1[symmetric])\n\n  define B where \"B i = map_sq_matrix (\\<lambda>p. coeff p i) (adjugate (\\<^bold>X - \\<^bold>C A))\" for i\n  have A_eq_B: \"adjugate (\\<^bold>X - \\<^bold>C A) = (\\<Sum>i\\<le>n. X^i *\\<^sub>S \\<^bold>C (B i))\"\n    by %invisible (simp add: map_sq_matrix_smult sum_map_sq_matrix B_def d_adj\n                        degree_le_max_degree poly_as_sum_of_monoms' cong: map_sq_matrix_cong)\ntext %visible \\<open>\\hrulefill ~~ Part 2 ~~ \\hrulefill\\<close>\n  have \"charpoly A *\\<^sub>S 1 = X *\\<^sub>S adjugate (\\<^bold>X - \\<^bold>C A) - \\<^bold>C A * adjugate (\\<^bold>X - \\<^bold>C A)\" \n    by %invisible (simp add: smult_one charpoly_def mult_adjugate_det[symmetric] field_simps diag_mult)\n  also have \"\\<dots> = (\\<Sum>i\\<le>n. X^(i + 1) *\\<^sub>S \\<^bold>C (B i)) - (\\<Sum>i\\<le>n. X^i *\\<^sub>S \\<^bold>C (A * B i))\"\n    unfolding %invisible A_eq_B by %invisible (simp add: sum_distrib_left smult_mult2[symmetric]\n      map_sq_matrix_mult[symmetric] C_linear smult_sum[symmetric] smult_smult)\n  also have \"(\\<Sum>i\\<le>n. X^(i + 1) *\\<^sub>S \\<^bold>C (B i)) =\n      (\\<Sum>i<n. X^(i + 1) *\\<^sub>S \\<^bold>C (B i)) + X^(n + 1) *\\<^sub>S \\<^bold>C (B n)\"\n    by %invisible (simp add: lessThan_Suc_atMost[symmetric])\n  also have \"(\\<Sum>i\\<le>n. X^i *\\<^sub>S \\<^bold>C (A * B i)) =\n      (\\<Sum>i<n. X^(i + 1) *\\<^sub>S \\<^bold>C (A * B (i + 1))) + \\<^bold>C (A * B 0)\"\n    unfolding %invisible lessThan_Suc_atMost[symmetric] lessThan_Suc_eq_insert_0\n    by %invisible (simp add: zero_notin_Suc_image monom_0 sum.reindex one_poly_def[symmetric] diag_mult)\n  finally have diag_charpoly:\n    \"charpoly A *\\<^sub>S 1 = X^(n + 1) *\\<^sub>S \\<^bold>C (B n) +\n      (\\<Sum>i<n. X^(i + 1) *\\<^sub>S \\<^bold>C (B i - A * B (i + 1))) - \\<^bold>C (A * B 0)\"\n    by %invisible (simp add: map_sq_matrix_diff C_linear sum_subtractf smult_diff)\ntext %visible \\<open>\\hrulefill ~~ Part 3 ~~ \\hrulefill\\<close>\n  let ?p = \"\\<lambda>i. coeff (charpoly A) i *\\<^sub>S A^i\"\n  let ?AB = \"\\<lambda>i. A^(i + 1) * B i\"\n  have \"(\\<Sum>i\\<le>n+1. ?p i) = ?p 0 + (\\<Sum>i<n. ?p (i + 1)) + ?p (n + 1)\"\n    unfolding %invisible sum.atMost_Suc_shift Suc_eq_plus1[symmetric]\n    by %invisible (simp add: lessThan_Suc_atMost[symmetric])\n  also have \"?p 0 = - ?AB 0\"\n    by %invisible (simp add: coeff_smult_1 diag_charpoly map_sq_matrix)\n  also have \"(\\<Sum>i<n. ?p (i + 1)) = (\\<Sum>i=0..<n. ?AB i - ?AB (i + 1))\"\n      by %invisible (rule sum.cong)\n         (auto simp: coeff_smult_1 coeff_pow_X diag_charpoly map_sq_matrix sum_subtractf\n                     if_distrib[where f=\"\\<lambda>x. x a\" for a] if_distrib[where f=\"\\<lambda>x. a * x\" for a]\n                     field_simps sum.If_cases power_Suc2\n               simp del: power_Suc)\n  also have \"\\<dots> = ?AB 0 - ?AB n\"\n    unfolding %invisible Suc_eq_plus1[symmetric]\n    by %invisible (subst sum_telescope_Ico) auto\n  also have \"?AB n = ?p (n + 1)\"\n    unfolding %invisible coeff_smult_1 diag_charpoly\n    by %invisible (simp add: mult_diag map_sq_matrix coeff_pow_X)\n  also have \"coeff (charpoly A) (n + 1) = 1\"\n    by %invisible (simp add: coeff_charpoly d_charpoly[simplified])\n  finally show ?thesis\n    by %invisible (simp add: poly_mat_def d_charpoly[simplified] diag_0_eq mult_diag)\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/Cayley_Hamilton/Cayley_Hamilton.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430353105599, "lm_q2_score": 0.8479677545357568, "lm_q1q2_score": 0.7047824933503287}}
{"text": "theory ArincQueuing\n imports \"../../ArincMultiCoreState\" Sep_Algebra.Separation_Algebra\nbegin\nsubsection {* channel messages *}\ntext {*\nmessages on channels definition for management of auxiliary variables\nTo get track of messages added and removed to/from a channel \nmessages are stored in an auxiliary variable. The queue for a channel ch\nis always equal to the initial value of the queue plus the auxiliary variables\nof the processes sending a message to the channel, minus the auxiliary variables\nof the processes removing/clearing messages from the channel. *}\n\n\ndefinition channel_messages :: \"channel_id  \\<Rightarrow> ('a \\<Rightarrow> (channel_id \\<Rightarrow> Message multiset)) \\<Rightarrow> \n                                  'a list \\<Rightarrow> Message multiset\"\nwhere\n\"channel_messages ch_id aux ls  \\<equiv>       \n      fold (\\<lambda>m ms. ms + m)  [((aux i) ch_id). i <-ls] {#}\n\"\n\nlemma union_fold: \n  \"fold (\\<lambda>m ms. ms + m)  ((l::'a multiset)#ls) s = (l::'a multiset) + (fold (\\<lambda>m ms. ms + m)  ls s)\"\nproof -\n  have \"\\<forall>ms m ma. foldl (+) ((ma::'a multiset) + m) ms = foldl (+) ma ms + m\"  \n    using union_commute\n    by (auto simp add: add.foldl_assoc union_commute)\n  then have \"foldl (+) s (l # ls) = foldl (+) s ls + l\"\n    by simp\n  then show ?thesis\n    by (simp add: foldl_conv_fold union_commute)\nqed\n\nlemma concat_fold1:\n  \"fold (\\<lambda>m ms. ms + m)  ((l1::'a multiset list)@l2) s = fold (\\<lambda>m ms. ms + m)  l1 {#} + \n                                                         fold (\\<lambda>m ms. ms + m) l2 s\"\nproof (induct l1)\n  case Nil thus ?case by auto\nnext\n  case (Cons l l1)\n  thus ?case\n    by (metis (full_types) append_Cons union_commute union_fold union_lcomm)\nqed\n\nlemma same_channel_messages:\n  \"(\\<forall>i<length ls.         \n           (aux (ls'!i)) ch_id = (aux (ls!i)) ch_id) \\<Longrightarrow>\n      length ls = length ls' \\<Longrightarrow> \n (channel_messages ch_id aux ls ) = (channel_messages  ch_id aux ls')\" \nproof -\n assume a0: \"(\\<forall>i<length ls.         \n               (aux (ls'!i)) ch_id = (aux (ls!i)) ch_id)\" and\n        a1:\"length ls = length ls'\" \n then have  \" [((aux i) ch_id). i <-ls] =  [((aux i) ch_id). i <-ls']\"    \n   by (auto intro: nth_Cons' nth_equalityI)\n thus ?thesis unfolding channel_messages_def by auto\nqed\n\nlemma channel_local_s:\n\"\\<not> (x \\<in># s) \\<Longrightarrow>\n x \\<in>#  fold (\\<lambda>m ms. ms + m)  [((aux i) ch_id). i <-ls] s \\<Longrightarrow>\n \\<exists>i. (i<length ls) \\<and> x \\<in># ((aux (ls!i)) ch_id)\n\"\nproof(induct ls arbitrary: s)\n  case Nil then show ?case by auto\nnext\n  case (Cons l ls) \n    then have \"x\\<in>#  (aux l ch_id) \\<or> \n               (\\<not>(x\\<in>#  (aux l ch_id))) \\<and> \n                  x \\<in># (fold (\\<lambda>m ms. ms + m) (map (\\<lambda>i. (aux i ch_id)) (ls))) (s + (aux l ch_id))\"\n    by auto\n    then show ?case proof\n      assume \"x \\<in># (aux l ch_id)\" then show ?thesis by auto\n    next\n      assume ass:\n         \"(\\<not>(x\\<in>#  (aux l ch_id))) \\<and> \n          x \\<in># fold (\\<lambda>m ms. ms + m) (map (\\<lambda>i. (aux i ch_id)) ls) (s +  (aux l ch_id))\"             \n      thus ?thesis  \n        using Cons(1)[of \"(aux l ch_id) + s\"] ass Cons(2) by (auto simp add: union_commute)\n    qed\nqed\n\nlemma in_channel_local: \n  \"x \\<in># channel_messages ch_id aux ls \\<Longrightarrow>    \n   \\<exists>i. (i<length ls) \\<and> x \\<in># ((aux (ls!i)) ch_id)\"\nunfolding channel_messages_def \nusing channel_local_s[of x \"{#}\"] by auto\n\nlemma l1':\"s\\<subseteq>#s1 \\<Longrightarrow>\n           s\\<subseteq>#fold (\\<lambda>m ms. ms + m) ls s1\"\nproof (induct ls arbitrary: s1)\n  case Nil thus ?case by auto\nnext\n  case (Cons l ls)\n  then have \"s\\<subseteq>#s1 + l\" \n    using add.commute subset_mset.dual_order.trans\n      by (simp add: Cons.prems subset_mset.add_increasing2)    \n  moreover have \"fold (\\<lambda>m ms. ms + m) ls (s1 +  l ) = \n                 fold (\\<lambda>m ms. ms + m) (l#ls) s1\" by auto\n  moreover have \"s1 +  l =  l + s1\"\n    by (simp add: add.commute) \n  ultimately show ?case using Cons(1)[of \" l+ s1\"] by metis\nqed\n\nlemma l1:\"s\\<subseteq>#s1 \\<Longrightarrow>\n          s\\<subseteq>#fold (\\<lambda>m ms. ms + m) (map (\\<lambda>i. (aux i ch_id)) ls) s1\"\nusing l1' by auto\n\nlemma channel_in_union: \n  \"i<length ls \\<Longrightarrow>\n    ls!i \\<subseteq># fold (\\<lambda>m ms. ms + m)  ls s\"\nproof (induct ls arbitrary: s i)\n  case Nil thus ?case by auto\nnext\n  case (Cons l ls)  \n  thus ?case proof (cases \"(l#ls)!i = l\")\n    case True\n    have f1:\" l\\<subseteq># s + l\" by auto\n    have \"fold (\\<lambda>m ms. ms + m) (l#ls) s = \n               fold (\\<lambda>m ms. ms + m) ls (s +  l)\" by auto\n    then show ?thesis using l1'[OF f1] True by auto\n  next\n    case False             \n    obtain i' where f1:\"(l#ls)!i = ls!i' \\<and> i'<length ls\"\n      using Cons.prems False less_Suc_eq_0_disj by auto      \n    then have \" ls!i' \\<subseteq># fold (\\<lambda>m ms. ms + m) ls (s +  l)\"\n      using Cons(1) less_Suc_eq_0_disj by auto\n    thus ?thesis using f1 by auto\n  qed \nqed\n\nlemma in_set_messages_in_channel: \n  assumes a0:\"i<length ls\"\n  shows \"((aux (ls!i)) ch_id) \\<subseteq># fold (\\<lambda>m ms. ms + m)  [((aux i) ch_id). i <-ls] s\"\nproof -\n  have a0:\"i<length [((aux i) ch_id). i <-ls]\" using a0 by auto\n  have \"[((aux i) ch_id). i <-ls]!i = ((aux (ls!i)) ch_id)\" using a0 by auto\n  then show ?thesis using channel_in_union[OF a0] by auto\nqed\n\nlemma i_messages_in_channel: \n  \" i<length ls \\<Longrightarrow>\n   ((aux (ls!i)) ch_id) \\<subseteq># channel_messages  ch_id aux ls\"\n unfolding channel_messages_def using in_set_messages_in_channel[of i ls ] by auto\n\nlemma union_fold_eq_add_sub:\n  assumes a0:\"i< length (ls::'a multiset list)\"\n  shows \"fold (\\<lambda>m ms. ms + m) ls s = (fold (\\<lambda>m ms. ms + m) ls s - ls!i) + ls!i\"\n using subset_mset.le_imp_diff_is_add channel_in_union[OF a0] by auto\n\n\nlemma aux_list_3:\n assumes a0: \"i<length ls\" and\n         a1: \"length ls - (i + 1) = k\"\n shows \"\\<exists>ls1 ls2. ls = ls1@[ls!i]@ls2 \\<and> length ls1 = i \\<and> length ls2 = length ls - i - 1\"\n\nusing a0 a1  \nproof (induct k arbitrary: ls i)\n case 0 thus ?case using take_Suc_conv_app_nth by force   \nnext\n case (Suc k)      \n   then obtain i' where i':\"i'=Suc i \\<and> i' < length ls\" using Suc\n     by (metis Suc_eq_plus1 Suc_lessI diff_self_eq_0 less_nat_zero_code zero_less_Suc)\n   moreover then have \"length ls - (i' + 1) = k\" using Suc(3) by auto\n   ultimately obtain ls1 ls2 where \"ls = ls1 @ [ls ! i'] @ ls2 \\<and> length ls1 = i' \\<and> length ls2 = length ls - i' - 1\"  \n     using Suc (1) by fastforce    \n   moreover then obtain ls1' where \"ls1 = ls1'@[ls!i]\"  using i' Suc(2)\n     by (metis append_eq_conv_conj hd_drop_conv_nth take_hd_drop) \n   ultimately have \"ls = ls1'@[ls!i]@([ls!i']@ls2) \\<and> length ls1' = i \\<and> \n                    length ([ls!i']@ls2) = length ls - i - 1\" using i' by auto\n   thus ?case by fastforce\n qed\n\n\nlemma eq_ls1_ls2:\n  assumes a0:\"i<length (ls::'a multiset list)\" and\n     a1: \"length ls = length ls'\" and\n     a2: \"\\<forall>i'<length ls. i' \\<noteq> i \\<longrightarrow> ls!i' = ls'!i'\"\n  shows \"\\<exists>ls1 ls2. ls = ls1@[ls!i]@ls2 \\<and> ls' = ls1@[ls'!i]@ ls2 \\<and> \n         length ls1 = i \\<and> length ls2 = length ls - i - 1\"\nproof -\nobtain ls1 ls2 where \n  ls1:\"ls = ls1@[ls!i]@ls2 \\<and> length ls1 = i \\<and> length ls2 = length ls - i - 1\" \n    using a0 aux_list_3 by metis\n  also obtain ls1' ls2' where \n  ls1':\"ls' = ls1'@[ls'!i]@ ls2' \\<and> length ls1' = i \\<and> length ls2' = length ls' - i - 1\" using a0 a1 aux_list_3 by metis\n  ultimately have \"ls1=ls1' \\<and> ls2=ls2'\"\n  proof-\n    have ls1_eq_len:\"length ls1=length ls1'\" using a0 a1 ls1 ls1' by auto\n    have ls2_eq_len:\"length ls2 = length ls2'\" using a0 a1 ls1 ls1' by auto \n    have i_less_ls:\"\\<forall>i'<i. i'< length ls\" using a0 by auto\n    have \"ls1=ls1'\" \n    proof -\n      have \"\\<forall>i'<i. ls1!i' = ls1'!i'\" using ls1 ls1' i_less_ls a2\n        by (metis cancel_comm_monoid_add_class.diff_cancel not_less0 nth_append zero_less_diff)  \n      thus ?thesis using ls1_eq_len ls1 by (simp add: nth_equalityI) \n    qed \n    also have \"ls2=ls2'\"\n    proof -      \n      have \"\\<forall>i'<length ls - i - 1. ls2!i' = ls!(i+i'+1)\" \n        using ls1\n        by (metis Suc_eq_plus1 add_Suc_right append_Cons append_Nil nth_Cons_Suc nth_append_length_plus)\n      also have \"\\<forall>i'<length ls - i - 1. ls2'!i' = ls'!(i+i'+1)\" \n        using ls1'\n        by (metis Suc_eq_plus1 add_Suc_right append_Cons append_Nil nth_Cons_Suc nth_append_length_plus)\n      ultimately have \"\\<forall>i'<length ls - i - 1. ls2!i' = ls2'!i'\" using a1 a2\n        by auto \n      thus ?thesis using ls2_eq_len ls1' ls1 by (simp add: nth_equalityI) \n    qed\n    ultimately show ?thesis by auto\n  qed\n  thus ?thesis using ls1 ls1' by fastforce\nqed \n\n\nlemma remove_diff_eq:\n  assumes a0:\"i<length (ls::'a multiset list)\" and\n     a1: \"length ls = length ls'\" and\n     a2: \"\\<forall>i'<length ls. i' \\<noteq> i \\<longrightarrow> ls!i' = ls'!i'\" \n  shows \"(fold (\\<lambda>m ms. ms + m) ls s) - (ls ! i) = (fold (\\<lambda>m ms. ms + m) ls' s) - (ls' ! i)\"\nproof -\n  obtain ls1 ls2 where \n   ls:\"ls = ls1@(ls!i#ls2) \\<and> ls' = ls1@(ls'!i# ls2) \\<and> \n    length ls1 = i \\<and> length ls2 = length ls - i - 1\" using eq_ls1_ls2[OF a0 a1 a2] by auto\n  then have \"(fold (\\<lambda>m ms. ms + m) ls s) = \n     fold (\\<lambda>m ms. ms + m)  ls1 {#} + ls!i + fold (\\<lambda>m ms. ms + m) ls2 s\" \n    using concat_fold1 union_fold by (metis union_assoc) \n  also have \"(fold (\\<lambda>m ms. ms + m) ls' s) = \n     fold (\\<lambda>m ms. ms + m)  ls1 {#} + ls'!i + fold (\\<lambda>m ms. ms + m) ls2 s\"\n    using ls concat_fold1 union_fold by (metis union_assoc)\n  ultimately show ?thesis\n    by (metis (no_types, lifting) add_implies_diff union_assoc union_commute) \nqed\n\nlemma add_msg_rec:\n  assumes a0:\"r1 + m = r2\" and\n          a1:\"m \\<subseteq># s - (r1 -r0)\" and\n          a2:\"r1 - r0 \\<subseteq># s\" and\n          a3:\"r0 \\<subseteq># r1\" \n  shows \"r2 - r0 \\<subseteq># s\"\nusing a0 a1 a2 a3 \n  by (simp add: subset_mset.le_diff_conv2 union_commute)\n    \nlemma add_msg_send:\n  assumes a0:\"r\\<subseteq># b + (s1 - s0)\" and\n          a1:\"s0 \\<subseteq># s1\"                   \n  shows \"r \\<subseteq># b + ((s1+{# m #}) - s0)\"\nproof -\n  have \"r - b \\<subseteq># s1 - s0 + {#m#}\"\n    by (metis (no_types) a0 add.commute mset_subset_eq_add_left subset_eq_diff_conv subset_mset.order.trans)\n  then show ?thesis\n    by (metis a1 add.commute subset_eq_diff_conv subset_mset.diff_add_assoc2)\nqed\n  \n  \nlemma same_message_channel:\n assumes \n        a1:\"length ls = length ls'\" and\n        a2:\"\\<forall>i'. i' \\<noteq> i \\<longrightarrow> aux_msg (ls ! i') ch = aux_msg (ls' ! i') ch\" and\n        a3: \"aux_msg (ls ! i) ch = aux_msg (ls' ! i) ch\" \n shows\n    \"channel_messages  ch  aux_msg ls  =\n      channel_messages  ch aux_msg ls'\"\nproof -\n  let ?ls=\"(map (\\<lambda>i. aux_msg i ch) ls)\"\n  let ?ls' = \"(map (\\<lambda>i. aux_msg i ch) ls')\"  \n  have a1:\"length ?ls = length ?ls'\" using a1 by auto\n  moreover have a2:\"\\<forall>i'<length ?ls. ?ls!i' = ?ls'!i'\" using  a1 a2 a3 by auto\n  ultimately have \"?ls = ?ls'\" by (auto intro: nth_equalityI) \n  thus ?thesis unfolding channel_messages_def by auto   \nqed\n\nlemma add_message_channel:\n assumes a0:\"i<length ls\" and\n        a1:\"length ls = length ls'\" and\n        a2:\"\\<forall>i'. i' \\<noteq> i \\<longrightarrow> aux_msg (ls ! i') ch = aux_msg (ls' ! i') ch\" and\n        a3: \"aux_msg (ls' ! i) ch = aux_msg (ls ! i) ch + mess\" \n shows\n    \"channel_messages  ch  aux_msg ls  + mess =\n      channel_messages  ch aux_msg ls'\"\nunfolding channel_messages_def \nproof -\n  let ?ls=\"(map (\\<lambda>i. aux_msg i ch) ls)\"\n  let ?ls' = \"(map (\\<lambda>i. aux_msg i ch) ls')\"\n  have a0:\"i<length ?ls\" using a0 by auto\n  have a1:\"length ?ls = length ?ls'\" using a1 by auto\n  have a2:\"\\<forall>i'<length ?ls. i' \\<noteq> i \\<longrightarrow> ?ls!i' = ?ls'!i'\" using a0 a1 a2 by auto\n  obtain ls1 ls2 where \n   ls:\"?ls = ls1@(?ls!i#ls2) \\<and> ?ls' = ls1@(?ls'!i# ls2) \\<and> \n    length ls1 = i \\<and> length ls2 = length ?ls - i - 1\" using eq_ls1_ls2[OF a0 a1 a2]  by auto\n  have ls_eq:\"(fold (\\<lambda>m ms. ms + m) ?ls {#}) =  \n             fold (\\<lambda>m ms. ms + m)  ls1 {#} + ?ls!i + fold (\\<lambda>m ms. ms + m) ls2 {#}\" and\n       ls'_eq:\"(fold (\\<lambda>m ms. ms + m) ?ls' {#}) =  \n             fold (\\<lambda>m ms. ms + m)  ls1 {#} + ?ls'!i + fold (\\<lambda>m ms. ms + m) ls2 {#}\"\n    by (metis  ls concat_fold1 union_fold union_assoc)+\n  also have ls_map:\"?ls!i = aux_msg (ls ! i) ch \\<and> ?ls'!i = aux_msg(ls'!i) ch\" using a2 a0 a1 by auto\n  ultimately show \"fold (\\<lambda>m ms. ms + m) ?ls {#} + mess = fold (\\<lambda>m ms. ms + m) ?ls' {#}\"   \n  proof -\n    have \"fold (\\<lambda>m ma. ma + m) (map (\\<lambda>l. aux_msg l ch) ls) {#} + mess = \n        fold (\\<lambda>m ma. ma + m) ls1 {#} + map (\\<lambda>l. aux_msg l ch) ls ! i + (fold (\\<lambda>m ma. ma + m) ls2 {#} + mess)\"\n    using ls_eq union_assoc by auto\n    then have \"fold (\\<lambda>m ma. ma + m) (map (\\<lambda>l. aux_msg l ch) ls) {#} + mess = \n              fold (\\<lambda>m ma. ma + m) ls1 {#} + aux_msg (ls ! i) ch + (mess + fold (\\<lambda>m ma. ma + m) ls2 {#})\"\n      by (simp add:ls_map union_commute)\n    then show ?thesis\n      by (simp add: a3 ls'_eq ls_map union_assoc)\n    qed  \nqed\n\n\ndefinition channel_sent_messages :: \"channel_id \\<Rightarrow> (nat \\<Rightarrow> channel_id \\<Rightarrow> Message multiset) \\<Rightarrow> locals list \\<Rightarrow> Message multiset\"\nwhere                                      \n\"channel_sent_messages ch_id msgs ls \\<equiv> (channel_messages ch_id a_que_aux ls) - (channel_messages ch_id msgs [0..< (length ls)])\"\n                                             \ndefinition channel_received_messages :: \"channel_id \\<Rightarrow>(nat => channel_id \\<Rightarrow> Message multiset) \\<Rightarrow> locals list \\<Rightarrow> Message multiset\"\nwhere\n\"channel_received_messages ch_id msgs ls \\<equiv> channel_messages  ch_id r_que_aux ls - (channel_messages ch_id msgs [0..< (length ls)])\"\n\n\ndefinition ch_spec\nwhere\n\"ch_spec B adds rems ch_id x \\<equiv>\n let ch = the (chans (communication_' x) ch_id) in\n channel_get_messages ch = \n  (B ch_id + channel_sent_messages  ch_id  adds (locals_' x) ) -\n             channel_received_messages  ch_id  rems (locals_' x) \\<and>\n  channel_received_messages  ch_id rems (locals_' x) \\<subseteq># \n    (B ch_id + channel_sent_messages ch_id adds  (locals_' x)) \\<and>\n(size (channel_get_messages ch) \\<le> \n   channel_size (get_channel conf ch_id))  \\<and> \n    channel_messages ch_id rems [0..<length (locals_' x)] \\<subseteq># \n    channel_messages  ch_id r_que_aux (locals_' x) \\<and>\n    channel_messages ch_id adds [0..<length (locals_' x)] \\<subseteq># \n    channel_messages  ch_id a_que_aux (locals_' x)\"\n                        (*x s :==(f s1 s2 s3 s4) s *)\n    \nlemma \"Q s = True \\<Longrightarrow> card ({|s.  Q s|}) = 1\" \n  by auto\n \n \ndefinition channel_spec\nwhere\n\"channel_spec B adds rems ch_id s \\<equiv> \n   \\<forall>ch. \n     (chans (communication_' s) ch_id = Some ch \\<and> \n     ch_id_queuing conf ch_id \\<longrightarrow>  \n       ch_spec B adds rems ch_id s)\n\"\n\ndefinition channel_spec_mut\nwhere\n\"channel_spec_mut B adds rems ch_id s \\<equiv> \n   \\<forall>ch. \n     (chans (communication_' s) ch_id = Some ch \\<and> \n      mut ch = 0 \\<and>\n     ch_id_queuing conf ch_id \\<longrightarrow>  \n       ch_spec B adds rems ch_id s)\n\"\n\n\nlemma channel_spec_intro:\n \"\\<forall>ch.  \n     (chans (communication_' x) ch_id) = Some ch \\<and> \n     ch_id_queuing conf ch_id  \\<longrightarrow> \n   ch_spec B adds rems ch_id  x \\<Longrightarrow>\n  channel_spec B adds rems ch_id x\"\nunfolding channel_spec_def ch_spec_def by fastforce\n\nlemma channel_spec_dest1:\n  \"channel_spec B  adds rems ch_id x \\<Longrightarrow>\n    (chans (communication_' x) ch_id) = Some ch \\<and> \n     ch_id_queuing conf ch_id  \\<longrightarrow>  \n    ch_spec B  adds rems ch_id x\"\nunfolding channel_spec_def ch_spec_def by fastforce\n\nlemma channel_spec_dest2:\n    \"channel_spec B  adds rems ch_id x \\<Longrightarrow>\n    (chans (communication_' x) ch_id) = Some ch \\<and> \n     ch_id_queuing conf ch_id  \\<Longrightarrow> \n    ch_spec B  adds rems ch_id x\"\nunfolding channel_spec_def ch_spec_def by fastforce\n\n\nsubsection {*definitions and lemmas on constrainings over local and comm fields\n             to preserve channel spec*}\ntext{* preserves\\_locals\\_constr establishes local variables to the component and the enviroment\n       that cannot modified for correctness of the specification \n       locals: evnt (event being executed); pt (port where the operation is carried out);\n               and aux\\_msg (auxiliary variable to verify the queue. This does not have necessary \n               to be for all i'. i!=i') as reflected by preserves\\_locals\\_constr'*}\ndefinition preserves_locals_constr\nwhere\n\"preserves_locals_constr  \\<equiv> \n    {(x,x',i). length (locals_' x) =  length (locals_' x') \\<and>\n               (\\<forall>i'. (i\\<noteq>i' \\<longrightarrow> evnt ((locals_' x)!i') = evnt ((locals_' x')!i') \\<and>\n                                pt ((locals_' x)!i') = pt ((locals_' x')!i') \\<and>                                \n                                (a_que_aux ((locals_' x)!i') = a_que_aux ((locals_' x')!i')) \\<and>\n                                (r_que_aux ((locals_' x)!i') = r_que_aux ((locals_' x')!i'))) \\<and>\n                     (i=i' \\<longrightarrow> evnt ((locals_' x)!i) = evnt ((locals_' x')!i) \\<and>\n                                pt ((locals_' x)!i) = pt ((locals_' x')!i) ))\n   }\n\"\n\ndefinition preserves_locals_constr'\nwhere\n\"preserves_locals_constr'  \\<equiv> \n    {(x,x',i). length (locals_' x) =  length (locals_' x') \\<and>\n               (\\<forall>i'. evnt ((locals_' x)!i') = evnt ((locals_' x')!i') \\<and>\n                      pt ((locals_' x)!i') = pt ((locals_' x')!i') \\<and>                     \n                     a_que_aux ((locals_' x)!i') (port_channel conf (communication_' x) (pt ((locals_' x)!i)))  = \n                     a_que_aux ((locals_' x')!i') (port_channel conf (communication_' x') (pt ((locals_' x)!i))) \\<and>\n                      r_que_aux ((locals_' x)!i') (port_channel conf (communication_' x) (pt ((locals_' x)!i)))  = \n                      r_que_aux ((locals_' x')!i') (port_channel conf (communication_' x') (pt ((locals_' x)!i))) )\n   }\n\"\n\nlemma preserves_locals'_D1:\n  \"(x,x',i)\\<in> preserves_locals_constr' \\<Longrightarrow> \n    length (locals_' x) =  length (locals_' x')\n  \"\n unfolding preserves_locals_constr'_def by auto\n\nlemma preserves_locals'_D2:\n  \"(x,x',i)\\<in> preserves_locals_constr' \\<Longrightarrow> \n    (\\<forall>i'. evnt ((locals_' x)!i') = evnt ((locals_' x')!i') \\<and>\n          pt ((locals_' x)!i') = pt ((locals_' x')!i') \\<and>                   \n         a_que_aux ((locals_' x)!i') (port_channel conf (communication_' x) (pt ((locals_' x)!i)))  = \n         a_que_aux ((locals_' x')!i') (port_channel conf (communication_' x') (pt ((locals_' x)!i))) \\<and>\n          r_que_aux ((locals_' x)!i') (port_channel conf (communication_' x) (pt ((locals_' x)!i)))  = \n          r_que_aux ((locals_' x')!i') (port_channel conf (communication_' x') (pt ((locals_' x)!i))) )\n  \"\nunfolding preserves_locals_constr'_def by fastforce\n\nlemma preserves_locals'_D3:\n  \"(x,x',i')\\<in> preserves_locals_constr' \\<Longrightarrow>        \n      a_que_aux ((locals_' x)!i') (port_channel conf (communication_' x) (pt ((locals_' x)!i')))  = \n     a_que_aux ((locals_' x')!i') (port_channel conf (communication_' x') (pt ((locals_' x)!i'))) \\<and>\n      r_que_aux ((locals_' x)!i') (port_channel conf (communication_' x) (pt ((locals_' x)!i')))  = \n      r_que_aux ((locals_' x')!i') (port_channel conf (communication_' x') (pt ((locals_' x)!i'))) \n  \"\nunfolding preserves_locals_constr'_def by fastforce\n\nlemma preserv_locals_sim'_a1: \n  \"(x,x',i) \\<in> preserves_locals_constr' \\<Longrightarrow>\n   (x',x,i) \\<in> preserves_locals_constr'\"\nproof -\n  assume a0:\"(x,x',i) \\<in> preserves_locals_constr'\"       \n  thus ?thesis unfolding preserves_locals_constr'_def \n  apply auto by metis+\nqed\n\nlemma preserv_locals_sim': \n     \"(x,x',i) \\<in> preserves_locals_constr' \\<longleftrightarrow>\n      (x',x,i) \\<in> preserves_locals_constr'\"\nusing preserv_locals_sim'_a1 by metis\n\nlemma preserves_locals_D1:\n  \"(x,x',i)\\<in> preserves_locals_constr \\<Longrightarrow> \n    length (locals_' x) =  length (locals_' x')\n  \"\n unfolding preserves_locals_constr_def by auto\n\nlemma preserves_locals_D2:\n  \"(x,x',i)\\<in> preserves_locals_constr \\<Longrightarrow> \n     \\<forall>i'. (i\\<noteq>i' \\<longrightarrow> evnt ((locals_' x)!i') = evnt ((locals_' x')!i') \\<and>\n                    pt ((locals_' x)!i') = pt ((locals_' x')!i') \\<and>                    \n                    a_que_aux ((locals_' x)!i')  = \n                    a_que_aux ((locals_' x')!i') \\<and>\n                    r_que_aux ((locals_' x)!i')  = \n                    r_que_aux ((locals_' x')!i') )\n  \"\nunfolding preserves_locals_constr_def by fastforce\n\nlemma preserves_locals_D3:\n  \"(x,x',i)\\<in> preserves_locals_constr \\<Longrightarrow> \n     evnt ((locals_' x)!i) = evnt ((locals_' x')!i) \\<and>\n     pt ((locals_' x)!i) = pt ((locals_' x')!i) \n  \"\nunfolding preserves_locals_constr_def by auto\n\nlemma preserv_locals_sim_a1: \n  \"(x,x',i) \\<in> preserves_locals_constr \\<Longrightarrow>\n   (x',x,i) \\<in> preserves_locals_constr\"\nproof -\n  assume a0:\"(x,x',i) \\<in> preserves_locals_constr\"  \n  then have a1:\"length (locals_' x) =  length (locals_' x') \\<and>\n             (\\<forall>i'. (i\\<noteq>i' \\<longrightarrow>  evnt ((locals_' x)!i') = evnt ((locals_' x')!i') \\<and>\n                               pt ((locals_' x)!i') = pt ((locals_' x')!i') \\<and>                               \n                               a_que_aux ((locals_' x)!i')  = \n                                a_que_aux ((locals_' x')!i') \\<and>\n                                r_que_aux ((locals_' x)!i')  = \n                               r_que_aux ((locals_' x')!i')) \\<and>\n                   (i=i' \\<longrightarrow> evnt ((locals_' x)!i) = evnt ((locals_' x')!i) \\<and>\n                                pt ((locals_' x)!i) = pt ((locals_' x')!i)))\n                               \"\n  unfolding preserves_locals_constr_def by fastforce\n  then have l:\"length (locals_' x') =  length (locals_' x)\" by auto\n  have \"(\\<forall>i'. (i\\<noteq>i' \\<longrightarrow>  evnt ((locals_' x)!i') = evnt ((locals_' x')!i') \\<and>\n                         pt ((locals_' x)!i') = pt ((locals_' x')!i') \\<and>                         \n                         a_que_aux ((locals_' x)!i')  = \n                          a_que_aux ((locals_' x')!i') \\<and>\n                          r_que_aux ((locals_' x)!i')  = \n                          r_que_aux ((locals_' x')!i') ) \\<and>\n               (i=i' \\<longrightarrow> evnt ((locals_' x')!i) = evnt ((locals_' x)!i) \\<and>\n                         pt ((locals_' x')!i) = pt ((locals_' x)!i)))\"\n  using a1 by fastforce \n  thus ?thesis using l unfolding preserves_locals_constr_def by auto\nqed\n\nlemma aux_eq: \"(x,x',i) \\<in> preserves_locals_constr \\<Longrightarrow>\n               (a_que_aux ((locals_' x)!i) = a_que_aux ((locals_' x')!i)) \\<and>\n               (r_que_aux ((locals_' x)!i) = r_que_aux ((locals_' x')!i)) \\<Longrightarrow>\n               \\<forall>i. (a_que_aux ((locals_' x)!i) = a_que_aux ((locals_' x')!i)) \\<and>\n                   (r_que_aux ((locals_' x)!i) = r_que_aux ((locals_' x')!i))\"\nusing preserves_locals_D2 by fastforce\n\nlemma preserv_locals_sim: \n     \"(x,x',i) \\<in> preserves_locals_constr \\<longleftrightarrow>\n      (x',x,i) \\<in> preserves_locals_constr\"\nusing preserv_locals_sim_a1 by metis\n\ndefinition preserves_comm_constr\nwhere\n\"preserves_comm_constr  \\<equiv> \n   {(x,x',ch). (\\<forall>ch'. ch\\<noteq>ch' \\<longrightarrow> (chans (communication_' x) ch') = \n                                  (chans (communication_' x') ch')) \\<and>\n                ports (communication_' x) = ports (communication_' x')}\n\"\n\nlemma preserv_comm_sim_a1: \n    \"(x,x',ch) \\<in> preserves_comm_constr \\<Longrightarrow>\n     (x',x,ch) \\<in> preserves_comm_constr\"\nproof -\n  {\n   assume a0:\"(x,x',ch) \\<in> preserves_comm_constr\" \n   then have channels:\n   \"(\\<forall>ch'. (ch\\<noteq>ch'\\<longrightarrow> (chans (communication_' x)) ch' =  (chans (communication_' x')) ch')) \\<and>\n           ports (communication_' x) = ports (communication_' x')\"\n     using a0 unfolding preserves_comm_constr_def by auto  \n    then show \"(x',x,ch) \\<in> preserves_comm_constr\"\n    unfolding preserves_comm_constr_def by fastforce    \n  }\nqed\n\nlemma preserv_comm_sim:\n   \"(x',x,ch) \\<in> preserves_comm_constr \\<longleftrightarrow>\n    (x,x',ch) \\<in> preserves_comm_constr\"\nusing preserv_comm_sim_a1\nby metis \n\nlemma preserves_comm_D2:\"\n       (x,x',ch_id)\\<in> preserves_comm_constr \\<Longrightarrow>\n       \\<forall>ch_id'. ch_id\\<noteq>ch_id' \\<longrightarrow> (chans (communication_' x)) ch_id' =  \n                                 (chans (communication_' x')) ch_id'\"\nunfolding preserves_comm_constr_def\nby auto\n\nlemma preserves_comm_D3:\"\n       (x,x',ch_id)\\<in> preserves_comm_constr \\<Longrightarrow>\n       ports (communication_' x) = ports (communication_' x')\"\nunfolding preserves_comm_constr_def\nby auto\n\ntext{* lemmas on modifying the auxiliar set of messages*}\n\n\n\nlemma channel_messages_eq:\n     \"\n     (x1,y1,i) \\<in> preserves_locals_constr  \\<Longrightarrow>\n    a_que_aux ((locals_' x1)!i) ch  = a_que_aux ((locals_' y1)!i) ch \\<and>\n    r_que_aux ((locals_' x1)!i) ch  = r_que_aux ((locals_' y1)!i) ch \\<Longrightarrow>\n     (channel_messages  ch a_que_aux (locals_' x1)) = \n       (channel_messages  ch a_que_aux (locals_' y1)) \\<and>\n       (channel_messages  ch r_que_aux (locals_' x1)) = \n       (channel_messages  ch r_que_aux (locals_' y1))\"\nproof-\n  assume \n         a1: \"(x1,y1,i) \\<in> preserves_locals_constr\" and\n         a2: \"(a_que_aux ((locals_' x1)!i) ch  = \n              a_que_aux ((locals_' y1)!i) ch) \\<and>\n              (r_que_aux ((locals_' x1)!i) ch  = \n              r_que_aux ((locals_' y1)!i) ch)\"\n  then have \"\\<forall>i'. i\\<noteq>i' \\<longrightarrow>  evnt ((locals_' x1)!i') = evnt ((locals_' y1)!i') \\<and>\n                             pt ((locals_' x1)!i') = pt ((locals_' y1)!i') \\<and>                             \n                             a_que_aux ((locals_' x1)!i') ch = \n                             a_que_aux ((locals_' y1)!i') ch \\<and>\n                             r_que_aux ((locals_' x1)!i') ch  = \n                             r_que_aux ((locals_' y1)!i') ch\"\n    using preserves_locals_D2 by auto\n  moreover have \"pt ((locals_' x1)!i) = pt ((locals_' y1)!i)\" \n    using a1 preserves_locals_D3 by auto  \n  moreover have \"evnt ((locals_' x1) ! i) = evnt ((locals_' y1)  ! i)\"\n    using preserves_locals_D3 a1 by auto\n \n  ultimately have \"(\\<forall>i'<length (locals_' x1).\n                  evnt ((locals_' x1) ! i') = evnt ((locals_' y1)  ! i') \\<and>\n                  a_que_aux ((locals_' x1)!i') ch = \n                 a_que_aux ((locals_' y1)!i') ch \\<and>\n                 r_que_aux ((locals_' x1)!i') ch = \n                 r_que_aux ((locals_' y1)!i') ch \\<and> \n                  pt ((locals_' x1) ! i') = pt ((locals_' y1)  ! i'))\"\n  using a2  by auto  \n  also have \"length (locals_' x1) = length (locals_' y1)\" using preserves_locals_D1 a1 by auto \n  ultimately show ?thesis using   preserves_locals_D1\n    by (simp add: same_channel_messages) \nqed\n\n  \n  lemma channel_messages_eq':\n     \"(x1,y1,i) \\<in> preserves_locals_constr'  \\<Longrightarrow>   \n      (port_channel conf (communication_' x1) (pt ((locals_' x1)!i))) =\n      (port_channel conf (communication_' y1) (pt ((locals_' x1)!i))) \\<Longrightarrow>\n     (channel_messages  (port_channel conf (communication_' x1) (pt ((locals_' x1)!i))) a_que_aux (locals_' x1)) = \n       (channel_messages  (port_channel conf  (communication_' y1) (pt ((locals_' x1)!i))) a_que_aux (locals_' y1)) \\<and>\n       (channel_messages  (port_channel conf  (communication_' x1)  (pt ((locals_' x1)!i))) r_que_aux (locals_' x1)) = \n       (channel_messages  (port_channel conf  (communication_' y1) (pt ((locals_' x1)!i))) r_que_aux (locals_' y1))\"\nproof-\n  assume \n         a1: \"(x1,y1,i) \\<in> preserves_locals_constr'\"   and\n         a1':\"(port_channel conf (communication_' x1) (pt ((locals_' x1)!i))) =\n              (port_channel conf (communication_' y1) (pt ((locals_' x1)!i)))\"\n         \n  have a2:\"\\<forall>i'.  evnt ((locals_' x1)!i') = evnt ((locals_' y1)!i') \\<and>\n                   pt ((locals_' x1)!i') = pt ((locals_' y1)!i') \\<and>                             \n                   a_que_aux ((locals_' x1)!i')  (port_channel conf (communication_' x1) (pt ((locals_' x1)!i))) = \n                   a_que_aux ((locals_' y1)!i')  (port_channel conf (communication_' y1) (pt ((locals_' x1)!i))) \\<and>\n                   r_que_aux ((locals_' x1)!i') (port_channel conf (communication_' x1) (pt ((locals_' x1)!i)))  = \n                   r_que_aux ((locals_' y1)!i') (port_channel conf (communication_' y1) (pt ((locals_' x1)!i)))\"\n    using a1 preserves_locals'_D2 by auto\n  moreover have \"pt ((locals_' x1)!i) = pt ((locals_' y1)!i)\" \n    using a1 unfolding preserves_locals_constr'_def by auto  \n  moreover have \"evnt ((locals_' x1) ! i) = evnt ((locals_' y1)  ! i)\"\n    using  a1 unfolding preserves_locals_constr'_def by auto\n \n  ultimately have \"(\\<forall>i'<length (locals_' x1).\n                  evnt ((locals_' x1) ! i') = evnt ((locals_' y1)  ! i') \\<and>\n                  a_que_aux ((locals_' x1)!i') (port_channel conf (communication_' x1) (pt ((locals_' x1)!i))) = \n                 a_que_aux ((locals_' y1)!i') (port_channel conf (communication_' y1) (pt ((locals_' x1)!i))) \\<and>\n                 r_que_aux ((locals_' x1)!i') (port_channel conf (communication_' x1) (pt ((locals_' x1)!i))) = \n                 r_que_aux ((locals_' y1)!i') (port_channel conf(communication_' y1)  (pt ((locals_' x1)!i))) \\<and> \n                  pt ((locals_' x1) ! i') = pt ((locals_' y1)  ! i'))\"\n  using a2  by auto  \n  also have \"length (locals_' x1) = length (locals_' y1)\" using preserves_locals'_D1 a1 by auto \n  ultimately show ?thesis using   preserves_locals'_D1 a1'\n    by (simp add: same_channel_messages) \nqed\n\n\n  \nlemma  add_channel_message_evnt:\n  \" i<length (locals_' x) \\<Longrightarrow>           \n  (x,x',i) \\<in> preserves_locals_constr \\<Longrightarrow>\n  aux_msg ((locals_' x')!i) ch =  aux_msg (locals_' x ! i) ch + mess \\<Longrightarrow>  \n  aux_msg = a_que_aux \\<or> aux_msg = r_que_aux \\<Longrightarrow>                             \n      channel_messages  ch aux_msg (locals_' x)  + mess  =\n              channel_messages  ch aux_msg (locals_' x') \n\"\nproof -\nassume a0:\"i<length (locals_' x)\" and                             \n       a1:  \"(x,x',i) \\<in> preserves_locals_constr\" and\n       a2: \"aux_msg ((locals_' x')!i) ch =  aux_msg (locals_' x ! i) ch + mess\" and\n       a3: \"aux_msg = a_que_aux \\<or> aux_msg = r_que_aux\" \n  have other_locals_eq:\"\\<forall>i'. i'\\<noteq>i \\<longrightarrow> evnt ((locals_' x)!i') = evnt ((locals_' x')!i') \\<and>\n                    pt ((locals_' x)!i') = pt ((locals_' x')!i') \\<and>                    \n                    aux_msg ((locals_' x)!i') ch = \n                    aux_msg ((locals_' x')!i') ch\"\n  using preserves_locals_D2[OF a1] a3  by fastforce    \n  then have other_aux_msg_eq:\"\\<forall>i'. i'\\<noteq>i \\<longrightarrow>\n                    aux_msg ((locals_' x)!i') ch = aux_msg ((locals_' x')!i') ch\"\n    by auto  \n  have len:\"length (locals_' x) = length (locals_' x')\" using preserves_locals_D1[OF a1] by auto\n  have assig: \"aux_msg ((locals_' x')!i) ch =  aux_msg (locals_' x ! i) ch  + mess\" \n    using a2 by auto\n  show ?thesis \n  using  a0 other_aux_msg_eq assig add_message_channel[OF a0 len _, of aux_msg ch mess] by auto  \nqed\n\nlemma  add_channel_message_not_evnt:\n  \"         \n  (x,x',i) \\<in> preserves_locals_constr \\<Longrightarrow>   \n  aux_msg = a_que_aux \\<or> aux_msg = r_que_aux \\<Longrightarrow>\n  aux_msg ((locals_' x)!i) ch =  aux_msg ((locals_' x')!i) ch \\<Longrightarrow>                                \n      channel_messages  ch aux_msg (locals_' x) =\n      channel_messages  ch aux_msg (locals_' x')  \n\"\nproof -\nassume a0:  \" (x,x',i) \\<in> preserves_locals_constr\" and\n       a1: \"aux_msg = a_que_aux \\<or> aux_msg = r_que_aux\" and \n       a2: \"aux_msg ((locals_' x)!i) ch =  aux_msg ((locals_' x')!i) ch\"            \n  have other_locals_eq:\"\\<forall>i'. i'\\<noteq>i \\<longrightarrow> evnt ((locals_' x)!i') = evnt ((locals_' x')!i') \\<and>\n                    pt ((locals_' x)!i') = pt ((locals_' x')!i') \\<and>                    \n                    aux_msg ((locals_' x)!i') ch = \n                    aux_msg ((locals_' x')!i') ch\"\n  using preserves_locals_D2[OF a0] a1  by fastforce \n  then have other_aux_msg_eq:\"\\<forall>i'. i'\\<noteq>i \\<longrightarrow>\n                    aux_msg ((locals_' x)!i') ch = aux_msg ((locals_' x')!i') ch\"\n    by auto \n  have len:\"length (locals_' x) = length (locals_' x')\" using preserves_locals_D1[OF a0] by auto\n  thus ?thesis using same_message_channel[OF len, of i aux_msg ch] other_aux_msg_eq a2 by auto\nqed \n\ntext{* Lemmas on the preservation of ch\\_spec and channel\\_spec when modifying abstract states \n       it is assumed that locals constrains are not changed*}\n\ntext{*not modifying the queue communication nor the auxiliary variable preserves\n     ch\\_spec and channel\\_spec this is the weakest precondition that satisfies\n    the relation*}\n\nsubsection {* Specification of the Rely Guarantee *}\n\n\nlemma ch_spec_eq:  \n    \"chans (communication_' x1) =chans (communication_' y1) \\<Longrightarrow>\n     (x1,y1,i) \\<in> preserves_locals_constr  \\<Longrightarrow>\n     a_que_aux ((locals_' x1)!i) ch = a_que_aux ((locals_' y1)!i) ch \\<Longrightarrow>\n     r_que_aux ((locals_' x1)!i) ch = r_que_aux ((locals_' y1)!i) ch \\<Longrightarrow>     \n     ch_spec B  adds rems ch x1 \\<Longrightarrow> ch_spec B  adds rems ch y1\"\nproof -\n  assume a0:\"chans (communication_' x1) =chans(communication_' y1)\" and\n         a1:\"(x1,y1,i) \\<in> preserves_locals_constr\" and\n         a2:\"a_que_aux ((locals_' x1)!i) ch = a_que_aux ((locals_' y1)!i) ch\" and\n         a3: \"r_que_aux ((locals_' x1)!i) ch = r_que_aux ((locals_' y1)!i) ch\" and\n         a4:\"ch_spec B  adds rems ch x1\"\n   have \n     eq_channel_message1:\n       \"channel_messages  ch  a_que_aux (locals_' x1)  = \n         channel_messages  ch a_que_aux (locals_' y1)\" and\n     eq_channel_message2:\n       \"channel_messages  ch  r_que_aux (locals_' x1)  = \n         channel_messages  ch r_que_aux (locals_' y1)\"\n     using channel_messages_eq a0 a1 a2 a3   by auto\n    thus ?thesis using a2 a3 a0 a4 unfolding ch_spec_def \n          channel_received_messages_def channel_sent_messages_def\n      using a1 preserves_locals_D1 by fastforce\nqed\n\nlemma channel_spec_eq:  \n    \"chans (communication_' x1) =chans(communication_' y1) \\<Longrightarrow>\n     (x1,y1,i) \\<in> preserves_locals_constr  \\<Longrightarrow>\n     a_que_aux ((locals_' x1)!i)  = a_que_aux ((locals_' y1)!i)  \\<Longrightarrow>\n     r_que_aux ((locals_' x1)!i)  = r_que_aux ((locals_' y1)!i)  \\<Longrightarrow>\n     channel_spec B  adds rems ch_id x1 \\<Longrightarrow>\n     channel_spec B  adds rems ch_id y1\"\nusing ch_spec_eq channel_spec_dest2 channel_spec_intro preserves_locals_D3 by fastforce \n\n\nlemma channel_not_queport_full_size:\n\" state_conf  x \\<Longrightarrow>  \n  port_open (communication_' x) p_id \\<Longrightarrow>\n  ch_spec B adds rems ch_id x \\<Longrightarrow>    \n  \\<not> port_full conf (communication_' x) p_id \\<Longrightarrow>\n  p_queuing conf (communication_' x) p_id \\<Longrightarrow>  \n  port_in_channel conf (communication_' x) p_id  ch_id \\<Longrightarrow>\n  (chans (communication_' x) ch_id) = Some ch \\<Longrightarrow>\n  size (channel_get_messages (channel_insert_message  ch m t) ) \\<le>\n   channel_size (get_channel conf ch_id) \n \"\nproof -\nassume\n   a0: \"ch_spec B adds rems ch_id x\" and\n   a1: \"\\<not> port_full conf (communication_' x) p_id \" and   \n   a1':\"port_open (communication_' x) p_id \" and\n   a2: \"p_queuing conf (communication_' x) p_id\" and\n   a3: \"port_in_channel conf (communication_' x) p_id ch_id\" and\n   a4: \"state_conf  x\" and   \n   a6: \"(chans (communication_' x) ch_id) = Some ch\"\n   have not_channe_full:\"\\<not> channel_full conf (communication_' x) ch_id\"\n     using port_not_full_channel_not_full[OF a4 a1' a1 a3]  by auto   \n   have \"chan_queuing ch\" \n     using a6 a2 a3 a4  ch_id_queuing_def option.sel p_queuing_def \n     by (metis a1' p_queuing_chan_queuing)      \n   then have \" channel_get_bufsize (channel_insert_message ch m t)\n                = (channel_get_bufsize ch) + 1\"\n     using insert_message_inc_buf_size  \n     by fastforce\n   moreover have \"\\<not> (channel_size (get_channel conf ch_id)  = \n                      channel_get_bufsize ch)\"\n     using not_channe_full a6 port_in_channel_get_channel[OF a3]  port_channel\n     unfolding channel_full_def\n     by fastforce\n   moreover have \"size (channel_get_messages ch) \\<le> \n                   channel_size (get_channel conf ch_id)\"\n     using Int_Collect a0 a6  unfolding ch_spec_def\n     using option.sel order_refl\n     using a3 channel_full_def channel_get_bufsize_def not_channe_full port_in_channel_get_channel by fastforce       \n   ultimately show ?thesis unfolding channel_get_bufsize_def\n     by auto           \n qed \n   \n  (* lemma channel_not_queport_empty_size:\n\" state_conf  x \\<Longrightarrow>  \n  ch_spec B adds rems ch_id x \\<Longrightarrow>      \n  p_queuing conf p_id \\<Longrightarrow>  \n  port_in_channel conf p_id  ch_id \\<Longrightarrow>\n  (chans (communication_' x) ch_id) = Some ch \\<Longrightarrow>\n  size (channel_get_messages (channel_remove_message  ch m) ) \\<le>\n   channel_size (get_channel conf ch_id) \n \"\nproof -\nassume\n   a0: \"ch_spec B adds rems ch_id x\" and   \n   a2: \"p_queuing conf p_id\" and\n   a3: \"port_in_channel conf p_id ch_id\" and\n   a4: \"state_conf  x\" and   \n   a6: \"(chans (communication_' x) ch_id) = Some ch\"     \n   have \"chan_queuing ch\" \n     using a6 a2 a3 a4 port_channel ch_id_queuing_def option.sel p_queuing_def state_conf_def\n     by metis (* by auto *)      \n   then have \" channel_get_bufsize (channel_remove_message ch m)\n                \\<le> (channel_get_bufsize ch)\"\n     using remove_message_less_eq_buf_size  \n     by fastforce\n   moreover have \"size (channel_get_messages ch) \\<le> \n                   channel_size (get_channel conf ch_id)\"\n     using Int_Collect a0 a6  unfolding ch_spec_def\n     using option.sel order_refl\n     using a3 channel_full_def channel_get_bufsize_def  port_in_channel_get_channel by fastforce       \n   ultimately show ?thesis unfolding channel_get_bufsize_def\n     by auto           \n qed *)\n   \n subsection {* Properties on channel spec*}   \n   text {* modifying the mutex preserves ch\\_spec*}\nlemma local_constr_eq_que_ch_spec:\n  \"ch_spec B adds rems ch_id x \\<Longrightarrow> \n   (x,x',i) \\<in> preserves_locals_constr \\<Longrightarrow>\n    channel_get_messages (the (chans (communication_' x) ch_id)) = \n    channel_get_messages (the (chans (communication_' x') ch_id)) \\<Longrightarrow>              \n   a_que_aux ((locals_' x)!i) ch_id = a_que_aux ((locals_' x')!i) ch_id \\<Longrightarrow>\n   r_que_aux ((locals_' x)!i) ch_id  = r_que_aux ((locals_' x')!i) ch_id \\<Longrightarrow>\n   ch_spec B adds rems ch_id x'\"\nproof - \n  assume a1: \"ch_spec B adds rems ch_id x\" and \n         a2: \"(x,x',i) \\<in> preserves_locals_constr\" and\n         a3: \" channel_get_messages (the (chans (communication_' x) ch_id)) = \n               channel_get_messages (the (chans (communication_' x') ch_id))\" and       \n         a4: \"a_que_aux ((locals_' x)!i) ch_id  = a_que_aux ((locals_' x')!i) ch_id\" and\n         a5: \"r_que_aux ((locals_' x)!i) ch_id = r_que_aux ((locals_' x')!i) ch_id\"\n   have \" channel_messages  ch_id a_que_aux (locals_' x)  = \n          channel_messages  ch_id a_que_aux (locals_' x') \\<and>\n          channel_messages  ch_id r_que_aux (locals_' x)  = \n          channel_messages  ch_id r_que_aux (locals_' x')\"        \n    unfolding preserves_locals_constr_def\n    using a2 channel_messages_eq a4 a5 by fastforce\n   then show ?thesis using a1 a3 \n     unfolding ch_spec_def channel_received_messages_def \n         channel_sent_messages_def Let_def\n     using a2 preserves_locals_D1 by fastforce\nqed\n\n\n\ntext {* modifying comm of ch=port\\_quechannel (pt ((locals\\_' x)!i)) \n       preserving locals const and comm constrains               \n        preserves channel\\_spec of any channel different from  ch\n      this helps to preserve the invariant when adding an element to the queue\n     in ch and modifying the aux\\_msg proving that the event does not\n      modify any ch' != ch*}\n(*lemma preserve_locals_comm_ch_spec_not_ch:\n  \"x\\<in> channel_spec B adds rems ch_id \\<Longrightarrow> \n   (x,x',i) \\<in> preserves_locals_constr \\<Longrightarrow> \n   (x,x',ch_id)\\<in> preserves_comm_constr \\<Longrightarrow>  \n   \\<forall>ch_id'. ch_id \\<noteq> ch_id' \\<longrightarrow> \n         (a_que_aux ((locals_' x)!i) ch_id' = a_que_aux ((locals_' x')!i) ch_id')  \\<and>\n         (r_que_aux ((locals_' x)!i) ch_id' = r_que_aux ((locals_' x')!i) ch_id') \\<Longrightarrow>           \n   \\<forall>ch_id' ch. ch_id'\\<noteq>ch_id \\<longrightarrow> \n      ((chans (communication_' x') ch_id') = Some ch \\<and> \n        ch_id_queuing conf ch_id' \\<and> channel_get_mutex ch = 0 \\<longrightarrow>\n         ch_spec B adds rems ch_id' x')\"\nproof-\n  assume\n  \n  a1: \"x\\<in> channel_spec B adds rems ch_id\" and \n  a2: \"(x,x',i) \\<in> preserves_locals_constr\" and        \n  a3: \"(x,x',ch_id)\\<in> preserves_comm_constr\" and \n  a4: \"\\<forall>ch_id'. ch_id \\<noteq> ch_id' \\<longrightarrow> \n         (a_que_aux ((locals_' x)!i) ch_id' = a_que_aux ((locals_' x')!i) ch_id')  \\<and>\n         (r_que_aux ((locals_' x)!i) ch_id' = r_que_aux ((locals_' x')!i) ch_id')\"   \n  {fix ch_id' ch'   \n   assume ass0:\"ch_id'\\<noteq>ch_id\" and\n          ass1:\"channel_get_mutex ch' = 0 \\<and> ch_id_queuing conf ch_id' \\<and>\n                (chans (communication_' x') ch_id') = Some ch'\"  \n   then have eq_chans:\n      \"(chans (communication_' x) ch_id') =\n       (chans (communication_' x') ch_id')\"  \n     using preserves_comm_D2[OF a3] by auto  \n   then have \"channel_get_mutex ch' = 0 \\<and> ch_id_queuing conf ch_id' \\<and>\n              (chans (communication_' x) ch_id') = Some ch'\"\n     using ass1 by auto   \n   then have ch:\"ch_spec B adds rems ch_id' x\"  \n     using a1 unfolding channel_spec_def ch_spec_def Let_def\n     by fastforce    \n   then have \"ch_spec B  adds rems ch_id' x'\" \n     using local_constr_eq_que_ch_spec[OF ch a2 ] eq_chans a4 ass0\n     by auto\n  } \n  thus ?thesis by auto\nqed\n  *)\n\ntext {*setting the mutex with a value different than zero \n       preserves channel\\_spec*}\n\n\n\ntext {* modifying the mutex to any value and preserving comm\\_constr for the enviroment\n        (channel different than ch is not modified) satisfies  channel\\_spec if ch\\_spec*}\nlemma local_constr_ch_spec_channel_spec:\n  \"\n   channel_spec B adds rems ch_id x \\<Longrightarrow>     \n   (x,x',i) \\<in> preserves_locals_constr \\<Longrightarrow>\n    channel_get_messages (the (chans (communication_' x) ch_id)) = \n    channel_get_messages (the (chans (communication_' x') ch_id)) \\<Longrightarrow>       \n   (a_que_aux ((locals_' x)!i) = a_que_aux ((locals_' x')!i)) \\<and>\n   (r_que_aux ((locals_' x)!i) = r_que_aux ((locals_' x')!i)) \\<Longrightarrow>\n  \\<exists>ch. chans (communication_' x) ch_id = Some ch \\<Longrightarrow>\n    channel_spec B adds rems ch_id x'\"\nproof -  \n  assume \n         a1: \"channel_spec B adds rems ch_id x\" and \n         a2: \"(x,x',i) \\<in> preserves_locals_constr\" and\n         a3: \"channel_get_messages (the (chans (communication_' x) ch_id)) = \n              channel_get_messages (the (chans (communication_' x') ch_id))\" and        \n         a5: \"\\<exists>ch. chans (communication_' x) ch_id = Some ch\" and\n         a6: \"(a_que_aux ((locals_' x)!i) = a_que_aux ((locals_' x')!i)) \\<and>\n              (r_que_aux ((locals_' x)!i) = r_que_aux ((locals_' x')!i))\" \n  {fix ch'\n   assume ass:\"ch_id_queuing conf ch_id \\<and> \n               (chans (communication_' x') ch_id) = Some ch'\"  \n   then have ch_x:\"ch_spec B adds rems ch_id x\" \n     using a5 a1 unfolding channel_spec_def by auto\n   have \"ch_spec B adds rems ch_id x'\"\n     using local_constr_eq_que_ch_spec[OF ch_x a2 a3] a6 a2 preserves_locals_D3 by force \n  } thus ?thesis  using a2 preserves_locals_D3 unfolding channel_spec_def ch_spec_def by fastforce\nqed\n  \n  lemma local_constr_subset_aux1:\n  \"\n   x\\<in>\\<lbrace>channel_messages ch_id rems [0..<length \\<acute>locals] \\<subseteq>#\n        channel_messages ch_id r_que_aux \\<acute>locals \\<and>\n        channel_messages ch_id adds [0..<length \\<acute>locals] \\<subseteq>#\n        channel_messages ch_id a_que_aux \\<acute>locals\\<rbrace> \\<Longrightarrow>     \n   (x,x',i) \\<in> preserves_locals_constr \\<Longrightarrow>\n   (a_que_aux ((locals_' x)!i) ch_id = a_que_aux ((locals_' x')!i) ch_id) \\<and>\n   (r_que_aux ((locals_' x)!i) ch_id = r_que_aux ((locals_' x')!i) ch_id) \\<Longrightarrow>  \n    channel_messages ch_id rems [0..<length (locals_' x)] \\<subseteq>#\n        channel_messages ch_id r_que_aux (locals_' x')\"\nproof -  \n  assume \n         a1: \"x\\<in>\\<lbrace>channel_messages ch_id rems [0..<length \\<acute>locals] \\<subseteq>#\n                  channel_messages ch_id r_que_aux \\<acute>locals \\<and>\n                  channel_messages ch_id adds [0..<length \\<acute>locals] \\<subseteq>#\n                  channel_messages ch_id a_que_aux \\<acute>locals\\<rbrace>\" and \n         a2: \"(x,x',i) \\<in> preserves_locals_constr\" and         \n         a6: \"(a_que_aux ((locals_' x)!i) ch_id = a_que_aux ((locals_' x')!i) ch_id) \\<and>\n              (r_que_aux ((locals_' x)!i) ch_id = r_que_aux ((locals_' x')!i) ch_id)\" \n  then show ?thesis\n    by (simp add: add_channel_message_not_evnt preserves_locals_D1 preserves_locals_D3)\nqed\n  \n  lemma local_constr_subset_aux2:\n  \"\n   x\\<in>\\<lbrace>channel_messages ch_id rems [0..<length \\<acute>locals] \\<subseteq>#\n        channel_messages ch_id r_que_aux \\<acute>locals \\<and>\n        channel_messages ch_id adds [0..<length \\<acute>locals] \\<subseteq>#\n        channel_messages ch_id a_que_aux \\<acute>locals\\<rbrace> \\<Longrightarrow>     \n   (x,x',i) \\<in> preserves_locals_constr \\<Longrightarrow>\n   (a_que_aux ((locals_' x)!i) ch_id = a_que_aux ((locals_' x')!i) ch_id) \\<and>\n   (r_que_aux ((locals_' x)!i) ch_id = r_que_aux ((locals_' x')!i) ch_id) \\<Longrightarrow>  \n    channel_messages ch_id adds [0..<length (locals_' x')] \\<subseteq>#\n        channel_messages ch_id a_que_aux (locals_' x')\"\nproof -  \n  assume \n         a1: \"x\\<in>\\<lbrace>channel_messages ch_id rems [0..<length \\<acute>locals] \\<subseteq>#\n                  channel_messages ch_id r_que_aux \\<acute>locals \\<and>\n                  channel_messages ch_id adds [0..<length \\<acute>locals] \\<subseteq>#\n                  channel_messages ch_id a_que_aux \\<acute>locals\\<rbrace>\" and \n         a2: \"(x,x',i) \\<in> preserves_locals_constr\" and         \n         a6: \"(a_que_aux ((locals_' x)!i) ch_id = a_que_aux ((locals_' x')!i) ch_id) \\<and>\n              (r_que_aux ((locals_' x)!i) ch_id = r_que_aux ((locals_' x')!i) ch_id)\" \n  then show ?thesis\n    by (simp add: add_channel_message_not_evnt preserves_locals_D1 preserves_locals_D3)\nqed\n  \nlemma local_constr_subset_aux:\n  \"\n   x\\<in>\\<lbrace>channel_messages ch_id rems [0..<length \\<acute>locals] \\<subseteq>#\n        channel_messages ch_id r_que_aux \\<acute>locals \\<and>\n        channel_messages ch_id adds [0..<length \\<acute>locals] \\<subseteq>#\n        channel_messages ch_id a_que_aux \\<acute>locals\\<rbrace> \\<Longrightarrow>     \n   (x,x',i) \\<in> preserves_locals_constr \\<Longrightarrow>\n   (a_que_aux ((locals_' x)!i) ch_id = a_que_aux ((locals_' x')!i) ch_id) \\<and>\n   (r_que_aux ((locals_' x)!i) ch_id = r_que_aux ((locals_' x')!i) ch_id) \\<Longrightarrow>  \n    x'\\<in> \\<lbrace>channel_messages ch_id rems [0..<length \\<acute>locals] \\<subseteq>#\n        channel_messages ch_id r_que_aux \\<acute>locals \\<and>\n        channel_messages ch_id adds [0..<length \\<acute>locals] \\<subseteq>#\n        channel_messages ch_id a_que_aux \\<acute>locals\\<rbrace>\"\nproof -  \n  assume \n         a1: \"x\\<in>\\<lbrace>channel_messages ch_id rems [0..<length \\<acute>locals] \\<subseteq>#\n                  channel_messages ch_id r_que_aux \\<acute>locals \\<and>\n                  channel_messages ch_id adds [0..<length \\<acute>locals] \\<subseteq>#\n                  channel_messages ch_id a_que_aux \\<acute>locals\\<rbrace>\" and \n         a2: \"(x,x',i) \\<in> preserves_locals_constr\" and         \n         a6: \"(a_que_aux ((locals_' x)!i) ch_id = a_que_aux ((locals_' x')!i) ch_id) \\<and>\n              (r_que_aux ((locals_' x)!i) ch_id = r_que_aux ((locals_' x')!i) ch_id)\" \n  then show ?thesis\n    by (simp add: add_channel_message_not_evnt preserves_locals_D1 preserves_locals_D3)\nqed\n\ntext {* modifying the queue when the mutex is not zero preserves channel\\_spec*}\nlemma \"c \\<subseteq># (a+(b-d)) \\<Longrightarrow> d\\<subseteq># b  \\<Longrightarrow> add_mset m (a + (b-d) - c) = a + ((add_mset m b)-d) -c \"  \n  by (metis add_mset_add_single mset_subset_eq_multiset_union_diff_commute union_mset_add_mset_right)\n\n  \nlemma atomic_tran_channel_ch_spec:\n  \"i< length (locals_' x) \\<Longrightarrow> \n   state_conf x \\<Longrightarrow>   \n   (x,x',i) \\<in> preserves_locals_constr \\<Longrightarrow>   \n   channel_get_messages (the (chans (communication_' x) ch_id)) + {# m #} = \n     channel_get_messages (the (chans (communication_' x') ch_id)) \\<Longrightarrow>   \n   a_que_aux ((locals_' x')!i) ch_id = a_que_aux ((locals_' x)!i) ch_id + {#m#} \\<Longrightarrow>   \n   r_que_aux ((locals_' x)!i) = r_que_aux ((locals_' x')!i) \\<Longrightarrow>   \n   (x,x',ch_id)\\<in> preserves_comm_constr \\<Longrightarrow>   \n    port_in_channel conf (communication_' x) (pt ((locals_' x)!i)) ch_id \\<Longrightarrow>  \n    port_open (communication_' x) (pt (locals_' x ! i)) \\<Longrightarrow>\n    p_queuing conf (communication_' x) (pt (locals_' x ! i)) \\<Longrightarrow>\n    ch_spec B adds rems ch_id x \\<Longrightarrow>\n   \\<not> port_full conf (communication_' x) (pt(locals_' x!i)) \\<Longrightarrow>\n    channel_messages ch_id adds [0..<length (locals_' x)] \\<subseteq># channel_messages  ch_id a_que_aux (locals_' x) \\<Longrightarrow>\n   (channel_messages ch_id r_que_aux (locals_' x) - channel_messages ch_id rems [0..<length (locals_' x)]) \\<subseteq>#\n    B ch_id + (channel_messages ch_id a_que_aux (locals_' x) - channel_messages ch_id adds [0..<length (locals_' x)])\n   \\<Longrightarrow>\n   ch_spec B adds rems ch_id x'\"\nproof-        \n assume\n   a0:\"i< length (locals_' x)\" and  \n   a0':\"state_conf x\" and\n   a2:\"(x,x',i) \\<in> preserves_locals_constr\" and  \n   a3:\"channel_get_messages (the (chans (communication_' x) ch_id)) + {# m #} = \n       channel_get_messages (the (chans (communication_' x') ch_id))\" and\n   a4:\"a_que_aux ((locals_' x')!i) ch_id = a_que_aux ((locals_' x)!i) ch_id + {#m#}\" and   \n   a6:\"r_que_aux ((locals_' x)!i) = r_que_aux ((locals_' x')!i)\" and   \n   a7:\"(x,x',ch_id)\\<in> preserves_comm_constr\" and\n   a8:\"port_in_channel conf (communication_' x) (pt ((locals_' x)!i)) ch_id \" and  \n   a8':\"port_open (communication_' x) (pt (locals_' x ! i))\" and\n   a9:\"p_queuing conf (communication_' x) (pt (locals_' x ! i))\" and\n   a10: \"ch_spec B adds rems ch_id x\" and\n   a11:\"\\<not> port_full conf (communication_' x) (pt(locals_' x!i))\" and\n   a12:\" channel_messages ch_id adds [0..<length (locals_' x)] \\<subseteq># channel_messages  ch_id a_que_aux (locals_' x)\" and \n   a13:\"(channel_messages ch_id r_que_aux (locals_' x) - channel_messages ch_id rems [0..<length (locals_' x)]) \\<subseteq>#\n    B ch_id + (channel_messages ch_id a_que_aux (locals_' x) - channel_messages ch_id adds [0..<length (locals_' x)])\"\n  have send_aux:\"channel_messages  ch_id a_que_aux (locals_' x)  + {#m#}  = \n                 channel_messages ch_id a_que_aux (locals_' x')\"  \n    using add_channel_message_evnt[OF a0 a2] a4 by metis\n  moreover have rec_aux:\"channel_messages  ch_id r_que_aux (locals_' x) = \n                          channel_messages ch_id r_que_aux (locals_' x')\"\n    using add_channel_message_not_evnt[OF a2 _] a6  by fastforce\n  moreover have x:\"channel_messages ch_id rems [0..<length (locals_' x)] = channel_messages ch_id rems [0..<length (locals_' x')] \\<and> \n                channel_messages ch_id adds [0..<length (locals_' x)] = channel_messages ch_id adds [0..<length (locals_' x')]\"\n    using a2 preserves_locals_D1 by fastforce   \n  ultimately have \"channel_get_messages (the (chans (communication_' x') ch_id)) = \n            (B ch_id + channel_sent_messages  ch_id adds (locals_' x')) -\n                (channel_received_messages  ch_id rems (locals_' x'))\"\n    using a10 a3 a4 a3 a12  a13 unfolding channel_received_messages_def ch_spec_def\n                channel_sent_messages_def multi_self_add_other_not_self  Let_def\n    by (metis (no_types, lifting) add.assoc subset_mset.add_diff_assoc2)                                               \n     \n  moreover have \n    \"channel_messages ch_id r_que_aux (locals_' x') - channel_messages ch_id rems [0..<length (locals_' x')]  \n      \\<subseteq># B ch_id + (channel_messages ch_id a_que_aux (locals_' x') - channel_messages ch_id adds [0..<length (locals_' x')])\"\n   using a10 a3 send_aux rec_aux a12 a13\n    unfolding ch_spec_def channel_received_messages_def \n              channel_sent_messages_def  Let_def\n    by (metis (no_types) a12 a13 ab_semigroup_add_class.add_ac(1) empty_le mset_subset_eq_multiset_union_diff_commute \n                         rec_aux send_aux subset_mset.add_increasing2 x)  \n  moreover have \n   \"size (channel_get_messages (the (chans (communication_' x') ch_id))) \\<le> \n    channel_size (get_channel conf ch_id)\"\n   using a10 a3 a11 \n    unfolding ch_spec_def\n    by (metis a0' a10 a8 a8' a9 channel_not_queport_full_size option.sel \n            p_queuing_chan_queuing queuing_insert_message)              \n    \n  ultimately show ?thesis \n    unfolding ch_spec_def Let_def channel_received_messages_def channel_sent_messages_def\n    by (metis a10 ch_spec_def local.x rec_aux send_aux subset_mset.add_increasing2 subset_mset.zero_le)     \nqed  \n  \nlemma \"r - ri \\<subseteq># B + (s - si) \\<Longrightarrow>\n       s = s' \\<Longrightarrow> r' = r - m \\<Longrightarrow> m \\<subseteq># B + (s - si) - (r - ri) \\<Longrightarrow>\n       r' - ri \\<subseteq># B + (s' - si)\n    \"\n  by (meson diff_subset_eq_self subset_eq_diff_conv subset_mset.order.trans)  \n  \nlemma atomic_tran_rem_channel_ch_spec:\n  \"i< length (locals_' x) \\<Longrightarrow> \n   state_conf x \\<Longrightarrow>   \n   (x,x',i) \\<in> preserves_locals_constr \\<Longrightarrow>      \n   m \\<subseteq># channel_get_messages (the (chans (communication_' x) ch_id)) \\<Longrightarrow>\n   channel_get_messages (the (chans (communication_' x) ch_id)) - m = \n     channel_get_messages (the (chans (communication_' x') ch_id)) \\<Longrightarrow>   \n   r_que_aux ((locals_' x')!i) ch_id = r_que_aux ((locals_' x)!i) ch_id + m \\<Longrightarrow>   \n   a_que_aux ((locals_' x)!i) = a_que_aux ((locals_' x')!i) \\<Longrightarrow>   \n   (x,x',ch_id)\\<in> preserves_comm_constr \\<Longrightarrow>   \n    port_in_channel conf (communication_' x) (pt ((locals_' x)!i)) ch_id \\<Longrightarrow>    \n    p_queuing conf (communication_' x) (pt (locals_' x ! i)) \\<Longrightarrow>\n    port_open (communication_' x) (pt (locals_' x ! i)) \\<Longrightarrow>\n    ch_spec B adds rems ch_id x \\<Longrightarrow>\n   channel_messages ch_id rems [0..<length (locals_' x)] \\<subseteq># channel_messages  ch_id r_que_aux (locals_' x) \\<Longrightarrow>\n   (channel_messages ch_id r_que_aux (locals_' x) - channel_messages ch_id rems [0..<length (locals_' x)]) \\<subseteq>#\n    B ch_id + (channel_messages ch_id a_que_aux (locals_' x) - channel_messages ch_id adds [0..<length (locals_' x)])\n   \\<Longrightarrow>\n   ch_spec B adds rems ch_id x'\"\nproof-        \n assume\n   a0:\"i< length (locals_' x)\" and  \n   a0':\"state_conf x\" and\n   a2:\"(x,x',i) \\<in> preserves_locals_constr\" and \n   a3':\"m \\<subseteq># channel_get_messages (the (chans (communication_' x) ch_id))\" and\n   a3:\"channel_get_messages (the (chans (communication_' x) ch_id)) - m = \n       channel_get_messages (the (chans (communication_' x') ch_id))\" and\n   a4:\"r_que_aux ((locals_' x')!i) ch_id = r_que_aux ((locals_' x)!i) ch_id + m\" and   \n   a6:\"a_que_aux ((locals_' x)!i) = a_que_aux ((locals_' x')!i)\" and   \n   a7:\"(x,x',ch_id)\\<in> preserves_comm_constr\" and\n   a8:\"port_in_channel conf (communication_' x) (pt ((locals_' x)!i)) ch_id \" and  \n   a8':\"port_open (communication_' x) (pt (locals_' x ! i))\" and\n   a9:\"p_queuing conf (communication_' x) (pt (locals_' x ! i))\" and\n   a10: \"ch_spec B adds rems ch_id x\" and \n   a12':\" channel_messages ch_id rems [0..<length (locals_' x)] \\<subseteq># channel_messages  ch_id r_que_aux (locals_' x)\" and\n   a13:\"(channel_messages ch_id r_que_aux (locals_' x) - channel_messages ch_id rems [0..<length (locals_' x)]) \\<subseteq>#\n    B ch_id + (channel_messages ch_id a_que_aux (locals_' x) - channel_messages ch_id adds [0..<length (locals_' x)])\"\n  have send_aux:\"channel_messages  ch_id r_que_aux (locals_' x)  + m  = \n                 channel_messages ch_id r_que_aux (locals_' x')\"  \n    using add_channel_message_evnt[OF a0 a2] a4 by metis\n  moreover have rec_aux:\"channel_messages  ch_id a_que_aux (locals_' x) = \n                          channel_messages ch_id a_que_aux (locals_' x')\"\n    using add_channel_message_not_evnt[OF a2 _] a6  by fastforce\n  moreover have x:\"channel_messages ch_id rems [0..<length (locals_' x)] = channel_messages ch_id rems [0..<length (locals_' x')] \\<and> \n                channel_messages ch_id adds [0..<length (locals_' x)] = channel_messages ch_id adds [0..<length (locals_' x')]\"\n    using a2 preserves_locals_D1 by fastforce   \n  ultimately have \"channel_get_messages (the (chans (communication_' x') ch_id)) = \n            (B ch_id + channel_sent_messages  ch_id adds (locals_' x')) -\n                (channel_received_messages  ch_id rems (locals_' x'))\"\n    using a10 a3 a4 a3  a12' a13 unfolding channel_received_messages_def ch_spec_def\n                channel_sent_messages_def multi_self_add_other_not_self  Let_def\n    by (metis (no_types, hide_lams) diff_diff_add_mset subset_mset.add_diff_assoc2)    \n  moreover have \n    \"channel_messages ch_id r_que_aux (locals_' x') - channel_messages ch_id rems [0..<length (locals_' x')]  \n      \\<subseteq># B ch_id + (channel_messages ch_id a_que_aux (locals_' x') - channel_messages ch_id adds [0..<length (locals_' x')])\"\n   using a10 a3 send_aux rec_aux  a12' a13 a3'\n    unfolding ch_spec_def channel_received_messages_def \n              channel_sent_messages_def  Let_def x\n    by (metis add_msg_rec x)     \n  moreover have \n   \"size (channel_get_messages (the (chans (communication_' x') ch_id))) \\<le> \n    channel_size (get_channel conf ch_id)\"\n   using a10 a3  a0' a10 a8 a9 a3'\n   unfolding ch_spec_def Let_def\n   using size_Diff_submset by fastforce       \n  ultimately show ?thesis \n    unfolding ch_spec_def Let_def channel_received_messages_def channel_sent_messages_def\n    by (metis a10 ch_spec_def local.x rec_aux send_aux subset_mset.add_increasing2 subset_mset.zero_le)     \nqed  \n\n\n\ntext {* modifying the queue when the mutex is not zero preserves channel\\_spec*}\n\n\nlemma modify_que_channel_ch_spec1:\n  \" state_conf x \\<Longrightarrow>\n   ch_spec B adds rems ch_id x \\<Longrightarrow> \n   (x,x',i) \\<in> preserves_locals_constr \\<Longrightarrow> \n    chans (communication_' x) ch_id = Some ch \\<Longrightarrow>    \n    chans (communication_' x') ch_id = Some ch' \\<Longrightarrow>\n   channel_get_messages ch + {# msg ((locals_' x')!i) #} =  \n   channel_get_messages ch' \\<Longrightarrow>\n   (a_que_aux ((locals_' x)!i) = a_que_aux ((locals_' x')!i)) \\<and>\n   (r_que_aux ((locals_' x)!i) = r_que_aux ((locals_' x')!i)) \\<Longrightarrow>   \n    port_in_channel conf (communication_' x) (pt ((locals_' x)!i)) ch_id \\<Longrightarrow>\n   port_open (communication_' x) (pt (locals_' x ! i)) \\<Longrightarrow>\n    \\<not> port_full conf  (communication_' x) (pt (locals_' x ! i)) \\<Longrightarrow>\n    p_queuing conf  (communication_' x) (pt (locals_' x ! i)) \\<Longrightarrow>   \n   (channel_messages ch_id r_que_aux (locals_' x) - channel_messages ch_id rems [0..<length (locals_' x)]) \\<subseteq>#\n    B ch_id + (channel_messages ch_id a_que_aux (locals_' x) - channel_messages ch_id adds [0..<length (locals_' x)]) \\<Longrightarrow>\n    channel_get_messages  ch' = \n      (B ch_id + channel_sent_messages  ch_id  adds (locals_' x')) - \n                channel_received_messages  ch_id rems (locals_' x')\n                + {# msg ((locals_' x')!i) #} \\<and>\n      channel_received_messages  ch_id rems (locals_' x')  \\<subseteq>#\n        B ch_id + channel_sent_messages  ch_id adds (locals_' x') \\<and>\n      size (channel_get_messages ch') \\<le> \n         channel_size (get_channel conf ch_id)\"\nproof-        \n assume \n  \n   a0':\"state_conf x\" and\n   a1:\"ch_spec B adds rems ch_id x\" and\n   a2:\"(x,x',i) \\<in> preserves_locals_constr\" and \n   a3:\" chans (communication_' x) ch_id = Some ch\" and\n   a4:\" chans (communication_' x') ch_id = Some ch'\" and\n   a5:\"channel_get_messages ch + {# msg ((locals_' x')!i) #} =  \n       channel_get_messages ch'\" and\n   a6: \"(a_que_aux ((locals_' x)!i) = a_que_aux ((locals_' x')!i)) \\<and>\n        (r_que_aux ((locals_' x)!i) = r_que_aux ((locals_' x')!i))\" and  \n   a7:\" port_in_channel conf (communication_' x) (pt ((locals_' x)!i)) ch_id \" and\n   a8:\"\\<not> port_full conf (communication_' x) (pt (locals_' x ! i))\" and\n   a8':\"port_open (communication_' x) (pt (locals_' x !i))\" and\n   a9:\"p_queuing conf (communication_' x) (pt (locals_' x ! i))\" and   \n   a10:\"(channel_messages ch_id r_que_aux (locals_' x) - channel_messages ch_id rems [0..<length (locals_' x)]) \\<subseteq>#\n    B ch_id + (channel_messages ch_id a_que_aux (locals_' x) - channel_messages ch_id adds [0..<length (locals_' x)])\" \n   \n  also have len_locals:\"length (locals_' x) = length (locals_' x')\" \n    using a2 preserves_locals_D1 by fastforce\n  ultimately have ev:\"(channel_messages  ch_id a_que_aux (locals_' x)) = \n              (channel_messages  ch_id a_que_aux (locals_' x')) \\<and>\n              (channel_messages  ch_id r_que_aux (locals_' x)) = \n              (channel_messages  ch_id r_que_aux (locals_' x'))\"\n   using channel_messages_eq by fastforce\n then have \"channel_get_messages ch' = \n      (B ch_id + channel_sent_messages ch_id adds  (locals_' x')) -\n       channel_received_messages  ch_id  rems(locals_' x') + {# msg ((locals_' x')!i) #}\"\n   using   a1 a3  a5 len_locals\n   unfolding ch_spec_def  \n             channel_received_messages_def channel_sent_messages_def\n   by simp             \n moreover have \"channel_received_messages  ch_id rems (locals_' x') \\<subseteq>#\n                 B ch_id + channel_sent_messages ch_id adds (locals_' x')\"\n   using ev a1 a3 a10 len_locals\n   unfolding channel_received_messages_def  \n              channel_sent_messages_def ch_spec_def \n   by auto\n moreover have \"(size (channel_get_messages ch') \\<le> \n                  channel_size (get_channel conf ch_id))\"\n  proof -\n    have ch_q:\"chan_queuing ch\" \n      using p_queuing_chan_queuing[OF a0' a8' a9 a7] a3 by auto\n    show ?thesis using queuing_insert_message[OF ch_q]\n      using channel_not_queport_full_size[OF a0' a8' a1 a8 a9 a7 a3] a5\n      by metis\n  qed\n ultimately show ?thesis by auto\nqed\n\nlemma modify_que_channel_ch_spec:\n  \"i< length (locals_' x) \\<Longrightarrow> \n   state_conf x \\<Longrightarrow>   \n   (x,x',i) \\<in> preserves_locals_constr \\<Longrightarrow>   \n   channel_get_messages (the (chans (communication_' x) ch_id)) = \n     channel_get_messages (the (chans (communication_' x') ch_id)) \\<Longrightarrow>   \n   a_que_aux ((locals_' x')!i) ch_id = a_que_aux ((locals_' x)!i) ch_id + {#m#} \\<Longrightarrow>   \n   r_que_aux ((locals_' x)!i) = r_que_aux ((locals_' x')!i) \\<Longrightarrow>   \n   (x,x',ch_id)\\<in> preserves_comm_constr \\<Longrightarrow>   \n    port_in_channel conf (communication_' x) (pt ((locals_' x)!i)) ch_id \\<Longrightarrow>   \n    port_open (communication_' x) (pt ((locals_' x)!i)) \\<Longrightarrow>\n    p_queuing conf (communication_' x) (pt (locals_' x ! i)) \\<Longrightarrow>    \n     channel_get_messages (the (chans (communication_' x) ch_id)) = \n            (B ch_id + channel_sent_messages ch_id adds (locals_' x)) -\n                 channel_received_messages ch_id rems (locals_' x) +  {#m#} \\<and>\n             channel_received_messages ch_id  rems (locals_' x)  \\<subseteq>#\n             (B ch_id + channel_sent_messages  ch_id  adds (locals_' x)) \\<and>\n          (size (channel_get_messages (the (chans (communication_' x) ch_id))) \\<le> \n             channel_size (get_channel conf ch_id)) \\<and>\n     channel_messages ch_id rems [0..<length (locals_' x)] \\<subseteq># channel_messages  ch_id r_que_aux (locals_' x) \\<and>\n    channel_messages ch_id adds [0..<length (locals_' x)] \\<subseteq># channel_messages  ch_id a_que_aux (locals_' x) \\<Longrightarrow>\n   ch_spec B adds rems ch_id x'\"\nproof-        \n assume \n   a0:\"i< length (locals_' x)\" and  \n   a0':\"state_conf x\" and\n   a2:\"(x,x',i) \\<in> preserves_locals_constr\" and  \n   a3:\"channel_get_messages (the (chans (communication_' x) ch_id)) = \n         channel_get_messages (the (chans (communication_' x') ch_id))\" and\n   a4:\"a_que_aux ((locals_' x')!i) ch_id = a_que_aux ((locals_' x)!i) ch_id + {#m#}\" and   \n   a6:\"r_que_aux ((locals_' x)!i) = r_que_aux ((locals_' x')!i)\" and   \n   a7:\"(x,x',ch_id)\\<in> preserves_comm_constr\" and\n   a8:\"port_in_channel conf (communication_' x) (pt ((locals_' x)!i)) ch_id \" and   \n   a8':\"port_open (communication_' x) (pt ((locals_' x)!i))\" and\n   a9:\"p_queuing conf (communication_' x) (pt (locals_' x ! i))\" and\n   a10: \"channel_get_messages (the (chans (communication_' x) ch_id)) = \n            (B ch_id + channel_sent_messages ch_id adds  (locals_' x)) -\n                channel_received_messages ch_id  rems (locals_' x) + {#m#} \\<and>\n          channel_received_messages  ch_id  rems (locals_' x) \\<subseteq>#\n             (B ch_id + channel_sent_messages ch_id adds (locals_' x)) \\<and>\n          (size (channel_get_messages (the (chans (communication_' x) ch_id))) \\<le> \n             channel_size (get_channel conf ch_id)) \\<and>\n        channel_messages ch_id rems [0..<length (locals_' x)] \\<subseteq># channel_messages  ch_id r_que_aux (locals_' x) \\<and>\n        channel_messages ch_id adds [0..<length (locals_' x)] \\<subseteq># channel_messages  ch_id a_que_aux (locals_' x)\"\n  then have len_loc:\"length (locals_' x) = length (locals_' x')\"\n    using preserves_locals_D1 by blast\n  have send_aux:\"channel_messages  ch_id a_que_aux (locals_' x)  + {#m#}  = \n                       channel_messages ch_id a_que_aux (locals_' x')\"  \n    using add_channel_message_evnt[OF a0 a2] a4 by metis\n  moreover have rec_aux:\"channel_messages  ch_id r_que_aux (locals_' x) = \n                          channel_messages ch_id r_que_aux (locals_' x')\"\n    using add_channel_message_not_evnt[OF a2 _] a6  by fastforce\n  ultimately have \"channel_get_messages (the (chans (communication_' x') ch_id)) = \n            (B ch_id + channel_sent_messages  ch_id adds (locals_' x')) -\n                (channel_received_messages  ch_id rems (locals_' x')) \\<and>\n             channel_received_messages  ch_id rems (locals_' x') \\<subseteq># \n                   (B ch_id + channel_sent_messages ch_id adds  (locals_' x'))\"\n    using len_loc a10 a3\n  proof -\n    have f1: \"\\<forall>m ma mb. \\<not> (m::Message multiset) \\<subseteq># ma \\<or> ma - m + mb = ma + mb - m\"\n      by (metis subset_mset.add_diff_assoc2)\n    have \"channel_sent_messages ch_id adds (locals_' x') =\n           channel_messages ch_id a_que_aux (locals_' x) + {#m#} - \n           channel_messages ch_id adds [0..<length (locals_' x)]\"\n      using channel_sent_messages_def len_loc send_aux by fastforce\n    then have \"channel_sent_messages ch_id adds (locals_' x') = \n                channel_messages ch_id a_que_aux (locals_' x) - \n                channel_messages ch_id adds [0..<length (locals_' x)] + {#m#}\"\n      using f1 a10 by presburger\n    then have f2: \"B ch_id + channel_sent_messages ch_id adds (locals_' x') = \n                   B ch_id + channel_sent_messages ch_id adds (locals_' x) + {#m#}\"\n      by (simp add: channel_sent_messages_def)\n    have \"channel_received_messages ch_id rems (locals_' x') = \n          channel_received_messages ch_id rems (locals_' x)\"\n      using channel_received_messages_def len_loc rec_aux by presburger\n    then show ?thesis\n      using f2 f1 a10 a3\n      by (metis mset_subset_eq_add_left subset_mset.add_increasing2 \n                subset_mset.le_add_same_cancel1) \n  qed                                                     \n  then show ?thesis \n    using a10 a3 send_aux rec_aux \n    unfolding ch_spec_def channel_received_messages_def \n              channel_sent_messages_def  Let_def\n    by (metis len_loc mset_subset_eq_add_left subset_mset.order_trans)    \nqed\n  \n   \nsection {* Rely Guarantee Specification*}   \n\n(*definition \"Guarantee_aux\"\n  where\n    \"Guarantee_aux adds B rems x y \\<equiv>\n  \\<forall>ch_id j.\n       (mut (the (chans (communication_' x) ch_id)) = j+1 \\<and> \n       mut (the (chans (communication_' y) ch_id)) = 0 )  \\<longrightarrow>\n      (port_channel conf (pt (locals_' x !j))) = ch_id \\<and> j<length (locals_' x) \\<and> \n      ((r_que_aux (locals_' y !j) (port_channel conf (pt (locals_' x !j)))\\<noteq>rems j (port_channel conf (pt (locals_' x !j))) \\<longrightarrow>\n       (\\<exists>m. r_que_aux (locals_' y !j) (port_channel conf (pt (locals_' x !j))) = \n          rems j (port_channel conf (pt (locals_' x !j))) + m \\<and>\n        m\\<subseteq># B (port_channel conf (pt (locals_' x !j))) + channel_sent_messages  (port_channel conf (pt (locals_' y !j))) adds  (locals_' x)) \\<and>\n     a_que_aux (locals_' y !j) (port_channel conf (pt (locals_' x !j))) = adds j (port_channel conf (pt (locals_' x !j)))\n     ) \\<and>\n     (a_que_aux (locals_' y !j) (port_channel conf (pt (locals_' x !j)))\\<noteq>adds j (port_channel conf (pt (locals_' x !j))) \\<longrightarrow>\n       a_que_aux (locals_' y !j) (port_channel conf (pt (locals_' x !j))) = {#msg (locals_' x !j)#} + adds j  (port_channel conf (pt (locals_' x !j))) \\<and>\n       r_que_aux (locals_' y !j) (port_channel conf (pt (locals_' x !j))) = rems j (port_channel conf (pt (locals_' x !j))) \\<and>\n       size (channel_get_messages (the (chans (communication_' y) (port_channel conf (pt (locals_' x !j)))))) \\<le> \n       channel_size (get_channel conf (port_channel conf (pt (locals_' x !j))))\n     ) \\<and>\n     channel_get_messages (the (chans (communication_' y) (port_channel conf (pt (locals_' x !j))))) = \n       B (port_channel conf (pt (locals_' x !j))) + channel_sent_messages  (port_channel conf (pt (locals_' x !j))) adds  (locals_' y) -\n         channel_received_messages  (port_channel conf (pt (locals_' x !j))) rems  (locals_' y)  \\<and>\n   (\\<forall>i. i\\<noteq>j \\<longrightarrow>  \n        a_que_aux (locals_' x !i) ch_id = a_que_aux (locals_' y !i) ch_id \\<and> \n        r_que_aux (locals_' x !i) ch_id = r_que_aux (locals_' y !i) ch_id)  \n   )\\<and>\n   (\\<forall>ch_id'. ch_id'\\<noteq>ch_id \\<longrightarrow>\n      chans (communication_' x) ch_id' = chans (communication_' y) ch_id'\\<and>\n      (\\<forall>i. a_que_aux (locals_' x !i) ch_id' = a_que_aux (locals_' y !i) ch_id' \\<and>\n           r_que_aux (locals_' x !i) ch_id' = r_que_aux (locals_' y !i) ch_id'))\" *)\n    \ndefinition \"Guarantee_mod_chan\"\nwhere\n\"Guarantee_mod_chan x y j \\<equiv>    \n  let ch = (port_channel conf  (communication_' x) (pt (locals_' x !j))) in\n  (channel_get_messages (the (chans (communication_' x) ch)) \\<noteq>\n    channel_get_messages (the (chans (communication_' y) ch)) \\<and>\n   p_queuing conf (communication_' x) (pt (locals_' x !j))  \\<longrightarrow>\n     port_open (communication_' x) (pt (locals_' x !j)) \\<and>\n    ((r_que_aux (locals_' y !j) ch\\<noteq> r_que_aux (locals_' x !j) ch) \\<or> \n     (a_que_aux (locals_' y !j) ch\\<noteq> a_que_aux (locals_' x !j) ch)) \\<and>\n     ((r_que_aux (locals_' y !j) ch\\<noteq> r_que_aux (locals_' x !j) ch \\<longrightarrow>\n        (\\<exists>m. r_que_aux (locals_' y !j) ch = r_que_aux (locals_' x !j) ch + m \\<and>\n           m\\<subseteq># channel_get_messages (the (chans (communication_' x) ch)) \\<and>\n          channel_get_messages (the (chans (communication_' y) ch)) = \n            channel_get_messages (the (chans (communication_' x) ch)) - m) \\<and>\n          a_que_aux (locals_' x !j) ch = a_que_aux (locals_' y !j) ch) \\<and>\n      (a_que_aux (locals_' y !j) ch\\<noteq> a_que_aux (locals_' x !j) ch \\<longrightarrow>\n       a_que_aux (locals_' y !j) ch = \n         {#msg (locals_' x !j)#} + a_que_aux (locals_' x !j) ch \\<and>         \n       r_que_aux (locals_' x !j) ch = r_que_aux (locals_' y !j) ch  \\<and>\n        size (channel_get_messages (the (chans (communication_' y) ch))) \\<le> \n         channel_size (get_channel conf ch) \\<and>\n       channel_get_messages (the (chans (communication_' y) ch)) = \n         channel_get_messages (the (chans (communication_' x) ch)) +   \n         {#msg (locals_' x !j)#} ) \n     )) \\<and>\n   ((channel_get_messages (the (chans (communication_' x) ch)) =\n    channel_get_messages (the (chans (communication_' y) ch)) \\<or> \n    \\<not> (p_queuing conf (communication_' x) (pt (locals_' x !j)))) \\<longrightarrow>\n          r_que_aux (locals_' y !j) ch = r_que_aux (locals_' x !j) ch \\<and>\n          a_que_aux (locals_' y !j) ch = a_que_aux (locals_' x !j) ch)           \n\"   \nlemma \"(\\<forall>ch_id. ch_id\\<noteq>(port_channel conf (communication_' x) (pt (locals_' x !i))) \\<longrightarrow>\n            chans (communication_' x) ch_id = chans (communication_' y) ch_id) \\<Longrightarrow>\n       (\\<forall>ch_id. chans (communication_' x) ch_id \\<noteq> chans (communication_' y) ch_id) \\<longrightarrow>\n                   ch_id=(port_channel conf (communication_' x) (pt (locals_' x !i)))\"  \n  by auto\n    \nlemma \"(\\<forall>ch_id. \n      (\\<nexists>j. j<length (locals_' x1) \\<and> ch_id = port_channel conf (communication_' x1) (pt (locals_' x1 !j))) \\<longrightarrow> \n      chans (communication_' x1) ch_id = chans (communication_' y1) ch_id)  \\<Longrightarrow> \n     (\\<forall>ch_id. \n      chans (communication_' x1) ch_id \\<noteq> chans (communication_' y1) ch_id \\<longrightarrow>\n      (\\<exists>j. j<length (locals_' x1) \\<and> ch_id = port_channel conf (communication_' x1) (pt (locals_' x1 !j))) \n      )\" by auto\n\ndefinition Guarantee_Send_Receive'\nwhere\n\"Guarantee_Send_Receive' i   \\<equiv> \n{(x,y). \n    let pch_id = port_channel conf (communication_' x) (pt (locals_' x !i)) in\n    ports (communication_' x) = ports (communication_' y)  \\<and>\n   ({ch. chans (communication_' x) ch = None} = {ch. chans (communication_' y) ch = None}) \\<and>\n    ({ch. \\<exists>ch1. chans (communication_' x) ch = Some ch1} = \n      {ch. \\<exists>ch1. chans (communication_' y) ch = Some ch1}) \\<and>\n   ((\\<exists>ch. chans (communication_' x) pch_id =  Some ch \\<and> chan_queuing ch) \\<longrightarrow>\n     (\\<exists>ch. chans (communication_' y) pch_id =  Some ch \\<and> chan_queuing ch)) \\<and>  \n    schedule (locals_' x !i) =  schedule (locals_' y !i) \\<and>\n   (\\<forall>ch_id. ch_id\\<noteq>pch_id \\<longrightarrow>\n            chans (communication_' x) ch_id = chans (communication_' y) ch_id) \\<and>       \n   (\\<forall>ch_id. (ch_id \\<noteq> pch_id \\<longrightarrow>\n               (a_que_aux (locals_' x !i) ch_id = a_que_aux (locals_' y !i) ch_id) \\<and> \n               (r_que_aux (locals_' x !i) ch_id = r_que_aux (locals_' y !i) ch_id))) \\<and>     \n    ((a_que_aux (locals_' x !i) \\<noteq> a_que_aux (locals_' y !i) \\<or> \n     (r_que_aux (locals_' x !i) \\<noteq> r_que_aux (locals_' y !i))) \\<longrightarrow>\n       (mut (the (chans (communication_' x) pch_id)) = i + 1)\n    ) \\<and>\n    (chans (communication_' x) pch_id\\<noteq> chans (communication_' y) pch_id \\<longrightarrow>\n      (mut (the (chans (communication_' x) pch_id)) = i + 1 \\<or> \n       mut (the (chans (communication_' y) pch_id)) = i + 1)) \\<and> \n   (mut (the (chans (communication_' x) pch_id)) \\<noteq> mut (the (chans (communication_' y) pch_id)) \\<longrightarrow>\n      (mut (the (chans (communication_' x) pch_id)) = 0 \\<or> \n      mut (the (chans (communication_' y) pch_id)) = 0)) \\<and>      \n   Guarantee_mod_chan  x y i   \n   }         \n\"\n\ndefinition Guarantee_Send_Receive\nwhere\n\"Guarantee_Send_Receive i   \\<equiv> \n {(x,y). (\\<exists>x1 y1.      \n    x=Normal x1 \\<and> y=Normal y1 \\<and> \n    length (locals_' x1) = length (locals_' y1) \\<and>   \n    evnt (locals_' x1 !i) = evnt (locals_' y1 !i) \\<and> \n    pt (locals_' x1 !i) =  pt (locals_' y1 !i) \\<and>\n    (\\<forall>j. (j\\<noteq>i) \\<longrightarrow> (locals_' x1)!j = (locals_' y1)!j) \\<and>      \n    state_conf x1 = state_conf y1 \\<and>                                 \n    (x1,y1)\\<in> Guarantee_Send_Receive' i    \n  ) \\<or> (x=y)             \n }  \n\"\n\ndefinition Rely_mod_chan\n  where\n\"Rely_mod_chan x y i \\<equiv>\nlet ch = (port_channel conf  (communication_' x) (pt (locals_' x !i))) in\n   ((channel_get_messages (the (chans (communication_' x) ch)) \\<noteq>\n      channel_get_messages (the (chans (communication_' y) ch))) \\<and>\n     p_queuing conf  (communication_' x) (pt (locals_' x !i)) \\<longrightarrow>      \n     (\\<exists>j<procs conf. \n        port_open (communication_' x) (pt (locals_' x !j)) \\<and>\n       ch =  (port_channel conf (communication_' x) (pt (locals_' x !j))) \\<and>\n        ((r_que_aux (locals_' y !j) ch\\<noteq> r_que_aux (locals_' x !j) ch) \\<or> \n         (a_que_aux (locals_' y !j) ch\\<noteq> a_que_aux (locals_' x !j) ch)) \\<and>\n       ((r_que_aux (locals_' y !j) ch\\<noteq> r_que_aux (locals_' x !j) ch \\<longrightarrow>\n          (\\<exists>m. r_que_aux (locals_' y !j) ch = r_que_aux (locals_' x !j) ch + m \\<and>\n             m\\<subseteq># channel_get_messages (the (chans (communication_' x) ch)) \\<and>\n            channel_get_messages (the (chans (communication_' y) ch)) = \n              channel_get_messages (the (chans (communication_' x) ch)) - m) \\<and>\n            a_que_aux (locals_' x !j) ch = a_que_aux (locals_' y !j) ch) \\<and>\n        (a_que_aux (locals_' y !j) ch\\<noteq> a_que_aux (locals_' x !j) ch \\<longrightarrow>\n         a_que_aux (locals_' y !j) ch = {#msg (locals_' x !j)#} + a_que_aux (locals_' x !j) ch \\<and>         \n         r_que_aux (locals_' x !j) ch = r_que_aux (locals_' y !j) ch  \\<and>\n          size (channel_get_messages (the (chans (communication_' y) ch))) \\<le> \n           channel_size (get_channel conf ch) \\<and>\n         channel_get_messages (the (chans (communication_' y) ch)) = \n           channel_get_messages (the (chans (communication_' x) ch)) + {#msg (locals_' x !j)#} ) \n       ) \\<and> (\\<forall>k. k\\<noteq>j \\<longrightarrow> locals_' x !k = locals_' y !k) \\<and> \n       (\\<forall>ch_id. ch_id\\<noteq>ch \\<longrightarrow> \n          a_que_aux (locals_' x !j) ch_id = a_que_aux (locals_' y !j) ch_id \\<and>\n          r_que_aux (locals_' x !j) ch_id = r_que_aux (locals_' y !j) ch_id)\n       )) \\<and>      \n    (((channel_get_messages (the (chans (communication_' x) ch)) =\n      channel_get_messages (the (chans (communication_' y) ch))) \\<or>\n     \\<not> p_queuing conf  (communication_' x) (pt (locals_' x !i)) \\<longrightarrow>        \n            (\\<forall>j. r_que_aux (locals_' y !j) ch = r_que_aux (locals_' x !j) ch \\<and>\n                 a_que_aux (locals_' y !j) ch = a_que_aux (locals_' x !j) ch)))    \n \"  \n                 \ndefinition Rely_Send_Receive:: \"nat \\<Rightarrow> ('b vars_scheme \\<times> 'b vars_scheme) set\"\nwhere\n\"Rely_Send_Receive i   \\<equiv>\n {(x,y).  \n   let pch_id = port_channel conf (communication_' x) (pt (locals_' x !i)) in\n   Rely_mod_chan x y i  \\<and>\n   ports (communication_' x) = ports (communication_' y) \\<and>\n   {ch. chans (communication_' x) ch = None} = \n     {ch. chans (communication_' y) ch = None} \\<and>\n   {ch. \\<exists>ch1. chans (communication_' x) ch = Some ch1} = \n     {ch. \\<exists>ch1. chans (communication_' y) ch = Some ch1} \\<and>  \n  (\\<forall>ch_id.\n    ((\\<exists>ch. chans (communication_' x) ch_id =  Some ch \\<and> chan_queuing ch) \\<longrightarrow>\n     (\\<exists>ch. chans (communication_' y) ch_id =  Some ch \\<and> chan_queuing ch))) \\<and>            \n  ((mut (the (chans (communication_' x) pch_id)) = i + 1 \\<or> \n   mut (the (chans (communication_' y) pch_id)) = i + 1)  \\<longrightarrow>\n      chans (communication_' x) pch_id = chans (communication_' y) pch_id \\<and>\n      (\\<forall>j. (a_que_aux (locals_' x !j) pch_id) = (a_que_aux(locals_' y !j)) pch_id \\<and>\n           (r_que_aux (locals_' x !j) pch_id) = (r_que_aux(locals_' y !j)) pch_id)                         \n   ) \\<and>    \n   (\\<forall>ch_id. \n      (\\<nexists>j. j<procs conf \\<and> ch_id = port_channel conf (communication_' x) (pt (locals_' x !j))) \\<longrightarrow> \n      chans (communication_' x) ch_id = chans (communication_' y) ch_id \\<and>\n       (\\<forall>i.(a_que_aux (locals_' x !i) ch_id = a_que_aux (locals_' y !i) ch_id) \\<and> \n           (r_que_aux (locals_' x !i) ch_id = r_que_aux (locals_' y !i) ch_id) )) \\<and>       \n   (mut (the (chans (communication_' x) pch_id)) \\<noteq> i + 1 \\<longrightarrow>\n      mut (the (chans (communication_' y) pch_id)) \\<noteq> i + 1)\n    \n }\n\"\n\ndefinition Rely_Send_ReceiveS::\" nat \\<Rightarrow> (('c vars_scheme, 'a) xstate \\<times> ('c vars_scheme, 'a) xstate) set\"\nwhere\n\"Rely_Send_ReceiveS i   \\<equiv> {(x,y). x=y}\n\"\n\ndefinition Rely_Send_ReceiveQ :: \" nat \\<Rightarrow> (('c vars_scheme, 'a) xstate \\<times> ('c vars_scheme, 'a) xstate) set\"\nwhere\n\"Rely_Send_ReceiveQ i   \\<equiv>\n  {(x,y). ((\\<exists>x1 y1. \n           x=Normal x1 \\<and> y = Normal y1 \\<and>\n           (locals_' x1)!i = (locals_' y1)!i \\<and> \n           length (locals_' x1) = length (locals_' y1) \\<and>\n           (\\<forall>j.  (evnt (locals_' x1 !j) = evnt (locals_' y1 !j)) \\<and>\n                    (pt (locals_' x1 !j) = pt (locals_' y1 !j))) \\<and>   \n            state_conf x1 = state_conf y1 \\<and>                   \n           ((x1,y1)\\<in> Rely_Send_Receive i)\n          ) \\<or> x = y)\n  }\"\n\ndefinition Rely :: \" nat \\<Rightarrow> (('c vars_scheme, 'a) xstate \\<times> ('c vars_scheme, 'a) xstate) set\"\nwhere\n\"Rely i   \\<equiv>                                             \n  {(x,y). (x,y)\\<in> Rely_Send_ReceiveQ i \\<or> (x,y)\\<in> Rely_Send_ReceiveS i\n  }\"\n\n\n  \nlemma Rely_eq_send:\n  assumes a0':\"i<length (locals_' x)\" and        \n         a1:\"channel_received_messages  ch rems (locals_' x) \\<subseteq># \n           (B ch + channel_sent_messages  ch adds  (locals_' x))\" and  \n         a2:\"channel_get_messages (the (chans (communication_' x) ch)) = \n             (B ch + \n            channel_sent_messages  ch  adds (locals_' x) ) -\n            channel_received_messages  ch  rems (locals_' x)\" and\n       a5:\"channel_messages ch adds [0..<length (locals_' x)] \\<subseteq># \n           channel_messages  ch a_que_aux (locals_' x)\" and       \n       a7:\"(x,y,i)\\<in>preserves_locals_constr\"  and\n       a8:\"a_que_aux (locals_' y ! i) ch = {#msg (locals_' x ! i)#} + a_que_aux (locals_' x ! i) ch\" and\n       a9:\"r_que_aux (locals_' x ! i) ch = r_que_aux (locals_' y ! i) ch\"  and\n       a10:\"channel_get_messages (the (chans (communication_' y) ch)) = \n            channel_get_messages (the (chans (communication_' x) ch)) + {#msg (locals_' x ! i)#}\"\n      shows \"channel_get_messages (the (chans (communication_' y) ch)) =\n    B ch + channel_sent_messages ch adds (locals_' y) - channel_received_messages ch rems (locals_' y)\"\nproof-  \n  have eq_rec:\"channel_received_messages  ch rems  (locals_' x) =\n               channel_received_messages  ch rems  (locals_' y)\" \n    using add_channel_message_not_evnt  a9 a7 preserves_locals_D1 \n    unfolding channel_received_messages_def by fastforce   \n  moreover have eq_send:\"channel_messages  ch a_que_aux (locals_' x)  + \n                {#msg (locals_' x ! i)#} = channel_messages  ch a_que_aux (locals_' y)\"      \n    using a7 add_channel_message_evnt \n    by (metis a0' a8 union_commute)\n  ultimately show ?thesis\n  proof -\n    have \"channel_sent_messages ch adds (locals_' y) = \n          channel_messages ch a_que_aux (locals_' x) - \n              channel_messages ch adds [0..<length (locals_' y)] + {#msg (locals_' x ! i)#}\"       \n      by (metis (no_types) a5 a7 channel_sent_messages_def eq_send preserves_locals_D1 \n        subset_mset.add_diff_assoc2)\n    then have \"B ch + \n              channel_sent_messages ch adds (locals_' y) = \n                B ch + \n                channel_sent_messages ch adds (locals_' x) + {#msg (locals_' x ! i)#}\"\n      by (metis (no_types) a7 ab_semigroup_add_class.add_ac(1) channel_sent_messages_def \n             preserves_locals_D1)\n    then show ?thesis\n      by (metis (no_types)  a1 a10 a2 eq_rec subset_mset.add_diff_assoc2)\n  qed    \nqed     \n  \nlemma Rely_subset_send:\n  assumes a0':\"i<length (locals_' x)\" and        \n         a1:\"channel_received_messages  ch rems (locals_' x) \\<subseteq># \n             B ch + channel_sent_messages  ch adds  (locals_' x)\" and       \n       a5:\"channel_messages ch adds [0..<length (locals_' x)] \\<subseteq># \n           channel_messages  ch a_que_aux (locals_' x)\" and       \n       a7:\"(x,y,i)\\<in>preserves_locals_constr\" and\n       a8:\"a_que_aux (locals_' y ! i) ch = {#msg (locals_' x ! i)#} + a_que_aux (locals_' x ! i) ch\" and\n       a9:\"r_que_aux (locals_' x ! i) ch = r_que_aux (locals_' y ! i) ch\"        \n      shows \"channel_received_messages  ch rems (locals_' y) \\<subseteq># \n            B ch + channel_sent_messages  ch adds  (locals_' y)\"\nproof-\n  have eq_rec:\"channel_received_messages  ch rems  (locals_' x) =\n               channel_received_messages  ch rems  (locals_' y)\" \n    using add_channel_message_not_evnt a9 a7 preserves_locals_D1 \n    unfolding channel_received_messages_def by fastforce   \n  moreover have eq_send:\"channel_messages ch a_que_aux (locals_' x)  + \n                {#msg (locals_' x ! i)#} = channel_messages ch a_que_aux (locals_' y)\"      \n    using a7 add_channel_message_evnt\n    by (metis a0' a8 union_commute)\n  ultimately show ?thesis\n    by (metis a1 a5 a7 add_msg_send channel_sent_messages_def preserves_locals_D1)\nqed   \n\n\nlemma Rely_eq_rec:\n  assumes a0':\"i<length (locals_' x)\" and        \n         a1:\"channel_received_messages ch rems (locals_' x) \\<subseteq># \n             B ch + \n             channel_sent_messages  ch adds  (locals_' x)\" and  \n         a2:\"channel_get_messages (the (chans (communication_' x) ch)) = \n              B ch + channel_sent_messages ch  adds (locals_' x)  - \n               channel_received_messages ch  rems (locals_' x)\" and\n       a5:\"channel_messages ch rems [0..<length (locals_' x)] \\<subseteq># \n           channel_messages ch r_que_aux (locals_' x)\" and       \n       a7:\"(x,y,i)\\<in>preserves_locals_constr\" and\n       a8:\"r_que_aux (locals_' y ! i) ch = r_que_aux (locals_' x ! i) ch + m\" and\n       a9:\"m \\<subseteq># channel_get_messages (the (chans (communication_' x) ch))\" and       \n       a11:\" a_que_aux (locals_' x ! i) ch = a_que_aux (locals_' y ! i) ch\" and\n       a10:\"channel_get_messages (the (chans (communication_' y) ch)) =\n          channel_get_messages (the (chans (communication_' x) ch)) - m\"\n      shows \"channel_get_messages (the (chans (communication_' y) ch)) =\n     B ch + channel_sent_messages ch adds (locals_' y) - \n     channel_received_messages ch rems (locals_' y)\"\nproof-\n  have eq_rec:\"channel_sent_messages ch adds  (locals_' x) =\n                  channel_sent_messages ch adds  (locals_' y)\" \n    using add_channel_message_not_evnt a11 a7 preserves_locals_D1\n    unfolding  channel_sent_messages_def  by fastforce\n  moreover have eq_send:\"channel_messages ch r_que_aux (locals_' x)  + m  =\n            channel_messages ch r_que_aux (locals_' y)\"      \n    using a7 add_channel_message_evnt\n    by (metis a0' a8 union_commute)\n  ultimately show ?thesis\n    using a10 a2 a5 a7  preserves_locals_D1 unfolding channel_received_messages_def by fastforce \n qed      \n \n\n   \nlemma Rely_subset_rec:\n  assumes a0':\"i<length (locals_' x)\" and         \n         a1:\"channel_received_messages ch rems (locals_' x) \\<subseteq># \n            B ch + channel_sent_messages ch adds  (locals_' x)\" and       \n       a3:\"channel_get_messages (the (chans (communication_' x) ch)) = \n            B ch + channel_sent_messages ch  adds (locals_' x)  -\n            channel_received_messages ch rems (locals_' x)\" and\n       a4:\"channel_messages ch rems [0..<length (locals_' x)] \\<subseteq># \n           channel_messages ch r_que_aux (locals_' x)\" and       \n       a7:\"(x,y,i)\\<in>preserves_locals_constr\" and\n       a8:\"r_que_aux (locals_' y ! i) ch = r_que_aux (locals_' x ! i) ch + m\" and\n       a9:\"m \\<subseteq># channel_get_messages (the (chans (communication_' x) ch))\" and       \n       a11:\" a_que_aux (locals_' x ! i) ch = a_que_aux (locals_' y ! i) ch\"               \n      shows \"channel_received_messages  ch rems (locals_' y) \\<subseteq># \n           (B ch + channel_sent_messages ch adds  (locals_' y))\"\nproof-\n  have \"channel_messages ch r_que_aux (locals_' x)  + m  =\n            channel_messages ch r_que_aux (locals_' y)\"      \n     using a0' a7 a8 add_channel_message_evnt by blast               \n    moreover have \"channel_sent_messages ch adds  (locals_' x) =\n                  channel_sent_messages ch adds  (locals_' y)\"\n      using add_channel_message_not_evnt a11 a7\n      using channel_sent_messages_def preserves_locals_D1 by fastforce   \n    moreover have \"m\\<subseteq>#(B ch + \n             channel_sent_messages ch adds  (locals_' y)) -\n             channel_received_messages ch rems  (locals_' x)\"\n      using a3  a9 calculation(2) by auto  \n    ultimately show ?thesis using a1  a4  add_msg_rec a7 preserves_locals_D1\n      unfolding  channel_received_messages_def by fastforce        \n qed      \n\nlemma Rely_subset:\n  assumes a0:\"p_queuing conf (communication_' x) (pt (locals_' x ! i))\" and           \n         a1:\"channel_received_messages  (port_channel conf (communication_' x) (pt (locals_' x !i))) rems (locals_' x) \\<subseteq># \n           (B (port_channel conf (communication_' x) (pt (locals_' x !i))) + \n             channel_sent_messages  (port_channel conf (communication_' x) (pt (locals_' x !i))) adds  (locals_' x))\" and\n       a2:\"(Normal x,Normal y)\\<in>  Rely_Send_ReceiveQ i  \" and\n       a3:\"channel_get_messages (the (chans (communication_' x)  (port_channel conf (communication_' x) (pt (locals_' x !i))))) = \n             (B (port_channel conf (communication_' x) (pt (locals_' x !i))) + \n            channel_sent_messages  (port_channel conf (communication_' x) (pt (locals_' x !i)))  adds (locals_' x) ) -\n            channel_received_messages  (port_channel conf (communication_' x) (pt (locals_' x !i)))  rems (locals_' x)\" and\n       a4:\"channel_messages (port_channel conf (communication_' x) (pt (locals_' x !i))) rems [0..<length (locals_' x)] \\<subseteq># \n           channel_messages  (port_channel conf (communication_' x) (pt (locals_' x !i))) r_que_aux (locals_' x)\" and\n       a5:\"channel_messages (port_channel conf (communication_' x) (pt (locals_' x !i))) adds [0..<length (locals_' x)] \\<subseteq># \n           channel_messages  (port_channel conf (communication_' x) (pt (locals_' x !i))) a_que_aux (locals_' x)\"  and\n       a6:\"procs conf = length (locals_' x)\"\n      shows \"channel_received_messages  (port_channel conf (communication_' y) (pt (locals_' x !i))) rems (locals_' y) \\<subseteq># \n           (B (port_channel conf (communication_' y) (pt (locals_' x !i))) + \n             channel_sent_messages  (port_channel conf (communication_' y) (pt (locals_' x !i))) adds  (locals_' y))\"\nproof (cases \n    \"channel_get_messages (the (chans (communication_' x) (port_channel conf (communication_' x) (pt (locals_' x !i))))) \\<noteq>\n      channel_get_messages (the (chans (communication_' y) (port_channel conf (communication_' y) (pt (locals_' x !i)))))\")                  \n  case True            \n  define ch where \"ch = port_channel conf (communication_' x) (pt (locals_' x !i))\" \n  note [simp] = ch_def    \n  have portch_eq:\"port_channel conf (communication_' y) (pt (locals_' x ! i)) =\n                  port_channel conf (communication_' x) (pt (locals_' x ! i))\" \n    using a2 port_channl_eq_ports[THEN sym] \n    unfolding Rely_Send_ReceiveQ_def Rely_Send_Receive_def Let_def by auto\n  have relchan:\"Rely_mod_chan x y i\"    \n    using a2 unfolding Rely_Send_ReceiveQ_def Rely_Send_Receive_def Rely_mod_chan_def Let_def\n    by fast\n  note b0 = mp [OF conjunct1[OF relchan[simplified Rely_mod_chan_def Let_def]]  \n                   conjI[OF True[simplified portch_eq] a0] ]  \n  then obtain j where \n   b0: \"j<procs conf \\<and>\n        port_open (communication_' x) (pt (locals_' x !j)) \\<and>\n       ch =  (port_channel conf (communication_' x) (pt (locals_' x !j))) \\<and>\n        ((r_que_aux (locals_' y !j) ch\\<noteq> r_que_aux (locals_' x !j) ch) \\<or> \n         (a_que_aux (locals_' y !j) ch\\<noteq> a_que_aux (locals_' x !j) ch)) \\<and>\n       ((r_que_aux (locals_' y !j) ch\\<noteq> r_que_aux (locals_' x !j) ch \\<longrightarrow>\n          (\\<exists>m. r_que_aux (locals_' y !j) ch = r_que_aux (locals_' x !j) ch + m \\<and>\n             m\\<subseteq># channel_get_messages (the (chans (communication_' x) ch)) \\<and>\n            channel_get_messages (the (chans (communication_' y) ch)) = \n              channel_get_messages (the (chans (communication_' x) ch)) - m) \\<and>\n            a_que_aux (locals_' x !j) ch = a_que_aux (locals_' y !j) ch) \\<and>\n        (a_que_aux (locals_' y !j) ch\\<noteq> a_que_aux (locals_' x !j) ch \\<longrightarrow>\n         a_que_aux (locals_' y !j) ch = {#msg (locals_' x !j)#} + a_que_aux (locals_' x !j) ch \\<and>         \n         r_que_aux (locals_' x !j) ch = r_que_aux (locals_' y !j) ch  \\<and>\n          size (channel_get_messages (the (chans (communication_' y) ch))) \\<le> \n           channel_size (get_channel conf ch) \\<and>\n         channel_get_messages (the (chans (communication_' y) ch)) = \n           channel_get_messages (the (chans (communication_' x) ch)) + {#msg (locals_' x !j)#} ) \n       ) \\<and> (\\<forall>k. k\\<noteq>j \\<longrightarrow> locals_' x !k = locals_' y !k) \\<and> \n       (\\<forall>ch_id. ch_id\\<noteq>ch \\<longrightarrow> \n          a_que_aux (locals_' x !j) ch_id = a_que_aux (locals_' y !j) ch_id \\<and>\n          r_que_aux (locals_' x !j) ch_id = r_que_aux (locals_' y !j) ch_id)\"      \n     using ch_def by blast     \n    have pre_local:\"length (locals_' x) = length (locals_' y) \\<and>\n          (\\<forall>i'. evnt ((locals_' x)!i') = evnt ((locals_' y)!i') \\<and>\n                pt ((locals_' x)!i') = pt ((locals_' y)!i'))\"\n      using a2 unfolding Rely_Send_ReceiveQ_def by auto       \n    have preserves:\"(x,y,j)\\<in>preserves_locals_constr\"\n      using pre_local b0 unfolding preserves_locals_constr_def by auto\n  { assume \"r_que_aux (locals_' y ! j) ch \\<noteq> r_que_aux (locals_' x ! j) ch\"\n    then obtain m where \n      mod:\"(r_que_aux (locals_' y ! j) ch =\n        r_que_aux (locals_' x ! j) ch + m \\<and>\n        m \\<subseteq># channel_get_messages (the (chans (communication_' x) ch)) \\<and>\n        channel_get_messages (the (chans (communication_' y) ch)) =\n          channel_get_messages (the (chans (communication_' x) ch)) - m) \\<and>\n        a_que_aux (locals_' x ! j) ch =\n          a_que_aux (locals_' y ! j) ch \\<and>\n       (\\<forall>ch_id. ch_id \\<noteq> ch \\<longrightarrow>\n                  a_que_aux (locals_' x ! j) ch_id = a_que_aux (locals_' y ! j) ch_id \\<and>\n                  r_que_aux (locals_' x ! j) ch_id = r_que_aux (locals_' y ! j) ch_id)\" \n      using b0 by blast          \n    have ?thesis \n      using mod\n         Rely_subset_rec[of j x \"(port_channel conf (communication_' x) (pt (locals_' x ! i)))\" rems B adds _ m, \n                          OF _ a1 a3 a4 preserves ]          \n      using b0[unfolded a6] by (simp add: portch_eq)       \n  }\n  moreover { assume \"a_que_aux (locals_' y ! j) ch \\<noteq> a_que_aux (locals_' x ! j) ch\"\n    then have \n       mod:\"a_que_aux (locals_' y ! j) ch =\n           {#msg (locals_' x ! j)#} + a_que_aux (locals_' x ! j) ch \\<and>\n           r_que_aux (locals_' x ! j) ch = r_que_aux (locals_' y ! j) ch \\<and>\n           size (channel_get_messages (the (chans (communication_' y) ch)))\n             \\<le> channel_size (get_channel conf ch) \\<and>\n           channel_get_messages (the (chans (communication_' y) ch)) =\n           channel_get_messages (the (chans (communication_' x) ch)) + {#msg (locals_' x ! j)#}\" \n      using b0 by blast                 \n      have ?thesis \n      using mod\n         Rely_subset_send[of j x \"(port_channel conf (communication_' x) (pt (locals_' x ! i)))\" rems B adds, \n                          OF _ a1 a5 preserves]\n      using b0[unfolded a6] by (simp add: portch_eq)       \n  }\n  ultimately show ?thesis using b0 by fastforce\nnext\n  case False    \n  define ch where \"ch = port_channel conf (communication_' x) (pt (locals_' x !i))\" \n  note [simp] = ch_def    \n  have portch_eq:\"port_channel conf (communication_' y) (pt (locals_' x ! i)) = ch\" \n    using a2 port_channl_eq_ports[THEN sym] \n    unfolding Rely_Send_ReceiveQ_def Rely_Send_Receive_def Let_def by auto\n  have relchan:\"Rely_mod_chan x y i\"    \n    using a2 unfolding Rely_Send_ReceiveQ_def Rely_Send_Receive_def Rely_mod_chan_def Let_def\n    by fast  \n  then have b0:\"(\\<forall>j. r_que_aux (locals_' y !j) ch = r_que_aux (locals_' x !j) ch \\<and>\n                  a_que_aux (locals_' y !j) ch = a_que_aux (locals_' x !j) ch)\"\n    using False portch_eq unfolding Rely_mod_chan_def Let_def by auto \n      have pre_local:\"length (locals_' x) = length (locals_' y) \\<and>\n        (\\<forall>i'. evnt ((locals_' x)!i') = evnt ((locals_' y)!i') \\<and>\n              pt ((locals_' x)!i') = pt ((locals_' y)!i'))\"\n        using a2 unfolding Rely_Send_ReceiveQ_def by auto            \n  have preserves:\"(x,y,i)\\<in>preserves_locals_constr'\"\n    using pre_local b0 portch_eq unfolding preserves_locals_constr'_def  by auto  \n  then show ?thesis using False a1 portch_eq channel_messages_eq'[OF preserves]  pre_local b0\n    unfolding channel_received_messages_def channel_sent_messages_def \n    by (simp add: pre_local)      \n  qed\n        \nlemma Rely_chan_eq:\n assumes a0:\"p_queuing conf  (communication_' x) (pt (locals_' x ! i))\" and\n         a1:\"channel_received_messages  (port_channel conf  (communication_' x) (pt (locals_' x !i))) rems (locals_' x) \\<subseteq># \n           (B (port_channel conf  (communication_' x) (pt (locals_' x !i))) + \n             channel_sent_messages  (port_channel conf  (communication_' x) (pt (locals_' x !i))) adds  (locals_' x))\" and\n       a2:\"(Normal x,Normal y)\\<in>  Rely_Send_ReceiveQ i  \" and\n       a3:\"channel_get_messages (the (chans (communication_' x) (port_channel conf  (communication_' x) (pt (locals_' x !i))))) = \n             (B (port_channel conf  (communication_' x) (pt (locals_' x !i))) + \n            channel_sent_messages  (port_channel conf  (communication_' x) (pt (locals_' x !i)))  adds (locals_' x) ) -\n            channel_received_messages  (port_channel conf  (communication_' x) (pt (locals_' x !i)))  rems (locals_' x)\" and\n       a4:\"channel_messages (port_channel conf  (communication_' x) (pt (locals_' x !i))) rems [0..<length (locals_' x)] \\<subseteq># \n           channel_messages  (port_channel conf  (communication_' x) (pt (locals_' x !i))) r_que_aux (locals_' x)\" and\n       a5:\"channel_messages (port_channel conf (communication_' x) (pt (locals_' x !i))) adds [0..<length (locals_' x)] \\<subseteq># \n           channel_messages  (port_channel conf  (communication_' x) (pt (locals_' x !i))) a_que_aux (locals_' x)\" and\n       a6:\"procs conf = length (locals_' x)\"\n      shows \"channel_get_messages (the (chans (communication_' y) (port_channel conf (communication_' y) (pt (locals_' x !i))))) = \n             (B (port_channel conf  (communication_' y) (pt (locals_' x !i))) + \n            channel_sent_messages  (port_channel conf  (communication_' y) (pt (locals_' x !i)))  adds (locals_' y) ) -\n            channel_received_messages  (port_channel conf  (communication_' y) (pt (locals_' x !i)))  rems (locals_' y)\"\nproof (cases \n    \"channel_get_messages (the (chans (communication_' x) (port_channel conf  (communication_' x) (pt (locals_' x !i))))) \\<noteq>\n      channel_get_messages (the (chans (communication_' y) (port_channel conf (communication_' y) (pt (locals_' x !i)))))\")\n  case True\n  define ch where \"ch = port_channel conf (communication_' x) (pt (locals_' x !i))\" \n  note [simp] = ch_def    \n  have portch_eq:\"port_channel conf (communication_' y) (pt (locals_' x ! i)) =\n                  port_channel conf (communication_' x) (pt (locals_' x ! i))\" \n    using a2 port_channl_eq_ports[THEN sym] \n    unfolding Rely_Send_ReceiveQ_def Rely_Send_Receive_def Let_def by auto\n  have relchan:\"Rely_mod_chan x y i\"    \n    using a2 unfolding Rely_Send_ReceiveQ_def Rely_Send_Receive_def Rely_mod_chan_def Let_def\n    by fast\n  note b0 = mp [OF conjunct1[OF relchan[simplified Rely_mod_chan_def Let_def]]  \n                   conjI[OF True[simplified portch_eq] a0] ]  \n  then obtain j where \n   b0: \"j<procs conf \\<and>\n        port_open (communication_' x) (pt (locals_' x !j)) \\<and>\n       ch =  (port_channel conf (communication_' x) (pt (locals_' x !j))) \\<and>\n        ((r_que_aux (locals_' y !j) ch\\<noteq> r_que_aux (locals_' x !j) ch) \\<or> \n         (a_que_aux (locals_' y !j) ch\\<noteq> a_que_aux (locals_' x !j) ch)) \\<and>\n       ((r_que_aux (locals_' y !j) ch\\<noteq> r_que_aux (locals_' x !j) ch \\<longrightarrow>\n          (\\<exists>m. r_que_aux (locals_' y !j) ch = r_que_aux (locals_' x !j) ch + m \\<and>\n             m\\<subseteq># channel_get_messages (the (chans (communication_' x) ch)) \\<and>\n            channel_get_messages (the (chans (communication_' y) ch)) = \n              channel_get_messages (the (chans (communication_' x) ch)) - m) \\<and>\n            a_que_aux (locals_' x !j) ch = a_que_aux (locals_' y !j) ch) \\<and>\n        (a_que_aux (locals_' y !j) ch\\<noteq> a_que_aux (locals_' x !j) ch \\<longrightarrow>\n         a_que_aux (locals_' y !j) ch = {#msg (locals_' x !j)#} + a_que_aux (locals_' x !j) ch \\<and>         \n         r_que_aux (locals_' x !j) ch = r_que_aux (locals_' y !j) ch  \\<and>\n          size (channel_get_messages (the (chans (communication_' y) ch))) \\<le> \n           channel_size (get_channel conf ch) \\<and>\n         channel_get_messages (the (chans (communication_' y) ch)) = \n           channel_get_messages (the (chans (communication_' x) ch)) + {#msg (locals_' x !j)#} ) \n       ) \\<and> (\\<forall>k. k\\<noteq>j \\<longrightarrow> locals_' x !k = locals_' y !k) \\<and> \n       (\\<forall>ch_id. ch_id\\<noteq>ch \\<longrightarrow> \n          a_que_aux (locals_' x !j) ch_id = a_que_aux (locals_' y !j) ch_id \\<and>\n          r_que_aux (locals_' x !j) ch_id = r_que_aux (locals_' y !j) ch_id)\"      \n     using ch_def by blast     \n    have pre_local:\"length (locals_' x) = length (locals_' y) \\<and>\n          (\\<forall>i'. evnt ((locals_' x)!i') = evnt ((locals_' y)!i') \\<and>\n                pt ((locals_' x)!i') = pt ((locals_' y)!i'))\"\n      using a2 unfolding Rely_Send_ReceiveQ_def by auto        \n    have preserves:\"(x,y,j)\\<in>preserves_locals_constr\"\n      using pre_local b0 unfolding preserves_locals_constr_def by auto\n  { assume \"r_que_aux (locals_' y ! j) ch \\<noteq> r_que_aux (locals_' x ! j) ch\"\n    then obtain m where \n    mod:\"(r_que_aux (locals_' y ! j) ch =\n        r_que_aux (locals_' x ! j) ch + m \\<and>\n        m \\<subseteq># channel_get_messages (the (chans (communication_' x) ch)) \\<and>\n        channel_get_messages (the (chans (communication_' y) ch)) =\n          channel_get_messages (the (chans (communication_' x) ch)) - m) \\<and>\n        a_que_aux (locals_' x ! j) ch =\n          a_que_aux (locals_' y ! j) ch \\<and>\n       (\\<forall>ch_id. ch_id \\<noteq> ch \\<longrightarrow>\n                  a_que_aux (locals_' x ! j) ch_id = a_que_aux (locals_' y ! j) ch_id \\<and>\n                  r_que_aux (locals_' x ! j) ch_id = r_que_aux (locals_' y ! j) ch_id)\" \n      using b0 by blast \n    have ?thesis                          \n      using mod \n         Rely_eq_rec[of j x \"(port_channel conf (communication_' x) (pt (locals_' x ! i)))\" rems B adds, \n                          OF _ a1 a3 a4 preserves]\n      using b0[unfolded a6] by (simp add: portch_eq)  \n  }\n  moreover { assume \"a_que_aux (locals_' y ! j) ch \\<noteq> a_que_aux (locals_' x ! j) ch\"\n    then have \n       mod:\"a_que_aux (locals_' y ! j) ch =\n           {#msg (locals_' x ! j)#} + a_que_aux (locals_' x ! j) ch \\<and>\n           r_que_aux (locals_' x ! j) ch = r_que_aux (locals_' y ! j) ch \\<and>\n           size (channel_get_messages (the (chans (communication_' y) ch)))\n             \\<le> channel_size (get_channel conf ch) \\<and>\n           channel_get_messages (the (chans (communication_' y) ch)) =\n           channel_get_messages (the (chans (communication_' x) ch)) + {#msg (locals_' x ! j)#}\" \n      using b0 by blast                 \n      have ?thesis \n      using mod\n         Rely_eq_send[of j x \"(port_channel conf (communication_' x) (pt (locals_' x ! i)))\" rems B adds, \n                          OF _ a1 a3 a5 preserves]\n      using b0[unfolded a6] by (simp add: portch_eq) \n  }\n  ultimately show ?thesis using b0 by fastforce \nnext\n  case False\n    define ch where \"ch = port_channel conf (communication_' x) (pt (locals_' x !i))\" \n  note [simp] = ch_def    \n  have portch_eq:\"port_channel conf (communication_' y) (pt (locals_' x ! i)) = ch\" \n    using a2 port_channl_eq_ports[THEN sym] \n    unfolding Rely_Send_ReceiveQ_def Rely_Send_Receive_def Let_def by auto\n  have relchan:\"Rely_mod_chan x y i\"    \n    using a2 unfolding Rely_Send_ReceiveQ_def Rely_Send_Receive_def Rely_mod_chan_def Let_def\n    by fast  \n  then have b0:\"(\\<forall>j. r_que_aux (locals_' y !j) ch = r_que_aux (locals_' x !j) ch \\<and>\n                  a_que_aux (locals_' y !j) ch = a_que_aux (locals_' x !j) ch)\"\n    using False portch_eq unfolding Rely_mod_chan_def Let_def by auto \n      have pre_local:\"length (locals_' x) = length (locals_' y) \\<and>\n        (\\<forall>i'. evnt ((locals_' x)!i') = evnt ((locals_' y)!i') \\<and>\n              pt ((locals_' x)!i') = pt ((locals_' y)!i'))\"\n        using a2 unfolding Rely_Send_ReceiveQ_def by auto            \n  have preserves:\"(x,y,i)\\<in>preserves_locals_constr'\"\n    using pre_local b0 portch_eq unfolding preserves_locals_constr'_def  by auto                \n    then show ?thesis using False a1 portch_eq channel_messages_eq'[OF preserves]      \n      using a3 channel_received_messages_def channel_sent_messages_def pre_local by auto      \n  qed\n    \nlemma Rely_size:\n assumes a0:\"p_queuing conf  (communication_' x) (pt (locals_' x ! i))\" and         \n       a2:\"(Normal x,Normal y)\\<in>  Rely_Send_ReceiveQ i  \" and\n       a5':\"size (channel_get_messages (the (chans (communication_' x) (port_channel conf  (communication_' x) (pt (locals_' x !i)))))) \\<le> \n             channel_size (get_channel conf (port_channel conf  (communication_' x) (pt (locals_' x !i))))\" and\n       a6:\"procs conf = length (locals_' x)\"\n      shows \"size (channel_get_messages (the (chans (communication_' y) (port_channel conf  (communication_' y) (pt (locals_' x !i)))))) \\<le> \n             channel_size (get_channel conf (port_channel conf  (communication_' y) (pt (locals_' x !i))))\"\nproof (cases \n    \"channel_get_messages (the (chans (communication_' x) (port_channel conf  (communication_' x) (pt (locals_' x !i))))) \\<noteq>\n      channel_get_messages (the (chans (communication_' y) (port_channel conf (communication_' y) (pt (locals_' x !i)))))\")\n  case True\n  define ch where \"ch = port_channel conf (communication_' x) (pt (locals_' x !i))\" \n  note [simp] = ch_def    \n  have portch_eq:\"port_channel conf (communication_' y) (pt (locals_' x ! i)) =\n                  port_channel conf (communication_' x) (pt (locals_' x ! i))\" \n    using a2 port_channl_eq_ports[THEN sym] \n    unfolding Rely_Send_ReceiveQ_def Rely_Send_Receive_def Let_def by auto\n  have relchan:\"Rely_mod_chan x y i\"    \n    using a2 unfolding Rely_Send_ReceiveQ_def Rely_Send_Receive_def Rely_mod_chan_def Let_def\n    by fast\n  note b0 = mp [OF conjunct1[OF relchan[simplified Rely_mod_chan_def Let_def]]  \n                   conjI[OF True[simplified portch_eq] a0] ]  \n  then obtain j where \n   b0: \"j<procs conf \\<and>\n        port_open (communication_' x) (pt (locals_' x !j)) \\<and>\n       ch =  (port_channel conf (communication_' x) (pt (locals_' x !j))) \\<and>\n        ((r_que_aux (locals_' y !j) ch\\<noteq> r_que_aux (locals_' x !j) ch) \\<or> \n         (a_que_aux (locals_' y !j) ch\\<noteq> a_que_aux (locals_' x !j) ch)) \\<and>\n       ((r_que_aux (locals_' y !j) ch\\<noteq> r_que_aux (locals_' x !j) ch \\<longrightarrow>\n          (\\<exists>m. r_que_aux (locals_' y !j) ch = r_que_aux (locals_' x !j) ch + m \\<and>\n             m\\<subseteq># channel_get_messages (the (chans (communication_' x) ch)) \\<and>\n            channel_get_messages (the (chans (communication_' y) ch)) = \n              channel_get_messages (the (chans (communication_' x) ch)) - m) \\<and>\n            a_que_aux (locals_' x !j) ch = a_que_aux (locals_' y !j) ch) \\<and>\n        (a_que_aux (locals_' y !j) ch\\<noteq> a_que_aux (locals_' x !j) ch \\<longrightarrow>\n         a_que_aux (locals_' y !j) ch = {#msg (locals_' x !j)#} + a_que_aux (locals_' x !j) ch \\<and>         \n         r_que_aux (locals_' x !j) ch = r_que_aux (locals_' y !j) ch  \\<and>\n          size (channel_get_messages (the (chans (communication_' y) ch))) \\<le> \n           channel_size (get_channel conf ch) \\<and>\n         channel_get_messages (the (chans (communication_' y) ch)) = \n           channel_get_messages (the (chans (communication_' x) ch)) + {#msg (locals_' x !j)#} ) \n       ) \\<and> (\\<forall>k. k\\<noteq>j \\<longrightarrow> locals_' x !k = locals_' y !k) \\<and> \n       (\\<forall>ch_id. ch_id\\<noteq>ch \\<longrightarrow> \n          a_que_aux (locals_' x !j) ch_id = a_que_aux (locals_' y !j) ch_id \\<and>\n          r_que_aux (locals_' x !j) ch_id = r_que_aux (locals_' y !j) ch_id)\"      \n     using ch_def by blast        \n  { assume \"r_que_aux (locals_' y ! j) ch \\<noteq> r_que_aux (locals_' x ! j) ch\"\n    then obtain m where \n    mod:\"(r_que_aux (locals_' y ! j) ch =\n        r_que_aux (locals_' x ! j) ch + m \\<and>\n        m \\<subseteq># channel_get_messages (the (chans (communication_' x) ch)) \\<and>\n        channel_get_messages (the (chans (communication_' y) ch)) =\n          channel_get_messages (the (chans (communication_' x) ch)) - m) \\<and>\n        a_que_aux (locals_' x ! j) ch =\n          a_que_aux (locals_' y ! j) ch \\<and>\n       (\\<forall>ch_id. ch_id \\<noteq> ch \\<longrightarrow>\n                  a_que_aux (locals_' x ! j) ch_id = a_que_aux (locals_' y ! j) ch_id \\<and>\n                  r_que_aux (locals_' x ! j) ch_id = r_que_aux (locals_' y ! j) ch_id)\" \n      using b0 by blast \n    have ?thesis\n      by (metis a5' ch_def diff_subset_eq_self dual_order.trans mod portch_eq size_mset_mono)                                \n  }\n  moreover { assume \"a_que_aux (locals_' y ! j) ch \\<noteq> a_que_aux (locals_' x ! j) ch\"\n    then have \n       mod:\"a_que_aux (locals_' y ! j) ch =\n           {#msg (locals_' x ! j)#} + a_que_aux (locals_' x ! j) ch \\<and>\n           r_que_aux (locals_' x ! j) ch = r_que_aux (locals_' y ! j) ch \\<and>\n           size (channel_get_messages (the (chans (communication_' y) ch)))\n             \\<le> channel_size (get_channel conf ch) \\<and>\n           channel_get_messages (the (chans (communication_' y) ch)) =\n           channel_get_messages (the (chans (communication_' x) ch)) + {#msg (locals_' x ! j)#}\" \n      using b0 by blast                 \n      then have ?thesis unfolding ch_def using portch_eq by auto           \n  }\n  ultimately show ?thesis using b0 by fastforce \nnext\n  case False\n    define ch where \"ch = port_channel conf (communication_' x) (pt (locals_' x !i))\" \n  note [simp] = ch_def    \n  have portch_eq:\"port_channel conf (communication_' y) (pt (locals_' x ! i)) = ch\" \n    using a2 port_channl_eq_ports[THEN sym] \n    unfolding Rely_Send_ReceiveQ_def Rely_Send_Receive_def Let_def by auto  \n  then show ?thesis\n      using False a5' portch_eq by auto      \n  qed    \n    \n\n\nlemma Rely_chan_subset1:\n  assumes \n       a1:\"channel_messages (port_channel conf (communication_' x) (pt (locals_' x !i))) rems [0..<length (locals_' x)] \\<subseteq># \n           channel_messages  (port_channel conf  (communication_' x) (pt (locals_' x !i))) r_que_aux (locals_' x)\" and\n       a2:\"(Normal x,Normal y)\\<in>  Rely_Send_ReceiveQ i  \" and a3:\"procs conf = length (locals_' x)\"               \n      shows \"channel_messages (port_channel conf  (communication_' y) (pt (locals_' x !i))) rems [0..<length (locals_' y)] \\<subseteq># \n               channel_messages  (port_channel conf  (communication_' y) (pt (locals_' x !i))) r_que_aux (locals_' y) \" \nproof-\n  have len:\"length (locals_' x) = length (locals_' y)\" using a2 unfolding Rely_Send_ReceiveQ_def by auto \n  define ch where \"ch = port_channel conf (communication_' x) (pt (locals_' x !i))\" \n  note [simp] = ch_def    \n  have portch_eq:\"port_channel conf (communication_' y) (pt (locals_' x ! i)) = ch\" \n    using a2 port_channl_eq_ports[THEN sym] \n    unfolding Rely_Send_ReceiveQ_def Rely_Send_Receive_def Let_def by auto\n  have relchan:\"Rely_mod_chan x y i\"    \n    using a2 unfolding Rely_Send_ReceiveQ_def Rely_Send_Receive_def Rely_mod_chan_def Let_def\n    by fast  \n  {\n    assume True:\"channel_get_messages (the (chans (communication_' x) ch)) \\<noteq>\n            channel_get_messages (the (chans (communication_' y) ch)) \\<and>\n            p_queuing conf (communication_' x) (pt (locals_' x !i))\"\n    note b0 = mp [OF conjunct1[OF relchan[simplified Rely_mod_chan_def Let_def]]  \n                   True[simplified ch_def]]\n    then obtain j where \n     b0: \"j<procs conf \\<and>\n        port_open (communication_' x) (pt (locals_' x !j)) \\<and>\n       ch =  (port_channel conf (communication_' x) (pt (locals_' x !j))) \\<and>\n        ((r_que_aux (locals_' y !j) ch\\<noteq> r_que_aux (locals_' x !j) ch) \\<or> \n         (a_que_aux (locals_' y !j) ch\\<noteq> a_que_aux (locals_' x !j) ch)) \\<and>\n       ((r_que_aux (locals_' y !j) ch\\<noteq> r_que_aux (locals_' x !j) ch \\<longrightarrow>\n          (\\<exists>m. r_que_aux (locals_' y !j) ch = r_que_aux (locals_' x !j) ch + m \\<and>\n             m\\<subseteq># channel_get_messages (the (chans (communication_' x) ch)) \\<and>\n            channel_get_messages (the (chans (communication_' y) ch)) = \n              channel_get_messages (the (chans (communication_' x) ch)) - m) \\<and>\n            a_que_aux (locals_' x !j) ch = a_que_aux (locals_' y !j) ch) \\<and>\n        (a_que_aux (locals_' y !j) ch\\<noteq> a_que_aux (locals_' x !j) ch \\<longrightarrow>\n         a_que_aux (locals_' y !j) ch = {#msg (locals_' x !j)#} + a_que_aux (locals_' x !j) ch \\<and>         \n         r_que_aux (locals_' x !j) ch = r_que_aux (locals_' y !j) ch  \\<and>\n          size (channel_get_messages (the (chans (communication_' y) ch))) \\<le> \n           channel_size (get_channel conf ch) \\<and>\n         channel_get_messages (the (chans (communication_' y) ch)) = \n           channel_get_messages (the (chans (communication_' x) ch)) + {#msg (locals_' x !j)#} ) \n       ) \\<and> (\\<forall>k. k\\<noteq>j \\<longrightarrow> locals_' x !k = locals_' y !k) \\<and> \n       (\\<forall>ch_id. ch_id\\<noteq>ch \\<longrightarrow> \n          a_que_aux (locals_' x !j) ch_id = a_que_aux (locals_' y !j) ch_id \\<and>\n          r_que_aux (locals_' x !j) ch_id = r_que_aux (locals_' y !j) ch_id)\"      \n     using ch_def by blast         \n    {assume \"r_que_aux (locals_' y ! j) ch \\<noteq> r_que_aux (locals_' x ! j) ch\"\n      then obtain m where\n        \"r_que_aux (locals_' y !j) ch = r_que_aux (locals_' x !j) ch + m\" \n        using b0 by fast\n      then have ?thesis\n        by (metis  a3 a1 add_message_channel  portch_eq b0 ch_def len mset_subset_eq_add_left \n            subset_mset.add_increasing2 subset_mset.le_add_same_cancel1)        \n    }\n    moreover {assume \"r_que_aux (locals_' y !j) ch = r_que_aux (locals_' x !j) ch\"\n      then have \"\\<forall>j. r_que_aux (locals_' y !j) ch = r_que_aux (locals_' x !j) ch\"\n        using b0 portch_eq by metis\n      then have ?thesis using len a1  same_channel_messages portch_eq ch_def by metis \n     }\n     ultimately have ?thesis by auto\n  }       \n  moreover\n  { assume ass0: \n           \"channel_get_messages (the (chans (communication_' x) ch)) =\n            channel_get_messages (the (chans (communication_' y) ch)) \\<or>\n            \\<not>p_queuing conf (communication_' x) (pt (locals_' x !i))\"       \n    then have \"\\<forall>j. r_que_aux (locals_' y !j) ch = r_que_aux (locals_' x !j) ch\"\n      using relchan  unfolding Rely_mod_chan_def Let_def by auto\n    then have ?thesis using len a1 portch_eq ch_def same_channel_messages by metis \n  }\n  ultimately show ?thesis by auto      \nqed\n  \nlemma Rely_chan_subset2:\n  assumes        \n       a1:\"channel_messages (port_channel conf  (communication_' x) (pt (locals_' x !i))) adds [0..<length (locals_' x)] \\<subseteq># \n           channel_messages  (port_channel conf (communication_' x) (pt (locals_' x !i))) a_que_aux (locals_' x)\" and\n       a2:\"(Normal x,Normal y)\\<in>  Rely_Send_ReceiveQ i  \" and a3:\"procs conf = length (locals_' x)\"                     \n      shows \"channel_messages (port_channel conf (communication_' y) (pt (locals_' x !i))) adds [0..<length (locals_' y)] \\<subseteq># \n               channel_messages  (port_channel conf (communication_' y) (pt (locals_' x !i))) a_que_aux (locals_' y)\" \n  proof-\n  have len:\"length (locals_' x) = length (locals_' y)\" using a2 unfolding Rely_Send_ReceiveQ_def by auto \n  define ch where \"ch = port_channel conf (communication_' x) (pt (locals_' x !i))\" \n  note [simp] = ch_def    \n  have portch_eq:\"port_channel conf (communication_' y) (pt (locals_' x ! i)) = ch\" \n    using a2 port_channl_eq_ports[THEN sym] \n    unfolding Rely_Send_ReceiveQ_def Rely_Send_Receive_def Let_def by auto\n  have relchan:\"Rely_mod_chan x y i\"    \n    using a2 unfolding Rely_Send_ReceiveQ_def Rely_Send_Receive_def Rely_mod_chan_def Let_def\n    by fast  \n  {\n    assume True:\"channel_get_messages (the (chans (communication_' x) ch)) \\<noteq>\n            channel_get_messages (the (chans (communication_' y) ch)) \\<and>\n            p_queuing conf (communication_' x) (pt (locals_' x !i))\"\n    note b0 = mp [OF conjunct1[OF relchan[simplified Rely_mod_chan_def Let_def]]  \n                   True[simplified ch_def]]\n    then obtain j where \n     b0: \"j<procs conf \\<and>\n        port_open (communication_' x) (pt (locals_' x !j)) \\<and>\n       ch =  (port_channel conf (communication_' x) (pt (locals_' x !j))) \\<and>\n        ((r_que_aux (locals_' y !j) ch\\<noteq> r_que_aux (locals_' x !j) ch) \\<or> \n         (a_que_aux (locals_' y !j) ch\\<noteq> a_que_aux (locals_' x !j) ch)) \\<and>\n       ((r_que_aux (locals_' y !j) ch\\<noteq> r_que_aux (locals_' x !j) ch \\<longrightarrow>\n          (\\<exists>m. r_que_aux (locals_' y !j) ch = r_que_aux (locals_' x !j) ch + m \\<and>\n             m\\<subseteq># channel_get_messages (the (chans (communication_' x) ch)) \\<and>\n            channel_get_messages (the (chans (communication_' y) ch)) = \n              channel_get_messages (the (chans (communication_' x) ch)) - m) \\<and>\n            a_que_aux (locals_' x !j) ch = a_que_aux (locals_' y !j) ch) \\<and>\n        (a_que_aux (locals_' y !j) ch\\<noteq> a_que_aux (locals_' x !j) ch \\<longrightarrow>\n         a_que_aux (locals_' y !j) ch = {#msg (locals_' x !j)#} + a_que_aux (locals_' x !j) ch \\<and>         \n         r_que_aux (locals_' x !j) ch = r_que_aux (locals_' y !j) ch  \\<and>\n          size (channel_get_messages (the (chans (communication_' y) ch))) \\<le> \n           channel_size (get_channel conf ch) \\<and>\n         channel_get_messages (the (chans (communication_' y) ch)) = \n           channel_get_messages (the (chans (communication_' x) ch)) + {#msg (locals_' x !j)#} ) \n       ) \\<and> (\\<forall>k. k\\<noteq>j \\<longrightarrow> locals_' x !k = locals_' y !k) \\<and> \n       (\\<forall>ch_id. ch_id\\<noteq>ch \\<longrightarrow> \n          a_que_aux (locals_' x !j) ch_id = a_que_aux (locals_' y !j) ch_id \\<and>\n          r_que_aux (locals_' x !j) ch_id = r_que_aux (locals_' y !j) ch_id)\"      \n      using ch_def by blast      \n    have pre_local:\"length (locals_' x) = length (locals_' y) \\<and>\n          (\\<forall>i'. evnt ((locals_' x)!i') = evnt ((locals_' y)!i') \\<and>\n                pt ((locals_' x)!i') = pt ((locals_' y)!i'))\"\n      using a2 unfolding Rely_Send_ReceiveQ_def by auto       \n    have preserves:\"(x,y,j)\\<in>preserves_locals_constr\"\n      using pre_local b0 unfolding preserves_locals_constr_def by auto\n    {assume \"a_que_aux (locals_' y !j) ch\\<noteq> a_que_aux (locals_' x !j) ch\"\n      then obtain m where\n        \"a_que_aux (locals_' y !j) ch = \n         a_que_aux (locals_' x !j) ch + m\" \n        using b0 by force\n      then have ?thesis\n        by (metis a3 a1 add_message_channel portch_eq len b0 ch_def mset_subset_eq_add_left \n                  subset_mset.add_increasing2 subset_mset.le_add_same_cancel1)\n    }\n    moreover {assume \"a_que_aux (locals_' y !j) ch = a_que_aux (locals_' x !j) ch\"\n      then have \"\\<forall>j. a_que_aux (locals_' y !j) ch =\n                     a_que_aux (locals_' x !j) ch\"\n        using b0 ch_def portch_eq by metis\n      then have ?thesis using len a1  same_channel_messages portch_eq ch_def \n        by metis \n     }\n     ultimately have ?thesis by auto\n  }       \n  moreover\n  { assume ass0: \"channel_get_messages (the (chans (communication_' x) ch)) =\n            channel_get_messages (the (chans (communication_' y) ch)) \\<or>\n            \\<not>p_queuing conf (communication_' x) (pt (locals_' x !i))\"\n    then have \"\\<forall>j. a_que_aux (locals_' y !j) ch = a_que_aux (locals_' x !j) ch\"\n      using relchan unfolding Rely_mod_chan_def Let_def by auto    \n    then have ?thesis using len a1 portch_eq ch_def same_channel_messages by metis \n  }\n  ultimately show ?thesis by auto      \nqed\n  \nlemma Rely_chan_subset:\n  assumes        \n       a1:\"channel_messages (port_channel conf (communication_' x) (pt (locals_' x !i))) rems [0..<length (locals_' x)] \\<subseteq># \n           channel_messages  (port_channel conf (communication_' x) (pt (locals_' x !i))) r_que_aux (locals_' x)\" and\n       a2:\"channel_messages (port_channel conf (communication_' x) (pt (locals_' x !i))) adds [0..<length (locals_' x)] \\<subseteq># \n           channel_messages  (port_channel conf (communication_' x) (pt (locals_' x !i))) a_que_aux (locals_' x)\" and        \n       a3:\"(Normal x,Normal y)\\<in>  Rely_Send_ReceiveQ i  \" and a4:\"procs conf = length (locals_' x)\"\n      shows \"channel_messages (port_channel conf (communication_' y) (pt (locals_' x !i))) rems [0..<length (locals_' y)] \\<subseteq># \n               channel_messages  (port_channel conf (communication_' y) (pt (locals_' x !i))) r_que_aux (locals_' y) \\<and>\n             channel_messages (port_channel conf (communication_' y) (pt (locals_' x !i))) adds [0..<length (locals_' y)] \\<subseteq># \n               channel_messages  (port_channel conf (communication_' y) (pt (locals_' x !i))) a_que_aux (locals_' y)\"  \n  using a1 a2 a3 a4 Rely_chan_subset1 Rely_chan_subset2 by blast\n\nlemma Rely_chan_spec:\n   assumes a0:\"p_queuing conf  (communication_' x) (pt (locals_' x ! i))\" and\n         a1:\"channel_received_messages  (port_channel conf (communication_' x)  (pt (locals_' x !i))) rems (locals_' x) \\<subseteq># \n           (B (port_channel conf  (communication_' x) (pt (locals_' x !i))) + \n             channel_sent_messages  (port_channel conf  (communication_' x) (pt (locals_' x !i))) adds  (locals_' x))\" and\n       a2:\"(Normal x,Normal y)\\<in>  Rely_Send_ReceiveQ i  \" and\n       a3:\"channel_get_messages (the (chans (communication_' x) (port_channel conf  (communication_' x) (pt (locals_' x !i))))) = \n             (B (port_channel conf  (communication_' x) (pt (locals_' x !i))) + \n            channel_sent_messages  (port_channel conf  (communication_' x) (pt (locals_' x !i)))  adds (locals_' x) ) -\n            channel_received_messages  (port_channel conf  (communication_' x) (pt (locals_' x !i)))  rems (locals_' x)\" and\n       a4:\"channel_messages (port_channel conf  (communication_' x) (pt (locals_' x !i))) rems [0..<length (locals_' x)] \\<subseteq># \n           channel_messages  (port_channel conf  (communication_' x) (pt (locals_' x !i))) r_que_aux (locals_' x)\" and\n       a5:\"channel_messages (port_channel conf (communication_' x) (pt (locals_' x !i))) adds [0..<length (locals_' x)] \\<subseteq># \n           channel_messages  (port_channel conf  (communication_' x) (pt (locals_' x !i))) a_que_aux (locals_' x)\" and\n       a5':\"size (channel_get_messages (the (chans (communication_' x) (port_channel conf  (communication_' x) (pt (locals_' x !i)))))) \\<le> \n             channel_size (get_channel conf (port_channel conf  (communication_' x) (pt (locals_' x !i))))\" and\n       a6:\"procs conf = length (locals_' x)\"\n      shows \"channel_get_messages (the (chans (communication_' y) (port_channel conf  (communication_' y) (pt (locals_' x !i))))) = \n             (B (port_channel conf  (communication_' y) (pt (locals_' x !i))) + \n            channel_sent_messages  (port_channel conf  (communication_' y) (pt (locals_' x !i)))  adds (locals_' y) ) -\n            channel_received_messages  (port_channel conf  (communication_' y) (pt (locals_' x !i)))  rems (locals_' y) \\<and>\n            channel_received_messages  (port_channel conf  (communication_' y) (pt (locals_' x !i))) rems (locals_' y) \\<subseteq># \n           (B (port_channel conf  (communication_' y) (pt (locals_' x !i))) + \n             channel_sent_messages  (port_channel conf  (communication_' y) (pt (locals_' x !i))) adds  (locals_' y)) \\<and>\n           size (channel_get_messages (the (chans (communication_' y) (port_channel conf  (communication_' y) (pt (locals_' x !i)))))) \\<le> \n             channel_size (get_channel conf (port_channel conf  (communication_' y) (pt (locals_' x !i)))) \\<and>\n           channel_messages (port_channel conf  (communication_' y) (pt (locals_' x !i))) rems [0..<length (locals_' y)] \\<subseteq># \n                   channel_messages  (port_channel conf  (communication_' y) (pt (locals_' x !i))) r_que_aux (locals_' y) \\<and>\n                 channel_messages (port_channel conf  (communication_' y) (pt (locals_' x !i))) adds [0..<length (locals_' y)] \\<subseteq># \n                   channel_messages  (port_channel conf  (communication_' y) (pt (locals_' x !i))) a_que_aux (locals_' y)\"\n  using Rely_chan_eq[OF a0,of rems B, OF a1 a2 a3 a4 a5 a6] \n        Rely_subset[OF a0, of rems B, OF a1 a2 a3 a4 a5 a6]\n        Rely_size[OF a0 a2  a5' a6]\n        Rely_chan_subset1 Rely_chan_subset2 a2 a4 a5 a6 by blast\n    \nlemma rely_eq_channel:\"         \n          mut (the (chans (communication_' x1) (port_channel conf (communication_' x1) (pt (locals_' x1 !i))))) = Suc i \\<Longrightarrow>  \n          (Normal x1, Normal y1) \\<in> Rely_Send_ReceiveQ i  \\<Longrightarrow>\n            (channel_messages (port_channel conf (communication_' x1) (pt (locals_' x1 ! i))) a_que_aux  (locals_' x1) )  = \n            (channel_messages (port_channel conf (communication_' y1) (pt (locals_' y1 ! i))) a_que_aux (locals_' y1))  \\<and>\n            (channel_messages (port_channel conf (communication_' x1) (pt (locals_' x1 ! i))) r_que_aux  (locals_' x1) )  = \n            (channel_messages (port_channel conf (communication_' y1) (pt (locals_' y1 ! i))) r_que_aux (locals_' y1) ) \"\nproof-\n let ?p = \"port_channel conf (communication_' x1) (pt (locals_' x1 !i))\"\n assume\n        a1:\"mut (the (chans (communication_' x1) ?p)) = Suc i\" and\n        a2:\"(Normal x1, Normal y1) \\<in> Rely_Send_ReceiveQ i \"\n  have ports:\"ports (communication_' x1) = ports (communication_' y1)\"\n      using a2 unfolding Rely_Send_ReceiveQ_def Rely_Send_Receive_def Let_def by auto  \n  have f1:\"locals_' x1 ! i = locals_' y1 ! i\" using a2 unfolding Rely_Send_ReceiveQ_def by auto\n  moreover have f2:\" \\<forall>j. evnt (locals_' x1 ! j) = evnt (locals_' y1 ! j) \\<and> \n                         pt (locals_' x1 ! j) = pt (locals_' y1 ! j)\" \n    using a2 unfolding Rely_Send_ReceiveQ_def by auto\n  moreover then have \"(\\<forall>j. (a_que_aux (locals_' x1 !j) ?p) = (a_que_aux(locals_' y1 !j)) ?p \\<and>\n                            (r_que_aux (locals_' x1 !j) ?p) = (r_que_aux(locals_' y1 !j)) ?p)\"    \n  using a1 a2  unfolding Rely_Send_ReceiveQ_def Rely_Send_Receive_def Let_def apply simp by blast\n  moreover have \"length (locals_' x1) = length (locals_' y1)\" \n    using a2 unfolding Rely_Send_ReceiveQ_def by auto  \n  ultimately show ?thesis\n    using same_channel_messages port_channl_eq_ports[OF ports]\n    by (simp add: same_channel_messages) \nqed\n  \nlemma rely_eq_ports1:\"(Normal x1,  y) \\<in> Rely_Send_ReceiveQ i \\<Longrightarrow>\n       \\<exists>y1. y=Normal y1 \\<and> ports (communication_' x1) = ports (communication_' y1) \\<and>\n       pt (locals_' x1 !i) = pt (locals_' y1 !i)\"   \n  unfolding Rely_Send_ReceiveQ_def Rely_Send_Receive_def Let_def by auto\n\nlemma rely_eq_ports:\"(Normal x1, Normal y1) \\<in> Rely_Send_ReceiveQ i \\<Longrightarrow>\n       ports (communication_' x1) = ports (communication_' y1) \\<and>\n       pt (locals_' x1 !i) = pt (locals_' y1 !i)\"   \n  unfolding Rely_Send_ReceiveQ_def Rely_Send_Receive_def Let_def by auto    \n    \nlemma rely_eq_channel_inits:\"         \n          mut (the (chans (communication_' x1) (port_channel conf (communication_' x1) (pt (locals_' x1 !i))))) = Suc i \\<Longrightarrow>  \n          (Normal x1, Normal y1) \\<in> Rely_Send_ReceiveQ i  \\<Longrightarrow>\n            (channel_messages (port_channel conf (communication_' x1) (pt (locals_' x1 ! i))) a_que_aux  (locals_' x1) ) -\n             (channel_messages (port_channel conf (communication_' x1) (pt (locals_' x1 ! i))) adds [0..< (length (locals_' x1))]) = \n            (channel_messages (port_channel conf (communication_' y1) (pt (locals_' y1 ! i))) a_que_aux (locals_' y1) -\n             (channel_messages (port_channel conf (communication_' y1) (pt (locals_' y1 ! i))) adds [0..< (length (locals_' y1))])) \\<and>\n            (channel_messages (port_channel conf (communication_' x1) (pt (locals_' x1 ! i))) r_que_aux  (locals_' x1) ) -\n             (channel_messages (port_channel conf (communication_' x1) (pt (locals_' x1 ! i))) rems [0..< (length (locals_' x1))]) = \n            (channel_messages (port_channel conf (communication_' y1) (pt (locals_' y1 ! i))) r_que_aux (locals_' y1) ) -\n             (channel_messages (port_channel conf (communication_' y1) (pt (locals_' y1 ! i))) rems [0..< (length (locals_' y1))])\"\n  apply (drule rely_eq_channel,assumption)\n  apply (frule rely_eq_ports)\n  apply clarsimp     \n  apply (frule port_channl_eq_ports[of _ _ i]) \n  unfolding Rely_Send_ReceiveQ_def by force\n  \n\nlemma rely_eq_queue:\"\n          (p_queuing conf (communication_' x1) (pt (locals_' x1 ! i))) \\<Longrightarrow>         \n          mut (the (chans (communication_' x1) (port_channel conf (communication_' x1) (pt (locals_' x1 !i))))) = Suc i \\<Longrightarrow>  \n          (Normal x1, Normal y1) \\<in> Rely_Send_ReceiveQ i  \\<Longrightarrow>\n          chans (communication_' x1) (port_channel conf (communication_' x1) (pt (locals_' x1 !i))) = \n          chans (communication_' y1) (port_channel conf (communication_' y1) (pt (locals_' x1 !i)))\"\nproof-\n  assume a0: \"(p_queuing conf (communication_' x1) (pt (locals_' x1 ! i)))\" and\n        a1:\"mut (the (chans (communication_' x1) (port_channel conf (communication_' x1) (pt (locals_' x1 !i))))) = Suc i\" and\n        a2:\"(Normal x1, Normal y1) \\<in> Rely_Send_ReceiveQ i \"        \n  thus ?thesis unfolding Rely_Send_ReceiveQ_def Rely_Send_Receive_def Let_def    \n    apply simp       \n    by (metis (no_types, lifting) port_channl_eq_ports)\n      \nqed\n  \nsubsection {* lemmas on reflexivity of Rely\\_Send*}\n  \nlemma reflexive_Guarantee_Send:\n  \"( s,  s) \\<in> Guarantee_Send_Receive i\"\n  unfolding Guarantee_Send_Receive_def Guarantee_Send_Receive'_def \n            Guarantee_mod_chan_def\n  by auto\n\nlemma reflexive_rely_send:\n  \"(a,a) \\<in> Rely_Send_ReceiveQ i\"\n  unfolding Rely_Send_ReceiveQ_def\n  by auto\n\n\n\nlemma sta_ch_spec_mut:\" \n           Sta (\\<lbrace>p_queuing conf  \\<acute>communication (pt (\\<acute>locals ! i))\\<rbrace> \\<inter>                 \n                \\<lbrace>port_get_mutex conf \\<acute>communication (pt (\\<acute>locals ! i)) = Suc i\\<rbrace> \\<inter>\n                {x.  ch_spec B adds rems (port_channel conf (communication_' x) (pt ((locals_' x) ! i))) x})\n             (Rely_Send_ReceiveQ i )\"\nunfolding  Sta_def \nproof clarify\n  fix i y x'\n  assume\n   a0:\"ch_spec B adds rems (port_channel conf (communication_' (x'::'a vars_scheme)) (pt (locals_' x' ! i))) x'\" and\n   a1:\"p_queuing conf (communication_' x') (pt (locals_' x' ! i))\" and\n   a2:\"port_get_mutex conf (communication_' x') (pt (locals_' x' ! i)) = Suc i\" and\n   a3:\"(Normal x', (y::('a vars_scheme, 'b) xstate)) \\<in> Rely_Send_ReceiveQ i  \" \n  then obtain y' where y:\"y=Normal y' \\<and> length (locals_' x') = length (locals_' y')\" \n    unfolding Rely_Send_ReceiveQ_def by auto\n  have eq_chan:\"channel_messages (port_channel conf (communication_' x') (pt (locals_' x' ! i))) a_que_aux  (locals_' x') = \n                channel_messages (port_channel conf (communication_' y') (pt (locals_' y' ! i))) a_que_aux  (locals_' y') \\<and>\n                channel_messages (port_channel conf (communication_' x') (pt (locals_' x' ! i))) r_que_aux  (locals_' x') = \n                channel_messages (port_channel conf(communication_' y')  (pt (locals_' y' ! i))) r_que_aux  (locals_' y')\"\n    using rely_eq_channel[OF a2[simplified port_get_mutex_def channel_get_mutex_def Let_def] a3[simplified y]]  \n    by auto\n  also have eq_q:\"chans (communication_' x') (port_channel conf (communication_' x') (pt (locals_' x' !i))) = \n                  chans (communication_' y') (port_channel conf (communication_' y') (pt (locals_' x' !i)))\"\n  using rely_eq_queue[OF a1]  using a1 a2 a3 y \n    unfolding port_get_mutex_def channel_get_mutex_def by fastforce\n  have eq_locals:\"locals_' x' !i = locals_' y'!i\" using a3 y unfolding Rely_Send_ReceiveQ_def by auto\n  then have eq:\"pt (locals_' x' !i) = pt(locals_' y'!i)\" by auto\n  have f1:\"p_queuing conf (communication_' y') (pt (locals_' y' ! i))\" using a1 y a3 unfolding Rely_def\n    by (metis (no_types, lifting) a3 p_queuing_def port_channl_eq_ports rely_eq_ports)\n  have f2:\"port_get_mutex conf (communication_' y') (pt (locals_' y' ! i)) = Suc i\"\n    using a1 a2 a3 y\n    unfolding Rely_Send_ReceiveQ_def Rely_Send_Receive_def  \n              port_get_mutex_def channel_get_mutex_def Let_def              \n    using eq_q by fastforce    \n  have f3:\"ch_spec B adds rems (port_channel conf (communication_' y') (pt (locals_' y' ! i))) y'\"\n    using a0 eq_chan eq_q eq_locals y\n    unfolding ch_spec_def  \n        channel_received_messages_def channel_sent_messages_def\n    by (metis a3 port_channl_eq_ports rely_eq_ports)            \n  then show \"\\<exists>y'. y = Normal y' \\<and>\n            y' \\<in> \\<lbrace>p_queuing conf \\<acute>communication (pt (\\<acute>locals ! i))\\<rbrace> \\<inter>                  \n                 \\<lbrace>port_get_mutex conf \\<acute>communication (pt (\\<acute>locals ! i)) = Suc i\\<rbrace> \\<inter>\n                  {x. ch_spec B adds rems (port_channel conf (communication_' x) (pt (locals_' x ! i))) x}\"\n   using y f1 f2 f3 by auto\nqed\n    \n\n\nlemma sta_send_mod_que:\"Sta\n          (\\<lbrace>p_queuing conf \\<acute>communication (pt (\\<acute>locals ! i))\\<rbrace> \\<inter>           \n           \\<lbrace>port_get_mutex conf \\<acute>communication (pt (\\<acute>locals ! i)) = Suc i\\<rbrace> \\<inter>\n           \\<lbrace>channel_get_messages (the (chans \\<acute>communication (port_channel conf \\<acute>communication (pt (\\<acute>locals ! i))))) =\n            add_mset (msg (\\<acute>locals ! i))\n             (B (port_channel conf \\<acute>communication (pt (\\<acute>locals ! i))) + \n             channel_sent_messages (port_channel conf \\<acute>communication (pt (\\<acute>locals ! i))) adds \\<acute>locals -\n             channel_received_messages (port_channel conf \\<acute>communication (pt (\\<acute>locals ! i))) rems \\<acute>locals) \\<and>\n           channel_received_messages  (port_channel conf \\<acute>communication (pt (\\<acute>locals ! i))) rems \\<acute>locals  \\<subseteq>#\n            B (port_channel conf \\<acute>communication (pt (\\<acute>locals ! i))) + \n              channel_sent_messages  (port_channel conf \\<acute>communication (pt (\\<acute>locals ! i))) adds \\<acute>locals \\<and>\n            size (channel_get_messages  (the (chans \\<acute>communication (port_channel conf \\<acute>communication (pt (\\<acute>locals ! i))))))\n            \\<le> channel_size (get_channel conf (port_channel conf \\<acute>communication (pt (\\<acute>locals ! i))))\\<rbrace>)\n          (Rely_Send_ReceiveQ i )\n\" \nunfolding  Sta_def \nproof clarify\n  fix i y x'\nassume\n   a1:\"p_queuing conf (communication_' x') (pt (locals_' (x'::'a vars_scheme) ! i))\" and\n   a2:\"port_get_mutex conf (communication_' x') (pt (locals_' x' ! i)) = Suc i\" and\n   a3:\"(Normal x', (y::('a vars_scheme, 'b) xstate)) \\<in> Rely_Send_ReceiveQ i   \" and  \n   a4:\"channel_get_messages (the (chans (communication_' x') (port_channel conf (communication_' x') (pt (locals_' x' ! i))))) =\n       add_mset (msg (locals_' x' ! i))\n        (B (port_channel conf (communication_' x') (pt (locals_' x' ! i))) + \n         channel_sent_messages (port_channel conf  (communication_' x') (pt (locals_' x' ! i))) adds (locals_' x') -\n         channel_received_messages (port_channel conf (communication_' x') (pt (locals_' x' ! i))) rems (locals_' x'))\" and\n   a5:\"channel_received_messages  (port_channel conf (communication_' x') (pt (locals_' x' ! i))) rems (locals_' x')  \\<subseteq>#\n        B (port_channel conf (communication_' x') (pt (locals_' x' ! i))) + \n          channel_sent_messages  (port_channel conf (communication_' x') (pt (locals_' x' ! i))) adds  (locals_' x')\" and \n   a6:\"size (channel_get_messages  (the (chans (communication_' x') (port_channel conf (communication_' x') (pt (locals_' x' ! i))))))\n        \\<le> channel_size (get_channel conf (port_channel conf (communication_' x') (pt (locals_' x' ! i))))\" \n  then obtain y' where y:\"y=Normal y' \\<and> length (locals_' x') = length (locals_' y')\" \n    unfolding Rely_Send_ReceiveQ_def by auto\n  have port_chan:\"port_channel conf (communication_' x') (pt (locals_' x' ! i)) = port_channel conf (communication_' y') (pt (locals_' x' ! i))\"\n    using port_channl_eq_ports rely_eq_ports using a3 y by blast   \n  have eq_chan:\"(channel_messages  (port_channel conf (communication_' x') (pt (locals_' x' ! i))) a_que_aux (locals_' x') ) -\n                 (channel_messages (port_channel conf (communication_' x') (pt (locals_' x' ! i))) adds [0..< (length (locals_' x'))]) = \n                (channel_messages  (port_channel conf(communication_' y')  (pt (locals_' y' ! i))) a_que_aux  (locals_' y'))-\n                 (channel_messages (port_channel conf (communication_' y') (pt (locals_' y' ! i))) adds [0..< (length (locals_' y'))]) \\<and>\n                 (channel_messages  (port_channel conf (communication_' x') (pt (locals_' x' ! i))) r_que_aux (locals_' x') )-\n                 (channel_messages (port_channel conf (communication_' x') (pt (locals_' x' ! i))) rems [0..< (length (locals_' x'))]) = \n                 (channel_messages  (port_channel conf (communication_' y') (pt (locals_' y' ! i))) r_que_aux  (locals_' y'))-\n                 (channel_messages (port_channel conf (communication_' y') (pt (locals_' y' ! i))) rems [0..< (length (locals_' y'))])\"\n    using rely_eq_channel_inits using a1 a2 a3 y \n    unfolding port_get_mutex_def  Let_def channel_get_mutex_def by blast\n  also have eq_q:\"chans (communication_' x') (port_channel conf (communication_' x') (pt (locals_' x' !i))) = \n                  chans (communication_' y') (port_channel conf (communication_' y') (pt (locals_' x' !i)))\"\n  using rely_eq_queue[OF a1]  using a1 a2 a3 y \n    unfolding port_get_mutex_def  Let_def channel_get_mutex_def by fastforce\n  have eq_locals:\"locals_' x' !i = locals_' y'!i\" using a3 y unfolding Rely_Send_ReceiveQ_def by auto\n  have f1:\"p_queuing conf (communication_' y') (pt (locals_' y' ! i))\" \n    using a1 y a3 unfolding Rely_Send_ReceiveQ_def\n    by (metis (no_types, lifting) a3 p_queuing_def port_channl_eq_ports rely_eq_ports)\n  have f2:\"port_get_mutex conf (communication_' y') (pt (locals_' y' ! i)) = Suc i\"\n    using a1 a2 a3 y \n    unfolding Rely_Send_ReceiveQ_def Rely_Send_Receive_def port_get_mutex_def  \n    channel_get_mutex_def Let_def eq_q\n    by fastforce\n  have f3:\"channel_get_messages (the (chans (communication_' y') (port_channel conf (communication_' y') (pt (locals_' y' ! i))))) =\n        B (port_channel conf (communication_' y') (pt (locals_' y' ! i))) + \n          channel_sent_messages (port_channel conf (communication_' y') (pt (locals_' y' ! i))) adds (locals_' y') -\n          channel_received_messages (port_channel conf (communication_' y') (pt (locals_' y' ! i))) rems (locals_' y') + \n            {# msg (locals_' y' ! i) #} \\<and>\n         channel_received_messages (port_channel conf (communication_' y') (pt (locals_' y' ! i))) rems  (locals_' y') \\<subseteq>#\n          B (port_channel conf (communication_' y') (pt (locals_' y' ! i))) + \n            channel_sent_messages (port_channel conf (communication_' y') (pt (locals_' y' ! i))) adds   (locals_' y') \\<and>\n      size (channel_get_messages  (the (chans (communication_' y') (port_channel conf (communication_' y') (pt (locals_' y' ! i))))))\n        \\<le> channel_size (get_channel conf (port_channel conf (communication_' y') (pt (locals_' y' ! i))))\"\n      using a4 a5 a6 eq_chan eq_q eq_locals port_chan\n      unfolding  channel_received_messages_def channel_sent_messages_def \n        by auto\n  then show \"\\<exists>y'. y = Normal y' \\<and>\n                   y' \\<in> \\<lbrace>p_queuing conf \\<acute>communication (pt (\\<acute>locals ! i))\\<rbrace> \\<inter> \\<lbrace>port_get_mutex conf \\<acute>communication (pt (\\<acute>locals ! i)) = Suc i\\<rbrace> \\<inter>\n                         \\<lbrace>channel_get_messages (the (chans \\<acute>communication (port_channel conf \\<acute>communication (pt (\\<acute>locals ! i))))) =\n                          add_mset (msg (\\<acute>locals ! i))\n                            (B (port_channel conf \\<acute>communication (pt (\\<acute>locals ! i))) + \n                              channel_sent_messages (port_channel conf \\<acute>communication (pt (\\<acute>locals ! i))) adds \\<acute>locals -\n                              channel_received_messages (port_channel conf \\<acute>communication (pt (\\<acute>locals ! i))) rems \\<acute>locals) \\<and>\n                           channel_received_messages (port_channel conf  \\<acute>communication(pt (\\<acute>locals ! i))) rems \\<acute>locals  \\<subseteq>#\n                          B (port_channel conf \\<acute>communication (pt (\\<acute>locals ! i))) +\n                          channel_sent_messages (port_channel conf \\<acute>communication (pt (\\<acute>locals ! i))) adds \\<acute>locals \\<and>\n                          size (channel_get_messages (the (chans \\<acute>communication (port_channel conf \\<acute>communication (pt (\\<acute>locals ! i))))))\n                          \\<le> channel_size (get_channel conf (port_channel conf \\<acute>communication (pt (\\<acute>locals ! i))))\\<rbrace>\"\n   using y f1 f2 f3 by fastforce\nqed\nsubsection {*Guarantee is in Rely*}\ntext{* we prove that Guarantee j is in Rely i for j!=i *}\n\nlemma Guar_in_Rely_i1:\n\"i < n \\<Longrightarrow>\n x < n \\<Longrightarrow>\n x \\<noteq> i \\<Longrightarrow>\n a = Normal x1 \\<Longrightarrow>\n b = Normal y1 \\<Longrightarrow>\n \\<forall>j<n. x \\<noteq> j \\<longrightarrow> locals_' x1 ! j = locals_' y1 ! j \\<Longrightarrow>\n  (locals_' x1)!i = (locals_' y1)!i\"\nby auto\n\nlemma Guar_in_Rely_i2:\n\"i < n \\<Longrightarrow>\n x < n \\<Longrightarrow>\n x \\<noteq> i \\<Longrightarrow>\n a = Normal x1 \\<Longrightarrow>\n b = Normal y1 \\<Longrightarrow>\n \\<forall>j<n. x \\<noteq> j \\<longrightarrow> locals_' x1 ! j = locals_' y1 ! j \\<Longrightarrow>\n ports (communication_' x1) = ports (communication_' y1) \\<Longrightarrow> \n ports (communication_' x1) =  ports (communication_' y1)\n\"\nby auto\n\nlemma Guar_in_Rely_i3:\n\"x \\<noteq> i \\<Longrightarrow> \n \\<forall>j. j \\<noteq> x \\<longrightarrow> locals_' x1 ! j = locals_' y1 ! j \\<Longrightarrow>   \n  (a_que_aux (locals_' x1 !x) ch1 \\<noteq> \n   a_que_aux (locals_' y1 !x) ch1 \\<or>\n   r_que_aux (locals_' x1 !x) ch1 \\<noteq> \n   r_que_aux (locals_' y1 !x) ch1 \\<longrightarrow>\n    mut (the (chans (communication_' x1) ch1)) = x + 1 \\<or>\n    mut (the (chans (communication_' y1) ch1)) = x + 1 ) \\<Longrightarrow>  \n (chans (communication_' x1) ch1\\<noteq> \n  chans (communication_' y1) ch1 \\<longrightarrow>\n      mut (the (chans (communication_' x1) ch1)) = x + 1 \\<or> \n      mut (the (chans (communication_' y1) ch1)) = x + 1 ) \\<Longrightarrow>    \n    (mut (the (chans (communication_' x1) ch1)) \\<noteq>\n     mut (the (chans (communication_' y1) ch1))) \\<longrightarrow>\n      (mut (the (chans (communication_' x1) ch1)) = 0 \\<or> \n      mut (the (chans (communication_' y1) ch1)) = 0) \\<Longrightarrow>  \n  ((mut (the (chans (communication_' x1) ch1)) = i + 1 \\<or> \n   mut (the (chans (communication_' y1) ch1)) = i + 1)  \\<longrightarrow>\n      chans (communication_' x1) ch1 =\n      chans (communication_' y1) ch1 \\<and>\n      (\\<forall>j. (a_que_aux (locals_' x1 !j) ch1) =  \n                   (a_que_aux(locals_' y1 !j)) ch1 \\<and>\n                   (r_que_aux (locals_' x1 !j) ch1) =  \n                   (r_que_aux(locals_' y1 !j)) ch1)                         \n           )\n\"\nproof(clarify)\n  assume \n         a2:\"x \\<noteq> i\" and                  \n         a5:\"\\<forall>j. j \\<noteq> x \\<longrightarrow> locals_' x1 ! j = locals_' y1 ! j\" and                             \n         a9:\"(chans (communication_' x1) ch1\\<noteq> \n              chans (communication_' y1) ch1 \\<longrightarrow>\n                mut (the (chans (communication_' x1) ch1)) = x + 1 \\<or> \n                mut (the (chans (communication_' y1) ch1)) = x + 1 )\" and\n         a10:\"(mut (the (chans (communication_' x1) ch1)) \\<noteq>\n               mut (the (chans (communication_' y1) ch1))) \\<longrightarrow>\n                  (mut (the (chans (communication_' x1) ch1)) = 0 \\<or> \n                   mut (the (chans (communication_' y1) ch1)) = 0)\" and \n         a11:\" a_que_aux (locals_' x1 ! x) ch1 \\<noteq>\n               a_que_aux (locals_' y1 ! x) ch1 \\<or>\n               r_que_aux (locals_' x1 ! x) ch1 \\<noteq>\n               r_que_aux (locals_' y1 ! x) ch1 \\<longrightarrow>\n                 mut (the (chans (communication_' x1) ch1)) = x + 1 \\<or>\n                 mut (the (chans (communication_' y1) ch1)) = x + 1 \" and\n         a12:\"mut (the (chans (communication_' x1) ch1)) = i + 1 \\<or>\n              mut (the (chans (communication_' y1) ch1)) = i + 1\"    \n  have \"chans (communication_' x1) ch1 = chans (communication_' y1) ch1\"\n    using   a2   a9 a10  a12 by force  \n  also have \"(\\<forall>j. a_que_aux (locals_' x1 ! j) ch1 = a_que_aux (locals_' y1 ! j) ch1 \\<and>\n                    r_que_aux (locals_' x1 ! j) ch1 = r_que_aux (locals_' y1 ! j) ch1)\"\n    using  a2  a5 a11 a12 calculation by auto   \n  ultimately show \n   \"chans (communication_' x1) ch1 = chans (communication_' y1) ch1 \\<and>\n    (\\<forall>j. a_que_aux (locals_' x1 ! j) ch1 = a_que_aux (locals_' y1 ! j) ch1 \\<and>\n          r_que_aux (locals_' x1 ! j) ch1 = r_que_aux (locals_' y1 ! j) ch1)\" by auto\nqed\n\n lemma guar_in_rely_i5:           \n   assumes a0:\"j\\<noteq>i\" and a0':\"ch = port_channel conf (communication_' x) (pt (locals_' x !j))\" and\n     a1:\"Guarantee_mod_chan x y j\" and \n     a1':\"ports (communication_' x) = ports (communication_' y)\" and\n    a2:\"(chans (communication_' x) ch\\<noteq> chans (communication_' y) ch \\<longrightarrow>\n          (mut (the (chans (communication_' x) ch)) = j + 1 \\<or> \n           mut (the (chans (communication_' y) ch)) = j + 1))\" and\n    a3:\"(\\<forall>ch_id. ch_id\\<noteq>ch \\<longrightarrow>\n            chans (communication_' x) ch_id = chans (communication_' y) ch_id)\" and\n    a4:\" (\\<forall>ch_id. (ch_id \\<noteq> ch \\<longrightarrow>\n               (a_que_aux (locals_' x !j) ch_id = a_que_aux (locals_' y !j) ch_id) \\<and> \n               (r_que_aux (locals_' x !j) ch_id = r_que_aux (locals_' y !j) ch_id)))\" and\n    a5:\"\\<forall>k. k\\<noteq>j \\<longrightarrow> locals_' x!k =locals_' y!k\" and\n    a6:\"j<procs conf\" \n  shows \"Rely_mod_chan x y i\"     \n proof-\n   let ?ch_rel = \"port_channel conf (communication_' x) (pt (locals_' x !i))\"\n  {\n    assume eq_chan:\"\n      channel_get_messages (the (chans (communication_' x) ?ch_rel)) \\<noteq>\n      channel_get_messages (the (chans (communication_' y) ?ch_rel))\" and\n          p_queuing:\"p_queuing conf (communication_' x) (pt (locals_' x !i))\"          \n   then have eq_port:\"port_channel conf (communication_' x) (pt (locals_' x !i)) = \n                      port_channel conf (communication_' x) (pt (locals_' x !j))\"\n     using a3 a0' by auto \n   have p_q:\"p_queuing conf  (communication_' x) (pt (locals_' x !j))\" \n     using eq_port p_queuing p_queuing_def by auto       \n   then have \"\n          port_open (communication_' x) (pt (locals_' x ! j)) \\<and>\n        (r_que_aux (locals_' y !j) ch\\<noteq> r_que_aux (locals_' x !j) ch \\<or> \n         a_que_aux (locals_' y !j) ch\\<noteq> a_que_aux (locals_' x !j) ch) \\<and>\n       ((r_que_aux (locals_' y !j) ch\\<noteq> r_que_aux (locals_' x !j) ch \\<longrightarrow>\n          (\\<exists>m. r_que_aux (locals_' y !j) ch = r_que_aux (locals_' x !j) ch + m \\<and>\n             m\\<subseteq># channel_get_messages (the (chans (communication_' x) ch)) \\<and>\n            channel_get_messages (the (chans (communication_' y) ch)) = \n              channel_get_messages (the (chans (communication_' x) ch)) - m) \\<and>\n            a_que_aux (locals_' x !j) ch = a_que_aux (locals_' y !j) ch) \\<and>\n        (a_que_aux (locals_' y !j) ch\\<noteq> a_que_aux (locals_' x !j) ch \\<longrightarrow>\n         a_que_aux (locals_' y !j) ch = \n           {#msg (locals_' x !j)#} + a_que_aux (locals_' x !j) ch \\<and>         \n         r_que_aux (locals_' x !j) ch = r_que_aux (locals_' y !j) ch  \\<and>\n          size (channel_get_messages (the (chans (communication_' y) ch))) \\<le> \n           channel_size (get_channel conf ch) \\<and>\n         channel_get_messages (the (chans (communication_' y) ch)) = \n           channel_get_messages (the (chans (communication_' x) ch)) +   \n           {#msg (locals_' x !j)#} ) \n       )\"\n     using a1 eq_chan p_queuing eq_port p_q  a0'\n     unfolding Guarantee_mod_chan_def Let_def by fastforce   \n   note x = this[simplified a0' eq_port[THEN sym]]\n   then have ?thesis using  eq_chan p_queuing a5 a4[simplified a0' eq_port[THEN sym]]  a6 a0' eq_port \n     unfolding Rely_mod_chan_def Let_def\n     by blast                        \n  } note l1 = this\n  moreover {\n    assume eq_chan:\"(channel_get_messages (the (chans (communication_' x) ?ch_rel)) =\n       channel_get_messages (the (chans (communication_' y) ?ch_rel))) \\<or>\n             \\<not> (p_queuing conf (communication_' x) (pt (locals_' x !i)))\"   \n      {assume eq_chann:\"(channel_get_messages (the (chans (communication_' x) ?ch_rel)) =\n             channel_get_messages (the (chans (communication_' y) ?ch_rel)))\"\n        {assume eq_port:\"?ch_rel = ch\"\n         then have \"r_que_aux (locals_' y !j) ch = r_que_aux (locals_' x !j) ch \\<and>\n          a_que_aux (locals_' y !j) ch = a_que_aux (locals_' x !j) ch\" \n         using a1 eq_chan eq_chann a0'   unfolding Guarantee_mod_chan_def Let_def by auto         \n       then have ?thesis using a5 eq_chann eq_port   \n         unfolding Rely_mod_chan_def Let_def by fastforce          \n        }   \n        moreover{assume eq_port:\"?ch_rel \\<noteq> ch\"            \n           then have ?thesis using a5 eq_chann eq_port a0' unfolding Rely_mod_chan_def Let_def\n             by (metis a4) \n        }     \n        ultimately have \"?thesis\" by auto\n      }\n      moreover \n      {assume not_pque:\"\\<not> p_queuing conf (communication_' x) (pt (locals_' x !i))\"\n        {assume eq_port:\"?ch_rel = ch\"\n           then have \"r_que_aux (locals_' y !j) ch = r_que_aux (locals_' x !j) ch \\<and>\n            a_que_aux (locals_' y !j) ch = a_que_aux (locals_' x !j) ch\" \n             using a1 eq_chan not_pque a0' \n             unfolding Guarantee_mod_chan_def Let_def p_queuing_def by auto            \n         then have ?thesis using a5 eq_port not_pque a0' \n           unfolding Rely_mod_chan_def Let_def by fastforce           \n         }   \n         moreover{\n           assume eq_port:\"?ch_rel \\<noteq> ch\"            \n           then have ?thesis using a5 not_pque eq_port a0' \n             unfolding Rely_mod_chan_def Let_def by (metis a4) \n        }     \n        ultimately have \"?thesis\" by auto         \n     }\n     ultimately have ?thesis using eq_chan by auto\n  }ultimately show ?thesis by auto     \nqed  \n  \nlemma Guar_in_Rely_i4:\n\"i < n \\<Longrightarrow>\n x < n \\<Longrightarrow>\n x \\<noteq> i \\<Longrightarrow>\n a = Normal x1 \\<Longrightarrow>\n b = Normal y1 \\<Longrightarrow>\n \\<forall>j. j \\<noteq> x \\<longrightarrow> locals_' x1 ! j = locals_' y1 ! j \\<Longrightarrow> \n (\\<forall>ch. ch \\<noteq> ch1 \\<longrightarrow>\n      chans (communication_' x1) ch = chans (communication_' y1) ch) \\<Longrightarrow>\n ((\\<exists>ch. chans (communication_' x1) ch1 =  Some ch \\<and> chan_queuing ch) \\<longrightarrow>\n  (\\<exists>ch. chans (communication_' y1) ch1 =  Some ch \\<and> chan_queuing ch)) \\<Longrightarrow>\n (\\<forall>ch_id.\n     ((\\<exists>ch. chans (communication_' x1) ch_id =  Some ch \\<and> chan_queuing ch) \\<longrightarrow>\n      (\\<exists>ch. chans (communication_' y1) ch_id =  Some ch \\<and> chan_queuing ch)))\"\n  by metis\n \n  \nlemma Guar_Rely_Send_ReceiveQ1:\n\"i < n \\<Longrightarrow> \n x < n \\<Longrightarrow> x \\<noteq> i \\<Longrightarrow>\n procs conf = n \\<Longrightarrow>\n (a, b) \\<in> Guarantee_Send_Receive x  \\<Longrightarrow> a=b \\<Longrightarrow>\n (a, b) \\<in> Rely_Send_ReceiveQ i\"\n  unfolding Guarantee_Send_Receive_def Rely_Send_ReceiveQ_def by auto\n\nlemma Guar_Rely_Send_ReceiveQ2:\n\"i < n \\<Longrightarrow> \n x < n \\<Longrightarrow> x \\<noteq> i \\<Longrightarrow>\n procs conf = n \\<Longrightarrow>\n (a, b) \\<in> Guarantee_Send_Receive x  \\<Longrightarrow> a\\<noteq>b \\<Longrightarrow>\n (a, b) \\<in> Rely_Send_ReceiveQ i\" \n  proof-\n  assume a0:\"i<n\" and\n         a1:\"x<n\" and\n         a2:\"x\\<noteq>i\" and a2':\" procs conf = n\" and\n         a3:\"(a,b) \\<in> Guarantee_Send_Receive x\" and a4:\"a\\<noteq>b\"\n then obtain x1 y1 where\na3a:\"a = Normal x1\" and\n a3b:\"b = Normal y1\" and\n  a30:\"length (locals_' x1) = length (locals_' y1)\" and   \n  a3':\"evnt (locals_' x1 !x) = evnt (locals_' y1 !x) \\<and> \n       pt (locals_' x1 !x) =  pt (locals_' y1 !x) \\<and>\n       state_conf x1 = state_conf y1\" and\n  a3c: \"(\\<forall>j. (j\\<noteq>x) \\<longrightarrow> (locals_' x1)!j = (locals_' y1)!j)\"\n   unfolding Guarantee_Send_Receive_def by fastforce     \n  then have a3'':\"(x1,y1)\\<in> Guarantee_Send_Receive' x\"\n    using  a3 a4 unfolding Guarantee_Send_Receive_def by auto\n  note g1 = case_prodD[OF CollectD[OF a3''[simplified Guarantee_Send_Receive'_def Let_def]]]\n  then have\n  g1:\"(\\<forall>ch_id. ch_id\\<noteq>(port_channel conf (communication_' x1) (pt (locals_' x1 !x))) \\<longrightarrow>\n            chans (communication_' x1) ch_id = chans (communication_' y1) ch_id \\<and>\n            (a_que_aux (locals_' x1 !x) ch_id = a_que_aux (locals_' y1 !x) ch_id) \\<and> \n               (r_que_aux (locals_' x1 !x) ch_id = r_que_aux (locals_' y1 !x) ch_id))\" and     \n  g2:\" schedule (locals_' x1 !x) =  schedule (locals_' y1 !x) \\<and>      \n     (\\<forall>ch_id. (ch_id \\<noteq> (port_channel conf (communication_' x1) (pt (locals_' x1 !x))) \\<longrightarrow>\n               (a_que_aux (locals_' x1 !x) ch_id = a_que_aux (locals_' y1 !x) ch_id) \\<and> \n               (r_que_aux (locals_' x1 !x) ch_id = r_que_aux (locals_' y1 !x) ch_id))) \\<and>\n    ((a_que_aux (locals_' x1 !x) \\<noteq> a_que_aux (locals_' y1 !x) \\<or> \n     (r_que_aux (locals_' x1 !x) \\<noteq> r_que_aux (locals_' y1 !x))) \\<longrightarrow>\n      (mut (the (chans (communication_' x1) (port_channel conf (communication_' x1) (pt (locals_' x1 !x))))) = x + 1 \\<or>\n       mut (the (chans (communication_' y1) (port_channel conf (communication_' x1) (pt (locals_' x1 !x))))) = x + 1)\n    ) \\<and>\n    (chans (communication_' x1) (port_channel conf (communication_' x1) (pt (locals_' x1 !x)))\\<noteq> \n    chans (communication_' y1) (port_channel conf (communication_' x1) (pt (locals_' x1 !x))) \\<longrightarrow>\n      (mut (the (chans (communication_' x1) (port_channel conf (communication_' x1) (pt (locals_' x1 !x))))) = x + 1 \\<or> \n       mut (the (chans (communication_' y1) (port_channel conf (communication_' x1) (pt (locals_' x1 !x))))) = x + 1)) \\<and> \n   (mut (the (chans (communication_' x1) (port_channel conf (communication_' x1) (pt (locals_' x1 !x))))) \\<noteq>\n    mut (the (chans (communication_' y1) (port_channel conf (communication_' x1) (pt (locals_' x1 !x))))) \\<longrightarrow>\n      (mut (the (chans (communication_' x1) (port_channel conf (communication_' x1) (pt (locals_' x1 !x))))) = 0 \\<or> \n      mut (the (chans (communication_' y1) (port_channel conf (communication_' x1) (pt (locals_' x1 !x))))) = 0))\" \n    unfolding Guarantee_Send_Receive'_def Let_def\n    by auto \n     \n   have\"ports (communication_' x1) = ports (communication_' y1) \\<and>\n   ({ch. chans (communication_' x1) ch = None} = \n      {ch. chans (communication_' y1) ch = None}) \\<and>\n    ({ch. \\<exists>ch1. chans (communication_' x1) ch = Some ch1} = \n      {ch. \\<exists>ch1. chans (communication_' y1) ch = Some ch1})\"    \n    using  a3'' unfolding Guarantee_Send_Receive'_def Let_def\n    by clarify\n   moreover have eq_port_channel:\"(port_channel conf (communication_' x1) (pt (locals_' x1 !x))) =\n                         (port_channel conf (communication_' y1) (pt (locals_' x1 !x)))\"\n   using calculation by (simp add: port_channl_eq_ports)\n   moreover have \n    \"(\\<forall>ch_id.\n      ((\\<exists>ch. chans (communication_' x1) ch_id =  Some ch \\<and> chan_queuing ch) \\<longrightarrow>\n      (\\<exists>ch. chans (communication_' y1) ch_id =  Some ch \\<and> chan_queuing ch)))\"\n    using a3 a3' a3'' Guar_in_Rely_i4[OF a0 a1 a2 a3a a3b a3c] \n    unfolding Guarantee_Send_Receive'_def Let_def by auto\n  moreover have \"((mut (the (chans (communication_' x1) (port_channel conf (communication_' x1) (pt (locals_' x1 !i))))) = i + 1 \\<or> \n   mut (the (chans (communication_' y1) (port_channel conf (communication_' x1) (pt (locals_' x1 !i))))) = i + 1)  \\<longrightarrow>\n      chans (communication_' x1) (port_channel conf (communication_' x1) (pt (locals_' x1 !i))) =\n      chans (communication_' y1) (port_channel conf (communication_' x1) (pt (locals_' x1 !i))) \\<and>\n      (\\<forall>j. (a_que_aux (locals_' x1 !j) (port_channel conf (communication_' x1) (pt (locals_' x1 !i)))) =  \n                   (a_que_aux(locals_' y1 !j)) (port_channel conf (communication_' x1) (pt (locals_' x1 !i))) \\<and>\n                   (r_que_aux (locals_' x1 !j) (port_channel conf (communication_' x1) (pt (locals_'  x1 !i)))) =  \n                   (r_que_aux(locals_' y1 !j)) (port_channel conf (communication_' x1) (pt (locals_'  x1 !i))))                         \n           )\n   \" using g1 g2  Guar_in_Rely_i3[OF a2 a3c _ _ _, of \"(port_channel conf (communication_' x1) (pt (locals_' x1 ! i)))\"] \n    \n  proof-\n    have a0:\"a_que_aux (locals_' x1 ! x) (port_channel conf (communication_' x1) (pt (locals_' x1 ! i))) \\<noteq>\n    a_que_aux (locals_' y1 ! x) (port_channel conf (communication_' x1) (pt (locals_' x1 ! i))) \\<or>\n    r_que_aux (locals_' x1 ! x) (port_channel conf (communication_' x1) (pt (locals_' x1 ! i))) \\<noteq>\n    r_que_aux (locals_' y1 ! x) (port_channel conf (communication_' x1) (pt (locals_' x1 ! i))) \\<longrightarrow>\n    mut (the (chans (communication_' x1) (port_channel conf (communication_' x1) (pt (locals_' x1 ! i))))) = x + 1 \\<or>\n    mut (the (chans (communication_' y1) (port_channel conf (communication_' x1) (pt (locals_' x1 ! i))))) =\n    x + 1\" using  g2  by metis\n    have a1:\"chans (communication_' x1) (port_channel conf (communication_' x1) (pt (locals_' x1 ! i))) \\<noteq>\n    chans (communication_' y1) (port_channel conf (communication_' x1) (pt (locals_' x1 ! i))) \\<longrightarrow>\n    mut (the (chans (communication_' x1) (port_channel conf (communication_' x1) (pt (locals_' x1 ! i))))) = x + 1 \\<or>\n    mut (the (chans (communication_' y1) (port_channel conf (communication_' x1) (pt (locals_' x1 ! i))))) =\n    x + 1\" using  g1 g2 by metis\n    have a3:\" mut (the (chans (communication_' x1) (port_channel conf (communication_' x1) (pt (locals_' x1 ! i))))) \\<noteq>\n  mut (the (chans (communication_' y1) (port_channel conf (communication_' x1) (pt (locals_' x1 ! i))))) \\<longrightarrow>\n  mut (the (chans (communication_' x1) (port_channel conf (communication_' x1) (pt (locals_' x1 ! i))))) = 0 \\<or>\n  mut (the (chans (communication_' y1) (port_channel conf (communication_' x1) (pt (locals_' x1 ! i))))) = 0\"\n      using g1 g2 by metis\n    show ?thesis      \n      using Guar_in_Rely_i3[OF a2 a3c a0 a1 a3] by fastforce\n  qed     \n  moreover have \"(\\<forall>ch_id. \n      (\\<nexists>j. j<procs conf \\<and> ch_id = port_channel conf (communication_' x1) (pt (locals_' x1 !j))) \\<longrightarrow> \n      chans (communication_' x1) ch_id = chans (communication_' y1) ch_id)\"\n    using a3'' a1 a2'  unfolding Guarantee_Send_Receive'_def Let_def by blast              \n  moreover have \"(\\<forall>ch_id. \n      (\\<nexists>j. j<procs conf \\<and> ch_id = port_channel conf (communication_' x1) (pt (locals_' x1 !j))) \\<longrightarrow> \n      chans (communication_' x1) ch_id = chans (communication_' y1) ch_id \\<and> \n     (\\<forall>i.(a_que_aux (locals_' x1 !i) ch_id = a_que_aux (locals_' y1 !i) ch_id) \\<and> \n         (r_que_aux (locals_' x1 !i) ch_id = r_que_aux (locals_' y1 !i) ch_id) ))\"\n    using a1 a2' a3c g1 by force          \n  moreover have G:\"Guarantee_mod_chan x1  y1 x\" using a3'' \n    unfolding Guarantee_Send_Receive'_def Let_def\n    by clarsimp\n  then have \"Rely_mod_chan x1 y1 i\" using guar_in_rely_i5[OF a2 _  G _ _ _ _ a3c] g1 g2\n    by (simp add: a1 a2' calculation(1) eq_port_channel)    \n  moreover have \n    \"(mut (the (chans (communication_' x1) (port_channel conf (communication_' x1) (pt (locals_' x1 ! i))))) \\<noteq>\n         i + 1 \\<longrightarrow>\n     mut (the (chans (communication_' y1) (port_channel conf (communication_' x1) (pt (locals_' x1 ! i))))) \\<noteq>\n     i + 1)\"\n    using calculation by fastforce     \n  ultimately have \"(x1,y1)\\<in>Rely_Send_Receive i\"\n    unfolding Rely_Send_Receive_def Let_def by fastforce  \n  thus ?thesis using a2 a3a a3b a30 a3' a3c   unfolding Rely_Send_ReceiveQ_def\n   by auto\nqed\n\nlemma Guar_Rely_Send_ReceiveQ:\n\"i < n \\<Longrightarrow> \n x < n \\<Longrightarrow> x \\<noteq> i \\<Longrightarrow>\n procs conf = n \\<Longrightarrow>\n (a, b) \\<in> Guarantee_Send_Receive x  \\<Longrightarrow> \n (a, b) \\<in> Rely_Send_ReceiveQ i\"\n  using Guar_Rely_Send_ReceiveQ1 Guar_Rely_Send_ReceiveQ2 by fastforce\n\ndefinition Rely_System\nwhere \n\"Rely_System \\<equiv> {(x,y). (\\<exists>x1 y1. x=Normal x1 \\<and> y=Normal y1 \\<and> \n                     locals_' x1 = locals_' y1 \\<and> \n                     communication_' x1 = communication_' y1)}\n\"\n\n\nsection {* Property Definitions *}\n\n  \ndefinition Invariant \nwhere\n\"Invariant B adds rems i \\<equiv>                                         \n  {s. state_conf s}   \\<inter> {s. channel_spec B adds rems (port_channel conf (communication_' s) (pt (locals_' s !i))) s}\n\"  \n\ndefinition Invariant_mut\nwhere\n\"Invariant_mut B adds rems i \\<equiv>                                         \n  {s. state_conf s}   \\<inter> {s. channel_spec_mut B adds rems (port_channel conf (communication_' s) (pt (locals_' s !i))) s}\n\"  \n\nlemma procs_len_locals:\"i< procs conf \\<Longrightarrow>    \n      x\\<in> Invariant B adds rems i \\<Longrightarrow>\n     i< length (locals_' x)\"\n  unfolding Invariant_def state_conf_def by auto\n \nlemma Invariant_eq:  \n    \"chans (communication_' x1) =chans(communication_' y1) \\<Longrightarrow>\n     ports (communication_' x1) = ports(communication_' y1) \\<Longrightarrow>\n     (x1,y1,i) \\<in> preserves_locals_constr  \\<Longrightarrow>\n     a_que_aux ((locals_' x1)!i)  = a_que_aux ((locals_' y1)!i)  \\<Longrightarrow>\n     r_que_aux ((locals_' x1)!i)  = r_que_aux ((locals_' y1)!i) \\<Longrightarrow>\n     x1\\<in> Invariant B adds rems i \\<Longrightarrow>\n     y1\\<in> Invariant B adds rems i\"\n  unfolding Invariant_def \n     apply (frule port_channl_eq_ports[of _ _ i])  \n   unfolding   state_conf_def port_exists_def                                     \n   by (simp add: preserves_locals_D1 channel_spec_eq preserves_locals_D3 \n          add_channel_message_not_evnt)+         \n        \n    \ndefinition pre_i \nwhere\n\"pre_i B adds rems i  \\<equiv>\n  Invariant B adds rems i\"\n                      \ndefinition pre_send \nwhere\n\"pre_send B adds rems i \\<equiv> pre_i B adds rems i  \\<inter> \\<lbrace>evnt (\\<acute>locals!i) = Send_Message_Q \\<rbrace>\"\n(* remove for Case-Study\ndefinition pre_receive\nwhere\n\"pre_receive B i \\<equiv> pre_i B i \\<inter> \\<lbrace>evnt (\\<acute>locals!i) = Receive_Message_Q \\<rbrace>\"\n\n*) \n\ndefinition chans_spec\nwhere\n\"chans_spec B adds rems \\<equiv>\n  {s.  \\<forall>ch_id. \n     channel_spec B adds rems ch_id s }\n\"\n\n\ndefinition Post_Send\nwhere\n\"Post_Send B adds rems i \\<equiv> Invariant B adds rems i \\<inter> \n                 \\<lbrace>(ret_n ((\\<acute>locals)!i)) = 1 \\<and>                        \n                      {# (msg ((\\<acute>locals)!i)) #} \\<subseteq># \n                  a_que_aux (\\<acute>locals!i) (port_channel conf \\<acute>communication (pt (\\<acute>locals !i))) \\<rbrace>\n\"\n\ndefinition Post_Receive\nwhere\n\"Post_Receive B adds rems i \\<equiv> \n  {s. s\\<in>Invariant B adds rems i}  \\<inter> \n  \\<lbrace>(ret_n ((\\<acute>locals)!i)) = 1 \\<longrightarrow>                      \n    (port_open (\\<acute>communication)  ((pt ((\\<acute>locals)!i)))) \\<and> \n    the (ret_msg ((\\<acute>locals)!i)) \\<in># \n     (B (port_channel conf \\<acute>communication (pt ((\\<acute>locals)!i))) +                 \n        channel_sent_messages (port_channel conf \\<acute>communication (pt ((\\<acute>locals)!i))) adds \\<acute>locals) \n  \\<rbrace>\n\"\n\ndefinition Post_Arinc_i\nwhere                \n\"Post_Arinc_i B adds rems i \\<equiv> Invariant B adds rems i\n\"\n\ndefinition Post_Arinc_i_mut\nwhere                \n\"Post_Arinc_i_mut B adds rems i \\<equiv> Invariant_mut B adds rems i\n\"\n \ndefinition Post_Arinc\nwhere                \n\"Post_Arinc B adds rems i \\<equiv> Invariant B adds rems i\n\"\n\ndefinition Inv_QueCom_ch\nwhere\n\"Inv_QueCom_ch B adds rems ch_id  \\<equiv> \n    {s. state_conf s   \\<and> channel_spec B adds rems ch_id s}\"  \n\ndefinition Pre_QueCom_ch\n  where\n    \"Pre_QueCom_ch B adds rems ch_id  \\<equiv>   \n   {s. state_conf s} \\<inter> {s. (\\<nexists>j. j<procs conf \\<and> ch_id = port_channel conf (communication_' s) (pt (locals_' s !j))) \\<longrightarrow>\n       s\\<in>Inv_QueCom_ch B adds rems ch_id }\"\n    \ndefinition Inv_QueCom\nwhere\n\"Inv_QueCom B adds rems  \\<equiv> {s. state_conf s}   \\<inter> {s. \\<forall>ch_id. channel_spec B adds rems ch_id s} \" \n\ndefinition Inv_QueCom_ch_mut\nwhere\n\"Inv_QueCom_ch_mut B adds rems ch_id  \\<equiv> \n    {s. state_conf s   \\<and> channel_spec_mut B adds rems ch_id s}\"  \n\ndefinition Pre_QueCom_ch_mut\n  where\n    \"Pre_QueCom_ch_mut B adds rems ch_id  \\<equiv>   \n   {s. state_conf s} \\<inter> {s. (\\<nexists>j. j<procs conf \\<and> ch_id = port_channel conf (communication_' s) (pt (locals_' s !j))) \\<longrightarrow>\n       s\\<in>Inv_QueCom_ch_mut B adds rems ch_id }\"\n    \ndefinition Inv_QueCom_mut\nwhere\n\"Inv_QueCom_mut B adds rems  \\<equiv> {s. state_conf s}   \\<inter> {s. \\<forall>ch_id. channel_spec_mut B adds rems ch_id s}\" \n\nsubsection {* lemmas on stability and reflexivity of Rely\\_Send*}\n\nlemma eq_locals:\n \"length (locals_' x) = length (locals_' y) \\<Longrightarrow>\n  \\<forall>i<length (locals_' x). msgc (locals_' x !i) ch_id = msgc (locals_' y !i) ch_id \\<Longrightarrow>\n  channel_messages  ch_id msgc (locals_' x)  =\n  channel_messages  ch_id msgc  (locals_' y) \"  \n  by (metis same_channel_messages)\n      \nlemma rely_state_conf:\n  assumes a1:\"(Normal x', Normal y') \\<in> Rely_Send_ReceiveQ i\" and\n          a2:\"state_conf x'\" \n        shows\"state_conf y'\"\n  using  a1 a2 unfolding state_conf_def Rely_Send_ReceiveQ_def  by auto\n    \nlemma sta_invariant_rely_send:       \n \"i<procs conf \\<Longrightarrow> Sta (Invariant B adds rems i) (Rely_Send_ReceiveQ i)\"\nunfolding Invariant_def Sta_def \nproof clarify  \n  fix y x'    \n  let ?ch_id = \"port_channel conf (communication_' (x'::'a vars_scheme)) (pt (locals_' x' ! i))\"\n  assume a0':\"i< procs conf\" and a0: \"state_conf x'\" and         \n         a2:\"channel_spec B adds rems  ?ch_id x'\" and\n         a3:\"(Normal x', (y::('a vars_scheme, 'b) xstate)) \\<in> Rely_Send_ReceiveQ i\"   \n  then obtain y' where y:\"y=Normal y'\" \n    unfolding Rely_Send_ReceiveQ_def by auto \n  have i_len:\"i<length (locals_' x')\" \n    using a0 a0' a2 procs_len_locals unfolding state_conf_def by fastforce   \n  have procs_len:\"procs conf = length (locals_' x')\"\n        using a0 a0' a2 procs_len_locals unfolding state_conf_def by fastforce\n  have len:\"length (locals_' x') = length (locals_' y')\" \n    using y a3 unfolding Rely_Send_ReceiveQ_def by auto\n  have pt:\"pt ((locals_' x')!i) = pt ((locals_' y')!i)\"\n    using y a3 unfolding Rely_Send_ReceiveQ_def by auto\n  have eq_port:\"?ch_id  = port_channel conf (communication_' y') (pt (locals_' x' ! i))\"\n    using a3 y port_channl_eq_ports unfolding Rely_Send_ReceiveQ_def Rely_Send_Receive_def Let_def\n    by auto             \n  have \"channel_spec B adds rems (port_channel conf (communication_' y') (pt (locals_' y' ! i))) y'\"\n  proof-\n    { \n    fix ch'\n    assume ass01: \"chans (communication_' y') (port_channel conf (communication_' y') (pt (locals_' y' ! i))) = Some ch' \\<and>\n            ch_id_queuing conf (port_channel conf (communication_' y') (pt (locals_' y' ! i)))\"\n    then obtain ch where\n    assx:\"chans (communication_' x') ?ch_id = Some ch \\<and>\n               ch_id_queuing conf ?ch_id\"\n      using ch_id_queuing[OF a0 ass01[simplified pt[THEN sym] eq_port[THEN sym]]] by auto\n     then have p_q:\"p_queuing conf (communication_' x') (pt (locals_' x' ! i))\"\n       unfolding p_queuing_def by auto  \n     then have spec_x1:\"channel_get_messages ch = B ?ch_id +\n       channel_sent_messages ?ch_id adds (locals_' x') -\n       channel_received_messages ?ch_id rems (locals_' x')\" and\n       spec_x2:\"channel_received_messages ?ch_id rems (locals_' x') \\<subseteq># B ?ch_id +\n          channel_sent_messages ?ch_id adds (locals_' x')\" and\n       spec_x3:\"(size (channel_get_messages ch) \\<le> channel_size (get_channel conf ?ch_id))\" and\n       spec_x4: \"channel_messages ?ch_id rems [0..<length (locals_' x')] \\<subseteq># \n                   channel_messages  ?ch_id r_que_aux (locals_' x')\" and\n        spec_x5: \"channel_messages ?ch_id adds [0..<length (locals_' x')] \\<subseteq># \n                   channel_messages  ?ch_id a_que_aux (locals_' x')\"\n       using assx a2 ass01  unfolding channel_spec_def ch_spec_def by auto\n     then have ?thesis unfolding channel_spec_def ch_spec_def using\n        Rely_chan_spec    y assx pt  a3 p_q procs_len Rely_chan_eq\n       by (metis (no_types) option.sel)           \n   \n   } thus ?thesis using channel_spec_intro by blast\n qed  \n  then show \"\\<exists>y'. y = Normal y' \\<and>\n            y' \\<in> Collect state_conf  \\<inter>\n            {s. channel_spec B adds rems (port_channel conf (communication_' s) (pt (locals_' s ! i))) s} \" \n    using a0 a3 y rely_state_conf by blast\nqed\n\n\n lemma pre_state_com:\n   \"\\<forall>ch_id. ch_id\\<noteq> ch \\<longrightarrow>\n      chans (communication_' s) ch_id  = chans (communication_' s') ch_id  \\<Longrightarrow> \n    (chans (communication_' s) ch \\<noteq> chans (communication_' s') ch) \\<longrightarrow>\n     (\\<forall>chs. chans (communication_' s) ch = Some chs \\<longrightarrow>\n       (\\<exists>chs'. chans (communication_' s') ch = Some chs' \\<and> chan_queuing chs = chan_queuing chs')) \\<Longrightarrow>\n    ports (communication_' s) = ports (communication_' s')  \\<Longrightarrow>\n   length (locals_' s) =  length (locals_' s') \\<Longrightarrow>   \n    state_conf s \\<Longrightarrow>\n    state_conf  s'\"    \n  unfolding  state_conf_def port_exists_def\n  apply auto\n     apply metis\n    apply(case_tac \"(channel_id cha) = ch\")\n    by auto\n    \n    \nlemma pre_quecom_ch:\n  assumes \n  a0:\"i< procs conf\" and\n  a1:\"ch = port_channel conf (communication_' s) (pt(locals_' s!i))\" and\n  a2:\"\\<forall>ch_id. ch_id\\<noteq> ch \\<longrightarrow>\n      chans (communication_' s) ch_id  = chans (communication_' s') ch_id\" and\n  a3:\"(chans (communication_' s) ch \\<noteq> chans (communication_' s') ch) \\<longrightarrow>\n     (\\<forall>chs. chans (communication_' s) ch = Some chs \\<longrightarrow>\n       (\\<exists>chs'. chans (communication_' s') ch = Some chs' \\<and> chan_queuing chs = chan_queuing chs'))\" and\n  a4:\"ports (communication_' s) = ports (communication_' s') \" and\n  a5:\"length (locals_' s) =  length (locals_' s')\" and\n  a6:\"\\<forall>i. pt (locals_' s ! i) = pt (locals_' s' ! i)\" and\n  a7:\"(\\<forall>i.(a_que_aux (locals_' s !i) ch_id = a_que_aux (locals_' s' !i) ch_id) \\<and> \n       (r_que_aux (locals_' s !i) ch_id = r_que_aux (locals_' s' !i) ch_id) )\" and\n  a8:\"s\\<in>Pre_QueCom_ch B adds rems ch_id\"\n  shows\"s'\\<in>Pre_QueCom_ch B adds rems ch_id\"    \nproof-\n  have \"state_conf s'\" \n    using a8 pre_state_com[OF a2 a3 a4 a5] unfolding Pre_QueCom_ch_def by auto\n  moreover \n  {assume \n     b0:\"(\\<nexists>j. j<procs conf \\<and> ch_id = port_channel  conf (communication_' s') (pt (locals_' s' !j)))\"     \n    then have \"s\\<in>Inv_QueCom_ch B adds rems ch_id\" \n      using port_channl_eq_ports[OF a4] a8 a6 unfolding Pre_QueCom_ch_def\n      by auto\n    then have \"s'\\<in>Inv_QueCom_ch B adds rems ch_id\"       \n      using port_channl_eq_ports[OF a4]\n      unfolding Inv_QueCom_ch_def   \n      by (metis (lifting)  a0 a1 a2 a5 a6 a7 b0 calculation ch_spec_def channel_received_messages_def \n         channel_sent_messages_def channel_spec_dest2\n        channel_spec_intro mem_Collect_eq same_message_channel) \n  }  \n  ultimately show ?thesis unfolding Pre_QueCom_ch_def by fastforce\n qed\n   \nlemma pre_quecom_ch':\n  assumes \n  a0:\"i< procs conf\" and\n  a1:\"ch = port_channel conf (communication_' s) (pt(locals_' s!i))\" and\n  a2:\"\\<forall>ch_id. ch_id\\<noteq> ch \\<longrightarrow>\n      chans (communication_' s) ch_id  = chans (communication_' s') ch_id\" and\n  a3:\"(chans (communication_' s) ch \\<noteq> chans (communication_' s') ch) \\<longrightarrow>\n     (\\<forall>chs. chans (communication_' s) ch = Some chs \\<longrightarrow>\n       (\\<exists>chs'. chans (communication_' s') ch = Some chs' \\<and> chan_queuing chs = chan_queuing chs'))\" and\n  a4:\"ports (communication_' s) = ports (communication_' s') \" and\n  a5:\"length (locals_' s) =  length (locals_' s')\" and\n  a6:\"\\<forall>i. pt (locals_' s ! i) = pt (locals_' s' ! i)\" and\n  a7:\"(\\<forall>j. j\\<noteq>i \\<longrightarrow> (a_que_aux (locals_' s !j)  = a_que_aux (locals_' s' !j)) \\<and> \n                    (r_que_aux (locals_' s !j)  = r_que_aux (locals_' s' !j) ) )\" and   \n  a7':\"(\\<forall>j. j\\<noteq> ch \\<longrightarrow> \n            a_que_aux ((locals_' s)!i) j = a_que_aux ((locals_' s')!i) j \\<and>\n            r_que_aux ((locals_' s)!i) j = r_que_aux ((locals_' s')!i) j)\" and\n  a8:\"s\\<in>Pre_QueCom_ch B adds rems ch_id\"\n  shows\"s'\\<in>Pre_QueCom_ch B adds rems ch_id\"    \nproof-\n  have state:\"state_conf s'\" \n    using a8 pre_state_com[OF a2 a3 a4 a5] unfolding Pre_QueCom_ch_def by auto\n  moreover \n  {assume \n     b0:\"(\\<nexists>j. j<procs conf \\<and> ch_id = port_channel conf (communication_' s') (pt (locals_' s' !j)))\"\n    then have b0':\"\\<forall>j. j\\<ge>procs conf \\<or> ch_id\\<noteq>port_channel conf (communication_' s') (pt (locals_' s' !j))\"\n      using leI by auto \n        then have a7:\"\\<forall>i. (a_que_aux (locals_' s' !i) ch_id = a_que_aux (locals_' s !i) ch_id) \\<and>\n                         (r_que_aux (locals_' s' !i) ch_id = r_que_aux (locals_' s !i) ch_id)\"\n          using a7 a7' a6 port_channl_eq_ports[OF a4] a1 by (metis a0 b0) \n        then have \"s\\<in>Inv_QueCom_ch B adds rems ch_id\" using a8 a6 b0 port_channl_eq_ports[OF a4]\n          unfolding Pre_QueCom_ch_def\n          by auto                 \n        then have \"s'\\<in>Inv_QueCom_ch B adds rems ch_id\"       \n          unfolding Inv_QueCom_ch_def using port_channl_eq_ports[OF a4]\n        by (metis (lifting)  a0 a1 a2 a5 a6 a7  b0 state ch_spec_def channel_received_messages_def \n           channel_sent_messages_def channel_spec_dest2 \n          channel_spec_intro mem_Collect_eq same_message_channel)\n   } ultimately show ?thesis unfolding Pre_QueCom_ch_def by auto\n qed   \n   \nlemma sta_no_channel_rely_send:\n  \" i < procs conf \\<Longrightarrow>\n    Sta (Pre_QueCom_ch B adds rems ch_id) (Rely_Send_ReceiveQ i)\"  \n  unfolding Sta_def \nproof clarsimp   \n   fix x'::\"'a vars_scheme\" and y::\"('a vars_scheme, 'b) xstate\"\n   assume a0:\"i < Sys_Config.procs conf\" and\n           a1:\"x' \\<in> Pre_QueCom_ch B adds rems ch_id\" and\n           a2:\"(Normal x', y) \\<in> Rely_Send_ReceiveQ i\"\n   then obtain y' where y:\"y = Normal y'\" unfolding Rely_Send_ReceiveQ_def by auto\n   then have eq_ports: \"ports (communication_' x') = ports (communication_' y')\" \n    using a2 unfolding Rely_Send_ReceiveQ_def Rely_Send_Receive_def Let_def by auto\n   have state_conf_y:\"state_conf y'\" \n   proof-{\n       show ?thesis using a2 a1 y unfolding Pre_QueCom_ch_def \n           by (fastforce simp: rely_state_conf)\n   } qed\n   moreover{\n     assume a3:\"(\\<nexists>j. j<procs conf \\<and> ch_id = port_channel conf (communication_' y') (pt (locals_' y' !j)))\"  \n     then have \"(\\<nexists>j. j<procs conf \\<and> ch_id = port_channel conf (communication_' x') (pt (locals_' x' !j)))\" \n       using y a2 port_channl_eq_ports[OF eq_ports] \n       unfolding Rely_Send_ReceiveQ_def\n       by auto\n     then have eq_vars:\"\n      chans (communication_' x') ch_id = chans (communication_' y') ch_id \\<and>\n       (\\<forall>i.(a_que_aux (locals_' x' !i) ch_id = a_que_aux (locals_' y' !i) ch_id) \\<and> \n           (r_que_aux (locals_' x' !i) ch_id = r_que_aux (locals_' y' !i) ch_id) )\"\n       using a2 y port_channl_eq_ports[OF eq_ports] \n       unfolding Rely_Send_ReceiveQ_def Rely_Send_Receive_def Let_def by blast    \n     moreover have x_inv:\"x'\\<in> Inv_QueCom_ch B adds rems ch_id\" \n       using a1 a2 y a3 port_channl_eq_ports[OF eq_ports]  \n       unfolding Pre_QueCom_ch_def Rely_Send_ReceiveQ_def by auto\n     moreover have \"length (locals_' y') = length (locals_' x')\"\n       using  a1 state_conf_y \n       unfolding  Pre_QueCom_ch_def state_conf_def by auto\n     ultimately have \"y'\\<in>Inv_QueCom_ch B adds rems ch_id\"        \n       using  same_message_channel unfolding Inv_QueCom_ch_def\n          by (metis (no_types, lifting) a2 ch_spec_def \n                    channel_received_messages_def channel_sent_messages_def \n                    channel_spec_def eq_vars mem_Collect_eq rely_state_conf y)\n   }\n   ultimately show \"\\<exists>y'. y = Normal y' \\<and> y' \\<in> Pre_QueCom_ch B adds rems ch_id\" \n     unfolding Pre_QueCom_ch_def\n     using y by auto \n qed\n   \n definition post_1_i\nwhere                \n\"post_1_i B adds rems \\<equiv> \n    \\<lbrace>\\<forall>ch_id. \n      (\\<nexists>j. j<procs conf \\<and> ch_id = port_channel conf \\<acute>communication (pt (\\<acute>locals !j))) \\<longrightarrow> \n      chans (\\<acute>communication) ch_id = B ch_id \\<and> \n     (\\<forall>i.(a_que_aux (\\<acute>locals !i) ch_id = adds i ch_id) \\<and> \n         (r_que_aux (\\<acute>locals !i) ch_id = rems i ch_id) )\\<rbrace>\"    \n\ndefinition post_1_i_s\nwhere                \n\"post_1_i_s s B adds rems \\<equiv> \n    \\<forall>ch_id. \n      (\\<nexists>j. j<procs conf \\<and> ch_id = port_channel conf (communication_' s) (pt (locals_' s !j))) \\<longrightarrow> \n      chans (communication_' s) ch_id = B ch_id \\<and> \n     (\\<forall>i.(a_que_aux (locals_' s !i) ch_id = adds i ch_id) \\<and> \n         (r_que_aux (locals_' s !i) ch_id = rems i ch_id))\"\n\n\n subsection {* Stability *} \nlemma sta_uni:\"LocalRG_HoareDef.Sta UNIV (Rely_Send_ReceiveQ i)\"\n  unfolding Sta_def Rely_Send_ReceiveQ_def Rely_Send_Receive_def by blast\n    \nlemma stable_state_conf:\"i < Sys_Config.procs conf \\<Longrightarrow>      \n      LocalRG_HoareDef.Sta {s. state_conf s}  (Rely_Send_ReceiveQ i)\"\n  unfolding state_conf_def Rely_Send_ReceiveQ_def Sta_def\n  by fastforce\n  \nlemma stable_post:\"i < Sys_Config.procs conf \\<Longrightarrow>      \n      LocalRG_HoareDef.Sta {s. post_1_i_s s B adds rems}  (Rely_Send_ReceiveQ i)\"  \n  unfolding post_1_i_s_def Rely_Send_ReceiveQ_def Rely_Send_Receive_def Sta_def Let_def\n    port_channel_def port_in_channel_def port_name_in_channel_def port_id_name_def port_exists_def\n    by fastforce\n      \nlemma stable_state:\"i < Sys_Config.procs conf \\<Longrightarrow>      \n      LocalRG_HoareDef.Sta ({s. state_conf s} \\<inter> {s. post_1_i_s s B adds rems}) \n  (Rely_Send_ReceiveQ i)\"\n  using stable_state_conf stable_post by (fastforce intro:Sta_intro)\n \n    lemma sta_event:\"LocalRG_HoareDef.Sta (\\<lbrace>evnt (\\<acute>locals ! i) = x\\<rbrace>) (Rely_Send_ReceiveQ i)\"\n  unfolding Rely_Send_ReceiveQ_def Rely_Send_Receive_def Sta_def\n  by fastforce\n    \nlemma sta_event_inv:\n  \"i < Sys_Config.procs conf \\<Longrightarrow>\n    LocalRG_HoareDef.Sta (Invariant B adds rems i \\<inter> \\<lbrace>evnt (\\<acute>locals ! i) = x\\<rbrace>) (Rely_Send_ReceiveQ i) \"   \n  using sta_event sta_invariant_rely_send by (fastforce intro:Sta_intro)  \n    \nlemma sta_event_inv_PreQue:\n  \"i < Sys_Config.procs conf \\<Longrightarrow>\n    LocalRG_HoareDef.Sta (Pre_QueCom_ch B adds rems ch_id \\<inter> \\<lbrace>evnt (\\<acute>locals ! i) = x\\<rbrace>) (Rely_Send_ReceiveQ i) \"   \n  using sta_event sta_no_channel_rely_send by (fastforce intro:Sta_intro)\n  \nlemma sta_not_event:\"LocalRG_HoareDef.Sta (-\\<lbrace>evnt (\\<acute>locals ! i) = x\\<rbrace>) (Rely_Send_ReceiveQ i)\"\n  unfolding Rely_Send_ReceiveQ_def Rely_Send_Receive_def Sta_def\n  by fastforce        \n    \nlemma sta_not_event_inv:\n  \"i < Sys_Config.procs conf \\<Longrightarrow>\n    LocalRG_HoareDef.Sta (Invariant B adds rems i \\<inter> -\\<lbrace>evnt (\\<acute>locals ! i) = x\\<rbrace>) (Rely_Send_ReceiveQ i) \"   \n   using sta_not_event sta_invariant_rely_send by (fastforce intro:Sta_intro)\n    \nend\n  \n", "meta": {"author": "CompSoftVer", "repo": "CSim2", "sha": "b09a4d77ea089168b1805db5204ac151df2b9eff", "save_path": "github-repos/isabelle/CompSoftVer-CSim2", "path": "github-repos/isabelle/CompSoftVer-CSim2/CSim2-b09a4d77ea089168b1805db5204ac151df2b9eff/Conc_Refinement/RefArinc/Communication/Spec/ArincQueuing.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8774767938900121, "lm_q2_score": 0.8031738010682209, "lm_q1q2_score": 0.7047663718977969}}
{"text": "theory Mod_Plus_Minus\n\nimports Kyber_spec\n\nbegin\nsection \\<open>Re-centered Modulo Operation\\<close>\ntext \\<open>To define the compress and decompress functions, \n  we need some special form of modulo. It returns the \n  representation of the equivalence class in \\<open>(-q div 2, q div 2]\\<close>.\n  Using these representatives, we ensure that the norm of the \n  representative is as small as possible.\\<close>\n\ndefinition mod_plus_minus :: \"int \\<Rightarrow> int \\<Rightarrow> int\" \n  (infixl \"mod+-\" 70) where\n\"m mod+- b = \n  ((m + \\<lfloor> real_of_int b / 2 \\<rfloor>) mod b) - \\<lfloor> real_of_int b / 2 \\<rfloor>\"\n \nlemma mod_range: \"b>0 \\<Longrightarrow> (a::int) mod (b::int) \\<in> {0..b-1}\"\nusing range_mod by auto\n\nlemma mod_rangeE: \n  assumes \"(a::int)\\<in>{0..<b}\"\n  shows \"a = a mod b\"\nusing assms by auto\n\nlemma mod_plus_minus_range: \n  assumes \"b>0\"\n  shows \"y mod+- b \\<in> {-\\<lfloor>b/2\\<rfloor>..\\<lfloor>b/2\\<rfloor>}\"\nunfolding mod_plus_minus_def \nusing mod_range[OF assms, of \"(y + \\<lfloor>real_of_int b / 2\\<rfloor>)\"]\nby (auto)(linarith)\n\nlemma odd_smaller_b:\n  assumes \"odd b\" \n  shows \"\\<lfloor> real_of_int b / 2 \\<rfloor> + \\<lfloor> real_of_int b / 2 \\<rfloor> < b\"\nusing assms \nby (smt (z3) floor_divide_of_int_eq odd_two_times_div_two_succ \n  of_int_hom.hom_add of_int_hom.hom_one)\n\nlemma mod_plus_minus_rangeE:\n  assumes \"y \\<in> {-\\<lfloor>real_of_int b/2\\<rfloor>..<\\<lfloor>real_of_int b/2\\<rfloor>}\"\n          \"odd b\"\n  shows \"y = y mod+- b\"\nproof -\n  have \"(y + \\<lfloor> real_of_int b / 2 \\<rfloor>) \\<in> {0..<b}\" \n    using assms(1) odd_smaller_b[OF assms(2)] by auto\n  then have \"(y + \\<lfloor> real_of_int b / 2 \\<rfloor>) mod b = \n    (y + \\<lfloor> real_of_int b / 2 \\<rfloor>)\" \n    using mod_rangeE by auto\n  then show ?thesis unfolding mod_plus_minus_def by auto\nqed\n\nlemma mod_plus_minus_rangeE':\n  assumes \"y \\<in> {-\\<lfloor>real_of_int b/2\\<rfloor>..\\<lfloor>real_of_int b/2\\<rfloor>}\"\n          \"odd b\"\n  shows \"y = y mod+- b\"\nproof -\n  have \"(y + \\<lfloor> real_of_int b / 2 \\<rfloor>) \\<in> {0..<b}\" \n    using assms(1) odd_smaller_b[OF assms(2)] by auto\n  then have \"(y + \\<lfloor> real_of_int b / 2 \\<rfloor>) mod b = \n    (y + \\<lfloor> real_of_int b / 2 \\<rfloor>)\" \n    using mod_rangeE by auto\n  then show ?thesis unfolding mod_plus_minus_def by auto\nqed\n\nlemma mod_plus_minus_zero:\n  assumes \"x mod+- b = 0\"\n  shows \"x mod b = 0\"\nusing assms unfolding mod_plus_minus_def\nby (metis add.commute add.right_neutral bits_mod_0 \n  diff_add_cancel group_cancel.add1 mod_add_left_eq)\n\nlemma mod_plus_minus_zero':\n  assumes \"b>0\" \"odd b\"\n  shows \"0 mod+- b = (0::int)\"\nusing mod_plus_minus_rangeE[of 0] \nby (smt (verit, best) assms(1) assms(2) atLeastAtMost_iff \n  atLeastLessThan_iff mod_plus_minus_range)\n\n\nlemma neg_mod_plus_minus:\n  assumes \"odd b\"\n          \"b>0\"\n  shows \"(- x) mod+- b = - (x mod+- b)\"\nproof -\n  obtain k :: int where k_def: \"(-x) mod+- b = (-x)+ k* b\" \n  using mod_plus_minus_def\n  proof -\n    assume a1: \"\\<And>k. - x mod+- b = - x + k * b \\<Longrightarrow> thesis\"\n    have \"\\<exists>i. i mod b + - (x + i) = - x mod+- b\"\n      by (metis (no_types) add.commute diff_add_cancel diff_minus_eq_add \n        floor_divide_of_int_eq mod_plus_minus_def of_int_numeral)\n    then show ?thesis\n      using a1 by (metis (no_types) diff_add_cancel diff_diff_add \n      diff_minus_eq_add minus_diff_eq minus_mult_div_eq_mod \n      mult.commute mult_minus_left)\n  qed\n  then have \"(-x) mod+- b = -(x - k*b)\" using k_def by auto\n  also have \"\\<dots> = - ((x-k*b) mod+- b)\"\n  proof -\n    have range_xkb:\"x - k * b \\<in> \n      {- \\<lfloor>real_of_int b / 2\\<rfloor>..\\<lfloor>real_of_int b / 2\\<rfloor>}\" \n      using k_def mod_plus_minus_range[OF assms(2)]\n      by (smt (verit, ccfv_SIG) atLeastAtMost_iff)\n    have \"x - k*b = (x - k*b) mod+- b\" \n      using mod_plus_minus_rangeE'[OF range_xkb assms(1)] by auto\n    then show ?thesis by auto\n  qed\n  also have \"-((x - k*b) mod+- b) = -(x mod+- b)\" \n    unfolding mod_plus_minus_def \n    by (smt (verit, best) mod_mult_self1)\n  finally show ?thesis by auto\nqed\n\n\nlemma mod_plus_minus_rep: \n  obtains k where \"x = k*b + x mod+- b\"\nunfolding mod_plus_minus_def \nby (metis add.commute add_diff_eq diff_eq_eq \n  minus_mult_div_eq_mod mult.commute)\n\nend", "meta": {"author": "ThikaXer", "repo": "Kyber_Formalization", "sha": "a1832e7b8e29852c35f252b5703083f912cfe5ff", "save_path": "github-repos/isabelle/ThikaXer-Kyber_Formalization", "path": "github-repos/isabelle/ThikaXer-Kyber_Formalization/Kyber_Formalization-a1832e7b8e29852c35f252b5703083f912cfe5ff/Mod_Plus_Minus.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8774767746654976, "lm_q2_score": 0.8031737892899221, "lm_q1q2_score": 0.7047663461219869}}
{"text": "theory AbiDecode imports AbiTypes Hex Ok\nbegin\n\n(* An decoder for the Solidity ABI.\n   It supports decoding from all byte-strings representing\n   valid Solidity-ABI encoded data\n   (not limited to canonical encodings) *)\n\n(* Functions for decoding basic data-types.*)\nfun decode_uint :: \"8 word list \\<Rightarrow> int\" where\n\"decode_uint l =\n  (Word.uint (Word.word_rcat (take 32 l) :: 256 word))\"\n\n\nfun decode_sint :: \"8 word list \\<Rightarrow> int\" where\n\"decode_sint l =\n  (Word.sint (Word.word_rcat (take 32 l) :: 256 word))\"\n\nfun decode_bool :: \"8 word list \\<Rightarrow> bool option\" where\n\"decode_bool l =\n  (let i = decode_uint l in\n   (if i = 0 then Some False\n              else if i = 1 then Some True\n              else None))\"\n\nfun decode_ufixed :: \"nat \\<Rightarrow> 8 word list \\<Rightarrow> rat\" where\n\"decode_ufixed n l =\n  (let i = decode_uint l in (Rat.of_int i / (10 ^ n)))\"\n\nfun decode_fixed :: \"nat \\<Rightarrow> 8 word list \\<Rightarrow> rat\" where\n\"decode_fixed n l =\n  (let i = decode_sint l in (Rat.of_int i / (10 ^ n)))\"\n\n(* bytes, fbytes, and strings will be padded to multiples of\n   32 bytes. skip_padding skips this padding. *)\nfun skip_padding :: \"nat \\<Rightarrow> nat\" where\n\"skip_padding n =\n  (case divmod_nat n 32 of\n    (_, 0) \\<Rightarrow> n\n    | (_, rem) \\<Rightarrow> n + 32 - rem)\"\n\n(* Ensure padding is zeroes.\n   This is necessary for static encoder and static\n   decoder to be inverses. *)\nfun check_padding :: \"nat \\<Rightarrow> 8 word list \\<Rightarrow> bool\" where\n\"check_padding n l =\n  (let p = skip_padding n in\n  ((p \\<le> length l) \\<and> (drop n (take p l) = replicate (p - n) (word_of_int 0))))\" \n\n\n(* Extract byte strings of known length *)\nfun decode_fbytes :: \"nat \\<Rightarrow> 8 word list \\<Rightarrow> 8 word list option\" where\n\"decode_fbytes n l =\n  (if check_padding n l then Some (take n l)\n   else None)\"\n\n\nfun decode_function_sel :: \"8 word list \\<Rightarrow> (int * int) option\" where\n\"decode_function_sel bs =\n  (if check_padding 24 bs then\n      Some (Word.uint (Word.word_rcat (take 20 bs) :: 160 word),\n            Word.uint (Word.word_rcat (take 4 (drop 20 bs)) :: 32 word))\n   else None)\"\n\nfun bytes_to_string :: \"8 word list \\<Rightarrow> char list\" where\n\"bytes_to_string bs =\n  List.map (\\<lambda> b . char_of_integer (integer_of_int (Word.uint b))) bs\"\n\n(* Lemma for decoder termination *)\nlemma abi_type_list_measure_replicate :\n  \"\\<And> t . abi_type_list_measure (replicate n t)\n           =  1 + n + (n * abi_type_measure t)\"\nproof(induction n)\n  case 0\n  then show ?case\n    by(simp)\nnext\n  case (Suc n)\n  then show ?case \n    by(simp)\nqed\n\n(* Construct decoder error messages *)\nfun decode_err :: \"char list \\<Rightarrow> (int * 8 word list) \\<Rightarrow> char list\"\n  where\n\"decode_err s (ix, l) =\n  s @ '' at byte '' @ decwrite (nat ix) @ '' of '' @ decwrite (length l) @ ''.''\"\n\n(* Decoder for static data *)\nfunction (sequential) decode_static :: \"abi_type \\<Rightarrow> (int * 8 word list) \\<Rightarrow> abi_value orerror\" \nand decode_static_tup :: \"abi_type list \\<Rightarrow> (int * 8 word list) \\<Rightarrow> abi_value list orerror\" where\n\"decode_static (Tuint n) (ix, l) =\n   (let l' = drop (nat ix) l in\n   (let res = decode_uint l' in\n    (if uint_value_valid n res then Ok (Vuint n res)\n     else Err (decode_err ''Invalid uint'' (ix, l)))))\"\n| \"decode_static (Tsint n) (ix, l) =\n   (let l' = drop (nat ix) l in\n   (let res = decode_sint l' in\n    (if sint_value_valid n res then Ok (Vsint n res)\n     else Err (decode_err ''Invalid sint'' (ix, l)))))\"\n| \"decode_static Taddr (ix, l) =\n  (let l' = drop (nat ix) l in\n   (let res = decode_uint l' in\n    (if addr_value_valid res then Ok (Vaddr res)\n     else Err (decode_err ''Invalid address'' (ix, l)))))\"\n| \"decode_static Tbool (ix, l) =\n  (let l' = drop (nat ix) l in\n   (case decode_bool l' of\n      None \\<Rightarrow> Err (decode_err ''Invalid bool'' (ix, l))\n      | Some b \\<Rightarrow> Ok (Vbool b)))\"\n| \"decode_static (Tfixed m n) (ix, l) =\n  (let l' = drop (nat ix) l in\n   (let res = decode_fixed n l' in\n    (if fixed_value_valid m n res then Ok (Vfixed m n res)\n     else Err (decode_err ''Invalid fixed'' (ix, l)))))\"\n| \"decode_static (Tufixed m n) (ix, l) =\n  (let l' = drop (nat ix) l in\n   (let res = decode_ufixed n l' in\n    (if ufixed_value_valid m n res then Ok (Vufixed m n res)\n     else Err (decode_err ''Invalid ufixed'' (ix, l)))))\"\n| \"decode_static (Tfbytes n) (ix, l) =\n  (let l' = drop (nat ix) l in\n   (case decode_fbytes n l' of\n      Some res \\<Rightarrow> (if fbytes_value_valid n res then Ok (Vfbytes n res)\n                    else Err (decode_err ''Invalid fbytes'' (ix, l)))\n      | None \\<Rightarrow> Err (decode_err ''invalid fbytes padding'' (ix, l))))\"\n\n| \"decode_static (Tfunction) (ix, l) =\n    (let l' = drop (nat ix) l in\n      (case decode_function_sel l' of\n        Some (i, j) \\<Rightarrow> (if function_value_valid i j then Ok (Vfunction i j)\n                        else Err (decode_err ''Invalid function'' (ix, l)))\n        | None \\<Rightarrow> Err (decode_err ''invalid function padding'' (ix, l))))\"\n    \n| \"decode_static (Tfarray t n) (ix, l) =\n  (case decode_static_tup (List.replicate n t) (ix, l) of\n    Err s \\<Rightarrow> Err s\n    | Ok vs \\<Rightarrow> \n        (if farray_value_valid_aux t n vs then Ok (Vfarray t n vs)\n         else Err (decode_err ''Invalid farray'' (ix, l))))\"\n| \"decode_static (Ttuple ts) (ix, l) = \n  (case decode_static_tup ts (ix, l) of\n    Err s \\<Rightarrow> Err s\n    | Ok vs \\<Rightarrow> \n      (if tuple_value_valid_aux ts vs then Ok (Vtuple ts vs)\n       else Err (decode_err ''Invalid tuple'' (ix, l))))\"\n| \"decode_static _ (ix, l) = Err (decode_err ''Ran static parser on dynamic array'' (ix, l))\"\n| \"decode_static_tup [] (ix, l) = Ok []\"\n| \"decode_static_tup (t#ts) (ix, l) =\n    (case decode_static t (ix, l) of\n      Err s \\<Rightarrow> Err s\n      | Ok v \\<Rightarrow> (case decode_static_tup ts \n                       (ix + (abi_static_size t), l) of\n          Err s \\<Rightarrow> Err s\n          | Ok vs \\<Rightarrow> Ok (v#vs)))\"\n  by pat_completeness auto\n\ntermination\nproof(relation \n\"measure (\\<lambda> x .\n    (case x of\n      Inl (t, l) \\<Rightarrow> 1 + abi_type_measure t\n      | Inr (ts, l) \\<Rightarrow> abi_type_list_measure ts))\"; (auto; fail)?)\n  show \"\\<And>t n ix l.\n       (Inr (replicate n t, ix, l), Inl (Tfarray t n, ix, l))\n       \\<in> measure (\\<lambda>x. case x of Inl (t, l) \\<Rightarrow> 1 + abi_type_measure t \n                              | Inr (ts, l) \\<Rightarrow> abi_type_list_measure ts)\"\n    by(auto simp add:abi_type_list_measure_replicate)\nnext\n  fix t ts\n  show \"\\<And> ix l.\n       (Inl (t, ix, l), Inr (t # ts, ix, l))\n       \\<in> measure (\\<lambda>x. case x of Inl (t, l) \\<Rightarrow> 1 + abi_type_measure t \n                              | Inr (ts, l) \\<Rightarrow> abi_type_list_measure ts)\"\n    by(cases ts; auto)\nqed\n\n(* Another measure for termination *)\nfun tails_measure :: \"(abi_value + (abi_type * nat)) list \\<Rightarrow> nat\" where\n\"tails_measure [] = 1\"\n| \"tails_measure ((Inl _)#ts) = 1 + tails_measure ts\"\n| \"tails_measure ((Inr (t, _))#ts) =\n    abi_type_measure t + tails_measure ts\"\n\nfun abi_size_lower_bound :: \"abi_type \\<Rightarrow> int\" where\n\"abi_size_lower_bound t =\n (if abi_type_isstatic t then abi_static_size t\n  else 32)\"\n\n(* Implementation of the core decoder\n   End-users should call decode instead (see below), which implements\n   top-level validity checks \n*)\nfunction (sequential) decode' :: \"abi_type \\<Rightarrow> (int * 8 word list) \\<Rightarrow> (abi_value * int) orerror\"\n\n(* first returned nat is the length of all the heads (used for computing offsets); \n   second returned nat is number of bytes consumed;\n   input nat is running count of head length. *)\nand decode'_dyn_tuple_heads :: \"abi_type list \\<Rightarrow> int \\<Rightarrow> (int * 8 word list) \\<Rightarrow> \n                (abi_value option list *  (int option) list * int * int) orerror\"\n(* list parameter gives an offset for each field that still needs to be parsed\n   the int parameter is an index of how many bytes into our overall tuple encoding we are *)\nand decode'_dyn_tuple_tails :: \"(int option) list \\<Rightarrow> abi_type list \\<Rightarrow> abi_value option list \\<Rightarrow> \n                                int \\<Rightarrow> (int * 8 word list) \\<Rightarrow> \n                (abi_value list * int) orerror\"\nwhere\n\"decode' t (ix, l) =\n(if ix < 0 then Err (decode_err ''Tried to decode at a negative index'' (ix, l))\n else (if (ix > length l) then Err (decode_err ''Tried to decode at an index out of range'' (ix, l))\n else\n (let l' = drop (nat ix) l in\n  \n  (if abi_type_isstatic t\n    then\n      if int (length l) < (abi_static_size t) + ix \n      then Err (decode_err ''Too few bytes for given static type'' (ix, l))\n      else (case decode_static t (ix, l) of\n            Err s \\<Rightarrow> Err s\n            | Ok v \\<Rightarrow> Ok (v, (abi_static_size t)))\n   else\n    (case t of\n      Tfarray t n \\<Rightarrow>\n        (let ts = List.replicate (nat n) t in\n        (case decode'_dyn_tuple_heads ts 0 (ix, l) of\n          Err s \\<Rightarrow> Err s\n          | Ok (vos, idxs, byteoffset, bytes_parsed) \\<Rightarrow>\n            (case decode'_dyn_tuple_tails idxs ts vos byteoffset (ix, l) of\n              Err s \\<Rightarrow> Err s\n              | Ok (vs, bytes_parsed') \\<Rightarrow> Ok (Vfarray t n vs, bytes_parsed + bytes_parsed'))))\n      | Tarray t \\<Rightarrow>\n       if int (length l) < 32 + ix \n       then Err (decode_err ''Too few bytes; could not read array size'' (ix, l))\n       else\n         (let n = (decode_uint (take 32 l')) in\n          \\<comment> \\<open>check data length against a lower bound for size of encoded data \\<close>\n          if int (length l) < 32 + (n * abi_size_lower_bound t) + ix\n          then Err (decode_err ''Bytes remaining less than lower bound on array size'' (ix, l))\n          else\n          (let ts = List.replicate (nat n) t in\n          (case decode'_dyn_tuple_heads ts 0 (ix + 32, l) of\n            Err s \\<Rightarrow> Err s\n            | Ok (vos, idxs, byteoffset, bytes_parsed) \\<Rightarrow>\n              (case decode'_dyn_tuple_tails idxs ts vos byteoffset (ix + 32, l) of\n                Err s \\<Rightarrow> Err s\n                | Ok (vs, bytes_parsed') \\<Rightarrow> Ok (Varray t vs, bytes_parsed + bytes_parsed' + 32)))))\n      | Ttuple ts \\<Rightarrow>\n        (case decode'_dyn_tuple_heads ts 0 (ix, l) of\n          Err s \\<Rightarrow> Err s\n          | Ok (vos, idxs, byteoffset, bytes_parsed) \\<Rightarrow>\n            (case decode'_dyn_tuple_tails idxs ts vos byteoffset (ix, l) of\n              Err s \\<Rightarrow> Err s\n              | Ok (vs, bytes_parsed') \\<Rightarrow> Ok (Vtuple ts vs, bytes_parsed + bytes_parsed')))\n      | Tbytes \\<Rightarrow>\n        if int (length l) < 32 + ix\n        then Err (decode_err ''Too few bytes; could not read bytestream size'' (ix, l))\n        else let sz = (decode_uint (take 32 l')) in\n             if int (length l) < sz + 32 + ix\n             then Err (decode_err ''Fewer bytes remaining than bytestream size'' (ix, l))\n             else (if check_padding (nat sz) (drop 32 l') \n                   then Ok (Vbytes (take (nat sz) (drop 32 l')), int(skip_padding (nat sz)) + 32)\n                   else Err (decode_err ''Invalid bytes padding'' (ix, l)))\n      | Tstring \\<Rightarrow> \n        if int(length l) < 32 + ix \n        then Err (decode_err ''Too few bytes; could not read string size'' (ix, l))\n        else let sz = (decode_uint (take 32 l')) in\n             if int (length l) < sz + 32 + ix\n             then Err (decode_err ''Fewer bytes remaining than string size'' (ix, l))\n             else (if check_padding (nat sz) (drop 32 l') \n             then Ok (Vstring (bytes_to_string (take (nat sz) (drop 32 l')))\n                     , int (skip_padding (nat sz)) + 32)\n                   else Err (decode_err ''Invalid string padding'' (ix, l)))\n      | _ \\<Rightarrow> Err (decode_err ''This should be dead code'' (ix, l)))))))\"\n\n(* indices ix are the index of the start of the overall tuple we are encoding *)\n| \"decode'_dyn_tuple_heads [] n (ix, l) = Ok ([], [], n, 0)\"\n| \"decode'_dyn_tuple_heads (th#tt) n (ix, l) =\n  (let l' = drop (nat (ix + n)) l in\n    (if abi_type_isstatic th\n      then (case decode' th (ix + n, l) of\n        Err s \\<Rightarrow> Err s\n        | Ok (v, bytes_parsed) \\<Rightarrow>\n          (case decode'_dyn_tuple_heads tt (n + nat (abi_static_size th)) (ix, l) of\n            Err s \\<Rightarrow> Err s\n            | Ok (vos, idxs, n', bytes_parsed') \\<Rightarrow> \n                Ok (Some v # vos, None#idxs, n', bytes_parsed + bytes_parsed')))\n    else\n      (if length l' < 32 then Err (decode_err ''Too few bytes; could not read tuple head'' (ix, l))\n       else let sz = (decode_sint (take 32 l')) in\n            (case decode'_dyn_tuple_heads tt (n + 32) (ix, l) of\n              Err s \\<Rightarrow> Err s\n              | Ok (vos, idxs, n', bytes_parsed) \\<Rightarrow> \n                  Ok (None # vos, (Some (ix + sz))#idxs, n', bytes_parsed + 32)))))\"\n\n| \"decode'_dyn_tuple_tails [] [] []  _ (ix, l) = Ok ([], 0)\"\n| \"decode'_dyn_tuple_tails (None#t) (th#tt) (Some vh#vt) offset (ix, l) = \n   (case decode'_dyn_tuple_tails t tt vt offset (ix, l) of\n    Err s \\<Rightarrow> Err s\n    | Ok (vs, bytes_parsed) \\<Rightarrow> Ok (vh#vs, bytes_parsed))\"\n\n| \"decode'_dyn_tuple_tails ((Some toffset)#t) (th#tt) (None#vt) offset (ix, l) =\n   (let ix' = toffset in\n       (case decode' th (ix', l) of\n              Err s \\<Rightarrow> Err s\n              | Ok (v, bytes_parsed) \\<Rightarrow>\n                     let offset' = offset + bytes_parsed in\n                     (case decode'_dyn_tuple_tails t tt vt offset' (ix, l) of\n                           Err s \\<Rightarrow> Err s\n                           | Ok (vs, bytes_parsed') \\<Rightarrow> \n                              Ok (v#vs, bytes_parsed + bytes_parsed'))))                          \n      \"\n\n| \"decode'_dyn_tuple_tails _ _ _ _ (ix, l) = Err (decode_err ''Should be dead code'' (ix, l))\"\n\n  by pat_completeness auto\n\nfun somes :: \"'a option list \\<Rightarrow> 'a list\" where\n\"somes [] = []\"\n| \"somes (None#t) = somes t\"\n| \"somes (Some h#t) = h # somes t\"\n\nlemma abi_type_measure_nonzero :\n  \"abi_type_measure t > 0\"\n  by(induction t; auto)\n\n(* Termination proof for decoder\n   (Automation fails to prove termination in a reasonable amount of time)\n*)\ntermination decode'\nproof(relation \n\"measure (\\<lambda> x .\n    (case x of\n       Inl (t, (ix, l)) \\<Rightarrow> 1 + abi_type_measure t\n      | Inr (Inl (ts,  n, (ix, l))) \\<Rightarrow> abi_type_list_measure ts\n      | Inr (Inr (idxs, ts, vs, n, (ix, l))) \\<Rightarrow> abi_type_list_measure ts))\";\n      (auto simp add:abi_type_list_measure_replicate; fail)?)\n\n  fix t ix l x x13\n  show\n    \"\\<And> xa xb.\n       \\<not> ix < 0 \\<Longrightarrow>\n       \\<not> int (length l) < ix \\<Longrightarrow>\n       x = drop (nat ix) l \\<Longrightarrow>\n       \\<not> abi_type_isstatic t \\<Longrightarrow>\n       t = Tarray x13 \\<Longrightarrow>\n       \\<not> int (length l) < 32 + ix \\<Longrightarrow>\n       xa = decode_uint (take 32 x) \\<Longrightarrow>\n       xb = replicate (nat xa) x13 \\<Longrightarrow>\n       (Inr (Inl (xb, 0, ix + 32, l)), Inl (t, ix, l))\n       \\<in> measure\n           (\\<lambda>x. case x of Inl (t, ix, l) \\<Rightarrow> 1 + abi_type_measure t \n                        | Inr (Inl (ts, n, ix, l)) \\<Rightarrow> abi_type_list_measure ts\n                        | Inr (Inr (idxs, ts, vs, n, ix, l)) \\<Rightarrow> abi_type_list_measure ts)\"\n\n    using abi_type_measure_nonzero[of x13]\n          Word.uint_lt[of \"(word_rcat (take 32 (drop (nat ix) l)) :: 256 word)\"]\n    by(auto simp add: abi_type_list_measure_replicate max_u256_def intro:Nat.add_less_mono)\nnext\n  fix t ix l x x13\n  show\n    \"\\<And> xa xb a xc y xd ya xe yb.\n       \\<not> ix < 0 \\<Longrightarrow>\n       \\<not> int (length l) < ix \\<Longrightarrow>\n       x = drop (nat ix) l \\<Longrightarrow>\n       \\<not> abi_type_isstatic t \\<Longrightarrow>\n       t = Tarray x13 \\<Longrightarrow>\n       \\<not> int (length l) < 32 + ix \\<Longrightarrow>\n       xa = decode_uint (take 32 x) \\<Longrightarrow>\n       xb = replicate (nat xa) x13 \\<Longrightarrow>\n       decode'_dyn_tuple_heads xb 0 (ix + 32, l) = Ok a \\<Longrightarrow>\n       (xc, y) = a \\<Longrightarrow>\n       (xd, ya) = y \\<Longrightarrow>\n       (xe, yb) = ya \\<Longrightarrow>\n       decode'_decode'_dyn_tuple_heads_decode'_dyn_tuple_tails_dom \n          (Inr (Inl (xb, 0, ix + 32, l))) \\<Longrightarrow>\n       (Inr (Inr (xd, xb, xc, xe, ix + 32, l)), Inl (t, ix, l))\n       \\<in> measure (\\<lambda>x. case x of Inl (t, ix, l) \\<Rightarrow> 1 + abi_type_measure t \n                              | Inr (Inl (ts, n, ix, l)) \\<Rightarrow> abi_type_list_measure ts\n                              | Inr (Inr (idxs, ts, vs, n, ix, l)) \\<Rightarrow> abi_type_list_measure ts)\"\n   using abi_type_measure_nonzero[of x13]\n          Word.uint_lt[of \"(word_rcat (take 32 (drop (nat ix) l)) :: 256 word)\"]\n   by(auto simp add: abi_type_list_measure_replicate max_u256_def intro:Nat.add_less_mono)\nnext\n  fix th tt\n  show\n    \"\\<And> n ix l x.\n       x = drop (nat (ix + n)) l \\<Longrightarrow>\n       abi_type_isstatic th \\<Longrightarrow>\n       (Inl (th, ix + n, l), Inr (Inl (th # tt, n, ix, l)))\n       \\<in> measure (\\<lambda>x. case x of Inl (t, ix, l) \\<Rightarrow> 1 + abi_type_measure t \n                              | Inr (Inl (ts, n, ix, l)) \\<Rightarrow> abi_type_list_measure ts \n                              | Inr (Inr (idxs, ts, vs, n, ix, l)) \\<Rightarrow> abi_type_list_measure ts)\"\n    by(cases tt; auto)\nnext\n  fix tt\n  show\n    \"\\<And> toffset t th vt offset ix l x.\n       x = toffset \\<Longrightarrow>\n       (Inl (th, x, l), Inr (Inr (Some toffset # t, th # tt, None # vt, offset, ix, l)))\n       \\<in> measure (\\<lambda>x. case x of Inl (t, ix, l) \\<Rightarrow> 1 + abi_type_measure t \n                              | Inr (Inl (ts, n, ix, l)) \\<Rightarrow> abi_type_list_measure ts \n                              | Inr (Inr (idxs, ts, vs, n, ix, l)) \\<Rightarrow> abi_type_list_measure ts)\"\n    by(cases tt; auto)\nqed\n\nfun decode :: \"abi_type \\<Rightarrow> 8 word list \\<Rightarrow> abi_value orerror\" where\n\"decode t l =\n  (if abi_type_valid t then\n    (case decode' t (0, l) of\n      Err s \\<Rightarrow> Err s\n      | Ok (v, _) \\<Rightarrow> Ok v)\n   else Err ''Invalid ABI type'')\"\n\nend", "meta": {"author": "mmalvarez", "repo": "SolidityABI", "sha": "68b306e7abc230a1095a8c4d4a79e22be836677b", "save_path": "github-repos/isabelle/mmalvarez-SolidityABI", "path": "github-repos/isabelle/mmalvarez-SolidityABI/SolidityABI-68b306e7abc230a1095a8c4d4a79e22be836677b/AbiDecode.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9407897525789548, "lm_q2_score": 0.7490872187162396, "lm_q1q2_score": 0.7047335791561085}}
{"text": "(* Title:      Semirings\n   Author:     Walter Guttmann\n   Maintainer: Walter Guttmann <walter.guttmann at canterbury.ac.nz>\n*)\n\nsection \\<open>Semirings\\<close>\n\ntext \\<open>\nThis theory develops a hierarchy of idempotent semirings.\nAll kinds of semiring considered here are bounded semilattices, but many lack additional properties typically assumed for semirings.\nIn particular, we consider the variants of semirings, in which\n\\begin{itemize}\n\\item multiplication is not required to be associative;\n\\item a right zero and unit of multiplication need not exist;\n\\item multiplication has a left residual;\n\\item multiplication from the left is not required to distribute over addition;\n\\item the semilattice order has a greatest element.\n\\end{itemize}\nWe have applied results from this theory a number of papers for unifying computation models.\nFor example, see \\cite{Guttmann2012c} for various relational and matrix-based computation models and \\cite{BerghammerGuttmann2015b} for multirelational models.\n\nThe main results in this theory relate different ways of defining reflexive-transitive closures as discussed in \\cite{BerghammerGuttmann2015b}.\n\\<close>\n\ntheory Semirings\n\nimports Fixpoints\n\nbegin\n\nsubsection \\<open>Idempotent Semirings\\<close>\n\ntext \\<open>\nThe following definitions are standard for relations.\nPutting them into a general class that depends only on the signature facilitates reuse.\nCoreflexives are sometimes called partial identities, subidentities, monotypes or tests.\n\\<close>\n\nclass times_one_ord = times + one + ord\nbegin\n\nabbreviation reflexive   :: \"'a \\<Rightarrow> bool\" where \"reflexive x   \\<equiv> 1 \\<le> x\"\nabbreviation coreflexive :: \"'a \\<Rightarrow> bool\" where \"coreflexive x \\<equiv> x \\<le> 1\"\n\nabbreviation transitive  :: \"'a \\<Rightarrow> bool\" where \"transitive x  \\<equiv> x * x \\<le> x\"\nabbreviation dense_rel   :: \"'a \\<Rightarrow> bool\" where \"dense_rel x   \\<equiv> x \\<le> x * x\"\nabbreviation idempotent  :: \"'a \\<Rightarrow> bool\" where \"idempotent x  \\<equiv> x * x = x\"\n\nabbreviation preorder    :: \"'a \\<Rightarrow> bool\" where \"preorder x    \\<equiv> reflexive x \\<and> transitive x\"\n\nabbreviation \"coreflexives \\<equiv> { x . coreflexive x }\"\n\nend\n\ntext \\<open>\nThe first algebra is a very weak idempotent semiring, in which multiplication is not necessarily associative.\n\\<close>\n\nclass non_associative_left_semiring = bounded_semilattice_sup_bot + times + one +\n  assumes mult_left_sub_dist_sup: \"x * y \\<squnion> x * z \\<le> x * (y \\<squnion> z)\"\n  assumes mult_right_dist_sup: \"(x \\<squnion> y) * z = x * z \\<squnion> y * z\"\n  assumes mult_left_zero [simp]: \"bot * x = bot\"\n  assumes mult_left_one [simp]: \"1 * x = x\"\n  assumes mult_sub_right_one: \"x \\<le> x * 1\"\nbegin\n\nsubclass times_one_ord .\n\ntext \\<open>\nWe first show basic isotonicity and subdistributivity properties of multiplication.\n\\<close>\n\nlemma mult_left_isotone:\n  \"x \\<le> y \\<Longrightarrow> x * z \\<le> y * z\"\n  using mult_right_dist_sup sup_right_divisibility by auto\n\nlemma mult_right_isotone:\n  \"x \\<le> y \\<Longrightarrow> z * x \\<le> z * y\"\n  using mult_left_sub_dist_sup sup.bounded_iff sup_right_divisibility by auto\n\nlemma mult_isotone:\n  \"w \\<le> y \\<Longrightarrow> x \\<le> z \\<Longrightarrow> w * x \\<le> y * z\"\n  using order_trans mult_left_isotone mult_right_isotone by blast\n\nlemma affine_isotone:\n  \"isotone (\\<lambda>x . y * x \\<squnion> z)\"\n  using isotone_def mult_right_isotone sup_left_isotone by auto\n\nlemma mult_left_sub_dist_sup_left:\n  \"x * y \\<le> x * (y \\<squnion> z)\"\n  by (simp add: mult_right_isotone)\n\nlemma mult_left_sub_dist_sup_right:\n  \"x * z \\<le> x * (y \\<squnion> z)\"\n  by (simp add: mult_right_isotone)\n\nlemma mult_right_sub_dist_sup_left:\n  \"x * z \\<le> (x \\<squnion> y) * z\"\n  by (simp add: mult_left_isotone)\n\nlemma mult_right_sub_dist_sup_right:\n  \"y * z \\<le> (x \\<squnion> y) * z\"\n  by (simp add: mult_left_isotone)\n\nlemma case_split_left:\n  assumes \"1 \\<le> w \\<squnion> z\"\n      and \"w * x \\<le> y\"\n      and \"z * x \\<le> y\"\n    shows \"x \\<le> y\"\nproof -\n  have \"(w \\<squnion> z) * x \\<le> y\"\n    by (simp add: assms(2-3) mult_right_dist_sup)\n  thus ?thesis\n    by (metis assms(1) dual_order.trans mult_left_one mult_left_isotone)\nqed\n\nlemma case_split_left_equal:\n  \"w \\<squnion> z = 1 \\<Longrightarrow> w * x = w * y \\<Longrightarrow> z * x = z * y \\<Longrightarrow> x = y\"\n  by (metis mult_left_one mult_right_dist_sup)\n\ntext \\<open>\nNext we consider under which semiring operations the above properties are closed.\n\\<close>\n\nlemma reflexive_one_closed:\n  \"reflexive 1\"\n  by simp\n\nlemma reflexive_sup_closed:\n  \"reflexive x \\<Longrightarrow> reflexive (x \\<squnion> y)\"\n  by (simp add: le_supI1)\n\nlemma reflexive_mult_closed:\n  \"reflexive x \\<Longrightarrow> reflexive y \\<Longrightarrow> reflexive (x * y)\"\n  using mult_isotone by fastforce\n\nlemma coreflexive_bot_closed:\n  \"coreflexive bot\"\n  by simp\n\nlemma coreflexive_one_closed:\n  \"coreflexive 1\"\n  by simp\n\nlemma coreflexive_sup_closed:\n  \"coreflexive x \\<Longrightarrow> coreflexive y \\<Longrightarrow> coreflexive (x \\<squnion> y)\"\n  by simp\n\nlemma coreflexive_mult_closed:\n  \"coreflexive x \\<Longrightarrow> coreflexive y \\<Longrightarrow> coreflexive (x * y)\"\n  using mult_isotone by fastforce\n\nlemma transitive_bot_closed:\n  \"transitive bot\"\n  by simp\n\nlemma transitive_one_closed:\n  \"transitive 1\"\n  by simp\n\n\n\nlemma dense_one_closed:\n  \"dense_rel 1\"\n  by simp\n\nlemma dense_sup_closed:\n  \"dense_rel x \\<Longrightarrow> dense_rel y \\<Longrightarrow> dense_rel (x \\<squnion> y)\"\n  by (metis mult_right_dist_sup order_lesseq_imp sup.mono mult_left_sub_dist_sup_left mult_left_sub_dist_sup_right)\n\nlemma idempotent_bot_closed:\n  \"idempotent bot\"\n  by simp\n\nlemma idempotent_one_closed:\n  \"idempotent 1\"\n  by simp\n\nlemma preorder_one_closed:\n  \"preorder 1\"\n  by simp\n\nlemma coreflexive_transitive:\n  \"coreflexive x \\<Longrightarrow> transitive x\"\n  using mult_left_isotone by fastforce\n\nlemma preorder_idempotent:\n  \"preorder x \\<Longrightarrow> idempotent x\"\n  using antisym mult_isotone by fastforce\n\ntext \\<open>\nWe study the following three ways of defining reflexive-transitive closures.\nEach of them is given as a least prefixpoint, but the underlying functions are different.\nThey implement left recursion, right recursion and symmetric recursion, respectively.\n\\<close>\n\nabbreviation Lf :: \"'a \\<Rightarrow> ('a \\<Rightarrow> 'a)\" where \"Lf y \\<equiv> (\\<lambda>x . 1 \\<squnion> x * y)\"\nabbreviation Rf :: \"'a \\<Rightarrow> ('a \\<Rightarrow> 'a)\" where \"Rf y \\<equiv> (\\<lambda>x . 1 \\<squnion> y * x)\"\nabbreviation Sf :: \"'a \\<Rightarrow> ('a \\<Rightarrow> 'a)\" where \"Sf y \\<equiv> (\\<lambda>x . 1 \\<squnion> y \\<squnion> x * x)\"\n\nabbreviation lstar :: \"'a \\<Rightarrow> 'a\" where \"lstar y \\<equiv> p\\<mu> (Lf y)\"\nabbreviation rstar :: \"'a \\<Rightarrow> 'a\" where \"rstar y \\<equiv> p\\<mu> (Rf y)\"\nabbreviation sstar :: \"'a \\<Rightarrow> 'a\" where \"sstar y \\<equiv> p\\<mu> (Sf y)\"\n\ntext \\<open>\nAll functions are isotone and, therefore, if the prefixpoints exist they are also fixpoints.\n\\<close>\n\nlemma lstar_rec_isotone:\n  \"isotone (Lf y)\"\n  using isotone_def sup_right_divisibility sup_right_isotone mult_right_sub_dist_sup_right by auto\n\nlemma rstar_rec_isotone:\n  \"isotone (Rf y)\"\n  using isotone_def sup_right_divisibility sup_right_isotone mult_left_sub_dist_sup_right by auto\n\nlemma sstar_rec_isotone:\n  \"isotone (Sf y)\"\n  using isotone_def sup_right_isotone mult_isotone by auto\n\nlemma lstar_fixpoint:\n  \"has_least_prefixpoint (Lf y) \\<Longrightarrow> lstar y = \\<mu> (Lf y)\"\n  by (simp add: pmu_mu lstar_rec_isotone)\n\nlemma rstar_fixpoint:\n  \"has_least_prefixpoint (Rf y) \\<Longrightarrow> rstar y = \\<mu> (Rf y)\"\n  by (simp add: pmu_mu rstar_rec_isotone)\n\nlemma sstar_fixpoint:\n  \"has_least_prefixpoint (Sf y) \\<Longrightarrow> sstar y = \\<mu> (Sf y)\"\n  by (simp add: pmu_mu sstar_rec_isotone)\n\nlemma sstar_increasing:\n  \"has_least_prefixpoint (Sf y) \\<Longrightarrow> y \\<le> sstar y\"\n  using order_trans pmu_unfold sup_ge1 sup_ge2 by blast\n\ntext \\<open>\nThe fixpoint given by right recursion is always below the one given by symmetric recursion.\n\\<close>\n\nlemma rstar_below_sstar:\n  assumes \"has_least_prefixpoint (Rf y)\"\n      and \"has_least_prefixpoint (Sf y)\"\n    shows \"rstar y \\<le> sstar y\"\nproof -\n  have \"y \\<le> sstar y\"\n    using assms(2) pmu_unfold by force\n  hence \"Rf y (sstar y) \\<le> Sf y (sstar y)\"\n    by (meson sup.cobounded1 sup.mono mult_left_isotone)\n  also have \"... \\<le> sstar y\"\n    using assms(2) pmu_unfold by blast\n  finally show ?thesis\n    using assms(1) is_least_prefixpoint_def least_prefixpoint by auto\nqed\n\nend\n\ntext \\<open>\nOur next structure adds one half of the associativity property.\nThis inequality holds, for example, for multirelations under the compositions defined by Parikh and Peleg \\cite{Parikh1983,Peleg1987}.\nThe converse inequality requires up-closed multirelations for Parikh's composition.\n\\<close>\n\nclass pre_left_semiring = non_associative_left_semiring +\n  assumes mult_semi_associative: \"(x * y) * z \\<le> x * (y * z)\"\nbegin\n\nlemma mult_one_associative [simp]:\n  \"x * 1 * y = x * y\"\n  by (metis dual_order.antisym mult_left_isotone mult_left_one mult_semi_associative mult_sub_right_one)\n\nlemma mult_sup_associative_one:\n  \"(x * (y * 1)) * z \\<le> x * (y * z)\"\n  by (metis mult_semi_associative mult_one_associative)\n\nlemma rstar_increasing:\n  assumes \"has_least_prefixpoint (Rf y)\"\n    shows \"y \\<le> rstar y\"\nproof -\n  have \"Rf y (rstar y) \\<le> rstar y\"\n    using assms pmu_unfold by blast\n  thus ?thesis\n    by (metis le_supE mult_right_isotone mult_sub_right_one sup.absorb_iff2)\nqed\n\nend\n\ntext \\<open>\nFor the next structure we add a left residual operation.\nSuch a residual is available, for example, for multirelations.\n\nThe operator notation for binary division is introduced in a class that requires a unary inverse.\nThis is appropriate for fields, but too strong in the present context of semirings.\nWe therefore reintroduce it without requiring a unary inverse.\n\\<close>\n\nno_notation\n  inverse_divide (infixl \"'/\" 70)\n\nnotation\n  divide (infixl \"'/\" 70)\n\nclass residuated_pre_left_semiring = pre_left_semiring + divide +\n  assumes lres_galois: \"x * y \\<le> z \\<longleftrightarrow> x \\<le> z / y\"\nbegin\n\ntext \\<open>\nWe first derive basic properties of left residuals from the Galois connection.\n\\<close>\n\nlemma lres_left_isotone:\n  \"x \\<le> y \\<Longrightarrow> x / z \\<le> y / z\"\n  using dual_order.trans lres_galois by blast\n\nlemma lres_right_antitone:\n  \"x \\<le> y \\<Longrightarrow> z / y \\<le> z / x\"\n  using dual_order.trans lres_galois mult_right_isotone by blast\n\nlemma lres_inverse:\n  \"(x / y) * y \\<le> x\"\n  by (simp add: lres_galois)\n\nlemma lres_one:\n  \"x / 1 \\<le> x\"\n  using mult_sub_right_one order_trans lres_inverse by blast\n\nlemma lres_mult_sub_lres_lres:\n  \"x / (z * y) \\<le> (x / y) / z\"\n  using lres_galois mult_semi_associative order.trans by blast\n\nlemma mult_lres_sub_assoc:\n  \"x * (y / z) \\<le> (x * y) / z\"\n  by (meson dual_order.trans lres_galois mult_right_isotone lres_inverse lres_mult_sub_lres_lres)\n\ntext \\<open>\nWith the help of a left residual, it follows that left recursion is below right recursion.\n\\<close>\n\nlemma lstar_below_rstar:\n  assumes \"has_least_prefixpoint (Lf y)\"\n      and \"has_least_prefixpoint (Rf y)\"\n    shows \"lstar y \\<le> rstar y\"\nproof -\n  have \"y * (rstar y / y) * y \\<le> y * rstar y\"\n    using lres_galois mult_lres_sub_assoc by auto\n  also have \"... \\<le> rstar y\"\n    using assms(2) le_supE pmu_unfold by blast\n  finally have \"y * (rstar y / y) \\<le> rstar y / y\"\n    by (simp add: lres_galois)\n  hence \"Rf y (rstar y / y) \\<le> rstar y / y\"\n    using assms(2) lres_galois rstar_increasing by fastforce\n  hence \"rstar y \\<le> rstar y / y\"\n    using assms(2) is_least_prefixpoint_def least_prefixpoint by auto\n  hence \"Lf y (rstar y) \\<le> rstar y\"\n    using assms(2) lres_galois pmu_unfold by fastforce\n  thus ?thesis\n    using assms(1) is_least_prefixpoint_def least_prefixpoint by auto\nqed\n\ntext \\<open>\nMoreover, right recursion gives the same result as symmetric recursion.\nThe next proof follows an argument of \\cite[Satz 10.1.5]{Berghammer2012}.\n\\<close>\n\nlemma rstar_sstar:\n  assumes \"has_least_prefixpoint (Rf y)\"\n      and \"has_least_prefixpoint (Sf y)\"\n    shows \"rstar y = sstar y\"\nproof -\n  have \"Rf y (rstar y / rstar y) * rstar y \\<le> rstar y \\<squnion> y * ((rstar y / rstar y) * rstar y)\"\n    using mult_right_dist_sup mult_semi_associative sup_right_isotone by auto\n  also have \"... \\<le> rstar y \\<squnion> y * rstar y\"\n    using mult_right_isotone sup_right_isotone lres_inverse by blast\n  also have \"... \\<le> rstar y\"\n    using assms(1) pmu_unfold by fastforce\n  finally have \"Rf y (rstar y / rstar y) \\<le> rstar y / rstar y\"\n    by (simp add: lres_galois)\n  hence \"rstar y * rstar y \\<le> rstar y\"\n    using assms(1) is_least_prefixpoint_def least_prefixpoint lres_galois by auto\n  hence \"y \\<squnion> rstar y * rstar y \\<le> rstar y\"\n    by (simp add: assms(1) rstar_increasing)\n  hence \"Sf y (rstar y) \\<le> rstar y\"\n    using assms(1) pmu_unfold by force\n  hence \"sstar y \\<le> rstar y\"\n    using assms(2) is_least_prefixpoint_def least_prefixpoint by auto\n  thus ?thesis\n    by (simp add: assms antisym rstar_below_sstar)\nqed\n\nend\n\ntext \\<open>\nIn the next structure we add full associativity of multiplication, as well as a right unit.\nStill, multiplication does not need to have a right zero and does not need to distribute over addition from the left.\n\\<close>\n\nclass idempotent_left_semiring = non_associative_left_semiring + monoid_mult\nbegin\n\nsubclass pre_left_semiring\n  by unfold_locales (simp add: mult_assoc)\n\nlemma zero_right_mult_decreasing:\n  \"x * bot \\<le> x\"\n  by (metis bot_least mult_1_right mult_right_isotone)\n\ntext \\<open>\nThe following result shows that for dense coreflexives there are two equivalent ways to express that a property is preserved.\nIn the setting of Kleene algebras, this is well known for tests, which form a Boolean subalgebra.\nThe point here is that only very few properties of tests are needed to show the equivalence.\n\\<close>\n\n\n\nend\n\ntext \\<open>\nThe next structure has both distributivity properties of multiplication.\nOnly a right zero is missing from full semirings.\nThis is important as many computation models do not have a right zero of sequential composition.\n\\<close>\n\nclass idempotent_left_zero_semiring = idempotent_left_semiring +\n  assumes mult_left_dist_sup: \"x * (y \\<squnion> z) = x * y \\<squnion> x * z\"\nbegin\n\nlemma case_split_right:\n  assumes \"1 \\<le> w \\<squnion> z\"\n      and \"x * w \\<le> y\"\n      and \"x * z \\<le> y\"\n    shows \"x \\<le> y\"\nproof -\n  have \"x * (w \\<squnion> z) \\<le> y\"\n    by (simp add: assms(2-3) mult_left_dist_sup)\n  thus ?thesis\n    by (metis assms(1) dual_order.trans mult_1_right mult_right_isotone)\nqed\n\nlemma case_split_right_equal:\n  \"w \\<squnion> z = 1 \\<Longrightarrow> x * w = y * w \\<Longrightarrow> x * z = y * z \\<Longrightarrow> x = y\"\n  by (metis mult_1_right mult_left_dist_sup)\n\ntext \\<open>\nThis is the first structure we can connect to the semirings provided by Isabelle/HOL.\n\\<close>\n\nsublocale semiring: ordered_semiring sup bot less_eq less times\n  apply unfold_locales\n  using sup_right_isotone apply blast\n  apply (simp add: mult_right_dist_sup)\n  apply (simp add: mult_left_dist_sup)\n  apply (simp add: mult_right_isotone)\n  by (simp add: mult_left_isotone)\n\nsublocale semiring: semiring_numeral 1 times sup ..\n\nend\n\ntext \\<open>\nCompleting this part of the hierarchy, we obtain idempotent semirings by adding a right zero of multiplication.\n\\<close>\n\nclass idempotent_semiring = idempotent_left_zero_semiring +\n  assumes mult_right_zero [simp]: \"x * bot = bot\"\nbegin\n\nsublocale semiring: semiring_0 sup bot times\n  by unfold_locales simp_all\n\nend\n\nsubsection \\<open>Bounded Idempotent Semirings\\<close>\n\ntext \\<open>\nAll of the following semirings have a greatest element in the underlying semilattice order.\nWith this element, we can express further standard properties of relations.\nWe extend each class in the above hierarchy in turn.\n\\<close>\n\nclass times_top = times + top\nbegin\n\nabbreviation vector     :: \"'a \\<Rightarrow> bool\" where \"vector x     \\<equiv> x * top = x\"\nabbreviation covector   :: \"'a \\<Rightarrow> bool\" where \"covector x   \\<equiv> top * x = x\"\nabbreviation total      :: \"'a \\<Rightarrow> bool\" where \"total x      \\<equiv> x * top = top\"\nabbreviation surjective :: \"'a \\<Rightarrow> bool\" where \"surjective x \\<equiv> top * x = top\"\n\nabbreviation \"vectors   \\<equiv> { x . vector x }\"\nabbreviation \"covectors \\<equiv> { x . covector x }\"\n\nend\n\nclass bounded_non_associative_left_semiring = non_associative_left_semiring + top +\n  assumes sup_right_top [simp]: \"x \\<squnion> top = top\"\nbegin\n\nsubclass times_top .\n\ntext \\<open>\nWe first give basic properties of the greatest element.\n\\<close>\n\nlemma sup_left_top [simp]:\n  \"top \\<squnion> x = top\"\n  using sup_right_top sup.commute by fastforce\n\nlemma top_greatest [simp]:\n  \"x \\<le> top\"\n  by (simp add: le_iff_sup)\n\nlemma top_left_mult_increasing:\n  \"x \\<le> top * x\"\n  by (metis mult_left_isotone mult_left_one top_greatest)\n\nlemma top_right_mult_increasing:\n  \"x \\<le> x * top\"\n  using mult_right_isotone mult_sub_right_one order_trans top_greatest by blast\n\nlemma top_mult_top [simp]:\n  \"top * top = top\"\n  by (simp add: antisym top_left_mult_increasing)\n\ntext \\<open>\nClosure of the above properties under the semiring operations is considered next.\n\\<close>\n\nlemma vector_bot_closed:\n  \"vector bot\"\n  by simp\n\nlemma vector_top_closed:\n  \"vector top\"\n  by simp\n\nlemma vector_sup_closed:\n  \"vector x \\<Longrightarrow> vector y \\<Longrightarrow> vector (x \\<squnion> y)\"\n  by (simp add: mult_right_dist_sup)\n\nlemma covector_top_closed:\n  \"covector top\"\n  by simp\n\nlemma total_one_closed:\n  \"total 1\"\n  by simp\n\nlemma total_top_closed:\n  \"total top\"\n  by simp\n\n\n\nlemma surjective_one_closed:\n  \"surjective 1\"\n  by (simp add: antisym mult_sub_right_one)\n\nlemma surjective_top_closed:\n  \"surjective top\"\n  by simp\n\nlemma surjective_sup_closed:\n  \"surjective x \\<Longrightarrow> surjective (x \\<squnion> y)\"\n  by (metis le_iff_sup mult_left_sub_dist_sup_left sup_left_top)\n\nlemma reflexive_top_closed:\n  \"reflexive top\"\n  by simp\n\nlemma transitive_top_closed:\n  \"transitive top\"\n  by simp\n\nlemma dense_top_closed:\n  \"dense_rel top\"\n  by simp\n\nlemma idempotent_top_closed:\n  \"idempotent top\"\n  by simp\n\nlemma preorder_top_closed:\n  \"preorder top\"\n  by simp\n\nend\n\ntext \\<open>\nSome closure properties require at least half of associativity.\n\\<close>\n\nclass bounded_pre_left_semiring = pre_left_semiring + bounded_non_associative_left_semiring\nbegin\n\nlemma vector_mult_closed:\n  \"vector y \\<Longrightarrow> vector (x * y)\"\n  by (metis antisym mult_semi_associative top_right_mult_increasing)\n\nlemma surjective_mult_closed:\n  \"surjective x \\<Longrightarrow> surjective y \\<Longrightarrow> surjective (x * y)\"\n  by (metis antisym mult_semi_associative top_greatest)\n\nend\n\ntext \\<open>\nWe next consider residuals with the greatest element.\n\\<close>\n\nclass bounded_residuated_pre_left_semiring = residuated_pre_left_semiring + bounded_pre_left_semiring\nbegin\n\nlemma lres_top_decreasing:\n  \"x / top \\<le> x\"\n  using lres_inverse order.trans top_right_mult_increasing by blast\n\nlemma top_lres_absorb [simp]:\n  \"top / x = top\"\n  using antisym lres_galois top_greatest by blast\n\nlemma covector_lres_closed:\n  \"covector x \\<Longrightarrow> covector (x / y)\"\n  by (metis antisym mult_lres_sub_assoc top_left_mult_increasing)\n\nend\n\ntext \\<open>\nSome closure properties require full associativity.\n\\<close>\n\nclass bounded_idempotent_left_semiring = bounded_pre_left_semiring + idempotent_left_semiring\nbegin\n\nlemma covector_mult_closed:\n  \"covector x \\<Longrightarrow> covector (x * y)\"\n  by (metis mult_assoc)\n\nlemma total_mult_closed:\n  \"total x \\<Longrightarrow> total y \\<Longrightarrow> total (x * y)\"\n  by (simp add: mult_assoc)\n\nend\n\ntext \\<open>\nSome closure properties require distributivity from the left.\n\\<close>\n\nclass bounded_idempotent_left_zero_semiring = bounded_idempotent_left_semiring + idempotent_left_zero_semiring\nbegin\n\nlemma covector_sup_closed:\n  \"covector x \\<Longrightarrow> covector y \\<Longrightarrow> covector (x \\<squnion> y)\"\n  by (simp add: mult_left_dist_sup)\n\nend\n\ntext \\<open>\nOur final structure is an idempotent semiring with a greatest element.\n\\<close>\n\nclass bounded_idempotent_semiring = bounded_idempotent_left_zero_semiring + idempotent_semiring\nbegin\n\nlemma covector_bot_closed:\n  \"covector bot\"\n  by simp\n\nend\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/Semirings.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8856314647623016, "lm_q2_score": 0.7956581097540519, "lm_q1q2_score": 0.7046598571914852}}
{"text": "(*  Title:      IPv4.thy\n    Authors:    Cornelius Diekmann, Julius Michaelis\n*)\ntheory IPv4\nimports IP_Address\n        NumberWang_IPv4\n        (* include \"HOL-Library.Code_Target_Nat\" if you need to work with actual numbers.*)\nbegin\n\n\nsection \\<open>IPv4 Adresses\\<close>\n  text\\<open>An IPv4 address is basically a 32 bit unsigned integer.\\<close>\n  type_synonym ipv4addr = \"32 word\"\n\n  text\\<open>Conversion between natural numbers and IPv4 adresses\\<close>\n  definition nat_of_ipv4addr :: \"ipv4addr \\<Rightarrow> nat\" where\n    \"nat_of_ipv4addr a = unat a\"\n  definition ipv4addr_of_nat :: \"nat \\<Rightarrow> ipv4addr\" where\n    \"ipv4addr_of_nat n =  of_nat n\"\n\n  text\\<open>The maximum IPv4 addres\\<close>\n  definition max_ipv4_addr :: \"ipv4addr\" where\n    \"max_ipv4_addr \\<equiv> ipv4addr_of_nat ((2^32) - 1)\"\n\n  lemma max_ipv4_addr_number: \"max_ipv4_addr = 4294967295\"\n    unfolding max_ipv4_addr_def ipv4addr_of_nat_def by(simp)\n  lemma \"max_ipv4_addr = 0b11111111111111111111111111111111\"\n    by(fact max_ipv4_addr_number)\n  lemma max_ipv4_addr_max_word: \"max_ipv4_addr = max_word\"\n    by(simp add: max_ipv4_addr_number max_word_def)\n  lemma max_ipv4_addr_max[simp]: \"\\<forall>a. a \\<le> max_ipv4_addr\"\n    by(simp add: max_ipv4_addr_max_word)\n  lemma UNIV_ipv4addrset: \"UNIV = {0 .. max_ipv4_addr}\" (*not in the simp set, for a reason*)\n    by(simp add: max_ipv4_addr_max_word) fastforce\n\n  text\\<open>identity functions\\<close>\n  lemma nat_of_ipv4addr_ipv4addr_of_nat:\n    \"\\<lbrakk> n \\<le> nat_of_ipv4addr max_ipv4_addr \\<rbrakk> \\<Longrightarrow> nat_of_ipv4addr (ipv4addr_of_nat n) = n\"\n    by (simp add: ipv4addr_of_nat_def le_unat_uoi nat_of_ipv4addr_def)\n  lemma nat_of_ipv4addr_ipv4addr_of_nat_mod: \"nat_of_ipv4addr (ipv4addr_of_nat n) = n mod 2^32\"\n    by(simp add: ipv4addr_of_nat_def nat_of_ipv4addr_def unat_of_nat)\n  lemma ipv4addr_of_nat_nat_of_ipv4addr: \"ipv4addr_of_nat (nat_of_ipv4addr addr) = addr\"\n    by(simp add: ipv4addr_of_nat_def nat_of_ipv4addr_def)\n\nsubsection\\<open>Representing IPv4 Adresses (Syntax)\\<close>\n  fun ipv4addr_of_dotdecimal :: \"nat \\<times> nat \\<times> nat \\<times> nat \\<Rightarrow> ipv4addr\" where\n    \"ipv4addr_of_dotdecimal (a,b,c,d) = ipv4addr_of_nat (d + 256 * c + 65536 * b + 16777216 * a )\"\n\n  fun dotdecimal_of_ipv4addr :: \"ipv4addr \\<Rightarrow> nat \\<times> nat \\<times> nat \\<times> nat\" where\n    \"dotdecimal_of_ipv4addr a = (nat_of_ipv4addr ((a >> 24) AND 0xFF),\n                                    nat_of_ipv4addr ((a >> 16) AND 0xFF),\n                                    nat_of_ipv4addr ((a >> 8) AND 0xFF),\n                                    nat_of_ipv4addr (a AND 0xff))\"\n\n  declare ipv4addr_of_dotdecimal.simps[simp del]\n  declare dotdecimal_of_ipv4addr.simps[simp del]\n\n  text\\<open>Examples:\\<close>\n  lemma \"ipv4addr_of_dotdecimal (192, 168, 0, 1) = 3232235521\"\n    by(simp add: ipv4addr_of_dotdecimal.simps ipv4addr_of_nat_def)\n    (*could be solved by eval, but needs \"HOL-Library.Code_Target_Nat\"*)\n  lemma \"dotdecimal_of_ipv4addr 3232235521 = (192, 168, 0, 1)\"\n    by(simp add: dotdecimal_of_ipv4addr.simps nat_of_ipv4addr_def)\n\n  text\\<open>a different notation for @{term ipv4addr_of_dotdecimal}\\<close>\n  lemma ipv4addr_of_dotdecimal_bit:\n    \"ipv4addr_of_dotdecimal (a,b,c,d) =\n      (ipv4addr_of_nat a << 24) + (ipv4addr_of_nat b << 16) +\n       (ipv4addr_of_nat c << 8) + ipv4addr_of_nat d\"\n  proof -\n    have a: \"(ipv4addr_of_nat a) << 24 = ipv4addr_of_nat (a * 16777216)\"\n      by(simp add: ipv4addr_of_nat_def shiftl_t2n)\n    have b: \"(ipv4addr_of_nat b) << 16 = ipv4addr_of_nat (b * 65536)\"\n      by(simp add: ipv4addr_of_nat_def shiftl_t2n)\n    have c: \"(ipv4addr_of_nat c) << 8 = ipv4addr_of_nat (c * 256)\"\n      by(simp add: ipv4addr_of_nat_def shiftl_t2n)\n    have ipv4addr_of_nat_suc: \"\\<And>x. ipv4addr_of_nat (Suc x) = word_succ (ipv4addr_of_nat (x))\"\n      by(simp add: ipv4addr_of_nat_def, metis Abs_fnat_hom_Suc of_nat_Suc)\n    { fix x y\n      have \"ipv4addr_of_nat x + ipv4addr_of_nat y = ipv4addr_of_nat (x+y)\"\n        apply(induction x arbitrary: y)\n         apply(simp add: ipv4addr_of_nat_def; fail)\n        by(simp add: ipv4addr_of_nat_suc word_succ_p1)\n    } from this a b c\n    show ?thesis\n      apply(simp add: ipv4addr_of_dotdecimal.simps)\n      apply(rule arg_cong[where f=ipv4addr_of_nat])\n      apply(thin_tac _)+\n      by presburger\n  qed\n\n  lemma size_ipv4addr: \"size (x::ipv4addr) = 32\" by(simp add:word_size)\n\n  lemma dotdecimal_of_ipv4addr_ipv4addr_of_dotdecimal:\n  \"\\<lbrakk> a < 256; b < 256; c < 256; d < 256 \\<rbrakk> \\<Longrightarrow>\n    dotdecimal_of_ipv4addr (ipv4addr_of_dotdecimal (a,b,c,d)) = (a,b,c,d)\"\n  proof -\n    assume  \"a < 256\" and \"b < 256\" and \"c < 256\" and \"d < 256\"\n    note assms= \\<open>a < 256\\<close> \\<open>b < 256\\<close> \\<open>c < 256\\<close> \\<open>d < 256\\<close>\n    hence a:  \"nat_of_ipv4addr ((ipv4addr_of_nat (d + 256 * c + 65536 * b + 16777216 * a) >> 24) AND mask 8) = a\"\n      apply(simp add: ipv4addr_of_nat_def word_of_nat)\n      apply(simp add: nat_of_ipv4addr_def unat_def)\n      apply(simp add: and_mask_mod_2p)\n      apply(simp add: shiftr_div_2n)\n      apply(simp add: uint_word_of_int)\n      done\n    have ipv4addr_of_nat_AND_mask8: \"(ipv4addr_of_nat a) AND mask 8 = (ipv4addr_of_nat (a mod 256))\"\n      for a\n      apply(simp add: ipv4addr_of_nat_def and_mask_mod_2p)\n      apply(simp add: word_of_nat) (*use this to get rid of of_nat. All thm are with word_of_int*)\n      apply(simp add: uint_word_of_int)\n      apply(subst mod_mod_cancel)\n       apply(simp; fail)\n      apply(simp add: zmod_int)\n      done\n    from assms have b:\n      \"nat_of_ipv4addr ((ipv4addr_of_nat (d + 256 * c + 65536 * b + 16777216 * a) >> 16) AND mask 8) = b\"\n      apply(simp add: ipv4addr_of_nat_def word_of_nat)\n      apply(simp add: nat_of_ipv4addr_def unat_def)\n      apply(simp add: and_mask_mod_2p)\n      apply(simp add: shiftr_div_2n)\n      apply(simp add: uint_word_of_int)\n      apply(simp add: NumberWang_IPv4.div65536[simplified])\n      (*The [simplified] is needed because Word_Lib adds some additional simp rules*)\n      done\n      \\<comment> \\<open>When @{file \\<open>../Word_Lib/Word_Lemmas.thy\\<close>} is imported,\n         some @{file \\<open>NumberWang_IPv4.thy\\<close>} lemmas need the\n         [simplified] attribute because @{text Word_Lib} adds some simp rules.\n         This theory should also work without @{file \\<open>../Word_Lib/Word_Lemmas.thy\\<close>}\\<close>\n    from assms have c:\n      \"nat_of_ipv4addr ((ipv4addr_of_nat (d + 256 * c + 65536 * b + 16777216 * a) >> 8) AND mask 8) = c\"\n      apply(simp add: ipv4addr_of_nat_def word_of_nat)\n      apply(simp add: nat_of_ipv4addr_def unat_def)\n      apply(simp add: and_mask_mod_2p)\n      apply(simp add: shiftr_div_2n)\n      apply(simp add: uint_word_of_int)\n      apply(simp add: NumberWang_IPv4.div256[simplified])\n      done\n    from \\<open>d < 256\\<close> have d: \"nat_of_ipv4addr (ipv4addr_of_nat (d + 256 * c + 65536 * b + 16777216 * a) AND mask 8) = d\"\n      apply(simp add: ipv4addr_of_nat_AND_mask8)\n      apply(simp add: ipv4addr_of_nat_def word_of_nat)\n      apply(simp add: nat_of_ipv4addr_def)\n      apply(subgoal_tac \"(d + 256 * c + 65536 * b + 16777216 * a) mod 256 = d\")\n       apply(simp add: unat_def uint_word_of_int; fail)\n      apply(simp add: NumberWang_IPv4.mod256)\n      done\n    from a b c d show ?thesis\n      apply(simp add: ipv4addr_of_dotdecimal.simps dotdecimal_of_ipv4addr.simps)\n      apply(simp add: mask_def)\n      done\n  qed\n\n  lemma ipv4addr_of_dotdecimal_dotdecimal_of_ipv4addr:\n    \"(ipv4addr_of_dotdecimal (dotdecimal_of_ipv4addr ip)) = ip\"\n  proof -\n    have ip_and_mask8_bl_drop24: \"(ip::ipv4addr) AND mask 8 = of_bl (drop 24 (to_bl ip))\"\n      by(simp add: Word_Lemmas.of_drop_to_bl size_ipv4addr)\n    have List_rev_drop_geqn: \"length x \\<ge> n \\<Longrightarrow> (take n (rev x)) = rev (drop (length x - n) x)\"\n      for x :: \"'a list\" and n by(simp add: List.rev_drop)\n    have and_mask_bl_take: \"length x \\<ge> n \\<Longrightarrow> ((of_bl x) AND mask n) = (of_bl (rev (take n (rev (x)))))\"\n      for x n by(simp add: List_rev_drop_geqn of_bl_drop)\n    have ipv4addr_and_255: \"x AND 255 = x AND mask 8\" for x :: ipv4addr\n      by(simp add: mask_def)\n    have bit_equality:\n      \"((ip >> 24) AND 0xFF << 24) + ((ip >> 16) AND 0xFF << 16) + ((ip >> 8) AND 0xFF << 8) + (ip AND 0xFF) =\n       of_bl (take 8 (to_bl ip) @ take 8 (drop 8 (to_bl ip)) @ take 8 (drop 16 (to_bl ip)) @ drop 24 (to_bl ip))\"\n      apply(simp add: ipv4addr_and_255)\n      apply(simp add: shiftr_slice)\n      apply(simp add: Word.slice_take' size_ipv4addr)\n      apply(simp add: and_mask_bl_take)\n      apply(simp add: List_rev_drop_geqn)\n      apply(simp add: drop_take)\n      apply(simp add: Word.shiftl_of_bl)\n      apply(simp add: of_bl_append)\n      apply(simp add: ip_and_mask8_bl_drop24)\n      done\n    have blip_split: \"\\<And> blip. length blip = 32 \\<Longrightarrow>\n      blip = (take 8 blip) @ (take 8 (drop 8 blip)) @ (take 8 (drop 16 blip)) @ (take 8 (drop 24 blip))\"\n      by(rename_tac blip,case_tac blip,simp_all)+ (*I'm so sorry for this ...*)\n    have \"ipv4addr_of_dotdecimal (dotdecimal_of_ipv4addr ip) = of_bl (to_bl ip)\"\n      apply(subst blip_split)\n       apply(simp; fail)\n      apply(simp add: ipv4addr_of_dotdecimal_bit dotdecimal_of_ipv4addr.simps)\n      apply(simp add: ipv4addr_of_nat_nat_of_ipv4addr)\n      apply(simp add: bit_equality)\n      done\n    thus ?thesis using Word.word_bl.Rep_inverse[symmetric] by simp\n  qed\n\n  lemma ipv4addr_of_dotdecimal_eqE:\n    \"\\<lbrakk> ipv4addr_of_dotdecimal (a,b,c,d) = ipv4addr_of_dotdecimal (e,f,g,h);\n       a < 256; b < 256; c < 256; d < 256; e < 256; f < 256; g < 256; h < 256 \\<rbrakk> \\<Longrightarrow>\n         a = e \\<and> b = f \\<and> c = g \\<and> d = h\"\n     by (metis Pair_inject dotdecimal_of_ipv4addr_ipv4addr_of_dotdecimal)\n\nsubsection\\<open>IP Ranges: Examples\\<close>\n  lemma \"(UNIV :: ipv4addr set) = {0 .. max_ipv4_addr}\" by(simp add: UNIV_ipv4addrset)\n  lemma \"(42::ipv4addr) \\<in> UNIV\" by(simp)\n\n  (*Warning, not executable!*)\n\n  lemma \"ipset_from_netmask (ipv4addr_of_dotdecimal (192,168,0,42)) (ipv4addr_of_dotdecimal (255,255,0,0)) =\n          {ipv4addr_of_dotdecimal (192,168,0,0) .. ipv4addr_of_dotdecimal (192,168,255,255)}\"\n   by(simp add: ipset_from_netmask_def ipv4addr_of_dotdecimal.simps ipv4addr_of_nat_def)\n\n  lemma \"ipset_from_netmask (ipv4addr_of_dotdecimal (192,168,0,42)) (ipv4addr_of_dotdecimal (0,0,0,0)) = UNIV\"\n    by(simp add: UNIV_ipv4addrset ipset_from_netmask_def ipv4addr_of_dotdecimal.simps\n                 ipv4addr_of_nat_def max_ipv4_addr_max_word)\n\n  text\\<open>192.168.0.0/24\\<close>\n\n  lemma fixes addr :: ipv4addr\n    shows \"ipset_from_cidr addr pflength =\n            ipset_from_netmask addr ((mask pflength) << (32 - pflength))\"\n    by(simp add: ipset_from_cidr_def)\n\n  lemma \"ipset_from_cidr (ipv4addr_of_dotdecimal (192,168,0,42)) 16 =\n          {ipv4addr_of_dotdecimal (192,168,0,0) .. ipv4addr_of_dotdecimal (192,168,255,255)}\"\n   by(simp add: ipset_from_cidr_alt mask_def  ipv4addr_of_dotdecimal.simps ipv4addr_of_nat_def)\n\n  lemma \"ip \\<in> (ipset_from_cidr (ipv4addr_of_dotdecimal (0, 0, 0, 0)) 0)\"\n    by(simp add: ipset_from_cidr_0)\n\n  lemma ipv4set_from_cidr_32: fixes addr :: ipv4addr\n    shows \"ipset_from_cidr addr 32 = {addr}\"\n    by(simp add: ipset_from_cidr_alt mask_def)\n\n  lemma  fixes pre :: ipv4addr\n    shows \"ipset_from_cidr pre len = {(pre AND ((mask len) << (32 - len))) .. pre OR (mask (32 - len))}\"\n    by (simp add: ipset_from_cidr_alt ipset_from_cidr_def)\n\n  text\\<open>making element check executable\\<close>\n  lemma addr_in_ipv4set_from_netmask_code[code_unfold]:\n    fixes addr :: ipv4addr\n    shows \"addr \\<in> (ipset_from_netmask base netmask) \\<longleftrightarrow>\n            (base AND netmask) \\<le> addr \\<and> addr \\<le> (base AND netmask) OR (NOT netmask)\"\n    by (simp add: addr_in_ipset_from_netmask_code)\n  lemma addr_in_ipv4set_from_cidr_code[code_unfold]:\n    fixes addr :: ipv4addr\n    shows \"addr \\<in> (ipset_from_cidr pre len) \\<longleftrightarrow>\n              (pre AND ((mask len) << (32 - len))) \\<le> addr \\<and> addr \\<le> pre OR (mask (32 - len))\"\n    by(simp add: addr_in_ipset_from_cidr_code)\n\n  (*small numbers because we didn't load Code_Target_Nat. Should work by eval*)\n  lemma \"ipv4addr_of_dotdecimal (192,168,42,8) \\<in> (ipset_from_cidr (ipv4addr_of_dotdecimal (192,168,0,0)) 16)\"\n    by(simp add: ipv4addr_of_dotdecimal.simps ipv4addr_of_nat_def ipset_from_cidr_def\n                    ipset_from_netmask_def mask_def)\n\n  definition ipv4range_UNIV :: \"32 wordinterval\" where \"ipv4range_UNIV \\<equiv> wordinterval_UNIV\"\n\n  lemma ipv4range_UNIV_set_eq: \"wordinterval_to_set ipv4range_UNIV = UNIV\"\n    by(simp only: ipv4range_UNIV_def wordinterval_UNIV_set_eq)\n\n\n  thm iffD1[OF wordinterval_eq_set_eq]\n  (*TODO: probably the following is a good idea?*)\n  (*\n  declare iffD1[OF wordinterval_eq_set_eq, cong]\n  *)\n\n\n  text\\<open>This \\<open>LENGTH('a)\\<close> is 32 for IPv4 addresses.\\<close>\n  lemma ipv4cidr_to_interval_simps[code_unfold]: \"ipcidr_to_interval ((pre::ipv4addr), len) = (\n      let netmask = (mask len) << (32 - len);\n          network_prefix = (pre AND netmask)\n      in (network_prefix, network_prefix OR (NOT netmask)))\"\n  by(simp add: ipcidr_to_interval_def Let_def ipcidr_to_interval_start.simps ipcidr_to_interval_end.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/IP_Addresses/IPv4.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8856314768368161, "lm_q2_score": 0.7956580927949806, "lm_q1q2_score": 0.7046598517791831}}
{"text": "theory Overtaking_Aux\n  imports Analysis \"Affine_Arithmetic/Polygon\"\nbegin\n      \ntype_synonym real2 = \"real \\<times> real\"\n        \ndefinition min2D :: \"real2 \\<Rightarrow> real2 \\<Rightarrow> real2\" where\n  \"min2D z1 z2 = (let x1 = fst z1; x2 = fst z2; y1 = snd z1; y2 = snd z2 in\n                    if x1 < x2 then z1 else\n                    if x1 = x2 then (if y1 \\<le> y2 then z1 else z2) else\n                    (* x1 > x2 *)   z2)\"\n  \ntheorem min2D_D:\n  assumes \"min2D x y = z\"\n  shows \"fst z \\<le> fst x \\<and> fst z \\<le> fst y\"\n  using assms unfolding min2D_def by smt\n    \ntheorem min2D_D2:\n  assumes \"min2D x y = z\"\n  shows \"z = x \\<or> z = y\"\n  using assms unfolding min2D_def by presburger\n\ntheorem min2D_D3:\n  assumes \"min2D x y = x\"\n  shows \"fst x < fst y \\<or> (fst x = fst y \\<and> snd x \\<le> snd y)\"\n  using assms unfolding min2D_def by smt  \n    \ntheorem min2D_D4:\n  assumes \"min2D x y = y\"\n  shows \"fst y < fst x \\<or> (fst x = fst y \\<and> snd y \\<le> snd x)\"\n  using assms unfolding min2D_def by smt \n\nsection \"Rectangle\"    \n  \nrecord rectangle = \n  Xcoord :: real\n  Ycoord :: real\n  Orient :: real\n  Length :: real\n  Width  :: real  \n              \ndefinition rotation_matrix' :: \"real \\<Rightarrow> real2 \\<Rightarrow> real2\" where\n  \"rotation_matrix' theta \\<equiv>  (\\<lambda>p :: real2. (cos theta * fst p - sin theta * snd p, \n                                             sin theta * fst p + cos theta * snd p))\"\n(* \ndefinition rotate_rect :: \"rectangle \\<Rightarrow> real2 \\<Rightarrow> real2\" where\n  \"rotate_rect rect \\<equiv> (let centre = (Xcoord rect, Ycoord rect); ori = Orient rect in \n                              (\\<lambda>p. p + centre) \\<circ> (rotation_matrix' ori) \\<circ> (\\<lambda>p. p - centre))\"   *)\n  \ndefinition rotate_rect :: \"rectangle \\<Rightarrow> real2 \\<Rightarrow> real2\" where\n  \"rotate_rect rect \\<equiv> (let centre = (Xcoord rect, Ycoord rect); ori = Orient rect in \n                                                                            (rotation_matrix' ori))\"    \n  \n(* the vertices are sorted in counter-clockwise manner *)    \ndefinition get_vertices :: \"rectangle \\<Rightarrow> real2 list\" where\n  \"get_vertices rect \\<equiv> (let x = Xcoord rect; y = Ycoord rect; l = Length rect; w = Width rect in \n                          [(x - l / 2, y + w / 2),\n                           (x - l / 2, y - w / 2),\n                           (x + l / 2, y - w / 2),\n                           (x + l / 2, y + w / 2)])\"\n\ndefinition get_vertices_zero :: \"rectangle \\<Rightarrow> real2 list\" where\n  \"get_vertices_zero rect \\<equiv> (let l = Length rect; w = Width rect in \n                          [(- l / 2,   w / 2),\n                           (- l / 2, - w / 2),\n                           (  l / 2, - w / 2),\n                           (  l / 2,   w / 2)])\"\n    \ntheorem \n  assumes \"vertices = get_vertices rect\"\n  assumes \"0 < Length rect\" and \"0 < Width rect\"  \n  shows \"ccw' (vertices ! 0) (vertices ! 1) (vertices ! 2)\"\nproof -\n  define x where \"x \\<equiv> Xcoord rect\"\n  define y where \"y \\<equiv> Ycoord rect\"\n  define l where \"l \\<equiv> Length rect\"\n  define w where \"w \\<equiv> Width rect\"      \n  note params = x_def y_def l_def w_def\n  from assms(2-3) have \"0 < l\" and \"0 < w\" unfolding params by auto  \n  from assms have 0: \"vertices ! 0 = (x - l / 2, y + w / 2)\" and 1: \"vertices ! 1 = (x - l/2, y - w/2)\"\n      and 2: \"vertices ! 2 = (x + l /2, y - w / 2)\"\n    unfolding get_vertices_def Let_def params by auto\n  have \"ccw' (vertices ! 0) (vertices ! 1) (vertices ! 2) = \n        ccw' 0 (vertices ! 1 - vertices ! 0) (vertices ! 2 - vertices ! 0)\" \n    unfolding ccw'_def using det3_translate_origin by auto    \n  also have \"... = ccw' 0 (0, -w) (l, -w)\" unfolding 0 1 2 by auto\n  finally have *: \"ccw' (vertices ! 0) (vertices ! 1) (vertices ! 2) = ccw' 0 (0,-w) (l,-w)\" by auto\n  have \"det3 0 (0,-w) (l,-w) =  w * l\" unfolding det3_def'  by (auto simp add:algebra_simps)   \n  with `0 < w` `0 < l` have \"0 < det3 0 (0,-w) (l,-w)\" by auto\n  hence \"ccw' 0 (0,-w) (l,-w)\" unfolding ccw'_def by auto\n  with * show ?thesis by auto  \nqed  \n  \ntheorem nbr_of_vertex:\n  \"length (get_vertices rect) = 4\"\n  unfolding get_vertices_def Let_def by auto \n    \ntheorem nbr_of_vertex_zero:\n  \"length (get_vertices_zero rect) = 4\"\n  unfolding get_vertices_zero_def Let_def by auto \n        \ndefinition get_vertices_rotated :: \"rectangle \\<Rightarrow> real2 list\" where\n  \"get_vertices_rotated rect \\<equiv> map (rotation_matrix' (Orient rect)) (get_vertices_zero rect)\"  \n  \ntheorem nbr_of_vertex_rotated:\n  \"length (get_vertices_rotated rect) = 4\"\n  unfolding get_vertices_rotated_def using length_map nbr_of_vertex_zero by auto\n\ndefinition get_vertices_rotated_translated :: \"rectangle \\<Rightarrow> real2 list\" where\n  \"get_vertices_rotated_translated rect \\<equiv> \n                               map (\\<lambda>p. p + (Xcoord rect, Ycoord rect)) (get_vertices_rotated rect)\"\n\ntheorem nbr_of_vertex_rotated_translated:\n  \"length (get_vertices_rotated_translated rect) = 4\"\n  unfolding get_vertices_rotated_translated_def using length_map nbr_of_vertex_rotated by auto  \n        \ndefinition get_lines :: \"rectangle \\<Rightarrow> (real2 \\<times> real2) list\" where\n  \"get_lines rect \\<equiv> (let vertices = get_vertices_rotated_translated rect; \n                         zero = vertices ! 0; one = vertices ! 1; \n                         two = vertices ! 2; three = vertices ! 3                  \n                      in \n                        [(zero, one), (one, two), (two, three), (three, zero)])\"\n  \ntheorem nbr_of_lines:\n  \"length (get_lines rect) = 4\"\n  unfolding get_lines_def unfolding Let_def by auto  \n  \n(* Definition of point inside a rectangle *)\ndefinition inside_rectangle :: \"real2 \\<Rightarrow> rectangle \\<Rightarrow> bool\" where\n  \"inside_rectangle p rect \\<equiv> (let lines = get_lines rect;\n                                line0 = lines ! 0; line1 = lines ! 1; line2 = lines ! 2; line3 = lines ! 3\n                              in \n                                ccw' p (fst line0) (snd line0) \\<and> ccw' p (fst line1) (snd line1) \\<and> \n                                ccw' p (fst line2) (snd line2) \\<and> ccw' p (fst line3) (snd line3))\"\n                                        \ntheorem centre_point_inside: \n  assumes \"0 < Length rect\" and \"0 < Width rect\" \n  shows \"inside_rectangle (Xcoord rect, Ycoord rect) rect\"\nproof -\n  define x where \"x \\<equiv> Xcoord rect\"\n  define y where \"y \\<equiv> Ycoord rect\"\n  define l where \"l \\<equiv> Length rect\"\n  define w where \"w \\<equiv> Width rect\"      \n  note params = x_def y_def l_def w_def \n  from assms have \"0 < l\" and \"0 < w\" unfolding params by auto\n      \n  define zero where \"zero \\<equiv> get_vertices_rotated_translated rect ! 0\"    \n  define one where \"one \\<equiv> get_vertices_rotated_translated rect ! 1\"\n  define two where \"two \\<equiv> get_vertices_rotated_translated rect ! 2\"\n  define three where \"three \\<equiv> get_vertices_rotated_translated rect ! 3\"\n  note vertices_def = zero_def one_def two_def three_def  \n  have \"zero = rotation_matrix' (Orient rect) (- l / 2, w / 2) + (x,y)\" and \n       \"one = rotation_matrix' (Orient rect) (- l / 2, - w / 2) + (x,y)\" and\n       \"two = rotation_matrix' (Orient rect) (l / 2, - w / 2) + (x,y)\" and \n       \"three = rotation_matrix' (Orient rect) (l / 2, w / 2) + (x,y)\"\n    unfolding vertices_def get_vertices_rotated_translated_def get_vertices_rotated_def\n      get_vertices_zero_def Let_def params by auto      \n  define line0 where \"line0 \\<equiv> get_lines rect ! 0\"    \n  define line1 where \"line1 \\<equiv> get_lines rect ! 1\"\n  define line2 where \"line2 \\<equiv> get_lines rect ! 2\"\n  define line3 where \"line3 \\<equiv> get_lines rect ! 3\"\n  note lines_def = line0_def line1_def line2_def line3_def    \n  have \"line0 = (zero,one)\" \"line1 = (one,two)\" \"line2 = (two, three)\" \"line3 = (three, zero)\"\n    unfolding lines_def get_lines_def Let_def vertices_def by auto\n \n  have \"ccw' (x,y) (fst line0) (snd line0)\" sorry\n  moreover      \n  have \"ccw' (x,y) (fst line1) (snd line1)\" sorry\n  moreover    \n  have \"ccw' (x,y) (fst line2) (snd line2)\" sorry\n  moreover\n  have \"ccw' (x,y) (fst line3) (snd line3)\" sorry\n  ultimately show ?thesis unfolding inside_rectangle_def Let_def params lines_def by auto      \nqed\n  \n    \n    \n    \n      \nend", "meta": {"author": "rizaldialbert", "repo": "overtaking", "sha": "0e76426d75f791635cd9e23b8e07669b7ce61a81", "save_path": "github-repos/isabelle/rizaldialbert-overtaking", "path": "github-repos/isabelle/rizaldialbert-overtaking/overtaking-0e76426d75f791635cd9e23b8e07669b7ce61a81/Overtaking_Aux.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8856314677809303, "lm_q2_score": 0.7956581000631541, "lm_q1q2_score": 0.7046598510107174}}
{"text": "theory PPL_Summer_School_2017\n  imports Main\nbegin\n  \n(* Pure *)  \n  \nlemma name: \"\\<And>P. P \\<Longrightarrow> P\"\nproof-\n  fix P\n  assume 1: \"P\"\n  show \"P\" by (rule 1)\nqed \n  \nlemma name2:\n  fixes P shows \"P \\<Longrightarrow> P\"\nproof-\n  assume 1: \"P\"\n  show \"P\" by (rule 1)\nqed\n  \nlemma name3:\n  fixes P assumes 1: \"P\" shows \"P\"\n  by (rule 1)\n  \nlemma mp_Pure:\n  \"\\<And> P Q. P \\<Longrightarrow> (P \\<Longrightarrow> Q) \\<Longrightarrow> Q\"\nproof-\n  fix P Q\n  assume 1: \"P\"\n  assume 2: \"P \\<Longrightarrow> Q\"\n  show \"Q\"\n    (* by (rule 2, rule 1) *)\n  proof (rule 2)\n    show \"P\" by (rule 1)\n  qed\nqed\n  \nlemma mp_Pure_short:\n  fixes P Q \n  assumes 1: \"P\"\n  assumes 2: \"P \\<Longrightarrow> Q\" shows \"Q\" by (rule 2, rule 1)\n    \n(* HOL *)\n    \nterm \"True\"\nterm \"False\"\nterm \"~ x\"\nterm \"x \\<longrightarrow> y\"\nterm \"x \\<and> y\"\nterm \"\\<forall>x :: nat. P x \\<or> ~ P x\"\n  \nlemma True_HOL: \"True\" by (rule HOL.TrueI)\n    \nlemma \"~ False\"\n  find_theorems \"(_ \\<Longrightarrow> False) \\<Longrightarrow> ~ _\"\n(* by (rule HOL.notI) *)\nproof (rule notI)\n  assume 1: \"False\"\n  show \"False\" by (rule 1)\nqed\n  \nlemma \"\\<forall>p. p \\<longrightarrow> p\"\n  find_theorems \"(\\<And>_. _) \\<Longrightarrow> \\<forall>_. _\" \nproof (rule allI) (* by (intro allI impI) *)\n  fix p\n  show \"p \\<longrightarrow> p\"\n  by (rule impI)\nqed\n  \nlemma \"\\<forall>p q. p \\<longrightarrow> (p \\<longrightarrow> q) \\<longrightarrow> q\"\nproof (intro allI impI)\n  find_theorems \"PROP _ \\<Longrightarrow> (_ \\<longrightarrow> _)\"\n  fix p q\n  assume 1: \"p\"\n  assume 2: \"p \\<longrightarrow> q\"\n    have 3: \"p \\<Longrightarrow> q\" using 2 by (elim impE)\n    show \"q\" by (rule 3, rule 1)\nqed\n    \nterm my_True\n  \ndefinition my_True where \"my_True = True\"\n  \nterm my_True\n  \nlemma \"my_True = True\"\n  by (rule my_True_def)\n    \nlemma \"my_True\"\n  unfolding my_True_def by (rule TrueI)\n    \ndefinition my_id where \"my_id x = x\"\n  \nlemma \"my_id x = x\" by (rule my_id_def)\n    \nlemma \"my_id (my_id x) = x\"\n  unfolding my_id_def by (rule refl)\n    \nlemma \"my_id (my_id x) = x\" by (simp add: my_id_def)\n    \ndeclare my_id_def[simp]\n  \ndefinition my_id2 where \"my_id2 = (\\<lambda>x. x)\"\n  \ndeclare my_id2_def[simp]\n  \n(* lemma \"my_id = my_id2\" \n  unfolding my_id_def my_id2_def by (rule refl) *)\n  \nlemma \"my_id = my_id2\" \n  by auto\n   \n(* List *)\n    \nterm \"[]\"\nterm \"x#xs\"\n  \nvalue \"[1::int, 2, 3, 4] ! 6\"\n  \ndefinition my_sorted (* :: \"int list \\<Rightarrow> bool\" *)\n  where \"my_sorted xs = (\n    \\<forall> i j. i < j \\<longrightarrow>  j < length xs\n    \\<longrightarrow> ~ (xs!i > xs!j))\"\n    \nlemma my_sortedI [intro]:\n  (* fixes xs *)\n  assumes 1: \"\\<And> i j. i < j \\<Longrightarrow> j < length xs \\<Longrightarrow>\n     ~ (xs!i > xs!j)\"\n  shows \"my_sorted xs\"\n  unfolding my_sorted_def\n  using 1 by auto\n    \nlemma my_sortedD [dest]:\n  fixes xs\n  assumes 1: \"my_sorted xs\"\n  shows \"\\<And>i j. i < j \\<Longrightarrow> j < length xs \\<Longrightarrow> \n        ~ (xs!i > xs!j)\"\n  using 1 unfolding my_sorted_def by auto\n    \nlemma my_sortedE [elim]:\n  fixes xs\n  assumes 1: \"my_sorted xs\"\n  assumes 2: \"(\\<And>i j. i < j \\<Longrightarrow> j < length xs \\<Longrightarrow> \n              ~ (xs!i > xs!j)) \\<Longrightarrow> P\"\n  shows \"P\"\n  using 1 2 unfolding my_sorted_def by auto\n    \nfun my_insert (* :: \"int \\<Rightarrow> int list \\<Rightarrow> int list\" *)\n  where \"my_insert x [] = [x]\"\n  |     \"my_insert x (y#ys) = \n        (if x \\<le> y then x # y # ys \n         else y # my_insert x ys)\"\n    \nfun my_sort (* :: \"int list \\<Rightarrow> int list\" *)\n  where \"my_sort [] = []\"\n  |     \"my_sort (x#xs) = my_insert x (my_sort xs)\"\n      \nvalue \"my_sort [1::int,5,3,8]\"\n  \nvalue \"my_sort [1,5,8,3::int]\"\n    \nvalue \"my_sort [3,7,5,1,9]\"\n  \nterm \"set xs\"\n  \nlemma my_sorted_Cons' [simp]:\n  assumes 1: \"my_sorted xs\"\n  assumes 2: \"\\<And>y. y \\<in> set xs \\<Longrightarrow> ~ (x > y)\"\n  shows \"my_sorted (x#xs)\" \nproof (rule my_sortedI)\n  fix i j :: \"nat\"\n  assume 3: \"i < j\"\n  assume 4: \"j < length (x#xs)\"\n  show \"~ ((x # xs) ! i > (x # xs) ! j)\"\n    \n  proof (cases i) \n    case 0\n    then show ?thesis using 1 2 3 4 by auto\n  next\n    case (Suc nat)\n    then show ?thesis using 1 2 3 4 by auto\n  qed\nqed \n  \nlemma my_sorted_Cons [simp]:\n  \"my_sorted (x#xs) \\<longleftrightarrow> \n   my_sorted xs \\<and> (\\<forall>y \\<in> set xs. ~ (x > y))\"\nproof (intro iffI)\n  assume 1: \"my_sorted xs \\<and> (\\<forall>y \\<in> set xs. ~ (x > y))\"\n  show \"my_sorted (x#xs)\"\n    using 1 by (intro my_sorted_Cons', auto)\nnext\n  assume 1: \"my_sorted (x#xs)\"\n  show \"my_sorted xs \\<and> (\\<forall>y \\<in> set xs. ~ (x > y))\"\n  proof (intro conjI)\n    show \"my_sorted xs\" (* using 1 by blast *)\n      apply (intro my_sortedI) \n      using \"1\" sorted_nth_monoI by auto\n  next\n    show \"\\<forall>y \\<in> set xs. ~ (x > y)\"\n    proof (intro ballI)\n      fix y\n      assume 2: \"y \\<in> set xs\"\n      obtain i where 3: \"xs ! i = y\" and 4: \"i < length xs\"\n        by (meson \"2\" in_set_conv_nth)\n        \n      show \"~ (x > y)\" \n        using 1 2 3 4 by auto\n    qed\n  qed\nqed     \n  \nlemma set_my_insert [simp]: \n  \"set (my_insert x xs) = set xs \\<union> {x}\"\nby (induct xs, auto)\n  \nlemma my_sorted_my_insert [intro]:\n  fixes xs :: \"('a ::preorder) list\"\n  assumes 1: \"my_sorted xs\"\n  shows \"my_sorted (my_insert x xs)\"\n  using 1 \n  apply (induct xs, auto)\n  apply (simp add: less_le_not_le)\n  apply (meson less_le_trans)\n  by (simp add: less_imp_le)\n    \ntheorem my_sorted_my_sort:\n  fixes xs :: \"('a :: preorder) list\"\n  shows \"my_sorted (my_sort xs)\"\nby (induct xs, auto)\n\ncorollary \n  fixes xs :: \"int list\"\n  shows \"my_sorted (my_sort xs)\"\n  by (rule my_sorted_my_sort)\n    \nexport_code my_sort in OCaml\nexport_code my_sort in Haskell\n  \ndefinition my_sort_integer :: \n  \"integer list \\<Rightarrow> integer list\"\n  where \"my_sort_integer = my_sort\"\n    \nexport_code my_sort_integer in OCaml\nexport_code my_sort_integer in Haskell\n  \ninstantiation char :: ord\nbegin\ndefinition less_eq_char where\n  \"less_eq_char a b = (nat_of_char a \\<le> nat_of_char b)\"\ndefinition less_char where\n  \"less_char a b = (nat_of_char a < nat_of_char b)\"\ninstance by (intro_classes)\nend\n  \ndeclare less_eq_char_def [simp]\ndeclare less_char_def [simp]\n  \nvalue \"my_sort [CHR ''r'', CHR ''a'', CHR ''b'']\n\ninstance char :: lineorder\nby (intro_classes, auto)\n\ncorollary \nfixes xs :: \"char list\"\nshows \"my_sorted (my_sort xs)\"\nby (rule my_sorted_my_sort)  \n \nend", "meta": {"author": "awazoooo", "repo": "PPL_Summer_School2017", "sha": "83de41680237f11d3cd51e3fa820018ed9196bdf", "save_path": "github-repos/isabelle/awazoooo-PPL_Summer_School2017", "path": "github-repos/isabelle/awazoooo-PPL_Summer_School2017/PPL_Summer_School2017-83de41680237f11d3cd51e3fa820018ed9196bdf/PPL_Summer_School_2017.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.828938825225204, "lm_q2_score": 0.8499711794579723, "lm_q1q2_score": 0.7045741109751726}}
{"text": "(*  Title:      Well-Quasi-Orders\n    Author:     Christian Sternagel <c.sternagel@gmail.com>\n    Maintainer: Christian Sternagel\n    License:    LGPL\n*)\n\nsection \\<open>Constructing Minimal Bad Sequences\\<close>\n\ntheory Minimal_Bad_Sequences\nimports\n  Almost_Full\n  Minimal_Elements\nbegin\n\ntext \\<open>\n  A locale capturing the construction of minimal bad sequences over values from @{term \"A\"}. Where\n  minimality is to be understood w.r.t.\\ @{term size} of an element.\n\\<close>\nlocale mbs =\n  fixes A :: \"('a :: size) set\"\nbegin\n\ntext \\<open>\n  Since the @{term size} is a well-founded measure, whenever some element satisfies a property\n  @{term P}, then there is a size-minimal such element.\n\\<close>\nlemma minimal:\n  assumes \"x \\<in> A\" and \"P x\"\n  shows \"\\<exists>y \\<in> A. size y \\<le> size x \\<and> P y \\<and> (\\<forall>z \\<in> A. size z < size y \\<longrightarrow> \\<not> P z)\"\nusing assms\nproof (induction x taking: size rule: measure_induct)\n  case (1 x)\n  then show ?case\n  proof (cases \"\\<forall>y \\<in> A. size y < size x \\<longrightarrow> \\<not> P y\")\n    case True\n    with 1 show ?thesis by blast\n  next\n    case False\n    then obtain y where \"y \\<in> A\" and \"size y < size x\" and \"P y\" by blast\n    with \"1.IH\" show ?thesis by (fastforce elim!: order_trans)\n  qed\nqed\n\nlemma less_not_eq [simp]:\n  \"x \\<in> A \\<Longrightarrow> size x < size y \\<Longrightarrow> x = y \\<Longrightarrow> False\"\n  by simp\n\ntext \\<open>\n  The set of all bad sequences over @{term A}.\n\\<close>\ndefinition \"BAD P = {f \\<in> SEQ A. bad P f}\"\n\nlemma BAD_iff [iff]:\n  \"f \\<in> BAD P \\<longleftrightarrow> (\\<forall>i. f i \\<in> A) \\<and> bad P f\"\n  by (auto simp: BAD_def)\n\ntext \\<open>\n  A partial order on infinite bad sequences.\n\\<close>\ndefinition geseq :: \"((nat \\<Rightarrow> 'a) \\<times> (nat \\<Rightarrow> 'a)) set\"\nwhere\n  \"geseq =\n    {(f, g). f \\<in> SEQ A \\<and> g \\<in> SEQ A \\<and> (f = g \\<or> (\\<exists>i. size (g i) < size (f i) \\<and> (\\<forall>j < i. f j = g j)))}\"\n\ntext \\<open>\n  The strict part of the above order.\n\\<close>\ndefinition gseq :: \"((nat \\<Rightarrow> 'a) \\<times> (nat \\<Rightarrow> 'a)) set\" where\n  \"gseq = {(f, g). f \\<in> SEQ A \\<and> g \\<in> SEQ A \\<and> (\\<exists>i. size (g i) < size (f i) \\<and> (\\<forall>j < i. f j = g j))}\"\n\nlemma geseq_iff:\n  \"(f, g) \\<in> geseq \\<longleftrightarrow>\n    f \\<in> SEQ A \\<and> g \\<in> SEQ A \\<and> (f = g \\<or> (\\<exists>i. size (g i) < size (f i) \\<and> (\\<forall>j < i. f j = g j)))\"\n  by (auto simp: geseq_def)\n\nlemma gseq_iff:\n  \"(f, g) \\<in> gseq \\<longleftrightarrow> f \\<in> SEQ A \\<and> g \\<in> SEQ A \\<and> (\\<exists>i. size (g i) < size (f i) \\<and> (\\<forall>j < i. f j = g j))\"\n  by (auto simp: gseq_def)\n\nlemma geseqE:\n  assumes \"(f, g) \\<in> geseq\"\n    and \"\\<lbrakk>\\<forall>i. f i \\<in> A; \\<forall>i. g i \\<in> A; f = g\\<rbrakk> \\<Longrightarrow> Q\"\n    and \"\\<And>i. \\<lbrakk>\\<forall>i. f i \\<in> A; \\<forall>i. g i \\<in> A; size (g i) < size (f i); \\<forall>j < i. f j = g j\\<rbrakk> \\<Longrightarrow> Q\"\n  shows \"Q\"\n  using assms by (auto simp: geseq_iff)\n\nlemma gseqE:\n  assumes \"(f, g) \\<in> gseq\"\n    and \"\\<And>i. \\<lbrakk>\\<forall>i. f i \\<in> A; \\<forall>i. g i \\<in> A; size (g i) < size (f i); \\<forall>j < i. f j = g j\\<rbrakk> \\<Longrightarrow> Q\"\n  shows \"Q\"\n  using assms by (auto simp: gseq_iff)\n\nsublocale min_elt_size?: minimal_element \"measure_on size UNIV\" A\nrewrites \"measure_on size UNIV \\<equiv> \\<lambda>x y. size x < size y\"\napply (unfold_locales)\napply (auto simp: po_on_def irreflp_on_def transp_on_def simp del: wfp_on_UNIV intro: wfp_on_subset)\napply (auto simp: measure_on_def inv_image_betw_def)\ndone\n\ncontext\n  fixes P :: \"'a \\<Rightarrow> 'a \\<Rightarrow> bool\"\nbegin\n\ntext \\<open>\n  A lower bound to all sequences in a set of sequences @{term B}.\n\\<close>\nabbreviation \"lb \\<equiv> lexmin (BAD P)\"\n\nlemma eq_upto_BAD_mem:\n  assumes \"f \\<in> eq_upto (BAD P) g i\"\n  shows \"f j \\<in> A\"\n  using assms by (auto)\n\ntext \\<open>\n  Assume that there is some infinite bad sequence @{term h}.\n\\<close>\ncontext\n  fixes h :: \"nat \\<Rightarrow> 'a\"\n  assumes BAD_ex: \"h \\<in> BAD P\"\nbegin\n\ntext \\<open>\n  When there is a bad sequence, then filtering @{term \"BAD P\"} w.r.t.~positions in @{term lb} never\n  yields an empty set of sequences.\n\\<close>\nlemma eq_upto_BAD_non_empty:\n  \"eq_upto (BAD P) lb i \\<noteq> {}\"\nusing eq_upto_lexmin_non_empty [of \"BAD P\"] and BAD_ex by auto\n\nlemma non_empty_ith:\n  shows \"ith (eq_upto (BAD P) lb i) i \\<subseteq> A\"\n  and \"ith (eq_upto (BAD P) lb i) i \\<noteq> {}\"\n  using eq_upto_BAD_non_empty [of i] by auto\n\nlemmas\n  lb_minimal = min_elt_minimal [OF non_empty_ith, folded lexmin] and\n  lb_mem = min_elt_mem [OF non_empty_ith, folded lexmin]\n\ntext \\<open>\n  @{term \"lb\"} is a infinite bad sequence.\n\\<close>\nlemma lb_BAD:\n  \"lb \\<in> BAD P\"\nproof -\n  have *: \"\\<And>j. lb j \\<in> ith (eq_upto (BAD P) lb j) j\" by (rule lb_mem)\n  then have \"\\<forall>i. lb i \\<in> A\" by (auto simp: ith_conv) (metis eq_upto_BAD_mem)\n  moreover\n  { assume \"good P lb\"\n    then obtain i j where \"i < j\" and \"P (lb i) (lb j)\" by (auto simp: good_def)\n    from * have \"lb j \\<in> ith (eq_upto (BAD P) lb j) j\" by (auto)\n    then obtain g where \"g \\<in> eq_upto (BAD P) lb j\" and \"g j = lb j\" by force\n    then have \"\\<forall>k \\<le> j. g k = lb k\" by (auto simp: order_le_less)\n    with \\<open>i < j\\<close> and \\<open>P (lb i) (lb j)\\<close> have \"P (g i) (g j)\" by auto\n    with \\<open>i < j\\<close> have \"good P g\" by (auto simp: good_def)\n    with \\<open>g \\<in> eq_upto (BAD P) lb j\\<close> have False by auto }\n  ultimately show ?thesis by blast\nqed\n\ntext \\<open>\n  There is no infinite bad sequence that is strictly smaller than @{term lb}.\n\\<close>\nlemma lb_lower_bound:\n  \"\\<forall>g. (lb, g) \\<in> gseq \\<longrightarrow> g \\<notin> BAD P\"\nproof (intro allI impI)\n  fix g\n  assume \"(lb, g) \\<in> gseq\"\n  then obtain i where \"g i \\<in> A\" and \"size (g i) < size (lb i)\"\n    and \"\\<forall>j < i. lb j = g j\" by (auto simp: gseq_iff)\n  moreover with lb_minimal\n    have \"g i \\<notin> ith (eq_upto (BAD P) lb i) i\" by auto\n  ultimately show \"g \\<notin> BAD P\" by blast\nqed\n\ntext \\<open>\n  If there is at least one bad sequence, then there is also a minimal one.\n\\<close>\nlemma lower_bound_ex:\n  \"\\<exists>f \\<in> BAD P. \\<forall>g. (f, g) \\<in> gseq \\<longrightarrow> g \\<notin> BAD P\"\n  using lb_BAD and lb_lower_bound by blast\n\nlemma gseq_conv:\n  \"(f, g) \\<in> gseq \\<longleftrightarrow> f \\<noteq> g \\<and> (f, g) \\<in> geseq\"\n  by (auto simp: gseq_def geseq_def dest: less_not_eq)\n\ntext \\<open>There is a minimal bad sequence.\\<close>\nlemma mbs:\n  \"\\<exists>f \\<in> BAD P. \\<forall>g. (f, g) \\<in> gseq \\<longrightarrow> good P g\"\n  using lower_bound_ex by (auto simp: gseq_conv geseq_iff)\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/Well_Quasi_Orders/Minimal_Bad_Sequences.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8499711870587668, "lm_q2_score": 0.828938806208442, "lm_q1q2_score": 0.7045741011120665}}
{"text": "(* Author: Tobias Nipkow *)\n\nsubsection \"Interval Analysis\"\n\ntheory Abs_Int2_ivl\nimports Abs_Int2\nbegin\n\ntype_synonym eint = \"int extended\"\ntype_synonym eint2 = \"eint * eint\"\n\ndefinition \\<gamma>_rep :: \"eint2 \\<Rightarrow> int set\" where\n\"\\<gamma>_rep p = (let (l,h) = p in {i. l \\<le> Fin i \\<and> Fin i \\<le> h})\"\n\ndefinition eq_ivl :: \"eint2 \\<Rightarrow> eint2 \\<Rightarrow> bool\" where\n\"eq_ivl p1 p2 = (\\<gamma>_rep p1 = \\<gamma>_rep p2)\"\n\nlemma refl_eq_ivl[simp]: \"eq_ivl p p\"\nby(auto simp: eq_ivl_def)\n\nquotient_type ivl = eint2 / eq_ivl\nby(rule equivpI)(auto simp: reflp_def symp_def transp_def eq_ivl_def)\n\nabbreviation ivl_abbr :: \"eint \\<Rightarrow> eint \\<Rightarrow> ivl\" (\"[_, _]\") where\n\"[l,h] == abs_ivl(l,h)\"\n\nlift_definition \\<gamma>_ivl :: \"ivl \\<Rightarrow> int set\" is \\<gamma>_rep\nby(simp add: eq_ivl_def)\n\nlemma \\<gamma>_ivl_nice: \"\\<gamma>_ivl[l,h] = {i. l \\<le> Fin i \\<and> Fin i \\<le> h}\"\nby transfer (simp add: \\<gamma>_rep_def)\n\nlift_definition num_ivl :: \"int \\<Rightarrow> ivl\" is \"\\<lambda>i. (Fin i, Fin i)\" .\n\nlift_definition in_ivl :: \"int \\<Rightarrow> ivl \\<Rightarrow> bool\"\n  is \"\\<lambda>i (l,h). l \\<le> Fin i \\<and> Fin i \\<le> h\"\nby(auto simp: eq_ivl_def \\<gamma>_rep_def)\n\nlemma in_ivl_nice: \"in_ivl i [l,h] = (l \\<le> Fin i \\<and> Fin i \\<le> h)\"\nby transfer simp\n\ndefinition is_empty_rep :: \"eint2 \\<Rightarrow> bool\" where\n\"is_empty_rep p = (let (l,h) = p in l>h | l=Pinf & h=Pinf | l=Minf & h=Minf)\"\n\nlemma \\<gamma>_rep_cases: \"\\<gamma>_rep p = (case p of (Fin i,Fin j) => {i..j} | (Fin i,Pinf) => {i..} |\n  (Minf,Fin i) \\<Rightarrow> {..i} | (Minf,Pinf) \\<Rightarrow> UNIV | _ \\<Rightarrow> {})\"\nby(auto simp add: \\<gamma>_rep_def split: prod.splits extended.splits)\n\nlift_definition  is_empty_ivl :: \"ivl \\<Rightarrow> bool\" is is_empty_rep\napply(auto simp: eq_ivl_def \\<gamma>_rep_cases is_empty_rep_def)\napply(auto simp: not_less less_eq_extended_case split: extended.splits)\ndone\n\nlemma eq_ivl_iff: \"eq_ivl p1 p2 = (is_empty_rep p1 & is_empty_rep p2 | p1 = p2)\"\nby(auto simp: eq_ivl_def is_empty_rep_def \\<gamma>_rep_cases Icc_eq_Icc split: prod.splits extended.splits)\n\ndefinition empty_rep :: eint2 where \"empty_rep = (Pinf,Minf)\"\n\nlift_definition empty_ivl :: ivl is empty_rep .\n\nlemma is_empty_empty_rep[simp]: \"is_empty_rep empty_rep\"\nby(auto simp add: is_empty_rep_def empty_rep_def)\n\nlemma is_empty_rep_iff: \"is_empty_rep p = (\\<gamma>_rep p = {})\"\nby(auto simp add: \\<gamma>_rep_cases is_empty_rep_def split: prod.splits extended.splits)\n\ndeclare is_empty_rep_iff[THEN iffD1, simp]\n\n\ninstantiation ivl :: semilattice_sup_top\nbegin\n\ndefinition le_rep :: \"eint2 \\<Rightarrow> eint2 \\<Rightarrow> bool\" where\n\"le_rep p1 p2 = (let (l1,h1) = p1; (l2,h2) = p2 in\n  if is_empty_rep(l1,h1) then True else\n  if is_empty_rep(l2,h2) then False else l1 \\<ge> l2 & h1 \\<le> h2)\"\n\nlemma le_iff_subset: \"le_rep p1 p2 \\<longleftrightarrow> \\<gamma>_rep p1 \\<subseteq> \\<gamma>_rep p2\"\napply rule\napply(auto simp: is_empty_rep_def le_rep_def \\<gamma>_rep_def split: if_splits prod.splits)[1]\napply(auto simp: is_empty_rep_def \\<gamma>_rep_cases le_rep_def)\napply(auto simp: not_less split: extended.splits)\ndone\n\nlift_definition less_eq_ivl :: \"ivl \\<Rightarrow> ivl \\<Rightarrow> bool\" is le_rep\nby(auto simp: eq_ivl_def le_iff_subset)\n\ndefinition less_ivl where \"i1 < i2 = (i1 \\<le> i2 \\<and> \\<not> i2 \\<le> (i1::ivl))\"\n\nlemma le_ivl_iff_subset: \"iv1 \\<le> iv2 \\<longleftrightarrow> \\<gamma>_ivl iv1 \\<subseteq> \\<gamma>_ivl iv2\"\nby transfer (rule le_iff_subset)\n\ndefinition sup_rep :: \"eint2 \\<Rightarrow> eint2 \\<Rightarrow> eint2\" where\n\"sup_rep p1 p2 = (if is_empty_rep p1 then p2 else if is_empty_rep p2 then p1\n  else let (l1,h1) = p1; (l2,h2) = p2 in  (min l1 l2, max h1 h2))\"\n\nlift_definition sup_ivl :: \"ivl \\<Rightarrow> ivl \\<Rightarrow> ivl\" is sup_rep\nby(auto simp: eq_ivl_iff sup_rep_def)\n\nlift_definition top_ivl :: ivl is \"(Minf,Pinf)\" .\n\nlemma is_empty_min_max:\n  \"\\<not> is_empty_rep (l1,h1) \\<Longrightarrow> \\<not> is_empty_rep (l2, h2) \\<Longrightarrow> \\<not> is_empty_rep (min l1 l2, max h1 h2)\"\nby(auto simp add: is_empty_rep_def max_def min_def split: if_splits)\n\ninstance\nproof (standard, goal_cases)\n  case 1 show ?case by (rule less_ivl_def)\nnext\n  case 2 show ?case by transfer (simp add: le_rep_def split: prod.splits)\nnext\n  case 3 thus ?case by transfer (auto simp: le_rep_def split: if_splits)\nnext\n  case 4 thus ?case by transfer (auto simp: le_rep_def eq_ivl_iff split: if_splits)\nnext\n  case 5 thus ?case by transfer (auto simp add: le_rep_def sup_rep_def is_empty_min_max)\nnext\n  case 6 thus ?case by transfer (auto simp add: le_rep_def sup_rep_def is_empty_min_max)\nnext\n  case 7 thus ?case by transfer (auto simp add: le_rep_def sup_rep_def)\nnext\n  case 8 show ?case by transfer (simp add: le_rep_def is_empty_rep_def)\nqed\n\nend\n\ntext\\<open>Implement (naive) executable equality:\\<close>\ninstantiation ivl :: equal\nbegin\n\ndefinition equal_ivl where\n\"equal_ivl i1 (i2::ivl) = (i1\\<le>i2 \\<and> i2 \\<le> i1)\"\n\ninstance\nproof (standard, goal_cases)\n  case 1 show ?case by(simp add: equal_ivl_def eq_iff)\nqed\n\nend\n\n\n\ninstantiation ivl :: bounded_lattice\nbegin\n\ndefinition inf_rep :: \"eint2 \\<Rightarrow> eint2 \\<Rightarrow> eint2\" where\n\"inf_rep p1 p2 = (let (l1,h1) = p1; (l2,h2) = p2 in (max l1 l2, min h1 h2))\"\n\nlemma \\<gamma>_inf_rep: \"\\<gamma>_rep(inf_rep p1 p2) = \\<gamma>_rep p1 \\<inter> \\<gamma>_rep p2\"\nby(auto simp:inf_rep_def \\<gamma>_rep_cases split: prod.splits extended.splits)\n\nlift_definition inf_ivl :: \"ivl \\<Rightarrow> ivl \\<Rightarrow> ivl\" is inf_rep\nby(auto simp: \\<gamma>_inf_rep eq_ivl_def)\n\nlemma \\<gamma>_inf: \"\\<gamma>_ivl (iv1 \\<sqinter> iv2) = \\<gamma>_ivl iv1 \\<inter> \\<gamma>_ivl iv2\"\nby transfer (rule \\<gamma>_inf_rep)\n\ndefinition \"\\<bottom> = empty_ivl\"\n\ninstance\nproof (standard, goal_cases)\n  case 1 thus ?case by (simp add: \\<gamma>_inf le_ivl_iff_subset)\nnext\n  case 2 thus ?case by (simp add: \\<gamma>_inf le_ivl_iff_subset)\nnext\n  case 3 thus ?case by (simp add: \\<gamma>_inf le_ivl_iff_subset)\nnext\n  case 4 show ?case\n    unfolding bot_ivl_def by transfer (auto simp: le_iff_subset)\nqed\n\nend\n\n\nlemma eq_ivl_empty: \"eq_ivl p empty_rep = is_empty_rep p\"\nby (metis eq_ivl_iff is_empty_empty_rep)\n\nlemma le_ivl_nice: \"[l1,h1] \\<le> [l2,h2] \\<longleftrightarrow>\n  (if [l1,h1] = \\<bottom> then True else\n   if [l2,h2] = \\<bottom> then False else l1 \\<ge> l2 & h1 \\<le> h2)\"\nunfolding bot_ivl_def by transfer (simp add: le_rep_def eq_ivl_empty)\n\nlemma sup_ivl_nice: \"[l1,h1] \\<squnion> [l2,h2] =\n  (if [l1,h1] = \\<bottom> then [l2,h2] else\n   if [l2,h2] = \\<bottom> then [l1,h1] else [min l1 l2,max h1 h2])\"\nunfolding bot_ivl_def by transfer (simp add: sup_rep_def eq_ivl_empty)\n\nlemma inf_ivl_nice: \"[l1,h1] \\<sqinter> [l2,h2] = [max l1 l2,min h1 h2]\"\nby transfer (simp add: inf_rep_def)\n\nlemma top_ivl_nice: \"\\<top> = [-\\<infinity>,\\<infinity>]\"\nby (simp add: top_ivl_def)\n\n\ninstantiation ivl :: plus\nbegin\n\ndefinition plus_rep :: \"eint2 \\<Rightarrow> eint2 \\<Rightarrow> eint2\" where\n\"plus_rep p1 p2 =\n  (if is_empty_rep p1 \\<or> is_empty_rep p2 then empty_rep else\n   let (l1,h1) = p1; (l2,h2) = p2 in (l1+l2, h1+h2))\"\n\nlift_definition plus_ivl :: \"ivl \\<Rightarrow> ivl \\<Rightarrow> ivl\" is plus_rep\nby(auto simp: plus_rep_def eq_ivl_iff)\n\ninstance ..\nend\n\nlemma plus_ivl_nice: \"[l1,h1] + [l2,h2] =\n  (if [l1,h1] = \\<bottom> \\<or> [l2,h2] = \\<bottom> then \\<bottom> else [l1+l2 , h1+h2])\"\nunfolding bot_ivl_def by transfer (auto simp: plus_rep_def eq_ivl_empty)\n\nlemma uminus_eq_Minf[simp]: \"-x = Minf \\<longleftrightarrow> x = Pinf\"\nby(cases x) auto\nlemma uminus_eq_Pinf[simp]: \"-x = Pinf \\<longleftrightarrow> x = Minf\"\nby(cases x) auto\n\nlemma uminus_le_Fin_iff: \"- x \\<le> Fin(-y) \\<longleftrightarrow> Fin y \\<le> (x::'a::ordered_ab_group_add extended)\"\nby(cases x) auto\nlemma Fin_uminus_le_iff: \"Fin(-y) \\<le> -x \\<longleftrightarrow> x \\<le> ((Fin y)::'a::ordered_ab_group_add extended)\"\nby(cases x) auto\n\ninstantiation ivl :: uminus\nbegin\n\ndefinition uminus_rep :: \"eint2 \\<Rightarrow> eint2\" where\n\"uminus_rep p = (let (l,h) = p in (-h, -l))\"\n\nlemma \\<gamma>_uminus_rep: \"i \\<in> \\<gamma>_rep p \\<Longrightarrow> -i \\<in> \\<gamma>_rep(uminus_rep p)\"\nby(auto simp: uminus_rep_def \\<gamma>_rep_def image_def uminus_le_Fin_iff Fin_uminus_le_iff\n        split: prod.split)\n\nlift_definition uminus_ivl :: \"ivl \\<Rightarrow> ivl\" is uminus_rep\nby (auto simp: uminus_rep_def eq_ivl_def \\<gamma>_rep_cases)\n   (auto simp: Icc_eq_Icc split: extended.splits)\n\ninstance ..\nend\n\nlemma \\<gamma>_uminus: \"i \\<in> \\<gamma>_ivl iv \\<Longrightarrow> -i \\<in> \\<gamma>_ivl(- iv)\"\nby transfer (rule \\<gamma>_uminus_rep)\n\nlemma uminus_nice: \"-[l,h] = [-h,-l]\"\nby transfer (simp add: uminus_rep_def)\n\ninstantiation ivl :: minus\nbegin\n\ndefinition minus_ivl :: \"ivl \\<Rightarrow> ivl \\<Rightarrow> ivl\" where\n\"(iv1::ivl) - iv2 = iv1 + -iv2\"\n\ninstance ..\nend\n\n\ndefinition inv_plus_ivl :: \"ivl \\<Rightarrow> ivl \\<Rightarrow> ivl \\<Rightarrow> ivl*ivl\" where\n\"inv_plus_ivl iv iv1 iv2 = (iv1 \\<sqinter> (iv - iv2), iv2 \\<sqinter> (iv - iv1))\"\n\ndefinition above_rep :: \"eint2 \\<Rightarrow> eint2\" where\n\"above_rep p = (if is_empty_rep p then empty_rep else let (l,h) = p in (l,\\<infinity>))\"\n\ndefinition below_rep :: \"eint2 \\<Rightarrow> eint2\" where\n\"below_rep p = (if is_empty_rep p then empty_rep else let (l,h) = p in (-\\<infinity>,h))\"\n\nlift_definition above :: \"ivl \\<Rightarrow> ivl\" is above_rep\nby(auto simp: above_rep_def eq_ivl_iff)\n\nlift_definition below :: \"ivl \\<Rightarrow> ivl\" is below_rep\nby(auto simp: below_rep_def eq_ivl_iff)\n\nlemma \\<gamma>_aboveI: \"i \\<in> \\<gamma>_ivl iv \\<Longrightarrow> i \\<le> j \\<Longrightarrow> j \\<in> \\<gamma>_ivl(above iv)\"\nby transfer \n   (auto simp add: above_rep_def \\<gamma>_rep_cases is_empty_rep_def\n         split: extended.splits)\n\nlemma \\<gamma>_belowI: \"i \\<in> \\<gamma>_ivl iv \\<Longrightarrow> j \\<le> i \\<Longrightarrow> j \\<in> \\<gamma>_ivl(below iv)\"\nby transfer \n   (auto simp add: below_rep_def \\<gamma>_rep_cases is_empty_rep_def\n         split: extended.splits)\n\ndefinition inv_less_ivl :: \"bool \\<Rightarrow> ivl \\<Rightarrow> ivl \\<Rightarrow> ivl * ivl\" where\n\"inv_less_ivl res iv1 iv2 =\n  (if res\n   then (iv1 \\<sqinter> (below iv2 - [1,1]),\n         iv2 \\<sqinter> (above iv1 + [1,1]))\n   else (iv1 \\<sqinter> above iv2, iv2 \\<sqinter> below iv1))\"\n\nlemma above_nice: \"above[l,h] = (if [l,h] = \\<bottom> then \\<bottom> else [l,\\<infinity>])\"\nunfolding bot_ivl_def by transfer (simp add: above_rep_def eq_ivl_empty)\n\nlemma below_nice: \"below[l,h] = (if [l,h] = \\<bottom> then \\<bottom> else [-\\<infinity>,h])\"\nunfolding bot_ivl_def by transfer (simp add: below_rep_def eq_ivl_empty)\n\nlemma add_mono_le_Fin:\n  \"\\<lbrakk>x1 \\<le> Fin y1; x2 \\<le> Fin y2\\<rbrakk> \\<Longrightarrow> x1 + x2 \\<le> Fin (y1 + (y2::'a::ordered_ab_group_add))\"\nby(drule (1) add_mono) simp\n\nlemma add_mono_Fin_le:\n  \"\\<lbrakk>Fin y1 \\<le> x1; Fin y2 \\<le> x2\\<rbrakk> \\<Longrightarrow> Fin(y1 + y2::'a::ordered_ab_group_add) \\<le> x1 + x2\"\nby(drule (1) add_mono) simp\n\nglobal_interpretation Val_semilattice\nwhere \\<gamma> = \\<gamma>_ivl and num' = num_ivl and plus' = \"(+)\"\nproof (standard, goal_cases)\n  case 1 thus ?case by transfer (simp add: le_iff_subset)\nnext\n  case 2 show ?case by transfer (simp add: \\<gamma>_rep_def)\nnext\n  case 3 show ?case by transfer (simp add: \\<gamma>_rep_def)\nnext\n  case 4 thus ?case\n    apply transfer\n    apply(auto simp: \\<gamma>_rep_def plus_rep_def add_mono_le_Fin add_mono_Fin_le)\n    by(auto simp: empty_rep_def is_empty_rep_def)\nqed\n\n\nglobal_interpretation Val_lattice_gamma\nwhere \\<gamma> = \\<gamma>_ivl and num' = num_ivl and plus' = \"(+)\"\ndefines aval_ivl = aval'\nproof (standard, goal_cases)\n  case 1 show ?case by(simp add: \\<gamma>_inf)\nnext\n  case 2 show ?case unfolding bot_ivl_def by transfer simp\nqed\n\nglobal_interpretation Val_inv\nwhere \\<gamma> = \\<gamma>_ivl and num' = num_ivl and plus' = \"(+)\"\nand test_num' = in_ivl\nand inv_plus' = inv_plus_ivl and inv_less' = inv_less_ivl\nproof (standard, goal_cases)\n  case 1 thus ?case by transfer (auto simp: \\<gamma>_rep_def)\nnext\n  case (2 _ _ _ _ _ i1 i2) thus ?case\n    unfolding inv_plus_ivl_def minus_ivl_def\n    apply(clarsimp simp add: \\<gamma>_inf)\n    using gamma_plus'[of \"i1+i2\" _ \"-i1\"] gamma_plus'[of \"i1+i2\" _ \"-i2\"]\n    by(simp add:  \\<gamma>_uminus)\nnext\n  case (3 i1 i2) thus ?case\n    unfolding inv_less_ivl_def minus_ivl_def one_extended_def\n    apply(clarsimp simp add: \\<gamma>_inf split: if_splits)\n    using gamma_plus'[of \"i1+1\" _ \"-1\"] gamma_plus'[of \"i2 - 1\" _ \"1\"]\n    apply(simp add: \\<gamma>_belowI[of i2] \\<gamma>_aboveI[of i1]\n      uminus_ivl.abs_eq uminus_rep_def \\<gamma>_ivl_nice)\n    apply(simp add: \\<gamma>_aboveI[of i2] \\<gamma>_belowI[of i1])\n    done\nqed\n\nglobal_interpretation Abs_Int_inv\nwhere \\<gamma> = \\<gamma>_ivl and num' = num_ivl and plus' = \"(+)\"\nand test_num' = in_ivl\nand inv_plus' = inv_plus_ivl and inv_less' = inv_less_ivl\ndefines inv_aval_ivl = inv_aval'\nand inv_bval_ivl = inv_bval'\nand step_ivl = step'\nand AI_ivl = AI\nand aval_ivl' = aval''\n..\n\n\ntext\\<open>Monotonicity:\\<close>\n\nlemma mono_plus_ivl: \"iv1 \\<le> iv2 \\<Longrightarrow> iv3 \\<le> iv4 \\<Longrightarrow> iv1+iv3 \\<le> iv2+(iv4::ivl)\"\napply transfer\napply(auto simp: plus_rep_def le_iff_subset split: if_splits)\nby(auto simp: is_empty_rep_iff \\<gamma>_rep_cases split: extended.splits)\n\nlemma mono_minus_ivl: \"iv1 \\<le> iv2 \\<Longrightarrow> -iv1 \\<le> -(iv2::ivl)\"\napply transfer\napply(auto simp: uminus_rep_def le_iff_subset split: if_splits prod.split)\nby(auto simp: \\<gamma>_rep_cases split: extended.splits)\n\nlemma mono_above: \"iv1 \\<le> iv2 \\<Longrightarrow> above iv1 \\<le> above iv2\"\napply transfer\napply(auto simp: above_rep_def le_iff_subset split: if_splits prod.split)\nby(auto simp: is_empty_rep_iff \\<gamma>_rep_cases split: extended.splits)\n\nlemma mono_below: \"iv1 \\<le> iv2 \\<Longrightarrow> below iv1 \\<le> below iv2\"\napply transfer\napply(auto simp: below_rep_def le_iff_subset split: if_splits prod.split)\nby(auto simp: is_empty_rep_iff \\<gamma>_rep_cases split: extended.splits)\n\nglobal_interpretation Abs_Int_inv_mono\nwhere \\<gamma> = \\<gamma>_ivl and num' = num_ivl and plus' = \"(+)\"\nand test_num' = in_ivl\nand inv_plus' = inv_plus_ivl and inv_less' = inv_less_ivl\nproof (standard, goal_cases)\n  case 1 thus ?case by (rule mono_plus_ivl)\nnext\n  case 2 thus ?case\n    unfolding inv_plus_ivl_def minus_ivl_def less_eq_prod_def\n    by (auto simp: le_infI1 le_infI2 mono_plus_ivl mono_minus_ivl)\nnext\n  case 3 thus ?case\n    unfolding less_eq_prod_def inv_less_ivl_def minus_ivl_def\n    by (auto simp: le_infI1 le_infI2 mono_plus_ivl mono_above mono_below)\nqed\n\n\nsubsubsection \"Tests\"\n\nvalue \"show_acom_opt (AI_ivl test1_ivl)\"\n\ntext\\<open>Better than \\<open>AI_const\\<close>:\\<close>\nvalue \"show_acom_opt (AI_ivl test3_const)\"\nvalue \"show_acom_opt (AI_ivl test4_const)\"\nvalue \"show_acom_opt (AI_ivl test6_const)\"\n\ndefinition \"steps c i = (step_ivl \\<top> ^^ i) (bot c)\"\n\nvalue \"show_acom_opt (AI_ivl test2_ivl)\"\nvalue \"show_acom (steps test2_ivl 0)\"\nvalue \"show_acom (steps test2_ivl 1)\"\nvalue \"show_acom (steps test2_ivl 2)\"\nvalue \"show_acom (steps test2_ivl 3)\"\n\ntext\\<open>Fixed point reached in 2 steps.\n Not so if the start value of x is known:\\<close>\n\nvalue \"show_acom_opt (AI_ivl test3_ivl)\"\nvalue \"show_acom (steps test3_ivl 0)\"\nvalue \"show_acom (steps test3_ivl 1)\"\nvalue \"show_acom (steps test3_ivl 2)\"\nvalue \"show_acom (steps test3_ivl 3)\"\nvalue \"show_acom (steps test3_ivl 4)\"\nvalue \"show_acom (steps test3_ivl 5)\"\n\ntext\\<open>Takes as many iterations as the actual execution. Would diverge if\nloop did not terminate. Worse still, as the following example shows: even if\nthe actual execution terminates, the analysis may not. The value of y keeps\nincreasing as the analysis is iterated, no matter how long:\\<close>\n\nvalue \"show_acom (steps test4_ivl 50)\"\n\ntext\\<open>Relationships between variables are NOT captured:\\<close>\nvalue \"show_acom_opt (AI_ivl test5_ivl)\"\n\ntext\\<open>Again, the analysis would not terminate:\\<close>\nvalue \"show_acom (steps test6_ivl 50)\"\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/Abs_Int2_ivl.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711794579723, "lm_q2_score": 0.8289388125473629, "lm_q1q2_score": 0.704574100199373}}
{"text": "theory conditions_negative\n  imports conditions_positive\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(**Anti-tonicity (ANTI).*)\ndefinition ANTI::\"('w \\<sigma> \\<Rightarrow> 'w \\<sigma>) \\<Rightarrow> bool\" (\"ANTI\")\n  where \"ANTI \\<phi> \\<equiv> \\<forall>A B. A \\<preceq> B \\<longrightarrow> \\<phi> B \\<preceq> \\<phi> A\"\n\ndeclare ANTI_def[cond]\n\n(**ANTI is self-dual*)\nlemma ANTI_dual: \"ANTI \\<phi> = ANTI \\<phi>\\<^sup>d\" by (smt (verit) BA_cp ANTI_def dual_invol op_dual_def)\n(**ANTI is the 'complement' of MONO*)\nlemma ANTI_MONO: \"MONO \\<phi> = ANTI \\<phi>\\<^sup>c\" by (metis ANTI_def BA_cp MONO_def svfun_compl_def)\n\n\n(**anti-expansive/extensive (nEXPN) and its dual anti-contractive (nCNTR).*)\ndefinition nEXPN::\"('w \\<sigma> \\<Rightarrow> 'w \\<sigma>) \\<Rightarrow> bool\" (\"nEXPN\")\n  where \"nEXPN \\<phi>  \\<equiv> \\<forall>A. \\<phi> A \\<preceq> \\<^bold>\\<midarrow>A\"\ndefinition nCNTR::\"('w \\<sigma> \\<Rightarrow> 'w \\<sigma>) \\<Rightarrow> bool\" (\"nCNTR\")\n  where \"nCNTR \\<phi> \\<equiv> \\<forall>A. \\<^bold>\\<midarrow>A \\<preceq> \\<phi> A\"\n\ndeclare nEXPN_def[cond] nCNTR_def[cond]\n\n(**nEXPN and nCNTR are dual to each other *)\nlemma nEXPN_nCNTR_dual1: \"nEXPN \\<phi> = nCNTR \\<phi>\\<^sup>d\" unfolding cond by (metis BA_cp BA_dn op_dual_def setequ_ext)\nlemma nEXPN_nCNTR_dual2: \"nCNTR \\<phi> = nEXPN \\<phi>\\<^sup>d\" by (simp add: dual_invol nEXPN_nCNTR_dual1)\n\n(**nEXPN and nCNTR are the 'complements' of EXPN and CNTR respectively*)\nlemma nEXPN_CNTR_compl: \"EXPN \\<phi> = nEXPN \\<phi>\\<^sup>c\" by (metis BA_cp EXPN_def nEXPN_def svfun_compl_def)\nlemma nCNTR_EXPN_compl: \"CNTR \\<phi> = nCNTR \\<phi>\\<^sup>c\" by (metis EXPN_CNTR_dual2 dual_compl_char1 dual_compl_char2 nEXPN_CNTR_compl nEXPN_nCNTR_dual2)\n\n(**anti-Normality (nNORM) and its dual (nDNRM).*)\ndefinition nNORM::\"('w \\<sigma> \\<Rightarrow> 'w \\<sigma>) \\<Rightarrow> bool\" (\"nNORM\")\n  where \"nNORM \\<phi>  \\<equiv> (\\<phi> \\<^bold>\\<bottom>) \\<approx> \\<^bold>\\<top>\"\ndefinition nDNRM::\"('w \\<sigma> \\<Rightarrow> 'w \\<sigma>) \\<Rightarrow> bool\" (\"nDNRM\")\n  where \"nDNRM \\<phi> \\<equiv> (\\<phi> \\<^bold>\\<top>) \\<approx> \\<^bold>\\<bottom>\" \n\ndeclare nNORM_def[cond] nDNRM_def[cond]\n\n(**nNORM and nDNRM are dual to each other *)\nlemma nNOR_dual1: \"nNORM \\<phi> = nDNRM \\<phi>\\<^sup>d\" unfolding cond by (simp add: bottom_def compl_def op_dual_def setequ_def top_def)\nlemma nNOR_dual2: \"nDNRM \\<phi> = nNORM \\<phi>\\<^sup>d\" by (simp add: dual_invol nNOR_dual1) \n\n(**nNORM and nDNRM are the 'complements' of NORM and DNRM respectively*)\nlemma nNORM_NORM_compl: \"NORM \\<phi> = nNORM \\<phi>\\<^sup>c\" by (simp add: NORM_def bottom_def compl_def nNORM_def setequ_def svfun_compl_def top_def)\nlemma nDNRM_DNRM_compl: \"DNRM \\<phi> = nDNRM \\<phi>\\<^sup>c\" by (simp add: DNRM_def bottom_def compl_def nDNRM_def setequ_def svfun_compl_def top_def)\n\n(**nEXPN (nCNTR) entail nDNRM (nNORM).*)\nlemma nEXPN_impl_nDNRM: \"nEXPN \\<phi> \\<longrightarrow> nDNRM \\<phi>\" unfolding cond by (metis bottom_def compl_def setequ_def subset_def top_def)\nlemma nCNTR_impl_nNORM: \"nCNTR \\<phi> \\<longrightarrow> nNORM \\<phi>\" by (simp add: nEXPN_impl_nDNRM nEXPN_nCNTR_dual2 nNOR_dual1)\n\n\n(**anti-Idempotence (nIDEM).*)\ndefinition nIDEM::\"('w \\<sigma> \\<Rightarrow> 'w \\<sigma>) \\<Rightarrow> bool\" (\"nIDEM\") \n  where \"nIDEM \\<phi>  \\<equiv> \\<forall>A. \\<phi>(\\<^bold>\\<midarrow>(\\<phi> A)) \\<approx> (\\<phi> A)\"\ndefinition nIDEM_a::\"('w \\<sigma> \\<Rightarrow> 'w \\<sigma>) \\<Rightarrow> bool\" (\"nIDEM\\<^sup>a\") \n  where \"nIDEM_a \\<phi> \\<equiv> \\<forall>A. (\\<phi> A) \\<preceq> \\<phi>(\\<^bold>\\<midarrow>(\\<phi> A))\"\ndefinition nIDEM_b::\"('w \\<sigma> \\<Rightarrow> 'w \\<sigma>) \\<Rightarrow> bool\" (\"nIDEM\\<^sup>b\") \n  where \"nIDEM_b \\<phi> \\<equiv> \\<forall>A. \\<phi>(\\<^bold>\\<midarrow>(\\<phi> A)) \\<preceq> (\\<phi> A)\"\n\ndeclare nIDEM_def[cond] nIDEM_a_def[cond] nIDEM_b_def[cond]\n\n(**nIDEM-a and nIDEM-b are dual to each other *)\nlemma nIDEM_dual1: \"nIDEM\\<^sup>a \\<phi> = nIDEM\\<^sup>b \\<phi>\\<^sup>d\" unfolding cond by (metis BA_cp BA_dn op_dual_def setequ_ext)\nlemma nIDEM_dual2: \"nIDEM\\<^sup>b \\<phi> = nIDEM\\<^sup>a \\<phi>\\<^sup>d\" by (simp add: dual_invol nIDEM_dual1)\n\nlemma nIDEM_char: \"nIDEM \\<phi> = (nIDEM\\<^sup>a \\<phi> \\<and> nIDEM\\<^sup>b \\<phi>)\" unfolding cond setequ_char by blast\nlemma nIDEM_dual: \"nIDEM \\<phi> = nIDEM \\<phi>\\<^sup>d\" using nIDEM_char nIDEM_dual1 nIDEM_dual2 by blast\n\n(**nIDEM(a/b) and IDEM(a/b) are the 'complements' each other*)\nlemma nIDEM_a_compl: \"IDEM\\<^sup>a \\<phi> = nIDEM\\<^sup>a \\<phi>\\<^sup>c\" by (metis (no_types, lifting) BA_cp IDEM_a_def nIDEM_a_def sfun_compl_invol svfun_compl_def)\nlemma nIDEM_b_compl: \"IDEM\\<^sup>b \\<phi> = nIDEM\\<^sup>b \\<phi>\\<^sup>c\" by (metis IDEM_dual2 dual_compl_char1 dual_compl_char2 nIDEM_a_compl nIDEM_dual2)\nlemma nIDEM_compl: \"nIDEM \\<phi> = IDEM \\<phi>\\<^sup>c\" by (simp add: IDEM_char nIDEM_a_compl nIDEM_b_compl nIDEM_char sfun_compl_invol)\n\n(**nEXPN (nCNTR) entail nIDEM-a (nIDEM-b).*)\nlemma nEXPN_impl_nIDEM_a: \"nEXPN \\<phi> \\<longrightarrow> nIDEM\\<^sup>b \\<phi>\" by (metis nEXPN_def nIDEM_b_def sfun_compl_invol svfun_compl_def)\nlemma nCNTR_impl_nIDEM_b: \"nCNTR \\<phi> \\<longrightarrow> nIDEM\\<^sup>a \\<phi>\" by (simp add: nEXPN_impl_nIDEM_a nEXPN_nCNTR_dual2 nIDEM_dual1)\n\n\n(**anti-distribution over joins or anti-additivity (nADDI) and its dual...*)\ndefinition nADDI::\"('w \\<sigma> \\<Rightarrow> 'w \\<sigma>) \\<Rightarrow> bool\" (\"nADDI\")\n  where \"nADDI \\<phi>  \\<equiv> \\<forall>A B. \\<phi>(A \\<^bold>\\<or> B) \\<approx> (\\<phi> A) \\<^bold>\\<and> (\\<phi> B)\" \ndefinition nADDI_a::\"('w \\<sigma> \\<Rightarrow> 'w \\<sigma>) \\<Rightarrow> bool\" (\"nADDI\\<^sup>a\")\n  where \"nADDI\\<^sup>a \\<phi> \\<equiv> \\<forall>A B. (\\<phi> A) \\<^bold>\\<and> (\\<phi> B) \\<preceq> \\<phi>(A \\<^bold>\\<or> B)\" \ndefinition nADDI_b::\"('w \\<sigma> \\<Rightarrow> 'w \\<sigma>) \\<Rightarrow> bool\" (\"nADDI\\<^sup>b\")\n  where \"nADDI\\<^sup>b \\<phi> \\<equiv> \\<forall>A B. \\<phi>(A \\<^bold>\\<or> B) \\<preceq> (\\<phi> A) \\<^bold>\\<and> (\\<phi> B)\"\n\n(**... anti-distribution over meets or anti-multiplicativity (nMULT).*)\ndefinition nMULT::\"('w \\<sigma> \\<Rightarrow> 'w \\<sigma>) \\<Rightarrow> bool\" (\"nMULT\") \n  where \"nMULT \\<phi>  \\<equiv> \\<forall>A B. \\<phi>(A \\<^bold>\\<and> B) \\<approx> (\\<phi> A) \\<^bold>\\<or> (\\<phi> B)\" \ndefinition nMULT_a::\"('w \\<sigma> \\<Rightarrow> 'w \\<sigma>) \\<Rightarrow> bool\" (\"nMULT\\<^sup>a\")\n  where \"nMULT\\<^sup>a \\<phi> \\<equiv> \\<forall>A B. (\\<phi> A) \\<^bold>\\<or> (\\<phi> B) \\<preceq> \\<phi>(A \\<^bold>\\<and> B)\"\ndefinition nMULT_b::\"('w \\<sigma> \\<Rightarrow> 'w \\<sigma>) \\<Rightarrow> bool\" (\"nMULT\\<^sup>b\")\n  where \"nMULT\\<^sup>b \\<phi> \\<equiv> \\<forall>A B. \\<phi>(A \\<^bold>\\<and> B) \\<preceq> (\\<phi> A) \\<^bold>\\<or> (\\<phi> B)\" \n\ndeclare nADDI_def[cond] nADDI_a_def[cond] nADDI_b_def[cond]\n        nMULT_def[cond] nMULT_a_def[cond] nMULT_b_def[cond]\n\nlemma nADDI_char: \"nADDI \\<phi> = (nADDI\\<^sup>a \\<phi> \\<and> nADDI\\<^sup>b \\<phi>)\" unfolding cond using setequ_char by blast\nlemma nMULT_char: \"nMULT \\<phi> = (nMULT\\<^sup>a \\<phi> \\<and> nMULT\\<^sup>b \\<phi>)\" unfolding cond using setequ_char by blast\n\n(**ANTI, nMULT-a and nADDI-b are equivalent.*)\nlemma ANTI_nMULTa: \"nMULT\\<^sup>a \\<phi> = ANTI \\<phi>\" unfolding cond by (smt (z3) L10 L7 join_def meet_def setequ_ext subset_def)\nlemma ANTI_nADDIb: \"nADDI\\<^sup>b \\<phi> = ANTI \\<phi>\" unfolding cond by (smt (verit) BA_cp BA_deMorgan1 L10 L3 L5 L8 L9 setequ_char setequ_ext)\n\n(**Below we prove several duality relationships between nADDI(a/b) and nMULT(a/b).*)\n\n(**Duality between nMULT-a and nADDI-b (an easy corollary from the self-duality of ANTI).*)\nlemma nMULTa_nADDIb_dual1: \"nMULT\\<^sup>a \\<phi> = nADDI\\<^sup>b \\<phi>\\<^sup>d\" using ANTI_nADDIb ANTI_nMULTa ANTI_dual by blast\nlemma nMULTa_nADDIb_dual2: \"nADDI\\<^sup>b \\<phi> = nMULT\\<^sup>a \\<phi>\\<^sup>d\" by (simp add: dual_invol nMULTa_nADDIb_dual1)\n(**Duality between nADDI-a and nMULT-b.*)\nlemma nADDIa_nMULTb_dual1: \"nADDI\\<^sup>a \\<phi> = nMULT\\<^sup>b \\<phi>\\<^sup>d\" unfolding cond by (metis (no_types, lifting) BA_cp BA_deMorgan1 BA_dn op_dual_def setequ_ext)\nlemma nADDIa_nMULTb_dual2: \"nMULT\\<^sup>b \\<phi> = nADDI\\<^sup>a \\<phi>\\<^sup>d\" by (simp add: dual_invol nADDIa_nMULTb_dual1)\n(**Duality between ADDI and MULT.*)\nlemma nADDI_nMULT_dual1: \"nADDI \\<phi> = nMULT \\<phi>\\<^sup>d\" using nADDI_char nADDIa_nMULTb_dual1 nMULT_char nMULTa_nADDIb_dual2 by blast\nlemma nADDI_nMULT_dual2: \"nMULT \\<phi> = nADDI \\<phi>\\<^sup>d\" by (simp add: dual_invol nADDI_nMULT_dual1)\n\n(**nADDI and nMULT are the 'complements' of ADDI and MULT respectively*)\nlemma nADDIa_compl: \"ADDI\\<^sup>a \\<phi> = nADDI\\<^sup>a \\<phi>\\<^sup>c\" by (metis ADDI_a_def BA_cp BA_deMorgan1 nADDI_a_def setequ_ext svfun_compl_def)\nlemma nADDIb_compl: \"ADDI\\<^sup>b \\<phi> = nADDI\\<^sup>b \\<phi>\\<^sup>c\" by (simp add: ANTI_nADDIb ANTI_MONO MONO_ADDIb sfun_compl_invol)\nlemma nADDI_compl: \"ADDI \\<phi> = nADDI \\<phi>\\<^sup>c\" by (simp add: ADDI_char nADDI_char nADDIa_compl nADDIb_compl)\nlemma nMULTa_compl: \"MULT\\<^sup>a \\<phi> = nMULT\\<^sup>a \\<phi>\\<^sup>c\" by (simp add: ANTI_MONO ANTI_nMULTa MONO_MULTa sfun_compl_invol)\nlemma nMULTb_compl: \"MULT\\<^sup>b \\<phi> = nMULT\\<^sup>b \\<phi>\\<^sup>c\" by (metis BA_cp BA_deMorgan2 MULT_b_def nMULT_b_def setequ_ext svfun_compl_def)\nlemma nMULT_compl: \"MULT \\<phi> = nMULT \\<phi>\\<^sup>c\" by (simp add: MULT_char nMULT_char nMULTa_compl nMULTb_compl)\n\n\n(**We verify properties regarding closure over meets/joins for fixed-points.*)\n\n(**nMULT for an operator implies join-closedness of the set of fixed-points of its dual-complement*)\nlemma nMULT_joinclosed: \"nMULT \\<phi> \\<Longrightarrow> join_closed (fp (\\<phi>\\<^sup>-))\" by (smt (verit, del_insts) ADDI_MULT_dual2 ADDI_joinclosed BA_deMorgan1 MULT_def dual_compl_char2 nMULT_def setequ_ext svfun_compl_def)\nlemma \"join_closed (fp (\\<phi>\\<^sup>-)) \\<Longrightarrow> nMULT \\<phi>\" nitpick oops (*countermodel found: needs further assumptions*)\nlemma joinclosed_nMULT: \"ANTI \\<phi> \\<Longrightarrow> nCNTR \\<phi> \\<Longrightarrow> nIDEM\\<^sup>b \\<phi> \\<Longrightarrow> join_closed (fp (\\<phi>\\<^sup>-)) \\<Longrightarrow> nMULT \\<phi>\" by (metis ANTI_MONO ANTI_dual IDEM_char IDEM_dual dual_compl_char1 dual_compl_char2 joinclosed_ADDI nADDI_compl nADDI_nMULT_dual2 nCNTR_impl_nIDEM_b nEXPN_CNTR_compl nEXPN_nCNTR_dual2 nIDEM_char nIDEM_compl sfun_compl_invol)\n\n(**nADDI for an operator implies meet-closedness of the set of fixed-points of its dual-complement*)\nlemma nADDI_meetclosed: \"nADDI \\<phi> \\<Longrightarrow> meet_closed (fp (\\<phi>\\<^sup>-))\" by (smt (verit, ccfv_threshold) ADDI_MULT_dual1 ADDI_def BA_deMorgan2 MULT_meetclosed dual_compl_char2 nADDI_def setequ_ext svfun_compl_def)\nlemma \"meet_closed (fp (\\<phi>\\<^sup>-)) \\<Longrightarrow> nADDI \\<phi>\" nitpick oops (*countermodel found: needs further assumptions*)\nlemma meetclosed_nADDI: \"ANTI \\<phi> \\<Longrightarrow> nEXPN \\<phi> \\<Longrightarrow> nIDEM\\<^sup>a \\<phi> \\<Longrightarrow> meet_closed (fp (\\<phi>\\<^sup>-)) \\<Longrightarrow> nADDI \\<phi>\" by (metis ADDI_MULT_dual2 ADDI_joinclosed ANTI_MONO ANTI_dual dual_compl_char1 dual_compl_char2 joinclosed_nMULT meetclosed_MULT nADDI_nMULT_dual1 nCNTR_EXPN_compl nEXPN_nCNTR_dual1 nIDEM_b_compl nIDEM_dual1 sfun_compl_invol)\n\n(**Assuming ANTI, we have that nEXPN (nCNTR) implies meet-closed (join-closed) for the set of fixed-points.*)\nlemma nEXPN_meetclosed: \"ANTI \\<phi> \\<Longrightarrow> nEXPN \\<phi> \\<Longrightarrow> meet_closed (fp \\<phi>)\" by (metis (full_types) L10 compl_def fixpoints_def meet_closed_def nEXPN_def setequ_ext subset_def)\nlemma nCNTR_joinclosed: \"ANTI \\<phi> \\<Longrightarrow> nCNTR \\<phi> \\<Longrightarrow> join_closed (fp \\<phi>)\" by (smt (verit, ccfv_threshold) BA_impl L9 fixpoints_def impl_char join_closed_def nCNTR_def setequ_char setequ_ext)\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/conditions/conditions_negative.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8289388040954684, "lm_q2_score": 0.8499711832583695, "lm_q1q2_score": 0.704574096165803}}
{"text": "(* Author: Lukas Bulwahn <lukas.bulwahn-at-gmail.com> *)\n\nsection \\<open>Ptolemy's Theorem\\<close>\n\ntheory Ptolemys_Theorem\nimports\n  \"HOL-Analysis.Multivariate_Analysis\"\nbegin\n\nsubsection \\<open>Preliminaries\\<close>\n\nsubsubsection \\<open>Additions to Rat theory\\<close>\n\nhide_const (open) normalize\n\nsubsubsection \\<open>Additions to Transcendental theory\\<close>\n\ntext \\<open>\nLemmas about @{const arcsin} and @{const arccos} commonly involve to show that their argument is\nin the domain of those partial functions, i.e., the argument @{term y} is between @{term \"-1::real\"}\nand @{term \"1::real\"}.\nAs the argumentation for @{term \"(-1::real) \\<le> y\"} and @{term \"y \\<le> (1::real)\"} is often very similar,\nwe prefer to prove @{term \"\\<bar>y\\<bar> \\<le> (1::real)\"} to the two goals above.\n\nThe lemma for rewriting the term @{term \"cos (arccos y)\"} is already provided in the Isabelle\ndistribution with name @{thm [source] cos_arccos_abs}. Here, we further provide the analogue on\n@{term \"arcsin\"} for rewriting @{term \"sin (arcsin y)\"}.\n\\<close>\n\nlemma sin_arcsin_abs: \"\\<bar>y\\<bar> \\<le> 1 \\<Longrightarrow> sin (arcsin y) = y\"\n  by (simp add: abs_le_iff)\n\ntext \\<open>\nThe further lemmas are the required variants from existing lemmas @{thm [source] arccos_lbound}\nand @{thm [source] arccos_ubound}.\n\\<close>\n\nlemma arccos_lbound_abs [simp]:\n  \"\\<bar>y\\<bar> \\<le> 1 \\<Longrightarrow> 0 \\<le> arccos y\"\nby (simp add: arccos_lbound)\n\nlemma arccos_ubound_abs [simp]:\n  \"\\<bar>y\\<bar> \\<le> 1 \\<Longrightarrow> arccos y \\<le> pi\"\nby (simp add: arccos_ubound)\n\ntext \\<open>\nAs we choose angles to be between @{term \"0::real\"} between @{term \"2 * pi\"},\nwe need some lemmas to reason about the sign of @{term \"sin x\"}\nfor angles @{term \"x\"}.\n\\<close>\n\nlemma sin_ge_zero_iff:\n  assumes \"0 \\<le> x\" \"x < 2 * pi\"\n  shows \"0 \\<le> sin x \\<longleftrightarrow> x \\<le> pi\"\nproof\n  assume \"0 \\<le> sin x\"\n  show \"x \\<le> pi\"\n  proof (rule ccontr)\n    assume \"\\<not> x \\<le> pi\"\n    from this \\<open>x < 2 * pi\\<close> have \"sin x < 0\"\n      using sin_lt_zero by auto\n    from this \\<open>0 \\<le> sin x\\<close> show False by auto\n  qed\nnext\n  assume \"x \\<le> pi\"\n  from this \\<open>0 \\<le> x\\<close> show \"0 \\<le> sin x\" by (simp add: sin_ge_zero)\nqed\n\nlemma sin_less_zero_iff:\n  assumes \"0 \\<le> x\" \"x < 2 * pi\"\n  shows \"sin x < 0 \\<longleftrightarrow> pi < x\"\nusing assms sin_ge_zero_iff by fastforce\n\nsubsubsection \\<open>Addition to Finite-Cartesian-Product theory\\<close>\n\ntext \\<open>\nHere follow generally useful additions and specialised equations\nfor two-dimensional real-valued vectors.\n\\<close>\n\nlemma axis_nth_eq_0 [simp]:\n  assumes \"i \\<noteq> j\"\n  shows \"axis i x $ j = 0\"\nusing assms unfolding axis_def by simp\n\nlemma norm_axis:\n  fixes x :: real\n  shows \"norm (axis i x) = abs x\"\nby (simp add: norm_eq_sqrt_inner inner_axis_axis)\n\nlemma norm_eq_on_real_2_vec:\n  fixes x :: \"real ^ 2\"\n  shows \"norm x = sqrt ((x $ 1) ^ 2 + (x $ 2) ^ 2)\"\nby (simp add: norm_eq_sqrt_inner inner_vec_def UNIV_2 power2_eq_square)\n\nlemma dist_eq_on_real_2_vec:\n  fixes a b :: \"real ^ 2\"\n  shows \"dist a b = sqrt ((a $ 1 - b $ 1) ^ 2 + (a $ 2 - b $ 2) ^ 2)\"\nunfolding dist_norm norm_eq_on_real_2_vec by simp\n\nsubsection \\<open>Polar Form of Two-Dimensional Real-Valued Vectors\\<close>\n\nsubsubsection \\<open>Definitions to Transfer to Polar Form and Back\\<close>\n\ndefinition of_radiant :: \"real \\<Rightarrow> real ^ 2\"\nwhere\n  \"of_radiant \\<omega> = axis 1 (cos \\<omega>) + axis 2 (sin \\<omega>)\"\n\ndefinition normalize :: \"real ^ 2 \\<Rightarrow> real ^ 2\"\nwhere\n  \"normalize p = (if p = 0 then axis 1 1 else (1 / norm p) *\\<^sub>R p)\"\n\ndefinition radiant_of :: \"real ^ 2 \\<Rightarrow> real\"\nwhere\n  \"radiant_of p = (THE \\<omega>. 0 \\<le> \\<omega> \\<and> \\<omega> < 2 * pi \\<and> of_radiant \\<omega> = normalize p)\"\n\ntext \\<open>\nThe vector @{term \"of_radiant \\<omega>\"} is the vector with length @{term \"1::real\"} and angle @{term \"\\<omega>\"}\nto the first axis.\nWe normalize vectors to length @{term \"1::real\"} keeping their orientation with the normalize function.\nConversely, @{term \"radiant_of p\"} is the angle of vector @{term p} to the first axis, where we\nchoose @{term \"radiant_of\"} to return angles between @{term \"0::real\"} and @{term \"2 * pi\"},\nfollowing the usual high-school convention.\nWith these definitions, we can express the main result\n@{term \"norm p *\\<^sub>R of_radiant (radiant_of p) = p\"}.\nNote that the main result holds for any definition of @{term \"radiant_of 0\"}.\nSo, we choose to define @{term \"normalize 0\"} and @{term \"radiant_of 0\"}, such that\n@{term \"radiant_of 0 = 0\"}.\n\\<close>\n\nsubsubsection \\<open>Lemmas on @{const of_radiant}\\<close>\n\nlemma nth_of_radiant_1 [simp]:\n  \"of_radiant \\<omega> $ 1 = cos \\<omega>\"\nunfolding of_radiant_def by simp\n\nlemma nth_of_radiant_2 [simp]:\n  \"of_radiant \\<omega> $ 2 = sin \\<omega>\"\nunfolding of_radiant_def by simp\n\nlemma norm_of_radiant:\n  \"norm (of_radiant \\<omega>) = 1\"\nunfolding of_radiant_def norm_eq_on_real_2_vec by simp\n\nlemma of_radiant_plus_2pi:\n  \"of_radiant (\\<omega> + 2 * pi) = of_radiant \\<omega>\"\nunfolding of_radiant_def by simp\n\nlemma of_radiant_minus_2pi:\n  \"of_radiant (\\<omega> - 2 * pi) = of_radiant \\<omega>\"\nproof -\n  have \"of_radiant (\\<omega> - 2 * pi) = of_radiant (\\<omega> - 2 * pi + 2 * pi)\"\n    by (simp only: of_radiant_plus_2pi)\n  also have \"\\<dots> = of_radiant \\<omega>\" by simp\n  finally show ?thesis .\nqed\n\nsubsubsection \\<open>Lemmas on @{const normalize}\\<close>\n\nlemma normalize_eq:\n  \"norm p *\\<^sub>R normalize p = p\"\nunfolding normalize_def by simp\n\n\n\nlemma nth_normalize [simp]:\n  \"\\<bar>normalize p $ i\\<bar> \\<le> 1\"\nusing norm_normalize component_le_norm_cart by metis\n\nlemma normalize_square:\n  \"(normalize p $ 1)\\<^sup>2 + (normalize p $ 2)\\<^sup>2 = 1\"\nusing dot_square_norm[of \"normalize p\"]\nby (simp add: inner_vec_def UNIV_2 power2_eq_square norm_normalize)\n\nlemma nth_normalize_ge_zero_iff:\n  \"0 \\<le> normalize p $ i \\<longleftrightarrow> 0 \\<le> p $ i\"\nproof\n  assume \"0 \\<le> normalize p $ i\"\n  from this show \"0 \\<le> p $ i\"\n    unfolding normalize_def by (auto split: if_split_asm simp add: zero_le_divide_iff)\nnext\n  assume \"0 \\<le> p $ i\"\n  have \"0 \\<le> axis 1 (1 :: real) $ i\"\n    using exhaust_2[of i] by auto\n  from this \\<open>0 \\<le> p $ i\\<close> show \"0 \\<le> normalize p $ i\"\n    unfolding normalize_def by auto\nqed\n\nlemma nth_normalize_less_zero_iff:\n  \"normalize p $ i < 0 \\<longleftrightarrow> p $ i < 0\"\nusing nth_normalize_ge_zero_iff leD leI by metis\n\nlemma normalize_boundary_iff:\n  \"\\<bar>normalize p $ 1\\<bar> = 1 \\<longleftrightarrow> p $ 2 = 0\"\nproof\n  assume \"\\<bar>normalize p $ 1\\<bar> = 1\"\n  from this have 1: \"(p $ 1) ^ 2 = norm p ^ 2\"\n    unfolding normalize_def by (auto split: if_split_asm simp add: power2_eq_iff)\n  moreover have \"(p $ 1) ^ 2 + (p $ 2) ^ 2 = norm p ^ 2\"\n    using norm_eq_on_real_2_vec by auto\n  ultimately show \"p $ 2 = 0\" by simp\nnext\n  assume \"p $ 2 = 0\"\n  from this have \"\\<bar>p $ 1\\<bar> = norm p\"\n    by (auto simp add: norm_eq_on_real_2_vec)\n  from this show \"\\<bar>normalize p $ 1\\<bar> = 1\"\n    unfolding normalize_def by simp\nqed\n\nlemma between_normalize_if_distant_from_0:\n  assumes \"norm p \\<ge> 1\"\n  shows \"between (0, p) (normalize p)\"\nusing assms by (auto simp add: between_mem_segment closed_segment_def normalize_def)\n\nlemma between_normalize_if_near_0:\n  assumes \"norm p \\<le> 1\"\n  shows \"between (0, normalize p) p\"\nproof -\n  have \"0 \\<le> norm p\" by simp\n  from assms have \"p = (norm p / norm p) *\\<^sub>R p \\<and> 0 \\<le> norm p \\<and> norm p \\<le> 1\" by auto\n  from this have \"\\<exists>u. p = (u / norm p) *\\<^sub>R p \\<and> 0 \\<le> u \\<and> u \\<le> 1\" by blast\n  from this show ?thesis\n    by (auto simp add: between_mem_segment closed_segment_def normalize_def)\nqed\n\nsubsubsection \\<open>Lemmas on @{const radiant_of}\\<close>\n\nlemma radiant_of:\n  \"0 \\<le> radiant_of p \\<and> radiant_of p < 2 * pi \\<and> of_radiant (radiant_of p) = normalize p\"\nproof -\n  let ?a = \"if 0 \\<le> p $ 2 then arccos (normalize p $ 1) else pi + arccos (- (normalize p $ 1))\"\n  have \"0 \\<le> ?a \\<and> ?a < 2 * pi \\<and> of_radiant ?a = normalize p\"\n  proof -\n    have \"0 \\<le> ?a\" by auto\n    moreover have \"?a < 2 * pi\"\n    proof cases\n      assume \"0 \\<le> p $ 2\"\n      from this have \"?a \\<le> pi\" by simp\n      from this show ?thesis\n        using pi_gt_zero by linarith\n    next\n      assume \"\\<not> 0 \\<le> p $ 2\"\n      have \"arccos (- normalize p $ 1) < pi\"\n      proof -\n        have \"\\<bar>normalize p $ 1\\<bar> \\<noteq> 1\"\n          using \\<open>\\<not> 0 \\<le> p $ 2\\<close> by (simp only: normalize_boundary_iff)\n        from this have \"arccos (- normalize p $ 1) \\<noteq> pi\"\n          unfolding arccos_minus_1[symmetric] by (subst arccos_eq_iff) auto\n        moreover have \"arccos (- normalize p $ 1) \\<le> pi\" by simp\n        ultimately show \"arccos (- normalize p $ 1) < pi\" by linarith\n      qed\n      from this \\<open>\\<not> 0 \\<le> p $ 2\\<close> show ?thesis by simp\n    qed\n    moreover have \"of_radiant ?a = normalize p\"\n    proof -\n      have \"of_radiant ?a $ i = normalize p $ i\" for i\n      proof -\n        have \"of_radiant ?a $ 1 = normalize p $ 1\"\n          unfolding of_radiant_def by (simp add: cos_arccos_abs)\n        moreover have \"of_radiant ?a $ 2 = normalize p $ 2\"\n        proof cases\n          assume \"0 \\<le> p $ 2\"\n          have \"sin (arccos (normalize p $ 1)) = sqrt (1 - (normalize p $ 1) ^ 2)\"\n            by (simp add: sin_arccos_abs)\n          also have \"\\<dots> = normalize p $ 2\"\n          proof -\n            have \"1 - (normalize p $ 1)\\<^sup>2 = (normalize p $ 2)\\<^sup>2\"\n              using normalize_square[of p] by auto\n            from this \\<open>0 \\<le> p $ 2\\<close> show ?thesis by (simp add: nth_normalize_ge_zero_iff)\n          qed\n          finally show ?thesis\n            using \\<open>0 \\<le> p $ 2\\<close> unfolding of_radiant_def by auto\n        next\n          assume \"\\<not> 0 \\<le> p $ 2\"\n          have \"- sin (arccos (- normalize p $ 1)) = - sqrt (1 - (normalize p $ 1)\\<^sup>2)\"\n            by (simp add: sin_arccos_abs)\n          also have \"\\<dots> = normalize p $ 2\"\n          proof -\n            have \"1 - (normalize p $ 1)\\<^sup>2 = (normalize p $ 2)\\<^sup>2\"\n              using normalize_square[of p] by auto\n            from this \\<open>\\<not> 0 \\<le> p $ 2\\<close> show ?thesis\n              using nth_normalize_ge_zero_iff by fastforce\n          qed\n          finally show ?thesis\n            using \\<open>\\<not> 0 \\<le> p $ 2\\<close> unfolding of_radiant_def by auto\n        qed\n        ultimately show ?thesis by (metis exhaust_2[of i])\n      qed\n      from this show ?thesis by (simp add: vec_eq_iff)\n    qed\n    ultimately show ?thesis by blast\n  qed\n  moreover {\n    fix \\<omega>\n    assume \"0 \\<le> \\<omega> \\<and> \\<omega> < 2 * pi \\<and> of_radiant \\<omega> = normalize p\"\n    from this have \"0 \\<le> \\<omega>\" \"\\<omega> < 2 * pi\" \"normalize p = of_radiant \\<omega>\" by auto\n    from this have \"cos \\<omega> = normalize p $ 1\" \"sin \\<omega> = normalize p $ 2\" by auto\n    have \"\\<omega> = ?a\"\n    proof cases\n      assume \"0 \\<le> p $ 2\"\n      from this have \"\\<omega> \\<le> pi\"\n        using \\<open>0 \\<le> \\<omega>\\<close> \\<open>\\<omega> < 2 * pi\\<close> \\<open>sin \\<omega> = normalize p $ 2\\<close>\n        by (simp add: sin_ge_zero_iff[symmetric] nth_normalize_ge_zero_iff)\n      from \\<open>0 \\<le> \\<omega>\\<close> this have \"\\<omega> = arccos (cos \\<omega>)\" by (simp add: arccos_cos)\n      from \\<open>cos \\<omega> = normalize p $ 1\\<close> this have \"\\<omega> = arccos (normalize p $ 1)\"\n        by (simp add: arccos_eq_iff)\n      from this show \"\\<omega> = ?a\" using \\<open>0 \\<le> p $ 2\\<close> by auto\n    next\n      assume \"\\<not> 0 \\<le> p $ 2\"\n      from this have \"\\<omega> > pi\"\n        using \\<open>0 \\<le> \\<omega>\\<close> \\<open>\\<omega> < 2 * pi\\<close> \\<open>sin \\<omega> = normalize p $ 2\\<close>\n        by (simp add: sin_less_zero_iff[symmetric] nth_normalize_less_zero_iff)\n      from this \\<open>\\<omega> < 2 * pi\\<close> have \"\\<omega> - pi = arccos (cos (\\<omega> - pi))\"\n        by (auto simp only: arccos_cos)\n      from this \\<open>cos \\<omega> = normalize p $ 1\\<close> have \"\\<omega> - pi = arccos (- normalize p $ 1)\" by simp\n      from this have \"\\<omega> = pi + arccos (- normalize p $ 1)\" by simp\n      from this show \"\\<omega> = ?a\" using \\<open>\\<not> 0 \\<le> p $ 2\\<close> by auto\n    qed\n  }\n  ultimately show ?thesis\n    unfolding radiant_of_def by (rule theI)\nqed\n\nlemma radiant_of_bounds [simp]:\n  \"0 \\<le> radiant_of p\" \"radiant_of p < 2 * pi\"\nusing radiant_of by auto\n\nlemma radiant_of_weak_ubound [simp]:\n  \"radiant_of p \\<le> 2 * pi\"\nusing radiant_of_bounds(2)[of p] by linarith\n\nsubsubsection \\<open>Main Equations for Transforming to Polar Form\\<close>\n\nlemma polar_form_eq:\n  \"norm p *\\<^sub>R of_radiant (radiant_of p) = p\"\nusing radiant_of normalize_eq by simp\n\nlemma relative_polar_form_eq:\n  \"Q + dist P Q *\\<^sub>R of_radiant (radiant_of (P - Q)) = P\"\nproof -\n  have \"norm (P - Q) *\\<^sub>R of_radiant (radiant_of (P - Q)) = P - Q\"\n    unfolding polar_form_eq ..\n  moreover have \"dist P Q = norm (P - Q)\" by (simp add: dist_norm)\n  ultimately show ?thesis by (metis add.commute diff_add_cancel)\nqed\n\nsubsection \\<open>Ptolemy's Theorem\\<close>\n\nlemma dist_circle_segment:\n  assumes \"0 \\<le> radius\" \"0 \\<le> \\<alpha>\" \"\\<alpha> \\<le> \\<beta>\" \"\\<beta> \\<le> 2 * pi\"\n  shows \"dist (center + radius *\\<^sub>R of_radiant \\<alpha>) (center + radius *\\<^sub>R of_radiant \\<beta>) = 2 * radius * sin ((\\<beta> - \\<alpha>) / 2)\"\n    (is \"?lhs = ?rhs\")\nproof -\n  have trigonometry: \"(cos \\<alpha> - cos \\<beta>)\\<^sup>2 + (sin \\<alpha> - sin \\<beta>)\\<^sup>2 = (2 *  sin ((\\<beta> - \\<alpha>) / 2))\\<^sup>2\"\n  proof -\n    have sin_diff_minus: \"sin ((\\<alpha> - \\<beta>) / 2) = - sin ((\\<beta> - \\<alpha>) / 2)\"\n      by (simp only: sin_minus[symmetric] minus_divide_left minus_diff_eq)\n    have \"(cos \\<alpha> - cos \\<beta>)\\<^sup>2 + (sin \\<alpha> - sin \\<beta>)\\<^sup>2 =\n      (2 * sin ((\\<alpha> + \\<beta>) / 2) * sin ((\\<beta> - \\<alpha>) / 2))\\<^sup>2 + (2 * sin ((\\<alpha> - \\<beta>) / 2) * cos ((\\<alpha> + \\<beta>) / 2))\\<^sup>2\"\n      by (simp only: cos_diff_cos sin_diff_sin)\n    also have \"\\<dots> = (2 * sin ((\\<beta> - \\<alpha>) / 2))\\<^sup>2 * ((sin ((\\<alpha> + \\<beta>) / 2))\\<^sup>2 + (cos ((\\<alpha> + \\<beta>) / 2))\\<^sup>2)\"\n      unfolding sin_diff_minus by algebra\n    also have \"\\<dots> = (2 *  sin ((\\<beta> - \\<alpha>) / 2))\\<^sup>2\" by simp\n    finally show ?thesis .\n  qed\n  from assms have \"0 \\<le> sin ((\\<beta> - \\<alpha>) / 2)\" by (simp add: sin_ge_zero)\n  have \"?lhs = sqrt (radius\\<^sup>2 * ((cos \\<alpha> - cos \\<beta>)\\<^sup>2 + (sin \\<alpha> - sin \\<beta>)\\<^sup>2))\"\n    unfolding dist_eq_on_real_2_vec by simp algebra\n  also have \"\\<dots> = sqrt (radius\\<^sup>2 *  (2 * sin ((\\<beta> - \\<alpha>) / 2))\\<^sup>2)\" by (simp add: trigonometry)\n  also have \"\\<dots> = ?rhs\"\n    using \\<open>0 \\<le> radius\\<close> \\<open>0 \\<le> sin ((\\<beta> - \\<alpha>) / 2)\\<close> by (simp add: real_sqrt_mult)\n  finally show ?thesis .\nqed\n\ntheorem ptolemy_trigonometric:\n  fixes \\<omega>\\<^sub>1 \\<omega>\\<^sub>2 \\<omega>\\<^sub>3 :: real\n  shows \"sin (\\<omega>\\<^sub>1 + \\<omega>\\<^sub>2) * sin (\\<omega>\\<^sub>2 + \\<omega>\\<^sub>3) = sin \\<omega>\\<^sub>1 * sin \\<omega>\\<^sub>3 + sin \\<omega>\\<^sub>2 * sin (\\<omega>\\<^sub>1 + \\<omega>\\<^sub>2 + \\<omega>\\<^sub>3)\"\nproof -\n  have \"sin (\\<omega>\\<^sub>1 + \\<omega>\\<^sub>2) * sin (\\<omega>\\<^sub>2 + \\<omega>\\<^sub>3) = ((sin \\<omega>\\<^sub>2)\\<^sup>2 + (cos \\<omega>\\<^sub>2)\\<^sup>2) * sin \\<omega>\\<^sub>1 * sin \\<omega>\\<^sub>3 + sin \\<omega>\\<^sub>2 * sin (\\<omega>\\<^sub>1 + \\<omega>\\<^sub>2 + \\<omega>\\<^sub>3)\"\n    by (simp only: sin_add cos_add) algebra\n  also have \"\\<dots> = sin \\<omega>\\<^sub>1 * sin \\<omega>\\<^sub>3 + sin \\<omega>\\<^sub>2 * sin (\\<omega>\\<^sub>1 + \\<omega>\\<^sub>2 + \\<omega>\\<^sub>3)\" by simp\n  finally show ?thesis .\nqed\n\ntheorem ptolemy:\n  fixes A B C D center :: \"real ^ 2\"\n  assumes \"dist center A = radius\" and \"dist center B = radius\"\n  assumes \"dist center C = radius\" and \"dist center D = radius\"\n  assumes ordering_of_points:\n    \"radiant_of (A - center) \\<le> radiant_of (B - center)\"\n    \"radiant_of (B - center) \\<le> radiant_of (C - center)\"\n    \"radiant_of (C - center) \\<le> radiant_of (D - center)\"\n  shows \"dist A C * dist B D = dist A B * dist C D + dist A D * dist B C\"\nproof -\n  from \\<open>dist center A = radius\\<close> have \"0 \\<le> radius\" by auto\n  define \\<alpha> \\<beta> \\<gamma> \\<delta>\n    where \"\\<alpha> = radiant_of (A - center)\" and \"\\<beta> = radiant_of (B - center)\"\n    and \"\\<gamma> = radiant_of (C - center)\" and \"\\<delta> = radiant_of (D - center)\"\n  from ordering_of_points have angle_basics:\n    \"\\<alpha> \\<le> \\<beta>\" \"\\<beta> \\<le> \\<gamma>\" \"\\<gamma> \\<le> \\<delta>\"\n    \"0 \\<le> \\<alpha>\" \"\\<alpha> \\<le> 2 * pi\" \"0 \\<le> \\<beta>\" \"\\<beta> \\<le> 2 * pi\"\n    \"0 \\<le> \\<gamma>\" \"\\<gamma> \\<le> 2 * pi\" \"0 \\<le> \\<delta>\" \"\\<delta> \\<le> 2 * pi\"\n    unfolding \\<alpha>_def \\<beta>_def \\<gamma>_def \\<delta>_def by auto\n  from assms(1-4) have\n    \"A = center + radius *\\<^sub>R of_radiant \\<alpha>\" \"B = center + radius *\\<^sub>R of_radiant \\<beta>\"\n    \"C = center + radius *\\<^sub>R of_radiant \\<gamma>\" \"D = center + radius *\\<^sub>R of_radiant \\<delta>\"\n    unfolding \\<alpha>_def \\<beta>_def \\<gamma>_def \\<delta>_def\n    using relative_polar_form_eq dist_commute by metis+\n\n  from this have dist_eqs:\n    \"dist A C = 2 * radius * sin ((\\<gamma> - \\<alpha>) / 2)\"\n    \"dist B D = 2 * radius * sin ((\\<delta> - \\<beta>) / 2)\"\n    \"dist A B = 2 * radius * sin ((\\<beta> - \\<alpha>) / 2)\"\n    \"dist C D = 2 * radius * sin ((\\<delta> - \\<gamma>) / 2)\"\n    \"dist A D = 2 * radius * sin ((\\<delta> - \\<alpha>) / 2)\"\n    \"dist B C = 2 * radius * sin ((\\<gamma> - \\<beta>) / 2)\"\n    using angle_basics \\<open>radius \\<ge> 0\\<close> dist_circle_segment by (auto)\n\n  have \"dist A C * dist B D = 4 * radius ^ 2 * sin ((\\<gamma> - \\<alpha>) / 2) * sin ((\\<delta> - \\<beta>) / 2)\"\n    unfolding dist_eqs by (simp add: power2_eq_square)\n  also have \"\\<dots> = 4 * radius ^ 2 * (sin ((\\<beta> - \\<alpha>) / 2) * sin ((\\<delta> - \\<gamma>) / 2) + sin ((\\<gamma> - \\<beta>) / 2) * sin ((\\<delta> - \\<alpha>) / 2))\"\n  proof -\n    define \\<omega>\\<^sub>1 \\<omega>\\<^sub>2 \\<omega>\\<^sub>3 where \"\\<omega>\\<^sub>1 = (\\<beta> - \\<alpha>) / 2\" and \"\\<omega>\\<^sub>2 = (\\<gamma> - \\<beta>) / 2\" and \"\\<omega>\\<^sub>3 = (\\<delta> - \\<gamma>) / 2\"\n    have \"(\\<gamma> - \\<alpha>) / 2 = \\<omega>\\<^sub>1 + \\<omega>\\<^sub>2\" and \"(\\<delta> - \\<beta>) / 2 = \\<omega>\\<^sub>2 + \\<omega>\\<^sub>3\" and \"(\\<delta> - \\<alpha>) / 2 = \\<omega>\\<^sub>1 + \\<omega>\\<^sub>2 + \\<omega>\\<^sub>3\"\n      unfolding \\<omega>\\<^sub>1_def \\<omega>\\<^sub>2_def \\<omega>\\<^sub>3_def by (auto simp add: field_simps)\n    have \"sin ((\\<gamma> - \\<alpha>) / 2) * sin ((\\<delta> - \\<beta>) / 2) = sin (\\<omega>\\<^sub>1 + \\<omega>\\<^sub>2) * sin (\\<omega>\\<^sub>2 + \\<omega>\\<^sub>3)\"\n      using \\<open>(\\<gamma> - \\<alpha>) / 2 = \\<omega>\\<^sub>1 + \\<omega>\\<^sub>2\\<close> \\<open>(\\<delta> - \\<beta>) / 2 = \\<omega>\\<^sub>2 + \\<omega>\\<^sub>3\\<close> by (simp only:)\n    also have \"\\<dots> = sin \\<omega>\\<^sub>1 * sin \\<omega>\\<^sub>3 + sin \\<omega>\\<^sub>2 * sin (\\<omega>\\<^sub>1 + \\<omega>\\<^sub>2 + \\<omega>\\<^sub>3)\"\n      by (rule ptolemy_trigonometric)\n    also have \"\\<dots> = (sin ((\\<beta> - \\<alpha>) / 2) * sin ((\\<delta> - \\<gamma>) / 2) + sin ((\\<gamma> - \\<beta>) / 2) * sin ((\\<delta> - \\<alpha>) / 2))\"\n      using \\<omega>\\<^sub>1_def \\<omega>\\<^sub>2_def \\<omega>\\<^sub>3_def \\<open>(\\<delta> - \\<alpha>) / 2 = \\<omega>\\<^sub>1 + \\<omega>\\<^sub>2 + \\<omega>\\<^sub>3\\<close> by (simp only:)\n    finally show ?thesis by simp\n  qed\n  also have \"\\<dots> = dist A B * dist C D + dist A D * dist B C\"\n    unfolding dist_eqs by (simp add: distrib_left power2_eq_square)\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/Ptolemys_Theorem/Ptolemys_Theorem.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8289387914176259, "lm_q2_score": 0.8499711737573762, "lm_q1q2_score": 0.7045740775142604}}
{"text": "(*  Title:       Category theory using Isar and Locales\n    Author:      Greg O'Keefe, June, July, August 2003\n    License: LGPL\n\nDefine natural transformation, prove that the identity arrow function is one.\n*)\n\nsection \\<open>Natural Transformations\\<close>\n\ntheory NatTrans\nimports Functors\nbegin\n\n(* guess the third axiom is implied by the fifth *)\nlocale natural_transformation = two_cats +\n  fixes F and G and u\n  assumes \"Functor F : AA \\<longrightarrow> BB\"\n  and \"Functor G : AA \\<longrightarrow> BB\"\n  and \"u : ob AA \\<rightarrow> ar BB\"\n  and \"u \\<in> extensional (ob AA)\"\n  and \"\\<forall>A\\<in>Ob. u A \\<in> Hom\\<^bsub>BB\\<^esub> (F\\<^bsub>\\<o>\\<^esub> A) (G\\<^bsub>\\<o>\\<^esub> A)\" \n  and \"\\<forall>A\\<in>Ob. \\<forall>B\\<in>Ob. \\<forall>f\\<in>Hom A B. (G\\<^bsub>\\<a>\\<^esub> f) \\<bullet>\\<^bsub>BB\\<^esub> (u A) = (u B) \\<bullet>\\<^bsub>BB\\<^esub> (F\\<^bsub>\\<a>\\<^esub> f)\"\n\nabbreviation\n  nt_syn  (\"_ : _ \\<Rightarrow> _ in Func '(_ , _ ')\" [81]) where\n  \"u : F \\<Rightarrow> G in Func(AA, BB) \\<equiv> natural_transformation AA BB F G u\"\n\n(* is this doing what I think its doing? *)\nlocale endoNT = natural_transformation + one_cat\n\ntheorem (in endoNT) id_restrict_natural:\n  \"(\\<lambda>A\\<in>Ob. Id A) : (id_func AA) \\<Rightarrow> (id_func AA) in Func(AA,AA)\"\nproof (intro natural_transformation.intro natural_transformation_axioms.intro \n    two_cats.intro ballI)\n  show \"(\\<lambda>A\\<in>Ob. Id A) : Ob \\<rightarrow> Ar\"\n    by (rule funcsetI) auto\n  show \"(\\<lambda>A\\<in>Ob. Id A) \\<in> extensional (Ob)\"\n    by (rule restrict_extensional)\n  fix A \n  assume A: \"A \\<in> Ob\" \n  hence \"Id A \\<in> Hom A A\" ..\n  thus \"(\\<lambda>X\\<in>Ob. Id X) A \\<in> Hom ((id_func AA)\\<^bsub>\\<o>\\<^esub> A)  ((id_func AA)\\<^bsub>\\<o>\\<^esub> A)\"\n    using A by (simp add: id_func_def) \n  fix B and f\n  assume B: \"B \\<in> Ob\" \n    and \"f \\<in> Hom A B\"\n  hence \"f \\<in> Ar\" and \"A = Dom f\" and \"B = Cod f\" and \"Dom f \\<in> Ob\" and \"Cod f \\<in> Ob\"\n    using A by (simp_all add: hom_def)\n  thus \"(id_func AA)\\<^bsub>\\<a>\\<^esub> f \\<bullet> (\\<lambda>A\\<in>Ob. Id A) A\n      = (\\<lambda>A\\<in>Ob. Id A) B \\<bullet> (id_func AA)\\<^bsub>\\<a>\\<^esub> f\"\n    by (simp add:  id_func_def)\nqed (auto intro: id_func_functor, unfold_locales, unfold_locales)\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/Category/NatTrans.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.86153820232079, "lm_q2_score": 0.8175744828610095, "lm_q1q2_score": 0.7043716502274238}}
{"text": "theory Pls_ac_enat\n  imports Main  \"~~/src/HOL/Library/BNF_Corec\" \"$HIPSTER_HOME/IsaHipster\" \nbegin    \n  \nsetup Tactic_Data.set_coinduct_sledgehammer  \n\ncodatatype (sset: 'a) Stream =\n  SCons (shd: 'a) (stl: \"'a Stream\")\n\ncodatatype ENat = is_zero: EZ | ESuc (epred: ENat)\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\nprimcorec pls :: \"ENat Stream \\<Rightarrow> ENat Stream \\<Rightarrow> ENat Stream\" where\n  \"pls s t = SCons (eplus (shd s) (shd t)) (pls (stl s) (stl t))\"\n\ndatatype 'a Lst = \n  Emp\n  | Cons \"'a\" \"'a Lst\"\n    \nfun obsStream :: \"int \\<Rightarrow> 'a Stream \\<Rightarrow> 'a Lst\" where\n\"obsStream n s = (if (n \\<le> 0) then Emp else Cons (shd s) (obsStream (n - 1) (stl s)))\"\n\n(*hipster_obs Stream Lst obsStream pls*)\nlemma lemma_a [thy_expl]: \"eplus x EZ = x\"\n  apply (coinduction  arbitrary: x rule: Pls_ac_enat.ENat.coinduct_strong)\n  by simp\n\nlemma lemma_aa [thy_expl]: \"eplus EZ x = x\"\n  apply (coinduction  arbitrary: x rule: Pls_ac_enat.ENat.coinduct_strong)\n  by simp\n    \nlemma lemma_ab [thy_expl]: \"eplus (ESuc x) y = eplus x (ESuc y)\"\n  apply (coinduction  arbitrary: x y rule: Pls_ac_enat.ENat.coinduct_strong)\n  apply simp\n  by (metis ENat.collapse(2) eplus.code)\n    \nlemma lemma_ac [thy_expl]: \"ESuc (eplus x y) = eplus x (ESuc y)\"\n  apply (coinduction  arbitrary: x y rule: Pls_ac_enat.ENat.coinduct_strong)\n  apply simp\n  by (metis eplus.code)\n    \nlemma lemma_ad [thy_expl]: \"eplus (eplus x y) z = eplus x (eplus y z)\"\n  apply (coinduction  arbitrary: x y z rule: Pls_ac_enat.ENat.coinduct_strong)\n  apply simp\n  by blast\n    \nlemma lemma_ae [thy_expl]: \"eplus y x = eplus x y\"\n  apply (coinduction  arbitrary: x y rule: Pls_ac_enat.ENat.coinduct_strong)\n  apply simp\n  by (metis ENat.collapse(1) ENat.collapse(2) lemma_a lemma_ab)\n\nlemma pls_ac: \"pls s (pls t u) = pls t (pls s u)\"\n  by hipster_coinduct_sledgehammer\n  (*by hipster_coinduct_sledgehammer\nFailed to apply initial proof method\\<here>:*)\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/CoTutorial/Pls_ac_enat.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278757303677, "lm_q2_score": 0.7981867825403177, "lm_q1q2_score": 0.7043422669531095}}
{"text": "theory Free_Idempotent_Monoid imports\n  Main\nbegin\n\n\n\n\n\ntext \\<open>The free idempotent monoid does not have unique normal forms if we just use the cancellation law\\<close>\n\n\ninductive cancel1 :: \"'a list \\<Rightarrow> 'a list \\<Rightarrow> bool\"\nwhere cancel1: \"xs \\<noteq> [] \\<Longrightarrow> cancel1 (gs @ xs @ xs @ gs') (gs @ xs @ gs')\"\n\nlemma cancel1_append_same1: \n  assumes \"cancel1 xs ys\"\n  shows \"cancel1 (zs @ xs) (zs @ ys)\"\nusing assms\nproof cases\n  case (cancel1 ys gs gs')\n  from \\<open>ys \\<noteq> []\\<close> have \"cancel1 ((zs @ gs) @ ys @ ys @ gs') ((zs @ gs) @ ys @ gs')\" ..\n  with cancel1 show ?thesis by simp\nqed\n\nlemma cancel1_append_same2: \"cancel1 xs ys \\<Longrightarrow> cancel1 (xs @ zs) (ys @ zs)\"\nby(cases rule: cancel1.cases)(auto intro: cancel1.intros)\n\nlemma cancel1_same:\n  assumes \"xs \\<noteq> []\"\n  shows \"cancel1 (xs @ xs) xs\"\nproof -\n  have \"cancel1 ([] @ xs @ xs @ []) ([] @ xs @ [])\" using assms ..\n  thus ?thesis by simp\nqed\n\ndefinition sclp :: \"('a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> bool\"\nwhere \"sclp r x y \\<longleftrightarrow> r x y \\<or> r y x\"\n\nlemma sclpI [simp, intro?]: \n  shows sclpI1: \"r x y \\<Longrightarrow> sclp r x y\"\n  and sclpI2: \"r y x \\<Longrightarrow> sclp r x y\"\nby(simp_all add: sclp_def)\n\nlemma sclpE:\n  assumes \"sclp r x y\"\n  obtains (base) \"r x y\" | (sym) \"r y x\"\nusing assms by(auto simp add: sclp_def)\n\nabbreviation eq :: \"'a list \\<Rightarrow> 'a list \\<Rightarrow> bool\"\nwhere \"eq \\<equiv> (sclp cancel1)\\<^sup>*\\<^sup>*\"\n\nlemma eq_sym: \"eq x y \\<Longrightarrow> eq y x\"\nby(induction rule: rtranclp_induct)(auto intro: sclpI converse_rtranclp_into_rtranclp elim!: sclpE)\n\nlemma equivp_eq: \"equivp eq\"\nby(intro equivpI reflpI sympI transpI)(auto intro: eq_sym)\n\nlemma eq_append_same1: \"eq xs' ys' \\<Longrightarrow> eq (xs @ xs') (xs @ ys')\"\nby(induction rule: rtranclp_induct)(auto intro: cancel1_append_same1 rtranclp.rtrancl_into_rtrancl sclpI elim!: sclpE)\n\nlemma append_eq_cong: \"\\<lbrakk>eq xs ys; eq xs' ys'\\<rbrakk> \\<Longrightarrow> eq (xs @ xs') (ys @ ys')\"\nby(induction rule: rtranclp_induct)(auto intro: eq_append_same1 rtranclp.rtrancl_into_rtrancl cancel1_append_same2 elim!: sclpE intro: sclpI)\n\nquotient_type 'a fim = \"'a list\" / eq\nby(rule equivp_eq)\n\ninstantiation fim :: (type) monoid_add begin\nlift_definition zero_fim :: \"'a fim\" is \"[]\" .\nlift_definition plus_fim :: \"'a fim \\<Rightarrow> 'a fim \\<Rightarrow> 'a fim\" is \"op @\" by(rule append_eq_cong)\ninstance by(intro_classes; transfer; simp)\nend\n\nlemma plus_idem_fim [simp]: fixes x :: \"'a fim\" shows \"x + x = x\"\nproof transfer\n  fix xs :: \"'a list\"\n  show \"eq (xs @ xs) xs\"\n  proof(cases \"xs = []\")\n    case False thus ?thesis using cancel1_same[of xs] by(auto intro: sclpI1)\n  qed simp\nqed\n\n\n\ntype_synonym ('a, 'b) af = \"'a fim \\<times> 'b\"\n\ndefinition pure :: \"'b \\<Rightarrow> ('a, 'b) af\"\nwhere \"pure x = (0, x)\"\n\nfun ap :: \"('a, 'b \\<Rightarrow> 'c) af \\<Rightarrow> ('a, 'b) af \\<Rightarrow> ('a, 'c) af\" (infixl \"\\<diamond>\" 60)\nwhere \"ap (u, f) (v, x) = (u + v, f x)\"\n\nlemma af_identity: \"pure id \\<diamond> x = x\"\nunfolding pure_def by(cases x) simp\n\nlemma af_homomorphism: \"pure f \\<diamond> pure x = pure (f x)\"\nunfolding pure_def by simp\n\nlemma af_composition: \"\\<And>g f x. pure comp \\<diamond> g \\<diamond> f \\<diamond> x = g \\<diamond> (f \\<diamond> x)\"\nunfolding pure_def by(clarsimp simp add: add_ac)\n\nlemma af_interchange: \"f \\<diamond> pure x = pure (\\<lambda>g. g x) \\<diamond> f\"\nunfolding pure_def by(cases f) simp\n\ndefinition W :: \"('x, ('a \\<Rightarrow> 'a \\<Rightarrow> 'b) \\<Rightarrow> 'a \\<Rightarrow> 'b) af\"\nwhere \"W = pure (\\<lambda>f x. f x x)\"\n\nlemma ap_W: \"W \\<diamond> f \\<diamond> x = f \\<diamond> x \\<diamond> x\"\nunfolding W_def pure_def\napply(cases f)\napply(cases x)\napply(rename_tac u f' v g')\napply(simp add: add_ac)\ndone\n\ntext \\<open> There is no combinator H because fim is the free idempotent monoid\\<close>\n\nend\n", "meta": {"author": "jshs", "repo": "applicative-lifting", "sha": "b58742496635799300e3400b56e83b6b5e0a3b7d", "save_path": "github-repos/isabelle/jshs-applicative-lifting", "path": "github-repos/isabelle/jshs-applicative-lifting/applicative-lifting-b58742496635799300e3400b56e83b6b5e0a3b7d/experiments/Free_Idempotent_Monoid.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.882427857178614, "lm_q2_score": 0.7981867825403176, "lm_q1q2_score": 0.7043422521453448}}
{"text": "theory \"Denotational_Semantics\" \nimports\n  Ordinary_Differential_Equations.ODE_Analysis\n  \"Lib\"\n  \"Ids\"\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\\<comment> \\<open>Vector of reals of length \\<open>'a\\<close>\\<close>\ntype_synonym 'a Rvec = \"real^('a::finite)\"\n\\<comment> \\<open>A state specifies one vector of values for unprimed variables \\<open>x\\<close> and a second vector for \\<open>x'\\<close>\\<close>\ntype_synonym 'a state = \"'a Rvec \\<times> 'a Rvec\"\n\\<comment> \\<open>\\<open>'a simple_state\\<close> is half a state - either the \\<open>x\\<close>s or the \\<open>x'\\<close>s\\<close>\ntype_synonym 'a simple_state = \"'a Rvec\"\n\ndefinition Vagree :: \"'c::finite state \\<Rightarrow> 'c state \\<Rightarrow> ('c + 'c) 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 :: \"'c::finite simple_state \\<Rightarrow> 'c simple_state \\<Rightarrow> 'c set \\<Rightarrow> bool\"\nwhere \"VSagree \\<nu> \\<nu>' V \\<longleftrightarrow> (\\<forall>i \\<in> V. (\\<nu> $ i) = (\\<nu>' $ i))\"\n\n\\<comment> \\<open>Agreement lemmas\\<close>\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_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 ('a, 'b, 'c) interp =\n  Functions       :: \"'a \\<Rightarrow> 'c Rvec \\<Rightarrow> real\"\n  Predicates      :: \"'c \\<Rightarrow> 'c Rvec \\<Rightarrow> bool\"\n  Contexts        :: \"'b \\<Rightarrow> 'c state set \\<Rightarrow> 'c state set\"\n  Programs        :: \"'c \\<Rightarrow> ('c state * 'c state) set\"\n  ODEs            :: \"'c \\<Rightarrow> 'c simple_state \\<Rightarrow> 'c simple_state\"\n  ODEBV           :: \"'c \\<Rightarrow> 'c set\"\n\nfun FunctionFrechet :: \"('a::finite, 'b::finite, 'c::finite) interp \\<Rightarrow> 'a \\<Rightarrow> 'c Rvec \\<Rightarrow> 'c Rvec \\<Rightarrow> real\"\n  where \"FunctionFrechet I i = (THE f'. \\<forall> x. (Functions I i has_derivative f' x) (at x))\"\n\n\\<comment> \\<open>For an interpretation to be valid, all functions must be differentiable everywhere.\\<close>\ndefinition is_interp :: \"('a::finite, 'b::finite, 'c::finite) 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\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\\<comment> \\<open>Agreement between interpretations.\\<close>\ndefinition Iagree :: \"('a::finite, 'b::finite, 'c::finite) interp \\<Rightarrow> ('a::finite, 'b::finite, 'c::finite) interp \\<Rightarrow> ('a + 'b + 'c) 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    (\\<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\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_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\\<comment> \\<open>Semantics for differential-free terms. Because there are no differentials, depends only on the \\<open>x\\<close> variables\\<close>\n\\<comment> \\<open>and not the \\<open>x'\\<close> variables.\\<close>\nprimrec sterm_sem :: \"('a::finite, 'b::finite, 'c::finite) interp \\<Rightarrow> ('a, 'c) trm \\<Rightarrow> 'c simple_state \\<Rightarrow> real\"\nwhere\n  \"sterm_sem I (Var x) v = v $ x\"\n| \"sterm_sem I (Function f args) v = Functions I f (\\<chi> i. sterm_sem I (args i) v)\"\n| \"sterm_sem I (Plus t1 t2) v = sterm_sem I t1 v + sterm_sem I t2 v\"\n| \"sterm_sem I (Times t1 t2) v = sterm_sem I t1 v * sterm_sem I t2 v\"\n| \"sterm_sem I (Const r) v = r\"\n| \"sterm_sem I ($' c) v = undefined\"\n| \"sterm_sem I (Differential d) v = undefined\"\n  \n\\<comment> \\<open>\\<open>frechet I \\<theta> \\<nu>\\<close> syntactically computes the frechet derivative of the term \\<open>\\<theta>\\<close> in the interpretation\\<close>\n\\<comment> \\<open>\\<open>I\\<close> at state \\<open>\\<nu>\\<close> (containing only the unprimed variables). The frechet derivative is a\\<close>\n\\<comment> \\<open>linear map from the differential state \\<open>\\<nu>\\<close> to reals.\\<close>\nprimrec frechet :: \"('a::finite, 'b::finite, 'c::finite) interp \\<Rightarrow> ('a, 'c) trm \\<Rightarrow> 'c simple_state \\<Rightarrow> 'c simple_state \\<Rightarrow> real\"\nwhere\n  \"frechet I (Var x) v = (\\<lambda>v'. v' \\<bullet> axis x 1)\"\n| \"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 I (Plus t1 t2) v = (\\<lambda>v'. frechet I t1 v v' + frechet I t2 v v')\"\n| \"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 I (Const r) v = (\\<lambda>v'. 0)\"\n| \"frechet I ($' c) v = undefined\"\n| \"frechet I (Differential d) v = undefined\"\n\ndefinition directional_derivative :: \"('a::finite, 'b::finite, 'c::finite) interp \\<Rightarrow> ('a, 'c) trm \\<Rightarrow> 'c state \\<Rightarrow> real\"\nwhere \"directional_derivative I t = (\\<lambda>v. frechet I t (fst v) (snd v))\"\n\n\\<comment> \\<open>Sem for terms that are allowed to contain differentials.\\<close>\n\\<comment> \\<open>Note there is some duplication with \\<open>sterm_sem\\<close>.\\<close>\nprimrec dterm_sem :: \"('a::finite, 'b::finite, 'c::finite) interp \\<Rightarrow> ('a, 'c) trm \\<Rightarrow> 'c 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 (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 (Differential t) = (\\<lambda>v. directional_derivative I t v)\"\n| \"dterm_sem I (Const c) = (\\<lambda>v. c)\"\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:: \"('a::finite, 'b::finite, 'c::finite) interp \\<Rightarrow> ('a, 'c) ODE \\<Rightarrow> 'c Rvec \\<Rightarrow> 'c Rvec\"\n  where\n  ODE_sem_OVar:\"ODE_sem I (OVar x) = ODEs I x\"\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\\<comment> \\<open>Note: Could define using \\<open>SOME\\<close> operator in a way that more closely matches above description,\\<close>\n\\<comment> \\<open>but that gets complicated in the \\<open>OVar\\<close> case because not all variables are bound by the \\<open>OVar\\<close>\\<close>\n| ODE_sem_OProd:\"ODE_sem I (OProd ODE1 ODE2) = (\\<lambda>\\<nu>. ODE_sem I ODE1 \\<nu> + ODE_sem I ODE2 \\<nu>)\"\n\n\\<comment> \\<open>The bound variables of an ODE\\<close>\nfun ODE_vars :: \"('a,'b,'c) interp \\<Rightarrow> ('a, 'c) ODE \\<Rightarrow> 'c set\"\n  where \n  \"ODE_vars I (OVar c) = ODEBV I c\"\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  \nfun semBV ::\"('a, 'b,'c) interp \\<Rightarrow> ('a, 'c) ODE \\<Rightarrow> ('c + 'c) 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::\"'sz\" and ODE::\"('sf,'sz) ODE\" and I::\"('sf,'sc,'sz) 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::\"('a::finite, 'b::finite, 'c::finite) interp \\<Rightarrow> ('a::finite, 'c::finite) ODE \\<Rightarrow> 'c::finite simple_state \\<Rightarrow> 'c::finite 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::\"('a::finite, 'b::finite, 'c::finite) interp \\<Rightarrow> ('a::finite, 'c::finite) ODE \\<Rightarrow> 'c::finite state \\<Rightarrow> 'c::finite simple_state \\<Rightarrow> 'c::finite 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\\<comment> \\<open>\\<open>repv \\<nu> x r\\<close> replaces the value of (unprimed) variable \\<open>x\\<close> in the state \\<open>\\<nu>\\<close> with r\\<close>\nfun repv :: \"'c::finite state \\<Rightarrow> 'c \\<Rightarrow> real \\<Rightarrow> 'c state\"\nwhere \"repv v x r = ((\\<chi> y. if x = y then r else vec_nth (fst v) y), snd v)\"\n\n\\<comment> \\<open>\\<open>repd \\<nu> x' r\\<close> replaces the value of (primed) variable \\<open>x'\\<close> in the state \\<open>\\<nu>\\<close> with \\<open>r\\<close>\\<close>\nfun repd :: \"'c::finite state \\<Rightarrow> 'c \\<Rightarrow> real \\<Rightarrow> 'c state\"\nwhere \"repd v x r = (fst v, (\\<chi> y. if x = y then r else vec_nth (snd v) y))\"  \n  \n\\<comment> \\<open>Semantics for formulas, differential formulas, programs.\\<close>\nfun fml_sem  :: \"('a::finite, 'b::finite, 'c::finite) interp \\<Rightarrow> ('a::finite, 'b::finite, 'c::finite) formula \\<Rightarrow> 'c::finite state set\" and\n  prog_sem :: \"('a::finite, 'b::finite, 'c::finite) interp \\<Rightarrow> ('a::finite, 'b::finite, 'c::finite) hp \\<Rightarrow> ('c::finite state * 'c::finite 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 (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\ncontext ids begin\ndefinition valid :: \"('sf, 'sc, 'sz) formula \\<Rightarrow> bool\"\nwhere \"valid \\<phi> \\<equiv> (\\<forall> I. \\<forall> \\<nu>. is_interp I \\<longrightarrow> \\<nu> \\<in> fml_sem I \\<phi>)\"\nend\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::\"('a::finite, 'b::finite, 'c::finite) interp \\<Rightarrow> ('a::finite, 'c::finite) ODE \\<Rightarrow> 'c::finite state \\<Rightarrow> 'c::finite simple_state \\<Rightarrow> 'c::finite 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 r) = (\\<lambda>v. r)\"\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 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 = {}\" unfolding FF_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 :: \"('a,'b,'c) sequent \\<Rightarrow> ('a,'b,'c) formula\"\nwhere\n  \"seq2fml (ante,succ) = Implies (foldr And ante TT) (foldr Or succ FF)\"\n  \ncontext ids begin\nfun seq_sem ::\"('sf, 'sc, 'sz) interp \\<Rightarrow> ('sf, 'sc, 'sz) sequent \\<Rightarrow> 'sz 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_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 :: \"('sf, 'sc, 'sz) 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\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/Differential_Dynamic_Logic/Denotational_Semantics.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8824278571786139, "lm_q2_score": 0.7981867753392728, "lm_q1q2_score": 0.7043422457909423}}
{"text": "section \\<open>Stochastic Matrices and the Perron--Frobenius Theorem\\<close>\n\ntext \\<open>Since a stationary distribution corresponds to a non-negative real\n  eigenvector of the stochastic matrix, we can apply the Perron--Frobenius\n  theorem. In this way we easily derive that every stochastic matrix has \n  a stationary distribution, and moreover that this distribution is unique, if the \n  matrix is irreducible, i.e., if the graph of the matrix is strongly connected.\\<close>\n\ntheory Stochastic_Matrix_Perron_Frobenius\nimports   \n  Perron_Frobenius.Perron_Frobenius_Irreducible\n  Stochastic_Matrix_Markov_Models\n  Eigenspace\nbegin    \n\nhide_const (open) Coset.order\n\nlemma pf_nonneg_mat_st_mat: \"pf_nonneg_mat (st_mat A)\" \n  by (unfold_locales, auto simp: non_neg_mat_st_mat)\n\nlemma stoch_non_neg_vec_norm1: assumes \"stoch_vec (v :: real ^ 'n)\" \"non_neg_vec v\" \n  shows \"norm1 v = 1\" \n  unfolding assms(1)[unfolded stoch_vec_def, symmetric] norm1_def\n  by (rule sum.cong, insert assms(2)[unfolded non_neg_vec_def], auto)\n\nlemma stationary_distribution_exists: \"\\<exists> v. A *st v = v\"\nproof -\n  let ?A = \"st_mat A\" \n  let ?c = \"complex_of_real\" \n  let ?B = \"\\<chi> i j. ?c (?A $ i $ j)\" \n  have \"real_non_neg_mat ?B\" using non_neg_mat_st_mat[of A] \n    unfolding real_non_neg_mat_def elements_mat_h_def non_neg_mat_def\n    by auto\n  from Perron_Frobenius.perron_frobenius_both[OF this] obtain v a where \n    ev: \"eigen_vector ?B v (?c a)\" and nn: \"real_non_neg_vec v\" \n    and a: \"a = HMA_Connect.spectral_radius ?B\" by auto\n  from spectral_radius_ev[of ?B, folded a] have a0: \"a \\<ge> 0\" by auto\n  define w where \"w = (\\<chi> i. Re (v $ i))\" \n  from nn have vw: \"v = (\\<chi> i. ?c (w $ i))\" unfolding real_non_neg_vec_def w_def\n    by (auto simp: vec_elements_h_def)\n  from ev[unfolded eigen_vector_def] have v0: \"v \\<noteq> 0\" and ev: \"?B *v v = ?c a *s v\" by auto\n  from v0 have w0: \"w \\<noteq> 0\" unfolding vw by (auto simp: Finite_Cartesian_Product.vec_eq_iff)\n  {\n    fix i\n    from ev have \"Re ((?B *v v) $ i) = Re ((?c a *s v) $ i)\" by simp\n    also have \"Re ((?c a *s v) $ i) = (a *s w) $ i\" unfolding vw by simp\n    also have \"Re ((?B *v v) $ i) = (?A *v w) $ i\" unfolding vw \n      by (simp add: matrix_vector_mult_def)\n    also note calculation\n  }\n  hence ev: \"?A *v w = a *s w\" by (auto simp: Finite_Cartesian_Product.vec_eq_iff)\n  from nn have nn: \"non_neg_vec w\" \n    unfolding vw by (auto simp: real_non_neg_vec_def non_neg_vec_def vec_elements_h_def)\n  (* we now mainly have to prove that a = 1 *)\n  let ?n = \"norm1 w\" \n  from w0 have n0: \"?n \\<noteq> 0\" by auto\n  hence n_pos: \"?n > 0\" using norm1_ge_0[of w] by linarith\n  define u where \"u = inverse ?n *s w\" \n  have nn: \"non_neg_vec u\" using nn n_pos unfolding u_def non_neg_vec_def by auto\n  have nu: \"norm1 u = 1\" unfolding u_def scalar_mult_eq_scaleR norm1_scaleR using n_pos\n    by (auto simp: field_simps)\n  have 1: \"stoch_vec u\" unfolding stoch_vec_def nu[symmetric] norm1_def\n    by (rule sum.cong, insert nn[unfolded non_neg_vec_def], auto)\n  from arg_cong[OF ev, of \"\\<lambda> x. inverse ?n *s x\"]\n  have ev: \"?A *v u = a *s u\" unfolding u_def\n    by (auto simp: ac_simps vector_smult_distrib matrix_vect_scaleR)\n  from right_stoch_mat_mult_stoch_vec[OF right_stoch_mat_st_mat[of A] 1, unfolded ev]\n  have st: \"stoch_vec (a *s u)\" .\n  from non_neg_mat_mult_non_neg_vec[OF non_neg_mat_st_mat[of A] nn, unfolded ev]\n  have nn': \"non_neg_vec (a *s u)\" .\n  from stoch_non_neg_vec_norm1[OF st nn', unfolded scalar_mult_eq_scaleR norm1_scaleR nu] a0\n  have \"a = 1\" by auto\n  with ev st have ev: \"?A *v u = u\" and st: \"stoch_vec u\" by auto\n  show ?thesis using ev st nn\n    by (intro exI[of _ \"to_st_vec u\"], transfer, auto)\nqed\n\nlemma stationary_distribution_unique: \n  assumes \"fixed_mat.irreducible (st_mat A)\" \n  shows \"\\<exists>! v. A *st v = v\" \nproof -\n  from stationary_distribution_exists obtain v where ev: \"A *st v = v\" by auto\n  show ?thesis\n  proof (intro ex1I, rule ev)\n    fix w\n    assume \"A *st w = w\" \n    thus \"w = v\" using ev assms\n    proof (transfer, goal_cases)\n      case (1 A w v)\n      interpret perron_frobenius A\n        by (unfold_locales, insert 1, auto)\n      from 1 have *: \"eigen_vector A v 1\" \"le_vec 0 v\" \"eigen_vector A w 1\"\n        by (auto simp: eigen_vector_def stoch_vec_def non_neg_vec_def)\n      from nonnegative_eigenvector_has_ev_sr[OF *(1-2)] have sr1: \"sr = 1\" by auto  \n      from multiplicity_sr_1[unfolded sr1] have \"order 1 (charpoly A) = 1\" .\n      from unique_eigen_vector_real[OF this *(1,3)] obtain a where \n        vw: \"v = a *s w\" by auto\n      from 1(2,4)[unfolded stoch_vec_def] have \"sum (($h) v) UNIV = sum (($h) w) UNIV\" by auto\n      also have \"sum (($h) v) UNIV = a * sum (($h) w) UNIV\" unfolding vw \n        by (auto simp: sum_distrib_left)\n      finally have \"a = 1\" using 1(2)[unfolded stoch_vec_def] by auto\n      with vw show \"v = w\" by auto\n    qed\n  qed\nqed\n\ntext \\<open>Let us now convert the stationary distribution results from matrices to Markov chains.\\<close>\n\ncontext transition_matrix\nbegin\n\nlemma stationary_distribution_exists: \n  \"\\<exists> x. stationary_distribution (pmf_of_st_vec x)\" \nproof -\n  from stationary_distribution_exists obtain x where ev: \"A *st x = x\" by auto\n  show ?thesis\n    by (intro exI[of _ x], unfold stationary_distribution_pmf_of_st_vec,\n    simp add: ev)\nqed\n\nlemma stationary_distribution_unique: assumes \"fixed_mat.irreducible (st_mat A)\" \n  shows \"\\<exists>! N. stationary_distribution N\" \nproof -\n  from stationary_distribution_exists obtain x where\n    st: \"stationary_distribution (pmf_of_st_vec x)\" by blast\n  show ?thesis\n  proof (rule ex1I, rule st)\n    fix N\n    assume st': \"stationary_distribution N\" \n    from stationary_distribution_implies_pmf_of_st_vec[OF this] obtain y where \n      N: \"N = pmf_of_st_vec y\" by auto\n    from st'[unfolded N] st \n    have \"A *st x = x\" \"A *st y = y\" unfolding stationary_distribution_pmf_of_st_vec by auto\n    from stationary_distribution_unique[OF assms] this have \"x = y\" by auto\n    with N show \"N = pmf_of_st_vec x\" by auto\n  qed\nqed\nend\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/Stochastic_Matrices/Stochastic_Matrix_Perron_Frobenius.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8519528132451417, "lm_q2_score": 0.8267117919359419, "lm_q1q2_score": 0.704319436882758}}
{"text": "(*  Title:      HOL/Real.thy\n    Author:     Jacques D. Fleuriot, University of Edinburgh, 1998\n    Author:     Larry Paulson, University of Cambridge\n    Author:     Jeremy Avigad, Carnegie Mellon University\n    Author:     Florian Zuleger, Johannes Hoelzl, and Simon Funke, TU Muenchen\n    Conversion to Isar and new proofs by Lawrence C Paulson, 2003/4\n    Construction of Cauchy Reals by Brian Huffman, 2010\n*)\n\nsection {* Development of the Reals using Cauchy Sequences *}\n\ntheory Real\nimports Rat Conditionally_Complete_Lattices\nbegin\n\ntext {*\n  This theory contains a formalization of the real numbers as\n  equivalence classes of Cauchy sequences of rationals.  See\n  @{file \"~~/src/HOL/ex/Dedekind_Real.thy\"} for an alternative\n  construction using Dedekind cuts.\n*}\n\nsubsection {* Preliminary lemmas *}\n\nlemma add_diff_add:\n  fixes a b c d :: \"'a::ab_group_add\"\n  shows \"(a + c) - (b + d) = (a - b) + (c - d)\"\n  by simp\n\nlemma minus_diff_minus:\n  fixes a b :: \"'a::ab_group_add\"\n  shows \"- a - - b = - (a - b)\"\n  by simp\n\nlemma mult_diff_mult:\n  fixes x y a b :: \"'a::ring\"\n  shows \"(x * y - a * b) = x * (y - b) + (x - a) * b\"\n  by (simp add: algebra_simps)\n\nlemma inverse_diff_inverse:\n  fixes a b :: \"'a::division_ring\"\n  assumes \"a \\<noteq> 0\" and \"b \\<noteq> 0\"\n  shows \"inverse a - inverse b = - (inverse a * (a - b) * inverse b)\"\n  using assms by (simp add: algebra_simps)\n\nlemma obtain_pos_sum:\n  fixes r :: rat assumes r: \"0 < r\"\n  obtains s t where \"0 < s\" and \"0 < t\" and \"r = s + t\"\nproof\n    from r show \"0 < r/2\" by simp\n    from r show \"0 < r/2\" by simp\n    show \"r = r/2 + r/2\" by simp\nqed\n\nsubsection {* Sequences that converge to zero *}\n\ndefinition\n  vanishes :: \"(nat \\<Rightarrow> rat) \\<Rightarrow> bool\"\nwhere\n  \"vanishes X = (\\<forall>r>0. \\<exists>k. \\<forall>n\\<ge>k. \\<bar>X n\\<bar> < r)\"\n\nlemma vanishesI: \"(\\<And>r. 0 < r \\<Longrightarrow> \\<exists>k. \\<forall>n\\<ge>k. \\<bar>X n\\<bar> < r) \\<Longrightarrow> vanishes X\"\n  unfolding vanishes_def by simp\n\nlemma vanishesD: \"\\<lbrakk>vanishes X; 0 < r\\<rbrakk> \\<Longrightarrow> \\<exists>k. \\<forall>n\\<ge>k. \\<bar>X n\\<bar> < r\"\n  unfolding vanishes_def by simp\n\nlemma vanishes_const [simp]: \"vanishes (\\<lambda>n. c) \\<longleftrightarrow> c = 0\"\n  unfolding vanishes_def\n  apply (cases \"c = 0\", auto)\n  apply (rule exI [where x=\"\\<bar>c\\<bar>\"], auto)\n  done\n\nlemma vanishes_minus: \"vanishes X \\<Longrightarrow> vanishes (\\<lambda>n. - X n)\"\n  unfolding vanishes_def by simp\n\nlemma vanishes_add:\n  assumes X: \"vanishes X\" and Y: \"vanishes Y\"\n  shows \"vanishes (\\<lambda>n. X n + Y n)\"\nproof (rule vanishesI)\n  fix r :: rat assume \"0 < r\"\n  then obtain s t where s: \"0 < s\" and t: \"0 < t\" and r: \"r = s + t\"\n    by (rule obtain_pos_sum)\n  obtain i where i: \"\\<forall>n\\<ge>i. \\<bar>X n\\<bar> < s\"\n    using vanishesD [OF X s] ..\n  obtain j where j: \"\\<forall>n\\<ge>j. \\<bar>Y n\\<bar> < t\"\n    using vanishesD [OF Y t] ..\n  have \"\\<forall>n\\<ge>max i j. \\<bar>X n + Y n\\<bar> < r\"\n  proof (clarsimp)\n    fix n assume n: \"i \\<le> n\" \"j \\<le> n\"\n    have \"\\<bar>X n + Y n\\<bar> \\<le> \\<bar>X n\\<bar> + \\<bar>Y n\\<bar>\" by (rule abs_triangle_ineq)\n    also have \"\\<dots> < s + t\" by (simp add: add_strict_mono i j n)\n    finally show \"\\<bar>X n + Y n\\<bar> < r\" unfolding r .\n  qed\n  thus \"\\<exists>k. \\<forall>n\\<ge>k. \\<bar>X n + Y n\\<bar> < r\" ..\nqed\n\nlemma vanishes_diff:\n  assumes X: \"vanishes X\" and Y: \"vanishes Y\"\n  shows \"vanishes (\\<lambda>n. X n - Y n)\"\n  unfolding diff_conv_add_uminus by (intro vanishes_add vanishes_minus X Y)\n\nlemma vanishes_mult_bounded:\n  assumes X: \"\\<exists>a>0. \\<forall>n. \\<bar>X n\\<bar> < a\"\n  assumes Y: \"vanishes (\\<lambda>n. Y n)\"\n  shows \"vanishes (\\<lambda>n. X n * Y n)\"\nproof (rule vanishesI)\n  fix r :: rat assume r: \"0 < r\"\n  obtain a where a: \"0 < a\" \"\\<forall>n. \\<bar>X n\\<bar> < a\"\n    using X by fast\n  obtain b where b: \"0 < b\" \"r = a * b\"\n  proof\n    show \"0 < r / a\" using r a by simp\n    show \"r = a * (r / a)\" using a by simp\n  qed\n  obtain k where k: \"\\<forall>n\\<ge>k. \\<bar>Y n\\<bar> < b\"\n    using vanishesD [OF Y b(1)] ..\n  have \"\\<forall>n\\<ge>k. \\<bar>X n * Y n\\<bar> < r\"\n    by (simp add: b(2) abs_mult mult_strict_mono' a k)\n  thus \"\\<exists>k. \\<forall>n\\<ge>k. \\<bar>X n * Y n\\<bar> < r\" ..\nqed\n\nsubsection {* Cauchy sequences *}\n\ndefinition\n  cauchy :: \"(nat \\<Rightarrow> rat) \\<Rightarrow> bool\"\nwhere\n  \"cauchy X \\<longleftrightarrow> (\\<forall>r>0. \\<exists>k. \\<forall>m\\<ge>k. \\<forall>n\\<ge>k. \\<bar>X m - X n\\<bar> < r)\"\n\nlemma cauchyI:\n  \"(\\<And>r. 0 < r \\<Longrightarrow> \\<exists>k. \\<forall>m\\<ge>k. \\<forall>n\\<ge>k. \\<bar>X m - X n\\<bar> < r) \\<Longrightarrow> cauchy X\"\n  unfolding cauchy_def by simp\n\nlemma cauchyD:\n  \"\\<lbrakk>cauchy X; 0 < r\\<rbrakk> \\<Longrightarrow> \\<exists>k. \\<forall>m\\<ge>k. \\<forall>n\\<ge>k. \\<bar>X m - X n\\<bar> < r\"\n  unfolding cauchy_def by simp\n\nlemma cauchy_const [simp]: \"cauchy (\\<lambda>n. x)\"\n  unfolding cauchy_def by simp\n\nlemma cauchy_add [simp]:\n  assumes X: \"cauchy X\" and Y: \"cauchy Y\"\n  shows \"cauchy (\\<lambda>n. X n + Y n)\"\nproof (rule cauchyI)\n  fix r :: rat assume \"0 < r\"\n  then obtain s t where s: \"0 < s\" and t: \"0 < t\" and r: \"r = s + t\"\n    by (rule obtain_pos_sum)\n  obtain i where i: \"\\<forall>m\\<ge>i. \\<forall>n\\<ge>i. \\<bar>X m - X n\\<bar> < s\"\n    using cauchyD [OF X s] ..\n  obtain j where j: \"\\<forall>m\\<ge>j. \\<forall>n\\<ge>j. \\<bar>Y m - Y n\\<bar> < t\"\n    using cauchyD [OF Y t] ..\n  have \"\\<forall>m\\<ge>max i j. \\<forall>n\\<ge>max i j. \\<bar>(X m + Y m) - (X n + Y n)\\<bar> < r\"\n  proof (clarsimp)\n    fix m n assume *: \"i \\<le> m\" \"j \\<le> m\" \"i \\<le> n\" \"j \\<le> n\"\n    have \"\\<bar>(X m + Y m) - (X n + Y n)\\<bar> \\<le> \\<bar>X m - X n\\<bar> + \\<bar>Y m - Y n\\<bar>\"\n      unfolding add_diff_add by (rule abs_triangle_ineq)\n    also have \"\\<dots> < s + t\"\n      by (rule add_strict_mono, simp_all add: i j *)\n    finally show \"\\<bar>(X m + Y m) - (X n + Y n)\\<bar> < r\" unfolding r .\n  qed\n  thus \"\\<exists>k. \\<forall>m\\<ge>k. \\<forall>n\\<ge>k. \\<bar>(X m + Y m) - (X n + Y n)\\<bar> < r\" ..\nqed\n\nlemma cauchy_minus [simp]:\n  assumes X: \"cauchy X\"\n  shows \"cauchy (\\<lambda>n. - X n)\"\nusing assms unfolding cauchy_def\nunfolding minus_diff_minus abs_minus_cancel .\n\nlemma cauchy_diff [simp]:\n  assumes X: \"cauchy X\" and Y: \"cauchy Y\"\n  shows \"cauchy (\\<lambda>n. X n - Y n)\"\n  using assms unfolding diff_conv_add_uminus by (simp del: add_uminus_conv_diff)\n\nlemma cauchy_imp_bounded:\n  assumes \"cauchy X\" shows \"\\<exists>b>0. \\<forall>n. \\<bar>X n\\<bar> < b\"\nproof -\n  obtain k where k: \"\\<forall>m\\<ge>k. \\<forall>n\\<ge>k. \\<bar>X m - X n\\<bar> < 1\"\n    using cauchyD [OF assms zero_less_one] ..\n  show \"\\<exists>b>0. \\<forall>n. \\<bar>X n\\<bar> < b\"\n  proof (intro exI conjI allI)\n    have \"0 \\<le> \\<bar>X 0\\<bar>\" by simp\n    also have \"\\<bar>X 0\\<bar> \\<le> Max (abs ` X ` {..k})\" by simp\n    finally have \"0 \\<le> Max (abs ` X ` {..k})\" .\n    thus \"0 < Max (abs ` X ` {..k}) + 1\" by simp\n  next\n    fix n :: nat\n    show \"\\<bar>X n\\<bar> < Max (abs ` X ` {..k}) + 1\"\n    proof (rule linorder_le_cases)\n      assume \"n \\<le> k\"\n      hence \"\\<bar>X n\\<bar> \\<le> Max (abs ` X ` {..k})\" by simp\n      thus \"\\<bar>X n\\<bar> < Max (abs ` X ` {..k}) + 1\" by simp\n    next\n      assume \"k \\<le> n\"\n      have \"\\<bar>X n\\<bar> = \\<bar>X k + (X n - X k)\\<bar>\" by simp\n      also have \"\\<bar>X k + (X n - X k)\\<bar> \\<le> \\<bar>X k\\<bar> + \\<bar>X n - X k\\<bar>\"\n        by (rule abs_triangle_ineq)\n      also have \"\\<dots> < Max (abs ` X ` {..k}) + 1\"\n        by (rule add_le_less_mono, simp, simp add: k `k \\<le> n`)\n      finally show \"\\<bar>X n\\<bar> < Max (abs ` X ` {..k}) + 1\" .\n    qed\n  qed\nqed\n\nlemma cauchy_mult [simp]:\n  assumes X: \"cauchy X\" and Y: \"cauchy Y\"\n  shows \"cauchy (\\<lambda>n. X n * Y n)\"\nproof (rule cauchyI)\n  fix r :: rat assume \"0 < r\"\n  then obtain u v where u: \"0 < u\" and v: \"0 < v\" and \"r = u + v\"\n    by (rule obtain_pos_sum)\n  obtain a where a: \"0 < a\" \"\\<forall>n. \\<bar>X n\\<bar> < a\"\n    using cauchy_imp_bounded [OF X] by fast\n  obtain b where b: \"0 < b\" \"\\<forall>n. \\<bar>Y n\\<bar> < b\"\n    using cauchy_imp_bounded [OF Y] by fast\n  obtain s t where s: \"0 < s\" and t: \"0 < t\" and r: \"r = a * t + s * b\"\n  proof\n    show \"0 < v/b\" using v b(1) by simp\n    show \"0 < u/a\" using u a(1) by simp\n    show \"r = a * (u/a) + (v/b) * b\"\n      using a(1) b(1) `r = u + v` by simp\n  qed\n  obtain i where i: \"\\<forall>m\\<ge>i. \\<forall>n\\<ge>i. \\<bar>X m - X n\\<bar> < s\"\n    using cauchyD [OF X s] ..\n  obtain j where j: \"\\<forall>m\\<ge>j. \\<forall>n\\<ge>j. \\<bar>Y m - Y n\\<bar> < t\"\n    using cauchyD [OF Y t] ..\n  have \"\\<forall>m\\<ge>max i j. \\<forall>n\\<ge>max i j. \\<bar>X m * Y m - X n * Y n\\<bar> < r\"\n  proof (clarsimp)\n    fix m n assume *: \"i \\<le> m\" \"j \\<le> m\" \"i \\<le> n\" \"j \\<le> n\"\n    have \"\\<bar>X m * Y m - X n * Y n\\<bar> = \\<bar>X m * (Y m - Y n) + (X m - X n) * Y n\\<bar>\"\n      unfolding mult_diff_mult ..\n    also have \"\\<dots> \\<le> \\<bar>X m * (Y m - Y n)\\<bar> + \\<bar>(X m - X n) * Y n\\<bar>\"\n      by (rule abs_triangle_ineq)\n    also have \"\\<dots> = \\<bar>X m\\<bar> * \\<bar>Y m - Y n\\<bar> + \\<bar>X m - X n\\<bar> * \\<bar>Y n\\<bar>\"\n      unfolding abs_mult ..\n    also have \"\\<dots> < a * t + s * b\"\n      by (simp_all add: add_strict_mono mult_strict_mono' a b i j *)\n    finally show \"\\<bar>X m * Y m - X n * Y n\\<bar> < r\" unfolding r .\n  qed\n  thus \"\\<exists>k. \\<forall>m\\<ge>k. \\<forall>n\\<ge>k. \\<bar>X m * Y m - X n * Y n\\<bar> < r\" ..\nqed\n\nlemma cauchy_not_vanishes_cases:\n  assumes X: \"cauchy X\"\n  assumes nz: \"\\<not> vanishes X\"\n  shows \"\\<exists>b>0. \\<exists>k. (\\<forall>n\\<ge>k. b < - X n) \\<or> (\\<forall>n\\<ge>k. b < X n)\"\nproof -\n  obtain r where \"0 < r\" and r: \"\\<forall>k. \\<exists>n\\<ge>k. r \\<le> \\<bar>X n\\<bar>\"\n    using nz unfolding vanishes_def by (auto simp add: not_less)\n  obtain s t where s: \"0 < s\" and t: \"0 < t\" and \"r = s + t\"\n    using `0 < r` by (rule obtain_pos_sum)\n  obtain i where i: \"\\<forall>m\\<ge>i. \\<forall>n\\<ge>i. \\<bar>X m - X n\\<bar> < s\"\n    using cauchyD [OF X s] ..\n  obtain k where \"i \\<le> k\" and \"r \\<le> \\<bar>X k\\<bar>\"\n    using r by fast\n  have k: \"\\<forall>n\\<ge>k. \\<bar>X n - X k\\<bar> < s\"\n    using i `i \\<le> k` by auto\n  have \"X k \\<le> - r \\<or> r \\<le> X k\"\n    using `r \\<le> \\<bar>X k\\<bar>` by auto\n  hence \"(\\<forall>n\\<ge>k. t < - X n) \\<or> (\\<forall>n\\<ge>k. t < X n)\"\n    unfolding `r = s + t` using k by auto\n  hence \"\\<exists>k. (\\<forall>n\\<ge>k. t < - X n) \\<or> (\\<forall>n\\<ge>k. t < X n)\" ..\n  thus \"\\<exists>t>0. \\<exists>k. (\\<forall>n\\<ge>k. t < - X n) \\<or> (\\<forall>n\\<ge>k. t < X n)\"\n    using t by auto\nqed\n\nlemma cauchy_not_vanishes:\n  assumes X: \"cauchy X\"\n  assumes nz: \"\\<not> vanishes X\"\n  shows \"\\<exists>b>0. \\<exists>k. \\<forall>n\\<ge>k. b < \\<bar>X n\\<bar>\"\nusing cauchy_not_vanishes_cases [OF assms]\nby clarify (rule exI, erule conjI, rule_tac x=k in exI, auto)\n\nlemma cauchy_inverse [simp]:\n  assumes X: \"cauchy X\"\n  assumes nz: \"\\<not> vanishes X\"\n  shows \"cauchy (\\<lambda>n. inverse (X n))\"\nproof (rule cauchyI)\n  fix r :: rat assume \"0 < r\"\n  obtain b i where b: \"0 < b\" and i: \"\\<forall>n\\<ge>i. b < \\<bar>X n\\<bar>\"\n    using cauchy_not_vanishes [OF X nz] by fast\n  from b i have nz: \"\\<forall>n\\<ge>i. X n \\<noteq> 0\" by auto\n  obtain s where s: \"0 < s\" and r: \"r = inverse b * s * inverse b\"\n  proof\n    show \"0 < b * r * b\" by (simp add: `0 < r` b)\n    show \"r = inverse b * (b * r * b) * inverse b\"\n      using b by simp\n  qed\n  obtain j where j: \"\\<forall>m\\<ge>j. \\<forall>n\\<ge>j. \\<bar>X m - X n\\<bar> < s\"\n    using cauchyD [OF X s] ..\n  have \"\\<forall>m\\<ge>max i j. \\<forall>n\\<ge>max i j. \\<bar>inverse (X m) - inverse (X n)\\<bar> < r\"\n  proof (clarsimp)\n    fix m n assume *: \"i \\<le> m\" \"j \\<le> m\" \"i \\<le> n\" \"j \\<le> n\"\n    have \"\\<bar>inverse (X m) - inverse (X n)\\<bar> =\n          inverse \\<bar>X m\\<bar> * \\<bar>X m - X n\\<bar> * inverse \\<bar>X n\\<bar>\"\n      by (simp add: inverse_diff_inverse nz * abs_mult)\n    also have \"\\<dots> < inverse b * s * inverse b\"\n      by (simp add: mult_strict_mono less_imp_inverse_less\n                    i j b * s)\n    finally show \"\\<bar>inverse (X m) - inverse (X n)\\<bar> < r\" unfolding r .\n  qed\n  thus \"\\<exists>k. \\<forall>m\\<ge>k. \\<forall>n\\<ge>k. \\<bar>inverse (X m) - inverse (X n)\\<bar> < r\" ..\nqed\n\nlemma vanishes_diff_inverse:\n  assumes X: \"cauchy X\" \"\\<not> vanishes X\"\n  assumes Y: \"cauchy Y\" \"\\<not> vanishes Y\"\n  assumes XY: \"vanishes (\\<lambda>n. X n - Y n)\"\n  shows \"vanishes (\\<lambda>n. inverse (X n) - inverse (Y n))\"\nproof (rule vanishesI)\n  fix r :: rat assume r: \"0 < r\"\n  obtain a i where a: \"0 < a\" and i: \"\\<forall>n\\<ge>i. a < \\<bar>X n\\<bar>\"\n    using cauchy_not_vanishes [OF X] by fast\n  obtain b j where b: \"0 < b\" and j: \"\\<forall>n\\<ge>j. b < \\<bar>Y n\\<bar>\"\n    using cauchy_not_vanishes [OF Y] by fast\n  obtain s where s: \"0 < s\" and \"inverse a * s * inverse b = r\"\n  proof\n    show \"0 < a * r * b\"\n      using a r b by simp\n    show \"inverse a * (a * r * b) * inverse b = r\"\n      using a r b by simp\n  qed\n  obtain k where k: \"\\<forall>n\\<ge>k. \\<bar>X n - Y n\\<bar> < s\"\n    using vanishesD [OF XY s] ..\n  have \"\\<forall>n\\<ge>max (max i j) k. \\<bar>inverse (X n) - inverse (Y n)\\<bar> < r\"\n  proof (clarsimp)\n    fix n assume n: \"i \\<le> n\" \"j \\<le> n\" \"k \\<le> n\"\n    have \"X n \\<noteq> 0\" and \"Y n \\<noteq> 0\"\n      using i j a b n by auto\n    hence \"\\<bar>inverse (X n) - inverse (Y n)\\<bar> =\n        inverse \\<bar>X n\\<bar> * \\<bar>X n - Y n\\<bar> * inverse \\<bar>Y n\\<bar>\"\n      by (simp add: inverse_diff_inverse abs_mult)\n    also have \"\\<dots> < inverse a * s * inverse b\"\n      apply (intro mult_strict_mono' less_imp_inverse_less)\n      apply (simp_all add: a b i j k n)\n      done\n    also note `inverse a * s * inverse b = r`\n    finally show \"\\<bar>inverse (X n) - inverse (Y n)\\<bar> < r\" .\n  qed\n  thus \"\\<exists>k. \\<forall>n\\<ge>k. \\<bar>inverse (X n) - inverse (Y n)\\<bar> < r\" ..\nqed\n\nsubsection {* Equivalence relation on Cauchy sequences *}\n\ndefinition realrel :: \"(nat \\<Rightarrow> rat) \\<Rightarrow> (nat \\<Rightarrow> rat) \\<Rightarrow> bool\"\n  where \"realrel = (\\<lambda>X Y. cauchy X \\<and> cauchy Y \\<and> vanishes (\\<lambda>n. X n - Y n))\"\n\nlemma realrelI [intro?]:\n  assumes \"cauchy X\" and \"cauchy Y\" and \"vanishes (\\<lambda>n. X n - Y n)\"\n  shows \"realrel X Y\"\n  using assms unfolding realrel_def by simp\n\nlemma realrel_refl: \"cauchy X \\<Longrightarrow> realrel X X\"\n  unfolding realrel_def by simp\n\nlemma symp_realrel: \"symp realrel\"\n  unfolding realrel_def\n  by (rule sympI, clarify, drule vanishes_minus, simp)\n\nlemma transp_realrel: \"transp realrel\"\n  unfolding realrel_def\n  apply (rule transpI, clarify)\n  apply (drule (1) vanishes_add)\n  apply (simp add: algebra_simps)\n  done\n\nlemma part_equivp_realrel: \"part_equivp realrel\"\n  by (fast intro: part_equivpI symp_realrel transp_realrel\n    realrel_refl cauchy_const)\n\nsubsection {* The field of real numbers *}\n\nquotient_type real = \"nat \\<Rightarrow> rat\" / partial: realrel\n  morphisms rep_real Real\n  by (rule part_equivp_realrel)\n\nlemma cr_real_eq: \"pcr_real = (\\<lambda>x y. cauchy x \\<and> Real x = y)\"\n  unfolding real.pcr_cr_eq cr_real_def realrel_def by auto\n\nlemma Real_induct [induct type: real]: (* TODO: generate automatically *)\n  assumes \"\\<And>X. cauchy X \\<Longrightarrow> P (Real X)\" shows \"P x\"\nproof (induct x)\n  case (1 X)\n  hence \"cauchy X\" by (simp add: realrel_def)\n  thus \"P (Real X)\" by (rule assms)\nqed\n\nlemma eq_Real:\n  \"cauchy X \\<Longrightarrow> cauchy Y \\<Longrightarrow> Real X = Real Y \\<longleftrightarrow> vanishes (\\<lambda>n. X n - Y n)\"\n  using real.rel_eq_transfer\n  unfolding real.pcr_cr_eq cr_real_def rel_fun_def realrel_def by simp\n\nlemma Domainp_pcr_real [transfer_domain_rule]: \"Domainp pcr_real = cauchy\"\nby (simp add: real.domain_eq realrel_def)\n\ninstantiation real :: field_inverse_zero\nbegin\n\nlift_definition zero_real :: \"real\" is \"\\<lambda>n. 0\"\n  by (simp add: realrel_refl)\n\nlift_definition one_real :: \"real\" is \"\\<lambda>n. 1\"\n  by (simp add: realrel_refl)\n\nlift_definition plus_real :: \"real \\<Rightarrow> real \\<Rightarrow> real\" is \"\\<lambda>X Y n. X n + Y n\"\n  unfolding realrel_def add_diff_add\n  by (simp only: cauchy_add vanishes_add simp_thms)\n\nlift_definition uminus_real :: \"real \\<Rightarrow> real\" is \"\\<lambda>X n. - X n\"\n  unfolding realrel_def minus_diff_minus\n  by (simp only: cauchy_minus vanishes_minus simp_thms)\n\nlift_definition times_real :: \"real \\<Rightarrow> real \\<Rightarrow> real\" is \"\\<lambda>X Y n. X n * Y n\"\n  unfolding realrel_def mult_diff_mult\n  by (subst (4) mult.commute, simp only: cauchy_mult vanishes_add\n    vanishes_mult_bounded cauchy_imp_bounded simp_thms)\n\nlift_definition inverse_real :: \"real \\<Rightarrow> real\"\n  is \"\\<lambda>X. if vanishes X then (\\<lambda>n. 0) else (\\<lambda>n. inverse (X n))\"\nproof -\n  fix X Y assume \"realrel X Y\"\n  hence X: \"cauchy X\" and Y: \"cauchy Y\" and XY: \"vanishes (\\<lambda>n. X n - Y n)\"\n    unfolding realrel_def by simp_all\n  have \"vanishes X \\<longleftrightarrow> vanishes Y\"\n  proof\n    assume \"vanishes X\"\n    from vanishes_diff [OF this XY] show \"vanishes Y\" by simp\n  next\n    assume \"vanishes Y\"\n    from vanishes_add [OF this XY] show \"vanishes X\" by simp\n  qed\n  thus \"?thesis X Y\"\n    unfolding realrel_def\n    by (simp add: vanishes_diff_inverse X Y XY)\nqed\n\ndefinition\n  \"x - y = (x::real) + - y\"\n\ndefinition\n  \"x / y = (x::real) * inverse y\"\n\nlemma add_Real:\n  assumes X: \"cauchy X\" and Y: \"cauchy Y\"\n  shows \"Real X + Real Y = Real (\\<lambda>n. X n + Y n)\"\n  using assms plus_real.transfer\n  unfolding cr_real_eq rel_fun_def by simp\n\nlemma minus_Real:\n  assumes X: \"cauchy X\"\n  shows \"- Real X = Real (\\<lambda>n. - X n)\"\n  using assms uminus_real.transfer\n  unfolding cr_real_eq rel_fun_def by simp\n\nlemma diff_Real:\n  assumes X: \"cauchy X\" and Y: \"cauchy Y\"\n  shows \"Real X - Real Y = Real (\\<lambda>n. X n - Y n)\"\n  unfolding minus_real_def\n  by (simp add: minus_Real add_Real X Y)\n\nlemma mult_Real:\n  assumes X: \"cauchy X\" and Y: \"cauchy Y\"\n  shows \"Real X * Real Y = Real (\\<lambda>n. X n * Y n)\"\n  using assms times_real.transfer\n  unfolding cr_real_eq rel_fun_def by simp\n\nlemma inverse_Real:\n  assumes X: \"cauchy X\"\n  shows \"inverse (Real X) =\n    (if vanishes X then 0 else Real (\\<lambda>n. inverse (X n)))\"\n  using assms inverse_real.transfer zero_real.transfer\n  unfolding cr_real_eq rel_fun_def by (simp split: split_if_asm, metis)\n\ninstance proof\n  fix a b c :: real\n  show \"a + b = b + a\"\n    by transfer (simp add: ac_simps realrel_def)\n  show \"(a + b) + c = a + (b + c)\"\n    by transfer (simp add: ac_simps realrel_def)\n  show \"0 + a = a\"\n    by transfer (simp add: realrel_def)\n  show \"- a + a = 0\"\n    by transfer (simp add: realrel_def)\n  show \"a - b = a + - b\"\n    by (rule minus_real_def)\n  show \"(a * b) * c = a * (b * c)\"\n    by transfer (simp add: ac_simps realrel_def)\n  show \"a * b = b * a\"\n    by transfer (simp add: ac_simps realrel_def)\n  show \"1 * a = a\"\n    by transfer (simp add: ac_simps realrel_def)\n  show \"(a + b) * c = a * c + b * c\"\n    by transfer (simp add: distrib_right realrel_def)\n  show \"(0\\<Colon>real) \\<noteq> (1\\<Colon>real)\"\n    by transfer (simp add: realrel_def)\n  show \"a \\<noteq> 0 \\<Longrightarrow> inverse a * a = 1\"\n    apply transfer\n    apply (simp add: realrel_def)\n    apply (rule vanishesI)\n    apply (frule (1) cauchy_not_vanishes, clarify)\n    apply (rule_tac x=k in exI, clarify)\n    apply (drule_tac x=n in spec, simp)\n    done\n  show \"a / b = a * inverse b\"\n    by (rule divide_real_def)\n  show \"inverse (0::real) = 0\"\n    by transfer (simp add: realrel_def)\nqed\n\nend\n\nsubsection {* Positive reals *}\n\nlift_definition positive :: \"real \\<Rightarrow> bool\"\n  is \"\\<lambda>X. \\<exists>r>0. \\<exists>k. \\<forall>n\\<ge>k. r < X n\"\nproof -\n  { fix X Y\n    assume \"realrel X Y\"\n    hence XY: \"vanishes (\\<lambda>n. X n - Y n)\"\n      unfolding realrel_def by simp_all\n    assume \"\\<exists>r>0. \\<exists>k. \\<forall>n\\<ge>k. r < X n\"\n    then obtain r i where \"0 < r\" and i: \"\\<forall>n\\<ge>i. r < X n\"\n      by fast\n    obtain s t where s: \"0 < s\" and t: \"0 < t\" and r: \"r = s + t\"\n      using `0 < r` by (rule obtain_pos_sum)\n    obtain j where j: \"\\<forall>n\\<ge>j. \\<bar>X n - Y n\\<bar> < s\"\n      using vanishesD [OF XY s] ..\n    have \"\\<forall>n\\<ge>max i j. t < Y n\"\n    proof (clarsimp)\n      fix n assume n: \"i \\<le> n\" \"j \\<le> n\"\n      have \"\\<bar>X n - Y n\\<bar> < s\" and \"r < X n\"\n        using i j n by simp_all\n      thus \"t < Y n\" unfolding r by simp\n    qed\n    hence \"\\<exists>r>0. \\<exists>k. \\<forall>n\\<ge>k. r < Y n\" using t by fast\n  } note 1 = this\n  fix X Y assume \"realrel X Y\"\n  hence \"realrel X Y\" and \"realrel Y X\"\n    using symp_realrel unfolding symp_def by auto\n  thus \"?thesis X Y\"\n    by (safe elim!: 1)\nqed\n\nlemma positive_Real:\n  assumes X: \"cauchy X\"\n  shows \"positive (Real X) \\<longleftrightarrow> (\\<exists>r>0. \\<exists>k. \\<forall>n\\<ge>k. r < X n)\"\n  using assms positive.transfer\n  unfolding cr_real_eq rel_fun_def by simp\n\nlemma positive_zero: \"\\<not> positive 0\"\n  by transfer auto\n\nlemma positive_add:\n  \"positive x \\<Longrightarrow> positive y \\<Longrightarrow> positive (x + y)\"\napply transfer\napply (clarify, rename_tac a b i j)\napply (rule_tac x=\"a + b\" in exI, simp)\napply (rule_tac x=\"max i j\" in exI, clarsimp)\napply (simp add: add_strict_mono)\ndone\n\nlemma positive_mult:\n  \"positive x \\<Longrightarrow> positive y \\<Longrightarrow> positive (x * y)\"\napply transfer\napply (clarify, rename_tac a b i j)\napply (rule_tac x=\"a * b\" in exI, simp)\napply (rule_tac x=\"max i j\" in exI, clarsimp)\napply (rule mult_strict_mono, auto)\ndone\n\nlemma positive_minus:\n  \"\\<not> positive x \\<Longrightarrow> x \\<noteq> 0 \\<Longrightarrow> positive (- x)\"\napply transfer\napply (simp add: realrel_def)\napply (drule (1) cauchy_not_vanishes_cases, safe, fast, fast)\ndone\n\ninstantiation real :: linordered_field_inverse_zero\nbegin\n\ndefinition\n  \"x < y \\<longleftrightarrow> positive (y - x)\"\n\ndefinition\n  \"x \\<le> (y::real) \\<longleftrightarrow> x < y \\<or> x = y\"\n\ndefinition\n  \"abs (a::real) = (if a < 0 then - a else a)\"\n\ndefinition\n  \"sgn (a::real) = (if a = 0 then 0 else if 0 < a then 1 else - 1)\"\n\ninstance proof\n  fix a b c :: real\n  show \"\\<bar>a\\<bar> = (if a < 0 then - a else a)\"\n    by (rule abs_real_def)\n  show \"a < b \\<longleftrightarrow> a \\<le> b \\<and> \\<not> b \\<le> a\"\n    unfolding less_eq_real_def less_real_def\n    by (auto, drule (1) positive_add, simp_all add: positive_zero)\n  show \"a \\<le> a\"\n    unfolding less_eq_real_def by simp\n  show \"a \\<le> b \\<Longrightarrow> b \\<le> c \\<Longrightarrow> a \\<le> c\"\n    unfolding less_eq_real_def less_real_def\n    by (auto, drule (1) positive_add, simp add: algebra_simps)\n  show \"a \\<le> b \\<Longrightarrow> b \\<le> a \\<Longrightarrow> a = b\"\n    unfolding less_eq_real_def less_real_def\n    by (auto, drule (1) positive_add, simp add: positive_zero)\n  show \"a \\<le> b \\<Longrightarrow> c + a \\<le> c + b\"\n    unfolding less_eq_real_def less_real_def by auto\n    (* FIXME: Procedure int_combine_numerals: c + b - (c + a) \\<equiv> b + - a *)\n    (* Should produce c + b - (c + a) \\<equiv> b - a *)\n  show \"sgn a = (if a = 0 then 0 else if 0 < a then 1 else - 1)\"\n    by (rule sgn_real_def)\n  show \"a \\<le> b \\<or> b \\<le> a\"\n    unfolding less_eq_real_def less_real_def\n    by (auto dest!: positive_minus)\n  show \"a < b \\<Longrightarrow> 0 < c \\<Longrightarrow> c * a < c * b\"\n    unfolding less_real_def\n    by (drule (1) positive_mult, simp add: algebra_simps)\nqed\n\nend\n\ninstantiation real :: distrib_lattice\nbegin\n\ndefinition\n  \"(inf :: real \\<Rightarrow> real \\<Rightarrow> real) = min\"\n\ndefinition\n  \"(sup :: real \\<Rightarrow> real \\<Rightarrow> real) = max\"\n\ninstance proof\nqed (auto simp add: inf_real_def sup_real_def max_min_distrib2)\n\nend\n\nlemma of_nat_Real: \"of_nat x = Real (\\<lambda>n. of_nat x)\"\napply (induct x)\napply (simp add: zero_real_def)\napply (simp add: one_real_def add_Real)\ndone\n\nlemma of_int_Real: \"of_int x = Real (\\<lambda>n. of_int x)\"\napply (cases x rule: int_diff_cases)\napply (simp add: of_nat_Real diff_Real)\ndone\n\nlemma of_rat_Real: \"of_rat x = Real (\\<lambda>n. x)\"\napply (induct x)\napply (simp add: Fract_of_int_quotient of_rat_divide)\napply (simp add: of_int_Real divide_inverse)\napply (simp add: inverse_Real mult_Real)\ndone\n\ninstance real :: archimedean_field\nproof\n  fix x :: real\n  show \"\\<exists>z. x \\<le> of_int z\"\n    apply (induct x)\n    apply (frule cauchy_imp_bounded, clarify)\n    apply (rule_tac x=\"ceiling b + 1\" in exI)\n    apply (rule less_imp_le)\n    apply (simp add: of_int_Real less_real_def diff_Real positive_Real)\n    apply (rule_tac x=1 in exI, simp add: algebra_simps)\n    apply (rule_tac x=0 in exI, clarsimp)\n    apply (rule le_less_trans [OF abs_ge_self])\n    apply (rule less_le_trans [OF _ le_of_int_ceiling])\n    apply simp\n    done\nqed\n\ninstantiation real :: floor_ceiling\nbegin\n\ndefinition [code del]:\n  \"floor (x::real) = (THE z. of_int z \\<le> x \\<and> x < of_int (z + 1))\"\n\ninstance proof\n  fix x :: real\n  show \"of_int (floor x) \\<le> x \\<and> x < of_int (floor x + 1)\"\n    unfolding floor_real_def using floor_exists1 by (rule theI')\nqed\n\nend\n\nsubsection {* Completeness *}\n\nlemma not_positive_Real:\n  assumes X: \"cauchy X\"\n  shows \"\\<not> positive (Real X) \\<longleftrightarrow> (\\<forall>r>0. \\<exists>k. \\<forall>n\\<ge>k. X n \\<le> r)\"\nunfolding positive_Real [OF X]\napply (auto, unfold not_less)\napply (erule obtain_pos_sum)\napply (drule_tac x=s in spec, simp)\napply (drule_tac r=t in cauchyD [OF X], clarify)\napply (drule_tac x=k in spec, clarsimp)\napply (rule_tac x=n in exI, clarify, rename_tac m)\napply (drule_tac x=m in spec, simp)\napply (drule_tac x=n in spec, simp)\napply (drule spec, drule (1) mp, clarify, rename_tac i)\napply (rule_tac x=\"max i k\" in exI, simp)\ndone\n\nlemma le_Real:\n  assumes X: \"cauchy X\" and Y: \"cauchy Y\"\n  shows \"Real X \\<le> Real Y = (\\<forall>r>0. \\<exists>k. \\<forall>n\\<ge>k. X n \\<le> Y n + r)\"\nunfolding not_less [symmetric, where 'a=real] less_real_def\napply (simp add: diff_Real not_positive_Real X Y)\napply (simp add: diff_le_eq ac_simps)\ndone\n\nlemma le_RealI:\n  assumes Y: \"cauchy Y\"\n  shows \"\\<forall>n. x \\<le> of_rat (Y n) \\<Longrightarrow> x \\<le> Real Y\"\nproof (induct x)\n  fix X assume X: \"cauchy X\" and \"\\<forall>n. Real X \\<le> of_rat (Y n)\"\n  hence le: \"\\<And>m r. 0 < r \\<Longrightarrow> \\<exists>k. \\<forall>n\\<ge>k. X n \\<le> Y m + r\"\n    by (simp add: of_rat_Real le_Real)\n  {\n    fix r :: rat assume \"0 < r\"\n    then obtain s t where s: \"0 < s\" and t: \"0 < t\" and r: \"r = s + t\"\n      by (rule obtain_pos_sum)\n    obtain i where i: \"\\<forall>m\\<ge>i. \\<forall>n\\<ge>i. \\<bar>Y m - Y n\\<bar> < s\"\n      using cauchyD [OF Y s] ..\n    obtain j where j: \"\\<forall>n\\<ge>j. X n \\<le> Y i + t\"\n      using le [OF t] ..\n    have \"\\<forall>n\\<ge>max i j. X n \\<le> Y n + r\"\n    proof (clarsimp)\n      fix n assume n: \"i \\<le> n\" \"j \\<le> n\"\n      have \"X n \\<le> Y i + t\" using n j by simp\n      moreover have \"\\<bar>Y i - Y n\\<bar> < s\" using n i by simp\n      ultimately show \"X n \\<le> Y n + r\" unfolding r by simp\n    qed\n    hence \"\\<exists>k. \\<forall>n\\<ge>k. X n \\<le> Y n + r\" ..\n  }\n  thus \"Real X \\<le> Real Y\"\n    by (simp add: of_rat_Real le_Real X Y)\nqed\n\nlemma Real_leI:\n  assumes X: \"cauchy X\"\n  assumes le: \"\\<forall>n. of_rat (X n) \\<le> y\"\n  shows \"Real X \\<le> y\"\nproof -\n  have \"- y \\<le> - Real X\"\n    by (simp add: minus_Real X le_RealI of_rat_minus le)\n  thus ?thesis by simp\nqed\n\nlemma less_RealD:\n  assumes Y: \"cauchy Y\"\n  shows \"x < Real Y \\<Longrightarrow> \\<exists>n. x < of_rat (Y n)\"\nby (erule contrapos_pp, simp add: not_less, erule Real_leI [OF Y])\n\nlemma of_nat_less_two_power:\n  \"of_nat n < (2::'a::linordered_idom) ^ n\"\napply (induct n)\napply simp\napply (subgoal_tac \"(1::'a) \\<le> 2 ^ n\")\napply (drule (1) add_le_less_mono, simp)\napply simp\ndone\n\nlemma complete_real:\n  fixes S :: \"real set\"\n  assumes \"\\<exists>x. x \\<in> S\" and \"\\<exists>z. \\<forall>x\\<in>S. x \\<le> z\"\n  shows \"\\<exists>y. (\\<forall>x\\<in>S. x \\<le> y) \\<and> (\\<forall>z. (\\<forall>x\\<in>S. x \\<le> z) \\<longrightarrow> y \\<le> z)\"\nproof -\n  obtain x where x: \"x \\<in> S\" using assms(1) ..\n  obtain z where z: \"\\<forall>x\\<in>S. x \\<le> z\" using assms(2) ..\n\n  def P \\<equiv> \"\\<lambda>x. \\<forall>y\\<in>S. y \\<le> of_rat x\"\n  obtain a where a: \"\\<not> P a\"\n  proof\n    have \"of_int (floor (x - 1)) \\<le> x - 1\" by (rule of_int_floor_le)\n    also have \"x - 1 < x\" by simp\n    finally have \"of_int (floor (x - 1)) < x\" .\n    hence \"\\<not> x \\<le> of_int (floor (x - 1))\" by (simp only: not_le)\n    then show \"\\<not> P (of_int (floor (x - 1)))\"\n      unfolding P_def of_rat_of_int_eq using x by fast\n  qed\n  obtain b where b: \"P b\"\n  proof\n    show \"P (of_int (ceiling z))\"\n    unfolding P_def of_rat_of_int_eq\n    proof\n      fix y assume \"y \\<in> S\"\n      hence \"y \\<le> z\" using z by simp\n      also have \"z \\<le> of_int (ceiling z)\" by (rule le_of_int_ceiling)\n      finally show \"y \\<le> of_int (ceiling z)\" .\n    qed\n  qed\n\n  def avg \\<equiv> \"\\<lambda>x y :: rat. x/2 + y/2\"\n  def bisect \\<equiv> \"\\<lambda>(x, y). if P (avg x y) then (x, avg x y) else (avg x y, y)\"\n  def A \\<equiv> \"\\<lambda>n. fst ((bisect ^^ n) (a, b))\"\n  def B \\<equiv> \"\\<lambda>n. snd ((bisect ^^ n) (a, b))\"\n  def C \\<equiv> \"\\<lambda>n. avg (A n) (B n)\"\n  have A_0 [simp]: \"A 0 = a\" unfolding A_def by simp\n  have B_0 [simp]: \"B 0 = b\" unfolding B_def by simp\n  have A_Suc [simp]: \"\\<And>n. A (Suc n) = (if P (C n) then A n else C n)\"\n    unfolding A_def B_def C_def bisect_def split_def by simp\n  have B_Suc [simp]: \"\\<And>n. B (Suc n) = (if P (C n) then C n else B n)\"\n    unfolding A_def B_def C_def bisect_def split_def by simp\n\n  have width: \"\\<And>n. B n - A n = (b - a) / 2^n\"\n    apply (simp add: eq_divide_eq)\n    apply (induct_tac n, simp)\n    apply (simp add: C_def avg_def algebra_simps)\n    done\n\n  have twos: \"\\<And>y r :: rat. 0 < r \\<Longrightarrow> \\<exists>n. y / 2 ^ n < r\"\n    apply (simp add: divide_less_eq)\n    apply (subst mult.commute)\n    apply (frule_tac y=y in ex_less_of_nat_mult)\n    apply clarify\n    apply (rule_tac x=n in exI)\n    apply (erule less_trans)\n    apply (rule mult_strict_right_mono)\n    apply (rule le_less_trans [OF _ of_nat_less_two_power])\n    apply simp\n    apply assumption\n    done\n\n  have PA: \"\\<And>n. \\<not> P (A n)\"\n    by (induct_tac n, simp_all add: a)\n  have PB: \"\\<And>n. P (B n)\"\n    by (induct_tac n, simp_all add: b)\n  have ab: \"a < b\"\n    using a b unfolding P_def\n    apply (clarsimp simp add: not_le)\n    apply (drule (1) bspec)\n    apply (drule (1) less_le_trans)\n    apply (simp add: of_rat_less)\n    done\n  have AB: \"\\<And>n. A n < B n\"\n    by (induct_tac n, simp add: ab, simp add: C_def avg_def)\n  have A_mono: \"\\<And>i j. i \\<le> j \\<Longrightarrow> A i \\<le> A j\"\n    apply (auto simp add: le_less [where 'a=nat])\n    apply (erule less_Suc_induct)\n    apply (clarsimp simp add: C_def avg_def)\n    apply (simp add: add_divide_distrib [symmetric])\n    apply (rule AB [THEN less_imp_le])\n    apply simp\n    done\n  have B_mono: \"\\<And>i j. i \\<le> j \\<Longrightarrow> B j \\<le> B i\"\n    apply (auto simp add: le_less [where 'a=nat])\n    apply (erule less_Suc_induct)\n    apply (clarsimp simp add: C_def avg_def)\n    apply (simp add: add_divide_distrib [symmetric])\n    apply (rule AB [THEN less_imp_le])\n    apply simp\n    done\n  have cauchy_lemma:\n    \"\\<And>X. \\<forall>n. \\<forall>i\\<ge>n. A n \\<le> X i \\<and> X i \\<le> B n \\<Longrightarrow> cauchy X\"\n    apply (rule cauchyI)\n    apply (drule twos [where y=\"b - a\"])\n    apply (erule exE)\n    apply (rule_tac x=n in exI, clarify, rename_tac i j)\n    apply (rule_tac y=\"B n - A n\" in le_less_trans) defer\n    apply (simp add: width)\n    apply (drule_tac x=n in spec)\n    apply (frule_tac x=i in spec, drule (1) mp)\n    apply (frule_tac x=j in spec, drule (1) mp)\n    apply (frule A_mono, drule B_mono)\n    apply (frule A_mono, drule B_mono)\n    apply arith\n    done\n  have \"cauchy A\"\n    apply (rule cauchy_lemma [rule_format])\n    apply (simp add: A_mono)\n    apply (erule order_trans [OF less_imp_le [OF AB] B_mono])\n    done\n  have \"cauchy B\"\n    apply (rule cauchy_lemma [rule_format])\n    apply (simp add: B_mono)\n    apply (erule order_trans [OF A_mono less_imp_le [OF AB]])\n    done\n  have 1: \"\\<forall>x\\<in>S. x \\<le> Real B\"\n  proof\n    fix x assume \"x \\<in> S\"\n    then show \"x \\<le> Real B\"\n      using PB [unfolded P_def] `cauchy B`\n      by (simp add: le_RealI)\n  qed\n  have 2: \"\\<forall>z. (\\<forall>x\\<in>S. x \\<le> z) \\<longrightarrow> Real A \\<le> z\"\n    apply clarify\n    apply (erule contrapos_pp)\n    apply (simp add: not_le)\n    apply (drule less_RealD [OF `cauchy A`], clarify)\n    apply (subgoal_tac \"\\<not> P (A n)\")\n    apply (simp add: P_def not_le, clarify)\n    apply (erule rev_bexI)\n    apply (erule (1) less_trans)\n    apply (simp add: PA)\n    done\n  have \"vanishes (\\<lambda>n. (b - a) / 2 ^ n)\"\n  proof (rule vanishesI)\n    fix r :: rat assume \"0 < r\"\n    then obtain k where k: \"\\<bar>b - a\\<bar> / 2 ^ k < r\"\n      using twos by fast\n    have \"\\<forall>n\\<ge>k. \\<bar>(b - a) / 2 ^ n\\<bar> < r\"\n    proof (clarify)\n      fix n assume n: \"k \\<le> n\"\n      have \"\\<bar>(b - a) / 2 ^ n\\<bar> = \\<bar>b - a\\<bar> / 2 ^ n\"\n        by simp\n      also have \"\\<dots> \\<le> \\<bar>b - a\\<bar> / 2 ^ k\"\n        using n by (simp add: divide_left_mono)\n      also note k\n      finally show \"\\<bar>(b - a) / 2 ^ n\\<bar> < r\" .\n    qed\n    thus \"\\<exists>k. \\<forall>n\\<ge>k. \\<bar>(b - a) / 2 ^ n\\<bar> < r\" ..\n  qed\n  hence 3: \"Real B = Real A\"\n    by (simp add: eq_Real `cauchy A` `cauchy B` width)\n  show \"\\<exists>y. (\\<forall>x\\<in>S. x \\<le> y) \\<and> (\\<forall>z. (\\<forall>x\\<in>S. x \\<le> z) \\<longrightarrow> y \\<le> z)\"\n    using 1 2 3 by (rule_tac x=\"Real B\" in exI, simp)\nqed\n\ninstantiation real :: linear_continuum\nbegin\n\nsubsection{*Supremum of a set of reals*}\n\ndefinition \"Sup X = (LEAST z::real. \\<forall>x\\<in>X. x \\<le> z)\"\ndefinition \"Inf (X::real set) = - Sup (uminus ` X)\"\n\ninstance\nproof\n  { fix x :: real and X :: \"real set\"\n    assume x: \"x \\<in> X\" \"bdd_above X\"\n    then obtain s where s: \"\\<forall>y\\<in>X. y \\<le> s\" \"\\<And>z. \\<forall>y\\<in>X. y \\<le> z \\<Longrightarrow> s \\<le> z\"\n      using complete_real[of X] unfolding bdd_above_def by blast\n    then show \"x \\<le> Sup X\"\n      unfolding Sup_real_def by (rule LeastI2_order) (auto simp: x) }\n  note Sup_upper = this\n\n  { fix z :: real and X :: \"real set\"\n    assume x: \"X \\<noteq> {}\" and z: \"\\<And>x. x \\<in> X \\<Longrightarrow> x \\<le> z\"\n    then obtain s where s: \"\\<forall>y\\<in>X. y \\<le> s\" \"\\<And>z. \\<forall>y\\<in>X. y \\<le> z \\<Longrightarrow> s \\<le> z\"\n      using complete_real[of X] by blast\n    then have \"Sup X = s\"\n      unfolding Sup_real_def by (best intro: Least_equality)  \n    also from s z have \"... \\<le> z\"\n      by blast\n    finally show \"Sup X \\<le> z\" . }\n  note Sup_least = this\n\n  { fix x :: real and X :: \"real set\" assume x: \"x \\<in> X\" \"bdd_below X\" then show \"Inf X \\<le> x\"\n      using Sup_upper[of \"-x\" \"uminus ` X\"] by (auto simp: Inf_real_def) }\n  { fix z :: real and X :: \"real set\" assume \"X \\<noteq> {}\" \"\\<And>x. x \\<in> X \\<Longrightarrow> z \\<le> x\" then show \"z \\<le> Inf X\"\n      using Sup_least[of \"uminus ` X\" \"- z\"] by (force simp: Inf_real_def) }\n  show \"\\<exists>a b::real. a \\<noteq> b\"\n    using zero_neq_one by blast\nqed\nend\n\n\nsubsection {* Hiding implementation details *}\n\nhide_const (open) vanishes cauchy positive Real\n\ndeclare Real_induct [induct del]\ndeclare Abs_real_induct [induct del]\ndeclare Abs_real_cases [cases del]\n\nlifting_update real.lifting\nlifting_forget real.lifting\n  \nsubsection{*More Lemmas*}\n\ntext {* BH: These lemmas should not be necessary; they should be\ncovered by existing simp rules and simplification procedures. *}\n\nlemma real_mult_less_iff1 [simp]: \"(0::real) < z ==> (x*z < y*z) = (x < y)\"\nby simp (* solved by linordered_ring_less_cancel_factor simproc *)\n\nlemma real_mult_le_cancel_iff1 [simp]: \"(0::real) < z ==> (x*z \\<le> y*z) = (x\\<le>y)\"\nby simp (* solved by linordered_ring_le_cancel_factor simproc *)\n\nlemma real_mult_le_cancel_iff2 [simp]: \"(0::real) < z ==> (z*x \\<le> z*y) = (x\\<le>y)\"\nby simp (* solved by linordered_ring_le_cancel_factor simproc *)\n\n\nsubsection {* Embedding numbers into the Reals *}\n\nabbreviation\n  real_of_nat :: \"nat \\<Rightarrow> real\"\nwhere\n  \"real_of_nat \\<equiv> of_nat\"\n\nabbreviation\n  real_of_int :: \"int \\<Rightarrow> real\"\nwhere\n  \"real_of_int \\<equiv> of_int\"\n\nabbreviation\n  real_of_rat :: \"rat \\<Rightarrow> real\"\nwhere\n  \"real_of_rat \\<equiv> of_rat\"\n\nclass real_of =\n  fixes real :: \"'a \\<Rightarrow> real\"\n\ninstantiation nat :: real_of\nbegin\n\ndefinition real_nat :: \"nat \\<Rightarrow> real\" where real_of_nat_def [code_unfold]: \"real \\<equiv> of_nat\" \n\ninstance ..\nend\n\ninstantiation int :: real_of\nbegin\n\ndefinition real_int :: \"int \\<Rightarrow> real\" where real_of_int_def [code_unfold]: \"real \\<equiv> of_int\" \n\ninstance ..\nend\n\ndeclare [[coercion_enabled]]\n\ndeclare [[coercion \"of_nat :: nat \\<Rightarrow> int\"]]\ndeclare [[coercion \"real   :: nat \\<Rightarrow> real\"]]\ndeclare [[coercion \"real   :: int \\<Rightarrow> real\"]]\n\n(* We do not add rat to the coerced types, this has often unpleasant side effects when writing\ninverse (Suc n) which sometimes gets two coercions: of_rat (inverse (of_nat (Suc n))) *)\n\ndeclare [[coercion_map map]]\ndeclare [[coercion_map \"\\<lambda>f g h x. g (h (f x))\"]]\ndeclare [[coercion_map \"\\<lambda>f g (x,y). (f x, g y)\"]]\n\nlemma real_eq_of_nat: \"real = of_nat\"\n  unfolding real_of_nat_def ..\n\nlemma real_eq_of_int: \"real = of_int\"\n  unfolding real_of_int_def ..\n\nlemma real_of_int_zero [simp]: \"real (0::int) = 0\"  \nby (simp add: real_of_int_def) \n\nlemma real_of_one [simp]: \"real (1::int) = (1::real)\"\nby (simp add: real_of_int_def) \n\nlemma real_of_int_add [simp]: \"real(x + y) = real (x::int) + real y\"\nby (simp add: real_of_int_def) \n\nlemma real_of_int_minus [simp]: \"real(-x) = -real (x::int)\"\nby (simp add: real_of_int_def) \n\nlemma real_of_int_diff [simp]: \"real(x - y) = real (x::int) - real y\"\nby (simp add: real_of_int_def) \n\nlemma real_of_int_mult [simp]: \"real(x * y) = real (x::int) * real y\"\nby (simp add: real_of_int_def) \n\nlemma real_of_int_power [simp]: \"real (x ^ n) = real (x::int) ^ n\"\nby (simp add: real_of_int_def of_int_power)\n\nlemmas power_real_of_int = real_of_int_power [symmetric]\n\nlemma real_of_int_setsum [simp]: \"real ((SUM x:A. f x)::int) = (SUM x:A. real(f x))\"\n  apply (subst real_eq_of_int)+\n  apply (rule of_int_setsum)\ndone\n\nlemma real_of_int_setprod [simp]: \"real ((PROD x:A. f x)::int) = \n    (PROD x:A. real(f x))\"\n  apply (subst real_eq_of_int)+\n  apply (rule of_int_setprod)\ndone\n\nlemma real_of_int_zero_cancel [simp, algebra, presburger]: \"(real x = 0) = (x = (0::int))\"\nby (simp add: real_of_int_def) \n\nlemma real_of_int_inject [iff, algebra, presburger]: \"(real (x::int) = real y) = (x = y)\"\nby (simp add: real_of_int_def) \n\nlemma real_of_int_less_iff [iff, presburger]: \"(real (x::int) < real y) = (x < y)\"\nby (simp add: real_of_int_def) \n\nlemma real_of_int_le_iff [simp, presburger]: \"(real (x::int) \\<le> real y) = (x \\<le> y)\"\nby (simp add: real_of_int_def) \n\nlemma real_of_int_gt_zero_cancel_iff [simp, presburger]: \"(0 < real (n::int)) = (0 < n)\"\nby (simp add: real_of_int_def) \n\nlemma real_of_int_ge_zero_cancel_iff [simp, presburger]: \"(0 <= real (n::int)) = (0 <= n)\"\nby (simp add: real_of_int_def) \n\nlemma real_of_int_lt_zero_cancel_iff [simp, presburger]: \"(real (n::int) < 0) = (n < 0)\" \nby (simp add: real_of_int_def)\n\nlemma real_of_int_le_zero_cancel_iff [simp, presburger]: \"(real (n::int) <= 0) = (n <= 0)\"\nby (simp add: real_of_int_def)\n\nlemma one_less_real_of_int_cancel_iff: \"1 < real (i :: int) \\<longleftrightarrow> 1 < i\"\n  unfolding real_of_one[symmetric] real_of_int_less_iff ..\n\nlemma one_le_real_of_int_cancel_iff: \"1 \\<le> real (i :: int) \\<longleftrightarrow> 1 \\<le> i\"\n  unfolding real_of_one[symmetric] real_of_int_le_iff ..\n\nlemma real_of_int_less_one_cancel_iff: \"real (i :: int) < 1 \\<longleftrightarrow> i < 1\"\n  unfolding real_of_one[symmetric] real_of_int_less_iff ..\n\nlemma real_of_int_le_one_cancel_iff: \"real (i :: int) \\<le> 1 \\<longleftrightarrow> i \\<le> 1\"\n  unfolding real_of_one[symmetric] real_of_int_le_iff ..\n\nlemma real_of_int_abs [simp]: \"real (abs x) = abs(real (x::int))\"\nby (auto simp add: abs_if)\n\nlemma int_less_real_le: \"((n::int) < m) = (real n + 1 <= real m)\"\n  apply (subgoal_tac \"real n + 1 = real (n + 1)\")\n  apply (simp del: real_of_int_add)\n  apply auto\ndone\n\nlemma int_le_real_less: \"((n::int) <= m) = (real n < real m + 1)\"\n  apply (subgoal_tac \"real m + 1 = real (m + 1)\")\n  apply (simp del: real_of_int_add)\n  apply simp\ndone\n\nlemma real_of_int_div_aux: \"(real (x::int)) / (real d) = \n    real (x div d) + (real (x mod d)) / (real d)\"\nproof -\n  have \"x = (x div d) * d + x mod d\"\n    by auto\n  then have \"real x = real (x div d) * real d + real(x mod d)\"\n    by (simp only: real_of_int_mult [THEN sym] real_of_int_add [THEN sym])\n  then have \"real x / real d = ... / real d\"\n    by simp\n  then show ?thesis\n    by (auto simp add: add_divide_distrib algebra_simps)\nqed\n\nlemma real_of_int_div:\n  fixes d n :: int\n  shows \"d dvd n \\<Longrightarrow> real (n div d) = real n / real d\"\n  by (simp add: real_of_int_div_aux)\n\nlemma real_of_int_div2:\n  \"0 <= real (n::int) / real (x) - real (n div x)\"\n  apply (case_tac \"x = 0\")\n  apply simp\n  apply (case_tac \"0 < x\")\n  apply (simp add: algebra_simps)\n  apply (subst real_of_int_div_aux)\n  apply simp\n  apply (simp add: algebra_simps)\n  apply (subst real_of_int_div_aux)\n  apply simp\n  apply (subst zero_le_divide_iff)\n  apply auto\ndone\n\nlemma real_of_int_div3:\n  \"real (n::int) / real (x) - real (n div x) <= 1\"\n  apply (simp add: algebra_simps)\n  apply (subst real_of_int_div_aux)\n  apply (auto simp add: divide_le_eq intro: order_less_imp_le)\ndone\n\nlemma real_of_int_div4: \"real (n div x) <= real (n::int) / real x\" \nby (insert real_of_int_div2 [of n x], simp)\n\nlemma Ints_real_of_int [simp]: \"real (x::int) \\<in> Ints\"\nunfolding real_of_int_def by (rule Ints_of_int)\n\n\nsubsection{*Embedding the Naturals into the Reals*}\n\nlemma real_of_nat_zero [simp]: \"real (0::nat) = 0\"\nby (simp add: real_of_nat_def)\n\nlemma real_of_nat_1 [simp]: \"real (1::nat) = 1\"\nby (simp add: real_of_nat_def)\n\nlemma real_of_nat_one [simp]: \"real (Suc 0) = (1::real)\"\nby (simp add: real_of_nat_def)\n\nlemma real_of_nat_add [simp]: \"real (m + n) = real (m::nat) + real n\"\nby (simp add: real_of_nat_def)\n\n(*Not for addsimps: often the LHS is used to represent a positive natural*)\nlemma real_of_nat_Suc: \"real (Suc n) = real n + (1::real)\"\nby (simp add: real_of_nat_def)\n\nlemma real_of_nat_less_iff [iff]: \n     \"(real (n::nat) < real m) = (n < m)\"\nby (simp add: real_of_nat_def)\n\nlemma real_of_nat_le_iff [iff]: \"(real (n::nat) \\<le> real m) = (n \\<le> m)\"\nby (simp add: real_of_nat_def)\n\nlemma real_of_nat_ge_zero [iff]: \"0 \\<le> real (n::nat)\"\nby (simp add: real_of_nat_def)\n\nlemma real_of_nat_Suc_gt_zero: \"0 < real (Suc n)\"\nby (simp add: real_of_nat_def del: of_nat_Suc)\n\nlemma real_of_nat_mult [simp]: \"real (m * n) = real (m::nat) * real n\"\nby (simp add: real_of_nat_def of_nat_mult)\n\nlemma real_of_nat_power [simp]: \"real (m ^ n) = real (m::nat) ^ n\"\nby (simp add: real_of_nat_def of_nat_power)\n\nlemmas power_real_of_nat = real_of_nat_power [symmetric]\n\nlemma real_of_nat_setsum [simp]: \"real ((SUM x:A. f x)::nat) = \n    (SUM x:A. real(f x))\"\n  apply (subst real_eq_of_nat)+\n  apply (rule of_nat_setsum)\ndone\n\nlemma real_of_nat_setprod [simp]: \"real ((PROD x:A. f x)::nat) = \n    (PROD x:A. real(f x))\"\n  apply (subst real_eq_of_nat)+\n  apply (rule of_nat_setprod)\ndone\n\nlemma real_of_card: \"real (card A) = setsum (%x.1) A\"\n  apply (subst card_eq_setsum)\n  apply (subst real_of_nat_setsum)\n  apply simp\ndone\n\nlemma real_of_nat_inject [iff]: \"(real (n::nat) = real m) = (n = m)\"\nby (simp add: real_of_nat_def)\n\nlemma real_of_nat_zero_iff [iff]: \"(real (n::nat) = 0) = (n = 0)\"\nby (simp add: real_of_nat_def)\n\nlemma real_of_nat_diff: \"n \\<le> m ==> real (m - n) = real (m::nat) - real n\"\nby (simp add: add: real_of_nat_def of_nat_diff)\n\nlemma real_of_nat_gt_zero_cancel_iff [simp]: \"(0 < real (n::nat)) = (0 < n)\"\nby (auto simp: real_of_nat_def)\n\nlemma real_of_nat_le_zero_cancel_iff [simp]: \"(real (n::nat) \\<le> 0) = (n = 0)\"\nby (simp add: add: real_of_nat_def)\n\nlemma not_real_of_nat_less_zero [simp]: \"~ real (n::nat) < 0\"\nby (simp add: add: real_of_nat_def)\n\nlemma nat_less_real_le: \"((n::nat) < m) = (real n + 1 <= real m)\"\n  apply (subgoal_tac \"real n + 1 = real (Suc n)\")\n  apply simp\n  apply (auto simp add: real_of_nat_Suc)\ndone\n\nlemma nat_le_real_less: \"((n::nat) <= m) = (real n < real m + 1)\"\n  apply (subgoal_tac \"real m + 1 = real (Suc m)\")\n  apply (simp add: less_Suc_eq_le)\n  apply (simp add: real_of_nat_Suc)\ndone\n\nlemma real_of_nat_div_aux: \"(real (x::nat)) / (real d) = \n    real (x div d) + (real (x mod d)) / (real d)\"\nproof -\n  have \"x = (x div d) * d + x mod d\"\n    by auto\n  then have \"real x = real (x div d) * real d + real(x mod d)\"\n    by (simp only: real_of_nat_mult [THEN sym] real_of_nat_add [THEN sym])\n  then have \"real x / real d = \\<dots> / real d\"\n    by simp\n  then show ?thesis\n    by (auto simp add: add_divide_distrib algebra_simps)\nqed\n\nlemma real_of_nat_div: \"(d :: nat) dvd n ==>\n    real(n div d) = real n / real d\"\n  by (subst real_of_nat_div_aux)\n    (auto simp add: dvd_eq_mod_eq_0 [symmetric])\n\nlemma real_of_nat_div2:\n  \"0 <= real (n::nat) / real (x) - real (n div x)\"\napply (simp add: algebra_simps)\napply (subst real_of_nat_div_aux)\napply simp\ndone\n\nlemma real_of_nat_div3:\n  \"real (n::nat) / real (x) - real (n div x) <= 1\"\napply(case_tac \"x = 0\")\napply (simp)\napply (simp add: algebra_simps)\napply (subst real_of_nat_div_aux)\napply simp\ndone\n\nlemma real_of_nat_div4: \"real (n div x) <= real (n::nat) / real x\" \nby (insert real_of_nat_div2 [of n x], simp)\n\nlemma real_of_int_of_nat_eq [simp]: \"real (of_nat n :: int) = real n\"\nby (simp add: real_of_int_def real_of_nat_def)\n\nlemma real_nat_eq_real [simp]: \"0 <= x ==> real(nat x) = real x\"\n  apply (subgoal_tac \"real(int(nat x)) = real(nat x)\")\n  apply force\n  apply (simp only: real_of_int_of_nat_eq)\ndone\n\nlemma Nats_real_of_nat [simp]: \"real (n::nat) \\<in> Nats\"\nunfolding real_of_nat_def by (rule of_nat_in_Nats)\n\nlemma Ints_real_of_nat [simp]: \"real (n::nat) \\<in> Ints\"\nunfolding real_of_nat_def by (rule Ints_of_nat)\n\nsubsection {* The Archimedean Property of the Reals *}\n\ntheorem reals_Archimedean:\n  assumes x_pos: \"0 < x\"\n  shows \"\\<exists>n. inverse (real (Suc n)) < x\"\n  unfolding real_of_nat_def using x_pos\n  by (rule ex_inverse_of_nat_Suc_less)\n\nlemma reals_Archimedean2: \"\\<exists>n. (x::real) < real (n::nat)\"\n  unfolding real_of_nat_def by (rule ex_less_of_nat)\n\nlemma reals_Archimedean3:\n  assumes x_greater_zero: \"0 < x\"\n  shows \"\\<forall>(y::real). \\<exists>(n::nat). y < real n * x\"\n  unfolding real_of_nat_def using `0 < x`\n  by (auto intro: ex_less_of_nat_mult)\n\n\nsubsection{* Rationals *}\n\nlemma Rats_real_nat[simp]: \"real(n::nat) \\<in> \\<rat>\"\nby (simp add: real_eq_of_nat)\n\nlemma Rats_eq_int_div_int:\n  \"\\<rat> = { real(i::int)/real(j::int) |i j. j \\<noteq> 0}\" (is \"_ = ?S\")\nproof\n  show \"\\<rat> \\<subseteq> ?S\"\n  proof\n    fix x::real assume \"x : \\<rat>\"\n    then obtain r where \"x = of_rat r\" unfolding Rats_def ..\n    have \"of_rat r : ?S\"\n      by (cases r)(auto simp add:of_rat_rat real_eq_of_int)\n    thus \"x : ?S\" using `x = of_rat r` by simp\n  qed\nnext\n  show \"?S \\<subseteq> \\<rat>\"\n  proof(auto simp:Rats_def)\n    fix i j :: int assume \"j \\<noteq> 0\"\n    hence \"real i / real j = of_rat(Fract i j)\"\n      by (simp add:of_rat_rat real_eq_of_int)\n    thus \"real i / real j \\<in> range of_rat\" by blast\n  qed\nqed\n\nlemma Rats_eq_int_div_nat:\n  \"\\<rat> = { real(i::int)/real(n::nat) |i n. n \\<noteq> 0}\"\nproof(auto simp:Rats_eq_int_div_int)\n  fix i j::int assume \"j \\<noteq> 0\"\n  show \"EX (i'::int) (n::nat). real i/real j = real i'/real n \\<and> 0<n\"\n  proof cases\n    assume \"j>0\"\n    hence \"real i/real j = real i/real(nat j) \\<and> 0<nat j\"\n      by (simp add: real_eq_of_int real_eq_of_nat of_nat_nat)\n    thus ?thesis by blast\n  next\n    assume \"~ j>0\"\n    hence \"real i/real j = real(-i)/real(nat(-j)) \\<and> 0<nat(-j)\" using `j\\<noteq>0`\n      by (simp add: real_eq_of_int real_eq_of_nat of_nat_nat)\n    thus ?thesis by blast\n  qed\nnext\n  fix i::int and n::nat assume \"0 < n\"\n  hence \"real i/real n = real i/real(int n) \\<and> int n \\<noteq> 0\" by simp\n  thus \"\\<exists>(i'::int) j::int. real i/real n = real i'/real j \\<and> j \\<noteq> 0\" by blast\nqed\n\nlemma Rats_abs_nat_div_natE:\n  assumes \"x \\<in> \\<rat>\"\n  obtains m n :: nat\n  where \"n \\<noteq> 0\" and \"\\<bar>x\\<bar> = real m / real n\" and \"gcd m n = 1\"\nproof -\n  from `x \\<in> \\<rat>` obtain i::int and n::nat where \"n \\<noteq> 0\" and \"x = real i / real n\"\n    by(auto simp add: Rats_eq_int_div_nat)\n  hence \"\\<bar>x\\<bar> = real(nat(abs i)) / real n\" by simp\n  then obtain m :: nat where x_rat: \"\\<bar>x\\<bar> = real m / real n\" by blast\n  let ?gcd = \"gcd m n\"\n  from `n\\<noteq>0` have gcd: \"?gcd \\<noteq> 0\" by simp\n  let ?k = \"m div ?gcd\"\n  let ?l = \"n div ?gcd\"\n  let ?gcd' = \"gcd ?k ?l\"\n  have \"?gcd dvd m\" .. then have gcd_k: \"?gcd * ?k = m\"\n    by (rule dvd_mult_div_cancel)\n  have \"?gcd dvd n\" .. then have gcd_l: \"?gcd * ?l = n\"\n    by (rule dvd_mult_div_cancel)\n  from `n \\<noteq> 0` and gcd_l\n  have \"?gcd * ?l \\<noteq> 0\" by simp\n  then have \"?l \\<noteq> 0\" by (blast dest!: mult_not_zero) \n  moreover\n  have \"\\<bar>x\\<bar> = real ?k / real ?l\"\n  proof -\n    from gcd have \"real ?k / real ?l =\n      real (?gcd * ?k) / real (?gcd * ?l)\"\n      by (simp only: real_of_nat_mult) simp\n    also from gcd_k and gcd_l have \"\\<dots> = real m / real n\" by simp\n    also from x_rat have \"\\<dots> = \\<bar>x\\<bar>\" ..\n    finally show ?thesis ..\n  qed\n  moreover\n  have \"?gcd' = 1\"\n  proof -\n    have \"?gcd * ?gcd' = gcd (?gcd * ?k) (?gcd * ?l)\"\n      by (rule gcd_mult_distrib_nat)\n    with gcd_k gcd_l have \"?gcd * ?gcd' = ?gcd\" by simp\n    with gcd show ?thesis by auto\n  qed\n  ultimately show ?thesis ..\nqed\n\nsubsection{*Density of the Rational Reals in the Reals*}\n\ntext{* This density proof is due to Stefan Richter and was ported by TN.  The\noriginal source is \\emph{Real Analysis} by H.L. Royden.\nIt employs the Archimedean property of the reals. *}\n\nlemma Rats_dense_in_real:\n  fixes x :: real\n  assumes \"x < y\" shows \"\\<exists>r\\<in>\\<rat>. x < r \\<and> r < y\"\nproof -\n  from `x<y` have \"0 < y-x\" by simp\n  with reals_Archimedean obtain q::nat \n    where q: \"inverse (real q) < y-x\" and \"0 < q\" by auto\n  def p \\<equiv> \"ceiling (y * real q) - 1\"\n  def r \\<equiv> \"of_int p / real q\"\n  from q have \"x < y - inverse (real q)\" by simp\n  also have \"y - inverse (real q) \\<le> r\"\n    unfolding r_def p_def\n    by (simp add: le_divide_eq left_diff_distrib le_of_int_ceiling `0 < q`)\n  finally have \"x < r\" .\n  moreover have \"r < y\"\n    unfolding r_def p_def\n    by (simp add: divide_less_eq diff_less_eq `0 < q`\n      less_ceiling_iff [symmetric])\n  moreover from r_def have \"r \\<in> \\<rat>\" by simp\n  ultimately show ?thesis by fast\nqed\n\nlemma of_rat_dense:\n  fixes x y :: real\n  assumes \"x < y\"\n  shows \"\\<exists>q :: rat. x < of_rat q \\<and> of_rat q < y\"\nusing Rats_dense_in_real [OF `x < y`]\nby (auto elim: Rats_cases)\n\n\nsubsection{*Numerals and Arithmetic*}\n\nlemma [code_abbrev]:\n  \"real_of_int (numeral k) = numeral k\"\n  \"real_of_int (- numeral k) = - numeral k\"\n  by simp_all\n\ntext{*Collapse applications of @{const real} to @{const numeral}*}\nlemma real_numeral [simp]:\n  \"real (numeral v :: int) = numeral v\"\n  \"real (- numeral v :: int) = - numeral v\"\nby (simp_all add: real_of_int_def)\n\nlemma  real_of_nat_numeral [simp]:\n  \"real (numeral v :: nat) = numeral v\"\nby (simp add: real_of_nat_def)\n\ndeclaration {*\n  K (Lin_Arith.add_inj_thms [@{thm real_of_nat_le_iff} RS iffD2, @{thm real_of_nat_inject} RS iffD2]\n    (* not needed because x < (y::nat) can be rewritten as Suc x <= y: real_of_nat_less_iff RS iffD2 *)\n  #> Lin_Arith.add_inj_thms [@{thm real_of_int_le_iff} RS iffD2, @{thm real_of_int_inject} RS iffD2]\n    (* not needed because x < (y::int) can be rewritten as x + 1 <= y: real_of_int_less_iff RS iffD2 *)\n  #> Lin_Arith.add_simps [@{thm real_of_nat_zero}, @{thm real_of_nat_Suc}, @{thm real_of_nat_add},\n      @{thm real_of_nat_mult}, @{thm real_of_int_zero}, @{thm real_of_one},\n      @{thm real_of_int_add}, @{thm real_of_int_minus}, @{thm real_of_int_diff},\n      @{thm real_of_int_mult}, @{thm real_of_int_of_nat_eq},\n      @{thm real_of_nat_numeral}, @{thm real_numeral(1)}, @{thm real_numeral(2)},\n      @{thm real_of_int_def[symmetric]}, @{thm real_of_nat_def[symmetric]}]\n  #> Lin_Arith.add_inj_const (@{const_name real}, @{typ \"nat \\<Rightarrow> real\"})\n  #> Lin_Arith.add_inj_const (@{const_name real}, @{typ \"int \\<Rightarrow> real\"})\n  #> Lin_Arith.add_inj_const (@{const_name of_nat}, @{typ \"nat \\<Rightarrow> real\"})\n  #> Lin_Arith.add_inj_const (@{const_name of_int}, @{typ \"int \\<Rightarrow> real\"}))\n*}\n\nsubsection{* Simprules combining x+y and 0: ARE THEY NEEDED?*}\n\nlemma real_add_minus_iff [simp]: \"(x + - a = (0::real)) = (x=a)\" \nby arith\n\ntext {* FIXME: redundant with @{text add_eq_0_iff} below *}\nlemma real_add_eq_0_iff: \"(x+y = (0::real)) = (y = -x)\"\nby auto\n\nlemma real_add_less_0_iff: \"(x+y < (0::real)) = (y < -x)\"\nby auto\n\nlemma real_0_less_add_iff: \"((0::real) < x+y) = (-x < y)\"\nby auto\n\nlemma real_add_le_0_iff: \"(x+y \\<le> (0::real)) = (y \\<le> -x)\"\nby auto\n\nlemma real_0_le_add_iff: \"((0::real) \\<le> x+y) = (-x \\<le> y)\"\nby auto\n\nsubsection {* Lemmas about powers *}\n\ntext {* FIXME: declare this in Rings.thy or not at all *}\ndeclare abs_mult_self [simp]\n\n(* used by Import/HOL/real.imp *)\nlemma two_realpow_ge_one: \"(1::real) \\<le> 2 ^ n\"\nby simp\n\nlemma two_realpow_gt [simp]: \"real (n::nat) < 2 ^ n\"\napply (induct \"n\")\napply (auto simp add: real_of_nat_Suc)\napply (subst mult_2)\napply (erule add_less_le_mono)\napply (rule two_realpow_ge_one)\ndone\n\ntext {* TODO: no longer real-specific; rename and move elsewhere *}\nlemma realpow_Suc_le_self:\n  fixes r :: \"'a::linordered_semidom\"\n  shows \"[| 0 \\<le> r; r \\<le> 1 |] ==> r ^ Suc n \\<le> r\"\nby (insert power_decreasing [of 1 \"Suc n\" r], simp)\n\ntext {* TODO: no longer real-specific; rename and move elsewhere *}\nlemma realpow_minus_mult:\n  fixes x :: \"'a::monoid_mult\"\n  shows \"0 < n \\<Longrightarrow> x ^ (n - 1) * x = x ^ n\"\nby (simp add: power_commutes split add: nat_diff_split)\n\ntext {* FIXME: declare this [simp] for all types, or not at all *}\nlemma real_two_squares_add_zero_iff [simp]:\n  \"(x * x + y * y = 0) = ((x::real) = 0 \\<and> y = 0)\"\nby (rule sum_squares_eq_zero_iff)\n\ntext {* FIXME: declare this [simp] for all types, or not at all *}\nlemma realpow_two_sum_zero_iff [simp]:\n     \"(x\\<^sup>2 + y\\<^sup>2 = (0::real)) = (x = 0 & y = 0)\"\nby (rule sum_power2_eq_zero_iff)\n\nlemma real_minus_mult_self_le [simp]: \"-(u * u) \\<le> (x * (x::real))\"\nby (rule_tac y = 0 in order_trans, auto)\n\nlemma realpow_square_minus_le [simp]: \"- u\\<^sup>2 \\<le> (x::real)\\<^sup>2\"\nby (auto simp add: power2_eq_square)\n\n\nlemma numeral_power_eq_real_of_int_cancel_iff[simp]:\n  \"numeral x ^ n = real (y::int) \\<longleftrightarrow> numeral x ^ n = y\"\n  by (metis real_numeral(1) real_of_int_inject real_of_int_power)\n\nlemma real_of_int_eq_numeral_power_cancel_iff[simp]:\n  \"real (y::int) = numeral x ^ n \\<longleftrightarrow> y = numeral x ^ n\"\n  using numeral_power_eq_real_of_int_cancel_iff[of x n y]\n  by metis\n\nlemma numeral_power_eq_real_of_nat_cancel_iff[simp]:\n  \"numeral x ^ n = real (y::nat) \\<longleftrightarrow> numeral x ^ n = y\"\n  by (metis of_nat_eq_iff of_nat_numeral real_of_int_eq_numeral_power_cancel_iff\n    real_of_int_of_nat_eq zpower_int)\n\nlemma real_of_nat_eq_numeral_power_cancel_iff[simp]:\n  \"real (y::nat) = numeral x ^ n \\<longleftrightarrow> y = numeral x ^ n\"\n  using numeral_power_eq_real_of_nat_cancel_iff[of x n y]\n  by metis\n\nlemma numeral_power_le_real_of_nat_cancel_iff[simp]:\n  \"(numeral x::real) ^ n \\<le> real a \\<longleftrightarrow> (numeral x::nat) ^ n \\<le> a\"\n  unfolding real_of_nat_le_iff[symmetric] by simp\n\nlemma real_of_nat_le_numeral_power_cancel_iff[simp]:\n  \"real a \\<le> (numeral x::real) ^ n \\<longleftrightarrow> a \\<le> (numeral x::nat) ^ n\"\n  unfolding real_of_nat_le_iff[symmetric] by simp\n\nlemma numeral_power_le_real_of_int_cancel_iff[simp]:\n  \"(numeral x::real) ^ n \\<le> real a \\<longleftrightarrow> (numeral x::int) ^ n \\<le> a\"\n  unfolding real_of_int_le_iff[symmetric] by simp\n\nlemma real_of_int_le_numeral_power_cancel_iff[simp]:\n  \"real a \\<le> (numeral x::real) ^ n \\<longleftrightarrow> a \\<le> (numeral x::int) ^ n\"\n  unfolding real_of_int_le_iff[symmetric] by simp\n\nlemma numeral_power_less_real_of_nat_cancel_iff[simp]:\n  \"(numeral x::real) ^ n < real a \\<longleftrightarrow> (numeral x::nat) ^ n < a\"\n  unfolding real_of_nat_less_iff[symmetric] by simp\n\nlemma real_of_nat_less_numeral_power_cancel_iff[simp]:\n  \"real a < (numeral x::real) ^ n \\<longleftrightarrow> a < (numeral x::nat) ^ n\"\n  unfolding real_of_nat_less_iff[symmetric] by simp\n\nlemma numeral_power_less_real_of_int_cancel_iff[simp]:\n  \"(numeral x::real) ^ n < real a \\<longleftrightarrow> (numeral x::int) ^ n < a\"\n  unfolding real_of_int_less_iff[symmetric] by simp\n\nlemma real_of_int_less_numeral_power_cancel_iff[simp]:\n  \"real a < (numeral x::real) ^ n \\<longleftrightarrow> a < (numeral x::int) ^ n\"\n  unfolding real_of_int_less_iff[symmetric] by simp\n\nlemma neg_numeral_power_le_real_of_int_cancel_iff[simp]:\n  \"(- numeral x::real) ^ n \\<le> real a \\<longleftrightarrow> (- numeral x::int) ^ n \\<le> a\"\n  unfolding real_of_int_le_iff[symmetric] by simp\n\nlemma real_of_int_le_neg_numeral_power_cancel_iff[simp]:\n  \"real a \\<le> (- numeral x::real) ^ n \\<longleftrightarrow> a \\<le> (- numeral x::int) ^ n\"\n  unfolding real_of_int_le_iff[symmetric] by simp\n\n\nsubsection{*Density of the Reals*}\n\nlemma real_lbound_gt_zero:\n     \"[| (0::real) < d1; 0 < d2 |] ==> \\<exists>e. 0 < e & e < d1 & e < d2\"\napply (rule_tac x = \" (min d1 d2) /2\" in exI)\napply (simp add: min_def)\ndone\n\n\ntext{*Similar results are proved in @{text Fields}*}\nlemma real_less_half_sum: \"x < y ==> x < (x+y) / (2::real)\"\n  by auto\n\nlemma real_gt_half_sum: \"x < y ==> (x+y)/(2::real) < y\"\n  by auto\n\nlemma real_sum_of_halves: \"x/2 + x/2 = (x::real)\"\n  by simp\n\nsubsection{*Absolute Value Function for the Reals*}\n\nlemma abs_minus_add_cancel: \"abs(x + (-y)) = abs (y + (-(x::real)))\"\nby (simp add: abs_if)\n\n(* FIXME: redundant, but used by Integration/RealRandVar.thy in AFP *)\nlemma abs_le_interval_iff: \"(abs x \\<le> r) = (-r\\<le>x & x\\<le>(r::real))\"\nby (force simp add: abs_le_iff)\n\nlemma abs_add_one_gt_zero: \"(0::real) < 1 + abs(x)\"\nby (simp add: abs_if)\n\nlemma abs_real_of_nat_cancel [simp]: \"abs (real x) = real (x::nat)\"\nby (rule abs_of_nonneg [OF real_of_nat_ge_zero])\n\nlemma abs_add_one_not_less_self: \"~ abs(x) + (1::real) < x\"\nby simp\n \nlemma abs_sum_triangle_ineq: \"abs ((x::real) + y + (-l + -m)) \\<le> abs(x + -l) + abs(y + -m)\"\nby simp\n\n\nsubsection{*Floor and Ceiling Functions from the Reals to the Integers*}\n\n(* FIXME: theorems for negative numerals *)\nlemma numeral_less_real_of_int_iff [simp]:\n     \"((numeral n) < real (m::int)) = (numeral n < m)\"\napply auto\napply (rule real_of_int_less_iff [THEN iffD1])\napply (drule_tac [2] real_of_int_less_iff [THEN iffD2], auto)\ndone\n\nlemma numeral_less_real_of_int_iff2 [simp]:\n     \"(real (m::int) < (numeral n)) = (m < numeral n)\"\napply auto\napply (rule real_of_int_less_iff [THEN iffD1])\napply (drule_tac [2] real_of_int_less_iff [THEN iffD2], auto)\ndone\n\nlemma real_of_nat_less_numeral_iff [simp]:\n  \"real (n::nat) < numeral w \\<longleftrightarrow> n < numeral w\"\n  using real_of_nat_less_iff[of n \"numeral w\"] by simp\n\nlemma numeral_less_real_of_nat_iff [simp]:\n  \"numeral w < real (n::nat) \\<longleftrightarrow> numeral w < n\"\n  using real_of_nat_less_iff[of \"numeral w\" n] by simp\n\nlemma numeral_le_real_of_int_iff [simp]:\n     \"((numeral n) \\<le> real (m::int)) = (numeral n \\<le> m)\"\nby (simp add: linorder_not_less [symmetric])\n\nlemma numeral_le_real_of_int_iff2 [simp]:\n     \"(real (m::int) \\<le> (numeral n)) = (m \\<le> numeral n)\"\nby (simp add: linorder_not_less [symmetric])\n\nlemma floor_real_of_nat [simp]: \"floor (real (n::nat)) = int n\"\nunfolding real_of_nat_def by simp\n\nlemma floor_minus_real_of_nat [simp]: \"floor (- real (n::nat)) = - int n\"\nunfolding real_of_nat_def by (simp add: floor_minus)\n\nlemma floor_real_of_int [simp]: \"floor (real (n::int)) = n\"\nunfolding real_of_int_def by simp\n\nlemma floor_minus_real_of_int [simp]: \"floor (- real (n::int)) = - n\"\nunfolding real_of_int_def by (simp add: floor_minus)\n\nlemma real_lb_ub_int: \" \\<exists>n::int. real n \\<le> r & r < real (n+1)\"\nunfolding real_of_int_def by (rule floor_exists)\n\nlemma lemma_floor: \"real m \\<le> r \\<Longrightarrow> r < real n + 1 \\<Longrightarrow> m \\<le> (n::int)\"\n  by simp\n\nlemma real_of_int_floor_le [simp]: \"real (floor r) \\<le> r\"\nunfolding real_of_int_def by (rule of_int_floor_le)\n\nlemma lemma_floor2: \"real n < real (x::int) + 1 ==> n \\<le> x\"\n  by simp\n\nlemma real_of_int_floor_cancel [simp]:\n    \"(real (floor x) = x) = (\\<exists>n::int. x = real n)\"\n  using floor_real_of_int by metis\n\nlemma floor_eq: \"[| real n < x; x < real n + 1 |] ==> floor x = n\"\n  by linarith\n\nlemma floor_eq2: \"[| real n \\<le> x; x < real n + 1 |] ==> floor x = n\"\n  by linarith\n\nlemma floor_eq3: \"[| real n < x; x < real (Suc n) |] ==> nat(floor x) = n\"\n  by linarith\n\nlemma floor_eq4: \"[| real n \\<le> x; x < real (Suc n) |] ==> nat(floor x) = n\"\n  by linarith\n\nlemma real_of_int_floor_ge_diff_one [simp]: \"r - 1 \\<le> real(floor r)\"\n  by linarith\n\nlemma real_of_int_floor_gt_diff_one [simp]: \"r - 1 < real(floor r)\"\n  by linarith\n\nlemma real_of_int_floor_add_one_ge [simp]: \"r \\<le> real(floor r) + 1\"\n  by linarith\n\nlemma real_of_int_floor_add_one_gt [simp]: \"r < real(floor r) + 1\"\n  by linarith\n\nlemma le_floor: \"real a <= x ==> a <= floor x\"\n  by linarith\n\nlemma real_le_floor: \"a <= floor x ==> real a <= x\"\n  by linarith\n\nlemma le_floor_eq: \"(a <= floor x) = (real a <= x)\"\n  by linarith\n\nlemma floor_less_eq: \"(floor x < a) = (x < real a)\"\n  by linarith\n\nlemma less_floor_eq: \"(a < floor x) = (real a + 1 <= x)\"\n  by linarith\n\nlemma floor_le_eq: \"(floor x <= a) = (x < real a + 1)\"\n  by linarith\n\nlemma floor_eq_iff: \"floor x = b \\<longleftrightarrow> real b \\<le> x \\<and> x < real (b + 1)\"\n  by linarith\n\nlemma floor_add [simp]: \"floor (x + real a) = floor x + a\"\n  by linarith\n\nlemma floor_add2[simp]: \"floor (real a + x) = a + floor x\"\n  by linarith\n\nlemma floor_subtract [simp]: \"floor (x - real a) = floor x - a\"\n  by linarith\n\nlemma floor_divide_real_eq_div: \"0 \\<le> b \\<Longrightarrow> floor (a / real b) = floor a div b\"\nproof cases\n  assume \"0 < b\"\n  { fix i j :: int assume \"real i \\<le> a\" \"a < 1 + real i\"\n      \"real j * real b \\<le> a\" \"a < real b + real j * real b\"\n    then have \"i < b + j * b\" \"j * b < 1 + i\"\n      unfolding real_of_int_less_iff[symmetric] by auto\n    then have \"(j - i div b) * b \\<le> i mod b\" \"i mod b < ((j - i div b) + 1) * b\"\n      by (auto simp: field_simps)\n    then have \"(j - i div b) * b < 1 * b\" \"0 * b < ((j - i div b) + 1) * b\"\n      using pos_mod_bound[OF `0<b`, of i] pos_mod_sign[OF `0<b`, of i] by linarith+\n    then have \"j = i div b\"\n      using `0 < b` unfolding mult_less_cancel_right by auto }\n  with `0 < b` show ?thesis\n    by (auto split: floor_split simp: field_simps)\nqed auto\n\nlemma floor_divide_eq_div:\n  \"floor (real a / real b) = a div b\"\nproof cases\n  assume \"b \\<noteq> 0 \\<or> b dvd a\"\n  with real_of_int_div3[of a b] show ?thesis\n    by (auto simp: real_of_int_div[symmetric] intro!: floor_eq2 real_of_int_div4 neq_le_trans)\n       (metis add_left_cancel zero_neq_one real_of_int_div_aux real_of_int_inject\n              real_of_int_zero_cancel right_inverse_eq div_self mod_div_trivial)\nqed (auto simp: real_of_int_div)\n\nlemma floor_divide_eq_div_numeral[simp]: \"\\<lfloor>numeral a / numeral b::real\\<rfloor> = numeral a div numeral b\"\n  using floor_divide_eq_div[of \"numeral a\" \"numeral b\"] by simp\n\nlemma floor_minus_divide_eq_div_numeral[simp]: \"\\<lfloor>- (numeral a / numeral b)::real\\<rfloor> = - numeral a div numeral b\"\n  using floor_divide_eq_div[of \"- numeral a\" \"numeral b\"] by simp\n\nlemma ceiling_real_of_nat [simp]: \"ceiling (real (n::nat)) = int n\"\n  by linarith\n\nlemma real_of_int_ceiling_ge [simp]: \"r \\<le> real (ceiling r)\"\n  by linarith\n\nlemma ceiling_real_of_int [simp]: \"ceiling (real (n::int)) = n\"\n  by linarith\n\nlemma real_of_int_ceiling_cancel [simp]:\n     \"(real (ceiling x) = x) = (\\<exists>n::int. x = real n)\"\n  using ceiling_real_of_int by metis\n\nlemma ceiling_eq: \"[| real n < x; x < real n + 1 |] ==> ceiling x = n + 1\"\n  by linarith\n\nlemma ceiling_eq2: \"[| real n < x; x \\<le> real n + 1 |] ==> ceiling x = n + 1\"\n  by linarith\n\nlemma ceiling_eq3: \"[| real n - 1 < x; x \\<le> real n  |] ==> ceiling x = n\"\n  by linarith\n\nlemma real_of_int_ceiling_diff_one_le [simp]: \"real (ceiling r) - 1 \\<le> r\"\n  by linarith\n\nlemma real_of_int_ceiling_le_add_one [simp]: \"real (ceiling r) \\<le> r + 1\"\n  by linarith\n\nlemma ceiling_le: \"x <= real a ==> ceiling x <= a\"\n  by linarith\n\nlemma ceiling_le_real: \"ceiling x <= a ==> x <= real a\"\n  by linarith\n\nlemma ceiling_le_eq: \"(ceiling x <= a) = (x <= real a)\"\n  by linarith\n\nlemma less_ceiling_eq: \"(a < ceiling x) = (real a < x)\"\n  by linarith\n\nlemma ceiling_less_eq: \"(ceiling x < a) = (x <= real a - 1)\"\n  by linarith\n\nlemma le_ceiling_eq: \"(a <= ceiling x) = (real a - 1 < x)\"\n  by linarith\n\nlemma ceiling_add [simp]: \"ceiling (x + real a) = ceiling x + a\"\n  by linarith\n\nlemma ceiling_subtract [simp]: \"ceiling (x - real a) = ceiling x - a\"\n  by linarith\n\nlemma ceiling_divide_eq_div: \"\\<lceil>real a / real b\\<rceil> = - (- a div b)\"\n  unfolding ceiling_def minus_divide_left real_of_int_minus[symmetric] floor_divide_eq_div by simp_all\n\nlemma ceiling_divide_eq_div_numeral [simp]:\n  \"\\<lceil>numeral a / numeral b :: real\\<rceil> = - (- numeral a div numeral b)\"\n  using ceiling_divide_eq_div[of \"numeral a\" \"numeral b\"] by simp\n\nlemma ceiling_minus_divide_eq_div_numeral [simp]:\n  \"\\<lceil>- (numeral a / numeral b :: real)\\<rceil> = - (numeral a div numeral b)\"\n  using ceiling_divide_eq_div[of \"- numeral a\" \"numeral b\"] by simp\n\nsubsubsection {* Versions for the natural numbers *}\n\ndefinition\n  natfloor :: \"real => nat\" where\n  \"natfloor x = nat(floor x)\"\n\ndefinition\n  natceiling :: \"real => nat\" where\n  \"natceiling x = nat(ceiling x)\"\n\nlemma natfloor_split[arith_split]: \"P (natfloor t) \\<longleftrightarrow> (t < 0 \\<longrightarrow> P 0) \\<and> (\\<forall>n. of_nat n \\<le> t \\<and> t < of_nat n + 1 \\<longrightarrow> P n)\"\nproof -\n  have [dest]: \"\\<And>n m::nat. real n \\<le> t \\<Longrightarrow> t < real n + 1 \\<Longrightarrow> real m \\<le> t \\<Longrightarrow> t < real m + 1 \\<Longrightarrow> n = m\"\n    by simp\n  show ?thesis\n    by (auto simp: natfloor_def real_of_nat_def[symmetric] split: split_nat floor_split)\nqed\n\nlemma natceiling_split[arith_split]:\n  \"P (natceiling t) \\<longleftrightarrow> (t \\<le> - 1 \\<longrightarrow> P 0) \\<and> (\\<forall>n. of_nat n - 1 < t \\<and> t \\<le> of_nat n \\<longrightarrow> P n)\"\nproof -\n  have [dest]: \"\\<And>n m::nat. real n - 1 < t \\<Longrightarrow> t \\<le> real n \\<Longrightarrow> real m - 1 < t \\<Longrightarrow> t \\<le> real m \\<Longrightarrow> n = m\"\n    by simp\n  show ?thesis\n    by (auto simp: natceiling_def real_of_nat_def[symmetric] split: split_nat ceiling_split)\nqed\n\nlemma natfloor_zero [simp]: \"natfloor 0 = 0\"\n  by linarith\n\nlemma natfloor_one [simp]: \"natfloor 1 = 1\"\n  by linarith\n\nlemma natfloor_numeral_eq [simp]: \"natfloor (numeral n) = numeral n\"\n  by (unfold natfloor_def, simp)\n\nlemma natfloor_real_of_nat [simp]: \"natfloor(real n) = n\"\n  by linarith\n\nlemma real_natfloor_le: \"0 <= x ==> real(natfloor x) <= x\"\n  by linarith\n\nlemma natfloor_neg: \"x <= 0 ==> natfloor x = 0\"\n  by linarith\n\nlemma natfloor_mono: \"x <= y ==> natfloor x <= natfloor y\"\n  by linarith\n\nlemma le_natfloor: \"real x <= a ==> x <= natfloor a\"\n  by linarith\n\nlemma natfloor_less_iff: \"0 \\<le> x \\<Longrightarrow> natfloor x < n \\<longleftrightarrow> x < real n\"\n  by linarith\n\nlemma less_natfloor: \"0 \\<le> x \\<Longrightarrow> x < real (n :: nat) \\<Longrightarrow> natfloor x < n\"\n  by linarith\n\nlemma le_natfloor_eq: \"0 <= x ==> (a <= natfloor x) = (real a <= x)\"\n  by linarith\n\nlemma le_natfloor_eq_numeral [simp]:\n    \"0 \\<le> x \\<Longrightarrow> (numeral n \\<le> natfloor x) = (numeral n \\<le> x)\"\n  by (subst le_natfloor_eq, assumption) simp\n\nlemma le_natfloor_eq_one [simp]: \"(1 \\<le> natfloor x) = (1 \\<le> x)\"\n  by linarith\n\nlemma natfloor_eq: \"real n \\<le> x \\<Longrightarrow> x < real n + 1 \\<Longrightarrow> natfloor x = n\"\n  by linarith\n\nlemma real_natfloor_add_one_gt: \"x < real (natfloor x) + 1\"\n  by linarith\n\nlemma real_natfloor_gt_diff_one: \"x - 1 < real(natfloor x)\"\n  by linarith\n\nlemma ge_natfloor_plus_one_imp_gt: \"natfloor z + 1 <= n ==> z < real n\"\n  by linarith\n\nlemma natfloor_add [simp]: \"0 <= x ==> natfloor (x + real a) = natfloor x + a\"\n  by linarith\n\nlemma natfloor_add_numeral [simp]:\n    \"0 <= x \\<Longrightarrow> natfloor (x + numeral n) = natfloor x + numeral n\"\n  by (simp add: natfloor_add [symmetric])\n\nlemma natfloor_add_one: \"0 <= x ==> natfloor(x + 1) = natfloor x + 1\"\n  by linarith\n\nlemma natfloor_subtract [simp]:\n    \"natfloor(x - real a) = natfloor x - a\"\n  by linarith\n\nlemma natfloor_div_nat: \"natfloor (x / real y) = natfloor x div y\"\nproof cases\n  assume \"0 \\<le> x\" then show ?thesis\n    unfolding natfloor_def real_of_int_of_nat_eq[symmetric]\n    by (subst floor_divide_real_eq_div) (simp_all add: nat_div_distrib)\nqed (simp add: divide_nonpos_nonneg natfloor_neg)\n\nlemma natfloor_div_numeral[simp]:\n  \"natfloor (numeral x / numeral y) = numeral x div numeral y\"\n  using natfloor_div_nat[of \"numeral x\" \"numeral y\"] by simp\n\nlemma le_mult_natfloor:\n  shows \"natfloor a * natfloor b \\<le> natfloor (a * b)\"\n  by (cases \"0 <= a & 0 <= b\")\n    (auto simp add: le_natfloor_eq mult_mono' real_natfloor_le natfloor_neg)\n\nlemma natceiling_zero [simp]: \"natceiling 0 = 0\"\n  by linarith\n\nlemma natceiling_one [simp]: \"natceiling 1 = 1\"\n  by linarith\n\nlemma zero_le_natceiling [simp]: \"0 <= natceiling x\"\n  by linarith\n\nlemma natceiling_numeral_eq [simp]: \"natceiling (numeral n) = numeral n\"\n  by (simp add: natceiling_def)\n\nlemma natceiling_real_of_nat [simp]: \"natceiling(real n) = n\"\n  by linarith\n\nlemma real_natceiling_ge: \"x <= real(natceiling x)\"\n  by linarith\n\nlemma natceiling_neg: \"x <= 0 ==> natceiling x = 0\"\n  by linarith\n\nlemma natceiling_mono: \"x <= y ==> natceiling x <= natceiling y\"\n  by linarith\n\nlemma natceiling_le: \"x <= real a ==> natceiling x <= a\"\n  by linarith\n\nlemma natceiling_le_eq: \"(natceiling x <= a) = (x <= real a)\"\n  by linarith\n\nlemma natceiling_le_eq_numeral [simp]:\n    \"(natceiling x <= numeral n) = (x <= numeral n)\"\n  by (simp add: natceiling_le_eq)\n\nlemma natceiling_le_eq_one: \"(natceiling x <= 1) = (x <= 1)\"\n  by linarith\n\nlemma natceiling_eq: \"real n < x ==> x <= real n + 1 ==> natceiling x = n + 1\"\n  by linarith\n\nlemma natceiling_add [simp]: \"0 <= x ==> natceiling (x + real a) = natceiling x + a\"\n  by linarith\n\nlemma natceiling_add_numeral [simp]:\n    \"0 <= x ==> natceiling (x + numeral n) = natceiling x + numeral n\"\n  by (simp add: natceiling_add [symmetric])\n\nlemma natceiling_add_one: \"0 <= x ==> natceiling(x + 1) = natceiling x + 1\"\n  by linarith\n\nlemma natceiling_subtract [simp]: \"natceiling(x - real a) = natceiling x - a\"\n  by linarith\n\nlemma Rats_no_top_le: \"\\<exists> q \\<in> \\<rat>. (x :: real) \\<le> q\"\n  by (auto intro!: bexI[of _ \"of_nat (natceiling x)\"]) (metis real_natceiling_ge real_of_nat_def)\n\nlemma Rats_no_bot_less: \"\\<exists> q \\<in> \\<rat>. q < (x :: real)\"\n  apply (auto intro!: bexI[of _ \"of_int (floor x - 1)\"])\n  apply (rule less_le_trans[OF _ of_int_floor_le])\n  apply simp\n  done\n\nsubsection {* Exponentiation with floor *}\n\nlemma floor_power:\n  assumes \"x = real (floor x)\"\n  shows \"floor (x ^ n) = floor x ^ n\"\nproof -\n  have *: \"x ^ n = real (floor x ^ n)\"\n    using assms by (induct n arbitrary: x) simp_all\n  show ?thesis unfolding real_of_int_inject[symmetric]\n    unfolding * floor_real_of_int ..\nqed\n\nlemma natfloor_power:\n  assumes \"x = real (natfloor x)\"\n  shows \"natfloor (x ^ n) = natfloor x ^ n\"\nproof -\n  from assms have \"0 \\<le> floor x\" by auto\n  note assms[unfolded natfloor_def real_nat_eq_real[OF `0 \\<le> floor x`]]\n  from floor_power[OF this]\n  show ?thesis unfolding natfloor_def nat_power_eq[OF `0 \\<le> floor x`, symmetric]\n    by simp\nqed\n\nlemma floor_numeral_power[simp]:\n  \"\\<lfloor>numeral x ^ n\\<rfloor> = numeral x ^ n\"\n  by (metis floor_of_int of_int_numeral of_int_power)\n\nlemma ceiling_numeral_power[simp]:\n  \"\\<lceil>numeral x ^ n\\<rceil> = numeral x ^ n\"\n  by (metis ceiling_of_int of_int_numeral of_int_power)\n\n\nsubsection {* Implementation of rational real numbers *}\n\ntext {* Formal constructor *}\n\ndefinition Ratreal :: \"rat \\<Rightarrow> real\" where\n  [code_abbrev, simp]: \"Ratreal = of_rat\"\n\ncode_datatype Ratreal\n\n\ntext {* Numerals *}\n\nlemma [code_abbrev]:\n  \"(of_rat (of_int a) :: real) = of_int a\"\n  by simp\n\nlemma [code_abbrev]:\n  \"(of_rat 0 :: real) = 0\"\n  by simp\n\nlemma [code_abbrev]:\n  \"(of_rat 1 :: real) = 1\"\n  by simp\n\nlemma [code_abbrev]:\n  \"(of_rat (- 1) :: real) = - 1\"\n  by simp\n\nlemma [code_abbrev]:\n  \"(of_rat (numeral k) :: real) = numeral k\"\n  by simp\n\nlemma [code_abbrev]:\n  \"(of_rat (- numeral k) :: real) = - numeral k\"\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  \"(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\n\ntext {* Operations *}\n\nlemma zero_real_code [code]:\n  \"0 = Ratreal 0\"\nby simp\n\nlemma one_real_code [code]:\n  \"1 = Ratreal 1\"\nby simp\n\ninstantiation real :: equal\nbegin\n\ndefinition \"HOL.equal (x\\<Colon>real) y \\<longleftrightarrow> x - y = 0\"\n\ninstance proof\nqed (simp add: equal_real_def)\n\nlemma real_equal_code [code]:\n  \"HOL.equal (Ratreal x) (Ratreal y) \\<longleftrightarrow> HOL.equal x y\"\n  by (simp add: equal_real_def equal)\n\nlemma [code nbe]:\n  \"HOL.equal (x::real) x \\<longleftrightarrow> True\"\n  by (rule equal_refl)\n\nend\n\nlemma real_less_eq_code [code]: \"Ratreal x \\<le> Ratreal y \\<longleftrightarrow> x \\<le> y\"\n  by (simp add: of_rat_less_eq)\n\nlemma real_less_code [code]: \"Ratreal x < Ratreal y \\<longleftrightarrow> x < y\"\n  by (simp add: of_rat_less)\n\nlemma real_plus_code [code]: \"Ratreal x + Ratreal y = Ratreal (x + y)\"\n  by (simp add: of_rat_add)\n\nlemma real_times_code [code]: \"Ratreal x * Ratreal y = Ratreal (x * y)\"\n  by (simp add: of_rat_mult)\n\nlemma real_uminus_code [code]: \"- Ratreal x = Ratreal (- x)\"\n  by (simp add: of_rat_minus)\n\nlemma real_minus_code [code]: \"Ratreal x - Ratreal y = Ratreal (x - y)\"\n  by (simp add: of_rat_diff)\n\nlemma real_inverse_code [code]: \"inverse (Ratreal x) = Ratreal (inverse x)\"\n  by (simp add: of_rat_inverse)\n \nlemma real_divide_code [code]: \"Ratreal x / Ratreal y = Ratreal (x / y)\"\n  by (simp add: of_rat_divide)\n\nlemma real_floor_code [code]: \"floor (Ratreal x) = floor x\"\n  by (metis Ratreal_def floor_le_iff floor_unique le_floor_iff of_int_floor_le of_rat_of_int_eq real_less_eq_code)\n\n\ntext {* Quickcheck *}\n\ndefinition (in term_syntax)\n  valterm_ratreal :: \"rat \\<times> (unit \\<Rightarrow> Code_Evaluation.term) \\<Rightarrow> real \\<times> (unit \\<Rightarrow> Code_Evaluation.term)\" where\n  [code_unfold]: \"valterm_ratreal k = Code_Evaluation.valtermify Ratreal {\\<cdot>} k\"\n\nnotation fcomp (infixl \"\\<circ>>\" 60)\nnotation scomp (infixl \"\\<circ>\\<rightarrow>\" 60)\n\ninstantiation real :: random\nbegin\n\ndefinition\n  \"Quickcheck_Random.random i = Quickcheck_Random.random i \\<circ>\\<rightarrow> (\\<lambda>r. Pair (valterm_ratreal r))\"\n\ninstance ..\n\nend\n\nno_notation fcomp (infixl \"\\<circ>>\" 60)\nno_notation scomp (infixl \"\\<circ>\\<rightarrow>\" 60)\n\ninstantiation real :: exhaustive\nbegin\n\ndefinition\n  \"exhaustive_real f d = Quickcheck_Exhaustive.exhaustive (%r. f (Ratreal r)) d\"\n\ninstance ..\n\nend\n\ninstantiation real :: full_exhaustive\nbegin\n\ndefinition\n  \"full_exhaustive_real f d = Quickcheck_Exhaustive.full_exhaustive (%r. f (valterm_ratreal r)) d\"\n\ninstance ..\n\nend\n\ninstantiation real :: narrowing\nbegin\n\ndefinition\n  \"narrowing = Quickcheck_Narrowing.apply (Quickcheck_Narrowing.cons Ratreal) narrowing\"\n\ninstance ..\n\nend\n\n\nsubsection {* Setup for Nitpick *}\n\ndeclaration {*\n  Nitpick_HOL.register_frac_type @{type_name real}\n   [(@{const_name zero_real_inst.zero_real}, @{const_name Nitpick.zero_frac}),\n    (@{const_name one_real_inst.one_real}, @{const_name Nitpick.one_frac}),\n    (@{const_name plus_real_inst.plus_real}, @{const_name Nitpick.plus_frac}),\n    (@{const_name times_real_inst.times_real}, @{const_name Nitpick.times_frac}),\n    (@{const_name uminus_real_inst.uminus_real}, @{const_name Nitpick.uminus_frac}),\n    (@{const_name inverse_real_inst.inverse_real}, @{const_name Nitpick.inverse_frac}),\n    (@{const_name ord_real_inst.less_real}, @{const_name Nitpick.less_frac}),\n    (@{const_name ord_real_inst.less_eq_real}, @{const_name Nitpick.less_eq_frac})]\n*}\n\nlemmas [nitpick_unfold] = inverse_real_inst.inverse_real one_real_inst.one_real\n    ord_real_inst.less_real ord_real_inst.less_eq_real plus_real_inst.plus_real\n    times_real_inst.times_real uminus_real_inst.uminus_real\n    zero_real_inst.zero_real\n\n\nsubsection {* Setup for SMT *}\n\nML_file \"Tools/SMT/smt_real.ML\"\nML_file \"Tools/SMT/z3_real.ML\"\n\nlemma [z3_rule]:\n  \"0 + (x::real) = x\"\n  \"x + 0 = x\"\n  \"0 * x = 0\"\n  \"1 * x = x\"\n  \"x + y = y + x\"\n  by 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/Real.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117855317474, "lm_q2_score": 0.8519528038477824, "lm_q1q2_score": 0.7043194236577788}}
{"text": "theory Ex008\nimports Main \nbegin \n\n\n\nlemma \"\\<not>(A \\<and> B) \\<longrightarrow> (\\<not>A \\<or> \\<not>B)\"\nproof -\n{\n  assume \"\\<not>(A \\<and> B)\"\n  {\n    assume \"\\<not>(\\<not>A \\<or> \\<not>B)\"\n    {\n      assume \"\\<not>A\"\n      hence \"\\<not>A \\<or> \\<not>B\" by (rule disjI1)\n      with \\<open>\\<not>(\\<not>A \\<or> \\<not>B)\\<close> have  False by contradiction\n    }\n    hence \"\\<not>\\<not>A\" by (rule notI)\n    hence A by (rule notnotD)\n    {\n      assume \"\\<not>B\"\n      hence \"\\<not>A \\<or> \\<not>B\" by (rule disjI2)\n      with  \\<open>\\<not>(\\<not>A \\<or> \\<not>B)\\<close> have False by contradiction\n    }\n    hence \"\\<not>\\<not>B\" by (rule notI)\n    hence B by (rule notnotD)\n    with \\<open>A\\<close> have \"A \\<and> B\" by (rule conjI)\n    with \\<open>\\<not>(A \\<and> B)\\<close> have False by contradiction\n  }\n  hence \" \\<not>\\<not> (\\<not> A \\<or> \\<not> B)\" by (rule notI)\n  hence  \"\\<not> A \\<or> \\<not> B\" by (rule notnotD)\n}\nthus ?thesis by (rule impI)\nqed\n\n\n(*prettified*)\n \n\nlemma \"\\<not>(A \\<and> B) \\<longrightarrow> (\\<not>A \\<or> \\<not>B)\"\nproof -\n{\n  assume \"\\<not>(A \\<and> B)\"\n  {\n    assume \"\\<not>(\\<not>A \\<or> \\<not>B)\"\n    {\n      assume \"\\<not>A\"\n      hence \"\\<not>A \\<or> \\<not>B\" ..\n      with \\<open>\\<not>(\\<not>A \\<or> \\<not>B)\\<close> have  False ..\n    }\n    hence \"\\<not>\\<not>A\" ..\n    hence A by (rule notnotD)\n    {\n      assume \"\\<not>B\"\n      hence \"\\<not>A \\<or> \\<not>B\" ..\n      with  \\<open>\\<not>(\\<not>A \\<or> \\<not>B)\\<close> have False ..\n    }\n    hence \"\\<not>\\<not>B\" ..\n    hence B by (rule notnotD)\n    with \\<open>A\\<close> have \"A \\<and> B\" ..\n    with \\<open>\\<not>(A \\<and> B)\\<close> have False ..\n  }\n  hence \" \\<not>\\<not> (\\<not> A \\<or> \\<not> B)\"..\n  hence  \"\\<not> A \\<or> \\<not> B\" by (rule notnotD)\n}\nthus ?thesis ..\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/Ex008.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898305367525, "lm_q2_score": 0.7772998560157665, "lm_q1q2_score": 0.7042257648279664}}
{"text": "(*<*)\n(*\n   Title:  Theory ListExtras.thy\n   Author: Maria Spichkova <maria.spichkova at rmit.edu.au>, 2014\n*)\n(*>*)\nheader {* Auxiliary Theory ListExtras.thy*}\n\ntheory ListExtras \nimports Main\nbegin\n\ndefinition\n  disjoint :: \"'a list \\<Rightarrow> 'a list \\<Rightarrow> bool\"\nwhere\n \"disjoint x y \\<equiv>  (set x) \\<inter> (set y) = {}\"\n\nprimrec\n  mem ::  \"'a \\<Rightarrow> 'a list \\<Rightarrow> bool\" (infixr \"mem\" 65)\nwhere\n  \"x mem [] = False\" |\n  \"x mem (y # l) = ((x = y) \\<or> (x mem l))\"\n\ndefinition\n  memS ::  \"'a \\<Rightarrow> 'a list \\<Rightarrow> bool\"\nwhere\n \"memS x l  \\<equiv>  x \\<in> (set l)\"\n\nlemma mem_memS_eq:  \"x mem l \\<equiv> memS x l\"\nproof (induct l)\n  case Nil\n  from this show ?case by (simp add: memS_def)\nnext\n    fix a la case (Cons a la)\n    from Cons show ?case by (simp add: memS_def)\n qed\n\nlemma mem_set_1:\nassumes \"a mem l\"\nshows \"a \\<in> set l\"\nusing assms by (metis memS_def mem_memS_eq)\n\nlemma mem_set_2:\nassumes \"a \\<in> set l\"\nshows \"a mem l\"\nusing assms by (metis (full_types) memS_def mem_memS_eq)\n\nlemma set_inter_mem: \nassumes \"x mem l1\"\n       and \"x mem l2\"\nshows \"set l1 \\<inter> set l2 \\<noteq> {}\"\nusing assms  by (metis IntI empty_iff mem_set_1)\n\nlemma mem_notdisjoint: \nassumes \"x mem l1\"\n       and \"x mem l2\"\nshows \"\\<not> disjoint l1 l2\"\nusing assms by (metis disjoint_def set_inter_mem)\n\nlemma mem_notdisjoint2:\nassumes h1:\"disjoint (schedule A) (schedule B)\"\n       and h2:\"x mem schedule A\"\nshows \"\\<not> x mem schedule B\"\nproof - \n  { assume \" x mem schedule B\"\n     from h2 and this have \"\\<not>  disjoint (schedule A) (schedule B)\" \n       by (simp add: mem_notdisjoint)\n    from h1 and this have \"False\" by simp\n   } then have \"\\<not> x mem schedule B\" by blast\n  then show ?thesis by simp\nqed\n\n\n\nlemma list_length_hint1: \nassumes \"l \\<noteq> []\"\nshows    \"0 < length l\" \nusing assms by simp\n\nlemma list_length_hint1a: \nassumes \"l \\<noteq> []\"\nshows    \"0 < length l\" \nusing assms by simp\n\nlemma list_length_hint2: \nassumes \"length x  = Suc 0\"\nshows    \"[hd x] = x\"\nusing assms  \nby (metis Zero_neq_Suc list.sel(1) length_Suc_conv neq_Nil_conv)\n\nlemma list_length_hint2a: \nassumes \"length l = Suc 0\"\nshows    \"tl l = []\"\nusing assms\nby (metis list_length_hint2 list.sel(3)) \n\nlemma list_length_hint3: \nassumes \"length l = Suc 0\"\nshows    \"l \\<noteq> []\"\nusing assms\nby (metis Zero_neq_Suc list.size(3))\n\nlemma list_length_hint4: \nassumes \"length x \\<le> Suc 0\"\n       and \"x \\<noteq> []\"\nshows \"length x = Suc 0\"\nusing assms\nby (metis le_0_eq le_Suc_eq length_greater_0_conv less_numeral_extra(3))\n\nlemma length_nonempty: \nassumes \"x \\<noteq> []\" \nshows    \"Suc 0 \\<le> length x\"\nusing assms\nby (metis length_greater_0_conv less_eq_Suc_le) \n\nlemma last_nth_length: \nassumes \"x \\<noteq> []\"\nshows    \"x ! ((length x) - Suc 0) = last x\"\nusing assms\nby (metis One_nat_def last_conv_nth)\n\nlemma list_nth_append0:\nassumes \"i < length x\"\nshows    \"x ! i = (x @ z) ! i\"\nusing assms\nby (metis nth_append) \n\n\n\n\n\nlemma list_nth_append4:\nassumes \"i < Suc (length x + length y)\"\n       and \"\\<not> i - Suc (length x) < Suc (length y)\" \nshows \"False\"\nusing assms  by arith\n\nlemma list_nth_append5:\nassumes \"i - length x < Suc (length y)\" \n       and \"\\<not> i - Suc (length x) < Suc (length y)\"\nshows \"\\<not>  i < Suc (length x + length y)\"\nusing assms  by arith\n\nlemma list_nth_append6:\nassumes \"\\<not> i - length x < Suc (length y)\"\n       and \"\\<not> i - Suc (length x) < Suc (length y)\"\nshows \"\\<not> i < Suc (length x + length y)\"\nusing assms by arith\n\nlemma list_nth_append6a:\nassumes \"i < Suc (length x + length y)\"\n       and \"\\<not> i - length x < Suc (length y)\"\nshows \"False\"\nusing assms by arith \n\nlemma list_nth_append7:\nassumes \"i - length x < Suc (length y)\"\n       and \"i - Suc (length x) < Suc (length y)\"\nshows    \"i < Suc (Suc (length x + length y))\"\nusing assms  by arith\n\nlemma list_nth_append8:\nassumes \"\\<not> i < Suc (length x + length y)\"\n       and \"i < Suc (Suc (length x + length y))\"\nshows     \"i = Suc (length x + length y)\"\nusing assms  by arith\n\nlemma list_nth_append9:\nassumes \"i - Suc (length x) < Suc (length y)\"\nshows    \"i < Suc (Suc (length x + length y))\"\nusing assms by arith\n  \nlemma list_nth_append10:\nassumes \"\\<not> i < Suc (length x)\"\n       and \"\\<not> i - Suc (length x) < Suc (length y)\"\nshows    \"\\<not> i < Suc (Suc (length x + length y))\"\nusing assms by arith\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/FocusStreamsCaseStudies/ListExtras.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8740772482857831, "lm_q2_score": 0.8056321936479701, "lm_q1q2_score": 0.7041847709542569}}
{"text": "(* Authors: Dongchen Jiang and Tobias Nipkow *)\n\ntheory Marriage\nimports Main \nbegin\n\ntheorem marriage_necessary:\n  fixes A :: \"'a \\<Rightarrow> 'b set\" and I :: \"'a set\"\n  assumes \"finite I\" and \"\\<forall> i\\<in>I. finite (A i)\"\n  and \"\\<exists>R. (\\<forall>i\\<in>I. R i \\<in> A i) \\<and> inj_on R I\" (is \"\\<exists>R. ?R R A & ?inj R A\")\n  shows \"\\<forall>J\\<subseteq>I. card J \\<le> card (\\<Union>(A ` J))\"\nproof clarify\n  fix J\n  assume \"J \\<subseteq> I\"\n  show \"card J \\<le> card (\\<Union>(A ` J))\"\n  proof-\n    from assms(3) obtain R where \"?R R A\" and \"?inj R A\" by auto\n    have \"inj_on R J\" by(rule subset_inj_on[OF \\<open>?inj R A\\<close> \\<open>J\\<subseteq>I\\<close>])\n    moreover have \"(R ` J) \\<subseteq> (\\<Union>(A ` J))\" using \\<open>J\\<subseteq>I\\<close> \\<open>?R R A\\<close> by auto\n    moreover have \"finite (\\<Union>(A ` J))\" using \\<open>J\\<subseteq>I\\<close> assms\n      by (metis finite_UN_I finite_subset subsetD)\n    ultimately show ?thesis by (rule card_inj_on_le)\n  qed\nqed\n\ntext\\<open>The proof by Halmos and Vaughan:\\<close>\ntheorem marriage_HV:\n  fixes A :: \"'a \\<Rightarrow> 'b set\" and I :: \"'a set\"\n  assumes \"finite I\" and \"\\<forall> i\\<in>I. finite (A i)\"\n  and \"\\<forall>J\\<subseteq>I. card J \\<le> card (\\<Union>(A ` J))\" (is \"?M A I\")\n  shows \"\\<exists>R. (\\<forall>i\\<in>I. R i \\<in> A i) \\<and> inj_on R I\"\n       (is \"?SDR A I\" is \"\\<exists>R. ?R R A I & ?inj R A I\")\nproof-\n  { fix I\n    have \"finite I \\<Longrightarrow> \\<forall>i\\<in>I. finite (A i) \\<Longrightarrow> ?M A I \\<Longrightarrow> ?SDR A I\"\n    proof(induct arbitrary: A rule: finite_psubset_induct)\n      case (psubset I)\n      show ?case\n      proof (cases)\n        assume \"I={}\" then show ?thesis by simp\n      next \n        assume \"I \\<noteq> {}\"\n        have \"\\<forall>i\\<in>I. A i \\<noteq> {}\"\n        proof (rule ccontr)\n          assume  \"\\<not> (\\<forall>i\\<in>I. A i\\<noteq>{})\"\n          then obtain i where \"i\\<in>I\" \"A i = {}\" by blast\n          hence \"{i}\\<subseteq> I\" by auto\n          from mp[OF spec[OF psubset.prems(2)] this] \\<open>A i={}\\<close>\n          show False by simp\n        qed\n        show ?thesis\n        proof cases\n          assume case1: \"\\<forall>K\\<subset>I. K\\<noteq>{} \\<longrightarrow> card (\\<Union>(A ` K)) \\<ge> card K + 1\"\n          show ?thesis\n          proof-\n            from \\<open>I\\<noteq>{}\\<close> obtain n where \"n\\<in>I\" by auto\n            with \\<open>\\<forall>i\\<in>I. A i \\<noteq> {}\\<close> have \"A n \\<noteq> {}\" by auto\n            then obtain x where \"x \\<in> A n\" by auto\n            let ?A' = \"\\<lambda>i. A i - {x}\" let ?I' = \"I - {n}\"\n            from \\<open>n\\<in>I\\<close> have \"?I' \\<subset> I\"\n              by (metis DiffD2 Diff_subset insertI1 psubset_eq)\n            have fin': \"\\<forall>i\\<in>?I'. finite (?A' i)\" using psubset.prems(1) by auto\n            have \"?M ?A' ?I'\"\n            proof clarify\n              fix J\n              assume \"J \\<subseteq> ?I'\"\n              hence \"J \\<subset> I\" by (metis \\<open>I - {n} \\<subset> I\\<close> subset_psubset_trans)\n              show \"card J \\<le> card (\\<Union>i\\<in>J. A i - {x})\"\n              proof cases\n                assume \"J = {}\" thus ?thesis by auto\n              next\n                assume \"J \\<noteq> {}\"\n                hence \"card J + 1 \\<le> card(\\<Union>(A ` J))\" using case1 \\<open>J\\<subset>I\\<close> by blast\n                moreover\n                have \"card(\\<Union>(A ` J)) - 1 \\<le> card (\\<Union>i\\<in>J. A i - {x})\" (is \"?l \\<le> ?r\")\n                proof-\n                  have \"finite J\" using \\<open>J \\<subset> I\\<close> psubset(1)\n                    by (metis psubset_imp_subset finite_subset)\n                  hence 1: \"finite(\\<Union>(A ` J))\"\n                    using \\<open>\\<forall>i\\<in>I. finite(A i)\\<close> \\<open>J\\<subset>I\\<close> by force\n                  have \"?l = card(\\<Union>(A ` J)) - card{x}\" by simp\n                  also have \"\\<dots> \\<le> card(\\<Union>(A ` J) - {x})\" using 1\n                    by (metis diff_card_le_card_Diff finite.intros)\n                  also have \"\\<Union>(A ` J) - {x} = (\\<Union>i\\<in>J. A i - {x})\" by blast\n                  finally show ?thesis .\n                qed\n                ultimately show ?thesis by arith\n              qed\n            qed\n            from psubset(2)[OF \\<open>?I'\\<subset>I\\<close> fin' \\<open>?M ?A' ?I'\\<close>]\n            obtain R' where \"?R R' ?A' ?I'\" \"?inj R' ?A' ?I'\" by auto\n            let ?Rx = \"R'(n := x)\"\n            have \"?R ?Rx A I\" using \\<open>x\\<in>A n\\<close> \\<open>?R R' ?A' ?I'\\<close> by force\n            have \"\\<forall>i\\<in>?I'. ?Rx i \\<noteq> x\" using \\<open>?R R' ?A' ?I'\\<close> by auto\n            hence \"?inj ?Rx A I\" using \\<open>?inj R' ?A' ?I'\\<close>\n              by(auto simp: inj_on_def)\n            with \\<open>?R ?Rx A I\\<close> show ?thesis by auto\n          qed\n        next\n          assume \"\\<not> (\\<forall>K\\<subset>I. K\\<noteq>{} \\<longrightarrow> card (\\<Union>(A ` K)) \\<ge> card K + 1)\"\n          then obtain K where\n            \"K\\<subset>I\" \"K\\<noteq>{}\" and c1: \"\\<not>(card (\\<Union>(A ` K)) \\<ge> card K + 1)\" by auto\n          with psubset.prems(2) have \"card (\\<Union>(A ` K)) \\<ge> card K\" by auto\n          with c1 have case2: \"card (\\<Union>(A ` K))= card K\" by auto\n          from \\<open>K\\<subset>I\\<close> \\<open>finite I\\<close> have \"finite K\" by (auto intro:finite_subset)\n          from psubset.prems \\<open>K\\<subset>I\\<close>\n          have \"\\<forall>i\\<in>K. finite (A i)\" \"\\<forall>J\\<subseteq>K. card J \\<le> card(\\<Union>(A ` J))\" by auto\n          from psubset(2)[OF \\<open>K\\<subset>I\\<close> this]\n          obtain R1 where \"?R R1 A K\" \"?inj R1 A K\" by auto\n          let ?AK = \"\\<lambda>i. A i - \\<Union>(A ` K)\" let ?IK = \"I - K\"\n          from \\<open>K\\<noteq>{}\\<close> \\<open>K\\<subset>I\\<close> have \"?IK\\<subset>I\" by auto\n          have \"\\<forall>i\\<in>?IK. finite (?AK i)\" using psubset.prems(1) by auto\n          have \"?M ?AK ?IK\"\n          proof clarify\n            fix J assume \"J \\<subseteq> ?IK\"\n            with \\<open>finite I\\<close> have \"finite J\" by(auto intro: finite_subset)\n            show \"card J \\<le> card (\\<Union> (?AK ` J))\"\n            proof-\n              from \\<open>J\\<subseteq>?IK\\<close> have \"J \\<inter> K = {}\" by auto\n              have \"card J = card(J\\<union>K) - card K\"\n                using \\<open>finite J\\<close> \\<open>finite K\\<close> \\<open>J\\<inter>K={}\\<close>\n                by (auto simp: card_Un_disjoint)\n              also have \"card(J\\<union>K) \\<le> card(\\<Union>(A ` (J\\<union>K)))\"\n              proof -\n                from \\<open>J\\<subseteq>?IK\\<close> \\<open>K\\<subset>I\\<close> have \"J \\<union> K \\<subseteq> I\" by auto\n                with psubset.prems(2) show ?thesis by blast\n              qed\n              also have \"\\<dots> - card K = card(\\<Union> (?AK ` J) \\<union> \\<Union>(A ` K)) - card K\"\n              proof-\n                have \"\\<Union>(A ` (J\\<union>K)) = \\<Union> (?AK ` J) \\<union> \\<Union>(A ` K)\"\n                  using \\<open>J\\<subseteq>?IK\\<close> by auto\n                thus ?thesis by simp\n              qed\n              also have \"\\<dots> = card (\\<Union> (?AK ` J)) + card(\\<Union>(A ` K)) - card K\"\n              proof-\n                have \"finite (\\<Union> (?AK ` J))\" using \\<open>finite J\\<close> \\<open>J\\<subseteq>?IK\\<close> psubset(3)\n                  by(blast intro: finite_UN_I finite_Diff)\n                moreover have \"finite (\\<Union>(A ` K))\"\n                  using \\<open>finite K\\<close> \\<open>\\<forall>i\\<in>K. finite (A i)\\<close> by auto\n                moreover have \"\\<Union> (?AK ` J) \\<inter> \\<Union>(A ` K) = {}\" by auto\n                ultimately show ?thesis\n                  by (simp add: card_Un_disjoint del:Un_Diff_cancel2)\n              qed\n              also have \"\\<dots> = card (\\<Union> (?AK ` J))\" using case2 by simp\n              finally show ?thesis by simp\n            qed\n          qed\n          from psubset(2)[OF \\<open>?IK\\<subset>I\\<close> \\<open>\\<forall>i\\<in>?IK. finite (?AK i)\\<close> \\<open>\\<forall>J\\<subseteq>?IK. card J \\<le> card (\\<Union>i\\<in>J. A i - \\<Union> (A ` K))\\<close>]\n          obtain R2 where \"?R R2 ?AK ?IK\" \"?inj R2 ?AK ?IK\" by auto\n          let ?R12 = \"\\<lambda>i. if i\\<in>K then R1 i else R2 i\"\n          have \"\\<forall>i\\<in>I. ?R12 i \\<in> A i\" using \\<open>?R R1 A K\\<close>\\<open>?R R2 ?AK ?IK\\<close> by auto\n          moreover have \"\\<forall>i\\<in>I. \\<forall>j\\<in>I. i\\<noteq>j\\<longrightarrow>?R12 i \\<noteq> ?R12 j\"\n          proof clarify\n            fix i j assume \"i\\<in>I\" \"j\\<in>I\" \"i\\<noteq>j\" \"?R12 i = ?R12 j\"\n            show False\n            proof-\n              { assume \"i\\<in>K \\<and> j\\<in>K \\<or> i\\<notin>K\\<and>j\\<notin>K\"\n                with \\<open>?inj R1 A K\\<close> \\<open>?inj R2 ?AK ?IK\\<close> \\<open>?R12 i=?R12 j\\<close> \\<open>i\\<noteq>j\\<close> \\<open>i\\<in>I\\<close> \\<open>j\\<in>I\\<close>\n                have ?thesis by (fastforce simp: inj_on_def)\n              } moreover\n              { assume \"i\\<in>K \\<and> j\\<notin>K \\<or> i\\<notin>K \\<and> j\\<in>K\"\n                with \\<open>?R R1 A K\\<close> \\<open>?R R2 ?AK ?IK\\<close> \\<open>?R12 i=?R12 j\\<close> \\<open>j\\<in>I\\<close> \\<open>i\\<in>I\\<close>\n                have ?thesis by auto (metis Diff_iff)\n              } ultimately show ?thesis by blast\n            qed\n          qed\n          ultimately show ?thesis unfolding inj_on_def by fast\n        qed\n      qed\n    qed\n  }\n  with assms \\<open>?M A I\\<close> show ?thesis by auto\nqed\n\n\ntext\\<open>The proof by Rado:\\<close>\ntheorem marriage_Rado:\n  fixes A :: \"'a \\<Rightarrow> 'b set\" and I :: \"'a set\"\n  assumes \"finite I\" and \"\\<forall> i\\<in>I. finite (A i)\"\n  and \"\\<forall>J\\<subseteq>I. card J \\<le> card (\\<Union>(A ` J))\" (is \"?M A\")\n  shows \"\\<exists>R. (\\<forall>i\\<in>I. R i \\<in> A i) \\<and> inj_on R I\"\n       (is \"?SDR A\" is \"\\<exists>R. ?R R A & ?inj R A\")\nproof-\n  { have \"\\<forall>i\\<in>I. finite (A i) \\<Longrightarrow> ?M A \\<Longrightarrow> ?SDR A\"\n    proof(induct n == \"\\<Sum>i\\<in>I. card(A i) - 1\" arbitrary: A)\n      case 0\n      have \"\\<forall>i\\<in>I.\\<exists>a. A(i) = {a}\"\n      proof (rule ccontr)\n        assume  \"\\<not> (\\<forall>i\\<in>I.\\<exists>a. A i = {a})\"\n        then obtain i where i: \"i:I\" \"\\<forall>a. A i \\<noteq> {a}\" by blast\n        hence \"{i}\\<subseteq> I\" by auto\n        from \"0\"(1-2) mp[OF spec[OF \"0.prems\"(2)] \\<open>{i}\\<subseteq>I\\<close>] \\<open>finite I\\<close> i\n        show False by (auto simp: card_le_Suc_iff)\n      qed\n      then obtain R where R: \"\\<forall>i\\<in>I. A i = {R i}\" by metis\n      then have \"\\<forall>i\\<in>I. R i \\<in> A i\" by blast\n      moreover have \"inj_on R I\"\n      proof (auto simp: inj_on_def)\n        fix x y assume \"x \\<in> I\" \"y \\<in> I\" \"R x = R y\"\n        with R spec[OF \"0.prems\"(2), of \"{x,y}\"] show \"x=y\"\n          by (simp add:le_Suc_eq card_insert_if split: if_splits)\n      qed\n      ultimately show ?case by blast\n    next\n      case (Suc n)\n      from Suc.hyps(2)[symmetric, THEN sum_SucD]\n      obtain i where i: \"i:I\" \"2 \\<le> card(A i)\" by auto\n      then obtain x1 x2 where \"x1 : A i\" \"x2 : A i\" \"x1 \\<noteq> x2\"\n        using Suc(3) by (fastforce simp: card_le_Suc_iff eval_nat_numeral)\n      let \"?Ai x\" = \"A i - {x}\" let \"?A x\" = \"A(i:=?Ai x)\"\n      let \"?U J\" = \"\\<Union>(A ` J)\" let \"?Ui J x\" = \"?U J \\<union> ?Ai x\"\n      have n1: \"n = (\\<Sum>j\\<in>I. card (?A x1 j) - 1)\"\n        using Suc.hyps(2) Suc.prems(1) i \\<open>finite I\\<close> \\<open>x1:A i\\<close>\n        by (auto simp: sum.remove card_Diff_singleton)\n      have n2: \"n = (\\<Sum>j\\<in>I. card (?A x2 j) - 1)\"\n        using Suc.hyps(2) Suc.prems(1) i \\<open>finite I\\<close> \\<open>x2:A i\\<close>\n        by (auto simp: sum.remove card_Diff_singleton)\n      have finx1: \"\\<forall>j\\<in>I. finite (?A x1 j)\" by (simp add: Suc(3))\n      have finx2: \"\\<forall>j\\<in>I. finite (?A x2 j)\" by (simp add: Suc(3))\n      { fix x assume \"\\<not> ?M (A(i:= ?Ai x))\"\n        with Suc.prems(2) obtain J\n          where J: \"J \\<subseteq> I\" \"card J > card(\\<Union>((A(i:= ?Ai x) ` J)))\"\n          by (auto simp add:not_less_eq_eq Suc_le_eq)\n        note fJi = finite_Diff[OF finite_subset[OF \\<open>J\\<subseteq>I\\<close> \\<open>finite I\\<close>], of \"{i}\"]\n        have fU: \"finite(?U (J-{i}))\" using \\<open>J\\<subseteq>I\\<close>\n          by (metis Diff_iff Suc(3) finite_UN[OF fJi] subsetD)\n        have \"i \\<in> J\" using J Suc.prems(2)\n          by (simp_all add: UNION_fun_upd not_le[symmetric] del: fun_upd_apply split: if_splits)\n        hence \"card(J-{i}) \\<ge> card(?Ui (J-{i}) x)\"\n          using fJi J by(simp add: UNION_fun_upd del: fun_upd_apply)\n        hence \"\\<exists>J\\<subseteq>I. i \\<notin> J \\<and> card(J) \\<ge> card(?Ui J x) \\<and> finite(?U J)\"\n          by (metis DiffD2 J(1) fU \\<open>i \\<in> J\\<close> insertI1 subset_insertI2 subset_insert_iff)\n      } note lem = this\n      have \"?M (?A x1) \\<or> ?M (?A x2)\" \\<comment> \\<open>Rado's Lemma\\<close>\n      proof(rule ccontr)\n        assume \"\\<not> (?M (?A x1) \\<or> ?M (?A x2))\"\n        with lem obtain J1 J2 where\n          J1: \"J1\\<subseteq>I\" \"i\\<notin>J1\" \"card J1 \\<ge> card(?Ui J1 x1)\" \"finite(?U J1)\" and\n          J2: \"J2\\<subseteq>I\" \"i\\<notin>J2\" \"card J2 \\<ge> card(?Ui J2 x2)\" \"finite(?U J2)\"\n          by metis\n        note fin1 = finite_subset[OF \\<open>J1\\<subseteq>I\\<close> assms(1)]\n        note fin2 = finite_subset[OF \\<open>J2\\<subseteq>I\\<close> assms(1)]\n        have finUi1: \"finite(?Ui J1 x1)\" using Suc(3) by(blast intro: J1(4) i(1))\n        have finUi2: \"finite(?Ui J2 x2)\" using Suc(3) by(blast intro: J2(4) i(1))\n        have \"card J1 + card J2 + 1 = card(J1 \\<union> J2) + 1 + card(J1 \\<inter> J2)\"\n          by simp (metis card_Un_Int fin1 fin2)\n        also have \"card(J1 \\<union> J2) + 1 = card(insert i (J1 \\<union> J2))\"\n          using \\<open>i\\<notin>J1\\<close> \\<open>i\\<notin>J2\\<close> fin1 fin2 by simp\n        also have \"\\<dots> \\<le> card (\\<Union> (A ` insert i (J1 \\<union> J2)))\" (is \"_ \\<le> card ?M\")\n          by (metis J1(1) J2(1) Suc(4) Un_least i(1) insert_subset)\n        also have \"?M = ?Ui J1 x1 \\<union> ?Ui J2 x2\" using \\<open>x1\\<noteq>x2\\<close> by auto\n        also have \"card(J1 \\<inter> J2) \\<le> card(\\<Union>(A ` (J1 \\<inter> J2)))\"\n          by (metis J2(1) Suc(4) le_infI2)\n        also have \"\\<dots> \\<le> card(?U J1 \\<inter> ?U J2)\" by(blast intro: card_mono J1(4))\n        also have \"\\<dots> \\<le> card(?Ui J1 x1 \\<inter> ?Ui J2 x2)\"\n          using Suc(3) \\<open>i\\<in>I\\<close> by(blast intro: card_mono J1(4))\n        finally show False using J1(3) J2(3)\n          by(auto simp add: card_Un_Int[symmetric, OF finUi1 finUi2])\n      qed\n      thus ?case using Suc.hyps(1)[OF n1 finx1] Suc.hyps(1)[OF n2 finx2]\n        by (metis DiffD1 fun_upd_def)\n    qed\n  } with assms \\<open>?M A\\<close> 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/Marriage/Marriage.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8740772450055544, "lm_q2_score": 0.8056321959813274, "lm_q1q2_score": 0.7041847703511335}}
{"text": "(*  Title:       EpiMonoIso\n    Author:      Eugene W. Stark <stark@cs.stonybrook.edu>, 2016\n    Maintainer:  Eugene W. Stark <stark@cs.stonybrook.edu>\n*)\n\nchapter EpiMonoIso\n\ntheory EpiMonoIso\nimports Category\nbegin\n\n  text\\<open>\n    This theory defines and develops properties of epimorphisms, monomorphisms,\n    isomorphisms, sections, and retractions.\n\\<close>\n\n  context category\n  begin\n\n     definition epi\n     where \"epi f = (arr f \\<and> inj_on (\\<lambda>g. g \\<cdot> f) {g. seq g f})\"\n\n     definition mono\n     where \"mono f = (arr f \\<and> inj_on (\\<lambda>g. f \\<cdot> g) {g. seq f g})\"\n\n     lemma epiI [intro]:\n     assumes \"arr f\" and \"\\<And>g g'. seq g f \\<and> seq g' f \\<and> g \\<cdot> f = g' \\<cdot> f \\<Longrightarrow> g = g'\"\n     shows \"epi f\"\n       using assms epi_def inj_on_def by blast\n\n     lemma epi_implies_arr:\n     assumes \"epi f\"\n     shows \"arr f\"\n       using assms epi_def by auto\n\n     lemma epiE [elim]:\n     assumes \"epi f\"\n     and \"seq g f\" and \"seq g' f\" and \"g \\<cdot> f = g' \\<cdot> f\"\n     shows \"g = g'\"\n       using assms unfolding epi_def inj_on_def by blast\n       \n     lemma monoI [intro]:\n     assumes \"arr g\" and \"\\<And>f f'. seq g f \\<and> seq g f' \\<and> g \\<cdot> f = g \\<cdot> f' \\<Longrightarrow> f = f'\"\n     shows \"mono g\"\n       using assms mono_def inj_on_def by blast\n\n     lemma mono_implies_arr:\n     assumes \"mono f\"\n     shows \"arr f\"\n       using assms mono_def by auto\n       \n     lemma monoE [elim]:\n     assumes \"mono g\"\n     and \"seq g f\" and \"seq g f'\" and \"g \\<cdot> f = g \\<cdot> f'\"\n     shows \"f' = f\"\n       using assms unfolding mono_def inj_on_def by blast\n\n     definition inverse_arrows\n     where \"inverse_arrows f g \\<equiv> ide (g \\<cdot> f) \\<and> ide (f \\<cdot> g)\"\n\n     lemma inverse_arrowsI [intro]:\n     assumes \"ide (g \\<cdot> f)\" and \"ide (f \\<cdot> g)\"\n     shows \"inverse_arrows f g\"\n       using assms inverse_arrows_def by blast\n\n     lemma inverse_arrowsE [elim]:\n     assumes \"inverse_arrows f g\"\n     and \"\\<lbrakk> ide (g \\<cdot> f); ide (f \\<cdot> g) \\<rbrakk> \\<Longrightarrow> T\"\n     shows \"T\"\n       using assms inverse_arrows_def by blast\n\n     lemma inverse_arrows_sym:\n       shows \"inverse_arrows f g \\<longleftrightarrow> inverse_arrows g f\"\n       using inverse_arrows_def by auto\n\n     lemma ide_self_inverse:\n     assumes \"ide a\"\n     shows \"inverse_arrows a a\"\n       using assms by auto\n\n     lemma inverse_arrow_unique:\n     assumes \"inverse_arrows f g\" and \"inverse_arrows f g'\"\n     shows \"g = g'\"\n       using assms apply (elim inverse_arrowsE)\n       by (metis comp_cod_arr ide_compE comp_assoc seqE)\n\n     lemma inverse_arrows_compose:\n     assumes \"seq g f\" and \"inverse_arrows f f'\" and \"inverse_arrows g g'\"\n     shows \"inverse_arrows (g \\<cdot> f) (f' \\<cdot> g')\"\n       using assms apply (elim inverse_arrowsE, intro inverse_arrowsI)\n        apply (metis seqE comp_arr_dom ide_compE comp_assoc)\n       by (metis seqE comp_arr_dom ide_compE comp_assoc)\n\n     definition \"section\"\n     where \"section f \\<equiv> \\<exists>g. ide (g \\<cdot> f)\"\n\n     lemma sectionI [intro]:\n     assumes \"ide (g \\<cdot> f)\"\n     shows \"section f\"\n       using assms section_def by auto\n\n     lemma sectionE [elim]:\n     assumes \"section f\"\n     obtains g where \"ide (g \\<cdot> f)\"\n       using assms section_def by blast\n\n     definition retraction\n     where \"retraction g \\<equiv> \\<exists>f. ide (g \\<cdot> f)\"\n\n     lemma retractionI [intro]:\n     assumes \"ide (g \\<cdot> f)\"\n     shows \"retraction g\"\n       using assms retraction_def by auto\n\n     lemma retractionE [elim]:\n     assumes \"retraction g\"\n     obtains f where \"ide (g \\<cdot> f)\"\n       using assms retraction_def by blast\n       \n     lemma section_is_mono:\n     assumes \"section g\"\n     shows \"mono g\"\n     proof\n       show \"arr g\" using assms section_def by blast\n       from assms obtain h where h: \"ide (h \\<cdot> g)\" by blast\n       have hg: \"seq h g\" using h by auto\n       fix f f'\n       assume \"seq g f \\<and> seq g f' \\<and> g \\<cdot> f = g \\<cdot> f'\"\n       thus \"f = f'\"\n         using hg h ide_compE seqE comp_assoc comp_cod_arr by metis\n     qed\n\n     lemma retraction_is_epi:\n     assumes \"retraction g\"\n     shows \"epi g\"\n     proof\n       show \"arr g\" using assms retraction_def by blast\n       from assms obtain f where f: \"ide (g \\<cdot> f)\" by blast\n       have gf: \"seq g f\" using f by auto\n       fix h h'\n       assume \"seq h g \\<and> seq h' g \\<and> h \\<cdot> g = h' \\<cdot> g\"\n       thus \"h = h'\"\n         using gf f ide_compE seqE comp_assoc comp_arr_dom by metis\n     qed\n\n     lemma section_retraction_compose:\n     assumes \"ide (e \\<cdot> m)\" and \"ide (e' \\<cdot> m')\" and \"seq m' m\"\n     shows \"ide ((e \\<cdot> e') \\<cdot> (m' \\<cdot> m))\"\n       using assms seqI seqE ide_compE comp_assoc comp_arr_dom by metis\n\n     \n\n     lemma retractions_compose [intro]:\n     assumes \"retraction e\" and \"retraction e'\" and \"seq e' e\"\n     shows \"retraction (e' \\<cdot> e)\"\n     proof -\n       from assms(1-2) obtain m m'\n       where *: \"ide (e \\<cdot> m) \\<and> ide (e' \\<cdot> m')\"\n         using retraction_def by auto\n       hence \"seq m m'\"\n         using assms(3) by (metis seqE seqI ide_compE)\n       with * show ?thesis\n         using section_retraction_compose retractionI by blast\n     qed\n       \n     lemma monos_compose [intro]:\n     assumes \"mono m\" and \"mono m'\" and \"seq m' m\"\n     shows \"mono (m' \\<cdot> m)\"\n     proof -\n       have \"inj_on (\\<lambda>f. (m' \\<cdot> m) \\<cdot> f) {f. seq (m' \\<cdot> m) f}\"\n         unfolding inj_on_def\n         using assms\n         by (metis CollectD seqE monoE comp_assoc)\n       thus ?thesis using assms(3) mono_def by force\n     qed           \n\n     lemma epis_compose [intro]:\n     assumes \"epi e\" and \"epi e'\" and \"seq e' e\"\n     shows \"epi (e' \\<cdot> e)\"\n     proof -\n       have \"inj_on (\\<lambda>g. g \\<cdot> (e' \\<cdot> e)) {g. seq g (e' \\<cdot> e)}\"\n         unfolding inj_on_def\n         using assms by (metis CollectD epiE match_2 comp_assoc)\n       thus ?thesis using assms(3) epi_def by force\n     qed           \n\n     definition iso\n     where \"iso f \\<equiv> \\<exists>g. inverse_arrows f g\"\n\n     lemma isoI [intro]:\n     assumes \"inverse_arrows f g\"\n     shows \"iso f\"\n       using assms iso_def by auto\n\n     lemma isoE [elim]:\n     assumes \"iso f\"\n     obtains g where \"inverse_arrows f g\"\n       using assms iso_def by blast\n\n     lemma ide_is_iso [simp]:\n     assumes \"ide a\"\n     shows \"iso a\"\n       using assms ide_self_inverse by auto\n\n     lemma iso_is_arr:\n     assumes \"iso f\"\n     shows \"arr f\"\n       using assms by blast\n\n     lemma iso_is_section:\n     assumes \"iso f\"\n     shows \"section f\"\n       using assms inverse_arrows_def by blast\n\n     lemma iso_is_retraction:\n     assumes \"iso f\"\n     shows \"retraction f\"\n       using assms inverse_arrows_def by blast\n\n    lemma iso_iff_mono_and_retraction:\n    shows \"iso f \\<longleftrightarrow> mono f \\<and> retraction f\"\n    proof\n      show \"iso f \\<Longrightarrow> mono f \\<and> retraction f\"\n        by (simp add: iso_is_retraction iso_is_section section_is_mono)\n      show \"mono f \\<and> retraction f \\<Longrightarrow> iso f\"\n      proof -\n        assume f: \"mono f \\<and> retraction f\"\n        from f obtain g where g: \"ide (f \\<cdot> g)\" by blast\n        have \"inverse_arrows f g\"\n          using f g comp_arr_dom comp_cod_arr comp_assoc inverse_arrowsI\n          by (metis ide_char' ide_compE monoE mono_implies_arr)\n        thus \"iso f\" by auto\n      qed\n    qed\n\n    lemma iso_iff_section_and_epi:\n    shows \"iso f \\<longleftrightarrow> section f \\<and> epi f\"\n    proof\n      show \"iso f \\<Longrightarrow> section f \\<and> epi f\"\n        by (simp add: iso_is_retraction iso_is_section retraction_is_epi)\n      show \"section f \\<and> epi f \\<Longrightarrow> iso f\"\n      proof -\n        assume f: \"section f \\<and> epi f\"\n        from f obtain g where g: \"ide (g \\<cdot> f)\" by blast\n        have \"inverse_arrows f g\"\n          using f g comp_arr_dom comp_cod_arr epi_implies_arr\n                comp_assoc ide_compE inverse_arrowsI epiE ide_char'\n          by metis\n        thus \"iso f\" by auto\n      qed\n    qed\n\n    lemma iso_iff_section_and_retraction:\n    shows \"iso f \\<longleftrightarrow> section f \\<and> retraction f\"\n      using iso_is_retraction iso_is_section iso_iff_mono_and_retraction section_is_mono\n      by auto\n\n    lemma isos_compose [intro]:\n    assumes \"iso f\" and \"iso f'\" and \"seq f' f\"\n    shows \"iso (f' \\<cdot> f)\"\n    proof -\n      from assms(1) obtain g where g: \"inverse_arrows f g\" by blast\n      from assms(2) obtain g' where g': \"inverse_arrows f' g'\" by blast\n      have \"inverse_arrows (f' \\<cdot> f) (g \\<cdot> g')\"\n        using assms g g inverse_arrowsI inverse_arrowsE section_retraction_compose\n        by (simp add: g' inverse_arrows_compose)\n      thus ?thesis using iso_def by auto\n    qed\n\n    definition isomorphic\n    where \"isomorphic a a' = (\\<exists>f. \\<guillemotleft>f : a \\<rightarrow> a'\\<guillemotright> \\<and> iso f)\"\n\n    lemma isomorphicI [intro]:\n    assumes \"iso f\"\n    shows \"isomorphic (dom f) (cod f)\"\n      using assms isomorphic_def iso_is_arr by blast\n\n    lemma isomorphicE [elim]:\n    assumes \"isomorphic a a'\"\n    obtains f where \"\\<guillemotleft>f : a \\<rightarrow> a'\\<guillemotright> \\<and> iso f\"\n      using assms isomorphic_def by meson\n\n    definition inv\n    where \"inv f = (SOME g. inverse_arrows f g)\"\n\n    lemma inv_is_inverse:\n    assumes \"iso f\"\n    shows \"inverse_arrows f (inv f)\"\n      using assms inv_def someI [of \"inverse_arrows f\"] by auto\n\n    lemma iso_inv_iso:\n    assumes \"iso f\"\n    shows \"iso (inv f)\"\n      using assms inv_is_inverse inverse_arrows_sym by blast\n\n    lemma inverse_unique:\n    assumes \"inverse_arrows f g\"\n    shows \"inv f = g\"\n      using assms inv_is_inverse inverse_arrow_unique isoI by auto\n\n    lemma inv_ide [simp]:\n    assumes \"ide a\"\n    shows \"inv a = a\"\n      using assms by (simp add: inverse_arrowsI inverse_unique)\n\n    lemma inv_inv [simp]:\n    assumes \"iso f\"\n    shows \"inv (inv f) = f\"\n      using assms inverse_arrows_sym inverse_unique by blast\n\n    lemma comp_arr_inv:\n    assumes \"inverse_arrows f g\"\n    shows \"f \\<cdot> g = dom g\"\n      using assms by auto\n\n    lemma comp_inv_arr:\n    assumes \"inverse_arrows f g\"\n    shows \"g \\<cdot> f = dom f\"\n      using assms by auto\n\n    lemma comp_arr_inv':\n    assumes \"iso f\"\n    shows \"f \\<cdot> inv f = cod f\"\n      using assms inv_is_inverse by blast\n\n    lemma comp_inv_arr':\n    assumes \"iso f\"\n    shows \"inv f \\<cdot> f = dom f\"\n      using assms inv_is_inverse by blast\n\n    lemma inv_in_hom [simp]:\n    assumes \"iso f\" and \"\\<guillemotleft>f : a \\<rightarrow> b\\<guillemotright>\"\n    shows \"\\<guillemotleft>inv f : b \\<rightarrow> a\\<guillemotright>\"\n      using assms inv_is_inverse seqE inverse_arrowsE\n      by (metis ide_compE in_homE in_homI)\n\n    lemma arr_inv [simp]:\n    assumes \"iso f\"\n    shows \"arr (inv f)\"\n      using assms inv_in_hom by blast\n\n    lemma dom_inv [simp]:\n    assumes \"iso f\"\n    shows \"dom (inv f) = cod f\"\n      using assms inv_in_hom by blast\n\n    lemma cod_inv [simp]:\n    assumes \"iso f\"\n    shows \"cod (inv f) = dom f\"\n      using assms inv_in_hom by blast\n\n    lemma inv_comp:\n    assumes \"iso f\" and \"iso g\" and \"seq g f\"\n    shows \"inv (g \\<cdot> f) = inv f \\<cdot> inv g\"\n      using assms inv_is_inverse inverse_unique inverse_arrows_compose inverse_arrows_def\n      by meson\n\n    lemma isomorphic_reflexive:\n    assumes \"ide f\"\n    shows \"isomorphic f f\"\n      unfolding isomorphic_def\n      using assms ide_is_iso ide_in_hom by blast\n\n    lemma isomorphic_symmetric:\n    assumes \"isomorphic f g\"\n    shows \"isomorphic g f\"\n      using assms iso_inv_iso inv_in_hom by blast\n\n    lemma isomorphic_transitive [trans]:\n    assumes \"isomorphic f g\" and \"isomorphic g h\"\n    shows \"isomorphic f h\"\n      using assms isomorphic_def isos_compose by auto\n\n    text \\<open>\n      A section or retraction of an isomorphism is in fact an inverse.\n\\<close>\n\n    lemma section_retraction_of_iso:\n    assumes \"iso f\"\n    shows \"ide (g \\<cdot> f) \\<Longrightarrow> inverse_arrows f g\"\n    and \"ide (f \\<cdot> g) \\<Longrightarrow> inverse_arrows f g\"\n    proof -\n      show \"ide (g \\<cdot> f) \\<Longrightarrow> inverse_arrows f g\"\n        using assms\n        by (metis comp_inv_arr' epiE ide_compE inv_is_inverse iso_iff_section_and_epi)\n      show \"ide (f \\<cdot> g) \\<Longrightarrow> inverse_arrows f g\"\n        using assms\n        by (metis ide_compE comp_arr_inv' inv_is_inverse iso_iff_mono_and_retraction monoE)\n    qed\n\n    text \\<open>\n      A situation that occurs frequently is that we have a commuting triangle,\n      but we need the triangle obtained by inverting one side that is an isomorphism.\n      The following fact streamlines this derivation.\n\\<close>\n\n    lemma invert_side_of_triangle:\n    assumes \"arr h\" and \"f \\<cdot> g = h\"\n    shows \"iso f \\<Longrightarrow> seq (inv f) h \\<and> g = inv f \\<cdot> h\"\n    and \"iso g \\<Longrightarrow> seq h (inv g) \\<and> f = h \\<cdot> inv g\"\n    proof -\n      show \"iso f \\<Longrightarrow> seq (inv f) h \\<and> g = inv f \\<cdot> h\"\n        by (metis assms seqE inv_is_inverse comp_cod_arr comp_inv_arr comp_assoc)\n      show \"iso g \\<Longrightarrow> seq h (inv g) \\<and> f = h \\<cdot> inv g\"\n        by (metis assms seqE inv_is_inverse comp_arr_dom comp_arr_inv dom_inv comp_assoc)\n    qed\n\n    text \\<open>\n      A similar situation is where we have a commuting square and we want to\n      invert two opposite sides.\n\\<close>\n\n    lemma invert_opposite_sides_of_square:\n    assumes \"seq f g\" and \"f \\<cdot> g = h \\<cdot> k\"\n    shows \"\\<lbrakk> iso f; iso k \\<rbrakk> \\<Longrightarrow> seq g (inv k) \\<and> seq (inv f) h \\<and> g \\<cdot> inv k = inv f \\<cdot> h\"\n      by (metis assms invert_side_of_triangle comp_assoc)\n\n  end\n\nend\n\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/Category3/EpiMonoIso.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772417253256, "lm_q2_score": 0.8056321959813274, "lm_q1q2_score": 0.7041847677084756}}
{"text": "(*\n  File: Set.thy\n  Author: Bohua Zhan\n\n  Basic axioms and constructions in set theory. The initial choices made in\n  set theory largely follow that in Isabelle/ZF.\n*)\n\ntheory Set\n  imports Logic_FOL\nbegin\n\nsection \\<open>Axiom of extension\\<close>\n\naxiomatization where\n  extension: \"\\<forall>z. z \\<in> x \\<longleftrightarrow> z \\<in> y \\<Longrightarrow> x = y\"\nsetup {* add_backward_prfstep_cond @{thm extension} [with_score 500] *}\n\nsection \\<open>Axiom of empty set\\<close>\n\naxiomatization Empty_set :: \"i\"  (\"\\<emptyset>\") where\n  empty_set [resolve]: \"x \\<notin> \\<emptyset>\"\n\nlemma nonempty_mem [backward]: \"A \\<noteq> \\<emptyset> \\<Longrightarrow> \\<exists>x. x \\<in> A\" by auto2\n\nsection \\<open>Axiom schema of specification\\<close>\n\naxiomatization Collect :: \"[i, i \\<Rightarrow> o] \\<Rightarrow> i\" where\n  collect [rewrite]: \"x \\<in> Collect(A,P) \\<longleftrightarrow> (x \\<in> A \\<and> P(x))\"\n\nsyntax\n  \"_Collect\" :: \"[pttrn, i, o] \\<Rightarrow> i\"  (\"(1{_ \\<in> _ ./ _})\")\ntranslations\n  \"{x\\<in>A. P}\" \\<rightleftharpoons> \"CONST Collect(A, \\<lambda>x. P)\"\n\nsection \\<open>Axiom of pairing\\<close>\n\naxiomatization Upair :: \"[i, i] \\<Rightarrow> i\" where\n  upair [rewrite]: \"x \\<in> Upair(y,z) \\<longleftrightarrow> (x = y \\<or> x = z)\"\n\nlemma Upair_nonempty [resolve]: \"Upair(a,b) \\<noteq> \\<emptyset>\"\n@proof @have \"a \\<in> Upair(a,b)\" @qed\n\nsection \\<open>Axiom of union\\<close>\n\naxiomatization Union :: \"i \\<Rightarrow> i\"  (\"\\<Union>_\" [90] 90) where\n  union [rewrite]: \"x \\<in> \\<Union>C \\<longleftrightarrow> (\\<exists>A\\<in>C. x\\<in>A)\"\n\nsection \\<open>Subset, and standard properties\\<close>\n\ndefinition subset :: \"i \\<Rightarrow> i \\<Rightarrow> o\"  (infixl \"\\<subseteq>\" 50) where [rewrite]:\n  \"A \\<subseteq> B \\<longleftrightarrow> (\\<forall>x\\<in>A. x\\<in>B)\"\n\nlemma subset_refl [resolve]: \"A \\<subseteq> A\" by auto2\nlemma subsetD [forward]: \"A \\<subseteq> B \\<Longrightarrow> c \\<in> A \\<Longrightarrow> c \\<in> B\" by auto2\nlemma subsetI [forward]: \"\\<forall>x\\<in>A. x \\<in> B \\<Longrightarrow> A \\<subseteq> B\" by auto2\nsetup {* add_backward_prfstep_cond @{thm subsetI} [with_score 500] *}\nsetup {* del_prfstep_thm @{thm subset_def} *}\n\nlemma subset_trans [forward,backward1,backward2]:\n  \"A \\<subseteq> B \\<Longrightarrow> B \\<subseteq> C \\<Longrightarrow> A \\<subseteq> C\" by auto2\nlemma extension_subset [forward,backward1,backward2]:\n  \"A \\<subseteq> B \\<Longrightarrow> B \\<subseteq> A \\<Longrightarrow> A = B\" by auto2\nlemma subset_nonempty [forward,backward2]:\n  \"A \\<subseteq> B \\<Longrightarrow> A \\<noteq> \\<emptyset> \\<Longrightarrow> B \\<noteq> \\<emptyset>\" by auto2\n\nsection \\<open>Axiom of power set\\<close>\n\naxiomatization Pow :: \"i \\<Rightarrow> i\" where\n  power [rewrite]: \"x \\<in> Pow(S) \\<longleftrightarrow> x \\<subseteq> S\"\n\nlemma PowI [typing2]: \"x \\<subseteq> S \\<Longrightarrow> x \\<in> Pow(S)\" by auto2\n\n(* Cantor's theorem *)\nlemma cantor: \"\\<exists>S \\<in> Pow(A). \\<forall>x\\<in>A. b(x) \\<noteq> S\"\n@proof\n  @let \"S = {x \\<in> A. x \\<notin> b(x)}\"\n  @have \"\\<forall>x\\<in>A. b(x) \\<noteq> S\" @with @case \"x \\<in> b(x)\" @end\n@qed\n\nsection \\<open>General intersection\\<close>\n\ndefinition Inter :: \"i \\<Rightarrow> i\"  (\"\\<Inter>_\" [90] 90) where [rewrite]:\n  \"\\<Inter>(A) = { x \\<in> \\<Union>(A). \\<forall>y\\<in>A. x\\<in>y}\"\nsetup {* register_wellform_data (\"\\<Inter>(A)\", [\"A \\<noteq> \\<emptyset>\"]) *}\nsetup {* add_prfstep_check_req (\"\\<Inter>(A)\", \"A \\<noteq> \\<emptyset>\") *}\n  \n(* Inter really makes sense only if A \\<noteq> \\<emptyset>*)\nlemma Inter_iff [rewrite]:\n  \"A \\<noteq> \\<emptyset> \\<Longrightarrow> x \\<in> \\<Inter>(A) \\<longleftrightarrow> (\\<forall>y\\<in>A. x\\<in>y)\" by auto2\nsetup {* del_prfstep_thm @{thm Inter_def} *}\n\nsection \\<open>Binary union and intersection, subtraction on sets\\<close>\n\ndefinition Un :: \"i \\<Rightarrow> i \\<Rightarrow> i\"  (infixl \"\\<union>\" 65) where [rewrite]:\n  \"A \\<union> B = \\<Union>(Upair(A,B))\"\n\nlemma Un_iff: \"c \\<in> A \\<union> B \\<longleftrightarrow> (c \\<in> A \\<or> c \\<in> B)\" by auto2\nsetup {* add_forward_prfstep_cond (equiv_forward_th @{thm Un_iff}) [with_score 500] *}\nsetup {* add_backward_prfstep (equiv_backward_th @{thm Un_iff}) *}\nsetup {* del_prfstep_thm @{thm Un_def} *}\n\nlemma UnD1 [forward]: \"c \\<in> A \\<union> B \\<Longrightarrow> c \\<notin> A \\<Longrightarrow> c \\<in> B\" by auto2\nlemma UnD2 [forward]: \"c \\<in> A \\<union> B \\<Longrightarrow> c \\<notin> B \\<Longrightarrow> c \\<in> A\" by auto2\nlemma UnI1 [typing2]: \"c \\<in> A \\<Longrightarrow> c \\<in> A \\<union> B\" by auto2\nlemma UnI2 [typing2]: \"c \\<in> B \\<Longrightarrow> c \\<in> A \\<union> B\" by auto2\nlemma Un_empty [forward]: \"A \\<union> B = \\<emptyset> \\<Longrightarrow> A = \\<emptyset>\" by auto2\nlemma Un_commute: \"A \\<union> B = B \\<union> A\" by auto2\nlemma Un_assoc: \"(A \\<union> B) \\<union> C = A \\<union> (B \\<union> C)\" by auto2\nlemma Un_least [backward]: \"A \\<subseteq> D \\<Longrightarrow> B \\<subseteq> D \\<Longrightarrow> A \\<union> B \\<subseteq> D\" by auto2\n\ndefinition Int :: \"i \\<Rightarrow> i \\<Rightarrow> i\"  (infixl \"\\<inter>\" 70) where [rewrite]:\n  \"A \\<inter> B = \\<Inter>(Upair(A,B))\"\n\nlemma Int_iff [rewrite]: \"c \\<in> A \\<inter> B \\<longleftrightarrow> (c \\<in> A \\<and> c \\<in> B)\" by auto2\nsetup {* del_prfstep_thm @{thm Int_def} *}\nlemma Int_commute: \"A \\<inter> B = B \\<inter> A\" by auto2\nlemma Int_assoc: \"(A \\<inter> B) \\<inter> C = A \\<inter> (B \\<inter> C)\" by auto2\nlemma Int_id [rewrite]: \"A \\<inter> A = A\" by auto2\nlemma Int_lower1 [resolve]: \"A \\<inter> B \\<subseteq> A\" by auto2\nlemma Int_lower2 [resolve]: \"A \\<inter> B \\<subseteq> B\" by auto2\nlemma Int_subset1 [rewrite]: \"A \\<subseteq> B \\<Longrightarrow> A \\<inter> B = A\" by auto2\nlemma Int_subset2 [rewrite]: \"A \\<subseteq> B \\<Longrightarrow> B \\<inter> A = A\" by auto2\n\ndefinition Diff :: \"i \\<Rightarrow> i \\<Rightarrow> i\"  (infixl \"\\<midarrow>\" 65) where Diff_def[rewrite]:\n  \"A \\<midarrow> B = {x \\<in> A. x \\<notin> B}\"\nlemma Diff_iff [rewrite]: \"c \\<in> A \\<midarrow> B \\<longleftrightarrow> (c \\<in> A \\<and> c \\<notin> B)\" by auto2\nsetup {* del_prfstep_thm @{thm Diff_def} *}\n\nlemma diff_subset [resolve]: \"A \\<midarrow> B \\<subseteq> A\" by auto2\n\nlemma diff_empty [forward]: \"A \\<midarrow> B = \\<emptyset> \\<Longrightarrow> A \\<subseteq> B\"\n@proof\n  @have \"\\<forall>x\\<in>A. x \\<in> B\" @with\n    @contradiction @have \"x \\<in> A \\<midarrow> B\"\n  @end\n@qed\n\nlemma diff_double [rewrite]: \"B \\<subseteq> A \\<Longrightarrow> A \\<midarrow> (A \\<midarrow> B) = B\" by auto2\n\nlemma compl_eq: \"E\\<midarrow>A = E\\<midarrow>B \\<Longrightarrow> A \\<subseteq> E \\<Longrightarrow> B \\<subseteq> E \\<Longrightarrow> A = B\"\n@proof\n  @have \"\\<forall>x. x \\<in> A \\<longleftrightarrow> x \\<in> B\" @with\n    @case \"x \\<in> A\" @with @have \"x \\<notin> E\\<midarrow>A\" @end\n    @case \"x \\<in> B\" @with @have \"x \\<notin> E\\<midarrow>B\" @end\n  @end \n@qed\nsetup {* add_forward_prfstep_cond @{thm compl_eq}\n  [with_cond \"?A \\<noteq> ?B\", with_filt (order_filter \"A\" \"B\")] *}\n\nlemma inter_compl1 [rewrite]: \"(X \\<midarrow> A) \\<inter> A = \\<emptyset>\" by auto2\nlemma inter_compl2 [rewrite]: \"A \\<inter> (X \\<midarrow> A) = \\<emptyset>\" by auto2\nlemma union_compl1 [rewrite]: \"A \\<subseteq> X \\<Longrightarrow> A \\<union> (X \\<midarrow> A) = X\" by auto2\nlemma union_compl2 [rewrite]: \"A \\<subseteq> X \\<Longrightarrow> (X \\<midarrow> A) \\<union> A = X\" by auto2\nlemma Int_empty1 [forward]: \"A \\<inter> B = \\<emptyset> \\<Longrightarrow> x \\<in> A \\<Longrightarrow> x \\<notin> B\"\n  @proof @contradiction @have \"x \\<in> A \\<inter> B\" @qed\nlemma Int_empty2 [forward]: \"A \\<inter> B = \\<emptyset> \\<Longrightarrow> x \\<in> B \\<Longrightarrow> x \\<notin> A\" by auto2\nlemma Int_diff_union [rewrite]: \"(X \\<inter> Y) \\<union> (X \\<midarrow> Y) = X\" by auto2\nlemma Int_diff_Int [rewrite]: \"(X \\<inter> Y) \\<inter> (X \\<midarrow> Y) = \\<emptyset>\" by auto2\n\nsection \\<open>Strict subsets\\<close>\n\ndefinition strict_subset :: \"i \\<Rightarrow> i \\<Rightarrow> o\" (infixl \"\\<subset>\" 50) where [rewrite]:\n  \"A \\<subset> B \\<longleftrightarrow> (A \\<subseteq> B \\<and> A \\<noteq> B)\"\n\nsection \\<open>Cons, notation for finite sets\\<close>\n\ndefinition cons :: \"[i, i] \\<Rightarrow> i\" where [rewrite]:\n  \"cons(a, A) = Upair(a,a) \\<union> A\"\n\nnonterminal \"is\"\nsyntax\n  \"\" :: \"i \\<Rightarrow> is\"  (\"_\")\n  \"_Enum\" :: \"[i, is] \\<Rightarrow> is\"  (\"_,/ _\")\n  \"_Finset\" :: \"is \\<Rightarrow> i\"  (\"{(_)}\")\ntranslations\n  \"{x, xs}\" == \"CONST cons(x, {xs})\"\n  \"{x}\" == \"CONST cons(x, \\<emptyset>)\"\n\nlemma cons_iff: \"a \\<in> cons(b, A) \\<longleftrightarrow> (a = b \\<or> a \\<in> A)\" by auto2\nsetup {* add_rewrite_rule_cond @{thm cons_iff}\n  [with_cond \"?a \\<noteq> ?b\", with_cond \"?A \\<noteq> \\<emptyset>\"] *}\nlemma mem_singleton [rewrite]: \"a \\<in> {b} \\<longleftrightarrow> a = b\" by auto2\nlemma not_mem_singleton: \"a \\<noteq> b \\<Longrightarrow> a \\<notin> {b}\" by auto2\nsetup {* add_forward_prfstep_cond @{thm not_mem_singleton} [with_term \"{?b}\"] *}\ntheorem mem_cons [typing2]: \"a \\<in> cons(a,S)\" by auto2\nsetup {* del_prfstep_thm @{thm cons_def} *}\n\ntheorem subset_cons: \"S \\<subseteq> cons(a,S)\" by auto2\nsetup {* add_forward_prfstep_cond @{thm subset_cons}\n  [with_term \"cons(?a,?S)\", with_cond \"?S \\<noteq> \\<emptyset>\", with_cond \"?S \\<noteq> {?b}\"] *}\n\ntheorem mem_cons2 [typing2]: \"b \\<in> {a,b}\" by auto2\n\nlemma Union_singleton [rewrite]: \"\\<Union>{a} = a\" by auto2\nlemma singleton_subset [backward]: \"x \\<in> X \\<Longrightarrow> {x} \\<subseteq> X\" by auto2\nlemma diff_singleton_not_mem [rewrite]: \"a \\<notin> X \\<Longrightarrow> X \\<midarrow> {a} = X\" by auto2\nlemma singleton_eq_iff [forward]: \"{a} = {b} \\<Longrightarrow> a = b\" by auto2\nlemma cons_nonempty [resolve]: \"cons(a, b) \\<noteq> \\<emptyset>\" by auto2\nlemma sub_singleton_empty [forward]: \"X \\<noteq> \\<emptyset> \\<Longrightarrow> X \\<subseteq> {a} \\<Longrightarrow> X = {a}\" by auto2\nlemma cons_mem [rewrite]: \"a \\<in> X \\<Longrightarrow> cons(a,X) = X\" by auto2\nlemma cons_minus [rewrite]: \"a \\<notin> S \\<Longrightarrow> cons(a,S) \\<midarrow> {a} = S\" by auto2\n\ndefinition succ :: \"i \\<Rightarrow> i\" where [rewrite]:\n  \"succ(i) = cons(i, i)\"\n\nsection \\<open>Axiom of replacement\\<close>\n\naxiomatization Replace :: \"[i, i \\<Rightarrow> i \\<Rightarrow> o] \\<Rightarrow> i\" where replacement [rewrite]:\n  \"\\<forall>x\\<in>A. \\<forall>y z. P(x,y) \\<and> P(x,z) \\<longrightarrow> y = z \\<Longrightarrow> b \\<in> Replace(A,P) \\<longleftrightarrow> (\\<exists>x\\<in>A. P(x,b))\"\nsetup {* add_prfstep_check_req (\"Replace(A,P)\", \"\\<forall>x\\<in>A. \\<forall>y z. P(x,y) \\<and> P(x,z) \\<longrightarrow> y = z\") *}\n\nsection \\<open>Definite description\\<close>\n\ndefinition The :: \"(i \\<Rightarrow> o) \\<Rightarrow> i\"  (binder \"THE \" 10) where [rewrite]:\n  \"(THE x. P(x)) = \\<Union>(Replace({\\<emptyset>}, \\<lambda>x y. P(y)))\"\n\n(* When encountering THE x. P(x), first show \\<exists>!x. P(x), then can conclude\n   THE x. P(x) satisfies P. *)\nsetup {* add_prfstep_check_req (\"THE x. P(x)\", \"\\<exists>!x. P(x)\") *}\nlemma theI' [forward]: \"\\<exists>!x. P(x) \\<Longrightarrow> P (THE x. P(x))\"\n  @proof @obtain \"a\" where \"P(a)\" @have \"(THE x. P(x)) = a\" @qed\n\n(* When trying to show (THE x. P(x)) = a, there is an alternative,\n   since because we already know term a satisfies predicate P. *)\nlemma the_equality [backward]: \"\\<forall>y. P(y) \\<longrightarrow> y = a \\<Longrightarrow> P(a) \\<Longrightarrow> (THE x. P(x)) = a\" by auto2\nsetup {* del_prfstep_thm @{thm The_def} *}\n\nsection \\<open>Ordered pairs\\<close>\n\ndefinition Pair :: \"[i, i] \\<Rightarrow> i\" where [rewrite]:\n  \"Pair(a,b) = {{a}, {a,b}}\"\n\ndefinition fst :: \"i \\<Rightarrow> i\" where [rewrite]:\n  \"fst(p) = (THE a. \\<exists>b. p = Pair(a, b))\"\n\ndefinition snd :: \"i \\<Rightarrow> i\" where [rewrite]:\n  \"snd(p) = (THE b. \\<exists>a. p = Pair(a, b))\"\n\n(* For pattern-matching *)\ndefinition split :: \"[[i, i] \\<Rightarrow> 'a, i] \\<Rightarrow> 'a::{}\" where\n  \"split(c) \\<equiv> \\<lambda>p. c(fst(p), snd(p))\"\nsetup {* Normalizer.add_rewr_normalizer (\"rewr_split\", @{thm split_def}) *}\n\n(* Patterns -- extends pre-defined type \"pttrn\" used in abstractions *)\nnonterminal patterns\nsyntax\n  \"_pattern\"  :: \"patterns => pttrn\"         (\"\\<langle>_\\<rangle>\")\n  \"\"          :: \"pttrn => patterns\"         (\"_\")\n  \"_patterns\" :: \"[pttrn, patterns] => patterns\"  (\"_,/_\")\n  \"_Tuple\"    :: \"[i, is] => i\"              (\"\\<langle>(_,/ _)\\<rangle>\")\ntranslations\n  \"\\<langle>x, y, z\\<rangle>\"   == \"\\<langle>x, \\<langle>y, z\\<rangle>\\<rangle>\"\n  \"\\<langle>x, y\\<rangle>\"      == \"CONST Pair(x, y)\"\n  \"\\<lambda>\\<langle>x,y,zs\\<rangle>.b\" == \"CONST split(\\<lambda>x \\<langle>y,zs\\<rangle>.b)\"\n  \"\\<lambda>\\<langle>x,y\\<rangle>.b\"    == \"CONST split(\\<lambda>x y. b)\"\n\nlemma pair_eqD [forward]: \"\\<langle>a, b\\<rangle> = \\<langle>c, d\\<rangle> \\<Longrightarrow> a = c \\<and> b = d\" by auto2\nlemma pair_eqI_fst [backward]: \"a = c \\<Longrightarrow> \\<langle>a,b\\<rangle> = \\<langle>c,b\\<rangle>\" by auto2\nlemma pair_eqI_snd [backward]: \"b = d \\<Longrightarrow> \\<langle>a,b\\<rangle> = \\<langle>a,d\\<rangle>\" by auto2\n\nsetup {* del_prfstep_thm @{thm Pair_def} *}\n\nlemma fst_conv [rewrite]: \"fst(\\<langle>a, b\\<rangle>) = a\" by auto2\nsetup {* del_prfstep_thm @{thm fst_def} *}\n\nlemma snd_conv [rewrite]: \"snd(\\<langle>a, b\\<rangle>) = b\" by auto2\nsetup {* del_prfstep_thm @{thm snd_def} *}\n\nsection \\<open>If expressions\\<close>\n\ndefinition If :: \"[o, i, i] \\<Rightarrow> i\"  (\"(if (_)/ then (_)/ else (_))\" [10] 10)  where [rewrite]:\n  \"(if P then a else b) = (THE z. P \\<and> z=a \\<or> \\<not>P \\<and> z=b)\"\n\nlemma If_eval:\n  \"P \\<Longrightarrow> (if P then a else b) = a\"\n  \"\\<not>P \\<Longrightarrow> (if P then a else b) = b\"\n  \"P \\<Longrightarrow> (if \\<not>P then a else b) = b\" by auto2+\nsetup {* fold (fn th => add_rewrite_rule_cond th [with_score 1]) @{thms If_eval} *}\nsetup {* del_prfstep_thm @{thm If_def} *}\n\nsetup {* add_gen_prfstep (\"case_intro\",\n  [WithTerm @{term_pat \"if ?cond then ?yes else ?no\"},\n   CreateCase @{term_pat \"?cond::o\"}]) *}\n\ndefinition Ifb :: \"[o, o, o] \\<Rightarrow> o\"  (\"(ifb (_)/ then (_)/ else (_))\" [10] 10)  where [rewrite]:\n  \"(ifb P then a else b) \\<longleftrightarrow> (P \\<and> a) \\<or> (\\<not>P \\<and> b)\"\n \nlemma Ifb_eval:\n  \"P \\<Longrightarrow> (ifb P then a else b) \\<longleftrightarrow> a\"\n  \"\\<not>P \\<Longrightarrow> (ifb P then a else b) \\<longleftrightarrow> b\"\n  \"P \\<Longrightarrow> (ifb \\<not>P then a else b) \\<longleftrightarrow> b\" by auto2+\nsetup {* fold (fn th => add_rewrite_rule_cond th [with_score 1]) @{thms Ifb_eval} *}\nsetup {* del_prfstep_thm @{thm Ifb_def} *}\n\nsetup {* add_gen_prfstep (\"case_intro_bool1\",\n  [WithFact @{term_pat \"ifb ?cond then ?yes else ?no\"},\n   CreateCase @{term_pat \"?cond::o\"}]) *}\n\nsetup {* add_gen_prfstep (\"case_intro_bool2\",\n  [WithGoal @{term_pat \"ifb ?cond then ?yes else ?no\"},\n   CreateCase @{term_pat \"?cond::o\"}]) *}\n\nsection \\<open>Functional form of replacement\\<close>\n\ndefinition RepFun :: \"[i, i \\<Rightarrow> i] \\<Rightarrow> i\" where [rewrite]:\n  \"RepFun(A,f) = Replace(A, \\<lambda>x y. y = f(x))\"\n\nlemma RepFun_iff [rewrite]:\n  \"y \\<in> RepFun(A,f) \\<longleftrightarrow> (\\<exists>x\\<in>A. y = f(x))\" by auto2\nsetup {* del_prfstep_thm @{thm RepFun_def} *}\n\nsyntax\n  \"_RepFun\" :: \"[i, pttrn, i] => i\"  (\"(1{_ ./ _ \\<in> _})\" [51,0,51])\ntranslations\n  \"{b. x\\<in>A}\" \\<rightleftharpoons> \"CONST RepFun(A, \\<lambda>x. b)\"\n\nlemma repfun_nonempty [backward]: \"A \\<noteq> \\<emptyset> \\<Longrightarrow> {b(x). x\\<in>A} \\<noteq> \\<emptyset>\"\n  @proof @obtain \"a \\<in> A\" @have \"b(a) \\<in> {b(x). x\\<in>A}\" @qed\n\nsection \\<open>Parametrized union and intersection\\<close>\n\ndefinition UnionS :: \"i \\<Rightarrow> [i \\<Rightarrow> i] \\<Rightarrow> i\" where [rewrite]:\n  \"UnionS(I,X) = \\<Union>{X(a). a\\<in>I}\"\n\ndefinition InterS :: \"i \\<Rightarrow> [i \\<Rightarrow> i] \\<Rightarrow> i\" where [rewrite]:\n  \"InterS(I,X) = \\<Inter>{X(a). a\\<in>I}\"\nsetup {* register_wellform_data (\"InterS(I,X)\", [\"I \\<noteq> \\<emptyset>\"]) *}\nsetup {* add_prfstep_check_req (\"InterS(I,X)\", \"I \\<noteq> \\<emptyset>\") *}\n\nsyntax\n  \"_UNION\" :: \"[pttrn, i, i] => i\"  (\"(3\\<Union>_\\<in>_./ _)\" 10)\n  \"_INTER\" :: \"[pttrn, i, i] => i\"  (\"(3\\<Inter>_\\<in>_./ _)\" 10)\ntranslations\n  \"\\<Union>a\\<in>I. X\" == \"CONST UnionS(I, \\<lambda>a. X)\"\n  \"\\<Inter>a\\<in>I. X\" == \"CONST InterS(I, \\<lambda>a. X)\"\n\nlemma UnionS_iff [rewrite]:\n  \"x \\<in> (\\<Union>a\\<in>I. X(a)) \\<longleftrightarrow> (\\<exists>a\\<in>I. x\\<in>X(a))\" by auto2\nlemma UnionSI [typing2]:\n  \"x \\<in> X(a) \\<Longrightarrow> a \\<in> I \\<Longrightarrow> x \\<in> (\\<Union>a\\<in>I. X(a))\" by auto2\nlemma InterS_iff [rewrite]:\n  \"I \\<noteq> \\<emptyset> \\<Longrightarrow> x \\<in> (\\<Inter>a\\<in>I. X(a)) \\<longleftrightarrow> (\\<forall>a\\<in>I. x\\<in>X(a))\" by auto2\nsetup {* del_prfstep_thm @{thm UnionS_def} *}\nsetup {* del_prfstep_thm @{thm InterS_def} *}\n\nsection \\<open>Sigma\\<close>\n\ndefinition Sigma :: \"[i, i \\<Rightarrow> i] \\<Rightarrow> i\" where [rewrite]:\n  \"Sigma(A,B) = (\\<Union>x\\<in>A. \\<Union>y\\<in>B(x). {\\<langle>x,y\\<rangle>})\"\n\nlemma Sigma_iff [rewrite]:\n  \"p \\<in> Sigma(A, B) \\<longleftrightarrow> p = \\<langle>fst(p),snd(p)\\<rangle> \\<and> fst(p) \\<in> A \\<and> snd(p) \\<in> B(fst(p))\" by auto2\nsetup {* del_prfstep_thm @{thm Sigma_def} *}\n\nsection \\<open>Product set\\<close>\n\ndefinition cart_prod :: \"[i, i] \\<Rightarrow> i\"  (infixr \"\\<times>\" 80) where [rewrite]:\n  \"A \\<times> B \\<equiv> Sigma(A, \\<lambda>_. B)\"\n\nlemma prod_memD [forward]:\n  \"p \\<in> A \\<times> B \\<Longrightarrow> p = \\<langle>fst(p),snd(p)\\<rangle> \\<and> fst(p) \\<in> A \\<and> snd(p) \\<in> B\" by auto2\n\nlemma prod_memI: \"a \\<in> A \\<Longrightarrow> \\<forall>b\\<in>B. \\<langle>a,b\\<rangle> \\<in> A\\<times>B\" by auto2\nsetup {* add_forward_prfstep_cond @{thm prod_memI} [with_term \"?A\\<times>?B\", with_score 500] *}\nsetup {* del_prfstep_thm @{thm cart_prod_def} *}\n\nlemma prod_memI' [backward,backward1,backward2]:\n  \"a \\<in> A \\<Longrightarrow> b \\<in> B \\<Longrightarrow> \\<langle>a,b\\<rangle> \\<in> A \\<times> B\" by auto2\n\n(* Determining the two sets from the product set. *)\nlemma prod_non_zero [forward]: \"A \\<times> B = \\<emptyset> \\<Longrightarrow> A = \\<emptyset> \\<or> B = \\<emptyset>\" by auto2\n\nlemma prod_subset: \"A \\<subseteq> C \\<Longrightarrow> B \\<subseteq> D \\<Longrightarrow> A \\<times> B \\<subseteq> C \\<times> D\" by auto2\nsetup {* add_backward_prfstep_cond @{thm prod_subset} [with_cond \"?A \\<noteq> ?C\", with_cond \"?B \\<noteq> ?D\"] *}\nlemma prod_subset1 [backward]: \"B \\<subseteq> D \\<Longrightarrow> A \\<times> B \\<subseteq> A \\<times> D\" by auto2\nlemma prod_subset2 [backward]: \"A \\<subseteq> C \\<Longrightarrow> A \\<times> B \\<subseteq> C \\<times> B\" by auto2\n\nlemma product_eq: \"A \\<times> B = C \\<times> D \\<Longrightarrow> A \\<noteq> \\<emptyset> \\<Longrightarrow> B \\<noteq> \\<emptyset> \\<Longrightarrow> A = C \\<and> B = D\" by auto2\nsetup {* add_forward_prfstep_cond @{thm product_eq} [with_cond \"?A \\<noteq> ?C\", with_cond \"?B \\<noteq> ?D\"] *}\nlemma product_eq1 [forward]: \"A \\<times> B = A \\<times> D \\<Longrightarrow> A \\<noteq> \\<emptyset> \\<Longrightarrow> B = D\" by auto2\nlemma product_eq2 [forward]: \"A \\<times> B = C \\<times> B \\<Longrightarrow> B \\<noteq> \\<emptyset> \\<Longrightarrow> A = C\" by auto2\n\nlemma prod_inter [rewrite_back]: \"(X \\<times> Y) \\<inter> (A \\<times> B) = (X \\<inter> A) \\<times> (Y \\<inter> B)\" by auto2\nsetup {* add_rewrite_rule_cond @{thm prod_inter} [with_cond \"?X \\<noteq> ?A\", with_cond \"?Y \\<noteq> ?B\"] *}\nlemma prod_inter1 [rewrite]: \"(X \\<times> Y) \\<inter> (X \\<times> B) = X \\<times> (Y \\<inter> B)\" by auto2\nlemma prod_inter2 [rewrite]: \"(X \\<times> Y) \\<inter> (A \\<times> Y) = (X \\<inter> A) \\<times> Y\" by auto2\n\nlemma prod_empty1 [rewrite]: \"\\<emptyset> \\<times> A = \\<emptyset>\" by auto2\nlemma prod_empty2 [rewrite]: \"A \\<times> \\<emptyset> = \\<emptyset>\" by auto2\nlemma prod_union1 [rewrite_bidir]: \"X \\<times> A \\<union> X \\<times> B = X \\<times> (A \\<union> B)\" by auto2\nlemma prod_union2 [rewrite_bidir]: \"A \\<times> X \\<union> B \\<times> X = (A \\<union> B) \\<times> X\" by auto2\nlemma prod_diff1 [rewrite]: \"X \\<times> A \\<midarrow> X \\<times> B = X \\<times> (A \\<midarrow> B)\" by auto2\nlemma prod_diff2 [rewrite]: \"A \\<times> X \\<midarrow> B \\<times> X = (A \\<midarrow> B) \\<times> X\" by auto2\n\nsection \\<open>Axiom of Foundation\\<close>\n\naxiomatization where\n  foundation [backward]: \"x \\<noteq> \\<emptyset> \\<Longrightarrow> \\<exists>y\\<in>x. y \\<inter> x = \\<emptyset>\"\n\nlemma no_mem_cycle1 [resolve]: \"a \\<notin> a\"\n@proof\n  @obtain \"x\\<in>{a}\" where \"x \\<inter> {a} = \\<emptyset>\"\n@qed\n\nlemma no_mem_cycle2 [resolve]: \"x \\<in> y \\<Longrightarrow> y \\<notin> x\"\n@proof\n  @obtain \"a \\<in> {x,y}\" where \"a \\<inter> {x,y} = \\<emptyset>\"\n@qed\n\nlemma succ_nonzero [resolve]: \"succ(x) \\<noteq> \\<emptyset>\" by auto2\nlemma succ_inj [forward]: \"succ(x) = succ(y) \\<Longrightarrow> x = y\" 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/Set.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8740772417253255, "lm_q2_score": 0.8056321843145405, "lm_q1q2_score": 0.7041847575108027}}
{"text": "theory ConcreteSemantics10_3_Live\n  imports Main \"~~/src/HOL/IMP/Big_Step\"  \"~~/src/HOL/IMP/Vars\" \nbegin \n\nsubsection \"Liveness Analysis\"\n\nfun L :: \"com \\<Rightarrow> vname set \\<Rightarrow> vname set\" where\n\"L SKIP X = X\" |\n\"L (x ::= a) X = vars a \\<union> (X - {x})\" |\n\"L (c\\<^sub>1;; c\\<^sub>2) X = L c\\<^sub>1 (L c\\<^sub>2 X)\" |\n\"L (IF b THEN c\\<^sub>1 ELSE c\\<^sub>2) X = vars b \\<union> L c\\<^sub>1 X \\<union> L c\\<^sub>2 X\" |\n\"L (WHILE b DO c) X = vars b \\<union> X \\<union> L c X\"\n\nvalue \"show (L (''y'' ::= V ''z'';; ''x'' ::= Plus (V ''y'') (V ''z'')) {''x''})\"\n\nvalue \"show (L (WHILE Less (V ''x'') (V ''x'') DO ''y'' ::= V ''z'') {''x''})\"\n\nfun \"kill\" :: \"com \\<Rightarrow> vname set\" where\n\"kill SKIP = {}\" |\n\"kill (x ::= a) = {x}\" |\n\"kill (c\\<^sub>1;; c\\<^sub>2) = kill c\\<^sub>1 \\<union> kill c\\<^sub>2\" |\n\"kill (IF b THEN c\\<^sub>1 ELSE c\\<^sub>2) = kill c\\<^sub>1 \\<inter> kill c\\<^sub>2\" |\n\"kill (WHILE b DO c) = {}\"\n\nfun gen :: \"com \\<Rightarrow> vname set\" where\n\"gen SKIP = {}\" |\n\"gen (x ::= a) = vars a\" |\n\"gen (c\\<^sub>1;; c\\<^sub>2) = gen c\\<^sub>1 \\<union> (gen c\\<^sub>2 - kill c\\<^sub>1)\" |\n\"gen (IF b THEN c\\<^sub>1 ELSE c\\<^sub>2) = vars b \\<union> gen c\\<^sub>1 \\<union> gen c\\<^sub>2\" |\n\"gen (WHILE b DO c) = vars b \\<union> gen c\"\n\n(* Lemma 10.15 (Liveness via gen/kill). *)\nlemma L_gen_kill: \"L c X = gen c \\<union> (X - kill c)\"\nproof(induction c arbitrary:X)\n  case SKIP\nthen show ?case by auto\nnext\n  case (Assign x1 x2)\n  then show ?case by auto\nnext\n  case (Seq c1 c2)\n  then show ?case by auto\nnext\n  case (If x1 c1 c2)\n  then show ?case by auto\nnext\n  case (While x1 c)\n  then show ?case by auto\nqed\n\n(*Lemma 10.15 (Liveness via gen/kill).*)\nlemma L_While_pfp: \"L c (L (WHILE b DO c) X) \\<subseteq> L (WHILE b DO c) X\"\n  apply(auto simp add: L_gen_kill)\n  done\n\nlemma L_While_lpfp:\n  \"vars b \\<union> X \\<union> L c P \\<subseteq> P \\<Longrightarrow> L (WHILE b DO c) X \\<subseteq> P\"\nby(simp add: L_gen_kill)\n\nlemma L_While_vars: \"vars b \\<subseteq> L (WHILE b DO c) X\"\nby auto\n\nlemma L_While_X: \"X \\<subseteq> L (WHILE b DO c) X\"\nby auto\n\ntext\\<open>Disable L WHILE equation and reason only with L WHILE constraints\\<close>\ndeclare L.simps(5)[simp del]\n\nsubsection \"Correctness\"\n\ntheorem L_correct:\n  \"(c,s) \\<Rightarrow> s'  \\<Longrightarrow> s = t on L c X \\<Longrightarrow>\n  \\<exists> t'. (c,t) \\<Rightarrow> t' & s' = t' on X\"\nproof (induction arbitrary: X t rule: big_step_induct)\ncase (Skip s)\n  then show ?case by auto\nnext\n  case (Assign x a s)\n  then show ?case by (auto simp add: ball_Un)\nnext\n  case (Seq c\\<^sub>1 s\\<^sub>1 s\\<^sub>2 c\\<^sub>2 s\\<^sub>3)\n(*\n       (c\\<^sub>1, s\\<^sub>1) \\<Rightarrow> s\\<^sub>2 \\<Longrightarrow>\n       (\\<And>X t. s\\<^sub>1 = t on L c\\<^sub>1 X \\<Longrightarrow> \\<exists>t'. (c\\<^sub>1, t) \\<Rightarrow> t' \\<and> s\\<^sub>2 = t' on X) \\<Longrightarrow>\n       (c\\<^sub>2, s\\<^sub>2) \\<Rightarrow> s\\<^sub>3 \\<Longrightarrow>\n       (\\<And>X t. s\\<^sub>2 = t on L c\\<^sub>2 X \\<Longrightarrow> \\<exists>t'. (c\\<^sub>2, t) \\<Rightarrow> t' \\<and> s\\<^sub>3 = t' on X) \\<Longrightarrow>\n       s\\<^sub>1 = t on L (c\\<^sub>1;; c\\<^sub>2) X \\<Longrightarrow> \\<exists>t'. (c\\<^sub>1;; c\\<^sub>2, t) \\<Rightarrow> t' \\<and> s\\<^sub>3 = t' on X\n*)\n  from Seq.IH(1) Seq.prems obtain t2 where \"(c\\<^sub>1, t) \\<Rightarrow> t2\" and \"s\\<^sub>2 = t2 on L c\\<^sub>2 X\" \n    by simp blast\n  obtain t3 where \"(c\\<^sub>2, t2) \\<Rightarrow> t3\" and \"s\\<^sub>3 = t3 on X\" \n    using Seq.IH(2) \\<open>s\\<^sub>2 = t2 on L c\\<^sub>2 X\\<close> by blast\n  then show ?case \n    using \\<open>(c\\<^sub>1, t) \\<Rightarrow> t2\\<close> by blast\nnext\n  case (IfTrue b s c\\<^sub>1 s' c\\<^sub>2)\n(*\n       bval b s \\<Longrightarrow>\n       (c\\<^sub>1, s) \\<Rightarrow> t \\<Longrightarrow>\n       (\\<And>X ta. s = ta on L c\\<^sub>1 X \\<Longrightarrow> \\<exists>t'. (c\\<^sub>1, ta) \\<Rightarrow> t' \\<and> t = t' on X) \\<Longrightarrow>\n       s = ta on L (IF b THEN c\\<^sub>1 ELSE c\\<^sub>2) X \\<Longrightarrow>\n       \\<exists>t'. (IF b THEN c\\<^sub>1 ELSE c\\<^sub>2, ta) \\<Rightarrow> t' \\<and> t = t' on X\n*)\n  then have \"s = t on vars b\" and \"s = t on L c\\<^sub>1 X \" by auto\n  have \"bval b t\" \n    using IfTrue.hyps(1) \\<open>s = t on vars b\\<close> bval_eq_if_eq_on_vars by blast\n from IfTrue.IH[OF \\<open>s = t on L c\\<^sub>1 X\\<close>] obtain t' where \"s' = t' on X\"  \"(c\\<^sub>1, t) \\<Rightarrow> t'\" by auto\n  then show ?case \n    using \\<open>bval b t\\<close> by blast\nnext\n  case (IfFalse b s c\\<^sub>2 s' c\\<^sub>1)\n  then have \"s = t on vars b\" and \"s = t on L c\\<^sub>2 X \" by auto\n  have \"\\<not> bval b t\" \n    using IfFalse.hyps(1) \\<open>s = t on vars b\\<close> bval_eq_if_eq_on_vars by blast\n from IfFalse.IH[OF \\<open>s = t on L c\\<^sub>2 X\\<close>] obtain t' where \"s' = t' on X\"  \"(c\\<^sub>2, t) \\<Rightarrow> t'\" by auto\n  then show ?case using \\<open>\\<not> bval b t\\<close> by blast\nnext\n  case (WhileFalse b s c)\n(*\n       \\<not> bval b s \\<Longrightarrow>\n       s = t on L (WHILE b DO c) X \\<Longrightarrow> \\<exists>t'. (WHILE b DO c, t) \\<Rightarrow> t' \\<and> s = t' on X\n*)\n  then have \"~ bval b t\" \n    by (metis L_While_vars bval_eq_if_eq_on_vars subsetD)\n  thus ?case \n    using L_While_X WhileFalse.prems by blast\nnext\n  case (WhileTrue b s\\<^sub>1 c s\\<^sub>2 s\\<^sub>3)\n(*\n       bval b s\\<^sub>1 \\<Longrightarrow>\n       (c, s\\<^sub>1) \\<Rightarrow> s\\<^sub>2 \\<Longrightarrow>\n       (\\<And>X t. s\\<^sub>1 = t on L c X \\<Longrightarrow> \\<exists>t'. (c, t) \\<Rightarrow> t' \\<and> s\\<^sub>2 = t' on X) \\<Longrightarrow>\n       (WHILE b DO c, s\\<^sub>2) \\<Rightarrow> s\\<^sub>3 \\<Longrightarrow>\n       (\\<And>X t. s\\<^sub>2 = t on L (WHILE b DO c) X \\<Longrightarrow>\n               \\<exists>t'. (WHILE b DO c, t) \\<Rightarrow> t' \\<and> s\\<^sub>3 = t' on X) \\<Longrightarrow>\n       s\\<^sub>1 = t on L (WHILE b DO c) X \\<Longrightarrow> \\<exists>t'. (WHILE b DO c, t) \\<Rightarrow> t' \\<and> s\\<^sub>3 = t' on X\n*)\n  let ?w = \"WHILE b DO c\"\n  have \"bval b t\" \n    by (metis L_While_vars WhileTrue.hyps(1) WhileTrue.prems bval_eq_if_eq_on_vars subsetD)\n  then have \"s\\<^sub>1 = t on L c (L ?w X)\" \n    using L_While_pfp WhileTrue.prems by blast\n  obtain t2 where \"(c, t) \\<Rightarrow> t2\" \"s\\<^sub>2 = t2 on L ?w X\" \n    using WhileTrue.IH(1) \\<open>s\\<^sub>1 = t on L c (L (WHILE b DO c) X)\\<close> by blast\n  obtain t3 where \"(?w, t2) \\<Rightarrow> t3\" \"s\\<^sub>3 = t3 on X\" \n    using WhileTrue.IH(2) \\<open>s\\<^sub>2 = t2 on L (WHILE b DO c) X\\<close> by blast\n  then show ?case \n    using \\<open>(c, t) \\<Rightarrow> t2\\<close> \\<open>bval b t\\<close> by blast\nqed\n\nsubsection \"Program Optimization\"\n\ntext\\<open>Burying assignments to dead variables:\\<close>\nfun bury :: \"com \\<Rightarrow> vname set \\<Rightarrow> com\" where\n\"bury SKIP X = SKIP\" |\n\"bury (x ::= a) X = (if x \\<in> X then x ::= a else SKIP)\" |\n\"bury (c\\<^sub>1;; c\\<^sub>2) X = (bury c\\<^sub>1 (L c\\<^sub>2 X);; bury c\\<^sub>2 X)\" |\n\"bury (IF b THEN c\\<^sub>1 ELSE c\\<^sub>2) X = IF b THEN bury c\\<^sub>1 X ELSE bury c\\<^sub>2 X\" |\n\"bury (WHILE b DO c) X = WHILE b DO bury c (L (WHILE b DO c) X)\"\n\n\n(* Lemma 10.19 (Correctness of bury, part 1). *)\ntheorem bury_correct:\n  \"(c,s) \\<Rightarrow> s'  \\<Longrightarrow> s = t on L c X \\<Longrightarrow>\n  \\<exists> t'. (bury c X,t) \\<Rightarrow> t' & s' = t' on X\"\nproof (induction arbitrary: X t rule: big_step_induct)\ncase (Skip s)\nthen show ?case by auto\nnext\n  case (Assign x a s)\n  then show ?case by (auto simp add: ball_Un)\nnext\n  case (Seq c\\<^sub>1 s\\<^sub>1 s\\<^sub>2 c\\<^sub>2 s\\<^sub>3)\n  from Seq.IH(1) Seq.prems obtain t2 where \"(bury c\\<^sub>1 (L c\\<^sub>2 X), t) \\<Rightarrow> t2\" and \"s\\<^sub>2 = t2 on L c\\<^sub>2 X\" \n    by simp blast\n  obtain t3 where \"(bury c\\<^sub>2 X, t2) \\<Rightarrow> t3\" and \"s\\<^sub>3 = t3 on X\" \n    by (metis Seq.IH(2) \\<open>(bury c\\<^sub>1 (L c\\<^sub>2 X), t) \\<Rightarrow> t2\\<close> \\<open>\\<And>thesis. (\\<And>t2. \\<lbrakk>(bury c\\<^sub>1 (L c\\<^sub>2 X), t) \\<Rightarrow> t2; s\\<^sub>2 = t2 on L c\\<^sub>2 X\\<rbrakk> \\<Longrightarrow> thesis) \\<Longrightarrow> thesis\\<close> big_step_determ)\n  then show ?case \n    using \\<open>(bury c\\<^sub>1 (L c\\<^sub>2 X), t) \\<Rightarrow> t2\\<close> by auto\nnext\n  case (IfTrue b s c\\<^sub>1 s' c\\<^sub>2)\n  then have \"s = t on vars b\" and \"s = t on L c\\<^sub>1 X \" by auto\n  have \"bval b t\" \n    using IfTrue.hyps(1) \\<open>s = t on vars b\\<close> bval_eq_if_eq_on_vars by blast\n  from IfTrue.IH[OF \\<open>s = t on L c\\<^sub>1 X\\<close>] obtain t' where\n    \"(bury c\\<^sub>1 X, t) \\<Rightarrow> t'\" \"s' =t' on X\" by auto\n  then show ?case \n    using \\<open>bval b t\\<close> by auto\nnext\n  case (IfFalse b s c\\<^sub>2 s' c\\<^sub>1)\n  then have \"s = t on vars b\" and \"s = t on L c\\<^sub>2 X \" by auto\n  have \"\\<not> bval b t\" \n    using IfFalse.hyps(1) \\<open>s = t on vars b\\<close> bval_eq_if_eq_on_vars by blast\n from IfFalse.IH[OF \\<open>s = t on L c\\<^sub>2 X\\<close>] obtain t' where \"s' = t' on X\"  \"(bury c\\<^sub>2 X, t) \\<Rightarrow> t'\" by auto\n  then show ?case using \\<open>\\<not> bval b t\\<close> \n    by auto\nnext\n  case (WhileFalse b s c)\n  then have \"\\<not> bval b t\" \n    by (metis L_While_vars bval_eq_if_eq_on_vars subsetD)\n  thus ?case \n    using L_While_X WhileFalse.prems by fastforce\nnext\n  case (WhileTrue b s\\<^sub>1 c s\\<^sub>2 s\\<^sub>3)\n  let ?w = \"WHILE b DO c\"\n  have \"bval b t\" \n    by (metis L_While_vars WhileTrue.hyps(1) WhileTrue.prems bval_eq_if_eq_on_vars subsetD)\n  then have \"s\\<^sub>1 = t on L c (L ?w X)\" \n    using L_While_pfp WhileTrue.prems by blast\n  obtain t2 where \"(bury c (L ?w X), t) \\<Rightarrow> t2\" \"s\\<^sub>2 = t2 on L ?w X\" \n    using WhileTrue.IH(1) \\<open>s\\<^sub>1 = t on L c (L (WHILE b DO c) X)\\<close> by blast\n  obtain t3 where \"(bury ?w X, t2) \\<Rightarrow> t3\" \"s\\<^sub>3 = t3 on X\" \n    using WhileTrue.IH(2) \\<open>s\\<^sub>2 = t2 on L (WHILE b DO c) X\\<close> by blast\n  then show ?case \n    using \\<open>(bury c (L (WHILE b DO c) X), t) \\<Rightarrow> t2\\<close> \\<open>bval b t\\<close> by auto\nqed\n\n(* Lemma 10.20 (Correctness of bury, part 2). *)\n\n(* Corollary 10.21 (Correctness of bury). *)\ncorollary final_bury_correct: \"(c,s) \\<Rightarrow> s' \\<Longrightarrow> (bury c UNIV,s) \\<Rightarrow> s'\"\nusing bury_correct[of c s s' UNIV]\n  by (auto simp: fun_eq_iff[symmetric])\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/ConcreteSemanticsChapter10/ConcreteSemantics10_3_Live.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8740772286044094, "lm_q2_score": 0.8056321866478978, "lm_q1q2_score": 0.7041847489797048}}
{"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>\\<open>'a\\<close> of the sort\n  \\<open>{plus, minus, zero}\\<close> is considered, on which a real scalar multiplication\n  \\<open>\\<cdot>\\<close> 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>\\<open>vector space\\<close> is a non-empty set \\<open>V\\<close> of elements from \\<^typ>\\<open>'a\\<close> with the\n  following vector space laws: The set \\<open>V\\<close> is closed under addition and scalar\n  multiplication, addition is associative and commutative; \\<open>- x\\<close> is the\n  inverse of \\<open>x\\<close> wrt.\\ addition and \\<open>0\\<close> is the neutral element of addition.\n  Addition and multiplication are distributive; scalar multiplication is\n  associative and the real number \\<open>1\\<close> is the neutral element of scalar\n  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:\n  \"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\nlemmas add_ac = add_assoc add_commute add_left_commute\n\n\ntext \\<open>\n  The existence of the zero element of a vector space follows from the\n  non-emptiness of carrier set.\n\\<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:\n    \"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", "meta": {"author": "seL4", "repo": "isabelle", "sha": "e1ab32a3bb41728cd19541063283e37919978a4c", "save_path": "github-repos/isabelle/seL4-isabelle", "path": "github-repos/isabelle/seL4-isabelle/isabelle-e1ab32a3bb41728cd19541063283e37919978a4c/src/HOL/Hahn_Banach/Vector_Space.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8104789086703225, "lm_q2_score": 0.868826777936422, "lm_q1q2_score": 0.7041657788054639}}
{"text": "section \\<open>Bernstein Polynomials over the interval [0, 1]\\<close>\n\ntheory Bernstein_01\n  imports \"HOL-Computational_Algebra.Computational_Algebra\" \n    \"Budan_Fourier.Budan_Fourier\"\n    \"RRI_Misc\"\nbegin\n\ntext \\<open>\nThe theorem of three circles is a statement about the Bernstein coefficients of a polynomial, the\ncoefficients when a polynomial is expressed as a sum of Bernstein polynomials. These coefficients\nbehave nicely under translations and rescaling and are the coefficients of a particular polynomial\nin the [0, 1] case. We shall define the [0, 1] case now and consider the general case later,\nderiving all the results by rescaling.\n\\<close>\n\nsubsection \\<open>Definition and basic results\\<close>\n\ndefinition Bernstein_Poly_01 :: \"nat \\<Rightarrow> nat \\<Rightarrow> real poly\" where\n  \"Bernstein_Poly_01 j p = (monom (p choose j) j) \n                              * (monom 1 (p-j) \\<circ>\\<^sub>p [:1, -1:])\"\n\nlemma degree_Bernstein: \n  assumes hb: \"j \\<le> p\" \n  shows \"degree (Bernstein_Poly_01 j p) = p\"\nproof -\n  have ha: \"monom (p choose j) j \\<noteq> (0::real poly)\" using hb by force\n  have hb: \"monom 1 (p-j) \\<circ>\\<^sub>p [:1, -1:] \\<noteq> (0::real poly)\"\n  proof\n    assume \"monom 1 (p-j) \\<circ>\\<^sub>p [:1, -1:] = (0::real poly)\"\n    hence \"lead_coeff (monom 1 (p - j) \\<circ>\\<^sub>p [:1, -1:]) = (0::real)\"\n      apply (subst leading_coeff_0_iff)\n      by simp\n    moreover have \"lead_coeff (monom (1::real) (p - j) \n        \\<circ>\\<^sub>p [:1, -1:]) = (((- 1) ^ (p - j))::real)\"\n      by (subst lead_coeff_comp, auto simp: degree_monom_eq)\n    ultimately show \"False\" by auto\n  qed\n  from ha hb show ?thesis\n    by (auto simp add: Bernstein_Poly_01_def degree_mult_eq \n          degree_monom_eq degree_pcompose)\nqed\n\nlemma coeff_gt: \n  assumes hb: \"j > p\" \n  shows \"Bernstein_Poly_01 j p = 0\"\n  by (simp add: hb Bernstein_Poly_01_def)\n\nlemma degree_Bernstein_le: \"degree (Bernstein_Poly_01 j p) \\<le> p\"\n  apply (cases \"j \\<le> p\")\n  by (simp_all add: degree_Bernstein coeff_gt)\n\nlemma poly_Bernstein_nonneg: \n  assumes \"x \\<ge> 0\" and \"1 \\<ge> x\" \n  shows \"poly (Bernstein_Poly_01 j p) x \\<ge> 0\"\n  using assms by (simp add: poly_monom poly_pcompose Bernstein_Poly_01_def)\n\nlemma Bernstein_symmetry: \n  assumes \"j \\<le> p\"\n  shows \"(Bernstein_Poly_01 j p) \\<circ>\\<^sub>p [:1, -1:] = Bernstein_Poly_01 (p-j) p\"\nproof -\n  have \"(Bernstein_Poly_01 j p) \\<circ>\\<^sub>p [:1, -1:]\n         = ((monom (p choose j) j) * (monom 1 (p-j) \\<circ>\\<^sub>p [:1, -1:])) \\<circ>\\<^sub>p [:1, -1:]\"\n    by (simp add: Bernstein_Poly_01_def)\n  also have \"... = (monom (p choose (p-j)) j * \n                    (monom 1 (p-j) \\<circ>\\<^sub>p [:1, -1:])) \\<circ>\\<^sub>p [:1, -1:]\" \n    by (fastforce simp: binomial_symmetric[OF assms])\n  also have \"... = monom (p choose (p-j)) j \\<circ>\\<^sub>p [:1, -1:] * \n                   (monom 1 (p-j)) \\<circ>\\<^sub>p ([:1, -1:] \\<circ>\\<^sub>p [:1, -1:])\"\n    by (force simp: pcompose_mult pcompose_assoc)\n  also have \"... = (monom (p choose (p-j)) j \\<circ>\\<^sub>p [:1, -1:]) * monom 1 (p-j)\"\n    by (force simp: pcompose_pCons)\n  also have \"... = smult (p choose (p-j)) (monom 1 j \\<circ>\\<^sub>p [:1, -1:]) \n                    * monom 1 (p-j)\" \n    by (simp add: assms smult_monom pcompose_smult[symmetric])\n  also have \"... = (monom 1 j \\<circ>\\<^sub>p [:1, -1:]) * monom (p choose (p-j)) (p-j)\"\n    apply (subst mult_smult_left)\n    apply (subst mult_smult_right[symmetric])\n    apply (subst smult_monom)\n    by force\n  also have \"... = Bernstein_Poly_01 (p-j) p\" using assms\n    by (auto simp: Bernstein_Poly_01_def)\n  finally show ?thesis .\nqed\n\nsubsection \\<open>@{term Bernstein_Poly_01} and @{term reciprocal_poly}\\<close>\n\nlemma Bernstein_reciprocal: \n  \"reciprocal_poly p (Bernstein_Poly_01 i p) \n    = smult (p choose i) ([:-1, 1:]^(p-i))\"\nproof cases\n  assume \"i \\<le> p\"\n  hence \"reciprocal_poly p (Bernstein_Poly_01 i p) = \n         reciprocal_poly (degree (Bernstein_Poly_01 i p)) (Bernstein_Poly_01 i p)\"\n    by (auto simp: degree_Bernstein)\n  also have \"... = reflect_poly (Bernstein_Poly_01 i p)\"\n    by (rule reciprocal_degree)\n  also have \"... = smult (p choose i) ([:-1, 1:]^(p-i))\"\n    by (auto simp: Bernstein_Poly_01_def reflect_poly_simps monom_altdef\n         pcompose_pCons reflect_poly_pCons' hom_distribs)\n  finally show ?thesis .\nnext\n  assume h:\"\\<not> i \\<le> p\"\n  hence \"reciprocal_poly p (Bernstein_Poly_01 i p) = (0::real poly)\"\n    by (auto simp: coeff_gt reciprocal_poly_def)\n  also have \"... = smult (p choose i) ([:-1, 1:]^(p - i))\" using h\n    by fastforce\n  finally show ?thesis .\nqed\n\nlemma Bernstein_reciprocal_translate: \n  \"reciprocal_poly p (Bernstein_Poly_01 i p) \\<circ>\\<^sub>p [:1, 1:] = \n   monom (p choose i) (p - i)\"\n  by (auto simp: Bernstein_reciprocal pcompose_smult pcompose_pCons monom_altdef hom_distribs)\n\nlemma coeff_Bernstein_sum_01: fixes b::\"nat \\<Rightarrow> real\" assumes hi: \"p \\<ge> i\"\n  shows \n    \"coeff (reciprocal_poly p \n            (\\<Sum>x = 0..p. smult (b x) (Bernstein_Poly_01 x p)) \\<circ>\\<^sub>p [:1, 1:]) \n      (p - i) = (p choose i) * (b i)\" (is \"?L = ?R\")\nproof -\n  define P where \"P \\<equiv> (\\<Sum>x = 0..p. (smult (b x) (Bernstein_Poly_01 x p)))\"\n\n  have \"\\<And>x. degree (smult (b x) (Bernstein_Poly_01 x p)) \\<le> p\"\n  proof -\n    fix x\n    show \"degree (smult (b x) (Bernstein_Poly_01 x p)) \\<le> p\"\n      apply (cases \"x \\<le> p\")\n      by (auto simp: degree_Bernstein coeff_gt)\n  qed\n  hence \"reciprocal_poly p P = \n         (\\<Sum>x = 0..p. reciprocal_poly p (smult (b x) (Bernstein_Poly_01 x p)))\"\n    apply (subst P_def)\n    apply (rule reciprocal_sum)\n    by presburger\n  also have\n    \"... = (\\<Sum>x = 0..p. (smult (b x * (p choose x)) ([:-1, 1:]^(p-x))))\"\n  proof (rule sum.cong)\n    fix x assume \"x \\<in> {0..p}\"\n    hence \"x \\<le> p\" by simp\n    thus \"reciprocal_poly p (smult (b x) (Bernstein_Poly_01 x p)) =\n          smult ((b x) * (p choose x)) ([:-1, 1:]^(p-x))\"\n      by (auto simp add: reciprocal_smult degree_Bernstein Bernstein_reciprocal)\n  qed (simp)\n  finally have \n    \"reciprocal_poly p P = \n     (\\<Sum>x = 0..p. (smult ((b x) * (p choose x)) ([:-1, 1:]^(p-x))))\" .\n  hence \n    \"(reciprocal_poly p P) \\<circ>\\<^sub>p [:1, 1:] = \n     (\\<Sum>x = 0..p. (smult ((b x) * (p choose x)) ([:-1, 1:]^(p-x))) \\<circ>\\<^sub>p [:1, 1:])\"\n    by (simp add: pcompose_sum pcompose_add)\n  also have \"... = (\\<Sum>x = 0..p. (monom ((b x) * (p choose x)) (p - x)))\"\n  proof (rule sum.cong)\n    fix x assume \"x \\<in> {0..p}\"\n    hence \"x \\<le> p\" by simp\n    thus \"smult (b x * (p choose x)) ([:- 1, 1:] ^ (p - x)) \\<circ>\\<^sub>p [:1, 1:] =\n          monom (b x * (p choose x)) (p - x)\"\n      by (simp add: hom_distribs pcompose_smult pcompose_pCons monom_altdef)\n  qed (simp)\n  finally have \"(reciprocal_poly p P) \\<circ>\\<^sub>p [:1, 1:] = \n                (\\<Sum>x = 0..p. (monom ((b x) * (p choose x)) (p - x)))\" .\n  hence \"?L = (\\<Sum>x = 0..p. if p - x = p - i then b x * real (p choose x) else 0)\"\n    by (auto simp add: P_def coeff_sum)\n  also have \"... = (\\<Sum>x = 0..p. if x = i then b x * real (p choose x) else 0)\"\n  proof (rule sum.cong)\n    fix x assume \"x \\<in> {0..p}\"\n    hence \"x \\<le> p\" by simp\n    thus \"(if p - x = p - i then b x * real (p choose x) else 0) =\n          (if x = i then b x * real (p choose x) else 0)\" using hi\n      by (auto simp add: leI)\n  qed (simp)\n  also have \"... = ?R\" by simp\n  finally show ?thesis .\nqed\n\nlemma Bernstein_sum_01: assumes hP: \"degree P \\<le> p\"\n  shows \n  \"P = (\\<Sum>j = 0..p. smult \n     (inverse (real (p choose j)) * \n      coeff (reciprocal_poly p P \\<circ>\\<^sub>p [:1, 1:]) (p-j))\n   (Bernstein_Poly_01 j p))\"\nproof -\n  define Q where \"Q \\<equiv> reciprocal_poly p P \\<circ>\\<^sub>p [:1, 1:]\"\n  from hP Q_def have hQ: \"degree Q \\<le> p\" \n    by (auto simp: degree_reciprocal degree_pcompose)\n  have \"reciprocal_poly p (\\<Sum>j = 0..p. \n        smult (inverse (real (p choose j)) * coeff Q (p-j)) \n        (Bernstein_Poly_01 j p)) \\<circ>\\<^sub>p [:1, 1:] = Q\"\n  proof (rule poly_eqI)\n    fix n\n    show \"coeff (reciprocal_poly p (\\<Sum>j = 0..p. \n          smult (inverse (real (p choose j)) * coeff Q (p-j))\n          (Bernstein_Poly_01 j p)) \\<circ>\\<^sub>p [:1, 1:]) n = coeff Q n\" \n      (is \"?L = ?R\")\n    proof cases\n      assume hn: \"n \\<le> p\"\n      hence \"?L = coeff (reciprocal_poly p (\\<Sum>j = 0..p. \n             smult (inverse (real (p choose j)) * coeff Q (p-j)) \n             (Bernstein_Poly_01 j p)) \\<circ>\\<^sub>p [:1, 1:]) (p - (p - n))\"\n        by force\n      also have \"... = (p choose (p-n)) * \n                       (inverse (real (p choose (p-n))) * \n                        coeff Q (p-(p-n)))\"\n        apply (subst coeff_Bernstein_sum_01)\n        by auto\n      also have \"... = ?R\" using hn\n        by fastforce\n      finally show \"?L = ?R\" .\n    next\n      assume hn: \"\\<not> n \\<le> p\"\n      have \"degree (\\<Sum>j = 0..p.\n            smult (inverse (real (p choose j)) * coeff Q (p - j))\n            (Bernstein_Poly_01 j p)) \\<le> p\"\n      proof (rule degree_sum_le)\n        fix q assume \"q \\<in> {0..p}\"\n        hence \"q \\<le> p\" by fastforce\n        thus \"degree (smult (inverse (real (p choose q)) * \n              coeff Q (p - q)) (Bernstein_Poly_01 q p)) \\<le> p\"\n          by (auto simp add: degree_Bernstein degree_smult_le)\n      qed simp\n      hence \"degree (reciprocal_poly p (\\<Sum>j = 0..p.\n            smult (inverse (real (p choose j)) * coeff Q (p - j)) \n            (Bernstein_Poly_01 j p)) \\<circ>\\<^sub>p [:1, 1:]) \\<le> p\"\n        by (auto simp add: degree_pcompose degree_reciprocal)\n      hence \"?L = 0\" using hn by (auto simp add: coeff_eq_0)\n      thus \"?L = ?R\" using hQ hn by (simp add: coeff_eq_0)\n    qed\n  qed\n  hence \"reciprocal_poly p P \\<circ>\\<^sub>p [:1, 1:] = \n         reciprocal_poly p (\\<Sum>j = 0..p. \n         smult (inverse (real (p choose j)) *\n         coeff (reciprocal_poly p P \\<circ>\\<^sub>p [:1, 1:]) (p-j))\n         (Bernstein_Poly_01 j p)) \\<circ>\\<^sub>p [:1, 1:]\" \n    by (auto simp: degree_reciprocal degree_pcompose Q_def)\n  hence \"reciprocal_poly p P \\<circ>\\<^sub>p ([:1, 1:] \\<circ>\\<^sub>p [:-1, 1:]) =\n         reciprocal_poly p (\\<Sum>j = 0..p. smult (inverse (real (p choose j)) * \n         coeff (reciprocal_poly p P \\<circ>\\<^sub>p [:1, 1:]) (p-j)) \n         (Bernstein_Poly_01 j p)) \\<circ>\\<^sub>p ([:1, 1:] \\<circ>\\<^sub>p [:-1, 1:])\"\n    by (auto simp: pcompose_assoc)\n  hence \"reciprocal_poly p P = reciprocal_poly p (\\<Sum>j = 0..p. \n         smult (inverse (real (p choose j)) *\n         coeff (reciprocal_poly p P \\<circ>\\<^sub>p [:1, 1:]) (p-j)) (Bernstein_Poly_01 j p))\" \n    by (auto simp: pcompose_pCons)\n  hence \"reciprocal_poly p (reciprocal_poly p P) = \n         reciprocal_poly p (reciprocal_poly p (\\<Sum>j = 0..p. \n         smult (inverse (real (p choose j)) *\n         coeff (reciprocal_poly p P \\<circ>\\<^sub>p [:1, 1:]) (p-j)) (Bernstein_Poly_01 j p)))\"\n    by argo\n  thus \"P = (\\<Sum>j = 0..p. smult (inverse (real (p choose j)) * \n        coeff (reciprocal_poly p P \\<circ>\\<^sub>p [:1, 1:]) (p-j)) (Bernstein_Poly_01 j p))\"\n    using hP by (auto simp: reciprocal_reciprocal degree_sum_le degree_smult_le \n                 degree_Bernstein degree_add_le)\nqed\n\nlemma Bernstein_Poly_01_span1: \n  assumes hP: \"degree P \\<le> p\"\n  shows \"P \\<in> poly_vs.span {Bernstein_Poly_01 x p | x. x \\<le> p}\"\nproof -\n  have \"Bernstein_Poly_01 x p\n         \\<in> poly_vs.span {Bernstein_Poly_01 x p |x. x \\<le> p}\"\n    if \"x \\<in> {0..p}\" for x\n  proof -\n    have \"\\<exists>n. Bernstein_Poly_01 x p = Bernstein_Poly_01 n p \\<and> n \\<le> p\"\n      using that by force\n    then show \n      \"Bernstein_Poly_01 x p \\<in> poly_vs.span {Bernstein_Poly_01 n p |n. n \\<le> p}\"\n      by (simp add: poly_vs.span_base)\n  qed\n  thus ?thesis\n    apply (subst Bernstein_sum_01[OF hP])\n    apply (rule poly_vs.span_sum)\n    apply (rule poly_vs.span_scale)\n    by blast\nqed\n\nlemma Bernstein_Poly_01_span:\n  \"poly_vs.span {Bernstein_Poly_01 x p | x. x \\<le> p} \n      = {x. degree x \\<le> p}\"\n  apply (subst monom_span[symmetric])\n  apply (subst poly_vs.span_eq)\n  by (auto simp: monom_span degree_Bernstein_le\n      Bernstein_Poly_01_span1 degree_monom_eq)\n\nsubsection \\<open>Bernstein coefficients and changes\\<close>\n\ndefinition Bernstein_coeffs_01 :: \"nat \\<Rightarrow> real poly \\<Rightarrow> real list\" where \n  \"Bernstein_coeffs_01 p P = \n   [(inverse (real (p choose j)) * \n    coeff (reciprocal_poly p P \\<circ>\\<^sub>p [:1, 1:]) (p-j)). j \\<leftarrow> [0..<(p+1)]]\"\n\nlemma length_Bernstein_coeffs_01: \"length (Bernstein_coeffs_01 p P) = p + 1\"\n  by (auto simp: Bernstein_coeffs_01_def)\n\nlemma nth_default_Bernstein_coeffs_01: assumes \"degree P \\<le> p\"\n  shows \"nth_default 0 (Bernstein_coeffs_01 p P) i = \n         inverse (p choose i) * coeff (reciprocal_poly p P \\<circ>\\<^sub>p [:1, 1:]) (p-i)\"\n  apply (cases \"p = i\")\n  using assms by (auto simp: Bernstein_coeffs_01_def nth_default_append\n                  nth_default_Cons Nitpick.case_nat_unfold binomial_eq_0)\n\nlemma Bernstein_coeffs_01_sum: assumes \"degree P \\<le> p\"\n  shows \"P = (\\<Sum>j = 0..p. smult (nth_default 0 (Bernstein_coeffs_01 p P) j) \n             (Bernstein_Poly_01 j p))\"\n  apply (subst nth_default_Bernstein_coeffs_01[OF assms])\n  apply (subst Bernstein_sum_01[OF assms])\n  by argo\n\ndefinition Bernstein_changes_01 :: \"nat \\<Rightarrow> real poly \\<Rightarrow> int\" where\n  \"Bernstein_changes_01 p P = nat (changes (Bernstein_coeffs_01 p P))\"\n\nlemma Bernstein_changes_01_def': \n  \"Bernstein_changes_01 p P = nat (changes [(inverse (real (p choose j)) * \n     coeff (reciprocal_poly p P \\<circ>\\<^sub>p [:1, 1:]) (p-j)). j \\<leftarrow> [0..<p + 1]])\"\n  by (simp add: Bernstein_changes_01_def Bernstein_coeffs_01_def)\n\nlemma Bernstein_changes_01_eq_changes: \n  assumes hP: \"degree P \\<le> p\"\n  shows \"Bernstein_changes_01 p P = \n         changes (coeffs ((reciprocal_poly p P) \\<circ>\\<^sub>p [:1, 1:]))\"\nproof (subst Bernstein_changes_01_def')\n  have h: \n    \"map (\\<lambda>j. inverse (real (p choose j)) * \n     coeff (reciprocal_poly p P \\<circ>\\<^sub>p [:1, 1:]) (p - j)) [0..<p + 1] = \n     map (\\<lambda>j. inverse (real (p choose j)) * \n     nth_default 0 [nth_default 0 (coeffs (reciprocal_poly p P \\<circ>\\<^sub>p [:1, 1:]))\n                    (p - j). j \\<leftarrow> [0..<p + 1]] j) [0..<p + 1]\"\n  proof (rule map_cong)\n    fix x\n    assume \"x \\<in> set [0..<p+1]\"\n    hence hx: \"x \\<le> p\" by fastforce\n    moreover have 1:\n      \"length (map (\\<lambda>j. nth_default 0 \n       (coeffs (reciprocal_poly p P \\<circ>\\<^sub>p [:1, 1:])) (p - j)) [0..<p + 1]) \\<le> Suc p\"\n      by force\n    moreover have \"length (coeffs (reciprocal_poly p P \\<circ>\\<^sub>p [:1, 1:])) \\<le> Suc p\"\n    proof (cases \"P=0\")\n      case False\n      then have \"reciprocal_poly p P \\<circ>\\<^sub>p [:1, 1:] \\<noteq> 0\" \n        using hP by (simp add: Missing_Polynomial.pcompose_eq_0 reciprocal_0_iff)\n      moreover have \"Suc (degree (reciprocal_poly p P \\<circ>\\<^sub>p [:1, 1:])) \\<le> Suc p\"\n        using hP by (auto simp: degree_pcompose degree_reciprocal)\n      ultimately show ?thesis \n        using length_coeffs_degree by force\n    qed (auto simp: reciprocal_0)\n    ultimately have h: \n      \"nth_default 0 (map (\\<lambda>j. nth_default 0 (coeffs \n       (reciprocal_poly p P \\<circ>\\<^sub>p [:1, 1:])) (p - j)) [0..<p + 1]) x =\n       nth_default 0 (coeffs (reciprocal_poly p P \\<circ>\\<^sub>p [:1, 1:])) (p - x)\"\n      (is \"?L = ?R\")\n    proof -\n      have \"?L = (map (\\<lambda>j. nth_default 0 (coeffs\n            (reciprocal_poly p P \\<circ>\\<^sub>p [:1, 1:])) (p - j)) [0..<p + 1]) ! x\"\n        using hx by (auto simp: nth_default_nth)\n      also have \"... =  nth_default 0 \n          (coeffs (reciprocal_poly p P \\<circ>\\<^sub>p [:1, 1:])) (p - [0..<p + 1] ! x)\"\n        apply (subst nth_map)\n        using hx by auto\n      also have \"... = ?R\"\n        apply (subst nth_upt)\n        using hx by auto\n      finally show ?thesis .\n    qed\n    show \"inverse (real (p choose x)) *\n          coeff (reciprocal_poly p P \\<circ>\\<^sub>p [:1, 1:]) (p - x) =\n          inverse (real (p choose x)) *\n          nth_default 0 (map (\\<lambda>j. nth_default 0 \n          (coeffs (reciprocal_poly p P \\<circ>\\<^sub>p [:1, 1:])) (p - j)) [0..<p + 1]) x\"\n      apply (subst h)\n      apply (subst nth_default_coeffs_eq)\n      by blast\n  qed auto\n\n  have 1: \n    \"rev (map (\\<lambda>j. nth_default 0 (coeffs (reciprocal_poly p P \\<circ>\\<^sub>p [:1, 1:])) \n     (p - j)) [0..<p + 1]) = map (\\<lambda>j. nth_default 0 (coeffs \n     (reciprocal_poly p P \\<circ>\\<^sub>p [:1, 1:])) j) [0..<p + 1]\"\n  proof (subst rev_map, rule map_cong')\n    have \"\\<And>q. (q \\<ge> p \\<longrightarrow> rev [q-p..<q+1] = map ((-) q) [0..<p+1])\"\n    proof (induction p)\n      case 0\n      then show ?case by simp\n    next\n      case (Suc p)\n      have IH: \"\\<And>q. (q \\<ge> p \\<longrightarrow> rev [q-p..<q+1] = map ((-) q) [0..<p+1])\"\n        using Suc.IH by blast\n      show ?case\n      proof\n        assume hq: \"Suc p \\<le> q\"\n        then have h: \"rev [q - p..<q + 1] = map ((-) (q)) [0..<p + 1]\"\n          apply (subst IH)\n          using hq by auto\n        have \"[q - Suc p..<q + 1] = (q - Suc p) # [q - p..<q + 1]\"\n          by (simp add: Suc_diff_Suc Suc_le_lessD hq upt_conv_Cons)\n        hence \"rev [q - Suc p..<q + 1] = rev [q - p..<q + 1] @ [q - Suc p]\"\n          by force\n        also have \"... = map ((-) (q)) [0..<p + 1] @ [q - Suc p]\"\n          using h by blast\n        also have \"... = map ((-) q) [0..<Suc p + 1]\"\n          by force\n        finally show \"rev [q - Suc p..<q + 1] = map ((-) q) [0..<Suc p + 1]\" .\n      qed\n    qed\n    thus \"rev [0..<p + 1] = map ((-) p) [0..<p + 1]\"\n      by force\n  next\n    fix y\n    assume \"y \\<in> set [0..<p + 1]\"\n    hence \"y \\<le> p\" by fastforce\n    thus \"nth_default 0 (coeffs (reciprocal_poly p P \\<circ>\\<^sub>p [:1, 1:])) (p - (p - y)) =\n          nth_default 0 (coeffs (reciprocal_poly p P \\<circ>\\<^sub>p [:1, 1:])) y\"\n      by fastforce\n  qed\n\n  have 2: \"\\<And> f. f \\<noteq> 0 \\<longrightarrow> degree f \\<le> p \\<longrightarrow>\n           map (nth_default 0 (coeffs f)) [0..<p + 1] = \n           coeffs f @ replicate (p - degree f) 0\"\n  proof (induction p)\n    case 0\n    then show ?case by (auto simp: degree_0_iff)\n  next\n    fix f\n    case (Suc p)\n    hence IH: \"(f \\<noteq> 0 \\<longrightarrow>\n                degree f \\<le> p \\<longrightarrow>\n                map (nth_default 0 (coeffs f)) [0..<p + 1] =\n                coeffs f @ replicate (p - degree f) 0)\" by blast\n    then show ?case\n    proof (cases)\n      assume h': \"Suc p = degree f\"\n      hence h: \"[0..<Suc p + 1] = [0..<length (coeffs f)]\" \n        by (metis add_is_0 degree_0 length_coeffs plus_1_eq_Suc zero_neq_one)\n      thus ?thesis\n        apply (subst h)\n        apply (subst map_nth_default)\n        using h' by fastforce\n    next\n      assume h': \"Suc p \\<noteq> degree f\"\n      show ?thesis\n      proof\n        assume hf: \"f \\<noteq> 0\"\n        show \"degree f \\<le> Suc p \\<longrightarrow>\n            map (nth_default 0 (coeffs f)) [0..<Suc p + 1] =\n            coeffs f @ replicate (Suc p - degree f) 0\"\n        proof\n          assume \"degree f \\<le> Suc p\"\n          hence 1: \"degree f \\<le> p\" using h' by fastforce\n          hence 2: \"map (nth_default 0 (coeffs f)) [0..<p + 1] =\n                  coeffs f @ replicate (p - degree f) 0\" using IH hf by blast\n          have \"map (nth_default 0 (coeffs f)) [0..<Suc p + 1] = \n                map (nth_default 0 (coeffs f)) [0..<p + 1] @\n                     [nth_default 0 (coeffs f) (Suc p)]\"\n            by fastforce\n          also have\n            \"... = coeffs f @ replicate (p - degree f) 0 @ [coeff f (Suc p)]\"\n            using 2 \n            by (auto simp: nth_default_coeffs_eq)\n          also have \"... = coeffs f @ replicate (p - degree f) 0 @ [0]\"\n            using \\<open>degree f \\<le> Suc p\\<close> h' le_antisym le_degree by blast\n          also have \"... = coeffs f @ replicate (Suc p - degree f) 0\" using 1\n            by (simp add: Suc_diff_le replicate_app_Cons_same)\n          finally show \"map (nth_default 0 (coeffs f)) [0..<Suc p + 1] =\n                coeffs f @ replicate (Suc p - degree f) 0\" .\n        qed\n      qed\n    qed\n  qed\n  \n  thus \"int (nat (changes (map (\\<lambda>j. inverse (real (p choose j)) *\n        coeff (reciprocal_poly p P \\<circ>\\<^sub>p [:1, 1:]) (p - j)) [0..<p + 1]))) =\n        changes (coeffs (reciprocal_poly p P \\<circ>\\<^sub>p [:1, 1:]))\"\n  proof cases\n    assume hP: \"P = 0\"\n    show \"int (nat (changes (map (\\<lambda>j. inverse (real (p choose j)) *\n          coeff (reciprocal_poly p P \\<circ>\\<^sub>p [:1, 1:]) (p - j)) [0..<p + 1]))) =\n          changes (coeffs (reciprocal_poly p P \\<circ>\\<^sub>p [:1, 1:]))\" (is \"?L = ?R\")\n    proof -\n      have \"?L = int (nat (changes (map (\\<lambda>j. 0::real) [0..<p+1])))\"\n        using hP by (auto simp: reciprocal_0 changes_nonneg)\n      also have \"... = 0\"\n        apply (induction p)\n        by (auto simp: map_replicate_trivial changes_nonneg\n            replicate_app_Cons_same)\n      also have \"0 = changes ([]::real list)\" by simp\n      also have \"... = ?R\" using hP by (auto simp: reciprocal_0)\n      finally show ?thesis .\n    qed\n  next\n    assume hP': \"P \\<noteq> 0\"\n    thus ?thesis\n      apply (subst h)\n      apply (subst changes_scale)\n        apply auto[2]\n      apply (subst changes_rev[symmetric])\n      apply (subst 1)\n      apply (subst 2)\n      apply (simp add: pcompose_eq_0 hP reciprocal_0_iff)\n      using assms apply (auto simp: degree_reciprocal)[1]\n      by (auto simp: changes_append_replicate_0 changes_nonneg)\n  qed\nqed\n\nlemma Bernstein_changes_01_test: fixes P::\"real poly\"\n  assumes hP: \"degree P \\<le> p\" and h0: \"P \\<noteq> 0\"\n  shows \"proots_count P {x. 0 < x \\<and> x < 1} \\<le> Bernstein_changes_01 p P \\<and>\n        even (Bernstein_changes_01 p P - proots_count P {x. 0 < x \\<and> x < 1})\"\nproof -\n  let ?Q = \"(reciprocal_poly p P) \\<circ>\\<^sub>p [:1, 1:]\"\n\n  have 1: \"changes (coeffs ?Q) \\<ge> proots_count ?Q {x. 0 < x} \\<and> \n        even (changes (coeffs ?Q) - proots_count ?Q {x. 0 < x})\"\n    apply (rule descartes_sign)\n    by (simp add: Missing_Polynomial.pcompose_eq_0 h0 hP reciprocal_0_iff)\n  \n  have \"((+) (1::real) ` Collect ((<) (0::real))) = {x. (1::real)<x}\"\n  proof\n    show \"{x::real. 1 < x} \\<subseteq> (+) 1 ` Collect ((<) 0)\"\n    proof\n      fix x::real assume \"x \\<in> {x. 1 < x}\"\n      hence \"1 < x\" by simp\n      hence \"-1 + x \\<in> Collect ((<) 0)\" by auto\n      hence \"1 + (-1 + x) \\<in> (+) 1 ` Collect ((<) 0)\" by blast\n      thus \"x \\<in> (+) 1 ` Collect ((<) 0)\" by argo\n    qed\n  qed auto\n  hence 2:  \"proots_count P {x. 0 < x \\<and> x < 1} = proots_count ?Q {x. 0 < x}\"\n    using assms\n    by (auto simp: proots_pcompose reciprocal_0_iff proots_count_reciprocal')\n  \n  show ?thesis\n    apply (subst Bernstein_changes_01_eq_changes[OF hP])\n    apply (subst Bernstein_changes_01_eq_changes[OF hP])\n    apply (subst 2)\n    apply (subst 2)\n    by (rule 1)\nqed\n\nsubsection \\<open>Expression as a Bernstein sum\\<close>\n\nlemma Bernstein_coeffs_01_0: \"Bernstein_coeffs_01 p 0 = replicate (p+1) 0\"\n  by (auto simp: Bernstein_coeffs_01_def reciprocal_0 map_replicate_trivial\n      replicate_append_same)\n\nlemma Bernstein_coeffs_01_1: \"Bernstein_coeffs_01 p 1 = replicate (p+1) 1\"\nproof -\n  have \"Bernstein_coeffs_01 p 1 =\n     map (\\<lambda>j. inverse (real (p choose j)) *\n     coeff (\\<Sum>k\\<le>p. smult (real (p choose k)) ([:0, 1:] ^ k)) (p - j)) [0..<(p+1)]\"\n    by (auto simp: Bernstein_coeffs_01_def reciprocal_1 monom_altdef\n        hom_distribs pcompose_pCons poly_0_coeff_0[symmetric] poly_binomial)\n  also have \"... = map (\\<lambda>j. inverse (real (p choose j)) * \n             real (p choose (p - j))) [0..<(p+1)]\"\n    by (auto simp: monom_altdef[symmetric] coeff_sum binomial)\n  also have \"... = map (\\<lambda>j. 1) [0..<(p+1)]\"\n    apply (rule map_cong)\n    subgoal by argo\n    subgoal apply (subst binomial_symmetric)\n      by auto\n    done\n  also have \"... = replicate (p+1) 1\"\n    by (auto simp: map_replicate_trivial replicate_append_same)\n  finally show ?thesis .\nqed\n\nlemma Bernstein_coeffs_01_x: assumes \"p \\<noteq> 0\"\n  shows \"Bernstein_coeffs_01 p (monom 1 1) = [i/p. i \\<leftarrow> [0..<(p+1)]]\"\nproof -\n  have \n    \"Bernstein_coeffs_01 p (monom 1 1) = map (\\<lambda>j. inverse (real (p choose j)) *\n     coeff (monom 1 (p - Suc 0) \\<circ>\\<^sub>p [:1, 1:]) (p - j)) [0..<(p+1)]\"\n    using assms by (auto simp: Bernstein_coeffs_01_def reciprocal_monom)\n  also have \n    \"... = map (\\<lambda>j. inverse (real (p choose j)) *\n     (\\<Sum>k\\<le>p - Suc 0. coeff (monom (real (p -  1 choose k)) k) (p - j))) [0..<(p+1)]\"\n    by (auto simp: monom_altdef hom_distribs pcompose_pCons poly_binomial coeff_sum)\n  also have\"... = map (\\<lambda>j. inverse (real (p choose j)) *\n            real (p -  1 choose (p - j))) [0..<(p+1)]\"\n    by auto\n  also have \"... = map (\\<lambda>j. j/p) [0..<(p+1)]\"\n  proof (rule map_cong)\n    fix x assume \"x \\<in> set [0..<(p+1)]\"\n    hence \"x \\<le> p\" by force\n    thus \"inverse (real (p choose x)) * real (p - 1 choose (p - x)) =\n          real x / real p\"\n    proof (cases \"x = 0\")\n      show \"x = 0 \\<Longrightarrow> ?thesis\"\n        using assms by fastforce\n      assume 1: \"x \\<le> p\" and 2: \"x \\<noteq> 0\"\n      hence \"p - x \\<le> p - 1\" by force\n      hence \"(p - 1 choose (p - x)) = (p - 1 choose (x - 1))\"\n        apply (subst binomial_symmetric)\n        using 1 2 by auto\n      hence \"x * (p choose x) = p * (p - 1 choose (p - x))\"\n         using 2 times_binomial_minus1_eq by simp\n       hence \"real x * real (p choose x) = real p * real (p - 1 choose (p - x))\"\n         by (metis of_nat_mult)\n       thus ?thesis using 1 2\n         by (auto simp: divide_simps)\n    qed\n  qed blast\n  finally show ?thesis .\nqed\n\nlemma Bernstein_coeffs_01_add: \n  assumes \"degree P \\<le> p\" and \"degree Q \\<le> p\"\n  shows \"nth_default 0 (Bernstein_coeffs_01 p (P + Q)) i = \n    nth_default 0 (Bernstein_coeffs_01 p P) i +\n    nth_default 0 (Bernstein_coeffs_01 p Q) i\"\n  using assms by (auto simp: nth_default_Bernstein_coeffs_01 degree_add_le\n                    reciprocal_add pcompose_add algebra_simps)\n\nlemma Bernstein_coeffs_01_smult: \n  assumes \"degree P \\<le> p\"\n  shows \"nth_default 0 (Bernstein_coeffs_01 p (smult a P)) i =\n          a * nth_default 0 (Bernstein_coeffs_01 p P) i\"\n  using assms\n  by (auto simp: nth_default_Bernstein_coeffs_01 reciprocal_smult\n      pcompose_smult)\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/Three_Circles/Bernstein_01.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8539127641048444, "lm_q2_score": 0.824461928533133, "lm_q1q2_score": 0.7040185642929383}}
{"text": "section \\<open>Missing Matrix Operations\\<close>\n\ntext \\<open>In this theory we provide an operation that can change a single\n  row in a matrix efficiently, and all other rows in the matrix implementation\n  will be reused.\\<close>\n\n(* TODO: move this part into JNF-AFP-entry *)\n\ntheory Matrix_Change_Row\n  imports \n    Jordan_Normal_Form.Matrix_IArray_Impl\n    Polynomial_Interpolation.Missing_Unsorted\nbegin\n\ndefinition change_row :: \"nat \\<Rightarrow> (nat \\<Rightarrow> 'a \\<Rightarrow> 'a) \\<Rightarrow> 'a mat \\<Rightarrow> 'a mat\" where\n  \"change_row k f A = mat (dim_row A) (dim_col A) (\\<lambda> (i,j). \n     if i = k then f j (A $$ (k,j)) else A $$ (i,j))\"\n\nlemma change_row_carrier[simp]: \n  \"(change_row k f A \\<in> carrier_mat nr nc) = (A \\<in> carrier_mat nr nc)\" \n  \"dim_row (change_row k f A) = dim_row A\" \n  \"dim_col (change_row k f A) = dim_col A\" \n  unfolding change_row_def carrier_mat_def by auto\n\nlemma change_row_index[simp]: \"A \\<in> carrier_mat nr nc \\<Longrightarrow> i < nr \\<Longrightarrow> j < nc \\<Longrightarrow>\n  change_row k f A $$ (i,j) = (if i = k then f j (A $$ (k,j)) else A $$ (i,j))\" \n  \"i < dim_row A \\<Longrightarrow> j < dim_col A \\<Longrightarrow> change_row k f A $$ (i,j) = (if i = k then f j (A $$ (k,j)) else A $$ (i,j))\" \n  unfolding change_row_def by auto\n\nlift_definition change_row_impl :: \"nat \\<Rightarrow> (nat \\<Rightarrow> 'a \\<Rightarrow> 'a) \\<Rightarrow> 'a mat_impl \\<Rightarrow> 'a mat_impl\" is\n  \"\\<lambda> k f (nr,nc,A). let Ak = IArray.sub A k; Arows = IArray.list_of A;\n     Ak' = IArray.IArray (map (\\<lambda> (i,c). f i c) (zip [0 ..< nc] (IArray.list_of Ak)));\n     A' = IArray.IArray (Arows [k := Ak'])\n     in (nr,nc,A')\" \nproof (auto, goal_cases)\n  case (1 k f nc b row)\n  show ?case \n  proof (cases b)\n    case (IArray rows)\n    with 1 have \"row \\<in> set rows \\<or> k < length rows \n       \\<and> row = IArray (map (\\<lambda> (i,c). f i c) (zip [0 ..< nc] (IArray.list_of (rows ! k))))\"\n      by (cases \"k < length rows\", auto simp: set_list_update dest: in_set_takeD in_set_dropD)\n    with 1 IArray show ?thesis by (cases, auto)\n  qed\nqed\n\nlemma change_row_code[code]: \"change_row k f (mat_impl A) = (if k < dim_row_impl A \n  then mat_impl (change_row_impl k f A) \n  else Code.abort (STR ''index out of bounds in change_row'') (\\<lambda> _. change_row k f (mat_impl A)))\"\n  (is \"?l = ?r\")\nproof (cases \"k < dim_row_impl A\")\n  case True\n  hence id: \"?r = mat_impl (change_row_impl k f A)\" by simp\n  show ?thesis unfolding id unfolding change_row_def\n  proof (rule eq_matI, goal_cases)\n    case (1 i j)\n    thus ?case using True\n      by (transfer, auto simp: mk_mat_def)\n  qed (transfer, auto)+\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/Modular_arithmetic_LLL_and_HNF_algorithms/Matrix_Change_Row.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127566694178, "lm_q2_score": 0.8244619306896955, "lm_q1q2_score": 0.7040185600042284}}
{"text": "section \"Equality\"\n\ntheory Derive_Eq\n  imports Main \"../Derive\" Derive_Datatypes\nbegin\n\nclass eq =\n  fixes eq :: \"'a \\<Rightarrow> 'a \\<Rightarrow> bool\"\n\n(* Manual instances for nat, unit, prod, and sum *)\ninstantiation nat and unit:: eq\nbegin\n  definition eq_nat : \"eq (x::nat) y \\<longleftrightarrow> x = y\"\n  definition eq_unit_def: \"eq (x::unit) y \\<longleftrightarrow> True\"\n  instance ..\nend\n\ninstantiation prod and sum :: (eq, eq) eq\nbegin\n  definition eq_prod_def: \"eq x y \\<longleftrightarrow> (eq (fst x) (fst y)) \\<and> (eq (snd x) (snd y))\"\n  definition eq_sum_def: \"eq x y = (case x of Inl a \\<Rightarrow> (case y of Inl b \\<Rightarrow> eq a b | Inr b \\<Rightarrow> False)\n                                            | Inr a \\<Rightarrow> (case y of Inl b \\<Rightarrow> False | Inr b \\<Rightarrow> eq a b))\"\n\n  instance ..\nend  \n\n(* nonrecursive test *)\n\nderive_generic eq simple .\n\n(* some tests *)\nlemma \"eq (A 4) (A 4)\" by eval\nlemma \"eq (A 6) (A 4) \\<longleftrightarrow> False\" by eval\nlemma \"eq C C\" by eval\nlemma \"eq (B 4 5) (B 4 5)\" by eval\nlemma \"eq (B 4 4) (A 3) \\<longleftrightarrow> False\" by eval\nlemma \"eq C (A 4) \\<longleftrightarrow> False\" by eval\n\n(* type with parameter *)\n\nderive_generic eq either .\n\nlemma \"eq (L (3::nat)) (R 3) \\<longleftrightarrow> False\" by code_simp\nlemma \"eq (L (3::nat)) (L 3)\" by code_simp\nlemma \"eq (L (3::nat)) (L 4) \\<longleftrightarrow> False\" by code_simp\n\n(* recursive types *)\nderive_generic eq list .\n\n\nlemma \"eq ([]::(nat list)) []\" by eval\nlemma \"eq ([1,2,3]:: (nat list)) [1,2,3]\" by eval\nlemma \"eq [(1::nat)] [1,2] \\<longleftrightarrow> False\" by eval\n\nderive_generic eq tree .\n\nlemma \"eq Leaf Leaf\" by code_simp\nlemma \"eq (Node (1::nat) Leaf Leaf) Leaf \\<longleftrightarrow> False\" by eval\nlemma \"eq (Node (1::nat) Leaf Leaf) (Node (1::nat) Leaf Leaf)\" by eval\nlemma \"eq (Node (1::nat) (Node 2 Leaf Leaf) (Node 3 Leaf Leaf)) (Node (1::nat) (Node 2 Leaf Leaf) (Node 4 Leaf Leaf)) \n    \\<longleftrightarrow> False\" by eval\n\n(* mutually recursive types *)\n\nderive_generic eq even_nat .\nderive_generic eq exp .\n\nlemma \"eq Even_Zero Even_Zero\" by eval\nlemma \"eq Even_Zero (Even_Succ (Odd_Succ Even_Zero)) \\<longleftrightarrow> False\" by eval\nlemma \"eq (Odd_Succ (Even_Succ (Odd_Succ Even_Zero))) (Odd_Succ (Even_Succ (Odd_Succ Even_Zero)))\" by eval\nlemma \"eq (Odd_Succ (Even_Succ (Odd_Succ Even_Zero))) (Odd_Succ (Even_Succ (Odd_Succ (Even_Succ (Odd_Succ Even_Zero)))))\n    \\<longleftrightarrow> False\" by eval\n\nlemma \"eq (Const (1::nat)) (Const (1::nat))\" by code_simp\nlemma \"eq (Const (1::nat)) (Var (1::nat)) \\<longleftrightarrow> False\" by eval\nlemma \"eq (Term (Prod (Const (1::nat)) (Factor (Const (2::nat))))) (Term (Prod (Const (1::nat)) (Factor (Const (2::nat)))))\"\n    by code_simp\nlemma \"eq (Term (Prod (Const (1::nat)) (Factor (Const (2::nat))))) (Term (Prod (Const (1::nat)) (Factor (Const (3::nat)))))\n    \\<longleftrightarrow> False\" by code_simp\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_Eq.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8539127641048444, "lm_q2_score": 0.8244619199068831, "lm_q1q2_score": 0.7040185569268734}}
{"text": "section \\<open> Healthiness Conditions \\<close>\n\ntheory utp_healthy\n  imports utp_pred_laws utp_recursion\nbegin\n\nsubsection \\<open> Main Definitions \\<close>\n\ntext \\<open> We collect closure laws for healthiness conditions in the following theorem attribute. \\<close>\n\nnamed_theorems closure\n\ntype_synonym 'a health = \"'a pred \\<Rightarrow> 'a pred\"\n\ntext \\<open> A predicate $P$ is healthy, under healthiness function $H$, if $P$ is a fixed-point of $H$. \\<close>\n\ndefinition Healthy :: \"'\\<alpha> pred \\<Rightarrow> '\\<alpha> health \\<Rightarrow> bool\" (infix \"is\" 30)\n  where [pred]: \"P is H \\<equiv> (H P = P)\"\n\nlemma Healthy_def': \"P is H \\<longleftrightarrow> (H P = P)\"\n  unfolding Healthy_def by auto\n\nlemma Healthy_if: \"P is H \\<Longrightarrow> (H P = P)\"\n  unfolding Healthy_def by auto\n\nlemma Healthy_intro: \"H(P) = P \\<Longrightarrow> P is H\"\n  by (simp add: Healthy_def)\n\nabbreviation Healthy_carrier :: \"'\\<alpha> health \\<Rightarrow> '\\<alpha> pred set\" (\"\\<lbrakk>_\\<rbrakk>\\<^sub>H\")\nwhere \"\\<lbrakk>H\\<rbrakk>\\<^sub>H \\<equiv> {P. P is H}\"\n\nlemma Healthy_carrier_image:\n  \"A \\<subseteq> \\<lbrakk>\\<H>\\<rbrakk>\\<^sub>H \\<Longrightarrow> \\<H> ` A = A\"\n    by (auto simp add: image_def, (metis Healthy_if mem_Collect_eq subsetCE)+)\n\nlemma Healthy_carrier_Collect: \"A \\<subseteq> \\<lbrakk>H\\<rbrakk>\\<^sub>H \\<Longrightarrow> A = {H(P) | P. P \\<in> A}\"\n  by (simp add: Healthy_carrier_image Setcompr_eq_image)\n\nlemma Healthy_func:\n  \"\\<lbrakk> F \\<in> \\<lbrakk>\\<H>\\<^sub>1\\<rbrakk>\\<^sub>H \\<rightarrow> \\<lbrakk>\\<H>\\<^sub>2\\<rbrakk>\\<^sub>H; P is \\<H>\\<^sub>1 \\<rbrakk> \\<Longrightarrow> F(P) = \\<H>\\<^sub>2(F(P))\"\n  by (metis Healthy_if PiE mem_Collect_eq)\n\nlemma Healthy_comp:\n  \"\\<lbrakk> P is \\<H>\\<^sub>1; P is \\<H>\\<^sub>2 \\<rbrakk> \\<Longrightarrow> P is \\<H>\\<^sub>1 \\<circ> \\<H>\\<^sub>2\"\n  by (simp add: Healthy_def)\n    \nlemma Healthy_apply_closed:\n  assumes \"F \\<in> \\<lbrakk>H\\<rbrakk>\\<^sub>H \\<rightarrow> \\<lbrakk>H\\<rbrakk>\\<^sub>H\" \"P is H\"\n  shows \"F(P) is H\"\n  using assms by auto\n\nlemma Healthy_set_image_member:\n  \"\\<lbrakk> P \\<in> F ` A; \\<And> x. F x is H \\<rbrakk> \\<Longrightarrow> P is H\"\n  by blast\n\nlemma Healthy_case_prod: \n  \"\\<lbrakk> \\<And> x y. P x y is H \\<rbrakk> \\<Longrightarrow> case_prod P v is H\"\n  by (simp add: prod.case_eq_if)\n\nlemma Healthy_SUPREMUM:\n  \"A \\<subseteq> \\<lbrakk>H\\<rbrakk>\\<^sub>H \\<Longrightarrow> Sup (H ` A) = \\<Sqinter> A\"\n  by (drule Healthy_carrier_image, presburger)\n\nlemma Healthy_INFIMUM:\n  \"A \\<subseteq> \\<lbrakk>H\\<rbrakk>\\<^sub>H \\<Longrightarrow> Inf (H ` A) = \\<Squnion> A\"\n  by (drule Healthy_carrier_image, presburger)\n\nlemma Healthy_nu [closure]:\n  assumes \"mono F\" \"F \\<in> \\<lbrakk>id\\<rbrakk>\\<^sub>H \\<rightarrow> \\<lbrakk>H\\<rbrakk>\\<^sub>H\"\n  shows \"\\<nu> F is H\"\n  by (metis (mono_tags) Healthy_def Healthy_func assms eq_id_iff lfp_unfold)\n\nlemma Healthy_mu [closure]:\n  assumes \"mono F\" \"F \\<in> \\<lbrakk>id\\<rbrakk>\\<^sub>H \\<rightarrow> \\<lbrakk>H\\<rbrakk>\\<^sub>H\"\n  shows \"\\<mu> F is H\"\n  by (metis (mono_tags) Healthy_def Healthy_func assms eq_id_iff gfp_unfold)\n\nlemma Healthy_subset_member: \"\\<lbrakk> A \\<subseteq> \\<lbrakk>H\\<rbrakk>\\<^sub>H; P \\<in> A \\<rbrakk> \\<Longrightarrow> H(P) = P\"\n  using Healthy_if by blast\n  \nlemma is_Healthy_subset_member: \"\\<lbrakk> A \\<subseteq> \\<lbrakk>H\\<rbrakk>\\<^sub>H; P \\<in> A \\<rbrakk> \\<Longrightarrow> P is H\"\n  by blast\n\nsubsection \\<open> Properties of Healthiness Conditions \\<close>\n\ndefinition Idempotent :: \"'\\<alpha> health \\<Rightarrow> bool\" where\n  \"Idempotent(H) \\<longleftrightarrow> (\\<forall> P. H(H(P)) = H(P))\"\n\nabbreviation Monotonic :: \"'\\<alpha> health \\<Rightarrow> bool\" where\n  \"Monotonic(H) \\<equiv> mono H\"\n\ndefinition IMH :: \"'\\<alpha> health \\<Rightarrow> bool\" where\n  \"IMH(H) \\<longleftrightarrow> Idempotent(H) \\<and> Monotonic(H)\"\n\ndefinition Antitone :: \"'\\<alpha> health \\<Rightarrow> bool\" where\n  \"Antitone(H) \\<longleftrightarrow> (\\<forall> P Q. Q \\<sqsubseteq> P \\<longrightarrow> (H(P) \\<sqsubseteq> H(Q)))\"\n\ndefinition Conjunctive :: \"'\\<alpha> health \\<Rightarrow> bool\" where\n  \"Conjunctive(H) \\<longleftrightarrow> (\\<exists> Q. \\<forall> P. H(P) = (P \\<and> Q))\"\n\ndefinition FunctionalConjunctive :: \"'\\<alpha> health \\<Rightarrow> bool\" where\n  \"FunctionalConjunctive(H) \\<longleftrightarrow> (\\<exists> F. \\<forall> P. H(P) = (P \\<and> F(P)) \\<and> Monotonic(F))\"\n\ndefinition WeakConjunctive :: \"'\\<alpha> health \\<Rightarrow> bool\" where\n  \"WeakConjunctive(H) \\<longleftrightarrow> (\\<forall> P. \\<exists> Q. H(P) = (P \\<and> Q))\"\n\ndefinition Disjunctuous :: \"'\\<alpha> health \\<Rightarrow> bool\" where\n  [pred]: \"Disjunctuous H = (\\<forall> P Q. H(P \\<or> Q) = (H(P) \\<or> H(Q)))\"\n\ndefinition Continuous :: \"'\\<alpha> health \\<Rightarrow> bool\" where\n  [pred]: \"Continuous H = (\\<forall> A. A \\<noteq> {} \\<longrightarrow> H (\\<Sqinter> A) = \\<Sqinter> (H ` A))\"\n\nlemma Healthy_Idempotent:\n  \"Idempotent H \\<Longrightarrow> H(P) is H\"\n  by (simp add: Healthy_def Idempotent_def)\n\nlemma Healthy_range: \"Idempotent H \\<Longrightarrow> range H = \\<lbrakk>H\\<rbrakk>\\<^sub>H\"\n  by (auto simp add: image_def Healthy_if Healthy_Idempotent, metis Healthy_if)\n\nlemma Idempotent_id [simp]: \"Idempotent id\"\n  by (simp add: Idempotent_def)\n\nlemma Idempotent_comp [intro]:\n  \"\\<lbrakk> Idempotent f; Idempotent g; f \\<circ> g = g \\<circ> f \\<rbrakk> \\<Longrightarrow> Idempotent (f \\<circ> g)\"\n  by (auto simp add: Idempotent_def comp_def, metis+)\n\nlemma Idempotent_image: \"Idempotent f \\<Longrightarrow> f ` (f ` A) = (f ` A)\"\n  by (metis (mono_tags, lifting) Idempotent_def image_cong image_image)\n\nnamed_theorems mono\n\nlemma Monotonic_refine: \"Monotonic F \\<longleftrightarrow> (\\<forall> P Q. P \\<sqsubseteq> Q \\<longrightarrow> F(P) \\<sqsubseteq> F(Q))\"\n  by (metis monoE monoI pred_ref_iff_le)\n\nlemma Monotonic_id [simp]: \"Monotonic id\"\n  by (simp add: monoI)\n\nlemma Monotonic_id' [mono]: \n  \"mono (\\<lambda> X. X)\" \n  by (simp add: monoI)\n    \nlemma Monotonic_const [mono]:\n  \"Monotonic (\\<lambda> x. c)\"\n  by (simp add: mono_def)\n    \nlemma Monotonic_comp [intro, mono]:\n  \"\\<lbrakk> Monotonic f; Monotonic g \\<rbrakk> \\<Longrightarrow> Monotonic (f \\<circ> g)\"\n  by (simp add: mono_def)\n\nlemma Monotonic_sup [mono]:\n  assumes \"Monotonic P\" \"Monotonic Q\"\n  shows \"Monotonic (\\<lambda> X. P X \\<sqinter> Q X)\"\n  using assms unfolding mono_def by (meson sup_mono)\n\nlemma Monotonic_disj [mono]:\n  assumes \"Monotonic P\" \"Monotonic Q\"\n  shows \"Monotonic (\\<lambda> X. P(X) \\<or> Q(X))\"\n  by (insert assms, simp add: disj_pred_def Monotonic_sup)\n\nlemma Monotonic_cond:\n  assumes \"Monotonic P\" \"Monotonic Q\"\n  shows \"Monotonic (\\<lambda> X. P(X) \\<triangleleft> b \\<triangleright> Q(X))\"\n  by (insert assms, simp add: mono_def pred le_fun_def)\n    \nlemma Conjuctive_Idempotent:\n  \"Conjunctive(H) \\<Longrightarrow> Idempotent(H)\"\n  by (auto simp add: Conjunctive_def Idempotent_def conj_pred_def)\n\nlemma Conjunctive_Monotonic:\n  \"Conjunctive(H) \\<Longrightarrow> Monotonic(H)\"\n  unfolding Conjunctive_def mono_def\n  by (metis (no_types, opaque_lifting) conj_pred_def le_inf_iff order.trans order_refl)\n\nlemma Conjunctive_conj:\n  assumes \"Conjunctive(HC)\"\n  shows \"HC(P \\<and> Q) = (HC(P) \\<and> Q)\"\n  using assms unfolding Conjunctive_def\n  by (metis conj_pred_def inf.commute inf_sup_aci(2))\n\nlemma Conjunctive_distr_conj:\n  assumes \"Conjunctive(HC)\"\n  shows \"HC(P \\<and> Q) = (HC(P) \\<and> HC(Q))\"\n  using assms unfolding Conjunctive_def\n  by (metis Conjunctive_conj assms conj_pred_def inf.right_idem inf_sup_aci(2))\n\nlemma Conjunctive_distr_disj:\n  assumes \"Conjunctive(HC)\"\n  shows \"HC(P \\<or> Q) = (HC(P) \\<or> HC(Q))\"\n  using assms unfolding Conjunctive_def\n  by (metis conj_pred_def disj_pred_def inf_sup_distrib2)\n\nlemma Conjunctive_distr_cond:\n  assumes \"Conjunctive(HC)\"\n  shows \"HC(P \\<triangleleft> b \\<triangleright> Q) = (HC(P) \\<triangleleft> b \\<triangleright> HC(Q))\"\n  using assms unfolding Conjunctive_def\n  apply pred_simp\n  by force\n  \nlemma FunctionalConjunctive_Monotonic:\n  \"FunctionalConjunctive(H) \\<Longrightarrow> Monotonic(H)\"\n  unfolding FunctionalConjunctive_def\n  by (smt (verit, del_insts) conj_pred_def dual_order.trans le_inf_iff mono_def order_refl)\n\nlemma WeakConjunctive_Refinement:\n  assumes \"WeakConjunctive(HC)\"\n  shows \"P \\<sqsubseteq> HC(P)\"\n  using assms unfolding WeakConjunctive_def\n  by (metis conj_pred_def inf1D1 pred_refine_iff)\n\nlemma WeakCojunctive_Healthy_Refinement:\n  assumes \"WeakConjunctive(HC)\" and \"P is HC\"\n  shows \"HC(P) \\<sqsubseteq> P\"\n  using assms unfolding WeakConjunctive_def Healthy_def by simp\n\nlemma WeakConjunctive_implies_WeakConjunctive:\n  \"Conjunctive(H) \\<Longrightarrow> WeakConjunctive(H)\"\n  unfolding WeakConjunctive_def Conjunctive_def by pred_auto\n\nlemma Disjunctuous_Monotonic: \"Disjunctuous H \\<Longrightarrow> Monotonic H\"\n  by (metis (no_types, lifting) Disjunctuous_def disj_pred_def le_iff_sup mono_def)\n\nlemma ContinuousD [dest]: \"\\<lbrakk> Continuous H; A \\<noteq> {} \\<rbrakk> \\<Longrightarrow> H (\\<Sqinter> A) = (\\<Sqinter> P\\<in>A. H(P))\"\n  by (simp add: Continuous_def)\n\nlemma Continuous_Disjunctous: \"Continuous H \\<Longrightarrow> Disjunctuous H\"\n  apply (auto simp add: Continuous_def Disjunctuous_def)\n  by (metis SUP_insert Sup_insert cSup_singleton disj_pred_def insert_not_empty)\n\nlemma Continuous_choice_dist: \"Continuous H \\<Longrightarrow> H(P \\<sqinter> Q) = H(P) \\<sqinter> H(Q)\"\n  using Continuous_Disjunctous Disjunctuous_def\n  by (metis disj_pred_def)\n\nlemma Continuous_Monotonic [closure]: \"Continuous H \\<Longrightarrow> Monotonic H\"\n  by (simp add: Continuous_Disjunctous Disjunctuous_Monotonic)\n\nlemma Continuous_comp [intro]:\n  \"\\<lbrakk> Continuous f; Continuous g \\<rbrakk> \\<Longrightarrow> Continuous (f \\<circ> g)\"\n  unfolding Continuous_def by (simp, blast)\n\nlemma Continuous_const [closure]: \"Continuous (\\<lambda> X. P)\"\n  by pred_auto\n\n\n\ntext \\<open> Closure laws derived from continuity \\<close>\n\nlemma Sup_Continuous_closed [closure]:\n  \"\\<lbrakk> Continuous H; \\<And> i. i \\<in> A \\<Longrightarrow> P(i) is H; A \\<noteq> {} \\<rbrakk> \\<Longrightarrow> (\\<Sqinter> i\\<in>A. P(i)) is H\"\n  by (drule ContinuousD[of H \"P ` A\"], auto) (metis (no_types, lifting) Healthy_def' SUP_cong image_image)\n\n(*\nlemma UINF_mem_Continuous_closed [closure]:\n  \"\\<lbrakk> Continuous H; \\<And> i. i \\<in> A \\<Longrightarrow> P(i) is H; A \\<noteq> {} \\<rbrakk> \\<Longrightarrow> (\\<Union> i\\<in>A. P(i)) is H\"\n  by (simp add: Sup_Continuous_closed UINF_as_Sup_collect)\n*)\n\nlemma Sup_mem_Continuous_closed_pair [closure]:\n  assumes \"Continuous H\" \"\\<And> i j. (i, j) \\<in> A \\<Longrightarrow> P i j is H\" \"A \\<noteq> {}\"\n  shows \"(\\<Sqinter> (i,j)\\<in>A. P i j) is H\"\n  by (simp add: Sup_Continuous_closed assms split_beta)\n\nlemma Sup_mem_Continuous_closed_triple:\n  assumes \"Continuous H\" \"\\<And> i j k. (i, j, k) \\<in> A \\<Longrightarrow> P i j k is H\" \"A \\<noteq> {}\"\n  shows \"(\\<Sqinter> (i,j,k)\\<in>A. P i j k) is H\"\n  by (simp add: Sup_Continuous_closed assms split_beta)\n\nlemma Sup_mem_Continuous_closed_quad:\n  assumes \"Continuous H\" \"\\<And> i j k l. (i, j, k, l) \\<in> A \\<Longrightarrow> P i j k l is H\" \"A \\<noteq> {}\"\n  shows \"(\\<Sqinter> (i,j,k,l)\\<in>A. P i j k l) is H\"\n  by (simp add: Sup_Continuous_closed assms split_beta)\n\nlemma Sup_mem_Continuous_closed_quint:\n  assumes \"Continuous H\" \"\\<And> i j k l m. (i, j, k, l, m) \\<in> A \\<Longrightarrow> P i j k l m is H\" \"A \\<noteq> {}\"\n  shows \"(\\<Sqinter> (i,j,k,l,m)\\<in>A. P i j k l m) is H\"\n  by (simp add: Sup_Continuous_closed assms split_beta)\n\ntext \\<open> All continuous functions are also Scott-continuous \\<close>\n\nlemma sup_continuous_Continuous [closure]: \"Continuous F \\<Longrightarrow> sup_continuous F\"\n  by (auto simp add: Continuous_def sup_continuous_def)\n\nlemma Inf_healthy: \"A \\<subseteq> \\<lbrakk>H\\<rbrakk>\\<^sub>H \\<Longrightarrow> (\\<Squnion> P\\<in>A. F(P)) = (\\<Squnion> P\\<in>A. F(H(P)))\"\n  by (rule INF_cong, auto simp add: Healthy_subset_member)\n\nlemma Sup_healthy: \"A \\<subseteq> \\<lbrakk>H\\<rbrakk>\\<^sub>H \\<Longrightarrow> (\\<Sqinter> P\\<in>A. F(P)) = (\\<Sqinter> P\\<in>A. F(H(P)))\"\n  by (rule SUP_cong, auto simp add: Healthy_subset_member)\n  \nend", "meta": {"author": "isabelle-utp", "repo": "UTP", "sha": "fc446b72cc3620e1d013ccd4d37aa693fb64ba59", "save_path": "github-repos/isabelle/isabelle-utp-UTP", "path": "github-repos/isabelle/isabelle-utp-UTP/UTP-fc446b72cc3620e1d013ccd4d37aa693fb64ba59/utp_healthy.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8539127455162773, "lm_q2_score": 0.8244619285331332, "lm_q1q2_score": 0.7040185489673725}}
{"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_MainRLT\nbegin\n\ntext \\<open>Thanks to suggestions by James Margetson\\<close>\n\ndefinition setle :: \"'a set \\<Rightarrow> 'a::ord \\<Rightarrow> bool\"  (infixl \\<open>*<=\\<close> 70)\n  where \"S *<= x = (\\<forall>y\\<in>S. y \\<le> x)\"\n\ndefinition setge :: \"'a::ord \\<Rightarrow> 'a set \\<Rightarrow> bool\"  (infixl \\<open><=*\\<close> 70)\n  where \"x <=* S = (\\<forall>y\\<in>S. x \\<le> y)\"\n\n\nsubsection \\<open>Rules for the Relations \\<open>*<=\\<close> and \\<open><=*\\<close>\\<close>\n\nlemma setleI: \"\\<forall>y\\<in>S. y \\<le> x \\<Longrightarrow> S *<= x\"\n  by (simp add: setle_def)\n\nlemma setleD: \"S *<= x \\<Longrightarrow> y\\<in>S \\<Longrightarrow> y \\<le> x\"\n  by (simp add: setle_def)\n\nlemma setgeI: \"\\<forall>y\\<in>S. x \\<le> y \\<Longrightarrow> x <=* S\"\n  by (simp add: setge_def)\n\nlemma setgeD: \"x <=* S \\<Longrightarrow> y\\<in>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 \\<in> 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>\\<open>leastP\\<close>, \\<^term>\\<open>ub\\<close> and \\<^term>\\<open>lub\\<close>\\<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 \\<in> 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 \\<in> 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 \\<in> 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 \\<in> 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 \\<in> R\"\n  by (simp add: isUb_def)\n\nlemma isUbI: \"S *<= x \\<Longrightarrow> x \\<in> 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 \\<in> 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>\\<open>greatestP\\<close>, \\<^term>\\<open>isLb\\<close> and \\<^term>\\<open>isGlb\\<close>\\<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 \\<in> 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 \\<in> 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 \\<in> 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 \\<in> 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 \\<in> R\"\n  by (simp add: isLb_def)\n\nlemma isLbI: \"x <=* S \\<Longrightarrow> x \\<in> 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 \\<open>range X\\<close> *)\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": "dtraytel", "repo": "HOLRLT", "sha": "e9029da59bb3af0c835604a65308498f9696a364", "save_path": "github-repos/isabelle/dtraytel-HOLRLT", "path": "github-repos/isabelle/dtraytel-HOLRLT/HOLRLT-e9029da59bb3af0c835604a65308498f9696a364/HOLRLT/Library/Lub_Glb.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920116079208, "lm_q2_score": 0.8791467643431002, "lm_q1q2_score": 0.7039257912404716}}
{"text": "(*  \n    Title:      Echelon_Form_Det_IArrays.thy\n    Author:     Jose Divas\u00f3n <jose.divasonm at unirioja.es>\n    Author:     Jes\u00fas Aransay <jesus-maria.aransay at unirioja.es>\n*)\n\nsection\\<open>Determinant of matrices computed using immutable arrays\\<close>\n\ntheory Echelon_Form_Det_IArrays\nimports \n  Echelon_Form_Det\n  Echelon_Form_IArrays\nbegin\n\nsubsection\\<open>Definitions\\<close>\n\ndefinition echelon_form_of_column_k_det_iarrays :: \n          \"'a::{bezout_ring} \\<times> 'a iarray iarray \\<times> nat \\<times> ('a \\<Rightarrow> 'a \\<Rightarrow> 'a \\<times> 'a \\<times> 'a \\<times> 'a \\<times> 'a) \n          \\<Rightarrow> nat \n          \\<Rightarrow> 'a \\<times> 'a iarray iarray \\<times> nat \\<times> ('a \\<Rightarrow> 'a \\<Rightarrow> 'a \\<times> 'a \\<times> 'a \\<times> 'a \\<times> 'a)\"\n where  \n \"echelon_form_of_column_k_det_iarrays A' k = \n    (let (det_P, A, i, bezout) = A'\n      in if ((i \\<noteq> nrows_iarray A) \\<and> (A !! i !! k = 0) \n            \\<and> (\\<not> vector_all_zero_from_index (i + 1, (column_iarray k A)))) \n         then (-1 * det_P, echelon_form_of_column_k_iarrays (A, i, bezout) k) \n         else (det_P,echelon_form_of_column_k_iarrays (A,i,bezout) k))\"\n\ndefinition \"echelon_form_of_upt_k_det_iarrays A' k bezout = \n      (let A = snd A'; \n           f = foldl echelon_form_of_column_k_det_iarrays (1, A, 0, bezout) [0..<Suc k] \n       in (fst f, fst (snd f)))\"\n\ndefinition echelon_form_of_det_iarrays :: \n  \"'a::{bezout_ring} iarray iarray \n    \\<Rightarrow> ('a \\<Rightarrow> 'a \\<Rightarrow> 'a \\<times> 'a \\<times> 'a \\<times> 'a \\<times> 'a) \n    \\<Rightarrow> ('a \\<times> ('a iarray iarray))\"\n  where \n  \"echelon_form_of_det_iarrays A bezout = \n      echelon_form_of_upt_k_det_iarrays (1::'a, A) (ncols_iarray A - 1) bezout\"\n\ndefinition \"det_iarrays_rings A = \n    (let A' = echelon_form_of_det_iarrays A euclid_ext2 \n     in 1 div (fst A') * prod_list (map (\\<lambda>i. (snd A') !! i !! i) [0..<nrows_iarray A]))\"\n\nsubsection\\<open>Properties\\<close>\n\nsubsubsection\\<open>Echelon Form of column k\\<close>\n\nlemma vector_all_zero_from_index3:\n  fixes A::\"'a::{bezout_ring}^'cols::{mod_type}^'rows::{mod_type}\"\n  shows \"(\\<exists>m>i. A $ m $ k \\<noteq> 0) \n  = (\\<not> vector_all_zero_from_index (to_nat i + 1, vec_to_iarray (column k A)))\"\n  using matrix_vector_all_zero_from_index2 \nproof -\n  have \"(\\<forall>m>i. A $ m $ k = 0) = (vector_all_zero_from_index (to_nat i + 1, vec_to_iarray (column k A)))\"\n    using matrix_vector_all_zero_from_index2[of i A k] by auto\n  hence \"(\\<not> (\\<forall>m>i. A $ m $ k = 0)) \n    = (\\<not>(vector_all_zero_from_index (to_nat i + 1, vec_to_iarray (column k A))))\"\n    by auto\n  thus ?thesis by auto\nqed\n\nlemma fst_matrix_to_iarray_echelon_form_of_column_k_det:\n  assumes k: \"k<ncols A\" and i: \"i\\<le>nrows A\"\n  shows \"fst ((echelon_form_of_column_k_det bezout) (det_P, A, i) k)\n  = fst (echelon_form_of_column_k_det_iarrays (det_P, matrix_to_iarray A, i, bezout) k)\"\nproof (cases \"i<nrows A\")\n  case True\n  have ex_rw: \"(\\<exists>m>from_nat i. A $ m $ from_nat k \\<noteq> 0) \n    = (\\<not> vector_all_zero_from_index (i + 1, column_iarray k (matrix_to_iarray A)))\"\n    using vector_all_zero_from_index3[of \"from_nat i\" A \"from_nat k\"] \n    unfolding vec_to_iarray_column\n    unfolding to_nat_from_nat_id[OF k[unfolded ncols_def]]\n    unfolding to_nat_from_nat_id[OF True[unfolded nrows_def]] .\n  have Aik: \"matrix_to_iarray A !! i !! k = A $ (from_nat i) $ (from_nat k)\"\n    by (metis True k matrix_to_iarray_nth ncols_def nrows_def to_nat_from_nat_id)\n  show ?thesis\n    unfolding echelon_form_of_column_k_det_iarrays_def echelon_form_of_column_k_det_def\n    unfolding Let_def \n    unfolding split_beta\n    unfolding fst_conv snd_conv \n    unfolding matrix_to_iarray_nrows\n    unfolding ex_rw Aik by auto\nnext\n  case False\n  hence i2: \"i=nrows A\" using i by simp\n  thus ?thesis\n    unfolding echelon_form_of_column_k_det_iarrays_def echelon_form_of_column_k_det_def\n    unfolding Let_def fst_conv snd_conv \n    unfolding matrix_to_iarray_nrows\n    unfolding i2 unfolding matrix_to_iarray_nrows by auto\nqed\n\nlemma snd_echelon_form_of_column_k_det:\n  shows \"(snd (echelon_form_of_column_k_det_iarrays (det_P, A, i, bezout) k))\n  = echelon_form_of_column_k_iarrays (A,i,bezout) k\"\n  unfolding echelon_form_of_column_k_det_iarrays_def Let_def by auto\n\n\nlemma fst_snd_echelon_form_of_column_k_le_nrows: \n  assumes \"i\\<le>nrows A\"\n  shows \"snd ((echelon_form_of_column_k bezout) (A, i) k) \\<le> nrows A\"\n  using assms \n  unfolding echelon_form_of_column_k_def Let_def fst_conv snd_conv\n  unfolding nrows_def by auto\n\nlemma fst_snd_snd_echelon_form_of_column_k_det_le_nrows:\n  assumes \"i\\<le>nrows A\"\n  shows \"snd (snd ((echelon_form_of_column_k_det bezout) (n, A, i) k)) \\<le> nrows A\"\n  unfolding echelon_form_of_column_k_det_def Let_def fst_conv snd_conv\n  by (simp add: assms fst_snd_echelon_form_of_column_k_le_nrows)\n\nsubsubsection\\<open>Echelon Form up to column k\\<close>\n\nlemma snd_snd_snd_foldl_echelon_form_of_column_k_det_iarrays:\n  \"snd (snd (snd (foldl echelon_form_of_column_k_det_iarrays (n, A, 0, bezout) [0..<k]))) = bezout\"\nproof (induct k)\n  case 0\n  show ?case by auto\nnext\n  case (Suc k)\n  show ?case \n    apply auto \n    apply (simp only: echelon_form_of_column_k_det_iarrays_def Let_def)\n    apply (auto simp add: split_beta echelon_form_of_column_k_iarrays_def Let_def Suc.hyps)\n    done\nqed\n\n(*lemma snd_snd_snd_echelon_form_of_column_k_det:\n  \"snd (snd (snd (foldl echelon_form_of_column_k_det (n, A, 0, bezout) [0..<k]))) = bezout\"\n  by (metis snd_foldl_ef_det_eq snd_snd_foldl_echelon_form_of_column_k)*)\n\nlemma matrix_to_iarray_echelon_form_of_column_k_det:\n  assumes \"k<ncols A\" and \"i\\<le>nrows A\"\n  shows \"matrix_to_iarray (fst (snd ((echelon_form_of_column_k_det bezout) (n, A, i) k))) \n  = (fst (snd (echelon_form_of_column_k_det_iarrays (n, matrix_to_iarray A, i, bezout) k)))\"\n  unfolding snd_echelon_form_of_column_k_det \n  unfolding echelon_form_of_column_k_det_def Let_def fst_conv snd_conv \n  using assms matrix_to_iarray_echelon_form_of_column_k by auto\n\n\nlemma fst_snd_snd_echelon_form_of_column_k_det:\n  assumes \"k < ncols A\"\n  and \"i \\<le> nrows A\"\n  shows \"snd (snd ((echelon_form_of_column_k_det bezout) (n,A,i) k)) \n  = fst (snd (snd (echelon_form_of_column_k_det_iarrays (n,matrix_to_iarray A, i, bezout) k)))\"\n  unfolding snd_echelon_form_of_column_k_det_eq\n  unfolding snd_echelon_form_of_column_k_det\n  by (rule fst_snd_matrix_to_iarray_echelon_form_of_column_k[OF assms])\n\nlemma \n  fixes A::\"'a::{bezout_domain}^'cols::{mod_type}^'rows::{mod_type}\"\n  assumes \"k<ncols A\"\n  shows matrix_to_iarray_fst_echelon_form_of_upt_k_det: \n  \"fst ((echelon_form_of_upt_k_det bezout) (1::'a,A) k) \n  = fst (echelon_form_of_upt_k_det_iarrays (1::'a,matrix_to_iarray A) k bezout)\"\n  and matrix_to_iarray_snd_echelon_form_of_upt_k_det:\n  \"matrix_to_iarray ((snd ((echelon_form_of_upt_k_det bezout) (1::'a,A) k))) \n  = (snd (echelon_form_of_upt_k_det_iarrays (1::'a, matrix_to_iarray A) k bezout))\"\n  and \"snd (snd (foldl (echelon_form_of_column_k_det bezout) (1::'a,A,0) [0..<Suc k])) \\<le> nrows A\"\n  and \"fst (snd (snd (foldl echelon_form_of_column_k_det_iarrays \n  (1::'a,matrix_to_iarray A,0,bezout) [0..<Suc k]))) = snd (snd \n  (foldl (echelon_form_of_column_k_det bezout) (1::'a,A,0) [0..<Suc k]))\"\n  using assms\nproof (induct k)\n  show \"fst ((echelon_form_of_upt_k_det bezout) (1, A) 0) \n    = fst (echelon_form_of_upt_k_det_iarrays (1, matrix_to_iarray A) 0 bezout)\"\n    unfolding echelon_form_of_upt_k_det_def echelon_form_of_upt_k_det_iarrays_def Let_def\n    by (auto, metis fst_matrix_to_iarray_echelon_form_of_column_k_det le0 ncols_not_0 neq0_conv)\n  show \"matrix_to_iarray (snd ((echelon_form_of_upt_k_det bezout) (1, A) 0)) =\n    snd (echelon_form_of_upt_k_det_iarrays (1, matrix_to_iarray A) 0 bezout)\"\n    unfolding echelon_form_of_upt_k_det_def echelon_form_of_upt_k_det_iarrays_def Let_def\n    by (auto, metis le0 matrix_to_iarray_echelon_form_of_column_k ncols_not_0 neq0_conv \n      snd_echelon_form_of_column_k_det snd_echelon_form_of_column_k_det_eq)\n  show \"snd (snd (foldl (echelon_form_of_column_k_det bezout)(1, A, 0) [0..<Suc 0])) \\<le> nrows A\"\n    by (simp add: fst_snd_snd_echelon_form_of_column_k_det_le_nrows)\n  show \"fst (snd (snd (foldl echelon_form_of_column_k_det_iarrays (1, matrix_to_iarray A, 0, bezout) [0..<Suc 0]))) =\n    snd (snd (foldl (echelon_form_of_column_k_det bezout) (1, A, 0) [0..<Suc 0]))\"\n    by (auto, metis fst_snd_matrix_to_iarray_echelon_form_of_column_k le0 ncols_not_0 neq0_conv \n      snd_echelon_form_of_column_k_det snd_echelon_form_of_column_k_det_eq)\nnext\n  fix k\n  assume \"(k < ncols A \\<Longrightarrow> fst ((echelon_form_of_upt_k_det bezout) (1::'a, A) k) \n    = fst (echelon_form_of_upt_k_det_iarrays (1::'a, matrix_to_iarray A) k bezout))\"\n    and \"(k < ncols A \\<Longrightarrow>\n    matrix_to_iarray (snd ((echelon_form_of_upt_k_det bezout) (1::'a, A) k)) \n    = snd (echelon_form_of_upt_k_det_iarrays (1::'a, matrix_to_iarray A) k bezout))\"\n    and \"(k < ncols A \\<Longrightarrow> \n    snd (snd (foldl (echelon_form_of_column_k_det bezout) (1::'a, A, 0) [0..<Suc k])) \\<le> nrows A)\"\n    and \"(k < ncols A \\<Longrightarrow>\n    fst (snd (snd (foldl echelon_form_of_column_k_det_iarrays (1::'a, matrix_to_iarray A, 0, bezout) [0..<Suc k]))) =\n    snd (snd (foldl (echelon_form_of_column_k_det bezout) (1::'a, A, 0) [0..<Suc k])))\" \n    and S: \"Suc k < ncols A\"\n  hence hyp1: \"fst ((echelon_form_of_upt_k_det bezout) (1::'a, A) k) \n    = fst (echelon_form_of_upt_k_det_iarrays (1::'a, matrix_to_iarray A) k bezout)\"\n    and hyp2: \"matrix_to_iarray (snd ((echelon_form_of_upt_k_det bezout) (1::'a, A) k)) \n    = snd (echelon_form_of_upt_k_det_iarrays (1::'a, matrix_to_iarray A) k bezout)\" \n    and hyp3: \"snd (snd (foldl (echelon_form_of_column_k_det bezout) (1::'a, A, 0) [0..<Suc k])) \n    \\<le> nrows A\"\n    and hyp4: \"fst (snd (snd (foldl echelon_form_of_column_k_det_iarrays \n    (1::'a, matrix_to_iarray A, 0, bezout) [0..<Suc k])))\n    = snd (snd (foldl (echelon_form_of_column_k_det bezout) (1::'a, A, 0) [0..<Suc k]))\"\n    by auto\n  have list_rw: \"[0..<Suc (Suc k)] = [0..<(Suc k)] @ [Suc k]\" by simp\n  let ?f = \"foldl (echelon_form_of_column_k_det bezout) (1, A, 0) [0..<Suc k]\"\n  have f_rw: \"?f= (fst ?f, fst (snd ?f), snd (snd ?f))\" by simp\n  let ?g=\"(foldl echelon_form_of_column_k_det_iarrays (1, matrix_to_iarray A, 0, bezout) [0..<Suc k])\"\n  have g_rw: \"?g = (fst ?g, fst (snd ?g), fst (snd (snd ?g)), snd (snd (snd ?g)))\" by simp\n  have rw1: \"fst ?g = fst ?f\" \n    using hyp1[unfolded echelon_form_of_upt_k_det_def echelon_form_of_upt_k_det_iarrays_def Let_def \n      fst_conv snd_conv] ..\n  have rw2: \"fst (snd ?g) = matrix_to_iarray (fst (snd ?f))\" \n    using hyp2[unfolded echelon_form_of_upt_k_det_def \n      echelon_form_of_upt_k_det_iarrays_def Let_def snd_conv] ..\n  have rw3: \"fst (snd (snd ?g)) = snd (snd ?f)\" \n    using hyp4 .\n  (*have rw4: \"snd (snd (snd ?g)) = snd (snd (snd ?f))\" \n    unfolding snd_snd_snd_foldl_echelon_form_of_column_k_det_iarrays\n    unfolding snd_snd_snd_echelon_form_of_column_k_det ..*)\n  show \"fst ((echelon_form_of_upt_k_det bezout) (1, A) (Suc k)) \n    = fst (echelon_form_of_upt_k_det_iarrays (1, matrix_to_iarray A) (Suc k) bezout)\"\n    unfolding echelon_form_of_upt_k_det_iarrays_def echelon_form_of_upt_k_det_def Let_def fst_conv snd_conv\n    unfolding list_rw foldl_append\n    unfolding List.foldl.simps\n    apply (subst f_rw)\n    apply (subst g_rw)\n    unfolding rw1[symmetric] rw2 rw3\n    unfolding snd_snd_snd_foldl_echelon_form_of_column_k_det_iarrays\n  proof (rule fst_matrix_to_iarray_echelon_form_of_column_k_det)\n    show \"Suc k < ncols (fst (snd ?f))\" using S unfolding ncols_def .\n    show \" snd (snd (foldl (echelon_form_of_column_k_det bezout) (1, A, 0) [0..<Suc k]))\n    \\<le> nrows (fst (snd (foldl (echelon_form_of_column_k_det bezout) (1, A, 0) [0..<Suc k])))\"\n    by (metis hyp3 nrows_def)\n  qed\n  show \"matrix_to_iarray (snd ((echelon_form_of_upt_k_det bezout) (1, A) (Suc k))) =\n    snd (echelon_form_of_upt_k_det_iarrays (1, matrix_to_iarray A) (Suc k) bezout)\"\n    unfolding echelon_form_of_upt_k_det_iarrays_def echelon_form_of_upt_k_det_def Let_def fst_conv snd_conv\n    unfolding list_rw foldl_append\n    unfolding List.foldl.simps\n    apply (subst f_rw)\n    apply (subst g_rw)\n    unfolding rw1[symmetric] rw2 rw3 unfolding snd_snd_snd_foldl_echelon_form_of_column_k_det_iarrays\n  proof (rule matrix_to_iarray_echelon_form_of_column_k_det)\n    show \"Suc k < ncols (fst (snd ?f))\" using S unfolding ncols_def .\n    show \"snd (snd (foldl (echelon_form_of_column_k_det bezout) (1, A, 0) [0..<Suc k]))\n    \\<le> nrows (fst (snd (foldl (echelon_form_of_column_k_det bezout) (1, A, 0) [0..<Suc k])))\"\n    by (metis hyp3 nrows_def)\n  qed\n  show \"snd (snd (foldl (echelon_form_of_column_k_det bezout) (1, A, 0) [0..<Suc (Suc k)])) \\<le> nrows A\"\n    unfolding list_rw foldl_append List.foldl.simps\n    apply (subst f_rw) \n    using fst_snd_snd_echelon_form_of_column_k_det_le_nrows\n    by (metis hyp3 nrows_def)\n  show \"fst (snd (snd (foldl echelon_form_of_column_k_det_iarrays \n    (1, matrix_to_iarray A, 0, bezout) [0..<Suc (Suc k)]))) \n    = snd (snd (foldl (echelon_form_of_column_k_det bezout) (1, A, 0) [0..<Suc (Suc k)]))\"\n    unfolding echelon_form_of_upt_k_det_iarrays_def echelon_form_of_upt_k_det_def Let_def fst_conv snd_conv\n    unfolding list_rw foldl_append\n    unfolding List.foldl.simps\n    apply (subst f_rw)\n    apply (subst g_rw)\n    unfolding rw1[symmetric] rw2 rw3 \n     unfolding snd_snd_snd_foldl_echelon_form_of_column_k_det_iarrays\n  proof (rule fst_snd_snd_echelon_form_of_column_k_det[symmetric])\n    show \"Suc k < ncols (fst (snd ?f))\" using S unfolding ncols_def .\n    show \"snd (snd (foldl (echelon_form_of_column_k_det bezout) (1, A, 0) [0..<Suc k]))\n    \\<le> nrows (fst (snd (foldl (echelon_form_of_column_k_det bezout) (1, A, 0) [0..<Suc k])))\"\n    by (metis hyp3 nrows_def)\n  qed\nqed\n\nsubsubsection\\<open>Echelon Form\\<close>\n\nlemma matrix_to_iarray_echelon_form_of_det[code_unfold]:\n  \"matrix_to_iarray (snd (echelon_form_of_det A bezout)) \n  = snd (echelon_form_of_det_iarrays (matrix_to_iarray A) bezout)\"\n  unfolding echelon_form_of_det_def echelon_form_of_det_iarrays_def\n  unfolding matrix_to_iarray_ncols[symmetric]\n  by (rule matrix_to_iarray_snd_echelon_form_of_upt_k_det, simp add: ncols_def)\n\nlemma fst_echelon_form_of_det[code_unfold]:\n  \"(fst (echelon_form_of_det A bezout)) \n  = fst (echelon_form_of_det_iarrays (matrix_to_iarray A) bezout)\"\n  unfolding echelon_form_of_det_def echelon_form_of_det_iarrays_def\n  unfolding matrix_to_iarray_ncols[symmetric]\n  by (rule matrix_to_iarray_fst_echelon_form_of_upt_k_det, simp add: ncols_def)\n\nsubsubsection\\<open>Computing the determinant\\<close>\n\nlemma det_echelon_form_of_euclidean_iarrays[code]:\n  fixes A::\"'a::{euclidean_ring_gcd}^'n::{mod_type}^'n::{mod_type}\"\n  shows \"det A = (let A' = echelon_form_of_det_iarrays (matrix_to_iarray A) euclid_ext2 \n  in 1 div (fst A') \n  * prod_list (map (\\<lambda>i. (snd A') !! i !! i) [0..<nrows_iarray (matrix_to_iarray A)]))\"\nproof -\n  let ?f=\"(\\<lambda>i. snd (echelon_form_of_det_iarrays (matrix_to_iarray A) euclid_ext2) !! i !! i)\"\n  have \"prod_list (map ?f [0..<nrows_iarray (matrix_to_iarray A)]) \n    = prod ?f (set [0..<nrows_iarray (matrix_to_iarray A)])\" \n    by (metis (mono_tags, lifting) distinct_upt prod.distinct_set_conv_list)  \n  also have \"... = prod (\\<lambda>i. snd (echelon_form_of_det A euclid_ext2) $ i $ i) (UNIV:: 'n set)\"\n  proof (rule prod.reindex_cong[of \"to_nat::('n=>nat)\"])\n    show \"inj (to_nat::('n=>nat))\" by (metis strict_mono_imp_inj_on strict_mono_to_nat)\n    show \"set [0..<nrows_iarray (matrix_to_iarray A)] = range (to_nat::'n=>nat)\"\n      unfolding nrows_eq_card_rows using bij_to_nat[where ?'a='n]\n      unfolding bij_betw_def \n      unfolding atLeast0LessThan atLeast_upt  by auto\n    fix x \n    show \"snd (echelon_form_of_det_iarrays (matrix_to_iarray A) euclid_ext2) !! to_nat x !! to_nat x\n      = snd (echelon_form_of_det A euclid_ext2) $ x $ x\"\n      unfolding matrix_to_iarray_echelon_form_of_det[symmetric]\n      unfolding matrix_to_iarray_nth ..\n  qed\n  finally have *:\"prod_list (map (\\<lambda>i. snd (echelon_form_of_det_iarrays \n    (matrix_to_iarray A) euclid_ext2) !! i !! i) [0..<nrows_iarray (matrix_to_iarray A)]) =\n    (\\<Prod>i\\<in>UNIV. snd (echelon_form_of_det A euclid_ext2) $ i $ i)\" .  \n  have \"det A = 1 div (fst (echelon_form_of_det A euclid_ext2)) \n    * prod (\\<lambda>i. snd (echelon_form_of_det A euclid_ext2) $ i $ i) (UNIV:: 'n set)\"\n    unfolding det_echelon_form_of_euclidean ..\n  also have \"... = (let A' = echelon_form_of_det_iarrays (matrix_to_iarray A) euclid_ext2\n    in 1 div (fst A') \n    * prod_list (map (\\<lambda>i. (snd A') !! i !! i) [0..<nrows_iarray (matrix_to_iarray A)]))\"\n    unfolding Let_def unfolding * fst_echelon_form_of_det ..\n  finally show ?thesis .\nqed\n\n\ncorollary matrix_to_iarray_det_euclidean_ring:\n  fixes A::\"'a::{euclidean_ring_gcd}^'n::{mod_type}^'n::{mod_type}\"\n  shows \"det A = det_iarrays_rings (matrix_to_iarray A)\"\n  unfolding det_echelon_form_of_euclidean_iarrays det_iarrays_rings_def ..\n\n\nsubsubsection\\<open>Computing the characteristic polynomial of a matrix\\<close>\n\ndefinition \"mat2matofpoly_iarrays A \n  = tabulate2 (nrows_iarray A) (ncols_iarray A)  (\\<lambda>i j. [:A !! i !! j:])\"\n\nlemma matrix_to_iarray_mat2matofpoly[code_unfold]: \n  \"matrix_to_iarray (mat2matofpoly A) = mat2matofpoly_iarrays (matrix_to_iarray A)\"\n  unfolding mat2matofpoly_def mat2matofpoly_iarrays_def tabulate2_def \nproof (rule matrix_to_iarray_eq_of_fun, auto)\n  show \"nrows_iarray (matrix_to_iarray A) = length (IArray.list_of (matrix_to_iarray (\\<chi> i j. [:A $ i $ j:])))\"\n    unfolding nrows_iarray_def matrix_to_iarray_def by simp\n  fix i \n  show \"vec_to_iarray (\\<chi> j. [:A $ i $ j:]) =\n    IArray (map (\\<lambda>j. [:IArray.list_of (IArray.list_of (matrix_to_iarray A) ! mod_type_class.to_nat i) ! j:])\n    [0..<ncols_iarray (matrix_to_iarray A)])\"\n    unfolding vec_to_iarray_def\n    unfolding matrix_to_iarray_ncols[symmetric] unfolding ncols_def\n    by (auto, metis IArray.sub_def vec_matrix vec_to_iarray_nth)\nqed\n\ntext\\<open>The following two lemmas must be added to the file \\<open>Matrix_To_IArray\\<close> \n  of the AFP Gauss-Jordan development.\\<close>\n\nlemma vec_to_iarray_minus[code_unfold]: \"vec_to_iarray (a - b) \n  = (vec_to_iarray a) - (vec_to_iarray b)\"\n  unfolding vec_to_iarray_def\n  unfolding minus_iarray_def by auto\n\nlemma matrix_to_iarray_minus[code_unfold]: \"matrix_to_iarray (A - B) \n  = (matrix_to_iarray A) - (matrix_to_iarray B)\"\n  unfolding matrix_to_iarray_def o_def\n  by (simp add: minus_iarray_def Let_def vec_to_iarray_minus)\n\ndefinition \"charpoly_iarrays A \n  = det_iarrays_rings (mat_iarray (monom 1 (Suc 0)) (nrows_iarray A) - mat2matofpoly_iarrays A)\"\n\nlemma matrix_to_iarray_charpoly[code]: \"charpoly A = charpoly_iarrays (matrix_to_iarray A)\"\n  unfolding charpoly_def charpoly_iarrays_def\n  unfolding matrix_to_iarray_mat2matofpoly[symmetric]\n  unfolding matrix_to_iarray_nrows[symmetric] nrows_def\n  unfolding matrix_to_iarray_mat[symmetric]\n  unfolding matrix_to_iarray_minus[symmetric]\n  unfolding det_iarrays_rings_def\n  unfolding det_echelon_form_of_euclidean_iarrays ..\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/Echelon_Form/Echelon_Form_Det_IArrays.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8791467738423874, "lm_q2_score": 0.8006919925839875, "lm_q1q2_score": 0.7039257821216454}}
{"text": "theory Sorting_Quicksort_Scheme\nimports Sorting_Setup Sorting_Partially_Sorted\nbegin\n\n\n  abbreviation \"is_threshold \\<equiv> 16::nat\"\n\n  context weak_ordering begin\n\n    definition \"partition1_spec xs \\<equiv> doN { \n      ASSERT (length xs \\<ge> 4); \n      SPEC (\\<lambda>(xs1,xs2). mset xs = mset xs1 + mset xs2 \\<and> xs1\\<noteq>[] \\<and> xs2\\<noteq>[] \\<and> slice_LT (\\<^bold>\\<le>) xs1 xs2)\n    }\"\n    definition introsort_aux1 :: \"'a list \\<Rightarrow> nat \\<Rightarrow> 'a list nres\" where \"introsort_aux1 xs d \\<equiv> RECT (\\<lambda>introsort_aux1 (xs,d). doN {\n      if length xs > is_threshold then doN {\n        if d=0 then\n          SPEC (sort_spec (\\<^bold><) xs)\n        else doN {\n          (xs1,xs2)\\<leftarrow>partition1_spec xs;\n          xs1 \\<leftarrow> introsort_aux1 (xs1,d-1);\n          xs2 \\<leftarrow> introsort_aux1 (xs2,d-1);\n          RETURN (xs1@xs2)\n        }\n      }\n      else\n        RETURN xs\n    }) (xs,d)\"\n    \n    lemma slice_strict_LT_imp_LE: \"slice_LT (\\<^bold><) xs ys \\<Longrightarrow> slice_LT (le_by_lt (\\<^bold><)) xs ys\"  \n      apply (erule slice_LT_mono)\n      by (meson le_by_lt_def wo_less_asym)\n      \n    lemma introsort_aux1_correct: \"introsort_aux1 xs d \\<le> SPEC (\\<lambda>xs'. mset xs' = mset xs \\<and> part_sorted_wrt (le_by_lt (\\<^bold><)) is_threshold xs')\"\n    \n      unfolding introsort_aux1_def partition1_spec_def sort_spec_def\n      \n      apply (refine_vcg RECT_rule_arb[where V=\"measure (\\<lambda>(xs,d). d+1)\" and pre=\"\\<lambda>xss (xs',d). xss=xs'\"])\n      apply (all \\<open>(auto intro: sorted_wrt_imp_part_sorted part_sorted_wrt_init; fail)?\\<close>)\n      apply (rule order_trans)\n      apply rprems\n      applyS (simp)\n      subgoal by auto\n      apply refine_vcg\n      subgoal\n        apply (rule order_trans)\n        apply rprems\n        applyS simp\n        subgoal by auto\n        apply refine_vcg  \n        subgoal by auto\n        subgoal\n          apply clarsimp\n          apply (rule part_sorted_concatI; assumption?) \n          apply (subst slice_LT_mset_eq1, assumption)\n          apply (subst slice_LT_mset_eq2, assumption)\n          using le_by_lt by blast\n        done\n      done\n    \n      \n    definition \"partition2_spec xs \\<equiv> doN { \n      ASSERT (length xs \\<ge> 4); \n      SPEC (\\<lambda>(xs',i). mset xs' = mset xs \\<and> 0<i \\<and> i<length xs \\<and> slice_LT (\\<^bold>\\<le>) (take i xs') (drop i xs'))\n    }\"\n      \n    lemma partition2_spec_refine: \"(xs,xs')\\<in>Id \\<Longrightarrow> partition2_spec xs \\<le>\\<Down>(br (\\<lambda>(xs,i). (take i xs, drop i xs)) (\\<lambda>(xs,i). 0<i \\<and> i<length xs)) (partition1_spec xs')\"\n      unfolding partition1_spec_def partition2_spec_def\n      apply (refine_vcg RES_refine)\n      by (auto dest: mset_eq_length simp: in_br_conv simp flip: mset_append)\n      \n    definition introsort_aux2 :: \"'a list \\<Rightarrow> nat \\<Rightarrow> 'a list nres\" where \"introsort_aux2 xs d \\<equiv> RECT (\\<lambda>introsort_aux (xs,d). doN {\n      if length xs > is_threshold then doN {\n        if d=0 then\n          SPEC (sort_spec (\\<^bold><) xs)\n        else doN {\n          (xs,m)\\<leftarrow>partition2_spec xs;\n          ASSERT (m\\<le>length xs);\n          xs1 \\<leftarrow> introsort_aux (take m xs,d-1);\n          xs2 \\<leftarrow> introsort_aux (drop m xs,d-1);\n          RETURN (xs1@xs2)\n        }\n      }\n      else\n        RETURN xs\n    }) (xs,d)\"\n      \n    lemma introsort_aux2_refine: \"introsort_aux2 xs d \\<le>\\<Down>Id (introsort_aux1 xs d)\"  \n      unfolding introsort_aux2_def introsort_aux1_def\n      apply (refine_rcg partition2_spec_refine)\n      apply refine_dref_type\n      apply (auto simp: in_br_conv)\n      done\n      \n    \n    definition \"partition3_spec xs l h \\<equiv> doN { \n      ASSERT (h-l\\<ge>4 \\<and> h\\<le>length xs); \n      SPEC (\\<lambda>(xs',i). slice_eq_mset l h xs' xs \\<and> l<i \\<and> i<h \\<and> slice_LT (\\<^bold>\\<le>) (slice l i xs') (slice i h xs')) \n    }\"\n    \n    lemma partition3_spec_refine: \"(xsi,xs) \\<in> slice_rel xs\\<^sub>0 l h \\<Longrightarrow> partition3_spec xsi l h  \\<le>\\<Down>(slice_rel xs\\<^sub>0 l h \\<times>\\<^sub>r idx_shift_rel l) (partition2_spec xs)\"\n      unfolding partition3_spec_def partition2_spec_def\n      apply (refine_vcg RES_refine)\n      apply (auto simp: slice_rel_def in_br_conv) [2]\n      apply (clarsimp simp: slice_rel_def in_br_conv)\n      subgoal for xs'i ii\n        apply (rule exI[where x=\"slice l h xs'i\"])\n        apply (rule conjI)\n        subgoal by (auto simp: slice_eq_mset_def)\n        apply (simp add: idx_shift_rel_alt)\n        by (auto simp: slice_eq_mset_def take_slice drop_slice)\n      done\n\n      \n    lemma partition3_spec_refine': \"\\<lbrakk>(xsi,xs) \\<in> slicep_rel l h; xsi'=xsi; l'=l; h'=h\\<rbrakk> \n      \\<Longrightarrow> partition3_spec xsi l h  \\<le>\\<Down>(slice_rel xsi' l' h' \\<times>\\<^sub>r idx_shift_rel l') (partition2_spec xs)\"\n      unfolding partition3_spec_def partition2_spec_def\n      apply (refine_vcg RES_refine)\n      apply (auto simp: slicep_rel_def in_br_conv) [2]\n      apply (clarsimp simp: slice_rel_def slicep_rel_def in_br_conv)\n      subgoal for xs'i ii\n        apply (rule exI[where x=\"slice l h xs'i\"])\n        apply (rule conjI)\n        subgoal by (auto simp: slice_eq_mset_def)\n        apply (simp add: idx_shift_rel_alt)\n        by (auto simp: slice_eq_mset_def take_slice drop_slice)\n      done\n      \n      \n    definition introsort_aux3 :: \"'a list \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> 'a list nres\" where \"introsort_aux3 xs l h d \n    \\<equiv> RECT (\\<lambda>introsort_aux (xs,l,h,d). doN {\n        ASSERT (l\\<le>h);\n        if h-l > is_threshold then doN {\n          if d=0 then\n            slice_sort_spec (\\<^bold><) xs l h\n          else doN {\n            (xs,m)\\<leftarrow>partition3_spec xs l h;\n            xs \\<leftarrow> introsort_aux (xs,l,m,d-1);\n            xs \\<leftarrow> introsort_aux (xs,m,h,d-1);\n            RETURN xs\n          }\n        }\n        else\n          RETURN xs\n      }) (xs,l,h,d)\"\n      \n    lemma introsort_aux3_refine: \"(xsi,xs)\\<in>slicep_rel l h \\<Longrightarrow> introsort_aux3 xsi l h d \\<le> \\<Down>(slice_rel xsi l h) (introsort_aux2 xs d)\"  \n      unfolding introsort_aux3_def introsort_aux2_def\n      \n      supply recref = RECT_dep_refine[where \n          R=\"\\<lambda>_. {((xsi::'a list, l, h, di::nat), (xs, d)). (xsi, xs) \\<in> slicep_rel l h \\<and> di=d}\" and\n          S=\"\\<lambda>_ (xsi::'a list, l, h, di::nat). slice_rel xsi l h\" and\n          arb\\<^sub>0 = \"()\"\n          ]\n\n      apply (refine_rcg \n        recref \n        partition3_spec_refine'\n        slice_sort_spec_refine_sort'\n        ; (rule refl)?\n        )\n\n      subgoal by auto\n      subgoal by auto\n      subgoal by (auto simp: slicep_rel_def)\n      subgoal by (auto simp: slicep_rel_def)\n      subgoal by auto\n      subgoal by auto\n      subgoal by auto\n      subgoal by auto\n      subgoal by auto\n      subgoal by auto\n      apply (rprems)\n      subgoal by (auto simp: slice_rel_alt idx_shift_rel_def slicep_rel_take)\n      apply rprems  \n      subgoal by (auto simp: slice_rel_alt idx_shift_rel_def slicep_rel_eq_outside_range slicep_rel_drop)\n      subgoal\n        apply (clarsimp simp: slice_rel_alt idx_shift_rel_def)\n        apply (rule conjI)\n        subgoal\n          apply (rule slicep_rel_append)\n          apply (subst slicep_rel_eq_outside_range; assumption?) \n          by auto \n        subgoal \n          apply (drule (1) eq_outside_range_gen_trans[OF _ _ refl refl])\n          apply (erule (1) eq_outside_range_gen_trans)\n          apply (auto simp: max_def algebra_simps slicep_rel_def split: if_splits)\n          done \n        done\n      subgoal by (auto simp: slice_rel_alt eq_outside_range_triv slicep_rel_def)\n      done\n    \n\n    definition \"slice_part_sorted_spec xsi l h \\<equiv> doN { ASSERT (l\\<le>h \\<and> h\\<le>length xsi); SPEC (\\<lambda>xsi'. \n        eq_outside_range xsi' xsi l h \n      \\<and> mset (slice l h xsi') = mset (slice l h xsi) \n      \\<and> part_sorted_wrt (le_by_lt (\\<^bold><)) is_threshold (slice l h xsi'))}\"\n    \n          \n    lemma introsort_aux3_correct: \"introsort_aux3 xsi l h d \\<le> slice_part_sorted_spec xsi l h\"\n    proof -\n    \n(*      have \"(xsi, slice l h xsi) \\<in> slicep_rel l h\"\n        unfolding slicep_rel_def apply auto\n        *)\n    \n      have A: \"\\<Down> (slice_rel xsi l h) (SPEC (\\<lambda>xs'. mset xs' = mset (slice l h xsi) \\<and> part_sorted_wrt (le_by_lt (\\<^bold><)) 16 xs'))\n        \\<le> slice_part_sorted_spec xsi l h\"\n        apply (clarsimp simp: slice_part_sorted_spec_def pw_le_iff refine_pw_simps)\n        apply (auto simp: slice_rel_alt  slicep_rel_def)\n        done\n    \n      note introsort_aux3_refine[of xsi \"slice l h xsi\" l h d]\n      also note introsort_aux2_refine\n      also note introsort_aux1_correct\n      also note A\n      finally show ?thesis\n        apply (clarsimp simp: slicep_rel_def slice_part_sorted_spec_def)\n        by (auto simp: pw_le_iff refine_pw_simps)\n        \n    qed    \n      \n\n    text \\<open>In the paper, we summarized steps 2 and 3. Here are the relevant lemmas: \\<close>        \n    lemma partition3_spec_alt: \"partition3_spec xs l h = \\<Down>(slice_rel xs l h \\<times>\\<^sub>r Id) (doN { ASSERT (l\\<le>h \\<and> h\\<le>length xs); (xs\\<^sub>1,xs\\<^sub>2) \\<leftarrow> partition1_spec (slice l h xs); RETURN (xs\\<^sub>1@xs\\<^sub>2, l+length xs\\<^sub>1) })\"  \n      unfolding partition3_spec_def partition1_spec_def\n      apply (auto simp: pw_eq_iff refine_pw_simps)\n      apply (auto simp: slice_eq_mset_def slice_rel_def in_br_conv)\n      subgoal\n        by (smt Sorting_Misc.slice_len diff_is_0_eq leD le_add_diff_inverse less_imp_le_nat less_le_trans list.size(3) mset_append slice_append)\n      subgoal by (metis mset_append)\n      subgoal\n        by (metis Misc.slice_len add_le_cancel_left drop_all drop_append_miracle leI le_add_diff_inverse)\n      subgoal\n        by (metis Misc.slice_def add_diff_cancel_left' append_assoc append_eq_conv_conj drop_slice drop_take drop_take_drop_unsplit)\n      done\n\n    corollary partition3_spec_alt': \"partition3_spec xs l h = \\<Down>({((xsi',m),(xs\\<^sub>1,xs\\<^sub>2)). (xsi',xs\\<^sub>1@xs\\<^sub>2)\\<in>slice_rel xs l h \\<and> m=l + length xs\\<^sub>1 }) (doN { ASSERT (l\\<le>h \\<and> h\\<le>length xs); partition1_spec (slice l h xs)})\"  \n      unfolding partition3_spec_alt\n      apply (auto simp: pw_eq_iff refine_pw_simps)\n      done\n      \n    corollary partition3_spec_direct_refine: \"\\<lbrakk> h-l\\<ge>4; (xsi,xs)\\<in>slicep_rel l h \\<rbrakk> \\<Longrightarrow> partition3_spec xsi l h \\<le> \\<Down>({((xsi',m),(xs\\<^sub>1,xs\\<^sub>2)). (xsi',xs\\<^sub>1@xs\\<^sub>2)\\<in>slice_rel xsi l h \\<and> m=l + length xs\\<^sub>1 }) (partition1_spec xs)\"  \n      unfolding partition3_spec_alt'\n      apply (auto simp: pw_le_iff refine_pw_simps)\n      apply (auto simp: slicep_rel_def)\n      done\n      \n          \n    lemma slice_part_sorted_spec_alt: \"slice_part_sorted_spec xsi l h = \\<Down> (slice_rel xsi l h) (doN { ASSERT(l\\<le>h \\<and> h\\<le>length xsi); SPEC (\\<lambda>xs'. mset xs' = mset (slice l h xsi) \\<and> part_sorted_wrt (le_by_lt (\\<^bold><)) 16 xs') })\"\n      apply (clarsimp simp: slice_part_sorted_spec_def pw_eq_iff refine_pw_simps)\n      apply (auto simp: slice_rel_alt  slicep_rel_def eq_outside_rane_lenD)\n      done\n\n    (* Extracted this subgoal to present it in paper *)      \n    lemma introsort_aux3_direct_refine_aux1': \"(xs', xs\\<^sub>1 @ xs\\<^sub>2) \\<in> slice_rel xs l h \\<Longrightarrow> xs\\<^sub>1 = slice l (l + length xs\\<^sub>1) xs'\"\n      apply (clarsimp simp: slice_rel_def in_br_conv)\n      by (metis Misc.slice_def add_diff_cancel_left' append.assoc append_eq_conv_conj append_take_drop_id)\n      \n    lemma introsort_aux3_direct_refine_aux1: \"\\<lbrakk>(xsi', xs\\<^sub>1 @ xs\\<^sub>2) \\<in> slice_rel xsi l' h'\\<rbrakk> \\<Longrightarrow> (xsi', xs\\<^sub>1) \\<in> slicep_rel l' (l' + length xs\\<^sub>1)\"  \n      apply (simp add: slicep_rel_def introsort_aux3_direct_refine_aux1')\n      apply (auto simp: slice_rel_alt slicep_rel_def)\n      by (metis Misc.slice_len ab_semigroup_add_class.add_ac(1) le_add1 length_append ordered_cancel_comm_monoid_diff_class.add_diff_inverse)\n    \n    lemma introsort_aux3_direct_refine: \"(xsi,xs)\\<in>slicep_rel l h \\<Longrightarrow> introsort_aux3 xsi l h d \\<le> \\<Down>(slice_rel xsi l h) (introsort_aux1 xs d)\"  \n      unfolding introsort_aux3_def introsort_aux1_def\n      \n      supply [refine del] = RECT_refine\n      \n      supply recref = RECT_dep_refine[where \n          R=\"\\<lambda>_. {((xsi::'a list, l, h, di::nat), (xs, d)). (xsi, xs) \\<in> slicep_rel l h \\<and> di=d}\" and\n          S=\"\\<lambda>_ (xsi::'a list, l, h, di::nat). slice_rel xsi l h\" and\n          arb\\<^sub>0 = \"()\"\n          ]\n\n      apply (refine_rcg \n        recref\n        slice_sort_spec_refine_sort'\n        partition3_spec_direct_refine\n        ; (rule refl)?\n        )\n\n      subgoal by auto\n      subgoal by auto\n      subgoal by (auto simp: slicep_rel_def)\n      subgoal by (auto simp: slicep_rel_def)\n      subgoal by auto\n      subgoal by auto\n      subgoal by auto\n      subgoal by auto\n      subgoal by auto\n      subgoal by auto\n      subgoal by auto\n      apply (rprems)\n      subgoal by (clarsimp simp: introsort_aux3_direct_refine_aux1)\n      apply rprems  \n      subgoal\n        apply (auto simp: slice_rel_alt slicep_rel_def)\n        subgoal by (metis Misc.slice_def drop_append_miracle drop_slice eq_outside_range_def)\n        subgoal by (metis Nat.add_diff_assoc Sorting_Misc.slice_len add_diff_cancel_left' add_le_cancel_left diff_add_zero diff_is_0_eq length_append)\n        subgoal by (simp add: eq_outside_rane_lenD)\n        done\n      subgoal\n        apply (clarsimp simp: slice_rel_alt idx_shift_rel_def)\n        apply (rule conjI)\n        subgoal\n          apply (rule slicep_rel_append)\n          apply (subst slicep_rel_eq_outside_range; assumption?) \n          by auto \n        subgoal \n          apply (drule (1) eq_outside_range_gen_trans[OF _ _ refl refl])\n          apply (erule (1) eq_outside_range_gen_trans)\n          apply (auto simp: max_def algebra_simps slicep_rel_def split: if_splits)\n          done \n        done\n      subgoal by (auto simp: slice_rel_alt eq_outside_range_triv slicep_rel_def)\n      done\n      \n      \n      \n      \n      \n      \n      \n    \n    definition \"final_sort_spec xs l h \\<equiv> doN {\n      ASSERT (h-l>1 \\<and> part_sorted_wrt (le_by_lt (\\<^bold><)) is_threshold (slice l h xs));\n      slice_sort_spec (\\<^bold><) xs l h\n      }\"\n    \n    definition \"introsort3 xs l h \\<equiv> doN {\n      ASSERT(l\\<le>h);\n      if h-l>1 then doN {\n        xs \\<leftarrow> slice_part_sorted_spec xs l h;\n        xs \\<leftarrow> final_sort_spec xs l h;\n        RETURN xs\n      } else RETURN xs\n    }\"  \n    \n    \n    lemma introsort3_correct: \"introsort3 xs l h \\<le> slice_sort_spec (\\<^bold><) xs l h\"\n      apply (cases \"l\\<le>h \\<and> h\\<le>length xs\")\n      subgoal\n        apply (cases \"1<h-l\")\n        subgoal\n          unfolding introsort3_def slice_part_sorted_spec_def final_sort_spec_def slice_sort_spec_alt\n          by (auto simp: pw_le_iff refine_pw_simps eq_outside_rane_lenD elim: eq_outside_range_gen_trans[of _ _ l h _ l h l h, simplified])\n        subgoal\n          unfolding introsort3_def slice_sort_spec_alt slice_part_sorted_spec_def final_sort_spec_def\n          by (simp add: eq_outside_range_triv sorted_wrt01)\n        done\n      subgoal            \n        unfolding slice_sort_spec_alt\n        apply refine_vcg \n        by simp\n      done\n      \n      \n          \n  end  \n\n\n\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/sorting/Sorting_Quicksort_Scheme.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8791467580102419, "lm_q2_score": 0.8006920068519378, "lm_q1q2_score": 0.7039257819885955}}
{"text": "section \\<open>Stamps: Type and Range Information\\<close>\n\ntheory StampLattice\nimports\n  Values\n  HOL.Lattices\nbegin\n\nsubsection \\<open>Void Stamp\\<close>\ntext \\<open>\nThe VoidStamp represents a type with no associated values.\nThe VoidStamp lattice is therefore a simple single element lattice.\n\\<close>\ndatatype void =\n  VoidStamp\n\ninstantiation void :: order\nbegin\n\ndefinition less_eq_void :: \"void \\<Rightarrow> void \\<Rightarrow> bool\" where\n  \"less_eq_void a b = True\"\n\ndefinition less_void :: \"void \\<Rightarrow> void \\<Rightarrow> bool\" where\n  \"less_void a b = False\"\n\ninstance\n  apply standard\n     apply (simp add: less_eq_void_def less_void_def)\n    apply (simp add: less_eq_void_def)\n   apply (simp add: less_eq_void_def)\n  by (metis (full_types) void.exhaust)\n\nend\n\ninstantiation void :: semilattice_inf\nbegin\n\ndefinition inf_void :: \"void \\<Rightarrow> void \\<Rightarrow> void\" where\n  \"inf_void a b = VoidStamp\"\n\ninstance\n  apply standard\n    apply (simp add: less_eq_void_def)\n   apply (simp add: less_eq_void_def)\n  by (metis (mono_tags) void.exhaust)\n\nend\n\ninstantiation void :: semilattice_sup\nbegin\n\ndefinition sup_void :: \"void \\<Rightarrow> void \\<Rightarrow> void\" where\n  \"sup_void a b = VoidStamp\"\n\ninstance\n  apply standard\n    apply (simp add: less_eq_void_def)\n   apply (simp add: less_eq_void_def)\n  by (metis (mono_tags) void.exhaust)\n\nend\n\ninstantiation void :: bounded_lattice\nbegin\n\ndefinition bot_void :: \"void\" where\n  \"bot_void = VoidStamp\"\n\ndefinition top_void :: \"void\" where\n  \"top_void = VoidStamp\"\n\ninstance\n  apply standard\n   apply (simp add: less_eq_void_def)\n  by (simp add: less_eq_void_def)\n\nend\n\ntext \\<open>Definition of the stamp type\\<close>\ndatatype stamp =\n  intstamp int64 int64 \\<comment>\\<open>Type: Integer; Range: Lower Bound \\& Upper Bound\\<close>\n(*\n  | floatstamp \\<comment>\\<open>Type: Float; Range: Lower Bound \\& Upper Bound\\<close>\n  | objectstamp classname \\<comment>\\<open>Type: Object Instance; Range: Upper Bound Superclass\\<close>\n*)\n\nsubsection \\<open>Stamp Lattice\\<close>\n\ntext_raw \\<open>\\input{lattice}\\\\\\<close>\n\nsubsubsection \\<open>Stamp Order\\<close>\ntext \\<open>\nDefines an ordering on the stamp type.\n\nOne stamp is less than another if the valid values\nfor the stamp are a strict subset of the other stamp.\n\\<close>\ninstantiation stamp :: order\nbegin\n\nfun less_eq_stamp :: \"stamp \\<Rightarrow> stamp \\<Rightarrow> bool\" where\n  \"less_eq_stamp (intstamp l1 u1) (intstamp l2 u2) = ({l1..u1} \\<subseteq> {l2..u2})\"\n\nfun less_stamp :: \"stamp \\<Rightarrow> stamp \\<Rightarrow> bool\" where\n  \"less_stamp (intstamp l1 u1) (intstamp l2 u2) = ({l1..u1} \\<subset> {l2..u2})\"\n\nlemma less_le_not_le:\n  fixes x y :: stamp\n  shows \"(x < y) = (x \\<le> y \\<and> \\<not> y \\<le> x)\"\n  using less_eq_stamp.simps less_stamp.simps\n  using stamp.exhaust subset_not_subset_eq by metis\n\nlemma order_refl:\n  fixes x :: stamp\n  shows \"x \\<le> x\"\n  using less_eq_stamp.simps less_stamp.simps\n  using dual_order.refl stamp.exhaust by metis\n\nlemma order_trans:\n  fixes x y z :: stamp\n  shows \"x \\<le> y \\<Longrightarrow> y \\<le> z \\<Longrightarrow> x \\<le> z\"\nproof -\n  fix x :: stamp and y :: stamp and z :: stamp\n  assume \"x \\<le> y\"\n  assume \"y \\<le> z\"\n  obtain l1 u1 where xdef: \"x = intstamp l1 u1\"\n    using stamp.exhaust \n    by blast\n  obtain l2 u2 where ydef: \"y = intstamp l2 u2\"\n    using stamp.exhaust \n    by blast\n  obtain l3 u3 where zdef: \"z = intstamp l3 u3\"\n    using stamp.exhaust \n    by blast\n  have s1: \"{l1..u1} \\<le> {l2..u2}\"\n    using \\<open>x \\<le> y\\<close> less_eq_stamp.simps xdef ydef by blast\n  have s2: \"{l2..u2} \\<le> {l3..u3}\"\n    using \\<open>y \\<le> z\\<close> less_eq_stamp.simps ydef zdef by blast\n  from s1 s2 have \"{l1..u1} \\<le> {l3..u3}\"\n    by (meson dual_order.trans)\n  then show \"x \\<le> z\"\n    using less_eq_stamp.simps\n    using xdef zdef by presburger\nqed\n\nlemma antisym:\n  fixes x y :: stamp\n  shows \"x \\<le> y \\<Longrightarrow> y \\<le> x \\<Longrightarrow> x = y\"\nproof -\n  fix x :: stamp\n  fix y :: stamp\n  assume xlessy: \"x \\<le> y\"\n  assume ylessx: \"y \\<le> x\"\n  obtain l1 u1 where xdef: \"x = intstamp l1 u1\"\n    using stamp.exhaust by blast\n  obtain l2 u2 where ydef: \"y = intstamp l2 u2\"\n    using stamp.exhaust by blast\n  \n  from xlessy have s1: \"{l1..u1} \\<subseteq> {l2..u2}\"\n    using less_eq_stamp.simps\n    using xdef ydef by blast\n  from ylessx have s2: \"{l2..u2} \\<subseteq> {l1..u1}\"\n    using less_eq_stamp.simps\n    using xdef ydef by blast\n  have \"{l1..u1} \\<subseteq> {l2..u2} \\<Longrightarrow> {l2..u2} \\<subseteq> {l1..u1} \\<Longrightarrow> {l1..u1} = {l2..u2}\"\n    by fastforce\n  then have s3: \"{l1..u1} = {l2..u2} \\<Longrightarrow> (l1 = l2) \\<and> (u1 = u2)\"\n    (* not true *)\n    (* consider: \n       {1..0} = {-1..-1}\n    *)\n    sorry\n  then have \"(l1 = l2) \\<and> (u1 = u2) \\<Longrightarrow> x = y\"\n    using xdef ydef by fastforce\n  then show \"x = y\"\n    using s1 s2 s3 by fastforce\nqed\n\ninstance\n  apply standard\n  using less_le_not_le apply simp\n  using order_refl apply simp\n  using order_trans apply simp\n  using antisym by simp\nend\n\nsubsubsection \\<open>Stamp Join\\<close>\ntext \\<open>\nDefines the @{emph \\<open>join\\<close>} operation for stamps.\n\nFor any two stamps, the @{emph \\<open>join\\<close>} is defined as the intersection\nof the valid values for the stamp.\n\\<close>\ninstantiation stamp :: semilattice_inf\nbegin\n\nnotation inf (infix \"\\<sqinter>\" 65)\n\nfun inf_stamp :: \"stamp \\<Rightarrow> stamp \\<Rightarrow> stamp\" where\n  \"inf_stamp (intstamp l1 u1) (intstamp l2 u2) = intstamp (max l1 l2) (min u1 u2)\"\n\nlemma inf_le1: \n  fixes x y :: stamp\n  shows \"(x \\<sqinter> y) \\<le> x\"\nproof -\n  fix x :: stamp\n  fix y :: stamp\n  obtain l1 u1 where xdef: \"x = intstamp l1 u1\"\n    using stamp.exhaust by blast\n  obtain l2 u2 where ydef: \"y = intstamp l2 u2\"\n    using stamp.exhaust by blast\n  have joindef: \"x \\<sqinter> y = intstamp (max l1 l2) (min u1 u2)\"\n    (is \"?join = intstamp ?l3 ?u3\")\n    using inf_stamp.simps xdef ydef\n    by force\n  have leq: \"{?l3..?u3} \\<subseteq> {l1..u1}\"\n    by force\n  have \"(x \\<sqinter> y) \\<le> x = ({?l3..?u3} \\<subseteq> {l1..u1})\"\n    using xdef joindef inf_stamp.simps\n    by force\n  then show \"(x \\<sqinter> y) \\<le> x\"\n    using leq\n    by fastforce\nqed\n\nlemma inf_le2:\n  fixes x y :: stamp\n  shows \"(x \\<sqinter> y) \\<le> y\"\nproof -\n  fix x :: stamp\n  fix y :: stamp\n  obtain l1 u1 where xdef: \"x = intstamp l1 u1\"\n    using stamp.exhaust by blast\n  obtain l2 u2 where ydef: \"y = intstamp l2 u2\"\n    using stamp.exhaust by blast\n  have joindef: \"x \\<sqinter> y = intstamp (max l1 l2) (min u1 u2)\"\n    (is \"?join = intstamp ?l3 ?u3\")\n    using inf_stamp.simps xdef ydef\n    by force\n  have leq: \"{?l3..?u3} \\<subseteq> {l2..u2}\"\n    by force\n  have \"(x \\<sqinter> y) \\<le> y = ({?l3..?u3} \\<subseteq> {l2..u2})\"\n    using ydef joindef\n    by force\n  then show \"(x \\<sqinter> y) \\<le> y\"\n    using leq\n    by fastforce\nqed\n\nlemma inf_greatest:\n  fixes x y z :: stamp\n  shows \"x \\<le> y \\<Longrightarrow> x \\<le> z \\<Longrightarrow> x \\<le> (y \\<sqinter> z)\"\nproof -\n  fix x y z :: stamp\n  assume xlessy: \"x \\<le> y\"\n  assume xlessz: \"x \\<le> z\"\n  obtain l1 u1 where xdef: \"x = intstamp l1 u1\"\n    using stamp.exhaust by blast\n  obtain l2 u2 where ydef: \"y = intstamp l2 u2\"\n    using stamp.exhaust by blast\n  obtain l3 u3 where zdef: \"z = intstamp l3 u3\"\n    using stamp.exhaust by blast\n  obtain l4 u4 where yzdef: \"y \\<sqinter> z = intstamp l4 u4\"\n    by (meson inf_stamp.elims)\n  have max4: \"l4 = max l2 l3\"\n    using yzdef ydef zdef inf_stamp.simps by simp\n  have min4: \"u4 = min u2 u3\"\n    using yzdef ydef zdef inf_stamp.simps by simp\n  have \"{l1..u1} \\<subseteq> {l2..u2}\"\n    using xlessy xdef ydef\n    using less_eq_stamp.simps by blast\n  have \"{l1..u1} \\<subseteq> {l3..u3}\"\n    using xlessz xdef zdef\n    using less_eq_stamp.simps by blast\n  have leq: \"{l1..u1} \\<subseteq> {l4..u4}\"\n    using \\<open>{l1..u1} \\<subseteq> {l2..u2}\\<close> \\<open>{l1..u1} \\<subseteq> {l3..u3}\\<close> max4 min4 by auto\n  have \"x \\<le> (y \\<sqinter> z) = ({l1..u1} \\<subseteq> {l4..u4})\"\n    by (simp add: xdef yzdef)\n  then show \"x \\<le> (y \\<sqinter> z)\"\n    using leq\n    by fastforce\nqed\n\ninstance\n  apply standard\n  using inf_le1 apply simp\n  using inf_le2 apply simp\n  using inf_greatest by simp\nend\n\n\nsubsubsection \\<open>Stamp Meet\\<close>\ntext \\<open>\nDefines the @{emph \\<open>meet\\<close>} operation for stamps.\n\nFor any two stamps, the @{emph \\<open>meet\\<close>} is defined as the union\nof the valid values for the stamp.\n\\<close>\ninstantiation stamp :: semilattice_sup\nbegin\n\nnotation sup (infix \"\\<squnion>\" 65)\n\nfun sup_stamp :: \"stamp \\<Rightarrow> stamp \\<Rightarrow> stamp\" where\n  \"sup_stamp (intstamp l1 u1) (intstamp l2 u2) = intstamp (min l1 l2) (max u1 u2)\"\n\nlemma sup_ge1: \n  fixes x y :: stamp\n  shows \"x \\<le> x \\<squnion> y\"\nproof -\n  fix x :: stamp\n  fix y :: stamp\n  obtain l1 u1 where xdef: \"x = intstamp l1 u1\"\n    using stamp.exhaust by blast\n  obtain l2 u2 where ydef: \"y = intstamp l2 u2\"\n    using stamp.exhaust by blast\n  have joindef: \"x \\<squnion> y = intstamp (min l1 l2) (max u1 u2)\"\n    (is \"?join = intstamp ?l3 ?u3\")\n    using inf_stamp.simps xdef ydef\n    by force\n  have leq: \"{l1..u1} \\<subseteq> {?l3..?u3}\"\n    by simp\n  have \"x \\<le> x \\<squnion> y = ({l1..u1} \\<subseteq> {?l3..?u3})\"\n    using xdef joindef inf_stamp.simps\n    by force\n  then show \"x \\<le> x \\<squnion> y\"\n    using leq\n    by fastforce\nqed\n\nlemma sup_ge2:\n  fixes x y :: stamp\n  shows \"y \\<le> x \\<squnion> y\"\nproof -\n  fix x :: stamp\n  fix y :: stamp\n  obtain l1 u1 where xdef: \"x = intstamp l1 u1\"\n    using stamp.exhaust by blast\n  obtain l2 u2 where ydef: \"y = intstamp l2 u2\"\n    using stamp.exhaust by blast\n  have joindef: \"x \\<squnion> y = intstamp (min l1 l2) (max u1 u2)\"\n    (is \"?join = intstamp ?l3 ?u3\")\n    using inf_stamp.simps xdef ydef\n    by force\n  have leq: \"{l2..u2} \\<subseteq> {?l3..?u3}\" (is \"?subset_thesis\")\n    by simp\n  have \"?thesis = (?subset_thesis)\"\n    using ydef joindef sup_stamp.simps less_eq_stamp.simps\n    by (metis StampLattice.sup_ge1 max.commute min.commute sup_stamp.elims)\n  then show \"?thesis\"\n    using leq\n    by fastforce\nqed\n\nlemma sup_least:\n  fixes x y z :: stamp\n  shows \"y \\<le> x \\<Longrightarrow> z \\<le> x \\<Longrightarrow> ((y \\<squnion> z) \\<le> x)\"\nproof -\n  fix x y z :: stamp\n  assume xlessy: \"y \\<le> x\"\n  assume xlessz: \"z \\<le> x\"\n  obtain l1 u1 where xdef: \"x = intstamp l1 u1\"\n    using stamp.exhaust by blast\n  obtain l2 u2 where ydef: \"y = intstamp l2 u2\"\n    using stamp.exhaust by blast\n  obtain l3 u3 where zdef: \"z = intstamp l3 u3\"\n    using stamp.exhaust by blast\n  have yzdef: \"y \\<squnion> z = intstamp (min l2 l3) (max u2 u3)\"\n    (is \"?meet = intstamp ?l4 ?u4\")\n    using sup_stamp.simps\n    by (simp add: ydef zdef)\n  have s1: \"{l2..u2} \\<subseteq> {l1..u1}\"\n    using xlessy xdef ydef\n    using less_eq_stamp.simps by blast\n  have s2: \"{l3..u3} \\<subseteq> {l1..u1}\"\n    using xlessz xdef zdef\n    using less_eq_stamp.simps by blast\n  have leq: \"{?l4..?u4} \\<subseteq> {l1..u1}\" (is ?subset_thesis)\n    using s1 s2 unfolding atLeastatMost_subset_iff\n    (* why is this such a hard proof? *)\n    by (metis (no_types, opaque_lifting) inf.orderE inf_stamp.simps max.bounded_iff max.cobounded2 min.bounded_iff min.cobounded2 stamp.inject xdef xlessy xlessz ydef zdef)\n  have \"(y \\<squnion> z \\<le> x) = ?subset_thesis\"\n    using yzdef xdef less_eq_stamp.simps \n    by simp\n  then show \"(y \\<squnion> z \\<le> x)\"\n    using leq by fastforce\nqed\n\ninstance\n  apply standard\n  using sup_ge1 apply simp\n  using sup_ge2 apply simp\n  using sup_least by simp\nend\n\n\nsubsubsection \\<open>Stamp Bounds\\<close>\ntext \\<open>\nDefines the top and bottom elements of the stamp lattice.\n\nThis poses an interesting question as our stamp type is a\nunion of the various @{emph \\<open>Stamp\\<close>} subclasses, e.g.\n@{emph \\<open>IntegerStamp\\<close>}, @{emph \\<open>ObjectStamp\\<close>}, etc.\n\nEach subclass should preferably have its own unique\ntop and bottom element, i.e. An @{emph \\<open>IntegerStamp\\<close>}\nwould have the top element of the full range of integers\nallowed by the bit width and a bottom of a range with no integers.\nWhile the @{emph \\<open>ObjectStamp\\<close>} should have @{emph \\<open>Object\\<close>}\nas the top and @{emph \\<open>Void\\<close>} as the bottom element.\n\\<close>\ninstantiation stamp :: bounded_lattice\nbegin\n\nnotation bot (\"\\<bottom>\" 50)\nnotation top (\"\\<top>\" 50)\n\ndefinition width_min :: \"nat \\<Rightarrow> int64\" where\n  \"width_min bits = -(2^(bits-1))\"\n\ndefinition width_max :: \"nat \\<Rightarrow> int64\" where\n  \"width_max bits = (2^(bits-1)) - 1\"\n\nvalue \"(sint (width_min 64), sint (width_max 64))\"\nvalue \"max_word::int64\"\n\nlemma\n  assumes \"x = width_min 64\"\n  assumes \"y = width_max 64\"\n  shows \"sint x < sint y\"\n  using assms unfolding width_min_def width_max_def by simp\n\ntext \\<open>\nNote that this definition is valid for unsigned integers only.\n\nThe bottom and top element for signed integers would be\n(- 9223372036854775808, 9223372036854775807).\n\nFor unsigned we have\n(0, 18446744073709551615).\n\nFor Java we are likely to be more concerned with signed integers.\nTo use the appropriate bottom and top for signed integers we\nwould need to change our definition of less\\_eq from\n{l1..u1} <= {l2..u2}\nto\n{sint l1..sint u1} <= {sint l2..sint u2}\n\nWe may still find an unsigned integer stamp useful.\nI plan to investigate the Java code to see if this is useful\nand then apply the changes to switch to signed integers.\n\\<close>\ndefinition \"bot_stamp = intstamp (-1) 0\"\ndefinition \"top_stamp = intstamp 0 (-1)\"\n\nlemma bot_least:\n  fixes a :: stamp\n  shows \"(\\<bottom>) \\<le> a\"\nproof -\n  obtain min max where bot_def:\"\\<bottom> = intstamp max min\"\n    using bot_stamp_def \n    by force\n  have \"min < max\"\n    using bot_def\n    unfolding bot_stamp_def width_min_def width_max_def\n    using word_gt_0 by fastforce\n  then have \"{max..min} = {}\"\n    using bot_def\n    unfolding bot_stamp_def width_min_def width_max_def\n    by auto\n  then show ?thesis\n    unfolding bot_stamp_def\n    using less_eq_stamp.simps\n    by (simp add: stamp.induct)\nqed\n\nlemma top_greatest:\n  fixes a :: stamp\n  shows \"a \\<le> (\\<top>)\"\nproof -\n  obtain min max where top_def:\"\\<top> = intstamp min max\"\n    using top_stamp_def \n    by force\n  have max_is_max: \"\\<not>(\\<exists> n. n > max)\"\n    by (metis stamp.inject top_def top_stamp_def word_order.extremum_strict)\n  have min_is_min: \"\\<not>(\\<exists> n. n < min)\"\n    by (metis not_less_iff_gr_or_eq stamp.inject top_def top_stamp_def word_coorder.not_eq_extremum)\n  have \"\\<not>(\\<exists> l u. {min..max} < {l..u})\"\n    using max_is_max min_is_min\n    by (metis atLeastatMost_psubset_iff not_less)\n  then show ?thesis\n    unfolding top_stamp_def\n    using less_eq_stamp.simps\n    using less_eq_stamp.elims(3) by fastforce\nqed\n\ninstance\n  apply standard\n  using bot_least apply simp\n  using top_greatest by simp\nend\n\n\nsubsection \\<open>Java Stamp Methods\\<close>\ntext \\<open>\nThe following are methods from the Java Stamp class,\nthey are the methods primarily used for optimizations.\n\\<close>\ndefinition is_unrestricted :: \"stamp \\<Rightarrow> bool\" where\n  \"is_unrestricted s = (\\<top> = s)\"\n\nfun is_empty :: \"stamp \\<Rightarrow> bool\" where\n  \"is_empty s = (\\<bottom> = s)\"\n\nfun as_constant :: \"stamp \\<Rightarrow> Value option\" where\n  \"as_constant (intstamp l u) = (if (card {l..u}) = 1\n    then Some (IntVal 64 (SOME x. x \\<in> {l..u}))\n    else None)\"\n\ndefinition always_distinct :: \"stamp \\<Rightarrow> stamp \\<Rightarrow> bool\" where\n  \"always_distinct stamp1 stamp2 = (\\<bottom> = (stamp1 \\<sqinter> stamp2))\"\n\ndefinition never_distinct :: \"stamp \\<Rightarrow> stamp \\<Rightarrow> bool\" where\n  \"never_distinct stamp1 stamp2 = \n    (as_constant stamp1 = as_constant stamp2 \\<and> as_constant stamp1 \\<noteq> None)\"\n\n\nsubsection \\<open>Mapping to Values\\<close>\nfun valid_value :: \"stamp => Value => bool\" where\n  \"valid_value (intstamp l u) (IntVal b v) = (v \\<in> {l..u})\" |\n  \"valid_value (intstamp l u) _ = False\"\n\ntext \\<open>\nThe @{const valid_value} function is used to map a stamp instance\nto the values that are allowed by the stamp.\n\nIt would be nice if there was a slightly more integrated way\nto perform this mapping as it requires some infrastructure\nto prove some fairly simple properties.\n\\<close>\nlemma bottom_range_empty:\n  \"\\<not>(valid_value (\\<bottom>) v)\"\n  unfolding bot_stamp_def\n  using valid_value.elims(2) by fastforce\n\nlemma join_values:\n  assumes \"joined = x_stamp \\<sqinter> y_stamp\"\n  shows \"valid_value joined x \\<longleftrightarrow> (valid_value x_stamp x \\<and> valid_value y_stamp x)\"\nproof (cases x)\n  case UndefVal\n  then show ?thesis\n    using valid_value.elims(2) by blast\n(* WAS:\nnext\n  case (IntVal32 x2)\n  then show ?thesis\n    using valid_value.elims(2) by blast\n*)\nnext\n  case (IntVal b x3)\n  obtain lx ux where xdef: \"x_stamp = intstamp lx ux\"\n    using stamp.exhaust by blast\n  obtain ly uy where ydef: \"y_stamp = intstamp ly uy\"\n    using stamp.exhaust by blast\n  obtain v where \"x = IntVal b v\"\n    using IntVal by blast\n  have \"joined = intstamp (max lx ly) (min ux uy)\"\n    (is \"joined = intstamp ?lj ?uj\")\n    by (simp add: xdef ydef assms)\n  then have \"valid_value joined (IntVal b v) = (v \\<in> {?lj..?uj})\"\n    by simp\n  then show ?thesis\n    using \\<open>x = IntVal b v\\<close> xdef ydef by force\nnext\n  case (ObjRef x5)\n  then show ?thesis\n    using valid_value.elims(2) by blast\nnext\n  case (ObjStr x6)\n  then show ?thesis\n    using valid_value.elims(2) by blast\nqed\n\nlemma disjoint_empty:\n  fixes x_stamp y_stamp :: stamp\n  assumes \"\\<bottom> = x_stamp \\<sqinter> y_stamp\"\n  shows \"\\<not>(valid_value x_stamp x \\<and> valid_value y_stamp x)\"\n  using assms bottom_range_empty join_values\n  by blast\n\n\nexperiment begin\ntext \\<open>A possible equivalent alternative to the definition of less\\_eq\\<close>\nfun less_eq_alt :: \"'a::ord \\<times> 'a \\<Rightarrow> 'a \\<times> 'a \\<Rightarrow> bool\" where\n  \"less_eq_alt (l1, u1) (l2, u2) = ((\\<not> l1 \\<le> u1) \\<or> l2 \\<le> l1 \\<and> u1 \\<le> u2)\"\n\ntext \\<open>Proof equivalence\\<close>\nlemma \n  fixes l1 l2 u1 u2 :: int\n  assumes \"l1 \\<le> u1 \\<and> l2 \\<le> u2\"\n  shows \"{l1..u1} \\<subseteq> {l2..u2} = ((l1 \\<ge> l2) \\<and> (u1 \\<le> u2))\"\n  by (simp add: assms)\n\nlemma \n  fixes l1 l2 u1 u2 :: int\n  shows \"{l1..u1} \\<subseteq> {l2..u2} = less_eq_alt (l1, u1) (l2, u2)\"\n  by simp\nend\n\n\n\nsubsection \\<open>Generic Integer Stamp\\<close>\n\ntext \\<open>\nExperimental definition of integer stamps generically,\nrestricting the datatype to only allow valid ranges and\nthe bottom integer element (max\\_int..min\\_int).\n\\<close>\n\nlemma \n  assumes \"(x::int) > 0\"\n  shows \"(2 ^ x)/2 = (2 ^ (x - 1))\"\n  sorry\n\ndefinition max_signed_int :: \"'a::len word\" where\n  \"max_signed_int = (2 ^ (LENGTH('a) - 1)) - 1\"\n\ndefinition min_signed_int :: \"'a::len word\" where\n  \"min_signed_int = -(2 ^ (LENGTH('a) - 1))\"\n\ndefinition int_bottom :: \"'a::len word \\<times> 'a word\" where\n  \"int_bottom = (max_signed_int, min_signed_int)\"\n\ndefinition int_top :: \"'a::len word \\<times> 'a word\" where\n  \"int_top = (min_signed_int, max_signed_int)\"\n\n(*\ndefinition signed_gt_eq :: \"'a::len word \\<Rightarrow> 'a word \\<Rightarrow> bool\" where\n  \"signed_gt_eq a b = (sint a \\<ge> sint a)\"\n\ndefinition signed_gt :: \"'a::len word \\<Rightarrow> 'a word \\<Rightarrow> bool\" where\n  \"signed_gt a b = (sint a > sint a)\"\n\ninterpretation wor: ordering_top \\<open>signed_gt_eq\\<close> \\<open>signed_gt\\<close> \\<open>max_signed_int :: 'a::len word\\<close>\n  apply (standard) sledgehammer\n*)\n\nlemma\n  fixes x :: \"'a::len word\"\n  shows \"sint x \\<le> sint (((2 ^ (LENGTH('a) - 1)) - 1)::'a word)\"\n  using sint_greater_eq sorry (*\n  by (smt (z3) Euclidean_Division.pos_mod_bound int_word_sint sint_0 sint_lt two_less_eq_exp_length word_of_int_2p_len)\n  *)\n\n(* helpful: sint_greater_eq *)\nvalue \"sint (0::1 word)\"\nvalue \"sint (1::1 word)\"\nvalue \"sint (((2 ^ 0) - 1)::1 word)\"\n\nvalue \"sint (((2 ^ 31) - 1)::32 word)\"\n\nlemma max_signed:\n  fixes a :: \"'a::len word\"\n  shows \"sint a \\<le> sint (max_signed_int::'a word)\"\nproof (cases \"sint a = sint (max_signed_int::'a word)\")\n  case True\n  then show ?thesis by simp\nnext\n  case False\n  have \"sint a < sint (max_signed_int::'a word)\"\n    using False unfolding max_signed_int_def sorry\n  then show ?thesis by simp\nqed\n\nlemma min_signed:\n  fixes a :: \"'a::len word\"\n  shows \"sint a \\<ge> sint (min_signed_int::'a word)\"\n  sorry\n\nvalue \"max_signed_int :: 32 word\"\nvalue \"int_bottom::(32 word \\<times> 32 word)\"\nvalue \"sint (2147483647::32 word)\"\nvalue \"sint (2147483648::32 word)\"\n\n\n\ntypedef (overloaded) ('a::len) intstamp = \n  \"{bounds :: ('a word, 'a word) prod . ((fst bounds) \\<le>s (snd bounds) \\<or> bounds = int_bottom)}\"\nproof -\n  show ?thesis\n    by (smt (z3) mem_Collect_eq prod.sel(1) prod.sel(2) signed_minus_1 sint_0)\nqed\n\nsetup_lifting type_definition_intstamp\n\nlift_definition lower :: \"('a::len) intstamp \\<Rightarrow> 'a word\"\n  is \"prod.fst \\<circ> Rep_intstamp\" .\n\nlift_definition upper :: \"('a::len) intstamp \\<Rightarrow> 'a word\"\n  is \"prod.snd \\<circ> Rep_intstamp\" .\n\nlift_definition lower_int :: \"('a::len) intstamp \\<Rightarrow> int\"\n  is \"sint \\<circ> prod.fst\" .\n\nlift_definition upper_int :: \"('a::len) intstamp \\<Rightarrow> int\"\n  is \"sint \\<circ> prod.snd\" .\n\nlift_definition range :: \"('a::len) intstamp \\<Rightarrow> int set\"\n  is \"\\<lambda> (l, u). {sint l..sint u}\" .\n\nlift_definition bounds :: \"('a::len) intstamp \\<Rightarrow> ('a word \\<times> 'a word)\"\n  is Rep_intstamp .\n\nlift_definition is_bottom :: \"('a::len) intstamp \\<Rightarrow> bool\"\n  is \"\\<lambda> x. x = int_bottom\" .\n\nlift_definition from_bounds :: \"('a::len word \\<times> 'a word) \\<Rightarrow> 'a intstamp\"\n  is \"Abs_intstamp\" .\n\n\ninstantiation intstamp :: (len) order\nbegin\n\ndefinition less_eq_intstamp :: \"'a intstamp \\<Rightarrow> 'a intstamp \\<Rightarrow> bool\" where\n  \"less_eq_intstamp s1 s2 = (range s1 \\<subseteq> range s2)\"\n\ndefinition less_intstamp :: \"'a intstamp \\<Rightarrow> 'a intstamp \\<Rightarrow> bool\" where\n  \"less_intstamp s1 s2 = (range s1 \\<subset> range s2)\"\n\n\nvalue \"int_bottom::(1 word \\<times> 1 word)\"\nvalue \"sint (0::1 word)\"\nvalue \"sint (1::1 word)\"\n\nvalue \"int_bottom::(2 word \\<times> 2 word)\"\nvalue \"sint (1::2 word)\"\nvalue \"sint (2::2 word)\"\nvalue \"sint ((2 ^ (LENGTH(32) - 1) - 1)::32 word) > sint ((- (2 ^ (LENGTH(32) - 1)))::32 word)\"\n\nlemma bottom_is_bottom:\n  assumes \"is_bottom s\"\n  shows \"s \\<le> a\"\nproof -\n  have boundsdef: \"bounds s = int_bottom\"\n    by (metis assms bounds.transfer is_bottom.rep_eq)\n  obtain min max where \"bounds s = (max, min)\"\n    by fastforce\n  then have \"max \\<noteq> min\"\n    by (metis boundsdef dual_order.eq_iff fst_conv int_bottom_def less_minus_one_simps(1) max_signed min_signed not_less sint_0 sint_n1 snd_conv)\n  then have \"sint min < sint max\"\n    unfolding boundsdef int_bottom_def \n    using max_signed\n    by (metis \\<open>bounds s = (max, min)\\<close> boundsdef int_bottom_def order.not_eq_order_implies_strict prod.sel(1) signed_word_eqI)\n  then have \"range s = {}\"\n    unfolding range_def bounds_def\n    by (simp add: \\<open>bounds s = (max, min)\\<close> bounds.transfer)\n  then show ?thesis\n    by (simp add: StampLattice.less_eq_intstamp_def)\nqed\n\nlemma bounds_has_value:\n  fixes x y :: int\n  assumes \"x < y\"\n  shows \"card {x..y} > 0\"\n  using assms by auto\n\nlemma bounds_has_no_value:\n  fixes x y :: int\n  assumes \"x < y\"\n  shows \"card {y..x} = 0\"\n  using assms by auto\n\nlemma bottom_unique: \n  fixes a s :: \"'a intstamp\"\n  assumes \"is_bottom s\"\n  shows \"a \\<le> s \\<longleftrightarrow> is_bottom a\"\nproof -\n  have \"\\<forall>x. sint (fst (bounds x)) \\<le> sint (snd (bounds x)) \\<or> is_bottom x\"\n    unfolding bounds_def is_bottom_def\n    using Rep_intstamp\n    using word_sle_eq by auto\n  then have \"\\<forall>x. (card (range x)) > 0 \\<or> is_bottom x\"\n    unfolding range_def using bounds_has_value\n    by (simp add: bounds.transfer case_prod_beta)\n  obtain min max where boundsdef: \"bounds s = (max, min)\"\n    by fastforce\n  have nooverlap: \"sint min < sint max\"\n    using max_signed\n    by (metis assms bounds.transfer boundsdef fst_conv int_bottom_def is_bottom.rep_eq min_signed order.not_eq_order_implies_strict signed_word_eqI sint_0 snd_conv verit_la_disequality zero_neq_one)\n  have \"range s = {sint max..sint min}\"\n    by (simp add: bounds.transfer boundsdef range.rep_eq)\n  then have \"card (range s) = 0\"\n    using nooverlap bounds_has_no_value by simp\n  then have \"\\<forall>x. (card (range x)) > 0 \\<longrightarrow> s < x\"\n    using \\<open>StampLattice.range s = {sint max..sint min}\\<close> atLeastatMost_empty less_intstamp_def by auto\n  then show ?thesis\n    by (meson \\<open>\\<forall>x. 0 < card (StampLattice.range x) \\<or> is_bottom x\\<close> bottom_is_bottom leD less_eq_intstamp_def less_intstamp_def)\nqed\n\n\nlemma bottom_antisym:\n  assumes \"is_bottom x\"\n  shows \"x \\<le> y \\<Longrightarrow> y \\<le> x \\<Longrightarrow> x = y\"\n  using assms proof (cases \"is_bottom y\")\ncase True\n  then show ?thesis\n    by (metis Rep_intstamp_inverse assms is_bottom.rep_eq)\nnext\n  case False\n  assume \"y \\<le> x\"\n  have \"\\<not>(y \\<le> x)\"\n    using bottom_unique False assms\n    by simp\n  then show ?thesis\n    using \\<open>y \\<le> x\\<close> by auto\nqed\n\nlemma int_antisym:\n  fixes x y :: \"'a intstamp\"\n  shows \"x \\<le> y \\<Longrightarrow> y \\<le> x \\<Longrightarrow> x = y\"\nproof -\n  fix x :: \"'a intstamp\"\n  fix y :: \"'a intstamp\"\n  assume xlessy: \"x \\<le> y\"\n  assume ylessx: \"y \\<le> x\"\n  obtain l1 u1 where xdef: \"bounds x = (l1, u1)\"\n    by fastforce\n  obtain l2 u2 where ydef: \"bounds y = (l2, u2)\"\n    by fastforce\n  \n  from xlessy have s1: \"{sint l1..sint u1} \\<subseteq> {sint l2..sint u2}\" (is \"?xlessy\")\n    using xdef ydef unfolding bounds_def range_def less_eq_intstamp_def\n    by simp\n  from ylessx have s2: \"{sint l2..sint u2} \\<subseteq> {sint l1..sint u1}\" (is \"?ylessx\")\n    using xdef ydef unfolding bounds_def range_def less_eq_intstamp_def\n    by simp\n  show \"x = y\" proof (cases \"is_bottom x\")\n    case True\n    then show ?thesis using bottom_antisym xlessy ylessx\n      by simp\n  next\n    case False\n    then show ?thesis sorry\n  qed\nqed\n\ninstance\n  apply standard\n     apply (simp add: less_eq_intstamp_def less_intstamp_def less_le_not_le)\n  apply blast\n  using less_eq_intstamp_def apply force\n  using less_eq_intstamp_def apply force\n  by (simp add: int_antisym)\nend\n\nvalue \"take_bit LENGTH(63) 20::int\"\nvalue \"take_bit LENGTH(63) ((-20)::int)\"\nvalue \"bit (20::int64) (63::nat)\"\nvalue \"bit ((-20)::int64) (63::nat)\"\n\nvalue \"((-20)::int64) < (20::int64)\"\n\nvalue \"take_bit LENGTH(63) ((-20)::int)\"\n\nlift_definition smax :: \"'a::len word \\<Rightarrow> 'a word \\<Rightarrow> 'a word\"\n  is \"\\<lambda> a b. (if (sint a) \\<le> (sint b) then b else a)\" .\n\nlift_definition smin :: \"'a::len word \\<Rightarrow> 'a word \\<Rightarrow> 'a word\"\n  is \"\\<lambda> a b. (if (sint a) \\<le> (sint b) then a else b)\" .\n\n\ninstantiation intstamp :: (len) semilattice_inf\nbegin\n\nnotation inf (infix \"\\<sqinter>\" 65)\n\ndefinition join_bounds :: \"'a intstamp \\<Rightarrow> 'a intstamp \\<Rightarrow> ('a word \\<times> 'a word)\" where\n  \"join_bounds s1 s2 = (smax (lower s1) (lower s2), smin (upper s1) (upper s2))\"\n\ndefinition join_or_bottom :: \"'a intstamp \\<Rightarrow> 'a intstamp \\<Rightarrow> ('a word \\<times> 'a word)\" where\n  \"join_or_bottom s1 s2 = (let bound = (join_bounds s1 s2) in \n    if sint (fst bound) \\<ge> sint (snd bound) then int_bottom else bound)\"\n\ndefinition inf_intstamp :: \"'a intstamp \\<Rightarrow> 'a intstamp \\<Rightarrow> 'a intstamp\" where\n  \"inf_intstamp s1 s2 = from_bounds (join_or_bottom s1 s2)\"\n\nlemma always_valid:\n  fixes s1 s2 :: \"'a intstamp\"\n  shows \"Rep_intstamp (from_bounds (join_or_bottom s1 s2)) = join_or_bottom s1 s2\"\n  unfolding join_or_bottom_def join_bounds_def from_bounds_def\n  using Abs_intstamp_inverse\n  by (smt (z3) from_bounds.transfer from_bounds_def mem_Collect_eq word_sle_eq)\n\nlemma invalid_join:\n  fixes s1 s2 :: \"'a intstamp\"\n  assumes \"bound = join_bounds s1 s2\"\n  assumes \"sint (fst bound) \\<ge> sint (snd bound)\"\n  shows \"from_bounds int_bottom = s1 \\<sqinter> s2\"\n  using assms(1) assms(2) inf_intstamp_def join_or_bottom_def by presburger\n\nlemma unfold_bounds:\n  \"bounds x = (lower x, upper x)\"\n  by (simp add: bounds.transfer lower.rep_eq upper.rep_eq)\n\nlemma int_inf_le1: \n  fixes x y :: \"'a intstamp\"\n  shows \"(x \\<sqinter> y) \\<le> x\"\nproof (cases \"is_bottom (x \\<sqinter> y)\")\n  case True\n  then show ?thesis\n    by (simp add: bottom_is_bottom)\nnext\n  case False\n  then show ?thesis\n  using False proof -\n  obtain l1 u1 where xdef: \"lower x = l1 \\<and> upper x = u1\"\n    by fastforce\n  obtain l2 u2 where ydef: \"lower y = l2 \\<and> upper y = u2\"\n    by fastforce\n  have joindef: \"x \\<sqinter> y = from_bounds ((smax l1 l2, smin u1 u2))\"\n    (is \"x \\<sqinter> y = from_bounds (?l3, ?u3)\")\n    using False\n    by (smt (z3) StampLattice.inf_intstamp_def StampLattice.join_bounds_def always_valid is_bottom.rep_eq join_or_bottom_def xdef ydef)\n  have leq: \"{sint ?l3..sint ?u3} \\<subseteq> {sint l1..sint u1}\"\n    by (smt (z3) atLeastatMost_subset_iff smax.transfer smin.transfer)\n  have \"(x \\<sqinter> y) \\<le> x = ({sint ?l3..sint ?u3} \\<subseteq> {sint l1..sint u1})\"\n    using xdef joindef range_def less_eq_intstamp_def\n    by (smt (z3) False StampLattice.always_valid StampLattice.join_or_bottom_def bounds.abs_eq case_prod_conv inf_intstamp_def is_bottom.rep_eq join_bounds_def range.rep_eq unfold_bounds ydef)\n  then show \"(x \\<sqinter> y) \\<le> x\"\n    using leq\n    by fastforce\nqed\nqed\n\nlemma int_inf_le2: \n  fixes x y :: \"'a intstamp\"\n  shows \"(x \\<sqinter> y) \\<le> y\"\nproof (cases \"is_bottom (x \\<sqinter> y)\")\n  case True\n  then show ?thesis\n    by (simp add: bottom_is_bottom)\nnext\n  case False\n  then show ?thesis\n  using False proof -\n  obtain l1 u1 where xdef: \"lower x = l1 \\<and> upper x = u1\"\n    by fastforce\n  obtain l2 u2 where ydef: \"lower y = l2 \\<and> upper y = u2\"\n    by fastforce\n  have joindef: \"x \\<sqinter> y = from_bounds ((smax l1 l2, smin u1 u2))\"\n    (is \"x \\<sqinter> y = from_bounds (?l3, ?u3)\")\n    using False\n    by (smt (z3) StampLattice.inf_intstamp_def StampLattice.join_bounds_def always_valid is_bottom.rep_eq join_or_bottom_def xdef ydef)\n  have leq: \"{sint ?l3..sint ?u3} \\<subseteq> {sint l1..sint u1}\"\n    by (smt (z3) atLeastatMost_subset_iff smax.transfer smin.transfer)\n  have \"(x \\<sqinter> y) \\<le> y = ({sint ?l3..sint ?u3} \\<subseteq> {sint l2..sint u2})\"\n    using xdef joindef range_def less_eq_intstamp_def\n    by (smt (z3) False StampLattice.always_valid StampLattice.join_or_bottom_def bounds.abs_eq case_prod_conv inf_intstamp_def is_bottom.rep_eq join_bounds_def range.rep_eq unfold_bounds ydef)\n  then show \"(x \\<sqinter> y) \\<le> y\"\n    using leq\n    by (smt (z3) atLeastatMost_subset_iff smax.transfer smin.transfer)\nqed\nqed\n\nlemma\n  assumes \"x \\<le> y\"\n  assumes \"is_bottom y\"\n  shows \"is_bottom x\"\n  using bottom_is_bottom assms\n  using bottom_unique by auto\n\nlemma int_inf_greatest:\n  fixes x y :: \"'a intstamp\"\n  shows \"x \\<le> y \\<Longrightarrow> x \\<le> z \\<Longrightarrow> x \\<le> y \\<sqinter> z\"\n  sorry\n\ninstance\n  apply standard\n    apply (simp add: local.int_inf_le1)\n   apply (simp add: local.int_inf_le2)\n  by (simp add: local.int_inf_greatest)\n\nend\n\n\ninstantiation intstamp :: (len) semilattice_sup\nbegin\n\nnotation sup (infix \"\\<squnion>\" 65)\n\ninstance sorry\n\nend\n\ninstantiation intstamp :: (len) bounded_lattice\nbegin\n\nnotation bot (\"\\<bottom>\" 50)\nnotation top (\"\\<top>\" 50)\n\ndefinition \"bot_intstamp = int_bottom\"\ndefinition \"top_intstamp = int_top\"\n\ninstance sorry\n\nend\n\nvalue \"sint (0::1 word)\"\nvalue \"sint (1::1 word)\"\n\ndatatype Stamp =\n  BottomStamp |\n  TopStamp |\n  VoidStamp |\n  (*Int1Stamp \"1 uintstamp\" |*)\n  Int8Stamp \"8 intstamp\" |\n  Int16Stamp \"16 intstamp\" |\n  Int32Stamp \"32 intstamp\" |\n  Int64Stamp \"64 intstamp\"\n\ninstantiation Stamp :: order\nbegin\n\nfun less_eq_Stamp :: \"Stamp \\<Rightarrow> Stamp \\<Rightarrow> bool\" where\n  \"less_eq_Stamp BottomStamp _ = True\" |\n  \"less_eq_Stamp _ TopStamp = True\" |\n  \"less_eq_Stamp VoidStamp VoidStamp = True\" |\n  \"less_eq_Stamp (Int8Stamp v1) (Int8Stamp v2) = (v1 \\<le> v2)\" |\n  \"less_eq_Stamp (Int16Stamp v1) (Int16Stamp v2) = (v1 \\<le> v2)\" |\n  \"less_eq_Stamp (Int32Stamp v1) (Int32Stamp v2) = (v1 \\<le> v2)\" |\n  \"less_eq_Stamp (Int64Stamp v1) (Int64Stamp v2) = (v1 \\<le> v2)\" |\n  \"less_eq_Stamp _ _ = False\"\n\nfun less_Stamp :: \"Stamp \\<Rightarrow> Stamp \\<Rightarrow> bool\" where\n  \"less_Stamp BottomStamp BottomStamp = False\" |\n  \"less_Stamp BottomStamp _ = True\" |\n  \"less_Stamp TopStamp TopStamp = False\" |\n  \"less_Stamp _ TopStamp = True\" |\n  \"less_Stamp VoidStamp VoidStamp = False\" |\n  \"less_Stamp (Int8Stamp v1) (Int8Stamp v2) = (v1 < v2)\" |\n  \"less_Stamp (Int16Stamp v1) (Int16Stamp v2) = (v1 < v2)\" |\n  \"less_Stamp (Int32Stamp v1) (Int32Stamp v2) = (v1 < v2)\" |\n  \"less_Stamp (Int64Stamp v1) (Int64Stamp v2) = (v1 < v2)\" |\n  \"less_Stamp _ _ = False\"\n\ninstance\n  apply standard sorry\nend\n\ninstantiation Stamp :: semilattice_inf\nbegin\n\nnotation inf (infix \"\\<sqinter>\" 65)\n\nfun inf_Stamp :: \"Stamp \\<Rightarrow> Stamp \\<Rightarrow> Stamp\" where\n  \"inf_Stamp BottomStamp _ = BottomStamp\" |\n  \"inf_Stamp _ BottomStamp = BottomStamp\" |\n  \"inf_Stamp TopStamp _ = TopStamp\" |\n  \"inf_Stamp _ TopStamp = TopStamp\" |\n  \"inf_Stamp VoidStamp VoidStamp = VoidStamp\" |\n  \"inf_Stamp (Int8Stamp v1) (Int8Stamp v2) = Int8Stamp (v1 \\<sqinter> v2)\" |\n  \"inf_Stamp (Int16Stamp v1) (Int16Stamp v2) = Int16Stamp (v1 \\<sqinter> v2)\" |\n  \"inf_Stamp (Int32Stamp v1) (Int32Stamp v2) = Int32Stamp (v1 \\<sqinter> v2)\" |\n  \"inf_Stamp (Int64Stamp v1) (Int64Stamp v2) = Int64Stamp (v1 \\<sqinter> v2)\"\n\ninstance\n  apply standard sorry\nend\n\n\ninstantiation Stamp :: semilattice_sup\nbegin\n\nnotation sup (infix \"\\<squnion>\" 65)\n\nfun sup_Stamp :: \"Stamp \\<Rightarrow> Stamp \\<Rightarrow> Stamp\" where\n  \"sup_Stamp BottomStamp _ = BottomStamp\" |\n  \"sup_Stamp _ BottomStamp = BottomStamp\" |\n  \"sup_Stamp TopStamp _ = TopStamp\" |\n  \"sup_Stamp _ TopStamp = TopStamp\" |\n  \"sup_Stamp VoidStamp VoidStamp = VoidStamp\" |\n  \"sup_Stamp (Int8Stamp v1) (Int8Stamp v2) = Int8Stamp (v1 \\<squnion> v2)\" |\n  \"sup_Stamp (Int16Stamp v1) (Int16Stamp v2) = Int16Stamp (v1 \\<squnion> v2)\" |\n  \"sup_Stamp (Int32Stamp v1) (Int32Stamp v2) = Int32Stamp (v1 \\<squnion> v2)\" |\n  \"sup_Stamp (Int64Stamp v1) (Int64Stamp v2) = Int64Stamp (v1 \\<squnion> v2)\"\n\ninstance\n  apply standard sorry\nend\n\n\ninstantiation Stamp :: bounded_lattice\nbegin\n\nnotation bot (\"\\<bottom>\" 50)\nnotation top (\"\\<top>\" 50)\n\ndefinition top_Stamp :: \"Stamp\" where\n  \"top_Stamp = TopStamp\"\ndefinition bot_Stamp :: \"Stamp\" where\n  \"bot_Stamp = BottomStamp\"\n\ninstance\n  apply standard sorry\nend\n\n\n\ncode_datatype Abs_intstamp\n(*\nvalue \"Int32Stamp (from_bounds (2::32 word, 5::32 word)) \\<sqinter> Int32Stamp (from_bounds (2::32 word, 5::32 word))\"\n*)\nend", "meta": {"author": "uqcyber", "repo": "veriopt-releases", "sha": "4ffab3c91bbd699772889dbf263bb6d2582256d7", "save_path": "github-repos/isabelle/uqcyber-veriopt-releases", "path": "github-repos/isabelle/uqcyber-veriopt-releases/veriopt-releases-4ffab3c91bbd699772889dbf263bb6d2582256d7/Graph/StampLattice.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8791467675095294, "lm_q2_score": 0.8006919949619793, "lm_q1q2_score": 0.7039257791415805}}
{"text": "(*  \n    Author:      Sebastiaan Joosten \n                 Ren\u00e9 Thiemann\n                 Akihisa Yamada\n    License:     BSD\n*)\nsection \\<open>Interval Arithmetic\\<close>\n\ntext \\<open>We provide basic interval arithmetic operations for real and complex intervals.\n  As application we prove that complex polynomial evaluation is continuous w.r.t.\n  interval arithmetic. To be more precise, if an interval sequence converges to some \n  element $x$, then the interval polynomial evaluation of $f$ tends to $f(x)$.\\<close>\n  \ntheory Interval_Arithmetic\nimports\n  Algebraic_Numbers_Prelim (* for ipoly *)\nbegin\n\ntext \\<open>Intervals\\<close>\n\ndatatype ('a) interval = Interval (lower: 'a) (upper: 'a)\n\nhide_const(open) lower upper\n\ndefinition to_interval where \"to_interval a \\<equiv> Interval a a\"\n\nabbreviation of_int_interval :: \"int \\<Rightarrow> 'a :: ring_1 interval\" where\n  \"of_int_interval x \\<equiv> to_interval (of_int x)\" \n\n\nsubsection \\<open>Syntactic Class Instantiations\\<close>\n\ninstantiation interval :: (\"zero\") zero begin\n  definition zero_interval where \"0 \\<equiv> Interval 0 0\"\n  instance..\nend\n\ninstantiation interval :: (one) one begin\n  definition \"1 = Interval 1 1\"\n  instance..\nend\n\ninstantiation interval :: (plus) plus begin\n  fun plus_interval where \"Interval lx ux + Interval ly uy = Interval (lx + ly) (ux + uy)\"\n  instance..\nend\n\ninstantiation interval :: (uminus) uminus begin\n  fun uminus_interval where \"- Interval l u = Interval (-u) (-l)\"\n  instance..\nend\n\ninstantiation interval :: (minus) minus begin\n  fun minus_interval where \"Interval lx ux - Interval ly uy = Interval (lx - uy) (ux - ly)\"\n  instance..\nend\n\ninstantiation interval :: (\"{ord,times}\") times begin\n  fun times_interval where\n  \"Interval lx ux * Interval ly uy =\n     (let x1 = lx * ly; x2 = lx * uy; x3 = ux * ly; x4 = ux * uy\n      in Interval (min x1 (min x2 (min x3 x4))) (max x1 (max x2 (max x3 x4))))\"\n  instance..\nend\n\ninstantiation interval :: (\"{ord,times,inverse}\") \"inverse\" begin\n  fun inverse_interval where\n    \"inverse (Interval l u) = Interval (inverse u) (inverse l)\"\n  definition divide_interval :: \"'a interval \\<Rightarrow> _\" where\n    \"divide_interval X Y = X  * (inverse Y)\"\n  instance..\nend\n\nsubsection \\<open>Class Instantiations\\<close>\n\ninstance interval :: (semigroup_add) semigroup_add\nproof\n  fix a b c :: \"'a interval\"\n  show \"a + b + c = a + (b + c)\" by (cases a, cases b, cases c, auto simp: ac_simps)\nqed\n\ninstance interval :: (monoid_add) monoid_add\nproof\n  fix a :: \"'a interval\"\n  show \"0 + a = a\" by (cases a, auto simp: zero_interval_def)\n  show \"a + 0 = a\" by (cases a, auto simp: zero_interval_def)\nqed\n\ninstance interval :: (ab_semigroup_add) ab_semigroup_add\nproof\n  fix a b :: \"'a interval\"\n  show \"a + b = b + a\" by (cases a, cases b, auto simp: ac_simps)\nqed\n\ninstance interval :: (comm_monoid_add) comm_monoid_add by (intro_classes, auto)\n\ntext \\<open>Intervals do not form an additive group, but satisfy some properties.\\<close>\n\nlemma interval_uminus_zero[simp]:\n  shows \"-(0 :: 'a :: group_add interval) = 0\"\n  by (simp add: zero_interval_def)\n\nlemma interval_diff_zero[simp]:\n  fixes a :: \"'a :: cancel_comm_monoid_add interval\"\n  shows \"a - 0 = a\" by (cases a, simp add: zero_interval_def)\n\ntext \\<open>Without type invariant, intervals do not form a multiplicative monoid,\n but satisfy some properties.\\<close>\n\ninstance interval :: (\"{linorder,mult_zero}\") mult_zero\nproof\n  fix a :: \"'a interval\"\n  show \"a * 0 = 0\" \"0 * a = 0\" by (atomize(full), cases a, auto simp: zero_interval_def)\nqed\n\nsubsection \\<open>Membership\\<close>\n\nfun in_interval :: \"'a :: order \\<Rightarrow> 'a interval \\<Rightarrow> bool\" (\"(_/ \\<in>\\<^sub>i _)\" [51, 51] 50) where\n  \"y \\<in>\\<^sub>i Interval lx ux = (lx \\<le> y \\<and> y \\<le> ux)\" \n\nlemma in_interval_to_interval[intro!]: \"a \\<in>\\<^sub>i to_interval a\"\n  by (auto simp: to_interval_def)\n\nlemma plus_in_interval:\n  fixes x y :: \"'a :: ordered_comm_monoid_add\"\n  shows \"x \\<in>\\<^sub>i X \\<Longrightarrow> y \\<in>\\<^sub>i Y \\<Longrightarrow> x + y \\<in>\\<^sub>i X + Y\"\n  by (cases X, cases Y, auto dest:add_mono)\n\n\n\nlemma minus_in_interval:\n  fixes x y :: \"'a :: ordered_ab_group_add\"\n  shows \"x \\<in>\\<^sub>i X \\<Longrightarrow> y \\<in>\\<^sub>i Y \\<Longrightarrow> x - y \\<in>\\<^sub>i X - Y\"\n  by (cases X, cases Y, auto dest:diff_mono)\n\nlemma times_in_interval:\n  fixes x y :: \"'a :: linordered_ring\"\n  assumes \"x \\<in>\\<^sub>i X\" \"y \\<in>\\<^sub>i Y\"\n  shows \"x * y \\<in>\\<^sub>i X * Y\"\nproof -\n  obtain X1 X2 where X:\"Interval X1 X2 = X\" by (cases X,auto)\n  obtain Y1 Y2 where Y:\"Interval Y1 Y2 = Y\" by (cases Y,auto)\n  from assms X Y have assms: \"X1 \\<le> x\" \"x \\<le> X2\" \"Y1 \\<le> y\" \"y \\<le> Y2\" by auto\n  have \"(X1 * Y1 \\<le> x * y \\<or> X1 * Y2 \\<le> x * y \\<or> X2 * Y1 \\<le> x * y \\<or> X2 * Y2 \\<le> x * y) \\<and>\n        (X1 * Y1 \\<ge> x * y \\<or> X1 * Y2 \\<ge> x * y \\<or> X2 * Y1 \\<ge> x * y \\<or> X2 * Y2 \\<ge> x * y)\"\n  proof (cases x \"0::'a\" rule: linorder_cases)\n    case x0: less\n    show ?thesis\n    proof (cases \"y < 0\")\n      case y0: True\n      from y0 x0 assms have \"x * y \\<le> X1 * y\" by (intro mult_right_mono_neg, auto)\n      also from x0 y0 assms have \"X1 * y \\<le> X1 * Y1\" by (intro mult_left_mono_neg, auto)\n      finally have 1: \"x * y \\<le> X1 * Y1\".\n      show ?thesis proof(cases \"X2 \\<le> 0\")\n        case True\n        with assms have \"X2 * Y2 \\<le> X2 * y\" by (auto intro: mult_left_mono_neg)\n        also from assms y0 have \"... \\<le> x * y\" by (auto intro: mult_right_mono_neg)\n        finally have \"X2 * Y2 \\<le> x * y\".\n        with 1 show ?thesis by auto\n      next\n        case False\n        with assms have \"X2 * Y1 \\<le> X2 * y\" by (auto intro: mult_left_mono)\n        also from assms y0 have \"... \\<le> x * y\" by (auto intro: mult_right_mono_neg)\n        finally have \"X2 * Y1 \\<le> x * y\".\n        with 1 show ?thesis by auto\n      qed\n    next\n      case False\n      then have y0: \"y \\<ge> 0\" by auto\n      from x0 y0 assms have \"X1 * Y2 \\<le> x * Y2\" by (intro mult_right_mono, auto)\n      also from y0 x0 assms have \"... \\<le> x * y\" by (intro mult_left_mono_neg, auto)\n      finally have 1: \"X1 * Y2 \\<le> x * y\".\n      show ?thesis\n      proof(cases \"X2 \\<le> 0\")\n        case X2: True\n        from assms y0 have \"x * y \\<le> X2 * y\" by (intro mult_right_mono)\n        also from assms X2 have \"... \\<le> X2 * Y1\" by (auto intro: mult_left_mono_neg)\n        finally have \"x * y \\<le> X2 * Y1\".\n        with 1 show ?thesis by auto\n      next\n        case X2: False\n        from assms y0 have \"x * y \\<le> X2 * y\" by (intro mult_right_mono)\n        also from assms X2 have \"... \\<le> X2 * Y2\" by (auto intro: mult_left_mono)\n        finally have \"x * y \\<le> X2 * Y2\".\n        with 1 show ?thesis by auto\n      qed\n    qed\n  next\n    case [simp]: equal\n    with assms show ?thesis by (cases \"Y2 \\<le> 0\", auto intro:mult_sign_intros)\n  next\n    case x0: greater\n    show ?thesis\n    proof (cases \"y < 0\")\n      case y0: True\n      from x0 y0 assms have \"X2 * Y1 \\<le> X2 * y\" by (intro mult_left_mono, auto)\n      also from y0 x0 assms have \"X2 * y \\<le> x * y\" by (intro mult_right_mono_neg, auto)\n      finally have 1: \"X2 * Y1 \\<le> x * y\".\n      show ?thesis\n      proof(cases \"Y2 \\<le> 0\")\n        case Y2: True\n        from x0 assms have \"x * y \\<le> x * Y2\" by (auto intro: mult_left_mono)\n        also from assms Y2 have \"... \\<le> X1 * Y2\" by (auto intro: mult_right_mono_neg)\n        finally have \"x * y \\<le> X1 * Y2\".\n        with 1 show ?thesis by auto\n      next\n        case Y2: False\n        from x0 assms have \"x * y \\<le> x * Y2\" by (auto intro: mult_left_mono)\n        also from assms Y2 have \"... \\<le> X2 * Y2\" by (auto intro: mult_right_mono)\n        finally have \"x * y \\<le> X2 * Y2\".\n        with 1 show ?thesis by auto\n      qed\n    next\n      case y0: False\n      from x0 y0 assms have \"x * y \\<le> X2 * y\" by (intro mult_right_mono, auto)\n      also from y0 x0 assms have \"... \\<le> X2 * Y2\" by (intro mult_left_mono, auto)\n      finally have 1: \"x * y \\<le> X2 * Y2\".\n      show ?thesis\n      proof(cases \"X1 \\<le> 0\")\n        case True\n        with assms have \"X1 * Y2 \\<le> X1 * y\" by (auto intro: mult_left_mono_neg)\n        also from assms y0 have \"... \\<le> x * y\" by (auto intro: mult_right_mono)\n        finally have \"X1 * Y2 \\<le> x * y\".\n        with 1 show ?thesis by auto\n      next\n        case False\n        with assms have \"X1 * Y1 \\<le> X1 * y\" by (auto intro: mult_left_mono)\n        also from assms y0 have \"... \\<le> x * y\" by (auto intro: mult_right_mono)\n        finally have \"X1 * Y1 \\<le> x * y\".\n        with 1 show ?thesis by auto\n      qed\n    qed\n  qed\n  hence min:\"min (X1 * Y1) (min (X1 * Y2) (min (X2 * Y1) (X2 * Y2))) \\<le> x * y\"\n    and max:\"x * y \\<le> max (X1 * Y1) (max (X1 * Y2) (max (X2 * Y1) (X2 * Y2)))\"\n    by (auto simp:min_le_iff_disj le_max_iff_disj)\n  show ?thesis using min max X Y by (auto simp: Let_def)\nqed\n\nsubsection \\<open>Convergence\\<close>\n\ndefinition interval_tendsto :: \"(nat \\<Rightarrow> 'a :: topological_space interval) \\<Rightarrow> 'a \\<Rightarrow> bool\"\n  (infixr \"\\<longlonglongrightarrow>\\<^sub>i\" 55) where\n  \"(X \\<longlonglongrightarrow>\\<^sub>i x) \\<equiv> ((interval.upper \\<circ> X) \\<longlonglongrightarrow> x) \\<and> ((interval.lower \\<circ> X) \\<longlonglongrightarrow> x)\"\n\nlemma interval_tendstoI[intro]:\n  assumes \"(interval.upper \\<circ> X) \\<longlonglongrightarrow> x\" and \"(interval.lower \\<circ> X) \\<longlonglongrightarrow> x\"\n  shows \"X \\<longlonglongrightarrow>\\<^sub>i x\"\n  using assms by (auto simp:interval_tendsto_def)\n\nlemma const_interval_tendsto: \"(\\<lambda>i. to_interval a) \\<longlonglongrightarrow>\\<^sub>i a\"\n  by (auto simp: o_def to_interval_def)\n\nlemma interval_tendsto_0: \"(\\<lambda>i. 0) \\<longlonglongrightarrow>\\<^sub>i 0\"\n  by (auto simp: o_def zero_interval_def)\n\nlemma plus_interval_tendsto:\n  fixes x y :: \"'a :: topological_monoid_add\"\n  assumes \"X \\<longlonglongrightarrow>\\<^sub>i x\" \"Y \\<longlonglongrightarrow>\\<^sub>i y\"\n  shows \"(\\<lambda> i. X i + Y i) \\<longlonglongrightarrow>\\<^sub>i x + y\"\nproof -\n  have *: \"X i + Y i = Interval (interval.lower (X i) + interval.lower (Y i)) (interval.upper (X i) + interval.upper (Y i))\" for i\n     by (cases \"X i\"; cases \"Y i\", auto)\n  from assms show ?thesis unfolding * interval_tendsto_def o_def by (auto intro: tendsto_intros)\nqed\n\nlemma uminus_interval_tendsto:\n  fixes x :: \"'a :: topological_group_add\"\n  assumes \"X \\<longlonglongrightarrow>\\<^sub>i x\"\n  shows \"(\\<lambda>i. - X i) \\<longlonglongrightarrow>\\<^sub>i -x\"\nproof-\n  have *: \"- X i = Interval (- interval.upper (X i)) (- interval.lower (X i))\" for i\n    by (cases \"X i\", auto)\n  from assms show ?thesis unfolding o_def * interval_tendsto_def by (auto intro: tendsto_intros)\nqed\n\nlemma minus_interval_tendsto:\n  fixes x y :: \"'a :: topological_group_add\"\n  assumes \"X \\<longlonglongrightarrow>\\<^sub>i x\" \"Y \\<longlonglongrightarrow>\\<^sub>i y\"\n  shows \"(\\<lambda> i. X i - Y i) \\<longlonglongrightarrow>\\<^sub>i x - y\"\nproof -\n  have *: \"X i - Y i = Interval (interval.lower (X i) - interval.upper (Y i)) (interval.upper (X i) - interval.lower (Y i))\" for i\n    by (cases \"X i\"; cases \"Y i\", auto)\n  from assms show ?thesis unfolding o_def * interval_tendsto_def by (auto intro: tendsto_intros)\nqed\n\nlemma times_interval_tendsto:\n  fixes x y :: \"'a :: {linorder_topology, real_normed_algebra}\"\n  assumes \"X \\<longlonglongrightarrow>\\<^sub>i x\" \"Y \\<longlonglongrightarrow>\\<^sub>i y\"\n  shows \"(\\<lambda> i. X i * Y i) \\<longlonglongrightarrow>\\<^sub>i x * y\"\nproof -\n  have *: \"(interval.lower (X i * Y i)) = (\n    let lx = (interval.lower (X i)); ux = (interval.upper (X i));\n        ly = (interval.lower (Y i)); uy = (interval.upper (Y i)); \n        x1 = lx * ly; x2 = lx * uy; x3 = ux * ly; x4 = ux * uy in \n      (min x1 (min x2 (min x3 x4))))\" \"(interval.upper (X i * Y i)) = (\n    let lx = (interval.lower (X i)); ux = (interval.upper (X i));\n        ly = (interval.lower (Y i)); uy = (interval.upper (Y i)); \n      x1 = lx * ly; x2 = lx * uy; x3 = ux * ly; x4 = ux * uy in \n      (max x1 (max x2 (max x3 x4))))\" for i\n    by (cases \"X i\"; cases \"Y i\", auto simp: Let_def)+\n  have \"(\\<lambda>i. (interval.lower (X i * Y i))) \\<longlonglongrightarrow> min (x * y) (min (x * y) (min (x * y) (x *y)))\" \n    using assms unfolding interval_tendsto_def * Let_def o_def\n    by (intro tendsto_min tendsto_intros, auto)\n  moreover \n  have \"(\\<lambda>i. (interval.upper (X i * Y i))) \\<longlonglongrightarrow> max (x * y) (max (x * y) (max (x * y) (x *y)))\" \n    using assms unfolding interval_tendsto_def * Let_def o_def\n    by (intro tendsto_max tendsto_intros, auto)\n  ultimately show ?thesis unfolding interval_tendsto_def o_def by auto\nqed\n\nlemma interval_tendsto_neq:\n  fixes a b :: \"real\"\n  assumes \"(\\<lambda> i. f i) \\<longlonglongrightarrow>\\<^sub>i a\" and \"a \\<noteq> b\" \n  shows \"\\<exists> n. \\<not> b \\<in>\\<^sub>i f n\" \nproof -\n  let ?d = \"norm (b - a) / 2\" \n  from assms have d: \"?d > 0\" by auto\n  from assms(1)[unfolded interval_tendsto_def] \n  have cvg: \"(interval.lower o f) \\<longlonglongrightarrow> a\" \"(interval.upper o f) \\<longlonglongrightarrow> a\" by auto\n  from LIMSEQ_D[OF cvg(1) d] obtain n1 where \n    n1: \"\\<And> n. n \\<ge> n1 \\<Longrightarrow> norm ((interval.lower \\<circ> f) n - a) < ?d \" by auto\n  from LIMSEQ_D[OF cvg(2) d] obtain n2 where\n    n2: \"\\<And> n. n \\<ge> n2 \\<Longrightarrow> norm ((interval.upper \\<circ> f) n - a) < ?d \" by auto\n  define n where \"n = max n1 n2\"  \n  from n1[of n] n2[of n] have bnd: \n    \"norm ((interval.lower \\<circ> f) n - a) < ?d\" \n    \"norm ((interval.upper \\<circ> f) n - a) < ?d\" \n    unfolding n_def by auto\n  show ?thesis by (rule exI[of _ n], insert bnd, cases \"f n\", auto,argo)\nqed\n\nsubsection \\<open>Complex Intervals\\<close>\n\ndatatype complex_interval = Complex_Interval (Re_interval: \"real interval\") (Im_interval: \"real interval\")\n\ndefinition in_complex_interval :: \"complex \\<Rightarrow> complex_interval \\<Rightarrow> bool\" (\"(_/ \\<in>\\<^sub>c _)\" [51, 51] 50) where\n  \"y \\<in>\\<^sub>c x \\<equiv> (case x of Complex_Interval r i \\<Rightarrow> Re y \\<in>\\<^sub>i r \\<and> Im y \\<in>\\<^sub>i i)\" \n      \ninstantiation complex_interval :: comm_monoid_add begin\n\n  definition \"0 \\<equiv> Complex_Interval 0 0\"\n\n  fun plus_complex_interval :: \"complex_interval \\<Rightarrow> complex_interval \\<Rightarrow> complex_interval\" where\n    \"Complex_Interval rx ix + Complex_Interval ry iy = Complex_Interval (rx + ry) (ix + iy)\" \n\n  instance\n  proof\n    fix a b c :: complex_interval\n    show \"a + b + c = a + (b + c)\" by (cases a, cases b, cases c, simp add: ac_simps)\n    show \"a + b = b + a\" by (cases a, cases b, simp add: ac_simps)\n    show \"0 + a = a\" by (cases a, simp add: ac_simps zero_complex_interval_def)\n  qed\nend\n\nlemma plus_complex_interval: \"x \\<in>\\<^sub>c X \\<Longrightarrow> y \\<in>\\<^sub>c Y \\<Longrightarrow> x + y \\<in>\\<^sub>c X + Y\"\n  unfolding in_complex_interval_def using plus_in_interval by (cases X, cases Y, auto)\n\ndefinition of_int_complex_interval :: \"int \\<Rightarrow> complex_interval\" where\n  \"of_int_complex_interval x = Complex_Interval (of_int_interval x) 0\" \n\nlemma of_int_complex_interval_0[simp]: \"of_int_complex_interval 0 = 0\"\n  by (simp add: of_int_complex_interval_def zero_complex_interval_def to_interval_def zero_interval_def)\n\nlemma of_int_complex_interval: \"of_int i \\<in>\\<^sub>c of_int_complex_interval i\" \n  unfolding in_complex_interval_def of_int_complex_interval_def\n  by (auto simp: zero_complex_interval_def zero_interval_def)\n\ninstantiation complex_interval :: mult_zero begin\n\n  fun times_complex_interval where\n    \"Complex_Interval rx ix * Complex_Interval ry iy =\n     Complex_Interval (rx * ry - ix * iy) (rx * iy + ix * ry)\"\n\n  instance\n  proof\n    fix a :: complex_interval\n    show \"0 * a = 0\" \"a * 0 = 0\" by (atomize(full), cases a, auto simp: zero_complex_interval_def)\n  qed\nend\n\ninstantiation complex_interval :: minus begin\n\n  fun minus_complex_interval where\n    \"Complex_Interval R I - Complex_Interval R' I' = Complex_Interval (R-R') (I-I')\"\n\n  instance..\n\nend\n\nlemma times_complex_interval: \"x \\<in>\\<^sub>c X \\<Longrightarrow> y \\<in>\\<^sub>c Y \\<Longrightarrow> x * y \\<in>\\<^sub>c X * Y\"\n  unfolding in_complex_interval_def\n  by (cases X, cases Y, auto intro: times_in_interval minus_in_interval plus_in_interval)\n\ndefinition ipoly_complex_interval :: \"int poly \\<Rightarrow> complex_interval \\<Rightarrow> complex_interval\" where\n  \"ipoly_complex_interval p x = fold_coeffs (\\<lambda>a b. of_int_complex_interval a + x * b) p 0\" \n\nlemma ipoly_complex_interval_0[simp]:\n  \"ipoly_complex_interval 0 x = 0\"\n  by (auto simp: ipoly_complex_interval_def)\n\nlemma ipoly_complex_interval_pCons[simp]:\n  \"ipoly_complex_interval (pCons a p) x = of_int_complex_interval a + x * (ipoly_complex_interval p x)\"\n  by (cases \"p = 0\"; cases \"a = 0\", auto simp: ipoly_complex_interval_def)\n\nlemma ipoly_complex_interval: assumes x: \"x \\<in>\\<^sub>c X\" \n  shows \"ipoly p x \\<in>\\<^sub>c ipoly_complex_interval p X\" \nproof -\n  define xs where \"xs = coeffs p\"\n  have 0: \"in_complex_interval 0 0\" (is \"in_complex_interval ?Z ?z\")\n    unfolding in_complex_interval_def zero_complex_interval_def zero_interval_def by auto\n  define Z where \"Z = ?Z\" \n  define z where \"z = ?z\" \n  from 0 have 0: \"in_complex_interval Z z\" unfolding Z_def z_def by auto\n  note x = times_complex_interval[OF x]\n  show ?thesis \n    unfolding poly_map_poly_code ipoly_complex_interval_def fold_coeffs_def \n      xs_def[symmetric] Z_def[symmetric] z_def[symmetric] using 0\n    by (induct xs arbitrary: Z z, auto intro!: plus_complex_interval of_int_complex_interval x)\nqed\n  \ndefinition complex_interval_tendsto (infix \"\\<longlonglongrightarrow>\\<^sub>c\" 55) where\n  \"C \\<longlonglongrightarrow>\\<^sub>c c \\<equiv> ((Re_interval \\<circ> C) \\<longlonglongrightarrow>\\<^sub>i Re c) \\<and> ((Im_interval \\<circ> C) \\<longlonglongrightarrow>\\<^sub>i Im c)\"\n\nlemma complex_interval_tendstoI[intro!]:\n  \"(Re_interval \\<circ> C) \\<longlonglongrightarrow>\\<^sub>i Re c \\<Longrightarrow> (Im_interval \\<circ> C) \\<longlonglongrightarrow>\\<^sub>i Im c \\<Longrightarrow> C \\<longlonglongrightarrow>\\<^sub>c c\"\n  by (simp add: complex_interval_tendsto_def)\n\nlemma of_int_complex_interval_tendsto: \"(\\<lambda>i. of_int_complex_interval n) \\<longlonglongrightarrow>\\<^sub>c of_int n\"\n  by (auto simp: o_def of_int_complex_interval_def intro!:const_interval_tendsto interval_tendsto_0)\n\nlemma Im_interval_plus: \"Im_interval (A + B) = Im_interval A + Im_interval B\" \n  by (cases A; cases B, auto)\n\nlemma Re_interval_plus: \"Re_interval (A + B) = Re_interval A + Re_interval B\" \n  by (cases A; cases B, auto)\n\nlemma Im_interval_minus: \"Im_interval (A - B) = Im_interval A - Im_interval B\" \n  by (cases A; cases B, auto)\n\nlemma Re_interval_minus: \"Re_interval (A - B) = Re_interval A - Re_interval B\" \n  by (cases A; cases B, auto)\n    \nlemma Re_interval_times: \"Re_interval (A * B) = Re_interval A * Re_interval B - Im_interval A * Im_interval B\" \n  by (cases A; cases B, auto)\n\nlemma Im_interval_times: \"Im_interval (A * B) = Re_interval A * Im_interval B + Im_interval A * Re_interval B\" \n  by (cases A; cases B, auto)\n\nlemma plus_complex_interval_tendsto:\n  \"A \\<longlonglongrightarrow>\\<^sub>c a \\<Longrightarrow> B \\<longlonglongrightarrow>\\<^sub>c b \\<Longrightarrow> (\\<lambda>i. A i + B i) \\<longlonglongrightarrow>\\<^sub>c a + b\" \n  unfolding complex_interval_tendsto_def\n  by (auto intro!: plus_interval_tendsto simp: o_def Re_interval_plus Im_interval_plus)\n\nlemma minus_complex_interval_tendsto:\n  \"A \\<longlonglongrightarrow>\\<^sub>c a \\<Longrightarrow> B \\<longlonglongrightarrow>\\<^sub>c b \\<Longrightarrow> (\\<lambda>i. A i - B i) \\<longlonglongrightarrow>\\<^sub>c a - b\" \n  unfolding complex_interval_tendsto_def\n  by (auto intro!: minus_interval_tendsto simp: o_def Re_interval_minus Im_interval_minus)\n\nlemma times_complex_interval_tendsto:\n  \"A \\<longlonglongrightarrow>\\<^sub>c a \\<Longrightarrow> B \\<longlonglongrightarrow>\\<^sub>c b \\<Longrightarrow> (\\<lambda>i. A i * B i) \\<longlonglongrightarrow>\\<^sub>c a * b\"\n  unfolding complex_interval_tendsto_def\n  by (auto intro!: minus_interval_tendsto times_interval_tendsto plus_interval_tendsto \n    simp: o_def Re_interval_times Im_interval_times)\n\nlemma ipoly_complex_interval_tendsto:\n  assumes \"C \\<longlonglongrightarrow>\\<^sub>c c\"\n  shows \"(\\<lambda>i. ipoly_complex_interval p (C i)) \\<longlonglongrightarrow>\\<^sub>c ipoly p c\"\nproof(induct p)\n  case 0\n  show ?case by (auto simp: o_def zero_complex_interval_def zero_interval_def complex_interval_tendsto_def)\nnext\n  case (pCons a p)\n  show ?case\n    apply (unfold ipoly_complex_interval_pCons of_int_hom.map_poly_pCons_hom poly_pCons)\n    apply (intro plus_complex_interval_tendsto times_complex_interval_tendsto assms pCons of_int_complex_interval_tendsto)\n    done\nqed\n\nlemma complex_interval_tendsto_neq: assumes \"(\\<lambda> i. f i) \\<longlonglongrightarrow>\\<^sub>c a\" \n  and \"a \\<noteq> b\" \nshows \"\\<exists> n. \\<not> b \\<in>\\<^sub>c f n\" \nproof -\n  from assms(1)[unfolded complex_interval_tendsto_def o_def]\n  have cvg: \"(\\<lambda>x. Re_interval (f x)) \\<longlonglongrightarrow>\\<^sub>i Re a\" \"(\\<lambda>x. Im_interval (f x)) \\<longlonglongrightarrow>\\<^sub>i Im a\" by auto\n  from assms(2) have \"Re a \\<noteq> Re b \\<or> Im a \\<noteq> Im b\"\n    using complex.expand by blast\n  thus ?thesis\n  proof\n    assume \"Re a \\<noteq> Re b\" \n    from interval_tendsto_neq[OF cvg(1) this] show ?thesis\n      unfolding in_complex_interval_def by (metis (no_types, lifting) complex_interval.case_eq_if)\n  next\n    assume \"Im a \\<noteq> Im b\" \n    from interval_tendsto_neq[OF cvg(2) this] show ?thesis\n      unfolding in_complex_interval_def by (metis (no_types, lifting) complex_interval.case_eq_if)\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/Algebraic_Numbers/Interval_Arithmetic.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.879146761176671, "lm_q2_score": 0.8006919949619792, "lm_q1q2_score": 0.7039257740709114}}
{"text": "section {* Introduction *}\n\ntheory Mereology\nimports \"~~/src/HOL/Algebra/Order\"\nbegin\n\nsection {* Definitions *}\n\ntypedecl \"i\" -- \"the type of individuals\"\n\nlocale mereology  =\n  fixes P:: \"i \\<Rightarrow> i \\<Rightarrow> bool\" (infix \"\\<preceq>\" 50)\n\nbegin\n\ndefinition PP:: \"i \\<Rightarrow> i \\<Rightarrow> bool\" (infix \"\\<prec>\" 50) \n  where \"x \\<prec> y \\<equiv> x \\<preceq> y \\<and> x \\<noteq> y\"\n\nlemma PP_irreflexive: \"\\<not> x \\<prec> x\"\n  by (simp add: PP_def)\n\nlemma PP_asymmetric: \"x \\<prec> y \\<longrightarrow> \\<not> y \\<prec> x\" oops\n\ndefinition overlap:: \"i \\<Rightarrow> i \\<Rightarrow> bool\" (\"O\")\n  where \"O x y \\<equiv> \\<exists> z. z \\<preceq> x \\<and> z \\<preceq> y\"\n\nlemma overlap_symmetric: \"O x y \\<longrightarrow> O y x\"\n  using overlap_def by blast\n\ndefinition disjoint:: \"i \\<Rightarrow> i \\<Rightarrow> bool\" (\"D\")\n  where \"D x y \\<equiv> \\<not> O x y\"\n\nlemma disjoint_symmetric: \"D x y \\<longrightarrow> D y x\"\n  using disjoint_def overlap_def by auto\n\ndefinition underlap:: \"i \\<Rightarrow> i \\<Rightarrow> bool\" (\"U\")\n  where \"U x y \\<equiv> \\<exists> z. x \\<preceq> z \\<and> y \\<preceq> z\"\n\nlemma underlap_symmetric: \"U x y \\<longrightarrow> U y x\"\n  using underlap_def by auto\n\ndefinition sum:: \"i \\<Rightarrow> i \\<Rightarrow> i\" (infix \"\\<oplus>\" 52)\n  where \"x \\<oplus> y \\<equiv> THE z. \\<forall> w. O w z \\<longleftrightarrow> O w x \\<or> O w y\"\n\nlemma sum_commutative: \"x \\<oplus> y = y \\<oplus> x\"\nproof -\n  have \"(THE z. \\<forall> w. O w z \\<longleftrightarrow> O w x \\<or> O w y) = (THE z. \\<forall> w. O w z \\<longleftrightarrow> O w y \\<or> O w x)\"\n    by metis\n  thus ?thesis\n    using sum_def by simp\nqed\n\ndefinition product:: \"i \\<Rightarrow> i \\<Rightarrow> i\" (infix \"\\<otimes>\" 53)\n  where \"x \\<otimes> y \\<equiv> THE z. \\<forall> w. w \\<preceq> z \\<longleftrightarrow> w \\<preceq> x \\<and> w \\<preceq> y\" -- \"product or intersection\"\n\nlemma product_commutative: \"x \\<otimes> y = y \\<otimes> x\"\nproof -\n  have  \"(THE z. \\<forall> w. w \\<preceq> z \\<longleftrightarrow> w \\<preceq>  x \\<and> w \\<preceq> y) = (THE z. \\<forall> w. w \\<preceq>  z \\<longleftrightarrow> w \\<preceq>  y \\<and> w \\<preceq> x)\"\n    by metis\n  thus ?thesis\n    using product_def by simp\nqed\n\ndefinition universe:: \"i\" (\"u\")\n  where \"u \\<equiv> THE z. \\<forall> w. w \\<preceq> z\"\n\ndefinition difference:: \"i \\<Rightarrow> i \\<Rightarrow> i\" (infix \"\\<ominus>\" 51)\n  where \"x \\<ominus> y \\<equiv> THE z. \\<forall> w. w \\<preceq> z \\<longleftrightarrow> w \\<preceq> x \\<and> D w y\"\n\ndefinition complement:: \"i \\<Rightarrow> i\" (\"\\<midarrow>\")\n  where \"\\<midarrow> x \\<equiv> THE z. \\<forall> w. w \\<preceq> z \\<longleftrightarrow> D w x\"\n\ndefinition general_sum:: \"(i \\<Rightarrow> bool) \\<Rightarrow> i\" (\"\\<sigma>\")\n  where \"\\<sigma> F \\<equiv> THE x. \\<forall> y. O y x \\<longleftrightarrow> (\\<exists> z. F z \\<and> O z y)\"\n\nabbreviation general_sum_infix:: \"(i \\<Rightarrow> bool) \\<Rightarrow> i\" (binder \"\\<sigma>\" [8] 9)\n  where \"\\<sigma> x. F x \\<equiv> \\<sigma> F\" --  \"general sum or fusion of the Fs\"\n\nlemma sum_of_its_PPs: \"\\<exists> y. y \\<prec> x \\<longrightarrow> x = (\\<sigma> z. z \\<prec> x)\"\n  using PP_irreflexive by blast\n\ndefinition general_product:: \"(i \\<Rightarrow> bool) \\<Rightarrow> i\" (\"\\<pi>\")\n  where \"\\<pi> F \\<equiv> \\<sigma> x. \\<forall> y. F y \\<longrightarrow> x \\<preceq> y\"\n\nabbreviation general_product_infix:: \"(i \\<Rightarrow> bool) \\<Rightarrow> i\" (binder \"\\<pi>\" [8] 9)\n  where \"\\<pi> x. F x \\<equiv> \\<pi> F\"\n\nend\n\nsection {* Ground Mereology *}\n\nlocale ground_mereology = mereology +\n assumes P_reflexivity: \"x \\<preceq> x\"\n assumes P_antisymmetry: \"x \\<preceq> y \\<longrightarrow> y \\<preceq> x \\<longrightarrow> x = y\"\n assumes P_transitivity: \"x \\<preceq> y \\<longrightarrow> y \\<preceq> z \\<longrightarrow> x \\<preceq> z\"\n\nbegin\n\ninterpretation partial_order: partial_order \"(|carrier = set i, eq = op =, le = op \\<preceq>|)\"\n  using P_reflexivity P_antisymmetry P_transitivity by unfold_locales auto\n\nlemma \"x = y \\<longleftrightarrow> x \\<preceq> y \\<and> y \\<preceq> x\"\n  using P_antisymmetry P_reflexivity by auto\n\nlemma \"x = y \\<longleftrightarrow> (\\<forall> z. z \\<preceq> x \\<longleftrightarrow> z \\<preceq> y)\"\n  using P_antisymmetry P_reflexivity by blast\n\nlemma \"x = y \\<longleftrightarrow> (\\<forall> z. x \\<preceq> z \\<longleftrightarrow> y \\<preceq> z)\"\n  using P_antisymmetry P_reflexivity by blast\n\nlemma PP_asymmetry: \"x \\<prec> y \\<longrightarrow> \\<not> y \\<prec> x\"\n  by (simp add: PP_def P_antisymmetry)\n\nlemma PP_transitivity: \"x \\<prec> y \\<longrightarrow> y \\<prec> z \\<longrightarrow> x \\<prec> z\"\n  by (metis PP_def PP_asymmetry P_transitivity)\n\nlemma \"x \\<prec> y \\<longleftrightarrow> x \\<preceq> y \\<and> \\<not> y \\<preceq> x\"\n  using PP_def P_antisymmetry by auto\n\nlemma \"x \\<preceq> y \\<and> y \\<prec> z \\<longrightarrow> x \\<prec> z\"\n  using PP_def PP_transitivity by blast\n\nlemma \"x \\<prec> y \\<and> y \\<preceq> z \\<longrightarrow> x \\<prec> z\"\n  using PP_def PP_transitivity by blast\n\nlemma overlap_reflexive: \"O x x\"\n  using overlap_def P_reflexivity by blast\n\nlemma P_implies_overlap: \"x \\<preceq> y \\<longrightarrow> O x y\"\n  using overlap_def P_reflexivity by auto\n\nlemma \"x \\<preceq> y \\<and> O x z \\<longrightarrow> O y z\"\n  using overlap_def P_transitivity by blast\n\nlemma \"(\\<forall> z. z \\<preceq> x \\<longrightarrow> O z y) \\<longleftrightarrow> (\\<forall> z. O z x \\<longrightarrow> O z y)\"\n  by (meson overlap_def P_transitivity P_implies_overlap)\n\nlemma disjoint_irreflexive: \"\\<not> D x x\"\n  by (simp add: disjoint_def overlap_reflexive)\n\nlemma \"x \\<preceq> y \\<and> D y z \\<longrightarrow> D x z\"\n  by (meson disjoint_def overlap_def P_transitivity)\n\nlemma \"U x x\"\n  using underlap_def P_reflexivity by blast\n\nlemma  P_implies_underlap: \"x \\<preceq> y \\<longrightarrow> U x y\"\n  using underlap_def P_reflexivity by auto\n\nlemma \"x \\<preceq> y \\<and> U y z \\<longrightarrow> U x z\"\n  using underlap_def P_transitivity by blast\n\nlemma \"(\\<forall> z. x \\<preceq> z \\<longrightarrow> U z y) \\<longleftrightarrow> (\\<forall> z. U z x \\<longrightarrow> U z y)\"\n  by (metis underlap_def P_transitivity P_implies_underlap)\n\nlemma product_idempotence: \"x \\<otimes> x = x\"\nproof -\n  have \"x \\<otimes> x = (THE z. \\<forall> w. w \\<preceq> z \\<longleftrightarrow> w \\<preceq> x \\<and> w \\<preceq> x)\"\n    using product_def by simp\n  also have  \"(THE z. \\<forall> w. w \\<preceq> z \\<longleftrightarrow> w \\<preceq> x \\<and> w \\<preceq> x) = x\"\n  proof (rule the_equality)\n    show \"\\<forall> w. w \\<preceq> x \\<longleftrightarrow> (w \\<preceq> x \\<and> w \\<preceq> x)\" by simp\n    show \"\\<And> z. \\<forall>w. w \\<preceq> z \\<longleftrightarrow> (w \\<preceq> x \\<and> w \\<preceq> x) \\<Longrightarrow> z = x\"\n      using P_antisymmetry P_reflexivity by blast\n  qed\n  finally show ?thesis\n    by simp\nqed\n\nlemma product_intro: \"(\\<forall> w. w \\<preceq> z \\<longleftrightarrow> (w \\<preceq> x \\<and> w \\<preceq> y)) \\<longrightarrow> x \\<otimes> y = z\"\nproof\n  assume antecedent: \"\\<forall> w. w \\<preceq> z \\<longleftrightarrow> (w \\<preceq> x \\<and> w \\<preceq> y)\"\n  hence \"(THE v. \\<forall> w. w \\<preceq> v \\<longleftrightarrow> w \\<preceq> x \\<and> w \\<preceq> y) = z\"\n  proof (rule the_equality)\n    show \"\\<And> v. \\<forall> w. w \\<preceq> v \\<longleftrightarrow> (w \\<preceq> x \\<and> w \\<preceq> y) \\<Longrightarrow> v = z \"\n      by (meson antecedent P_antisymmetry P_reflexivity)\n  qed\n  thus \"x \\<otimes> y = z\"\n    using product_def by auto\nqed\n\nlemma difference_intro: \"(\\<forall> w. w \\<preceq> z \\<longleftrightarrow> (w \\<preceq> x \\<and> D w y)) \\<longrightarrow> x \\<ominus> y = z\"\nproof\n  assume antecedent: \"\\<forall> w. w \\<preceq> z \\<longleftrightarrow> (w \\<preceq> x \\<and> D w y)\"\n  hence \"(THE v. \\<forall> w. w \\<preceq> v \\<longleftrightarrow> (w \\<preceq> x \\<and> D w y)) = z\"\n  proof (rule the_equality)\n    show \"\\<And>v. \\<forall>w. (w \\<preceq> v) = (w \\<preceq> x \\<and> D w y) \\<Longrightarrow> v = z\"\n      by (meson antecedent P_antisymmetry P_reflexivity)\n  qed\n  thus \"x \\<ominus> y = z\"\n    by (simp add: difference_def)\nqed\n\nlemma disjoint_difference_absorption: \"D x y \\<longrightarrow> x \\<ominus> y = x\"\nproof\n  assume \"D x y\"\n  hence \"\\<forall> w. w \\<preceq> x \\<longleftrightarrow> (w \\<preceq> x \\<and> D w y)\"\n    by (meson disjoint_def overlap_def P_transitivity)\n  with difference_intro show \"x \\<ominus> y = x\"..\nqed\n\nlemma complement_intro: \"(\\<forall> w. w \\<preceq> y \\<longleftrightarrow> D w x) \\<longrightarrow> (\\<midarrow> x) = y\"\nproof\n  assume antecedent: \"\\<forall> w. w \\<preceq> y \\<longleftrightarrow> D w x\"\n  hence \"(THE z. \\<forall> w. w \\<preceq> z \\<longleftrightarrow> D w x) = y\"\n  proof (rule the_equality)\n    show \"\\<And>z. \\<forall>w. (w \\<preceq> z) = D w x \\<Longrightarrow> z = y\"\n      using antecedent P_antisymmetry P_reflexivity by blast\n  qed\n  thus \"(\\<midarrow> x) = y\"\n    using complement_def by auto\nqed\n\nend\n\nsection {* Minimal Mereology *}\n\nlocale minimal_mereology = ground_mereology +\n  assumes weak_supplementation: \"x \\<prec> y \\<longrightarrow> (\\<exists> z. z \\<preceq> y \\<and> D z x)\"\n\nbegin\n\nlemma proper_weak_supplementation: \"(\\<forall> x. \\<forall> y. x \\<prec> y \\<longrightarrow> (\\<exists> z. z \\<prec> y \\<and> D z x))\"\n  by (metis disjoint_def disjoint_symmetric P_implies_overlap\nPP_def weak_supplementation)\n\nlemma company: \"x \\<prec> y \\<longrightarrow> (\\<exists> z. z \\<noteq> x \\<and> z \\<prec> y)\"\n  using disjoint_irreflexive proper_weak_supplementation by force\n\nlemma strong_company: \"x \\<prec> y \\<longrightarrow> (\\<exists> z. z \\<prec> y \\<and> \\<not> z \\<preceq> x)\"\n  by (meson disjoint_def P_implies_overlap proper_weak_supplementation)\n\nend\n\nsection {* Extensional Mereology *}\n\nlocale extensional_mereology = ground_mereology +\n  assumes strong_supplementation: \"\\<not> x \\<preceq> y \\<longrightarrow> (\\<exists> z. z \\<preceq> x \\<and> D z y)\"\n\nbegin\n\nlemma PPs_principle:  \"(\\<exists> z. z \\<prec> x) \\<longrightarrow> (\\<forall> z. z \\<prec> x \\<longrightarrow> z \\<preceq> y) \\<longrightarrow> x \\<preceq> y\"\n  by (metis disjoint_def overlap_def PP_def P_reflexivity strong_supplementation)\n\nlemma extensionality: \"(\\<exists> z. z \\<prec> x \\<or> z \\<prec> y) \\<longrightarrow> (\\<forall> z. z \\<prec> x \\<longleftrightarrow> z \\<prec> y) \\<longrightarrow> x = y\"\n  by (meson PP_def P_antisymmetry PPs_principle)\n\nlemma weak_supplementation: \"x \\<prec> y \\<longrightarrow> (\\<exists> z. z \\<preceq> y \\<and> D z x)\"\n  using PP_def P_antisymmetry strong_supplementation by blast\n\nlemma Ps_of_Ps_overlap: \"x \\<preceq> y \\<longleftrightarrow> (\\<forall> z. z \\<preceq> x \\<longrightarrow> O z y)\"\n  using disjoint_def P_transitivity P_implies_overlap strong_supplementation by blast\n\nlemma P_overlappers_overlap: \"x \\<preceq> y \\<longleftrightarrow> (\\<forall> z. O z x \\<longrightarrow> O z y)\"\n  by (meson overlap_def P_transitivity Ps_of_Ps_overlap)\nlemma identity_overlap_eq: \"x = y \\<longleftrightarrow> (\\<forall> z. O x z \\<longleftrightarrow> O y z)\"\n  by (meson disjoint_def overlap_symmetric P_antisymmetry P_implies_overlap strong_supplementation)\n\nlemma \"x \\<preceq> y \\<longleftrightarrow> (\\<forall> z. D z y \\<longrightarrow> D z x)\"\n  by (metis disjoint_def P_transitivity overlap_def strong_supplementation)\n\nlemma \"x \\<preceq> y \\<longleftrightarrow> (\\<forall> z. D z y \\<longrightarrow> \\<not> z \\<preceq> x)\"\n  by (meson disjoint_def P_transitivity P_implies_overlap strong_supplementation)\n\nlemma disjoin_equivalence: \"x = y \\<longleftrightarrow> (\\<forall> z. D z x \\<longleftrightarrow> D z y)\"\n  by (metis disjoint_def PP_def P_implies_overlap strong_supplementation weak_supplementation)\n\nlemma sum_idempotence: \"x \\<oplus> x = x\"\nproof -\n  have \"x \\<oplus> x = (THE z. \\<forall> w. O w z \\<longleftrightarrow> O w x \\<or> O w x)\"\n    using sum_def by simp\n  also have \"\\<dots> = x\"\n  proof (rule the_equality)\n    show \"\\<forall> w. O w x \\<longleftrightarrow> (O w x \\<or> O w x)\" by simp\n    show \"\\<And>z. \\<forall> w. O w z \\<longleftrightarrow> (O w x \\<or> O w x) \\<Longrightarrow> z = x\"\n      by (meson disjoint_def disjoin_equivalence)\n  qed\n  finally show \"x \\<oplus> x = x\" by simp\nqed\n\nlemma sum_intro:\n   \"(\\<forall> w. O w x \\<longleftrightarrow> (O w y \\<or> O w z)) \\<longrightarrow> y \\<oplus> z = x\"\nproof\n  assume antecedent: \"\\<forall> w. O w x \\<longleftrightarrow> (O w y \\<or> O w z)\"\n  hence \"(THE x. \\<forall> w. O w x \\<longleftrightarrow> (O w y \\<or> O w z)) = x\"\n  proof (rule the_equality)\n    show \"\\<And> a. \\<forall>w. O w a \\<longleftrightarrow> (O w y \\<or> O w z) \\<Longrightarrow> a = x\"\n      by (meson antecedent identity_overlap_eq overlap_symmetric)\n  qed\n  thus \"y \\<oplus> z = x\"\n    using sum_def by blast\nqed\n\nlemma universe_intro: \"(\\<forall> y. y \\<preceq> x) \\<longrightarrow> x = u\"\n  by (simp add: P_antisymmetry the_equality universe_def)\n\nlemma general_sum_absorpotion: \"(\\<sigma> z. z \\<preceq> x) = x\"\nproof -\n  have \"(THE v. \\<forall> y. O y v \\<longleftrightarrow> (\\<exists> z. z \\<preceq> x \\<and> O z y)) = x\"\n  proof (rule the_equality)\n    show \"\\<forall> y. O y x \\<longleftrightarrow> (\\<exists>z. z \\<preceq> x \\<and> O z y)\"\n      using overlap_symmetric P_overlappers_overlap by blast\n    thus \"\\<And> v. \\<forall> y. O y v \\<longleftrightarrow> (\\<exists> z. z \\<preceq> x \\<and> O z y) \\<Longrightarrow> v = x\"\n      by (metis sum_intro)\n  qed\n  thus \"(\\<sigma> z. z \\<preceq> x) = x\"\n    by (simp add: general_sum_def)\nqed\n\nlemma general_sum_intro: \"(\\<forall> y. O y z \\<longleftrightarrow> (\\<exists> x. F x \\<and> O x y)) \\<longrightarrow> (\\<sigma> x. F x) = z\"\nproof\n  assume antecedent: \"(\\<forall> y. O y z \\<longleftrightarrow> (\\<exists> x. F x \\<and> O x y))\"\n  hence \"(THE v. \\<forall> y. O y v \\<longleftrightarrow> (\\<exists> x. F x \\<and> O x y)) = z\"\n  proof (rule the_equality)\n    show \"\\<And> v. \\<forall> y. O y v \\<longleftrightarrow> (\\<exists>x. F x \\<and> O x y) \\<Longrightarrow> v = z\"\n      by (metis antecedent sum_intro)\n  qed\n  thus \"(\\<sigma> v. F v) = z\"\n    using general_sum_def by blast\nqed\n\nlemma general_sum_idempotence: \"(\\<sigma> z. z = x) = x\"\n  by (metis (full_types) general_sum_intro overlap_symmetric)\n\nlemma general_product_idempotence: \"x = (\\<pi> z. z = x)\"\nproof -\n  have \"(\\<pi> z. z = x) = (\\<sigma> z. \\<forall> y. x = y \\<longrightarrow> z \\<preceq> y)\"\n    by (simp add: general_product_def)\n  also have \"... = (THE z. \\<forall> y. O y z \\<longleftrightarrow> (\\<exists> v. (\\<forall> j. x = j \\<longrightarrow> v \\<preceq> j) \\<and> O v y))\"\n    using general_sum_def by simp\n  also have \"... = x\"\n  proof (rule the_equality)\n    show \"\\<forall>y. O y x = (\\<exists>v. (\\<forall> j. x = j \\<longrightarrow> v \\<preceq> j) \\<and> O v y)\"\n      using overlap_symmetric P_overlappers_overlap by blast\n    thus \"\\<And>z. \\<forall> y. O y z = (\\<exists>v. (\\<forall> j. x = j \\<longrightarrow> v \\<preceq> j) \\<and> O v y) \\<Longrightarrow> z = x\"\n      by (metis sum_intro)\n  qed\n  finally show \"x = (\\<pi> z. z = x)\" by simp\nqed\n\nlemma general_product_absorption: \"x = (\\<pi> z. x \\<preceq> z)\"\nproof -\n  have \"(\\<pi> z. x \\<preceq> z) = (\\<sigma> z. \\<forall> y. x \\<preceq> y \\<longrightarrow> z \\<preceq> y)\"\n    by (simp add: general_product_def)\n  also have \"... = (THE z. \\<forall> y. O y z \\<longleftrightarrow> (\\<exists> v. (\\<forall> j. x \\<preceq> j \\<longrightarrow> v \\<preceq> j)  \\<and> O v y))\"\n    using general_sum_def by simp\n  also have \"... = x\"\n  proof (rule the_equality)\n    show \"\\<forall>y. O y x = (\\<exists>v. (\\<forall>j. x \\<preceq> j \\<longrightarrow> v \\<preceq> j) \\<and> O v y)\"\n      by (meson overlap_def P_reflexivity P_transitivity)\n    thus \"\\<And>z. \\<forall>y. O y z = (\\<exists>v. (\\<forall>j. x \\<preceq> j \\<longrightarrow> v \\<preceq> j) \\<and> O v y) \\<Longrightarrow> z = x\"\n      by (metis P_antisymmetry P_implies_overlap Ps_of_Ps_overlap)\n  qed\n  finally show \"x = (\\<pi> z. x \\<preceq> z)\"\n    by simp\nqed\n\nend\n\nsublocale extensional_mereology \\<subseteq> minimal_mereology\n  by (simp add: ground_mereology_axioms minimal_mereology_axioms.intro minimal_mereology_def weak_supplementation)\n\nsubsection {* Closure Mereology *}\n\nlocale closure_mereology = ground_mereology +\n  assumes sum_closure: \"U x y \\<longrightarrow> (\\<exists> z. \\<forall> w. O w z \\<longleftrightarrow> (O w x \\<or> O w y))\"\n-- \"sum closure\"\n  assumes product_closure: \"O x y \\<longrightarrow> (\\<exists> z. \\<forall> w. w \\<preceq> z \\<longleftrightarrow> (w \\<preceq> x \\<and> w \\<preceq> y))\"\n-- \"product closure\"\n\nbegin\n\nlemma product_character: \"O x y \\<longrightarrow> (\\<forall> w. w \\<preceq> (x \\<otimes> y) \\<longleftrightarrow> (w \\<preceq> x \\<and> w \\<preceq> y))\"\nproof\n  assume \"O x y\"\n  with product_closure have \"\\<exists> z. \\<forall> w. w \\<preceq> z \\<longleftrightarrow> (w \\<preceq> x \\<and> w \\<preceq> y)\"..\n  then obtain z where z: \"\\<forall> w. w \\<preceq> z \\<longleftrightarrow> (w \\<preceq> x \\<and> w \\<preceq> y)\"..\n  with product_intro have \"x \\<otimes> y = z\"..\n  thus \"(\\<forall> w. w \\<preceq> (x \\<otimes> y) \\<longleftrightarrow> (w \\<preceq> x \\<and> w \\<preceq> y))\"\n    by (simp add: z)\nqed\n\nlemma P_of_first_factor: \"O x y \\<longrightarrow> x \\<otimes> y \\<preceq> x\"\n  using P_reflexivity product_character by blast\n\nlemma P_of_second_factor: \"O x y \\<longrightarrow> x \\<otimes> y \\<preceq> y\"\n  using P_reflexivity product_character by blast\n\nlemma \"O x y \\<and> z \\<preceq> x \\<otimes> y \\<longrightarrow> z \\<preceq> x\"\n  using product_character by blast\n\nlemma \"O x y \\<and> z \\<preceq> x \\<otimes> y \\<longrightarrow> z \\<preceq> y\"\n  using product_character by blast\n\nlemma \"x \\<preceq> y \\<longrightarrow> x \\<otimes> y = x\"\n  using P_antisymmetry P_reflexivity P_implies_overlap product_character by blast\n\nlemma  \"O x y \\<and> x = x \\<otimes> y \\<longrightarrow> x \\<preceq> y\"\n  using P_of_second_factor by force\n\nlemma product_overlap_implies_overlap: \"O x y \\<and> O w (x \\<otimes> y) \\<longrightarrow> O w x\"\n  using overlap_def product_character by blast\n\nlemma PP_of_first_factor: \"x \\<noteq> y \\<and> O x y \\<longrightarrow> x \\<otimes> y \\<prec> x \\<or> x \\<otimes> y \\<prec> y\"\n  by (simp add: P_of_first_factor P_of_second_factor PP_def)\n\nlemma product_association: \"(\\<exists> w. w \\<preceq> x \\<and> w \\<preceq> y \\<and> w \\<preceq> z) \\<longrightarrow> x \\<otimes> (y \\<otimes> z) = (x \\<otimes> y) \\<otimes> z\"\nproof\n  assume antecedent: \"(\\<exists> w. w \\<preceq> x \\<and> w \\<preceq> y \\<and> w \\<preceq> z)\"\n  hence \"O y z\"\n    using overlap_def by auto\n  with product_character have yz: \"\\<forall> w. w \\<preceq> (y \\<otimes> z) \\<longleftrightarrow> (w \\<preceq> y \\<and> w \\<preceq> z)\"..\n  hence \"O x (y \\<otimes> z)\"\n    by (simp add: antecedent overlap_def)\n  with product_character have \"\\<forall> w. w \\<preceq> (x \\<otimes> (y \\<otimes> z)) \\<longleftrightarrow> (w \\<preceq> x \\<and> w \\<preceq> (y \\<otimes> z))\"..\n  hence xyz: \"\\<forall> w. w \\<preceq> (x \\<otimes> (y \\<otimes> z)) \\<longleftrightarrow> (w \\<preceq> x \\<and> w \\<preceq> y \\<and> w \\<preceq> z)\"\n    using yz by simp\n  from antecedent have \"O x y\"\n    using overlap_def by auto\n  with product_character have xy: \"(\\<forall> w. w \\<preceq> (x \\<otimes> y) \\<longleftrightarrow> (w \\<preceq> x \\<and> w \\<preceq> y))\"..\n  hence \"O (x \\<otimes> y) z\"\n    by (simp add: antecedent overlap_def)\n  with product_character have \"\\<forall> w. w \\<preceq> ((x \\<otimes> y) \\<otimes> z) \\<longleftrightarrow> (w \\<preceq> (x \\<otimes> y)) \\<and> w \\<preceq> z\"..\n  hence  \"\\<forall> w. w \\<preceq> ((x \\<otimes> y) \\<otimes> z) \\<longleftrightarrow> w \\<preceq> x \\<and> w \\<preceq> y \\<and> w \\<preceq> z\"\n    using xy by simp\n  thus \"x \\<otimes> (y \\<otimes> z) = (x \\<otimes> y) \\<otimes> z\"\n    using xyz P_antisymmetry P_reflexivity by blast\nqed\n\nend\n\nsection {* Closed Extensional Mereology *}\n\nlocale closed_minimal_mereology = closure_mereology + minimal_mereology\n\nbegin\n\nlemma strong_supplementation: \"\\<not> x \\<preceq> y \\<longrightarrow> (\\<exists> z. z \\<preceq> x \\<and> D z y)\"\nproof fix x y\n  assume \"\\<not> x \\<preceq> y\"\n  show \"(\\<exists> z. z \\<preceq> x \\<and> D z y)\"\n  proof cases\n    assume \"D x y\"\n    thus \"(\\<exists> z. z \\<preceq> x \\<and> D z y)\"\n      using P_reflexivity by auto\n  next\n    assume \"\\<not> D x y\"\n    hence \"O x y\"\n      using disjoint_def by simp\n    with product_character have product: \"\\<forall> w. w \\<preceq> (x \\<otimes> y) \\<longleftrightarrow> (w \\<preceq> x \\<and> w \\<preceq> y)\"..\n    hence \"x \\<otimes> y \\<prec> x\"\n      using \\<open>\\<not> x \\<preceq> y\\<close> P_reflexivity PP_def by auto\n    with weak_supplementation have \"\\<exists> z. z \\<preceq> x \\<and> D z (x \\<otimes> y)\"..\n    then obtain c where c: \"c \\<preceq> x \\<and> D c (x \\<otimes> y)\"..\n    hence \"c \\<preceq> x \\<and> D c y\"\n      by (meson disjoint_def overlap_def P_transitivity product)\n    thus \"\\<exists> z. z \\<preceq> x \\<and> D z y\"..\n  qed\nqed\n\nend\n\nlocale closed_extensional_mereology = extensional_mereology + closure_mereology\n\nsublocale closed_extensional_mereology \\<subseteq> closed_minimal_mereology\n  by (simp add: closed_minimal_mereology_def closure_mereology_axioms minimal_mereology_axioms)\n\nsublocale closed_minimal_mereology \\<subseteq> closed_extensional_mereology\n  by (simp add: closed_extensional_mereology_def closure_mereology_axioms\nextensional_mereology_axioms.intro extensional_mereology_def ground_mereology_axioms\nstrong_supplementation)\n\ncontext closed_extensional_mereology\nbegin\n\nlemma underlapping_sum_character: \"U x y \\<longrightarrow> (\\<forall> w. O w (x \\<oplus> y) \\<longleftrightarrow> (O w x \\<or> O w y))\"\nproof\n  assume \"U x y\"\n  with sum_closure have \"(\\<exists> z. \\<forall> w. O w z \\<longleftrightarrow> (O w x \\<or> O w y))\"..\n  then obtain a where a: \"\\<forall> w. O w a \\<longleftrightarrow> (O w x \\<or> O w y)\"..\n  with sum_intro have \"x \\<oplus> y = a\"..\n  thus \"\\<forall> w. O w (x \\<oplus> y) \\<longleftrightarrow> (O w x \\<or> O w y)\" using a by simp\nqed\n\nlemma conditonal_sum_associativity: \n\"(\\<exists> v. x \\<preceq> v \\<and> y \\<preceq> v \\<and> z \\<preceq> v) \\<longrightarrow>  x \\<oplus> (y \\<oplus> z) = (x \\<oplus> y) \\<oplus> z\"\nproof\n  assume antecedent: \"\\<exists> v. x \\<preceq> v \\<and> y \\<preceq> v \\<and> z \\<preceq> v\"\n  hence \"U x y\"\n    using underlap_def by auto\n  with underlapping_sum_character have xy: \"(\\<forall> w. O w (x \\<oplus> y) \\<longleftrightarrow> (O w x \\<or> O w y))\"..\n   hence \"U (x \\<oplus> y) z\"\n    using underlap_def antecedent P_overlappers_overlap by auto\n  with underlapping_sum_character have \"(\\<forall> w. O w ((x \\<oplus> y) \\<oplus> z) \\<longleftrightarrow> (O w (x \\<oplus> y) \\<or> O w z))\"..\n  hence xyz: \"\\<forall> w. O w ((x \\<oplus> y) \\<oplus> z) \\<longleftrightarrow> (O w x \\<or> O w y \\<or> O w z)\"\n    using xy by simp  \n  have \"U y z\"\n    using antecedent underlap_def by auto\n  with underlapping_sum_character have yz: \"(\\<forall> w. O w (y \\<oplus> z) \\<longleftrightarrow> (O w y \\<or> O w z))\"..\n  hence \"U x (y \\<oplus> z)\"\n    using underlap_def antecedent P_overlappers_overlap by auto\n  with underlapping_sum_character have \"(\\<forall> w. O w (x \\<oplus> (y \\<oplus> z)) \\<longleftrightarrow> (O w x \\<or> O w (y \\<oplus> z)))\"..\n  hence \"\\<forall> w. O w (x \\<oplus> (y \\<oplus> z)) \\<longleftrightarrow> (O w x \\<or> O w y \\<or> O w z)\"\n    using yz by simp\n  hence \"\\<forall> w. O w (x \\<oplus> (y \\<oplus> z)) \\<longleftrightarrow>  O w ((x \\<oplus> y) \\<oplus> z)\"\n    using xyz by simp\n  thus \"x \\<oplus> (y \\<oplus> z) = (x \\<oplus> y) \\<oplus> z\"\n    using P_overlappers_overlap P_antisymmetry by auto\nqed\n\nlemma sums_of_Ps_are_Ps: \"x \\<preceq> z \\<and> y \\<preceq> z \\<longrightarrow> x \\<oplus> y \\<preceq> z\"\nproof\n  assume \"x \\<preceq> z \\<and> y \\<preceq> z\"\n  hence \"U x y\"\n    using underlap_def by blast\n  with underlapping_sum_character have \"\\<forall> w. O w (x \\<oplus> y) \\<longleftrightarrow> (O w x \\<or> O w y)\"..\n  thus \"x \\<oplus> y \\<preceq> z\"\n    using P_overlappers_overlap \\<open>x \\<preceq> z \\<and> y \\<preceq> z\\<close> by auto\nqed\n\nlemma P_implies_absorption: \"y \\<preceq> x \\<longrightarrow> x = x \\<oplus> y\"\n  by (metis sum_intro P_overlappers_overlap)\n\nend\n\nsection {* Closed Extensional Mereology with Universe *}\n\nlocale closure_mereology_with_universe = closure_mereology +\n  assumes universe_closure: \"\\<exists> z. \\<forall> x. x \\<preceq> z\"\n\nbegin\n\nlemma universal_underlap: \"U x y\"\n  by (metis underlap_def universe_closure)\n\nlemma universal_sum_closure: \"(\\<exists> z. \\<forall> w. O w z \\<longleftrightarrow> (O w x \\<or> O w y))\"\n  by (simp add: sum_closure universal_underlap)\n\nlemma universe_intro: \"(\\<forall> x. x \\<preceq> z) \\<longrightarrow> u = z\"\nproof\n  assume \"\\<forall> x. x \\<preceq> z\"\n  hence \"(THE y. \\<forall> x. x \\<preceq> y) = z\"\n  proof (rule the_equality)\n    show \"\\<And> y. \\<forall> x. x \\<preceq> y \\<Longrightarrow> y = z\"\n      by (simp add: \\<open>\\<forall>x. x \\<preceq> z\\<close> P_antisymmetry)\n  qed\n  thus \"u = z\"\n    by (simp add: universe_def)\nqed\n\nlemma universe_character: \"\\<forall> x. x \\<preceq> u\"\n  using universe_closure universe_intro by blast\n\nlemma \"u \\<preceq> x \\<longrightarrow> u = x\"\n  by (simp add: P_antisymmetry universe_character)\n\nlemma \"\\<not> u \\<prec> x\"\n  by (simp add: P_antisymmetry PP_def universe_character)\n\nlemma multiplicative_identity: \"x \\<otimes> u = x\"\n  by (simp add: product_intro universe_character)\n\nend\n\nlocale closed_extensional_mereology_with_universe = closure_mereology_with_universe +\n  closed_extensional_mereology\n\nbegin\n\nlemma \"x \\<oplus> u = u\"\n  using P_implies_absorption sum_commutative universe_character by auto\n\nlemma sum_character: \"\\<forall> w. O w (x \\<oplus> y) \\<longleftrightarrow> (O w x \\<or> O w y)\"\n  by (simp add: underlapping_sum_character universal_underlap)\n\nlemma sum_associativity: \"x \\<oplus> (y \\<oplus> z) = (x \\<oplus> y) \\<oplus> z\"\n  using conditonal_sum_associativity universe_character by blast\n\nlemma first_summand_inclusion: \"x \\<preceq> x \\<oplus> y\"\n  by (simp add: P_overlappers_overlap sum_character)\n\nlemma second_summand_inclusion: \"y \\<preceq> x \\<oplus> y\"\n  using first_summand_inclusion sum_commutative by fastforce\n\nlemma  sum_is_P_iff_summands_are: \"x \\<oplus> y \\<preceq> z \\<longleftrightarrow> x \\<preceq> z \\<and> y \\<preceq> z\"\n  using first_summand_inclusion P_transitivity second_summand_inclusion\nsums_of_Ps_are_Ps by blast\n\nlemma  disjoint_summands_are_PPs: \"D x y \\<longrightarrow> x \\<prec> x \\<oplus> y \\<and> y \\<prec> x \\<oplus> y\"\n  by (metis disjoint_def disjoint_symmetric first_summand_inclusion P_implies_overlap\nPP_def second_summand_inclusion)\n\nlemma nonP_implies_proper_summand: \"\\<not> x \\<preceq> y \\<longrightarrow> y \\<prec> x \\<oplus> y\"\n  by (metis first_summand_inclusion PP_def second_summand_inclusion)\n\nlemma distinct_iff_proper_summand: \"x \\<noteq> y \\<longleftrightarrow> x \\<prec> x \\<oplus> y \\<or> y \\<prec> x \\<oplus> y\"\n  using first_summand_inclusion PP_def second_summand_inclusion sum_idempotence by auto\n\nlemma absorption_iff_P: \"x = x \\<oplus> y \\<longleftrightarrow> y \\<preceq> x\"\n  by (metis P_implies_absorption second_summand_inclusion)\n\nlemma  disjoint_second_implies_P_first: \"(x \\<preceq> y \\<oplus> z \\<and> D x z) \\<longrightarrow> x \\<preceq> y\"\nproof\n  assume antecedent: \"x \\<preceq> y \\<oplus> z \\<and> D x z\"\n  have \"\\<forall> w. O w (y \\<oplus> z) \\<longleftrightarrow> (O w y \\<or> O w z)\" using sum_character.\n  thus \"x \\<preceq> y\"\n    by (meson antecedent disjoint_def overlap_symmetric P_overlappers_overlap Ps_of_Ps_overlap)\nqed\n\nlemma proper_sum_monotonicity: \"x \\<prec> y \\<and> D y z \\<longrightarrow> x \\<oplus> z \\<prec> y \\<oplus> z\"\n  by (metis absorption_iff_P disjoint_second_implies_P_first PP_def sum_commutative \nsecond_summand_inclusion sum_is_P_iff_summands_are)\n\nend\n\nsection {* Closed Extensional Mereology with Differences *}\n\nlocale closure_mereology_with_differences = closure_mereology +\n  assumes difference_closure: \"(\\<exists> w. w \\<preceq> x \\<and> D w y) \\<longrightarrow> (\\<exists> z. \\<forall> w. w \\<preceq> z \\<longleftrightarrow> (w \\<preceq> x \\<and> D w y))\"\n\nbegin\n\nlemma difference_character:  \"(\\<exists> w. w \\<preceq> x \\<and> D w y) \\<longrightarrow> (\\<forall> w. w \\<preceq> (x \\<ominus> y) \\<longleftrightarrow> (w \\<preceq> x \\<and> D w y))\"\nproof\n  assume \"(\\<exists> w. w \\<preceq> x \\<and> D w y)\"\n  with difference_closure have \"(\\<exists> z. \\<forall> w. w \\<preceq> z \\<longleftrightarrow> (w \\<preceq> x \\<and> D w y))\"..\n  then obtain z where z: \"\\<forall> w. w \\<preceq> z \\<longleftrightarrow> (w \\<preceq> x \\<and> D w y)\"..\n  with difference_intro have \"(x \\<ominus> y) = z\"..\n  thus \"\\<forall> w. w \\<preceq> (x \\<ominus> y) \\<longleftrightarrow> (w \\<preceq> x \\<and> D w y)\"\n    using z by simp\nqed\n\nend\n\nlocale closed_extensional_mereology_with_differences =\nclosed_extensional_mereology + closure_mereology_with_differences\n\nbegin\n\nlemma proper_difference: \"(O x y \\<and> \\<not> x \\<preceq> y) \\<longrightarrow> (x \\<ominus> y) \\<prec> x\"\nproof\n  assume \"O x y \\<and> \\<not> x \\<preceq> y\"\n  hence \"\\<not> x \\<preceq> y\"..\n  with strong_supplementation have \"(\\<exists> w. w \\<preceq> x \\<and> D w y)\"..\n  with difference_character have \"\\<forall> w. w \\<preceq> (x \\<ominus> y) \\<longleftrightarrow> (w \\<preceq> x \\<and> D w y)\"..\n  thus \"(x \\<ominus> y) \\<prec> x\"\n    using \\<open>O x y \\<and> \\<not> x \\<preceq> y\\<close> disjoint_def P_reflexivity PP_def by auto\nqed\n\nlemma PP_implies_proper_difference: \"x \\<prec> y \\<longrightarrow> y \\<ominus> x \\<prec> y\"\n  using overlap_symmetric P_implies_overlap proper_difference PP_asymmetry\nPP_def by blast\n\nlemma no_difference_implies_disjoint: \"\\<not> y \\<preceq> x \\<and> y \\<ominus> x = y \\<longrightarrow> D x y\"\n  using disjoint_def disjoint_symmetric proper_difference PP_def by blast\n\nlemma proper_difference_absorption: \"x \\<prec> y \\<longrightarrow> x \\<oplus> (y \\<ominus> x) = y\"\nproof\n  assume \"x \\<prec> y\"\n  with weak_supplementation have \"(\\<exists> w. w \\<preceq> y \\<and> D w x)\"..\n  with difference_character have difference: \"\\<forall> w. w \\<preceq> (y \\<ominus> x) \\<longleftrightarrow> (w \\<preceq> y \\<and> D w x)\"..\n  hence \"U x (y \\<ominus> x)\"\n    by (metis \\<open>x \\<prec> y\\<close> PP_def underlap_def P_reflexivity)\n  with underlapping_sum_character have \"\\<forall> w. O w (x \\<oplus> (y \\<ominus> x)) \\<longleftrightarrow> O w x \\<or> O w (y \\<ominus> x)\"..\n  hence \"\\<forall> w. O w (x \\<oplus> (y \\<ominus> x)) \\<longleftrightarrow> O w y \\<or> (O w y \\<and> D w x)\"\n    by (metis \\<open>x \\<prec> y\\<close> difference disjoint_def P_overlappers_overlap overlap_def\noverlap_symmetric PP_def)\n  hence  \"\\<forall> w. O w (x \\<oplus> (y \\<ominus> x)) \\<longleftrightarrow> O w y\"\n    by blast\n  thus \"x \\<oplus> (y \\<ominus> x) = y\"\n    by (simp add: P_antisymmetry P_overlappers_overlap)\n qed  \n  \nlemma difference_absorbs_product: \"O x y \\<and> \\<not> x \\<preceq> y \\<longrightarrow> x \\<ominus> (x \\<otimes> y) = x \\<ominus> y\"\nproof\n  assume \"O x y \\<and> \\<not> x \\<preceq> y\"\n  hence \"\\<not> x \\<preceq> y\"..\n  with strong_supplementation have \"\\<exists> w. w \\<preceq> x \\<and> D w y\"..\n  with difference_character have right: \"\\<forall> w. w \\<preceq> (x \\<ominus> y) \\<longleftrightarrow> (w \\<preceq> x \\<and> D w y)\"..\n  have \"O x y\" using \\<open>O x y \\<and> \\<not> x \\<preceq> y\\<close>..\n  with product_character have product: \"\\<forall> w. w \\<preceq> (x \\<otimes> y) \\<longleftrightarrow> (w \\<preceq> x \\<and> w \\<preceq> y)\"..\n  hence \"\\<not> x \\<preceq> (x \\<otimes> y)\"\n    using \\<open>O x y \\<and> \\<not> x \\<preceq> y\\<close> by blast\n  with strong_supplementation have \"\\<exists> w. w \\<preceq> x \\<and> D w (x \\<otimes> y)\"..\n  with difference_character have left: \"\\<forall> w. w \\<preceq> (x \\<ominus> (x \\<otimes> y)) \\<longleftrightarrow> (w \\<preceq> x \\<and> D w (x \\<otimes> y))\".. \n  hence \"\\<forall> w. w \\<preceq> (x \\<ominus> (x \\<otimes> y)) \\<longleftrightarrow> (w \\<preceq> x \\<and> D w (x \\<otimes> y))\"\n    by (simp add: disjoint_def)\n  hence \"\\<forall> w. w \\<preceq> (x \\<ominus> (x \\<otimes> y)) \\<longleftrightarrow> w \\<preceq> (x \\<ominus> y)\"\n    using product right disjoint_def overlap_def P_transitivity by smt\n  thus \"x \\<ominus> (x \\<otimes> y) = x \\<ominus> y\"\n    using P_antisymmetry P_reflexivity by blast\nqed\n  \nlemma difference_monotonicity: \"\\<not> x \\<preceq> z \\<longrightarrow> x \\<preceq> y \\<longrightarrow> x \\<ominus> z \\<preceq> y \\<ominus> z\"\nproof\n  assume \"\\<not> x \\<preceq> z\"\n  with strong_supplementation have \"\\<exists> w. w \\<preceq> x \\<and> D w z\"..\n  with difference_character have left: \"(\\<forall> w. w \\<preceq> (x \\<ominus> z) \\<longleftrightarrow> (w \\<preceq> x \\<and> D w z))\"..\n  show \"x \\<preceq> y \\<longrightarrow> x \\<ominus> z \\<preceq> y \\<ominus> z\"\n  proof\n    assume \"x \\<preceq> y\"\n    hence \"\\<not> y \\<preceq> z\"\n      using \\<open>\\<not> x \\<preceq> z\\<close> P_transitivity by blast\n    with strong_supplementation have \"\\<exists> w. w \\<preceq> y \\<and> D w z\"..\n    with difference_character have right: \"(\\<forall> w. w \\<preceq> (y \\<ominus> z) \\<longleftrightarrow> (w \\<preceq> y \\<and> D w z))\"..\n    hence \"\\<forall> w. w \\<preceq> (x \\<ominus> z) \\<longrightarrow> w \\<preceq> (y \\<ominus> z)\"\n      using P_transitivity \\<open>x \\<preceq> y\\<close> left by blast\n    thus \"x \\<ominus> z \\<preceq> y \\<ominus> z\"\n      using P_reflexivity by auto\n  qed\nqed\n\nend\n\nsection {* Closed Extensional Mereology with Complements *}\n\nlocale closure_mereology_with_complements = closure_mereology +\n  assumes complement_closure: \"\\<not> (\\<forall> y. y \\<preceq> x) \\<longrightarrow> (\\<exists> z. \\<forall> w. w \\<preceq> z \\<longleftrightarrow> D w x)\"\n\nbegin\n\nlemma complement_character: \"\\<not> (\\<forall> y. y \\<preceq> x) \\<longrightarrow> (\\<forall> w. w \\<preceq> (\\<midarrow> x) \\<longleftrightarrow> D w x)\"\nproof\n  assume \"\\<not> (\\<forall> y. y \\<preceq> x)\"\n  with complement_closure have \"\\<exists> z. \\<forall> w. w \\<preceq> z \\<longleftrightarrow> D w x\"..\n  then obtain a where a: \"\\<forall> w. w \\<preceq> a \\<longleftrightarrow> D w x\"..\n  hence \"(THE z. \\<forall> w. w \\<preceq> z \\<longleftrightarrow> D w x) = a\"\n  proof (rule the_equality)\n    show \"\\<And>z. \\<forall>w. (w \\<preceq> z) = D w x \\<Longrightarrow> z = a\"\n      using a P_antisymmetry P_reflexivity by blast\n  qed\n  hence \"(\\<midarrow> x) = a\"\n    using complement_def by auto\n  thus \"(\\<forall> w. w \\<preceq> (\\<midarrow> x) \\<longleftrightarrow> D w x)\"\n    by (simp add: a)\nqed\n\nlemma disjoint_implies_overlaps_complement: \"D x y \\<longrightarrow> O x (\\<midarrow> y)\"\n  using complement_character disjoint_def P_implies_overlap by blast\n\nlemma difference_closure: \"(\\<exists> w. w \\<preceq> x \\<and> D w y) \\<longrightarrow> (\\<exists> z. \\<forall> w. w \\<preceq> z \\<longleftrightarrow> (w \\<preceq> x \\<and> D w y))\"\nproof\n  assume antecedent: \"(\\<exists> w. w \\<preceq> x \\<and> D w y)\"\n  hence \"\\<not> (\\<forall> z. z \\<preceq> y)\"\n    using disjoint_def P_implies_overlap by blast\n  with complement_character have comp: \"\\<forall> w. w \\<preceq> (\\<midarrow> y) \\<longleftrightarrow> D w y\"..\n  hence \"O x (\\<midarrow> y)\"\n    by (simp add: antecedent overlap_def)\n  with product_character have \"\\<forall> w. w \\<preceq> x \\<otimes> \\<midarrow> y \\<longleftrightarrow> w \\<preceq> x \\<and> w \\<preceq> \\<midarrow> y\"..\n  hence \"\\<forall> w. w \\<preceq> x \\<otimes> \\<midarrow> y \\<longleftrightarrow> w \\<preceq> x \\<and> D w y\"\n    using comp by blast\n  thus \"\\<exists> z. \\<forall> w. w \\<preceq> z \\<longleftrightarrow> (w \\<preceq> x \\<and> D w y)\"..\nqed\n\nend\n\nsublocale closure_mereology_with_complements \\<subseteq> closure_mereology_with_differences\n  by (simp add: closure_mereology_axioms closure_mereology_with_differences.intro\nclosure_mereology_with_differences_axioms.intro difference_closure)\n\nlocale closed_extensional_mereology_with_complements = closed_extensional_mereology +\n  closure_mereology_with_complements\n\nbegin\n\nlemma complement_sums_disjoints: \"x \\<noteq> u \\<longrightarrow> (\\<sigma> z. D x z) = \\<midarrow> x\"\nproof\n  assume \"x \\<noteq> u\"\n  hence \"\\<not> (\\<forall> y. y \\<preceq> x)\"\n    using universe_intro by blast\n  with complement_character have \"\\<forall> w. (w \\<preceq> \\<midarrow> x) \\<longleftrightarrow> D w x\"..\n  hence \"\\<forall> y. O y (\\<midarrow> x) \\<longleftrightarrow> (\\<exists> z. (D x z) \\<and> O z y)\"\n    by (meson disjoint_symmetric overlap_symmetric P_overlappers_overlap)\n  with general_sum_intro show \"(\\<sigma> z. D x z) = \\<midarrow> x\"..\nqed\n\nend\n\nlocale closed_extensional_mereology_with_universe_and_complements =\nclosed_extensional_mereology_with_universe + closed_extensional_mereology_with_complements \n\nbegin\n\nlemma univ_complement_character: \"x \\<noteq> u \\<longrightarrow> (\\<forall> w. w \\<preceq> (\\<midarrow> x) \\<longleftrightarrow> D w x)\"\n  using complement_character universe_intro by blast\n\nlemma unique_complement: \"(\\<exists>! z. \\<forall> w. w \\<preceq> z \\<longleftrightarrow> D w x) \\<longleftrightarrow> x \\<noteq> u\"\nproof\n  assume  \"(\\<exists>! z. \\<forall> w.  w \\<preceq> z \\<longleftrightarrow> D w x)\"\n  thus \"x \\<noteq> u\"\n    by (meson disjoint_def P_reflexivity P_implies_overlap universe_character)\nnext\n  assume \"x \\<noteq> u\"\n  show \"\\<exists>! z. \\<forall> w. w \\<preceq> z \\<longleftrightarrow> D w x\"\n  proof\n    show \"\\<forall> w. (w \\<preceq> \\<midarrow> x) \\<longleftrightarrow> D w x\"\n      using \\<open>x \\<noteq> u\\<close> univ_complement_character by simp\n    show \"\\<And>z. \\<forall>w. (w \\<preceq> z) \\<longleftrightarrow> D w x \\<Longrightarrow> z = \\<midarrow> x\"\n      using complement_intro by simp\n  qed\nqed\n\nlemma complement_disjointness: \"x \\<noteq> u \\<longrightarrow> D x (\\<midarrow> x)\"\n  using disjoint_symmetric P_reflexivity univ_complement_character by blast\n\nlemma additive_inverse: \"x \\<noteq> u \\<longrightarrow> x \\<oplus> (\\<midarrow> x) = u\"\nproof\n  assume \"x \\<noteq> u\"\n  with univ_complement_character have \"(\\<forall> w. w \\<preceq> (\\<midarrow> x) \\<longleftrightarrow> D w x)\"..\n  have \"\\<forall> w. O w (x \\<oplus> (\\<midarrow> x)) \\<longleftrightarrow> (O w x \\<or> O w (\\<midarrow> x))\" using sum_character.\n  thus \"(x \\<oplus> (\\<midarrow> x)) = u\"\n    by (metis \\<open>\\<forall>w. (w \\<preceq> \\<midarrow> x) = D w x\\<close> disjoint_def P_overlappers_overlap P_implies_overlap universe_intro)\nqed\n\nlemma in_comp_iff_disjoint: \"y \\<noteq> u \\<longrightarrow> x \\<preceq> \\<midarrow> y \\<longleftrightarrow> D x y\"\n  by (simp add: univ_complement_character)\n\nlemma double_comp_eq: \"x \\<noteq> u \\<longrightarrow> x = (\\<midarrow>(\\<midarrow> x))\"\n  by (metis additive_inverse complement_disjointness disjoint_irreflexive\ndisjoint_second_implies_P_first first_summand_inclusion P_antisymmetry\nuniv_complement_character)\n\nlemma prod_disj_imp_overlap_comp: \"O w x \\<and> O x y \\<and> O x (\\<midarrow>y) \\<longrightarrow> D w (x \\<otimes> y) \\<longrightarrow> O w (x \\<otimes> (\\<midarrow>y))\"\nproof\n  assume antecedent: \"O w x \\<and> O x y \\<and> O x (\\<midarrow> y)\"\n  hence \"O w x\"..\n  with product_character have prodwx: \"(\\<forall> v. v \\<preceq> (w \\<otimes> x) \\<longleftrightarrow> (v \\<preceq> w \\<and> v \\<preceq> x))\"..\n  have \"O x (\\<midarrow> y)\"\n    using antecedent by blast\n  with product_character have prod_comp: \"(\\<forall> w. w \\<preceq> (x \\<otimes> (\\<midarrow> y)) \\<longleftrightarrow> (w \\<preceq> x \\<and> w \\<preceq> (\\<midarrow> y)))\"..\n  from antecedent have \"O x y\" by blast\n  with product_character have prodxy: \"(\\<forall> w. w \\<preceq> (x \\<otimes> y) \\<longleftrightarrow> (w \\<preceq> x \\<and> w \\<preceq> y))\"..\n  show \"D w (x \\<otimes> y) \\<longrightarrow> O w (x \\<otimes> (\\<midarrow>y))\"\n  proof\n    assume disjoint: \"D w (x \\<otimes> y)\"\n    hence \"y \\<noteq> u\"\n      using antecedent disjoint_def multiplicative_identity by auto\n    with univ_complement_character have comp: \"\\<forall> w. w \\<preceq> (\\<midarrow> y) \\<longleftrightarrow> D w y\"..\n    hence \"w \\<otimes> x \\<preceq> x \\<otimes> (\\<midarrow> y)\" using prodwx prodxy\n      using antecedent disjoint disjoint_def overlap_def P_of_second_factor prod_comp by auto\n    hence \"w \\<otimes> x \\<preceq> w \\<and> w \\<otimes> x \\<preceq> x \\<otimes> (\\<midarrow> y)\"\n      by (simp add: antecedent P_of_first_factor)\n    thus \"O w (x \\<otimes> (\\<midarrow>y))\"\n      using overlap_def by blast\n  qed\nqed\n\nlemma T57:\n\"y \\<noteq> u \\<and> O x y \\<and> \\<not> x \\<preceq> y \\<longrightarrow> x = ((x \\<otimes> y) \\<oplus> (x \\<otimes> (\\<midarrow>y)))\"\nproof\n  assume antecedent: \"y \\<noteq> u \\<and> O x y \\<and> \\<not> x \\<preceq> y\"\n  hence \"y \\<noteq> u\"..\n  with univ_complement_character have comp: \"(\\<forall> w. w \\<preceq> (\\<midarrow> y) \\<longleftrightarrow> D w y)\"..\n  hence \"O x (\\<midarrow> y)\"\n    by (simp add: antecedent overlap_def strong_supplementation)\n  with product_character have prod_comp: \"\\<forall> w. w \\<preceq> x \\<otimes> (\\<midarrow> y) \\<longleftrightarrow> w \\<preceq> x \\<and> w \\<preceq> (\\<midarrow> y)\"..\n  from antecedent have \"O x y \\<and> \\<not> x \\<preceq> y\"..\n  hence \"O x y\"..\n  with product_character have prod: \"\\<forall> w. w \\<preceq> x \\<otimes> y \\<longleftrightarrow> w \\<preceq> x \\<and> w \\<preceq> y\"..\n  from sum_character have \"\\<forall>w. O w ((x \\<otimes> y) \\<oplus> (x \\<otimes> (\\<midarrow>y))) \\<longleftrightarrow> (O w (x \\<otimes> y) \\<or> O w (x \\<otimes> (\\<midarrow>y)))\".\n  have \"\\<forall> w. O w x \\<longleftrightarrow> O w (x \\<otimes> y) \\<or> O w (x \\<otimes> (\\<midarrow>y))\"\n  proof\n    fix w\n    show \"O w x \\<longleftrightarrow> O w (x \\<otimes> y) \\<or> O w (x \\<otimes> (\\<midarrow>y))\"\n    proof\n      assume \"O w x\"\n      with product_character have product: \"\\<forall> v. v \\<preceq> w \\<otimes> x \\<longleftrightarrow> v \\<preceq> w \\<and> v \\<preceq> x\"..\n      show \"O w (x \\<otimes> y) \\<or> O w (x \\<otimes> (\\<midarrow>y))\"\n      proof cases\n        assume \"O w (x \\<otimes> y)\"\n        thus \"O w (x \\<otimes> y) \\<or> O w (x \\<otimes> (\\<midarrow>y))\"..\n      next\n        assume \"\\<not> O w (x \\<otimes> y)\"\n        hence \"O w (x \\<otimes> (\\<midarrow> y))\"\n          by (simp add: \\<open>O w x\\<close> \\<open>O x (\\<midarrow> y)\\<close> antecedent disjoint_def prod_disj_imp_overlap_comp)\n        thus \"O w (x \\<otimes> y) \\<or> O w (x \\<otimes> (\\<midarrow>y))\"..\n      qed\n    next\n      assume \"O w (x \\<otimes> y) \\<or> O w (x \\<otimes> (\\<midarrow>y))\"\n      thus \"O w x\"\n      proof (rule disjE)\n        assume \"O w (x \\<otimes> y)\"\n        thus \"O w x\"\n          using antecedent product_overlap_implies_overlap by blast\n      next\n        assume \"O w (x \\<otimes> (\\<midarrow>y))\"\n        thus \"O w x\"\n          using \\<open>O x (\\<midarrow> y)\\<close> product_overlap_implies_overlap by blast\n      qed\n    qed\n  qed\n  thus \" x = ((x \\<otimes> y) \\<oplus> (x \\<otimes> (\\<midarrow>y)))\"\n    using sum_intro identity_overlap_eq by force\nqed\n\nlemma cancellation: \"D x y \\<longrightarrow> (x \\<oplus> y) \\<ominus> x = y\"\nproof\n  assume \"D x y\"\n  hence \"y \\<preceq> (x \\<oplus> y) \\<and> D y x\"\n    by (simp add: disjoint_symmetric second_summand_inclusion)\n  hence  \"(\\<exists> w. w \\<preceq> (x \\<oplus> y) \\<and> D w x)\"..\n  with difference_character have \"(\\<forall> w. w \\<preceq> ((x \\<oplus> y) \\<ominus> x) \\<longleftrightarrow> (w \\<preceq> (x \\<oplus> y) \\<and> D w x))\"..\n  thus \"(x \\<oplus> y) \\<ominus> x = y\"\n    by (metis \\<open>y \\<preceq> x \\<oplus> y \\<and> D y x\\<close> disjoint_second_implies_P_first sum_commutative\nP_antisymmetry P_reflexivity)\nqed\n\nend\n\nlocale closed_extensional_mereology_with_universe_and_differences =\nclosed_extensional_mereology_with_universe + closed_extensional_mereology_with_differences\n\nbegin\n\nlemma complement_closure: \"\\<not> (\\<forall> y. y \\<preceq> x) \\<longrightarrow> (\\<exists> z. \\<forall> w. w \\<preceq> z \\<longleftrightarrow> D w x)\"\nproof\n  assume \"\\<not> (\\<forall> y. y \\<preceq> x)\"\n  hence \"\\<exists> w. w \\<preceq> u \\<and> D w x\"\n    using strong_supplementation universe_character by blast\n  with difference_character have \"\\<forall> w. w \\<preceq> u \\<ominus> x \\<longleftrightarrow> w \\<preceq> u \\<and> D w x\"..\n  hence \"\\<forall> w. w \\<preceq> u \\<ominus> x \\<longleftrightarrow> D w x\"\n    by (simp add: universe_character)\n  thus \"\\<exists> z. \\<forall> w. w \\<preceq> z \\<longleftrightarrow> D w x\"..\nqed\n\nend\n\nsublocale closed_extensional_mereology_with_universe_and_differences \\<subseteq> closed_extensional_mereology_with_universe_and_complements\n  by (simp add: closed_extensional_mereology_axioms closed_extensional_mereology_with_complements.intro\nclosed_extensional_mereology_with_universe_and_complements.intro closed_extensional_mereology_with_universe_axioms\nclosure_mereology_axioms closure_mereology_with_complements.intro closure_mereology_with_complements_axioms.intro complement_closure)\n\nsublocale closed_extensional_mereology_with_universe_and_complements \\<subseteq> closed_extensional_mereology_with_universe_and_differences\n  by (simp add: closed_extensional_mereology_axioms closed_extensional_mereology_with_differences.intro\nclosed_extensional_mereology_with_universe_and_differences.intro closed_extensional_mereology_with_universe_axioms\nclosure_mereology_with_differences_axioms)\n\nsection {* General Mereology *}\n\ntext {* General Mereology is obtained from Ground Mereology by adding the axiom of fusion or\nunrestricted composition @{cite \"casati_Ps_1999\"} p. 46:  *}\n\nlocale general_mereology = ground_mereology +\n  assumes fusion: \"(\\<exists> x. F x) \\<longrightarrow> (\\<exists> z. \\<forall> y. O y z \\<longleftrightarrow> (\\<exists> x. F x \\<and> O x y))\"\n-- \"fusion or unrestricted composition\"\n\nbegin\n \nlemma sum_closure: \"(\\<exists>z. \\<forall>w. O w z \\<longleftrightarrow> (O w a \\<or> O w b))\"\nproof -\n  have \"(\\<exists> x. (x = a \\<or> x = b)) \\<longrightarrow> (\\<exists> z. \\<forall> y. O y z \\<longleftrightarrow> (\\<exists> x. (x = a \\<or> x = b) \\<and> O x y))\"\n    using fusion solve_direct.\n  hence \"(\\<exists> z. \\<forall> y. O y z \\<longleftrightarrow> (\\<exists> x. (x = a \\<or> x = b) \\<and> O x y))\"\n    by blast\n  thus \"(\\<exists>z. \\<forall>w. O w z \\<longleftrightarrow> (O w a \\<or> O w b))\"\n    by (metis overlap_symmetric) \nqed\n\nlemma universal_overlap: \"\\<exists> z. \\<forall> x. O x z\"\nproof -\n  have \"(\\<exists> x. x = x) \\<longrightarrow> (\\<exists> z. \\<forall> y. O y z \\<longleftrightarrow> (\\<exists> x. x = x \\<and> O x y))\"\n    using fusion by fast\n  hence  \"\\<exists> z. \\<forall> y. O y z \\<longleftrightarrow> (\\<exists> x. x = x \\<and> O x y)\"\n    by simp\n  hence  \"\\<exists> z. \\<forall> y. O y z \\<longleftrightarrow> (\\<exists> x. O x y)\"\n    by simp\n  thus ?thesis\n    by (metis overlap_def P_reflexivity)\nqed\n\nend\n\nlocale general_minimal_mereology = minimal_mereology + general_mereology -- \"General Minimal Mereology\"\n\nsubsection {* Classical Extensional Mereology *}\n\nlocale classical_extensional_mereology = extensional_mereology + general_mereology\nbegin\n\ntext {* Following proof from @{cite \"pontow_note_2004\"} pp. 202-3  *}\n\nlemma general_sum_character: \"(\\<exists> x. F x) \\<longrightarrow> (\\<forall> y. y \\<preceq> (\\<sigma> v. F v) \\<longleftrightarrow> (\\<forall> w. w \\<preceq> y \\<longrightarrow> (\\<exists> v. F v \\<and> O v w)))\"\nproof\n  assume \"(\\<exists> x. F x)\"\n  hence \"\\<exists> z. \\<forall> y. O y z \\<longleftrightarrow> (\\<exists> x. F x \\<and> O x y)\"\n    using fusion by simp\n  then obtain z where z: \"\\<forall> y. O y z \\<longleftrightarrow> (\\<exists> x. F x \\<and> O x y)\"..\n  with general_sum_intro have sum:  \"(\\<sigma> v. F v) = z \"..\n  show \"\\<forall> y. y \\<preceq> (\\<sigma> v. F v) \\<longleftrightarrow> (\\<forall> w. w \\<preceq> y \\<longrightarrow> (\\<exists> v. F v \\<and> O v w))\"\n  proof\n    fix y\n    show \"y \\<preceq> (\\<sigma> v. F v) \\<longleftrightarrow> (\\<forall> w. w \\<preceq> y \\<longrightarrow> (\\<exists> v. F v \\<and> O v w))\"\n    proof\n      assume \"y \\<preceq> (\\<sigma> v. F v)\"\n      hence \"y \\<preceq> z\"\n        using sum by simp\n      hence \"O y z\"\n        using overlap_def P_reflexivity by auto\n      hence \"(\\<exists> x. F x \\<and> O x y)\"\n        using z by simp\n      thus \"(\\<forall> w. w \\<preceq> y \\<longrightarrow> (\\<exists> v. F v \\<and> O v w))\"\n        by (metis overlap_def P_reflexivity P_transitivity \\<open>y \\<preceq> z\\<close> z)\n    next\n      assume \"(\\<forall> w. w \\<preceq> y \\<longrightarrow> (\\<exists> v. F v \\<and> O v w))\"\n      hence \"y \\<preceq> z\" using z\n        by (meson disjoint_def strong_supplementation)\n      thus \"y \\<preceq> (\\<sigma> v. F v)\"\n        using sum by simp\n    qed\n  qed\nqed\n\ntext {* Following proof from @{cite \"pontow_note_2004\"} pp. 204  *}\n\nlemma product_closure: \"O x y \\<longrightarrow> (\\<exists> z. \\<forall> w. w \\<preceq> z \\<longleftrightarrow> (w \\<preceq> x \\<and> w \\<preceq> y))\"\nproof\n  assume \"O x y\"\n  hence common_P: \"\\<exists> z. (z \\<preceq> x \\<and> z \\<preceq> y)\"\n    using overlap_def by simp\n  have \"(\\<exists> v. (v \\<preceq> x \\<and> v \\<preceq> y)) \\<longrightarrow> (\\<forall> w. w \\<preceq> (\\<sigma> v. (v \\<preceq> x \\<and> v \\<preceq> y))  \\<longleftrightarrow> (\\<forall> z. z \\<preceq> w \\<longrightarrow> (\\<exists> v. (v \\<preceq> x \\<and> v \\<preceq> y) \\<and> O v z)))\"\n    using general_sum_character.\n  hence common_P_sum: \"(\\<forall> w. w \\<preceq> (\\<sigma> v. (v \\<preceq> x \\<and> v \\<preceq> y)) \\<longleftrightarrow> (\\<forall> z. z \\<preceq> w \\<longrightarrow> (\\<exists> v. (v \\<preceq> x \\<and> v \\<preceq> y) \\<and> O v z)))\"\n    using common_P..\n  have \"\\<forall> w. w \\<preceq> (\\<sigma> v. (v \\<preceq> x \\<and> v \\<preceq> y)) \\<longleftrightarrow> (w \\<preceq> x \\<and> w \\<preceq> y)\"\n  proof\n    fix w\n    show \"w \\<preceq> (\\<sigma> v. (v \\<preceq> x \\<and> v \\<preceq> y)) \\<longleftrightarrow> (w \\<preceq> x \\<and> w \\<preceq> y)\"\n    proof\n      assume \"w \\<preceq> (\\<sigma> v. (v \\<preceq> x \\<and> v \\<preceq> y))\"\n      hence \"(\\<forall> t. t \\<preceq> w \\<longrightarrow> (\\<exists> v. v \\<preceq> x \\<and> v \\<preceq> y \\<and> O v t))\"\n        using common_P_sum by simp\n      hence \"\\<forall> t. t \\<preceq> w \\<longrightarrow> (O t x \\<and> O t y)\"\n        by (meson overlap_symmetric P_overlappers_overlap)\n      thus \"w \\<preceq> x \\<and> w \\<preceq> y\"\n        using strong_supplementation P_transitivity disjoint_def by meson\n    next\n      assume \"w \\<preceq> x \\<and> w \\<preceq> y\"\n      thus \"w \\<preceq> (\\<sigma> v. (v \\<preceq> x \\<and> v \\<preceq> y))\"\n        using overlap_def P_reflexivity common_P_sum by fastforce\n    qed\n  qed\n  thus \"(\\<exists> z. \\<forall> w. w \\<preceq> z \\<longleftrightarrow> (w \\<preceq> x \\<and> w \\<preceq> y))\"..\nqed\n\nlemma universe_closure: \"\\<exists> z. \\<forall> x. x \\<preceq> z\"\n  using disjoint_def universal_overlap strong_supplementation by blast\n\ntext {* Pontow p. 209: *}\n\nlemma difference_closure: \"(\\<exists> w. w \\<preceq> a \\<and> D w b) \\<longrightarrow> (\\<exists> z. \\<forall> w. w \\<preceq> z \\<longleftrightarrow> (w \\<preceq> a \\<and> D w b))\"\nproof\n  assume antecedent: \"(\\<exists> w. w \\<preceq> a \\<and> D w b)\"\n  have \"(\\<exists> x. (x \\<preceq> a \\<and> D x b)) \\<longrightarrow> (\\<forall> y. y \\<preceq> (\\<sigma> v. (v \\<preceq> a \\<and> D v b)) \\<longleftrightarrow> (\\<forall> w. w \\<preceq> y \\<longrightarrow> (\\<exists> v. (v \\<preceq> a \\<and> D v b) \\<and> O v w)))\"\n    using general_sum_character.\n  hence sum: \"\\<forall> y. y \\<preceq> (\\<sigma> v. (v \\<preceq> a \\<and> D v b)) \\<longleftrightarrow> (\\<forall> w. w \\<preceq> y \\<longrightarrow> (\\<exists> v. (v \\<preceq> a \\<and> D v b) \\<and> O v w))\"\n    using antecedent..\n  have \"\\<forall> w. w \\<preceq> (\\<sigma> v. (v \\<preceq> a \\<and> D v b)) \\<longleftrightarrow> (w \\<preceq> a \\<and> D w b)\"\n  proof\n    fix w\n    show \"w \\<preceq> (\\<sigma> v. (v \\<preceq> a \\<and> D v b)) \\<longleftrightarrow> (w \\<preceq> a \\<and> D w b)\"\n    proof\n      assume left: \"w \\<preceq> (\\<sigma> v. (v \\<preceq> a \\<and> D v b))\"\n      have \"\\<forall> z. z \\<preceq> w \\<longrightarrow> O z a\"\n        using left overlap_symmetric P_overlappers_overlap sum by blast\n      hence \"w \\<preceq> a\"\n        using strong_supplementation disjoint_def by blast\n      have \"\\<forall> v. v \\<preceq> w \\<longrightarrow> \\<not> v \\<preceq> b\"\n        by (metis overlap_def disjoint_def P_transitivity sum left)\n      hence \"D w b\"\n        using overlap_def disjoint_def by simp\n      with \\<open>w \\<preceq> a\\<close> show \"w \\<preceq> a \\<and> D w b\"..\n    next\n      assume \"w \\<preceq> a \\<and> D w b\"\n      thus \"w \\<preceq> (\\<sigma> v. (v \\<preceq> a \\<and> D v b))\"\n        using overlap_symmetric P_implies_overlap sum by blast\n    qed\n  qed\n  thus \"(\\<exists> z. \\<forall> w. w \\<preceq> z \\<longleftrightarrow> (w \\<preceq> a \\<and> D w b))\"..\nqed\n\nlemma complement_closure: \"(\\<exists> w. D w x) \\<longrightarrow> (\\<exists> z. \\<forall> w. w \\<preceq> z \\<longleftrightarrow> D w x)\"\n  by (meson difference_closure universe_closure)\n\nend\n\nsublocale classical_extensional_mereology \\<subseteq> closed_extensional_mereology_with_universe_and_differences\nproof (unfold_locales)\n  show \"\\<And>x y. U x y \\<longrightarrow> (\\<exists>z. \\<forall>w. O w z = (O w x \\<or> O w y))\" using sum_closure by simp\n  show \" \\<And>x y. O x y \\<longrightarrow> (\\<exists>z. \\<forall>w. (w \\<preceq> z) = (w \\<preceq> x \\<and> w \\<preceq> y))\" using product_closure.\n  show \"\\<exists>z. \\<forall>x. x \\<preceq> z\" using universe_closure.\n  show \"\\<And>x y. (\\<exists>w. w \\<preceq> x \\<and> D w y) \\<longrightarrow> (\\<exists>z. \\<forall>w. (w \\<preceq> z) = (w \\<preceq> x \\<and> D w y))\" using difference_closure.\nqed\n\ncontext classical_extensional_mereology\nbegin\n\n\n(* lemma T60: \"(\\<exists> y. x \\<prec> y) \\<longrightarrow> x = (\\<pi> z. x \\<prec> z)\" nitpick [user_axioms] oops\n\nlemma T61:\n\"(\\<exists> x. \\<forall> y. F y \\<longrightarrow> x \\<preceq> y) \\<longrightarrow> (\\<pi> x. F x) = (THE x. \\<forall> y. x \\<preceq> y \\<longleftrightarrow> (\\<forall> z. F z \\<longrightarrow> y \\<preceq> x))\" nitpick [user_axioms] oops\n\n\nlemma T61a: \"(\\<sigma> x. \\<forall> y. F y \\<longrightarrow> x \\<preceq> y) = (THE x. \\<forall> y. x \\<preceq> y \\<longleftrightarrow> (\\<forall> z. F z \\<longrightarrow> y \\<preceq> x))\" nitpick oops\n\ntext {* It seems as if Simons thought \"(THE x. \\<forall> y. x \\<preceq> y \\<longleftrightarrow> (\\<forall> z. F z \\<longrightarrow> y \\<preceq> x))\" is an alternative way\nof defining general product, but the definitions are not equivalent. Really?! *}\n\n*)\n\nlemma general_sum_redef: \"(\\<exists> x. F x) \\<longrightarrow> (\\<sigma> x. F x) = (THE x. \\<forall> y. x \\<preceq> y \\<longleftrightarrow> (\\<forall> z. F z \\<longrightarrow> z \\<preceq> y))\"\nproof\n  assume \"\\<exists> x. F x\"\n  hence \"(\\<exists> z. \\<forall> y. O y z \\<longleftrightarrow> (\\<exists> x. F x \\<and> O x y))\"\n    using fusion by simp\n  then obtain z where z: \"\\<forall> y. O y z \\<longleftrightarrow> (\\<exists> x. F x \\<and> O x y)\"..\n  hence \"(\\<sigma> x. F x) = z\"\n    using general_sum_intro by simp\n  have \"(THE x. \\<forall> y. x \\<preceq> y \\<longleftrightarrow> (\\<forall> z. F z \\<longrightarrow> z \\<preceq> y)) = z\"\n  proof (rule the_equality)\n    show \"\\<forall>y. z \\<preceq> y \\<longleftrightarrow> (\\<forall> z. F z \\<longrightarrow> z \\<preceq> y)\"\n    proof\n      fix y\n      show \"z \\<preceq> y \\<longleftrightarrow> (\\<forall> z. F z \\<longrightarrow> z \\<preceq> y)\"\n      proof\n        assume \"z \\<preceq> y\" \n        thus \"(\\<forall> z. F z \\<longrightarrow> z \\<preceq> y)\"\n          using overlap_symmetric P_overlappers_overlap z by blast\n      next\n        assume \"(\\<forall> z. F z \\<longrightarrow> z \\<preceq> y)\"\n        thus \"z \\<preceq> y\"\n          using overlap_symmetric P_overlappers_overlap z by blast\n      qed\n    qed\n    thus \"\\<And>x. \\<forall>y. (x \\<preceq> y) = (\\<forall>z. F z \\<longrightarrow> z \\<preceq> y) \\<Longrightarrow> x = z\"\n      using P_antisymmetry P_reflexivity by blast\n  qed\n  thus \"(\\<sigma> x. F x) = (THE x. \\<forall> y. x \\<preceq> y \\<longleftrightarrow> (\\<forall> z. F z \\<longrightarrow> z \\<preceq> y))\" \n    using \\<open>(\\<sigma> x. F x) = z\\<close> by metis\nqed\n\nlemma T66:\n\"(\\<exists> x. F x) \\<longrightarrow> (\\<sigma> x. F x) = (THE x. (\\<forall> y. F y \\<longrightarrow> y \\<preceq> x) \\<and> (\\<forall> y. O y x \\<longleftrightarrow> (\\<exists> z. F z \\<and> O y z)))\"\nproof\n  assume \"\\<exists> x. F x\"\n  hence \"(\\<exists> z. \\<forall> y. O y z \\<longleftrightarrow> (\\<exists> x. F x \\<and> O x y))\"\n    using fusion by simp\n  then obtain z where z: \"\\<forall> y. O y z \\<longleftrightarrow> (\\<exists> x. F x \\<and> O x y)\"..\n  hence \"z = (\\<sigma> x. F x)\"\n    using general_sum_intro by simp\n  have \"(THE x. (\\<forall> y. F y \\<longrightarrow> y \\<preceq> x) \\<and> (\\<forall> y. O y x \\<longleftrightarrow> (\\<exists> z. F z \\<and> O y z))) = z\"\n  proof (rule the_equality)\n    show \"(\\<forall>y. F y \\<longrightarrow> y \\<preceq> z) \\<and> (\\<forall>y. O y z = (\\<exists>z. F z \\<and> O y z))\"\n      using overlap_symmetric P_overlappers_overlap z by blast\n    thus \" \\<And>x. (\\<forall>y. F y \\<longrightarrow> y \\<preceq> x) \\<and> (\\<forall>y. O y x = (\\<exists>z. F z \\<and> O y z)) \\<Longrightarrow> x = z\"\n      by (metis sum_intro)\n  qed\n  thus \"(\\<sigma> x. F x) = (THE x. (\\<forall> y. F y \\<longrightarrow> y \\<preceq> x) \\<and> (\\<forall> y. O y x \\<longleftrightarrow> (\\<exists> z. F z \\<and> O y z)))\" \n    using \\<open>z = (\\<sigma> x. F x)\\<close> by metis\nqed\n\nlemma \"(\\<exists> y. F y) \\<longrightarrow> O x (\\<sigma> y. F y) \\<longleftrightarrow> (\\<exists> z. F z \\<and> O z x)\"\nproof\n  assume \"(\\<exists> y. F y)\"\n  hence \"\\<exists> z. \\<forall> y. O y z \\<longleftrightarrow> (\\<exists> x. F x \\<and> O x y)\"\n    using fusion by simp\n  then obtain z where z: \"\\<forall> y. O y z \\<longleftrightarrow> (\\<exists> x. F x \\<and> O x y)\"..\n  hence \"(\\<sigma> y. F y) = z\"\n    using general_sum_intro by simp\n  thus \"O x (\\<sigma> y. F y) \\<longleftrightarrow> (\\<exists> z. F z \\<and> O z x)\" by (metis z)\nqed\n\nlemma T68: \"D x (\\<sigma> y. F y) \\<longrightarrow> (\\<forall> z. F z \\<longrightarrow> D z x)\"\nproof\n  assume antecedent: \"D x (\\<sigma> y. F y)\"\n  show \"(\\<forall> z. F z \\<longrightarrow> D z x)\"\n  proof cases\n    assume \"\\<exists> z. F z\"\n    with general_sum_character have sum: \"\\<forall> y. (y \\<preceq> (\\<sigma> v. F v)) \\<longleftrightarrow> (\\<forall> w. w \\<preceq> y \\<longrightarrow> (\\<exists> v. F v \\<and> O v w))\"..\n    show \"(\\<forall> z. F z \\<longrightarrow> D z x)\"\n    proof\n      fix z\n      show \"F z \\<longrightarrow> D z x\"\n      proof\n        assume \"F z\"\n        from sum have \"(z \\<preceq> (\\<sigma> v. F v)) \\<longleftrightarrow> (\\<forall> w. w \\<preceq> z \\<longrightarrow> (\\<exists> v. F v \\<and> O v w))\"..\n        with \\<open>F z\\<close> have \"(z \\<preceq> (\\<sigma> v. F v))\"\n          by (metis overlap_symmetric P_reflexivity Ps_of_Ps_overlap)\n        with antecedent show \"D z x\" \n          by (metis disjoint_def overlap_symmetric P_overlappers_overlap)\n      qed\n    qed\n  next\n    assume \"\\<not> (\\<exists> z. F z)\"\n    thus \"\\<forall> z. F z \\<longrightarrow> D z x\"\n      by blast\n  qed\nqed\n\n(*\nlemma T70: \"(\\<sigma> x. F x) \\<preceq> (\\<sigma> y. G y) \\<longrightarrow> (\\<forall> x. F x \\<longrightarrow> (\\<exists> y. G y \\<and> O x y))\" nitpick oops *)\n\nlemma \"(\\<exists> x. F x) \\<and> (\\<exists> x. G x) \\<longrightarrow>\n (\\<sigma> x. F x) \\<preceq> (\\<sigma> y. G y) \\<longrightarrow> (\\<forall> x. F x \\<longrightarrow> (\\<exists> y. G y \\<and> O x y))\"\nproof\n  assume \"(\\<exists> x. F x) \\<and> (\\<exists> x. G x)\"\n  hence \"\\<exists> z. \\<forall> y. O y z \\<longleftrightarrow> (\\<exists> x. F x \\<and> O x y)\"\n    using fusion by simp\n  then obtain z where z: \"\\<forall> y. O y z \\<longleftrightarrow> (\\<exists> x. F x \\<and> O x y)\"..\n  hence \"(\\<sigma> y. F y) = z\"\n    using general_sum_intro by simp\n  have \"(\\<exists> x. G x)\"\n    by (simp add: \\<open>(\\<exists>x. F x) \\<and> (\\<exists>x. G x)\\<close>)\n  hence \"\\<exists> z. \\<forall> y. O y z \\<longleftrightarrow> (\\<exists> x. G x \\<and> O x y)\"\n    using fusion by simp\n  then obtain z where z: \"\\<forall> y. O y z \\<longleftrightarrow> (\\<exists> x. G x \\<and> O x y)\"..\n  hence \"(\\<sigma> y. G y) = z\"\n    using general_sum_intro by simp\n  show \"(\\<sigma> x. F x) \\<preceq> (\\<sigma> y. G y) \\<longrightarrow> (\\<forall> x. F x \\<longrightarrow> (\\<exists> y. G y \\<and> O x y))\"\n  proof\n    assume \"(\\<sigma> x. F x) \\<preceq> (\\<sigma> y. G y)\"\n    thus \"(\\<forall> x. F x \\<longrightarrow> (\\<exists> y. G y \\<and> O x y))\"\n      by (metis T68 \\<open>(\\<sigma> y. G y) = z\\<close> mereology.disjoint_def mereology.overlap_symmetric\nP_overlappers_overlap P_implies_overlap z)\n  qed\nqed\n\nend\n\nend\n\n", "meta": {"author": "Manikaran20", "repo": "Mereology", "sha": "d71a0c42c48e370e64bbeb85cee7d0ba5c2d388e", "save_path": "github-repos/isabelle/Manikaran20-Mereology", "path": "github-repos/isabelle/Manikaran20-Mereology/Mereology-d71a0c42c48e370e64bbeb85cee7d0ba5c2d388e/Mereology.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467548438124, "lm_q2_score": 0.8006919925839875, "lm_q1q2_score": 0.7039257669096385}}
{"text": "text \\<open>https://coq-math-problems.github.io/Problem1/\\<close>\n\ntheory Valley \n  imports Main\nbegin\n  \ninductive valley_at :: \"(nat \\<Rightarrow> nat) \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> bool\"\n  where valley_at_0: \"valley_at f x 0\"\n  | extend_valley: \"\\<lbrakk>valley_at f x n; f x = f (x + n + 1)\\<rbrakk> \\<Longrightarrow> valley_at f x (Suc n)\"\n   \nlemma valley_def: \"valley_at f x n \\<longleftrightarrow> (\\<forall>y. x \\<le> y \\<and> y \\<le> x + n \\<longrightarrow> f x = f y)\"\nproof (intro iffI)\n  assume \"valley_at f x n\"\n  thus \"\\<forall>y. x \\<le> y \\<and> y \\<le> x + n \\<longrightarrow> f x = f y\"\n    by (induction rule: valley_at.induct) (auto elim: le_SucE)\nnext\n  assume \"\\<forall>y. x \\<le> y \\<and> y \\<le> x + n \\<longrightarrow> f x = f y\"\n  thus \"valley_at f x n\"\n    by (induction n) (auto intro: valley_at_0 extend_valley)\nqed\n    \nabbreviation \"decr\" where \"decr f \\<equiv> monotone op \\<le> op \\<ge> f\"\n    \nlemma valley_or_drop: \"decr f \\<Longrightarrow> valley_at f x n \\<or> (\\<exists>y. f y < f x)\"\n  by (metis nat_less_le valley_def monotone_def)\n\nlemma \n  assumes \"decr f\" \n  shows \"\\<exists>x. valley_at f x n\"\nproof (induction arbitrary: n rule: measure_induct_rule[of f])\n  case (less x)\n  with \\<open>decr f\\<close> valley_or_drop show ?case\n    by blast\nqed\n  \nend", "meta": {"author": "sgraf812", "repo": "dailyprover", "sha": "67c33785906ccb80a2d7be65a8ab14f491988440", "save_path": "github-repos/isabelle/sgraf812-dailyprover", "path": "github-repos/isabelle/sgraf812-dailyprover/dailyprover-67c33785906ccb80a2d7be65a8ab14f491988440/Valley.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.89330940889474, "lm_q2_score": 0.787931188173138, "lm_q1q2_score": 0.703866343956676}}
{"text": "(*  Author:     Tobias Nipkow, Lawrence C Paulson and Markus Wenzel *)\n\nsection {* Set theory for higher-order logic *}\n\ntheory Set\nimports Lattices\nbegin\n\nsubsection {* Sets as predicates *}\n\ntypedecl 'a set\n\naxiomatization Collect :: \"('a \\<Rightarrow> bool) \\<Rightarrow> 'a set\" -- \"comprehension\"\n  and member :: \"'a \\<Rightarrow> 'a set \\<Rightarrow> bool\" -- \"membership\"\nwhere\n  mem_Collect_eq [iff, code_unfold]: \"member a (Collect P) = P a\"\n  and Collect_mem_eq [simp]: \"Collect (\\<lambda>x. member x A) = A\"\n\nnotation\n  member  (\"op :\") and\n  member  (\"(_/ : _)\" [51, 51] 50)\n\nabbreviation not_member where\n  \"not_member x A \\<equiv> ~ (x : A)\" -- \"non-membership\"\n\nnotation\n  not_member  (\"op ~:\") and\n  not_member  (\"(_/ ~: _)\" [51, 51] 50)\n\nnotation (xsymbols)\n  member      (\"op \\<in>\") and\n  member      (\"(_/ \\<in> _)\" [51, 51] 50) and\n  not_member  (\"op \\<notin>\") and\n  not_member  (\"(_/ \\<notin> _)\" [51, 51] 50)\n\nnotation (HTML output)\n  member      (\"op \\<in>\") and\n  member      (\"(_/ \\<in> _)\" [51, 51] 50) and\n  not_member  (\"op \\<notin>\") and\n  not_member  (\"(_/ \\<notin> _)\" [51, 51] 50)\n\n\ntext {* Set comprehensions *}\n\nsyntax\n  \"_Coll\" :: \"pttrn => bool => 'a set\"    (\"(1{_./ _})\")\ntranslations\n  \"{x. P}\" == \"CONST Collect (%x. P)\"\n\nsyntax\n  \"_Collect\" :: \"pttrn => 'a set => bool => 'a set\"    (\"(1{_ :/ _./ _})\")\nsyntax (xsymbols)\n  \"_Collect\" :: \"pttrn => 'a set => bool => 'a set\"    (\"(1{_ \\<in>/ _./ _})\")\ntranslations\n  \"{p:A. P}\" => \"CONST Collect (%p. p:A & P)\"\n\nlemma CollectI: \"P a \\<Longrightarrow> a \\<in> {x. P x}\"\n  by simp\n\nlemma CollectD: \"a \\<in> {x. P x} \\<Longrightarrow> P a\"\n  by simp\n\nlemma Collect_cong: \"(\\<And>x. P x = Q x) ==> {x. P x} = {x. Q x}\"\n  by simp\n\ntext {*\nSimproc for pulling @{text \"x=t\"} in @{text \"{x. \\<dots> & x=t & \\<dots>}\"}\nto the front (and similarly for @{text \"t=x\"}):\n*}\n\nsimproc_setup defined_Collect (\"{x. P x & Q x}\") = {*\n  fn _ => Quantifier1.rearrange_Collect\n    (fn _ =>\n      resolve_tac @{thms Collect_cong} 1 THEN\n      resolve_tac @{thms iffI} 1 THEN\n      ALLGOALS\n        (EVERY' [REPEAT_DETERM o eresolve_tac @{thms conjE},\n          DEPTH_SOLVE_1 o ares_tac @{thms conjI}]))\n*}\n\nlemmas CollectE = CollectD [elim_format]\n\nlemma set_eqI:\n  assumes \"\\<And>x. x \\<in> A \\<longleftrightarrow> x \\<in> B\"\n  shows \"A = B\"\nproof -\n  from assms have \"{x. x \\<in> A} = {x. x \\<in> B}\" by simp\n  then show ?thesis by simp\nqed\n\nlemma set_eq_iff:\n  \"A = B \\<longleftrightarrow> (\\<forall>x. x \\<in> A \\<longleftrightarrow> x \\<in> B)\"\n  by (auto intro:set_eqI)\n\ntext {* Lifting of predicate class instances *}\n\ninstantiation set :: (type) boolean_algebra\nbegin\n\ndefinition less_eq_set where\n  \"A \\<le> B \\<longleftrightarrow> (\\<lambda>x. member x A) \\<le> (\\<lambda>x. member x B)\"\n\ndefinition less_set where\n  \"A < B \\<longleftrightarrow> (\\<lambda>x. member x A) < (\\<lambda>x. member x B)\"\n\ndefinition inf_set where\n  \"A \\<sqinter> B = Collect ((\\<lambda>x. member x A) \\<sqinter> (\\<lambda>x. member x B))\"\n\ndefinition sup_set where\n  \"A \\<squnion> B = Collect ((\\<lambda>x. member x A) \\<squnion> (\\<lambda>x. member x B))\"\n\ndefinition bot_set where\n  \"\\<bottom> = Collect \\<bottom>\"\n\ndefinition top_set where\n  \"\\<top> = Collect \\<top>\"\n\ndefinition uminus_set where\n  \"- A = Collect (- (\\<lambda>x. member x A))\"\n\ndefinition minus_set where\n  \"A - B = Collect ((\\<lambda>x. member x A) - (\\<lambda>x. member x B))\"\n\ninstance proof\nqed (simp_all add: less_eq_set_def less_set_def inf_set_def sup_set_def\n  bot_set_def top_set_def uminus_set_def minus_set_def\n  less_le_not_le inf_compl_bot sup_compl_top sup_inf_distrib1 diff_eq\n  set_eqI fun_eq_iff\n  del: inf_apply sup_apply bot_apply top_apply minus_apply uminus_apply)\n\nend\n\ntext {* Set enumerations *}\n\nabbreviation empty :: \"'a set\" (\"{}\") where\n  \"{} \\<equiv> bot\"\n\ndefinition insert :: \"'a \\<Rightarrow> 'a set \\<Rightarrow> 'a set\" where\n  insert_compr: \"insert a B = {x. x = a \\<or> x \\<in> B}\"\n\nsyntax\n  \"_Finset\" :: \"args => 'a set\"    (\"{(_)}\")\ntranslations\n  \"{x, xs}\" == \"CONST insert x {xs}\"\n  \"{x}\" == \"CONST insert x {}\"\n\n\nsubsection {* Subsets and bounded quantifiers *}\n\nabbreviation\n  subset :: \"'a set \\<Rightarrow> 'a set \\<Rightarrow> bool\" where\n  \"subset \\<equiv> less\"\n\nabbreviation\n  subset_eq :: \"'a set \\<Rightarrow> 'a set \\<Rightarrow> bool\" where\n  \"subset_eq \\<equiv> less_eq\"\n\nnotation (output)\n  subset  (\"op <\") and\n  subset  (\"(_/ < _)\" [51, 51] 50) and\n  subset_eq  (\"op <=\") and\n  subset_eq  (\"(_/ <= _)\" [51, 51] 50)\n\nnotation (xsymbols)\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\nnotation (HTML output)\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\nabbreviation (input)\n  supset :: \"'a set \\<Rightarrow> 'a set \\<Rightarrow> bool\" where\n  \"supset \\<equiv> greater\"\n\nabbreviation (input)\n  supset_eq :: \"'a set \\<Rightarrow> 'a set \\<Rightarrow> bool\" where\n  \"supset_eq \\<equiv> greater_eq\"\n\nnotation (xsymbols)\n  supset  (\"op \\<supset>\") and\n  supset  (\"(_/ \\<supset> _)\" [51, 51] 50) and\n  supset_eq  (\"op \\<supseteq>\") and\n  supset_eq  (\"(_/ \\<supseteq> _)\" [51, 51] 50)\n\ndefinition Ball :: \"'a set \\<Rightarrow> ('a \\<Rightarrow> bool) \\<Rightarrow> bool\" where\n  \"Ball A P \\<longleftrightarrow> (\\<forall>x. x \\<in> A \\<longrightarrow> P x)\"   -- \"bounded universal quantifiers\"\n\ndefinition Bex :: \"'a set \\<Rightarrow> ('a \\<Rightarrow> bool) \\<Rightarrow> bool\" where\n  \"Bex A P \\<longleftrightarrow> (\\<exists>x. x \\<in> A \\<and> P x)\"   -- \"bounded existential quantifiers\"\n\nsyntax\n  \"_Ball\"       :: \"pttrn => 'a set => bool => bool\"      (\"(3ALL _:_./ _)\" [0, 0, 10] 10)\n  \"_Bex\"        :: \"pttrn => 'a set => bool => bool\"      (\"(3EX _:_./ _)\" [0, 0, 10] 10)\n  \"_Bex1\"       :: \"pttrn => 'a set => bool => bool\"      (\"(3EX! _:_./ _)\" [0, 0, 10] 10)\n  \"_Bleast\"     :: \"id => 'a set => bool => 'a\"           (\"(3LEAST _:_./ _)\" [0, 0, 10] 10)\n\nsyntax (HOL)\n  \"_Ball\"       :: \"pttrn => 'a set => bool => bool\"      (\"(3! _:_./ _)\" [0, 0, 10] 10)\n  \"_Bex\"        :: \"pttrn => 'a set => bool => bool\"      (\"(3? _:_./ _)\" [0, 0, 10] 10)\n  \"_Bex1\"       :: \"pttrn => 'a set => bool => bool\"      (\"(3?! _:_./ _)\" [0, 0, 10] 10)\n\nsyntax (xsymbols)\n  \"_Ball\"       :: \"pttrn => 'a set => bool => bool\"      (\"(3\\<forall>_\\<in>_./ _)\" [0, 0, 10] 10)\n  \"_Bex\"        :: \"pttrn => 'a set => bool => bool\"      (\"(3\\<exists>_\\<in>_./ _)\" [0, 0, 10] 10)\n  \"_Bex1\"       :: \"pttrn => 'a set => bool => bool\"      (\"(3\\<exists>!_\\<in>_./ _)\" [0, 0, 10] 10)\n  \"_Bleast\"     :: \"id => 'a set => bool => 'a\"           (\"(3LEAST_\\<in>_./ _)\" [0, 0, 10] 10)\n\nsyntax (HTML output)\n  \"_Ball\"       :: \"pttrn => 'a set => bool => bool\"      (\"(3\\<forall>_\\<in>_./ _)\" [0, 0, 10] 10)\n  \"_Bex\"        :: \"pttrn => 'a set => bool => bool\"      (\"(3\\<exists>_\\<in>_./ _)\" [0, 0, 10] 10)\n  \"_Bex1\"       :: \"pttrn => 'a set => bool => bool\"      (\"(3\\<exists>!_\\<in>_./ _)\" [0, 0, 10] 10)\n\ntranslations\n  \"ALL x:A. P\" == \"CONST Ball A (%x. P)\"\n  \"EX x:A. P\" == \"CONST Bex A (%x. P)\"\n  \"EX! x:A. P\" => \"EX! x. x:A & P\"\n  \"LEAST x:A. P\" => \"LEAST x. x:A & P\"\n\nsyntax (output)\n  \"_setlessAll\" :: \"[idt, 'a, bool] => bool\"  (\"(3ALL _<_./ _)\"  [0, 0, 10] 10)\n  \"_setlessEx\"  :: \"[idt, 'a, bool] => bool\"  (\"(3EX _<_./ _)\"  [0, 0, 10] 10)\n  \"_setleAll\"   :: \"[idt, 'a, bool] => bool\"  (\"(3ALL _<=_./ _)\" [0, 0, 10] 10)\n  \"_setleEx\"    :: \"[idt, 'a, bool] => bool\"  (\"(3EX _<=_./ _)\" [0, 0, 10] 10)\n  \"_setleEx1\"   :: \"[idt, 'a, bool] => bool\"  (\"(3EX! _<=_./ _)\" [0, 0, 10] 10)\n\nsyntax (xsymbols)\n  \"_setlessAll\" :: \"[idt, 'a, bool] => bool\"   (\"(3\\<forall>_\\<subset>_./ _)\"  [0, 0, 10] 10)\n  \"_setlessEx\"  :: \"[idt, 'a, bool] => bool\"   (\"(3\\<exists>_\\<subset>_./ _)\"  [0, 0, 10] 10)\n  \"_setleAll\"   :: \"[idt, 'a, bool] => bool\"   (\"(3\\<forall>_\\<subseteq>_./ _)\" [0, 0, 10] 10)\n  \"_setleEx\"    :: \"[idt, 'a, bool] => bool\"   (\"(3\\<exists>_\\<subseteq>_./ _)\" [0, 0, 10] 10)\n  \"_setleEx1\"   :: \"[idt, 'a, bool] => bool\"   (\"(3\\<exists>!_\\<subseteq>_./ _)\" [0, 0, 10] 10)\n\nsyntax (HOL output)\n  \"_setlessAll\" :: \"[idt, 'a, bool] => bool\"   (\"(3! _<_./ _)\"  [0, 0, 10] 10)\n  \"_setlessEx\"  :: \"[idt, 'a, bool] => bool\"   (\"(3? _<_./ _)\"  [0, 0, 10] 10)\n  \"_setleAll\"   :: \"[idt, 'a, bool] => bool\"   (\"(3! _<=_./ _)\" [0, 0, 10] 10)\n  \"_setleEx\"    :: \"[idt, 'a, bool] => bool\"   (\"(3? _<=_./ _)\" [0, 0, 10] 10)\n  \"_setleEx1\"   :: \"[idt, 'a, bool] => bool\"   (\"(3?! _<=_./ _)\" [0, 0, 10] 10)\n\nsyntax (HTML output)\n  \"_setlessAll\" :: \"[idt, 'a, bool] => bool\"   (\"(3\\<forall>_\\<subset>_./ _)\"  [0, 0, 10] 10)\n  \"_setlessEx\"  :: \"[idt, 'a, bool] => bool\"   (\"(3\\<exists>_\\<subset>_./ _)\"  [0, 0, 10] 10)\n  \"_setleAll\"   :: \"[idt, 'a, bool] => bool\"   (\"(3\\<forall>_\\<subseteq>_./ _)\" [0, 0, 10] 10)\n  \"_setleEx\"    :: \"[idt, 'a, bool] => bool\"   (\"(3\\<exists>_\\<subseteq>_./ _)\" [0, 0, 10] 10)\n  \"_setleEx1\"   :: \"[idt, 'a, bool] => bool\"   (\"(3\\<exists>!_\\<subseteq>_./ _)\" [0, 0, 10] 10)\n\ntranslations\n \"\\<forall>A\\<subset>B. P\"   =>  \"ALL A. A \\<subset> B --> P\"\n \"\\<exists>A\\<subset>B. P\"   =>  \"EX A. A \\<subset> B & P\"\n \"\\<forall>A\\<subseteq>B. P\"   =>  \"ALL A. A \\<subseteq> B --> P\"\n \"\\<exists>A\\<subseteq>B. P\"   =>  \"EX A. A \\<subseteq> B & P\"\n \"\\<exists>!A\\<subseteq>B. P\"  =>  \"EX! A. A \\<subseteq> B & P\"\n\nprint_translation {*\n  let\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 sbset = @{const_syntax subset};\n    val sbset_eq = @{const_syntax subset_eq};\n\n    val trans =\n     [((All_binder, impl, sbset), @{syntax_const \"_setlessAll\"}),\n      ((All_binder, impl, sbset_eq), @{syntax_const \"_setleAll\"}),\n      ((Ex_binder, conj, sbset), @{syntax_const \"_setlessEx\"}),\n      ((Ex_binder, conj, sbset_eq), @{syntax_const \"_setleEx\"})];\n\n    fun mk v (v', T) c n P =\n      if v = v' andalso not (Term.exists_subterm (fn Free (x, _) => x = v | _ => false) n)\n      then Syntax.const c $ Syntax_Trans.mark_bound_body (v', T) $ n $ P\n      else raise Match;\n\n    fun tr' q = (q, fn _ =>\n      (fn [Const (@{syntax_const \"_bound\"}, _) $ Free (v, Type (@{type_name set}, _)),\n          Const (c, _) $\n            (Const (d, _) $ (Const (@{syntax_const \"_bound\"}, _) $ Free (v', T)) $ n) $ P] =>\n          (case AList.lookup (op =) trans (q, c, d) of\n            NONE => raise Match\n          | SOME l => mk v (v', T) l n P)\n        | _ => raise Match));\n  in\n    [tr' All_binder, tr' Ex_binder]\n  end\n*}\n\n\ntext {*\n  \\medskip Translate between @{text \"{e | x1...xn. P}\"} and @{text\n  \"{u. EX x1..xn. u = e & P}\"}; @{text \"{y. EX x1..xn. y = e & P}\"} is\n  only translated if @{text \"[0..n] subset bvs(e)\"}.\n*}\n\nsyntax\n  \"_Setcompr\" :: \"'a => idts => bool => 'a set\"    (\"(1{_ |/_./ _})\")\n\nparse_translation {*\n  let\n    val ex_tr = snd (Syntax_Trans.mk_binder_tr (\"EX \", @{const_syntax Ex}));\n\n    fun nvars (Const (@{syntax_const \"_idts\"}, _) $ _ $ idts) = nvars idts + 1\n      | nvars _ = 1;\n\n    fun setcompr_tr ctxt [e, idts, b] =\n      let\n        val eq = Syntax.const @{const_syntax HOL.eq} $ Bound (nvars idts) $ e;\n        val P = Syntax.const @{const_syntax HOL.conj} $ eq $ b;\n        val exP = ex_tr ctxt [idts, P];\n      in Syntax.const @{const_syntax Collect} $ absdummy dummyT exP end;\n\n  in [(@{syntax_const \"_Setcompr\"}, setcompr_tr)] end;\n*}\n\nprint_translation {*\n [Syntax_Trans.preserve_binder_abs2_tr' @{const_syntax Ball} @{syntax_const \"_Ball\"},\n  Syntax_Trans.preserve_binder_abs2_tr' @{const_syntax Bex} @{syntax_const \"_Bex\"}]\n*} -- {* to avoid eta-contraction of body *}\n\nprint_translation {*\nlet\n  val ex_tr' = snd (Syntax_Trans.mk_binder_tr' (@{const_syntax Ex}, \"DUMMY\"));\n\n  fun setcompr_tr' ctxt [Abs (abs as (_, _, P))] =\n    let\n      fun check (Const (@{const_syntax Ex}, _) $ Abs (_, _, P), n) = check (P, n + 1)\n        | check (Const (@{const_syntax HOL.conj}, _) $\n              (Const (@{const_syntax HOL.eq}, _) $ Bound m $ e) $ P, n) =\n            n > 0 andalso m = n andalso not (loose_bvar1 (P, n)) andalso\n            subset (op =) (0 upto (n - 1), add_loose_bnos (e, 0, []))\n        | check _ = false;\n\n        fun tr' (_ $ abs) =\n          let val _ $ idts $ (_ $ (_ $ _ $ e) $ Q) = ex_tr' ctxt [abs]\n          in Syntax.const @{syntax_const \"_Setcompr\"} $ e $ idts $ Q end;\n    in\n      if check (P, 0) then tr' P\n      else\n        let\n          val (x as _ $ Free(xN, _), t) = Syntax_Trans.atomic_abs_tr' abs;\n          val M = Syntax.const @{syntax_const \"_Coll\"} $ x $ t;\n        in\n          case t of\n            Const (@{const_syntax HOL.conj}, _) $\n              (Const (@{const_syntax Set.member}, _) $\n                (Const (@{syntax_const \"_bound\"}, _) $ Free (yN, _)) $ A) $ P =>\n            if xN = yN then Syntax.const @{syntax_const \"_Collect\"} $ x $ A $ P else M\n          | _ => M\n        end\n    end;\n  in [(@{const_syntax Collect}, setcompr_tr')] end;\n*}\n\nsimproc_setup defined_Bex (\"EX x:A. P x & Q x\") = {*\n  fn _ => Quantifier1.rearrange_bex\n    (fn ctxt =>\n      unfold_tac ctxt @{thms Bex_def} THEN\n      Quantifier1.prove_one_point_ex_tac)\n*}\n\nsimproc_setup defined_All (\"ALL x:A. P x --> Q x\") = {*\n  fn _ => Quantifier1.rearrange_ball\n    (fn ctxt =>\n      unfold_tac ctxt @{thms Ball_def} THEN\n      Quantifier1.prove_one_point_all_tac)\n*}\n\nlemma ballI [intro!]: \"(!!x. x:A ==> P x) ==> ALL x:A. P x\"\n  by (simp add: Ball_def)\n\nlemmas strip = impI allI ballI\n\nlemma bspec [dest?]: \"ALL x:A. P x ==> x:A ==> P x\"\n  by (simp add: Ball_def)\n\ntext {*\n  Gives better instantiation for bound:\n*}\n\nsetup {*\n  map_theory_claset (fn ctxt =>\n    ctxt addbefore (\"bspec\", fn ctxt' => dresolve_tac @{thms bspec} THEN' assume_tac ctxt'))\n*}\n\nML {*\nstructure Simpdata =\nstruct\n\nopen Simpdata;\n\nval mksimps_pairs = [(@{const_name Ball}, @{thms bspec})] @ mksimps_pairs;\n\nend;\n\nopen Simpdata;\n*}\n\ndeclaration {* fn _ =>\n  Simplifier.map_ss (Simplifier.set_mksimps (mksimps mksimps_pairs))\n*}\n\nlemma ballE [elim]: \"ALL x:A. P x ==> (P x ==> Q) ==> (x ~: A ==> Q) ==> Q\"\n  by (unfold Ball_def) blast\n\nlemma bexI [intro]: \"P x ==> x:A ==> EX x:A. P x\"\n  -- {* Normally the best argument order: @{prop \"P x\"} constrains the\n    choice of @{prop \"x:A\"}. *}\n  by (unfold Bex_def) blast\n\nlemma rev_bexI [intro?]: \"x:A ==> P x ==> EX x:A. P x\"\n  -- {* The best argument order when there is only one @{prop \"x:A\"}. *}\n  by (unfold Bex_def) blast\n\nlemma bexCI: \"(ALL x:A. ~P x ==> P a) ==> a:A ==> EX x:A. P x\"\n  by (unfold Bex_def) blast\n\nlemma bexE [elim!]: \"EX x:A. P x ==> (!!x. x:A ==> P x ==> Q) ==> Q\"\n  by (unfold Bex_def) blast\n\nlemma ball_triv [simp]: \"(ALL x:A. P) = ((EX x. x:A) --> P)\"\n  -- {* Trival rewrite rule. *}\n  by (simp add: Ball_def)\n\nlemma bex_triv [simp]: \"(EX x:A. P) = ((EX x. x:A) & P)\"\n  -- {* Dual form for existentials. *}\n  by (simp add: Bex_def)\n\nlemma bex_triv_one_point1 [simp]: \"(EX x:A. x = a) = (a:A)\"\n  by blast\n\nlemma bex_triv_one_point2 [simp]: \"(EX x:A. a = x) = (a:A)\"\n  by blast\n\nlemma bex_one_point1 [simp]: \"(EX x:A. x = a & P x) = (a:A & P a)\"\n  by blast\n\nlemma bex_one_point2 [simp]: \"(EX x:A. a = x & P x) = (a:A & P a)\"\n  by blast\n\nlemma ball_one_point1 [simp]: \"(ALL x:A. x = a --> P x) = (a:A --> P a)\"\n  by blast\n\nlemma ball_one_point2 [simp]: \"(ALL x:A. a = x --> P x) = (a:A --> P a)\"\n  by blast\n\nlemma ball_conj_distrib:\n  \"(\\<forall>x\\<in>A. P x \\<and> Q x) \\<longleftrightarrow> ((\\<forall>x\\<in>A. P x) \\<and> (\\<forall>x\\<in>A. Q x))\"\n  by blast\n\nlemma bex_disj_distrib:\n  \"(\\<exists>x\\<in>A. P x \\<or> Q x) \\<longleftrightarrow> ((\\<exists>x\\<in>A. P x) \\<or> (\\<exists>x\\<in>A. Q x))\"\n  by blast\n\n\ntext {* Congruence rules *}\n\nlemma ball_cong:\n  \"A = B ==> (!!x. x:B ==> P x = Q x) ==>\n    (ALL x:A. P x) = (ALL x:B. Q x)\"\n  by (simp add: Ball_def)\n\nlemma strong_ball_cong [cong]:\n  \"A = B ==> (!!x. x:B =simp=> P x = Q x) ==>\n    (ALL x:A. P x) = (ALL x:B. Q x)\"\n  by (simp add: simp_implies_def Ball_def)\n\nlemma bex_cong:\n  \"A = B ==> (!!x. x:B ==> P x = Q x) ==>\n    (EX x:A. P x) = (EX x:B. Q x)\"\n  by (simp add: Bex_def cong: conj_cong)\n\nlemma strong_bex_cong [cong]:\n  \"A = B ==> (!!x. x:B =simp=> P x = Q x) ==>\n    (EX x:A. P x) = (EX x:B. Q x)\"\n  by (simp add: simp_implies_def Bex_def cong: conj_cong)\n\nlemma bex1_def: \"(\\<exists>!x\\<in>X. P x) \\<longleftrightarrow> (\\<exists>x\\<in>X. P x) \\<and> (\\<forall>x\\<in>X. \\<forall>y\\<in>X. P x \\<longrightarrow> P y \\<longrightarrow> x = y)\"\n  by auto\n\nsubsection {* Basic operations *}\n\nsubsubsection {* Subsets *}\n\nlemma subsetI [intro!]: \"(\\<And>x. x \\<in> A \\<Longrightarrow> x \\<in> B) \\<Longrightarrow> A \\<subseteq> B\"\n  by (simp add: less_eq_set_def le_fun_def)\n\ntext {*\n  \\medskip Map the type @{text \"'a set => anything\"} to just @{typ\n  'a}; for overloading constants whose first argument has type @{typ\n  \"'a set\"}.\n*}\n\nlemma subsetD [elim, intro?]: \"A \\<subseteq> B ==> c \\<in> A ==> c \\<in> B\"\n  by (simp add: less_eq_set_def le_fun_def)\n  -- {* Rule in Modus Ponens style. *}\n\nlemma rev_subsetD [intro?]: \"c \\<in> A ==> A \\<subseteq> B ==> c \\<in> B\"\n  -- {* The same, with reversed premises for use with @{text erule} --\n      cf @{text rev_mp}. *}\n  by (rule subsetD)\n\ntext {*\n  \\medskip Converts @{prop \"A \\<subseteq> B\"} to @{prop \"x \\<in> A ==> x \\<in> B\"}.\n*}\n\nlemma subsetCE [elim]: \"A \\<subseteq> B ==> (c \\<notin> A ==> P) ==> (c \\<in> B ==> P) ==> P\"\n  -- {* Classical elimination rule. *}\n  by (auto simp add: less_eq_set_def le_fun_def)\n\nlemma subset_eq: \"A \\<le> B = (\\<forall>x\\<in>A. x \\<in> B)\" by blast\n\nlemma contra_subsetD: \"A \\<subseteq> B ==> c \\<notin> B ==> c \\<notin> A\"\n  by blast\n\nlemma subset_refl: \"A \\<subseteq> A\"\n  by (fact order_refl) (* already [iff] *)\n\nlemma subset_trans: \"A \\<subseteq> B ==> B \\<subseteq> C ==> A \\<subseteq> C\"\n  by (fact order_trans)\n\nlemma set_rev_mp: \"x:A ==> A \\<subseteq> B ==> x:B\"\n  by (rule subsetD)\n\nlemma set_mp: \"A \\<subseteq> B ==> x:A ==> x:B\"\n  by (rule subsetD)\n\nlemma subset_not_subset_eq [code]:\n  \"A \\<subset> B \\<longleftrightarrow> A \\<subseteq> B \\<and> \\<not> B \\<subseteq> A\"\n  by (fact less_le_not_le)\n\nlemma eq_mem_trans: \"a=b ==> b \\<in> A ==> a \\<in> A\"\n  by simp\n\nlemmas basic_trans_rules [trans] =\n  order_trans_rules set_rev_mp set_mp eq_mem_trans\n\n\nsubsubsection {* Equality *}\n\nlemma subset_antisym [intro!]: \"A \\<subseteq> B ==> B \\<subseteq> A ==> A = B\"\n  -- {* Anti-symmetry of the subset relation. *}\n  by (iprover intro: set_eqI subsetD)\n\ntext {*\n  \\medskip Equality rules from ZF set theory -- are they appropriate\n  here?\n*}\n\nlemma equalityD1: \"A = B ==> A \\<subseteq> B\"\n  by simp\n\nlemma equalityD2: \"A = B ==> B \\<subseteq> A\"\n  by simp\n\ntext {*\n  \\medskip Be careful when adding this to the claset as @{text\n  subset_empty} is in the simpset: @{prop \"A = {}\"} goes to @{prop \"{}\n  \\<subseteq> A\"} and @{prop \"A \\<subseteq> {}\"} and then back to @{prop \"A = {}\"}!\n*}\n\nlemma equalityE: \"A = B ==> (A \\<subseteq> B ==> B \\<subseteq> A ==> P) ==> P\"\n  by simp\n\nlemma equalityCE [elim]:\n    \"A = B ==> (c \\<in> A ==> c \\<in> B ==> P) ==> (c \\<notin> A ==> c \\<notin> B ==> P) ==> P\"\n  by blast\n\nlemma eqset_imp_iff: \"A = B ==> (x : A) = (x : B)\"\n  by simp\n\nlemma eqelem_imp_iff: \"x = y ==> (x : A) = (y : A)\"\n  by simp\n\n\nsubsubsection {* The empty set *}\n\nlemma empty_def:\n  \"{} = {x. False}\"\n  by (simp add: bot_set_def bot_fun_def)\n\nlemma empty_iff [simp]: \"(c : {}) = False\"\n  by (simp add: empty_def)\n\nlemma emptyE [elim!]: \"a : {} ==> P\"\n  by simp\n\nlemma empty_subsetI [iff]: \"{} \\<subseteq> A\"\n    -- {* One effect is to delete the ASSUMPTION @{prop \"{} <= A\"} *}\n  by blast\n\nlemma equals0I: \"(!!y. y \\<in> A ==> False) ==> A = {}\"\n  by blast\n\nlemma equals0D: \"A = {} ==> a \\<notin> A\"\n    -- {* Use for reasoning about disjointness: @{text \"A Int B = {}\"} *}\n  by blast\n\nlemma ball_empty [simp]: \"Ball {} P = True\"\n  by (simp add: Ball_def)\n\nlemma bex_empty [simp]: \"Bex {} P = False\"\n  by (simp add: Bex_def)\n\n\nsubsubsection {* The universal set -- UNIV *}\n\nabbreviation UNIV :: \"'a set\" where\n  \"UNIV \\<equiv> top\"\n\nlemma UNIV_def:\n  \"UNIV = {x. True}\"\n  by (simp add: top_set_def top_fun_def)\n\nlemma UNIV_I [simp]: \"x : UNIV\"\n  by (simp add: UNIV_def)\n\ndeclare UNIV_I [intro]  -- {* unsafe makes it less likely to cause problems *}\n\nlemma UNIV_witness [intro?]: \"EX x. x : UNIV\"\n  by simp\n\nlemma subset_UNIV: \"A \\<subseteq> UNIV\"\n  by (fact top_greatest) (* already simp *)\n\ntext {*\n  \\medskip Eta-contracting these two rules (to remove @{text P})\n  causes them to be ignored because of their interaction with\n  congruence rules.\n*}\n\nlemma ball_UNIV [simp]: \"Ball UNIV P = All P\"\n  by (simp add: Ball_def)\n\nlemma bex_UNIV [simp]: \"Bex UNIV P = Ex P\"\n  by (simp add: Bex_def)\n\nlemma UNIV_eq_I: \"(\\<And>x. x \\<in> A) \\<Longrightarrow> UNIV = A\"\n  by auto\n\nlemma UNIV_not_empty [iff]: \"UNIV ~= {}\"\n  by (blast elim: equalityE)\n\nlemma empty_not_UNIV[simp]: \"{} \\<noteq> UNIV\"\nby blast\n\n\nsubsubsection {* The Powerset operator -- Pow *}\n\ndefinition Pow :: \"'a set => 'a set set\" where\n  Pow_def: \"Pow A = {B. B \\<le> A}\"\n\nlemma Pow_iff [iff]: \"(A \\<in> Pow B) = (A \\<subseteq> B)\"\n  by (simp add: Pow_def)\n\nlemma PowI: \"A \\<subseteq> B ==> A \\<in> Pow B\"\n  by (simp add: Pow_def)\n\nlemma PowD: \"A \\<in> Pow B ==> A \\<subseteq> B\"\n  by (simp add: Pow_def)\n\nlemma Pow_bottom: \"{} \\<in> Pow B\"\n  by simp\n\nlemma Pow_top: \"A \\<in> Pow A\"\n  by simp\n\nlemma Pow_not_empty: \"Pow A \\<noteq> {}\"\n  using Pow_top by blast\n\n\nsubsubsection {* Set complement *}\n\nlemma Compl_iff [simp]: \"(c \\<in> -A) = (c \\<notin> A)\"\n  by (simp add: fun_Compl_def uminus_set_def)\n\nlemma ComplI [intro!]: \"(c \\<in> A ==> False) ==> c \\<in> -A\"\n  by (simp add: fun_Compl_def uminus_set_def) blast\n\ntext {*\n  \\medskip This form, with negated conclusion, works well with the\n  Classical prover.  Negated assumptions behave like formulae on the\n  right side of the notional turnstile ... *}\n\nlemma ComplD [dest!]: \"c : -A ==> c~:A\"\n  by simp\n\nlemmas ComplE = ComplD [elim_format]\n\nlemma Compl_eq: \"- A = {x. ~ x : A}\"\n  by blast\n\n\nsubsubsection {* Binary intersection *}\n\nabbreviation inter :: \"'a set \\<Rightarrow> 'a set \\<Rightarrow> 'a set\" (infixl \"Int\" 70) where\n  \"op Int \\<equiv> inf\"\n\nnotation (xsymbols)\n  inter  (infixl \"\\<inter>\" 70)\n\nnotation (HTML output)\n  inter  (infixl \"\\<inter>\" 70)\n\nlemma Int_def:\n  \"A \\<inter> B = {x. x \\<in> A \\<and> x \\<in> B}\"\n  by (simp add: inf_set_def inf_fun_def)\n\nlemma Int_iff [simp]: \"(c : A Int B) = (c:A & c:B)\"\n  by (unfold Int_def) blast\n\nlemma IntI [intro!]: \"c:A ==> c:B ==> c : A Int B\"\n  by simp\n\nlemma IntD1: \"c : A Int B ==> c:A\"\n  by simp\n\nlemma IntD2: \"c : A Int B ==> c:B\"\n  by simp\n\nlemma IntE [elim!]: \"c : A Int B ==> (c:A ==> c:B ==> P) ==> P\"\n  by simp\n\nlemma mono_Int: \"mono f \\<Longrightarrow> f (A \\<inter> B) \\<subseteq> f A \\<inter> f B\"\n  by (fact mono_inf)\n\n\nsubsubsection {* Binary union *}\n\nabbreviation union :: \"'a set \\<Rightarrow> 'a set \\<Rightarrow> 'a set\" (infixl \"Un\" 65) where\n  \"union \\<equiv> sup\"\n\nnotation (xsymbols)\n  union  (infixl \"\\<union>\" 65)\n\nnotation (HTML output)\n  union  (infixl \"\\<union>\" 65)\n\nlemma Un_def:\n  \"A \\<union> B = {x. x \\<in> A \\<or> x \\<in> B}\"\n  by (simp add: sup_set_def sup_fun_def)\n\nlemma Un_iff [simp]: \"(c : A Un B) = (c:A | c:B)\"\n  by (unfold Un_def) blast\n\nlemma UnI1 [elim?]: \"c:A ==> c : A Un B\"\n  by simp\n\nlemma UnI2 [elim?]: \"c:B ==> c : A Un B\"\n  by simp\n\ntext {*\n  \\medskip Classical introduction rule: no commitment to @{prop A} vs\n  @{prop B}.\n*}\n\nlemma UnCI [intro!]: \"(c~:B ==> c:A) ==> c : A Un B\"\n  by auto\n\nlemma UnE [elim!]: \"c : A Un B ==> (c:A ==> P) ==> (c:B ==> P) ==> P\"\n  by (unfold Un_def) blast\n\nlemma insert_def: \"insert a B = {x. x = a} \\<union> B\"\n  by (simp add: insert_compr Un_def)\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 {* Set difference *}\n\nlemma Diff_iff [simp]: \"(c : A - B) = (c:A & c~:B)\"\n  by (simp add: minus_set_def fun_diff_def)\n\nlemma DiffI [intro!]: \"c : A ==> c ~: B ==> c : A - B\"\n  by simp\n\nlemma DiffD1: \"c : A - B ==> c : A\"\n  by simp\n\nlemma DiffD2: \"c : A - B ==> c : B ==> P\"\n  by simp\n\nlemma DiffE [elim!]: \"c : A - B ==> (c:A ==> c~:B ==> P) ==> P\"\n  by simp\n\nlemma set_diff_eq: \"A - B = {x. x : A & ~ x : B}\" by blast\n\nlemma Compl_eq_Diff_UNIV: \"-A = (UNIV - A)\"\nby blast\n\n\nsubsubsection {* Augmenting a set -- @{const insert} *}\n\nlemma insert_iff [simp]: \"(a : insert b A) = (a = b | a:A)\"\n  by (unfold insert_def) blast\n\nlemma insertI1: \"a : insert a B\"\n  by simp\n\nlemma insertI2: \"a : B ==> a : insert b B\"\n  by simp\n\nlemma insertE [elim!]: \"a : insert b A ==> (a = b ==> P) ==> (a:A ==> P) ==> P\"\n  by (unfold insert_def) blast\n\nlemma insertCI [intro!]: \"(a~:B ==> a = b) ==> a: insert b B\"\n  -- {* Classical introduction rule. *}\n  by auto\n\nlemma subset_insert_iff: \"(A \\<subseteq> insert x B) = (if x:A then A - {x} \\<subseteq> B else A \\<subseteq> B)\"\n  by auto\n\nlemma set_insert:\n  assumes \"x \\<in> A\"\n  obtains B where \"A = insert x B\" and \"x \\<notin> B\"\nproof\n  from assms show \"A = insert x (A - {x})\" by blast\nnext\n  show \"x \\<notin> A - {x}\" by blast\nqed\n\nlemma insert_ident: \"x ~: A ==> x ~: B ==> (insert x A = insert x B) = (A = B)\"\nby auto\n\nlemma insert_eq_iff: assumes \"a \\<notin> A\" \"b \\<notin> B\"\nshows \"insert a A = insert b B \\<longleftrightarrow>\n  (if a=b then A=B else \\<exists>C. A = insert b C \\<and> b \\<notin> C \\<and> B = insert a C \\<and> a \\<notin> C)\"\n  (is \"?L \\<longleftrightarrow> ?R\")\nproof\n  assume ?L\n  show ?R\n  proof cases\n    assume \"a=b\" with assms `?L` show ?R by (simp add: insert_ident)\n  next\n    assume \"a\\<noteq>b\"\n    let ?C = \"A - {b}\"\n    have \"A = insert b ?C \\<and> b \\<notin> ?C \\<and> B = insert a ?C \\<and> a \\<notin> ?C\"\n      using assms `?L` `a\\<noteq>b` by auto\n    thus ?R using `a\\<noteq>b` by auto\n  qed\nnext\n  assume ?R thus ?L by (auto split: if_splits)\nqed\n\nsubsubsection {* Singletons, using insert *}\n\nlemma singletonI [intro!]: \"a : {a}\"\n    -- {* Redundant? But unlike @{text insertCI}, it proves the subgoal immediately! *}\n  by (rule insertI1)\n\nlemma singletonD [dest!]: \"b : {a} ==> b = a\"\n  by blast\n\nlemmas singletonE = singletonD [elim_format]\n\nlemma singleton_iff: \"(b : {a}) = (b = a)\"\n  by blast\n\nlemma singleton_inject [dest!]: \"{a} = {b} ==> a = b\"\n  by blast\n\nlemma singleton_insert_inj_eq [iff]:\n     \"({b} = insert a A) = (a = b & A \\<subseteq> {b})\"\n  by blast\n\nlemma singleton_insert_inj_eq' [iff]:\n     \"(insert a A = {b}) = (a = b & A \\<subseteq> {b})\"\n  by blast\n\nlemma subset_singletonD: \"A \\<subseteq> {x} ==> A = {} | A = {x}\"\n  by fast\n\nlemma singleton_conv [simp]: \"{x. x = a} = {a}\"\n  by blast\n\nlemma singleton_conv2 [simp]: \"{x. a = x} = {a}\"\n  by blast\n\nlemma diff_single_insert: \"A - {x} \\<subseteq> B ==> A \\<subseteq> insert x B\"\n  by blast\n\nlemma doubleton_eq_iff: \"({a,b} = {c,d}) = (a=c & b=d | a=d & b=c)\"\n  by (blast elim: equalityE)\n\nlemma Un_singleton_iff:\n  \"(A \\<union> B = {x}) = (A = {} \\<and> B = {x} \\<or> A = {x} \\<and> B = {} \\<or> A = {x} \\<and> B = {x})\"\nby auto\n\nlemma singleton_Un_iff:\n  \"({x} = A \\<union> B) = (A = {} \\<and> B = {x} \\<or> A = {x} \\<and> B = {} \\<or> A = {x} \\<and> B = {x})\"\nby auto\n\n\nsubsubsection {* Image of a set under a function *}\n\ntext {*\n  Frequently @{term b} does not have the syntactic form of @{term \"f x\"}.\n*}\n\ndefinition image :: \"('a \\<Rightarrow> 'b) \\<Rightarrow> 'a set \\<Rightarrow> 'b set\" (infixr \"`\" 90)\nwhere\n  \"f ` A = {y. \\<exists>x\\<in>A. y = f x}\"\n\nlemma image_eqI [simp, intro]:\n  \"b = f x \\<Longrightarrow> x \\<in> A \\<Longrightarrow> b \\<in> f ` A\"\n  by (unfold image_def) blast\n\nlemma imageI:\n  \"x \\<in> A \\<Longrightarrow> f x \\<in> f ` A\"\n  by (rule image_eqI) (rule refl)\n\nlemma rev_image_eqI:\n  \"x \\<in> A \\<Longrightarrow> b = f x \\<Longrightarrow> b \\<in> f ` A\"\n  -- {* This version's more effective when we already have the\n    required @{term x}. *}\n  by (rule image_eqI)\n\nlemma imageE [elim!]:\n  assumes \"b \\<in> (\\<lambda>x. f x) ` A\" -- {* The eta-expansion gives variable-name preservation. *}\n  obtains x where \"b = f x\" and \"x \\<in> A\"\n  using assms by (unfold image_def) blast\n\nlemma Compr_image_eq:\n  \"{x \\<in> f ` A. P x} = f ` {x \\<in> A. P (f x)}\"\n  by auto\n\nlemma image_Un:\n  \"f ` (A \\<union> B) = f ` A \\<union> f ` B\"\n  by blast\n\nlemma image_iff:\n  \"z \\<in> f ` A \\<longleftrightarrow> (\\<exists>x\\<in>A. z = f x)\"\n  by blast\n\nlemma image_subsetI:\n  \"(\\<And>x. x \\<in> A \\<Longrightarrow> f x \\<in> B) \\<Longrightarrow> f ` A \\<subseteq> B\"\n  -- {* Replaces the three steps @{text subsetI}, @{text imageE},\n    @{text hypsubst}, but breaks too many existing proofs. *}\n  by blast\n\nlemma image_subset_iff:\n  \"f ` A \\<subseteq> B \\<longleftrightarrow> (\\<forall>x\\<in>A. f x \\<in> B)\"\n  -- {* This rewrite rule would confuse users if made default. *}\n  by blast\n\nlemma subset_imageE:\n  assumes \"B \\<subseteq> f ` A\"\n  obtains C where \"C \\<subseteq> A\" and \"B = f ` C\"\nproof -\n  from assms have \"B = f ` {a \\<in> A. f a \\<in> B}\" by fast\n  moreover have \"{a \\<in> A. f a \\<in> B} \\<subseteq> A\" by blast\n  ultimately show thesis by (blast intro: that)\nqed\n\nlemma subset_image_iff:\n  \"B \\<subseteq> f ` A \\<longleftrightarrow> (\\<exists>AA\\<subseteq>A. B = f ` AA)\"\n  by (blast elim: subset_imageE)\n\nlemma image_ident [simp]:\n  \"(\\<lambda>x. x) ` Y = Y\"\n  by blast\n\nlemma image_empty [simp]:\n  \"f ` {} = {}\"\n  by blast\n\nlemma image_insert [simp]:\n  \"f ` insert a B = insert (f a) (f ` B)\"\n  by blast\n\nlemma image_constant:\n  \"x \\<in> A \\<Longrightarrow> (\\<lambda>x. c) ` A = {c}\"\n  by auto\n\nlemma image_constant_conv:\n  \"(\\<lambda>x. c) ` A = (if A = {} then {} else {c})\"\n  by auto\n\nlemma image_image:\n  \"f ` (g ` A) = (\\<lambda>x. f (g x)) ` A\"\n  by blast\n\nlemma insert_image [simp]:\n  \"x \\<in> A ==> insert (f x) (f ` A) = f ` A\"\n  by blast\n\nlemma image_is_empty [iff]:\n  \"f ` A = {} \\<longleftrightarrow> A = {}\"\n  by blast\n\nlemma empty_is_image [iff]:\n  \"{} = f ` A \\<longleftrightarrow> A = {}\"\n  by blast\n\nlemma image_Collect:\n  \"f ` {x. P x} = {f x | x. P x}\"\n  -- {* NOT suitable as a default simprule: the RHS isn't simpler than the LHS,\n      with its implicit quantifier and conjunction.  Also image enjoys better\n      equational properties than does the RHS. *}\n  by blast\n\nlemma if_image_distrib [simp]:\n  \"(\\<lambda>x. if P x then f x else g x) ` S\n    = (f ` (S \\<inter> {x. P x})) \\<union> (g ` (S \\<inter> {x. \\<not> P x}))\"\n  by auto\n\nlemma image_cong:\n  \"M = N \\<Longrightarrow> (\\<And>x. x \\<in> N \\<Longrightarrow> f x = g x) \\<Longrightarrow> f ` M = g ` N\"\n  by (simp add: image_def)\n\nlemma image_Int_subset:\n  \"f ` (A \\<inter> B) \\<subseteq> f ` A \\<inter> f ` B\"\n  by blast\n\nlemma image_diff_subset:\n  \"f ` A - f ` B \\<subseteq> f ` (A - B)\"\n  by blast\n\nlemma ball_imageD:\n  assumes \"\\<forall>x\\<in>f ` A. P x\"\n  shows \"\\<forall>x\\<in>A. P (f x)\"\n  using assms by simp\n\nlemma bex_imageD:\n  assumes \"\\<exists>x\\<in>f ` A. P x\"\n  shows \"\\<exists>x\\<in>A. P (f x)\"\n  using assms by auto\n\n\ntext {*\n  \\medskip Range of a function -- just a translation for image!\n*}\n\nabbreviation range :: \"('a \\<Rightarrow> 'b) \\<Rightarrow> 'b set\"\nwhere -- \"of function\"\n  \"range f \\<equiv> f ` UNIV\"\n\nlemma range_eqI:\n  \"b = f x \\<Longrightarrow> b \\<in> range f\"\n  by simp\n\nlemma rangeI:\n  \"f x \\<in> range f\"\n  by simp\n\nlemma rangeE [elim?]:\n  \"b \\<in> range (\\<lambda>x. f x) \\<Longrightarrow> (\\<And>x. b = f x \\<Longrightarrow> P) \\<Longrightarrow> P\"\n  by (rule imageE)\n\nlemma full_SetCompr_eq:\n  \"{u. \\<exists>x. u = f x} = range f\"\n  by auto\n\nlemma range_composition: \n  \"range (\\<lambda>x. f (g x)) = f ` range g\"\n  by auto\n\n\nsubsubsection {* Some rules with @{text \"if\"} *}\n\ntext{* Elimination of @{text\"{x. \\<dots> & x=t & \\<dots>}\"}. *}\n\nlemma Collect_conv_if: \"{x. x=a & P x} = (if P a then {a} else {})\"\n  by auto\n\nlemma Collect_conv_if2: \"{x. a=x & P x} = (if P a then {a} else {})\"\n  by auto\n\ntext {*\n  Rewrite rules for boolean case-splitting: faster than @{text\n  \"split_if [split]\"}.\n*}\n\nlemma split_if_eq1: \"((if Q then x else y) = b) = ((Q --> x = b) & (~ Q --> y = b))\"\n  by (rule split_if)\n\nlemma split_if_eq2: \"(a = (if Q then x else y)) = ((Q --> a = x) & (~ Q --> a = y))\"\n  by (rule split_if)\n\ntext {*\n  Split ifs on either side of the membership relation.  Not for @{text\n  \"[simp]\"} -- can cause goals to blow up!\n*}\n\nlemma split_if_mem1: \"((if Q then x else y) : b) = ((Q --> x : b) & (~ Q --> y : b))\"\n  by (rule split_if)\n\nlemma split_if_mem2: \"(a : (if Q then x else y)) = ((Q --> a : x) & (~ Q --> a : y))\"\n  by (rule split_if [where P=\"%S. a : S\"])\n\nlemmas split_ifs = if_bool_eq_conj split_if_eq1 split_if_eq2 split_if_mem1 split_if_mem2\n\n(*Would like to add these, but the existing code only searches for the\n  outer-level constant, which in this case is just Set.member; we instead need\n  to use term-nets to associate patterns with rules.  Also, if a rule fails to\n  apply, then the formula should be kept.\n  [(\"uminus\", Compl_iff RS iffD1), (\"minus\", [Diff_iff RS iffD1]),\n   (\"Int\", [IntD1,IntD2]),\n   (\"Collect\", [CollectD]), (\"Inter\", [InterD]), (\"INTER\", [INT_D])]\n *)\n\n\nsubsection {* Further operations and lemmas *}\n\nsubsubsection {* The ``proper subset'' relation *}\n\nlemma psubsetI [intro!]: \"A \\<subseteq> B ==> A \\<noteq> B ==> A \\<subset> B\"\n  by (unfold less_le) blast\n\nlemma psubsetE [elim!]:\n    \"[|A \\<subset> B;  [|A \\<subseteq> B; ~ (B\\<subseteq>A)|] ==> R|] ==> R\"\n  by (unfold less_le) blast\n\nlemma psubset_insert_iff:\n  \"(A \\<subset> insert x B) = (if x \\<in> B then A \\<subset> B else if x \\<in> A then A - {x} \\<subset> B else A \\<subseteq> B)\"\n  by (auto simp add: less_le subset_insert_iff)\n\nlemma psubset_eq: \"(A \\<subset> B) = (A \\<subseteq> B & A \\<noteq> B)\"\n  by (simp only: less_le)\n\nlemma psubset_imp_subset: \"A \\<subset> B ==> A \\<subseteq> B\"\n  by (simp add: psubset_eq)\n\nlemma psubset_trans: \"[| A \\<subset> B; B \\<subset> C |] ==> A \\<subset> C\"\napply (unfold less_le)\napply (auto dest: subset_antisym)\ndone\n\nlemma psubsetD: \"[| A \\<subset> B; c \\<in> A |] ==> c \\<in> B\"\napply (unfold less_le)\napply (auto dest: subsetD)\ndone\n\nlemma psubset_subset_trans: \"A \\<subset> B ==> B \\<subseteq> C ==> A \\<subset> C\"\n  by (auto simp add: psubset_eq)\n\nlemma subset_psubset_trans: \"A \\<subseteq> B ==> B \\<subset> C ==> A \\<subset> C\"\n  by (auto simp add: psubset_eq)\n\nlemma psubset_imp_ex_mem: \"A \\<subset> B ==> \\<exists>b. b \\<in> (B - A)\"\n  by (unfold less_le) blast\n\nlemma atomize_ball:\n    \"(!!x. x \\<in> A ==> P x) == Trueprop (\\<forall>x\\<in>A. P x)\"\n  by (simp only: Ball_def atomize_all atomize_imp)\n\nlemmas [symmetric, rulify] = atomize_ball\n  and [symmetric, defn] = atomize_ball\n\nlemma image_Pow_mono:\n  assumes \"f ` A \\<subseteq> B\"\n  shows \"image f ` Pow A \\<subseteq> Pow B\"\n  using assms by blast\n\nlemma image_Pow_surj:\n  assumes \"f ` A = B\"\n  shows \"image f ` Pow A = Pow B\"\n  using assms by (blast elim: subset_imageE)\n\n\nsubsubsection {* Derived rules involving subsets. *}\n\ntext {* @{text insert}. *}\n\nlemma subset_insertI: \"B \\<subseteq> insert a B\"\n  by (rule subsetI) (erule insertI2)\n\nlemma subset_insertI2: \"A \\<subseteq> B \\<Longrightarrow> A \\<subseteq> insert b B\"\n  by blast\n\nlemma subset_insert: \"x \\<notin> A ==> (A \\<subseteq> insert x B) = (A \\<subseteq> B)\"\n  by blast\n\n\ntext {* \\medskip Finite Union -- the least upper bound of two sets. *}\n\nlemma Un_upper1: \"A \\<subseteq> A \\<union> B\"\n  by (fact sup_ge1)\n\nlemma Un_upper2: \"B \\<subseteq> A \\<union> B\"\n  by (fact sup_ge2)\n\nlemma Un_least: \"A \\<subseteq> C ==> B \\<subseteq> C ==> A \\<union> B \\<subseteq> C\"\n  by (fact sup_least)\n\n\ntext {* \\medskip Finite Intersection -- the greatest lower bound of two sets. *}\n\nlemma Int_lower1: \"A \\<inter> B \\<subseteq> A\"\n  by (fact inf_le1)\n\nlemma Int_lower2: \"A \\<inter> B \\<subseteq> B\"\n  by (fact inf_le2)\n\nlemma Int_greatest: \"C \\<subseteq> A ==> C \\<subseteq> B ==> C \\<subseteq> A \\<inter> B\"\n  by (fact inf_greatest)\n\n\ntext {* \\medskip Set difference. *}\n\nlemma Diff_subset: \"A - B \\<subseteq> A\"\n  by blast\n\nlemma Diff_subset_conv: \"(A - B \\<subseteq> C) = (A \\<subseteq> B \\<union> C)\"\nby blast\n\n\nsubsubsection {* Equalities involving union, intersection, inclusion, etc. *}\n\ntext {* @{text \"{}\"}. *}\n\nlemma Collect_const [simp]: \"{s. P} = (if P then UNIV else {})\"\n  -- {* supersedes @{text \"Collect_False_empty\"} *}\n  by auto\n\nlemma subset_empty [simp]: \"(A \\<subseteq> {}) = (A = {})\"\n  by (fact bot_unique)\n\nlemma not_psubset_empty [iff]: \"\\<not> (A < {})\"\n  by (fact not_less_bot) (* FIXME: already simp *)\n\nlemma Collect_empty_eq [simp]: \"(Collect P = {}) = (\\<forall>x. \\<not> P x)\"\nby blast\n\nlemma empty_Collect_eq [simp]: \"({} = Collect P) = (\\<forall>x. \\<not> P x)\"\nby blast\n\nlemma Collect_neg_eq: \"{x. \\<not> P x} = - {x. P x}\"\n  by blast\n\nlemma Collect_disj_eq: \"{x. P x | Q x} = {x. P x} \\<union> {x. Q x}\"\n  by blast\n\nlemma Collect_imp_eq: \"{x. P x --> Q x} = -{x. P x} \\<union> {x. Q x}\"\n  by blast\n\nlemma Collect_conj_eq: \"{x. P x & Q x} = {x. P x} \\<inter> {x. Q x}\"\n  by blast\n\n\ntext {* \\medskip @{text insert}. *}\n\nlemma insert_is_Un: \"insert a A = {a} Un A\"\n  -- {* NOT SUITABLE FOR REWRITING since @{text \"{a} == insert a {}\"} *}\n  by blast\n\nlemma insert_not_empty [simp]: \"insert a A \\<noteq> {}\"\n  by blast\n\nlemmas empty_not_insert = insert_not_empty [symmetric]\ndeclare empty_not_insert [simp]\n\nlemma insert_absorb: \"a \\<in> A ==> insert a A = A\"\n  -- {* @{text \"[simp]\"} causes recursive calls when there are nested inserts *}\n  -- {* with \\emph{quadratic} running time *}\n  by blast\n\nlemma insert_absorb2 [simp]: \"insert x (insert x A) = insert x A\"\n  by blast\n\nlemma insert_commute: \"insert x (insert y A) = insert y (insert x A)\"\n  by blast\n\nlemma insert_subset [simp]: \"(insert x A \\<subseteq> B) = (x \\<in> B & A \\<subseteq> B)\"\n  by blast\n\nlemma mk_disjoint_insert: \"a \\<in> A ==> \\<exists>B. A = insert a B & a \\<notin> B\"\n  -- {* use new @{text B} rather than @{text \"A - {a}\"} to avoid infinite unfolding *}\n  apply (rule_tac x = \"A - {a}\" in exI, blast)\n  done\n\nlemma insert_Collect: \"insert a (Collect P) = {u. u \\<noteq> a --> P u}\"\n  by auto\n\nlemma insert_inter_insert[simp]: \"insert a A \\<inter> insert a B = insert a (A \\<inter> B)\"\n  by blast\n\nlemma insert_disjoint [simp]:\n \"(insert a A \\<inter> B = {}) = (a \\<notin> B \\<and> A \\<inter> B = {})\"\n \"({} = insert a A \\<inter> B) = (a \\<notin> B \\<and> {} = A \\<inter> B)\"\n  by auto\n\nlemma disjoint_insert [simp]:\n \"(B \\<inter> insert a A = {}) = (a \\<notin> B \\<and> B \\<inter> A = {})\"\n \"({} = A \\<inter> insert b B) = (b \\<notin> A \\<and> {} = A \\<inter> B)\"\n  by auto\n\n\ntext {* \\medskip @{text Int} *}\n\nlemma Int_absorb: \"A \\<inter> A = A\"\n  by (fact inf_idem) (* already simp *)\n\nlemma Int_left_absorb: \"A \\<inter> (A \\<inter> B) = A \\<inter> B\"\n  by (fact inf_left_idem)\n\nlemma Int_commute: \"A \\<inter> B = B \\<inter> A\"\n  by (fact inf_commute)\n\nlemma Int_left_commute: \"A \\<inter> (B \\<inter> C) = B \\<inter> (A \\<inter> C)\"\n  by (fact inf_left_commute)\n\nlemma Int_assoc: \"(A \\<inter> B) \\<inter> C = A \\<inter> (B \\<inter> C)\"\n  by (fact inf_assoc)\n\nlemmas Int_ac = Int_assoc Int_left_absorb Int_commute Int_left_commute\n  -- {* Intersection is an AC-operator *}\n\nlemma Int_absorb1: \"B \\<subseteq> A ==> A \\<inter> B = B\"\n  by (fact inf_absorb2)\n\nlemma Int_absorb2: \"A \\<subseteq> B ==> A \\<inter> B = A\"\n  by (fact inf_absorb1)\n\nlemma Int_empty_left: \"{} \\<inter> B = {}\"\n  by (fact inf_bot_left) (* already simp *)\n\nlemma Int_empty_right: \"A \\<inter> {} = {}\"\n  by (fact inf_bot_right) (* already simp *)\n\nlemma disjoint_eq_subset_Compl: \"(A \\<inter> B = {}) = (A \\<subseteq> -B)\"\n  by blast\n\nlemma disjoint_iff_not_equal: \"(A \\<inter> B = {}) = (\\<forall>x\\<in>A. \\<forall>y\\<in>B. x \\<noteq> y)\"\n  by blast\n\nlemma Int_UNIV_left: \"UNIV \\<inter> B = B\"\n  by (fact inf_top_left) (* already simp *)\n\nlemma Int_UNIV_right: \"A \\<inter> UNIV = A\"\n  by (fact inf_top_right) (* already simp *)\n\nlemma Int_Un_distrib: \"A \\<inter> (B \\<union> C) = (A \\<inter> B) \\<union> (A \\<inter> C)\"\n  by (fact inf_sup_distrib1)\n\nlemma Int_Un_distrib2: \"(B \\<union> C) \\<inter> A = (B \\<inter> A) \\<union> (C \\<inter> A)\"\n  by (fact inf_sup_distrib2)\n\nlemma Int_UNIV [simp]: \"(A \\<inter> B = UNIV) = (A = UNIV & B = UNIV)\"\n  by (fact inf_eq_top_iff) (* already simp *)\n\nlemma Int_subset_iff [simp]: \"(C \\<subseteq> A \\<inter> B) = (C \\<subseteq> A & C \\<subseteq> B)\"\n  by (fact le_inf_iff)\n\nlemma Int_Collect: \"(x \\<in> A \\<inter> {x. P x}) = (x \\<in> A & P x)\"\n  by blast\n\n\ntext {* \\medskip @{text Un}. *}\n\nlemma Un_absorb: \"A \\<union> A = A\"\n  by (fact sup_idem) (* already simp *)\n\nlemma Un_left_absorb: \"A \\<union> (A \\<union> B) = A \\<union> B\"\n  by (fact sup_left_idem)\n\nlemma Un_commute: \"A \\<union> B = B \\<union> A\"\n  by (fact sup_commute)\n\nlemma Un_left_commute: \"A \\<union> (B \\<union> C) = B \\<union> (A \\<union> C)\"\n  by (fact sup_left_commute)\n\nlemma Un_assoc: \"(A \\<union> B) \\<union> C = A \\<union> (B \\<union> C)\"\n  by (fact sup_assoc)\n\nlemmas Un_ac = Un_assoc Un_left_absorb Un_commute Un_left_commute\n  -- {* Union is an AC-operator *}\n\nlemma Un_absorb1: \"A \\<subseteq> B ==> A \\<union> B = B\"\n  by (fact sup_absorb2)\n\nlemma Un_absorb2: \"B \\<subseteq> A ==> A \\<union> B = A\"\n  by (fact sup_absorb1)\n\nlemma Un_empty_left: \"{} \\<union> B = B\"\n  by (fact sup_bot_left) (* already simp *)\n\nlemma Un_empty_right: \"A \\<union> {} = A\"\n  by (fact sup_bot_right) (* already simp *)\n\nlemma Un_UNIV_left: \"UNIV \\<union> B = UNIV\"\n  by (fact sup_top_left) (* already simp *)\n\nlemma Un_UNIV_right: \"A \\<union> UNIV = UNIV\"\n  by (fact sup_top_right) (* already simp *)\n\nlemma Un_insert_left [simp]: \"(insert a B) \\<union> C = insert a (B \\<union> C)\"\n  by blast\n\nlemma Un_insert_right [simp]: \"A \\<union> (insert a B) = insert a (A \\<union> B)\"\n  by blast\n\nlemma Int_insert_left:\n    \"(insert a B) Int C = (if a \\<in> C then insert a (B \\<inter> C) else B \\<inter> C)\"\n  by auto\n\nlemma Int_insert_left_if0[simp]:\n    \"a \\<notin> C \\<Longrightarrow> (insert a B) Int C = B \\<inter> C\"\n  by auto\n\nlemma Int_insert_left_if1[simp]:\n    \"a \\<in> C \\<Longrightarrow> (insert a B) Int C = insert a (B Int C)\"\n  by auto\n\nlemma Int_insert_right:\n    \"A \\<inter> (insert a B) = (if a \\<in> A then insert a (A \\<inter> B) else A \\<inter> B)\"\n  by auto\n\nlemma Int_insert_right_if0[simp]:\n    \"a \\<notin> A \\<Longrightarrow> A Int (insert a B) = A Int B\"\n  by auto\n\nlemma Int_insert_right_if1[simp]:\n    \"a \\<in> A \\<Longrightarrow> A Int (insert a B) = insert a (A Int B)\"\n  by auto\n\nlemma Un_Int_distrib: \"A \\<union> (B \\<inter> C) = (A \\<union> B) \\<inter> (A \\<union> C)\"\n  by (fact sup_inf_distrib1)\n\nlemma Un_Int_distrib2: \"(B \\<inter> C) \\<union> A = (B \\<union> A) \\<inter> (C \\<union> A)\"\n  by (fact sup_inf_distrib2)\n\nlemma Un_Int_crazy:\n    \"(A \\<inter> B) \\<union> (B \\<inter> C) \\<union> (C \\<inter> A) = (A \\<union> B) \\<inter> (B \\<union> C) \\<inter> (C \\<union> A)\"\n  by blast\n\nlemma subset_Un_eq: \"(A \\<subseteq> B) = (A \\<union> B = B)\"\n  by (fact le_iff_sup)\n\nlemma Un_empty [iff]: \"(A \\<union> B = {}) = (A = {} & B = {})\"\n  by (fact sup_eq_bot_iff) (* FIXME: already simp *)\n\nlemma Un_subset_iff [simp]: \"(A \\<union> B \\<subseteq> C) = (A \\<subseteq> C & B \\<subseteq> C)\"\n  by (fact le_sup_iff)\n\nlemma Un_Diff_Int: \"(A - B) \\<union> (A \\<inter> B) = A\"\n  by blast\n\nlemma Diff_Int2: \"A \\<inter> C - B \\<inter> C = A \\<inter> C - B\"\n  by blast\n\n\ntext {* \\medskip Set complement *}\n\nlemma Compl_disjoint [simp]: \"A \\<inter> -A = {}\"\n  by (fact inf_compl_bot)\n\nlemma Compl_disjoint2 [simp]: \"-A \\<inter> A = {}\"\n  by (fact compl_inf_bot)\n\nlemma Compl_partition: \"A \\<union> -A = UNIV\"\n  by (fact sup_compl_top)\n\nlemma Compl_partition2: \"-A \\<union> A = UNIV\"\n  by (fact compl_sup_top)\n\nlemma double_complement: \"- (-A) = (A::'a set)\"\n  by (fact double_compl) (* already simp *)\n\nlemma Compl_Un: \"-(A \\<union> B) = (-A) \\<inter> (-B)\"\n  by (fact compl_sup) (* already simp *)\n\nlemma Compl_Int: \"-(A \\<inter> B) = (-A) \\<union> (-B)\"\n  by (fact compl_inf) (* already simp *)\n\nlemma subset_Compl_self_eq: \"(A \\<subseteq> -A) = (A = {})\"\n  by blast\n\nlemma Un_Int_assoc_eq: \"((A \\<inter> B) \\<union> C = A \\<inter> (B \\<union> C)) = (C \\<subseteq> A)\"\n  -- {* Halmos, Naive Set Theory, page 16. *}\n  by blast\n\nlemma Compl_UNIV_eq: \"-UNIV = {}\"\n  by (fact compl_top_eq) (* already simp *)\n\nlemma Compl_empty_eq: \"-{} = UNIV\"\n  by (fact compl_bot_eq) (* already simp *)\n\nlemma Compl_subset_Compl_iff [iff]: \"(-A \\<subseteq> -B) = (B \\<subseteq> A)\"\n  by (fact compl_le_compl_iff) (* FIXME: already simp *)\n\nlemma Compl_eq_Compl_iff [iff]: \"(-A = -B) = (A = (B::'a set))\"\n  by (fact compl_eq_compl_iff) (* FIXME: already simp *)\n\nlemma Compl_insert: \"- insert x A = (-A) - {x}\"\n  by blast\n\ntext {* \\medskip Bounded quantifiers.\n\n  The following are not added to the default simpset because\n  (a) they duplicate the body and (b) there are no similar rules for @{text Int}. *}\n\nlemma ball_Un: \"(\\<forall>x \\<in> A \\<union> B. P x) = ((\\<forall>x\\<in>A. P x) & (\\<forall>x\\<in>B. P x))\"\n  by blast\n\nlemma bex_Un: \"(\\<exists>x \\<in> A \\<union> B. P x) = ((\\<exists>x\\<in>A. P x) | (\\<exists>x\\<in>B. P x))\"\n  by blast\n\n\ntext {* \\medskip Set difference. *}\n\nlemma Diff_eq: \"A - B = A \\<inter> (-B)\"\n  by blast\n\nlemma Diff_eq_empty_iff [simp]: \"(A - B = {}) = (A \\<subseteq> B)\"\n  by blast\n\nlemma Diff_cancel [simp]: \"A - A = {}\"\n  by blast\n\nlemma Diff_idemp [simp]: \"(A - B) - B = A - (B::'a set)\"\nby blast\n\nlemma Diff_triv: \"A \\<inter> B = {} ==> A - B = A\"\n  by (blast elim: equalityE)\n\nlemma empty_Diff [simp]: \"{} - A = {}\"\n  by blast\n\nlemma Diff_empty [simp]: \"A - {} = A\"\n  by blast\n\nlemma Diff_UNIV [simp]: \"A - UNIV = {}\"\n  by blast\n\nlemma Diff_insert0 [simp]: \"x \\<notin> A ==> A - insert x B = A - B\"\n  by blast\n\nlemma Diff_insert: \"A - insert a B = A - B - {a}\"\n  -- {* NOT SUITABLE FOR REWRITING since @{text \"{a} == insert a 0\"} *}\n  by blast\n\nlemma Diff_insert2: \"A - insert a B = A - {a} - B\"\n  -- {* NOT SUITABLE FOR REWRITING since @{text \"{a} == insert a 0\"} *}\n  by blast\n\nlemma insert_Diff_if: \"insert x A - B = (if x \\<in> B then A - B else insert x (A - B))\"\n  by auto\n\nlemma insert_Diff1 [simp]: \"x \\<in> B ==> insert x A - B = A - B\"\n  by blast\n\nlemma insert_Diff_single[simp]: \"insert a (A - {a}) = insert a A\"\nby blast\n\nlemma insert_Diff: \"a \\<in> A ==> insert a (A - {a}) = A\"\n  by blast\n\nlemma Diff_insert_absorb: \"x \\<notin> A ==> (insert x A) - {x} = A\"\n  by auto\n\nlemma Diff_disjoint [simp]: \"A \\<inter> (B - A) = {}\"\n  by blast\n\nlemma Diff_partition: \"A \\<subseteq> B ==> A \\<union> (B - A) = B\"\n  by blast\n\nlemma double_diff: \"A \\<subseteq> B ==> B \\<subseteq> C ==> B - (C - A) = A\"\n  by blast\n\nlemma Un_Diff_cancel [simp]: \"A \\<union> (B - A) = A \\<union> B\"\n  by blast\n\nlemma Un_Diff_cancel2 [simp]: \"(B - A) \\<union> A = B \\<union> A\"\n  by blast\n\nlemma Diff_Un: \"A - (B \\<union> C) = (A - B) \\<inter> (A - C)\"\n  by blast\n\nlemma Diff_Int: \"A - (B \\<inter> C) = (A - B) \\<union> (A - C)\"\n  by blast\n\nlemma Un_Diff: \"(A \\<union> B) - C = (A - C) \\<union> (B - C)\"\n  by blast\n\nlemma Int_Diff: \"(A \\<inter> B) - C = A \\<inter> (B - C)\"\n  by blast\n\nlemma Diff_Int_distrib: \"C \\<inter> (A - B) = (C \\<inter> A) - (C \\<inter> B)\"\n  by blast\n\nlemma Diff_Int_distrib2: \"(A - B) \\<inter> C = (A \\<inter> C) - (B \\<inter> C)\"\n  by blast\n\nlemma Diff_Compl [simp]: \"A - (- B) = A \\<inter> B\"\n  by auto\n\nlemma Compl_Diff_eq [simp]: \"- (A - B) = -A \\<union> B\"\n  by blast\n\n\ntext {* \\medskip Quantification over type @{typ bool}. *}\n\nlemma bool_induct: \"P True \\<Longrightarrow> P False \\<Longrightarrow> P x\"\n  by (cases x) auto\n\nlemma all_bool_eq: \"(\\<forall>b. P b) \\<longleftrightarrow> P True \\<and> P False\"\n  by (auto intro: bool_induct)\n\nlemma bool_contrapos: \"P x \\<Longrightarrow> \\<not> P False \\<Longrightarrow> P True\"\n  by (cases x) auto\n\nlemma ex_bool_eq: \"(\\<exists>b. P b) \\<longleftrightarrow> P True \\<or> P False\"\n  by (auto intro: bool_contrapos)\n\nlemma UNIV_bool: \"UNIV = {False, True}\"\n  by (auto intro: bool_induct)\n\ntext {* \\medskip @{text Pow} *}\n\nlemma Pow_empty [simp]: \"Pow {} = {{}}\"\n  by (auto simp add: Pow_def)\n\nlemma Pow_insert: \"Pow (insert a A) = Pow A \\<union> (insert a ` Pow A)\"\n  by (blast intro: image_eqI [where ?x = \"u - {a}\" for u])\n\nlemma Pow_Compl: \"Pow (- A) = {-B | B. A \\<in> Pow B}\"\n  by (blast intro: exI [where ?x = \"- u\" for u])\n\nlemma Pow_UNIV [simp]: \"Pow UNIV = UNIV\"\n  by blast\n\nlemma Un_Pow_subset: \"Pow A \\<union> Pow B \\<subseteq> Pow (A \\<union> B)\"\n  by blast\n\nlemma Pow_Int_eq [simp]: \"Pow (A \\<inter> B) = Pow A \\<inter> Pow B\"\n  by blast\n\n\ntext {* \\medskip Miscellany. *}\n\nlemma set_eq_subset: \"(A = B) = (A \\<subseteq> B & B \\<subseteq> A)\"\n  by blast\n\nlemma subset_iff: \"(A \\<subseteq> B) = (\\<forall>t. t \\<in> A --> t \\<in> B)\"\n  by blast\n\nlemma subset_iff_psubset_eq: \"(A \\<subseteq> B) = ((A \\<subset> B) | (A = B))\"\n  by (unfold less_le) blast\n\nlemma all_not_in_conv [simp]: \"(\\<forall>x. x \\<notin> A) = (A = {})\"\n  by blast\n\nlemma ex_in_conv: \"(\\<exists>x. x \\<in> A) = (A \\<noteq> {})\"\n  by blast\n\nlemma ball_simps [simp, no_atp]:\n  \"\\<And>A P Q. (\\<forall>x\\<in>A. P x \\<or> Q) \\<longleftrightarrow> ((\\<forall>x\\<in>A. P x) \\<or> Q)\"\n  \"\\<And>A P Q. (\\<forall>x\\<in>A. P \\<or> Q x) \\<longleftrightarrow> (P \\<or> (\\<forall>x\\<in>A. Q x))\"\n  \"\\<And>A P Q. (\\<forall>x\\<in>A. P \\<longrightarrow> Q x) \\<longleftrightarrow> (P \\<longrightarrow> (\\<forall>x\\<in>A. Q x))\"\n  \"\\<And>A P Q. (\\<forall>x\\<in>A. P x \\<longrightarrow> Q) \\<longleftrightarrow> ((\\<exists>x\\<in>A. P x) \\<longrightarrow> Q)\"\n  \"\\<And>P. (\\<forall>x\\<in>{}. P x) \\<longleftrightarrow> True\"\n  \"\\<And>P. (\\<forall>x\\<in>UNIV. P x) \\<longleftrightarrow> (\\<forall>x. P x)\"\n  \"\\<And>a B P. (\\<forall>x\\<in>insert a B. P x) \\<longleftrightarrow> (P a \\<and> (\\<forall>x\\<in>B. P x))\"\n  \"\\<And>P Q. (\\<forall>x\\<in>Collect Q. P x) \\<longleftrightarrow> (\\<forall>x. Q x \\<longrightarrow> P x)\"\n  \"\\<And>A P f. (\\<forall>x\\<in>f`A. P x) \\<longleftrightarrow> (\\<forall>x\\<in>A. P (f x))\"\n  \"\\<And>A P. (\\<not> (\\<forall>x\\<in>A. P x)) \\<longleftrightarrow> (\\<exists>x\\<in>A. \\<not> P x)\"\n  by auto\n\nlemma bex_simps [simp, no_atp]:\n  \"\\<And>A P Q. (\\<exists>x\\<in>A. P x \\<and> Q) \\<longleftrightarrow> ((\\<exists>x\\<in>A. P x) \\<and> Q)\"\n  \"\\<And>A P Q. (\\<exists>x\\<in>A. P \\<and> Q x) \\<longleftrightarrow> (P \\<and> (\\<exists>x\\<in>A. Q x))\"\n  \"\\<And>P. (\\<exists>x\\<in>{}. P x) \\<longleftrightarrow> False\"\n  \"\\<And>P. (\\<exists>x\\<in>UNIV. P x) \\<longleftrightarrow> (\\<exists>x. P x)\"\n  \"\\<And>a B P. (\\<exists>x\\<in>insert a B. P x) \\<longleftrightarrow> (P a | (\\<exists>x\\<in>B. P x))\"\n  \"\\<And>P Q. (\\<exists>x\\<in>Collect Q. P x) \\<longleftrightarrow> (\\<exists>x. Q x \\<and> P x)\"\n  \"\\<And>A P f. (\\<exists>x\\<in>f`A. P x) \\<longleftrightarrow> (\\<exists>x\\<in>A. P (f x))\"\n  \"\\<And>A P. (\\<not>(\\<exists>x\\<in>A. P x)) \\<longleftrightarrow> (\\<forall>x\\<in>A. \\<not> P x)\"\n  by auto\n\n\nsubsubsection {* Monotonicity of various operations *}\n\nlemma image_mono: \"A \\<subseteq> B ==> f`A \\<subseteq> f`B\"\n  by blast\n\nlemma Pow_mono: \"A \\<subseteq> B ==> Pow A \\<subseteq> Pow B\"\n  by blast\n\nlemma insert_mono: \"C \\<subseteq> D ==> insert a C \\<subseteq> insert a D\"\n  by blast\n\nlemma Un_mono: \"A \\<subseteq> C ==> B \\<subseteq> D ==> A \\<union> B \\<subseteq> C \\<union> D\"\n  by (fact sup_mono)\n\nlemma Int_mono: \"A \\<subseteq> C ==> B \\<subseteq> D ==> A \\<inter> B \\<subseteq> C \\<inter> D\"\n  by (fact inf_mono)\n\nlemma Diff_mono: \"A \\<subseteq> C ==> D \\<subseteq> B ==> A - B \\<subseteq> C - D\"\n  by blast\n\nlemma Compl_anti_mono: \"A \\<subseteq> B ==> -B \\<subseteq> -A\"\n  by (fact compl_mono)\n\ntext {* \\medskip Monotonicity of implications. *}\n\nlemma in_mono: \"A \\<subseteq> B ==> x \\<in> A --> x \\<in> B\"\n  apply (rule impI)\n  apply (erule subsetD, assumption)\n  done\n\nlemma conj_mono: \"P1 --> Q1 ==> P2 --> Q2 ==> (P1 & P2) --> (Q1 & Q2)\"\n  by iprover\n\nlemma disj_mono: \"P1 --> Q1 ==> P2 --> Q2 ==> (P1 | P2) --> (Q1 | Q2)\"\n  by iprover\n\nlemma imp_mono: \"Q1 --> P1 ==> P2 --> Q2 ==> (P1 --> P2) --> (Q1 --> Q2)\"\n  by iprover\n\nlemma imp_refl: \"P --> P\" ..\n\nlemma not_mono: \"Q --> P ==> ~ P --> ~ Q\"\n  by iprover\n\nlemma ex_mono: \"(!!x. P x --> Q x) ==> (EX x. P x) --> (EX x. Q x)\"\n  by iprover\n\nlemma all_mono: \"(!!x. P x --> Q x) ==> (ALL x. P x) --> (ALL x. Q x)\"\n  by iprover\n\nlemma Collect_mono: \"(!!x. P x --> Q x) ==> Collect P \\<subseteq> Collect Q\"\n  by blast\n\nlemma Int_Collect_mono:\n    \"A \\<subseteq> B ==> (!!x. x \\<in> A ==> P x --> Q x) ==> A \\<inter> Collect P \\<subseteq> B \\<inter> Collect Q\"\n  by blast\n\nlemmas basic_monos =\n  subset_refl imp_refl disj_mono conj_mono\n  ex_mono Collect_mono in_mono\n\nlemma eq_to_mono: \"a = b ==> c = d ==> b --> d ==> a --> c\"\n  by iprover\n\n\nsubsubsection {* Inverse image of a function *}\n\ndefinition vimage :: \"('a => 'b) => 'b set => 'a set\" (infixr \"-`\" 90) where\n  \"f -` B == {x. f x : B}\"\n\nlemma vimage_eq [simp]: \"(a : f -` B) = (f a : B)\"\n  by (unfold vimage_def) blast\n\nlemma vimage_singleton_eq: \"(a : f -` {b}) = (f a = b)\"\n  by simp\n\nlemma vimageI [intro]: \"f a = b ==> b:B ==> a : f -` B\"\n  by (unfold vimage_def) blast\n\nlemma vimageI2: \"f a : A ==> a : f -` A\"\n  by (unfold vimage_def) fast\n\nlemma vimageE [elim!]: \"a: f -` B ==> (!!x. f a = x ==> x:B ==> P) ==> P\"\n  by (unfold vimage_def) blast\n\nlemma vimageD: \"a : f -` A ==> f a : A\"\n  by (unfold vimage_def) fast\n\nlemma vimage_empty [simp]: \"f -` {} = {}\"\n  by blast\n\nlemma vimage_Compl: \"f -` (-A) = -(f -` A)\"\n  by blast\n\nlemma vimage_Un [simp]: \"f -` (A Un B) = (f -` A) Un (f -` B)\"\n  by blast\n\nlemma vimage_Int [simp]: \"f -` (A Int B) = (f -` A) Int (f -` B)\"\n  by fast\n\nlemma vimage_Collect_eq [simp]: \"f -` Collect P = {y. P (f y)}\"\n  by blast\n\nlemma vimage_Collect: \"(!!x. P (f x) = Q x) ==> f -` (Collect P) = Collect Q\"\n  by blast\n\nlemma vimage_insert: \"f-`(insert a B) = (f-`{a}) Un (f-`B)\"\n  -- {* NOT suitable for rewriting because of the recurrence of @{term \"{a}\"}. *}\n  by blast\n\nlemma vimage_Diff: \"f -` (A - B) = (f -` A) - (f -` B)\"\n  by blast\n\nlemma vimage_UNIV [simp]: \"f -` UNIV = UNIV\"\n  by blast\n\nlemma vimage_mono: \"A \\<subseteq> B ==> f -` A \\<subseteq> f -` B\"\n  -- {* monotonicity *}\n  by blast\n\nlemma vimage_image_eq: \"f -` (f ` A) = {y. EX x:A. f x = f y}\"\nby (blast intro: sym)\n\nlemma image_vimage_subset: \"f ` (f -` A) <= A\"\nby blast\n\nlemma image_vimage_eq [simp]: \"f ` (f -` A) = A Int range f\"\nby blast\n\nlemma image_subset_iff_subset_vimage: \"f ` A \\<subseteq> B \\<longleftrightarrow> A \\<subseteq> f -` B\"\n  by blast \n\nlemma vimage_const [simp]: \"((\\<lambda>x. c) -` A) = (if c \\<in> A then UNIV else {})\"\n  by auto\n\nlemma vimage_if [simp]: \"((\\<lambda>x. if x \\<in> B then c else d) -` A) =\n   (if c \\<in> A then (if d \\<in> A then UNIV else B)\n    else if d \\<in> A then -B else {})\"\n  by (auto simp add: vimage_def)\n\nlemma vimage_inter_cong:\n  \"(\\<And> w. w \\<in> S \\<Longrightarrow> f w = g w) \\<Longrightarrow> f -` y \\<inter> S = g -` y \\<inter> S\"\n  by auto\n\nlemma vimage_ident [simp]: \"(%x. x) -` Y = Y\"\n  by blast\n\n\nsubsubsection {* Getting the Contents of a Singleton Set *}\n\ndefinition the_elem :: \"'a set \\<Rightarrow> 'a\" where\n  \"the_elem X = (THE x. X = {x})\"\n\nlemma the_elem_eq [simp]: \"the_elem {x} = x\"\n  by (simp add: the_elem_def)\n\nlemma the_elem_image_unique:\n  assumes \"A \\<noteq> {}\"\n  assumes *: \"\\<And>y. y \\<in> A \\<Longrightarrow> f y = f x\"\n  shows \"the_elem (f ` A) = f x\"\nunfolding the_elem_def proof (rule the1_equality)\n  from `A \\<noteq> {}` obtain y where \"y \\<in> A\" by auto\n  with * have \"f x = f y\" by simp\n  with `y \\<in> A` have \"f x \\<in> f ` A\" by blast\n  with * show \"f ` A = {f x}\" by auto\n  then show \"\\<exists>!x. f ` A = {x}\" by auto\nqed\n\n\nsubsubsection {* Least value operator *}\n\nlemma Least_mono:\n  \"mono (f::'a::order => 'b::order) ==> EX x:S. ALL y:S. x <= y\n    ==> (LEAST y. y : f ` S) = f (LEAST x. x : S)\"\n    -- {* Courtesy of Stephan Merz *}\n  apply clarify\n  apply (erule_tac P = \"%x. x : S\" in LeastI2_order, fast)\n  apply (rule LeastI2_order)\n  apply (auto elim: monoD intro!: order_antisym)\n  done\n\n\nsubsubsection {* Monad operation *}\n\ndefinition bind :: \"'a set \\<Rightarrow> ('a \\<Rightarrow> 'b set) \\<Rightarrow> 'b set\" where\n  \"bind A f = {x. \\<exists>B \\<in> f`A. x \\<in> B}\"\n\nhide_const (open) bind\n\nlemma bind_bind:\n  fixes A :: \"'a set\"\n  shows \"Set.bind (Set.bind A B) C = Set.bind A (\\<lambda>x. Set.bind (B x) C)\"\n  by (auto simp add: bind_def)\n\nlemma empty_bind [simp]:\n  \"Set.bind {} f = {}\"\n  by (simp add: bind_def)\n\nlemma nonempty_bind_const:\n  \"A \\<noteq> {} \\<Longrightarrow> Set.bind A (\\<lambda>_. B) = B\"\n  by (auto simp add: bind_def)\n\nlemma bind_const: \"Set.bind A (\\<lambda>_. B) = (if A = {} then {} else B)\"\n  by (auto simp add: bind_def)\n\n\nsubsubsection {* Operations for execution *}\n\ndefinition is_empty :: \"'a set \\<Rightarrow> bool\" where\n  [code_abbrev]: \"is_empty A \\<longleftrightarrow> A = {}\"\n\nhide_const (open) is_empty\n\ndefinition remove :: \"'a \\<Rightarrow> 'a set \\<Rightarrow> 'a set\" where\n  [code_abbrev]: \"remove x A = A - {x}\"\n\nhide_const (open) remove\n\nlemma member_remove [simp]:\n  \"x \\<in> Set.remove y A \\<longleftrightarrow> x \\<in> A \\<and> x \\<noteq> y\"\n  by (simp add: remove_def)\n\ndefinition filter :: \"('a \\<Rightarrow> bool) \\<Rightarrow> 'a set \\<Rightarrow> 'a set\" where\n  [code_abbrev]: \"filter P A = {a \\<in> A. P a}\"\n\nhide_const (open) filter\n\nlemma member_filter [simp]:\n  \"x \\<in> Set.filter P A \\<longleftrightarrow> x \\<in> A \\<and> P x\"\n  by (simp add: filter_def)\n\ninstantiation set :: (equal) equal\nbegin\n\ndefinition\n  \"HOL.equal A B \\<longleftrightarrow> A \\<subseteq> B \\<and> B \\<subseteq> A\"\n\ninstance proof\nqed (auto simp add: equal_set_def)\n\nend\n\n\ntext {* Misc *}\n\nhide_const (open) member not_member\n\nlemmas equalityI = subset_antisym\n\nML {*\nval Ball_def = @{thm Ball_def}\nval Bex_def = @{thm Bex_def}\nval CollectD = @{thm CollectD}\nval CollectE = @{thm CollectE}\nval CollectI = @{thm CollectI}\nval Collect_conj_eq = @{thm Collect_conj_eq}\nval Collect_mem_eq = @{thm Collect_mem_eq}\nval IntD1 = @{thm IntD1}\nval IntD2 = @{thm IntD2}\nval IntE = @{thm IntE}\nval IntI = @{thm IntI}\nval Int_Collect = @{thm Int_Collect}\nval UNIV_I = @{thm UNIV_I}\nval UNIV_witness = @{thm UNIV_witness}\nval UnE = @{thm UnE}\nval UnI1 = @{thm UnI1}\nval UnI2 = @{thm UnI2}\nval ballE = @{thm ballE}\nval ballI = @{thm ballI}\nval bexCI = @{thm bexCI}\nval bexE = @{thm bexE}\nval bexI = @{thm bexI}\nval bex_triv = @{thm bex_triv}\nval bspec = @{thm bspec}\nval contra_subsetD = @{thm contra_subsetD}\nval equalityCE = @{thm equalityCE}\nval equalityD1 = @{thm equalityD1}\nval equalityD2 = @{thm equalityD2}\nval equalityE = @{thm equalityE}\nval equalityI = @{thm equalityI}\nval imageE = @{thm imageE}\nval imageI = @{thm imageI}\nval image_Un = @{thm image_Un}\nval image_insert = @{thm image_insert}\nval insert_commute = @{thm insert_commute}\nval insert_iff = @{thm insert_iff}\nval mem_Collect_eq = @{thm mem_Collect_eq}\nval rangeE = @{thm rangeE}\nval rangeI = @{thm rangeI}\nval range_eqI = @{thm range_eqI}\nval subsetCE = @{thm subsetCE}\nval subsetD = @{thm subsetD}\nval subsetI = @{thm subsetI}\nval subset_refl = @{thm subset_refl}\nval subset_trans = @{thm subset_trans}\nval vimageD = @{thm vimageD}\nval vimageE = @{thm vimageE}\nval vimageI = @{thm vimageI}\nval vimageI2 = @{thm vimageI2}\nval vimage_Collect = @{thm vimage_Collect}\nval vimage_Int = @{thm vimage_Int}\nval vimage_Un = @{thm vimage_Un}\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/Set.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916205190225, "lm_q2_score": 0.8152324960856177, "lm_q1q2_score": 0.7038649058951291}}
{"text": "(*  Title:      Open Induction\n    Author:     Mizuhito Ogawa\n                Christian Sternagel <c-sterna@jaist.ac.jp>\n    Maintainer: Christian Sternagel\n    License:    LGPL\n*)\n\nheader {* Open Induction *}\n\ntheory Open_Induction\nimports\n  Main\n  \"../Well_Quasi_Orders/Restricted_Predicates\"\nbegin\n\n\nsubsection {* (Greatest) Lower Bounds and Chains *}\n\ntext {*A set @{term B} has the \\emph{lower bound} @{term x} w.r.t.\\ to the order\n@{term_type \"P :: 'a => 'a => bool\"} iff @{term x} is less than or equal to every element\nof @{term B}.*}\ndefinition lb where\n  \"lb P B x \\<equiv> \\<forall>y\\<in>B. P x y\"\n\ntext {*A set @{term B} has the \\emph{greatest lower bound} @{term x} (w.r.t.\\ @{term P})\niff @{term x} is a lower bound \\emph{and} less than or equal to every other lower bound\nof @{term B}.*}\ndefinition glb where\n  \"glb P B x \\<equiv> lb P B x \\<and> (\\<forall>y. lb P B y \\<longrightarrow> P y x)\"\n\ntext {*A subset @{term C} of @{term A} is a \\emph{chain} on @{term A} (w.r.t.\\ @{term P})\niff for all pairs of elements of @{term C}, one is less than or equal to the other one.*}\ndefinition chain_on where\n  \"chain_on P C A \\<equiv> C \\<subseteq> A \\<and> (\\<forall>x\\<in>C. \\<forall>y\\<in>C. P x y \\<or> P y x)\"\n\ntext {*A chain @{term M} on @{term A} (w.r.t.\\ @{term P}) is a \\emph{maximal chain} iff\nthere is no chain on @{term A} that is a superset of @{term M}.*}\ndefinition max_chain_on where\n  \"max_chain_on P M A \\<equiv> chain_on P M A \\<and> (\\<forall>C. chain_on P C A \\<and> M \\<subseteq> C \\<longrightarrow> M = C)\"\n\nlemma chain_onI [Pure.intro!]:\n  \"C \\<subseteq> A \\<Longrightarrow> (\\<And>x y. \\<lbrakk>x \\<in> C; y \\<in> C\\<rbrakk> \\<Longrightarrow> P x y \\<or> P y x) \\<Longrightarrow> chain_on P C A\"\n  unfolding chain_on_def by blast\n\nlemma chain_on_subset:\n  \"A \\<subseteq> B \\<Longrightarrow> chain_on P C A \\<Longrightarrow> chain_on P C B\"\n  unfolding chain_on_def by force\n\nlemma chain_on_imp_subset:\n  \"chain_on P C A \\<Longrightarrow> C \\<subseteq> A\" by (simp add: chain_on_def)\n\nlemma chain_on_Union:\n  assumes \"C \\<in> chains {C. chain_on P C A}\" (is \"C \\<in> chains ?A\")\n  shows \"chain_on P (\\<Union>C) A\"\nproof\n  from assms have \"C \\<subseteq> ?A\" and\n    *[rule_format]: \"\\<forall>x\\<in>C. \\<forall>y\\<in>C. x \\<subseteq> y \\<or> y \\<subseteq> x\"\n    by (auto simp: chains_def chain_subset_def)\n  then show \"\\<Union>C \\<subseteq> A\" unfolding chain_on_def by blast\n  fix x y assume \"x \\<in> \\<Union>C\" and \"y \\<in> \\<Union>C\"\n  then obtain X Y\n    where \"X \\<in> C\" and \"Y \\<in> C\" and \"x \\<in> X\" and \"y \\<in> Y\" by auto\n  with `C \\<subseteq> ?A` have \"X \\<subseteq> A\" and \"Y \\<subseteq> A\"\n    and \"chain_on P X A\" and \"chain_on P Y A\" unfolding chain_on_def by auto\n  with `x \\<in> X` and `y \\<in> Y` show \"P x y \\<or> P y x\"\n    using * [OF `X \\<in> C` `Y \\<in> C`]\n    unfolding chain_on_def by blast\nqed\n\nlemma chain_on_glb:\n  assumes \"qo_on P A\"\n  shows \"chain_on P C A \\<Longrightarrow> C \\<noteq> {} \\<Longrightarrow> glb P C x \\<Longrightarrow> x \\<in> A \\<Longrightarrow> y \\<in> A \\<Longrightarrow> P y x \\<Longrightarrow> chain_on P ({y} \\<union> C) A\"\n  using qo_on_imp_reflp_on [OF assms, unfolded reflp_on_def, rule_format, of y]\n    and qo_on_imp_transp_on [OF assms, unfolded transp_on_def]\n  unfolding chain_on_def glb_def lb_def by blast\n\n\nsubsection {* Open Properties *}\n\ndefinition open_on where\n  \"open_on P Q A \\<equiv>\n    \\<forall>C. chain_on P C A \\<and> C \\<noteq> {} \\<and> (\\<exists>x\\<in>A. glb P C x \\<and> Q x) \\<longrightarrow> (\\<exists>y\\<in>C. Q y)\"\n\nlemma open_on_glb:\n  \"\\<lbrakk>chain_on P C A; C \\<noteq> {}; open_on P Q A; \\<forall>x\\<in>C. \\<not> Q x; x \\<in> A; glb P C x\\<rbrakk> \\<Longrightarrow> \\<not> Q x\"\n  by (auto simp: open_on_def)\n\nlemma max_chain_on_exists:\n  \"\\<exists>M. max_chain_on P M A\"\nproof -\n  let ?S = \"{C. chain_on P C A}\"\n  have \"\\<And>C. C \\<in> chains ?S \\<Longrightarrow> \\<Union>C \\<in> ?S\"\n    using chain_on_Union and chain_on_imp_subset by blast\n  with Zorn_Lemma [of ?S]\n    obtain M where \"M \\<in> ?S\" and *: \"\\<forall>z\\<in>?S. M \\<subseteq> z \\<longrightarrow> z = M\" by blast\n  then have \"M \\<subseteq> A\" and \"chain_on P M A\" by (auto dest: chain_on_imp_subset)\n  moreover {\n    fix C assume \"chain_on P C A\" and \"M \\<subseteq> C\"\n    with * have \"M = C\"\n      using chain_on_imp_subset [OF `chain_on P C A`]\n      by blast }\n  ultimately show \"?thesis\" by (auto simp: max_chain_on_def)\nqed\n\n\nsubsection {* Downward Completeness *}\n\ntext {*An order @{term P} is \\emph{downward-complete} on @{term A} iff every non-empty\nchain on @{term A} has a greatest lower bound in @{term A}.*}\ndefinition dc_on where\n  \"dc_on P A \\<equiv> \\<forall>C. chain_on P C A \\<and> C \\<noteq> {} \\<longrightarrow> (\\<exists>x\\<in>A. glb P C x)\"\n\n\nsubsection {* The Open Induction Schema *}\n\nlemma open_induct_on [consumes 4]:\n  assumes \"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  note refl =\n    qo_on_imp_reflp_on [OF `qo_on P A`, unfolded reflp_on_def, rule_format]\n  assume \"\\<not> Q x\"\n  let ?A = \"{x\\<in>A. \\<not> Q x}\"\n  from max_chain_on_exists [of P ?A] obtain M where\n    chain: \"chain_on P M ?A\" and\n    max: \"\\<And>C. chain_on P C ?A \\<Longrightarrow> M \\<subseteq> C \\<Longrightarrow> M = C\" by (auto simp: max_chain_on_def)\n  from chain have \"M \\<subseteq> ?A\" by (auto simp: chain_on_imp_subset)\n  show False\n  proof (cases \"M = {}\")\n    assume \"M = {}\"\n    moreover have \"chain_on P {x} ?A\"\n      using refl and `x \\<in> A` and `\\<not> Q x` by (simp add: chain_on_def)\n    ultimately show False using max by blast\n  next\n    assume \"M \\<noteq> {}\"\n    have \"?A \\<subseteq> A\" by blast\n    with chain have \"chain_on P M A\"\n      using chain_on_subset by blast\n    moreover with `dc_on P A` and `M \\<noteq> {}` obtain m where\n      \"m \\<in> A\" and \"glb P M m\"\n      unfolding dc_on_def by auto\n    ultimately have \"\\<not> Q m\" and \"m \\<in> ?A\"\n      using open_on_glb [OF _ `M \\<noteq> {}` `open_on P Q A` _ _ `glb P M m`]\n      and `M \\<subseteq> ?A` by auto\n    from ind [OF `m \\<in> A`] and `\\<not> Q m` obtain y where\n      \"y \\<in> A\" and \"strict P y m\" and \"\\<not> Q y\" by blast\n    then have \"P y m\" and \"y \\<in> ?A\" by simp+\n    from qo_on_subset [OF `?A \\<subseteq> A` `qo_on P A`] have \"qo_on P ?A\" .\n    from chain_on_glb [OF this chain, of m y]\n     and `M \\<noteq> {}` and `glb P M m` and `m \\<in> ?A` and `y \\<in> ?A` and `P y m`\n      have \"chain_on P ({y} \\<union> M) ?A\" by blast\n    show False\n    proof (cases \"y \\<in> M\")\n      assume \"y \\<in> M\"\n      with `glb P M m` and `strict P y m`\n        show False by (simp add: glb_def lb_def)\n    next\n      assume \"y \\<notin> M\"\n      with max [OF `chain_on P ({y} \\<union> M) ?A`] show False by blast\n    qed\n  qed\nqed\n\n\nsubsection {* Universal Open Induction Schemas *}\n\ntext {*Open induction on quasi-orders (i.e., @{class preorder}).*}\nlemma (in preorder) dc_open_induct [consumes 2]:\n  assumes \"dc_on (op \\<le>) UNIV\"\n    and \"open_on (op \\<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 (op \\<le>) UNIV\"\n    unfolding qo_on_UNIV_conv\n    unfolding less_le_not_le [symmetric] ..\n  moreover have \"dc_on (op \\<le>) UNIV\" by fact\n  ultimately show \"Q x\"\n    using assms and open_induct_on [of \"op \\<le>\" UNIV Q]\n    unfolding less_le_not_le by blast\nqed\n\n\nsubsection {* Type Class of Downward Complete Orders *}\n\nclass dcorder = preorder +\n  assumes dc: \"\\<lbrakk>chain_on (op \\<le>) C UNIV; C \\<noteq> {}\\<rbrakk> \\<Longrightarrow> (\\<exists>x. glb (op \\<le>) C x)\"\nbegin\n\nlemma dc_on_UNIV: \"dc_on (op \\<le>) UNIV\"\n  using dc unfolding dc_on_def by blast\n\ntext {*Open induction on downward-complete orders.*}\nlemmas open_induct [consumes 1] = dc_open_induct [OF dc_on_UNIV]\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/Open_Induction/Open_Induction.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8633916029436189, "lm_q2_score": 0.8152324938410784, "lm_q1q2_score": 0.7038648896291727}}
{"text": "(*  Title:      HOL/Datatype_Examples/Lambda_Term.thy\n    Author:     Dmitriy Traytel, TU Muenchen\n    Author:     Andrei Popescu, TU Muenchen\n    Copyright   2012\n\nLambda-terms.\n*)\n\nsection \\<open>Lambda-Terms\\<close>\n\ntheory Lambda_Term\nimports \"~~/src/HOL/Library/FSet\"\nbegin\n\nsection \\<open>Datatype definition\\<close>\n\ndatatype 'a trm =\n  Var 'a |\n  App \"'a trm\" \"'a trm\" |\n  Lam 'a \"'a trm\" |\n  Lt \"('a \\<times> 'a trm) fset\" \"'a trm\"\n\n\nsubsection \\<open>Example: The set of all variables varsOf and free variables fvarsOf of a term\\<close>\n\nprimrec varsOf :: \"'a trm \\<Rightarrow> 'a set\" where\n  \"varsOf (Var a) = {a}\"\n| \"varsOf (App f x) = varsOf f \\<union> varsOf x\"\n| \"varsOf (Lam x b) = {x} \\<union> varsOf b\"\n| \"varsOf (Lt F t) = varsOf t \\<union> (\\<Union>{{x} \\<union> X | x X. (x,X) |\\<in>| fimage (map_prod id varsOf) F})\"\n\nprimrec fvarsOf :: \"'a trm \\<Rightarrow> 'a set\" where\n  \"fvarsOf (Var x) = {x}\"\n| \"fvarsOf (App t1 t2) = fvarsOf t1 \\<union> fvarsOf t2\"\n| \"fvarsOf (Lam x t) = fvarsOf t - {x}\"\n| \"fvarsOf (Lt xts t) = fvarsOf t - {x | x X. (x,X) |\\<in>| fimage (map_prod id varsOf) xts} \\<union>\n    (\\<Union>{X | x X. (x,X) |\\<in>| fimage (map_prod id varsOf) xts})\"\n\nlemma diff_Un_incl_triv: \"\\<lbrakk>A \\<subseteq> D; C \\<subseteq> E\\<rbrakk> \\<Longrightarrow> A - B \\<union> C \\<subseteq> D \\<union> E\" by blast\n\nlemma in_fimage_map_prod_fset_iff[simp]:\n  \"(x, y) |\\<in>| fimage (map_prod f g) xts \\<longleftrightarrow> (\\<exists> t1 t2. (t1, t2) |\\<in>| xts \\<and> x = f t1 \\<and> y = g t2)\"\n  by force\n\nlemma fvarsOf_varsOf: \"fvarsOf t \\<subseteq> varsOf t\"\nproof induct\n  case (Lt xts t) thus ?case unfolding fvarsOf.simps varsOf.simps by (elim diff_Un_incl_triv) auto\nqed auto\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/Datatype_Examples/Lambda_Term.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8633916099737806, "lm_q2_score": 0.8152324871074608, "lm_q1q2_score": 0.70386488954664}}
{"text": "header {* Deciding Regular Expression Equivalence *}\n\ntheory Equivalence_Checking\nimports\n  NDerivative\n  \"~~/src/HOL/Library/While_Combinator\"\nbegin\n\n\nsubsection {* Bisimulation between languages and regular expressions *}\n\ncoinductive bisimilar :: \"'a lang \\<Rightarrow> 'a lang \\<Rightarrow> bool\" where\n\"([] \\<in> K \\<longleftrightarrow> [] \\<in> L) \n \\<Longrightarrow> (\\<And>x. bisimilar (Deriv x K) (Deriv x L))\n \\<Longrightarrow> bisimilar K L\"\n\nlemma equal_if_bisimilar:\nassumes \"bisimilar K L\" shows \"K = L\"\nproof (rule set_eqI)\n  fix w\n  from `bisimilar K L` show \"w \\<in> K \\<longleftrightarrow> w \\<in> L\"\n  proof (induct w arbitrary: K L)\n    case Nil thus ?case by (auto elim: bisimilar.cases)\n  next\n    case (Cons a w K L)\n    from `bisimilar K L` have \"bisimilar (Deriv a K) (Deriv a L)\"\n      by (auto elim: bisimilar.cases)\n    then have \"w \\<in> Deriv a K \\<longleftrightarrow> w \\<in> Deriv a L\" by (rule Cons(1))\n    thus ?case by (auto simp: Deriv_def)\n  qed\nqed\n\nlemma language_coinduct:\nfixes R (infixl \"\\<sim>\" 50)\nassumes \"K \\<sim> L\"\nassumes \"\\<And>K L. K \\<sim> L \\<Longrightarrow> ([] \\<in> K \\<longleftrightarrow> [] \\<in> L)\"\nassumes \"\\<And>K L x. K \\<sim> L \\<Longrightarrow> Deriv x K \\<sim> Deriv x L\"\nshows \"K = L\"\napply (rule equal_if_bisimilar)\napply (rule bisimilar.coinduct[of R, OF `K \\<sim> L`])\napply (auto simp: assms)\ndone\n\ntype_synonym 'a rexp_pair = \"'a rexp * 'a rexp\"\ntype_synonym 'a rexp_pairs = \"'a rexp_pair list\"\n\ndefinition is_bisimulation ::  \"'a::order list \\<Rightarrow> 'a rexp_pair set \\<Rightarrow> bool\"\nwhere\n\"is_bisimulation as R =\n  (\\<forall>(r,s)\\<in> R. (atoms r \\<union> atoms s \\<subseteq> set as) \\<and> (nullable r \\<longleftrightarrow> nullable s) \\<and>\n    (\\<forall>a\\<in>set as. (nderiv a r, nderiv a s) \\<in> R))\"\n\nlemma bisim_lang_eq:\nassumes bisim: \"is_bisimulation as ps\"\nassumes \"(r, s) \\<in> ps\"\nshows \"lang r = lang s\"\nproof -\n  def ps' \\<equiv> \"insert (Zero, Zero) ps\"\n  from bisim have bisim': \"is_bisimulation as ps'\"\n    by (auto simp: ps'_def is_bisimulation_def)\n  let ?R = \"\\<lambda>K L. (\\<exists>(r,s)\\<in>ps'. K = lang r \\<and> L = lang s)\"\n  show ?thesis\n  proof (rule language_coinduct[where R=\"?R\"])\n    from `(r, s) \\<in> ps` \n    have \"(r, s) \\<in> ps'\" by (auto simp: ps'_def)\n    thus \"?R (lang r) (lang s)\" by auto\n  next\n    fix K L assume \"?R K L\"\n    then obtain r s where rs: \"(r, s) \\<in> ps'\"\n      and KL: \"K = lang r\" \"L = lang s\" by auto\n    with bisim' have \"nullable r \\<longleftrightarrow> nullable s\"\n      by (auto simp: is_bisimulation_def)\n    thus \"[] \\<in> K \\<longleftrightarrow> [] \\<in> L\" by (auto simp: nullable_iff KL)\n    fix a\n    show \"?R (Deriv a K) (Deriv a L)\"\n    proof cases\n      assume \"a \\<in> set as\"\n      with rs bisim'\n      have \"(nderiv a r, nderiv a s) \\<in> ps'\"\n        by (auto simp: is_bisimulation_def)\n      thus ?thesis by (force simp: KL lang_nderiv)\n    next\n      assume \"a \\<notin> set as\"\n      with bisim' rs\n      have \"a \\<notin> atoms r\" \"a \\<notin> atoms s\" by (auto simp: is_bisimulation_def)\n      then have \"nderiv a r = Zero\" \"nderiv a s = Zero\"\n        by (auto intro: deriv_no_occurrence)\n      then have \"Deriv a K = lang Zero\" \n        \"Deriv a L = lang Zero\" \n        unfolding KL lang_nderiv[symmetric] by auto\n      thus ?thesis by (auto simp: ps'_def)\n    qed\n  qed  \nqed\n\nsubsection {* Closure computation *}\n\ndefinition closure ::\n  \"'a::order list \\<Rightarrow> 'a rexp_pair \\<Rightarrow> ('a rexp_pairs * 'a rexp_pair set) option\"\nwhere\n\"closure as = rtrancl_while (%(r,s). nullable r = nullable s)\n  (%(r,s). map (\\<lambda>a. (nderiv a r, nderiv a s)) as)\"\n\ndefinition pre_bisim :: \"'a::order list \\<Rightarrow> 'a rexp \\<Rightarrow> 'a rexp \\<Rightarrow>\n 'a rexp_pairs * 'a rexp_pair set \\<Rightarrow> bool\"\nwhere\n\"pre_bisim as r s = (\\<lambda>(ws,R).\n (r,s) \\<in> R \\<and> set ws \\<subseteq> R \\<and>\n (\\<forall>(r,s)\\<in> R. atoms r \\<union> atoms s \\<subseteq> set as) \\<and>\n (\\<forall>(r,s)\\<in> R - set ws. (nullable r \\<longleftrightarrow> nullable s) \\<and>\n   (\\<forall>a\\<in>set as. (nderiv a r, nderiv a s) \\<in> R)))\"\n\n\n\nsubsection {* Bisimulation-free proof of closure computation *}\n\ntext{* The equivalence check can be viewed as the product construction\nof two automata. The state space is the reflexive transitive closure of\nthe pair of next-state functions, i.e. derivatives. *}\n\nlemma rtrancl_nderiv_nderivs: defines \"nderivs == foldl (%r a. nderiv a r)\"\nshows \"{((r,s),(nderiv a r,nderiv a s))| r s a. a : A}^* =\n       {((r,s),(nderivs r w,nderivs s w))| r s w. w : lists A}\" (is \"?L = ?R\")\nproof-\n  note [simp] = nderivs_def\n  { fix r s r' s'\n    have \"((r,s),(r',s')) : ?L \\<Longrightarrow> ((r,s),(r',s')) : ?R\"\n    proof(induction rule: converse_rtrancl_induct2)\n      case refl show ?case by (force intro!: foldl.simps(1)[symmetric])\n    next\n      case step thus ?case by(force intro!: foldl.simps(2)[symmetric])\n    qed\n  } moreover\n  { fix r s r' s'\n    { fix w have \"\\<forall>x\\<in>set w. x \\<in> A \\<Longrightarrow> ((r, s), nderivs r w, nderivs s w) :?L\"\n      proof(induction w rule: rev_induct)\n        case Nil show ?case by simp\n      next\n        case snoc thus ?case by (auto elim!: rtrancl_into_rtrancl)\n      qed\n    } \n    hence \"((r,s),(r',s')) : ?R \\<Longrightarrow> ((r,s),(r',s')) : ?L\" by auto\n  } ultimately show ?thesis by (auto simp: in_lists_conv_set) blast\nqed\n\nlemma nullable_nderivs:\n  \"nullable (foldl (%r a. nderiv a r) r w) = (w : lang r)\"\nby (induct w arbitrary: r) (simp_all add: nullable_iff lang_nderiv Deriv_def)\n\ntheorem closure_sound_complete:\nassumes result: \"closure as (r,s) = Some(ws,R)\"\nand atoms: \"set as = atoms r \\<union> atoms s\"\nshows \"ws = [] \\<longleftrightarrow> lang r = lang s\"\nproof -\n  have leq: \"(lang r = lang s) =\n  (\\<forall>(r',s') \\<in> {((r0,s0),(nderiv a r0,nderiv a s0))| r0 s0 a. a : set as}^* `` {(r,s)}.\n    nullable r' = nullable s')\"\n    by(simp add: atoms rtrancl_nderiv_nderivs Ball_def lang_eq_ext imp_ex nullable_nderivs\n         del:Un_iff)\n  have \"{(x,y). y \\<in> set ((\\<lambda>(p,q). map (\\<lambda>a. (nderiv a p, nderiv a q)) as) x)} =\n    {((r,s), nderiv a r, nderiv a s) |r s a. a \\<in> set as}\"\n    by auto\n  with atoms rtrancl_while_Some[OF result[unfolded closure_def]]\n  show ?thesis by (auto simp add: leq Ball_def split: if_splits)\nqed\n\nsubsection {* The overall procedure *}\n\nprimrec add_atoms :: \"'a rexp \\<Rightarrow> 'a list \\<Rightarrow> 'a list\"\nwhere\n  \"add_atoms Zero = id\"\n| \"add_atoms One = id\"\n| \"add_atoms (Atom a) = List.insert a\"\n| \"add_atoms (Plus r s) = add_atoms s o add_atoms r\"\n| \"add_atoms (Times r s) = add_atoms s o add_atoms r\"\n| \"add_atoms (Star r) = add_atoms r\"\n\nlemma set_add_atoms: \"set (add_atoms r as) = atoms r \\<union> set as\"\nby (induct r arbitrary: as) auto\n\n\ndefinition check_eqv :: \"nat rexp \\<Rightarrow> nat rexp \\<Rightarrow> bool\" where\n\"check_eqv r s =\n  (let nr = norm r; ns = norm s; as = add_atoms nr (add_atoms ns [])\n   in case closure as (nr, ns) of\n     Some([],_) \\<Rightarrow> True | _ \\<Rightarrow> False)\"\n\n\n\ntext{* Test: *}\nlemma \"check_eqv (Plus One (Times (Atom 0) (Star(Atom 0)))) (Star(Atom 0))\"\nby eval\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/Equivalence_Checking.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.863391602943619, "lm_q2_score": 0.8152324826183822, "lm_q1q2_score": 0.7038648799395911}}
{"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  theory TIP_prop_53\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 count :: \"Nat => Nat list => Nat\" where\n  \"count y (nil2) = Z\"\n| \"count y (cons2 z2 ys) =\n     (if x y z2 then S (count y ys) else count y ys)\"\n\nfun t2 :: \"Nat => Nat => bool\" where\n  \"t2 (Z) z = True\"\n| \"t2 (S z2) (Z) = False\"\n| \"t2 (S z2) (S x2) = t2 z2 x2\"\n\nfun insort :: \"Nat => Nat list => Nat list\" where\n  \"insort y (nil2) = cons2 y (nil2)\"\n| \"insort y (cons2 z2 xs) =\n     (if t2 y z2 then cons2 y (cons2 z2 xs) else cons2 z2 (insort y xs))\"\n\nfun sort :: \"Nat list => Nat list\" where\n  \"sort (nil2) = nil2\"\n| \"sort (cons2 z xs) = insort z (sort xs)\"\n\ntheorem property0 :\n  \"((count n xs) = (count n (sort 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/Isaplanner/Isaplanner/TIP_prop_53.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513675912913, "lm_q2_score": 0.785308580887758, "lm_q1q2_score": 0.7038338896018294}}
{"text": "theory Height\n  imports \"Lambda\"\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\n\nlemma height_ge_one: \n  shows \"1 \\<le> (height e)\"\nby (induct e rule: lam.induct) \n   (simp_all)\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'\" using height_ge_one by simp\n  then show \"height (Var y[x::=e']) \\<le> height (Var y) - 1 + height e'\" by simp\nnext\n  case (Lam y e1)\n  have ih: \"height (e1[x::=e']) \\<le> height e1 - 1 + height e'\" by fact\n  moreover\n  have vc: \"atom y \\<sharp> x\" \"atom 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  have 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 fact+\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": "goodlyrottenapple", "repo": "LCAT", "sha": "5be6e45068032ce1ccb7405e9a01d76ca914bd93", "save_path": "github-repos/isabelle/goodlyrottenapple-LCAT", "path": "github-repos/isabelle/goodlyrottenapple-LCAT/LCAT-5be6e45068032ce1ccb7405e9a01d76ca914bd93/Nominal2-Isabelle2015/Nominal/Ex/Height.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.896251362048962, "lm_q2_score": 0.785308578375437, "lm_q1q2_score": 0.7038338829977194}}
{"text": "(*  Title:      HOL/Word/Misc_Auxiliary.thy\n    Author:     Jeremy Dawson, NICTA\n*)\n\nsection \\<open>Generic auxiliary\\<close>\n\ntheory Misc_Auxiliary\n  imports Main\nbegin\n\nsubsection \\<open>Arithmetic lemmas\\<close>\n\nlemma int_mod_lem: \"0 < n \\<Longrightarrow> 0 \\<le> b \\<and> b < n \\<longleftrightarrow> b mod n = b\"\n  for b n :: int\n  apply safe\n    apply (erule (1) mod_pos_pos_trivial)\n   apply (erule_tac [!] subst)\n   apply auto\n  done\n\nlemma int_mod_ge: \"a < n \\<Longrightarrow> 0 < n \\<Longrightarrow> a \\<le> a mod n\"\n  for a n :: int\n  by (metis dual_order.trans le_cases mod_pos_pos_trivial pos_mod_conj)\n\nlemma int_mod_ge': \"b < 0 \\<Longrightarrow> 0 < n \\<Longrightarrow> b + n \\<le> b mod n\"\n  for b n :: int\n  by (metis add_less_same_cancel2 int_mod_ge mod_add_self2)\n\nlemma int_mod_le': \"0 \\<le> b - n \\<Longrightarrow> b mod n \\<le> b - n\"\n  for b n :: int\n  by (metis minus_mod_self2 zmod_le_nonneg_dividend)\n\nlemma emep1: \"even n \\<Longrightarrow> even d \\<Longrightarrow> 0 \\<le> d \\<Longrightarrow> (n + 1) mod d = (n mod d) + 1\"\n  for n d :: int\n  by (auto simp add: pos_zmod_mult_2 add.commute dvd_def)\n\nlemma m1mod2k: \"- 1 mod 2 ^ n = (2 ^ n - 1 :: int)\"\n  by (rule zmod_minus1) simp\n\nlemma sub_inc_One: \"Num.sub (Num.inc n) num.One = numeral n\"\n  by (metis add_diff_cancel add_neg_numeral_special(3) add_uminus_conv_diff numeral_inc)\n  \nlemma inc_BitM: \"Num.inc (Num.BitM n) = num.Bit0 n\"\n  by (simp add: BitM_plus_one[symmetric] add_One)\n\n\nsubsection \\<open>Lemmas on list operations\\<close>\n\nlemma butlast_power: \"(butlast ^^ n) bl = take (length bl - n) bl\"\n  by (induct n) (auto simp: butlast_take)\n\nlemma nth_rev: \"n < length xs \\<Longrightarrow> rev xs ! n = xs ! (length xs - 1 - n)\"\n  using rev_nth by simp\n\nlemma nth_rev_alt: \"n < length ys \\<Longrightarrow> ys ! n = rev ys ! (length ys - Suc n)\"\n  by (simp add: nth_rev)\n\nlemma hd_butlast: \"length xs > 1 \\<Longrightarrow> hd (butlast xs) = hd xs\"\n  by (cases xs) auto\n\n\nsubsection \\<open>Implicit augmentation of list prefixes\\<close>\n\nprimrec takefill :: \"'a \\<Rightarrow> nat \\<Rightarrow> 'a list \\<Rightarrow> 'a list\"\nwhere\n    Z: \"takefill fill 0 xs = []\"\n  | Suc: \"takefill fill (Suc n) xs =\n      (case xs of\n        [] \\<Rightarrow> fill # takefill fill n xs\n      | y # ys \\<Rightarrow> y # takefill fill n ys)\"\n\nlemma nth_takefill: \"m < n \\<Longrightarrow> takefill fill n l ! m = (if m < length l then l ! m else fill)\"\n  apply (induct n arbitrary: m l)\n   apply clarsimp\n  apply clarsimp\n  apply (case_tac m)\n   apply (simp split: list.split)\n  apply (simp split: list.split)\n  done\n\nlemma takefill_alt: \"takefill fill n l = take n l @ replicate (n - length l) fill\"\n  by (induct n arbitrary: l) (auto split: list.split)\n\nlemma takefill_replicate [simp]: \"takefill fill n (replicate m fill) = replicate n fill\"\n  by (simp add: takefill_alt replicate_add [symmetric])\n\nlemma takefill_le': \"n = m + k \\<Longrightarrow> takefill x m (takefill x n l) = takefill x m l\"\n  by (induct m arbitrary: l n) (auto split: list.split)\n\nlemma length_takefill [simp]: \"length (takefill fill n l) = n\"\n  by (simp add: takefill_alt)\n\nlemma take_takefill': \"n = k + m \\<Longrightarrow> take k (takefill fill n w) = takefill fill k w\"\n  by (induct k arbitrary: w n) (auto split: list.split)\n\nlemma drop_takefill: \"drop k (takefill fill (m + k) w) = takefill fill m (drop k w)\"\n  by (induct k arbitrary: w) (auto split: list.split)\n\nlemma takefill_le [simp]: \"m \\<le> n \\<Longrightarrow> takefill x m (takefill x n l) = takefill x m l\"\n  by (auto simp: le_iff_add takefill_le')\n\nlemma take_takefill [simp]: \"m \\<le> n \\<Longrightarrow> take m (takefill fill n w) = takefill fill m w\"\n  by (auto simp: le_iff_add take_takefill')\n\nlemma takefill_append: \"takefill fill (m + length xs) (xs @ w) = xs @ (takefill fill m w)\"\n  by (induct xs) auto\n\nlemma takefill_same': \"l = length xs \\<Longrightarrow> takefill fill l xs = xs\"\n  by (induct xs arbitrary: l) auto\n\nlemmas takefill_same [simp] = takefill_same' [OF refl]\n\nlemma tf_rev:\n  \"n + k = m + length bl \\<Longrightarrow> takefill x m (rev (takefill y n bl)) =\n    rev (takefill y m (rev (takefill x k (rev bl))))\"\n  apply (rule nth_equalityI)\n   apply (auto simp add: nth_takefill nth_rev)\n  apply (rule_tac f = \"\\<lambda>n. bl ! n\" in arg_cong)\n  apply arith\n  done\n\nlemma takefill_minus: \"0 < n \\<Longrightarrow> takefill fill (Suc (n - 1)) w = takefill fill n w\"\n  by auto\n\nlemmas takefill_Suc_cases =\n  list.cases [THEN takefill.Suc [THEN trans]]\n\nlemmas takefill_Suc_Nil = takefill_Suc_cases (1)\nlemmas takefill_Suc_Cons = takefill_Suc_cases (2)\n\nlemmas takefill_minus_simps = takefill_Suc_cases [THEN [2]\n  takefill_minus [symmetric, THEN trans]]\n\nlemma takefill_numeral_Nil [simp]:\n  \"takefill fill (numeral k) [] = fill # takefill fill (pred_numeral k) []\"\n  by (simp add: numeral_eq_Suc)\n\nlemma takefill_numeral_Cons [simp]:\n  \"takefill fill (numeral k) (x # xs) = x # takefill fill (pred_numeral k) xs\"\n  by (simp add: numeral_eq_Suc)\n\n\nsubsection \\<open>Auxiliary: Range projection\\<close>\n\ndefinition bl_of_nth :: \"nat \\<Rightarrow> (nat \\<Rightarrow> 'a) \\<Rightarrow> 'a list\"\n  where \"bl_of_nth n f = map f (rev [0..<n])\"\n\nlemma bl_of_nth_simps [simp, code]:\n  \"bl_of_nth 0 f = []\"\n  \"bl_of_nth (Suc n) f = f n # bl_of_nth n f\"\n  by (simp_all add: bl_of_nth_def)\n\nlemma length_bl_of_nth [simp]: \"length (bl_of_nth n f) = n\"\n  by (simp add: bl_of_nth_def)\n\nlemma nth_bl_of_nth [simp]: \"m < n \\<Longrightarrow> rev (bl_of_nth n f) ! m = f m\"\n  by (simp add: bl_of_nth_def rev_map)\n\nlemma bl_of_nth_inj: \"(\\<And>k. k < n \\<Longrightarrow> f k = g k) \\<Longrightarrow> bl_of_nth n f = bl_of_nth n g\"\n  by (simp add: bl_of_nth_def)\n\nlemma bl_of_nth_nth_le: \"n \\<le> length xs \\<Longrightarrow> bl_of_nth n (nth (rev xs)) = drop (length xs - n) xs\"\n  apply (induct n arbitrary: xs)\n   apply clarsimp\n  apply clarsimp\n  apply (rule trans [OF _ hd_Cons_tl])\n   apply (frule Suc_le_lessD)\n   apply (simp add: nth_rev trans [OF drop_Suc drop_tl, symmetric])\n   apply (subst hd_drop_conv_nth)\n    apply force\n   apply simp_all\n  apply (rule_tac f = \"\\<lambda>n. drop n xs\" in arg_cong)\n  apply simp\n  done\n\nlemma bl_of_nth_nth [simp]: \"bl_of_nth (length xs) ((!) (rev xs)) = xs\"\n  by (simp add: bl_of_nth_nth_le)\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/Misc_Auxiliary.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8902942261220294, "lm_q2_score": 0.7905303236047049, "lm_q1q2_score": 0.7038045826796482}}
{"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_27\n  imports \"../../Test_Base\"\nbegin\n\ndatatype 'a list = nil2 | cons2 \"'a\" \"'a list\"\n\ndatatype Nat = Z | S \"Nat\"\n\nfun y :: \"'a list => 'a list => 'a list\" where\n  \"y (nil2) y2 = y2\"\n| \"y (cons2 z2 xs) y2 = cons2 z2 (y xs y2)\"\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 y22) = x x2 y22\"\n\nfun elem :: \"Nat => Nat list => bool\" where\n  \"elem z (nil2) = False\"\n| \"elem z (cons2 z2 xs) = (if x z z2 then True else elem z xs)\"\n\ntheorem property0 :\n  \"((elem z ys) ==> (elem z (y xs ys)))\"(*This problem is very similar to TIP_prop_26.thy*)\n  find_proof DInd\n  apply (induct arbitrary: ys rule: TIP_prop_27.elem.induct)\n   apply auto\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_27.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942144788076, "lm_q2_score": 0.7905303162021596, "lm_q1q2_score": 0.7038045668848851}}
{"text": "header{* Simplification Lemmas for Lattices *}\n\n(*\n    Author: Viorel Preoteasa\n*)\n\ntheory Lattice_Prop\nimports Main\nbegin\n\ntext{*\nThis theory introduces some simplification lemmas\nfor semilattices and lattices\n*}\n\nnotation \n   inf (infixl \"\\<sqinter>\" 70) and\n   sup (infixl \"\\<squnion>\" 65)\n\ncontext semilattice_inf begin\n\n\nlemma [simp]: \"x \\<sqinter> y \\<sqinter> z \\<le> y\"\n  by (rule_tac y = \"x \\<sqinter> y\" in order_trans, rule inf_le1, simp)\n\nlemma [simp]: \"x \\<sqinter> (y \\<sqinter> z) \\<le> y\"\n  by (rule_tac y = \"y \\<sqinter> z\" in order_trans, rule inf_le2, simp)\n\nlemma [simp]: \"x \\<sqinter> (y \\<sqinter> z) \\<le> z\"\n  by (rule_tac y = \"y \\<sqinter> z\" in order_trans, rule inf_le2, simp)\nend\n\ncontext semilattice_sup begin\n\nlemma [simp]: \"x \\<le> x \\<squnion> y \\<squnion> z\"\n  by (rule_tac y = \"x \\<squnion> y\" in order_trans, simp_all) \n\nlemma [simp]: \"y \\<le> x \\<squnion> y \\<squnion> z\"\n  by (rule_tac y = \"x \\<squnion> y\" in order_trans, simp_all)\n\nlemma [simp]: \"y \\<le> x \\<squnion> (y \\<squnion> z)\"\n  by (rule_tac y = \"y \\<squnion> z\" in order_trans, simp_all)\n\nlemma [simp]: \"z \\<le> x \\<squnion> (y \\<squnion> z)\"\n  by (rule_tac y = \"y \\<squnion> z\" in order_trans, simp_all)\nend\n\ncontext lattice begin\n\nlemma [simp]: \"x \\<sqinter> y \\<le> x \\<squnion> z\"\n  by (rule_tac y = x in order_trans, simp_all)\n\nlemma [simp]: \"y \\<sqinter> x \\<le> x \\<squnion> z\"\n  by (rule_tac y = x in order_trans, simp_all)\n\nlemma [simp]: \"x \\<sqinter> y \\<le> z \\<squnion> x\"\n  by (rule_tac y = x in order_trans, simp_all)\n\nlemma [simp]: \"y \\<sqinter> x \\<le> z \\<squnion> x\"\n  by (rule_tac y = x in order_trans, simp_all)\n\nend\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/LatticeProperties/Lattice_Prop.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213772699436, "lm_q2_score": 0.7826624789529375, "lm_q1q2_score": 0.7037085660136734}}
{"text": "theory Exercises\nimports Main\nbegin\n\n(* we are given these definitions *)\n\ndatatype '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\nvalue \"rev(Cons True (Cons False Nil))\"\n\n(* exercise 2.1 - expression evaluation *)\n\nvalue \"1 + (2::nat)\"\n\nvalue \"1 + (2::int)\"\n\nvalue \"1 - (2::nat)\" (* evaluates as 0 *)\n\nvalue \"1 - (2::int)\"\n\n(* exercise 2.2 - associativity of add *)\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_assoc [simp]: \"add (add xs ys) zs = add xs (add ys zs)\"\n  apply(induction xs)\n  apply (auto)\n  done\n\nlemma add_ys_0 [simp]: \"add ys 0 = ys\"\n  apply(induction ys)\n   apply auto\n  done\n\nlemma suc_add [simp]: \"Suc (add ys xs) = add ys (Suc xs)\"\n  apply(induction ys)\n  apply(auto)\n  done\n                                                         \nlemma add_comm [simp]: \"add xs ys = add ys xs\"\n  apply(induction xs)\n  apply (auto)\n  done\n\nend", "meta": {"author": "Twigonometry", "repo": "IsabellePractice", "sha": "74ae764a1b84de45ae3ef6e88cc530807dc4ed05", "save_path": "github-repos/isabelle/Twigonometry-IsabellePractice", "path": "github-repos/isabelle/Twigonometry-IsabellePractice/IsabellePractice-74ae764a1b84de45ae3ef6e88cc530807dc4ed05/Exercises.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.899121388082479, "lm_q2_score": 0.7826624688140726, "lm_q1q2_score": 0.7037085653601689}}
{"text": "section \\<open> Sequence Toolkit \\<close>\n\ntheory Sequence_Toolkit\n  imports Number_Toolkit\nbegin\n\nsubsection \\<open> Conversion \\<close>\n\ntext \\<open> We define a number of coercions for mapping a list to finite function. \\<close>\n\nabbreviation rel_of_list :: \"'a list \\<Rightarrow> nat \\<leftrightarrow> 'a\" (\"[_]\\<^sub>s\") where\n\"rel_of_list xs \\<equiv> [list_pfun xs]\\<^sub>\\<Zpfun>\"\n\nabbreviation seq_nth (\"_'(_')\\<^sub>s\" [999,0] 999) where\n\"seq_nth xs i \\<equiv> xs ! (i - 1)\"\n\ndeclare [[coercion list_ffun]]\ndeclare [[coercion list_pfun]]\ndeclare [[coercion rel_of_list]]\ndeclare [[coercion seq_nth]]\n\nsubsection \\<open> Number range\\<close>\n\nlemma number_range: \"{i..j} = {k :: \\<int>. i \\<le> k \\<and> k \\<le> j}\"\n  by (auto)\n\ntext \\<open> The number range from $i$ to $j$ is the set of all integers greater than or equal to $i$, \n  which are also less than or equal to $j$.\\<close>\n\nsubsection \\<open> Iteration \\<close>\n\ndefinition iter :: \"\\<int> \\<Rightarrow> ('X \\<leftrightarrow> 'X) \\<Rightarrow> ('X \\<leftrightarrow> 'X)\" where\n\"iter n R = (if (n \\<ge> 0) then R ^^ (nat n) else (R\\<^sup>\\<sim>) ^^ (nat n))\"\n\nlemma iter_eqs:\n  \"iter 0 r = Id\"\n  \"n \\<ge> 0 \\<Longrightarrow> iter (n + 1) r = r \\<^bold>; (iter n r)\"\n  \"n < 0 \\<Longrightarrow> iter (n + 1) r = iter n (r\\<^sup>\\<sim>)\"\n  by (simp_all add: iter_def, metis Suc_nat_eq_nat_zadd1 add.commute relpow.simps(2) relpow_commute)\n\nsubsection \\<open> Number of members of a set \\<close>\n\nlemma size_rel_of_list: \n  \"#xs = length xs\" \n  by simp\n\nsubsection \\<open> Minimum \\<close>\n\ntext \\<open> Implemented by the function @{const Min}. \\<close>\n\nsubsection \\<open> Maximum \\<close>\n\ntext \\<open> Implemented by the function @{const Max}. \\<close>\n\nsubsection \\<open> Finite sequences \\<close>\n\ndefinition \"seq A = lists A\"\n\nlemma seq_iff [simp]: \"xs \\<in> seq A \\<longleftrightarrow> set xs \\<subseteq> A\"\n  by (simp add: in_lists_conv_set seq_def subset_code(1))\n  \nlemma seq_ffun_set: \"range list_ffun = {f :: \\<nat> \\<Zffun> 'X. dom(f) = {1..#f}}\"\n  by (simp add: range_list_ffun, force)\n\nsubsection \\<open> Non-empty finite sequences \\<close>\n\ndefinition \"seq\\<^sub>1 A = seq A - {[]}\"\n\nlemma seq\\<^sub>1_iff [simp]: \"xs \\<in> seq\\<^sub>1(A) \\<longleftrightarrow> (xs \\<in> seq A \\<and> #xs > 0)\"\n  by (simp add: seq\\<^sub>1_def)\n\nsubsection \\<open> Injective sequences \\<close>\n\ndefinition \"iseq A = seq A \\<inter> Collect distinct\"\n\nlemma iseq_iff [simp]: \"xs \\<in> iseq(A) \\<longleftrightarrow> (xs \\<in> seq A \\<and> distinct xs)\"\n  by (simp add: iseq_def)\n\nsubsection \\<open> Bounded sequences \\<close>\n\ndefinition bseq :: \"\\<nat> \\<Rightarrow> 'a set \\<Rightarrow> 'a list set\" (\"bseq[_]\") where\n\"bseq n A = blists n A\"\n\n(* Proof that this corresponds to the Z definition required *)\n\nsubsection \\<open> Sequence brackets \\<close>\n\ntext \\<open> Provided by the HOL list notation @{term \"[x, y, z]\"}. \\<close>\n\nsubsection \\<open> Concatenation \\<close>\n\ntext \\<open> Provided by the HOL concatenation operator @{term \"(@)\"}. \\<close>\n\nsubsection \\<open> Reverse \\<close>\n\ntext \\<open> Provided by the HOL function @{const rev}. \\<close>\n\nsubsection \\<open> Head of a sequence \\<close>\n\ndefinition head :: \"'a list \\<Zpfun> 'a\" where\n\"head = (\\<lambda> xs :: 'a list | #xs > 0 \\<bullet> hd xs)\"\n\nlemma dom_head: \"dom head = {xs. #xs > 0}\"\n  by (simp add: head_def)\n\nlemma head_app: \"#xs > 0 \\<Longrightarrow> head xs = hd xs\"\n  by (simp add: head_def)\n\nlemma head_z_def: \"xs \\<in> seq\\<^sub>1(A) \\<Longrightarrow> head xs = xs 1\"\n  by (simp add: hd_conv_nth head_app seq\\<^sub>1_def)\n\nsubsection \\<open> Last of a sequence \\<close>\n\nhide_const (open) last\n\ndefinition last :: \"'a list \\<Zpfun> 'a\" where\n\"last = (\\<lambda> xs :: 'a list | #xs > 0 \\<bullet> List.last xs)\"\n\nlemma dom_last: \"dom last = {xs. #xs > 0}\"\n  by (simp add: last_def)\n\nlemma last_app: \"#xs > 0 \\<Longrightarrow> last xs = List.last xs\"\n  by (simp add: last_def)\n\nlemma last_eq: \"#s > 0 \\<Longrightarrow> last s = s (#s)\"\n  by (simp add: last_app last_conv_nth)\n\nsubsection \\<open> Tail of a sequence \\<close>\n\ndefinition tail :: \"'a list \\<Zpfun> 'a list\" where\n\"tail = (\\<lambda> xs :: 'a list | #xs > 0 \\<bullet> tl xs)\"\n\nlemma dom_tail: \"dom tail = {xs. #xs > 0}\"\n  by (simp add: tail_def)\n\nlemma tail_app: \"#xs > 0 \\<Longrightarrow> tail xs = tl xs\"\n  by (simp add: tail_def)\n\nsubsection \\<open> Domain \\<close>\n\ndefinition dom_seq :: \"'a list \\<Rightarrow> \\<nat> set\" where\n[simp]: \"dom_seq xs = {0..<#xs}\"\n\nadhoc_overloading dom dom_seq\n\nsubsection \\<open> Range \\<close>\n\ndefinition ran_seq :: \"'a list \\<Rightarrow> 'a set\" where\n[simp]: \"ran_seq xs = set xs\"\n\nadhoc_overloading ran ran_seq\n\nsubsection \\<open> Filter \\<close>\n\nnotation seq_filter (infix \"\\<restriction>\" 80)\n\nlemma seq_filter_Nil: \"[] \\<restriction> V = []\" by simp\n\nlemma seq_filter_append: \"(s @ t) \\<restriction> V = (s \\<restriction> V) @ (t \\<restriction> V)\" \n  by (simp add: seq_filter_append)\n\nlemma seq_filter_subset_iff: \"ran s \\<subseteq> V \\<longleftrightarrow> (s \\<restriction> V = s)\"\n  by (auto simp add: seq_filter_def subsetD, meson filter_id_conv)\n\nlemma seq_filter_empty: \"s \\<restriction> {} = []\" by simp\n\nlemma seq_filter_size: \"#(s \\<restriction> V) \\<le> #s\"\n  by (simp add: seq_filter_def)\n\nlemma seq_filter_twice: \"(s \\<restriction> V) \\<restriction> W = s \\<restriction> (V \\<inter> W)\" by simp\n\nsubsection \\<open> Examples \\<close>\n\nlemma \"([1,2,3] \\<^bold>; (\\<lambda> x \\<bullet> x + 1)) 1 = 2\"\n  by (simp add: pfun_graph_comp[THEN sym] list_pfun_def pcomp_pabs)\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/Sequence_Toolkit.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8221891479496523, "lm_q2_score": 0.8558511488056151, "lm_q1q2_score": 0.7036715268082198}}
{"text": "(*  Title:      Util_NatInf.thy\n    Date:       Oct 2006\n    Author:     David Trachtenherz\n*)\n\nsection \\<open>Results for natural arithmetics with infinity\\<close>\n\ntheory Util_NatInf\nimports \"HOL-Library.Extended_Nat\"\nbegin\n\nsubsection \\<open>Arithmetic operations with @{typ enat}\\<close>\n\nsubsubsection \\<open>Additional definitions\\<close>\n\ninstantiation enat :: modulo\nbegin\n\ndefinition\n  div_enat_def [code del]: \"\n  a div b \\<equiv> (case a of\n    (enat x) \\<Rightarrow> (case b of (enat y) \\<Rightarrow> enat (x div y) | \\<infinity> \\<Rightarrow> 0) |\n    \\<infinity> \\<Rightarrow> (case b of (enat y) \\<Rightarrow> ((case y of 0 \\<Rightarrow> 0 | Suc n \\<Rightarrow> \\<infinity>)) | \\<infinity> \\<Rightarrow> \\<infinity> ))\"\ndefinition\n  mod_enat_def [code del]: \"\n  a mod b \\<equiv> (case a of\n    (enat x) \\<Rightarrow> (case b of (enat y) \\<Rightarrow> enat (x mod y) | \\<infinity> \\<Rightarrow> a) |\n    \\<infinity> \\<Rightarrow> \\<infinity>)\"\n\ninstance ..\n\nend\n\n\nlemmas enat_arith_defs =\n  zero_enat_def one_enat_def\n  plus_enat_def diff_enat_def times_enat_def div_enat_def mod_enat_def\ndeclare zero_enat_def[simp]\n\n\nlemmas ineq0_conv_enat[simp] = i0_less[symmetric, unfolded zero_enat_def]\n\nlemmas iless_eSuc0_enat[simp] = iless_eSuc0[unfolded zero_enat_def]\n\n\nsubsubsection \\<open>Addition, difference, order\\<close>\n\nlemma diff_eq_conv_nat: \"(x - y = (z::nat)) = (if y < x then x = y + z else z = 0)\"\nby auto\nlemma idiff_eq_conv: \"\n  (x - y = (z::enat)) =\n  (if y < x then x = y + z else if x \\<noteq> \\<infinity> then z = 0 else z = \\<infinity>)\"\nby (case_tac x, case_tac y, case_tac z, auto, case_tac z, auto)\nlemmas idiff_eq_conv_enat = idiff_eq_conv[unfolded zero_enat_def]\n\nlemma less_eq_idiff_eq_sum: \"y \\<le> (x::enat) \\<Longrightarrow> (z \\<le> x - y) = (z + y \\<le> x)\"\nby (case_tac x, case_tac y, case_tac z, fastforce+)\n\n\nlemma eSuc_pred: \"0 < n \\<Longrightarrow> eSuc (n - eSuc 0) = n\"\napply (case_tac n)\napply (simp add: eSuc_enat)+\ndone\nlemmas eSuc_pred_enat = eSuc_pred[unfolded zero_enat_def]\nlemmas iadd_0_enat[simp] = add_0_left[where 'a = enat, unfolded zero_enat_def]\nlemmas iadd_0_right_enat[simp] = add_0_right[where 'a=enat, unfolded zero_enat_def]\n\nlemma ile_add1: \"(n::enat) \\<le> n + m\"\nby (case_tac m, case_tac n, simp_all)\nlemma ile_add2: \"(n::enat) \\<le> m + n\"\nby (simp only: add.commute[of m] ile_add1)\n\nlemma iadd_iless_mono: \"\\<lbrakk> (i::enat) < j; k < l \\<rbrakk> \\<Longrightarrow> i + k < j + l\"\nby (case_tac i, case_tac k, case_tac j, case_tac l, simp_all)\n\nlemma trans_ile_iadd1: \"i \\<le> (j::enat) \\<Longrightarrow> i \\<le> j + m\"\nby (rule order_trans[OF _ ile_add1])\nlemma trans_ile_iadd2: \"i \\<le> (j::enat) \\<Longrightarrow> i \\<le> m + j\"\nby (rule order_trans[OF _ ile_add2])\n\nlemma trans_iless_iadd1: \"i < (j::enat) \\<Longrightarrow> i < j + m\"\nby (rule order_less_le_trans[OF _ ile_add1])\nlemma trans_iless_iadd2: \"i < (j::enat) \\<Longrightarrow> i < m + j\"\nby (rule order_less_le_trans[OF _ ile_add2])\n\n\n\nlemma iadd_ileD2: \"m + k \\<le> (n::enat) \\<Longrightarrow> k \\<le> n\"\nby (rule iadd_ileD1, simp only: add.commute[of m])\n\n\n\n\nlemma idiff_ile_mono2: \"m \\<le> (n::enat) \\<Longrightarrow> l - n \\<le> l - m\"\nby (case_tac m, case_tac n, case_tac l, simp_all, case_tac l, simp_all)\n\nlemma idiff_iless_mono: \"\\<lbrakk> m < (n::enat); l \\<le> m \\<rbrakk> \\<Longrightarrow> m - l < n - l\"\nby (case_tac m, case_tac n, case_tac l, simp_all, case_tac l, simp_all)\n\nlemma idiff_iless_mono2: \"\\<lbrakk> m < (n::enat); m < l \\<rbrakk> \\<Longrightarrow> l - n \\<le> l - m\"\nby (case_tac m, case_tac n, case_tac l, simp_all, case_tac l, simp_all)\n\n\nsubsubsection \\<open>Multiplication and division\\<close>\n\nlemmas imult_infinity_enat[simp] = imult_infinity[unfolded zero_enat_def]\nlemmas imult_infinity_right_enat[simp] = imult_infinity_right[unfolded zero_enat_def]\n\nlemma idiv_enat_enat[simp, code]: \"enat a div enat b = enat (a div b)\"\nunfolding div_enat_def by simp\n\nlemma idiv_infinity: \"0 < n \\<Longrightarrow> (\\<infinity>::enat) div n = \\<infinity>\"\nunfolding div_enat_def\napply (case_tac n, simp_all)\napply (rename_tac n1, case_tac n1, simp_all)\ndone\n\nlemmas idiv_infinity_enat[simp] = idiv_infinity[unfolded zero_enat_def]\n\nlemma idiv_infinity_right[simp]: \"n \\<noteq> \\<infinity> \\<Longrightarrow> n div (\\<infinity>::enat) = 0\"\nunfolding div_enat_def by (case_tac n, simp_all)\n\nlemma idiv_infinity_if: \"n div \\<infinity> = (if n = \\<infinity> then \\<infinity> else 0::enat)\"\nunfolding div_enat_def\nby (case_tac n, simp_all)\n\nlemmas idiv_infinity_if_enat = idiv_infinity_if[unfolded zero_enat_def]\n\nlemmas imult_0_enat[simp] = mult_zero_left[where 'a=enat,unfolded zero_enat_def]\nlemmas imult_0_right_enat[simp] = mult_zero_right[where 'a=enat,unfolded zero_enat_def]\n\nlemmas imult_is_0_enat = imult_is_0[unfolded zero_enat_def]\nlemmas enat_0_less_mult_iff_enat = enat_0_less_mult_iff[unfolded zero_enat_def]\n\nlemma imult_infinity_if: \"\\<infinity> * n = (if n = 0 then 0 else \\<infinity>::enat)\"\nby (case_tac n, simp_all)\nlemma imult_infinity_right_if: \"n * \\<infinity> = (if n = 0 then 0 else \\<infinity>::enat)\"\nby (case_tac n, simp_all)\nlemmas imult_infinity_if_enat = imult_infinity_if[unfolded zero_enat_def]\nlemmas imult_infinity_right_if_enat = imult_infinity_right_if[unfolded zero_enat_def]\n\nlemmas imult_is_infinity_enat = imult_is_infinity[unfolded zero_enat_def]\n\nlemma idiv_by_0: \"(a::enat) div 0 = 0\"\nunfolding div_enat_def by (case_tac a, simp_all)\nlemmas idiv_by_0_enat[simp, code] = idiv_by_0[unfolded zero_enat_def]\n\nlemma idiv_0: \"0 div (a::enat) = 0\"\nunfolding div_enat_def by (case_tac a, simp_all)\nlemmas idiv_0_enat[simp, code] = idiv_0[unfolded zero_enat_def]\n\nlemma imod_by_0: \"(a::enat) mod 0 = a\"\nunfolding mod_enat_def by (case_tac a, simp_all)\nlemmas imod_by_0_enat[simp, code] = imod_by_0[unfolded zero_enat_def]\n\nlemma imod_0: \"0 mod (a::enat) = 0\"\nunfolding mod_enat_def by (case_tac a, simp_all)\nlemmas imod_0_enat[simp, code] = imod_0[unfolded zero_enat_def]\n\nlemma imod_enat_enat[simp, code]: \"enat a mod enat b = enat (a mod b)\"\nunfolding mod_enat_def by simp\nlemma imod_infinity[simp, code]: \"\\<infinity> mod n = (\\<infinity>::enat)\"\nunfolding mod_enat_def by simp\nlemma imod_infinity_right[simp, code]: \"n mod (\\<infinity>::enat) = n\"\nunfolding mod_enat_def by (case_tac n) simp_all\n\nlemma idiv_self: \"\\<lbrakk> 0 < (n::enat); n \\<noteq> \\<infinity> \\<rbrakk> \\<Longrightarrow> n div n = 1\"\nby (case_tac n, simp_all add: one_enat_def)\nlemma imod_self: \"n \\<noteq> \\<infinity> \\<Longrightarrow> (n::enat) mod n = 0\"\nby (case_tac n, simp_all)\n\nlemma idiv_iless: \"m < (n::enat) \\<Longrightarrow> m div n = 0\"\nby (case_tac m, simp_all) (case_tac n, simp_all)\nlemma imod_iless: \"m < (n::enat) \\<Longrightarrow> m mod n = m\"\nby (case_tac m, simp_all) (case_tac n, simp_all)\n\nlemma imod_iless_divisor: \"\\<lbrakk> 0 < (n::enat); m \\<noteq> \\<infinity> \\<rbrakk>  \\<Longrightarrow> m mod n < n\"\nby (case_tac m, simp_all) (case_tac n, simp_all)\nlemma imod_ile_dividend: \"(m::enat) mod n \\<le> m\"\nby (case_tac m, simp_all) (case_tac n, simp_all)\nlemma idiv_ile_dividend: \"(m::enat) div n \\<le> m\"\nby (case_tac m, simp_all) (case_tac n, simp_all)\n\nlemma idiv_imult2_eq: \"(a::enat) div (b * c) = a div b div c\"\napply (case_tac a, case_tac b, case_tac c, simp_all add: div_mult2_eq)\napply (simp add: imult_infinity_if)\napply (case_tac \"b = 0\", simp)\napply (case_tac \"c = 0\", simp)\napply (simp add: idiv_infinity[OF enat_0_less_mult_iff[THEN iffD2]])\ndone\n\nlemma imult_ile_mono: \"\\<lbrakk> (i::enat) \\<le> j; k \\<le> l \\<rbrakk> \\<Longrightarrow> i * k \\<le> j * l\"\napply (case_tac i, case_tac j, case_tac k, case_tac l, simp_all add: mult_le_mono)\napply (case_tac k, case_tac l, simp_all)\napply (case_tac k, case_tac l, simp_all)\ndone\n\nlemma imult_ile_mono1: \"(i::enat) \\<le> j \\<Longrightarrow> i * k \\<le> j * k\"\nby (rule imult_ile_mono[OF _ order_refl])\n\nlemma imult_ile_mono2: \"(i::enat) \\<le> j \\<Longrightarrow> k * i \\<le> k * j\"\nby (rule imult_ile_mono[OF order_refl])\n\nlemma imult_iless_mono1: \"\\<lbrakk> (i::enat) < j; 0 < k; k \\<noteq> \\<infinity> \\<rbrakk> \\<Longrightarrow> i * k \\<le> j * k\"\nby (case_tac i, case_tac j, case_tac k, simp_all)\nlemma imult_iless_mono2: \"\\<lbrakk> (i::enat) < j; 0 < k; k \\<noteq> \\<infinity> \\<rbrakk> \\<Longrightarrow> k * i \\<le> k * j\"\nby (simp only: mult.commute[of k], rule imult_iless_mono1)\n\nlemma imod_1: \"(enat m) mod eSuc 0 = 0\"\nby (simp add: eSuc_enat)\nlemmas imod_1_enat[simp, code] = imod_1[unfolded zero_enat_def]\n\nlemma imod_iadd_self2: \"(m + enat n) mod (enat n) = m mod (enat n)\"\nby (case_tac m, simp_all)\n\nlemma imod_iadd_self1: \"(enat n + m) mod (enat n) = m mod (enat n)\"\nby (simp only: add.commute[of _ m] imod_iadd_self2)\n\nlemma idiv_imod_equality: \"(m::enat) div n * n + m mod n + k = m + k\"\nby (case_tac m, simp_all) (case_tac n, simp_all)\nlemma imod_idiv_equality: \"(m::enat) div n * n + m mod n = m\"\nby (insert idiv_imod_equality[of m n 0], simp)\n\nlemma idiv_ile_mono: \"m \\<le> (n::enat) \\<Longrightarrow> m div k \\<le> n div k\"\napply (case_tac \"k = 0\", simp)\napply (case_tac m, case_tac k, simp_all)\napply (case_tac n)\n apply (simp add: div_le_mono)\napply (simp add: idiv_infinity)\napply (simp add: i0_lb[unfolded zero_enat_def])\ndone\nlemma idiv_ile_mono2: \"\\<lbrakk> 0 < m; m \\<le> (n::enat) \\<rbrakk> \\<Longrightarrow> k div n \\<le> k div m\"\napply (case_tac \"n = 0\", simp)\napply (case_tac m, case_tac k, simp_all)\napply (case_tac n)\n apply (simp add: div_le_mono2)\napply simp\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/List-Infinite/CommonArith/Util_NatInf.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511616741041, "lm_q2_score": 0.822189134878876, "lm_q1q2_score": 0.7036715262019128}}
{"text": "header {* Algebra of Monotonic Boolean Transformers *}\n\ntheory  Mono_Bool_Tran_Algebra\nimports Mono_Bool_Tran\nbegin\n\ntext{*\nIn this section we introduce the {\\em algebra of monotonic boolean transformers}.\nThis is a bounded distributive lattice with a monoid operation, a\ndual operator and an iteration operator. The standard model for this\nalgebra is the set of monotonic boolean transformers introduced\nin the previous section. \n*}\n\nclass dual = \n  fixes dual::\"'a \\<Rightarrow> 'a\" (\"_ ^ o\" [81] 80)\n\nclass omega = \n  fixes omega::\"'a \\<Rightarrow> 'a\" (\"_ ^ \\<omega>\" [81] 80)\n\nclass star = \n  fixes star::\"'a \\<Rightarrow> 'a\" (\"(_ ^ *)\" [81] 80)\n\nclass dual_star = \n  fixes dual_star::\"'a \\<Rightarrow> 'a\" (\"(_ ^ \\<otimes>)\" [81] 80)\n\nclass mbt_algebra = monoid_mult + dual + omega + distrib_lattice + order_top + order_bot + star + dual_star +\n  assumes\n      dual_le: \"(x \\<le> y) = (y ^ o \\<le> x ^ o)\"\n  and dual_dual [simp]: \"(x ^ o) ^ o = x\"\n  and dual_comp: \"(x * y) ^ o = x ^ o * y ^ o\"\n  and dual_one [simp]: \"1 ^ o = 1\"\n  and top_comp [simp]: \"\\<top> * x = \\<top>\"\n  and inf_comp: \"(x \\<sqinter> y) * z = (x * z) \\<sqinter> (y * z)\"\n  and le_comp: \"x \\<le> y \\<Longrightarrow> z * x \\<le> z * y\"\n  and dual_neg: \"(x * \\<top>) \\<sqinter> (x ^ o * \\<bottom>) = \\<bottom>\"\n  and omega_fix: \"x ^ \\<omega> = (x * (x ^ \\<omega>)) \\<sqinter> 1\"\n  and omega_least: \"(x * z) \\<sqinter> y \\<le> z \\<Longrightarrow> (x ^ \\<omega>) * y \\<le> z\"\n  and star_fix: \"x ^ * = (x * (x ^ *)) \\<sqinter> 1\"\n  and star_greatest: \"z \\<le> (x * z) \\<sqinter> y \\<Longrightarrow> z \\<le> (x ^ *) * y\"\n  and dual_star_def: \"(x ^ \\<otimes>) = (((x ^ o) ^ *) ^ o)\"\nbegin\n\nlemma le_comp_right: \"x \\<le> y \\<Longrightarrow> x * z \\<le> y * z\"\n  apply (cut_tac x = x and y = y and z = z in inf_comp)\n  apply (simp add: inf_absorb1)\n  apply (subgoal_tac \"x * z \\<sqinter> (y * z) \\<le> y * z\")\n  apply simp\n  by (rule inf_le2)\n\nsubclass bounded_lattice\n  proof qed\n\nend\n\ninstantiation MonoTran :: (complete_boolean_algebra) mbt_algebra\nbegin\n\nlift_definition dual_MonoTran :: \"'a MonoTran \\<Rightarrow> 'a MonoTran\"\n  is dual_fun\n  by (fact mono_dual_fun)\n\nlift_definition omega_MonoTran :: \"'a MonoTran \\<Rightarrow> 'a MonoTran\"\n  is omega_fun\n  by (fact mono_omega_fun)\n\nlift_definition star_MonoTran :: \"'a MonoTran \\<Rightarrow> 'a MonoTran\"\n  is star_fun\n  by (fact mono_star_fun)\n\ndefinition dual_star_MonoTran :: \"'a MonoTran \\<Rightarrow> 'a MonoTran\"\nwhere\n  \"(x::('a MonoTran)) ^ \\<otimes> = ((x ^ o) ^ *) ^ o\"\n  \ninstance proof\n  fix x y :: \"'a MonoTran\" show \"(x \\<le> y) = (y ^ o \\<le> x ^ o)\"\n    apply transfer\n    apply (auto simp add: fun_eq_iff le_fun_def)\n    apply (drule_tac x = \"-xa\" in spec)\n    apply simp\n    done\nnext\n  fix x :: \"'a MonoTran\" show \"(x ^ o) ^ o = x\"\n    apply transfer\n    apply (simp add: fun_eq_iff)\n    done\nnext\n  fix x y :: \"'a MonoTran\" show \"(x * y) ^ o = x ^ o * y ^ o\"\n    apply transfer\n    apply (simp add: fun_eq_iff)\n    done\nnext\n  show \"(1\\<Colon>'a MonoTran) ^ o = 1\"\n    apply transfer\n    apply (simp add: fun_eq_iff)\n    done\nnext\n  fix x :: \"'a MonoTran\" show \"\\<top> * x = \\<top>\"\n    apply transfer\n    apply (simp add: fun_eq_iff)\n    done\nnext\n  fix x y z :: \"'a MonoTran\" show \"(x \\<sqinter> y) * z = (x * z) \\<sqinter> (y * z)\"\n    apply transfer\n    apply (simp add: fun_eq_iff)\n    done\nnext\n  fix x y z :: \"'a MonoTran\" assume A: \"x \\<le> y\" from A show \" z * x \\<le> z * y\"\n    apply transfer\n    apply (auto simp add: le_fun_def elim: monoE)\n    done\nnext\n  fix x :: \"'a MonoTran\" show \"x * \\<top> \\<sqinter> (x ^ o * \\<bottom>) = \\<bottom>\"\n    apply transfer\n    apply (simp add: fun_eq_iff inf_compl_bot)\n    done\nnext\n  fix x :: \"'a MonoTran\" show \"x ^ \\<omega> = x * x ^ \\<omega> \\<sqinter> 1\"\n    apply transfer\n    apply (simp add: fun_eq_iff)\n    apply (simp add: omega_fun_def Omega_fun_def)\n    apply (subst lfp_unfold, simp_all add: ac_simps)\n    apply (auto intro!: mono_comp mono_comp_fun)\n    done\nnext\n  fix x y z :: \"'a MonoTran\" assume A: \"x * z \\<sqinter> y \\<le> z\" from A show \"x ^ \\<omega> * y \\<le> z\"\n    apply transfer\n    apply (auto simp add: lfp_omega lfp_def)\n    apply (rule Inf_lower)\n    apply (auto simp add: Omega_fun_def ac_simps)\n    done\nnext\n  fix x :: \"'a MonoTran\" show \"x ^ * = x * x ^ * \\<sqinter> 1\"\n    apply transfer\n    apply (auto simp add: star_fun_def Omega_fun_def)\n    apply (subst gfp_unfold, simp_all add: ac_simps)\n    apply (auto intro!: mono_comp mono_comp_fun)\n    done\nnext\n  fix x y z :: \"'a MonoTran\" assume A: \"z \\<le> x * z \\<sqinter> y\" from A show \"z \\<le> x ^ * * y\"\n    apply transfer\n    apply (auto simp add: gfp_star gfp_def)\n    apply (rule Sup_upper)\n    apply (auto simp add: Omega_fun_def)\n    done\nnext\n  fix x :: \"'a MonoTran\" show \"x ^ \\<otimes> = ((x ^ o) ^ *) ^ o\"\n    by (simp add: dual_star_MonoTran_def) \nqed\n\nend\n\ncontext mbt_algebra begin\n\nlemma dual_top [simp]: \"\\<top> ^ o = \\<bottom>\"\n  apply (rule antisym, simp_all)\n  by (subst dual_le, simp)\n\nlemma dual_bot [simp]: \"\\<bottom> ^ o = \\<top>\"\n  apply (rule antisym, simp_all)\n  by (subst dual_le, simp)\n\nlemma dual_inf: \"(x \\<sqinter> y) ^ o = (x ^ o) \\<squnion> (y ^ o)\"\n  apply (rule antisym, simp_all, safe)\n  apply (subst dual_le, simp, safe)\n  apply (subst dual_le, simp)\n  apply (subst dual_le, simp)\n  apply (subst dual_le, simp)\n  by (subst dual_le, simp)\n\nlemma dual_sup: \"(x \\<squnion> y) ^ o = (x ^ o) \\<sqinter> (y ^ o)\"\n  apply (rule antisym, simp_all, safe)\n  apply (subst dual_le, simp)\n  apply (subst dual_le, simp)\n  apply (subst dual_le, simp, safe)\n  apply (subst dual_le, simp)\n  by (subst dual_le, simp)\n\nlemma sup_comp: \"(x \\<squnion> y) * z = (x * z) \\<squnion> (y * z)\"\n  apply (subgoal_tac \"((x ^ o \\<sqinter> y ^ o) * z ^ o) ^ o = ((x ^ o * z ^ o) \\<sqinter> (y ^ o * z ^ o)) ^ o\")\n  apply (simp add: dual_inf dual_comp)\n  by (simp add: inf_comp)\n\n\nlemma dual_eq: \"x ^ o = y ^ o \\<Longrightarrow> x = y\"\n  apply (subgoal_tac \"(x ^ o) ^ o = (y ^ o) ^ o\")\n  apply (subst (asm) dual_dual)\n  apply (subst (asm) dual_dual)\n  by simp_all\n\nlemma dual_neg_top [simp]: \"(x ^ o * \\<bottom>) \\<squnion> (x * \\<top>) = \\<top>\"\n  apply (rule dual_eq)\n  by(simp add: dual_sup dual_comp dual_neg)\n\n \n\n\n\nlemma [simp]: \"(x * \\<bottom>) * y = x * \\<bottom>\" \n  by (simp add: mult.assoc)\n\n\nlemma gt_one_comp: \"1 \\<le> x \\<Longrightarrow> y \\<le> x * y\"\n  by (cut_tac x = 1 and y = x and z = y in le_comp_right, simp_all)\n\n\n  theorem omega_comp_fix: \"x ^ \\<omega> * y = (x * (x ^ \\<omega>) * y) \\<sqinter> y\"\n  apply (subst omega_fix)\n  by (simp add: inf_comp)\n\n  theorem dual_star_fix: \"x^\\<otimes> = (x * (x^\\<otimes>)) \\<squnion> 1\"\n    by (metis dual_comp dual_dual dual_inf dual_one dual_star_def star_fix)\n\n  theorem star_comp_fix: \"x ^ * * y = (x * (x ^ *) * y) \\<sqinter> y\"\n  apply (subst star_fix)\n  by (simp add: inf_comp)\n\n  theorem dual_star_comp_fix: \"x^\\<otimes> * y = (x * (x^\\<otimes>) * y) \\<squnion> y\"\n  apply (subst dual_star_fix)\n  by (simp add: sup_comp)\n\n  theorem dual_star_least: \"(x * z) \\<squnion> y \\<le> z \\<Longrightarrow> (x^\\<otimes>) * y \\<le> z\"\n    apply (subst dual_le)\n    apply (simp add: dual_star_def dual_comp)\n    apply (rule star_greatest)\n    apply (subst dual_le)\n    by (simp add: dual_inf dual_comp)\n\n  lemma omega_one [simp]: \"1 ^ \\<omega> = \\<bottom>\"\n    apply (rule antisym, simp_all)\n    by (cut_tac x = \"1::'a\" and y = 1 and z = \\<bottom> in omega_least, simp_all)\n\n  lemma omega_mono: \"x \\<le> y \\<Longrightarrow> x ^ \\<omega> \\<le> y ^ \\<omega>\"\n    apply (cut_tac x = x and y = 1 and z = \"y ^ \\<omega>\" in omega_least, simp_all)\n    apply (subst (2) omega_fix, simp_all)\n    apply (rule_tac y = \"x * y ^ \\<omega>\" in order_trans, simp)\n    by (rule le_comp_right, simp)\nend\n\nsublocale mbt_algebra < conjunctive \"inf\" \"inf\" \"times\"\ndone\nsublocale mbt_algebra < disjunctive \"sup\" \"sup\" \"times\"\ndone\n\ncontext mbt_algebra begin\nlemma dual_conjunctive: \"x \\<in> conjunctive \\<Longrightarrow> x ^ o \\<in> disjunctive\"\n  apply (simp add: conjunctive_def disjunctive_def)\n  apply safe\n  apply (rule dual_eq)\n  by (simp add: dual_comp dual_sup)\n\nlemma dual_disjunctive: \"x \\<in> disjunctive \\<Longrightarrow> x ^ o \\<in> conjunctive\"\n  apply (simp add: conjunctive_def disjunctive_def)\n  apply safe\n  apply (rule dual_eq)\n  by (simp add: dual_comp dual_inf)\n\nlemma comp_pres_conj: \"x \\<in> conjunctive \\<Longrightarrow> y \\<in> conjunctive \\<Longrightarrow> x * y \\<in> conjunctive\"\n  apply (subst conjunctive_def, safe)\n  by (simp add: mult.assoc conjunctiveD)\n\nlemma comp_pres_disj: \"x \\<in> disjunctive \\<Longrightarrow> y \\<in> disjunctive \\<Longrightarrow> x * y \\<in> disjunctive\"\n  apply (subst disjunctive_def, safe)\n  by (simp add: mult.assoc disjunctiveD)\n\nlemma start_pres_conj: \"x \\<in> conjunctive \\<Longrightarrow> (x ^ *) \\<in> conjunctive\"\n  apply (subst conjunctive_def, safe)\n  apply (rule antisym, simp_all)\n  apply (metis inf_le1 inf_le2 le_comp)\n  apply (rule star_greatest)\n  apply (subst conjunctiveD, simp)\n  apply (subst star_comp_fix)\n  apply (subst star_comp_fix)\n  by (metis inf.assoc inf_left_commute mult.assoc order_refl)\n\nlemma dual_star_pres_disj: \"x \\<in> disjunctive \\<Longrightarrow> x^\\<otimes> \\<in> disjunctive\"\n  apply (simp add: dual_star_def)\n  apply (rule dual_conjunctive)\n  apply (rule start_pres_conj)\n  by (rule dual_disjunctive, simp)\n\nsubsection{*Assertions*}\n\ntext{*\nUsually, in Kleene algebra with tests or in other progrm algebras, tests or assertions\nor assumptions are defined using an existential quantifier. An element of the algebra\nis a test if it has a complement with respect to $\\bot$ and $1$. In this formalization\nassertions can be defined much simpler using the dual operator.\n*}\n\ndefinition\n   \"assertion = {x . x \\<le> 1 \\<and> (x * \\<top>) \\<sqinter> (x ^ o) = x}\"\n\nlemma assertion_prop: \"x \\<in> assertion \\<Longrightarrow> (x * \\<top>) \\<sqinter> 1 = x\"\n  apply (simp add: assertion_def)\n  apply safe\n  apply (rule antisym)\n  apply simp_all\n  proof -\n    assume [simp]: \"x \\<le> 1\"\n    assume A: \"x * \\<top> \\<sqinter> x ^ o = x\"\n    have \"x * \\<top> \\<sqinter> 1 \\<le> x * \\<top> \\<sqinter> x ^ o\"\n      apply simp\n      apply (rule_tac y = 1 in order_trans)\n      apply simp\n      apply (subst dual_le)\n      by simp\n    also have \"\\<dots> = x\" by (cut_tac A, simp)\n    finally show \"x * \\<top> \\<sqinter> 1 \\<le> x\" .\n  next\n    assume A: \"x * \\<top> \\<sqinter> x ^ o = x\"\n    have \"x = x * \\<top> \\<sqinter> x ^ o\" by (simp add: A)\n    also have \"\\<dots> \\<le> x * \\<top>\" by simp\n    finally show \"x \\<le> x * \\<top>\" .\n  qed\n\nlemma dual_assertion_prop: \"x \\<in> assertion \\<Longrightarrow> ((x ^ o) * \\<bottom>) \\<squnion> 1 = x ^ o\"\n  apply (rule dual_eq)\n  by (simp add: dual_sup dual_comp assertion_prop)\n\nlemma assertion_disjunctive: \"x \\<in> assertion \\<Longrightarrow> x \\<in> disjunctive\"\n  apply (simp add: disjunctive_def, safe)\n  apply (drule assertion_prop)\n  proof -\n    assume A: \"x * \\<top> \\<sqinter> 1 = x\"\n    fix y z::\"'a\"\n    have \"x * (y \\<squnion> z) = (x * \\<top> \\<sqinter> 1) * (y \\<squnion> z)\" by (cut_tac  A, simp)\n    also have \"\\<dots> = (x * \\<top>) \\<sqinter> (y \\<squnion> z)\" by (simp add: inf_comp)\n    also have \"\\<dots> = ((x * \\<top>) \\<sqinter> y) \\<squnion> ((x * \\<top>) \\<sqinter> z)\" by (simp add: inf_sup_distrib)\n    also have \"\\<dots> = (((x * \\<top>) \\<sqinter> 1) * y) \\<squnion> (((x * \\<top>) \\<sqinter> 1) * z)\" by (simp add: inf_comp)\n    also have \"\\<dots> = x * y \\<squnion> x * z\" by (cut_tac  A, simp)\n    finally show \"x * (y \\<squnion> z) = x * y \\<squnion> x * z\" .\n  qed\n\nlemma Abs_MonoTran_injective: \"mono x \\<Longrightarrow> mono y \\<Longrightarrow> Abs_MonoTran x = Abs_MonoTran y \\<Longrightarrow> x = y\"\n  apply (subgoal_tac \"Rep_MonoTran (Abs_MonoTran x) = Rep_MonoTran (Abs_MonoTran y)\")\n  apply (subst (asm) Abs_MonoTran_inverse, simp)\n  by (subst (asm) Abs_MonoTran_inverse, simp_all)\nend\n\nlemma mbta_MonoTran_disjunctive: \"Rep_MonoTran ` disjunctive = Apply.disjunctive\"\n  apply (simp add: disjunctive_def Apply.disjunctive_def)\n  apply transfer\n  apply auto\n  proof -\n    fix f :: \"'a \\<Rightarrow> 'a\" and a b\n    assume prem: \"\\<forall>y. mono y \\<longrightarrow> (\\<forall>z. mono z \\<longrightarrow> f \\<circ> y \\<squnion> z = (f \\<circ> y) \\<squnion> (f \\<circ> z))\"\n    { fix g h :: \"'b \\<Rightarrow> 'a\"\n      assume \"mono g\" and \"mono h\"\n      then have \"f \\<circ> g \\<squnion> h = (f \\<circ> g) \\<squnion> (f \\<circ> h)\"\n        using prem by blast\n    } note * = this\n    assume \"mono f\"\n    show \"f (a \\<squnion> b) = f a \\<squnion> f b\" (is \"?P = ?Q\")\n    proof (rule order_antisym)\n      show \"?P \\<le> ?Q\"\n        using * [of \"\\<lambda>_. a\" \"\\<lambda>_. b\"] by (simp add: comp_def fun_eq_iff)\n    next\n      from `mono f` show \"?Q \\<le> ?P\" by (rule Lattices.semilattice_sup_class.mono_sup)\n    qed\n  next\n    fix f :: \"'a \\<Rightarrow> 'a\"\n    assume \"\\<forall>y z. f (y \\<squnion> z) = f y \\<squnion> f z\"\n    then have *: \"\\<And>y z. f (y \\<squnion> z) = f y \\<squnion> f z\" by blast\n    show \"mono f\"\n    proof\n      fix a b :: 'a\n      assume \"a \\<le> b\"\n      then show \"f a \\<le> f b\"\n        unfolding sup.order_iff * [symmetric] by simp\n    qed\n  qed\n\nlemma assertion_MonoTran: \"assertion = Abs_MonoTran ` assertion_fun\"\n    apply (safe)\n    apply (subst assertion_fun_disj_less_one)\n    apply (simp add: image_def)\n    apply (rule_tac x = \"Rep_MonoTran x\" in bexI)\n    apply (simp add: Rep_MonoTran_inverse)\n    apply safe\n    apply (drule assertion_disjunctive)\n    apply (unfold mbta_MonoTran_disjunctive [THEN sym], simp)\n    apply (simp add: assertion_def less_eq_MonoTran_def one_MonoTran_def Abs_MonoTran_inverse)\n    apply (simp add: assertion_def)\n    by (simp_all add: inf_MonoTran_def less_eq_MonoTran_def \n      times_MonoTran_def dual_MonoTran_def top_MonoTran_def Abs_MonoTran_inverse one_MonoTran_def assertion_fun_dual)\n\ncontext mbt_algebra begin\nlemma assertion_conjunctive: \"x \\<in> assertion \\<Longrightarrow> x \\<in> conjunctive\"\n  apply (simp add: conjunctive_def, safe)\n  apply (drule assertion_prop)\n  proof -\n    assume A: \"x * \\<top> \\<sqinter> 1 = x\"\n    fix y z::\"'a\"\n    have \"x * (y \\<sqinter> z) = (x * \\<top> \\<sqinter> 1) * (y \\<sqinter> z)\" by (cut_tac  A, simp)\n    also have \"\\<dots> = (x * \\<top>) \\<sqinter> (y \\<sqinter> z)\" by (simp add: inf_comp)\n    also have \"\\<dots> = ((x * \\<top>) \\<sqinter> y) \\<sqinter> ((x * \\<top>) \\<sqinter> z)\"\n      apply (rule antisym, simp_all, safe)\n      apply (rule_tac y = \"y \\<sqinter> z\" in order_trans)\n      apply (rule inf_le2)\n      apply simp\n      apply (rule_tac y = \"y \\<sqinter> z\" in order_trans)\n      apply (rule inf_le2)\n      apply simp_all\n      apply (simp add: inf_assoc)\n      apply (rule_tac y = \" x * \\<top> \\<sqinter> y\" in order_trans)\n      apply (rule inf_le1)\n      apply simp\n      apply (rule_tac y = \" x * \\<top> \\<sqinter> z\" in order_trans)\n      apply (rule inf_le2)\n      by simp\n    also have \"\\<dots> = (((x * \\<top>) \\<sqinter> 1) * y) \\<sqinter> (((x * \\<top>) \\<sqinter> 1) * z)\" by (simp add: inf_comp)\n    also have \"\\<dots> = (x * y) \\<sqinter> (x * z)\" by (cut_tac  A, simp)\n    finally show \"x * (y \\<sqinter> z) = (x * y) \\<sqinter> (x * z)\" .\n  qed\n\nlemma dual_assertion_conjunctive: \"x \\<in> assertion \\<Longrightarrow> x ^ o \\<in> conjunctive\"\n  apply (drule assertion_disjunctive)\n  by (rule dual_disjunctive, simp)\n\nlemma dual_assertion_disjunct: \"x \\<in> assertion \\<Longrightarrow> x ^ o \\<in> disjunctive\"\n  apply (drule assertion_conjunctive)\n  by (rule dual_conjunctive, simp)\n\n\nlemma [simp]: \"x \\<in> assertion \\<Longrightarrow> y \\<in> assertion \\<Longrightarrow> x \\<sqinter> y \\<le> x * y\"\n  apply (simp add: assertion_def, safe)\n  proof -\n  assume A: \"x \\<le> 1\"\n  assume B: \"x * \\<top> \\<sqinter> x ^ o = x\"\n  assume C: \"y \\<le> 1\"\n  assume D: \"y * \\<top> \\<sqinter> y ^ o = y\"\n  have \"x \\<sqinter> y = (x * \\<top> \\<sqinter> x ^ o) \\<sqinter> (y * \\<top> \\<sqinter> y ^ o)\" by (cut_tac B D, simp)\n  also have \"\\<dots> \\<le> (x * \\<top>) \\<sqinter> (((x^o) * (y * \\<top>)) \\<sqinter> ((x^o) * (y^o)))\"\n    apply (simp, safe)\n      apply (rule_tac y = \"x * \\<top> \\<sqinter> x ^ o\" in order_trans)\n      apply (rule inf_le1)\n      apply simp\n      apply (rule_tac y = \"y * \\<top>\" in order_trans)\n      apply (rule_tac y = \"y * \\<top> \\<sqinter> y ^ o\" in order_trans)\n      apply (rule inf_le2)\n      apply simp\n      apply (rule gt_one_comp)\n      apply (subst dual_le, simp add: A)\n      apply (rule_tac y = \"y ^ o\" in order_trans)\n      apply (rule_tac y = \"y * \\<top> \\<sqinter> y ^ o\" in order_trans)\n      apply (rule inf_le2)\n      apply simp\n      apply (rule gt_one_comp)\n      by (subst dual_le, simp add: A)\n    also have \"... = ((x * \\<top>) \\<sqinter> (x ^ o)) * ((y * \\<top>) \\<sqinter> (y ^ o))\"\n      apply (cut_tac x = x in dual_assertion_conjunctive)\n      apply (cut_tac A, cut_tac B, simp add: assertion_def)\n      by (simp add: inf_comp conjunctiveD)\n    also have \"... = x * y\"\n      by (cut_tac B, cut_tac D, simp)\n    finally show \"x \\<sqinter> y \\<le> x * y\" .\n  qed\n    \nlemma [simp]: \"x \\<in> assertion \\<Longrightarrow> x * y \\<le> y\"\n  by (unfold assertion_def, cut_tac x = x and y = 1 and z = y in le_comp_right, simp_all)\n\n\nlemma [simp]: \"x \\<in> assertion \\<Longrightarrow> y \\<in> assertion \\<Longrightarrow> x * y \\<le> x\"\n  apply (subgoal_tac \"x * y \\<le> (x * \\<top>) \\<sqinter> (x ^ o)\")\n  apply (simp add: assertion_def) \n  apply (simp, safe)\n  apply (rule le_comp, simp)\n  apply (rule_tac y = 1 in order_trans)\n  apply (rule_tac y = y in order_trans)\n  apply simp\n  apply (simp add: assertion_def)\n  by (subst dual_le, simp add: assertion_def)\n\nlemma assertion_inf_comp_eq: \"x \\<in> assertion \\<Longrightarrow> y \\<in> assertion \\<Longrightarrow> x \\<sqinter> y = x * y\"\n  by (rule antisym, simp_all)\n\nlemma one_right_assertion [simp]: \"x \\<in> assertion \\<Longrightarrow> x * 1 = x\"\n  apply (drule assertion_prop)\n  proof -\n    assume A: \"x * \\<top> \\<sqinter> 1 = x\"\n    have \"x * 1 = (x * \\<top> \\<sqinter> 1) * 1\" by (simp add: A)\n    also have \"\\<dots> = x * \\<top> \\<sqinter> 1\" by (simp add: inf_comp)\n    also have \"\\<dots> = x\" by (simp add: A)\n    finally show ?thesis .\n  qed\n\nlemma [simp]: \"x \\<in> assertion \\<Longrightarrow> x \\<squnion> 1 = 1\"\n  by (rule antisym, simp_all add: assertion_def)\n  \nlemma [simp]: \"x \\<in> assertion \\<Longrightarrow> 1 \\<squnion> x = 1\"\n  by (rule antisym, simp_all add: assertion_def)\n  \nlemma [simp]: \"x \\<in> assertion \\<Longrightarrow> x \\<sqinter> 1 = x\"\n  by (rule antisym, simp_all add: assertion_def)\n  \nlemma [simp]: \"x \\<in> assertion \\<Longrightarrow> 1 \\<sqinter> x = x\"\n  by (rule antisym, simp_all add: assertion_def)\n\nlemma [simp]:  \"x \\<in> assertion \\<Longrightarrow> x \\<le> x * \\<top>\"\n  by (cut_tac x = 1 and y = \\<top> and z = x in le_comp, simp_all)\n\nlemma [simp]: \"x \\<in> assertion \\<Longrightarrow> x \\<le> 1\"\n  by (simp add: assertion_def)\n\ndefinition\n  \"neg_assert (x::'a) = (x ^ o * \\<bottom>) \\<sqinter> 1\"\n  \n\nlemma sup_uminus[simp]: \"x \\<in> assertion \\<Longrightarrow> x \\<squnion> neg_assert x = 1\"\n  apply (simp add: neg_assert_def)\n  apply (simp add: sup_inf_distrib)\n  apply (rule antisym, simp_all)\n  apply (unfold assertion_def)\n  apply safe\n  apply (subst dual_le)\n  apply (simp add: dual_sup dual_comp)\n  apply (subst inf_commute)\n  by simp\n\nlemma inf_uminus[simp]: \"x \\<in> assertion \\<Longrightarrow> x \\<sqinter> neg_assert x = \\<bottom>\"\n  apply (simp add: neg_assert_def)\n  apply (rule antisym, simp_all)\n  apply (rule_tac y = \"x \\<sqinter> (x ^ o * \\<bottom>)\" in order_trans)\n  apply simp\n  apply (rule_tac y = \"x ^ o * \\<bottom> \\<sqinter> 1\" in order_trans)\n  apply (rule inf_le2)\n  apply simp\n  apply (rule_tac y = \"(x * \\<top>)  \\<sqinter> (x ^ o * \\<bottom>)\" in order_trans)\n  apply simp\n  apply (rule_tac y = x in order_trans)\n  apply simp_all\n  by (simp add: dual_neg)\n\n\nlemma uminus_assertion[simp]: \"x \\<in> assertion \\<Longrightarrow> neg_assert x \\<in> assertion\"\n  apply (subst assertion_def)\n  apply (simp add: neg_assert_def)\n  apply (simp add: inf_comp dual_inf dual_comp inf_sup_distrib)\n  apply (subst inf_commute)\n  by (simp add: dual_neg)\n\nlemma uminus_uminus [simp]: \"x \\<in> assertion \\<Longrightarrow> neg_assert (neg_assert x) = x\"\n  apply (simp add: neg_assert_def)\n  by (simp add: dual_inf dual_comp sup_comp assertion_prop)\n\nlemma dual_comp_neg [simp]: \"x ^ o * y \\<squnion> (neg_assert x) * \\<top> = x ^ o * y\"\n  apply (simp add: neg_assert_def inf_comp)\n  apply (rule antisym, simp_all)\n  by (rule le_comp, simp)\n\n\nlemma [simp]: \"(neg_assert x) ^ o * y \\<squnion> x * \\<top> = (neg_assert x) ^ o * y\"\n  apply (simp add: neg_assert_def inf_comp dual_inf dual_comp sup_comp)\n  by (rule antisym, simp_all)\n\nlemma [simp]: \" x * \\<top> \\<squnion> (neg_assert x) ^ o * y= (neg_assert x) ^ o * y\"\n  by (simp add: neg_assert_def inf_comp dual_inf dual_comp sup_comp)\n\nlemma inf_assertion [simp]: \"x \\<in> assertion \\<Longrightarrow> y \\<in> assertion \\<Longrightarrow> x \\<sqinter> y \\<in> assertion\"\n  apply (subst assertion_def)\n  apply safe\n  apply (rule_tac y = x in order_trans)\n  apply simp_all\n  apply (simp add: assertion_inf_comp_eq)\n  proof -\n    assume A: \"x \\<in> assertion\"\n    assume B: \"y \\<in> assertion\"\n    have C: \"(x * \\<top>) \\<sqinter> (x ^ o) = x\"\n      by (cut_tac A, unfold assertion_def, simp) \n    have D: \"(y * \\<top>) \\<sqinter> (y ^ o) = y\"\n      by (cut_tac B, unfold assertion_def, simp)\n    have \"x * y = ((x * \\<top>) \\<sqinter> (x ^ o)) * ((y * \\<top>) \\<sqinter> (y ^ o))\" by (simp add: C D)\n    also have \"\\<dots> = x * \\<top> \\<sqinter> ((x ^ o) * ((y * \\<top>) \\<sqinter> (y ^ o)))\" by (simp add: inf_comp)\n    also have \"\\<dots> =  x * \\<top> \\<sqinter> ((x ^ o) * (y * \\<top>)) \\<sqinter> ((x ^ o) *(y ^ o))\" \n      by (cut_tac A, cut_tac x = x in dual_assertion_conjunctive, simp_all add: conjunctiveD inf_assoc)\n    also have \"\\<dots> = (((x * \\<top>) \\<sqinter> (x ^ o)) * (y * \\<top>)) \\<sqinter> ((x ^ o) *(y ^ o))\"\n      by (simp add: inf_comp)\n    also have \"\\<dots> = (x * y * \\<top>)  \\<sqinter> ((x * y) ^ o)\" by (simp add: C mult.assoc dual_comp)\n    finally show \"(x * y * \\<top>)  \\<sqinter> ((x * y) ^ o) = x * y\" by simp\n  qed\n\nlemma comp_assertion [simp]: \"x \\<in> assertion \\<Longrightarrow> y \\<in> assertion \\<Longrightarrow> x * y \\<in> assertion\"\n  by (subst assertion_inf_comp_eq [THEN sym], simp_all)\n\n\nlemma sup_assertion [simp]: \"x \\<in> assertion \\<Longrightarrow> y \\<in> assertion \\<Longrightarrow> x \\<squnion> y \\<in> assertion\"\n  apply (subst assertion_def)\n  apply safe\n  apply (unfold assertion_def)\n  apply simp\n  apply safe\n  proof -\n    assume [simp]: \"x \\<le> 1\"\n    assume [simp]: \"y \\<le> 1\"\n    assume A: \"x * \\<top> \\<sqinter> x ^ o = x\"\n    assume B: \"y * \\<top> \\<sqinter> y ^ o = y\"\n    have \"(y * \\<top>) \\<sqinter> (x ^ o) \\<sqinter> (y ^ o) = (x ^ o) \\<sqinter> (y * \\<top>) \\<sqinter> (y ^ o)\" by (simp add: inf_commute)\n    also have \"\\<dots> = (x ^ o) \\<sqinter> ((y * \\<top>) \\<sqinter> (y ^ o))\" by (simp add: inf_assoc)\n    also have \"\\<dots> = (x ^ o) \\<sqinter> y\" by (simp add: B)\n    also have \"\\<dots> = y\"\n      apply (rule antisym, simp_all)\n      apply (rule_tac y = 1 in order_trans)\n      apply simp\n      by (subst dual_le, simp)\n    finally have [simp]: \"(y * \\<top>) \\<sqinter> (x ^ o) \\<sqinter> (y ^ o) = y\" .\n    have \"x * \\<top> \\<sqinter> (x ^ o) \\<sqinter> (y ^ o) = x \\<sqinter> (y ^ o)\"  by (simp add: A)\n    also have \"\\<dots> = x\"\n      apply (rule antisym, simp_all)\n      apply (rule_tac y = 1 in order_trans)\n      apply simp\n      by (subst dual_le, simp)\n    finally have [simp]: \"x * \\<top> \\<sqinter> (x ^ o) \\<sqinter> (y ^ o) = x\" .\n    have \"(x \\<squnion> y) * \\<top> \\<sqinter> (x \\<squnion> y) ^ o = (x * \\<top> \\<squnion> y * \\<top>) \\<sqinter> ((x ^ o) \\<sqinter> (y ^ o))\" by (simp add: sup_comp dual_sup)\n    also have \"\\<dots> = x \\<squnion> y\" by (simp add: inf_sup_distrib inf_assoc [THEN sym])\n    finally show \"(x \\<squnion> y) * \\<top> \\<sqinter> (x \\<squnion> y) ^ o = x \\<squnion> y\" .\n  qed\n\nlemma [simp]: \"x \\<in> assertion \\<Longrightarrow> x * x = x\"\n  by (simp add: assertion_inf_comp_eq [THEN sym])\n\nlemma [simp]: \"x \\<in> assertion \\<Longrightarrow> (x ^ o) * (x ^ o) = x ^ o\"\n  apply (rule dual_eq)\n  by (simp add: dual_comp assertion_inf_comp_eq [THEN sym])\n\nlemma [simp]: \"x \\<in> assertion \\<Longrightarrow> x * (x ^ o) = x\"\n  proof -\n    assume A: \"x \\<in> assertion\"\n    have B: \"x * \\<top> \\<sqinter> (x ^ o) = x\" by (cut_tac A, unfold assertion_def, simp)\n    have \"x * x ^ o = (x * \\<top> \\<sqinter> (x ^ o)) * x ^ o\" by (simp add: B)\n    also have \"\\<dots> = x * \\<top> \\<sqinter> (x ^ o)\" by (cut_tac A, simp add: inf_comp)\n    also have \"\\<dots> = x\" by (simp add: B)\n    finally show ?thesis .\n  qed\n\nlemma [simp]: \"x \\<in> assertion \\<Longrightarrow> (x ^ o) * x = x ^ o\"\n  apply (rule dual_eq)\n  by (simp add: dual_comp)\n\n\nlemma [simp]: \"\\<bottom> \\<in> assertion\"\n  by (unfold assertion_def, simp)\n\nlemma [simp]: \"1 \\<in> assertion\"\n  by (unfold assertion_def, simp)\n\n\nsubsection {*Weakest precondition of true*}\n\ndefinition\n  \"wpt x = (x * \\<top>) \\<sqinter> 1\"\n\nlemma wpt_is_assertion [simp]: \"wpt x \\<in> assertion\"\n  apply (unfold wpt_def assertion_def, safe)\n  apply simp\n  apply (simp add: inf_comp dual_inf dual_comp inf_sup_distrib)\n  apply (rule antisym)\n  by (simp_all add: dual_neg)\n\nlemma wpt_comp: \"(wpt x) * x = x\"\n  apply (simp add: wpt_def inf_comp)\n  apply (rule antisym, simp_all)\n  by (cut_tac x = 1 and y = \\<top> and z = x in le_comp, simp_all)\n\nlemma wpt_comp_2: \"wpt (x * y) = wpt (x * (wpt y))\"\n  by (simp add: wpt_def inf_comp mult.assoc)\n\nlemma wpt_assertion [simp]: \"x \\<in> assertion \\<Longrightarrow> wpt x = x\"\n  by (simp add: wpt_def assertion_prop)\n\nlemma wpt_le_assertion: \"x \\<in> assertion \\<Longrightarrow> x * y = y \\<Longrightarrow> wpt y \\<le> x\"\n  apply (simp add: wpt_def)\n  proof -\n    assume A: \"x \\<in> assertion\"\n    assume B: \"x * y = y\"\n    have \"y * \\<top> \\<sqinter> 1 = x * (y * \\<top>) \\<sqinter> 1\" by (simp add: B mult.assoc [THEN sym])\n    also have \"\\<dots> \\<le> x * \\<top> \\<sqinter> 1\" \n      apply simp\n      apply (rule_tac y = \"x * (y * \\<top>)\" in order_trans)\n      apply simp_all\n      by (rule le_comp, simp)\n    also have \"\\<dots> = x\" by (cut_tac A, simp add: assertion_prop)\n    finally show \"y * \\<top> \\<sqinter> 1 \\<le> x\" .\n  qed\n\nlemma wpt_choice: \"wpt (x \\<sqinter> y) = wpt x \\<sqinter> wpt y\"\n  apply (simp add: wpt_def inf_comp)\n  proof -\n    have \"x * \\<top> \\<sqinter> 1 \\<sqinter> (y * \\<top> \\<sqinter> 1) = x * \\<top> \\<sqinter> ((y * \\<top> \\<sqinter> 1) \\<sqinter> 1)\" apply (subst inf_assoc) by (simp add: inf_commute)\n    also have \"... = x * \\<top> \\<sqinter> (y * \\<top> \\<sqinter> 1)\" by (subst inf_assoc, simp)\n    also have \"... = (x * \\<top>) \\<sqinter> (y * \\<top>) \\<sqinter> 1\" by (subst inf_assoc, simp)\n    finally show \"x * \\<top> \\<sqinter> (y * \\<top>) \\<sqinter> 1 = x * \\<top> \\<sqinter> 1 \\<sqinter> (y * \\<top> \\<sqinter> 1)\" by simp\n  qed\nend \n\ncontext lattice begin\nlemma [simp]: \"x \\<le> y \\<Longrightarrow> x \\<sqinter> y = x\"\n  by (simp add: inf_absorb1)\nend\n\n\ncontext mbt_algebra begin\n\nlemma wpt_dual_assertion_comp: \"x \\<in> assertion \\<Longrightarrow> y \\<in> assertion \\<Longrightarrow> wpt ((x ^ o) * y) = (neg_assert x) \\<squnion> y\"\n  apply (simp add: wpt_def neg_assert_def)\n  proof -\n    assume A: \"x \\<in> assertion\"\n    assume B: \"y \\<in> assertion\"\n    have C: \"((x ^ o) * \\<bottom>) \\<squnion> 1 = x ^ o\"\n      by (rule dual_assertion_prop, rule A)\n    have \"x ^ o * y * \\<top> \\<sqinter> 1 = (((x ^ o) * \\<bottom>) \\<squnion> 1) * y * \\<top> \\<sqinter> 1\" by (simp add: C)\n    also have \"\\<dots> = ((x ^ o) * \\<bottom> \\<squnion> (y * \\<top>)) \\<sqinter> 1\" by (simp add: sup_comp)\n    also have \"\\<dots> = (((x ^ o) * \\<bottom>) \\<sqinter> 1) \\<squnion> ((y * \\<top>) \\<sqinter> 1)\" by (simp add: inf_sup_distrib2)\n    also have \"\\<dots> = (((x ^ o) * \\<bottom>) \\<sqinter> 1) \\<squnion> y\" by (cut_tac B, drule assertion_prop, simp)\n    finally show \"x ^ o * y * \\<top> \\<sqinter> 1 = (((x ^ o) * \\<bottom>) \\<sqinter> 1) \\<squnion> y\" .\n  qed\n\nlemma le_comp_left_right: \"x \\<le> y \\<Longrightarrow> u \\<le> v \\<Longrightarrow> x * u \\<le> y * v\"\n  apply (rule_tac y = \"x * v\" in order_trans)\n  apply (rule le_comp, simp)\n  by (rule le_comp_right, simp)\n\nlemma wpt_dual_assertion: \"x \\<in> assertion \\<Longrightarrow> wpt (x ^ o) = 1\"\n  apply (simp add: wpt_def)\n  apply (rule antisym)\n  apply simp_all\n  apply (cut_tac x = 1 and y = \"x ^ o\" and u = 1 and v = \\<top> in le_comp_left_right)\n  apply simp_all\n  apply (subst dual_le)\n  by simp\n\nlemma assertion_commute: \"x \\<in> assertion \\<Longrightarrow> y \\<in> conjunctive \\<Longrightarrow> y * x = wpt(y * x) * y\"\n  apply (simp add: wpt_def)\n  apply (simp add: inf_comp)\n  apply (drule_tac x = y and y = \"x * \\<top>\" and z = 1 in conjunctiveD)\n  by (simp add: mult.assoc [THEN sym] assertion_prop)\n\n\nlemma wpt_mono: \"x \\<le> y \\<Longrightarrow> wpt x \\<le> wpt y\"\n  apply (simp add: wpt_def)\n  apply (rule_tac y = \"x * \\<top>\" in order_trans, simp_all)\n  by (rule le_comp_right, simp)\n\nlemma \"a \\<in> conjunctive \\<Longrightarrow> x * a \\<le> a * y \\<Longrightarrow> (x ^ \\<omega>) * a \\<le> a * (y ^ \\<omega>)\"\n  apply (rule omega_least)\n  apply (simp add: mult.assoc [THEN sym])\n  apply (rule_tac y = \"a * y * y ^ \\<omega> \\<sqinter> a\" in order_trans)\n  apply (simp)\n  apply (rule_tac y = \"x * a * y ^ \\<omega>\" in order_trans, simp_all)\n  apply (rule le_comp_right, simp)\n  apply (simp add: mult.assoc)\n  apply (subst (2) omega_fix)\n  by (simp add: conjunctiveD)\n\nlemma [simp]: \"x \\<le> 1 \\<Longrightarrow> y * x \\<le> y\"\n  by (cut_tac x = x and y = 1 and z = y in le_comp, simp_all)\n\nlemma [simp]: \"x \\<le> x * \\<top>\"\n  by (cut_tac x = 1 and y = \\<top> and z = x in le_comp, simp_all)\n\nlemma [simp]: \"x * \\<bottom> \\<le> x\"\n  by (cut_tac x = \\<bottom> and y = 1 and z = x in le_comp, simp_all)\n\nend\n\nsubsection{*Monotonic Boolean trasformers algebra with post condition statement*}\n\ndefinition\n  \"post_fun (p::'a::order) q = (if p \\<le> q then (\\<top>::'b::{order_bot,order_top}) else \\<bottom>)\"\n\nlemma mono_post_fun [simp]: \"mono (post_fun (p::_::{order_bot,order_top}))\"\n  apply (simp add: post_fun_def mono_def, safe)\n  apply (subgoal_tac \"p \\<le> y\", simp)\n  apply (rule_tac y = x in order_trans)\n  apply simp_all\n  done\n\n\n\nlemma post_refin [simp]: \"mono S \\<Longrightarrow> ((S p)::'a::bounded_lattice) \\<sqinter> (post_fun p) x \\<le> S x\"\n  apply (simp add: le_fun_def assert_fun_def post_fun_def, safe)\n  by (rule_tac f = S in monoD, simp_all)\n\nclass post_mbt_algebra = mbt_algebra +\n  fixes post :: \"'a \\<Rightarrow> 'a\"\n  assumes post_1: \"(post x) * x * \\<top> = \\<top>\"\n  and post_2: \"y * x * \\<top> \\<sqinter> (post x) \\<le> y\"\n\ninstantiation MonoTran :: (complete_boolean_algebra) post_mbt_algebra\nbegin\n\nlift_definition post_MonoTran :: \"'a::complete_boolean_algebra MonoTran \\<Rightarrow> 'a::complete_boolean_algebra MonoTran\"\n  is \"\\<lambda>x. post_fun (x \\<top>)\"\n  by (rule mono_post_fun)\n\ninstance proof\n  fix x :: \"'a MonoTran\" show \"post x * x * \\<top> = \\<top>\"\n    apply transfer\n    apply (simp add: fun_eq_iff)\n    done\n  fix x y :: \"'a MonoTran\" show \"y * x * \\<top> \\<sqinter> post x \\<le> y\"\n    apply transfer\n    apply (simp add: le_fun_def)\n    done\nqed\n   \nend\n\nsubsection{*Complete monotonic Boolean transformers algebra*}\n\nclass complete_mbt_algebra = post_mbt_algebra + complete_distrib_lattice +\n  assumes Inf_comp: \"(Inf X) * z = (INF x : X . (x * z))\"\n\ninstance MonoTran :: (complete_boolean_algebra) complete_mbt_algebra\n  apply intro_classes\n  unfolding INF_def\n  apply transfer\n  apply (simp add: Inf_comp_fun INF_def [symmetric])\n  done\n\ncontext complete_mbt_algebra begin\nlemma dual_Inf: \"(Inf X) ^ o = (SUP x: X . x ^ o)\"\n  apply (rule antisym)\n  apply (subst dual_le, simp)\n  apply (rule Inf_greatest)\n  apply (subst dual_le, simp)\n  apply (rule SUP_upper, simp)\n  apply (rule SUP_least)\n  apply (subst dual_le, simp)\n  by (rule Inf_lower, simp)\n\nlemma dual_Sup: \"(Sup X) ^ o = (INF x: X . x ^ o)\"\n  apply (rule antisym)\n  apply (rule INF_greatest)\n  apply (subst dual_le, simp)\n  apply (rule Sup_upper, simp)\n  apply (subst dual_le, simp)\n  apply (rule Sup_least)\n  apply (subst dual_le, simp)\n  by (rule INF_lower, simp)\n\nlemma INF_comp: \"(INFIMUM A f) * z = (INF a : A . (f a) * z)\"\n  unfolding INF_def Inf_comp\n  apply (subgoal_tac \"((\\<lambda>x\\<Colon>'a. x * z) ` f ` A) = ((\\<lambda>a\\<Colon>'b. f a * z) ` A)\")\n  by auto\n\nlemma dual_INF: \"(INFIMUM A f) ^ o = (SUP a : A . (f a) ^ o)\"\n  unfolding INF_def SUP_def Inf_comp dual_Inf\n  apply (subgoal_tac \"(dual ` f ` A) = ((\\<lambda>a\\<Colon>'b. f a ^ o) ` A)\")\n  by auto\n\nlemma dual_SUP: \"(SUPREMUM A f) ^ o = (INF a : A . (f a) ^ o)\"\n  unfolding INF_def dual_Sup SUP_def\n  apply (subgoal_tac \"(dual ` f ` A) = ((\\<lambda>a\\<Colon>'b. f a ^ o) ` A)\")\n  by auto\n\nlemma Sup_comp: \"(Sup X) * z = (SUP x : X . (x * z))\"\n  apply (rule dual_eq)\n  by (simp add: dual_comp dual_Sup dual_SUP INF_comp)\n\nlemma SUP_comp: \"(SUPREMUM A f) * z = (SUP a : A . (f a) * z)\"\n  unfolding SUP_def Sup_comp\n  apply (subgoal_tac \"((\\<lambda>x\\<Colon>'a. x * z) ` f ` A) = ((\\<lambda>a\\<Colon>'b. f a * z) ` A)\")\n  by auto\n\n\nlemma Sup_assertion [simp]: \"X \\<subseteq> assertion \\<Longrightarrow> Sup X \\<in> assertion\"\n  apply (unfold assertion_def)\n  apply safe\n  apply (rule Sup_least)\n  apply blast\n  apply (simp add: Sup_comp dual_Sup SUP_def Sup_inf del: Sup_image_eq)\n  apply (subgoal_tac \"((\\<lambda>y . y \\<sqinter> INFIMUM X dual) ` (\\<lambda>x . x * \\<top>) ` X) = X\")\n  apply simp\n  proof -\n    assume A: \"X \\<subseteq> {x. x \\<le> 1 \\<and> x * \\<top> \\<sqinter> x ^ o = x}\"\n    have B [simp]: \"!! x . x \\<in> X \\<Longrightarrow>  x * \\<top> \\<sqinter> (INFIMUM X dual) = x\"\n      proof -\n        fix x\n        assume C: \"x \\<in> X\"\n        have \"x * \\<top> \\<sqinter> INFIMUM X dual = x * \\<top> \\<sqinter> (x ^ o \\<sqinter> INFIMUM X dual)\"\n          apply (subgoal_tac \"INFIMUM X dual = (x ^ o \\<sqinter> INFIMUM X dual)\", simp)\n          apply (rule antisym, simp_all)\n          by (unfold INF_def, rule Inf_lower, cut_tac C, simp)\n        also have \"\\<dots> = x \\<sqinter> INFIMUM X dual\" by (unfold  inf_assoc [THEN sym], cut_tac A, cut_tac C, auto)\n        also have \"\\<dots> = x\"\n          apply (rule antisym, simp_all)\n          apply (rule INF_greatest)\n          apply (cut_tac A C)\n          apply (rule_tac y = 1 in order_trans)\n          apply auto[1]\n          by (subst dual_le, auto)\n        finally show \"x * \\<top> \\<sqinter> INFIMUM X dual = x\" .\n      qed\n      show \"(\\<lambda>y. y \\<sqinter> INFIMUM X dual) ` (\\<lambda>x . x * \\<top>) ` X = X\"\n        by (unfold image_def, auto)\n    qed\n\nlemma Sup_range_assertion [simp]: \"(!!w . p w \\<in> assertion) \\<Longrightarrow> Sup (range p) \\<in> assertion\"\n  by (rule Sup_assertion, auto)\n\nlemma Sup_less_assertion [simp]: \"(!!w . p w \\<in> assertion) \\<Longrightarrow> Sup_less p w \\<in> assertion\"\n  by (unfold Sup_less_def, rule Sup_assertion, auto)\n\ntheorem omega_lfp: \n  \"x ^ \\<omega> * y = lfp (\\<lambda> z . (x * z) \\<sqinter> y)\"\n  apply (rule antisym)\n  apply (rule lfp_greatest)\n  apply (drule omega_least, simp)\n  apply (rule lfp_lowerbound)\n  apply (subst (2) omega_fix)\n  by (simp add: inf_comp mult.assoc)\nend\n\nlemma [simp]: \"mono (\\<lambda> (t::'a::mbt_algebra) . x * t \\<sqinter> y)\"\n  apply (simp add: mono_def, safe)\n  apply (rule_tac y = \"x * xa\" in order_trans, simp)\n  by (rule le_comp, simp)\n\n\nclass mbt_algebra_fusion = mbt_algebra +\n  assumes fusion: \"(\\<forall> t . x * t \\<sqinter> y \\<sqinter> z \\<le> u * (t \\<sqinter> z) \\<sqinter> v)\n          \\<Longrightarrow> (x ^ \\<omega>) * y \\<sqinter> z \\<le> (u ^ \\<omega>) * v \"\n\nlemma \n    \"class.mbt_algebra_fusion (1::'a::complete_mbt_algebra) (op *) (op \\<sqinter>) (op \\<le>) (op <) (op \\<squnion>) dual dual_star omega star \\<bottom> \\<top>\"\n    apply unfold_locales\n    apply (cut_tac h = \"\\<lambda> t . t \\<sqinter> z\" and f = \"\\<lambda> t . x * t \\<sqinter> y\" and g = \"\\<lambda> t . u * t \\<sqinter> v\" in weak_fusion)\n    apply (rule inf_Disj)\n    apply simp_all\n    apply (simp add: le_fun_def)\n    by  (simp add: omega_lfp)\n\ncontext mbt_algebra_fusion\nbegin\n\n\n\nlemma omega_pres_conj: \"x \\<in> conjunctive \\<Longrightarrow> x ^ \\<omega> \\<in> conjunctive\"\n  apply (subst omega_star, simp)\n  apply (rule comp_pres_conj)\n  apply (rule assertion_conjunctive, simp)\n  by (rule start_pres_conj, simp)\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/MonoBoolTranAlgebra/Mono_Bool_Tran_Algebra.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511579973931, "lm_q2_score": 0.8221891327004133, "lm_q1q2_score": 0.703671521314521}}
{"text": "(*  Title:      HOL/Metis_Examples/Trans_Closure.thy\n    Author:     Lawrence C. Paulson, Cambridge University Computer Laboratory\n    Author:     Jasmin Blanchette, TU Muenchen\n\nMetis example featuring the transitive closure.\n*)\n\nsection \\<open>Metis Example Featuring the Transitive Closure\\<close>\n\ntheory Trans_Closure\nimports MainRLT\nbegin\n\ndeclare [[metis_new_skolem]]\n\ntype_synonym addr = nat\n\ndatatype val\n  = Unit        \\<comment> \\<open>dummy result value of void expressions\\<close>\n  | Null        \\<comment> \\<open>null reference\\<close>\n  | Bool bool   \\<comment> \\<open>Boolean value\\<close>\n  | Intg int    \\<comment> \\<open>integer value\\<close>\n  | Addr addr   \\<comment> \\<open>addresses of objects in the heap\\<close>\n\nconsts R :: \"(addr \\<times> addr) set\"\n\nconsts f :: \"addr \\<Rightarrow> val\"\n\nlemma \"\\<lbrakk>f c = Intg x; \\<forall>y. f b = Intg y \\<longrightarrow> y \\<noteq> x; (a, b) \\<in> R\\<^sup>*; (b, c) \\<in> R\\<^sup>*\\<rbrakk>\n       \\<Longrightarrow> \\<exists>c. (b, c) \\<in> R \\<and> (a, c) \\<in> R\\<^sup>*\"\n(* sledgehammer *)\nproof -\n  assume A1: \"f c = Intg x\"\n  assume A2: \"\\<forall>y. f b = Intg y \\<longrightarrow> y \\<noteq> x\"\n  assume A3: \"(a, b) \\<in> R\\<^sup>*\"\n  assume A4: \"(b, c) \\<in> R\\<^sup>*\"\n  have F1: \"f c \\<noteq> f b\" using A2 A1 by metis\n  have F2: \"\\<forall>u. (b, u) \\<in> R \\<longrightarrow> (a, u) \\<in> R\\<^sup>*\" using A3 by (metis transitive_closure_trans(6))\n  have F3: \"\\<exists>x. (b, x b c R) \\<in> R \\<or> c = b\" using A4 by (metis converse_rtranclE)\n  have \"c \\<noteq> b\" using F1 by metis\n  hence \"\\<exists>u. (b, u) \\<in> R\" using F3 by metis\n  thus \"\\<exists>c. (b, c) \\<in> R \\<and> (a, c) \\<in> R\\<^sup>*\" using F2 by metis\nqed\n\nlemma \"\\<lbrakk>f c = Intg x; \\<forall>y. f b = Intg y \\<longrightarrow> y \\<noteq> x; (a, b) \\<in> R\\<^sup>*; (b,c) \\<in> R\\<^sup>*\\<rbrakk>\n       \\<Longrightarrow> \\<exists>c. (b, c) \\<in> R \\<and> (a, c) \\<in> R\\<^sup>*\"\n(* sledgehammer [isar_proofs, compress = 2] *)\nproof -\n  assume A1: \"f c = Intg x\"\n  assume A2: \"\\<forall>y. f b = Intg y \\<longrightarrow> y \\<noteq> x\"\n  assume A3: \"(a, b) \\<in> R\\<^sup>*\"\n  assume A4: \"(b, c) \\<in> R\\<^sup>*\"\n  have \"b \\<noteq> c\" using A1 A2 by metis\n  hence \"\\<exists>x\\<^sub>1. (b, x\\<^sub>1) \\<in> R\" using A4 by (metis converse_rtranclE)\n  thus \"\\<exists>c. (b, c) \\<in> R \\<and> (a, c) \\<in> R\\<^sup>*\" using A3 by (metis transitive_closure_trans(6))\nqed\n\nlemma \"\\<lbrakk>f c = Intg x; \\<forall>y. f b = Intg y \\<longrightarrow> y \\<noteq> x; (a, b) \\<in> R\\<^sup>*; (b, c) \\<in> R\\<^sup>*\\<rbrakk>\n       \\<Longrightarrow> \\<exists>c. (b, c) \\<in> R \\<and> (a, c) \\<in> R\\<^sup>*\"\napply (erule_tac x = b in converse_rtranclE)\n apply metis\nby (metis transitive_closure_trans(6))\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/Trans_Closure.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511579973931, "lm_q2_score": 0.822189121808099, "lm_q1q2_score": 0.7036715119923213}}
{"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.*)\n  theory TIP_prop_30\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 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\nfun t2 :: \"Nat => Nat => bool\" where\n  \"t2 y (Z) = False\"\n| \"t2 (Z) (S z2) = True\"\n| \"t2 (S x2) (S z2) = t2 x2 z2\"\n  (*t2 x y = x < y*)\n\nfun ins :: \"Nat => Nat list => Nat list\" where\n  \"ins y (nil2) = cons2 y (nil2)\"\n| \"ins y (cons2 z2 xs) =\n     (if t2 y z2 then cons2 y (cons2 z2 xs) else cons2 z2 (ins y xs))\"\n\ntheorem property0 :\n  \"elem y (ins y xs)\"\n  (*why induction on \"xs\" instead of y?\n    Because the innermost recursive function, ins, is defined with the case distinction\n    on the second argument.\n    Because \"y\" appears in two different places.*)\n  apply(induct xs (*arbitrary: y*))(*generalization is optional.*)\n   apply clarsimp\n   apply(induct_tac y)\n    apply auto[1]\n   apply auto[1]\n  apply clarsimp(*This clarsimp uses the induction hypothesis.*)\n    (*without the meta-universal quantifier the following induction becomes unnecessarily hard.*)\n    (*Why \"\\<And>y. x y y\"?\n      because of \"\\<not> x y y\" in the premises.*)\n  apply(subgoal_tac \"\\<And>y. x y y\")\n   apply fastforce\n  apply(induct_tac ya)\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/UR/TIP_with_Proof/Isaplanner/Isaplanner/TIP_prop_30.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.855851154320682, "lm_q2_score": 0.822189123986562, "lm_q1q2_score": 0.7036715108338094}}
{"text": "(*  \n    Author:      Ren\u00e9 Thiemann \n                 Akihisa Yamada\n    License:     BSD\n*)\nsection \\<open>Matrix Kernel\\<close>\n\ntext \\<open>We define the kernel of a matrix $A$ and prove the following properties.\n\n\\begin{itemize}\n\\item The kernel stays invariant when multiplying $A$ with an invertible matrix from the left.\n\\item The dimension of the kernel stays invariant when \n  multiplying $A$ with an invertible matrix from the right.\n\\item The function find-base-vectors returns a basis of the kernel if $A$ is in row-echelon form.\n\\item The dimension of the kernel of a block-diagonal matrix is the sum of the dimensions of\n  the kernels of the blocks.\n\\item There is an executable algorithm which computes the dimension of the kernel of a matrix\n  (which just invokes Gauss-Jordan and then counts the number of pivot elements).\n\\end{itemize}\n\\<close>\n\ntheory Matrix_Kernel\nimports \n  VS_Connect\n  Missing_VectorSpace\n  Determinant\nbegin\n\nhide_const real_vector.span\nhide_const (open) Real_Vector_Spaces.span\nhide_const real_vector.dim\nhide_const (open) Real_Vector_Spaces.dim\n\ndefinition mat_kernel :: \"'a :: comm_ring_1 mat \\<Rightarrow> 'a vec set\" where\n  \"mat_kernel A = { v . v \\<in> carrier_vec (dim_col A) \\<and> A *\\<^sub>v v = 0\\<^sub>v (dim_row A)}\"\n\nlemma mat_kernelI: assumes \"A \\<in> carrier_mat nr nc\" \"v \\<in> carrier_vec nc\" \"A *\\<^sub>v v = 0\\<^sub>v nr\"\n  shows \"v \\<in> mat_kernel A\"\n  using assms unfolding mat_kernel_def by auto\n\nlemma mat_kernelD: assumes \"A \\<in> carrier_mat nr nc\" \"v \\<in> mat_kernel A\"\n  shows \"v \\<in> carrier_vec nc\" \"A *\\<^sub>v v = 0\\<^sub>v nr\"\n  using assms unfolding mat_kernel_def by auto\n\nlemma mat_kernel: assumes \"A \\<in> carrier_mat nr nc\" \n  shows \"mat_kernel A = {v. v \\<in> carrier_vec nc \\<and> A *\\<^sub>v v = 0\\<^sub>v nr}\"\n  unfolding mat_kernel_def using assms by auto\n\nlemma mat_kernel_carrier:\n  assumes \"A \\<in> carrier_mat nr nc\" shows \"mat_kernel A \\<subseteq> carrier_vec nc\"\n  using assms mat_kernel by auto\n\nlemma mat_kernel_mult_subset: assumes A: \"A \\<in> carrier_mat nr nc\"\n  and B: \"B \\<in> carrier_mat n nr\"\n  shows \"mat_kernel A \\<subseteq> mat_kernel (B * A)\"\nproof -\n  from A B have BA: \"B * A \\<in> carrier_mat n nc\" by auto\n  show ?thesis unfolding mat_kernel[OF BA] mat_kernel[OF A] using A B by auto\nqed\n\n\n\nlemma mat_kernel_mult_eq: assumes A: \"A \\<in> carrier_mat nr nc\"\n  and B: \"B \\<in> carrier_mat nr nr\"\n  and C: \"C \\<in> carrier_mat nr nr\"\n  and inv: \"C * B = 1\\<^sub>m nr\"\n  shows \"mat_kernel (B * A) = mat_kernel A\"\nproof \n  from B A have BA: \"B * A \\<in> carrier_mat nr nc\" by auto\n  show \"mat_kernel A \\<subseteq> mat_kernel (B * A)\" by (rule mat_kernel_mult_subset[OF A B])\n  {\n    fix v\n    assume v: \"v \\<in> mat_kernel (B * A)\"\n    from mat_kernelD[OF BA this] have v: \"v \\<in> carrier_vec nc\" and z: \"B * A *\\<^sub>v v = 0\\<^sub>v nr\" by auto\n    from arg_cong[OF z, of \"\\<lambda> v. C *\\<^sub>v v\"] \n    have \"C *\\<^sub>v (B * A *\\<^sub>v v) = 0\\<^sub>v nr\" using C v by auto\n    also have \"C *\\<^sub>v (B * A *\\<^sub>v v) = ((C * B) * A) *\\<^sub>v v\" \n      unfolding assoc_mult_mat_vec[symmetric, OF C BA v]    \n      unfolding assoc_mult_mat[OF C B A] by simp\n    also have \"\\<dots> = A *\\<^sub>v v\" unfolding inv using A v by auto\n    finally have \"v \\<in> mat_kernel A\"\n      by (intro mat_kernelI[OF A v])\n  }\n  thus \"mat_kernel (B * A) \\<subseteq> mat_kernel A\" by auto\nqed\n\nlocale kernel =\n  fixes nr :: nat\n    and nc :: nat\n    and A :: \"'a :: field mat\"\n  assumes A: \"A \\<in> carrier_mat nr nc\"\nbegin\n\nsublocale NC: vec_space \"TYPE('a)\" nc .\n\nabbreviation \"VK \\<equiv> NC.V\\<lparr>carrier := mat_kernel A\\<rparr>\"\n\nsublocale Ker: vectorspace class_ring VK \n  rewrites \"carrier VK = mat_kernel A\"\n    and [simp]: \"add VK = (+)\"\n    and [simp]: \"zero VK = 0\\<^sub>v nc\"\n    and [simp]: \"module.smult VK = (\\<cdot>\\<^sub>v)\"\n    and \"carrier class_ring = UNIV\"\n    and \"monoid.mult class_ring = (*)\"\n    and \"add class_ring = (+)\"\n    and \"one class_ring = 1\"\n    and \"zero class_ring = 0\"\n    and \"a_inv (class_ring :: 'a ring) = uminus\"\n    and \"a_minus (class_ring :: 'a ring) = minus\"\n    and \"pow (class_ring :: 'a ring) = (^)\"\n    and \"finsum (class_ring :: 'a ring) = sum\"\n    and \"finprod (class_ring :: 'a ring) = prod\"\n    and \"m_inv (class_ring :: 'a ring) x = (if x = 0 then div0 else inverse x)\"\n  apply (intro vectorspace.intro)\n  apply (rule NC.submodule_is_module)\n  apply (unfold_locales)\n  by (insert A mult_add_distrib_mat_vec[OF A] mult_mat_vec[OF A] mat_kernel[OF A], auto simp: class_ring_simps)\n\nabbreviation \"basis \\<equiv> Ker.basis\"\nabbreviation \"span \\<equiv> Ker.span\"\nabbreviation \"lincomb \\<equiv> Ker.lincomb\"\nabbreviation \"dim \\<equiv> Ker.dim\"\nabbreviation \"lin_dep \\<equiv> Ker.lin_dep\"\nabbreviation \"lin_indpt \\<equiv> Ker.lin_indpt\"\nabbreviation \"gen_set \\<equiv> Ker.gen_set\"\n\nlemma finsum_same:\n  assumes \"f : S \\<rightarrow> mat_kernel A\"\n  shows \"finsum VK f S = finsum NC.V f S\"\n  using assms\nproof (induct S rule: infinite_finite_induct)\n  case (insert s S)\n    hence base: \"finite S\" \"s \\<notin> S\"\n      and f_VK: \"f : S \\<rightarrow> mat_kernel A\" \"f s : mat_kernel A\" by auto\n    hence f_NC: \"f : S \\<rightarrow> carrier_vec nc\" \"f s : carrier_vec nc\" using mat_kernel[OF A] by auto\n    have IH: \"finsum VK f S = finsum NC.V f S\" using insert f_VK by auto\n    thus ?case\n      unfolding NC.M.finsum_insert[OF base f_NC]\n      unfolding Ker.finsum_insert[OF base f_VK]\n      by simp\nqed auto\n\nlemma lincomb_same:\n  assumes S_kernel: \"S \\<subseteq> mat_kernel A\"\n  shows \"lincomb a S = NC.lincomb a S\"\n  unfolding Ker.lincomb_def\n  unfolding NC.lincomb_def\n  apply(subst finsum_same)\n  using S_kernel Ker.smult_closed[unfolded module_vec_simps class_ring_simps] by auto\n\nlemma span_same:\n  assumes S_kernel: \"S \\<subseteq> mat_kernel A\"\n  shows \"span S = NC.span S\"\nproof (rule;rule)\n  fix v assume L: \"v : span S\" show \"v : NC.span S\"\n  proof -\n    obtain a U where know: \"finite U\" \"U \\<subseteq> S\" \"a : U \\<rightarrow> UNIV\" \"v = lincomb a U\"\n      using L unfolding Ker.span_def by auto\n    hence v: \"v = NC.lincomb a U\" using lincomb_same S_kernel by auto\n    show ?thesis\n      unfolding NC.span_def by (rule,intro exI conjI;fact)\n  qed\n  next fix v assume R: \"v : NC.span S\" show \"v : span S\"\n  proof -\n    obtain a U where know: \"finite U\" \"U \\<subseteq> S\" \"v = NC.lincomb a U\"\n      using R unfolding NC.span_def by auto\n    hence v: \"v = lincomb a U\" using lincomb_same S_kernel by auto\n    show ?thesis unfolding Ker.span_def by (rule, intro exI conjI, insert v know, auto)\n  qed\nqed\n\nlemma lindep_same:\n  assumes S_kernel: \"S \\<subseteq> mat_kernel A\"\n  shows \"Ker.lin_dep S = NC.lin_dep S\"\nproof\n  note [simp] = module_vec_simps class_ring_simps\n  { assume L: \"Ker.lin_dep S\"\n    then obtain v a U\n    where finU: \"finite U\" and US: \"U \\<subseteq> S\"\n      and lc: \"lincomb a U = 0\\<^sub>v nc\"\n      and vU: \"v \\<in> U\"\n      and av0: \"a v \\<noteq> 0\"\n      unfolding Ker.lin_dep_def by auto\n    have lc': \"NC.lincomb a U = 0\\<^sub>v nc\"\n      using lc lincomb_same US S_kernel by auto\n    show \"NC.lin_dep S\" unfolding NC.lin_dep_def\n      by (intro exI conjI, insert finU US lc' vU av0, auto)\n  }\n  assume R: \"NC.lin_dep S\"\n  then obtain v a U\n  where finU: \"finite U\" and US: \"U \\<subseteq> S\"\n    and lc: \"NC.lincomb a U = 0\\<^sub>v nc\"\n    and vU: \"v : U\"\n    and av0: \"a v \\<noteq> 0\"\n    unfolding NC.lin_dep_def by auto\n  have lc': \"lincomb a U = zero VK\"\n    using lc lincomb_same US S_kernel by auto\n  show \"Ker.lin_dep S\" unfolding Ker.lin_dep_def\n    by (intro exI conjI,insert finU US lc' vU av0, auto)\nqed\n\nlemma lincomb_index:\n  assumes i: \"i < nc\"\n    and Xk: \"X \\<subseteq> mat_kernel A\"\n  shows \"lincomb a X $ i = sum (\\<lambda>x. a x * x $ i) X\"\nproof -\n  have X: \"X \\<subseteq> carrier_vec nc\" using Xk mat_kernel_def A by auto\n  show ?thesis\n    using vec_space.lincomb_index[OF i X]\n    using lincomb_same[OF Xk] by auto\nqed\n\nend\n\n\n\n\ndefinition kernel_dim :: \"'a :: field mat \\<Rightarrow> nat\" where\n  [code del]: \"kernel_dim A = kernel.dim (dim_col A) A\"\n\nlemma (in kernel) kernel_dim [simp]: \"kernel_dim A = dim\" unfolding kernel_dim_def\n  using A by simp\n\nlemma kernel_dim_code[code]: \n  \"kernel_dim A = dim_col A - length (pivot_positions (gauss_jordan_single A))\"\nproof -\n  define nr where \"nr = dim_row A\" \n  define nc where \"nc = dim_col A\"\n  let ?B = \"gauss_jordan_single A\"\n  have A: \"A \\<in> carrier_mat nr nc\" unfolding nr_def nc_def by auto\n  from gauss_jordan_single[OF A refl]\n    obtain P Q where AB: \"?B = P * A\" and QP: \"Q * P = 1\\<^sub>m nr\" and\n    P: \"P \\<in> carrier_mat nr nr\" and Q: \"Q \\<in> carrier_mat nr nr\" and B: \"?B \\<in> carrier_mat nr nc\" \n    and row: \"row_echelon_form ?B\" by auto\n  interpret K: kernel nr nc ?B\n    by (unfold_locales, rule B)\n  from mat_kernel_mult_eq[OF A P Q QP, folded AB]\n  have \"kernel_dim A = K.dim\" unfolding kernel_dim_def using A by simp\n  also have \"\\<dots> = nc - length (pivot_positions ?B)\" using find_base_vectors[OF row B] by auto\n  also have \"\\<dots> = dim_col A - length (pivot_positions ?B)\"\n    unfolding nc_def by simp\n  finally show ?thesis .\nqed\n\n\nlemma kernel_one_mat: fixes A :: \"'a :: field mat\" and n :: nat\n  defines A: \"A \\<equiv> 1\\<^sub>m n\"\n  shows \n    \"kernel.dim n A = 0\"\n    \"kernel.basis n A {}\"\nproof -\n  have Ac: \"A \\<in> carrier_mat n n\" unfolding A by auto\n  have \"pivot_fun A id n\"\n    unfolding A by (rule pivot_funI, auto)\n  hence row: \"row_echelon_form A\" unfolding row_echelon_form_def A by auto\n  have \"{i. i < n \\<and> row A i \\<noteq> 0\\<^sub>v n} = {0 ..< n}\" unfolding A by auto\n  hence id: \"card {i. i < n \\<and> row A i \\<noteq> 0\\<^sub>v n} = n\" by auto\n  interpret kernel n n A by (unfold_locales, rule Ac)\n  from find_base_vectors[OF row Ac, unfolded id]\n  show \"dim = 0\" \"basis {}\" by auto\nqed\n\nlemma kernel_upper_triangular: assumes A: \"A \\<in> carrier_mat n n\"\n  and ut: \"upper_triangular A\" and 0: \"0 \\<notin> set (diag_mat A)\"\n  shows \"kernel.dim n A = 0\" \"kernel.basis n A {}\"\nproof -\n  define ma where \"ma = diag_mat A\"\n  from det_upper_triangular[OF ut A] have \"det A = prod_list (diag_mat A)\" .\n  also have \"\\<dots> \\<noteq> 0\" using 0 unfolding ma_def[symmetric]\n    by (induct ma, auto)\n  finally have \"det A \\<noteq> 0\" .\n  from det_non_zero_imp_unit[OF A this, unfolded Units_def, of \"()\"]\n    obtain B where B: \"B \\<in> carrier_mat n n\" and BA: \"B * A = 1\\<^sub>m n\" and AB: \"A * B = 1\\<^sub>m n\"\n    by (auto simp: ring_mat_def)\n  from mat_kernel_mult_eq[OF A B A AB, unfolded BA]\n  have id: \"mat_kernel A = mat_kernel (1\\<^sub>m n)\" ..\n  show \"kernel.dim n A = 0\" \"kernel.basis n A {}\"\n    unfolding id by (rule kernel_one_mat)+\nqed\n\nlemma kernel_basis_exists: assumes A: \"A \\<in> carrier_mat nr nc\"\n  shows \"\\<exists> B. finite B \\<and> kernel.basis nc A B\"\nproof -\n  obtain C where gj: \"gauss_jordan_single A = C\" by auto\n  from gauss_jordan_single[OF A gj]\n  obtain P Q where CPA: \"C = P * A\" and QP: \"Q * P = 1\\<^sub>m nr\"\n    and P: \"P \\<in> carrier_mat nr nr\" and Q: \"Q \\<in> carrier_mat nr nr\"   \n    and C: \"C \\<in> carrier_mat nr nc\" and row: \"row_echelon_form C\"\n    by auto\n  from find_base_vectors[OF row C] have \"\\<exists> B. finite B \\<and> kernel.basis nc C B\" by blast\n  also have \"mat_kernel C = mat_kernel A\" unfolding CPA\n    by (rule mat_kernel_mult_eq[OF A P Q QP])\n  finally show ?thesis .\nqed\n\n\nlemma mat_kernel_mult_right_gen_set: assumes A: \"A \\<in> carrier_mat nr nc\"\n  and B: \"B \\<in> carrier_mat nc nc\"\n  and C: \"C \\<in> carrier_mat nc nc\"\n  and inv: \"B * C = 1\\<^sub>m nc\"\n  and gen_set: \"kernel.gen_set nc (A * B) gen\" and gen: \"gen \\<subseteq> mat_kernel (A * B)\"\n  shows \"kernel.gen_set nc A (((*\\<^sub>v) B) ` gen)\" \"(*\\<^sub>v) B ` gen \\<subseteq> mat_kernel A\" \"card (((*\\<^sub>v) B) ` gen) = card gen\"\nproof -\n  let ?AB = \"A * B\"\n  let ?gen = \"((*\\<^sub>v) B) ` gen\"\n  from A B have AB: \"A * B \\<in> carrier_mat nr nc\" by auto\n  from B have dimB: \"dim_row B = nc\" by auto\n  from inv B C have CB: \"C * B = 1\\<^sub>m nc\" by (metis mat_mult_left_right_inverse)\n  interpret AB: kernel nr nc ?AB \n    by (unfold_locales, rule AB)\n  interpret A: kernel nr nc A\n    by (unfold_locales, rule A)\n  {\n    fix w\n    assume \"w \\<in> ?gen\"\n    then obtain v where w: \"w = B *\\<^sub>v v\" and v: \"v \\<in> gen\" by auto\n    from v have \"v \\<in> mat_kernel ?AB\" using gen by auto\n    hence v: \"v \\<in> carrier_vec nc\" and 0: \"?AB *\\<^sub>v v = 0\\<^sub>v nr\" unfolding mat_kernel[OF AB] by auto\n    have \"?AB *\\<^sub>v v = A *\\<^sub>v w\" unfolding w using v A B by simp\n    with 0 have 0: \"A *\\<^sub>v w = 0\\<^sub>v nr\" by auto\n    from w B v have w: \"w \\<in> carrier_vec nc\" by auto\n    from 0 w have \"w \\<in> mat_kernel A\" unfolding mat_kernel[OF A] by auto\n  } \n  thus genn: \"?gen \\<subseteq> mat_kernel A\" by auto\n  hence one_dir: \"A.span ?gen \\<subseteq> mat_kernel A\" by fastforce\n  {\n    fix v v'\n    assume v: \"v \\<in> gen\" and v': \"v' \\<in> gen\" and id: \"B *\\<^sub>v v = B *\\<^sub>v v'\"\n    from v v' have v: \"v \\<in> carrier_vec nc\" and v': \"v' \\<in> carrier_vec nc\" \n      using gen unfolding mat_kernel[OF AB] by auto\n    from arg_cong[OF id, of \"\\<lambda> v. C *\\<^sub>v v\"]\n    have \"v = v'\" using v v'\n      unfolding assoc_mult_mat_vec[symmetric, OF C B v] \n        assoc_mult_mat_vec[symmetric, OF C B v'] CB\n      by auto\n  } note inj = this\n  hence inj_gen: \"inj_on ((*\\<^sub>v) B) gen\" unfolding inj_on_def by auto\n  show \"card ?gen = card gen\" using inj_gen by (rule card_image)\n  {\n    fix v\n    let ?Cv = \"C *\\<^sub>v v\"\n    assume \"v \\<in> mat_kernel A\"\n    from mat_kernelD[OF A this] have v: \"v \\<in> carrier_vec nc\" and 0: \"A *\\<^sub>v v = 0\\<^sub>v nr\" by auto\n    have \"?AB *\\<^sub>v ?Cv = (A * (B * C)) *\\<^sub>v v\" using A B C v \n      by (subst assoc_mult_mat_vec[symmetric, OF AB C v], subst assoc_mult_mat[OF A B C], simp)\n    also have \"\\<dots> = 0\\<^sub>v nr\" unfolding inv using 0 A v by simp\n    finally have 0: \"?AB *\\<^sub>v ?Cv = 0\\<^sub>v nr\" and Cv: \"?Cv \\<in> carrier_vec nc\" using C v by auto\n    hence \"?Cv \\<in> mat_kernel ?AB\" unfolding mat_kernel[OF AB] by auto\n    with gen_set have \"?Cv \\<in> AB.span gen\" by auto\n    from this[unfolded AB.Ker.span_def] obtain a gen' where \n      Cv: \"?Cv = AB.lincomb a gen'\" and sub: \"gen' \\<subseteq> gen\" and fin: \"finite gen'\" by auto\n    let ?gen' = \"((*\\<^sub>v) B) ` gen'\"\n    from sub gen have gen': \"gen' \\<subseteq> mat_kernel ?AB\" by auto\n    have lin1: \"AB.lincomb a gen' \\<in> carrier_vec nc\"\n      using AB.Ker.lincomb_closed[OF gen', of a]\n      unfolding mat_kernel[OF AB] by (auto simp: class_field_def)\n    hence dim1: \"dim_vec (AB.lincomb a gen') = nc\" by auto\n    hence dim1b: \"dim_vec (B *\\<^sub>v (AB.Ker.lincomb a gen')) = nc\" using B by auto\n    from genn sub have genn': \"?gen' \\<subseteq> mat_kernel A\" by auto\n    from gen sub have gen'nc: \"gen' \\<subseteq> carrier_vec nc\" unfolding mat_kernel[OF AB] by auto\n    define a' where \"a' = (\\<lambda> b. a (C *\\<^sub>v b))\"\n    from A.Ker.lincomb_closed[OF genn']\n    have lin2: \"A.Ker.lincomb a' ?gen' \\<in> carrier_vec nc\"\n      unfolding mat_kernel[OF A] by (auto simp: class_field_def)\n    hence dim2: \"dim_vec (A.Ker.lincomb a' ?gen') = nc\" by auto\n    have \"v = B *\\<^sub>v ?Cv\" \n      by (unfold assoc_mult_mat_vec[symmetric, OF B C v] inv, insert v, simp)\n    hence \"v = B *\\<^sub>v AB.Ker.lincomb a gen'\" unfolding Cv by simp\n    also have \"\\<dots> = A.Ker.lincomb a' ?gen'\"\n    proof (rule eq_vecI; unfold dim1 dim1b dim2)\n      fix i\n      assume i: \"i < nc\"\n      with dimB have ii: \"i < dim_row B\" by auto\n      from sub inj have inj: \"inj_on ((*\\<^sub>v) B) gen'\" unfolding inj_on_def by auto\n      {\n        fix v\n        assume \"v \\<in> gen'\"\n        with gen'nc have v: \"v \\<in> carrier_vec nc\" by auto\n        hence \"a' (B *\\<^sub>v v) = a v\" unfolding a'_def assoc_mult_mat_vec[symmetric, OF C B v] CB by auto\n      } note a' = this\n      have \"A.Ker.lincomb a' ?gen' $ i = (\\<Sum>v\\<in>(*\\<^sub>v) B ` gen'. a' v * v $ i)\"\n        unfolding A.lincomb_index[OF i genn']  by simp\n      also have \"\\<dots> = (\\<Sum>v\\<in>gen'. a v * ((B *\\<^sub>v v) $ i))\"\n        by (rule sum.reindex_cong[OF inj refl], auto simp: a')\n      also have \"\\<dots> = (\\<Sum>v\\<in>gen'. (\\<Sum>j = 0..< nc. a v * row B i $ j * v $ j))\"\n        unfolding mult_mat_vec_def dimB scalar_prod_def index_vec[OF i]\n        by (rule sum.cong, insert gen'nc, auto simp: sum_distrib_left ac_simps)\n      also have \"\\<dots> = (\\<Sum>j = 0 ..< nc. (\\<Sum>v \\<in> gen'. a v * row B i $ j * v $ j))\"\n        by (rule sum.swap)\n      also have \"\\<dots> = (\\<Sum>j = 0..<nc. row B i $ j * (\\<Sum>v\\<in>gen'. a v * v $ j))\"\n        by (rule sum.cong, auto simp: sum_distrib_left ac_simps)\n      also have \"\\<dots> = (B *\\<^sub>v AB.Ker.lincomb a gen') $ i\"\n        unfolding index_mult_mat_vec[OF ii]\n        unfolding scalar_prod_def dim1\n        by (rule sum.cong[OF refl], subst AB.lincomb_index[OF _ gen'], auto)\n      finally show \"(B *\\<^sub>v AB.Ker.lincomb a gen') $ i = A.Ker.lincomb a' ?gen' $ i\" ..\n    qed auto\n    finally have \"v \\<in> A.Ker.span ?gen\" using sub fin\n      unfolding A.Ker.span_def by (auto simp: class_field_def intro!: exI[of _ a'] exI[of _ ?gen'])\n  }\n  hence other_dir: \"A.Ker.span ?gen \\<supseteq> mat_kernel A\" by fastforce\n  from one_dir other_dir show \"kernel.gen_set nc A (((*\\<^sub>v) B) ` gen)\" by auto\nqed\n\nlemma mat_kernel_mult_right_basis: assumes A: \"A \\<in> carrier_mat nr nc\"\n  and B: \"B \\<in> carrier_mat nc nc\"\n  and C: \"C \\<in> carrier_mat nc nc\"\n  and inv: \"B * C = 1\\<^sub>m nc\"\n  and fin: \"finite gen\"\n  and basis: \"kernel.basis nc (A * B) gen\"\n  shows \"kernel.basis nc A (((*\\<^sub>v) B) ` gen)\" \n  \"card (((*\\<^sub>v) B) ` gen) = card gen\"\nproof -\n  let ?AB = \"A * B\"\n  let ?gen = \"((*\\<^sub>v) B) ` gen\"\n  from A B have AB: \"?AB \\<in> carrier_mat nr nc\" by auto\n  from B have dimB: \"dim_row B = nc\" by auto\n  from inv B C have CB: \"C * B = 1\\<^sub>m nc\" by (metis mat_mult_left_right_inverse)\n  interpret AB: kernel nr nc ?AB \n    by (unfold_locales, rule AB)\n  interpret A: kernel nr nc A\n    by (unfold_locales, rule A)\n  from basis[unfolded AB.Ker.basis_def] have gen_set: \"AB.gen_set gen\" and genAB: \"gen \\<subseteq> mat_kernel ?AB\" by auto\n  from mat_kernel_mult_right_gen_set[OF A B C inv gen_set genAB]\n  have gen: \"A.gen_set ?gen\" and sub: \"?gen \\<subseteq> mat_kernel A\" and card: \"card ?gen = card gen\" .\n  from card show \"card ?gen = card gen\" .\n  from fin have fing: \"finite ?gen\" by auto\n  from gen have gen: \"A.Ker.span ?gen = mat_kernel A\" by auto\n  have ABC: \"A * B * C = A\" using A B C inv by simp\n  from kernel_basis_exists[OF A] obtain bas where finb: \"finite bas\" and bas: \"A.basis bas\" by auto\n  from bas have bas': \"A.gen_set bas\" \"bas \\<subseteq> mat_kernel A\" unfolding A.Ker.basis_def by auto\n  let ?bas = \"(*\\<^sub>v) C ` bas\"\n  from mat_kernel_mult_right_gen_set[OF AB C B CB, unfolded ABC, OF bas']\n  have bas': \"?bas \\<subseteq> mat_kernel ?AB\" \"AB.Ker.span ?bas = mat_kernel ?AB\" \"card ?bas = card bas\" by auto\n  from finb bas have cardb: \"A.dim = card bas\" by (rule A.Ker.dim_basis)\n  from fin basis have cardg: \"AB.dim = card gen\" by (rule AB.Ker.dim_basis)\n  from AB.Ker.gen_ge_dim[OF _ bas'(1-2)] finb bas'(3) cardb cardg\n  have ineq1: \"card gen \\<le> A.dim\" by auto\n  from A.Ker.dim_gen_is_basis[OF fing sub gen, unfolded card, OF this]\n  show \"A.basis ?gen\" .\nqed  \n  \n  \nlemma mat_kernel_dim_mult_eq_right: assumes A: \"A \\<in> carrier_mat nr nc\"\n  and B: \"B \\<in> carrier_mat nc nc\"\n  and C: \"C \\<in> carrier_mat nc nc\"\n  and BC: \"B * C = 1\\<^sub>m nc\"\n  shows \"kernel.dim nc (A * B) = kernel.dim nc A\"\nproof -\n  let ?AB = \"A * B\"\n  from A B have AB: \"?AB \\<in> carrier_mat nr nc\" by auto\n  interpret AB: kernel nr nc ?AB \n    by (unfold_locales, rule AB)\n  interpret A: kernel nr nc A\n    by (unfold_locales, rule A)\n  from kernel_basis_exists[OF AB] obtain bas where finb: \"finite bas\" and bas: \"AB.basis bas\" by auto\n  let ?bas = \"((*\\<^sub>v) B) ` bas\"\n  from mat_kernel_mult_right_basis[OF A B C BC finb bas] finb\n  have bas': \"A.basis ?bas\" and finb': \"finite ?bas\" and card: \"card ?bas = card bas\" by auto\n  show \"AB.dim = A.dim\" unfolding A.Ker.dim_basis[OF finb' bas'] AB.Ker.dim_basis[OF finb bas] card ..\nqed\n\n\nlocale vardim =\n  fixes f_ty :: \"'a :: field itself\"\nbegin\n\nabbreviation \"M == \\<lambda>k. module_vec TYPE('a) k\"\n\nabbreviation \"span == \\<lambda>k. LinearCombinations.module.span class_ring (M k)\"\nabbreviation \"lincomb == \\<lambda>k. module.lincomb (M k)\"\nabbreviation \"lin_dep == \\<lambda>k. module.lin_dep class_ring (M k)\"\nabbreviation \"padr m v == v @\\<^sub>v 0\\<^sub>v m\"\ndefinition \"unpadr m v == vec (dim_vec v - m) (\\<lambda>i. v $ i)\"\nabbreviation \"padl m v == 0\\<^sub>v m @\\<^sub>v v\"\ndefinition \"unpadl m v == vec (dim_vec v - m) (\\<lambda>i. v $ (m+i))\"\n\nlemma unpadr_padr[simp]: \"unpadr m (padr m v) = v\" unfolding unpadr_def by auto\nlemma unpadl_padl[simp]: \"unpadl m (padl m v) = v\" unfolding unpadl_def by auto\n\nlemma padr_unpadr[simp]: \"v : padr m ` U \\<Longrightarrow> padr m (unpadr m v) = v\" by auto\nlemma padl_unpadl[simp]: \"v : padl m ` U \\<Longrightarrow> padl m (unpadl m v) = v\" by auto\n\n(* somehow not automatically proven *)\nlemma padr_image:\n  assumes \"U \\<subseteq> carrier_vec n\" shows \"padr m ` U \\<subseteq> carrier_vec (n + m)\"\nproof(rule subsetI)\n  fix v assume \"v : padr m ` U\"\n  then obtain u where \"u : U\" and vmu: \"v = padr m u\" by auto\n  hence \"u : carrier_vec n\" using assms by auto\n  thus \"v : carrier_vec (n + m)\"\n    unfolding vmu\n    using zero_carrier_vec[of m] append_carrier_vec by metis\nqed\n\n\nlemma padr_inj:\n  shows \"inj_on (padr m) (carrier_vec n :: 'a vec set)\"\n  apply(intro inj_onI) using append_vec_eq by auto\n\nlemma padl_inj:\n  shows \"inj_on (padl m) (carrier_vec n :: 'a vec set)\"\n  apply(intro inj_onI)\n  using append_vec_eq[OF zero_carrier_vec zero_carrier_vec] by auto\n\nlemma lincomb_pad:\n  fixes m n a\n  assumes U: \"(U :: 'a vec set) \\<subseteq> carrier_vec n\"\n      and finU: \"finite U\"\n  defines \"goal pad unpad W == pad m (lincomb n a W) = lincomb (n+m) (a o unpad m) (pad m ` W)\"\n  shows \"goal padr unpadr U\" (is ?R) and \"goal padl unpadl U\" (is \"?L\")\nproof -\n  interpret N: vectorspace class_ring \"M n\" using vec_vs.\n  interpret NM: vectorspace class_ring \"M (n+m)\" using vec_vs.\n  note [simp] = module_vec_simps class_ring_simps\n  have \"?R \\<and> ?L\" using finU U\n  proof (induct set:finite)\n    case empty thus ?case\n      unfolding goal_def unfolding N.lincomb_def NM.lincomb_def by auto next\n    case (insert u U)\n      hence finU: \"finite U\"\n        and U: \"U \\<subseteq> carrier_vec n\"\n        and u[simp]: \"u : carrier_vec n\"\n        and uU: \"u \\<notin> U\"\n        and auU: \"a : insert u U \\<rightarrow> UNIV\"\n        and aU: \"a : U \\<rightarrow> UNIV\"\n        and au: \"a u : UNIV\"\n        by auto\n      have IHr: \"goal padr unpadr U\" and IHl: \"goal padl unpadl U\"\n        using insert(3) U aU by auto\n      note N_lci = N.lincomb_insert2[unfolded module_vec_simps]\n      note NM_lci = NM.lincomb_insert2[unfolded module_vec_simps]\n      have auu[simp]: \"a u \\<cdot>\\<^sub>v u : carrier_vec n\" using au u by simp\n      have laU[simp]: \"lincomb n a U : carrier_vec n\"\n        using N.lincomb_closed[unfolded module_vec_simps class_ring_simps, OF U aU].\n      let ?m0 = \"0\\<^sub>v m :: 'a vec\"\n      have m0: \"?m0 : carrier_vec m\" by auto\n      have ins: \"lincomb n a (insert u U) = a u \\<cdot>\\<^sub>v u + lincomb n a U\"\n        using N_lci[OF finU U] auU uU u by auto\n      show ?case\n      proof\n        have \"padr m (a u \\<cdot>\\<^sub>v u + lincomb n a U) =\n          (a u \\<cdot>\\<^sub>v u + lincomb n a U) @\\<^sub>v (?m0 + ?m0)\" by auto\n        also have \"... = padr m (a u \\<cdot>\\<^sub>v u) + padr m (lincomb n a U)\"\n          using append_vec_add[symmetric, OF auu laU]\n          using zero_carrier_vec[of m] by metis\n        also have \"padr m (lincomb n a U) = lincomb (n+m) (a o unpadr m) (padr m ` U)\"\n          using IHr unfolding goal_def.\n        also have \"padr m (a u \\<cdot>\\<^sub>v u) = a u \\<cdot>\\<^sub>v padr m u\" by auto\n        also have \"... = (a o unpadr m) (padr m u) \\<cdot>\\<^sub>v padr m u\" by auto\n        also have \"... + lincomb (n+m) (a o unpadr m) (padr m ` U) =\n          lincomb (n+m) (a o unpadr m) (insert (padr m u) (padr m ` U))\"\n          apply(subst NM_lci[symmetric])\n          using finU uU U append_vec_eq[OF u] by auto\n        also have \"insert (padr m u) (padr m ` U) = padr m ` insert u U\"\n          by auto\n        finally show \"goal padr unpadr (insert u U)\" unfolding goal_def ins.\n        have [simp]: \"n+m = m+n\" by auto\n        have \"padl m (a u \\<cdot>\\<^sub>v u + lincomb n a U) =\n          (?m0 + ?m0) @\\<^sub>v (a u \\<cdot>\\<^sub>v u + lincomb n a U)\" by auto\n        also have \"... = padl m (a u \\<cdot>\\<^sub>v u) + padl m (lincomb n a U)\"\n          using append_vec_add[symmetric, OF _ _ auu laU]\n          using zero_carrier_vec[of m] by metis\n        also have \"padl m (lincomb n a U) = lincomb (n+m) (a o unpadl m) (padl m ` U)\"\n          using IHl unfolding goal_def.\n        also have \"padl m (a u \\<cdot>\\<^sub>v u) = a u \\<cdot>\\<^sub>v padl m u\" by auto\n        also have \"... = (a o unpadl m) (padl m u) \\<cdot>\\<^sub>v padl m u\" by auto\n        also have \"... + lincomb (n+m) (a o unpadl m) (padl m ` U) =\n          lincomb (n+m) (a o unpadl m) (insert (padl m u) (padl m ` U))\"\n          apply(subst NM_lci[symmetric])\n          using finU uU U append_vec_eq[OF m0] by auto\n        also have \"insert (padl m u) (padl m ` U) = padl m ` insert u U\"\n          by auto\n        finally show \"goal padl unpadl (insert u U)\" unfolding goal_def ins.\n      qed\n  qed\n  thus ?R ?L by auto\nqed\n\nlemma span_pad:\n  assumes U: \"(U::'a vec set) \\<subseteq> carrier_vec n\"\n  defines \"goal pad m == pad m ` span n U = span (n+m) (pad m ` U)\"\n  shows \"goal padr m\" \"goal padl m\"\nproof -\n  interpret N: vectorspace class_ring \"M n\" using vec_vs.\n  interpret NM: vectorspace class_ring \"M (n+m)\" using vec_vs.\n  { fix pad :: \"'a vec \\<Rightarrow> 'a vec\" and unpad :: \"'a vec \\<Rightarrow> 'a vec\"\n    assume main: \"\\<And>A a. A \\<subseteq> U \\<Longrightarrow> finite A \\<Longrightarrow>\n      pad (lincomb n a A) = lincomb (n+m) (a o unpad) (pad ` A)\"\n    assume [simp]: \"\\<And>v. unpad (pad v) = v\"\n    assume pU: \"pad ` U \\<subseteq> carrier_vec (n+m)\"\n    have \"pad ` (span n U) = span (n+m) (pad ` U)\"\n    proof (intro Set.equalityI subsetI)\n      fix x assume \"x : pad ` (span n U)\"\n      then obtain v where \"v : span n U\" and xv: \"x = pad v\" by auto\n      then obtain a A\n        where AU: \"A \\<subseteq> U\" and finA: \"finite A\" and a: \"a : A \\<rightarrow> UNIV\"\n          and vaA: \"v = lincomb n a A\"\n        unfolding N.span_def by auto\n      hence A: \"A \\<subseteq> carrier_vec n\" using U by auto\n      show \"x : span (n+m) (pad ` U)\" unfolding NM.span_def\n      proof (intro CollectI exI conjI)\n        show \"x = lincomb (n+m) (a o unpad) (pad ` A)\"\n          using xv vaA main[OF AU finA] by auto\n        show \"pad ` A \\<subseteq> pad ` U\" using AU by auto\n      qed (insert finA, auto simp: class_ring_simps)\n      next\n      fix x assume \"x : span (n+m) (pad ` U)\"\n      then obtain a' A'\n        where A'U: \"A' \\<subseteq> pad ` U\" and finA': \"finite A'\" and a': \"a' : A' \\<rightarrow> UNIV\"\n          and xa'A': \"x = lincomb (n+m) a' A'\"\n        unfolding NM.span_def by auto\n      then obtain A where finA: \"finite A\" and AU: \"A \\<subseteq> U\" and A'A: \"A' = pad ` A\"\n        using finite_subset_image[OF finA' A'U] by auto\n      hence A: \"A \\<subseteq> carrier_vec n\" using U by auto\n      have A': \"A' \\<subseteq> carrier_vec (n+m)\" using A'U pU by auto\n      define a where \"a = a' o pad\"\n      define a'' where \"a'' = (a' o pad) o unpad\"\n      have a: \"a : A \\<rightarrow> UNIV\" by auto\n      have restr: \"restrict a' A' = restrict a'' A'\"\n      proof(rule restrict_ext)\n        fix u' assume \"u' : A'\"\n        then obtain u where \"u : A\" and \"u' = pad u\" unfolding A'A by auto\n        thus \"a' u' = a'' u'\" unfolding a''_def a_def by auto\n      qed\n      have \"x = lincomb (n+m) a' A'\" using xa'A' unfolding A'A.\n      also have \"... = lincomb (n+m) a'' A'\"\n        apply (subst NM.lincomb_restrict)\n        using finA' A' restr by (auto simp: module_vec_simps class_ring_simps)\n      also have \"... = lincomb (n+m) a'' (pad ` A)\" unfolding A'A..\n      also have \"... = pad (lincomb n a A)\"\n        unfolding a''_def using main[OF AU finA] unfolding a_def by auto\n      finally show \"x : pad ` (span n U)\" unfolding N.span_def\n      apply(rule image_eqI, intro CollectI exI conjI)\n        using finA AU by (auto simp: class_ring_simps)\n    qed\n  }\n  note main = this\n  have AUC: \"\\<And>A. A \\<subseteq> U \\<Longrightarrow> A \\<subseteq> carrier_vec n\" using U by simp\n  have [simp]: \"n+m = m+n\" by auto\n  show \"goal padr m\" unfolding goal_def\n    apply (subst main[OF _ _ padr_image[OF U]])\n    using lincomb_pad[OF AUC] unpadr_padr by auto\n  show \"goal padl m\" unfolding goal_def\n    apply (subst main)\n    using lincomb_pad[OF AUC] unpadl_padl padl_image[OF U] by auto\nqed\n\nlemma kernel_padr:\n  assumes aA: \"a : mat_kernel (A :: 'a :: field mat)\"\n      and A: \"A : carrier_mat nr1 nc1\"\n      and B: \"B : carrier_mat nr1 nc2\"\n      and D: \"D : carrier_mat nr2 nc2\"\n  shows \"padr nc2 a : mat_kernel (four_block_mat A B (0\\<^sub>m nr2 nc1) D)\" (is \"_ : mat_kernel ?ABCD\")\n  unfolding mat_kernel_def\nproof (rule, intro conjI)\n  have [simp]: \"dim_row A = nr1\" \"dim_row D = nr2\" \"dim_row ?ABCD = nr1 + nr2\" using A D by auto\n  have a: \"a : carrier_vec nc1\" using mat_kernel_carrier[OF A] aA by auto\n  show \"?ABCD *\\<^sub>v padr nc2 a = 0\\<^sub>v (dim_row ?ABCD)\" (is \"?l = ?r\")\n  proof\n    fix i assume i: \"i < dim_vec ?r\"\n    hence \"?l $ i = row ?ABCD i \\<bullet> padr nc2 a\" by auto\n    also have \"... = 0\"\n    proof (cases \"i < nr1\")\n      case True\n        hence rows: \"row A i : carrier_vec nc1\" \"row B i : carrier_vec nc2\"\n          using A B by auto\n        have \"row ?ABCD i = row A i @\\<^sub>v row B i\"\n          using row_four_block_mat(1)[OF A B _ D True] by auto\n        also have \"... \\<bullet> padr nc2 a = row A i \\<bullet> a + row B i \\<bullet> 0\\<^sub>v nc2\"\n          using scalar_prod_append[OF rows] a by auto\n        also have \"row A i \\<bullet> a = (A *\\<^sub>v a) $ i\" using True A by auto\n        also have \"... = 0\" using mat_kernelD[OF A aA] True by auto\n        also have \"row B i \\<bullet> 0\\<^sub>v nc2 = 0\" using True rows by auto\n        finally show ?thesis by simp\n      next case False\n        let ?C = \"0\\<^sub>m nr2 nc1\"\n        let ?i = \"i - nr1\"\n        have rows:\n            \"row ?C ?i : carrier_vec nc1\" \"row D ?i : carrier_vec nc2\"\n          using D i False A by auto\n        have \"row ?ABCD i = row ?C ?i @\\<^sub>v row D ?i\"\n          using row_four_block_mat(2)[OF A B _ D False] i A D by auto\n        also have \"... \\<bullet> padr nc2 a = row ?C ?i \\<bullet> a + row D ?i \\<bullet> 0\\<^sub>v nc2\"\n          using scalar_prod_append[OF rows] a by auto\n        also have \"row ?C ?i \\<bullet> a = 0\\<^sub>v nc1 \\<bullet> a\" using False A i by auto\n        also have \"... = 0\" using a by auto\n        also have \"row D ?i \\<bullet> 0\\<^sub>v nc2 = 0\" using False rows by auto\n        finally show ?thesis by simp\n    qed\n    finally show \"?l $ i = ?r $ i\" using i by auto\n  qed auto\n  show \"padr nc2 a : carrier_vec (dim_col ?ABCD)\" using a A D by auto\nqed\n\nlemma kernel_padl:\n  assumes dD: \"d \\<in> mat_kernel (D :: 'a :: field mat)\"\n      and A: \"A \\<in> carrier_mat nr1 nc1\"\n      and C: \"C \\<in> carrier_mat nr2 nc1\"\n      and D: \"D \\<in> carrier_mat nr2 nc2\"\n  shows \"padl nc1 d \\<in> mat_kernel (four_block_mat A (0\\<^sub>m nr1 nc2) C D)\" (is \"_ \\<in> mat_kernel ?ABCD\")\n  unfolding mat_kernel_def\nproof (rule, intro conjI)\n  have [simp]: \"dim_row A = nr1\" \"dim_row D = nr2\" \"dim_row ?ABCD = nr1 + nr2\" using A D by auto\n  have d: \"d : carrier_vec nc2\" using mat_kernel_carrier[OF D] dD by auto\n  show \"?ABCD *\\<^sub>v padl nc1 d = 0\\<^sub>v (dim_row ?ABCD)\" (is \"?l = ?r\")\n  proof\n    fix i assume i: \"i < dim_vec ?r\"\n    hence \"?l $ i = row ?ABCD i \\<bullet> padl nc1 d\" by auto\n    also have \"... = 0\"\n    proof (cases \"i < nr1\")\n      case True\n        let ?B = \"0\\<^sub>m nr1 nc2\"\n        have rows: \"row A i : carrier_vec nc1\" \"row ?B i : carrier_vec nc2\"\n          using A True by auto\n        have \"row ?ABCD i = row A i @\\<^sub>v row ?B i\"\n          using row_four_block_mat(1)[OF A _ C D True] by auto\n        also have \"... \\<bullet> padl nc1 d = row A i \\<bullet> 0\\<^sub>v nc1 + row ?B i \\<bullet> d\"\n          using scalar_prod_append[OF rows] d by auto\n        also have \"row A i \\<bullet> 0\\<^sub>v nc1 = 0\" using A True by auto\n        also have \"row ?B i \\<bullet> d = 0\" using True d by auto\n        finally show ?thesis by simp\n      next case False\n        let ?i = \"i - nr1\"\n        have rows:\n            \"row C ?i : carrier_vec nc1\" \"row D ?i : carrier_vec nc2\"\n          using C D i False A by auto\n        have \"row ?ABCD i = row C ?i @\\<^sub>v row D ?i\"\n          using row_four_block_mat(2)[OF A _ C D False] i A D by auto\n        also have \"... \\<bullet> padl nc1 d = row C ?i \\<bullet> 0\\<^sub>v nc1 + row D ?i \\<bullet> d\"\n          using scalar_prod_append[OF rows] d by auto\n        also have \"row C ?i \\<bullet> 0\\<^sub>v nc1 = 0\" using False A C i by auto\n        also have \"row D ?i \\<bullet> d = (D *\\<^sub>v d) $ ?i\" using D d False i by auto\n        also have \"... = 0\" using mat_kernelD[OF D dD] using False i by auto\n        finally show ?thesis by simp\n    qed\n    finally show \"?l $ i = ?r $ i\" using i by auto\n  qed auto\n  show \"padl nc1 d : carrier_vec (dim_col ?ABCD)\" using d A D by auto\nqed\n\nlemma mat_kernel_split:\n  assumes A: \"A \\<in> carrier_mat n n\"\n      and D: \"D \\<in> carrier_mat m m\"\n      and kAD: \"k \\<in> mat_kernel (four_block_mat A (0\\<^sub>m n m) (0\\<^sub>m m n) D)\"\n           (is \"_ \\<in> mat_kernel ?A00D\")\n  shows \"vec_first k n \\<in> mat_kernel A\" (is \"?a \\<in> _\")\n    and \"vec_last k m \\<in> mat_kernel D\" (is \"?d \\<in> _\")\nproof -\n  have \"0\\<^sub>v n @\\<^sub>v 0\\<^sub>v m = 0\\<^sub>v (n+m)\" by auto\n  also\n    have A00D: \"?A00D : carrier_mat (n+m) (n+m)\" using four_block_carrier_mat[OF A D].\n    hence k: \"k : carrier_vec (n+m)\" using kAD mat_kernel_carrier by auto\n    hence \"?a @\\<^sub>v ?d = k\" by simp\n    hence \"0\\<^sub>v (n+m) = ?A00D *\\<^sub>v (?a @\\<^sub>v ?d)\" using mat_kernelD[OF A00D] kAD by auto\n  also have \"... = A *\\<^sub>v ?a @\\<^sub>v D *\\<^sub>v ?d\"\n    using mult_mat_vec_split[OF A D] by auto\n  finally have \"0\\<^sub>v n @\\<^sub>v 0\\<^sub>v m = A *\\<^sub>v ?a @\\<^sub>v D *\\<^sub>v ?d\".\n  hence \"0\\<^sub>v n = A *\\<^sub>v ?a \\<and> 0\\<^sub>v m = D *\\<^sub>v ?d\"\n    apply(subst append_vec_eq[of _ n, symmetric]) using A D by auto\n  thus \"?a : mat_kernel A\" \"?d : mat_kernel D\" unfolding mat_kernel_def using A D by auto\nqed\n\nlemma padr_padl_eq:\n  assumes v: \"v : carrier_vec n\"\n  shows \"padr m v = padl n u \\<longleftrightarrow> v = 0\\<^sub>v n \\<and> u = 0\\<^sub>v m\"\n  apply (subst append_vec_eq) using v by auto\n\n\nlemma pad_disjoint:\n  assumes A: \"A \\<subseteq> carrier_vec n\" and A0: \"0\\<^sub>v n \\<notin> A\" and B: \"B \\<subseteq> carrier_vec m\"\n  shows \"padr m ` A \\<inter> padl n ` B = {}\" (is \"?A \\<inter> ?B = _\")\nproof (intro equals0I)\n  fix ab assume \"ab : ?A \\<inter> ?B\"\n  then obtain a b\n    where \"ab = padr m a\" \"ab = padl n b\" and dim: \"a : A\" \"b : B\" by force\n  hence \"padr m a = padl n b\" by auto\n  hence \"a = 0\\<^sub>v n\" using dim A B by auto\n  thus \"False\" using dim A0 by auto\nqed\n\nlemma padr_padl_lindep:\n  assumes A: \"A \\<subseteq> carrier_vec n\" and liA: \"~ lin_dep n A\"\n      and B: \"B \\<subseteq> carrier_vec m\" and liB: \"~ lin_dep m B\"\n  shows \"~ lin_dep (n+m) (padr m ` A \\<union> padl n ` B)\" (is \"~ lin_dep _ (?A \\<union> ?B)\")\nproof -\n  interpret N: vectorspace class_ring \"M n\" using vec_vs.\n  interpret M: vectorspace class_ring \"M m\" using vec_vs.\n  interpret NM: vectorspace class_ring \"M (n+m)\" using vec_vs.\n  note [simp] = module_vec_simps class_ring_simps\n  have AB: \"?A \\<union> ?B \\<subseteq> carrier_vec (n+m)\"\n    using padr_image[OF A] padl_image[OF B] by auto\n  show ?thesis\n    unfolding NM.lin_dep_def\n    unfolding not_ex not_imp[symmetric] not_not\n  proof(intro allI impI)\n    fix U f u\n    assume finU: \"finite U\"\n       and UAB: \"U \\<subseteq> ?A \\<union> ?B\"\n       and f: \"f : U \\<rightarrow> carrier class_ring\"\n       and 0: \"lincomb (n+m) f U = \\<zero>\\<^bsub>M (n+m)\\<^esub>\"\n       and uU: \"u : U\"\n    let ?UA = \"U \\<inter> ?A\" and ?UB = \"U \\<inter> ?B\"\n    have \"?UA \\<subseteq> ?A\" \"?UB \\<subseteq> ?B\" by auto\n    then obtain A' B'\n      where A'A: \"A' \\<subseteq> A\" and B'B: \"B' \\<subseteq> B\"\n        and UAA': \"?UA = padr m ` A'\" and UBB': \"?UB = padl n ` B'\"\n      unfolding subset_image_iff by auto\n    hence A': \"A' \\<subseteq> carrier_vec n\" and B': \"B' \\<subseteq> carrier_vec m\" using A B by auto\n    have finA': \"finite A'\" and finB': \"finite B'\"\n    proof -\n      have \"padr m ` A' \\<subseteq> U\" \"padl n ` B' \\<subseteq> U\" using UAA' UBB' by auto\n      hence pre: \"finite (padr m ` A')\" \"finite (padl n ` B')\"\n        using finite_subset[OF _ finU] by auto\n      show \"finite A'\"\n        apply (rule finite_imageD) using subset_inj_on[OF padr_inj A'] pre by auto\n      show \"finite B'\"\n        apply (rule finite_imageD) using subset_inj_on[OF padl_inj B'] pre by auto\n    qed\n    have \"0\\<^sub>v n \\<notin> A\" using N.zero_nin_lin_indpt[OF _ liA] A class_semiring.one_zeroI by auto\n    hence \"?A \\<inter> ?B = {}\" using pad_disjoint A B by auto\n    hence disj: \"?UA \\<inter> ?UB = {}\" by auto\n    have split: \"U = padr m ` A' \\<union> padl n ` B'\"\n      unfolding UAA'[symmetric] UBB'[symmetric] using UAB by auto\n    show \"f u = \\<zero>\\<^bsub>(class_ring::'a ring)\\<^esub>\"\n    proof -\n      let ?a = \"f \\<circ> padr m\"\n      let ?b = \"f \\<circ> padl n\"\n      have lcA': \"lincomb n ?a A' : carrier_vec n\" using N.lincomb_closed A' by auto\n      have lcB': \"lincomb m ?b B' : carrier_vec m\" using M.lincomb_closed B' by auto\n  \n      have \"0\\<^sub>v n @\\<^sub>v 0\\<^sub>v m = 0\\<^sub>v (n+m)\" by auto\n      also have \"... = lincomb (n+m) f U\" using 0 by auto\n      also have \"U = ?UA \\<union> ?UB\" using UAB by auto\n      also have \"lincomb (n+m) f ... = lincomb (n+m) f ?UA + lincomb (n+m) f ?UB\"\n        apply(subst NM.lincomb_union) using A B finU disj by auto\n      also have \"lincomb (n+m) f ?UA = lincomb (n+m) (restrict f ?UA) ?UA\"\n        apply (subst NM.lincomb_restrict) using A finU by auto\n      also have \"restrict f ?UA = restrict (?a \\<circ> unpadr m) ?UA\"\n        apply(rule restrict_ext) by auto\n      also have \"lincomb (n+m) ... ?UA = lincomb (n+m) (?a \\<circ> unpadr m) ?UA\"\n        apply(subst NM.lincomb_restrict) using A finU by auto\n      also have \"?UA = padr m ` A'\" using UAA'.\n      also have \"lincomb (n+m) (?a \\<circ> unpadr m) ... =\n        padr m (lincomb n ?a A')\"\n        using lincomb_pad(1)[OF A' finA',symmetric].\n      also have \"lincomb (n+m) f ?UB = lincomb (n+m) (restrict f ?UB) ?UB\"\n        apply (subst NM.lincomb_restrict) using B finU by auto\n      also have \"restrict f ?UB = restrict (?b \\<circ> unpadl n) ?UB\"\n        apply(rule restrict_ext) by auto\n      also have \"lincomb (n+m) ... ?UB = lincomb (n+m) (?b \\<circ> unpadl n) ?UB\"\n        apply(subst NM.lincomb_restrict) using B finU by auto\n      also have \"n+m = m+n\" by auto\n      also have \"?UB = padl n ` B'\" using UBB'.\n      also have \"lincomb (m+n) (?b \\<circ> unpadl n) ... =\n        padl n (lincomb m ?b B')\"\n        using lincomb_pad(2)[OF B' finB',symmetric].\n      also have \"padr m (lincomb n ?a A') + ... =\n          (lincomb n ?a A' + 0\\<^sub>v n) @\\<^sub>v (0\\<^sub>v m + lincomb m ?b B')\"\n        apply (rule append_vec_add) using lcA' lcB' by auto\n      also have \"... = lincomb n ?a A' @\\<^sub>v lincomb m ?b B'\" using lcA' lcB' by auto\n      finally have \"0\\<^sub>v n @\\<^sub>v 0\\<^sub>v m = lincomb n ?a A' @\\<^sub>v lincomb m ?b B'\".\n      hence \"0\\<^sub>v n = lincomb n ?a A' \\<and> 0\\<^sub>v m = lincomb m ?b B'\"\n        apply(subst append_vec_eq[symmetric]) using lcA' lcB' by auto\n      from conjunct1[OF this] conjunct2[OF this]\n      have \"?a : A' \\<rightarrow> {0}\" \"?b : B' \\<rightarrow> {0}\"\n        using N.not_lindepD[OF liA finA' A'A]\n        using M.not_lindepD[OF liB finB' B'B] by auto\n      hence \"f : padr m ` A' \\<rightarrow> {0}\" \"f : padl n ` B' \\<rightarrow> {0}\" by auto\n      hence \"f : padr m ` A' \\<union> padl n ` B' \\<rightarrow> {0}\" by auto\n      hence \"f : U \\<rightarrow> {0}\" using split by auto\n      hence \"f u = 0\" using uU by auto\n      thus ?thesis by simp\n    qed\n  qed\nqed\n\nend\n\nlemma kernel_four_block_0_mat:\n  assumes Adef: \"(A :: 'a::field mat) = four_block_mat B (0\\<^sub>m n m) (0\\<^sub>m m n) D\"\n  and B: \"B \\<in> carrier_mat n n\"\n  and D: \"D \\<in> carrier_mat m m\"\n  shows \"kernel.dim (n + m) A = kernel.dim n B + kernel.dim m D\"\nproof -\n  have [simp]: \"n + m = m + n\" by auto\n  have A: \"A \\<in> carrier_mat (n+m) (n+m)\"\n    using Adef four_block_carrier_mat[OF B D] by auto\n  interpret vardim \"TYPE('a)\".\n  interpret MN: vectorspace class_ring \"M (n+m)\" using vec_vs.\n  interpret KA: kernel \"n+m\" \"n+m\" A by (unfold_locales, rule A)\n  interpret KB: kernel n n B by (unfold_locales, rule B)\n  interpret KD: kernel m m D by (unfold_locales, rule D)\n\n  note [simp] = module_vec_simps\n\n  from kernel_basis_exists[OF B]\n    obtain baseB where fin_bB: \"finite baseB\" and bB: \"KB.basis baseB\" by blast\n  hence bBkB: \"baseB \\<subseteq> mat_kernel B\" unfolding KB.Ker.basis_def by auto\n  hence bBc: \"baseB \\<subseteq> carrier_vec n\" using mat_kernel_carrier[OF B] by auto\n  have bB0: \"0\\<^sub>v n \\<notin> baseB\"\n    using bB unfolding KB.Ker.basis_def\n    using KB.Ker.vs_zero_lin_dep[OF bBkB] by auto\n  have bBkA: \"padr m ` baseB \\<subseteq> mat_kernel A\"\n  proof\n    fix a assume \"a : padr m ` baseB\"\n    then obtain b where ab: \"a = padr m b\" and \"b : baseB\" by auto\n    hence \"b : mat_kernel B\" using bB unfolding KB.Ker.basis_def by auto\n    hence \"padr m b : mat_kernel A\"\n      unfolding Adef using kernel_padr[OF _ B _ D] by auto\n    thus \"a : mat_kernel A\" using ab by auto\n  qed\n  from kernel_basis_exists[OF D]\n    obtain baseD where fin_bD: \"finite baseD\" and bD: \"KD.basis baseD\" by blast\n  hence bDkD: \"baseD \\<subseteq> mat_kernel D\" unfolding KD.Ker.basis_def by auto\n  hence bDc: \"baseD \\<subseteq> carrier_vec m\" using mat_kernel_carrier[OF D] by auto\n  have bDkA: \"padl n ` baseD \\<subseteq> mat_kernel A\"\n  proof\n    fix a assume \"a : padl n ` baseD\"\n    then obtain d where ad: \"a = padl n d\" and \"d : baseD\" by auto\n    hence \"d : mat_kernel D\" using bD unfolding KD.Ker.basis_def by auto\n    hence \"padl n d : mat_kernel A\"\n      unfolding Adef using kernel_padl[OF _ B _ D] by auto\n    thus \"a : mat_kernel A\" using ad by auto\n  qed\n  let ?BD = \"(padr m ` baseB \\<union> padl n ` baseD)\"\n  have finBD: \"finite ?BD\" using fin_bB fin_bD by auto\n  have \"KA.basis  ?BD\"\n    unfolding KA.Ker.basis_def\n  proof (intro conjI Set.equalityI)\n    show BDk: \"?BD \\<subseteq> mat_kernel A\" using bBkA bDkA by auto\n    also have \"mat_kernel A \\<subseteq> carrier_vec (m+n)\" using mat_kernel_carrier A by auto\n    finally have BD: \"?BD \\<subseteq> carrier (M (n + m))\" by auto\n    show \"mat_kernel A \\<subseteq> KA.Ker.span ?BD\"\n      unfolding KA.span_same[OF BDk]\n    proof\n      have BD: \"?BD \\<subseteq> carrier_vec (n+m)\" (is \"_ \\<subseteq> ?R\")\n      proof(rule)\n        fix v assume \"v : ?BD\"\n        moreover\n        { assume \"v : padr m ` baseB\"\n          then obtain b where \"b : baseB\" and vb: \"v = padr m b\" by auto\n          hence \"b : carrier_vec n\" using bBc by auto\n          hence \"v : ?R\" unfolding vb apply(subst append_carrier_vec) by auto\n        }\n        moreover\n        { assume \"v : padl n ` baseD\"\n          then obtain d where \"d : baseD\" and vd: \"v = padl n d\" by auto\n          hence \"d : carrier_vec m\" using bDc by auto\n          hence \"v : ?R\" unfolding vd apply(subst append_carrier_vec) by auto\n        }\n        ultimately show \"v: ?R\" by auto\n      qed\n      fix a assume a: \"a : mat_kernel A\"\n      hence \"a : carrier_vec (n+m)\" using a mat_kernel_carrier[OF A] by auto\n      hence \"a = vec_first a n @\\<^sub>v vec_last a m\" (is \"_ = ?b @\\<^sub>v ?d\") by simp\n      also have \"... = padr m ?b + padl n ?d\" by auto\n      finally have 1: \"a = padr m ?b + padl n ?d\".\n  \n      have subkernel: \"?b : mat_kernel B\" \"?d : mat_kernel D\"\n        using mat_kernel_split[OF B D] a Adef by auto\n      hence \"?b : span n baseB\"\n        using bB unfolding KB.Ker.basis_def using KB.span_same by auto\n      hence \"padr m ?b : padr m ` span n baseB\" by auto\n      also have \"padr m ` span n baseB = span (n+m) (padr m ` baseB)\"\n        using span_pad[OF bBc] by auto\n      also have \"... \\<subseteq> span (n+m) ?BD\" using MN.span_is_monotone by auto\n      finally have 2: \"padr m ?b : span (n+m) ?BD\".\n      have \"?d : span m baseD\"\n        using subkernel bD unfolding KD.Ker.basis_def using KD.span_same by auto\n      hence \"padl n ?d : padl n ` span m baseD\" by auto\n      also have \"padl n ` span m baseD = span (n+m) (padl n ` baseD)\"\n        using span_pad[OF bDc] by auto\n      also have \"... \\<subseteq> span (n+m) ?BD\" using MN.span_is_monotone by auto\n      finally have 3: \"padl n ?d : span (n+m) ?BD\".\n  \n      have \"padr m ?b + padl n ?d : span (n+m) ?BD\"\n        using MN.span_add1[OF _ 2 3] BD by auto\n      thus \"a \\<in> span (n+m) ?BD\" using 1 by auto\n    qed\n    show \"KA.Ker.span ?BD \\<subseteq> mat_kernel A\" using KA.Ker.span_closed[OF BDk] by auto\n    have li: \"~ lin_dep n baseB\" \"~ lin_dep m baseD\"\n      using bB[unfolded KB.Ker.basis_def]\n      unfolding KB.lindep_same[OF bBkB]\n      using bD[unfolded KD.Ker.basis_def]\n      unfolding KD.lindep_same[OF bDkD] by auto\n    show \"~ KA.Ker.lin_dep ?BD\"\n      unfolding KA.lindep_same[OF BDk]\n      apply(rule padr_padl_lindep) using bBc bDc li by auto\n  qed\n  hence \"KA.dim = card ?BD\" using KA.Ker.dim_basis[OF finBD] by auto\n  also have \"card ?BD = card (padr m ` baseB) + card (padl n ` baseD)\"\n    apply(rule card_Un_disjoint)\n    using pad_disjoint[OF bBc bB0 bDc] fin_bB fin_bD by auto\n  also have \"... = card baseB + card baseD\"\n    using card_image[OF subset_inj_on[OF padr_inj]]\n    using card_image[OF subset_inj_on[OF padl_inj]] bBc bDc by auto\n  also have \"card baseB = KB.dim\" using KB.Ker.dim_basis[OF fin_bB] bB by auto\n  also have \"card baseD = KD.dim\" using KD.Ker.dim_basis[OF fin_bD] bD by auto\n  finally show ?thesis.\n\nqed\n\nlemma similar_mat_wit_kernel_dim: assumes A: \"A \\<in> carrier_mat n n\"\n  and wit: \"similar_mat_wit A B P Q\"\n  shows \"kernel.dim n A = kernel.dim n B\"\nproof -\n  from similar_mat_witD2[OF A wit]\n  have QP: \"Q * P = 1\\<^sub>m n\" and AB: \"A = P * B * Q\" and \n    A: \"A \\<in> carrier_mat n n\" and B: \"B \\<in> carrier_mat n n\" and P: \"P \\<in> carrier_mat n n\" and Q: \"Q \\<in> carrier_mat n n\" by auto\n  from P B have PB: \"P * B \\<in> carrier_mat n n\" by auto\n  show ?thesis unfolding AB mat_kernel_dim_mult_eq_right[OF PB Q P QP] mat_kernel_mult_eq[OF B P Q QP]\n    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/Evaluation/Jordan_Normal_Form/Matrix_Kernel.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8558511396138365, "lm_q2_score": 0.8221891370573388, "lm_q1q2_score": 0.7036715099286402}}
{"text": "(*  Title:       General Algorithms for Iterators\n    Author:      Thomas Tuerk <tuerk@in.tum.de>\n    Maintainer:  Thomas Tuerk <tuerk@in.tum.de>\n*)\nsection {* General Algorithms for Iterators over Finite Sets *}\ntheory SetIteratorGA\nimports Main \"SetIteratorOperations\"\nbegin\n\nsubsection {* Quantification *}\n\ndefinition iterate_ball where\n    \"iterate_ball (it::('x,bool) set_iterator) P = it id (\\<lambda>x \\<sigma>. P x) True\"\n\nlemma iterate_ball_correct :\nassumes it: \"set_iterator it S0\"\nshows \"iterate_ball it P = (\\<forall>x\\<in>S0. P x)\"\nunfolding iterate_ball_def\napply (rule set_iterator_rule_P [OF it,\n            where I = \"\\<lambda>S \\<sigma>. \\<sigma> = (\\<forall>x\\<in>S0-S. P x)\"])\napply auto\ndone\n\ndefinition iterate_bex where\n    \"iterate_bex (it::('x,bool) set_iterator) P = it (\\<lambda>\\<sigma>. \\<not>\\<sigma>) (\\<lambda>x \\<sigma>. P x) False\"\n\nlemma iterate_bex_correct :\nassumes it: \"set_iterator it S0\"\nshows \"iterate_bex it P = (\\<exists>x\\<in>S0. P x)\"\nunfolding iterate_bex_def\napply (rule set_iterator_rule_P [OF it, where I = \"\\<lambda>S \\<sigma>. \\<sigma> = (\\<exists>x\\<in>S0-S. P x)\"])\napply auto\ndone\n\nsubsection {* Iterator to List *}\n\ndefinition iterate_to_list where\n    \"iterate_to_list (it::('x,'x list) set_iterator) = it (\\<lambda>_. True) (\\<lambda>x \\<sigma>. x # \\<sigma>) []\"\n\nlemma iterate_to_list_foldli [simp] :\n  \"iterate_to_list (foldli xs) = rev xs\"\nunfolding iterate_to_list_def\nby (induct xs rule: rev_induct, simp_all add: foldli_snoc) \n\nlemma iterate_to_list_genord_correct :\nassumes it: \"set_iterator_genord it S0 R\"\nshows \"set (iterate_to_list it) = S0 \\<and> distinct (iterate_to_list it) \\<and>\n       sorted_by_rel R (rev (iterate_to_list it))\"\nusing it unfolding set_iterator_genord_foldli_conv by auto\n\nlemma iterate_to_list_correct :\nassumes it: \"set_iterator it S0\"\nshows \"set (iterate_to_list it) = S0 \\<and> distinct (iterate_to_list it)\"\nusing iterate_to_list_genord_correct [OF it[unfolded set_iterator_def]]\nby simp\n\nlemma (in linorder) iterate_to_list_linord_correct :\nfixes S0 :: \"'a set\"\nassumes it_OK: \"set_iterator_linord it S0\"\nshows \"set (iterate_to_list it) = S0 \\<and> distinct (iterate_to_list it) \\<and>\n       sorted (rev (iterate_to_list it))\"\nusing it_OK unfolding set_iterator_linord_foldli_conv by auto\n\nlemma (in linorder) iterate_to_list_rev_linord_correct :\nfixes S0 :: \"'a set\"\nassumes it_OK: \"set_iterator_rev_linord it S0\"\nshows \"set (iterate_to_list it) = S0 \\<and> distinct (iterate_to_list it) \\<and>\n       sorted (iterate_to_list it)\"\nusing it_OK unfolding set_iterator_rev_linord_foldli_conv by auto\n\nlemma (in linorder) iterate_to_list_map_linord_correct :\nassumes it_OK: \"map_iterator_linord it m\"\nshows \"map_of (iterate_to_list it) = m \\<and> distinct (map fst (iterate_to_list it)) \\<and>\n       sorted (map fst (rev (iterate_to_list it)))\"\nusing it_OK unfolding map_iterator_linord_foldli_conv \nby clarify (simp add: rev_map[symmetric])\n\nlemma (in linorder) iterate_to_list_map_rev_linord_correct :\nassumes it_OK: \"map_iterator_rev_linord it m\"\nshows \"map_of (iterate_to_list it) = m \\<and> distinct (map fst (iterate_to_list it)) \\<and>\n       sorted (map fst (iterate_to_list it))\"\nusing it_OK unfolding map_iterator_rev_linord_foldli_conv \nby clarify (simp add: rev_map[symmetric])\n\n\nsubsection {* Size *}\n\nlemma set_iterator_finite :\nassumes it: \"set_iterator it S0\"\nshows \"finite S0\"\nusing set_iterator_genord.finite_S0 [OF it[unfolded set_iterator_def]] .\n\nlemma map_iterator_finite :\nassumes it: \"map_iterator it m\"\nshows \"finite (dom m)\"\nusing set_iterator_genord.finite_S0 [OF it[unfolded set_iterator_def]]\nby (simp add: finite_map_to_set) \n\ndefinition iterate_size where\n    \"iterate_size (it::('x,nat) set_iterator) = it (\\<lambda>_. True) (\\<lambda>x \\<sigma>. Suc \\<sigma>) 0\"\n\nlemma iterate_size_correct :\nassumes it: \"set_iterator it S0\"\nshows \"iterate_size it = card S0 \\<and> finite S0\"\nunfolding iterate_size_def\napply (rule_tac set_iterator_rule_insert_P [OF it, \n    where I = \"\\<lambda>S \\<sigma>. \\<sigma> = card S \\<and> finite S\"])\napply auto\ndone\n\ndefinition iterate_size_abort where\n  \"iterate_size_abort (it::('x,nat) set_iterator) n = it (\\<lambda>\\<sigma>. \\<sigma> < n) (\\<lambda>x \\<sigma>. Suc \\<sigma>) 0\"\n\nlemma iterate_size_abort_correct :\nassumes it: \"set_iterator it S0\"\nshows \"iterate_size_abort it n = (min n (card S0)) \\<and> finite S0\"\nunfolding iterate_size_abort_def\nproof (rule set_iterator_rule_insert_P [OF it,\n   where I = \"\\<lambda>S \\<sigma>. \\<sigma> = (min n (card S)) \\<and> finite S\"], goal_cases)\n  case (4 \\<sigma> S)\n  assume \"S \\<subseteq> S0\" \"S \\<noteq> S0\" \"\\<not> \\<sigma> < n\" \"\\<sigma> = min n (card S) \\<and> finite S\" \n\n  from `\\<sigma> = min n (card S) \\<and> finite S` `\\<not> \\<sigma> < n` \n  have \"\\<sigma> = n\" \"n \\<le> card S\"\n    by (auto simp add: min_less_iff_disj)\n\n  note fin_S0 = set_iterator_genord.finite_S0 [OF it[unfolded set_iterator_def]]\n  from card_mono [OF fin_S0 `S \\<subseteq> S0`] have \"card S \\<le> card S0\" .\n  \n  with `\\<sigma> = n` `n \\<le> card S` fin_S0\n  show \"\\<sigma> = min n (card S0) \\<and> finite S0\" by simp\nqed simp_all\n\nsubsection {* Emptyness Check *}\n\ndefinition iterate_is_empty_by_size where\n    \"iterate_is_empty_by_size it = (iterate_size_abort it 1 = 0)\"\n\nlemma iterate_is_empty_by_size_correct :\nassumes it: \"set_iterator it S0\"\nshows \"iterate_is_empty_by_size it = (S0 = {})\"\nusing iterate_size_abort_correct[OF it, of 1]\nunfolding iterate_is_empty_by_size_def\nby (cases \"card S0\") auto\n\ndefinition iterate_is_empty where\n    \"iterate_is_empty (it::('x,bool) set_iterator) = (it (\\<lambda>b. b) (\\<lambda>_ _. False) True)\"\n\nlemma iterate_is_empty_correct :\nassumes it: \"set_iterator it S0\"\nshows \"iterate_is_empty it = (S0 = {})\"\nunfolding iterate_is_empty_def\napply (rule set_iterator_rule_insert_P [OF it,\n   where I = \"\\<lambda>S \\<sigma>. \\<sigma> \\<longleftrightarrow> S = {}\"])\napply auto\ndone\n\nsubsection {* Check for singleton Sets *}\n\ndefinition iterate_is_sng where\n    \"iterate_is_sng it = (iterate_size_abort it 2 = 1)\"\n\nlemma iterate_is_sng_correct :\nassumes it: \"set_iterator it S0\"\nshows \"iterate_is_sng it = (card S0 = 1)\"\nusing iterate_size_abort_correct[OF it, of 2]\nunfolding iterate_is_sng_def\napply (cases \"card S0\", simp, rename_tac n')\napply (case_tac n')\napply auto\ndone\n\nsubsection {* Selection *}\n\ndefinition iterate_sel where\n    \"iterate_sel (it::('x,'y option) set_iterator) f = it (\\<lambda>\\<sigma>. \\<sigma> = None) (\\<lambda>x \\<sigma>. f x) None\"\n\nlemma iterate_sel_genord_correct :\nassumes it_OK: \"set_iterator_genord it S0 R\"\nshows \"iterate_sel it f = None \\<longleftrightarrow> (\\<forall>x\\<in>S0. (f x = None))\"\n      \"iterate_sel it f = Some y \\<Longrightarrow> (\\<exists>x \\<in> S0. f x = Some y \\<and> (\\<forall>x' \\<in> S0-{x}. \\<forall>y. f x' = Some y' \\<longrightarrow> R x x'))\"\nproof -\n  show \"iterate_sel it f = None \\<longleftrightarrow> (\\<forall>x\\<in>S0. (f x = None))\"\n    unfolding iterate_sel_def\n    apply (rule_tac set_iterator_genord.iteratei_rule_insert_P [OF it_OK, \n       where I = \"\\<lambda>S \\<sigma>. (\\<sigma> = None) \\<longleftrightarrow> (\\<forall>x\\<in>S. (f x = None))\"])\n    apply auto\n  done\nnext\n  have \"iterate_sel it f = Some y \\<longrightarrow> (\\<exists>x \\<in> S0. f x = Some y \\<and> (\\<forall>x' \\<in> S0-{x}. \\<forall>y'. f x' = Some y' \\<longrightarrow> R x x'))\"\n    unfolding iterate_sel_def\n    apply (rule_tac set_iterator_genord.iteratei_rule_insert_P [OF it_OK, \n       where I = \"\\<lambda>S \\<sigma>. (\\<forall>y. \\<sigma> = Some y \\<longrightarrow> (\\<exists>x \\<in> S. f x = Some y \\<and> (\\<forall>x' \\<in> S-{x}.\\<forall>y'. f x' = Some y' \\<longrightarrow> R x x'))) \\<and>\n                        ((\\<sigma> = None) \\<longleftrightarrow> (\\<forall>x\\<in>S. f x = None))\"])\n    apply simp\n    apply (auto simp add: Bex_def subset_iff Ball_def)\n    apply metis\n  done\n  moreover assume \"iterate_sel it f = Some y\" \n  finally show \"(\\<exists>x \\<in> S0. f x = Some y \\<and> (\\<forall>x' \\<in> S0-{x}. \\<forall>y. f x' = Some y' \\<longrightarrow> R x x'))\" by blast\nqed\n\n\ndefinition iterate_sel_no_map where\n    \"iterate_sel_no_map it P = iterate_sel it (\\<lambda>x. if P x then Some x else None)\" \nlemmas iterate_sel_no_map_alt_def = iterate_sel_no_map_def[unfolded iterate_sel_def, code]\n\nlemma iterate_sel_no_map_genord_correct :\nassumes it_OK: \"set_iterator_genord it S0 R\"\nshows \"iterate_sel_no_map it P = None \\<longleftrightarrow> (\\<forall>x\\<in>S0. \\<not>(P x))\"\n      \"iterate_sel_no_map it P = Some x \\<Longrightarrow> (x \\<in> S0 \\<and> P x \\<and> (\\<forall>x' \\<in> S0-{x}. P x' \\<longrightarrow> R x x'))\"\nunfolding iterate_sel_no_map_def\nusing iterate_sel_genord_correct[OF it_OK, of \"\\<lambda>x. if P x then Some x else None\"]\napply (simp_all add: Bex_def)\napply (metis option.inject option.simps(2)) \ndone\n\nlemma iterate_sel_no_map_correct :\nassumes it_OK: \"set_iterator it S0\"\nshows \"iterate_sel_no_map it P = None \\<longleftrightarrow> (\\<forall>x\\<in>S0. \\<not>(P x))\"\n      \"iterate_sel_no_map it P = Some x \\<Longrightarrow> x \\<in> S0 \\<and> P x\"\nproof -\n  note iterate_sel_no_map_genord_correct [OF it_OK[unfolded set_iterator_def], of P]\n  thus \"iterate_sel_no_map it P = None \\<longleftrightarrow> (\\<forall>x\\<in>S0. \\<not>(P x))\"\n       \"iterate_sel_no_map it P = Some x \\<Longrightarrow> x \\<in> S0 \\<and> P x\"\n    by simp_all\nqed\n\nlemma (in linorder) iterate_sel_no_map_linord_correct :\nassumes it_OK: \"set_iterator_linord it S0\"\nshows \"iterate_sel_no_map it P = None \\<longleftrightarrow> (\\<forall>x\\<in>S0. \\<not>(P x))\"\n      \"iterate_sel_no_map it P = Some x \\<Longrightarrow> (x \\<in> S0 \\<and> P x \\<and> (\\<forall>x'\\<in>S0. P x' \\<longrightarrow> x \\<le> x'))\"\nproof -\n  note iterate_sel_no_map_genord_correct [OF it_OK[unfolded set_iterator_linord_def], of P]\n  thus \"iterate_sel_no_map it P = None \\<longleftrightarrow> (\\<forall>x\\<in>S0. \\<not>(P x))\"\n       \"iterate_sel_no_map it P = Some x \\<Longrightarrow> (x \\<in> S0 \\<and> P x \\<and> (\\<forall>x'\\<in>S0. P x' \\<longrightarrow> x \\<le> x'))\"\n    by auto\nqed\n\nlemma (in linorder) iterate_sel_no_map_rev_linord_correct :\nassumes it_OK: \"set_iterator_rev_linord it S0\"\nshows \"iterate_sel_no_map it P = None \\<longleftrightarrow> (\\<forall>x\\<in>S0. \\<not>(P x))\"\n      \"iterate_sel_no_map it P = Some x \\<Longrightarrow> (x \\<in> S0 \\<and> P x \\<and> (\\<forall>x'\\<in>S0. P x' \\<longrightarrow> x' \\<le> x))\"\nproof -\n  note iterate_sel_no_map_genord_correct [OF it_OK[unfolded set_iterator_rev_linord_def], of P]\n  thus \"iterate_sel_no_map it P = None \\<longleftrightarrow> (\\<forall>x\\<in>S0. \\<not>(P x))\"\n       \"iterate_sel_no_map it P = Some x \\<Longrightarrow> (x \\<in> S0 \\<and> P x \\<and> (\\<forall>x'\\<in>S0. P x' \\<longrightarrow> x' \\<le> x))\"\n    by auto\nqed\n\n\nlemma iterate_sel_no_map_map_correct :\nassumes it_OK: \"map_iterator it m\"\nshows \"iterate_sel_no_map it P = None \\<longleftrightarrow> (\\<forall>k v. m k = Some v \\<longrightarrow> \\<not>(P (k, v)))\"\n      \"iterate_sel_no_map it P = Some (k, v) \\<Longrightarrow> (m k = Some v \\<and> P (k, v))\"\nproof -\n  note iterate_sel_no_map_genord_correct [OF it_OK[unfolded set_iterator_def], of P]\n  thus \"iterate_sel_no_map it P = None \\<longleftrightarrow> (\\<forall>k v. m k = Some v \\<longrightarrow> \\<not>(P (k, v)))\"\n       \"iterate_sel_no_map it P = Some (k, v) \\<Longrightarrow> (m k = Some v \\<and> P (k, v))\"\n    by (auto simp add: map_to_set_def)\nqed\n\nlemma (in linorder) iterate_sel_no_map_map_linord_correct :\nassumes it_OK: \"map_iterator_linord it m\"\nshows \"iterate_sel_no_map it P = None \\<longleftrightarrow> (\\<forall>k v. m k = Some v \\<longrightarrow> \\<not>(P (k, v)))\"\n      \"iterate_sel_no_map it P = Some (k, v) \\<Longrightarrow> (m k = Some v \\<and> P (k, v) \\<and> (\\<forall>k' v' . m k' = Some v' \\<and>\n           P (k', v') \\<longrightarrow> k \\<le> k'))\"\nproof -\n  note iterate_sel_no_map_genord_correct [OF it_OK[unfolded set_iterator_map_linord_def], of P]\n  thus \"iterate_sel_no_map it P = None \\<longleftrightarrow> (\\<forall>k v. m k = Some v \\<longrightarrow> \\<not>(P (k, v)))\"\n       \"iterate_sel_no_map it P = Some (k, v) \\<Longrightarrow> (m k = Some v \\<and> P (k, v) \\<and> (\\<forall>k' v' . m k' = Some v' \\<and>\n           P (k', v') \\<longrightarrow> k \\<le> k'))\"\n    apply (auto simp add: map_to_set_def Ball_def) \n  done\nqed\n\nlemma (in linorder) iterate_sel_no_map_map_rev_linord_correct :\nassumes it_OK: \"map_iterator_rev_linord it m\"\nshows \"iterate_sel_no_map it P = None \\<longleftrightarrow> (\\<forall>k v. m k = Some v \\<longrightarrow> \\<not>(P (k, v)))\"\n      \"iterate_sel_no_map it P = Some (k, v) \\<Longrightarrow> (m k = Some v \\<and> P (k, v) \\<and> (\\<forall>k' v' . m k' = Some v' \\<and>\n           P (k', v') \\<longrightarrow> k' \\<le> k))\"\nproof -\n  note iterate_sel_no_map_genord_correct [OF it_OK[unfolded set_iterator_map_rev_linord_def], of P]\n  thus \"iterate_sel_no_map it P = None \\<longleftrightarrow> (\\<forall>k v. m k = Some v \\<longrightarrow> \\<not>(P (k, v)))\"\n       \"iterate_sel_no_map it P = Some (k, v) \\<Longrightarrow> (m k = Some v \\<and> P (k, v) \\<and> (\\<forall>k' v' . m k' = Some v' \\<and>\n           P (k', v') \\<longrightarrow> k' \\<le> k))\"\n    apply (auto simp add: map_to_set_def Ball_def) \n  done\nqed\n\n\nsubsection {* Creating ordered iterators *}\n\ntext {* One can transform an iterator into an ordered one by converting it to list, \n        sorting this list and then converting back to an iterator. In general, this brute-force\n        method is inefficient, though. *}\n\ndefinition iterator_to_ordered_iterator where\n  \"iterator_to_ordered_iterator sort_fun it =\n   foldli (sort_fun (iterate_to_list it))\"\n\nlemma iterator_to_ordered_iterator_correct :\nassumes sort_fun_OK: \"\\<And>l. sorted_by_rel R (sort_fun l) \\<and> mset (sort_fun l) = mset l\"\n    and it_OK: \"set_iterator it S0\"\nshows \"set_iterator_genord (iterator_to_ordered_iterator sort_fun it) S0 R\"\nproof -\n  def l \\<equiv> \"iterate_to_list it\"\n  have l_props: \"set l = S0\" \"distinct l\" \n    using iterate_to_list_correct [OF it_OK, folded l_def] by simp_all\n\n  with sort_fun_OK[of l] have sort_l_props:\n    \"sorted_by_rel R (sort_fun l)\"\n    \"set (sort_fun l) = S0\" \"distinct (sort_fun l)\"\n    apply (simp_all)\n    apply (metis set_mset_mset)\n    apply (metis distinct_count_atmost_1 set_mset_mset)\n  done\n\n  show ?thesis\n    apply (rule set_iterator_genord_I[of \"sort_fun l\"])\n    apply (simp_all add: sort_l_props iterator_to_ordered_iterator_def l_def[symmetric])\n  done\nqed\n\n\ndefinition iterator_to_ordered_iterator_quicksort where\n  \"iterator_to_ordered_iterator_quicksort R it =\n   iterator_to_ordered_iterator (quicksort_by_rel R []) it\"\n\nlemmas iterator_to_ordered_iterator_quicksort_code[code] =\n  iterator_to_ordered_iterator_quicksort_def[unfolded iterator_to_ordered_iterator_def]\n\nlemma iterator_to_ordered_iterator_quicksort_correct :\nassumes lin : \"\\<And>x y. (R x y) \\<or> (R y x)\"\n    and trans_R: \"\\<And>x y z. R x y \\<Longrightarrow> R y z \\<Longrightarrow> R x z\"\n    and it_OK: \"set_iterator it S0\"\nshows \"set_iterator_genord (iterator_to_ordered_iterator_quicksort R it) S0 R\"\nunfolding iterator_to_ordered_iterator_quicksort_def\napply (rule iterator_to_ordered_iterator_correct [OF _ it_OK])\napply (simp_all add: sorted_by_rel_quicksort_by_rel[OF lin trans_R])\ndone\n\ndefinition iterator_to_ordered_iterator_mergesort where\n  \"iterator_to_ordered_iterator_mergesort R it =\n   iterator_to_ordered_iterator (mergesort_by_rel R) it\"\n\nlemmas iterator_to_ordered_iterator_mergesort_code[code] =\n  iterator_to_ordered_iterator_mergesort_def[unfolded iterator_to_ordered_iterator_def]\n\nlemma iterator_to_ordered_iterator_mergesort_correct :\nassumes lin : \"\\<And>x y. (R x y) \\<or> (R y x)\"\n    and trans_R: \"\\<And>x y z. R x y \\<Longrightarrow> R y z \\<Longrightarrow> R x z\"\n    and it_OK: \"set_iterator it S0\"\nshows \"set_iterator_genord (iterator_to_ordered_iterator_mergesort R it) S0 R\"\nunfolding iterator_to_ordered_iterator_mergesort_def\napply (rule iterator_to_ordered_iterator_correct [OF _ it_OK])\napply (simp_all add: sorted_by_rel_mergesort_by_rel[OF lin trans_R])\ndone\n\nend\n\n\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/Iterator/SetIteratorGA.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8558511322604133, "lm_q2_score": 0.8221891327004132, "lm_q1q2_score": 0.7036715001538558}}
{"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_32\n  imports \"../../Test_Base\"\nbegin\n\ndatatype Nat = Z | S \"Nat\"\n\nfun min :: \"Nat => Nat => Nat\" where\n  \"min (Z) y = Z\"\n| \"min (S z) (Z) = Z\"\n| \"min (S z) (S y1) = S (min z y1)\"\n\ntheorem property0 :(* Similar to TIP_prop_23.thy *)\n  \"((min a b) = (min 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\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_32.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045996818986, "lm_q2_score": 0.7931059609645724, "lm_q1q2_score": 0.703647256602901}}
{"text": "theory ex3_07 imports Main \"~~/src/HOL/IMP/AExp\" \"~~/src/HOL/IMP/BExp\" begin\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\ntheorem \"bval (Eq a1 a2) s = (aval a1 s = aval a2 s)\"\napply auto\ndone\n\ntheorem \"bval (Le a1 a2) s = (aval a1 s \\<le> aval a2 s)\"\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/chapter3/ex3_07.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8872045996818986, "lm_q2_score": 0.7931059585194573, "lm_q1q2_score": 0.7036472544335836}}
{"text": "theory Support \n  imports \"HOL-Nominal.Nominal\" \nbegin\n\ntext \\<open>\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\\<close>\n\natom_decl atom\n\ntext \\<open>The set of even atoms.\\<close>\nabbreviation\n  EVEN :: \"atom set\"\nwhere\n  \"EVEN \\<equiv> {atom n | n. \\<exists>i. n=2*i}\"\n\ntext \\<open>The set of odd atoms:\\<close>\nabbreviation  \n  ODD :: \"atom set\"\nwhere\n  \"ODD \\<equiv> {atom n | n. \\<exists>i. n=2*i+1}\"\n\ntext \\<open>An atom is either even or odd.\\<close>\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 \\<open>\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.)\\<close>\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 \\<open>The sets of even and odd atoms are disjunct.\\<close>\nlemma EVEN_intersect_ODD:\n  shows \"EVEN \\<inter> ODD = {}\"\n  using even_or_odd\n  by (auto) (presburger)\n\ntext \\<open>\n  The preceeding two lemmas help us to prove \n  the following two useful equalities:\\<close>\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 \\<open>The sets EVEN and ODD are infinite.\\<close>\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 \\<open>\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.\\<close>\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 \\<open>As a corollary we get that EVEN and ODD have infinite support.\\<close>\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 \\<open>\n  The set of all atoms has empty support, since any swappings leaves \n  this set unchanged.\\<close>\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 \\<open>Putting everything together.\\<close>\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 \\<open>Moral: support is a sublte notion.\\<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/Nominal/Examples/Support.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872046026642944, "lm_q2_score": 0.7931059438487663, "lm_q1q2_score": 0.7036472437830349}}
{"text": "theory Mereotopology\nimports Mereology\nbegin\nsection {* theories *}\n\nsubsection {* Ground Topology *}\n\nlocale T =\n fixes C :: \"i \\<Rightarrow> i \\<Rightarrow> bool\" (\"C\")--\"Connectedness\"\n assumes connection_reflexivity: \"C x x\" -- \"reflexivity of connectedness \"\n and connection_symmetry: \"C x y \\<longrightarrow> C y x\" -- \"symmetry of connectedness\"\n\nbegin\n\ndefinition E :: \"i \\<Rightarrow> i \\<Rightarrow> bool\" (\"E\") --\"Enclosure\"\n  where \"E x y \\<equiv> \\<forall>z. C z x \\<longrightarrow> C z y\"\n\n\nlemma enclosure_reflexivity: \"E x x\"\n  by (simp add: E_def)\n\nlemma enclosure_transitivity: \"E x y \\<longrightarrow> E y z \\<longrightarrow> E x z \"\n  by (simp add: E_def)\n\nlemma connection_extensional: \"(\\<forall> z. C x z \\<longleftrightarrow> C y z) \\<longleftrightarrow> x = y\" nitpick oops\n\nlemma\n  assumes connection_extensional: \"(\\<forall> z. C x z \\<longleftrightarrow> C y z) \\<longleftrightarrow> x = y\"\n  shows enclousre_antisymmetry: \"E x y \\<and> E y x \\<longrightarrow> x = y\"\n    using E_def connection_extensional connection_symmetry by blast\n\nend\n\nsection{* Ground Mereotopology *}\n\nlocale MT = ground_mereology + T +\n  assumes monotonicity: \"P x y \\<longrightarrow> E x y\"\n\nbegin\n\nlemma \"P x y \\<longrightarrow> (\\<forall>z. C x z \\<longrightarrow> C z y)\"\n  using E_def monotonicity connection_symmetry by blast\n\nlemma connection_extensional: \"(\\<forall> z. C x z \\<longleftrightarrow> C y z) \\<longleftrightarrow> x = y\" nitpick oops\n\nlemma overlap_implies_connection: \"O x y \\<longrightarrow> C x y\"\n  using E_def monotonicity overlap_def connection_symmetry connection_reflexivity by blast\n\nlemma  \"C x y \\<longrightarrow> O x y\" nitpick oops\n\ndefinition EC :: \"i => i\\<Rightarrow> bool\" (\"EC\") -- \"external connection\"\n  where \"EC x y \\<equiv> C x y \\<and> D x y\"\n\nlemma external_connection_irreflexive: \"\\<not> EC x x\"\n  by (simp add: EC_def disjoint_irreflexive)\n\nlemma external_connection_symmetric: \"EC x y \\<longrightarrow> EC y x\"\n  using EC_def connection_symmetry disjoint_symmetric by blast\n\ndefinition IP :: \"i => i\\<Rightarrow> bool\" (\"IP\") -- \"Internal part - part of y connected only to overlappers of y\"\n  where\n\"IP x y \\<equiv> P x y \\<and> (\\<forall>z. C z x \\<longrightarrow> O z y)\"\n\nlemma internal_part_antisymmetry: \"IP x y \\<longrightarrow> IP y x \\<longrightarrow> x = y\"\n  by (simp add: IP_def P_antisymmetry)\n\nlemma internal_part_transitivity: \"IP x y \\<longrightarrow> IP y z \\<longrightarrow> IP x z\"\n  using IP_def P_transitivity overlap_implies_connection by blast\n\ndefinition TP :: \"i \\<Rightarrow> i \\<Rightarrow> bool\" (\"TP\") -- \"Tangential part\"\n  where \"TP x y \\<equiv> P x y \\<and> \\<not> IP x y\"\n\nlemma tangential_part_reflexivity: \"\\<exists> y. TP y x \\<longrightarrow> TP x x\" by simp\n\nlemma tangential_part_antisymmetry: \"TP x y \\<longrightarrow> TP y x \\<longrightarrow> x = y\"\n  by (simp add: P_antisymmetry TP_def)\n\ndefinition IO :: \"i \\<Rightarrow> i \\<Rightarrow> bool\" (\"IO\")--\"Internal overlap\"\n  where\n\"IO x y \\<equiv> \\<exists> z. IP z x \\<and> IP z y\"\n\nlemma IO_reflexive: \"\\<exists> y. IO y x \\<longrightarrow> IO x x\"\n  by simp\nlemma IO_symmetric: \"IO x y \\<longrightarrow> IO y x\"\n  using IO_def by blast\n\ndefinition TO :: \"i \\<Rightarrow> i \\<Rightarrow> bool\" (\"TO\")--\"tangential overlap\"\n  where\n\"TO x y \\<equiv> O x y \\<and> \\<not>IO x y\"\n\nlemma TO_reflexive: \"\\<exists> y. TO y x \\<longrightarrow> TO x x\"\n  by simp\nlemma TO_symmetric: \"TO x y \\<longrightarrow> TO y x\"\n  using IO_symmetric TO_def overlap_symmetric by blast\n\ndefinition IU :: \"i\\<Rightarrow>i\\<Rightarrow> bool\" (\"IU\")--\"Internal underlap\"\n  where \"IU x y \\<equiv> \\<exists>z. IP x z \\<and> IP y z\"\n\ndefinition TU :: \"i\\<Rightarrow>i\\<Rightarrow>bool\" (\"TU\")--\"Tangentially underlap\"\n  where \"TU x y \\<equiv> U x y \\<and> \\<not> IU x y\"\n\ndefinition IPP :: \"i => i\\<Rightarrow> bool\" (\"IPP\")--\"internal proper part\"\n  where \"IPP x y \\<equiv> IP x y \\<and> \\<not>(IP y x)\"\n\ndefinition TPP :: \"i\\<Rightarrow>i\\<Rightarrow>bool\" (\"TPP\")--\"tangential proper part\"\n  where\n\"TPP x y \\<equiv> TP x y \\<and> \\<not>( TP y x)\"\n\ndefinition SC :: \"i \\<Rightarrow> bool\" (\"SC\") -- \"Self-connectedness\"\n  where\n\"SC x \\<equiv> \\<forall> y.\\<forall> z.(\\<forall> w. O w x \\<longleftrightarrow> O w y \\<or> O w z) \\<longrightarrow> C y z\"\n\nend \n\nsection {* Closed Mereotopology *}\n\nlocale CMT = closure_mereology + MT +\n  assumes connection_implies_underlap: \"C x y \\<longrightarrow> U x y \"\n\nlemma (in CMT) SCC: \"(C x y \\<and> SC x \\<and> SC y) \\<longrightarrow> (\\<exists>z. SC z \\<and> (\\<forall> w. O w z \\<longleftrightarrow> O w x \\<or> O w y))\" nitpick [user_axioms] oops\n\ntext {* The failure of SCC in closed minimal mereotopology seems to be a minor error in Casati and Varzi. *}\n\nlocale CEMT = closed_extensional_mereology + CMT\n\n\nsection {* Classical Extensional Mereotopology *}\n\nlocale GEMT = classical_extensional_mereology + MT\n\nbegin\n\nlemma C_implies_U: \"C x y \\<longrightarrow> U x y\"\n  by (simp add: universal_underlap)\n\nlemma \"\\<forall> x. IP x u\"\n  by (simp add: IP_def P_implies_overlap universe_character)\n\nlemma SC_def2:  \"SC x \\<longleftrightarrow> (\\<forall> y z. x = (y \\<oplus> z) \\<longrightarrow> C y z)\"\nproof\n  assume \"SC x\"\n  hence \"\\<forall> y z. (\\<forall> w. O w x \\<longleftrightarrow> (O w y \\<or> O w z)) \\<longrightarrow> C y z\"\n    using SC_def by simp\n  thus \"(\\<forall> y z. x = (y \\<oplus> z) \\<longrightarrow> C y z)\"\n    using sum_character by simp\nnext\n  assume \"\\<forall> y z. x = (y \\<oplus> z) \\<longrightarrow> C y z\"\n  have \"\\<forall> y z. (\\<forall> w. O w x \\<longleftrightarrow> (O w y \\<or> O w z)) \\<longrightarrow> C y z\"\n  proof fix y\n    show \"\\<forall> z. (\\<forall> w. O w x \\<longleftrightarrow> (O w y \\<or> O w z)) \\<longrightarrow> C y z\"\n    proof fix z\n      show \"(\\<forall> w. O w x \\<longleftrightarrow> (O w y \\<or> O w z)) \\<longrightarrow> C y z\"\n      proof\n        assume \"\\<forall> w. O w x \\<longleftrightarrow> (O w y \\<or> O w z)\"\n        with sum_intro have \"(y \\<oplus> z) = x\"..\n        thus \"C y z\" using \\<open>\\<forall>y z. x = y \\<oplus> z \\<longrightarrow> C y z\\<close> by blast\n      qed\n    qed\n  qed\n  thus \"SC x\" using SC_def by simp\nqed\n\nlemma separation: \"O x y \\<longrightarrow> O x z \\<longrightarrow> (P x (y \\<oplus> z) \\<longrightarrow> ((x \\<otimes> y) \\<oplus> (x \\<otimes> z)) = x)\" sorry (* Can you prove this? *)\n\nlemma identity: \"x \\<oplus> y = w \\<oplus> v \\<longrightarrow> \\<not> (O v x \\<and> O w x \\<or> O v y \\<and> O w y) \\<longrightarrow> x = w \\<and> y = v \\<or> x = v \\<and> y = w\"  sorry (* Can you prove this? *)\n\nlemma connected_self_connected_sum: \"(C x y \\<and> SC x \\<and> SC y) \\<longrightarrow> SC (x \\<oplus> y)\"\nproof\n  assume \"C x y \\<and> SC x \\<and> SC y\"\n  have \"\\<forall> v w. (x \\<oplus> y) = (v \\<oplus> w) \\<longrightarrow> C v w\"\n  proof\n    fix v\n    show \"\\<forall> w. (x \\<oplus> y) = (v \\<oplus> w) \\<longrightarrow> C v w\"\n    proof\n      fix w\n      show \"(x \\<oplus> y) = (v \\<oplus> w) \\<longrightarrow> C v w\"\n      proof\n        assume \"(x \\<oplus> y) = (v \\<oplus> w)\"\n        show \"C v w\"\n        proof (cases)\n          assume \"O v x \\<and> O w x \\<or> O v y \\<and> O w y\"\n          thus \"C v w\"\n          proof (rule disjE)\n            assume \"O v x \\<and> O w x\"\n            hence \"P x (v \\<oplus> w) \\<longrightarrow>  x = ((x \\<otimes> v) \\<oplus> (x \\<otimes> w))\"\n              by (simp add: \\<open>O v x \\<and> O w x\\<close> overlap_symmetric separation)\n            have \"P x (v \\<oplus> w)\"\n              by (metis \\<open>x \\<oplus> y = v \\<oplus> w\\<close> first_summand_inclusion)\n            hence \"x = ((x \\<otimes> v) \\<oplus> (x \\<otimes> w))\"\n              using \\<open>x \\<preceq> v \\<oplus> w \\<longrightarrow> x = x \\<otimes> v \\<oplus> x \\<otimes> w\\<close> by auto\n            hence \"C (x \\<otimes> v) (x \\<otimes> w)\"\n              using SC_def2 \\<open>C x y \\<and> SC x \\<and> SC y\\<close> by blast\n            hence \"C v (x \\<otimes> w)\"\n              by (metis P_of_first_factor T.E_def T_axioms \\<open>O v x \\<and> O w x\\<close> connection_symmetry monotonicity product_commutative)\n            thus \"C v w\"\n              by (metis P_of_first_factor T.E_def T_axioms \\<open>O v x \\<and> O w x\\<close> monotonicity product_commutative)\n          next\n            assume \"O v y \\<and> O w y\"\n            hence \"P y (v \\<oplus> w) \\<longrightarrow>  y = ((y \\<otimes> v) \\<oplus> (y \\<otimes> w))\"\n              by (simp add: \\<open>O v y \\<and> O w y\\<close> overlap_symmetric separation)\n            have \"P y (v \\<oplus> w)\"\n              by (metis \\<open>x \\<oplus> y = v \\<oplus> w\\<close> second_summand_inclusion)\n            hence \"y = ((y \\<otimes> v) \\<oplus> (y \\<otimes> w))\"\n              using \\<open>y \\<preceq> v \\<oplus> w \\<longrightarrow> y = y \\<otimes> v \\<oplus> y \\<otimes> w\\<close> by auto\n            hence \"C (y \\<otimes> v) (y \\<otimes> w)\"\n              using SC_def2 \\<open>C x y \\<and> SC x \\<and> SC y\\<close> by blast\n            hence \"C v (y \\<otimes> w)\"\n              by (metis E_def P_of_first_factor \\<open>O v y \\<and> O w y\\<close> connection_symmetry monotonicity product_commutative)\n            thus \"C v w\"\n              by (metis E_def P_of_first_factor \\<open>O v y \\<and> O w y\\<close> monotonicity product_commutative)\n          qed\n        next\n          assume \"\\<not> (O v x \\<and> O w x \\<or> O v y \\<and> O w y)\"\n          hence \"x = w \\<and> y = v \\<or> x = v \\<and> y = w\"\n            using identity \\<open>x \\<oplus> y = v \\<oplus> w\\<close> by auto\n          thus \"C v w\"\n            using \\<open>C x y \\<and> SC x \\<and> SC y\\<close> connection_symmetry by blast\n        qed\n      qed\n    qed\n  qed\n  thus \"SC (x \\<oplus> y)\" using SC_def2 by simp\nqed\n\nlemma \"(C x y \\<and> SC x \\<and> SC y) \\<longrightarrow> (\\<exists> z. SC z \\<and> (\\<forall> w. O w z \\<longleftrightarrow> O w x \\<or> O w y))\"\nproof\n  assume \"(C x y \\<and> SC x \\<and> SC y)\"\n  with connected_self_connected_sum have \"SC (x \\<oplus> y)\"..\n  have \"\\<forall> w. O w (x \\<oplus> y) \\<longleftrightarrow> O w x \\<or> O w y\" using sum_character.\n  hence \"SC (x \\<oplus> y) \\<and> (\\<forall> w. O w (x \\<oplus> y) \\<longleftrightarrow> O w x \\<or> O w y)\" \n    using \\<open>SC (x \\<oplus> y)\\<close> by simp\n  thus \"\\<exists> z. SC z \\<and> (\\<forall> w. O w z \\<longleftrightarrow> O w x \\<or> O w y)\"..\nqed\n\ndefinition i :: \"(i \\<Rightarrow> i)\" (\"\\<^bold>i\")--\"interior\"\n  where \"\\<^bold>i x \\<equiv> \\<sigma> z. IP z x\"\n\nlemma interior_fusion: \"(\\<exists> y. IP y x) \\<longrightarrow> (\\<exists> v. \\<forall> y. O y v \\<longleftrightarrow> (\\<exists> z. IP z x \\<and> O z y))\" using fusion.\n\nlemma interior_intro: \"(\\<forall> y. O y a \\<longleftrightarrow> (\\<exists> z. IP z x \\<and> O z y)) \\<longrightarrow> (\\<^bold>i x) = a\"\nproof -\n  have \"(\\<forall> y. O y a \\<longleftrightarrow> (\\<exists> z. IP z x \\<and> O z y)) \\<longrightarrow> (\\<sigma> z. IP z x) = a\" using general_sum_intro.\n  thus ?thesis using i_def by simp\nqed\n\nlemma interior_character: \"(\\<exists> y. IP y x) \\<longrightarrow> (\\<forall> y. O y (\\<^bold>i x) \\<longleftrightarrow> (\\<exists> z. IP z x \\<and> O z y))\"\nproof\n  assume antecedent: \"(\\<exists> y. IP y x)\"\n  with interior_fusion have \"\\<exists> v. \\<forall> y. O y v \\<longleftrightarrow> (\\<exists> z. IP z x \\<and> O z y)\"..\n  then obtain v where v: \"\\<forall> y. O y v \\<longleftrightarrow> (\\<exists> z. IP z x \\<and> O z y)\"..\n  with interior_intro have \"(\\<^bold>i x) = v\"..\n  thus \"(\\<forall> y. O y (\\<^bold>i x) \\<longleftrightarrow> (\\<exists> z. IP z x \\<and> O z y))\"\n    using v by blast\nqed\n\nlemma interior_is_part: \"(\\<exists> y. IP y x) \\<longrightarrow> P (\\<^bold>i x) x\" -- \"the interior of an individual is part of it\"\nproof\n  assume \"(\\<exists> y. IP y x)\"\n  with interior_fusion have \"\\<exists> v. \\<forall> y. O y v \\<longleftrightarrow> (\\<exists> z. IP z x \\<and> O z y)\"..\n  then obtain a where a: \"\\<forall> y. O y a \\<longleftrightarrow> (\\<exists> z. IP z x \\<and> O z y)\"..\n  with interior_intro have \"(\\<^bold>i x) = a\"..\n  thus \"P (\\<^bold>i x) x\"\n    by (metis IP_def P_overlappers_overlap a overlap_symmetric)\nqed\n\nlemma interior_overlaps: \"(\\<exists> y. IP y x) \\<longrightarrow> O (\\<^bold>i x) x\"\n  by (simp add: P_implies_overlap interior_is_part)\nlemma interior_connects:  \"(\\<exists> y. IP y x) \\<longrightarrow> C (\\<^bold>i x) x\"\n  using P_implies_overlap interior_is_part overlap_implies_connection by blast\nlemma encloses_interior:  \"(\\<exists> y. IP y x) \\<longrightarrow> E (\\<^bold>i x) x\"\n  by (simp add: interior_is_part monotonicity)\n\nlemma \"(\\<exists> y. IP y x) \\<longrightarrow> (\\<exists> y. IP y z) \\<longrightarrow> P z x \\<longrightarrow> P (\\<^bold>i z) (\\<^bold>i x)\" nitpick oops\n\ndefinition e :: \"(i\\<Rightarrow>i)\" (\"e\") -- \"exterior\"\n  where \"e x \\<equiv> \\<^bold>i (\\<midarrow> x)\"\n\nlemma exterior_closure: \"(\\<exists> y. IP y (\\<midarrow> x)) \\<longrightarrow> (\\<exists> a. \\<forall> y. O y a \\<longleftrightarrow> (\\<exists> z. IP z (\\<midarrow> x) \\<and> O z y))\" sorry (* prove this! *)\n\nlemma exterior_intro: \"(\\<forall> y. O y a \\<longleftrightarrow> (\\<exists> z. IP z (\\<midarrow> x) \\<and> O z y)) \\<longrightarrow> (e x) = a\"\nproof\n  assume \"(\\<forall> y. O y a \\<longleftrightarrow> (\\<exists> z. IP z (\\<midarrow> x) \\<and> O z y))\"\n  with interior_intro have \"(\\<^bold>i (\\<midarrow> x)) = a\"..\n  thus \"(e x) = a\"\n    using e_def by simp\nqed\n\nlemma exterior_character: \"(\\<exists> y. IP y (\\<midarrow> x)) \\<longrightarrow> (\\<forall> y. O y (e x) \\<longleftrightarrow> (\\<exists> z. IP z (\\<midarrow> x) \\<and> O z y))\" sorry (* prove this! *)\n\nlemma \"x \\<noteq> u \\<and> (\\<exists> y. IP y (\\<midarrow> x)) \\<longrightarrow> \\<not> P (e x) x\"\n  using e_def P_implies_overlap in_comp_iff_disjoint interior_is_part disjoint_def by fastforce\n\nlemma \"x \\<noteq> u \\<and> (\\<exists> y. IP y (\\<midarrow> x)) \\<longrightarrow> \\<not> P x (e x)\"\n  by (metis e_def P_implies_overlap P_overlappers_overlap complement_disjointness interior_is_part disjoint_def)\n\nlemma \"x \\<noteq> u \\<and> (\\<exists> y. IP y (\\<midarrow> x)) \\<longrightarrow> D x (e x)\"\n  using complement_disjointness P_overlappers_overlap extensional_mereology_axioms\nexterior_character interior_character interior_is_part disjoint_def by blast\n\ndefinition c :: \"i\\<Rightarrow>i\" (\"c\")--\"closure\"\n  where\n\"c x \\<equiv> \\<midarrow> (e x)\"\n\nlemma closure_intro:  \"(\\<forall> y. P y a \\<longleftrightarrow> D y (e x)) \\<longrightarrow> (c x) = a\"\n  by (metis P_antisymmetry P_implies_overlap P_overlappers_overlap P_reflexivity c_def\ncomplement_character disjoint_def overlap_def overlap_symmetric overlap_def overlap_reflexive)\n\nlemma closure_character: \"x \\<noteq> u \\<and> (\\<exists> y. IP y (\\<midarrow> x)) \\<longrightarrow> (\\<forall> y. P y (c x) \\<longleftrightarrow> D y (e x))\" sorry (* prove this *)\n\nlemma closure_closure: \"x \\<noteq> u \\<and> (\\<exists> y. IP y (\\<midarrow> x)) \\<longrightarrow> (\\<exists> a. \\<forall> y. P y a \\<longleftrightarrow> D y (e x))\"\nproof\n  assume antecedent: \"x \\<noteq> u \\<and> (\\<exists> y. IP y (\\<midarrow> x))\"\n  with closure_character have \"(\\<forall> y. P y (c x) \\<longleftrightarrow> D y (e x))\"..\n  thus \"(\\<exists> a. \\<forall> y. P y a \\<longleftrightarrow> D y (e x))\"..\nqed\n\nlemma closure_inclusion: \"x \\<noteq> u \\<and> (\\<exists> y. IP y (\\<midarrow> x)) \\<longrightarrow> P x (c x)\"\n  using closure_character disjoint_symmetric e_def in_comp_iff_disjoint interior_is_part by fastforce\n\nlemma closure_overlap: \"x \\<noteq> u \\<and> (\\<exists> y. IP y (\\<midarrow> x)) \\<longrightarrow> O x (c x)\"\n  by (simp add: P_implies_overlap closure_inclusion)\n\nlemma closure_connection: \"x \\<noteq> u \\<and> (\\<exists> y. IP y (\\<midarrow> x)) \\<longrightarrow> C x (c x)\"\n  by (simp add: closure_overlap overlap_implies_connection)\n\ndefinition b :: \"i\\<Rightarrow>i\" (\"b\")--\"boundary\"\n  where \"b x \\<equiv> \\<midarrow> (\\<^bold>i x \\<oplus> e x)\"\n\nlemma boundary_closure: \"(\\<^bold>i x \\<oplus> e x) \\<noteq> u \\<longrightarrow> x \\<noteq> u \\<longrightarrow> (\\<exists> z. IP z x) \\<longrightarrow> (\\<exists> z. IP z (\\<midarrow> x)) \\<longrightarrow> (\\<exists> a. \\<forall> z. P z a \\<longleftrightarrow> D z (\\<^bold>i x \\<oplus> e x))\" sorry  (* prove this *)\n\nlemma boundary_intro : \"(\\<forall> w. P w a \\<longleftrightarrow> D w (\\<^bold>i x \\<oplus> e x)) \\<longrightarrow> b x = a\" (* Very good work on proving this in the last version *)\n  by (metis P_antisymmetry P_implies_overlap P_reflexivity b_def complement_character disjoint_def)\n\nlemma boundary_character: \"(\\<^bold>i x \\<oplus> e x) \\<noteq> u \\<longrightarrow> x \\<noteq> u \\<longrightarrow> (\\<exists> z. IP z x) \\<longrightarrow> (\\<exists> z. IP z (\\<midarrow> x)) \\<longrightarrow> (\\<forall> z. P z (b x) \\<longleftrightarrow> D z (\\<^bold>i x \\<oplus> e x))\" sorry (*prove this*)\n\ntext {* The following axioms are from Varzi \"Parts, Wholes and Part-Whole Relations: The Prospects of Mereotopology page 273: *}\n\ndefinition OP :: \"i \\<Rightarrow> bool\" (\"OP\")--\"open\"\n  where \"OP x \\<equiv> \\<^bold>i x = x\"\n\ndefinition CL :: \"i \\<Rightarrow> bool\" (\"CL\") -- \"closed\"\n  where \"CL x \\<equiv> c x = x\"\n\nend\n\nlocale GEMTC = GEMT + \n  assumes C4: \"CL x \\<and> CL y \\<longrightarrow> CL (x \\<oplus> y)\" \n  assumes C5: \"(\\<forall> x. F x \\<longrightarrow> Cl x) \\<longrightarrow> (\\<exists> z. \\<forall> y. F y \\<longrightarrow> z \\<preceq> y) \\<longrightarrow> CL (\\<pi> z. F z)\"\n\nbegin\n\nlemma C4': \"OP x \\<and> OP y \\<longrightarrow> z = x \\<otimes> y \\<longrightarrow> OP z\"  sorry (* can your prove this? *)\n\nlemma C5': \"(\\<exists> x. F x) \\<longrightarrow> (\\<forall> x. F x \\<longrightarrow> OP x) \\<longrightarrow> OP (\\<sigma> x. F x)\"  sorry (* can you prove this? *)\n\nlemma interior_inclusion : \"\\<exists> y. IP y x \\<longrightarrow> P (\\<^bold>i x) x\"\n  by (simp add: IP_def)\n\nlemma interior_idempotence: \"\\<exists> y. IP y x \\<longrightarrow> \\<^bold>i (\\<^bold>i x) = \\<^bold>i x\"\n  by (metis IP_def P_overlappers_overlap interior_character internal_part_antisymmetry overlap_reflexive)\n\nlemma interior_distributes_over_product: \n\"(\\<exists> z. IP z (x \\<otimes> y)) \\<and> (\\<exists> z. IP z x) \\<and> (\\<exists> z. IP z y) \\<longrightarrow> \\<^bold>i (x \\<otimes> y) = \\<^bold>i x \\<otimes> \\<^bold>i y\" sorry (* This proof might be a hard one. *)\n\nlemma closure_inclusion: \"(\\<exists> y. IP y (\\<midarrow> x)) \\<longrightarrow> P x (c x)\" sorry (* can you prove this? *)\n\nlemma closure_idempotence: \"(\\<exists> y. IP y (\\<midarrow> x)) \\<longrightarrow> c (c x) = c x\"  sorry (* can you prove this? *)\n\nlemma closure_distributes_over_sum:\n\"(\\<exists> z. IP z (\\<midarrow>(x \\<oplus> y))) \\<longrightarrow> (\\<exists> z. IP z (\\<midarrow> x)) \\<longrightarrow> (\\<exists> z. IP z (\\<midarrow> y)) \\<longrightarrow> c (x \\<oplus> y) = c x \\<oplus> c y\" sorry (* This proof might be a hard one. *)\n\nlemma boundary_sharing:\n  assumes \"(\\<^bold>i x \\<oplus> e x) \\<noteq> u \\<longrightarrow> x \\<noteq> u \\<longrightarrow> (\\<exists> z. IP z x) \\<longrightarrow> (\\<exists> z. IP z (\\<midarrow> x))\"\n  shows  \"b x = b (\\<midarrow> x)\"  sorry  (* can your prove this? *)\n\nlemma boundary_idempotence: \n  assumes \"(\\<^bold>i x \\<oplus> e x) \\<noteq> u \\<longrightarrow> x \\<noteq> u \\<longrightarrow> (\\<exists> z. IP z x) \\<longrightarrow> (\\<exists> z. IP z (\\<midarrow> x))\"\n  shows \"b (b x) = b x\"  sorry  (* can your prove this? *)\n\nlemma boundary_distributes_over_sum:\n  assumes \"(\\<^bold>i x \\<oplus> e x) \\<noteq> u \\<longrightarrow> x \\<noteq> u \\<longrightarrow> (\\<exists> z. IP z x) \\<longrightarrow> (\\<exists> z. IP z (\\<midarrow> x))\"\n  shows \"b (x \\<otimes> y) \\<oplus> b (x \\<oplus> y) = b x \\<oplus> b y\"  sorry (* can your prove this? *)\n\n(* These lemmas look helpful - well done: *)\n\nlemma p_intro : \"(\\<forall>z. P a z \\<longleftrightarrow> (P z (\\<^bold>i x) \\<and> P z (\\<^bold>i y))) \\<longrightarrow> ((\\<^bold>i x) \\<otimes> (\\<^bold>i y)) = a\"\n  by (metis (full_types) P_antisymmetry P_implies_overlap complement_disjointness disjoint_def universe_closure universe_intro)\n\nlemma p : \"(\\<forall>z. P a z \\<longleftrightarrow> (P z x \\<and> P z y)) \\<longrightarrow> (x \\<otimes> y) = a\"\n  by (metis P_antisymmetry P_implies_overlap disjoint_def in_comp_iff_disjoint universe_closure)\n\nlemma pi : \"(\\<exists>w. IP a w \\<and> (\\<forall>v. P w v \\<longleftrightarrow> P v x \\<and> P v y)\\<longrightarrow> a = \\<^bold>i (x \\<otimes> y))\"\n  by (meson P_antisymmetry P_reflexivity)\n\nlemma pi2 : \"(\\<forall>z. O z a \\<longleftrightarrow> (\\<exists>w. IP w (x \\<otimes> y) \\<and> O w z))\\<longrightarrow> \\<^bold>i (x \\<otimes> y) = a\" sledgehammer oops\n\nlemma Px : \"\\<exists>w. IP (x \\<otimes> y) w \\<longrightarrow> (\\<forall>v. P w v \\<longleftrightarrow> P v x \\<and> P v y)\" sledgehammer oops\n\nlemma \"(\\<forall>v.\\<exists>w. P w v \\<and> P v x \\<and> P v y \\<longrightarrow> P w x \\<and> P w y)\"\n  by auto\n\nlemma Pi3 : \"\\<exists>w. IP (x \\<otimes> y) w \\<longrightarrow> P w x \\<and> P w y\"\n  using IP_def by blast\n\nlemma pp : \"(\\<exists>z. IP z (x \\<otimes> y)) \\<longrightarrow> P (\\<^bold>i (x \\<otimes> y)) (x \\<otimes> y)\"\n  using interior_is_part by auto\n\nlemma \"\\<not> (\\<forall> x. C x a) \\<longrightarrow> (\\<forall> y. P y (e a) \\<longleftrightarrow> \\<not> C y a)\"  oops\n\nlemma \"x \\<noteq> u \\<longrightarrow> (\\<forall> y. P y (c x) \\<longleftrightarrow> P y x \\<or> (\\<forall> z. P z y \\<longrightarrow> C z x))\"  oops\n\nlemma  C_iff_O_orEC: \"C x y \\<longleftrightarrow> (O x y \\<or> EC x y)\"\n  using EC_def disjoint_def overlap_implies_connection by blast\n\nlemma  \"EC x y \\<longrightarrow> (\\<exists> y. IP y (\\<midarrow> x))\"  oops\n\n(* The following theses are still the main ones left to prove. But I don't feel we can attack it until\nwe at least understand the informal idea behind it. I will find out about this for you. *)\n\nlemma C_implies_O_c:  \"C x y \\<longrightarrow> (O x (c y) \\<or> O (c x) y)\"  oops\n\nlemma EC_implies_O_c: \"((\\<exists> z. IP z (\\<midarrow> x)) \\<or> (\\<exists> z. IP z (\\<midarrow> y))) \\<longrightarrow> \nEC x y \\<longrightarrow> (O x (c y) \\<or> O (c x) y)\"\nproof \n  assume \"(\\<exists> z. IP z (\\<midarrow> x)) \\<or> (\\<exists> z. IP z (\\<midarrow> y))\"\n  thus \"EC x y \\<longrightarrow> (O x (c y) \\<or> O (c x) y)\"\n  proof (rule disjE)\n    assume \"\\<exists> z. IP z (\\<midarrow> x)\"\n    show \"EC x y \\<longrightarrow> (O x (c y) \\<or> O (c x) y)\"\n    proof\n      assume \"EC x y\"\n      hence \"x \\<noteq> u\"\n        using EC_def P_implies_overlap disjoint_def overlap_symmetric universe_character by blast\n      hence \"x \\<noteq> u \\<and> (\\<exists> z. IP z (\\<midarrow> x))\" using \\<open>\\<exists>z. IP z (\\<midarrow> x)\\<close>..\n      with closure_closure have \"(\\<exists> a. \\<forall> y. P y a \\<longleftrightarrow> D y (e x))\"..\n      then obtain a where a: \"\\<forall> y. P y a \\<longleftrightarrow> D y (e x)\"..\n      with closure_intro have \"(c x) = a\"..\n      hence \"O (c x) y\" sorry\n      thus \"O x (c y) \\<or> O (c x) y\"..\n    qed\n  next\n    assume \"(\\<exists> z. IP z (\\<midarrow> y))\"\n    show \"EC x y \\<longrightarrow> (O x (c y) \\<or> O (c x) y)\"\n    proof\n      assume \"EC x y\"\n      hence \"O x (c y)\" sorry\n      thus \"O x (c y) \\<or> O (c x) y\"..\n    qed\n  qed\nqed\n\nlemma \"C x y \\<longleftrightarrow> (O x y \\<or> (O x (c y) \\<or> O (c x) y))\" nitpick oops\n\nlemma \"C x y \\<longleftrightarrow> (O x y \\<or> (O x (c y) \\<or> O (c x) y))\"\nproof\n  assume \"C x y\"\n  show \"O x y \\<or> (O x (c y) \\<or> O (c x) y)\"\n  proof\n    cases\n    assume \"O x y\"\n    thus \"O x y \\<or> (O x (c y) \\<or> O (c x) y)\"..\n  next assume \"D x y\"\n    hence \"EC x y\" using EC_def \\<open>C x y\\<close> by blast\n    hence \"(O x (c y) \\<or> O (c x) y)\"\n      using EC_implies_O_c by blast\n    thus \"(O x y \\<or> (O x (c y) \\<or> O (c x) y))\"..\n  qed\nnext\n  assume \"O x y \\<or> (O x (c y) \\<or> O (c x) y)\"\n  thus \"C x y\" \n  proof (rule disjE)\n    assume \"O x y\"\n    thus \"C x y\" by (simp add: overlap_imnplies_connection)\n  next\n    assume \"(O x (c y) \\<or> O (c x) y)\"\n    thus \"C x y\"\n    proof (rule disjE)\n      assume \"O x (c y)\"\n      show \"C x y\"\n      proof cases\n        assume \"y = u\"\n        hence \"O x y\"\n          by (simp add: T11 T51a)\n        thus \"C x y\" by (simp add: overlap_imnplies_connection)\n      next\n        assume \"y \\<noteq> u\"\n        thus \"C x y\"  sorry\n      qed\n        next\n          assume \"O (c x) y\"\n      show \"C x y\"\n      proof\n        cases\n        assume \"x = u\"\n        thus \"C x y\" using T10 T11 T51a overlap_imnplies_connection by blast\n        next\n          assume \"x \\<noteq> u\"\n          thus \"C x y\"  sorry\n        qed\n      qed\n    qed\n  qed\n\nlemma \"(\\<exists> z. IP z x) \\<and> (\\<exists> z. IP z y) \\<longrightarrow> EC x y \\<longrightarrow> C z y \\<and> \\<not> C (\\<^bold>i x) (\\<^bold>i y)\" oops\n\nlemma \"C x y \\<longleftrightarrow> (O x y \\<or> (O x (c y) \\<or> O (c x) y))\" oops\n\nlemma  \"x \\<noteq> u \\<and> (\\<exists> z. IP z (\\<midarrow> x)) \\<and> y \\<noteq> u \\<and> (\\<exists> z. IP z (\\<midarrow> y)) \\<longrightarrow>\n C x y \\<longleftrightarrow> (O x y \\<or> (O x (c y) \\<or> O (c x) y))\" sledgehammer oops\n\nlemma (in GEmonotonicity) \"x \\<noteq> u \\<and> (\\<exists> z. IP z (\\<midarrow> x)) \\<and> y \\<noteq> u \\<and> (\\<exists> z. IP z (\\<midarrow> y)) \\<longrightarrow>\n C x y \\<longleftrightarrow> (O x y \\<or> (O x (c y) \\<or> O (c x) y))\" sledgehammer oops\n\ndefinition SSC :: \"i\\<Rightarrow>bool\" (\"SSC\")\n  where\n\"SSC x \\<equiv> SC x \\<and> SC (\\<^bold>i x) \"\n\ndefinition MSSC :: \"(i\\<Rightarrow>bool)\" (\"MSSC\")\n  where\n\"MSSC x \\<equiv> SSC x \\<and> (\\<forall>y. (SSC y \\<and> O y x) \\<longrightarrow> P y x)\"\n\nend\n", "meta": {"author": "Manikaran20", "repo": "Mereology", "sha": "d71a0c42c48e370e64bbeb85cee7d0ba5c2d388e", "save_path": "github-repos/isabelle/Manikaran20-Mereology", "path": "github-repos/isabelle/Manikaran20-Mereology/Mereology-d71a0c42c48e370e64bbeb85cee7d0ba5c2d388e/Mereotopology.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9149009526726545, "lm_q2_score": 0.7690802370707283, "lm_q1q2_score": 0.7036322415777202}}
{"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.*)\n  theory TIP_prop_84\nimports \"../../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) z = nil2\"\n| \"zip (cons2 z2 x2) (nil2) = nil2\"\n| \"zip (cons2 z2 x2) (cons2 x3 x4) =\n     cons2 (pair2 z2 x3) (zip x2 x4)\"\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 take :: \"Nat => 'a list => 'a list\" where\n\"take (Z) z = nil2\"\n| \"take (S z2) (nil2) = nil2\"\n| \"take (S z2) (cons2 x2 x3) = cons2 x2 (take z2 x3)\"\n\nfun len :: \"'a list => Nat\" where\n\"len (nil2) = Z\"\n| \"len (cons2 z xs) = S (len xs)\"\n\nfun drop :: \"Nat => 'a list => 'a list\" where\n\"drop (Z) z = z\"\n| \"drop (S z2) (nil2) = nil2\"\n| \"drop (S z2) (cons2 x2 x3) = drop z2 x3\"\n\ntheorem property0 :\n  \"((zip xs (x ys zs)) =\n      (x (zip (take (len ys) xs) ys) (zip (drop (len ys) xs) zs)))\"\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/Isaplanner/Isaplanner/TIP_prop_84.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972751232808, "lm_q2_score": 0.8080672158638528, "lm_q1q2_score": 0.7035011162475262}}
{"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.*)\n  theory TIP_prop_81\nimports \"../../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 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\nfun t2 :: \"Nat => Nat => Nat\" where\n\"t2 (Z) y = y\"\n| \"t2 (S z) y = S (t2 z y)\"\n\ntheorem property0 :\n  \"((take n (drop m xs)) = (drop m (take (t2 n m) 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/Isaplanner/Isaplanner/TIP_prop_81.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206870747658, "lm_q2_score": 0.7799928951399098, "lm_q1q2_score": 0.7034917278980232}}
{"text": "(*  Title:       Category theory using Isar and Locales\n    Author:      Greg O'Keefe, June, July, August 2003\n    License: LGPL\n\nFunctors: Define functors and prove a trivial example.\n*)\n\nsection \\<open>Functors\\<close>\n\ntheory Functors\nimports Cat\nbegin\n\nsubsection \\<open>Definitions\\<close>\n\nrecord ('o1,'a1,'o2,'a2) \"functor\" =\n  om :: \"'o1 \\<Rightarrow> 'o2\"\n  am :: \"'a1 \\<Rightarrow> 'a2\"\n\nabbreviation\n  om_syn  (\"_ \\<^bsub>\\<o>\\<^esub>\" [81]) where\n  \"F\\<^bsub>\\<o>\\<^esub> \\<equiv> om F\"\n\nabbreviation\n  am_syn  (\"_ \\<^bsub>\\<a>\\<^esub>\" [81]) where\n  \"F\\<^bsub>\\<a>\\<^esub> \\<equiv> am F\"\n\nlocale two_cats = AA?: category AA + BB?: category BB\n    for AA :: \"('o1,'a1,'m1)category_scheme\" (structure)\n    and BB :: \"('o2,'a2,'m2)category_scheme\" (structure) + \n  fixes preserves_dom  ::  \"('o1,'a1,'o2,'a2)functor \\<Rightarrow> bool\"\n    and preserves_cod  ::  \"('o1,'a1,'o2,'a2)functor \\<Rightarrow> bool\"\n    and preserves_id  ::  \"('o1,'a1,'o2,'a2)functor \\<Rightarrow> bool\"\n    and preserves_comp  ::  \"('o1,'a1,'o2,'a2)functor \\<Rightarrow> bool\"\n  defines \"preserves_dom G \\<equiv> \\<forall>f\\<in>Ar\\<^bsub>AA\\<^esub>. G\\<^bsub>\\<o>\\<^esub> (Dom\\<^bsub>AA\\<^esub> f) = Dom\\<^bsub>BB\\<^esub> (G\\<^bsub>\\<a>\\<^esub> f)\"\n    and \"preserves_cod G \\<equiv> \\<forall>f\\<in>Ar\\<^bsub>AA\\<^esub>. G\\<^bsub>\\<o>\\<^esub> (Cod\\<^bsub>AA\\<^esub> f) = Cod\\<^bsub>BB\\<^esub> (G\\<^bsub>\\<a>\\<^esub> f)\"\n    and \"preserves_id G \\<equiv> \\<forall>A\\<in>Ob\\<^bsub>AA\\<^esub>. G\\<^bsub>\\<a>\\<^esub> (Id\\<^bsub>AA\\<^esub> A) = Id\\<^bsub>BB\\<^esub> (G\\<^bsub>\\<o>\\<^esub> A)\"\n    and \"preserves_comp G \\<equiv>\n      \\<forall>f\\<in>Ar\\<^bsub>AA\\<^esub>. \\<forall>g\\<in>Ar\\<^bsub>AA\\<^esub>. Cod\\<^bsub>AA\\<^esub> f = Dom\\<^bsub>AA\\<^esub> g \\<longrightarrow> G\\<^bsub>\\<a>\\<^esub> (g \\<bullet>\\<^bsub>AA\\<^esub> f) = (G\\<^bsub>\\<a>\\<^esub> g) \\<bullet>\\<^bsub>BB\\<^esub> (G\\<^bsub>\\<a>\\<^esub> f)\"\n\nlocale \"functor\" = two_cats +\n  fixes F (structure)\n  assumes F_preserves_arrows: \"F\\<^bsub>\\<a>\\<^esub> : Ar\\<^bsub>AA\\<^esub> \\<rightarrow> Ar\\<^bsub>BB\\<^esub>\"\n    and F_preserves_objects: \"F\\<^bsub>\\<o>\\<^esub> : Ob\\<^bsub>AA\\<^esub> \\<rightarrow> Ob\\<^bsub>BB\\<^esub>\"\n    and F_preserves_dom: \"preserves_dom F\"\n    and F_preserves_cod: \"preserves_cod F\"\n    and F_preserves_id: \"preserves_id F\"\n    and F_preserves_comp: \"preserves_comp F\"\nbegin\n\nlemmas F_axioms = F_preserves_arrows F_preserves_objects F_preserves_dom \n  F_preserves_cod F_preserves_id F_preserves_comp\n\nlemmas func_pred_defs = preserves_dom_def preserves_cod_def preserves_id_def preserves_comp_def\n\nend\n\ntext \\<open>This gives us nicer notation for asserting that things are functors.\\<close>\n\nabbreviation\n  Functor  (\"Functor _ : _ \\<longrightarrow> _\" [81]) where\n  \"Functor F : AA \\<longrightarrow> BB \\<equiv> functor AA BB F\"\n\n\nsubsection \\<open>Simple Lemmas\\<close>\n\ntext \\<open>For example:\\<close>\n\nlemma (in \"functor\") \"Functor F : AA \\<longrightarrow> BB\" ..\n\n\nlemma functors_preserve_arrows [intro]:\n  assumes \"Functor F : AA \\<longrightarrow> BB\"\n    and \"f \\<in> ar AA\"\n  shows \"F\\<^bsub>\\<a>\\<^esub> f \\<in> ar BB\"\nproof-\n  from \\<open>Functor F : AA \\<longrightarrow> BB\\<close>\n  have \"F\\<^bsub>\\<a>\\<^esub> : ar AA \\<rightarrow> ar BB\"\n    by (simp add: functor_def functor_axioms_def)\n  from this and \\<open>f \\<in> ar AA\\<close>\n  show ?thesis by (rule funcset_mem)\nqed\n\n\nlemma (in \"functor\") functors_preserve_homsets:\n  assumes 1: \"A \\<in> Ob\\<^bsub>AA\\<^esub>\"\n  and 2: \"B \\<in> Ob\\<^bsub>AA\\<^esub>\"\n  and 3: \"f \\<in> Hom\\<^bsub>AA\\<^esub> A B\"\n  shows \"F\\<^bsub>\\<a>\\<^esub> f \\<in> Hom\\<^bsub>BB\\<^esub> (F\\<^bsub>\\<o>\\<^esub> A) (F\\<^bsub>\\<o>\\<^esub> B)\"\nproof-\n  from 3 \n  have 4: \"f \\<in> Ar\" \n    by (simp add: hom_def)\n  with F_preserves_arrows \n  have 5: \"F\\<^bsub>\\<a>\\<^esub> f \\<in> Ar\\<^bsub>BB\\<^esub>\" \n    by (rule funcset_mem)\n  from 4 and F_preserves_dom \n  have \"Dom\\<^bsub>BB\\<^esub> (F\\<^bsub>\\<a>\\<^esub> f) = F\\<^bsub>\\<o>\\<^esub> (Dom\\<^bsub>AA\\<^esub> f)\"\n    by (simp add: preserves_dom_def)\n  also from 3 have \"\\<dots> = F\\<^bsub>\\<o>\\<^esub> A\"\n    by (simp add: hom_def)\n  finally have 6: \"Dom\\<^bsub>BB\\<^esub> (F\\<^bsub>\\<a>\\<^esub> f) = F\\<^bsub>\\<o>\\<^esub> A\" .\n  from 4 and F_preserves_cod \n  have \"Cod\\<^bsub>BB\\<^esub> (F\\<^bsub>\\<a>\\<^esub> f) = F\\<^bsub>\\<o>\\<^esub> (Cod\\<^bsub>AA\\<^esub> f)\"\n    by (simp add: preserves_cod_def)\n  also from 3 have \"\\<dots> = F\\<^bsub>\\<o>\\<^esub> B\"\n    by (simp add: hom_def)\n  finally have 7: \"Cod\\<^bsub>BB\\<^esub> (F\\<^bsub>\\<a>\\<^esub> f) = F\\<^bsub>\\<o>\\<^esub> B\" .\n  from 5 and 6 and 7\n  show ?thesis\n    by (simp add: hom_def)\nqed\n    \n\nlemma functors_preserve_objects [intro]:\n  assumes \"Functor F : AA \\<longrightarrow> BB\"\n    and \"A \\<in> ob AA\"\n  shows \"F\\<^bsub>\\<o>\\<^esub> A \\<in> ob BB\"\nproof-\n  from \\<open>Functor F : AA \\<longrightarrow> BB\\<close>\n  have \"F\\<^bsub>\\<o>\\<^esub> : ob AA \\<rightarrow> ob BB\"\n    by (simp add: functor_def functor_axioms_def)\n  from this and \\<open>A \\<in> ob AA\\<close>\n  show ?thesis by (rule funcset_mem)\nqed\n\n\nsubsection \\<open>Identity Functor\\<close>\n\ndefinition\n  id_func :: \"('o,'a,'m) category_scheme \\<Rightarrow> ('o,'a,'o,'a) functor\" where\n  \"id_func CC = \\<lparr>om=(\\<lambda>A\\<in>ob CC. A), am=(\\<lambda>f\\<in>ar CC. f)\\<rparr>\"\n\nlocale one_cat = two_cats +\n  assumes endo: \"BB = AA\"\n\nlemma (in one_cat) id_func_preserves_arrows:\n  shows \"(id_func AA)\\<^bsub>\\<a>\\<^esub> : Ar \\<rightarrow> Ar\"\n  by (unfold id_func_def, rule funcsetI, simp)\n\n\nlemma (in one_cat) id_func_preserves_objects:\n  shows \"(id_func AA)\\<^bsub>\\<o>\\<^esub> : Ob \\<rightarrow> Ob\"\n  by (unfold id_func_def, rule funcsetI, simp)\n\n\nlemma (in one_cat) id_func_preserves_dom:\n  shows  \"preserves_dom (id_func AA)\"\nunfolding preserves_dom_def endo\nproof\n  fix f\n  assume f: \"f \\<in> Ar\"\n  hence lhs: \"(id_func AA)\\<^bsub>\\<o>\\<^esub> (Dom f) = Dom f\"\n    by (simp add: id_func_def) auto\n  have \"(id_func AA)\\<^bsub>\\<a>\\<^esub> f = f\"\n    using f by (simp add: id_func_def)\n  hence rhs: \"Dom (id_func AA)\\<^bsub>\\<a>\\<^esub> f = Dom f\"\n    by simp\n  from lhs and rhs show \"(id_func AA)\\<^bsub>\\<o>\\<^esub> (Dom f) = Dom (id_func AA)\\<^bsub>\\<a>\\<^esub> f\"\n    by simp\nqed\n\nlemma (in one_cat) id_func_preserves_cod:\n  \"preserves_cod (id_func AA)\"\napply (unfold preserves_cod_def, simp only: endo)\nproof\n  fix f\n  assume f: \"f \\<in> Ar\"\n  hence lhs: \"(id_func AA)\\<^bsub>\\<o>\\<^esub> (Cod f) = Cod f\"\n    by (simp add: id_func_def) auto\n  have \"(id_func AA)\\<^bsub>\\<a>\\<^esub> f = f\"\n    using f by (simp add: id_func_def)\n  hence rhs: \"Cod (id_func AA)\\<^bsub>\\<a>\\<^esub> f = Cod f\"\n    by simp\n  from lhs and rhs show \"(id_func AA)\\<^bsub>\\<o>\\<^esub> (Cod f) = Cod (id_func AA)\\<^bsub>\\<a>\\<^esub> f\"\n    by simp\nqed\n\n\nlemma (in one_cat) id_func_preserves_id:\n  \"preserves_id (id_func AA)\"\nunfolding preserves_id_def endo\nproof\n  fix A\n  assume A: \"A \\<in> Ob\"\n  hence lhs: \"(id_func AA)\\<^bsub>\\<a>\\<^esub> (Id A) = Id A\"\n    by (simp add: id_func_def) auto\n  have \"(id_func AA)\\<^bsub>\\<o>\\<^esub> A = A\"\n    using A by (simp add: id_func_def)\n  hence rhs: \"Id ((id_func AA)\\<^bsub>\\<o>\\<^esub> A) = Id A\"\n    by simp\n  from lhs and rhs show \"(id_func AA)\\<^bsub>\\<a>\\<^esub> (Id A) = Id ((id_func AA)\\<^bsub>\\<o>\\<^esub> A)\"\n    by simp\nqed\n\n\nlemma (in one_cat) id_func_preserves_comp:\n  \"preserves_comp (id_func AA)\"\nunfolding preserves_comp_def endo\nproof (intro ballI impI)\n  fix f and g\n  assume f: \"f \\<in> Ar\" and g: \"g \\<in> Ar\" and \"Cod f = Dom g\"\n  then have \"g \\<bullet> f \\<in> Ar\" ..\n  hence lhs: \"(id_func AA)\\<^bsub>\\<a>\\<^esub> (g \\<bullet> f) = g \\<bullet> f\"\n    by (simp add: id_func_def)\n  have id_f: \"(id_func AA)\\<^bsub>\\<a>\\<^esub> f = f\"\n    using f by (simp add: id_func_def)\n  have id_g: \"(id_func AA)\\<^bsub>\\<a>\\<^esub> g = g\"\n    using g by (simp add: id_func_def)\n  hence rhs: \"(id_func AA)\\<^bsub>\\<a>\\<^esub> g \\<bullet> (id_func AA)\\<^bsub>\\<a>\\<^esub> f = g \\<bullet> f\"\n    by (simp add: id_f id_g)\n  from lhs and rhs \n  show \"(id_func AA)\\<^bsub>\\<a>\\<^esub> (g \\<bullet> f) = (id_func AA)\\<^bsub>\\<a>\\<^esub> g \\<bullet> (id_func AA)\\<^bsub>\\<a>\\<^esub> f\"\n    by simp\nqed\n\ntheorem (in one_cat) id_func_functor:\n  \"Functor (id_func AA) : AA \\<longrightarrow> AA\"\nproof-\n  from id_func_preserves_arrows\n    and id_func_preserves_objects\n    and id_func_preserves_dom\n    and id_func_preserves_cod\n    and id_func_preserves_id\n    and id_func_preserves_comp\n  show ?thesis\n    by unfold_locales (simp_all add: endo preserves_dom_def\n      preserves_cod_def preserves_id_def preserves_comp_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/Category/Functors.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.875787001374006, "lm_q2_score": 0.8031737963569014, "lm_q1q2_score": 0.7034091706935872}}
{"text": "chapter \\<open>General Lemmas for Proving Function Inequalities\\<close>\n\ntheory Bounds_Lemmas\nimports Complex_Main\n\nbegin\n\ntext\\<open>These are for functions that are differentiable over a closed interval.\\<close>\n\nlemma gen_lower_bound_increasing:\n  fixes a :: real\n  assumes \"a \\<le> x\"\n      and \"\\<And>y. a \\<le> y \\<Longrightarrow> y \\<le> x \\<Longrightarrow> ((\\<lambda>x. fl x - f x) has_real_derivative g y) (at y)\"\n      and \"\\<And>y. a \\<le> y \\<Longrightarrow> y \\<le> x \\<Longrightarrow> g y \\<le> 0\"\n      and \"fl a = f a\"\n    shows \"fl x \\<le> f x\"\nproof -\n  have \"fl x - f x \\<le> fl a - f a\"\n    apply (rule DERIV_nonpos_imp_nonincreasing [where f = \"\\<lambda>x. fl x - f x\"])\n    apply (rule assms)\n    apply (intro allI impI exI conjI)\n    apply (rule assms | simp)+\n    done\n  also have \"... = 0\"\n    by (simp add: assms)\n  finally show ?thesis\n    by simp\nqed\n\nlemma gen_lower_bound_decreasing:\n  fixes a :: real\n  assumes \"x \\<le> a\"\n      and \"\\<And>y. x \\<le> y \\<Longrightarrow> y \\<le> a \\<Longrightarrow> ((\\<lambda>x. fl x - f x) has_real_derivative g y) (at y)\"\n      and \"\\<And>y. x \\<le> y \\<Longrightarrow> y \\<le> a \\<Longrightarrow> g y \\<ge> 0\"\n      and \"fl a = f a\"\n    shows \"fl x \\<le> f x\"\nproof -\n  have \"fl (- (-x)) \\<le> f (- (-x))\"\n    apply (rule gen_lower_bound_increasing [of \"-a\" \"-x\" _ _ \"\\<lambda>u. - g (-u)\"])\n    apply (auto simp: assms)\n    apply (subst DERIV_mirror [symmetric])\n    apply (simp add: assms)\n    done\n  then show ?thesis\n    by simp\nqed\n\nlemma gen_upper_bound_increasing:\n  fixes a :: real\n  assumes \"a \\<le> x\"\n      and \"\\<And>y. a \\<le> y \\<Longrightarrow> y \\<le> x \\<Longrightarrow> ((\\<lambda>x. fu x - f x) has_real_derivative g y) (at y)\"\n      and \"\\<And>y. a \\<le> y \\<Longrightarrow> y \\<le> x \\<Longrightarrow> g y \\<ge> 0\"\n      and \"fu a = f a\"\n    shows \"f x \\<le> fu x\"\napply (rule gen_lower_bound_increasing [of a x f fu  \"\\<lambda>u. - g u\"])\nusing assms DERIV_minus [where f = \"\\<lambda>x. fu x - f x\"]\napply auto\ndone\n\nlemma gen_upper_bound_decreasing:\n  fixes a :: real\n  assumes \"x \\<le> a\"\n      and \"\\<And>y. x \\<le> y \\<Longrightarrow> y \\<le> a \\<Longrightarrow> ((\\<lambda>x. fu x - f x) has_real_derivative g y) (at y)\"\n      and \"\\<And>y. x \\<le> y \\<Longrightarrow> y \\<le> a \\<Longrightarrow> g y \\<le> 0\"\n      and \"fu a = f a\"\n    shows \"f x \\<le> fu x\"\napply (rule gen_lower_bound_decreasing [of x a _ _  \"\\<lambda>u. - g u\"])\nusing assms DERIV_minus [where f = \"\\<lambda>x. fu x - f x\"]\napply auto\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/Special_Function_Bounds/Bounds_Lemmas.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869851639066, "lm_q2_score": 0.8031737987125612, "lm_q1q2_score": 0.7034091597371164}}
{"text": "header {* Example usage of the ``sturm'' method *}\n(* Author: Manuel Eberl <eberlm@in.tum.de> *)\ntheory Sturm_Ex\nimports \"../Sturm\"\nbegin\n\ntext {*\n  In this section, we give a variety of statements about real polynomials that can b\n  proven by the \\emph{sturm} method.\n*}\n\nlemma\n \"\\<forall>x::real. x^2 + 1 \\<noteq> 0\"\nby sturm\n\nlemma\n  fixes x :: real\n  shows \"x^2 + 1 \\<noteq> 0\" by sturm\n\nlemma \"(x::real) > 1 \\<Longrightarrow> x^3 > 1\" by sturm\n\nlemma \"\\<forall>x::real. x*x \\<noteq> -1\" by sturm\n\nschematic_lemma A:\n\"card {x::real. -0.010831 < x \\<and> x < 0.010831 \\<and> \n    1/120*x^5 + 1/24*x^4 +1/6*x^3 - 49/16777216*x^2 - 17/2097152*x = 0} \n  = ?n\"\n  by sturm\n\nlemma \"card {x::real. x^3 + x = 2*x^2 \\<and> x^3 - 6*x^2 + 11*x = 6} = 1\" \nby sturm\n\n\nschematic_lemma \"card {x::real. x^3 + x = 2*x^2 \\<or> x^3 - 6*x^2 + 11*x = 6} = ?n\" by sturm\n\nlemma\n  \"card {x::real. -0.010831 < x \\<and> x < 0.010831 \\<and> \n     poly [:0, -17/2097152, -49/16777216, 1/6, 1/24, 1/120:] x = 0} = 3\"\n  by sturm\n\nlemma \"\\<forall>x::real. x*x \\<noteq> 0 \\<or> x*x - 1 \\<noteq> 2*x\" by sturm\n\nlemma \"(x::real)*x+1 \\<noteq> 0 \\<and> (x^2+1)*(x^2+2) \\<noteq> 0\" by sturm\n\ntext{*3 examples related to continued fraction approximants to exp: LCP*}\nlemma fixes x::real\n  shows \"-7.29347719 \\<le> x \\<Longrightarrow> 0 < x^5 + 30*x^4 + 420*x^3 + 3360*x^2 + 15120*x + 30240\"\nby sturm\n\nlemma fixes x::real\n  shows \"0 < x^6 + 42*x^5 + 840*x^4 + 10080*x^3 + 75600*x\\<^sup>2 + 332640*x + 665280\"\nby sturm\n\nschematic_lemma \"card {x::real. x^7 + 56*x^6 + 1512*x^5 + 25200*x^4 + 277200*x^3 + 1995840*x^2 + 8648640*x = -17297280} = ?n\" \nby sturm\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/Sturm_Sequences/Examples/Sturm_Ex.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869851639066, "lm_q2_score": 0.8031737869342623, "lm_q1q2_score": 0.7034091494218355}}
{"text": "\\<^marker>\\<open>creator \"Alexander Krauss\"\\<close>\n\\<^marker>\\<open>creator \"Josh Chen\"\\<close>\n\\<^marker>\\<open>creator \"Kevin Kappelmann\"\\<close>\nsection\\<open>Ordinals\\<close>\ntheory Ordinals\n  imports Least_Fixpoint\nbegin\n\ntext \\<open>The class of ordinal numbers is defined abstractly, as the \\<in>-transitive sets\nwhose members are also \\<in>-transitive.\\<close>\n\ndefinition [typedef]: \"Ord \\<equiv> type (\\<lambda>x. mem_trans x \\<and> (\\<forall>y \\<in> x. mem_trans y))\"\n\nlemma OrdI: \"mem_trans X \\<Longrightarrow> (\\<And>x. x \\<in> X \\<Longrightarrow> mem_trans x) \\<Longrightarrow> X : Ord\"\n  by unfold_types auto\n\ntext \\<open>Basic properties of ordinals:\\<close>\n\nlemma Ord_if_mem_Ord [elim]: \"x : Ord \\<Longrightarrow> y \\<in> x \\<Longrightarrow> y : Ord\"\n  by unfold_types (unfold mem_trans_def, auto)\n\nlemma mem_trans_if_Ord: \"x : Ord \\<Longrightarrow> mem_trans x\"\n  by unfold_types\n\nlemma subset_if_mem_Ord [elim]: \"x : Ord \\<Longrightarrow> y \\<in> x \\<Longrightarrow> y \\<subseteq> x\"\n  by unfold_types (fastforce simp: mem_trans_def)\n\nlemma Subset_if_Element_Ord [derive]:\n  \"x : Ord \\<Longrightarrow> y : Element x \\<Longrightarrow> y : Subset x\"\n  (*TODO: should be discharged by the type checker*)\n  by (intro SubsetI, drule ElementD) (fact subset_if_mem_Ord)\n\n(*Adapted from a proof by Chad Brown*)\nlemma Ord_eq_if_not_mem_if_not_mem:\n  \"X : Ord \\<Longrightarrow> Y : Ord \\<Longrightarrow> X \\<notin> Y \\<Longrightarrow> Y \\<notin> X \\<Longrightarrow> X = Y\"\nproof (induction X Y rule: mem_double_induct)\n  fix X Y\n  assume\n    ord: \"X : Ord\" \"Y: Ord\" and\n    IH1: \"\\<And>x. x \\<in> X \\<Longrightarrow> x : Ord \\<Longrightarrow> Y : Ord \\<Longrightarrow> x \\<notin> Y \\<Longrightarrow> Y \\<notin> x \\<Longrightarrow> x = Y\" and\n    IH2: \"\\<And>y. y \\<in> Y \\<Longrightarrow> X : Ord \\<Longrightarrow> y : Ord \\<Longrightarrow> X \\<notin> y \\<Longrightarrow> y \\<notin> X \\<Longrightarrow> X = y\" and\n    not_mem: \"X \\<notin> Y\" \"Y \\<notin> X\"\n  show \"X = Y\"\n  proof (rule eqI)\n    fix x assume \"x \\<in> X\"\n    with \\<open>X : Ord\\<close> have \"x \\<subseteq> X\" \"x : Ord\" by auto\n    with not_mem ord IH1 \\<open>x \\<in> X\\<close> show \"x \\<in> Y\" by blast\n  next\n    fix y assume \"y \\<in> Y\"\n    with \\<open>Y : Ord\\<close>  have \"y \\<subseteq> Y\" \"y: Ord\" by auto\n    with not_mem ord IH2 \\<open>y \\<in> Y\\<close> show \"y \\<in> X\" by blast\n  qed\nqed\n\nlemma Ord_trichotomy:\n  assumes \"X : Ord\" \"Y : Ord\"\n  obtains (lt) \"X \\<in> Y\" | (eq) \"X = Y\" | (gt) \"Y \\<in> X\"\n  using assms Ord_eq_if_not_mem_if_not_mem by auto\n\nlemma emptyset_Ord [type]: \"{} : Ord\"\n  by unfold_types auto\n\n\nsubsection \\<open>Successor ordinals\\<close>\n\ndefinition succ where \"succ x \\<equiv> x \\<union> {x}\"\n\nlemma succ_type [type]: \"succ : Ord \\<Rightarrow> Ord\"\n  unfolding succ_def by unfold_types (unfold mem_trans_def, auto 5 0)\n\nlemma mem_succE [elim]:\n  assumes \"x \\<in> succ y\"\n  obtains \"x \\<in> y\" | \"x = y\"\n  using assms unfolding succ_def by auto\n\ntext \\<open>Simp rules\\<close>\n\nlemma succ_empty_eq [iff]: \"succ {} = {{}}\"\n  unfolding succ_def by simp\n\nlemma succ_succ_empty_eq [iff]: \"succ (succ {}) = {{}, {{}}}\"\n  unfolding succ_def by auto\n\nlemma succ_ne_self [iff]: \"succ x \\<noteq> x\"\n  unfolding succ_def by auto\n\nlemma succ_ne_empty [iff]: \"succ x \\<noteq> {}\"\n  unfolding succ_def by auto\n\nlemma mem_succ_self [iff]: \"x \\<in> succ x\"\n  unfolding succ_def by auto\n\ntext \\<open>Injectivity\\<close>\n\nlemma succ_inj [dest]: \"succ x = succ y \\<Longrightarrow> x = y\"\nproof (rule ccontr)\n  assume succ_eq: \"succ x = succ y\" and neq: \"x \\<noteq> y\"\n  have \"x \\<in> succ x\" and \"y \\<in> succ y\" by auto\n  then have \"x \\<in> succ y\" and \"y \\<in> succ x\" by (auto simp only: succ_eq)\n  with neq have \"x \\<in> y\" and \"y \\<in> x\" by auto\n  then show False using not_mem_if_mem by blast\nqed\n\nlemma succ_ne_if_ne [intro!]: \"x \\<noteq> y \\<Longrightarrow> succ x \\<noteq> succ y\"\n  by auto\n\nlemma mem_succ_if_mem [intro]: \"x \\<in> y \\<Longrightarrow> x \\<in> succ y\"\n  unfolding succ_def by auto\n\nlemma univ_closed_succ [intro!]: \"x \\<in> univ X \\<Longrightarrow> succ x \\<in> univ X\"\n  unfolding succ_def by auto\n\n\nsubsection \\<open>The Smallest Infinite Ordinal \\<omega>\\<close>\n\ndefinition \"omega_op X = {{}} \\<union> {succ x | x \\<in> X}\"\n\nlemma omega_op_Monop [type]: \"omega_op : Monop V\"\n  unfolding omega_op_def by (rule MonopI) auto\n\ndefinition \"omega \\<equiv> lfp V omega_op\"\n\nbundle isa_set_omega_syntax begin notation omega (\"\\<omega>\") end\nbundle no_isa_set_omega_syntax begin no_notation omega (\"\\<omega>\") end\nunbundle isa_set_omega_syntax\n\nlemma fixpoint_omega [iff]: \"fixpoint \\<omega> omega_op\"\n  unfolding omega_def by auto\n\nlemma empty_mem_omega [iff]: \"{} \\<in> \\<omega>\"\n  by (subst fixpoint_omega[unfolded fixpoint_def omega_op_def, symmetric])\n    simp\n\nlemma succ_mem_omega_if_mem [intro!]: \"n \\<in> \\<omega> \\<Longrightarrow> succ n \\<in> \\<omega>\"\n  by (subst fixpoint_omega[unfolded fixpoint_def omega_op_def, symmetric])\n    auto\n\nlemma omega_induct [case_names empty succ, induct set: omega]:\n  assumes \"n \\<in> \\<omega>\"\n  and \"P {}\"\n  and \"\\<And>n. \\<lbrakk>n \\<in> \\<omega>; P n\\<rbrakk> \\<Longrightarrow> P (succ n)\"\n  shows \"P n\"\n  using \\<open>n \\<in> \\<omega>\\<close>[unfolded omega_def]\n  by (rule lfp_induct[OF omega_op_Monop])\n    (auto intro: assms(2-3) simp only: omega_op_def omega_def)\n\nlemma mem_omegaE:\n  assumes \"n \\<in> \\<omega>\"\n  obtains (empty) \"n = {}\" | (succ) m where \"m \\<in> \\<omega>\" \"n = succ m\"\n  using assms omega_induct[where ?P=\"\\<lambda>m. n = m \\<longrightarrow> _\"] by blast\n\nlemma eq_empty_or_empty_mem_if_mem_omegaE:\n  assumes \"n \\<in> \\<omega>\"\n  obtains (eq_empty) \"n = {}\" | (empty_mem) \"{} \\<in> n\"\n  using assms by (induction n rule: omega_induct) auto\n\nlemma empty_mem_succ_if_mem_omega: \"n \\<in> \\<omega> \\<Longrightarrow> {} \\<in> succ n\"\n  by (rule eq_empty_or_empty_mem_if_mem_omegaE) auto\n\nlemma mem_trans_omega [iff]: \"mem_trans \\<omega>\"\n  by (rule mem_transI, rule omega_induct) auto\n\nlemma mem_trans_if_mem_omega: \"n \\<in> \\<omega> \\<Longrightarrow> mem_trans n\"\n  by (induction n rule: omega_induct) (auto simp: mem_trans_def)\n\nlemma omega_Ord [type]: \"\\<omega> : Ord\"\n  by (rule OrdI) (auto elim: mem_trans_if_mem_omega)\n\nlemma Ord_if_mem_omega: \"n \\<in> \\<omega> \\<Longrightarrow> n : Ord\"\n  by (fact Ord_if_mem_Ord[OF omega_Ord])\n\nlemma mem_trans_if_mem_omega' [trans]: \"\\<lbrakk>n \\<in> \\<omega>; k \\<in> m; m \\<in> n\\<rbrakk> \\<Longrightarrow> k \\<in> n\"\n  using mem_trans_if_mem_omega[unfolded mem_trans_def] by auto\n\nlemma mem_if_succ_mem_if_mem_omega: \"n \\<in> \\<omega> \\<Longrightarrow> succ m \\<in> n \\<Longrightarrow> m \\<in> n\"\n  using mem_trans_if_mem_omega'[of n m \"succ m\"] by auto\n\nlemma subset_omega_if_mem_omega: \"n \\<in> \\<omega> \\<Longrightarrow> n \\<subseteq> \\<omega>\"\n  using mem_trans_omega[unfolded mem_trans_def] by blast\n\nlemma mem_omega_if_mem_if_mem_omega: \"x \\<in> \\<omega> \\<Longrightarrow> y \\<in> x \\<Longrightarrow> y \\<in> \\<omega>\"\n  using subset_omega_if_mem_omega by auto\n\nlemma succ_mem_succ_if_mem_if_mem_omega:\n  \"\\<lbrakk>n \\<in> \\<omega>; m \\<in> n\\<rbrakk> \\<Longrightarrow> succ m \\<in> succ n\"\n  by (induction n rule: omega_induct) auto\n\nlemma mem_if_succ_mem_succ_if_mem_omega:\n  assumes \"n \\<in> \\<omega>\" and succ_m_mem: \"succ m \\<in> succ n\"\n  shows \"m \\<in> n\"\nproof -\n  have \"mem_trans (succ n)\" by (rule mem_trans_if_mem_omega) auto\n  from mem_transD[OF this] have \"succ m \\<subseteq> succ n\" by auto\n  then have \"m \\<in> (n \\<union> {n})\" by auto\n  with succ_m_mem show \"m \\<in> n\" by auto\nqed\n\nlemma succ_mem_succ_iff_mem_if_mem_omega [iff]:\n  \"n \\<in> \\<omega> \\<Longrightarrow> succ m \\<in> succ n \\<longleftrightarrow> m \\<in> n\"\n  using succ_mem_succ_if_mem_if_mem_omega mem_if_succ_mem_succ_if_mem_omega\n  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/Ordinals.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8840392725805823, "lm_q2_score": 0.7956581073313275, "lm_q1q2_score": 0.7033930144280296}}
{"text": "section \\<open> Robot localisation \\<close>\n\ntheory utp_prob_rel_lattice_robot_localisation\n  imports \n    \"UTP_prob_relations.utp_prob_rel\"\nbegin \n\nunbundle UTP_Syntax\n\ndeclare [[show_types]]\n\nnamed_theorems robot_local_defs\n\nsubsection \\<open> Definitions \\<close>\nalphabet robot_local_state = \n  bel :: nat\n\ndefinition \"door p = ((p = (0::\\<nat>)) \\<or> (p = 2))\"\n\ndefinition init :: \"robot_local_state rvhfun\" where\n\"init = bel \\<^bold>\\<U> {(0::\\<nat>), 1, 2}\"\n\ntext \\<open> A noisy sensor is more likely to get a right reading than a wrong reading: 4 vs. 1.\\<close>\ndefinition scale_door :: \"robot_local_state rvhfun\"  where\n\"scale_door = (3 * \\<lbrakk>\\<guillemotleft>door\\<guillemotright> (bel\\<^sup>>)\\<rbrakk>\\<^sub>\\<I>\\<^sub>e + 1)\\<^sub>e\"\n\ndefinition scale_wall :: \"robot_local_state rvhfun\"  where\n\"scale_wall = (3 * \\<lbrakk>\\<not>\\<guillemotleft>door\\<guillemotright> (bel\\<^sup>>)\\<rbrakk>\\<^sub>\\<I>\\<^sub>e + 1)\\<^sub>e\"\n\ndefinition move_right :: \"robot_local_state prhfun\"  where\n\"move_right = (bel := (bel + 1) mod 3)\"\n\ndefinition robot_localisation where \n\"robot_localisation = ((((init \\<parallel> scale_door) ; move_right) \\<parallel> scale_door) ; move_right) \\<parallel> scale_wall\"\n\ndefinition believe_1::\"robot_local_state rvhfun\" where \n\"believe_1 \\<equiv> (4/9 * \\<lbrakk>bel\\<^sup>> = 0\\<rbrakk>\\<^sub>\\<I>\\<^sub>e + 1/9 * \\<lbrakk>bel\\<^sup>> = 1\\<rbrakk>\\<^sub>\\<I>\\<^sub>e + 4/9 * \\<lbrakk>bel\\<^sup>> = 2\\<rbrakk>\\<^sub>\\<I>\\<^sub>e)\\<^sub>e\"\n\ndefinition move_right_1::\"robot_local_state rvhfun\" where \n\"move_right_1 \\<equiv> (4/9 * \\<lbrakk>bel\\<^sup>> = 0\\<rbrakk>\\<^sub>\\<I>\\<^sub>e + 4/9 * \\<lbrakk>bel\\<^sup>> = 1\\<rbrakk>\\<^sub>\\<I>\\<^sub>e + 1/9 * \\<lbrakk>bel\\<^sup>> = 2\\<rbrakk>\\<^sub>\\<I>\\<^sub>e)\\<^sub>e\"\n\ndefinition believe_2::\"robot_local_state rvhfun\" where \n\"believe_2 \\<equiv> (2/3 * \\<lbrakk>bel\\<^sup>> = 0\\<rbrakk>\\<^sub>\\<I>\\<^sub>e + 1/6 * \\<lbrakk>bel\\<^sup>> = 1\\<rbrakk>\\<^sub>\\<I>\\<^sub>e + 1/6 * \\<lbrakk>bel\\<^sup>> = 2\\<rbrakk>\\<^sub>\\<I>\\<^sub>e)\\<^sub>e\"\n\ndefinition move_right_2::\"robot_local_state rvhfun\" where \n\"move_right_2 \\<equiv> (1/6 * \\<lbrakk>bel\\<^sup>> = 0\\<rbrakk>\\<^sub>\\<I>\\<^sub>e + 2/3 * \\<lbrakk>bel\\<^sup>> = 1\\<rbrakk>\\<^sub>\\<I>\\<^sub>e + 1/6 * \\<lbrakk>bel\\<^sup>> = 2\\<rbrakk>\\<^sub>\\<I>\\<^sub>e)\\<^sub>e\"\n\ndefinition believe_3::\"robot_local_state rvhfun\" where \n\"believe_3 \\<equiv> (1/18 * \\<lbrakk>bel\\<^sup>> = 0\\<rbrakk>\\<^sub>\\<I>\\<^sub>e + 8/9 * \\<lbrakk>bel\\<^sup>> = 1\\<rbrakk>\\<^sub>\\<I>\\<^sub>e + 1/18 * \\<lbrakk>bel\\<^sup>> = 2\\<rbrakk>\\<^sub>\\<I>\\<^sub>e)\\<^sub>e\"\n\nsubsection \\<open> First sensor reading \\<close>\nlemma init_knowledge_sum: \"(\\<Sum>\\<^sub>\\<infinity>v\\<^sub>0::robot_local_state.\n       (if v\\<^sub>0 = \\<lparr>bel\\<^sub>v = 0::\\<nat>\\<rparr> \\<or> v\\<^sub>0 = \\<lparr>bel\\<^sub>v = Suc (0::\\<nat>)\\<rparr> \\<or> v\\<^sub>0 = \\<lparr>bel\\<^sub>v = 2::\\<nat>\\<rparr> then 1::\\<real> else (0::\\<real>)) *\n       ((3::\\<real>) * (if bel\\<^sub>v v\\<^sub>0 = (0::\\<nat>) \\<or> bel\\<^sub>v v\\<^sub>0 = (2::\\<nat>) then 1::\\<real> else (0::\\<real>)) + (1::\\<real>)) /\n       (3::\\<real>)) = 3\"\nproof -\n  let ?bel_set = \"{\\<lparr>bel\\<^sub>v = 0::\\<nat>\\<rparr>, \\<lparr>bel\\<^sub>v = Suc (0::\\<nat>)\\<rparr>, \\<lparr>bel\\<^sub>v = 2::\\<nat>\\<rparr>}\"\n  let ?sum = \"(\\<Sum>\\<^sub>\\<infinity>v\\<^sub>0::robot_local_state.\n       (if v\\<^sub>0 = \\<lparr>bel\\<^sub>v = 0::\\<nat>\\<rparr> \\<or> v\\<^sub>0 = \\<lparr>bel\\<^sub>v = Suc (0::\\<nat>)\\<rparr> \\<or> v\\<^sub>0 = \\<lparr>bel\\<^sub>v = 2::\\<nat>\\<rparr> then 1::\\<real> else (0::\\<real>)) *\n       ((3::\\<real>) * (if bel\\<^sub>v v\\<^sub>0 = (0::\\<nat>) \\<or> bel\\<^sub>v v\\<^sub>0 = (2::\\<nat>) then 1::\\<real> else (0::\\<real>)) + (1::\\<real>)) /\n       (3::\\<real>))\"\n  let ?fun = \"\\<lambda>v\\<^sub>0. (if v\\<^sub>0 = \\<lparr>bel\\<^sub>v = 0::\\<nat>\\<rparr> \\<or> v\\<^sub>0 = \\<lparr>bel\\<^sub>v = 2\\<rparr> then 4::\\<real> else \n        (if \\<lparr>bel\\<^sub>v = Suc (0::\\<nat>)\\<rparr> = v\\<^sub>0 then 1::\\<real> else (0::\\<real>))) / 3\"\n  have \"?sum = (\\<Sum>\\<^sub>\\<infinity>v\\<^sub>0::robot_local_state. ?fun v\\<^sub>0)\"\n    apply (subst infsum_cong[where g=\"\\<lambda>v\\<^sub>0. (if v\\<^sub>0 = \\<lparr>bel\\<^sub>v = 0::\\<nat>\\<rparr> \\<or> v\\<^sub>0 = \\<lparr>bel\\<^sub>v = 2\\<rparr> then 4::\\<real> else \n        (if v\\<^sub>0 = \\<lparr>bel\\<^sub>v = Suc (0::\\<nat>)\\<rparr> then 1::\\<real> else (0::\\<real>))) / 3\"])\n    apply simp\n    by (simp add: infsum_cong)\n  also have \"... = (\\<Sum>\\<^sub>\\<infinity>v\\<^sub>0::robot_local_state \\<in> ?bel_set \\<union> (UNIV - ?bel_set). ?fun v\\<^sub>0)\"\n    by auto\n  also have \"... = (\\<Sum>\\<^sub>\\<infinity>v\\<^sub>0::robot_local_state \\<in> ?bel_set. ?fun v\\<^sub>0)\"\n    apply (rule infsum_cong_neutral)\n    apply fastforce\n     apply fastforce\n    by blast\n  also have \"... = (\\<Sum>v\\<^sub>0::robot_local_state \\<in> {\\<lparr>bel\\<^sub>v = 0::\\<nat>\\<rparr>}. ?fun v\\<^sub>0) + \n      (\\<Sum>v\\<^sub>0::robot_local_state \\<in> {\\<lparr>bel\\<^sub>v = Suc (0::\\<nat>)\\<rparr>, \\<lparr>bel\\<^sub>v = (2::\\<nat>)\\<rparr>}. ?fun v\\<^sub>0)\"\n    apply (subst infsum_finite)\n    apply (simp)\n    by force\n  also have \"... = (\\<Sum>v\\<^sub>0::robot_local_state \\<in> {\\<lparr>bel\\<^sub>v = 0::\\<nat>\\<rparr>}. ?fun v\\<^sub>0) + \n      (\\<Sum>v\\<^sub>0::robot_local_state \\<in> {\\<lparr>bel\\<^sub>v = Suc (0::\\<nat>)\\<rparr>}. ?fun v\\<^sub>0) +\n      (\\<Sum>v\\<^sub>0::robot_local_state \\<in> {\\<lparr>bel\\<^sub>v = (2::\\<nat>)\\<rparr>}. ?fun v\\<^sub>0)\"\n    by force\n  also have \"... = 3\"\n    by simp\n  then show ?thesis\n    using calculation by presburger\nqed\n\nlemma believe_1_simp: \"(init \\<parallel> scale_door) = prfun_of_rvfun believe_1\"\n  apply (simp add: pparallel_def init_def scale_door_def believe_1_def)\n  apply (simp add: dist_norm_final_def)\n  apply (simp add: rvfun_uniform_dist_altdef)\n  apply (rule HOL.arg_cong[where f=\"prfun_of_rvfun\"])\n  apply (simp add: door_def)\n  apply (simp add: expr_defs assigns_r_def)\n  apply (pred_auto)\n  using init_knowledge_sum apply auto[1]\n  using init_knowledge_sum apply linarith\n  apply (simp add: init_knowledge_sum)\n  using init_knowledge_sum by auto[1]\n\n(* Use algebraic laws *)\nlemma believe_1_simp': \"(init \\<parallel> scale_door) = prfun_of_rvfun believe_1\"\n  apply (simp add: init_def believe_1_def)\n  apply (subst prfun_parallel_uniform_dist)\n  apply (simp)+\n  apply (simp add: scale_door_def)\n  apply (rule HOL.arg_cong[where f=\"prfun_of_rvfun\"])\n  apply (simp add: door_def)\n  apply (simp add: expr_defs)\n  by (pred_auto)\n\nsubsection \\<open> First move \\<close>\nlemma move_right_1_simp: \"(init \\<parallel> scale_door) ; move_right = prfun_of_rvfun move_right_1\"\n  apply (simp add: pseqcomp_def move_right_1_def)\n  (* apply (simp add: pparallel_def dist_norm_final_def) *)\n  apply (simp add: init_def)\n  apply (subst prfun_parallel_uniform_dist')\n  apply (simp)+\n  apply (simp add: scale_door_def door_def)\n  apply (expr_auto)\n  apply (simp add: scale_door_def door_def)\n   apply (expr_auto)\n  apply (simp add: pfun_defs dist_norm_final_def move_right_def scale_door_def door_def )\n  apply (subst rvfun_assignment_inverse)\n  apply (rule HOL.arg_cong[where f=\"prfun_of_rvfun\"])\n  apply (expr_auto add: rel assigns_r_def)\nproof -\n  let ?lhs_f = \"\\<lambda>v\\<^sub>0::robot_local_state. ((if v\\<^sub>0 = \\<lparr>bel\\<^sub>v = 0::\\<nat>\\<rparr> then 1::\\<real> else (0::\\<real>)) * (4::\\<real>) +\n        ((if v\\<^sub>0 = \\<lparr>bel\\<^sub>v = Suc (0::\\<nat>)\\<rparr> then 1::\\<real> else (0::\\<real>)) +\n         (if v\\<^sub>0 = \\<lparr>bel\\<^sub>v = 2::\\<nat>\\<rparr> then 1::\\<real> else (0::\\<real>)) * (4::\\<real>))) *\n       (if \\<lparr>bel\\<^sub>v = 0::\\<nat>\\<rparr> = v\\<^sub>0\\<lparr>bel\\<^sub>v := Suc (bel\\<^sub>v v\\<^sub>0) mod (3::\\<nat>)\\<rparr> then 1::\\<real> else (0::\\<real>)) / 9\"\n  let ?lhs = \"(\\<Sum>\\<^sub>\\<infinity>v\\<^sub>0::robot_local_state. ?lhs_f v\\<^sub>0)\"\n\n  have f1: \"\\<forall>v\\<^sub>0. \\<not>(v\\<^sub>0 = \\<lparr>bel\\<^sub>v = 0::\\<nat>\\<rparr> \\<and> \\<lparr>bel\\<^sub>v = 0::\\<nat>\\<rparr> = v\\<^sub>0\\<lparr>bel\\<^sub>v := Suc (bel\\<^sub>v v\\<^sub>0) mod (3::\\<nat>)\\<rparr>)\"\n    by (auto)\n  have f2: \"\\<forall>v\\<^sub>0. \\<not>(v\\<^sub>0 = \\<lparr>bel\\<^sub>v = Suc (0::\\<nat>)\\<rparr> \\<and> \\<lparr>bel\\<^sub>v = 0::\\<nat>\\<rparr> = v\\<^sub>0\\<lparr>bel\\<^sub>v := Suc (bel\\<^sub>v v\\<^sub>0) mod (3::\\<nat>)\\<rparr>)\"\n    by (auto)\n  have f3: \"\\<forall>v\\<^sub>0. (v\\<^sub>0 = \\<lparr>bel\\<^sub>v = 2::\\<nat>\\<rparr> \\<and> \\<lparr>bel\\<^sub>v = 0::\\<nat>\\<rparr> = v\\<^sub>0\\<lparr>bel\\<^sub>v := Suc (bel\\<^sub>v v\\<^sub>0) mod (3::\\<nat>)\\<rparr>) = \n          (v\\<^sub>0 = \\<lparr>bel\\<^sub>v = 2::\\<nat>\\<rparr>)\"\n    by (auto)\n  have \"?lhs = (4 / 9)\"\n    apply (subst ring_distribs(2))+\n    apply (simp add: mult.commute[where b = \"(4::\\<real>)\"])+\n    apply (simp add: mult.assoc)+\n    apply (subst conditional_conds_conj)+\n    apply (simp add: f1 f2 f3)\n    apply (subst infsum_cdiv_left)\n    apply (rule summable_on_cmult_right)\n    apply (smt (verit, best) infsum_singleton_summable summable_on_cong zero_neq_one)\n    apply (subst infsum_cmult_right)\n    apply (smt (verit, best) infsum_singleton_summable summable_on_cong zero_neq_one)\n    apply (subst infsum_constant_finite_states)\n    by (simp)+\n    \n  then show \"?lhs * (9::\\<real>) =  (4::\\<real>)\"\n    by linarith\nnext\n  let ?lhs_f = \"\\<lambda>v\\<^sub>0::robot_local_state. ((if v\\<^sub>0 = \\<lparr>bel\\<^sub>v = 0::\\<nat>\\<rparr> then 1::\\<real> else (0::\\<real>)) * (4::\\<real>) +\n        ((if v\\<^sub>0 = \\<lparr>bel\\<^sub>v = Suc (0::\\<nat>)\\<rparr> then 1::\\<real> else (0::\\<real>)) +\n         (if v\\<^sub>0 = \\<lparr>bel\\<^sub>v = 2::\\<nat>\\<rparr> then 1::\\<real> else (0::\\<real>)) * (4::\\<real>))) *\n       (if \\<lparr>bel\\<^sub>v = Suc (0::\\<nat>)\\<rparr> = v\\<^sub>0\\<lparr>bel\\<^sub>v := Suc (bel\\<^sub>v v\\<^sub>0) mod (3::\\<nat>)\\<rparr> then 1::\\<real> else (0::\\<real>)) / 9\"\n  let ?lhs = \"(\\<Sum>\\<^sub>\\<infinity>v\\<^sub>0::robot_local_state. ?lhs_f v\\<^sub>0)\"\n\n  have f1: \"\\<forall>v\\<^sub>0. (v\\<^sub>0 = \\<lparr>bel\\<^sub>v = 0::\\<nat>\\<rparr> \\<and> \\<lparr>bel\\<^sub>v = Suc (0::\\<nat>)\\<rparr> = v\\<^sub>0\\<lparr>bel\\<^sub>v := Suc (bel\\<^sub>v v\\<^sub>0) mod (3::\\<nat>)\\<rparr>) = \n      (v\\<^sub>0 = \\<lparr>bel\\<^sub>v = 0::\\<nat>\\<rparr>)\"\n    by (auto)\n  have f2: \"\\<forall>v\\<^sub>0. \\<not>(v\\<^sub>0 = \\<lparr>bel\\<^sub>v = Suc (0::\\<nat>)\\<rparr> \\<and> \\<lparr>bel\\<^sub>v = Suc (0::\\<nat>)\\<rparr> = v\\<^sub>0\\<lparr>bel\\<^sub>v := Suc (bel\\<^sub>v v\\<^sub>0) mod (3::\\<nat>)\\<rparr>)\"\n    by (auto)\n  have f3: \"\\<forall>v\\<^sub>0. \\<not>(v\\<^sub>0 = \\<lparr>bel\\<^sub>v = 2::\\<nat>\\<rparr> \\<and> \\<lparr>bel\\<^sub>v = Suc (0::\\<nat>)\\<rparr> = v\\<^sub>0\\<lparr>bel\\<^sub>v := Suc (bel\\<^sub>v v\\<^sub>0) mod (3::\\<nat>)\\<rparr>)\"\n    by (auto)\n  have \"?lhs = (4 / 9)\"\n    apply (subst ring_distribs(2))+\n    apply (simp add: mult.commute[where b = \"(4::\\<real>)\"])+\n    apply (simp add: mult.assoc)+\n    apply (subst conditional_conds_conj)+\n    apply (simp add: f1 f2 f3)\n    apply (subst infsum_cdiv_left)\n    apply (rule summable_on_cmult_right)\n    apply (smt (verit, best) infsum_singleton_summable summable_on_cong zero_neq_one)\n    apply (subst infsum_cmult_right)\n    apply (smt (verit, best) infsum_singleton_summable summable_on_cong zero_neq_one)\n    apply (subst infsum_constant_finite_states)\n    by (simp)+\n    \n  then show \"?lhs * (9::\\<real>) =  (4::\\<real>)\"\n    by linarith\nnext\n  let ?lhs_f = \"\\<lambda>v\\<^sub>0::robot_local_state. ((if v\\<^sub>0 = \\<lparr>bel\\<^sub>v = 0::\\<nat>\\<rparr> then 1::\\<real> else (0::\\<real>)) * (4::\\<real>) +\n        ((if v\\<^sub>0 = \\<lparr>bel\\<^sub>v = Suc (0::\\<nat>)\\<rparr> then 1::\\<real> else (0::\\<real>)) +\n         (if v\\<^sub>0 = \\<lparr>bel\\<^sub>v = 2::\\<nat>\\<rparr> then 1::\\<real> else (0::\\<real>)) * (4::\\<real>))) *\n       (if \\<lparr>bel\\<^sub>v = (2::\\<nat>)\\<rparr> = v\\<^sub>0\\<lparr>bel\\<^sub>v := Suc (bel\\<^sub>v v\\<^sub>0) mod (3::\\<nat>)\\<rparr>  then 1::\\<real> else (0::\\<real>)) / 9\"\n  let ?lhs = \"(\\<Sum>\\<^sub>\\<infinity>v\\<^sub>0::robot_local_state. ?lhs_f v\\<^sub>0)\"\n\n  have f1: \"\\<forall>v\\<^sub>0. \\<not>(v\\<^sub>0 = \\<lparr>bel\\<^sub>v = 0::\\<nat>\\<rparr> \\<and> \\<lparr>bel\\<^sub>v = (2::\\<nat>)\\<rparr> = v\\<^sub>0\\<lparr>bel\\<^sub>v := Suc (bel\\<^sub>v v\\<^sub>0) mod (3::\\<nat>)\\<rparr>)\"\n    by (auto)\n  have f2: \"\\<forall>v\\<^sub>0. (v\\<^sub>0 = \\<lparr>bel\\<^sub>v = Suc (0::\\<nat>)\\<rparr> \\<and> \\<lparr>bel\\<^sub>v = (2::\\<nat>)\\<rparr> = v\\<^sub>0\\<lparr>bel\\<^sub>v := Suc (bel\\<^sub>v v\\<^sub>0) mod (3::\\<nat>)\\<rparr>) \n     = (v\\<^sub>0 = \\<lparr>bel\\<^sub>v = Suc (0::\\<nat>)\\<rparr>)\"\n    by (auto)\n  have f3: \"\\<forall>v\\<^sub>0. \\<not>(v\\<^sub>0 = \\<lparr>bel\\<^sub>v = 2::\\<nat>\\<rparr> \\<and> \\<lparr>bel\\<^sub>v = (2::\\<nat>)\\<rparr> = v\\<^sub>0\\<lparr>bel\\<^sub>v := Suc (bel\\<^sub>v v\\<^sub>0) mod (3::\\<nat>)\\<rparr>)\"\n    by (auto)\n  have \"?lhs = (1 / 9)\"\n    apply (subst ring_distribs(2))+\n    apply (simp add: mult.commute[where b = \"(4::\\<real>)\"])+\n    apply (simp add: mult.assoc)+\n    apply (subst conditional_conds_conj)+\n    apply (simp add: f1 f2 f3)\n    apply (subst infsum_cdiv_left)\n    apply (smt (verit, best) infsum_singleton_summable summable_on_cong zero_neq_one)\n    apply (subst infsum_constant_finite_states)\n    by (simp)+\n    \n  then show \"?lhs * (9::\\<real>) =  (1::\\<real>)\"\n    by linarith\nnext\n  fix bel\n  assume a1: \"(0::\\<nat>) < bel\"\n  assume a2: \"\\<not> bel = Suc (0::\\<nat>)\"\n  assume a3: \"\\<not> bel = (2::\\<nat>)\"\n  let ?lhs_f = \"\\<lambda>v\\<^sub>0::robot_local_state. ((if v\\<^sub>0 = \\<lparr>bel\\<^sub>v = 0::\\<nat>\\<rparr> then 1::\\<real> else (0::\\<real>)) * (4::\\<real>) +\n        ((if v\\<^sub>0 = \\<lparr>bel\\<^sub>v = Suc (0::\\<nat>)\\<rparr> then 1::\\<real> else (0::\\<real>)) +\n         (if v\\<^sub>0 = \\<lparr>bel\\<^sub>v = 2::\\<nat>\\<rparr> then 1::\\<real> else (0::\\<real>)) * (4::\\<real>))) *\n       (if \\<lparr>bel\\<^sub>v = bel\\<rparr> = v\\<^sub>0\\<lparr>bel\\<^sub>v := Suc (bel\\<^sub>v v\\<^sub>0) mod (3::\\<nat>)\\<rparr> then 1::\\<real> else (0::\\<real>)) / 9\"\n  let ?lhs = \"(\\<Sum>\\<^sub>\\<infinity>v\\<^sub>0::robot_local_state. ?lhs_f v\\<^sub>0)\"\n\n  have f1: \"\\<forall>v\\<^sub>0. \\<not>(v\\<^sub>0 = \\<lparr>bel\\<^sub>v = 0::\\<nat>\\<rparr> \\<and> \\<lparr>bel\\<^sub>v = bel\\<rparr> = v\\<^sub>0\\<lparr>bel\\<^sub>v := Suc (bel\\<^sub>v v\\<^sub>0) mod (3::\\<nat>)\\<rparr>)\"\n    using a2 by force\n  have f2: \"\\<forall>v\\<^sub>0. \\<not>(v\\<^sub>0 = \\<lparr>bel\\<^sub>v = Suc (0::\\<nat>)\\<rparr> \\<and> \\<lparr>bel\\<^sub>v = bel\\<rparr> = v\\<^sub>0\\<lparr>bel\\<^sub>v := Suc (bel\\<^sub>v v\\<^sub>0) mod (3::\\<nat>)\\<rparr>)\"\n    using a3 by force\n  have f3: \"\\<forall>v\\<^sub>0. \\<not>(v\\<^sub>0 = \\<lparr>bel\\<^sub>v = 2::\\<nat>\\<rparr> \\<and> \\<lparr>bel\\<^sub>v = bel\\<rparr> = v\\<^sub>0\\<lparr>bel\\<^sub>v := Suc (bel\\<^sub>v v\\<^sub>0) mod (3::\\<nat>)\\<rparr>)\"\n    using a1 by force\n  have \"?lhs = 0\"\n    apply (subst ring_distribs(2))+\n    apply (simp add: mult.commute[where b = \"(4::\\<real>)\"])+\n    apply (simp add: mult.assoc)+\n    apply (subst conditional_conds_conj)+\n    by (simp add: f1 f2 f3)\n    \n  then show \"?lhs =  0\"\n    by linarith\nqed\n\nlemma move_right_1_dist: \"rvfun_of_prfun (prfun_of_rvfun move_right_1) = move_right_1\"\nproof -\n  have summable_1: \"(\\<lambda>s::robot_local_state. (4::\\<real>) * (if bel\\<^sub>v s = (0::\\<nat>) then 1::\\<real> else (0::\\<real>)) / (9::\\<real>)) \n        summable_on UNIV\"\n    apply (rule summable_on_cdiv_left)\n    apply (rule summable_on_cmult_right)\n    apply (rule infsum_constant_finite_states_summable)\n    by (smt (z3) Collect_mono card_0_eq finite.insertI infinite_arbitrarily_large rev_finite_subset \n      robot_local_state.surjective singleton_conv unit.exhaust)\n\n  have summable_2: \"(\\<lambda>s::robot_local_state. (4::\\<real>) * (if bel\\<^sub>v s = Suc (0::\\<nat>) then 1::\\<real> else (0::\\<real>)) / (9::\\<real>)) \n      summable_on UNIV\"\n    apply (rule summable_on_cdiv_left)\n    apply (rule summable_on_cmult_right)\n    apply (rule infsum_constant_finite_states_summable)\n    by (smt (z3) Collect_mono finite.emptyI finite.insertI rev_finite_subset \n      robot_local_state.equality singleton_conv unit.exhaust)\n\n  have summable_3: \"(\\<lambda>s::robot_local_state. (if bel\\<^sub>v s = (2::\\<nat>) then 1::\\<real> else (0::\\<real>)) / (9::\\<real>)) \n      summable_on UNIV\"\n    apply (rule summable_on_cdiv_left)\n    apply (rule infsum_constant_finite_states_summable)\n    by (smt (z3) Collect_mono finite.emptyI finite.insertI rev_finite_subset \n      robot_local_state.equality singleton_conv unit.exhaust)\n\n  have sum_1: \"(\\<Sum>\\<^sub>\\<infinity>s::robot_local_state. (4::\\<real>) * (if bel\\<^sub>v s = (0::\\<nat>) then 1::\\<real> else (0::\\<real>)) / (9::\\<real>)) = 4/9\"\n    apply (subst infsum_cdiv_left)\n    apply (rule summable_on_cmult_right)\n    apply (rule infsum_constant_finite_states_summable)\n    apply (smt (z3) Collect_mono finite.emptyI finite.insertI rev_finite_subset \n      robot_local_state.equality singleton_conv unit.exhaust)\n    apply (subst infsum_cmult_right)\n    apply (rule infsum_constant_finite_states_summable)\n    apply (smt (z3) Collect_mono finite.emptyI finite.insertI rev_finite_subset \n      robot_local_state.equality singleton_conv unit.exhaust)\n    apply (subst infsum_constant_finite_states)\n    apply (smt (z3) Collect_mono finite.emptyI finite.insertI rev_finite_subset \n      robot_local_state.equality singleton_conv unit.exhaust)\n    apply (simp)\n    apply (subst card_1_singleton_iff)\n    apply (rule_tac x = \"\\<lparr>bel\\<^sub>v = (0::\\<nat>)\\<rparr>\" in exI)\n    by force\n\nhave sum_2: \"(\\<Sum>\\<^sub>\\<infinity>s::robot_local_state. (4::\\<real>) * (if bel\\<^sub>v s = Suc (0::\\<nat>) then 1::\\<real> else (0::\\<real>)) / (9::\\<real>)) = 4/9\"\n    apply (subst infsum_cdiv_left)\n    apply (rule summable_on_cmult_right)\n    apply (rule infsum_constant_finite_states_summable)\n    apply (smt (z3) Collect_mono finite.emptyI finite.insertI rev_finite_subset \n      robot_local_state.equality singleton_conv unit.exhaust)\n    apply (subst infsum_cmult_right)\n    apply (rule infsum_constant_finite_states_summable)\n    apply (smt (z3) Collect_mono finite.emptyI finite.insertI rev_finite_subset \n      robot_local_state.equality singleton_conv unit.exhaust)\n    apply (subst infsum_constant_finite_states)\n    apply (smt (z3) Collect_mono finite.emptyI finite.insertI rev_finite_subset \n      robot_local_state.equality singleton_conv unit.exhaust)\n    apply (simp)\n    apply (subst card_1_singleton_iff)\n    apply (rule_tac x = \"\\<lparr>bel\\<^sub>v = Suc (0::\\<nat>)\\<rparr>\" in exI)\n    by force\n\n  have sum_3: \"(\\<Sum>\\<^sub>\\<infinity>s::robot_local_state. (if bel\\<^sub>v s = (2::\\<nat>) then 1::\\<real> else (0::\\<real>)) / (9::\\<real>)) = 1/9\"\n    apply (subst infsum_cdiv_left)\n    apply (rule infsum_constant_finite_states_summable)\n    apply (smt (z3) Collect_mono finite.emptyI finite.insertI rev_finite_subset \n      robot_local_state.equality singleton_conv unit.exhaust)\n    apply (subst infsum_constant_finite_states)\n    apply (smt (z3) Collect_mono finite.emptyI finite.insertI rev_finite_subset \n      robot_local_state.equality singleton_conv unit.exhaust)\n    apply (simp)\n    apply (subst card_1_singleton_iff)\n    apply (rule_tac x = \"\\<lparr>bel\\<^sub>v = (2::\\<nat>)\\<rparr>\" in exI)\n  by force\n\n  show ?thesis\n    apply (simp add: move_right_1_def)\n    apply (subst rvfun_inverse)\n     apply (expr_auto add: dist_defs)\n    by simp\nqed\n\nsubsection \\<open> Second sensor reading \\<close>\nlemma believe_2_sum: \"(\\<Sum>\\<^sub>\\<infinity>v\\<^sub>0::robot_local_state.\n         (4::\\<real>) * (if bel\\<^sub>v v\\<^sub>0 = (0::\\<nat>) then 1::\\<real> else (0::\\<real>)) *\n         ((3::\\<real>) * (if bel\\<^sub>v v\\<^sub>0 = (0::\\<nat>) \\<or> bel\\<^sub>v v\\<^sub>0 = (2::\\<nat>) then 1::\\<real> else (0::\\<real>)) + (1::\\<real>)) /\n         (9::\\<real>) +\n         (4::\\<real>) * (if bel\\<^sub>v v\\<^sub>0 = Suc (0::\\<nat>) then 1::\\<real> else (0::\\<real>)) *\n         ((3::\\<real>) * (if bel\\<^sub>v v\\<^sub>0 = (0::\\<nat>) \\<or> bel\\<^sub>v v\\<^sub>0 = (2::\\<nat>) then 1::\\<real> else (0::\\<real>)) + (1::\\<real>)) /\n         (9::\\<real>) +\n         (if bel\\<^sub>v v\\<^sub>0 = (2::\\<nat>) then 1::\\<real> else (0::\\<real>)) *\n         ((3::\\<real>) * (if bel\\<^sub>v v\\<^sub>0 = (0::\\<nat>) \\<or> bel\\<^sub>v v\\<^sub>0 = (2::\\<nat>) then 1::\\<real> else (0::\\<real>)) + (1::\\<real>)) /\n         (9::\\<real>)) = 8 /3\"\n  apply (simp add: ring_distribs(1))\n  apply (subst mult.assoc[symmetric,where b = \"3\"])\n  apply (subst mult.commute[where b = \"3\"])\n  apply (subst mult.assoc)\n  apply (subst conditional_conds_conj)+\nproof -\n  let ?f1 = \"(\\<lambda>v\\<^sub>0::robot_local_state. ((12::\\<real>) *\n        (if bel\\<^sub>v v\\<^sub>0 = (0::\\<nat>) \\<and> (bel\\<^sub>v v\\<^sub>0 = (0::\\<nat>) \\<or> bel\\<^sub>v v\\<^sub>0 = (2::\\<nat>)) then 1::\\<real> else (0::\\<real>)) +\n        (4::\\<real>) * (if bel\\<^sub>v v\\<^sub>0 = (0::\\<nat>) then 1::\\<real> else (0::\\<real>))) /\n       (9::\\<real>))\"\n  let ?f2 = \"(\\<lambda>v\\<^sub>0::robot_local_state. ((12::\\<real>) *\n        (if bel\\<^sub>v v\\<^sub>0 = Suc (0::\\<nat>) \\<and> (bel\\<^sub>v v\\<^sub>0 = (0::\\<nat>) \\<or> bel\\<^sub>v v\\<^sub>0 = (2::\\<nat>)) then 1::\\<real> else (0::\\<real>)) +\n        (4::\\<real>) * (if bel\\<^sub>v v\\<^sub>0 = Suc (0::\\<nat>) then 1::\\<real> else (0::\\<real>))) /\n       (9::\\<real>))\"\n  let ?f3 = \"(\\<lambda>v\\<^sub>0::robot_local_state. ((3::\\<real>) * (if bel\\<^sub>v v\\<^sub>0 = (2::\\<nat>) \\<and> (bel\\<^sub>v v\\<^sub>0 = (0::\\<nat>) \\<or> bel\\<^sub>v v\\<^sub>0 = (2::\\<nat>)) then 1::\\<real> else (0::\\<real>)) +\n      (if bel\\<^sub>v v\\<^sub>0 = (2::\\<nat>) then 1::\\<real> else (0::\\<real>))) /\n     (9::\\<real>))\"\n  have summable_1: \"?f1 summable_on UNIV\"\n    apply (rule summable_on_cdiv_left)\n    apply (rule summable_on_add)\n    apply (rule summable_on_cmult_right)\n    apply (rule infsum_constant_finite_states_summable)\n    apply (smt (verit, ccfv_SIG) Collect_mono finite.emptyI finite.insertI not_finite_existsD \n        rev_finite_subset robot_local_state.equality singleton_conv unit.exhaust)\n    apply (rule summable_on_cmult_right)\n    apply (rule infsum_constant_finite_states_summable)\n    by (metis (mono_tags, lifting) card.infinite card_1_singleton nat.simps(3) not_finite_existsD \n        robot_local_state.equality unit.exhaust)\n  have summable_2: \"?f2 summable_on UNIV\"\n    apply (rule summable_on_cdiv_left)\n    apply (rule summable_on_add)\n    apply (rule summable_on_cmult_right)\n    apply (rule infsum_constant_finite_states_summable)\n    apply (smt (verit, ccfv_SIG) Collect_mono finite.emptyI finite.insertI not_finite_existsD \n        rev_finite_subset robot_local_state.equality singleton_conv unit.exhaust)\n    apply (rule summable_on_cmult_right)\n    apply (rule infsum_constant_finite_states_summable)\n    by (metis (mono_tags, lifting) card.infinite card_1_singleton nat.simps(3) not_finite_existsD \n        robot_local_state.equality unit.exhaust)\n  have summable_3: \"?f3 summable_on UNIV\"\n    apply (rule summable_on_cdiv_left)\n    apply (rule summable_on_add)\n    apply (rule summable_on_cmult_right)\n    apply (rule infsum_constant_finite_states_summable)\n    apply (smt (verit, ccfv_SIG) Collect_mono finite.emptyI finite.insertI not_finite_existsD \n        rev_finite_subset robot_local_state.equality singleton_conv unit.exhaust)\n    apply (rule infsum_constant_finite_states_summable)\n    by (metis (mono_tags, lifting) card.infinite card_1_singleton nat.simps(3) not_finite_existsD \n        robot_local_state.equality unit.exhaust)\n\n  have card_1: \"card {s::robot_local_state. bel\\<^sub>v s = 0} = Suc (0)\"\n    apply (subst card_1_singleton_iff)\n    by (smt (verit, del_insts) Collect_cong robot_local_state.equality robot_local_state.select_convs(1) \n      singleton_conv unit.exhaust)\n  have card_2: \"card {s::robot_local_state. bel\\<^sub>v s = Suc (0)} = Suc (0)\"\n    apply (subst card_1_singleton_iff)\n    by (smt (verit, del_insts) Collect_cong robot_local_state.equality robot_local_state.select_convs(1) \n      singleton_conv unit.exhaust)\n  have card_3: \"card {s::robot_local_state. bel\\<^sub>v s = 2} = Suc (0)\"\n    apply (subst card_1_singleton_iff)\n    by (smt (verit, del_insts) Collect_cong robot_local_state.equality robot_local_state.select_convs(1) \n      singleton_conv unit.exhaust)\n\n  have sum_1: \"(\\<Sum>\\<^sub>\\<infinity>v\\<^sub>0::robot_local_state. ?f1 v\\<^sub>0) = 16 / 9\"\n    apply (subst infsum_cdiv_left)\n    apply (rule summable_on_add)\n    apply (rule summable_on_cmult_right)\n    apply (rule infsum_constant_finite_states_summable)\n    apply (smt (verit, ccfv_SIG) Collect_mono finite.emptyI finite.insertI not_finite_existsD \n        rev_finite_subset robot_local_state.equality singleton_conv unit.exhaust)\n    apply (rule summable_on_cmult_right)\n    apply (rule infsum_constant_finite_states_summable)\n    apply (metis (mono_tags, lifting) card.infinite card_1_singleton nat.simps(3) not_finite_existsD \n        robot_local_state.equality unit.exhaust)\n    apply (subst infsum_add)\n    apply (rule summable_on_cmult_right)\n    apply (rule infsum_constant_finite_states_summable)\n    apply (smt (verit, ccfv_SIG) Collect_mono finite.emptyI finite.insertI not_finite_existsD \n        rev_finite_subset robot_local_state.equality singleton_conv unit.exhaust)\n    apply (rule summable_on_cmult_right)\n    apply (rule infsum_constant_finite_states_summable)\n    apply (metis (mono_tags, lifting) card.infinite card_1_singleton nat.simps(3) not_finite_existsD \n        robot_local_state.equality unit.exhaust)\n    apply (subst infsum_cmult_right)\n    apply (rule infsum_constant_finite_states_summable)\n    apply (metis (mono_tags, lifting) card.infinite card_1_singleton nat.simps(3) not_finite_existsD \n        robot_local_state.equality unit.exhaust)\n    apply (subst infsum_cmult_right)\n    apply (rule infsum_constant_finite_states_summable)\n    apply (metis (mono_tags, lifting) card.infinite card_1_singleton nat.simps(3) not_finite_existsD \n        robot_local_state.equality unit.exhaust)\n    apply (subst infsum_constant_finite_states)\n    apply (metis (mono_tags, lifting) card.infinite card_1_singleton nat.simps(3) not_finite_existsD \n        robot_local_state.equality unit.exhaust)\n    apply (subst infsum_constant_finite_states)\n    apply (metis (mono_tags, lifting) card.infinite card_1_singleton nat.simps(3) not_finite_existsD \n        robot_local_state.equality unit.exhaust)\n    using card_1 by (smt (verit, ccfv_SIG) Collect_cong One_nat_def of_nat_1)\n\n  have sum_2: \"(\\<Sum>\\<^sub>\\<infinity>v\\<^sub>0::robot_local_state. ?f2 v\\<^sub>0) = 4 / 9\"\n    apply (subst infsum_cdiv_left)\n    apply (rule summable_on_add)\n    apply (rule summable_on_cmult_right)\n    apply (rule infsum_constant_finite_states_summable)\n    apply (smt (verit, ccfv_SIG) Collect_mono finite.emptyI finite.insertI not_finite_existsD \n        rev_finite_subset robot_local_state.equality singleton_conv unit.exhaust)\n    apply (rule summable_on_cmult_right)\n    apply (rule infsum_constant_finite_states_summable)\n    apply (metis (mono_tags, lifting) card.infinite card_1_singleton nat.simps(3) not_finite_existsD \n        robot_local_state.equality unit.exhaust)\n    apply (subst infsum_add)\n    apply (rule summable_on_cmult_right)\n    apply (rule infsum_constant_finite_states_summable)\n    apply (smt (verit, ccfv_SIG) Collect_mono finite.emptyI finite.insertI not_finite_existsD \n        rev_finite_subset robot_local_state.equality singleton_conv unit.exhaust)\n    apply (rule summable_on_cmult_right)\n    apply (rule infsum_constant_finite_states_summable)\n    apply (metis (mono_tags, lifting) card.infinite card_1_singleton nat.simps(3) not_finite_existsD \n        robot_local_state.equality unit.exhaust)\n    apply (subst infsum_cmult_right)\n    apply (rule infsum_constant_finite_states_summable)\n    apply (metis (mono_tags, lifting) card.infinite card_1_singleton nat.simps(3) not_finite_existsD \n        robot_local_state.equality unit.exhaust)\n    apply (subst infsum_cmult_right)\n    apply (rule infsum_constant_finite_states_summable)\n    apply (metis (mono_tags, lifting) card.infinite card_1_singleton nat.simps(3) not_finite_existsD \n        robot_local_state.equality unit.exhaust)\n    apply (subst infsum_constant_finite_states)\n    apply (metis (mono_tags, lifting) card.infinite card_1_singleton nat.simps(3) not_finite_existsD \n        robot_local_state.equality unit.exhaust)\n    apply (subst infsum_constant_finite_states)\n    apply (metis (mono_tags, lifting) card.infinite card_1_singleton nat.simps(3) not_finite_existsD \n        robot_local_state.equality unit.exhaust)\n    using card_2 by (simp add: card_0_singleton)\n\n  have sum_3: \"(\\<Sum>\\<^sub>\\<infinity>v\\<^sub>0::robot_local_state. ?f3 v\\<^sub>0) = 4 / 9\"\n    apply (subst infsum_cdiv_left)\n    apply (rule summable_on_add)\n    apply (rule summable_on_cmult_right)\n    apply (rule infsum_constant_finite_states_summable)\n    apply (smt (verit, ccfv_SIG) Collect_mono finite.emptyI finite.insertI not_finite_existsD \n        rev_finite_subset robot_local_state.equality singleton_conv unit.exhaust)\n    apply (rule infsum_constant_finite_states_summable)\n    apply (metis (mono_tags, lifting) card.infinite card_1_singleton nat.simps(3) not_finite_existsD \n        robot_local_state.equality unit.exhaust)\n    apply (subst infsum_add)\n    apply (rule summable_on_cmult_right)\n    apply (rule infsum_constant_finite_states_summable)\n    apply (smt (verit, ccfv_SIG) Collect_mono finite.emptyI finite.insertI not_finite_existsD \n        rev_finite_subset robot_local_state.equality singleton_conv unit.exhaust)\n    apply (rule infsum_constant_finite_states_summable)\n    apply (metis (mono_tags, lifting) card.infinite card_1_singleton nat.simps(3) not_finite_existsD \n        robot_local_state.equality unit.exhaust)\n    apply (subst infsum_cmult_right)\n    apply (rule infsum_constant_finite_states_summable)\n    apply (metis (mono_tags, lifting) card.infinite card_1_singleton nat.simps(3) not_finite_existsD \n        robot_local_state.equality unit.exhaust)\n    apply (subst infsum_constant_finite_states)\n    apply (metis (mono_tags, lifting) card.infinite card_1_singleton nat.simps(3) not_finite_existsD \n        robot_local_state.equality unit.exhaust)\n    apply (subst infsum_constant_finite_states)\n    apply (metis (mono_tags, lifting) card.infinite card_1_singleton nat.simps(3) not_finite_existsD \n        robot_local_state.equality unit.exhaust)\n  using card_3 by (smt (verit, ccfv_SIG) Collect_cong One_nat_def of_nat_1)\n\n  show \"(\\<Sum>\\<^sub>\\<infinity>v\\<^sub>0::robot_local_state. ?f1 v\\<^sub>0 + ?f2 v\\<^sub>0 + ?f3 v\\<^sub>0) * 3 = 8\"\n    apply (subst infsum_add)\n    apply (rule summable_on_add)\n    using summable_1 apply blast\n    using summable_2 apply blast\n    using summable_3 apply blast\n    apply (subst infsum_add)\n    using summable_1 apply blast\n    using summable_2 apply blast\n    by (simp add: sum_1 sum_2 sum_3)\nqed\n  \nlemma believe_2_simp: \"(((init \\<parallel> scale_door) ; move_right) \\<parallel> scale_door) = \n  prfun_of_rvfun believe_2\"\n  apply (simp add: move_right_1_simp believe_2_def)\n  apply (simp add: scale_door_def door_def pfun_defs)\n  apply (simp add: move_right_1_dist)\n  apply (simp add: move_right_1_def dist_defs)\n  apply (expr_simp_1)\n  apply (rule HOL.arg_cong[where f=\"prfun_of_rvfun\"])\n  apply (simp add: ring_distribs(2))\n  apply (subst fun_eq_iff, rule allI)\n  apply (auto)\n  by (simp add: believe_2_sum)+\n\nlemma believe_2_dist: \"rvfun_of_prfun (prfun_of_rvfun believe_2) = believe_2\"\nproof -\n  have summable_1: \"(\\<lambda>s::robot_local_state. (2::\\<real>) * (if bel\\<^sub>v s = (0::\\<nat>) then 1::\\<real> else (0::\\<real>)) / (3::\\<real>)) \n        summable_on UNIV\"\n    apply (rule summable_on_cdiv_left)\n    apply (rule summable_on_cmult_right)\n    apply (rule infsum_constant_finite_states_summable)\n    by (smt (z3) Collect_mono card_0_eq finite.insertI infinite_arbitrarily_large rev_finite_subset \n      robot_local_state.surjective singleton_conv unit.exhaust)\n\n  have summable_2: \"(\\<lambda>s::robot_local_state. (if bel\\<^sub>v s = Suc (0::\\<nat>) then 1::\\<real> else (0::\\<real>)) / (6::\\<real>)) \n      summable_on UNIV\"\n    apply (rule summable_on_cdiv_left)\n    apply (rule infsum_constant_finite_states_summable)\n    by (smt (z3) Collect_mono finite.emptyI finite.insertI rev_finite_subset \n      robot_local_state.equality singleton_conv unit.exhaust)\n\n  have summable_3: \"(\\<lambda>s::robot_local_state. (if bel\\<^sub>v s = (2::\\<nat>) then 1::\\<real> else (0::\\<real>)) / (6::\\<real>)) \n      summable_on UNIV\"\n    apply (rule summable_on_cdiv_left)\n    apply (rule infsum_constant_finite_states_summable)\n    by (smt (z3) Collect_mono finite.emptyI finite.insertI rev_finite_subset \n      robot_local_state.equality singleton_conv unit.exhaust)\n\n  have sum_1: \"(\\<Sum>\\<^sub>\\<infinity>s::robot_local_state. (2::\\<real>) * (if bel\\<^sub>v s = (0::\\<nat>) then 1::\\<real> else (0::\\<real>)) / (3::\\<real>)) = 2/3\"\n    apply (subst infsum_cdiv_left)\n    apply (rule summable_on_cmult_right)\n    apply (rule infsum_constant_finite_states_summable)\n    apply (smt (z3) Collect_mono finite.emptyI finite.insertI rev_finite_subset \n      robot_local_state.equality singleton_conv unit.exhaust)\n    apply (subst infsum_cmult_right)\n    apply (rule infsum_constant_finite_states_summable)\n    apply (smt (z3) Collect_mono finite.emptyI finite.insertI rev_finite_subset \n      robot_local_state.equality singleton_conv unit.exhaust)\n    apply (subst infsum_constant_finite_states)\n    apply (smt (z3) Collect_mono finite.emptyI finite.insertI rev_finite_subset \n      robot_local_state.equality singleton_conv unit.exhaust)\n    apply (simp)\n    apply (subst card_1_singleton_iff)\n    apply (rule_tac x = \"\\<lparr>bel\\<^sub>v = (0::\\<nat>)\\<rparr>\" in exI)\n    by force\n\n  have sum_2: \"(\\<Sum>\\<^sub>\\<infinity>s::robot_local_state. (if bel\\<^sub>v s = Suc (0::\\<nat>) then 1::\\<real> else (0::\\<real>)) / (6::\\<real>)) = 1/6\"\n    apply (subst infsum_cdiv_left)\n    apply (rule infsum_constant_finite_states_summable)\n    apply (smt (z3) Collect_mono finite.emptyI finite.insertI rev_finite_subset \n      robot_local_state.equality singleton_conv unit.exhaust)\n    apply (subst infsum_constant_finite_states)\n    apply (smt (z3) Collect_mono finite.emptyI finite.insertI rev_finite_subset \n      robot_local_state.equality singleton_conv unit.exhaust)\n    apply (simp)\n    apply (subst card_1_singleton_iff)\n    apply (rule_tac x = \"\\<lparr>bel\\<^sub>v = Suc (0::\\<nat>)\\<rparr>\" in exI)\n    by force\n\n  have sum_3: \"(\\<Sum>\\<^sub>\\<infinity>s::robot_local_state. (if bel\\<^sub>v s = (2::\\<nat>) then 1::\\<real> else (0::\\<real>)) / (6::\\<real>)) = 1/6\"\n    apply (subst infsum_cdiv_left)\n    apply (rule infsum_constant_finite_states_summable)\n    apply (smt (z3) Collect_mono finite.emptyI finite.insertI rev_finite_subset \n      robot_local_state.equality singleton_conv unit.exhaust)\n    apply (subst infsum_constant_finite_states)\n    apply (smt (z3) Collect_mono finite.emptyI finite.insertI rev_finite_subset \n      robot_local_state.equality singleton_conv unit.exhaust)\n    apply (simp)\n    apply (subst card_1_singleton_iff)\n    apply (rule_tac x = \"\\<lparr>bel\\<^sub>v = (2::\\<nat>)\\<rparr>\" in exI)\n  by force\n\n  show ?thesis\n    apply (simp add: believe_2_def)\n    apply (subst rvfun_inverse)\n    apply (expr_auto add: dist_defs)\n    by (simp)\nqed\n\nsubsection \\<open> Second move \\<close>\nlemma move_right_2_simp: \n  \"((((init \\<parallel> scale_door) ; move_right) \\<parallel> scale_door) ; move_right) = prfun_of_rvfun move_right_2\"\n  apply (simp add: believe_2_simp)\n  apply (simp add: move_right_2_def move_right_def)\n  apply (simp add: pfun_defs)\n  apply (simp add: believe_2_dist)\n  apply (subst rvfun_assignment_inverse)\n  apply (simp add: believe_2_def)\n  apply (rule HOL.arg_cong[where f=\"prfun_of_rvfun\"])\n  apply (expr_auto add: rel assigns_r_def)\n  apply (simp_all add: ring_distribs(2))\n  apply (simp add: mult.assoc)+\n  apply (subst conditional_conds_conj)+\n  defer\n  apply (simp add: mult.assoc)+\n  apply (subst conditional_conds_conj)+\n  defer\n  apply (simp add: mult.assoc)+\n  apply (subst conditional_conds_conj)+\n  defer\n  apply (simp add: mult.assoc)+\n  apply (subst conditional_conds_conj)+\n  defer \nproof -\n  let ?lhs_f = \"\\<lambda>v\\<^sub>0::robot_local_state. (2::\\<real>) *\n       (if bel\\<^sub>v v\\<^sub>0 = (0::\\<nat>) \\<and> \\<lparr>bel\\<^sub>v = Suc (0::\\<nat>)\\<rparr> = v\\<^sub>0\\<lparr>bel\\<^sub>v := Suc (bel\\<^sub>v v\\<^sub>0) mod (3::\\<nat>)\\<rparr> then 1::\\<real>\n        else (0::\\<real>)) / (3::\\<real>) +\n       (if bel\\<^sub>v v\\<^sub>0 = Suc (0::\\<nat>) \\<and> \\<lparr>bel\\<^sub>v = Suc (0::\\<nat>)\\<rparr> = v\\<^sub>0\\<lparr>bel\\<^sub>v := Suc (bel\\<^sub>v v\\<^sub>0) mod (3::\\<nat>)\\<rparr> then 1::\\<real>\n        else (0::\\<real>)) / (6::\\<real>) +\n       (if bel\\<^sub>v v\\<^sub>0 = (2::\\<nat>) \\<and> \\<lparr>bel\\<^sub>v = Suc (0::\\<nat>)\\<rparr> = v\\<^sub>0\\<lparr>bel\\<^sub>v := Suc (bel\\<^sub>v v\\<^sub>0) mod (3::\\<nat>)\\<rparr> then 1::\\<real>\n        else (0::\\<real>)) / (6::\\<real>)\"\n  let ?lhs = \"(\\<Sum>\\<^sub>\\<infinity>v\\<^sub>0::robot_local_state. ?lhs_f v\\<^sub>0)\"\n\n  have f1: \"\\<forall>v\\<^sub>0. (bel\\<^sub>v v\\<^sub>0 = (0::\\<nat>) \\<and> (\\<lparr>bel\\<^sub>v = Suc (0::\\<nat>)\\<rparr> = v\\<^sub>0\\<lparr>bel\\<^sub>v := Suc (bel\\<^sub>v v\\<^sub>0) mod (3::\\<nat>)\\<rparr>)) = \n      (\\<lparr>bel\\<^sub>v = 0::\\<nat>\\<rparr> = v\\<^sub>0)\"\n    by auto\n  have f2: \"\\<forall>v\\<^sub>0. \\<not>(bel\\<^sub>v v\\<^sub>0 = Suc (0::\\<nat>) \\<and> \\<lparr>bel\\<^sub>v = Suc (0::\\<nat>)\\<rparr> = v\\<^sub>0\\<lparr>bel\\<^sub>v := Suc (bel\\<^sub>v v\\<^sub>0) mod (3::\\<nat>)\\<rparr>)\"\n    apply (auto)\n    by (metis n_not_Suc_n robot_local_state.select_convs(1) robot_local_state.surjective \n        robot_local_state.update_convs(1))\n  have f3: \"\\<forall>v\\<^sub>0. \\<not>(bel\\<^sub>v v\\<^sub>0 = (2::\\<nat>) \\<and> \\<lparr>bel\\<^sub>v = Suc (0::\\<nat>)\\<rparr> = v\\<^sub>0\\<lparr>bel\\<^sub>v := Suc (bel\\<^sub>v v\\<^sub>0) mod (3::\\<nat>)\\<rparr>)\"\n    apply (auto)\n    by (metis n_not_Suc_n robot_local_state.select_convs(1) robot_local_state.surjective \n        robot_local_state.update_convs(1))\n  show \"?lhs * (3::\\<real>) = (2::\\<real>)\"\n    apply (simp add: f1 f2 f3)\n    apply (subst infsum_cdiv_left)\n    apply (rule summable_on_cmult_right)\n    apply (simp add: infsum_singleton_summable)\n    apply (subst infsum_cmult_right)\n    apply (simp add: infsum_singleton_summable)\n    apply (subst infsum_constant_finite_states)\n    by (simp)+\nnext\n  let ?lhs_f = \"\\<lambda>v\\<^sub>0::robot_local_state. (2::\\<real>) *\n       (if bel\\<^sub>v v\\<^sub>0 = (0::\\<nat>) \\<and> \\<lparr>bel\\<^sub>v = (0::\\<nat>)\\<rparr> = v\\<^sub>0\\<lparr>bel\\<^sub>v := Suc (bel\\<^sub>v v\\<^sub>0) mod (3::\\<nat>)\\<rparr> then 1::\\<real>\n        else (0::\\<real>)) / (3::\\<real>) +\n       (if bel\\<^sub>v v\\<^sub>0 = Suc (0::\\<nat>) \\<and> \\<lparr>bel\\<^sub>v = (0::\\<nat>)\\<rparr> = v\\<^sub>0\\<lparr>bel\\<^sub>v := Suc (bel\\<^sub>v v\\<^sub>0) mod (3::\\<nat>)\\<rparr> then 1::\\<real>\n        else (0::\\<real>)) / (6::\\<real>) +\n       (if bel\\<^sub>v v\\<^sub>0 = (2::\\<nat>) \\<and> \\<lparr>bel\\<^sub>v = (0::\\<nat>)\\<rparr> = v\\<^sub>0\\<lparr>bel\\<^sub>v := Suc (bel\\<^sub>v v\\<^sub>0) mod (3::\\<nat>)\\<rparr> then 1::\\<real>\n        else (0::\\<real>)) / (6::\\<real>)\"\n  let ?lhs = \"(\\<Sum>\\<^sub>\\<infinity>v\\<^sub>0::robot_local_state. ?lhs_f v\\<^sub>0)\"\n\n  have f1: \"\\<forall>v\\<^sub>0. \\<not>(bel\\<^sub>v v\\<^sub>0 = (0::\\<nat>) \\<and> (\\<lparr>bel\\<^sub>v = (0::\\<nat>)\\<rparr> = v\\<^sub>0\\<lparr>bel\\<^sub>v := Suc (bel\\<^sub>v v\\<^sub>0) mod (3::\\<nat>)\\<rparr>))\"\n    apply (auto)\n    by (metis n_not_Suc_n robot_local_state.select_convs(1) robot_local_state.surjective \n        robot_local_state.update_convs(1))\n  have f2: \"\\<forall>v\\<^sub>0. \\<not>(bel\\<^sub>v v\\<^sub>0 = Suc (0::\\<nat>) \\<and> \\<lparr>bel\\<^sub>v = (0::\\<nat>)\\<rparr> = v\\<^sub>0\\<lparr>bel\\<^sub>v := Suc (bel\\<^sub>v v\\<^sub>0) mod (3::\\<nat>)\\<rparr>)\"\n    apply (auto)\n    by (metis nat.distinct(1) robot_local_state.select_convs(1) robot_local_state.surjective \n        robot_local_state.update_convs(1))\n  have f3: \"\\<forall>v\\<^sub>0. (bel\\<^sub>v v\\<^sub>0 = (2::\\<nat>) \\<and> \\<lparr>bel\\<^sub>v = (0::\\<nat>)\\<rparr> = v\\<^sub>0\\<lparr>bel\\<^sub>v := Suc (bel\\<^sub>v v\\<^sub>0) mod (3::\\<nat>)\\<rparr>)  = \n      (\\<lparr>bel\\<^sub>v = 2::\\<nat>\\<rparr> = v\\<^sub>0)\"\n    by (auto)\n  show \"?lhs * (6::\\<real>) = (1::\\<real>)\"\n    apply (simp add: f1 f2 f3)\n    apply (subst infsum_cdiv_left)\n    apply (simp add: infsum_singleton_summable)\n    apply (subst infsum_constant_finite_states)\n    by (simp)+\nnext\n  let ?lhs_f = \"\\<lambda>v\\<^sub>0::robot_local_state. (2::\\<real>) *\n       (if bel\\<^sub>v v\\<^sub>0 = (0::\\<nat>) \\<and> \\<lparr>bel\\<^sub>v = (2::\\<nat>)\\<rparr> = v\\<^sub>0\\<lparr>bel\\<^sub>v := Suc (bel\\<^sub>v v\\<^sub>0) mod (3::\\<nat>)\\<rparr> then 1::\\<real>\n        else (0::\\<real>)) / (3::\\<real>) +\n       (if bel\\<^sub>v v\\<^sub>0 = Suc (0::\\<nat>) \\<and> \\<lparr>bel\\<^sub>v = (2::\\<nat>)\\<rparr> = v\\<^sub>0\\<lparr>bel\\<^sub>v := Suc (bel\\<^sub>v v\\<^sub>0) mod (3::\\<nat>)\\<rparr> then 1::\\<real>\n        else (0::\\<real>)) / (6::\\<real>) +\n       (if bel\\<^sub>v v\\<^sub>0 = (2::\\<nat>) \\<and> \\<lparr>bel\\<^sub>v = (2::\\<nat>)\\<rparr> = v\\<^sub>0\\<lparr>bel\\<^sub>v := Suc (bel\\<^sub>v v\\<^sub>0) mod (3::\\<nat>)\\<rparr> then 1::\\<real>\n        else (0::\\<real>)) / (6::\\<real>)\"\n  let ?lhs = \"(\\<Sum>\\<^sub>\\<infinity>v\\<^sub>0::robot_local_state. ?lhs_f v\\<^sub>0)\"\n\n  have f1: \"\\<forall>v\\<^sub>0. \\<not>(bel\\<^sub>v v\\<^sub>0 = (0::\\<nat>) \\<and> (\\<lparr>bel\\<^sub>v = (2::\\<nat>)\\<rparr> = v\\<^sub>0\\<lparr>bel\\<^sub>v := Suc (bel\\<^sub>v v\\<^sub>0) mod (3::\\<nat>)\\<rparr>))\"\n    apply (auto)\n    by (metis n_not_Suc_n numeral_2_eq_2 robot_local_state.select_convs(1) \n        robot_local_state.surjective robot_local_state.update_convs(1))\n  have f2: \"\\<forall>v\\<^sub>0. (bel\\<^sub>v v\\<^sub>0 = Suc (0::\\<nat>) \\<and> \\<lparr>bel\\<^sub>v = (2::\\<nat>)\\<rparr> = v\\<^sub>0\\<lparr>bel\\<^sub>v := Suc (bel\\<^sub>v v\\<^sub>0) mod (3::\\<nat>)\\<rparr>) =  \n      (\\<lparr>bel\\<^sub>v = Suc (0::\\<nat>)\\<rparr> = v\\<^sub>0)\"\n    by (auto)\n  have f3: \"\\<forall>v\\<^sub>0. \\<not>(bel\\<^sub>v v\\<^sub>0 = (2::\\<nat>) \\<and> \\<lparr>bel\\<^sub>v = (2::\\<nat>)\\<rparr> = v\\<^sub>0\\<lparr>bel\\<^sub>v := Suc (bel\\<^sub>v v\\<^sub>0) mod (3::\\<nat>)\\<rparr>)\"\n    apply (auto)\n    by (metis robot_local_state.select_convs(1) robot_local_state.surjective \n        robot_local_state.update_convs(1) zero_neq_numeral)\n  show \"?lhs * (6::\\<real>) = (1::\\<real>)\"\n    apply (simp add: f1 f2 f3)\n    apply (subst infsum_cdiv_left)\n    apply (simp add: infsum_singleton_summable)\n    apply (subst infsum_constant_finite_states)\n    by (simp)+\nnext\n  fix bel\n  assume a1: \"\\<not> bel = Suc (0::\\<nat>)\"\n  assume a2: \"(0::\\<nat>) < bel\"\n  assume a3: \"\\<not> bel = (2::\\<nat>)\"\n\n  have f1: \"\\<forall>v\\<^sub>0. \\<not>(bel\\<^sub>v v\\<^sub>0 = (0::\\<nat>) \\<and> \\<lparr>bel\\<^sub>v = bel\\<rparr> = v\\<^sub>0\\<lparr>bel\\<^sub>v := Suc (bel\\<^sub>v v\\<^sub>0) mod (3::\\<nat>)\\<rparr>)\"\n    apply (auto)\n    by (metis a1 robot_local_state.select_convs(1) robot_local_state.surjective \n        robot_local_state.update_convs(1))\n  have f2: \"\\<forall>v\\<^sub>0. \\<not>(bel\\<^sub>v v\\<^sub>0 = Suc (0::\\<nat>) \\<and> \\<lparr>bel\\<^sub>v = bel\\<rparr> = v\\<^sub>0\\<lparr>bel\\<^sub>v := Suc (bel\\<^sub>v v\\<^sub>0) mod (3::\\<nat>)\\<rparr>)\"\n    apply (auto)\n    by (metis a3 numeral_2_eq_2 robot_local_state.select_convs(1) robot_local_state.surjective \n        robot_local_state.update_convs(1))\n  have f3: \"\\<forall>v\\<^sub>0. \\<not>(bel\\<^sub>v v\\<^sub>0 = (2::\\<nat>) \\<and> \\<lparr>bel\\<^sub>v = bel\\<rparr> = v\\<^sub>0\\<lparr>bel\\<^sub>v := Suc (bel\\<^sub>v v\\<^sub>0) mod (3::\\<nat>)\\<rparr>)\"\n    apply (auto)\n    by (metis a2 nat_neq_iff robot_local_state.select_convs(1) robot_local_state.surjective \n        robot_local_state.update_convs(1))\n\n  show \"(\\<Sum>\\<^sub>\\<infinity>v\\<^sub>0::robot_local_state.\n          (2::\\<real>) * (if bel\\<^sub>v v\\<^sub>0 = (0::\\<nat>) \\<and> \\<lparr>bel\\<^sub>v = bel\\<rparr> = v\\<^sub>0\\<lparr>bel\\<^sub>v := Suc (bel\\<^sub>v v\\<^sub>0) mod (3::\\<nat>)\\<rparr> then 1::\\<real>\n           else (0::\\<real>)) /\n          (3::\\<real>) +\n          (if bel\\<^sub>v v\\<^sub>0 = Suc (0::\\<nat>) \\<and> \\<lparr>bel\\<^sub>v = bel\\<rparr> = v\\<^sub>0\\<lparr>bel\\<^sub>v := Suc (bel\\<^sub>v v\\<^sub>0) mod (3::\\<nat>)\\<rparr> then 1::\\<real>\n           else (0::\\<real>)) /\n          (6::\\<real>) +\n          (if bel\\<^sub>v v\\<^sub>0 = (2::\\<nat>) \\<and> \\<lparr>bel\\<^sub>v = bel\\<rparr> = v\\<^sub>0\\<lparr>bel\\<^sub>v := Suc (bel\\<^sub>v v\\<^sub>0) mod (3::\\<nat>)\\<rparr> then 1::\\<real>\n           else (0::\\<real>)) /\n          (6::\\<real>)) =\n       (0::\\<real>) \"\n    by (simp add: f1 f2 f3)\nqed\n\n\nlemma move_right_2_dist: \"rvfun_of_prfun (prfun_of_rvfun move_right_2) = move_right_2\"\nproof -\n  have summable_1: \"(\\<lambda>s::robot_local_state. (if bel\\<^sub>v s = (0::\\<nat>) then 1::\\<real> else (0::\\<real>)) / (6::\\<real>)) \n        summable_on UNIV\"\n    apply (rule summable_on_cdiv_left)\n    apply (rule infsum_constant_finite_states_summable)\n    by (smt (z3) Collect_mono card_0_eq finite.insertI infinite_arbitrarily_large rev_finite_subset \n      robot_local_state.surjective singleton_conv unit.exhaust)\n\n  have summable_2: \"(\\<lambda>s::robot_local_state. (2::\\<real>) * (if bel\\<^sub>v s = Suc (0::\\<nat>) then 1::\\<real> else (0::\\<real>)) / (3::\\<real>)) \n      summable_on UNIV\"\n    apply (rule summable_on_cdiv_left)\n    apply (rule summable_on_cmult_right)\n    apply (rule infsum_constant_finite_states_summable)\n    by (smt (z3) Collect_mono finite.emptyI finite.insertI rev_finite_subset \n      robot_local_state.equality singleton_conv unit.exhaust)\n\n  have summable_3: \"(\\<lambda>s::robot_local_state. (if bel\\<^sub>v s = (2::\\<nat>) then 1::\\<real> else (0::\\<real>)) / (6::\\<real>)) \n      summable_on UNIV\"\n    apply (rule summable_on_cdiv_left)\n    apply (rule infsum_constant_finite_states_summable)\n    by (smt (z3) Collect_mono finite.emptyI finite.insertI rev_finite_subset \n      robot_local_state.equality singleton_conv unit.exhaust)\n\n  have sum_1: \"(\\<Sum>\\<^sub>\\<infinity>s::robot_local_state. (if bel\\<^sub>v s = (0::\\<nat>) then 1::\\<real> else (0::\\<real>)) / (6::\\<real>)) = 1/6\"\n    apply (subst infsum_cdiv_left)\n    apply (rule infsum_constant_finite_states_summable)\n    apply (smt (z3) Collect_mono finite.emptyI finite.insertI rev_finite_subset \n      robot_local_state.equality singleton_conv unit.exhaust)\n    apply (subst infsum_constant_finite_states)\n    apply (smt (z3) Collect_mono finite.emptyI finite.insertI rev_finite_subset \n      robot_local_state.equality singleton_conv unit.exhaust)\n    apply (simp)\n    apply (subst card_1_singleton_iff)\n    apply (rule_tac x = \"\\<lparr>bel\\<^sub>v = (0::\\<nat>)\\<rparr>\" in exI)\n    by force\n\n  have sum_2: \"(\\<Sum>\\<^sub>\\<infinity>s::robot_local_state. (2::\\<real>) * (if bel\\<^sub>v s = Suc (0::\\<nat>) then 1::\\<real> else (0::\\<real>)) / (3::\\<real>)) = 2/3\"\n    apply (subst infsum_cdiv_left)\n    apply (rule summable_on_cmult_right)\n    apply (rule infsum_constant_finite_states_summable)\n    apply (smt (z3) Collect_mono finite.emptyI finite.insertI rev_finite_subset \n      robot_local_state.equality singleton_conv unit.exhaust)\n    apply (subst infsum_cmult_right)\n    apply (rule infsum_constant_finite_states_summable)\n    apply (smt (z3) Collect_mono finite.emptyI finite.insertI rev_finite_subset \n      robot_local_state.equality singleton_conv unit.exhaust)\n    apply (subst infsum_constant_finite_states)\n    apply (smt (z3) Collect_mono finite.emptyI finite.insertI rev_finite_subset \n      robot_local_state.equality singleton_conv unit.exhaust)\n    apply (simp)\n    apply (subst card_1_singleton_iff)\n    apply (rule_tac x = \"\\<lparr>bel\\<^sub>v = Suc (0::\\<nat>)\\<rparr>\" in exI)\n    by force\n\n  have sum_3: \"(\\<Sum>\\<^sub>\\<infinity>s::robot_local_state. (if bel\\<^sub>v s = (2::\\<nat>) then 1::\\<real> else (0::\\<real>)) / (6::\\<real>)) = 1/6\"\n    apply (subst infsum_cdiv_left)\n    apply (rule infsum_constant_finite_states_summable)\n    apply (smt (z3) Collect_mono finite.emptyI finite.insertI rev_finite_subset \n      robot_local_state.equality singleton_conv unit.exhaust)\n    apply (subst infsum_constant_finite_states)\n    apply (smt (z3) Collect_mono finite.emptyI finite.insertI rev_finite_subset \n      robot_local_state.equality singleton_conv unit.exhaust)\n    apply (simp)\n    apply (subst card_1_singleton_iff)\n    apply (rule_tac x = \"\\<lparr>bel\\<^sub>v = (2::\\<nat>)\\<rparr>\" in exI)\n  by force\n\n  show ?thesis\n    apply (simp add: move_right_2_def)\n    apply (subst rvfun_inverse)\n    apply (expr_auto add: dist_defs)\n    by (simp)\nqed\n\nsubsection \\<open> Third sensor reading \\<close>\nlemma believe_3_sum: \"(\\<Sum>\\<^sub>\\<infinity>v\\<^sub>0::robot_local_state.\n          (if bel\\<^sub>v v\\<^sub>0 = (0::\\<nat>) then 1::\\<real> else (0::\\<real>)) *\n          ((3::\\<real>) * (if (0::\\<nat>) < bel\\<^sub>v v\\<^sub>0 \\<and> \\<not> bel\\<^sub>v v\\<^sub>0 = (2::\\<nat>) then 1::\\<real> else (0::\\<real>)) + (1::\\<real>)) / (6::\\<real>) \n        +  (2::\\<real>) * (if bel\\<^sub>v v\\<^sub>0 = Suc (0::\\<nat>) then 1::\\<real> else (0::\\<real>)) *\n          ((3::\\<real>) * (if (0::\\<nat>) < bel\\<^sub>v v\\<^sub>0 \\<and> \\<not> bel\\<^sub>v v\\<^sub>0 = (2::\\<nat>) then 1::\\<real> else (0::\\<real>)) + (1::\\<real>)) /\n          (3::\\<real>) +  (if bel\\<^sub>v v\\<^sub>0 = (2::\\<nat>) then 1::\\<real> else (0::\\<real>)) *\n          ((3::\\<real>) * (if (0::\\<nat>) < bel\\<^sub>v v\\<^sub>0 \\<and> \\<not> bel\\<^sub>v v\\<^sub>0 = (2::\\<nat>) then 1::\\<real> else (0::\\<real>)) + (1::\\<real>)) /\n          (6::\\<real>)) = 3\"\n  apply (simp add: ring_distribs(1))\n  apply (subst mult.assoc[symmetric,where b = \"3\"])\n  apply (subst mult.commute[where b = \"3\"])\n  apply (subst mult.assoc)\n  apply (subst mult.assoc[symmetric,where b = \"3\"])\n  apply (subst mult.commute[where b = \"3\"])\n  apply (subst mult.assoc)\n  apply (subst conditional_conds_conj)+\nproof -\n  let ?f1 = \"(\\<lambda>v\\<^sub>0::robot_local_state. \n    ((3::\\<real>) * (if bel\\<^sub>v v\\<^sub>0 = (0::\\<nat>) \\<and> (0::\\<nat>) < bel\\<^sub>v v\\<^sub>0 \\<and> \\<not> bel\\<^sub>v v\\<^sub>0 = (2::\\<nat>) then 1::\\<real> else (0::\\<real>)) +\n        (if bel\\<^sub>v v\\<^sub>0 = (0::\\<nat>) then 1::\\<real> else (0::\\<real>))) / (6::\\<real>))\"\n  let ?f2 = \"(\\<lambda>v\\<^sub>0::robot_local_state. \n    ((6::\\<real>) * (if bel\\<^sub>v v\\<^sub>0 = Suc (0::\\<nat>) \\<and> (0::\\<nat>) < bel\\<^sub>v v\\<^sub>0 \\<and> \\<not> bel\\<^sub>v v\\<^sub>0 = (2::\\<nat>) then 1::\\<real> else (0::\\<real>)) +\n        (2::\\<real>) * (if bel\\<^sub>v v\\<^sub>0 = Suc (0::\\<nat>) then 1::\\<real> else (0::\\<real>))) /\n       (3::\\<real>))\"\n  let ?f3 = \"(\\<lambda>v\\<^sub>0::robot_local_state. \n    ((3::\\<real>) * (if bel\\<^sub>v v\\<^sub>0 = (2::\\<nat>) \\<and> (0::\\<nat>) < bel\\<^sub>v v\\<^sub>0 \\<and> \\<not> bel\\<^sub>v v\\<^sub>0 = (2::\\<nat>) then 1::\\<real> else (0::\\<real>)) +\n        (if bel\\<^sub>v v\\<^sub>0 = (2::\\<nat>) then 1::\\<real> else (0::\\<real>))) /\n       (6::\\<real>))\"\n  have summable_1: \"?f1 summable_on UNIV\"\n    apply (rule summable_on_cdiv_left)\n    apply (rule summable_on_add)\n    apply (rule summable_on_cmult_right)\n    apply (rule infsum_constant_finite_states_summable)\n    apply (smt (verit, ccfv_SIG) Collect_mono finite.emptyI finite.insertI not_finite_existsD \n        rev_finite_subset robot_local_state.equality singleton_conv unit.exhaust)\n    apply (rule infsum_constant_finite_states_summable)\n    by (metis (mono_tags, lifting) card.infinite card_1_singleton nat.simps(3) not_finite_existsD \n        robot_local_state.equality unit.exhaust)\n  have summable_2: \"?f2 summable_on UNIV\"\n    apply (rule summable_on_cdiv_left)\n    apply (rule summable_on_add)\n    apply (rule summable_on_cmult_right)\n    apply (rule infsum_constant_finite_states_summable)\n    apply (smt (verit, ccfv_SIG) Collect_mono finite.emptyI finite.insertI not_finite_existsD \n        rev_finite_subset robot_local_state.equality singleton_conv unit.exhaust)\n    apply (rule summable_on_cmult_right)\n    apply (rule infsum_constant_finite_states_summable)\n    by (metis (mono_tags, lifting) card.infinite card_1_singleton nat.simps(3) not_finite_existsD \n        robot_local_state.equality unit.exhaust)\n  have summable_3: \"?f3 summable_on UNIV\"\n    apply (rule summable_on_cdiv_left)\n    apply (rule summable_on_add)\n    apply (rule summable_on_cmult_right)\n    apply (rule infsum_constant_finite_states_summable)\n    apply (smt (verit, ccfv_SIG) Collect_mono finite.emptyI finite.insertI not_finite_existsD \n        rev_finite_subset robot_local_state.equality singleton_conv unit.exhaust)\n    apply (rule infsum_constant_finite_states_summable)\n    by (metis (mono_tags, lifting) card.infinite card_1_singleton nat.simps(3) not_finite_existsD \n        robot_local_state.equality unit.exhaust)\n\n  have card_1: \"card {s::robot_local_state. bel\\<^sub>v s = 0} = Suc (0)\"\n    apply (subst card_1_singleton_iff)\n    by (smt (verit, del_insts) Collect_cong robot_local_state.equality robot_local_state.select_convs(1) \n      singleton_conv unit.exhaust)\n  have card_2: \"card {s::robot_local_state. bel\\<^sub>v s = Suc (0)} = Suc (0)\"\n    apply (subst card_1_singleton_iff)\n    by (smt (verit, del_insts) Collect_cong robot_local_state.equality robot_local_state.select_convs(1) \n      singleton_conv unit.exhaust)\n  have card_2': \"card {s::robot_local_state. bel\\<^sub>v s = Suc (0::\\<nat>) \\<and> (0::\\<nat>) < bel\\<^sub>v s \\<and> \\<not> bel\\<^sub>v s = (2::\\<nat>)} = Suc 0\"\n    apply (subst card_1_singleton_iff)\n    by (metis (mono_tags, lifting) Collect_cong card_1_singleton_iff card_2 less_Suc0 n_not_Suc_n numeral_2_eq_2)\n  have card_3: \"card {s::robot_local_state. bel\\<^sub>v s = 2} = Suc (0)\"\n    apply (subst card_1_singleton_iff)\n    by (smt (verit, del_insts) Collect_cong robot_local_state.equality robot_local_state.select_convs(1) \n      singleton_conv unit.exhaust)\n  have card_3': \"card {s::robot_local_state. bel\\<^sub>v s = (2::\\<nat>) \\<and> (0::\\<nat>) < bel\\<^sub>v s \\<and> \\<not> bel\\<^sub>v s = (2::\\<nat>)} = 0\"\n    by (simp add: card_0_singleton)\n\n  have f1: \"\\<forall>v\\<^sub>0. \\<not>(bel\\<^sub>v v\\<^sub>0 = (0::\\<nat>) \\<and> (0::\\<nat>) < bel\\<^sub>v v\\<^sub>0 \\<and> \\<not> bel\\<^sub>v v\\<^sub>0 = (2::\\<nat>))\"\n    by auto\n  have sum_1: \"(\\<Sum>\\<^sub>\\<infinity>v\\<^sub>0::robot_local_state. ?f1 v\\<^sub>0) = 1 / 6\"\n    apply (subst infsum_cdiv_left)\n    apply (rule summable_on_add)\n    apply (rule summable_on_cmult_right)\n    apply (rule infsum_constant_finite_states_summable)\n    apply (smt (verit, ccfv_SIG) Collect_mono finite.emptyI finite.insertI not_finite_existsD \n        rev_finite_subset robot_local_state.equality singleton_conv unit.exhaust)\n    apply (rule infsum_constant_finite_states_summable)\n    apply (metis (mono_tags, lifting) card.infinite card_1_singleton nat.simps(3) not_finite_existsD \n        robot_local_state.equality unit.exhaust)\n    apply (simp add: f1)\n    apply (subst infsum_constant_finite_states)\n    apply (metis (mono_tags, lifting) card.infinite card_1_singleton nat.simps(3) not_finite_existsD \n        robot_local_state.equality unit.exhaust)\n    using card_1 by (smt (verit, ccfv_SIG) Collect_cong One_nat_def of_nat_1)\n\n  have sum_2: \"(\\<Sum>\\<^sub>\\<infinity>v\\<^sub>0::robot_local_state. ?f2 v\\<^sub>0) = 8/3\"\n    apply (subst infsum_cdiv_left)\n    apply (rule summable_on_add)\n    apply (rule summable_on_cmult_right)\n    apply (rule infsum_constant_finite_states_summable)\n    apply (smt (verit, ccfv_SIG) Collect_mono finite.emptyI finite.insertI not_finite_existsD \n        rev_finite_subset robot_local_state.equality singleton_conv unit.exhaust)\n    apply (rule summable_on_cmult_right)\n    apply (rule infsum_constant_finite_states_summable)\n    apply (metis (mono_tags, lifting) card.infinite card_1_singleton nat.simps(3) not_finite_existsD \n        robot_local_state.equality unit.exhaust)\n    apply (subst infsum_add)\n    apply (rule summable_on_cmult_right)\n    apply (rule infsum_constant_finite_states_summable)\n    apply (smt (verit, ccfv_SIG) Collect_mono finite.emptyI finite.insertI not_finite_existsD \n        rev_finite_subset robot_local_state.equality singleton_conv unit.exhaust)\n    apply (rule summable_on_cmult_right)\n    apply (rule infsum_constant_finite_states_summable)\n    apply (metis (mono_tags, lifting) card.infinite card_1_singleton nat.simps(3) not_finite_existsD \n        robot_local_state.equality unit.exhaust)\n    apply (subst infsum_cmult_right)\n    apply (rule infsum_constant_finite_states_summable)\n    apply (metis (mono_tags, lifting) card.infinite card_1_singleton nat.simps(3) not_finite_existsD \n        robot_local_state.equality unit.exhaust)\n    apply (subst infsum_cmult_right)\n    apply (rule infsum_constant_finite_states_summable)\n    apply (metis (mono_tags, lifting) card.infinite card_1_singleton nat.simps(3) not_finite_existsD \n        robot_local_state.equality unit.exhaust)\n    apply (subst infsum_constant_finite_states)\n    apply (metis (mono_tags, lifting) card.infinite card_1_singleton nat.simps(3) not_finite_existsD \n        robot_local_state.equality unit.exhaust)\n    apply (subst infsum_constant_finite_states)\n    apply (metis (mono_tags, lifting) card.infinite card_1_singleton nat.simps(3) not_finite_existsD \n        robot_local_state.equality unit.exhaust)\n    by (simp add: card_2 card_2')\n\n  have sum_3: \"(\\<Sum>\\<^sub>\\<infinity>v\\<^sub>0::robot_local_state. ?f3 v\\<^sub>0) = 1 / 6\"\n    apply (subst infsum_cdiv_left)\n    apply (rule summable_on_add)\n    apply (rule summable_on_cmult_right)\n    apply (rule infsum_constant_finite_states_summable)\n    apply (smt (verit, ccfv_SIG) Collect_mono finite.emptyI finite.insertI not_finite_existsD \n        rev_finite_subset robot_local_state.equality singleton_conv unit.exhaust)\n    apply (rule infsum_constant_finite_states_summable)\n    apply (metis (mono_tags, lifting) card.infinite card_1_singleton nat.simps(3) not_finite_existsD \n        robot_local_state.equality unit.exhaust)\n    apply (subst infsum_add)\n    apply (rule summable_on_cmult_right)\n    apply (rule infsum_constant_finite_states_summable)\n    apply (smt (verit, ccfv_SIG) Collect_mono finite.emptyI finite.insertI not_finite_existsD \n        rev_finite_subset robot_local_state.equality singleton_conv unit.exhaust)\n    apply (rule infsum_constant_finite_states_summable)\n    apply (metis (mono_tags, lifting) card.infinite card_1_singleton nat.simps(3) not_finite_existsD \n        robot_local_state.equality unit.exhaust)\n    apply (subst infsum_cmult_right)\n    apply (rule infsum_constant_finite_states_summable)\n    apply (metis (mono_tags, lifting) card.infinite card_1_singleton nat.simps(3) not_finite_existsD \n        robot_local_state.equality unit.exhaust)\n    apply (subst infsum_constant_finite_states)\n    apply (metis (mono_tags, lifting) card.infinite card_1_singleton nat.simps(3) not_finite_existsD \n        robot_local_state.equality unit.exhaust)\n    apply (subst infsum_constant_finite_states)\n    apply (metis (mono_tags, lifting) card.infinite card_1_singleton nat.simps(3) not_finite_existsD \n        robot_local_state.equality unit.exhaust)\n    by (simp add: card_3 card_3')\n\n  show \"(\\<Sum>\\<^sub>\\<infinity>v\\<^sub>0::robot_local_state. ?f1 v\\<^sub>0 + ?f2 v\\<^sub>0 + ?f3 v\\<^sub>0) = 3\"\n    apply (subst infsum_add)\n    apply (rule summable_on_add)\n    using summable_1 apply blast\n    using summable_2 apply blast\n    using summable_3 apply blast\n    apply (subst infsum_add)\n    using summable_1 apply blast\n    using summable_2 apply blast\n    by (simp add: sum_1 sum_2 sum_3)\nqed\n\nlemma believe_3_simp: \"robot_localisation = prfun_of_rvfun believe_3\"\n  apply (simp add: robot_localisation_def)\n  apply (simp add: move_right_2_simp believe_3_def)\n  apply (simp add: scale_wall_def door_def pfun_defs)\n  apply (simp add: move_right_2_dist)\n  apply (simp add: move_right_2_def dist_defs)\n  apply (expr_simp_1)\n  apply (rule HOL.arg_cong[where f=\"prfun_of_rvfun\"])\n  apply (simp add: ring_distribs(2))\n  apply (subst fun_eq_iff, rule allI)\n  apply (auto)\n  by (simp add: believe_3_sum)+\n\nlemma robot_localisation: \"\n    (((   init \\<parallel> scale_door) ; \n    move_right \\<parallel> scale_door) ; \n    move_right \\<parallel> scale_wall)\n  = \n    prfun_of_rvfun (\n      1/18 * \\<lbrakk>bel\\<^sup>> = 0\\<rbrakk>\\<^sub>\\<I>\\<^sub>e + \n      8/9  * \\<lbrakk>bel\\<^sup>> = 1\\<rbrakk>\\<^sub>\\<I>\\<^sub>e + \n      1/18 * \\<lbrakk>bel\\<^sup>> = 2\\<rbrakk>\\<^sub>\\<I>\\<^sub>e\n    )\\<^sub>e\"\n  apply (simp add: robot_localisation_def)\n  apply (simp add: move_right_2_simp believe_3_def)\n  apply (simp add: scale_wall_def door_def pfun_defs)\n  apply (simp add: move_right_2_dist)\n  apply (simp add: move_right_2_def dist_defs)\n  apply (expr_simp_1)\n  apply (rule HOL.arg_cong[where f=\"prfun_of_rvfun\"])\n  apply (simp add: ring_distribs(2))\n  apply (subst fun_eq_iff, rule allI)\n  apply (auto)\n  by (simp add: believe_3_sum)+\n\nlemma robot_localisation': \"\n  ((((init \\<parallel> scale_door) ; move_right) \\<parallel> scale_door) ; move_right) \\<parallel> scale_wall \n  = prfun_of_rvfun (1/18 * \\<lbrakk>bel\\<^sup>> = 0\\<rbrakk>\\<^sub>\\<I>\\<^sub>e + 8/9 * \\<lbrakk>bel\\<^sup>> = 1\\<rbrakk>\\<^sub>\\<I>\\<^sub>e + 1/18 * \\<lbrakk>bel\\<^sup>> = 2\\<rbrakk>\\<^sub>\\<I>\\<^sub>e)\\<^sub>e\"\n  using believe_3_def believe_3_simp robot_localisation_def by presburger\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/utp_prob_rel_lattice_robot_localisation.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8840392695254319, "lm_q2_score": 0.7956581097540519, "lm_q1q2_score": 0.7033930141389579}}
{"text": "(* Author: Manuel Eberl *)\n\nsection {* Abstract euclidean algorithm *}\n\ntheory Euclidean_Algorithm\nimports Complex_Main\nbegin\n\ncontext semiring_div\nbegin \n\nabbreviation is_unit :: \"'a \\<Rightarrow> bool\"\nwhere\n  \"is_unit x \\<equiv> x dvd 1\"\n\ndefinition associated :: \"'a \\<Rightarrow> 'a \\<Rightarrow> bool\" \nwhere\n  \"associated x y \\<longleftrightarrow> x dvd y \\<and> y dvd x\"\n\ndefinition ring_inv :: \"'a \\<Rightarrow> 'a\"\nwhere\n  \"ring_inv x = 1 div x\"\n\nlemma unit_prod [intro]:\n  \"is_unit x \\<Longrightarrow> is_unit y \\<Longrightarrow> is_unit (x * y)\"\n  by (subst mult_1_left [of 1, symmetric], rule mult_dvd_mono) \n\nlemma unit_ring_inv:\n  \"is_unit y \\<Longrightarrow> x div y = x * ring_inv y\"\n  by (simp add: div_mult_swap ring_inv_def)\n\nlemma unit_ring_inv_ring_inv [simp]:\n  \"is_unit x \\<Longrightarrow> ring_inv (ring_inv x) = x\"\n  unfolding ring_inv_def\n  by (metis div_mult_mult1_if div_mult_self1_is_id dvd_mult_div_cancel mult_1_right)\n\nlemma inv_imp_eq_ring_inv:\n  \"a * b = 1 \\<Longrightarrow> ring_inv a = b\"\n  by (metis dvd_mult_div_cancel dvd_mult_right mult_1_right mult.left_commute one_dvd ring_inv_def)\n\nlemma ring_inv_is_inv1 [simp]:\n  \"is_unit a \\<Longrightarrow> a * ring_inv a = 1\"\n  unfolding ring_inv_def by simp\n\nlemma ring_inv_is_inv2 [simp]:\n  \"is_unit a \\<Longrightarrow> ring_inv a * a = 1\"\n  by (simp add: ac_simps)\n\nlemma unit_ring_inv_unit [simp, intro]:\n  assumes \"is_unit x\"\n  shows \"is_unit (ring_inv x)\"\nproof -\n  from assms have \"1 = ring_inv x * x\" by simp\n  then show \"is_unit (ring_inv x)\" by (rule dvdI)\nqed\n\nlemma mult_unit_dvd_iff:\n  \"is_unit y \\<Longrightarrow> x * y dvd z \\<longleftrightarrow> x dvd z\"\nproof\n  assume \"is_unit y\" \"x * y dvd z\"\n  then show \"x dvd z\" by (simp add: dvd_mult_left)\nnext\n  assume \"is_unit y\" \"x dvd z\"\n  then obtain k where \"z = x * k\" unfolding dvd_def by blast\n  with `is_unit y` have \"z = (x * y) * (ring_inv y * k)\" \n      by (simp add: mult_ac)\n  then show \"x * y dvd z\" by (rule dvdI)\nqed\n\nlemma div_unit_dvd_iff:\n  \"is_unit y \\<Longrightarrow> x div y dvd z \\<longleftrightarrow> x dvd z\"\n  by (subst unit_ring_inv) (assumption, simp add: mult_unit_dvd_iff)\n\nlemma dvd_mult_unit_iff:\n  \"is_unit y \\<Longrightarrow> x dvd z * y \\<longleftrightarrow> x dvd z\"\nproof\n  assume \"is_unit y\" and \"x dvd z * y\"\n  have \"z * y dvd z * (y * ring_inv y)\" by (subst mult_assoc [symmetric]) simp\n  also from `is_unit y` have \"y * ring_inv y = 1\" by simp\n  finally have \"z * y dvd z\" by simp\n  with `x dvd z * y` show \"x dvd z\" by (rule dvd_trans)\nnext\n  assume \"x dvd z\"\n  then show \"x dvd z * y\" by simp\nqed\n\nlemma dvd_div_unit_iff:\n  \"is_unit y \\<Longrightarrow> x dvd z div y \\<longleftrightarrow> x dvd z\"\n  by (subst unit_ring_inv) (assumption, simp add: dvd_mult_unit_iff)\n\nlemmas unit_dvd_iff = mult_unit_dvd_iff div_unit_dvd_iff dvd_mult_unit_iff dvd_div_unit_iff\n\nlemma unit_div [intro]:\n  \"is_unit x \\<Longrightarrow> is_unit y \\<Longrightarrow> is_unit (x div y)\"\n  by (subst unit_ring_inv) (assumption, rule unit_prod, simp_all)\n\nlemma unit_div_mult_swap:\n  \"is_unit z \\<Longrightarrow> x * (y div z) = x * y div z\"\n  by (simp only: unit_ring_inv [of _ y] unit_ring_inv [of _ \"x*y\"] ac_simps)\n\nlemma unit_div_commute:\n  \"is_unit y \\<Longrightarrow> x div y * z = x * z div y\"\n  by (simp only: unit_ring_inv [of _ x] unit_ring_inv [of _ \"x*z\"] ac_simps)\n\nlemma unit_imp_dvd [dest]:\n  \"is_unit y \\<Longrightarrow> y dvd x\"\n  by (rule dvd_trans [of _ 1]) simp_all\n\nlemma dvd_unit_imp_unit:\n  \"is_unit y \\<Longrightarrow> x dvd y \\<Longrightarrow> is_unit x\"\n  by (rule dvd_trans)\n\nlemma ring_inv_0 [simp]:\n  \"ring_inv 0 = 0\"\n  unfolding ring_inv_def by simp\n\nlemma unit_ring_inv'1:\n  assumes \"is_unit y\"\n  shows \"x div (y * z) = x * ring_inv y div z\" \nproof -\n  from assms have \"x div (y * z) = x * (ring_inv y * y) div (y * z)\"\n    by simp\n  also have \"... = y * (x * ring_inv y) div (y * z)\"\n    by (simp only: mult_ac)\n  also have \"... = x * ring_inv y div z\"\n    by (cases \"y = 0\", simp, rule div_mult_mult1)\n  finally show ?thesis .\nqed\n\nlemma associated_comm:\n  \"associated x y \\<Longrightarrow> associated y x\"\n  by (simp add: associated_def)\n\nlemma associated_0 [simp]:\n  \"associated 0 b \\<longleftrightarrow> b = 0\"\n  \"associated a 0 \\<longleftrightarrow> a = 0\"\n  unfolding associated_def by simp_all\n\nlemma associated_unit:\n  \"is_unit x \\<Longrightarrow> associated x y \\<Longrightarrow> is_unit y\"\n  unfolding associated_def using dvd_unit_imp_unit by auto\n\nlemma is_unit_1 [simp]:\n  \"is_unit 1\"\n  by simp\n\nlemma not_is_unit_0 [simp]:\n  \"\\<not> is_unit 0\"\n  by auto\n\nlemma unit_mult_left_cancel:\n  assumes \"is_unit x\"\n  shows \"(x * y) = (x * z) \\<longleftrightarrow> y = z\"\nproof -\n  from assms have \"x \\<noteq> 0\" by auto\n  then show ?thesis by (metis div_mult_self1_is_id)\nqed\n\n\n\nlemma unit_div_cancel:\n  \"is_unit x \\<Longrightarrow> (y div x) = (z div x) \\<longleftrightarrow> y = z\"\n  apply (subst unit_ring_inv[of _ y], assumption)\n  apply (subst unit_ring_inv[of _ z], assumption)\n  apply (rule unit_mult_right_cancel, erule unit_ring_inv_unit)\n  done\n\nlemma unit_eq_div1:\n  \"is_unit y \\<Longrightarrow> x div y = z \\<longleftrightarrow> x = z * y\"\n  apply (subst unit_ring_inv, assumption)\n  apply (subst unit_mult_right_cancel[symmetric], assumption)\n  apply (subst mult_assoc, subst ring_inv_is_inv2, assumption, simp)\n  done\n\nlemma unit_eq_div2:\n  \"is_unit y \\<Longrightarrow> x = z div y \\<longleftrightarrow> x * y = z\"\n  by (subst (1 2) eq_commute, simp add: unit_eq_div1, subst eq_commute, rule refl)\n\nlemma associated_iff_div_unit:\n  \"associated x y \\<longleftrightarrow> (\\<exists>z. is_unit z \\<and> x = z * y)\"\nproof\n  assume \"associated x y\"\n  show \"\\<exists>z. is_unit z \\<and> x = z * y\"\n  proof (cases \"x = 0\")\n    assume \"x = 0\"\n    then show \"\\<exists>z. is_unit z \\<and> x = z * y\" using `associated x y`\n        by (intro exI[of _ 1], simp add: associated_def)\n  next\n    assume [simp]: \"x \\<noteq> 0\"\n    hence [simp]: \"x dvd y\" \"y dvd x\" using `associated x y`\n        unfolding associated_def by simp_all\n    hence \"1 = x div y * (y div x)\"\n      by (simp add: div_mult_swap)\n    hence \"is_unit (x div y)\" ..\n    moreover have \"x = (x div y) * y\" by simp\n    ultimately show ?thesis by blast\n  qed\nnext\n  assume \"\\<exists>z. is_unit z \\<and> x = z * y\"\n  then obtain z where \"is_unit z\" and \"x = z * y\" by blast\n  hence \"y = x * ring_inv z\" by (simp add: algebra_simps)\n  hence \"x dvd y\" by simp\n  moreover from `x = z * y` have \"y dvd x\" by simp\n  ultimately show \"associated x y\" unfolding associated_def by simp\nqed\n\nlemmas unit_simps = mult_unit_dvd_iff div_unit_dvd_iff dvd_mult_unit_iff \n  dvd_div_unit_iff unit_div_mult_swap unit_div_commute\n  unit_mult_left_cancel unit_mult_right_cancel unit_div_cancel \n  unit_eq_div1 unit_eq_div2\n\nend\n\ncontext ring_div\nbegin\n\nlemma is_unit_neg [simp]:\n  \"is_unit (- x) \\<Longrightarrow> is_unit x\"\n  by simp\n\nlemma is_unit_neg_1 [simp]:\n  \"is_unit (-1)\"\n  by simp\n\nend\n\nlemma is_unit_nat [simp]:\n  \"is_unit (x::nat) \\<longleftrightarrow> x = 1\"\n  by simp\n\nlemma is_unit_int:\n  \"is_unit (x::int) \\<longleftrightarrow> x = 1 \\<or> x = -1\"\n  by auto\n\ntext {*\n  A Euclidean semiring is a semiring upon which the Euclidean algorithm can be\n  implemented. It must provide:\n  \\begin{itemize}\n  \\item division with remainder\n  \\item a size function such that @{term \"size (a mod b) < size b\"} \n        for any @{term \"b \\<noteq> 0\"}\n  \\item a normalisation factor such that two associated numbers are equal iff \n        they are the same when divided by their normalisation factors.\n  \\end{itemize}\n  The existence of these functions makes it possible to derive gcd and lcm functions \n  for any Euclidean semiring.\n*} \nclass euclidean_semiring = semiring_div + \n  fixes euclidean_size :: \"'a \\<Rightarrow> nat\"\n  fixes normalisation_factor :: \"'a \\<Rightarrow> 'a\"\n  assumes mod_size_less [simp]: \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 * b) \\<ge> euclidean_size a\"\n  assumes normalisation_factor_is_unit [intro,simp]: \n    \"a \\<noteq> 0 \\<Longrightarrow> is_unit (normalisation_factor a)\"\n  assumes normalisation_factor_mult: \"normalisation_factor (a * b) = \n    normalisation_factor a * normalisation_factor b\"\n  assumes normalisation_factor_unit: \"is_unit x \\<Longrightarrow> normalisation_factor x = x\"\n  assumes normalisation_factor_0 [simp]: \"normalisation_factor 0 = 0\"\nbegin\n\nlemma normalisation_factor_dvd [simp]:\n  \"a \\<noteq> 0 \\<Longrightarrow> normalisation_factor a dvd b\"\n  by (rule unit_imp_dvd, simp)\n    \nlemma normalisation_factor_1 [simp]:\n  \"normalisation_factor 1 = 1\"\n  by (simp add: normalisation_factor_unit)\n\nlemma normalisation_factor_0_iff [simp]:\n  \"normalisation_factor x = 0 \\<longleftrightarrow> x = 0\"\nproof\n  assume \"normalisation_factor x = 0\"\n  hence \"\\<not> is_unit (normalisation_factor x)\"\n    by (metis not_is_unit_0)\n  then show \"x = 0\" by force\nnext\n  assume \"x = 0\"\n  then show \"normalisation_factor x = 0\" by simp\nqed\n\nlemma normalisation_factor_pow:\n  \"normalisation_factor (x ^ n) = normalisation_factor x ^ n\"\n  by (induct n) (simp_all add: normalisation_factor_mult power_Suc2)\n\nlemma normalisation_correct [simp]:\n  \"normalisation_factor (x div normalisation_factor x) = (if x = 0 then 0 else 1)\"\nproof (cases \"x = 0\", simp)\n  assume \"x \\<noteq> 0\"\n  let ?nf = \"normalisation_factor\"\n  from normalisation_factor_is_unit[OF `x \\<noteq> 0`] have \"?nf x \\<noteq> 0\"\n    by (metis not_is_unit_0) \n  have \"?nf (x div ?nf x) * ?nf (?nf x) = ?nf (x div ?nf x * ?nf x)\" \n    by (simp add: normalisation_factor_mult)\n  also have \"x div ?nf x * ?nf x = x\" using `x \\<noteq> 0`\n    by simp\n  also have \"?nf (?nf x) = ?nf x\" using `x \\<noteq> 0` \n    normalisation_factor_is_unit normalisation_factor_unit by simp\n  finally show ?thesis using `x \\<noteq> 0` and `?nf x \\<noteq> 0` \n    by (metis div_mult_self2_is_id div_self)\nqed\n\nlemma normalisation_0_iff [simp]:\n  \"x div normalisation_factor x = 0 \\<longleftrightarrow> x = 0\"\n  by (cases \"x = 0\", simp, subst unit_eq_div1, blast, simp)\n\nlemma associated_iff_normed_eq:\n  \"associated a b \\<longleftrightarrow> a div normalisation_factor a = b div normalisation_factor b\"\nproof (cases \"b = 0\", simp, cases \"a = 0\", metis associated_0(1) normalisation_0_iff, rule iffI)\n  let ?nf = normalisation_factor\n  assume \"a \\<noteq> 0\" \"b \\<noteq> 0\" \"a div ?nf a = b div ?nf b\"\n  hence \"a = b * (?nf a div ?nf b)\"\n    apply (subst (asm) unit_eq_div1, blast, subst (asm) unit_div_commute, blast)\n    apply (subst div_mult_swap, simp, simp)\n    done\n  with `a \\<noteq> 0` `b \\<noteq> 0` have \"\\<exists>z. is_unit z \\<and> a = z * b\"\n    by (intro exI[of _ \"?nf a div ?nf b\"], force simp: mult_ac)\n  with associated_iff_div_unit show \"associated a b\" by simp\nnext\n  let ?nf = normalisation_factor\n  assume \"a \\<noteq> 0\" \"b \\<noteq> 0\" \"associated a b\"\n  with associated_iff_div_unit obtain z where \"is_unit z\" and \"a = z * b\" by blast\n  then show \"a div ?nf a = b div ?nf b\"\n    apply (simp only: `a = z * b` normalisation_factor_mult normalisation_factor_unit)\n    apply (rule div_mult_mult1, force)\n    done\n  qed\n\nlemma normed_associated_imp_eq:\n  \"associated a b \\<Longrightarrow> normalisation_factor a \\<in> {0, 1} \\<Longrightarrow> normalisation_factor b \\<in> {0, 1} \\<Longrightarrow> a = b\"\n  by (simp add: associated_iff_normed_eq, elim disjE, simp_all)\n    \nlemmas normalisation_factor_dvd_iff [simp] =\n  unit_dvd_iff [OF normalisation_factor_is_unit]\n\nlemma euclidean_division:\n  fixes a :: 'a and b :: 'a\n  assumes \"b \\<noteq> 0\"\n  obtains s and t where \"a = s * b + t\" \n    and \"euclidean_size t < euclidean_size b\"\nproof -\n  from div_mod_equality[of a b 0] \n     have \"a = a div b * b + a mod b\" by simp\n  with that and assms show ?thesis by force\nqed\n\nlemma dvd_euclidean_size_eq_imp_dvd:\n  assumes \"a \\<noteq> 0\" and b_dvd_a: \"b dvd a\" and size_eq: \"euclidean_size a = euclidean_size b\"\n  shows \"a dvd b\"\nproof (subst dvd_eq_mod_eq_0, rule ccontr)\n  assume \"b mod a \\<noteq> 0\"\n  from b_dvd_a have b_dvd_mod: \"b dvd b mod a\" by (simp add: dvd_mod_iff)\n  from b_dvd_mod obtain c where \"b mod a = b * c\" unfolding dvd_def by blast\n    with `b mod a \\<noteq> 0` have \"c \\<noteq> 0\" by auto\n  with `b mod a = b * c` have \"euclidean_size (b mod a) \\<ge> euclidean_size b\"\n      using size_mult_mono by force\n  moreover from `a \\<noteq> 0` have \"euclidean_size (b mod a) < euclidean_size a\"\n      using mod_size_less by blast\n  ultimately show False using size_eq by simp\nqed\n\nfunction gcd_eucl :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a\"\nwhere\n  \"gcd_eucl a b = (if b = 0 then a div normalisation_factor a else gcd_eucl b (a mod b))\"\n  by (pat_completeness, simp)\ntermination by (relation \"measure (euclidean_size \\<circ> snd)\", simp_all)\n\ndeclare gcd_eucl.simps [simp del]\n\nlemma gcd_induct: \"\\<lbrakk>\\<And>b. P b 0; \\<And>a b. 0 \\<noteq> b \\<Longrightarrow> P b (a mod b) \\<Longrightarrow> P a b\\<rbrakk> \\<Longrightarrow> P a b\"\nproof (induct a b rule: gcd_eucl.induct)\n  case (\"1\" m n)\n    then show ?case by (cases \"n = 0\") auto\nqed\n\ndefinition lcm_eucl :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a\"\nwhere\n  \"lcm_eucl a b = a * b div (gcd_eucl a b * normalisation_factor (a * b))\"\n\n  (* Somewhat complicated definition of Lcm that has the advantage of working\n     for infinite sets as well *)\n\ndefinition Lcm_eucl :: \"'a set \\<Rightarrow> 'a\"\nwhere\n  \"Lcm_eucl A = (if \\<exists>l. l \\<noteq> 0 \\<and> (\\<forall>x\\<in>A. x dvd l) then\n     let l = SOME l. l \\<noteq> 0 \\<and> (\\<forall>x\\<in>A. x dvd l) \\<and> euclidean_size l =\n       (LEAST n. \\<exists>l. l \\<noteq> 0 \\<and> (\\<forall>x\\<in>A. x dvd l) \\<and> euclidean_size l = n)\n       in l div normalisation_factor l\n      else 0)\"\n\ndefinition Gcd_eucl :: \"'a set \\<Rightarrow> 'a\"\nwhere\n  \"Gcd_eucl A = Lcm_eucl {d. \\<forall>a\\<in>A. d dvd a}\"\n\nend\n\nclass euclidean_semiring_gcd = euclidean_semiring + gcd + Gcd +\n  assumes gcd_gcd_eucl: \"gcd = gcd_eucl\" and lcm_lcm_eucl: \"lcm = lcm_eucl\"\n  assumes Gcd_Gcd_eucl: \"Gcd = Gcd_eucl\" and Lcm_Lcm_eucl: \"Lcm = Lcm_eucl\"\nbegin\n\nlemma gcd_red:\n  \"gcd x y = gcd y (x mod y)\"\n  by (metis gcd_eucl.simps mod_0 mod_by_0 gcd_gcd_eucl)\n\nlemma gcd_non_0:\n  \"y \\<noteq> 0 \\<Longrightarrow> gcd x y = gcd y (x mod y)\"\n  by (rule gcd_red)\n\nlemma gcd_0_left:\n  \"gcd 0 x = x div normalisation_factor x\"\n   by (simp only: gcd_gcd_eucl, subst gcd_eucl.simps, subst gcd_eucl.simps, simp add: Let_def)\n\nlemma gcd_0:\n  \"gcd x 0 = x div normalisation_factor x\"\n  by (simp only: gcd_gcd_eucl, subst gcd_eucl.simps, simp add: Let_def)\n\nlemma gcd_dvd1 [iff]: \"gcd x y dvd x\"\n  and gcd_dvd2 [iff]: \"gcd x y dvd y\"\nproof (induct x y rule: gcd_eucl.induct)\n  fix x y :: 'a\n  assume IH1: \"y \\<noteq> 0 \\<Longrightarrow> gcd y (x mod y) dvd y\"\n  assume IH2: \"y \\<noteq> 0 \\<Longrightarrow> gcd y (x mod y) dvd (x mod y)\"\n  \n  have \"gcd x y dvd x \\<and> gcd x y dvd y\"\n  proof (cases \"y = 0\")\n    case True\n      then show ?thesis by (cases \"x = 0\", simp_all add: gcd_0)\n  next\n    case False\n      with IH1 and IH2 show ?thesis by (simp add: gcd_non_0 dvd_mod_iff)\n  qed\n  then show \"gcd x y dvd x\" \"gcd x y dvd y\" by simp_all\nqed\n\nlemma dvd_gcd_D1: \"k dvd gcd m n \\<Longrightarrow> k dvd m\"\n  by (rule dvd_trans, assumption, rule gcd_dvd1)\n\nlemma dvd_gcd_D2: \"k dvd gcd m n \\<Longrightarrow> k dvd n\"\n  by (rule dvd_trans, assumption, rule gcd_dvd2)\n\nlemma gcd_greatest:\n  fixes k x y :: 'a\n  shows \"k dvd x \\<Longrightarrow> k dvd y \\<Longrightarrow> k dvd gcd x y\"\nproof (induct x y rule: gcd_eucl.induct)\n  case (1 x y)\n  show ?case\n    proof (cases \"y = 0\")\n      assume \"y = 0\"\n      with 1 show ?thesis by (cases \"x = 0\", simp_all add: gcd_0)\n    next\n      assume \"y \\<noteq> 0\"\n      with 1 show ?thesis by (simp add: gcd_non_0 dvd_mod_iff) \n    qed\nqed\n\nlemma dvd_gcd_iff:\n  \"k dvd gcd x y \\<longleftrightarrow> k dvd x \\<and> k dvd y\"\n  by (blast intro!: gcd_greatest intro: dvd_trans)\n\nlemmas gcd_greatest_iff = dvd_gcd_iff\n\nlemma gcd_zero [simp]:\n  \"gcd x y = 0 \\<longleftrightarrow> x = 0 \\<and> y = 0\"\n  by (metis dvd_0_left dvd_refl gcd_dvd1 gcd_dvd2 gcd_greatest)+\n\nlemma normalisation_factor_gcd [simp]:\n  \"normalisation_factor (gcd x y) = (if x = 0 \\<and> y = 0 then 0 else 1)\" (is \"?f x y = ?g x y\")\nproof (induct x y rule: gcd_eucl.induct)\n  fix x y :: 'a\n  assume IH: \"y \\<noteq> 0 \\<Longrightarrow> ?f y (x mod y) = ?g y (x mod y)\"\n  then show \"?f x y = ?g x y\" by (cases \"y = 0\", auto simp: gcd_non_0 gcd_0)\nqed\n\nlemma gcdI:\n  \"k dvd x \\<Longrightarrow> k dvd y \\<Longrightarrow> (\\<And>l. l dvd x \\<Longrightarrow> l dvd y \\<Longrightarrow> l dvd k)\n    \\<Longrightarrow> normalisation_factor k = (if k = 0 then 0 else 1) \\<Longrightarrow> k = gcd x y\"\n  by (intro normed_associated_imp_eq) (auto simp: associated_def intro: gcd_greatest)\n\nsublocale gcd!: abel_semigroup gcd\nproof\n  fix x y z \n  show \"gcd (gcd x y) z = gcd x (gcd y z)\"\n  proof (rule gcdI)\n    have \"gcd (gcd x y) z dvd gcd x y\" \"gcd x y dvd x\" by simp_all\n    then show \"gcd (gcd x y) z dvd x\" by (rule dvd_trans)\n    have \"gcd (gcd x y) z dvd gcd x y\" \"gcd x y dvd y\" by simp_all\n    hence \"gcd (gcd x y) z dvd y\" by (rule dvd_trans)\n    moreover have \"gcd (gcd x y) z dvd z\" by simp\n    ultimately show \"gcd (gcd x y) z dvd gcd y z\"\n      by (rule gcd_greatest)\n    show \"normalisation_factor (gcd (gcd x y) z) =  (if gcd (gcd x y) z = 0 then 0 else 1)\"\n      by auto\n    fix l assume \"l dvd x\" and \"l dvd gcd y z\"\n    with dvd_trans[OF _ gcd_dvd1] and dvd_trans[OF _ gcd_dvd2]\n      have \"l dvd y\" and \"l dvd z\" by blast+\n    with `l dvd x` show \"l dvd gcd (gcd x y) z\"\n      by (intro gcd_greatest)\n  qed\nnext\n  fix x y\n  show \"gcd x y = gcd y x\"\n    by (rule gcdI) (simp_all add: gcd_greatest)\nqed\n\nlemma gcd_unique: \"d dvd a \\<and> d dvd b \\<and> \n    normalisation_factor d = (if d = 0 then 0 else 1) \\<and>\n    (\\<forall>e. e dvd a \\<and> e dvd b \\<longrightarrow> e dvd d) \\<longleftrightarrow> d = gcd a b\"\n  by (rule, auto intro: gcdI simp: gcd_greatest)\n\nlemma gcd_dvd_prod: \"gcd a b dvd k * b\"\n  using mult_dvd_mono [of 1] by auto\n\nlemma gcd_1_left [simp]: \"gcd 1 x = 1\"\n  by (rule sym, rule gcdI, simp_all)\n\nlemma gcd_1 [simp]: \"gcd x 1 = 1\"\n  by (rule sym, rule gcdI, simp_all)\n\nlemma gcd_proj2_if_dvd: \n  \"y dvd x \\<Longrightarrow> gcd x y = y div normalisation_factor y\"\n  by (cases \"y = 0\", simp_all add: dvd_eq_mod_eq_0 gcd_non_0 gcd_0)\n\nlemma gcd_proj1_if_dvd: \n  \"x dvd y \\<Longrightarrow> gcd x y = x div normalisation_factor x\"\n  by (subst gcd.commute, simp add: gcd_proj2_if_dvd)\n\nlemma gcd_proj1_iff: \"gcd m n = m div normalisation_factor m \\<longleftrightarrow> m dvd n\"\nproof\n  assume A: \"gcd m n = m div normalisation_factor m\"\n  show \"m dvd n\"\n  proof (cases \"m = 0\")\n    assume [simp]: \"m \\<noteq> 0\"\n    from A have B: \"m = gcd m n * normalisation_factor m\"\n      by (simp add: unit_eq_div2)\n    show ?thesis by (subst B, simp add: mult_unit_dvd_iff)\n  qed (insert A, simp)\nnext\n  assume \"m dvd n\"\n  then show \"gcd m n = m div normalisation_factor m\" by (rule gcd_proj1_if_dvd)\nqed\n  \nlemma gcd_proj2_iff: \"gcd m n = n div normalisation_factor n \\<longleftrightarrow> n dvd m\"\n  by (subst gcd.commute, simp add: gcd_proj1_iff)\n\nlemma gcd_mod1 [simp]:\n  \"gcd (x mod y) y = gcd x y\"\n  by (rule gcdI, metis dvd_mod_iff gcd_dvd1 gcd_dvd2, simp_all add: gcd_greatest dvd_mod_iff)\n\nlemma gcd_mod2 [simp]:\n  \"gcd x (y mod x) = gcd x y\"\n  by (rule gcdI, simp, metis dvd_mod_iff gcd_dvd1 gcd_dvd2, simp_all add: gcd_greatest dvd_mod_iff)\n         \nlemma normalisation_factor_dvd' [simp]:\n  \"normalisation_factor x dvd x\"\n  by (cases \"x = 0\", simp_all)\n\nlemma gcd_mult_distrib': \n  \"k div normalisation_factor k * gcd x y = gcd (k*x) (k*y)\"\nproof (induct x y rule: gcd_eucl.induct)\n  case (1 x y)\n  show ?case\n  proof (cases \"y = 0\")\n    case True\n    then show ?thesis by (simp add: normalisation_factor_mult gcd_0 algebra_simps div_mult_div_if_dvd)\n  next\n    case False\n    hence \"k div normalisation_factor k * gcd x y =  gcd (k * y) (k * (x mod y))\" \n      using 1 by (subst gcd_red, simp)\n    also have \"... = gcd (k * x) (k * y)\"\n      by (simp add: mult_mod_right gcd.commute)\n    finally show ?thesis .\n  qed\nqed\n\nlemma gcd_mult_distrib:\n  \"k * gcd x y = gcd (k*x) (k*y) * normalisation_factor k\"\nproof-\n  let ?nf = \"normalisation_factor\"\n  from gcd_mult_distrib' \n    have \"gcd (k*x) (k*y) = k div ?nf k * gcd x y\" ..\n  also have \"... = k * gcd x y div ?nf k\"\n    by (metis dvd_div_mult dvd_eq_mod_eq_0 mod_0 normalisation_factor_dvd)\n  finally show ?thesis\n    by simp\nqed\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   have \"gcd a b dvd a\" by (rule gcd_dvd1)\n   then obtain c where A: \"a = gcd a b * c\" unfolding dvd_def by blast\n   with `a \\<noteq> 0` show ?thesis by (subst (2) A, intro size_mult_mono) auto\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 `a \\<noteq> 0` have \"euclidean_size (gcd a b) = euclidean_size a\"\n    by (intro le_antisym, simp_all)\n  with assms have \"a dvd gcd a b\" by (auto intro: dvd_euclidean_size_eq_imp_dvd)\n  hence \"a dvd b\" using dvd_gcd_D2 by blast\n  with `\\<not>a dvd b` 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 gcd_mult_unit1: \"is_unit a \\<Longrightarrow> gcd (x*a) y = gcd x y\"\n  apply (rule gcdI)\n  apply (rule dvd_trans, rule gcd_dvd1, simp add: unit_simps)\n  apply (rule gcd_dvd2)\n  apply (rule gcd_greatest, simp add: unit_simps, assumption)\n  apply (subst normalisation_factor_gcd, simp add: gcd_0)\n  done\n\nlemma gcd_mult_unit2: \"is_unit a \\<Longrightarrow> gcd x (y*a) = gcd x y\"\n  by (subst gcd.commute, subst gcd_mult_unit1, assumption, rule gcd.commute)\n\nlemma gcd_div_unit1: \"is_unit a \\<Longrightarrow> gcd (x div a) y = gcd x y\"\n  by (simp add: unit_ring_inv gcd_mult_unit1)\n\nlemma gcd_div_unit2: \"is_unit a \\<Longrightarrow> gcd x (y div a) = gcd x y\"\n  by (simp add: unit_ring_inv gcd_mult_unit2)\n\nlemma gcd_idem: \"gcd x x = x div normalisation_factor x\"\n  by (cases \"x = 0\") (simp add: gcd_0_left, rule sym, rule gcdI, simp_all)\n\nlemma gcd_right_idem: \"gcd (gcd p q) q = gcd p q\"\n  apply (rule gcdI)\n  apply (simp add: ac_simps)\n  apply (rule gcd_dvd2)\n  apply (rule gcd_greatest, erule (1) gcd_greatest, assumption)\n  apply simp\n  done\n\nlemma gcd_left_idem: \"gcd p (gcd p q) = gcd p q\"\n  apply (rule gcdI)\n  apply simp\n  apply (rule dvd_trans, rule gcd_dvd2, rule gcd_dvd2)\n  apply (rule gcd_greatest, assumption, erule gcd_greatest, assumption)\n  apply simp\n  done\n\nlemma comp_fun_idem_gcd: \"comp_fun_idem gcd\"\nproof\n  fix a b show \"gcd a \\<circ> gcd b = gcd b \\<circ> gcd a\"\n    by (simp add: fun_eq_iff ac_simps)\nnext\n  fix a show \"gcd a \\<circ> gcd a = gcd a\"\n    by (simp add: fun_eq_iff gcd_left_idem)\nqed\n\nlemma coprime_dvd_mult:\n  assumes \"gcd k n = 1\" and \"k dvd m * n\"\n  shows \"k dvd m\"\nproof -\n  let ?nf = \"normalisation_factor\"\n  from assms gcd_mult_distrib [of m k n] \n    have A: \"m = gcd (m * k) (m * n) * ?nf m\" by simp\n  from `k dvd m * n` show ?thesis by (subst A, simp_all add: gcd_greatest)\nqed\n\nlemma coprime_dvd_mult_iff:\n  \"gcd k n = 1 \\<Longrightarrow> (k dvd m * n) = (k dvd m)\"\n  by (rule, rule coprime_dvd_mult, simp_all)\n\nlemma gcd_dvd_antisym:\n  \"gcd a b dvd gcd c d \\<Longrightarrow> gcd c d dvd gcd a b \\<Longrightarrow> gcd a b = gcd c d\"\nproof (rule gcdI)\n  assume A: \"gcd a b dvd gcd c d\" and B: \"gcd c d dvd gcd a b\"\n  have \"gcd c d dvd c\" by simp\n  with A show \"gcd a b dvd c\" by (rule dvd_trans)\n  have \"gcd c d dvd d\" by simp\n  with A show \"gcd a b dvd d\" by (rule dvd_trans)\n  show \"normalisation_factor (gcd a b) = (if gcd a b = 0 then 0 else 1)\"\n    by simp\n  fix l assume \"l dvd c\" and \"l dvd d\"\n  hence \"l dvd gcd c d\" by (rule gcd_greatest)\n  from this and B show \"l dvd gcd a b\" by (rule dvd_trans)\nqed\n\nlemma gcd_mult_cancel:\n  assumes \"gcd k n = 1\"\n  shows \"gcd (k * m) n = gcd m n\"\nproof (rule gcd_dvd_antisym)\n  have \"gcd (gcd (k * m) n) k = gcd (gcd k n) (k * m)\" by (simp add: ac_simps)\n  also note `gcd k n = 1`\n  finally have \"gcd (gcd (k * m) n) k = 1\" by simp\n  hence \"gcd (k * m) n dvd m\" by (rule coprime_dvd_mult, simp add: ac_simps)\n  moreover have \"gcd (k * m) n dvd n\" by simp\n  ultimately show \"gcd (k * m) n dvd gcd m n\" by (rule gcd_greatest)\n  have \"gcd m n dvd (k * m)\" and \"gcd m n dvd n\" by simp_all\n  then show \"gcd m n dvd gcd (k * m) n\" by (rule gcd_greatest)\nqed\n\nlemma coprime_crossproduct:\n  assumes [simp]: \"gcd a d = 1\" \"gcd b c = 1\"\n  shows \"associated (a * c) (b * d) \\<longleftrightarrow> associated a b \\<and> associated c d\" (is \"?lhs \\<longleftrightarrow> ?rhs\")\nproof\n  assume ?rhs then show ?lhs unfolding associated_def by (fast intro: mult_dvd_mono)\nnext\n  assume ?lhs\n  from `?lhs` have \"a dvd b * d\" unfolding associated_def by (metis dvd_mult_left) \n  hence \"a dvd b\" by (simp add: coprime_dvd_mult_iff)\n  moreover from `?lhs` have \"b dvd a * c\" unfolding associated_def by (metis dvd_mult_left) \n  hence \"b dvd a\" by (simp add: coprime_dvd_mult_iff)\n  moreover from `?lhs` have \"c dvd d * b\" \n    unfolding associated_def by (auto dest: dvd_mult_right simp add: ac_simps)\n  hence \"c dvd d\" by (simp add: coprime_dvd_mult_iff gcd.commute)\n  moreover from `?lhs` have \"d dvd c * a\"\n    unfolding associated_def by (auto dest: dvd_mult_right simp add: ac_simps)\n  hence \"d dvd c\" by (simp add: coprime_dvd_mult_iff gcd.commute)\n  ultimately show ?rhs unfolding associated_def by simp\nqed\n\nlemma gcd_add1 [simp]:\n  \"gcd (m + n) n = gcd m n\"\n  by (cases \"n = 0\", simp_all add: gcd_non_0)\n\nlemma gcd_add2 [simp]:\n  \"gcd m (m + n) = gcd m n\"\n  using gcd_add1 [of n m] by (simp add: ac_simps)\n\nlemma gcd_add_mult: \"gcd m (k * m + n) = gcd m n\"\n  by (subst gcd.commute, subst gcd_red, simp)\n\nlemma coprimeI: \"(\\<And>l. \\<lbrakk>l dvd x; l dvd y\\<rbrakk> \\<Longrightarrow> l dvd 1) \\<Longrightarrow> gcd x y = 1\"\n  by (rule sym, rule gcdI, simp_all)\n\nlemma coprime: \"gcd a b = 1 \\<longleftrightarrow> (\\<forall>d. d dvd a \\<and> d dvd b \\<longleftrightarrow> is_unit d)\"\n  by (auto intro: coprimeI gcd_greatest dvd_gcd_D1 dvd_gcd_D2)\n\nlemma div_gcd_coprime:\n  assumes nz: \"a \\<noteq> 0 \\<or> b \\<noteq> 0\"\n  defines [simp]: \"d \\<equiv> gcd a b\"\n  defines [simp]: \"a' \\<equiv> a div d\" and [simp]: \"b' \\<equiv> b div d\"\n  shows \"gcd a' b' = 1\"\nproof (rule coprimeI)\n  fix l assume \"l dvd a'\" \"l dvd b'\"\n  then obtain s t where \"a' = l * s\" \"b' = l * t\" unfolding dvd_def by blast\n  moreover have \"a = a' * d\" \"b = b' * d\" by simp_all\n  ultimately have \"a = (l * d) * s\" \"b = (l * d) * t\"\n    by (simp_all only: ac_simps)\n  hence \"l*d dvd a\" and \"l*d dvd b\" by (simp_all only: dvd_triv_left)\n  hence \"l*d dvd d\" by (simp add: gcd_greatest)\n  then obtain u where \"d = l * d * u\" ..\n  then have \"d * (l * u) = d\" by (simp add: ac_simps)\n  moreover from nz have \"d \\<noteq> 0\" by simp\n  with div_mult_self1_is_id have \"d * (l * u) div d = l * u\" . \n  ultimately have \"1 = l * u\"\n    using `d \\<noteq> 0` by simp\n  then show \"l dvd 1\" ..\nqed\n\nlemma coprime_mult: \n  assumes da: \"gcd d a = 1\" and db: \"gcd d b = 1\"\n  shows \"gcd d (a * b) = 1\"\n  apply (subst gcd.commute)\n  using da apply (subst gcd_mult_cancel)\n  apply (subst gcd.commute, assumption)\n  apply (subst gcd.commute, rule db)\n  done\n\nlemma coprime_lmult:\n  assumes dab: \"gcd d (a * b) = 1\" \n  shows \"gcd d a = 1\"\nproof (rule coprimeI)\n  fix l assume \"l dvd d\" and \"l dvd a\"\n  hence \"l dvd a * b\" by simp\n  with `l dvd d` and dab show \"l dvd 1\" by (auto intro: gcd_greatest)\nqed\n\nlemma coprime_rmult:\n  assumes dab: \"gcd d (a * b) = 1\"\n  shows \"gcd d b = 1\"\nproof (rule coprimeI)\n  fix l assume \"l dvd d\" and \"l dvd b\"\n  hence \"l dvd a * b\" by simp\n  with `l dvd d` and dab show \"l dvd 1\" by (auto intro: gcd_greatest)\nqed\n\nlemma coprime_mul_eq: \"gcd d (a * b) = 1 \\<longleftrightarrow> gcd d a = 1 \\<and> gcd d b = 1\"\n  using coprime_rmult[of d a b] coprime_lmult[of d a b] coprime_mult[of d a b] by blast\n\nlemma gcd_coprime:\n  assumes z: \"gcd a b \\<noteq> 0\" and a: \"a = a' * gcd a b\" and b: \"b = b' * gcd a b\"\n  shows \"gcd a' b' = 1\"\nproof -\n  from z have \"a \\<noteq> 0 \\<or> b \\<noteq> 0\" by simp\n  with div_gcd_coprime have \"gcd (a div gcd a b) (b div gcd a b) = 1\" .\n  also from assms have \"a div gcd a b = a'\" by (metis div_mult_self2_is_id)+\n  also from assms have \"b div gcd a b = b'\" by (metis div_mult_self2_is_id)+\n  finally show ?thesis .\nqed\n\nlemma coprime_power:\n  assumes \"0 < n\"\n  shows \"gcd a (b ^ n) = 1 \\<longleftrightarrow> gcd a b = 1\"\nusing assms proof (induct n)\n  case (Suc n) then show ?case\n    by (cases n) (simp_all add: coprime_mul_eq)\nqed simp\n\nlemma gcd_coprime_exists:\n  assumes nz: \"gcd a b \\<noteq> 0\"\n  shows \"\\<exists>a' b'. a = a' * gcd a b \\<and> b = b' * gcd a b \\<and> gcd a' b' = 1\"\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  apply (insert nz, auto intro: div_gcd_coprime)\n  done\n\nlemma coprime_exp:\n  \"gcd d a = 1 \\<Longrightarrow> gcd d (a^n) = 1\"\n  by (induct n, simp_all add: coprime_mult)\n\nlemma coprime_exp2 [intro]:\n  \"gcd a b = 1 \\<Longrightarrow> gcd (a^n) (b^m) = 1\"\n  apply (rule coprime_exp)\n  apply (subst gcd.commute)\n  apply (rule coprime_exp)\n  apply (subst gcd.commute)\n  apply assumption\n  done\n\nlemma gcd_exp:\n  \"gcd (a^n) (b^n) = (gcd a b) ^ n\"\nproof (cases \"a = 0 \\<and> b = 0\")\n  assume \"a = 0 \\<and> b = 0\"\n  then show ?thesis by (cases n, simp_all add: gcd_0_left)\nnext\n  assume A: \"\\<not>(a = 0 \\<and> b = 0)\"\n  hence \"1 = gcd ((a div gcd a b)^n) ((b div gcd a b)^n)\"\n    using div_gcd_coprime by (subst sym, auto simp: div_gcd_coprime)\n  hence \"(gcd a b) ^ n = (gcd a b) ^ n * ...\" by simp\n  also note gcd_mult_distrib\n  also have \"normalisation_factor ((gcd a b)^n) = 1\"\n    by (simp add: normalisation_factor_pow A)\n  also have \"(gcd a b)^n * (a div gcd a b)^n = a^n\"\n    by (subst ac_simps, subst div_power, simp, rule dvd_div_mult_self, rule dvd_power_same, simp)\n  also have \"(gcd a b)^n * (b div gcd a b)^n = b^n\"\n    by (subst ac_simps, subst div_power, simp, rule dvd_div_mult_self, rule dvd_power_same, simp)\n  finally show ?thesis by simp\nqed\n\nlemma coprime_common_divisor: \n  \"gcd a b = 1 \\<Longrightarrow> x dvd a \\<Longrightarrow> x dvd b \\<Longrightarrow> is_unit x\"\n  apply (subgoal_tac \"x dvd gcd a b\")\n  apply simp\n  apply (erule (1) gcd_greatest)\n  done\n\nlemma division_decomp: \n  assumes dc: \"a dvd b * c\"\n  shows \"\\<exists>b' c'. a = b' * c' \\<and> b' dvd b \\<and> c' dvd c\"\nproof (cases \"gcd a b = 0\")\n  assume \"gcd a b = 0\"\n  hence \"a = 0 \\<and> b = 0\" by simp\n  hence \"a = 0 * c \\<and> 0 dvd b \\<and> c dvd c\" by simp\n  then show ?thesis by blast\nnext\n  let ?d = \"gcd a b\"\n  assume \"?d \\<noteq> 0\"\n  from gcd_coprime_exists[OF this]\n    obtain a' b' where ab': \"a = a' * ?d\" \"b = b' * ?d\" \"gcd a' b' = 1\"\n    by blast\n  from ab'(1) have \"a' dvd a\" unfolding dvd_def by blast\n  with dc have \"a' dvd b*c\" using dvd_trans[of a' a \"b*c\"] by simp\n  from dc ab'(1,2) have \"a'*?d dvd (b'*?d) * c\" by simp\n  hence \"?d * a' dvd ?d * (b' * c)\" by (simp add: mult_ac)\n  with `?d \\<noteq> 0` have \"a' dvd b' * c\" by simp\n  with coprime_dvd_mult[OF ab'(3)] \n    have \"a' dvd c\" by (subst (asm) ac_simps, blast)\n  with ab'(1) have \"a = ?d * a' \\<and> ?d dvd b \\<and> a' dvd c\" by (simp add: mult_ac)\n  then show ?thesis by blast\nqed\n\nlemma pow_divides_pow:\n  assumes ab: \"a ^ n dvd b ^ n\" and n: \"n \\<noteq> 0\"\n  shows \"a dvd b\"\nproof (cases \"gcd a b = 0\")\n  assume \"gcd a b = 0\"\n  then show ?thesis by simp\nnext\n  let ?d = \"gcd a b\"\n  assume \"?d \\<noteq> 0\"\n  from n obtain m where m: \"n = Suc m\" by (cases n, simp_all)\n  from `?d \\<noteq> 0` have zn: \"?d ^ n \\<noteq> 0\" by (rule power_not_zero)\n  from gcd_coprime_exists[OF `?d \\<noteq> 0`]\n    obtain a' b' where ab': \"a = a' * ?d\" \"b = b' * ?d\" \"gcd a' b' = 1\"\n    by blast\n  from ab have \"(a' * ?d) ^ n dvd (b' * ?d) ^ n\"\n    by (simp add: ab'(1,2)[symmetric])\n  hence \"?d^n * a'^n dvd ?d^n * b'^n\"\n    by (simp only: power_mult_distrib ac_simps)\n  with zn have \"a'^n dvd b'^n\" by simp\n  hence \"a' dvd b'^n\" using dvd_trans[of a' \"a'^n\" \"b'^n\"] by (simp add: m)\n  hence \"a' dvd b'^m * b'\" by (simp add: m ac_simps)\n  with coprime_dvd_mult[OF coprime_exp[OF ab'(3), of m]]\n    have \"a' dvd b'\" by (subst (asm) ac_simps, blast)\n  hence \"a'*?d dvd b'*?d\" by (rule mult_dvd_mono, simp)\n  with ab'(1,2) show ?thesis by simp\nqed\n\nlemma pow_divides_eq [simp]:\n  \"n \\<noteq> 0 \\<Longrightarrow> a ^ n dvd b ^ n \\<longleftrightarrow> a dvd b\"\n  by (auto intro: pow_divides_pow dvd_power_same)\n\nlemma divides_mult:\n  assumes mr: \"m dvd r\" and nr: \"n dvd r\" and mn: \"gcd m n = 1\"\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: ac_simps)\n  hence \"m dvd n'\" using coprime_dvd_mult_iff[OF mn] by simp\n  then obtain k where k: \"n' = m*k\" unfolding dvd_def by blast\n  with n' have \"r = m * n * k\" by (simp add: mult_ac)\n  then show ?thesis unfolding dvd_def by blast\nqed\n\nlemma coprime_plus_one [simp]: \"gcd (n + 1) n = 1\"\n  by (subst add_commute, simp)\n\nlemma setprod_coprime [rule_format]:\n  \"(\\<forall>i\\<in>A. gcd (f i) x = 1) \\<longrightarrow> gcd (\\<Prod>i\\<in>A. f i) x = 1\"\n  apply (cases \"finite A\")\n  apply (induct set: finite)\n  apply (auto simp add: gcd_mult_cancel)\n  done\n\nlemma coprime_divisors: \n  assumes \"d dvd a\" \"e dvd b\" \"gcd a b = 1\"\n  shows \"gcd d e = 1\" \nproof -\n  from assms obtain k l where \"a = d * k\" \"b = e * l\"\n    unfolding dvd_def by blast\n  with assms have \"gcd (d * k) (e * l) = 1\" by simp\n  hence \"gcd (d * k) e = 1\" by (rule coprime_lmult)\n  also have \"gcd (d * k) e = gcd e (d * k)\" by (simp add: ac_simps)\n  finally have \"gcd e d = 1\" by (rule coprime_lmult)\n  then show ?thesis by (simp add: ac_simps)\nqed\n\nlemma invertible_coprime:\n  assumes \"x * y mod m = 1\"\n  shows \"coprime x m\"\nproof -\n  from assms have \"coprime m (x * y mod m)\"\n    by simp\n  then have \"coprime m (x * y)\"\n    by simp\n  then have \"coprime m x\"\n    by (rule coprime_lmult)\n  then show ?thesis\n    by (simp add: ac_simps)\nqed\n\nlemma lcm_gcd:\n  \"lcm a b = a * b div (gcd a b * normalisation_factor (a*b))\"\n  by (simp only: lcm_lcm_eucl gcd_gcd_eucl lcm_eucl_def)\n\nlemma lcm_gcd_prod:\n  \"lcm a b * gcd a b = a * b div normalisation_factor (a*b)\"\nproof (cases \"a * b = 0\")\n  let ?nf = normalisation_factor\n  assume \"a * b \\<noteq> 0\"\n  hence \"gcd a b \\<noteq> 0\" by simp\n  from lcm_gcd have \"lcm a b * gcd a b = gcd a b * (a * b div (?nf (a*b) * gcd a b))\" \n    by (simp add: mult_ac)\n  also from `a * b \\<noteq> 0` have \"... = a * b div ?nf (a*b)\" \n    by (simp_all add: unit_ring_inv'1 unit_ring_inv)\n  finally show ?thesis .\nqed (auto simp add: lcm_gcd)\n\nlemma lcm_dvd1 [iff]:\n  \"x dvd lcm x y\"\nproof (cases \"x*y = 0\")\n  assume \"x * y \\<noteq> 0\"\n  hence \"gcd x y \\<noteq> 0\" by simp\n  let ?c = \"ring_inv (normalisation_factor (x*y))\"\n  from `x * y \\<noteq> 0` have [simp]: \"is_unit (normalisation_factor (x*y))\" by simp\n  from lcm_gcd_prod[of x y] have \"lcm x y * gcd x y = x * ?c * y\"\n    by (simp add: mult_ac unit_ring_inv)\n  hence \"lcm x y * gcd x y div gcd x y = x * ?c * y div gcd x y\" by simp\n  with `gcd x y \\<noteq> 0` have \"lcm x y = x * ?c * y div gcd x y\"\n    by (subst (asm) div_mult_self2_is_id, simp_all)\n  also have \"... = x * (?c * y div gcd x y)\"\n    by (metis div_mult_swap gcd_dvd2 mult_assoc)\n  finally show ?thesis by (rule dvdI)\nqed (auto simp add: lcm_gcd)\n\nlemma lcm_least:\n  \"\\<lbrakk>a dvd k; b dvd k\\<rbrakk> \\<Longrightarrow> lcm a b dvd k\"\nproof (cases \"k = 0\")\n  let ?nf = normalisation_factor\n  assume \"k \\<noteq> 0\"\n  hence \"is_unit (?nf k)\" by simp\n  hence \"?nf k \\<noteq> 0\" by (metis not_is_unit_0)\n  assume A: \"a dvd k\" \"b dvd k\"\n  hence \"gcd a b \\<noteq> 0\" using `k \\<noteq> 0` by auto\n  from A obtain r s where ar: \"k = a * r\" and bs: \"k = b * s\" \n    unfolding dvd_def by blast\n  with `k \\<noteq> 0` have \"r * s \\<noteq> 0\"\n    by auto (drule sym [of 0], simp)\n  hence \"is_unit (?nf (r * s))\" by simp\n  let ?c = \"?nf k div ?nf (r*s)\"\n  from `is_unit (?nf k)` and `is_unit (?nf (r * s))` have \"is_unit ?c\" by (rule unit_div)\n  hence \"?c \\<noteq> 0\" using not_is_unit_0 by fast \n  from ar bs have \"k * k * gcd s r = ?nf k * k * gcd (k * s) (k * r)\"\n    by (subst mult_assoc, subst gcd_mult_distrib[of k s r], simp only: ac_simps)\n  also have \"... = ?nf k * k * gcd ((r*s) * a) ((r*s) * b)\"\n    by (subst (3) `k = a * r`, subst (3) `k = b * s`, simp add: algebra_simps)\n  also have \"... = ?c * r*s * k * gcd a b\" using `r * s \\<noteq> 0`\n    by (subst gcd_mult_distrib'[symmetric], simp add: algebra_simps unit_simps)\n  finally have \"(a*r) * (b*s) * gcd s r = ?c * k * r * s * gcd a b\"\n    by (subst ar[symmetric], subst bs[symmetric], simp add: mult_ac)\n  hence \"a * b * gcd s r * (r * s) = ?c * k * gcd a b * (r * s)\"\n    by (simp add: algebra_simps)\n  hence \"?c * k * gcd a b = a * b * gcd s r\" using `r * s \\<noteq> 0`\n    by (metis div_mult_self2_is_id)\n  also have \"... = lcm a b * gcd a b * gcd s r * ?nf (a*b)\"\n    by (subst lcm_gcd_prod[of a b], metis gcd_mult_distrib gcd_mult_distrib') \n  also have \"... = lcm a b * gcd s r * ?nf (a*b) * gcd a b\"\n    by (simp add: algebra_simps)\n  finally have \"k * ?c = lcm a b * gcd s r * ?nf (a*b)\" using `gcd a b \\<noteq> 0`\n    by (metis mult.commute div_mult_self2_is_id)\n  hence \"k = lcm a b * (gcd s r * ?nf (a*b)) div ?c\" using `?c \\<noteq> 0`\n    by (metis div_mult_self2_is_id mult_assoc) \n  also have \"... = lcm a b * (gcd s r * ?nf (a*b) div ?c)\" using `is_unit ?c`\n    by (simp add: unit_simps)\n  finally show ?thesis by (rule dvdI)\nqed simp\n\nlemma lcm_zero:\n  \"lcm a b = 0 \\<longleftrightarrow> a = 0 \\<or> b = 0\"\nproof -\n  let ?nf = normalisation_factor\n  {\n    assume \"a \\<noteq> 0\" \"b \\<noteq> 0\"\n    hence \"a * b div ?nf (a * b) \\<noteq> 0\" by (simp add: no_zero_divisors)\n    moreover from `a \\<noteq> 0` and `b \\<noteq> 0` have \"gcd a b \\<noteq> 0\" by simp\n    ultimately have \"lcm a b \\<noteq> 0\" using lcm_gcd_prod[of a b] by (intro notI, simp)\n  } moreover {\n    assume \"a = 0 \\<or> b = 0\"\n    hence \"lcm a b = 0\" by (elim disjE, simp_all add: lcm_gcd)\n  }\n  ultimately show ?thesis by blast\nqed\n\nlemmas lcm_0_iff = lcm_zero\n\nlemma gcd_lcm: \n  assumes \"lcm a b \\<noteq> 0\"\n  shows \"gcd a b = a * b div (lcm a b * normalisation_factor (a * b))\"\nproof-\n  from assms have \"gcd a b \\<noteq> 0\" by (simp add: lcm_zero)\n  let ?c = \"normalisation_factor (a*b)\"\n  from `lcm a b \\<noteq> 0` have \"?c \\<noteq> 0\" by (intro notI, simp add: lcm_zero no_zero_divisors)\n  hence \"is_unit ?c\" by simp\n  from lcm_gcd_prod [of a b] have \"gcd a b = a * b div ?c div lcm a b\"\n    by (subst (2) div_mult_self2_is_id[OF `lcm a b \\<noteq> 0`, symmetric], simp add: mult_ac)\n  also from `is_unit ?c` have \"... = a * b div (?c * lcm a b)\"\n    by (simp only: unit_ring_inv'1 unit_ring_inv)\n  finally show ?thesis by (simp only: ac_simps)\nqed\n\nlemma normalisation_factor_lcm [simp]:\n  \"normalisation_factor (lcm a b) = (if a = 0 \\<or> b = 0 then 0 else 1)\"\nproof (cases \"a = 0 \\<or> b = 0\")\n  case True then show ?thesis\n    by (auto simp add: lcm_gcd) \nnext\n  case False\n  let ?nf = normalisation_factor\n  from lcm_gcd_prod[of a b] \n    have \"?nf (lcm a b) * ?nf (gcd a b) = ?nf (a*b) div ?nf (a*b)\"\n    by (metis div_by_0 div_self normalisation_correct normalisation_factor_0 normalisation_factor_mult)\n  also have \"... = (if a*b = 0 then 0 else 1)\"\n    by simp\n  finally show ?thesis using False by simp\nqed\n\nlemma lcm_dvd2 [iff]: \"y dvd lcm x y\"\n  using lcm_dvd1 [of y x] by (simp add: lcm_gcd ac_simps)\n\nlemma lcmI:\n  \"\\<lbrakk>x dvd k; y dvd k; \\<And>l. x dvd l \\<Longrightarrow> y dvd l \\<Longrightarrow> k dvd l;\n    normalisation_factor k = (if k = 0 then 0 else 1)\\<rbrakk> \\<Longrightarrow> k = lcm x y\"\n  by (intro normed_associated_imp_eq) (auto simp: associated_def intro: lcm_least)\n\nsublocale lcm!: abel_semigroup lcm\nproof\n  fix x y z\n  show \"lcm (lcm x y) z = lcm x (lcm y z)\"\n  proof (rule lcmI)\n    have \"x dvd lcm x y\" and \"lcm x y dvd lcm (lcm x y) z\" by simp_all\n    then show \"x dvd lcm (lcm x y) z\" by (rule dvd_trans)\n    \n    have \"y dvd lcm x y\" and \"lcm x y dvd lcm (lcm x y) z\" by simp_all\n    hence \"y dvd lcm (lcm x y) z\" by (rule dvd_trans)\n    moreover have \"z dvd lcm (lcm x y) z\" by simp\n    ultimately show \"lcm y z dvd lcm (lcm x y) z\" by (rule lcm_least)\n\n    fix l assume \"x dvd l\" and \"lcm y z dvd l\"\n    have \"y dvd lcm y z\" by simp\n    from this and `lcm y z dvd l` have \"y dvd l\" by (rule dvd_trans)\n    have \"z dvd lcm y z\" by simp\n    from this and `lcm y z dvd l` have \"z dvd l\" by (rule dvd_trans)\n    from `x dvd l` and `y dvd l` have \"lcm x y dvd l\" by (rule lcm_least)\n    from this and `z dvd l` show \"lcm (lcm x y) z dvd l\" by (rule lcm_least)\n  qed (simp add: lcm_zero)\nnext\n  fix x y\n  show \"lcm x y = lcm y x\"\n    by (simp add: lcm_gcd ac_simps)\nqed\n\nlemma dvd_lcm_D1:\n  \"lcm m n dvd k \\<Longrightarrow> m dvd k\"\n  by (rule dvd_trans, rule lcm_dvd1, assumption)\n\nlemma dvd_lcm_D2:\n  \"lcm m n dvd k \\<Longrightarrow> n dvd k\"\n  by (rule dvd_trans, rule lcm_dvd2, assumption)\n\nlemma gcd_dvd_lcm [simp]:\n  \"gcd a b dvd lcm a b\"\n  by (metis dvd_trans gcd_dvd2 lcm_dvd2)\n\nlemma lcm_1_iff:\n  \"lcm a b = 1 \\<longleftrightarrow> is_unit a \\<and> is_unit b\"\nproof\n  assume \"lcm a b = 1\"\n  then show \"is_unit a \\<and> is_unit b\" by auto\nnext\n  assume \"is_unit a \\<and> is_unit b\"\n  hence \"a dvd 1\" and \"b dvd 1\" by simp_all\n  hence \"is_unit (lcm a b)\" by (rule lcm_least)\n  hence \"lcm a b = normalisation_factor (lcm a b)\"\n    by (subst normalisation_factor_unit, simp_all)\n  also have \"\\<dots> = 1\" using `is_unit a \\<and> is_unit b`\n    by auto\n  finally show \"lcm a b = 1\" .\nqed\n\nlemma lcm_0_left [simp]:\n  \"lcm 0 x = 0\"\n  by (rule sym, rule lcmI, simp_all)\n\nlemma lcm_0 [simp]:\n  \"lcm x 0 = 0\"\n  by (rule sym, rule lcmI, simp_all)\n\nlemma lcm_unique:\n  \"a dvd d \\<and> b dvd d \\<and> \n  normalisation_factor d = (if d = 0 then 0 else 1) \\<and>\n  (\\<forall>e. a dvd e \\<and> b dvd e \\<longrightarrow> d dvd e) \\<longleftrightarrow> d = lcm a b\"\n  by (rule, auto intro: lcmI simp: lcm_least lcm_zero)\n\nlemma dvd_lcm_I1 [simp]:\n  \"k dvd m \\<Longrightarrow> k dvd lcm m n\"\n  by (metis lcm_dvd1 dvd_trans)\n\nlemma dvd_lcm_I2 [simp]:\n  \"k dvd n \\<Longrightarrow> k dvd lcm m n\"\n  by (metis lcm_dvd2 dvd_trans)\n\nlemma lcm_1_left [simp]:\n  \"lcm 1 x = x div normalisation_factor x\"\n  by (cases \"x = 0\") (simp, rule sym, rule lcmI, simp_all)\n\nlemma lcm_1_right [simp]:\n  \"lcm x 1 = x div normalisation_factor x\"\n  by (simp add: ac_simps)\n\nlemma lcm_coprime:\n  \"gcd a b = 1 \\<Longrightarrow> lcm a b = a * b div normalisation_factor (a*b)\"\n  by (subst lcm_gcd) simp\n\nlemma lcm_proj1_if_dvd: \n  \"y dvd x \\<Longrightarrow> lcm x y = x div normalisation_factor x\"\n  by (cases \"x = 0\") (simp, rule sym, rule lcmI, simp_all)\n\nlemma lcm_proj2_if_dvd: \n  \"x dvd y \\<Longrightarrow> lcm x y = y div normalisation_factor y\"\n  using lcm_proj1_if_dvd [of x y] by (simp add: ac_simps)\n\nlemma lcm_proj1_iff:\n  \"lcm m n = m div normalisation_factor m \\<longleftrightarrow> n dvd m\"\nproof\n  assume A: \"lcm m n = m div normalisation_factor m\"\n  show \"n dvd m\"\n  proof (cases \"m = 0\")\n    assume [simp]: \"m \\<noteq> 0\"\n    from A have B: \"m = lcm m n * normalisation_factor m\"\n      by (simp add: unit_eq_div2)\n    show ?thesis by (subst B, simp)\n  qed simp\nnext\n  assume \"n dvd m\"\n  then show \"lcm m n = m div normalisation_factor m\" by (rule lcm_proj1_if_dvd)\nqed\n\nlemma lcm_proj2_iff:\n  \"lcm m n = n div normalisation_factor n \\<longleftrightarrow> m dvd n\"\n  using lcm_proj1_iff [of n m] by (simp add: ac_simps)\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 lcm_dvd1)\n  then obtain c where A: \"lcm a b = a * c\" unfolding dvd_def by blast\n  with `a \\<noteq> 0` and `b \\<noteq> 0` have \"c \\<noteq> 0\" by (auto simp: lcm_zero)\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 `a \\<noteq> 0` and `b \\<noteq> 0` 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_zero)\n  hence \"b dvd a\" by (rule dvd_lcm_D2)\n  with `\\<not>b dvd a` 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\nlemma lcm_mult_unit1:\n  \"is_unit a \\<Longrightarrow> lcm (x*a) y = lcm x y\"\n  apply (rule lcmI)\n  apply (rule dvd_trans[of _ \"x*a\"], simp, rule lcm_dvd1)\n  apply (rule lcm_dvd2)\n  apply (rule lcm_least, simp add: unit_simps, assumption)\n  apply (subst normalisation_factor_lcm, simp add: lcm_zero)\n  done\n\nlemma lcm_mult_unit2:\n  \"is_unit a \\<Longrightarrow> lcm x (y*a) = lcm x y\"\n  using lcm_mult_unit1 [of a y x] by (simp add: ac_simps)\n\nlemma lcm_div_unit1:\n  \"is_unit a \\<Longrightarrow> lcm (x div a) y = lcm x y\"\n  by (simp add: unit_ring_inv lcm_mult_unit1)\n\nlemma lcm_div_unit2:\n  \"is_unit a \\<Longrightarrow> lcm x (y div a) = lcm x y\"\n  by (simp add: unit_ring_inv lcm_mult_unit2)\n\nlemma lcm_left_idem:\n  \"lcm p (lcm p q) = lcm p q\"\n  apply (rule lcmI)\n  apply simp\n  apply (subst lcm.assoc [symmetric], rule lcm_dvd2)\n  apply (rule lcm_least, assumption)\n  apply (erule (1) lcm_least)\n  apply (auto simp: lcm_zero)\n  done\n\nlemma lcm_right_idem:\n  \"lcm (lcm p q) q = lcm p q\"\n  apply (rule lcmI)\n  apply (subst lcm.assoc, rule lcm_dvd1)\n  apply (rule lcm_dvd2)\n  apply (rule lcm_least, erule (1) lcm_least, assumption)\n  apply (auto simp: lcm_zero)\n  done\n\nlemma comp_fun_idem_lcm: \"comp_fun_idem lcm\"\nproof\n  fix a b show \"lcm a \\<circ> lcm b = lcm b \\<circ> lcm a\"\n    by (simp add: fun_eq_iff ac_simps)\nnext\n  fix a show \"lcm a \\<circ> lcm a = lcm a\" unfolding o_def\n    by (intro ext, simp add: lcm_left_idem)\nqed\n\nlemma dvd_Lcm [simp]: \"x \\<in> A \\<Longrightarrow> x dvd Lcm A\"\n  and Lcm_dvd [simp]: \"(\\<forall>x\\<in>A. x dvd l') \\<Longrightarrow> Lcm A dvd l'\"\n  and normalisation_factor_Lcm [simp]: \n          \"normalisation_factor (Lcm A) = (if Lcm A = 0 then 0 else 1)\"\nproof -\n  have \"(\\<forall>x\\<in>A. x dvd Lcm A) \\<and> (\\<forall>l'. (\\<forall>x\\<in>A. x dvd l') \\<longrightarrow> Lcm A dvd l') \\<and>\n    normalisation_factor (Lcm A) = (if Lcm A = 0 then 0 else 1)\" (is ?thesis)\n  proof (cases \"\\<exists>l. l \\<noteq>  0 \\<and> (\\<forall>x\\<in>A. x dvd l)\")\n    case False\n    hence \"Lcm A = 0\" by (auto simp: Lcm_Lcm_eucl Lcm_eucl_def)\n    with False show ?thesis by auto\n  next\n    case True\n    then obtain l\\<^sub>0 where l\\<^sub>0_props: \"l\\<^sub>0 \\<noteq> 0 \\<and> (\\<forall>x\\<in>A. x dvd l\\<^sub>0)\" by blast\n    def n \\<equiv> \"LEAST n. \\<exists>l. l \\<noteq> 0 \\<and> (\\<forall>x\\<in>A. x dvd l) \\<and> euclidean_size l = n\"\n    def l \\<equiv> \"SOME l. l \\<noteq> 0 \\<and> (\\<forall>x\\<in>A. x dvd l) \\<and> euclidean_size l = n\"\n    have \"\\<exists>l. l \\<noteq> 0 \\<and> (\\<forall>x\\<in>A. x 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>x\\<in>A. x dvd l\" and \"euclidean_size l = n\" \n      unfolding l_def by simp_all\n    {\n      fix l' assume \"\\<forall>x\\<in>A. x dvd l'\"\n      with `\\<forall>x\\<in>A. x dvd l` have \"\\<forall>x\\<in>A. x dvd gcd l l'\" by (auto intro: gcd_greatest)\n      moreover from `l \\<noteq> 0` have \"gcd l l' \\<noteq> 0\" by simp\n      ultimately have \"\\<exists>b. b \\<noteq> 0 \\<and> (\\<forall>x\\<in>A. x dvd b) \\<and> euclidean_size b = euclidean_size (gcd l l')\"\n        by (intro exI[of _ \"gcd l l'\"], auto)\n      hence \"euclidean_size (gcd l l') \\<ge> 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\" by simp\n        then obtain a where \"l = gcd l l' * a\" unfolding dvd_def by blast\n        with `l \\<noteq> 0` have \"a \\<noteq> 0\" 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 `l = gcd l l' * a` ..\n        also note `euclidean_size l = n`\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: `euclidean_size l = n`)\n      with `l \\<noteq> 0` have \"l dvd gcd l l'\" by (blast intro: dvd_euclidean_size_eq_imp_dvd)\n      hence \"l dvd l'\" by (blast dest: dvd_gcd_D2)\n    }\n\n    with `(\\<forall>x\\<in>A. x dvd l)` and normalisation_factor_is_unit[OF `l \\<noteq> 0`] and `l \\<noteq> 0`\n      have \"(\\<forall>x\\<in>A. x dvd l div normalisation_factor l) \\<and> \n        (\\<forall>l'. (\\<forall>x\\<in>A. x dvd l') \\<longrightarrow> l div normalisation_factor l dvd l') \\<and>\n        normalisation_factor (l div normalisation_factor l) = \n        (if l div normalisation_factor l = 0 then 0 else 1)\"\n      by (auto simp: unit_simps)\n    also from True have \"l div normalisation_factor l = Lcm A\"\n      by (simp add: Lcm_Lcm_eucl Lcm_eucl_def Let_def n_def l_def)\n    finally show ?thesis .\n  qed\n  note A = this\n\n  {fix x assume \"x \\<in> A\" then show \"x dvd Lcm A\" using A by blast}\n  {fix l' assume \"\\<forall>x\\<in>A. x dvd l'\" then show \"Lcm A dvd l'\" using A by blast}\n  from A show \"normalisation_factor (Lcm A) = (if Lcm A = 0 then 0 else 1)\" by blast\nqed\n    \nlemma LcmI:\n  \"(\\<And>x. x\\<in>A \\<Longrightarrow> x dvd l) \\<Longrightarrow> (\\<And>l'. (\\<forall>x\\<in>A. x dvd l') \\<Longrightarrow> l dvd l') \\<Longrightarrow>\n      normalisation_factor l = (if l = 0 then 0 else 1) \\<Longrightarrow> l = Lcm A\"\n  by (intro normed_associated_imp_eq)\n    (auto intro: Lcm_dvd dvd_Lcm simp: associated_def)\n\nlemma Lcm_subset:\n  \"A \\<subseteq> B \\<Longrightarrow> Lcm A dvd Lcm B\"\n  by (blast intro: Lcm_dvd dvd_Lcm)\n\nlemma Lcm_Un:\n  \"Lcm (A \\<union> B) = lcm (Lcm A) (Lcm B)\"\n  apply (rule lcmI)\n  apply (blast intro: Lcm_subset)\n  apply (blast intro: Lcm_subset)\n  apply (intro Lcm_dvd ballI, elim UnE)\n  apply (rule dvd_trans, erule dvd_Lcm, assumption)\n  apply (rule dvd_trans, erule dvd_Lcm, assumption)\n  apply simp\n  done\n\nlemma Lcm_1_iff:\n  \"Lcm A = 1 \\<longleftrightarrow> (\\<forall>x\\<in>A. is_unit x)\"\nproof\n  assume \"Lcm A = 1\"\n  then show \"\\<forall>x\\<in>A. is_unit x\" by auto\nqed (rule LcmI [symmetric], auto)\n\nlemma Lcm_no_units:\n  \"Lcm A = Lcm (A - {x. is_unit x})\"\nproof -\n  have \"(A - {x. is_unit x}) \\<union> {x\\<in>A. is_unit x} = A\" by blast\n  hence \"Lcm A = lcm (Lcm (A - {x. is_unit x})) (Lcm {x\\<in>A. is_unit x})\"\n    by (simp add: Lcm_Un[symmetric])\n  also have \"Lcm {x\\<in>A. is_unit x} = 1\" by (simp add: Lcm_1_iff)\n  finally show ?thesis by simp\nqed\n\nlemma Lcm_empty [simp]:\n  \"Lcm {} = 1\"\n  by (simp add: Lcm_1_iff)\n\nlemma Lcm_eq_0 [simp]:\n  \"0 \\<in> A \\<Longrightarrow> Lcm A = 0\"\n  by (drule dvd_Lcm) simp\n\nlemma Lcm0_iff':\n  \"Lcm A = 0 \\<longleftrightarrow> \\<not>(\\<exists>l. l \\<noteq> 0 \\<and> (\\<forall>x\\<in>A. x dvd l))\"\nproof\n  assume \"Lcm A = 0\"\n  show \"\\<not>(\\<exists>l. l \\<noteq> 0 \\<and> (\\<forall>x\\<in>A. x dvd l))\"\n  proof\n    assume ex: \"\\<exists>l. l \\<noteq> 0 \\<and> (\\<forall>x\\<in>A. x dvd l)\"\n    then obtain l\\<^sub>0 where l\\<^sub>0_props: \"l\\<^sub>0 \\<noteq> 0 \\<and> (\\<forall>x\\<in>A. x dvd l\\<^sub>0)\" by blast\n    def n \\<equiv> \"LEAST n. \\<exists>l. l \\<noteq> 0 \\<and> (\\<forall>x\\<in>A. x dvd l) \\<and> euclidean_size l = n\"\n    def l \\<equiv> \"SOME l. l \\<noteq> 0 \\<and> (\\<forall>x\\<in>A. x dvd l) \\<and> euclidean_size l = n\"\n    have \"\\<exists>l. l \\<noteq> 0 \\<and> (\\<forall>x\\<in>A. x 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\" unfolding l_def by simp_all\n    hence \"l div normalisation_factor l \\<noteq> 0\" by simp\n    also from ex have \"l div normalisation_factor l = Lcm A\"\n       by (simp only: Lcm_Lcm_eucl Lcm_eucl_def n_def l_def if_True Let_def)\n    finally show False using `Lcm A = 0` by contradiction\n  qed\nqed (simp only: Lcm_Lcm_eucl Lcm_eucl_def if_False)\n\nlemma Lcm0_iff [simp]:\n  \"finite A \\<Longrightarrow> Lcm A = 0 \\<longleftrightarrow> 0 \\<in> A\"\nproof -\n  assume \"finite A\"\n  have \"0 \\<in> A \\<Longrightarrow> Lcm A = 0\"  by (intro dvd_0_left dvd_Lcm)\n  moreover {\n    assume \"0 \\<notin> A\"\n    hence \"\\<Prod>A \\<noteq> 0\" \n      apply (induct rule: finite_induct[OF `finite A`]) \n      apply simp\n      apply (subst setprod.insert, assumption, assumption)\n      apply (rule no_zero_divisors)\n      apply blast+\n      done\n    moreover from `finite A` have \"\\<forall>x\\<in>A. x dvd \\<Prod>A\" by blast\n    ultimately have \"\\<exists>l. l \\<noteq> 0 \\<and> (\\<forall>x\\<in>A. x dvd l)\" by blast\n    with Lcm0_iff' have \"Lcm A \\<noteq> 0\" by simp\n  }\n  ultimately show \"Lcm A = 0 \\<longleftrightarrow> 0 \\<in> A\" by blast\nqed\n\nlemma Lcm_no_multiple:\n  \"(\\<forall>m. m \\<noteq> 0 \\<longrightarrow> (\\<exists>x\\<in>A. \\<not>x dvd m)) \\<Longrightarrow> Lcm A = 0\"\nproof -\n  assume \"\\<forall>m. m \\<noteq> 0 \\<longrightarrow> (\\<exists>x\\<in>A. \\<not>x dvd m)\"\n  hence \"\\<not>(\\<exists>l. l \\<noteq> 0 \\<and> (\\<forall>x\\<in>A. x dvd l))\" by blast\n  then show \"Lcm A = 0\" by (simp only: Lcm_Lcm_eucl Lcm_eucl_def if_False)\nqed\n\nlemma Lcm_insert [simp]:\n  \"Lcm (insert a A) = lcm a (Lcm A)\"\nproof (rule lcmI)\n  fix l assume \"a dvd l\" and \"Lcm A dvd l\"\n  hence \"\\<forall>x\\<in>A. x dvd l\" by (blast intro: dvd_trans dvd_Lcm)\n  with `a dvd l` show \"Lcm (insert a A) dvd l\" by (force intro: Lcm_dvd)\nqed (auto intro: Lcm_dvd dvd_Lcm)\n \nlemma Lcm_finite:\n  assumes \"finite A\"\n  shows \"Lcm A = Finite_Set.fold lcm 1 A\"\n  by (induct rule: finite.induct[OF `finite A`])\n    (simp_all add: comp_fun_idem.fold_insert_idem[OF comp_fun_idem_lcm])\n\nlemma Lcm_set [code, code_unfold]:\n  \"Lcm (set xs) = fold lcm xs 1\"\n  using comp_fun_idem.fold_set_fold[OF comp_fun_idem_lcm] Lcm_finite by (simp add: ac_simps)\n\nlemma Lcm_singleton [simp]:\n  \"Lcm {a} = a div normalisation_factor a\"\n  by simp\n\nlemma Lcm_2 [simp]:\n  \"Lcm {a,b} = lcm a b\"\n  by (simp only: Lcm_insert Lcm_empty lcm_1_right)\n    (cases \"b = 0\", simp, rule lcm_div_unit2, simp)\n\nlemma Lcm_coprime:\n  assumes \"finite A\" and \"A \\<noteq> {}\" \n  assumes \"\\<And>a b. a \\<in> A \\<Longrightarrow> b \\<in> A \\<Longrightarrow> a \\<noteq> b \\<Longrightarrow> gcd a b = 1\"\n  shows \"Lcm A = \\<Prod>A div normalisation_factor (\\<Prod>A)\"\nusing assms proof (induct rule: finite_ne_induct)\n  case (insert a A)\n  have \"Lcm (insert a A) = lcm a (Lcm A)\" by simp\n  also from insert have \"Lcm A = \\<Prod>A div normalisation_factor (\\<Prod>A)\" by blast\n  also have \"lcm a \\<dots> = lcm a (\\<Prod>A)\" by (cases \"\\<Prod>A = 0\") (simp_all add: lcm_div_unit2)\n  also from insert have \"gcd a (\\<Prod>A) = 1\" by (subst gcd.commute, intro setprod_coprime) auto\n  with insert have \"lcm a (\\<Prod>A) = \\<Prod>(insert a A) div normalisation_factor (\\<Prod>(insert a A))\"\n    by (simp add: lcm_coprime)\n  finally show ?case .\nqed simp\n      \nlemma Lcm_coprime':\n  \"card A \\<noteq> 0 \\<Longrightarrow> (\\<And>a b. a \\<in> A \\<Longrightarrow> b \\<in> A \\<Longrightarrow> a \\<noteq> b \\<Longrightarrow> gcd a b = 1)\n    \\<Longrightarrow> Lcm A = \\<Prod>A div normalisation_factor (\\<Prod>A)\"\n  by (rule Lcm_coprime) (simp_all add: card_eq_0_iff)\n\nlemma Gcd_Lcm:\n  \"Gcd A = Lcm {d. \\<forall>x\\<in>A. d dvd x}\"\n  by (simp add: Gcd_Gcd_eucl Lcm_Lcm_eucl Gcd_eucl_def)\n\nlemma Gcd_dvd [simp]: \"x \\<in> A \\<Longrightarrow> Gcd A dvd x\"\n  and dvd_Gcd [simp]: \"(\\<forall>x\\<in>A. g' dvd x) \\<Longrightarrow> g' dvd Gcd A\"\n  and normalisation_factor_Gcd [simp]: \n    \"normalisation_factor (Gcd A) = (if Gcd A = 0 then 0 else 1)\"\nproof -\n  fix x assume \"x \\<in> A\"\n  hence \"Lcm {d. \\<forall>x\\<in>A. d dvd x} dvd x\" by (intro Lcm_dvd) blast\n  then show \"Gcd A dvd x\" by (simp add: Gcd_Lcm)\nnext\n  fix g' assume \"\\<forall>x\\<in>A. g' dvd x\"\n  hence \"g' dvd Lcm {d. \\<forall>x\\<in>A. d dvd x}\" by (intro dvd_Lcm) blast\n  then show \"g' dvd Gcd A\" by (simp add: Gcd_Lcm)\nnext\n  show \"normalisation_factor (Gcd A) = (if Gcd A = 0 then 0 else 1)\"\n    by (simp add: Gcd_Lcm)\nqed\n\nlemma GcdI:\n  \"(\\<And>x. x\\<in>A \\<Longrightarrow> l dvd x) \\<Longrightarrow> (\\<And>l'. (\\<forall>x\\<in>A. l' dvd x) \\<Longrightarrow> l' dvd l) \\<Longrightarrow>\n    normalisation_factor l = (if l = 0 then 0 else 1) \\<Longrightarrow> l = Gcd A\"\n  by (intro normed_associated_imp_eq)\n    (auto intro: Gcd_dvd dvd_Gcd simp: associated_def)\n\nlemma Lcm_Gcd:\n  \"Lcm A = Gcd {m. \\<forall>x\\<in>A. x dvd m}\"\n  by (rule LcmI[symmetric]) (auto intro: dvd_Gcd Gcd_dvd)\n\nlemma Gcd_0_iff:\n  \"Gcd A = 0 \\<longleftrightarrow> A \\<subseteq> {0}\"\n  apply (rule iffI)\n  apply (rule subsetI, drule Gcd_dvd, simp)\n  apply (auto intro: GcdI[symmetric])\n  done\n\nlemma Gcd_empty [simp]:\n  \"Gcd {} = 0\"\n  by (simp add: Gcd_0_iff)\n\nlemma Gcd_1:\n  \"1 \\<in> A \\<Longrightarrow> Gcd A = 1\"\n  by (intro GcdI[symmetric]) (auto intro: Gcd_dvd dvd_Gcd)\n\nlemma Gcd_insert [simp]:\n  \"Gcd (insert a A) = gcd a (Gcd A)\"\nproof (rule gcdI)\n  fix l assume \"l dvd a\" and \"l dvd Gcd A\"\n  hence \"\\<forall>x\\<in>A. l dvd x\" by (blast intro: dvd_trans Gcd_dvd)\n  with `l dvd a` show \"l dvd Gcd (insert a A)\" by (force intro: Gcd_dvd)\nqed auto\n\nlemma Gcd_finite:\n  assumes \"finite A\"\n  shows \"Gcd A = Finite_Set.fold gcd 0 A\"\n  by (induct rule: finite.induct[OF `finite A`])\n    (simp_all add: comp_fun_idem.fold_insert_idem[OF comp_fun_idem_gcd])\n\nlemma Gcd_set [code, code_unfold]:\n  \"Gcd (set xs) = fold gcd xs 0\"\n  using comp_fun_idem.fold_set_fold[OF comp_fun_idem_gcd] Gcd_finite by (simp add: ac_simps)\n\nlemma Gcd_singleton [simp]: \"Gcd {a} = a div normalisation_factor a\"\n  by (simp add: gcd_0)\n\nlemma Gcd_2 [simp]: \"Gcd {a,b} = gcd a b\"\n  by (simp only: Gcd_insert Gcd_empty gcd_0) (cases \"b = 0\", simp, rule gcd_div_unit2, simp)\n\nend\n\ntext {*\n  A Euclidean ring is a Euclidean semiring with additive inverses. It provides a \n  few more lemmas; in particular, Bezout's lemma holds for any Euclidean ring.\n*}\n\nclass euclidean_ring = euclidean_semiring + idom\n\nclass euclidean_ring_gcd = euclidean_semiring_gcd + idom\nbegin\n\nsubclass euclidean_ring ..\n\nlemma gcd_neg1 [simp]:\n  \"gcd (-x) y = gcd x y\"\n  by (rule sym, rule gcdI, simp_all add: gcd_greatest)\n\nlemma gcd_neg2 [simp]:\n  \"gcd x (-y) = gcd x y\"\n  by (rule sym, rule gcdI, simp_all add: gcd_greatest)\n\nlemma gcd_neg_numeral_1 [simp]:\n  \"gcd (- numeral n) x = gcd (numeral n) x\"\n  by (fact gcd_neg1)\n\nlemma gcd_neg_numeral_2 [simp]:\n  \"gcd x (- numeral n) = gcd x (numeral n)\"\n  by (fact gcd_neg2)\n\nlemma gcd_diff1: \"gcd (m - n) n = gcd m n\"\n  by (subst diff_conv_add_uminus, subst gcd_neg2[symmetric],  subst gcd_add1, simp)\n\nlemma gcd_diff2: \"gcd (n - m) n = gcd m n\"\n  by (subst gcd_neg1[symmetric], simp only: minus_diff_eq gcd_diff1)\n\nlemma coprime_minus_one [simp]: \"gcd (n - 1) n = 1\"\nproof -\n  have \"gcd (n - 1) n = gcd n (n - 1)\" by (fact gcd.commute)\n  also have \"\\<dots> = gcd ((n - 1) + 1) (n - 1)\" by simp\n  also have \"\\<dots> = 1\" by (rule coprime_plus_one)\n  finally show ?thesis .\nqed\n\nlemma lcm_neg1 [simp]: \"lcm (-x) y = lcm x y\"\n  by (rule sym, rule lcmI, simp_all add: lcm_least lcm_zero)\n\nlemma lcm_neg2 [simp]: \"lcm x (-y) = lcm x y\"\n  by (rule sym, rule lcmI, simp_all add: lcm_least lcm_zero)\n\nlemma lcm_neg_numeral_1 [simp]: \"lcm (- numeral n) x = lcm (numeral n) x\"\n  by (fact lcm_neg1)\n\nlemma lcm_neg_numeral_2 [simp]: \"lcm x (- numeral n) = lcm x (numeral n)\"\n  by (fact lcm_neg2)\n\nfunction euclid_ext :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a \\<times> 'a \\<times> 'a\" where\n  \"euclid_ext a b = \n     (if b = 0 then \n        let x = ring_inv (normalisation_factor a) in (x, 0, a * x)\n      else \n        case euclid_ext b (a mod b) of\n            (s,t,c) \\<Rightarrow> (t, s - t * (a div b), c))\"\n  by (pat_completeness, simp)\n  termination by (relation \"measure (euclidean_size \\<circ> snd)\", simp_all)\n\ndeclare euclid_ext.simps [simp del]\n\nlemma euclid_ext_0: \n  \"euclid_ext a 0 = (ring_inv (normalisation_factor a), 0, a * ring_inv (normalisation_factor a))\"\n  by (subst euclid_ext.simps, simp add: Let_def)\n\nlemma euclid_ext_non_0:\n  \"b \\<noteq> 0 \\<Longrightarrow> euclid_ext a b = (case euclid_ext b (a mod b) of \n    (s,t,c) \\<Rightarrow> (t, s - t * (a div b), c))\"\n  by (subst euclid_ext.simps, simp)\n\ndefinition euclid_ext' :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a \\<times> 'a\"\nwhere\n  \"euclid_ext' a b = (case euclid_ext a b of (s, t, _) \\<Rightarrow> (s, t))\"\n\nlemma euclid_ext_gcd [simp]:\n  \"(case euclid_ext a b of (_,_,t) \\<Rightarrow> t) = gcd a b\"\nproof (induct a b rule: euclid_ext.induct)\n  case (1 a b)\n  then show ?case\n  proof (cases \"b = 0\")\n    case True\n      then show ?thesis by (cases \"a = 0\") \n        (simp_all add: euclid_ext_0 unit_div mult_ac unit_simps gcd_0)\n    next\n    case False with 1 show ?thesis\n      by (simp add: euclid_ext_non_0 ac_simps split: prod.split prod.split_asm)\n    qed\nqed\n\nlemma euclid_ext_gcd' [simp]:\n  \"euclid_ext a b = (r, s, t) \\<Longrightarrow> t = gcd a b\"\n  by (insert euclid_ext_gcd[of a b], drule (1) subst, simp)\n\nlemma euclid_ext_correct:\n  \"case euclid_ext x y of (s,t,c) \\<Rightarrow> s*x + t*y = c\"\nproof (induct x y rule: euclid_ext.induct)\n  case (1 x y)\n  show ?case\n  proof (cases \"y = 0\")\n    case True\n    then show ?thesis by (simp add: euclid_ext_0 mult_ac)\n  next\n    case False\n    obtain s t c where stc: \"euclid_ext y (x mod y) = (s,t,c)\"\n      by (cases \"euclid_ext y (x mod y)\", blast)\n    from 1 have \"c = s * y + t * (x mod y)\" by (simp add: stc False)\n    also have \"... = t*((x div y)*y + x mod y) + (s - t * (x div y))*y\"\n      by (simp add: algebra_simps) \n    also have \"(x div y)*y + x mod y = x\" using mod_div_equality .\n    finally show ?thesis\n      by (subst euclid_ext.simps, simp add: False stc)\n    qed\nqed\n\nlemma euclid_ext'_correct:\n  \"fst (euclid_ext' a b) * a + snd (euclid_ext' a b) * b = gcd a b\"\nproof-\n  obtain s t c where \"euclid_ext a b = (s,t,c)\"\n    by (cases \"euclid_ext a b\", blast)\n  with euclid_ext_correct[of a b] euclid_ext_gcd[of a b]\n    show ?thesis unfolding euclid_ext'_def by simp\nqed\n\nlemma bezout: \"\\<exists>s t. s * x + t * y = gcd x y\"\n  using euclid_ext'_correct by blast\n\nlemma euclid_ext'_0 [simp]: \"euclid_ext' x 0 = (ring_inv (normalisation_factor x), 0)\" \n  by (simp add: bezw_def euclid_ext'_def euclid_ext_0)\n\nlemma euclid_ext'_non_0: \"y \\<noteq> 0 \\<Longrightarrow> euclid_ext' x y = (snd (euclid_ext' y (x mod y)),\n  fst (euclid_ext' y (x mod y)) - snd (euclid_ext' y (x mod y)) * (x div y))\"\n  by (cases \"euclid_ext y (x mod y)\") \n    (simp add: euclid_ext'_def euclid_ext_non_0)\n  \nend\n\ninstantiation nat :: euclidean_semiring\nbegin\n\ndefinition [simp]:\n  \"euclidean_size_nat = (id :: nat \\<Rightarrow> nat)\"\n\ndefinition [simp]:\n  \"normalisation_factor_nat (n::nat) = (if n = 0 then 0 else 1 :: nat)\"\n\ninstance proof\nqed simp_all\n\nend\n\ninstantiation int :: euclidean_ring\nbegin\n\ndefinition [simp]:\n  \"euclidean_size_int = (nat \\<circ> abs :: int \\<Rightarrow> nat)\"\n\ndefinition [simp]:\n  \"normalisation_factor_int = (sgn :: int \\<Rightarrow> int)\"\n\ninstance proof\n  case goal2 then show ?case by (auto simp add: abs_mult nat_mult_distrib)\nnext\n  case goal3 then show ?case by (simp add: zsgn_def)\nnext\n  case goal5 then show ?case by (auto simp: zsgn_def)\nnext\n  case goal6 then show ?case by (auto split: abs_split simp: zsgn_def)\nqed (auto simp: sgn_times split: abs_split)\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/Number_Theory/Euclidean_Algorithm.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339716830606, "lm_q2_score": 0.8376199572530448, "lm_q1q2_score": 0.7033779334650948}}
{"text": "(*  Title:    HOL/Library/Periodic_Fun.thy\n    Author:   Manuel Eberl, TU M\u00fcnchen\n*)\n\nsection \\<open>Periodic Functions\\<close>\n\ntheory Periodic_Fun\nimports Complex_Main\nbegin\n\ntext \\<open>\n  A locale for periodic functions. The idea is that one proves $f(x + p) = f(x)$\n  for some period $p$ and gets derived results like $f(x - p) = f(x)$ and $f(x + 2p) = f(x)$\n  for free.\n\n  \\<^term>\\<open>g\\<close> and \\<^term>\\<open>gm\\<close> are ``plus/minus k periods'' functions. \n  \\<^term>\\<open>g1\\<close> and \\<^term>\\<open>gn1\\<close> are ``plus/minus one period'' functions.\n  This is useful e.g. if the period is one; the lemmas one gets are then \n  \\<^term>\\<open>f (x + 1) = f x\\<close> instead of \\<^term>\\<open>f (x + 1 * 1) = f x\\<close> etc.\n\\<close>\nlocale periodic_fun = \n  fixes f :: \"('a :: {ring_1}) \\<Rightarrow> 'b\" and g gm :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a\" and g1 gn1 :: \"'a \\<Rightarrow> 'a\"\n  assumes plus_1: \"f (g1 x) = f x\"\n  assumes periodic_arg_plus_0: \"g x 0 = x\"\n  assumes periodic_arg_plus_distrib: \"g x (of_int (m + n)) = g (g x (of_int n)) (of_int m)\"\n  assumes plus_1_eq: \"g x 1 = g1 x\" and minus_1_eq: \"g x (-1) = gn1 x\" \n          and minus_eq: \"g x (-y) = gm x y\"\nbegin\n\nlemma plus_of_nat: \"f (g x (of_nat n)) = f x\"\n  by (induction n) (insert periodic_arg_plus_distrib[of _ 1 \"int n\" for n], \n                    simp_all add: plus_1 periodic_arg_plus_0 plus_1_eq)\n\nlemma minus_of_nat: \"f (gm x (of_nat n)) = f x\"\nproof -\n  have \"f (g x (- of_nat n)) = f (g (g x (- of_nat n)) (of_nat n))\"\n    by (rule plus_of_nat[symmetric])\n  also have \"\\<dots> = f (g (g x (of_int (- of_nat n))) (of_int (of_nat n)))\" by simp\n  also have \"\\<dots> = f x\" \n    by (subst periodic_arg_plus_distrib [symmetric]) (simp add: periodic_arg_plus_0)\n  finally show ?thesis by (simp add: minus_eq)\nqed\n\nlemma plus_of_int: \"f (g x (of_int n)) = f x\"\n  by (induction n) (simp_all add: plus_of_nat minus_of_nat minus_eq del: of_nat_Suc)\n\nlemma minus_of_int: \"f (gm x (of_int n)) = f x\"\n  using plus_of_int[of x \"of_int (-n)\"] by (simp add: minus_eq)\n\nlemma plus_numeral: \"f (g x (numeral n)) = f x\"\n  by (subst of_nat_numeral[symmetric], subst plus_of_nat) (rule refl)\n\nlemma minus_numeral: \"f (gm x (numeral n)) = f x\"\n  by (subst of_nat_numeral[symmetric], subst minus_of_nat) (rule refl)\n\nlemma minus_1: \"f (gn1 x) = f x\"\n  using minus_of_nat[of x 1] by (simp flip: minus_1_eq minus_eq)\n\nlemmas periodic_simps = plus_of_nat minus_of_nat plus_of_int minus_of_int \n                        plus_numeral minus_numeral plus_1 minus_1\n\nend\n\n\ntext \\<open>\n  Specialised case of the \\<^term>\\<open>periodic_fun\\<close> locale for periods that are not 1.\n  Gives lemmas \\<^term>\\<open>f (x - period) = f x\\<close> etc.\n\\<close>\nlocale periodic_fun_simple = \n  fixes f :: \"('a :: {ring_1}) \\<Rightarrow> 'b\" and period :: 'a\n  assumes plus_period: \"f (x + period) = f x\"\nbegin\nsublocale periodic_fun f \"\\<lambda>z x. z + x * period\" \"\\<lambda>z x. z - x * period\" \n  \"\\<lambda>z. z + period\" \"\\<lambda>z. z - period\"\n  by standard (simp_all add: ring_distribs plus_period)\nend\n\n\ntext \\<open>\n  Specialised case of the \\<^term>\\<open>periodic_fun\\<close> locale for period 1.\n  Gives lemmas \\<^term>\\<open>f (x - 1) = f x\\<close> etc.\n\\<close>\nlocale periodic_fun_simple' = \n  fixes f :: \"('a :: {ring_1}) \\<Rightarrow> 'b\"\n  assumes plus_period: \"f (x + 1) = f x\"\nbegin\nsublocale periodic_fun f \"\\<lambda>z x. z + x\" \"\\<lambda>z x. z - x\" \"\\<lambda>z. z + 1\" \"\\<lambda>z. z - 1\"\n  by standard (simp_all add: ring_distribs plus_period)\n\nlemma of_nat: \"f (of_nat n) = f 0\" using plus_of_nat[of 0 n] by simp\nlemma uminus_of_nat: \"f (-of_nat n) = f 0\" using minus_of_nat[of 0 n] by simp\nlemma of_int: \"f (of_int n) = f 0\" using plus_of_int[of 0 n] by simp\nlemma uminus_of_int: \"f (-of_int n) = f 0\" using minus_of_int[of 0 n] by simp\nlemma of_numeral: \"f (numeral n) = f 0\" using plus_numeral[of 0 n] by simp\nlemma of_neg_numeral: \"f (-numeral n) = f 0\" using minus_numeral[of 0 n] by simp\nlemma of_1: \"f 1 = f 0\" using plus_of_nat[of 0 1] by simp\nlemma of_neg_1: \"f (-1) = f 0\" using minus_of_nat[of 0 1] by simp\n\nlemmas periodic_simps' = \n  of_nat uminus_of_nat of_int uminus_of_int of_numeral of_neg_numeral of_1 of_neg_1\n\nend\n\nlemma sin_plus_pi: \"sin ((z :: 'a :: {real_normed_field,banach}) + of_real pi) = - sin z\"\n  by (simp add: sin_add)\n  \nlemma cos_plus_pi: \"cos ((z :: 'a :: {real_normed_field,banach}) + of_real pi) = - cos z\"\n  by (simp add: cos_add)\n\ninterpretation sin: periodic_fun_simple sin \"2 * of_real pi :: 'a :: {real_normed_field,banach}\"\nproof\n  fix z :: 'a\n  have \"sin (z + 2 * of_real pi) = sin (z + of_real pi + of_real pi)\" by (simp add: ac_simps)\n  also have \"\\<dots> = sin z\" by (simp only: sin_plus_pi) simp\n  finally show \"sin (z + 2 * of_real pi) = sin z\" .\nqed\n\ninterpretation cos: periodic_fun_simple cos \"2 * of_real pi :: 'a :: {real_normed_field,banach}\"\nproof\n  fix z :: 'a\n  have \"cos (z + 2 * of_real pi) = cos (z + of_real pi + of_real pi)\" by (simp add: ac_simps)\n  also have \"\\<dots> = cos z\" by (simp only: cos_plus_pi) simp\n  finally show \"cos (z + 2 * of_real pi) = cos z\" .\nqed\n\ninterpretation tan: periodic_fun_simple tan \"2 * of_real pi :: 'a :: {real_normed_field,banach}\"\n  by standard (simp only: tan_def [abs_def] sin.plus_1 cos.plus_1)\n\ninterpretation cot: periodic_fun_simple cot \"2 * of_real pi :: 'a :: {real_normed_field,banach}\"\n  by standard (simp only: cot_def [abs_def] sin.plus_1 cos.plus_1)\n\nlemma cos_eq_neg_periodic_intro:\n  assumes \"x - y = 2*(of_int k)*pi + pi \\<or> x + y = 2*(of_int k)*pi + pi\"\n  shows \"cos x = - cos y\" using assms\nproof\n  assume \"x - y = 2 * (of_int k) * pi + pi\" \n  then show ?thesis\n    using cos.periodic_simps[of \"y+pi\"]\n    by (auto simp add:algebra_simps)\nnext\n  assume \"x + y = 2 * real_of_int k * pi + pi \"\n  then show ?thesis\n    using cos.periodic_simps[of \"-y+pi\"]\n    by (clarsimp simp add: algebra_simps) (smt (verit))\nqed\n\nlemma cos_eq_periodic_intro:\n  assumes \"x - y = 2*(of_int k)*pi \\<or> x + y = 2*(of_int k)*pi\"\n  shows \"cos x = cos y\"\n  by (smt (verit, best) assms cos_eq_neg_periodic_intro cos_minus_pi cos_periodic_pi)\n\nlemma cos_eq_arccos_Ex:\n  \"cos x = y \\<longleftrightarrow> -1\\<le>y \\<and> y\\<le>1 \\<and> (\\<exists>k::int. x = arccos y + 2*k*pi \\<or> x = - arccos y + 2*k*pi)\" (is \"?L=?R\")\nproof\n  assume ?R then show \"cos x = y\"\n    by (metis cos.plus_of_int cos_arccos cos_minus id_apply mult.assoc mult.left_commute of_real_eq_id)\nnext\n  assume L: ?L\n  let ?goal = \"(\\<exists>k::int. x = arccos y + 2*k*pi \\<or> x = - arccos y + 2*k*pi)\"\n  obtain k::int where k: \"-pi < x - k*(2*pi)\" \"x - k*(2*pi) \\<le> pi\"\n    using ceiling_divide_lower [of \"2*pi\" \"x-pi\"] ceiling_divide_upper [of \"2*pi\" \"x-pi\"] \n    by (simp add: divide_simps algebra_simps) (metis mult.commute)\n  have *: \"cos (x - k * 2*pi) = y\"\n    using cos.periodic_simps(3)[of x \"-k\"] L by (auto simp add:field_simps)\n  then have **: ?goal when \"x-k*2*pi \\<ge> 0\"\n    using arccos_cos k that by force\n  then show \"-1\\<le>y \\<and> y\\<le>1 \\<and> ?goal\"\n    using \"*\" arccos_cos2 k(1) by force\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/Library/Periodic_Fun.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.839733955639775, "lm_q2_score": 0.8376199694135332, "lm_q1q2_score": 0.7033779302384936}}
{"text": "theory Missing_Permutations\nimports \n  Missing_Multiset\n  \"~~/src/HOL/Library/Permutations\"\nbegin\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 permutes_vimage: \"f permutes A \\<Longrightarrow> f -` A = A\"\n  by (simp add: bij_vimage_eq_inv_image permutes_bij permutes_image[OF permutes_inv])\n\nlemma permutes_inj_on: \"f permutes S \\<Longrightarrow> inj_on f A\"\n  unfolding permutes_def inj_on_def by auto\n\nlemma inj_on_image: \"inj_on f (\\<Union>A) \\<Longrightarrow> inj_on (op ` f) A\"\n  unfolding inj_on_def by blast\n\nlemma disjoint_image: \"inj_on f (\\<Union>A) \\<Longrightarrow> disjoint A \\<Longrightarrow> disjoint (op ` f ` A)\"\n  unfolding inj_on_def disjoint_def by blast\n\nlemma map_of_permute: \n  assumes \"\\<sigma> permutes fst ` set xs\"\n  shows   \"map_of xs \\<circ> \\<sigma> = map_of (map (\\<lambda>(x,y). (inv \\<sigma> x, y)) xs)\" (is \"_ = map_of (map ?f _)\")\nproof\n  fix x\n  from assms have \"inj \\<sigma>\" \"surj \\<sigma>\" by (simp_all add: permutes_inj permutes_surj)\n  thus \"(map_of xs \\<circ> \\<sigma>) x = map_of (map ?f xs) x\"\n    by (induction xs) (auto simp: inv_f_f surj_f_inv_f)\nqed\n\ndefinition permute_list :: \"(nat \\<Rightarrow> nat) \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where\n  \"permute_list f xs = map (\\<lambda>i. xs ! (f i)) [0..<length xs]\"\n\nlemma permute_list_map: \n  assumes \"f permutes {..<length xs}\"\n  shows   \"permute_list f (map g xs) = map g (permute_list f xs)\"\n  using permutes_in_image[OF assms] by (auto simp: permute_list_def)\n\nlemma permute_list_nth:\n  assumes \"f permutes {..<length xs}\" \"i < length xs\"\n  shows   \"permute_list f xs ! i = xs ! f i\"\n  using permutes_in_image[OF assms(1)] assms(2) \n  by (simp add: permute_list_def)\n\nlemma permute_list_Nil [simp]: \"permute_list f [] = []\"\n  by (simp add: permute_list_def)\n\nlemma length_permute_list [simp]: \"length (permute_list f xs) = length xs\"\n  by (simp add: permute_list_def)\n\nlemma permute_list_compose: \n  assumes \"g permutes {..<length xs}\"\n  shows   \"permute_list (f \\<circ> g) xs = permute_list g (permute_list f xs)\"\n  using assms[THEN permutes_in_image] by (auto simp add: permute_list_def)\n\nlemma permute_list_ident [simp]: \"permute_list (\\<lambda>x. x) xs = xs\"\n  by (simp add: permute_list_def map_nth)\n\nlemma permute_list_id [simp]: \"permute_list id xs = xs\"\n  by (simp add: id_def)\n\nlemma mset_upt [simp]: \"mset [m..<n] = mset_set {m..<n}\"\n  by (induction n) (simp_all add: atLeastLessThanSuc add_ac)\n\nlemma mset_permute_list [simp]:\n  assumes \"f permutes {..<length (xs :: 'a list)}\"\n  shows   \"mset (permute_list f xs) = mset xs\"\nproof (rule multiset_eqI)\n  fix y :: 'a\n  from assms have [simp]: \"f x < length xs \\<longleftrightarrow> x < length xs\" for x\n    using permutes_in_image[OF assms] by auto\n  have \"count (mset (permute_list f xs)) y = \n          card ((\\<lambda>i. xs ! f i) -` {y} \\<inter> {..<length xs})\"\n    by (simp add: permute_list_def mset_map count_image_mset atLeast0LessThan)\n  also have \"(\\<lambda>i. xs ! f i) -` {y} \\<inter> {..<length xs} = f -` {i. i < length xs \\<and> y = xs ! i}\"\n    by auto\n  also from assms have \"card \\<dots> = card {i. i < length xs \\<and> y = xs ! i}\"\n    by (intro card_vimage_inj) (auto simp: permutes_inj permutes_surj)\n  also have \"\\<dots> = count (mset xs) y\" by (simp add: count_mset length_filter_conv_card)\n  finally show \"count (mset (permute_list f xs)) y = count (mset xs) y\" by simp\nqed\n\nlemma set_permute_list [simp]:\n  assumes \"f permutes {..<length xs}\"\n  shows   \"set (permute_list f xs) = set xs\"\n  by (rule mset_eq_setD[OF mset_permute_list]) fact\n\nlemma distinct_permute_list [simp]:\n  assumes \"f permutes {..<length xs}\"\n  shows   \"distinct (permute_list f xs) = distinct xs\"\n  by (simp add: distinct_count_atmost_1 assms)\n\nlemma mset_eq_permutation:\n  assumes mset_eq: \"mset (xs::'a list) = mset ys\"\n  defines [simp]: \"n \\<equiv> length xs\"\n  obtains f where \"f permutes {..<length ys}\" \"permute_list f ys = xs\"\nproof -\n  from mset_eq have [simp]: \"length xs = length ys\"\n    by (rule mset_eq_length)\n  def indices_of \\<equiv> \"\\<lambda>(x::'a) xs. {i. i < length xs \\<and> x = xs ! i}\"\n  have indices_of_subset: \"indices_of x xs \\<subseteq> {..<length xs}\" for x xs\n    unfolding indices_of_def by blast\n  have [simp]: \"finite (indices_of x xs)\" for x xs\n    by (rule finite_subset[OF indices_of_subset]) simp_all\n\n  have \"\\<forall>x\\<in>set xs. \\<exists>f. bij_betw f (indices_of x xs) (indices_of x ys)\"\n  proof\n    fix x\n    from mset_eq have \"count (mset xs) x = count (mset ys) x\" by simp\n    hence \"card (indices_of x xs) = card (indices_of x ys)\"\n      by (simp add: count_mset length_filter_conv_card indices_of_def)\n    thus \"\\<exists>f. bij_betw f (indices_of x xs) (indices_of x ys)\"\n      by (intro finite_same_card_bij) simp_all\n  qed\n  hence \"\\<exists>f. \\<forall>x\\<in>set xs. bij_betw (f x) (indices_of x xs) (indices_of x ys)\"\n    by (rule bchoice)\n  then guess f .. note f = this\n  def g \\<equiv> \"\\<lambda>i. if i < n then f (xs ! i) i else i\"\n\n  have bij_f: \"bij_betw (\\<lambda>i. f (xs ! i) i) (indices_of x xs) (indices_of x ys)\"\n    if x: \"x \\<in> set xs\" for x\n  proof (subst bij_betw_cong)\n    from f x show \"bij_betw (f x) (indices_of x xs) (indices_of x ys)\" by blast\n    fix i assume \"i \\<in> indices_of x xs\"\n    thus \"f (xs ! i) i = f x i\" by (simp add: indices_of_def)\n  qed\n\n  hence \"bij_betw (\\<lambda>i. f (xs ! i) i) (\\<Union>x\\<in>set xs. indices_of x xs) (\\<Union>x\\<in>set xs. indices_of x ys)\"\n    by (intro bij_betw_UNION_disjoint) (auto simp add: disjoint_family_on_def indices_of_def)\n  also have \"(\\<Union>x\\<in>set xs. indices_of x xs) = {..<n}\" by (auto simp: indices_of_def)\n  also from mset_eq have \"set xs = set ys\" by (rule mset_eq_setD) \n  also have \"(\\<Union>x\\<in>set ys. indices_of x ys) = {..<n}\"\n    by (auto simp: indices_of_def set_conv_nth)\n  also have \"bij_betw (\\<lambda>i. f (xs ! i) i) {..<n} {..<n} \\<longleftrightarrow> bij_betw g {..<n} {..<n}\"\n    by (intro bij_betw_cong) (simp_all add: g_def)\n  finally have \"g permutes {..<length ys}\"\n    by (intro bij_imp_permutes refl) (simp_all add: g_def)\n\n  moreover have \"permute_list g ys = xs\" \n  proof (rule sym, intro nth_equalityI allI impI)\n    fix i assume i: \"i < length xs\"\n    from i have \"permute_list g ys ! i = ys ! f (xs ! i) i\"\n      by (simp add: permute_list_def g_def)\n    also from i have \"i \\<in> indices_of (xs ! i) xs\" by (simp add: indices_of_def)\n    with bij_f[of \"xs ! i\"] i have \"f (xs ! i) i \\<in> indices_of (xs ! i) ys\"\n      by (auto simp: bij_betw_def)\n    hence \"ys ! f (xs ! i) i = xs ! i\" by (simp add: indices_of_def)\n    finally show \"xs ! i = permute_list g ys ! i\" ..\n  qed simp_all\n\n  ultimately show ?thesis by (rule that)\nqed\n\nlemma distinct_Ex1: \n  \"distinct xs \\<Longrightarrow> x \\<in> set xs \\<Longrightarrow> (\\<exists>!i. i < length xs \\<and> xs ! i = x)\"\n  by (auto simp: in_set_conv_nth nth_eq_iff_index_eq)\n\nlemma bij_betw_nth:\n  assumes \"distinct xs\" \"A = {..<length xs}\" \"B = set xs\" \n  shows   \"bij_betw (op ! xs) A B\"\n  using assms unfolding bij_betw_def\n  by (auto intro!: inj_on_nth simp: set_conv_nth)\n\nlemma permutes_invI: \n  assumes perm: \"p permutes S\"\n      and inv:  \"\\<And>x. x \\<in> S \\<Longrightarrow> p' (p x) = x\" \n      and outside: \"\\<And>x. x \\<notin> S \\<Longrightarrow> p' x = x\"\n  shows   \"inv p = p'\"\nproof\n  fix x show \"inv p x = p' x\"\n  proof (cases \"x \\<in> S\")\n    assume [simp]: \"x \\<in> S\"\n    from assms have \"p' x = p' (p (inv p x))\" by (simp add: permutes_inverses)\n    also from permutes_inv[OF perm] \n      have \"\\<dots> = inv p x\" by (subst inv) (simp_all add: permutes_in_image)\n    finally show \"inv p x = p' x\" ..\n  qed (insert permutes_inv[OF perm], simp_all add: outside permutes_not_in)\nqed\n\nlemma permute_list_zip: \n  assumes \"f permutes A\" \"A = {..<length xs}\"\n  assumes [simp]: \"length xs = length ys\"\n  shows   \"permute_list f (zip xs ys) = zip (permute_list f xs) (permute_list f ys)\"\nproof -\n  from permutes_in_image[OF assms(1)] assms(2)\n    have [simp]: \"f i < length ys \\<longleftrightarrow> i < length ys\" for i by simp\n  have \"permute_list f (zip xs ys) = map (\\<lambda>i. zip xs ys ! f i) [0..<length ys]\"\n    by (simp_all add: permute_list_def zip_map_map)\n  also have \"\\<dots> = map (\\<lambda>(x, y). (xs ! f x, ys ! f y)) (zip [0..<length ys] [0..<length ys])\"\n    by (intro nth_equalityI) simp_all\n  also have \"\\<dots> = zip (permute_list f xs) (permute_list f ys)\"\n    by (simp_all add: permute_list_def zip_map_map)\n  finally show ?thesis .\nqed\n\n\ndefinition list_permutes where\n  \"list_permutes xs A \\<longleftrightarrow> set (map fst xs) \\<subseteq> A \\<and> set (map snd xs) = set (map fst xs) \\<and> \n     distinct (map fst xs) \\<and> distinct (map snd xs)\"\n\nlemma list_permutesI [simp]:\n  assumes \"set (map fst xs) \\<subseteq> A\" \"set (map snd xs) = set (map fst xs)\" \"distinct (map fst xs)\"\n  shows   \"list_permutes xs A\"\nproof -\n  from assms(2,3) have \"distinct (map snd xs)\"\n    by (intro card_distinct) (simp_all add: distinct_card del: set_map)\n  with assms show ?thesis by (simp add: list_permutes_def)\nqed\n\ndefinition permutation_of_list where\n  \"permutation_of_list xs x = (case map_of xs x of None \\<Rightarrow> x | Some y \\<Rightarrow> y)\"\n\nlemma permutation_of_list_Cons:\n  \"permutation_of_list ((x,y) # xs) x' = (if x = x' then y else permutation_of_list xs x')\"\n  by (simp add: permutation_of_list_def)\n\nfun inverse_permutation_of_list where\n  \"inverse_permutation_of_list [] x = x\"\n| \"inverse_permutation_of_list ((y,x')#xs) x =\n     (if x = x' then y else inverse_permutation_of_list xs x)\"\n\ndeclare inverse_permutation_of_list.simps [simp del]\n\nlemma inj_on_map_of:\n  assumes \"distinct (map snd xs)\"\n  shows   \"inj_on (map_of xs) (set (map fst xs))\"\nproof (rule inj_onI)\n  fix x y assume xy: \"x \\<in> set (map fst xs)\" \"y \\<in> set (map fst xs)\"\n  assume eq: \"map_of xs x = map_of xs y\"\n  from xy obtain x' y' \n    where x'y': \"map_of xs x = Some x'\" \"map_of xs y = Some y'\" \n    by (cases \"map_of xs x\"; cases \"map_of xs y\")\n       (simp_all add: map_of_eq_None_iff)\n  moreover from this x'y' have \"(x,x') \\<in> set xs\" \"(y,y') \\<in> set xs\"\n    by (force dest: map_of_SomeD)+\n  moreover from this eq x'y' have \"x' = y'\" by simp\n  ultimately show \"x = y\" using assms\n    by (force simp: distinct_map dest: inj_onD[of _ _ \"(x,x')\" \"(y,y')\"])\nqed\n\nlemma inj_on_the: \"None \\<notin> A \\<Longrightarrow> inj_on the A\"\n  by (auto simp: inj_on_def option.the_def split: option.splits)\n\nlemma inj_on_map_of':\n  assumes \"distinct (map snd xs)\"\n  shows   \"inj_on (the \\<circ> map_of xs) (set (map fst xs))\"\n  by (intro comp_inj_on inj_on_map_of assms inj_on_the)\n     (force simp: eq_commute[of None] map_of_eq_None_iff)\n\nlemma image_map_of:\n  assumes \"distinct (map fst xs)\"\n  shows   \"map_of xs ` set (map fst xs) = Some ` set (map snd xs)\"\n  using assms by (auto simp: rev_image_eqI)\n\nlemma the_Some_image [simp]: \"the ` Some ` A = A\"\n  by (subst image_image) simp\n\nlemma image_map_of':\n  assumes \"distinct (map fst xs)\"\n  shows   \"(the \\<circ> map_of xs) ` set (map fst xs) = set (map snd xs)\"\n  by (simp only: image_comp [symmetric] image_map_of assms the_Some_image)\n\nlemma permutation_of_list_permutes [simp]:\n  assumes \"list_permutes xs A\"\n  shows   \"permutation_of_list xs permutes A\" (is \"?f permutes _\")\nproof (rule permutes_subset[OF bij_imp_permutes])\n  from assms show \"set (map fst xs) \\<subseteq> A\"\n    by (simp add: list_permutes_def)\n  from assms have \"inj_on (the \\<circ> map_of xs) (set (map fst xs))\" (is ?P)\n    by (intro inj_on_map_of') (simp_all add: list_permutes_def)\n  also have \"?P \\<longleftrightarrow> inj_on ?f (set (map fst xs))\"\n    by (intro inj_on_cong)\n       (auto simp: permutation_of_list_def map_of_eq_None_iff split: option.splits)\n  finally have \"bij_betw ?f (set (map fst xs)) (?f ` set (map fst xs))\"\n    by (rule inj_on_imp_bij_betw)\n  also from assms have \"?f ` set (map fst xs) = (the \\<circ> map_of xs) ` set (map fst xs)\"\n    by (intro image_cong refl)\n       (auto simp: permutation_of_list_def map_of_eq_None_iff split: option.splits)\n  also from assms have \"\\<dots> = set (map fst xs)\" \n    by (subst image_map_of') (simp_all add: list_permutes_def)\n  finally show \"bij_betw ?f (set (map fst xs)) (set (map fst xs))\" .\nqed (force simp: permutation_of_list_def dest!: map_of_SomeD split: option.splits)+\n\nlemma eval_permutation_of_list [simp]:\n  \"permutation_of_list [] x = x\"\n  \"x = x' \\<Longrightarrow> permutation_of_list ((x',y)#xs) x = y\"\n  \"x \\<noteq> x' \\<Longrightarrow> permutation_of_list ((x',y')#xs) x = permutation_of_list xs x\"\n  by (simp_all add: permutation_of_list_def)\n\nlemma eval_inverse_permutation_of_list [simp]:\n  \"inverse_permutation_of_list [] x = x\"\n  \"x = x' \\<Longrightarrow> inverse_permutation_of_list ((y,x')#xs) x = y\"\n  \"x \\<noteq> x' \\<Longrightarrow> inverse_permutation_of_list ((y',x')#xs) x = inverse_permutation_of_list xs x\"\n  by (simp_all add: inverse_permutation_of_list.simps)\n\nlemma permutation_of_list_id:\n  assumes \"x \\<notin> set (map fst xs)\"\n  shows   \"permutation_of_list xs x = x\"\n  using assms by (induction xs) (auto simp: permutation_of_list_Cons)\n\nlemma permutation_of_list_unique':\n  assumes \"distinct (map fst xs)\" \"(x, y) \\<in> set xs\"\n  shows   \"permutation_of_list xs x = y\"\n  using assms by (induction xs) (force simp: permutation_of_list_Cons)+\n\nlemma permutation_of_list_unique:\n  assumes \"list_permutes xs A\" \"(x,y) \\<in> set xs\"\n  shows   \"permutation_of_list xs x = y\"\n  using assms by (intro permutation_of_list_unique') (simp_all add: list_permutes_def)\n\nlemma inverse_permutation_of_list_id:\n  assumes \"x \\<notin> set (map snd xs)\"\n  shows   \"inverse_permutation_of_list xs x = x\"\n  using assms by (induction xs) auto\n\nlemma inverse_permutation_of_list_unique':\n  assumes \"distinct (map snd xs)\" \"(x, y) \\<in> set xs\"\n  shows   \"inverse_permutation_of_list xs y = x\"\n  using assms by (induction xs) (force simp: inverse_permutation_of_list.simps)+\n\nlemma inverse_permutation_of_list_unique:\n  assumes \"list_permutes xs A\" \"(x,y) \\<in> set xs\"\n  shows   \"inverse_permutation_of_list xs y = x\"\n  using assms by (intro inverse_permutation_of_list_unique') (simp_all add: list_permutes_def)\n\nlemma inverse_permutation_of_list_correct:\n  assumes \"list_permutes xs (A :: 'a set)\"\n  shows   \"inverse_permutation_of_list xs = inv (permutation_of_list xs)\"\nproof (rule ext, rule sym, subst permutes_inv_eq)\n  from assms show \"permutation_of_list xs permutes A\" by simp\nnext\n  fix x\n  show \"permutation_of_list xs (inverse_permutation_of_list xs x) = x\"\n  proof (cases \"x \\<in> set (map snd xs)\")\n    case True\n    then obtain y where \"(y, x) \\<in> set xs\" by force\n    with assms show ?thesis\n      by (simp add: inverse_permutation_of_list_unique permutation_of_list_unique)\n  qed (insert assms, auto simp: list_permutes_def\n         inverse_permutation_of_list_id permutation_of_list_id)\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/Missing_Permutations.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8397339596505965, "lm_q2_score": 0.8376199572530448, "lm_q1q2_score": 0.7033779233864628}}
{"text": "(*  Title:      HOL/Library/Sublist_Order.thy\n    Authors:    Peter Lammich, Uni Muenster <peter.lammich@uni-muenster.de>\n                Florian Haftmann, Tobias Nipkow, TU Muenchen\n*)\n\nsection {* Sublist Ordering *}\n\ntheory Sublist_Order\nimports Sublist\nbegin\n\ntext {*\n  This theory defines sublist ordering on lists.\n  A list @{text ys} is a sublist of a list @{text xs},\n  iff one obtains @{text ys} by erasing some elements from @{text xs}.\n*}\n\nsubsection {* Definitions and basic lemmas *}\n\ninstantiation list :: (type) ord\nbegin\n\ndefinition\n  \"(xs :: 'a list) \\<le> ys \\<longleftrightarrow> sublisteq xs ys\"\n\ndefinition\n  \"(xs :: 'a list) < ys \\<longleftrightarrow> xs \\<le> ys \\<and> \\<not> ys \\<le> xs\"\n\ninstance ..\n\nend\n\ninstance list :: (type) order\nproof\n  fix xs ys :: \"'a list\"\n  show \"xs < ys \\<longleftrightarrow> xs \\<le> ys \\<and> \\<not> ys \\<le> xs\" unfolding less_list_def .. \nnext\n  fix xs :: \"'a list\"\n  show \"xs \\<le> xs\" by (simp add: less_eq_list_def)\nnext\n  fix xs ys :: \"'a list\"\n  assume \"xs <= ys\" and \"ys <= xs\"\n  thus \"xs = ys\" by (unfold less_eq_list_def) (rule sublisteq_antisym)\nnext\n  fix xs ys zs :: \"'a list\"\n  assume \"xs <= ys\" and \"ys <= zs\"\n  thus \"xs <= zs\" by (unfold less_eq_list_def) (rule sublisteq_trans)\nqed\n\nlemmas less_eq_list_induct [consumes 1, case_names empty drop take] =\n  list_emb.induct [of \"op =\", folded less_eq_list_def]\nlemmas less_eq_list_drop = list_emb.list_emb_Cons [of \"op =\", folded less_eq_list_def]\nlemmas le_list_Cons2_iff [simp, code] = sublisteq_Cons2_iff [folded less_eq_list_def]\nlemmas le_list_map = sublisteq_map [folded less_eq_list_def]\nlemmas le_list_filter = sublisteq_filter [folded less_eq_list_def]\nlemmas le_list_length = list_emb_length [of \"op =\", folded less_eq_list_def]\n\nlemma less_list_length: \"xs < ys \\<Longrightarrow> length xs < length ys\"\n  by (metis list_emb_length sublisteq_same_length le_neq_implies_less less_list_def less_eq_list_def)\n\nlemma less_list_empty [simp]: \"[] < xs \\<longleftrightarrow> xs \\<noteq> []\"\n  by (metis less_eq_list_def list_emb_Nil order_less_le)\n\nlemma less_list_below_empty [simp]: \"xs < [] \\<longleftrightarrow> False\"\n  by (metis list_emb_Nil less_eq_list_def less_list_def)\n\nlemma less_list_drop: \"xs < ys \\<Longrightarrow> xs < x # ys\"\n  by (unfold less_le less_eq_list_def) (auto)\n\nlemma less_list_take_iff: \"x # xs < x # ys \\<longleftrightarrow> xs < ys\"\n  by (metis sublisteq_Cons2_iff less_list_def less_eq_list_def)\n\nlemma less_list_drop_many: \"xs < ys \\<Longrightarrow> xs < zs @ ys\"\n  by (metis sublisteq_append_le_same_iff sublisteq_drop_many order_less_le self_append_conv2 less_eq_list_def)\n\nlemma less_list_take_many_iff: \"zs @ xs < zs @ ys \\<longleftrightarrow> xs < ys\"\n  by (metis less_list_def less_eq_list_def sublisteq_append')\n\nlemma less_list_rev_take: \"xs @ zs < ys @ zs \\<longleftrightarrow> xs < ys\"\n  by (unfold less_le less_eq_list_def) 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/Library/Sublist_Order.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.835483553488848, "lm_q2_score": 0.8418256512199033, "lm_q1q2_score": 0.7033314864992684}}
{"text": "section \\<open> Dyadic rational numbers \\<close>\n\ntheory Dyadic\n  imports\n    HOL.Transcendental\n  \"HOL-Library.Float\"\n  Lightweight_Cardinals\nbegin\n\ntext \\<open> A dyadic rational is a rational whose denominator is a power of 2. They are precisely the\n  rational numbers that can be encoded in binary. \\<close>\n\ndefinition dyadic :: \"'a::field_char_0 \\<Rightarrow> bool\" where\n\"dyadic x = (\\<exists> a \\<in> \\<int>. \\<exists> b. x = a / 2^b)\"\n\nabbreviation Dyadics :: \"'a::field_char_0 set\" (\"\\<rat>\\<^sub>D\")\nwhere \"\\<rat>\\<^sub>D \\<equiv> {x. dyadic x}\"\n\nlemma dyadic_zero: \"dyadic 0\"\n  by (auto simp add: dyadic_def)\n\nlemma dyadic_one: \"dyadic 1\"\n  by (auto simp add: dyadic_def)\n\nlemma dyadic_plus:\n  assumes \"dyadic x\" \"dyadic y\"\n  shows \"dyadic (x + y)\"\nusing assms\nproof (clarsimp simp add: dyadic_def)\n  fix a1 a2 :: \"'a :: field_char_0\" and b1 b2 :: nat\n  assume as: \"a1 \\<in> \\<int>\" \"a2 \\<in> \\<int>\"\n  have \"a1 / 2 ^ b1 + a2 / 2 ^ b2 = (2 ^ (b2 - b1) * a1 + 2 ^ (b1 - b2) * a2) / 2 ^ max b1 b2\"\n    by (cases \"b1 \\<ge> b2\")\n       (simp_all add: max_absorb1 max_absorb2 divide_add_eq_iff power_diff add_divide_eq_iff mult.commute)\n  moreover from as have \"2 ^ (b2 - b1) * a1 + 2 ^ (b1 - b2) * a2 \\<in> \\<int>\"\n    by (metis Ints_add Ints_mult Ints_of_int Ints_power of_int_numeral)\n  ultimately show \"\\<exists>a\\<in>\\<int>. \\<exists>b. a1 / 2 ^ b1 + a2 / 2 ^ b2 = a / 2 ^ b\"\n    by auto\nqed\n\nlemma dyadic_uminus: \"dyadic x \\<Longrightarrow> dyadic (- x)\"\n  using Ints_minus minus_divide_left by (force simp add: dyadic_def)\n\nlemma dyadic_minus:\n  assumes \"dyadic x\" \"dyadic y\"\n  shows \"dyadic (x - y)\"\nproof -\n  have xy: \"x - y = (x + (- y))\"\n    using diff_conv_add_uminus by blast\n  from assms show ?thesis\n    unfolding xy by (blast intro: dyadic_plus dyadic_uminus)\nqed\n\nlemma dyadic_times:\n  assumes \"dyadic x\" \"dyadic y\"\n  shows \"dyadic (x * y)\"\n  using assms\n  by (auto simp add: dyadic_def, metis Ints_mult power_add)\n\nlemma dyadic_rational: \"dyadic x \\<Longrightarrow> x \\<in> \\<rat>\"\n  by (auto simp add: dyadic_def, metis Ints_def Rats_divide Rats_number_of Rats_of_int Rats_power imageE)\n\nlemma dyadic_sum: \"\\<lbrakk> finite A; \\<forall> i \\<in> A. dyadic (f i) \\<rbrakk> \\<Longrightarrow> dyadic (sum f A)\"\n  by (induct rule: finite_induct, auto intro: dyadic_plus dyadic_zero)\n\nlemma dyadic_div_pow_2: \"x \\<in> \\<int> \\<Longrightarrow> dyadic (x / 2^n)\"\n  by (auto simp add: dyadic_def)\n\nlemma Dyadics_Rats: \"\\<rat>\\<^sub>D \\<subseteq> \\<rat>\"\n  using dyadic_rational by blast\n\nlemma Ints_dyadic: \"\\<int> \\<subseteq> \\<rat>\\<^sub>D\"\n  apply (auto)\n  apply (rename_tac x)\n  apply (simp add: dyadic_def)\n  apply (rule_tac x=\"x\" in bexI)\n  apply (rule_tac x=\"0\" in exI)\n  apply (auto)\ndone\n\nlemma Nats_dyadic: \"\\<nat> \\<subseteq> \\<rat>\\<^sub>D\"\n  by (metis Ints_dyadic Ints_of_nat Nats_cases subset_eq)\n\nlemma Dyadics_countable:\n  \"countable \\<rat>\\<^sub>D\"\n  using Dyadics_Rats countable_rat countable_subset by blast\n\nlemma coprime_power_two: \"b > 0 \\<Longrightarrow> coprime (a::int) (2^b) \\<longleftrightarrow> odd a\"\n  by (induct b arbitrary: a, auto)\n\ntypedef drat = \"{x :: rat. dyadic x}\"\n  by (rule_tac x=\"0\" in exI, auto simp add: dyadic_def)\n\nsetup_lifting type_definition_drat\n\nlift_definition drat_of_int :: \"int \\<Rightarrow> drat\" is rat_of_int\n  apply (rename_tac int)\n  apply (simp add: dyadic_def)\n  apply (rule_tac x=\"rat_of_int int\" in bexI)\n  apply (rule_tac x=\"0\" in exI)\n  apply (auto)\ndone\n\nlift_definition DFract :: \"int \\<Rightarrow> nat \\<Rightarrow> drat\"\nis \"\\<lambda> a b. Fract a (2 ^ b)\"\n  apply (auto simp add: dyadic_def)\n  apply (rename_tac a b)\n  apply (rule_tac x=\"of_int a\" in bexI)\n  apply (rule_tac x=\"b\" in exI)\n  apply (auto simp add: Fract_of_int_quotient)\ndone\n\nlift_definition dfrac_of :: \"drat \\<Rightarrow> int \\<times> nat\" is\n\"\\<lambda> x. (fst (quotient_of x), nat \\<lfloor>log 2 (snd (quotient_of x))\\<rfloor>)\" .\n\ndefinition drat_of_float :: \"float \\<Rightarrow> drat\" where\n\"drat_of_float n =\n  (if (exponent n \\<ge> 0)\n    then drat_of_int (mantissa n * 2^nat (exponent n))\n    else DFract (mantissa n) (nat (- exponent n)))\"\n\ndefinition float_of_drat :: \"drat \\<Rightarrow> float\" where\n\"float_of_drat n = (let (m,e) = dfrac_of n in Float m (- int e))\"\n\nlemma dfrac_of_DFract:\n  assumes \"coprime a (2^b)\"\n  shows \"dfrac_of (DFract a b) = (a, b)\"\nproof (cases \"b = 0\")\n  case True\n  thus ?thesis\n    by (transfer, simp add: quotient_of_Fract)\nnext\n  case False with assms show ?thesis\n    by (transfer, auto simp add: quotient_of_Fract powr_realpow[THEN sym])\nqed\n\nlemma dyadic_Fract: \"dyadic x \\<Longrightarrow> \\<exists> a b. x = Fract a (2^b)\"\n  apply (auto simp add: dyadic_def)\n  apply (erule Ints_cases)\n  apply (rename_tac a b z)\n  apply (rule_tac x=\"z\" in exI)\n  apply (rule_tac x=\"b\" in exI)\n  apply (simp add: Fract_of_int_quotient of_int_power)\ndone\n\nlemma dyadic_FractE: \"\\<lbrakk> dyadic x; \\<And> a b. x = Fract a (2^b) \\<Longrightarrow> P \\<rbrakk> \\<Longrightarrow> P\"\n  using dyadic_Fract by blast\n\nfun tdiv2 :: \"nat \\<Rightarrow> nat\" where\n\"tdiv2 x = (if (odd x \\<or> x = 0) then 0 else Suc (tdiv2 (x div 2)))\"\n\ndeclare tdiv2.simps [simp del]\n\nlemma odd_div_tdiv2:\n  fixes x :: nat\n  assumes \"x > 0\"\n  shows \"odd (x div (2^(tdiv2 x)))\"\n  using assms\n  apply (case_tac \"odd x\")\n  apply (simp add: tdiv2.simps)\n  apply (induct x rule: tdiv2.induct)\n  apply (simp)\n  apply (rename_tac x)\n  apply (case_tac \"even (x div 2)\")\n  apply (metis div_mult2_eq dvd_div_eq_0_iff neq0_conv power.simps(2) tdiv2.simps)\n  apply (simp add: tdiv2.simps)\ndone\n\nlemma tdiv2_mod: \"x mod (2^(tdiv2 x)) = 0\"\n  apply (induct x rule: tdiv2.induct)\n  apply (auto)\n  apply (metis (no_types) comm_monoid_mult_class.mult_1 dvd_imp_mod_0 dvd_triv_left mod_mult2_eq mult_zero_right neq0_conv power.simps(1) power.simps(2) tdiv2.simps)\ndone\n\ntext \\<open> Every number greater than 0 can be expressed as the multiple of a perfect square\n        and an odd number \\<close>\n\nlemma evenE_nat [elim?]:\n  fixes a :: nat\n  assumes \"a > 0\"\n  obtains b n where \"odd b\" \"a = 2^n * b\"\nproof -\n  have \"odd (a div (2^(tdiv2 a)))\"\n    using assms odd_div_tdiv2 by blast\n  moreover have \"a div (2^(tdiv2 a)) * (2^(tdiv2 a)) = a\"\n    using div_mult_mod_eq[of a \"2^(tdiv2 a)\"] by (simp add: tdiv2_mod)\n  ultimately show ?thesis\n    by (metis mult.commute that)\nqed\n\nlemma evenE_int [elim?]:\n  fixes a :: int\n  assumes \"a \\<noteq> 0\"\n  obtains b n where \"odd b\" \"a = 2^n * b\"\nproof (cases \"a \\<ge> 0\")\n  case True\n  then obtain a' :: nat where \"a = int a'\"\n    using nonneg_eq_int by blast\n  moreover obtain b' n' where \"odd b'\" \"a' = 2^n' * b'\"\n    using assms calculation evenE_nat by auto\n  ultimately show ?thesis using that\n    by (metis of_nat_dvd_iff of_nat_mult of_nat_numeral of_nat_power)\nnext\n  case False\n  then obtain a' :: nat where a: \"a = - (int a')\"\n    by (metis int_cases2 of_nat_0_le_iff)\n  moreover obtain b' n' where b: \"odd b'\" \"a' = 2^n' * b'\"\n    using assms calculation evenE_nat by auto\n  ultimately show ?thesis using that\n  proof -\n    have \"int b' * int (2 ^ n') = int a'\"\n      by (simp add: b)\n    then show ?thesis\n      by (metis a b(1) dvd_minus_iff even_of_nat mult.commute mult_minus_right of_nat_numeral of_nat_power that)\n  qed\nqed\n\nlemma rat_of_int_div: \"\\<lbrakk> y dvd x \\<rbrakk> \\<Longrightarrow> rat_of_int x / rat_of_int y = rat_of_int (x div y)\"\n  by (metis Fract_of_int_quotient div_by_1 divide_eq_0_iff dvd_div_mult_self eq_rat(1) gcd_1_int gcd_dvd1 of_int_eq_0_iff of_int_rat zdiv_eq_0_iff)\n\n(* FIXME: This proof can be tidied and shortened *)\n\nlemma dyadic_Fract_0_1_coprime:\n  assumes \"dyadic x\" \"x \\<in> {0<..<1}\"\n  obtains a b where \"x = Fract a (2^b)\" \"coprime a (2^b)\"\nproof -\n  obtain a' b' where x_def: \"x = Fract a' (2 ^ b')\"\n    using assms dyadic_Fract by blast\n  with assms have a'_nz: \"a' > 0\"\n    by (simp add: zero_less_Fract_iff)\n  with assms(2) have \"a' \\<noteq> 0\"\n    by (auto simp add: rat_number_collapse(1))\n  then obtain k n where kn: \"odd k\" \"a' = 2^n * k\" \"k > 0\"\n    by (metis a'_nz evenE_int not_numeral_less_zero power_less_zero_eq zero_less_mult_iff)\n  then have \"x = Fract k (2 ^ (b' - n))\"\n  proof -\n    from kn have tn_dv1: \"(2^n) dvd a'\"\n      by (auto)\n    from assms x_def have \"a' < 2 ^ b'\"\n      by (simp add: Fract_less_one_iff)\n    moreover from kn have \"2 ^ n \\<le> 2 ^ n * k\"\n      by auto\n    ultimately have \"(2^n :: int) < 2^b'\"\n      using kn(2) by (simp only:)\n    hence nb': \"n < b'\"\n      by auto\n    hence tn_dv2: \"(2^n :: int) dvd (2^b')\"\n      by (simp add: le_imp_power_dvd less_imp_le_nat)\n    have \"rat_of_int a' / rat_of_int (2 ^ b') = (rat_of_int a' / rat_of_int (2^n)) / (rat_of_int (2^b') / rat_of_int (2^n))\"\n      by simp\n    also have \"... = rat_of_int (a' div 2^n) / (rat_of_int ((2^b') div (2^n)))\"\n      using rat_of_int_div tn_dv1 tn_dv2 by presburger\n    also from kn have \"... = rat_of_int k / (rat_of_int ((2^b') div (2^n)))\"\n      by simp\n    also have \"... = rat_of_int k / rat_of_int (2 ^ (b' - n))\"\n      by (metis (mono_tags, lifting) dbl_simps(3) eq_numeral_simps(4) less_imp_le_nat nb' of_int_numeral of_int_power power_diff rat_of_int_div tn_dv2)\n    finally show ?thesis\n      by (simp add: Fract_of_int_quotient x_def)\n  qed\n  moreover have \"coprime k (2 ^ (b' - n))\"\n    by (simp add: kn(1))\n  ultimately show ?thesis\n    using that by blast\nqed\n\ncontext field_char_0\nbegin\n\nlift_definition of_drat :: \"drat \\<Rightarrow> 'a\"\n  is \"\\<lambda>x. of_int (fst (quotient_of x)) / of_int (snd (quotient_of x))\" .\n\nend\n\nlemma of_drat_exists:\n  assumes \"x \\<in> \\<rat>\\<^sub>D\"\n  shows \"\\<exists> n. x = of_drat n\"\nproof -\n  from assms obtain a :: int and b :: nat where \"x = (of_int a) / 2^b\"\n    by (auto simp add: dyadic_def, metis Ints_def imageE)\n  thus ?thesis\n    apply (rule_tac x=\"DFract a b\" in exI)\n    apply (simp)\n    apply (transfer)\n    apply (rename_tac x a b)\n    apply (auto simp add: dyadic_def quotient_of_Fract)\n    apply (subgoal_tac \"snd (Rat.normalize (a, 2 ^ b)) \\<noteq> 0\")\n    apply (metis normalize_eq of_int_of_nat_eq of_int_power of_nat_numeral of_rat_rat order_less_irrefl power_eq_0_iff prod.collapse rel_simps(51))\n    apply (metis less_irrefl normalize_denom_pos prod.collapse)\n  done\nqed\n\nlemma drat_cases:\n  \"\\<lbrakk> x \\<in> \\<rat>\\<^sub>D; \\<And> n. x = of_drat n \\<Longrightarrow> P \\<rbrakk> \\<Longrightarrow> P\"\n  using of_drat_exists by blast\n\nlemma gcd_power_two: \"gcd a (2^Suc b) = (if ((a::int) mod 2 = 0) then (2 * gcd (a div 2) (2^b)) else 1)\"\n  apply (auto)\n   apply (subst gcd_mult_distrib_int[THEN sym])\n   apply (auto)\n  apply (force intro: coprime_imp_gcd_eq_1)\ndone\n\ninstantiation drat :: \"{plus,minus,uminus,times,one,zero}\"\nbegin\n  lift_definition zero_drat :: drat is 0\n    by (fact dyadic_zero)\n  lift_definition one_drat :: drat is 1\n    by (fact dyadic_one)\n  lift_definition plus_drat :: \"drat \\<Rightarrow> drat \\<Rightarrow> drat\" is \"(+)\"\n    by (fact dyadic_plus)\n  lift_definition minus_drat :: \"drat \\<Rightarrow> drat \\<Rightarrow> drat\" is \"(-)\"\n    by (fact dyadic_minus)\n  lift_definition uminus_drat :: \"drat \\<Rightarrow> drat\" is \"uminus\"\n    by (fact dyadic_uminus)\n  lift_definition times_drat :: \"drat \\<Rightarrow> drat \\<Rightarrow> drat\" is \"times\"\n    by (fact dyadic_times)\ninstance ..\nend\n\ninstance drat :: idom\n  by (intro_classes, (transfer, auto simp add: distrib_left distrib_right)+)\n\ninstantiation drat :: linorder\nbegin\n  lift_definition less_eq_drat :: \"drat \\<Rightarrow> drat \\<Rightarrow> bool\" is \"(\\<le>)\" .\n  lift_definition less_drat :: \"drat \\<Rightarrow> drat \\<Rightarrow> bool\" is \"(<)\" .\ninstance\n  by (intro_classes, (transfer, auto)+)\nend\n\ninstantiation drat :: linordered_idom\nbegin\n  lift_definition sgn_drat :: \"drat \\<Rightarrow> drat\" is sgn\n    apply (transfer, auto simp add: dyadic_def sgn_rat_def)\n    apply (rule_tac x=\"-1\" in bexI, rule_tac x=\"0\" in exI, auto)\n  done\n  lift_definition abs_drat :: \"drat \\<Rightarrow> drat\" is abs\n    apply (transfer, auto simp add: dyadic_def abs_rat_def)\n    using Ints_minus minus_divide_left apply blast\n  done\n\ninstance\n  by (intro_classes, (transfer, auto)+)\nend\n\nlemma of_drat_0: \"of_drat 0 = 0\"\n  by (transfer, simp)\n\nlemma of_drat_1: \"of_drat 1 = 1\"\n  by (transfer, simp)\n\nlemma quotient_of_div_simp:\n  \"of_int (fst (quotient_of x)) / of_int (snd (quotient_of x)) = of_rat x\"\n  by (metis (mono_tags, lifting) of_rat_divide of_rat_of_int_eq prod.collapse quotient_of_div)\n\nlemma dyadic_of_rat: \"dyadic x \\<Longrightarrow> dyadic (of_rat x)\"\n  apply (auto simp add: dyadic_def)\n  apply (rename_tac a b)\n  apply (rule_tac x=\"of_rat a\" in bexI)\n  apply (rule_tac x=\"b\" in exI)\n  apply (simp add: of_rat_divide of_rat_power)\n  apply (metis Ints_cases Ints_of_int of_rat_of_int_eq)\ndone\n\nlemma dyadic_of_drat: \"dyadic (of_drat x)\"\n  by (transfer, simp add: quotient_of_div_simp dyadic_of_rat)\n\nlemma of_drat_less_eq:\n  \"(of_drat x :: 'a::{linordered_field}) \\<le> of_drat y \\<longleftrightarrow> x \\<le> y\"\n  by (transfer, auto simp add: of_rat_less_eq quotient_of_div_simp)\n\nlemma of_drat_less:\n  \"(of_drat x :: 'a::{linordered_field}) < of_drat y \\<longleftrightarrow> x < y\"\n  by (transfer, auto simp add: of_rat_less quotient_of_div_simp)\n\nlemma of_drat_0_1:\n  \"(of_drat x :: 'a::{linordered_field}) \\<in> {0<..<1} \\<longleftrightarrow> x \\<in> {0<..<1}\"\n  by (auto) (metis of_drat_0 of_drat_less, metis of_drat_1 of_drat_less)+\n\nlemma drat_0_1_induct:\n  assumes \"x \\<in> {0<..<1}\" \"\\<And> a b. coprime a (2^b) \\<Longrightarrow> P (DFract a b)\"\n  shows \"P x\"\nproof -\n  from assms(1) have \"(of_drat x :: rat) \\<in> {0<..<1}\"\n    by (auto, metis of_drat_0 of_drat_less, metis of_drat_1 of_drat_less)\n  then obtain a b where \"of_drat x = Fract a (2^b)\" \"coprime a (2^b)\"\n    using dyadic_Fract_0_1_coprime dyadic_of_drat by blast\n  moreover hence \"x = DFract a b\"\n    by (transfer, simp add: quotient_of_div_simp)\n  ultimately show ?thesis\n    using assms(2) by blast\nqed\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/Dyadic.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8418256631249077, "lm_q2_score": 0.8354835330070839, "lm_q1q2_score": 0.7033314792036292}}
{"text": "section \\<open>Complex Path Integrals and Cauchy's Integral Theorem\\<close>\n\ntext\\<open>By John Harrison et al.  Ported from HOL Light by L C Paulson (2015)\\<close>\n\ntheory Cauchy_Integral_Theorem\nimports\n  \"HOL-Analysis.Analysis\"\n  Contour_Integration\nbegin\n\nlemma leibniz_rule_holomorphic:\n  fixes f::\"complex \\<Rightarrow> 'b::euclidean_space \\<Rightarrow> complex\"\n  assumes \"\\<And>x t. x \\<in> U \\<Longrightarrow> t \\<in> cbox a b \\<Longrightarrow> ((\\<lambda>x. f x t) has_field_derivative fx x t) (at x within U)\"\n  assumes \"\\<And>x. x \\<in> U \\<Longrightarrow> (f x) integrable_on cbox a b\"\n  assumes \"continuous_on (U \\<times> (cbox a b)) (\\<lambda>(x, t). fx x t)\"\n  assumes \"convex U\"\n  shows \"(\\<lambda>x. integral (cbox a b) (f x)) holomorphic_on U\"\n  using leibniz_rule_field_differentiable[OF assms(1-3) _ assms(4)]\n  by (auto simp: holomorphic_on_def)\n\nlemma Ln_measurable [measurable]: \"Ln \\<in> measurable borel borel\"\nproof -\n  have *: \"Ln (-of_real x) = of_real (ln x) + \\<i> * pi\" if \"x > 0\" for x\n    using that by (subst Ln_minus) (auto simp: Ln_of_real)\n  have **: \"Ln (of_real x) = of_real (ln (-x)) + \\<i> * pi\" if \"x < 0\" for x\n    using *[of \"-x\"] that by simp\n  have cont: \"(\\<lambda>x. indicat_real (- \\<real>\\<^sub>\\<le>\\<^sub>0) x *\\<^sub>R Ln x) \\<in> borel_measurable borel\"\n    by (intro borel_measurable_continuous_on_indicator continuous_intros) auto\n  have \"(\\<lambda>x. if x \\<in> \\<real>\\<^sub>\\<le>\\<^sub>0 then ln (-Re x) + \\<i> * pi else indicator (-\\<real>\\<^sub>\\<le>\\<^sub>0) x *\\<^sub>R Ln x) \\<in> borel \\<rightarrow>\\<^sub>M borel\"\n    (is \"?f \\<in> _\") by (rule measurable_If_set[OF _ cont]) auto\n  hence \"(\\<lambda>x. if x = 0 then Ln 0 else ?f x) \\<in> borel \\<rightarrow>\\<^sub>M borel\" by measurable\n  also have \"(\\<lambda>x. if x = 0 then Ln 0 else ?f x) = Ln\"\n    by (auto simp: fun_eq_iff ** nonpos_Reals_def)\n  finally show ?thesis .\nqed\n\nlemma powr_complex_measurable [measurable]:\n  assumes [measurable]: \"f \\<in> measurable M borel\" \"g \\<in> measurable M borel\"\n  shows   \"(\\<lambda>x. f x powr g x :: complex) \\<in> measurable M borel\"\n  using assms by (simp add: powr_def) \n\ntext\\<open>The special case of midpoints used in the main quadrisection\\<close>\n\nlemma has_contour_integral_midpoint:\n  assumes \"(f has_contour_integral i) (linepath a (midpoint a b))\"\n          \"(f has_contour_integral j) (linepath (midpoint a b) b)\"\n    shows \"(f has_contour_integral (i + j)) (linepath a b)\"\nproof (rule has_contour_integral_split)\n  show \"midpoint a b - a = (1/2) *\\<^sub>R (b - a)\"\n  using assms by (auto simp: midpoint_def scaleR_conv_of_real)\nqed (use assms in auto)\n\nlemma contour_integral_midpoint:\n  assumes \"continuous_on (closed_segment a b) f\"\n  shows \"contour_integral (linepath a b) f =\n         contour_integral (linepath a (midpoint a b)) f + contour_integral (linepath (midpoint a b) b) f\"\nproof (rule contour_integral_split)\n  show \"midpoint a b - a = (1/2) *\\<^sub>R (b - a)\"\n  using assms by (auto simp: midpoint_def scaleR_conv_of_real)\nqed (use assms in auto)\n\ntext\\<open>A couple of special case lemmas that are useful below\\<close>\n\nlemma triangle_linear_has_chain_integral:\n    \"((\\<lambda>x. m*x + d) has_contour_integral 0) (linepath a b +++ linepath b c +++ linepath c a)\"\nproof (rule Cauchy_theorem_primitive)\n  show \"\\<And>x. x \\<in> UNIV \\<Longrightarrow> ((\\<lambda>x. m / 2 * x\\<^sup>2 + d * x) has_field_derivative m * x + d) (at x)\"\n    by (auto intro!: derivative_eq_intros)\nqed auto\n\nlemma has_chain_integral_chain_integral3:\n  assumes \"(f has_contour_integral i) (linepath a b +++ linepath b c +++ linepath c d)\" \n           (is \"(f has_contour_integral i) ?g\")\n  shows \"contour_integral (linepath a b) f + contour_integral (linepath b c) f + contour_integral (linepath c d) f = i\"\n       (is \"?lhs = _\")\nproof -\n  have \"f contour_integrable_on ?g\"\n    using assms contour_integrable_on_def by blast\n  then have \"?lhs = contour_integral ?g f\"\n    by (simp add: valid_path_join has_contour_integral_integrable)\n  then show ?thesis\n    using assms contour_integral_unique by blast\nqed\n\nlemma has_chain_integral_chain_integral4:\n  assumes \"(f has_contour_integral i) (linepath a b +++ linepath b c +++ linepath c d +++ linepath d e)\" \n           (is \"(f has_contour_integral i) ?g\")\n  shows \"contour_integral (linepath a b) f + contour_integral (linepath b c) f + contour_integral (linepath c d) f + contour_integral (linepath d e) f = i\"\n       (is \"?lhs = _\")\nproof -\n  have \"f contour_integrable_on ?g\"\n    using assms contour_integrable_on_def by blast\n  then have \"?lhs = contour_integral ?g f\"\n    by (simp add: valid_path_join has_contour_integral_integrable)\n  then show ?thesis\n    using assms contour_integral_unique by blast\nqed\n\nsubsection\\<^marker>\\<open>tag unimportant\\<close> \\<open>The key quadrisection step\\<close>\n\nlemma norm_sum_half:\n  assumes \"norm(a + b) \\<ge> e\"\n    shows \"norm a \\<ge> e/2 \\<or> norm b \\<ge> e/2\"\nproof -\n  have \"e \\<le> norm (- a - b)\"\n    by (simp add: add.commute assms norm_minus_commute)\n  thus ?thesis\n    using norm_triangle_ineq4 order_trans by fastforce\nqed\n\nlemma norm_sum_lemma:\n  assumes \"e \\<le> norm (a + b + c + d)\"\n    shows \"e / 4 \\<le> norm a \\<or> e / 4 \\<le> norm b \\<or> e / 4 \\<le> norm c \\<or> e / 4 \\<le> norm d\"\nproof -\n  have \"e \\<le> norm ((a + b) + (c + d))\" using assms\n    by (simp add: algebra_simps)\n  then show ?thesis\n    by (auto dest!: norm_sum_half)\nqed\n\nlemma Cauchy_theorem_quadrisection:\n  assumes f: \"continuous_on (convex hull {a,b,c}) f\"\n      and dist: \"dist a b \\<le> K\" \"dist b c \\<le> K\" \"dist c a \\<le> K\"\n      and e: \"e * K^2 \\<le>\n              norm (contour_integral(linepath a b) f + contour_integral(linepath b c) f + contour_integral(linepath c a) f)\"\n  shows \"\\<exists>a' b' c'.\n           a' \\<in> convex hull {a,b,c} \\<and> b' \\<in> convex hull {a,b,c} \\<and> c' \\<in> convex hull {a,b,c} \\<and>\n           dist a' b' \\<le> K/2  \\<and>  dist b' c' \\<le> K/2  \\<and>  dist c' a' \\<le> K/2  \\<and>\n           e * (K/2)^2 \\<le> norm(contour_integral(linepath a' b') f + contour_integral(linepath b' c') f + contour_integral(linepath c' a') f)\"\n         (is \"\\<exists>x y z. ?\\<Phi> x y z\")\nproof -\n  note divide_le_eq_numeral1 [simp del]\n  define a' where \"a' = midpoint b c\"\n  define b' where \"b' = midpoint c a\"\n  define c' where \"c' = midpoint a b\"\n  have fabc: \"continuous_on (closed_segment a b) f\" \"continuous_on (closed_segment b c) f\" \"continuous_on (closed_segment c a) f\"\n    using f continuous_on_subset segments_subset_convex_hull by metis+\n  have fcont': \"continuous_on (closed_segment c' b') f\"\n               \"continuous_on (closed_segment a' c') f\"\n               \"continuous_on (closed_segment b' a') f\"\n    unfolding a'_def b'_def c'_def\n    by (rule continuous_on_subset [OF f],\n           metis midpoints_in_convex_hull convex_hull_subset hull_subset insert_subset segment_convex_hull)+\n  define pathint where \"pathint x y \\<equiv> contour_integral(linepath x y) f\" for x y\n  have *: \"pathint a b + pathint b c + pathint c a =\n          (pathint a c' + pathint c' b' + pathint b' a) +\n          (pathint a' c' + pathint c' b + pathint b a') +\n          (pathint a' c + pathint c b' + pathint b' a') +\n          (pathint a' b' + pathint b' c' + pathint c' a')\"\n    unfolding pathint_def\n    by (simp add: fcont' contour_integral_reverse_linepath) (simp add: a'_def b'_def c'_def contour_integral_midpoint fabc)\n  have [simp]: \"\\<And>x y. cmod (x * 2 - y * 2) = cmod (x - y) * 2\"\n    by (metis left_diff_distrib mult.commute norm_mult_numeral1)\n  have [simp]: \"\\<And>x y. cmod (x - y) = cmod (y - x)\"\n    by (simp add: norm_minus_commute)\n  consider \"e * K\\<^sup>2 / 4 \\<le> cmod (pathint a c' + pathint c' b' + pathint b' a)\" |\n           \"e * K\\<^sup>2 / 4 \\<le> cmod (pathint a' c' + pathint c' b + pathint b a')\" |\n           \"e * K\\<^sup>2 / 4 \\<le> cmod (pathint a' c + pathint c b' + pathint b' a')\" |\n           \"e * K\\<^sup>2 / 4 \\<le> cmod (pathint a' b' + pathint b' c' + pathint c' a')\"\n    using assms by (metis \"*\" norm_sum_lemma pathint_def)\n  then show ?thesis\n  proof cases\n    case 1 then have \"?\\<Phi> a c' b'\"\n      using assms unfolding pathint_def [symmetric]\n      apply (clarsimp simp: c'_def b'_def midpoints_in_convex_hull hull_subset [THEN subsetD])\n      apply (auto simp: midpoint_def dist_norm scaleR_conv_of_real field_split_simps)\n      done\n    then show ?thesis by blast\n  next\n    case 2 then  have \"?\\<Phi> a' c' b\"\n      using assms unfolding pathint_def [symmetric]\n      apply (clarsimp simp: a'_def c'_def midpoints_in_convex_hull hull_subset [THEN subsetD])\n      apply (auto simp: midpoint_def dist_norm scaleR_conv_of_real field_split_simps)\n      done\n    then show ?thesis by blast\n  next\n    case 3 then have \"?\\<Phi> a' c b'\"\n      using assms unfolding pathint_def [symmetric]\n      apply (clarsimp simp: a'_def b'_def midpoints_in_convex_hull hull_subset [THEN subsetD])\n      apply (auto simp: midpoint_def dist_norm scaleR_conv_of_real field_split_simps)\n      done\n    then show ?thesis by blast\n  next\n    case 4 then have \"?\\<Phi> a' b' c'\"\n      using assms unfolding pathint_def [symmetric]\n      apply (clarsimp simp: a'_def c'_def b'_def midpoints_in_convex_hull hull_subset [THEN subsetD])\n      apply (auto simp: midpoint_def dist_norm scaleR_conv_of_real field_split_simps)\n      done\n    then show ?thesis by blast\n  qed\nqed\n\nsubsection\\<^marker>\\<open>tag unimportant\\<close> \\<open>Cauchy's theorem for triangles\\<close>\n\nlemma triangle_points_closer:\n  fixes a::complex\n  shows \"\\<lbrakk>x \\<in> convex hull {a,b,c};  y \\<in> convex hull {a,b,c}\\<rbrakk>\n         \\<Longrightarrow> norm(x - y) \\<le> norm(a - b) \\<or>\n             norm(x - y) \\<le> norm(b - c) \\<or>\n             norm(x - y) \\<le> norm(c - a)\"\n  using simplex_extremal_le [of \"{a,b,c}\"]\n  by (auto simp: norm_minus_commute)\n\n\nlemma holomorphic_point_small_triangle:\n  assumes x: \"x \\<in> S\"\n      and f: \"continuous_on S f\"\n      and cd: \"f field_differentiable (at x within S)\"\n      and e: \"0 < e\"\n    shows \"\\<exists>k>0. \\<forall>a b c. dist a b \\<le> k \\<and> dist b c \\<le> k \\<and> dist c a \\<le> k \\<and>\n              x \\<in> convex hull {a,b,c} \\<and> convex hull {a,b,c} \\<subseteq> S\n              \\<longrightarrow> norm(contour_integral(linepath a b) f + contour_integral(linepath b c) f +\n                       contour_integral(linepath c a) f)\n                  \\<le> e*(dist a b + dist b c + dist c a)^2\"\n           (is \"\\<exists>k>0. \\<forall>a b c. _ \\<longrightarrow> ?normle a b c\")\nproof -\n  have le_of_3: \"\\<And>a x y z. \\<lbrakk>0 \\<le> x*y; 0 \\<le> x*z; 0 \\<le> y*z; a \\<le> (e*(x + y + z))*x + (e*(x + y + z))*y + (e*(x + y + z))*z\\<rbrakk>\n                     \\<Longrightarrow> a \\<le> e*(x + y + z)^2\"\n    by (simp add: algebra_simps power2_eq_square)\n  have disj_le: \"\\<lbrakk>x \\<le> a \\<or> x \\<le> b \\<or> x \\<le> c; 0 \\<le> a; 0 \\<le> b; 0 \\<le> c\\<rbrakk> \\<Longrightarrow> x \\<le> a + b + c\"\n             for x::real and a b c\n    by linarith\n  have fabc: \"f contour_integrable_on linepath a b\" \"f contour_integrable_on linepath b c\" \"f contour_integrable_on linepath c a\"\n              if \"convex hull {a, b, c} \\<subseteq> S\" for a b c\n    using segments_subset_convex_hull that\n    by (metis continuous_on_subset f contour_integrable_continuous_linepath)+\n  note path_bound = has_contour_integral_bound_linepath [simplified norm_minus_commute, OF has_contour_integral_integral]\n  { fix f' a b c d\n    assume d: \"0 < d\"\n       and f': \"\\<And>y. \\<lbrakk>cmod (y - x) \\<le> d; y \\<in> S\\<rbrakk> \\<Longrightarrow> cmod (f y - f x - f' * (y - x)) \\<le> e * cmod (y - x)\"\n       and le: \"cmod (a - b) \\<le> d\" \"cmod (b - c) \\<le> d\" \"cmod (c - a) \\<le> d\"\n       and xc: \"x \\<in> convex hull {a, b, c}\"\n       and S: \"convex hull {a, b, c} \\<subseteq> S\"\n    have pa: \"contour_integral (linepath a b) f + contour_integral (linepath b c) f + contour_integral (linepath c a) f =\n              contour_integral (linepath a b) (\\<lambda>y. f y - f x - f' * (y-x)) +\n              contour_integral (linepath b c) (\\<lambda>y. f y - f x - f' * (y-x)) +\n              contour_integral (linepath c a) (\\<lambda>y. f y - f x - f' * (y-x))\"\n      apply (simp add: contour_integral_diff contour_integral_lmul contour_integrable_lmul contour_integrable_diff fabc [OF S])\n      apply (simp add: field_simps)\n      done\n    { fix y\n      assume yc: \"y \\<in> convex hull {a,b,c}\"\n      have \"cmod (f y - f x - f' * (y - x)) \\<le> e*norm(y - x)\"\n      proof (rule f')\n        show \"cmod (y - x) \\<le> d\"\n          by (metis triangle_points_closer [OF xc yc] le norm_minus_commute order_trans)\n      qed (use S yc in blast)\n      also have \"\\<dots> \\<le> e * (cmod (a - b) + cmod (b - c) + cmod (c - a))\"\n        by (simp add: yc e xc disj_le [OF triangle_points_closer])\n      finally have \"cmod (f y - f x - f' * (y - x)) \\<le> e * (cmod (a - b) + cmod (b - c) + cmod (c - a))\" .\n    } note cm_le = this\n    have \"?normle a b c\"\n      unfolding dist_norm pa\n      using f' xc S e\n      apply (intro le_of_3 norm_triangle_le add_mono path_bound)\n      apply (simp_all add: contour_integral_diff contour_integral_lmul contour_integrable_lmul contour_integrable_diff fabc)\n      apply (blast intro: cm_le elim: dest: segments_subset_convex_hull [THEN subsetD])+\n      done\n  } note * = this\n  show ?thesis\n    using cd e\n    apply (simp add: field_differentiable_def has_field_derivative_def has_derivative_within_alt approachable_lt_le2 Ball_def)\n    apply (clarify dest!: spec mp)\n    using * unfolding dist_norm\n    apply blast\n    done\nqed\n\n\ntext\\<open>Hence the most basic theorem for a triangle.\\<close>\n\nlocale Chain =\n  fixes x0 At Follows\n  assumes At0: \"At x0 0\"\n      and AtSuc: \"\\<And>x n. At x n \\<Longrightarrow> \\<exists>x'. At x' (Suc n) \\<and> Follows x' x\"\nbegin\n  primrec f where\n    \"f 0 = x0\"\n  | \"f (Suc n) = (SOME x. At x (Suc n) \\<and> Follows x (f n))\"\n\n  lemma At: \"At (f n) n\"\n  proof (induct n)\n    case 0 show ?case\n      by (simp add: At0)\n  next\n    case (Suc n) show ?case\n      by (metis (no_types, lifting) AtSuc [OF Suc] f.simps(2) someI_ex)\n  qed\n\n  lemma Follows: \"Follows (f(Suc n)) (f n)\"\n    by (metis (no_types, lifting) AtSuc [OF At [of n]] f.simps(2) someI_ex)\n\n  declare f.simps(2) [simp del]\nend\n\nlemma Chain3:\n  assumes At0: \"At x0 y0 z0 0\"\n      and AtSuc: \"\\<And>x y z n. At x y z n \\<Longrightarrow> \\<exists>x' y' z'. At x' y' z' (Suc n) \\<and> Follows x' y' z' x y z\"\n  obtains f g h where\n    \"f 0 = x0\" \"g 0 = y0\" \"h 0 = z0\"\n                      \"\\<And>n. At (f n) (g n) (h n) n\"\n                       \"\\<And>n. Follows (f(Suc n)) (g(Suc n)) (h(Suc n)) (f n) (g n) (h n)\"\nproof -\n  interpret three: Chain \"(x0,y0,z0)\" \"\\<lambda>(x,y,z). At x y z\" \"\\<lambda>(x',y',z'). \\<lambda>(x,y,z). Follows x' y' z' x y z\"\n  proof qed (use At0 AtSuc in auto)\n  show ?thesis\n  proof\n    show \"\\<And>n. Follows (fst (three.f (Suc n))) (fst (snd (three.f (Suc n))))\n                      (snd (snd (three.f (Suc n)))) (fst (three.f n))\n                     (fst (snd (three.f n))) (snd (snd (three.f n)))\"\n         \"\\<And>n. At (fst (three.f n)) (fst (snd (three.f n))) (snd (snd (three.f n))) n\"\n      using three.At three.Follows\n      by (simp_all add: split_beta')\n  qed auto\nqed\n\n\nproposition\\<^marker>\\<open>tag unimportant\\<close> Cauchy_theorem_triangle:\n  assumes \"f holomorphic_on (convex hull {a,b,c})\"\n    shows \"(f has_contour_integral 0) (linepath a b +++ linepath b c +++ linepath c a)\"\nproof -\n  have contf: \"continuous_on (convex hull {a,b,c}) f\"\n    by (metis assms holomorphic_on_imp_continuous_on)\n  let ?pathint = \"\\<lambda>x y. contour_integral(linepath x y) f\"\n  { fix y::complex\n    assume fy: \"(f has_contour_integral y) (linepath a b +++ linepath b c +++ linepath c a)\"\n       and ynz: \"y \\<noteq> 0\"\n    define K where \"K = 1 + max (dist a b) (max (dist b c) (dist c a))\"\n    define e where \"e = norm y / K^2\"\n    have K1: \"K \\<ge> 1\"  by (simp add: K_def max.coboundedI1)\n    then have K: \"K > 0\" by linarith\n    have [iff]: \"dist a b \\<le> K\" \"dist b c \\<le> K\" \"dist c a \\<le> K\"\n      by (simp_all add: K_def)\n    have e: \"e > 0\"\n      unfolding e_def using ynz K1 by simp\n    define At where \"At x y z n \\<longleftrightarrow>\n        convex hull {x,y,z} \\<subseteq> convex hull {a,b,c} \\<and>\n        dist x y \\<le> K/2^n \\<and> dist y z \\<le> K/2^n \\<and> dist z x \\<le> K/2^n \\<and>\n        norm(?pathint x y + ?pathint y z + ?pathint z x) \\<ge> e*(K/2^n)^2\"\n      for x y z n\n    have At0: \"At a b c 0\"\n      using fy\n      by (simp add: At_def e_def has_chain_integral_chain_integral3)\n    { fix x y z n\n      assume At: \"At x y z n\"\n      then have contf': \"continuous_on (convex hull {x,y,z}) f\"\n        using contf At_def continuous_on_subset by metis\n      have \"\\<exists>x' y' z'. At x' y' z' (Suc n) \\<and> convex hull {x',y',z'} \\<subseteq> convex hull {x,y,z}\"\n        using At Cauchy_theorem_quadrisection [OF contf', of \"K/2^n\" e]\n        apply (simp add: At_def algebra_simps)\n        apply (meson convex_hull_subset empty_subsetI insert_subset subsetCE)\n        done\n    } note AtSuc = this\n    obtain fa fb fc\n      where f0 [simp]: \"fa 0 = a\" \"fb 0 = b\" \"fc 0 = c\"\n        and cosb: \"\\<And>n. convex hull {fa n, fb n, fc n} \\<subseteq> convex hull {a,b,c}\"\n        and dist: \"\\<And>n. dist (fa n) (fb n) \\<le> K/2^n\"\n                  \"\\<And>n. dist (fb n) (fc n) \\<le> K/2^n\"\n                  \"\\<And>n. dist (fc n) (fa n) \\<le> K/2^n\"\n        and no: \"\\<And>n. norm(?pathint (fa n) (fb n) +\n                           ?pathint (fb n) (fc n) +\n                           ?pathint (fc n) (fa n)) \\<ge> e * (K/2^n)^2\"\n        and conv_le: \"\\<And>n. convex hull {fa(Suc n), fb(Suc n), fc(Suc n)} \\<subseteq> convex hull {fa n, fb n, fc n}\"\n      by (rule Chain3 [of At, OF At0 AtSuc]) (auto simp: At_def)\n    obtain x where x: \"\\<And>n. x \\<in> convex hull {fa n, fb n, fc n}\"\n    proof (rule bounded_closed_nest)\n      show \"\\<And>n. closed (convex hull {fa n, fb n, fc n})\"\n        by (simp add: compact_imp_closed finite_imp_compact_convex_hull)\n      show \"\\<And>m n. m \\<le> n \\<Longrightarrow> convex hull {fa n, fb n, fc n} \\<subseteq> convex hull {fa m, fb m, fc m}\"\n        by (erule transitive_stepwise_le) (auto simp: conv_le)\n    qed (fastforce intro: finite_imp_bounded_convex_hull)+\n    then have xin: \"x \\<in> convex hull {a,b,c}\"\n      using assms f0 by blast\n    then have fx: \"f field_differentiable at x within (convex hull {a,b,c})\"\n      using assms holomorphic_on_def by blast\n    { fix k n\n      assume k: \"0 < k\"\n         and le:\n            \"\\<And>x' y' z'.\n               \\<lbrakk>dist x' y' \\<le> k; dist y' z' \\<le> k; dist z' x' \\<le> k;\n                x \\<in> convex hull {x',y',z'};\n                convex hull {x',y',z'} \\<subseteq> convex hull {a,b,c}\\<rbrakk>\n               \\<Longrightarrow>\n               cmod (?pathint x' y' + ?pathint y' z' + ?pathint z' x') * 10\n                     \\<le> e * (dist x' y' + dist y' z' + dist z' x')\\<^sup>2\"\n         and Kk: \"K / k < 2 ^ n\"\n      have \"K / 2 ^ n < k\" using Kk k\n        by (auto simp: field_simps)\n      then have DD: \"dist (fa n) (fb n) \\<le> k\" \"dist (fb n) (fc n) \\<le> k\" \"dist (fc n) (fa n) \\<le> k\"\n        using dist [of n]  k\n        by linarith+\n      have dle: \"(dist (fa n) (fb n) + dist (fb n) (fc n) + dist (fc n) (fa n))\\<^sup>2\n               \\<le> (3 * K / 2 ^ n)\\<^sup>2\"\n        using dist [of n] e K\n        by (simp add: abs_le_square_iff [symmetric])\n      have less10: \"\\<And>x y::real. 0 < x \\<Longrightarrow> y \\<le> 9*x \\<Longrightarrow> y < x*10\"\n        by linarith\n      have \"e * (dist (fa n) (fb n) + dist (fb n) (fc n) + dist (fc n) (fa n))\\<^sup>2 \\<le> e * (3 * K / 2 ^ n)\\<^sup>2\"\n        using ynz dle e mult_le_cancel_left_pos by blast\n      also have \"\\<dots> <\n          cmod (?pathint (fa n) (fb n) + ?pathint (fb n) (fc n) + ?pathint (fc n) (fa n)) * 10\"\n        using no [of n] e K\n        by (simp add: e_def field_simps) (simp only: zero_less_norm_iff [symmetric])\n      finally have False\n        using le [OF DD x cosb] by auto\n    } then\n    have ?thesis\n      using holomorphic_point_small_triangle [OF xin contf fx, of \"e/10\"] e\n      apply clarsimp\n      apply (rule_tac y1=\"K/k\" in exE [OF real_arch_pow[of 2]], force+)\n      done\n  }\n  moreover have \"f contour_integrable_on (linepath a b +++ linepath b c +++ linepath c a)\"\n    by simp (meson contf continuous_on_subset contour_integrable_continuous_linepath segments_subset_convex_hull(1)\n                   segments_subset_convex_hull(3) segments_subset_convex_hull(5))\n  ultimately show ?thesis\n    using has_contour_integral_integral by fastforce\nqed\n\nsubsection\\<^marker>\\<open>tag unimportant\\<close> \\<open>Version needing function holomorphic in interior only\\<close>\n\nlemma Cauchy_theorem_flat_lemma:\n  assumes f: \"continuous_on (convex hull {a,b,c}) f\"\n      and c: \"c - a = k *\\<^sub>R (b - a)\"\n      and k: \"0 \\<le> k\"\n    shows \"contour_integral (linepath a b) f + contour_integral (linepath b c) f +\n          contour_integral (linepath c a) f = 0\"\nproof -\n  have fabc: \"continuous_on (closed_segment a b) f\" \"continuous_on (closed_segment b c) f\" \"continuous_on (closed_segment c a) f\"\n    using f continuous_on_subset segments_subset_convex_hull by metis+\n  show ?thesis\n  proof (cases \"k \\<le> 1\")\n    case True show ?thesis\n      by (simp add: contour_integral_split [OF fabc(1) k True c] contour_integral_reverse_linepath fabc)\n  next\n    case False\n    show ?thesis\n    proof (subst contour_integral_split [symmetric])\n      show \"b - a = (1/k) *\\<^sub>R (c - a)\"\n        using False c by force\n      show \"contour_integral (linepath a c) f + contour_integral (linepath c a) f = 0\"\n        by (simp add: contour_integral_reverse_linepath fabc(3))\n      show \"continuous_on (closed_segment a c) f\"\n        by (metis closed_segment_commute fabc(3))\n    qed (use False in auto)\n  qed\nqed\n\nlemma Cauchy_theorem_flat:\n  assumes f: \"continuous_on (convex hull {a,b,c}) f\"\n      and c: \"c - a = k *\\<^sub>R (b - a)\"\n    shows \"contour_integral (linepath a b) f +\n           contour_integral (linepath b c) f +\n           contour_integral (linepath c a) f = 0\"\nproof (cases \"0 \\<le> k\")\n  case True with assms show ?thesis\n    by (blast intro: Cauchy_theorem_flat_lemma)\nnext\n  case False\n  have \"continuous_on (closed_segment a b) f\" \"continuous_on (closed_segment b c) f\" \"continuous_on (closed_segment c a) f\"\n    using f continuous_on_subset segments_subset_convex_hull by metis+\n  moreover have \"contour_integral (linepath b a) f + contour_integral (linepath a c) f +\n                 contour_integral (linepath c b) f = 0\"\n  proof (rule Cauchy_theorem_flat_lemma [of b a c f \"1-k\"])\n    show \"continuous_on (convex hull {b, a, c}) f\"\n      by (simp add: f insert_commute)\n    show \"c - b = (1 - k) *\\<^sub>R (a - b)\"\n      using c by (auto simp: algebra_simps)\n  qed (use False in auto)\n  ultimately show ?thesis\n    by (metis (no_types, lifting) contour_integral_reverse_linepath eq_neg_iff_add_eq_0 minus_add_cancel)\nqed\n\n\nproposition Cauchy_theorem_triangle_interior:\n  assumes contf: \"continuous_on (convex hull {a,b,c}) f\"\n      and holf:  \"f holomorphic_on interior (convex hull {a,b,c})\"\n     shows \"(f has_contour_integral 0) (linepath a b +++ linepath b c +++ linepath c a)\"\nproof -\n  define pathint where \"pathint \\<equiv> \\<lambda>x y. contour_integral(linepath x y) f\"\n  have fabc: \"continuous_on (closed_segment a b) f\" \"continuous_on (closed_segment b c) f\" \"continuous_on (closed_segment c a) f\"\n    using contf continuous_on_subset segments_subset_convex_hull by metis+\n  have \"bounded (f ` (convex hull {a,b,c}))\"\n    by (simp add: compact_continuous_image compact_convex_hull compact_imp_bounded contf)\n  then obtain B where \"0 < B\" and Bnf: \"\\<And>x. x \\<in> convex hull {a,b,c} \\<Longrightarrow> norm (f x) \\<le> B\"\n     by (auto simp: dest!: bounded_pos [THEN iffD1])\n  have \"bounded (convex hull {a,b,c})\"\n    by (simp add: bounded_convex_hull)\n  then obtain C where C: \"0 < C\" and Cno: \"\\<And>y. y \\<in> convex hull {a,b,c} \\<Longrightarrow> norm y < C\"\n    using bounded_pos_less by blast\n  then have diff_2C: \"norm(x - y) \\<le> 2*C\"\n           if x: \"x \\<in> convex hull {a, b, c}\" and y: \"y \\<in> convex hull {a, b, c}\" for x y\n  proof -\n    have \"cmod x \\<le> C\"\n      using x by (meson Cno not_le not_less_iff_gr_or_eq)\n    hence \"cmod (x - y) \\<le> C + C\"\n      using y by (meson Cno add_mono_thms_linordered_field(4) less_eq_real_def norm_triangle_ineq4 order_trans)\n    thus \"cmod (x - y) \\<le> 2 * C\"\n      by (metis mult_2)\n  qed\n  have contf': \"continuous_on (convex hull {b,a,c}) f\"\n    using contf by (simp add: insert_commute)\n  { fix y::complex\n    assume fy: \"(f has_contour_integral y) (linepath a b +++ linepath b c +++ linepath c a)\"\n       and ynz: \"y \\<noteq> 0\"\n    have pi_eq_y: \"pathint a b + pathint b c + pathint c a= y\"\n      unfolding pathint_def by (rule has_chain_integral_chain_integral3 [OF fy])\n    have ?thesis\n    proof (cases \"c=a \\<or> a=b \\<or> b=c\")\n      case True then show ?thesis\n        using Cauchy_theorem_flat [OF contf, of 0]\n        using has_chain_integral_chain_integral3 [OF fy] ynz\n        by (force simp: fabc contour_integral_reverse_linepath)\n    next\n      case False\n      then have car3: \"card {a, b, c} = Suc (DIM(complex))\"\n        by auto\n      { assume \"interior(convex hull {a,b,c}) = {}\"\n        then have \"collinear{a,b,c}\"\n          using interior_convex_hull_eq_empty [OF car3]\n          by (simp add: collinear_3_eq_affine_dependent)\n        with False obtain d where \"c \\<noteq> a\" \"a \\<noteq> b\" \"b \\<noteq> c\" \"c - b = d *\\<^sub>R (a - b)\"\n          by (auto simp: collinear_3 collinear_lemma)\n        then have \"False\"\n          using False Cauchy_theorem_flat [OF contf'] pi_eq_y ynz\n          by (simp add: fabc add_eq_0_iff contour_integral_reverse_linepath pathint_def)\n      }\n      then obtain d where d: \"d \\<in> interior (convex hull {a, b, c})\"\n        by blast\n      { fix d1\n        assume d1_pos: \"0 < d1\"\n           and d1: \"\\<And>x x'. \\<lbrakk>x\\<in>convex hull {a, b, c}; x'\\<in>convex hull {a, b, c}; cmod (x' - x) < d1\\<rbrakk>\n                           \\<Longrightarrow> cmod (f x' - f x) < cmod y / (24 * C)\"\n        define e where \"e = min 1 (min (d1/(4*C)) ((norm y / 24 / C) / B))\"\n        define shrink where \"shrink x = x - e *\\<^sub>R (x - d)\" for x\n        have e: \"0 < e\" \"e \\<le> 1\" \"e \\<le> d1 / (4 * C)\" \"e \\<le> cmod y / 24 / C / B\"\n          using d1_pos \\<open>C>0\\<close> \\<open>B>0\\<close> ynz by (simp_all add: e_def)\n        have e_le_d1: \"e * (4 * C) \\<le> d1\"\n          using e \\<open>C>0\\<close> by (simp add: field_simps)\n        have \"shrink a \\<in> interior(convex hull {a,b,c})\"\n             \"shrink b \\<in> interior(convex hull {a,b,c})\"\n             \"shrink c \\<in> interior(convex hull {a,b,c})\"\n          using d e by (auto simp: hull_inc mem_interior_convex_shrink shrink_def)\n        then have fhp0: \"(f has_contour_integral 0)\n                (linepath (shrink a) (shrink b) +++ linepath (shrink b) (shrink c) +++ linepath (shrink c) (shrink a))\"\n          by (simp add: Cauchy_theorem_triangle holomorphic_on_subset [OF holf] hull_minimal)\n        then have f_0_shrink: \"pathint (shrink a) (shrink b) + pathint (shrink b) (shrink c) + pathint (shrink c) (shrink a) = 0\"\n          by (simp add: has_chain_integral_chain_integral3 pathint_def)\n        have fpi_abc: \"f contour_integrable_on linepath (shrink a) (shrink b)\"\n                      \"f contour_integrable_on linepath (shrink b) (shrink c)\"\n                      \"f contour_integrable_on linepath (shrink c) (shrink a)\"\n          using fhp0  by (auto simp: valid_path_join dest: has_contour_integral_integrable)\n        have cmod_shr: \"\\<And>x y. cmod (shrink y - shrink x - (y - x)) = e * cmod (x - y)\"\n          using e by (simp add: shrink_def real_vector.scale_right_diff_distrib [symmetric])\n        have sh_eq: \"\\<And>a b d::complex. (b - e *\\<^sub>R (b - d)) - (a - e *\\<^sub>R (a - d)) - (b - a) = e *\\<^sub>R (a - b)\"\n          by (simp add: algebra_simps)\n        have \"cmod y / (24 * C) \\<le> cmod y / cmod (b - a) / 12\"\n          using False \\<open>C>0\\<close> diff_2C [of b a] ynz\n          by (auto simp: field_split_simps hull_inc)\n        have less_C: \"x * cmod u < C\" if \"u \\<in> convex hull {a,b,c}\" \"0 \\<le> x\" \"x \\<le> 1\" for x u\n        proof (cases \"x=0\")\n          case False\n          with that show ?thesis\n            using Cno [of u] mult_left_le_one_le [of \"cmod u\" x] le_less_trans norm_ge_zero by blast\n        qed (simp add: \\<open>0<C\\<close>)\n        { fix u v\n          assume uv: \"u \\<in> convex hull {a, b, c}\" \"v \\<in> convex hull {a, b, c}\" \"u\\<noteq>v\"\n             and fpi_uv: \"f contour_integrable_on linepath (shrink u) (shrink v)\"\n          have shr_uv: \"shrink u \\<in> interior(convex hull {a,b,c})\"\n                       \"shrink v \\<in> interior(convex hull {a,b,c})\"\n            using d e uv\n            by (auto simp: hull_inc mem_interior_convex_shrink shrink_def)\n          have cmod_fuv: \"\\<And>x. 0\\<le>x \\<Longrightarrow> x\\<le>1 \\<Longrightarrow> cmod (f (linepath (shrink u) (shrink v) x)) \\<le> B\"\n            using shr_uv by (blast intro: Bnf linepath_in_convex_hull interior_subset [THEN subsetD])\n          { fix x::real   assume x: \"0\\<le>x\" \"x\\<le>1\"\n            have \"\\<bar>1 - x\\<bar> * cmod u < C\" \"\\<bar>x\\<bar> * cmod v < C\"\n              using uv x by (auto intro!: less_C)\n            moreover have  \"\\<bar>x\\<bar> * cmod d < C\" \"\\<bar>1 - x\\<bar> * cmod d < C\"\n              using x d interior_subset by (auto intro!: less_C)\n            ultimately\n            have cmod_less_4C: \"cmod ((1 - x) *\\<^sub>R u - (1 - x) *\\<^sub>R d) + cmod (x *\\<^sub>R v - x *\\<^sub>R d) < (C+C) + (C+C)\"\n              by (metis add_strict_mono le_less_trans norm_scaleR norm_triangle_ineq4)\n            have ll: \"linepath (shrink u) (shrink v) x - linepath u v x = -e * ((1 - x) *\\<^sub>R (u - d) + x *\\<^sub>R (v - d))\"\n              by (simp add: linepath_def shrink_def algebra_simps scaleR_conv_of_real)\n            have cmod_less_dt: \"cmod (linepath (shrink u) (shrink v) x - linepath u v x) < d1\"\n              unfolding ll norm_mult scaleR_diff_right\n              using \\<open>e>0\\<close> cmod_less_4C by (force intro: norm_triangle_lt less_le_trans [OF _ e_le_d1])\n            have \"cmod (f (linepath (shrink u) (shrink v) x)) * cmod (shrink v - shrink u - (v - u)) +\n                          cmod (v - u) * cmod (f (linepath (shrink u) (shrink v) x) - f (linepath u v x))\n                          \\<le> B * (cmod y / 24 / C / B * 2 * C) + 2 * C * (cmod y / 24 / C)\"\n            proof (intro add_mono [OF mult_mono])\n              show \"cmod (f (linepath (shrink u) (shrink v) x)) \\<le> B\"\n                using cmod_fuv x by blast\n              have \"B * (12 * (e * cmod (u - v))) \\<le> 24 * e * C * B\"\n                using e \\<open>B>0\\<close> diff_2C [of u v] uv by (auto simp: field_simps)\n              also have \"\\<dots> \\<le> cmod y\"\n                using \\<open>C>0\\<close> \\<open>B>0\\<close> e by (simp add: field_simps)\n              finally show \"cmod (shrink v - shrink u - (v - u)) \\<le> cmod y / 24 / C / B * 2 * C\"\n                using \\<open>0 < B\\<close> \\<open>0 < C\\<close> by (simp add: cmod_shr mult_ac divide_simps)\n              have \"cmod (f (linepath (shrink u) (shrink v) x) - f (linepath u v x)) < cmod y / (24 * C)\"\n                using x uv shr_uv cmod_less_dt\n                by (auto simp: hull_inc intro: d1 interior_subset [THEN subsetD] linepath_in_convex_hull)\n              also have \"\\<dots> \\<le> cmod y / cmod (v - u) / 12\"\n                using False uv \\<open>C>0\\<close> diff_2C [of v u] ynz\n                by (auto simp: field_split_simps hull_inc)\n              finally have \"cmod (f (linepath (shrink u) (shrink v) x) - f (linepath u v x)) \\<le> cmod y / cmod (v - u) / 12\"\n                by simp\n              then show \"cmod (v - u) * cmod (f (linepath (shrink u) (shrink v) x) - f (linepath u v x))\n                       \\<le> 2 * C * (cmod y / 24 / C)\"\n                using uv C  by (simp add: field_simps)\n            qed (use \\<open>0 < B\\<close> in auto)\n            also have \"\\<dots> \\<le> cmod y / 6\"\n              by simp\n            finally have \"cmod (f (linepath (shrink u) (shrink v) x)) * cmod (shrink v - shrink u - (v - u)) +\n                          cmod (v - u) * cmod (f (linepath (shrink u) (shrink v) x) - f (linepath u v x))\n                          \\<le> cmod y / 6\" .\n          } note cmod_diff_le = this\n          have f_uv: \"continuous_on (closed_segment u v) f\"\n            by (blast intro: uv continuous_on_subset [OF contf closed_segment_subset_convex_hull])\n          have **: \"\\<And>f' x' f x::complex. f'*x' - f*x = f' * (x' - x) + x * (f' - f)\"\n            by (simp add: algebra_simps)\n          have \"norm (pathint (shrink u) (shrink v) - pathint u v)\n                \\<le> (B*(norm y /24/C/B)*2*C + (2*C)*(norm y/24/C)) * content (cbox 0 (1::real))\"\n            apply (rule has_integral_bound\n                    [of _ \"\\<lambda>x. f(linepath (shrink u) (shrink v) x) * (shrink v - shrink u) - f(linepath u v x)*(v - u)\"\n                        _ 0 1])\n            using ynz \\<open>0 < B\\<close> \\<open>0 < C\\<close>\n            apply (simp_all add: pathint_def has_integral_diff has_contour_integral_linepath [symmetric] has_contour_integral_integral\n                fpi_uv f_uv contour_integrable_continuous_linepath del: le_divide_eq_numeral1)\n            apply (auto simp: ** norm_triangle_le norm_mult cmod_diff_le simp del: le_divide_eq_numeral1)\n            done\n          also have \"\\<dots> \\<le> norm y / 6\"\n            by simp\n          finally have \"norm (pathint (shrink u) (shrink v) - pathint u v) \\<le> norm y / 6\" .\n          } note * = this\n          have \"norm (pathint (shrink a) (shrink b) - pathint a b) \\<le> norm y / 6\"\n            using False fpi_abc by (rule_tac *) (auto simp: hull_inc)\n          moreover\n          have \"norm (pathint (shrink b) (shrink c) - pathint b c) \\<le> norm y / 6\"\n            using False fpi_abc by (rule_tac *) (auto simp: hull_inc)\n          moreover\n          have \"norm (pathint (shrink c) (shrink a) - pathint c a) \\<le> norm y / 6\"\n            using False fpi_abc by (rule_tac *) (auto simp: hull_inc)\n          ultimately\n          have \"norm((pathint (shrink a) (shrink b) - pathint a b) +\n                     (pathint (shrink b) (shrink c) - pathint b c) + (pathint (shrink c) (shrink a) - pathint c a))\n                \\<le> norm y / 6 + norm y / 6 + norm y / 6\"\n            by (metis norm_triangle_le add_mono)\n          also have \"\\<dots> = norm y / 2\"\n            by simp\n          finally have \"norm((pathint (shrink a) (shrink b) + pathint (shrink b) (shrink c) + pathint (shrink c) (shrink a)) -\n                          (pathint a b + pathint b c + pathint c a))\n                \\<le> norm y / 2\"\n            by (simp add: algebra_simps)\n          then\n          have \"norm(pathint a b + pathint b c + pathint c a) \\<le> norm y / 2\"\n            by (simp add: f_0_shrink) (metis (mono_tags) add.commute minus_add_distrib norm_minus_cancel uminus_add_conv_diff)\n          then have \"False\"\n            using pi_eq_y ynz by auto\n        }\n        note * = this\n        have \"uniformly_continuous_on (convex hull {a,b,c}) f\"\n          by (simp add: contf compact_convex_hull compact_uniformly_continuous)\n        moreover have \"norm y / (24 * C) > 0\"\n          using ynz \\<open>C > 0\\<close> by auto\n        ultimately obtain \\<delta> where \"\\<delta> > 0\" and\n          \"\\<forall>x\\<in>convex hull {a, b, c}. \\<forall>x'\\<in>convex hull {a, b, c}.\n             dist x' x < \\<delta> \\<longrightarrow> dist (f x') (f x) < cmod y / (24 * C)\"\n          using \\<open>C > 0\\<close> ynz unfolding uniformly_continuous_on_def dist_norm by blast\n        hence False using *[of \\<delta>] by (auto simp: dist_norm)\n        then show ?thesis ..\n      qed\n  }\n  moreover have \"f contour_integrable_on (linepath a b +++ linepath b c +++ linepath c a)\"\n    using fabc contour_integrable_continuous_linepath by auto\n  ultimately show ?thesis\n    using has_contour_integral_integral by fastforce\nqed\n\nsubsection\\<^marker>\\<open>tag unimportant\\<close> \\<open>Version allowing finite number of exceptional points\\<close>\n\nproposition\\<^marker>\\<open>tag unimportant\\<close> Cauchy_theorem_triangle_cofinite:\n  assumes \"continuous_on (convex hull {a,b,c}) f\"\n      and \"finite S\"\n      and \"(\\<And>x. x \\<in> interior(convex hull {a,b,c}) - S \\<Longrightarrow> f field_differentiable (at x))\"\n     shows \"(f has_contour_integral 0) (linepath a b +++ linepath b c +++ linepath c a)\"\nusing assms\nproof (induction \"card S\" arbitrary: a b c S rule: less_induct)\n  case (less S a b c)\n  show ?case\n  proof (cases \"S={}\")\n    case True with less show ?thesis\n      by (fastforce simp: holomorphic_on_def field_differentiable_at_within Cauchy_theorem_triangle_interior)\n  next\n    case False\n    then obtain d S' where d: \"S = insert d S'\" \"d \\<notin> S'\"\n      by (meson Set.set_insert all_not_in_conv)\n    then show ?thesis\n    proof (cases \"d \\<in> convex hull {a,b,c}\")\n      case False\n      show \"(f has_contour_integral 0) (linepath a b +++ linepath b c +++ linepath c a)\"\n      proof (rule less.hyps)\n        show \"\\<And>x. x \\<in> interior (convex hull {a, b, c}) - S' \\<Longrightarrow> f field_differentiable at x\"\n        using False d interior_subset by (auto intro!: less.prems)\n    qed (use d less.prems in auto)\n    next\n      case True\n      have *: \"convex hull {a, b, d} \\<subseteq> convex hull {a, b, c}\"\n        by (meson True hull_subset insert_subset convex_hull_subset)\n      have abd: \"(f has_contour_integral 0) (linepath a b +++ linepath b d +++ linepath d a)\"\n      proof (rule less.hyps)\n        show \"\\<And>x. x \\<in> interior (convex hull {a, b, d}) - S' \\<Longrightarrow> f field_differentiable at x\"\n          using d not_in_interior_convex_hull_3\n          by (clarsimp intro!: less.prems) (metis * insert_absorb insert_subset interior_mono)\n      qed (use d continuous_on_subset [OF  _ *] less.prems in auto)\n      have *: \"convex hull {b, c, d} \\<subseteq> convex hull {a, b, c}\"\n        by (meson True hull_subset insert_subset convex_hull_subset)\n      have bcd: \"(f has_contour_integral 0) (linepath b c +++ linepath c d +++ linepath d b)\"\n      proof (rule less.hyps)\n        show \"\\<And>x. x \\<in> interior (convex hull {b, c, d}) - S' \\<Longrightarrow> f field_differentiable at x\"\n          using d not_in_interior_convex_hull_3\n          by (clarsimp intro!: less.prems) (metis * insert_absorb insert_subset interior_mono)\n      qed (use d continuous_on_subset [OF  _ *] less.prems in auto)\n      have *: \"convex hull {c, a, d} \\<subseteq> convex hull {a, b, c}\"\n        by (meson True hull_subset insert_subset convex_hull_subset)\n      have cad: \"(f has_contour_integral 0) (linepath c a +++ linepath a d +++ linepath d c)\"\n      proof (rule less.hyps)\n        show \"\\<And>x. x \\<in> interior (convex hull {c, a, d}) - S' \\<Longrightarrow> f field_differentiable at x\"\n          using d not_in_interior_convex_hull_3\n          by (clarsimp intro!: less.prems) (metis * insert_absorb insert_subset interior_mono)\n      qed (use d continuous_on_subset [OF  _ *] less.prems in auto)\n      have \"f contour_integrable_on linepath a b\"\n        using less.prems abd contour_integrable_joinD1 contour_integrable_on_def by blast\n      moreover have \"f contour_integrable_on linepath b c\"\n        using less.prems bcd contour_integrable_joinD1 contour_integrable_on_def by blast\n      moreover have \"f contour_integrable_on linepath c a\"\n        using less.prems cad contour_integrable_joinD1 contour_integrable_on_def by blast\n      ultimately have fpi: \"f contour_integrable_on (linepath a b +++ linepath b c +++ linepath c a)\"\n        by auto\n      { fix y::complex\n        assume fy: \"(f has_contour_integral y) (linepath a b +++ linepath b c +++ linepath c a)\"\n           and ynz: \"y \\<noteq> 0\"\n        have cont_ad: \"continuous_on (closed_segment a d) f\"\n          by (meson \"*\" continuous_on_subset less.prems(1) segments_subset_convex_hull(3))\n        have cont_bd: \"continuous_on (closed_segment b d) f\"\n          by (meson True closed_segment_subset_convex_hull continuous_on_subset hull_subset insert_subset less.prems(1))\n        have cont_cd: \"continuous_on (closed_segment c d) f\"\n          by (meson \"*\" continuous_on_subset less.prems(1) segments_subset_convex_hull(2))\n        have \"contour_integral  (linepath a b) f = - (contour_integral (linepath b d) f + (contour_integral (linepath d a) f))\"\n             \"contour_integral  (linepath b c) f = - (contour_integral (linepath c d) f + (contour_integral (linepath d b) f))\"\n             \"contour_integral  (linepath c a) f = - (contour_integral (linepath a d) f + contour_integral (linepath d c) f)\"\n            using has_chain_integral_chain_integral3 [OF abd]\n                  has_chain_integral_chain_integral3 [OF bcd]\n                  has_chain_integral_chain_integral3 [OF cad]\n            by (simp_all add: algebra_simps add_eq_0_iff)\n        then have ?thesis\n          using cont_ad cont_bd cont_cd fy has_chain_integral_chain_integral3 contour_integral_reverse_linepath by fastforce\n      }\n      then show ?thesis\n        using fpi contour_integrable_on_def by blast\n    qed\n  qed\nqed\n\nsubsection\\<^marker>\\<open>tag unimportant\\<close> \\<open>Cauchy's theorem for an open starlike set\\<close>\n\nlemma starlike_convex_subset:\n  assumes S: \"a \\<in> S\" \"closed_segment b c \\<subseteq> S\" and subs: \"\\<And>x. x \\<in> S \\<Longrightarrow> closed_segment a x \\<subseteq> S\"\n  shows \"convex hull {a,b,c} \\<subseteq> S\"\nproof -\n  have \"convex hull {b, c} \\<subseteq> S\"\n    using assms(2) segment_convex_hull by auto\n  then have \"\\<And>u v d. \\<lbrakk>0 \\<le> u; 0 \\<le> v; u + v = 1; d \\<in> convex hull {b, c}\\<rbrakk> \\<Longrightarrow> u *\\<^sub>R a + v *\\<^sub>R d \\<in> S\"\n    by (meson subs convexD convex_closed_segment ends_in_segment subsetCE)\n  then show ?thesis\n    by (auto simp add: convex_hull_insert [of \"{b,c}\" a])\nqed\n\nlemma triangle_contour_integrals_starlike_primitive:\n  assumes contf: \"continuous_on S f\"\n      and S: \"a \\<in> S\" \"open S\"\n      and x: \"x \\<in> S\"\n      and subs: \"\\<And>y. y \\<in> S \\<Longrightarrow> closed_segment a y \\<subseteq> S\"\n      and zer: \"\\<And>b c. closed_segment b c \\<subseteq> S\n                   \\<Longrightarrow> contour_integral (linepath a b) f + contour_integral (linepath b c) f +\n                       contour_integral (linepath c a) f = 0\"\n    shows \"((\\<lambda>x. contour_integral(linepath a x) f) has_field_derivative f x) (at x)\"\nproof -\n  let ?pathint = \"\\<lambda>x y. contour_integral(linepath x y) f\"\n  { fix e y\n    assume e: \"0 < e\" and bxe: \"ball x e \\<subseteq> S\" and close: \"cmod (y - x) < e\"\n    have y: \"y \\<in> S\"\n      using bxe close  by (force simp: dist_norm norm_minus_commute)\n    have cont_ayf: \"continuous_on (closed_segment a y) f\"\n      using contf continuous_on_subset subs y by blast\n    have xys: \"closed_segment x y \\<subseteq> S\"\n      by (metis bxe centre_in_ball close closed_segment_subset convex_ball dist_norm dual_order.trans e mem_ball norm_minus_commute)\n    have \"?pathint a y - ?pathint a x = ?pathint x y\"\n      using zer [OF xys]  contour_integral_reverse_linepath [OF cont_ayf]  add_eq_0_iff by force\n  } note [simp] = this\n  { fix e::real\n    assume e: \"0 < e\"\n    have cont_atx: \"continuous (at x) f\"\n      using x S contf continuous_on_eq_continuous_at by blast\n    then obtain d1 where d1: \"d1>0\" and d1_less: \"\\<And>y. cmod (y - x) < d1 \\<Longrightarrow> cmod (f y - f x) < e/2\"\n      unfolding continuous_at Lim_at dist_norm  using e\n      by (drule_tac x=\"e/2\" in spec) force\n    obtain d2 where d2: \"d2>0\" \"ball x d2 \\<subseteq> S\" using  \\<open>open S\\<close> x\n      by (auto simp: open_contains_ball)\n    have dpos: \"min d1 d2 > 0\" using d1 d2 by simp\n    { fix y\n      assume yx: \"y \\<noteq> x\" and close: \"cmod (y - x) < min d1 d2\"\n      have y: \"y \\<in> S\"\n        using d2 close  by (force simp: dist_norm norm_minus_commute)\n      have \"closed_segment x y \\<subseteq> S\"\n        using close d2  by (auto simp: dist_norm norm_minus_commute dest!: segment_bound(1))\n      then have fxy: \"f contour_integrable_on linepath x y\"\n        by (metis contour_integrable_continuous_linepath continuous_on_subset [OF contf])\n      then obtain i where i: \"(f has_contour_integral i) (linepath x y)\"\n        by (auto simp: contour_integrable_on_def)\n      then have \"((\\<lambda>w. f w - f x) has_contour_integral (i - f x * (y - x))) (linepath x y)\"\n        by (rule has_contour_integral_diff [OF _ has_contour_integral_const_linepath])\n      then have \"cmod (i - f x * (y - x)) \\<le> e / 2 * cmod (y - x)\"\n      proof (rule has_contour_integral_bound_linepath)\n        show \"\\<And>u. u \\<in> closed_segment x y \\<Longrightarrow> cmod (f u - f x) \\<le> e / 2\"\n          by (meson close d1_less le_less_trans less_imp_le min.strict_boundedE segment_bound1)\n      qed (use e in simp)\n      also have \"\\<dots> < e * cmod (y - x)\"\n        by (simp add: e yx)\n      finally have \"cmod (?pathint x y - f x * (y-x)) / cmod (y-x) < e\"\n        using i yx  by (simp add: contour_integral_unique divide_less_eq)\n    }\n    then have \"\\<exists>d>0. \\<forall>y. y \\<noteq> x \\<and> cmod (y-x) < d \\<longrightarrow> cmod (?pathint x y - f x * (y-x)) / cmod (y-x) < e\"\n      using dpos by blast\n  }\n  then have \"(\\<lambda>y. (?pathint x y - f x * (y - x)) /\\<^sub>R cmod (y - x)) \\<midarrow>x\\<rightarrow> 0\"\n    by (simp add: Lim_at dist_norm inverse_eq_divide)\n  then have \"(\\<lambda>y. (1 / cmod (y - x)) *\\<^sub>R (?pathint a y - (?pathint a x + f x * (y - x)))) \\<midarrow>x\\<rightarrow> 0\"\n    using \\<open>open S\\<close> x \n    by (force simp: dist_norm open_contains_ball inverse_eq_divide [symmetric] eventually_at intro:  Lim_transform [OF _ tendsto_eventually])\n  then show ?thesis\n    by (simp add: has_field_derivative_def has_derivative_at2 bounded_linear_mult_right)\nqed\n\n(** Existence of a primitive.*)\nlemma holomorphic_starlike_primitive:\n  fixes f :: \"complex \\<Rightarrow> complex\"\n  assumes contf: \"continuous_on S f\"\n      and S: \"starlike S\" and os: \"open S\"\n      and k: \"finite k\"\n      and fcd: \"\\<And>x. x \\<in> S - k \\<Longrightarrow> f field_differentiable at x\"\n    shows \"\\<exists>g. \\<forall>x \\<in> S. (g has_field_derivative f x) (at x)\"\nproof -\n  obtain a where a: \"a\\<in>S\" and a_cs: \"\\<And>x. x\\<in>S \\<Longrightarrow> closed_segment a x \\<subseteq> S\"\n    using S by (auto simp: starlike_def)\n  { fix x b c\n    assume \"x \\<in> S\" \"closed_segment b c \\<subseteq> S\"\n    then have abcs: \"convex hull {a, b, c} \\<subseteq> S\"\n      by (simp add: a a_cs starlike_convex_subset)\n    then have \"continuous_on (convex hull {a, b, c}) f\"\n      by (simp add: continuous_on_subset [OF contf])\n    then have \"(f has_contour_integral 0) (linepath a b +++ linepath b c +++ linepath c a)\"\n      using abcs interior_subset by (force intro: fcd Cauchy_theorem_triangle_cofinite [OF _ k])\n  } note 0 = this\n  show ?thesis\n  proof (intro exI ballI)\n    show \"\\<And>x. x \\<in> S \\<Longrightarrow> ((\\<lambda>x. contour_integral (linepath a x) f) has_field_derivative f x) (at x)\"\n      using \"0\" a a_cs contf has_chain_integral_chain_integral3 os triangle_contour_integrals_starlike_primitive by force\n  qed\nqed\n\nlemma Cauchy_theorem_starlike:\n \"\\<lbrakk>open S; starlike S; finite k; continuous_on S f;\n   \\<And>x. x \\<in> S - k \\<Longrightarrow> f field_differentiable at x;\n   valid_path g; path_image g \\<subseteq> S; pathfinish g = pathstart g\\<rbrakk>\n   \\<Longrightarrow> (f has_contour_integral 0)  g\"\n  by (metis holomorphic_starlike_primitive Cauchy_theorem_primitive at_within_open)\n\nlemma Cauchy_theorem_starlike_simple:\n  \"\\<lbrakk>open S; starlike S; f holomorphic_on S; valid_path g; path_image g \\<subseteq> S; pathfinish g = pathstart g\\<rbrakk>\n   \\<Longrightarrow> (f has_contour_integral 0) g\"\n  using Cauchy_theorem_starlike [OF _ _ finite.emptyI]\n  by (simp add: holomorphic_on_imp_continuous_on holomorphic_on_imp_differentiable_at)\n\nsubsection\\<open>Cauchy's theorem for a convex set\\<close>\n\ntext\\<open>For a convex set we can avoid assuming openness and boundary analyticity\\<close>\n\nlemma triangle_contour_integrals_convex_primitive:\n  assumes contf: \"continuous_on S f\"\n      and S: \"a \\<in> S\" \"convex S\"\n      and x: \"x \\<in> S\"\n      and zer: \"\\<And>b c. \\<lbrakk>b \\<in> S; c \\<in> S\\<rbrakk>\n                   \\<Longrightarrow> contour_integral (linepath a b) f + contour_integral (linepath b c) f +\n                       contour_integral (linepath c a) f = 0\"\n    shows \"((\\<lambda>x. contour_integral(linepath a x) f) has_field_derivative f x) (at x within S)\"\nproof -\n  let ?pathint = \"\\<lambda>x y. contour_integral(linepath x y) f\"\n  { fix y\n    assume y: \"y \\<in> S\"\n    have cont_ayf: \"continuous_on (closed_segment a y) f\"\n      using S y  by (meson contf continuous_on_subset convex_contains_segment)\n    have xys: \"closed_segment x y \\<subseteq> S\"  (*?*)\n      using convex_contains_segment S x y by auto\n    have \"?pathint a y - ?pathint a x = ?pathint x y\"\n      using zer [OF x y]  contour_integral_reverse_linepath [OF cont_ayf]  add_eq_0_iff by force\n  } note [simp] = this\n  { fix e::real\n    assume e: \"0 < e\"\n    have cont_atx: \"continuous (at x within S) f\"\n      using x S contf  by (simp add: continuous_on_eq_continuous_within)\n    then obtain d1 where d1: \"d1>0\" and d1_less: \"\\<And>y. \\<lbrakk>y \\<in> S; cmod (y - x) < d1\\<rbrakk> \\<Longrightarrow> cmod (f y - f x) < e/2\"\n      unfolding continuous_within Lim_within dist_norm using e\n      by (drule_tac x=\"e/2\" in spec) force\n    { fix y\n      assume yx: \"y \\<noteq> x\" and close: \"cmod (y - x) < d1\" and y: \"y \\<in> S\"\n      have fxy: \"f contour_integrable_on linepath x y\"\n        using convex_contains_segment S x y\n        by (blast intro!: contour_integrable_continuous_linepath continuous_on_subset [OF contf])\n      then obtain i where i: \"(f has_contour_integral i) (linepath x y)\"\n        by (auto simp: contour_integrable_on_def)\n      then have \"((\\<lambda>w. f w - f x) has_contour_integral (i - f x * (y - x))) (linepath x y)\"\n        by (rule has_contour_integral_diff [OF _ has_contour_integral_const_linepath])\n      then have \"cmod (i - f x * (y - x)) \\<le> e / 2 * cmod (y - x)\"\n      proof (rule has_contour_integral_bound_linepath)\n        show \"\\<And>u. u \\<in> closed_segment x y \\<Longrightarrow> cmod (f u - f x) \\<le> e / 2\"\n          by (meson assms(3) close convex_contains_segment d1_less le_less_trans less_imp_le segment_bound1 subset_iff x y)\n      qed (use e in simp)\n      also have \"\\<dots> < e * cmod (y - x)\"\n        by (simp add: e yx)\n      finally have \"cmod (?pathint x y - f x * (y-x)) / cmod (y-x) < e\"\n        using i yx  by (simp add: contour_integral_unique divide_less_eq)\n    }\n    then have \"\\<exists>d>0. \\<forall>y\\<in>S. y \\<noteq> x \\<and> cmod (y-x) < d \\<longrightarrow> cmod (?pathint x y - f x * (y-x)) / cmod (y-x) < e\"\n      using d1 by blast\n  }\n  then have \"((\\<lambda>y. (?pathint x y - f x * (y - x)) /\\<^sub>R cmod (y - x)) \\<longlongrightarrow> 0) (at x within S)\"\n    by (simp add: Lim_within dist_norm inverse_eq_divide)\n  then have \"((\\<lambda>y. (1 / cmod (y - x)) *\\<^sub>R (?pathint a y - (?pathint a x + f x * (y - x)))) \\<longlongrightarrow> 0)\n             (at x within S)\"\n    using linordered_field_no_ub\n    by (force simp: inverse_eq_divide [symmetric] eventually_at intro: Lim_transform [OF _ tendsto_eventually])\n  then show ?thesis\n    by (simp add: has_field_derivative_def has_derivative_within bounded_linear_mult_right)\nqed\n\nlemma contour_integral_convex_primitive:\n  assumes \"convex S\" \"continuous_on S f\"\n          \"\\<And>a b c. \\<lbrakk>a \\<in> S; b \\<in> S; c \\<in> S\\<rbrakk> \\<Longrightarrow> (f has_contour_integral 0) (linepath a b +++ linepath b c +++ linepath c a)\"\n  obtains g where \"\\<And>x. x \\<in> S \\<Longrightarrow> (g has_field_derivative f x) (at x within S)\"\nproof (cases \"S={}\")\n  case False\n  with assms that show ?thesis\n    by (blast intro: triangle_contour_integrals_convex_primitive has_chain_integral_chain_integral3)\nqed auto\n\nlemma holomorphic_convex_primitive:\n  fixes f :: \"complex \\<Rightarrow> complex\"\n  assumes \"convex S\" \"finite K\" and contf: \"continuous_on S f\"\n    and fd: \"\\<And>x. x \\<in> interior S - K \\<Longrightarrow> f field_differentiable at x\"\n  obtains g where \"\\<And>x. x \\<in> S \\<Longrightarrow> (g has_field_derivative f x) (at x within S)\"\nproof (rule contour_integral_convex_primitive [OF \\<open>convex S\\<close> contf Cauchy_theorem_triangle_cofinite])\n  have *: \"convex hull {a, b, c} \\<subseteq> S\" if \"a \\<in> S\" \"b \\<in> S\" \"c \\<in> S\" for a b c\n    by (simp add: \\<open>convex S\\<close> hull_minimal that)\n  show \"continuous_on (convex hull {a, b, c}) f\" if \"a \\<in> S\" \"b \\<in> S\" \"c \\<in> S\" for a b c\n    by (meson \"*\" contf continuous_on_subset that)\n  show \"f field_differentiable at x\" if \"a \\<in> S\" \"b \\<in> S\" \"c \\<in> S\" \"x \\<in> interior (convex hull {a, b, c}) - K\" for a b c x\n    by (metis \"*\" DiffD1 DiffD2 DiffI fd interior_mono subsetCE that)\nqed (use assms in \\<open>force+\\<close>)\n\nlemma holomorphic_convex_primitive':\n  fixes f :: \"complex \\<Rightarrow> complex\"\n  assumes \"convex S\" and \"open S\" and \"f holomorphic_on S\"\n  obtains g where \"\\<And>x. x \\<in> S \\<Longrightarrow> (g has_field_derivative f x) (at x within S)\"\nproof (rule holomorphic_convex_primitive)\n  fix x assume \"x \\<in> interior S - {}\"\n  with assms show \"f field_differentiable at x\"\n    by (auto intro!: holomorphic_on_imp_differentiable_at simp: interior_open)\nqed (use assms in \\<open>auto intro: holomorphic_on_imp_continuous_on\\<close>)\n\ncorollary\\<^marker>\\<open>tag unimportant\\<close> Cauchy_theorem_convex:\n    \"\\<lbrakk>continuous_on S f; convex S; finite K;\n      \\<And>x. x \\<in> interior S - K \\<Longrightarrow> f field_differentiable at x;\n      valid_path g; path_image g \\<subseteq> S; pathfinish g = pathstart g\\<rbrakk>\n     \\<Longrightarrow> (f has_contour_integral 0) g\"\n  by (metis holomorphic_convex_primitive Cauchy_theorem_primitive)\n\ncorollary Cauchy_theorem_convex_simple:\n  assumes holf: \"f holomorphic_on S\" \n      and \"convex S\" \"valid_path g\" \"path_image g \\<subseteq> S\" \"pathfinish g = pathstart g\"\n  shows \"(f has_contour_integral 0) g\"\nproof -\n  have \"f holomorphic_on interior S\"\n    by (meson holf holomorphic_on_subset interior_subset)\n  with Cauchy_theorem_convex [where K = \"{}\"] show ?thesis\n    using assms\n    by (metis Diff_empty finite.emptyI holomorphic_on_imp_continuous_on holomorphic_on_imp_differentiable_at open_interior)\nqed\n\ntext\\<open>In particular for a disc\\<close>\ncorollary\\<^marker>\\<open>tag unimportant\\<close> Cauchy_theorem_disc:\n    \"\\<lbrakk>finite K; continuous_on (cball a e) f;\n      \\<And>x. x \\<in> ball a e - K \\<Longrightarrow> f field_differentiable at x;\n     valid_path g; path_image g \\<subseteq> cball a e;\n     pathfinish g = pathstart g\\<rbrakk> \\<Longrightarrow> (f has_contour_integral 0) g\"\n  by (auto intro: Cauchy_theorem_convex)\n\ncorollary\\<^marker>\\<open>tag unimportant\\<close> Cauchy_theorem_disc_simple:\n    \"\\<lbrakk>f holomorphic_on (ball a e); valid_path g; path_image g \\<subseteq> ball a e;\n     pathfinish g = pathstart g\\<rbrakk> \\<Longrightarrow> (f has_contour_integral 0) g\"\nby (simp add: Cauchy_theorem_convex_simple)\n\nsubsection\\<^marker>\\<open>tag unimportant\\<close> \\<open>Generalize integrability to local primitives\\<close>\n\nlemma contour_integral_local_primitive_lemma:\n  fixes f :: \"complex\\<Rightarrow>complex\"\n  assumes gpd: \"g piecewise_differentiable_on {a..b}\"\n      and dh: \"\\<And>x. x \\<in> S \\<Longrightarrow> (f has_field_derivative f' x) (at x within S)\"\n      and gs: \"\\<And>x. x \\<in> {a..b} \\<Longrightarrow> g x \\<in> S\"\n  shows \n    \"(\\<lambda>x. f' (g x) * vector_derivative g (at x within {a..b})) integrable_on {a..b}\"\nproof (cases \"cbox a b = {}\")\n  case False\n  then show ?thesis\n    unfolding integrable_on_def by (auto intro: assms contour_integral_primitive_lemma)\nqed auto\n\nlemma contour_integral_local_primitive_any:\n  fixes f :: \"complex \\<Rightarrow> complex\"\n  assumes gpd: \"g piecewise_differentiable_on {a..b}\"\n      and dh: \"\\<And>x. x \\<in> S\n               \\<Longrightarrow> \\<exists>d h. 0 < d \\<and>\n                         (\\<forall>y. norm(y - x) < d \\<longrightarrow> (h has_field_derivative f y) (at y within S))\"\n      and gs: \"\\<And>x. x \\<in> {a..b} \\<Longrightarrow> g x \\<in> S\"\n  shows \"(\\<lambda>x. f(g x) * vector_derivative g (at x)) integrable_on {a..b}\"\nproof -\n  { fix x\n    assume x: \"a \\<le> x\" \"x \\<le> b\"\n    obtain d h where d: \"0 < d\"\n               and h: \"(\\<And>y. norm(y - g x) < d \\<Longrightarrow> (h has_field_derivative f y) (at y within S))\"\n      using x gs dh by (metis atLeastAtMost_iff)\n    have \"continuous_on {a..b} g\" using gpd piecewise_differentiable_on_def by blast\n    then obtain e where e: \"e>0\" and lessd: \"\\<And>x'. x' \\<in> {a..b} \\<Longrightarrow> \\<bar>x' - x\\<bar> < e \\<Longrightarrow> cmod (g x' - g x) < d\"\n      using x d by (fastforce simp: dist_norm continuous_on_iff)\n    have \"\\<exists>e>0. \\<forall>u v. u \\<le> x \\<and> x \\<le> v \\<and> {u..v} \\<subseteq> ball x e \\<and> (u \\<le> v \\<longrightarrow> a \\<le> u \\<and> v \\<le> b) \\<longrightarrow>\n                          (\\<lambda>x. f (g x) * vector_derivative g (at x)) integrable_on {u..v}\"\n    proof -\n      have \"(\\<lambda>x. f (g x) * vector_derivative g (at x within {u..v})) integrable_on {u..v}\"\n        if \"u \\<le> x\" \"x \\<le> v\" and ball: \"{u..v} \\<subseteq> ball x e\" and auvb: \"u \\<le> v \\<Longrightarrow> a \\<le> u \\<and> v \\<le> b\"\n        for u v\n      proof (rule contour_integral_local_primitive_lemma)\n        show \"g piecewise_differentiable_on {u..v}\"\n          by (metis atLeastatMost_subset_iff gpd piecewise_differentiable_on_subset auvb)\n        show \"\\<And>x. x \\<in> g ` {u..v} \\<Longrightarrow> (h has_field_derivative f x) (at x within g ` {u..v})\"\n          using that by (force simp: ball_def dist_norm intro: lessd gs DERIV_subset [OF h])\n      qed auto\n      then show ?thesis\n        using e integrable_on_localized_vector_derivative by blast\n    qed\n  } then\n  show ?thesis\n    by (force simp: intro!: integrable_on_little_subintervals [of a b, simplified])\nqed\n\nlemma contour_integral_local_primitive:\n  fixes f :: \"complex \\<Rightarrow> complex\"\n  assumes g: \"valid_path g\" \"path_image g \\<subseteq> S\"\n      and dh: \"\\<And>x. x \\<in> S\n               \\<Longrightarrow> \\<exists>d h. 0 < d \\<and>\n                         (\\<forall>y. norm(y - x) < d \\<longrightarrow> (h has_field_derivative f y) (at y within S))\"\n    shows \"f contour_integrable_on g\"\nproof -\n  have \"(\\<lambda>x. f (g x) * vector_derivative g (at x)) integrable_on {0..1}\"\n    using contour_integral_local_primitive_any [OF _ dh] g\n    unfolding path_image_def valid_path_def\n    by (metis (no_types, lifting) image_subset_iff piecewise_C1_imp_differentiable)\n  then show ?thesis\n    using contour_integrable_on by presburger\nqed\n\n\ntext\\<open>In particular if a function is holomorphic\\<close>\n\nlemma contour_integrable_holomorphic:\n  assumes contf: \"continuous_on S f\"\n      and os: \"open S\"\n      and k: \"finite k\"\n      and g: \"valid_path g\" \"path_image g \\<subseteq> S\"\n      and fcd: \"\\<And>x. x \\<in> S - k \\<Longrightarrow> f field_differentiable at x\"\n    shows \"f contour_integrable_on g\"\nproof -\n  { fix z\n    assume z: \"z \\<in> S\"\n    obtain d where \"d>0\" and d: \"ball z d \\<subseteq> S\" using  \\<open>open S\\<close> z\n      by (auto simp: open_contains_ball)\n    then have contfb: \"continuous_on (ball z d) f\"\n      using contf continuous_on_subset by blast\n    obtain h where \"\\<forall>y\\<in>ball z d. (h has_field_derivative f y) (at y within ball z d)\"\n      by (metis holomorphic_convex_primitive [OF convex_ball k contfb fcd] d interior_subset Diff_iff subsetD)\n    then have \"\\<forall>y\\<in>ball z d. (h has_field_derivative f y) (at y within S)\"\n      by (metis open_ball at_within_open d os subsetCE)\n    then have \"\\<exists>h. (\\<forall>y. cmod (y - z) < d \\<longrightarrow> (h has_field_derivative f y) (at y within S))\"\n      by (force simp: dist_norm norm_minus_commute)\n    then have \"\\<exists>d h. 0 < d \\<and> (\\<forall>y. cmod (y - z) < d \\<longrightarrow> (h has_field_derivative f y) (at y within S))\"\n      using \\<open>0 < d\\<close> by blast\n  }\n  then show ?thesis\n    by (rule contour_integral_local_primitive [OF g])\nqed\n\nlemma contour_integrable_holomorphic_simple:\n  assumes fh: \"f holomorphic_on S\"\n      and os: \"open S\"\n      and g: \"valid_path g\" \"path_image g \\<subseteq> S\"\n    shows \"f contour_integrable_on g\"\nproof -\n  have \"\\<And>x. x \\<in> S \\<Longrightarrow> f field_differentiable at x\"\n    using fh holomorphic_on_imp_differentiable_at os by blast\n  moreover have \"continuous_on S f\"\n    by (simp add: fh holomorphic_on_imp_continuous_on)\n  ultimately show ?thesis\n    by (metis Diff_empty contour_integrable_holomorphic finite.emptyI g os)\nqed\n\nlemma continuous_on_inversediff:\n  fixes z:: \"'a::real_normed_field\" shows \"z \\<notin> S \\<Longrightarrow> continuous_on S (\\<lambda>w. 1 / (w - z))\"\n  by (rule continuous_intros | force)+\n\nlemma contour_integrable_inversediff:\n  assumes g: \"valid_path g\"\n      and notin: \"z \\<notin> path_image g\"\n    shows \"(\\<lambda>w. 1 / (w-z)) contour_integrable_on g\"\nproof (rule contour_integrable_holomorphic_simple)\n  show \"(\\<lambda>w. 1 / (w-z)) holomorphic_on UNIV - {z}\"\n    by (auto simp: holomorphic_on_open open_delete intro!: derivative_eq_intros)\nqed (use assms in auto)\n\ntext\\<open>Key fact that path integral is the same for a \"nearby\" path. This is the\n main lemma for the homotopy form of Cauchy's theorem and is also useful\n if we want \"without loss of generality\" to assume some nice properties of a\n path (e.g. smoothness). It can also be used to define the integrals of\n analytic functions over arbitrary continuous paths. This is just done for\n winding numbers now.\n\\<close>\n\ntext\\<open>A technical definition to avoid duplication of similar proofs,\n     for paths joined at the ends versus looping paths\\<close>\ndefinition linked_paths :: \"bool \\<Rightarrow> (real \\<Rightarrow> 'a) \\<Rightarrow> (real \\<Rightarrow> 'a::topological_space) \\<Rightarrow> bool\"\n  where \"linked_paths atends g h ==\n        (if atends then pathstart h = pathstart g \\<and> pathfinish h = pathfinish g\n                   else pathfinish g = pathstart g \\<and> pathfinish h = pathstart h)\"\n\ntext\\<open>This formulation covers two cases: \\<^term>\\<open>g\\<close> and \\<^term>\\<open>h\\<close> share their\n      start and end points; \\<^term>\\<open>g\\<close> and \\<^term>\\<open>h\\<close> both loop upon themselves.\\<close>\nlemma contour_integral_nearby:\n  assumes os: \"open S\" and p: \"path p\" \"path_image p \\<subseteq> S\"\n  shows \"\\<exists>d. 0 < d \\<and>\n            (\\<forall>g h. valid_path g \\<and> valid_path h \\<and>\n                  (\\<forall>t \\<in> {0..1}. norm(g t - p t) < d \\<and> norm(h t - p t) < d) \\<and>\n                  linked_paths atends g h\n                  \\<longrightarrow> path_image g \\<subseteq> S \\<and> path_image h \\<subseteq> S \\<and>\n                      (\\<forall>f. f holomorphic_on S \\<longrightarrow> contour_integral h f = contour_integral g f))\"\nproof -\n  have \"\\<forall>z. \\<exists>e. z \\<in> path_image p \\<longrightarrow> 0 < e \\<and> ball z e \\<subseteq> S\"\n    using open_contains_ball os p(2) by blast\n  then obtain ee where ee: \"\\<And>z. z \\<in> path_image p \\<Longrightarrow> 0 < ee z \\<and> ball z (ee z) \\<subseteq> S\"\n    by metis\n  define cover where \"cover = (\\<lambda>z. ball z (ee z/3)) ` (path_image p)\"\n  have \"compact (path_image p)\"\n    by (metis p(1) compact_path_image)\n  moreover have \"path_image p \\<subseteq> (\\<Union>c\\<in>path_image p. ball c (ee c / 3))\"\n    using ee by auto\n  ultimately have \"\\<exists>D \\<subseteq> cover. finite D \\<and> path_image p \\<subseteq> \\<Union>D\"\n    by (simp add: compact_eq_Heine_Borel cover_def)\n  then obtain D where D: \"D \\<subseteq> cover\" \"finite D\" \"path_image p \\<subseteq> \\<Union>D\"\n    by blast\n  then obtain k where k: \"k \\<subseteq> {0..1}\" \"finite k\" and D_eq: \"D = ((\\<lambda>z. ball z (ee z / 3)) \\<circ> p) ` k\"\n    unfolding cover_def path_image_def image_comp \n    by (meson finite_subset_image)\n  then have kne: \"k \\<noteq> {}\"\n    using D by auto\n  have pi: \"\\<And>i. i \\<in> k \\<Longrightarrow> p i \\<in> path_image p\"\n    using k  by (auto simp: path_image_def)\n  then have eepi: \"\\<And>i. i \\<in> k \\<Longrightarrow> 0 < ee((p i))\"\n    by (metis ee)\n  define e where \"e = Min((ee \\<circ> p) ` k)\"\n  have fin_eep: \"finite ((ee \\<circ> p) ` k)\"\n    using k  by blast\n  have \"0 < e\"\n    using ee k  by (simp add: kne e_def Min_gr_iff [OF fin_eep] eepi)\n  have \"uniformly_continuous_on {0..1} p\"\n    using p  by (simp add: path_def compact_uniformly_continuous)\n  then obtain d::real where d: \"d>0\"\n          and de: \"\\<And>x x'. \\<bar>x' - x\\<bar> < d \\<Longrightarrow> x\\<in>{0..1} \\<Longrightarrow> x'\\<in>{0..1} \\<Longrightarrow> cmod (p x' - p x) < e/3\"\n    unfolding uniformly_continuous_on_def dist_norm real_norm_def\n    by (metis divide_pos_pos \\<open>0 < e\\<close> zero_less_numeral)\n  then obtain N::nat where N: \"N>0\" \"inverse N < d\"\n    using real_arch_inverse [of d]   by auto\n  show ?thesis\n  proof (intro exI conjI allI; clarify?)\n    show \"e/3 > 0\"\n      using \\<open>0 < e\\<close> by simp\n    fix g h\n    assume g: \"valid_path g\" and ghp: \"\\<forall>t\\<in>{0..1}. cmod (g t - p t) < e / 3 \\<and>  cmod (h t - p t) < e / 3\"\n       and h: \"valid_path h\"\n       and joins: \"linked_paths atends g h\"\n    { fix t::real\n      assume t: \"0 \\<le> t\" \"t \\<le> 1\"\n      then obtain u where u: \"u \\<in> k\" and ptu: \"p t \\<in> ball(p u) (ee(p u) / 3)\"\n        using \\<open>path_image p \\<subseteq> \\<Union>D\\<close> D_eq by (force simp: path_image_def)\n      then have ele: \"e \\<le> ee (p u)\" using fin_eep\n        by (simp add: e_def)\n      have \"cmod (g t - p t) < e / 3\" \"cmod (h t - p t) < e / 3\"\n        using ghp t by auto\n      with ele have \"cmod (g t - p t) < ee (p u) / 3\"\n                    \"cmod (h t - p t) < ee (p u) / 3\"\n        by linarith+\n      then have \"g t \\<in> ball(p u) (ee(p u))\"  \"h t \\<in> ball(p u) (ee(p u))\"\n        using norm_diff_triangle_ineq [of \"g t\" \"p t\" \"p t\" \"p u\"]\n              norm_diff_triangle_ineq [of \"h t\" \"p t\" \"p t\" \"p u\"] ptu eepi u\n        by (force simp: dist_norm ball_def norm_minus_commute)+\n      then have \"g t \\<in> S\" \"h t \\<in> S\" using ee u k\n        by (auto simp: path_image_def ball_def)\n    }\n    then have ghs: \"path_image g \\<subseteq> S\" \"path_image h \\<subseteq> S\"\n      by (auto simp: path_image_def)\n    moreover\n    { fix f\n      assume fhols: \"f holomorphic_on S\"\n      then have fpa: \"f contour_integrable_on g\"  \"f contour_integrable_on h\"\n        using g ghs h holomorphic_on_imp_continuous_on os contour_integrable_holomorphic_simple\n        by blast+\n      have contf: \"continuous_on S f\"\n        by (simp add: fhols holomorphic_on_imp_continuous_on)\n      { fix z\n        assume z: \"z \\<in> path_image p\"\n        have \"f holomorphic_on ball z (ee z)\"\n          using fhols ee z holomorphic_on_subset by blast\n        then have \"\\<exists>ff. (\\<forall>w \\<in> ball z (ee z). (ff has_field_derivative f w) (at w))\"\n          using holomorphic_convex_primitive [of \"ball z (ee z)\" \"{}\" f, simplified]\n          by (metis open_ball at_within_open holomorphic_on_def holomorphic_on_imp_continuous_on mem_ball)\n      }\n      then obtain ff where ff:\n            \"\\<And>z w. \\<lbrakk>z \\<in> path_image p; w \\<in> ball z (ee z)\\<rbrakk> \\<Longrightarrow> (ff z has_field_derivative f w) (at w)\"\n        by metis\n      { fix n\n        assume n: \"n \\<le> N\"\n        then have \"contour_integral(subpath 0 (n/N) h) f - contour_integral(subpath 0 (n/N) g) f =\n                   contour_integral(linepath (g(n/N)) (h(n/N))) f - contour_integral(linepath (g 0) (h 0)) f\"\n        proof (induct n)\n          case 0 show ?case by simp\n        next\n          case (Suc n)\n          obtain t where t: \"t \\<in> k\" and \"p (n/N) \\<in> ball(p t) (ee(p t) / 3)\"\n            using \\<open>path_image p \\<subseteq> \\<Union>D\\<close> [THEN subsetD, where c=\"p (n/N)\"] D_eq N Suc.prems\n            by (force simp: path_image_def)\n          then have ptu: \"cmod (p t - p (n/N)) < ee (p t) / 3\"\n            by (simp add: dist_norm)\n          have e3le: \"e/3 \\<le> ee (p t) / 3\"  using fin_eep t\n            by (simp add: e_def)\n          { fix x\n            assume x: \"n/N \\<le> x\" \"x \\<le> (1 + n)/N\"\n            then have nN01: \"0 \\<le> n/N\" \"(1 + n)/N \\<le> 1\"\n              using Suc.prems by auto\n            then have x01: \"0 \\<le> x\" \"x \\<le> 1\"\n              using x by linarith+\n            have \"cmod (p t - p x)  < ee (p t) / 3 + e/3\"\n            proof (rule norm_diff_triangle_less [OF ptu de])\n              show \"\\<bar>real n / real N - x\\<bar> < d\"\n                using x N by (auto simp: field_simps)\n            qed (use x01 Suc.prems in auto)\n            then have ptx: \"cmod (p t - p x) < 2*ee (p t)/3\"\n              using e3le eepi [OF t] by simp\n            have \"cmod (p t - g x) < 2*ee (p t)/3 + e/3\"\n              using ghp x01 \n              by (force simp add: norm_minus_commute intro!: norm_diff_triangle_less [OF ptx])\n            also have \"\\<dots> \\<le> ee (p t)\"\n              using e3le eepi [OF t] by simp\n            finally have gg: \"cmod (p t - g x) < ee (p t)\" .\n            have \"cmod (p t - h x) < 2*ee (p t)/3 + e/3 \"\n              using ghp x01 \n              by (force simp add: norm_minus_commute intro!: norm_diff_triangle_less [OF ptx])\n            also have \"\\<dots> \\<le> ee (p t)\"\n              using e3le eepi [OF t] by simp\n            finally have \"cmod (p t - g x) < ee (p t)\" \"cmod (p t - h x) < ee (p t)\"\n              using gg by auto\n          } note ptgh_ee = this\n          have \"closed_segment (g (n/N)) (h (n/N)) = path_image (linepath (h (n/N)) (g (n/N)))\"\n            by (simp add: closed_segment_commute)\n          also have pi_hgn: \"\\<dots> \\<subseteq> ball (p t) (ee (p t))\"\n            using ptgh_ee [of \"n/N\"] Suc.prems\n            by (auto simp: field_simps dist_norm dest: segment_furthest_le [where y=\"p t\"])\n          finally have gh_ns: \"closed_segment (g (n/N)) (h (n/N)) \\<subseteq> S\"\n            using ee pi t by blast\n          have pi_ghn': \"path_image (linepath (g ((1 + n) / N)) (h ((1 + n) / N))) \\<subseteq> ball (p t) (ee (p t))\"\n            using ptgh_ee [of \"(1+n)/N\"] Suc.prems\n            by (auto simp: field_simps dist_norm dest: segment_furthest_le [where y=\"p t\"])\n          then have gh_n's: \"closed_segment (g ((1 + n) / N)) (h ((1 + n) / N)) \\<subseteq> S\"\n            using \\<open>N>0\\<close> Suc.prems ee pi t\n            by (auto simp: Path_Connected.path_image_join field_simps)\n          have pi_subset_ball:\n                \"path_image (subpath (n/N) ((1+n) / N) g +++ linepath (g ((1+n) / N)) (h ((1+n) / N)) +++\n                             subpath ((1+n) / N) (n/N) h +++ linepath (h (n/N)) (g (n/N)))\n                 \\<subseteq> ball (p t) (ee (p t))\"\n          proof (intro subset_path_image_join pi_hgn pi_ghn')\n            show \"path_image (subpath (n/N) ((1+n) / N) g) \\<subseteq> ball (p t) (ee (p t))\"\n                 \"path_image (subpath ((1+n) / N) (n/N) h) \\<subseteq> ball (p t) (ee (p t))\"\n              using \\<open>N>0\\<close> Suc.prems\n              by (auto simp: path_image_subpath dist_norm field_simps ptgh_ee)\n          qed\n          have pi0: \"(f has_contour_integral 0)\n                       (subpath (n/ N) ((Suc n)/N) g +++ linepath(g ((Suc n) / N)) (h((Suc n) / N)) +++\n                        subpath ((Suc n) / N) (n/N) h +++ linepath(h (n/N)) (g (n/N)))\"\n          proof (rule Cauchy_theorem_primitive)\n            show \"\\<And>x. x \\<in> ball (p t) (ee (p t)) \n                      \\<Longrightarrow> (ff (p t) has_field_derivative f x) (at x within ball (p t) (ee (p t)))\"\n              by (metis ff open_ball at_within_open pi t)\n            qed (use Suc.prems pi_subset_ball in \\<open>simp_all add: valid_path_subpath g h\\<close>)\n          have fpa1: \"f contour_integrable_on subpath (n/N) (real (Suc n) / real N) g\"\n            using Suc.prems by (simp add: contour_integrable_subpath g fpa)\n          have fpa2: \"f contour_integrable_on linepath (g (real (Suc n) / real N)) (h (real (Suc n) / real N))\"\n            using gh_n's\n            by (auto intro!: contour_integrable_continuous_linepath continuous_on_subset [OF contf])\n          have fpa3: \"f contour_integrable_on linepath (h (n/N)) (g (n/N))\"\n            using gh_ns\n            by (auto simp: closed_segment_commute intro!: contour_integrable_continuous_linepath continuous_on_subset [OF contf])\n          have eq0: \"contour_integral (subpath (n/N) ((Suc n) / real N) g) f +\n                     contour_integral (linepath (g ((Suc n) / N)) (h ((Suc n) / N))) f +\n                     contour_integral (subpath ((Suc n) / N) (n/N) h) f +\n                     contour_integral (linepath (h (n/N)) (g (n/N))) f = 0\"\n            using contour_integral_unique [OF pi0] Suc.prems\n            by (simp add: g h fpa valid_path_subpath contour_integrable_subpath\n                          fpa1 fpa2 fpa3 algebra_simps del: of_nat_Suc)\n          have *: \"\\<And>hn he hn' gn gd gn' hgn ghn gh0 ghn'.\n                    \\<lbrakk>hn - gn = ghn - gh0;\n                     gd + ghn' + he + hgn = (0::complex);\n                     hn - he = hn'; gn + gd = gn'; hgn = -ghn\\<rbrakk> \\<Longrightarrow> hn' - gn' = ghn' - gh0\"\n            by (auto simp: algebra_simps)\n          have \"contour_integral (subpath 0 (n/N) h) f - contour_integral (subpath ((Suc n) / N) (n/N) h) f =\n                contour_integral (subpath 0 (n/N) h) f + contour_integral (subpath (n/N) ((Suc n) / N) h) f\"\n            unfolding reversepath_subpath [symmetric, of \"((Suc n) / N)\"]\n            using Suc.prems by (simp add: h fpa contour_integral_reversepath valid_path_subpath contour_integrable_subpath)\n          also have \"\\<dots> = contour_integral (subpath 0 ((Suc n) / N) h) f\"\n            using Suc.prems by (simp add: contour_integral_subpath_combine h fpa)\n          finally have pi0_eq:\n               \"contour_integral (subpath 0 (n/N) h) f - contour_integral (subpath ((Suc n) / N) (n/N) h) f =\n                contour_integral (subpath 0 ((Suc n) / N) h) f\" .\n          show ?case\n          proof (rule * [OF Suc.hyps eq0 pi0_eq])\n            show \"contour_integral (subpath 0 (n/N) g) f +\n                  contour_integral (subpath (n/N) ((Suc n) / N) g) f =\n                  contour_integral (subpath 0 ((Suc n) / N) g) f\"\n              using Suc.prems contour_integral_subpath_combine fpa(1) g by auto\n            show \"contour_integral (linepath (h (n/N)) (g (n/N))) f = - contour_integral (linepath (g (n/N)) (h (n/N))) f\"\n              by (metis contour_integral_unique fpa3 has_contour_integral_integral has_contour_integral_reverse_linepath)\n          qed (use Suc.prems in auto)\n      qed\n      } note ind = this\n      have \"contour_integral h f = contour_integral g f\"\n        using ind [OF order_refl] N joins\n        by (simp add: linked_paths_def pathstart_def pathfinish_def split: if_split_asm)\n    }\n    ultimately\n    show \"path_image g \\<subseteq> S \\<and> path_image h \\<subseteq> S \\<and> (\\<forall>f. f holomorphic_on S \\<longrightarrow> contour_integral h f = contour_integral g f)\"\n      by metis\n  qed\nqed\n\n\nlemma\n  assumes \"open S\" \"path p\" \"path_image p \\<subseteq> S\"\n    shows contour_integral_nearby_ends:\n      \"\\<exists>d. 0 < d \\<and>\n              (\\<forall>g h. valid_path g \\<and> valid_path h \\<and>\n                    (\\<forall>t \\<in> {0..1}. norm(g t - p t) < d \\<and> norm(h t - p t) < d) \\<and>\n                    pathstart h = pathstart g \\<and> pathfinish h = pathfinish g\n                    \\<longrightarrow> path_image g \\<subseteq> S \\<and>\n                        path_image h \\<subseteq> S \\<and>\n                        (\\<forall>f. f holomorphic_on S\n                            \\<longrightarrow> contour_integral h f = contour_integral g f))\"\n    and contour_integral_nearby_loops:\n      \"\\<exists>d. 0 < d \\<and>\n              (\\<forall>g h. valid_path g \\<and> valid_path h \\<and>\n                    (\\<forall>t \\<in> {0..1}. norm(g t - p t) < d \\<and> norm(h t - p t) < d) \\<and>\n                    pathfinish g = pathstart g \\<and> pathfinish h = pathstart h\n                    \\<longrightarrow> path_image g \\<subseteq> S \\<and>\n                        path_image h \\<subseteq> S \\<and>\n                        (\\<forall>f. f holomorphic_on S\n                            \\<longrightarrow> contour_integral h f = contour_integral g f))\"\n  using contour_integral_nearby [OF assms, where atends=True]\n  using contour_integral_nearby [OF assms, where atends=False]\n  unfolding linked_paths_def by simp_all\n\nlemma contour_integral_bound_exists:\nassumes S: \"open S\"\n    and g: \"valid_path g\"\n    and pag: \"path_image g \\<subseteq> S\"\n  shows \"\\<exists>L. 0 < L \\<and>\n             (\\<forall>f B. f holomorphic_on S \\<and> (\\<forall>z \\<in> S. norm(f z) \\<le> B)\n               \\<longrightarrow> norm(contour_integral g f) \\<le> L*B)\"\nproof -\n  have \"path g\" using g\n    by (simp add: valid_path_imp_path)\n  then obtain d::real and p\n    where d: \"0 < d\"\n      and p: \"polynomial_function p\" \"path_image p \\<subseteq> S\"\n      and pi: \"\\<And>f. f holomorphic_on S \\<Longrightarrow> contour_integral g f = contour_integral p f\"\n    using contour_integral_nearby_ends [OF S \\<open>path g\\<close> pag]\n    by (metis cancel_comm_monoid_add_class.diff_cancel g norm_zero path_approx_polynomial_function valid_path_polynomial_function)\n  then obtain p' where p': \"polynomial_function p'\"\n    \"\\<And>x. (p has_vector_derivative (p' x)) (at x)\"\n    by (blast intro: has_vector_derivative_polynomial_function that)\n  then have \"bounded(p' ` {0..1})\"\n    using continuous_on_polymonial_function\n    by (force simp: intro!: compact_imp_bounded compact_continuous_image)\n  then obtain L where L: \"L>0\" and nop': \"\\<And>x. \\<lbrakk>0 \\<le> x; x \\<le> 1\\<rbrakk> \\<Longrightarrow> norm (p' x) \\<le> L\"\n    by (force simp: bounded_pos)\n  { fix f B\n    assume f: \"f holomorphic_on S\" and B: \"\\<And>z. z\\<in>S \\<Longrightarrow> cmod (f z) \\<le> B\"\n    then have \"f contour_integrable_on p \\<and> valid_path p\"\n      using p S\n      by (blast intro: valid_path_polynomial_function contour_integrable_holomorphic_simple holomorphic_on_imp_continuous_on)\n    moreover have \"cmod (vector_derivative p (at x)) * cmod (f (p x)) \\<le> L * B\" if \"0 \\<le> x\" \"x \\<le> 1\" for x\n    proof (rule mult_mono)\n      show \"cmod (vector_derivative p (at x)) \\<le> L\"\n        by (metis nop' p'(2) that vector_derivative_at)\n      show \"cmod (f (p x)) \\<le> B\"\n        by (metis B atLeastAtMost_iff imageI p(2) path_defs(4) subset_eq that)\n    qed (use \\<open>L>0\\<close> in auto)\n    ultimately \n    have \"cmod (integral {0..1} (\\<lambda>x. f (p x) * vector_derivative p (at x))) \\<le> L * B\"\n      by (intro order_trans [OF integral_norm_bound_integral])\n         (auto simp: mult.commute norm_mult contour_integrable_on)\n    then have \"cmod (contour_integral g f) \\<le> L * B\"\n      using contour_integral_integral f pi by presburger\n  } then\n  show ?thesis using \\<open>L > 0\\<close>\n    by (intro exI[of _ L]) auto\nqed\n\n\nsubsection\\<open>Homotopy forms of Cauchy's theorem\\<close>\n\nlemma Cauchy_theorem_homotopic:\n    assumes hom: \"if atends then homotopic_paths S g h else homotopic_loops S g h\"\n        and \"open S\" and f: \"f holomorphic_on S\"\n        and vpg: \"valid_path g\" and vph: \"valid_path h\"\n    shows \"contour_integral g f = contour_integral h f\"\nproof -\n  have pathsf: \"linked_paths atends g h\"\n    using hom  by (auto simp: linked_paths_def homotopic_paths_imp_pathstart homotopic_paths_imp_pathfinish homotopic_loops_imp_loop)\n  obtain k :: \"real \\<times> real \\<Rightarrow> complex\"\n    where contk: \"continuous_on ({0..1} \\<times> {0..1}) k\"\n      and ks: \"k ` ({0..1} \\<times> {0..1}) \\<subseteq> S\"\n      and k [simp]: \"\\<forall>x. k (0, x) = g x\" \"\\<forall>x. k (1, x) = h x\"\n      and ksf: \"\\<forall>t\\<in>{0..1}. linked_paths atends g (\\<lambda>x. k (t, x))\"\n      using hom pathsf by (auto simp: linked_paths_def homotopic_paths_def homotopic_loops_def homotopic_with_def split: if_split_asm)\n  have ucontk: \"uniformly_continuous_on ({0..1} \\<times> {0..1}) k\"\n    by (blast intro: compact_Times compact_uniformly_continuous [OF contk])\n  { fix t::real assume t: \"t \\<in> {0..1}\"\n    have \"Pair t ` {0..1} \\<subseteq> {0..1} \\<times> {0..1}\"\n      using t by force\n    then have pak: \"path (k \\<circ> (\\<lambda>u. (t, u)))\"\n      unfolding path_def\n      by (intro continuous_intros continuous_on_subset [OF contk])+\n    have pik: \"path_image (k \\<circ> Pair t) \\<subseteq> S\"\n      using ks t by (auto simp: path_image_def)\n    obtain e where \"e>0\" and e:\n         \"\\<And>g h. \\<lbrakk>valid_path g; valid_path h;\n                  \\<forall>u\\<in>{0..1}. cmod (g u - (k \\<circ> Pair t) u) < e \\<and> cmod (h u - (k \\<circ> Pair t) u) < e;\n                  linked_paths atends g h\\<rbrakk>\n                 \\<Longrightarrow> contour_integral h f = contour_integral g f\"\n      using contour_integral_nearby [OF \\<open>open S\\<close> pak pik, of atends] f by metis\n    obtain d where \"d>0\" and d:\n        \"\\<And>x x'. \\<lbrakk>x \\<in> {0..1} \\<times> {0..1}; x' \\<in> {0..1} \\<times> {0..1}; norm (x'-x) < d\\<rbrakk> \\<Longrightarrow> norm (k x' - k x) < e/4\"\n      by (rule uniformly_continuous_onE [OF ucontk, of \"e/4\"]) (auto simp: dist_norm \\<open>e>0\\<close>)\n    { fix t1 t2\n      assume t1: \"0 \\<le> t1\" \"t1 \\<le> 1\" and t2: \"0 \\<le> t2\" \"t2 \\<le> 1\" and ltd: \"\\<bar>t1 - t\\<bar> < d\" \"\\<bar>t2 - t\\<bar> < d\"\n      have no2: \"norm(g1 - kt) < e\" if \"norm(g1 - k1) < e/4\" \"norm(k1 - kt) < e/4\" for g1 k1 kt :: complex\n      proof (rule norm_triangle_half_l)\n        show \"cmod (g1 - k1) < e/2\" \"cmod (kt - k1) < e/2\"\n          using \\<open>e > 0\\<close> that by (auto simp: norm_minus_commute intro: order_less_trans)\n      qed\n      have \"\\<exists>d>0. \\<forall>g1 g2. valid_path g1 \\<and> valid_path g2 \\<and>\n                          (\\<forall>u\\<in>{0..1}. cmod (g1 u - k (t1, u)) < d \\<and> cmod (g2 u - k (t2, u)) < d) \\<and>\n                          linked_paths atends g1 g2 \\<longrightarrow>\n                          contour_integral g2 f = contour_integral g1 f\"\n        using t t1 t2 ltd \\<open>e > 0\\<close>\n        by (rule_tac x=\"e/4\" in exI) (auto intro!: e simp: d no2 simp del: less_divide_eq_numeral1)\n    }\n    then have \"\\<exists>e. 0 < e \\<and>\n              (\\<forall>t1 t2. t1 \\<in> {0..1} \\<and> t2 \\<in> {0..1} \\<and> \\<bar>t1 - t\\<bar> < e \\<and> \\<bar>t2 - t\\<bar> < e\n                \\<longrightarrow> (\\<exists>d. 0 < d \\<and>\n                     (\\<forall>g1 g2. valid_path g1 \\<and> valid_path g2 \\<and>\n                       (\\<forall>u \\<in> {0..1}.\n                          norm(g1 u - k((t1,u))) < d \\<and> norm(g2 u - k((t2,u))) < d) \\<and>\n                          linked_paths atends g1 g2\n                          \\<longrightarrow> contour_integral g2 f = contour_integral g1 f)))\"\n      by (rule_tac x=d in exI) (simp add: \\<open>d > 0\\<close>)\n  }\n  then obtain ee where ee:\n       \"\\<And>t. t \\<in> {0..1} \\<Longrightarrow> ee t > 0 \\<and>\n          (\\<forall>t1 t2. t1 \\<in> {0..1} \\<longrightarrow> t2 \\<in> {0..1} \\<longrightarrow> \\<bar>t1 - t\\<bar> < ee t \\<longrightarrow> \\<bar>t2 - t\\<bar> < ee t\n            \\<longrightarrow> (\\<exists>d. 0 < d \\<and>\n                 (\\<forall>g1 g2. valid_path g1 \\<and> valid_path g2 \\<and>\n                   (\\<forall>u \\<in> {0..1}.\n                      norm(g1 u - k((t1,u))) < d \\<and> norm(g2 u - k((t2,u))) < d) \\<and>\n                      linked_paths atends g1 g2\n                      \\<longrightarrow> contour_integral g2 f = contour_integral g1 f)))\"\n    by metis\n  note ee_rule = ee [THEN conjunct2, rule_format, of 0 0 0]\n  define C where \"C = (\\<lambda>t. ball t (ee t / 3)) ` {0..1}\"\n  obtain C' where C': \"C' \\<subseteq> C\" \"finite C'\" and C'01: \"{0..1} \\<subseteq> \\<Union>C'\"\n  proof (rule compactE [OF compact_interval])\n    show \"{0..1} \\<subseteq> \\<Union>C\"\n      using ee [THEN conjunct1] by (auto simp: C_def dist_norm)\n  qed (use C_def in auto)\n  define kk where \"kk = {t \\<in> {0..1}. ball t (ee t / 3) \\<in> C'}\"\n  have kk01: \"kk \\<subseteq> {0..1}\" by (auto simp: kk_def)\n  define e where \"e = Min (ee ` kk)\"\n  have C'_eq: \"C' = (\\<lambda>t. ball t (ee t / 3)) ` kk\"\n    using C' by (auto simp: kk_def C_def)\n  have ee_pos[simp]: \"\\<And>t. t \\<in> {0..1} \\<Longrightarrow> ee t > 0\"\n    by (simp add: kk_def ee)\n  moreover have \"finite kk\"\n    using \\<open>finite C'\\<close> kk01 by (force simp: C'_eq inj_on_def ball_eq_ball_iff dest: ee_pos finite_imageD)\n  moreover have \"kk \\<noteq> {}\" using \\<open>{0..1} \\<subseteq> \\<Union>C'\\<close> C'_eq by force\n  ultimately have \"e > 0\"\n    using finite_less_Inf_iff [of \"ee ` kk\" 0] kk01 by (force simp: e_def)\n  then obtain N::nat where \"N > 0\" and N: \"1/N < e/3\"\n    by (meson divide_pos_pos nat_approx_posE zero_less_Suc zero_less_numeral)\n  have e_le_ee: \"\\<And>i. i \\<in> kk \\<Longrightarrow> e \\<le> ee i\"\n    using \\<open>finite kk\\<close> by (simp add: e_def Min_le_iff [of \"ee ` kk\"])\n  have plus: \"\\<exists>t \\<in> kk. x \\<in> ball t (ee t / 3)\" if \"x \\<in> {0..1}\" for x\n    using C' subsetD [OF C'01 that]  unfolding C'_eq by blast\n  have [OF order_refl]:\n      \"\\<exists>d. 0 < d \\<and> (\\<forall>j. valid_path j \\<and> (\\<forall>u \\<in> {0..1}. norm(j u - k (n/N, u)) < d) \\<and> linked_paths atends g j\n                        \\<longrightarrow> contour_integral j f = contour_integral g f)\"\n       if \"n \\<le> N\" for n\n  using that\n  proof (induct n)\n    case 0 show ?case \n      using ee_rule \n      by clarsimp (metis diff_self norm_eq_zero vpg)\n  next\n    case (Suc n)\n    then have N01: \"n/N \\<in> {0..1}\" \"(Suc n)/N \\<in> {0..1}\"  by auto\n    then obtain t where t: \"t \\<in> kk\" \"n/N \\<in> ball t (ee t / 3)\"\n      using plus [of \"n/N\"] by blast\n    then have nN_less: \"\\<bar>n/N - t\\<bar> < ee t\"\n      by (simp add: dist_norm del: less_divide_eq_numeral1)\n    have n'N_less: \"\\<bar>real (Suc n) / real N - t\\<bar> < ee t\"\n      using t N \\<open>N > 0\\<close> e_le_ee [of t]\n      by (simp add: dist_norm add_divide_distrib abs_diff_less_iff del: less_divide_eq_numeral1) (simp add: field_simps)\n    have t01: \"t \\<in> {0..1}\" using \\<open>kk \\<subseteq> {0..1}\\<close> \\<open>t \\<in> kk\\<close> by blast\n    obtain d1 where \"d1 > 0\" and d1:\n        \"\\<And>g1 g2. \\<lbrakk>valid_path g1; valid_path g2;\n                   \\<forall>u\\<in>{0..1}. cmod (g1 u - k (n/N, u)) < d1 \\<and> cmod (g2 u - k ((Suc n) / N, u)) < d1;\n                   linked_paths atends g1 g2\\<rbrakk>\n                   \\<Longrightarrow> contour_integral g2 f = contour_integral g1 f\"\n      using ee [THEN conjunct2, rule_format, OF t01 N01 nN_less n'N_less] by fastforce\n    have \"n \\<le> N\" using Suc.prems by auto\n    with Suc.hyps\n    obtain d2 where \"d2 > 0\"\n      and d2: \"\\<And>j. \\<lbrakk>valid_path j; \\<forall>u\\<in>{0..1}. cmod (j u - k (n/N, u)) < d2; linked_paths atends g j\\<rbrakk>\n                     \\<Longrightarrow> contour_integral j f = contour_integral g f\"\n      by auto\n    have \"Pair (n/ N) ` {0..1} \\<subseteq> {0..1} \\<times> {0..1}\"\n      using N01 by auto\n    then have \"continuous_on {0..1} (k \\<circ> (\\<lambda>u. (n/N, u)))\"\n      by (intro continuous_intros continuous_on_subset [OF contk])\n    then have pkn: \"path (\\<lambda>u. k (n/N, u))\"\n      by (simp add: path_def)\n    have min12: \"min d1 d2 > 0\" by (simp add: \\<open>0 < d1\\<close> \\<open>0 < d2\\<close>)\n    obtain p where \"polynomial_function p\"\n        and psf: \"pathstart p = pathstart (\\<lambda>u. k (n/N, u))\"\n                 \"pathfinish p = pathfinish (\\<lambda>u. k (n/N, u))\"\n        and pk_le:  \"\\<And>t. t\\<in>{0..1} \\<Longrightarrow> cmod (p t - k (n/N, t)) < min d1 d2\"\n      using path_approx_polynomial_function [OF pkn min12] by blast\n    then have vpp: \"valid_path p\" using valid_path_polynomial_function by blast\n    have lpa: \"linked_paths atends g p\"\n      by (metis (mono_tags, lifting) N01(1) ksf linked_paths_def pathfinish_def pathstart_def psf)\n    show ?case\n    proof (intro exI; safe)\n      fix j\n      assume \"valid_path j\" \"linked_paths atends g j\"\n        and \"\\<forall>u\\<in>{0..1}. cmod (j u - k (real (Suc n) / real N, u)) < min d1 d2\"\n      then have \"contour_integral j f = contour_integral p f\"\n        using pk_le N01(1) ksf by (force intro!: vpp d1 simp add: linked_paths_def psf)\n      also have \"... = contour_integral g f\"\n        using pk_le by (force intro!: vpp d2 lpa)\n      finally show \"contour_integral j f = contour_integral g f\" .\n    qed (simp add: \\<open>0 < d1\\<close> \\<open>0 < d2\\<close>)\n  qed\n  then obtain d where \"0 < d\"\n                       \"\\<And>j. valid_path j \\<and> (\\<forall>u \\<in> {0..1}. norm(j u - k (1,u)) < d) \\<and> linked_paths atends g j\n                            \\<Longrightarrow> contour_integral j f = contour_integral g f\"\n    using \\<open>N>0\\<close> by auto\n  then have \"linked_paths atends g h \\<Longrightarrow> contour_integral h f = contour_integral g f\"\n    using \\<open>N>0\\<close> vph by fastforce\n  then show ?thesis\n    by (simp add: pathsf)\nqed\n\nproposition Cauchy_theorem_homotopic_paths:\n    assumes hom: \"homotopic_paths S g h\"\n        and \"open S\" and f: \"f holomorphic_on S\"\n        and vpg: \"valid_path g\" and vph: \"valid_path h\"\n    shows \"contour_integral g f = contour_integral h f\"\n  using Cauchy_theorem_homotopic [of True S g h] assms by simp\n\nproposition Cauchy_theorem_homotopic_loops:\n    assumes hom: \"homotopic_loops S g h\"\n        and \"open S\" and f: \"f holomorphic_on S\"\n        and vpg: \"valid_path g\" and vph: \"valid_path h\"\n    shows \"contour_integral g f = contour_integral h f\"\n  using Cauchy_theorem_homotopic [of False S g h] assms by simp\n\nlemma has_contour_integral_newpath:\n    \"\\<lbrakk>(f has_contour_integral y) h; f contour_integrable_on g; contour_integral g f = contour_integral h f\\<rbrakk>\n     \\<Longrightarrow> (f has_contour_integral y) g\"\n  using has_contour_integral_integral contour_integral_unique by auto\n\nlemma Cauchy_theorem_null_homotopic:\n     \"\\<lbrakk>f holomorphic_on S; open S; valid_path g; homotopic_loops S g (linepath a a)\\<rbrakk> \n      \\<Longrightarrow> (f has_contour_integral 0) g\"\n  by (metis Cauchy_theorem_homotopic_loops contour_integrable_holomorphic_simple valid_path_linepath\n            contour_integral_trivial has_contour_integral_integral homotopic_loops_imp_subset)\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/Complex_Analysis/Cauchy_Integral_Theorem.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8418256472515683, "lm_q2_score": 0.8354835411997897, "lm_q1q2_score": 0.7033314728385454}}
{"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_BubSortCount\nimports \"../../Test_Base\"\nbegin\n\ndatatype ('a, 'b) pair = pair2 \"'a\" \"'b\"\n\ndatatype 'a list = nil2 | cons2 \"'a\" \"'a list\"\n\nfun count :: \"'a => 'a list => int\" where\n\"count x (nil2) = 0\"\n| \"count x (cons2 z ys) =\n     (if (x = z) then 1 + (count x ys) else count x ys)\"\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  \"((count x (bubsort 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_BubSortCount.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240964782011, "lm_q2_score": 0.8128673201042492, "lm_q1q2_score": 0.7033123925938557}}
{"text": "(*  Title:       Signed (Finite) Multisets\n    Author:      Jasmin Blanchette <jasmin.blanchette at inria.fr>, 2016\n    Maintainer:  Jasmin Blanchette <jasmin.blanchette at inria.fr>\n*)\n\nsection \\<open>Signed (Finite) Multisets\\<close>\n\ntheory Signed_Multiset\nimports Multiset_More\nabbrevs\n  \"!z\" = \"\\<^sub>z\"\nbegin\n\n\nsubsection \\<open>Definition of Signed Multisets\\<close>\n\ndefinition equiv_zmset :: \"'a multiset \\<times> 'a multiset \\<Rightarrow> 'a multiset \\<times> 'a multiset \\<Rightarrow> bool\" where\n  \"equiv_zmset = (\\<lambda>(Mp, Mn) (Np, Nn). Mp + Nn = Np + Mn)\"\n\nquotient_type 'a zmultiset = \"'a multiset \\<times> 'a multiset\" / equiv_zmset\n  by (rule equivpI, simp_all add: equiv_zmset_def reflp_def symp_def transp_def)\n    (metis multi_union_self_other_eq union_lcomm)\n\n\nsubsection \\<open>Basic Operations on Signed Multisets\\<close>\n\ninstantiation zmultiset :: (type) cancel_comm_monoid_add\nbegin\n\nlift_definition zero_zmultiset :: \"'a zmultiset\" is \"({#}, {#})\" .\n\nabbreviation empty_zmset :: \"'a zmultiset\" (\"{#}\\<^sub>z\") where\n  \"empty_zmset \\<equiv> 0\"\n\nlift_definition minus_zmultiset :: \"'a zmultiset \\<Rightarrow> 'a zmultiset \\<Rightarrow> 'a zmultiset\" is\n  \"\\<lambda>(Mp, Mn) (Np, Nn). (Mp + Nn, Mn + Np)\"\n  by (auto simp: equiv_zmset_def union_commute union_lcomm)\n\nlift_definition plus_zmultiset :: \"'a zmultiset \\<Rightarrow> 'a zmultiset \\<Rightarrow> 'a zmultiset\" is\n  \"\\<lambda>(Mp, Mn) (Np, Nn). (Mp + Np, Mn + Nn)\"\n  by (auto simp: equiv_zmset_def union_commute union_lcomm)\n\ninstance\n  by (intro_classes; transfer) (auto simp: equiv_zmset_def)\n\nend\n\ninstantiation zmultiset :: (type) group_add\nbegin\n\nlift_definition uminus_zmultiset :: \"'a zmultiset \\<Rightarrow> 'a zmultiset\" is \"\\<lambda>(Mp, Mn). (Mn, Mp)\"\n  by (auto simp: equiv_zmset_def add.commute)\n\ninstance\n  by (intro_classes; transfer) (auto simp: equiv_zmset_def)\n\nend\n\nlift_definition zcount :: \"'a zmultiset \\<Rightarrow> 'a \\<Rightarrow> int\" is\n  \"\\<lambda>(Mp, Mn) x. int (count Mp x) - int (count Mn x)\"\n  by (auto simp del: of_nat_add simp: equiv_zmset_def fun_eq_iff multiset_eq_iff diff_eq_eq\n    diff_add_eq eq_diff_eq of_nat_add[symmetric])\n\nlemma zcount_inject: \"zcount M = zcount N \\<longleftrightarrow> M = N\"\n  by transfer (auto simp del: of_nat_add simp: equiv_zmset_def fun_eq_iff multiset_eq_iff\n    diff_eq_eq diff_add_eq eq_diff_eq of_nat_add[symmetric])\n\nlemma zmultiset_eq_iff: \"M = N \\<longleftrightarrow> (\\<forall>a. zcount M a = zcount N a)\"\n  by (simp only: zcount_inject[symmetric] fun_eq_iff)\n\nlemma zmultiset_eqI: \"(\\<And>x. zcount A x = zcount B x) \\<Longrightarrow> A = B\"\n  using zmultiset_eq_iff by auto\n\nlemma zcount_uminus[simp]: \"zcount (- A) x = - zcount A x\"\n  by transfer auto\n\nlift_definition add_zmset :: \"'a \\<Rightarrow> 'a zmultiset \\<Rightarrow> 'a zmultiset\" is\n  \"\\<lambda>x (Mp, Mn). (add_mset x Mp, Mn)\"\n  by (auto simp: equiv_zmset_def)\n\nsyntax\n  \"_zmultiset\" :: \"args \\<Rightarrow> 'a zmultiset\" (\"{#(_)#}\\<^sub>z\")\ntranslations\n  \"{#x, xs#}\\<^sub>z\" == \"CONST add_zmset x {#xs#}\\<^sub>z\"\n  \"{#x#}\\<^sub>z\" == \"CONST add_zmset x {#}\\<^sub>z\"\n\nlemma zcount_empty[simp]: \"zcount {#}\\<^sub>z a = 0\"\n  by transfer auto\n\nlemma zcount_add_zmset[simp]:\n  \"zcount (add_zmset b A) a = (if b = a then zcount A a + 1 else zcount A a)\"\n  by transfer auto\n\nlemma zcount_single: \"zcount {#b#}\\<^sub>z a = (if b = a then 1 else 0)\"\n  by simp\n\nlemma add_add_same_iff_zmset[simp]: \"add_zmset a A = add_zmset a B \\<longleftrightarrow> A = B\"\n  by (auto simp: zmultiset_eq_iff)\n\nlemma add_zmset_commute: \"add_zmset x (add_zmset y M) = add_zmset y (add_zmset x M)\"\n  by (auto simp: zmultiset_eq_iff)\n\nlemma\n  singleton_ne_empty_zmset[simp]: \"{#x#}\\<^sub>z \\<noteq> {#}\\<^sub>z\" and\n  empty_ne_singleton_zmset[simp]: \"{#}\\<^sub>z \\<noteq> {#x#}\\<^sub>z\"\n  by (auto dest!: arg_cong2[of _ _ x _ zcount])\n\nlemma\n  singleton_ne_uminus_singleton_zmset[simp]: \"{#x#}\\<^sub>z \\<noteq> - {#y#}\\<^sub>z\" and\n  uminus_singleton_ne_singleton_zmset[simp]: \"- {#x#}\\<^sub>z \\<noteq> {#y#}\\<^sub>z\"\n  by (auto dest!: arg_cong2[of _ _ x x zcount] split: if_splits)\n\n\nsubsubsection \\<open>Conversion to Set and Membership\\<close>\n\ndefinition set_zmset :: \"'a zmultiset \\<Rightarrow> 'a set\" where\n  \"set_zmset M = {x. zcount M x \\<noteq> 0}\"\n\nabbreviation elem_zmset :: \"'a \\<Rightarrow> 'a zmultiset \\<Rightarrow> bool\" where\n  \"elem_zmset a M \\<equiv> a \\<in> set_zmset M\"\n\nnotation\n  elem_zmset (\"'(\\<in>#\\<^sub>z')\") and\n  elem_zmset (\"(_/ \\<in>#\\<^sub>z _)\" [51, 51] 50)\n\nnotation (ASCII)\n  elem_zmset (\"'(:#z')\") and\n  elem_zmset (\"(_/ :#z _)\" [51, 51] 50)\n\nabbreviation not_elem_zmset :: \"'a \\<Rightarrow> 'a zmultiset \\<Rightarrow> bool\" where\n  \"not_elem_zmset a M \\<equiv> a \\<notin> set_zmset M\"\n\nnotation\n  not_elem_zmset (\"'(\\<notin>#\\<^sub>z')\") and\n  not_elem_zmset (\"(_/ \\<notin>#\\<^sub>z _)\" [51, 51] 50)\n\nnotation (ASCII)\n  not_elem_zmset (\"'(~:#z')\") and\n  not_elem_zmset (\"(_/ ~:#z _)\" [51, 51] 50)\n\ncontext\nbegin\n\nqualified abbreviation Ball :: \"'a zmultiset \\<Rightarrow> ('a \\<Rightarrow> bool) \\<Rightarrow> bool\" where\n  \"Ball M \\<equiv> Set.Ball (set_zmset M)\"\n\nqualified abbreviation Bex :: \"'a zmultiset \\<Rightarrow> ('a \\<Rightarrow> bool) \\<Rightarrow> bool\" where\n  \"Bex M \\<equiv> Set.Bex (set_zmset M)\"\n\nend\n\nsyntax\n  \"_MBall\" :: \"pttrn \\<Rightarrow> 'a set \\<Rightarrow> bool \\<Rightarrow> bool\" (\"(3\\<forall>_\\<in>#\\<^sub>z_./ _)\" [0, 0, 10] 10)\n  \"_MBex\" :: \"pttrn \\<Rightarrow> 'a set \\<Rightarrow> bool \\<Rightarrow> bool\" (\"(3\\<exists>_\\<in>#\\<^sub>z_./ _)\" [0, 0, 10] 10)\n\nsyntax (ASCII)\n  \"_MBall\" :: \"pttrn \\<Rightarrow> 'a set \\<Rightarrow> bool \\<Rightarrow> bool\" (\"(3\\<forall>_:#\\<^sub>z_./ _)\" [0, 0, 10] 10)\n  \"_MBex\" :: \"pttrn \\<Rightarrow> 'a set \\<Rightarrow> bool \\<Rightarrow> bool\" (\"(3\\<exists>_:#\\<^sub>z_./ _)\" [0, 0, 10] 10)\n\ntranslations\n  \"\\<forall>x\\<in>#\\<^sub>zA. P\" \\<rightleftharpoons> \"CONST Signed_Multiset.Ball A (\\<lambda>x. P)\"\n  \"\\<exists>x\\<in>#\\<^sub>zA. P\" \\<rightleftharpoons> \"CONST Signed_Multiset.Bex A (\\<lambda>x. P)\"\n\nlemma zcount_eq_zero_iff: \"zcount M x = 0 \\<longleftrightarrow> x \\<notin>#\\<^sub>z M\"\n  by (auto simp add: set_zmset_def)\n\nlemma not_in_iff_zmset: \"x \\<notin>#\\<^sub>z M \\<longleftrightarrow> zcount M x = 0\"\n  by (auto simp add: zcount_eq_zero_iff)\n\nlemma zcount_ne_zero_iff[simp]: \"zcount M x \\<noteq> 0 \\<longleftrightarrow> x \\<in>#\\<^sub>z M\"\n  by (auto simp add: set_zmset_def)\n\nlemma zcount_inI:\n  assumes \"zcount M x = 0 \\<Longrightarrow> False\"\n  shows \"x \\<in>#\\<^sub>z M\"\nproof (rule ccontr)\n  assume \"x \\<notin>#\\<^sub>z M\"\n  with assms show False by (simp add: not_in_iff_zmset)\nqed\n\nlemma set_zmset_empty[simp]: \"set_zmset {#}\\<^sub>z = {}\"\n  by (simp add: set_zmset_def)\n\nlemma set_zmset_single: \"set_zmset {#b#}\\<^sub>z = {b}\"\n  by (simp add: set_zmset_def)\n\nlemma set_zmset_eq_empty_iff[simp]: \"set_zmset M = {} \\<longleftrightarrow> M = {#}\\<^sub>z\"\n  by (auto simp add: zmultiset_eq_iff zcount_eq_zero_iff)\n\nlemma finite_count_ne: \"finite {x. count M x \\<noteq> count N x}\"\nproof -\n  have \"{x. count M x \\<noteq> count N x} \\<subseteq> set_mset M \\<union> set_mset N\"\n    by (auto simp: not_in_iff)\n  moreover have \"finite (set_mset M \\<union> set_mset N)\"\n    by (rule finite_UnI[OF finite_set_mset finite_set_mset])\n  ultimately show ?thesis\n    by (rule finite_subset)\nqed\n\nlemma finite_set_zmset[iff]: \"finite (set_zmset M)\"\n  unfolding set_zmset_def by transfer (auto intro: finite_count_ne)\n\nlemma zmultiset_nonemptyE[elim]:\n  assumes \"A \\<noteq> {#}\\<^sub>z\"\n  obtains x where \"x \\<in>#\\<^sub>z A\"\nproof -\n  have \"\\<exists>x. x \\<in>#\\<^sub>z A\"\n    by (rule ccontr) (insert assms, auto)\n  with that show ?thesis\n    by blast\nqed\n\n\nsubsubsection \\<open>Union\\<close>\n\nlemma zcount_union[simp]: \"zcount (M + N) a = zcount M a + zcount N a\"\n  by transfer auto\n\nlemma union_add_left_zmset[simp]: \"add_zmset a A + B = add_zmset a (A + B)\"\n  by (auto simp: zmultiset_eq_iff)\n\nlemma union_zmset_add_zmset_right[simp]: \"A + add_zmset a B = add_zmset a (A + B)\"\n  by (auto simp: zmultiset_eq_iff)\n\nlemma add_zmset_add_single: \\<open>add_zmset a A = A + {#a#}\\<^sub>z\\<close>\n  by (subst union_zmset_add_zmset_right, subst add.comm_neutral) (rule refl)\n\n\nsubsubsection \\<open>Difference\\<close>\n\nlemma zcount_diff[simp]: \"zcount (M - N) a = zcount M a - zcount N a\"\n  by transfer auto\n\nlemma add_zmset_diff_bothsides: \\<open>add_zmset a M - add_zmset a A = M - A\\<close>\n  by (auto simp: zmultiset_eq_iff)\n\nlemma in_diff_zcount: \"a \\<in>#\\<^sub>z M - N \\<longleftrightarrow> zcount N a \\<noteq> zcount M a\"\n  by (fastforce simp: set_zmset_def)\n\nlemma diff_add_zmset:\n  fixes M N Q :: \"'a zmultiset\"\n  shows \"M - (N + Q) = M - N - Q\"\n  by (rule sym) (fact diff_diff_add)\n\nlemma insert_Diff_zmset[simp]: \"add_zmset x (M - {#x#}\\<^sub>z) = M\"\n  by (clarsimp simp: zmultiset_eq_iff)\n\nlemma diff_union_swap_zmset: \"add_zmset b (M - {#a#}\\<^sub>z) = add_zmset b M - {#a#}\\<^sub>z\"\n  by (auto simp add: zmultiset_eq_iff)\n\nlemma diff_add_zmset_swap[simp]: \"add_zmset b M - A = add_zmset b (M - A)\"\n  by (auto simp add: zmultiset_eq_iff)\n\nlemma diff_diff_add_zmset[simp]: \"(M :: 'a zmultiset) - N - P = M - (N + P)\"\n  by (rule diff_diff_add)\n\nlemma zmset_add[elim?]:\n  obtains B where \"A = add_zmset a B\"\nproof -\n  have \"A = add_zmset a (A - {#a#}\\<^sub>z)\"\n    by simp\n  with that show thesis .\nqed\n\n\nsubsubsection \\<open>Equality of Signed Multisets\\<close>\n\nlemma single_eq_single_zmset[simp]: \"{#a#}\\<^sub>z = {#b#}\\<^sub>z \\<longleftrightarrow> a = b\"\n  by (auto simp add: zmultiset_eq_iff)\n\nlemma multi_self_add_other_not_self_zmset[simp]: \"M = add_zmset x M \\<longleftrightarrow> False\"\n  by (auto simp add: zmultiset_eq_iff)\n\nlemma add_zmset_remove_trivial: \\<open>add_zmset x M - {#x#}\\<^sub>z = M\\<close>\n  by simp\n\nlemma diff_single_eq_union_zmset: \"M - {#x#}\\<^sub>z = N \\<longleftrightarrow> M = add_zmset x N\"\n  by auto\n\nlemma union_single_eq_diff_zmset: \"add_zmset x M = N \\<Longrightarrow> M = N - {#x#}\\<^sub>z\"\n  unfolding add_zmset_add_single[of _ M] by (fact add_implies_diff)\n\nlemma add_zmset_eq_conv_diff:\n  \"add_zmset a M = add_zmset b N \\<longleftrightarrow>\n   M = N \\<and> a = b \\<or> M = add_zmset b (N - {#a#}\\<^sub>z) \\<and> N = add_zmset a (M - {#b#}\\<^sub>z)\"\n  by (simp add: zmultiset_eq_iff) fastforce\n\nlemma add_zmset_eq_conv_ex:\n  \"(add_zmset a M = add_zmset b N) =\n    (M = N \\<and> a = b \\<or> (\\<exists>K. M = add_zmset b K \\<and> N = add_zmset a K))\"\n  by (auto simp add: add_zmset_eq_conv_diff)\n\nlemma multi_member_split: \"\\<exists>A. M = add_zmset x A\"\n  by (rule exI[where x = \"M - {#x#}\\<^sub>z\"]) simp\n\n\nsubsection \\<open>Conversions from and to Multisets\\<close>\n\nlift_definition zmset_of :: \"'a multiset \\<Rightarrow> 'a zmultiset\" is \"\\<lambda>f. (Abs_multiset f, {#})\" .\n\nlemma zmset_of_inject[simp]: \"zmset_of M = zmset_of N \\<longleftrightarrow> M = N\"\n  by (simp add: zmset_of_def, transfer, auto simp: equiv_zmset_def)\n\nlemma zmset_of_empty[simp]: \"zmset_of {#} = {#}\\<^sub>z\"\n  by (simp add: zmset_of_def zero_zmultiset_def)\n\nlemma zmset_of_add_mset[simp]: \"zmset_of (add_mset x M) = add_zmset x (zmset_of M)\"\n  by transfer (auto simp: equiv_zmset_def add_mset_def cong: if_cong)\n\nlemma zcount_of_mset[simp]: \"zcount (zmset_of M) x = int (count M x)\"\n  by (induct M) auto\n\nlemma zmset_of_plus: \"zmset_of (M + N) = zmset_of M + zmset_of N\"\n  by (transfer, auto simp: equiv_zmset_def eq_onp_same_args plus_multiset.abs_eq)+\n\nlift_definition mset_pos :: \"'a zmultiset \\<Rightarrow> 'a multiset\" is \"\\<lambda>(Mp, Mn). count (Mp - Mn)\"\n  by (clarsimp simp: equiv_zmset_def intro!: arg_cong[of _ _ count])\n    (metis add.commute add_diff_cancel_right)\n\nlift_definition mset_neg :: \"'a zmultiset \\<Rightarrow> 'a multiset\" is \"\\<lambda>(Mp, Mn). count (Mn - Mp)\"\n  by (clarsimp simp: equiv_zmset_def intro!: arg_cong[of _ _ count])\n    (metis add.commute add_diff_cancel_right)\n\nlemma\n  zmset_of_inverse[simp]: \"mset_pos (zmset_of M) = M\" and\n  minus_zmset_of_inverse[simp]: \"mset_neg (- zmset_of M) = M\"\n  by (transfer, simp)+\n\nlemma neg_zmset_pos[simp]: \"mset_neg (zmset_of M) = {#}\"\n  by (rule zmset_of_inject[THEN iffD1], simp, transfer, auto simp: equiv_zmset_def)+\n\nlemma\n  count_mset_pos[simp]: \"count (mset_pos M) x = nat (zcount M x)\" and\n  count_mset_neg[simp]: \"count (mset_neg M) x = nat (- zcount M x)\"\n  by (transfer; auto)+\n\nlemma\n  mset_pos_empty[simp]: \"mset_pos {#}\\<^sub>z = {#}\" and\n  mset_neg_empty[simp]: \"mset_neg {#}\\<^sub>z = {#}\"\n  by (rule multiset_eqI, simp)+\n\nlemma\n  mset_pos_singleton[simp]: \"mset_pos {#x#}\\<^sub>z = {#x#}\" and\n  mset_neg_singleton[simp]: \"mset_neg {#x#}\\<^sub>z = {#}\"\n  by (rule multiset_eqI, simp)+\n\nlemma\n  mset_pos_neg_partition: \"M = zmset_of (mset_pos M) - zmset_of (mset_neg M)\" and\n  mset_pos_as_neg: \"zmset_of (mset_pos M) = zmset_of (mset_neg M) + M\" and\n  mset_neg_as_pos: \"zmset_of (mset_neg M) = zmset_of (mset_pos M) - M\"\n  by (rule zmultiset_eqI, simp)+\n\nlemma mset_pos_uminus[simp]: \"mset_pos (- A) = mset_neg A\"\n  by (rule multiset_eqI) simp\n\nlemma mset_neg_uminus[simp]: \"mset_neg (- A) = mset_pos A\"\n  by (rule multiset_eqI) simp\n\nlemma mset_pos_plus[simp]:\n  \"mset_pos (A + B) = (mset_pos A - mset_neg B) + (mset_pos B - mset_neg A)\"\n  by (rule multiset_eqI) simp\n\nlemma mset_neg_plus[simp]:\n  \"mset_neg (A + B) = (mset_neg A - mset_pos B) + (mset_neg B - mset_pos A)\"\n  by (rule multiset_eqI) simp\n\nlemma mset_pos_diff[simp]:\n  \"mset_pos (A - B) = (mset_pos A - mset_pos B) + (mset_neg B - mset_neg A)\"\n  by (rule mset_pos_plus[of A \"- B\", simplified])\n\nlemma mset_neg_diff[simp]:\n  \"mset_neg (A - B) = (mset_neg A - mset_neg B) + (mset_pos B - mset_pos A)\"\n  by (rule mset_neg_plus[of A \"- B\", simplified])\n\nlemma mset_pos_neg_dual:\n  \"mset_pos a + mset_pos b + (mset_neg a - mset_pos b) + (mset_neg b - mset_pos a) =\n   mset_neg a + mset_neg b + (mset_pos a - mset_neg b) + (mset_pos b - mset_neg a)\"\n  using [[linarith_split_limit = 20]] by (rule multiset_eqI) simp\n\nlemma decompose_zmset_of2:\n  obtains A B C where\n    \"M = zmset_of A + C\" and\n    \"N = zmset_of B + C\"\nproof\n  let ?A = \"zmset_of (mset_pos M + mset_neg N)\"\n  let ?B = \"zmset_of (mset_pos N + mset_neg M)\"\n  let ?C = \"- (zmset_of (mset_neg M) + zmset_of (mset_neg N))\"\n\n  show \"M = ?A + ?C\"\n    by (simp add: zmset_of_plus mset_pos_neg_partition)\n  show \"N = ?B + ?C\"\n    by (simp add: zmset_of_plus diff_add_zmset mset_pos_neg_partition)\nqed\n\n\nsubsubsection \\<open>Pointwise Ordering Induced by @{const zcount}\\<close>\n\ndefinition subseteq_zmset :: \"'a zmultiset \\<Rightarrow> 'a zmultiset \\<Rightarrow> bool\" (infix \"\\<subseteq>#\\<^sub>z\" 50) where\n  \"A \\<subseteq>#\\<^sub>z B \\<longleftrightarrow> (\\<forall>a. zcount A a \\<le> zcount B a)\"\n\ndefinition subset_zmset :: \"'a zmultiset \\<Rightarrow> 'a zmultiset \\<Rightarrow> bool\" (infix \"\\<subset>#\\<^sub>z\" 50) where\n  \"A \\<subset>#\\<^sub>z B \\<longleftrightarrow> A \\<subseteq>#\\<^sub>z B \\<and> A \\<noteq> B\"\n\nabbreviation (input)\n  supseteq_zmset :: \"'a zmultiset \\<Rightarrow> 'a zmultiset \\<Rightarrow> bool\" (infix \"\\<supseteq>#\\<^sub>z\" 50)\nwhere\n  \"supseteq_zmset A B \\<equiv> B \\<subseteq>#\\<^sub>z A\"\n\nabbreviation (input)\n  supset_zmset :: \"'a zmultiset \\<Rightarrow> 'a zmultiset \\<Rightarrow> bool\" (infix \"\\<supset>#\\<^sub>z\" 50)\nwhere\n  \"supset_zmset A B \\<equiv> B \\<subset>#\\<^sub>z A\"\n\nnotation (input)\n  subseteq_zmset (infix \"\\<subseteq>#\\<^sub>z\" 50) and\n  supseteq_zmset (infix \"\\<supseteq>#\\<^sub>z\" 50)\n\nnotation (ASCII)\n  subseteq_zmset (infix \"\\<subseteq>#\\<^sub>z\" 50) and\n  subset_zmset (infix \"\\<subset>#\\<^sub>z\" 50) and\n  supseteq_zmset (infix \"\\<supseteq>#\\<^sub>z\" 50) and\n  supset_zmset (infix \">#\\<^sub>z\" 50)\n\ninterpretation subset_zmset: ordered_ab_semigroup_add_imp_le \"(+)\" \"(-)\" \"(\\<subseteq>#\\<^sub>z)\" \"(\\<subset>#\\<^sub>z)\"\n  by unfold_locales (auto simp add: subset_zmset_def subseteq_zmset_def zmultiset_eq_iff\n    intro: order_trans antisym)\n\ninterpretation subset_zmset:\n  ordered_ab_semigroup_monoid_add_imp_le \"(+)\" 0 \"(-)\" \"(\\<subseteq>#\\<^sub>z)\" \"(\\<subset>#\\<^sub>z)\"\n  by unfold_locales\n\nlemma zmset_subset_eqI: \"(\\<And>a. zcount A a \\<le> zcount B a) \\<Longrightarrow> A \\<subseteq>#\\<^sub>z B\"\n  by (simp add: subseteq_zmset_def)\n\nlemma zmset_subset_eq_zcount: \"A \\<subseteq>#\\<^sub>z B \\<Longrightarrow> zcount A a \\<le> zcount B a\"\n  by (simp add: subseteq_zmset_def)\n\nlemma zmset_subset_eq_add_zmset_cancel: \\<open>add_zmset a A \\<subseteq>#\\<^sub>z add_zmset a B \\<longleftrightarrow> A \\<subseteq>#\\<^sub>z B\\<close>\n  unfolding add_zmset_add_single[of _ A] add_zmset_add_single[of _ B]\n  by (rule subset_zmset.add_le_cancel_right)\n\nlemma zmset_subset_eq_zmultiset_union_diff_commute:\n  \"A - B + C = A + C - B\" for A B C :: \"'a zmultiset\"\n  by (simp add: add.commute add_diff_eq)\n\nlemma zmset_subset_eq_insertD: \"add_zmset x A \\<subseteq>#\\<^sub>z B \\<Longrightarrow> A \\<subset>#\\<^sub>z B\"\n  unfolding subset_zmset_def subseteq_zmset_def\n  by (metis (no_types) add.commute add_le_same_cancel2 zcount_add_zmset dual_order.trans le_cases\n    le_numeral_extra(2))\n\nlemma zmset_subset_insertD: \"add_zmset x A \\<subset>#\\<^sub>z B \\<Longrightarrow> A \\<subset>#\\<^sub>z B\"\n  by (rule zmset_subset_eq_insertD) (rule subset_zmset.less_imp_le)\n\nlemma subset_eq_diff_conv_zmset: \"A - C \\<subseteq>#\\<^sub>z B \\<longleftrightarrow> A \\<subseteq>#\\<^sub>z B + C\"\n  by (simp add: subseteq_zmset_def ordered_ab_group_add_class.diff_le_eq)\n\nlemma multi_psub_of_add_self_zmset[simp]: \"A \\<subset>#\\<^sub>z add_zmset x A\"\n  by (auto simp: subset_zmset_def subseteq_zmset_def)\n\nlemma multi_psub_self_zmset: \"A \\<subset>#\\<^sub>z A = False\"\n  by simp\n\nlemma zmset_subset_add_zmset[simp]: \"add_zmset x N \\<subset>#\\<^sub>z add_zmset x M \\<longleftrightarrow> N \\<subset>#\\<^sub>z M\"\n  unfolding add_zmset_add_single[of _ N] add_zmset_add_single[of _ M]\n  by (fact subset_zmset.add_less_cancel_right)\n\nlemma zmset_of_subseteq_iff[simp]: \"zmset_of M \\<subseteq>#\\<^sub>z zmset_of N \\<longleftrightarrow> M \\<subseteq># N\"\n  by (simp add: subseteq_zmset_def subseteq_mset_def)\n\nlemma zmset_of_subset_iff[simp]: \"zmset_of M \\<subset>#\\<^sub>z zmset_of N \\<longleftrightarrow> M \\<subset># N\"\n  by (simp add: subset_zmset_def subset_mset_def)\n\nlemma\n  mset_pos_supset: \"A \\<subseteq>#\\<^sub>z zmset_of (mset_pos A)\" and\n  mset_neg_supset: \"- A \\<subseteq>#\\<^sub>z zmset_of (mset_neg A)\"\n  by (auto intro: zmset_subset_eqI)\n\nlemma subset_mset_zmsetE:\n  assumes \"M \\<subset>#\\<^sub>z N\"\n  obtains A B C where\n    \"M = zmset_of A + C\" and \"N = zmset_of B + C\" and \"A \\<subset># B\"\n  by (metis assms decompose_zmset_of2 subset_zmset.add_less_cancel_right zmset_of_subset_iff)\n\nlemma subseteq_mset_zmsetE:\n  assumes \"M \\<subseteq>#\\<^sub>z N\"\n  obtains A B C where\n    \"M = zmset_of A + C\" and \"N = zmset_of B + C\" and \"A \\<subseteq># B\"\n  by (metis assms add.commute add.right_neutral subset_mset.order_refl subset_mset_def\n    subset_mset_zmsetE subset_zmset_def zmset_of_empty)\n\n\nsubsubsection \\<open>Subset is an Order\\<close>\n\ninterpretation subset_zmset: order \"(\\<subseteq>#\\<^sub>z)\" \"(\\<subset>#\\<^sub>z)\"\n  by unfold_locales\n\n\nsubsection \\<open>Replicate and Repeat Operations\\<close>\n\ndefinition replicate_zmset :: \"nat \\<Rightarrow> 'a \\<Rightarrow> 'a zmultiset\" where\n  \"replicate_zmset n x = (add_zmset x ^^ n) {#}\\<^sub>z\"\n\nlemma replicate_zmset_0[simp]: \"replicate_zmset 0 x = {#}\\<^sub>z\"\n  unfolding replicate_zmset_def by simp\n\nlemma replicate_zmset_Suc[simp]: \"replicate_zmset (Suc n) x = add_zmset x (replicate_zmset n x)\"\n  unfolding replicate_zmset_def by (induct n) (auto intro: add.commute)\n\nlemma count_replicate_zmset[simp]:\n  \"zcount (replicate_zmset n x) y = (if y = x then of_nat n else 0)\"\n  unfolding replicate_zmset_def by (induct n) auto\n\nfun repeat_zmset :: \"nat \\<Rightarrow> 'a zmultiset \\<Rightarrow> 'a zmultiset\" where\n  \"repeat_zmset 0 _ = {#}\\<^sub>z\" |\n  \"repeat_zmset (Suc n) A = A + repeat_zmset n A\"\n\nlemma count_repeat_zmset[simp]: \"zcount (repeat_zmset i A) a = of_nat i * zcount A a\"\n  by (induct i) (auto simp: semiring_normalization_rules(3))\n\nlemma repeat_zmset_right[simp]: \"repeat_zmset a (repeat_zmset b A) = repeat_zmset (a * b) A\"\n  by (auto simp: zmultiset_eq_iff left_diff_distrib')\n\nlemma left_diff_repeat_zmset_distrib':\n  \\<open>i \\<ge> j \\<Longrightarrow> repeat_zmset (i - j) u = repeat_zmset i u - repeat_zmset j u\\<close>\n  by (auto simp: zmultiset_eq_iff int_distrib(3) of_nat_diff)\n\nlemma left_add_mult_distrib_zmset:\n  \"repeat_zmset i u + (repeat_zmset j u + k) = repeat_zmset (i+j) u + k\"\n  by (auto simp: zmultiset_eq_iff add_mult_distrib int_distrib(1))\n\nlemma repeat_zmset_distrib: \"repeat_zmset (m + n) A = repeat_zmset m A + repeat_zmset n A\"\n  by (auto simp: zmultiset_eq_iff Nat.add_mult_distrib int_distrib(1))\n\nlemma repeat_zmset_distrib2[simp]:\n  \"repeat_zmset n (A + B) = repeat_zmset n A + repeat_zmset n B\"\n  by (auto simp: zmultiset_eq_iff add_mult_distrib2 int_distrib(2))\n\nlemma repeat_zmset_replicate_zmset[simp]: \"repeat_zmset n {#a#}\\<^sub>z = replicate_zmset n a\"\n  by (auto simp: zmultiset_eq_iff)\n\nlemma repeat_zmset_distrib_add_zmset[simp]:\n  \"repeat_zmset n (add_zmset a A) = replicate_zmset n a + repeat_zmset n A\"\n  by (auto simp: zmultiset_eq_iff int_distrib(2))\n\nlemma repeat_zmset_empty[simp]: \"repeat_zmset n {#}\\<^sub>z = {#}\\<^sub>z\"\n  by (induct n) simp_all\n\n\nsubsubsection \\<open>Filter (with Comprehension Syntax)\\<close>\n\nlift_definition filter_zmset :: \"('a \\<Rightarrow> bool) \\<Rightarrow> 'a zmultiset \\<Rightarrow> 'a zmultiset\" is\n  \"\\<lambda>P (Mp, Mn). (filter_mset P Mp, filter_mset P Mn)\"\n  by (auto simp del: filter_union_mset simp: equiv_zmset_def filter_union_mset[symmetric])\n\nsyntax (ASCII)\n  \"_MCollect\" :: \"pttrn \\<Rightarrow> 'a zmultiset \\<Rightarrow> bool \\<Rightarrow> 'a zmultiset\" (\"(1{#_ :#z _./ _#})\")\nsyntax\n  \"_MCollect\" :: \"pttrn \\<Rightarrow> 'a zmultiset \\<Rightarrow> bool \\<Rightarrow> 'a zmultiset\" (\"(1{#_ \\<in>#\\<^sub>z _./ _#})\")\ntranslations\n  \"{#x \\<in>#\\<^sub>z M. P#}\" == \"CONST filter_zmset (\\<lambda>x. P) M\"\n\nlemma count_filter_zmset[simp]:\n  \"zcount (filter_zmset P M) a = (if P a then zcount M a else 0)\"\n  by transfer auto\n\nlemma filter_empty_zmset[simp]: \"filter_zmset P {#}\\<^sub>z = {#}\\<^sub>z\"\n  by (rule zmultiset_eqI) simp\n\nlemma filter_single_zmset: \"filter_zmset P {#x#}\\<^sub>z = (if P x then {#x#}\\<^sub>z else {#}\\<^sub>z)\"\n  by (rule zmultiset_eqI) simp\n\nlemma filter_union_zmset[simp]: \"filter_zmset P (M + N) = filter_zmset P M + filter_zmset P N\"\n  by (rule zmultiset_eqI) simp\n\nlemma filter_diff_zmset[simp]: \"filter_zmset P (M - N) = filter_zmset P M - filter_zmset P N\"\n  by (rule zmultiset_eqI) simp\n\nlemma filter_add_zmset[simp]:\n  \"filter_zmset P (add_zmset x A) =\n   (if P x then add_zmset x (filter_zmset P A) else filter_zmset P A)\"\n  by (auto simp: zmultiset_eq_iff)\n\nlemma zmultiset_filter_mono:\n  assumes \"A \\<subseteq>#\\<^sub>z B\"\n  shows \"filter_zmset f A \\<subseteq>#\\<^sub>z filter_zmset f B\"\n  using assms by (simp add: subseteq_zmset_def)\n\nlemma filter_filter_zmset: \"filter_zmset P (filter_zmset Q M) = {#x \\<in># M. Q x \\<and> P x#}\"\n  by (auto simp: zmultiset_eq_iff)\n\nlemma\n  filter_zmset_True[simp]: \"{#y \\<in>#\\<^sub>z M. True#} = M\" and\n  filter_zmset_False[simp]: \"{#y \\<in>#\\<^sub>z M. False#} = {#}\\<^sub>z\"\n  by (auto simp: zmultiset_eq_iff)\n\n\nsubsection \\<open>Uncategorized\\<close>\n\nlemma multi_drop_mem_not_eq_zmset: \"B - {#c#}\\<^sub>z \\<noteq> B\"\n  by (simp add: diff_single_eq_union_zmset)\n\nlemma zmultiset_partition: \"M = {#x \\<in>#\\<^sub>z M. P x #} + {#x \\<in>#\\<^sub>z M. \\<not> P x#}\"\n  by (subst zmultiset_eq_iff) auto\n\n\nsubsection \\<open>Image\\<close>\n\ndefinition image_zmset :: \"('a \\<Rightarrow> 'b) \\<Rightarrow> 'a zmultiset \\<Rightarrow> 'b zmultiset\" where\n  \"image_zmset f M =\n   zmset_of (fold_mset (add_mset \\<circ> f) {#} (mset_pos M)) -\n   zmset_of (fold_mset (add_mset \\<circ> f) {#} (mset_neg M))\"\n\n\nsubsection \\<open>Multiset Order\\<close>\n\ninstantiation zmultiset :: (preorder) order\nbegin\n\nlift_definition less_zmultiset :: \"'a zmultiset \\<Rightarrow> 'a zmultiset \\<Rightarrow> bool\" is\n  \"\\<lambda>(Mp, Mn) (Np, Nn). Mp + Nn < Mn + Np\"\nproof (clarsimp simp: equiv_zmset_def)\n  fix A1 B2 B1 A2 C1 D2 D1 C2 :: \"'a multiset\"\n  assume\n    ab: \"A1 + A2 = B1 + B2\" and\n    cd: \"C1 + C2 = D1 + D2\"\n\n  have \"A1 + D2 < B2 + C1 \\<longleftrightarrow> A1 + A2 + D2 < A2 + B2 + C1\"\n    by simp\n  also have \"\\<dots> \\<longleftrightarrow> B1 + B2 + D2 < A2 + B2 + C1\"\n    unfolding ab by (rule refl)\n  also have \"\\<dots> \\<longleftrightarrow> B1 + D2 < A2 + C1\"\n    by simp\n  also have \"\\<dots> \\<longleftrightarrow> B1 + D1 + D2 < A2 + C1 + D1\"\n    by simp\n  also have \"\\<dots> \\<longleftrightarrow> B1 + C1 + C2 < A2 + C1 + D1\"\n    using cd by (simp add: add.assoc)\n  also have \"\\<dots> \\<longleftrightarrow> B1 + C2 < A2 + D1\"\n    by simp\n  finally show \"A1 + D2 < B2 + C1 \\<longleftrightarrow> B1 + C2 < A2 + D1\"\n    by assumption\nqed\n\ndefinition less_eq_zmultiset :: \"'a zmultiset \\<Rightarrow> 'a zmultiset \\<Rightarrow> bool\" where\n  \"less_eq_zmultiset M' M \\<longleftrightarrow> M' < M \\<or> M' = M\"\n\ninstance\nproof ((intro_classes; unfold less_eq_zmultiset_def; transfer),\n    auto simp: equiv_zmset_def union_commute)\n  fix A1 B1 D C B2 A2 :: \"'a multiset\"\n  assume ab: \"A1 + A2 \\<noteq> B1 + B2\"\n\n  {\n    assume ab1: \"A1 + C < B1 + D\"\n\n    {\n      assume ab2: \"D + A2 < C + B2\"\n      show \"A1 + A2 < B1 + B2\"\n      proof -\n        have f1: \"\\<And>m. D + A2 + m < C + B2 + m\"\n          using ab2 add_less_cancel_right by blast\n        have \"\\<And>m. C + (A1 + m) < D + (B1 + m)\"\n          by (simp add: ab1 add.commute)\n        then have \"D + (A2 + A1) < D + (B1 + B2)\"\n          using f1 by (metis add.assoc add.commute mset_le_trans)\n        then show ?thesis\n          by (simp add: add.commute)\n      qed\n    }\n    {\n      assume ab2: \"D + A2 = C + B2\"\n      show \"A1 + A2 < B1 + B2\"\n      proof -\n        have \"\\<And>m. C + A1 + m < D + B1 + m\"\n          by (simp add: ab1 add.commute)\n        then have \"D + (A2 + A1) < D + (B1 + B2)\"\n          by (metis (no_types) ab2 add.assoc add.commute)\n        then show ?thesis\n          by (simp add: add.commute)\n      qed\n    }\n  }\n\n  {\n    assume ab1: \"A1 + C = B1 + D\"\n\n    {\n      assume ab2: \"D + A2 < C + B2\"\n      show \"A1 + A2 < B1 + B2\"\n      proof -\n        have \"A1 + (D + A2) < B1 + (D + B2)\"\n          by (metis (no_types) ab1 ab2 add.assoc add_less_cancel_left)\n        then show ?thesis\n          by simp\n      qed\n    }\n    {\n      assume ab2: \"D + A2 = C + B2\"\n      have False\n        by (metis (no_types) ab ab1 ab2 add.assoc add.commute add_diff_cancel_right')\n      thus \"A1 + A2 < B1 + B2\"\n        by sat\n    }\n  }\nqed\n\nend\n\ninstance zmultiset :: (preorder) ordered_cancel_comm_monoid_add\n  by (intro_classes, unfold less_eq_zmultiset_def, transfer, auto simp: equiv_zmset_def)\n\ninstance zmultiset :: (preorder) ordered_ab_group_add\n  by (intro_classes; transfer; auto simp: equiv_zmset_def)\n\ninstantiation zmultiset :: (linorder) distrib_lattice\nbegin\n\ndefinition inf_zmultiset :: \"'a zmultiset \\<Rightarrow> 'a zmultiset \\<Rightarrow> 'a zmultiset\" where\n  \"inf_zmultiset A B = (if A < B then A else B)\"\n\ndefinition sup_zmultiset :: \"'a zmultiset \\<Rightarrow> 'a zmultiset \\<Rightarrow> 'a zmultiset\" where\n  \"sup_zmultiset A B = (if B > A then B else A)\"\n\nlemma not_lt_iff_ge_zmset: \"\\<not> x < y \\<longleftrightarrow> x \\<ge> y\" for x y :: \"'a zmultiset\"\n  by (unfold less_eq_zmultiset_def, transfer, auto simp: equiv_zmset_def algebra_simps)\n\ninstance\n  by intro_classes (auto simp: less_eq_zmultiset_def inf_zmultiset_def sup_zmultiset_def\n    dest!: not_lt_iff_ge_zmset[THEN iffD1])\n\nend\n\nlemma zmset_of_less: \"zmset_of M < zmset_of N \\<longleftrightarrow> M < N\"\n  by (clarsimp simp: zmset_of_def, transfer, simp)+\n\nlemma zmset_of_le: \"zmset_of M \\<le> zmset_of N \\<longleftrightarrow> M \\<le> N\"\n  by (simp_all add: less_eq_zmultiset_def zmset_of_def; transfer; auto simp: equiv_zmset_def)\n\ninstance zmultiset :: (preorder) ordered_ab_semigroup_add\n  by (intro_classes, unfold less_eq_zmultiset_def, transfer, auto simp: equiv_zmset_def)\n\nlemma uminus_add_conv_diff_mset[cancelation_simproc_pre]: \\<open>-a + b = b - a\\<close> for a :: \\<open>'a zmultiset\\<close>\n  by (simp add: add.commute)\n\nlemma uminus_add_add_uminus[cancelation_simproc_pre]: \\<open>b -a + c = b + c - a\\<close> for a :: \\<open>'a zmultiset\\<close>\n  by (simp add: uminus_add_conv_diff_mset zmset_subset_eq_zmultiset_union_diff_commute)\n\nlemma add_zmset_eq_add_NO_MATCH[cancelation_simproc_pre]:\n  \\<open>NO_MATCH {#}\\<^sub>z H \\<Longrightarrow> add_zmset a H = {#a#}\\<^sub>z + H\\<close>\n  by auto\n\nlemma repeat_zmset_iterate_add: \\<open>repeat_zmset n M = iterate_add n M\\<close>\n  unfolding iterate_add_def by (induction n) auto\n\ndeclare repeat_zmset_iterate_add[cancelation_simproc_pre]\n\ndeclare repeat_zmset_iterate_add[symmetric, cancelation_simproc_post]\n\nsimproc_setup zmseteq_cancel_numerals\n  (\"(l::'a zmultiset) + m = n\" | \"(l::'a zmultiset) = m + n\" |\n   \"add_zmset a m = n\" | \"m = add_zmset a n\" |\n   \"replicate_zmset p a = n\" | \"m = replicate_zmset p a\" |\n   \"repeat_zmset p m = n\" | \"m = repeat_zmset p m\") =\n  \\<open>fn phi => Cancel_Simprocs.eq_cancel\\<close>\n\nlemma zmset_subseteq_add_iff1:\n  \\<open>j \\<le> i \\<Longrightarrow> (repeat_zmset i u + m \\<subseteq>#\\<^sub>z repeat_zmset j u + n) = (repeat_zmset (i - j) u + m \\<subseteq>#\\<^sub>z n)\\<close>\n  by (simp add: add.commute add_diff_eq left_diff_repeat_zmset_distrib' subset_eq_diff_conv_zmset)\n\nlemma zmset_subseteq_add_iff2:\n  \\<open>i \\<le> j \\<Longrightarrow> (repeat_zmset i u + m \\<subseteq>#\\<^sub>z repeat_zmset j u + n) = (m \\<subseteq>#\\<^sub>z repeat_zmset (j - i) u + n)\\<close>\nproof -\n  assume \"i \\<le> j\"\n  then have \"\\<And>z. repeat_zmset j (z::'a zmultiset) - repeat_zmset i z = repeat_zmset (j - i) z\"\n    by (simp add: left_diff_repeat_zmset_distrib')\n  then show ?thesis\n    by (metis add.commute diff_diff_eq2 subset_eq_diff_conv_zmset)\nqed\n\nlemma zmset_subset_add_iff1:\n  \\<open>j \\<le> i \\<Longrightarrow> (repeat_zmset i u + m \\<subset>#\\<^sub>z repeat_zmset j u + n) = (repeat_zmset (i - j) u + m \\<subset>#\\<^sub>z n)\\<close>\n  by (simp add: subset_zmset.less_le_not_le zmset_subseteq_add_iff1 zmset_subseteq_add_iff2)\n\nlemma zmset_subset_add_iff2:\n  \\<open>i \\<le> j \\<Longrightarrow> (repeat_zmset i u + m \\<subset>#\\<^sub>z repeat_zmset j u + n) = (m \\<subset>#\\<^sub>z repeat_zmset (j - i) u + n)\\<close>\n  by (simp add: subset_zmset.less_le_not_le zmset_subseteq_add_iff1 zmset_subseteq_add_iff2)\n\nML_file \\<open>zmultiset_simprocs.ML\\<close>\n\nsimproc_setup zmsetsubset_cancel\n  (\"(l::'a zmultiset) + m \\<subset>#\\<^sub>z n\" | \"(l::'a zmultiset) \\<subset>#\\<^sub>z m + n\" |\n   \"add_zmset a m \\<subset>#\\<^sub>z n\" | \"m \\<subset>#\\<^sub>z add_zmset a n\" |\n   \"replicate_zmset p a \\<subset>#\\<^sub>z n\" | \"m \\<subset>#\\<^sub>z replicate_zmset p a\" |\n   \"repeat_zmset p m \\<subset>#\\<^sub>z n\" | \"m \\<subset>#\\<^sub>z repeat_zmset p m\") =\n  \\<open>fn phi => ZMultiset_Simprocs.subset_cancel_zmsets\\<close>\n\nsimproc_setup zmsetsubseteq_cancel\n  (\"(l::'a zmultiset) + m \\<subseteq>#\\<^sub>z n\" | \"(l::'a zmultiset) \\<subseteq>#\\<^sub>z m + n\" |\n   \"add_zmset a m \\<subseteq>#\\<^sub>z n\" | \"m \\<subseteq>#\\<^sub>z add_zmset a n\" |\n   \"replicate_zmset p a \\<subseteq>#\\<^sub>z n\" | \"m \\<subseteq>#\\<^sub>z replicate_zmset p a\" |\n   \"repeat_zmset p m \\<subseteq>#\\<^sub>z n\" | \"m \\<subseteq>#\\<^sub>z repeat_zmset p m\") =\n  \\<open>fn phi => ZMultiset_Simprocs.subseteq_cancel_zmsets\\<close>\n\ninstance zmultiset :: (preorder) ordered_ab_semigroup_add_imp_le\n  by (intro_classes; unfold less_eq_zmultiset_def; transfer; auto)\n\nsimproc_setup zmsetless_cancel\n  (\"(l::'a::preorder zmultiset) + m < n\" | \"(l::'a zmultiset) < m + n\" |\n   \"add_zmset a m < n\" | \"m < add_zmset a n\" |\n   \"replicate_zmset p a < n\" | \"m < replicate_zmset p a\" |\n   \"repeat_zmset p m < n\" | \"m < repeat_zmset p m\") =\n  \\<open>fn phi => Cancel_Simprocs.less_cancel\\<close>\n\nsimproc_setup zmsetless_eq_cancel\n  (\"(l::'a::preorder zmultiset) + m \\<le> n\" | \"(l::'a zmultiset) \\<le> m + n\" |\n   \"add_zmset a m \\<le> n\" | \"m \\<le> add_zmset a n\" |\n   \"replicate_zmset p a \\<le> n\" | \"m \\<le> replicate_zmset p a\" |\n   \"repeat_zmset p m \\<le> n\" | \"m \\<le> repeat_zmset p m\") =\n  \\<open>fn phi => Cancel_Simprocs.less_eq_cancel\\<close>\n\nsimproc_setup zmsetdiff_cancel\n  (\"n + (l::'a zmultiset)\" | \"(l::'a zmultiset) - m\" |\n   \"add_zmset a m - n\" | \"m - add_zmset a n\" |\n   \"replicate_zmset p r - n\" | \"m - replicate_zmset p r\" |\n   \"repeat_zmset p m - n\" | \"m - repeat_zmset p m\") =\n  \\<open>fn phi => Cancel_Simprocs.diff_cancel\\<close>\n\ninstance zmultiset :: (linorder) linordered_cancel_ab_semigroup_add\n  by (intro_classes, unfold less_eq_zmultiset_def, transfer, auto simp: equiv_zmset_def add.commute)\n\nlemma less_mset_zmsetE:\n  assumes \"M < N\"\n  obtains A B C where\n    \"M = zmset_of A + C\" and \"N = zmset_of B + C\" and \"A < B\"\n  by (metis add_less_imp_less_right assms decompose_zmset_of2 zmset_of_less)\n\nlemma less_eq_mset_zmsetE:\n  assumes \"M \\<le> N\"\n  obtains A B C where\n    \"M = zmset_of A + C\" and \"N = zmset_of B + C\" and \"A \\<le> B\"\n  by (metis add.commute add.right_neutral assms le_neq_trans less_imp_le less_mset_zmsetE order_refl\n    zmset_of_empty)\n\nlemma subset_eq_imp_le_zmset: \"M \\<subseteq>#\\<^sub>z N \\<Longrightarrow> M \\<le> N\"\n  by (metis (no_types) add_mono_thms_linordered_semiring(3) subset_eq_imp_le_multiset\n    subseteq_mset_zmsetE zmset_of_le)\n\nlemma subset_imp_less_zmset: \"M \\<subset>#\\<^sub>z N \\<Longrightarrow> M < N\"\n  by (metis le_neq_trans subset_eq_imp_le_zmset subset_zmset_def)\n\nlemma lt_imp_ex_zcount_lt:\n  assumes m_lt_n: \"M < N\"\n  shows \"\\<exists>y. zcount M y < zcount N y\"\nproof (rule ccontr, clarsimp)\n  assume \"\\<forall>y. \\<not> zcount M y < zcount N y\"\n  hence \"\\<forall>y. zcount M y \\<ge> zcount N y\"\n    by (simp add: leI)\n  hence \"M \\<supseteq>#\\<^sub>z N\"\n    by (simp add: zmset_subset_eqI)\n  hence \"M \\<ge> N\"\n    by (simp add: subset_eq_imp_le_zmset)\n  thus False\n    using m_lt_n by simp\nqed\n\ninstance zmultiset :: (preorder) no_top\nproof\n  fix M :: \\<open>'a zmultiset\\<close>\n  obtain a :: 'a where True by fast\n  let ?M = \\<open>zmset_of (mset_pos M) + zmset_of (mset_neg M)\\<close>\n  have \\<open>M < add_zmset a ?M + ?M\\<close>\n    by (subst mset_pos_neg_partition)\n      (auto simp: subset_zmset_def subseteq_zmset_def zmultiset_eq_iff\n        intro!: subset_imp_less_zmset)\n  then show \\<open>\\<exists>N. M < N\\<close>\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/Nested_Multisets_Ordinals/Signed_Multiset.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240825770432, "lm_q2_score": 0.8128673133042217, "lm_q1q2_score": 0.7033123754105112}}
{"text": "(*  Title:      HOL/ex/Groebner_Examples.thy\n    Author:     Amine Chaieb, TU Muenchen\n*)\n\nsection {* Groebner Basis Examples *}\n\ntheory Groebner_Examples\nimports Groebner_Basis\nbegin\n\nsubsection {* Basic examples *}\n\nlemma\n  fixes x :: int\n  shows \"x ^ 3 = x ^ 3\"\n  apply (tactic {* ALLGOALS (CONVERSION\n    (Conv.arg_conv (Conv.arg1_conv (Semiring_Normalizer.semiring_normalize_conv @{context})))) *})\n  by (rule refl)\n\nlemma\n  fixes x :: int\n  shows \"(x - (-2))^5 = x ^ 5 + (10 * x ^ 4 + (40 * x ^ 3 + (80 * x\\<^sup>2 + (80 * x + 32))))\" \n  apply (tactic {* ALLGOALS (CONVERSION\n    (Conv.arg_conv (Conv.arg1_conv (Semiring_Normalizer.semiring_normalize_conv @{context})))) *})\n  by (rule refl)\n\nschematic_lemma\n  fixes x :: int\n  shows \"(x - (-2))^5  * (y - 78) ^ 8 = ?X\" \n  apply (tactic {* ALLGOALS (CONVERSION\n    (Conv.arg_conv (Conv.arg1_conv (Semiring_Normalizer.semiring_normalize_conv @{context})))) *})\n  by (rule refl)\n\nlemma \"((-3) ^ (Suc (Suc (Suc 0)))) == (X::'a::{comm_ring_1})\"\n  apply (simp only: power_Suc power_0)\n  apply (simp only: semiring_norm)\n  oops\n\nlemma \"((x::int) + y)^3 - 1 = (x - z)^2 - 10 \\<Longrightarrow> x = z + 3 \\<Longrightarrow> x = - y\"\n  by algebra\n\nlemma \"(4::nat) + 4 = 3 + 5\"\n  by algebra\n\nlemma \"(4::int) + 0 = 4\"\n  apply algebra?\n  by simp\n\nlemma\n  assumes \"a * x\\<^sup>2 + b * x + c = (0::int)\" and \"d * x\\<^sup>2 + e * x + f = 0\"\n  shows \"d\\<^sup>2 * c\\<^sup>2 - 2 * d * c * a * f + a\\<^sup>2 * f\\<^sup>2 - e * d * b * c - e * b * a * f +\n    a * e\\<^sup>2 * c + f * d * b\\<^sup>2 = 0\"\n  using assms by algebra\n\nlemma \"(x::int)^3  - x^2  - 5*x - 3 = 0 \\<longleftrightarrow> (x = 3 \\<or> x = -1)\"\n  by algebra\n\ntheorem \"x* (x\\<^sup>2 - x  - 5) - 3 = (0::int) \\<longleftrightarrow> (x = 3 \\<or> x = -1)\"\n  by algebra\n\nlemma\n  fixes x::\"'a::idom\"\n  shows \"x\\<^sup>2*y = x\\<^sup>2 & x*y\\<^sup>2 = y\\<^sup>2 \\<longleftrightarrow>  x = 1 & y = 1 | x = 0 & y = 0\"\n  by algebra\n\nsubsection {* Lemmas for Lagrange's theorem *}\n\ndefinition\n  sq :: \"'a::times => 'a\" where\n  \"sq x == x*x\"\n\nlemma\n  fixes x1 :: \"'a::{idom}\"\n  shows\n  \"(sq x1 + sq x2 + sq x3 + sq x4) * (sq y1 + sq y2 + sq y3 + sq y4) =\n    sq (x1*y1 - x2*y2 - x3*y3 - x4*y4)  +\n    sq (x1*y2 + x2*y1 + x3*y4 - x4*y3)  +\n    sq (x1*y3 - x2*y4 + x3*y1 + x4*y2)  +\n    sq (x1*y4 + x2*y3 - x3*y2 + x4*y1)\"\n  by (algebra add: sq_def)\n\nlemma\n  fixes p1 :: \"'a::{idom}\"\n  shows\n  \"(sq p1 + sq q1 + sq r1 + sq s1 + sq t1 + sq u1 + sq v1 + sq w1) *\n   (sq p2 + sq q2 + sq r2 + sq s2 + sq t2 + sq u2 + sq v2 + sq w2)\n    = sq (p1*p2 - q1*q2 - r1*r2 - s1*s2 - t1*t2 - u1*u2 - v1*v2 - w1*w2) +\n      sq (p1*q2 + q1*p2 + r1*s2 - s1*r2 + t1*u2 - u1*t2 - v1*w2 + w1*v2) +\n      sq (p1*r2 - q1*s2 + r1*p2 + s1*q2 + t1*v2 + u1*w2 - v1*t2 - w1*u2) +\n      sq (p1*s2 + q1*r2 - r1*q2 + s1*p2 + t1*w2 - u1*v2 + v1*u2 - w1*t2) +\n      sq (p1*t2 - q1*u2 - r1*v2 - s1*w2 + t1*p2 + u1*q2 + v1*r2 + w1*s2) +\n      sq (p1*u2 + q1*t2 - r1*w2 + s1*v2 - t1*q2 + u1*p2 - v1*s2 + w1*r2) +\n      sq (p1*v2 + q1*w2 + r1*t2 - s1*u2 - t1*r2 + u1*s2 + v1*p2 - w1*q2) +\n      sq (p1*w2 - q1*v2 + r1*u2 + s1*t2 - t1*s2 - u1*r2 + v1*q2 + w1*p2)\"\n  by (algebra add: sq_def)\n\n\nsubsection {* Colinearity is invariant by rotation *}\n\ntype_synonym point = \"int \\<times> int\"\n\ndefinition collinear ::\"point \\<Rightarrow> point \\<Rightarrow> point \\<Rightarrow> bool\" where\n  \"collinear \\<equiv> \\<lambda>(Ax,Ay) (Bx,By) (Cx,Cy).\n    ((Ax - Bx) * (By - Cy) = (Ay - By) * (Bx - Cx))\"\n\nlemma collinear_inv_rotation:\n  assumes \"collinear (Ax, Ay) (Bx, By) (Cx, Cy)\" and \"c\\<^sup>2 + s\\<^sup>2 = 1\"\n  shows \"collinear (Ax * c - Ay * s, Ay * c + Ax * s)\n    (Bx * c - By * s, By * c + Bx * s) (Cx * c - Cy * s, Cy * c + Cx * s)\"\n  using assms \n  by (algebra add: collinear_def split_def fst_conv snd_conv)\n\nlemma \"EX (d::int). a*y - a*x = n*d \\<Longrightarrow> EX u v. a*u + n*v = 1 \\<Longrightarrow> EX e. y - x = n*e\"\n  by algebra\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/Groebner_Examples.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240756264638, "lm_q2_score": 0.8128673178375735, "lm_q1q2_score": 0.7033123736829774}}
{"text": "(*  Title:       Termination of the hydra battle\n    Author:      Jasmin Blanchette <jasmin.blanchette at inria.fr>, 2017\n    Maintainer:  Jasmin Blanchette <jasmin.blanchette at inria.fr>\n*)\n\nsection \\<open>Termination of the Hydra Battle\\<close>\n\ntheory Hydra_Battle\nimports Syntactic_Ordinal\nbegin\n\nhide_const (open) Nil Cons\n\ntext \\<open>\nThe \\<open>h\\<close> function and its auxiliaries \\<open>f\\<close> and \\<open>d\\<close> represent the\nhydra battle. The \\<open>encode\\<close> function converts a hydra (represented as a\nLisp-like tree) to a syntactic ordinal. The definitions follow Dershowitz and\nMoser.\n\\<close>\n\ndatatype lisp =\n  Nil\n| Cons (car: lisp) (cdr: lisp)\nwhere\n  \"car Nil = Nil\"\n| \"cdr Nil = Nil\"\n\nprimrec encode :: \"lisp \\<Rightarrow> hmultiset\" where\n  \"encode Nil = 0\"\n| \"encode (Cons l r) = \\<omega>^(encode l) + encode r\"\n\nprimrec f :: \"nat \\<Rightarrow> lisp \\<Rightarrow> lisp \\<Rightarrow> lisp\" where\n  \"f 0 y x = x\"\n| \"f (Suc m) y x = Cons y (f m y x)\"\n\nlemma encode_f: \"encode (f n y x) = of_nat n * \\<omega>^(encode y) + encode x\"\n  unfolding of_nat_times_\\<omega>_exp by (induct n) (auto simp: HMSet_plus[symmetric])\n\nfunction d :: \"nat \\<Rightarrow> lisp \\<Rightarrow> lisp\" where\n  \"d n x =\n   (if car x = Nil then cdr x\n    else if car (car x) = Nil then f n (cdr (car x)) (cdr x)\n    else Cons (d n (car x)) (cdr x))\"\n  by pat_completeness auto\ntermination\n  by (relation \"measure (\\<lambda>(_, x). size x)\", rule wf_measure, rename_tac n x, case_tac x, auto)\n\ndeclare d.simps[simp del]\n\nfunction h :: \"nat \\<Rightarrow> lisp \\<Rightarrow> lisp\" where\n  \"h n x = (if x = Nil then Nil else h (n + 1) (d n x))\"\n  by pat_completeness auto\ntermination\nproof -\n  let ?R = \"inv_image {(m, n). m < n} (\\<lambda>(n, x). encode x)\"\n\n  show ?thesis\n  proof (relation ?R)\n    show \"wf ?R\"\n      by (rule wf_inv_image) (rule wf)\n  next\n    fix n x\n    assume x_cons: \"x \\<noteq> Nil\"\n    thus \"((n + 1, d n x), n, x) \\<in> ?R\"\n      unfolding inv_image_def mem_Collect_eq prod.case\n    proof (induct x)\n      case (Cons l r)\n      note ihl = this(1)\n      show ?case\n      proof (subst d.simps, simp, intro conjI impI)\n        assume l_cons: \"l \\<noteq> Nil\"\n        {\n          assume \"car l = Nil\"\n          show \"encode (f n (cdr l) r) < \\<omega>^(encode l) + encode r\"\n            using l_cons by (cases l) (auto simp: encode_f[unfolded of_nat_times_\\<omega>_exp])\n        }\n        {\n          show \"encode (d n l) < encode l\"\n            by (rule ihl[OF l_cons])\n        }\n      qed\n    qed simp\n  qed\nqed\n\ndeclare h.simps[simp del]\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/Nested_Multisets_Ordinals/Hydra_Battle.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8652240721511739, "lm_q2_score": 0.8128673201042492, "lm_q1q2_score": 0.7033123728192103}}
{"text": "(*  Title:      Sort.thy\n    Author:     Danijela Petrovi\\'c, Facylty of Mathematics, University of Belgrade *)\n\nsection \\<open>Verification of functional Selection Sort\\<close>\n\ntheory SelectionSort_Functional\nimports RemoveMax\nbegin\n\nsubsection \\<open>Defining data structure\\<close>\n\ntext\\<open>Selection sort works with list and that is the reason why {\\em\n  Collection} should be interpreted as list.\\<close>\n\ninterpretation Collection \"[]\" \"\\<lambda> l. l = []\" id mset\nby (unfold_locales, auto)\n\nsubsection \\<open>Defining function remove\\_max\\<close>\n\ntext\\<open>The following is definition of {\\em remove\\_max} function. \nThe idea is very well known -- assume that the maximum element is the\nfirst one and then compare with each element of the list. Function\n{\\em f} is one step in iteration, it compares current maximum {\\em m}\nwith one element {\\em x}, if it is bigger then {\\em m} stays current\nmaximum and {\\em x} is added in the resulting list, otherwise {\\em x}\nis current maximum and {\\em m} is added in the resulting\nlist.\n\\<close>\n\nfun f where \"f (m, l) x = (if x \\<ge> m then (x, m#l) else (m, x#l))\"\n\ndefinition remove_max where\n  \"remove_max l = foldl f (hd l, []) (tl l)\"\n\nlemma max_Max_commute: \n  \"finite A \\<Longrightarrow> max (Max (insert m A)) x = max m (Max (insert x A))\"\n  apply (cases \"A = {}\", simp)  \n  by (metis Max_insert max.commute max.left_commute)\n\ntext\\<open>The function really returned the\nmaximum value.\\<close>\n\nlemma remove_max_max_lemma:\n  shows \"fst (foldl f (m, t) l) =  Max (set (m # l))\"\nproof (induct l arbitrary: m t rule: rev_induct)\n  case (snoc x xs)\n  let ?a = \"foldl f (m, t) xs\"\n  let ?m' = \"fst ?a\" and ?t' = \"snd ?a\"\n  have \"fst (foldl f (m, t) (xs @ [x])) = max ?m' x\"\n    by (cases ?a) (auto simp add: max_def)\n  thus ?case\n    using snoc\n    by (simp add: max_Max_commute)\nqed simp\n\nlemma remove_max_max:\n  assumes \"l \\<noteq> []\" \"(m, l') = remove_max l\"\n  shows \"m = Max (set l)\"\nusing assms\nunfolding remove_max_def\nusing remove_max_max_lemma[of \"hd l\" \"[]\" \"tl l\"]\nusing fst_conv[of m l']\nby simp\n\ntext\\<open>Nothing new is added in the list and noting is deleted\nfrom the list except the maximum element.\\<close>\n\nlemma remove_max_mset_lemma:\n  assumes \"(m, l') = foldl f (m', t') l\"\n  shows \"mset (m # l') = mset (m' # t' @ l)\"\nusing assms\nproof (induct l arbitrary: l' m m' t' rule: rev_induct)\n  case (snoc x xs)\n  let ?a = \"foldl f (m', t') xs\"\n  let ?m' = \"fst ?a\" and ?t' = \"snd ?a\"\n  have \"mset (?m' # ?t') = mset (m' # t' @ xs)\"\n    using snoc(1)[of ?m' ?t' m' t']\n    by simp\n  thus ?case\n    using snoc(2)\n    apply (cases \"?a\")\n    by (auto split: if_split_asm) \nqed simp\n\nlemma remove_max_mset:\n  assumes \"l \\<noteq> []\" \"(m, l') = remove_max l\" \n  shows \"add_mset m (mset l') = mset l\"\nusing assms\nunfolding remove_max_def\nusing remove_max_mset_lemma[of m l' \"hd l\" \"[]\" \"tl l\"]\nby auto\n\ndefinition ssf_ssort' where\n  [simp, code del]: \"ssf_ssort' = RemoveMax.ssort' (\\<lambda> l. l = []) remove_max\"\ndefinition ssf_ssort where \n  [simp, code del]: \"ssf_ssort = RemoveMax.ssort (\\<lambda> l. l = []) id remove_max\"\n\ninterpretation SSRemoveMax: \n  RemoveMax \"[]\" \"\\<lambda> l. l = []\" id mset remove_max \"\\<lambda> _. True\" \n  rewrites\n \"RemoveMax.ssort' (\\<lambda> l. l = []) remove_max = ssf_ssort'\" and\n \"RemoveMax.ssort (\\<lambda> l. l = []) id remove_max = ssf_ssort\"\nusing remove_max_max\nby (unfold_locales, auto simp add: remove_max_mset)\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/Selection_Heap_Sort/SelectionSort_Functional.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240756264639, "lm_q2_score": 0.8128673087708699, "lm_q1q2_score": 0.7033123658382473}}
{"text": "section \\<open> Guarded Recursion \\<close>\n\ntheory utp_rdes_guarded\n  imports utp_rdes_productive\nbegin\n\nsubsection \\<open> Traces with a size measure \\<close>\n\ntext \\<open> Guarded recursion relies on our ability to measure the trace's size, in order to see if it\n  is decreasing on each iteration. Thus, we here equip the trace algebra with the @{term size}\n  function that provides this. \\<close>\n\nclass size_trace = trace + size +\n  assumes\n    size_zero: \"size 0 = 0\" and\n    size_nzero: \"s > 0 \\<Longrightarrow> size(s) > 0\" and\n    size_plus: \"size (s + t) = size(s) + size(t)\"\n  \\<comment> \\<open> These axioms may be stronger than necessary. In particular, @{thm size_nzero} requires that\n       a non-empty trace have a positive size. But this may not be the case with all trace models\n       and is possibly more restrictive than necessary. In future we will explore weakening. \\<close>\nbegin\n\nlemma size_mono: \"s \\<le> t \\<Longrightarrow> size(s) \\<le> size(t)\"\n  by (metis le_add1 local.diff_add_cancel_left' local.size_plus)\n\nlemma size_strict_mono: \"s < t \\<Longrightarrow> size(s) < size(t)\"\n  by (metis cancel_ab_semigroup_add_class.add_diff_cancel_left' local.diff_add_cancel_left' local.less_iff local.minus_gr_zero_iff local.size_nzero local.size_plus zero_less_diff)\n\nlemma trace_strict_prefixE: \"xs < ys \\<Longrightarrow> (\\<And>zs. \\<lbrakk> ys = xs + zs; size(zs) > 0 \\<rbrakk> \\<Longrightarrow> thesis) \\<Longrightarrow> thesis\"\n  by (metis local.diff_add_cancel_left' local.less_iff local.minus_gr_zero_iff local.size_nzero)\n\nlemma size_minus_trace: \"y \\<le> x \\<Longrightarrow> size(x - y) = size(x) - size(y)\"\n  by (metis diff_add_inverse local.diff_add_cancel_left' local.size_plus)\n\nend\n\ntext \\<open> Both natural numbers and lists are measurable trace algebras. \\<close>\n\ninstance nat :: size_trace\n  by (intro_classes, simp_all)\n\ninstance list :: (type) size_trace\n  by (intro_classes, simp_all add: less_list_def' plus_list_def prefix_length_less)\n\nsyntax\n  \"_usize\"      :: \"logic \\<Rightarrow> logic\" (\"size\\<^sub>u'(_')\")\n\ntranslations\n  \"size\\<^sub>u(t)\" == \"CONST uop CONST size t\"\n\nsubsection \\<open> Guardedness \\<close>\n\ndefinition gvrt :: \"(('t::size_trace,'\\<alpha>) rp \\<times> ('t,'\\<alpha>) rp) chain\" where\n[upred_defs]: \"gvrt(n) \\<equiv> ($tr \\<le>\\<^sub>u $tr\\<acute> \\<and> size\\<^sub>u(&tt) <\\<^sub>u \\<guillemotleft>n\\<guillemotright>)\"\n\nlemma gvrt_chain: \"chain gvrt\"\n  apply (simp add: chain_def, safe)\n  apply (rel_simp)\n  apply (rel_simp)+\ndone\n\nlemma gvrt_limit: \"\\<Sqinter> (range gvrt) = ($tr \\<le>\\<^sub>u $tr\\<acute>)\"\n  by (rel_auto)\n\ndefinition Guarded :: \"(('t::size_trace,'\\<alpha>) hrel_rp \\<Rightarrow> ('t,'\\<alpha>) hrel_rp) \\<Rightarrow> bool\" where\n[upred_defs]: \"Guarded(F) = (\\<forall> X n. (F(X) \\<and> gvrt(n+1)) = (F(X \\<and> gvrt(n)) \\<and> gvrt(n+1)))\"\n\nlemma GuardedI: \"\\<lbrakk> \\<And> X n. (F(X) \\<and> gvrt(n+1)) = (F(X \\<and> gvrt(n)) \\<and> gvrt(n+1)) \\<rbrakk> \\<Longrightarrow> Guarded F\"\n  by (simp add: Guarded_def)\n\ntext \\<open> Guarded reactive designs yield unique fixed-points. \\<close>\n\ntheorem guarded_fp_uniq:\n  assumes \"mono F\" \"F \\<in> \\<lbrakk>id\\<rbrakk>\\<^sub>H \\<rightarrow> \\<lbrakk>SRD\\<rbrakk>\\<^sub>H\" \"Guarded F\"\n  shows \"\\<mu> F = \\<nu> F\"\nproof -\n  have \"constr F gvrt\"\n    using assms    \n    by (auto simp add: constr_def gvrt_chain Guarded_def tcontr_alt_def')\n  hence \"($tr \\<le>\\<^sub>u $tr\\<acute> \\<and> \\<mu> F) = ($tr \\<le>\\<^sub>u $tr\\<acute> \\<and> \\<nu> F)\"\n    apply (rule constr_fp_uniq)\n     apply (simp add: assms)\n    using gvrt_limit apply blast\n    done\n  moreover have \"($tr \\<le>\\<^sub>u $tr\\<acute> \\<and> \\<mu> F) = \\<mu> F\"\n  proof -\n    have \"\\<mu> F is R1\"\n      by (rule SRD_healths(1), rule Healthy_mu, simp_all add: assms)\n    thus ?thesis\n      by (metis Healthy_def R1_def conj_comm)\n  qed\n  moreover have \"($tr \\<le>\\<^sub>u $tr\\<acute> \\<and> \\<nu> F) = \\<nu> F\"\n  proof -\n    have \"\\<nu> F is R1\"\n      by (rule SRD_healths(1), rule Healthy_nu, simp_all add: assms)\n    thus ?thesis\n      by (metis Healthy_def R1_def conj_comm)\n  qed\n  ultimately show ?thesis\n    by (simp)\nqed\n\nlemma Guarded_const [closure]: \"Guarded (\\<lambda> X. P)\"\n  by (simp add: Guarded_def)\n\nlemma UINF_Guarded [closure]:\n  assumes  \"\\<And> P. P \\<in> A \\<Longrightarrow> Guarded P\"\n  shows \"Guarded (\\<lambda> X. \\<Sqinter>P\\<in>A \\<bullet> P(X))\"\nproof (rule GuardedI)\n  fix X n\n  have \"\\<And> Y. ((\\<Sqinter>P\\<in>A \\<bullet> P Y) \\<and> gvrt(n+1)) = ((\\<Sqinter>P\\<in>A \\<bullet> (P Y \\<and> gvrt(n+1))) \\<and> gvrt(n+1))\"\n  proof -\n    fix Y\n    let ?lhs = \"((\\<Sqinter>P\\<in>A \\<bullet> P Y) \\<and> gvrt(n+1))\" and ?rhs = \"((\\<Sqinter>P\\<in>A \\<bullet> (P Y \\<and> gvrt(n+1))) \\<and> gvrt(n+1))\"\n    have a:\"?lhs\\<lbrakk>false/$ok\\<rbrakk> = ?rhs\\<lbrakk>false/$ok\\<rbrakk>\"\n      by (rel_auto)\n    have b:\"?lhs\\<lbrakk>true/$ok\\<rbrakk>\\<lbrakk>true/$wait\\<rbrakk> = ?rhs\\<lbrakk>true/$ok\\<rbrakk>\\<lbrakk>true/$wait\\<rbrakk>\"\n      by (rel_auto)\n    have c:\"?lhs\\<lbrakk>true/$ok\\<rbrakk>\\<lbrakk>false/$wait\\<rbrakk> = ?rhs\\<lbrakk>true/$ok\\<rbrakk>\\<lbrakk>false/$wait\\<rbrakk>\"\n      by (rel_auto)\n    show \"?lhs = ?rhs\"\n      using a b c\n      by (rule_tac bool_eq_splitI[of \"in_var ok\"], simp, rule_tac bool_eq_splitI[of \"in_var wait\"], simp_all)\n  qed\n  moreover have \"((\\<Sqinter>P\\<in>A \\<bullet> (P X \\<and> gvrt(n+1))) \\<and> gvrt(n+1)) =  ((\\<Sqinter>P\\<in>A \\<bullet> (P (X \\<and> gvrt(n)) \\<and> gvrt(n+1))) \\<and> gvrt(n+1))\"\n  proof -\n    have \"(\\<Sqinter>P\\<in>A \\<bullet> (P X \\<and> gvrt(n+1))) = (\\<Sqinter>P\\<in>A \\<bullet> (P (X \\<and> gvrt(n)) \\<and> gvrt(n+1)))\"\n    proof (rule UINF_cong)\n      fix P assume \"P \\<in> A\"\n      thus \"(P X \\<and> gvrt(n+1)) = (P (X \\<and> gvrt(n)) \\<and> gvrt(n+1))\"\n        using Guarded_def assms by blast\n    qed\n    thus ?thesis by simp\n  qed\n  ultimately show \"((\\<Sqinter>P\\<in>A \\<bullet> P X) \\<and> gvrt(n+1)) = ((\\<Sqinter>P\\<in>A \\<bullet> (P (X \\<and> gvrt(n)))) \\<and> gvrt(n+1))\"\n    by simp\nqed\n\nlemma intChoice_Guarded [closure]:\n  assumes \"Guarded P\" \"Guarded Q\"\n  shows \"Guarded (\\<lambda> X. P(X) \\<sqinter> Q(X))\"\nproof -\n  have \"Guarded (\\<lambda> X. \\<Sqinter>F\\<in>{P,Q} \\<bullet> F(X))\"\n    by (rule UINF_Guarded, auto simp add: assms)\n  thus ?thesis\n    by (simp)\nqed\n\nlemma cond_srea_Guarded [closure]:\n  assumes \"Guarded P\" \"Guarded Q\"\n  shows \"Guarded (\\<lambda> X. P(X) \\<triangleleft> b \\<triangleright>\\<^sub>R Q(X))\"\n  using assms by (rel_auto)\n\ntext \\<open> A tail recursive reactive design with a productive body is guarded. \\<close>\n\nlemma Guarded_if_Productive [closure]:\n  fixes P :: \"('s, 't::size_trace,'\\<alpha>) hrel_rsp\"\n  assumes \"P is NSRD\" \"P is Productive\"\n  shows \"Guarded (\\<lambda> X. P ;; SRD(X))\"\nproof (clarsimp simp add: Guarded_def)\n  \\<comment> \\<open> We split the proof into three cases corresponding to valuations for ok, wait, and wait'\n        respectively. \\<close>\n  fix X n\n  have a:\"(P ;; SRD(X) \\<and> gvrt (Suc n))\\<lbrakk>false/$ok\\<rbrakk> =\n        (P ;; SRD(X \\<and> gvrt n) \\<and> gvrt (Suc n))\\<lbrakk>false/$ok\\<rbrakk>\"\n    by (simp add: usubst closure SRD_left_zero_1 assms)\n  have b:\"((P ;; SRD(X) \\<and> gvrt (Suc n))\\<lbrakk>true/$ok\\<rbrakk>)\\<lbrakk>true/$wait\\<rbrakk> =\n          ((P ;; SRD(X \\<and> gvrt n) \\<and> gvrt (Suc n))\\<lbrakk>true/$ok\\<rbrakk>)\\<lbrakk>true/$wait\\<rbrakk>\"\n    by (simp add: usubst closure SRD_left_zero_2 assms)\n  have c:\"((P ;; SRD(X) \\<and> gvrt (Suc n))\\<lbrakk>true/$ok\\<rbrakk>)\\<lbrakk>false/$wait\\<rbrakk> =\n          ((P ;; SRD(X \\<and> gvrt n) \\<and> gvrt (Suc n))\\<lbrakk>true/$ok\\<rbrakk>)\\<lbrakk>false/$wait\\<rbrakk>\"\n  proof -\n    have 1:\"(P\\<lbrakk>true/$wait\\<acute>\\<rbrakk> ;; (SRD X)\\<lbrakk>true/$wait\\<rbrakk> \\<and> gvrt (Suc n))\\<lbrakk>true,false/$ok,$wait\\<rbrakk> =\n          (P\\<lbrakk>true/$wait\\<acute>\\<rbrakk> ;; (SRD (X \\<and> gvrt n))\\<lbrakk>true/$wait\\<rbrakk> \\<and> gvrt (Suc n))\\<lbrakk>true,false/$ok,$wait\\<rbrakk>\"\n      by (metis (no_types, lifting) Healthy_def R3h_wait_true SRD_healths(3) SRD_idem)\n    have 2:\"(P\\<lbrakk>false/$wait\\<acute>\\<rbrakk> ;; (SRD X)\\<lbrakk>false/$wait\\<rbrakk> \\<and> gvrt (Suc n))\\<lbrakk>true,false/$ok,$wait\\<rbrakk> =\n          (P\\<lbrakk>false/$wait\\<acute>\\<rbrakk> ;; (SRD (X \\<and> gvrt n))\\<lbrakk>false/$wait\\<rbrakk> \\<and> gvrt (Suc n))\\<lbrakk>true,false/$ok,$wait\\<rbrakk>\"\n    proof -\n      have exp:\"\\<And> Y::('s, 't,'\\<alpha>) hrel_rsp. (P\\<lbrakk>false/$wait\\<acute>\\<rbrakk> ;; (SRD Y)\\<lbrakk>false/$wait\\<rbrakk> \\<and> gvrt (Suc n))\\<lbrakk>true,false/$ok,$wait\\<rbrakk> =\n                  ((((\\<not>\\<^sub>r pre\\<^sub>R P) ;; (SRD(Y))\\<lbrakk>false/$wait\\<rbrakk> \\<or> (post\\<^sub>R P \\<and> $tr\\<acute> >\\<^sub>u $tr) ;; (SRD Y)\\<lbrakk>true,false/$ok,$wait\\<rbrakk>))\n                     \\<and> gvrt (Suc n))\\<lbrakk>true,false/$ok,$wait\\<rbrakk>\"\n      proof -\n        fix Y :: \"('s, 't,'\\<alpha>) hrel_rsp\"\n\n        have \"(P\\<lbrakk>false/$wait\\<acute>\\<rbrakk> ;; (SRD Y)\\<lbrakk>false/$wait\\<rbrakk> \\<and> gvrt (Suc n))\\<lbrakk>true,false/$ok,$wait\\<rbrakk> =\n              ((\\<^bold>R\\<^sub>s(pre\\<^sub>R(P) \\<turnstile> peri\\<^sub>R(P) \\<diamondop> (post\\<^sub>R(P) \\<and> $tr <\\<^sub>u $tr\\<acute>)))\\<lbrakk>false/$wait\\<acute>\\<rbrakk> ;; (SRD Y)\\<lbrakk>false/$wait\\<rbrakk> \\<and> gvrt (Suc n))\\<lbrakk>true,false/$ok,$wait\\<rbrakk>\"\n          by (metis (no_types) Healthy_def Productive_form assms(1) assms(2) NSRD_is_SRD)\n        also have \"... =\n             ((R1(R2c(pre\\<^sub>R(P) \\<Rightarrow> ($ok\\<acute> \\<and> post\\<^sub>R(P) \\<and> $tr <\\<^sub>u $tr\\<acute>))))\\<lbrakk>false/$wait\\<acute>\\<rbrakk> ;; (SRD Y)\\<lbrakk>false/$wait\\<rbrakk> \\<and> gvrt (Suc n))\\<lbrakk>true,false/$ok,$wait\\<rbrakk>\"\n          by (simp add: RHS_def R1_def R2c_def R2s_def R3h_def RD1_def RD2_def usubst unrest assms closure design_def)\n        also have \"... =\n             (((\\<not>\\<^sub>r pre\\<^sub>R(P) \\<or> ($ok\\<acute> \\<and> post\\<^sub>R(P) \\<and> $tr <\\<^sub>u $tr\\<acute>)))\\<lbrakk>false/$wait\\<acute>\\<rbrakk> ;; (SRD Y)\\<lbrakk>false/$wait\\<rbrakk> \\<and> gvrt (Suc n))\\<lbrakk>true,false/$ok,$wait\\<rbrakk>\"\n          by (simp add: impl_alt_def R2c_disj R1_disj R2c_not  assms closure R2c_and\n              R2c_preR rea_not_def R1_extend_conj' R2c_ok' R2c_post_SRD R1_tr_less_tr' R2c_tr_less_tr')\n        also have \"... =\n             ((((\\<not>\\<^sub>r pre\\<^sub>R P) ;; (SRD(Y))\\<lbrakk>false/$wait\\<rbrakk> \\<or> ($ok\\<acute> \\<and> post\\<^sub>R P \\<and> $tr\\<acute> >\\<^sub>u $tr) ;; (SRD Y)\\<lbrakk>false/$wait\\<rbrakk>)) \\<and> gvrt (Suc n))\\<lbrakk>true,false/$ok,$wait\\<rbrakk>\"\n          by (simp add: usubst unrest assms closure seqr_or_distl NSRD_neg_pre_left_zero)\n        also have \"... =\n             ((((\\<not>\\<^sub>r pre\\<^sub>R P) ;; (SRD(Y))\\<lbrakk>false/$wait\\<rbrakk> \\<or> (post\\<^sub>R P \\<and> $tr\\<acute> >\\<^sub>u $tr) ;; (SRD Y)\\<lbrakk>true,false/$ok,$wait\\<rbrakk>)) \\<and> gvrt (Suc n))\\<lbrakk>true,false/$ok,$wait\\<rbrakk>\"\n        proof -\n          have \"($ok\\<acute> \\<and> post\\<^sub>R P \\<and> $tr\\<acute> >\\<^sub>u $tr) ;; (SRD Y)\\<lbrakk>false/$wait\\<rbrakk> =\n                ((post\\<^sub>R P \\<and> $tr\\<acute> >\\<^sub>u $tr) \\<and> $ok\\<acute> =\\<^sub>u true) ;; (SRD Y)\\<lbrakk>false/$wait\\<rbrakk>\"\n            by (rel_blast)\n          also have \"... = (post\\<^sub>R P \\<and> $tr\\<acute> >\\<^sub>u $tr)\\<lbrakk>true/$ok\\<acute>\\<rbrakk> ;; (SRD Y)\\<lbrakk>false/$wait\\<rbrakk>\\<lbrakk>true/$ok\\<rbrakk>\"\n            using seqr_left_one_point[of ok \"(post\\<^sub>R P \\<and> $tr\\<acute> >\\<^sub>u $tr)\" True \"(SRD Y)\\<lbrakk>false/$wait\\<rbrakk>\"]\n            by (simp add: true_alt_def[THEN sym])\n          finally show ?thesis by (simp add: usubst unrest)\n        qed\n        finally\n        show \"(P\\<lbrakk>false/$wait\\<acute>\\<rbrakk> ;; (SRD Y)\\<lbrakk>false/$wait\\<rbrakk> \\<and> gvrt (Suc n))\\<lbrakk>true,false/$ok,$wait\\<rbrakk> =\n                 ((((\\<not>\\<^sub>r pre\\<^sub>R P) ;; (SRD(Y))\\<lbrakk>false/$wait\\<rbrakk> \\<or> (post\\<^sub>R P \\<and> $tr\\<acute> >\\<^sub>u $tr) ;; (SRD Y)\\<lbrakk>true,false/$ok,$wait\\<rbrakk>))\n                 \\<and> gvrt (Suc n))\\<lbrakk>true,false/$ok,$wait\\<rbrakk>\" .\n      qed\n\n      have 1:\"((post\\<^sub>R P \\<and> $tr\\<acute> >\\<^sub>u $tr) ;; (SRD X)\\<lbrakk>true,false/$ok,$wait\\<rbrakk> \\<and> gvrt (Suc n)) =\n              ((post\\<^sub>R P \\<and> $tr\\<acute> >\\<^sub>u $tr) ;; (SRD (X \\<and> gvrt n))\\<lbrakk>true,false/$ok,$wait\\<rbrakk> \\<and> gvrt (Suc n))\"\n        apply (rel_auto)\n         apply (rename_tac tr st more ok wait tr' st' more' tr\\<^sub>0 st\\<^sub>0 more\\<^sub>0 ok')\n         apply (rule_tac x=\"tr\\<^sub>0\" in exI, rule_tac x=\"st\\<^sub>0\" in exI, rule_tac x=\"more\\<^sub>0\" in exI)\n         apply (simp)\n         apply (erule trace_strict_prefixE)\n         apply (rename_tac tr st ref ok wait tr' st' ref' tr\\<^sub>0 st\\<^sub>0 ref\\<^sub>0 ok' zs)\n         apply (rule_tac x=\"False\" in exI)\n         apply (simp add: size_minus_trace)\n         apply (subgoal_tac \"size(tr) < size(tr\\<^sub>0)\")\n          apply (simp add: less_diff_conv2 size_mono)\n        using size_strict_mono apply blast\n        apply (rename_tac tr st more ok wait tr' st' more' tr\\<^sub>0 st\\<^sub>0 more\\<^sub>0 ok')\n        apply (rule_tac x=\"tr\\<^sub>0\" in exI, rule_tac x=\"st\\<^sub>0\" in exI, rule_tac x=\"more\\<^sub>0\" in exI)\n        apply (simp)\n        apply (erule trace_strict_prefixE)\n        apply (rename_tac tr st more ok wait tr' st' more' tr\\<^sub>0 st\\<^sub>0 more\\<^sub>0 ok' zs)\n        apply (auto simp add: size_minus_trace)\n        apply (subgoal_tac \"size(tr) < size(tr\\<^sub>0)\")\n         apply (simp add: less_diff_conv2 size_mono)\n        using size_strict_mono apply blast\n        done\n      have 2:\"(\\<not>\\<^sub>r pre\\<^sub>R P) ;; (SRD X)\\<lbrakk>false/$wait\\<rbrakk> = (\\<not>\\<^sub>r pre\\<^sub>R P) ;; (SRD(X \\<and> gvrt n))\\<lbrakk>false/$wait\\<rbrakk>\"\n        by (simp add: NSRD_neg_pre_left_zero closure assms SRD_healths)\n      show ?thesis\n        by (simp add: exp 1 2 utp_pred_laws.inf_sup_distrib2)\n    qed\n\n    show ?thesis\n    proof -\n      have \"(P ;; (SRD X) \\<and> gvrt (n+1))\\<lbrakk>true,false/$ok,$wait\\<rbrakk> =\n          ((P\\<lbrakk>true/$wait\\<acute>\\<rbrakk> ;; (SRD X)\\<lbrakk>true/$wait\\<rbrakk> \\<and> gvrt (n+1))\\<lbrakk>true,false/$ok,$wait\\<rbrakk> \\<or>\n          (P\\<lbrakk>false/$wait\\<acute>\\<rbrakk> ;; (SRD X)\\<lbrakk>false/$wait\\<rbrakk> \\<and> gvrt (n+1))\\<lbrakk>true,false/$ok,$wait\\<rbrakk>)\"\n        by (subst seqr_bool_split[of wait], simp_all add: usubst utp_pred_laws.distrib(4))\n\n      also\n      have \"... = ((P\\<lbrakk>true/$wait\\<acute>\\<rbrakk> ;; (SRD (X \\<and> gvrt n))\\<lbrakk>true/$wait\\<rbrakk> \\<and> gvrt (n+1))\\<lbrakk>true,false/$ok,$wait\\<rbrakk> \\<or>\n                 (P\\<lbrakk>false/$wait\\<acute>\\<rbrakk> ;; (SRD (X \\<and> gvrt n))\\<lbrakk>false/$wait\\<rbrakk> \\<and> gvrt (n+1))\\<lbrakk>true,false/$ok,$wait\\<rbrakk>)\"\n        by (simp add: 1 2)\n\n      also\n      have \"... = ((P\\<lbrakk>true/$wait\\<acute>\\<rbrakk> ;; (SRD (X \\<and> gvrt n))\\<lbrakk>true/$wait\\<rbrakk> \\<or>\n                    P\\<lbrakk>false/$wait\\<acute>\\<rbrakk> ;; (SRD (X \\<and> gvrt n))\\<lbrakk>false/$wait\\<rbrakk>) \\<and> gvrt (n+1))\\<lbrakk>true,false/$ok,$wait\\<rbrakk>\"\n        by (simp add: usubst utp_pred_laws.distrib(4))\n\n      also have \"... = (P ;; (SRD (X \\<and> gvrt n)) \\<and> gvrt (n+1))\\<lbrakk>true,false/$ok,$wait\\<rbrakk>\"\n        by (subst seqr_bool_split[of wait], simp_all add: usubst)\n      finally show ?thesis by (simp add: usubst)\n    qed\n\n  qed\n  show \"(P ;; SRD(X) \\<and> gvrt (Suc n)) = (P ;; SRD(X \\<and> gvrt n) \\<and> gvrt (Suc n))\"\n    apply (rule_tac bool_eq_splitI[of \"in_var ok\"])\n      apply (simp_all add: a)\n    apply (rule_tac bool_eq_splitI[of \"in_var wait\"])\n      apply (simp_all add: b c)\n  done\nqed\n\nsubsection \\<open> Tail recursive fixed-point calculations \\<close>\n\ndeclare upred_semiring.power_Suc [simp]\n\nlemma mu_csp_form_1 [rdes]:\n  fixes P :: \"('s, 't::size_trace,'\\<alpha>) hrel_rsp\"\n  assumes \"P is NSRD\" \"P is Productive\"\n  shows \"(\\<mu> X \\<bullet> P ;; SRD(X)) = (\\<Sqinter>i \\<bullet> P \\<^bold>^ (i+1)) ;; Miracle\"\nproof -\n  have 1:\"Continuous (\\<lambda>X. P ;; SRD X)\"\n    using SRD_Continuous\n    by (clarsimp simp add: Continuous_def seq_SUP_distl[THEN sym], drule_tac x=\"A\" in spec, simp)\n  have 2: \"(\\<lambda>X. P ;; SRD X) \\<in> \\<lbrakk>id\\<rbrakk>\\<^sub>H \\<rightarrow> \\<lbrakk>SRD\\<rbrakk>\\<^sub>H\"\n    by (blast intro: funcsetI closure assms)\n  with 1 2 have \"(\\<mu> X \\<bullet> P ;; SRD(X)) = (\\<nu> X \\<bullet> P ;; SRD(X))\"\n    by (simp add: guarded_fp_uniq Guarded_if_Productive[OF assms] funcsetI closure)\n  also have \"... = (\\<Sqinter>i. ((\\<lambda>X. P ;; SRD X) ^^ i) false)\"\n    by (simp add: sup_continuous_lfp 1 sup_continuous_Continuous false_upred_def)\n  also have \"... = ((\\<lambda>X. P ;; SRD X) ^^ 0) false \\<sqinter> (\\<Sqinter>i. ((\\<lambda>X. P ;; SRD X) ^^ (i+1)) false)\"\n    by (subst Sup_power_expand, simp)\n  also have \"... = (\\<Sqinter>i. ((\\<lambda>X. P ;; SRD X) ^^ (i+1)) false)\"\n    by (simp)\n  also have \"... = (\\<Sqinter>i. P \\<^bold>^ (i+1) ;; Miracle)\"\n  proof (rule SUP_cong, simp_all) \n    fix i\n    show \"P ;; SRD (((\\<lambda>X. P ;; SRD X) ^^ i) false) = (P ;; P \\<^bold>^ i) ;; Miracle\"\n    proof (induct i)\n      case 0\n      then show ?case\n        by (simp, metis srdes_theory.healthy_top)\n    next\n      case (Suc i)\n      then show ?case\n        by (simp add: Healthy_if NSRD_is_SRD SRD_power_comp SRD_seqr_closure assms(1) seqr_assoc[THEN sym] srdes_theory.top_closed)\n    qed\n  qed\n  also have \"... = (\\<Sqinter>i. P \\<^bold>^ (i+1)) ;; Miracle\"\n    by (simp add: seq_Sup_distr)\n  finally show ?thesis\n    by (simp add: UINF_as_Sup_collect)\nqed\n\nlemma mu_csp_form_NSRD [closure]:\n  fixes P :: \"('s, 't::size_trace,'\\<alpha>) hrel_rsp\"\n  assumes \"P is NSRD\" \"P is Productive\"\n  shows \"(\\<mu> X \\<bullet> P ;; SRD(X)) is NSRD\"\n  by (simp add: mu_csp_form_1 assms closure)\n\nlemma mu_csp_form_1':\n  fixes P :: \"('s, 't::size_trace,'\\<alpha>) hrel_rsp\"\n  assumes \"P is NSRD\" \"P is Productive\"\n  shows \"(\\<mu> X \\<bullet> P ;; SRD(X)) = (P ;; P\\<^sup>\\<star>) ;; Miracle\"\nproof -\n  have \"(\\<mu> X \\<bullet> P ;; SRD(X)) = (\\<Sqinter> i\\<in>UNIV \\<bullet> P ;; P \\<^bold>^ i) ;; Miracle\"\n    by (simp add: mu_csp_form_1 assms closure ustar_def)\n  also have \"... = (P ;; P\\<^sup>\\<star>) ;; Miracle\"\n    by (simp only: seq_UINF_distl[THEN sym], simp add: ustar_def)\n  finally show ?thesis .\nqed\n\ndeclare upred_semiring.power_Suc [simp del]\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/theories/rea_designs/utp_rdes_guarded.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8652240686758841, "lm_q2_score": 0.8128673110375458, "lm_q1q2_score": 0.7033123621495307}}
{"text": "theory mbc_properties\n  imports embedding\nbegin\nnitpick_params[assms=true, user_axioms=true, show_all, expect=genuine, format = 3]\n\nsection \\<open>Properties of paraconsistent logic mbC \\<close>\n\nabbreviation neg :: \"wo\\<Rightarrow>wo\" (\"\\<^bold>\\<not>_\" [54] 55) where \"\\<^bold>\\<not>\\<phi> \\<equiv> \\<^bold>\\<not>\\<^sup>p\\<phi>\" (* negation is paraconsistent*)\nabbreviation circ :: \"wo\\<Rightarrow>wo\" (\"\\<^bold>\\<circ>_\" [54] 55) where \"\\<^bold>\\<circ>\\<phi> \\<equiv> \\<^bold>\\<circ>\\<^sup>m\\<^sup>b\\<^sup>c\\<phi>\" (* logic is (R)mbC *)\n\n(* (1) *)\nlemma \"[a \\<^bold>\\<and> \\<^bold>\\<not>a \\<^bold>\\<turnstile>\\<^sub>l \\<^bold>\\<not>\\<^bold>\\<circ>a]\" by simp\nlemma \"[\\<^bold>\\<not>\\<^bold>\\<circ>a \\<^bold>\\<turnstile>\\<^sub>l a \\<^bold>\\<and> \\<^bold>\\<not>a]\" nitpick oops (* countermodel found *) \n\n(* (2) *)\nlemma \"[\\<^bold>\\<circ>a \\<^bold>\\<turnstile>\\<^sub>l \\<^bold>\\<not>(a \\<^bold>\\<and> \\<^bold>\\<not>a)]\" by simp \nlemma \"[\\<^bold>\\<not>(a \\<^bold>\\<and> \\<^bold>\\<not>a) \\<^bold>\\<turnstile>\\<^sub>l \\<^bold>\\<circ>a]\" nitpick oops (* countermodel found *) \n\n(* (3) *)\nlemma \"[\\<^bold>\\<not>a \\<^bold>\\<rightarrow> b \\<^bold>\\<turnstile>\\<^sub>l a \\<^bold>\\<or> b]\" by blast\nlemma \"[a \\<^bold>\\<or> b \\<^bold>\\<turnstile>\\<^sub>l \\<^bold>\\<not>a \\<^bold>\\<rightarrow> b]\" nitpick oops (* countermodel found *)\n\n(* (4) *)\nlemma \"[\\<^bold>\\<circ>a, a \\<^bold>\\<or> b  \\<^bold>\\<turnstile>\\<^sub>l \\<^bold>\\<not>a \\<^bold>\\<rightarrow> b]\" by simp\n\n(* (5) *)\nlemma \"[a \\<^bold>\\<rightarrow> b \\<^bold>\\<turnstile>\\<^sub>l \\<^bold>\\<not>b \\<^bold>\\<rightarrow> \\<^bold>\\<not>a]\" nitpick oops (* countermodel found *)\nlemma \"[\\<^bold>\\<circ>b, a \\<^bold>\\<rightarrow> b \\<^bold>\\<turnstile>\\<^sub>l \\<^bold>\\<not>b \\<^bold>\\<rightarrow> \\<^bold>\\<not>a]\" by blast\n\n(* (6) *)\nlemma \"[a \\<^bold>\\<rightarrow> \\<^bold>\\<not>b \\<^bold>\\<turnstile>\\<^sub>l b \\<^bold>\\<rightarrow> \\<^bold>\\<not>a]\" nitpick oops (* countermodel found *)\nlemma \"[\\<^bold>\\<circ>b, a \\<^bold>\\<rightarrow> \\<^bold>\\<not>b \\<^bold>\\<turnstile>\\<^sub>l b \\<^bold>\\<rightarrow> \\<^bold>\\<not>a]\" by blast\n\n(* (7) *)\nlemma \"[\\<^bold>\\<not>a \\<^bold>\\<rightarrow> b \\<^bold>\\<turnstile>\\<^sub>l \\<^bold>\\<not>b \\<^bold>\\<rightarrow> a]\" nitpick oops (* countermodel found *)\nlemma \"[\\<^bold>\\<circ>b, \\<^bold>\\<not>a \\<^bold>\\<rightarrow> b \\<^bold>\\<turnstile>\\<^sub>l \\<^bold>\\<not>b \\<^bold>\\<rightarrow> a]\" by blast\n\n(* (8) *)\nlemma \"[\\<^bold>\\<not>a \\<^bold>\\<rightarrow> \\<^bold>\\<not>b \\<^bold>\\<turnstile>\\<^sub>l b \\<^bold>\\<rightarrow> a]\" nitpick oops (* countermodel found *)\nlemma \"[\\<^bold>\\<circ>b, \\<^bold>\\<not>a \\<^bold>\\<rightarrow> \\<^bold>\\<not>b \\<^bold>\\<turnstile>\\<^sub>l b \\<^bold>\\<rightarrow> a]\" by blast\n\nend", "meta": {"author": "davfuenmayor", "repo": "Goedel-Incompleteness-Isabelle", "sha": "8675e275eba6375cbae8e086a3f23924d0b90bba", "save_path": "github-repos/isabelle/davfuenmayor-Goedel-Incompleteness-Isabelle", "path": "github-repos/isabelle/davfuenmayor-Goedel-Incompleteness-Isabelle/Goedel-Incompleteness-Isabelle-8675e275eba6375cbae8e086a3f23924d0b90bba/isabelle-sources/mbc_properties.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9111797027760039, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.7032881241685257}}
{"text": "(* Title:  Euler.thy\n   Author: Lars Noschinski, TU M\u00fcnchen\n*)\ntheory Euler imports\n  Arc_Walk\n  Digraph_Component\n  Digraph_Isomorphism\nbegin\n\nsection {* Euler Trails in Digraphs *}\n\ntext {*\n  In this section we prove the well-known theorem characterizing the\n  existence of an Euler Trail in an directed graph\n*}\n\nsubsection {* Trails and Euler Trails *}\n\ndefinition (in pre_digraph) euler_trail :: \"'a \\<Rightarrow> 'b awalk \\<Rightarrow> 'a \\<Rightarrow> bool\" where\n  \"euler_trail u p v \\<equiv> trail u p v \\<and> set p = arcs G \\<and> set (awalk_verts u p) = verts G\"\n\ncontext wf_digraph begin\n\n(* XXX move; notused*)\n\n\n(* XXX move; notused*)\nlemma (in fin_digraph) trails_finite: \"finite {p. \\<exists>u v. trail u p v}\"\nproof -\n  have \"{p. \\<exists>u v. trail u p v} \\<subseteq> {p. distinct p \\<and> set p \\<subseteq> arcs G}\"\n    by (auto simp: trail_def)\n  with finite_arcs finite_distinct show ?thesis by (blast intro: finite_subset)\nqed\n(* XXX: simplify apath_finite proof? *)\n\nlemma rotate_awalkE:\n  assumes \"awalk u p u\" \"w \\<in> set (awalk_verts u p)\"\n  obtains q r where \"p = q @ r\" \"awalk w (r @ q) w\" \"set (awalk_verts w (r @ q)) = set (awalk_verts u p)\"\nproof -\n  from assms obtain q r where A: \"p = q @ r\" and A': \"awalk u q w\" \"awalk w r u\"\n    by atomize_elim (rule awalk_decomp)\n  \n  then have B: \"awalk w (r @ q) w\" by auto\n\n  have C: \"set (awalk_verts w (r @ q)) = set (awalk_verts u p)\"\n    using `awalk u p u` A A' by (auto simp: set_awalk_verts_append)\n\n  from A B C show ?thesis ..\nqed\n\nlemma rotate_trailE:\n  assumes \"trail u p u\" \"w \\<in> set (awalk_verts u p)\"\n  obtains q r where \"p = q @ r\" \"trail w (r @ q) w\" \"set (awalk_verts w (r @ q)) = set (awalk_verts u p)\"\n  using assms by - (rule rotate_awalkE[where u=u and p=p and w=w], auto simp: trail_def)\n\nlemma rotate_trailE':\n  assumes \"trail u p u\" \"w \\<in> set (awalk_verts u p)\"\n  obtains q where \"trail w q w\" \"set q = set p\" \"set (awalk_verts w q) = set (awalk_verts u p)\"\nproof -\n  from assms obtain q r where \"p = q @ r\" \"trail w (r @ q) w\" \"set (awalk_verts w (r @ q)) = set (awalk_verts u p)\"\n    by (rule rotate_trailE)\n  then have \"set (r @ q) = set p\" by auto\n  show ?thesis by (rule that) fact+\nqed\n\nlemma sym_reachableI_in_awalk:\n  assumes walk: \"awalk u p v\" and\n    w1: \"w1 \\<in> set (awalk_verts u p)\" and w2: \"w2 \\<in> set (awalk_verts u p)\"\n  shows \"w1 \\<rightarrow>\\<^sup>*\\<^bsub>mk_symmetric G\\<^esub> w2\"\nproof -\n  from walk w1 obtain q r where \"p = q @ r\" \"awalk u q w1\" \"awalk w1 r v\"\n    by (atomize_elim) (rule awalk_decomp)\n  then have w2_in: \"w2 \\<in> set (awalk_verts u q) \\<union> set (awalk_verts w1 r)\"\n    using w2 by (auto simp: set_awalk_verts_append)\n\n  show ?thesis\n  proof cases\n    assume A: \"w2 \\<in> set (awalk_verts u q)\"\n    obtain s where \"awalk w2 s w1\"\n      using awalk_decomp[OF `awalk u q w1` A] by blast\n    then have \"w2 \\<rightarrow>\\<^sup>*\\<^bsub>mk_symmetric G\\<^esub> w1\" \n      by (intro reachable_awalkI reachable_mk_symmetricI)\n    with symmetric_mk_symmetric show ?thesis by (rule symmetric_reachable)\n  next\n    assume \"w2 \\<notin> set (awalk_verts u q)\"\n    then have A: \"w2 \\<in> set (awalk_verts w1 r)\"\n      using w2_in by blast\n    obtain s where \"awalk w1 s w2\"\n      using awalk_decomp[OF `awalk w1 r v` A] by blast\n    then show \"w1 \\<rightarrow>\\<^sup>*\\<^bsub>mk_symmetric G\\<^esub> w2\" \n      by (intro reachable_awalkI reachable_mk_symmetricI)\n  qed\nqed\n\nlemma euler_imp_connected:\n  assumes \"euler_trail u p v\" shows \"connected G\"\nproof -\n  { have \"verts G \\<noteq> {}\" using assms unfolding euler_trail_def trail_def by auto }\n  moreover\n  { fix w1 w2 assume \"w1 \\<in> verts G\" \"w2 \\<in> verts G\"\n    then have \"awalk u p v \" \"w1 \\<in> set (awalk_verts u p)\" \"w2 \\<in> set (awalk_verts u p)\"\n      using assms by (auto simp: euler_trail_def trail_def)\n    then have \"w1 \\<rightarrow>\\<^sup>*\\<^bsub>mk_symmetric G\\<^esub> w2\" by (rule sym_reachableI_in_awalk) }\n  ultimately show \"connected G\" by (rule connectedI)\nqed\n\nend\n\n\n\nsubsection {* Arc Balance of Walks *}\n\ncontext pre_digraph begin\n\n(* XXX change order of arguments? *)\ndefinition arc_set_balance :: \"'a \\<Rightarrow> 'b set \\<Rightarrow> int\" where\n  \"arc_set_balance w A = int (card (in_arcs G w \\<inter> A)) - int (card (out_arcs G w \\<inter> A))\"\n\ndefinition  arc_set_balanced :: \"'a \\<Rightarrow> 'b set \\<Rightarrow> 'a \\<Rightarrow> bool\" where\n  \"arc_set_balanced u A v \\<equiv>\n      if u = v then (\\<forall>w \\<in> verts G. arc_set_balance w A = 0)\n      else (\\<forall>w \\<in> verts G. (w \\<noteq> u \\<and> w \\<noteq> v) \\<longrightarrow> arc_set_balance w A = 0)\n        \\<and> arc_set_balance u A = -1\n        \\<and> arc_set_balance v A = 1\"\n\nabbreviation arc_balance :: \"'a \\<Rightarrow> 'b awalk \\<Rightarrow> int\" where\n  \"arc_balance w p \\<equiv> arc_set_balance w (set p)\"\n\nabbreviation arc_balanced :: \"'a \\<Rightarrow> 'b awalk \\<Rightarrow> 'a \\<Rightarrow> bool\" where\n  \"arc_balanced u p v \\<equiv> arc_set_balanced u (set p) v\"\n\nlemma arc_set_balanced_all:\n  \"arc_set_balanced u (arcs G) v =\n      (if u = v then (\\<forall>w \\<in> verts G. in_degree G w = out_degree G w)\n      else (\\<forall>w \\<in> verts G. (w \\<noteq> u \\<and> w \\<noteq> v) \\<longrightarrow> in_degree G w = out_degree G w)\n        \\<and> in_degree G u + 1 = out_degree G u\n        \\<and> out_degree G v + 1 = in_degree G v)\"\n  unfolding arc_set_balanced_def arc_set_balance_def in_degree_def out_degree_def by auto\n\nend\n\ncontext wf_digraph begin\n\n\n(* XXX tune assumption? e \\<notin> set es oder so? *)\nlemma arc_balance_Cons:\n  assumes \"trail u (e # es) v\"\n  shows \"arc_set_balance w (insert e (set es)) = arc_set_balance w {e} + arc_balance w es\"\nproof -\n  from assms have \"e \\<notin> set es\" \"e \\<in> arcs G\" by (auto simp: trail_def)\n\n  with `e \\<notin> set es` show ?thesis\n    apply (cases \"w = tail G e\")\n    apply (case_tac [!] \"w = head G e\")\n    apply (auto simp: arc_set_balance_def)\n    done\nqed\n\nlemma arc_balancedI_trail:\n  assumes \"trail u p v\" shows \"arc_balanced u p v\"\n  using assms\nproof (induct p arbitrary: u)\n  case Nil then show ?case by (auto simp: arc_set_balanced_def arc_set_balance_def trail_def)\nnext\n  case (Cons e es)\n  then have \"arc_balanced (head G e) es v\" \"u = tail G e\" \"e \\<in> arcs G\"\n    by (auto simp: awalk_Cons_iff trail_def)\n  moreover\n  have \"\\<And>w. arc_balance w [e] = (if w = tail G e \\<and> tail G e \\<noteq> head G e then -1\n      else if w = head G e \\<and> tail G e \\<noteq> head G e then 1 else 0)\"\n      using `e \\<in> _` by (case_tac \"w = tail G e\") (auto simp: arc_set_balance_def)\n  ultimately show ?case\n    by (auto simp: arc_set_balanced_def arc_balance_Cons[OF `trail u _ _`])\nqed\n\nlemma trail_arc_balanceE:\n  assumes \"trail u p v\"\n  obtains \"\\<And>w. \\<lbrakk> u = v \\<or> (w \\<noteq> u \\<and> w \\<noteq> v); w \\<in> verts G \\<rbrakk>\n      \\<Longrightarrow> arc_balance w p = 0\"\n    and \"\\<lbrakk> u \\<noteq> v \\<rbrakk> \\<Longrightarrow> arc_balance u p = - 1\"\n    and \"\\<lbrakk> u \\<noteq> v \\<rbrakk> \\<Longrightarrow> arc_balance v p = 1\"\n  using arc_balancedI_trail[OF assms] unfolding arc_set_balanced_def by (intro that) (metis,presburger+)\n\nend\n\n\n\nsubsection {* Closed Euler Trails *}\n\nlemma (in wf_digraph) awalk_vertex_props:\n  assumes \"awalk u p v\" \"p \\<noteq> []\"\n  assumes \"\\<And>w. w \\<in> set (awalk_verts u p) \\<Longrightarrow> P w \\<or> Q w\"\n  assumes \"P u\" \"Q v\"\n  shows \"\\<exists>e \\<in> set p. P (tail G e) \\<and> Q (head G e)\"\n  using assms(2,1,3-)\nproof (induct p arbitrary: u rule: list_nonempty_induct)\n  case (cons e es)\n  show ?case\n  proof (cases \"P (tail G e) \\<and> Q (head G e)\")\n    case False\n    then have \"P (head G e) \\<or> Q (head G e)\"\n      using cons.prems(1) cons.prems(2)[of \"head G e\"]\n      by (auto simp: awalk_Cons_iff set_awalk_verts)\n    then have \"P (tail G e) \\<and> P (head G e)\"\n      using False using cons.prems(1,3) by auto\n    \n    then have \"\\<exists>e \\<in> set es. P (tail G e) \\<and> Q (head G e)\"\n      using cons by (auto intro: cons simp: awalk_Cons_iff)\n    then show ?thesis by auto\n  qed auto\nqed (simp add: awalk_simps)\n\nlemma (in wf_digraph) connected_verts:\n  assumes \"connected G\" \"arcs G \\<noteq> {}\"\n  shows \"verts G = tail G ` arcs G \\<union> head G ` arcs G\"\nproof -\n  { assume \"verts G = {}\" then have ?thesis by (auto dest: tail_in_verts) }\n  moreover\n  { assume \"\\<exists>v. verts G = {v}\"\n    then obtain v where \"verts G = {v}\" by (auto simp: card_Suc_eq)\n    moreover\n    with `arcs G \\<noteq> {}` obtain e where \"e \\<in> arcs G\" \"tail G e = v\" \"head G e = v\"\n      by (auto dest: tail_in_verts head_in_verts)\n    moreover have \"tail G ` arcs G \\<union> head G ` arcs G \\<subseteq> verts G\" by auto \n    ultimately have ?thesis by auto }\n  moreover\n  { assume A: \"\\<exists>u v. u \\<in> verts G \\<and> v \\<in> verts G \\<and> u \\<noteq> v\"\n    { fix u assume \"u \\<in> verts G\"\n\n      interpret S: pair_wf_digraph \"mk_symmetric G\" by rule\n      from A obtain v where \"v \\<in> verts G\" \"u \\<noteq> v\" by blast\n      then obtain p where \"S.awalk u p v\"\n        using `connected G` `u \\<in> verts G` by (auto elim: connected_awalkE)\n      with `u \\<noteq> v` obtain e where \"e \\<in> parcs (mk_symmetric G)\" \"fst e = u\"\n        by (metis S.awalk_Cons_iff S.awalk_empty_ends list_exhaust2)\n      then obtain e' where \"tail G e' = u \\<or> head G e' = u\" \"e' \\<in> arcs G\"\n        by (force simp: parcs_mk_symmetric)\n      then have \"u \\<in> tail G ` arcs G \\<union> head G `arcs G\" by auto }\n    then have ?thesis by auto }\n  ultimately show ?thesis by blast\nqed\n\nlemma (in wf_digraph) connected_arcs_empty:\n  assumes \"connected G\" \"arcs G = {}\" \"verts G \\<noteq> {}\" obtains v where \"verts G = {v}\"\nproof (atomize_elim, rule ccontr)\n  assume A: \"\\<not> (\\<exists>v. verts G = {v})\"\n\n  interpret S: pair_wf_digraph \"mk_symmetric G\" by rule\n\n  from `verts G \\<noteq> {}` obtain u where \"u \\<in> verts G\" by auto\n  with A obtain v where \"v \\<in> verts G\" \"u \\<noteq> v\" by auto\n\n  from `connected G` `u \\<in> verts G` `v \\<in> verts G`\n  obtain p where \"S.awalk u p v\"\n    using `connected G` `u \\<in> verts G` by (auto elim: connected_awalkE)\n  with `u \\<noteq> v` obtain e where \"e \\<in> parcs (mk_symmetric G)\"\n    by (metis S.awalk_Cons_iff S.awalk_empty_ends list_exhaust2)\n  with `arcs G = {}` show False\n    by (auto simp: parcs_mk_symmetric)\nqed\n\nlemma (in wf_digraph) euler_trail_conv_connected:\n  assumes \"connected G\"\n  shows \"euler_trail u p v \\<longleftrightarrow> trail u p v \\<and> set p = arcs G\" (is \"?L \\<longleftrightarrow> ?R\")\nproof\n  assume ?R show ?L\n  proof cases\n    assume \"p = []\" with assms `?R` show ?thesis\n      by (auto simp: euler_trail_def trail_def awalk_def elim: connected_arcs_empty)\n  next\n    assume \"p \\<noteq> []\" then have \"arcs G \\<noteq> {}\" using `?R` by auto\n    with assms `?R` `p \\<noteq> []` show ?thesis\n      by (auto simp: euler_trail_def trail_def set_awalk_verts_not_Nil connected_verts)\n  qed\nqed (simp add: euler_trail_def)\n\nlemma (in wf_digraph) awalk_connected:\n  assumes \"connected G\" \"awalk u p v\" \"set p \\<noteq> arcs G\"\n  shows \"\\<exists>e. e \\<in> arcs G - set p \\<and> (tail G e \\<in> set (awalk_verts u p) \\<or> head G e \\<in> set (awalk_verts u p))\"\nproof (rule ccontr)\n  assume A: \"\\<not>?thesis\"\n\n  obtain e where \"e \\<in> arcs G - set p\"\n    using assms by (auto simp: trail_def)\n  with A have \"tail G e \\<notin> set (awalk_verts u p)\" \"tail G e \\<in> verts G\"\n    by auto\n\n  interpret S: pair_wf_digraph \"mk_symmetric G\" ..\n\n  have \"u \\<in> verts G\" using `awalk u p v` by (auto simp: awalk_hd_in_verts)\n  with `tail G e \\<in> _` and `connected G`\n  obtain q where q: \"S.awalk u q (tail G e)\"\n    by (auto elim: connected_awalkE)\n\n  have \"u \\<in> set (awalk_verts u p)\"\n    using `awalk u p v` by (auto simp: set_awalk_verts)\n\n  have \"q \\<noteq> []\" using `u \\<in> set _` `tail G e \\<notin> _` q by auto\n\n  have \"\\<exists>e \\<in> set q. fst e \\<in> set (awalk_verts u p) \\<and> snd e \\<notin> set (awalk_verts u p)\"\n    by (rule S.awalk_vertex_props[OF `S.awalk _ _ _` `q \\<noteq> []`]) (auto simp: `u \\<in> set _` `tail G e \\<notin> _`)\n  then obtain se' where se': \"se' \\<in> set q\" \"fst se' \\<in> set (awalk_verts u p)\" \"snd se' \\<notin> set (awalk_verts u p)\"\n    by auto\n\n  from se' have \"se' \\<in> parcs (mk_symmetric G)\" using q by auto\n  then obtain e' where \"e' \\<in> arcs G\" \"(tail G e' = fst se' \\<and> head G e' = snd se') \\<or> (tail G e' = snd se' \\<and> head G e' = fst se')\"\n    by (auto simp: parcs_mk_symmetric)\n  moreover\n  then have \"e' \\<notin> set p\" using se' `awalk u p v`\n    by (auto dest: awalk_verts_arc2 awalk_verts_arc1)\n  ultimately show False using se'\n    using A by auto\nqed\n\nlemma (in wf_digraph) trail_connected:\n  assumes \"connected G\" \"trail u p v\" \"set p \\<noteq> arcs G\"\n  shows \"\\<exists>e. e \\<in> arcs G - set p \\<and> (tail G e \\<in> set (awalk_verts u p) \\<or> head G e \\<in> set (awalk_verts u p))\"\n  using assms by (intro awalk_connected) (auto simp: trail_def)\n\ntheorem (in fin_digraph) closed_euler1:\n  assumes con: \"connected G\"\n  assumes deg: \"\\<And>u. u \\<in> verts G \\<Longrightarrow> in_degree G u = out_degree G u\"\n  shows \"\\<exists>u p. euler_trail u p u\"\nproof -\n  from con obtain u where \"u \\<in> verts G\" by (auto simp: connected_def strongly_connected_def)\n  then have \"trail u [] u\" by (auto simp: trail_def awalk_simps)\n  moreover\n  { fix u p v assume  \"trail u p v\"\n    then have \"\\<exists>u' p' v'. euler_trail u' p' v'\"\n    proof (induct \"card (arcs G) - length p\" arbitrary: u p v)\n      case 0\n      then have \"u \\<in> verts G\" by (auto simp: trail_def)\n\n      have \"set p \\<subseteq> arcs G\" using `trail u p v` by (auto simp: trail_def)\n      with 0 have \"set p = arcs G\"\n        by (auto simp: trail_def distinct_card[symmetric] card_seteq)\n      then have \"euler_trail u p v\"\n        using 0 by (simp add: euler_trail_conv_connected[OF con])\n      then show ?case by blast\n    next\n      case (Suc n)\n      then have neq: \"set p \\<noteq> arcs G\" \"u \\<in> verts G\"\n        by (auto simp: trail_def distinct_card[symmetric])\n\n      show ?case\n      proof (cases \"u = v\")\n        assume \"u \\<noteq> v\"\n        then have \"arc_balance u p = -1\"\n          using Suc neq by (auto elim: trail_arc_balanceE)\n        then have \"card (in_arcs G u \\<inter> set p) < card (out_arcs G u \\<inter> set p)\"\n          unfolding arc_set_balance_def by auto\n        also have \"\\<dots> \\<le> card (out_arcs G u)\"\n          by (rule card_mono) auto\n        finally have \"card (in_arcs G u \\<inter> set p) < card (in_arcs G u)\"\n          using deg[OF `u \\<in> _`] unfolding out_degree_def in_degree_def by simp\n        then have \"in_arcs G u - set p \\<noteq> {}\"\n          by (auto dest: card_psubset[rotated 2])\n        then obtain a where \"a \\<in> arcs G\" \"head G a = u\" \"a \\<notin> set p\"\n          by (auto simp: in_arcs_def)\n        then have *: \"trail (tail G a) (a # p) v\"\n          using Suc by (auto simp: trail_def awalk_simps)\n        then show ?thesis\n          using Suc by (intro Suc) auto\n      next\n        assume \"u = v\"\n        with neq con Suc\n        obtain a where a_in: \"a \\<in> arcs G - set p\"\n            and a_end: \"(tail G a \\<in> set (awalk_verts u p) \\<or> head G a \\<in> set (awalk_verts u p))\"\n          by (atomize_elim) (rule trail_connected)\n        have \"trail u p u\" using Suc `u = v` by simp\n        show ?case\n        proof (cases \"tail G a \\<in> set (awalk_verts u p)\")\n          case True\n          with `trail u p u` obtain q where q: \"set p = set q\" \"trail (tail G a) q (tail G a)\"\n            by (rule rotate_trailE') blast\n          with True a_in have *: \"trail (tail G a) (q @ [a]) (head G a)\"\n            by (fastforce simp: trail_def awalk_simps )\n          moreover\n          from q Suc have \"length q = length p\"\n            by (simp add: trail_def distinct_card[symmetric])\n          ultimately\n          show ?thesis using Suc  by (intro Suc) auto\n        next\n          case False\n          with a_end have \"head G a \\<in> set (awalk_verts u p)\" by blast\n          with `trail u p u` obtain q where q: \"set p = set q\" \"trail (head G a) q (head G a)\"\n            by (rule rotate_trailE') blast\n          with False a_in have *: \"trail (tail G a) (a # q) (head G a)\"\n            by (fastforce simp: trail_def awalk_simps )\n          moreover\n          from q Suc have \"length q = length p\"\n            by (simp add: trail_def distinct_card[symmetric])\n          ultimately\n          show ?thesis using Suc by (intro Suc) auto\n        qed\n      qed\n    qed }\n  ultimately obtain u p v where et: \"euler_trail u p v\" by blast\n  moreover\n  have \"u = v\"\n  proof -\n    have \"arc_balanced u p v\"\n      using `euler_trail u p v` by (auto simp: euler_trail_def dest: arc_balancedI_trail)\n    then show ?thesis\n      using `euler_trail u p v` deg\n      by (auto simp add: euler_trail_def trail_def arc_set_balanced_all split: split_if_asm)\n  qed\n  ultimately show ?thesis by blast\nqed\n\nlemma (in wf_digraph) closed_euler_imp_eq_degree:\n  assumes \"euler_trail u p u\"\n  assumes \"v \\<in> verts G\"\n  shows \"in_degree G v = out_degree G v\"\nproof -\n  from assms have \"arc_balanced u p u\" \"set p = arcs G\"\n    unfolding euler_trail_def by (auto dest: arc_balancedI_trail)\n  with assms have \"arc_balance v p = 0\"\n    unfolding arc_set_balanced_def by auto\n  moreover\n  from `set p = _` have \"in_arcs G v \\<inter> set p = in_arcs G v\" \"out_arcs G v \\<inter> set p = out_arcs G v\"\n    by (auto intro: in_arcs_in_arcs out_arcs_in_arcs)\n  ultimately\n  show ?thesis unfolding arc_set_balance_def in_degree_def out_degree_def by auto\nqed\n\n\n\ntheorem (in fin_digraph) closed_euler2:\n  assumes \"euler_trail u p u\"\n  shows \"connected G\"\n    and \"\\<And>u. u \\<in> verts G \\<Longrightarrow> in_degree G u = out_degree G u\" (is \"\\<And>u. _ \\<Longrightarrow> ?eq_deg u\")\nproof -\n  from assms show \"connected G\" by (rule euler_imp_connected)\nnext\n  fix v assume A: \"v \\<in> verts G\"\n  with assms show \"?eq_deg v\" by (rule closed_euler_imp_eq_degree)\nqed\n\ncorollary (in fin_digraph) closed_euler:\n  \"(\\<exists>u p. euler_trail u p u) \\<longleftrightarrow> connected G \\<and> (\\<forall>u \\<in> verts G. in_degree G u = out_degree G u)\"\n  by (auto dest: closed_euler1 closed_euler2)\n\n\n\nsubsection {* Open euler trails *}\n\ntext {*\n  Intuitively, a graph has an open euler trail if and only if it is possible to add\n  an arc such that the resulting graph has a closed euler trail. However, this is\n  not true in our formalization, as the arc type @{typ 'b} might be finite:\n\n  Consider for example the graph\n  @{term \"\\<lparr> verts = {0,1}, arcs = {()}, tail = \\<lambda>_. 0, head = \\<lambda>_. 1 \\<rparr>\"}. This graph\n  obviously has an open euler trail, but we cannot add another arc, as we already\n  exhausted the universe.\n\n  However, for each @{term \"fin_digraph G\"} there exist an isomorphic graph\n  @{term H} with arc type @{typ \"'a \\<times> nat \\<times> 'a\"}. Hence, we first characterize\n  the existence of euler trail for the infinite arc type @{typ \"'a \\<times> nat \\<times> 'a\"}\n  and transfer that result back to arbitrary arc types.\n*}\n\nlemma open_euler_infinite_label:\n  fixes G :: \"('a, 'a \\<times> nat \\<times> 'a) pre_digraph\"\n  assumes \"fin_digraph G\"\n  assumes [simp]: \"tail G = fst\" \"head G = snd o snd\"\n  assumes con: \"connected G\"\n  assumes uv: \"u \\<in> verts G\" \"v \\<in> verts G\"\n  assumes deg: \"\\<And>w. \\<lbrakk>w \\<in> verts G; u \\<noteq> w; v \\<noteq> w\\<rbrakk> \\<Longrightarrow> in_degree G w = out_degree G w\"\n  assumes deg_in: \"in_degree G u + 1 = out_degree G u\"\n  assumes deg_out: \"out_degree G v + 1 = in_degree G v\"\n  shows \"\\<exists>p. pre_digraph.euler_trail G u p v\"\nproof -\n  def [simp]: label \\<equiv> \"fst o snd :: 'a \\<times> nat \\<times> 'a \\<Rightarrow> nat\"\n\n  interpret fin_digraph G by fact\n\n  have \"finite (label ` arcs G)\" by auto\n  moreover have \"\\<not>finite (UNIV :: nat set)\" by blast\n  ultimately obtain l where \"l \\<notin> label ` arcs G\" by atomize_elim (rule ex_new_if_finite)\n\n  from deg_in deg_out have \"u \\<noteq> v\" by auto\n\n  let ?e = \"(v,l,u)\"\n\n  have e_notin:\"?e \\<notin> arcs G\"\n    using `l \\<notin> _` by (auto simp: image_def)\n\n  let ?H = \"add_arc ?e\"\n    -- \"We define a graph which has an closed euler trail\"\n\n  have [simp]: \"verts ?H = verts G\" using uv by simp\n  have [intro]: \"\\<And>a. compatible (add_arc a) G\" by (simp add: compatible_def)\n\n  interpret H: fin_digraph \"add_arc a\" for a\n    where \"tail (add_arc a) = tail G\" and \"head (add_arc a) = head G\"\n      and \"pre_digraph.cas (add_arc a) = cas\"\n      and \"pre_digraph.awalk_verts (add_arc a) = awalk_verts\"\n      by unfold_locales (auto dest: wellformed intro: compatible_cas compatible_awalk_verts\n          simp: verts_add_arc_conv)\n\n  have \"\\<exists>u p. H.euler_trail ?e u p u\"\n  proof (rule H.closed_euler1)\n    show \"connected ?H\"\n    proof (rule H.connectedI)\n      interpret sH: pair_fin_digraph \"mk_symmetric ?H\" ..\n      fix u v assume \"u \\<in> verts ?H\" \"v \\<in> verts ?H\"\n      with con have \"u \\<rightarrow>\\<^sup>*\\<^bsub>mk_symmetric G\\<^esub> v\" by (auto simp: connected_def)\n      moreover\n      have \"subgraph G ?H\" by (auto simp: subgraph_def) unfold_locales\n      ultimately show \"u \\<rightarrow>\\<^sup>*\\<^bsub>with_proj (mk_symmetric ?H)\\<^esub> v\"\n        by (blast intro: sH.reachable_mono subgraph_mk_symmetric)\n    qed (simp add: verts_add_arc_conv)\n  next\n    fix w assume \"w \\<in> verts ?H\"\n    then show \"in_degree ?H w = out_degree ?H w\"\n      using deg deg_in deg_out e_notin\n      apply (cases \"w = u\")\n      apply (case_tac [!] \"w = v\")\n      by (auto simp: in_degree_add_arc_iff out_degree_add_arc_iff)\n  qed\n\n  then obtain w p where Het: \"H.euler_trail ?e w p w\" by blast\n  then have \"?e \\<in> set p\" by (auto simp: pre_digraph.euler_trail_def)\n  then obtain q r where p_decomp: \"p = q @ [?e] @ r\"\n    by (auto simp: in_set_conv_decomp)\n    -- \"We show now that removing the additional arc of @{term ?H}\n      from p yields an euler trail in G \"\n\n  have \"euler_trail u (r @ q) v\"\n  proof (unfold euler_trail_conv_connected[OF con], intro conjI)\n    from Het have Ht': \"H.trail ?e v (?e # r @ q) v\"\n      unfolding p_decomp H.euler_trail_def H.trail_def\n      by (auto simp: p_decomp H.awalk_Cons_iff)\n    then have \"H.trail ?e u (r @ q) v\" \"?e \\<notin> set (r @ q)\"\n      by (auto simp: H.trail_def H.awalk_Cons_iff)\n    then show t': \"trail u (r @ q) v\"\n      by (auto simp: trail_def H.trail_def awalk_def H.awalk_def)\n\n    show \"set (r @ q) = arcs G\"\n    proof -\n      have \"arcs G = arcs ?H - {?e}\" using e_notin by auto\n      also have \"arcs ?H = set p\" using Het\n        by (auto simp: pre_digraph.euler_trail_def pre_digraph.trail_def)\n      finally show ?thesis using `?e \\<notin> set _` by (auto simp: p_decomp)\n    qed\n  qed\n  then show ?thesis by blast\nqed\n\ncontext wf_digraph begin\n\nlemma trail_app_isoI:\n  assumes t: \"trail u p v\"\n    and hom: \"digraph_isomorphism hom\"\n  shows \"pre_digraph.trail (app_iso hom G) (iso_verts hom u) (map (iso_arcs hom) p) (iso_verts hom v)\"\nproof -\n  interpret H: wf_digraph \"app_iso hom G\" using hom ..\n  from t hom have i: \"inj_on (iso_arcs hom) (set p)\"\n     unfolding trail_def digraph_isomorphism_def by (auto dest:subset_inj_on[where A=\"set p\"])\n  then have \"distinct (map (iso_arcs hom) p) = distinct p\"\n    by (auto simp: distinct_map dest: inj_onD)\n  with t hom show ?thesis\n    by (auto simp: pre_digraph.trail_def awalk_app_isoI)\nqed\n\nlemma euler_trail_app_isoI:\n  assumes t: \"euler_trail u p v\"\n    and hom: \"digraph_isomorphism hom\"\n  shows \"pre_digraph.euler_trail (app_iso hom G) (iso_verts hom u) (map (iso_arcs hom) p) (iso_verts hom v)\"\nproof -\n  from t have \"awalk u p v\" by (auto simp: euler_trail_def trail_def)\n  with assms show ?thesis\n    by (simp add: pre_digraph.euler_trail_def trail_app_isoI awalk_verts_app_iso_eq)\nqed\n\n\nend\n\ncontext fin_digraph begin\n\n(* XXX: We can get rid of \"u \\<in> verts G\" \"v \\<in> verts G\" here and in @{thm open_euler_infinite_label} *)\ntheorem open_euler1:\n  assumes \"connected G\"\n  assumes \"u \\<in> verts G\" \"v \\<in> verts G\"\n  assumes \"\\<And>w. \\<lbrakk>w \\<in> verts G; u \\<noteq> w; v \\<noteq> w\\<rbrakk> \\<Longrightarrow> in_degree G w = out_degree G w\"\n  assumes \"in_degree G u + 1 = out_degree G u\"\n  assumes \"out_degree G v + 1 = in_degree G v\"\n  shows \"\\<exists>p. euler_trail u p v\"\nproof -\n  obtain f and n :: nat where \"f ` arcs G = {i. i < n}\"\n      and i: \"inj_on f (arcs G)\"\n    by atomize_elim (rule finite_imp_inj_to_nat_seg, auto)\n\n  def iso_f \\<equiv> \"\\<lparr> iso_verts = id, iso_arcs = (\\<lambda>a. (tail G a, f a, head G a)),\n    head = snd o snd, tail = fst \\<rparr>\"\n  have [simp]: \"iso_verts iso_f = id\" \"iso_head iso_f = snd o snd\" \"iso_tail iso_f = fst\"\n    unfolding iso_f_def by auto\n  have di_iso_f: \"digraph_isomorphism iso_f\" unfolding digraph_isomorphism_def iso_f_def\n    by (auto intro: inj_onI dest: inj_onD[OF i])\n\n  let ?iso_g = \"inv_iso iso_f\"\n  have [simp]: \"\\<And>u. u \\<in> verts G \\<Longrightarrow> iso_verts ?iso_g u = u\"\n    by (auto simp: inv_iso_def fun_eq_iff the_inv_into_f_eq)\n\n  let ?H = \"app_iso iso_f G\"\n  interpret H: fin_digraph ?H using di_iso_f ..\n\n  have \"\\<exists>p. H.euler_trail u p v\"\n    using di_iso_f assms i\n    by (intro open_euler_infinite_label) (auto simp: connectedI_app_iso app_iso_eq)\n  then obtain p where Het: \"H.euler_trail u p v\" by blast\n\n  have \"pre_digraph.euler_trail (app_iso ?iso_g ?H) (iso_verts ?iso_g u) (map (iso_arcs ?iso_g) p) (iso_verts ?iso_g v)\"\n    using Het by (intro H.euler_trail_app_isoI digraph_isomorphism_invI di_iso_f)\n  then show ?thesis using di_iso_f `u \\<in> _` `v \\<in> _` by simp rule\nqed\n\ntheorem open_euler2:\n  assumes et: \"euler_trail u p v\" and \"u \\<noteq> v\"\n  shows \"connected G \\<and>\n    (\\<forall>w \\<in> verts G. u \\<noteq> w \\<longrightarrow> v \\<noteq> w \\<longrightarrow> in_degree G w = out_degree G w) \\<and>\n    in_degree G u + 1 = out_degree G u \\<and>\n    out_degree G v + 1 = in_degree G v\"\nproof -\n  from et have *: \"trail u p v\" \"u \\<in> verts G\" \"v \\<in> verts G\"\n    by (auto simp: euler_trail_def trail_def awalk_hd_in_verts)\n\n  from et have [simp]: \"\\<And>u. card (in_arcs G u \\<inter> set p) = in_degree G u\"\n      \"\\<And>u. card (out_arcs G u \\<inter> set p) = out_degree G u\"\n    by (auto simp: in_degree_def out_degree_def euler_trail_def intro: arg_cong[where f=card])\n\n  from assms * show ?thesis\n    by (auto simp: arc_set_balance_def elim: trail_arc_balanceE\n        intro: euler_imp_connected)\nqed\n\ncorollary open_euler:\n  \"(\\<exists>u p v. euler_trail u p v \\<and> u \\<noteq> v) \\<longleftrightarrow>\n    connected G \\<and> (\\<exists>u v. u \\<in> verts G \\<and> v \\<in> verts G \\<and>\n      (\\<forall>w \\<in> verts G. u \\<noteq> w \\<longrightarrow> v \\<noteq> w \\<longrightarrow> in_degree G w = out_degree G w) \\<and>\n      in_degree G u + 1 = out_degree G u \\<and>\n      out_degree G v + 1 = in_degree G v)\" (is \"?L \\<longleftrightarrow> ?R\")\nproof\n  assume ?L\n  then obtain u p v where *: \"euler_trail u p v\" \"u \\<noteq> v\"\n    by auto\n  then have \"u \\<in> verts G\" \"v \\<in> verts G\"\n    by (auto simp: euler_trail_def trail_def awalk_hd_in_verts)\n  then show ?R using open_euler2[OF *] by blast\nnext\n  assume ?R\n  then obtain u v where *:\n    \"connected G\" \"u \\<in> verts G\" \"v \\<in> verts G\"\n    \"\\<And>w. \\<lbrakk>w \\<in> verts G; u \\<noteq> w; v \\<noteq> w\\<rbrakk> \\<Longrightarrow> in_degree G w = out_degree G w\"\n    \"in_degree G u + 1 = out_degree G u\"\n    \"out_degree G v + 1 = in_degree G v\"\n    by blast\n  then have \"u \\<noteq> v\" by auto\n  from * show ?L by (metis open_euler1 `u \\<noteq> v`)\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/Graph_Theory/Euler.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.857768108626046, "lm_q2_score": 0.8198933403143929, "lm_q1q2_score": 0.7032783597965678}}
{"text": "theory \"Cambridge-Tripos\"\n  imports \"HOL-Complex_Analysis.Complex_Analysis\" \"HOL-Algebra.Algebra\" \"HOL-Library.Function_Algebras\"\n\nbegin\n\n(*\nproblem_number:2022_IA_1-II-9D-a\nnatural language statement:\nLet $a_{n}$ be a sequence of real numbers. Show that if $a_{n}$ converges, the sequence $\\frac{1}{n} \\sum_{k=1}^{n} a_{k}$ also converges and $\\lim _{n \\rightarrow \\infty} \\frac{1}{n} \\sum_{k=1}^{n} a_{k}=\\lim _{n \\rightarrow \\infty} a_{n}$.\nlean statement:\n\ncodex statement:\ntheorem lim_sum_div_n_eq_lim:\n  fixes f::\"nat \\<Rightarrow> 'a::real_normed_vector\"\n  assumes \"convergent f\"\n  shows \"convergent (\\<lambda>n. (\\<Sum>i<n. f i) / n) \\<and> lim (\\<lambda>n. (\\<Sum>i<n. f i) / n) = lim f\"\nOur comment on the codex statement: type real, not 'a::real_normed_vector\n *)\ntheorem \"exercise_2022_IA_1-II-9D-a\":\n  fixes a::\"nat \\<Rightarrow> real\"\n  assumes \"convergent a\"\n  shows \"convergent (\\<lambda>n. (\\<Sum>i<n. a i) / n) \\<and> lim (\\<lambda>n. (\\<Sum>i<n. a i) / n) = lim a\"\n  oops\n\n(*\nproblem_number:2022_IA_1-II-10D-c\nnatural language statement:\nLet a function $g:(0, \\infty) \\rightarrow \\mathbb{R}$ be continuous and bounded. Show that for every $T>0$ there exists a sequence $x_{n}$ such that $x_{n} \\rightarrow \\infty$ and $\\lim _{n \\rightarrow \\infty}\\left(g\\left(x_{n}+T\\right)-g\\left(x_{n}\\right)\\right)=0 .$\nlean statement:\n\ncodex statement:\ntheorem exists_seq_tendsto_infty_of_continuous_bounded:\n  fixes g::\"real \\<Rightarrow> real\"\n  assumes \"continuous_on {0<..} g\" \"bounded (range g)\"\n  shows \"\\<forall>T>0. \\<exists>x. x\\<longrightarrow>\\<infinity> \\<and> (\\<forall>n. g (x n + T) - g (x n) \\<longrightarrow> 0)\"\nOur comment on the codex statement: the limits are expressed wrongly, especially \"x tends to infinity\"\n *)\ntheorem \"exercise_2022_IA_1-II-10D-c\":\n  fixes g::\"real \\<Rightarrow> real\"\n  assumes \"continuous_on {0<..} g\" \"bounded (range g)\"\n  shows \"\\<forall>T>0. \\<exists>x::nat\\<Rightarrow>real. filterlim x at_top sequentially \\<and> (\\<lambda>n. g (x n + T) - g (x n)) \\<longlonglongrightarrow> 0\"\n  oops\n\n(*\nproblem_number:2022_IA_4-I-1E-a\nnatural language statement:\nBy considering numbers of the form $3 p_{1} \\ldots p_{k}-1$, show that there are infinitely many primes \nof the form $3 n+2$ with $n \\in \\mathbb{N}$.\nlean statement:\n\ncodex statement:\ntheorem exists_infinite_primes_of_form_3n_plus_2:\n  fixes n::nat\n  assumes \"\\<forall>p. prime p \\<longrightarrow> p dvd n \\<longrightarrow> p = 2 \\<or> p = 3\"\n  shows \"\\<exists>p. prime p \\<and> p dvd n\"\nOur comment on the codex statement: ALL WRONG. It turned the hint into a (contradictory) assumption!\n *)\ntheorem \"exercise_2022_IA_4-I-1E-a\": \n  shows \"infinite {p::nat. prime p \\<and> (\\<exists>n. p = 3*n+2)}\"\n  oops\n\n(*\nproblem_number:2022_IA_4-I-2D-a\nnatural language statement:\nProve that $\\sqrt[3]{2}+\\sqrt[3]{3}$ is irrational.\nlean statement:\n\ncodex statement:\ntheorem irrational_of_sum_of_irrational_roots:\n  assumes \"\\<forall>x y. x^3 = 2 \\<and> y^3 = 3 \\<longrightarrow> x = y\"\n  shows \"\\<forall>x y. x^3 = 2 \\<and> y^3 = 3 \\<longrightarrow> x + y \\<noteq> 0\"\nOur comment on the codex statement: <YOU CAN LEAVE YOUR COMMENT HERE>\n *)\ntheorem \"exercise_2022_IA_4-I-2D-a\":\n  shows \"root 3 2 + root 3 3 \\<notin> \\<rat>\"\n  oops\n\n\n(*\nproblem_number:2022_IB_3-II-13G-a-i\nnatural language statement:\nLet $U \\subset \\mathbb{C}$ be a (non-empty) connected open set and let $f_n$ be a sequence of holomorphic functions defined on $U$. Suppose that $f_n$ converges uniformly to a function $f$ on every compact subset of $U$. Show that $f$ is holomorphic in $U$.\nlean statement:\n\ncodex statement:\ntheorem holomorphic_of_uniform_convergent_holomorphic:\n  fixes f::\"complex \\<Rightarrow> complex\" and f::\"nat \\<Rightarrow> complex \\<Rightarrow> complex\"\n  assumes \"open U\" \"connected U\" \"\\<forall>n. holomorphic_on U (f n)\" \"\\<forall>K. compact K \\<subseteq> U \\<longrightarrow> uniform_limit (f n) f (uniformity_on K)\"\n  shows \"holomorphic_on U f\"\nOur comment on the codex statement: Can't have two variables called f. U is nonempty\n *)\ntheorem \"exercise_2022_IB_3-II-13G-a-i\":\n  assumes \"open U\" \"connected U\" \"U \\<noteq> {}\" \n  assumes \"\\<forall>n. (f n) holomorphic_on U\" and \"\\<forall>K. compact K \\<and> K \\<subseteq> U \\<longrightarrow> uniform_limit K f F sequentially\"\n  shows \"F holomorphic_on U\"\n  oops\n\n\n(*\nproblem_number:2022_IB_3-II-11G-b\nnatural language statement:\nLet $f: \\mathbb{R}^{2} \\rightarrow \\mathbb{R}^{2}$ be the map given by $f(x, y)=\\left(\\frac{\\cos x+\\cos y-1}{2}, \\cos x-\\cos y\\right)$. Prove that $f$ has a fixed point.\nlean statement:\n\ncodex statement:\ntheorem exists_fixed_point_of_f:\n  fixes f::\"real \\<Rightarrow> real \\<Rightarrow> real\"\n  assumes \"f = (\\<lambda>x y. (cos x + cos y - 1)/2, cos x - cos y)\"\n  shows \"\\<exists>x. f x = x\"\nOur comment on the codex statement: <YOU CAN LEAVE YOUR COMMENT HERE>\n *)\ntheorem \"exercise_2022_IB_3-II-11G-b\": \n  defines \"f \\<equiv> (\\<lambda>(x,y). ((cos x + cos y - 1)/2, cos x - cos y))\"\n  shows \"\\<exists>u. f u = u\"\n  oops\n\n\n(*\nproblem_number:2022_IB_1-I-3G-i\nnatural language statement:\nShow that $f(z)=\\frac{z}{\\sin z}$ has a removable singularity at $z=0$.\nlean statement:\n\ncodex statement:\ntheorem removable_singularity_sin_z:\n  fixes f::\"complex \\<Rightarrow> complex\"\n  assumes \"f holomorphic_on {z. z \\<noteq> 0}\" \"f 0 = 0\"\n  shows \"f holomorphic_on UNIV\"\nOur comment on the codex statement: \"singularity\" (as opposed to pole) is not expressible in Isabelle/HOL; the rest is also wrong\n *)\ntheorem \"exercise_2022_IB_1-I-3G-i\": \n  shows \"(\\<lambda>z. z / sin z) holomorphic_on UNIV\"\n  oops\n\n(*\nproblem_number:2022_IB_3-I-1E-ii\nnatural language statement:\nLet $R$ be a subring of a ring $S$, and let $J$ be an ideal in $S$. Show that $R+J$ is a subring of $S$ and that $\\frac{R}{R \\cap J} \\cong \\frac{R+J}{J}$.\nlean statement:\n\ncodex statement:\ntheorem is_ring_of_subring_plus_ideal:\n  fixes R S::\"'a::comm_ring_1 ring\" and J::\"'a ring\"\n  assumes \"subring R S\" \"ideal J S\"\n  shows \"subring (R + J) S\"\nOur comment on the codex statement: <YOU CAN LEAVE YOUR COMMENT HERE>\n *)\nno_notation Sum_Type.Plus (infixr \"<+>\" 65)\n\ntheorem (in ring) \"exercise_2022_IB_3-I-1E-ii\": \n  assumes \"subring R' R\" \"ideal J R\"\n  shows \"subring (R' <+> J) S \\<and> (R \\<lparr> carrier := R' \\<rparr>) Quot (R' \\<inter> J) \\<simeq> (R \\<lparr> carrier := (R' <+> J) \\<rparr>) Quot J\"\n  oops\n\n\n(*\nproblem_number:2022_IIB_1-II-8F-a-i\nnatural language statement:\nLet $V$ be a finite dimensional complex inner product space, and let $\\alpha$ be an endomorphism of $V$. Define its adjoint $\\alpha^*$. Assume that $\\alpha$ is normal, i.e. $\\alpha$ commutes with its adjoint: $\\alpha \\alpha^*=\\alpha^* \\alpha$. Show that $\\alpha$ and $\\alpha^*$ have a common eigenvector $\\mathbf{v}$.\nlean statement:\n\ncodex statement:\ntheorem exists_common_eigenvector_of_normal_endomorphism:\n  fixes V::\"complex vector\" and \\<alpha>::\"complex \\<Rightarrow> complex\"\n  assumes \"finite_dimensional V\" \"inner_product_space V\" \"linear \\<alpha>\" \"\\<alpha> o \\<alpha> = \\<alpha> o \\<alpha>\"\n  shows \"\\<exists>v. v \\<noteq> 0 \\<and> (\\<alpha> v = \\<alpha> v) \\<and> (\\<alpha> v = \\<alpha> v)\"\nOur comment on the codex statement: <YOU CAN LEAVE YOUR COMMENT HERE>\n *)\ntheorem \"exercise_2022_IIB_1-II-8F-a-i\": undefined oops\n\n\n(*\nproblem_number:2021_IIB_3-II-11F-ii\nnatural language statement:\nLet $X$ be an open subset of Euclidean space $\\mathbb{R}^n$. Show that $X$ is connected if and only if $X$ is path-connected.\nlean statement:\n\ncodex statement:\ntheorem connected_of_path_connected:\n  fixes X::\"'a::euclidean_space set\"\n  assumes \"open X\" \"path_connected X\"\n  shows \"connected X\"\nOur comment on the codex statement: <YOU CAN LEAVE YOUR COMMENT HERE>\n *)\ntheorem \"exercise_2021_IIB_3-II-11F-ii\": \n  fixes S::\"'a::euclidean_space set\"\n  assumes \"open S\" \n  shows \"connected S \\<longleftrightarrow> path_connected S\"\n  using assms connected_open_path_connected path_connected_imp_connected by blast\n\n\n(*\nproblem_number:2021_IIB_2-I-1G\nnatural language statement:\nLet $M$ be a module over a Principal Ideal Domain $R$ and let $N$ be a submodule of $M$. Show that $M$ is finitely generated if and only if $N$ and $M / N$ are finitely generated.\nlean statement:\n\ncodex statement:\ntheorem finitely_generated_of_finitely_generated_quotient_and_submodule:\n  fixes R::\"'a::comm_ring_1\" and M::\"'a module\" and N::\"'a module\"\n  assumes \"PID R\" \"submodule N M\"\n  shows \"finitely_generated R M \\<longleftrightarrow> finitely_generated R N \\<and> finitely_generated R (quotient_module.quotient N)\"\nOur comment on the codex statement: <YOU CAN LEAVE YOUR COMMENT HERE>\n *)\ntheorem \"exercise_2021_IIB_2-I-1G\": undefined oops\n\n\n(*\nproblem_number:2021_IIB_3-I-1G-i\nnatural language statement:\nLet $G$ be a finite group, and let $H$ be a proper subgroup of $G$ of index $n$. Show that there is a normal subgroup $K$ of $G$ such that $|G / K|$ divides $n$ ! and $|G / K| \\geqslant n$\nlean statement:\n\ncodex statement:\ntheorem exists_normal_subgroup_of_index_divides_factorial:\n  fixes G::\"('a, 'b) monoid_scheme\" (structure) and H::\"('a, 'b) monoid_scheme\" (structure)\n  assumes \"group G\" \"subgroup H G\" \"finite_index G H\"\n  shows \"\\<exists>K. normal_subgroup K G \\<and> card (G / K) dvd card (H / (\\<one> H)) \\<and> card (G / K) \\<ge> card (H / (\\<one> H))\"\nOur comment on the codex statement: partly OK\n *)\ntheorem (in group) \"exercise_2021_IIB_3-I-1G-i\": \n  assumes \"finite (carrier G)\" \"subgroup H G\" \"H \\<noteq> carrier G\"  \"n = card (rcosets H)\"\n  shows \"\\<exists>K. normal K G \\<and> order (G Mod K) dvd fact n \\<and> order (G Mod K) \\<ge> n\"\n  oops\n\n(*\nproblem_number:2021_IIB_1-II-9G-v\nnatural language statement:\nLet $R$ be the ring of continuous functions $\\mathbb{R}\\to\\mathbb{R}$. Show that $R$ is not Noetherian.\nlean statement:\n\ncodex statement:\ntheorem not_noetherian_of_continuous_functions:\n  fixes R::\"('a::euclidean_space \\<Rightarrow> 'b::euclidean_space) ring\"\n  assumes \"continuous_on UNIV f\" \"continuous_on UNIV g\"\n  shows \"\\<exists>I. ideal I R \\<and> \\<forall>J. ideal J R \\<longrightarrow> J \\<subseteq> I \\<longrightarrow> J = I\"\nOur comment on the codex statement: wrong\n *)\ntheorem \"exercise_2021_IIB_1-II-9G-v\": \n    defines \"CF \\<equiv> \\<lparr>carrier = {f::real\\<Rightarrow>real. continuous_on UNIV f}, mult = (*), one = 1, ring.zero = 0, add = (+)\\<rparr>\"\n    shows \"\\<not> noetherian_ring CF\"\n  oops\n\n(*\nproblem_number:2018_IA_1-I-3E-b\nnatural language statement:\nLet $f: \\mathbb{R} \\rightarrow(0, \\infty)$ be a decreasing function. Let $x_{1}=1$ and $x_{n+1}=x_{n}+f\\left(x_{n}\\right)$. Prove that $x_{n} \\rightarrow \\infty$ as $n \\rightarrow \\infty$.\nlean statement:\n\ncodex statement:\ntheorem tendsto_at_top_of_decreasing_seq:\n  fixes f::\"real \\<Rightarrow> real\"\n  assumes \"decseq f\" \"\\<forall>x. f x > 0\"\n  shows \"(\\<Sum>i<n. f i) \\<longrightarrow> \\<infinity>\"\nOur comment on the codex statement: mostly wrong\n *)\ntheorem (in group) \"exercise_2018_IA_1-I-3E-b\": \n  fixes f::\"real \\<Rightarrow> real\"\n  assumes \"antimono f\" \"\\<forall>x. f x > 0\"\n  defines \"s \\<equiv> rec_nat 1 (\\<lambda>n r. r + f r)\"\n  shows \"filterlim s at_top sequentially\"\n  oops\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/Cambridge-Tripos.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681049901037, "lm_q2_score": 0.8198933381139645, "lm_q1q2_score": 0.7032783549280257}}
{"text": "(*  Title:      HOL/Library/FSet.thy\n    Author:     Ondrej Kuncar, TU Muenchen\n    Author:     Cezary Kaliszyk and Christian Urban\n    Author:     Andrei Popescu, TU Muenchen\n*)\n\nsection \\<open>Type of finite sets defined as a subtype of sets\\<close>\n\ntheory FSet\nimports Main\nbegin\n\nsubsection \\<open>Definition of the type\\<close>\n\ntypedef 'a fset = \"{A :: 'a set. finite A}\"  morphisms fset Abs_fset\nby auto\n\nsetup_lifting type_definition_fset\n\n\nsubsection \\<open>Basic operations and type class instantiations\\<close>\n\n(* FIXME transfer and right_total vs. bi_total *)\ninstantiation fset :: (finite) finite\nbegin\ninstance by (standard; transfer; simp)\nend\n\ninstantiation fset :: (type) \"{bounded_lattice_bot, distrib_lattice, minus}\"\nbegin\n\nlift_definition bot_fset :: \"'a fset\" is \"{}\" parametric empty_transfer by simp\n\nlift_definition less_eq_fset :: \"'a fset \\<Rightarrow> 'a fset \\<Rightarrow> bool\" is subset_eq parametric subset_transfer\n  .\n\ndefinition less_fset :: \"'a fset \\<Rightarrow> 'a fset \\<Rightarrow> bool\" where \"xs < ys \\<equiv> xs \\<le> ys \\<and> xs \\<noteq> (ys::'a fset)\"\n\nlemma less_fset_transfer[transfer_rule]:\n  includes lifting_syntax\n  assumes [transfer_rule]: \"bi_unique A\"\n  shows \"((pcr_fset A) ===> (pcr_fset A) ===> op =) op \\<subset> op <\"\n  unfolding less_fset_def[abs_def] psubset_eq[abs_def] by transfer_prover\n\n\nlift_definition sup_fset :: \"'a fset \\<Rightarrow> 'a fset \\<Rightarrow> 'a fset\" is union parametric union_transfer\n  by simp\n\nlift_definition inf_fset :: \"'a fset \\<Rightarrow> 'a fset \\<Rightarrow> 'a fset\" is inter parametric inter_transfer\n  by simp\n\nlift_definition minus_fset :: \"'a fset \\<Rightarrow> 'a fset \\<Rightarrow> 'a fset\" is minus parametric Diff_transfer\n  by simp\n\ninstance\n  by (standard; transfer; auto)+\n\nend\n\nabbreviation fempty :: \"'a fset\" (\"{||}\") where \"{||} \\<equiv> bot\"\nabbreviation fsubset_eq :: \"'a fset \\<Rightarrow> 'a fset \\<Rightarrow> bool\" (infix \"|\\<subseteq>|\" 50) where \"xs |\\<subseteq>| ys \\<equiv> xs \\<le> ys\"\nabbreviation fsubset :: \"'a fset \\<Rightarrow> 'a fset \\<Rightarrow> bool\" (infix \"|\\<subset>|\" 50) where \"xs |\\<subset>| ys \\<equiv> xs < ys\"\nabbreviation funion :: \"'a fset \\<Rightarrow> 'a fset \\<Rightarrow> 'a fset\" (infixl \"|\\<union>|\" 65) where \"xs |\\<union>| ys \\<equiv> sup xs ys\"\nabbreviation finter :: \"'a fset \\<Rightarrow> 'a fset \\<Rightarrow> 'a fset\" (infixl \"|\\<inter>|\" 65) where \"xs |\\<inter>| ys \\<equiv> inf xs ys\"\nabbreviation fminus :: \"'a fset \\<Rightarrow> 'a fset \\<Rightarrow> 'a fset\" (infixl \"|-|\" 65) where \"xs |-| ys \\<equiv> minus xs ys\"\n\ninstantiation fset :: (equal) equal\nbegin\ndefinition \"HOL.equal A B \\<longleftrightarrow> A |\\<subseteq>| B \\<and> B |\\<subseteq>| A\"\ninstance by intro_classes (auto simp add: equal_fset_def)\nend\n\ninstantiation fset :: (type) conditionally_complete_lattice\nbegin\n\ncontext includes lifting_syntax\nbegin\n\nlemma right_total_Inf_fset_transfer:\n  assumes [transfer_rule]: \"bi_unique A\" and [transfer_rule]: \"right_total A\"\n  shows \"(rel_set (rel_set A) ===> rel_set A)\n    (\\<lambda>S. if finite (\\<Inter>S \\<inter> Collect (Domainp A)) then \\<Inter>S \\<inter> Collect (Domainp A) else {})\n      (\\<lambda>S. if finite (Inf S) then Inf S else {})\"\n    by transfer_prover\n\nlemma Inf_fset_transfer:\n  assumes [transfer_rule]: \"bi_unique A\" and [transfer_rule]: \"bi_total A\"\n  shows \"(rel_set (rel_set A) ===> rel_set A) (\\<lambda>A. if finite (Inf A) then Inf A else {})\n    (\\<lambda>A. if finite (Inf A) then Inf A else {})\"\n  by transfer_prover\n\nlift_definition Inf_fset :: \"'a fset set \\<Rightarrow> 'a fset\" is \"\\<lambda>A. if finite (Inf A) then Inf A else {}\"\nparametric right_total_Inf_fset_transfer Inf_fset_transfer by simp\n\nlemma Sup_fset_transfer:\n  assumes [transfer_rule]: \"bi_unique A\"\n  shows \"(rel_set (rel_set A) ===> rel_set A) (\\<lambda>A. if finite (Sup A) then Sup A else {})\n  (\\<lambda>A. if finite (Sup A) then Sup A else {})\" by transfer_prover\n\nlift_definition Sup_fset :: \"'a fset set \\<Rightarrow> 'a fset\" is \"\\<lambda>A. if finite (Sup A) then Sup A else {}\"\nparametric Sup_fset_transfer by simp\n\nlemma finite_Sup: \"\\<exists>z. finite z \\<and> (\\<forall>a. a \\<in> X \\<longrightarrow> a \\<le> z) \\<Longrightarrow> finite (Sup X)\"\nby (auto intro: finite_subset)\n\nlemma transfer_bdd_below[transfer_rule]: \"(rel_set (pcr_fset op =) ===> op =) bdd_below bdd_below\"\n  by auto\n\nend\n\ninstance\nproof\n  fix x z :: \"'a fset\"\n  fix X :: \"'a fset set\"\n  {\n    assume \"x \\<in> X\" \"bdd_below X\"\n    then show \"Inf X |\\<subseteq>| x\" by transfer auto\n  next\n    assume \"X \\<noteq> {}\" \"(\\<And>x. x \\<in> X \\<Longrightarrow> z |\\<subseteq>| x)\"\n    then show \"z |\\<subseteq>| Inf X\" by transfer (clarsimp, blast)\n  next\n    assume \"x \\<in> X\" \"bdd_above X\"\n    then obtain z where \"x \\<in> X\" \"(\\<And>x. x \\<in> X \\<Longrightarrow> x |\\<subseteq>| z)\"\n      by (auto simp: bdd_above_def)\n    then show \"x |\\<subseteq>| Sup X\"\n      by transfer (auto intro!: finite_Sup)\n  next\n    assume \"X \\<noteq> {}\" \"(\\<And>x. x \\<in> X \\<Longrightarrow> x |\\<subseteq>| z)\"\n    then show \"Sup X |\\<subseteq>| z\" by transfer (clarsimp, blast)\n  }\nqed\nend\n\ninstantiation fset :: (finite) complete_lattice\nbegin\n\nlift_definition top_fset :: \"'a fset\" is UNIV parametric right_total_UNIV_transfer UNIV_transfer\n  by simp\n\ninstance\n  by (standard; transfer; auto)\n\nend\n\ninstantiation fset :: (finite) complete_boolean_algebra\nbegin\n\nlift_definition uminus_fset :: \"'a fset \\<Rightarrow> 'a fset\" is uminus\n  parametric right_total_Compl_transfer Compl_transfer by simp\n\ninstance\n  by (standard; transfer) (simp_all add: Diff_eq)\n\nend\n\nabbreviation fUNIV :: \"'a::finite fset\" where \"fUNIV \\<equiv> top\"\nabbreviation fuminus :: \"'a::finite fset \\<Rightarrow> 'a fset\" (\"|-| _\" [81] 80) where \"|-| x \\<equiv> uminus x\"\n\ndeclare top_fset.rep_eq[simp]\n\n\nsubsection \\<open>Other operations\\<close>\n\nlift_definition finsert :: \"'a \\<Rightarrow> 'a fset \\<Rightarrow> 'a fset\" is insert parametric Lifting_Set.insert_transfer\n  by simp\n\nsyntax\n  \"_insert_fset\"     :: \"args => 'a fset\"  (\"{|(_)|}\")\n\ntranslations\n  \"{|x, xs|}\" == \"CONST finsert x {|xs|}\"\n  \"{|x|}\"     == \"CONST finsert x {||}\"\n\nlift_definition fmember :: \"'a \\<Rightarrow> 'a fset \\<Rightarrow> bool\" (infix \"|\\<in>|\" 50) is Set.member\n  parametric member_transfer .\n\nabbreviation notin_fset :: \"'a \\<Rightarrow> 'a fset \\<Rightarrow> bool\" (infix \"|\\<notin>|\" 50) where \"x |\\<notin>| S \\<equiv> \\<not> (x |\\<in>| S)\"\n\ncontext includes lifting_syntax\nbegin\n\nlift_definition ffilter :: \"('a \\<Rightarrow> bool) \\<Rightarrow> 'a fset \\<Rightarrow> 'a fset\" is Set.filter\n  parametric Lifting_Set.filter_transfer unfolding Set.filter_def by simp\n\nlift_definition fPow :: \"'a fset \\<Rightarrow> 'a fset fset\" is Pow parametric Pow_transfer\nby (simp add: finite_subset)\n\nlift_definition fcard :: \"'a fset \\<Rightarrow> nat\" is card parametric card_transfer .\n\nlift_definition fimage :: \"('a \\<Rightarrow> 'b) \\<Rightarrow> 'a fset \\<Rightarrow> 'b fset\" (infixr \"|`|\" 90) is image\n  parametric image_transfer by simp\n\nlift_definition fthe_elem :: \"'a fset \\<Rightarrow> 'a\" is the_elem .\n\nlift_definition fbind :: \"'a fset \\<Rightarrow> ('a \\<Rightarrow> 'b fset) \\<Rightarrow> 'b fset\" is Set.bind parametric bind_transfer\nby (simp add: Set.bind_def)\n\nlift_definition ffUnion :: \"'a fset fset \\<Rightarrow> 'a fset\" is Union parametric Union_transfer by simp\n\nlift_definition fBall :: \"'a fset \\<Rightarrow> ('a \\<Rightarrow> bool) \\<Rightarrow> bool\" is Ball parametric Ball_transfer .\nlift_definition fBex :: \"'a fset \\<Rightarrow> ('a \\<Rightarrow> bool) \\<Rightarrow> bool\" is Bex parametric Bex_transfer .\n\nlift_definition ffold :: \"('a \\<Rightarrow> 'b \\<Rightarrow> 'b) \\<Rightarrow> 'b \\<Rightarrow> 'a fset \\<Rightarrow> 'b\" is Finite_Set.fold .\n\nlift_definition fset_of_list :: \"'a list \\<Rightarrow> 'a fset\" is set by (rule finite_set)\n\n\nsubsection \\<open>Transferred lemmas from Set.thy\\<close>\n\nlemmas fset_eqI = set_eqI[Transfer.transferred]\nlemmas fset_eq_iff[no_atp] = set_eq_iff[Transfer.transferred]\nlemmas fBallI[intro!] = ballI[Transfer.transferred]\nlemmas fbspec[dest?] = bspec[Transfer.transferred]\nlemmas fBallE[elim] = ballE[Transfer.transferred]\nlemmas fBexI[intro] = bexI[Transfer.transferred]\nlemmas rev_fBexI[intro?] = rev_bexI[Transfer.transferred]\nlemmas fBexCI = bexCI[Transfer.transferred]\nlemmas fBexE[elim!] = bexE[Transfer.transferred]\nlemmas fBall_triv[simp] = ball_triv[Transfer.transferred]\nlemmas fBex_triv[simp] = bex_triv[Transfer.transferred]\nlemmas fBex_triv_one_point1[simp] = bex_triv_one_point1[Transfer.transferred]\nlemmas fBex_triv_one_point2[simp] = bex_triv_one_point2[Transfer.transferred]\nlemmas fBex_one_point1[simp] = bex_one_point1[Transfer.transferred]\nlemmas fBex_one_point2[simp] = bex_one_point2[Transfer.transferred]\nlemmas fBall_one_point1[simp] = ball_one_point1[Transfer.transferred]\nlemmas fBall_one_point2[simp] = ball_one_point2[Transfer.transferred]\nlemmas fBall_conj_distrib = ball_conj_distrib[Transfer.transferred]\nlemmas fBex_disj_distrib = bex_disj_distrib[Transfer.transferred]\nlemmas fBall_cong = ball_cong[Transfer.transferred]\nlemmas fBex_cong = bex_cong[Transfer.transferred]\nlemmas fsubsetI[intro!] = subsetI[Transfer.transferred]\nlemmas fsubsetD[elim, intro?] = subsetD[Transfer.transferred]\nlemmas rev_fsubsetD[no_atp,intro?] = rev_subsetD[Transfer.transferred]\nlemmas fsubsetCE[no_atp,elim] = subsetCE[Transfer.transferred]\nlemmas fsubset_eq[no_atp] = subset_eq[Transfer.transferred]\nlemmas contra_fsubsetD[no_atp] = contra_subsetD[Transfer.transferred]\nlemmas fsubset_refl = subset_refl[Transfer.transferred]\nlemmas fsubset_trans = subset_trans[Transfer.transferred]\nlemmas fset_rev_mp = set_rev_mp[Transfer.transferred]\nlemmas fset_mp = set_mp[Transfer.transferred]\nlemmas fsubset_not_fsubset_eq[code] = subset_not_subset_eq[Transfer.transferred]\nlemmas eq_fmem_trans = eq_mem_trans[Transfer.transferred]\nlemmas fsubset_antisym[intro!] = subset_antisym[Transfer.transferred]\nlemmas fequalityD1 = equalityD1[Transfer.transferred]\nlemmas fequalityD2 = equalityD2[Transfer.transferred]\nlemmas fequalityE = equalityE[Transfer.transferred]\nlemmas fequalityCE[elim] = equalityCE[Transfer.transferred]\nlemmas eqfset_imp_iff = eqset_imp_iff[Transfer.transferred]\nlemmas eqfelem_imp_iff = eqelem_imp_iff[Transfer.transferred]\nlemmas fempty_iff[simp] = empty_iff[Transfer.transferred]\nlemmas fempty_fsubsetI[iff] = empty_subsetI[Transfer.transferred]\nlemmas equalsffemptyI = equals0I[Transfer.transferred]\nlemmas equalsffemptyD = equals0D[Transfer.transferred]\nlemmas fBall_fempty[simp] = ball_empty[Transfer.transferred]\nlemmas fBex_fempty[simp] = bex_empty[Transfer.transferred]\nlemmas fPow_iff[iff] = Pow_iff[Transfer.transferred]\nlemmas fPowI = PowI[Transfer.transferred]\nlemmas fPowD = PowD[Transfer.transferred]\nlemmas fPow_bottom = Pow_bottom[Transfer.transferred]\nlemmas fPow_top = Pow_top[Transfer.transferred]\nlemmas fPow_not_fempty = Pow_not_empty[Transfer.transferred]\nlemmas finter_iff[simp] = Int_iff[Transfer.transferred]\nlemmas finterI[intro!] = IntI[Transfer.transferred]\nlemmas finterD1 = IntD1[Transfer.transferred]\nlemmas finterD2 = IntD2[Transfer.transferred]\nlemmas finterE[elim!] = IntE[Transfer.transferred]\nlemmas funion_iff[simp] = Un_iff[Transfer.transferred]\nlemmas funionI1[elim?] = UnI1[Transfer.transferred]\nlemmas funionI2[elim?] = UnI2[Transfer.transferred]\nlemmas funionCI[intro!] = UnCI[Transfer.transferred]\nlemmas funionE[elim!] = UnE[Transfer.transferred]\nlemmas fminus_iff[simp] = Diff_iff[Transfer.transferred]\nlemmas fminusI[intro!] = DiffI[Transfer.transferred]\nlemmas fminusD1 = DiffD1[Transfer.transferred]\nlemmas fminusD2 = DiffD2[Transfer.transferred]\nlemmas fminusE[elim!] = DiffE[Transfer.transferred]\nlemmas finsert_iff[simp] = insert_iff[Transfer.transferred]\nlemmas finsertI1 = insertI1[Transfer.transferred]\nlemmas finsertI2 = insertI2[Transfer.transferred]\nlemmas finsertE[elim!] = insertE[Transfer.transferred]\nlemmas finsertCI[intro!] = insertCI[Transfer.transferred]\nlemmas fsubset_finsert_iff = subset_insert_iff[Transfer.transferred]\nlemmas finsert_ident = insert_ident[Transfer.transferred]\nlemmas fsingletonI[intro!,no_atp] = singletonI[Transfer.transferred]\nlemmas fsingletonD[dest!,no_atp] = singletonD[Transfer.transferred]\nlemmas fsingleton_iff = singleton_iff[Transfer.transferred]\nlemmas fsingleton_inject[dest!] = singleton_inject[Transfer.transferred]\nlemmas fsingleton_finsert_inj_eq[iff,no_atp] = singleton_insert_inj_eq[Transfer.transferred]\nlemmas fsingleton_finsert_inj_eq'[iff,no_atp] = singleton_insert_inj_eq'[Transfer.transferred]\nlemmas fsubset_fsingletonD = subset_singletonD[Transfer.transferred]\nlemmas fminus_single_finsert = Diff_single_insert[Transfer.transferred]\nlemmas fdoubleton_eq_iff = doubleton_eq_iff[Transfer.transferred]\nlemmas funion_fsingleton_iff = Un_singleton_iff[Transfer.transferred]\nlemmas fsingleton_funion_iff = singleton_Un_iff[Transfer.transferred]\nlemmas fimage_eqI[simp, intro] = image_eqI[Transfer.transferred]\nlemmas fimageI = imageI[Transfer.transferred]\nlemmas rev_fimage_eqI = rev_image_eqI[Transfer.transferred]\nlemmas fimageE[elim!] = imageE[Transfer.transferred]\nlemmas Compr_fimage_eq = Compr_image_eq[Transfer.transferred]\nlemmas fimage_funion = image_Un[Transfer.transferred]\nlemmas fimage_iff = image_iff[Transfer.transferred]\nlemmas fimage_fsubset_iff[no_atp] = image_subset_iff[Transfer.transferred]\nlemmas fimage_fsubsetI = image_subsetI[Transfer.transferred]\nlemmas fimage_ident[simp] = image_ident[Transfer.transferred]\nlemmas if_split_fmem1 = if_split_mem1[Transfer.transferred]\nlemmas if_split_fmem2 = if_split_mem2[Transfer.transferred]\nlemmas pfsubsetI[intro!,no_atp] = psubsetI[Transfer.transferred]\nlemmas pfsubsetE[elim!,no_atp] = psubsetE[Transfer.transferred]\nlemmas pfsubset_finsert_iff = psubset_insert_iff[Transfer.transferred]\nlemmas pfsubset_eq = psubset_eq[Transfer.transferred]\nlemmas pfsubset_imp_fsubset = psubset_imp_subset[Transfer.transferred]\nlemmas pfsubset_trans = psubset_trans[Transfer.transferred]\nlemmas pfsubsetD = psubsetD[Transfer.transferred]\nlemmas pfsubset_fsubset_trans = psubset_subset_trans[Transfer.transferred]\nlemmas fsubset_pfsubset_trans = subset_psubset_trans[Transfer.transferred]\nlemmas pfsubset_imp_ex_fmem = psubset_imp_ex_mem[Transfer.transferred]\nlemmas fimage_fPow_mono = image_Pow_mono[Transfer.transferred]\nlemmas fimage_fPow_surj = image_Pow_surj[Transfer.transferred]\nlemmas fsubset_finsertI = subset_insertI[Transfer.transferred]\nlemmas fsubset_finsertI2 = subset_insertI2[Transfer.transferred]\nlemmas fsubset_finsert = subset_insert[Transfer.transferred]\nlemmas funion_upper1 = Un_upper1[Transfer.transferred]\nlemmas funion_upper2 = Un_upper2[Transfer.transferred]\nlemmas funion_least = Un_least[Transfer.transferred]\nlemmas finter_lower1 = Int_lower1[Transfer.transferred]\nlemmas finter_lower2 = Int_lower2[Transfer.transferred]\nlemmas finter_greatest = Int_greatest[Transfer.transferred]\nlemmas fminus_fsubset = Diff_subset[Transfer.transferred]\nlemmas fminus_fsubset_conv = Diff_subset_conv[Transfer.transferred]\nlemmas fsubset_fempty[simp] = subset_empty[Transfer.transferred]\nlemmas not_pfsubset_fempty[iff] = not_psubset_empty[Transfer.transferred]\nlemmas finsert_is_funion = insert_is_Un[Transfer.transferred]\nlemmas finsert_not_fempty[simp] = insert_not_empty[Transfer.transferred]\nlemmas fempty_not_finsert = empty_not_insert[Transfer.transferred]\nlemmas finsert_absorb = insert_absorb[Transfer.transferred]\nlemmas finsert_absorb2[simp] = insert_absorb2[Transfer.transferred]\nlemmas finsert_commute = insert_commute[Transfer.transferred]\nlemmas finsert_fsubset[simp] = insert_subset[Transfer.transferred]\nlemmas finsert_inter_finsert[simp] = insert_inter_insert[Transfer.transferred]\nlemmas finsert_disjoint[simp,no_atp] = insert_disjoint[Transfer.transferred]\nlemmas disjoint_finsert[simp,no_atp] = disjoint_insert[Transfer.transferred]\nlemmas fimage_fempty[simp] = image_empty[Transfer.transferred]\nlemmas fimage_finsert[simp] = image_insert[Transfer.transferred]\nlemmas fimage_constant = image_constant[Transfer.transferred]\nlemmas fimage_constant_conv = image_constant_conv[Transfer.transferred]\nlemmas fimage_fimage = image_image[Transfer.transferred]\nlemmas finsert_fimage[simp] = insert_image[Transfer.transferred]\nlemmas fimage_is_fempty[iff] = image_is_empty[Transfer.transferred]\nlemmas fempty_is_fimage[iff] = empty_is_image[Transfer.transferred]\nlemmas fimage_cong = image_cong[Transfer.transferred]\nlemmas fimage_finter_fsubset = image_Int_subset[Transfer.transferred]\nlemmas fimage_fminus_fsubset = image_diff_subset[Transfer.transferred]\nlemmas finter_absorb = Int_absorb[Transfer.transferred]\nlemmas finter_left_absorb = Int_left_absorb[Transfer.transferred]\nlemmas finter_commute = Int_commute[Transfer.transferred]\nlemmas finter_left_commute = Int_left_commute[Transfer.transferred]\nlemmas finter_assoc = Int_assoc[Transfer.transferred]\nlemmas finter_ac = Int_ac[Transfer.transferred]\nlemmas finter_absorb1 = Int_absorb1[Transfer.transferred]\nlemmas finter_absorb2 = Int_absorb2[Transfer.transferred]\nlemmas finter_fempty_left = Int_empty_left[Transfer.transferred]\nlemmas finter_fempty_right = Int_empty_right[Transfer.transferred]\nlemmas disjoint_iff_fnot_equal = disjoint_iff_not_equal[Transfer.transferred]\nlemmas finter_funion_distrib = Int_Un_distrib[Transfer.transferred]\nlemmas finter_funion_distrib2 = Int_Un_distrib2[Transfer.transferred]\nlemmas finter_fsubset_iff[no_atp, simp] = Int_subset_iff[Transfer.transferred]\nlemmas funion_absorb = Un_absorb[Transfer.transferred]\nlemmas funion_left_absorb = Un_left_absorb[Transfer.transferred]\nlemmas funion_commute = Un_commute[Transfer.transferred]\nlemmas funion_left_commute = Un_left_commute[Transfer.transferred]\nlemmas funion_assoc = Un_assoc[Transfer.transferred]\nlemmas funion_ac = Un_ac[Transfer.transferred]\nlemmas funion_absorb1 = Un_absorb1[Transfer.transferred]\nlemmas funion_absorb2 = Un_absorb2[Transfer.transferred]\nlemmas funion_fempty_left = Un_empty_left[Transfer.transferred]\nlemmas funion_fempty_right = Un_empty_right[Transfer.transferred]\nlemmas funion_finsert_left[simp] = Un_insert_left[Transfer.transferred]\nlemmas funion_finsert_right[simp] = Un_insert_right[Transfer.transferred]\nlemmas finter_finsert_left = Int_insert_left[Transfer.transferred]\nlemmas finter_finsert_left_ifffempty[simp] = Int_insert_left_if0[Transfer.transferred]\nlemmas finter_finsert_left_if1[simp] = Int_insert_left_if1[Transfer.transferred]\nlemmas finter_finsert_right = Int_insert_right[Transfer.transferred]\nlemmas finter_finsert_right_ifffempty[simp] = Int_insert_right_if0[Transfer.transferred]\nlemmas finter_finsert_right_if1[simp] = Int_insert_right_if1[Transfer.transferred]\nlemmas funion_finter_distrib = Un_Int_distrib[Transfer.transferred]\nlemmas funion_finter_distrib2 = Un_Int_distrib2[Transfer.transferred]\nlemmas funion_finter_crazy = Un_Int_crazy[Transfer.transferred]\nlemmas fsubset_funion_eq = subset_Un_eq[Transfer.transferred]\nlemmas funion_fempty[iff] = Un_empty[Transfer.transferred]\nlemmas funion_fsubset_iff[no_atp, simp] = Un_subset_iff[Transfer.transferred]\nlemmas funion_fminus_finter = Un_Diff_Int[Transfer.transferred]\nlemmas fminus_finter2 = Diff_Int2[Transfer.transferred]\nlemmas funion_finter_assoc_eq = Un_Int_assoc_eq[Transfer.transferred]\nlemmas fBall_funion = ball_Un[Transfer.transferred]\nlemmas fBex_funion = bex_Un[Transfer.transferred]\nlemmas fminus_eq_fempty_iff[simp,no_atp] = Diff_eq_empty_iff[Transfer.transferred]\nlemmas fminus_cancel[simp] = Diff_cancel[Transfer.transferred]\nlemmas fminus_idemp[simp] = Diff_idemp[Transfer.transferred]\nlemmas fminus_triv = Diff_triv[Transfer.transferred]\nlemmas fempty_fminus[simp] = empty_Diff[Transfer.transferred]\nlemmas fminus_fempty[simp] = Diff_empty[Transfer.transferred]\nlemmas fminus_finsertffempty[simp,no_atp] = Diff_insert0[Transfer.transferred]\nlemmas fminus_finsert = Diff_insert[Transfer.transferred]\nlemmas fminus_finsert2 = Diff_insert2[Transfer.transferred]\nlemmas finsert_fminus_if = insert_Diff_if[Transfer.transferred]\nlemmas finsert_fminus1[simp] = insert_Diff1[Transfer.transferred]\nlemmas finsert_fminus_single[simp] = insert_Diff_single[Transfer.transferred]\nlemmas finsert_fminus = insert_Diff[Transfer.transferred]\nlemmas fminus_finsert_absorb = Diff_insert_absorb[Transfer.transferred]\nlemmas fminus_disjoint[simp] = Diff_disjoint[Transfer.transferred]\nlemmas fminus_partition = Diff_partition[Transfer.transferred]\nlemmas double_fminus = double_diff[Transfer.transferred]\nlemmas funion_fminus_cancel[simp] = Un_Diff_cancel[Transfer.transferred]\nlemmas funion_fminus_cancel2[simp] = Un_Diff_cancel2[Transfer.transferred]\nlemmas fminus_funion = Diff_Un[Transfer.transferred]\nlemmas fminus_finter = Diff_Int[Transfer.transferred]\nlemmas funion_fminus = Un_Diff[Transfer.transferred]\nlemmas finter_fminus = Int_Diff[Transfer.transferred]\nlemmas fminus_finter_distrib = Diff_Int_distrib[Transfer.transferred]\nlemmas fminus_finter_distrib2 = Diff_Int_distrib2[Transfer.transferred]\nlemmas fUNIV_bool[no_atp] = UNIV_bool[Transfer.transferred]\nlemmas fPow_fempty[simp] = Pow_empty[Transfer.transferred]\nlemmas fPow_finsert = Pow_insert[Transfer.transferred]\nlemmas funion_fPow_fsubset = Un_Pow_subset[Transfer.transferred]\nlemmas fPow_finter_eq[simp] = Pow_Int_eq[Transfer.transferred]\nlemmas fset_eq_fsubset = set_eq_subset[Transfer.transferred]\nlemmas fsubset_iff[no_atp] = subset_iff[Transfer.transferred]\nlemmas fsubset_iff_pfsubset_eq = subset_iff_psubset_eq[Transfer.transferred]\nlemmas all_not_fin_conv[simp] = all_not_in_conv[Transfer.transferred]\nlemmas ex_fin_conv = ex_in_conv[Transfer.transferred]\nlemmas fimage_mono = image_mono[Transfer.transferred]\nlemmas fPow_mono = Pow_mono[Transfer.transferred]\nlemmas finsert_mono = insert_mono[Transfer.transferred]\nlemmas funion_mono = Un_mono[Transfer.transferred]\nlemmas finter_mono = Int_mono[Transfer.transferred]\nlemmas fminus_mono = Diff_mono[Transfer.transferred]\nlemmas fin_mono = in_mono[Transfer.transferred]\nlemmas fthe_felem_eq[simp] = the_elem_eq[Transfer.transferred]\nlemmas fLeast_mono = Least_mono[Transfer.transferred]\nlemmas fbind_fbind = bind_bind[Transfer.transferred]\nlemmas fempty_fbind[simp] = empty_bind[Transfer.transferred]\nlemmas nonfempty_fbind_const = nonempty_bind_const[Transfer.transferred]\nlemmas fbind_const = bind_const[Transfer.transferred]\nlemmas ffmember_filter[simp] = member_filter[Transfer.transferred]\nlemmas fequalityI = equalityI[Transfer.transferred]\nlemmas fset_of_list_simps[simp] = set_simps[Transfer.transferred]\nlemmas fset_of_list_append[simp] = set_append[Transfer.transferred]\nlemmas fset_of_list_rev[simp] = set_rev[Transfer.transferred]\nlemmas fset_of_list_map[simp] = set_map[Transfer.transferred]\n\n\nsubsection \\<open>Additional lemmas\\<close>\n\nsubsubsection \\<open>\\<open>fsingleton\\<close>\\<close>\n\nlemmas fsingletonE = fsingletonD [elim_format]\n\n\nsubsubsection \\<open>\\<open>femepty\\<close>\\<close>\n\nlemma fempty_ffilter[simp]: \"ffilter (\\<lambda>_. False) A = {||}\"\nby transfer auto\n\n(* FIXME, transferred doesn't work here *)\nlemma femptyE [elim!]: \"a |\\<in>| {||} \\<Longrightarrow> P\"\n  by simp\n\n\nsubsubsection \\<open>\\<open>fset\\<close>\\<close>\n\nlemmas fset_simps[simp] = bot_fset.rep_eq finsert.rep_eq\n\nlemma finite_fset [simp]:\n  shows \"finite (fset S)\"\n  by transfer simp\n\nlemmas fset_cong = fset_inject\n\nlemma filter_fset [simp]:\n  shows \"fset (ffilter P xs) = Collect P \\<inter> fset xs\"\n  by transfer auto\n\nlemma notin_fset: \"x |\\<notin>| S \\<longleftrightarrow> x \\<notin> fset S\" by (simp add: fmember.rep_eq)\n\nlemmas inter_fset[simp] = inf_fset.rep_eq\n\nlemmas union_fset[simp] = sup_fset.rep_eq\n\nlemmas minus_fset[simp] = minus_fset.rep_eq\n\n\nsubsubsection \\<open>\\<open>ffilter\\<close>\\<close>\n\nlemma subset_ffilter:\n  \"ffilter P A |\\<subseteq>| ffilter Q A = (\\<forall> x. x |\\<in>| A \\<longrightarrow> P x \\<longrightarrow> Q x)\"\n  by transfer auto\n\nlemma eq_ffilter:\n  \"(ffilter P A = ffilter Q A) = (\\<forall>x. x |\\<in>| A \\<longrightarrow> P x = Q x)\"\n  by transfer auto\n\nlemma pfsubset_ffilter:\n  \"(\\<And>x. x |\\<in>| A \\<Longrightarrow> P x \\<Longrightarrow> Q x) \\<Longrightarrow> (x |\\<in>| A & \\<not> P x & Q x) \\<Longrightarrow>\n    ffilter P A |\\<subset>| ffilter Q A\"\n  unfolding less_fset_def by (auto simp add: subset_ffilter eq_ffilter)\n\n\nsubsubsection \\<open>\\<open>fset_of_list\\<close>\\<close>\n\nlemma fset_of_list_filter[simp]:\n  \"fset_of_list (filter P xs) = ffilter P (fset_of_list xs)\"\n  by transfer (auto simp: Set.filter_def)\n\nlemma fset_of_list_subset[intro]:\n  \"set xs \\<subseteq> set ys \\<Longrightarrow> fset_of_list xs |\\<subseteq>| fset_of_list ys\"\n  by transfer simp\n\nlemma fset_of_list_elem: \"(x |\\<in>| fset_of_list xs) \\<longleftrightarrow> (x \\<in> set xs)\"\n  by transfer simp\n\n\nsubsubsection \\<open>\\<open>finsert\\<close>\\<close>\n\n(* FIXME, transferred doesn't work here *)\nlemma set_finsert:\n  assumes \"x |\\<in>| A\"\n  obtains B where \"A = finsert x B\" and \"x |\\<notin>| B\"\nusing assms by transfer (metis Set.set_insert finite_insert)\n\nlemma mk_disjoint_finsert: \"a |\\<in>| A \\<Longrightarrow> \\<exists>B. A = finsert a B \\<and> a |\\<notin>| B\"\n  by (rule exI [where x = \"A |-| {|a|}\"]) blast\n\n\nsubsubsection \\<open>\\<open>fimage\\<close>\\<close>\n\nlemma subset_fimage_iff: \"(B |\\<subseteq>| f|`|A) = (\\<exists> AA. AA |\\<subseteq>| A \\<and> B = f|`|AA)\"\nby transfer (metis mem_Collect_eq rev_finite_subset subset_image_iff)\n\n\nsubsubsection \\<open>bounded quantification\\<close>\n\nlemma bex_simps [simp, no_atp]:\n  \"\\<And>A P Q. fBex A (\\<lambda>x. P x \\<and> Q) = (fBex A P \\<and> Q)\"\n  \"\\<And>A P Q. fBex A (\\<lambda>x. P \\<and> Q x) = (P \\<and> fBex A Q)\"\n  \"\\<And>P. fBex {||} P = False\"\n  \"\\<And>a B P. fBex (finsert a B) P = (P a \\<or> fBex B P)\"\n  \"\\<And>A P f. fBex (f |`| A) P = fBex A (\\<lambda>x. P (f x))\"\n  \"\\<And>A P. (\\<not> fBex A P) = fBall A (\\<lambda>x. \\<not> P x)\"\nby auto\n\nlemma ball_simps [simp, no_atp]:\n  \"\\<And>A P Q. fBall A (\\<lambda>x. P x \\<or> Q) = (fBall A P \\<or> Q)\"\n  \"\\<And>A P Q. fBall A (\\<lambda>x. P \\<or> Q x) = (P \\<or> fBall A Q)\"\n  \"\\<And>A P Q. fBall A (\\<lambda>x. P \\<longrightarrow> Q x) = (P \\<longrightarrow> fBall A Q)\"\n  \"\\<And>A P Q. fBall A (\\<lambda>x. P x \\<longrightarrow> Q) = (fBex A P \\<longrightarrow> Q)\"\n  \"\\<And>P. fBall {||} P = True\"\n  \"\\<And>a B P. fBall (finsert a B) P = (P a \\<and> fBall B P)\"\n  \"\\<And>A P f. fBall (f |`| A) P = fBall A (\\<lambda>x. P (f x))\"\n  \"\\<And>A P. (\\<not> fBall A P) = fBex A (\\<lambda>x. \\<not> P x)\"\nby auto\n\nlemma atomize_fBall:\n    \"(\\<And>x. x |\\<in>| A ==> P x) == Trueprop (fBall A (\\<lambda>x. P x))\"\napply (simp only: atomize_all atomize_imp)\napply (rule equal_intr_rule)\n  by (transfer, simp)+\n\nlemma fBall_mono[mono]: \"P \\<le> Q \\<Longrightarrow> fBall S P \\<le> fBall S Q\"\nby auto\n\n\nend\n\n\nsubsubsection \\<open>\\<open>fcard\\<close>\\<close>\n\n(* FIXME: improve transferred to handle bounded meta quantification *)\n\nlemma fcard_fempty:\n  \"fcard {||} = 0\"\n  by transfer (rule card_empty)\n\nlemma fcard_finsert_disjoint:\n  \"x |\\<notin>| A \\<Longrightarrow> fcard (finsert x A) = Suc (fcard A)\"\n  by transfer (rule card_insert_disjoint)\n\nlemma fcard_finsert_if:\n  \"fcard (finsert x A) = (if x |\\<in>| A then fcard A else Suc (fcard A))\"\n  by transfer (rule card_insert_if)\n\nlemma card_0_eq [simp, no_atp]:\n  \"fcard A = 0 \\<longleftrightarrow> A = {||}\"\n  by transfer (rule card_0_eq)\n\nlemma fcard_Suc_fminus1:\n  \"x |\\<in>| A \\<Longrightarrow> Suc (fcard (A |-| {|x|})) = fcard A\"\n  by transfer (rule card_Suc_Diff1)\n\nlemma fcard_fminus_fsingleton:\n  \"x |\\<in>| A \\<Longrightarrow> fcard (A |-| {|x|}) = fcard A - 1\"\n  by transfer (rule card_Diff_singleton)\n\nlemma fcard_fminus_fsingleton_if:\n  \"fcard (A |-| {|x|}) = (if x |\\<in>| A then fcard A - 1 else fcard A)\"\n  by transfer (rule card_Diff_singleton_if)\n\nlemma fcard_fminus_finsert[simp]:\n  assumes \"a |\\<in>| A\" and \"a |\\<notin>| B\"\n  shows \"fcard (A |-| finsert a B) = fcard (A |-| B) - 1\"\nusing assms by transfer (rule card_Diff_insert)\n\nlemma fcard_finsert: \"fcard (finsert x A) = Suc (fcard (A |-| {|x|}))\"\nby transfer (rule card_insert)\n\nlemma fcard_finsert_le: \"fcard A \\<le> fcard (finsert x A)\"\nby transfer (rule card_insert_le)\n\nlemma fcard_mono:\n  \"A |\\<subseteq>| B \\<Longrightarrow> fcard A \\<le> fcard B\"\nby transfer (rule card_mono)\n\nlemma fcard_seteq: \"A |\\<subseteq>| B \\<Longrightarrow> fcard B \\<le> fcard A \\<Longrightarrow> A = B\"\nby transfer (rule card_seteq)\n\nlemma pfsubset_fcard_mono: \"A |\\<subset>| B \\<Longrightarrow> fcard A < fcard B\"\nby transfer (rule psubset_card_mono)\n\nlemma fcard_funion_finter:\n  \"fcard A + fcard B = fcard (A |\\<union>| B) + fcard (A |\\<inter>| B)\"\nby transfer (rule card_Un_Int)\n\nlemma fcard_funion_disjoint:\n  \"A |\\<inter>| B = {||} \\<Longrightarrow> fcard (A |\\<union>| B) = fcard A + fcard B\"\nby transfer (rule card_Un_disjoint)\n\nlemma fcard_funion_fsubset:\n  \"B |\\<subseteq>| A \\<Longrightarrow> fcard (A |-| B) = fcard A - fcard B\"\nby transfer (rule card_Diff_subset)\n\nlemma diff_fcard_le_fcard_fminus:\n  \"fcard A - fcard B \\<le> fcard(A |-| B)\"\nby transfer (rule diff_card_le_card_Diff)\n\nlemma fcard_fminus1_less: \"x |\\<in>| A \\<Longrightarrow> fcard (A |-| {|x|}) < fcard A\"\nby transfer (rule card_Diff1_less)\n\nlemma fcard_fminus2_less:\n  \"x |\\<in>| A \\<Longrightarrow> y |\\<in>| A \\<Longrightarrow> fcard (A |-| {|x|} |-| {|y|}) < fcard A\"\nby transfer (rule card_Diff2_less)\n\nlemma fcard_fminus1_le: \"fcard (A |-| {|x|}) \\<le> fcard A\"\nby transfer (rule card_Diff1_le)\n\nlemma fcard_pfsubset: \"A |\\<subseteq>| B \\<Longrightarrow> fcard A < fcard B \\<Longrightarrow> A < B\"\nby transfer (rule card_psubset)\n\n\nsubsubsection \\<open>\\<open>ffold\\<close>\\<close>\n\n(* FIXME: improve transferred to handle bounded meta quantification *)\n\ncontext comp_fun_commute\nbegin\n  lemmas ffold_empty[simp] = fold_empty[Transfer.transferred]\n\n  lemma ffold_finsert [simp]:\n    assumes \"x |\\<notin>| A\"\n    shows \"ffold f z (finsert x A) = f x (ffold f z A)\"\n    using assms by (transfer fixing: f) (rule fold_insert)\n\n  lemma ffold_fun_left_comm:\n    \"f x (ffold f z A) = ffold f (f x z) A\"\n    by (transfer fixing: f) (rule fold_fun_left_comm)\n\n  lemma ffold_finsert2:\n    \"x |\\<notin>| A \\<Longrightarrow> ffold f z (finsert x A) = ffold f (f x z) A\"\n    by (transfer fixing: f) (rule fold_insert2)\n\n  lemma ffold_rec:\n    assumes \"x |\\<in>| A\"\n    shows \"ffold f z A = f x (ffold f z (A |-| {|x|}))\"\n    using assms by (transfer fixing: f) (rule fold_rec)\n\n  lemma ffold_finsert_fremove:\n    \"ffold f z (finsert x A) = f x (ffold f z (A |-| {|x|}))\"\n     by (transfer fixing: f) (rule fold_insert_remove)\nend\n\nlemma ffold_fimage:\n  assumes \"inj_on g (fset A)\"\n  shows \"ffold f z (g |`| A) = ffold (f \\<circ> g) z A\"\nusing assms by transfer' (rule fold_image)\n\nlemma ffold_cong:\n  assumes \"comp_fun_commute f\" \"comp_fun_commute g\"\n  \"\\<And>x. x |\\<in>| A \\<Longrightarrow> f x = g x\"\n    and \"s = t\" and \"A = B\"\n  shows \"ffold f s A = ffold g t B\"\nusing assms by transfer (metis Finite_Set.fold_cong)\n\ncontext comp_fun_idem\nbegin\n\n  lemma ffold_finsert_idem:\n    \"ffold f z (finsert x A) = f x (ffold f z A)\"\n    by (transfer fixing: f) (rule fold_insert_idem)\n\n  declare ffold_finsert [simp del] ffold_finsert_idem [simp]\n\n  lemma ffold_finsert_idem2:\n    \"ffold f z (finsert x A) = ffold f (f x z) A\"\n    by (transfer fixing: f) (rule fold_insert_idem2)\n\nend\n\n\nsubsection \\<open>Choice in fsets\\<close>\n\nlemma fset_choice:\n  assumes \"\\<forall>x. x |\\<in>| A \\<longrightarrow> (\\<exists>y. P x y)\"\n  shows \"\\<exists>f. \\<forall>x. x |\\<in>| A \\<longrightarrow> P x (f x)\"\n  using assms by transfer metis\n\n\nsubsection \\<open>Induction and Cases rules for fsets\\<close>\n\nlemma fset_exhaust [case_names empty insert, cases type: fset]:\n  assumes fempty_case: \"S = {||} \\<Longrightarrow> P\"\n  and     finsert_case: \"\\<And>x S'. S = finsert x S' \\<Longrightarrow> P\"\n  shows \"P\"\n  using assms by transfer blast\n\nlemma fset_induct [case_names empty insert]:\n  assumes fempty_case: \"P {||}\"\n  and     finsert_case: \"\\<And>x S. P S \\<Longrightarrow> P (finsert x S)\"\n  shows \"P S\"\nproof -\n  (* FIXME transfer and right_total vs. bi_total *)\n  note Domainp_forall_transfer[transfer_rule]\n  show ?thesis\n  using assms by transfer (auto intro: finite_induct)\nqed\n\nlemma fset_induct_stronger [case_names empty insert, induct type: fset]:\n  assumes empty_fset_case: \"P {||}\"\n  and     insert_fset_case: \"\\<And>x S. \\<lbrakk>x |\\<notin>| S; P S\\<rbrakk> \\<Longrightarrow> P (finsert x S)\"\n  shows \"P S\"\nproof -\n  (* FIXME transfer and right_total vs. bi_total *)\n  note Domainp_forall_transfer[transfer_rule]\n  show ?thesis\n  using assms by transfer (auto intro: finite_induct)\nqed\n\nlemma fset_card_induct:\n  assumes empty_fset_case: \"P {||}\"\n  and     card_fset_Suc_case: \"\\<And>S T. Suc (fcard S) = (fcard T) \\<Longrightarrow> P S \\<Longrightarrow> P T\"\n  shows \"P S\"\nproof (induct S)\n  case empty\n  show \"P {||}\" by (rule empty_fset_case)\nnext\n  case (insert x S)\n  have h: \"P S\" by fact\n  have \"x |\\<notin>| S\" by fact\n  then have \"Suc (fcard S) = fcard (finsert x S)\"\n    by transfer auto\n  then show \"P (finsert x S)\"\n    using h card_fset_Suc_case by simp\nqed\n\nlemma fset_strong_cases:\n  obtains \"xs = {||}\"\n    | ys x where \"x |\\<notin>| ys\" and \"xs = finsert x ys\"\nby transfer blast\n\nlemma fset_induct2:\n  \"P {||} {||} \\<Longrightarrow>\n  (\\<And>x xs. x |\\<notin>| xs \\<Longrightarrow> P (finsert x xs) {||}) \\<Longrightarrow>\n  (\\<And>y ys. y |\\<notin>| ys \\<Longrightarrow> P {||} (finsert y ys)) \\<Longrightarrow>\n  (\\<And>x xs y ys. \\<lbrakk>P xs ys; x |\\<notin>| xs; y |\\<notin>| ys\\<rbrakk> \\<Longrightarrow> P (finsert x xs) (finsert y ys)) \\<Longrightarrow>\n  P xsa ysa\"\n  apply (induct xsa arbitrary: ysa)\n  apply (induct_tac x rule: fset_induct_stronger)\n  apply simp_all\n  apply (induct_tac xa rule: fset_induct_stronger)\n  apply simp_all\n  done\n\n\nsubsection \\<open>Setup for Lifting/Transfer\\<close>\n\nsubsubsection \\<open>Relator and predicator properties\\<close>\n\nlift_definition rel_fset :: \"('a \\<Rightarrow> 'b \\<Rightarrow> bool) \\<Rightarrow> 'a fset \\<Rightarrow> 'b fset \\<Rightarrow> bool\" is rel_set\nparametric rel_set_transfer .\n\nlemma rel_fset_alt_def: \"rel_fset R = (\\<lambda>A B. (\\<forall>x.\\<exists>y. x|\\<in>|A \\<longrightarrow> y|\\<in>|B \\<and> R x y)\n  \\<and> (\\<forall>y. \\<exists>x. y|\\<in>|B \\<longrightarrow> x|\\<in>|A \\<and> R x y))\"\napply (rule ext)+\napply transfer'\napply (subst rel_set_def[unfolded fun_eq_iff])\nby blast\n\nlemma finite_rel_set:\n  assumes fin: \"finite X\" \"finite Z\"\n  assumes R_S: \"rel_set (R OO S) X Z\"\n  shows \"\\<exists>Y. finite Y \\<and> rel_set R X Y \\<and> rel_set S Y Z\"\nproof -\n  obtain f where f: \"\\<forall>x\\<in>X. R x (f x) \\<and> (\\<exists>z\\<in>Z. S (f x) z)\"\n  apply atomize_elim\n  apply (subst bchoice_iff[symmetric])\n  using R_S[unfolded rel_set_def OO_def] by blast\n\n  obtain g where g: \"\\<forall>z\\<in>Z. S (g z) z \\<and> (\\<exists>x\\<in>X. R x (g z))\"\n  apply atomize_elim\n  apply (subst bchoice_iff[symmetric])\n  using R_S[unfolded rel_set_def OO_def] by blast\n\n  let ?Y = \"f ` X \\<union> g ` Z\"\n  have \"finite ?Y\" by (simp add: fin)\n  moreover have \"rel_set R X ?Y\"\n    unfolding rel_set_def\n    using f g by clarsimp blast\n  moreover have \"rel_set S ?Y Z\"\n    unfolding rel_set_def\n    using f g by clarsimp blast\n  ultimately show ?thesis by metis\nqed\n\nsubsubsection \\<open>Transfer rules for the Transfer package\\<close>\n\ntext \\<open>Unconditional transfer rules\\<close>\n\ncontext includes lifting_syntax\nbegin\n\nlemmas fempty_transfer [transfer_rule] = empty_transfer[Transfer.transferred]\n\nlemma finsert_transfer [transfer_rule]:\n  \"(A ===> rel_fset A ===> rel_fset A) finsert finsert\"\n  unfolding rel_fun_def rel_fset_alt_def by blast\n\nlemma funion_transfer [transfer_rule]:\n  \"(rel_fset A ===> rel_fset A ===> rel_fset A) funion funion\"\n  unfolding rel_fun_def rel_fset_alt_def by blast\n\nlemma ffUnion_transfer [transfer_rule]:\n  \"(rel_fset (rel_fset A) ===> rel_fset A) ffUnion ffUnion\"\n  unfolding rel_fun_def rel_fset_alt_def by transfer (simp, fast)\n\nlemma fimage_transfer [transfer_rule]:\n  \"((A ===> B) ===> rel_fset A ===> rel_fset B) fimage fimage\"\n  unfolding rel_fun_def rel_fset_alt_def by simp blast\n\nlemma fBall_transfer [transfer_rule]:\n  \"(rel_fset A ===> (A ===> op =) ===> op =) fBall fBall\"\n  unfolding rel_fset_alt_def rel_fun_def by blast\n\nlemma fBex_transfer [transfer_rule]:\n  \"(rel_fset A ===> (A ===> op =) ===> op =) fBex fBex\"\n  unfolding rel_fset_alt_def rel_fun_def by blast\n\n(* FIXME transfer doesn't work here *)\nlemma fPow_transfer [transfer_rule]:\n  \"(rel_fset A ===> rel_fset (rel_fset A)) fPow fPow\"\n  unfolding rel_fun_def\n  using Pow_transfer[unfolded rel_fun_def, rule_format, Transfer.transferred]\n  by blast\n\nlemma rel_fset_transfer [transfer_rule]:\n  \"((A ===> B ===> op =) ===> rel_fset A ===> rel_fset B ===> op =)\n    rel_fset rel_fset\"\n  unfolding rel_fun_def\n  using rel_set_transfer[unfolded rel_fun_def,rule_format, Transfer.transferred, where A = A and B = B]\n  by simp\n\nlemma bind_transfer [transfer_rule]:\n  \"(rel_fset A ===> (A ===> rel_fset B) ===> rel_fset B) fbind fbind\"\n  unfolding rel_fun_def\n  using bind_transfer[unfolded rel_fun_def, rule_format, Transfer.transferred] by blast\n\ntext \\<open>Rules requiring bi-unique, bi-total or right-total relations\\<close>\n\nlemma fmember_transfer [transfer_rule]:\n  assumes \"bi_unique A\"\n  shows \"(A ===> rel_fset A ===> op =) (op |\\<in>|) (op |\\<in>|)\"\n  using assms unfolding rel_fun_def rel_fset_alt_def bi_unique_def by metis\n\nlemma finter_transfer [transfer_rule]:\n  assumes \"bi_unique A\"\n  shows \"(rel_fset A ===> rel_fset A ===> rel_fset A) finter finter\"\n  using assms unfolding rel_fun_def\n  using inter_transfer[unfolded rel_fun_def, rule_format, Transfer.transferred] by blast\n\nlemma fminus_transfer [transfer_rule]:\n  assumes \"bi_unique A\"\n  shows \"(rel_fset A ===> rel_fset A ===> rel_fset A) (op |-|) (op |-|)\"\n  using assms unfolding rel_fun_def\n  using Diff_transfer[unfolded rel_fun_def, rule_format, Transfer.transferred] by blast\n\nlemma fsubset_transfer [transfer_rule]:\n  assumes \"bi_unique A\"\n  shows \"(rel_fset A ===> rel_fset A ===> op =) (op |\\<subseteq>|) (op |\\<subseteq>|)\"\n  using assms unfolding rel_fun_def\n  using subset_transfer[unfolded rel_fun_def, rule_format, Transfer.transferred] by blast\n\nlemma fSup_transfer [transfer_rule]:\n  \"bi_unique A \\<Longrightarrow> (rel_set (rel_fset A) ===> rel_fset A) Sup Sup\"\n  unfolding rel_fun_def\n  apply clarify\n  apply transfer'\n  using Sup_fset_transfer[unfolded rel_fun_def] by blast\n\n(* FIXME: add right_total_fInf_transfer *)\n\nlemma fInf_transfer [transfer_rule]:\n  assumes \"bi_unique A\" and \"bi_total A\"\n  shows \"(rel_set (rel_fset A) ===> rel_fset A) Inf Inf\"\n  using assms unfolding rel_fun_def\n  apply clarify\n  apply transfer'\n  using Inf_fset_transfer[unfolded rel_fun_def] by blast\n\nlemma ffilter_transfer [transfer_rule]:\n  assumes \"bi_unique A\"\n  shows \"((A ===> op=) ===> rel_fset A ===> rel_fset A) ffilter ffilter\"\n  using assms unfolding rel_fun_def\n  using Lifting_Set.filter_transfer[unfolded rel_fun_def, rule_format, Transfer.transferred] by blast\n\nlemma card_transfer [transfer_rule]:\n  \"bi_unique A \\<Longrightarrow> (rel_fset A ===> op =) fcard fcard\"\n  unfolding rel_fun_def\n  using card_transfer[unfolded rel_fun_def, rule_format, Transfer.transferred] by blast\n\nend\n\nlifting_update fset.lifting\nlifting_forget fset.lifting\n\n\nsubsection \\<open>BNF setup\\<close>\n\ncontext\nincludes fset.lifting\nbegin\n\nlemma rel_fset_alt:\n  \"rel_fset R a b \\<longleftrightarrow> (\\<forall>t \\<in> fset a. \\<exists>u \\<in> fset b. R t u) \\<and> (\\<forall>t \\<in> fset b. \\<exists>u \\<in> fset a. R u t)\"\nby transfer (simp add: rel_set_def)\n\nlemma fset_to_fset: \"finite A \\<Longrightarrow> fset (the_inv fset A) = A\"\napply (rule f_the_inv_into_f[unfolded inj_on_def])\napply (simp add: fset_inject)\napply (rule range_eqI Abs_fset_inverse[symmetric] CollectI)+\n.\n\nlemma rel_fset_aux:\n\"(\\<forall>t \\<in> fset a. \\<exists>u \\<in> fset b. R t u) \\<and> (\\<forall>u \\<in> fset b. \\<exists>t \\<in> fset a. R t u) \\<longleftrightarrow>\n ((BNF_Def.Grp {a. fset a \\<subseteq> {(a, b). R a b}} (fimage fst))\\<inverse>\\<inverse> OO\n  BNF_Def.Grp {a. fset a \\<subseteq> {(a, b). R a b}} (fimage snd)) a b\" (is \"?L = ?R\")\nproof\n  assume ?L\n  define R' where \"R' =\n    the_inv fset (Collect (case_prod R) \\<inter> (fset a \\<times> fset b))\" (is \"_ = the_inv fset ?L'\")\n  have \"finite ?L'\" by (intro finite_Int[OF disjI2] finite_cartesian_product) (transfer, simp)+\n  hence *: \"fset R' = ?L'\" unfolding R'_def by (intro fset_to_fset)\n  show ?R unfolding Grp_def relcompp.simps conversep.simps\n  proof (intro CollectI case_prodI exI[of _ a] exI[of _ b] exI[of _ R'] conjI refl)\n    from * show \"a = fimage fst R'\" using conjunct1[OF \\<open>?L\\<close>]\n      by (transfer, auto simp add: image_def Int_def split: prod.splits)\n    from * show \"b = fimage snd R'\" using conjunct2[OF \\<open>?L\\<close>]\n      by (transfer, auto simp add: image_def Int_def split: prod.splits)\n  qed (auto simp add: *)\nnext\n  assume ?R thus ?L unfolding Grp_def relcompp.simps conversep.simps\n  apply (simp add: subset_eq Ball_def)\n  apply (rule conjI)\n  apply (transfer, clarsimp, metis snd_conv)\n  by (transfer, clarsimp, metis fst_conv)\nqed\n\nbnf \"'a fset\"\n  map: fimage\n  sets: fset\n  bd: natLeq\n  wits: \"{||}\"\n  rel: rel_fset\napply -\n          apply transfer' apply simp\n         apply transfer' apply force\n        apply transfer apply force\n       apply transfer' apply force\n      apply (rule natLeq_card_order)\n     apply (rule natLeq_cinfinite)\n    apply transfer apply (metis ordLess_imp_ordLeq finite_iff_ordLess_natLeq)\n   apply (fastforce simp: rel_fset_alt)\n apply (simp add: Grp_def relcompp.simps conversep.simps fun_eq_iff rel_fset_alt\n   rel_fset_aux[unfolded OO_Grp_alt])\napply transfer apply simp\ndone\n\nlemma rel_fset_fset: \"rel_set \\<chi> (fset A1) (fset A2) = rel_fset \\<chi> A1 A2\"\n  by transfer (rule refl)\n\nend\n\nlemmas [simp] = fset.map_comp fset.map_id fset.set_map\n\n\nsubsection \\<open>Size setup\\<close>\n\ncontext includes fset.lifting begin\nlift_definition size_fset :: \"('a \\<Rightarrow> nat) \\<Rightarrow> 'a fset \\<Rightarrow> nat\" is \"\\<lambda>f. sum (Suc \\<circ> f)\" .\nend\n\ninstantiation fset :: (type) size begin\ndefinition size_fset where\n  size_fset_overloaded_def: \"size_fset = FSet.size_fset (\\<lambda>_. 0)\"\ninstance ..\nend\n\nlemmas size_fset_simps[simp] =\n  size_fset_def[THEN meta_eq_to_obj_eq, THEN fun_cong, THEN fun_cong,\n    unfolded map_fun_def comp_def id_apply]\n\nlemmas size_fset_overloaded_simps[simp] =\n  size_fset_simps[of \"\\<lambda>_. 0\", unfolded add_0_left add_0_right,\n    folded size_fset_overloaded_def]\n\nlemma fset_size_o_map: \"inj f \\<Longrightarrow> size_fset g \\<circ> fimage f = size_fset (g \\<circ> f)\"\n  apply (subst fun_eq_iff)\n  including fset.lifting by transfer (auto intro: sum.reindex_cong subset_inj_on)\n\nsetup \\<open>\nBNF_LFP_Size.register_size_global @{type_name fset} @{const_name size_fset}\n  @{thm size_fset_overloaded_def} @{thms size_fset_simps size_fset_overloaded_simps}\n  @{thms fset_size_o_map}\n\\<close>\n\nlifting_update fset.lifting\nlifting_forget fset.lifting\n\nsubsection \\<open>Advanced relator customization\\<close>\n\n(* Set vs. sum relators: *)\n\nlemma rel_set_rel_sum[simp]:\n\"rel_set (rel_sum \\<chi> \\<phi>) A1 A2 \\<longleftrightarrow>\n rel_set \\<chi> (Inl -` A1) (Inl -` A2) \\<and> rel_set \\<phi> (Inr -` A1) (Inr -` A2)\"\n(is \"?L \\<longleftrightarrow> ?Rl \\<and> ?Rr\")\nproof safe\n  assume L: \"?L\"\n  show ?Rl unfolding rel_set_def Bex_def vimage_eq proof safe\n    fix l1 assume \"Inl l1 \\<in> A1\"\n    then obtain a2 where a2: \"a2 \\<in> A2\" and \"rel_sum \\<chi> \\<phi> (Inl l1) a2\"\n    using L unfolding rel_set_def by auto\n    then obtain l2 where \"a2 = Inl l2 \\<and> \\<chi> l1 l2\" by (cases a2, auto)\n    thus \"\\<exists> l2. Inl l2 \\<in> A2 \\<and> \\<chi> l1 l2\" using a2 by auto\n  next\n    fix l2 assume \"Inl l2 \\<in> A2\"\n    then obtain a1 where a1: \"a1 \\<in> A1\" and \"rel_sum \\<chi> \\<phi> a1 (Inl l2)\"\n    using L unfolding rel_set_def by auto\n    then obtain l1 where \"a1 = Inl l1 \\<and> \\<chi> l1 l2\" by (cases a1, auto)\n    thus \"\\<exists> l1. Inl l1 \\<in> A1 \\<and> \\<chi> l1 l2\" using a1 by auto\n  qed\n  show ?Rr unfolding rel_set_def Bex_def vimage_eq proof safe\n    fix r1 assume \"Inr r1 \\<in> A1\"\n    then obtain a2 where a2: \"a2 \\<in> A2\" and \"rel_sum \\<chi> \\<phi> (Inr r1) a2\"\n    using L unfolding rel_set_def by auto\n    then obtain r2 where \"a2 = Inr r2 \\<and> \\<phi> r1 r2\" by (cases a2, auto)\n    thus \"\\<exists> r2. Inr r2 \\<in> A2 \\<and> \\<phi> r1 r2\" using a2 by auto\n  next\n    fix r2 assume \"Inr r2 \\<in> A2\"\n    then obtain a1 where a1: \"a1 \\<in> A1\" and \"rel_sum \\<chi> \\<phi> a1 (Inr r2)\"\n    using L unfolding rel_set_def by auto\n    then obtain r1 where \"a1 = Inr r1 \\<and> \\<phi> r1 r2\" by (cases a1, auto)\n    thus \"\\<exists> r1. Inr r1 \\<in> A1 \\<and> \\<phi> r1 r2\" using a1 by auto\n  qed\nnext\n  assume Rl: \"?Rl\" and Rr: \"?Rr\"\n  show ?L unfolding rel_set_def Bex_def vimage_eq proof safe\n    fix a1 assume a1: \"a1 \\<in> A1\"\n    show \"\\<exists> a2. a2 \\<in> A2 \\<and> rel_sum \\<chi> \\<phi> a1 a2\"\n    proof(cases a1)\n      case (Inl l1) then obtain l2 where \"Inl l2 \\<in> A2 \\<and> \\<chi> l1 l2\"\n      using Rl a1 unfolding rel_set_def by blast\n      thus ?thesis unfolding Inl by auto\n    next\n      case (Inr r1) then obtain r2 where \"Inr r2 \\<in> A2 \\<and> \\<phi> r1 r2\"\n      using Rr a1 unfolding rel_set_def by blast\n      thus ?thesis unfolding Inr by auto\n    qed\n  next\n    fix a2 assume a2: \"a2 \\<in> A2\"\n    show \"\\<exists> a1. a1 \\<in> A1 \\<and> rel_sum \\<chi> \\<phi> a1 a2\"\n    proof(cases a2)\n      case (Inl l2) then obtain l1 where \"Inl l1 \\<in> A1 \\<and> \\<chi> l1 l2\"\n      using Rl a2 unfolding rel_set_def by blast\n      thus ?thesis unfolding Inl by auto\n    next\n      case (Inr r2) then obtain r1 where \"Inr r1 \\<in> A1 \\<and> \\<phi> r1 r2\"\n      using Rr a2 unfolding rel_set_def by blast\n      thus ?thesis unfolding Inr by auto\n    qed\n  qed\nqed\n\n\nsubsection \\<open>Quickcheck setup\\<close>\n\ntext \\<open>Setup adapted from sets.\\<close>\n\nnotation Quickcheck_Exhaustive.orelse (infixr \"orelse\" 55)\n\ndefinition (in term_syntax) [code_unfold]:\n\"valterm_femptyset = Code_Evaluation.valtermify ({||} :: ('a :: typerep) fset)\"\n\ndefinition (in term_syntax) [code_unfold]:\n\"valtermify_finsert x s = Code_Evaluation.valtermify finsert {\\<cdot>} (x :: ('a :: typerep * _)) {\\<cdot>} s\"\n\ninstantiation fset :: (exhaustive) exhaustive\nbegin\n\nfun exhaustive_fset where\n\"exhaustive_fset f i = (if i = 0 then None else (f {||} orelse exhaustive_fset (\\<lambda>A. f A orelse Quickcheck_Exhaustive.exhaustive (\\<lambda>x. if x |\\<in>| A then None else f (finsert x A)) (i - 1)) (i - 1)))\"\n\ninstance ..\n\nend\n\ninstantiation fset :: (full_exhaustive) full_exhaustive\nbegin\n\nfun full_exhaustive_fset where\n\"full_exhaustive_fset f i = (if i = 0 then None else (f valterm_femptyset orelse full_exhaustive_fset (\\<lambda>A. f A orelse Quickcheck_Exhaustive.full_exhaustive (\\<lambda>x. if fst x |\\<in>| fst A then None else f (valtermify_finsert x A)) (i - 1)) (i - 1)))\"\n\ninstance ..\n\nend\n\nno_notation Quickcheck_Exhaustive.orelse (infixr \"orelse\" 55)\n\nnotation scomp (infixl \"\\<circ>\\<rightarrow>\" 60)\n\ninstantiation fset :: (random) random\nbegin\n\nfun random_aux_fset :: \"natural \\<Rightarrow> natural \\<Rightarrow> natural \\<times> natural \\<Rightarrow> ('a fset \\<times> (unit \\<Rightarrow> term)) \\<times> natural \\<times> natural\" where\n\"random_aux_fset 0 j = Quickcheck_Random.collapse (Random.select_weight [(1, Pair valterm_femptyset)])\" |\n\"random_aux_fset (Code_Numeral.Suc i) j =\n  Quickcheck_Random.collapse (Random.select_weight\n    [(1, Pair valterm_femptyset),\n     (Code_Numeral.Suc i,\n      Quickcheck_Random.random j \\<circ>\\<rightarrow> (\\<lambda>x. random_aux_fset i j \\<circ>\\<rightarrow> (\\<lambda>s. Pair (valtermify_finsert x s))))])\"\n\n\n\ndefinition \"random_fset i = random_aux_fset i i\"\n\ninstance ..\n\nend\n\nno_notation scomp (infixl \"\\<circ>\\<rightarrow>\" 60)\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/FSet.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.857768094082276, "lm_q2_score": 0.8198933425148213, "lm_q1q2_score": 0.703278349759685}}
{"text": "theory Find_First\nimports\n  \"HOL-Library.Finite_Map\"\n  \"List-Index.List_Index\"\nbegin\n\nfun find_first :: \"'a \\<Rightarrow> 'a list \\<Rightarrow> nat option\" where\n\"find_first _ [] = None\" |\n\"find_first x (y # ys) = (if x = y then Some 0 else map_option Suc (find_first x ys))\"\n\nlemma find_first_correct:\n  assumes \"find_first x xs = Some i\"\n  shows \"i < length xs\" \"xs ! i = x\" \"x \\<notin> set (take i xs)\"\nusing assms\nproof (induction xs arbitrary: i)\n  case (Cons y ys)\n  { case 1 with Cons show ?case by (cases \"x = y\") auto }\n  { case 2 with Cons show ?case by (cases \"x = y\") auto }\n  { case 3 with Cons show ?case by (cases \"x = y\") auto }\nqed auto\n\nlemma find_first_none: \"x \\<notin> set xs \\<Longrightarrow> find_first x xs = None\"\nby (induct xs) auto\n\nlemma find_first_some_strong:\n  assumes \"x \\<in> set (take n xs)\" \"n \\<le> length xs\"\n  obtains i where \"find_first x xs = Some i\" \"i < n\"\nusing assms\nproof (induction xs arbitrary: thesis n)\n  case (Cons y ys)\n  show ?case\n    proof (cases \"x = y\")\n      case True\n      show ?thesis\n        proof (rule Cons.prems)\n          show \"find_first x (y # ys) = Some 0\"\n            unfolding \\<open>x = y\\<close> by simp\n        next\n          show \"0 < n\"\n            using Cons by (metis length_pos_if_in_set length_take min.absorb2)\n          qed\n    next\n      case False\n      show ?thesis\n        proof (rule Cons.IH)\n          fix i\n          assume \"find_first x ys = Some i\" \"i < n - 1\"\n          with False have \"find_first x (y # ys) = Some (Suc i)\" \"Suc i < n\"\n            using False by auto\n          thus thesis\n            using Cons by metis\n        next\n          show \"x \\<in> set (take (n - 1) ys)\"\n            using Cons False by (metis empty_iff list.set(1) set_ConsD take_Cons')\n        next\n          show \"n - 1 \\<le> length ys\"\n            using Cons by (metis One_nat_def le_diff_conv list.size(4))\n        qed\n    qed\nqed simp\n\nlemma find_first_some:\n  assumes \"x \\<in> set xs\"\n  obtains i where \"find_first x xs = Some i\" \"i < length xs\"\nusing assms\nby (metis order_refl take_all find_first_some_strong)\n\n\n\nlemma find_first_append:\n  \"find_first x (ys @ zs) =\n    (case find_first x ys of None \\<Rightarrow> map_option (\\<lambda>i. i + length ys) (find_first x zs) | Some a \\<Rightarrow> Some a)\"\nby (induct ys) (auto simp: option.map_comp comp_def map_option.identity split: option.splits)\n\nlemma find_first_first:\n  assumes \"i < length xs\" \"x \\<notin> set (take i xs)\" \"xs ! i = x\"\n  shows \"find_first x xs = Some i\"\nproof -\n  let ?ys = \"take i xs\"\n  let ?zs = \"drop i xs\"\n\n  have \"?zs ! 0 = x\"\n    using assms by simp\n  hence \"find_first x ?zs = Some 0\"\n    using assms by (cases ?zs) auto\n  moreover have \"find_first x ?ys = None\"\n    using assms by (simp add: find_first_none)\n  ultimately have \"find_first x (?ys @ ?zs) = Some i\"\n    unfolding find_first_append\n    using assms by simp\n  thus ?thesis\n    using assms by simp\nqed\n\nlemma find_first_prefix:\n  assumes \"find_first x xs = Some i\" \"i < n\"\n  shows \"find_first x (take n xs) = Some i\"\nproof (rule find_first_first)\n  show \"i < length (take n xs)\"\n    using assms by (simp add: find_first_correct)\nnext\n  have \"x \\<notin> set (take i xs)\"\n    using assms by (simp add: find_first_correct)\n  with assms show \"x \\<notin> set (take i (take n xs))\"\n    by (simp add: min.absorb1)\nnext\n  show \"take n xs ! i = x\"\n    using assms by (simp add: find_first_correct)\nqed\n\nlemma find_first_later:\n  assumes \"i < length xs\" \"j < length xs\" \"i < j\"\n  assumes \"xs ! i = x\" \"xs ! j = x\"\n  shows \"find_first x xs \\<noteq> Some j\"\nproof (cases \"x \\<in> set (take i xs)\")\n  case True\n  then obtain k where \"find_first x xs = Some k\" \"k < i\"\n    using assms by (auto elim: find_first_some_strong)\n  thus ?thesis\n    using assms by simp\nnext\n  case False\n  hence \"find_first x xs = Some i\"\n    using assms by (simp add: find_first_first)\n  thus ?thesis\n    using assms by simp\nqed\n\nlemma find_first_in_map:\n  assumes \"length xs \\<le> length ys\" \"find_first n xs = Some i\"\n  shows \"fmlookup (fmap_of_list (zip xs ys)) n = Some (ys ! i)\"\nusing assms proof (induction xs arbitrary: ys i)\n  case (Cons x xs)\n  then obtain y ys' where \"ys = y # ys'\"\n    by (metis Skolem_list_nth le_0_eq length_greater_0_conv less_nat_zero_code list.set_cases listrel_Cons1 listrel_iff_nth nth_mem)\n  with Cons show ?case\n    by (cases \"x = n\") auto\nqed auto\n\nfun common_prefix where\n\"common_prefix (x # xs) (y # ys) = (if x = y then x # common_prefix xs ys else [])\" |\n\"common_prefix _ _ = []\"\n\nlemma common_prefix_find:\n  assumes \"z \\<in> set (common_prefix xs ys)\"\n  shows \"find_first z xs = find_first z ys\"\nusing assms\nby (induct xs ys rule: common_prefix.induct) auto\n\nlemma find_first_insert_nth_eq:\n  assumes \"n \\<le> length xs\" \"x \\<notin> set (take n xs)\"\n  shows \"find_first x (insert_nth n x xs) = Some n\"\nusing assms\n  by (auto simp: find_first_append find_first_none split: option.splits)\n\nlemma insert_nth_induct:\n  fixes P :: \"nat \\<Rightarrow> 'a \\<Rightarrow> 'a list \\<Rightarrow> bool\"\n    and a0 :: \"nat\"\n    and a1 :: \"'a\"\n    and a2 :: \"'a list\"\n  assumes \"\\<And>x xs. P 0 x xs\"\n    and \"\\<And>n x y ys. P n x ys \\<Longrightarrow> P (Suc n) x (y # ys)\"\n    and \"\\<And>n x. P (Suc n) x []\"\n  shows \"P a0 a1 a2\"\nusing assms\napply induction_schema\napply pat_completeness\napply lexicographic_order\ndone\n\nlemma find_first_insert_nth_neq:\n  assumes \"x \\<noteq> y\"\n  shows \"find_first x (insert_nth n y xs) = map_option (\\<lambda>i. if i < n then i else Suc i) (find_first x xs)\"\nusing assms\nproof (induction n y xs rule: insert_nth_induct)\n  case 2\n  note insert_nth_take_drop[simp del]\n  show ?case\n    apply auto\n    apply (subst 2)\n    apply (rule 2)\n    unfolding option.map_comp\n    apply (rule option.map_cong0)\n    by auto\nqed 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/Higher_Order_Terms/Find_First.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951182587158, "lm_q2_score": 0.8333245953120233, "lm_q1q2_score": 0.7032385579087364}}
{"text": "(*  Title:      HOL/Inductive.thy\n    Author:     Markus Wenzel, TU Muenchen\n*)\n\nsection {* Knaster-Tarski Fixpoint Theorem and inductive definitions *}\n\ntheory Inductive\nimports Complete_Lattices Ctr_Sugar\nkeywords\n  \"inductive\" \"coinductive\" \"inductive_cases\" \"inductive_simps\" :: thy_decl and\n  \"monos\" and\n  \"print_inductives\" :: diag and\n  \"old_rep_datatype\" :: thy_goal and\n  \"primrec\" :: thy_decl\nbegin\n\nsubsection {* Least and greatest fixed points *}\n\ncontext complete_lattice\nbegin\n\ndefinition\n  lfp :: \"('a \\<Rightarrow> 'a) \\<Rightarrow> 'a\" where\n  \"lfp f = Inf {u. f u \\<le> u}\"    --{*least fixed point*}\n\ndefinition\n  gfp :: \"('a \\<Rightarrow> 'a) \\<Rightarrow> 'a\" where\n  \"gfp f = Sup {u. u \\<le> f u}\"    --{*greatest fixed point*}\n\n\nsubsection{* Proof of Knaster-Tarski Theorem using @{term lfp} *}\n\ntext{*@{term \"lfp f\"} is the least upper bound of\n      the set @{term \"{u. f(u) \\<le> u}\"} *}\n\nlemma lfp_lowerbound: \"f A \\<le> A ==> lfp f \\<le> A\"\n  by (auto simp add: lfp_def intro: Inf_lower)\n\nlemma lfp_greatest: \"(!!u. f u \\<le> u ==> A \\<le> u) ==> A \\<le> lfp f\"\n  by (auto simp add: lfp_def intro: Inf_greatest)\n\nend\n\nlemma lfp_lemma2: \"mono f ==> f (lfp f) \\<le> lfp f\"\n  by (iprover intro: lfp_greatest order_trans monoD lfp_lowerbound)\n\nlemma lfp_lemma3: \"mono f ==> lfp f \\<le> f (lfp f)\"\n  by (iprover intro: lfp_lemma2 monoD lfp_lowerbound)\n\n\n\nlemma lfp_const: \"lfp (\\<lambda>x. t) = t\"\n  by (rule lfp_unfold) (simp add:mono_def)\n\n\nsubsection {* General induction rules for least fixed points *}\n\ntheorem lfp_induct:\n  assumes mono: \"mono f\" and ind: \"f (inf (lfp f) P) <= P\"\n  shows \"lfp f <= P\"\nproof -\n  have \"inf (lfp f) P <= lfp f\" by (rule inf_le1)\n  with mono have \"f (inf (lfp f) P) <= f (lfp f)\" ..\n  also from mono have \"f (lfp f) = lfp f\" by (rule lfp_unfold [symmetric])\n  finally have \"f (inf (lfp f) P) <= lfp f\" .\n  from this and ind have \"f (inf (lfp f) P) <= inf (lfp f) P\" by (rule le_infI)\n  hence \"lfp f <= inf (lfp f) P\" by (rule lfp_lowerbound)\n  also have \"inf (lfp f) P <= P\" by (rule inf_le2)\n  finally show ?thesis .\nqed\n\nlemma lfp_induct_set:\n  assumes lfp: \"a: lfp(f)\"\n      and mono: \"mono(f)\"\n      and indhyp: \"!!x. [| x: f(lfp(f) Int {x. P(x)}) |] ==> P(x)\"\n  shows \"P(a)\"\n  by (rule lfp_induct [THEN subsetD, THEN CollectD, OF mono _ lfp])\n    (auto simp: intro: indhyp)\n\nlemma lfp_ordinal_induct:\n  fixes f :: \"'a\\<Colon>complete_lattice \\<Rightarrow> 'a\"\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 (Sup M)\"\n  shows \"P (lfp f)\"\nproof -\n  let ?M = \"{S. S \\<le> lfp f \\<and> P S}\"\n  have \"P (Sup ?M)\" using P_Union by simp\n  also have \"Sup ?M = lfp f\"\n  proof (rule antisym)\n    show \"Sup ?M \\<le> lfp f\" by (blast intro: Sup_least)\n    hence \"f (Sup ?M) \\<le> f (lfp f)\" by (rule mono [THEN monoD])\n    hence \"f (Sup ?M) \\<le> lfp f\" using mono [THEN lfp_unfold] by simp\n    hence \"f (Sup ?M) \\<in> ?M\" using P_f P_Union by simp\n    hence \"f (Sup ?M) \\<le> Sup ?M\" by (rule Sup_upper)\n    thus \"lfp f \\<le> Sup ?M\" by (rule lfp_lowerbound)\n  qed\n  finally show ?thesis .\nqed \n\nlemma lfp_ordinal_induct_set: \n  assumes mono: \"mono f\"\n  and P_f: \"!!S. P S ==> P(f S)\"\n  and P_Union: \"!!M. !S:M. P S ==> P(Union M)\"\n  shows \"P(lfp f)\"\n  using assms by (rule lfp_ordinal_induct)\n\n\ntext{*Definition forms of @{text lfp_unfold} and @{text lfp_induct}, \n    to control unfolding*}\n\nlemma def_lfp_unfold: \"[| h==lfp(f);  mono(f) |] ==> h = f(h)\"\n  by (auto intro!: lfp_unfold)\n\nlemma def_lfp_induct: \n    \"[| A == lfp(f); mono(f);\n        f (inf A P) \\<le> P\n     |] ==> A \\<le> P\"\n  by (blast intro: lfp_induct)\n\nlemma def_lfp_induct_set: \n    \"[| A == lfp(f);  mono(f);   a:A;                    \n        !!x. [| x: f(A Int {x. P(x)}) |] ==> P(x)         \n     |] ==> P(a)\"\n  by (blast intro: lfp_induct_set)\n\n(*Monotonicity of lfp!*)\nlemma lfp_mono: \"(!!Z. f Z \\<le> g Z) ==> lfp f \\<le> lfp g\"\n  by (rule lfp_lowerbound [THEN lfp_greatest], blast intro: order_trans)\n\n\nsubsection {* Proof of Knaster-Tarski Theorem using @{term gfp} *}\n\ntext{*@{term \"gfp f\"} is the greatest lower bound of \n      the set @{term \"{u. u \\<le> f(u)}\"} *}\n\nlemma gfp_upperbound: \"X \\<le> f X ==> X \\<le> gfp f\"\n  by (auto simp add: gfp_def intro: Sup_upper)\n\nlemma gfp_least: \"(!!u. u \\<le> f u ==> u \\<le> X) ==> gfp f \\<le> X\"\n  by (auto simp add: gfp_def intro: Sup_least)\n\nlemma gfp_lemma2: \"mono f ==> gfp f \\<le> f (gfp f)\"\n  by (iprover intro: gfp_least order_trans monoD gfp_upperbound)\n\nlemma gfp_lemma3: \"mono f ==> f (gfp f) \\<le> gfp f\"\n  by (iprover intro: gfp_lemma2 monoD gfp_upperbound)\n\nlemma gfp_unfold: \"mono f ==> gfp f = f (gfp f)\"\n  by (iprover intro: order_antisym gfp_lemma2 gfp_lemma3)\n\n\nsubsection {* Coinduction rules for greatest fixed points *}\n\ntext{*weak version*}\nlemma weak_coinduct: \"[| a: X;  X \\<subseteq> f(X) |] ==> a : gfp(f)\"\n  by (rule gfp_upperbound [THEN subsetD]) auto\n\nlemma weak_coinduct_image: \"!!X. [| a : X; g`X \\<subseteq> f (g`X) |] ==> g a : gfp f\"\n  apply (erule gfp_upperbound [THEN subsetD])\n  apply (erule imageI)\n  done\n\nlemma coinduct_lemma:\n     \"[| X \\<le> f (sup X (gfp f));  mono f |] ==> sup X (gfp f) \\<le> f (sup X (gfp f))\"\n  apply (frule gfp_lemma2)\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{*strong version, thanks to Coen and Frost*}\nlemma coinduct_set: \"[| mono(f);  a: X;  X \\<subseteq> f(X Un gfp(f)) |] ==> a : gfp(f)\"\n  by (rule weak_coinduct[rotated], rule coinduct_lemma) blast+\n\nlemma coinduct: \"[| mono(f); X \\<le> f (sup X (gfp f)) |] ==> X \\<le> gfp(f)\"\n  apply (rule order_trans)\n  apply (rule sup_ge1)\n  apply (rule gfp_upperbound)\n  apply (erule coinduct_lemma)\n  apply assumption\n  done\n\nlemma gfp_fun_UnI2: \"[| mono(f);  a: gfp(f) |] ==> a: f(X Un gfp(f))\"\n  by (blast dest: gfp_lemma2 mono_Un)\n\n\nsubsection {* Even Stronger Coinduction Rule, by Martin Coen *}\n\ntext{* Weakens the condition @{term \"X \\<subseteq> f(X)\"} to one expressed using both\n  @{term lfp} and @{term gfp}*}\n\nlemma coinduct3_mono_lemma: \"mono(f) ==> mono(%x. f(x) Un X Un B)\"\nby (iprover intro: subset_refl monoI Un_mono monoD)\n\nlemma coinduct3_lemma:\n     \"[| X \\<subseteq> f(lfp(%x. f(x) Un X Un gfp(f)));  mono(f) |]\n      ==> lfp(%x. f(x) Un X Un gfp(f)) \\<subseteq> f(lfp(%x. f(x) Un X Un gfp(f)))\"\napply (rule subset_trans)\napply (erule coinduct3_mono_lemma [THEN lfp_lemma3])\napply (rule Un_least [THEN Un_least])\napply (rule subset_refl, assumption)\napply (rule gfp_unfold [THEN equalityD1, THEN subset_trans], assumption)\napply (rule monoD, assumption)\napply (subst coinduct3_mono_lemma [THEN lfp_unfold], auto)\ndone\n\nlemma coinduct3: \n  \"[| mono(f);  a:X;  X \\<subseteq> f(lfp(%x. f(x) Un X Un gfp(f))) |] ==> a : gfp(f)\"\napply (rule coinduct3_lemma [THEN [2] weak_coinduct])\napply (rule coinduct3_mono_lemma [THEN lfp_unfold, THEN ssubst])\napply (simp_all)\ndone\n\n\ntext{*Definition forms of @{text gfp_unfold} and @{text coinduct}, \n    to control unfolding*}\n\nlemma def_gfp_unfold: \"[| A==gfp(f);  mono(f) |] ==> A = f(A)\"\n  by (auto intro!: gfp_unfold)\n\nlemma def_coinduct:\n     \"[| A==gfp(f);  mono(f);  X \\<le> f(sup X A) |] ==> X \\<le> A\"\n  by (iprover intro!: coinduct)\n\nlemma def_coinduct_set:\n     \"[| A==gfp(f);  mono(f);  a:X;  X \\<subseteq> f(X Un A) |] ==> a: A\"\n  by (auto intro!: coinduct_set)\n\n(*The version used in the induction/coinduction package*)\nlemma def_Collect_coinduct:\n    \"[| A == gfp(%w. Collect(P(w)));  mono(%w. Collect(P(w)));   \n        a: X;  !!z. z: X ==> P (X Un A) z |] ==>  \n     a : A\"\n  by (erule def_coinduct_set) auto\n\nlemma def_coinduct3:\n    \"[| A==gfp(f); mono(f);  a:X;  X \\<subseteq> f(lfp(%x. f(x) Un X Un A)) |] ==> a: A\"\n  by (auto intro!: coinduct3)\n\ntext{*Monotonicity of @{term gfp}!*}\nlemma gfp_mono: \"(!!Z. f Z \\<le> g Z) ==> gfp f \\<le> gfp g\"\n  by (rule gfp_upperbound [THEN gfp_least], blast intro: order_trans)\n\n\nsubsection {* Inductive predicates and sets *}\n\ntext {* Package setup. *}\n\ntheorems 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\nML_file \"Tools/inductive.ML\"\n\ntheorems [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 {* Inductive datatypes and primitive recursion *}\n\ntext {* Package setup. *}\n\nML_file \"Tools/Old_Datatype/old_datatype_aux.ML\"\nML_file \"Tools/Old_Datatype/old_datatype_prop.ML\"\nML_file \"Tools/Old_Datatype/old_datatype_data.ML\"\nML_file \"Tools/Old_Datatype/old_rep_datatype.ML\"\nML_file \"Tools/Old_Datatype/old_datatype_codegen.ML\"\nML_file \"Tools/Old_Datatype/old_primrec.ML\"\n\nML_file \"Tools/BNF/bnf_fp_rec_sugar_util.ML\"\nML_file \"Tools/BNF/bnf_lfp_rec_sugar.ML\"\n\ntext{* Lambda-abstractions with pattern matching: *}\n\nsyntax\n  \"_lam_pats_syntax\" :: \"cases_syn => 'a => 'b\"               (\"(%_)\" 10)\nsyntax (xsymbols)\n  \"_lam_pats_syntax\" :: \"cases_syn => 'a => 'b\"               (\"(\\<lambda>_)\" 10)\n\nparse_translation {*\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 \"_lam_pats_syntax\"}, fun_tr)] end\n*}\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/Inductive.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245953120233, "lm_q2_score": 0.8438951104066295, "lm_q1q2_score": 0.7032385513653997}}
{"text": "(*  \n  Title:    Order_Predicates.thy\n  Author:   Manuel Eberl, TU M\u00fcnchen\n\n  Locales for order relations modelled as predicates (as opposed to sets of pairs).\n*)\nsection \\<open>Order Relations as Binary Predicates\\<close>\n\ntheory Order_Predicates\nimports \n  Main\n  \"~~/src/HOL/Library/Disjoint_Sets\"\n  \"~~/src/HOL/Library/Permutations\"\n  Missing_Permutations\n  \"../List-Index/List_Index\"\nbegin\n\n(* TODO: Move *)\nlemma assumes \"disjoint (A \\<union> B)\"\n      shows   disjoint_unionD1: \"disjoint A\" and disjoint_unionD2: \"disjoint B\"\n  using assms by (simp_all add: disjoint_def)\n\ndefinition is_singleton :: \"'a set \\<Rightarrow> bool\" where\n  \"is_singleton A \\<longleftrightarrow> (\\<exists>x. A = {x})\"\n\nlemma is_singletonI [simp, intro!]: \"is_singleton {x}\"\n  unfolding is_singleton_def by simp\n\nlemma is_singletonI': \"A \\<noteq> {} \\<Longrightarrow> (\\<And>x y. x \\<in> A \\<Longrightarrow> y \\<in> A \\<Longrightarrow> x = y) \\<Longrightarrow> is_singleton A\"\n  unfolding is_singleton_def by blast\n\nlemma is_singletonE: \"is_singleton A \\<Longrightarrow> (\\<And>x. A = {x} \\<Longrightarrow> P) \\<Longrightarrow> P\"\n  unfolding is_singleton_def by blast\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 is_singleton_the_elem: \"is_singleton A \\<longleftrightarrow> A = {the_elem A}\"\n  by (auto simp: is_singleton_def)\n\n(* END TODO *)\n\n\nsubsection \\<open>Basic Operations on Relations\\<close>\n\ntext \\<open>The type of binary relations\\<close>\ntype_synonym 'a relation = \"'a \\<Rightarrow> 'a \\<Rightarrow> bool\"\n\ndefinition map_relation :: \"('a \\<Rightarrow> 'b) \\<Rightarrow> 'b relation \\<Rightarrow> 'a relation\" where\n  \"map_relation f R = (\\<lambda>x y. R (f x) (f y))\"\n\ndefinition restrict_relation :: \"'a set \\<Rightarrow> 'a relation \\<Rightarrow> 'a relation\" where\n  \"restrict_relation A R = (\\<lambda>x y. x \\<in> A \\<and> y \\<in> A \\<and> R x y)\"\n\nlemma restrict_relation_restrict_relation [simp]:\n  \"restrict_relation A (restrict_relation B R) = restrict_relation (A \\<inter> B) R\"\n  by (intro ext) (auto simp add: restrict_relation_def)\n\nlemma restrict_relation_empty [simp]: \"restrict_relation {} R = (\\<lambda>_ _. False)\"\n  by (simp add: restrict_relation_def)\n\nlemma restrict_relation_UNIV [simp]: \"restrict_relation UNIV R = R\"\n  by (simp add: restrict_relation_def)\n\n\nsubsection \\<open>Preorders\\<close>\n\ntext \\<open>Preorders are reflexive and transitive binary relations.\\<close>\nlocale preorder_on =\n  fixes carrier :: \"'a set\"\n  fixes le :: \"'a relation\"\n  assumes not_outside: \"le x y \\<Longrightarrow> x \\<in> carrier\" \"le x y \\<Longrightarrow> y \\<in> carrier\"\n  assumes refl: \"x \\<in> carrier \\<Longrightarrow> le x x\"\n  assumes trans: \"le x y \\<Longrightarrow> le y z \\<Longrightarrow> le x z\"\nbegin\n\nlemma carrier_eq: \"carrier = {x. le x x}\"\n  using not_outside refl by auto\n  \nlemma preorder_on_map:\n  \"preorder_on (f -` carrier) (map_relation f le)\"\n  by unfold_locales (auto dest: not_outside simp: map_relation_def refl elim: trans)\n  \nlemma preorder_on_restrict:\n  \"preorder_on (carrier \\<inter> A) (restrict_relation A le)\"\n  by unfold_locales (auto simp: restrict_relation_def refl intro: trans not_outside)\n\nlemma preorder_on_restrict_subset:\n  \"A \\<subseteq> carrier \\<Longrightarrow> preorder_on A (restrict_relation A le)\"\n  using preorder_on_restrict[of A] by (simp add: Int_absorb1)\n\nlemma restrict_relation_carrier [simp]:\n  \"restrict_relation carrier le = le\"\n  using not_outside by (intro ext) (auto simp add: restrict_relation_def)\n\nend\n  \n\nsubsection \\<open>Total preorders\\<close>\n\ntext \\<open>Total preorders are preorders where any two elements are comparable.\\<close>\nlocale total_preorder_on = preorder_on +\n  assumes total: \"x \\<in> carrier \\<Longrightarrow> y \\<in> carrier \\<Longrightarrow> le x y \\<or> le y x\"\nbegin\n\nlemma total': \"\\<not>le x y \\<Longrightarrow> x \\<in> carrier \\<Longrightarrow> y \\<in> carrier \\<Longrightarrow> le y x\"\n  using total[of x y] by blast\n\nlemma total_preorder_on_map:\n  \"total_preorder_on (f -` carrier) (map_relation f le)\"\nproof -\n  interpret R': preorder_on \"f -` carrier\" \"map_relation f le\"\n    using preorder_on_map[of f] .\n  show ?thesis by unfold_locales (simp add: map_relation_def total)\nqed\n\nlemma total_preorder_on_restrict:\n  \"total_preorder_on (carrier \\<inter> A) (restrict_relation A le)\"\nproof -\n  interpret R': preorder_on \"carrier \\<inter> A\" \"restrict_relation A le\"\n    by (rule preorder_on_restrict)\n  from total show ?thesis\n    by unfold_locales (auto simp: restrict_relation_def)\nqed\n\nlemma total_preorder_on_restrict_subset:\n  \"A \\<subseteq> carrier \\<Longrightarrow> total_preorder_on A (restrict_relation A le)\"\n  using total_preorder_on_restrict[of A] by (simp add: Int_absorb1)\n\nend\n\n\ntext \\<open>Some fancy notation for order relations\\<close>\nabbreviation (input) weakly_preferred :: \"'a \\<Rightarrow> 'a relation \\<Rightarrow> 'a \\<Rightarrow> bool\"\n    (\"_ \\<preceq>[_] _\" [51,10,51] 60) where\n  \"a \\<preceq>[R] b \\<equiv> R a b\"\n  \ndefinition strongly_preferred (\"_ \\<prec>[_] _\" [51,10,51] 60) where\n  \"a \\<prec>[R] b \\<equiv> (a \\<preceq>[R] b) \\<and> \\<not>(b \\<preceq>[R] a)\"\n\ndefinition indifferent (\"_ \\<sim>[_] _\" [51,10,51] 60) where\n  \"a \\<sim>[R] b \\<equiv> (a \\<preceq>[R] b) \\<and> (b \\<preceq>[R] a)\"\n\nabbreviation (input) weakly_not_preferred (\"_ \\<succeq>[_] _\" [51,10,51] 60) where\n  \"a \\<succeq>[R] b \\<equiv> b \\<preceq>[R] a\"\n  term \"a \\<succeq>[R] b \\<longleftrightarrow> b \\<preceq>[R] a\"\n\nabbreviation (input) strongly_not_preferred (\"_ \\<succ>[_] _\" [51,10,51] 60) where\n  \"a \\<succ>[R] b \\<equiv> b \\<prec>[R] a\"\n\ncontext preorder_on\nbegin\n\nlemma strict_trans: \"a \\<prec>[le] b \\<Longrightarrow> b \\<prec>[le] c \\<Longrightarrow> a \\<prec>[le] c\"\n  unfolding strongly_preferred_def by (blast intro: trans)\n\nlemma weak_strict_trans: \"a \\<preceq>[le] b \\<Longrightarrow> b \\<prec>[le] c \\<Longrightarrow> a \\<prec>[le] c\"\n  unfolding strongly_preferred_def by (blast intro: trans)\n\nlemma strict_weak_trans: \"a \\<prec>[le] b \\<Longrightarrow> b \\<preceq>[le] c \\<Longrightarrow> a \\<prec>[le] c\"\n  unfolding strongly_preferred_def by (blast intro: trans)\n\nend\n\nlemma (in total_preorder_on) not_weakly_preferred_iff:\n  \"a \\<in> carrier \\<Longrightarrow> b \\<in> carrier \\<Longrightarrow> \\<not>a \\<preceq>[le] b \\<longleftrightarrow> b \\<prec>[le] a\"\n  using total[of a b] by (auto simp: strongly_preferred_def)\n\nlemma (in total_preorder_on) not_strongly_preferred_iff:\n  \"a \\<in> carrier \\<Longrightarrow> b \\<in> carrier \\<Longrightarrow> \\<not>a \\<prec>[le] b \\<longleftrightarrow> b \\<preceq>[le] a\"\n  using total[of a b] by (auto simp: strongly_preferred_def)\n\n\n\nsubsection \\<open>Orders\\<close>\n\nlocale order_on = preorder_on +\n  assumes antisymmetric: \"le x y \\<Longrightarrow> le y x \\<Longrightarrow> x = y\"\n\nlocale linorder_on = order_on carrier le + total_preorder_on carrier le for carrier le\n\n\nsubsection \\<open>Maximal elements\\<close>\n\ntext \\<open>\n  Maximal elements are elements in a preorder for which there exists no strictly greater element.\n\\<close>\n\ndefinition Max_wrt_among :: \"'a relation \\<Rightarrow> 'a set \\<Rightarrow> 'a set\" where\n  \"Max_wrt_among R A = {x\\<in>A. R x x \\<and> (\\<forall>y\\<in>A. R x y \\<longrightarrow> R y x)}\"\n\nlemma Max_wrt_among_cong:\n  assumes \"restrict_relation A R = restrict_relation A R'\"\n  shows   \"Max_wrt_among R A = Max_wrt_among R' A\"\nproof -\n  from assms have \"R x y \\<longleftrightarrow> R' x y\" if \"x \\<in> A\" \"y \\<in> A\" for x y\n    using that by (auto simp: restrict_relation_def fun_eq_iff)\n  thus ?thesis unfolding Max_wrt_among_def by blast\nqed\n\ndefinition Max_wrt :: \"'a relation \\<Rightarrow> 'a set\" where\n  \"Max_wrt R = Max_wrt_among R UNIV\"\n  \nlemma Max_wrt_altdef: \"Max_wrt R = {x. R x x \\<and> (\\<forall>y. R x y \\<longrightarrow> R y x)}\"\n  unfolding Max_wrt_def Max_wrt_among_def by simp\n\ncontext preorder_on\nbegin\n\nlemma Max_wrt_among_preorder:\n  \"Max_wrt_among le A = {x\\<in>carrier \\<inter> A. \\<forall>y\\<in>carrier \\<inter> A. le x y \\<longrightarrow> le y x}\"\n  unfolding Max_wrt_among_def using not_outside refl by blast\n\nlemma Max_wrt_preorder:\n  \"Max_wrt le = {x\\<in>carrier. \\<forall>y\\<in>carrier. le x y \\<longrightarrow> le y x}\"\n  unfolding Max_wrt_altdef using not_outside refl by blast\n\nlemma Max_wrt_among_subset:\n  \"Max_wrt_among le A \\<subseteq> carrier\" \"Max_wrt_among le A \\<subseteq> A\"\n  unfolding Max_wrt_among_preorder by auto\n  \nlemma Max_wrt_subset:\n  \"Max_wrt le \\<subseteq> carrier\"\n  unfolding Max_wrt_preorder by auto\n\nlemma Max_wrt_among_nonempty:\n  assumes \"B \\<inter> carrier \\<noteq> {}\" \"finite (B \\<inter> carrier)\"\n  shows   \"Max_wrt_among le B \\<noteq> {}\"\nproof -\n  def A \\<equiv> \"B \\<inter> carrier\"\n  have \"A \\<subseteq> carrier\" by (simp add: A_def)\n  from assms(2,1)[folded A_def] this have \"{x\\<in>A. (\\<forall>y\\<in>A. le x y \\<longrightarrow> le y x)} \\<noteq> {}\"\n  proof (induction A rule: finite_ne_induct)\n    case (singleton x)\n    thus ?case by (auto simp: refl)\n  next\n    case (insert x A)\n    then obtain y where y: \"y \\<in> A\" \"\\<And>z. z \\<in> A \\<Longrightarrow> le y z \\<Longrightarrow> le z y\" by blast\n    thus ?case using insert.prems\n      by (cases \"le y x\") (blast intro: trans)+\n  qed\n  thus ?thesis by (simp add: A_def Max_wrt_among_preorder Int_commute)\nqed\n  \nlemma Max_wrt_nonempty:\n  \"carrier \\<noteq> {} \\<Longrightarrow> finite carrier \\<Longrightarrow> Max_wrt le \\<noteq> {}\"\n  using Max_wrt_among_nonempty[of UNIV] by (simp add: Max_wrt_def)\n\nlemma Max_wrt_among_map_relation_vimage:\n  \"f -` Max_wrt_among le A \\<subseteq> Max_wrt_among (map_relation f le) (f -` A)\"\n  by (auto simp: Max_wrt_among_def map_relation_def)\n\n\n\nlemma image_subset_vimage_the_inv_into: \n  assumes \"inj_on f A\" \"B \\<subseteq> A\"\n  shows   \"f ` B \\<subseteq> the_inv_into A f -` B\"\n  using assms by (auto simp: the_inv_into_f_f)\n\nlemma Max_wrt_among_map_relation_bij_subset:\n  assumes \"bij (f :: 'a \\<Rightarrow> 'b)\"\n  shows   \"f ` Max_wrt_among le A \\<subseteq> \n             Max_wrt_among (map_relation (inv f) le) (f ` A)\"\n  using assms Max_wrt_among_map_relation_vimage[of \"inv f\" A]\n  by (simp add: bij_imp_bij_inv inv_inv_eq bij_vimage_eq_inv_image)\n  \nlemma Max_wrt_among_map_relation_bij:\n  assumes \"bij f\"\n  shows   \"f ` Max_wrt_among le A = Max_wrt_among (map_relation (inv f) le) (f ` A)\"\nproof (intro equalityI Max_wrt_among_map_relation_bij_subset assms)\n  interpret R: preorder_on \"f ` carrier\" \"map_relation (inv f) le\"\n    using preorder_on_map[of \"inv f\"] assms \n      by (simp add: bij_imp_bij_inv bij_vimage_eq_inv_image inv_inv_eq)\n  show \"Max_wrt_among (map_relation (inv f) le) (f ` A) \\<subseteq> f ` Max_wrt_among le A\"\n    unfolding Max_wrt_among_preorder R.Max_wrt_among_preorder \n    using assms bij_is_inj[OF assms]\n    by (auto simp: map_relation_def inv_f_f image_Int [symmetric])\nqed\n\nlemma Max_wrt_map_relation_bij:\n  \"bij f \\<Longrightarrow> f ` Max_wrt le = Max_wrt (map_relation (inv f) le)\"\nproof -\n  assume bij: \"bij f\"\n  interpret R: preorder_on \"f ` carrier\" \"map_relation (inv f) le\"\n    using preorder_on_map[of \"inv f\"] bij\n      by (simp add: bij_imp_bij_inv bij_vimage_eq_inv_image inv_inv_eq)\n  from bij show ?thesis\n    unfolding R.Max_wrt_preorder Max_wrt_preorder\n    by (auto simp: map_relation_def inv_f_f bij_is_inj)\nqed\n\nlemma Max_wrt_among_mono:\n  \"le x y \\<Longrightarrow> x \\<in> Max_wrt_among le A \\<Longrightarrow> y \\<in> A \\<Longrightarrow> y \\<in> Max_wrt_among le A\"\n  using assms not_outside by (auto simp: Max_wrt_among_preorder intro: trans)\n\nlemma Max_wrt_mono:\n  \"le x y \\<Longrightarrow> x \\<in> Max_wrt le \\<Longrightarrow> y \\<in> Max_wrt le\"\n  unfolding Max_wrt_def using Max_wrt_among_mono[of x y UNIV] by blast\n\nend\n\n\ncontext total_preorder_on\nbegin\n\nlemma Max_wrt_among_total_preorder:\n  \"Max_wrt_among le A = {x\\<in>carrier \\<inter> A. \\<forall>y\\<in>carrier \\<inter> A. le y x}\"\n  unfolding Max_wrt_among_preorder using total by blast\n\nlemma Max_wrt_total_preorder:\n  \"Max_wrt le = {x\\<in>carrier. \\<forall>y\\<in>carrier. le y x}\"\n  unfolding Max_wrt_preorder using total by blast\n\nlemma decompose_Max:\n  assumes A: \"A \\<subseteq> carrier\"\n  defines \"M \\<equiv> Max_wrt_among le A\"\n  shows   \"restrict_relation A le = (\\<lambda>x y. x \\<in> A \\<and> y \\<in> M \\<or> (y \\<notin> M \\<and> restrict_relation (A - M) le x y))\"\n  using A by (intro ext) (auto simp: M_def Max_wrt_among_total_preorder \n                            restrict_relation_def Int_absorb1 intro: trans)\n\nend\n\n\nsubsection \\<open>Weak rankings\\<close>\n\ninductive of_weak_ranking :: \"'alt set list \\<Rightarrow> 'alt relation\" where\n  \"i \\<le> j \\<Longrightarrow> i < length xs \\<Longrightarrow> j < length xs \\<Longrightarrow> x \\<in> xs ! i \\<Longrightarrow> y \\<in> xs ! j \\<Longrightarrow> \n     x \\<succeq>[of_weak_ranking xs] y\"\n\nlemma of_weak_ranking_Nil [simp]: \"of_weak_ranking [] = (\\<lambda>_ _. False)\"\n  by (intro ext) (simp add: of_weak_ranking.simps)\n  \nlemma of_weak_ranking_Cons:\n  \"x \\<succeq>[of_weak_ranking (z#zs)] y \\<longleftrightarrow> x \\<in> z \\<and> y \\<in> (\\<Union>set (z#zs)) \\<or> x \\<succeq>[of_weak_ranking zs] y\" \n      (is \"?lhs \\<longleftrightarrow> ?rhs\")\nproof \n  assume ?lhs\n  then obtain i j \n    where ij: \"i < length (z#zs)\" \"j < length (z#zs)\" \"i \\<le> j\" \"x \\<in> (z#zs) ! i\" \"y \\<in> (z#zs) ! j\"\n    by (blast elim: of_weak_ranking.cases)\n  thus ?rhs by (cases i; cases j) (force intro: of_weak_ranking.intros)+\nnext\n  assume ?rhs\n  thus ?lhs\n  proof (elim disjE conjE)\n    assume \"x \\<in> z\" \"y \\<in> \\<Union>set (z # zs)\"\n    then obtain j where \"j < length (z # zs)\" \"y \\<in> (z # zs) ! j\" \n      by (subst (asm) set_conv_nth) auto\n    with \\<open>x \\<in> z\\<close> show \"of_weak_ranking (z # zs) y x\" \n      by (intro of_weak_ranking.intros[of 0 j]) auto\n  next\n    assume \"of_weak_ranking zs y x\"\n    then obtain i j where \"i < length zs\" \"j < length zs\" \"i \\<le> j\" \"x \\<in> zs ! i\" \"y \\<in> zs ! j\"\n      by (blast elim: of_weak_ranking.cases)\n    thus \"of_weak_ranking (z # zs) y x\"\n      by (intro of_weak_ranking.intros[of \"Suc i\" \"Suc j\"]) auto\n  qed\nqed\n\nlemma of_weak_ranking_indifference:\n  assumes \"A \\<in> set xs\" \"x \\<in> A\" \"y \\<in> A\"\n  shows   \"x \\<preceq>[of_weak_ranking xs] y\"\n  using assms by (induction xs) (auto simp: of_weak_ranking_Cons)\n\n\nlemma of_weak_ranking_map:\n  \"map_relation f (of_weak_ranking xs) = of_weak_ranking (map (op -` f) xs)\"\n  by (intro ext, induction xs)\n     (simp_all add: map_relation_def of_weak_ranking_Cons)\n\nlemma of_weak_ranking_permute':\n  assumes \"f permutes (\\<Union>set xs)\"\n  shows   \"map_relation f (of_weak_ranking xs) = of_weak_ranking (map (op ` (inv f)) xs)\"\nproof -\n  have \"map_relation f (of_weak_ranking xs) = of_weak_ranking (map (op -` f) xs)\"\n    by (rule of_weak_ranking_map)\n  also from assms have \"map (op -` f) xs = map (op ` (inv f)) xs\"\n    by (intro map_cong refl) (simp_all add: bij_vimage_eq_inv_image permutes_bij)\n  finally show ?thesis .\nqed \n\nlemma of_weak_ranking_permute:\n  assumes \"f permutes (\\<Union>set xs)\"\n  shows   \"of_weak_ranking (map (op ` f) xs) = map_relation (inv f) (of_weak_ranking xs)\"\n  using of_weak_ranking_permute'[OF permutes_inv[OF assms]] assms\n  by (simp add: inv_inv_eq permutes_bij)\n\ndefinition is_weak_ranking where\n  \"is_weak_ranking xs \\<longleftrightarrow> ({} \\<notin> set xs) \\<and>\n     (\\<forall>i j. i < length xs \\<and> j < length xs \\<and> i \\<noteq> j \\<longrightarrow> xs ! i \\<inter> xs ! j = {})\"\n\ndefinition is_finite_weak_ranking where\n  \"is_finite_weak_ranking xs \\<longleftrightarrow> is_weak_ranking xs \\<and> (\\<forall>x\\<in>set xs. finite x)\"\n\ndefinition weak_ranking :: \"'alt relation \\<Rightarrow> 'alt set list\" where\n  \"weak_ranking R = (SOME xs. is_weak_ranking xs \\<and> R = of_weak_ranking xs)\"\n\n\n\nlemma is_weak_ranking_nonempty: \"is_weak_ranking xs \\<Longrightarrow> {} \\<notin> set xs\"\n  by (simp add: is_weak_ranking_def) \n     \n\n\nlemma is_weak_ranking_map_inj:\n  assumes \"is_weak_ranking xs\" \"inj_on f (\\<Union>set xs)\"\n  shows   \"is_weak_ranking (map (op ` f) xs)\"\n  using assms by (auto simp: is_weak_ranking_iff distinct_map inj_on_image disjoint_image)\n\nlemma of_weak_ranking_rev [simp]:\n  \"of_weak_ranking (rev xs) (x::'a) y \\<longleftrightarrow> of_weak_ranking xs y x\"\nproof -\n  have \"of_weak_ranking (rev xs) y x\" if \"of_weak_ranking xs x y\" for xs and x y :: 'a\n  proof -\n    from that obtain i j where \"i < length xs\" \"j < length xs\" \"x \\<in> xs ! i\" \"y \\<in> xs ! j\" \"i \\<ge> j\"\n      by (elim of_weak_ranking.cases) simp_all\n    thus ?thesis\n      by (intro of_weak_ranking.intros[of \"length xs - i - 1\" \"length xs - j - 1\"] diff_le_mono2)\n         (auto simp: diff_le_mono2 rev_nth)\n  qed\n  from this[of xs y x] this[of \"rev xs\" x y] show ?thesis by (intro iffI) simp_all\nqed\n\n\nlemma is_weak_ranking_Nil [simp]: \"is_weak_ranking []\"\n  by (auto simp: is_weak_ranking_def)\n\nlemma is_finite_weak_ranking_Nil [simp]: \"is_finite_weak_ranking []\"\n  by (auto simp: is_finite_weak_ranking_def)\n\nlemma is_weak_ranking_Cons_empty [simp]:\n  \"\\<not>is_weak_ranking ({} # xs)\" by (simp add: is_weak_ranking_def)\n\nlemma is_finite_weak_ranking_Cons_empty [simp]:\n  \"\\<not>is_finite_weak_ranking ({} # xs)\" by (simp add: is_finite_weak_ranking_def)\n  \nlemma is_weak_ranking_singleton [simp]:\n  \"is_weak_ranking [x] \\<longleftrightarrow> x \\<noteq> {}\" \n  by (auto simp add: is_weak_ranking_def)\n\nlemma is_finite_weak_ranking_singleton [simp]:\n  \"is_finite_weak_ranking [x] \\<longleftrightarrow> x \\<noteq> {} \\<and> finite x\" \n  by (auto simp add: is_finite_weak_ranking_def)\n  \nlemma is_weak_ranking_append:\n  \"is_weak_ranking (xs @ ys) \\<longleftrightarrow> \n      is_weak_ranking xs \\<and> is_weak_ranking ys \\<and>\n      (set xs \\<inter> set ys = {} \\<and> (\\<Union>set xs) \\<inter> (\\<Union>set ys) = {})\"\n  by (simp only: is_weak_ranking_iff)\n     (auto dest: disjointD disjoint_unionD1 disjoint_unionD2 intro: disjoint_union)\n\nlemma is_weak_ranking_Cons:\n  \"is_weak_ranking (x # xs) \\<longleftrightarrow> \n      x \\<noteq> {} \\<and> is_weak_ranking xs \\<and> x \\<inter> \\<Union>set xs = {}\"\n  using is_weak_ranking_append[of \"[x]\" xs] by auto\n\nlemma is_finite_weak_ranking_Cons:\n  \"is_finite_weak_ranking (x # xs) \\<longleftrightarrow> \n      x \\<noteq> {} \\<and> finite x \\<and> is_finite_weak_ranking xs \\<and> x \\<inter> \\<Union>set xs = {}\"\n  by (auto simp add: is_finite_weak_ranking_def is_weak_ranking_Cons)\n\nprimrec is_weak_ranking_aux where\n  \"is_weak_ranking_aux A [] \\<longleftrightarrow> True\"\n| \"is_weak_ranking_aux A (x#xs) \\<longleftrightarrow> x \\<noteq> {} \\<and>\n       A \\<inter> x = {} \\<and> is_weak_ranking_aux (A \\<union> x) xs\"\n\n\nlemma is_weak_ranking_aux:\n  \"is_weak_ranking_aux A xs \\<longleftrightarrow> A \\<inter> (\\<Union>set xs) = {} \\<and> is_weak_ranking xs\"\n  by (induction xs arbitrary: A) (auto simp: is_weak_ranking_Cons)\n\nlemma is_weak_ranking_code [code]:\n  \"is_weak_ranking xs \\<longleftrightarrow> is_weak_ranking_aux {} xs\"\n  by (subst is_weak_ranking_aux) auto\n\nlemma of_weak_ranking_altdef:\n  assumes \"is_weak_ranking xs\" \"x \\<in> \\<Union>set xs\" \"y \\<in> \\<Union>set xs\"\n  shows   \"of_weak_ranking xs x y \\<longleftrightarrow> \n             find_index (op \\<in> x) xs \\<ge> find_index (op \\<in> y) xs\"\nproof -\n from assms \n    have A: \"find_index (op \\<in> x) xs < length xs\" \"find_index (op \\<in> y) xs < length xs\"\n    by (simp_all add: find_index_less_size_conv)\n from this[THEN nth_find_index] \n    have B: \"x \\<in> xs ! find_index (op \\<in> x) xs\" \"y \\<in> xs ! find_index (op \\<in> y) xs\" .\n  show ?thesis\n  proof\n    assume \"of_weak_ranking xs x y\"\n    then obtain i j where ij: \"j \\<le> i\" \"i < length xs\" \"j < length xs\" \"x \\<in> xs ! i\" \"y \\<in> xs !j\"\n      by (cases rule: of_weak_ranking.cases) simp_all\n    with A B have \"i = find_index (op \\<in> x) xs\" \"j = find_index (op \\<in> y) xs\"\n      using assms(1) unfolding is_weak_ranking_def by blast+\n    with ij show \"find_index (op \\<in> x) xs \\<ge> find_index (op \\<in> y) xs\" by simp\n  next\n    assume \"find_index (op \\<in> x) xs \\<ge> find_index (op \\<in> y) xs\"\n    from this A(2,1) B(2,1) show \"of_weak_ranking xs x y\"\n      by (rule of_weak_ranking.intros)\n  qed\nqed\n\n  \n\n\nlemma restrict_relation_of_weak_ranking_Cons:\n  assumes \"is_weak_ranking (A # As)\"\n  shows   \"restrict_relation (\\<Union>set As) (of_weak_ranking (A # As)) = of_weak_ranking As\"\nproof -\n  from assms interpret R: total_preorder_on \"\\<Union>set As\" \"of_weak_ranking As\"\n    by (intro total_preorder_of_weak_ranking)\n       (simp_all add: is_weak_ranking_Cons)\n  from assms show ?thesis using R.not_outside\n    by (intro ext) (auto simp: restrict_relation_def of_weak_ranking_Cons\n                     is_weak_ranking_Cons)\nqed\n\n\n\n\nlemmas of_weak_ranking_wf = \n  total_preorder_of_weak_ranking is_weak_ranking_code insert_commute\n\n\n(* Test *)\nlemma \"total_preorder_on {1,2,3,4::nat} (of_weak_ranking [{1,3},{2},{4}])\"\n  by (simp add: of_weak_ranking_wf)\n\n\ncontext\n  fixes x :: \"'alt set\" and xs :: \"'alt set list\"\n  assumes wf: \"is_weak_ranking (x#xs)\"\nbegin\n\ninterpretation R: total_preorder_on \"\\<Union>set (x#xs)\" \"of_weak_ranking (x#xs)\"\n  by (intro total_preorder_of_weak_ranking) (simp_all add: wf)\n\nlemma of_weak_ranking_imp_in_set:\n  assumes \"of_weak_ranking xs a b\"\n  shows   \"a \\<in> \\<Union>set xs\" \"b \\<in> \\<Union>set xs\"\n  using assms by (fastforce elim!: of_weak_ranking.cases)+\n\nlemma of_weak_ranking_Cons':\n  assumes \"a \\<in> \\<Union>set (x#xs)\" \"b \\<in> \\<Union>set (x#xs)\"\n  shows   \"of_weak_ranking (x#xs) a b \\<longleftrightarrow> b \\<in> x \\<or> (a \\<notin> x \\<and> of_weak_ranking xs a b)\"\nproof\n  assume \"of_weak_ranking (x # xs) a b\"\n  with wf of_weak_ranking_imp_in_set[of a b] \n    show \"(b \\<in> x \\<or>  a \\<notin> x \\<and> of_weak_ranking xs a b)\"\n    by (auto simp: is_weak_ranking_Cons of_weak_ranking_Cons)\nnext\n  assume \"b \\<in> x \\<or> a \\<notin> x \\<and> of_weak_ranking xs a b\"\n  with assms show \"of_weak_ranking (x#xs) a b\"\n    by (fastforce simp: of_weak_ranking_Cons)\nqed\n\nlemma Max_wrt_among_of_weak_ranking_Cons1:\n  assumes \"x \\<inter> A = {}\"\n  shows   \"Max_wrt_among (of_weak_ranking (x#xs)) A = Max_wrt_among (of_weak_ranking xs) A\"\nproof -\n  from wf interpret R': total_preorder_on \"\\<Union>set xs\" \"of_weak_ranking xs\"\n    by (intro total_preorder_of_weak_ranking) (simp_all add: is_weak_ranking_Cons)\n  from assms show ?thesis\n    by (auto simp: R.Max_wrt_among_total_preorder\n          R'.Max_wrt_among_total_preorder of_weak_ranking_Cons)\nqed\n\nlemma Max_wrt_among_of_weak_ranking_Cons2:\n  assumes \"x \\<inter> A \\<noteq> {}\"\n  shows   \"Max_wrt_among (of_weak_ranking (x#xs)) A = x \\<inter> A\"\nproof -\n  from wf interpret R': total_preorder_on \"\\<Union>set xs\" \"of_weak_ranking xs\"\n    by (intro total_preorder_of_weak_ranking) (simp_all add: is_weak_ranking_Cons)\n  from assms obtain a where \"a \\<in> x \\<inter> A\" by blast\n  with wf R'.not_outside(1)[of a] show ?thesis\n    by (auto simp: R.Max_wrt_among_total_preorder is_weak_ranking_Cons\n          R'.Max_wrt_among_total_preorder of_weak_ranking_Cons)\nqed\n\nlemma Max_wrt_among_of_weak_ranking_Cons:\n  \"Max_wrt_among (of_weak_ranking (x#xs)) A =\n     (if x \\<inter> A = {} then Max_wrt_among (of_weak_ranking xs) A else x \\<inter> A)\"\n  using Max_wrt_among_of_weak_ranking_Cons1 Max_wrt_among_of_weak_ranking_Cons2 by simp\n\nlemma Max_wrt_of_weak_ranking_Cons:\n  \"Max_wrt (of_weak_ranking (x#xs)) = x\"\n  using wf by (simp add: is_weak_ranking_Cons Max_wrt_def Max_wrt_among_of_weak_ranking_Cons)\n\nend\n\nlemma Max_wrt_of_weak_ranking:\n  assumes \"is_weak_ranking xs\"\n  shows   \"Max_wrt (of_weak_ranking xs) = (if xs = [] then {} else hd xs)\"\nproof (cases xs)\n  case Nil\n  hence \"of_weak_ranking xs = (\\<lambda>_ _. False)\" by (intro ext) simp_all\n  with Nil show ?thesis by (simp add: Max_wrt_def Max_wrt_among_def)\nnext\n  case (Cons x xs')\n  with assms show ?thesis by (simp add: Max_wrt_of_weak_ranking_Cons)\nqed\n\n\nlocale finite_total_preorder_on = total_preorder_on +\n  assumes finite_carrier [intro]: \"finite carrier\"\nbegin\n\nlemma finite_total_preorder_on_map:\n  assumes \"finite (f -` carrier)\"\n  shows   \"finite_total_preorder_on (f -` carrier) (map_relation f le)\"\nproof -\n  interpret R': total_preorder_on \"f -` carrier\" \"map_relation f le\"\n    using total_preorder_on_map[of f] .\n  from assms show ?thesis by unfold_locales simp\nqed\n\nfunction weak_ranking_aux :: \"'a set \\<Rightarrow> 'a set list\" where\n  \"weak_ranking_aux {} = []\"\n| \"A \\<noteq> {} \\<Longrightarrow> A \\<subseteq> carrier \\<Longrightarrow> weak_ranking_aux A =\n     Max_wrt_among le A # weak_ranking_aux (A - Max_wrt_among le A)\"\n| \"\\<not>(A \\<subseteq> carrier) \\<Longrightarrow> weak_ranking_aux A = undefined\"\nby blast simp_all\ntermination proof (relation \"Wellfounded.measure card\")\n  fix A\n  let ?B = \"Max_wrt_among le A\"\n  assume A: \"A \\<noteq> {}\" \"A \\<subseteq> carrier\"\n  moreover from A(2) have \"finite A\" by (rule finite_subset) blast\n  moreover from A have \"?B \\<noteq> {}\" \"?B \\<subseteq> A\"\n    by (intro Max_wrt_among_nonempty Max_wrt_among_subset; force)+\n  ultimately have \"card (A - ?B) < card A\"\n    by (intro psubset_card_mono) auto\n  thus \"(A - ?B, A) \\<in> measure card\" by simp\nqed simp_all\n\n(* TODO Move *)\nlemma Int_emptyI: \"(\\<And>x. x \\<in> A \\<Longrightarrow> x \\<in> B \\<Longrightarrow> False) \\<Longrightarrow> A \\<inter> B = {}\"\n  by blast\n\nlemma weak_ranking_aux_Union:\n  \"A \\<subseteq> carrier \\<Longrightarrow> \\<Union>set (weak_ranking_aux A) = A\"\nproof (induction A rule: weak_ranking_aux.induct [case_names empty nonempty])\n  case (nonempty A)\n  with Max_wrt_among_subset[of A] show ?case by auto\nqed simp_all\n\nlemma weak_ranking_aux_wf:\n  \"A \\<subseteq> carrier \\<Longrightarrow> is_weak_ranking (weak_ranking_aux A)\"\nproof (induction A rule: weak_ranking_aux.induct [case_names empty nonempty])\n  case (nonempty A)\n  have \"is_weak_ranking (Max_wrt_among le A # weak_ranking_aux (A - Max_wrt_among le A))\"\n    unfolding is_weak_ranking_Cons\n  proof (intro conjI)\n    from nonempty.prems nonempty.hyps show \"Max_wrt_among le A \\<noteq> {}\"\n      by (intro Max_wrt_among_nonempty) auto\n  next\n    from nonempty.prems show \"is_weak_ranking (weak_ranking_aux (A - Max_wrt_among le A))\"\n      by (intro nonempty.IH) blast\n  next\n    from nonempty.prems nonempty.hyps have \"Max_wrt_among le A \\<noteq> {}\"\n      by (intro Max_wrt_among_nonempty) auto\n    moreover from nonempty.prems \n      have \"\\<Union>set (weak_ranking_aux (A - Max_wrt_among le A)) = A - Max_wrt_among le A\"\n      by (intro weak_ranking_aux_Union) auto\n    ultimately show \"Max_wrt_among le A \\<inter> \\<Union>set (weak_ranking_aux (A - Max_wrt_among le A)) = {}\"\n      by blast+\n  qed\n  with nonempty.prems nonempty.hyps show ?case by simp\nqed simp_all    \n\nlemma of_weak_ranking_weak_ranking_aux':\n  assumes \"A \\<subseteq> carrier\" \"x \\<in> A\" \"y \\<in> A\"\n  shows   \"of_weak_ranking (weak_ranking_aux A) x y \\<longleftrightarrow> restrict_relation A le x y\"\nusing assms\nproof (induction A rule: weak_ranking_aux.induct [case_names empty nonempty])\n  case (nonempty A)\n  def M \\<equiv> \"Max_wrt_among le A\"\n  from nonempty.prems nonempty.hyps have M: \"M \\<subseteq> A\" unfolding M_def\n    by (intro Max_wrt_among_subset)\n  from nonempty.prems have in_MD: \"le x y\" if \"x \\<in> A\" \"y \\<in> M\" for x y\n    using that unfolding M_def Max_wrt_among_total_preorder\n    by (auto simp: Int_absorb1)\n  from nonempty.prems have in_MI: \"x \\<in> M\" if \"y \\<in> M\" \"x \\<in> A\"  \"le y x\" for x y\n    using that unfolding M_def Max_wrt_among_total_preorder\n    by (auto simp: Int_absorb1 intro: trans)\n\n  from nonempty.prems nonempty.hyps\n    have IH: \"of_weak_ranking (weak_ranking_aux (A - M)) x y = \n                restrict_relation (A - M) le x y\" if \"x \\<notin> M\" \"y \\<notin> M\"\n       using that unfolding M_def by (intro nonempty.IH) auto\n  from nonempty.prems \n    interpret R': total_preorder_on \"A - M\" \"of_weak_ranking (weak_ranking_aux (A - M))\"\n    by (intro total_preorder_of_weak_ranking weak_ranking_aux_wf weak_ranking_aux_Union) auto\n  \n  from nonempty.prems nonempty.hyps M weak_ranking_aux_Union[of A] R'.not_outside[of x y] \n    show ?case\n    by (cases \"x \\<in> M\"; cases \"y \\<in> M\")\n       (auto simp: restrict_relation_def of_weak_ranking_Cons IH M_def [symmetric]\n             intro: in_MD dest: in_MI)\nqed simp_all\n\nlemma of_weak_ranking_weak_ranking_aux:\n  \"of_weak_ranking (weak_ranking_aux carrier) = le\"\nproof (intro ext)\n  fix x y\n  have \"is_weak_ranking (weak_ranking_aux carrier)\" by (rule weak_ranking_aux_wf) simp\n  then interpret R: total_preorder_on carrier \"of_weak_ranking (weak_ranking_aux carrier)\"\n    by (intro total_preorder_of_weak_ranking weak_ranking_aux_wf weak_ranking_aux_Union)\n       (simp_all add: weak_ranking_aux_Union)\n\n  show \"of_weak_ranking (weak_ranking_aux carrier) x y = le x y\"\n  proof (cases \"x \\<in> carrier \\<and> y \\<in> carrier\")\n    case True\n    thus ?thesis\n      using of_weak_ranking_weak_ranking_aux'[of carrier x y]  by simp\n  next\n    case False\n    with R.not_outside have \"of_weak_ranking (weak_ranking_aux carrier) x y = False\"\n      by auto\n    also from not_outside False have \"\\<dots> = le x y\" by auto\n    finally show ?thesis .\n  qed\nqed\n\nlemma weak_ranking_aux_unique':\n  assumes \"\\<Union>set As \\<subseteq> carrier\" \"is_weak_ranking As\"\n          \"of_weak_ranking As = restrict_relation (\\<Union>set As) le\"\n  shows   \"As = weak_ranking_aux (\\<Union>set As)\"\nusing assms\nproof (induction As)\n  case (Cons A As)\n  have \"restrict_relation (\\<Union>set As) (of_weak_ranking (A # As)) = of_weak_ranking As\"\n    by (intro restrict_relation_of_weak_ranking_Cons Cons.prems)\n  also have eq1: \"of_weak_ranking (A # As) = restrict_relation (\\<Union>set (A # As)) le\" by fact\n  finally have eq: \"of_weak_ranking As = restrict_relation (\\<Union>set As) le\"\n    by (simp add: Int_absorb2)\n  with Cons.prems have eq2: \"weak_ranking_aux (\\<Union>set As) = As\"\n    by (intro sym [OF Cons.IH]) (auto simp: is_weak_ranking_Cons)\n\n  from eq1 have \n    \"Max_wrt_among le (\\<Union>set (A # As)) = \n       Max_wrt_among (of_weak_ranking (A#As)) (\\<Union>set (A#As))\"\n    by (intro Max_wrt_among_cong) simp_all\n  also from Cons.prems have \"\\<dots> = A\"\n    by (subst Max_wrt_among_of_weak_ranking_Cons2)\n       (simp_all add: is_weak_ranking_Cons)\n  finally have Max: \"Max_wrt_among le (\\<Union>set (A # As)) = A\" .\n\n  moreover from Cons.prems have \"A \\<noteq> {}\" by (simp add: is_weak_ranking_Cons)\n  ultimately have \"weak_ranking_aux (\\<Union>set (A # As)) = A # weak_ranking_aux (A \\<union> \\<Union>set As - A)\" \n    using Cons.prems by simp\n  also from Cons.prems have \"A \\<union> \\<Union>set As - A = \\<Union>set As\"\n    by (auto simp: is_weak_ranking_Cons)\n  also from eq2 have \"weak_ranking_aux \\<dots> = As\" .\n  finally show ?case ..\nqed simp_all\n\nlemma weak_ranking_aux_unique:\n  assumes \"is_weak_ranking As\" \"of_weak_ranking As = le\"\n  shows   \"As = weak_ranking_aux carrier\"\nproof -\n  interpret R: total_preorder_on \"\\<Union>set As\" \"of_weak_ranking As\"\n    by (intro total_preorder_of_weak_ranking assms) simp_all\n  from assms have \"x \\<in> (\\<Union>set As) \\<longleftrightarrow> x \\<in> carrier\" for x\n    using R.not_outside not_outside R.refl[of x] refl[of x]\n    by blast\n  hence eq: \"\\<Union>set As = carrier\" by blast\n  from assms eq have \"As = weak_ranking_aux (\\<Union>set As)\"\n    by (intro weak_ranking_aux_unique') simp_all\n  with eq show ?thesis by simp\nqed\n\nlemma weak_ranking_total_preorder:\n  \"is_weak_ranking (weak_ranking le)\" \"of_weak_ranking (weak_ranking le) = le\"\nproof -\n  from weak_ranking_aux_wf[of carrier] of_weak_ranking_weak_ranking_aux\n    have \"\\<exists>x. is_weak_ranking x \\<and> le = of_weak_ranking x\" by auto\n  hence \"is_weak_ranking (weak_ranking le) \\<and> le = of_weak_ranking (weak_ranking le)\"\n    unfolding weak_ranking_def by (rule someI_ex)\n  thus \"is_weak_ranking (weak_ranking le)\" \"of_weak_ranking (weak_ranking le) = le\"\n    by simp_all\nqed\n\nlemma weak_ranking_altdef:\n  \"weak_ranking le = weak_ranking_aux carrier\"\n  by (intro weak_ranking_aux_unique weak_ranking_total_preorder)\n\nlemma weak_ranking_Union: \"(\\<Union>set (weak_ranking le)) = carrier\"\n  by (simp add: weak_ranking_altdef weak_ranking_aux_Union)\n\nlemma weak_ranking_unique:\n  assumes \"is_weak_ranking As\" \"of_weak_ranking As = le\"\n  shows   \"As = weak_ranking le\"\n  using assms unfolding weak_ranking_altdef by (rule weak_ranking_aux_unique)\n\nlemma weak_ranking_permute:\n  assumes \"f permutes carrier\"\n  shows   \"weak_ranking (map_relation (inv f) le) = map (op ` f) (weak_ranking le)\"\nproof -\n  from assms have \"inv f -` carrier = carrier\"\n    by (simp add: permutes_vimage permutes_inv)\n  then interpret R: finite_total_preorder_on \"inv f -` carrier\" \"map_relation (inv f) le\"\n    by (intro finite_total_preorder_on_map) (simp_all add: finite_carrier)\n  from assms have \"is_weak_ranking (map (op ` f) (weak_ranking le))\"\n    by (intro is_weak_ranking_map_inj) \n       (simp_all add: weak_ranking_total_preorder permutes_inj_on)\n  with assms show ?thesis\n    by (intro sym[OF R.weak_ranking_unique])\n       (simp_all add: of_weak_ranking_permute weak_ranking_Union weak_ranking_total_preorder)\nqed\n\nlemma weak_ranking_index_unique:\n  assumes \"is_weak_ranking xs\" \"i < length xs\" \"j < length xs\" \"x \\<in> xs ! i\" \"x \\<in> xs ! j\"\n  shows   \"i = j\"\n  using assms unfolding is_weak_ranking_def by auto\n\nlemma weak_ranking_index_unique':\n  assumes \"is_weak_ranking xs\" \"i < length xs\" \"x \\<in> xs ! i\"\n  shows   \"i = find_index (op \\<in> x) xs\"\n  using assms find_index_less_size_conv nth_mem\n  by (intro weak_ranking_index_unique[OF assms(1,2) _ assms(3)]\n        nth_find_index[of \"op \\<in> x\"]) blast+\n\nlemma weak_ranking_eqclass1:\n  assumes \"A \\<in> set (weak_ranking le)\" \"x \\<in> A\" \"y \\<in> A\"\n  shows   \"le x y\"\nproof -\n  from assms obtain i where \"weak_ranking le ! i = A\" \"i < length (weak_ranking le)\" \n    by (auto simp: set_conv_nth)\n  with assms have \"of_weak_ranking (weak_ranking le) x y\"\n    by (intro of_weak_ranking.intros[of i i]) auto\n  thus ?thesis by (simp add: weak_ranking_total_preorder)\nqed\n\nlemma weak_ranking_eqclass2:\n  assumes A: \"A \\<in> set (weak_ranking le)\" \"x \\<in> A\" and le: \"le x y\" \"le y x\"\n  shows   \"y \\<in> A\"\nproof -\n  def xs \\<equiv> \"weak_ranking le\"\n  have wf: \"is_weak_ranking xs\" by (simp add: xs_def weak_ranking_total_preorder)\n  let ?le' = \"of_weak_ranking xs\"\n  from le have le': \"?le' x y\" \"?le' y x\" by (simp_all add: weak_ranking_total_preorder xs_def)\n  from le'(1) obtain i j\n    where ij: \"j \\<le> i\" \"i < length xs\" \"j < length xs\" \"x \\<in> xs ! i\" \"y \\<in> xs ! j\"\n    by (cases rule: of_weak_ranking.cases)\n  from le'(2) obtain i' j'\n    where i'j': \"j' \\<le> i'\" \"i' < length xs\" \"j' < length xs\" \"x \\<in> xs ! j'\" \"y \\<in> xs ! i'\"\n    by (cases rule: of_weak_ranking.cases)\n  from ij i'j' have eq: \"i = j'\" \"j = i'\"\n    by (intro weak_ranking_index_unique[OF wf]; simp)+\n  moreover from A obtain k where k: \"k < length xs\" \"A = xs ! k\" \n    by (auto simp: xs_def set_conv_nth)\n  ultimately have \"k = i\" using ij i'j' A\n    by (intro weak_ranking_index_unique[OF wf, of _ _ x]) auto\n  with ij i'j' k eq show ?thesis by (auto simp: xs_def)\nqed\n\nlemma hd_weak_ranking:\n  assumes \"x \\<in> hd (weak_ranking le)\" \"y \\<in> carrier\"\n  shows   \"le y x\"\nproof -\n  from weak_ranking_Union assms obtain i\n    where \"i < length (weak_ranking le)\" \"y \\<in> weak_ranking le ! i\"\n    by (auto simp: set_conv_nth)\n  moreover from assms(2) weak_ranking_Union have \"weak_ranking le \\<noteq> []\" by auto\n  ultimately have \"of_weak_ranking (weak_ranking le) y x\" using assms(1)\n    by (intro of_weak_ranking.intros[of 0 i]) (auto simp: hd_conv_nth)\n  thus ?thesis by (simp add: weak_ranking_total_preorder)\nqed\n\nlemma last_weak_ranking:\n  assumes \"x \\<in> last (weak_ranking le)\" \"y \\<in> carrier\"\n  shows   \"le x y\"\nproof -\n  from weak_ranking_Union assms obtain i\n    where \"i < length (weak_ranking le)\" \"y \\<in> weak_ranking le ! i\"\n    by (auto simp: set_conv_nth)\n  moreover from assms(2) weak_ranking_Union have \"weak_ranking le \\<noteq> []\" by auto\n  ultimately have \"of_weak_ranking (weak_ranking le) x y\" using assms(1)\n    by (intro of_weak_ranking.intros[of i \"length (weak_ranking le) - 1\"])\n       (auto simp: last_conv_nth)\n  thus ?thesis by (simp add: weak_ranking_total_preorder)\nqed\n\ntext \\<open>\n  The index in weak ranking of a given alternative. An element with index 0 is \n  first-ranked; larger indices correspond to less-preferred alternatives.\n\\<close>\ndefinition weak_ranking_index :: \"'a \\<Rightarrow> nat\" where\n  \"weak_ranking_index x = find_index (\\<lambda>A. x \\<in> A) (weak_ranking le)\"\n\nlemma nth_weak_ranking_index:\n  assumes \"x \\<in> carrier\"\n  shows   \"weak_ranking_index x < length (weak_ranking le)\" \n          \"x \\<in> weak_ranking le ! weak_ranking_index x\"\nproof -\n  from assms weak_ranking_Union show \"weak_ranking_index x < length (weak_ranking le)\"\n     unfolding weak_ranking_index_def by (auto simp add: find_index_less_size_conv)\n  thus \"x \\<in> weak_ranking le ! weak_ranking_index x\" unfolding weak_ranking_index_def\n    by (rule nth_find_index)\nqed\n\nlemma ranking_index_eqI:\n  \"i < length (weak_ranking le) \\<Longrightarrow> x \\<in> weak_ranking le ! i \\<Longrightarrow> weak_ranking_index x = i\"\n  using weak_ranking_index_unique'[of \"weak_ranking le\" i x]\n  by (simp add: weak_ranking_index_def weak_ranking_total_preorder)\n\nlemma ranking_index_le_iff [simp]:\n  assumes \"x \\<in> carrier\" \"y \\<in> carrier\"\n  shows   \"weak_ranking_index x \\<ge> weak_ranking_index y \\<longleftrightarrow> le x y\"\nproof -\n  have \"le x y \\<longleftrightarrow> of_weak_ranking (weak_ranking le) x y\"\n    by (simp add: weak_ranking_total_preorder)\n  also have \"\\<dots> \\<longleftrightarrow> weak_ranking_index x \\<ge> weak_ranking_index y\"\n  proof\n    assume \"weak_ranking_index x \\<ge> weak_ranking_index y\"\n    thus \"of_weak_ranking (weak_ranking le) x y\"\n      by (rule of_weak_ranking.intros) (simp_all add: nth_weak_ranking_index assms)\n  next\n    assume \"of_weak_ranking (weak_ranking le) x y\"\n    then obtain i j where \n      \"i \\<le> j\" \"i < length (weak_ranking le)\" \"j < length (weak_ranking le)\"\n      \"x \\<in> weak_ranking le ! j\" \"y \\<in> weak_ranking le ! i\"\n      by (elim of_weak_ranking.cases) blast\n    with ranking_index_eqI[of i] ranking_index_eqI[of j]\n      show \"weak_ranking_index x \\<ge> weak_ranking_index y\" by simp\n  qed\n  finally show ?thesis ..\nqed\n\nend\n\nlemmas of_weak_ranking_weak_ranking = \n  finite_total_preorder_on.weak_ranking_total_preorder(2)\n\nlemma finite_total_preorder_on_iff:\n  \"finite_total_preorder_on A R \\<longleftrightarrow> total_preorder_on A R \\<and> finite A\"\n  by (simp add: finite_total_preorder_on_def finite_total_preorder_on_axioms_def)\n\nlemma finite_total_preorder_of_weak_ranking:\n  assumes \"\\<Union>set xs = A\" \"is_finite_weak_ranking xs\"\n  shows   \"finite_total_preorder_on A (of_weak_ranking xs)\"\nproof -\n  from assms(2) have \"is_weak_ranking xs\" by (simp add: is_finite_weak_ranking_def)\n  from assms(1) and this interpret total_preorder_on A \"of_weak_ranking xs\"\n    by (rule total_preorder_of_weak_ranking)\n  from assms(2) show ?thesis\n    by unfold_locales (simp add: assms(1)[symmetric] is_finite_weak_ranking_def)\nqed  \n\nlemma weak_ranking_of_weak_ranking:\n  assumes \"is_finite_weak_ranking xs\"\n  shows   \"weak_ranking (of_weak_ranking xs) = xs\"\nproof -\n  from assms interpret finite_total_preorder_on \"\\<Union>set xs\" \"of_weak_ranking xs\"\n    by (intro finite_total_preorder_of_weak_ranking) simp_all\n  from assms show ?thesis\n    by (intro sym[OF weak_ranking_unique]) (simp_all add: is_finite_weak_ranking_def)\nqed\n\n\nlemma weak_ranking_eqD:\n  assumes \"finite_total_preorder_on alts R1\"\n  assumes \"finite_total_preorder_on alts R2\"\n  assumes \"weak_ranking R1 = weak_ranking R2\"\n  shows   \"R1 = R2\"\nproof -\n  from assms have \"of_weak_ranking (weak_ranking R1) = of_weak_ranking (weak_ranking R2)\" by simp\n  with assms(1,2) show ?thesis by (simp add: of_weak_ranking_weak_ranking)\nqed\n\nlemma weak_ranking_eq_iff:\n  assumes \"finite_total_preorder_on alts R1\"\n  assumes \"finite_total_preorder_on alts R2\"\n  shows   \"weak_ranking R1 = weak_ranking R2 \\<longleftrightarrow> R1 = R2\"\n  using assms weak_ranking_eqD by auto\n\n\ndefinition preferred_alts :: \"'alt relation \\<Rightarrow> 'alt \\<Rightarrow> 'alt set\" where\n  \"preferred_alts R x = {y. y \\<succeq>[R] x}\"\n\nlemma (in preorder_on) preferred_alts_altdef:\n  \"preferred_alts le x = {y\\<in>carrier. y \\<succeq>[le] x}\"\n  by (auto simp: preferred_alts_def intro: not_outside)\n\n\nsubsection \\<open>Rankings\\<close>\n\n(* TODO: Extend theory on rankings. Can probably mostly be based on\n   existing theory on weak rankings. *)\n\ndefinition ranking :: \"'a relation \\<Rightarrow> 'a list\" where\n  \"ranking R = map the_elem (weak_ranking R)\"\n\nlocale finite_linorder_on = linorder_on +\n  assumes finite_carrier [intro]: \"finite carrier\"\nbegin\n\nsublocale finite_total_preorder_on carrier le\n  by unfold_locales (fact finite_carrier)\n\nlemma singleton_weak_ranking:\n  assumes \"A \\<in> set (weak_ranking le)\"\n  shows   \"is_singleton A\"\nproof (rule is_singletonI')\n  from assms show \"A \\<noteq> {}\"\n    using weak_ranking_total_preorder(1) is_weak_ranking_iff by auto\nnext\n  fix x y assume \"x \\<in> A\" \"y \\<in> A\"\n  with assms \n    have \"x \\<preceq>[of_weak_ranking (weak_ranking le)] y\" \"y \\<preceq>[of_weak_ranking (weak_ranking le)] x\"\n    by (auto intro!: of_weak_ranking_indifference)\n  with weak_ranking_total_preorder(2) \n    show \"x = y\" by (intro antisymmetric) simp_all\nqed\n\nlemma weak_ranking_ranking: \"weak_ranking le = map (\\<lambda>x. {x}) (ranking le)\"\n  unfolding ranking_def map_map o_def\nproof (rule sym, rule map_idI)\n  fix A assume \"A \\<in> set (weak_ranking le)\"\n  hence \"is_singleton A\" by (rule singleton_weak_ranking)\n  thus \"{the_elem A} = A\" by (auto elim: is_singletonE)\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/Order_Predicates.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8438951143326726, "lm_q2_score": 0.8333245911726381, "lm_q1q2_score": 0.7032385511438611}}
{"text": "(*  Title:      CRR_Model.thy\n    Author:     Mnacho Echenim, Univ. Grenoble Alpes\n*)\n\nsection \\<open>The Cox Ross Rubinstein model\\<close>\n\ntext \\<open>This section defines the Cox-Ross-Rubinstein model of a financial market, and charcterizes a risk-neutral\nprobability space for this market. This, together with the proof that every derivative is attainable, permits to\nobtain a formula to explicitely compute the fair price of any derivative.\\<close>\n\ntheory CRR_Model imports Fair_Price\n\nbegin\n\nlocale CRR_hyps = prob_grw + rsk_free_asset +\n  fixes stk\nassumes stocks: \"stocks Mkt = {stk, risk_free_asset}\"\n  and stk_price: \"prices Mkt stk = geom_proc\"\n  and S0_positive: \"0 < init\"\n  and down_positive: \"0 < d\" and down_lt_up: \"d < u\"\n  and psgt: \"0 < p\"\n  and pslt: \"p < 1\"\n\n\nlocale CRR_market = CRR_hyps +\n  fixes G\nassumes stock_filtration:\"G = stoch_proc_filt M geom_proc borel\"\n\nsubsection \\<open>Preliminary results on the market\\<close>\n\nlemma (in CRR_market) case_asset:\n  assumes \"asset \\<in> stocks Mkt\"\n  shows \"asset = stk \\<or> asset = risk_free_asset\"\nproof (rule ccontr)\n  assume \"\\<not> (asset = stk \\<or> asset = risk_free_asset)\"\n  hence \"asset \\<noteq> stk \\<and> asset \\<noteq> risk_free_asset\" by simp\n  moreover have \"asset \\<in> {stk, risk_free_asset}\" using assms stocks by simp\n  ultimately show False by auto\nqed\n\nlemma (in CRR_market)\n  assumes \"N = bernoulli_stream q\"\nand \"0 < q\"\nand \"q < 1\"\nshows bernoulli_gen_filtration: \"filtration N G\"\nand bernoulli_sigma_finite: \"\\<forall>n. sigma_finite_subalgebra N (G n)\"\nproof -\n  show \"filtration N G\"\n  proof -\n    have \"disc_filtr M (stoch_proc_filt M geom_proc borel)\"\n    proof (rule stoch_proc_filt_disc_filtr)\n      fix i\n      show \"random_variable borel (geom_proc i)\"\n        by (simp add: geom_rand_walk_borel_measurable)\n    qed\n    hence \"filtration M G\" using stock_filtration  by (simp add: filtration_def disc_filtr_def)\n    have \"filt_equiv nat_filtration M N\" using pslt psgt by (simp add: assms bernoulli_stream_equiv)\n    hence \"sets N = sets M\" unfolding filt_equiv_def by simp\n    thus ?thesis unfolding filtration_def\n      by (metis filtration_def \\<open>Filtration.filtration M G\\<close> sets_eq_imp_space_eq subalgebra_def)\n  qed\n  show \"\\<forall>n. sigma_finite_subalgebra N (G n)\" using assms unfolding subalgebra_def\n    using  filtration_def  subalgebra_sigma_finite\n    by (metis \\<open>Filtration.filtration N G\\<close> bernoulli_stream_def prob_space.prob_space_stream_space\n        prob_space.subalgebra_sigma_finite prob_space_measure_pmf)\nqed\n\n\nsublocale CRR_market \\<subseteq> rfr_disc_equity_market  _ G\nproof (unfold_locales)\n  show  \"disc_filtr M G \\<and> sets (G \\<bottom>) = {{}, space M}\"\n  proof\n    show \"sets (G \\<bottom>) = {{}, space M}\" using infinite_cts_filtration.stoch_proc_filt_triv_init stock_filtration geometric_process\n        geom_rand_walk_borel_adapted\n      by (meson infinite_coin_toss_space_axioms infinite_cts_filtration_axioms.intro infinite_cts_filtration_def\n          init_triv_filt_def)\n    show \"disc_filtr M G\"\n      by (metis Filtration.filtration_def bernoulli bernoulli_gen_filtration disc_filtr_def psgt pslt)\n  qed\n  show \"\\<forall>asset\\<in>stocks Mkt. borel_adapt_stoch_proc G (prices Mkt asset)\"\n  proof -\n    have \"borel_adapt_stoch_proc G (prices Mkt stk)\" using stk_price stock_filtration stoch_proc_filt_adapt\n      by (simp add: stoch_proc_filt_adapt geom_rand_walk_borel_measurable)\n    moreover have \"borel_adapt_stoch_proc G (prices Mkt risk_free_asset)\"\n      using \\<open>disc_filtr M G \\<and> sets (G \\<bottom>) = {{}, space M}\\<close> disc_filtr_prob_space.disc_rfr_proc_borel_adapted\n        disc_filtr_prob_space.intro disc_filtr_prob_space_axioms.intro prob_space_axioms rf_price by fastforce\n    moreover have \"disc_filtr_prob_space M G\" proof (unfold_locales)\n      show \"disc_filtr M G\" by (simp add: \\<open>disc_filtr M G \\<and> sets (G \\<bottom>) = {{}, space M}\\<close>)\n    qed\n    ultimately show ?thesis using stocks by force\n  qed\nqed\n\n\n\n\nlemma (in CRR_market) two_stocks:\nshows \"stk \\<noteq> risk_free_asset\"\nproof (rule ccontr)\n  assume \"\\<not>stk \\<noteq> risk_free_asset\"\n  hence \"disc_rfr_proc r = prices Mkt stk\" using rf_price by simp\n  also have \"... = geom_proc\" using stk_price by simp\n  finally have eqf: \"disc_rfr_proc r = geom_proc\" .\n  hence \"\\<forall>w. disc_rfr_proc r 0 w = geom_proc 0 w\" by simp\n  hence \"1 = init\" using geometric_process by simp\n  have eqfs: \"\\<forall>w. disc_rfr_proc r (Suc 0) w = geom_proc (Suc 0) w\" using eqf by simp\n  hence \"disc_rfr_proc r (Suc 0) (sconst True) = geom_proc (Suc 0) (sconst True)\" by simp\n  hence \"1+r = u\" using geometric_process \\<open>1 = init\\<close> by simp\n  have \"disc_rfr_proc r (Suc 0) (sconst False) = geom_proc (Suc 0) (sconst False)\" using eqfs by simp\n  hence \"1+r = d\" using geometric_process \\<open>1 = init\\<close> by simp\n  show False using \\<open>1+r = u\\<close> \\<open>1+r = d\\<close> down_lt_up by simp\nqed\n\n\nlemma (in CRR_market) stock_pf_vp_expand:\n  assumes \"stock_portfolio Mkt pf\"\n  shows \"val_process Mkt pf n w = geom_proc n w * pf stk (Suc n) w +\n    disc_rfr_proc r n w * pf risk_free_asset (Suc n) w\"\nproof -\n  have \"val_process Mkt pf n w =(sum (\\<lambda>x. ((prices Mkt) x n w) * (pf x (Suc n) w)) (stocks Mkt))\"\n  proof (rule subset_val_process')\n    show \"finite (stocks Mkt)\" using stocks by auto\n    show \"support_set pf \\<subseteq> stocks Mkt\" using assms unfolding stock_portfolio_def by simp\n  qed\n  also have \"... = (\\<Sum>x\\<in> {stk, risk_free_asset}. ((prices Mkt) x n w) * (pf x (Suc n) w))\" using stocks  by simp\n  also have \"... =  prices Mkt stk n w * pf stk (Suc n) w +\n    (\\<Sum> x\\<in> {risk_free_asset}. ((prices Mkt) x n w) * (pf x (Suc n) w))\" by (simp add:two_stocks)\n  also have \"... = prices Mkt stk n w * pf stk (Suc n) w +\n    prices Mkt risk_free_asset n w * pf risk_free_asset (Suc n) w\" by simp\n  also have \"... = geom_proc n w * pf stk (Suc n) w + disc_rfr_proc r n w * pf risk_free_asset (Suc n) w\"\n    using rf_price stk_price by simp\n  finally show ?thesis .\nqed\n\nlemma (in CRR_market) stock_pf_uvp_expand:\n  assumes \"stock_portfolio Mkt pf\"\n  shows \"cls_val_process Mkt pf (Suc n) w = geom_proc (Suc n) w * pf stk (Suc n) w +\n    disc_rfr_proc r (Suc n) w * pf risk_free_asset (Suc n) w\"\nproof -\n  have \"cls_val_process Mkt pf (Suc n) w =(sum (\\<lambda>x. ((prices Mkt) x (Suc n) w) * (pf x (Suc n) w)) (stocks Mkt))\"\n  proof (rule subset_cls_val_process')\n    show \"finite (stocks Mkt)\" using stocks by auto\n    show \"support_set pf \\<subseteq> stocks Mkt\" using assms unfolding stock_portfolio_def by simp\n  qed\n  also have \"... = (\\<Sum>x\\<in> {stk, risk_free_asset}. ((prices Mkt) x (Suc n) w) * (pf x (Suc n) w))\" using  stocks by simp\n  also have \"... =  prices Mkt stk (Suc n) w * pf stk (Suc n) w +\n    (\\<Sum> x\\<in> {risk_free_asset}. ((prices Mkt) x (Suc n) w) * (pf x (Suc n) w))\" by (simp add:two_stocks)\n  also have \"... = prices Mkt stk (Suc n) w * pf stk (Suc n) w +\n    prices Mkt risk_free_asset (Suc n) w * pf risk_free_asset (Suc n) w\" by simp\n  also have \"... = geom_proc (Suc n) w * pf stk (Suc n) w + disc_rfr_proc r (Suc n) w * pf risk_free_asset (Suc n) w\"\n    using rf_price stk_price by simp\n  finally show ?thesis .\nqed\n\n\n\nlemma (in CRR_market) pos_pf_neg_uvp:\n  assumes \"stock_portfolio Mkt pf\"\n  and \"d < 1+r\"\n  and \"0 < pf stk (Suc n) (spick w n False)\"\n  and \"val_process Mkt pf n (spick w n False) \\<le> 0\"\nshows \"cls_val_process Mkt pf (Suc n) (spick w n False) < 0\"\nproof -\n  define wnf where \"wnf = spick w n False\"\n  have \"cls_val_process Mkt pf (Suc n) (spick w n False) =\n    geom_proc (Suc n) wnf * pf stk (Suc n) wnf +\n    disc_rfr_proc r (Suc n) wnf * pf risk_free_asset (Suc n) wnf\" unfolding wnf_def\n    using assms by (simp add:stock_pf_uvp_expand)\n  also have \"... = d * geom_proc n wnf * pf stk (Suc n) wnf + disc_rfr_proc r (Suc n) wnf * pf risk_free_asset (Suc n) wnf\"\n    unfolding wnf_def using geometric_process spickI[of n w False] by simp\n  also have \"... = d * geom_proc n wnf * pf stk (Suc n) wnf + (1+r) * disc_rfr_proc r n wnf * pf risk_free_asset (Suc n) wnf\"\n    by simp\n  also have \"... < (1+r) * geom_proc n wnf * pf stk (Suc n) wnf + (1+r) * disc_rfr_proc r n wnf * pf risk_free_asset (Suc n) wnf\"\n    unfolding wnf_def using assms geom_rand_walk_strictly_positive S0_positive\n      down_positive down_lt_up by simp\n  also have \"... = (1+r) * (geom_proc n wnf * pf stk (Suc n) wnf + disc_rfr_proc r n wnf * pf risk_free_asset (Suc n) wnf)\"\n    by (simp add: distrib_left)\n  also have \"... = (1+r) * val_process Mkt pf n wnf\" using stock_pf_vp_expand assms by simp\n  also have \"... \\<le> 0\"\n  proof -\n    have \"0 < 1+r\" using assms down_positive by simp\n    moreover have \"val_process Mkt pf n wnf \\<le> 0\" using assms unfolding wnf_def by simp\n    ultimately show \"(1+r) * (val_process Mkt pf n wnf) \\<le>  0\" unfolding wnf_def\n      using less_eq_real_def[of 0 \"1+r\"] mult_nonneg_nonpos[of \"1+r\" \"val_process Mkt pf n (spick w n False)\"] by simp\n  qed\n  finally show ?thesis .\nqed\n\n\nlemma (in CRR_market) neg_pf_neg_uvp:\n  assumes \"stock_portfolio Mkt pf\"\n  and \"1+r < u\"\n  and \"pf stk (Suc n) (spick w n True) < 0\"\n  and \"val_process Mkt pf n (spick w n True) \\<le> 0\"\nshows \"cls_val_process Mkt pf (Suc n) (spick w n True) < 0\"\nproof -\n  define wnf where \"wnf = spick w n True\"\n  have \"cls_val_process Mkt pf (Suc n) (spick w n True) =\n    geom_proc (Suc n) wnf * pf stk (Suc n) wnf +\n    disc_rfr_proc r (Suc n) wnf * pf risk_free_asset (Suc n) wnf\" unfolding wnf_def\n    using assms by (simp add:stock_pf_uvp_expand)\n  also have \"... = u * geom_proc n wnf * pf stk (Suc n) wnf + disc_rfr_proc r (Suc n) wnf * pf risk_free_asset (Suc n) wnf\"\n    unfolding wnf_def using geometric_process spickI[of n w True] by simp\n  also have \"... = u * geom_proc n wnf * pf stk (Suc n) wnf + (1+r) * disc_rfr_proc r n wnf * pf risk_free_asset (Suc n) wnf\"\n    by simp\n  also have \"... < (1+r) * geom_proc n wnf * pf stk (Suc n) wnf + (1+r) * disc_rfr_proc r n wnf * pf risk_free_asset (Suc n) wnf\"\n    unfolding wnf_def using assms geom_rand_walk_strictly_positive S0_positive\n      down_positive down_lt_up by simp\n  also have \"... = (1+r) * (geom_proc n wnf * pf stk (Suc n) wnf + disc_rfr_proc r n wnf * pf risk_free_asset (Suc n) wnf)\"\n    by (simp add: distrib_left)\n  also have \"... = (1+r) * val_process Mkt pf n wnf\" using stock_pf_vp_expand assms by simp\n  also have \"... \\<le> 0\"\n  proof -\n    have \"0 < 1+r\" using acceptable_rate by simp\n    moreover have \"val_process Mkt pf n wnf \\<le> 0\" using assms unfolding wnf_def by simp\n    ultimately show \"(1+r) * (val_process Mkt pf n wnf) \\<le>  0\" unfolding wnf_def\n      using less_eq_real_def[of 0 \"1+r\"] mult_nonneg_nonpos[of \"1+r\" \"val_process Mkt pf n (spick w n True)\"] by simp\n  qed\n  finally show ?thesis .\nqed\n\n\n\n\nlemma (in CRR_market) zero_pf_neg_uvp:\n  assumes \"stock_portfolio Mkt pf\"\n  and \"pf stk (Suc n) w = 0\"\n  and \"pf risk_free_asset (Suc n) w \\<noteq> 0\"\n  and \"val_process Mkt pf n w \\<le> 0\"\nshows \"cls_val_process Mkt pf (Suc n) w < 0\"\nproof -\n  have \"cls_val_process Mkt pf (Suc n) w =\n    S (Suc n) w * pf stk (Suc n) w +\n    disc_rfr_proc r (Suc n) w * pf risk_free_asset (Suc n) w\"\n    using assms by (simp add:stock_pf_uvp_expand)\n  also have \"... = disc_rfr_proc r (Suc n) w * pf risk_free_asset (Suc n) w\" using assms by simp\n  also have \"... = (1+r) * disc_rfr_proc r n w * pf risk_free_asset (Suc n) w\" by simp\n  also have \"... < 0\"\n  proof -\n    have \"0 < 1+r\" using acceptable_rate by simp\n    moreover have \"0 < disc_rfr_proc r n w\" using acceptable_rate by (simp add: disc_rfr_proc_positive)\n    ultimately have \"0 < (1+r) * disc_rfr_proc r n w\" by simp\n    have 1: \"0< pf risk_free_asset (Suc n) w \\<longrightarrow> 0 <(1+r) * disc_rfr_proc r n w * pf risk_free_asset (Suc n) w\"\n    proof (intro impI)\n      assume \"0 < pf risk_free_asset (Suc n) w\"\n      thus \"0 < (1 + r) * disc_rfr_proc r n w * pf risk_free_asset (Suc n) w\" using \\<open>0 < (1+r) * disc_rfr_proc r n w\\<close>\n        by simp\n    qed\n    have 2: \"pf risk_free_asset (Suc n) w < 0 \\<longrightarrow> (1+r) * disc_rfr_proc r n w * pf risk_free_asset (Suc n) w < 0\"\n    proof (intro impI)\n      assume \"pf risk_free_asset (Suc n) w < 0\"\n      thus \"(1 + r) * disc_rfr_proc r n w * pf risk_free_asset (Suc n) w < 0\" using \\<open>0 < (1+r) * disc_rfr_proc r n w\\<close>\n        by (simp add:mult_pos_neg)\n    qed\n    have \"0 \\<ge> val_process Mkt pf n w\" using assms by simp\n    also have \"val_process Mkt pf n w = geom_proc n w * pf stk (Suc n) w +\n      disc_rfr_proc r n w * pf risk_free_asset (Suc n) w\" using assms by (simp add:stock_pf_vp_expand)\n    also have \"... = disc_rfr_proc r n w * pf risk_free_asset (Suc n) w\" using assms by simp\n    finally have \"0\\<ge> disc_rfr_proc r n w * pf risk_free_asset (Suc n) w\" .\n    have \"0< pf risk_free_asset (Suc n) w \\<or> pf risk_free_asset (Suc n) w < 0\"  using assms\n       by linarith\n    thus ?thesis\n      using \"2\" \\<open>0 < disc_rfr_proc r n w\\<close> \\<open>disc_rfr_proc r n w * pf risk_free_asset (Suc n) w \\<le> 0\\<close>\n        mult_pos_pos by fastforce\n  qed\n  finally show ?thesis .\nqed\n\n\n\nlemma (in CRR_market) neg_pf_exists:\n  assumes \"stock_portfolio Mkt pf\"\n  and \"trading_strategy pf\"\n  and \"1+r < u\"\n  and \"d < 1+r\"\n  and \"val_process Mkt pf n w \\<le> 0\"\n  and \"pf stk (Suc n) w \\<noteq> 0 \\<or> pf risk_free_asset (Suc n) w \\<noteq> 0\"\nshows \"\\<exists>y. cls_val_process Mkt pf (Suc n) y < 0\"\nproof -\n  have \"borel_predict_stoch_proc G (pf stk)\"\n  proof (rule inc_predict_support_trading_strat')\n    show \"trading_strategy pf\" using assms by simp\n    show \"stk \\<in> support_set pf \\<union> {stk}\" by simp\n  qed\n  hence \"pf stk (Suc n) \\<in> borel_measurable (G n)\" unfolding predict_stoch_proc_def by simp\n  have \"val_process Mkt pf n \\<in> borel_measurable (G n)\"\n  proof -\n    have \"borel_adapt_stoch_proc G (val_process Mkt pf)\" using assms\n      using support_adapt_def ats_val_process_adapted readable unfolding  stock_portfolio_def by blast\n    thus ?thesis unfolding adapt_stoch_proc_def by simp\n  qed\n  define wn where \"wn = pseudo_proj_True n w\"\n  show ?thesis\n  proof (cases \"pf stk (Suc n) w \\<noteq> 0\")\n    case True\n    show ?thesis\n    proof (cases \"pf stk (Suc n) w > 0\")\n      case True\n      have \"0 <pf stk (Suc n) (spick wn n False)\"\n      proof -\n        have \"0 < pf stk (Suc n) w\" using \\<open>0 < pf stk (Suc n) w\\<close> by simp\n        also have \"... = pf stk (Suc n) wn\" unfolding wn_def\n          using \\<open>pf stk (Suc n) \\<in> borel_measurable (G n)\\<close> stoch_proc_subalg_nat_filt[of geom_proc] geometric_process\n          nat_filtration_info stock_filtration\n          by (metis comp_apply geom_rand_walk_borel_adapted measurable_from_subalg)\n        also have \"... = pf stk (Suc n) (spick wn n False)\" using \\<open>pf stk (Suc n) \\<in> borel_measurable (G n)\\<close> comp_def nat_filtration_info\n              pseudo_proj_True_stake_image spickI stoch_proc_subalg_nat_filt[of geom_proc] geometric_process stock_filtration\n          by (metis geom_rand_walk_borel_adapted measurable_from_subalg)\n        finally show ?thesis .\n      qed\n      moreover have \"0 \\<ge> val_process Mkt pf n (spick wn n False)\"\n      proof -\n        have \"0 \\<ge> val_process Mkt pf n w\" using assms by simp\n        also have \"val_process Mkt pf n w = val_process Mkt pf n wn\" unfolding wn_def using \\<open>val_process Mkt pf n \\<in> borel_measurable (G n)\\<close>\n          nat_filtration_info stoch_proc_subalg_nat_filt[of geom_proc] geometric_process\n          stock_filtration by (metis comp_apply geom_rand_walk_borel_adapted measurable_from_subalg)\n        also have \"... = val_process Mkt pf n (spick wn n False)\" using \\<open>val_process Mkt pf n \\<in> borel_measurable (G n)\\<close>\n          comp_def nat_filtration_info\n              pseudo_proj_True_stake_image spickI stoch_proc_subalg_nat_filt[of geom_proc] geometric_process stock_filtration\n          by (metis geom_rand_walk_borel_adapted measurable_from_subalg)\n        finally show ?thesis .\n      qed\n      ultimately have \"cls_val_process Mkt pf (Suc n) (spick wn n False) < 0\" using assms\n        by (simp add:pos_pf_neg_uvp)\n      thus \"\\<exists>y. cls_val_process Mkt pf (Suc n) y < 0\" by auto\n    next\n      case False\n      have \"0 >pf stk (Suc n) (spick wn n True)\"\n      proof -\n        have \"0 > pf stk (Suc n) w\" using \\<open>\\<not> 0 < pf stk (Suc n) w\\<close> \\<open>pf stk (Suc n) w \\<noteq> 0\\<close> by simp\n        also have \"pf stk (Suc n) w = pf stk (Suc n) wn\" unfolding wn_def using \\<open>pf stk (Suc n) \\<in> borel_measurable (G n)\\<close>\n          nat_filtration_info stoch_proc_subalg_nat_filt[of geom_proc] geometric_process\n          stock_filtration by (metis comp_apply geom_rand_walk_borel_adapted measurable_from_subalg)\n        also have \"... = pf stk (Suc n) (spick wn n True)\" using \\<open>pf stk (Suc n) \\<in> borel_measurable (G n)\\<close>\n          comp_def nat_filtration_info\n              pseudo_proj_True_stake_image spickI stoch_proc_subalg_nat_filt[of geom_proc] geometric_process stock_filtration\n          by (metis geom_rand_walk_borel_adapted measurable_from_subalg)\n        finally show ?thesis .\n      qed\n      moreover have \"0 \\<ge> val_process Mkt pf n (spick wn n True)\"\n      proof -\n        have \"0 \\<ge> val_process Mkt pf n w\" using assms by simp\n        also have \"val_process Mkt pf n w = val_process Mkt pf n wn\" unfolding wn_def using \\<open>val_process Mkt pf n \\<in> borel_measurable (G n)\\<close>\n          comp_def nat_filtration_info\n              pseudo_proj_True_stake_image spickI stoch_proc_subalg_nat_filt[of geom_proc] geometric_process stock_filtration\n          by (metis geom_rand_walk_borel_adapted measurable_from_subalg)\n        also have \"... = val_process Mkt pf n (spick wn n True)\" using \\<open>val_process Mkt pf n \\<in> borel_measurable (G n)\\<close>\n          comp_def nat_filtration_info\n              pseudo_proj_True_stake_image spickI stoch_proc_subalg_nat_filt[of geom_proc] geometric_process stock_filtration\n          by (metis geom_rand_walk_borel_adapted measurable_from_subalg)\n        finally show ?thesis .\n      qed\n      ultimately have \"cls_val_process Mkt pf (Suc n) (spick wn n True) < 0\" using assms\n        by (simp add:neg_pf_neg_uvp)\n      thus \"\\<exists>y. cls_val_process Mkt pf (Suc n) y < 0\" by auto\n    qed\n  next\n    case False\n    hence \"pf risk_free_asset (Suc n) w \\<noteq> 0\" using assms by simp\n    hence \"cls_val_process Mkt pf (Suc n) w < 0\" using False assms by (auto simp add:zero_pf_neg_uvp)\n    thus \"\\<exists>y. cls_val_process Mkt pf (Suc n) y < 0\" by auto\n  qed\nqed\n\n\nlemma (in CRR_market) non_zero_components:\nassumes \"val_process Mkt pf n y \\<noteq> 0\"\nand \"stock_portfolio Mkt pf\"\nshows  \"pf stk (Suc n) y \\<noteq> 0 \\<or> pf risk_free_asset (Suc n) y \\<noteq> 0\"\nproof (rule ccontr)\n  assume \"\\<not>(pf stk (Suc n) y \\<noteq> 0 \\<or> pf risk_free_asset (Suc n) y \\<noteq> 0)\"\n  hence \"pf stk (Suc n) y = 0\" \"pf risk_free_asset (Suc n) y = 0\" by auto\n  have \"val_process Mkt pf n y = geom_proc n y * pf stk (Suc n) y +\n    disc_rfr_proc r n y * pf risk_free_asset (Suc n) y\" using \\<open>stock_portfolio Mkt pf\\<close>\n    stock_pf_vp_expand[of pf n]  by simp\n  also have \"... = 0\" using \\<open>pf stk (Suc n) y = 0\\<close> \\<open>pf risk_free_asset (Suc n) y = 0\\<close> by simp\n  finally have \"val_process Mkt pf n y = 0\" .\n  moreover have \"val_process Mkt pf n y \\<noteq> 0\" using assms by simp\n  ultimately show False by simp\nqed\n\nlemma (in CRR_market) neg_pf_Suc:\n  assumes \"stock_portfolio Mkt pf\"\n  and \"trading_strategy pf\"\n  and \"self_financing Mkt pf\"\n  and \"1+r < u\"\n  and \"d < 1+r\"\n  and \"cls_val_process Mkt pf n w < 0\"\nshows \"n \\<le> m \\<Longrightarrow> \\<exists>y. cls_val_process Mkt pf m y < 0\"\nproof (induct m)\n  case 0\n  assume \"n \\<le> 0\"\n  hence \"n=0\" by simp\n  thus \"\\<exists>y. cls_val_process Mkt pf 0 y < 0\" using assms by auto\nnext\n  case (Suc m)\n  assume \"n \\<le> Suc m\"\n  thus \"\\<exists>y. cls_val_process Mkt pf (Suc m) y < 0\"\n  proof (cases \"n < Suc m\")\n    case False\n    hence \"n = Suc m\" using \\<open>n \\<le> Suc m\\<close> by simp\n    thus \"\\<exists>y. cls_val_process Mkt pf (Suc m) y < 0\" using assms by auto\n  next\n    case True\n    hence \"n \\<le> m\" by simp\n    hence \"\\<exists>y. cls_val_process Mkt pf m y < 0\" using Suc by simp\n    from this obtain y where \"cls_val_process Mkt pf m y < 0\" by auto\n    hence \"val_process Mkt pf m y < 0\" using assms by (simp add:self_financingE)\n    hence \"val_process Mkt pf m y \\<le> 0\" by simp\n    have \"val_process Mkt pf m y \\<noteq> 0\" using \\<open>val_process Mkt pf m y < 0\\<close> by simp\n    hence \"pf stk (Suc m) y \\<noteq> 0 \\<or> pf risk_free_asset (Suc m) y \\<noteq> 0\" using assms non_zero_components by simp\n    thus \"\\<exists>y. cls_val_process Mkt pf (Suc m) y < 0\" using neg_pf_exists[of pf m y] assms\n      \\<open>val_process Mkt pf m y \\<le> 0\\<close> by simp\n  qed\nqed\n\n\n\n\nlemma (in CRR_market) viable_if:\n  assumes \"1+r < u\"\n  and \"d < 1+r\"\nshows \"viable_market Mkt\" unfolding viable_market_def\nproof (rule ccontr)\n  assume \"\\<not>(\\<forall>p. stock_portfolio Mkt p \\<longrightarrow> \\<not> arbitrage_process Mkt p)\"\n  hence \"\\<exists>p. stock_portfolio Mkt p \\<and> arbitrage_process Mkt p\" by simp\n  from this obtain pf where \"stock_portfolio Mkt pf\" and \"arbitrage_process Mkt pf\" by auto\n  have \"(\\<exists> m. (self_financing Mkt pf) \\<and> (trading_strategy pf) \\<and>\n    (\\<forall>w \\<in> space M. cls_val_process Mkt pf 0 w = 0) \\<and>\n    (AE w in M. 0 \\<le> cls_val_process Mkt pf m w) \\<and>\n    0 < \\<P>(w in M. cls_val_process Mkt pf m w > 0))\" using \\<open>arbitrage_process Mkt pf\\<close>\n    using arbitrage_processE by simp\n  from this obtain m where \"self_financing Mkt pf\" and \"(trading_strategy pf)\"\n    and \"(\\<forall>w \\<in> space M. cls_val_process Mkt pf 0 w = 0)\"\n    and \"(AE w in M. 0 \\<le> cls_val_process Mkt pf m w)\"\n    and \"0 < \\<P>(w in M. cls_val_process Mkt pf m w > 0)\" by auto\n  have \"{w\\<in> space M. cls_val_process Mkt pf m w > 0} \\<noteq> {}\" using\n    \\<open>0 < \\<P>(w in M. cls_val_process Mkt pf m w > 0)\\<close> by force\n  hence \"\\<exists>w\\<in> space M. cls_val_process Mkt pf m w > 0\" by auto\n  from this obtain y where \"y\\<in> space M\" and \"cls_val_process Mkt pf m y > 0\" by auto\n  define A where \"A = {n::nat. n \\<le> m \\<and> cls_val_process Mkt pf n y > 0}\"\n  have \"finite A\" unfolding A_def by auto\n  have \"m \\<in> A\" using \\<open>cls_val_process Mkt pf m y > 0\\<close> unfolding A_def by simp\n  hence \"A \\<noteq> {}\" by auto\n  hence \"Min A \\<in> A\" using \\<open>finite A\\<close> by simp\n  have \"Min A \\<le> m\" using \\<open>finite A\\<close> \\<open>m\\<in> A\\<close> by simp\n  have \"0 < Min A\"\n  proof -\n    have \"cls_val_process Mkt pf 0 y = 0\" using \\<open>y\\<in> space M\\<close> \\<open>\\<forall>w \\<in> space M. cls_val_process Mkt pf 0 w = 0\\<close>\n      by simp\n    hence \"0\\<notin> A\" unfolding A_def by simp\n    moreover have \"0 \\<le> Min A\" by simp\n    ultimately show ?thesis using \\<open>Min A \\<in> A\\<close> neq0_conv by fastforce\n  qed\n  hence \"\\<exists>l. Suc l = Min A\" using Suc_diff_1 by blast\n  from this obtain l where \"Suc l = Min A\" by auto\n  have \"cls_val_process Mkt pf l y \\<le> 0\"\n  proof -\n    have \"l < Min A\" using \\<open>Suc l = Min A\\<close> by simp\n    hence \"l\\<notin> A\" using \\<open>finite A\\<close> \\<open>A \\<noteq> {}\\<close> by auto\n    moreover have \"l \\<le> m\" using \\<open>Suc l = Min A\\<close> \\<open>m\\<in> A\\<close> \\<open>finite A\\<close> \\<open>A \\<noteq> {}\\<close> \\<open>l < Min A\\<close> by auto\n    ultimately show ?thesis unfolding A_def by auto\n  qed\n  hence \"val_process Mkt pf l y \\<le> 0\" using \\<open>self_financing Mkt pf\\<close> by (simp add:self_financingE)\n  moreover have \"pf stk (Suc l) y \\<noteq> 0 \\<or> pf risk_free_asset (Suc l) y \\<noteq> 0\"\n  proof (rule ccontr)\n    assume \"\\<not>(pf stk (Suc l) y \\<noteq> 0 \\<or> pf risk_free_asset (Suc l) y \\<noteq> 0)\"\n    hence \"pf stk (Suc l) y = 0\" \"pf risk_free_asset (Suc l) y = 0\" by auto\n    have \"cls_val_process Mkt pf (Min A) y = geom_proc (Suc l) y * pf stk (Suc l) y +\n      disc_rfr_proc r (Suc l) y * pf risk_free_asset (Suc l) y\" using \\<open>stock_portfolio Mkt pf\\<close>\n      \\<open>Suc l = Min A\\<close> stock_pf_uvp_expand[of pf l]  by simp\n    also have \"... = 0\" using \\<open>pf stk (Suc l) y = 0\\<close> \\<open>pf risk_free_asset (Suc l) y = 0\\<close> by simp\n    finally have \"cls_val_process Mkt pf (Min A) y = 0\" .\n    moreover have \"cls_val_process Mkt pf (Min A) y > 0\" using \\<open>Min A \\<in> A\\<close> unfolding A_def by simp\n    ultimately show False by simp\n  qed\n  ultimately have \"\\<exists>z. cls_val_process Mkt pf (Suc l) z < 0\" using assms \\<open>stock_portfolio Mkt pf\\<close>\n    \\<open>trading_strategy pf\\<close> by (simp add:neg_pf_exists)\n  from this obtain z where \"cls_val_process Mkt pf (Suc l) z < 0\" by auto\n  hence \"\\<exists>x'. cls_val_process Mkt pf m x' < 0\" using neg_pf_Suc assms \\<open>trading_strategy pf\\<close>\n      \\<open>self_financing Mkt pf\\<close> \\<open>Suc l = Min A\\<close> \\<open>Min A \\<le> m\\<close> \\<open>stock_portfolio Mkt pf\\<close> by simp\n  from this obtain x' where \"cls_val_process Mkt pf m x' < 0\" by auto\n  have \"x'\\<in> space M\" using bernoulli_stream_space bernoulli by auto\n  hence \"x'\\<in> {w\\<in> space M. \\<not>0 \\<le> cls_val_process Mkt pf m w}\" using \\<open>cls_val_process Mkt pf m x' < 0\\<close> by auto\n  from \\<open>AE w in M. 0 \\<le> cls_val_process Mkt pf m w\\<close> obtain N where\n    \"{w\\<in> space M. \\<not>0 \\<le> cls_val_process Mkt pf m w} \\<subseteq> N\" and \"emeasure M N = 0\" and \"N\\<in> sets M\" using AE_E by auto\n  have \"{w\\<in> space M. (stake m w = stake m x')} \\<subseteq> N\"\n  proof\n    fix x\n    assume \"x \\<in> {w \\<in> space M. stake m w = stake m x'}\"\n    hence \"x\\<in> space M\" and \"stake m x = stake m x'\" by auto\n    have \"cls_val_process Mkt pf m \\<in> borel_measurable (G m)\"\n    proof -\n      have \"borel_adapt_stoch_proc G (cls_val_process Mkt pf)\" using \\<open>trading_strategy pf\\<close> \\<open>stock_portfolio Mkt pf\\<close>\n        by (meson support_adapt_def readable  stock_portfolio_def subsetCE cls_val_process_adapted)\n      thus ?thesis unfolding adapt_stoch_proc_def by simp\n    qed\n    hence \"cls_val_process Mkt pf m x' = cls_val_process Mkt pf m x\"\n      using  \\<open>stake m x = stake m x'\\<close> borel_measurable_stake[of \"cls_val_process Mkt pf m\" m x x']\n      pseudo_proj_True_stake_image spickI stoch_proc_subalg_nat_filt[of geom_proc] geometric_process stock_filtration\n          by (metis geom_rand_walk_borel_adapted measurable_from_subalg)\n    hence \"cls_val_process Mkt pf m x < 0\" using \\<open>cls_val_process Mkt pf m x' < 0\\<close> by simp\n    thus \"x\\<in> N\" using \\<open>{w\\<in> space M. \\<not>0 \\<le> cls_val_process Mkt pf m w} \\<subseteq> N\\<close> \\<open>x\\<in> space M\\<close>\n      \\<open>cls_val_process Mkt pf (Suc l) z < 0\\<close> by auto\n  qed\n  moreover have \"emeasure M {w\\<in> space M. (stake m w = stake m x')} \\<noteq> 0\" using bernoulli_stream_pref_prob_neq_zero psgt pslt by simp\n  ultimately show False using \\<open>emeasure M N = 0\\<close> \\<open>N \\<in> events\\<close> emeasure_eq_0 by blast\nqed\n\n\nlemma (in CRR_market) viable_only_if_d:\n  assumes \"viable_market Mkt\"\n  shows \"d < 1+r\"\nproof (rule ccontr)\n  assume \"\\<not> d < 1+r\"\n  hence \"1+r \\<le> d\" by simp\n  define arb_pf where \"arb_pf = (\\<lambda> (x::'a) (n::nat) w. 0::real)(stk:= (\\<lambda> n w. 1), risk_free_asset := (\\<lambda> n w. - geom_proc 0 w))\"\n  have \"support_set arb_pf = {stk, risk_free_asset}\"\n  proof\n    show \"support_set arb_pf \\<subseteq> {stk, risk_free_asset}\"\n      by (simp add: arb_pf_def subset_iff support_set_def)\n    have \"stk\\<in> support_set arb_pf\" unfolding arb_pf_def support_set_def using two_stocks by simp\n    moreover have \"risk_free_asset\\<in> support_set arb_pf\" unfolding arb_pf_def support_set_def\n      using two_stocks geometric_process S0_positive by simp\n    ultimately show \"{stk, risk_free_asset}\\<subseteq> support_set arb_pf\" by simp\n  qed\n  hence \"stock_portfolio Mkt arb_pf\" using stocks\n    by (simp add: portfolio_def stock_portfolio_def)\n  have \"arbitrage_process Mkt arb_pf\"\n  proof (rule arbitrage_processI, intro exI conjI)\n    show \"self_financing Mkt arb_pf\" unfolding arb_pf_def using \\<open>support_set arb_pf = {stk, risk_free_asset}\\<close>\n      by (simp add: static_portfolio_self_financing)\n    show \"trading_strategy arb_pf\" unfolding trading_strategy_def\n    proof (intro conjI ballI)\n      show \"portfolio arb_pf\" unfolding portfolio_def using \\<open>support_set arb_pf = {stk, risk_free_asset}\\<close> by simp\n      fix asset\n      assume \"asset\\<in> support_set arb_pf\"\n      show \"borel_predict_stoch_proc G (arb_pf asset)\"\n      proof (cases \"asset = stk\")\n        case True\n        hence \"arb_pf asset = (\\<lambda> n w. 1)\" unfolding arb_pf_def by (simp add: two_stocks)\n        show ?thesis unfolding predict_stoch_proc_def\n        proof\n          show \"arb_pf asset 0 \\<in> borel_measurable (G 0)\" using \\<open>arb_pf asset = (\\<lambda> n w. 1)\\<close> by simp\n          show \"\\<forall>n. arb_pf asset (Suc n) \\<in> borel_measurable (G n)\"\n          proof\n            fix n\n            show \"arb_pf asset (Suc n) \\<in> borel_measurable (G n)\" using \\<open>arb_pf asset = (\\<lambda> n w. 1)\\<close> by simp\n          qed\n        qed\n      next\n        case False\n        hence \"arb_pf asset = (\\<lambda> n w. - geom_proc 0 w)\" using \\<open>support_set arb_pf = {stk, risk_free_asset}\\<close>\n          \\<open>asset \\<in> support_set arb_pf\\<close> unfolding arb_pf_def by simp\n        show ?thesis unfolding predict_stoch_proc_def\n        proof\n          show \"arb_pf asset 0 \\<in> borel_measurable (G 0)\" using \\<open>arb_pf asset = (\\<lambda> n w. - geom_proc 0 w)\\<close>\n            geometric_process by simp\n          show \"\\<forall>n. arb_pf asset (Suc n) \\<in> borel_measurable (G n)\"\n          proof\n            fix n\n            show \"arb_pf asset (Suc n) \\<in> borel_measurable (G n)\" using \\<open>arb_pf asset = (\\<lambda> n w. - geom_proc 0 w)\\<close>\n              geometric_process by simp\n          qed\n        qed\n      qed\n    qed\n    show \"\\<forall>w\\<in>space M. cls_val_process Mkt arb_pf 0 w = 0\"\n    proof\n      fix w\n      assume \"w\\<in> space M\"\n      have \"cls_val_process Mkt arb_pf 0 w = geom_proc 0 w * arb_pf stk (Suc 0) w +\n        disc_rfr_proc r 0 w * arb_pf risk_free_asset (Suc 0) w\" using stock_pf_vp_expand\n        \\<open>stock_portfolio Mkt arb_pf\\<close>\n        using \\<open>self_financing Mkt arb_pf\\<close> self_financingE by fastforce\n      also have \"... = geom_proc 0 w * (1) + disc_rfr_proc r 0 w * arb_pf risk_free_asset (Suc 0) w\"\n        by (simp add: arb_pf_def two_stocks)\n      also have \"... = geom_proc 0 w + arb_pf risk_free_asset (Suc 0) w\" by simp\n      also have \"... = geom_proc 0 w  - geom_proc 0 w\" unfolding arb_pf_def by simp\n      also have \"... = 0\" by simp\n      finally show \"cls_val_process Mkt arb_pf 0 w = 0\" .\n    qed\n    have dev: \"\\<forall>w\\<in> space M. cls_val_process Mkt arb_pf (Suc 0) w = geom_proc (Suc 0) w - (1+r) * geom_proc 0 w\"\n    proof (intro ballI)\n      fix w\n      assume \"w\\<in> space M\"\n      have \"cls_val_process Mkt arb_pf (Suc 0) w =  geom_proc (Suc 0) w * arb_pf stk (Suc 0) w +\n        disc_rfr_proc r (Suc 0) w * arb_pf risk_free_asset (Suc 0) w\" using stock_pf_uvp_expand\n        \\<open>stock_portfolio Mkt arb_pf\\<close> by simp\n      also have \"... = geom_proc (Suc 0) w + disc_rfr_proc r (Suc 0) w * arb_pf risk_free_asset (Suc 0) w\"\n        by (simp add: arb_pf_def two_stocks)\n      also have \"... = geom_proc (Suc 0) w + (1+r) * arb_pf risk_free_asset (Suc 0) w\" by simp\n      also have \"... = geom_proc (Suc 0) w - (1+r) * geom_proc 0 w\" by (simp add:arb_pf_def)\n      finally show \"cls_val_process Mkt arb_pf (Suc 0) w = geom_proc (Suc 0) w - (1+r) * geom_proc 0 w\" .\n    qed\n    have iniT: \"\\<forall>w\\<in> space M. snth w 0 \\<longrightarrow> cls_val_process Mkt arb_pf (Suc 0) w > 0\"\n    proof (intro ballI impI)\n      fix w\n      assume \"w\\<in> space M\" and \"snth w 0\"\n      have \"cls_val_process Mkt arb_pf (Suc 0) w =  geom_proc (Suc 0) w - (1+r) * geom_proc 0 w\"\n        using dev \\<open>w\\<in> space M\\<close> by simp\n      also have \"... = u * geom_proc 0 w - (1+r) * geom_proc 0 w\" using \\<open>snth w 0\\<close> geometric_process by simp\n      also have \"... = (u - (1+r)) * geom_proc 0 w\" by (simp add: left_diff_distrib)\n      also have \"... > 0\" using S0_positive \\<open>1 + r \\<le> d\\<close> down_lt_up geometric_process by auto\n      finally show \"cls_val_process Mkt arb_pf (Suc 0) w > 0\" .\n    qed\n    have iniF: \"\\<forall>w\\<in> space M. \\<not>snth w 0 \\<longrightarrow> cls_val_process Mkt arb_pf (Suc 0) w \\<ge> 0\"\n    proof (intro ballI impI)\n      fix w\n      assume \"w\\<in> space M\" and \"\\<not>snth w 0\"\n      have \"cls_val_process Mkt arb_pf (Suc 0) w =  geom_proc (Suc 0) w - (1+r) * geom_proc 0 w\"\n        using dev \\<open>w\\<in> space M\\<close> by simp\n      also have \"... = d * geom_proc 0 w - (1+r) * geom_proc 0 w\" using \\<open>\\<not>snth w 0\\<close> geometric_process by simp\n      also have \"... = (d - (1+r)) * geom_proc 0 w\" by (simp add: left_diff_distrib)\n      also have \"... \\<ge> 0\" using S0_positive \\<open>1 + r \\<le> d\\<close> down_lt_up geometric_process by auto\n      finally show \"cls_val_process Mkt arb_pf (Suc 0) w \\<ge> 0\" .\n    qed\n    have \"\\<forall>w\\<in> space M. cls_val_process Mkt arb_pf (Suc 0) w \\<ge> 0\"\n    proof\n      fix w\n      assume \"w\\<in> space M\"\n      show \"cls_val_process Mkt arb_pf (Suc 0) w \\<ge> 0\"\n      proof (cases \"snth w 0\")\n        case True\n        thus ?thesis using \\<open>w\\<in> space M\\<close> iniT by auto\n      next\n        case False\n        thus ?thesis using \\<open>w\\<in> space M\\<close> iniF by simp\n      qed\n    qed\n    thus \"AE w in M. 0 \\<le> cls_val_process Mkt arb_pf (Suc 0) w\" by simp\n    show \"0 < prob {w \\<in> space M. 0 < cls_val_process Mkt arb_pf (Suc 0) w}\"\n    proof -\n      have \"cls_val_process Mkt arb_pf (Suc 0) \\<in> borel_measurable M\" using borel_adapt_stoch_proc_borel_measurable\n        cls_val_process_adapted \\<open>trading_strategy arb_pf\\<close> \\<open>stock_portfolio Mkt arb_pf\\<close>\n        using support_adapt_def readable unfolding  stock_portfolio_def by blast\n      hence set_event:\"{w \\<in> space M. 0 < cls_val_process Mkt arb_pf (Suc 0) w} \\<in> sets M\"\n        using borel_measurable_iff_greater by blast\n      have \"\\<forall>n. emeasure M {w \\<in> space M. w !! n} = ennreal p\"\n        using bernoulli p_gt_0 p_lt_1 bernoulli_stream_component_probability[of M p]\n        by auto\n      hence \"emeasure M {w \\<in> space M. w !! 0} = ennreal p\" by blast\n      moreover have \"{w \\<in> space M. w !! 0} \\<subseteq> {w \\<in> space M. 0 < cls_val_process Mkt arb_pf 1 w}\"\n      proof\n        fix w\n        assume \"w\\<in> {w \\<in> space M. w !! 0}\"\n        hence \"w \\<in> space M\" and \"w !! 0\" by auto note wprops = this\n        hence \"0 < cls_val_process Mkt arb_pf 1 w\" using iniT by simp\n        thus \"w\\<in> {w \\<in> space M. 0 < cls_val_process Mkt arb_pf 1 w}\" using wprops by simp\n      qed\n      ultimately have \"p \\<le> emeasure M {w \\<in> space M. 0 < cls_val_process Mkt arb_pf 1 w}\"\n        using emeasure_mono set_event by fastforce\n      hence \"p \\<le> prob {w \\<in> space M. 0 < cls_val_process Mkt arb_pf 1 w}\" by (simp add: emeasure_eq_measure)\n      thus \"0 < prob {w \\<in> space M. 0 < cls_val_process Mkt arb_pf (Suc 0) w}\" using psgt by simp\n    qed\n  qed\n  thus False using assms unfolding viable_market_def using \\<open>stock_portfolio Mkt arb_pf\\<close> by simp\nqed\n\n\nlemma (in CRR_market) viable_only_if_u:\n  assumes \"viable_market Mkt\"\n  shows \"1+r < u\"\nproof (rule ccontr)\n  assume \"\\<not> 1+r < u\"\n  hence \"u \\<le> 1+r\" by simp\n  define arb_pf where \"arb_pf = (\\<lambda> (x::'a) (n::nat) w. 0::real)(stk:= (\\<lambda> n w. -1), risk_free_asset := (\\<lambda> n w. geom_proc 0 w))\"\n  have \"support_set arb_pf = {stk, risk_free_asset}\"\n  proof\n    show \"support_set arb_pf \\<subseteq> {stk, risk_free_asset}\"\n      by (simp add: arb_pf_def subset_iff support_set_def)\n    have \"stk\\<in> support_set arb_pf\" unfolding arb_pf_def support_set_def using two_stocks by simp\n    moreover have \"risk_free_asset\\<in> support_set arb_pf\" unfolding arb_pf_def support_set_def\n      using two_stocks geometric_process S0_positive by simp\n    ultimately show \"{stk, risk_free_asset}\\<subseteq> support_set arb_pf\" by simp\n  qed\n  hence \"stock_portfolio Mkt arb_pf\" using stocks\n    by (simp add: portfolio_def stock_portfolio_def)\n  have \"arbitrage_process Mkt arb_pf\"\n  proof (rule arbitrage_processI, intro exI conjI)\n    show \"self_financing Mkt arb_pf\" unfolding arb_pf_def using \\<open>support_set arb_pf = {stk, risk_free_asset}\\<close>\n      by (simp add: static_portfolio_self_financing)\n    show \"trading_strategy arb_pf\" unfolding trading_strategy_def\n    proof (intro conjI ballI)\n      show \"portfolio arb_pf\" unfolding portfolio_def using \\<open>support_set arb_pf = {stk, risk_free_asset}\\<close> by simp\n      fix asset\n      assume \"asset\\<in> support_set arb_pf\"\n      show \"borel_predict_stoch_proc G (arb_pf asset)\"\n      proof (cases \"asset = stk\")\n        case True\n        hence \"arb_pf asset = (\\<lambda> n w. -1)\" unfolding arb_pf_def by (simp add: two_stocks)\n        show ?thesis unfolding predict_stoch_proc_def\n        proof\n          show \"arb_pf asset 0 \\<in> borel_measurable (G 0)\" using \\<open>arb_pf asset = (\\<lambda> n w. -1)\\<close> by simp\n          show \"\\<forall>n. arb_pf asset (Suc n) \\<in> borel_measurable (G n)\"\n          proof\n            fix n\n            show \"arb_pf asset (Suc n) \\<in> borel_measurable (G n)\" using \\<open>arb_pf asset = (\\<lambda> n w. -1)\\<close> by simp\n          qed\n        qed\n      next\n        case False\n        hence \"arb_pf asset = (\\<lambda> n w. geom_proc 0 w)\" using \\<open>support_set arb_pf = {stk, risk_free_asset}\\<close>\n          \\<open>asset \\<in> support_set arb_pf\\<close> unfolding arb_pf_def by simp\n        show ?thesis unfolding predict_stoch_proc_def\n        proof\n          show \"arb_pf asset 0 \\<in> borel_measurable (G 0)\" using \\<open>arb_pf asset = (\\<lambda> n w. geom_proc 0 w)\\<close>\n            geometric_process by simp\n          show \"\\<forall>n. arb_pf asset (Suc n) \\<in> borel_measurable (G n)\"\n          proof\n            fix n\n            show \"arb_pf asset (Suc n) \\<in> borel_measurable (G n)\" using \\<open>arb_pf asset = (\\<lambda> n w. geom_proc 0 w)\\<close>\n              geometric_process by simp\n          qed\n        qed\n      qed\n    qed\n    show \"\\<forall>w\\<in>space M. cls_val_process Mkt arb_pf 0 w = 0\"\n    proof\n      fix w\n      assume \"w\\<in> space M\"\n      have \"cls_val_process Mkt arb_pf 0 w = geom_proc 0 w * arb_pf stk (Suc 0) w +\n        disc_rfr_proc r 0 w * arb_pf risk_free_asset (Suc 0) w\" using stock_pf_vp_expand\n        \\<open>stock_portfolio Mkt arb_pf\\<close>\n        using \\<open>self_financing Mkt arb_pf\\<close> self_financingE by fastforce\n      also have \"... = geom_proc 0 w * (-1) + disc_rfr_proc r 0 w * arb_pf risk_free_asset (Suc 0) w\"\n        by (simp add: arb_pf_def two_stocks)\n      also have \"... = -geom_proc 0 w + arb_pf risk_free_asset (Suc 0) w\" by simp\n      also have \"... = geom_proc 0 w  - geom_proc 0 w\" unfolding arb_pf_def by simp\n      also have \"... = 0\" by simp\n      finally show \"cls_val_process Mkt arb_pf 0 w = 0\" .\n    qed\n    have dev: \"\\<forall>w\\<in> space M. cls_val_process Mkt arb_pf (Suc 0) w = -geom_proc (Suc 0) w + (1+r) * geom_proc 0 w\"\n    proof (intro ballI)\n      fix w\n      assume \"w\\<in> space M\"\n      have \"cls_val_process Mkt arb_pf (Suc 0) w =  geom_proc (Suc 0) w * arb_pf stk (Suc 0) w +\n        disc_rfr_proc r (Suc 0) w * arb_pf risk_free_asset (Suc 0) w\" using stock_pf_uvp_expand\n        \\<open>stock_portfolio Mkt arb_pf\\<close> by simp\n      also have \"... = -geom_proc (Suc 0) w + disc_rfr_proc r (Suc 0) w * arb_pf risk_free_asset (Suc 0) w\"\n        by (simp add: arb_pf_def two_stocks)\n      also have \"... = -geom_proc (Suc 0) w + (1+r) * arb_pf risk_free_asset (Suc 0) w\" by simp\n      also have \"... = -geom_proc (Suc 0) w + (1+r) * geom_proc 0 w\" by (simp add:arb_pf_def)\n      finally show \"cls_val_process Mkt arb_pf (Suc 0) w = -geom_proc (Suc 0) w + (1+r) * geom_proc 0 w\" .\n    qed\n    have iniT: \"\\<forall>w\\<in> space M. snth w 0 \\<longrightarrow> cls_val_process Mkt arb_pf (Suc 0) w \\<ge> 0\"\n    proof (intro ballI impI)\n      fix w\n      assume \"w\\<in> space M\" and \"snth w 0\"\n      have \"cls_val_process Mkt arb_pf (Suc 0) w =  -geom_proc (Suc 0) w + (1+r) * geom_proc 0 w\"\n        using dev \\<open>w\\<in> space M\\<close> by simp\n      also have \"... = - u * geom_proc 0 w + (1+r) * geom_proc 0 w\" using \\<open>snth w 0\\<close> geometric_process by simp\n      also have \"... = (-u + (1+r)) * geom_proc 0 w\" by (simp add: left_diff_distrib)\n      also have \"... \\<ge> 0\" using S0_positive \\<open>u\\<le> 1 + r\\<close> down_lt_up geometric_process by auto\n      finally show \"cls_val_process Mkt arb_pf (Suc 0) w \\<ge> 0\" .\n    qed\n    have iniF: \"\\<forall>w\\<in> space M. \\<not>snth w 0 \\<longrightarrow> cls_val_process Mkt arb_pf (Suc 0) w > 0\"\n    proof (intro ballI impI)\n      fix w\n      assume \"w\\<in> space M\" and \"\\<not>snth w 0\"\n      have \"cls_val_process Mkt arb_pf (Suc 0) w =  -geom_proc (Suc 0) w + (1+r) * geom_proc 0 w\"\n        using dev \\<open>w\\<in> space M\\<close> by simp\n      also have \"... = -d * geom_proc 0 w + (1+r) * geom_proc 0 w\" using \\<open>\\<not>snth w 0\\<close> geometric_process by simp\n      also have \"... = (-d + (1+r)) * geom_proc 0 w\" by (simp add: left_diff_distrib)\n      also have \"... > 0\" using S0_positive \\<open>u <= 1 + r\\<close> down_lt_up geometric_process by auto\n      finally show \"cls_val_process Mkt arb_pf (Suc 0) w > 0\" .\n    qed\n    have \"\\<forall>w\\<in> space M. cls_val_process Mkt arb_pf (Suc 0) w \\<ge> 0\"\n    proof\n      fix w\n      assume \"w\\<in> space M\"\n      show \"cls_val_process Mkt arb_pf (Suc 0) w \\<ge> 0\"\n      proof (cases \"snth w 0\")\n        case True\n        thus ?thesis using \\<open>w\\<in> space M\\<close> iniT by simp\n      next\n        case False\n        thus ?thesis using \\<open>w\\<in> space M\\<close> iniF by auto\n      qed\n    qed\n    thus \"AE w in M. 0 \\<le> cls_val_process Mkt arb_pf (Suc 0) w\" by simp\n    show \"0 < prob {w \\<in> space M. 0 < cls_val_process Mkt arb_pf (Suc 0) w}\"\n    proof -\n      have \"cls_val_process Mkt arb_pf (Suc 0) \\<in> borel_measurable M\" using borel_adapt_stoch_proc_borel_measurable\n        cls_val_process_adapted \\<open>trading_strategy arb_pf\\<close> \\<open>stock_portfolio Mkt arb_pf\\<close>\n         using support_adapt_def readable unfolding stock_portfolio_def by blast\n      hence set_event:\"{w \\<in> space M. 0 < cls_val_process Mkt arb_pf (Suc 0) w} \\<in> sets M\"\n        using borel_measurable_iff_greater by blast\n      have \"\\<forall>n. emeasure M {w \\<in> space M. \\<not>w !! n} = ennreal (1-p)\"\n        using bernoulli p_gt_0 p_lt_1 bernoulli_stream_component_probability_compl[of M p]\n        by auto\n      hence \"emeasure M {w \\<in> space M. \\<not>w !! 0} = ennreal (1-p)\" by blast\n      moreover have \"{w \\<in> space M. \\<not>w !! 0} \\<subseteq> {w \\<in> space M. 0 < cls_val_process Mkt arb_pf 1 w}\"\n      proof\n        fix w\n        assume \"w\\<in> {w \\<in> space M. \\<not>w !! 0}\"\n        hence \"w \\<in> space M\" and \"\\<not>w !! 0\" by auto note wprops = this\n        hence \"0 < cls_val_process Mkt arb_pf 1 w\" using iniF by simp\n        thus \"w\\<in> {w \\<in> space M. 0 < cls_val_process Mkt arb_pf 1 w}\" using wprops by simp\n      qed\n      ultimately have \"1-p \\<le> emeasure M {w \\<in> space M. 0 < cls_val_process Mkt arb_pf 1 w}\"\n        using emeasure_mono set_event by fastforce\n      hence \"1-p \\<le> prob {w \\<in> space M. 0 < cls_val_process Mkt arb_pf 1 w}\" by (simp add: emeasure_eq_measure)\n      thus \"0 < prob {w \\<in> space M. 0 < cls_val_process Mkt arb_pf (Suc 0) w}\" using pslt by simp\n    qed\n  qed\n  thus False using assms unfolding viable_market_def using \\<open>stock_portfolio Mkt arb_pf\\<close> by simp\nqed\n\nlemma (in CRR_market) viable_iff:\nshows \"viable_market Mkt \\<longleftrightarrow> (d < 1+r \\<and> 1+r < u)\" using viable_if viable_only_if_d viable_only_if_u by auto\n\n\nsubsection \\<open>Risk-neutral probability space for the geometric random walk\\<close>\n\n\n\nlemma (in CRR_market) stock_price_borel_measurable:\n  shows \"borel_adapt_stoch_proc G (prices Mkt stk)\"\nproof -\n  have \"borel_adapt_stoch_proc (stoch_proc_filt M geom_proc borel) (prices Mkt stk)\"\n    by (simp add: geom_rand_walk_borel_measurable stk_price stoch_proc_filt_adapt)\n  thus ?thesis by (simp add:stock_filtration)\nqed\n\n\nlemma (in CRR_market) risk_free_asset_martingale:\n  assumes \"N = bernoulli_stream q\"\n  and \"0 < q\"\n  and \"q < 1\"\n  shows \"martingale N G (discounted_value r (prices Mkt risk_free_asset))\"\nproof -\n  have \"filtration N G\" by (simp add: assms bernoulli_gen_filtration)\n  moreover have \"\\<forall>n. sigma_finite_subalgebra N (G n)\" by (simp add: assms bernoulli_sigma_finite)\n  moreover have \"finite_measure N\" using assms bernoulli_stream_def prob_space.prob_space_stream_space\n    prob_space_def prob_space_measure_pmf by auto\n  moreover have \"discounted_value r (prices Mkt risk_free_asset) = (\\<lambda> n w. 1)\" using discounted_rfr by auto\n  ultimately show ?thesis using finite_measure.constant_martingale by simp\nqed\n\n\n\n\n\n\n\nlemma (in CRR_market) geom_proc_integrable:\n  assumes \"N = bernoulli_stream q\"\nand \"0 \\<le> q\"\nand \"q \\<le> 1\"\nshows \"integrable N (geom_proc n)\"\nproof (rule infinite_coin_toss_space.nat_filtration_borel_measurable_integrable)\n  show \"infinite_coin_toss_space q N\" using assms by unfold_locales\n  show \"geom_proc n \\<in> borel_measurable (infinite_coin_toss_space.nat_filtration N n)\" using geometric_process\n    prob_grw.geom_rand_walk_borel_adapted[of q N geom_proc u d init]\n    by (metis \\<open>infinite_coin_toss_space q N\\<close> geom_rand_walk_pseudo_proj_True infinite_coin_toss_space.nat_filtration_borel_measurable_characterization\n         prob_grw.geom_rand_walk_borel_measurable prob_grw_axioms prob_grw_def)\nqed\n\nlemma (in CRR_market) CRR_infinite_cts_filtration:\n  shows \"infinite_cts_filtration p M nat_filtration\"\n  by (unfold_locales, simp)\n\n\nlemma (in CRR_market) proj_stoch_proc_geom_disc_fct:\n  shows \"disc_fct (proj_stoch_proc geom_proc n)\" unfolding disc_fct_def using CRR_infinite_cts_filtration\n    by (simp add: countable_finite geom_rand_walk_borel_adapted infinite_cts_filtration.proj_stoch_set_finite_range)\n\nlemma (in CRR_market) proj_stoch_proc_geom_rng:\n  assumes \"N = bernoulli_stream q\"\nshows  \"proj_stoch_proc geom_proc n \\<in> N \\<rightarrow>\\<^sub>M stream_space borel\"\nproof -\n  have \"random_variable (stream_space borel) (proj_stoch_proc geom_proc n)\" using CRR_infinite_cts_filtration\n    using geom_rand_walk_borel_adapted nat_discrete_filtration proj_stoch_measurable_if_adapted by blast\n  then show ?thesis\n    using assms(1) bernoulli bernoulli_stream_def by auto\nqed\n\nlemma (in CRR_market) proj_stoch_proc_geom_open_set:\n  shows  \"\\<forall>r\\<in>range (proj_stoch_proc geom_proc n) \\<inter> space (stream_space borel).\n     \\<exists>A\\<in>sets (stream_space borel). range (proj_stoch_proc geom_proc n) \\<inter> A = {r}\"\nproof\n  fix r\n  assume \"r\\<in> range (proj_stoch_proc geom_proc n) \\<inter> space (stream_space borel)\"\n  show \"\\<exists>A\\<in>sets (stream_space borel). range (proj_stoch_proc geom_proc n) \\<inter> A = {r}\"\n  proof\n    show \"infinite_cts_filtration.stream_space_single (proj_stoch_proc geom_proc n) r \\<in> sets (stream_space borel)\"\n      using infinite_cts_filtration.stream_space_single_set \\<open>r \\<in> range (proj_stoch_proc geom_proc n) \\<inter> space (stream_space borel)\\<close>\n        geom_rand_walk_borel_adapted CRR_infinite_cts_filtration by blast\n    show \"range (proj_stoch_proc geom_proc n) \\<inter> infinite_cts_filtration.stream_space_single (proj_stoch_proc geom_proc n) r = {r}\"\n      using infinite_cts_filtration.stream_space_single_preimage \\<open>r \\<in> range (proj_stoch_proc geom_proc n) \\<inter> space (stream_space borel)\\<close>\n        geom_rand_walk_borel_adapted CRR_infinite_cts_filtration by blast\n  qed\nqed\n\nlemma (in CRR_market) bernoulli_AE_cond_exp:\n  assumes \"N = bernoulli_stream q\"\nand \"0 < q\"\nand \"q < 1\"\nand \"integrable N X\"\nshows \"AE w in N. real_cond_exp N (fct_gen_subalgebra N (stream_space borel) (proj_stoch_proc geom_proc n)) X w =\n    expl_cond_expect N (proj_stoch_proc geom_proc n) X w\"\nproof (rule finite_measure.charact_cond_exp')\n  have \"infinite_cts_filtration p M nat_filtration\"\n    by (unfold_locales, simp)\n  show \"finite_measure N\" using assms\n    by (simp add: bernoulli_stream_def prob_space.finite_measure prob_space.prob_space_stream_space prob_space_measure_pmf)\n  show \"disc_fct (proj_stoch_proc geom_proc n)\" using proj_stoch_proc_geom_disc_fct by simp\n  show \"integrable N X\"  using assms by simp\n  show \"proj_stoch_proc geom_proc n \\<in> N \\<rightarrow>\\<^sub>M stream_space borel\" using assms proj_stoch_proc_geom_rng by simp\n  show \"\\<forall>r\\<in>range (proj_stoch_proc geom_proc n) \\<inter> space (stream_space borel).\n     \\<exists>A\\<in>sets (stream_space borel). range (proj_stoch_proc geom_proc n) \\<inter> A = {r}\"\n    using proj_stoch_proc_geom_open_set by simp\nqed\n\nlemma (in CRR_market) geom_proc_cond_exp:\n  assumes \"N = bernoulli_stream q\"\nand \"0 < q\"\nand \"q < 1\"\nshows \"AE w in N. real_cond_exp N (fct_gen_subalgebra N (stream_space borel) (proj_stoch_proc geom_proc n)) (geom_proc (Suc n)) w =\n    expl_cond_expect N (proj_stoch_proc geom_proc n) (geom_proc (Suc n)) w\"\nproof (rule bernoulli_AE_cond_exp)\n  show \"integrable N (geom_proc (Suc n))\"  using assms geom_proc_integrable[of N q \"Suc n\"] by simp\nqed (auto simp add: assms)\n\n\nlemma (in CRR_market) expl_cond_eq_sets:\n  assumes \"N = bernoulli_stream q\"\n  shows  \"expl_cond_expect N (proj_stoch_proc geom_proc n) X \\<in>\n        borel_measurable (fct_gen_subalgebra N (stream_space borel) (proj_stoch_proc geom_proc n))\"\nproof (rule expl_cond_exp_borel)\n  show \"proj_stoch_proc geom_proc n \\<in> space N \\<rightarrow> space (stream_space borel)\"\n  proof -\n    have \"random_variable (stream_space borel) (proj_stoch_proc geom_proc n)\"\n      using CRR_infinite_cts_filtration geom_rand_walk_borel_adapted proj_stoch_measurable_if_adapted\n        nat_discrete_filtration by blast\n    then show ?thesis\n      by (simp add: assms(1) bernoulli bernoulli_stream_space measurable_def)\n  qed\n  show \"disc_fct (proj_stoch_proc geom_proc n)\" unfolding disc_fct_def using CRR_infinite_cts_filtration\n    by (simp add: countable_finite geom_rand_walk_borel_adapted infinite_cts_filtration.proj_stoch_set_finite_range)\n  show \"\\<forall>r\\<in>range (proj_stoch_proc geom_proc n) \\<inter> space (stream_space borel).\n    \\<exists>A\\<in>sets (stream_space borel). range (proj_stoch_proc geom_proc n) \\<inter> A = {r}\"\n  proof\n    fix r\n    assume \"r\\<in>range (proj_stoch_proc geom_proc n) \\<inter> space (stream_space borel)\"\n    show \"\\<exists>A\\<in>sets (stream_space borel). range (proj_stoch_proc geom_proc n) \\<inter> A = {r}\"\n    proof\n      show \"infinite_cts_filtration.stream_space_single (proj_stoch_proc geom_proc n) r \\<in> sets (stream_space borel)\"\n        using infinite_cts_filtration.stream_space_single_set \\<open>r \\<in> range (proj_stoch_proc geom_proc n) \\<inter> space (stream_space borel)\\<close>\n          geom_rand_walk_borel_adapted CRR_infinite_cts_filtration by blast\n      show \"range (proj_stoch_proc geom_proc n) \\<inter> infinite_cts_filtration.stream_space_single (proj_stoch_proc geom_proc n) r = {r}\"\n        using infinite_cts_filtration.stream_space_single_preimage \\<open>r \\<in> range (proj_stoch_proc geom_proc n) \\<inter> space (stream_space borel)\\<close>\n          geom_rand_walk_borel_adapted CRR_infinite_cts_filtration by blast\n    qed\n  qed\nqed\n\n\nlemma (in CRR_market) bernoulli_real_cond_exp_AE:\n  assumes \"N = bernoulli_stream q\"\nand \"0 < q\"\nand \"q < 1\"\nand \"integrable N X\"\nshows \"real_cond_exp N (fct_gen_subalgebra N (stream_space borel) (proj_stoch_proc geom_proc n))\n   X w = expl_cond_expect N (proj_stoch_proc geom_proc n) X w\"\nproof -\n  have \"real_cond_exp N (fct_gen_subalgebra N (stream_space borel) (proj_stoch_proc geom_proc n))\n   X w = expl_cond_expect N (proj_stoch_proc geom_proc n) X w\"\n  proof (rule infinite_coin_toss_space.nat_filtration_AE_eq)\n    show \"infinite_coin_toss_space q N\" using assms\n      by (simp add: infinite_coin_toss_space_def)\n    show \"AE w in N. real_cond_exp N (fct_gen_subalgebra N (stream_space borel) (proj_stoch_proc geom_proc n)) X w =\n    expl_cond_expect N (proj_stoch_proc geom_proc n) X w\"  using assms bernoulli_AE_cond_exp by simp\n    show \"real_cond_exp N (fct_gen_subalgebra N (stream_space borel) (proj_stoch_proc geom_proc n)) X\n      \\<in> borel_measurable (infinite_coin_toss_space.nat_filtration N n)\"\n    proof -\n      have \"real_cond_exp N (fct_gen_subalgebra N (stream_space borel) (proj_stoch_proc geom_proc n)) X\n        \\<in> borel_measurable (fct_gen_subalgebra N (stream_space borel) (proj_stoch_proc geom_proc n))\"\n        by simp\n      moreover have \"subalgebra (infinite_coin_toss_space.nat_filtration N n) (fct_gen_subalgebra N (stream_space borel) (proj_stoch_proc geom_proc n))\"\n        using stock_filtration infinite_coin_toss_space.stoch_proc_subalg_nat_filt[of q N geom_proc n]\n        infinite_cts_filtration.stoch_proc_filt_gen[of q N]\n        by (metis \\<open>infinite_coin_toss_space q N\\<close> infinite_cts_filtration_axioms.intro infinite_cts_filtration_def\n            prob_grw.geom_rand_walk_borel_adapted prob_grw_axioms prob_grw_def)\n      ultimately show ?thesis using measurable_from_subalg by blast\n    qed\n    show \"expl_cond_expect N (proj_stoch_proc geom_proc n) X \\<in>\n      borel_measurable (infinite_coin_toss_space.nat_filtration N n)\"\n    proof -\n      have \"expl_cond_expect N (proj_stoch_proc geom_proc n) X \\<in>\n        borel_measurable (fct_gen_subalgebra N (stream_space borel) (proj_stoch_proc geom_proc n))\"\n        by (simp add: expl_cond_eq_sets assms)\n      moreover have \"subalgebra (infinite_coin_toss_space.nat_filtration N n) (fct_gen_subalgebra N (stream_space borel) (proj_stoch_proc geom_proc n))\"\n      using stock_filtration infinite_coin_toss_space.stoch_proc_subalg_nat_filt[of q N geom_proc n]\n        infinite_cts_filtration.stoch_proc_filt_gen[of q N]\n        by (metis \\<open>infinite_coin_toss_space q N\\<close> infinite_cts_filtration_axioms.intro infinite_cts_filtration_def\n            prob_grw.geom_rand_walk_borel_adapted prob_grw_axioms prob_grw_def)\n      ultimately show ?thesis using measurable_from_subalg by blast\n    qed\n    show \"0 < q\" and \"q < 1\" using assms by auto\n  qed\n  thus ?thesis by simp\nqed\n\nlemma (in CRR_market) geom_proc_real_cond_exp_AE:\n  assumes \"N = bernoulli_stream q\"\nand \"0 < q\"\nand \"q < 1\"\nshows \"real_cond_exp N (fct_gen_subalgebra N (stream_space borel) (proj_stoch_proc geom_proc n))\n   (geom_proc (Suc n)) w = expl_cond_expect N (proj_stoch_proc geom_proc n) (geom_proc (Suc n)) w\"\nproof (rule bernoulli_real_cond_exp_AE)\nshow \"integrable N (geom_proc (Suc n))\"  using assms geom_proc_integrable[of N q \"Suc n\"] by simp\nqed (auto simp add: assms)\n\n\nlemma (in CRR_market) geom_proc_stoch_proc_filt:\n  assumes \"N= bernoulli_stream q\"\nand \"0 < q\"\nand \"q < 1\"\nshows \"stoch_proc_filt N geom_proc borel n = fct_gen_subalgebra N (stream_space borel) (proj_stoch_proc geom_proc n)\"\nproof (rule infinite_cts_filtration.stoch_proc_filt_gen)\n  show \"infinite_cts_filtration q N (infinite_coin_toss_space.nat_filtration N)\" unfolding infinite_cts_filtration_def\n  proof\n    show \"infinite_coin_toss_space q N\" using assms\n      by (simp add: infinite_coin_toss_space_def)\n    show \"infinite_cts_filtration_axioms N (infinite_coin_toss_space.nat_filtration N)\"\n      using infinite_cts_filtration_axioms_def by blast\n  qed\n  show \"borel_adapt_stoch_proc (infinite_coin_toss_space.nat_filtration N) geom_proc\"\n    using \\<open>infinite_cts_filtration q N (infinite_coin_toss_space.nat_filtration N)\\<close>\n      prob_grw.geom_rand_walk_borel_adapted prob_grw_axioms prob_grw_def\n    using infinite_cts_filtration_def by auto\nqed\n\nlemma (in CRR_market) bernoulli_cond_exp:\n  assumes \"N = bernoulli_stream q\"\n  and \"0 < q\"\n  and \"q < 1\"\nand \"integrable N X\"\nshows \"real_cond_exp N (stoch_proc_filt N geom_proc borel n) X w = expl_cond_expect N (proj_stoch_proc geom_proc n) X w\"\nproof -\n  have aeq: \"AE w in N. real_cond_exp N (fct_gen_subalgebra N (stream_space borel) (proj_stoch_proc geom_proc n)) X w =\n    expl_cond_expect N (proj_stoch_proc geom_proc n) X w\"  using assms\n    bernoulli_AE_cond_exp by simp\n  have \"\\<forall>w. real_cond_exp N (fct_gen_subalgebra N (stream_space borel) (proj_stoch_proc geom_proc n))\n   X w = expl_cond_expect N (proj_stoch_proc geom_proc n) X w\"  using assms bernoulli_real_cond_exp_AE by simp\n  moreover have \"stoch_proc_filt N geom_proc borel n = fct_gen_subalgebra N (stream_space borel) (proj_stoch_proc geom_proc n)\"\n    using assms geom_proc_stoch_proc_filt by simp\n  ultimately show ?thesis by simp\nqed\n\nlemma (in CRR_market) stock_cond_exp:\n  assumes \"N = bernoulli_stream q\"\n  and \"0 < q\"\n  and \"q < 1\"\nshows \"real_cond_exp N (stoch_proc_filt N geom_proc borel n) (geom_proc (Suc n)) w = expl_cond_expect N (proj_stoch_proc geom_proc n) (geom_proc (Suc n)) w\"\nproof (rule bernoulli_cond_exp)\nshow \"integrable N (geom_proc (Suc n))\"  using assms geom_proc_integrable[of N q \"Suc n\"] by simp\nqed (auto simp add: assms)\n\n\n\n\nlemma (in prob_space) discount_factor_real_cond_exp:\n  assumes \"integrable M X\"\nand \"subalgebra M G\"\nand \"-1 < r\"\nshows \"AE w in M. real_cond_exp M G (\\<lambda>x. discount_factor r n x * X x) w = discount_factor r n w * (real_cond_exp M G X) w\"\nproof (rule sigma_finite_subalgebra.real_cond_exp_mult)\n  show \"sigma_finite_subalgebra M G\" using assms subalgebra_sigma_finite by simp\n  show \"discount_factor r n \\<in> borel_measurable G\" by (simp add: discount_factor_borel_measurable)\n  show \"random_variable borel X\" using assms by simp\n  show \"integrable M (\\<lambda>x. discount_factor r n x * X x)\"  using assms discounted_integrable[of M \"\\<lambda>n. X\"]\n    unfolding discounted_value_def by simp\nqed\n\n\nlemma (in prob_space) discounted_value_real_cond_exp:\n  assumes \"integrable M X\"\n  and \"-1 < r\"\nand \"subalgebra M G\"\n  shows \"AE w in M. real_cond_exp M G ((discounted_value r (\\<lambda> m. X)) n) w =\n    discounted_value r (\\<lambda>m. (real_cond_exp M G X)) n w\" using  assms\n  unfolding discounted_value_def  init_triv_filt_def filtration_def\n  by (simp add: assms discount_factor_real_cond_exp)\n\n\nlemma (in CRR_market)\n  assumes \"q = (1 + r - d)/(u -d)\"\n  and \"viable_market Mkt\"\n  shows gt_param: \"0 < q\"\n    and lt_param: \"q < 1\"\n    and risk_neutral_param: \"u * q + d * (1 - q) = 1 + r\"\nproof -\n  show \"0 < q\" using  down_lt_up viable_only_if_d assms by simp\n  show \"q < 1\" using down_lt_up viable_only_if_u assms by simp\n  show \"u * q + d * (1 - q) = 1 + r\"\n  proof -\n    have \"1 - q = 1 - (1 + r - d) / (u - d)\" using assms by simp\n    also have \"... = (u - d)/(u - d) - (1 + r - d) / (u - d)\" using down_lt_up by simp\n    also have \"... = (u - d - (1 + r - d))/(u-d)\" using  diff_divide_distrib[of \"u - d\" \"1 + r -d\" \"u -d\"] by simp\n    also have \"... = (u - 1 - r)/(u-d)\" by simp\n    finally have \"1 - q = (u - 1 - r)/(u -d)\" .\n    hence \"u * q + d * (1 - q) = u * (1 + r - d)/(u - d) + d * (u - 1 - r)/(u - d)\" using assms by simp\n    also have \"... = (u * (1 + r - d) + d * (u - 1 - r))/(u - d)\" using add_divide_distrib[of \"u * (1 + r - d)\"] by simp\n    also have \"... = (u * (1 + r) - u * d + d * u - d * (1 + r))/(u - d)\"\n      by (simp add: diff_diff_add right_diff_distrib')\n    also have \"... = (u * (1+r) - d * (1+r))/(u - d)\" by simp\n    also have \"... = ((u - d) * (1+r))/(u - d)\" by (simp add: left_diff_distrib)\n    also have \"... = 1 + r\" using down_lt_up by simp\n    finally show ?thesis .\n  qed\nqed\n\nlemma (in CRR_market) bernoulli_expl_cond_expect_adapt:\n  assumes \"N = bernoulli_stream q\"\nand \"0 < q\"\nand \"q < 1\"\n  shows \"expl_cond_expect N (proj_stoch_proc geom_proc n) f\\<in> borel_measurable (G n)\"\nproof -\n  have \"sets N = sets M\" using assms by (simp add: bernoulli bernoulli_stream_def sets_stream_space_cong)\n  have icf: \"infinite_cts_filtration p M nat_filtration\" by (unfold_locales, simp)\n  have \"G n = stoch_proc_filt M geom_proc borel n\" using stock_filtration by simp\n  also have \"... = fct_gen_subalgebra M (stream_space borel) (proj_stoch_proc geom_proc n)\"\n  proof (rule infinite_cts_filtration.stoch_proc_filt_gen)\n    show \"infinite_cts_filtration p M nat_filtration\" using icf .\n    show \"borel_adapt_stoch_proc nat_filtration geom_proc\" using geom_rand_walk_borel_adapted .\n  qed\n  also have \"... = fct_gen_subalgebra N (stream_space borel) (proj_stoch_proc geom_proc n)\"\n    by (rule fct_gen_subalgebra_eq_sets, (simp add: \\<open>sets N = sets M\\<close>))\n  finally have \"G n = fct_gen_subalgebra N (stream_space borel) (proj_stoch_proc geom_proc n)\" .\n  moreover have \"expl_cond_expect N (proj_stoch_proc geom_proc n) f \\<in>\n    borel_measurable (fct_gen_subalgebra N (stream_space borel) (proj_stoch_proc geom_proc n))\"\n    by (simp add: expl_cond_eq_sets assms)\n  ultimately show ?thesis by simp\nqed\n\n\n\nlemma (in CRR_market) real_cond_exp_discount_stock:\n  assumes \"N = bernoulli_stream q\"\nand \"0 < q\"\nand \"q < 1\"\nshows \"AE w in N. real_cond_exp N (G n)\n   (discounted_value r (prices Mkt stk) (Suc n)) w =\n                  discounted_value r (\\<lambda>m w. (q * u + (1 - q) * d) * prices Mkt stk n w) (Suc n) w\"\nproof -\n  have qlt: \"0 < q\" and qgt: \"q < 1\" using assms by auto\n  have \"G n = (fct_gen_subalgebra M (stream_space borel)\n                                (proj_stoch_proc geom_proc n))\"\n    using stock_filtration infinite_cts_filtration.stoch_proc_filt_gen[of p M nat_filtration geom_proc n] geometric_process\n      geom_rand_walk_borel_adapted CRR_infinite_cts_filtration by simp\n  also have \"... = (fct_gen_subalgebra N (stream_space borel)\n                                (proj_stoch_proc geom_proc n))\"\n  proof (rule fct_gen_subalgebra_eq_sets)\n    show \"events = sets N\" using assms qlt qgt\n      by (simp add: bernoulli bernoulli_stream_def sets_stream_space_cong)\n  qed\n  finally have \"G n = (fct_gen_subalgebra N (stream_space borel)\n                                (proj_stoch_proc geom_proc n))\" .\n  hence \"AE w in N. real_cond_exp N (G n)\n   (discounted_value r (prices Mkt stk) (Suc n)) w = real_cond_exp N (fct_gen_subalgebra N (stream_space borel)\n                                (proj_stoch_proc geom_proc n))\n                                (discounted_value r (prices Mkt stk) (Suc n)) w\" by simp\n  moreover have \"AE w in N. real_cond_exp N (fct_gen_subalgebra N (stream_space borel)\n                                (proj_stoch_proc geom_proc n))\n                                (discounted_value r (prices Mkt stk) (Suc n)) w =\n                            real_cond_exp N (fct_gen_subalgebra N (stream_space borel)\n                                (proj_stoch_proc geom_proc n))\n                                (discounted_value r (\\<lambda>m. (prices Mkt stk) (Suc n)) (Suc n)) w\"\n  proof -\n    have \"\\<forall>w. (discounted_value r (prices Mkt stk) (Suc n)) w =\n      (discounted_value r (\\<lambda>m. (prices Mkt stk) (Suc n)) (Suc n)) w\"\n    proof\n      fix w\n      show \"discounted_value r (prices Mkt stk) (Suc n) w = discounted_value r (\\<lambda>m. prices Mkt stk (Suc n)) (Suc n) w\"\n        by (simp add: discounted_value_def)\n    qed\n    hence \"(discounted_value r (prices Mkt stk) (Suc n)) =\n      (discounted_value r (\\<lambda>m. (prices Mkt stk) (Suc n)) (Suc n))\" by auto\n    thus ?thesis by simp\n    qed\n  moreover have \"AE w in N. (real_cond_exp N (fct_gen_subalgebra N (stream_space borel)\n                                (proj_stoch_proc geom_proc n))\n                                (discounted_value r (\\<lambda>m. (prices Mkt stk) (Suc n)) (Suc n))) w =\n               discounted_value r (\\<lambda>m. real_cond_exp N (fct_gen_subalgebra N (stream_space borel)\n                                                     (proj_stoch_proc geom_proc n))\n                                                     ((prices Mkt stk) (Suc n))) (Suc n) w\"\n  proof (rule prob_space.discounted_value_real_cond_exp)\n    show \"-1 < r\" using acceptable_rate by simp\n    show \"integrable N (prices Mkt stk (Suc n))\" using stk_price geom_proc_integrable assms qlt qgt by simp\n    show \"subalgebra N (fct_gen_subalgebra N (stream_space borel) (proj_stoch_proc geom_proc n))\"\n    proof (rule fct_gen_subalgebra_is_subalgebra)\n      show \"proj_stoch_proc geom_proc n \\<in> N \\<rightarrow>\\<^sub>M stream_space borel\"\n      proof -\n        have \"proj_stoch_proc geom_proc n \\<in> measurable M (stream_space borel)\"\n        proof (rule proj_stoch_measurable_if_adapted)\n          show \"borel_adapt_stoch_proc nat_filtration geom_proc\" using\n            geometric_process\n            geom_rand_walk_borel_adapted by simp\n          show \"filtration M nat_filtration\" using CRR_infinite_cts_filtration\n            by (simp add: nat_discrete_filtration)\n        qed\n        thus ?thesis using assms bernoulli_stream_equiv filt_equiv_measurable qlt qgt psgt pslt by blast\n      qed\n    qed\n    show \"prob_space N\" using assms\n      by (simp add: bernoulli bernoulli_stream_def prob_space.prob_space_stream_space prob_space_measure_pmf)\n  qed\n  moreover have \"AE w in N. discounted_value r (\\<lambda>m. real_cond_exp N (fct_gen_subalgebra N (stream_space borel)\n                                                     (proj_stoch_proc geom_proc n))\n                                                     ((prices Mkt stk) (Suc n))) (Suc n) w =\n                    discounted_value r (\\<lambda>m w. (q * u + (1 - q) * d) * prices Mkt stk n w) (Suc n) w\"\n  proof (rule discounted_AE_cong)\n   have \"AEeq N (real_cond_exp N (fct_gen_subalgebra N (stream_space borel)\n                                (proj_stoch_proc geom_proc n))\n                                ((prices Mkt stk) (Suc n)))\n               (\\<lambda>w. q * (prices Mkt stk) (Suc n) (pseudo_proj_True n w) +\n                (1 - q) * (prices Mkt stk) (Suc n) (pseudo_proj_False n w))\"\n     proof (rule infinite_cts_filtration.f_borel_Suc_real_cond_exp)\n      show icf: \"infinite_cts_filtration q N (infinite_coin_toss_space.nat_filtration N)\" unfolding infinite_cts_filtration_def\n      proof\n        show \"infinite_coin_toss_space q N\" using assms qlt qgt\n          by (simp add: infinite_coin_toss_space_def)\n        show \"infinite_cts_filtration_axioms N (infinite_coin_toss_space.nat_filtration N)\"\n          using infinite_cts_filtration_axioms_def by blast\n      qed\n      have badapt: \"borel_adapt_stoch_proc (infinite_coin_toss_space.nat_filtration N) (prices Mkt stk)\"\n        using stk_price prob_grw.geom_rand_walk_borel_adapted[of q N  geom_proc]\n        unfolding adapt_stoch_proc_def\n        by (metis (full_types) borel_measurable_integrable geom_proc_integrable geom_rand_walk_pseudo_proj_True icf\n            infinite_coin_toss_space.nat_filtration_borel_measurable_characterization infinite_coin_toss_space_def\n            infinite_cts_filtration_def)\n      show \"prices Mkt stk (Suc n) \\<in> borel_measurable (infinite_coin_toss_space.nat_filtration N (Suc n))\"\n        using badapt unfolding adapt_stoch_proc_def by simp\n      show \"proj_stoch_proc geom_proc n \\<in> infinite_coin_toss_space.nat_filtration N n \\<rightarrow>\\<^sub>M stream_space borel\"\n      proof (rule proj_stoch_adapted_if_adapted)\n        show \"filtration N (infinite_coin_toss_space.nat_filtration N)\" using icf\n          using infinite_coin_toss_space.nat_discrete_filtration infinite_cts_filtration_def by blast\n        show \"borel_adapt_stoch_proc (infinite_coin_toss_space.nat_filtration N) geom_proc\" using badapt stk_price by simp\n      qed\n      show \"set_discriminating n (proj_stoch_proc geom_proc n) (stream_space borel)\" unfolding set_discriminating_def\n      proof (intro allI impI)\n        fix w\n        assume \"proj_stoch_proc geom_proc n w \\<noteq> proj_stoch_proc geom_proc n (pseudo_proj_True n w)\"\n        hence False using CRR_infinite_cts_filtration\n          by (metis \\<open>proj_stoch_proc geom_proc n w \\<noteq> proj_stoch_proc geom_proc n (pseudo_proj_True n w)\\<close>\n            geom_rand_walk_borel_adapted infinite_cts_filtration.proj_stoch_proj_invariant)\n        thus \"\\<exists>A\\<in>sets (stream_space borel).\n      (proj_stoch_proc geom_proc n w \\<in> A) = (proj_stoch_proc geom_proc n (pseudo_proj_True n w) \\<notin> A)\" by simp\n      qed\n      show \"\\<forall>w. proj_stoch_proc geom_proc n -` {proj_stoch_proc geom_proc n w} \\<in>\n        sets (infinite_coin_toss_space.nat_filtration N n)\"\n      proof\n        fix w\n        show \"proj_stoch_proc geom_proc n -` {proj_stoch_proc geom_proc n w} \\<in> sets (infinite_coin_toss_space.nat_filtration N n)\"\n          using \\<open>proj_stoch_proc geom_proc n \\<in> infinite_coin_toss_space.nat_filtration N n \\<rightarrow>\\<^sub>M stream_space borel\\<close>\n          using assms geom_rand_walk_borel_adapted nat_filtration_from_eq_sets   qlt qgt\n            infinite_cts_filtration.proj_stoch_singleton_set CRR_infinite_cts_filtration by blast\n      qed\n      show \"\\<forall>r\\<in>range (proj_stoch_proc geom_proc n) \\<inter> space (stream_space borel).\n        \\<exists>A\\<in>sets (stream_space borel). range (proj_stoch_proc geom_proc n) \\<inter> A = {r}\"\n      proof\n        fix r\n        assume asm: \"r \\<in> range (proj_stoch_proc geom_proc n) \\<inter> space (stream_space borel)\"\n        define A where \"A = infinite_cts_filtration.stream_space_single (proj_stoch_proc geom_proc n) r\"\n        have \"A \\<in> sets (stream_space borel)\"  using infinite_cts_filtration.stream_space_single_set\n          unfolding A_def using badapt icf stk_price asm by blast\n        moreover have \"range (proj_stoch_proc geom_proc n) \\<inter> A = {r}\"\n          unfolding A_def using badapt icf stk_price infinite_cts_filtration.stream_space_single_preimage asm by blast\n        ultimately show \"\\<exists>A\\<in>sets (stream_space borel). range (proj_stoch_proc geom_proc n) \\<inter> A = {r}\" by auto\n      qed\n      show \"\\<forall>y z. proj_stoch_proc geom_proc n y = proj_stoch_proc geom_proc n z \\<and> y !! n = z !! n \\<longrightarrow>\n        prices Mkt stk (Suc n) y = prices Mkt stk (Suc n) z\"\n      proof (intro allI impI)\n        fix y z\n        assume \"proj_stoch_proc geom_proc n y = proj_stoch_proc geom_proc n z \\<and> y !! n = z !! n\"\n        hence \"geom_proc n y = geom_proc n z\" using proj_stoch_proc_component(2)[of n n]\n        proof -\n          show ?thesis\n            by (metis \\<open>\\<And>w f. n \\<le> n \\<Longrightarrow> proj_stoch_proc f n w !! n = f n w\\<close> \\<open>proj_stoch_proc geom_proc n y = proj_stoch_proc geom_proc n z \\<and> y !! n = z !! n\\<close> order_refl)\n        qed\n        hence \"geom_proc (Suc n) y = geom_proc (Suc n) z\" using geometric_process\n          by (simp add: \\<open>proj_stoch_proc geom_proc n y = proj_stoch_proc geom_proc n z \\<and> y !! n = z !! n\\<close>)\n        thus \"prices Mkt stk (Suc n) y = prices Mkt stk (Suc n) z\" using stk_price by simp\n      qed\n      show \"0 < q\" and \"q < 1\" using assms by auto\n    qed\n    moreover have \"\\<forall>w. q * prices Mkt stk (Suc n) (pseudo_proj_True n w) + (1 - q) * prices Mkt stk (Suc n) (pseudo_proj_False n w) =\n      (q * u + (1 - q) * d) * prices Mkt stk n w\"\n    proof\n      fix w\n      have \"q * prices Mkt stk (Suc n) (pseudo_proj_True n w) + (1 - q) * prices Mkt stk (Suc n) (pseudo_proj_False n w) =\n        q * geom_proc (Suc n) (pseudo_proj_True n w) + (1-q) * geom_proc (Suc n) (pseudo_proj_False n w)\"\n        by (simp add:stk_price)\n      also have \"... = q * u * geom_proc n (pseudo_proj_True n w) + (1-q) * geom_proc (Suc n) (pseudo_proj_False n w)\"\n        using geometric_process unfolding pseudo_proj_True_def by simp\n      also have \"... = q * u * geom_proc n w + (1-q) * geom_proc (Suc n) (pseudo_proj_False n w)\"\n        by (metis geom_rand_walk_pseudo_proj_True o_apply)\n      also have \"... = q * u * geom_proc n w + (1-q) * d * geom_proc n (pseudo_proj_False n w)\"\n        using geometric_process unfolding pseudo_proj_False_def by simp\n      also have \"... = q * u * geom_proc n w + (1-q) * d * geom_proc n w\"\n        by (metis geom_rand_walk_pseudo_proj_False o_apply)\n      also have \"... = (q * u + (1 - q) * d) * geom_proc n w\" by (simp add: distrib_right)\n      finally show \"q * prices Mkt stk (Suc n) (pseudo_proj_True n w) + (1 - q) * prices Mkt stk (Suc n) (pseudo_proj_False n w) =\n        (q * u + (1 - q) * d) * prices Mkt stk n w\" using stk_price by simp\n    qed\n    ultimately show \"AEeq N (real_cond_exp N (fct_gen_subalgebra N (stream_space borel)\n                                  (proj_stoch_proc geom_proc n))\n                                  ((prices Mkt stk) (Suc n)))\n                    (\\<lambda>w. (q * u + (1 - q) * d) * prices Mkt stk n w)\" by simp\n  qed\n  ultimately show ?thesis by auto\nqed\n\n\n\nlemma (in CRR_market) risky_asset_martingale_only_if:\n  assumes \"N = bernoulli_stream q\"\n  and \"0 < q\"\n  and \"q < 1\"\n  and  \"martingale N G (discounted_value r (prices Mkt stk))\"\nshows \"q = (1 + r - d) / (u - d)\"\nproof -\n  have \"AE w in N. real_cond_exp N (G 0)\n       (discounted_value r (prices Mkt stk) (Suc 0)) w =  discounted_value r (prices Mkt stk) 0 w\" using assms\n    unfolding martingale_def by simp\n  hence \"AE w in N. real_cond_exp N (G 0)\n       (discounted_value r (prices Mkt stk) (Suc 0)) w =  prices Mkt stk 0 w\" by (simp add: discounted_init)\n  moreover have \"AE w in N. real_cond_exp N (G 0) (discounted_value r (prices Mkt stk) (Suc 0)) w =\n    discounted_value r (\\<lambda>m w. (q * u + (1 - q) * d) * prices Mkt stk 0 w) (Suc 0) w\"\n    using assms real_cond_exp_discount_stock by simp\n  ultimately have \"AE w in N. discounted_value r (\\<lambda>m w. (q * u + (1 - q) * d) * prices Mkt stk 0 w) (Suc 0) w =\n    prices Mkt stk 0 w\" by auto\n  hence \"AE w in N. discounted_value r (\\<lambda>m w. (q * u + (1 - q) * d) * init) (Suc 0) w =\n    (\\<lambda>w. init) w\" using stk_price geometric_process by simp\n  hence \"AE w in N. discount_factor r (Suc 0) w * (q * u + (1 - q) * d) * init =\n    (\\<lambda>w. init) w\" unfolding discounted_value_def by simp\n  hence \"AE w in N. (1+r) * discount_factor r (Suc 0) w * (q * u + (1 - q) * d) * init =\n    (1+r) * (\\<lambda>w. init) w\" by auto\n  hence prev: \"AE w in N. discount_factor r 0 w * (q * u + (1 - q) * d) * init =\n    (1+r) * (\\<lambda>w. init) w\" using discount_factor_times_rfr[of r 0] acceptable_rate\n  proof -\n    have \"\\<forall>s. (1 + r) * discount_factor r (Suc 0) (s::bool stream) = discount_factor r 0 s\"\n    by (metis (no_types) \\<open>\\<And>w. - 1 < r \\<Longrightarrow> (1 + r) * discount_factor r (Suc 0) w = discount_factor r 0 w\\<close> acceptable_rate)\n    then show ?thesis\n    using \\<open>AEeq N (\\<lambda>w. (1 + r) * discount_factor r (Suc 0) w * (q * u + (1 - q) * d) * init) (\\<lambda>w. (1 + r) * init)\\<close> by presburger\n  qed\n  hence \"\\<forall>w. (\\<lambda>w. discount_factor r 0 w * (q * u + (1 - q) * d) * init) w =\n    (\\<lambda>w. (1+r) * init) w\"\n  proof -\n    have \"(\\<lambda>w. discount_factor r 0 w *  (q * u + (1 - q) * d) * init)\n      \\<in> borel_measurable (infinite_coin_toss_space.nat_filtration N 0)\"\n    proof (rule borel_measurable_times)+\n      show \"(\\<lambda>x. init) \\<in> borel_measurable (infinite_coin_toss_space.nat_filtration N 0)\" by simp\n      show \"(\\<lambda>x. q * u + (1 - q) * d) \\<in> borel_measurable (infinite_coin_toss_space.nat_filtration N 0)\" by simp\n      show \"discount_factor r 0 \\<in> borel_measurable (infinite_coin_toss_space.nat_filtration N 0)\"\n        using discount_factor_nonrandom[of r 0 \"infinite_coin_toss_space.nat_filtration N 0\"] by simp\n    qed\n    moreover have \"(\\<lambda>w. (1 + r) * init) \\<in> borel_measurable (infinite_coin_toss_space.nat_filtration N 0)\" by simp\n    moreover have \"infinite_coin_toss_space q N\" using assms by (simp add: infinite_coin_toss_space_def)\n    ultimately show ?thesis\n      using  prev infinite_coin_toss_space.nat_filtration_AE_eq[of q N\n        \"(\\<lambda>w. discount_factor r 0 w * (q * u + (1 - q) * d) * init)\" \"(\\<lambda>w. (1 + r) * init)\" 0] assms\n      by (simp add: discount_factor_init)\n  qed\n  hence \"(q * u + (1 - q) * d) * init = (1+r) * init\" by (simp add: discount_factor_init)\n  hence \"q * u + (1 - q) * d = 1+r\" using S0_positive by simp\n  hence \"q * u + d - q * d = 1+r\" by (simp add: left_diff_distrib)\n  hence \"q * (u - d) = 1 + r - d\"\n    by (metis (no_types, hide_lams) add.commute add.left_commute add_diff_cancel_left' add_uminus_conv_diff left_diff_distrib mult.commute)\n  thus \"q = (1 + r - d) / (u - d)\" using down_lt_up\n    by (metis add.commute add.right_neutral diff_add_cancel nonzero_eq_divide_eq order_less_irrefl)\nqed\n\n\n\nlocale CRR_market_viable = CRR_market +\n  assumes CRR_viable: \"viable_market Mkt\"\n\n\nlemma (in CRR_market_viable) real_cond_exp_discount_stock_q_const:\n  assumes \"N = bernoulli_stream q\"\nand \"q = (1+r-d) / (u-d)\"\nshows \"AE w in N. real_cond_exp N (G n)\n   (discounted_value r (prices Mkt stk) (Suc n)) w =\n                  discounted_value r (prices Mkt stk) n w\"\nproof -\n  have qlt: \"0 < q\" and qgt: \"q < 1\" using assms gt_param lt_param CRR_viable by auto\n  have \"AE w in N. real_cond_exp N (G n) (discounted_value r (prices Mkt stk) (Suc n)) w =\n                  discounted_value r (\\<lambda>m w. (q * u + (1 - q) * d) * prices Mkt stk n w) (Suc n) w\"\n    using assms real_cond_exp_discount_stock[of N q] qlt qgt by simp\n  moreover have \"\\<forall>w. (q * u + (1 - q) * d) * prices Mkt stk n w =\n    (1+r) * prices Mkt stk n w\" using risk_neutral_param assms CRR_viable\n      by (simp add: mult.commute)\n  ultimately have \"AE w in N. real_cond_exp N (G n) (discounted_value r (prices Mkt stk) (Suc n)) w =\n                  discounted_value r (\\<lambda>m w. (1+r) * prices Mkt stk n w) (Suc n) w\" by simp\n  moreover have \"\\<forall>w\\<in> space N. discounted_value r (\\<lambda>m w. (1+r) * prices Mkt stk n w) (Suc n) w =\n                     discounted_value r (\\<lambda>m w. prices Mkt stk n w) n w\"\n    using  acceptable_rate by (simp add:discounted_mult_times_rfr)\n  moreover hence \"\\<forall>w\\<in> space N. discounted_value r (\\<lambda>m w. (1+r) * prices Mkt stk n w) (Suc n) w =\n                     discounted_value r (prices Mkt stk) n w\"\n    using  acceptable_rate by (simp add:discounted_value_def)\n  ultimately show \"AE w in N. real_cond_exp N (G n) (discounted_value r (prices Mkt stk) (Suc n)) w =\n                    discounted_value r (prices Mkt stk) n w\" by simp\nqed\n\n\nlemma (in CRR_market_viable) risky_asset_martingale_if:\n  assumes \"N = bernoulli_stream q\"\n  and \"q = (1 + r - d) / (u - d)\"\nshows \"martingale N G (discounted_value r (prices Mkt stk))\"\nproof (rule disc_martingale_charact)\n  have qlt: \"0 < q\" and qgt: \"q < 1\" using assms gt_param lt_param CRR_viable by auto\n  show \"\\<forall>n. integrable N (discounted_value r (prices Mkt stk) n)\"\n  proof\n    fix n\n    show \"integrable N (discounted_value r (prices Mkt stk) n)\"\n    proof (rule discounted_integrable)\n      show \"space N = space M\" using assms by (simp add: bernoulli bernoulli_stream_space)\n      show \"integrable N (prices Mkt stk n)\"\n      proof (rule infinite_coin_toss_space.nat_filtration_borel_measurable_integrable)\n        show \"infinite_coin_toss_space q N\" using assms qlt qgt\n          by (simp add: infinite_coin_toss_space_def)\n        show \"prices Mkt stk n \\<in> borel_measurable (infinite_coin_toss_space.nat_filtration N n)\"\n          using geom_rand_walk_borel_adapted stk_price  nat_filtration_from_eq_sets unfolding adapt_stoch_proc_def\n          by (metis \\<open>infinite_coin_toss_space q N\\<close> borel_measurable_integrable geom_proc_integrable geom_rand_walk_pseudo_proj_True\n              infinite_coin_toss_space.nat_filtration_borel_measurable_characterization infinite_coin_toss_space_def)\n      qed\n      show \"-1 < r\" using acceptable_rate by simp\n    qed\n  qed\n  show \"filtration N G\" using qlt qgt by (simp add: bernoulli_gen_filtration assms)\n  show \"\\<forall>n. sigma_finite_subalgebra N (G n)\" using qlt qgt by (simp add: assms bernoulli_sigma_finite)\n  show \"\\<forall>m. discounted_value r (prices Mkt stk) m \\<in> borel_measurable (G m)\"\n  proof\n    fix m\n    have \"discounted_value r (\\<lambda>ma. prices Mkt stk m) m \\<in> borel_measurable (G m)\"\n    proof (rule discounted_measurable)\n      show \"prices Mkt stk m \\<in> borel_measurable (G m)\" using stock_price_borel_measurable\n        unfolding adapt_stoch_proc_def by simp\n    qed\n    thus \"discounted_value r (prices Mkt stk) m \\<in> borel_measurable (G m)\"\n      by (metis (mono_tags, lifting) discounted_value_def measurable_cong)\n  qed\n  show \"\\<forall>n. AE w in N. real_cond_exp N (G n)\n       (discounted_value r (prices Mkt stk) (Suc n)) w = discounted_value r (prices Mkt stk) n w\"\n  proof\n    fix n\n    show \"AE w in N. real_cond_exp N (G n)\n       (discounted_value r (prices Mkt stk) (Suc n)) w = discounted_value r (prices Mkt stk) n w\"\n      using assms real_cond_exp_discount_stock_q_const by simp\n  qed\nqed\n\n\nlemma (in CRR_market_viable) risk_neutral_iff':\n  assumes \"N = bernoulli_stream q\"\nand \"0 \\<le> q\"\nand \"q \\<le> 1\"\nand \"filt_equiv nat_filtration M N\"\nshows \"rfr_disc_equity_market.risk_neutral_prob G Mkt r N \\<longleftrightarrow> q= (1 + r - d) / (u - d)\"\nproof\n  have \"0 < q\" and \"q < 1\" using assms filt_equiv_sgt filt_equiv_slt psgt pslt by auto note qprops = this\n  have dem: \"rfr_disc_equity_market M G Mkt r risk_free_asset\"  by unfold_locales\n  {\n    assume \"rfr_disc_equity_market.risk_neutral_prob G Mkt r N\"\n    hence \"(prob_space N) \\<and> (\\<forall> asset \\<in> stocks Mkt. martingale N G (discounted_value r (prices Mkt asset)))\"\n      using rfr_disc_equity_market.risk_neutral_prob_def[of M G Mkt] dem  by simp\n    hence \"martingale N G (discounted_value r (prices Mkt stk))\" using stocks by simp\n    thus \"q = (1 + r - d) / (u - d)\" using assms risky_asset_martingale_only_if[of N q] qprops by simp\n  }\n  {\n    assume \"q = (1 + r - d) / (u - d)\"\n    hence \"martingale N G (discounted_value r (prices Mkt stk))\" using risky_asset_martingale_if[of N q] assms by simp\n    moreover have \"martingale N G (discounted_value r (prices Mkt risk_free_asset))\" using risk_free_asset_martingale\n      assms qprops by simp\n    ultimately show \"rfr_disc_equity_market.risk_neutral_prob G Mkt r N\" using stocks\n      using assms(1) bernoulli_stream_def dem prob_space.prob_space_stream_space prob_space_measure_pmf\n        rfr_disc_equity_market.risk_neutral_prob_def by fastforce\n  }\nqed\n\nlemma (in CRR_market_viable) risk_neutral_iff:\n  assumes \"N = bernoulli_stream q\"\nand \"0 < q\"\nand \"q < 1\"\nshows \"rfr_disc_equity_market.risk_neutral_prob G Mkt r N \\<longleftrightarrow> q= (1 + r - d) / (u - d)\"\n  using bernoulli_stream_equiv assms risk_neutral_iff' psgt pslt by auto\n\nsubsection \\<open>Existence of a replicating portfolio\\<close>\n\n\n\n\nfun (in CRR_market) rn_rev_price where\n  \"rn_rev_price N der matur 0 w = der w\" |\n  \"rn_rev_price N der matur (Suc n) w = discount_factor r (Suc 0) w *\n                                  expl_cond_expect N (proj_stoch_proc geom_proc (matur - Suc n)) (rn_rev_price N der matur n) w\"\n\n\n\n\n\n\nlemma (in CRR_market) stock_filtration_eq:\n  assumes \"N = bernoulli_stream q\"\nand \"0 < q\"\nand \"q < 1\"\nshows \"G n = stoch_proc_filt N geom_proc borel n\"\nproof -\n  have \"G n= stoch_proc_filt M geom_proc borel n\" using stock_filtration by simp\n  also have \"... = stoch_proc_filt N geom_proc borel n\"\n  proof (rule stoch_proc_filt_filt_equiv)\n    show \"filt_equiv nat_filtration M N\" using assms bernoulli_stream_equiv psgt pslt by simp\n  qed\n  finally show ?thesis .\nqed\n\n\n\nlemma (in CRR_market) real_exp_eq:\n  assumes \"der\\<in> borel_measurable (G matur)\"\nand \"N = bernoulli_stream q\"\nand \"0 < q\"\nand \"q < 1\"\nshows \"real_cond_exp N (stoch_proc_filt N geom_proc borel n) der w =\n      expl_cond_expect N (proj_stoch_proc geom_proc n) der w\"\nproof -\n  have \"der \\<in> borel_measurable (nat_filtration matur)\" using assms\n      using geom_rand_walk_borel_adapted measurable_from_subalg stoch_proc_subalg_nat_filt stock_filtration by blast\n  have \"integrable N der\"\n  proof (rule infinite_coin_toss_space.nat_filtration_borel_measurable_integrable)\n    show \"infinite_coin_toss_space q N\" using assms\n      by (simp add: infinite_coin_toss_space_def)\n    show \"der \\<in> borel_measurable (infinite_coin_toss_space.nat_filtration N matur)\"\n      by (metis \\<open>der \\<in> borel_measurable (nat_filtration matur)\\<close> \\<open>infinite_coin_toss_space q N\\<close>\n          assms(2) assms(3) assms(4) infinite_coin_toss_space.nat_filtration_space measurable_from_subalg\n          nat_filtration_from_eq_sets nat_filtration_space subalgebra_def subset_eq)\n  qed\n  show \"real_cond_exp N (stoch_proc_filt N geom_proc borel n) der w =\n    expl_cond_expect N (proj_stoch_proc geom_proc n) der w\"\n  proof (rule bernoulli_cond_exp)\n    show \"N = bernoulli_stream q\" \"0 < q\" \"q < 1\" using assms by auto\n    show \"integrable N der\" using \\<open>integrable N der\\<close> .\n  qed\nqed\n\nlemma (in CRR_market) rn_rev_price_rev_borel_adapt:\nassumes \"cash_flow \\<in> borel_measurable (G matur)\"\nand \"N = bernoulli_stream q\"\nand \"0 < q\"\nand \"q < 1\"\nshows \"(n \\<le> matur) \\<Longrightarrow> (rn_rev_price N cash_flow matur n) \\<in> borel_measurable (G (matur - n))\"\nproof (induct n)\ncase 0 thus ?case using assms by simp\nnext\n  case (Suc n)\n  have \"rn_rev_price N cash_flow matur (Suc n) =\n      (\\<lambda>w. discount_factor r (Suc 0) w *\n        (expl_cond_expect N (proj_stoch_proc geom_proc (matur - Suc n)) (rn_rev_price N cash_flow matur n)) w)\"\n    using rn_rev_price.simps(2) by blast\n  also have \"... \\<in> borel_measurable (G (matur - Suc n))\"\n  proof (rule borel_measurable_times)\n    show \"discount_factor r (Suc 0) \\<in> borel_measurable (G (matur - Suc n))\" by (simp add:discount_factor_borel_measurable)\n    show \"expl_cond_expect N (proj_stoch_proc geom_proc (matur - Suc n)) (rn_rev_price N cash_flow matur n)\n      \\<in> borel_measurable (G (matur - Suc n))\" using assms by (simp add: bernoulli_expl_cond_expect_adapt)\n  qed\n  finally show \"rn_rev_price N cash_flow matur (Suc n) \\<in> borel_measurable (G (matur - Suc n))\" .\nqed\n\nlemma (in infinite_coin_toss_space) bernoulli_discounted_integrable:\n  assumes \"N = bernoulli_stream q\"\nand \"0 < q\"\nand \"q < 1\"\n  and \"der \\<in> borel_measurable (nat_filtration n)\"\nand \"-1 < r\"\n  shows \"integrable N (discounted_value r (\\<lambda>m. der) m)\"\nproof -\n  have \"prob_space N\" using assms\n    by (simp add: bernoulli bernoulli_stream_def prob_space.prob_space_stream_space prob_space_measure_pmf)\n  have \"integrable N der\"\n  proof (rule infinite_coin_toss_space.nat_filtration_borel_measurable_integrable)\n    show \"infinite_coin_toss_space q N\" using assms\n      by (simp add: infinite_coin_toss_space_def)\n    show \"der \\<in> borel_measurable (infinite_coin_toss_space.nat_filtration N n)\"\n      using assms filt_equiv_filtration\n      by (simp add: assms(1) measurable_def nat_filtration_from_eq_sets nat_filtration_space)\n  qed\n  thus ?thesis using discounted_integrable assms\n    by (metis \\<open>prob_space N\\<close> prob_space.discounted_integrable)\nqed\n\n\n\nlemma (in CRR_market) rn_rev_expl_cond_expect:\n  assumes \"der\\<in> borel_measurable (G matur)\"\nand \"N = bernoulli_stream q\"\nand \"0 < q\"\nand \"q < 1\"\nshows \"n \\<le> matur \\<Longrightarrow> rn_rev_price N der matur n w =\n  expl_cond_expect N (proj_stoch_proc geom_proc (matur - n)) (discounted_value r (\\<lambda>m. der) n) w\"\nproof (induct n arbitrary: w)\n  case 0\n  have \"der \\<in> borel_measurable (nat_filtration matur)\" using assms\n      using geom_rand_walk_borel_adapted measurable_from_subalg stoch_proc_subalg_nat_filt stock_filtration by blast\n  have \"integrable N der\"\n  proof (rule infinite_coin_toss_space.nat_filtration_borel_measurable_integrable)\n    show \"infinite_coin_toss_space q N\" using assms\n      by (simp add: infinite_coin_toss_space_def)\n    show \"der \\<in> borel_measurable (infinite_coin_toss_space.nat_filtration N matur)\"\n      by (metis \\<open>der \\<in> borel_measurable (nat_filtration matur)\\<close> \\<open>infinite_coin_toss_space q N\\<close>\n          assms(2) assms(3) assms(4) infinite_coin_toss_space.nat_filtration_space measurable_from_subalg\n          nat_filtration_from_eq_sets nat_filtration_space subalgebra_def subset_eq)\n  qed\n  have \"rn_rev_price N der matur 0 w = der w\" by simp\n  also have \"... = expl_cond_expect N (proj_stoch_proc geom_proc matur) (discounted_value r (\\<lambda>m. der) 0) w\"\n  proof (rule nat_filtration_AE_eq)\n    show \"der \\<in> borel_measurable (nat_filtration matur)\" using \\<open>der \\<in> borel_measurable (nat_filtration matur)\\<close> .\n    have \"(discounted_value r (\\<lambda>m. der) 0) = der\" unfolding discounted_value_def discount_factor_def by simp\n    moreover have \"AEeq N (real_cond_exp N (G matur) der) der\"\n    proof (rule sigma_finite_subalgebra.real_cond_exp_F_meas)\n      show \"der \\<in> borel_measurable (G matur)\" using assms by simp\n      show \"integrable N der\" using \\<open>integrable N der\\<close> .\n      show \"sigma_finite_subalgebra N (G matur)\" using bernoulli_sigma_finite\n        using assms by simp\n    qed\n    moreover have \"\\<forall>w. real_cond_exp N (stoch_proc_filt N geom_proc borel matur) der w =\n      expl_cond_expect N (proj_stoch_proc geom_proc matur) der w\" using assms real_exp_eq by simp\n    ultimately have eqn: \"AEeq N der (expl_cond_expect N (proj_stoch_proc geom_proc matur) (discounted_value r (\\<lambda>m. der) 0))\"\n      using stock_filtration_eq assms by auto\n    have \"stoch_proc_filt M geom_proc borel matur = stoch_proc_filt N geom_proc borel matur\"\n      using  bernoulli_stream_equiv[of N q] assms psgt pslt by (simp add: stoch_proc_filt_filt_equiv)\n    also have \"stoch_proc_filt N geom_proc borel matur =\n      fct_gen_subalgebra N (stream_space borel) (proj_stoch_proc geom_proc matur)\"\n      using assms geom_proc_stoch_proc_filt by simp\n    finally have \"stoch_proc_filt M geom_proc borel matur =\n      fct_gen_subalgebra N (stream_space borel) (proj_stoch_proc geom_proc matur)\" .\n    moreover have \"expl_cond_expect N (proj_stoch_proc geom_proc matur) (discounted_value r (\\<lambda>m. der) 0)\n      \\<in> borel_measurable (fct_gen_subalgebra N (stream_space borel) (proj_stoch_proc geom_proc matur))\"\n    proof (rule expl_cond_exp_borel)\n      show \"proj_stoch_proc geom_proc matur \\<in> space N \\<rightarrow> space (stream_space borel)\"\n        using assms proj_stoch_proc_geom_rng by (simp add: measurable_def)\n      show \"disc_fct (proj_stoch_proc geom_proc matur)\" using proj_stoch_proc_geom_disc_fct by simp\n      show \"\\<forall>r\\<in>range (proj_stoch_proc geom_proc matur) \\<inter> space (stream_space borel).\n        \\<exists>A\\<in>sets (stream_space borel). range (proj_stoch_proc geom_proc matur) \\<inter> A = {r}\"\n        using proj_stoch_proc_geom_open_set by simp\n    qed\n    ultimately show ebm: \"expl_cond_expect N (proj_stoch_proc geom_proc matur) (discounted_value r (\\<lambda>m. der) 0)\n      \\<in> borel_measurable (nat_filtration matur)\"\n      by (metis geom_rand_walk_borel_adapted measurable_from_subalg stoch_proc_subalg_nat_filt)\n    show \"AEeq M der (expl_cond_expect N (proj_stoch_proc geom_proc matur) (discounted_value r (\\<lambda>m. der) 0))\"\n    proof (rule filt_equiv_borel_AE_eq_iff[THEN iffD2])\n      show \"filt_equiv nat_filtration M N\" using assms bernoulli_stream_equiv psgt pslt by simp\n      show \"der \\<in> borel_measurable (nat_filtration matur)\" using \\<open>der \\<in> borel_measurable (nat_filtration matur)\\<close> .\n      show \"AEeq N der (expl_cond_expect N (proj_stoch_proc geom_proc matur) (discounted_value r (\\<lambda>m. der) 0))\"\n        using eqn .\n      show \"expl_cond_expect N (proj_stoch_proc geom_proc matur) (discounted_value r (\\<lambda>m. der) 0)\n        \\<in> borel_measurable (nat_filtration matur)\" using ebm .\n      show \"prob_space N\" using assms by (simp add: bernoulli_stream_def\n            prob_space.prob_space_stream_space prob_space_measure_pmf)\n      show \"prob_space M\" by (simp add: bernoulli bernoulli_stream_def\n            prob_space.prob_space_stream_space prob_space_measure_pmf)\n    qed\n    show \"0 < p\" \"p < 1\" using psgt pslt by auto\n  qed\n  also have \"... = expl_cond_expect N (proj_stoch_proc geom_proc (matur - 0)) (discounted_value r (\\<lambda>m. der) 0) w\"\n    by simp\n  finally show \"rn_rev_price N der matur 0 w =\n    expl_cond_expect N (proj_stoch_proc geom_proc (matur - 0)) (discounted_value r (\\<lambda>m. der) 0) w\" .\nnext\n  case (Suc n)\n  have \"rn_rev_price N der matur (Suc n) w = discount_factor r (Suc 0) w *\n          expl_cond_expect N (proj_stoch_proc geom_proc (matur - Suc n)) (rn_rev_price N der matur n) w\" by simp\n  also have \"... = discount_factor r (Suc 0) w *\n    real_cond_exp N (stoch_proc_filt N geom_proc borel (matur - Suc n)) (rn_rev_price N der matur n) w\"\n  proof -\n    have \"expl_cond_expect N (proj_stoch_proc geom_proc (matur - Suc n)) (rn_rev_price N der matur n) w =\n     real_cond_exp N (stoch_proc_filt N geom_proc borel (matur - Suc n)) (rn_rev_price N der matur n) w\"\n    proof (rule real_exp_eq[symmetric])\n      show \"rn_rev_price N der matur n \\<in> borel_measurable (G (matur - n))\"\n        using assms rn_rev_price_rev_borel_adapt Suc by simp\n      show \"N = bernoulli_stream q\" \"0 < q\" \"q < 1\" using assms by auto\n    qed\n    thus ?thesis by simp\n  qed\n  also have \"... = discount_factor r (Suc 0) w *\n    real_cond_exp N (stoch_proc_filt N geom_proc borel (matur - Suc n))\n    (expl_cond_expect N (proj_stoch_proc geom_proc (matur - n)) (discounted_value r (\\<lambda>m. der) n)) w\"\n  proof -\n    have \"real_cond_exp N (stoch_proc_filt N geom_proc borel (matur - Suc n)) (rn_rev_price N der matur n) w =\n      real_cond_exp N (stoch_proc_filt N geom_proc borel (matur - Suc n))\n    (expl_cond_expect N (proj_stoch_proc geom_proc (matur - n)) (discounted_value r (\\<lambda>m. der) n)) w\"\n    proof (rule infinite_coin_toss_space.nat_filtration_AE_eq)\n      show \"AEeq N (real_cond_exp N (stoch_proc_filt N geom_proc borel (matur - Suc n)) (rn_rev_price N der matur n))\n        (real_cond_exp N (stoch_proc_filt N geom_proc borel (matur - Suc n))\n        (expl_cond_expect N (proj_stoch_proc geom_proc (matur - n)) (discounted_value r (\\<lambda>m. der) n)))\"\n      proof (rule sigma_finite_subalgebra.real_cond_exp_cong)\n        show \"sigma_finite_subalgebra N (stoch_proc_filt N geom_proc borel (matur - Suc n))\"\n          using assms(2) assms(3) assms(4) bernoulli_sigma_finite stock_filtration_eq by auto\n        show \"rn_rev_price N der matur n \\<in> borel_measurable N\"\n        proof -\n          have \"rn_rev_price N der matur n \\<in> borel_measurable (G (matur - n))\"\n            by (metis (full_types) Suc.prems Suc_leD assms(1) assms(2) assms(3) assms(4) rn_rev_price_rev_borel_adapt)\n          then show ?thesis\n            by (metis (no_types) assms(2) bernoulli bernoulli_stream_def filtration_measurable measurable_cong_sets sets_measure_pmf sets_stream_space_cong)\n        qed\n        show \"expl_cond_expect N (proj_stoch_proc geom_proc (matur - n)) (discounted_value r (\\<lambda>m. der) n) \\<in> borel_measurable N\"\n          using Suc.hyps Suc.prems Suc_leD \\<open>rn_rev_price N der matur n \\<in> borel_measurable N\\<close> by presburger\n        show \"AEeq N (rn_rev_price N der matur n)\n          (expl_cond_expect N (proj_stoch_proc geom_proc (matur - n)) (discounted_value r (\\<lambda>m. der) n))\" using Suc by auto\n      qed\n      show \"real_cond_exp N (stoch_proc_filt N geom_proc borel (matur - Suc n)) (rn_rev_price N der matur n)\n        \\<in> borel_measurable (infinite_coin_toss_space.nat_filtration N (matur - Suc n))\"\n        by (metis assms(2) assms(3) assms(4) borel_measurable_cond_exp infinite_coin_toss_space.intro\n            infinite_coin_toss_space.stoch_proc_subalg_nat_filt linear measurable_from_subalg not_less\n            prob_grw.geom_rand_walk_borel_adapted prob_grw_axioms prob_grw_def)\n      show \"real_cond_exp N (stoch_proc_filt N geom_proc borel (matur - Suc n))\n         (expl_cond_expect N (proj_stoch_proc geom_proc (matur - n)) (discounted_value r (\\<lambda>m. der) n))\n        \\<in> borel_measurable (infinite_coin_toss_space.nat_filtration N (matur - Suc n))\"\n        by (metis assms(2) assms(3) assms(4) borel_measurable_cond_exp infinite_coin_toss_space.intro\n              infinite_coin_toss_space.stoch_proc_subalg_nat_filt linear measurable_from_subalg not_less\n              prob_grw.geom_rand_walk_borel_adapted prob_grw_axioms prob_grw_def)\n      show \"0 < q\" \"q < 1\" using assms by auto\n      show \"infinite_coin_toss_space q N\" using assms\n        by (simp add: infinite_coin_toss_space_def)\n    qed\n    thus ?thesis by simp\n  qed\n  also have \"... = discount_factor r (Suc 0) w *\n  real_cond_exp N (stoch_proc_filt N geom_proc borel (matur - Suc n))\n   (real_cond_exp N (stoch_proc_filt N geom_proc borel (matur - n)) (discounted_value r (\\<lambda>m. der) n)) w\"\n  proof -\n    have \"real_cond_exp N (stoch_proc_filt N geom_proc borel (matur - Suc n))\n      (expl_cond_expect N (proj_stoch_proc geom_proc (matur - n)) (discounted_value r (\\<lambda>m. der) n)) w =\n      real_cond_exp N (stoch_proc_filt N geom_proc borel (matur - Suc n))\n      (real_cond_exp N (stoch_proc_filt N geom_proc borel (matur - n)) (discounted_value r (\\<lambda>m. der) n)) w\"\n    proof (rule infinite_coin_toss_space.nat_filtration_AE_eq)\n      show \"AEeq N (real_cond_exp N (stoch_proc_filt N geom_proc borel (matur - Suc n))\n             (expl_cond_expect N (proj_stoch_proc geom_proc (matur - n)) (discounted_value r (\\<lambda>m. der) n)))\n         (real_cond_exp N (stoch_proc_filt N geom_proc borel (matur - Suc n))\n           (real_cond_exp N (stoch_proc_filt N geom_proc borel (matur - n)) (discounted_value r (\\<lambda>m. der) n)))\"\n      proof (rule sigma_finite_subalgebra.real_cond_exp_cong)\n        show \"sigma_finite_subalgebra N (stoch_proc_filt N geom_proc borel (matur - Suc n))\"\n          using assms(2) assms(3) assms(4) bernoulli_sigma_finite stock_filtration_eq by auto\n        show \"real_cond_exp N (stoch_proc_filt N geom_proc borel (matur - n)) (discounted_value r (\\<lambda>m. der) n) \\<in> borel_measurable N\"\n          by simp\n        show \"expl_cond_expect N (proj_stoch_proc geom_proc (matur - n)) (discounted_value r (\\<lambda>m. der) n) \\<in> borel_measurable N\"\n          by (metis assms(2) assms(3) assms(4) bernoulli bernoulli_expl_cond_expect_adapt bernoulli_stream_def filtration_measurable\n              measurable_cong_sets sets_measure_pmf sets_stream_space_cong)\n        show \"AEeq N (expl_cond_expect N (proj_stoch_proc geom_proc (matur - n)) (discounted_value r (\\<lambda>m. der) n))\n          (real_cond_exp N (stoch_proc_filt N geom_proc borel (matur - n)) (discounted_value r (\\<lambda>m. der) n))\"\n        proof -\n          have \"discounted_value r (\\<lambda>m. der) n \\<in> borel_measurable (G matur)\" using assms discounted_measurable[of der]\n            by simp\n          hence \"\\<forall>w. (expl_cond_expect N (proj_stoch_proc geom_proc (matur - n)) (discounted_value r (\\<lambda>m. der) n)) w =\n            (real_cond_exp N (stoch_proc_filt N geom_proc borel (matur - n)) (discounted_value r (\\<lambda>m. der) n)) w\"\n            using real_exp_eq[of _ matur N q \"matur-n\"] assms by simp\n          thus ?thesis by simp\n        qed\n      qed\n      show \"real_cond_exp N (stoch_proc_filt N geom_proc borel (matur - Suc n))\n         (real_cond_exp N (stoch_proc_filt N geom_proc borel (matur - n)) (discounted_value r (\\<lambda>m. der) n))\n        \\<in> borel_measurable (infinite_coin_toss_space.nat_filtration N (matur - Suc n))\"\n        by (metis assms(2) assms(3) assms(4) borel_measurable_cond_exp infinite_coin_toss_space.intro\n              infinite_coin_toss_space.stoch_proc_subalg_nat_filt linear measurable_from_subalg not_less\n              prob_grw.geom_rand_walk_borel_adapted prob_grw_axioms prob_grw_def)\n      show \"real_cond_exp N (stoch_proc_filt N geom_proc borel (matur - Suc n))\n         (expl_cond_expect N (proj_stoch_proc geom_proc (matur - n)) (discounted_value r (\\<lambda>m. der) n))\n        \\<in> borel_measurable (infinite_coin_toss_space.nat_filtration N (matur - Suc n))\"\n        by (metis assms(2) assms(3) assms(4) borel_measurable_cond_exp infinite_coin_toss_space.intro\n              infinite_coin_toss_space.stoch_proc_subalg_nat_filt linear measurable_from_subalg not_less\n              prob_grw.geom_rand_walk_borel_adapted prob_grw_axioms prob_grw_def)\n      show \"0 < q\" \"q < 1\" using assms by auto\n      show \"infinite_coin_toss_space q N\" using assms\n        by (simp add: infinite_coin_toss_space_def)\n    qed\n    thus ?thesis by simp\n  qed\n  also have \"... = real_cond_exp N (stoch_proc_filt N geom_proc borel (matur - Suc n))\n    (discounted_value r (\\<lambda>m. der) (Suc n)) w\"\n  proof (rule infinite_coin_toss_space.nat_filtration_AE_eq)\n    show \"real_cond_exp N (stoch_proc_filt N geom_proc borel (matur - Suc n)) (discounted_value r (\\<lambda>m. der) (Suc n))\n      \\<in> borel_measurable (infinite_coin_toss_space.nat_filtration N (matur - Suc n))\"\n        by (metis assms(2) assms(3) assms(4) borel_measurable_cond_exp infinite_coin_toss_space.intro\n              infinite_coin_toss_space.stoch_proc_subalg_nat_filt linear measurable_from_subalg not_less\n              prob_grw.geom_rand_walk_borel_adapted prob_grw_axioms prob_grw_def)\n      show \"(\\<lambda>a. discount_factor r (Suc 0) a *\n          real_cond_exp N (stoch_proc_filt N geom_proc borel (matur - Suc n))\n           (real_cond_exp N (stoch_proc_filt N geom_proc borel (matur - n)) (discounted_value r (\\<lambda>m. der) n)) a)\n        \\<in> borel_measurable (infinite_coin_toss_space.nat_filtration N (matur - Suc n))\"\n      proof -\n        have \"real_cond_exp N (stoch_proc_filt N geom_proc borel (matur - Suc n))\n           (real_cond_exp N (stoch_proc_filt N geom_proc borel (matur - n)) (discounted_value r (\\<lambda>m. der) n))\n        \\<in> borel_measurable (infinite_coin_toss_space.nat_filtration N (matur - Suc n))\"\n        by (metis assms(2) assms(3) assms(4) borel_measurable_cond_exp infinite_coin_toss_space.intro\n              infinite_coin_toss_space.stoch_proc_subalg_nat_filt linear measurable_from_subalg not_less\n              prob_grw.geom_rand_walk_borel_adapted prob_grw_axioms prob_grw_def)\n      thus ?thesis using discounted_measurable[of \"real_cond_exp N (stoch_proc_filt N geom_proc borel (matur - Suc n))\n        (real_cond_exp N (stoch_proc_filt N geom_proc borel (matur - n)) (discounted_value r (\\<lambda>m. der) n))\"]\n        unfolding discounted_value_def by simp\n    qed\n    show \"0 < q\" \"q < 1\" using assms by auto\n    show \"infinite_coin_toss_space q N\" using assms\n      by (simp add: infinite_coin_toss_space_def)\n    show \"AEeq N (\\<lambda>w. discount_factor r (Suc 0) w *\n                 real_cond_exp N (stoch_proc_filt N geom_proc borel (matur - Suc n))\n                  (real_cond_exp N (stoch_proc_filt N geom_proc borel (matur - n)) (discounted_value r (\\<lambda>m. der) n)) w)\n     (real_cond_exp N (stoch_proc_filt N geom_proc borel (matur - Suc n)) (discounted_value r (\\<lambda>m. der) (Suc n)))\"\n    proof-\n      have \"AEeq N\n        (\\<lambda>w. discount_factor r (Suc 0) w *\n                 real_cond_exp N (stoch_proc_filt N geom_proc borel (matur - Suc n))\n                  (real_cond_exp N (stoch_proc_filt N geom_proc borel (matur - n)) (discounted_value r (\\<lambda>m. der) n)) w)\n        (\\<lambda>w. discount_factor r (Suc 0) w *\n                 real_cond_exp N (stoch_proc_filt N geom_proc borel (matur - Suc n)) (discounted_value r (\\<lambda>m. der) n) w)\"\n      proof -\n        have \"AEeq N (real_cond_exp N (stoch_proc_filt N geom_proc borel (matur - Suc n))\n                  (real_cond_exp N (stoch_proc_filt N geom_proc borel (matur - n)) (discounted_value r (\\<lambda>m. der) n)))\n                (real_cond_exp N (stoch_proc_filt N geom_proc borel (matur - Suc n)) (discounted_value r (\\<lambda>m. der) n))\"\n        proof (rule sigma_finite_subalgebra.real_cond_exp_nested_subalg)\n          show \"sigma_finite_subalgebra N (stoch_proc_filt N geom_proc borel (matur - Suc n))\"\n            using assms(2) assms(3) assms(4) bernoulli_sigma_finite stock_filtration_eq by auto\n          show \"subalgebra N (stoch_proc_filt N geom_proc borel (matur - n))\"\n            using assms(2) assms(3) assms(4) bernoulli_sigma_finite sigma_finite_subalgebra.subalg\n              stock_filtration_eq by fastforce\n          show \"subalgebra (stoch_proc_filt N geom_proc borel (matur - n)) (stoch_proc_filt N geom_proc borel (matur - Suc n))\"\n          proof -\n            have \"init_triv_filt M (stoch_proc_filt M geom_proc borel)\" using infinite_cts_filtration.stoch_proc_filt_triv_init\n              using info_filtration stock_filtration by auto\n            moreover have \"matur - (Suc n) \\<le> matur - n\" by simp\n            ultimately show ?thesis unfolding init_triv_filt_def filtration_def\n              using assms(2) assms(3) assms(4) stock_filtration stock_filtration_eq by auto\n          qed\n          show \"integrable N (discounted_value r (\\<lambda>m. der) n) \" using bernoulli_discounted_integrable[of N q der matur r n] acceptable_rate assms\n            using geom_rand_walk_borel_adapted measurable_from_subalg stoch_proc_subalg_nat_filt stock_filtration by blast\n        qed\n        thus ?thesis  by auto\n      qed\n      moreover have \"AEeq N\n        (\\<lambda>w. discount_factor r (Suc 0) w *\n         real_cond_exp N (stoch_proc_filt N geom_proc borel (matur - Suc n)) (discounted_value r (\\<lambda>m. der) n) w)\n        (\\<lambda>w. discount_factor r (Suc 0) w * (discounted_value r\n         (\\<lambda>m. real_cond_exp N (stoch_proc_filt N geom_proc borel (matur - Suc n)) der) n) w)\"\n      proof -\n        have \"AEeq N (real_cond_exp N (stoch_proc_filt N geom_proc borel (matur - Suc n)) (discounted_value r (\\<lambda>m. der) n))\n          (discounted_value r\n         (\\<lambda>m. real_cond_exp N (stoch_proc_filt N geom_proc borel (matur - Suc n)) der) n)\"\n        proof (rule prob_space.discounted_value_real_cond_exp)\n          show \"prob_space N\" using assms\n            by (simp add: bernoulli bernoulli_stream_def prob_space.prob_space_stream_space prob_space_measure_pmf)\n          have \"der \\<in> borel_measurable (nat_filtration matur)\" using assms\n            using geom_rand_walk_borel_adapted measurable_from_subalg stoch_proc_subalg_nat_filt stock_filtration by blast\n          show \"integrable N der\"\n          proof (rule infinite_coin_toss_space.nat_filtration_borel_measurable_integrable)\n            show \"infinite_coin_toss_space q N\" using assms\n              by (simp add: infinite_coin_toss_space_def)\n            show \"der \\<in> borel_measurable (infinite_coin_toss_space.nat_filtration N matur)\"\n              by (metis \\<open>der \\<in> borel_measurable (nat_filtration matur)\\<close> \\<open>infinite_coin_toss_space q N\\<close>\n                  assms(2) assms(3) assms(4) infinite_coin_toss_space.nat_filtration_space measurable_from_subalg\n                  nat_filtration_from_eq_sets nat_filtration_space subalgebra_def subset_eq)\n          qed\n          show \"-1 < r\" using acceptable_rate .\n          show \"subalgebra N (stoch_proc_filt N geom_proc borel (matur - Suc n))\"\n            using assms(2) assms(3) assms(4) bernoulli_sigma_finite sigma_finite_subalgebra.subalg\n              stock_filtration_eq by fastforce\n        qed\n        thus ?thesis  by auto\n      qed\n      moreover have \"\\<forall>w. (\\<lambda>w. discount_factor r (Suc 0) w * (discounted_value r\n         (\\<lambda>m. real_cond_exp N (stoch_proc_filt N geom_proc borel (matur - Suc n)) der) n) w) w =\n        (discounted_value r\n         (\\<lambda>m. real_cond_exp N (stoch_proc_filt N geom_proc borel (matur - Suc n)) der) (Suc n)) w\"\n        unfolding discounted_value_def discount_factor_def  by simp\n      moreover have \"AEeq N\n        (real_cond_exp N (stoch_proc_filt N geom_proc borel (matur - Suc n))\n        (discounted_value r (\\<lambda>m. der) (Suc n)))\n        (discounted_value r\n        (\\<lambda>m. real_cond_exp N (stoch_proc_filt N geom_proc borel (matur - Suc n)) der) (Suc n))\"\n      proof (rule prob_space.discounted_value_real_cond_exp)\n        show \"prob_space N\" using assms\n            by (simp add: bernoulli bernoulli_stream_def prob_space.prob_space_stream_space prob_space_measure_pmf)\n        have \"der \\<in> borel_measurable (nat_filtration matur)\" using assms\n          using geom_rand_walk_borel_adapted measurable_from_subalg stoch_proc_subalg_nat_filt stock_filtration by blast\n        show \"integrable N der\"\n        proof (rule infinite_coin_toss_space.nat_filtration_borel_measurable_integrable)\n          show \"infinite_coin_toss_space q N\" using assms\n            by (simp add: infinite_coin_toss_space_def)\n          show \"der \\<in> borel_measurable (infinite_coin_toss_space.nat_filtration N matur)\"\n            by (metis \\<open>der \\<in> borel_measurable (nat_filtration matur)\\<close> \\<open>infinite_coin_toss_space q N\\<close>\n                assms(2) assms(3) assms(4) infinite_coin_toss_space.nat_filtration_space measurable_from_subalg\n                nat_filtration_from_eq_sets nat_filtration_space subalgebra_def subset_eq)\n        qed\n        show \"-1 < r\" using acceptable_rate .\n        show \"subalgebra N (stoch_proc_filt N geom_proc borel (matur - Suc n))\"\n          using assms(2) assms(3) assms(4) bernoulli_sigma_finite sigma_finite_subalgebra.subalg\n            stock_filtration_eq by fastforce\n      qed\n      ultimately show ?thesis by auto\n    qed\n  qed\n  also have \"... = expl_cond_expect N (proj_stoch_proc geom_proc (matur - Suc n))\n    (discounted_value r (\\<lambda>m. der) (Suc n)) w\"\n  proof (rule real_exp_eq)\n    show \"discounted_value r (\\<lambda>m. der) (Suc n) \\<in> borel_measurable (G matur)\" using assms discounted_measurable[of der]\n      by simp\n    show \"N = bernoulli_stream q\" \"0 < q\" \"q < 1\" using assms by auto\n  qed\n  finally show \"rn_rev_price N der matur (Suc n) w =\n    expl_cond_expect N (proj_stoch_proc geom_proc (matur - Suc n)) (discounted_value r (\\<lambda>m. der) (Suc n)) w\" .\nqed\n\ndefinition (in CRR_market) rn_price where\n\"rn_price N der matur n w = expl_cond_expect N (proj_stoch_proc geom_proc n) (discounted_value r (\\<lambda>m. der) (matur - n)) w\"\n\n\ndefinition (in CRR_market) rn_price_ind where\n\"rn_price_ind N der matur n w = rn_rev_price N der matur (matur - n) w\"\n\nlemma (in CRR_market) rn_price_eq:\n  assumes \"N = bernoulli_stream q\"\nand \"0 < q\"\nand \"q < 1\"\nand \"der \\<in> borel_measurable (G matur)\"\nand \"n \\<le> matur\"\nshows \"rn_price N der matur n w = rn_price_ind N der matur n w\" using rn_rev_expl_cond_expect\n  unfolding rn_price_def rn_price_ind_def\n  by (simp add: assms)\n\n\nlemma (in CRR_market) geom_proc_filt_info:\n  fixes f::\"bool stream \\<Rightarrow> 'b::{t0_space}\"\n  assumes \"f \\<in> borel_measurable (G n)\"\n  shows \"f w = f (pseudo_proj_True n w)\"\nproof -\n  have \"subalgebra (nat_filtration n) (G n)\" using stoch_proc_subalg_nat_filt[of geom_proc n] geometric_process\n    stock_filtration geom_rand_walk_borel_adapted by simp\n  hence \"f\\<in> borel_measurable (nat_filtration n)\" using assms by (simp add: measurable_from_subalg)\n  thus ?thesis using nat_filtration_info[of f n] by (metis comp_apply)\nqed\n\n\n\n\n\n\nlemma (in CRR_market) rn_price_borel_adapt:\nassumes \"cash_flow \\<in> borel_measurable (G matur)\"\nand \"N = bernoulli_stream q\"\nand \"0 < q\"\nand \"q < 1\"\nand \"n \\<le> matur\"\nshows \"(rn_price N cash_flow matur n) \\<in> borel_measurable (G n)\"\nproof -\n  show \"(rn_price N cash_flow matur n) \\<in> borel_measurable (G n)\"\n    using assms rn_rev_price_rev_borel_adapt[of cash_flow matur N q \"matur - n\"] rn_price_eq rn_price_ind_def\n    by (smt add.right_neutral cancel_comm_monoid_add_class.diff_cancel diff_commute diff_le_self\n        increasing_measurable_info measurable_cong nat_le_linear ordered_cancel_comm_monoid_diff_class.add_diff_inverse)\nqed\n\n\ndefinition (in CRR_market) delta_price where\n  \"delta_price N cash_flow T =\n    (\\<lambda> n w. if (Suc n \\<le> T)\n      then (rn_price N cash_flow T (Suc n) (pseudo_proj_True n w) - rn_price N cash_flow T (Suc n) (pseudo_proj_False n w))/\n        (geom_proc (Suc n) (spick w n True) - geom_proc (Suc n) (spick w n False))\n      else 0)\"\n\n\nlemma (in CRR_market) delta_price_eq:\n  assumes \"Suc n \\<le> T\"\n  shows \"delta_price N cash_flow T n w = (rn_price N cash_flow T (Suc n) (spick w n True) - rn_price N cash_flow T (Suc n) (spick w n False))/\n    ((geom_proc n w) * (u - d))\"\nproof -\n  have \"(geom_proc (Suc n) (spick w n True) - geom_proc (Suc n) (spick w n False)) = geom_proc n w * (u - d)\"\n    by (simp add: geom_rand_walk_diff_induct)\n  then show ?thesis unfolding delta_price_def using assms spick_eq_pseudo_proj_True spick_eq_pseudo_proj_False by simp\nqed\n\n\n\nlemma (in CRR_market) geom_proc_spick:\n  shows \"geom_proc (Suc n) (spick w n x)  = (if x then u else d) * geom_proc n w\"\nproof -\n  have \"geom_proc (Suc n) (spick w n x)  = geom_rand_walk u d init (Suc n) (spick w n x)\" using geometric_process by simp\n  also have \"... = (case (spick w n x) !! n of True \\<Rightarrow> u | False \\<Rightarrow> d) * geom_rand_walk u d init n (spick w n x)\"\n    by simp\n  also have \"... = (case x of True \\<Rightarrow> u | False \\<Rightarrow> d) * geom_rand_walk u d init n (spick w n x)\"\n    unfolding spick_def by simp\n  also have \"... = (if x then u else d) * geom_rand_walk u d init n (spick w n x)\" by simp\n  also have \"... = (if x then u else d) * geom_rand_walk u d init n w\"\n    by (metis comp_def geom_rand_walk_pseudo_proj_True geometric_process pseudo_proj_True_stake_image spickI)\n  finally show ?thesis using geometric_process by simp\nqed\n\n\nlemma (in CRR_market) spick_red_geom:\n  shows \"(\\<lambda>w. spick w n x) \\<in> measurable (fct_gen_subalgebra M borel (geom_proc n)) (fct_gen_subalgebra M borel (geom_proc (Suc n)))\"\n  unfolding measurable_def\nproof (intro CollectI conjI)\n  show \"(\\<lambda>w. spick w n x)\n    \\<in> space (fct_gen_subalgebra M borel (geom_proc n)) \\<rightarrow> space (fct_gen_subalgebra M borel (geom_proc (Suc n)))\"\n    by (simp add: bernoulli bernoulli_stream_space fct_gen_subalgebra_space)\n  show \"\\<forall>y\\<in>sets (fct_gen_subalgebra M borel (geom_proc (Suc n))).\n       (\\<lambda>w. spick w n x) -` y \\<inter> space (fct_gen_subalgebra M borel (geom_proc n))\n       \\<in> sets (fct_gen_subalgebra M borel (geom_proc n))\"\n  proof\n    fix A\n    assume A: \"A \\<in> sets (fct_gen_subalgebra M borel (geom_proc (Suc n)))\"\n    show \"(\\<lambda>w. spick w n x) -` A \\<inter> space (fct_gen_subalgebra M borel (geom_proc n)) \\<in>\n    sets (fct_gen_subalgebra M borel (geom_proc n))\"\n    proof -\n      define sp where \"sp = (\\<lambda>w. spick w n x)\"\n      have \"A \\<in> {(geom_proc (Suc n)) -` B \\<inter> space M |B. B \\<in> sets borel}\" using A\n        by (simp add:fct_gen_subalgebra_sigma_sets)\n      from this obtain C where \"C\\<in> sets borel\" and \"A = (geom_proc (Suc n)) -`C \\<inter> space M\" by auto\n      hence \"A = (geom_proc (Suc n)) -`C\" using bernoulli bernoulli_stream_space by simp\n      hence \"sp -`A = sp -` (geom_proc (Suc n)) -`C\" by simp\n      also have \"... = (geom_proc (Suc n) \\<circ> sp) -` C\" by auto\n      also have \"... = (\\<lambda>w. (if x then u else d) * geom_proc n w) -` C\" using geom_proc_spick\n        sp_def by auto\n      also have \"... \\<in> sets (fct_gen_subalgebra M borel (geom_proc n))\"\n      proof (cases x)\n        case True\n        hence \"(\\<lambda>w. (if x then u else d) * geom_proc n w) -` C = (\\<lambda>w. u * geom_proc n w) -` C\" by simp\n        moreover have \"(\\<lambda>w. u * geom_proc n w) \\<in> borel_measurable (fct_gen_subalgebra M borel (geom_proc n))\"\n        proof -\n          have \"geom_proc n \\<in>borel_measurable (fct_gen_subalgebra M borel (geom_proc n))\"\n            using fct_gen_subalgebra_fct_measurable\n            by (metis (no_types, lifting) geom_rand_walk_borel_measurable measurable_def mem_Collect_eq)\n          thus ?thesis by simp\n        qed\n        ultimately show ?thesis using \\<open>C\\<in> sets borel\\<close>\n          by (metis bernoulli bernoulli_stream_preimage fct_gen_subalgebra_space measurable_sets)\n      next\n        case False\n        hence \"(\\<lambda>w. (if x then u else d) * geom_proc n w) -` C = (\\<lambda>w. d * geom_proc n w) -` C\" by simp\n        moreover have \"(\\<lambda>w. d * geom_proc n w) \\<in> borel_measurable (fct_gen_subalgebra M borel (geom_proc n))\"\n        proof -\n          have \"geom_proc n \\<in>borel_measurable (fct_gen_subalgebra M borel (geom_proc n))\"\n            using fct_gen_subalgebra_fct_measurable\n            by (metis (no_types, lifting) geom_rand_walk_borel_measurable measurable_def mem_Collect_eq)\n          thus ?thesis by simp\n        qed\n        ultimately show ?thesis using \\<open>C\\<in> sets borel\\<close>\n          by (metis bernoulli bernoulli_stream_preimage fct_gen_subalgebra_space measurable_sets)\n      qed\n      finally show ?thesis unfolding sp_def by (simp add: bernoulli bernoulli_stream_space fct_gen_subalgebra_space)\n    qed\n  qed\nqed\n\nlemma (in CRR_market) geom_spick_Suc:\n  assumes \"A \\<in> {(geom_proc (Suc n)) -` B |B. B \\<in> sets borel}\"\n  shows \"(\\<lambda>w. spick w n x) -`A \\<in> {geom_proc n -`B | B. B\\<in> sets borel}\"\nproof -\n  have \"sets (fct_gen_subalgebra M borel (geom_proc n)) = {geom_proc n -` B \\<inter>space M |B. B \\<in> sets borel}\"\n    by (simp add: fct_gen_subalgebra_sigma_sets)\n  also have \"... =  {geom_proc n -` B |B. B \\<in> sets borel}\" using bernoulli bernoulli_stream_space by simp\n  finally have sf: \"sets (fct_gen_subalgebra M borel (geom_proc n)) = {geom_proc n -` B |B. B \\<in> sets borel}\" .\n  define sp where \"sp = (\\<lambda>w. spick w n x)\"\n  from assms(1) obtain C where \"C\\<in> sets borel\" and \"A = (geom_proc (Suc n)) -`C\" by auto\n  hence \"A = (geom_proc (Suc n)) -`C\" using bernoulli bernoulli_stream_space by simp\n  hence \"sp -`A = sp -` (geom_proc (Suc n)) -`C\" by simp\n  also have \"... = (geom_proc (Suc n) \\<circ> sp) -` C\" by auto\n  also have \"... = (\\<lambda>w. (if x then u else d) * geom_proc n w) -` C\" using geom_proc_spick\n    sp_def by auto\n  also have \"... \\<in> {geom_proc n -`B | B. B\\<in> sets borel}\"\n  proof (cases x)\n    case True\n    hence \"(\\<lambda>w. (if x then u else d) * geom_proc n w) -` C = (\\<lambda>w. u * geom_proc n w) -` C\" by simp\n    moreover have \"(\\<lambda>w. u * geom_proc n w) \\<in> borel_measurable (fct_gen_subalgebra M borel (geom_proc n))\"\n    proof -\n      have \"geom_proc n \\<in>borel_measurable (fct_gen_subalgebra M borel (geom_proc n))\"\n        using fct_gen_subalgebra_fct_measurable\n        by (metis (no_types, lifting) geom_rand_walk_borel_measurable measurable_def mem_Collect_eq)\n      thus ?thesis by simp\n    qed\n    ultimately show ?thesis using \\<open>C\\<in> sets borel\\<close> sf\n      by (simp add: bernoulli bernoulli_stream_preimage fct_gen_subalgebra_space in_borel_measurable_borel)\n  next\n    case False\n    hence \"(\\<lambda>w. (if x then u else d) * geom_proc n w) -` C = (\\<lambda>w. d * geom_proc n w) -` C\" by simp\n    moreover have \"(\\<lambda>w. d * geom_proc n w) \\<in> borel_measurable (fct_gen_subalgebra M borel (geom_proc n))\"\n    proof -\n      have \"geom_proc n \\<in>borel_measurable (fct_gen_subalgebra M borel (geom_proc n))\"\n        using fct_gen_subalgebra_fct_measurable\n        by (metis (no_types, lifting) geom_rand_walk_borel_measurable measurable_def mem_Collect_eq)\n      thus ?thesis by simp\n    qed\n    ultimately show ?thesis using \\<open>C\\<in> sets borel\\<close> sf\n      by (simp add: bernoulli bernoulli_stream_preimage fct_gen_subalgebra_space in_borel_measurable_borel)\n  qed\n  finally show ?thesis unfolding sp_def .\nqed\n\n\nlemma (in CRR_market) geom_spick_lt:\n  assumes \"m< n\"\n  shows \"geom_proc m (spick w n x) = geom_proc m w\"\nproof -\n  have \"geom_proc m (spick w n x) = geom_proc m (pseudo_proj_True m (spick w n x))\"\n    using  geom_rand_walk_pseudo_proj_True by (metis comp_apply)\n  also have \"... = geom_proc m (pseudo_proj_True m w)\" using assms\n    by (metis less_imp_le_nat pseudo_proj_True_def pseudo_proj_True_prefix spickI)\n  also have \"... = geom_proc m w\" using  geom_rand_walk_pseudo_proj_True by (metis comp_apply)\n  finally show ?thesis .\nqed\n\nlemma (in CRR_market) geom_spick_eq:\n  shows \"geom_proc m (spick w m x) = geom_proc m w\"\nproof (cases x)\n  case True\n  have \"geom_proc m (spick w m x) = geom_proc m (pseudo_proj_True m (spick w m x))\"\n    using  geom_rand_walk_pseudo_proj_True by (metis comp_apply)\n  also have \"... = geom_proc m (pseudo_proj_True m w)\" using True\n    by (metis pseudo_proj_True_def spickI)\n  also have \"... = geom_proc m w\" using  geom_rand_walk_pseudo_proj_True by (metis comp_apply)\n  finally show ?thesis .\nnext\n  case False\n  have \"geom_proc m (spick w m x) = geom_proc m (pseudo_proj_False m (spick w m x))\"\n    using  geom_rand_walk_pseudo_proj_False by (metis comp_apply)\n  also have \"... = geom_proc m (pseudo_proj_False m w)\" using False\n    by (metis pseudo_proj_False_def spickI)\n  also have \"... = geom_proc m w\" using  geom_rand_walk_pseudo_proj_False by (metis comp_apply)\n  finally show ?thesis .\nqed\n\n\nlemma (in CRR_market) spick_red_geom_filt:\n  shows \"(\\<lambda>w. spick w n x) \\<in> measurable (G n) (G (Suc n))\" unfolding measurable_def\nproof (intro CollectI conjI)\n  show \"(\\<lambda>w. spick w n x) \\<in> space (G n) \\<rightarrow> space (G (Suc n))\" using stock_filtration\n    by (simp add: bernoulli bernoulli_stream_space stoch_proc_filt_space)\n  show \"\\<forall>y\\<in>sets (G (Suc n)). (\\<lambda>w. spick w n x) -` y \\<inter> space (G n) \\<in> sets (G n)\"\n  proof\n    fix B\n    assume \"B\\<in> sets (G (Suc n))\"\n    hence \"B\\<in> (sigma_sets (space M) (\\<Union> i\\<in> {m. m\\<le> (Suc n)}. {(geom_proc i -`A) \\<inter> (space M) | A. A\\<in> sets borel }))\"\n      using stock_filtration stoch_proc_filt_sets geometric_process\n    proof -\n      have \"\\<forall>n. sigma_sets (space M) (\\<Union>n\\<in>{na. na \\<le> n}. {geom_proc n -` R \\<inter> space M |R. R \\<in> sets borel}) = sets (G n)\"\n        by (simp add: geom_rand_walk_borel_measurable stoch_proc_filt_sets stock_filtration)\n      then show ?thesis\n        using \\<open>B \\<in> sets (G (Suc n))\\<close> by blast\n    qed\n    hence \"(\\<lambda>w. spick w n x) -` B \\<in> sets (G n)\"\n    proof (induct rule:sigma_sets.induct)\n      {\n        fix C\n        assume \"C \\<in> (\\<Union>i\\<in>{m. m \\<le> Suc n}. {geom_proc i -` A \\<inter> space M |A. A \\<in> sets borel})\"\n        hence \"\\<exists>m \\<le> Suc n. C\\<in> {geom_proc m -` A \\<inter> space M |A. A \\<in> sets borel}\" by auto\n        from this obtain m where \"m\\<le> Suc n\" and \"C\\<in> {geom_proc m -` A \\<inter> space M |A. A \\<in> sets borel}\" by auto\n        note Cprops = this\n        from this obtain D where \"C = geom_proc m -` D\\<inter> space M\" and \"D\\<in> sets borel\" by auto\n        hence \"C = geom_proc m -`D\" using bernoulli bernoulli_stream_space by simp\n        have \"C\\<in> {geom_proc m -` A |A. A \\<in> sets borel}\" using bernoulli bernoulli_stream_space Cprops by simp\n        show \"(\\<lambda>w. spick w n x) -` C \\<in> sets (G n)\"\n        proof (cases \"m \\<le> n\")\n          case True\n          have \"(\\<lambda>w. spick w n x) -` C = (\\<lambda>w. spick w n x) -` geom_proc m -`D\" using \\<open>C = geom_proc m -`D\\<close> by simp\n          also have \"... = (geom_proc m \\<circ> (\\<lambda>w. spick w n x)) -`D\" by auto\n          also have \"... = geom_proc m -`D\" using geom_spick_lt geom_spick_eq \\<open>m\\<le>n\\<close>\n            using le_eq_less_or_eq by auto\n          also have \"... \\<in> sets (G n)\" using stock_filtration geometric_process\n            \\<open>D\\<in> sets borel\\<close>\n            by (metis (no_types, lifting) True adapt_stoch_proc_def bernoulli bernoulli_stream_preimage\n                geom_rand_walk_borel_measurable increasing_measurable_info measurable_sets stoch_proc_filt_adapt\n                stoch_proc_filt_space)\n          finally show \"(\\<lambda>w. spick w n x) -` C \\<in> sets (G n)\" .\n        next\n          case False\n          hence \"m = Suc n\" using \\<open>m \\<le> Suc n\\<close> by simp\n          hence \"(\\<lambda>w. spick w n x) -` C \\<in> {geom_proc n -` B |B. B \\<in> sets borel}\"\n            using \\<open>C\\<in> {geom_proc m -` A |A. A \\<in> sets borel}\\<close> geom_spick_Suc by simp\n          also have \"... \\<subseteq> sets (G n)\"\n          proof -\n            have \"{geom_proc n -` B |B. B \\<in> sets borel} \\<subseteq> {geom_proc n -` B \\<inter> space M |B. B \\<in> sets borel}\"\n              using bernoulli bernoulli_stream_space by simp\n            also have \"... \\<subseteq> (\\<Union>i\\<in>{m. m \\<le> n}. {geom_proc i -` A \\<inter> space M |A. A \\<in> sets borel})\"\n               by auto\n            also have \"... \\<subseteq>  sigma_sets (space M) (\\<Union>i\\<in>{m. m \\<le> n}. {geom_proc i -` A \\<inter> space M |A. A \\<in> sets borel})\"\n              by (rule sigma_sets_superset_generator)\n            also have \"... = sets (G n)\" using stock_filtration geometric_process\n              stoch_proc_filt_sets[of n geom_proc M borel] geom_rand_walk_borel_measurable by blast\n            finally show ?thesis .\n          qed\n          finally show ?thesis .\n        qed\n      }\n      show \"(\\<lambda>w. spick w n x) -` {} \\<in> sets (G n)\" by simp\n      {\n        fix C\n        assume \"C \\<in> sigma_sets (space M) (\\<Union>i\\<in>{m. m \\<le> Suc n}. {geom_proc i -` A \\<inter> space M |A. A \\<in> sets borel})\"\n          and \"(\\<lambda>w. spick w n x) -` C \\<in> sets (G n)\"\n        hence \"(\\<lambda>w. spick w n x) -` (space M - C) = (\\<lambda>w. spick w n x) -` (space M) - (\\<lambda>w. spick w n x) -` C\"\n          by (simp add: vimage_Diff)\n        also have \"... = space M - (\\<lambda>w. spick w n x) -` C\" using bernoulli bernoulli_stream_space by simp\n        also have \"... \\<in> sets (G n)\" using \\<open>(\\<lambda>w. spick w n x) -` C \\<in> sets (G n)\\<close>\n          by (metis algebra.compl_sets disc_filtr_def discrete_filtration sets.sigma_algebra_axioms\n              sigma_algebra_def subalgebra_def)\n        finally show \"(\\<lambda>w. spick w n x) -` (space M - C) \\<in> sets (G n)\" .\n      }\n      {\n        fix C::\"nat \\<Rightarrow> bool stream set\"\n        assume \"(\\<And>i. C i \\<in> sigma_sets (space M) (\\<Union>i\\<in>{m. m \\<le> Suc n}. {geom_proc i -` A \\<inter> space M |A. A \\<in> sets borel}))\"\n          and \"(\\<And>i. (\\<lambda>w. spick w n x) -` C i \\<in> sets (G n))\"\n        hence \"(\\<lambda>w. spick w n x) -` \\<Union>(C ` UNIV) = (\\<Union> i\\<in> UNIV. (\\<lambda>w. spick w n x) -` (C i))\" by blast\n        also have \"... \\<in> sets (G n)\" using \\<open>\\<And>i. (\\<lambda>w. spick w n x) -` C i \\<in> sets (G n)\\<close> by simp\n        finally show \"(\\<lambda>w. spick w n x) -` \\<Union>(C ` UNIV) \\<in> sets (G n)\" .\n      }\n    qed\n    thus \"(\\<lambda>w. spick w n x) -` B \\<inter> space (G n) \\<in> sets (G n)\" using stock_filtration stoch_proc_filt_space\n      bernoulli bernoulli_stream_space by simp\n  qed\nqed\n\nlemma (in CRR_market) delta_price_adapted:\n   fixes cash_flow::\"bool stream \\<Rightarrow> real\"\n   assumes \"cash_flow \\<in> borel_measurable (G T)\"\nand \"N = bernoulli_stream q\"\nand \"0 < q\"\nand \"q < 1\"\n  shows \"borel_adapt_stoch_proc G (delta_price N cash_flow T)\"\nunfolding adapt_stoch_proc_def\nproof\n  fix n\n  show \"delta_price N cash_flow T n \\<in> borel_measurable (G n)\"\n  proof (cases \"Suc n \\<le> T\")\n    case True\n    hence deleq: \"\\<forall>w. delta_price N cash_flow T n w = (rn_price N cash_flow T (Suc n) (spick w n True) - rn_price N cash_flow T (Suc n) (spick w n False))/\n    ((geom_proc n w) * (u - d))\" using delta_price_eq by simp\n    have \"(\\<lambda>w. rn_price N cash_flow T (Suc n) (spick w n True)) \\<in> borel_measurable (G n)\"\n    proof -\n      have \"rn_price N cash_flow T (Suc n) \\<in> borel_measurable  (G (Suc n))\" using rn_price_borel_adapt assms\n        using True by blast\n      moreover have \"(\\<lambda>w. spick w n True) \\<in> G n \\<rightarrow>\\<^sub>M G (Suc n)\" using spick_red_geom_filt by simp\n      ultimately show ?thesis by simp\n    qed\n    moreover have \"(\\<lambda>w. rn_price N cash_flow T (Suc n) (spick w n False)) \\<in> borel_measurable (G n)\"\n    proof -\n      have \"rn_price N cash_flow T (Suc n) \\<in> borel_measurable  (G (Suc n))\" using rn_price_borel_adapt assms\n        using True by blast\n      moreover have \"(\\<lambda>w. spick w n False) \\<in> G n \\<rightarrow>\\<^sub>M G (Suc n)\" using spick_red_geom_filt by simp\n      ultimately show ?thesis by simp\n    qed\n    ultimately have \"(\\<lambda>w. rn_price N cash_flow T (Suc n) (spick w n True) - rn_price N cash_flow T (Suc n) (spick w n False))\n      \\<in> borel_measurable (G n)\" by simp\n    moreover have \"(\\<lambda>w. (geom_proc n w) * (u - d)) \\<in> borel_measurable (G n)\"\n    proof -\n      have \"geom_proc n \\<in> borel_measurable (G n)\" using stock_filtration\n        by (metis adapt_stoch_proc_def stk_price stock_price_borel_measurable)\n      thus ?thesis by simp\n    qed\n    ultimately have \"(\\<lambda>w. (rn_price N cash_flow T (Suc n) (spick w n True) - rn_price N cash_flow T (Suc n) (spick w n False))/\n      ((geom_proc n w) * (u - d)))\\<in> borel_measurable (G n)\" by simp\n    thus ?thesis using deleq by presburger\n  next\n    case False\n    thus ?thesis unfolding delta_price_def by simp\n  qed\nqed\n\nfun (in CRR_market) delta_predict where\n  \"delta_predict N der matur 0  = (\\<lambda>w. delta_price N der matur 0 w)\" |\n  \"delta_predict N der matur (Suc n) = (\\<lambda>w. delta_price N der matur n w)\"\n\nlemma (in CRR_market) delta_predict_predict:\n  assumes \"der \\<in> borel_measurable (G matur)\"\nand \"N = bernoulli_stream q\"\nand \"0 < q\"\nand \"q < 1\"\n  shows \"borel_predict_stoch_proc G (delta_predict N der matur)\" unfolding predict_stoch_proc_def\nproof (intro conjI)\n  show \"delta_predict N der matur 0 \\<in> borel_measurable (G 0)\" using delta_price_adapted[of der matur N q]\n    assms unfolding adapt_stoch_proc_def by force\n  show \"\\<forall>n. delta_predict N der matur (Suc n) \\<in> borel_measurable (G n)\"\n  proof\n    fix n\n    show \"delta_predict N der matur (Suc n) \\<in> borel_measurable (G n)\" using delta_price_adapted[of der matur N q]\n    assms unfolding adapt_stoch_proc_def by force\n  qed\nqed\n\n\ndefinition (in CRR_market) delta_pf where\n\"delta_pf N der matur = qty_single stk (delta_predict N der matur)\"\n\nlemma (in CRR_market) delta_pf_support:\n  shows \"support_set (delta_pf N der matur) \\<subseteq> {stk}\" unfolding delta_pf_def\n  using single_comp_support[of stk \"delta_predict N der matur\"] by simp\n\ndefinition (in CRR_market) self_fin_delta_pf where\n\"self_fin_delta_pf N der matur v0 = self_finance Mkt v0 (delta_pf N der matur) risk_free_asset\"\n\nlemma (in disc_equity_market) self_finance_trading_strat:\n  assumes \"trading_strategy pf\"\nand \"portfolio pf\"\nand \"borel_adapt_stoch_proc F (prices Mkt asset)\"\nand \"support_adapt Mkt pf\"\nshows \"trading_strategy (self_finance Mkt v pf asset)\" unfolding self_finance_def\nproof (rule sum_trading_strat)\n  show \"trading_strategy pf\" using assms by simp\n  show \"trading_strategy (qty_single asset (remaining_qty Mkt v pf asset))\" unfolding trading_strategy_def\n  proof (intro conjI ballI)\n  show \"portfolio (qty_single asset (remaining_qty Mkt v pf asset))\"\n    by (simp add: self_finance_def single_comp_portfolio)\n  show \"\\<And>a.\n       a \\<in> support_set (qty_single asset (remaining_qty Mkt v pf asset)) \\<Longrightarrow>\n       borel_predict_stoch_proc F (qty_single asset (remaining_qty Mkt v pf asset) a)\"\n  proof (cases \"support_set (qty_single asset (remaining_qty Mkt v pf asset)) = {}\")\n    case False\n    hence eqasset: \"support_set (qty_single asset (remaining_qty Mkt v pf asset)) = {asset}\"\n      using single_comp_support by fastforce\n    fix a\n    assume \"a\\<in> support_set (qty_single asset (remaining_qty Mkt v pf asset))\"\n    hence \"a = asset\" using eqasset by simp\n    hence \"qty_single asset (remaining_qty Mkt v pf asset) a = (remaining_qty Mkt v pf asset)\"\n      unfolding qty_single_def by simp\n    moreover have \"borel_predict_stoch_proc F (remaining_qty Mkt v pf asset)\"\n    proof (rule remaining_qty_predict)\n      show \"trading_strategy pf\" using assms by simp\n      show \"borel_adapt_stoch_proc F (prices Mkt asset)\" using assms by simp\n      show \"support_adapt Mkt pf\" using assms by simp\n    qed\n    ultimately show \"borel_predict_stoch_proc F (qty_single asset (remaining_qty Mkt v pf asset) a)\"\n      by simp\n  next\n    case True\n    thus \"\\<And>a. a \\<in> support_set (qty_single asset (remaining_qty Mkt v pf asset)) \\<Longrightarrow>\n         support_set (qty_single asset (remaining_qty Mkt v pf asset)) = {} \\<Longrightarrow>\n         borel_predict_stoch_proc F (qty_single asset (remaining_qty Mkt v pf asset) a)\" by simp\n  qed\nqed\nqed\n\nlemma (in CRR_market) self_fin_delta_pf_trad_strat:\n  assumes \"der\\<in> borel_measurable (G matur)\"\nand \"N = bernoulli_stream q\"\nand \"0 < q\"\nand \"q < 1\"\n  shows \"trading_strategy (self_fin_delta_pf N der matur v0)\" unfolding self_fin_delta_pf_def\nproof (rule self_finance_trading_strat)\n  show \"trading_strategy (delta_pf N der matur)\" unfolding trading_strategy_def\n  proof (intro conjI ballI)\n    show \"portfolio (delta_pf N der matur)\" unfolding portfolio_def using delta_pf_support\n      by (meson finite.emptyI finite_insert infinite_super)\n    show \"\\<And>asset. asset \\<in> support_set (delta_pf N der matur) \\<Longrightarrow> borel_predict_stoch_proc G (delta_pf N der matur asset)\"\n    proof (cases \"support_set (delta_pf N der matur) = {}\")\n      case False\n      fix asset\n      assume \"asset \\<in> support_set (delta_pf N der matur)\"\n      hence \"asset = stk\" using False delta_pf_support by auto\n      hence \"delta_pf N der matur asset = delta_predict N der matur\" unfolding delta_pf_def qty_single_def by simp\n      thus \"borel_predict_stoch_proc G (delta_pf N der matur asset)\" using delta_predict_predict\n        assms by simp\n    next\n      case True\n      thus \"\\<And>asset. asset \\<in> support_set (delta_pf N der matur) \\<Longrightarrow>\n             support_set (delta_pf N der matur) = {} \\<Longrightarrow> borel_predict_stoch_proc G (delta_pf N der matur asset)\" by simp\n    qed\n  qed\n  show \"portfolio (delta_pf N der matur)\" using delta_pf_support unfolding portfolio_def\n    by (meson finite.emptyI finite_insert infinite_super)\n  show \"borel_adapt_stoch_proc G (prices Mkt risk_free_asset)\" using rf_price\n    disc_rfr_proc_borel_adapted by simp\n  show \"support_adapt Mkt (delta_pf N der matur)\" unfolding support_adapt_def\n  proof\n    show \"\\<And>asset. asset \\<in> support_set (delta_pf N der matur) \\<Longrightarrow> borel_adapt_stoch_proc G (prices Mkt asset)\"\n    proof (cases \"support_set (delta_pf N der matur) = {}\")\n      case False\n      fix asset\n      assume \"asset \\<in> support_set (delta_pf N der matur)\"\n      hence \"asset = stk\" using False delta_pf_support by auto\n      hence \"prices Mkt asset = geom_proc\" using stk_price by simp\n      thus \"borel_adapt_stoch_proc G (prices Mkt asset)\"\n        using \\<open>asset = stk\\<close> stock_price_borel_measurable by auto\n    next\n      case True\n      thus \"\\<And>asset. asset \\<in> support_set (delta_pf N der matur) \\<Longrightarrow> borel_adapt_stoch_proc G (prices Mkt asset)\"\n        by simp\n    qed\n  qed\nqed\n\ndefinition (in CRR_market) delta_hedging where\n\"delta_hedging N der matur = self_fin_delta_pf N der matur\n  (prob_space.expectation N (discounted_value r (\\<lambda>m. der) matur))\"\n\n\nlemma (in CRR_market)  geom_proc_eq_snth:\n  shows \"(\\<And>m. m \\<le> Suc n \\<Longrightarrow> geom_proc m x = geom_proc m y) \\<Longrightarrow>\n    (\\<And>m. m \\<le> n \\<Longrightarrow> snth x m = snth y m)\"\nproof (induct n )\n  case 0\n  assume asm: \"(\\<And>m. m \\<le>Suc  0 \\<Longrightarrow> geom_proc m x = geom_proc m y)\" and \"m\\<le> 0\"\n  hence \"m = 0\" by simp\n  have \"geom_proc (Suc 0) x = geom_proc (Suc 0) y\" using asm by simp\n  have \"snth x 0 = snth y 0\"\n  proof (rule ccontr)\n    assume \"snth x 0 \\<noteq> snth y 0\"\n    show False\n    proof (cases \"snth x 0\")\n      case True\n      hence \"\\<not> snth y 0\" using \\<open>snth x 0 \\<noteq> snth y 0\\<close> by simp\n      have \"geom_proc (Suc 0) x = u * init\" using geometric_process True by simp\n      moreover have \"geom_proc (Suc 0) y = d * init\" using geometric_process \\<open>\\<not> snth y 0\\<close> by simp\n      ultimately have \"geom_proc (Suc 0) x \\<noteq> geom_proc (Suc 0) y\" using S0_positive down_lt_up by simp\n      thus ?thesis using \\<open>geom_proc (Suc 0) x = geom_proc (Suc 0) y\\<close> by simp\n    next\n      case False\n      hence \"snth y 0\" using \\<open>snth x 0 \\<noteq> snth y 0\\<close> by simp\n      have \"geom_proc (Suc 0) x = d * init\" using geometric_process False by simp\n      moreover have \"geom_proc (Suc 0) y = u * init\" using geometric_process \\<open>snth y 0\\<close> by simp\n      ultimately have \"geom_proc (Suc 0) x \\<noteq> geom_proc (Suc 0) y\" using S0_positive down_lt_up by simp\n      thus ?thesis using \\<open>geom_proc (Suc 0) x = geom_proc (Suc 0) y\\<close> by simp\n    qed\n  qed\n  thus \"\\<And>m. (\\<And>m. m \\<le> Suc 0 \\<Longrightarrow> geom_proc m x = geom_proc m y) \\<Longrightarrow> m \\<le> 0 \\<Longrightarrow> x !! m = y !! m\" by simp\nnext\n  case (Suc n)\n  assume fst: \"(\\<And>m. (\\<And>m. m \\<le> Suc n \\<Longrightarrow> geom_proc m x = geom_proc m y) \\<Longrightarrow> m \\<le> n \\<Longrightarrow> x !! m = y !! m)\"\n    and scd: \"(\\<And>m. m \\<le> Suc (Suc n) \\<Longrightarrow> geom_proc m x = geom_proc m y)\" and \"m \\<le> Suc n\"\n  show \"x !! m = y !! m\"\n  proof (cases \"m \\<le> n\")\n    case True\n    thus ?thesis using fst scd by simp\n  next\n    case False\n    hence \"m = Suc n\" using \\<open>m\\<le> Suc n\\<close> by simp\n    have \"geom_proc (Suc (Suc n)) x = geom_proc (Suc (Suc n)) y\" using scd by simp\n    show ?thesis\n    proof (rule ccontr)\n      assume \"x !! m \\<noteq> y !! m\"\n      thus False\n      proof (cases \"x !! m\")\n        case True\n        hence \"\\<not> y !! m\" using \\<open>x !! m \\<noteq> y !! m\\<close> by simp\n        have \"geom_proc (Suc (Suc n)) x = u * geom_proc (Suc n) x\" using geometric_process True\n          \\<open>m = Suc n\\<close> by simp\n        also have \"... = u * geom_proc (Suc n) y\" using scd \\<open>m = Suc n\\<close> by simp\n        finally have \"geom_proc (Suc (Suc n)) x = u * geom_proc (Suc n) y\" .\n        moreover have \"geom_proc (Suc (Suc n)) y = d * geom_proc (Suc n) y\" using geometric_process\n          \\<open>m = Suc n\\<close> \\<open>\\<not> y !! m\\<close> by simp\n        ultimately have \"geom_proc (Suc (Suc n)) x \\<noteq> geom_proc (Suc (Suc n)) y\"\n          by (metis S0_positive down_lt_up down_positive geom_rand_walk_strictly_positive less_irrefl mult_cancel_right)\n        thus ?thesis using \\<open>geom_proc (Suc (Suc n)) x = geom_proc (Suc (Suc n)) y\\<close> by simp\n      next\n        case False\n        hence \"y !! m\" using \\<open>x !! m \\<noteq> y !! m\\<close> by simp\n        have \"geom_proc (Suc (Suc n)) x = d * geom_proc (Suc n) x\" using geometric_process False\n          \\<open>m = Suc n\\<close> by simp\n        also have \"... = d * geom_proc (Suc n) y\" using scd \\<open>m = Suc n\\<close> by simp\n        finally have \"geom_proc (Suc (Suc n)) x = d * geom_proc (Suc n) y\" .\n        moreover have \"geom_proc (Suc (Suc n)) y = u * geom_proc (Suc n) y\" using geometric_process\n          \\<open>m = Suc n\\<close> \\<open>y !! m\\<close> by simp\n        ultimately have \"geom_proc (Suc (Suc n)) x \\<noteq> geom_proc (Suc (Suc n)) y\"\n          by (metis S0_positive down_lt_up down_positive geom_rand_walk_strictly_positive less_irrefl mult_cancel_right)\n        thus ?thesis using \\<open>geom_proc (Suc (Suc n)) x = geom_proc (Suc (Suc n)) y\\<close> by simp\n      qed\n    qed\n  qed\nqed\n\nlemma (in CRR_market)  geom_proc_eq_pseudo_proj_True:\n  shows \"(\\<And>m. m \\<le>  n \\<Longrightarrow> geom_proc m x = geom_proc m y) \\<Longrightarrow>\n    (pseudo_proj_True (n) x = pseudo_proj_True (n) y)\"\nproof -\n  assume a1: \"\\<And>m. m \\<le> n \\<Longrightarrow> geom_proc m x = geom_proc m y\"\n  obtain nn :: \"bool stream \\<Rightarrow> bool stream \\<Rightarrow> nat \\<Rightarrow> nat\" where\n    \"\\<forall>x1 x2 x3. (\\<exists>v4<Suc (Suc x3). geom_proc v4 x2 \\<noteq> geom_proc v4 x1) = (nn x1 x2 x3 < Suc (Suc x3) \\<and> geom_proc (nn x1 x2 x3) x2 \\<noteq> geom_proc (nn x1 x2 x3) x1)\"\n    by moura\n  then have f2: \"\\<forall>n s sa na. (nn sa s n < Suc (Suc n) \\<and> geom_proc (nn sa s n) s \\<noteq> geom_proc (nn sa s n) sa \\<or> \\<not> na < Suc n) \\<or> s !! na = sa !! na\"\n    by (meson geom_proc_eq_snth less_Suc_eq_le)\n  obtain nna :: \"bool stream \\<Rightarrow> bool stream \\<Rightarrow> nat \\<Rightarrow> nat\" where\n    f3: \"\\<forall>x0 x1 x2. (\\<exists>v3. Suc v3 < Suc x2 \\<and> x1 !! v3 \\<noteq> x0 !! v3) = (Suc (nna x0 x1 x2) < Suc x2 \\<and> x1 !! nna x0 x1 x2 \\<noteq> x0 !! nna x0 x1 x2)\"\n    by moura\n  obtain nnb :: \"nat \\<Rightarrow> nat\" where\n    f4: \"\\<forall>x0. (\\<exists>v2. x0 = Suc v2) = (x0 = Suc (nnb x0))\"\n    by moura\n  moreover\n  { assume \"\\<not> nn y x (nnb n) < Suc (Suc (nnb n)) \\<or> geom_proc (nn y x (nnb n)) x = geom_proc (nn y x (nnb n)) y\"\n    moreover\n    { assume \"\\<not> nna y x n < Suc (nnb n)\"\n      then have \"\\<not> Suc (nna y x n) < Suc n \\<or> x !! nna y x n = y !! nna y x n\"\n        using f4 by (metis (no_types) Suc_le_D Suc_le_lessD less_Suc_eq_le) }\n    ultimately have \"pseudo_proj_True n x = pseudo_proj_True n y \\<or> \\<not> Suc (nna y x n) < Suc n \\<or> x !! nna y x n = y !! nna y x n\"\nusing f2 by meson }\n  ultimately have \"pseudo_proj_True n x = pseudo_proj_True n y \\<or> \\<not> Suc (nna y x n) < Suc n \\<or> x !! nna y x n = y !! nna y x n\"\n    using a1 Suc_le_D less_Suc_eq_le by presburger\n  then show ?thesis\n    using f3 by (meson less_Suc_eq_le pseudo_proj_True_snth')\nqed\n\n\n\n\nlemma (in CRR_market)  proj_stoch_eq_pseudo_proj_True:\n  assumes \"proj_stoch_proc geom_proc m x = proj_stoch_proc geom_proc m y\"\n  shows \"pseudo_proj_True m x = pseudo_proj_True m y\"\nproof -\n  have \"\\<forall> k \\<le> m. geom_proc k x = geom_proc k y\"\n  proof (intro allI impI)\n    fix k\n    assume \"k \\<le> m\"\n    thus \"geom_proc k x = geom_proc k y\" using proj_stoch_proc_eq_snth[of geom_proc m x y k] assms by simp\n  qed\n  thus ?thesis  using geom_proc_eq_pseudo_proj_True[of m x y] by auto\nqed\n\nlemma (in CRR_market_viable) rn_rev_price_cond_expect:\n  assumes \"N = bernoulli_stream q\"\nand \"0 <q\"\nand \"q < 1\"\nand \"der \\<in> borel_measurable (G matur)\"\nand \"Suc n \\<le> matur\"\nshows \"expl_cond_expect N (proj_stoch_proc geom_proc n) (rn_rev_price N der matur (matur - Suc n)) w=\n  (q * rn_rev_price N der matur (matur - Suc n) (pseudo_proj_True n w)  +\n      (1 - q) * rn_rev_price N der matur (matur - Suc n) (pseudo_proj_False n w))\"\nproof (rule infinite_cts_filtration.f_borel_Suc_expl_cond_expect)\n  show \"infinite_cts_filtration q N nat_filtration\" using  assms  pslt psgt\n    bernoulli_nat_filtration by simp\n  show \"rn_rev_price N der matur (matur - Suc n) \\<in> borel_measurable (nat_filtration (Suc n))\"\n    using rn_rev_price_rev_borel_adapt[of der matur N q \"Suc n\"]   assms\n      stock_filtration stoch_proc_subalg_nat_filt[of geom_proc] geom_rand_walk_borel_adapted\n    by (metis add_diff_cancel_right' diff_le_self measurable_from_subalg\n        ordered_cancel_comm_monoid_diff_class.add_diff_inverse rn_rev_price_rev_borel_adapt)\n  show \"proj_stoch_proc geom_proc n \\<in> nat_filtration n \\<rightarrow>\\<^sub>M stream_space borel\"\n    using proj_stoch_adapted_if_adapted[of M nat_filtration geom_proc borel n]\n    pslt psgt bernoulli_nat_filtration[of M p] bernoulli geom_rand_walk_borel_adapted\n    nat_discrete_filtration by blast\n  show \"set_discriminating n (proj_stoch_proc geom_proc n) (stream_space borel)\"\n    using infinite_cts_filtration.proj_stoch_set_discriminating\n    pslt psgt bernoulli_nat_filtration[of M p] bernoulli geom_rand_walk_borel_adapted by simp\n  show \"proj_stoch_proc geom_proc n -` {proj_stoch_proc geom_proc n w} \\<in> sets (nat_filtration n)\"\n    using infinite_cts_filtration.proj_stoch_singleton_set\n    pslt psgt bernoulli_nat_filtration[of M p] bernoulli geom_rand_walk_borel_adapted by simp\n  show \"\\<forall>y z. proj_stoch_proc geom_proc n y = proj_stoch_proc geom_proc n z \\<and> y !! n = z !! n \\<longrightarrow>\n    rn_rev_price N der matur (matur - Suc n) y = rn_rev_price N der matur (matur - Suc n) z\"\n  proof (intro allI impI)\n    fix y z\n    assume as:\"proj_stoch_proc geom_proc n y = proj_stoch_proc geom_proc n z \\<and> y !! n = z !! n\"\n    hence \"pseudo_proj_True n y = pseudo_proj_True n z\" using proj_stoch_eq_pseudo_proj_True[of n y z] by simp\n    moreover have \"snth y n = snth z n\" using as by simp\n    ultimately have \"pseudo_proj_True (Suc n) y = pseudo_proj_True (Suc n) z\"\n    proof -\n    have f1: \"\\<forall>n s sa. (\\<exists>na. Suc na \\<le> n \\<and> s !! na \\<noteq> sa !! na) \\<or> pseudo_proj_True n s = pseudo_proj_True n sa\"\n    by (meson pseudo_proj_True_snth')\n      obtain nn :: \"bool stream \\<Rightarrow> bool stream \\<Rightarrow> nat \\<Rightarrow> nat\" where\n        \"\\<forall>x0 x1 x2. (\\<exists>v3. Suc v3 \\<le> x2 \\<and> x1 !! v3 \\<noteq> x0 !! v3) = (Suc (nn x0 x1 x2) \\<le> x2 \\<and> x1 !! nn x0 x1 x2 \\<noteq> x0 !! nn x0 x1 x2)\"\n        by moura\n        then have f2: \"\\<forall>n s sa. Suc (nn sa s n) \\<le> n \\<and> s !! nn sa s n \\<noteq> sa !! nn sa s n \\<or> pseudo_proj_True n s = pseudo_proj_True n sa\"\n          using f1 by presburger\n        have f3: \"stake n y = stake n (pseudo_proj_True n z)\"\n          by (metis \\<open>pseudo_proj_True n y = pseudo_proj_True n z\\<close> pseudo_proj_True_stake)\n        { assume \"stake (Suc n) z \\<noteq> stake (Suc n) (pseudo_proj_True (Suc n) y)\"\n          then have \"stake n y @ [y !! n] \\<noteq> stake n z @ [z !! n]\"\n            by (metis (no_types) pseudo_proj_True_stake stake_Suc)\n          then have \"stake (Suc n) z = stake (Suc n) (pseudo_proj_True (Suc n) y)\"\n            using f3 by (simp add: \\<open>y !! n = z !! n\\<close> pseudo_proj_True_stake) }\n        then have \"\\<not> Suc (nn z y (Suc n)) \\<le> Suc n \\<or> y !! nn z y (Suc n) = z !! nn z y (Suc n)\"\n        by (metis (no_types) pseudo_proj_True_stake stake_snth)\n      then show ?thesis\n        using f2 by blast\n    qed\n    have \"rn_rev_price N der matur (matur - Suc n) y =\n      rn_rev_price N der matur (matur - Suc n) (pseudo_proj_True (Suc n) y)\" using nat_filtration_info[of \"rn_rev_price N der matur (matur - Suc n)\" \"Suc n\"]\n      rn_rev_price_rev_borel_adapt[of der matur N q]\n      by (metis \\<open>rn_rev_price N der matur (matur - Suc n) \\<in> borel_measurable (nat_filtration (Suc n))\\<close> o_apply)\n    also have \"... = rn_rev_price N der matur (matur - Suc n) (pseudo_proj_True (Suc n) z)\"\n      using \\<open>pseudo_proj_True (Suc n) y = pseudo_proj_True (Suc n) z\\<close> by simp\n    also have \"... = rn_rev_price N der matur (matur - Suc n) z\" using nat_filtration_info[of \"rn_rev_price N der matur (matur - Suc n)\" \"Suc n\"]\n      rn_rev_price_rev_borel_adapt[of der matur N q]\n      by (metis \\<open>rn_rev_price N der matur (matur - Suc n) \\<in> borel_measurable (nat_filtration (Suc n))\\<close> o_apply)\n    finally show \"rn_rev_price N der matur (matur - Suc n) y = rn_rev_price N der matur (matur - Suc n) z\" .\n  qed\n  show \"0 < q\" and \"q < 1\" using assms by auto\nqed\n\n\n\n\nlemma (in CRR_market_viable) rn_price_eq_ind:\n  assumes \"N = bernoulli_stream q\"\nand \"n < matur\"\nand \"0 < q\"\nand \"q < 1\"\nand \"der \\<in> borel_measurable (G matur)\"\nshows \"(1+r) * rn_price N der matur n w = q * rn_price N der matur (Suc n) (pseudo_proj_True n w) +\n  (1 - q) * rn_price N der matur (Suc n) (pseudo_proj_False n w)\"\nproof -\n  define V where \"V = rn_price N der matur\"\n  let ?m = \"matur - Suc n\"\n  have \"matur -n = Suc ?m\" by (simp add: assms Suc_diff_Suc Suc_le_lessD)\n  have \"(1+r) * V n w = (1+r) * rn_price_ind N der matur n w\" using rn_price_eq assms unfolding V_def by simp\n  also have \"... = (1+r) * rn_rev_price N der matur (Suc ?m) w\" using \\<open>matur -n = Suc ?m\\<close>\n    unfolding rn_price_ind_def by simp\n  also have \"... = (1+r) * discount_factor r (Suc 0) w *\n                    expl_cond_expect N (proj_stoch_proc geom_proc (matur - Suc ?m)) (rn_rev_price N der matur ?m) w\"\n    by simp\n  also have \"... = expl_cond_expect N (proj_stoch_proc geom_proc (matur - Suc ?m)) (rn_rev_price N der matur ?m) w\"\n    unfolding discount_factor_def using acceptable_rate by auto\n  also have \"... = expl_cond_expect N (proj_stoch_proc geom_proc n) (rn_rev_price N der matur ?m) w\"\n    using \\<open>matur -n = Suc ?m\\<close> by simp\n  also have \"... = (q * rn_rev_price N der matur ?m (pseudo_proj_True n w)  +\n    (1 - q) * rn_rev_price N der matur ?m (pseudo_proj_False n w))\"\n    using rn_rev_price_cond_expect[of N q der matur n w] assms   by simp\n  also have \"... =  q * rn_price_ind N der matur (Suc n) (pseudo_proj_True n w) +\n    (1 - q) * rn_price_ind N der matur (Suc n) (pseudo_proj_False n w)\" unfolding rn_price_ind_def by simp\n  also have \"... = q * rn_price N der matur (Suc n) (pseudo_proj_True n w) +\n    (1 - q) * rn_price N der matur (Suc n) (pseudo_proj_False n w)\" using rn_price_eq assms  by simp\n  also have \"... = q * V (Suc n) (pseudo_proj_True n w) + (1 - q) *V (Suc n) (pseudo_proj_False n w)\"\n    unfolding V_def by simp\n  finally have \"(1+r) * V n w = q * V (Suc n) (pseudo_proj_True n w) + (1 - q) *V (Suc n) (pseudo_proj_False n w)\" .\n  thus ?thesis unfolding V_def by simp\nqed\n\n\n\nlemma self_finance_updated_suc_suc:\n  assumes \"portfolio pf\"\n  and \"\\<forall>n. prices Mkt asset n w \\<noteq> 0\"\n  shows \"cls_val_process Mkt (self_finance Mkt v pf asset) (Suc (Suc n)) w = cls_val_process Mkt pf (Suc (Suc n)) w +\n    (prices Mkt asset (Suc (Suc n)) w / (prices Mkt asset (Suc n) w)) *\n      (cls_val_process Mkt (self_finance Mkt v pf asset) (Suc n) w -\n     val_process Mkt pf (Suc n) w)\"\nproof -\n  have \"cls_val_process Mkt (self_finance Mkt v pf asset) (Suc (Suc n)) w = cls_val_process Mkt pf (Suc (Suc n)) w +\n    prices Mkt asset (Suc (Suc n)) w * remaining_qty Mkt v pf asset (Suc (Suc n)) w\" using assms\n    by (simp add: self_finance_updated)\n  also have \"... = cls_val_process Mkt pf (Suc (Suc n)) w +\n    prices Mkt asset (Suc (Suc n)) w * ((remaining_qty Mkt v pf asset (Suc n) w) +\n    (cls_val_process Mkt pf (Suc n) w - val_process Mkt pf (Suc n) w)/(prices Mkt asset (Suc n) w))\"\n    by simp\n  also have \"... = cls_val_process Mkt pf (Suc (Suc n)) w +\n    prices Mkt asset (Suc (Suc n)) w *\n      ((prices Mkt asset (Suc n) w) * (remaining_qty Mkt v pf asset (Suc n) w) / (prices Mkt asset (Suc n) w) +\n    (cls_val_process Mkt pf (Suc n) w - val_process Mkt pf (Suc n) w)/(prices Mkt asset (Suc n) w))\" using assms\n    by (metis nonzero_mult_div_cancel_left)\n  also have \"... = cls_val_process Mkt pf (Suc (Suc n)) w +\n    prices Mkt asset (Suc (Suc n)) w * ((prices Mkt asset (Suc n) w) * (remaining_qty Mkt v pf asset (Suc n) w) +\n    cls_val_process Mkt pf (Suc n) w - val_process Mkt pf (Suc n) w)/(prices Mkt asset (Suc n) w)\"\n    using add_divide_distrib[symmetric, of \"prices Mkt asset (Suc n) w * remaining_qty Mkt v pf asset (Suc n) w\"\n        \"prices Mkt asset (Suc n) w\"]  by simp\n  also have \"... = cls_val_process Mkt pf (Suc (Suc n)) w +\n    (prices Mkt asset (Suc (Suc n)) w / (prices Mkt asset (Suc n) w)) *\n    ((prices Mkt asset (Suc n) w) * (remaining_qty Mkt v pf asset (Suc n) w) +\n    cls_val_process Mkt pf (Suc n) w - val_process Mkt pf (Suc n) w)\" by simp\n  also have \"... = cls_val_process Mkt pf (Suc (Suc n)) w +\n    (prices Mkt asset (Suc (Suc n)) w / (prices Mkt asset (Suc n) w)) *\n      (cls_val_process Mkt (self_finance Mkt v pf asset) (Suc n) w -\n     val_process Mkt pf (Suc n) w)\"\n    using self_finance_updated[of Mkt asset n w pf v] assms by auto\n  finally show ?thesis .\nqed\n\nlemma self_finance_updated_suc_0:\n  assumes \"portfolio pf\"\n  and \"\\<forall>n w. prices Mkt asset n w \\<noteq> 0\"\n  shows \"cls_val_process Mkt (self_finance Mkt v pf asset) (Suc 0) w = cls_val_process Mkt pf (Suc 0) w +\n    (prices Mkt asset (Suc 0) w / (prices Mkt asset 0 w)) *\n      (val_process Mkt (self_finance Mkt v pf asset) 0 w -\n     val_process Mkt pf 0 w)\"\nproof -\n  have \"cls_val_process Mkt (self_finance Mkt v pf asset) (Suc 0) w = cls_val_process Mkt pf (Suc 0) w +\n    prices Mkt asset (Suc 0) w * remaining_qty Mkt v pf asset (Suc 0) w\" using assms\n    by (simp add: self_finance_updated)\n  also have \"... = cls_val_process Mkt pf (Suc 0) w +\n    prices Mkt asset (Suc 0) w * ((v - val_process Mkt pf 0 w)/(prices Mkt asset 0 w))\"\n    by simp\n  also have \"... = cls_val_process Mkt pf (Suc 0) w +\n    prices Mkt asset (Suc 0) w * ((remaining_qty Mkt v pf asset 0 w) +\n    (v - val_process Mkt pf 0 w)/(prices Mkt asset 0 w))\"\n    by simp\n  also have \"... = cls_val_process Mkt pf (Suc 0) w +\n    prices Mkt asset (Suc 0) w *\n      ((prices Mkt asset 0 w) * (remaining_qty Mkt v pf asset 0 w) / (prices Mkt asset 0 w) +\n    (v - val_process Mkt pf 0 w)/(prices Mkt asset 0 w))\" using assms\n    by (metis nonzero_mult_div_cancel_left)\n  also have \"... = cls_val_process Mkt pf (Suc 0) w +\n    prices Mkt asset (Suc 0) w * ((prices Mkt asset 0 w) * (remaining_qty Mkt v pf asset 0 w) +\n    v - val_process Mkt pf 0 w)/(prices Mkt asset 0 w)\"\n    using add_divide_distrib[symmetric, of \"prices Mkt asset 0 w * remaining_qty Mkt v pf asset 0 w\"\n        \"prices Mkt asset 0 w\"]  by simp\n  also have \"... = cls_val_process Mkt pf (Suc 0) w +\n    (prices Mkt asset (Suc 0) w / (prices Mkt asset 0 w)) *\n    ((prices Mkt asset 0 w) * (remaining_qty Mkt v pf asset 0 w) +\n    v - val_process Mkt pf 0 w)\" by simp\n  also have \"... = cls_val_process Mkt pf (Suc 0) w +\n    (prices Mkt asset (Suc 0) w / (prices Mkt asset 0 w)) *\n    ((prices Mkt asset 0 w) * (remaining_qty Mkt v pf asset 0 w) +\n    val_process Mkt (self_finance Mkt v pf asset) 0 w - val_process Mkt pf 0 w)\"\n    using self_finance_init[of Mkt asset pf v w] assms by simp\n  also have \"... = cls_val_process Mkt pf (Suc 0) w +\n    (prices Mkt asset (Suc 0) w / (prices Mkt asset 0 w)) *\n      (val_process Mkt (self_finance Mkt v pf asset) 0 w -\n     val_process Mkt pf 0 w)\" by simp\n  finally show ?thesis .\nqed\n\nlemma self_finance_updated_ind:\n  assumes \"portfolio pf\"\n  and \"\\<forall>n w. prices Mkt asset n w \\<noteq> 0\"\n  shows \"cls_val_process Mkt (self_finance Mkt v pf asset) (Suc n) w = cls_val_process Mkt pf (Suc n) w +\n    (prices Mkt asset (Suc n) w / (prices Mkt asset n w)) *\n      (val_process Mkt (self_finance Mkt v pf asset) n w -\n     val_process Mkt pf n w)\"\nproof (cases \"n = 0\")\n  case True\n  thus ?thesis using assms self_finance_updated_suc_0 by simp\nnext\n  case False\n  hence \"\\<exists>m. n = Suc m\" by (simp add: not0_implies_Suc)\n  from this obtain m where \"n = Suc m\" by auto\n  hence \"cls_val_process Mkt (self_finance Mkt v pf asset) (Suc n) w =\n    cls_val_process Mkt (self_finance Mkt v pf asset) (Suc (Suc m)) w\" by simp\n  also have \"...  = cls_val_process Mkt pf (Suc (Suc m)) w +\n    (prices Mkt asset (Suc (Suc m)) w / (prices Mkt asset (Suc m) w)) *\n      (cls_val_process Mkt (self_finance Mkt v pf asset) (Suc m) w -\n     val_process Mkt pf (Suc m) w)\" using assms self_finance_updated_suc_suc[of pf] by simp\n  also have \"... = cls_val_process Mkt pf (Suc (Suc m)) w +\n    (prices Mkt asset (Suc (Suc m)) w / (prices Mkt asset (Suc m) w)) *\n      (val_process Mkt (self_finance Mkt v pf asset) (Suc m) w -\n     val_process Mkt pf (Suc m) w)\" using assms self_finance_charact unfolding self_financing_def\n    by (simp add: self_finance_succ self_finance_updated)\n  also have \"... = cls_val_process Mkt pf (Suc n) w +\n    (prices Mkt asset (Suc n) w / (prices Mkt asset n w)) *\n      (val_process Mkt (self_finance Mkt v pf asset) n w -\n     val_process Mkt pf n w)\" using \\<open>n = Suc m\\<close> by simp\n  finally show ?thesis .\nqed\n\n\nlemma  (in rfr_disc_equity_market) self_finance_risk_free_update_ind:\n  assumes \"portfolio pf\"\n  shows \"cls_val_process Mkt (self_finance Mkt v pf risk_free_asset) (Suc n) w = cls_val_process Mkt pf (Suc n) w +\n    (1 + r) * (val_process Mkt (self_finance Mkt v pf risk_free_asset) n w - val_process Mkt pf n w)\"\nproof -\n  have \"cls_val_process Mkt (self_finance Mkt v pf risk_free_asset) (Suc n) w =\n    cls_val_process Mkt pf (Suc n) w +\n    (prices Mkt risk_free_asset (Suc n) w / (prices Mkt risk_free_asset n w)) *\n      (val_process Mkt (self_finance Mkt v pf risk_free_asset) n w -\n     val_process Mkt pf n w)\"\n  proof (rule self_finance_updated_ind, (simp add: assms), intro allI)\n    fix n w\n    show \"prices Mkt risk_free_asset n w \\<noteq> 0\" using positive by (metis less_irrefl)\n  qed\n  also have \"... = cls_val_process Mkt pf (Suc n) w +\n    (1+r) * (val_process Mkt (self_finance Mkt v pf risk_free_asset) n w -\n     val_process Mkt pf n w)\" using rf_price  positive\n    by (metis acceptable_rate disc_rfr_proc_Suc_div)\n  finally show ?thesis .\nqed\n\n\n\nlemma (in CRR_market) delta_pf_portfolio:\n  shows \"portfolio (delta_pf N der matur)\" unfolding delta_pf_def by (simp add: single_comp_portfolio)\n\nlemma (in CRR_market) delta_pf_updated:\n  shows \"cls_val_process Mkt (delta_pf N der matur) (Suc n) w =\n    geom_proc (Suc n) w * delta_price N der matur n w\" unfolding delta_pf_def\n    using stk_price qty_single_updated[of Mkt] by simp\n\nlemma (in CRR_market) delta_pf_val_process:\n  shows \"val_process Mkt (delta_pf N der matur) n w =\n    geom_proc n w * delta_price N der matur n w\" unfolding delta_pf_def\n  using stk_price qty_single_val_process[of Mkt] by simp\n\nlemma (in CRR_market) delta_hedging_cls_val_process:\n  shows \"cls_val_process Mkt (delta_hedging N der matur) (Suc n) w =\n    geom_proc (Suc n) w * delta_price N der matur n w +\n    (1 + r) * (val_process Mkt (delta_hedging N der matur) n w - geom_proc n w * delta_price N der matur n w)\"\nproof -\n  define X where \"X = delta_hedging N der matur\"\n  define init where \"init = integral\\<^sup>L N (discounted_value r (\\<lambda>m. der) matur)\"\n  have \"cls_val_process Mkt X (Suc n) w = cls_val_process Mkt (delta_pf N der matur) (Suc n) w +\n    (1 + r) * (val_process Mkt X n w - val_process Mkt (delta_pf N der matur) n w)\"\n    unfolding X_def delta_hedging_def self_fin_delta_pf_def init_def\n  proof (rule self_finance_risk_free_update_ind)\n    show \"portfolio (delta_pf N der matur)\" unfolding  portfolio_def using delta_pf_support\n      by (meson finite.simps infinite_super)\n  qed\n  also have \"... = geom_proc (Suc n) w * delta_price N der matur n w +\n    (1 + r) * (val_process Mkt X n w - val_process Mkt (delta_pf N der matur) n w)\"\n    using delta_pf_updated by simp\n  also have \"... = geom_proc (Suc n) w * delta_price N der matur n w +\n    (1 + r) * (val_process Mkt X n w - geom_proc n w * delta_price N der matur n w)\"\n    using delta_pf_val_process by simp\n  finally show ?thesis unfolding X_def .\nqed\n\n\n\n\n\n\n\nlemma (in CRR_market_viable) delta_hedging_eq_derivative_price:\n  fixes der::\"bool stream \\<Rightarrow> real\" and matur::nat\n  assumes \"N = bernoulli_stream ((1 + r - d) / (u - d))\"\n  and \"der\\<in> borel_measurable (G matur)\"\n  shows \"\\<And>n w. n\\<le> matur \\<Longrightarrow>\n    val_process Mkt (delta_hedging N der matur) n w =\n    (rn_price N der matur) n w\"\nunfolding delta_hedging_def\nproof -\n  define q where \"q = (1 + r - d) / (u - d)\"\n  have \"0 < q\" and \"q < 1\" unfolding q_def using assms gt_param lt_param CRR_viable by auto\n  note qprops = this\n  define init where  \"init = (prob_space.expectation N (discounted_value r (\\<lambda>m. der) matur))\"\n  define X where \"X = val_process Mkt (delta_hedging N der matur)\"\n  define V where \"V = rn_price N der matur\"\n  define \\<Delta> where \"\\<Delta> = delta_price N der matur\"\n  {\n    fix n\n    fix w\n    have \"n \\<le> matur \\<Longrightarrow> X n w = V n w\"\n    proof (induct n)\n    case 0\n    have v0: \"V 0 \\<in> borel_measurable (G 0)\" using assms rn_price_borel_adapt \"0.prems\" qprops\n      unfolding V_def q_def by auto\n    have \"X 0 w= init\" using self_finance_init[of Mkt risk_free_asset \"delta_pf N der matur\" \"integral\\<^sup>L N (discounted_value r (\\<lambda>m. der) matur)\"]\n        delta_pf_support\n      unfolding  X_def init_def delta_hedging_def self_fin_delta_pf_def init_def\n      by (metis finite_insert infinite_imp_nonempty infinite_super less_irrefl portfolio_def positive)\n    also have \"... = V 0 w\" \n    proof -\n      have \"\\<forall>x\\<in>space N. real_cond_exp N (G 0) (discounted_value r (\\<lambda>m. der) matur) x =\n        integral\\<^sup>L N (discounted_value r (\\<lambda>m. der) matur)\"\n      proof (rule prob_space.trivial_subalg_cond_expect_eq)\n        show \"prob_space N\" using assms qprops unfolding q_def\n          by (simp add: bernoulli bernoulli_stream_def prob_space.prob_space_stream_space prob_space_measure_pmf)\n        have \"init_triv_filt M (stoch_proc_filt M geom_proc borel)\"\n        proof (rule infinite_cts_filtration.stoch_proc_filt_triv_init)\n          show \"borel_adapt_stoch_proc nat_filtration geom_proc\" using geom_rand_walk_borel_adapted by simp\n          show \"infinite_cts_filtration p M nat_filtration\" using bernoulli_nat_filtration[of M p] bernoulli psgt pslt\n            by simp\n        qed\n        hence \"init_triv_filt N (stoch_proc_filt M geom_proc borel)\" using assms qprops\n          filt_equiv_triv_init[of nat_filtration N] stock_filtration\n          bernoulli_stream_equiv[of N] psgt pslt unfolding q_def by simp\n        thus \"subalgebra N (G 0)\" and \"sets (G 0) = {{}, space N}\" using stock_filtration unfolding init_triv_filt_def\n          filtration_def bot_nat_def by auto\n        show \"integrable N (discounted_value r (\\<lambda>m. der) matur)\"\n        proof (rule bernoulli_discounted_integrable)\n          show \"der \\<in> borel_measurable (nat_filtration matur)\" using assms geom_rand_walk_borel_adapted\n              measurable_from_subalg stoch_proc_subalg_nat_filt stock_filtration by blast\n          show \"N = bernoulli_stream q\" using assms unfolding q_def by simp\n          show \"0 < q\" \"q < 1\" using qprops by auto\n        qed (simp add: acceptable_rate)\n      qed\n      hence \"integral\\<^sup>L N (discounted_value r (\\<lambda>m. der) matur) =\n        real_cond_exp N (G 0) (discounted_value r (\\<lambda>m. der) matur) w\" using bernoulli_stream_space[of N q]\n        by (simp add: assms(1) q_def)\n      also have \"... = real_cond_exp N (stoch_proc_filt M geom_proc borel 0) (discounted_value r (\\<lambda>m. der) matur) w\"\n        using stock_filtration by simp\n      also have \"... = real_cond_exp N (stoch_proc_filt N geom_proc borel 0) (discounted_value r (\\<lambda>m. der) matur) w\"\n        using stoch_proc_filt_filt_equiv[of nat_filtration M N geom_proc]\n          bernoulli_stream_equiv[of N] q_def qprops assms pslt psgt by auto\n      also have \"... = expl_cond_expect N (proj_stoch_proc geom_proc 0) (discounted_value r (\\<lambda>m. der) matur) w\"\n      proof (rule bernoulli_cond_exp)\n        show \"N = bernoulli_stream q\" using assms unfolding q_def by simp\n        show \"0 < q\" \"q < 1\" using qprops by auto\n        show \"integrable N (discounted_value r (\\<lambda>m. der) matur)\"\n        proof (rule bernoulli_discounted_integrable)\n          show \"der \\<in> borel_measurable (nat_filtration matur)\" using assms geom_rand_walk_borel_adapted\n              measurable_from_subalg stoch_proc_subalg_nat_filt stock_filtration by blast\n          show \"N = bernoulli_stream q\" using assms unfolding q_def by simp\n          show \"0 < q\" \"q < 1\" using qprops by auto\n        qed (simp add: acceptable_rate)\n      qed\n      finally show \"init = V 0 w\" unfolding init_def V_def rn_price_def by simp\n    qed\n    finally show \"X 0 w = V 0 w\" .\n    next\n      case (Suc n)\n      hence \"n < matur\" by simp\n      show ?case\n      proof -\n        have \"X n w = V n w\" using Suc by (simp add: Suc.hyps Suc.prems Suc_leD)\n        have \"0< 1+r\" using acceptable_rate by simp\n        let ?m = \"matur - Suc n\"\n        have \"matur -n = Suc ?m\" by (simp add: Suc.prems Suc_diff_Suc Suc_le_lessD)\n        have \"(1+r) * V n w = q * V (Suc n) (pseudo_proj_True n w) + (1 - q) *V (Suc n) (pseudo_proj_False n w)\"\n          using rn_price_eq_ind qprops assms Suc q_def V_def by simp\n        show \"X (Suc n) w = V (Suc n) w\"\n        proof (cases \"snth w n\")\n        case True\n          hence pseq: \"pseudo_proj_True (Suc n) w = pseudo_proj_True (Suc n) (spick w n True)\"\n            by (metis (mono_tags, lifting) pseudo_proj_True_stake_image spickI stake_Suc)\n          have \"X (Suc n) w = cls_val_process Mkt (delta_hedging N der matur) (Suc n) w\"\n            unfolding X_def delta_hedging_def self_fin_delta_pf_def using  delta_pf_portfolio\n            unfolding self_financing_def\n            by (metis less_irrefl positive self_finance_charact self_financingE)\n          also have \"... = geom_proc (Suc n) w * \\<Delta> n w + (1 + r) * (X n w - geom_proc n w * \\<Delta> n w)\"\n            using delta_hedging_cls_val_process unfolding X_def \\<Delta>_def by simp\n          also have \"... = u * geom_proc n w * \\<Delta> n w + (1 + r) * (X n w - geom_proc n w * \\<Delta> n w)\"\n            using True geometric_process by simp\n          also have \"... = u * geom_proc n w * \\<Delta> n w + (1 + r) * X n w - (1+r) * geom_proc n w * \\<Delta> n w\"\n            by (simp add: right_diff_distrib)\n          also have \"... = (1+r) * X n w + geom_proc n w * \\<Delta> n w * u - geom_proc n w * \\<Delta> n w * (1 + r)\"\n            by (simp add: mult.commute mult.left_commute)\n          also have \"... = (1+r)* X n w + geom_proc n w * \\<Delta> n w * (u - (1 + r))\" by (simp add: right_diff_distrib)\n          also have \"... = (1+r) * X n w + geom_proc n w * (V (Suc n) (pseudo_proj_True n w) - V (Suc n) (pseudo_proj_False n w))/\n            (geom_proc (Suc n) (spick w n True) - geom_proc (Suc n) (spick w n False)) * (u - (1 + r))\"\n            using Suc V_def by (simp add: \\<Delta>_def delta_price_def geom_rand_walk_diff_induct)\n          also have \"... = (1+r) * X n w + geom_proc n w * ((V (Suc n) (pseudo_proj_True n w) - V (Suc n) (pseudo_proj_False n w))) /\n            (geom_proc n w * (u - d)) * (u - (1 + r))\"\n          proof -\n            have \"geom_proc (Suc n) (spick w n True) - geom_proc (Suc n) (spick w n False) =\n              geom_proc n w * (u - d)\"\n              by (simp add: geom_rand_walk_diff_induct)\n            then show ?thesis by simp\n          qed\n          also have \"... = (1+r) * X n w + ((V (Suc n) (pseudo_proj_True n w) - V (Suc n) (pseudo_proj_False n w)))* (u - (1 + r))/ (u-d)\"\n          proof -\n            have \"geom_proc n w \\<noteq> 0\"\n              by (metis S0_positive down_lt_up down_positive geom_rand_walk_strictly_positive less_irrefl)\n            then show ?thesis\n              by simp\n          qed\n          also have \"... = (1+r) * X n w + ((V (Suc n) (pseudo_proj_True n w) - V (Suc n) (pseudo_proj_False n w))* (1 - q))\"\n          proof -\n            have \"1 - q = 1 - (1 + r - d)/(u -d)\" unfolding q_def by simp\n            also have \"... = (u - d)/(u - d) - (1 + r - d)/(u -d)\" using down_lt_up by simp\n            also have \"... = (u - d - (1 + r - d))/(u - d)\" using diff_divide_distrib[of \"u - d\" \"1 + r -d\"] by simp\n            also have \"... = (u - (1+r))/(u-d)\" by simp\n            finally have \"1 - q = (u - (1+r))/(u-d)\" .\n            thus ?thesis by simp\n          qed\n          also have \"... = (1+r) * X n w + (1 - q) * V (Suc n) (pseudo_proj_True n w) -\n            (1 - q) * V (Suc n) (pseudo_proj_False n w)\"\n            by (simp add: mult.commute right_diff_distrib)\n          also have \"... = (1+r) * V n w + (1 - q) * V (Suc n) (pseudo_proj_True n w) -\n            (1 - q) * V (Suc n) (pseudo_proj_False n w)\" using \\<open>X n w = V n w\\<close> by simp\n          also have \"... = q * V (Suc n) (pseudo_proj_True n w) + (1 - q) * V (Suc n) (pseudo_proj_False n w) +\n            (1 - q) * V (Suc n) (pseudo_proj_True n w) - (1 - q) * V (Suc n) (pseudo_proj_False n w)\"\n          using assms Suc rn_price_eq_ind[of N q n matur der w] \\<open>n < matur\\<close> qprops unfolding V_def q_def\n            by simp\n          also have \"... = q * V (Suc n) (pseudo_proj_True n w) + (1 - q) * V (Suc n) (pseudo_proj_True n w)\" by simp\n          also have \"... = V (Suc n) (pseudo_proj_True n w)\"\n            using distrib_right[of q \"1 - q\"  \"V (Suc n) (pseudo_proj_True n w)\"] by simp\n          also have \"... = V (Suc n) w\"\n          proof -\n            have \"V (Suc n) \\<in> borel_measurable (G (Suc n))\" unfolding V_def q_def\n            proof (rule rn_price_borel_adapt)\n              show \"der \\<in> borel_measurable (G matur)\" using assms by simp\n              show \"N = bernoulli_stream q\" using assms unfolding q_def by simp\n              show \"0 < q\" and \"q < 1\" using qprops by auto\n              show \"Suc n \\<le> matur\" using Suc by simp\n            qed\n            hence \"V (Suc n) (pseudo_proj_True n w) = V (Suc n) (pseudo_proj_True (Suc n) (pseudo_proj_True n w))\"\n              using  geom_proc_filt_info[of \"V (Suc n)\" \"Suc n\"] by simp\n            also have \"... = V (Suc n) (pseudo_proj_True (Suc n) w)\" using True\n              by (simp add: pseq spick_eq_pseudo_proj_True)\n            also have \"... = V (Suc n) w\" using \\<open>V (Suc n) \\<in> borel_measurable (G (Suc n))\\<close>\n              geom_proc_filt_info[of \"V (Suc n)\" \"Suc n\"] by simp\n            finally show ?thesis .\n          qed\n          finally show \"X (Suc n) w = V (Suc n) w\" .\n        next\n        case False\n          hence pseq: \"pseudo_proj_True (Suc n) w = pseudo_proj_True (Suc n) (spick w n False)\" using filtration\n            by (metis (full_types) pseudo_proj_True_def spickI stake_Suc)\n          have \"X (Suc n) w = cls_val_process Mkt (delta_hedging N der matur) (Suc n) w\"\n            unfolding X_def delta_hedging_def self_fin_delta_pf_def using  delta_pf_portfolio\n            unfolding self_financing_def\n            by (metis less_irrefl positive self_finance_charact self_financingE)\n          also have \"... = geom_proc (Suc n) w * \\<Delta> n w + (1 + r) * (X n w - geom_proc n w * \\<Delta> n w)\"\n            using delta_hedging_cls_val_process unfolding X_def \\<Delta>_def by simp\n          also have \"... = d * geom_proc n w * \\<Delta> n w + (1 + r) * (X n w - geom_proc n w * \\<Delta> n w)\"\n            using False geometric_process by simp\n          also have \"... = d * geom_proc n w * \\<Delta> n w + (1 + r) * X n w - (1+r) * geom_proc n w * \\<Delta> n w\"\n            by (simp add: right_diff_distrib)\n          also have \"... = (1+r) * X n w + geom_proc n w * \\<Delta> n w * d - geom_proc n w * \\<Delta> n w * (1 + r)\"\n            by (simp add: mult.commute mult.left_commute)\n          also have \"... = (1+r)* X n w + geom_proc n w * \\<Delta> n w * (d - (1 + r))\" by (simp add: right_diff_distrib)\n          also have \"... = (1+r) * X n w + geom_proc n w * (V (Suc n) (pseudo_proj_True n w) - V (Suc n) (pseudo_proj_False n w))/\n            (geom_proc (Suc n) (spick w n True) - geom_proc (Suc n) (spick w n False)) * (d - (1 + r))\"\n            using Suc V_def by (simp add: \\<Delta>_def delta_price_def geom_rand_walk_diff_induct)\n          also have \"... = (1+r) * X n w + geom_proc n w * ((V (Suc n) (pseudo_proj_True n w) - V (Suc n) (pseudo_proj_False n w))) /\n            (geom_proc n w * (u - d)) * (d - (1 + r))\"\n            by (simp add: geom_rand_walk_diff_induct)\n          also have \"... = (1+r) * X n w + ((V (Suc n) (pseudo_proj_True n w) - V (Suc n) (pseudo_proj_False n w)))* (d - (1 + r))/ (u-d)\"\n          proof -\n            have \"geom_proc n w \\<noteq> 0\"\n              by (metis S0_positive down_lt_up down_positive geom_rand_walk_strictly_positive less_irrefl)\n            then show ?thesis\n              by simp\n          qed\n          also have \"... = (1+r) * X n w + ((V (Suc n) (pseudo_proj_True n w) - V (Suc n) (pseudo_proj_False n w))* (-q))\"\n          proof -\n            have \"0-q = 0-(1 + r - d)/(u -d)\" unfolding q_def by simp\n            also have \"... = (d - (1 + r))/(u -d)\" by (simp add: minus_divide_left)\n            finally have \"0 - q = (d - (1+r))/(u-d)\" .\n            thus ?thesis by simp\n          qed\n          also have \"... = (1+r) * X n w + (- V (Suc n) (pseudo_proj_True n w) * q + V (Suc n) (pseudo_proj_False n w)* q)\"\n            by (metis (no_types, hide_lams) add.inverse_inverse distrib_right minus_mult_commute minus_real_def mult_minus_left)\n          also have \"... = (1+r) * X n w - q * V (Suc n) (pseudo_proj_True n w) + q * V (Suc n) (pseudo_proj_False n w)\" by simp\n          also have \"... = (1+r) * V n w -q * V (Suc n) (pseudo_proj_True n w) +\n            q * V (Suc n) (pseudo_proj_False n w)\" using \\<open>X n w = V n w\\<close> by simp\n          also have \"... = q * V (Suc n) (pseudo_proj_True n w) + (1 - q) * V (Suc n) (pseudo_proj_False n w) -\n            q * V (Suc n) (pseudo_proj_True n w) + q * V (Suc n) (pseudo_proj_False n w)\"\n            using assms Suc rn_price_eq_ind[of N q n matur der w] \\<open>n < matur\\<close> qprops unfolding V_def q_def\n            by simp\n          also have \"... = (1-q) * V (Suc n) (pseudo_proj_False n w) + q * V (Suc n) (pseudo_proj_False n w)\" by simp\n          also have \"... = V (Suc n) (pseudo_proj_False n w)\"\n            using distrib_right[of q \"1 - q\"  \"V (Suc n) (pseudo_proj_False n w)\"] by simp\n          also have \"... = V (Suc n) w\"\n          proof -\n            have \"V (Suc n) \\<in> borel_measurable (G (Suc n))\" unfolding V_def q_def\n            proof (rule rn_price_borel_adapt)\n              show \"der \\<in> borel_measurable (G matur)\" using assms by simp\n              show \"N = bernoulli_stream q\" using assms unfolding q_def by simp\n              show \"0 < q\" and \"q < 1\" using qprops by auto\n              show \"Suc n \\<le> matur\" using Suc by simp\n            qed\n            hence \"V (Suc n) (pseudo_proj_False n w) = V (Suc n) (pseudo_proj_False (Suc n) (pseudo_proj_False n w))\"\n              using  geom_proc_filt_info'[of \"V (Suc n)\" \"Suc n\"] by simp\n            also have \"... = V (Suc n) (pseudo_proj_False (Suc n) w)\" using False  spick_eq_pseudo_proj_False\n              by (metis pseq pseudo_proj_True_imp_False)\n            also have \"... = V (Suc n) w\" using \\<open>V (Suc n) \\<in> borel_measurable (G (Suc n))\\<close>\n              geom_proc_filt_info'[of \"V (Suc n)\" \"Suc n\"] by simp\n            finally show ?thesis .\n          qed\n          finally show \"X (Suc n) w = V (Suc n) w\" .\n        qed\n      qed\n    qed\n  }\n  thus \"\\<And>n w. n \\<le> matur \\<Longrightarrow>\n           val_process Mkt (self_fin_delta_pf N der matur (integral\\<^sup>L N (discounted_value r (\\<lambda>m. der) matur))) n w =\n            rn_price N der matur n w\" by (simp add: X_def init_def V_def delta_hedging_def)\nqed\n\n\nlemma (in CRR_market_viable) delta_hedging_same_cash_flow:\n  assumes \"der \\<in> borel_measurable (G matur)\"\nand \"N = bernoulli_stream ((1 + r - d) / (u - d))\"\n  shows \"cls_val_process Mkt (delta_hedging N der matur) matur w =\n    der w\"\nproof  -\n  define q where \"q = (1 + r - d) / (u - d)\"\n  have \"0 < q\" and \"q < 1\" unfolding q_def using assms gt_param lt_param CRR_viable by auto\n  note qprops = this\n  have \"cls_val_process Mkt (delta_hedging N der matur) matur w =\n    val_process Mkt (delta_hedging N der matur) matur w\" using self_financingE self_finance_charact\n    unfolding delta_hedging_def self_fin_delta_pf_def\n    by (metis delta_pf_portfolio mult_1s(1) mult_cancel_right not_real_square_gt_zero positive)\n  also have \"... = rn_price N der matur matur w\" using delta_hedging_eq_derivative_price assms by simp\n  also have \"... = rn_rev_price N der matur 0 w\" using rn_price_eq qprops assms\n    unfolding rn_price_ind_def q_def by simp\n  also have \"... = der w\" by simp\n  finally show ?thesis .\nqed\n\nlemma (in CRR_market) delta_hedging_trading_strat:\n  assumes \"N = bernoulli_stream q\"\n  and \"0 < q\"\nand \"q < 1\"\nand \"der \\<in> borel_measurable (G matur)\"\n  shows \"trading_strategy (delta_hedging N der matur)\" unfolding delta_hedging_def\n  by (simp add: assms self_fin_delta_pf_trad_strat)\n\nlemma (in CRR_market) delta_hedging_self_financing:\n  shows \"self_financing Mkt (delta_hedging N der matur)\" unfolding delta_hedging_def self_fin_delta_pf_def\nproof (rule self_finance_charact)\n  show \"\\<forall>n w. prices Mkt risk_free_asset (Suc n) w \\<noteq> 0\" using positive\n    by (metis less_numeral_extra(3))\n  show \"portfolio (delta_pf N der matur)\" using delta_pf_portfolio .\nqed\n\nlemma (in CRR_market_viable) delta_hedging_replicating:\n  assumes \"der \\<in> borel_measurable (G matur)\"\n  and \"N = bernoulli_stream ((1 + r - d) / (u - d))\"\n  shows \"replicating_portfolio (delta_hedging N der matur) der matur\"\nunfolding replicating_portfolio_def\nproof (intro conjI)\n  define q where \"q = (1 + r - d) / (u - d)\"\n  have \"0 < q\" and \"q < 1\" unfolding q_def using assms gt_param lt_param CRR_viable by auto\n  note qprops = this\n  let ?X = \"(delta_hedging N der matur)\"\n  show \"trading_strategy ?X\" using delta_hedging_trading_strat qprops assms unfolding q_def by simp\n  show \"self_financing Mkt ?X\" using delta_hedging_self_financing .\n  show \"stock_portfolio Mkt (delta_hedging N der matur)\" unfolding delta_hedging_def self_fin_delta_pf_def\n    stock_portfolio_def portfolio_def using stocks delta_pf_support\n    by (smt Un_insert_right delta_pf_portfolio insert_commute portfolio_def self_finance_def\n        self_finance_portfolio single_comp_support subset_insertI2 subset_singleton_iff\n        sum_support_set sup_bot.right_neutral)\n  show \"AEeq M (cls_val_process Mkt (delta_hedging N der matur) matur) der\"\n    using delta_hedging_same_cash_flow assms by simp\nqed\n\ndefinition (in disc_equity_market) complete_market where\n\"complete_market \\<longleftrightarrow> (\\<forall>matur. \\<forall> der\\<in> borel_measurable (F matur). (\\<exists>p. replicating_portfolio p der matur))\"\n\nlemma (in CRR_market_viable) CRR_market_complete:\n  shows \"complete_market\" unfolding complete_market_def\nproof (intro allI impI)\n  fix matur::nat\n  show \"\\<forall> der \\<in> borel_measurable (G matur). (\\<exists>p. replicating_portfolio p der matur)\"\n  proof\n    fix der::\"bool stream\\<Rightarrow>real\"\n    assume \"der \\<in> borel_measurable (G matur)\"\n    define N where \"N = bernoulli_stream ((1 + r - d) / (u - d))\"\n    hence \"replicating_portfolio (delta_hedging N der matur) der matur\" using delta_hedging_replicating\n      \\<open>der \\<in> borel_measurable (G matur)\\<close> by simp\n    thus \"\\<exists>pf. replicating_portfolio pf der matur\" by auto\n  qed\nqed\n\n\nlemma subalgebras_filtration:\n  assumes \"filtration M F\"\nand \"\\<forall>t. subalgebra (F t) (G t)\"\nand \"\\<forall> s t. s \\<le> t \\<longrightarrow> subalgebra (G t) (G s)\"\nshows \"filtration M G\" unfolding filtration_def\nproof (intro conjI allI impI)\n  {\n    fix t\n    have \"subalgebra (F t) (G t)\" using assms by simp\n    moreover have \"subalgebra M (F t)\" using assms unfolding filtration_def by simp\n    ultimately show \"subalgebra M (G t)\" by (metis subalgebra_def subsetCE subsetI)\n  }\n  {\n    fix s t::'b\n    assume \"s \\<le> t\"\n    thus \"subalgebra (G t) (G s)\" using assms by simp\n  }\nqed\n\n\n\nlemma subfilt_filt_equiv:\n  assumes \"filt_equiv F M N\"\nand \"\\<forall> t. subalgebra (F t) (G t)\"\nand \"\\<forall> s t. s \\<le> t \\<longrightarrow> subalgebra (G t) (G s)\"\nshows \"filt_equiv G M N\" unfolding filt_equiv_def\nproof (intro conjI)\n  show \"sets M = sets N\" using assms unfolding filt_equiv_def by simp\n  show \"filtration M G\" using assms subalgebras_filtration[of M F G] unfolding filt_equiv_def by simp\n  show \"\\<forall>t A. A \\<in> sets (G t) \\<longrightarrow> (emeasure M A = 0) = (emeasure N A = 0)\"\n  proof (intro allI ballI impI)\n    fix t\n    fix A\n    assume \"A\\<in> sets (G t)\"\n    hence \"A \\<in> sets (F t)\" using assms unfolding subalgebra_def by auto\n    thus \"(emeasure M A = 0) = (emeasure N A = 0)\" using assms unfolding filt_equiv_def by simp\n  qed\nqed\n\nlemma (in CRR_market_viable) CRR_market_fair_price:\n  assumes \"pyf\\<in> borel_measurable (G matur)\"\n  shows \"fair_price Mkt\n    (\\<Sum> w\\<in> range (pseudo_proj_True matur). (prod (prob_component ((1 + r - d) / (u - d)) w) {0..<matur}) *\n      ((discounted_value r (\\<lambda>m. pyf) matur) w))\n    pyf matur\"\nproof -\n  define dpf where \"dpf = (discounted_value r (\\<lambda>m. pyf) matur)\"\n  define q where \"q = (1 + r - d) / (u - d)\"\n  have \"\\<exists>pf. replicating_portfolio pf pyf matur\" using CRR_market_complete assms unfolding complete_market_def by simp\n  from this obtain pf where \"replicating_portfolio pf pyf matur\" by auto note pfprop = this\n  define N where \"N = bernoulli_stream ((1 + r - d) / (u - d))\"\n  have \"fair_price Mkt (integral\\<^sup>L N dpf) pyf matur\" unfolding dpf_def\n  proof (rule replicating_expectation_finite)\n    show \"risk_neutral_prob N\" using assms risk_neutral_iff\n      using CRR_viable gt_param lt_param N_def by blast\n    have \"filt_equiv nat_filtration M N\"  using bernoulli_stream_equiv[of N \"(1+r-d)/(u-d)\"]\n        assms gt_param lt_param CRR_viable psgt pslt N_def by simp\n    thus \"filt_equiv G M N\" using subfilt_filt_equiv\n      using Filtration.filtration_def filtration geom_rand_walk_borel_adapted\n        stoch_proc_subalg_nat_filt stock_filtration by blast\n    show \"pyf \\<in> borel_measurable (G matur)\" using assms by simp\n    show \"viable_market Mkt\" using CRR_viable by simp\n    have \"infinite_cts_filtration p M nat_filtration\" using bernoulli_nat_filtration[of M p] bernoulli psgt pslt\n      by simp\n    thus \"sets (G 0) = {{}, space M}\" using stock_filtration\n      infinite_cts_filtration.stoch_proc_filt_triv_init[of p M nat_filtration geom_proc]\n      geom_rand_walk_borel_adapted bot_nat_def unfolding init_triv_filt_def by simp\n    show \"replicating_portfolio pf pyf matur\" using pfprop .\n    show \"\\<forall>n. \\<forall>asset\\<in>support_set pf. finite (prices Mkt asset n ` space M)\"\n    proof (intro allI ballI)\n      fix n\n      fix asset\n      assume \"asset \\<in> support_set pf\"\n      hence \"prices Mkt asset n \\<in> borel_measurable (G n)\" using readable pfprop\n        unfolding  replicating_portfolio_def stock_portfolio_def adapt_stoch_proc_def by auto\n      hence \"prices Mkt asset n \\<in> borel_measurable (nat_filtration n)\" using stock_filtration\n        stoch_proc_subalg_nat_filt geom_rand_walk_borel_adapted\n        measurable_from_subalg[of \"nat_filtration n\" \"G n\" \"prices Mkt asset n\" borel]\n        unfolding adapt_stoch_proc_def by auto\n      thus \"finite (prices Mkt asset n ` space M)\" using nat_filtration_vimage_finite[of \"prices Mkt asset n\"] by simp\n    qed\n    show \"\\<forall>n. \\<forall>asset\\<in>support_set pf. finite (pf asset n ` space M)\"\n    proof (intro allI ballI)\n      fix n\n      fix asset\n      assume \"asset \\<in> support_set pf\"\n      hence \"pf asset n \\<in> borel_measurable (G n)\" using pfprop predict_imp_adapt[of \"pf asset\"]\n        unfolding replicating_portfolio_def trading_strategy_def adapt_stoch_proc_def by auto\n      hence \"pf asset n \\<in> borel_measurable (nat_filtration n)\" using stock_filtration\n        stoch_proc_subalg_nat_filt geom_rand_walk_borel_adapted\n        measurable_from_subalg[of \"nat_filtration n\" \"G n\" \"pf asset n\" borel]\n        unfolding adapt_stoch_proc_def by auto\n      thus \"finite (pf asset n ` space M)\" using nat_filtration_vimage_finite[of \"pf asset n\"] by simp\n    qed\n  qed\n  moreover have \"integral\\<^sup>L N dpf =\n    (\\<Sum> w\\<in> range (pseudo_proj_True matur). (prod (prob_component q w) {0..<matur}) * (dpf w))\"\n  proof (rule infinite_cts_filtration.expect_prob_comp)\n    show \"infinite_cts_filtration q N nat_filtration\" using  assms  pslt psgt\n        bernoulli_nat_filtration unfolding q_def using gt_param lt_param CRR_viable N_def by auto\n    have \"dpf \\<in> borel_measurable (G matur)\" using assms discounted_measurable[of pyf \"G matur\"]\n      unfolding dpf_def by simp\n    thus \"dpf \\<in> borel_measurable (nat_filtration matur)\" using stock_filtration\n        stoch_proc_subalg_nat_filt geom_rand_walk_borel_adapted\n        measurable_from_subalg[of \"nat_filtration matur\" \"G matur\" dpf]\n      unfolding adapt_stoch_proc_def by auto\n  qed\n  ultimately show ?thesis unfolding dpf_def q_def 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/DiscretePricing/CRR_Model.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8438951025545427, "lm_q2_score": 0.8333246015211009, "lm_q1q2_score": 0.7032385500618729}}
{"text": "(*  Title:      HOL/Types_To_Sets/Examples/Linear_Algebra_On.thy\n    Author:     Fabian Immler, TU M\u00fcnchen\n*)\ntheory Linear_Algebra_On\n  imports\n    \"Prerequisites\"\n    \"../Types_To_Sets\"\n    Linear_Algebra_On_With\nbegin\n\nsubsection \\<open>Rewrite rules to make \\<open>ab_group_add\\<close> operations implicit.\\<close>\n\nnamed_theorems implicit_ab_group_add\n\nlemmas [implicit_ab_group_add] = sum_with[symmetric]\n\nlemma semigroup_add_on_with_eq[implicit_ab_group_add]:\n  \"semigroup_add_on_with S ((+)::_::semigroup_add \\<Rightarrow> _) \\<longleftrightarrow> (\\<forall>a\\<in>S. \\<forall>b\\<in>S. a + b \\<in> S)\"\n  by (simp add: semigroup_add_on_with_Ball_def ac_simps)\n\nlemma ab_semigroup_add_on_with_eq[implicit_ab_group_add]:\n  \"ab_semigroup_add_on_with S ((+)::_::ab_semigroup_add \\<Rightarrow> _) = semigroup_add_on_with S (+)\"\n  unfolding ab_semigroup_add_on_with_Ball_def\n  by (simp add: semigroup_add_on_with_eq ac_simps)\n\nlemma comm_monoid_add_on_with_eq[implicit_ab_group_add]:\n  \"comm_monoid_add_on_with S ((+)::_::comm_monoid_add \\<Rightarrow> _) 0 \\<longleftrightarrow> semigroup_add_on_with S (+) \\<and> 0 \\<in> S\"\n  unfolding comm_monoid_add_on_with_Ball_def\n  by (simp add: ab_semigroup_add_on_with_eq ac_simps)\n\nlemma ab_group_add_on_with[implicit_ab_group_add]:\n  \"ab_group_add_on_with S ((+)::_::ab_group_add \\<Rightarrow> _) 0 (-) uminus \\<longleftrightarrow>\n    comm_monoid_add_on_with S (+) 0 \\<and> (\\<forall>a\\<in>S. -a\\<in>S)\"\n  unfolding ab_group_add_on_with_Ball_def\n  by simp\n\nsubsection \\<open>Definitions \\<^emph>\\<open>on\\<close> carrier set\\<close>\n\nlocale module_on =\n  fixes S and scale :: \"'a::comm_ring_1 \\<Rightarrow> 'b::ab_group_add \\<Rightarrow> 'b\" (infixr \"*s\" 75)\n  assumes scale_right_distrib_on [algebra_simps]: \"x \\<in> S \\<Longrightarrow> y \\<in> S \\<Longrightarrow> a *s (x + y) = a *s x + a *s y\"\n    and scale_left_distrib_on [algebra_simps]: \"x \\<in> S \\<Longrightarrow> (a + b) *s x = a *s x + b *s x\"\n    and scale_scale_on [simp]: \"x \\<in> S \\<Longrightarrow> a *s (b *s x) = (a * b) *s x\"\n    and scale_one_on [simp]: \"x \\<in> S \\<Longrightarrow> 1 *s x = x\"\n    and mem_add: \"x \\<in> S \\<Longrightarrow> y \\<in> S \\<Longrightarrow> x + y \\<in> S\"\n    and mem_zero: \"0 \\<in> S\"\n    and mem_scale: \"x \\<in> S \\<Longrightarrow> a *s x \\<in> S\"\nbegin\n\nlemma S_ne: \"S \\<noteq> {}\" using mem_zero by auto\n\nlemma scale_minus_left_on: \"scale (- a) x = - scale a x\" if \"x \\<in> S\"\n  by (metis add_cancel_right_right scale_left_distrib_on neg_eq_iff_add_eq_0 that)\n\nlemma mem_uminus: \"x \\<in> S \\<Longrightarrow> -x \\<in> S\"\n  by (metis mem_scale scale_minus_left_on scale_one_on)\n\ndefinition subspace :: \"'b set \\<Rightarrow> bool\"\n  where subspace_on_def: \"subspace T \\<longleftrightarrow> 0 \\<in> T \\<and> (\\<forall>x\\<in>T. \\<forall>y\\<in>T. x + y \\<in> T) \\<and> (\\<forall>c. \\<forall>x\\<in>T. c *s x \\<in> T)\"\n\ndefinition span :: \"'b set \\<Rightarrow> 'b set\"\n  where span_on_def: \"span b = {sum (\\<lambda>a. r a *s  a) t | t r. finite t \\<and> t \\<subseteq> b}\"\n\ndefinition dependent :: \"'b set \\<Rightarrow> bool\"\n  where dependent_on_def: \"dependent s \\<longleftrightarrow> (\\<exists>t u. finite t \\<and> t \\<subseteq> s \\<and> (sum (\\<lambda>v. u v *s v) t = 0 \\<and> (\\<exists>v\\<in>t. u v \\<noteq> 0)))\"\n\nlemma implicit_subspace_with[implicit_ab_group_add]: \"subspace_with (+) 0 (*s) = subspace\"\n  unfolding subspace_on_def subspace_with_def ..\n\nlemma implicit_dependent_with[implicit_ab_group_add]: \"dependent_with (+) 0 (*s) = dependent\"\n  unfolding dependent_on_def dependent_with_def sum_with ..\n\nlemma implicit_span_with[implicit_ab_group_add]: \"span_with (+) 0 (*s) = span\"\n  unfolding span_on_def span_with_def sum_with ..\n\nend\n\nlemma implicit_module_on_with[implicit_ab_group_add]:\n  \"module_on_with S (+) (-) uminus 0 = module_on S\"\nproof (intro ext iffI)\n  fix s::\"'a\\<Rightarrow>'b\\<Rightarrow>'b\" assume \"module_on S s\"\n  then interpret module_on S s .\n  show \"module_on_with S (+) (-) uminus 0 s\"\n    by (auto simp: module_on_with_def implicit_ab_group_add\n        mem_add mem_zero mem_uminus scale_right_distrib_on scale_left_distrib_on mem_scale)\nqed (auto simp: module_on_with_def module_on_def implicit_ab_group_add)\n\nlocale module_pair_on = m1: module_on S1 scale1 +\n                        m2: module_on S2 scale2\n                        for S1:: \"'b::ab_group_add set\" and S2::\"'c::ab_group_add set\"\n                          and scale1::\"'a::comm_ring_1 \\<Rightarrow> _\" and scale2::\"'a \\<Rightarrow> _\"\n\nlemma implicit_module_pair_on_with[implicit_ab_group_add]:\n  \"module_pair_on_with S1 S2 (+) (-) uminus 0 s1 (+) (-) uminus 0 s2 = module_pair_on S1 S2 s1 s2\"\n  unfolding module_pair_on_with_def implicit_module_on_with module_pair_on_def ..\n\nlocale module_hom_on = m1: module_on S1 s1 + m2: module_on S2 s2\n  for S1 :: \"'b::ab_group_add set\" and S2 :: \"'c::ab_group_add set\"\n    and s1 :: \"'a::comm_ring_1 \\<Rightarrow> 'b \\<Rightarrow> 'b\" (infixr \"*a\" 75)\n    and s2 :: \"'a::comm_ring_1 \\<Rightarrow> 'c \\<Rightarrow> 'c\" (infixr \"*b\" 75) +\n  fixes f :: \"'b \\<Rightarrow> 'c\"\n  assumes add: \"\\<And>b1 b2. b1 \\<in> S1 \\<Longrightarrow> b2 \\<in> S1 \\<Longrightarrow> f (b1 + b2) = f b1 + f b2\"\n    and scale: \"\\<And>b. b \\<in> S1 \\<Longrightarrow> f (r *a b) = r *b f b\"\n\nlemma implicit_module_hom_on_with[implicit_ab_group_add]:\n  \"module_hom_on_with S1 S2 (+) (-) uminus 0 s1 (+) (-) uminus 0 s2 = module_hom_on S1 S2 s1 s2\"\n  unfolding module_hom_on_with_def implicit_module_pair_on_with module_hom_on_def module_pair_on_def\n    module_hom_on_axioms_def\n  by (auto intro!: ext)\n\nlocale vector_space_on = module_on S scale\n  for S and scale :: \"'a::field \\<Rightarrow> 'b::ab_group_add \\<Rightarrow> 'b\" (infixr \"*s\" 75)\nbegin\n\ndefinition dim :: \"'b set \\<Rightarrow> nat\"\n  where \"dim V = (if \\<exists>b\\<subseteq>S. \\<not> dependent b \\<and> span b = span V\n    then card (SOME b. b \\<subseteq> S \\<and> \\<not> dependent b \\<and> span b = span V)\n    else 0)\"\n\nlemma implicit_dim_with[implicit_ab_group_add]: \"dim_on_with S (+) 0 (*s) = dim\"\n  unfolding dim_on_with_def dim_def implicit_ab_group_add ..\n\nend\n\nlemma vector_space_on_alt_def: \"vector_space_on S = module_on S\"\n  unfolding vector_space_on_def module_on_def\n  by auto\n\nlemma implicit_vector_space_on_with[implicit_ab_group_add]:\n  \"vector_space_on_with S (+) (-) uminus 0 = vector_space_on S\"\n  unfolding vector_space_on_alt_def vector_space_on_def vector_space_on_with_def implicit_module_on_with ..\n\nlocale linear_on = module_hom_on S1 S2 s1 s2 f\n  for S1 S2 and s1::\"'a::field \\<Rightarrow> 'b \\<Rightarrow> 'b::ab_group_add\"\n    and s2::\"'a::field \\<Rightarrow> 'c \\<Rightarrow> 'c::ab_group_add\"\n    and f\n\nlemma implicit_linear_on_with[implicit_ab_group_add]:\n  \"linear_on_with S1 S2 (+) (-) uminus 0 s1 (+) (-) uminus 0 s2 = linear_on S1 S2 s1 s2\"\n  unfolding linear_on_with_def linear_on_def implicit_module_hom_on_with ..\n\nlocale finite_dimensional_vector_space_on = vector_space_on S scale for S scale +\n  fixes basis :: \"'a set\"\n  assumes finite_Basis: \"finite basis\"\n  and independent_Basis: \"\\<not> dependent basis\"\n  and span_Basis: \"span basis = S\" and basis_subset: \"basis \\<subseteq> S\"\n\nlocale vector_space_pair_on = m1: vector_space_on S1 scale1 +\n  m2: vector_space_on S2 scale2\n  for S1:: \"'b::ab_group_add set\" and S2::\"'c::ab_group_add set\"\n    and scale1::\"'a::field \\<Rightarrow> _\" and scale2::\"'a \\<Rightarrow> _\"\n\nlocale finite_dimensional_vector_space_pair_1_on =\n  vs1: finite_dimensional_vector_space_on S1 scale1 Basis1 +\n  vs2: vector_space_on S2 scale2\n  for S1 S2\n    and scale1::\"'a::field \\<Rightarrow> 'b::ab_group_add \\<Rightarrow> 'b\"\n    and scale2::\"'a::field \\<Rightarrow> 'c::ab_group_add \\<Rightarrow> 'c\"\n    and Basis1\n\nlocale finite_dimensional_vector_space_pair_on =\n  vs1: finite_dimensional_vector_space_on S1 scale1 Basis1 +\n  vs2: finite_dimensional_vector_space_on S2 scale2 Basis2\n  for S1 S2\n    and scale1::\"'a::field \\<Rightarrow> 'b::ab_group_add \\<Rightarrow> 'b\"\n    and scale2::\"'a::field \\<Rightarrow> 'c::ab_group_add \\<Rightarrow> 'c\"\n    and Basis1 Basis2\n\n\nsubsection \\<open>Local Typedef for Subspace\\<close>\n\nlocale local_typedef_module_on = module_on S scale\n  for S and scale::\"'a::comm_ring_1\\<Rightarrow>'b\\<Rightarrow>'b::ab_group_add\" and s::\"'s itself\" +\n  assumes Ex_type_definition_S: \"\\<exists>(Rep::'s \\<Rightarrow> 'b) (Abs::'b \\<Rightarrow> 's). type_definition Rep Abs S\"\nbegin\n\nlemma mem_sum: \"sum f X \\<in> S\" if \"\\<And>x. x \\<in> X \\<Longrightarrow> f x \\<in> S\"\n  using that\n  by (induction X rule: infinite_finite_induct) (auto intro!: mem_zero mem_add)\n\nsublocale local_typedef S \"TYPE('s)\"\n  using Ex_type_definition_S by unfold_locales\n\nsublocale local_typedef_ab_group_add_on_with \"(+)::'b\\<Rightarrow>'b\\<Rightarrow>'b\" \"0::'b\" \"(-)\" uminus S \"TYPE('s)\"\n  using mem_zero mem_add mem_scale[of _ \"-1\"]\n  by unfold_locales (auto simp: scale_minus_left_on)\n\ncontext includes lifting_syntax begin\n\ndefinition scale_S::\"'a \\<Rightarrow> 's \\<Rightarrow> 's\" where \"scale_S = (id ---> rep ---> Abs) scale\"\n\nlemma scale_S_transfer[transfer_rule]: \"((=) ===> cr_S ===> cr_S) scale scale_S\"\n  unfolding scale_S_def\n  by (auto simp: cr_S_def mem_scale intro!: rel_funI)\n\nend\n\nlemma type_module_on_with: \"module_on_with UNIV plus_S minus_S uminus_S (zero_S::'s) scale_S\"\nproof -\n  have \"module_on_with {x. x \\<in> S} (+) (-) uminus 0 scale\"\n    using module_on_axioms\n    by (auto simp: module_on_with_def module_on_def ab_group_add_on_with_Ball_def\n        comm_monoid_add_on_with_Ball_def mem_uminus\n        ab_semigroup_add_on_with_Ball_def semigroup_add_on_with_def)\n  then show ?thesis\n    by transfer'\nqed\n\nlemma UNIV_transfer[transfer_rule]: \"(rel_set cr_S) S UNIV\"\n  by (auto simp: rel_set_def cr_S_def) (metis Abs_inverse)\n\nend\n\ncontext includes lifting_syntax begin\n\nlemma Eps_unique_transfer_lemma:\n  \"f' (Eps (\\<lambda>x. Domainp A x \\<and> f x)) = g' (Eps g)\"\n  if [transfer_rule]: \"right_total A\" \"(A ===> (=)) f g\" \"(A ===> (=)) f' g'\"\n    and holds: \"\\<exists>x. Domainp A x \\<and> f x\"\n    and unique_g: \"\\<And>x y. g x \\<Longrightarrow> g y \\<Longrightarrow> g' x = g' y\"\nproof -\n  define Epsg where \"Epsg = Eps g\"\n  have \"\\<exists>x. g x\"\n    by transfer (simp add: holds)\n  then have \"g Epsg\"\n    unfolding Epsg_def\n    by (rule someI_ex)\n  obtain x where x[transfer_rule]: \"A x Epsg\"\n    by (meson \\<open>right_total A\\<close> right_totalE)\n  then have \"Domainp A x\" by auto\n  from \\<open>g Epsg\\<close>[untransferred] have \"f x\" .\n  from unique_g have unique:\n    \"\\<And>x y. Domainp A x \\<Longrightarrow> Domainp A y \\<Longrightarrow> f x \\<Longrightarrow> f y \\<Longrightarrow> f' x = f' y\"\n    by transfer\n  have \"f' (Eps (\\<lambda>x. Domainp A x \\<and> f x)) = f' x\"\n    apply (rule unique[OF _ \\<open>Domainp A x\\<close> _ \\<open>f x\\<close>])\n    apply (metis (mono_tags, lifting) local.holds someI_ex)\n    apply (metis (mono_tags, lifting) local.holds someI_ex)\n    done\n  show \"f' (SOME x. Domainp A x \\<and> f x) = g' (Eps g)\"\n    using x \\<open>f' (Eps _) = f' x\\<close> Epsg_def\n    using rel_funE that(3) by fastforce\nqed\n\nend\n\nlocale local_typedef_vector_space_on = local_typedef_module_on S scale s + vector_space_on S scale\n  for S and scale::\"'a::field\\<Rightarrow>'b\\<Rightarrow>'b::ab_group_add\" and s::\"'s itself\"\nbegin\n\nlemma type_vector_space_on_with: \"vector_space_on_with UNIV plus_S minus_S uminus_S (zero_S::'s) scale_S\"\n  using type_module_on_with\n  by (auto simp: vector_space_on_with_def)\n\ncontext includes lifting_syntax begin\n\ndefinition dim_S::\"'s set \\<Rightarrow> nat\" where \"dim_S = dim_on_with UNIV plus_S zero_S scale_S\"\n\nlemma transfer_dim[transfer_rule]: \"(rel_set cr_S ===> (=)) dim dim_S\"\nproof (rule rel_funI)\n  fix V V'\n  assume [transfer_rule]: \"rel_set cr_S V V'\"\n  then have subset: \"V \\<subseteq> S\"\n    by (auto simp: rel_set_def cr_S_def)\n  then have \"span V \\<subseteq> S\"\n    by (auto simp: span_on_def intro!: mem_sum mem_scale)\n  note type_dim_eq_card =\n    vector_space.dim_eq_card[var_simplified explicit_ab_group_add, unoverload_type 'd,\n      OF type.ab_group_add_axioms type_vector_space_on_with]\n  have *: \"(\\<exists>b\\<subseteq>UNIV. \\<not> dependent_with plus_S zero_S scale_S b \\<and> span_with plus_S zero_S scale_S b = span_with plus_S zero_S scale_S V') \\<longleftrightarrow>\n    (\\<exists>b\\<subseteq>S. \\<not> local.dependent b \\<and> local.span b = local.span V)\"\n    unfolding subset_iff\n    by transfer (simp add: implicit_ab_group_add Ball_def)\n  have **[symmetric]:\n    \"card (SOME b. Domainp (rel_set cr_S) b \\<and> (\\<not> dependent_with (+) 0 scale b \\<and> span_with (+) 0 scale b = span_with (+) 0 scale V)) =\n      card (SOME b. \\<not> dependent_with plus_S zero_S scale_S b \\<and> span_with plus_S zero_S scale_S b = span_with plus_S zero_S scale_S V')\"\n    if \"b \\<subseteq> S\" \"\\<not>dependent b\" \"span b = span V\" for b\n    apply (rule Eps_unique_transfer_lemma[where f'=card and g'=card])\n    subgoal by (rule right_total_rel_set) (rule transfer_raw)\n    subgoal by transfer_prover\n    subgoal by transfer_prover\n    subgoal using that by (auto simp: implicit_ab_group_add Domainp_set Domainp_cr_S)\n    subgoal premises prems for b c\n    proof -\n      from type_dim_eq_card[of b V'] type_dim_eq_card[of c V'] prems\n      show ?thesis by simp\n    qed\n    done\n  show \"local.dim V = dim_S V'\"\n    unfolding dim_def dim_S_def * dim_on_with_def\n    by (auto simp: ** Domainp_set Domainp_cr_S implicit_ab_group_add subset_eq)\nqed\n\nend\n\n\nend\n\nlocale local_typedef_finite_dimensional_vector_space_on = local_typedef_vector_space_on S scale s +\n  finite_dimensional_vector_space_on S scale Basis\n  for S and scale::\"'a::field\\<Rightarrow>'b\\<Rightarrow>'b::ab_group_add\" and Basis and s::\"'s itself\"\nbegin\n\ndefinition \"Basis_S = Abs ` Basis\"\n\nlemma Basis_S_transfer[transfer_rule]: \"rel_set cr_S Basis Basis_S\"\n  using Abs_inverse rep_inverse basis_subset\n  by (force simp: rel_set_def Basis_S_def cr_S_def)\n\nlemma type_finite_dimensional_vector_space_on_with:\n  \"finite_dimensional_vector_space_on_with UNIV plus_S minus_S uminus_S zero_S scale_S Basis_S\"\nproof -\n  have \"finite Basis_S\" by transfer (rule finite_Basis)\n  moreover have \"\\<not> dependent_with plus_S zero_S scale_S Basis_S\"\n    by transfer (simp add: implicit_dependent_with independent_Basis)\n  moreover have \"span_with plus_S zero_S scale_S Basis_S = UNIV\"\n    by transfer (simp add: implicit_span_with span_Basis)\n  ultimately show ?thesis\n    using type_vector_space_on_with\n    by (auto simp: finite_dimensional_vector_space_on_with_def)\nqed\n\nend\n\nlocale local_typedef_module_pair =\n  lt1: local_typedef_module_on S1 scale1 s +\n  lt2: local_typedef_module_on S2 scale2 t\n  for S1::\"'b::ab_group_add set\" and scale1::\"'a::comm_ring_1 \\<Rightarrow> 'b \\<Rightarrow> 'b\" and s::\"'s itself\"\n    and S2::\"'c::ab_group_add set\" and scale2::\"'a \\<Rightarrow> 'c \\<Rightarrow> 'c\" and t::\"'t itself\"\nbegin\n\nlemma type_module_pair_on_with:\n  \"module_pair_on_with UNIV UNIV lt1.plus_S lt1.minus_S lt1.uminus_S (lt1.zero_S::'s) lt1.scale_S\n  lt2.plus_S lt2.minus_S lt2.uminus_S (lt2.zero_S::'t) lt2.scale_S\"\n  by (simp add: lt1.type_module_on_with lt2.type_module_on_with module_pair_on_with_def)\n\nend\n\nlocale local_typedef_vector_space_pair =\n  local_typedef_module_pair S1 scale1 s S2 scale2 t\n  for S1::\"'b::ab_group_add set\" and scale1::\"'a::field \\<Rightarrow> 'b \\<Rightarrow> 'b\" and s::\"'s itself\"\n    and S2::\"'c::ab_group_add set\" and scale2::\"'a \\<Rightarrow> 'c \\<Rightarrow> 'c\" and t::\"'t itself\"\nbegin\n\nlemma type_vector_space_pair_on_with:\n  \"vector_space_pair_on_with UNIV UNIV lt1.plus_S lt1.minus_S lt1.uminus_S (lt1.zero_S::'s) lt1.scale_S\n  lt2.plus_S lt2.minus_S lt2.uminus_S (lt2.zero_S::'t) lt2.scale_S\"\n  by (simp add: type_module_pair_on_with vector_space_pair_on_with_def)\n\nsublocale lt1: local_typedef_vector_space_on S1 scale1 s by unfold_locales\nsublocale lt2: local_typedef_vector_space_on S2 scale2 t by unfold_locales\n\nend\n\nlocale local_typedef_finite_dimensional_vector_space_pair_1 =\n  lt1: local_typedef_finite_dimensional_vector_space_on S1 scale1 Basis1 s +\n  lt2: local_typedef_vector_space_on S2 scale2 t\n  for S1::\"'b::ab_group_add set\" and scale1::\"'a::field \\<Rightarrow> 'b \\<Rightarrow> 'b\" and Basis1 and s::\"'s itself\"\n    and S2::\"'c::ab_group_add set\" and scale2::\"'a \\<Rightarrow> 'c \\<Rightarrow> 'c\" and t::\"'t itself\"\nbegin\n\nlemma type_finite_dimensional_vector_space_pair_1_on_with:\n  \"finite_dimensional_vector_space_pair_1_on_with UNIV UNIV lt1.plus_S lt1.minus_S lt1.uminus_S (lt1.zero_S::'s) lt1.scale_S lt1.Basis_S\n  lt2.plus_S lt2.minus_S lt2.uminus_S (lt2.zero_S::'t) lt2.scale_S\"\n  by (simp add: finite_dimensional_vector_space_pair_1_on_with_def\n      lt1.type_finite_dimensional_vector_space_on_with lt2.type_vector_space_on_with)\n\nend\n\nlocale local_typedef_finite_dimensional_vector_space_pair =\n  lt1: local_typedef_finite_dimensional_vector_space_on S1 scale1 Basis1 s +\n  lt2: local_typedef_finite_dimensional_vector_space_on S2 scale2 Basis2 t\n  for S1::\"'b::ab_group_add set\" and scale1::\"'a::field \\<Rightarrow> 'b \\<Rightarrow> 'b\" and Basis1 and s::\"'s itself\"\n    and S2::\"'c::ab_group_add set\" and scale2::\"'a \\<Rightarrow> 'c \\<Rightarrow> 'c\" and Basis2 and t::\"'t itself\"\nbegin\n\nlemma type_finite_dimensional_vector_space_pair_on_with:\n  \"finite_dimensional_vector_space_pair_on_with UNIV UNIV lt1.plus_S lt1.minus_S lt1.uminus_S (lt1.zero_S::'s) lt1.scale_S lt1.Basis_S\n  lt2.plus_S lt2.minus_S lt2.uminus_S (lt2.zero_S::'t) lt2.scale_S lt2.Basis_S\"\n  by (simp add: finite_dimensional_vector_space_pair_on_with_def\n      lt1.type_finite_dimensional_vector_space_on_with\n      lt2.type_finite_dimensional_vector_space_on_with)\n\nend\n\n\nsubsection \\<open>Transfer from type-based \\<^theory>\\<open>HOL.Modules\\<close> and \\<^theory>\\<open>HOL.Vector_Spaces\\<close>\\<close>\n\nlemmas [transfer_rule] = right_total_fun_eq_transfer\n  and [transfer_rule del] = vimage_parametric\n\nsubsubsection \\<open>Modules\\<close>\n\ncontext module_on begin\n\ncontext includes lifting_syntax assumes ltd: \"\\<exists>(Rep::'s \\<Rightarrow> 'b) (Abs::'b \\<Rightarrow> 's). type_definition Rep Abs S\" begin\n\ninterpretation local_typedef_module_on S scale \"TYPE('s)\" by unfold_locales fact\n\ntext\\<open>Get theorem names:\\<close>\nprint_locale! module\ntext\\<open>Then replace:\n\\<^verbatim>\\<open>notes[^\"]*\"([^\"]*).*\\<close>\nwith\n\\<^verbatim>\\<open>$1 = module.$1\\<close>\n\\<close>\ntext \\<open>TODO: automate systematic naming!\\<close>\nlemmas_with [var_simplified explicit_ab_group_add,\n    unoverload_type 'd,\n    OF type.ab_group_add_axioms type_module_on_with,\n    untransferred,\n    var_simplified implicit_ab_group_add]:\n    lt_scale_left_commute = module.scale_left_commute\n  and lt_scale_zero_left = module.scale_zero_left\n  and lt_scale_minus_left = module.scale_minus_left\n  and lt_scale_left_diff_distrib = module.scale_left_diff_distrib\n  and lt_scale_sum_left = module.scale_sum_left\n  and lt_scale_zero_right = module.scale_zero_right\n  and lt_scale_minus_right = module.scale_minus_right\n  and lt_scale_right_diff_distrib = module.scale_right_diff_distrib\n  and lt_scale_sum_right = module.scale_sum_right\n  and lt_sum_constant_scale = module.sum_constant_scale\n  and lt_subspace_def = module.subspace_def\n  and lt_subspaceI = module.subspaceI\n  and lt_subspace_single_0 = module.subspace_single_0\n  and lt_subspace_0 = module.subspace_0\n  and lt_subspace_add = module.subspace_add\n  and lt_subspace_scale = module.subspace_scale\n  and lt_subspace_neg = module.subspace_neg\n  and lt_subspace_diff = module.subspace_diff\n  and lt_subspace_sum = module.subspace_sum\n  and lt_subspace_inter = module.subspace_inter\n  and lt_span_explicit = module.span_explicit\n  and lt_span_explicit' = module.span_explicit'\n  and lt_span_finite = module.span_finite\n  and lt_span_induct_alt = module.span_induct_alt\n  and lt_span_mono = module.span_mono\n  and lt_span_base = module.span_base\n  and lt_span_superset = module.span_superset\n  and lt_span_zero = module.span_zero\n  and lt_span_add = module.span_add\n  and lt_span_scale = module.span_scale\n  and lt_subspace_span = module.subspace_span\n  and lt_span_neg = module.span_neg\n  and lt_span_diff = module.span_diff\n  and lt_span_sum = module.span_sum\n  and lt_span_minimal = module.span_minimal\n  and lt_span_unique = module.span_unique\n  and lt_span_subspace_induct = module.span_subspace_induct\n  and lt_span_induct = module.span_induct\n  and lt_span_empty = module.span_empty\n  and lt_span_subspace = module.span_subspace\n  and lt_span_span = module.span_span\n  and lt_span_add_eq = module.span_add_eq\n  and lt_span_add_eq2 = module.span_add_eq2\n  and lt_span_singleton = module.span_singleton\n  and lt_span_Un = module.span_Un\n  and lt_span_insert = module.span_insert\n  and lt_span_breakdown = module.span_breakdown\n  and lt_span_breakdown_eq = module.span_breakdown_eq\n  and lt_span_clauses = module.span_clauses\n  and lt_span_eq_iff = module.span_eq_iff\n  and lt_span_eq = module.span_eq\n  and lt_eq_span_insert_eq = module.eq_span_insert_eq\n  and lt_dependent_explicit = module.dependent_explicit\n  and lt_dependent_mono = module.dependent_mono\n  and lt_independent_mono = module.independent_mono\n  and lt_dependent_zero = module.dependent_zero\n  and lt_independent_empty = module.independent_empty\n  and lt_independent_explicit_module = module.independent_explicit_module\n  and lt_independentD = module.independentD\n  and lt_independent_Union_directed = module.independent_Union_directed\n  and lt_dependent_finite = module.dependent_finite\n  and lt_independentD_alt = module.independentD_alt\n  and lt_independentD_unique = module.independentD_unique\n  and lt_spanning_subset_independent = module.spanning_subset_independent\n  and lt_module_hom_scale_self = module.module_hom_scale_self\n  and lt_module_hom_scale_left = module.module_hom_scale_left\n  and lt_module_hom_id = module.module_hom_id\n  and lt_module_hom_ident = module.module_hom_ident\n  and lt_module_hom_uminus = module.module_hom_uminus\n  and lt_subspace_UNIV = module.subspace_UNIV\n(* should work but don't:\n  and span_def = module.span_def\n  and span_UNIV = module.span_UNIV\n  and lt_span_alt = module.span_alt\n  and dependent_alt = module.dependent_alt\n  and independent_alt = module.independent_alt\n  and unique_representation = module.unique_representation\n  and subspace_Int = module.subspace_Int\n  and subspace_Inter = module.subspace_Inter\n*)\n(* not expected to work:\nand representation_ne_zero = module.representation_ne_zero\nand representation_ne_zero = module.representation_ne_zero\nand finite_representation = module.finite_representation\nand sum_nonzero_representation_eq = module.sum_nonzero_representation_eq\nand sum_representation_eq = module.sum_representation_eq\nand representation_eqI = module.representation_eqI\nand representation_basis = module.representation_basis\nand representation_zero = module.representation_zero\nand representation_diff = module.representation_diff\nand representation_neg = module.representation_neg\nand representation_add = module.representation_add\nand representation_sum = module.representation_sum\nand representation_scale = module.representation_scale\nand representation_extend = module.representation_extend\nend\n*)\n\nend\n\nlemmas_with [cancel_type_definition,\n    OF S_ne,\n    folded subset_iff',\n    simplified pred_fun_def,\n    simplified\\<comment>\\<open>too much?\\<close>]:\n      scale_left_commute = lt_scale_left_commute\n  and scale_zero_left = lt_scale_zero_left\n  and scale_minus_left = lt_scale_minus_left\n  and scale_left_diff_distrib = lt_scale_left_diff_distrib\n  and scale_sum_left = lt_scale_sum_left\n  and scale_zero_right = lt_scale_zero_right\n  and scale_minus_right = lt_scale_minus_right\n  and scale_right_diff_distrib = lt_scale_right_diff_distrib\n  and scale_sum_right = lt_scale_sum_right\n  and sum_constant_scale = lt_sum_constant_scale\n  and subspace_def = lt_subspace_def\n  and subspaceI = lt_subspaceI\n  and subspace_single_0 = lt_subspace_single_0\n  and subspace_0 = lt_subspace_0\n  and subspace_add = lt_subspace_add\n  and subspace_scale = lt_subspace_scale\n  and subspace_neg = lt_subspace_neg\n  and subspace_diff = lt_subspace_diff\n  and subspace_sum = lt_subspace_sum\n  and subspace_inter = lt_subspace_inter\n  and span_explicit = lt_span_explicit\n  and span_explicit' = lt_span_explicit'\n  and span_finite = lt_span_finite\n  and span_induct_alt[consumes 1, case_names base step, induct set : span] = lt_span_induct_alt\n  and span_mono = lt_span_mono\n  and span_base = lt_span_base\n  and span_superset = lt_span_superset\n  and span_zero = lt_span_zero\n  and span_add = lt_span_add\n  and span_scale = lt_span_scale\n  and subspace_span = lt_subspace_span\n  and span_neg = lt_span_neg\n  and span_diff = lt_span_diff\n  and span_sum = lt_span_sum\n  and span_minimal = lt_span_minimal\n  and span_unique = lt_span_unique\n  and span_subspace_induct[consumes 2] = lt_span_subspace_induct\n  and span_induct[consumes 1, case_names base step, induct set : span] = lt_span_induct\n  and span_empty = lt_span_empty\n  and span_subspace = lt_span_subspace\n  and span_span = lt_span_span\n  and span_add_eq = lt_span_add_eq\n  and span_add_eq2 = lt_span_add_eq2\n  and span_singleton = lt_span_singleton\n  and span_Un = lt_span_Un\n  and span_insert = lt_span_insert\n  and span_breakdown = lt_span_breakdown\n  and span_breakdown_eq = lt_span_breakdown_eq\n  and span_clauses = lt_span_clauses\n  and span_eq_iff = lt_span_eq_iff\n  and span_eq = lt_span_eq\n  and eq_span_insert_eq = lt_eq_span_insert_eq\n  and dependent_explicit = lt_dependent_explicit\n  and dependent_mono = lt_dependent_mono\n  and independent_mono = lt_independent_mono\n  and dependent_zero = lt_dependent_zero\n  and independent_empty = lt_independent_empty\n  and independent_explicit_module = lt_independent_explicit_module\n  and independentD = lt_independentD\n  and independent_Union_directed = lt_independent_Union_directed\n  and dependent_finite = lt_dependent_finite\n  and independentD_alt = lt_independentD_alt\n  and independentD_unique = lt_independentD_unique\n  and spanning_subset_independent = lt_spanning_subset_independent\n  and module_hom_scale_self = lt_module_hom_scale_self\n  and module_hom_scale_left = lt_module_hom_scale_left\n  and module_hom_id = lt_module_hom_id\n  and module_hom_ident = lt_module_hom_ident\n  and module_hom_uminus = lt_module_hom_uminus\n  and subspace_UNIV = lt_subspace_UNIV\nend\n\nsubsubsection \\<open>Vector Spaces\\<close>\n\ncontext vector_space_on begin\n\ncontext includes lifting_syntax assumes \"\\<exists>(Rep::'s \\<Rightarrow> 'b) (Abs::'b \\<Rightarrow> 's). type_definition Rep Abs S\" begin\n\ninterpretation local_typedef_vector_space_on S scale \"TYPE('s)\" by unfold_locales fact\n\nlemmas_with [var_simplified explicit_ab_group_add,\n    unoverload_type 'd,\n    OF type.ab_group_add_axioms type_vector_space_on_with,\n    folded dim_S_def,\n    untransferred,\n    var_simplified implicit_ab_group_add]:\n    lt_linear_id = vector_space.linear_id\nand lt_linear_ident = vector_space.linear_ident\nand lt_linear_scale_self = vector_space.linear_scale_self\nand lt_linear_scale_left = vector_space.linear_scale_left\nand lt_linear_uminus = vector_space.linear_uminus\nand lt_linear_imp_scale[\"consumes\" - 1, \"case_names\" \"1\"] = vector_space.linear_imp_scale\nand lt_scale_eq_0_iff = vector_space.scale_eq_0_iff\nand lt_scale_left_imp_eq = vector_space.scale_left_imp_eq\nand lt_scale_right_imp_eq = vector_space.scale_right_imp_eq\nand lt_scale_cancel_left = vector_space.scale_cancel_left\nand lt_scale_cancel_right = vector_space.scale_cancel_right\nand lt_injective_scale = vector_space.injective_scale\nand lt_dependent_def = vector_space.dependent_def\nand lt_dependent_single = vector_space.dependent_single\nand lt_in_span_insert = vector_space.in_span_insert\nand lt_dependent_insertD = vector_space.dependent_insertD\nand lt_independent_insertI = vector_space.independent_insertI\nand lt_independent_insert = vector_space.independent_insert\nand lt_maximal_independent_subset_extend[\"consumes\" - 1, \"case_names\" \"1\"] = vector_space.maximal_independent_subset_extend\nand lt_maximal_independent_subset[\"consumes\" - 1, \"case_names\" \"1\"] = vector_space.maximal_independent_subset\nand lt_in_span_delete = vector_space.in_span_delete\nand lt_span_redundant = vector_space.span_redundant\nand lt_span_trans = vector_space.span_trans\nand lt_span_insert_0 = vector_space.span_insert_0\nand lt_span_delete_0 = vector_space.span_delete_0\nand lt_span_image_scale = vector_space.span_image_scale\nand lt_exchange_lemma = vector_space.exchange_lemma\nand lt_independent_span_bound = vector_space.independent_span_bound\nand lt_independent_explicit_finite_subsets = vector_space.independent_explicit_finite_subsets\nand lt_independent_if_scalars_zero = vector_space.independent_if_scalars_zero\nand lt_subspace_sums = vector_space.subspace_sums\nand lt_dim_unique = vector_space.dim_unique\nand lt_dim_eq_card = vector_space.dim_eq_card\nand lt_basis_card_eq_dim = vector_space.basis_card_eq_dim\nand lt_basis_exists = vector_space.basis_exists\nand lt_dim_eq_card_independent = vector_space.dim_eq_card_independent\nand lt_dim_span = vector_space.dim_span\nand lt_dim_span_eq_card_independent = vector_space.dim_span_eq_card_independent\nand lt_dim_le_card = vector_space.dim_le_card\nand lt_span_eq_dim = vector_space.span_eq_dim\nand lt_dim_le_card' = vector_space.dim_le_card'\nand lt_span_card_ge_dim = vector_space.span_card_ge_dim\nand lt_dim_with = vector_space.dim_with\n(* should work but don't:v\n\nand lt_bij_if_span_eq_span_bases = vector_space.bij_if_span_eq_span_bases\n*)\n(* not expected to work:\nand lt_dim_def = vector_space.dim_def\nand lt_extend_basis_superset = vector_space.extend_basis_superset\nand lt_independent_extend_basis = vector_space.independent_extend_basis\nand lt_span_extend_basis = vector_space.span_extend_basis\n*)\n\nend\n\nlemmas_with [cancel_type_definition,\n    OF S_ne,\n    folded subset_iff',\n    simplified pred_fun_def,\n    simplified\\<comment>\\<open>too much?\\<close>]:\n    linear_id = lt_linear_id\nand linear_ident = lt_linear_ident\nand linear_scale_self = lt_linear_scale_self\nand linear_scale_left = lt_linear_scale_left\nand linear_uminus = lt_linear_uminus\nand linear_imp_scale[\"consumes\" - 1, \"case_names\" \"1\"] = lt_linear_imp_scale\nand scale_eq_0_iff = lt_scale_eq_0_iff\nand scale_left_imp_eq = lt_scale_left_imp_eq\nand scale_right_imp_eq = lt_scale_right_imp_eq\nand scale_cancel_left = lt_scale_cancel_left\nand scale_cancel_right = lt_scale_cancel_right\nand dependent_def = lt_dependent_def\nand dependent_single = lt_dependent_single\nand in_span_insert = lt_in_span_insert\nand dependent_insertD = lt_dependent_insertD\nand independent_insertI = lt_independent_insertI\nand independent_insert = lt_independent_insert\nand maximal_independent_subset_extend[\"consumes\" - 1, \"case_names\" \"1\"] = lt_maximal_independent_subset_extend\nand maximal_independent_subset[\"consumes\" - 1, \"case_names\" \"1\"] = lt_maximal_independent_subset\nand in_span_delete = lt_in_span_delete\nand span_redundant = lt_span_redundant\nand span_trans = lt_span_trans\nand span_insert_0 = lt_span_insert_0\nand span_delete_0 = lt_span_delete_0\nand span_image_scale = lt_span_image_scale\nand exchange_lemma = lt_exchange_lemma\nand independent_span_bound = lt_independent_span_bound\nand independent_explicit_finite_subsets = lt_independent_explicit_finite_subsets\nand independent_if_scalars_zero = lt_independent_if_scalars_zero\nand subspace_sums = lt_subspace_sums\nand dim_unique = lt_dim_unique\nand dim_eq_card = lt_dim_eq_card\nand basis_card_eq_dim = lt_basis_card_eq_dim\nand basis_exists[\"consumes\" - 1, \"case_names\" \"1\"] = lt_basis_exists\nand dim_eq_card_independent = lt_dim_eq_card_independent\nand dim_span = lt_dim_span\nand dim_span_eq_card_independent = lt_dim_span_eq_card_independent\nand dim_le_card = lt_dim_le_card\nand span_eq_dim = lt_span_eq_dim\nand dim_le_card' = lt_dim_le_card'\nand span_card_ge_dim = lt_span_card_ge_dim\nand dim_with = lt_dim_with\n\nend\n\nsubsubsection \\<open>Finite Dimensional Vector Spaces\\<close>\n\ncontext finite_dimensional_vector_space_on begin\n\ncontext includes lifting_syntax assumes \"\\<exists>(Rep::'s \\<Rightarrow> 'a) (Abs::'a \\<Rightarrow> 's). type_definition Rep Abs S\" begin\n\ninterpretation local_typedef_finite_dimensional_vector_space_on S scale basis \"TYPE('s)\" by unfold_locales fact\n\nlemmas_with [var_simplified explicit_ab_group_add,\n    unoverload_type 'd,\n    OF type.ab_group_add_axioms type_finite_dimensional_vector_space_on_with,\n    folded dim_S_def,\n    untransferred,\n    var_simplified implicit_ab_group_add]:\n     lt_finiteI_independent = finite_dimensional_vector_space.finiteI_independent\nand  lt_dim_empty = finite_dimensional_vector_space.dim_empty\nand  lt_dim_insert = finite_dimensional_vector_space.dim_insert\nand  lt_dim_singleton = finite_dimensional_vector_space.dim_singleton\nand  lt_choose_subspace_of_subspace[\"consumes\" - 1, \"case_names\" \"1\"] = finite_dimensional_vector_space.choose_subspace_of_subspace\nand  lt_basis_subspace_exists[\"consumes\" - 1, \"case_names\" \"1\"] = finite_dimensional_vector_space.basis_subspace_exists\nand  lt_dim_mono = finite_dimensional_vector_space.dim_mono\nand  lt_dim_subset = finite_dimensional_vector_space.dim_subset\nand  lt_dim_eq_0 = finite_dimensional_vector_space.dim_eq_0\nand  lt_dim_UNIV = finite_dimensional_vector_space.dim_UNIV\nand  lt_independent_card_le_dim = finite_dimensional_vector_space.independent_card_le_dim\nand  lt_card_ge_dim_independent = finite_dimensional_vector_space.card_ge_dim_independent\nand  lt_card_le_dim_spanning = finite_dimensional_vector_space.card_le_dim_spanning\nand  lt_card_eq_dim = finite_dimensional_vector_space.card_eq_dim\nand  lt_subspace_dim_equal = finite_dimensional_vector_space.subspace_dim_equal\nand  lt_dim_eq_span = finite_dimensional_vector_space.dim_eq_span\nand  lt_dim_psubset = finite_dimensional_vector_space.dim_psubset\nand  lt_indep_card_eq_dim_span = finite_dimensional_vector_space.indep_card_eq_dim_span\nand  lt_independent_bound_general = finite_dimensional_vector_space.independent_bound_general\nand  lt_independent_explicit = finite_dimensional_vector_space.independent_explicit\nand  lt_dim_sums_Int = finite_dimensional_vector_space.dim_sums_Int\nand  lt_dependent_biggerset_general = finite_dimensional_vector_space.dependent_biggerset_general\nand  lt_subset_le_dim = finite_dimensional_vector_space.subset_le_dim\nand  lt_linear_inj_imp_surj = finite_dimensional_vector_space.linear_inj_imp_surj\nand  lt_linear_surj_imp_inj = finite_dimensional_vector_space.linear_surj_imp_inj\nand  lt_linear_inverse_left = finite_dimensional_vector_space.linear_inverse_left\nand  lt_left_inverse_linear = finite_dimensional_vector_space.left_inverse_linear\nand  lt_right_inverse_linear = finite_dimensional_vector_space.right_inverse_linear\n(* not expected to work:\n     lt_dimension_def = finite_dimensional_vector_space.dimension_def\nand  lt_dim_subset_UNIV = finite_dimensional_vector_space.dim_subset_UNIV\nand  lt_dim_eq_full = finite_dimensional_vector_space.dim_eq_full\nand  lt_inj_linear_imp_inv_linear = finite_dimensional_vector_space.inj_linear_imp_inv_linear\n*)\n\nend\n\nlemmas_with [cancel_type_definition,\n    OF S_ne,\n    folded subset_iff',\n    simplified pred_fun_def,\n    simplified\\<comment>\\<open>too much?\\<close>]:\n     finiteI_independent = lt_finiteI_independent\nand  dim_empty = lt_dim_empty\nand  dim_insert = lt_dim_insert\nand  dim_singleton = lt_dim_singleton\nand  choose_subspace_of_subspace[\"consumes\" - 1, \"case_names\" \"1\"] = lt_choose_subspace_of_subspace\nand  basis_subspace_exists[\"consumes\" - 1, \"case_names\" \"1\"] = lt_basis_subspace_exists\nand  dim_mono = lt_dim_mono\nand  dim_subset = lt_dim_subset\nand  dim_eq_0 = lt_dim_eq_0\nand  dim_UNIV = lt_dim_UNIV\nand  independent_card_le_dim = lt_independent_card_le_dim\nand  card_ge_dim_independent = lt_card_ge_dim_independent\nand  card_le_dim_spanning = lt_card_le_dim_spanning\nand  card_eq_dim = lt_card_eq_dim\nand  subspace_dim_equal = lt_subspace_dim_equal\nand  dim_eq_span = lt_dim_eq_span\nand  dim_psubset = lt_dim_psubset\nand  indep_card_eq_dim_span = lt_indep_card_eq_dim_span\nand  independent_bound_general = lt_independent_bound_general\nand  independent_explicit = lt_independent_explicit\nand  dim_sums_Int = lt_dim_sums_Int\nand  dependent_biggerset_general = lt_dependent_biggerset_general\nand  subset_le_dim = lt_subset_le_dim\nand  linear_inj_imp_surj = lt_linear_inj_imp_surj\nand  linear_surj_imp_inj = lt_linear_surj_imp_inj\nand  linear_inverse_left = lt_linear_inverse_left\nand  left_inverse_linear = lt_left_inverse_linear\nand  right_inverse_linear = lt_right_inverse_linear\n\nend\n\ncontext module_pair_on begin\n\ncontext includes lifting_syntax\n  assumes\n    \"\\<exists>(Rep::'s \\<Rightarrow> 'b) (Abs::'b \\<Rightarrow> 's). type_definition Rep Abs S1\"\n    \"\\<exists>(Rep::'t \\<Rightarrow> 'c) (Abs::'c \\<Rightarrow> 't). type_definition Rep Abs S2\" begin\n\ninterpretation local_typedef_module_pair S1 scale1 \"TYPE('s)\" S2 scale2 \"TYPE('t)\" by unfold_locales fact+\n\nlemmas_with [var_simplified explicit_ab_group_add,\n    unoverload_type 'e 'f,\n  OF lt2.type.ab_group_add_axioms lt1.type.ab_group_add_axioms type_module_pair_on_with,\n  untransferred,\n  var_simplified implicit_ab_group_add]:\n  lt_module_hom_zero = module_pair.module_hom_zero\nand lt_module_hom_add = module_pair.module_hom_add\nand lt_module_hom_sub = module_pair.module_hom_sub\nand lt_module_hom_neg = module_pair.module_hom_neg\nand lt_module_hom_scale = module_pair.module_hom_scale\nand lt_module_hom_compose_scale = module_pair.module_hom_compose_scale\nand lt_module_hom_sum = module_pair.module_hom_sum\nand lt_module_hom_eq_on_span = module_pair.module_hom_eq_on_span\n(* should work, but doesnt\nand lt_bij_module_hom_imp_inv_module_hom = module_pair.bij_module_hom_imp_inv_module_hom[of scale1 scale2]\n*)\n\nend\n\nlemmas_with [cancel_type_definition, OF m1.S_ne,\n  cancel_type_definition, OF m2.S_ne,\n    folded subset_iff' top_set_def,\n    simplified pred_fun_def,\n    simplified\\<comment>\\<open>too much?\\<close>]:\n  module_hom_zero = lt_module_hom_zero\nand module_hom_add = lt_module_hom_add\nand module_hom_sub = lt_module_hom_sub\nand module_hom_neg = lt_module_hom_neg\nand module_hom_scale = lt_module_hom_scale\nand module_hom_compose_scale = lt_module_hom_compose_scale\nand module_hom_sum = lt_module_hom_sum\nand module_hom_eq_on_span = lt_module_hom_eq_on_span\n\nend\n\ncontext vector_space_pair_on begin\n\ncontext includes lifting_syntax\n  notes [transfer_rule del] = Collect_transfer\n  assumes\n    \"\\<exists>(Rep::'s \\<Rightarrow> 'b) (Abs::'b \\<Rightarrow> 's). type_definition Rep Abs S1\"\n    \"\\<exists>(Rep::'t \\<Rightarrow> 'c) (Abs::'c \\<Rightarrow> 't). type_definition Rep Abs S2\" begin\n\ninterpretation local_typedef_vector_space_pair S1 scale1 \"TYPE('s)\" S2 scale2 \"TYPE('t)\" by unfold_locales fact+\n\nlemmas_with [var_simplified explicit_ab_group_add,\n    unoverload_type 'e 'f,\n  OF lt2.type.ab_group_add_axioms lt1.type.ab_group_add_axioms type_vector_space_pair_on_with,\n  folded lt1.dim_S_def lt2.dim_S_def,\n  untransferred,\n  var_simplified implicit_ab_group_add]:\n  lt_linear_0 = vector_space_pair.linear_0\nand lt_linear_add = vector_space_pair.linear_add\nand lt_linear_scale = vector_space_pair.linear_scale\nand lt_linear_neg = vector_space_pair.linear_neg\nand lt_linear_diff = vector_space_pair.linear_diff\nand lt_linear_sum = vector_space_pair.linear_sum\nand lt_linear_inj_on_iff_eq_0 = vector_space_pair.linear_inj_on_iff_eq_0\nand lt_linear_inj_iff_eq_0 = vector_space_pair.linear_inj_iff_eq_0\nand lt_linear_subspace_image = vector_space_pair.linear_subspace_image\nand lt_linear_subspace_vimage = vector_space_pair.linear_subspace_vimage\nand lt_linear_subspace_kernel = vector_space_pair.linear_subspace_kernel\nand lt_linear_span_image = vector_space_pair.linear_span_image\nand lt_linear_dependent_inj_imageD = vector_space_pair.linear_dependent_inj_imageD\nand lt_linear_eq_0_on_span = vector_space_pair.linear_eq_0_on_span\nand lt_linear_independent_injective_image = vector_space_pair.linear_independent_injective_image\nand lt_linear_inj_on_span_independent_image = vector_space_pair.linear_inj_on_span_independent_image\nand lt_linear_inj_on_span_iff_independent_image = vector_space_pair.linear_inj_on_span_iff_independent_image\nand lt_linear_subspace_linear_preimage = vector_space_pair.linear_subspace_linear_preimage\nand lt_linear_spans_image = vector_space_pair.linear_spans_image\nand lt_linear_spanning_surjective_image = vector_space_pair.linear_spanning_surjective_image\nand lt_linear_eq_on_span = vector_space_pair.linear_eq_on_span\nand lt_linear_compose_scale_right = vector_space_pair.linear_compose_scale_right\nand lt_linear_compose_add = vector_space_pair.linear_compose_add\nand lt_linear_zero = vector_space_pair.linear_zero\nand lt_linear_compose_sub = vector_space_pair.linear_compose_sub\nand lt_linear_compose_neg = vector_space_pair.linear_compose_neg\nand lt_linear_compose_scale = vector_space_pair.linear_compose_scale\nand lt_linear_indep_image_lemma = vector_space_pair.linear_indep_image_lemma\nand lt_linear_eq_on = vector_space_pair.linear_eq_on\nand lt_linear_compose_sum = vector_space_pair.linear_compose_sum\nand lt_linear_independent_extend_subspace = vector_space_pair.linear_independent_extend_subspace\nand lt_linear_independent_extend = vector_space_pair.linear_independent_extend\nand lt_linear_exists_left_inverse_on = vector_space_pair.linear_exists_left_inverse_on\nand lt_linear_exists_right_inverse_on = vector_space_pair.linear_exists_right_inverse_on\nand lt_linear_inj_on_left_inverse = vector_space_pair.linear_inj_on_left_inverse\nand lt_linear_injective_left_inverse = vector_space_pair.linear_injective_left_inverse\nand lt_linear_surj_right_inverse = vector_space_pair.linear_surj_right_inverse\nand lt_linear_surjective_right_inverse = vector_space_pair.linear_surjective_right_inverse\nand lt_finite_basis_to_basis_subspace_isomorphism = vector_space_pair.finite_basis_to_basis_subspace_isomorphism\n(* should work, but doesnt\n*)\n(* not expected to work:\n  lt_construct_def = vector_space_pair.construct_def\n  lt_construct_cong = vector_space_pair.construct_cong\n  lt_linear_construct = vector_space_pair.linear_construct\n  lt_construct_basis = vector_space_pair.construct_basis\n  lt_construct_outside = vector_space_pair.construct_outside\n  lt_construct_add = vector_space_pair.construct_add\n  lt_construct_scale = vector_space_pair.construct_scale\n  lt_construct_in_span = vector_space_pair.construct_in_span\n  lt_in_span_in_range_construct = vector_space_pair.in_span_in_range_construct\n  lt_range_construct_eq_span = vector_space_pair.range_construct_eq_span\n*)\nend\n\nlemmas_with [cancel_type_definition, OF m1.S_ne,\n    cancel_type_definition, OF m2.S_ne,\n    folded subset_iff' top_set_def,\n    simplified pred_fun_def,\n    simplified\\<comment>\\<open>too much?\\<close>]:\n  linear_0 = lt_linear_0\n  and linear_add = lt_linear_add\n  and linear_scale = lt_linear_scale\n  and linear_neg = lt_linear_neg\n  and linear_diff = lt_linear_diff\n  and linear_sum = lt_linear_sum\n  and linear_inj_on_iff_eq_0 = lt_linear_inj_on_iff_eq_0\n  and linear_inj_iff_eq_0 = lt_linear_inj_iff_eq_0\n  and linear_subspace_image = lt_linear_subspace_image\n  and linear_subspace_vimage = lt_linear_subspace_vimage\n  and linear_subspace_kernel = lt_linear_subspace_kernel\n  and linear_span_image = lt_linear_span_image\n  and linear_dependent_inj_imageD = lt_linear_dependent_inj_imageD\n  and linear_eq_0_on_span = lt_linear_eq_0_on_span\n  and linear_independent_injective_image = lt_linear_independent_injective_image\n  and linear_inj_on_span_independent_image = lt_linear_inj_on_span_independent_image\n  and linear_inj_on_span_iff_independent_image = lt_linear_inj_on_span_iff_independent_image\n  and linear_subspace_linear_preimage = lt_linear_subspace_linear_preimage\n  and linear_spans_image = lt_linear_spans_image\n  and linear_spanning_surjective_image = lt_linear_spanning_surjective_image\n  and linear_eq_on_span = lt_linear_eq_on_span\n  and linear_compose_scale_right = lt_linear_compose_scale_right\n  and linear_compose_add = lt_linear_compose_add\n  and linear_zero = lt_linear_zero\n  and linear_compose_sub = lt_linear_compose_sub\n  and linear_compose_neg = lt_linear_compose_neg\n  and linear_compose_scale = lt_linear_compose_scale\n  and linear_indep_image_lemma = lt_linear_indep_image_lemma\n  and linear_eq_on = lt_linear_eq_on\n  and linear_compose_sum = lt_linear_compose_sum\n  and linear_independent_extend_subspace = lt_linear_independent_extend_subspace\n  and linear_independent_extend = lt_linear_independent_extend\n  and linear_exists_left_inverse_on = lt_linear_exists_left_inverse_on\n  and linear_exists_right_inverse_on = lt_linear_exists_right_inverse_on\n  and linear_inj_on_left_inverse = lt_linear_inj_on_left_inverse\n  and linear_injective_left_inverse = lt_linear_injective_left_inverse\n  and linear_surj_right_inverse = lt_linear_surj_right_inverse\n  and linear_surjective_right_inverse = lt_linear_surjective_right_inverse\n  and finite_basis_to_basis_subspace_isomorphism = lt_finite_basis_to_basis_subspace_isomorphism\n\nend\n\ncontext finite_dimensional_vector_space_pair_1_on begin\n\ncontext includes lifting_syntax\n  notes [transfer_rule del] = Collect_transfer\n  assumes\n    \"\\<exists>(Rep::'s \\<Rightarrow> 'b) (Abs::'b \\<Rightarrow> 's). type_definition Rep Abs S1\"\n    \"\\<exists>(Rep::'t \\<Rightarrow> 'c) (Abs::'c \\<Rightarrow> 't). type_definition Rep Abs S2\" begin\n\ninterpretation local_typedef_finite_dimensional_vector_space_pair_1 S1 scale1 Basis1 \"TYPE('s)\" S2 scale2 \"TYPE('t)\" by unfold_locales fact+\n\nlemmas_with [var_simplified explicit_ab_group_add,\n    unoverload_type 'e 'f,\n  OF lt2.type.ab_group_add_axioms lt1.type.ab_group_add_axioms type_finite_dimensional_vector_space_pair_1_on_with,\n  folded lt1.dim_S_def lt2.dim_S_def,\n  untransferred,\n  var_simplified implicit_ab_group_add]:\n   lt_dim_image_eq = finite_dimensional_vector_space_pair_1.dim_image_eq\nand lt_dim_image_le = finite_dimensional_vector_space_pair_1.dim_image_le\n\nend\n\nlemmas_with [cancel_type_definition, OF vs1.S_ne,\n    cancel_type_definition, OF vs2.S_ne,\n    folded subset_iff' top_set_def,\n    simplified pred_fun_def,\n    simplified\\<comment>\\<open>too much?\\<close>]:\n  dim_image_eq = lt_dim_image_eq\nand dim_image_le = lt_dim_image_le\n\nend\n\n\ncontext finite_dimensional_vector_space_pair_on begin\n\ncontext includes lifting_syntax\n  notes [transfer_rule del] = Collect_transfer\n  assumes\n    \"\\<exists>(Rep::'s \\<Rightarrow> 'b) (Abs::'b \\<Rightarrow> 's). type_definition Rep Abs S1\"\n    \"\\<exists>(Rep::'t \\<Rightarrow> 'c) (Abs::'c \\<Rightarrow> 't). type_definition Rep Abs S2\" begin\n\ninterpretation local_typedef_finite_dimensional_vector_space_pair S1 scale1 Basis1 \"TYPE('s)\" S2 scale2 Basis2 \"TYPE('t)\" by unfold_locales fact+\n\nlemmas_with [var_simplified explicit_ab_group_add,\n    unoverload_type 'e 'f,\n  OF lt2.type.ab_group_add_axioms lt1.type.ab_group_add_axioms type_finite_dimensional_vector_space_pair_on_with,\n  folded lt1.dim_S_def lt2.dim_S_def,\n  untransferred,\n  var_simplified implicit_ab_group_add]:\nlt_linear_surjective_imp_injective = finite_dimensional_vector_space_pair.linear_surjective_imp_injective\nand lt_linear_injective_imp_surjective = finite_dimensional_vector_space_pair.linear_injective_imp_surjective\nand lt_linear_injective_isomorphism = finite_dimensional_vector_space_pair.linear_injective_isomorphism\nand lt_linear_surjective_isomorphism = finite_dimensional_vector_space_pair.linear_surjective_isomorphism\nand lt_basis_to_basis_subspace_isomorphism = finite_dimensional_vector_space_pair.basis_to_basis_subspace_isomorphism\nand lt_subspace_isomorphism = finite_dimensional_vector_space_pair.subspace_isomorphism\n\nend\n\nlemmas_with [cancel_type_definition, OF vs1.S_ne,\n    cancel_type_definition, OF vs2.S_ne,\n    folded subset_iff' top_set_def,\n    simplified pred_fun_def,\n    simplified\\<comment>\\<open>too much?\\<close>]:\nlinear_surjective_imp_injective = lt_linear_surjective_imp_injective\nand linear_injective_imp_surjective = lt_linear_injective_imp_surjective\nand linear_injective_isomorphism = lt_linear_injective_isomorphism\nand linear_surjective_isomorphism = lt_linear_surjective_isomorphism\nand basis_to_basis_subspace_isomorphism = lt_basis_to_basis_subspace_isomorphism\nand subspace_isomorphism = lt_subspace_isomorphism\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/Types_To_Sets/Examples/Linear_Algebra_On.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8438951104066293, "lm_q2_score": 0.8333245911726382, "lm_q1q2_score": 0.7032385478721929}}
{"text": "(*  Title:    HOL/Library/Periodic_Fun.thy\n    Author:   Manuel Eberl, TU M\u00fcnchen\n*)\n\nsection \\<open>Periodic Functions\\<close>\n\ntheory Periodic_Fun\nimports Complex_MainRLT\nbegin\n\ntext \\<open>\n  A locale for periodic functions. The idea is that one proves $f(x + p) = f(x)$\n  for some period $p$ and gets derived results like $f(x - p) = f(x)$ and $f(x + 2p) = f(x)$\n  for free.\n\n  \\<^term>\\<open>g\\<close> and \\<^term>\\<open>gm\\<close> are ``plus/minus k periods'' functions. \n  \\<^term>\\<open>g1\\<close> and \\<^term>\\<open>gn1\\<close> are ``plus/minus one period'' functions.\n  This is useful e.g. if the period is one; the lemmas one gets are then \n  \\<^term>\\<open>f (x + 1) = f x\\<close> instead of \\<^term>\\<open>f (x + 1 * 1) = f x\\<close> etc.\n\\<close>\nlocale periodic_fun = \n  fixes f :: \"('a :: {ring_1}) \\<Rightarrow> 'b\" and g gm :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a\" and g1 gn1 :: \"'a \\<Rightarrow> 'a\"\n  assumes plus_1: \"f (g1 x) = f x\"\n  assumes periodic_arg_plus_0: \"g x 0 = x\"\n  assumes periodic_arg_plus_distrib: \"g x (of_int (m + n)) = g (g x (of_int n)) (of_int m)\"\n  assumes plus_1_eq: \"g x 1 = g1 x\" and minus_1_eq: \"g x (-1) = gn1 x\" \n          and minus_eq: \"g x (-y) = gm x y\"\nbegin\n\nlemma plus_of_nat: \"f (g x (of_nat n)) = f x\"\n  by (induction n) (insert periodic_arg_plus_distrib[of _ 1 \"int n\" for n], \n                    simp_all add: plus_1 periodic_arg_plus_0 plus_1_eq)\n\nlemma minus_of_nat: \"f (gm x (of_nat n)) = f x\"\nproof -\n  have \"f (g x (- of_nat n)) = f (g (g x (- of_nat n)) (of_nat n))\"\n    by (rule plus_of_nat[symmetric])\n  also have \"\\<dots> = f (g (g x (of_int (- of_nat n))) (of_int (of_nat n)))\" by simp\n  also have \"\\<dots> = f x\" \n    by (subst periodic_arg_plus_distrib [symmetric]) (simp add: periodic_arg_plus_0)\n  finally show ?thesis by (simp add: minus_eq)\nqed\n\nlemma plus_of_int: \"f (g x (of_int n)) = f x\"\n  by (induction n) (simp_all add: plus_of_nat minus_of_nat minus_eq del: of_nat_Suc)\n\nlemma minus_of_int: \"f (gm x (of_int n)) = f x\"\n  using plus_of_int[of x \"of_int (-n)\"] by (simp add: minus_eq)\n\nlemma plus_numeral: \"f (g x (numeral n)) = f x\"\n  by (subst of_nat_numeral[symmetric], subst plus_of_nat) (rule refl)\n\nlemma minus_numeral: \"f (gm x (numeral n)) = f x\"\n  by (subst of_nat_numeral[symmetric], subst minus_of_nat) (rule refl)\n\nlemma minus_1: \"f (gn1 x) = f x\"\n  using minus_of_nat[of x 1] by (simp flip: minus_1_eq minus_eq)\n\nlemmas periodic_simps = plus_of_nat minus_of_nat plus_of_int minus_of_int \n                        plus_numeral minus_numeral plus_1 minus_1\n\nend\n\n\ntext \\<open>\n  Specialised case of the \\<^term>\\<open>periodic_fun\\<close> locale for periods that are not 1.\n  Gives lemmas \\<^term>\\<open>f (x - period) = f x\\<close> etc.\n\\<close>\nlocale periodic_fun_simple = \n  fixes f :: \"('a :: {ring_1}) \\<Rightarrow> 'b\" and period :: 'a\n  assumes plus_period: \"f (x + period) = f x\"\nbegin\nsublocale periodic_fun f \"\\<lambda>z x. z + x * period\" \"\\<lambda>z x. z - x * period\" \n  \"\\<lambda>z. z + period\" \"\\<lambda>z. z - period\"\n  by standard (simp_all add: ring_distribs plus_period)\nend\n\n\ntext \\<open>\n  Specialised case of the \\<^term>\\<open>periodic_fun\\<close> locale for period 1.\n  Gives lemmas \\<^term>\\<open>f (x - 1) = f x\\<close> etc.\n\\<close>\nlocale periodic_fun_simple' = \n  fixes f :: \"('a :: {ring_1}) \\<Rightarrow> 'b\"\n  assumes plus_period: \"f (x + 1) = f x\"\nbegin\nsublocale periodic_fun f \"\\<lambda>z x. z + x\" \"\\<lambda>z x. z - x\" \"\\<lambda>z. z + 1\" \"\\<lambda>z. z - 1\"\n  by standard (simp_all add: ring_distribs plus_period)\n\nlemma of_nat: \"f (of_nat n) = f 0\" using plus_of_nat[of 0 n] by simp\nlemma uminus_of_nat: \"f (-of_nat n) = f 0\" using minus_of_nat[of 0 n] by simp\nlemma of_int: \"f (of_int n) = f 0\" using plus_of_int[of 0 n] by simp\nlemma uminus_of_int: \"f (-of_int n) = f 0\" using minus_of_int[of 0 n] by simp\nlemma of_numeral: \"f (numeral n) = f 0\" using plus_numeral[of 0 n] by simp\nlemma of_neg_numeral: \"f (-numeral n) = f 0\" using minus_numeral[of 0 n] by simp\nlemma of_1: \"f 1 = f 0\" using plus_of_nat[of 0 1] by simp\nlemma of_neg_1: \"f (-1) = f 0\" using minus_of_nat[of 0 1] by simp\n\nlemmas periodic_simps' = \n  of_nat uminus_of_nat of_int uminus_of_int of_numeral of_neg_numeral of_1 of_neg_1\n\nend\n\nlemma sin_plus_pi: \"sin ((z :: 'a :: {real_normed_field,banach}) + of_real pi) = - sin z\"\n  by (simp add: sin_add)\n  \nlemma cos_plus_pi: \"cos ((z :: 'a :: {real_normed_field,banach}) + of_real pi) = - cos z\"\n  by (simp add: cos_add)\n\ninterpretation sin: periodic_fun_simple sin \"2 * of_real pi :: 'a :: {real_normed_field,banach}\"\nproof\n  fix z :: 'a\n  have \"sin (z + 2 * of_real pi) = sin (z + of_real pi + of_real pi)\" by (simp add: ac_simps)\n  also have \"\\<dots> = sin z\" by (simp only: sin_plus_pi) simp\n  finally show \"sin (z + 2 * of_real pi) = sin z\" .\nqed\n\ninterpretation cos: periodic_fun_simple cos \"2 * of_real pi :: 'a :: {real_normed_field,banach}\"\nproof\n  fix z :: 'a\n  have \"cos (z + 2 * of_real pi) = cos (z + of_real pi + of_real pi)\" by (simp add: ac_simps)\n  also have \"\\<dots> = cos z\" by (simp only: cos_plus_pi) simp\n  finally show \"cos (z + 2 * of_real pi) = cos z\" .\nqed\n\ninterpretation tan: periodic_fun_simple tan \"2 * of_real pi :: 'a :: {real_normed_field,banach}\"\n  by standard (simp only: tan_def [abs_def] sin.plus_1 cos.plus_1)\n\ninterpretation cot: periodic_fun_simple cot \"2 * of_real pi :: 'a :: {real_normed_field,banach}\"\n  by standard (simp only: cot_def [abs_def] sin.plus_1 cos.plus_1)\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/Periodic_Fun.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8333245911726382, "lm_q2_score": 0.8438950966654774, "lm_q1q2_score": 0.7032385364213529}}
{"text": "theory ConcreteSemantics10_4_Live_True\n  imports Main \"~~/src/HOL/IMP/Big_Step\" \"~~/src/HOL/IMP/Vars\" \"~~/src/HOL/Library/While_Combinator\"  \nbegin \n\nsubsection \"True Liveness Analysis\"\n\nsubsubsection \"Analysis\"\n\nfun L :: \"com \\<Rightarrow> vname set \\<Rightarrow> vname set\" where\n\"L SKIP X = X\" |\n\"L (x ::= a) X = (if x \\<in> X then vars a \\<union> (X - {x}) else X)\" |\n\"L (c\\<^sub>1;; c\\<^sub>2) X = L c\\<^sub>1 (L c\\<^sub>2 X)\" |\n\"L (IF b THEN c\\<^sub>1 ELSE c\\<^sub>2) X = vars b \\<union> L c\\<^sub>1 X \\<union> L c\\<^sub>2 X\" |\n\"L (WHILE b DO c) X = lfp(\\<lambda>Y. vars b \\<union> X \\<union> L c Y)\"\n\n(*Lemma 10.30.*)\nlemma L_mono: \"mono(L c)\"\nproof-\n  have \"X \\<subseteq> Y \\<Longrightarrow> L c X \\<subseteq> L c Y\" for X Y\n  proof (induction c arbitrary: X Y)\n  case SKIP\n    then show ?case \n      by (simp add: monoI)\n  next\n    case (Assign x1 x2)\n    then show ?case by auto\n  next\n    case (Seq c1 c2)\n    then show ?case \n      by simp\n  next\n    case (If x1 c1 c2)\n    then show ?case by (simp add: subset_iff)\n  next\n    case (While x1 c)\n    show ?case \n    proof(simp, rule lfp_mono)\n      fix Z show \"vars x1 \\<union> X \\<union> L c Z \\<subseteq> vars x1 \\<union> Y \\<union> L c Z\" \n        using While.prems by auto\n    qed\n  qed\n  thus ?thesis \n    by (simp add: monoI)\nqed\n\nlemma mono_union_L:\n  \"mono (\\<lambda>Y. X \\<union> L c Y)\"\n  by (smt L_mono le_iff_sup le_sup_iff monoI mono_Un sup.idem sup.mono)\n\nlemma L_While_unfold: \"L (WHILE b DO c) X = vars b \\<union> X \\<union> L c (L (WHILE b DO c) X)\"\n  apply(metis lfp_unfold[OF mono_union_L] L.simps(5))\n  done\n(*\n 1. lfp (\\<lambda>Y. vars b \\<union> X \\<union> L c Y) = vars b \\<union> X \\<union> L c (lfp (\\<lambda>Y. vars b \\<union> X \\<union> L c Y)) \n*)\n\nlemma L_While_pfp: \"L c (L (WHILE b DO c) X) \\<subseteq> L (WHILE b DO c) X\"\n  using L_While_unfold by blast\n\nlemma L_While_vars: \"vars b \\<subseteq> L (WHILE b DO c) X\"\n  using L_While_unfold by auto\n\nlemma L_While_X: \"X \\<subseteq> L (WHILE b DO c) X\"\n  using L_While_unfold by auto\n\nsubsubsection \"Correctness\"\n(*Lemma 10.31 (Correctness of L).*)\ntheorem L_correct:\n  \"(c,s) \\<Rightarrow> s'  \\<Longrightarrow> s = t on L c X \\<Longrightarrow>\n  \\<exists> t'. (c,t) \\<Rightarrow> t' & s' = t' on X\"\nproof (induction arbitrary: X t rule: big_step_induct)\ncase (Skip s)\n  then show ?case by auto\nnext\n  case (Assign x a s)\n  then show ?case by (auto simp add: ball_Un)\nnext\n  case (Seq c\\<^sub>1 s\\<^sub>1 s\\<^sub>2 c\\<^sub>2 s\\<^sub>3)\n  from Seq.IH(1) Seq.prems obtain t2 where \"(c\\<^sub>1, t) \\<Rightarrow> t2\" and \"s\\<^sub>2 = t2 on L c\\<^sub>2 X\" \n    by simp blast\n  obtain t3 where \"(c\\<^sub>2, t2) \\<Rightarrow> t3\" and \"s\\<^sub>3 = t3 on X\" \n    using Seq.IH(2) \\<open>s\\<^sub>2 = t2 on L c\\<^sub>2 X\\<close> by blast\n  then show ?case \n    using \\<open>(c\\<^sub>1, t) \\<Rightarrow> t2\\<close> by blast\nnext\n  case (IfTrue b s c\\<^sub>1 s' c\\<^sub>2)\n  then have \"s = t on vars b\" and \"s = t on L c\\<^sub>1 X \" by auto\n  have \"bval b t\" \n    using IfTrue.hyps(1) \\<open>s = t on vars b\\<close> bval_eq_if_eq_on_vars by blast\n from IfTrue.IH[OF \\<open>s = t on L c\\<^sub>1 X\\<close>] obtain t' where \"s' = t' on X\"  \"(c\\<^sub>1, t) \\<Rightarrow> t'\" by auto\n  then show ?case \n    using \\<open>bval b t\\<close> by blast\nnext\n  case (IfFalse b s c\\<^sub>2 s' c\\<^sub>1)\n  then have \"s = t on vars b\" and \"s = t on L c\\<^sub>2 X \" by auto\n  have \"\\<not> bval b t\" \n    using IfFalse.hyps(1) \\<open>s = t on vars b\\<close> bval_eq_if_eq_on_vars by blast\n from IfFalse.IH[OF \\<open>s = t on L c\\<^sub>2 X\\<close>] obtain t' where \"s' = t' on X\"  \"(c\\<^sub>2, t) \\<Rightarrow> t'\" by auto\n  then show ?case using \\<open>\\<not> bval b t\\<close> by blast\nnext\n  case (WhileFalse b s c)\n  then have \"~ bval b t\" \n    by (metis L_While_vars bval_eq_if_eq_on_vars subsetD)\n  thus ?case \n    using L_While_X WhileFalse.prems by blast\nnext\n  case (WhileTrue b s\\<^sub>1 c s\\<^sub>2 s\\<^sub>3)\n  let ?w = \"WHILE b DO c\"\n  have \"bval b t\" \n    by (metis L_While_vars WhileTrue.hyps(1) WhileTrue.prems bval_eq_if_eq_on_vars subsetD)\n  then have \"s\\<^sub>1 = t on L c (L ?w X)\" \n    using L_While_pfp WhileTrue.prems by blast\n  obtain t2 where \"(c, t) \\<Rightarrow> t2\" \"s\\<^sub>2 = t2 on L ?w X\" \n    using WhileTrue.IH(1) \\<open>s\\<^sub>1 = t on L c (L (WHILE b DO c) X)\\<close> by blast\n  obtain t3 where \"(?w, t2) \\<Rightarrow> t3\" \"s\\<^sub>3 = t3 on X\" \n    using WhileTrue.IH(2) \\<open>s\\<^sub>2 = t2 on L (WHILE b DO c) X\\<close> by blast\n  then show ?case \n    using \\<open>(c, t) \\<Rightarrow> t2\\<close> \\<open>bval b t\\<close> by blast\nqed\n\nsubsubsection \"Executability\"\n\nlemma L_subset_vars: \"L c X \\<subseteq> rvars c \\<union> X\"\nproof (induction c arbitrary: X)\ncase SKIP\n  then show ?case by auto\nnext\n  case (Assign x1 x2)\n  then show ?case by auto\nnext\n  case (Seq c1 c2)\n  then show ?case by auto\nnext\n  case (If x1 c1 c2)\n  then show ?case by auto\nnext\n  case (While x1 c)\n(*\n1. \\<And>x1 c X. (\\<And>X. L c X \\<subseteq> rvars c \\<union> X) \\<Longrightarrow> L (WHILE x1 DO c) X \\<subseteq> rvars (WHILE x1 DO c) \\<union> X\n*)\n  then have \"lfp (\\<lambda>Y. vars x1 \\<union> X \\<union> L c Y) \\<subseteq> vars x1 \\<union> rvars c \\<union> X\" \n    by (metis Un_subset_iff lfp_lowerbound sup.cobounded2 sup.left_idem sup_assoc sup_left_commute)\n  show ?case \n    by (simp add: \\<open>lfp (\\<lambda>Y. vars x1 \\<union> X \\<union> L c Y) \\<subseteq> vars x1 \\<union> rvars c \\<union> X\\<close>)\nqed\n\n(* Lemma 10.34. *)\nlemma L_While: fixes b c X\nassumes \"finite X\" defines \"f == \\<lambda>Y. vars b \\<union> X \\<union> L c Y\"\nshows \"L (WHILE b DO c) X = while (\\<lambda>Y. f Y \\<noteq> Y) f {}\" (is \"_ = ?r\")\nproof -\n  let ?V = \"vars b \\<union> rvars c \\<union> X\"\n  have \"lfp f = ?r\"\n  proof(rule lfp_while[where C = ?V])\n(* 1. mono f\n 2. \\<And>Xa. Xa \\<subseteq> vars b \\<union> rvars c \\<union> X \\<Longrightarrow> f Xa \\<subseteq> vars b \\<union> rvars c \\<union> X\n 3. finite (vars b \\<union> rvars c \\<union> X)*)\n    show \"mono f\" \n      by (metis (no_types, lifting) L_mono Un_mono f_def le_iff_sup mono_def sup.idem)\n  next\n    fix Xa show \" Xa \\<subseteq> vars b \\<union> rvars c \\<union> X \\<Longrightarrow> f Xa \\<subseteq> vars b \\<union> rvars c \\<union> X\" \n      using L_subset_vars f_def by auto\n  next\n    show \"finite (vars b \\<union> rvars c \\<union> X)\" \n      by (simp add: assms(1))\n  qed\n  thus ?thesis  by (simp add: f_def)\nqed\n\nlemma L_While_set: \"L (WHILE b DO c) (set xs) =\n  (let f = (\\<lambda>Y. vars b \\<union> set xs \\<union> L c Y)\n   in while (\\<lambda>Y. f Y \\<noteq> Y) f {})\"\n  using L_While by auto\n\ntext\\<open>Replace the equation for \\<open>L (WHILE \\<dots>)\\<close> by the executable @{thm[source] L_While_set}:\\<close>\nlemmas [code] = L.simps(1-4) L_While_set\ntext\\<open>Sorry, this syntax is odd.\\<close>\n\ntext\\<open>A test:\\<close>\nlemma \"(let b = Less (N 0) (V ''y''); c = ''y'' ::= V ''x'';; ''x'' ::= V ''z''\n  in L (WHILE b DO c) {''y''}) = {''x'', ''y'', ''z''}\"\n  by eval\n\nsubsubsection \"Limiting the number of iterations\"\n\ntext\\<open>The final parameter is the default value:\\<close>\n\nfun iter :: \"('a \\<Rightarrow> 'a) \\<Rightarrow> nat \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> 'a\" where\n\"iter f 0 p d = d\" |\n\"iter f (Suc n) p d = (if f p = p then p else iter f n (f p) d)\"\n\n(*Lemma 10.32.*)\nlemma lfp_subset_iter:\n  \"\\<lbrakk> mono f; !!X. f X \\<subseteq> f' X; lfp f \\<subseteq> D \\<rbrakk> \\<Longrightarrow> lfp f \\<subseteq> iter f' n A D\"\nproof(induction n arbitrary: A)\ncase 0\n  then show ?case \n    by simp\nnext\n  case (Suc n)\n  then show ?case \n    by (metis ConcreteSemantics10_4_Live_True.iter.simps(2) lfp_lowerbound)\nqed\n\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/ConcreteSemanticsChapter10/ConcreteSemantics10_4_Live_True.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9046505402422644, "lm_q2_score": 0.7772998560157665, "lm_q1q2_score": 0.7031847346748975}}
{"text": "(*\n * Copyright 2014, NICTA\n *\n * This software may be distributed and modified according to the terms of\n * the BSD 2-Clause license. Note that NO WARRANTY is provided.\n * See \"LICENSE_BSD2.txt\" for details.\n *\n * @TAG(NICTA_BSD)\n *)\n\nsection \"Generic Lemmas used in the Word Library\"\n\ntheory HOL_Lemmas\nimports Main\nbegin\n\ndefinition\n  strict_part_mono :: \"'a set \\<Rightarrow> ('a :: order \\<Rightarrow> 'b :: order) \\<Rightarrow> bool\" where\n \"strict_part_mono S f \\<equiv> \\<forall>A\\<in>S. \\<forall>B\\<in>S. A < B \\<longrightarrow> f A < f B\"\n\nlemma strict_part_mono_by_steps:\n  \"strict_part_mono {..n :: nat} f = (n \\<noteq> 0 \\<longrightarrow> f (n - 1) < f n \\<and> strict_part_mono {.. n - 1} f)\"\n  apply (cases n; simp add: strict_part_mono_def)\n  apply (safe; clarsimp)\n  apply (case_tac \"B = Suc nat\"; simp)\n  apply (case_tac \"A = nat\"; clarsimp)\n  apply (erule order_less_trans [rotated])\n  apply simp\n  done\n\nlemma strict_part_mono_singleton[simp]:\n  \"strict_part_mono {x} f\"\n  by (simp add: strict_part_mono_def)\n\nlemma strict_part_mono_lt:\n  \"\\<lbrakk> x < f 0; strict_part_mono {.. n :: nat} f \\<rbrakk> \\<Longrightarrow> \\<forall>m \\<le> n. x < f m\"\n  by (metis atMost_iff le_0_eq le_cases neq0_conv order.strict_trans strict_part_mono_def)\n\nlemma strict_part_mono_reverseE:\n  \"\\<lbrakk> f n \\<le> f m; strict_part_mono {.. N :: nat} f; n \\<le> N \\<rbrakk> \\<Longrightarrow> n \\<le> m\"\n  by (rule ccontr) (fastforce simp: linorder_not_le strict_part_mono_def)\n\nlemma takeWhile_take_has_property:\n  \"n \\<le> length (takeWhile P xs) \\<Longrightarrow> \\<forall>x \\<in> set (take n xs). P x\"\n  by (induct xs arbitrary: n; simp split: if_split_asm) (case_tac n, simp_all)\n\nlemma takeWhile_take_has_property_nth:\n  \"\\<lbrakk> n < length (takeWhile P xs) \\<rbrakk> \\<Longrightarrow> P (xs ! n)\"\n  by (induct xs arbitrary: n; simp split: if_split_asm) (case_tac n, simp_all)\n\nlemma takeWhile_replicate:\n  \"takeWhile f (replicate len x) = (if f x then replicate len x else [])\"\n  by (induct_tac len) auto\n\n\n\nlemma takeWhile_replicate_id:\n  \"f x \\<Longrightarrow> takeWhile f (replicate len x) = replicate len x\"\n  by (simp add: takeWhile_replicate)\n\nlemma le_imp_diff_le:\n  \"(j::nat) \\<le> k \\<Longrightarrow> j - n \\<le> k\"\n  by simp\n\nlemma power_sub:\n  fixes a :: nat\n  assumes lt: \"n \\<le> m\"\n  and     av: \"0 < a\"\n  shows \"a ^ (m - n) = a ^ m div a ^ n\"\nproof (subst nat_mult_eq_cancel1 [symmetric])\n  show \"(0::nat) < a ^ n\" using av by simp\nnext\n  from lt obtain q where mv: \"n + q = m\"\n    by (auto simp: le_iff_add)\n\n  have \"a ^ n * (a ^ m div a ^ n) = a ^ m\"\n  proof (subst mult.commute)\n    have \"a ^ m = (a ^ m div a ^ n) * a ^ n + a ^ m mod a ^ n\"\n      by (rule  div_mult_mod_eq [symmetric])\n\n    moreover have \"a ^ m mod a ^ n = 0\"\n      by (subst mod_eq_0_iff, rule exI [where x = \"a ^ q\"],\n      (subst power_add [symmetric] mv)+, rule refl)\n\n    ultimately show \"(a ^ m div a ^ n) * a ^ n = a ^ m\" by simp\n  qed\n\n  then show \"a ^ n * a ^ (m - n) = a ^ n * (a ^ m div a ^ n)\" using lt\n    by (simp add: power_add [symmetric])\nqed\n\n\nlemma union_sub:\n  \"\\<lbrakk>B \\<subseteq> A; C \\<subseteq> B\\<rbrakk> \\<Longrightarrow> (A - B) \\<union> (B - C) = (A - C)\"\n  by fastforce\n\nlemma insert_sub:\n  \"x \\<in> xs \\<Longrightarrow> (insert x (xs - ys)) = (xs - (ys - {x}))\"\n  by blast\n\nlemma ran_upd:\n  \"\\<lbrakk> inj_on f (dom f); f y = Some z \\<rbrakk> \\<Longrightarrow> ran (\\<lambda>x. if x = y then None else f x) = ran f - {z}\"\n  unfolding ran_def\n  apply (rule set_eqI)\n  apply simp\n  by (metis domI inj_on_eq_iff option.sel)\n\nlemma nat_less_power_trans:\n  fixes n :: nat\n  assumes nv: \"n < 2 ^ (m - k)\" \n  and     kv: \"k \\<le> m\"\n  shows \"2 ^ k * n < 2 ^ m\"\nproof (rule order_less_le_trans)\n  show \"2 ^ k * n < 2 ^ k * 2 ^ (m - k)\"\n    by (rule mult_less_mono2 [OF nv zero_less_power]) simp\n    \n  show \"(2::nat) ^ k * 2 ^ (m - k) \\<le> 2 ^ m\" using nv kv\n    by (subst power_add [symmetric]) simp\nqed\n\nlemma nat_le_power_trans:\n  fixes n :: nat\n  shows \"\\<lbrakk>n \\<le> 2 ^ (m - k); k \\<le> m\\<rbrakk> \\<Longrightarrow> 2 ^ k * n \\<le> 2 ^ m\"\n  by (metis le_imp_less_or_eq less_imp_le nat_less_power_trans power_sub split_div_lemma\n            zero_less_numeral zero_less_power)\n  \nlemma x_power_minus_1:\n  fixes x :: \"'a :: {ab_group_add, power, numeral, one}\"\n  shows \"x + (2::'a) ^ n - (1::'a) = x + (2 ^ n - 1)\" by simp\n\nlemma nat_diff_add:\n  fixes i :: nat\n  shows \"\\<lbrakk> i + j = k \\<rbrakk> \\<Longrightarrow> i = k - j\"\n  by arith\n\nlemma pow_2_gt: \"n \\<ge> 2 \\<Longrightarrow> (2::int) < 2 ^ n\"\n  by (induct n) auto\n\nlemma if_apply_def2:\n  \"(if P then F else G) = (\\<lambda>x. (P \\<longrightarrow> F x) \\<and> (\\<not> P \\<longrightarrow> G x))\"\n  by simp\n\nlemma case_bool_If:\n  \"case_bool P Q b = (if b then P else Q)\"\n  by simp\n\nlemma sum_to_zero:\n  \"(a :: 'a :: ring) + b = 0 \\<Longrightarrow> a = (- b)\"\n  by (drule arg_cong[where f=\"\\<lambda> x. x - a\"], simp)\n\nlemma arith_is_1:\n  \"\\<lbrakk> x \\<le> Suc 0; x > 0 \\<rbrakk> \\<Longrightarrow> x = 1\"\n  by arith\n\nlemma if_f:\n  \"(if a then f b else f c) = f (if a then b else c)\"\n  by simp\n\nlemma upt_add_eq_append':\n  assumes \"i \\<le> j\" and \"j \\<le> k\"\n  shows \"[i..<k] = [i..<j] @ [j..<k]\"\n  using assms le_Suc_ex upt_add_eq_append by blast\n\nlemma split_upt_on_n:\n  \"n < m \\<Longrightarrow> [0 ..< m] = [0 ..< n] @ [n] @ [Suc n ..< m]\"\n  by (metis append_Cons append_Nil less_Suc_eq_le less_imp_le_nat upt_add_eq_append'\n            upt_rec zero_less_Suc)\n\nlemma drop_Suc_nth:\n  \"n < length xs \\<Longrightarrow> drop n xs = xs!n # drop (Suc n) xs\"\n  by (simp add: Cons_nth_drop_Suc)\n\nlemma n_less_equal_power_2 [simp]:\n  \"n < 2 ^ n\"\n  by (induct n; simp)\n\nlemma nat_min_simps [simp]:\n  \"(a::nat) \\<le> b \\<Longrightarrow> min b a = a\"\n  \"a \\<le> b \\<Longrightarrow> min a b = a\"\n  by auto\n\nlemma power_sub_int:\n  \"\\<lbrakk> m \\<le> n; 0 < b \\<rbrakk> \\<Longrightarrow> b ^ n div b ^ m = (b ^ (n - m) :: int)\"\n  apply (subgoal_tac \"\\<exists>n'. n = m + n'\")\n   apply (clarsimp simp: power_add)\n  apply (rule exI[where x=\"n - m\"])\n  apply simp\n  done\n\nend\n", "meta": {"author": "pirapira", "repo": "eth-isabelle", "sha": "d0bb02b3e64a2046a7c9670545d21f10bccd7b27", "save_path": "github-repos/isabelle/pirapira-eth-isabelle", "path": "github-repos/isabelle/pirapira-eth-isabelle/eth-isabelle-d0bb02b3e64a2046a7c9670545d21f10bccd7b27/Word_Lib/HOL_Lemmas.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.84594244507642, "lm_q2_score": 0.8311430415844384, "lm_q1q2_score": 0.7030991768061925}}
{"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>\\<open>'a\\<close> 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>\\<open>dual\\<close> and \\<^term>\\<open>undual\\<close> 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>\\<open>dual\\<close> (and \\<^term>\\<open>undual\\<close>) 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": "seL4", "repo": "isabelle", "sha": "e1ab32a3bb41728cd19541063283e37919978a4c", "save_path": "github-repos/isabelle/seL4-isabelle", "path": "github-repos/isabelle/seL4-isabelle/isabelle-e1ab32a3bb41728cd19541063283e37919978a4c/src/HOL/Lattice/Orders.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8459424373085146, "lm_q2_score": 0.8311430415844385, "lm_q1q2_score": 0.7030991703499521}}
{"text": "(* \n  Title: Sup-Lattices and Other Simplifications\n  Author: Georg Struth \n  Maintainer: Georg Struth <g.struth@sheffield.ac.uk> \n*)\n\nsection \\<open>Sup-Lattices and Other Simplifications\\<close>\n\ntheory Sup_Lattice\n  imports  Main \n           \"HOL-Library.Lattice_Syntax\"\n\nbegin\n\ntext \\<open>Some definitions for orderings and lattices in Isabelle could be simpler. The strict order in \nin ord could be defined instead of being axiomatised. The function mono could have been defined on ord\nand not on order---even on a general (di)graph it serves as a morphism. In complete lattices, the \nsupremum---and dually the infimum---suffices to define the other operations (in the Isabelle/HOL-definition\ninfimum, binary supremum and infimum, bottom and top element are axiomatised). This not only increases\nthe number of proof obligations in subclass or sublocale statements, instantiations or interpretations,\nit also complicates situations where suprema are presented faithfully, e.g. mapped onto suprema in \nsome subalgebra, whereas infima in the subalgebra are different from those in the super-structure.\\<close>\n\n\ntext \\<open>It would be even nicer to use a class less-eq which dispenses with the strict order symbol\nin ord. Then one would not have to redefine this symbol in all instantiations or interpretations.\nAt least, it does not carry any proof obligations.\\<close>\n\ncontext ord\nbegin\n\ntext \\<open>ub-set yields the set of all upper bounds of a set; lb-set the set of all lower bounds.\\<close>\n\ndefinition ub_set :: \"'a set \\<Rightarrow> 'a set\" where\n  \"ub_set X = {y. \\<forall>x \\<in> X. x \\<le> y}\"\n\ndefinition lb_set :: \"'a set \\<Rightarrow> 'a set\" where\n  \"lb_set X = {y. \\<forall>x \\<in> X. y \\<le> x}\"\n\nend\n\ndefinition ord_pres :: \"('a::ord \\<Rightarrow> 'b::ord) \\<Rightarrow> bool\" where\n \"ord_pres f = (\\<forall>x y. x \\<le> y \\<longrightarrow> f x \\<le> f y)\"\n\nlemma ord_pres_mono: \n  fixes f :: \"'a::order \\<Rightarrow> 'b::order\"\n  shows \"mono f = ord_pres f\"\n  by (simp add: mono_def ord_pres_def)\n\nclass preorder_lean = ord +\n  assumes preorder_refl: \"x \\<le> x\"\n  and preorder_trans: \"x \\<le> y \\<Longrightarrow> y \\<le> z \\<Longrightarrow> x \\<le> z\"\n\nbegin\n\ndefinition le :: \"'a \\<Rightarrow> 'a \\<Rightarrow> bool\" where\n  \"le x y = (x \\<le> y \\<and> \\<not> (x \\<ge> y))\"\n\nend\n\nsublocale preorder_lean \\<subseteq> prel: preorder \"(\\<le>)\" le\n  by (unfold_locales, auto simp add: le_def preorder_refl preorder_trans)\n \nclass order_lean = preorder_lean +\n  assumes order_antisym: \"x \\<le> y \\<Longrightarrow> x \\<ge> y \\<Longrightarrow> x = y\"\n\nsublocale order_lean \\<subseteq> posl: order \"(\\<le>)\" le\n  by (unfold_locales, simp add: order_antisym)\n\nclass Sup_lattice = order_lean + Sup +\n  assumes Sups_upper: \"x \\<in> X \\<Longrightarrow> x \\<le> \\<Squnion>X\"\n  and Sups_least: \"(\\<And>x. x \\<in> X \\<Longrightarrow> x \\<le> z) \\<Longrightarrow> \\<Squnion>X \\<le> z\"\n\nbegin\n\ndefinition Infs :: \"'a set \\<Rightarrow> 'a\" where\n  \"Infs X =  \\<Squnion>{y. \\<forall>x \\<in> X. y \\<le> x}\"\n\ndefinition sups :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a\" where\n  \"sups x y = \\<Squnion>{x,y}\"\n\ndefinition infs :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a\" where\n  \"infs x y = Infs{x,y}\"\n\ndefinition bots :: 'a where \n  \"bots = \\<Squnion>{}\"\n\ndefinition tops :: 'a where\n  \"tops = Infs{}\"\n\nlemma Infs_prop: \"Infs = Sup \\<circ> lb_set\"\n  unfolding fun_eq_iff by (simp add: Infs_def prel.lb_set_def)\n\nend\n\nclass Inf_lattice = order_lean + Inf +\n  assumes Infi_lower: \"x \\<in> X \\<Longrightarrow> \\<Sqinter>X \\<le> x\"\n  and Infi_greatest: \"(\\<And>x. x \\<in> X \\<Longrightarrow> z \\<le> x) \\<Longrightarrow> z \\<le> \\<Sqinter>X\"\n\nbegin\n\ndefinition Supi :: \"'a set \\<Rightarrow> 'a\" where\n  \"Supi X = \\<Sqinter>{y. \\<forall>x \\<in> X. x \\<le> y}\"\n\ndefinition supi :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a\" where\n  \"supi x y = Supi{x,y}\"\n\ndefinition infi :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a\" where\n  \"infi x y = \\<Sqinter>{x,y}\"\n\ndefinition boti :: 'a where \n  \"boti = Supi{}\"\n\ndefinition topi :: 'a where\n  \"topi = \\<Sqinter>{}\"\n\nlemma Supi_prop: \"Supi = Inf \\<circ> ub_set\"\n  unfolding fun_eq_iff by (simp add: Supi_def prel.ub_set_def)\n\nend\n\nsublocale Inf_lattice \\<subseteq> ldual: Sup_lattice Inf \"(\\<ge>)\"\n  rewrites \"ldual.Infs = Supi\"\n  and \"ldual.infs = supi\"\n  and \"ldual.sups = infi\"\n  and \"ldual.tops = boti\"\n  and \"ldual.bots = topi\"\nproof-\n  show \"class.Sup_lattice Inf (\\<ge>)\"\n    by (unfold_locales, simp_all add: Infi_lower Infi_greatest preorder_trans)\n  then interpret ldual: Sup_lattice Inf \"(\\<ge>)\".\n  show a: \"ldual.Infs = Supi\"\n    unfolding fun_eq_iff by (simp add: ldual.Infs_def Supi_def)\n  show \"ldual.infs = supi\"\n    unfolding fun_eq_iff by (simp add: a ldual.infs_def supi_def)\n  show \"ldual.sups = infi\"\n    unfolding fun_eq_iff by (simp add: ldual.sups_def infi_def) \n  show \"ldual.tops = boti\"\n    by (simp add: a ldual.tops_def boti_def)\n  show \"ldual.bots = topi\"\n    by (simp add: ldual.bots_def topi_def)\nqed\n\nsublocale Sup_lattice \\<subseteq> supclat: complete_lattice Infs Sup_class.Sup infs \"(\\<le>)\" le sups bots tops\n  apply unfold_locales\n  unfolding Infs_def infs_def sups_def bots_def tops_def\n  by (simp_all, auto intro: Sups_least, simp_all add: Sups_upper)\n       \n sublocale Inf_lattice \\<subseteq> infclat: complete_lattice Inf_class.Inf Supi infi \"(\\<le>)\" le supi boti topi\n  by (unfold_locales, simp_all add: ldual.Sups_upper ldual.Sups_least ldual.supclat.Inf_lower ldual.supclat.Inf_greatest)\n\nend\n\n\n\n\n\n\n\n\n\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/Order_Lattice_Props/Sup_Lattice.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8311430478583169, "lm_q2_score": 0.8459424295406088, "lm_q1q2_score": 0.7030991692010512}}
{"text": "\nsection \\<open>Quicksort with function package\\<close>\n\ntheory Quicksort\nimports \"HOL-Library.Multiset\"\nbegin\n\ncontext linorder\nbegin\n\nfun quicksort :: \"'a list \\<Rightarrow> 'a list\" where\n  \"quicksort []     = []\"\n| \"quicksort (x#xs) = quicksort [y\\<leftarrow>xs. \\<not> x\\<le>y] \n                        @ [x] @ \n                      quicksort [y\\<leftarrow>xs. x\\<le>y]\"\n\n\n\nlemma mset_quicksort [simp]:\n  \"mset (quicksort xs) = mset xs\"\napply(induct xs rule: quicksort.induct)\n  apply simp\n  by (simp add: add.commute)\n\nlemma \"[y\\<leftarrow>xs . \\<not> x \\<le> y] = (filter ((>) x) xs)\"\n  by (meson local.leD local.leI) \n\nlemma set_quicksort [simp]: \"set (quicksort xs) = set xs\"\nproof -\n  have \"set_mset (mset (quicksort xs)) = set_mset (mset xs)\"\n    by simp\n  then show ?thesis by (simp only: set_mset_mset)\nqed\n\nlemma sorted_quicksort: \"sorted (quicksort xs)\"\napply(induct xs rule: quicksort.induct)\n  apply simp\n  by (auto simp add: sorted_append not_le less_imp_le)\n\ntheorem sort_quicksort:\n  \"sort = quicksort\"\n  by (rule ext, rule properties_for_sort) \n      (fact mset_quicksort sorted_quicksort)+\n\nend\n\nend\n", "meta": {"author": "LVPGroup", "repo": "fpp", "sha": "7e18377ea2c553bf6e57412727a4f06832d93577", "save_path": "github-repos/isabelle/LVPGroup-fpp", "path": "github-repos/isabelle/LVPGroup-fpp/fpp-7e18377ea2c553bf6e57412727a4f06832d93577/4_ds_algo/Sorting/Quicksort.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970842359877, "lm_q2_score": 0.7981867753392728, "lm_q1q2_score": 0.7030405843945569}}
{"text": "theory ExF011\n  imports Main\nbegin \n  \n   \n  \nlemma \"(\\<not> (\\<exists>x. \\<forall>y. P x y)) \\<longrightarrow> \\<not>(\\<exists>x. \\<exists>y .  \\<not>P x y) \\<longrightarrow> False \" \nproof -\n  {\n    assume a:\"(\\<not> (\\<exists>x. \\<forall>y. P x y))\"\n    {\n      fix aa\n      assume b:\"\\<not>(\\<exists>x. \\<exists>y .  \\<not>P x y)\"\n      {\n        fix bb\n        {\n          assume \"\\<not>P aa bb\"\n          hence \"\\<exists>y. \\<not>P aa y\" by (rule exI)\n          hence \"\\<exists>x. \\<exists>y. \\<not>P x y\" by (rule exI)\n          with b have False by contradiction\n        }\n        hence \"\\<not>\\<not>P aa bb\" by (rule notI)\n        hence \"P aa bb\" by (rule notnotD)\n      }\n      hence \"\\<forall>y. P aa y\" by (rule allI)\n      hence \"\\<exists>x. \\<forall>y. P x y\" by (rule exI)\n      with a have False by contradiction\n    }\n    hence \"\\<not>(\\<exists>x. \\<exists>y .  \\<not>P x y) \\<longrightarrow> False \" 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/FOL/ExF011.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896845856298, "lm_q2_score": 0.7634837635542925, "lm_q1q2_score": 0.7030079738294065}}
{"text": "theory BCIgen imports Main\nbegin\n\nsection \\<open>A toy background theory\\<close> (*skip on first read*)\n\n(*Sets are encoded as characteristic functions/predicates (i.e. functions with a 'bool' codomain)*)\ntype_synonym 'a \\<sigma> = \\<open>'a \\<Rightarrow> bool\\<close>\n\n(*Standard subset relation*)\ndefinition subset::\"'a \\<sigma> \\<Rightarrow> 'a \\<sigma> \\<Rightarrow> bool\" (infixr \"\\<^bold>\\<subseteq>\" 51) \n  where \"A \\<^bold>\\<subseteq> B \\<equiv> \\<forall>x. A x \\<longrightarrow> B x\"\n\n(*The infimum (i.e. big-intersection) of a set of sets*)\ndefinition Infimum:: \"('a \\<sigma>)\\<sigma> \\<Rightarrow> 'a \\<sigma>\" (\"\\<^bold>\\<Inter>\")\n  where \"\\<^bold>\\<Inter>S \\<equiv> \\<lambda>z. (\\<forall>X. S X \\<longrightarrow> X z)\"\n\n(*A set S can be closed under a zero-ary, unary, or binary operation (\\<chi>/0, \\<phi>/1, or \\<xi>/2 resp.)*)\nabbreviation (input) op0_closed::\"'a  \\<Rightarrow> 'a \\<sigma>  \\<Rightarrow> bool\" (\"_-closed\\<^sub>0\") \n  where \"\\<chi>-closed\\<^sub>0 \\<equiv> \\<lambda>S. S \\<chi>\" (*just for illustration, not really useful as a definition *)\ndefinition op1_closed::\"('a \\<Rightarrow> 'a) \\<Rightarrow> 'a \\<sigma> \\<Rightarrow> bool\" (\"_-closed\\<^sub>1\")\n  where \"\\<phi>-closed\\<^sub>1 \\<equiv> \\<lambda>S. \\<forall>x. S x \\<longrightarrow> S(\\<phi> x)\"\ndefinition op2_closed::\"('a \\<Rightarrow> 'a \\<Rightarrow> 'a) \\<Rightarrow> 'a \\<sigma> \\<Rightarrow> bool\" (\"_-closed\\<^sub>2\")\n  where \"\\<xi>-closed\\<^sub>2 \\<equiv> \\<lambda>S. \\<forall>x y. S x \\<and> S y \\<longrightarrow> S(\\<xi> x y)\"\n\n(*Closure under a binary operation can be reduced to closure under a unary operation via partial application*)\nlemma op2_closed_def2: \"\\<xi>-closed\\<^sub>2 = (\\<lambda>S. (\\<forall>x. S x \\<longrightarrow> (\\<xi> x)-closed\\<^sub>1 S))\"\n  unfolding op1_closed_def op2_closed_def by blast\n\n(*Convenient abbreviation to say that the set S is a (sub)algebra wrt. to the operations \\<chi>/0, \\<phi>/1*)\ndefinition \"subAlg \\<chi> \\<phi> \\<equiv> \\<lambda>S. (\\<chi>-closed\\<^sub>0 S) \\<and> (\\<phi>-closed\\<^sub>1 S)\" (*i.e. (\\<chi>-closed\\<^sub>0 S) \\<and> (\\<phi>-closed\\<^sub>1 S)*)\n\n(*The set of elements denoted by terms of the form \\<phi>\\<^sup>n\\<chi>. Let's call them 'inductive(ly generated) sets'*)\ndefinition \"indAlg \\<chi> \\<phi> \\<equiv> \\<^bold>\\<Inter>(subAlg \\<chi> \\<phi>)\"\n\n(*Convenient shorthand for composing unary with binary functions*)\nabbreviation (input) fcomp12::\"('b \\<Rightarrow> 'c) \\<Rightarrow> ('a \\<Rightarrow> 'a \\<Rightarrow> 'b) \\<Rightarrow> ('a \\<Rightarrow> 'a \\<Rightarrow> 'c)\" (infixr \"\\<circ>\\<^sub>1\\<^sub>2\" 75) \n  where \"\\<phi> \\<circ>\\<^sub>1\\<^sub>2 \\<xi> \\<equiv> \\<lambda>x y. \\<phi>(\\<xi> x y)\"\n\n\nsection \\<open>Encoding BCI problem\\<close>\n\n(*For each model, the semantic domain \\<D>\\<^sup>i can be seen as the carrier of an algebra \\<A> = <\\<D>\\<^sup>i,e/0,s/1>*)\ntypedecl i \nconsts e :: \"i\"  (*zero-ary operation*)\n       s :: \"i\\<Rightarrow>i\"  (*unary operation*)\n\n(*The first three axioms axiomatize (via equations!) a binary operation 'f' in terms of 'e' and 's'*)\nabbreviation (input) \"A1 f \\<equiv> \\<forall>x. f x e = s e\"\nabbreviation (input) \"A2 f \\<equiv> \\<forall>y. f e (s y) = s (s (f e y))\"\nabbreviation (input) \"A3 f \\<equiv> \\<forall>x y. f (s x) (s y) = f x (f (s x) y)\"\n\n(*The final two axioms constrain a given set 'd' as a subuniverse (subalgebra) of \\<A> (= <\\<D>\\<^sup>i,e/0,s/1>)*)\nabbreviation (input) \"A4 d \\<equiv> d e\"\nabbreviation (input) \"A5 d \\<equiv> \\<forall>x. d x \\<longrightarrow> d (s x)\"\n\n(*Observe that the last two axioms correspond to the definition of a <e,s>-subalgebra of \\<A>*)\nlemma \"(A4 d \\<and> A5 d) = (subAlg e s) d\"  unfolding  op1_closed_def subAlg_def ..\n\n(*Boolos original problem basically asks whether, for an arbitrary <e,s>-subalgebra 'd', the image under 'f'\n (as axiomatized with A1-A3) of two particular elements (denoted by the terms of the form 's\\<^sup>ne') is in 'd'*)\ntheorem BCI: \"A1 f \\<Longrightarrow> A2 f \\<Longrightarrow> A3 f \\<Longrightarrow> \\<forall>d. (A4 d \\<and> A5 d) \\<longrightarrow> d (f (s(s(s(s e)))) (s(s(s(s e)))))\"\n  (*sledgehammer*) oops (*not solvable automatically yet*)\n\n\nsection \\<open>A generalized BCI problem\\<close>\n\n(*Let us introduce a convenient shorthand notation for the (inductively generated) set N of all elements\n that are denoted by terms of the form s\\<^sup>ne (for some arbitrary n). This is the smallest <e,s>-subalgebra.*)\nabbreviation \"N \\<equiv> indAlg e s\"\n\n(*A natural generalization of Boolos' problem asks whether the image under 'f' of any two elements \n belonging to N (i.e. denoted by terms of the form 's\\<^sup>ne') belongs again to N. In other words, we want\n to find out whether axioms A1-A3 constrain 'f' in such a way that N is closed under 'f'.*)\nlemma BCIgen: \"A1 f \\<and> A2 f \\<and> A3 f \\<longrightarrow> f-closed\\<^sub>2 N\" oops (*no automatic proof...yet*)\n\n(*First of all, note that the axioms A1-A3 don't guarantee that N is closed under the unary\n  operation (f x) for any arbitrary x in the domain...*)\nlemma \"A1 f \\<and> A2 f \\<and> A3 f \\<longrightarrow> (\\<forall>x. (f x)-closed\\<^sub>1 N)\" nitpick oops (*countermodel found*)\n(*...but only for those x that belong in fact to the (inductive) set N...*)\nlemma \"A1 f \\<and> A2 f \\<and> A3 f \\<longrightarrow> (\\<forall>x. N x \\<longrightarrow> (f x)-closed\\<^sub>1 N)\" oops\n(*...or equivalently*)\nlemma \"A1 f \\<and> A2 f \\<and> A3 f \\<longrightarrow> N  \\<^bold>\\<subseteq> (\\<lambda>x. (f x)-closed\\<^sub>1 N)\" oops (*still difficult to prove automatically*)\n\n(*Recall that when we want to show that a set contains an inductively generated set it suffices to show\n  that it is a (sub)algebra wrt. the corresponding signature (the other direction does not hold though!)*)\nlemma \"(subAlg \\<chi> \\<phi>) S \\<longrightarrow> (indAlg \\<chi> \\<phi>) \\<^bold>\\<subseteq> S\" by (metis (full_types) Infimum_def indAlg_def subset_def)\nlemma \"(indAlg \\<chi> \\<phi>) \\<^bold>\\<subseteq> S \\<longrightarrow> (subAlg \\<chi> \\<phi>) S\" nitpick oops (*countermodel*)\n\n(*Thus we see that our result holds if we manage to prove the following (slightly more general) statement:*)\nlemma BCIgen: \"A1 f \\<and> A2 f \\<and> A3 f \\<longrightarrow> (subAlg e s) (\\<lambda>x. (f x)-closed\\<^sub>1 N)\"\n  unfolding subAlg_def apply auto oops (*unfolds definition of subalgebra and obtains subgoals*)\n\n(*which, after unfolding definitions, divides into two subgoals (using minimal sets of assumptions)*)\nlemma BCIgen_base: \"A1 f \\<and> A2 f \\<longrightarrow> (f e)-closed\\<^sub>1 N\" oops (*still not proven automatically*)\nlemma BCIgen_induct: \"A1 f \\<and> A3 f \\<longrightarrow> s-closed\\<^sub>1 (\\<lambda>x. (f x)-closed\\<^sub>1 N)\" oops (*still not proven automatically*)\n\n(*As it happens, proving the two lemmata above requires the following (monomorphic!) definition:*)\ndefinition p:: \"(i \\<Rightarrow> i \\<Rightarrow> i) \\<Rightarrow> i \\<Rightarrow> i \\<Rightarrow> bool\" (*we need to enforce the type for the definition to be useful*)\n  where \"p f \\<equiv> N \\<circ>\\<^sub>1\\<^sub>2 f\" (*\\<lambda>x y. N (f x y)*)\n\n(*We can now prove the 'base' case...*)\nlemma BCIgen_base: \"A1 f \\<and> A2 f \\<longrightarrow> (f e)-closed\\<^sub>1 N\"\n  by (smt (verit) Infimum_def indAlg_def op1_closed_def p_def subAlg_def)\n(*...as well as the 'inductive' case*)\nlemma BCIgen_induct: \"A1 f \\<and> A3 f \\<longrightarrow> s-closed\\<^sub>1 (\\<lambda>x. (f x)-closed\\<^sub>1 N)\"\n  by (smt (verit, best) Infimum_def indAlg_def op1_closed_def p_def subAlg_def)\n\n(*So we can now finally prove what we set out to*)\nlemma BCIgen: \"A1 f \\<and> A2 f \\<and> A3 f \\<longrightarrow> f-closed\\<^sub>2 N\" \n  by (metis (mono_tags, lifting) Infimum_def BCIgen_base indAlg_def BCIgen_induct op2_closed_def2 subAlg_def)\n\n(*Interestingly, ATPs can automatically detect that BCI follows from the (cut) lemma above!*)\ntheorem BCI: \"A1 f \\<and> A2 f \\<and> A3 f \\<longrightarrow> (\\<forall>d. (A4 d \\<and> A5 d) \\<longrightarrow> d (f (s(s(s(s e)))) (s(s(s(s e))))))\"\n  by (smt (z3) BCIgen Infimum_def indAlg_def op1_closed_def op2_closed_def2 subAlg_def)\n\n(*The main benefit of proving Boolos problem automatically via a suitable cut-lemma (BCIgen) is that \n we are now in a position to repeat the previous experiment using other axiom sets (e.g. axiomatizing \n other Ackermann-style functions or hyper-operators). *)\n\nend", "meta": {"author": "davfuenmayor", "repo": "IWIL-2023", "sha": "master", "save_path": "github-repos/isabelle/davfuenmayor-IWIL-2023", "path": "github-repos/isabelle/davfuenmayor-IWIL-2023/IWIL-2023-main/sources/BCIgen.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9173026618464796, "lm_q2_score": 0.7662936430859597, "lm_q1q2_score": 0.702923198558787}}
{"text": "theory Analysis_More\n  imports Ordinary_Differential_Equations.Flow\nbegin\n\n\nsubsection \\<open>Some results about derivatives\\<close>\n\ntext \\<open>Projection of has_vector_derivative onto components.\\<close>\nlemma has_vector_derivative_proj:\n  assumes \"(p has_vector_derivative q t) (at t within D)\"\n  shows \"((\\<lambda>t. p t $ i) has_vector_derivative q t $ i) (at t within D)\"\n  using assms unfolding has_vector_derivative_def has_derivative_def \n  apply (simp add: bounded_linear_scaleR_left)\n  using tendsto_vec_nth by fastforce\n\nlemma has_vderiv_on_proj:\n  assumes \"(p has_vderiv_on q) D\"\n  shows \"((\\<lambda>t. p t $ i) has_vderiv_on (\\<lambda>t. q t $ i)) D\"\n  using assms unfolding has_vderiv_on_def \n  by (simp add: has_vector_derivative_proj)\n\nlemma has_vector_derivative_projI:\n  assumes \"\\<forall>i. ((\\<lambda>t. p t $ i) has_vector_derivative q t $ i) (at t within D)\"\n  shows \"(p has_vector_derivative q t) (at t within D)\"\n  using assms unfolding has_vector_derivative_def has_derivative_def\n  apply (auto simp add: bounded_linear_scaleR_left)\n  by (auto intro: vec_tendstoI)\n\nlemma has_derivative_coords [simp,derivative_intros]:\n  \"((\\<lambda>t. t$i) has_derivative (\\<lambda>t. t$i)) (at x)\"\n  unfolding has_derivative_def by auto\n\nlemma has_vector_derivative_divide[derivative_intros]:\n  fixes a:: \"'a::real_normed_field\"\n  shows \"(f has_vector_derivative x) F \\<Longrightarrow> ((\\<lambda>x. f x / a) has_vector_derivative (x/a)) F\"\n  unfolding divide_inverse by(fact has_vector_derivative_mult_left)\n\nlemma has_derivative_divide[derivative_intros]:\n  fixes a:: \"'a::real_normed_field\"\n  shows \"(f has_derivative g) F \\<Longrightarrow> ((\\<lambda>x. f x / a) has_derivative (\\<lambda>x. g x / a)) F\"\n  unfolding divide_inverse by(fact has_derivative_mult_left)\n\n\ntext \\<open>If the derivative is always 0, then the function is always 0.\\<close>\nlemma mvt_real_eq:\n  fixes p :: \"real \\<Rightarrow> real\"\n  assumes \"\\<forall>t\\<in>{0 .. d}. (p has_derivative q t) (at t within {0 .. d}) \"\n    and \"d \\<ge> 0\"\n    and \"\\<forall>t\\<in>{0 ..<d}. \\<forall>s. q t s = 0\"\n    and \"x \\<in> {0 .. d}\"\n  shows \"p 0 = p x\" \nproof -\n  have \"\\<forall>t\\<in>{0 .. x}. (p has_derivative q t) (at t within {0 .. x})\"\n    using assms \n    by (metis atLeastAtMost_iff atLeastatMost_subset_iff has_derivative_subset less_eq_real_def order_less_le_trans)\n    then show ?thesis\n  using assms\n  using mvt_simple[of 0 x p q]\n  by force\nqed\n\ntext \\<open>If the derivative is always non-negative, then the function is increasing.\\<close>\nlemma mvt_real_ge:\n  fixes p :: \"real \\<Rightarrow>real\"\n assumes \"\\<forall>t\\<in>{0 .. d}. (p has_derivative q t) (at t within {0 .. d}) \"\n  and \"d \\<ge> 0\"\n  and \"\\<forall>t\\<in>{0 ..<d}. \\<forall>s\\<ge>0. q t s \\<ge> 0\"\n  and \"x \\<in> {0 .. d}\"\n  shows \"p 0 \\<le> p x\"\nproof -\n  have \"\\<forall>t\\<in>{0 .. x}. (p has_derivative q t) (at t within {0 .. x})\"\n    using assms \n    by (meson atLeastAtMost_iff atLeastatMost_subset_iff has_derivative_subset in_mono order_refl)\n  then show ?thesis\n  using assms\n  using mvt_simple[of 0 x p q]\n  by (smt atLeastAtMost_iff atLeastLessThan_iff greaterThanLessThan_iff)\nqed\n\ntext \\<open>If the derivative is always non-positive, then the function is decreasing.\\<close>\nlemma mvt_real_le:\n  fixes p :: \"real \\<Rightarrow>real\"\n  assumes \"\\<forall>t\\<in>{0 .. d}. (p has_derivative q t) (at t within {0 .. d}) \"\n    and \"d \\<ge> 0\"\n    and \"\\<forall>t\\<in>{0 ..<d}. \\<forall>s\\<ge>0 . q t s \\<le> 0\"\n    and \"x \\<in> {0 .. d}\"\n  shows \"p 0 \\<ge> p x\"\nproof -\n  have \"\\<forall>t\\<in>{0 .. x}. (p has_derivative q t) (at t within {0 .. x})\"\n    using assms \n    by (meson atLeastAtMost_iff atLeastatMost_subset_iff has_derivative_subset in_mono order_refl)\n  then obtain xa where \"xa\\<in>{0<..<x}\" \" p x - p 0 = q xa (x - 0)\" if \"x>0\"\n    using  mvt_simple[of 0 x p q] \n    using atLeastAtMost_iff by blast\n  then have \"p x \\<le> p 0\" if \"x>0\"\n  using assms \n  by (smt atLeastAtMost_iff atLeastLessThan_iff greaterThanLessThan_iff)\n  then show ?thesis\n    using assms  by fastforce\n  \nqed\n\n\nlemma real_inv_le:\n  fixes p :: \"real \\<Rightarrow> real\" and con :: real\n  assumes \"\\<forall>t\\<in>{-e..d+e}. (p has_derivative q t) (at t within {-e..d+e})\"\n    and \"d \\<ge> 0\"\n    and \"\\<forall>t\\<in>{0 ..<d}. (p t = con \\<longrightarrow> q t 1 < 0)\"\n    and \"p 0 \\<le> con \"\n    and \"x \\<in> {0 .. d}\"\n    and \"e > 0\"\n  shows \"p x \\<le> con\" \nproof (rule ccontr) \n  assume a:\" \\<not> p x \\<le> con\"\n  have 1:\"p x > con\"\n    using a by auto\n  have 2:\"\\<forall>t\\<in>{0 .. d}. continuous (at t within {-e<..<d+e}) p\"\n    using assms has_derivative_subset\n    using has_derivative_continuous \n    by (smt atLeastAtMost_iff continuous_within_subset greaterThanLessThan_subseteq_atLeastAtMost_iff greaterThan_iff)\n  have 3:\"\\<forall>t\\<in>{0 .. d}. isCont p t\"\n    apply auto subgoal for t\n      using continuous_within_open[of t \"{-e<..<d+e}\" p]\n      using 2 assms(5) assms(6) by auto\n    done\n  have 4:\"{y. p y = con \\<and> y \\<in> {0 .. x}} \\<noteq> {}\"\n    using IVT[of p 0 con x] using 3 1 assms \n    by auto\n  have 5: \"{y. p y = con \\<and> y \\<in> {0 .. x}} = ({0 .. x} \\<inter> p -` {con})\"\n    by auto\n  have 6: \"closed ({0 .. x} \\<inter> p -` {con})\"\n    using 3 assms(5) apply simp\n    apply (rule continuous_closed_preimage)\n      apply auto\n    by (simp add: continuous_at_imp_continuous_on)\n  have 7: \"compact {0 .. x}\"\n    using assms\n    by blast\n  have 8: \"compact {y. p y = con \\<and> y \\<in> {0 .. x}}\"\n    apply auto\n    using 4 5 6 7 \n    by (smt Collect_cong Int_left_absorb atLeastAtMost_iff compact_Int_closed)\n  obtain t where t1:\"t \\<in> {y. p y = con \\<and> y \\<in> {0 .. x}}\" and t2:\"\\<forall> tt\\<in> {y. p y = con \\<and> y \\<in> {0 .. x}}. tt \\<le>t\"\n    using compact_attains_sup[of \"{y. p y = con \\<and> y \\<in> {0 .. x}}\"] 4 8 \n    by blast\n  have 9:\"t<x\"\n    using t1 1 \n    using leI by fastforce\n  have 10:\"p tt > con\" if \"tt\\<in>{t<..x}\" for tt\n  proof(rule ccontr)\n    assume \"\\<not> con < p tt\"\n    then have not:\"p tt \\<le>con\" by auto\n    have \"\\<exists> t' \\<in> {t<..x}. p t' = con\"\n    proof(cases \"p tt = con\")\n      case True\n      then show ?thesis using that by auto\n    next\n      case False\n      then have \"p tt < con\"\n        using not by auto\n      then have \"{y. p y = con \\<and> y \\<in> {tt .. x}} \\<noteq> {}\"\n        using IVT[of p tt con x] using 3 1 assms that t1 \n        by auto\n      then show ?thesis using that by auto\n    qed\n    then show False using t1 t2 9 \n      using atLeastAtMost_iff greaterThanAtMost_iff by auto\n  qed     \n  have 11:\"(p has_derivative q t) (at t within {-e..d+e})\"\n    using assms t1 by auto\n  then have 12:\"\\<forall>s . q t s = q t 1 * s\"\n    using has_derivative_bounded_linear[of p \"q t\" \"(at t within {-e..d+e})\"]\n    using real_bounded_linear by auto\n  have 13:\"(p has_real_derivative q t 1) (at t within {-e..d+e})\"\n    using 11 12 \n    by (metis has_derivative_imp_has_field_derivative mult.commute)\n  have 14:\"q t 1 < 0\" using t1 assms 9 by auto\n  have 15:\"\\<exists>dd>0. \\<forall>h>0. t + h \\<in> {-e..d+e} \\<longrightarrow> h < dd \\<longrightarrow> p (t + h) < p t\"\n    using has_real_derivative_neg_dec_right[of p \"q t 1\" t \"{-e..d+e}\"] 13 14 \n    by auto\n  then obtain dd where d1:\"\\<forall>h>0. t + h \\<in> {-e..d+e} \\<longrightarrow> h < dd \\<longrightarrow> p (t + h) < p t\" and d2:\"dd>0\" by auto\n  then have 16:\"min (dd/2) (x-t)/2 < dd\" and \"min (dd/2) (x-t)/2 > 0\"\n    using 9 by auto\n  then have 17:\"(t + min (dd/2) (x-t)/2)> t\" \"(t + min (dd/2) (x-t)/2) < x\" \n    apply auto\n    using d2 9\n     by (smt field_sum_of_halves)\n   then have 18:\"p (t + min (dd/2) (x-t)/2) < p t\"\n    using d1 t1 16 assms(5) assms(6) by auto\n  have 19:\"p (t + min (dd/2) (x-t)/2)>con\" using 10 17 by auto\n  show False using 18 19 t1\n    by auto \n  qed\n\n\nlemma real_inv_ge:\n  fixes p :: \"real \\<Rightarrow> real\" and con :: real\n  assumes \"\\<forall>t\\<in>{-e..d+e}. (p has_derivative q t) (at t within {-e..d+e})\"\n    and \"d \\<ge> 0\"\n    and \"\\<forall>t\\<in>{0 ..<d}. (p t = con \\<longrightarrow> q t 1 > 0)\"\n    and \"p 0 \\<ge> con \"\n    and \"x \\<in> {0 .. d}\"\n    and \"e > 0\"\n  shows \"p x \\<ge> con\" \nproof (rule ccontr) \n  assume a:\" \\<not> p x \\<ge> con\"\n  have 1:\"p x < con\"\n    using a by auto\n  have \" \\<forall>t\\<in>{- e..d + e}. (p has_derivative q t) (at t within {- e<..<d + e})\"\n    using assms has_derivative_subset\n    by (smt greaterThanLessThan_subseteq_atLeastAtMost_iff)\n  then have \" \\<forall>t\\<in>{0..d}. (p has_derivative q t) (at t within {- e<..<d + e})\"\n    using assms by auto\n  then have 2:\"\\<forall>t\\<in>{0 .. d}. continuous (at t within {-e<..<d+e}) p\"\n    using has_derivative_continuous \n    by blast\n  have 3:\"\\<forall>t\\<in>{0 .. d}. isCont p t\"\n    apply auto subgoal for t\n      using continuous_within_open[of t \"{-e<..<d+e}\" p]\n      using 2 assms(5) assms(6) by auto\n    done\n  have 4:\"{y. p y = con \\<and> y \\<in> {0 .. x}} \\<noteq> {}\"\n    using IVT2[of p x con 0] using 3 1 assms \n    by auto\n  have 5: \"{y. p y = con \\<and> y \\<in> {0 .. x}} = ({0 .. x} \\<inter> p -` {con})\"\n    by auto\n  have 6: \"closed ({0 .. x} \\<inter> p -` {con})\"\n    using 3 assms(5) apply simp\n    apply (rule continuous_closed_preimage)\n      apply auto\n    by (simp add: continuous_at_imp_continuous_on)\n  have 7: \"compact {0 .. x}\"\n    using assms\n    by blast\n  have 8: \"compact {y. p y = con \\<and> y \\<in> {0 .. x}}\"\n    apply auto\n    using 4 5 6 7 \n    by (smt Collect_cong Int_left_absorb atLeastAtMost_iff compact_Int_closed)\n  obtain t where t1:\"t \\<in> {y. p y = con \\<and> y \\<in> {0 .. x}}\" and t2:\"\\<forall> tt\\<in> {y. p y = con \\<and> y \\<in> {0 .. x}}. tt \\<le>t\"\n    using compact_attains_sup[of \"{y. p y = con \\<and> y \\<in> {0 .. x}}\"] 4 8 \n    by blast\n  have 9:\"t<x\"\n    using t1 1 \n    using leI by fastforce\n  have 10:\"p tt < con\" if \"tt\\<in>{t<..x}\" for tt\n  proof(rule ccontr)\n    assume \"\\<not> con > p tt\"\n    then have not:\"p tt \\<ge> con\" by auto\n    have \"\\<exists> t' \\<in> {t<..x}. p t' = con\"\n    proof(cases \"p tt = con\")\n      case True\n      then show ?thesis using that by auto\n    next\n      case False\n      then have \"p tt > con\"\n        using not by auto\n      then have \"{y. p y = con \\<and> y \\<in> {tt .. x}} \\<noteq> {}\"\n        using IVT2[of p x con tt] using 3 1 assms that t1 \n        by auto\n      then show ?thesis using that by auto\n    qed\n    then show False using t1 t2 9 \n      using atLeastAtMost_iff greaterThanAtMost_iff by auto\n  qed     \n  have 11:\"(p has_derivative q t) (at t within {-e..d+e})\"\n    using assms t1 by auto\n  then have 12:\"\\<forall>s . q t s = q t 1 * s\"\n    using has_derivative_bounded_linear[of p \"q t\" \"(at t within {-e..d+e})\"]\n    using real_bounded_linear by auto\n  have 13:\"(p has_real_derivative q t 1) (at t within {-e..d+e})\"\n    using 11 12 \n    by (metis has_derivative_imp_has_field_derivative mult.commute)\n  have 14:\"q t 1 > 0\" using t1 assms 9 by auto\n  have 15:\"\\<exists>dd>0. \\<forall>h>0. t + h \\<in> {-e..d+e} \\<longrightarrow> h < dd \\<longrightarrow> p (t + h) > p t\"\n    using has_real_derivative_pos_inc_right[of p \"q t 1\" t \"{-e..d+e}\"] 13 14 \n    by auto\n  then obtain dd where d1:\"\\<forall>h>0. t + h \\<in> {-e..d+e} \\<longrightarrow> h < dd \\<longrightarrow> p (t + h) > p t\" and d2:\"dd>0\" by auto\n  then have 16:\"min (dd/2) (x-t)/2 < dd\" and \"min (dd/2) (x-t)/2 > 0\"\n    using 9 by auto\n  then have 17:\"(t + min (dd/2) (x-t)/2)> t\" \"(t + min (dd/2) (x-t)/2) < x\" \n    apply auto\n    using d2 9\n     by (smt field_sum_of_halves)\n   then have 18:\"p (t + min (dd/2) (x-t)/2) > p t\"\n    using d1 t1 16 assms(5) assms(6) by auto\n  have 19:\"p (t + min (dd/2) (x-t)/2)< con\" using 10 17 by auto\n  show False using 18 19 t1\n    by auto \nqed\n\nlemma real_inv_l:\n  fixes p :: \"real \\<Rightarrow> real\" and con :: real\n  assumes \"\\<forall>t\\<in>{-e..d+e}. (p has_derivative q t) (at t within {-e..d+e})\"\n    and \"d \\<ge> 0\"\n    and \"\\<forall>t\\<in>{0 ..<d}. (p t \\<le> con \\<longrightarrow> q t 1 < 0)\"\n    and \"p 0 < con \"\n    and \"x \\<in> {0 .. d}\"\n    and \"e > 0\"\n  shows \"p x < con\"\nproof (rule ccontr) \n  assume a:\" \\<not> p x < con\"\n  have 1:\"p x \\<ge> con\"\n    using a by auto\n  have 2:\"\\<forall>t\\<in>{0 .. d}. continuous (at t within {-e<..<d+e}) p\"\n    using assms has_derivative_subset\n    using has_derivative_continuous \n    by (smt atLeastAtMost_iff continuous_within_subset greaterThanLessThan_subseteq_atLeastAtMost_iff greaterThan_iff)\n  have 3:\"\\<forall>t\\<in>{0 .. d}. isCont p t\"\n    apply auto subgoal for t\n      using continuous_within_open[of t \"{-e<..<d+e}\" p]\n      using 2 assms(5) assms(6) by auto\n    done\n  have 4:\"{y. p y = con \\<and> y \\<in> {0 .. x}} \\<noteq> {}\"\n    using IVT[of p 0 con x] using 3 1 assms \n    by auto\n  have 5: \"{y. p y = con \\<and> y \\<in> {0 .. x}} = ({0 .. x} \\<inter> p -` {con})\"\n    by auto\n  have 6: \"closed ({0 .. x} \\<inter> p -` {con})\"\n    using 3 assms(5) apply simp\n    apply (rule continuous_closed_preimage)\n      apply auto\n    by (simp add: continuous_at_imp_continuous_on)\n  have 7: \"compact {0 .. x}\"\n    using assms\n    by blast\n  have 8: \"compact {y. p y = con \\<and> y \\<in> {0 .. x}}\"\n    apply auto\n    using 4 5 6 7 \n    by (smt Collect_cong Int_left_absorb atLeastAtMost_iff compact_Int_closed)\n  obtain t where t1:\"t \\<in> {y. p y = con \\<and> y \\<in> {0 .. x}}\" and t2:\"\\<forall> tt\\<in> {y. p y = con \\<and> y \\<in> {0 .. x}}. tt \\<ge> t\"\n    using compact_attains_inf[of \"{y. p y = con \\<and> y \\<in> {0 .. x}}\"] 4 8 \n    by blast\n  have 9:\"t > 0\"\n    using t1 1 assms(4) \n    using less_eq_real_def by auto\n  have 10:\"p tt < con\" if \"tt\\<in>{0..<t}\" for tt\n  proof(rule ccontr)\n    assume \"\\<not> p tt < con\"\n    then have not:\"p tt \\<ge> con\" by auto\n    have \"\\<exists> t' \\<in> {0..<t}. p t' = con\"\n    proof(cases \"p tt = con\")\n      case True\n      then show ?thesis using that by auto\n    next\n      case False\n      then have \"p tt > con\"\n        using not by auto\n      then have \"{y. p y = con \\<and> y \\<in> {0 .. tt}} \\<noteq> {}\"\n        using IVT[of p 0 con tt] using 3 1 assms that t1 \n        by auto\n      then show ?thesis using that by auto\n    qed\n    then show False using t1 t2 9 \n      using atLeastAtMost_iff greaterThanAtMost_iff by auto\n  qed     \n  have 11:\"(p has_derivative q y) (at y within {0..t})\" if \"y \\<in> {0 ..t}\"for y\n    apply(rule has_derivative_subset [where s = \"{-e<..<d+e}\"])\n    using assms that t1\n    apply auto \n    by (smt atLeastAtMost_iff at_within_Icc_at has_derivative_at_withinI)\n  have 12:\"\\<exists> tt \\<in> {0<..<t} . p t - p 0 = q tt t \"\n    using mvt_simple[of 0 t p q] 9 11\n    by auto\n  obtain tt where tt1:\"p t - p 0 = q tt t\" and tt2:\"tt \\<in> {0<..<t}\"\n    using 12 by auto\n  have 13:\"\\<forall>s . q tt s = q tt 1 * s\"\n    using has_derivative_bounded_linear[of p \"q tt\" \"(at tt within {0..t})\"]\n    using real_bounded_linear 11 tt2 by auto\n  have 14:\"p t - p 0 = q tt 1 * t\" using tt1 13 \n    by metis\n  have 15:\"q tt 1 > 0\" using 14 assms(4) t1 9 \n    by (metis (mono_tags, lifting) diff_gt_0_iff_gt mem_Collect_eq zero_less_mult_pos2)\n  then show False using assms(3) 10[of tt] tt2 \n    by (smt \"10\" a assms(5) atLeastAtMost_iff atLeastLessThan_iff greaterThanLessThan_iff)\nqed\n\n\nlemma real_inv_g:\n  fixes p :: \"real \\<Rightarrow> real\" and con :: real\n  assumes \"\\<forall>t\\<in>{-e..d+e}. (p has_derivative q t) (at t within {-e..d+e})\"\n    and \"d \\<ge> 0\"\n    and \"\\<forall>t\\<in>{0 ..<d}. (p t \\<ge> con \\<longrightarrow> q t 1 \\<ge> 0)\"\n    and \"p 0 > con \"\n    and \"x \\<in> {0 .. d}\"\n    and \"e > 0\"\n  shows \"p x > con\" \nproof (rule ccontr) \n  assume a:\" \\<not> p x > con\"\n  have 1:\"p x \\<le> con\"\n    using a by auto\n  have 2:\"\\<forall>t\\<in>{0 .. d}. continuous (at t within {-e<..<d+e}) p\"\n    using assms has_derivative_subset\n    using has_derivative_continuous \n    by (smt atLeastAtMost_iff continuous_within_subset greaterThanLessThan_subseteq_atLeastAtMost_iff greaterThan_iff)\n  have 3:\"\\<forall>t\\<in>{0 .. d}. isCont p t\"\n    apply auto subgoal for t\n      using continuous_within_open[of t \"{-e<..<d+e}\" p]\n      using 2 assms(5) assms(6) by auto\n    done\n  have 4:\"{y. p y = con \\<and> y \\<in> {0 .. x}} \\<noteq> {}\"\n    using IVT2[of p x con 0] using 3 1 assms \n    by auto\n  have 5: \"{y. p y = con \\<and> y \\<in> {0 .. x}} = ({0 .. x} \\<inter> p -` {con})\"\n    by auto\n  have 6: \"closed ({0 .. x} \\<inter> p -` {con})\"\n    using 3 assms(5) apply simp\n    apply (rule continuous_closed_preimage)\n      apply auto\n    by (simp add: continuous_at_imp_continuous_on)\n  have 7: \"compact {0 .. x}\"\n    using assms\n    by blast\n  have 8: \"compact {y. p y = con \\<and> y \\<in> {0 .. x}}\"\n    apply auto\n    using 4 5 6 7 \n    by (smt Collect_cong Int_left_absorb atLeastAtMost_iff compact_Int_closed)\n  obtain t where t1:\"t \\<in> {y. p y = con \\<and> y \\<in> {0 .. x}}\" and t2:\"\\<forall> tt\\<in> {y. p y = con \\<and> y \\<in> {0 .. x}}. tt \\<ge> t\"\n    using compact_attains_inf[of \"{y. p y = con \\<and> y \\<in> {0 .. x}}\"] 4 8 \n    by blast\n  have 9:\"t > 0\"\n    using t1 1 assms(4) \n    using less_eq_real_def by auto\n  have 10:\"p tt > con\" if \"tt\\<in>{0..<t}\" for tt\n  proof(rule ccontr)\n    assume \"\\<not> p tt > con\"\n    then have not:\"p tt \\<le> con\" by auto\n    have \"\\<exists> t' \\<in> {0..<t}. p t' = con\"\n    proof(cases \"p tt = con\")\n      case True\n      then show ?thesis using that by auto\n    next\n      case False\n      then have \"p tt < con\"\n        using not by auto\n      then have \"{y. p y = con \\<and> y \\<in> {0 .. tt}} \\<noteq> {}\"\n        using IVT2[of p tt con 0] using 3 1 assms that t1 \n        by auto\n      then show ?thesis using that by auto\n    qed\n    then show False using t1 t2 9 \n      using atLeastAtMost_iff greaterThanAtMost_iff by auto\n  qed     \n  have 11:\"(p has_derivative q y) (at y within {0..t})\" if \"y \\<in> {0 ..t}\"for y\n    apply(rule has_derivative_subset [where s = \"{-e<..<d+e}\"])\n    using assms that t1\n    apply auto \n    by (smt atLeastAtMost_iff at_within_Icc_at has_derivative_at_withinI)\n  have 12:\"\\<exists> tt \\<in> {0<..<t} . p t - p 0 = q tt t \"\n    using mvt_simple[of 0 t p q] 9 11\n    by auto\n  obtain tt where tt1:\"p t - p 0 = q tt t\" and tt2:\"tt \\<in> {0<..<t}\"\n    using 12 by auto\n  have 13:\"\\<forall>s . q tt s = q tt 1 * s\"\n    using has_derivative_bounded_linear[of p \"q tt\" \"(at tt within {0..t})\"]\n    using real_bounded_linear 11 tt2 by auto\n  have 14:\"p t - p 0 = q tt 1 * t\" using tt1 13 \n    by metis\n  have 15:\"q tt 1 < 0\" using 14 assms(4) t1 9 \n    by (metis (mono_tags, lifting) less_iff_diff_less_0 mem_Collect_eq mult_less_0_iff not_less_iff_gr_or_eq)\n  then show False using assms(3) 10[of tt] tt2 \n    by (smt \"1\" \"10\" assms(5) atLeastAtMost_iff atLeastLessThan_iff greaterThanLessThan_iff) \nqed\n\nsubsection \\<open>Definition of states\\<close>\n\ntext \\<open>Variable names\\<close>\ntype_synonym var = char\n\ntext \\<open>State\\<close>\ntype_synonym state = \"var \\<Rightarrow> real\"\n\ntext \\<open>Expressions\\<close>\ntype_synonym exp = \"state \\<Rightarrow> real\"\n\ntext \\<open>Predicates\\<close>\ntype_synonym fform = \"state \\<Rightarrow> bool\"\n\ntext \\<open>States as a vector\\<close>\ntype_synonym vec = \"real^(var)\"\n\ntext \\<open>Conversion between state and vector\\<close>\ndefinition state2vec :: \"state \\<Rightarrow> vec\" where\n  \"state2vec s = (\\<chi> x. s x)\"\n\ndefinition vec2state :: \"vec \\<Rightarrow> state\" where\n  \"(vec2state v) x = v $ x\"\n\nlemma vec_state_map1[simp]: \"vec2state (state2vec s) = s\"\n  unfolding vec2state_def state2vec_def by auto\n\nlemma vec_state_map2[simp]: \"state2vec (vec2state s) = s\"\n  unfolding vec2state_def state2vec_def by auto\n\nsubsection \\<open>Definition of ODEs\\<close>\n\ndatatype ODE =\n  ODE \"var \\<Rightarrow> exp\"\n\ntext \\<open>Given ODE and a state, find the derivative vector.\\<close>\nfun ODE2Vec :: \"ODE \\<Rightarrow> state \\<Rightarrow> vec\" where\n  \"ODE2Vec (ODE f) s = state2vec (\\<lambda>a. f a s)\"\n\ntext \\<open>History p on time {0 .. d} is a solution to ode.\\<close>\ndefinition ODEsol :: \"ODE \\<Rightarrow> (real \\<Rightarrow> state) \\<Rightarrow> real \\<Rightarrow> bool\" where\n  \"ODEsol ode p d = (d \\<ge> 0 \\<and> (\\<exists>\\<epsilon>>0. ((\\<lambda>t. state2vec (p t)) has_vderiv_on (\\<lambda>t. ODE2Vec ode (p t))) {-\\<epsilon> .. d+\\<epsilon>}))\"\n\ntext \\<open>History p on time {0 ..} is a solution to ode.\\<close>\ndefinition ODEsolInf :: \"ODE \\<Rightarrow> (real \\<Rightarrow> state) \\<Rightarrow> bool\" where\n  \"ODEsolInf ode p = (\\<exists>\\<epsilon>>0. ((\\<lambda>t. state2vec (p t)) has_vderiv_on (\\<lambda>t. ODE2Vec ode (p t))) {-\\<epsilon> ..})\"\n\n\nsubsection \\<open>Further results in analysis\\<close>\n\nlemma ODEsol_old:\n  assumes \"ODEsol ode p d\"\n  shows \"((\\<lambda>t. state2vec (p t)) has_vderiv_on (\\<lambda>t. ODE2Vec ode (p t))) {0 .. d}\"\nproof-\n  obtain e where e: \"e > 0\" \"((\\<lambda>t. state2vec (p t)) has_vderiv_on (\\<lambda>t. ODE2Vec ode (p t))) {-e .. d+e}\"\n    using assms(1) unfolding ODEsol_def by blast\n  then show ?thesis \n    using e(1) has_vderiv_on_subset[OF e(2)] by auto\nqed\n\nlemma ODEsolInf_old:\n   assumes \"ODEsolInf  ode p\"\n   shows \"((\\<lambda>t. state2vec (p t)) has_vderiv_on (\\<lambda>t. ODE2Vec ode (p t))) {0 ..}\"\nproof-\n  obtain e where e: \"e > 0\" \"((\\<lambda>t. state2vec (p t)) has_vderiv_on (\\<lambda>t. ODE2Vec ode (p t))) {-e ..}\"\n    using assms(1) unfolding ODEsolInf_def by blast\n  then show ?thesis \n    using e(1) has_vderiv_on_subset[OF e(2)] by auto\nqed\n\nlemma ODEsol_merge:\n  assumes \"ODEsol ode p d\"\n    and \"ODEsol ode p2 d2\"\n    and \"p2 0 = p d\"\n  shows \"ODEsol ode (\\<lambda>\\<tau>. if \\<tau> < d then p \\<tau> else p2 (\\<tau> - d)) (d + d2)\"\n  unfolding ODEsol_def\n  apply auto\n  subgoal \n    using assms(1,2) unfolding ODEsol_def by auto\n  subgoal\n  proof-\n    have step1:\"d\\<ge>0 \\<and> d2\\<ge>0\"\n      using assms unfolding ODEsol_def by auto\n    then have step2:\"{0 .. d+d2} = {0 .. d}\\<union>{d .. d+d2}\"\n      by auto\n    have step3:\"({0..d} \\<union> closure {d..d + d2} \\<inter> closure {0..d}) = {0..d}\"\n      using step1 by auto\n    have step4:\"({d..d + d2} \\<union> closure {d..d + d2} \\<inter> closure {0..d}) = {d..d+d2}\"\n      using step1 by auto\n    obtain e1 where e1: \"e1 > 0\" \"((\\<lambda>t. state2vec (p t)) has_vderiv_on (\\<lambda>t. ODE2Vec ode (p t))) {-e1 .. d+e1}\"\n      using assms(1) unfolding ODEsol_def by blast\n    obtain e2 where e2: \"e2 > 0\" \"((\\<lambda>t. state2vec (p2 t)) has_vderiv_on (\\<lambda>t. ODE2Vec ode (p2 t))) {-e2 .. d2+e2}\"\n      using assms(2) unfolding ODEsol_def by blast\n    obtain e where e: \"e > 0\" \"e < e1\" \"e < e2\"\n      using e1(1) e2(1) field_lbound_gt_zero by auto\n    then have stepe:\"{0 .. d2+e}\\<subseteq>{- e2..d2 + e2}\" \"{-e .. d}\\<subseteq>{- e1..d + e1}\" \"{- e..d + d2 + e} = {- e..d} \\<union> {d..d + d2 + e}\"\n      using step1  by auto\n    have stepclo1:\"({- e..d} \\<union> closure {d..d + d2 + e} \\<inter> closure {- e..d}) = {- e..d}\"\n      using e step1 by auto \n    have stepclo2:\" ({d..d + d2 + e} \\<union> closure {d..d + d2 + e} \\<inter> closure {- e..d}) = {d..d + d2 + e}\"\n      using e step1 by auto\n    have stepclo3: \"x \\<in> closure {d..d + d2 + e} \\<Longrightarrow>\n          x \\<in> closure {- e..d} \\<Longrightarrow> x = d\" for x\n      using e step1  by auto\n    have step5: \"((\\<lambda>t. t - d) has_vderiv_on (\\<lambda>t. 1)) {d .. d+d2+e}\"\n      by (auto intro!: derivative_intros)\n    then have step6: \"((\\<lambda>t. state2vec (p2 (t-d))) has_vderiv_on (\\<lambda>t. ODE2Vec ode (p2 (t-d)))) {d .. d+d2+e}\"\n      using has_vderiv_on_compose2[of \"(\\<lambda>t. state2vec (p2 t))\" \"(\\<lambda>t. ODE2Vec ode (p2 (t)))\" \"{0 .. d2+e}\" \"(\\<lambda>t. (t-d))\" \"(\\<lambda>t. 1)\" \"{d .. d+d2+e}\"]\n      using e2 e unfolding ODEsol_def\n      using has_vderiv_on_subset[OF e2(2) stepe(1)] by auto\n     have step7:\" ((\\<lambda>t. if t \\<in> {-e..d} then state2vec (p t) else state2vec (p2 (t - d))) has_vderiv_on\n     (\\<lambda>t. if t \\<in> {-e..d} then ODE2Vec ode (p t) else ODE2Vec ode (p2 (t - d)))){-e..d + d2+e}\"\n      using has_vderiv_on_If[of \"{-e .. d+d2+e}\" \"{-e .. d}\" \"{d .. d+d2+e}\" \"(\\<lambda>t. state2vec (p t))\" \"(\\<lambda>t. ODE2Vec ode (p t))\" \"(\\<lambda>t. state2vec (p2 (t-d)))\" \"(\\<lambda>t. ODE2Vec ode (p2 (t-d)))\"]\n      using step1 step2 step3 step4 step6 stepclo1 stepclo2 stepclo3\n      using has_vderiv_on_subset[OF e1(2) stepe(2)] e stepe assms(3)\n      by auto\n    show ?thesis\n      apply(rule exI[where x=e])\n      using has_vderiv_eq[of \"(\\<lambda>t. if t \\<in> {-e..d} then state2vec (p t) else state2vec (p2 (t - d)))\" \"(\\<lambda>t. if t \\<in> {-e..d} then ODE2Vec ode (p t) else ODE2Vec ode (p2 (t - d)))\" \"{-e..d + d2+e}\" \"(\\<lambda>t. state2vec (if t < d then p t else p2 (t - d)))\" \"(\\<lambda>t. ODE2Vec ode (if t < d then p t else p2 (t - d)))\" \"{-e..d + d2+e}\"]\n      using step7\n      using assms(3) step1 e\n      by auto\n  qed\n  done\n\nlemma ODEsol_split:\n  assumes \"ODEsol ode p d\"\n    and \"0 < t1\" and \"t1 < d\"\n  shows \"ODEsol ode p t1\"\n        \"ODEsol ode (\\<lambda>t. p (t + t1)) (d - t1)\"\n  subgoal\n  proof-\n    obtain e where e: \"e > 0\" \"((\\<lambda>t. state2vec (p t)) has_vderiv_on (\\<lambda>t. ODE2Vec ode (p t))) {-e .. d+e}\"\n      using assms(1) unfolding ODEsol_def by blast\n    then show ?thesis unfolding ODEsol_def\n    using has_vderiv_on_subset[of \"(\\<lambda>t. state2vec (p t))\" \" (\\<lambda>t. ODE2Vec ode (p t))\" \"{-e .. d+e}\" \"{-e..t1+e}\"]\n    using assms unfolding ODEsol_def by auto\nqed\n  subgoal\n    unfolding ODEsol_def apply auto\n    subgoal using assms by auto\n    subgoal \n    proof-\n      obtain e where e: \"e > 0\" \"((\\<lambda>t. state2vec (p t)) has_vderiv_on (\\<lambda>t. ODE2Vec ode (p t))) {-e .. d+e}\"\n        using assms(1) unfolding ODEsol_def by blast\n      have step1:\"((\\<lambda>t. state2vec (p (t))) has_vderiv_on (\\<lambda>t. ODE2Vec ode (p (t)))) {t1-e..d+e}\"\n        using has_vderiv_on_subset[of \"(\\<lambda>t. state2vec (p t))\" \" (\\<lambda>t. ODE2Vec ode (p t))\" \"{-e..d+e}\" \"{t1-e..d+e}\"]\n        using e assms  by auto\n      have step2:\"((\\<lambda>t.(t+t1)) has_vderiv_on (\\<lambda>t. 1)) {-e..d-t1+e}\"\n        by (auto intro!: derivative_intros)\n      have step3:\"t \\<in> {- e..d - t1 + e} \\<Longrightarrow> t + t1 \\<in> {t1 - e..d + e}\" for t\n        using e assms by auto\n      show ?thesis\n        apply (rule exI[where x=e])\n        apply auto \n        subgoal using e by auto\n        using has_vderiv_on_compose2[of \"(\\<lambda>t. state2vec (p (t)))\" \"(\\<lambda>t. ODE2Vec ode (p (t)))\" \"{t1-e..d+e}\" \"(\\<lambda>t.(t+t1))\" \"(\\<lambda>t. 1)\" \" {-e..d-t1+e}\"]\n        using step1 step2 step3 by auto\n    qed\n    done\n  done\n\n\n\nend\n", "meta": {"author": "AgHHL", "repo": "lics2023", "sha": "e2ea9c15a8c0e1bf658679274ee87f30baf4abc3", "save_path": "github-repos/isabelle/AgHHL-lics2023", "path": "github-repos/isabelle/AgHHL-lics2023/lics2023-e2ea9c15a8c0e1bf658679274ee87f30baf4abc3/case1/Analysis_More.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677660619633, "lm_q2_score": 0.8289388146603365, "lm_q1q2_score": 0.7029133948695774}}
{"text": "(*  Title:       Computing Square Roots using the Babylonian Method\n    Author:      Ren\u00e9 Thiemann       <rene.thiemann@uibk.ac.at>\n    Maintainer:  Ren\u00e9 Thiemann\n    License:     LGPL\n*)\nsection \\<open>A Fast Logarithm Algorithm\\<close>\n\ntheory Log_Impl\nimports \n  Sqrt_Babylonian_Auxiliary\nbegin\n\ntext \\<open>We implement the discrete logarithm function in a manner similar to\n  a repeated squaring exponentiation algorithm.\\<close>\n\ntext \\<open>In order to prove termination of the algorithm without intermediate checks \n  we need to ensure that we only use proper bases, \n  i.e., values of at least 2. This will be encoded into a separate type.\\<close>\n\ntypedef proper_base = \"{x :: int. x \\<ge> 2}\" by auto\n\nsetup_lifting type_definition_proper_base\n\nlift_definition get_base :: \"proper_base \\<Rightarrow> int\" is \"\\<lambda> x. x\" .\n\nlift_definition square_base :: \"proper_base \\<Rightarrow> proper_base\" is \"\\<lambda> x. x * x\" \nproof -\n  fix i :: int\n  assume i: \"2 \\<le> i\"\n  have \"2 * 2 \\<le> i * i\" \n    by (rule mult_mono[OF i i], insert i, auto)\n  thus \"2 \\<le> i * i\" by auto\nqed\n\nlift_definition into_base :: \"int \\<Rightarrow> proper_base\" is \"\\<lambda> x. if x \\<ge> 2 then x else 2\" by auto\n\nlemma square_base: \"get_base (square_base b) = get_base b * get_base b\" \n  by (transfer, auto)\n\nlemma get_base_2: \"get_base b \\<ge> 2\"\n  by (transfer, auto)\n\nlemma b_less_square_base_b: \"get_base b < get_base (square_base b)\" \n  unfolding square_base using get_base_2[of b] by simp\n\nlemma b_less_div_base_b: assumes xb: \"\\<not> x < get_base b\"\n  shows \"x div get_base b < x\"\nproof -\n  from get_base_2[of b] have b: \"get_base b \\<ge> 2\" .\n  with xb have x2: \"x \\<ge> 2\" by auto\n  with b int_div_less_self[of x \"(get_base b)\"] \n  show ?thesis by auto\nqed\n    \ntext \\<open>We now state the main algorithm.\\<close>\n    \nfunction log_main :: \"proper_base \\<Rightarrow> int \\<Rightarrow> nat \\<times> int\" where\n  \"log_main b x = (if x < get_base b then (0,1) else\n    case log_main (square_base b) x of \n      (z, bz) \\<Rightarrow> \n    let l = 2 * z; bz1 = bz * get_base b\n      in if x < bz1 then (l,bz) else (Suc l,bz1))\" \n  by pat_completeness auto\n\ntermination by (relation \"measure (\\<lambda> (b,x). nat (1 + x - get_base b))\",\n  insert b_less_square_base_b, auto)   \n\nlemma log_main: \"x > 0 \\<Longrightarrow> log_main b x = (y,by) \\<Longrightarrow> by = (get_base b)^y \\<and> (get_base b)^y \\<le> x \\<and> x < (get_base b)^(Suc y)\" \nproof (induct b x arbitrary: y \"by\" rule: log_main.induct)\n  case (1 b x y \"by\")\n  note x = 1(2)\n  note y = 1(3)\n  note IH = 1(1)\n  let ?b = \"get_base b\" \n  show ?case\n  proof (cases \"x < ?b\")\n    case True\n    with x y show ?thesis by auto\n  next\n    case False\n    obtain z bz where zz: \"log_main (square_base b) x = (z,bz)\" \n      by (cases \"log_main (square_base b) x\", auto)\n    have id: \"get_base (square_base b) ^ k = ?b ^ (2 * k)\" for k unfolding square_base\n      by (simp add: power_mult semiring_normalization_rules(29))\n    from IH[OF False x zz, unfolded id] \n    have z: \"?b ^ (2 * z) \\<le> x\" \"x < ?b ^ (2 * Suc z)\" and bz: \"bz = get_base b ^ (2 * z)\" by auto\n    from y[unfolded log_main.simps[of b x] Let_def zz split] bz False\n    have yy: \"(if x < bz * ?b then (2 * z, bz) else (Suc (2 * z), bz * ?b)) =\n      (y, by)\" by auto\n    show ?thesis\n    proof (cases \"x < bz * ?b\")\n      case True\n      with yy have yz: \"y = 2 * z\" \"by = bz\" by auto\n      from True z(1) bz show ?thesis unfolding yz by (auto simp: ac_simps)\n    next\n      case False\n      with yy have yz: \"y = Suc (2 * z)\" \"by = ?b * bz\" by auto\n      from False have \"?b ^ Suc (2 * z) \\<le> x\" by (auto simp: bz ac_simps)\n      with z(2) bz show ?thesis unfolding yz by auto\n    qed\n  qed\nqed\n    \ntext \\<open>We then derive the floor- and ceiling-log functions.\\<close>\n\ndefinition log_floor :: \"int \\<Rightarrow> int \\<Rightarrow> nat\" where\n  \"log_floor b x = fst (log_main (into_base b) x)\" \n\ndefinition log_ceiling :: \"int \\<Rightarrow> int \\<Rightarrow> nat\" where\n  \"log_ceiling b x = (case log_main (into_base b) x of\n     (y,by) \\<Rightarrow> if x = by then y else Suc y)\" \n\nlemma log_floor_sound: assumes \"b > 1\" \"x > 0\" \"log_floor b x = y\"  \n  shows \"b^y \\<le> x\" \"x < b^(Suc y)\" \nproof -\n  from assms(1,3) have id: \"get_base (into_base b) = b\" by transfer auto\n  obtain yy bb where log: \"log_main (into_base b) x = (yy,bb)\" \n    by (cases \"log_main (into_base b) x\", auto)\n  from log_main[OF assms(2) log] assms(3)[unfolded log_floor_def log] id\n  show \"b^y \\<le> x\" \"x < b^(Suc y)\" by auto\nqed\n\nlemma log_ceiling_sound: assumes \"b > 1\" \"x > 0\" \"log_ceiling b x = y\"  \n  shows \"x \\<le> b^y\" \"y \\<noteq> 0 \\<Longrightarrow> b^(y - 1) < x\" \nproof -\n  from assms(1,3) have id: \"get_base (into_base b) = b\" by transfer auto\n  obtain yy bb where log: \"log_main (into_base b) x = (yy,bb)\" \n    by (cases \"log_main (into_base b) x\", auto)\n  from log_main[OF assms(2) log, unfolded id] assms(3)[unfolded log_ceiling_def log split]\n  have bnd: \"b ^ yy \\<le> x\" \"x < b ^ Suc yy\" and\n    y: \"y = (if x = b ^ yy then yy else Suc yy)\" by auto\n  have \"x \\<le> b^y \\<and> (y \\<noteq> 0 \\<longrightarrow> b^(y - 1) < x)\"\n  proof (cases \"x = b ^ yy\")\n    case True\n    with y bnd assms(1) show ?thesis by (cases yy, auto)\n  next\n    case False\n    with y bnd show ?thesis by auto\n  qed\n  thus \"x \\<le> b^y\" \"y \\<noteq> 0 \\<Longrightarrow> b^(y - 1) < x\" by auto\nqed\n\ntext \\<open>Finally, we connect it to the @{const log} function working on real numbers.\\<close>\n\nlemma log_floor[simp]: assumes b: \"b > 1\" and x: \"x > 0\"\n  shows \"log_floor b x = \\<lfloor>log b x\\<rfloor>\"\nproof -\n  obtain y where y: \"log_floor b x = y\" by auto\n  note main = log_floor_sound[OF assms y]\n  from b x have *: \"1 < real_of_int b\" \"0 < real_of_int (b ^ y)\" \"0 < real_of_int x\" \n    and **: \"1 < real_of_int b\" \"0 < real_of_int x\" \"0 < real_of_int (b ^ Suc y)\" \n    by auto\n  show ?thesis unfolding y\n  proof (rule sym, rule floor_unique)\n    show \"real_of_int (int y) \\<le> log (real_of_int b) (real_of_int x)\" \n      using main(1)[folded log_le_cancel_iff[OF *, unfolded of_int_le_iff]]\n      using log_pow_cancel[of b y] b by auto\n    show \"log (real_of_int b) (real_of_int x) < real_of_int (int y) + 1\" \n      using main(2)[folded log_less_cancel_iff[OF **, unfolded of_int_less_iff]]\n      using log_pow_cancel[of b \"Suc y\"] b by auto\n  qed\nqed\n    \nlemma log_ceiling[simp]: assumes b: \"b > 1\" and x: \"x > 0\"\n  shows \"log_ceiling b x = \\<lceil>log b x\\<rceil>\"\nproof -\n  obtain y where y: \"log_ceiling b x = y\" by auto\n  note main = log_ceiling_sound[OF assms y]\n  from b x have *: \"1 < real_of_int b\" \"0 < real_of_int (b ^ (y - 1))\" \"0 < real_of_int x\" \n    and **: \"1 < real_of_int b\" \"0 < real_of_int x\" \"0 < real_of_int (b ^ y)\" \n    by auto\n  show ?thesis unfolding y\n  proof (rule sym, rule ceiling_unique)\n    show \"log (real_of_int b) (real_of_int x) \\<le> real_of_int (int y)\" \n      using main(1)[folded log_le_cancel_iff[OF **, unfolded of_int_le_iff]]\n      using log_pow_cancel[of b y] b by auto\n    from x have x: \"x \\<ge> 1\" by auto\n    show \"real_of_int (int y) - 1 < log (real_of_int b) (real_of_int x)\" \n    proof (cases \"y = 0\")\n      case False\n      thus ?thesis \n        using main(2)[folded log_less_cancel_iff[OF *, unfolded of_int_less_iff]]\n        using log_pow_cancel[of b \"y - 1\"] b x by auto\n    next\n      case True\n      have \"real_of_int (int y) - 1 = log b (1/b)\" using True b \n        by (subst log_divide, auto)\n      also have \"\\<dots> < log b 1\"\n        by (subst log_less_cancel_iff, insert b, auto) \n      also have \"\\<dots> \\<le> log b x\" \n        by (subst log_le_cancel_iff, insert b x, auto) \n      finally show \"real_of_int (int y) - 1 < log (real_of_int b) (real_of_int x)\" .\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/Sqrt_Babylonian/Log_Impl.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8289388167733099, "lm_q2_score": 0.8479677526147223, "lm_q1q2_score": 0.7029133855143708}}
{"text": "(*  Title:      HOL/Library/Countable_Set_Type.thy\n    Author:     Andrei Popescu, TU Muenchen\n    Copyright   2012\n\nType of (at most) countable sets.\n*)\n\nsection {* Type of (at Most) Countable Sets *}\n\ntheory Countable_Set_Type\nimports Countable_Set Cardinal_Notations\nbegin\n\nabbreviation \"Grp \\<equiv> BNF_Def.Grp\"\n\n\nsubsection{* Cardinal stuff *}\n\nlemma countable_card_of_nat: \"countable A \\<longleftrightarrow> |A| \\<le>o |UNIV::nat set|\"\n  unfolding countable_def card_of_ordLeq[symmetric] by auto\n\nlemma countable_card_le_natLeq: \"countable A \\<longleftrightarrow> |A| \\<le>o natLeq\"\n  unfolding countable_card_of_nat using card_of_nat ordLeq_ordIso_trans ordIso_symmetric by blast\n\nlemma countable_or_card_of:\nassumes \"countable A\"\nshows \"(finite A \\<and> |A| <o |UNIV::nat set| ) \\<or>\n       (infinite A  \\<and> |A| =o |UNIV::nat set| )\"\nby (metis assms countable_card_of_nat infinite_iff_card_of_nat ordIso_iff_ordLeq\n      ordLeq_iff_ordLess_or_ordIso)\n\nlemma countable_cases_card_of[elim]:\n  assumes \"countable A\"\n  obtains (Fin) \"finite A\" \"|A| <o |UNIV::nat set|\"\n        | (Inf) \"infinite A\" \"|A| =o |UNIV::nat set|\"\n  using assms countable_or_card_of by blast\n\nlemma countable_or:\n  \"countable A \\<Longrightarrow> (\\<exists> f::'a\\<Rightarrow>nat. finite A \\<and> inj_on f A) \\<or> (\\<exists> f::'a\\<Rightarrow>nat. infinite A \\<and> bij_betw f A UNIV)\"\n  by (elim countable_enum_cases) fastforce+\n\nlemma countable_cases[elim]:\n  assumes \"countable A\"\n  obtains (Fin) f :: \"'a\\<Rightarrow>nat\" where \"finite A\" \"inj_on f A\"\n        | (Inf) f :: \"'a\\<Rightarrow>nat\" where \"infinite A\" \"bij_betw f A UNIV\"\n  using assms countable_or by metis\n\nlemma countable_ordLeq:\nassumes \"|A| \\<le>o |B|\" and \"countable B\"\nshows \"countable A\"\nusing assms unfolding countable_card_of_nat by(rule ordLeq_transitive)\n\nlemma countable_ordLess:\nassumes AB: \"|A| <o |B|\" and B: \"countable B\"\nshows \"countable A\"\nusing countable_ordLeq[OF ordLess_imp_ordLeq[OF AB] B] .\n\nsubsection {* The type of countable sets *}\n\ntypedef 'a cset = \"{A :: 'a set. countable A}\" morphisms rcset acset\n  by (rule exI[of _ \"{}\"]) simp\n\nsetup_lifting type_definition_cset\n\ndeclare\n  rcset_inverse[simp]\n  acset_inverse[Transfer.transferred, unfolded mem_Collect_eq, simp]\n  acset_inject[Transfer.transferred, unfolded mem_Collect_eq, simp]\n  rcset[Transfer.transferred, unfolded mem_Collect_eq, simp]\n\nlift_definition cin :: \"'a \\<Rightarrow> 'a cset \\<Rightarrow> bool\" is \"op \\<in>\" parametric member_transfer\n  .\nlift_definition cempty :: \"'a cset\" is \"{}\" parametric empty_transfer\n  by (rule countable_empty)\nlift_definition cinsert :: \"'a \\<Rightarrow> 'a cset \\<Rightarrow> 'a cset\" is insert parametric Lifting_Set.insert_transfer\n  by (rule countable_insert)\nlift_definition csingle :: \"'a \\<Rightarrow> 'a cset\" is \"\\<lambda>x. {x}\"\n  by (rule countable_insert[OF countable_empty])\nlift_definition cUn :: \"'a cset \\<Rightarrow> 'a cset \\<Rightarrow> 'a cset\" is \"op \\<union>\" parametric union_transfer\n  by (rule countable_Un)\nlift_definition cInt :: \"'a cset \\<Rightarrow> 'a cset \\<Rightarrow> 'a cset\" is \"op \\<inter>\" parametric inter_transfer\n  by (rule countable_Int1)\nlift_definition cDiff :: \"'a cset \\<Rightarrow> 'a cset \\<Rightarrow> 'a cset\" is \"op -\" parametric Diff_transfer\n  by (rule countable_Diff)\nlift_definition cimage :: \"('a \\<Rightarrow> 'b) \\<Rightarrow> 'a cset \\<Rightarrow> 'b cset\" is \"op `\" parametric image_transfer\n  by (rule countable_image)\n\nsubsection {* Registration as BNF *}\n\nlemma card_of_countable_sets_range:\nfixes A :: \"'a set\"\nshows \"|{X. X \\<subseteq> A \\<and> countable X \\<and> X \\<noteq> {}}| \\<le>o |{f::nat \\<Rightarrow> 'a. range f \\<subseteq> A}|\"\napply(rule card_of_ordLeqI[of from_nat_into]) using inj_on_from_nat_into\nunfolding inj_on_def by auto\n\nlemma card_of_countable_sets_Func:\n\"|{X. X \\<subseteq> A \\<and> countable X \\<and> X \\<noteq> {}}| \\<le>o |A| ^c natLeq\"\nusing card_of_countable_sets_range card_of_Func_UNIV[THEN ordIso_symmetric]\nunfolding cexp_def Field_natLeq Field_card_of\nby (rule ordLeq_ordIso_trans)\n\nlemma ordLeq_countable_subsets:\n\"|A| \\<le>o |{X. X \\<subseteq> A \\<and> countable X}|\"\napply (rule card_of_ordLeqI[of \"\\<lambda> a. {a}\"]) unfolding inj_on_def by auto\n\nlemma finite_countable_subset:\n\"finite {X. X \\<subseteq> A \\<and> countable X} \\<longleftrightarrow> finite A\"\napply default\n apply (erule contrapos_pp)\n apply (rule card_of_ordLeq_infinite)\n apply (rule ordLeq_countable_subsets)\n apply assumption\napply (rule finite_Collect_conjI)\napply (rule disjI1)\nby (erule finite_Collect_subsets)\n\nlemma rcset_to_rcset: \"countable A \\<Longrightarrow> rcset (the_inv rcset A) = A\"\n  apply (rule f_the_inv_into_f[unfolded inj_on_def image_iff])\n   apply transfer' apply simp\n  apply transfer' apply simp\n  done\n\nlemma Collect_Int_Times:\n\"{(x, y). R x y} \\<inter> A \\<times> B = {(x, y). R x y \\<and> x \\<in> A \\<and> y \\<in> B}\"\nby auto\n\ndefinition rel_cset :: \"('a \\<Rightarrow> 'b \\<Rightarrow> bool) \\<Rightarrow> 'a cset \\<Rightarrow> 'b cset \\<Rightarrow> bool\" where\n\"rel_cset R a b \\<longleftrightarrow>\n (\\<forall>t \\<in> rcset a. \\<exists>u \\<in> rcset b. R t u) \\<and>\n (\\<forall>t \\<in> rcset b. \\<exists>u \\<in> rcset a. R u t)\"\n\nlemma rel_cset_aux:\n\"(\\<forall>t \\<in> rcset a. \\<exists>u \\<in> rcset b. R t u) \\<and> (\\<forall>t \\<in> rcset b. \\<exists>u \\<in> rcset a. R u t) \\<longleftrightarrow>\n ((Grp {x. rcset x \\<subseteq> {(a, b). R a b}} (cimage fst))\\<inverse>\\<inverse> OO\n          Grp {x. rcset x \\<subseteq> {(a, b). R a b}} (cimage snd)) a b\" (is \"?L = ?R\")\nproof\n  assume ?L\n  def R' \\<equiv> \"the_inv rcset (Collect (split R) \\<inter> (rcset a \\<times> rcset b))\"\n  (is \"the_inv rcset ?L'\")\n  have L: \"countable ?L'\" by auto\n  hence *: \"rcset R' = ?L'\" unfolding R'_def by (intro rcset_to_rcset)\n  thus ?R unfolding Grp_def relcompp.simps conversep.simps\n  proof (intro CollectI case_prodI exI[of _ a] exI[of _ b] exI[of _ R'] conjI refl)\n    from * `?L` show \"a = cimage fst R'\" by transfer (auto simp: image_def Collect_Int_Times)\n  next\n    from * `?L` show \"b = cimage snd R'\" by transfer (auto simp: image_def Collect_Int_Times)\n  qed simp_all\nnext\n  assume ?R thus ?L unfolding Grp_def relcompp.simps conversep.simps\n    by transfer force\nqed\n\nbnf \"'a cset\"\n  map: cimage\n  sets: rcset\n  bd: natLeq\n  wits: \"cempty\"\n  rel: rel_cset\nproof -\n  show \"cimage id = id\" by transfer' simp\nnext\n  fix f g show \"cimage (g \\<circ> f) = cimage g \\<circ> cimage f\" by transfer' fastforce\nnext\n  fix C f g assume eq: \"\\<And>a. a \\<in> rcset C \\<Longrightarrow> f a = g a\"\n  thus \"cimage f C = cimage g C\" by transfer force\nnext\n  fix f show \"rcset \\<circ> cimage f = op ` f \\<circ> rcset\" by transfer' fastforce\nnext\n  show \"card_order natLeq\" by (rule natLeq_card_order)\nnext\n  show \"cinfinite natLeq\" by (rule natLeq_cinfinite)\nnext\n  fix C show \"|rcset C| \\<le>o natLeq\" by transfer (unfold countable_card_le_natLeq)\nnext\n  fix R S\n  show \"rel_cset R OO rel_cset S \\<le> rel_cset (R OO S)\"\n    unfolding rel_cset_def[abs_def] by fast\nnext\n  fix R\n  show \"rel_cset R =\n        (Grp {x. rcset x \\<subseteq> Collect (split R)} (cimage fst))\\<inverse>\\<inverse> OO\n         Grp {x. rcset x \\<subseteq> Collect (split R)} (cimage snd)\"\n  unfolding rel_cset_def[abs_def] rel_cset_aux by simp\nqed (transfer, 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/Library/Countable_Set_Type.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8479677506936879, "lm_q2_score": 0.8289388125473629, "lm_q1q2_score": 0.7029133803384839}}
{"text": "(*  Title:      HOL/Library/Subseq_Order.thy\n    Author:     Peter Lammich, Uni Muenster <peter.lammich@uni-muenster.de>\n    Author:     Florian Haftmann, TU Muenchen\n    Author:     Tobias Nipkow, TU Muenchen\n*)\n\nsection \\<open>Subsequence Ordering\\<close>\n\ntheory Subseq_Order\nimports Sublist\nbegin\n\ntext \\<open>\n  This theory defines subsequence ordering on lists. A list \\<open>ys\\<close> is a subsequence of a\n  list \\<open>xs\\<close>, iff one obtains \\<open>ys\\<close> by erasing some elements from \\<open>xs\\<close>.\n\\<close>\n\nsubsection \\<open>Definitions and basic lemmas\\<close>\n\ninstantiation list :: (type) ord\nbegin\n\ndefinition \"xs \\<le> ys \\<longleftrightarrow> subseq xs ys\" for xs ys :: \"'a list\"\ndefinition \"xs < ys \\<longleftrightarrow> xs \\<le> ys \\<and> \\<not> ys \\<le> xs\" for xs ys :: \"'a list\"\n\ninstance ..\n\nend\n\ninstance list :: (type) order\nproof\n  fix xs ys zs :: \"'a list\"\n  show \"xs < ys \\<longleftrightarrow> xs \\<le> ys \\<and> \\<not> ys \\<le> xs\"\n    unfolding less_list_def ..\n  show \"xs \\<le> xs\"\n    by (simp add: less_eq_list_def)\n  show \"xs = ys\" if \"xs \\<le> ys\" and \"ys \\<le> xs\"\n    using that unfolding less_eq_list_def\n    by (rule subseq_order.antisym)\n  show \"xs \\<le> zs\" if \"xs \\<le> ys\" and \"ys \\<le> zs\"\n    using that unfolding less_eq_list_def\n    by (rule subseq_order.order_trans)\nqed\n\nlemmas less_eq_list_induct [consumes 1, case_names empty drop take] =\n  list_emb.induct [of \"(=)\", folded less_eq_list_def]\nlemmas less_eq_list_drop = list_emb.list_emb_Cons [of \"(=)\", folded less_eq_list_def]\nlemmas le_list_Cons2_iff [simp, code] = subseq_Cons2_iff [folded less_eq_list_def]\nlemmas le_list_map = subseq_map [folded less_eq_list_def]\nlemmas le_list_filter = subseq_filter [folded less_eq_list_def]\nlemmas le_list_length = list_emb_length [of \"(=)\", folded less_eq_list_def]\n\nlemma less_list_length: \"xs < ys \\<Longrightarrow> length xs < length ys\"\n  by (metis list_emb_length subseq_same_length le_neq_implies_less less_list_def less_eq_list_def)\n\nlemma less_list_empty [simp]: \"[] < xs \\<longleftrightarrow> xs \\<noteq> []\"\n  by (metis less_eq_list_def list_emb_Nil order_less_le)\n\nlemma less_list_below_empty [simp]: \"xs < [] \\<longleftrightarrow> False\"\n  by (metis list_emb_Nil less_eq_list_def less_list_def)\n\nlemma less_list_drop: \"xs < ys \\<Longrightarrow> xs < x # ys\"\n  by (unfold less_le less_eq_list_def) (auto)\n\nlemma less_list_take_iff: \"x # xs < x # ys \\<longleftrightarrow> xs < ys\"\n  by (metis subseq_Cons2_iff less_list_def less_eq_list_def)\n\nlemma less_list_drop_many: \"xs < ys \\<Longrightarrow> xs < zs @ ys\"\n  by (metis subseq_append_le_same_iff subseq_drop_many order_less_le\n      self_append_conv2 less_eq_list_def)\n\nlemma less_list_take_many_iff: \"zs @ xs < zs @ ys \\<longleftrightarrow> xs < ys\"\n  by (metis less_list_def less_eq_list_def subseq_append')\n\nlemma less_list_rev_take: \"xs @ zs < ys @ zs \\<longleftrightarrow> xs < ys\"\n  by (unfold less_le less_eq_list_def) auto\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/Subseq_Order.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8479677430095496, "lm_q2_score": 0.8289388146603365, "lm_q1q2_score": 0.7029133757605368}}
{"text": "theory \"HOLCF-Meet\"\nimports HOLCF\nbegin\n\ntext \\<open>\nThis theory defines the $\\sqcap$ operator on HOLCF domains, and introduces a type class for domains\nwhere all finite meets exist.\n\\<close>\n\nsubsubsection \\<open>Towards meets: Lower bounds\\<close>\n\ncontext po\nbegin\ndefinition is_lb :: \"'a set \\<Rightarrow> 'a \\<Rightarrow> bool\" (infix \">|\" 55) where\n  \"S >| x \\<longleftrightarrow> (\\<forall>y\\<in>S. x \\<sqsubseteq> y)\"\n\nlemma is_lbI: \"(!!x. x \\<in> S ==> l \\<sqsubseteq> x) ==> S >| l\"\n  by (simp add: is_lb_def)\n\nlemma is_lbD: \"[|S >| l; x \\<in> S|] ==> l \\<sqsubseteq> x\"\n  by (simp add: is_lb_def)\n\nlemma is_lb_empty [simp]: \"{} >| l\"\n  unfolding is_lb_def by fast\n\nlemma is_lb_insert [simp]: \"(insert x A) >| y = (y \\<sqsubseteq> x \\<and> A >| y)\"\n  unfolding is_lb_def by fast\n\nlemma is_lb_downward: \"[|S >| l; y \\<sqsubseteq> l|] ==> S >| y\"\n  unfolding is_lb_def by (fast intro: below_trans)\n\nsubsubsection \\<open>Greatest lower bounds\\<close>\n\ndefinition is_glb :: \"'a set \\<Rightarrow> 'a \\<Rightarrow> bool\" (infix \">>|\" 55) where\n  \"S >>| x \\<longleftrightarrow> S >| x \\<and> (\\<forall>u. S >| u --> u \\<sqsubseteq> x)\"\n\ndefinition glb :: \"'a set \\<Rightarrow> 'a\" (\"\\<Sqinter>_\" [60]60) where\n  \"glb S = (THE x. S >>| x)\" \n\ntext \\<open>Access to the definition as inference rule\\<close>\n\nlemma is_glbD1: \"S >>| x ==> S >| x\"\n  unfolding is_glb_def by fast\n\nlemma is_glbD2: \"[|S >>| x; S >| u|] ==> u \\<sqsubseteq> x\"\n  unfolding is_glb_def by fast\n\nlemma (in po) is_glbI: \"[|S >| x; !!u. S >| u ==> u \\<sqsubseteq> x|] ==> S >>| x\"\n  unfolding is_glb_def by fast\n\nlemma is_glb_above_iff: \"S >>| x ==> u \\<sqsubseteq> x \\<longleftrightarrow> S >| u\"\n  unfolding is_glb_def is_lb_def by (metis below_trans)\n\ntext \\<open>glbs are unique\\<close>\n\nlemma is_glb_unique: \"[|S >>| x; S >>| y|] ==> x = y\"\n  unfolding is_glb_def is_lb_def by (blast intro: below_antisym)\n\ntext \\<open>technical lemmas about @{term glb} and @{term is_glb}\\<close>\n\nlemma is_glb_glb: \"M >>| x ==> M >>| glb M\"\n  unfolding glb_def by (rule theI [OF _ is_glb_unique])\n\nlemma glb_eqI: \"M >>| l ==> glb M = l\"\n  by (rule is_glb_unique [OF is_glb_glb])\n\nlemma is_glb_singleton: \"{x} >>| x\"\n  by (simp add: is_glb_def)\n\nlemma glb_singleton [simp]: \"glb {x} = x\"\n  by (rule is_glb_singleton [THEN glb_eqI])\n\nlemma is_glb_bin: \"x \\<sqsubseteq> y ==> {x, y} >>| x\"\n  by (simp add: is_glb_def)\n\nlemma glb_bin: \"x \\<sqsubseteq> y ==> glb {x, y} = x\"\n  by (rule is_glb_bin [THEN glb_eqI])\n\nlemma is_glb_maximal: \"[|S >| x; x \\<in> S|] ==> S >>| x\"\n  by (erule is_glbI, erule (1) is_lbD)\n\nlemma glb_maximal: \"[|S >| x; x \\<in> S|] ==> glb S = x\"\n  by (rule is_glb_maximal [THEN glb_eqI])\n\nlemma glb_above: \"S >>| z \\<Longrightarrow> x \\<sqsubseteq> glb S \\<longleftrightarrow> S >| x\"\n  by (metis glb_eqI is_glb_above_iff)\nend\n\nlemma (in cpo) Meet_insert: \"S >>| l \\<Longrightarrow> {x, l} >>| l2 \\<Longrightarrow> insert x S >>| l2\"\n  apply (rule is_glbI)\n  apply (metis is_glb_above_iff is_glb_def is_lb_insert)\n  by (metis is_glb_above_iff is_glb_def is_glb_singleton is_lb_insert)\n\ntext \\<open>Binary, hence finite meets.\\<close>\n\nclass Finite_Meet_cpo = cpo +\n  assumes binary_meet_exists: \"\\<exists> l. l \\<sqsubseteq> x \\<and> l \\<sqsubseteq> y \\<and> (\\<forall> z. z \\<sqsubseteq> x \\<longrightarrow> z \\<sqsubseteq> y \\<longrightarrow> z \\<sqsubseteq> l)\"\nbegin\n\n  lemma binary_meet_exists': \"\\<exists>l. {x, y} >>| l\"\n    using binary_meet_exists[of x y]\n    unfolding is_glb_def is_lb_def\n    by auto\n\n  lemma finite_meet_exists:\n    assumes \"S \\<noteq> {}\"\n    and \"finite S\"\n    shows \"\\<exists>x. S >>| x\"\n  using \\<open>S \\<noteq> {}\\<close>\n  apply (induct rule: finite_induct[OF \\<open>finite S\\<close>])\n  apply (erule notE, rule refl)[1]\n  apply (case_tac \"F = {}\")\n  apply (metis is_glb_singleton)\n  apply (metis Meet_insert binary_meet_exists')\n  done\nend\n\ndefinition meet :: \"'a::cpo \\<Rightarrow> 'a \\<Rightarrow> 'a\" (infix \"\\<sqinter>\" 80) where\n  \"x \\<sqinter> y = (if \\<exists> z. {x, y} >>| z then glb {x, y} else x)\"\n\nlemma meet_def': \"(x::'a::Finite_Meet_cpo) \\<sqinter> y = glb {x, y}\"\n  unfolding meet_def by (metis binary_meet_exists')\n\n\n\nlemma meet_bot1[simp]:\n  fixes y :: \"'a :: {Finite_Meet_cpo,pcpo}\"\n  shows \"(\\<bottom> \\<sqinter> y) = \\<bottom>\" unfolding meet_def' by (metis minimal po_class.glb_bin)\nlemma meet_bot2[simp]:\n  fixes x :: \"'a :: {Finite_Meet_cpo,pcpo}\"\n  shows \"(x \\<sqinter> \\<bottom>) = \\<bottom>\" by (metis meet_bot1 meet_comm)\n\nlemma meet_below1[intro]:\n  fixes x y :: \"'a :: Finite_Meet_cpo\"\n  assumes \"x \\<sqsubseteq> z\"\n  shows \"(x \\<sqinter> y) \\<sqsubseteq> z\" unfolding meet_def' by (metis assms binary_meet_exists' below_trans glb_eqI is_glbD1 is_lb_insert)\nlemma meet_below2[intro]:\n  fixes x y :: \"'a :: Finite_Meet_cpo\"\n  assumes \"y \\<sqsubseteq> z\"\n  shows \"(x \\<sqinter> y) \\<sqsubseteq> z\" unfolding meet_def' by (metis assms binary_meet_exists' below_trans glb_eqI is_glbD1 is_lb_insert)\n\nlemma meet_above_iff:\n  fixes x y z :: \"'a :: Finite_Meet_cpo\"\n  shows \"z \\<sqsubseteq> x \\<sqinter> y \\<longleftrightarrow> z \\<sqsubseteq> x \\<and> z \\<sqsubseteq> y\"\nproof-\n  obtain g where \"{x,y} >>| g\" by (metis binary_meet_exists')\n  thus ?thesis\n  unfolding meet_def' by (simp add: glb_above)\nqed\n\nlemma below_meet[simp]:\n  fixes x y :: \"'a :: Finite_Meet_cpo\"\n  assumes \"x \\<sqsubseteq> z\"\n  shows \"(x \\<sqinter> z) = x\" by (metis assms glb_bin meet_def')\n\n\n\nlemma meet_aboveI:\n  fixes x y z :: \"'a :: Finite_Meet_cpo\"\n  shows \"z \\<sqsubseteq> x \\<Longrightarrow> z \\<sqsubseteq> y \\<Longrightarrow> z \\<sqsubseteq> x \\<sqinter> y\" by (simp add: meet_above_iff)\n\nlemma is_meetI:\n  fixes x y z :: \"'a :: Finite_Meet_cpo\"\n  assumes \"z \\<sqsubseteq> x\"\n  assumes \"z \\<sqsubseteq> y\"\n  assumes \"\\<And> a. \\<lbrakk> a \\<sqsubseteq> x ; a \\<sqsubseteq> y \\<rbrakk> \\<Longrightarrow> a \\<sqsubseteq> z\"\n  shows \"x \\<sqinter> y = z\"\nby (metis assms below_antisym meet_above_iff below_refl)\n\nlemma meet_assoc[simp]: \"((x::'a::Finite_Meet_cpo) \\<sqinter> y) \\<sqinter> z = x \\<sqinter> (y \\<sqinter> z)\"\n  apply (rule is_meetI)\n  apply (metis below_refl meet_above_iff)\n  apply (metis below_refl meet_below2)\n  apply (metis meet_above_iff)\n  done\n\nlemma meet_self[simp]: \"r \\<sqinter> r = (r::'a::Finite_Meet_cpo)\"\n  by (metis below_refl is_meetI)\n\n\n\nlemma meet_monofun1:\n  fixes y :: \"'a :: Finite_Meet_cpo\"\n  shows \"monofun (\\<lambda>x. (x \\<sqinter> y))\"\n  by (rule monofunI)(auto simp add: meet_above_iff)\n\nlemma chain_meet1:\n  fixes y :: \"'a :: Finite_Meet_cpo\"\n  assumes \"chain Y\"\n  shows \"chain (\\<lambda> i. Y i \\<sqinter> y)\"\nby (rule chainI) (auto simp add: meet_above_iff intro: chainI chainE[OF assms])\n\nclass cont_binary_meet = Finite_Meet_cpo +\n  assumes meet_cont': \"chain Y \\<Longrightarrow> (\\<Squnion> i. Y i) \\<sqinter> y = (\\<Squnion> i. Y i \\<sqinter> y)\"\n\nlemma meet_cont1:\n  fixes y :: \"'a :: cont_binary_meet\"\n  shows \"cont (\\<lambda>x. (x \\<sqinter> y))\"\n  by (rule contI2[OF meet_monofun1]) (simp add: meet_cont')\n\nlemma meet_cont2: \n  fixes x :: \"'a :: cont_binary_meet\"\n  shows \"cont (\\<lambda>y. (x \\<sqinter> y))\" by (subst meet_comm, rule meet_cont1)\n\nlemma meet_cont[cont2cont,simp]:\"cont f \\<Longrightarrow> cont g \\<Longrightarrow> cont (\\<lambda>x. (f x \\<sqinter> (g x::'a::cont_binary_meet)))\"\n  apply (rule cont2cont_case_prod[where g = \"\\<lambda> x. (f x, g x)\" and f = \"\\<lambda> p x y . x \\<sqinter> y\", simplified])\n  apply (rule meet_cont1)\n  apply (rule meet_cont2)\n  apply (metis cont2cont_Pair)\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/SeLFiE/Example/afp-2020-05-16/thys/Launchbury/HOLCF-Meet.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8596637505099168, "lm_q2_score": 0.817574478416099, "lm_q1q2_score": 0.7028391424363727}}
{"text": "(*<*)\n(*:maxLineLen=78:*)\ntheory RecursiveVDMExamples\nimports VDMToolkit\nbegin\n\n(********************************************************)\nsection \\<open>Constructive type (\\<^typ>\\<open>\\<nat>\\<close>) recursion primitive and function\\<close>\n\n\\<comment> \\<open>Automatic with pattern matching only, if-then-else fails\\<close>\nprimrec factN :: \\<open>\\<nat> \\<Rightarrow> \\<nat>\\<close> where \n\\<open>factN n = (if n = 0 then 1 else n * (factN (n - 1)))\\<close>\n\n\\<comment> \\<open>Automatic but forces \\<^typ>\\<open>\\<nat>\\<close> constructors\\<close>\nprimrec factN :: \\<open>\\<nat> \\<Rightarrow> \\<nat>\\<close> where\n  \\<open>factN       0 = 1\\<close> \n| \\<open>factN (Suc n) = (n * (factN n))\\<close>\n\n\\<comment> \\<open>Pattern completeness missed is allowed as a warning\\<close>\nprimrec factNmissingConstructors :: \\<open>\\<nat> \\<Rightarrow> \\<nat>\\<close> where\n  \\<open>factNmissingConstructors 0 = 1\\<close> \n\n\\<comment> \\<open>Automatic termination with pattern matching\\<close>\nfun factN' :: \\<open>\\<nat> \\<Rightarrow> \\<nat>\\<close> where \n\\<open>factN' n = (if n = 0 then 1 else n * (factN' (n - 1)))\\<close> \n\n\\<comment> \\<open>Pattern completeness missed is provided as undefined\\<close>\nfun factNincmplete' :: \\<open>\\<nat> \\<Rightarrow> \\<nat>\\<close> where \n\\<open>factNincmplete' (Suc n) = (factNincmplete' n)\\<close> \n\n(********************************************************)\nsection \\<open>Algebraic type  (\\<^typ>\\<open>\\<int>\\<close>) recursion primitive and function\\<close>\n\n\\<comment> \\<open>Primitive recursion doesn't work for non-constructive types\\<close>\nprimrec factZ :: \\<open>VDMNat \\<Rightarrow> VDMNat\\<close> where \n  \\<open>factZ 0 = 1\\<close>\n\n\\<comment> \\<open>Function works but can't find termination proof automatically\\<close>\nfun factZ :: \\<open>VDMNat \\<Rightarrow> VDMNat\\<close> where \n\\<open>factZ n = (if n = 0 then 1 else n * (factZ (n - 1)))\\<close> \n\n\\<comment> \\<open>User must provide termination argument\\<close>\nfunction (domintros) factZ :: \\<open>VDMNat \\<Rightarrow> VDMNat\\<close> where \n\\<open>factZ n = (if n = 0 then 1 else n * (factZ (n - 1)))\\<close> \n  \\<comment> \\<open>pattern consistency goal\\<close>\n   apply simp\n  \\<comment> \\<open>pattern completeness goal\\<close>\n  by simp\n\n  \\<comment> \\<open>Recursive termination goal\\<close>\n  termination\n    oops\n\n  \\<comment> \\<open>Various theorems about recursion\\<close>\n    find_theorems name:\"factZ\"\n    \n(********************************************************)\nsection \\<open>Simple recursion catering for VDM specification\\<close>\n\n\\<comment> \\<open>Automatically generated: implicitly inferred input type invariant check\\<close>\ndefinition pre_factV :: \\<open>VDMNat \\<Rightarrow> \\<bool>\\<close> where \n\\<open>pre_factV n \\<equiv> inv_VDMNat n\\<close>\n\n\\<comment> \\<open>VDM only operates if precondition is satisfied\\<close>\nfunction (domintros) factV :: \\<open>VDMNat \\<Rightarrow> VDMNat\\<close> where\n\\<open>factV n = (if pre_factV n then (if n = 0 then 1 else n * (factV (n - 1))) else undefined)\\<close>\n  by (pat_completeness, auto) \\<^marker>\\<open>tag sledgehammer\\<close>\n\n  \\<comment> \\<open>Well formedness expression relating conditions for every recursive and original calls\\<close>\n  abbreviation factV_wf :: \\<open>(VDMNat \\<times> VDMNat) set\\<close> where\n    \\<open>factV_wf \\<equiv> { (n - 1, n) | n . pre_factV n \\<and> n \\<noteq> 0 }\\<close>\n  \n  \\<comment> \\<open>Notice the psimps (partial function) simplification rules and guarding domain predicates\\<close>\n  find_theorems name:\"factV\"\n\n  \\<comment> \\<open>For VDM nat and int, we have proved general well formedness relations theorem\\<close>\n  termination\n    apply (relation \\<open>(gen_VDMNat_term factV_wf)\\<close>) \n    \\<comment> \\<open>This enables sledgehammer to find the well-formedness part of the proof\\<close>\n    using l_gen_VDMNat_term_wf apply blast \\<^marker>\\<open>tag sledgehammer\\<close>\n    \\<comment> \\<open>Remains to be shown that the local recursive relation is within the general relation space\\<close>\n    (*Sledgehammering... No proof found *)\n    oops\n\n  termination \n    apply (relation \\<open>(gen_VDMNat_term factV_wf)\\<close>) \n    using l_gen_VDMNat_term_wf apply blast \\<^marker>\\<open>tag sledgehammer\\<close>\n    \\<comment> \\<open>Even though sledgehammer struggles, the proof is in fact trivial\\<close>\n    by (simp add: pre_factV_def int_ge_less_than_def)\n\n  \\<comment> \\<open>Notice the psimps (partial function) simplification rules are gone, and simps (total function) are in place instead\\<close>\n  find_theorems name:factV\n\ndefinition largest_wf_int_rel :: \"\\<int> \\<Rightarrow> (\\<int> \\<times> \\<int>) set\" where\n\"largest_wf_int_rel d = {(z', z). d \\<le> z' \\<and> z' < z}\"\n\n\\<comment> \\<open>Flag can also generate this lemma (and proof sketch) to ensure the recursive relation is a fix-point\\<close>\n\\<comment> \\<open>This is useful when recursive relation is not within largest upper bound to discover how to prove it well formed\\<close>\nlemma l_fact_term_valid: \\<open>(gen_VDMNat_term factV_wf) = factV_wf\\<close>\n  apply (simp )\n  apply (intro equalityI subsetI)\n  apply (simp_all add: pre_factV_def int_ge_less_than_def case_prod_beta)\n  by auto\n\n(********************************************************)\nsection \\<open>VDM recursion over sets\\<close>\n\n\\<comment> \\<open>  \n  sumset: set of nat -> nat \n  sumset(s) == if s = {} then 0 else let e in set s in sumset(s - {e}) + e\n  pre (forall n in set s & n > 5)\n  --@IsaMeasure({(x - { let e in set x in e }, x) | x : set of nat & x <> {}}) \n  --@Witness(sumset({ 1 }))\n  measure card s;\n\\<close>\n\n\\<comment> \\<open>Automatically generated: implicitly inferred type invariant check + user defined pre\\<close>\ndefinition pre_sumset :: \\<open>VDMNat VDMSet \\<Rightarrow> \\<bool>\\<close> where\n  \\<open>pre_sumset s \\<equiv> inv_VDMSet' inv_VDMNat s \\<and> (\\<forall> n \\<in> s . n > 5)\\<close>\n\n\\<comment> \\<open>Automatically generated def set: inferred from function AST + signature\\<close>\n\\<comment> \\<open>Notice the unfolding is staggered and deep into the AST term\\<close>\nlemmas pre_sumset_defs = pre_sumset_def inv_VDMSet'_defs inv_VDMNat_def \n\n\\<comment> \\<open>Mostly verbatim translation from VDM; let-in-set becomes Isabelle's Hilbert Choice binder (\\<some>)\\<close>\nfunction (domintros) sumset :: \\<open>VDMNat VDMSet \\<Rightarrow> VDMNat\\<close> where \n  \\<open>sumset s = (if pre_sumset s then \n                  (if s = {} then 0 else \n                      let e = (\\<some> x . x \\<in> s) in sumset (s - {e}) + e) \n                   else undefined)\\<close>\n  \\<comment> \\<open>Automatically generated proof for pattern compatibility and completeness\\<close>\n  \\<comment> \\<open>Users will have to finish this before proceeding if proof suggestion fails!\\<close>\n  by (pat_completeness, auto)\n\n  \\<comment> \\<open>Recursive definitions available, yet as partial functions (psimps + dom predicate)\\<close>\n  find_theorems name:\"sumset\"\n\n  \\<comment> \\<open>Well founded recursive relation translated from user defined @IsaMeasure\\<close>\n  \\<comment> \\<open>We automatically infer recursive relations for this specific (commonly used) kind of set recursion\\<close>\n  \\<comment> \\<open>It is crucial for termination proof that pre condition is included, which translator does automatically\\<close>\n  abbreviation sumset_wf_rel :: \\<open>(VDMNat VDMSet \\<times> VDMNat VDMSet) set\\<close> where\n    \\<open>sumset_wf_rel \\<equiv> { (s - {(\\<some> e . e \\<in> s)}, s)| s . pre_sumset s \\<and> s \\<noteq> {}}\\<close>\n\n  \\<comment> \\<open>Translator infers recursive relation well formedness lemma being about sets\\<close>\n  lemma l_sumset_rel_wf: \\<open>wf (gen_set_term sumset_wf_rel)\\<close>\n    \\<comment> \\<open>Proof in this case is discovered by sledgehammer\\<close>\n    using l_gen_set_term_wf by blast \\<^marker>\\<open>tag sledgehammer\\<close>\n\n  \\<comment> \\<open>Termination proof setup is automatically generated\\<close>\n  termination\n    apply (relation \\<open>(gen_set_term sumset_wf_rel)\\<close>)\n    using l_sumset_rel_wf apply blast \\<^marker>\\<open>tag sledgehammer\\<close>\n    oops\n\n  \\<comment> \\<open>Verbatim copy of failed goal. Perhaps could be auto generated? (Problem it might be spurious)\\<close>\n  lemma l_pre_sumset_sumset_wf_rel: \n     \\<open>pre_sumset s \\<Longrightarrow> s \\<noteq> {} \\<Longrightarrow> (s - {(\\<some> x. x \\<in> s)}, s) \\<in> (gen_set_term sumset_wf_rel)\\<close>\n    unfolding gen_set_term_def apply (simp add: pre_sumset_defs)\\<^marker>\\<open>tag manual\\<close>\n    by (metis Diff_subset member_remove psubsetI remove_def some_in_eq)\\<^marker>\\<open>tag sledgehammer\\<close>\n\n  \\<comment> \\<open>Lemma enables sledgehammer to find the termination proof\\<close>\n  termination\n    apply (relation \\<open>(gen_set_term sumset_wf_rel)\\<close>)\n    using l_sumset_rel_wf apply blast \\<^marker>\\<open>tag sledgehammer\\<close>\n    using l_pre_sumset_sumset_wf_rel by presburger \\<^marker>\\<open>tag sledgehammer\\<close>\n\n  \\<comment> \\<open>Recursive definitions available as total functions (simps)\\<close>\n  find_theorems name:\"sumset\"\n\n  \\<comment> \\<open>Recursion over maps is similar, if more involved; see paper source\\<close>\n\n  \\<comment> \\<open>VDM measures are not expressive enough for non-functional measures?\\<close>\n\n(********************************************************)\nsection \\<open>Complex recursion example with automation support\\<close>\n\n\\<comment> \\<open>ack: nat * nat -> nat \n    ack(m,n) == if m = 0 then n+1\n           else if n = 0 then ack(m-1, 1)\n           else               ack(m-1, ack(m, (n-1)))\n    --@IsaMeasure( pair_less_VDMNat )\n    measure is not yet specified;\n  \\<close>\n\ndefinition pre_ack :: \\<open>VDMNat \\<Rightarrow> VDMNat \\<Rightarrow> \\<bool>\\<close> where\n  \\<open>pre_ack m n \\<equiv> inv_VDMNat m \\<and> inv_VDMNat n\\<close>\nlemmas pre_ack_defs = pre_ack_def \n\nfunction (domintros) ack :: \\<open>VDMNat \\<Rightarrow> VDMNat \\<Rightarrow> VDMNat\\<close> where\n  \\<open>ack m n = (if pre_ack m n then\n                       if m = 0 then n+1\n                  else if n = 0 then ack (m-1) 1\n                  else               ack (m-1) (ack m (n-1))\n                  else               undefined)\\<close>\n  by (pat_completeness, auto) \\<^marker>\\<open>tag sledgehammer\\<close>\n\n  \\<comment> \\<open>User defined well formed relation, yet as part of Isabelle's high levels of automation armoury \\<close>\n  abbreviation ack_wf :: \\<open>((VDMNat \\<times> VDMNat) \\<times> (VDMNat \\<times> VDMNat)) VDMSet\\<close> \n    where \\<open>ack_wf \\<equiv> pair_less_VDMNat\\<close>\n\n  \\<comment> \\<open>Proof is manual, but mostly discovered by sledgehammer\\<close>\n  termination \n    apply (relation ack_wf)\\<^marker>\\<open>tag manual\\<close>\n    using wf_pair_less_VDMNat apply blast \\<^marker>\\<open>tag sledgehammer\\<close>\n    apply (simp add: l_pair_less_VDMNat_I1 pre_ack_def) \\<^marker>\\<open>tag sledgehammer\\<close>\n    apply (simp add:  pre_ack_defs) \\<^marker>\\<open>tag sledgehammer\\<close>\n    by (simp add: pair_less_VDMNat_def pre_ack_def) \\<^marker>\\<open>tag sledgehammer\\<close>\n\n(********************************************************)\nsection \\<open>Complex recursion where Isabelle proof discovers missing VDM specification!\\<close>\n\n\\<comment> \\<open>perm: int * int * int -> int \n    perm(m,n,r) == if 0 < r then perm(m, r-1, n) \n              else if 0 < n then perm(r, n-1, m) else m\n    measure is not yet specified;\\<close>\n\ndefinition pre_perm :: \\<open>VDMInt \\<Rightarrow> VDMInt \\<Rightarrow> VDMInt \\<Rightarrow> \\<bool>\\<close> where\n  \\<open>pre_perm m n r \\<equiv> inv_VDMInt m \\<and> inv_VDMInt n \\<and> inv_VDMInt r\\<close>\nlemmas pre_perm_defs = pre_perm_def inv_VDMInt_def inv_True_def\n\nfunction (domintros) perm :: \\<open>VDMInt \\<Rightarrow> VDMInt \\<Rightarrow> VDMInt \\<Rightarrow> VDMInt\\<close> where\n  \\<open>perm m n r = (if pre_perm m n r then\n                         if 0 < r then perm m (r-1) n \n                    else if 0 < n then perm r (n-1) m else m\n                 else undefined)\\<close>\n  by (pat_completeness, auto) \\<^marker>\\<open>tag sledgehammer\\<close>\n\n  \\<comment> \\<open>Inferred recursive relation based on recursive call patterns and VDM AST\\<close>\n  definition perm_wf_rel :: \\<open>((VDMInt \\<times> VDMInt \\<times> VDMInt) \\<times> \n                              (VDMInt \\<times> VDMInt \\<times> VDMInt)) VDMSet\\<close>\n    where \\<open>perm_wf_rel \\<equiv> \n     { ((m, r-1, n), (m, n, r)) | m r n . pre_perm m n r \\<and> 0 < r } \\<union> \n     { ((r, n-1, m), (m, n, r)) | m r n . pre_perm m n r \\<and> \\<not> 0 < r \\<and> 0 < n }\\<close>\n\n  \\<comment> \\<open>Automatically generated lemma left for the user to discharge\\<close>\n  \\<comment> \\<open>This will force the user to think of a VDM measure to use, which can be\n      expressed in this case using the measure method\\<close>\n  lemma l_perm_wf_rel: \\<open>wf perm_wf_rel\\<close>\n    sorry\n\n  termination \n    apply (relation \\<open>perm_wf_rel\\<close>) \n      apply (simp add: l_perm_wf_rel) \\<^marker>\\<open>tag sledgehammer\\<close>\n    \\<comment> \\<open>Sledgehammer fails here, yet the proof is \"easy\" \\<close>\n    by (simp_all add: perm_wf_rel_def)  \\<^marker>\\<open>tag manual\\<close>\n\n  (*----------------------------------------------------------------*)\n  subsection \\<open>Distilling missing proof: take 1\\<close>\n\n  \\<comment> \\<open>Suggests a VDM measure as max(m+n+r, 0)\\<close>\n  lemma l_perm_wf_rel_VDM_measure: \n    \\<open>perm_wf_rel \\<subseteq> measure (\\<lambda> (m, r, n) . nat (max 0 (m+r+n)))\\<close>\n    apply (intro subsetI, case_tac x)\n      apply (simp add: pre_perm_defs perm_wf_rel_def case_prod_beta max_def)\n       apply (elim disjE conjE, simp_all) \n       nitpick\n       \\<comment> \\<open>Counter example shows the recursion would fail for certain inputs!\\<close>\n       \\<comment> \\<open>It suggests a precondition is needed.\\<close>\n       \\<comment> \\<open>@NB would quickcheck find it?\\<close>\n       sorry\n\n  \\<comment> \\<open>If measure lemma is proved, sledgehammer can find the missing proof\\<close>\n  lemma l_perm_wf_rel': \\<open>wf perm_wf_rel\\<close>\n    using l_perm_wf_rel_VDM_measure wf_subset by blast\n\n  (*----------------------------------------------------------------*)\n  subsection \\<open>Distilling missing proof: take 2\\<close>\n\n  \\<comment> \\<open>Reviewed VDM specification must include:\n      * pre ((0 < r or 0 < n) => m+n+r > 0)   \n      * measure maxs({m+n+r, 0});    \n     \\<close>\n  definition pre_perm' :: \\<open>VDMInt \\<Rightarrow> VDMInt \\<Rightarrow> VDMInt \\<Rightarrow> \\<bool>\\<close> where\n    \\<open>pre_perm' m n r \\<equiv> pre_perm m n r \\<and> ((0 < r \\<or> 0 < n) \\<longrightarrow> m+n+r > 0)\\<close>\n  lemmas pre_perm'_defs = pre_perm'_def pre_perm_defs\n\n  definition perm_wf_rel' :: \\<open>((VDMInt \\<times> VDMInt \\<times> VDMInt) \\<times> \n                              (VDMInt \\<times> VDMInt \\<times> VDMInt)) VDMSet\\<close>\n    where \\<open>perm_wf_rel' \\<equiv> \n     { ((m, r-1, n), (m, n, r)) | m r n . pre_perm' m n r \\<and> 0 < r } \\<union> \n     { ((r, n-1, m), (m, n, r)) | m r n . pre_perm' m n r \\<and> \\<not> 0 < r \\<and> 0 < n }\\<close>\n\nfunction (domintros) perm' :: \\<open>VDMInt \\<Rightarrow> VDMInt \\<Rightarrow> VDMInt \\<Rightarrow> VDMInt\\<close> where\n  \\<open>perm' m n r = (if pre_perm' m n r then\n                         if 0 < r then perm' m (r-1) n \n                    else if 0 < n then perm' r (n-1) m else m\n                 else undefined)\\<close>\n  by (pat_completeness, auto) \\<^marker>\\<open>tag sledgehammer\\<close>\n\n  lemma l_perm_wf_rel_VDM_measure':\n    \\<open>perm_wf_rel' \\<subseteq> measure (\\<lambda> (m, r, n) . nat (max 0 (m+r+n)))\\<close>\n    apply (intro subsetI, case_tac x)\n      apply (simp add: pre_perm'_defs perm_wf_rel'_def case_prod_beta max_def)\n       apply (elim disjE conjE, simp_all) \n  done\n\n  \\<comment> \\<open>With the lemma proved, sledgehammer can find the missing proof on updated spec\\<close>\n  lemma l_perm_wf_rel'': \\<open>wf perm_wf_rel'\\<close>\n    using l_perm_wf_rel_VDM_measure' wf_subset by blast\n\n  termination \n    apply (relation \\<open>perm_wf_rel'\\<close>) \n      apply (simp add: l_perm_wf_rel'') \\<^marker>\\<open>tag sledgehammer\\<close>\n    \\<comment> \\<open>Sledgehammer fails here, yet the proof is \"easy\" \\<close>\n    by (simp_all add: perm_wf_rel'_def)  \\<^marker>\\<open>tag manual\\<close>\n\nend\n(*>*)", "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/pub/recursion/RecursiveVDMExamples.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8596637577007393, "lm_q2_score": 0.8175744695262775, "lm_q1q2_score": 0.7028391406731483}}
{"text": "(*  Title:      HOL/Analysis/Path_Connected.thy\n    Authors:    LC Paulson and Robert Himmelmann (TU Muenchen), based on material from HOL Light\n*)\n\nsection \\<open>Path-Connectedness\\<close>\n\ntheory Path_Connected\nimports\n  Starlike\n  T1_Spaces\nbegin\n\nsubsection \\<open>Paths and Arcs\\<close>\n\ndefinition\\<^marker>\\<open>tag important\\<close> path :: \"(real \\<Rightarrow> 'a::topological_space) \\<Rightarrow> bool\"\n  where \"path g \\<longleftrightarrow> continuous_on {0..1} g\"\n\ndefinition\\<^marker>\\<open>tag important\\<close> pathstart :: \"(real \\<Rightarrow> 'a::topological_space) \\<Rightarrow> 'a\"\n  where \"pathstart g = g 0\"\n\ndefinition\\<^marker>\\<open>tag important\\<close> pathfinish :: \"(real \\<Rightarrow> 'a::topological_space) \\<Rightarrow> 'a\"\n  where \"pathfinish g = g 1\"\n\ndefinition\\<^marker>\\<open>tag important\\<close> path_image :: \"(real \\<Rightarrow> 'a::topological_space) \\<Rightarrow> 'a set\"\n  where \"path_image g = g ` {0 .. 1}\"\n\ndefinition\\<^marker>\\<open>tag important\\<close> reversepath :: \"(real \\<Rightarrow> 'a::topological_space) \\<Rightarrow> real \\<Rightarrow> 'a\"\n  where \"reversepath g = (\\<lambda>x. g(1 - x))\"\n\ndefinition\\<^marker>\\<open>tag important\\<close> joinpaths :: \"(real \\<Rightarrow> 'a::topological_space) \\<Rightarrow> (real \\<Rightarrow> 'a) \\<Rightarrow> real \\<Rightarrow> 'a\"\n    (infixr \"+++\" 75)\n  where \"g1 +++ g2 = (\\<lambda>x. if x \\<le> 1/2 then g1 (2 * x) else g2 (2 * x - 1))\"\n\ndefinition\\<^marker>\\<open>tag important\\<close> simple_path :: \"(real \\<Rightarrow> 'a::topological_space) \\<Rightarrow> bool\"\n  where \"simple_path g \\<longleftrightarrow>\n     path g \\<and> (\\<forall>x\\<in>{0..1}. \\<forall>y\\<in>{0..1}. g x = g y \\<longrightarrow> x = y \\<or> x = 0 \\<and> y = 1 \\<or> x = 1 \\<and> y = 0)\"\n\ndefinition\\<^marker>\\<open>tag important\\<close> arc :: \"(real \\<Rightarrow> 'a :: topological_space) \\<Rightarrow> bool\"\n  where \"arc g \\<longleftrightarrow> path g \\<and> inj_on g {0..1}\"\n\n\nsubsection\\<^marker>\\<open>tag unimportant\\<close>\\<open>Invariance theorems\\<close>\n\nlemma path_eq: \"path p \\<Longrightarrow> (\\<And>t. t \\<in> {0..1} \\<Longrightarrow> p t = q t) \\<Longrightarrow> path q\"\n  using continuous_on_eq path_def by blast\n\nlemma path_continuous_image: \"path g \\<Longrightarrow> continuous_on (path_image g) f \\<Longrightarrow> path(f \\<circ> g)\"\n  unfolding path_def path_image_def\n  using continuous_on_compose by blast\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\nlemma path_translation_eq:\n  fixes g :: \"real \\<Rightarrow> 'a :: real_normed_vector\"\n  shows \"path((\\<lambda>x. a + x) \\<circ> g) = path g\"\n  using continuous_on_translation_eq path_def by blast\n\nlemma path_linear_image_eq:\n  fixes f :: \"'a::euclidean_space \\<Rightarrow> 'b::euclidean_space\"\n   assumes \"linear f\" \"inj f\"\n     shows \"path(f \\<circ> g) = path g\"\nproof -\n  from linear_injective_left_inverse [OF assms]\n  obtain h where h: \"linear h\" \"h \\<circ> f = id\"\n    by blast\n  then have g: \"g = h \\<circ> (f \\<circ> g)\"\n    by (metis comp_assoc id_comp)\n  show ?thesis\n    unfolding path_def\n    using h assms\n    by (metis g continuous_on_compose linear_continuous_on linear_conv_bounded_linear)\nqed\n\nlemma pathstart_translation: \"pathstart((\\<lambda>x. a + x) \\<circ> g) = a + pathstart g\"\n  by (simp add: pathstart_def)\n\nlemma pathstart_linear_image_eq: \"linear f \\<Longrightarrow> pathstart(f \\<circ> g) = f(pathstart g)\"\n  by (simp add: pathstart_def)\n\nlemma pathfinish_translation: \"pathfinish((\\<lambda>x. a + x) \\<circ> g) = a + pathfinish g\"\n  by (simp add: pathfinish_def)\n\nlemma pathfinish_linear_image: \"linear f \\<Longrightarrow> pathfinish(f \\<circ> g) = f(pathfinish g)\"\n  by (simp add: pathfinish_def)\n\nlemma path_image_translation: \"path_image((\\<lambda>x. a + x) \\<circ> g) = (\\<lambda>x. a + x) ` (path_image g)\"\n  by (simp add: image_comp path_image_def)\n\nlemma path_image_linear_image: \"linear f \\<Longrightarrow> path_image(f \\<circ> g) = f ` (path_image g)\"\n  by (simp add: image_comp path_image_def)\n\nlemma reversepath_translation: \"reversepath((\\<lambda>x. a + x) \\<circ> g) = (\\<lambda>x. a + x) \\<circ> reversepath g\"\n  by (rule ext) (simp add: reversepath_def)\n\nlemma reversepath_linear_image: \"linear f \\<Longrightarrow> reversepath(f \\<circ> g) = f \\<circ> reversepath g\"\n  by (rule ext) (simp add: reversepath_def)\n\nlemma joinpaths_translation:\n    \"((\\<lambda>x. a + x) \\<circ> g1) +++ ((\\<lambda>x. a + x) \\<circ> g2) = (\\<lambda>x. a + x) \\<circ> (g1 +++ g2)\"\n  by (rule ext) (simp add: joinpaths_def)\n\nlemma joinpaths_linear_image: \"linear f \\<Longrightarrow> (f \\<circ> g1) +++ (f \\<circ> g2) = f \\<circ> (g1 +++ g2)\"\n  by (rule ext) (simp add: joinpaths_def)\n\nlemma simple_path_translation_eq:\n  fixes g :: \"real \\<Rightarrow> 'a::euclidean_space\"\n  shows \"simple_path((\\<lambda>x. a + x) \\<circ> g) = simple_path g\"\n  by (simp add: simple_path_def path_translation_eq)\n\nlemma simple_path_linear_image_eq:\n  fixes f :: \"'a::euclidean_space \\<Rightarrow> 'b::euclidean_space\"\n  assumes \"linear f\" \"inj f\"\n    shows \"simple_path(f \\<circ> g) = simple_path g\"\n  using assms inj_on_eq_iff [of f]\n  by (auto simp: path_linear_image_eq simple_path_def path_translation_eq)\n\nlemma arc_translation_eq:\n  fixes g :: \"real \\<Rightarrow> 'a::euclidean_space\"\n  shows \"arc((\\<lambda>x. a + x) \\<circ> g) = arc g\"\n  by (auto simp: arc_def inj_on_def path_translation_eq)\n\nlemma arc_linear_image_eq:\n  fixes f :: \"'a::euclidean_space \\<Rightarrow> 'b::euclidean_space\"\n   assumes \"linear f\" \"inj f\"\n     shows  \"arc(f \\<circ> g) = arc g\"\n  using assms inj_on_eq_iff [of f]\n  by (auto simp: arc_def inj_on_def path_linear_image_eq)\n\n\nsubsection\\<^marker>\\<open>tag unimportant\\<close>\\<open>Basic lemmas about paths\\<close>\n\nlemma path_of_real: \"path complex_of_real\" \n  unfolding path_def by (intro continuous_intros)\n\nlemma path_const: \"path (\\<lambda>t. a)\" for a::\"'a::real_normed_vector\"\n  unfolding path_def by (intro continuous_intros)\n\nlemma path_minus: \"path g \\<Longrightarrow> path (\\<lambda>t. - g t)\" for g::\"real\\<Rightarrow>'a::real_normed_vector\"\n  unfolding path_def by (intro continuous_intros)\n\nlemma path_add: \"\\<lbrakk>path f; path g\\<rbrakk> \\<Longrightarrow> path (\\<lambda>t. f t + g t)\" for f::\"real\\<Rightarrow>'a::real_normed_vector\"\n  unfolding path_def by (intro continuous_intros)\n\nlemma path_diff: \"\\<lbrakk>path f; path g\\<rbrakk> \\<Longrightarrow> path (\\<lambda>t. f t - g t)\" for f::\"real\\<Rightarrow>'a::real_normed_vector\"\n  unfolding path_def by (intro continuous_intros)\n\nlemma path_mult: \"\\<lbrakk>path f; path g\\<rbrakk> \\<Longrightarrow> path (\\<lambda>t. f t * g t)\" for f::\"real\\<Rightarrow>'a::real_normed_field\"\n  unfolding path_def by (intro continuous_intros)\n\nlemma pathin_iff_path_real [simp]: \"pathin euclideanreal g \\<longleftrightarrow> path g\"\n  by (simp add: pathin_def path_def)\n\nlemma continuous_on_path: \"path f \\<Longrightarrow> t \\<subseteq> {0..1} \\<Longrightarrow> continuous_on t f\"\n  using continuous_on_subset path_def by blast\n\nlemma arc_imp_simple_path: \"arc g \\<Longrightarrow> simple_path g\"\n  by (simp add: arc_def inj_on_def simple_path_def)\n\nlemma arc_imp_path: \"arc g \\<Longrightarrow> path g\"\n  using arc_def by blast\n\nlemma arc_imp_inj_on: \"arc g \\<Longrightarrow> inj_on g {0..1}\"\n  by (auto simp: arc_def)\n\nlemma simple_path_imp_path: \"simple_path g \\<Longrightarrow> path g\"\n  using simple_path_def by blast\n\nlemma simple_path_cases: \"simple_path g \\<Longrightarrow> arc g \\<or> pathfinish g = pathstart g\"\n  unfolding simple_path_def arc_def inj_on_def pathfinish_def pathstart_def\n  by force\n\nlemma simple_path_imp_arc: \"simple_path g \\<Longrightarrow> pathfinish g \\<noteq> pathstart g \\<Longrightarrow> arc g\"\n  using simple_path_cases by auto\n\nlemma arc_distinct_ends: \"arc g \\<Longrightarrow> pathfinish g \\<noteq> pathstart g\"\n  unfolding arc_def inj_on_def pathfinish_def pathstart_def\n  by fastforce\n\nlemma arc_simple_path: \"arc g \\<longleftrightarrow> simple_path g \\<and> pathfinish g \\<noteq> pathstart g\"\n  using arc_distinct_ends arc_imp_simple_path simple_path_cases by blast\n\nlemma simple_path_eq_arc: \"pathfinish g \\<noteq> pathstart g \\<Longrightarrow> (simple_path g = arc g)\"\n  by (simp add: arc_simple_path)\n\nlemma path_image_const [simp]: \"path_image (\\<lambda>t. a) = {a}\"\n  by (force simp: path_image_def)\n\nlemma path_image_nonempty [simp]: \"path_image g \\<noteq> {}\"\n  unfolding path_image_def image_is_empty box_eq_empty\n  by auto\n\nlemma pathstart_in_path_image[intro]: \"pathstart g \\<in> path_image g\"\n  unfolding pathstart_def path_image_def\n  by auto\n\nlemma pathfinish_in_path_image[intro]: \"pathfinish g \\<in> path_image g\"\n  unfolding pathfinish_def path_image_def\n  by auto\n\nlemma connected_path_image[intro]: \"path g \\<Longrightarrow> connected (path_image g)\"\n  unfolding path_def path_image_def\n  using connected_continuous_image connected_Icc by blast\n\nlemma compact_path_image[intro]: \"path g \\<Longrightarrow> compact (path_image g)\"\n  unfolding path_def path_image_def\n  using compact_continuous_image connected_Icc by blast\n\nlemma reversepath_reversepath[simp]: \"reversepath (reversepath g) = g\"\n  unfolding reversepath_def\n  by auto\n\nlemma pathstart_reversepath[simp]: \"pathstart (reversepath g) = pathfinish g\"\n  unfolding pathstart_def reversepath_def pathfinish_def\n  by auto\n\nlemma pathfinish_reversepath[simp]: \"pathfinish (reversepath g) = pathstart g\"\n  unfolding pathstart_def reversepath_def pathfinish_def\n  by auto\n\nlemma reversepath_o: \"reversepath g = g \\<circ> (-)1\"\n  by (auto simp: reversepath_def)\n\nlemma pathstart_join[simp]: \"pathstart (g1 +++ g2) = pathstart g1\"\n  unfolding pathstart_def joinpaths_def pathfinish_def\n  by auto\n\nlemma pathfinish_join[simp]: \"pathfinish (g1 +++ g2) = pathfinish g2\"\n  unfolding pathstart_def joinpaths_def pathfinish_def\n  by auto\n\nlemma path_image_reversepath[simp]: \"path_image (reversepath g) = path_image g\"\nproof -\n  have *: \"\\<And>g. path_image (reversepath g) \\<subseteq> path_image g\"\n    unfolding path_image_def subset_eq reversepath_def Ball_def image_iff\n    by force\n  show ?thesis\n    using *[of g] *[of \"reversepath g\"]\n    unfolding reversepath_reversepath\n    by auto\nqed\n\nlemma path_reversepath [simp]: \"path (reversepath g) \\<longleftrightarrow> path g\"\nproof -\n  have *: \"\\<And>g. path g \\<Longrightarrow> path (reversepath g)\"\n    unfolding path_def reversepath_def\n    apply (rule continuous_on_compose[unfolded o_def, of _ \"\\<lambda>x. 1 - x\"])\n    apply (auto intro: continuous_intros continuous_on_subset[of \"{0..1}\"])\n    done\n  show ?thesis\n    using \"*\" by force\nqed\n\nlemma arc_reversepath:\n  assumes \"arc g\" shows \"arc(reversepath g)\"\nproof -\n  have injg: \"inj_on g {0..1}\"\n    using assms\n    by (simp add: arc_def)\n  have **: \"\\<And>x y::real. 1-x = 1-y \\<Longrightarrow> x = y\"\n    by simp\n  show ?thesis\n    using assms  by (clarsimp simp: arc_def intro!: inj_onI) (simp add: inj_onD reversepath_def **)\nqed\n\nlemma simple_path_reversepath: \"simple_path g \\<Longrightarrow> simple_path (reversepath g)\"\n  apply (simp add: simple_path_def)\n  apply (force simp: reversepath_def)\n  done\n\nlemmas reversepath_simps =\n  path_reversepath path_image_reversepath pathstart_reversepath pathfinish_reversepath\n\nlemma path_join[simp]:\n  assumes \"pathfinish g1 = pathstart g2\"\n  shows \"path (g1 +++ g2) \\<longleftrightarrow> path g1 \\<and> path g2\"\n  unfolding path_def pathfinish_def pathstart_def\nproof safe\n  assume cont: \"continuous_on {0..1} (g1 +++ g2)\"\n  have g1: \"continuous_on {0..1} g1 \\<longleftrightarrow> continuous_on {0..1} ((g1 +++ g2) \\<circ> (\\<lambda>x. x / 2))\"\n    by (intro continuous_on_cong refl) (auto simp: joinpaths_def)\n  have g2: \"continuous_on {0..1} g2 \\<longleftrightarrow> continuous_on {0..1} ((g1 +++ g2) \\<circ> (\\<lambda>x. x / 2 + 1/2))\"\n    using assms\n    by (intro continuous_on_cong refl) (auto simp: joinpaths_def pathfinish_def pathstart_def)\n  show \"continuous_on {0..1} g1\" and \"continuous_on {0..1} g2\"\n    unfolding g1 g2\n    by (auto intro!: continuous_intros continuous_on_subset[OF cont] simp del: o_apply)\nnext\n  assume g1g2: \"continuous_on {0..1} g1\" \"continuous_on {0..1} g2\"\n  have 01: \"{0 .. 1} = {0..1/2} \\<union> {1/2 .. 1::real}\"\n    by auto\n  {\n    fix x :: real\n    assume \"0 \\<le> x\" and \"x \\<le> 1\"\n    then have \"x \\<in> (\\<lambda>x. x * 2) ` {0..1 / 2}\"\n      by (intro image_eqI[where x=\"x/2\"]) auto\n  }\n  note 1 = this\n  {\n    fix x :: real\n    assume \"0 \\<le> x\" and \"x \\<le> 1\"\n    then have \"x \\<in> (\\<lambda>x. x * 2 - 1) ` {1 / 2..1}\"\n      by (intro image_eqI[where x=\"x/2 + 1/2\"]) auto\n  }\n  note 2 = this\n  show \"continuous_on {0..1} (g1 +++ g2)\"\n    using assms\n    unfolding joinpaths_def 01\n    apply (intro continuous_on_cases closed_atLeastAtMost g1g2[THEN continuous_on_compose2] continuous_intros)\n    apply (auto simp: field_simps pathfinish_def pathstart_def intro!: 1 2)\n    done\nqed\n\n\nsubsection\\<^marker>\\<open>tag unimportant\\<close> \\<open>Path Images\\<close>\n\nlemma bounded_path_image: \"path g \\<Longrightarrow> bounded(path_image g)\"\n  by (simp add: compact_imp_bounded compact_path_image)\n\nlemma closed_path_image:\n  fixes g :: \"real \\<Rightarrow> 'a::t2_space\"\n  shows \"path g \\<Longrightarrow> closed(path_image g)\"\n  by (metis compact_path_image compact_imp_closed)\n\nlemma connected_simple_path_image: \"simple_path g \\<Longrightarrow> connected(path_image g)\"\n  by (metis connected_path_image simple_path_imp_path)\n\nlemma compact_simple_path_image: \"simple_path g \\<Longrightarrow> compact(path_image g)\"\n  by (metis compact_path_image simple_path_imp_path)\n\nlemma bounded_simple_path_image: \"simple_path g \\<Longrightarrow> bounded(path_image g)\"\n  by (metis bounded_path_image simple_path_imp_path)\n\nlemma closed_simple_path_image:\n  fixes g :: \"real \\<Rightarrow> 'a::t2_space\"\n  shows \"simple_path g \\<Longrightarrow> closed(path_image g)\"\n  by (metis closed_path_image simple_path_imp_path)\n\nlemma connected_arc_image: \"arc g \\<Longrightarrow> connected(path_image g)\"\n  by (metis connected_path_image arc_imp_path)\n\nlemma compact_arc_image: \"arc g \\<Longrightarrow> compact(path_image g)\"\n  by (metis compact_path_image arc_imp_path)\n\nlemma bounded_arc_image: \"arc g \\<Longrightarrow> bounded(path_image g)\"\n  by (metis bounded_path_image arc_imp_path)\n\nlemma closed_arc_image:\n  fixes g :: \"real \\<Rightarrow> 'a::t2_space\"\n  shows \"arc g \\<Longrightarrow> closed(path_image g)\"\n  by (metis closed_path_image arc_imp_path)\n\nlemma path_image_join_subset: \"path_image (g1 +++ g2) \\<subseteq> path_image g1 \\<union> path_image g2\"\n  unfolding path_image_def joinpaths_def\n  by auto\n\nlemma subset_path_image_join:\n  assumes \"path_image g1 \\<subseteq> s\"\n    and \"path_image g2 \\<subseteq> s\"\n  shows \"path_image (g1 +++ g2) \\<subseteq> s\"\n  using path_image_join_subset[of g1 g2] and assms\n  by auto\n\nlemma path_image_join:\n  assumes \"pathfinish g1 = pathstart g2\"\n  shows \"path_image(g1 +++ g2) = path_image g1 \\<union> path_image g2\"\nproof -\n  have \"path_image g1 \\<subseteq> path_image (g1 +++ g2)\"\n  proof (clarsimp simp: path_image_def joinpaths_def)\n    fix u::real\n    assume \"0 \\<le> u\" \"u \\<le> 1\"\n    then show \"g1 u \\<in> (\\<lambda>x. g1 (2 * x)) ` ({0..1} \\<inter> {x. x * 2 \\<le> 1})\"\n      by (rule_tac x=\"u/2\" in image_eqI) auto\n  qed\n  moreover \n  have \\<section>: \"g2 u \\<in> (\\<lambda>x. g2 (2 * x - 1)) ` ({0..1} \\<inter> {x. \\<not> x * 2 \\<le> 1})\" \n    if \"0 < u\" \"u \\<le> 1\" for u\n    using that assms\n    by (rule_tac x=\"(u+1)/2\" in image_eqI) (auto simp: field_simps pathfinish_def pathstart_def)\n  have \"g2 0 \\<in> (\\<lambda>x. g1 (2 * x)) ` ({0..1} \\<inter> {x. x * 2 \\<le> 1})\"\n    using assms\n    by (rule_tac x=\"1/2\" in image_eqI) (auto simp: pathfinish_def pathstart_def)\n  then have \"path_image g2 \\<subseteq> path_image (g1 +++ g2)\"\n    by (auto simp: path_image_def joinpaths_def intro!: \\<section>)\n  ultimately show ?thesis\n    using path_image_join_subset by blast\nqed\n\nlemma not_in_path_image_join:\n  assumes \"x \\<notin> path_image g1\"\n    and \"x \\<notin> path_image g2\"\n  shows \"x \\<notin> path_image (g1 +++ g2)\"\n  using assms and path_image_join_subset[of g1 g2]\n  by auto\n\nlemma pathstart_compose: \"pathstart(f \\<circ> p) = f(pathstart p)\"\n  by (simp add: pathstart_def)\n\nlemma pathfinish_compose: \"pathfinish(f \\<circ> p) = f(pathfinish p)\"\n  by (simp add: pathfinish_def)\n\nlemma path_image_compose: \"path_image (f \\<circ> p) = f ` (path_image p)\"\n  by (simp add: image_comp path_image_def)\n\nlemma path_compose_join: \"f \\<circ> (p +++ q) = (f \\<circ> p) +++ (f \\<circ> q)\"\n  by (rule ext) (simp add: joinpaths_def)\n\nlemma path_compose_reversepath: \"f \\<circ> reversepath p = reversepath(f \\<circ> p)\"\n  by (rule ext) (simp add: reversepath_def)\n\nlemma joinpaths_eq:\n  \"(\\<And>t. t \\<in> {0..1} \\<Longrightarrow> p t = p' t) \\<Longrightarrow>\n   (\\<And>t. t \\<in> {0..1} \\<Longrightarrow> q t = q' t)\n   \\<Longrightarrow>  t \\<in> {0..1} \\<Longrightarrow> (p +++ q) t = (p' +++ q') t\"\n  by (auto simp: joinpaths_def)\n\nlemma simple_path_inj_on: \"simple_path g \\<Longrightarrow> inj_on g {0<..<1}\"\n  by (auto simp: simple_path_def path_image_def inj_on_def less_eq_real_def Ball_def)\n\n\nsubsection\\<^marker>\\<open>tag unimportant\\<close>\\<open>Simple paths with the endpoints removed\\<close>\n\nlemma simple_path_endless:\n  assumes \"simple_path c\"\n  shows \"path_image c - {pathstart c,pathfinish c} = c ` {0<..<1}\" (is \"?lhs = ?rhs\")\nproof\n  show \"?lhs \\<subseteq> ?rhs\"\n    using less_eq_real_def by (auto simp: path_image_def pathstart_def pathfinish_def)\n  show \"?rhs \\<subseteq> ?lhs\"\n    using assms \n    apply (auto simp: simple_path_def path_image_def pathstart_def pathfinish_def Ball_def)\n    using less_eq_real_def zero_le_one by blast+\nqed\n\nlemma connected_simple_path_endless:\n  assumes \"simple_path c\"\n  shows \"connected(path_image c - {pathstart c,pathfinish c})\"\nproof -\n  have \"continuous_on {0<..<1} c\"\n    using assms by (simp add: simple_path_def continuous_on_path path_def subset_iff)\n  then have \"connected (c ` {0<..<1})\"\n    using connected_Ioo connected_continuous_image by blast\n  then show ?thesis\n    using assms by (simp add: simple_path_endless)\nqed\n\nlemma nonempty_simple_path_endless:\n    \"simple_path c \\<Longrightarrow> path_image c - {pathstart c,pathfinish c} \\<noteq> {}\"\n  by (simp add: simple_path_endless)\n\n\nsubsection\\<^marker>\\<open>tag unimportant\\<close>\\<open>The operations on paths\\<close>\n\nlemma path_image_subset_reversepath: \"path_image(reversepath g) \\<le> path_image g\"\n  by simp\n\nlemma path_imp_reversepath: \"path g \\<Longrightarrow> path(reversepath g)\"\n  by simp\n\nlemma half_bounded_equal: \"1 \\<le> x * 2 \\<Longrightarrow> x * 2 \\<le> 1 \\<longleftrightarrow> x = (1/2::real)\"\n  by simp\n\nlemma continuous_on_joinpaths:\n  assumes \"continuous_on {0..1} g1\" \"continuous_on {0..1} g2\" \"pathfinish g1 = pathstart g2\"\n    shows \"continuous_on {0..1} (g1 +++ g2)\"\nproof -\n  have \"{0..1::real} = {0..1/2} \\<union> {1/2..1}\"\n    by auto\n  then show ?thesis\n    using assms by (metis path_def path_join)\nqed\n\nlemma path_join_imp: \"\\<lbrakk>path g1; path g2; pathfinish g1 = pathstart g2\\<rbrakk> \\<Longrightarrow> path(g1 +++ g2)\"\n  by simp\n\nlemma simple_path_join_loop:\n  assumes \"arc g1\" \"arc g2\"\n          \"pathfinish g1 = pathstart g2\"  \"pathfinish g2 = pathstart g1\"\n          \"path_image g1 \\<inter> path_image g2 \\<subseteq> {pathstart g1, pathstart g2}\"\n  shows \"simple_path(g1 +++ g2)\"\nproof -\n  have injg1: \"inj_on g1 {0..1}\"\n    using assms\n    by (simp add: arc_def)\n  have injg2: \"inj_on g2 {0..1}\"\n    using assms\n    by (simp add: arc_def)\n  have g12: \"g1 1 = g2 0\"\n   and g21: \"g2 1 = g1 0\"\n   and sb:  \"g1 ` {0..1} \\<inter> g2 ` {0..1} \\<subseteq> {g1 0, g2 0}\"\n    using assms\n    by (simp_all add: arc_def pathfinish_def pathstart_def path_image_def)\n  { fix x and y::real\n    assume g2_eq: \"g2 (2 * x - 1) = g1 (2 * y)\"\n      and xyI: \"x \\<noteq> 1 \\<or> y \\<noteq> 0\"\n      and xy: \"x \\<le> 1\" \"0 \\<le> y\" \" y * 2 \\<le> 1\" \"\\<not> x * 2 \\<le> 1\" \n    then consider \"g1 (2 * y) = g1 0\" | \"g1 (2 * y) = g2 0\"\n      using sb by force\n    then have False\n    proof cases\n      case 1\n      then have \"y = 0\"\n        using xy g2_eq by (auto dest!: inj_onD [OF injg1])\n      then show ?thesis\n        using xy g2_eq xyI by (auto dest: inj_onD [OF injg2] simp flip: g21)\n    next\n      case 2\n      then have \"2*x = 1\"\n        using g2_eq g12 inj_onD [OF injg2] atLeastAtMost_iff xy(1) xy(4) by fastforce\n      with xy show False by auto\n    qed\n  } note * = this\n  { fix x and y::real\n    assume xy: \"g1 (2 * x) = g2 (2 * y - 1)\" \"y \\<le> 1\" \"0 \\<le> x\" \"\\<not> y * 2 \\<le> 1\" \"x * 2 \\<le> 1\" \n    then have \"x = 0 \\<and> y = 1\"\n      using * xy by force\n   } note ** = this\n  show ?thesis\n    using assms\n    apply (simp add: arc_def simple_path_def)\n    apply (auto simp: joinpaths_def split: if_split_asm \n                dest!: * ** dest: inj_onD [OF injg1] inj_onD [OF injg2])\n    done\nqed\n\nlemma arc_join:\n  assumes \"arc g1\" \"arc g2\"\n          \"pathfinish g1 = pathstart g2\"\n          \"path_image g1 \\<inter> path_image g2 \\<subseteq> {pathstart g2}\"\n    shows \"arc(g1 +++ g2)\"\nproof -\n  have injg1: \"inj_on g1 {0..1}\"\n    using assms\n    by (simp add: arc_def)\n  have injg2: \"inj_on g2 {0..1}\"\n    using assms\n    by (simp add: arc_def)\n  have g11: \"g1 1 = g2 0\"\n   and sb:  \"g1 ` {0..1} \\<inter> g2 ` {0..1} \\<subseteq> {g2 0}\"\n    using assms\n    by (simp_all add: arc_def pathfinish_def pathstart_def path_image_def)\n  { fix x and y::real\n    assume xy: \"g2 (2 * x - 1) = g1 (2 * y)\" \"x \\<le> 1\" \"0 \\<le> y\" \" y * 2 \\<le> 1\" \"\\<not> x * 2 \\<le> 1\"\n    then have \"g1 (2 * y) = g2 0\"\n      using sb by force\n    then have False\n      using xy inj_onD injg2 by fastforce\n   } note * = this\n  show ?thesis\n    using assms\n    apply (simp add: arc_def inj_on_def)\n    apply (auto simp: joinpaths_def arc_imp_path split: if_split_asm \n                dest: * *[OF sym] inj_onD [OF injg1] inj_onD [OF injg2])\n    done\nqed\n\nlemma reversepath_joinpaths:\n    \"pathfinish g1 = pathstart g2 \\<Longrightarrow> reversepath(g1 +++ g2) = reversepath g2 +++ reversepath g1\"\n  unfolding reversepath_def pathfinish_def pathstart_def joinpaths_def\n  by (rule ext) (auto simp: mult.commute)\n\n\nsubsection\\<^marker>\\<open>tag unimportant\\<close>\\<open>Some reversed and \"if and only if\" versions of joining theorems\\<close>\n\nlemma path_join_path_ends:\n  fixes g1 :: \"real \\<Rightarrow> 'a::metric_space\"\n  assumes \"path(g1 +++ g2)\" \"path g2\"\n    shows \"pathfinish g1 = pathstart g2\"\nproof (rule ccontr)\n  define e where \"e = dist (g1 1) (g2 0)\"\n  assume Neg: \"pathfinish g1 \\<noteq> pathstart g2\"\n  then have \"0 < dist (pathfinish g1) (pathstart g2)\"\n    by auto\n  then have \"e > 0\"\n    by (metis e_def pathfinish_def pathstart_def)\n  then have \"\\<forall>e>0. \\<exists>d>0. \\<forall>x'\\<in>{0..1}. dist x' 0 < d \\<longrightarrow> dist (g2 x') (g2 0) < e\"\n    using \\<open>path g2\\<close> atLeastAtMost_iff zero_le_one unfolding path_def continuous_on_iff\n    by blast\n  then obtain d1 where \"d1 > 0\"\n       and d1: \"\\<And>x'. \\<lbrakk>x'\\<in>{0..1}; norm x' < d1\\<rbrakk> \\<Longrightarrow> dist (g2 x') (g2 0) < e/2\"\n    by (metis \\<open>0 < e\\<close> half_gt_zero_iff norm_conv_dist)\n  obtain d2 where \"d2 > 0\"\n       and d2: \"\\<And>x'. \\<lbrakk>x'\\<in>{0..1}; dist x' (1/2) < d2\\<rbrakk>\n                      \\<Longrightarrow> dist ((g1 +++ g2) x') (g1 1) < e/2\"\n    using assms(1) \\<open>e > 0\\<close> unfolding path_def continuous_on_iff\n    apply (drule_tac x=\"1/2\" in bspec, simp)\n    apply (drule_tac x=\"e/2\" in spec, force simp: joinpaths_def)\n    done\n  have int01_1: \"min (1/2) (min d1 d2) / 2 \\<in> {0..1}\"\n    using \\<open>d1 > 0\\<close> \\<open>d2 > 0\\<close> by (simp add: min_def)\n  have dist1: \"norm (min (1 / 2) (min d1 d2) / 2) < d1\"\n    using \\<open>d1 > 0\\<close> \\<open>d2 > 0\\<close> by (simp add: min_def dist_norm)\n  have int01_2: \"1/2 + min (1/2) (min d1 d2) / 4 \\<in> {0..1}\"\n    using \\<open>d1 > 0\\<close> \\<open>d2 > 0\\<close> by (simp add: min_def)\n  have dist2: \"dist (1 / 2 + min (1 / 2) (min d1 d2) / 4) (1 / 2) < d2\"\n    using \\<open>d1 > 0\\<close> \\<open>d2 > 0\\<close> by (simp add: min_def dist_norm)\n  have [simp]: \"\\<not> min (1 / 2) (min d1 d2) \\<le> 0\"\n    using \\<open>d1 > 0\\<close> \\<open>d2 > 0\\<close> by (simp add: min_def)\n  have \"dist (g2 (min (1 / 2) (min d1 d2) / 2)) (g1 1) < e/2\"\n       \"dist (g2 (min (1 / 2) (min d1 d2) / 2)) (g2 0) < e/2\"\n    using d1 [OF int01_1 dist1] d2 [OF int01_2 dist2] by (simp_all add: joinpaths_def)\n  then have \"dist (g1 1) (g2 0) < e/2 + e/2\"\n    using dist_triangle_half_r e_def by blast\n  then show False\n    by (simp add: e_def [symmetric])\nqed\n\nlemma path_join_eq [simp]:\n  fixes g1 :: \"real \\<Rightarrow> 'a::metric_space\"\n  assumes \"path g1\" \"path g2\"\n    shows \"path(g1 +++ g2) \\<longleftrightarrow> pathfinish g1 = pathstart g2\"\n  using assms by (metis path_join_path_ends path_join_imp)\n\nlemma simple_path_joinE:\n  assumes \"simple_path(g1 +++ g2)\" and \"pathfinish g1 = pathstart g2\"\n  obtains \"arc g1\" \"arc g2\"\n          \"path_image g1 \\<inter> path_image g2 \\<subseteq> {pathstart g1, pathstart g2}\"\nproof -\n  have *: \"\\<And>x y. \\<lbrakk>0 \\<le> x; x \\<le> 1; 0 \\<le> y; y \\<le> 1; (g1 +++ g2) x = (g1 +++ g2) y\\<rbrakk>\n               \\<Longrightarrow> x = y \\<or> x = 0 \\<and> y = 1 \\<or> x = 1 \\<and> y = 0\"\n    using assms by (simp add: simple_path_def)\n  have \"path g1\"\n    using assms path_join simple_path_imp_path by blast\n  moreover have \"inj_on g1 {0..1}\"\n  proof (clarsimp simp: inj_on_def)\n    fix x y\n    assume \"g1 x = g1 y\" \"0 \\<le> x\" \"x \\<le> 1\" \"0 \\<le> y\" \"y \\<le> 1\"\n    then show \"x = y\"\n      using * [of \"x/2\" \"y/2\"] by (simp add: joinpaths_def split_ifs)\n  qed\n  ultimately have \"arc g1\"\n    using assms  by (simp add: arc_def)\n  have [simp]: \"g2 0 = g1 1\"\n    using assms by (metis pathfinish_def pathstart_def)\n  have \"path g2\"\n    using assms path_join simple_path_imp_path by blast\n  moreover have \"inj_on g2 {0..1}\"\n  proof (clarsimp simp: inj_on_def)\n    fix x y\n    assume \"g2 x = g2 y\" \"0 \\<le> x\" \"x \\<le> 1\" \"0 \\<le> y\" \"y \\<le> 1\"\n    then show \"x = y\"\n      using * [of \"(x + 1) / 2\" \"(y + 1) / 2\"]\n      by (force simp: joinpaths_def split_ifs field_split_simps)\n  qed\n  ultimately have \"arc g2\"\n    using assms  by (simp add: arc_def)\n  have \"g2 y = g1 0 \\<or> g2 y = g1 1\"\n       if \"g1 x = g2 y\" \"0 \\<le> x\" \"x \\<le> 1\" \"0 \\<le> y\" \"y \\<le> 1\" for x y\n      using * [of \"x / 2\" \"(y + 1) / 2\"] that\n      by (auto simp: joinpaths_def split_ifs field_split_simps)\n  then have \"path_image g1 \\<inter> path_image g2 \\<subseteq> {pathstart g1, pathstart g2}\"\n    by (fastforce simp: pathstart_def pathfinish_def path_image_def)\n  with \\<open>arc g1\\<close> \\<open>arc g2\\<close> show ?thesis using that by blast\nqed\n\nlemma simple_path_join_loop_eq:\n  assumes \"pathfinish g2 = pathstart g1\" \"pathfinish g1 = pathstart g2\"\n    shows \"simple_path(g1 +++ g2) \\<longleftrightarrow>\n             arc g1 \\<and> arc g2 \\<and> path_image g1 \\<inter> path_image g2 \\<subseteq> {pathstart g1, pathstart g2}\"\nby (metis assms simple_path_joinE simple_path_join_loop)\n\nlemma arc_join_eq:\n  assumes \"pathfinish g1 = pathstart g2\"\n    shows \"arc(g1 +++ g2) \\<longleftrightarrow>\n           arc g1 \\<and> arc g2 \\<and> path_image g1 \\<inter> path_image g2 \\<subseteq> {pathstart g2}\"\n           (is \"?lhs = ?rhs\")\nproof\n  assume ?lhs\n  then have \"simple_path(g1 +++ g2)\" by (rule arc_imp_simple_path)\n  then have *: \"\\<And>x y. \\<lbrakk>0 \\<le> x; x \\<le> 1; 0 \\<le> y; y \\<le> 1; (g1 +++ g2) x = (g1 +++ g2) y\\<rbrakk>\n               \\<Longrightarrow> x = y \\<or> x = 0 \\<and> y = 1 \\<or> x = 1 \\<and> y = 0\"\n    using assms by (simp add: simple_path_def)\n  have False if \"g1 0 = g2 u\" \"0 \\<le> u\" \"u \\<le> 1\" for u\n    using * [of 0 \"(u + 1) / 2\"] that assms arc_distinct_ends [OF \\<open>?lhs\\<close>]\n    by (auto simp: joinpaths_def pathstart_def pathfinish_def split_ifs field_split_simps)\n  then have n1: \"pathstart g1 \\<notin> path_image g2\"\n    unfolding pathstart_def path_image_def\n    using atLeastAtMost_iff by blast\n  show ?rhs using \\<open>?lhs\\<close>\n    using \\<open>simple_path (g1 +++ g2)\\<close> assms n1 simple_path_joinE by auto\nnext\n  assume ?rhs then show ?lhs\n    using assms\n    by (fastforce simp: pathfinish_def pathstart_def intro!: arc_join)\nqed\n\nlemma arc_join_eq_alt:\n        \"pathfinish g1 = pathstart g2\n        \\<Longrightarrow> (arc(g1 +++ g2) \\<longleftrightarrow>\n             arc g1 \\<and> arc g2 \\<and>\n             path_image g1 \\<inter> path_image g2 = {pathstart g2})\"\nusing pathfinish_in_path_image by (fastforce simp: arc_join_eq)\n\n\nsubsection\\<^marker>\\<open>tag unimportant\\<close>\\<open>The joining of paths is associative\\<close>\n\nlemma path_assoc:\n    \"\\<lbrakk>pathfinish p = pathstart q; pathfinish q = pathstart r\\<rbrakk>\n     \\<Longrightarrow> path(p +++ (q +++ r)) \\<longleftrightarrow> path((p +++ q) +++ r)\"\nby simp\n\nlemma simple_path_assoc:\n  assumes \"pathfinish p = pathstart q\" \"pathfinish q = pathstart r\"\n    shows \"simple_path (p +++ (q +++ r)) \\<longleftrightarrow> simple_path ((p +++ q) +++ r)\"\nproof (cases \"pathstart p = pathfinish r\")\n  case True show ?thesis\n  proof\n    assume \"simple_path (p +++ q +++ r)\"\n    with assms True show \"simple_path ((p +++ q) +++ r)\"\n      by (fastforce simp add: simple_path_join_loop_eq arc_join_eq path_image_join\n                    dest: arc_distinct_ends [of r])\n  next\n    assume 0: \"simple_path ((p +++ q) +++ r)\"\n    with assms True have q: \"pathfinish r \\<notin> path_image q\"\n      using arc_distinct_ends\n      by (fastforce simp add: simple_path_join_loop_eq arc_join_eq path_image_join)\n    have \"pathstart r \\<notin> path_image p\"\n      using assms\n      by (metis 0 IntI arc_distinct_ends arc_join_eq_alt empty_iff insert_iff\n              pathfinish_in_path_image pathfinish_join simple_path_joinE)\n    with assms 0 q True show \"simple_path (p +++ q +++ r)\"\n      by (auto simp: simple_path_join_loop_eq arc_join_eq path_image_join\n               dest!: subsetD [OF _ IntI])\n  qed\nnext\n  case False\n  { fix x :: 'a\n    assume a: \"path_image p \\<inter> path_image q \\<subseteq> {pathstart q}\"\n              \"(path_image p \\<union> path_image q) \\<inter> path_image r \\<subseteq> {pathstart r}\"\n              \"x \\<in> path_image p\" \"x \\<in> path_image r\"\n    have \"pathstart r \\<in> path_image q\"\n      by (metis assms(2) pathfinish_in_path_image)\n    with a have \"x = pathstart q\"\n      by blast\n  }\n  with False assms show ?thesis\n    by (auto simp: simple_path_eq_arc simple_path_join_loop_eq arc_join_eq path_image_join)\nqed\n\nlemma arc_assoc:\n     \"\\<lbrakk>pathfinish p = pathstart q; pathfinish q = pathstart r\\<rbrakk>\n      \\<Longrightarrow> arc(p +++ (q +++ r)) \\<longleftrightarrow> arc((p +++ q) +++ r)\"\nby (simp add: arc_simple_path simple_path_assoc)\n\nsubsubsection\\<^marker>\\<open>tag unimportant\\<close>\\<open>Symmetry and loops\\<close>\n\nlemma path_sym:\n    \"\\<lbrakk>pathfinish p = pathstart q; pathfinish q = pathstart p\\<rbrakk> \\<Longrightarrow> path(p +++ q) \\<longleftrightarrow> path(q +++ p)\"\n  by auto\n\nlemma simple_path_sym:\n    \"\\<lbrakk>pathfinish p = pathstart q; pathfinish q = pathstart p\\<rbrakk>\n     \\<Longrightarrow> simple_path(p +++ q) \\<longleftrightarrow> simple_path(q +++ p)\"\nby (metis (full_types) inf_commute insert_commute simple_path_joinE simple_path_join_loop)\n\nlemma path_image_sym:\n    \"\\<lbrakk>pathfinish p = pathstart q; pathfinish q = pathstart p\\<rbrakk>\n     \\<Longrightarrow> path_image(p +++ q) = path_image(q +++ p)\"\nby (simp add: path_image_join sup_commute)\n\n\nsubsection\\<open>Subpath\\<close>\n\ndefinition\\<^marker>\\<open>tag important\\<close> subpath :: \"real \\<Rightarrow> real \\<Rightarrow> (real \\<Rightarrow> 'a) \\<Rightarrow> real \\<Rightarrow> 'a::real_normed_vector\"\n  where \"subpath a b g \\<equiv> \\<lambda>x. g((b - a) * x + a)\"\n\nlemma path_image_subpath_gen:\n  fixes g :: \"_ \\<Rightarrow> 'a::real_normed_vector\"\n  shows \"path_image(subpath u v g) = g ` (closed_segment u v)\"\n  by (auto simp add: closed_segment_real_eq path_image_def subpath_def)\n\nlemma path_image_subpath:\n  fixes g :: \"real \\<Rightarrow> 'a::real_normed_vector\"\n  shows \"path_image(subpath u v g) = (if u \\<le> v then g ` {u..v} else g ` {v..u})\"\n  by (simp add: path_image_subpath_gen closed_segment_eq_real_ivl)\n\nlemma path_image_subpath_commute:\n  fixes g :: \"real \\<Rightarrow> 'a::real_normed_vector\"\n  shows \"path_image(subpath u v g) = path_image(subpath v u g)\"\n  by (simp add: path_image_subpath_gen closed_segment_eq_real_ivl)\n\nlemma path_subpath [simp]:\n  fixes g :: \"real \\<Rightarrow> 'a::real_normed_vector\"\n  assumes \"path g\" \"u \\<in> {0..1}\" \"v \\<in> {0..1}\"\n    shows \"path(subpath u v g)\"\nproof -\n  have \"continuous_on {0..1} (g \\<circ> (\\<lambda>x. ((v-u) * x+ u)))\"\n    using assms\n    apply (intro continuous_intros; simp add: image_affinity_atLeastAtMost [where c=u])\n    apply (auto simp: path_def continuous_on_subset)\n    done\n  then show ?thesis\n    by (simp add: path_def subpath_def)\nqed\n\nlemma pathstart_subpath [simp]: \"pathstart(subpath u v g) = g(u)\"\n  by (simp add: pathstart_def subpath_def)\n\nlemma pathfinish_subpath [simp]: \"pathfinish(subpath u v g) = g(v)\"\n  by (simp add: pathfinish_def subpath_def)\n\nlemma subpath_trivial [simp]: \"subpath 0 1 g = g\"\n  by (simp add: subpath_def)\n\nlemma subpath_reversepath: \"subpath 1 0 g = reversepath g\"\n  by (simp add: reversepath_def subpath_def)\n\nlemma reversepath_subpath: \"reversepath(subpath u v g) = subpath v u g\"\n  by (simp add: reversepath_def subpath_def algebra_simps)\n\nlemma subpath_translation: \"subpath u v ((\\<lambda>x. a + x) \\<circ> g) = (\\<lambda>x. a + x) \\<circ> subpath u v g\"\n  by (rule ext) (simp add: subpath_def)\n\nlemma subpath_image: \"subpath u v (f \\<circ> g) = f \\<circ> subpath u v g\"\n  by (rule ext) (simp add: subpath_def)\n\nlemma affine_ineq:\n  fixes x :: \"'a::linordered_idom\"\n  assumes \"x \\<le> 1\" \"v \\<le> u\"\n    shows \"v + x * u \\<le> u + x * v\"\nproof -\n  have \"(1-x)*(u-v) \\<ge> 0\"\n    using assms by auto\n  then show ?thesis\n    by (simp add: algebra_simps)\nqed\n\nlemma sum_le_prod1:\n  fixes a::real shows \"\\<lbrakk>a \\<le> 1; b \\<le> 1\\<rbrakk> \\<Longrightarrow> a + b \\<le> 1 + a * b\"\nby (metis add.commute affine_ineq mult.right_neutral)\n\nlemma simple_path_subpath_eq:\n  \"simple_path(subpath u v g) \\<longleftrightarrow>\n     path(subpath u v g) \\<and> u\\<noteq>v \\<and>\n     (\\<forall>x y. x \\<in> closed_segment u v \\<and> y \\<in> closed_segment u v \\<and> g x = g y\n                \\<longrightarrow> x = y \\<or> x = u \\<and> y = v \\<or> x = v \\<and> y = u)\"\n    (is \"?lhs = ?rhs\")\nproof \n  assume ?lhs\n  then have p: \"path (\\<lambda>x. g ((v - u) * x + u))\"\n        and sim: \"(\\<And>x y. \\<lbrakk>x\\<in>{0..1}; y\\<in>{0..1}; g ((v - u) * x + u) = g ((v - u) * y + u)\\<rbrakk>\n                  \\<Longrightarrow> x = y \\<or> x = 0 \\<and> y = 1 \\<or> x = 1 \\<and> y = 0)\"\n    by (auto simp: simple_path_def subpath_def)\n  { fix x y\n    assume \"x \\<in> closed_segment u v\" \"y \\<in> closed_segment u v\" \"g x = g y\"\n    then have \"x = y \\<or> x = u \\<and> y = v \\<or> x = v \\<and> y = u\"\n      using sim [of \"(x-u)/(v-u)\" \"(y-u)/(v-u)\"] p\n      by (auto split: if_split_asm simp add: closed_segment_real_eq image_affinity_atLeastAtMost)\n        (simp_all add: field_split_simps)\n  } moreover\n  have \"path(subpath u v g) \\<and> u\\<noteq>v\"\n    using sim [of \"1/3\" \"2/3\"] p\n    by (auto simp: subpath_def)\n  ultimately show ?rhs\n    by metis\nnext\n  assume ?rhs\n  then\n  have d1: \"\\<And>x y. \\<lbrakk>g x = g y; u \\<le> x; x \\<le> v; u \\<le> y; y \\<le> v\\<rbrakk> \\<Longrightarrow> x = y \\<or> x = u \\<and> y = v \\<or> x = v \\<and> y = u\"\n   and d2: \"\\<And>x y. \\<lbrakk>g x = g y; v \\<le> x; x \\<le> u; v \\<le> y; y \\<le> u\\<rbrakk> \\<Longrightarrow> x = y \\<or> x = u \\<and> y = v \\<or> x = v \\<and> y = u\"\n   and ne: \"u < v \\<or> v < u\"\n   and psp: \"path (subpath u v g)\"\n    by (auto simp: closed_segment_real_eq image_affinity_atLeastAtMost)\n  have [simp]: \"\\<And>x. u + x * v = v + x * u \\<longleftrightarrow> u=v \\<or> x=1\"\n    by algebra\n  show ?lhs using psp ne\n    unfolding simple_path_def subpath_def\n    by (fastforce simp add: algebra_simps affine_ineq mult_left_mono crossproduct_eq dest: d1 d2)\nqed\n\nlemma arc_subpath_eq:\n  \"arc(subpath u v g) \\<longleftrightarrow> path(subpath u v g) \\<and> u\\<noteq>v \\<and> inj_on g (closed_segment u v)\"\n    (is \"?lhs = ?rhs\")\nproof \n  assume ?lhs\n  then have p: \"path (\\<lambda>x. g ((v - u) * x + u))\"\n        and sim: \"(\\<And>x y. \\<lbrakk>x\\<in>{0..1}; y\\<in>{0..1}; g ((v - u) * x + u) = g ((v - u) * y + u)\\<rbrakk>\n                  \\<Longrightarrow> x = y)\"\n    by (auto simp: arc_def inj_on_def subpath_def)\n  { fix x y\n    assume \"x \\<in> closed_segment u v\" \"y \\<in> closed_segment u v\" \"g x = g y\"\n    then have \"x = y\"\n      using sim [of \"(x-u)/(v-u)\" \"(y-u)/(v-u)\"] p\n      by (cases \"v = u\")\n        (simp_all split: if_split_asm add: inj_on_def closed_segment_real_eq image_affinity_atLeastAtMost,\n           simp add: field_simps)\n  } moreover\n  have \"path(subpath u v g) \\<and> u\\<noteq>v\"\n    using sim [of \"1/3\" \"2/3\"] p\n    by (auto simp: subpath_def)\n  ultimately show ?rhs\n    unfolding inj_on_def\n    by metis\nnext\n  assume ?rhs\n  then\n  have d1: \"\\<And>x y. \\<lbrakk>g x = g y; u \\<le> x; x \\<le> v; u \\<le> y; y \\<le> v\\<rbrakk> \\<Longrightarrow> x = y\"\n   and d2: \"\\<And>x y. \\<lbrakk>g x = g y; v \\<le> x; x \\<le> u; v \\<le> y; y \\<le> u\\<rbrakk> \\<Longrightarrow> x = y\"\n   and ne: \"u < v \\<or> v < u\"\n   and psp: \"path (subpath u v g)\"\n    by (auto simp: inj_on_def closed_segment_real_eq image_affinity_atLeastAtMost)\n  show ?lhs using psp ne\n    unfolding arc_def subpath_def inj_on_def\n    by (auto simp: algebra_simps affine_ineq mult_left_mono crossproduct_eq dest: d1 d2)\nqed\n\n\nlemma simple_path_subpath:\n  assumes \"simple_path g\" \"u \\<in> {0..1}\" \"v \\<in> {0..1}\" \"u \\<noteq> v\"\n  shows \"simple_path(subpath u v g)\"\n  using assms\n  apply (simp add: simple_path_subpath_eq simple_path_imp_path)\n  apply (simp add: simple_path_def closed_segment_real_eq image_affinity_atLeastAtMost, fastforce)\n  done\n\nlemma arc_simple_path_subpath:\n    \"\\<lbrakk>simple_path g; u \\<in> {0..1}; v \\<in> {0..1}; g u \\<noteq> g v\\<rbrakk> \\<Longrightarrow> arc(subpath u v g)\"\n  by (force intro: simple_path_subpath simple_path_imp_arc)\n\nlemma arc_subpath_arc:\n    \"\\<lbrakk>arc g; u \\<in> {0..1}; v \\<in> {0..1}; u \\<noteq> v\\<rbrakk> \\<Longrightarrow> arc(subpath u v g)\"\n  by (meson arc_def arc_imp_simple_path arc_simple_path_subpath inj_onD)\n\nlemma arc_simple_path_subpath_interior:\n    \"\\<lbrakk>simple_path g; u \\<in> {0..1}; v \\<in> {0..1}; u \\<noteq> v; \\<bar>u-v\\<bar> < 1\\<rbrakk> \\<Longrightarrow> arc(subpath u v g)\"\n  by (force simp: simple_path_def intro: arc_simple_path_subpath)\n\nlemma path_image_subpath_subset:\n    \"\\<lbrakk>u \\<in> {0..1}; v \\<in> {0..1}\\<rbrakk> \\<Longrightarrow> path_image(subpath u v g) \\<subseteq> path_image g\"\n  by (metis atLeastAtMost_iff atLeastatMost_subset_iff path_image_def path_image_subpath subset_image_iff)\n\nlemma join_subpaths_middle: \"subpath (0) ((1 / 2)) p +++ subpath ((1 / 2)) 1 p = p\"\n  by (rule ext) (simp add: joinpaths_def subpath_def field_split_simps)\n\n\nsubsection\\<^marker>\\<open>tag unimportant\\<close>\\<open>There is a subpath to the frontier\\<close>\n\nlemma subpath_to_frontier_explicit:\n    fixes S :: \"'a::metric_space set\"\n    assumes g: \"path g\" and \"pathfinish g \\<notin> S\"\n    obtains u where \"0 \\<le> u\" \"u \\<le> 1\"\n                \"\\<And>x. 0 \\<le> x \\<and> x < u \\<Longrightarrow> g x \\<in> interior S\"\n                \"(g u \\<notin> interior S)\" \"(u = 0 \\<or> g u \\<in> closure S)\"\nproof -\n  have gcon: \"continuous_on {0..1} g\"     \n    using g by (simp add: path_def)\n  moreover have \"bounded ({u. g u \\<in> closure (- S)} \\<inter> {0..1})\"\n    using compact_eq_bounded_closed by fastforce\n  ultimately have com: \"compact ({0..1} \\<inter> {u. g u \\<in> closure (- S)})\"\n    using closed_vimage_Int\n    by (metis (full_types) Int_commute closed_atLeastAtMost closed_closure compact_eq_bounded_closed vimage_def)\n  have \"1 \\<in> {u. g u \\<in> closure (- S)}\"\n    using assms by (simp add: pathfinish_def closure_def)\n  then have dis: \"{0..1} \\<inter> {u. g u \\<in> closure (- S)} \\<noteq> {}\"\n    using atLeastAtMost_iff zero_le_one by blast\n  then obtain u where \"0 \\<le> u\" \"u \\<le> 1\" and gu: \"g u \\<in> closure (- S)\"\n                  and umin: \"\\<And>t. \\<lbrakk>0 \\<le> t; t \\<le> 1; g t \\<in> closure (- S)\\<rbrakk> \\<Longrightarrow> u \\<le> t\"\n    using compact_attains_inf [OF com dis] by fastforce\n  then have umin': \"\\<And>t. \\<lbrakk>0 \\<le> t; t \\<le> 1; t < u\\<rbrakk> \\<Longrightarrow>  g t \\<in> S\"\n    using closure_def by fastforce\n  have \\<section>: \"g u \\<in> closure S\" if \"u \\<noteq> 0\"\n  proof -\n    have \"u > 0\" using that \\<open>0 \\<le> u\\<close> by auto\n    { fix e::real assume \"e > 0\"\n      obtain d where \"d>0\" and d: \"\\<And>x'. \\<lbrakk>x' \\<in> {0..1}; dist x' u \\<le> d\\<rbrakk> \\<Longrightarrow> dist (g x') (g u) < e\"\n        using continuous_onE [OF gcon _ \\<open>e > 0\\<close>] \\<open>0 \\<le> _\\<close> \\<open>_ \\<le> 1\\<close> atLeastAtMost_iff by auto\n      have *: \"dist (max 0 (u - d / 2)) u \\<le> d\"\n        using \\<open>0 \\<le> u\\<close> \\<open>u \\<le> 1\\<close> \\<open>d > 0\\<close> by (simp add: dist_real_def)\n      have \"\\<exists>y\\<in>S. dist y (g u) < e\"\n        using \\<open>0 < u\\<close> \\<open>u \\<le> 1\\<close> \\<open>d > 0\\<close>\n        by (force intro: d [OF _ *] umin')\n    }\n    then show ?thesis\n      by (simp add: frontier_def closure_approachable)\n  qed\n  show ?thesis\n  proof\n    show \"\\<And>x. 0 \\<le> x \\<and> x < u \\<Longrightarrow> g x \\<in> interior S\"\n      using \\<open>u \\<le> 1\\<close> interior_closure umin by fastforce\n    show \"g u \\<notin> interior S\"\n      by (simp add: gu interior_closure)\n  qed (use \\<open>0 \\<le> u\\<close> \\<open>u \\<le> 1\\<close> \\<section> in auto)\nqed\n\nlemma subpath_to_frontier_strong:\n    assumes g: \"path g\" and \"pathfinish g \\<notin> S\"\n    obtains u where \"0 \\<le> u\" \"u \\<le> 1\" \"g u \\<notin> interior S\"\n                    \"u = 0 \\<or> (\\<forall>x. 0 \\<le> x \\<and> x < 1 \\<longrightarrow> subpath 0 u g x \\<in> interior S)  \\<and>  g u \\<in> closure S\"\nproof -\n  obtain u where \"0 \\<le> u\" \"u \\<le> 1\"\n             and gxin: \"\\<And>x. 0 \\<le> x \\<and> x < u \\<Longrightarrow> g x \\<in> interior S\"\n             and gunot: \"(g u \\<notin> interior S)\" and u0: \"(u = 0 \\<or> g u \\<in> closure S)\"\n    using subpath_to_frontier_explicit [OF assms] by blast\n  show ?thesis\n  proof\n    show \"g u \\<notin> interior S\"\n      using gunot by blast\n  qed (use \\<open>0 \\<le> u\\<close> \\<open>u \\<le> 1\\<close> u0 in \\<open>(force simp: subpath_def gxin)+\\<close>)\nqed\n\nlemma subpath_to_frontier:\n    assumes g: \"path g\" and g0: \"pathstart g \\<in> closure S\" and g1: \"pathfinish g \\<notin> S\"\n    obtains u where \"0 \\<le> u\" \"u \\<le> 1\" \"g u \\<in> frontier S\" \"path_image(subpath 0 u g) - {g u} \\<subseteq> interior S\"\nproof -\n  obtain u where \"0 \\<le> u\" \"u \\<le> 1\"\n             and notin: \"g u \\<notin> interior S\"\n             and disj: \"u = 0 \\<or>\n                        (\\<forall>x. 0 \\<le> x \\<and> x < 1 \\<longrightarrow> subpath 0 u g x \\<in> interior S) \\<and> g u \\<in> closure S\"\n                       (is \"_ \\<or> ?P\")\n    using subpath_to_frontier_strong [OF g g1] by blast\n  show ?thesis\n  proof\n    show \"g u \\<in> frontier S\"\n      by (metis DiffI disj frontier_def g0 notin pathstart_def)\n    show \"path_image (subpath 0 u g) - {g u} \\<subseteq> interior S\"\n      using disj\n    proof\n      assume \"u = 0\"\n      then show ?thesis\n        by (simp add: path_image_subpath)\n    next\n      assume P: ?P\n      show ?thesis\n      proof (clarsimp simp add: path_image_subpath_gen)\n        fix y\n        assume y: \"y \\<in> closed_segment 0 u\" \"g y \\<notin> interior S\"\n        with \\<open>0 \\<le> u\\<close> have \"0 \\<le> y\" \"y \\<le> u\" \n          by (auto simp: closed_segment_eq_real_ivl split: if_split_asm)\n        then have \"y=u \\<or> subpath 0 u g (y/u) \\<in> interior S\"\n          using P less_eq_real_def by force\n        then show \"g y = g u\"\n          using y by (auto simp: subpath_def split: if_split_asm)\n      qed\n    qed\n  qed (use \\<open>0 \\<le> u\\<close> \\<open>u \\<le> 1\\<close> in auto)\nqed\n\nlemma exists_path_subpath_to_frontier:\n    fixes S :: \"'a::real_normed_vector set\"\n    assumes \"path g\" \"pathstart g \\<in> closure S\" \"pathfinish g \\<notin> S\"\n    obtains h where \"path h\" \"pathstart h = pathstart g\" \"path_image h \\<subseteq> path_image g\"\n                    \"path_image h - {pathfinish h} \\<subseteq> interior S\"\n                    \"pathfinish h \\<in> frontier S\"\nproof -\n  obtain u where u: \"0 \\<le> u\" \"u \\<le> 1\" \"g u \\<in> frontier S\" \"(path_image(subpath 0 u g) - {g u}) \\<subseteq> interior S\"\n    using subpath_to_frontier [OF assms] by blast\n  show ?thesis\n  proof\n    show \"path_image (subpath 0 u g) \\<subseteq> path_image g\"\n      by (simp add: path_image_subpath_subset u)\n    show \"pathstart (subpath 0 u g) = pathstart g\"\n      by (metis pathstart_def pathstart_subpath)\n  qed (use assms u in \\<open>auto simp: path_image_subpath\\<close>)\nqed\n\nlemma exists_path_subpath_to_frontier_closed:\n    fixes S :: \"'a::real_normed_vector set\"\n    assumes S: \"closed S\" and g: \"path g\" and g0: \"pathstart g \\<in> S\" and g1: \"pathfinish g \\<notin> S\"\n    obtains h where \"path h\" \"pathstart h = pathstart g\" \"path_image h \\<subseteq> path_image g \\<inter> S\"\n                    \"pathfinish h \\<in> frontier S\"\nproof -\n  obtain h where h: \"path h\" \"pathstart h = pathstart g\" \"path_image h \\<subseteq> path_image g\"\n                    \"path_image h - {pathfinish h} \\<subseteq> interior S\"\n                    \"pathfinish h \\<in> frontier S\"\n    using exists_path_subpath_to_frontier [OF g _ g1] closure_closed [OF S] g0 by auto\n  show ?thesis\n  proof\n    show \"path_image h \\<subseteq> path_image g \\<inter> S\"\n      using assms h interior_subset [of S] by (auto simp: frontier_def)\n  qed (use h in auto)\nqed\n\n\nsubsection \\<open>Shift Path to Start at Some Given Point\\<close>\n\ndefinition\\<^marker>\\<open>tag important\\<close> shiftpath :: \"real \\<Rightarrow> (real \\<Rightarrow> 'a::topological_space) \\<Rightarrow> real \\<Rightarrow> 'a\"\n  where \"shiftpath a f = (\\<lambda>x. if (a + x) \\<le> 1 then f (a + x) else f (a + x - 1))\"\n\nlemma shiftpath_alt_def: \"shiftpath a f = (\\<lambda>x. if x \\<le> 1-a then f (a + x) else f (a + x - 1))\"\n  by (auto simp: shiftpath_def)\n\nlemma pathstart_shiftpath: \"a \\<le> 1 \\<Longrightarrow> pathstart (shiftpath a g) = g a\"\n  unfolding pathstart_def shiftpath_def by auto\n\nlemma pathfinish_shiftpath:\n  assumes \"0 \\<le> a\"\n    and \"pathfinish g = pathstart g\"\n  shows \"pathfinish (shiftpath a g) = g a\"\n  using assms\n  unfolding pathstart_def pathfinish_def shiftpath_def\n  by auto\n\nlemma endpoints_shiftpath:\n  assumes \"pathfinish g = pathstart g\"\n    and \"a \\<in> {0 .. 1}\"\n  shows \"pathfinish (shiftpath a g) = g a\"\n    and \"pathstart (shiftpath a g) = g a\"\n  using assms\n  by (auto intro!: pathfinish_shiftpath pathstart_shiftpath)\n\nlemma closed_shiftpath:\n  assumes \"pathfinish g = pathstart g\"\n    and \"a \\<in> {0..1}\"\n  shows \"pathfinish (shiftpath a g) = pathstart (shiftpath a g)\"\n  using endpoints_shiftpath[OF assms]\n  by auto\n\nlemma path_shiftpath:\n  assumes \"path g\"\n    and \"pathfinish g = pathstart g\"\n    and \"a \\<in> {0..1}\"\n  shows \"path (shiftpath a g)\"\nproof -\n  have *: \"{0 .. 1} = {0 .. 1-a} \\<union> {1-a .. 1}\"\n    using assms(3) by auto\n  have **: \"\\<And>x. x + a = 1 \\<Longrightarrow> g (x + a - 1) = g (x + a)\"\n    using assms(2)[unfolded pathfinish_def pathstart_def]\n    by auto\n  show ?thesis\n    unfolding path_def shiftpath_def *\n  proof (rule continuous_on_closed_Un)\n    have contg: \"continuous_on {0..1} g\"\n      using \\<open>path g\\<close> path_def by blast\n    show \"continuous_on {0..1-a} (\\<lambda>x. if a + x \\<le> 1 then g (a + x) else g (a + x - 1))\"\n    proof (rule continuous_on_eq)\n      show \"continuous_on {0..1-a} (g \\<circ> (+) a)\"\n        by (intro continuous_intros continuous_on_subset [OF contg]) (use \\<open>a \\<in> {0..1}\\<close> in auto)\n    qed auto\n    show \"continuous_on {1-a..1} (\\<lambda>x. if a + x \\<le> 1 then g (a + x) else g (a + x - 1))\"\n    proof (rule continuous_on_eq)\n      show \"continuous_on {1-a..1} (g \\<circ> (+) (a - 1))\"\n        by (intro continuous_intros continuous_on_subset [OF contg]) (use \\<open>a \\<in> {0..1}\\<close> in auto)\n    qed (auto simp:  \"**\" add.commute add_diff_eq)\n  qed auto\nqed\n\nlemma shiftpath_shiftpath:\n  assumes \"pathfinish g = pathstart g\"\n    and \"a \\<in> {0..1}\"\n    and \"x \\<in> {0..1}\"\n  shows \"shiftpath (1 - a) (shiftpath a g) x = g x\"\n  using assms\n  unfolding pathfinish_def pathstart_def shiftpath_def\n  by auto\n\nlemma path_image_shiftpath:\n  assumes a: \"a \\<in> {0..1}\"\n    and \"pathfinish g = pathstart g\"\n  shows \"path_image (shiftpath a g) = path_image g\"\nproof -\n  { fix x\n    assume g: \"g 1 = g 0\" \"x \\<in> {0..1::real}\" and gne: \"\\<And>y. y\\<in>{0..1} \\<inter> {x. \\<not> a + x \\<le> 1} \\<Longrightarrow> g x \\<noteq> g (a + y - 1)\"\n    then have \"\\<exists>y\\<in>{0..1} \\<inter> {x. a + x \\<le> 1}. g x = g (a + y)\"\n    proof (cases \"a \\<le> x\")\n      case False\n      then show ?thesis\n        apply (rule_tac x=\"1 + x - a\" in bexI)\n        using g gne[of \"1 + x - a\"] a by (force simp: field_simps)+\n    next\n      case True\n      then show ?thesis\n        using g a  by (rule_tac x=\"x - a\" in bexI) (auto simp: field_simps)\n    qed\n  }\n  then show ?thesis\n    using assms\n    unfolding shiftpath_def path_image_def pathfinish_def pathstart_def\n    by (auto simp: image_iff)\nqed\n\nlemma simple_path_shiftpath:\n  assumes \"simple_path g\" \"pathfinish g = pathstart g\" and a: \"0 \\<le> a\" \"a \\<le> 1\"\n    shows \"simple_path (shiftpath a g)\"\n  unfolding simple_path_def\nproof (intro conjI impI ballI)\n  show \"path (shiftpath a g)\"\n    by (simp add: assms path_shiftpath simple_path_imp_path)\n  have *: \"\\<And>x y. \\<lbrakk>g x = g y; x \\<in> {0..1}; y \\<in> {0..1}\\<rbrakk> \\<Longrightarrow> x = y \\<or> x = 0 \\<and> y = 1 \\<or> x = 1 \\<and> y = 0\"\n    using assms by (simp add:  simple_path_def)\n  show \"x = y \\<or> x = 0 \\<and> y = 1 \\<or> x = 1 \\<and> y = 0\"\n    if \"x \\<in> {0..1}\" \"y \\<in> {0..1}\" \"shiftpath a g x = shiftpath a g y\" for x y\n    using that a unfolding shiftpath_def\n    by (force split: if_split_asm dest!: *)\nqed\n\n\nsubsection \\<open>Straight-Line Paths\\<close>\n\ndefinition\\<^marker>\\<open>tag important\\<close> linepath :: \"'a::real_normed_vector \\<Rightarrow> 'a \\<Rightarrow> real \\<Rightarrow> 'a\"\n  where \"linepath a b = (\\<lambda>x. (1 - x) *\\<^sub>R a + x *\\<^sub>R b)\"\n\nlemma pathstart_linepath[simp]: \"pathstart (linepath a b) = a\"\n  unfolding pathstart_def linepath_def\n  by auto\n\nlemma pathfinish_linepath[simp]: \"pathfinish (linepath a b) = b\"\n  unfolding pathfinish_def linepath_def\n  by auto\n\nlemma linepath_inner: \"linepath a b x \\<bullet> v = linepath (a \\<bullet> v) (b \\<bullet> v) x\"\n  by (simp add: linepath_def algebra_simps)\n\nlemma Re_linepath': \"Re (linepath a b x) = linepath (Re a) (Re b) x\"\n  by (simp add: linepath_def)\n\nlemma Im_linepath': \"Im (linepath a b x) = linepath (Im a) (Im b) x\"\n  by (simp add: linepath_def)\n\nlemma linepath_0': \"linepath a b 0 = a\"\n  by (simp add: linepath_def)\n\nlemma linepath_1': \"linepath a b 1 = b\"\n  by (simp add: linepath_def)\n\nlemma continuous_linepath_at[intro]: \"continuous (at x) (linepath a b)\"\n  unfolding linepath_def\n  by (intro continuous_intros)\n\nlemma continuous_on_linepath [intro,continuous_intros]: \"continuous_on s (linepath a b)\"\n  using continuous_linepath_at\n  by (auto intro!: continuous_at_imp_continuous_on)\n\nlemma path_linepath[iff]: \"path (linepath a b)\"\n  unfolding path_def\n  by (rule continuous_on_linepath)\n\nlemma path_image_linepath[simp]: \"path_image (linepath a b) = closed_segment a b\"\n  unfolding path_image_def segment linepath_def\n  by auto\n\nlemma reversepath_linepath[simp]: \"reversepath (linepath a b) = linepath b a\"\n  unfolding reversepath_def linepath_def\n  by auto\n\nlemma linepath_0 [simp]: \"linepath 0 b x = x *\\<^sub>R b\"\n  by (simp add: linepath_def)\n\nlemma linepath_cnj: \"cnj (linepath a b x) = linepath (cnj a) (cnj b) x\"\n  by (simp add: linepath_def)\n\nlemma arc_linepath:\n  assumes \"a \\<noteq> b\" shows [simp]: \"arc (linepath a b)\"\nproof -\n  {\n    fix x y :: \"real\"\n    assume \"x *\\<^sub>R b + y *\\<^sub>R a = x *\\<^sub>R a + y *\\<^sub>R b\"\n    then have \"(x - y) *\\<^sub>R a = (x - y) *\\<^sub>R b\"\n      by (simp add: algebra_simps)\n    with assms have \"x = y\"\n      by simp\n  }\n  then show ?thesis\n    unfolding arc_def inj_on_def\n    by (fastforce simp: algebra_simps linepath_def)\nqed\n\nlemma simple_path_linepath[intro]: \"a \\<noteq> b \\<Longrightarrow> simple_path (linepath a b)\"\n  by (simp add: arc_imp_simple_path)\n\nlemma linepath_trivial [simp]: \"linepath a a x = a\"\n  by (simp add: linepath_def real_vector.scale_left_diff_distrib)\n\nlemma linepath_refl: \"linepath a a = (\\<lambda>x. a)\"\n  by auto\n\nlemma subpath_refl: \"subpath a a g = linepath (g a) (g a)\"\n  by (simp add: subpath_def linepath_def algebra_simps)\n\nlemma linepath_of_real: \"(linepath (of_real a) (of_real b) x) = of_real ((1 - x)*a + x*b)\"\n  by (simp add: scaleR_conv_of_real linepath_def)\n\nlemma of_real_linepath: \"of_real (linepath a b x) = linepath (of_real a) (of_real b) x\"\n  by (metis linepath_of_real mult.right_neutral of_real_def real_scaleR_def)\n\nlemma inj_on_linepath:\n  assumes \"a \\<noteq> b\" shows \"inj_on (linepath a b) {0..1}\"\nproof (clarsimp simp: inj_on_def linepath_def)\n  fix x y\n  assume \"(1 - x) *\\<^sub>R a + x *\\<^sub>R b = (1 - y) *\\<^sub>R a + y *\\<^sub>R b\" \"0 \\<le> x\" \"x \\<le> 1\" \"0 \\<le> y\" \"y \\<le> 1\"\n  then have \"x *\\<^sub>R (a - b) = y *\\<^sub>R (a - b)\"\n    by (auto simp: algebra_simps)\n  then show \"x=y\"\n    using assms by auto\nqed\n\nlemma linepath_le_1:\n  fixes a::\"'a::linordered_idom\" shows \"\\<lbrakk>a \\<le> 1; b \\<le> 1; 0 \\<le> u; u \\<le> 1\\<rbrakk> \\<Longrightarrow> (1 - u) * a + u * b \\<le> 1\"\n  using mult_left_le [of a \"1-u\"] mult_left_le [of b u] by auto\n\nlemma linepath_in_path:\n  shows \"x \\<in> {0..1} \\<Longrightarrow> linepath a b x \\<in> closed_segment a b\"\n  by (auto simp: segment linepath_def)\n\nlemma linepath_image_01: \"linepath a b ` {0..1} = closed_segment a b\"\n  by (auto simp: segment linepath_def)\n\nlemma linepath_in_convex_hull:\n  fixes x::real\n  assumes a: \"a \\<in> convex hull S\"\n    and b: \"b \\<in> convex hull S\"\n    and x: \"0\\<le>x\" \"x\\<le>1\"\n  shows \"linepath a b x \\<in> convex hull S\"\nproof -\n  have \"linepath a b x \\<in> closed_segment a b\"\n    using x by (auto simp flip: linepath_image_01)\n  then show ?thesis\n    using a b convex_contains_segment by blast\nqed\n\nlemma Re_linepath: \"Re(linepath (of_real a) (of_real b) x) = (1 - x)*a + x*b\"\n  by (simp add: linepath_def)\n\nlemma Im_linepath: \"Im(linepath (of_real a) (of_real b) x) = 0\"\n  by (simp add: linepath_def)\n\nlemma bounded_linear_linepath:\n  assumes \"bounded_linear f\"\n  shows   \"f (linepath a b x) = linepath (f a) (f b) x\"\nproof -\n  interpret f: bounded_linear f by fact\n  show ?thesis by (simp add: linepath_def f.add f.scale)\nqed\n\nlemma bounded_linear_linepath':\n  assumes \"bounded_linear f\"\n  shows   \"f \\<circ> linepath a b = linepath (f a) (f b)\"\n  using bounded_linear_linepath[OF assms] by (simp add: fun_eq_iff)\n\nlemma linepath_cnj': \"cnj \\<circ> linepath a b = linepath (cnj a) (cnj b)\"\n  by (simp add: linepath_def fun_eq_iff)\n\nlemma differentiable_linepath [intro]: \"linepath a b differentiable at x within A\"\n  by (auto simp: linepath_def)\n\nlemma has_vector_derivative_linepath_within:\n    \"(linepath a b has_vector_derivative (b - a)) (at x within S)\"\n  by (force intro: derivative_eq_intros simp add: linepath_def has_vector_derivative_def algebra_simps)\n\n\nsubsection\\<^marker>\\<open>tag unimportant\\<close>\\<open>Segments via convex hulls\\<close>\n\nlemma segments_subset_convex_hull:\n    \"closed_segment a b \\<subseteq> (convex hull {a,b,c})\"\n    \"closed_segment a c \\<subseteq> (convex hull {a,b,c})\"\n    \"closed_segment b c \\<subseteq> (convex hull {a,b,c})\"\n    \"closed_segment b a \\<subseteq> (convex hull {a,b,c})\"\n    \"closed_segment c a \\<subseteq> (convex hull {a,b,c})\"\n    \"closed_segment c b \\<subseteq> (convex hull {a,b,c})\"\nby (auto simp: segment_convex_hull linepath_of_real  elim!: rev_subsetD [OF _ hull_mono])\n\nlemma midpoints_in_convex_hull:\n  assumes \"x \\<in> convex hull s\" \"y \\<in> convex hull s\"\n    shows \"midpoint x y \\<in> convex hull s\"\nproof -\n  have \"(1 - inverse(2)) *\\<^sub>R x + inverse(2) *\\<^sub>R y \\<in> convex hull s\"\n    by (rule convexD_alt) (use assms in auto)\n  then show ?thesis\n    by (simp add: midpoint_def algebra_simps)\nqed\n\nlemma not_in_interior_convex_hull_3:\n  fixes a :: \"complex\"\n  shows \"a \\<notin> interior(convex hull {a,b,c})\"\n        \"b \\<notin> interior(convex hull {a,b,c})\"\n        \"c \\<notin> interior(convex hull {a,b,c})\"\n  by (auto simp: card_insert_le_m1 not_in_interior_convex_hull)\n\nlemma midpoint_in_closed_segment [simp]: \"midpoint a b \\<in> closed_segment a b\"\n  using midpoints_in_convex_hull segment_convex_hull by blast\n\nlemma midpoint_in_open_segment [simp]: \"midpoint a b \\<in> open_segment a b \\<longleftrightarrow> a \\<noteq> b\"\n  by (simp add: open_segment_def)\n\nlemma continuous_IVT_local_extremum:\n  fixes f :: \"'a::euclidean_space \\<Rightarrow> real\"\n  assumes contf: \"continuous_on (closed_segment a b) f\"\n      and \"a \\<noteq> b\" \"f a = f b\"\n  obtains z where \"z \\<in> open_segment a b\"\n                  \"(\\<forall>w \\<in> closed_segment a b. (f w) \\<le> (f z)) \\<or>\n                   (\\<forall>w \\<in> closed_segment a b. (f z) \\<le> (f w))\"\nproof -\n  obtain c where \"c \\<in> closed_segment a b\" and c: \"\\<And>y. y \\<in> closed_segment a b \\<Longrightarrow> f y \\<le> f c\"\n    using continuous_attains_sup [of \"closed_segment a b\" f] contf by auto\n  obtain d where \"d \\<in> closed_segment a b\" and d: \"\\<And>y. y \\<in> closed_segment a b \\<Longrightarrow> f d \\<le> f y\"\n    using continuous_attains_inf [of \"closed_segment a b\" f] contf by auto\n  show ?thesis\n  proof (cases \"c \\<in> open_segment a b \\<or> d \\<in> open_segment a b\")\n    case True\n    then show ?thesis\n      using c d that by blast\n  next\n    case False\n    then have \"(c = a \\<or> c = b) \\<and> (d = a \\<or> d = b)\"\n      by (simp add: \\<open>c \\<in> closed_segment a b\\<close> \\<open>d \\<in> closed_segment a b\\<close> open_segment_def)\n    with \\<open>a \\<noteq> b\\<close> \\<open>f a = f b\\<close> c d show ?thesis\n      by (rule_tac z = \"midpoint a b\" in that) (fastforce+)\n  qed\nqed\n\ntext\\<open>An injective map into R is also an open map w.r.T. the universe, and conversely. \\<close>\nproposition injective_eq_1d_open_map_UNIV:\n  fixes f :: \"real \\<Rightarrow> real\"\n  assumes contf: \"continuous_on S f\" and S: \"is_interval S\"\n    shows \"inj_on f S \\<longleftrightarrow> (\\<forall>T. open T \\<and> T \\<subseteq> S \\<longrightarrow> open(f ` T))\"\n          (is \"?lhs = ?rhs\")\nproof safe\n  fix T\n  assume injf: ?lhs and \"open T\" and \"T \\<subseteq> S\"\n  have \"\\<exists>U. open U \\<and> f x \\<in> U \\<and> U \\<subseteq> f ` T\" if \"x \\<in> T\" for x\n  proof -\n    obtain \\<delta> where \"\\<delta> > 0\" and \\<delta>: \"cball x \\<delta> \\<subseteq> T\"\n      using \\<open>open T\\<close> \\<open>x \\<in> T\\<close> open_contains_cball_eq by blast\n    show ?thesis\n    proof (intro exI conjI)\n      have \"closed_segment (x-\\<delta>) (x+\\<delta>) = {x-\\<delta>..x+\\<delta>}\"\n        using \\<open>0 < \\<delta>\\<close> by (auto simp: closed_segment_eq_real_ivl)\n      also have \"\\<dots> \\<subseteq> S\"\n        using \\<delta> \\<open>T \\<subseteq> S\\<close> by (auto simp: dist_norm subset_eq)\n      finally have \"f ` (open_segment (x-\\<delta>) (x+\\<delta>)) = open_segment (f (x-\\<delta>)) (f (x+\\<delta>))\"\n        using continuous_injective_image_open_segment_1\n        by (metis continuous_on_subset [OF contf] inj_on_subset [OF injf])\n      then show \"open (f ` {x-\\<delta><..<x+\\<delta>})\"\n        using \\<open>0 < \\<delta>\\<close> by (simp add: open_segment_eq_real_ivl)\n      show \"f x \\<in> f ` {x - \\<delta><..<x + \\<delta>}\"\n        by (auto simp: \\<open>\\<delta> > 0\\<close>)\n      show \"f ` {x - \\<delta><..<x + \\<delta>} \\<subseteq> f ` T\"\n        using \\<delta> by (auto simp: dist_norm subset_iff)\n    qed\n  qed\n  with open_subopen show \"open (f ` T)\"\n    by blast\nnext\n  assume R: ?rhs\n  have False if xy: \"x \\<in> S\" \"y \\<in> S\" and \"f x = f y\" \"x \\<noteq> y\" for x y\n  proof -\n    have \"open (f ` open_segment x y)\"\n      using R\n      by (metis S convex_contains_open_segment is_interval_convex open_greaterThanLessThan open_segment_eq_real_ivl xy)\n    moreover\n    have \"continuous_on (closed_segment x y) f\"\n      by (meson S closed_segment_subset contf continuous_on_subset is_interval_convex that)\n    then obtain \\<xi> where \"\\<xi> \\<in> open_segment x y\"\n                    and \\<xi>: \"(\\<forall>w \\<in> closed_segment x y. (f w) \\<le> (f \\<xi>)) \\<or>\n                            (\\<forall>w \\<in> closed_segment x y. (f \\<xi>) \\<le> (f w))\"\n      using continuous_IVT_local_extremum [of x y f] \\<open>f x = f y\\<close> \\<open>x \\<noteq> y\\<close> by blast\n    ultimately obtain e where \"e>0\" and e: \"\\<And>u. dist u (f \\<xi>) < e \\<Longrightarrow> u \\<in> f ` open_segment x y\"\n      using open_dist by (metis image_eqI)\n    have fin: \"f \\<xi> + (e/2) \\<in> f ` open_segment x y\" \"f \\<xi> - (e/2) \\<in> f ` open_segment x y\"\n      using e [of \"f \\<xi> + (e/2)\"] e [of \"f \\<xi> - (e/2)\"] \\<open>e > 0\\<close> by (auto simp: dist_norm)\n    show ?thesis\n      using \\<xi> \\<open>0 < e\\<close> fin open_closed_segment by fastforce\n  qed\n  then show ?lhs\n    by (force simp: inj_on_def)\nqed\n\n\nsubsection\\<^marker>\\<open>tag unimportant\\<close> \\<open>Bounding a point away from a path\\<close>\n\nlemma not_on_path_ball:\n  fixes g :: \"real \\<Rightarrow> 'a::heine_borel\"\n  assumes \"path g\"\n    and z: \"z \\<notin> path_image g\"\n  shows \"\\<exists>e > 0. ball z e \\<inter> path_image g = {}\"\nproof -\n  have \"closed (path_image g)\"\n    by (simp add: \\<open>path g\\<close> closed_path_image)\n  then obtain a where \"a \\<in> path_image g\" \"\\<forall>y \\<in> path_image g. dist z a \\<le> dist z y\"\n    by (auto intro: distance_attains_inf[OF _ path_image_nonempty, of g z])\n  then show ?thesis\n    by (rule_tac x=\"dist z a\" in exI) (use dist_commute z in auto)\nqed\n\nlemma not_on_path_cball:\n  fixes g :: \"real \\<Rightarrow> 'a::heine_borel\"\n  assumes \"path g\"\n    and \"z \\<notin> path_image g\"\n  shows \"\\<exists>e>0. cball z e \\<inter> (path_image g) = {}\"\nproof -\n  obtain e where \"ball z e \\<inter> path_image g = {}\" \"e > 0\"\n    using not_on_path_ball[OF assms] by auto\n  moreover have \"cball z (e/2) \\<subseteq> ball z e\"\n    using \\<open>e > 0\\<close> by auto\n  ultimately show ?thesis\n    by (rule_tac x=\"e/2\" in exI) auto\nqed\n\nsubsection \\<open>Path component\\<close>\n\ntext \\<open>Original formalization by Tom Hales\\<close>\n\ndefinition\\<^marker>\\<open>tag important\\<close> \"path_component S x y \\<equiv>\n  (\\<exists>g. path g \\<and> path_image g \\<subseteq> S \\<and> pathstart g = x \\<and> pathfinish g = y)\"\n\nabbreviation\\<^marker>\\<open>tag important\\<close>\n  \"path_component_set S x \\<equiv> Collect (path_component S x)\"\n\nlemmas path_defs = path_def pathstart_def pathfinish_def path_image_def path_component_def\n\nlemma path_component_mem:\n  assumes \"path_component S x y\"\n  shows \"x \\<in> S\" and \"y \\<in> S\"\n  using assms\n  unfolding path_defs\n  by auto\n\nlemma path_component_refl:\n  assumes \"x \\<in> S\"\n  shows \"path_component S x x\"\n  using assms\n  unfolding path_defs\n  by (metis (full_types) assms continuous_on_const image_subset_iff path_image_def)\n\nlemma path_component_refl_eq: \"path_component S x x \\<longleftrightarrow> x \\<in> S\"\n  by (auto intro!: path_component_mem path_component_refl)\n\nlemma path_component_sym: \"path_component S x y \\<Longrightarrow> path_component S y x\"\n  unfolding path_component_def\n  by (metis (no_types) path_image_reversepath path_reversepath pathfinish_reversepath pathstart_reversepath)\n\nlemma path_component_trans:\n  assumes \"path_component S x y\" and \"path_component S y z\"\n  shows \"path_component S x z\"\n  using assms\n  unfolding path_component_def\n  by (metis path_join pathfinish_join pathstart_join subset_path_image_join)\n\nlemma path_component_of_subset: \"S \\<subseteq> T \\<Longrightarrow> path_component S x y \\<Longrightarrow> path_component T x y\"\n  unfolding path_component_def by auto\n\nlemma path_component_linepath:\n    fixes S :: \"'a::real_normed_vector set\"\n    shows \"closed_segment a b \\<subseteq> S \\<Longrightarrow> path_component S a b\"\n  unfolding path_component_def\n  by (rule_tac x=\"linepath a b\" in exI, auto)\n\nsubsubsection\\<^marker>\\<open>tag unimportant\\<close> \\<open>Path components as sets\\<close>\n\nlemma path_component_set:\n  \"path_component_set S x =\n    {y. (\\<exists>g. path g \\<and> path_image g \\<subseteq> S \\<and> pathstart g = x \\<and> pathfinish g = y)}\"\n  by (auto simp: path_component_def)\n\nlemma path_component_subset: \"path_component_set S x \\<subseteq> S\"\n  by (auto simp: path_component_mem(2))\n\nlemma path_component_eq_empty: \"path_component_set S x = {} \\<longleftrightarrow> x \\<notin> S\"\n  using path_component_mem path_component_refl_eq\n    by fastforce\n\nlemma path_component_mono:\n     \"S \\<subseteq> T \\<Longrightarrow> (path_component_set S x) \\<subseteq> (path_component_set T x)\"\n  by (simp add: Collect_mono path_component_of_subset)\n\nlemma path_component_eq:\n   \"y \\<in> path_component_set S x \\<Longrightarrow> path_component_set S y = path_component_set S x\"\nby (metis (no_types, lifting) Collect_cong mem_Collect_eq path_component_sym path_component_trans)\n\n\nsubsection \\<open>Path connectedness of a space\\<close>\n\ndefinition\\<^marker>\\<open>tag important\\<close> \"path_connected S \\<longleftrightarrow>\n  (\\<forall>x\\<in>S. \\<forall>y\\<in>S. \\<exists>g. path g \\<and> path_image g \\<subseteq> S \\<and> pathstart g = x \\<and> pathfinish g = y)\"\n\nlemma path_connectedin_iff_path_connected_real [simp]:\n     \"path_connectedin euclideanreal S \\<longleftrightarrow> path_connected S\"\n  by (simp add: path_connectedin path_connected_def path_defs)\n\nlemma path_connected_component: \"path_connected S \\<longleftrightarrow> (\\<forall>x\\<in>S. \\<forall>y\\<in>S. path_component S x y)\"\n  unfolding path_connected_def path_component_def by auto\n\nlemma path_connected_component_set: \"path_connected S \\<longleftrightarrow> (\\<forall>x\\<in>S. path_component_set S x = S)\"\n  unfolding path_connected_component path_component_subset\n  using path_component_mem by blast\n\nlemma path_component_maximal:\n     \"\\<lbrakk>x \\<in> T; path_connected T; T \\<subseteq> S\\<rbrakk> \\<Longrightarrow> T \\<subseteq> (path_component_set S x)\"\n  by (metis path_component_mono path_connected_component_set)\n\nlemma convex_imp_path_connected:\n  fixes S :: \"'a::real_normed_vector set\"\n  assumes \"convex S\"\n  shows \"path_connected S\"\n  unfolding path_connected_def\n  using assms convex_contains_segment by fastforce\n\nlemma path_connected_UNIV [iff]: \"path_connected (UNIV :: 'a::real_normed_vector set)\"\n  by (simp add: convex_imp_path_connected)\n\nlemma path_component_UNIV: \"path_component_set UNIV x = (UNIV :: 'a::real_normed_vector set)\"\n  using path_connected_component_set by auto\n\nlemma path_connected_imp_connected:\n  assumes \"path_connected S\"\n  shows \"connected S\"\nproof (rule connectedI)\n  fix e1 e2\n  assume as: \"open e1\" \"open e2\" \"S \\<subseteq> e1 \\<union> e2\" \"e1 \\<inter> e2 \\<inter> S = {}\" \"e1 \\<inter> S \\<noteq> {}\" \"e2 \\<inter> S \\<noteq> {}\"\n  then obtain x1 x2 where obt:\"x1 \\<in> e1 \\<inter> S\" \"x2 \\<in> e2 \\<inter> S\"\n    by auto\n  then obtain g where g: \"path g\" \"path_image g \\<subseteq> S\" \"pathstart g = x1\" \"pathfinish g = x2\"\n    using assms[unfolded path_connected_def,rule_format,of x1 x2] by auto\n  have *: \"connected {0..1::real}\"\n    by (auto intro!: convex_connected)\n  have \"{0..1} \\<subseteq> {x \\<in> {0..1}. g x \\<in> e1} \\<union> {x \\<in> {0..1}. g x \\<in> e2}\"\n    using as(3) g(2)[unfolded path_defs] by blast\n  moreover have \"{x \\<in> {0..1}. g x \\<in> e1} \\<inter> {x \\<in> {0..1}. g x \\<in> e2} = {}\"\n    using as(4) g(2)[unfolded path_defs]\n    unfolding subset_eq\n    by auto\n  moreover have \"{x \\<in> {0..1}. g x \\<in> e1} \\<noteq> {} \\<and> {x \\<in> {0..1}. g x \\<in> e2} \\<noteq> {}\"\n    using g(3,4)[unfolded path_defs]\n    using obt\n    by (simp add: ex_in_conv [symmetric], metis zero_le_one order_refl)\n  ultimately show False\n    using *[unfolded connected_local not_ex, rule_format,\n      of \"{0..1} \\<inter> g -` e1\" \"{0..1} \\<inter> g -` e2\"]\n    using continuous_openin_preimage_gen[OF g(1)[unfolded path_def] as(1)]\n    using continuous_openin_preimage_gen[OF g(1)[unfolded path_def] as(2)]\n    by auto\nqed\n\nlemma open_path_component:\n  fixes S :: \"'a::real_normed_vector set\"\n  assumes \"open S\"\n  shows \"open (path_component_set S x)\"\n  unfolding open_contains_ball\nproof\n  fix y\n  assume as: \"y \\<in> path_component_set S x\"\n  then have \"y \\<in> S\"\n    by (simp add: path_component_mem(2))\n  then obtain e where e: \"e > 0\" \"ball y e \\<subseteq> S\"\n    using assms openE by blast\nhave \"\\<And>u. dist y u < e \\<Longrightarrow> path_component S x u\"\n      by (metis (full_types) as centre_in_ball convex_ball convex_imp_path_connected e mem_Collect_eq mem_ball path_component_eq path_component_of_subset path_connected_component)\n  then show \"\\<exists>e > 0. ball y e \\<subseteq> path_component_set S x\"\n    using \\<open>e>0\\<close> by auto\nqed\n\nlemma open_non_path_component:\n  fixes S :: \"'a::real_normed_vector set\"\n  assumes \"open S\"\n  shows \"open (S - path_component_set S x)\"\n  unfolding open_contains_ball\nproof\n  fix y\n  assume y: \"y \\<in> S - path_component_set S x\"\n  then obtain e where e: \"e > 0\" \"ball y e \\<subseteq> S\"\n    using assms openE by auto\n  show \"\\<exists>e>0. ball y e \\<subseteq> S - path_component_set S x\"\n  proof (intro exI conjI subsetI DiffI notI)\n    show \"\\<And>x. x \\<in> ball y e \\<Longrightarrow> x \\<in> S\"\n      using e by blast\n    show False if \"z \\<in> ball y e\" \"z \\<in> path_component_set S x\" for z\n    proof -\n      have \"y \\<in> path_component_set S z\"\n        by (meson assms convex_ball convex_imp_path_connected e open_contains_ball_eq open_path_component path_component_maximal that(1))\n      then have \"y \\<in> path_component_set S x\"\n        using path_component_eq that(2) by blast\n      then show False\n        using y by blast\n    qed\n  qed (use e in auto)\nqed\n\nlemma connected_open_path_connected:\n  fixes S :: \"'a::real_normed_vector set\"\n  assumes \"open S\"\n    and \"connected S\"\n  shows \"path_connected S\"\n  unfolding path_connected_component_set\nproof (rule, rule, rule path_component_subset, rule)\n  fix x y\n  assume \"x \\<in> S\" and \"y \\<in> S\"\n  show \"y \\<in> path_component_set S x\"\n  proof (rule ccontr)\n    assume \"\\<not> ?thesis\"\n    moreover have \"path_component_set S x \\<inter> S \\<noteq> {}\"\n      using \\<open>x \\<in> S\\<close> path_component_eq_empty path_component_subset[of S x]\n      by auto\n    ultimately\n    show False\n      using \\<open>y \\<in> S\\<close> open_non_path_component[OF assms(1)] open_path_component[OF assms(1)]\n      using assms(2)[unfolded connected_def not_ex, rule_format,\n        of \"path_component_set S x\" \"S - path_component_set S x\"]\n      by auto\n  qed\nqed\n\nlemma path_connected_continuous_image:\n  assumes contf: \"continuous_on S f\"\n    and \"path_connected S\"\n  shows \"path_connected (f ` S)\"\n  unfolding path_connected_def\nproof (rule, rule)\n  fix x' y'\n  assume \"x' \\<in> f ` S\" \"y' \\<in> f ` S\"\n  then obtain x y where x: \"x \\<in> S\" and y: \"y \\<in> S\" and x': \"x' = f x\" and y': \"y' = f y\"\n    by auto\n  from x y obtain g where \"path g \\<and> path_image g \\<subseteq> S \\<and> pathstart g = x \\<and> pathfinish g = y\"\n    using assms(2)[unfolded path_connected_def] by fast\n  then show \"\\<exists>g. path g \\<and> path_image g \\<subseteq> f ` S \\<and> pathstart g = x' \\<and> pathfinish g = y'\"\n    unfolding x' y' path_defs\n    by (fastforce intro: continuous_on_compose continuous_on_subset[OF contf])\nqed\n\nlemma path_connected_translationI:\n  fixes a :: \"'a :: topological_group_add\"\n  assumes \"path_connected S\" shows \"path_connected ((\\<lambda>x. a + x) ` S)\"\n  by (intro path_connected_continuous_image assms continuous_intros)\n\nlemma path_connected_translation:\n  fixes a :: \"'a :: topological_group_add\"\n  shows \"path_connected ((\\<lambda>x. a + x) ` S) = path_connected S\"\nproof -\n  have \"\\<forall>x y. (+) (x::'a) ` (+) (0 - x) ` y = y\"\n    by (simp add: image_image)\n  then show ?thesis\n    by (metis (no_types) path_connected_translationI)\nqed\n\nlemma path_connected_segment [simp]:\n    fixes a :: \"'a::real_normed_vector\"\n    shows \"path_connected (closed_segment a b)\"\n  by (simp add: convex_imp_path_connected)\n\nlemma path_connected_open_segment [simp]:\n    fixes a :: \"'a::real_normed_vector\"\n    shows \"path_connected (open_segment a b)\"\n  by (simp add: convex_imp_path_connected)\n\nlemma homeomorphic_path_connectedness:\n  \"S homeomorphic T \\<Longrightarrow> path_connected S \\<longleftrightarrow> path_connected T\"\n  unfolding homeomorphic_def homeomorphism_def by (metis path_connected_continuous_image)\n\nlemma path_connected_empty [simp]: \"path_connected {}\"\n  unfolding path_connected_def by auto\n\nlemma path_connected_singleton [simp]: \"path_connected {a}\"\n  unfolding path_connected_def pathstart_def pathfinish_def path_image_def\n  using path_def by fastforce\n\nlemma path_connected_Un:\n  assumes \"path_connected S\"\n    and \"path_connected T\"\n    and \"S \\<inter> T \\<noteq> {}\"\n  shows \"path_connected (S \\<union> T)\"\n  unfolding path_connected_component\nproof (intro ballI)\n  fix x y\n  assume x: \"x \\<in> S \\<union> T\" and y: \"y \\<in> S \\<union> T\"\n  from assms obtain z where z: \"z \\<in> S\" \"z \\<in> T\"\n    by auto\n  show \"path_component (S \\<union> T) x y\"\n    using x y\n  proof safe\n    assume \"x \\<in> S\" \"y \\<in> S\"\n    then show \"path_component (S \\<union> T) x y\"\n      by (meson Un_upper1 \\<open>path_connected S\\<close> path_component_of_subset path_connected_component)\n  next\n    assume \"x \\<in> S\" \"y \\<in> T\"\n    then show \"path_component (S \\<union> T) x y\"\n      by (metis z assms(1-2) le_sup_iff order_refl path_component_of_subset path_component_trans path_connected_component)\n  next\n  assume \"x \\<in> T\" \"y \\<in> S\"\n    then show \"path_component (S \\<union> T) x y\"\n      by (metis z assms(1-2) le_sup_iff order_refl path_component_of_subset path_component_trans path_connected_component)\n  next\n    assume \"x \\<in> T\" \"y \\<in> T\"\n    then show \"path_component (S \\<union> T) x y\"\n      by (metis Un_upper1 assms(2) path_component_of_subset path_connected_component sup_commute)\n  qed\nqed\n\nlemma path_connected_UNION:\n  assumes \"\\<And>i. i \\<in> A \\<Longrightarrow> path_connected (S i)\"\n    and \"\\<And>i. i \\<in> A \\<Longrightarrow> z \\<in> S i\"\n  shows \"path_connected (\\<Union>i\\<in>A. S i)\"\n  unfolding path_connected_component\nproof clarify\n  fix x i y j\n  assume *: \"i \\<in> A\" \"x \\<in> S i\" \"j \\<in> A\" \"y \\<in> S j\"\n  then have \"path_component (S i) x z\" and \"path_component (S j) z y\"\n    using assms by (simp_all add: path_connected_component)\n  then have \"path_component (\\<Union>i\\<in>A. S i) x z\" and \"path_component (\\<Union>i\\<in>A. S i) z y\"\n    using *(1,3) by (auto elim!: path_component_of_subset [rotated])\n  then show \"path_component (\\<Union>i\\<in>A. S i) x y\"\n    by (rule path_component_trans)\nqed\n\nlemma path_component_path_image_pathstart:\n  assumes p: \"path p\" and x: \"x \\<in> path_image p\"\n  shows \"path_component (path_image p) (pathstart p) x\"\nproof -\n  obtain y where x: \"x = p y\" and y: \"0 \\<le> y\" \"y \\<le> 1\"\n    using x by (auto simp: path_image_def)\n  show ?thesis\n    unfolding path_component_def \n  proof (intro exI conjI)\n    have \"continuous_on ((*) y ` {0..1}) p\"\n      by (simp add: continuous_on_path image_mult_atLeastAtMost_if p y)\n    then have \"continuous_on {0..1} (p \\<circ> ((*) y))\"\n      using continuous_on_compose continuous_on_mult_const by blast\n    then show \"path (\\<lambda>u. p (y * u))\"\n      by (simp add: path_def)\n    show \"path_image (\\<lambda>u. p (y * u)) \\<subseteq> path_image p\"\n      using y mult_le_one by (fastforce simp: path_image_def image_iff)\n  qed (auto simp: pathstart_def pathfinish_def x)\nqed\n\nlemma path_connected_path_image: \"path p \\<Longrightarrow> path_connected(path_image p)\"\n  unfolding path_connected_component\n  by (meson path_component_path_image_pathstart path_component_sym path_component_trans)\n\nlemma path_connected_path_component [simp]:\n   \"path_connected (path_component_set s x)\"\nproof -\n  { fix y z\n    assume pa: \"path_component s x y\" \"path_component s x z\"\n    then have pae: \"path_component_set s x = path_component_set s y\"\n      using path_component_eq by auto\n    have yz: \"path_component s y z\"\n      using pa path_component_sym path_component_trans by blast\n    then have \"\\<exists>g. path g \\<and> path_image g \\<subseteq> path_component_set s x \\<and> pathstart g = y \\<and> pathfinish g = z\"\n      apply (simp add: path_component_def)\n      by (metis pae path_component_maximal path_connected_path_image pathstart_in_path_image)\n  }\n  then show ?thesis\n    by (simp add: path_connected_def)\nqed\n\nlemma path_component: \"path_component S x y \\<longleftrightarrow> (\\<exists>t. path_connected t \\<and> t \\<subseteq> S \\<and> x \\<in> t \\<and> y \\<in> t)\"\n  apply (intro iffI)\n  apply (metis path_connected_path_image path_defs(5) pathfinish_in_path_image pathstart_in_path_image)\n  using path_component_of_subset path_connected_component by blast\n\nlemma path_component_path_component [simp]:\n   \"path_component_set (path_component_set S x) x = path_component_set S x\"\nproof (cases \"x \\<in> S\")\n  case True show ?thesis\n    by (metis True mem_Collect_eq path_component_refl path_connected_component_set path_connected_path_component)\nnext\n  case False then show ?thesis\n    by (metis False empty_iff path_component_eq_empty)\nqed\n\nlemma path_component_subset_connected_component:\n   \"(path_component_set S x) \\<subseteq> (connected_component_set S x)\"\nproof (cases \"x \\<in> S\")\n  case True show ?thesis\n    by (simp add: True connected_component_maximal path_component_refl path_component_subset path_connected_imp_connected)\nnext\n  case False then show ?thesis\n    using path_component_eq_empty by auto\nqed\n\n\nsubsection\\<^marker>\\<open>tag unimportant\\<close>\\<open>Lemmas about path-connectedness\\<close>\n\nlemma path_connected_linear_image:\n  fixes f :: \"'a::real_normed_vector \\<Rightarrow> 'b::real_normed_vector\"\n  assumes \"path_connected S\" \"bounded_linear f\"\n    shows \"path_connected(f ` S)\"\nby (auto simp: linear_continuous_on assms path_connected_continuous_image)\n\nlemma is_interval_path_connected: \"is_interval S \\<Longrightarrow> path_connected S\"\n  by (simp add: convex_imp_path_connected is_interval_convex)\n\nlemma path_connected_Ioi[simp]: \"path_connected {a<..}\" for a :: real\n  by (simp add: convex_imp_path_connected)\n\nlemma path_connected_Ici[simp]: \"path_connected {a..}\" for a :: real\n  by (simp add: convex_imp_path_connected)\n\nlemma path_connected_Iio[simp]: \"path_connected {..<a}\" for a :: real\n  by (simp add: convex_imp_path_connected)\n\nlemma path_connected_Iic[simp]: \"path_connected {..a}\" for a :: real\n  by (simp add: convex_imp_path_connected)\n\nlemma path_connected_Ioo[simp]: \"path_connected {a<..<b}\" for a b :: real\n  by (simp add: convex_imp_path_connected)\n\nlemma path_connected_Ioc[simp]: \"path_connected {a<..b}\" for a b :: real\n  by (simp add: convex_imp_path_connected)\n\nlemma path_connected_Ico[simp]: \"path_connected {a..<b}\" for a b :: real\n  by (simp add: convex_imp_path_connected)\n\nlemma path_connectedin_path_image:\n  assumes \"pathin X g\" shows \"path_connectedin X (g ` ({0..1}))\"\n  unfolding pathin_def\nproof (rule path_connectedin_continuous_map_image)\n  show \"continuous_map (subtopology euclideanreal {0..1}) X g\"\n    using assms pathin_def by blast\nqed (auto simp: is_interval_1 is_interval_path_connected)\n\nlemma path_connected_space_subconnected:\n     \"path_connected_space X \\<longleftrightarrow>\n      (\\<forall>x \\<in> topspace X. \\<forall>y \\<in> topspace X. \\<exists>S. path_connectedin X S \\<and> x \\<in> S \\<and> y \\<in> S)\"\n  by (metis path_connectedin path_connectedin_topspace path_connected_space_def)\n\n\nlemma connectedin_path_image: \"pathin X g \\<Longrightarrow> connectedin X (g ` ({0..1}))\"\n  by (simp add: path_connectedin_imp_connectedin path_connectedin_path_image)\n\nlemma compactin_path_image: \"pathin X g \\<Longrightarrow> compactin X (g ` ({0..1}))\"\n  unfolding pathin_def\n  by (rule image_compactin [of \"top_of_set {0..1}\"]) auto\n\nlemma linear_homeomorphism_image:\n  fixes f :: \"'a::euclidean_space \\<Rightarrow> 'b::euclidean_space\"\n  assumes \"linear f\" \"inj f\"\n  obtains g where \"homeomorphism (f ` S) S g f\"\nproof -\n  obtain g where \"linear g\" \"g \\<circ> f = id\"\n    using assms linear_injective_left_inverse by blast\n  then have \"homeomorphism (f ` S) S g f\"\n    using assms unfolding homeomorphism_def\n    by (auto simp: eq_id_iff [symmetric] image_comp linear_conv_bounded_linear linear_continuous_on)\n  then show thesis ..\nqed\n\nlemma linear_homeomorphic_image:\n  fixes f :: \"'a::euclidean_space \\<Rightarrow> 'b::euclidean_space\"\n  assumes \"linear f\" \"inj f\"\n    shows \"S homeomorphic f ` S\"\nby (meson homeomorphic_def homeomorphic_sym linear_homeomorphism_image [OF assms])\n\nlemma path_connected_Times:\n  assumes \"path_connected s\" \"path_connected t\"\n    shows \"path_connected (s \\<times> t)\"\nproof (simp add: path_connected_def Sigma_def, clarify)\n  fix x1 y1 x2 y2\n  assume \"x1 \\<in> s\" \"y1 \\<in> t\" \"x2 \\<in> s\" \"y2 \\<in> t\"\n  obtain g where \"path g\" and g: \"path_image g \\<subseteq> s\" and gs: \"pathstart g = x1\" and gf: \"pathfinish g = x2\"\n    using \\<open>x1 \\<in> s\\<close> \\<open>x2 \\<in> s\\<close> assms by (force simp: path_connected_def)\n  obtain h where \"path h\" and h: \"path_image h \\<subseteq> t\" and hs: \"pathstart h = y1\" and hf: \"pathfinish h = y2\"\n    using \\<open>y1 \\<in> t\\<close> \\<open>y2 \\<in> t\\<close> assms by (force simp: path_connected_def)\n  have \"path (\\<lambda>z. (x1, h z))\"\n    using \\<open>path h\\<close>\n    unfolding path_def\n    by (intro continuous_intros continuous_on_compose2 [where g = \"Pair _\"]; force)\n  moreover have \"path (\\<lambda>z. (g z, y2))\"\n    using \\<open>path g\\<close>\n    unfolding path_def\n    by (intro continuous_intros continuous_on_compose2 [where g = \"Pair _\"]; force)\n  ultimately have 1: \"path ((\\<lambda>z. (x1, h z)) +++ (\\<lambda>z. (g z, y2)))\"\n    by (metis hf gs path_join_imp pathstart_def pathfinish_def)\n  have \"path_image ((\\<lambda>z. (x1, h z)) +++ (\\<lambda>z. (g z, y2))) \\<subseteq> path_image (\\<lambda>z. (x1, h z)) \\<union> path_image (\\<lambda>z. (g z, y2))\"\n    by (rule Path_Connected.path_image_join_subset)\n  also have \"\\<dots> \\<subseteq> (\\<Union>x\\<in>s. \\<Union>x1\\<in>t. {(x, x1)})\"\n    using g h \\<open>x1 \\<in> s\\<close> \\<open>y2 \\<in> t\\<close> by (force simp: path_image_def)\n  finally have 2: \"path_image ((\\<lambda>z. (x1, h z)) +++ (\\<lambda>z. (g z, y2))) \\<subseteq> (\\<Union>x\\<in>s. \\<Union>x1\\<in>t. {(x, x1)})\" .\n  show \"\\<exists>g. path g \\<and> path_image g \\<subseteq> (\\<Union>x\\<in>s. \\<Union>x1\\<in>t. {(x, x1)}) \\<and>\n            pathstart g = (x1, y1) \\<and> pathfinish g = (x2, y2)\"\n    using 1 2 gf hs\n    by (metis (no_types, lifting) pathfinish_def pathfinish_join pathstart_def pathstart_join)\nqed\n\nlemma is_interval_path_connected_1:\n  fixes s :: \"real set\"\n  shows \"is_interval s \\<longleftrightarrow> path_connected s\"\nusing is_interval_connected_1 is_interval_path_connected path_connected_imp_connected by blast\n\n\nsubsection\\<^marker>\\<open>tag unimportant\\<close>\\<open>Path components\\<close>\n\nlemma Union_path_component [simp]:\n   \"Union {path_component_set S x |x. x \\<in> S} = S\"\napply (rule subset_antisym)\nusing path_component_subset apply force\nusing path_component_refl by auto\n\nlemma path_component_disjoint:\n   \"disjnt (path_component_set S a) (path_component_set S b) \\<longleftrightarrow>\n    (a \\<notin> path_component_set S b)\"\n  unfolding disjnt_iff\n  using path_component_sym path_component_trans by blast\n\nlemma path_component_eq_eq:\n   \"path_component S x = path_component S y \\<longleftrightarrow>\n        (x \\<notin> S) \\<and> (y \\<notin> S) \\<or> x \\<in> S \\<and> y \\<in> S \\<and> path_component S x y\"\n    (is \"?lhs = ?rhs\")\nproof \n  assume ?lhs then show ?rhs\n    by (metis (no_types) path_component_mem(1) path_component_refl)\nnext\n  assume ?rhs then show ?lhs\n  proof\n    assume \"x \\<notin> S \\<and> y \\<notin> S\" then show ?lhs\n      by (metis Collect_empty_eq_bot path_component_eq_empty)\n  next\n    assume S: \"x \\<in> S \\<and> y \\<in> S \\<and> path_component S x y\" show ?lhs\n      by (rule ext) (metis S path_component_trans path_component_sym)\n  qed\nqed\n\nlemma path_component_unique:\n  assumes \"x \\<in> c\" \"c \\<subseteq> S\" \"path_connected c\"\n          \"\\<And>c'. \\<lbrakk>x \\<in> c'; c' \\<subseteq> S; path_connected c'\\<rbrakk> \\<Longrightarrow> c' \\<subseteq> c\"\n   shows \"path_component_set S x = c\"\n    (is \"?lhs = ?rhs\")\nproof \n  show \"?lhs \\<subseteq> ?rhs\"\n    using assms\n    by (metis mem_Collect_eq path_component_refl path_component_subset path_connected_path_component subsetD)\nqed (simp add: assms path_component_maximal)\n\nlemma path_component_intermediate_subset:\n   \"path_component_set u a \\<subseteq> t \\<and> t \\<subseteq> u\n        \\<Longrightarrow> path_component_set t a = path_component_set u a\"\nby (metis (no_types) path_component_mono path_component_path_component subset_antisym)\n\nlemma complement_path_component_Union:\n  fixes x :: \"'a :: topological_space\"\n  shows \"S - path_component_set S x =\n         \\<Union>({path_component_set S y| y. y \\<in> S} - {path_component_set S x})\"\nproof -\n  have *: \"(\\<And>x. x \\<in> S - {a} \\<Longrightarrow> disjnt a x) \\<Longrightarrow> \\<Union>S - a = \\<Union>(S - {a})\"\n    for a::\"'a set\" and S\n    by (auto simp: disjnt_def)\n  have \"\\<And>y. y \\<in> {path_component_set S x |x. x \\<in> S} - {path_component_set S x}\n            \\<Longrightarrow> disjnt (path_component_set S x) y\"\n    using path_component_disjoint path_component_eq by fastforce\n  then have \"\\<Union>{path_component_set S x |x. x \\<in> S} - path_component_set S x =\n             \\<Union>({path_component_set S y |y. y \\<in> S} - {path_component_set S x})\"\n    by (meson *)\n  then show ?thesis by simp\nqed\n\n\nsubsection\\<open>Path components\\<close>\n\ndefinition path_component_of\n  where \"path_component_of X x y \\<equiv> \\<exists>g. pathin X g \\<and> g 0 = x \\<and> g 1 = y\"\n\nabbreviation path_component_of_set\n  where \"path_component_of_set X x \\<equiv> Collect (path_component_of X x)\"\n\ndefinition path_components_of :: \"'a topology \\<Rightarrow> 'a set set\"\n  where \"path_components_of X \\<equiv> path_component_of_set X ` topspace X\"\n\nlemma pathin_canon_iff: \"pathin (top_of_set T) g \\<longleftrightarrow> path g \\<and> g ` {0..1} \\<subseteq> T\"\n  by (simp add: path_def pathin_def)\n\nlemma path_component_of_canon_iff [simp]:\n  \"path_component_of (top_of_set T) a b \\<longleftrightarrow> path_component T a b\"\n  by (simp add: path_component_of_def pathin_canon_iff path_defs)\n\nlemma path_component_in_topspace:\n   \"path_component_of X x y \\<Longrightarrow> x \\<in> topspace X \\<and> y \\<in> topspace X\"\n  by (auto simp: path_component_of_def pathin_def continuous_map_def)\n\nlemma path_component_of_refl:\n   \"path_component_of X x x \\<longleftrightarrow> x \\<in> topspace X\"\n  by (metis path_component_in_topspace path_component_of_def pathin_const)\n\nlemma path_component_of_sym:\n  assumes \"path_component_of X x y\"\n  shows \"path_component_of X y x\"\n  using assms\n  apply (clarsimp simp: path_component_of_def pathin_def)\n  apply (rule_tac x=\"g \\<circ> (\\<lambda>t. 1 - t)\" in exI)\n  apply (auto intro!: continuous_map_compose simp: continuous_map_in_subtopology continuous_on_op_minus)\n  done\n\nlemma path_component_of_sym_iff:\n   \"path_component_of X x y \\<longleftrightarrow> path_component_of X y x\"\n  by (metis path_component_of_sym)\n\nlemma continuous_map_cases_le:\n  assumes contp: \"continuous_map X euclideanreal p\"\n    and contq: \"continuous_map X euclideanreal q\"\n    and contf: \"continuous_map (subtopology X {x. x \\<in> topspace X \\<and> p x \\<le> q x}) Y f\"\n    and contg: \"continuous_map (subtopology X {x. x \\<in> topspace X \\<and> q x \\<le> p x}) Y g\"\n    and fg: \"\\<And>x. \\<lbrakk>x \\<in> topspace X; p x = q x\\<rbrakk> \\<Longrightarrow> f x = g x\"\n  shows \"continuous_map X Y (\\<lambda>x. if p x \\<le> q x then f x else g x)\"\nproof -\n  have \"continuous_map X Y (\\<lambda>x. if q x - p x \\<in> {0..} then f x else g x)\"\n  proof (rule continuous_map_cases_function)\n    show \"continuous_map X euclideanreal (\\<lambda>x. q x - p x)\"\n      by (intro contp contq continuous_intros)\n    show \"continuous_map (subtopology X {x \\<in> topspace X. q x - p x \\<in> euclideanreal closure_of {0..}}) Y f\"\n      by (simp add: contf)\n    show \"continuous_map (subtopology X {x \\<in> topspace X. q x - p x \\<in> euclideanreal closure_of (topspace euclideanreal - {0..})}) Y g\"\n      by (simp add: contg flip: Compl_eq_Diff_UNIV)\n  qed (auto simp: fg)\n  then show ?thesis\n    by simp\nqed\n\nlemma continuous_map_cases_lt:\n  assumes contp: \"continuous_map X euclideanreal p\"\n    and contq: \"continuous_map X euclideanreal q\"\n    and contf: \"continuous_map (subtopology X {x. x \\<in> topspace X \\<and> p x \\<le> q x}) Y f\"\n    and contg: \"continuous_map (subtopology X {x. x \\<in> topspace X \\<and> q x \\<le> p x}) Y g\"\n    and fg: \"\\<And>x. \\<lbrakk>x \\<in> topspace X; p x = q x\\<rbrakk> \\<Longrightarrow> f x = g x\"\n  shows \"continuous_map X Y (\\<lambda>x. if p x < q x then f x else g x)\"\nproof -\n  have \"continuous_map X Y (\\<lambda>x. if q x - p x \\<in> {0<..} then f x else g x)\"\n  proof (rule continuous_map_cases_function)\n    show \"continuous_map X euclideanreal (\\<lambda>x. q x - p x)\"\n      by (intro contp contq continuous_intros)\n    show \"continuous_map (subtopology X {x \\<in> topspace X. q x - p x \\<in> euclideanreal closure_of {0<..}}) Y f\"\n      by (simp add: contf)\n    show \"continuous_map (subtopology X {x \\<in> topspace X. q x - p x \\<in> euclideanreal closure_of (topspace euclideanreal - {0<..})}) Y g\"\n      by (simp add: contg flip: Compl_eq_Diff_UNIV)\n  qed (auto simp: fg)\n  then show ?thesis\n    by simp\nqed\n\nlemma path_component_of_trans:\n  assumes \"path_component_of X x y\" and \"path_component_of X y z\"\n  shows \"path_component_of X x z\"\n  unfolding path_component_of_def pathin_def\nproof -\n  let ?T01 = \"top_of_set {0..1::real}\"\n  obtain g1 g2 where g1: \"continuous_map ?T01 X g1\" \"x = g1 0\" \"y = g1 1\"\n    and g2: \"continuous_map ?T01 X g2\" \"g2 0 = g1 1\" \"z = g2 1\"\n    using assms unfolding path_component_of_def pathin_def by blast\n  let ?g = \"\\<lambda>x. if x \\<le> 1/2 then (g1 \\<circ> (\\<lambda>t. 2 * t)) x else (g2 \\<circ> (\\<lambda>t. 2 * t -1)) x\"\n  show \"\\<exists>g. continuous_map ?T01 X g \\<and> g 0 = x \\<and> g 1 = z\"\n  proof (intro exI conjI)\n    show \"continuous_map (subtopology euclideanreal {0..1}) X ?g\"\n    proof (intro continuous_map_cases_le continuous_map_compose, force, force)\n      show \"continuous_map (subtopology ?T01 {x \\<in> topspace ?T01. x \\<le> 1/2}) ?T01 ((*) 2)\"\n        by (auto simp: continuous_map_in_subtopology continuous_map_from_subtopology)\n      have \"continuous_map\n             (subtopology (top_of_set {0..1}) {x. 0 \\<le> x \\<and> x \\<le> 1 \\<and> 1 \\<le> x * 2})\n             euclideanreal (\\<lambda>t. 2 * t - 1)\"\n        by (intro continuous_intros) (force intro: continuous_map_from_subtopology)\n      then show \"continuous_map (subtopology ?T01 {x \\<in> topspace ?T01. 1/2 \\<le> x}) ?T01 (\\<lambda>t. 2 * t - 1)\"\n        by (force simp: continuous_map_in_subtopology)\n      show \"(g1 \\<circ> (*) 2) x = (g2 \\<circ> (\\<lambda>t. 2 * t - 1)) x\" if \"x \\<in> topspace ?T01\" \"x = 1/2\" for x\n        using that by (simp add: g2(2) mult.commute continuous_map_from_subtopology)\n    qed (auto simp: g1 g2)\n  qed (auto simp: g1 g2)\nqed\n\nlemma path_component_of_mono:\n   \"\\<lbrakk>path_component_of (subtopology X S) x y; S \\<subseteq> T\\<rbrakk> \\<Longrightarrow> path_component_of (subtopology X T) x y\"\n  unfolding path_component_of_def\n  by (metis subsetD pathin_subtopology)\n\nlemma path_component_of:\n  \"path_component_of X x y \\<longleftrightarrow> (\\<exists>T. path_connectedin X T \\<and> x \\<in> T \\<and> y \\<in> T)\"\n    (is \"?lhs = ?rhs\")\nproof \n  assume ?lhs then show ?rhs\n    by (metis atLeastAtMost_iff image_eqI order_refl path_component_of_def path_connectedin_path_image zero_le_one)\nnext\n  assume ?rhs then show ?lhs\n    by (metis path_component_of_def path_connectedin)\nqed\n\nlemma path_component_of_set:\n   \"path_component_of X x y \\<longleftrightarrow> (\\<exists>g. pathin X g \\<and> g 0 = x \\<and> g 1 = y)\"\n  by (auto simp: path_component_of_def)\n\nlemma path_component_of_subset_topspace:\n   \"Collect(path_component_of X x) \\<subseteq> topspace X\"\n  using path_component_in_topspace by fastforce\n\nlemma path_component_of_eq_empty:\n   \"Collect(path_component_of X x) = {} \\<longleftrightarrow> (x \\<notin> topspace X)\"\n  using path_component_in_topspace path_component_of_refl by fastforce\n\nlemma path_connected_space_iff_path_component:\n   \"path_connected_space X \\<longleftrightarrow> (\\<forall>x \\<in> topspace X. \\<forall>y \\<in> topspace X. path_component_of X x y)\"\n  by (simp add: path_component_of path_connected_space_subconnected)\n\nlemma path_connected_space_imp_path_component_of:\n   \"\\<lbrakk>path_connected_space X; a \\<in> topspace X; b \\<in> topspace X\\<rbrakk>\n        \\<Longrightarrow> path_component_of X a b\"\n  by (simp add: path_connected_space_iff_path_component)\n\nlemma path_connected_space_path_component_set:\n   \"path_connected_space X \\<longleftrightarrow> (\\<forall>x \\<in> topspace X. Collect(path_component_of X x) = topspace X)\"\n  using path_component_of_subset_topspace path_connected_space_iff_path_component by fastforce\n\nlemma path_component_of_maximal:\n   \"\\<lbrakk>path_connectedin X s; x \\<in> s\\<rbrakk> \\<Longrightarrow> s \\<subseteq> Collect(path_component_of X x)\"\n  using path_component_of by fastforce\n\nlemma path_component_of_equiv:\n   \"path_component_of X x y \\<longleftrightarrow> x \\<in> topspace X \\<and> y \\<in> topspace X \\<and> path_component_of X x = path_component_of X y\"\n    (is \"?lhs = ?rhs\")\nproof\n  assume ?lhs\n  then show ?rhs\n    apply (simp add: fun_eq_iff path_component_in_topspace)\n    apply (meson path_component_of_sym path_component_of_trans)\n    done\nqed (simp add: path_component_of_refl)\n\nlemma path_component_of_disjoint:\n     \"disjnt (Collect (path_component_of X x)) (Collect (path_component_of X y)) \\<longleftrightarrow>\n      ~(path_component_of X x y)\"\n  by (force simp: disjnt_def path_component_of_eq_empty path_component_of_equiv)\n\nlemma path_component_of_eq:\n   \"path_component_of X x = path_component_of X y \\<longleftrightarrow>\n        (x \\<notin> topspace X) \\<and> (y \\<notin> topspace X) \\<or>\n        x \\<in> topspace X \\<and> y \\<in> topspace X \\<and> path_component_of X x y\"\n  by (metis Collect_empty_eq_bot path_component_of_eq_empty path_component_of_equiv)\n\nlemma path_component_of_aux:\n  \"path_component_of X x y\n        \\<Longrightarrow> path_component_of (subtopology X (Collect (path_component_of X x))) x y\"\n    by (meson path_component_of path_component_of_maximal path_connectedin_subtopology)\n\nlemma path_connectedin_path_component_of:\n  \"path_connectedin X (Collect (path_component_of X x))\"\nproof -\n  have \"topspace (subtopology X (path_component_of_set X x)) = path_component_of_set X x\"\n    by (meson path_component_of_subset_topspace topspace_subtopology_subset)\n  then have \"path_connected_space (subtopology X (path_component_of_set X x))\"\n    by (metis (full_types) path_component_of_aux mem_Collect_eq path_component_of_equiv path_connected_space_iff_path_component)\n  then show ?thesis\n    by (simp add: path_component_of_subset_topspace path_connectedin_def)\nqed\n\nlemma path_connectedin_euclidean [simp]:\n   \"path_connectedin euclidean S \\<longleftrightarrow> path_connected S\"\n  by (auto simp: path_connectedin_def path_connected_space_iff_path_component path_connected_component)\n\nlemma path_connected_space_euclidean_subtopology [simp]:\n   \"path_connected_space(subtopology euclidean S) \\<longleftrightarrow> path_connected S\"\n  using path_connectedin_topspace by force\n\nlemma Union_path_components_of:\n     \"\\<Union>(path_components_of X) = topspace X\"\n  by (auto simp: path_components_of_def path_component_of_equiv)\n\nlemma path_components_of_maximal:\n   \"\\<lbrakk>C \\<in> path_components_of X; path_connectedin X S; ~disjnt C S\\<rbrakk> \\<Longrightarrow> S \\<subseteq> C\"\n  apply (auto simp: path_components_of_def path_component_of_equiv)\n  using path_component_of_maximal path_connectedin_def apply fastforce\n  by (meson disjnt_subset2 path_component_of_disjoint path_component_of_equiv path_component_of_maximal)\n\nlemma pairwise_disjoint_path_components_of:\n     \"pairwise disjnt (path_components_of X)\"\n  by (auto simp: path_components_of_def pairwise_def path_component_of_disjoint path_component_of_equiv)\n\nlemma complement_path_components_of_Union:\n   \"C \\<in> path_components_of X\n        \\<Longrightarrow> topspace X - C = \\<Union>(path_components_of X - {C})\"\n  by (metis Diff_cancel Diff_subset Union_path_components_of cSup_singleton diff_Union_pairwise_disjoint insert_subset pairwise_disjoint_path_components_of)\n\nlemma nonempty_path_components_of:\n  assumes \"C \\<in> path_components_of X\" shows \"C \\<noteq> {}\"\nproof -\n  have \"C \\<in> path_component_of_set X ` topspace X\"\n    using assms path_components_of_def by blast\n  then show ?thesis\n    using path_component_of_refl by fastforce\nqed\n\nlemma path_components_of_subset: \"C \\<in> path_components_of X \\<Longrightarrow> C \\<subseteq> topspace X\"\n  by (auto simp: path_components_of_def path_component_of_equiv)\n\nlemma path_connectedin_path_components_of:\n   \"C \\<in> path_components_of X \\<Longrightarrow> path_connectedin X C\"\n  by (auto simp: path_components_of_def path_connectedin_path_component_of)\n\nlemma path_component_in_path_components_of:\n  \"Collect (path_component_of X a) \\<in> path_components_of X \\<longleftrightarrow> a \\<in> topspace X\"\n  by (metis imageI nonempty_path_components_of path_component_of_eq_empty path_components_of_def)\n\nlemma path_connectedin_Union:\n  assumes \\<A>: \"\\<And>S. S \\<in> \\<A> \\<Longrightarrow> path_connectedin X S\" \"\\<Inter>\\<A> \\<noteq> {}\"\n  shows \"path_connectedin X (\\<Union>\\<A>)\"\nproof -\n  obtain a where \"\\<And>S. S \\<in> \\<A> \\<Longrightarrow> a \\<in> S\"\n    using assms by blast\n  then have \"\\<And>x. x \\<in> topspace (subtopology X (\\<Union>\\<A>)) \\<Longrightarrow> path_component_of (subtopology X (\\<Union>\\<A>)) a x\"\n    by simp (meson Union_upper \\<A> path_component_of path_connectedin_subtopology)\n  then show ?thesis\n    using \\<A> unfolding path_connectedin_def\n    by (metis Sup_le_iff path_component_of_equiv path_connected_space_iff_path_component)\nqed\n\nlemma path_connectedin_Un:\n   \"\\<lbrakk>path_connectedin X S; path_connectedin X T; S \\<inter> T \\<noteq> {}\\<rbrakk>\n    \\<Longrightarrow> path_connectedin X (S \\<union> T)\"\n  by (blast intro: path_connectedin_Union [of \"{S,T}\", simplified])\n\nlemma path_connected_space_iff_components_eq:\n  \"path_connected_space X \\<longleftrightarrow>\n    (\\<forall>C \\<in> path_components_of X. \\<forall>C' \\<in> path_components_of X. C = C')\"\n  unfolding path_components_of_def\nproof (intro iffI ballI)\n  assume \"\\<forall>C \\<in> path_component_of_set X ` topspace X.\n             \\<forall>C' \\<in> path_component_of_set X ` topspace X. C = C'\"\n  then show \"path_connected_space X\"\n    using path_component_of_refl path_connected_space_iff_path_component by fastforce\nqed (auto simp: path_connected_space_path_component_set)\n\nlemma path_components_of_eq_empty:\n   \"path_components_of X = {} \\<longleftrightarrow> topspace X = {}\"\n  using Union_path_components_of nonempty_path_components_of by fastforce\n\nlemma path_components_of_empty_space:\n   \"topspace X = {} \\<Longrightarrow> path_components_of X = {}\"\n  by (simp add: path_components_of_eq_empty)\n\nlemma path_components_of_subset_singleton:\n  \"path_components_of X \\<subseteq> {S} \\<longleftrightarrow>\n        path_connected_space X \\<and> (topspace X = {} \\<or> topspace X = S)\"\nproof (cases \"topspace X = {}\")\n  case True\n  then show ?thesis\n    by (auto simp: path_components_of_empty_space path_connected_space_topspace_empty)\nnext\n  case False\n  have \"(path_components_of X = {S}) \\<longleftrightarrow> (path_connected_space X \\<and> topspace X = S)\"\n  proof (intro iffI conjI)\n    assume L: \"path_components_of X = {S}\"\n    then show \"path_connected_space X\"\n      by (simp add: path_connected_space_iff_components_eq)\n    show \"topspace X = S\"\n      by (metis L ccpo_Sup_singleton [of S] Union_path_components_of)\n  next\n    assume R: \"path_connected_space X \\<and> topspace X = S\"\n    then show \"path_components_of X = {S}\"\n      using ccpo_Sup_singleton [of S]\n      by (metis False all_not_in_conv insert_iff mk_disjoint_insert path_component_in_path_components_of path_connected_space_iff_components_eq path_connected_space_path_component_set)\n  qed\n  with False show ?thesis\n    by (simp add: path_components_of_eq_empty subset_singleton_iff)\nqed\n\nlemma path_connected_space_iff_components_subset_singleton:\n   \"path_connected_space X \\<longleftrightarrow> (\\<exists>a. path_components_of X \\<subseteq> {a})\"\n  by (simp add: path_components_of_subset_singleton)\n\nlemma path_components_of_eq_singleton:\n   \"path_components_of X = {S} \\<longleftrightarrow> path_connected_space X \\<and> topspace X \\<noteq> {} \\<and> S = topspace X\"\n  by (metis cSup_singleton insert_not_empty path_components_of_subset_singleton subset_singleton_iff)\n\nlemma path_components_of_path_connected_space:\n   \"path_connected_space X \\<Longrightarrow> path_components_of X = (if topspace X = {} then {} else {topspace X})\"\n  by (simp add: path_components_of_eq_empty path_components_of_eq_singleton)\n\nlemma path_component_subset_connected_component_of:\n   \"path_component_of_set X x \\<subseteq> connected_component_of_set X x\"\nproof (cases \"x \\<in> topspace X\")\n  case True\n  then show ?thesis\n    by (simp add: connected_component_of_maximal path_component_of_refl path_connectedin_imp_connectedin path_connectedin_path_component_of)\nnext\n  case False\n  then show ?thesis\n    using path_component_of_eq_empty by fastforce\nqed\n\nlemma exists_path_component_of_superset:\n  assumes S: \"path_connectedin X S\" and ne: \"topspace X \\<noteq> {}\"\n  obtains C where \"C \\<in> path_components_of X\" \"S \\<subseteq> C\"\nproof (cases \"S = {}\")\n  case True\n  then show ?thesis\n    using ne path_components_of_eq_empty that by fastforce\nnext\n  case False\n  then obtain a where \"a \\<in> S\"\n    by blast\n  show ?thesis\n  proof\n    show \"Collect (path_component_of X a) \\<in> path_components_of X\"\n      by (meson \\<open>a \\<in> S\\<close> S subsetD path_component_in_path_components_of path_connectedin_subset_topspace)\n    show \"S \\<subseteq> Collect (path_component_of X a)\"\n      by (simp add: S \\<open>a \\<in> S\\<close> path_component_of_maximal)\n  qed\nqed\n\nlemma path_component_of_eq_overlap:\n   \"path_component_of X x = path_component_of X y \\<longleftrightarrow>\n      (x \\<notin> topspace X) \\<and> (y \\<notin> topspace X) \\<or>\n      Collect (path_component_of X x) \\<inter> Collect (path_component_of X y) \\<noteq> {}\"\n  by (metis disjnt_def empty_iff inf_bot_right mem_Collect_eq path_component_of_disjoint path_component_of_eq path_component_of_eq_empty)\n\nlemma path_component_of_nonoverlap:\n   \"Collect (path_component_of X x) \\<inter> Collect (path_component_of X y) = {} \\<longleftrightarrow>\n    (x \\<notin> topspace X) \\<or> (y \\<notin> topspace X) \\<or>\n    path_component_of X x \\<noteq> path_component_of X y\"\n  by (metis inf.idem path_component_of_eq_empty path_component_of_eq_overlap)\n\nlemma path_component_of_overlap:\n   \"Collect (path_component_of X x) \\<inter> Collect (path_component_of X y) \\<noteq> {} \\<longleftrightarrow>\n    x \\<in> topspace X \\<and> y \\<in> topspace X \\<and> path_component_of X x = path_component_of X y\"\n  by (meson path_component_of_nonoverlap)\n\nlemma path_components_of_disjoint:\n     \"\\<lbrakk>C \\<in> path_components_of X; C' \\<in> path_components_of X\\<rbrakk> \\<Longrightarrow> disjnt C C' \\<longleftrightarrow> C \\<noteq> C'\"\n  by (auto simp: path_components_of_def path_component_of_disjoint path_component_of_equiv)\n\nlemma path_components_of_overlap:\n    \"\\<lbrakk>C \\<in> path_components_of X; C' \\<in> path_components_of X\\<rbrakk> \\<Longrightarrow> C \\<inter> C' \\<noteq> {} \\<longleftrightarrow> C = C'\"\n  by (auto simp: path_components_of_def path_component_of_equiv)\n\nlemma path_component_of_unique:\n   \"\\<lbrakk>x \\<in> C; path_connectedin X C; \\<And>C'. \\<lbrakk>x \\<in> C'; path_connectedin X C'\\<rbrakk> \\<Longrightarrow> C' \\<subseteq> C\\<rbrakk>\n        \\<Longrightarrow> Collect (path_component_of X x) = C\"\n  by (meson subsetD eq_iff path_component_of_maximal path_connectedin_path_component_of)\n\nlemma path_component_of_discrete_topology [simp]:\n  \"Collect (path_component_of (discrete_topology U) x) = (if x \\<in> U then {x} else {})\"\nproof -\n  have \"\\<And>C'. \\<lbrakk>x \\<in> C'; path_connectedin (discrete_topology U) C'\\<rbrakk> \\<Longrightarrow> C' \\<subseteq> {x}\"\n    by (metis path_connectedin_discrete_topology subsetD singletonD)\n  then have \"x \\<in> U \\<Longrightarrow> Collect (path_component_of (discrete_topology U) x) = {x}\"\n    by (simp add: path_component_of_unique)\n  then show ?thesis\n    using path_component_in_topspace by fastforce\nqed\n\nlemma path_component_of_discrete_topology_iff [simp]:\n  \"path_component_of (discrete_topology U) x y \\<longleftrightarrow> x \\<in> U \\<and> y=x\"\n  by (metis empty_iff insertI1 mem_Collect_eq path_component_of_discrete_topology singletonD)\n\nlemma path_components_of_discrete_topology [simp]:\n   \"path_components_of (discrete_topology U) = (\\<lambda>x. {x}) ` U\"\n  by (auto simp: path_components_of_def image_def fun_eq_iff)\n\nlemma homeomorphic_map_path_component_of:\n  assumes f: \"homeomorphic_map X Y f\" and x: \"x \\<in> topspace X\"\n  shows \"Collect (path_component_of Y (f x)) = f ` Collect(path_component_of X x)\"\nproof -\n  obtain g where g: \"homeomorphic_maps X Y f g\"\n    using f homeomorphic_map_maps by blast\n  show ?thesis\n  proof\n    have \"Collect (path_component_of Y (f x)) \\<subseteq> topspace Y\"\n      by (simp add: path_component_of_subset_topspace)\n    moreover have \"g ` Collect(path_component_of Y (f x)) \\<subseteq> Collect (path_component_of X (g (f x)))\"\n      using g x unfolding homeomorphic_maps_def\n      by (metis f homeomorphic_imp_surjective_map imageI mem_Collect_eq path_component_of_maximal path_component_of_refl path_connectedin_continuous_map_image path_connectedin_path_component_of)\n    ultimately show \"Collect (path_component_of Y (f x)) \\<subseteq> f ` Collect (path_component_of X x)\"\n      using g x unfolding homeomorphic_maps_def continuous_map_def image_iff subset_iff\n      by metis\n    show \"f ` Collect (path_component_of X x) \\<subseteq> Collect (path_component_of Y (f x))\"\n    proof (rule path_component_of_maximal)\n      show \"path_connectedin Y (f ` Collect (path_component_of X x))\"\n        by (meson f homeomorphic_map_path_connectedness_eq path_connectedin_path_component_of)\n    qed (simp add: path_component_of_refl x)\n  qed\nqed\n\nlemma homeomorphic_map_path_components_of:\n  assumes \"homeomorphic_map X Y f\"\n  shows \"path_components_of Y = (image f) ` (path_components_of X)\"\n    (is \"?lhs = ?rhs\")\n  unfolding path_components_of_def homeomorphic_imp_surjective_map [OF assms, symmetric]\n  using assms homeomorphic_map_path_component_of by fastforce\n\n\nsubsection \\<open>Sphere is path-connected\\<close>\n\nlemma path_connected_punctured_universe:\n  assumes \"2 \\<le> DIM('a::euclidean_space)\"\n  shows \"path_connected (- {a::'a})\"\nproof -\n  let ?A = \"{x::'a. \\<exists>i\\<in>Basis. x \\<bullet> i < a \\<bullet> i}\"\n  let ?B = \"{x::'a. \\<exists>i\\<in>Basis. a \\<bullet> i < x \\<bullet> i}\"\n\n  have A: \"path_connected ?A\"\n    unfolding Collect_bex_eq\n  proof (rule path_connected_UNION)\n    fix i :: 'a\n    assume \"i \\<in> Basis\"\n    then show \"(\\<Sum>i\\<in>Basis. (a \\<bullet> i - 1)*\\<^sub>R i) \\<in> {x::'a. x \\<bullet> i < a \\<bullet> i}\"\n      by simp\n    show \"path_connected {x. x \\<bullet> i < a \\<bullet> i}\"\n      using convex_imp_path_connected [OF convex_halfspace_lt, of i \"a \\<bullet> i\"]\n      by (simp add: inner_commute)\n  qed\n  have B: \"path_connected ?B\"\n    unfolding Collect_bex_eq\n  proof (rule path_connected_UNION)\n    fix i :: 'a\n    assume \"i \\<in> Basis\"\n    then show \"(\\<Sum>i\\<in>Basis. (a \\<bullet> i + 1) *\\<^sub>R i) \\<in> {x::'a. a \\<bullet> i < x \\<bullet> i}\"\n      by simp\n    show \"path_connected {x. a \\<bullet> i < x \\<bullet> i}\"\n      using convex_imp_path_connected [OF convex_halfspace_gt, of \"a \\<bullet> i\" i]\n      by (simp add: inner_commute)\n  qed\n  obtain S :: \"'a set\" where \"S \\<subseteq> Basis\" and \"card S = Suc (Suc 0)\"\n    using ex_card[OF assms]\n    by auto\n  then obtain b0 b1 :: 'a where \"b0 \\<in> Basis\" and \"b1 \\<in> Basis\" and \"b0 \\<noteq> b1\"\n    unfolding card_Suc_eq by auto\n  then have \"a + b0 - b1 \\<in> ?A \\<inter> ?B\"\n    by (auto simp: inner_simps inner_Basis)\n  then have \"?A \\<inter> ?B \\<noteq> {}\"\n    by fast\n  with A B have \"path_connected (?A \\<union> ?B)\"\n    by (rule path_connected_Un)\n  also have \"?A \\<union> ?B = {x. \\<exists>i\\<in>Basis. x \\<bullet> i \\<noteq> a \\<bullet> i}\"\n    unfolding neq_iff bex_disj_distrib Collect_disj_eq ..\n  also have \"\\<dots> = {x. x \\<noteq> a}\"\n    unfolding euclidean_eq_iff [where 'a='a]\n    by (simp add: Bex_def)\n  also have \"\\<dots> = - {a}\"\n    by auto\n  finally show ?thesis .\nqed\n\ncorollary connected_punctured_universe:\n  \"2 \\<le> DIM('N::euclidean_space) \\<Longrightarrow> connected(- {a::'N})\"\n  by (simp add: path_connected_punctured_universe path_connected_imp_connected)\n\nproposition path_connected_sphere:\n  fixes a :: \"'a :: euclidean_space\"\n  assumes \"2 \\<le> DIM('a)\"\n  shows \"path_connected(sphere a r)\"\nproof (cases r \"0::real\" rule: linorder_cases)\n  case less\n  then show ?thesis\n    by (simp)\nnext\n  case equal\n  then show ?thesis\n    by (simp)\nnext\n  case greater\n  then have eq: \"(sphere (0::'a) r) = (\\<lambda>x. (r / norm x) *\\<^sub>R x) ` (- {0::'a})\"\n    by (force simp: image_iff split: if_split_asm)\n  have \"continuous_on (- {0::'a}) (\\<lambda>x. (r / norm x) *\\<^sub>R x)\"\n    by (intro continuous_intros) auto\n  then have \"path_connected ((\\<lambda>x. (r / norm x) *\\<^sub>R x) ` (- {0::'a}))\"\n    by (intro path_connected_continuous_image path_connected_punctured_universe assms)\n  with eq have \"path_connected (sphere (0::'a) r)\"\n    by auto\n  then have \"path_connected((+) a ` (sphere (0::'a) r))\"\n    by (simp add: path_connected_translation)\n  then show ?thesis\n    by (metis add.right_neutral sphere_translation)\nqed\n\nlemma connected_sphere:\n    fixes a :: \"'a :: euclidean_space\"\n    assumes \"2 \\<le> DIM('a)\"\n      shows \"connected(sphere a r)\"\n  using path_connected_sphere [OF assms]\n  by (simp add: path_connected_imp_connected)\n\n\ncorollary path_connected_complement_bounded_convex:\n    fixes S :: \"'a :: euclidean_space set\"\n    assumes \"bounded S\" \"convex S\" and 2: \"2 \\<le> DIM('a)\"\n    shows \"path_connected (- S)\"\nproof (cases \"S = {}\")\n  case True then show ?thesis\n    using convex_imp_path_connected by auto\nnext\n  case False\n  then obtain a where \"a \\<in> S\" by auto\n  have \\<section> [rule_format]: \"\\<forall>y\\<in>S. \\<forall>u. 0 \\<le> u \\<and> u \\<le> 1 \\<longrightarrow> (1 - u) *\\<^sub>R a + u *\\<^sub>R y \\<in> S\"\n    using \\<open>convex S\\<close> \\<open>a \\<in> S\\<close> by (simp add: convex_alt)\n  { fix x y assume \"x \\<notin> S\" \"y \\<notin> S\"\n    then have \"x \\<noteq> a\" \"y \\<noteq> a\" using \\<open>a \\<in> S\\<close> by auto\n    then have bxy: \"bounded(insert x (insert y S))\"\n      by (simp add: \\<open>bounded S\\<close>)\n    then obtain B::real where B: \"0 < B\" and Bx: \"norm (a - x) < B\" and By: \"norm (a - y) < B\"\n                          and \"S \\<subseteq> ball a B\"\n      using bounded_subset_ballD [OF bxy, of a] by (auto simp: dist_norm)\n    define C where \"C = B / norm(x - a)\"\n    let ?Cxa = \"a + C *\\<^sub>R (x - a)\"\n    { fix u\n      assume u: \"(1 - u) *\\<^sub>R x + u *\\<^sub>R ?Cxa \\<in> S\" and \"0 \\<le> u\" \"u \\<le> 1\"\n      have CC: \"1 \\<le> 1 + (C - 1) * u\"\n        using \\<open>x \\<noteq> a\\<close> \\<open>0 \\<le> u\\<close> Bx\n        by (auto simp add: C_def norm_minus_commute)\n      have *: \"\\<And>v. (1 - u) *\\<^sub>R x + u *\\<^sub>R (a + v *\\<^sub>R (x - a)) = a + (1 + (v - 1) * u) *\\<^sub>R (x - a)\"\n        by (simp add: algebra_simps)\n      have \"a + ((1 / (1 + C * u - u)) *\\<^sub>R x + ((u / (1 + C * u - u)) *\\<^sub>R a + (C * u / (1 + C * u - u)) *\\<^sub>R x)) =\n            (1 + (u / (1 + C * u - u))) *\\<^sub>R a + ((1 / (1 + C * u - u)) + (C * u / (1 + C * u - u))) *\\<^sub>R x\"\n        by (simp add: algebra_simps)\n      also have \"\\<dots> = (1 + (u / (1 + C * u - u))) *\\<^sub>R a + (1 + (u / (1 + C * u - u))) *\\<^sub>R x\"\n        using CC by (simp add: field_simps)\n      also have \"\\<dots> = x + (1 + (u / (1 + C * u - u))) *\\<^sub>R a + (u / (1 + C * u - u)) *\\<^sub>R x\"\n        by (simp add: algebra_simps)\n      also have \"\\<dots> = x + ((1 / (1 + C * u - u)) *\\<^sub>R a +\n              ((u / (1 + C * u - u)) *\\<^sub>R x + (C * u / (1 + C * u - u)) *\\<^sub>R a))\"\n        using CC by (simp add: field_simps) (simp add: add_divide_distrib scaleR_add_left)\n      finally have xeq: \"(1 - 1 / (1 + (C - 1) * u)) *\\<^sub>R a + (1 / (1 + (C - 1) * u)) *\\<^sub>R (a + (1 + (C - 1) * u) *\\<^sub>R (x - a)) = x\"\n        by (simp add: algebra_simps)\n      have False\n        using \\<section> [of \"a + (1 + (C - 1) * u) *\\<^sub>R (x - a)\" \"1 / (1 + (C - 1) * u)\"]\n        using u \\<open>x \\<noteq> a\\<close> \\<open>x \\<notin> S\\<close> \\<open>0 \\<le> u\\<close> CC\n        by (auto simp: xeq *)\n    }\n    then have pcx: \"path_component (- S) x ?Cxa\"\n      by (force simp: closed_segment_def intro!: path_component_linepath)\n    define D where \"D = B / norm(y - a)\"  \\<comment> \\<open>massive duplication with the proof above\\<close>\n    let ?Dya = \"a + D *\\<^sub>R (y - a)\"\n    { fix u\n      assume u: \"(1 - u) *\\<^sub>R y + u *\\<^sub>R ?Dya \\<in> S\" and \"0 \\<le> u\" \"u \\<le> 1\"\n      have DD: \"1 \\<le> 1 + (D - 1) * u\"\n        using \\<open>y \\<noteq> a\\<close> \\<open>0 \\<le> u\\<close> By\n        by (auto simp add: D_def norm_minus_commute)\n      have *: \"\\<And>v. (1 - u) *\\<^sub>R y + u *\\<^sub>R (a + v *\\<^sub>R (y - a)) = a + (1 + (v - 1) * u) *\\<^sub>R (y - a)\"\n        by (simp add: algebra_simps)\n      have \"a + ((1 / (1 + D * u - u)) *\\<^sub>R y + ((u / (1 + D * u - u)) *\\<^sub>R a + (D * u / (1 + D * u - u)) *\\<^sub>R y)) =\n            (1 + (u / (1 + D * u - u))) *\\<^sub>R a + ((1 / (1 + D * u - u)) + (D * u / (1 + D * u - u))) *\\<^sub>R y\"\n        by (simp add: algebra_simps)\n      also have \"\\<dots> = (1 + (u / (1 + D * u - u))) *\\<^sub>R a + (1 + (u / (1 + D * u - u))) *\\<^sub>R y\"\n        using DD by (simp add: field_simps)\n      also have \"\\<dots> = y + (1 + (u / (1 + D * u - u))) *\\<^sub>R a + (u / (1 + D * u - u)) *\\<^sub>R y\"\n        by (simp add: algebra_simps)\n      also have \"\\<dots> = y + ((1 / (1 + D * u - u)) *\\<^sub>R a +\n              ((u / (1 + D * u - u)) *\\<^sub>R y + (D * u / (1 + D * u - u)) *\\<^sub>R a))\"\n        using DD by (simp add: field_simps) (simp add: add_divide_distrib scaleR_add_left)\n      finally have xeq: \"(1 - 1 / (1 + (D - 1) * u)) *\\<^sub>R a + (1 / (1 + (D - 1) * u)) *\\<^sub>R (a + (1 + (D - 1) * u) *\\<^sub>R (y - a)) = y\"\n        by (simp add: algebra_simps)\n      have False\n        using \\<section> [of \"a + (1 + (D - 1) * u) *\\<^sub>R (y - a)\" \"1 / (1 + (D - 1) * u)\"]\n        using u \\<open>y \\<noteq> a\\<close> \\<open>y \\<notin> S\\<close> \\<open>0 \\<le> u\\<close> DD\n        by (auto simp: xeq *)\n    }\n    then have pdy: \"path_component (- S) y ?Dya\"\n      by (force simp: closed_segment_def intro!: path_component_linepath)\n    have pyx: \"path_component (- S) ?Dya ?Cxa\"\n    proof (rule path_component_of_subset)\n      show \"sphere a B \\<subseteq> - S\"\n        using \\<open>S \\<subseteq> ball a B\\<close> by (force simp: ball_def dist_norm norm_minus_commute)\n      have aB: \"?Dya \\<in> sphere a B\" \"?Cxa \\<in> sphere a B\"\n        using \\<open>x \\<noteq> a\\<close> using \\<open>y \\<noteq> a\\<close> B by (auto simp: dist_norm C_def D_def)\n      then show \"path_component (sphere a B) ?Dya ?Cxa\"\n        using path_connected_sphere [OF 2] path_connected_component by blast\n    qed\n    have \"path_component (- S) x y\"\n      by (metis path_component_trans path_component_sym pcx pdy pyx)\n  }\n  then show ?thesis\n    by (auto simp: path_connected_component)\nqed\n\nlemma connected_complement_bounded_convex:\n    fixes S :: \"'a :: euclidean_space set\"\n    assumes \"bounded S\" \"convex S\" \"2 \\<le> DIM('a)\"\n      shows  \"connected (- S)\"\n  using path_connected_complement_bounded_convex [OF assms] path_connected_imp_connected by blast\n\nlemma connected_diff_ball:\n    fixes S :: \"'a :: euclidean_space set\"\n    assumes \"connected S\" \"cball a r \\<subseteq> S\" \"2 \\<le> DIM('a)\"\n      shows \"connected (S - ball a r)\"\nproof (rule connected_diff_open_from_closed [OF ball_subset_cball])\n  show \"connected (cball a r - ball a r)\"\n    using assms connected_sphere by (auto simp: cball_diff_eq_sphere)\nqed (auto simp: assms dist_norm)\n\nproposition connected_open_delete:\n  assumes \"open S\" \"connected S\" and 2: \"2 \\<le> DIM('N::euclidean_space)\"\n    shows \"connected(S - {a::'N})\"\nproof (cases \"a \\<in> S\")\n  case True\n  with \\<open>open S\\<close> obtain \\<epsilon> where \"\\<epsilon> > 0\" and \\<epsilon>: \"cball a \\<epsilon> \\<subseteq> S\"\n    using open_contains_cball_eq by blast\n  define b where \"b \\<equiv> a + \\<epsilon> *\\<^sub>R (SOME i. i \\<in> Basis)\"\n  have \"dist a b = \\<epsilon>\"\n    by (simp add: b_def dist_norm SOME_Basis \\<open>0 < \\<epsilon>\\<close> less_imp_le)\n  with \\<epsilon> have \"b \\<in> \\<Inter>{S - ball a r |r. 0 < r \\<and> r < \\<epsilon>}\"\n    by auto\n  then have nonemp: \"(\\<Inter>{S - ball a r |r. 0 < r \\<and> r < \\<epsilon>}) = {} \\<Longrightarrow> False\"\n    by auto\n  have con: \"\\<And>r. r < \\<epsilon> \\<Longrightarrow> connected (S - ball a r)\"\n    using \\<epsilon> by (force intro: connected_diff_ball [OF \\<open>connected S\\<close> _ 2])\n  have \"x \\<in> \\<Union>{S - ball a r |r. 0 < r \\<and> r < \\<epsilon>}\" if \"x \\<in> S - {a}\" for x\n     using that \\<open>0 < \\<epsilon>\\<close> \n     by (intro UnionI [of \"S - ball a (min \\<epsilon> (dist a x) / 2)\"]) auto\n  then have \"S - {a} = \\<Union>{S - ball a r | r. 0 < r \\<and> r < \\<epsilon>}\"\n    by auto\n  then show ?thesis\n    by (auto intro: connected_Union con dest!: nonemp)\nnext\n  case False then show ?thesis\n    by (simp add: \\<open>connected S\\<close>)\nqed\n\ncorollary path_connected_open_delete:\n  assumes \"open S\" \"connected S\" and 2: \"2 \\<le> DIM('N::euclidean_space)\"\n  shows \"path_connected(S - {a::'N})\"\n  by (simp add: assms connected_open_delete connected_open_path_connected open_delete)\n\ncorollary path_connected_punctured_ball:\n  \"2 \\<le> DIM('N::euclidean_space) \\<Longrightarrow> path_connected(ball a r - {a::'N})\"\n  by (simp add: path_connected_open_delete)\n\ncorollary connected_punctured_ball:\n  \"2 \\<le> DIM('N::euclidean_space) \\<Longrightarrow> connected(ball a r - {a::'N})\"\n  by (simp add: connected_open_delete)\n\ncorollary connected_open_delete_finite:\n  fixes S T::\"'a::euclidean_space set\"\n  assumes S: \"open S\" \"connected S\" and 2: \"2 \\<le> DIM('a)\" and \"finite T\"\n  shows \"connected(S - T)\"\n  using \\<open>finite T\\<close> S\nproof (induct T)\n  case empty\n  show ?case using \\<open>connected S\\<close> by simp\nnext\n  case (insert x F)\n  then have \"connected (S-F)\" by auto\n  moreover have \"open (S - F)\" using finite_imp_closed[OF \\<open>finite F\\<close>] \\<open>open S\\<close> by auto\n  ultimately have \"connected (S - F - {x})\" using connected_open_delete[OF _ _ 2] by auto\n  thus ?case by (metis Diff_insert)\nqed\n\nlemma sphere_1D_doubleton_zero:\n  assumes 1: \"DIM('a) = 1\" and \"r > 0\"\n  obtains x y::\"'a::euclidean_space\"\n    where \"sphere 0 r = {x,y} \\<and> dist x y = 2*r\"\nproof -\n  obtain b::'a where b: \"Basis = {b}\"\n    using 1 card_1_singletonE by blast\n  show ?thesis\n  proof (intro that conjI)\n    have \"x = norm x *\\<^sub>R b \\<or> x = - norm x *\\<^sub>R b\" if \"r = norm x\" for x\n    proof -\n      have xb: \"(x \\<bullet> b) *\\<^sub>R b = x\"\n        using euclidean_representation [of x, unfolded b] by force\n      then have \"norm ((x \\<bullet> b) *\\<^sub>R b) = norm x\"\n        by simp\n      with b have \"\\<bar>x \\<bullet> b\\<bar> = norm x\"\n        using norm_Basis by (simp add: b)\n      with xb show ?thesis\n        by (metis (mono_tags, opaque_lifting) abs_eq_iff abs_norm_cancel)\n    qed\n    with \\<open>r > 0\\<close> b show \"sphere 0 r = {r *\\<^sub>R b, - r *\\<^sub>R b}\"\n      by (force simp: sphere_def dist_norm)\n    have \"dist (r *\\<^sub>R b) (- r *\\<^sub>R b) = norm (r *\\<^sub>R b + r *\\<^sub>R b)\"\n      by (simp add: dist_norm)\n    also have \"\\<dots> = norm ((2*r) *\\<^sub>R b)\"\n      by (metis mult_2 scaleR_add_left)\n    also have \"\\<dots> = 2*r\"\n      using \\<open>r > 0\\<close> b norm_Basis by fastforce\n    finally show \"dist (r *\\<^sub>R b) (- r *\\<^sub>R b) = 2*r\" .\n  qed\nqed\n\nlemma sphere_1D_doubleton:\n  fixes a :: \"'a :: euclidean_space\"\n  assumes \"DIM('a) = 1\" and \"r > 0\"\n  obtains x y where \"sphere a r = {x,y} \\<and> dist x y = 2*r\"\nproof -\n  have \"sphere a r = (+) a ` sphere 0 r\"\n    by (metis add.right_neutral sphere_translation)\n  then show ?thesis\n    using sphere_1D_doubleton_zero [OF assms]\n    by (metis (mono_tags, lifting) dist_add_cancel image_empty image_insert that)\nqed\n\nlemma psubset_sphere_Compl_connected:\n  fixes S :: \"'a::euclidean_space set\"\n  assumes S: \"S \\<subset> sphere a r\" and \"0 < r\" and 2: \"2 \\<le> DIM('a)\"\n  shows \"connected(- S)\"\nproof -\n  have \"S \\<subseteq> sphere a r\"\n    using S by blast\n  obtain b where \"dist a b = r\" and \"b \\<notin> S\"\n    using S mem_sphere by blast\n  have CS: \"- S = {x. dist a x \\<le> r \\<and> (x \\<notin> S)} \\<union> {x. r \\<le> dist a x \\<and> (x \\<notin> S)}\"\n    by auto\n  have \"{x. dist a x \\<le> r \\<and> x \\<notin> S} \\<inter> {x. r \\<le> dist a x \\<and> x \\<notin> S} \\<noteq> {}\"\n    using \\<open>b \\<notin> S\\<close> \\<open>dist a b = r\\<close> by blast\n  moreover have \"connected {x. dist a x \\<le> r \\<and> x \\<notin> S}\"\n    using assms\n    by (force intro: connected_intermediate_closure [of \"ball a r\"])\n  moreover\n  have \"connected {x. r \\<le> dist a x \\<and> x \\<notin> S}\"\n  proof (rule connected_intermediate_closure [of \"- cball a r\"])\n    show \"{x. r \\<le> dist a x \\<and> x \\<notin> S} \\<subseteq> closure (- cball a r)\"\n      using interior_closure by (force intro: connected_complement_bounded_convex)\n  qed (use assms connected_complement_bounded_convex in auto)\n  ultimately show ?thesis\n    by (simp add: CS connected_Un)\nqed\n\n\nsubsection\\<open>Every annulus is a connected set\\<close>\n\nlemma path_connected_2DIM_I:\n  fixes a :: \"'N::euclidean_space\"\n  assumes 2: \"2 \\<le> DIM('N)\" and pc: \"path_connected {r. 0 \\<le> r \\<and> P r}\"\n  shows \"path_connected {x. P(norm(x - a))}\"\nproof -\n  have \"{x. P(norm(x - a))} = (+) a ` {x. P(norm x)}\"\n    by force\n  moreover have \"path_connected {x::'N. P(norm x)}\"\n  proof -\n    let ?D = \"{x. 0 \\<le> x \\<and> P x} \\<times> sphere (0::'N) 1\"\n    have \"x \\<in> (\\<lambda>z. fst z *\\<^sub>R snd z) ` ?D\"\n      if \"P (norm x)\" for x::'N\n    proof (cases \"x=0\")\n      case True\n      with that show ?thesis\n        apply (simp add: image_iff)\n        by (metis (no_types) mem_sphere_0 order_refl vector_choose_size zero_le_one)\n    next\n      case False\n      with that show ?thesis\n        by (rule_tac x=\"(norm x, x /\\<^sub>R norm x)\" in image_eqI) auto\n    qed\n    then have *: \"{x::'N. P(norm x)} =  (\\<lambda>z. fst z *\\<^sub>R snd z) ` ?D\"\n      by auto\n    have \"continuous_on ?D (\\<lambda>z:: real\\<times>'N. fst z *\\<^sub>R snd z)\"\n      by (intro continuous_intros)\n    moreover have \"path_connected ?D\"\n      by (metis path_connected_Times [OF pc] path_connected_sphere 2)\n    ultimately show ?thesis\n      by (simp add: \"*\" path_connected_continuous_image)\n  qed\n  ultimately show ?thesis\n    using path_connected_translation by metis\nqed\n\nproposition path_connected_annulus:\n  fixes a :: \"'N::euclidean_space\"\n  assumes \"2 \\<le> DIM('N)\"\n  shows \"path_connected {x. r1 < norm(x - a) \\<and> norm(x - a) < r2}\"\n        \"path_connected {x. r1 < norm(x - a) \\<and> norm(x - a) \\<le> r2}\"\n        \"path_connected {x. r1 \\<le> norm(x - a) \\<and> norm(x - a) < r2}\"\n        \"path_connected {x. r1 \\<le> norm(x - a) \\<and> norm(x - a) \\<le> r2}\"\n  by (auto simp: is_interval_def intro!: is_interval_convex convex_imp_path_connected path_connected_2DIM_I [OF assms])\n\nproposition connected_annulus:\n  fixes a :: \"'N::euclidean_space\"\n  assumes \"2 \\<le> DIM('N::euclidean_space)\"\n  shows \"connected {x. r1 < norm(x - a) \\<and> norm(x - a) < r2}\"\n        \"connected {x. r1 < norm(x - a) \\<and> norm(x - a) \\<le> r2}\"\n        \"connected {x. r1 \\<le> norm(x - a) \\<and> norm(x - a) < r2}\"\n        \"connected {x. r1 \\<le> norm(x - a) \\<and> norm(x - a) \\<le> r2}\"\n  by (auto simp: path_connected_annulus [OF assms] path_connected_imp_connected)\n\n\nsubsection\\<^marker>\\<open>tag unimportant\\<close>\\<open>Relations between components and path components\\<close>\n\nlemma open_connected_component:\n  fixes S :: \"'a::real_normed_vector set\"\n  assumes \"open S\"\n  shows \"open (connected_component_set S x)\"\nproof (clarsimp simp: open_contains_ball)\n  fix y\n  assume xy: \"connected_component S x y\"\n  then obtain e where \"e>0\" \"ball y e \\<subseteq> S\"\n    using assms connected_component_in openE by blast\n  then show \"\\<exists>e>0. ball y e  \\<subseteq> connected_component_set S x\"\n    by (metis xy centre_in_ball connected_ball connected_component_eq_eq connected_component_in connected_component_maximal)\nqed\n\ncorollary open_components:\n    fixes S :: \"'a::real_normed_vector set\"\n    shows \"\\<lbrakk>open u; S \\<in> components u\\<rbrakk> \\<Longrightarrow> open S\"\n  by (simp add: components_iff) (metis open_connected_component)\n\nlemma in_closure_connected_component:\n  fixes S :: \"'a::real_normed_vector set\"\n  assumes x: \"x \\<in> S\" and S: \"open S\"\n  shows \"x \\<in> closure (connected_component_set S y) \\<longleftrightarrow>  x \\<in> connected_component_set S y\"\nproof -\n  { assume \"x \\<in> closure (connected_component_set S y)\"\n    moreover have \"x \\<in> connected_component_set S x\"\n      using x by simp\n    ultimately have \"x \\<in> connected_component_set S y\"\n      using S by (meson Compl_disjoint closure_iff_nhds_not_empty connected_component_disjoint disjoint_eq_subset_Compl open_connected_component)\n  }\n  then show ?thesis\n    by (auto simp: closure_def)\nqed\n\nlemma connected_disjoint_Union_open_pick:\n  assumes \"pairwise disjnt B\"\n          \"\\<And>S. S \\<in> A \\<Longrightarrow> connected S \\<and> S \\<noteq> {}\"\n          \"\\<And>S. S \\<in> B \\<Longrightarrow> open S\"\n          \"\\<Union>A \\<subseteq> \\<Union>B\"\n          \"S \\<in> A\"\n  obtains T where \"T \\<in> B\" \"S \\<subseteq> T\" \"S \\<inter> \\<Union>(B - {T}) = {}\"\nproof -\n  have \"S \\<subseteq> \\<Union>B\" \"connected S\" \"S \\<noteq> {}\"\n    using assms \\<open>S \\<in> A\\<close> by blast+\n  then obtain T where \"T \\<in> B\" \"S \\<inter> T \\<noteq> {}\"\n    by (metis Sup_inf_eq_bot_iff inf.absorb_iff2 inf_commute)\n  have 1: \"open T\" by (simp add: \\<open>T \\<in> B\\<close> assms)\n  have 2: \"open (\\<Union>(B-{T}))\" using assms by blast\n  have 3: \"S \\<subseteq> T \\<union> \\<Union>(B - {T})\" using \\<open>S \\<subseteq> \\<Union>B\\<close> by blast\n  have \"T \\<inter> \\<Union>(B - {T}) = {}\" using \\<open>T \\<in> B\\<close> \\<open>pairwise disjnt B\\<close>\n    by (auto simp: pairwise_def disjnt_def)\n  then have 4: \"T \\<inter> \\<Union>(B - {T}) \\<inter> S = {}\" by auto\n  from connectedD [OF \\<open>connected S\\<close> 1 2 4 3]\n  have \"S \\<inter> \\<Union>(B-{T}) = {}\"\n    by (auto simp: Int_commute \\<open>S \\<inter> T \\<noteq> {}\\<close>)\n  with \\<open>T \\<in> B\\<close> have \"S \\<subseteq> T\"\n    using \"3\" by auto\n  show ?thesis\n    using \\<open>S \\<inter> \\<Union>(B - {T}) = {}\\<close> \\<open>S \\<subseteq> T\\<close> \\<open>T \\<in> B\\<close> that by auto\nqed\n\nlemma connected_disjoint_Union_open_subset:\n  assumes A: \"pairwise disjnt A\" and B: \"pairwise disjnt B\"\n      and SA: \"\\<And>S. S \\<in> A \\<Longrightarrow> open S \\<and> connected S \\<and> S \\<noteq> {}\"\n      and SB: \"\\<And>S. S \\<in> B \\<Longrightarrow> open S \\<and> connected S \\<and> S \\<noteq> {}\"\n      and eq [simp]: \"\\<Union>A = \\<Union>B\"\n    shows \"A \\<subseteq> B\"\nproof\n  fix S\n  assume \"S \\<in> A\"\n  obtain T where \"T \\<in> B\" \"S \\<subseteq> T\" \"S \\<inter> \\<Union>(B - {T}) = {}\"\n    using SA SB \\<open>S \\<in> A\\<close> connected_disjoint_Union_open_pick [OF B, of A] eq order_refl by blast\n  moreover obtain S' where \"S' \\<in> A\" \"T \\<subseteq> S'\" \"T \\<inter> \\<Union>(A - {S'}) = {}\"\n    using SA SB \\<open>T \\<in> B\\<close> connected_disjoint_Union_open_pick [OF A, of B] eq order_refl by blast\n  ultimately have \"S' = S\"\n    by (metis A Int_subset_iff SA \\<open>S \\<in> A\\<close> disjnt_def inf.orderE pairwise_def)\n  with \\<open>T \\<subseteq> S'\\<close> have \"T \\<subseteq> S\" by simp\n  with \\<open>S \\<subseteq> T\\<close> have \"S = T\" by blast\n  with \\<open>T \\<in> B\\<close> show \"S \\<in> B\" by simp\nqed\n\nlemma connected_disjoint_Union_open_unique:\n  assumes A: \"pairwise disjnt A\" and B: \"pairwise disjnt B\"\n      and SA: \"\\<And>S. S \\<in> A \\<Longrightarrow> open S \\<and> connected S \\<and> S \\<noteq> {}\"\n      and SB: \"\\<And>S. S \\<in> B \\<Longrightarrow> open S \\<and> connected S \\<and> S \\<noteq> {}\"\n      and eq [simp]: \"\\<Union>A = \\<Union>B\"\n    shows \"A = B\"\nby (rule subset_antisym; metis connected_disjoint_Union_open_subset assms)\n\nproposition components_open_unique:\n fixes S :: \"'a::real_normed_vector set\"\n  assumes \"pairwise disjnt A\" \"\\<Union>A = S\"\n          \"\\<And>X. X \\<in> A \\<Longrightarrow> open X \\<and> connected X \\<and> X \\<noteq> {}\"\n    shows \"components S = A\"\nproof -\n  have \"open S\" using assms by blast\n  show ?thesis\n  proof (rule connected_disjoint_Union_open_unique)\n    show \"disjoint (components S)\"\n      by (simp add: components_eq disjnt_def pairwise_def)\n  qed (use \\<open>open S\\<close> in \\<open>simp_all add: assms open_components in_components_connected in_components_nonempty\\<close>)\nqed\n\n\nsubsection\\<^marker>\\<open>tag unimportant\\<close>\\<open>Existence of unbounded components\\<close>\n\nlemma cobounded_unbounded_component:\n    fixes S :: \"'a :: euclidean_space set\"\n    assumes \"bounded (-S)\"\n      shows \"\\<exists>x. x \\<in> S \\<and> \\<not> bounded (connected_component_set S x)\"\nproof -\n  obtain i::'a where i: \"i \\<in> Basis\"\n    using nonempty_Basis by blast\n  obtain B where B: \"B>0\" \"-S \\<subseteq> ball 0 B\"\n    using bounded_subset_ballD [OF assms, of 0] by auto\n  then have *: \"\\<And>x. B \\<le> norm x \\<Longrightarrow> x \\<in> S\"\n    by (force simp: ball_def dist_norm)\n  have unbounded_inner: \"\\<not> bounded {x. inner i x \\<ge> B}\"\n  proof (clarsimp simp: bounded_def dist_norm)\n    fix e x\n    show \"\\<exists>y. B \\<le> i \\<bullet> y \\<and> \\<not> norm (x - y) \\<le> e\"\n      using i\n      by (rule_tac x=\"x + (max B e + 1 + \\<bar>i \\<bullet> x\\<bar>) *\\<^sub>R i\" in exI) (auto simp: inner_right_distrib)\n  qed\n  have \\<section>: \"\\<And>x. B \\<le> i \\<bullet> x \\<Longrightarrow> x \\<in> S\"\n    using * Basis_le_norm [OF i] by (metis abs_ge_self inner_commute order_trans)\n  have \"{x. B \\<le> i \\<bullet> x} \\<subseteq> connected_component_set S (B *\\<^sub>R i)\"\n    by (intro connected_component_maximal) (auto simp: i intro: convex_connected convex_halfspace_ge [of B] \\<section>)\n  then have \"\\<not> bounded (connected_component_set S (B *\\<^sub>R i))\"\n    using bounded_subset unbounded_inner by blast\n  moreover have \"B *\\<^sub>R i \\<in> S\"\n    by (rule *) (simp add: norm_Basis [OF i])\n  ultimately show ?thesis\n    by blast\nqed\n\nlemma cobounded_unique_unbounded_component:\n    fixes S :: \"'a :: euclidean_space set\"\n    assumes bs: \"bounded (-S)\" and \"2 \\<le> DIM('a)\"\n        and bo: \"\\<not> bounded(connected_component_set S x)\"\n                \"\\<not> bounded(connected_component_set S y)\"\n      shows \"connected_component_set S x = connected_component_set S y\"\nproof -\n  obtain i::'a where i: \"i \\<in> Basis\"\n    using nonempty_Basis by blast\n  obtain B where B: \"B>0\" \"-S \\<subseteq> ball 0 B\"\n    using bounded_subset_ballD [OF bs, of 0] by auto\n  then have *: \"\\<And>x. B \\<le> norm x \\<Longrightarrow> x \\<in> S\"\n    by (force simp: ball_def dist_norm)\n  obtain x' where x': \"connected_component S x x'\" \"norm x' > B\"\n    using bo [unfolded bounded_def dist_norm, simplified, rule_format]\n    by (metis diff_zero norm_minus_commute not_less)\n  obtain y' where y': \"connected_component S y y'\" \"norm y' > B\"\n    using bo [unfolded bounded_def dist_norm, simplified, rule_format]\n    by (metis diff_zero norm_minus_commute not_less)\n  have x'y': \"connected_component S x' y'\"\n    unfolding connected_component_def\n  proof (intro exI conjI)\n    show \"connected (- ball 0 B :: 'a set)\"\n      using assms by (auto intro: connected_complement_bounded_convex)\n  qed (use x' y' dist_norm * in auto)\n  show ?thesis\n  proof (rule connected_component_eq)\n    show \"x \\<in> connected_component_set S y\"\n      using x' y' x'y'\n      by (metis (no_types) connected_component_eq_eq connected_component_in mem_Collect_eq)\n  qed\nqed\n\nlemma cobounded_unbounded_components:\n    fixes S :: \"'a :: euclidean_space set\"\n    shows \"bounded (-S) \\<Longrightarrow> \\<exists>c. c \\<in> components S \\<and> \\<not>bounded c\"\n  by (metis cobounded_unbounded_component components_def imageI)\n\nlemma cobounded_unique_unbounded_components:\n    fixes S :: \"'a :: euclidean_space set\"\n    shows  \"\\<lbrakk>bounded (- S); c \\<in> components S; \\<not> bounded c; c' \\<in> components S; \\<not> bounded c'; 2 \\<le> DIM('a)\\<rbrakk> \\<Longrightarrow> c' = c\"\n  unfolding components_iff\n  by (metis cobounded_unique_unbounded_component)\n\nlemma cobounded_has_bounded_component:\n  fixes S :: \"'a :: euclidean_space set\"\n  assumes \"bounded (- S)\" \"\\<not> connected S\" \"2 \\<le> DIM('a)\"\n  obtains C where \"C \\<in> components S\" \"bounded C\"\n  by (meson cobounded_unique_unbounded_components connected_eq_connected_components_eq assms)\n\n\nsubsection\\<open>The \\<open>inside\\<close> and \\<open>outside\\<close> of a Set\\<close>\n\ntext\\<^marker>\\<open>tag important\\<close>\\<open>The inside comprises the points in a bounded connected component of the set's complement.\n  The outside comprises the points in unbounded connected component of the complement.\\<close>\n\ndefinition\\<^marker>\\<open>tag important\\<close> inside where\n  \"inside S \\<equiv> {x. (x \\<notin> S) \\<and> bounded(connected_component_set ( - S) x)}\"\n\ndefinition\\<^marker>\\<open>tag important\\<close> outside where\n  \"outside S \\<equiv> -S \\<inter> {x. \\<not> bounded(connected_component_set (- S) x)}\"\n\nlemma outside: \"outside S = {x. \\<not> bounded(connected_component_set (- S) x)}\"\n  by (auto simp: outside_def) (metis Compl_iff bounded_empty connected_component_eq_empty)\n\nlemma inside_no_overlap [simp]: \"inside S \\<inter> S = {}\"\n  by (auto simp: inside_def)\n\nlemma outside_no_overlap [simp]:\n   \"outside S \\<inter> S = {}\"\n  by (auto simp: outside_def)\n\nlemma inside_Int_outside [simp]: \"inside S \\<inter> outside S = {}\"\n  by (auto simp: inside_def outside_def)\n\nlemma inside_Un_outside [simp]: \"inside S \\<union> outside S = (- S)\"\n  by (auto simp: inside_def outside_def)\n\nlemma inside_eq_outside:\n   \"inside S = outside S \\<longleftrightarrow> S = UNIV\"\n  by (auto simp: inside_def outside_def)\n\nlemma inside_outside: \"inside S = (- (S \\<union> outside S))\"\n  by (force simp: inside_def outside)\n\nlemma outside_inside: \"outside S = (- (S \\<union> inside S))\"\n  by (auto simp: inside_outside) (metis IntI equals0D outside_no_overlap)\n\nlemma union_with_inside: \"S \\<union> inside S = - outside S\"\n  by (auto simp: inside_outside) (simp add: outside_inside)\n\nlemma union_with_outside: \"S \\<union> outside S = - inside S\"\n  by (simp add: inside_outside)\n\nlemma outside_mono: \"S \\<subseteq> T \\<Longrightarrow> outside T \\<subseteq> outside S\"\n  by (auto simp: outside bounded_subset connected_component_mono)\n\nlemma inside_mono: \"S \\<subseteq> T \\<Longrightarrow> inside S - T \\<subseteq> inside T\"\n  by (auto simp: inside_def bounded_subset connected_component_mono)\n\nlemma segment_bound_lemma:\n  fixes u::real\n  assumes \"x \\<ge> B\" \"y \\<ge> B\" \"0 \\<le> u\" \"u \\<le> 1\"\n  shows \"(1 - u) * x + u * y \\<ge> B\"\nproof -\n  obtain dx dy where \"dx \\<ge> 0\" \"dy \\<ge> 0\" \"x = B + dx\" \"y = B + dy\"\n    using assms by auto (metis add.commute diff_add_cancel)\n  with \\<open>0 \\<le> u\\<close> \\<open>u \\<le> 1\\<close> show ?thesis\n    by (simp add: add_increasing2 mult_left_le field_simps)\nqed\n\nlemma cobounded_outside:\n  fixes S :: \"'a :: real_normed_vector set\"\n  assumes \"bounded S\" shows \"bounded (- outside S)\"\nproof -\n  obtain B where B: \"B>0\" \"S \\<subseteq> ball 0 B\"\n    using bounded_subset_ballD [OF assms, of 0] by auto\n  { fix x::'a and C::real\n    assume Bno: \"B \\<le> norm x\" and C: \"0 < C\"\n    have \"\\<exists>y. connected_component (- S) x y \\<and> norm y > C\"\n    proof (cases \"x = 0\")\n      case True with B Bno show ?thesis by force\n    next\n      case False \n      have \"closed_segment x (((B + C) / norm x) *\\<^sub>R x) \\<subseteq> - ball 0 B\"\n      proof\n        fix w\n        assume \"w \\<in> closed_segment x (((B + C) / norm x) *\\<^sub>R x)\"\n        then obtain u where\n          w: \"w = (1 - u + u * (B + C) / norm x) *\\<^sub>R x\" \"0 \\<le> u\" \"u \\<le> 1\"\n          by (auto simp add: closed_segment_def real_vector_class.scaleR_add_left [symmetric])\n        with False B C have \"B \\<le> (1 - u) * norm x + u * (B + C)\"\n          using segment_bound_lemma [of B \"norm x\" \"B + C\" u] Bno\n          by simp\n        with False B C show \"w \\<in> - ball 0 B\"\n          using distrib_right [of _ _ \"norm x\"]\n          by (simp add: ball_def w not_less)\n      qed\n      also have \"... \\<subseteq> -S\"\n        by (simp add: B)\n      finally have \"\\<exists>T. connected T \\<and> T \\<subseteq> - S \\<and> x \\<in> T \\<and> ((B + C) / norm x) *\\<^sub>R x \\<in> T\"\n        by (rule_tac x=\"closed_segment x (((B+C)/norm x) *\\<^sub>R x)\" in exI) simp\n      with False B\n      show ?thesis\n        by (rule_tac x=\"((B+C)/norm x) *\\<^sub>R x\" in exI) (simp add: connected_component_def)\n    qed\n  }\n  then show ?thesis\n    apply (simp add: outside_def assms)\n    apply (rule bounded_subset [OF bounded_ball [of 0 B]])\n    apply (force simp: dist_norm not_less bounded_pos)\n    done\nqed\n\nlemma unbounded_outside:\n    fixes S :: \"'a::{real_normed_vector, perfect_space} set\"\n    shows \"bounded S \\<Longrightarrow> \\<not> bounded(outside S)\"\n  using cobounded_imp_unbounded cobounded_outside by blast\n\nlemma bounded_inside:\n    fixes S :: \"'a::{real_normed_vector, perfect_space} set\"\n    shows \"bounded S \\<Longrightarrow> bounded(inside S)\"\n  by (simp add: bounded_Int cobounded_outside inside_outside)\n\nlemma connected_outside:\n    fixes S :: \"'a::euclidean_space set\"\n    assumes \"bounded S\" \"2 \\<le> DIM('a)\"\n      shows \"connected(outside S)\"\n  apply (clarsimp simp add: connected_iff_connected_component outside)\n  apply (rule_tac S=\"connected_component_set (- S) x\" in connected_component_of_subset)\n  apply (metis (no_types) assms cobounded_unbounded_component cobounded_unique_unbounded_component connected_component_eq_eq connected_component_idemp double_complement mem_Collect_eq)\n  by (simp add: Collect_mono connected_component_eq)\n\nlemma outside_connected_component_lt:\n  \"outside S = {x. \\<forall>B. \\<exists>y. B < norm(y) \\<and> connected_component (- S) x y}\"\n  apply (auto simp: outside bounded_def dist_norm)\n   apply (metis diff_0 norm_minus_cancel not_less)\n  by (metis less_diff_eq norm_minus_commute norm_triangle_ineq2 order.trans pinf(6))\n\nlemma outside_connected_component_le:\n  \"outside S = {x. \\<forall>B. \\<exists>y. B \\<le> norm(y) \\<and> connected_component (- S) x y}\"\n  apply (simp add: outside_connected_component_lt Set.set_eq_iff)\n  by (meson gt_ex leD le_less_linear less_imp_le order.trans)\n\nlemma not_outside_connected_component_lt:\n    fixes S :: \"'a::euclidean_space set\"\n    assumes S: \"bounded S\" and \"2 \\<le> DIM('a)\"\n      shows \"- (outside S) = {x. \\<forall>B. \\<exists>y. B < norm(y) \\<and> \\<not> connected_component (- S) x y}\"\nproof -\n  obtain B::real where B: \"0 < B\" and Bno: \"\\<And>x. x \\<in> S \\<Longrightarrow> norm x \\<le> B\"\n    using S [simplified bounded_pos] by auto\n  { fix y::'a and z::'a\n    assume yz: \"B < norm z\" \"B < norm y\"\n    have \"connected_component (- cball 0 B) y z\"\n      using assms yz\n      by (force simp: dist_norm intro: connected_componentI [OF _ subset_refl] connected_complement_bounded_convex)\n    then have \"connected_component (- S) y z\"\n      by (metis connected_component_of_subset Bno Compl_anti_mono mem_cball_0 subset_iff)\n  } note cyz = this\n  show ?thesis\n    apply (auto simp: outside bounded_pos)\n    apply (metis Compl_iff bounded_iff cobounded_imp_unbounded mem_Collect_eq not_le)\n    by (metis B connected_component_trans cyz not_le)\nqed\n\nlemma not_outside_connected_component_le:\n  fixes S :: \"'a::euclidean_space set\"\n  assumes S: \"bounded S\"  \"2 \\<le> DIM('a)\"\n  shows \"- (outside S) = {x. \\<forall>B. \\<exists>y. B \\<le> norm(y) \\<and> \\<not> connected_component (- S) x y}\"\n  apply (auto intro: less_imp_le simp: not_outside_connected_component_lt [OF assms])\n  by (meson gt_ex less_le_trans)\n\nlemma inside_connected_component_lt:\n    fixes S :: \"'a::euclidean_space set\"\n    assumes S: \"bounded S\"  \"2 \\<le> DIM('a)\"\n      shows \"inside S = {x. (x \\<notin> S) \\<and> (\\<forall>B. \\<exists>y. B < norm(y) \\<and> \\<not> connected_component (- S) x y)}\"\n  by (auto simp: inside_outside not_outside_connected_component_lt [OF assms])\n\nlemma inside_connected_component_le:\n    fixes S :: \"'a::euclidean_space set\"\n    assumes S: \"bounded S\"  \"2 \\<le> DIM('a)\"\n      shows \"inside S = {x. (x \\<notin> S) \\<and> (\\<forall>B. \\<exists>y. B \\<le> norm(y) \\<and> \\<not> connected_component (- S) x y)}\"\n  by (auto simp: inside_outside not_outside_connected_component_le [OF assms])\n\nlemma inside_subset:\n  assumes \"connected U\" and \"\\<not> bounded U\" and \"T \\<union> U = - S\"\n  shows \"inside S \\<subseteq> T\"\n  apply (auto simp: inside_def)\n  by (metis bounded_subset [of \"connected_component_set (- S) _\"] connected_component_maximal\n      Compl_iff Un_iff assms subsetI)\n\nlemma frontier_not_empty:\n  fixes S :: \"'a :: real_normed_vector set\"\n  shows \"\\<lbrakk>S \\<noteq> {}; S \\<noteq> UNIV\\<rbrakk> \\<Longrightarrow> frontier S \\<noteq> {}\"\n    using connected_Int_frontier [of UNIV S] by auto\n\nlemma frontier_eq_empty:\n  fixes S :: \"'a :: real_normed_vector set\"\n  shows \"frontier S = {} \\<longleftrightarrow> S = {} \\<or> S = UNIV\"\nusing frontier_UNIV frontier_empty frontier_not_empty by blast\n\nlemma frontier_of_connected_component_subset:\n  fixes S :: \"'a::real_normed_vector set\"\n  shows \"frontier(connected_component_set S x) \\<subseteq> frontier S\"\nproof -\n  { fix y\n    assume y1: \"y \\<in> closure (connected_component_set S x)\"\n       and y2: \"y \\<notin> interior (connected_component_set S x)\"\n    have \"y \\<in> closure S\"\n      using y1 closure_mono connected_component_subset by blast\n    moreover have \"z \\<in> interior (connected_component_set S x)\"\n          if \"0 < e\" \"ball y e \\<subseteq> interior S\" \"dist y z < e\" for e z\n    proof -\n      have \"ball y e \\<subseteq> connected_component_set S y\"\n        using connected_component_maximal that interior_subset \n        by (metis centre_in_ball connected_ball subset_trans)\n      then show ?thesis\n        using y1 apply (simp add: closure_approachable open_contains_ball_eq [OF open_interior])\n        by (metis connected_component_eq dist_commute mem_Collect_eq mem_ball mem_interior subsetD \\<open>0 < e\\<close> y2)\n    qed\n    then have \"y \\<notin> interior S\"\n      using y2 by (force simp: open_contains_ball_eq [OF open_interior])\n    ultimately have \"y \\<in> frontier S\"\n      by (auto simp: frontier_def)\n  }\n  then show ?thesis by (auto simp: frontier_def)\nqed\n\nlemma frontier_Union_subset_closure:\n  fixes F :: \"'a::real_normed_vector set set\"\n  shows \"frontier(\\<Union>F) \\<subseteq> closure(\\<Union>t \\<in> F. frontier t)\"\nproof -\n  have \"\\<exists>y\\<in>F. \\<exists>y\\<in>frontier y. dist y x < e\"\n       if \"T \\<in> F\" \"y \\<in> T\" \"dist y x < e\"\n          \"x \\<notin> interior (\\<Union>F)\" \"0 < e\" for x y e T\n  proof (cases \"x \\<in> T\")\n    case True with that show ?thesis\n      by (metis Diff_iff Sup_upper closure_subset contra_subsetD dist_self frontier_def interior_mono)\n  next\n    case False\n    have 1: \"closed_segment x y \\<inter> T \\<noteq> {}\" \n      using \\<open>y \\<in> T\\<close> by blast\n    have 2: \"closed_segment x y - T \\<noteq> {}\"\n      using False by blast\n    obtain c where \"c \\<in> closed_segment x y\" \"c \\<in> frontier T\"\n       using False connected_Int_frontier [OF connected_segment 1 2] by auto\n    then show ?thesis\n    proof -\n      have \"norm (y - x) < e\"\n        by (metis dist_norm \\<open>dist y x < e\\<close>)\n      moreover have \"norm (c - x) \\<le> norm (y - x)\"\n        by (simp add: \\<open>c \\<in> closed_segment x y\\<close> segment_bound(1))\n      ultimately have \"norm (c - x) < e\"\n        by linarith\n      then show ?thesis\n        by (metis (no_types) \\<open>c \\<in> frontier T\\<close> dist_norm that(1))\n    qed\n  qed\n  then show ?thesis\n    by (fastforce simp add: frontier_def closure_approachable)\nqed\n\nlemma frontier_Union_subset:\n  fixes F :: \"'a::real_normed_vector set set\"\n  shows \"finite F \\<Longrightarrow> frontier(\\<Union>F) \\<subseteq> (\\<Union>t \\<in> F. frontier t)\"\nby (rule order_trans [OF frontier_Union_subset_closure])\n   (auto simp: closure_subset_eq)\n\nlemma frontier_of_components_subset:\n  fixes S :: \"'a::real_normed_vector set\"\n  shows \"C \\<in> components S \\<Longrightarrow> frontier C \\<subseteq> frontier S\"\n  by (metis Path_Connected.frontier_of_connected_component_subset components_iff)\n\nlemma frontier_of_components_closed_complement:\n  fixes S :: \"'a::real_normed_vector set\"\n  shows \"\\<lbrakk>closed S; C \\<in> components (- S)\\<rbrakk> \\<Longrightarrow> frontier C \\<subseteq> S\"\n  using frontier_complement frontier_of_components_subset frontier_subset_eq by blast\n\nlemma frontier_minimal_separating_closed:\n  fixes S :: \"'a::real_normed_vector set\"\n  assumes \"closed S\"\n      and nconn: \"\\<not> connected(- S)\"\n      and C: \"C \\<in> components (- S)\"\n      and conn: \"\\<And>T. \\<lbrakk>closed T; T \\<subset> S\\<rbrakk> \\<Longrightarrow> connected(- T)\"\n    shows \"frontier C = S\"\nproof (rule ccontr)\n  assume \"frontier C \\<noteq> S\"\n  then have \"frontier C \\<subset> S\"\n    using frontier_of_components_closed_complement [OF \\<open>closed S\\<close> C] by blast\n  then have \"connected(- (frontier C))\"\n    by (simp add: conn)\n  have \"\\<not> connected(- (frontier C))\"\n    unfolding connected_def not_not\n  proof (intro exI conjI)\n    show \"open C\"\n      using C \\<open>closed S\\<close> open_components by blast\n    show \"open (- closure C)\"\n      by blast\n    show \"C \\<inter> - closure C \\<inter> - frontier C = {}\"\n      using closure_subset by blast\n    show \"C \\<inter> - frontier C \\<noteq> {}\"\n      using C \\<open>open C\\<close> components_eq frontier_disjoint_eq by fastforce\n    show \"- frontier C \\<subseteq> C \\<union> - closure C\"\n      by (simp add: \\<open>open C\\<close> closed_Compl frontier_closures)\n    then show \"- closure C \\<inter> - frontier C \\<noteq> {}\"\n      by (metis (no_types, lifting) C Compl_subset_Compl_iff \\<open>frontier C \\<subset> S\\<close> compl_sup frontier_closures in_components_subset psubsetE sup.absorb_iff2 sup.boundedE sup_bot.right_neutral sup_inf_absorb)\n  qed\n  then show False\n    using \\<open>connected (- frontier C)\\<close> by blast\nqed\n\nlemma connected_component_UNIV [simp]:\n    fixes x :: \"'a::real_normed_vector\"\n    shows \"connected_component_set UNIV x = UNIV\"\nusing connected_iff_eq_connected_component_set [of \"UNIV::'a set\"] connected_UNIV\nby auto\n\nlemma connected_component_eq_UNIV:\n    fixes x :: \"'a::real_normed_vector\"\n    shows \"connected_component_set s x = UNIV \\<longleftrightarrow> s = UNIV\"\n  using connected_component_in connected_component_UNIV by blast\n\nlemma components_UNIV [simp]: \"components UNIV = {UNIV :: 'a::real_normed_vector set}\"\n  by (auto simp: components_eq_sing_iff)\n\nlemma interior_inside_frontier:\n    fixes S :: \"'a::real_normed_vector set\"\n    assumes \"bounded S\"\n      shows \"interior S \\<subseteq> inside (frontier S)\"\nproof -\n  { fix x y\n    assume x: \"x \\<in> interior S\" and y: \"y \\<notin> S\"\n       and cc: \"connected_component (- frontier S) x y\"\n    have \"connected_component_set (- frontier S) x \\<inter> frontier S \\<noteq> {}\"\n    proof (rule connected_Int_frontier; simp add: set_eq_iff)\n      show \"\\<exists>u. connected_component (- frontier S) x u \\<and> u \\<in> S\"\n        by (meson cc connected_component_in connected_component_refl_eq interior_subset subsetD x)\n      show \"\\<exists>u. connected_component (- frontier S) x u \\<and> u \\<notin> S\"\n        using y cc by blast\n    qed\n    then have \"bounded (connected_component_set (- frontier S) x)\"\n      using connected_component_in by auto\n  }\n  then show ?thesis\n    apply (auto simp: inside_def frontier_def)\n    apply (rule classical)\n    apply (rule bounded_subset [OF assms], blast)\n    done\nqed\n\nlemma inside_empty [simp]: \"inside {} = ({} :: 'a :: {real_normed_vector, perfect_space} set)\"\n  by (simp add: inside_def)\n\nlemma outside_empty [simp]: \"outside {} = (UNIV :: 'a :: {real_normed_vector, perfect_space} set)\"\n  using inside_empty inside_Un_outside by blast\n\nlemma inside_same_component:\n   \"\\<lbrakk>connected_component (- S) x y; x \\<in> inside S\\<rbrakk> \\<Longrightarrow> y \\<in> inside S\"\n  using connected_component_eq connected_component_in\n  by (fastforce simp add: inside_def)\n\nlemma outside_same_component:\n   \"\\<lbrakk>connected_component (- S) x y; x \\<in> outside S\\<rbrakk> \\<Longrightarrow> y \\<in> outside S\"\n  using connected_component_eq connected_component_in\n  by (fastforce simp add: outside_def)\n\nlemma convex_in_outside:\n  fixes S :: \"'a :: {real_normed_vector, perfect_space} set\"\n  assumes S: \"convex S\" and z: \"z \\<notin> S\"\n    shows \"z \\<in> outside S\"\nproof (cases \"S={}\")\n  case True then show ?thesis by simp\nnext\n  case False then obtain a where \"a \\<in> S\" by blast\n  with z have zna: \"z \\<noteq> a\" by auto\n  { assume \"bounded (connected_component_set (- S) z)\"\n    with bounded_pos_less obtain B where \"B>0\" and B: \"\\<And>x. connected_component (- S) z x \\<Longrightarrow> norm x < B\"\n      by (metis mem_Collect_eq)\n    define C where \"C = (B + 1 + norm z) / norm (z-a)\"\n    have \"C > 0\"\n      using \\<open>0 < B\\<close> zna by (simp add: C_def field_split_simps add_strict_increasing)\n    have \"\\<bar>norm (z + C *\\<^sub>R (z-a)) - norm (C *\\<^sub>R (z-a))\\<bar> \\<le> norm z\"\n      by (metis add_diff_cancel norm_triangle_ineq3)\n    moreover have \"norm (C *\\<^sub>R (z-a)) > norm z + B\"\n      using zna \\<open>B>0\\<close> by (simp add: C_def le_max_iff_disj)\n    ultimately have C: \"norm (z + C *\\<^sub>R (z-a)) > B\" by linarith\n    { fix u::real\n      assume u: \"0\\<le>u\" \"u\\<le>1\" and ins: \"(1 - u) *\\<^sub>R z + u *\\<^sub>R (z + C *\\<^sub>R (z - a)) \\<in> S\"\n      then have Cpos: \"1 + u * C > 0\"\n        by (meson \\<open>0 < C\\<close> add_pos_nonneg less_eq_real_def zero_le_mult_iff zero_less_one)\n      then have *: \"(1 / (1 + u * C)) *\\<^sub>R z + (u * C / (1 + u * C)) *\\<^sub>R z = z\"\n        by (simp add: scaleR_add_left [symmetric] field_split_simps)\n      then have False\n        using convexD_alt [OF S \\<open>a \\<in> S\\<close> ins, of \"1/(u*C + 1)\"] \\<open>C>0\\<close> \\<open>z \\<notin> S\\<close> Cpos u\n        by (simp add: * field_split_simps)\n    } note contra = this\n    have \"connected_component (- S) z (z + C *\\<^sub>R (z-a))\"\n    proof (rule connected_componentI [OF connected_segment])\n      show \"closed_segment z (z + C *\\<^sub>R (z - a)) \\<subseteq> - S\"\n        using contra by (force simp add: closed_segment_def)\n    qed auto\n    then have False\n      using zna B [of \"z + C *\\<^sub>R (z-a)\"] C\n      by (auto simp: field_split_simps max_mult_distrib_right)\n  }\n  then show ?thesis\n    by (auto simp: outside_def z)\nqed\n\nlemma outside_convex:\n  fixes S :: \"'a :: {real_normed_vector, perfect_space} set\"\n  assumes \"convex S\"\n    shows \"outside S = - S\"\n  by (metis ComplD assms convex_in_outside equalityI inside_Un_outside subsetI sup.cobounded2)\n\nlemma outside_singleton [simp]:\n  fixes x :: \"'a :: {real_normed_vector, perfect_space}\"\n  shows \"outside {x} = -{x}\"\n  by (auto simp: outside_convex)\n\nlemma inside_convex:\n  fixes S :: \"'a :: {real_normed_vector, perfect_space} set\"\n  shows \"convex S \\<Longrightarrow> inside S = {}\"\n  by (simp add: inside_outside outside_convex)\n\nlemma inside_singleton [simp]:\n  fixes x :: \"'a :: {real_normed_vector, perfect_space}\"\n  shows \"inside {x} = {}\"\n  by (auto simp: inside_convex)\n\nlemma outside_subset_convex:\n  fixes S :: \"'a :: {real_normed_vector, perfect_space} set\"\n  shows \"\\<lbrakk>convex T; S \\<subseteq> T\\<rbrakk> \\<Longrightarrow> - T \\<subseteq> outside S\"\n  using outside_convex outside_mono by blast\n\nlemma outside_Un_outside_Un:\n  fixes S :: \"'a::real_normed_vector set\"\n  assumes \"S \\<inter> outside(T \\<union> U) = {}\"\n  shows \"outside(T \\<union> U) \\<subseteq> outside(T \\<union> S)\"\nproof\n  fix x\n  assume x: \"x \\<in> outside (T \\<union> U)\"\n  have \"Y \\<subseteq> - S\" if \"connected Y\" \"Y \\<subseteq> - T\" \"Y \\<subseteq> - U\" \"x \\<in> Y\" \"u \\<in> Y\" for u Y\n  proof -\n    have \"Y \\<subseteq> connected_component_set (- (T \\<union> U)) x\"\n      by (simp add: connected_component_maximal that)\n    also have \"\\<dots> \\<subseteq> outside(T \\<union> U)\"\n      by (metis (mono_tags, lifting) Collect_mono mem_Collect_eq outside outside_same_component x)\n    finally have \"Y \\<subseteq> outside(T \\<union> U)\" .\n    with assms show ?thesis by auto\n  qed\n  with x show \"x \\<in> outside (T \\<union> S)\"\n    by (simp add: outside_connected_component_lt connected_component_def) meson\nqed\n\nlemma outside_frontier_misses_closure:\n    fixes S :: \"'a::real_normed_vector set\"\n    assumes \"bounded S\"\n    shows  \"outside(frontier S) \\<subseteq> - closure S\"\n  unfolding outside_inside boolean_algebra_class.compl_le_compl_iff\nproof -\n  { assume \"interior S \\<subseteq> inside (frontier S)\"\n    hence \"interior S \\<union> inside (frontier S) = inside (frontier S)\"\n      by (simp add: subset_Un_eq)\n    then have \"closure S \\<subseteq> frontier S \\<union> inside (frontier S)\"\n      using frontier_def by auto\n  }\n  then show \"closure S \\<subseteq> frontier S \\<union> inside (frontier S)\"\n    using interior_inside_frontier [OF assms] by blast\nqed\n\nlemma outside_frontier_eq_complement_closure:\n  fixes S :: \"'a :: {real_normed_vector, perfect_space} set\"\n    assumes \"bounded S\" \"convex S\"\n      shows \"outside(frontier S) = - closure S\"\nby (metis Diff_subset assms convex_closure frontier_def outside_frontier_misses_closure\n          outside_subset_convex subset_antisym)\n\nlemma inside_frontier_eq_interior:\n     fixes S :: \"'a :: {real_normed_vector, perfect_space} set\"\n     shows \"\\<lbrakk>bounded S; convex S\\<rbrakk> \\<Longrightarrow> inside(frontier S) = interior S\"\n  apply (simp add: inside_outside outside_frontier_eq_complement_closure)\n  using closure_subset interior_subset\n  apply (auto simp: frontier_def)\n  done\n\nlemma open_inside:\n    fixes S :: \"'a::real_normed_vector set\"\n    assumes \"closed S\"\n      shows \"open (inside S)\"\nproof -\n  { fix x assume x: \"x \\<in> inside S\"\n    have \"open (connected_component_set (- S) x)\"\n      using assms open_connected_component by blast\n    then obtain e where e: \"e>0\" and e: \"\\<And>y. dist y x < e \\<longrightarrow> connected_component (- S) x y\"\n      using dist_not_less_zero\n      apply (simp add: open_dist)\n      by (metis (no_types, lifting) Compl_iff connected_component_refl_eq inside_def mem_Collect_eq x)\n    then have \"\\<exists>e>0. ball x e \\<subseteq> inside S\"\n      by (metis e dist_commute inside_same_component mem_ball subsetI x)\n  }\n  then show ?thesis\n    by (simp add: open_contains_ball)\nqed\n\nlemma open_outside:\n    fixes S :: \"'a::real_normed_vector set\"\n    assumes \"closed S\"\n      shows \"open (outside S)\"\nproof -\n  { fix x assume x: \"x \\<in> outside S\"\n    have \"open (connected_component_set (- S) x)\"\n      using assms open_connected_component by blast\n    then obtain e where e: \"e>0\" and e: \"\\<And>y. dist y x < e \\<longrightarrow> connected_component (- S) x y\"\n      using dist_not_less_zero x\n      by (auto simp add: open_dist outside_def intro: connected_component_refl)\n    then have \"\\<exists>e>0. ball x e \\<subseteq> outside S\"\n      by (metis e dist_commute outside_same_component mem_ball subsetI x)\n  }\n  then show ?thesis\n    by (simp add: open_contains_ball)\nqed\n\nlemma closure_inside_subset:\n    fixes S :: \"'a::real_normed_vector set\"\n    assumes \"closed S\"\n      shows \"closure(inside S) \\<subseteq> S \\<union> inside S\"\nby (metis assms closure_minimal open_closed open_outside sup.cobounded2 union_with_inside)\n\nlemma frontier_inside_subset:\n    fixes S :: \"'a::real_normed_vector set\"\n    assumes \"closed S\"\n      shows \"frontier(inside S) \\<subseteq> S\"\nproof -\n  have \"closure (inside S) \\<inter> - inside S = closure (inside S) - interior (inside S)\"\n    by (metis (no_types) Diff_Compl assms closure_closed interior_closure open_closed open_inside)\n  moreover have \"- inside S \\<inter> - outside S = S\"\n    by (metis (no_types) compl_sup double_compl inside_Un_outside)\n  moreover have \"closure (inside S) \\<subseteq> - outside S\"\n    by (metis (no_types) assms closure_inside_subset union_with_inside)\n  ultimately have \"closure (inside S) - interior (inside S) \\<subseteq> S\"\n    by blast\n  then show ?thesis\n    by (simp add: frontier_def open_inside interior_open)\nqed\n\nlemma closure_outside_subset:\n    fixes S :: \"'a::real_normed_vector set\"\n    assumes \"closed S\"\n      shows \"closure(outside S) \\<subseteq> S \\<union> outside S\"\n  by (metis assms closed_open closure_minimal inside_outside open_inside sup_ge2)\n\nlemma frontier_outside_subset:\n  fixes S :: \"'a::real_normed_vector set\"\n  assumes \"closed S\"\n  shows \"frontier(outside S) \\<subseteq> S\"\n  unfolding frontier_def\n  by (metis Diff_subset_conv assms closure_outside_subset interior_eq open_outside sup_aci(1))\n\nlemma inside_complement_unbounded_connected_empty:\n     \"\\<lbrakk>connected (- S); \\<not> bounded (- S)\\<rbrakk> \\<Longrightarrow> inside S = {}\"\n  using inside_subset by blast\n\nlemma inside_bounded_complement_connected_empty:\n    fixes S :: \"'a::{real_normed_vector, perfect_space} set\"\n    shows \"\\<lbrakk>connected (- S); bounded S\\<rbrakk> \\<Longrightarrow> inside S = {}\"\n  by (metis inside_complement_unbounded_connected_empty cobounded_imp_unbounded)\n\nlemma inside_inside:\n    assumes \"S \\<subseteq> inside T\"\n    shows \"inside S - T \\<subseteq> inside T\"\nunfolding inside_def\nproof clarify\n  fix x\n  assume x: \"x \\<notin> T\" \"x \\<notin> S\" and bo: \"bounded (connected_component_set (- S) x)\"\n  show \"bounded (connected_component_set (- T) x)\"\n  proof (cases \"S \\<inter> connected_component_set (- T) x = {}\")\n    case True then show ?thesis\n      by (metis bounded_subset [OF bo] compl_le_compl_iff connected_component_idemp connected_component_mono disjoint_eq_subset_Compl double_compl)\n  next\n    case False \n    then obtain y where y: \"y  \\<in> S\" \"y \\<in> connected_component_set (- T) x\"\n      by (meson disjoint_iff)\n    then have \"bounded (connected_component_set (- T) y)\"\n      using assms [unfolded inside_def] by blast\n    with y show ?thesis\n      by (metis connected_component_eq)\n  qed\nqed\n\nlemma inside_inside_subset: \"inside(inside S) \\<subseteq> S\"\n  using inside_inside union_with_outside by fastforce\n\nlemma inside_outside_intersect_connected:\n      \"\\<lbrakk>connected T; inside S \\<inter> T \\<noteq> {}; outside S \\<inter> T \\<noteq> {}\\<rbrakk> \\<Longrightarrow> S \\<inter> T \\<noteq> {}\"\n  apply (simp add: inside_def outside_def ex_in_conv [symmetric] disjoint_eq_subset_Compl, clarify)\n  by (metis (no_types, opaque_lifting) Compl_anti_mono connected_component_eq connected_component_maximal contra_subsetD double_compl)\n\nlemma outside_bounded_nonempty:\n  fixes S :: \"'a :: {real_normed_vector, perfect_space} set\"\n    assumes \"bounded S\" shows \"outside S \\<noteq> {}\"\n  by (metis (no_types, lifting) Collect_empty_eq Collect_mem_eq Compl_eq_Diff_UNIV Diff_cancel\n                   Diff_disjoint UNIV_I assms ball_eq_empty bounded_diff cobounded_outside convex_ball\n                   double_complement order_refl outside_convex outside_def)\n\nlemma outside_compact_in_open:\n    fixes S :: \"'a :: {real_normed_vector,perfect_space} set\"\n    assumes S: \"compact S\" and T: \"open T\" and \"S \\<subseteq> T\" \"T \\<noteq> {}\"\n      shows \"outside S \\<inter> T \\<noteq> {}\"\nproof -\n  have \"outside S \\<noteq> {}\"\n    by (simp add: compact_imp_bounded outside_bounded_nonempty S)\n  with assms obtain a b where a: \"a \\<in> outside S\" and b: \"b \\<in> T\" by auto\n  show ?thesis\n  proof (cases \"a \\<in> T\")\n    case True with a show ?thesis by blast\n  next\n    case False\n      have front: \"frontier T \\<subseteq> - S\"\n        using \\<open>S \\<subseteq> T\\<close> frontier_disjoint_eq T by auto\n      { fix \\<gamma>\n        assume \"path \\<gamma>\" and pimg_sbs: \"path_image \\<gamma> - {pathfinish \\<gamma>} \\<subseteq> interior (- T)\"\n           and pf: \"pathfinish \\<gamma> \\<in> frontier T\" and ps: \"pathstart \\<gamma> = a\"\n        define c where \"c = pathfinish \\<gamma>\"\n        have \"c \\<in> -S\" unfolding c_def using front pf by blast\n        moreover have \"open (-S)\" using S compact_imp_closed by blast\n        ultimately obtain \\<epsilon>::real where \"\\<epsilon> > 0\" and \\<epsilon>: \"cball c \\<epsilon> \\<subseteq> -S\"\n          using open_contains_cball[of \"-S\"] S by blast\n        then obtain d where \"d \\<in> T\" and d: \"dist d c < \\<epsilon>\"\n          using closure_approachable [of c T] pf unfolding c_def\n          by (metis Diff_iff frontier_def)\n        then have \"d \\<in> -S\" using \\<epsilon>\n          using dist_commute by (metis contra_subsetD mem_cball not_le not_less_iff_gr_or_eq)\n        have pimg_sbs_cos: \"path_image \\<gamma> \\<subseteq> -S\"\n          using \\<open>c \\<in> - S\\<close> \\<open>S \\<subseteq> T\\<close> c_def interior_subset pimg_sbs by fastforce\n        have \"closed_segment c d \\<le> cball c \\<epsilon>\"\n          by (metis \\<open>0 < \\<epsilon>\\<close> centre_in_cball closed_segment_subset convex_cball d dist_commute less_eq_real_def mem_cball)\n        with \\<epsilon> have \"closed_segment c d \\<subseteq> -S\" by blast\n        moreover have con_gcd: \"connected (path_image \\<gamma> \\<union> closed_segment c d)\"\n          by (rule connected_Un) (auto simp: c_def \\<open>path \\<gamma>\\<close> connected_path_image)\n        ultimately have \"connected_component (- S) a d\"\n          unfolding connected_component_def using pimg_sbs_cos ps by blast\n        then have \"outside S \\<inter> T \\<noteq> {}\"\n          using outside_same_component [OF _ a]  by (metis IntI \\<open>d \\<in> T\\<close> empty_iff)\n      } note * = this\n      have pal: \"pathstart (linepath a b) \\<in> closure (- T)\"\n        by (auto simp: False closure_def)\n      show ?thesis\n        by (rule exists_path_subpath_to_frontier [OF path_linepath pal _ *]) (auto simp: b)\n  qed\nqed\n\nlemma inside_inside_compact_connected:\n    fixes S :: \"'a :: euclidean_space set\"\n    assumes S: \"closed S\" and T: \"compact T\" and \"connected T\" \"S \\<subseteq> inside T\"\n      shows \"inside S \\<subseteq> inside T\"\nproof (cases \"inside T = {}\")\n  case True with assms show ?thesis by auto\nnext\n  case False\n  consider \"DIM('a) = 1\" | \"DIM('a) \\<ge> 2\"\n    using antisym not_less_eq_eq by fastforce\n  then show ?thesis\n  proof cases\n    case 1 then show ?thesis\n             using connected_convex_1_gen assms False inside_convex by blast\n  next\n    case 2\n    have \"bounded S\"\n      using assms by (meson bounded_inside bounded_subset compact_imp_bounded)\n    then have coms: \"compact S\"\n      by (simp add: S compact_eq_bounded_closed)\n    then have bst: \"bounded (S \\<union> T)\"\n      by (simp add: compact_imp_bounded T)\n    then obtain r where \"0 < r\" and r: \"S \\<union> T \\<subseteq> ball 0 r\"\n      using bounded_subset_ballD by blast\n    have outst: \"outside S \\<inter> outside T \\<noteq> {}\"\n    proof -\n      have \"- ball 0 r \\<subseteq> outside S\"\n        by (meson convex_ball le_supE outside_subset_convex r)\n      moreover have \"- ball 0 r \\<subseteq> outside T\"\n        by (meson convex_ball le_supE outside_subset_convex r)\n      ultimately show ?thesis\n        by (metis Compl_subset_Compl_iff Int_subset_iff bounded_ball inf.orderE outside_bounded_nonempty outside_no_overlap)\n    qed\n    have \"S \\<inter> T = {}\" using assms\n      by (metis disjoint_iff_not_equal inside_no_overlap subsetCE)\n    moreover have \"outside S \\<inter> inside T \\<noteq> {}\"\n      by (meson False assms(4) compact_eq_bounded_closed coms open_inside outside_compact_in_open T)\n    ultimately have \"inside S \\<inter> T = {}\"\n      using inside_outside_intersect_connected [OF \\<open>connected T\\<close>, of S]\n      by (metis \"2\" compact_eq_bounded_closed coms connected_outside inf.commute inside_outside_intersect_connected outst)\n    then show ?thesis\n      using inside_inside [OF \\<open>S \\<subseteq> inside T\\<close>] by blast\n  qed\nqed\n\nlemma connected_with_inside:\n    fixes S :: \"'a :: real_normed_vector set\"\n    assumes S: \"closed S\" and cons: \"connected S\"\n      shows \"connected(S \\<union> inside S)\"\nproof (cases \"S \\<union> inside S = UNIV\")\n  case True with assms show ?thesis by auto\nnext\n  case False\n  then obtain b where b: \"b \\<notin> S\" \"b \\<notin> inside S\" by blast\n  have *: \"\\<exists>y T. y \\<in> S \\<and> connected T \\<and> a \\<in> T \\<and> y \\<in> T \\<and> T \\<subseteq> (S \\<union> inside S)\" \n    if \"a \\<in> S \\<union> inside S\" for a\n    using that \n  proof\n    assume \"a \\<in> S\" then show ?thesis\n      by (rule_tac x=a in exI, rule_tac x=\"{a}\" in exI, simp)\n  next\n    assume a: \"a \\<in> inside S\"\n    then have ain: \"a \\<in> closure (inside S)\"\n      by (simp add: closure_def)\n    show ?thesis\n      apply (rule exists_path_subpath_to_frontier [OF path_linepath [of a b], of \"inside S\"])\n        apply (simp_all add: ain b)\n      subgoal for h\n        apply (rule_tac x=\"pathfinish h\" in exI)\n        apply (simp add: subsetD [OF frontier_inside_subset[OF S]])\n        apply (rule_tac x=\"path_image h\" in exI)\n        apply (simp add: pathfinish_in_path_image connected_path_image, auto)\n        by (metis Diff_single_insert S frontier_inside_subset insert_iff interior_subset subsetD)\n      done\n  qed\n  show ?thesis\n    apply (simp add: connected_iff_connected_component)\n    apply (clarsimp simp add: connected_component_def dest!: *)\n    subgoal for x y u u' T t'\n      by (rule_tac x=\"(S \\<union> T \\<union> t')\" in exI) (auto intro!: connected_Un cons)\n    done\nqed\n\ntext\\<open>The proof is virtually the same as that above.\\<close>\nlemma connected_with_outside:\n    fixes S :: \"'a :: real_normed_vector set\"\n    assumes S: \"closed S\" and cons: \"connected S\"\n      shows \"connected(S \\<union> outside S)\"\nproof (cases \"S \\<union> outside S = UNIV\")\n  case True with assms show ?thesis by auto\nnext\n  case False\n  then obtain b where b: \"b \\<notin> S\" \"b \\<notin> outside S\" by blast\n  have *: \"\\<exists>y T. y \\<in> S \\<and> connected T \\<and> a \\<in> T \\<and> y \\<in> T \\<and> T \\<subseteq> (S \\<union> outside S)\" if \"a \\<in> (S \\<union> outside S)\" for a\n  using that proof\n    assume \"a \\<in> S\" then show ?thesis\n      by (rule_tac x=a in exI, rule_tac x=\"{a}\" in exI, simp)\n  next\n    assume a: \"a \\<in> outside S\"\n    then have ain: \"a \\<in> closure (outside S)\"\n      by (simp add: closure_def)\n    show ?thesis\n      apply (rule exists_path_subpath_to_frontier [OF path_linepath [of a b], of \"outside S\"])\n        apply (simp_all add: ain b)\n      subgoal for h\n      apply (rule_tac x=\"pathfinish h\" in exI)\n        apply (simp add: subsetD [OF frontier_outside_subset[OF S]])\n      apply (rule_tac x=\"path_image h\" in exI)\n      apply (simp add: pathfinish_in_path_image connected_path_image, auto)\n        by (metis (no_types, lifting) frontier_outside_subset insertE insert_Diff interior_eq open_outside pathfinish_in_path_image S subsetCE)\n      done\n  qed\n  show ?thesis\n    apply (simp add: connected_iff_connected_component)\n    apply (clarsimp simp add: connected_component_def dest!: *)\n    subgoal for x y u u' T t'\n      by (rule_tac x=\"(S \\<union> T \\<union> t')\" in exI) (auto intro!: connected_Un cons)\n    done\nqed\n\nlemma inside_inside_eq_empty [simp]:\n    fixes S :: \"'a :: {real_normed_vector, perfect_space} set\"\n    assumes S: \"closed S\" and cons: \"connected S\"\n      shows \"inside (inside S) = {}\"\n  by (metis (no_types) unbounded_outside connected_with_outside [OF assms] bounded_Un\n           inside_complement_unbounded_connected_empty unbounded_outside union_with_outside)\n\nlemma inside_in_components:\n     \"inside S \\<in> components (- S) \\<longleftrightarrow> connected(inside S) \\<and> inside S \\<noteq> {}\" (is \"?lhs = ?rhs\")\nproof \n  assume R: ?rhs\n  then have \"\\<And>x. \\<lbrakk>x \\<in> S; x \\<in> inside S\\<rbrakk> \\<Longrightarrow> \\<not> connected (inside S)\"\n    by (simp add: inside_outside)\n  with R show ?lhs\n    unfolding in_components_maximal\n    by (auto intro: inside_same_component connected_componentI)\nqed (simp add: in_components_maximal)\n\ntext\\<open>The proof is like that above.\\<close>\nlemma outside_in_components:\n     \"outside S \\<in> components (- S) \\<longleftrightarrow> connected(outside S) \\<and> outside S \\<noteq> {}\" (is \"?lhs = ?rhs\")\nproof \n  assume R: ?rhs\n  then have \"\\<And>x. \\<lbrakk>x \\<in> S; x \\<in> outside S\\<rbrakk> \\<Longrightarrow> \\<not> connected (outside S)\"\n    by (meson disjoint_iff outside_no_overlap)\n  with R show ?lhs\n    unfolding in_components_maximal\n    by (auto intro: outside_same_component connected_componentI)\nqed (simp add: in_components_maximal)\n\nlemma bounded_unique_outside:\n  fixes S :: \"'a :: euclidean_space set\"\n  assumes \"bounded S\" \"DIM('a) \\<ge> 2\"\n  shows \"(c \\<in> components (- S) \\<and> \\<not> bounded c \\<longleftrightarrow> c = outside S)\" \n  using assms\n  by (metis cobounded_unique_unbounded_components connected_outside double_compl outside_bounded_nonempty outside_in_components unbounded_outside)\n\n\nsubsection\\<open>Condition for an open map's image to contain a ball\\<close>\n\nproposition ball_subset_open_map_image:\n  fixes f :: \"'a::heine_borel \\<Rightarrow> 'b :: {real_normed_vector,heine_borel}\"\n  assumes contf: \"continuous_on (closure S) f\"\n      and oint: \"open (f ` interior S)\"\n      and le_no: \"\\<And>z. z \\<in> frontier S \\<Longrightarrow> r \\<le> norm(f z - f a)\"\n      and \"bounded S\" \"a \\<in> S\" \"0 < r\"\n    shows \"ball (f a) r \\<subseteq> f ` S\"\nproof (cases \"f ` S = UNIV\")\n  case True then show ?thesis by simp\nnext\n  case False\n  then have \"closed (frontier (f ` S))\" \"frontier (f ` S) \\<noteq> {}\"\n    using \\<open>a \\<in> S\\<close> by (auto simp: frontier_eq_empty)\n  then obtain w where w: \"w \\<in> frontier (f ` S)\"\n    and dw_le: \"\\<And>y. y \\<in> frontier (f ` S) \\<Longrightarrow> norm (f a - w) \\<le> norm (f a - y)\"\n    by (auto simp add: dist_norm intro: distance_attains_inf [of \"frontier(f ` S)\" \"f a\"])\n  then obtain \\<xi> where \\<xi>: \"\\<And>n. \\<xi> n \\<in> f ` S\" and tendsw: \"\\<xi> \\<longlonglongrightarrow> w\"\n    by (metis Diff_iff frontier_def closure_sequential)\n    then have \"\\<And>n. \\<exists>x \\<in> S. \\<xi> n = f x\" by force\n    then obtain z where zs: \"\\<And>n. z n \\<in> S\" and fz: \"\\<And>n. \\<xi> n = f (z n)\"\n      by metis\n    then obtain y K where y: \"y \\<in> closure S\" and \"strict_mono (K :: nat \\<Rightarrow> nat)\" \n                      and Klim: \"(z \\<circ> K) \\<longlonglongrightarrow> y\"\n      using \\<open>bounded S\\<close>\n      unfolding compact_closure [symmetric] compact_def by (meson closure_subset subset_iff)\n    then have ftendsw: \"((\\<lambda>n. f (z n)) \\<circ> K) \\<longlonglongrightarrow> w\"\n      by (metis LIMSEQ_subseq_LIMSEQ fun.map_cong0 fz tendsw)\n    have zKs: \"\\<And>n. (z \\<circ> K) n \\<in> S\" by (simp add: zs)\n    have fz: \"f \\<circ> z = \\<xi>\"  \"(\\<lambda>n. f (z n)) = \\<xi>\"\n      using fz by auto\n    then have \"(\\<xi> \\<circ> K) \\<longlonglongrightarrow> f y\"\n      by (metis (no_types) Klim zKs y contf comp_assoc continuous_on_closure_sequentially)\n    with fz have wy: \"w = f y\" using fz LIMSEQ_unique ftendsw by auto\n    have rle: \"r \\<le> norm (f y - f a)\"\n    proof (rule le_no)\n      show \"y \\<in> frontier S\"\n        using w wy oint by (force simp: imageI image_mono interiorI interior_subset frontier_def y)\n    qed\n    have **: \"(b \\<inter> (- S) \\<noteq> {} \\<and> b - (- S) \\<noteq> {} \\<Longrightarrow> b \\<inter> f \\<noteq> {})\n              \\<Longrightarrow> (b \\<inter> S \\<noteq> {}) \\<Longrightarrow> b \\<inter> f = {} \\<Longrightarrow> b \\<subseteq> S\" \n             for b f and S :: \"'b set\"\n      by blast\n    have \\<section>: \"\\<And>y. \\<lbrakk>norm (f a - y) < r; y \\<in> frontier (f ` S)\\<rbrakk> \\<Longrightarrow> False\"\n      by (metis dw_le norm_minus_commute not_less order_trans rle wy)\n    show ?thesis\n      apply (rule ** [OF connected_Int_frontier [where t = \"f`S\", OF connected_ball]])\n        (*such a horrible mess*)\n      using \\<open>a \\<in> S\\<close> \\<open>0 < r\\<close> by (auto simp: disjoint_iff_not_equal dist_norm dest: \\<section>)\nqed\n\n\nsubsubsection\\<open>Special characterizations of classes of functions into and out of R.\\<close>\n\nlemma Hausdorff_space_euclidean [simp]: \"Hausdorff_space (euclidean :: 'a::metric_space topology)\"\nproof -\n  have \"\\<exists>U V. open U \\<and> open V \\<and> x \\<in> U \\<and> y \\<in> V \\<and> disjnt U V\"\n    if \"x \\<noteq> y\"\n    for x y :: 'a\n  proof (intro exI conjI)\n    let ?r = \"dist x y / 2\"\n    have [simp]: \"?r > 0\"\n      by (simp add: that)\n    show \"open (ball x ?r)\" \"open (ball y ?r)\" \"x \\<in> (ball x ?r)\" \"y \\<in> (ball y ?r)\"\n      by (auto simp add: that)\n    show \"disjnt (ball x ?r) (ball y ?r)\"\n      unfolding disjnt_def by (simp add: disjoint_ballI)\n  qed\n  then show ?thesis\n    by (simp add: Hausdorff_space_def)\nqed\n\nproposition embedding_map_into_euclideanreal:\n  assumes \"path_connected_space X\"\n  shows \"embedding_map X euclideanreal f \\<longleftrightarrow>\n         continuous_map X euclideanreal f \\<and> inj_on f (topspace X)\"\n  proof safe\n  show \"continuous_map X euclideanreal f\"\n    if \"embedding_map X euclideanreal f\"\n    using continuous_map_in_subtopology homeomorphic_imp_continuous_map that\n    unfolding embedding_map_def by blast\n  show \"inj_on f (topspace X)\"\n    if \"embedding_map X euclideanreal f\"\n    using that homeomorphic_imp_injective_map\n    unfolding embedding_map_def by blast\n  show \"embedding_map X euclideanreal f\"\n    if cont: \"continuous_map X euclideanreal f\" and inj: \"inj_on f (topspace X)\"\n  proof -\n    obtain g where gf: \"\\<And>x. x \\<in> topspace X \\<Longrightarrow> g (f x) = x\"\n      using inv_into_f_f [OF inj] by auto\n    show ?thesis\n      unfolding embedding_map_def homeomorphic_map_maps homeomorphic_maps_def\n    proof (intro exI conjI)\n      show \"continuous_map X (top_of_set (f ` topspace X)) f\"\n        by (simp add: cont continuous_map_in_subtopology)\n      let ?S = \"f ` topspace X\"\n      have eq: \"{x \\<in> ?S. g x \\<in> U} = f ` U\" if \"openin X U\" for U\n        using openin_subset [OF that] by (auto simp: gf)\n      have 1: \"g ` ?S \\<subseteq> topspace X\"\n        using eq by blast\n      have \"openin (top_of_set ?S) {x \\<in> ?S. g x \\<in> T}\"\n        if \"openin X T\" for T\n      proof -\n        have \"T \\<subseteq> topspace X\"\n          by (simp add: openin_subset that)\n        have RR: \"\\<forall>x \\<in> ?S \\<inter> g -` T. \\<exists>d>0. \\<forall>x' \\<in> ?S \\<inter> ball x d. g x' \\<in> T\"\n        proof (clarsimp simp add: gf)\n          have pcS: \"path_connectedin euclidean ?S\"\n            using assms cont path_connectedin_continuous_map_image path_connectedin_topspace by blast\n          show \"\\<exists>d>0. \\<forall>x'\\<in>f ` topspace X \\<inter> ball (f x) d. g x' \\<in> T\"\n            if \"x \\<in> T\" for x\n          proof -\n            have x: \"x \\<in> topspace X\"\n              using \\<open>T \\<subseteq> topspace X\\<close> \\<open>x \\<in> T\\<close> by blast\n            obtain u v d where \"0 < d\" \"u \\<in> topspace X\" \"v \\<in> topspace X\"\n                         and sub_fuv: \"?S \\<inter> {f x - d .. f x + d} \\<subseteq> {f u..f v}\"\n            proof (cases \"\\<exists>u \\<in> topspace X. f u < f x\")\n              case True\n              then obtain u where u: \"u \\<in> topspace X\" \"f u < f x\" ..\n              show ?thesis\n              proof (cases \"\\<exists>v \\<in> topspace X. f x < f v\")\n                case True\n                then obtain v where v: \"v \\<in> topspace X\" \"f x < f v\" ..\n                show ?thesis\n                proof\n                  let ?d = \"min (f x - f u) (f v - f x)\"\n                  show \"0 < ?d\"\n                    by (simp add: \\<open>f u < f x\\<close> \\<open>f x < f v\\<close>)\n                  show \"f ` topspace X \\<inter> {f x - ?d..f x + ?d} \\<subseteq> {f u..f v}\"\n                    by fastforce\n                qed (auto simp: u v)\n              next\n                case False\n                show ?thesis\n                proof\n                  let ?d = \"f x - f u\"\n                  show \"0 < ?d\"\n                    by (simp add: u)\n                  show \"f ` topspace X \\<inter> {f x - ?d..f x + ?d} \\<subseteq> {f u..f x}\"\n                    using x u False by auto\n                qed (auto simp: x u)\n              qed\n            next\n              case False\n              note no_u = False\n              show ?thesis\n              proof (cases \"\\<exists>v \\<in> topspace X. f x < f v\")\n                case True\n                then obtain v where v: \"v \\<in> topspace X\" \"f x < f v\" ..\n                show ?thesis\n                proof\n                  let ?d = \"f v - f x\"\n                  show \"0 < ?d\"\n                    by (simp add: v)\n                  show \"f ` topspace X \\<inter> {f x - ?d..f x + ?d} \\<subseteq> {f x..f v}\"\n                    using False by auto\n                qed (auto simp: x v)\n              next\n                case False\n                show ?thesis\n                proof\n                  show \"f ` topspace X \\<inter> {f x - 1..f x + 1} \\<subseteq> {f x..f x}\"\n                    using False no_u by fastforce\n                qed (auto simp: x)\n              qed\n            qed\n            then obtain h where \"pathin X h\" \"h 0 = u\" \"h 1 = v\"\n              using assms unfolding path_connected_space_def by blast\n            obtain C where \"compactin X C\" \"connectedin X C\" \"u \\<in> C\" \"v \\<in> C\"\n            proof\n              show \"compactin X (h ` {0..1})\"\n                using that by (simp add: \\<open>pathin X h\\<close> compactin_path_image)\n              show \"connectedin X (h ` {0..1})\"\n                using \\<open>pathin X h\\<close> connectedin_path_image by blast\n            qed (use \\<open>h 0 = u\\<close> \\<open>h 1 = v\\<close> in auto)\n            have \"continuous_map (subtopology euclideanreal (?S \\<inter> {f x - d .. f x + d})) (subtopology X C) g\"\n            proof (rule continuous_inverse_map)\n              show \"compact_space (subtopology X C)\"\n                using \\<open>compactin X C\\<close> compactin_subspace by blast\n              show \"continuous_map (subtopology X C) euclideanreal f\"\n                by (simp add: cont continuous_map_from_subtopology)\n              have \"{f u .. f v} \\<subseteq> f ` topspace (subtopology X C)\"\n              proof (rule connected_contains_Icc)\n                show \"connected (f ` topspace (subtopology X C))\"\n                  using connectedin_continuous_map_image [OF cont]\n                  by (simp add: \\<open>compactin X C\\<close> \\<open>connectedin X C\\<close> compactin_subset_topspace inf_absorb2)\n                show \"f u \\<in> f ` topspace (subtopology X C)\"\n                  by (simp add: \\<open>u \\<in> C\\<close> \\<open>u \\<in> topspace X\\<close>)\n                show \"f v \\<in> f ` topspace (subtopology X C)\"\n                  by (simp add: \\<open>v \\<in> C\\<close> \\<open>v \\<in> topspace X\\<close>)\n              qed\n              then show \"f ` topspace X \\<inter> {f x - d..f x + d} \\<subseteq> f ` topspace (subtopology X C)\"\n                using sub_fuv by blast\n            qed (auto simp: gf)\n            then have contg: \"continuous_map (subtopology euclideanreal (?S \\<inter> {f x - d .. f x + d})) X g\"\n              using continuous_map_in_subtopology by blast\n            have \"\\<exists>e>0. \\<forall>x \\<in> ?S \\<inter> {f x - d .. f x + d} \\<inter> ball (f x) e. g x \\<in> T\"\n              using openin_continuous_map_preimage [OF contg \\<open>openin X T\\<close>] x \\<open>x \\<in> T\\<close> \\<open>0 < d\\<close>\n              unfolding openin_euclidean_subtopology_iff\n              by (force simp: gf dist_commute)\n            then obtain e where \"e > 0 \\<and> (\\<forall>x\\<in>f ` topspace X \\<inter> {f x - d..f x + d} \\<inter> ball (f x) e. g x \\<in> T)\"\n              by metis\n            with \\<open>0 < d\\<close> have \"min d e > 0\" \"\\<forall>u. u \\<in> topspace X \\<longrightarrow> \\<bar>f x - f u\\<bar> < min d e \\<longrightarrow> u \\<in> T\"\n              using dist_real_def gf by force+\n            then show ?thesis\n              by (metis (full_types) Int_iff dist_real_def image_iff mem_ball gf)\n          qed\n        qed\n        then obtain d where d: \"\\<And>r. r \\<in> ?S \\<inter> g -` T \\<Longrightarrow>\n                d r > 0 \\<and> (\\<forall>x \\<in> ?S \\<inter> ball r (d r). g x \\<in> T)\"\n          by metis\n        show ?thesis\n          unfolding openin_subtopology\n        proof (intro exI conjI)\n          show \"{x \\<in> ?S. g x \\<in> T} = (\\<Union>r \\<in> ?S \\<inter> g -` T. ball r (d r)) \\<inter> f ` topspace X\"\n            using d by (auto simp: gf)\n        qed auto\n      qed\n      then show \"continuous_map (top_of_set ?S) X g\"\n        by (simp add: continuous_map_def gf)\n    qed (auto simp: gf)\n  qed\nqed\n\nsubsubsection \\<open>An injective function into R is a homeomorphism and so an open map.\\<close>\n\nlemma injective_into_1d_eq_homeomorphism:\n  fixes f :: \"'a::topological_space \\<Rightarrow> real\"\n  assumes f: \"continuous_on S f\" and S: \"path_connected S\"\n  shows \"inj_on f S \\<longleftrightarrow> (\\<exists>g. homeomorphism S (f ` S) f g)\"\nproof\n  show \"\\<exists>g. homeomorphism S (f ` S) f g\"\n    if \"inj_on f S\"\n  proof -\n    have \"embedding_map (top_of_set S) euclideanreal f\"\n      using that embedding_map_into_euclideanreal [of \"top_of_set S\" f] assms by auto\n    then show ?thesis\n      by (simp add: embedding_map_def) (metis all_closedin_homeomorphic_image f homeomorphism_injective_closed_map that)\n  qed\nqed (metis homeomorphism_def inj_onI)\n\nlemma injective_into_1d_imp_open_map:\n  fixes f :: \"'a::topological_space \\<Rightarrow> real\"\n  assumes \"continuous_on S f\" \"path_connected S\" \"inj_on f S\" \"openin (subtopology euclidean S) T\"\n  shows \"openin (subtopology euclidean (f ` S)) (f ` T)\"\n  using assms homeomorphism_imp_open_map injective_into_1d_eq_homeomorphism by blast\n\nlemma homeomorphism_into_1d:\n  fixes f :: \"'a::topological_space \\<Rightarrow> real\"\n  assumes \"path_connected S\" \"continuous_on S f\" \"f ` S = T\" \"inj_on f S\"\n  shows \"\\<exists>g. homeomorphism S T f g\"\n  using assms injective_into_1d_eq_homeomorphism by blast\n\nsubsection\\<^marker>\\<open>tag unimportant\\<close> \\<open>Rectangular paths\\<close>\n\ndefinition\\<^marker>\\<open>tag unimportant\\<close> rectpath where\n  \"rectpath a1 a3 = (let a2 = Complex (Re a3) (Im a1); a4 = Complex (Re a1) (Im a3)\n                      in linepath a1 a2 +++ linepath a2 a3 +++ linepath a3 a4 +++ linepath a4 a1)\"\n\nlemma path_rectpath [simp, intro]: \"path (rectpath a b)\"\n  by (simp add: Let_def rectpath_def)\n\nlemma pathstart_rectpath [simp]: \"pathstart (rectpath a1 a3) = a1\"\n  by (simp add: rectpath_def Let_def)\n\nlemma pathfinish_rectpath [simp]: \"pathfinish (rectpath a1 a3) = a1\"\n  by (simp add: rectpath_def Let_def)\n\nlemma simple_path_rectpath [simp, intro]:\n  assumes \"Re a1 \\<noteq> Re a3\" \"Im a1 \\<noteq> Im a3\"\n  shows   \"simple_path (rectpath a1 a3)\"\n  unfolding rectpath_def Let_def using assms\n  by (intro simple_path_join_loop arc_join arc_linepath)\n     (auto simp: complex_eq_iff path_image_join closed_segment_same_Re closed_segment_same_Im)\n\nlemma path_image_rectpath:\n  assumes \"Re a1 \\<le> Re a3\" \"Im a1 \\<le> Im a3\"\n  shows \"path_image (rectpath a1 a3) =\n           {z. Re z \\<in> {Re a1, Re a3} \\<and> Im z \\<in> {Im a1..Im a3}} \\<union>\n           {z. Im z \\<in> {Im a1, Im a3} \\<and> Re z \\<in> {Re a1..Re a3}}\" (is \"?lhs = ?rhs\")\nproof -\n  define a2 a4 where \"a2 = Complex (Re a3) (Im a1)\" and \"a4 = Complex (Re a1) (Im a3)\"\n  have \"?lhs = closed_segment a1 a2 \\<union> closed_segment a2 a3 \\<union>\n                  closed_segment a4 a3 \\<union> closed_segment a1 a4\"\n    by (simp_all add: rectpath_def Let_def path_image_join closed_segment_commute\n                      a2_def a4_def Un_assoc)\n  also have \"\\<dots> = ?rhs\" using assms\n    by (auto simp: rectpath_def Let_def path_image_join a2_def a4_def\n          closed_segment_same_Re closed_segment_same_Im closed_segment_eq_real_ivl)\n  finally show ?thesis .\nqed\n\nlemma path_image_rectpath_subset_cbox:\n  assumes \"Re a \\<le> Re b\" \"Im a \\<le> Im b\"\n  shows   \"path_image (rectpath a b) \\<subseteq> cbox a b\"\n  using assms by (auto simp: path_image_rectpath in_cbox_complex_iff)\n\nlemma path_image_rectpath_inter_box:\n  assumes \"Re a \\<le> Re b\" \"Im a \\<le> Im b\"\n  shows   \"path_image (rectpath a b) \\<inter> box a b = {}\"\n  using assms by (auto simp: path_image_rectpath in_box_complex_iff)\n\nlemma path_image_rectpath_cbox_minus_box:\n  assumes \"Re a \\<le> Re b\" \"Im a \\<le> Im b\"\n  shows   \"path_image (rectpath a b) = cbox a b - box a b\"\n  using assms by (auto simp: path_image_rectpath in_cbox_complex_iff\n                             in_box_complex_iff)\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/Analysis/Path_Connected.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8596637505099168, "lm_q2_score": 0.817574471748733, "lm_q1q2_score": 0.7028391367046799}}
{"text": "(*  Title:      Util_Nat.thy\n    Date:       Oct 2006\n    Author:     David Trachtenherz\n*)\n\nsection \\<open>Results for natural arithmetics\\<close>\n\ntheory Util_Nat\nimports Main\nbegin\n\nsubsection \\<open>Some convenience arithmetic lemmata\\<close>\n\nlemma add_1_Suc_conv: \"m + 1 = Suc m\" by simp\nlemma sub_Suc0_sub_Suc_conv: \"b - a - Suc 0 = b - Suc a\" by simp\n\nlemma Suc_diff_Suc: \"m < n \\<Longrightarrow> Suc (n - Suc m) = n - m\"\napply (rule subst[OF sub_Suc0_sub_Suc_conv])\napply (rule Suc_pred)\napply (simp only: zero_less_diff)\ndone\n\nlemma nat_grSuc0_conv: \"(Suc 0 < n) = (n \\<noteq> 0 \\<and> n \\<noteq> Suc 0)\"\nby fastforce\n\nlemma nat_geSucSuc0_conv: \"(Suc (Suc 0) \\<le> n) = (n \\<noteq> 0 \\<and> n \\<noteq> Suc 0)\"\nby fastforce\n\nlemma nat_lessSucSuc0_conv: \"(n < Suc (Suc 0)) = (n = 0 \\<or> n = Suc 0)\"\nby fastforce\n\nlemma nat_leSuc0_conv: \"(n \\<le> Suc 0) = (n = 0 \\<or> n = Suc 0)\"\nby fastforce\n\nlemma mult_pred: \"(m - Suc 0) * n = m * n - n\"\nby (simp add: diff_mult_distrib)\n\nlemma mult_pred_right: \"m * (n - Suc 0) = m * n - m\"\nby (simp add: diff_mult_distrib2)\n\nlemma gr_implies_gr0: \"m < (n::nat) \\<Longrightarrow> 0 < n\" by simp\n\ncorollary mult_cancel1_gr0: \"\n  (0::nat) < k \\<Longrightarrow> (k * m = k * n) = (m = n)\" by simp\ncorollary mult_cancel2_gr0: \"\n  (0::nat) < k \\<Longrightarrow> (m * k = n * k) = (m = n)\" by simp\n\ncorollary mult_le_cancel1_gr0: \"\n  (0::nat) < k \\<Longrightarrow> (k * m \\<le> k * n) = (m \\<le> n)\" by simp\ncorollary mult_le_cancel2_gr0: \"\n  (0::nat) < k \\<Longrightarrow> (m * k \\<le> n * k) = (m \\<le> n)\" by simp\n\nlemma gr0_imp_self_le_mult1: \"0 < (k::nat) \\<Longrightarrow> m \\<le> m * k\"\nby (drule Suc_leI, drule mult_le_mono[OF order_refl], simp)\n\nlemma gr0_imp_self_le_mult2: \"0 < (k::nat) \\<Longrightarrow> m \\<le> k * m\"\nby (subst mult.commute, rule gr0_imp_self_le_mult1)\n\nlemma less_imp_Suc_mult_le: \"m < n \\<Longrightarrow> Suc m * k \\<le> n * k\"\nby (rule mult_le_mono1, simp)\n\nlemma less_imp_Suc_mult_pred_less: \"\\<lbrakk> m < n; 0 < k \\<rbrakk> \\<Longrightarrow> Suc m * k - Suc 0 < n * k\"\napply (rule Suc_le_lessD)\napply (simp only: Suc_pred[OF nat_0_less_mult_iff[THEN iffD2, OF conjI, OF zero_less_Suc]])\napply (rule less_imp_Suc_mult_le, assumption)\ndone\n\nlemma ord_zero_less_diff: \"(0 < (b::'a::ordered_ab_group_add) - a) = (a < b)\"\nby (simp add: less_diff_eq)\n\nlemma ord_zero_le_diff: \"(0 \\<le> (b::'a::ordered_ab_group_add) - a) = (a \\<le> b)\"\nby (simp add: le_diff_eq)\n\ntext \\<open>\\<open>diff_diff_right\\<close> in rule format\\<close>\nlemmas diff_diff_right = Nat.diff_diff_right[rule_format]\n\n\nlemma less_add1: \"(0::nat) < j \\<Longrightarrow> i < i + j\" by simp\nlemma less_add2: \"(0::nat) < j \\<Longrightarrow> i < j + i\" by simp\n\nlemma add_lessD2: \"i + j < (k::nat) \\<Longrightarrow> j < k\" by simp\n\nlemma add_le_mono2: \"i \\<le> (j::nat) \\<Longrightarrow> k + i \\<le> k + j\" by simp\n\nlemma add_less_mono2: \"i < (j::nat) \\<Longrightarrow> k + i < k + j\" by simp\n\n\nlemma diff_less_self: \"\\<lbrakk> (0::nat) < i;  0 < j \\<rbrakk> \\<Longrightarrow> i - j < i\" by simp\n\nlemma\n  ge_less_neq_conv: \"((a::'a::linorder) \\<le> n) = (\\<forall>x. x < a \\<longrightarrow> n \\<noteq> x)\" and\n  le_greater_neq_conv: \"(n \\<le> (a::'a::linorder)) = (\\<forall>x. a < x \\<longrightarrow> n \\<noteq> x)\"\nby (subst linorder_not_less[symmetric], blast)+\nlemma\n  greater_le_neq_conv: \"((a::'a::linorder) < n) = (\\<forall>x. x \\<le> a \\<longrightarrow> n \\<noteq> x)\" and\n  less_ge_neq_conv: \"(n < (a::'a::linorder)) = (\\<forall>x. a \\<le> x \\<longrightarrow> n \\<noteq> x)\"\nby (subst linorder_not_le[symmetric], blast)+\n\n\n\ntext \\<open>Lemmas for @term{abs} function\\<close>\n\nlemma leq_pos_imp_abs_leq: \"\\<lbrakk> 0 \\<le> (a::'a::ordered_ab_group_add_abs); a \\<le> b \\<rbrakk> \\<Longrightarrow> \\<bar>a\\<bar> \\<le> \\<bar>b\\<bar>\"\nby simp\nlemma leq_neg_imp_abs_geq: \"\\<lbrakk> (a::'a::ordered_ab_group_add_abs) \\<le> 0; b \\<le> a \\<rbrakk> \\<Longrightarrow> \\<bar>a\\<bar> \\<le> \\<bar>b\\<bar>\"\nby simp\nlemma abs_range: \"\\<lbrakk> 0 \\<le> (a::'a::{ordered_ab_group_add_abs,abs_if}); -a \\<le> x; x \\<le> a \\<rbrakk> \\<Longrightarrow> \\<bar>x\\<bar> \\<le> a\"\napply (clarsimp simp: abs_if)\napply (rule neg_le_iff_le[THEN iffD1], simp)\ndone\n\n\n\ntext \\<open>Lemmas for @term{sgn} function\\<close>\n\nlemma sgn_abs:\"(x::'a::linordered_idom) \\<noteq> 0 \\<Longrightarrow> \\<bar>sgn x\\<bar> = 1\"\nby (case_tac \"x < 0\", simp+)\nlemma sgn_mult_abs:\"\\<bar>x\\<bar> * \\<bar>sgn (a::'a::linordered_idom)\\<bar> = \\<bar>x * sgn a\\<bar>\"\nby (fastforce simp add: sgn_if abs_if)\nlemma abs_imp_sgn_abs: \"\\<bar>a\\<bar> = \\<bar>b\\<bar> \\<Longrightarrow> \\<bar>sgn (a::'a::linordered_idom)\\<bar> = \\<bar>sgn b\\<bar>\"\nby (fastforce simp add: abs_if)\nlemma sgn_mono: \"a \\<le> b \\<Longrightarrow> sgn (a::'a::{linordered_idom,linordered_semidom}) \\<le> sgn b\"\nby (auto simp add: sgn_if)\n\n\nsubsection \\<open>Additional facts about inequalities\\<close>\n\nlemma add_diff_le: \"k \\<le> n \\<Longrightarrow> m + k - n \\<le> (m::nat)\"\nby (case_tac \"m + k < n\", simp_all)\n\nlemma less_add_diff: \"k < (n::nat) \\<Longrightarrow> m < n + m - k\"\n\nby (rule add_less_imp_less_right[of _ k], simp)\n\nlemma add_diff_less: \"\\<lbrakk> k < n; 0 < m \\<rbrakk> \\<Longrightarrow> m + k - n < (m::nat)\"\nby (case_tac \"m + k < n\", simp_all)\n\n\nlemma add_le_imp_le_diff1: \"i + k \\<le> j \\<Longrightarrow> i \\<le> j - (k::nat)\"\nby (case_tac \"k \\<le> j\", simp_all)\n\nlemma add_le_imp_le_diff2: \"k + i \\<le> j \\<Longrightarrow> i \\<le> j - (k::nat)\" by simp\n\nlemma diff_less_imp_less_add: \"j - (k::nat) < i \\<Longrightarrow> j < i + k\" by simp\n\nlemma diff_less_conv: \"0 < i \\<Longrightarrow> (j - (k::nat) < i) = (j < i + k)\"\nby (safe, simp_all)\n\n\n\nlemma diff_less_imp_swap: \"\\<lbrakk> 0 < (i::nat); k - i < j \\<rbrakk> \\<Longrightarrow> (k - j < i)\" by simp\nlemma diff_less_swap: \"\\<lbrakk> 0 < (i::nat); 0 < j \\<rbrakk> \\<Longrightarrow> (k - j < i) = (k - i < j)\"\nby (blast intro: diff_less_imp_swap)\n\nlemma less_diff_imp_less: \"(i::nat) < j - m \\<Longrightarrow> i < j\" by simp\nlemma le_diff_imp_le: \"(i::nat) \\<le> j - m \\<Longrightarrow> i \\<le> j\" by simp\n\nlemma less_diff_le_imp_less: \"\\<lbrakk> (i::nat) < j - m; n \\<le> m \\<rbrakk> \\<Longrightarrow> i < j - n\" by simp\nlemma le_diff_le_imp_le: \"\\<lbrakk> (i::nat) \\<le> j - m; n \\<le> m \\<rbrakk> \\<Longrightarrow> i \\<le> j - n\" by simp\n\nlemma le_imp_diff_le: \"(j::nat) \\<le> k \\<Longrightarrow> j - n \\<le> k\" by simp\n\n\nsubsection \\<open>Inequalities for Suc and pred\\<close>\n\ncorollary less_eq_le_pred: \"0 < (n::nat) \\<Longrightarrow> (m < n) = (m \\<le> n - Suc 0)\"\nby (safe, simp_all)\n\ncorollary less_imp_le_pred: \"m < n \\<Longrightarrow> m \\<le> n - Suc 0\" by simp\ncorollary le_pred_imp_less: \"\\<lbrakk> 0 < n; m \\<le> n - Suc 0 \\<rbrakk> \\<Longrightarrow> m < n\" by simp\n\ncorollary pred_less_eq_le: \"0 < m \\<Longrightarrow> (m - Suc 0 < n) = (m \\<le> n)\"\nby (safe, simp_all)\ncorollary pred_less_imp_le: \"m - Suc 0 < n \\<Longrightarrow> m \\<le> n\" by simp\ncorollary le_imp_pred_less: \"\\<lbrakk> 0 < m; m \\<le> n \\<rbrakk> \\<Longrightarrow> m - Suc 0 < n\" by simp\n\nlemma diff_add_inverse_Suc: \"n < m \\<Longrightarrow> n + (m - Suc n) = m - Suc 0\" by simp\n\nlemma pred_mono: \"\\<lbrakk> m < n; 0 < m \\<rbrakk> \\<Longrightarrow> m - Suc 0 < n - Suc 0\" by simp\ncorollary pred_Suc_mono: \"\\<lbrakk> m < Suc n; 0 < m \\<rbrakk> \\<Longrightarrow> m - Suc 0 < n\" by simp\n\nlemma Suc_less_pred_conv: \"(Suc m < n) = (m < n - Suc 0)\" by (safe, simp_all)\nlemma Suc_le_pred_conv: \"0 < n \\<Longrightarrow> (Suc m \\<le> n) = (m \\<le> n - Suc 0)\" by (safe, simp_all)\nlemma Suc_le_imp_le_pred: \"Suc m \\<le> n \\<Longrightarrow> m \\<le> n - Suc 0\" by simp\n\n\nsubsection \\<open>Additional facts about cancellation in (in-)equalities\\<close>\n\nlemma diff_cancel_imp_eq: \"\\<lbrakk> 0 < (n::nat);  n + i - j = n \\<rbrakk> \\<Longrightarrow> i = j\" by simp\n\nlemma nat_diff_left_cancel_less: \"k - m < k - (n::nat) \\<Longrightarrow> n < m\" by simp\nlemma nat_diff_right_cancel_less: \"n - k < (m::nat) - k \\<Longrightarrow> n < m\" by simp\n\nlemma nat_diff_left_cancel_le1: \"\\<lbrakk> k - m \\<le> k - (n::nat); m < k \\<rbrakk> \\<Longrightarrow> n \\<le> m\" by simp\nlemma nat_diff_left_cancel_le2: \"\\<lbrakk> k - m \\<le> k - (n::nat); n \\<le> k \\<rbrakk> \\<Longrightarrow> n \\<le> m\" by simp\n\nlemma nat_diff_right_cancel_le1: \"\\<lbrakk> m - k \\<le> n - (k::nat); k < m \\<rbrakk> \\<Longrightarrow> m \\<le> n\" by simp\nlemma nat_diff_right_cancel_le2: \"\\<lbrakk> m - k \\<le> n - (k::nat); k \\<le> n \\<rbrakk> \\<Longrightarrow> m \\<le> n\" by simp\n\nlemma nat_diff_left_cancel_eq1: \"\\<lbrakk> k - m = k - (n::nat); m < k \\<rbrakk> \\<Longrightarrow> m = n\" by simp\nlemma nat_diff_left_cancel_eq2: \"\\<lbrakk> k - m = k - (n::nat); n < k \\<rbrakk> \\<Longrightarrow> m = n\" by simp\n\nlemma nat_diff_right_cancel_eq1: \"\\<lbrakk> m - k = n - (k::nat); k < m \\<rbrakk> \\<Longrightarrow> m = n\" by simp\nlemma nat_diff_right_cancel_eq2: \"\\<lbrakk> m - k = n - (k::nat); k < n \\<rbrakk> \\<Longrightarrow> m = n\" by simp\n\nlemma eq_diff_left_iff: \"\\<lbrakk> (m::nat) \\<le> k; n \\<le> k\\<rbrakk> \\<Longrightarrow> (k - m = k - n) = (m = n)\"\nby (safe, simp_all)\n\nlemma eq_imp_diff_eq: \"m = (n::nat) \\<Longrightarrow> m - k = n - k\" by simp\n\n\ntext \\<open>List of definitions and lemmas\\<close>\n\nthm\n  Nat.add_Suc_right\n  add_1_Suc_conv\n  sub_Suc0_sub_Suc_conv\n\nthm\n  Nat.mult_cancel1\n  Nat.mult_cancel2\n  mult_cancel1_gr0\n  mult_cancel2_gr0\n\nthm\n  Nat.add_lessD1\n  add_lessD2\n\nthm\n  Nat.zero_less_diff\n  ord_zero_less_diff\n  ord_zero_le_diff\n\nthm\n  Nat.le_add_diff\n  add_diff_le\n  less_add_diff\n  add_diff_less\n\nthm\n  Nat.le_diff_conv Nat.le_diff_conv2\n  Nat.less_diff_conv\n  diff_less_imp_less_add\n  diff_less_conv\n\nthm\n  le_diff_swap\n  diff_less_imp_swap\n  diff_less_swap\n\nthm\n  less_diff_imp_less\n  le_diff_imp_le\n\nthm\n  less_diff_le_imp_less\n  le_diff_le_imp_le\n\nthm\n  Nat.less_imp_diff_less\n  le_imp_diff_le\n\nthm\n  Nat.less_Suc_eq_le\n  less_eq_le_pred\n  less_imp_le_pred\n  le_pred_imp_less\n\nthm\n  Nat.Suc_le_eq\n  pred_less_eq_le\n  pred_less_imp_le\n  le_imp_pred_less\n\nthm\n  diff_cancel_imp_eq\nthm\n  diff_add_inverse_Suc\nthm\n  Nat.nat_add_left_cancel_less\n  Nat.nat_add_left_cancel_le\n  Nat.nat_add_right_cancel\n  Nat.nat_add_left_cancel\n  Nat.eq_diff_iff\n  Nat.less_diff_iff\n  Nat.le_diff_iff\nthm\n  nat_diff_left_cancel_less\n  nat_diff_right_cancel_less\nthm\n  nat_diff_left_cancel_le1\n  nat_diff_left_cancel_le2\n  nat_diff_right_cancel_le1\n  nat_diff_right_cancel_le2\nthm\n  nat_diff_left_cancel_eq1\n  nat_diff_left_cancel_eq2\n  nat_diff_right_cancel_eq1\n  nat_diff_right_cancel_eq2\n\nthm\n  Nat.eq_diff_iff\n  eq_diff_left_iff\n\nthm\n  Nat.nat_add_right_cancel Nat.nat_add_left_cancel\n  Nat.diff_le_mono\n  eq_imp_diff_eq\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_Nat.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637433190939, "lm_q2_score": 0.817574478416099, "lm_q1q2_score": 0.7028391365573394}}
{"text": "(*  Title:      Additional Facts about Subgroups and Normal Subgroups\n    Author:     Jakob von Raumer, Karlsruhe Institute of Technology\n    Maintainer: Jakob von Raumer <jakob.raumer@student.kit.edu>\n*)\n\ntheory SubgroupsAndNormalSubgroups\nimports\n  \"Coset\"\n  \"../Secondary_Sylow/SndSylow\"\n  \"SndIsomorphismGrp\"\nbegin\n\nsection {* Preliminary lemmas *}\n\ntext {* A group of order 1 is always the trivial group. *}\n\n\nlemma (in group) order_one_triv_iff:\n  shows \"(order G = 1) = (carrier G = {\\<one>})\"\nproof\n  assume order:\"order G = 1\"\n  then obtain x where x:\"carrier G = {x}\" unfolding order_def by (auto simp add: card_Suc_eq)\n  hence \"\\<one> = x\" using one_closed by auto\n  with x show \"carrier G = {\\<one>}\" by simp\nnext\n  assume \"carrier G = {\\<one>}\"\n  thus \"order G = 1\" unfolding order_def by auto\nqed\n\nlemma (in group) finite_pos_order:\n  assumes finite:\"finite (carrier G)\"\n  shows \"0 < order G\"\nproof -\n  from one_closed finite show ?thesis unfolding order_def by (metis card_gt_0_iff subgroup_nonempty subgroup_self)\nqed\n\nlemma iso_order_closed:\n  assumes \"\\<phi> \\<in> G \\<cong> H\"\n  shows \"order G = order H\"\nusing assms\nunfolding order_def iso_def by (metis (no_types) bij_betw_same_card mem_Collect_eq)\n\nsection {* More Facts about Subgroups *}\n\nlemma (in subgroup) subgroup_of_restricted_group:\n  assumes \"subgroup U (G\\<lparr> carrier := H\\<rparr>)\"\n  shows \"U \\<subseteq> H\"\nusing assms subgroup_imp_subset by force\n\nlemma (in subgroup) subgroup_of_subgroup:\n  assumes \"group G\"\n  assumes \"subgroup U (G\\<lparr> carrier := H\\<rparr>)\"\n  shows \"subgroup U G\"\nproof\n  from assms(2) have \"U \\<subseteq> H\" by (rule subgroup_of_restricted_group)\n  thus \"U \\<subseteq> carrier G\" by (auto simp:subset)\nnext\n  fix x y\n  have a:\"x \\<otimes> y = x \\<otimes>\\<^bsub>G\\<lparr> carrier := H\\<rparr>\\<^esub> y\" by simp\n  assume \"x \\<in> U\" \"y \\<in> U\"\n  with assms a show \" x \\<otimes> y \\<in> U\" by (metis subgroup.m_closed)\nnext\n  have \"\\<one>\\<^bsub>G\\<lparr> carrier := H\\<rparr>\\<^esub> = \\<one>\" by simp\n  with assms show \"\\<one> \\<in> U\" by (metis subgroup.one_closed)\nnext\n  have \"subgroup H G\"..\n  fix x\n  assume \"x \\<in> U\"\n  with assms(2) have \"inv\\<^bsub>G\\<lparr> carrier := H\\<rparr>\\<^esub> x \\<in> U\" by (rule subgroup.m_inv_closed)\n  moreover from assms `x \\<in> U` have \"x \\<in> H\" by (metis in_mono subgroup_of_restricted_group)\n  with assms(1) `subgroup H G` have \"inv\\<^bsub>G\\<lparr> carrier := H\\<rparr>\\<^esub> x = inv x\" by (rule group.subgroup_inv_equality)\n  ultimately show \"inv x \\<in> U\" by simp\nqed\n\ntext {* Being a subgroup is preserved by surjective homomorphisms *}\n\nlemma (in subgroup) surj_hom_subgroup:\n  assumes \\<phi>:\"group_hom G F \\<phi>\"\n  assumes \\<phi>surj:\"\\<phi> ` (carrier G) = carrier F\"\n  shows \"subgroup (\\<phi> ` H) F\"\nproof\n  from \\<phi>surj show img_subset:\"\\<phi> ` H \\<subseteq> carrier F\" unfolding iso_def bij_betw_def by auto\nnext\n  fix f f'\n\tassume h:\"f \\<in> \\<phi> ` H\" and h':\"f' \\<in> \\<phi> ` H\"\n\twith \\<phi>surj obtain g g' where g:\"g \\<in> H\" \"f = \\<phi> g\" and g':\"g' \\<in> H\" \"f' = \\<phi> g'\" by auto\n\thence \"g \\<otimes>\\<^bsub>G\\<^esub> g' \\<in> H\" by (metis m_closed)\n  hence \"\\<phi> (g \\<otimes>\\<^bsub>G\\<^esub> g') \\<in> \\<phi> ` H\" by simp\n  with g g' \\<phi> show \"f \\<otimes>\\<^bsub>F\\<^esub> f' \\<in> \\<phi> ` H\"  using group_hom.hom_mult by fastforce\nnext\n  have \"\\<phi> \\<one> \\<in> \\<phi> ` H\" by auto\n  with \\<phi> show  \"\\<one>\\<^bsub>F\\<^esub> \\<in> \\<phi> ` H\" by (metis group_hom.hom_one)\nnext\n  fix f\n  assume f:\"f \\<in> \\<phi> ` H\"\n  then obtain g where g:\"g \\<in> H\" \"f = \\<phi> g\" by auto\n  hence \"inv g \\<in> H\" by auto\n  hence \"\\<phi> (inv g) \\<in> \\<phi> ` H\" by auto\n  with \\<phi> g subset show \"inv\\<^bsub>F\\<^esub> f \\<in> \\<phi> ` H\" using group_hom.hom_inv by fastforce\nqed\n\ntext {* ... and thus of course by isomorphisms of groups. *}\n\nlemma iso_subgroup:\n  assumes groups:\"group G\" \"group F\"\n  assumes HG:\"subgroup H G\"\n  assumes \\<phi>:\"\\<phi> \\<in> G \\<cong> F\"\n  shows \"subgroup (\\<phi> ` H) F\"\nproof -\n  from groups \\<phi> have \"group_hom G F \\<phi>\" unfolding group_hom_def group_hom_axioms_def iso_def by auto\n  moreover from \\<phi> have \"\\<phi> ` (carrier G) = carrier F\" unfolding iso_def bij_betw_def by simp\n  moreover note HG\n  ultimately show ?thesis by (metis subgroup.surj_hom_subgroup)\nqed\n\ntext {* An isomorphism restricts to an isomorphism of subgroups. *}\n\nlemma iso_restrict:\n  assumes groups:\"group G\" \"group F\"\n  assumes HG:\"subgroup H G\"\n  assumes \\<phi>:\"\\<phi> \\<in> G \\<cong> F\"\n  shows \"(restrict \\<phi> H) \\<in> (G\\<lparr>carrier := H\\<rparr>) \\<cong> (F\\<lparr>carrier := \\<phi> ` H\\<rparr>)\"\nunfolding iso_def hom_def bij_betw_def inj_on_def\nproof auto\n  fix g h\n  assume \"g \\<in> H\" \"h \\<in> H\"\n  hence \"g \\<in> carrier G\" \"h \\<in> carrier G\" by (metis HG subgroup.mem_carrier)+\n  thus \"\\<phi> (g \\<otimes>\\<^bsub>G\\<^esub> h) = \\<phi> g \\<otimes>\\<^bsub>F\\<^esub> \\<phi> h\" using \\<phi> unfolding iso_def hom_def by auto\nnext\n  fix g h\n  assume \"g \\<in> H\" \"h \\<in> H\" \"g \\<otimes>\\<^bsub>G\\<^esub> h \\<notin> H\"\n  hence \"False\" using HG unfolding subgroup_def by auto\n  thus \"undefined = \\<phi> g \\<otimes>\\<^bsub>F\\<^esub> \\<phi> h\" by auto\nnext\n  fix g h\n  assume g:\"g \\<in> H\" and h:\"h \\<in> H\" and eq:\"\\<phi> g = \\<phi> h\"\n  hence \"g \\<in> carrier G\" \"h \\<in> carrier G\" by (metis HG subgroup.mem_carrier)+\n  with eq show \"g = h\" using \\<phi> unfolding iso_def bij_betw_def inj_on_def by auto\nqed\n\ntext {* The intersection of two subgroups is, again, a subgroup *}\n\nlemma (in group) subgroup_intersect:\n  assumes \"subgroup H G\"\n  assumes \"subgroup H' G\"\n  shows \"subgroup (H \\<inter> H') G\"\nusing assms unfolding subgroup_def by auto\n\nsection {* Facts about Normal Subgroups *}\n\nlemma (in normal) is_normal:\n  shows \"H \\<lhd> G\"\nby (metis coset_eq is_subgroup normalI)\n\ntext {* Being a normal subgroup is preserved by surjective homomorphisms. *}\n\nlemma (in normal) surj_hom_normal_subgroup:\n  assumes \\<phi>:\"group_hom G F \\<phi>\"\n  assumes \\<phi>surj:\"\\<phi> ` (carrier G) = carrier F\"\n  shows \"(\\<phi> ` H) \\<lhd> F\"\nproof (rule group.normalI)\n  from \\<phi> show \"group F\" unfolding group_hom_def group_hom_axioms_def by simp\nnext\n  from \\<phi> \\<phi>surj show \"subgroup (\\<phi> ` H) F\" by (rule surj_hom_subgroup)\nnext\n  show \"\\<forall>x\\<in>carrier F. \\<phi> ` H #>\\<^bsub>F\\<^esub> x = x <#\\<^bsub>F\\<^esub> \\<phi> ` H\"\n  proof\n    fix f\n    assume f:\"f \\<in> carrier F\"\n    with \\<phi>surj obtain g where g:\"g \\<in> carrier G\" \"f = \\<phi> g\" by auto\n    hence \"\\<phi> ` H #>\\<^bsub>F\\<^esub> f = \\<phi> ` H #>\\<^bsub>F\\<^esub> \\<phi> g\" by simp\n    also have \"... = (\\<lambda>x. (\\<phi> x) \\<otimes>\\<^bsub>F\\<^esub> (\\<phi> g)) ` H\" unfolding r_coset_def image_def by auto\n    also have \"... = (\\<lambda>x. \\<phi> (x \\<otimes> g)) ` H\" using subset g \\<phi> group_hom.hom_mult unfolding image_def by fastforce\n    also have \"... = \\<phi> ` (H #> g)\" using \\<phi> unfolding r_coset_def by auto\n    also have \"... = \\<phi> ` (g <# H)\" by (metis coset_eq g(1))\n    also have \"... = (\\<lambda>x. \\<phi> (g \\<otimes> x)) ` H\" using \\<phi> unfolding l_coset_def by auto\n    also have \"... = (\\<lambda>x. (\\<phi> g) \\<otimes>\\<^bsub>F\\<^esub> (\\<phi> x)) ` H\" using subset g \\<phi> group_hom.hom_mult by fastforce\n    also have \"... = \\<phi> g <#\\<^bsub>F\\<^esub> \\<phi> ` H\" unfolding l_coset_def image_def by auto\n    also have \"... = f <#\\<^bsub>F\\<^esub> \\<phi> ` H\" using g by simp\n    finally show \"\\<phi> ` H #>\\<^bsub>F\\<^esub> f = f <#\\<^bsub>F\\<^esub> \\<phi> ` H\".\n  qed\nqed\n\ntext {* Being a normal subgroup is preserved by group isomorphisms. *}\n\nlemma iso_normal_subgroup:\n  assumes groups:\"group G\" \"group F\"\n  assumes HG:\"H \\<lhd> G\"\n  assumes \\<phi>:\"\\<phi> \\<in> G \\<cong> F\"\n  shows \"(\\<phi> ` H) \\<lhd> F\"\nproof -\n  from groups \\<phi> have \"group_hom G F \\<phi>\" unfolding group_hom_def group_hom_axioms_def iso_def by auto\n  moreover from \\<phi> have \"\\<phi> ` (carrier G) = carrier F\" unfolding iso_def bij_betw_def by simp\n  moreover note HG\n  ultimately show ?thesis using normal.surj_hom_normal_subgroup by metis\nqed\n\ntext {* The trivial subgroup is a subgroup: *}\n\nlemma (in group) triv_subgroup:\n  shows \"subgroup {\\<one>} G\"\nunfolding subgroup_def by auto\n\ntext {* The cardinality of the right cosets of the trivial subgroup is the cardinality of the group itself: *}\n\nlemma (in group) card_rcosets_triv:\n  assumes \"finite (carrier G)\"\n  shows \"card (rcosets {\\<one>}) = order G\"\nproof -\n  have \"subgroup {\\<one>} G\" by (rule triv_subgroup)\n  with assms have \"card (rcosets {\\<one>}) * card {\\<one>} = order G\" by (rule lagrange)\n  thus ?thesis by (auto simp:card_Suc_eq)\nqed\n\ntext {* The intersection of two normal subgroups is, again, a normal subgroup. *}\n\nlemma (in group) normal_subgroup_intersect:\n  assumes \"M \\<lhd> G\" and \"N \\<lhd> G\"\n  shows \"M \\<inter> N \\<lhd> G\"\nusing assms subgroup_intersect is_group normal_inv_iff by simp\n\ntext {* The set product of two normal subgroups is a normal subgroup. *}\n\nlemma (in group) setmult_lcos_assoc:\n     \"\\<lbrakk>H \\<subseteq> carrier G; K \\<subseteq> carrier G; x \\<in> carrier G\\<rbrakk>\n      \\<Longrightarrow> (x <# H) <#> K = x <# (H <#> K)\"\nby (force simp add: l_coset_def set_mult_def m_assoc)\n\nlemma (in group) normal_subgroup_set_mult_closed:\n  assumes \"M \\<lhd> G\" and \"N \\<lhd> G\"\n  shows \"M <#> N \\<lhd> G\"\nproof (rule normalI)\n  from assms show \"subgroup (M <#> N) G\"\n    using second_isomorphism_grp.normal_set_mult_subgroup normal_imp_subgroup\n    unfolding second_isomorphism_grp_def second_isomorphism_grp_axioms_def by force\nnext\n  show \"\\<forall>x\\<in>carrier G. M <#> N #> x = x <# (M <#> N)\"\n  proof\n    fix x\n    assume x:\"x \\<in> carrier G\"\n    have \"M <#> N #> x = M <#> (N #> x)\" by (metis assms(1,2) normal_inv_iff setmult_rcos_assoc subgroup_imp_subset x)\n    also have \"\\<dots> = M <#> (x <# N)\" by (metis assms(2) normal.coset_eq x)\n    also have \"\\<dots> = (M #> x) <#> N\" by (metis assms(1,2) normal_imp_subgroup rcos_assoc_lcos subgroup_imp_subset x)\n    also have \"\\<dots> = (x <# M) <#> N\" by (metis assms(1) normal.coset_eq x)\n    also have \"\\<dots> = x <# (M <#> N)\" by (metis assms(1,2) normal_imp_subgroup setmult_lcos_assoc subgroup_imp_subset x)\n    finally show \"M <#> N #> x = x <# (M <#> N)\".\n  qed\nqed\n\ntext {* The following is a very basic lemma about subgroups: If restricting the carrier of\n  a group yields a group it's a subgroup of the group we've started with. *}\n\nlemma (in group) restrict_group_imp_subgroup:\n  assumes \"H \\<subseteq> carrier G\" \"group (G\\<lparr>carrier := H\\<rparr>)\"\n  shows \"subgroup H G\"\nproof\n  from assms(1) show \"H \\<subseteq> carrier G\" .\nnext\n  fix x y\n  assume \"x \\<in> H\" \"y \\<in> H\"\n  hence \"x \\<in> carrier (G\\<lparr>carrier := H\\<rparr>)\" \"y \\<in> carrier (G\\<lparr>carrier := H\\<rparr>)\" by auto\n  with assms(2) show \"x \\<otimes> y \\<in> H\" using assms(2) group.is_monoid monoid.m_closed by fastforce\nnext\n  show \"\\<one> \\<in> H\" using assms(2) group.is_monoid monoid.one_closed by fastforce\nnext\n  fix x\n  assume \"x \\<in> H\"\n  hence x:\"x \\<in> carrier (G\\<lparr>carrier := H\\<rparr>)\" by auto\n  hence \"inv\\<^bsub>G\\<lparr>carrier := H\\<rparr>\\<^esub> x \\<in> carrier (G\\<lparr>carrier := H\\<rparr>)\" using assms(2) group.inv_closed by fastforce\n  hence \"inv\\<^bsub>G\\<lparr>carrier := H\\<rparr>\\<^esub> x \\<in> carrier G\" using x assms(1) by auto\n  moreover have \"inv\\<^bsub>G\\<lparr>carrier := H\\<rparr>\\<^esub> x \\<otimes> x = \\<one>\" using assms(2) group.l_inv x by fastforce\n  moreover have \"x \\<in> carrier G\" using x assms(1) by auto\n  ultimately have \"inv\\<^bsub>G\\<lparr>carrier := H\\<rparr>\\<^esub> x = inv x\" using inv_equality[symmetric] by auto\n  thus \"inv x \\<in> H\" using assms(2) group.inv_closed x by fastforce\nqed\n\ntext {* A subgroup relation survives factoring by a normal subgroup. *}\n\nlemma (in group) normal_subgroup_factorize:\n  assumes \"N \\<lhd> G\" and \"N \\<subseteq> H\" and \"subgroup H G\"\n  shows \"subgroup (rcosets\\<^bsub>G\\<lparr>carrier := H\\<rparr>\\<^esub> N) (G Mod N)\"\nproof -\n  interpret GModN: group \"G Mod N\" using assms(1) by (rule normal.factorgroup_is_group)\n  have \"N \\<lhd> G\\<lparr>carrier := H\\<rparr>\" using assms by (metis normal_restrict_supergroup)\n  hence grpHN:\"group (G\\<lparr>carrier := H\\<rparr> Mod N)\" by (rule normal.factorgroup_is_group)\n  have \"op <#>\\<^bsub>G\\<lparr>carrier := H\\<rparr>\\<^esub> = (\\<lambda>U K. (\\<Union>h\\<in>U. \\<Union>k\\<in>K. {h \\<otimes>\\<^bsub>G\\<lparr>carrier := H\\<rparr>\\<^esub> k}))\" using set_mult_def by metis\n  moreover have \"\\<dots> = (\\<lambda>U K. (\\<Union>h\\<in>U. \\<Union>k\\<in>K. {h \\<otimes>\\<^bsub>G\\<^esub> k}))\" by auto\n  moreover have \"op <#> = (\\<lambda>U K. (\\<Union>h\\<in>U. \\<Union>k\\<in>K. {h \\<otimes> k}))\" using set_mult_def by metis\n  ultimately have \"op <#>\\<^bsub>G\\<lparr>carrier := H\\<rparr>\\<^esub> = op <#>\\<^bsub>G\\<^esub>\" by simp\n  with grpHN have \"group ((G Mod N)\\<lparr>carrier := (rcosets\\<^bsub>G\\<lparr>carrier := H\\<rparr>\\<^esub> N)\\<rparr>)\" unfolding FactGroup_def by auto\n  moreover have \"rcosets\\<^bsub>G\\<lparr>carrier := H\\<rparr>\\<^esub> N \\<subseteq> carrier (G Mod N)\" unfolding FactGroup_def RCOSETS_def r_coset_def\n    using assms(3) subgroup_imp_subset by fastforce\n  ultimately show ?thesis using GModN.is_group group.restrict_group_imp_subgroup by auto\nqed\n\ntext {* A normality relation survives factoring by a normal subgroup. *}\n\nlemma (in group) normality_factorization:\n  assumes NG:\"N \\<lhd> G\" and NH:\"N \\<subseteq> H\" and HG:\"H \\<lhd> G\"\n  shows \"(rcosets\\<^bsub>G\\<lparr>carrier := H\\<rparr>\\<^esub> N) \\<lhd> (G Mod N)\"\nproof -\n  from assms(1) interpret GModN: group \"G Mod N\" by (metis normal.factorgroup_is_group)\n  show ?thesis\n  proof (auto simp: GModN.normal_inv_iff)\n    from assms show \"subgroup (rcosets\\<^bsub>G\\<lparr>carrier := H\\<rparr>\\<^esub> N) (G Mod N)\" using normal_imp_subgroup normal_subgroup_factorize by force\n  next\n    fix U V\n    assume U:\"U \\<in> carrier (G Mod N)\" and V:\"V \\<in> rcosets\\<^bsub>G\\<lparr>carrier := H\\<rparr>\\<^esub> N\"\n    then obtain g where g:\"g \\<in> carrier G\" \"U = N #> g\" unfolding FactGroup_def RCOSETS_def by auto\n    from V obtain h where h:\"h \\<in> H\" \"V = N #> h\" unfolding FactGroup_def RCOSETS_def r_coset_def by auto\n    hence hG:\"h \\<in> carrier G\" using HG normal_imp_subgroup subgroup.mem_carrier by force\n    hence ghG:\"g \\<otimes> h \\<in> carrier G\" using g m_closed by auto\n    from g h have \"g \\<otimes> h \\<otimes> inv g \\<in> H\" using HG normal_inv_iff by auto\n    moreover have \"U <#> V <#> inv\\<^bsub>G Mod N\\<^esub> U = N #> (g \\<otimes> h \\<otimes> inv g)\"\n    proof -\n      from g U have \"inv\\<^bsub>G Mod N\\<^esub> U = N #> inv g\" using NG normal.inv_FactGroup normal.rcos_inv by fastforce\n      hence \"U <#> V <#> inv\\<^bsub>G Mod N\\<^esub> U = (N #> g) <#> (N #> h) <#> (N #> inv g)\" using g h by simp\n      also have \"\\<dots> = N #> (g \\<otimes> h) <#> (N #> inv g)\" using g hG NG normal.rcos_sum by force\n      also have \"\\<dots> = N #> (g \\<otimes> h \\<otimes> inv g)\" using g inv_closed ghG NG normal.rcos_sum by force\n      finally show ?thesis .\n    qed\n    ultimately show \"U <#> V <#> inv\\<^bsub>G Mod N\\<^esub> U \\<in> rcosets\\<^bsub>G\\<lparr>carrier := H\\<rparr>\\<^esub> N\" unfolding RCOSETS_def r_coset_def by auto\n  qed\nqed\n\ntext {* Factoring by a normal subgroups yields the trivial group iff the subgroup is the whole group. *}\n\nlemma (in normal) fact_group_trivial_iff:\n  assumes \"finite (carrier G)\"\n  shows \"(carrier (G Mod H) = {\\<one>\\<^bsub>G Mod H\\<^esub>}) = (H = carrier G)\"\nproof\n  assume \"carrier (G Mod H) = {\\<one>\\<^bsub>G Mod H\\<^esub>}\"\n  moreover with assms lagrange have \"order (G Mod H) * card H = order G\" unfolding FactGroup_def order_def using is_subgroup by force\n  ultimately have \"card H = order G\" unfolding order_def by auto\n  thus \"H = carrier G\" using subgroup_imp_subset is_subgroup assms card_subset_eq unfolding order_def\n    by metis\nnext\n  from assms have ordergt0:\"order G > 0\" unfolding order_def by (metis subgroup.finite_imp_card_positive subgroup_self)\n  assume \"H = carrier G\"\n  hence \"card H = order G\" unfolding order_def by simp\n  with assms is_subgroup lagrange have \"card (rcosets H) * order G = order G\" by metis\n  with ordergt0 have \"card (rcosets H) = 1\" by (metis mult_eq_self_implies_10 mult.commute neq0_conv)\n  hence \"order (G Mod H) = 1\" unfolding order_def FactGroup_def by auto\n  thus \"carrier (G Mod H) = {\\<one>\\<^bsub>G Mod H\\<^esub>}\" using factorgroup_is_group by (metis group.order_one_triv_iff)\nqed\n\ntext {* Finite groups have finite quotients. *}\n\nlemma (in normal) factgroup_finite:\n  assumes \"finite (carrier G)\"\n  shows \"finite (rcosets H)\"\nusing assms unfolding RCOSETS_def by auto\n\ntext {* The union of all the cosets contained in a subgroup of a quotient group acts as a represenation for that subgroup. *}\n\nlemma (in normal) factgroup_subgroup_union_char:\n  assumes \"subgroup A (G Mod H)\"\n  shows \"(\\<Union>A) = {x \\<in> carrier G. H #> x \\<in> A}\"\nproof\n  show \"\\<Union>A \\<subseteq> {x \\<in> carrier G. H #> x \\<in> A}\"\n  proof\n    fix x\n    assume x:\"x \\<in> \\<Union>A\"\n    then obtain a where a:\"a \\<in> A\" \"x \\<in> a\" by auto\n    with assms have xx:\"x \\<in> carrier G\" using subgroup_imp_subset unfolding FactGroup_def RCOSETS_def r_coset_def by force\n    from assms a obtain y where y:\"y \\<in> carrier G\" \"a = H #> y\" using subgroup_imp_subset unfolding FactGroup_def RCOSETS_def by force\n    with a have \"x \\<in> H #> y\" by simp\n    hence \"H #> y = H #> x\" using y is_subgroup repr_independence by auto\n    with y(2) a(1) have \"H #> x \\<in> A\" by auto\n    with xx show \"x \\<in> {x \\<in> carrier G. H #> x \\<in> A}\" by simp\n  qed\nnext\n  show \"{x \\<in> carrier G. H #> x \\<in> A} \\<subseteq> \\<Union>A\"\n  proof\n    fix x\n    assume x:\"x \\<in> {x \\<in> carrier G. H #> x \\<in> A}\"\n    hence xx:\"x \\<in> carrier G\" \"H #> x \\<in> A\" by auto\n    moreover have \"x \\<in> H #> x\" by (metis is_subgroup rcos_self xx(1))\n    ultimately show \"x \\<in> \\<Union>A\" by auto\n  qed\nqed\n\nlemma (in normal) factgroup_subgroup_union_subgroup:\n  assumes \"subgroup A (G Mod H)\"\n  shows \"subgroup (\\<Union>A) G\"\nproof -\n  have \"subgroup {x \\<in> carrier G. H #> x \\<in> A} G\"\n  proof\n    show \"{x \\<in> carrier G. H #> x \\<in> A} \\<subseteq> carrier G\" by auto\n  next\n    fix x y\n    assume \"x \\<in> {x \\<in> carrier G. H #> x \\<in> A}\" and \"y \\<in> {x \\<in> carrier G. H #> x \\<in> A}\"\n    hence x:\"x \\<in> carrier G\" \"H #> x \\<in> A\" and y:\"y \\<in> carrier G\" \"H #> y \\<in> A\" by auto\n    hence xyG:\"x \\<otimes> y \\<in> carrier G\" by (metis m_closed)\n    from assms x y have \"(H #> x) <#> (H #> y) \\<in> A\" using subgroup.m_closed unfolding FactGroup_def by fastforce\n    hence \"H #> (x \\<otimes> y) \\<in> A\" by (metis rcos_sum x(1) y(1))\n    with xyG show \"x \\<otimes> y \\<in> {x \\<in> carrier G. H #> x \\<in> A}\" by simp\n  next\n    have \"H #> \\<one> \\<in> A\" using assms subgroup.one_closed unfolding FactGroup_def by (metis coset_mult_one monoid.select_convs(2) subset)\n    with assms one_closed show \"\\<one> \\<in> {x \\<in> carrier G. H #> x \\<in> A}\" by simp\n  next\n    fix x\n    assume \"x \\<in> {x \\<in> carrier G. H #> x \\<in> A}\"\n    hence x:\"x \\<in> carrier G\" \"H #> x \\<in> A\" by auto\n    hence invx:\"inv x \\<in> carrier G\" using inv_closed by simp\n    from assms x have \"set_inv (H #> x) \\<in> A\" using subgroup.m_inv_closed by (metis inv_FactGroup subgroup.mem_carrier)\n    hence \"H #> (inv x) \\<in> A\" by (metis rcos_inv x(1))\n    with invx show \"inv x \\<in> {x \\<in> carrier G. H #> x \\<in> A}\" by simp\n  qed\n  with assms factgroup_subgroup_union_char show ?thesis by auto\nqed\n\nlemma (in normal) factgroup_subgroup_union_normal:\n  assumes \"A \\<lhd> (G Mod H)\"\n  shows \"\\<Union>A \\<lhd> G\"\nproof - \n  have \"{x \\<in> carrier G. H #> x \\<in> A} \\<lhd> G\"\n  unfolding normal_def normal_axioms_def\n  proof auto (*(auto del: equalityI)*)\n    from assms show \"subgroup {x \\<in> carrier G. H #> x \\<in> A} G\"\n      by (metis (full_types) factgroup_subgroup_union_char factgroup_subgroup_union_subgroup normal_imp_subgroup)\n  next\n    show \"group G\" by (rule is_group)\n  next\n    interpret Anormal: normal A \"(G Mod H)\" using assms by simp\n    fix x y\n    assume x:\"x \\<in> carrier G\" \"y \\<in> {x \\<in> carrier G. H #> x \\<in> A} #> x\"\n    then obtain x' where \"x' \\<in> {x \\<in> carrier G. H #> x \\<in> A}\" \"y = x' \\<otimes> x\" unfolding r_coset_def by auto\n    hence x':\"x' \\<in> carrier G\" \"H #> x' \\<in> A\" by auto\n    from x(1) have Hx:\"H #> x \\<in> carrier (G Mod H)\" unfolding FactGroup_def RCOSETS_def by force\n    with x' have \"(inv\\<^bsub>G Mod H\\<^esub> (H #> x)) \\<otimes>\\<^bsub>G Mod H\\<^esub> (H #> x') \\<otimes>\\<^bsub>G Mod H\\<^esub> (H #> x) \\<in> A\" using Anormal.inv_op_closed1 by auto\n    hence \"(set_inv (H #> x)) <#> (H #> x') <#> (H #> x) \\<in> A\" using inv_FactGroup Hx unfolding FactGroup_def by auto\n    hence \"(H #> (inv x)) <#> (H #> x') <#> (H #> x) \\<in> A\" using x(1) by (metis rcos_inv)\n    hence \"(H #> (inv x \\<otimes> x')) <#> (H #> x) \\<in> A\" by (metis inv_closed rcos_sum x'(1) x(1))\n    hence \"H #> (inv x \\<otimes> x' \\<otimes> x) \\<in> A\" by (metis inv_closed m_closed rcos_sum x'(1) x(1))\n    moreover have \"inv x \\<otimes> x' \\<otimes> x \\<in> carrier G\" using x x' by (metis inv_closed m_closed)\n    ultimately have \"inv x \\<otimes> x' \\<otimes> x \\<in> {x \\<in> carrier G. H #> x \\<in> A}\" by auto\n    hence xcoset:\"x \\<otimes> (inv x \\<otimes> x' \\<otimes> x) \\<in> x <# {x \\<in> carrier G. H #> x \\<in> A}\" unfolding l_coset_def using x(1) by auto\n    have \"x \\<otimes> (inv x \\<otimes> x' \\<otimes> x) = (x \\<otimes> inv x) \\<otimes> x' \\<otimes> x\" by (metis Units_eq Units_inv_Units m_assoc m_closed x'(1) x(1))\n    also have \"\\<dots> = x' \\<otimes> x\" by (metis l_one r_inv x'(1) x(1))\n    also have \"\\<dots> = y\" by (metis `y = x' \\<otimes> x`)\n    finally have \"x \\<otimes> (inv x \\<otimes> x' \\<otimes> x) = y\".\n    with xcoset show \"y \\<in> x <# {x \\<in> carrier G. H #> x \\<in> A}\" by auto\n  next\n    interpret Anormal: normal A \"(G Mod H)\" using assms by simp\n    fix x y\n    assume x:\"x \\<in> carrier G\" \"y \\<in> x <# {x \\<in> carrier G. H #> x \\<in> A}\"\n    then obtain x' where \"x' \\<in> {x \\<in> carrier G. H #> x \\<in> A}\" \"y = x \\<otimes> x'\" unfolding l_coset_def by auto\n    hence x':\"x' \\<in> carrier G\" \"H #> x' \\<in> A\" by auto\n    from x(1) have invx:\"inv x \\<in> carrier G\" by (rule inv_closed)\n    hence Hinvx:\"H #> (inv x) \\<in> carrier (G Mod H)\" unfolding FactGroup_def RCOSETS_def by force\n    with x' have \"(inv\\<^bsub>G Mod H\\<^esub> (H #> inv x)) \\<otimes>\\<^bsub>G Mod H\\<^esub> (H #> x') \\<otimes>\\<^bsub>G Mod H\\<^esub> (H #> inv x) \\<in> A\" using invx Anormal.inv_op_closed1 by auto\n    hence \"(set_inv (H #> inv x)) <#> (H #> x') <#> (H #> inv x) \\<in> A\" using inv_FactGroup Hinvx unfolding FactGroup_def by auto\n    hence \"(H #> inv (inv x)) <#> (H #> x') <#> (H #> inv x) \\<in> A\" using invx by (metis rcos_inv)\n    hence \"(H #> x) <#> (H #> x') <#> (H #> inv x) \\<in> A\" by (metis inv_inv x(1))\n    hence \"(H #> (x \\<otimes> x')) <#> (H #> inv x) \\<in> A\" by (metis rcos_sum x'(1) x(1))\n    hence \"H #> (x \\<otimes> x' \\<otimes> inv x) \\<in> A\" by (metis inv_closed m_closed rcos_sum x'(1) x(1))\n    moreover have \"x \\<otimes> x' \\<otimes> inv x \\<in> carrier G\" using x x' by (metis inv_closed m_closed)\n    ultimately have \"x \\<otimes> x' \\<otimes> inv x \\<in> {x \\<in> carrier G. H #> x \\<in> A}\" by auto\n    hence xcoset:\"(x \\<otimes> x' \\<otimes> inv x) \\<otimes> x \\<in> {x \\<in> carrier G. H #> x \\<in> A} #> x\" unfolding r_coset_def using invx by auto\n    have \"(x \\<otimes> x' \\<otimes> inv x) \\<otimes> x = (x \\<otimes> x') \\<otimes> (inv x \\<otimes> x)\" by (metis Units_eq Units_inv_Units m_assoc m_closed x'(1) x(1))\n    also have \"\\<dots> = x \\<otimes> x'\" using x(1) l_inv x'(1) m_closed r_one by auto\n    also have \"\\<dots> = y\" by (metis `y = x \\<otimes> x'`)\n    finally have \"x \\<otimes> x' \\<otimes> inv x \\<otimes> x = y\".\n    with xcoset show \"y \\<in> {x \\<in> carrier G. H #> x \\<in> A} #> x\" by auto\n  qed\n  with assms show ?thesis by (metis (full_types) factgroup_subgroup_union_char normal_imp_subgroup)\nqed\n\nlemma (in normal) factgroup_subgroup_union_factor:\n  assumes \"subgroup A (G Mod H)\"\n  shows \"A = rcosets\\<^bsub>G\\<lparr>carrier := \\<Union>A\\<rparr>\\<^esub> H\"\nproof -\n  have \"A = rcosets\\<^bsub>G\\<lparr>carrier := {x \\<in> carrier G. H #> x \\<in> A}\\<rparr>\\<^esub> H\"\n  proof auto\n    fix U\n    assume U:\"U \\<in> A\"\n    then obtain x' where x':\"x' \\<in> carrier G\" \"U = H #> x'\" using assms subgroup_imp_subset unfolding FactGroup_def RCOSETS_def by force\n    with U have \"H #> x' \\<in> A\" by simp\n    with x' show \"U \\<in> rcosets\\<^bsub>G\\<lparr>carrier := {x \\<in> carrier G. H #> x \\<in> A}\\<rparr>\\<^esub> H\" unfolding RCOSETS_def r_coset_def by auto\n  next\n    fix U\n    assume U:\"U \\<in> rcosets\\<^bsub>G\\<lparr>carrier := {x \\<in> carrier G. H #> x \\<in> A}\\<rparr>\\<^esub> H\"\n    then obtain x' where x':\"x' \\<in> {x \\<in> carrier G. H #> x \\<in> A}\" \"U = H #> x'\" unfolding RCOSETS_def r_coset_def by auto\n    hence \"x' \\<in> carrier G\" \"H #> x' \\<in> A\" by auto\n    with x' show \"U \\<in> A\" by simp\n  qed\n  with assms show ?thesis using factgroup_subgroup_union_char by auto\nqed\n\n\nsection  {* Flattening the type of group carriers *}\n\ntext {* Flattening here means to convert the type of group elements from 'a set to 'a.\nThis is possible whenever the empty set is not an element of the group. *}\n\ndefinition flatten where\n  \"flatten (G::('a set, 'b) monoid_scheme) rep = \\<lparr>carrier=(rep ` (carrier G)),\n      mult=(\\<lambda> x y. rep ((the_inv_into (carrier G) rep x) \\<otimes>\\<^bsub>G\\<^esub> (the_inv_into (carrier G) rep y))), one=rep \\<one>\\<^bsub>G\\<^esub> \\<rparr>\"\n\nlemma flatten_set_group_hom:\n  assumes group:\"group G\"\n  assumes inj:\"inj_on rep (carrier G)\"\n  shows \"rep \\<in> hom G (flatten G rep)\"\nunfolding hom_def\nproof auto\n  fix g\n  assume g:\"g \\<in> carrier G\"\n  thus \"rep g \\<in> carrier (flatten G rep)\" unfolding flatten_def by auto\nnext\n  fix g h\n  assume g:\"g \\<in> carrier G\" and h:\"h \\<in> carrier G\"\n  hence \"rep g \\<in> carrier (flatten G rep)\" \"rep h \\<in> carrier (flatten G rep)\" unfolding flatten_def by auto\n  hence \"rep g \\<otimes>\\<^bsub>flatten G rep\\<^esub> rep h\n    = rep (the_inv_into (carrier G) rep (rep g) \\<otimes>\\<^bsub>G\\<^esub> the_inv_into (carrier G) rep (rep h))\" unfolding flatten_def by auto\n  also have \"\\<dots> = rep (g \\<otimes>\\<^bsub>G\\<^esub> h)\" using inj g h by (metis the_inv_into_f_f)\n  finally show \"rep (g \\<otimes>\\<^bsub>G\\<^esub> h) = rep g \\<otimes>\\<^bsub>flatten G rep\\<^esub> rep h\"..\nqed\n\nlemma flatten_set_group:\n  assumes group:\"group G\"\n  assumes inj:\"inj_on rep (carrier G)\"\n  shows \"group (flatten G rep)\"\nproof (rule groupI)\n  fix x y\n  assume x:\"x \\<in> carrier (flatten G rep)\" and y:\"y \\<in> carrier (flatten G rep)\"\n  def g \\<equiv> \"the_inv_into (carrier G) rep x\" and h \\<equiv> \"the_inv_into (carrier G) rep y\"\n  hence \"x \\<otimes>\\<^bsub>flatten G rep\\<^esub> y = rep (g \\<otimes>\\<^bsub>G\\<^esub> h)\" unfolding flatten_def by auto\n  moreover from g_def h_def have \"g \\<in> carrier G\" \"h \\<in> carrier G\" \n    using inj x y the_inv_into_into unfolding flatten_def by (metis partial_object.select_convs(1) subset_refl)+\n  hence \"g \\<otimes>\\<^bsub>G\\<^esub> h \\<in> carrier G\" by (metis group group.is_monoid monoid.m_closed)\n  hence \"rep (g \\<otimes>\\<^bsub>G\\<^esub> h) \\<in> carrier (flatten G rep)\" unfolding flatten_def by simp\n  ultimately show \"x \\<otimes>\\<^bsub>flatten G rep\\<^esub> y \\<in> carrier (flatten G rep)\" by simp\nnext\n  show \"\\<one>\\<^bsub>flatten G rep\\<^esub> \\<in> carrier (flatten G rep)\" unfolding flatten_def by (simp add: group group.is_monoid)\nnext\n  fix x y z\n  assume x:\"x \\<in> carrier (flatten G rep)\" and y:\"y \\<in> carrier (flatten G rep)\" and z:\"z \\<in> carrier (flatten G rep)\"\n  def g \\<equiv> \"the_inv_into (carrier G) rep x\" and h \\<equiv> \"the_inv_into (carrier G) rep y\" and k \\<equiv> \"the_inv_into (carrier G) rep z\"\n  hence \"x \\<otimes>\\<^bsub>flatten G rep\\<^esub> y \\<otimes>\\<^bsub>flatten G rep\\<^esub> z = (rep (g \\<otimes>\\<^bsub>G\\<^esub> h)) \\<otimes> \\<^bsub>flatten G rep\\<^esub> z\" unfolding flatten_def by auto\n  also have \"\\<dots> = rep (the_inv_into (carrier G) rep (rep (g \\<otimes>\\<^bsub>G\\<^esub> h)) \\<otimes>\\<^bsub>G\\<^esub> k)\" using k_def unfolding flatten_def by auto\n  also from g_def h_def k_def have ghkG:\"g \\<in> carrier G\" \"h \\<in> carrier G\" \"k \\<in> carrier G\"\n    using inj x y z the_inv_into_into unfolding flatten_def by fastforce+\n  hence gh:\"g \\<otimes>\\<^bsub>G\\<^esub> h \\<in> carrier G\" and hk:\"h \\<otimes>\\<^bsub>G\\<^esub> k \\<in> carrier G\" by (metis group group.is_monoid monoid.m_closed)+\n  hence \"rep (the_inv_into (carrier G) rep (rep (g \\<otimes>\\<^bsub>G\\<^esub> h)) \\<otimes>\\<^bsub>G\\<^esub> k) = rep ((g \\<otimes>\\<^bsub>G\\<^esub> h) \\<otimes>\\<^bsub>G\\<^esub> k)\"\n    unfolding flatten_def using inj the_inv_into_f_f by fastforce\n  also have \"\\<dots> = rep (g \\<otimes>\\<^bsub>G\\<^esub> (h \\<otimes>\\<^bsub>G\\<^esub> k))\" using group group.is_monoid ghkG monoid.m_assoc by fastforce\n  also have \"\\<dots> = x \\<otimes>\\<^bsub>flatten G rep\\<^esub> (rep (h \\<otimes>\\<^bsub>G\\<^esub> k))\" unfolding g_def flatten_def using hk inj the_inv_into_f_f by fastforce\n  also have \"\\<dots> = x \\<otimes>\\<^bsub>flatten G rep\\<^esub> (y \\<otimes>\\<^bsub>flatten G rep\\<^esub> z)\" unfolding h_def k_def flatten_def using x y by force\n  finally show \"x \\<otimes>\\<^bsub>flatten G rep\\<^esub> y \\<otimes>\\<^bsub>flatten G rep\\<^esub> z = x \\<otimes>\\<^bsub>flatten G rep\\<^esub> (y \\<otimes>\\<^bsub>flatten G rep\\<^esub> z)\".\nnext\n  fix x\n  assume x:\"x \\<in> carrier (flatten G rep)\"\n  def g \\<equiv> \"the_inv_into (carrier G) rep x\"\n  hence gG:\"g \\<in> carrier G\" using inj x unfolding flatten_def using the_inv_into_into by force\n  have \"\\<one>\\<^bsub>G\\<^esub> \\<in> (carrier G)\" by (simp add: group group.is_monoid)\n  hence \"the_inv_into (carrier G) rep (\\<one>\\<^bsub>flatten G rep\\<^esub>) = \\<one>\\<^bsub>G\\<^esub>\" unfolding flatten_def using the_inv_into_f_f inj by force\n  hence \"\\<one>\\<^bsub>flatten G rep\\<^esub> \\<otimes>\\<^bsub>flatten G rep\\<^esub> x = rep (\\<one>\\<^bsub>G\\<^esub> \\<otimes>\\<^bsub>G\\<^esub> g)\" unfolding flatten_def g_def by simp\n  also have \"\\<dots> = rep g\" using gG group by (metis group.is_monoid monoid.l_one)\n  also have \"\\<dots> = x\" unfolding g_def using inj x f_the_inv_into_f unfolding flatten_def by force\n  finally show \"\\<one>\\<^bsub>flatten G rep\\<^esub> \\<otimes>\\<^bsub>flatten G rep\\<^esub> x = x\".\nnext\n  from group inj have hom:\"rep \\<in> hom G (flatten G rep)\" using flatten_set_group_hom by auto\n  fix x\n  assume x:\"x \\<in> carrier (flatten G rep)\"\n  def g \\<equiv> \"the_inv_into (carrier G) rep x\"\n  hence gG:\"g \\<in> carrier G\" using inj x unfolding flatten_def using the_inv_into_into by force\n  hence invG:\"inv\\<^bsub>G\\<^esub> g \\<in> carrier G\" by (metis group group.inv_closed)\n  hence \"rep (inv\\<^bsub>G\\<^esub> g) \\<in> carrier (flatten G rep)\" unfolding flatten_def by auto\n  moreover have \"rep (inv\\<^bsub>G\\<^esub> g) \\<otimes>\\<^bsub>flatten G rep\\<^esub> x = rep (inv\\<^bsub>G\\<^esub> g) \\<otimes>\\<^bsub>flatten G rep\\<^esub> (rep g)\"\n    unfolding g_def using f_the_inv_into_f inj x unfolding flatten_def by fastforce\n  hence \"rep (inv\\<^bsub>G\\<^esub> g) \\<otimes>\\<^bsub>flatten G rep\\<^esub> x = rep (inv\\<^bsub>G\\<^esub> g \\<otimes>\\<^bsub>G\\<^esub> g)\"\n    using hom unfolding hom_def using gG invG hom_def by auto\n  hence \"rep (inv\\<^bsub>G\\<^esub> g) \\<otimes>\\<^bsub>flatten G rep\\<^esub> x = rep \\<one>\\<^bsub>G\\<^esub>\" using invG gG by (metis group group.l_inv)\n  hence \"rep (inv\\<^bsub>G\\<^esub> g) \\<otimes>\\<^bsub>flatten G rep\\<^esub> x = \\<one>\\<^bsub>flatten G rep\\<^esub>\" unfolding flatten_def by auto\n  ultimately show \"\\<exists>y\\<in>carrier (flatten G rep). y \\<otimes>\\<^bsub>flatten G rep\\<^esub> x = \\<one>\\<^bsub>flatten G rep\\<^esub>\" by auto\nqed\n\nlemma (in normal) flatten_set_group_mod_inj:\n  shows \"inj_on (\\<lambda>U. SOME g. g \\<in> U) (carrier (G Mod H))\"\nproof (rule inj_onI)\n  fix U V\n  assume U:\"U \\<in> carrier (G Mod H)\" and V:\"V \\<in> carrier (G Mod H)\"\n  then obtain g h where g:\"U = H #> g\" \"g \\<in> carrier G\" and h:\"V = H #> h\" \"h \\<in> carrier G\"\n    unfolding FactGroup_def RCOSETS_def by auto\n  hence notempty:\"U \\<noteq> {}\" \"V \\<noteq> {}\" by (metis empty_iff is_subgroup rcos_self)+\n  assume \"(SOME g. g \\<in> U) = (SOME g. g \\<in> V)\"\n  with notempty have \"(SOME g. g \\<in> U) \\<in> U \\<inter> V\" by (metis IntI ex_in_conv someI)\n  thus \"U = V\" by (metis Int_iff g h is_subgroup repr_independence)\nqed\n\nlemma (in normal) flatten_set_group_mod:\n  shows \"group (flatten (G Mod H) (\\<lambda>U. SOME g. g \\<in> U))\"\nusing factorgroup_is_group flatten_set_group_mod_inj by (rule flatten_set_group)\n\nlemma (in normal) flatten_set_group_mod_iso:\n  shows \"(\\<lambda>U. SOME g. g \\<in> U) \\<in> (G Mod H) \\<cong> (flatten (G Mod H) (\\<lambda>U. SOME g. g \\<in> U))\"\nunfolding iso_def bij_betw_def\napply (auto)\n apply (metis flatten_set_group_mod_inj factorgroup_is_group flatten_set_group_hom)\n apply (rule flatten_set_group_mod_inj)\n unfolding flatten_def apply (auto)\ndone\n\nend\n", "meta": {"author": "javra", "repo": "isabelle_algebra", "sha": "922a6962b451ef543ca18feaecae92ece373d535", "save_path": "github-repos/isabelle/javra-isabelle_algebra", "path": "github-repos/isabelle/javra-isabelle_algebra/isabelle_algebra-922a6962b451ef543ca18feaecae92ece373d535/Jordan_Holder/SubgroupsAndNormalSubgroups.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8596637361282707, "lm_q2_score": 0.8175744828610095, "lm_q1q2_score": 0.7028391344994344}}
{"text": "(*  Title:    HOL/Analysis/Integral_Test.thy\n    Author:   Manuel Eberl, TU M\u00fcnchen\n*)\n\nsection \\<open>Integral Test for Summability\\<close>\n\ntheory Integral_Test\nimports Henstock_Kurzweil_Integration\nbegin\n\ntext \\<open>\n  The integral test for summability. We show here that for a decreasing non-negative\n  function, the infinite sum over that function evaluated at the natural numbers\n  converges iff the corresponding integral converges.\n\n  As a useful side result, we also provide some results on the difference between\n  the integral and the partial sum. (This is useful e.g. for the definition of the\n  Euler-Mascheroni constant)\n\\<close>\n\n(* TODO: continuous_in \\<rightarrow> integrable_on *)\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 sum_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 sum_diff) auto\n  also have \"\\<dots> \\<le> 0\" by (auto intro!: sum_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\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/Integral_Test.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744584140003, "lm_q2_score": 0.8596637505099168, "lm_q1q2_score": 0.7028391252412935}}
{"text": "(*  Title:      HOL/Nonstandard_Analysis/HSEQ.thy\n    Author:     Jacques D. Fleuriot\n    Copyright:  1998  University of Cambridge\n\nConvergence of sequences and series.\n\nConversion to Isar and new proofs by Lawrence C Paulson, 2004\nAdditional contributions by Jeremy Avigad and Brian Huffman.\n*)\n\nsection \\<open>Sequences and Convergence (Nonstandard)\\<close>\n\ntheory HSEQ\n  imports Limits NatStar\n  abbrevs \"--->\" = \"\\<longlonglongrightarrow>\\<^sub>N\\<^sub>S\"\nbegin\n\ndefinition\n  NSLIMSEQ :: \"[nat => 'a::real_normed_vector, 'a] => bool\"\n    (\"((_)/ \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S (_))\" [60, 60] 60) where\n    \\<comment>\\<open>Nonstandard definition of convergence of sequence\\<close>\n  \"X \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S L = (\\<forall>N \\<in> HNatInfinite. ( *f* X) N \\<approx> star_of L)\"\n\ndefinition\n  nslim :: \"(nat => 'a::real_normed_vector) => 'a\" where\n    \\<comment>\\<open>Nonstandard definition of limit using choice operator\\<close>\n  \"nslim X = (THE L. X \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S L)\"\n\ndefinition\n  NSconvergent :: \"(nat => 'a::real_normed_vector) => bool\" where\n    \\<comment>\\<open>Nonstandard definition of convergence\\<close>\n  \"NSconvergent X = (\\<exists>L. X \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S L)\"\n\ndefinition\n  NSBseq :: \"(nat => 'a::real_normed_vector) => bool\" where\n    \\<comment>\\<open>Nonstandard definition for bounded sequence\\<close>\n  \"NSBseq X = (\\<forall>N \\<in> HNatInfinite. ( *f* X) N : HFinite)\"\n\ndefinition\n  NSCauchy :: \"(nat => 'a::real_normed_vector) => bool\" where\n    \\<comment>\\<open>Nonstandard definition\\<close>\n  \"NSCauchy X = (\\<forall>M \\<in> HNatInfinite. \\<forall>N \\<in> HNatInfinite. ( *f* X) M \\<approx> ( *f* X) N)\"\n\nsubsection \\<open>Limits of Sequences\\<close>\n\nlemma NSLIMSEQ_iff:\n    \"(X \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S L) = (\\<forall>N \\<in> HNatInfinite. ( *f* X) N \\<approx> star_of L)\"\nby (simp add: NSLIMSEQ_def)\n\nlemma NSLIMSEQ_I:\n  \"(\\<And>N. N \\<in> HNatInfinite \\<Longrightarrow> starfun X N \\<approx> star_of L) \\<Longrightarrow> X \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S L\"\nby (simp add: NSLIMSEQ_def)\n\nlemma NSLIMSEQ_D:\n  \"\\<lbrakk>X \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S L; N \\<in> HNatInfinite\\<rbrakk> \\<Longrightarrow> starfun X N \\<approx> star_of L\"\nby (simp add: NSLIMSEQ_def)\n\nlemma NSLIMSEQ_const: \"(%n. k) \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S k\"\nby (simp add: NSLIMSEQ_def)\n\nlemma NSLIMSEQ_add:\n      \"[| X \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S a; Y \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S b |] ==> (%n. X n + Y n) \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S a + b\"\nby (auto intro: approx_add simp add: NSLIMSEQ_def starfun_add [symmetric])\n\nlemma NSLIMSEQ_add_const: \"f \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S a ==> (%n.(f n + b)) \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S a + b\"\nby (simp only: NSLIMSEQ_add NSLIMSEQ_const)\n\nlemma NSLIMSEQ_mult:\n  fixes a b :: \"'a::real_normed_algebra\"\n  shows \"[| X \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S a; Y \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S b |] ==> (%n. X n * Y n) \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S a * b\"\nby (auto intro!: approx_mult_HFinite simp add: NSLIMSEQ_def)\n\nlemma NSLIMSEQ_minus: \"X \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S a ==> (%n. -(X n)) \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S -a\"\nby (auto simp add: NSLIMSEQ_def)\n\nlemma NSLIMSEQ_minus_cancel: \"(%n. -(X n)) \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S -a ==> X \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S a\"\nby (drule NSLIMSEQ_minus, simp)\n\nlemma NSLIMSEQ_diff:\n     \"[| X \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S a; Y \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S b |] ==> (%n. X n - Y n) \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S a - b\"\n  using NSLIMSEQ_add [of X a \"- Y\" \"- b\"] by (simp add: NSLIMSEQ_minus fun_Compl_def)\n\n(* FIXME: delete *)\nlemma NSLIMSEQ_add_minus:\n     \"[| X \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S a; Y \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S b |] ==> (%n. X n + -Y n) \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S a + -b\"\n  by (simp add: NSLIMSEQ_diff)\n\nlemma NSLIMSEQ_diff_const: \"f \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S a ==> (%n.(f n - b)) \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S a - b\"\nby (simp add: NSLIMSEQ_diff NSLIMSEQ_const)\n\nlemma NSLIMSEQ_inverse:\n  fixes a :: \"'a::real_normed_div_algebra\"\n  shows \"[| X \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S a;  a ~= 0 |] ==> (%n. inverse(X n)) \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S inverse(a)\"\nby (simp add: NSLIMSEQ_def star_of_approx_inverse)\n\nlemma NSLIMSEQ_mult_inverse:\n  fixes a b :: \"'a::real_normed_field\"\n  shows\n     \"[| X \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S a;  Y \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S b;  b ~= 0 |] ==> (%n. X n / Y n) \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S a/b\"\nby (simp add: NSLIMSEQ_mult NSLIMSEQ_inverse divide_inverse)\n\nlemma starfun_hnorm: \"\\<And>x. hnorm (( *f* f) x) = ( *f* (\\<lambda>x. norm (f x))) x\"\nby transfer simp\n\nlemma NSLIMSEQ_norm: \"X \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S a \\<Longrightarrow> (\\<lambda>n. norm (X n)) \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S norm a\"\nby (simp add: NSLIMSEQ_def starfun_hnorm [symmetric] approx_hnorm)\n\ntext\\<open>Uniqueness of limit\\<close>\nlemma NSLIMSEQ_unique: \"[| X \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S a; X \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S b |] ==> a = b\"\napply (simp add: NSLIMSEQ_def)\napply (drule HNatInfinite_whn [THEN [2] bspec])+\napply (auto dest: approx_trans3)\ndone\n\nlemma NSLIMSEQ_pow [rule_format]:\n  fixes a :: \"'a::{real_normed_algebra,power}\"\n  shows \"(X \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S a) --> ((%n. (X n) ^ m) \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S a ^ m)\"\napply (induct \"m\")\napply (auto simp add: power_Suc intro: NSLIMSEQ_mult NSLIMSEQ_const)\ndone\n\ntext\\<open>We can now try and derive a few properties of sequences,\n     starting with the limit comparison property for sequences.\\<close>\n\nlemma NSLIMSEQ_le:\n       \"[| f \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S l; g \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S m;\n           \\<exists>N. \\<forall>n \\<ge> N. f(n) \\<le> g(n)\n        |] ==> l \\<le> (m::real)\"\napply (simp add: NSLIMSEQ_def, safe)\napply (drule starfun_le_mono)\napply (drule HNatInfinite_whn [THEN [2] bspec])+\napply (drule_tac x = whn in spec)\napply (drule bex_Infinitesimal_iff2 [THEN iffD2])+\napply clarify\napply (auto intro: hypreal_of_real_le_add_Infininitesimal_cancel2)\ndone\n\nlemma NSLIMSEQ_le_const: \"[| X \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S (r::real); \\<forall>n. a \\<le> X n |] ==> a \\<le> r\"\nby (erule NSLIMSEQ_le [OF NSLIMSEQ_const], auto)\n\nlemma NSLIMSEQ_le_const2: \"[| X \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S (r::real); \\<forall>n. X n \\<le> a |] ==> r \\<le> a\"\nby (erule NSLIMSEQ_le [OF _ NSLIMSEQ_const], auto)\n\ntext\\<open>Shift a convergent series by 1:\n  By the equivalence between Cauchiness and convergence and because\n  the successor of an infinite hypernatural is also infinite.\\<close>\n\nlemma NSLIMSEQ_Suc: \"f \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S l ==> (%n. f(Suc n)) \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S l\"\napply (unfold NSLIMSEQ_def, safe)\napply (drule_tac x=\"N + 1\" in bspec)\napply (erule HNatInfinite_add)\napply (simp add: starfun_shift_one)\ndone\n\nlemma NSLIMSEQ_imp_Suc: \"(%n. f(Suc n)) \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S l ==> f \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S l\"\napply (unfold NSLIMSEQ_def, safe)\napply (drule_tac x=\"N - 1\" in bspec) \napply (erule Nats_1 [THEN [2] HNatInfinite_diff])\napply (simp add: starfun_shift_one one_le_HNatInfinite)\ndone\n\nlemma NSLIMSEQ_Suc_iff: \"((%n. f(Suc n)) \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S l) = (f \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S l)\"\nby (blast intro: NSLIMSEQ_imp_Suc NSLIMSEQ_Suc)\n\nsubsubsection \\<open>Equivalence of @{term LIMSEQ} and @{term NSLIMSEQ}\\<close>\n\nlemma LIMSEQ_NSLIMSEQ:\n  assumes X: \"X \\<longlonglongrightarrow> L\" shows \"X \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S L\"\nproof (rule NSLIMSEQ_I)\n  fix N assume N: \"N \\<in> HNatInfinite\"\n  have \"starfun X N - star_of L \\<in> Infinitesimal\"\n  proof (rule InfinitesimalI2)\n    fix r::real assume r: \"0 < r\"\n    from LIMSEQ_D [OF X r]\n    obtain no where \"\\<forall>n\\<ge>no. norm (X n - L) < r\" ..\n    hence \"\\<forall>n\\<ge>star_of no. hnorm (starfun X n - star_of L) < star_of r\"\n      by transfer\n    thus \"hnorm (starfun X N - star_of L) < star_of r\"\n      using N by (simp add: star_of_le_HNatInfinite)\n  qed\n  thus \"starfun X N \\<approx> star_of L\"\n    by (unfold approx_def)\nqed\n\nlemma NSLIMSEQ_LIMSEQ:\n  assumes X: \"X \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S L\" shows \"X \\<longlonglongrightarrow> L\"\nproof (rule LIMSEQ_I)\n  fix r::real assume r: \"0 < r\"\n  have \"\\<exists>no. \\<forall>n\\<ge>no. hnorm (starfun X n - star_of L) < star_of r\"\n  proof (intro exI allI impI)\n    fix n assume \"whn \\<le> n\"\n    with HNatInfinite_whn have \"n \\<in> HNatInfinite\"\n      by (rule HNatInfinite_upward_closed)\n    with X have \"starfun X n \\<approx> star_of L\"\n      by (rule NSLIMSEQ_D)\n    hence \"starfun X n - star_of L \\<in> Infinitesimal\"\n      by (unfold approx_def)\n    thus \"hnorm (starfun X n - star_of L) < star_of r\"\n      using r by (rule InfinitesimalD2)\n  qed\n  thus \"\\<exists>no. \\<forall>n\\<ge>no. norm (X n - L) < r\"\n    by transfer\nqed\n\ntheorem LIMSEQ_NSLIMSEQ_iff: \"(f \\<longlonglongrightarrow> L) = (f \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S L)\"\nby (blast intro: LIMSEQ_NSLIMSEQ NSLIMSEQ_LIMSEQ)\n\nsubsubsection \\<open>Derived theorems about @{term NSLIMSEQ}\\<close>\n\ntext\\<open>We prove the NS version from the standard one, since the NS proof\n   seems more complicated than the standard one above!\\<close>\nlemma NSLIMSEQ_norm_zero: \"((\\<lambda>n. norm (X n)) \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S 0) = (X \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S 0)\"\nby (simp add: LIMSEQ_NSLIMSEQ_iff [symmetric] tendsto_norm_zero_iff)\n\nlemma NSLIMSEQ_rabs_zero: \"((%n. \\<bar>f n\\<bar>) \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S 0) = (f \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S (0::real))\"\nby (simp add: LIMSEQ_NSLIMSEQ_iff [symmetric] tendsto_rabs_zero_iff)\n\ntext\\<open>Generalization to other limits\\<close>\nlemma NSLIMSEQ_imp_rabs: \"f \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S (l::real) ==> (%n. \\<bar>f n\\<bar>) \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S \\<bar>l\\<bar>\"\napply (simp add: NSLIMSEQ_def)\napply (auto intro: approx_hrabs \n            simp add: starfun_abs)\ndone\n\nlemma NSLIMSEQ_inverse_zero:\n     \"\\<forall>y::real. \\<exists>N. \\<forall>n \\<ge> N. y < f(n)\n      ==> (%n. inverse(f n)) \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S 0\"\nby (simp add: LIMSEQ_NSLIMSEQ_iff [symmetric] LIMSEQ_inverse_zero)\n\nlemma NSLIMSEQ_inverse_real_of_nat: \"(%n. inverse(real(Suc n))) \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S 0\"\nby (simp add: LIMSEQ_NSLIMSEQ_iff [symmetric] LIMSEQ_inverse_real_of_nat del: of_nat_Suc)\n\nlemma NSLIMSEQ_inverse_real_of_nat_add:\n     \"(%n. r + inverse(real(Suc n))) \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S r\"\nby (simp add: LIMSEQ_NSLIMSEQ_iff [symmetric] LIMSEQ_inverse_real_of_nat_add del: of_nat_Suc)\n\nlemma NSLIMSEQ_inverse_real_of_nat_add_minus:\n     \"(%n. r + -inverse(real(Suc n))) \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S r\"\n  using LIMSEQ_inverse_real_of_nat_add_minus by (simp add: LIMSEQ_NSLIMSEQ_iff [symmetric])\n\nlemma NSLIMSEQ_inverse_real_of_nat_add_minus_mult:\n     \"(%n. r*( 1 + -inverse(real(Suc n)))) \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S r\"\n  using LIMSEQ_inverse_real_of_nat_add_minus_mult by (simp add: LIMSEQ_NSLIMSEQ_iff [symmetric])\n\n\nsubsection \\<open>Convergence\\<close>\n\nlemma nslimI: \"X \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S L ==> nslim X = L\"\napply (simp add: nslim_def)\napply (blast intro: NSLIMSEQ_unique)\ndone\n\nlemma lim_nslim_iff: \"lim X = nslim X\"\nby (simp add: lim_def nslim_def LIMSEQ_NSLIMSEQ_iff)\n\nlemma NSconvergentD: \"NSconvergent X ==> \\<exists>L. (X \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S L)\"\nby (simp add: NSconvergent_def)\n\nlemma NSconvergentI: \"(X \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S L) ==> NSconvergent X\"\nby (auto simp add: NSconvergent_def)\n\nlemma convergent_NSconvergent_iff: \"convergent X = NSconvergent X\"\nby (simp add: convergent_def NSconvergent_def LIMSEQ_NSLIMSEQ_iff)\n\nlemma NSconvergent_NSLIMSEQ_iff: \"NSconvergent X = (X \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S nslim X)\"\nby (auto intro: theI NSLIMSEQ_unique simp add: NSconvergent_def nslim_def)\n\n\nsubsection \\<open>Bounded Monotonic Sequences\\<close>\n\nlemma NSBseqD: \"[| NSBseq X;  N: HNatInfinite |] ==> ( *f* X) N : HFinite\"\nby (simp add: NSBseq_def)\n\nlemma Standard_subset_HFinite: \"Standard \\<subseteq> HFinite\"\nunfolding Standard_def by auto\n\nlemma NSBseqD2: \"NSBseq X \\<Longrightarrow> ( *f* X) N \\<in> HFinite\"\napply (cases \"N \\<in> HNatInfinite\")\napply (erule (1) NSBseqD)\napply (rule subsetD [OF Standard_subset_HFinite])\napply (simp add: HNatInfinite_def Nats_eq_Standard)\ndone\n\nlemma NSBseqI: \"\\<forall>N \\<in> HNatInfinite. ( *f* X) N : HFinite ==> NSBseq X\"\nby (simp add: NSBseq_def)\n\ntext\\<open>The standard definition implies the nonstandard definition\\<close>\n\nlemma Bseq_NSBseq: \"Bseq X ==> NSBseq X\"\nproof (unfold NSBseq_def, safe)\n  assume X: \"Bseq X\"\n  fix N assume N: \"N \\<in> HNatInfinite\"\n  from BseqD [OF X] obtain K where \"\\<forall>n. norm (X n) \\<le> K\" by fast\n  hence \"\\<forall>N. hnorm (starfun X N) \\<le> star_of K\" by transfer\n  hence \"hnorm (starfun X N) \\<le> star_of K\" by simp\n  also have \"star_of K < star_of (K + 1)\" by simp\n  finally have \"\\<exists>x\\<in>Reals. hnorm (starfun X N) < x\" by (rule bexI, simp)\n  thus \"starfun X N \\<in> HFinite\" by (simp add: HFinite_def)\nqed\n\ntext\\<open>The nonstandard definition implies the standard definition\\<close>\n\nlemma SReal_less_omega: \"r \\<in> \\<real> \\<Longrightarrow> r < \\<omega>\"\napply (insert HInfinite_omega)\napply (simp add: HInfinite_def)\napply (simp add: order_less_imp_le)\ndone\n\nlemma NSBseq_Bseq: \"NSBseq X \\<Longrightarrow> Bseq X\"\nproof (rule ccontr)\n  let ?n = \"\\<lambda>K. LEAST n. K < norm (X n)\"\n  assume \"NSBseq X\"\n  hence finite: \"( *f* X) (( *f* ?n) \\<omega>) \\<in> HFinite\"\n    by (rule NSBseqD2)\n  assume \"\\<not> Bseq X\"\n  hence \"\\<forall>K>0. \\<exists>n. K < norm (X n)\"\n    by (simp add: Bseq_def linorder_not_le)\n  hence \"\\<forall>K>0. K < norm (X (?n K))\"\n    by (auto intro: LeastI_ex)\n  hence \"\\<forall>K>0. K < hnorm (( *f* X) (( *f* ?n) K))\"\n    by transfer\n  hence \"\\<omega> < hnorm (( *f* X) (( *f* ?n) \\<omega>))\"\n    by simp\n  hence \"\\<forall>r\\<in>\\<real>. r < hnorm (( *f* X) (( *f* ?n) \\<omega>))\"\n    by (simp add: order_less_trans [OF SReal_less_omega])\n  hence \"( *f* X) (( *f* ?n) \\<omega>) \\<in> HInfinite\"\n    by (simp add: HInfinite_def)\n  with finite show \"False\"\n    by (simp add: HFinite_HInfinite_iff)\nqed\n\ntext\\<open>Equivalence of nonstandard and standard definitions\n  for a bounded sequence\\<close>\nlemma Bseq_NSBseq_iff: \"(Bseq X) = (NSBseq X)\"\nby (blast intro!: NSBseq_Bseq Bseq_NSBseq)\n\ntext\\<open>A convergent sequence is bounded: \n Boundedness as a necessary condition for convergence. \n The nonstandard version has no existential, as usual\\<close>\n\nlemma NSconvergent_NSBseq: \"NSconvergent X ==> NSBseq X\"\napply (simp add: NSconvergent_def NSBseq_def NSLIMSEQ_def)\napply (blast intro: HFinite_star_of approx_sym approx_HFinite)\ndone\n\ntext\\<open>Standard Version: easily now proved using equivalence of NS and\n standard definitions\\<close>\n\nlemma convergent_Bseq: \"convergent X ==> Bseq (X::nat \\<Rightarrow> _::real_normed_vector)\"\nby (simp add: NSconvergent_NSBseq convergent_NSconvergent_iff Bseq_NSBseq_iff)\n\nsubsubsection\\<open>Upper Bounds and Lubs of Bounded Sequences\\<close>\n\nlemma NSBseq_isUb: \"NSBseq X ==> \\<exists>U::real. isUb UNIV {x. \\<exists>n. X n = x} U\"\nby (simp add: Bseq_NSBseq_iff [symmetric] Bseq_isUb)\n\nlemma NSBseq_isLub: \"NSBseq X ==> \\<exists>U::real. isLub UNIV {x. \\<exists>n. X n = x} U\"\nby (simp add: Bseq_NSBseq_iff [symmetric] Bseq_isLub)\n\nsubsubsection\\<open>A Bounded and Monotonic Sequence Converges\\<close>\n\ntext\\<open>The best of both worlds: Easier to prove this result as a standard\n   theorem and then use equivalence to \"transfer\" it into the\n   equivalent nonstandard form if needed!\\<close>\n\nlemma Bmonoseq_NSLIMSEQ: \"\\<forall>n \\<ge> m. X n = X m ==> \\<exists>L. (X \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S L)\"\nby (auto dest!: Bmonoseq_LIMSEQ simp add: LIMSEQ_NSLIMSEQ_iff)\n\nlemma NSBseq_mono_NSconvergent:\n     \"[| NSBseq X; \\<forall>m. \\<forall>n \\<ge> m. X m \\<le> X n |] ==> NSconvergent (X::nat=>real)\"\nby (auto intro: Bseq_mono_convergent \n         simp add: convergent_NSconvergent_iff [symmetric] \n                   Bseq_NSBseq_iff [symmetric])\n\n\nsubsection \\<open>Cauchy Sequences\\<close>\n\nlemma NSCauchyI:\n  \"(\\<And>M N. \\<lbrakk>M \\<in> HNatInfinite; N \\<in> HNatInfinite\\<rbrakk> \\<Longrightarrow> starfun X M \\<approx> starfun X N)\n   \\<Longrightarrow> NSCauchy X\"\nby (simp add: NSCauchy_def)\n\nlemma NSCauchyD:\n  \"\\<lbrakk>NSCauchy X; M \\<in> HNatInfinite; N \\<in> HNatInfinite\\<rbrakk>\n   \\<Longrightarrow> starfun X M \\<approx> starfun X N\"\nby (simp add: NSCauchy_def)\n\nsubsubsection\\<open>Equivalence Between NS and Standard\\<close>\n\nlemma Cauchy_NSCauchy:\n  assumes X: \"Cauchy X\" shows \"NSCauchy X\"\nproof (rule NSCauchyI)\n  fix M assume M: \"M \\<in> HNatInfinite\"\n  fix N assume N: \"N \\<in> HNatInfinite\"\n  have \"starfun X M - starfun X N \\<in> Infinitesimal\"\n  proof (rule InfinitesimalI2)\n    fix r :: real assume r: \"0 < r\"\n    from CauchyD [OF X r]\n    obtain k where \"\\<forall>m\\<ge>k. \\<forall>n\\<ge>k. norm (X m - X n) < r\" ..\n    hence \"\\<forall>m\\<ge>star_of k. \\<forall>n\\<ge>star_of k.\n           hnorm (starfun X m - starfun X n) < star_of r\"\n      by transfer\n    thus \"hnorm (starfun X M - starfun X N) < star_of r\"\n      using M N by (simp add: star_of_le_HNatInfinite)\n  qed\n  thus \"starfun X M \\<approx> starfun X N\"\n    by (unfold approx_def)\nqed\n\nlemma NSCauchy_Cauchy:\n  assumes X: \"NSCauchy X\" shows \"Cauchy X\"\nproof (rule CauchyI)\n  fix r::real assume r: \"0 < r\"\n  have \"\\<exists>k. \\<forall>m\\<ge>k. \\<forall>n\\<ge>k. hnorm (starfun X m - starfun X n) < star_of r\"\n  proof (intro exI allI impI)\n    fix M assume \"whn \\<le> M\"\n    with HNatInfinite_whn have M: \"M \\<in> HNatInfinite\"\n      by (rule HNatInfinite_upward_closed)\n    fix N assume \"whn \\<le> N\"\n    with HNatInfinite_whn have N: \"N \\<in> HNatInfinite\"\n      by (rule HNatInfinite_upward_closed)\n    from X M N have \"starfun X M \\<approx> starfun X N\"\n      by (rule NSCauchyD)\n    hence \"starfun X M - starfun X N \\<in> Infinitesimal\"\n      by (unfold approx_def)\n    thus \"hnorm (starfun X M - starfun X N) < star_of r\"\n      using r by (rule InfinitesimalD2)\n  qed\n  thus \"\\<exists>k. \\<forall>m\\<ge>k. \\<forall>n\\<ge>k. norm (X m - X n) < r\"\n    by transfer\nqed\n\ntheorem NSCauchy_Cauchy_iff: \"NSCauchy X = Cauchy X\"\nby (blast intro!: NSCauchy_Cauchy Cauchy_NSCauchy)\n\nsubsubsection \\<open>Cauchy Sequences are Bounded\\<close>\n\ntext\\<open>A Cauchy sequence is bounded -- nonstandard version\\<close>\n\nlemma NSCauchy_NSBseq: \"NSCauchy X ==> NSBseq X\"\nby (simp add: Cauchy_Bseq Bseq_NSBseq_iff [symmetric] NSCauchy_Cauchy_iff)\n\nsubsubsection \\<open>Cauchy Sequences are Convergent\\<close>\n\ntext\\<open>Equivalence of Cauchy criterion and convergence:\n  We will prove this using our NS formulation which provides a\n  much easier proof than using the standard definition. We do not\n  need to use properties of subsequences such as boundedness,\n  monotonicity etc... Compare with Harrison's corresponding proof\n  in HOL which is much longer and more complicated. Of course, we do\n  not have problems which he encountered with guessing the right\n  instantiations for his 'espsilon-delta' proof(s) in this case\n  since the NS formulations do not involve existential quantifiers.\\<close>\n\nlemma NSconvergent_NSCauchy: \"NSconvergent X \\<Longrightarrow> NSCauchy X\"\napply (simp add: NSconvergent_def NSLIMSEQ_def NSCauchy_def, safe)\napply (auto intro: approx_trans2)\ndone\n\nlemma real_NSCauchy_NSconvergent:\n  fixes X :: \"nat \\<Rightarrow> real\"\n  shows \"NSCauchy X \\<Longrightarrow> NSconvergent X\"\napply (simp add: NSconvergent_def NSLIMSEQ_def)\napply (frule NSCauchy_NSBseq)\napply (simp add: NSBseq_def NSCauchy_def)\napply (drule HNatInfinite_whn [THEN [2] bspec])\napply (drule HNatInfinite_whn [THEN [2] bspec])\napply (auto dest!: st_part_Ex simp add: SReal_iff)\napply (blast intro: approx_trans3)\ndone\n\nlemma NSCauchy_NSconvergent:\n  fixes X :: \"nat \\<Rightarrow> 'a::banach\"\n  shows \"NSCauchy X \\<Longrightarrow> NSconvergent X\"\napply (drule NSCauchy_Cauchy [THEN Cauchy_convergent])\napply (erule convergent_NSconvergent_iff [THEN iffD1])\ndone\n\nlemma NSCauchy_NSconvergent_iff:\n  fixes X :: \"nat \\<Rightarrow> 'a::banach\"\n  shows \"NSCauchy X = NSconvergent X\"\nby (fast intro: NSCauchy_NSconvergent NSconvergent_NSCauchy)\n\n\nsubsection \\<open>Power Sequences\\<close>\n\ntext\\<open>The sequence @{term \"x^n\"} tends to 0 if @{term \"0\\<le>x\"} and @{term\n\"x<1\"}.  Proof will use (NS) Cauchy equivalence for convergence and\n  also fact that bounded and monotonic sequence converges.\\<close>\n\ntext\\<open>We now use NS criterion to bring proof of theorem through\\<close>\n\nlemma NSLIMSEQ_realpow_zero:\n  \"[| 0 \\<le> (x::real); x < 1 |] ==> (%n. x ^ n) \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S 0\"\napply (simp add: NSLIMSEQ_def)\napply (auto dest!: convergent_realpow simp add: convergent_NSconvergent_iff)\napply (frule NSconvergentD)\napply (auto simp add: NSLIMSEQ_def NSCauchy_NSconvergent_iff [symmetric] NSCauchy_def starfun_pow)\napply (frule HNatInfinite_add_one)\napply (drule bspec, assumption)\napply (drule bspec, assumption)\napply (drule_tac x = \"N + (1::hypnat) \" in bspec, assumption)\napply (simp add: hyperpow_add)\napply (drule approx_mult_subst_star_of, assumption)\napply (drule approx_trans3, assumption)\napply (auto simp del: star_of_mult simp add: star_of_mult [symmetric])\ndone\n\nlemma NSLIMSEQ_rabs_realpow_zero: \"\\<bar>c\\<bar> < (1::real) ==> (%n. \\<bar>c\\<bar> ^ n) \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S 0\"\nby (simp add: LIMSEQ_rabs_realpow_zero LIMSEQ_NSLIMSEQ_iff [symmetric])\n\nlemma NSLIMSEQ_rabs_realpow_zero2: \"\\<bar>c\\<bar> < (1::real) ==> (%n. c ^ n) \\<longlonglongrightarrow>\\<^sub>N\\<^sub>S 0\"\nby (simp add: LIMSEQ_rabs_realpow_zero2 LIMSEQ_NSLIMSEQ_iff [symmetric])\n\n(***---------------------------------------------------------------\n    Theorems proved by Harrison in HOL that we do not need\n    in order to prove equivalence between Cauchy criterion\n    and convergence:\n -- Show that every sequence contains a monotonic subsequence\nGoal \"\\<exists>f. subseq f & monoseq (%n. s (f n))\"\n -- Show that a subsequence of a bounded sequence is bounded\nGoal \"Bseq X ==> Bseq (%n. X (f n))\";\n -- Show we can take subsequential terms arbitrarily far\n    up a sequence\nGoal \"subseq f ==> n \\<le> f(n)\";\nGoal \"subseq f ==> \\<exists>n. N1 \\<le> n & N2 \\<le> f(n)\";\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/Nonstandard_Analysis/HSEQ.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8723473813156294, "lm_q2_score": 0.8056321913146127, "lm_q1q2_score": 0.7027911323968745}}
{"text": "(*  Title:      HOL/Fields.thy\n    Author:     Gertrud Bauer\n    Author:     Steven Obua\n    Author:     Tobias Nipkow\n    Author:     Lawrence C Paulson\n    Author:     Markus Wenzel\n    Author:     Jeremy Avigad\n*)\n\nsection \\<open>Fields\\<close>\n\ntheory Fields\nimports Nat\nbegin\n\ncontext idom\nbegin\n\nlemma inj_mult_left [simp]: \\<open>inj ((*) a) \\<longleftrightarrow> a \\<noteq> 0\\<close> (is \\<open>?P \\<longleftrightarrow> ?Q\\<close>)\nproof\n  assume ?P\n  show ?Q\n  proof\n    assume \\<open>a = 0\\<close>\n    with \\<open>?P\\<close> have \"inj ((*) 0)\"\n      by simp\n    moreover have \"0 * 0 = 0 * 1\"\n      by simp\n    ultimately have \"0 = 1\"\n      by (rule injD)\n    then show False\n      by simp\n  qed\nnext\n  assume ?Q then show ?P\n    by (auto intro: injI)\nqed\n\nend\n\n\nsubsection \\<open>Division rings\\<close>\n\ntext \\<open>\n  A division ring is like a field, but without the commutativity requirement.\n\\<close>\n\nclass inverse = divide +\n  fixes inverse :: \"'a \\<Rightarrow> 'a\"\nbegin\n  \nabbreviation inverse_divide :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a\"  (infixl \"'/\" 70)\nwhere\n  \"inverse_divide \\<equiv> divide\"\n\nend\n\ntext \\<open>Setup for linear arithmetic prover\\<close>\n\nML_file \\<open>~~/src/Provers/Arith/fast_lin_arith.ML\\<close>\nML_file \\<open>Tools/lin_arith.ML\\<close>\nsetup \\<open>Lin_Arith.global_setup\\<close>\ndeclaration \\<open>K (\n  Lin_Arith.init_arith_data\n  #> Lin_Arith.add_discrete_type \\<^type_name>\\<open>nat\\<close>\n  #> Lin_Arith.add_lessD @{thm Suc_leI}\n  #> Lin_Arith.add_simps @{thms simp_thms ring_distribs if_True if_False\n      minus_diff_eq\n      add_0_left add_0_right order_less_irrefl\n      zero_neq_one zero_less_one zero_le_one\n      zero_neq_one [THEN not_sym] not_one_le_zero not_one_less_zero\n      add_Suc add_Suc_right nat.inject\n      Suc_le_mono Suc_less_eq Zero_not_Suc\n      Suc_not_Zero le_0_eq One_nat_def}\n  #> Lin_Arith.add_simprocs [\\<^simproc>\\<open>group_cancel_add\\<close>, \\<^simproc>\\<open>group_cancel_diff\\<close>,\n      \\<^simproc>\\<open>group_cancel_eq\\<close>, \\<^simproc>\\<open>group_cancel_le\\<close>,\n      \\<^simproc>\\<open>group_cancel_less\\<close>,\n      \\<^simproc>\\<open>nateq_cancel_sums\\<close>,\\<^simproc>\\<open>natless_cancel_sums\\<close>,\n      \\<^simproc>\\<open>natle_cancel_sums\\<close>])\\<close>\n\nsimproc_setup fast_arith_nat (\"(m::nat) < n\" | \"(m::nat) \\<le> n\" | \"(m::nat) = n\") =\n  \\<open>K Lin_Arith.simproc\\<close> \\<comment> \\<open>Because of this simproc, the arithmetic solver is\n   really only useful to detect inconsistencies among the premises for subgoals which are\n   \\<^emph>\\<open>not\\<close> themselves (in)equalities, because the latter activate\n   \\<^text>\\<open>fast_nat_arith_simproc\\<close> anyway. However, it seems cheaper to activate the\n   solver all the time rather than add the additional check.\\<close>\n\nlemmas [arith_split] = nat_diff_split split_min split_max\n\ntext\\<open>Lemmas \\<open>divide_simps\\<close> move division to the outside and eliminates them on (in)equalities.\\<close>\n\nnamed_theorems divide_simps \"rewrite rules to eliminate divisions\"\n\nclass division_ring = ring_1 + inverse +\n  assumes left_inverse [simp]:  \"a \\<noteq> 0 \\<Longrightarrow> inverse a * a = 1\"\n  assumes right_inverse [simp]: \"a \\<noteq> 0 \\<Longrightarrow> a * inverse a = 1\"\n  assumes divide_inverse: \"a / b = a * inverse b\"\n  assumes inverse_zero [simp]: \"inverse 0 = 0\"\nbegin\n\nsubclass ring_1_no_zero_divisors\nproof\n  fix a b :: 'a\n  assume a: \"a \\<noteq> 0\" and b: \"b \\<noteq> 0\"\n  show \"a * b \\<noteq> 0\"\n  proof\n    assume ab: \"a * b = 0\"\n    hence \"0 = inverse a * (a * b) * inverse b\" by simp\n    also have \"\\<dots> = (inverse a * a) * (b * inverse b)\"\n      by (simp only: mult.assoc)\n    also have \"\\<dots> = 1\" using a b by simp\n    finally show False by simp\n  qed\nqed\n\nlemma nonzero_imp_inverse_nonzero:\n  \"a \\<noteq> 0 \\<Longrightarrow> inverse a \\<noteq> 0\"\nproof\n  assume ianz: \"inverse a = 0\"\n  assume \"a \\<noteq> 0\"\n  hence \"1 = a * inverse a\" by simp\n  also have \"... = 0\" by (simp add: ianz)\n  finally have \"1 = 0\" .\n  thus False by (simp add: eq_commute)\nqed\n\nlemma inverse_zero_imp_zero:\n  assumes \"inverse a = 0\" shows \"a = 0\"\nproof (rule ccontr)\n  assume \"a \\<noteq> 0\"\n  then have \"inverse a \\<noteq> 0\"\n    by (simp add: nonzero_imp_inverse_nonzero)\n  with assms show False\n    by auto\nqed\n\nlemma inverse_unique:\n  assumes ab: \"a * b = 1\"\n  shows \"inverse a = b\"\nproof -\n  have \"a \\<noteq> 0\" using ab by (cases \"a = 0\") simp_all\n  moreover have \"inverse a * (a * b) = inverse a\" by (simp add: ab)\n  ultimately show ?thesis by (simp add: mult.assoc [symmetric])\nqed\n\nlemma nonzero_inverse_minus_eq:\n  \"a \\<noteq> 0 \\<Longrightarrow> inverse (- a) = - inverse a\"\nby (rule inverse_unique) simp\n\nlemma nonzero_inverse_inverse_eq:\n  \"a \\<noteq> 0 \\<Longrightarrow> inverse (inverse a) = a\"\nby (rule inverse_unique) simp\n\nlemma nonzero_inverse_eq_imp_eq:\n  assumes \"inverse a = inverse b\" and \"a \\<noteq> 0\" and \"b \\<noteq> 0\"\n  shows \"a = b\"\nproof -\n  from \\<open>inverse a = inverse b\\<close>\n  have \"inverse (inverse a) = inverse (inverse b)\" by (rule arg_cong)\n  with \\<open>a \\<noteq> 0\\<close> and \\<open>b \\<noteq> 0\\<close> show \"a = b\"\n    by (simp add: nonzero_inverse_inverse_eq)\nqed\n\nlemma inverse_1 [simp]: \"inverse 1 = 1\"\nby (rule inverse_unique) simp\n\nlemma nonzero_inverse_mult_distrib:\n  assumes \"a \\<noteq> 0\" and \"b \\<noteq> 0\"\n  shows \"inverse (a * b) = inverse b * inverse a\"\nproof -\n  have \"a * (b * inverse b) * inverse a = 1\" using assms by simp\n  hence \"a * b * (inverse b * inverse a) = 1\" by (simp only: mult.assoc)\n  thus ?thesis by (rule inverse_unique)\nqed\n\nlemma division_ring_inverse_add:\n  \"a \\<noteq> 0 \\<Longrightarrow> b \\<noteq> 0 \\<Longrightarrow> inverse a + inverse b = inverse a * (a + b) * inverse b\"\nby (simp add: algebra_simps)\n\nlemma division_ring_inverse_diff:\n  \"a \\<noteq> 0 \\<Longrightarrow> b \\<noteq> 0 \\<Longrightarrow> inverse a - inverse b = inverse a * (b - a) * inverse b\"\nby (simp add: algebra_simps)\n\nlemma right_inverse_eq: \"b \\<noteq> 0 \\<Longrightarrow> a / b = 1 \\<longleftrightarrow> a = b\"\nproof\n  assume neq: \"b \\<noteq> 0\"\n  {\n    hence \"a = (a / b) * b\" by (simp add: divide_inverse mult.assoc)\n    also assume \"a / b = 1\"\n    finally show \"a = b\" by simp\n  next\n    assume \"a = b\"\n    with neq show \"a / b = 1\" by (simp add: divide_inverse)\n  }\nqed\n\nlemma nonzero_inverse_eq_divide: \"a \\<noteq> 0 \\<Longrightarrow> inverse a = 1 / a\"\nby (simp add: divide_inverse)\n\nlemma divide_self [simp]: \"a \\<noteq> 0 \\<Longrightarrow> a / a = 1\"\nby (simp add: divide_inverse)\n\nlemma inverse_eq_divide [field_simps, field_split_simps, divide_simps]: \"inverse a = 1 / a\"\nby (simp add: divide_inverse)\n\nlemma add_divide_distrib: \"(a+b) / c = a/c + b/c\"\nby (simp add: divide_inverse algebra_simps)\n\nlemma times_divide_eq_right [simp]: \"a * (b / c) = (a * b) / c\"\n  by (simp add: divide_inverse mult.assoc)\n\nlemma minus_divide_left: \"- (a / b) = (-a) / b\"\n  by (simp add: divide_inverse)\n\nlemma nonzero_minus_divide_right: \"b \\<noteq> 0 \\<Longrightarrow> - (a / b) = a / (- b)\"\n  by (simp add: divide_inverse nonzero_inverse_minus_eq)\n\nlemma nonzero_minus_divide_divide: \"b \\<noteq> 0 \\<Longrightarrow> (-a) / (-b) = a / b\"\n  by (simp add: divide_inverse nonzero_inverse_minus_eq)\n\nlemma divide_minus_left [simp]: \"(-a) / b = - (a / b)\"\n  by (simp add: divide_inverse)\n\nlemma diff_divide_distrib: \"(a - b) / c = a / c - b / c\"\n  using add_divide_distrib [of a \"- b\" c] by simp\n\nlemma nonzero_eq_divide_eq [field_simps]: \"c \\<noteq> 0 \\<Longrightarrow> a = b / c \\<longleftrightarrow> a * c = b\"\nproof -\n  assume [simp]: \"c \\<noteq> 0\"\n  have \"a = b / c \\<longleftrightarrow> a * c = (b / c) * c\" by simp\n  also have \"... \\<longleftrightarrow> a * c = b\" by (simp add: divide_inverse mult.assoc)\n  finally show ?thesis .\nqed\n\nlemma nonzero_divide_eq_eq [field_simps]: \"c \\<noteq> 0 \\<Longrightarrow> b / c = a \\<longleftrightarrow> b = a * c\"\nproof -\n  assume [simp]: \"c \\<noteq> 0\"\n  have \"b / c = a \\<longleftrightarrow> (b / c) * c = a * c\" by simp\n  also have \"... \\<longleftrightarrow> b = a * c\" by (simp add: divide_inverse mult.assoc)\n  finally show ?thesis .\nqed\n\nlemma nonzero_neg_divide_eq_eq [field_simps]: \"b \\<noteq> 0 \\<Longrightarrow> - (a / b) = c \\<longleftrightarrow> - a = c * b\"\n  using nonzero_divide_eq_eq[of b \"-a\" c] by simp\n\nlemma nonzero_neg_divide_eq_eq2 [field_simps]: \"b \\<noteq> 0 \\<Longrightarrow> c = - (a / b) \\<longleftrightarrow> c * b = - a\"\n  using nonzero_neg_divide_eq_eq[of b a c] by auto\n\nlemma divide_eq_imp: \"c \\<noteq> 0 \\<Longrightarrow> b = a * c \\<Longrightarrow> b / c = a\"\n  by (simp add: divide_inverse mult.assoc)\n\nlemma eq_divide_imp: \"c \\<noteq> 0 \\<Longrightarrow> a * c = b \\<Longrightarrow> a = b / c\"\n  by (drule sym) (simp add: divide_inverse mult.assoc)\n\nlemma add_divide_eq_iff [field_simps]:\n  \"z \\<noteq> 0 \\<Longrightarrow> x + y / z = (x * z + y) / z\"\n  by (simp add: add_divide_distrib nonzero_eq_divide_eq)\n\nlemma divide_add_eq_iff [field_simps]:\n  \"z \\<noteq> 0 \\<Longrightarrow> x / z + y = (x + y * z) / z\"\n  by (simp add: add_divide_distrib nonzero_eq_divide_eq)\n\nlemma diff_divide_eq_iff [field_simps]:\n  \"z \\<noteq> 0 \\<Longrightarrow> x - y / z = (x * z - y) / z\"\n  by (simp add: diff_divide_distrib nonzero_eq_divide_eq eq_diff_eq)\n\nlemma minus_divide_add_eq_iff [field_simps]:\n  \"z \\<noteq> 0 \\<Longrightarrow> - (x / z) + y = (- x + y * z) / z\"\n  by (simp add: add_divide_distrib diff_divide_eq_iff)\n\nlemma divide_diff_eq_iff [field_simps]:\n  \"z \\<noteq> 0 \\<Longrightarrow> x / z - y = (x - y * z) / z\"\n  by (simp add: field_simps)\n\nlemma minus_divide_diff_eq_iff [field_simps]:\n  \"z \\<noteq> 0 \\<Longrightarrow> - (x / z) - y = (- x - y * z) / z\"\n  by (simp add: divide_diff_eq_iff[symmetric])\n\nlemma division_ring_divide_zero [simp]:\n  \"a / 0 = 0\"\n  by (simp add: divide_inverse)\n\nlemma divide_self_if [simp]:\n  \"a / a = (if a = 0 then 0 else 1)\"\n  by simp\n\nlemma inverse_nonzero_iff_nonzero [simp]:\n  \"inverse a = 0 \\<longleftrightarrow> a = 0\"\n  by rule (fact inverse_zero_imp_zero, simp)\n\nlemma inverse_minus_eq [simp]:\n  \"inverse (- a) = - inverse a\"\nproof cases\n  assume \"a=0\" thus ?thesis by simp\nnext\n  assume \"a\\<noteq>0\"\n  thus ?thesis by (simp add: nonzero_inverse_minus_eq)\nqed\n\nlemma inverse_inverse_eq [simp]:\n  \"inverse (inverse a) = a\"\nproof cases\n  assume \"a=0\" thus ?thesis by simp\nnext\n  assume \"a\\<noteq>0\"\n  thus ?thesis by (simp add: nonzero_inverse_inverse_eq)\nqed\n\nlemma inverse_eq_imp_eq:\n  \"inverse a = inverse b \\<Longrightarrow> a = b\"\n  by (drule arg_cong [where f=\"inverse\"], simp)\n\nlemma inverse_eq_iff_eq [simp]:\n  \"inverse a = inverse b \\<longleftrightarrow> a = b\"\n  by (force dest!: inverse_eq_imp_eq)\n\nlemma mult_commute_imp_mult_inverse_commute:\n  assumes \"y * x = x * y\"\n  shows   \"inverse y * x = x * inverse y\"\nproof (cases \"y=0\")\n  case False\n  hence \"x * inverse y = inverse y * y * x * inverse y\"\n    by simp\n  also have \"\\<dots> = inverse y * (x * y * inverse y)\"\n    by (simp add: mult.assoc assms)\n  finally show ?thesis by (simp add: mult.assoc False)\nqed simp\n\nlemmas mult_inverse_of_nat_commute =\n  mult_commute_imp_mult_inverse_commute[OF mult_of_nat_commute]\n\nlemma divide_divide_eq_left':\n  \"(a / b) / c = a / (c * b)\"\n  by (cases \"b = 0 \\<or> c = 0\")\n     (auto simp: divide_inverse mult.assoc nonzero_inverse_mult_distrib)\n\nlemma add_divide_eq_if_simps [field_split_simps, divide_simps]:\n    \"a + b / z = (if z = 0 then a else (a * z + b) / z)\"\n    \"a / z + b = (if z = 0 then b else (a + b * z) / z)\"\n    \"- (a / z) + b = (if z = 0 then b else (-a + b * z) / z)\"\n    \"a - b / z = (if z = 0 then a else (a * z - b) / z)\"\n    \"a / z - b = (if z = 0 then -b else (a - b * z) / z)\"\n    \"- (a / z) - b = (if z = 0 then -b else (- a - b * z) / z)\"\n  by (simp_all add: add_divide_eq_iff divide_add_eq_iff diff_divide_eq_iff divide_diff_eq_iff\n      minus_divide_diff_eq_iff)\n\nlemma [field_split_simps, divide_simps]:\n  shows divide_eq_eq: \"b / c = a \\<longleftrightarrow> (if c \\<noteq> 0 then b = a * c else a = 0)\"\n    and eq_divide_eq: \"a = b / c \\<longleftrightarrow> (if c \\<noteq> 0 then a * c = b else a = 0)\"\n    and minus_divide_eq_eq: \"- (b / c) = a \\<longleftrightarrow> (if c \\<noteq> 0 then - b = a * c else a = 0)\"\n    and eq_minus_divide_eq: \"a = - (b / c) \\<longleftrightarrow> (if c \\<noteq> 0 then a * c = - b else a = 0)\"\n  by (auto simp add:  field_simps)\n\nend\n\nsubsection \\<open>Fields\\<close>\n\nclass field = comm_ring_1 + inverse +\n  assumes field_inverse: \"a \\<noteq> 0 \\<Longrightarrow> inverse a * a = 1\"\n  assumes field_divide_inverse: \"a / b = a * inverse b\"\n  assumes field_inverse_zero: \"inverse 0 = 0\"\nbegin\n\nsubclass division_ring\nproof\n  fix a :: 'a\n  assume \"a \\<noteq> 0\"\n  thus \"inverse a * a = 1\" by (rule field_inverse)\n  thus \"a * inverse a = 1\" by (simp only: mult.commute)\nnext\n  fix a b :: 'a\n  show \"a / b = a * inverse b\" by (rule field_divide_inverse)\nnext\n  show \"inverse 0 = 0\"\n    by (fact field_inverse_zero) \nqed\n\nsubclass idom_divide\nproof\n  fix b a\n  assume \"b \\<noteq> 0\"\n  then show \"a * b / b = a\"\n    by (simp add: divide_inverse ac_simps)\nnext\n  fix a\n  show \"a / 0 = 0\"\n    by (simp add: divide_inverse)\nqed\n\ntext\\<open>There is no slick version using division by zero.\\<close>\nlemma inverse_add:\n  \"a \\<noteq> 0 \\<Longrightarrow> b \\<noteq> 0 \\<Longrightarrow> inverse a + inverse b = (a + b) * inverse a * inverse b\"\n  by (simp add: division_ring_inverse_add ac_simps)\n\nlemma nonzero_mult_divide_mult_cancel_left [simp]:\n  assumes [simp]: \"c \\<noteq> 0\"\n  shows \"(c * a) / (c * b) = a / b\"\nproof (cases \"b = 0\")\n  case True then show ?thesis by simp\nnext\n  case False\n  then have \"(c*a)/(c*b) = c * a * (inverse b * inverse c)\"\n    by (simp add: divide_inverse nonzero_inverse_mult_distrib)\n  also have \"... =  a * inverse b * (inverse c * c)\"\n    by (simp only: ac_simps)\n  also have \"... =  a * inverse b\" by simp\n    finally show ?thesis by (simp add: divide_inverse)\nqed\n\nlemma nonzero_mult_divide_mult_cancel_right [simp]:\n  \"c \\<noteq> 0 \\<Longrightarrow> (a * c) / (b * c) = a / b\"\n  using nonzero_mult_divide_mult_cancel_left [of c a b] by (simp add: ac_simps)\n\nlemma times_divide_eq_left [simp]: \"(b / c) * a = (b * a) / c\"\n  by (simp add: divide_inverse ac_simps)\n\nlemma divide_inverse_commute: \"a / b = inverse b * a\"\n  by (simp add: divide_inverse mult.commute)\n\nlemma add_frac_eq:\n  assumes \"y \\<noteq> 0\" and \"z \\<noteq> 0\"\n  shows \"x / y + w / z = (x * z + w * y) / (y * z)\"\nproof -\n  have \"x / y + w / z = (x * z) / (y * z) + (y * w) / (y * z)\"\n    using assms by simp\n  also have \"\\<dots> = (x * z + y * w) / (y * z)\"\n    by (simp only: add_divide_distrib)\n  finally show ?thesis\n    by (simp only: mult.commute)\nqed\n\ntext\\<open>Special Cancellation Simprules for Division\\<close>\n\nlemma nonzero_divide_mult_cancel_right [simp]:\n  \"b \\<noteq> 0 \\<Longrightarrow> b / (a * b) = 1 / a\"\n  using nonzero_mult_divide_mult_cancel_right [of b 1 a] by simp\n\nlemma nonzero_divide_mult_cancel_left [simp]:\n  \"a \\<noteq> 0 \\<Longrightarrow> a / (a * b) = 1 / b\"\n  using nonzero_mult_divide_mult_cancel_left [of a 1 b] by simp\n\nlemma nonzero_mult_divide_mult_cancel_left2 [simp]:\n  \"c \\<noteq> 0 \\<Longrightarrow> (c * a) / (b * c) = a / b\"\n  using nonzero_mult_divide_mult_cancel_left [of c a b] by (simp add: ac_simps)\n\nlemma nonzero_mult_divide_mult_cancel_right2 [simp]:\n  \"c \\<noteq> 0 \\<Longrightarrow> (a * c) / (c * b) = a / b\"\n  using nonzero_mult_divide_mult_cancel_right [of b c a] by (simp add: ac_simps)\n\nlemma diff_frac_eq:\n  \"y \\<noteq> 0 \\<Longrightarrow> z \\<noteq> 0 \\<Longrightarrow> x / y - w / z = (x * z - w * y) / (y * z)\"\n  by (simp add: field_simps)\n\nlemma frac_eq_eq:\n  \"y \\<noteq> 0 \\<Longrightarrow> z \\<noteq> 0 \\<Longrightarrow> (x / y = w / z) = (x * z = w * y)\"\n  by (simp add: field_simps)\n\nlemma divide_minus1 [simp]: \"x / - 1 = - x\"\n  using nonzero_minus_divide_right [of \"1\" x] by simp\n\ntext\\<open>This version builds in division by zero while also re-orienting\n      the right-hand side.\\<close>\nlemma inverse_mult_distrib [simp]:\n  \"inverse (a * b) = inverse a * inverse b\"\nproof cases\n  assume \"a \\<noteq> 0 \\<and> b \\<noteq> 0\"\n  thus ?thesis by (simp add: nonzero_inverse_mult_distrib ac_simps)\nnext\n  assume \"\\<not> (a \\<noteq> 0 \\<and> b \\<noteq> 0)\"\n  thus ?thesis by force\nqed\n\nlemma inverse_divide [simp]:\n  \"inverse (a / b) = b / a\"\n  by (simp add: divide_inverse mult.commute)\n\n\ntext \\<open>Calculations with fractions\\<close>\n\ntext\\<open>There is a whole bunch of simp-rules just for class \\<open>field\\<close> but none for class \\<open>field\\<close> and \\<open>nonzero_divides\\<close>\nbecause the latter are covered by a simproc.\\<close>\n\nlemmas mult_divide_mult_cancel_left = nonzero_mult_divide_mult_cancel_left\n\nlemmas mult_divide_mult_cancel_right = nonzero_mult_divide_mult_cancel_right\n\nlemma divide_divide_eq_right [simp]:\n  \"a / (b / c) = (a * c) / b\"\n  by (simp add: divide_inverse ac_simps)\n\nlemma divide_divide_eq_left [simp]:\n  \"(a / b) / c = a / (b * c)\"\n  by (simp add: divide_inverse mult.assoc)\n\nlemma divide_divide_times_eq:\n  \"(x / y) / (z / w) = (x * w) / (y * z)\"\n  by simp\n\ntext \\<open>Special Cancellation Simprules for Division\\<close>\n\nlemma mult_divide_mult_cancel_left_if [simp]:\n  shows \"(c * a) / (c * b) = (if c = 0 then 0 else a / b)\"\n  by simp\n\n\ntext \\<open>Division and Unary Minus\\<close>\n\nlemma minus_divide_right:\n  \"- (a / b) = a / - b\"\n  by (simp add: divide_inverse)\n\nlemma divide_minus_right [simp]:\n  \"a / - b = - (a / b)\"\n  by (simp add: divide_inverse)\n\nlemma minus_divide_divide:\n  \"(- a) / (- b) = a / b\"\n  by (cases \"b=0\") (simp_all add: nonzero_minus_divide_divide)\n\nlemma inverse_eq_1_iff [simp]:\n  \"inverse x = 1 \\<longleftrightarrow> x = 1\"\n  by (insert inverse_eq_iff_eq [of x 1], simp)\n\nlemma divide_eq_0_iff [simp]:\n  \"a / b = 0 \\<longleftrightarrow> a = 0 \\<or> b = 0\"\n  by (simp add: divide_inverse)\n\nlemma divide_cancel_right [simp]:\n  \"a / c = b / c \\<longleftrightarrow> c = 0 \\<or> a = b\"\n  by (cases \"c=0\") (simp_all add: divide_inverse)\n\nlemma divide_cancel_left [simp]:\n  \"c / a = c / b \\<longleftrightarrow> c = 0 \\<or> a = b\"\n  by (cases \"c=0\") (simp_all add: divide_inverse)\n\nlemma divide_eq_1_iff [simp]:\n  \"a / b = 1 \\<longleftrightarrow> b \\<noteq> 0 \\<and> a = b\"\n  by (cases \"b=0\") (simp_all add: right_inverse_eq)\n\nlemma one_eq_divide_iff [simp]:\n  \"1 = a / b \\<longleftrightarrow> b \\<noteq> 0 \\<and> a = b\"\n  by (simp add: eq_commute [of 1])\n\nlemma divide_eq_minus_1_iff:\n   \"(a / b = - 1) \\<longleftrightarrow> b \\<noteq> 0 \\<and> a = - b\"\nusing divide_eq_1_iff by fastforce\n\nlemma times_divide_times_eq:\n  \"(x / y) * (z / w) = (x * z) / (y * w)\"\n  by simp\n\nlemma add_frac_num:\n  \"y \\<noteq> 0 \\<Longrightarrow> x / y + z = (x + z * y) / y\"\n  by (simp add: add_divide_distrib)\n\nlemma add_num_frac:\n  \"y \\<noteq> 0 \\<Longrightarrow> z + x / y = (x + z * y) / y\"\n  by (simp add: add_divide_distrib add.commute)\n\nlemma dvd_field_iff:\n  \"a dvd b \\<longleftrightarrow> (a = 0 \\<longrightarrow> b = 0)\"\nproof (cases \"a = 0\")\n  case False\n  then have \"b = a * (b / a)\"\n    by (simp add: field_simps)\n  then have \"a dvd b\" ..\n  with False show ?thesis\n    by simp\nqed simp\n\nlemma inj_divide_right [simp]:\n  \"inj (\\<lambda>b. b / a) \\<longleftrightarrow> a \\<noteq> 0\"\nproof -\n  have \"(\\<lambda>b. b / a) = (*) (inverse a)\"\n    by (simp add: field_simps fun_eq_iff)\n  then have \"inj (\\<lambda>y. y / a) \\<longleftrightarrow> inj ((*) (inverse a))\"\n    by simp\n  also have \"\\<dots> \\<longleftrightarrow> inverse a \\<noteq> 0\"\n    by simp\n  also have \"\\<dots> \\<longleftrightarrow> a \\<noteq> 0\"\n    by simp\n  finally show ?thesis\n    by simp\nqed\n\nend\n\nclass field_char_0 = field + ring_char_0\n\n\nsubsection \\<open>Ordered fields\\<close>\n\nclass field_abs_sgn = field + idom_abs_sgn\nbegin\n\nlemma sgn_inverse [simp]:\n  \"sgn (inverse a) = inverse (sgn a)\"\nproof (cases \"a = 0\")\n  case True then show ?thesis by simp\nnext\n  case False\n  then have \"a * inverse a = 1\"\n    by simp\n  then have \"sgn (a * inverse a) = sgn 1\"\n    by simp\n  then have \"sgn a * sgn (inverse a) = 1\"\n    by (simp add: sgn_mult)\n  then have \"inverse (sgn a) * (sgn a * sgn (inverse a)) = inverse (sgn a) * 1\"\n    by simp\n  then have \"(inverse (sgn a) * sgn a) * sgn (inverse a) = inverse (sgn a)\"\n    by (simp add: ac_simps)\n  with False show ?thesis\n    by (simp add: sgn_eq_0_iff)\nqed\n\nlemma abs_inverse [simp]:\n  \"\\<bar>inverse a\\<bar> = inverse \\<bar>a\\<bar>\"\nproof -\n  from sgn_mult_abs [of \"inverse a\"] sgn_mult_abs [of a]\n  have \"inverse (sgn a) * \\<bar>inverse a\\<bar> = inverse (sgn a * \\<bar>a\\<bar>)\"\n    by simp\n  then show ?thesis by (auto simp add: sgn_eq_0_iff)\nqed\n    \nlemma sgn_divide [simp]:\n  \"sgn (a / b) = sgn a / sgn b\"\n  unfolding divide_inverse sgn_mult by simp\n\nlemma abs_divide [simp]:\n  \"\\<bar>a / b\\<bar> = \\<bar>a\\<bar> / \\<bar>b\\<bar>\"\n  unfolding divide_inverse abs_mult by simp\n  \nend\n\nclass linordered_field = field + linordered_idom\nbegin\n\nlemma positive_imp_inverse_positive:\n  assumes a_gt_0: \"0 < a\"\n  shows \"0 < inverse a\"\nproof -\n  have \"0 < a * inverse a\"\n    by (simp add: a_gt_0 [THEN less_imp_not_eq2])\n  thus \"0 < inverse a\"\n    by (simp add: a_gt_0 [THEN less_not_sym] zero_less_mult_iff)\nqed\n\nlemma negative_imp_inverse_negative:\n  \"a < 0 \\<Longrightarrow> inverse a < 0\"\n  by (insert positive_imp_inverse_positive [of \"-a\"],\n    simp add: nonzero_inverse_minus_eq less_imp_not_eq)\n\nlemma inverse_le_imp_le:\n  assumes invle: \"inverse a \\<le> inverse b\" and apos: \"0 < a\"\n  shows \"b \\<le> a\"\nproof (rule classical)\n  assume \"\\<not> b \\<le> a\"\n  hence \"a < b\"  by (simp add: linorder_not_le)\n  hence bpos: \"0 < b\"  by (blast intro: apos less_trans)\n  hence \"a * inverse a \\<le> a * inverse b\"\n    by (simp add: apos invle less_imp_le mult_left_mono)\n  hence \"(a * inverse a) * b \\<le> (a * inverse b) * b\"\n    by (simp add: bpos less_imp_le mult_right_mono)\n  thus \"b \\<le> a\"  by (simp add: mult.assoc apos bpos less_imp_not_eq2)\nqed\n\nlemma inverse_positive_imp_positive:\n  assumes inv_gt_0: \"0 < inverse a\" and nz: \"a \\<noteq> 0\"\n  shows \"0 < a\"\nproof -\n  have \"0 < inverse (inverse a)\"\n    using inv_gt_0 by (rule positive_imp_inverse_positive)\n  thus \"0 < a\"\n    using nz by (simp add: nonzero_inverse_inverse_eq)\nqed\n\nlemma inverse_negative_imp_negative:\n  assumes inv_less_0: \"inverse a < 0\" and nz: \"a \\<noteq> 0\"\n  shows \"a < 0\"\nproof -\n  have \"inverse (inverse a) < 0\"\n    using inv_less_0 by (rule negative_imp_inverse_negative)\n  thus \"a < 0\" using nz by (simp add: nonzero_inverse_inverse_eq)\nqed\n\nlemma linordered_field_no_lb:\n  \"\\<forall>x. \\<exists>y. y < x\"\nproof\n  fix x::'a\n  have m1: \"- (1::'a) < 0\" by simp\n  from add_strict_right_mono[OF m1, where c=x]\n  have \"(- 1) + x < x\" by simp\n  thus \"\\<exists>y. y < x\" by blast\nqed\n\nlemma linordered_field_no_ub:\n  \"\\<forall> x. \\<exists>y. y > x\"\nproof\n  fix x::'a\n  have m1: \" (1::'a) > 0\" by simp\n  from add_strict_right_mono[OF m1, where c=x]\n  have \"1 + x > x\" by simp\n  thus \"\\<exists>y. y > x\" by blast\nqed\n\nlemma less_imp_inverse_less:\n  assumes less: \"a < b\" and apos:  \"0 < a\"\n  shows \"inverse b < inverse a\"\nproof (rule ccontr)\n  assume \"\\<not> inverse b < inverse a\"\n  hence \"inverse a \\<le> inverse b\" by simp\n  hence \"\\<not> (a < b)\"\n    by (simp add: not_less inverse_le_imp_le [OF _ apos])\n  thus False by (rule notE [OF _ less])\nqed\n\nlemma inverse_less_imp_less:\n  assumes \"inverse a < inverse b\" \"0 < a\"\n  shows \"b < a\"\nproof -\n  have \"a \\<noteq> b\"\n    using assms by (simp add: less_le)\n  moreover have \"b \\<le> a\"\n    using assms by (force simp: less_le dest: inverse_le_imp_le)\n  ultimately show ?thesis\n    by (simp add: less_le)\nqed\n\ntext\\<open>Both premises are essential. Consider -1 and 1.\\<close>\nlemma inverse_less_iff_less [simp]:\n  \"0 < a \\<Longrightarrow> 0 < b \\<Longrightarrow> inverse a < inverse b \\<longleftrightarrow> b < a\"\n  by (blast intro: less_imp_inverse_less dest: inverse_less_imp_less)\n\nlemma le_imp_inverse_le:\n  \"a \\<le> b \\<Longrightarrow> 0 < a \\<Longrightarrow> inverse b \\<le> inverse a\"\n  by (force simp add: le_less less_imp_inverse_less)\n\nlemma inverse_le_iff_le [simp]:\n  \"0 < a \\<Longrightarrow> 0 < b \\<Longrightarrow> inverse a \\<le> inverse b \\<longleftrightarrow> b \\<le> a\"\n  by (blast intro: le_imp_inverse_le dest: inverse_le_imp_le)\n\n\ntext\\<open>These results refer to both operands being negative.  The opposite-sign\ncase is trivial, since inverse preserves signs.\\<close>\nlemma inverse_le_imp_le_neg:\n  assumes \"inverse a \\<le> inverse b\" \"b < 0\"\n  shows \"b \\<le> a\"\nproof (rule classical)\n  assume \"\\<not> b \\<le> a\"\n  with \\<open>b < 0\\<close> have \"a < 0\"\n    by force\n  with assms show \"b \\<le> a\"\n    using inverse_le_imp_le [of \"-b\" \"-a\"] by (simp add: nonzero_inverse_minus_eq)\nqed\n\nlemma less_imp_inverse_less_neg:\n  assumes \"a < b\" \"b < 0\"\n  shows \"inverse b < inverse a\"\nproof -\n  have \"a < 0\"\n    using assms by (blast intro: less_trans)\n  with less_imp_inverse_less [of \"-b\" \"-a\"] show ?thesis\n    by (simp add: nonzero_inverse_minus_eq assms)\nqed\n\nlemma inverse_less_imp_less_neg:\n  assumes \"inverse a < inverse b\" \"b < 0\"\n  shows \"b < a\"\nproof (rule classical)\n  assume \"\\<not> b < a\"\n  with \\<open>b < 0\\<close> have \"a < 0\"\n    by force\n  with inverse_less_imp_less [of \"-b\" \"-a\"] show ?thesis\n    by (simp add: nonzero_inverse_minus_eq assms)\nqed\n\nlemma inverse_less_iff_less_neg [simp]:\n  \"a < 0 \\<Longrightarrow> b < 0 \\<Longrightarrow> inverse a < inverse b \\<longleftrightarrow> b < a\"\n  using inverse_less_iff_less [of \"-b\" \"-a\"]\n  by (simp del: inverse_less_iff_less add: nonzero_inverse_minus_eq)\n\nlemma le_imp_inverse_le_neg:\n  \"a \\<le> b \\<Longrightarrow> b < 0 \\<Longrightarrow> inverse b \\<le> inverse a\"\n  by (force simp add: le_less less_imp_inverse_less_neg)\n\nlemma inverse_le_iff_le_neg [simp]:\n  \"a < 0 \\<Longrightarrow> b < 0 \\<Longrightarrow> inverse a \\<le> inverse b \\<longleftrightarrow> b \\<le> a\"\n  by (blast intro: le_imp_inverse_le_neg dest: inverse_le_imp_le_neg)\n\nlemma one_less_inverse:\n  \"0 < a \\<Longrightarrow> a < 1 \\<Longrightarrow> 1 < inverse a\"\n  using less_imp_inverse_less [of a 1, unfolded inverse_1] .\n\nlemma one_le_inverse:\n  \"0 < a \\<Longrightarrow> a \\<le> 1 \\<Longrightarrow> 1 \\<le> inverse a\"\n  using le_imp_inverse_le [of a 1, unfolded inverse_1] .\n\nlemma pos_le_divide_eq [field_simps]:\n  assumes \"0 < c\"\n  shows \"a \\<le> b / c \\<longleftrightarrow> a * c \\<le> b\"\nproof -\n  from assms have \"a \\<le> b / c \\<longleftrightarrow> a * c \\<le> (b / c) * c\"\n    using mult_le_cancel_right [of a c \"b * inverse c\"] by (auto simp add: field_simps)\n  also have \"... \\<longleftrightarrow> a * c \\<le> b\"\n    by (simp add: less_imp_not_eq2 [OF assms] divide_inverse mult.assoc)\n  finally show ?thesis .\nqed\n\nlemma pos_less_divide_eq [field_simps]:\n  assumes \"0 < c\"\n  shows \"a < b / c \\<longleftrightarrow> a * c < b\"\nproof -\n  from assms have \"a < b / c \\<longleftrightarrow> a * c < (b / c) * c\"\n    using mult_less_cancel_right [of a c \"b / c\"] by auto\n  also have \"... = (a*c < b)\"\n    by (simp add: less_imp_not_eq2 [OF assms] divide_inverse mult.assoc)\n  finally show ?thesis .\nqed\n\nlemma neg_less_divide_eq [field_simps]:\n  assumes \"c < 0\"\n  shows \"a < b / c \\<longleftrightarrow> b < a * c\"\nproof -\n  from assms have \"a < b / c \\<longleftrightarrow> (b / c) * c < a * c\"\n    using mult_less_cancel_right [of \"b / c\" c a] by auto\n  also have \"... \\<longleftrightarrow> b < a * c\"\n    by (simp add: less_imp_not_eq [OF assms] divide_inverse mult.assoc)\n  finally show ?thesis .\nqed\n\nlemma neg_le_divide_eq [field_simps]:\n  assumes \"c < 0\"\n  shows \"a \\<le> b / c \\<longleftrightarrow> b \\<le> a * c\"\nproof -\n  from assms have \"a \\<le> b / c \\<longleftrightarrow> (b / c) * c \\<le> a * c\"\n    using mult_le_cancel_right [of \"b * inverse c\" c a] by (auto simp add: field_simps)\n  also have \"... \\<longleftrightarrow> b \\<le> a * c\"\n    by (simp add: less_imp_not_eq [OF assms] divide_inverse mult.assoc)\n  finally show ?thesis .\nqed\n\nlemma pos_divide_le_eq [field_simps]:\n  assumes \"0 < c\"\n  shows \"b / c \\<le> a \\<longleftrightarrow> b \\<le> a * c\"\nproof -\n  from assms have \"b / c \\<le> a \\<longleftrightarrow> (b / c) * c \\<le> a * c\"\n    using mult_le_cancel_right [of \"b / c\" c a] by auto\n  also have \"... \\<longleftrightarrow> b \\<le> a * c\"\n    by (simp add: less_imp_not_eq2 [OF assms] divide_inverse mult.assoc)\n  finally show ?thesis .\nqed\n\nlemma pos_divide_less_eq [field_simps]:\n  assumes \"0 < c\"\n  shows \"b / c < a \\<longleftrightarrow> b < a * c\"\nproof -\n  from assms have \"b / c < a \\<longleftrightarrow> (b / c) * c < a * c\"\n    using mult_less_cancel_right [of \"b / c\" c a] by auto\n  also have \"... \\<longleftrightarrow> b < a * c\"\n    by (simp add: less_imp_not_eq2 [OF assms] divide_inverse mult.assoc)\n  finally show ?thesis .\nqed\n\nlemma neg_divide_le_eq [field_simps]:\n  assumes \"c < 0\"\n  shows \"b / c \\<le> a \\<longleftrightarrow> a * c \\<le> b\"\nproof -\n  from assms have \"b / c \\<le> a \\<longleftrightarrow> a * c \\<le> (b / c) * c\"\n    using mult_le_cancel_right [of a c \"b / c\"] by auto\n  also have \"... \\<longleftrightarrow> a * c \\<le> b\"\n    by (simp add: less_imp_not_eq [OF assms] divide_inverse mult.assoc)\n  finally show ?thesis .\nqed\n\nlemma neg_divide_less_eq [field_simps]:\n  assumes \"c < 0\"\n  shows \"b / c < a \\<longleftrightarrow> a * c < b\"\nproof -\n  from assms have \"b / c < a \\<longleftrightarrow> a * c < b / c * c\"\n    using mult_less_cancel_right [of a c \"b / c\"] by auto\n  also have \"... \\<longleftrightarrow> a * c < b\"\n    by (simp add: less_imp_not_eq [OF assms] divide_inverse mult.assoc)\n  finally show ?thesis .\nqed\n\ntext\\<open>The following \\<open>field_simps\\<close> rules are necessary, as minus is always moved atop of\ndivision but we want to get rid of division.\\<close>\n\nlemma pos_le_minus_divide_eq [field_simps]: \"0 < c \\<Longrightarrow> a \\<le> - (b / c) \\<longleftrightarrow> a * c \\<le> - b\"\n  unfolding minus_divide_left by (rule pos_le_divide_eq)\n\nlemma neg_le_minus_divide_eq [field_simps]: \"c < 0 \\<Longrightarrow> a \\<le> - (b / c) \\<longleftrightarrow> - b \\<le> a * c\"\n  unfolding minus_divide_left by (rule neg_le_divide_eq)\n\nlemma pos_less_minus_divide_eq [field_simps]: \"0 < c \\<Longrightarrow> a < - (b / c) \\<longleftrightarrow> a * c < - b\"\n  unfolding minus_divide_left by (rule pos_less_divide_eq)\n\nlemma neg_less_minus_divide_eq [field_simps]: \"c < 0 \\<Longrightarrow> a < - (b / c) \\<longleftrightarrow> - b < a * c\"\n  unfolding minus_divide_left by (rule neg_less_divide_eq)\n\nlemma pos_minus_divide_less_eq [field_simps]: \"0 < c \\<Longrightarrow> - (b / c) < a \\<longleftrightarrow> - b < a * c\"\n  unfolding minus_divide_left by (rule pos_divide_less_eq)\n\nlemma neg_minus_divide_less_eq [field_simps]: \"c < 0 \\<Longrightarrow> - (b / c) < a \\<longleftrightarrow> a * c < - b\"\n  unfolding minus_divide_left by (rule neg_divide_less_eq)\n\nlemma pos_minus_divide_le_eq [field_simps]: \"0 < c \\<Longrightarrow> - (b / c) \\<le> a \\<longleftrightarrow> - b \\<le> a * c\"\n  unfolding minus_divide_left by (rule pos_divide_le_eq)\n\nlemma neg_minus_divide_le_eq [field_simps]: \"c < 0 \\<Longrightarrow> - (b / c) \\<le> a \\<longleftrightarrow> a * c \\<le> - b\"\n  unfolding minus_divide_left by (rule neg_divide_le_eq)\n\nlemma frac_less_eq:\n  \"y \\<noteq> 0 \\<Longrightarrow> z \\<noteq> 0 \\<Longrightarrow> x / y < w / z \\<longleftrightarrow> (x * z - w * y) / (y * z) < 0\"\n  by (subst less_iff_diff_less_0) (simp add: diff_frac_eq )\n\nlemma frac_le_eq:\n  \"y \\<noteq> 0 \\<Longrightarrow> z \\<noteq> 0 \\<Longrightarrow> x / y \\<le> w / z \\<longleftrightarrow> (x * z - w * y) / (y * z) \\<le> 0\"\n  by (subst le_iff_diff_le_0) (simp add: diff_frac_eq )\n\nlemma divide_pos_pos[simp]:\n  \"0 < x \\<Longrightarrow> 0 < y \\<Longrightarrow> 0 < x / y\"\nby(simp add:field_simps)\n\nlemma divide_nonneg_pos:\n  \"0 \\<le> x \\<Longrightarrow> 0 < y \\<Longrightarrow> 0 \\<le> x / y\"\nby(simp add:field_simps)\n\nlemma divide_neg_pos:\n  \"x < 0 \\<Longrightarrow> 0 < y \\<Longrightarrow> x / y < 0\"\n  by(simp add:field_simps)\n\nlemma divide_nonpos_pos:\n  \"x \\<le> 0 \\<Longrightarrow> 0 < y \\<Longrightarrow> x / y \\<le> 0\"\n  by(simp add:field_simps)\n\nlemma divide_pos_neg:\n  \"0 < x \\<Longrightarrow> y < 0 \\<Longrightarrow> x / y < 0\"\n  by(simp add:field_simps)\n\nlemma divide_nonneg_neg:\n  \"0 \\<le> x \\<Longrightarrow> y < 0 \\<Longrightarrow> x / y \\<le> 0\"\n  by(simp add:field_simps)\n\nlemma divide_neg_neg:\n  \"x < 0 \\<Longrightarrow> y < 0 \\<Longrightarrow> 0 < x / y\"\n  by(simp add:field_simps)\n\nlemma divide_nonpos_neg:\n  \"x \\<le> 0 \\<Longrightarrow> y < 0 \\<Longrightarrow> 0 \\<le> x / y\"\n  by(simp add:field_simps)\n\nlemma divide_strict_right_mono:\n  \"\\<lbrakk>a < b; 0 < c\\<rbrakk> \\<Longrightarrow> a / c < b / c\"\n  by (simp add: less_imp_not_eq2 divide_inverse mult_strict_right_mono\n      positive_imp_inverse_positive)\n\n\nlemma divide_strict_right_mono_neg:\n  assumes \"b < a\" \"c < 0\" shows \"a / c < b / c\"\nproof -\n  have \"b / - c < a / - c\"\n    by (rule divide_strict_right_mono) (use assms in auto)\n  then show ?thesis\n    by (simp add: less_imp_not_eq)\nqed\n\ntext\\<open>The last premise ensures that \\<^term>\\<open>a\\<close> and \\<^term>\\<open>b\\<close>\n      have the same sign\\<close>\nlemma divide_strict_left_mono:\n  \"\\<lbrakk>b < a; 0 < c; 0 < a*b\\<rbrakk> \\<Longrightarrow> c / a < c / b\"\n  by (auto simp: field_simps zero_less_mult_iff mult_strict_right_mono)\n\nlemma divide_left_mono:\n  \"\\<lbrakk>b \\<le> a; 0 \\<le> c; 0 < a*b\\<rbrakk> \\<Longrightarrow> c / a \\<le> c / b\"\n  by (auto simp: field_simps zero_less_mult_iff mult_right_mono)\n\nlemma divide_strict_left_mono_neg:\n  \"\\<lbrakk>a < b; c < 0; 0 < a*b\\<rbrakk> \\<Longrightarrow> c / a < c / b\"\n  by (auto simp: field_simps zero_less_mult_iff mult_strict_right_mono_neg)\n\nlemma mult_imp_div_pos_le: \"0 < y \\<Longrightarrow> x \\<le> z * y \\<Longrightarrow> x / y \\<le> z\"\nby (subst pos_divide_le_eq, assumption+)\n\nlemma mult_imp_le_div_pos: \"0 < y \\<Longrightarrow> z * y \\<le> x \\<Longrightarrow> z \\<le> x / y\"\nby(simp add:field_simps)\n\nlemma mult_imp_div_pos_less: \"0 < y \\<Longrightarrow> x < z * y \\<Longrightarrow> x / y < z\"\nby(simp add:field_simps)\n\nlemma mult_imp_less_div_pos: \"0 < y \\<Longrightarrow> z * y < x \\<Longrightarrow> z < x / y\"\nby(simp add:field_simps)\n\nlemma frac_le:\n  assumes \"0 \\<le> y\" \"x \\<le> y\" \"0 < w\" \"w \\<le> z\"\n  shows \"x / z \\<le> y / w\"\nproof (rule mult_imp_div_pos_le)\n  show \"z > 0\"\n    using assms by simp\n  have \"x \\<le> y * z / w\"\n  proof (rule mult_imp_le_div_pos [OF \\<open>0 < w\\<close>])\n    show \"x * w \\<le> y * z\"\n      using assms by (auto intro: mult_mono)\n  qed\n  also have \"... = y / w * z\"\n    by simp\n  finally show \"x \\<le> y / w * z\" .\nqed\n\nlemma frac_less:\n  assumes \"0 \\<le> x\" \"x < y\" \"0 < w\" \"w \\<le> z\"\n  shows \"x / z < y / w\"\nproof (rule mult_imp_div_pos_less)\n  show \"z > 0\"\n    using assms by simp\n  have \"x < y * z / w\"\n  proof (rule mult_imp_less_div_pos [OF \\<open>0 < w\\<close>])\n    show \"x * w < y * z\"\n      using assms by (auto intro: mult_less_le_imp_less)\n  qed\n  also have \"... = y / w * z\"\n    by simp\n  finally show \"x < y / w * z\" .\nqed\n\nlemma frac_less2:\n  assumes \"0 < x\" \"x \\<le> y\" \"0 < w\" \"w < z\"\n  shows \"x / z < y / w\"\nproof (rule mult_imp_div_pos_less)\n  show \"z > 0\"\n    using assms by simp\n  show \"x < y / w * z\"\n    using assms by (force intro: mult_imp_less_div_pos mult_le_less_imp_less)\nqed\n\nlemma less_half_sum: \"a < b \\<Longrightarrow> a < (a+b) / (1+1)\"\n  by (simp add: field_simps zero_less_two)\n\nlemma gt_half_sum: \"a < b \\<Longrightarrow> (a+b)/(1+1) < b\"\n  by (simp add: field_simps zero_less_two)\n\nsubclass unbounded_dense_linorder\nproof\n  fix x y :: 'a\n  from less_add_one show \"\\<exists>y. x < y\" ..\n  from less_add_one have \"x + (- 1) < (x + 1) + (- 1)\" by (rule add_strict_right_mono)\n  then have \"x - 1 < x + 1 - 1\" by simp\n  then have \"x - 1 < x\" by (simp add: algebra_simps)\n  then show \"\\<exists>y. y < x\" ..\n  show \"x < y \\<Longrightarrow> \\<exists>z>x. z < y\" by (blast intro!: less_half_sum gt_half_sum)\nqed\n\nsubclass field_abs_sgn ..\n\nlemma inverse_sgn [simp]:\n  \"inverse (sgn a) = sgn a\"\n  by (cases a 0 rule: linorder_cases) simp_all\n\nlemma divide_sgn [simp]:\n  \"a / sgn b = a * sgn b\"\n  by (cases b 0 rule: linorder_cases) simp_all\n\nlemma nonzero_abs_inverse:\n  \"a \\<noteq> 0 \\<Longrightarrow> \\<bar>inverse a\\<bar> = inverse \\<bar>a\\<bar>\"\n  by (rule abs_inverse)\n\nlemma nonzero_abs_divide:\n  \"b \\<noteq> 0 \\<Longrightarrow> \\<bar>a / b\\<bar> = \\<bar>a\\<bar> / \\<bar>b\\<bar>\"\n  by (rule abs_divide)\n\nlemma field_le_epsilon:\n  assumes e: \"\\<And>e. 0 < e \\<Longrightarrow> x \\<le> y + e\"\n  shows \"x \\<le> y\"\nproof (rule dense_le)\n  fix t assume \"t < x\"\n  hence \"0 < x - t\" by (simp add: less_diff_eq)\n  from e [OF this] have \"x + 0 \\<le> x + (y - t)\" by (simp add: algebra_simps)\n  then have \"0 \\<le> y - t\" by (simp only: add_le_cancel_left)\n  then show \"t \\<le> y\" by (simp add: algebra_simps)\nqed\n\nlemma inverse_positive_iff_positive [simp]: \"(0 < inverse a) = (0 < a)\"\nproof (cases \"a = 0\")\n  case False\n  then show ?thesis\n    by (blast intro: inverse_positive_imp_positive positive_imp_inverse_positive)\nqed auto\n\nlemma inverse_negative_iff_negative [simp]: \"(inverse a < 0) = (a < 0)\"\nproof (cases \"a = 0\")\n  case False\n  then show ?thesis\n    by (blast intro: inverse_negative_imp_negative negative_imp_inverse_negative)\nqed auto\n\nlemma inverse_nonnegative_iff_nonnegative [simp]: \"0 \\<le> inverse a \\<longleftrightarrow> 0 \\<le> a\"\n  by (simp add: not_less [symmetric])\n\nlemma inverse_nonpositive_iff_nonpositive [simp]: \"inverse a \\<le> 0 \\<longleftrightarrow> a \\<le> 0\"\n  by (simp add: not_less [symmetric])\n\nlemma one_less_inverse_iff: \"1 < inverse x \\<longleftrightarrow> 0 < x \\<and> x < 1\"\n  using less_trans[of 1 x 0 for x]\n  by (cases x 0 rule: linorder_cases) (auto simp add: field_simps)\n\nlemma one_le_inverse_iff: \"1 \\<le> inverse x \\<longleftrightarrow> 0 < x \\<and> x \\<le> 1\"\nproof (cases \"x = 1\")\n  case True then show ?thesis by simp\nnext\n  case False then have \"inverse x \\<noteq> 1\" by simp\n  then have \"1 \\<noteq> inverse x\" by blast\n  then have \"1 \\<le> inverse x \\<longleftrightarrow> 1 < inverse x\" by (simp add: le_less)\n  with False show ?thesis by (auto simp add: one_less_inverse_iff)\nqed\n\nlemma inverse_less_1_iff: \"inverse x < 1 \\<longleftrightarrow> x \\<le> 0 \\<or> 1 < x\"\n  by (simp add: not_le [symmetric] one_le_inverse_iff)\n\nlemma inverse_le_1_iff: \"inverse x \\<le> 1 \\<longleftrightarrow> x \\<le> 0 \\<or> 1 \\<le> x\"\n  by (simp add: not_less [symmetric] one_less_inverse_iff)\n\nlemma [field_split_simps, divide_simps]:\n  shows le_divide_eq: \"a \\<le> b / c \\<longleftrightarrow> (if 0 < c then a * c \\<le> b else if c < 0 then b \\<le> a * c else a \\<le> 0)\"\n    and divide_le_eq: \"b / c \\<le> a \\<longleftrightarrow> (if 0 < c then b \\<le> a * c else if c < 0 then a * c \\<le> b else 0 \\<le> a)\"\n    and less_divide_eq: \"a < b / c \\<longleftrightarrow> (if 0 < c then a * c < b else if c < 0 then b < a * c else a < 0)\"\n    and divide_less_eq: \"b / c < a \\<longleftrightarrow> (if 0 < c then b < a * c else if c < 0 then a * c < b else 0 < a)\"\n    and le_minus_divide_eq: \"a \\<le> - (b / c) \\<longleftrightarrow> (if 0 < c then a * c \\<le> - b else if c < 0 then - b \\<le> a * c else a \\<le> 0)\"\n    and minus_divide_le_eq: \"- (b / c) \\<le> a \\<longleftrightarrow> (if 0 < c then - b \\<le> a * c else if c < 0 then a * c \\<le> - b else 0 \\<le> a)\"\n    and less_minus_divide_eq: \"a < - (b / c) \\<longleftrightarrow> (if 0 < c then a * c < - b else if c < 0 then - b < a * c else  a < 0)\"\n    and minus_divide_less_eq: \"- (b / c) < a \\<longleftrightarrow> (if 0 < c then - b < a * c else if c < 0 then a * c < - b else 0 < a)\"\n  by (auto simp: field_simps not_less dest: antisym)\n\ntext \\<open>Division and Signs\\<close>\n\nlemma\n  shows zero_less_divide_iff: \"0 < a / b \\<longleftrightarrow> 0 < a \\<and> 0 < b \\<or> a < 0 \\<and> b < 0\"\n    and divide_less_0_iff: \"a / b < 0 \\<longleftrightarrow> 0 < a \\<and> b < 0 \\<or> a < 0 \\<and> 0 < b\"\n    and zero_le_divide_iff: \"0 \\<le> a / b \\<longleftrightarrow> 0 \\<le> a \\<and> 0 \\<le> b \\<or> a \\<le> 0 \\<and> b \\<le> 0\"\n    and divide_le_0_iff: \"a / b \\<le> 0 \\<longleftrightarrow> 0 \\<le> a \\<and> b \\<le> 0 \\<or> a \\<le> 0 \\<and> 0 \\<le> b\"\n  by (auto simp add: field_split_simps)\n\ntext \\<open>Division and the Number One\\<close>\n\ntext\\<open>Simplify expressions equated with 1\\<close>\n\nlemma zero_eq_1_divide_iff [simp]: \"0 = 1 / a \\<longleftrightarrow> a = 0\"\n  by (cases \"a = 0\") (auto simp: field_simps)\n\nlemma one_divide_eq_0_iff [simp]: \"1 / a = 0 \\<longleftrightarrow> a = 0\"\n  using zero_eq_1_divide_iff[of a] by simp\n\ntext\\<open>Simplify expressions such as \\<open>0 < 1/x\\<close> to \\<open>0 < x\\<close>\\<close>\n\nlemma zero_le_divide_1_iff [simp]:\n  \"0 \\<le> 1 / a \\<longleftrightarrow> 0 \\<le> a\"\n  by (simp add: zero_le_divide_iff)\n\nlemma zero_less_divide_1_iff [simp]:\n  \"0 < 1 / a \\<longleftrightarrow> 0 < a\"\n  by (simp add: zero_less_divide_iff)\n\nlemma divide_le_0_1_iff [simp]:\n  \"1 / a \\<le> 0 \\<longleftrightarrow> a \\<le> 0\"\n  by (simp add: divide_le_0_iff)\n\nlemma divide_less_0_1_iff [simp]:\n  \"1 / a < 0 \\<longleftrightarrow> a < 0\"\n  by (simp add: divide_less_0_iff)\n\nlemma divide_right_mono:\n  \"\\<lbrakk>a \\<le> b; 0 \\<le> c\\<rbrakk> \\<Longrightarrow> a/c \\<le> b/c\"\n  by (force simp add: divide_strict_right_mono le_less)\n\nlemma divide_right_mono_neg: \"a \\<le> b \\<Longrightarrow> c \\<le> 0 \\<Longrightarrow> b / c \\<le> a / c\"\n  by (auto dest: divide_right_mono [of _ _ \"- c\"])\n\nlemma divide_left_mono_neg: \"a \\<le> b \\<Longrightarrow> c \\<le> 0 \\<Longrightarrow> 0 < a * b \\<Longrightarrow> c / a \\<le> c / b\"\n  by (auto simp add: mult.commute dest: divide_left_mono [of _ _ \"- c\"])\n\nlemma inverse_le_iff: \"inverse a \\<le> inverse b \\<longleftrightarrow> (0 < a * b \\<longrightarrow> b \\<le> a) \\<and> (a * b \\<le> 0 \\<longrightarrow> a \\<le> b)\"\n  by (cases a 0 b 0 rule: linorder_cases[case_product linorder_cases])\n     (auto simp add: field_simps zero_less_mult_iff mult_le_0_iff)\n\nlemma inverse_less_iff: \"inverse a < inverse b \\<longleftrightarrow> (0 < a * b \\<longrightarrow> b < a) \\<and> (a * b \\<le> 0 \\<longrightarrow> a < b)\"\n  by (subst less_le) (auto simp: inverse_le_iff)\n\nlemma divide_le_cancel: \"a / c \\<le> b / c \\<longleftrightarrow> (0 < c \\<longrightarrow> a \\<le> b) \\<and> (c < 0 \\<longrightarrow> b \\<le> a)\"\n  by (simp add: divide_inverse mult_le_cancel_right)\n\nlemma divide_less_cancel: \"a / c < b / c \\<longleftrightarrow> (0 < c \\<longrightarrow> a < b) \\<and> (c < 0 \\<longrightarrow> b < a) \\<and> c \\<noteq> 0\"\n  by (auto simp add: divide_inverse mult_less_cancel_right)\n\ntext\\<open>Simplify quotients that are compared with the value 1.\\<close>\n\nlemma le_divide_eq_1:\n  \"(1 \\<le> b / a) = ((0 < a \\<and> a \\<le> b) \\<or> (a < 0 \\<and> b \\<le> a))\"\n  by (auto simp add: le_divide_eq)\n\nlemma divide_le_eq_1:\n  \"(b / a \\<le> 1) = ((0 < a \\<and> b \\<le> a) \\<or> (a < 0 \\<and> a \\<le> b) \\<or> a=0)\"\n  by (auto simp add: divide_le_eq)\n\nlemma less_divide_eq_1:\n  \"(1 < b / a) = ((0 < a \\<and> a < b) \\<or> (a < 0 \\<and> b < a))\"\n  by (auto simp add: less_divide_eq)\n\nlemma divide_less_eq_1:\n  \"(b / a < 1) = ((0 < a \\<and> b < a) \\<or> (a < 0 \\<and> a < b) \\<or> a=0)\"\n  by (auto simp add: divide_less_eq)\n\nlemma divide_nonneg_nonneg [simp]:\n  \"0 \\<le> x \\<Longrightarrow> 0 \\<le> y \\<Longrightarrow> 0 \\<le> x / y\"\n  by (auto simp add: field_split_simps)\n\nlemma divide_nonpos_nonpos:\n  \"x \\<le> 0 \\<Longrightarrow> y \\<le> 0 \\<Longrightarrow> 0 \\<le> x / y\"\n  by (auto simp add: field_split_simps)\n\nlemma divide_nonneg_nonpos:\n  \"0 \\<le> x \\<Longrightarrow> y \\<le> 0 \\<Longrightarrow> x / y \\<le> 0\"\n  by (auto simp add: field_split_simps)\n\nlemma divide_nonpos_nonneg:\n  \"x \\<le> 0 \\<Longrightarrow> 0 \\<le> y \\<Longrightarrow> x / y \\<le> 0\"\n  by (auto simp add: field_split_simps)\n\ntext \\<open>Conditional Simplification Rules: No Case Splits\\<close>\n\nlemma le_divide_eq_1_pos [simp]:\n  \"0 < a \\<Longrightarrow> (1 \\<le> b/a) = (a \\<le> b)\"\n  by (auto simp add: le_divide_eq)\n\nlemma le_divide_eq_1_neg [simp]:\n  \"a < 0 \\<Longrightarrow> (1 \\<le> b/a) = (b \\<le> a)\"\n  by (auto simp add: le_divide_eq)\n\nlemma divide_le_eq_1_pos [simp]:\n  \"0 < a \\<Longrightarrow> (b/a \\<le> 1) = (b \\<le> a)\"\n  by (auto simp add: divide_le_eq)\n\nlemma divide_le_eq_1_neg [simp]:\n  \"a < 0 \\<Longrightarrow> (b/a \\<le> 1) = (a \\<le> b)\"\n  by (auto simp add: divide_le_eq)\n\nlemma less_divide_eq_1_pos [simp]:\n  \"0 < a \\<Longrightarrow> (1 < b/a) = (a < b)\"\n  by (auto simp add: less_divide_eq)\n\nlemma less_divide_eq_1_neg [simp]:\n  \"a < 0 \\<Longrightarrow> (1 < b/a) = (b < a)\"\n  by (auto simp add: less_divide_eq)\n\nlemma divide_less_eq_1_pos [simp]:\n  \"0 < a \\<Longrightarrow> (b/a < 1) = (b < a)\"\n  by (auto simp add: divide_less_eq)\n\nlemma divide_less_eq_1_neg [simp]:\n  \"a < 0 \\<Longrightarrow> b/a < 1 \\<longleftrightarrow> a < b\"\n  by (auto simp add: divide_less_eq)\n\nlemma eq_divide_eq_1 [simp]:\n  \"(1 = b/a) = ((a \\<noteq> 0 \\<and> a = b))\"\n  by (auto simp add: eq_divide_eq)\n\nlemma divide_eq_eq_1 [simp]:\n  \"(b/a = 1) = ((a \\<noteq> 0 \\<and> a = b))\"\n  by (auto simp add: divide_eq_eq)\n\nlemma abs_div_pos: \"0 < y \\<Longrightarrow> \\<bar>x\\<bar> / y = \\<bar>x / y\\<bar>\"\n  by (simp add: order_less_imp_le)\n\nlemma zero_le_divide_abs_iff [simp]: \"(0 \\<le> a / \\<bar>b\\<bar>) = (0 \\<le> a \\<or> b = 0)\"\n  by (auto simp: zero_le_divide_iff)\n\nlemma divide_le_0_abs_iff [simp]: \"(a / \\<bar>b\\<bar> \\<le> 0) = (a \\<le> 0 \\<or> b = 0)\"\n  by (auto simp: divide_le_0_iff)\n\nlemma field_le_mult_one_interval:\n  assumes *: \"\\<And>z. \\<lbrakk> 0 < z ; z < 1 \\<rbrakk> \\<Longrightarrow> z * x \\<le> y\"\n  shows \"x \\<le> y\"\nproof (cases \"0 < x\")\n  assume \"0 < x\"\n  thus ?thesis\n    using dense_le_bounded[of 0 1 \"y/x\"] *\n    unfolding le_divide_eq if_P[OF \\<open>0 < x\\<close>] by simp\nnext\n  assume \"\\<not>0 < x\" hence \"x \\<le> 0\" by simp\n  obtain s::'a where s: \"0 < s\" \"s < 1\" using dense[of 0 \"1::'a\"] by auto\n  hence \"x \\<le> s * x\" using mult_le_cancel_right[of 1 x s] \\<open>x \\<le> 0\\<close> by auto\n  also note *[OF s]\n  finally show ?thesis .\nqed\n\ntext\\<open>For creating values between \\<^term>\\<open>u\\<close> and \\<^term>\\<open>v\\<close>.\\<close>\nlemma scaling_mono:\n  assumes \"u \\<le> v\" \"0 \\<le> r\" \"r \\<le> s\"\n  shows \"u + r * (v - u) / s \\<le> v\"\nproof -\n  have \"r/s \\<le> 1\" using assms\n    using divide_le_eq_1 by fastforce\n  moreover have \"0 \\<le> v - u\"\n    using assms by simp\n  ultimately have \"(r/s) * (v - u) \\<le> 1 * (v - u)\"\n    by (rule mult_right_mono)\n  then show ?thesis\n    by (simp add: field_simps)\nqed\n\nend\n\ntext \\<open>Min/max Simplification Rules\\<close>\n\nlemma min_mult_distrib_left:\n  fixes x::\"'a::linordered_idom\" \n  shows \"p * min x y = (if 0 \\<le> p then min (p*x) (p*y) else max (p*x) (p*y))\"\nby (auto simp add: min_def max_def mult_le_cancel_left)\n\nlemma min_mult_distrib_right:\n  fixes x::\"'a::linordered_idom\" \n  shows \"min x y * p = (if 0 \\<le> p then min (x*p) (y*p) else max (x*p) (y*p))\"\nby (auto simp add: min_def max_def mult_le_cancel_right)\n\nlemma min_divide_distrib_right:\n  fixes x::\"'a::linordered_field\" \n  shows \"min x y / p = (if 0 \\<le> p then min (x/p) (y/p) else max (x/p) (y/p))\"\nby (simp add: min_mult_distrib_right divide_inverse)\n\nlemma max_mult_distrib_left:\n  fixes x::\"'a::linordered_idom\" \n  shows \"p * max x y = (if 0 \\<le> p then max (p*x) (p*y) else min (p*x) (p*y))\"\nby (auto simp add: min_def max_def mult_le_cancel_left)\n\nlemma max_mult_distrib_right:\n  fixes x::\"'a::linordered_idom\" \n  shows \"max x y * p = (if 0 \\<le> p then max (x*p) (y*p) else min (x*p) (y*p))\"\nby (auto simp add: min_def max_def mult_le_cancel_right)\n\nlemma max_divide_distrib_right:\n  fixes x::\"'a::linordered_field\" \n  shows \"max x y / p = (if 0 \\<le> p then max (x/p) (y/p) else min (x/p) (y/p))\"\nby (simp add: max_mult_distrib_right divide_inverse)\n\nhide_fact (open) field_inverse field_divide_inverse field_inverse_zero\n\ncode_identifier\n  code_module Fields \\<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/Fields.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.8723473779969194, "lm_q1q2_score": 0.7027911276877168}}
{"text": "(*  Title:      HOL/HOLCF/ex/Fix2.thy\n    Author:     Franz Regensburger\n\nShow that fix is the unique least fixed-point operator.\nFrom axioms gix1_def,gix2_def it follows that fix = gix\n*)\n\ntheory Fix2\nimports HOLCF\nbegin\n\naxiomatization\n  gix :: \"('a \\<rightarrow> 'a) \\<rightarrow>'a\" where\n  gix1_def: \"F\\<cdot>(gix\\<cdot>F) = gix\\<cdot>F\" and\n  gix2_def: \"F\\<cdot>y = y \\<Longrightarrow> gix\\<cdot>F << y\"\n\n\nlemma lemma1: \"fix = gix\"\napply (rule cfun_eqI)\napply (rule below_antisym)\napply (rule fix_least)\napply (rule gix1_def)\napply (rule gix2_def)\napply (rule fix_eq [symmetric])\ndone\n\nlemma lemma2: \"gix\\<cdot>F = lub (range (\\<lambda>i. iterate i\\<cdot>F\\<cdot>UU))\"\napply (rule lemma1 [THEN subst])\napply (rule fix_def2)\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/HOLCF/ex/Fix2.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.907312221360624, "lm_q2_score": 0.7745833737577158, "lm_q1q2_score": 0.7027889614731195}}
{"text": "(* Author: Tobias Nipkow *)\n\nsection \"Trie1\"\n\ntheory Trie1\nimports Main\nbegin\n\n\n\nhide_const (open) insert\n\ndeclare Let_def[simp]\n\n\nsubsection \"Trie\"\n\ndatatype trie = Leaf | Node bool \"trie * trie\"\n\nfun isin :: \"trie \\<Rightarrow> bool list \\<Rightarrow> bool\" where\n\"isin Leaf ks = False\" |\n\"isin (Node b (l,r)) ks =\n   (case ks of\n      [] \\<Rightarrow> b |\n      k#ks \\<Rightarrow> isin (if k then r else l) ks)\"\n\nfun insert :: \"bool list \\<Rightarrow> trie \\<Rightarrow> trie\" where\n\"insert [] Leaf = Node True (Leaf,Leaf)\" |\n\"insert [] (Node b lr) = Node True lr\" |\n\"insert (k#ks) Leaf =\n  Node False (if k then (Leaf, insert ks Leaf)\n                   else (insert ks Leaf, Leaf))\" |\n\"insert (k#ks) (Node b (l,r)) =\n  Node b (if k then (l, insert ks r)\n               else (insert ks l, r))\"\n\nlemma isin_insert: \"isin (insert as t) bs = (as = bs \\<or> isin t bs)\"\napply(induction as t arbitrary: bs rule: insert.induct)\napply (auto split: list.splits)\ndone\n\ntext \\<open>A simple implementation of delete; does not shrink the trie!\\<close>\n\nfun delete :: \"bool list \\<Rightarrow> trie \\<Rightarrow> trie\" where\n\"delete ks Leaf = Leaf\" |\n\"delete ks (Node b (l,r)) =\n   (case ks of\n      [] \\<Rightarrow> Node False (l,r) |\n      k#ks' \\<Rightarrow> Node b (if k then (l, delete ks' r) else (delete ks' l, r)))\"\n\nlemma \"isin (delete as t) bs = (as \\<noteq> bs \\<and> isin t bs)\"\napply(induction as t arbitrary: bs rule: delete.induct)\napply (auto split: list.splits)\ndone\n\nfun node :: \"bool \\<Rightarrow> trie * trie \\<Rightarrow> trie\" where\n\"node b lr = (if \\<not> b \\<and> lr = (Leaf,Leaf) then Leaf else Node b lr)\"\n\nfun delete2 :: \"bool list \\<Rightarrow> trie \\<Rightarrow> trie\" where\n\"delete2 ks Leaf = Leaf\" |\n\"delete2 ks (Node b (l,r)) =\n   (case ks of\n      [] \\<Rightarrow> node False (l,r) |\n      k#ks' \\<Rightarrow> node b (if k then (l, delete2 ks' r) else (delete2 ks' l, r)))\"\n\nlemma \"isin (delete2 as t) bs = isin (delete as t) bs\"\napply(induction as t arbitrary: bs rule: delete2.induct)\n apply simp\napply (force split: list.splits)\ndone\n\n\nsubsection \"Patricia Trie\"\n\ndatatype ptrie = LeafP | NodeP \"bool list\" bool \"ptrie * ptrie\"\n\nfun isinP :: \"ptrie \\<Rightarrow> bool list \\<Rightarrow> bool\" where\n\"isinP LeafP ks = False\" |\n\"isinP (NodeP ps b (l,r)) 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 (if k then r else l) ks'\n   else False)\"\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\nfun insertP :: \"bool list \\<Rightarrow> ptrie \\<Rightarrow> ptrie\" where\n\"insertP ks LeafP  = NodeP ks True (LeafP,LeafP)\" |\n\"insertP ks (NodeP ps b (l,r)) =\n  (case split ks ps of\n     (qs,k#ks',p#ps') \\<Rightarrow>\n       let tp = NodeP ps' b (l,r); tk = NodeP ks' True (LeafP,LeafP) in\n       NodeP qs False (if k then (tp,tk) else (tk,tp)) |\n     (qs,k#ks',[]) \\<Rightarrow>\n       NodeP ps b (if k then (l, insertP ks' r) else (insertP ks' l, r)) |\n     (qs,[],p#ps') \\<Rightarrow>\n       let t = NodeP ps' b (l,r) in\n       NodeP qs True (if p then (LeafP,t) else (t,LeafP)) |\n     (qs,[],[]) \\<Rightarrow> NodeP ps True (l,r))\"\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 Node False (if k then (Leaf,t') else (t',Leaf)))\"\n\nfun abs_ptrie :: \"ptrie \\<Rightarrow> trie\" where\n\"abs_ptrie LeafP = Leaf\" |\n\"abs_ptrie (NodeP ps b (l,r)) = prefix_trie ps (Node b (abs_ptrie l, abs_ptrie r))\"\n\nlemma isin_prefix_trie: \"isin (prefix_trie ps t) ks =\n (length ks \\<ge> length ps \\<and>\n  (let n = length ps in ps = take n ks \\<and> isin t (drop n ks)))\"\napply(induction ps arbitrary: ks)\napply(auto split: list.split)\ndone\n\nlemma isinP: \"isinP t ks = isin (abs_ptrie t) ks\"\napply(induction t arbitrary: ks rule: abs_ptrie.induct)\n apply(auto simp: isin_prefix_trie split: list.split)\n using nat_le_linear apply force\nusing nat_le_linear apply force\ndone\n\nlemma prefix_trie_Leafs: \"prefix_trie ks (Node True (Leaf,Leaf)) = insert ks Leaf\"\napply(induction ks)\napply auto\ndone\n\nlemma insert_prefix_trie_same:\n  \"insert ps (prefix_trie ps (Node b lr)) = prefix_trie ps (Node True lr)\"\napply(induction ps)\napply auto\ndone\n\nlemma insert_append: \"insert (ks @ k # ks') (prefix_trie ks (Node b (t1,t2))) =\n  prefix_trie ks (Node b (if k then (t1, insert ks' t2) else (insert ks' t1, t2)))\"\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_ptrie_insertP:\n  \"abs_ptrie (insertP ks t) = insert ks (abs_ptrie t)\"\napply(induction t arbitrary: ks)\napply(auto simp: prefix_trie_Leafs insert_prefix_trie_same insert_append prefix_trie_append\n           dest!: split_if split: list.split prod.split)\ndone\n\ncorollary isinP_insertP: \"isinP (insertP ks t) ks' = (ks=ks' \\<or> isinP t ks')\"\nby (simp add: isin_insert isinP abs_ptrie_insertP)\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/10/Trie1.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357735451834, "lm_q2_score": 0.8104789155369047, "lm_q1q2_score": 0.7027142134746015}}
{"text": "theory soma\n  imports Main\nbegin\nprimrec soma::\"nat \\<Rightarrow> nat \\<Rightarrow> nat\" where\nsomaeq1:\"soma x 0 = x\"|\nsomaeq2:\"soma x (Suc y) = Suc (soma x y)\"\n\nthm nat.induct\nprint_statement nat.induct\n\nvalue \"soma 1 0\"\nvalue \"soma 1 1\"\n\ntheorem soma1:\"\\<forall>x. soma x y = x + y\"\nproof (induct y)\n  show \"\\<forall>x. soma x 0 = x + 0\"\n  proof (rule allI)\n    fix x0::nat\n    have \"soma x0 0 = x0\" by (simp only:somaeq1)\n    also have \"... = x0 + 0\" by simp\n    finally show \"soma x0 0 = x0 + 0\" by simp\n  qed\nnext\n  fix y0::nat\n  assume HI:\"\\<forall>x. soma x y0 = x + y0\"\n  show \"\\<forall>x. soma x (Suc y0) = x + (Suc y0)\"\n  proof (rule allI)\n    fix x0::nat\n    have \"soma x0 (Suc y0) = Suc (soma x0 y0)\" by (simp only:somaeq2)\n    also have \"... = Suc (x0 + y0)\" by (simp only:HI)\n    also have \"... = x0 + (Suc y0)\" by simp\n    finally show \"soma x0 (Suc y0) = x0 + (Suc y0)\" by simp\n  qed\nqed\n\ntheorem soma2:\"\\<forall>x. soma x y = soma y x\"\nproof (induct y)\n  show \"\\<forall>x. soma x 0 = soma 0 x\"\n  proof (rule allI)\n    fix x0::nat\n    have \"soma x0 0 = x0\" by (simp only:somaeq1)\n    also have \"... = 0 + x0\" by simp\n    also have \"... = soma 0 x0\" by (simp only:soma1)\n    finally show \"soma x0 0 = soma 0 x0\" by simp\n  qed\nnext\n  fix y0::nat\n  assume HI:\"\\<forall>x. soma x y0 = soma y0 x\"\n  show \"\\<forall>x. soma x (Suc y0) = soma (Suc y0) x\"\n  proof (rule allI)\n    fix x0::nat\n    have \"soma x0 (Suc y0) = Suc (soma x0 y0)\" by (simp only:somaeq2)\n    also have \"... = Suc (soma y0 x0)\" by (simp only:HI)\n    also  have \"... = soma (Suc y0) x0\" by (simp only:soma1)\n    finally show \"soma x0 (Suc y0) = soma (Suc y0) x0\" by simp\n  qed\nqed\n\ntheorem soma3:\"\\<forall>x. soma x (Suc y) = soma (Suc x) y\"\nproof (induct y)\n  show \"\\<forall>x. soma x (Suc 0) = soma (Suc x) 0\"\n  proof (rule allI)\n    fix x0::nat\n    have \"soma x0 (Suc 0) = Suc (soma x0 0)\" by (simp only:somaeq2)\n    also have \"... = Suc (x0)\" by (simp only:somaeq1)\n    also have \"... = soma (Suc x0) 0\" by (simp only:soma1)\n    finally show \"soma x0 (Suc 0) = soma (Suc x0) 0\" by simp\n  qed\nnext\n  fix y0::nat\n  assume HI:\"\\<forall>x. soma x (Suc y0) = soma (Suc x) y0\"\n  show \"\\<forall>x. soma x (Suc (Suc y0)) = soma (Suc x) (Suc y0)\"\n  proof (rule allI)\n    fix x0::nat\n    have \"soma x0 (Suc (Suc y0)) = Suc (soma x0 (Suc y0))\" by (simp only:somaeq2)\n    also have \"... = Suc (soma (Suc x0) y0)\" by (simp only:HI)\n    also have \"... = soma (Suc x0) (Suc y0)\" by (simp only:soma1)\n    finally show \"soma x0 (Suc (Suc y0)) = soma (Suc x0) (Suc y0)\" by simp\n  qed\nqed\n\nend\n", "meta": {"author": "pedroeml", "repo": "metodos-formais", "sha": "400e4a747786792f2654590e617ab86ae39517da", "save_path": "github-repos/isabelle/pedroeml-metodos-formais", "path": "github-repos/isabelle/pedroeml-metodos-formais/metodos-formais-400e4a747786792f2654590e617ab86ae39517da/T1/soma.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357460591569, "lm_q2_score": 0.810478913248044, "lm_q1q2_score": 0.7027141892132325}}
{"text": "theory E4_5\n  imports 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\ninductive iter :: \"('a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> nat \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> bool\" for r where\niter0 : \"iter r n x x\" |\niter1 : \"r x y \\<Longrightarrow> iter r 1 x y \\<Longrightarrow> iter r n y z \\<Longrightarrow> iter r (n + 1) x z\" |\niter2 : \"iter r n x y \\<Longrightarrow> r y z \\<Longrightarrow> iter r (n + 1) x z\" |\niter3 : \"iter r n x y \\<Longrightarrow> iter r m y z \\<Longrightarrow> iter r (m + n) x z\"\n\nlemma star_trans[simp, intro] : \"star r x y \\<Longrightarrow> star r y z \\<Longrightarrow> star r x z\"\nproof (induction rule : star.induct)\n  case (refl x)\n  thus ?case by auto\nnext\n  case (step x y z)\n  thus ?case by (meson star.step)\nqed\n\nlemma \"iter r n x y \\<Longrightarrow> star r x y\"\nproof (induction rule : iter.induct)\n  case (iter0 n x)\n  then show ?case by (meson star.simps)\nnext\n  case (iter1 x y n z)\n  then show ?case by blast\nnext\n  case (iter2 n x y z)\n  then show ?case by (meson star.refl star.step star_trans)\nnext\n  case (iter3 n x y m z)\n  then show ?case by blast\nqed\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/chapter4/E4_5.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.897695283896349, "lm_q2_score": 0.782662489091802, "lm_q1q2_score": 0.7025924253402884}}
{"text": "theory Submission\nimports Defs \"HOL-Library.Sublist\"\nbegin\n\n\nsubsection \\<open>Some lemmas about \\<^const>\\<open>takeWhile\\<close> and \\<^const>\\<open>dropWhile\\<close>\\<close>\n\n(* TODO Move all of this *)\nlemma takeWhile_eq_Nil [simp]: \"xs = [] \\<or> \\<not>P (hd xs) \\<Longrightarrow> takeWhile P xs = []\"\n  by (cases xs) auto\n\nlemma dropWhile_eq_self [simp]: \"xs = [] \\<or> \\<not>P (hd xs) \\<Longrightarrow> dropWhile P xs = xs\"\n  by (cases xs) auto\n\nlemma takeWhile_append3: \"ys = [] \\<or> \\<not>P (hd ys) \\<Longrightarrow> takeWhile P (xs @ ys) = takeWhile P xs\"\n  by (induction xs) auto\n\nlemma takeWhile_append:\n  \"takeWhile P (xs @ ys) = (if \\<forall>x\\<in>set xs. P x then xs @ takeWhile P ys else takeWhile P xs)\"\n  using takeWhile_append1[of _ xs P ys] takeWhile_append2[of xs P ys] by auto\n\nlemma takeWhile_replicate: \"takeWhile P (replicate n x) = (if P x then replicate n x else [])\"\n  and dropWhile_replicate: \"dropWhile P (replicate n x) = (if P x then [] else replicate n x)\"\n  by (induction n; simp)+\n\nlemma takeWhile_replicate_True [simp]: \"P x \\<Longrightarrow> takeWhile P (replicate n x) = replicate n x\"\n  and takeWhile_replicate_False [simp]: \"\\<not>P x \\<Longrightarrow> takeWhile P (replicate n x) = []\"\n  and dropWhile_replicate_True [simp]: \"P x \\<Longrightarrow> dropWhile P (replicate n x) = []\"\n  and dropWhile_replicate_False [simp]: \"\\<not>P x \\<Longrightarrow> dropWhile P (replicate n x) = replicate n x\"\n  by (simp_all add: takeWhile_replicate dropWhile_replicate)\n\nlemma takeWhile_replicate_append_True [simp]:\n        \"P x \\<Longrightarrow> takeWhile P (replicate n x @ xs) = replicate n x @ takeWhile P xs\"\n  and takeWhile_replicate_append_False [simp]:\n        \"\\<not>P x \\<Longrightarrow> n > 0 \\<Longrightarrow> takeWhile P (replicate n x @ xs) = []\"\n  and dropWhile_replicate_append_True [simp]:\n        \"P x \\<Longrightarrow> dropWhile P (replicate n x @ xs) = dropWhile P xs\"\n  and dropWhile_replicate_append_False [simp]:\n        \"\\<not>P x \\<Longrightarrow> n > 0 \\<Longrightarrow> dropWhile P (replicate n x @ xs) = replicate n x @ xs\"\n     by (induction n; simp; fail)+\n\n\nsubsection \\<open>Applying a relation to successive elements in a list\\<close>\n\ninductive successively :: \"('a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> 'a list \\<Rightarrow> bool\" for P where\n  \"successively P []\"\n| \"successively P [x]\"\n| \"P x y \\<Longrightarrow> successively P (y # xs) \\<Longrightarrow> successively P (x # y # xs)\"\n\nlemmas [simp, intro] = successively.intros(1,2)\n\nlemma successively_Cons_Cons [simp]:\n  \"successively P (x # y # xs) \\<longleftrightarrow> P x y \\<and> successively P (y # xs)\"\n  by (subst successively.simps) auto\n\nlemma successively_Cons:\n  \"successively P (x # xs) \\<longleftrightarrow> xs = [] \\<or> P x (hd xs) \\<and> successively P xs\"\n  by (cases xs) auto\n\nlemma successively_ConsI [intro]:\n  \"P x (hd xs) \\<Longrightarrow> successively P xs \\<Longrightarrow> successively P (x # xs)\"\n  by (auto simp: successively_Cons)\n\nlemma successively_ConsD [dest]:\n  \"successively P (x # xs) \\<Longrightarrow> successively P xs\"\n  by (auto simp: successively_Cons)\n\nlemma successively_append_iff:\n  \"successively P (xs @ ys) \\<longleftrightarrow>\n     successively P xs \\<and> successively P ys \\<and> \n     (xs = [] \\<or> ys = [] \\<or> P (last xs) (hd ys))\"\n  by (induction xs) (auto simp: successively_Cons)\n\nlemma\n  assumes \"successively P (xs @ ys)\"\n  shows   successively_appendD1 [dest]: \"successively P xs\"\n    and   successively_appendD2 [dest]: \"successively P ys\"\n  using assms by (auto simp: successively_append_iff)\n\nlemma successively_appendI [intro?]:\n  assumes \"successively P xs\" \"successively P ys\" \"xs = [] \\<or> ys = [] \\<or> P (last xs) (hd ys)\"\n  shows   \"successively P (xs @ ys)\"\n  using assms by (auto simp: successively_append_iff)\n\nlemma successively_sublist:\n  assumes \"successively P ys\" \"sublist xs ys\"\n  shows   \"successively P xs\"\n  using assms by (auto simp: sublist_def)\n\nlemma sorted_wrt_imp_successively: \"sorted_wrt P xs \\<Longrightarrow> successively P xs\"\n  by (induction xs rule: induct_list012) auto\n\nlemma successively_conv_sorted_wrt:\n  assumes \"\\<And>x y z. x \\<in> set xs \\<Longrightarrow> y \\<in> set xs \\<Longrightarrow> z \\<in> set xs \\<Longrightarrow>\n                   P x y \\<Longrightarrow> P y z \\<Longrightarrow> P x z\"\n  shows   \"successively P xs \\<longleftrightarrow> sorted_wrt P xs\"\nproof\n  assume \"successively P xs\"\n  from this and assms show \"sorted_wrt P xs\"\n  proof (induction rule: successively.induct)\n    case (3 x y xs)\n    have IH: \"sorted_wrt P (y # xs)\"\n      using \"3.prems\" unfolding set_simps(2)[of _ \"y # xs\"] by (intro \"3.IH\") blast\n    have \"P x z\" if \"z \\<in> set xs\" for z\n    proof -\n      from \"3.hyps\" have \"P x y\"\n        by auto\n      moreover from IH and that have \"P y z\"\n        by auto\n      ultimately show \"P x z\"\n        using \"3.prems\" that by auto\n    qed\n    with IH and \\<open>P x y\\<close> show ?case by auto\n  qed auto\nqed (use sorted_wrt_imp_successively in blast)\n\nlemma successively_conv_sorted_wrt':\n  assumes \"transp P\"\n  shows   \"successively P xs \\<longleftrightarrow> sorted_wrt P xs\"\n  using assms unfolding transp_def\n  by (intro successively_conv_sorted_wrt) blast\n\n\nsubsection \\<open>Lists without repeated adjacent elements\\<close>\n\ndefinition adj_distinct where\n  \"adj_distinct = successively (\\<noteq>)\"\n\nlemmas adj_distinct_induct = successively.induct[of \"(\\<noteq>)\", folded adj_distinct_def, consumes 1]\n\nlemma adj_distinct_Nil [simp]: \"adj_distinct []\"\n  and adj_distinct_singleton [simp]: \"adj_distinct [x]\"\n  by (auto simp: adj_distinct_def)\n\nlemma adj_distinct_Cons_Cons [simp]: \"adj_distinct (x # y # xs) \\<longleftrightarrow> x \\<noteq> y \\<and> adj_distinct (y # xs)\"\n  by (auto simp: adj_distinct_def)\n\nlemma adj_distinct_Cons: \"adj_distinct (x # xs) \\<longleftrightarrow> xs = [] \\<or> x \\<noteq> hd xs \\<and> adj_distinct xs\"\n  by (cases xs) auto\n\nlemma adj_distinct_ConsI [intro?]: \"x \\<noteq> hd xs \\<and> adj_distinct xs \\<Longrightarrow> adj_distinct (x # xs)\"\n  by (cases xs) auto\n\nlemma adj_distinct_ConsD1 [dest]: \"adj_distinct (x # xs) \\<Longrightarrow> xs \\<noteq> [] \\<Longrightarrow> x \\<noteq> hd xs\"\n  by (cases xs) auto\n\nlemma adj_distinct_ConsD2 [dest]: \"adj_distinct (x # xs) \\<Longrightarrow> adj_distinct xs\"\n  by (cases xs) auto\n\nlemma adj_distinct_remdups_adj [intro]: \"adj_distinct (remdups_adj xs)\"\n  by (induction xs rule: remdups_adj.induct) (auto simp: adj_distinct_Cons)\n\nlemma adj_distinct_altdef: \"adj_distinct xs \\<longleftrightarrow> remdups_adj xs = xs\"\nproof\n  assume eq: \"remdups_adj xs = xs\"\n  have \"adj_distinct (remdups_adj xs)\"\n    by blast\n  with eq show \"adj_distinct xs\"\n    by simp\nnext\n  assume \"adj_distinct xs\"\n  thus \"remdups_adj xs = xs\"\n    by (induction rule: adj_distinct_induct) auto\nqed\n\nlemma adj_distinct_rev [simp]: \"adj_distinct (rev xs) \\<longleftrightarrow> adj_distinct xs\"\n  by (simp add: adj_distinct_altdef)\n\nlemma adj_distinct_append_iff:\n  \"adj_distinct (xs @ ys) \\<longleftrightarrow>\n     adj_distinct xs \\<and> adj_distinct ys \\<and> (xs = [] \\<or> ys = [] \\<or> last xs \\<noteq> hd ys)\"\n  by (auto simp: adj_distinct_def successively_append_iff)\n\nlemma adj_distinct_appendD1 [dest]: \"adj_distinct (xs @ ys) \\<Longrightarrow> adj_distinct xs\"\n  and adj_distinct_appendD2 [dest]: \"adj_distinct (xs @ ys) \\<Longrightarrow> adj_distinct ys\"\n  by (auto simp: adj_distinct_append_iff)\n\nlemma adj_distinct_sublist:\n  assumes \"adj_distinct ys\" \"sublist xs ys\"\n  shows   \"adj_distinct xs\"\n  using assms by (auto simp: sublist_def)\n\n\nsubsection \\<open>Run-length encoding\\<close>\n\nlemmas [termination_simp] = length_dropWhile_le\n\ntext \\<open>\n  The following function performs run-length encoding of a list, converting each run of \\<open>n > 0\\<close>\n  successive equal elements \\<open>x\\<close> into a single element \\<open>(x, n)\\<close>.\n\\<close>\n\nlemma length_rle: \"length (rle xs) \\<le> length xs\"\n  by (induction xs rule: rle.induct) (auto intro: order.trans[OF _ length_dropWhile_le])\n\nlemma rle_eq_Nil_iff [simp]: \"rle xs = [] \\<longleftrightarrow> xs = []\"\n  by (cases xs) auto\n\nlemma Nil_eq_rle_iff [simp]: \"[] = rle xs \\<longleftrightarrow> xs = []\"\n  by (cases xs) auto\n\nlemma rle_replicate: \"rle (replicate n x) = (if n = 0 then [] else [(x, n)])\"\n  by (cases n) auto\n\nlemma rle_replicate' [simp]: \"n > 0 \\<Longrightarrow> rle (replicate n x) = [(x, n)]\"\n  by (subst rle_replicate) auto\n\nlemma fst_hd_rle [simp]: \"xs \\<noteq> [] \\<Longrightarrow> fst (hd (rle xs)) = hd xs\"\n  by (cases xs) auto\n\nlemma map_fst_run_le [simp]: \"map fst (rle xs) = remdups_adj xs\"\n  by (induction xs rule: remdups_adj.induct) auto\n\nlemma fst_set_rle [simp]: \"fst ` set (rle xs) = set xs\"\nproof -\n  have \"fst ` set (rle xs) = set (map fst (rle xs))\"\n    by (rule set_map [symmetric])\n  also have \"map fst (rle xs) = remdups_adj xs\"\n    by simp\n  finally show ?thesis\n    by simp\nqed\n\nlemma snd_rle_pos: \"n \\<in> snd ` set (rle xs) \\<Longrightarrow> n > 0\"\n  by (induction xs rule: rle.induct) auto\n\n\ntext \\<open>\n  A valid run-length encoding contains no zero-length runs, and two adjacent runs always\n  have a different element.\n\\<close>\ndefinition valid_rle :: \"('a \\<times> nat) list \\<Rightarrow> bool\" where\n  \"valid_rle xs \\<longleftrightarrow> 0 \\<notin> snd ` set xs \\<and> adj_distinct (map fst xs)\"\n\nlemma valid_rle_append_iff [intro]:\n  \"valid_rle (xs @ ys) \\<longleftrightarrow>\n     valid_rle xs \\<and> valid_rle ys \\<and> (xs = [] \\<or> ys = [] \\<or> fst (last xs) \\<noteq> fst (hd ys))\"\n  by (auto simp: valid_rle_def adj_distinct_append_iff last_map hd_map)\n\nlemma \n  assumes \"valid_rle (xs @ ys)\"\n  shows valid_rle_appendD1 [dest]: \"valid_rle xs\"\n    and valid_rle_appendD2 [dest]: \"valid_rle ys\"\n  using assms by (auto simp: valid_rle_append_iff)\n\nlemma valid_rle_ConsD [dest]: \"valid_rle (x # xs) \\<Longrightarrow> valid_rle xs\"\n  by (auto simp: valid_rle_def)\n\nlemma valid_rle_rle [intro]: \"valid_rle (rle xs)\"\n  using snd_rle_pos[of _ xs] by (auto simp: valid_rle_def)\n\nlemma valid_rle_rev [simp]: \"valid_rle (rev xs) \\<longleftrightarrow> valid_rle xs\"\n  by (auto simp: valid_rle_def simp flip: rev_map)\n\n\n\ntext \\<open>\n  The inverse of the run-length encoding function:\n\\<close>\ndefinition unrle\n  where \"unrle = concat \\<circ> map (\\<lambda>(x, n). replicate n x)\"\n\nlemma unrle_Nil [simp]: \"unrle [] = []\"\n  and unrle_Cons [simp]: \"unrle (x # xs) = replicate (snd x) (fst x) @ unrle xs\"\n  and unrle_append [simp]: \"unrle (xs @ ys) = unrle xs @ unrle ys\"\n  and unrle_rev [simp]: \"unrle (rev xs) = rev (unrle xs)\"\n  by (auto simp: unrle_def case_prod_unfold rev_concat rev_map o_def)\n\nlemma unrle_eq_Nil_iff [simp]: \"unrle xs = [] \\<longleftrightarrow> snd ` set xs \\<subseteq> {0}\"\n  by (induction xs) auto\n\nlemma unrle_Nil_eq_iff [simp]: \"Nil = unrle xs \\<longleftrightarrow> snd ` set xs \\<subseteq> {0}\"\n  by (induction xs) auto\n\nlemma hd_unrle [simp]: \"xs \\<noteq> [] \\<Longrightarrow> snd (hd xs) > 0 \\<Longrightarrow> hd (unrle xs) = fst (hd xs)\"\n  by (cases xs) (auto simp: unrle_def)\n\nlemma unrle_map_1 [simp]: \"unrle (map (\\<lambda>x. (x, Suc 0)) xs) = xs\"\n  by (induction xs) (auto simp: unrle_def o_def)\n\n\nlemma unrle_rle [simp]: \"unrle (rle xs) = xs\"\nproof (induction xs rule: rle.induct) \n  case (2 x xs)\n  have \"replicate (length (takeWhile (\\<lambda>y. y = x) xs)) x = takeWhile (\\<lambda>y. y = x) xs\"\n    by (induction xs) auto\n  thus ?case\n    using 2 by simp\nqed auto\n\nlemma rle_unrle [simp]:\n  assumes \"valid_rle xs\"\n  shows   \"rle (unrle xs) = xs\"\n  using assms\nproof (induction xs)\n  case (Cons x' xs)\n  obtain x n where [simp]: \"x' = (x, n)\"\n    by (cases x')\n  have [simp]: \"n > 0\" \"n \\<noteq> 0\"\n    using Cons.prems by (auto simp: valid_rle_def)\n  show ?case\n  proof (cases \"xs = []\")\n    case [simp]: False\n    have [simp]: \"snd (hd xs) > 0\" \"x \\<noteq> fst (hd xs)\"\n      using Cons.prems by (auto simp: valid_rle_def adj_distinct_Cons hd_map)\n    have \"takeWhile (\\<lambda>y. y = x) (unrle xs) = []\"\n         \"dropWhile (\\<lambda>y. y = x) (unrle xs) = unrle xs\"\n      by (subst takeWhile_eq_Nil dropWhile_eq_self; force; fail)+\n    hence \"rle (replicate n x @ unrle xs) = (x, n) # rle (unrle xs)\"\n      by (cases n) auto\n    thus ?thesis\n      using Cons by (auto simp: valid_rle_def adj_distinct_Cons hd_unrle)\n  qed auto\nqed auto\n\ntext \\<open>\n  The \\<^const>\\<open>unrle\\<close> function is injective on all valid run-length encodings\n\\<close>\nlemma unrle_eqD [simp]:\n  assumes \"valid_rle xs\" \"valid_rle ys\"\n  assumes \"unrle xs = unrle ys\"\n  shows   \"xs = ys\"\nproof -\n  have \"rle (unrle xs) = rle (unrle ys)\"\n    by (simp add: assms(3))\n  with assms(1,2) show ?thesis\n    by (subst (asm) (1 2) rle_unrle) auto\nqed\n\ntext \\<open>\n  The injectivity of \\<^const>\\<open>unrle\\<close> allows us to show several properties of \\<^const>\\<open>rle\\<close> more\n  easily using the following lemma:\n\\<close>\nlemma rle_eqI:\n  assumes \"valid_rle ys\" \"unrle ys = xs\"\n  shows \"rle xs = ys\"\n  by (rule unrle_eqD) (use assms in auto)\n\nlemma rle_rev [simp]: \"rle (rev xs) = rev (rle xs)\"\n  by (rule rle_eqI) auto\n\nlemma fst_last_rle [simp]: \"xs \\<noteq> [] \\<Longrightarrow> fst (last (rle xs)) = last xs\"\n  by (simp flip: hd_rev rle_rev)\n\nlemma rle_append:\n  assumes \"xs = [] \\<or> ys = [] \\<or> last xs \\<noteq> hd ys\"\n  shows   \"rle (xs @ ys) = rle xs @ rle ys\"\n  by (rule rle_eqI) (use assms in \\<open>auto simp: valid_rle_append_iff\\<close>)\n\nlemma rle_of_adj_distinct: \"adj_distinct xs \\<Longrightarrow> rle xs = map (\\<lambda>x. (x, 1)) xs\"\n  by (rule rle_eqI) (auto simp: valid_rle_def o_def)\n\n\nlemma rle_rev_if_rle_append: \"(xs = [] \\<or> ys = [] \\<or> last xs \\<noteq> hd ys \\<Longrightarrow> rle (xs @ ys) = rle xs @ rle ys)\n       \\<Longrightarrow>rle (rev xs) = rev (rle xs)\"\n  by (rule rle_eqI) auto\n\n\nend", "meta": {"author": "maxhaslbeck", "repo": "proofground2020-solutions", "sha": "023ec2643f6aa06e60bec391e20f178c258ea1a3", "save_path": "github-repos/isabelle/maxhaslbeck-proofground2020-solutions", "path": "github-repos/isabelle/maxhaslbeck-proofground2020-solutions/proofground2020-solutions-023ec2643f6aa06e60bec391e20f178c258ea1a3/favourite_computer_game/Isabelle/eberlm_the_elder/Submission.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006919925839875, "lm_q2_score": 0.8774767762675405, "lm_q1q2_score": 0.7025886284358308}}
{"text": "theory Sorted\nimports \"$HIPSTER_HOME/IsaHipster\"\n\nbegin\ndatatype Nat = \n  Z\n  | Succ \"Nat\"\n\nfun leq :: \"Nat => Nat => bool\"\nwhere\n  \"leq Z y = True\"\n| \"leq x Z = False\"\n| \"leq (Succ x) (Succ y) = leq x y\"\n\n(*hipster leq*)\nlemma lemma_a [thy_expl]: \"leq x2 x2 = True\"\nby (hipster_induct_simp_metis Sorted.leq.simps)\n\nlemma lemma_aa [thy_expl]: \"leq x2 (Succ x2) = True\"\nby (hipster_induct_simp_metis Sorted.leq.simps)\n\nlemma lemma_ab [thy_expl]: \"leq (Succ x2) x2 = False\"\nby (hipster_induct_simp_metis Sorted.leq.simps)\n\nfun sorted :: \"Nat list => bool\"\nwhere\n  \"sorted [] = True\"\n| \"sorted [x] = True\"\n| \"sorted (x # y # xs) = ((leq x y) \\<and> (sorted (y#xs)))\"\nthm sorted.induct\n\nfun last :: \"'a list \\<Rightarrow> 'a\" where\n  \"last ([t]) = t\"\n| \"last (_ # ts) = last ts\"\nthm last.induct\n\nfun ins :: \" Nat => Nat list => Nat list\"\nwhere\n \"ins x [] = [x]\"\n|\"ins x (y#ys) = (if (leq x y) then (x#y#ys) else (y#(ins x ys)))\"\nthm ins.induct\n\n(*hipster sorted ins*)\nlemma lemma_ac [thy_expl]: \"leq x2 x2 = True\"\nby (tactic \\<open>Hipster_Tacs.induct_simp_metis @{context} @{thms Sorted.sorted.simps Sorted.ins.simps thy_expl}\\<close>)\n\nlemma lemma_ad [thy_expl]: \"Sorted.sorted (ins Z x2) = Sorted.sorted x2\"\nby (tactic \\<open>Hipster_Tacs.induct_simp_metis @{context} @{thms Sorted.sorted.simps Sorted.ins.simps thy_expl}\\<close>)\n\nlemma unknown [thy_expl]: \"ins Z (ins x y) = ins x (ins Z y)\"\noops\n\nlemma unknown [thy_expl]: \"ins x (ins y z) = ins y (ins x z)\"\noops\n\nlemma unknown [thy_expl]: \"Sorted.sorted (ins x y) = Sorted.sorted y\"\noops\n\nfun isort :: \"Nat list => Nat list\"\nwhere\n  \"isort [] = []\"\n| \"isort (x#xs) = ins x (isort xs)\"\n\nlemma unknown [thy_expl]: \"Sorted.sorted x \\<Longrightarrow> isort x = x\"\noops\n\n(*hipster sorted ins isort*)\n(*hipster_cond sorted isort*)\nML \\<open>\n  val _ = Proof_Context.init_global\n\\<close>\n(*hipster_cond sorted isort leq sorted ins*)\nlemma lemma_ae [thy_expl]: \"ins Z (isort x2) = isort (ins Z x2)\"\nby (hipster_induct_simp_metis Sorted.sorted.simps Sorted.isort.simps Sorted.leq.simps Sorted.sorted.simps Sorted.ins.simps)\n(*\nlemma unknown [thy_expl]: \"ins x (ins y z) = ins y (ins x z)\"\noops\n\nlemma unknown [thy_expl]: \"Sorted.sorted (ins x y) = Sorted.sorted y\"\noops\n\nlemma unknown [thy_expl]: \"isort (ins x y) = ins x (isort y)\"\noops\n\nlemma unknown [thy_expl]: \"Sorted.sorted (isort x) = True\"\noops\n\nlemma unknown [thy_expl]: \"isort (isort x) = isort x\"\noops\n\nlemma unknown [thy_expl]: \"ins Z (ins x y) = ins x (ins Z y)\"\noops\n\nlemma unknown [thy_expl]: \"Sorted.sorted x \\<Longrightarrow> isort x = x\"\noops *)\n\nlemma insSortInvarZ [simp] : \"sorted ts \\<Longrightarrow> sorted (ins Z ts)\"\nby (hipster_induct_simp_metis Sorted.sorted.simps Sorted.ins.simps)\nlemma insSortInvar: \"sorted ts \\<Longrightarrow> sorted (ins x ts)\"\napply(case_tac x)\napply(simp_all)\napply(induction ts rule: ins.induct)\napply(simp_all)\napply (hipster_induct_simp_metis Sorted.sorted.simps Sorted.ins.simps Sorted.leq.simps)\noops\n\n(*\nlemma unknown [thy_expl]: \"Sorted.sorted y \\<Longrightarrow> Sorted.sorted (ins x y) = True\"\noops\n\nlemma unknown [thy_expl]: \"Sorted.sorted y \\<Longrightarrow> isort (ins x y) = ins x y\"\noops\n\nlemma unknown [thy_expl]: \"Sorted.sorted x \\<Longrightarrow> isort (ins Z x) = ins Z x\"\noops *)\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/Examples/Sorted.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297941266014, "lm_q2_score": 0.7799928951399098, "lm_q1q2_score": 0.7024068412805548}}
{"text": "(*  Title:      HOL/Examples/AckermannM.thy\n    Author:     Larry Paulson\n*)\n\nsection \\<open>A Tail-Recursive, Stack-Based Ackermann's Function\\<close>\n\ntext \\<open>Unlike the other Ackermann example, 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\u2013476.\\<close>\n\ntheory AckermannM 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\ntext\\<open>Setting up the termination proof for the stack-based version.\\<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>Here is the stack-based version, which uses lists.\\<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\ntermination\n  by (relation \"inv_image {(x,y). x<y} ack_mset\") (auto simp: wf case1)\n\ntext \\<open>Unlike the other Ackermann theory, no extra function is needed to prove equivalence\\<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: \"ack m n = ackloop [n,m]\"\n  by (simp add: ackloop_ack)\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/AckermannM.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619350028204, "lm_q2_score": 0.8519528076067261, "lm_q1q2_score": 0.702402660290527}}
{"text": "(*  \n    Author:      Ren\u00e9 Thiemann \n                 Akihisa Yamada\n    License:     BSD\n*)\nsection \\<open>Neville Aitken Interpolation\\<close>\n\ntext \\<open>We prove soundness of Neville-Aitken's polynomial interpolation algorithm \n  using the recursive formula directly. We further provide an implementation \n  which avoids the exponential branching in the recursion.\\<close>\n\ntheory Neville_Aitken_Interpolation\nimports \n  \"HOL-Computational_Algebra.Polynomial\"\nbegin\n\ncontext\n  fixes x :: \"nat \\<Rightarrow> 'a :: field\"\n  and f :: \"nat \\<Rightarrow> 'a\"\nbegin\n\nprivate definition X :: \"nat \\<Rightarrow> 'a poly\" where [code_unfold]: \"X i = [:-x i, 1:]\"\n\nfunction neville_aitken_main :: \"nat \\<Rightarrow> nat \\<Rightarrow> 'a poly\" where\n  \"neville_aitken_main i j = (if i < j then \n      (smult (inverse (x j - x i)) (X i * neville_aitken_main (i + 1) j -\n      X j * neville_aitken_main i (j - 1))) \n    else [:f i:])\"\n  by pat_completeness auto\n\ntermination by (relation \"measure (\\<lambda> (i,j). j - i)\", auto)\n\ndefinition neville_aitken :: \"nat \\<Rightarrow> 'a poly\" where\n  \"neville_aitken = neville_aitken_main 0\"\n\ndeclare neville_aitken_main.simps[simp del]\n\nlemma neville_aitken_main: assumes dist: \"\\<And> i j. i < j \\<Longrightarrow> j \\<le> n \\<Longrightarrow> x i \\<noteq> x j\"\n  shows \"i \\<le> k \\<Longrightarrow> k \\<le> j \\<Longrightarrow> j \\<le> n \\<Longrightarrow> poly (neville_aitken_main i j) (x k) = (f k)\"\nproof (induct i j arbitrary: k rule: neville_aitken_main.induct)\n  case (1 i j k)\n  note neville_aitken_main.simps[of i j, simp]\n  show ?case\n  proof (cases \"i < j\")\n    case False\n    with 1(3-) have \"k = i\" by auto\n    with False show ?thesis by auto\n  next\n    case True note ij = this\n    from dist[OF True 1(5)] have diff: \"x i \\<noteq> x j\" by auto\n    from True have id: \"neville_aitken_main i j = \n      (smult (inverse (x j - x i)) (X i * neville_aitken_main (i + 1) j - X j \n        * neville_aitken_main i (j - 1)))\" by simp\n    note IH = 1(1-2)[OF True]\n    show ?thesis\n    proof (cases \"k = i\")\n      case True\n      show ?thesis unfolding id True poly_smult using IH(2)[of i] ij 1(3-) diff\n        by (simp add: X_def field_simps)\n    next\n      case False note ki = this\n      show ?thesis \n      proof (cases \"k = j\")\n        case True\n        show ?thesis unfolding id True poly_smult using IH(1)[of j] ij 1(3-) diff\n          by (simp add: X_def field_simps)\n      next\n        case False\n        with ki show ?thesis unfolding id poly_smult using IH(1-2)[of k] ij 1(3-) diff\n          by (simp add: X_def field_simps)\n      qed\n    qed\n  qed\nqed\n\nlemma degree_neville_aitken_main: \"degree (neville_aitken_main i j) \\<le> j - i\"\nproof (induct i j rule: neville_aitken_main.induct)\n  case (1 i j)\n  note simp = neville_aitken_main.simps[of i j]\n  show ?case\n  proof (cases \"i < j\")\n    case False\n    thus ?thesis unfolding simp by simp\n  next\n    case True\n    note IH = 1[OF this]\n    let ?n = neville_aitken_main\n    have X: \"\\<And> i. degree (X i) = Suc 0\" unfolding X_def by auto\n    have \"degree (X i * ?n (i + 1) j) \\<le> Suc (degree (?n (i+1) j))\"\n      by (rule order.trans[OF degree_mult_le], simp add: X)\n    also have \"\\<dots> \\<le> Suc (j - (i+1))\" using IH(1) by simp\n    finally have 1: \"degree (X i * ?n (i + 1) j) \\<le> j - i\" using True by auto\n    have \"degree (X j * ?n i (j - 1)) \\<le> Suc (degree (?n i (j - 1)))\"\n      by (rule order.trans[OF degree_mult_le], simp add: X)\n    also have \"\\<dots> \\<le> Suc ((j - 1) - i)\" using IH(2) by simp\n    finally have 2: \"degree (X j * ?n i (j - 1)) \\<le> j - i\" using True by auto\n    have id: \"?n i j = smult (inverse (x j - x i))\n            (X i * ?n (i + 1) j - X j * ?n i (j - 1))\" unfolding simp using True by simp\n    have \"degree (?n i j) \\<le> degree (X i * ?n (i + 1) j - X j * ?n i (j - 1))\"\n      unfolding id by simp\n    also have \"\\<dots> \\<le> max (degree (X i * ?n (i + 1) j)) (degree (X j * ?n i (j - 1)))\"\n      by (rule degree_diff_le_max)\n    also have \"\\<dots> \\<le> j - i\" using 1 2 by auto\n    finally show ?thesis .\n  qed\nqed\n\nlemma degree_neville_aitken: \"degree (neville_aitken n) \\<le> n\"\n  unfolding neville_aitken_def using degree_neville_aitken_main[of 0 n] by simp\n\nfun neville_aitken_merge :: \"('a \\<times> 'a \\<times> 'a poly) list \\<Rightarrow> ('a \\<times> 'a \\<times> 'a poly) list\" where\n  \"neville_aitken_merge ((xi,xj,p_ij) # (xsi,xsj,p_sisj) # rest) = \n     (xi,xsj, smult (inverse (xsj - xi)) ([:-xi,1:] * p_sisj\n      + [:xsj,-1:] * p_ij)) # neville_aitken_merge ((xsi,xsj,p_sisj) # rest)\"\n| \"neville_aitken_merge [_] = []\"\n| \"neville_aitken_merge [] = []\"\n\nlemma length_neville_aitken_merge[termination_simp]: \"length (neville_aitken_merge xs) = length xs - 1\"\n  by (induct xs rule: neville_aitken_merge.induct, auto)\n\nfun neville_aitken_impl_main :: \"('a \\<times> 'a \\<times> 'a poly) list \\<Rightarrow> 'a poly\" where\n  \"neville_aitken_impl_main (e1 # e2 # es) = \n     neville_aitken_impl_main (neville_aitken_merge (e1 # e2 # es))\"\n| \"neville_aitken_impl_main [(_,_,p)] = p\"\n| \"neville_aitken_impl_main [] = 0\"\n\nlemma neville_aitken_merge: \n  \"xs = map (\\<lambda> i. (x i, x (i + j), neville_aitken_main i (i + j)))  [l ..< Suc (l + k)] \n   \\<Longrightarrow> neville_aitken_merge xs\n       = (map (\\<lambda> i. (x i, x (i + Suc j), neville_aitken_main i (i + Suc j))) [l ..< l + k])\"\nproof (induct xs arbitrary: l k rule: neville_aitken_merge.induct)\n  case (1 xi xj p_ij xsi xsj p_sisj rest l k)\n  let ?n = neville_aitken_main\n  let ?f = \"\\<lambda> j i. (x i, x (i + j), ?n i (i + j))\"\n  define f where \"f = ?f\"\n  let ?map = \"\\<lambda> j. map (?f j)\"\n  note res = 1(2)\n  from arg_cong[OF res, of length] obtain kk where k: \"k = Suc kk\" by (cases k, auto)\n  hence id: \"[l..<Suc (l + k)] = l # [Suc l ..< Suc (Suc l + kk)]\"\n    by (simp add: upt_rec)\n  from res[unfolded id] have id2: \"(xsi, xsj, p_sisj) # rest =\n    ?map j [Suc l..< Suc (Suc l + kk)]\" \n    and id3: \"xi = x l\" \"xj = x (l + j)\" \"p_ij = ?n l (l + j)\" \n        \"xsi = x (Suc l)\" \"xsj = x (Suc (l + j))\" \"p_sisj = ?n (Suc l) (Suc (l + j))\"\n      by (auto simp: upt_rec)\n  note IH = 1(1)[OF id2]\n  have X: \"[:x (Suc (l + j)), - 1:] = - X (Suc l + j)\" unfolding X_def by simp\n  have id4: \"(xi, xsj, smult (inverse (xsj - xi)) ([:- xi, 1:] * p_sisj +\n     [:xsj, - 1:] * p_ij)) = (x l, x (l + Suc j), ?n l (l + Suc j))\"\n    unfolding id3 neville_aitken_main.simps[of l \"l + Suc j\"] \n      X_def[symmetric] X by simp\n  have id5: \"[l..<l + k] = l # [Suc l ..< Suc l + kk]\" unfolding k\n    by (simp add: upt_rec)\n  show ?case unfolding neville_aitken_merge.simps IH id4\n    unfolding id5 by simp\nqed auto\n\nlemma neville_aitken_impl_main: \n  \"xs = map (\\<lambda> i. (x i, x (i + j), neville_aitken_main i (i + j)))  [l ..< Suc (l + k)] \n   \\<Longrightarrow> neville_aitken_impl_main xs = neville_aitken_main l (l + j + k)\"\nproof (induct xs arbitrary: l k j rule: neville_aitken_impl_main.induct)\n  case (1 e1 e2 es l k j)\n  note res = 1(2)\n  from res obtain kk where k: \"k = Suc kk\" by (cases k, auto)\n  hence id1: \"l + k = Suc (l + kk)\" by auto\n  show ?case unfolding neville_aitken_impl_main.simps 1(1)[OF neville_aitken_merge[OF 1(2), unfolded id1]]\n    by (simp add: k)\nqed auto\n\n\n\nlemma neville_aitken: assumes \"\\<And> i j. i < j \\<Longrightarrow> j \\<le> n \\<Longrightarrow> x i \\<noteq> x j\"\n  shows \"j \\<le> n \\<Longrightarrow> poly (neville_aitken x f n) (x j) = (f j)\"\n  unfolding neville_aitken_def\n  by (rule neville_aitken_main[OF assms, of n], auto)\n\ndefinition neville_aitken_interpolation_poly :: \"('a :: field \\<times> 'a)list \\<Rightarrow> 'a poly\" where\n  \"neville_aitken_interpolation_poly x_fs = (let \n    start = map (\\<lambda> (xi,fi). (xi,xi,[:fi:])) x_fs in \n    neville_aitken_impl_main start)\"\n\nlemma neville_aitken_interpolation_impl: assumes \"x_fs \\<noteq> []\"\n  shows \"neville_aitken_interpolation_poly x_fs =\n  neville_aitken (\\<lambda> i. fst (x_fs ! i)) (\\<lambda> i. snd (x_fs ! i)) (length x_fs - 1)\"\nproof -\n  from assms have id: \"Suc (length x_fs - 1) = length x_fs\" by auto\n  show ?thesis\n    unfolding neville_aitken_interpolation_poly_def Let_def\n    by (rule neville_aitken_impl, unfold id, rule nth_equalityI, auto split: prod.splits)\nqed\n  \nlemma neville_aitken_interpolation_poly: assumes dist: \"distinct (map fst xs_ys)\"\n  and p: \"p = neville_aitken_interpolation_poly xs_ys\"\n  and xy: \"(x,y) \\<in> set xs_ys\"\n  shows \"poly p x = y\"\nproof -\n  have p: \"p = neville_aitken (\\<lambda> i. fst (xs_ys ! i)) (\\<lambda> i. snd (xs_ys ! i)) (length xs_ys - 1)\"\n    unfolding p\n    by (rule neville_aitken_interpolation_impl, insert xy, auto)\n  from xy obtain i where i: \"i < length xs_ys\" and x: \"x = fst (xs_ys ! i)\" and y: \"y = snd (xs_ys ! i)\"\n    unfolding set_conv_nth by (metis fst_conv in_set_conv_nth snd_conv xy)\n  show ?thesis unfolding p x y\n  proof (rule neville_aitken)\n    fix i j\n    show \"i < j \\<Longrightarrow> j \\<le> length xs_ys - 1 \\<Longrightarrow> fst (xs_ys ! i) \\<noteq> fst (xs_ys ! j)\" using dist\n      by (metis (mono_tags, lifting) One_nat_def diff_less dual_order.strict_trans2 length_map \n        length_pos_if_in_set lessI less_or_eq_imp_le neq_iff nth_eq_iff_index_eq nth_map xy)\n  qed (insert i, auto)\nqed\n\nlemma degree_neville_aitken_interpolation_poly:  \n  shows \"degree (neville_aitken_interpolation_poly xs_ys) \\<le> length xs_ys - 1\"\nproof (cases \"length xs_ys\")\n  case 0\n  hence id: \"xs_ys = []\" by (cases xs_ys, auto)\n  show ?thesis unfolding id neville_aitken_interpolation_poly_def Let_def by simp\nnext\n  case (Suc nn)\n  have id: \"neville_aitken_interpolation_poly xs_ys = \n    neville_aitken (\\<lambda> i. fst (xs_ys ! i)) (\\<lambda> i. snd (xs_ys ! i)) (length xs_ys - 1)\"\n    by (rule neville_aitken_interpolation_impl, insert Suc, auto)\n  show ?thesis unfolding id by (rule degree_neville_aitken)\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/Neville_Aitken_Interpolation.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.851952809486198, "lm_q2_score": 0.8244619220634456, "lm_q1q2_score": 0.7024026508163433}}
{"text": "theory Submission\n  imports Defs\nbegin\n\ntheorem solution:\n  fixes G (structure) and H (structure) and f\n  assumes\n    hom: \"f \\<in> hom G H\" and\n    group_G: \"group G\" and\n    group_H: \"group H\" and\n    h1: \"\\<forall>a b. a \\<otimes> b \\<otimes> inv a \\<otimes> inv b \\<in> group.center G\" and\n    h2: \"\\<forall>x \\<in> group.center G. f x = \\<one>\\<^bsub>H\\<^esub> \\<longrightarrow> x = \\<one>\"\n  shows \"inj_on f (carrier G)\"\nproof -\n  have \"\\<forall> a \\<in> carrier G. f a = \\<one>\\<^bsub>H\\<^esub> \\<longrightarrow> a = \\<one>\"\n  proof safe\n    fix a :: 'a\n    assume [simp]: \\<open>a \\<in> carrier G\\<close> and [simp]: \\<open>f a = \\<one>\\<^bsub>H\\<^esub>\\<close>\n    then have \"a \\<in> group.center G\"\n      unfolding group.center_def[OF group_G]\n    proof safe\n      fix g :: 'a\n      assume [simp]: \\<open>g \\<in> carrier G\\<close>\n      note h[simp] = hom_mult[OF hom] hom_one[OF hom]\n      note closed[simp] = monoid.m_closed[OF group.is_monoid, OF group_G] hom_in_carrier[OF hom]\n      note group[simp] = group_G group_H group.is_monoid\n      have \"f (a \\<otimes> g \\<otimes> inv a \\<otimes> inv g) = \\<one>\\<^bsub>H\\<^esub>\"\n      proof -\n        have [simp]: \"f (inv a) = inv\\<^bsub>H\\<^esub> (f a)\"\n          by (metis \\<open>a \\<in> carrier G\\<close> \\<open>f a = \\<one>\\<^bsub>H\\<^esub>\\<close> group.inv_closed group.l_cancel_one' group.l_inv\n                group_G group_H h hom hom_in_carrier)\n        have \"f (a \\<otimes> g \\<otimes> inv a \\<otimes> inv g) = f a \\<otimes>\\<^bsub>H\\<^esub> f g \\<otimes>\\<^bsub>H\\<^esub> f (inv a) \\<otimes>\\<^bsub>H\\<^esub> f (inv g)\"\n          by simp\n        also have \"\\<dots> = f g \\<otimes>\\<^bsub>H\\<^esub> f (inv g)\"\n          by (simp add: monoid.inv_one)\n        also have \"\\<dots> = \\<one>\\<^bsub>H\\<^esub>\"\n          by (simp flip: h add: group.r_inv)\n        finally show ?thesis .\n      qed\n      with h1 h2 have \"a \\<otimes> g \\<otimes> inv a \\<otimes> inv g = \\<one>\"\n        by auto\n      then show \\<open>a \\<otimes> g = g \\<otimes> a\\<close>\n        by (subst group.inv_solve_right'[symmetric]; simp) (subst (asm) group.inv_solve_right'; simp)\n    qed\n    with h2 \\<open>f a = \\<one>\\<^bsub>H\\<^esub>\\<close> show \\<open>a = \\<one>\\<close>\n      by simp\n  qed\n  with hom have \"f \\<in> mon G H\"\n    unfolding mon_iff_hom_one[OF group_G group_H] by simp\n  then show ?thesis \\<comment> \\<open>Missing \\<open>monoid_hom.injective_iff\\<close> from Lean here\\<close>\n    unfolding mon_def by simp\nqed\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/group-theory/isabelle/wimmers/Submission.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8856314677809303, "lm_q2_score": 0.7931059609645724, "lm_q1q2_score": 0.7023995963148595}}
{"text": "\\<^marker>\\<open>creator \"Kevin Kappelmann\"\\<close>\nparagraph \\<open>Irreflexive\\<close>\ntheory Binary_Relations_Irreflexive\n  imports\n    Binary_Relation_Functions\n    HOL_Syntax_Bundles_Lattices\nbegin\n\nconsts irreflexive_on :: \"'a \\<Rightarrow> ('b \\<Rightarrow> 'b \\<Rightarrow> bool) \\<Rightarrow> bool\"\n\noverloading\n  irreflexive_on_pred \\<equiv> \"irreflexive_on :: ('a \\<Rightarrow> bool) \\<Rightarrow> ('a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> bool\"\nbegin\n  definition \"irreflexive_on_pred P R \\<equiv> \\<forall>x. P x \\<longrightarrow> \\<not>(R x x)\"\nend\n\nlemma irreflexive_onI [intro]:\n  assumes \"\\<And>x. P x \\<Longrightarrow> \\<not>(R x x)\"\n  shows \"irreflexive_on P R\"\n  using assms unfolding irreflexive_on_pred_def by blast\n\nlemma irreflexive_onD [dest]:\n  assumes \"irreflexive_on P R\"\n  and \"P x\"\n  shows \"\\<not>(R x x)\"\n  using assms unfolding irreflexive_on_pred_def by blast\n\ndefinition \"irreflexive (R :: 'a \\<Rightarrow> _) \\<equiv> irreflexive_on (\\<top> :: 'a \\<Rightarrow> bool) R\"\n\nlemma irreflexive_eq_irreflexive_on:\n  \"irreflexive (R :: 'a \\<Rightarrow> _) = irreflexive_on (\\<top> :: 'a \\<Rightarrow> bool) R\"\n  unfolding irreflexive_def ..\n\nlemma irreflexiveI [intro]:\n  assumes \"\\<And>x. \\<not>(R x x)\"\n  shows \"irreflexive R\"\n  unfolding irreflexive_eq_irreflexive_on using assms by (intro irreflexive_onI)\n\nlemma irreflexiveD:\n  assumes \"irreflexive R\"\n  shows \"\\<not>(R x x)\"\n  using assms unfolding irreflexive_eq_irreflexive_on by auto\n\nlemma irreflexive_on_if_irreflexive:\n  fixes P :: \"'a \\<Rightarrow> bool\" and R :: \"'a \\<Rightarrow> _\"\n  assumes \"irreflexive R\"\n  shows \"irreflexive_on P R\"\n  using assms by (intro irreflexive_onI) (blast dest: irreflexiveD)\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_Irreflexive.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324713956856, "lm_q2_score": 0.8615382058759129, "lm_q1q2_score": 0.7023539207780254}}
{"text": "theory Chap2\nimports Main\n\nbegin\n\ndatatype nat = Zero | Suc nat\n\nfun add :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\" where\n\"add Zero n = n\" | \n\"add (Suc m) n = Suc(add m n)\"\n\nlemma add_02: \"add m Zero = m\"\napply(induction m)\napply(auto)\ndone\n\nend\n\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/chapter2/Chap2.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9196425399873763, "lm_q2_score": 0.7634837581726991, "lm_q1q2_score": 0.7021321426050487}}
{"text": "theory \"Traceable-Objects\"\nimports Main\nbegin\n\nsection \\<open>A few properties of foldl\\<close>\n\nlemma l1:\"foldl (o) a (rev (x#xs)) = (foldl (o) a (rev xs)) o x\"\n  by simp\n\nlemma l2:\"foldl (o) a (x#xs) = a o (foldl (o) x xs)\"\nproof (induct \"rev xs\" arbitrary:a x xs)\n  case Nil\n  then show ?case\n    by auto \nnext\n  case (Cons a xa)\n  then show ?case\n    by (metis (no_types, lifting) append_Cons comp_assoc l1 rev.simps(2) rev_swap) \nqed\n\nlemma l3:\"foldl (o) x xs = x o (foldl (o) id xs)\"\n  by (metis comp_id foldl_Cons l2)\n\ntext \\<open>TODO: this could be generalized to multiplicative commutative monoids \n(functions with the composition operation are a multiplicative commutative monoid).\\<close>\n\nsection \\<open>Data types and traceability\\<close>\n\nlocale data_type = \n  fixes f :: \"'b \\<Rightarrow> 'a \\<Rightarrow> 'a\" \\<comment> \\<open>the transition function of the data type\\<close>\n  and init :: \"'a\"\nbegin\n\ndefinition exec \\<comment> \\<open>a state transformer corresponding to applying all operations in order\\<close>\n  where \"exec ops \\<equiv> foldl (o) id (map f ops)\" \\<comment> \\<open>@{term \"(o)\"} is function composition \\<close>\n\nlemma exec_Cons:\"exec (x#xs) = (f x) o (exec xs)\"\n  using exec_def l3 by force\n\nlemma exec_Nil:\"exec [] = id\"\n  by (simp add: exec_def)\n\ndefinition is_traceable \\<comment> \\<open>A state has a unique history from the initial state\\<close>\n  where \"is_traceable \\<equiv> \\<forall> ops\\<^sub>1 ops\\<^sub>2 . exec ops\\<^sub>1 init = exec ops\\<^sub>2 init \\<longrightarrow> ops\\<^sub>1 = ops\\<^sub>2\"\n  \nend\n\nlocale traceable_data_type = data_type f init for f init +\n  assumes traceable:\"is_traceable\"\nbegin\n\ntext \\<open>Prove some facts about traceable datatypes...\\<close>\n\nend\n\nsection \\<open>Append-only lists are traceable\\<close>\n\ninterpretation list_data_type: data_type \"(#)\" \"[]\" .\n\nlemma l4:\"list_data_type.exec xs [] =  xs\"\nproof (induct xs)\n  case Nil\n  then show ?case\n    by (simp add: list_data_type.exec_Nil) \nnext\n  case (Cons a xs) \n  then show ?case \n    by (simp add: data_type.exec_Cons)\nqed\n\ninterpretation list_traceable:traceable_data_type \"(#)\" \"[]\"\n  using l4 list_data_type.is_traceable_def traceable_data_type_def by fastforce\n\ntext \\<open>Now the facts proved about traceable datatypes are available for append-only lists.\\<close>\n\nend", "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/Traceable-Objects.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278726384089, "lm_q2_score": 0.7956581000631541, "lm_q1q2_score": 0.7021108845862474}}
{"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_list_nat_perm_trans\nimports \"../../Test_Base\"\nbegin\n\ndatatype 'a list = nil2 | cons2 \"'a\" \"'a list\"\n\nfun elem :: \"'a => 'a list => bool\" where\n\"elem x (nil2) = False\"\n| \"elem x (cons2 z xs) = ((z = x) | (elem x xs))\"\n\nfun deleteBy :: \"('a => ('a => bool)) => 'a => 'a list =>\n                 'a list\" where\n\"deleteBy x y (nil2) = nil2\"\n| \"deleteBy x y (cons2 y2 ys) =\n     (if (x y) y2 then ys else cons2 y2 (deleteBy x y ys))\"\n\nfun isPermutation :: \"'a list => 'a list => bool\" where\n\"isPermutation (nil2) (nil2) = True\"\n| \"isPermutation (nil2) (cons2 z x2) = False\"\n| \"isPermutation (cons2 x3 xs) y =\n     ((elem x3 y) &\n        (isPermutation\n           xs (deleteBy (% (x4 :: 'a) => % (x5 :: 'a) => (x4 = x5)) x3 y)))\"\n\ntheorem property0 :\n  \"((isPermutation xs ys) ==>\n      ((isPermutation ys zs) ==> (isPermutation xs zs)))\"\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_list_nat_perm_trans.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278540866547, "lm_q2_score": 0.7956581024858786, "lm_q1q2_score": 0.7021108719632735}}
{"text": "theory TypedLambda2\nimports Main Tools \"~~/src/HOL/Proofs/Lambda/ListOrder\"\nbegin\n\ndeclare [[syntax_ambiguity_warning = false]]\n\n\nsubsection {* Lambda-terms in de Bruijn notation and substitution *}\n\ndatatype dB =\n    Var nat\n  | App dB dB (infixl \"\\<degree>\" 200)\n  | Abs dB\n\nprimrec\n  lift :: \"[dB, nat] => dB\"\nwhere\n    \"lift (Var i) k = (if i < k then Var i else Var (i + 1))\"\n  | \"lift (s \\<degree> t) k = lift s k \\<degree> lift t k\"\n  | \"lift (Abs s) k = Abs (lift s (k + 1))\"\n\nprimrec\n  subst :: \"[dB, dB, nat] => dB\"  (\"_[_'/_]\" [300, 0, 0] 300)\nwhere (* FIXME base names *)\n    subst_Var: \"(Var i)[s/k] =\n      (if k < i then Var (i - 1) else if i = k then s else Var i)\"\n  | subst_App: \"(t \\<degree> u)[s/k] = t[s/k] \\<degree> u[s/k]\"\n  | subst_Abs: \"(Abs t)[s/k] = Abs (t[lift s 0 / k+1])\"\n\ndeclare subst_Var [simp del]\n\nsubsection {* Beta-reduction *}\n\ninductive beta :: \"[dB, dB] => bool\"  (infixl \"\\<rightarrow>\\<^sub>\\<beta>\" 50)\n  where\n    beta [simp, intro!]: \"Abs s \\<degree> t \\<rightarrow>\\<^sub>\\<beta> s[t/0]\"\n  | appL [simp, intro!]: \"s \\<rightarrow>\\<^sub>\\<beta> t ==> s \\<degree> u \\<rightarrow>\\<^sub>\\<beta> t \\<degree> u\"\n  | appR [simp, intro!]: \"s \\<rightarrow>\\<^sub>\\<beta> t ==> u \\<degree> s \\<rightarrow>\\<^sub>\\<beta> u \\<degree> t\"\n  | abs [simp, intro!]: \"s \\<rightarrow>\\<^sub>\\<beta> t ==> Abs s \\<rightarrow>\\<^sub>\\<beta> Abs t\"\n\nabbreviation\n  beta_reds :: \"[dB, dB] => bool\"  (infixl \"->>\" 50) where\n  \"s ->> t == beta^** s t\"\n\nnotation (latex)\n  beta_reds  (infixl \"\\<rightarrow>\\<^sub>\\<beta>\\<^sup>*\" 50)\n\ninductive_cases beta_cases [elim!]:\n  \"Var i \\<rightarrow>\\<^sub>\\<beta> t\"\n  \"Abs r \\<rightarrow>\\<^sub>\\<beta> s\"\n  \"s \\<degree> t \\<rightarrow>\\<^sub>\\<beta> u\"\n\ndeclare if_not_P [simp] not_less_eq [simp]\n  \\<comment> \\<open>don't add @{text \"r_into_rtrancl[intro!]\"}\\<close>\n\n\nsubsection {* Congruence rules *}\n\nlemma rtrancl_beta_Abs [intro!]:\n    \"s \\<rightarrow>\\<^sub>\\<beta>\\<^sup>* s' ==> Abs s \\<rightarrow>\\<^sub>\\<beta>\\<^sup>* Abs s'\"\n  by (induct set: rtranclp) (blast intro: rtranclp.rtrancl_into_rtrancl)+\n\nlemma rtrancl_beta_AppL:\n    \"s \\<rightarrow>\\<^sub>\\<beta>\\<^sup>* s' ==> s \\<degree> t \\<rightarrow>\\<^sub>\\<beta>\\<^sup>* s' \\<degree> t\"\n  by (induct set: rtranclp) (blast intro: rtranclp.rtrancl_into_rtrancl)+\n\nlemma rtrancl_beta_AppR:\n    \"t \\<rightarrow>\\<^sub>\\<beta>\\<^sup>* t' ==> s \\<degree> t \\<rightarrow>\\<^sub>\\<beta>\\<^sup>* s \\<degree> t'\"\n  by (induct set: rtranclp) (blast intro: rtranclp.rtrancl_into_rtrancl)+\n\nlemma rtrancl_beta_App [intro]:\n    \"[| s \\<rightarrow>\\<^sub>\\<beta>\\<^sup>* s'; t \\<rightarrow>\\<^sub>\\<beta>\\<^sup>* t' |] ==> s \\<degree> t \\<rightarrow>\\<^sub>\\<beta>\\<^sup>* s' \\<degree> t'\"\n  by (blast intro!: rtrancl_beta_AppL rtrancl_beta_AppR intro: rtranclp_trans)\n\n\nsubsection {* Substitution-lemmas *}\n\nlemma subst_eq [simp]: \"(Var k)[u/k] = u\"\n  by (simp add: subst_Var)\n\nlemma subst_gt [simp]: \"i < j ==> (Var j)[u/i] = Var (j - 1)\"\n  by (simp add: subst_Var)\n\nlemma subst_lt [simp]: \"j < i ==> (Var j)[u/i] = Var j\"\n  by (simp add: subst_Var)\n\nlemma lift_lift:\n    \"i < k + 1 \\<Longrightarrow> lift (lift t i) (Suc k) = lift (lift t k) i\"\n  by (induct t arbitrary: i k) auto\n\nlemma lift_subst [simp]:\n    \"j < i + 1 \\<Longrightarrow> lift (t[s/j]) i = (lift t (i + 1)) [lift s i / j]\"\n  by (induct t arbitrary: i j s)\n    (simp_all add: diff_Suc subst_Var lift_lift split: nat.split)\n\nlemma lift_subst_lt:\n    \"i < j + 1 \\<Longrightarrow> lift (t[s/j]) i = (lift t i) [lift s i / j + 1]\"\n  by (induct t arbitrary: i j s) (simp_all add: subst_Var lift_lift)\n\nlemma subst_lift [simp]:\n    \"(lift t k)[s/k] = t\"\n  by (induct t arbitrary: k s) simp_all\n\nlemma subst_subst:\n    \"i < j + 1 \\<Longrightarrow> t[lift v i / Suc j][u[v/j]/i] = t[u/i][v/j]\"\n  by (induct t arbitrary: i j u v)\n    (simp_all add: diff_Suc subst_Var lift_lift [symmetric] lift_subst_lt\n      split: nat.split)\n\n\nsubsection {* Preservation theorems *}\n\ntext {* Not used in Church-Rosser proof, but in Strong\n  Normalization. \\medskip *}\n\ntheorem subst_preserves_beta [simp]:\n    \"r \\<rightarrow>\\<^sub>\\<beta> s ==> r[t/i] \\<rightarrow>\\<^sub>\\<beta> s[t/i]\"\n  by (induct arbitrary: t i set: beta) (simp_all add: subst_subst [symmetric])\n\ntheorem lift_preserves_beta [simp]:\n    \"r \\<rightarrow>\\<^sub>\\<beta> s ==> lift r i \\<rightarrow>\\<^sub>\\<beta> lift s i\"\n  by (induct arbitrary: i set: beta) auto\n\n\ntheorem subst_preserves_beta2 [simp]: \"r \\<rightarrow>\\<^sub>\\<beta> s ==> t[r/i] \\<rightarrow>\\<^sub>\\<beta>\\<^sup>* t[s/i]\"\n  apply (induct t arbitrary: r s i)\n    close (simp add: subst_Var r_into_rtranclp)\n   close (simp add: rtrancl_beta_App)\n  by (simp add: rtrancl_beta_Abs)\n\n\nabbreviation\n  list_application :: \"dB => dB list => dB\"  (infixl \"\\<degree>\\<degree>\" 150) where\n  \"t \\<degree>\\<degree> ts == foldl (\\<degree>) t ts\"\n\n\nlemma App_eq_foldl_conv:\n  \"(r \\<degree> s = t \\<degree>\\<degree> ts) =\n    (if ts = [] then r \\<degree> s = t\n    else (\\<exists>ss. ts = ss @ [s] \\<and> r = t \\<degree>\\<degree> ss))\"\n  apply (rule_tac xs = ts in rev_exhaust)\n   apply auto\n  done\n\nlemma Abs_eq_apps_conv [iff]:\n    \"(Abs r = s \\<degree>\\<degree> ss) = (Abs r = s \\<and> ss = [])\"\n  by (induct ss rule: rev_induct) auto\n\n\nlemma Abs_apps_eq_Abs_apps_conv [iff]:\n    \"(Abs r \\<degree>\\<degree> rs = Abs s \\<degree>\\<degree> ss) = (r = s \\<and> rs = ss)\"\n  apply (induct rs arbitrary: ss rule: rev_induct)\n   apply simp\n   apply blast\n  apply (induct_tac ss rule: rev_induct)\n   apply auto\n  done\n\nlemma Abs_App_neq_Var_apps [iff]:\n    \"Abs s \\<degree> t \\<noteq> Var n \\<degree>\\<degree> ss\"\n  by (induct ss arbitrary: s t rule: rev_induct) auto\n\n\nlemma lift_map [simp]:\n    \"lift (t \\<degree>\\<degree> ts) i = lift t i \\<degree>\\<degree> map (\\<lambda>t. lift t i) ts\"\n  by (induct ts arbitrary: t) simp_all\n\nlemma subst_map [simp]:\n    \"subst (t \\<degree>\\<degree> ts) u i = subst t u i \\<degree>\\<degree> map (\\<lambda>t. subst t u i) ts\"\n  by (induct ts arbitrary: t) simp_all\n\nlemma app_last: \"(t \\<degree>\\<degree> ts) \\<degree> u = t \\<degree>\\<degree> (ts @ [u])\"\n  by simp\n\n\n\n\nsubsection {* Environments *}\n\ndefinition\n  shift :: \"(nat \\<Rightarrow> 'a) \\<Rightarrow> nat \\<Rightarrow> 'a \\<Rightarrow> nat \\<Rightarrow> 'a\"  (\"_<_:_>\" [90, 0, 0] 91) where\n  \"e<i:a> = (\\<lambda>j. if j < i then e j else if j = i then a else e (j - 1))\"\n\nnotation (xsymbols)\n  shift  (\"_\\<langle>_:_\\<rangle>\" [90, 0, 0] 91)\n\nnotation (HTML output)\n  shift  (\"_\\<langle>_:_\\<rangle>\" [90, 0, 0] 91)\n\n\n\nlemma shift_gt [simp]: \"j < i \\<Longrightarrow> (e\\<langle>i:T\\<rangle>) j = e j\"\n  by (simp add: shift_def)\n\nlemma shift_lt [simp]: \"i < j \\<Longrightarrow> (e\\<langle>i:T\\<rangle>) j = e (j - 1)\"\n  by (simp add: shift_def)\n\nlemma shift_commute [simp]: \"e\\<langle>i:U\\<rangle>\\<langle>0:T\\<rangle> = e\\<langle>0:T\\<rangle>\\<langle>Suc i:U\\<rangle>\"\n  by (rule ext) (simp_all add: shift_def split: nat.split)\n\n\nsubsection {* Types and typing rules *}\n\ndatatype type =\n    Atom nat\n  | Fun type type    (infixr \"\\<Rightarrow>\" 200)\n  | Prod type type\n\ninductive typing :: \"(nat \\<Rightarrow> type) \\<Rightarrow> dB \\<Rightarrow> type \\<Rightarrow> bool\"  (\"_ \\<turnstile> _ : _\" [50, 50, 50] 50)\n  where\n    Var [intro!]: \"env x = T \\<Longrightarrow> env \\<turnstile> Var x : T\"\n  | Abs [intro!]: \"env\\<langle>0:T\\<rangle> \\<turnstile> t : U \\<Longrightarrow> env \\<turnstile> Abs t : (T \\<Rightarrow> U)\"\n  | App [intro!]: \"env \\<turnstile> s : T \\<Rightarrow> U \\<Longrightarrow> env \\<turnstile> t : T \\<Longrightarrow> env \\<turnstile> (s \\<degree> t) : U\"\n  | Pair [intro!]: \"\\<lbrakk> env \\<turnstile> s : T; env \\<turnstile> t : U \\<rbrakk> \\<Longrightarrow> \n        env \\<turnstile> Abs ((Var 0) \\<degree> (lift s 0) \\<degree> (lift t 0)) : Prod T U\"\n  | Fst [intro!]: \"env \\<turnstile> s : Prod T U \\<Longrightarrow> env \\<turnstile> s : (T \\<Rightarrow> U \\<Rightarrow> T) \\<Rightarrow> T\"\n\ninductive_cases typing_elims [elim!]:\n  \"e \\<turnstile> Var i : T\"\n  \"e \\<turnstile> t \\<degree> u : T\"\n  \"e \\<turnstile> Abs t : T\"\nprint_theorems\n\nlemma typing_elim_app: assumes \"e \\<turnstile> t \\<degree> u : T\" shows \"(\\<And>T' U'. e \\<turnstile> t : T' \\<Rightarrow> U' \\<Longrightarrow> e \\<turnstile> u : T' \\<Longrightarrow> P) \\<Longrightarrow> P\"\n  using assms apply cases close auto\n  apply (erule typing_elims(2)) by auto\n\nprimrec\n  typings :: \"(nat \\<Rightarrow> type) \\<Rightarrow> dB list \\<Rightarrow> type list \\<Rightarrow> bool\"\nwhere\n    \"typings e [] Ts = (Ts = [])\"\n  | \"typings e (t # ts) Ts =\n      (case Ts of\n        [] \\<Rightarrow> False\n      | T # Ts \\<Rightarrow> e \\<turnstile> t : T \\<and> typings e ts Ts)\"\n\nabbreviation\n  typings_rel :: \"(nat \\<Rightarrow> type) \\<Rightarrow> dB list \\<Rightarrow> type list \\<Rightarrow> bool\"\n    (\"_ ||- _ : _\" [50, 50, 50] 50) where\n  \"env ||- ts : Ts == typings env ts Ts\"\n\nnotation (latex)\n  typings_rel  (\"_ \\<tturnstile> _ : _\" [50, 50, 50] 50)\n\nabbreviation\n  funs :: \"type list \\<Rightarrow> type \\<Rightarrow> type\"  (infixr \"=>>\" 200) where\n  \"Ts =>> T == foldr Fun Ts T\"\n\nnotation (latex)\n  funs  (infixr \"\\<Rrightarrow>\" 200)\n\n\n\nsubsection {* Lists of types *}\n\nlemma lists_typings:\n    \"e \\<tturnstile> ts : Ts \\<Longrightarrow> listsp (\\<lambda>t. \\<exists>T. e \\<turnstile> t : T) ts\"\n  apply (induct ts arbitrary: Ts)\n   apply (case_tac Ts)\n     apply simp\n     apply (rule listsp.Nil)\n    apply simp\n  apply (case_tac Ts)\n   apply simp\n  apply simp\n  apply (rule listsp.Cons)\n   apply blast\n  apply blast\n  done\n\nlemma types_snoc_eq: \"e \\<tturnstile> ts @ [t] : Ts @ [T] =\n  (e \\<tturnstile> ts : Ts \\<and> e \\<turnstile> t : T)\"\n  apply (induct ts arbitrary: Ts)\n  apply (case_tac Ts)\n  apply simp+\n  apply (case_tac Ts)\n  apply (case_tac \"ts @ [t]\")\n  apply simp+\n  done\n\nlemma rev_exhaust2 [extraction_expand]:\n  obtains (Nil) \"xs = []\"  |  (snoc) ys y where \"xs = ys @ [y]\"\n  \\<comment> \\<open>Cannot use @{text rev_exhaust} from the @{text List}\n    theory, since it is not constructive\\<close>\n  apply (subgoal_tac \"\\<forall>ys. xs = rev ys \\<longrightarrow> thesis\")\n  apply (erule_tac x=\"rev xs\" in allE)\n  apply simp\n  apply (rule allI)\n  apply (rule impI)\n  apply (case_tac ys)\n  apply simp\n  apply simp\n  done\n\nlemma types_snocE: \"e \\<tturnstile> ts @ [t] : Ts \\<Longrightarrow>\n  (\\<And>Us U. Ts = Us @ [U] \\<Longrightarrow> e \\<tturnstile> ts : Us \\<Longrightarrow> e \\<turnstile> t : U \\<Longrightarrow> P) \\<Longrightarrow> P\"\n  apply (cases Ts rule: rev_exhaust2)\n  apply simp\n  apply (case_tac \"ts @ [t]\")\n  apply (simp add: types_snoc_eq)+\n  done\n\n\nsubsection {* n-ary function types *}\n\nlemma list_app_typeD:\n    \"e \\<turnstile> t \\<degree>\\<degree> ts : T \\<Longrightarrow> \\<exists>Ts. e \\<turnstile> t : Ts \\<Rrightarrow> T \\<and> e \\<tturnstile> ts : Ts\"\nproof (induction ts arbitrary: t T)\ncase Nil thus ?case by simp\nnext case (Cons a ts) thus ?case\n  apply simp\n  apply atomize\n  apply (erule_tac x = \"t \\<degree> a\" in allE)\n  apply (erule_tac x = T in allE)\n  apply (erule impE)\n   close assumption\n  apply (elim exE conjE)\n  apply (erule typing_elim_app)  \n  apply (rule_tac x = \"U' # Ts\" in exI, simp)\n  apply (frule Fst)\n  by simp\nqed\n\nlemma list_app_typeE:\n  \"e \\<turnstile> t \\<degree>\\<degree> ts : T \\<Longrightarrow> (\\<And>Ts. e \\<turnstile> t : Ts \\<Rrightarrow> T \\<Longrightarrow> e \\<tturnstile> ts : Ts \\<Longrightarrow> C) \\<Longrightarrow> C\"\n  by (insert list_app_typeD) fast\n\nlemma list_app_typeI:\n    \"e \\<turnstile> t : Ts \\<Rrightarrow> T \\<Longrightarrow> e \\<tturnstile> ts : Ts \\<Longrightarrow> e \\<turnstile> t \\<degree>\\<degree> ts : T\"\n  apply (induct ts arbitrary: t T Ts)\n   apply simp\n  apply (rename_tac a b t T Ts)\n  apply atomize\n  apply (case_tac Ts)\n   apply simp\n  apply simp\n  apply (erule_tac x = \"t \\<degree> a\" in allE)\n  apply (erule_tac x = T in allE)\n  apply (rename_tac list)\n  apply (erule_tac x = list in allE)\n  apply (erule impE)\n   apply (erule conjE)\n   apply (erule typing.App)\n   apply assumption\n  apply blast\n  done\n\n\n\nsubsection {* Lifting preserves well-typedness *}\n\nlemma lift_type [intro!]: \"e \\<turnstile> t : T \\<Longrightarrow> e\\<langle>i:U\\<rangle> \\<turnstile> lift t i : T\"\n  apply (induct arbitrary: i U set: typing, auto) \n  by (subst lift_lift, auto)+\n\nlemma lift_types:\n  \"e \\<tturnstile> ts : Ts \\<Longrightarrow> e\\<langle>i:U\\<rangle> \\<tturnstile> (map (\\<lambda>t. lift t i) ts) : Ts\"\n  apply (induct ts arbitrary: Ts)\n   apply simp\n  apply (case_tac Ts)\n   apply auto\n  done\n\n\nsubsection {* Substitution lemmas *}\n\nlemma subst_lemma:\n    \"e \\<turnstile> t : T \\<Longrightarrow> e' \\<turnstile> u : U \\<Longrightarrow> e = e'\\<langle>i:U\\<rangle> \\<Longrightarrow> e' \\<turnstile> t[u/i] : T\"\n  apply (induct arbitrary: e' i U u set: typing)\n    apply (rule_tac x = x and y = i in linorder_cases)\n      apply auto\n  close blast\n  by (subst lift_subst_lt[simplified,symmetric], auto)+ \n  \n\nlemma substs_lemma:\n  \"e \\<turnstile> u : T \\<Longrightarrow> e\\<langle>i:T\\<rangle> \\<tturnstile> ts : Ts \\<Longrightarrow>\n     e \\<tturnstile> (map (\\<lambda>t. t[u/i]) ts) : Ts\"\n  apply (induct ts arbitrary: Ts)\n   apply (case_tac Ts)\n    apply simp\n   apply simp\n  apply atomize\n  apply (case_tac Ts)\n   apply simp\n  apply simp\n  apply (erule conjE)\n  apply (erule (1) subst_lemma)\n  apply (rule refl)\n  done\n\n\nsubsection {* Subject reduction *}\n\n\nlemma reduce_below_lift:\n  assumes \"lift s' k \\<rightarrow>\\<^sub>\\<beta> t\"\n  shows \"\\<exists>t'. t = lift t' k \\<and> s' \\<rightarrow>\\<^sub>\\<beta> t'\"\nproof -\ndef s == \"lift s' k\"\nfrom assms have st: \"s \\<rightarrow>\\<^sub>\\<beta> t\" unfolding s_def by simp\nhave \"\\<And>s' k. s=lift s' k \\<Longrightarrow> \\<exists>t'. t = lift t' k \\<and> s' \\<rightarrow>\\<^sub>\\<beta> t'\"\n  using st proof (induction)\n  case (abs s t) \n    obtain s0 where \"s'=Abs s0\" and \"s = lift s0 (Suc k)\"\n      apply (atomize_elim)\n      apply (cases s')\n      using `Abs s = lift s' k` apply auto\n      by (metis dB.distinct(3))\n    with abs.IH obtain t' where \"t = lift t' (Suc k)\" and \"s0 \\<rightarrow>\\<^sub>\\<beta> t'\" by auto\n    show ?case apply (rule exI[of _ \"Abs t'\"], auto)\n      apply (metis `t = lift t' (Suc k)`)\n      by (metis `s' = Abs s0` `s0 \\<rightarrow>\\<^sub>\\<beta> t'` beta.abs)\n  next case (appL s t u)\n    obtain s0 u0 where s':\"s'=s0 \\<degree> u0\" \n          and s:\"s = lift s0 k\" and u:\"u = lift u0 k\"\n      by (metis appL.prems dB.distinct(1) dB.distinct(5) dB.exhaust dB.inject(2) lift.simps(2) subst_App subst_lift)\n    with appL.IH obtain t' where t:\"t = lift t' k\" and s0: \"s0 \\<rightarrow>\\<^sub>\\<beta> t'\" by auto\n    show ?case apply (rule exI[of _ \"t' \\<degree> u0\"], auto) \n      close (fact t) close (fact u)\n      by (metis (full_types) s' s0 beta.appL)\n  next case (appR s t u)\n    obtain s0 u0 where s':\"s'=u0 \\<degree> s0\" \n          and s:\"s = lift s0 k\" and u:\"u = lift u0 k\"\n      by (metis appR.prems dB.distinct(1) dB.distinct(6) dB.exhaust dB.inject(2) lift.simps(2) subst_App subst_lift)\n    with appR.IH obtain t' where t:\"t = lift t' k\" and s0: \"s0 \\<rightarrow>\\<^sub>\\<beta> t'\" by auto\n    show ?case apply (rule exI[of _ \"u0 \\<degree> t'\"], auto) \n      close (fact u) close (fact t) \n      by (metis (full_types) s' s0 beta.appR)\n  next case (beta s t)\n    then obtain s0 t0 where s':\"s'=Abs s0 \\<degree> t0\" \n        and s:\"s=lift s0 (Suc k)\" and t:\"t=lift t0 k\" \n      apply (atomize_elim)\n      apply (cases s')\n      close (metis beta.beta beta_cases(1) subst_lift subst_preserves_beta) \n      defer close auto\n      apply (rename_tac s0' t0', case_tac s0')\n      defer close auto close auto\n      by (metis dB.distinct(3) dB.inject(2) lift.simps(2) subst_Abs subst_lift)\n    show \"\\<exists>t'. s[t/0] = lift t' k \\<and> s' \\<rightarrow>\\<^sub>\\<beta> t'\"\n      apply (rule exI[of _ \"s0[t0/0]\"])\n      by (auto simp: s t s')\n  qed\n  with s_def show ?thesis by auto\nqed\n\n\nlemma remove_product_type:\n  assumes \"e \\<turnstile> Abs r : T'\"\n  shows \"\\<exists>A B. e \\<turnstile> Abs r : A \\<Rightarrow> B\"\nusing assms apply (cases, auto)\n  apply (rename_tac x X y Y)\n  apply (rule_tac x=\"X \\<Rightarrow> Y \\<Rightarrow> Atom 0\" in  exI)\n  by (rule_tac x=\"Atom 0\" in  exI, auto)\n\nlemma remove_product_type_fst:\n  assumes \"e \\<turnstile> r : Prod A B\"\n  shows \"e \\<turnstile> r : (A \\<Rightarrow> B \\<Rightarrow> A) \\<Rightarrow> A\"\nusing assms apply (cases, auto)\n(* Wrong if e is a variable! ! ! *)\nby auto\n\nlemma subject_reduction: \"e \\<turnstile> t : T \\<Longrightarrow> t \\<rightarrow>\\<^sub>\\<beta> t' \\<Longrightarrow> e \\<turnstile> t' : T\"\nproof (induct arbitrary: t' set: typing)\ncase Var thus ?case by blast\nnext case Abs thus ?case by blast\nnext case Pair thus ?case apply auto\n  apply (frule reduce_below_lift, auto)\n  by (frule reduce_below_lift, auto)\nnext case Fst thus ?case  by auto\nnext case (App env s T U t) show ?case\n  using App.prems proof (cases)\n  case (beta s0) show ?thesis\n    using `env \\<turnstile> s : T \\<Rightarrow> U` proof (cases)\n    case Var thus ?thesis by (metis dB.distinct(3) local.beta(1))\n    next case App thus ?thesis by (metis dB.distinct(6) local.beta(1))\n    next case Abs thus ?thesis by (metis App.hyps(3) dB.inject(3) local.beta(1) local.beta(2) subst_lemma)\n    next case Pair fix V assume s:\"s = Abs (Var 0 \\<degree> Abs (Abs (Var (Suc 0))))\" and T:\"T = Prod U V\" \nprint_facts\n      with App.hyps have \"env \\<turnstile> t : Prod U V\" by auto\n      hence t_typ:\"env \\<turnstile> t : (U\\<Rightarrow>V\\<Rightarrow>U) \\<Rightarrow> U\" by (rule remove_product_type_fst)\n      from `s=Abs s0` and s have \"s0 = Var 0 \\<degree> Abs (Abs (Var (Suc 0)))\" by simp\n      with beta have t':\"t' = t \\<degree> Abs (Abs (Var (Suc 0)))\" by auto\n      show \"env \\<turnstile> t' : U\"\n        unfolding t' apply (rule typing.intros)\n        close (rule t_typ) by auto\n    qed\n  next case appL with App show ?thesis by auto\n  next case appR with App show ?thesis by auto\n  qed\nqed   \n\n\n\nsubsection {* Alternative induction rule for types *}\n\nlemma type_induct [induct type]:\n  assumes\n  \"(\\<And>T. (\\<And>T1 T2. T = T1 \\<Rightarrow> T2 \\<Longrightarrow> P T1) \\<Longrightarrow>\n    (\\<And>T1 T2. T = T1 \\<Rightarrow> T2 \\<Longrightarrow> P T2) \\<Longrightarrow> P T)\"\n  shows \"P T\"\nproof (induct T)\n  case Atom\n  show ?case by (rule assms) simp_all\nnext\n  case Fun\n  show ?case by (rule assms) (insert Fun, simp_all)\nnext\n  case Prod\n  show ?case by (rule assms) (insert Prod, simp_all)\nqed\n\n\ntext {*\n  Lifting beta-reduction to lists of terms, reducing exactly one element.\n*}\n\nabbreviation\n  list_beta :: \"dB list => dB list => bool\"  (infixl \"=>\" 50) where\n  \"rs => ss == step1 beta rs ss\"\n\nlemma head_Var_reduction:\n  \"Var n \\<degree>\\<degree> rs \\<rightarrow>\\<^sub>\\<beta> v \\<Longrightarrow> \\<exists>ss. rs => ss \\<and> v = Var n \\<degree>\\<degree> ss\"\n  apply (induct u == \"Var n \\<degree>\\<degree> rs\" v arbitrary: rs set: beta)\n     close simp\n    apply (rule_tac xs = rs in rev_exhaust)\n     close simp\n    close (atomize, force intro: append_step1I)\n   apply (rule_tac xs = rs in rev_exhaust)\n    close simp\n    apply (auto 0 3 intro: disjI2 [THEN append_step1I])\n  done\n\nlemma apps_betasE [elim!]:\n  assumes major: \"r \\<degree>\\<degree> rs \\<rightarrow>\\<^sub>\\<beta> s\"\n    and cases: \"!!r'. [| r \\<rightarrow>\\<^sub>\\<beta> r'; s = r' \\<degree>\\<degree> rs |] ==> R\"\n      \"!!rs'. [| rs => rs'; s = r \\<degree>\\<degree> rs' |] ==> R\"\n      \"!!t u us. [| r = Abs t; rs = u # us; s = t[u/0] \\<degree>\\<degree> us |] ==> R\"\n  shows R\nproof -\n  from major have\n   \"(\\<exists>r'. r \\<rightarrow>\\<^sub>\\<beta> r' \\<and> s = r' \\<degree>\\<degree> rs) \\<or>\n    (\\<exists>rs'. rs => rs' \\<and> s = r \\<degree>\\<degree> rs') \\<or>\n    (\\<exists>t u us. r = Abs t \\<and> rs = u # us \\<and> s = t[u/0] \\<degree>\\<degree> us)\"\n  proof (induct u == \"r \\<degree>\\<degree> rs\" s arbitrary: r rs set: beta)\n  case beta thus ?case\n       apply (case_tac r)\n         close simp\n        apply (simp add: App_eq_foldl_conv)\n        apply (split split_if_asm)\n         apply simp\n         close blast\n        close simp\n       apply (simp add: App_eq_foldl_conv)\n       apply (split split_if_asm)\n        close simp\n       by simp\n  next case appL thus ?case\n      apply auto\n      apply (drule App_eq_foldl_conv [THEN iffD1])\n      apply (split split_if_asm)\n       apply simp\n       close blast\n      by (force intro!: disjI1 [THEN append_step1I])\n  next case appR thus ?case\n     apply auto\n     apply (drule App_eq_foldl_conv [THEN iffD1])\n     apply (split split_if_asm)\n      apply simp\n      close blast\n     by (clarify, auto 0 3 del: exI intro!: exI intro: append_step1I)\n  next case abs thus ?case by auto\n  qed\n  with cases show ?thesis by blast\nqed\n\nlemma apps_preserves_beta [simp]:\n    \"r \\<rightarrow>\\<^sub>\\<beta> s ==> r \\<degree>\\<degree> ss \\<rightarrow>\\<^sub>\\<beta> s \\<degree>\\<degree> ss\"\n  by (induct ss rule: rev_induct) auto\n\nlemma apps_preserves_beta2 [simp]:\n    \"r ->> s ==> r \\<degree>\\<degree> ss ->> s \\<degree>\\<degree> ss\"\n  apply (induct set: rtranclp)\n   apply blast\n  apply (blast intro: apps_preserves_beta rtranclp.rtrancl_into_rtrancl)\n  done\n\nlemma apps_preserves_betas [simp]:\n    \"rs => ss \\<Longrightarrow> r \\<degree>\\<degree> rs \\<rightarrow>\\<^sub>\\<beta> r \\<degree>\\<degree> ss\"\n  apply (induct rs arbitrary: ss rule: rev_induct)\n   apply simp\n  apply simp\n  apply (rule_tac xs = ss in rev_exhaust)\n   apply simp\n  apply simp\n  apply (drule Snoc_step1_SnocD)\n  apply blast\n  done\n\n\nsubsection {* Terminating lambda terms *}\n\ninductive IT :: \"dB => bool\"\n  where\n    Var [intro]: \"listsp IT rs ==> IT (Var n \\<degree>\\<degree> rs)\"\n  | Lambda [intro]: \"IT r ==> IT (Abs r)\"\n  | Beta [intro]: \"IT ((r[s/0]) \\<degree>\\<degree> ss) ==> IT s ==> IT ((Abs r \\<degree> s) \\<degree>\\<degree> ss)\"\n\n\nsubsection {* Every term in @{text \"IT\"} terminates *}\n\nlemma double_induction_lemma [rule_format]:\n  \"termip beta s ==> \\<forall>t. termip beta t -->\n    (\\<forall>r ss. t = r[s/0] \\<degree>\\<degree> ss --> termip beta (Abs r \\<degree> s \\<degree>\\<degree> ss))\"\n  apply (erule accp_induct)\n  apply (rule allI)\n  apply (rule impI)\n  apply (erule thin_rl)\n  apply (erule accp_induct)\n  apply clarify\n  apply (rule accp.accI)\n  apply (safe del: apps_betasE elim!: apps_betasE)\n    apply (blast intro: subst_preserves_beta apps_preserves_beta)\n   apply (blast intro: apps_preserves_beta2 subst_preserves_beta2 rtranclp_converseI\n     dest: accp_downwards)  (* FIXME: acc_downwards can be replaced by acc(R ^* ) = acc(r) *)\n  apply (blast dest: apps_preserves_betas)\n  done\n\nlemma IT_implies_termi: \"IT t ==> termip beta t\"\nproof (induct set: IT)\ncase Var thus ?case \n    apply (drule_tac rev_predicate1D [OF _ listsp_mono [where B=\"termip beta\"]])\n    close (fast del: predicate1I intro!: predicate1I)\n    apply (drule lists_accD)\n    apply (erule accp_induct)\n    apply (rule accp.accI)\n    by (blast dest: head_Var_reduction)\nnext case Lambda thus ?case\n   apply (erule_tac accp_induct)\n   apply (rule accp.accI)\n   by blast\nnext case Beta thus ?case\n  by (blast intro: double_induction_lemma)\nqed\n\n\nsubsection {* Every terminating term is in @{text \"IT\"} *}\n\n\n\n\ninductive_cases [elim!]:\n  \"IT (Var n \\<degree>\\<degree> ss)\"\n  \"IT (Abs t)\"\n  \"IT (Abs r \\<degree> s \\<degree>\\<degree> ts)\"\n\n(*\ntheorem termi_implies_IT: \"termip beta r ==> IT r\"\n  apply (erule accp_induct)\n  apply (rename_tac r)\n  apply (erule thin_rl)\n  apply (erule rev_mp)\n  apply simp\n  apply (rule_tac t = r in Apps_dB_induct)\n   apply clarify\n   apply (rule IT.intros)\n   apply clarify\n   apply (drule bspec, assumption)\n   apply (erule mp)\n   apply clarify\n   apply (drule_tac r=beta in conversepI)\n   apply (drule_tac r=\"beta^--1\" in ex_step1I, assumption)\n   apply clarify\n   apply (rename_tac us)\n   apply (erule_tac x = \"Var n \\<degree>\\<degree> us\" in allE)\n   apply force\n   apply (rename_tac u ts)\n   apply (case_tac ts)\n    apply simp\n    apply blast\n   apply (rename_tac s ss)\n   apply simp\n   apply clarify\n   apply (rule IT.intros)\n    apply (blast intro: apps_preserves_beta)\n   apply (erule mp)\n   apply clarify\n   apply (rename_tac t)\n   apply (erule_tac x = \"Abs u \\<degree> t \\<degree>\\<degree> ss\" in allE)\n   apply force\n   done\n*)\n\ntext {*\nFormalization by Stefan Berghofer. Partly based on a paper proof by\nFelix Joachimski and Ralph Matthes \\cite{Matthes-Joachimski-AML}.\n*}\n\n\nsubsection {* Properties of @{text IT} *}\n\nlemma lift_IT [intro!]: \"IT t \\<Longrightarrow> IT (lift t i)\"\n  apply (induct arbitrary: i set: IT)\n    apply (simp (no_asm))\n    apply (rule conjI)\n     apply\n      (rule impI,\n       rule IT.Var,\n       erule listsp.induct,\n       simp (no_asm),\n       simp (no_asm),\n       rule listsp.Cons,\n       blast,\n       assumption)+\n     apply auto\n   done\n\nlemma subst_Var_IT: \"IT r \\<Longrightarrow> IT (r[Var i/j])\"\n  apply (induct arbitrary: i j set: IT)\n    txt {* Case @{term Var}: *}\n    apply (simp (no_asm) add: subst_Var)\n    apply\n    ((rule conjI impI)+,\n      rule IT.Var,\n      erule listsp.induct,\n      simp (no_asm),\n      simp (no_asm),\n      rule listsp.Cons,\n      fast,\n      assumption)+\n   txt {* Case @{term Lambda}: *}\n   apply atomize\n   apply simp\n   apply (rule IT.Lambda)\n   apply fast\n  txt {* Case @{term Beta}: *}\n  apply atomize\n  apply (simp (no_asm_use) add: subst_subst [symmetric])\n  apply (rule IT.Beta)\n   apply auto\n  done\n\nlemma Var_IT: \"IT (Var n)\"\n  apply (subgoal_tac \"IT (Var n \\<degree>\\<degree> [])\")\n   apply simp\n  apply (rule IT.Var)\n  apply (rule listsp.Nil)\n  done\n\nlemma app_Var_IT: \"IT t \\<Longrightarrow> IT (t \\<degree> Var i)\"\nproof (induct set: IT)\ncase Var thus ?case\n    apply (subst app_last)\n    apply (rule IT.Var)\n    apply simp\n    apply (rule listsp.Cons)\n     close (rule Var_IT)\n    by (rule listsp.Nil)\nnext case Lambda show ?case\n  apply (insert Lambda)\n  apply (rule IT.Beta [where ?ss = \"[]\", unfolded foldl_Nil [THEN eq_reflection]])\n  close (erule subst_Var_IT)\n  by (rule Var_IT)\nnext case Beta thus ?case\n  apply (subst app_last)\n  apply (rule IT.Beta)\n   apply (subst app_last [symmetric])\n   close assumption\n  by assumption\nqed\n\nsubsection {* Well-typed substitution preserves termination *}\n\nlemma subst_type_IT:\n  \"\\<And>t e T u i. IT t \\<Longrightarrow> e\\<langle>i:U\\<rangle> \\<turnstile> t : T \\<Longrightarrow>\n    IT u \\<Longrightarrow> e \\<turnstile> u : U \\<Longrightarrow> IT (t[u/i])\"\n  (is \"PROP ?P U\" is \"\\<And>t e T u i. _ \\<Longrightarrow> PROP ?Q t e T u i U\")\nproof (induct U)\n  fix T t\n  assume MI1: \"\\<And>T1 T2. T = T1 \\<Rightarrow> T2 \\<Longrightarrow> PROP ?P T1\"\n  assume MI2: \"\\<And>T1 T2. T = T1 \\<Rightarrow> T2 \\<Longrightarrow> PROP ?P T2\"\n  assume \"IT t\"\n  thus \"\\<And>e T' u i. PROP ?Q t e T' u i T\"\n  proof induct\n    fix e T' u i\n    assume uIT: \"IT u\"\n    assume uT: \"e \\<turnstile> u : T\"\n    {\n      case (Var rs n e1 T'1 u1 i1)\n      assume nT: \"e\\<langle>i:T\\<rangle> \\<turnstile> Var n \\<degree>\\<degree> rs : T'\"\n      let ?ty = \"\\<lambda>t. \\<exists>T'. e\\<langle>i:T\\<rangle> \\<turnstile> t : T'\"\n      let ?R = \"\\<lambda>t. \\<forall>e T' u i.\n        e\\<langle>i:T\\<rangle> \\<turnstile> t : T' \\<longrightarrow> IT u \\<longrightarrow> e \\<turnstile> u : T \\<longrightarrow> IT (t[u/i])\"\n      show \"IT ((Var n \\<degree>\\<degree> rs)[u/i])\"\n      proof (cases \"n = i\")\n        case True\n        show ?thesis\n        proof (cases rs)\n          case Nil\n          with uIT True show ?thesis by simp\n        next\n          case (Cons a as)\n          with nT have \"e\\<langle>i:T\\<rangle> \\<turnstile> Var n \\<degree> a \\<degree>\\<degree> as : T'\" by simp\n          then obtain Ts\n              where headT: \"e\\<langle>i:T\\<rangle> \\<turnstile> Var n \\<degree> a : Ts \\<Rrightarrow> T'\"\n              and argsT: \"e\\<langle>i:T\\<rangle> \\<tturnstile> as : Ts\"\n            by (rule list_app_typeE)\n          from headT obtain T''\n              where varT: \"e\\<langle>i:T\\<rangle> \\<turnstile> Var n : T'' \\<Rightarrow> Ts \\<Rrightarrow> T'\"\n              and argT: \"e\\<langle>i:T\\<rangle> \\<turnstile> a : T''\"\n            by cases simp_all\n          from varT True have T: \"T = T'' \\<Rightarrow> Ts \\<Rrightarrow> T'\"\n            by cases auto\n          with uT have uT': \"e \\<turnstile> u : T'' \\<Rightarrow> Ts \\<Rrightarrow> T'\" by simp\n          from T have \"IT ((Var 0 \\<degree>\\<degree> map (\\<lambda>t. lift t 0)\n            (map (\\<lambda>t. t[u/i]) as))[(u \\<degree> a[u/i])/0])\"\n          proof (rule MI2)\n            from T have \"IT ((lift u 0 \\<degree> Var 0)[a[u/i]/0])\"\n            proof (rule MI1)\n              have \"IT (lift u 0)\" by (rule lift_IT [OF uIT])\n              thus \"IT (lift u 0 \\<degree> Var 0)\" by (rule app_Var_IT)\n              show \"e\\<langle>0:T''\\<rangle> \\<turnstile> lift u 0 \\<degree> Var 0 : Ts \\<Rrightarrow> T'\"\n              proof (rule typing.App)\n                show \"e\\<langle>0:T''\\<rangle> \\<turnstile> lift u 0 : T'' \\<Rightarrow> Ts \\<Rrightarrow> T'\"\n                  by (rule lift_type) (rule uT')\n                show \"e\\<langle>0:T''\\<rangle> \\<turnstile> Var 0 : T''\"\n                  by (rule typing.Var) simp\n              qed\n              from Var have \"?R a\" by cases (simp_all add: Cons)\n              with argT uIT uT show \"IT (a[u/i])\" by simp\n              from argT uT show \"e \\<turnstile> a[u/i] : T''\"\n                by (rule subst_lemma) simp\n            qed\n            thus \"IT (u \\<degree> a[u/i])\" by simp\n            from Var have \"listsp ?R as\"\n              by cases (simp_all add: Cons)\n            moreover from argsT have \"listsp ?ty as\"\n              by (rule lists_typings)\n            ultimately have \"listsp (\\<lambda>t. ?R t \\<and> ?ty t) as\"\n              by simp\n            hence \"listsp IT (map (\\<lambda>t. lift t 0) (map (\\<lambda>t. t[u/i]) as))\"\n              (is \"listsp IT (?ls as)\")\n            proof induct\n              case Nil\n              show ?case by fastforce\n            next\n              case (Cons b bs)\n              hence I: \"?R b\" by simp\n              from Cons obtain U where \"e\\<langle>i:T\\<rangle> \\<turnstile> b : U\" by fast\n              with uT uIT I have \"IT (b[u/i])\" by simp\n              hence \"IT (lift (b[u/i]) 0)\" by (rule lift_IT)\n              hence \"listsp IT (lift (b[u/i]) 0 # ?ls bs)\"\n                by (rule listsp.Cons) (rule Cons)\n              thus ?case by simp\n            qed\n            thus \"IT (Var 0 \\<degree>\\<degree> ?ls as)\" by (rule IT.Var)\n            have \"e\\<langle>0:Ts \\<Rrightarrow> T'\\<rangle> \\<turnstile> Var 0 : Ts \\<Rrightarrow> T'\"\n              by (rule typing.Var) simp\n            moreover from uT argsT have \"e \\<tturnstile> map (\\<lambda>t. t[u/i]) as : Ts\"\n              by (rule substs_lemma)\n            hence \"e\\<langle>0:Ts \\<Rrightarrow> T'\\<rangle> \\<tturnstile> ?ls as : Ts\"\n              by (rule lift_types)\n            ultimately show \"e\\<langle>0:Ts \\<Rrightarrow> T'\\<rangle> \\<turnstile> Var 0 \\<degree>\\<degree> ?ls as : T'\"\n              by (rule list_app_typeI)\n            from argT uT have \"e \\<turnstile> a[u/i] : T''\"\n              by (rule subst_lemma) (rule refl)\n            with uT' show \"e \\<turnstile> u \\<degree> a[u/i] : Ts \\<Rrightarrow> T'\"\n              by (rule typing.App)\n          qed\n          with Cons True show ?thesis\n            by (simp add: comp_def)\n        qed\n      next\n        case False\n        from Var have \"listsp ?R rs\" by simp\n        moreover from nT obtain Ts where \"e\\<langle>i:T\\<rangle> \\<tturnstile> rs : Ts\"\n          by (rule list_app_typeE)\n        hence \"listsp ?ty rs\" by (rule lists_typings)\n        ultimately have \"listsp (\\<lambda>t. ?R t \\<and> ?ty t) rs\"\n          by simp\n        hence \"listsp IT (map (\\<lambda>x. x[u/i]) rs)\"\n        proof induct\n          case Nil\n          show ?case by fastforce\n        next\n          case (Cons a as)\n          hence I: \"?R a\" by simp\n          from Cons obtain U where \"e\\<langle>i:T\\<rangle> \\<turnstile> a : U\" by fast\n          with uT uIT I have \"IT (a[u/i])\" by simp\n          hence \"listsp IT (a[u/i] # map (\\<lambda>t. t[u/i]) as)\"\n            by (rule listsp.Cons) (rule Cons)\n          thus ?case by simp\n        qed\n        with False show ?thesis by (auto simp add: subst_Var)\n      qed\n    next\n      case (Lambda r e1 T'1 u1 i1)\n        assume \"e\\<langle>i:T\\<rangle> \\<turnstile> Abs r : T'\" \n        then obtain A B where AB:\"e\\<langle>i:T\\<rangle> \\<turnstile> Abs r : A \\<Rightarrow> B\" \n          by (atomize_elim, rule remove_product_type)\n        assume \"\\<And>e T' u i. PROP ?Q r e T' u i T\"\n        with AB uIT uT show \"IT (Abs r[u/i])\"\n          by fastxforce\n    next\n      case (Beta r a as e1 T'1 u1 i1)\n      assume T: \"e\\<langle>i:T\\<rangle> \\<turnstile> Abs r \\<degree> a \\<degree>\\<degree> as : T'\"\n      assume SI1: \"\\<And>e T' u i. PROP ?Q (r[a/0] \\<degree>\\<degree> as) e T' u i T\"\n      assume SI2: \"\\<And>e T' u i. PROP ?Q a e T' u i T\"\n      have \"IT (Abs (r[lift u 0/Suc i]) \\<degree> a[u/i] \\<degree>\\<degree> map (\\<lambda>t. t[u/i]) as)\"\n      proof (rule IT.Beta)\n        have \"Abs r \\<degree> a \\<degree>\\<degree> as \\<rightarrow>\\<^sub>\\<beta> r[a/0] \\<degree>\\<degree> as\"\n          by (rule apps_preserves_beta) (rule beta.beta)\n        with T have \"e\\<langle>i:T\\<rangle> \\<turnstile> r[a/0] \\<degree>\\<degree> as : T'\"\n          by (rule subject_reduction)\n        hence \"IT ((r[a/0] \\<degree>\\<degree> as)[u/i])\"\n          using uIT uT by (rule SI1)\n        thus \"IT (r[lift u 0/Suc i][a[u/i]/0] \\<degree>\\<degree> map (\\<lambda>t. t[u/i]) as)\"\n          by (simp del: subst_map add: subst_subst subst_map [symmetric])\n        from T obtain U where \"e\\<langle>i:T\\<rangle> \\<turnstile> Abs r \\<degree> a : U\"\n          by (rule list_app_typeE) fast\n        then obtain T'' where \"e\\<langle>i:T\\<rangle> \\<turnstile> a : T''\" by cases simp_all\n        thus \"IT (a[u/i])\" using uIT uT by (rule SI2)\n      qed\n      thus \"IT ((Abs r \\<degree> a \\<degree>\\<degree> as)[u/i])\" by simp\n    }\n  qed\nqed\n\n\nsubsection {* Well-typed terms are strongly normalizing *}\n\nlemma type_implies_IT:\n  assumes \"e \\<turnstile> t : T\"\n  shows \"IT t\"\n  using assms\nproof induct\n  case Var\n  show ?case by (rule Var_IT)\nnext\n  case Abs\n  show ?case by (rule IT.Lambda) (rule Abs)\nnext\n  case (App e s T U t)\n  have \"IT ((Var 0 \\<degree> lift t 0)[s/0])\"\n  proof (rule subst_type_IT)\n    have \"IT (lift t 0)\" using `IT t` by (rule lift_IT)\n    hence \"listsp IT [lift t 0]\" by (rule listsp.Cons) (rule listsp.Nil)\n    hence \"IT (Var 0 \\<degree>\\<degree> [lift t 0])\" by (rule IT.Var)\n    also have \"Var 0 \\<degree>\\<degree> [lift t 0] = Var 0 \\<degree> lift t 0\" by simp\n    finally show \"IT \\<dots>\" .\n    have \"e\\<langle>0:T \\<Rightarrow> U\\<rangle> \\<turnstile> Var 0 : T \\<Rightarrow> U\"\n      by (rule typing.Var) simp\n    moreover have \"e\\<langle>0:T \\<Rightarrow> U\\<rangle> \\<turnstile> lift t 0 : T\"\n      by (rule lift_type) (rule App.hyps)\n    ultimately show \"e\\<langle>0:T \\<Rightarrow> U\\<rangle> \\<turnstile> Var 0 \\<degree> lift t 0 : U\"\n      by (rule typing.App)\n    show \"IT s\" by fact\n    show \"e \\<turnstile> s : T \\<Rightarrow> U\" by fact\n  qed\n  thus ?case by simp\nnext\n  case (Pair env s T t U) \n  have \"IT (Abs (Var 0 \\<degree>\\<degree> [lift s 0, lift t 0]))\"\n    apply (rule IT.intros)+\n    using Pair by auto\n  thus ?case by auto\nnext\n  case (Fst) \n    have \"IT (Abs (Var 0 \\<degree>\\<degree> [Abs (Abs (Var (Suc 0) \\<degree>\\<degree> []))]))\"\n      apply (rule IT.intros)+\n      apply (rule listsp.intros)\n      apply (rule IT.intros)+\n      by auto\n    thus ?case by auto\nqed\n\ntheorem type_implies_termi: \"e \\<turnstile> t : T \\<Longrightarrow> termip beta t\"\nproof -\n  assume \"e \\<turnstile> t : T\"\n  hence \"IT t\" by (rule type_implies_IT)\n  thus ?thesis by (rule IT_implies_termi)\nqed\n\nend\n", "meta": {"author": "dominique-unruh", "repo": "IsaCrypt", "sha": "1abc2041871af7b758adcc914b83f0d9135ec129", "save_path": "github-repos/isabelle/dominique-unruh-IsaCrypt", "path": "github-repos/isabelle/dominique-unruh-IsaCrypt/IsaCrypt-1abc2041871af7b758adcc914b83f0d9135ec129/old/TypedLambda2.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8221891392358015, "lm_q2_score": 0.8539127510928476, "lm_q1q2_score": 0.7020777898035035}}
{"text": "(*  Title:      HOL/Datatype_Examples/Koenig.thy\n    Author:     Dmitriy Traytel, TU Muenchen\n    Author:     Andrei Popescu, TU Muenchen\n    Copyright   2012\n\nKoenig's lemma.\n*)\n\nsection \\<open>Koenig's Lemma\\<close>\n\ntheory Koenig\nimports TreeFI \"~~/src/HOL/Library/Stream\"\nbegin\n\n(* infinite trees: *)\ncoinductive infiniteTr where\n\"\\<lbrakk>tr' \\<in> set (sub tr); infiniteTr tr'\\<rbrakk> \\<Longrightarrow> infiniteTr tr\"\n\nlemma infiniteTr_strong_coind[consumes 1, case_names sub]:\nassumes *: \"phi tr\" and\n**: \"\\<And> tr. phi tr \\<Longrightarrow> \\<exists> tr' \\<in> set (sub tr). phi tr' \\<or> infiniteTr tr'\"\nshows \"infiniteTr tr\"\nusing assms by (elim infiniteTr.coinduct) blast\n\nlemma infiniteTr_coind[consumes 1, case_names sub, induct pred: infiniteTr]:\nassumes *: \"phi tr\" and\n**: \"\\<And> tr. phi tr \\<Longrightarrow> \\<exists> tr' \\<in> set (sub tr). phi tr'\"\nshows \"infiniteTr tr\"\nusing assms by (elim infiniteTr.coinduct) blast\n\nlemma infiniteTr_sub[simp]:\n\"infiniteTr tr \\<Longrightarrow> (\\<exists> tr' \\<in> set (sub tr). infiniteTr tr')\"\nby (erule infiniteTr.cases) blast\n\nprimcorec konigPath where\n  \"shd (konigPath t) = lab t\"\n| \"stl (konigPath t) = konigPath (SOME tr. tr \\<in> set (sub t) \\<and> infiniteTr tr)\"\n\n(* proper paths in trees: *)\ncoinductive properPath where\n\"\\<lbrakk>shd as = lab tr; tr' \\<in> set (sub tr); properPath (stl as) tr'\\<rbrakk> \\<Longrightarrow>\n properPath as tr\"\n\nlemma properPath_strong_coind[consumes 1, case_names shd_lab sub]:\nassumes *: \"phi as tr\" and\n**: \"\\<And> as tr. phi as tr \\<Longrightarrow> shd as = lab tr\" and\n***: \"\\<And> as tr.\n         phi as tr \\<Longrightarrow>\n         \\<exists> tr' \\<in> set (sub tr). phi (stl as) tr' \\<or> properPath (stl as) tr'\"\nshows \"properPath as tr\"\nusing assms by (elim properPath.coinduct) blast\n\nlemma properPath_coind[consumes 1, case_names shd_lab sub, induct pred: properPath]:\nassumes *: \"phi as tr\" and\n**: \"\\<And> as tr. phi as tr \\<Longrightarrow> shd as = lab tr\" and\n***: \"\\<And> as tr.\n         phi as tr \\<Longrightarrow>\n         \\<exists> tr' \\<in> set (sub tr). phi (stl as) tr'\"\nshows \"properPath as tr\"\nusing properPath_strong_coind[of phi, OF * **] *** by blast\n\nlemma properPath_shd_lab:\n\"properPath as tr \\<Longrightarrow> shd as = lab tr\"\nby (erule properPath.cases) blast\n\nlemma properPath_sub:\n\"properPath as tr \\<Longrightarrow>\n \\<exists> tr' \\<in> set (sub tr). phi (stl as) tr' \\<or> properPath (stl as) tr'\"\nby (erule properPath.cases) blast\n\n(* prove the following by coinduction *)\ntheorem Konig:\n  assumes \"infiniteTr tr\"\n  shows \"properPath (konigPath tr) tr\"\nproof-\n  {fix as\n   assume \"infiniteTr tr \\<and> as = konigPath tr\" hence \"properPath as tr\"\n   proof (coinduction arbitrary: tr as rule: properPath_coind)\n     case (sub tr as)\n     let ?t = \"SOME t'. t' \\<in> set (sub tr) \\<and> infiniteTr t'\"\n     from sub have \"\\<exists>t' \\<in> set (sub tr). infiniteTr t'\" by simp\n     then have \"\\<exists>t'. t' \\<in> set (sub tr) \\<and> infiniteTr t'\" by blast\n     then have \"?t \\<in> set (sub tr) \\<and> infiniteTr ?t\" by (rule someI_ex)\n     moreover have \"stl (konigPath tr) = konigPath ?t\" by simp\n     ultimately show ?case using sub by blast\n   qed simp\n  }\n  thus ?thesis using assms by blast\nqed\n\n(* some more stream theorems *)\n\nprimcorec plus :: \"nat stream \\<Rightarrow> nat stream \\<Rightarrow> nat stream\" (infixr \"\\<oplus>\" 66) where\n  \"shd (plus xs ys) = shd xs + shd ys\"\n| \"stl (plus xs ys) = plus (stl xs) (stl ys)\"\n\ndefinition scalar :: \"nat \\<Rightarrow> nat stream \\<Rightarrow> nat stream\" (infixr \"\\<cdot>\" 68) where\n  [simp]: \"scalar n = smap (\\<lambda>x. n * x)\"\n\nprimcorec ones :: \"nat stream\" where \"ones = 1 ## ones\"\nprimcorec twos :: \"nat stream\" where \"twos = 2 ## twos\"\ndefinition ns :: \"nat \\<Rightarrow> nat stream\" where [simp]: \"ns n = scalar n ones\"\n\nlemma \"ones \\<oplus> ones = twos\"\n  by coinduction simp\n\nlemma \"n \\<cdot> twos = ns (2 * n)\"\n  by coinduction simp\n\nlemma prod_scalar: \"(n * m) \\<cdot> xs = n \\<cdot> m \\<cdot> xs\"\n  by (coinduction arbitrary: xs) auto\n\nlemma scalar_plus: \"n \\<cdot> (xs \\<oplus> ys) = n \\<cdot> xs \\<oplus> n \\<cdot> ys\"\n  by (coinduction arbitrary: xs ys) (auto simp: add_mult_distrib2)\n\nlemma plus_comm: \"xs \\<oplus> ys = ys \\<oplus> xs\"\n  by (coinduction arbitrary: xs ys) auto\n\nlemma plus_assoc: \"(xs \\<oplus> ys) \\<oplus> zs = xs \\<oplus> ys \\<oplus> zs\"\n  by (coinduction arbitrary: xs ys zs) auto\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/Datatype_Examples/Koenig.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8539127529517044, "lm_q2_score": 0.822189134878876, "lm_q1q2_score": 0.7020777876114013}}
{"text": "theory inductive_predicates_pg\nimports Main\nbegin\n\ndatatype tau = \nC0 |\nC1 tau |\nC2 tau tau |\nC3 tau tau tau\nthm tau.induct\n\nvalue \"C0\"\nvalue \"C1 C0\"\nvalue \"C2 (C0) (C1 C0)\"\n\ninductive ev :: \"nat \\<Rightarrow> bool\" where \nev0: \"ev 0\" |\nevSS: \"ev n \\<Longrightarrow> ev(Suc(Suc n))\"\nthm ev.cases ev.induct\n\ninductive IP :: \"tau \\<Rightarrow> bool\"  where\nrule0: \"IP C0\" |\nrule1: \"IP x\" |\nrule2: \"Q (x::tau) \\<Longrightarrow> IP x\" |\nrule3: \"Q (x::tau) \\<Longrightarrow> IP x'\" \nthm IP.cases IP.induct\n\n(* *)\n\ninductive bar2 :: \"'a \\<Rightarrow> bool\" where\nbar0: \"bar2 x\" |\nbar1: \"bar2 x \\<Longrightarrow> bar2 x\" |\nbar2: \"bar2 x \\<Longrightarrow> bar2 y\"\n\n(* *)\n\ninductive I :: \"tau \\<Rightarrow> bool\"  where\nrule0: \"I C0\" |\nrule1: \"I x\" |\nrule2: \"Q x \\<Longrightarrow> I (x::tau)\" |\nrule3: \"Q (x::tau) \\<Longrightarrow> I x'\" |\nrule4: \"Q x \\<Longrightarrow> I (C1 x)\" |\nrule5: \"Q (C1 x) \\<Longrightarrow> I x\" |\nrule6: \"Q (C1 x) \\<Longrightarrow> I x'\" |\nrule7: \"Q (x::tau) \\<Longrightarrow> I (C2 x' x'')\" |\nrule8: \"I (C2 x' x'')\" |\nrule9: \"Q (x::tau) \\<Longrightarrow> I C0 \\<Longrightarrow> I (C3 x x' x'') \\<Longrightarrow> I (C2 x x')\" |\nrule10: \"Q (x::tau) \\<Longrightarrow> I C0 \\<Longrightarrow> I x \\<Longrightarrow> I (C3 x x' x'') \\<Longrightarrow> I (C2 x x')\"\nthm I.cases I.induct\nthm nat.induct\nthm I.induct\n(*\nI ?x \\<Longrightarrow>\n?P C0 \\<Longrightarrow>\n(\\<And>x. ?P x) \\<Longrightarrow>\n(\\<And>Q x. Q x \\<Longrightarrow> ?P x) \\<Longrightarrow>\n(\\<And>Q x x'. Q x \\<Longrightarrow> ?P x') \\<Longrightarrow>\n(\\<And>Q x. Q x \\<Longrightarrow> ?P (C1 x)) \\<Longrightarrow>\n(\\<And>Q x. Q (C1 x) \\<Longrightarrow> ?P x) \\<Longrightarrow>\n(\\<And>Q x x'. Q (C1 x) \\<Longrightarrow> ?P x') \\<Longrightarrow>\n(\\<And>Q x x' x''. Q x \\<Longrightarrow> ?P (C2 x' x'')) \\<Longrightarrow>\n(\\<And>x' x''. ?P (C2 x' x'')) \\<Longrightarrow>\n(\\<And>Q x x' x''. Q x \\<Longrightarrow> I C0 \\<Longrightarrow> ?P C0 \\<Longrightarrow> I (C3 x x' x'') \\<Longrightarrow> ?P (C3 x x' x'') \\<Longrightarrow> ?P (C2 x x')) \\<Longrightarrow>\n(\\<And>Q x x' x''. Q x \\<Longrightarrow> I C0 \\<Longrightarrow> ?P C0 \\<Longrightarrow> I x \\<Longrightarrow> ?P x \\<Longrightarrow> I (C3 x x' x'') \\<Longrightarrow> ?P (C3 x x' x'') \\<Longrightarrow> ?P (C2 x x')) \\<Longrightarrow> ?P ?x\n*)\n\ntheorem \"I x \\<Longrightarrow> P x\"\n  apply (induction rule: I.induct)\n  sorry\n\ntheorem \"I x \\<Longrightarrow> P x\"\n  apply (rule I.induct)\n  sorry\n\ntheorem \"I x \\<Longrightarrow> P x\"\n  apply (cases rule: I.cases)\n  apply simp (* explicitly unifies! *)\n  sorry\n\n(* \nExercise 4.4. Analogous to star, give an inductive definition of the n-fold iteration of a relation r:\niter r n x y should hold if there are x0, ..., xn s.t. x = x0, xn = y and r xi xi+1 for all i < n\nCorrect and prove the following claim: star r x y =\\<Rightarrow> iter r n x y.\n\niter r n x y \\<equiv> \\<exists> x1 ... xn . x=x0 \\<and> y=xn \\<and> \\<forall> i < n. r xi x(i+1)\n*)\n\n(* \niter r n x y = there should be a path from x to y using r to get from x to y.\niter0: iter must be reflexive. i.e. there is a path of length 0 from x to y and y is simply itself x.\niterSS: is inductively defined. If we already know there is a path of length n from y to z and we\nsimply include the extra step x\\<rightarrow>y using r, then of course there is a path from x to z using r.\nSimply use the old path from the inductively defined  iter r n y z the \"old path\" and then add the\nnew path x\\<rightarrow>y using r. Thus there is a path of length n+1 (i.e. we can conclude the left most \npredicate in the meta-implication chain.\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\" |\niterSS: \"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 \nrefl: \"star r x x\"|\nstep: \"r x y \\<Longrightarrow> star r y z \\<Longrightarrow> star r x z\"\nthm star.induct\n\nlemma \"star r x y \\<Longrightarrow> \\<exists> n. iter r n x y\"\n  apply (induction rule: star.induct)\n(* apply (rule_tac ?n2=\"0\" in exI) *)\n(* apply (rule_tac r=\"\\<lambda>x. 0\" in exI) *)\n   apply (meson iter0)\n(* \nproof: \n1) r x y & r* y z let's us conclude r* x z via start.step\n2) Then using the assumptions r* x z and for any n. iter r n y z \nwe can use iter.iterSS to get iter r (Suc n) x z for any n (from previous selection).\nWhich gives us iter r ?n x z for the n above as required (need to show existential so there is the\nwitness).\n*)\n  by (meson iterSS)\n\nlemma \"iter r n x y \\<Longrightarrow> star r x y\"\n  apply (induction rule: iter.induct)\n   apply (rule star.refl)\n  by (simp add: star.step)\n\nlemma\n  shows \"iter r n x y \\<Longrightarrow> star r x y\"\nproof (induction rule: iter.induct)\n  case (iter0 x)\n  then show ?case by (rule star.refl)\nnext\n  case (iterSS x y n z)\n  then show ?case by (meson 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/inductive_predicates_pg.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.853912760387131, "lm_q2_score": 0.8221891261650247, "lm_q1q2_score": 0.7020777862838594}}
{"text": "theory BasicDef\n  imports Main HOL.Real\nbegin\n\nsubsection \\<open>Bool\\<close>\n\nvalue \"True \\<and> False\"\n\nvalue \"True \\<longrightarrow> False\"\n\nvalue \"False \\<longrightarrow> True\"\n\ndefinition \"TRUE \\<equiv> True\"\n\ndefinition \"FALSE \\<equiv> False\"\n\ndefinition \"A \\<equiv> TRUE \\<and> FALSE\"\nvalue A\n\nconsts boolconst :: bool\nspecification (boolconst)\n   \"boolconst = False\"\n  by auto\n\ndefinition AND :: \"bool \\<Rightarrow> bool \\<Rightarrow> bool\"\n  where \"AND a b \\<equiv> \\<not>a \\<and> \\<not>b\"\n\ndefinition \"lAND \\<equiv> \\<lambda>a b. \\<not>a \\<and> \\<not>b\"\n\nvalue \"AND True False\"\nvalue \"lAND True False\"\nvalue \"True \\<and> False\"\n\nlemma \"\\<forall>a b. (AND a b) = (\\<not>(a \\<or> b))\" \n  by (simp add:AND_def)\n\nlemma \"\\<forall>a b. (AND a b) = (lAND a b)\"\n  by (simp add:AND_def lAND_def)\n\nsubsection \\<open>Nat number\\<close>\n\nvalue \"3::nat\"\n\nvalue \"(1::nat) + 2\"\n\nvalue \"(3::nat) - 2\"\n\nvalue \"(2::nat) * 2\"\n\nvalue \"(2::nat)^3\"\n\nvalue \"(8::nat) div 3\"\n\nvalue \"(6::nat) mod 4\"\n\nvalue \"(2::nat) dvd 6\"\n\nvalue \"(2::nat) < 4\"\n\nvalue \"(2::nat) \\<le> 4\"\n\nvalue \"min (2::nat) 4\"\n\nvalue \"max (2::nat) 4\"\n\nvalue \"Min {1::nat, 3, 4}\"\n\nvalue \"Max {1::nat, 3, 4}\"\n\n(* value \"of_nat (5::nat)\" *)\n\n(* value \"op ^^ (\\<lambda>x::nat. x + 2) 3 4\" *)\n\n\ndefinition next_nat :: \"nat \\<Rightarrow> nat\"\n  where \"next_nat n \\<equiv> Suc n\"\n\ndefinition next_nat2 :: \"nat \\<Rightarrow> nat\"\n  where \"next_nat2 n \\<equiv> n + 1\"\n\nlemma \"next_nat n = next_nat2 n\"\n  by (simp add: next_nat_def next_nat2_def)\n\ndefinition times5 :: \"nat \\<Rightarrow> nat\"\n  where \"times5 n \\<equiv> 5 * n\"\n\ndefinition greater :: \"nat \\<Rightarrow> nat \\<Rightarrow> bool\"\n  where \"greater m n \\<equiv> (m > n)\"\n\ndefinition greater2 :: \"(nat \\<times> nat) \\<Rightarrow> bool\"\n  where \"greater2 mn \\<equiv> (fst mn > snd mn)\"\n\ndefinition greater3 :: \"(nat \\<times> nat) \\<Rightarrow> bool\"\n  where \"greater3 \\<equiv> \\<lambda>(m,n). (m > n)\"\n\ndefinition greater4 :: \"nat \\<Rightarrow> nat \\<Rightarrow> bool\"\n  where \"greater4 \\<equiv> \\<lambda>m n. (m > n)\"\n\nlemma \"\\<forall>m n. greater2 (m,n) = greater3 (m,n)\"\n   by (simp add: greater2_def greater3_def) \n\nlemma \"\\<forall>m n. greater3 (m,n) = greater4 m n\"\n  by (simp add: greater3_def greater4_def) \n\nvalue \"greater4 10\"\n\n(* value \"greater3 10\" *)\n\nsubsection \\<open>integer\\<close>\n\nvalue \"- (4::int)\"\n\nvalue \"(5::int) div 3\"\n\nvalue \"sgn (- (15::int))\"\n\ndefinition test :: \"int \\<rightharpoonup> int\"\n  where \"test n \\<equiv> (if n > 0 then Some n else None)\"\n\n\nsubsection \\<open>function type\\<close>\n\ndefinition f :: \"nat \\<Rightarrow> nat\"\n  where \"f x \\<equiv> 2 * x + 1\"\n\ndefinition g :: \"nat \\<Rightarrow> nat\"\n  where \"g x \\<equiv> 3 * x + 1\"\n\nterm f\nterm g\n\nterm \"True\"\n\ndefinition h :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\"\n  where \"h x y \\<equiv> x + y\"\n\nterm h\n\ndefinition h2 :: \"(nat \\<times> nat) \\<Rightarrow> nat\"\n  where \"h2 \\<equiv> \\<lambda>(x,y). x + y\"\n\nvalue \"h 3 5\"\nvalue \"h 3\"\nvalue \"h2 (3,5)\"\n\n(* value \"h2 3\" *)\n\nsubsection \\<open>term, expression, formula\\<close>\n\nconsts cst1 :: int\nspecification(cst1)\n  \"cst1 = 1\" by simp\n\nconsts cst2 :: int\nspecification(cst2)\n  \"cst2 > 1\"\n  using gt_ex by auto\n\ndefinition \"cst3 = (3::int)\"\nterm cst3\n\nthm cst3_def\n\nconsts fun1 :: \"nat \\<Rightarrow> nat\"\nspecification(fun1)\n  fun1def: \"fun1 n = Suc n\"\n  by auto\n\nlemma \"fun1 2 = 3\"\n  using fun1def by simp\n\naxiomatization fun2 :: \"nat \\<Rightarrow> nat\" where fun2_def: \"fun2 n = n + 2\"\n\nlemma \"fun2 5 = 7\"\n  using fun2_def by simp\n\ndefinition fun2' :: \"nat \\<Rightarrow> nat\"\n  where \"fun2' n \\<equiv> n + 2\"\n\nlemma \"fun2 = fun2'\"\n  using fun2_def fun2'_def by auto\n\nterm \"cst1\"\n\nterm \"''a string''\"\n\nterm \"\\<lambda>x. y\"\nvalue \"(\\<lambda>x. y) a\"\n\nterm \"\\<lambda>x. True\"\nvalue \"(\\<lambda>x. True) 2\"\nvalue \"(\\<lambda>x. True) ''abc''\"\nvalue \"(\\<lambda>x. True) 2.0\"\n\nterm \"\\<lambda>x. Suc x\"\nvalue \"(\\<lambda>x. Suc x) 5\"\n\nterm \"\\<lambda>x. (x::int) + 10\"\n\nterm \"\\<lambda>x. \\<lambda>y. x * y\"\nterm \"\\<lambda>x y. x * y\"\nvalue \"(\\<lambda>x y. x * y) (5::int) (6::int)\"\nvalue \"(\\<lambda>x y. x * y) (5.0::real) (6::int)\"\nvalue \"(\\<lambda>x y. x * y) (5.0::real) (6.5::real)\"\n\nterm \"\\<lambda>x y. (x::int) * y\"\nvalue \"(\\<lambda>x y. (x::int) * y) 5 6\"\n\nterm \"\\<lambda>x. (x::int) + a\"\nvalue \"(\\<lambda>x. (x::int) + a) 1\"\n\nlemma \"(\\<lambda>x y. x * y) = (\\<lambda>x. \\<lambda>y. x * y)\"\n  by simp\n\ndefinition \"lam1 \\<equiv> \\<lambda>x y z. (if x \\<ge> y then\n                               if x \\<ge> z then x else z\n                             else \n                               if y \\<ge> z then y else z)\"\nterm \"lam1\"\nvalue \"lam1 (2::int) 3 1\"\n\ndefinition \"lam2 \\<equiv> \\<lambda>f x. f x\"\nterm \"lam2\"\nvalue \"lam2 Suc 1\"\n\nterm \"(\\<lambda>f x. f x)\"\nvalue \"(\\<lambda>f x. f x) Suc 1\"\n\ndefinition \"lam3 \\<equiv> \\<lambda>f g x y. f (g x y)\"\nvalue \"lam3 Suc plus 10 20\"\nterm \"(\\<lambda>f g x y. f (g x y))\"\nvalue \"(\\<lambda>f g x y. f (g x y)) Suc plus 10 20\"\n\ndefinition f1 :: \"nat \\<Rightarrow> nat\"\n  where \"f1 \\<equiv> \\<lambda>x. 2 * x + 1\"\n\ndefinition g1 :: \"nat \\<Rightarrow> nat\"\n  where \"g1 \\<equiv> \\<lambda>x. 3 * x + 1\"\n\nlemma \"f1 = f\"\n  unfolding f_def f1_def by auto\n\nlemma \"g1 = g\"\n  unfolding g_def g1_def by auto\n\ndefinition addint :: \"int \\<Rightarrow> int\"\n  where \"addint i \\<equiv> i + 1\"\n\ndefinition addint2 :: \"int \\<Rightarrow> int\"\n  where \"addint2 \\<equiv> \\<lambda>i. (i + 1)\"\n\nthm addint_def\n\nlemma \"addint = addint2\"\n  unfolding addint_def addint2_def by simp\n\nlemma \"addint = (\\<lambda>i. (i + 1))\"\n  unfolding addint_def by simp\n\n\ndefinition if1 :: \"bool \\<Rightarrow> string\"\n  where \"if1 b \\<equiv> if b then \n                    ''its true'' \n                 else ''its false''\"\nvalue \"if1 True\"\nvalue \"(\\<lambda>b. if b then \n              ''its true'' \n            else ''its false'') True\"\n\nterm \"if b then e1 else e2\"\n\n\nterm \"let x = i; y = i + 1 in (x + y) * 2\"\n\ndefinition let1 :: \"nat \\<Rightarrow> nat\"\n  where \"let1 i = (let x = i; y = i + 1 in (x + y) * 2)\"\n\nvalue \"let1 3\"\n\nlemma \"(let x = i; y = i + 1 in (x + y) * 2) = (i + (i + 1)) * 2\"\n  by simp\n\ndefinition let2 :: \"nat \\<Rightarrow> nat\"\n  where \"let2 i = (let x = i; y = i + 1 in\n                    (\\<lambda>x. (Suc x) + y) x + (\\<lambda>y. (Suc y) + x) y)\"\n\nlemma \"let x = i; y = i + 1 \n       in (\\<lambda>x. (Suc x) + y) x + (\\<lambda>y. (Suc y) + x) y = ((\\<lambda>x. (Suc x) + (i + 1)) i + (\\<lambda>y. (Suc y) + i) (i + 1))\"\n  by simp\n\nvalue \"let2 3\"\n\n\nterm \"let x = (5::nat) in x * 2\"\n\n\ndefinition case1 :: \"nat \\<Rightarrow> string\"\n  where \"case1 n \\<equiv> case n of 0 \\<Rightarrow> ''zero'' |\n                             (Suc m) \\<Rightarrow> ''not zero''\"\n\nprimrec case2 :: \"nat \\<Rightarrow> string\"\n  where \"case2 0 = ''zero''\" |\n        \"case2 (Suc m) = ''not zero''\"\n\nlemma \"case1 x = case2 x\" \n  apply(simp add:case1_def) apply(induct x) apply(cases x) by simp+ \n\nvalue \"case1 0\"\nvalue \"case1 1\"\n\n\n\nend\n  ", "meta": {"author": "LVPGroup", "repo": "fpp", "sha": "7e18377ea2c553bf6e57412727a4f06832d93577", "save_path": "github-repos/isabelle/LVPGroup-fpp", "path": "github-repos/isabelle/LVPGroup-fpp/fpp-7e18377ea2c553bf6e57412727a4f06832d93577/2_functionalprog/BasicDef.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.853912760387131, "lm_q2_score": 0.8221891239865619, "lm_q1q2_score": 0.7020777844236422}}
{"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>Models of Relation Algebra\\<close>\n\ntheory Relation_Algebra_Models\n  imports Relation_Algebra Kleene_Algebra.Inf_Matrix\nbegin\n\ntext \\<open>We formalise two models. First we show the obvious: binary relations\nform a relation algebra. Then we show that infinite matrices (which we\nformalised originally for Kleene algebras) form models of relation algebra if\nwe restrict their element type to @{typ bool}.\\<close>\n\nsubsection \\<open>Binary Relations\\<close>\n\ntext \\<open>Since Isabelle's libraries for binary relations are very well\ndeveloped, the proof for this model is entirely trivial.\\<close>\n\ninterpretation rel_relation_algebra: relation_algebra \"(-)\" uminus \"(\\<inter>)\" \"(\\<subseteq>)\" \"(\\<subset>)\" \"(\\<union>)\" \"{}\" UNIV \"(O)\" Relation.converse Id\nby unfold_locales auto\n\nsubsection \\<open>Infinite Boolean Matrices\\<close>\n\ntext \\<open>Next we consider infinite Boolean matrices. We define the maximal\nBoolean matrix (all of its entries are @{const True}), the converse or\ntranspose of a matrix, the intersection of two Boolean matrices and the\ncomplement of a Boolean matrix.\\<close>\n\ndefinition mat_top :: \"('a, 'b, bool) matrix\" (\"\\<tau>\")\n  where \"\\<tau> i j \\<equiv> True\"\n\ndefinition mat_transpose :: \"('a, 'b, 'c) matrix \\<Rightarrow> ('b, 'a, 'c) matrix\" (\"_\\<^sup>\\<dagger>\" [101] 100)\n  where \"f\\<^sup>\\<dagger> \\<equiv> (\\<lambda>i j. f j i)\"\n\ndefinition mat_inter :: \"('a, 'b, bool) matrix \\<Rightarrow> ('a, 'b, bool) matrix \\<Rightarrow> ('a, 'b, bool) matrix\" (infixl \"\\<sqinter>\" 70)\n  where \"f \\<sqinter> g \\<equiv> (\\<lambda>i j. f i j \\<cdot> g i j)\"\n\ndefinition mat_complement :: \"('a, 'b, bool) matrix \\<Rightarrow> ('a, 'b, bool) matrix\" (\"_\\<^sup>c\" [101] 100)\n  where \"f\\<^sup>c = (\\<lambda>i j. - f i j)\"\n\ntext \\<open>Next we show that the Booleans form a dioid. We state this as an\n\\emph{instantiation} result. The Kleene algebra files contain an\n\\emph{interpretation} proof, which is not sufficient for our purposes.\\<close>\n\ninstantiation bool :: dioid_one_zero\nbegin\n\n  definition zero_bool_def:\n    \"zero_bool \\<equiv> False\"\n\n  definition one_bool_def:\n    \"one_bool \\<equiv> True\"\n\n  definition times_bool_def:\n    \"times_bool \\<equiv> (\\<and>)\"\n\n  definition plus_bool_def:\n    \"plus_bool \\<equiv> (\\<or>)\"\n\n  instance\n  by standard (auto simp: plus_bool_def times_bool_def one_bool_def zero_bool_def)\n\nend\n\ntext \\<open>We now show that infinite Boolean matrices form a Boolean algebra.\\<close>\n\nlemma le_funI2: \"(\\<And>i j. f i j \\<le> g i j) \\<Longrightarrow> f \\<le> g\"\nby (metis le_funI)\n\ninterpretation matrix_ba: boolean_algebra \"\\<lambda>f g. f \\<sqinter> g\\<^sup>c\" mat_complement \"(\\<sqinter>)\" \"(\\<le>)\" \"(<)\" mat_add mat_zero mat_top\nby standard (force intro!: le_funI simp: mat_inter_def plus_bool_def mat_add_def mat_zero_def zero_bool_def mat_top_def mat_complement_def)+\n\ntext \\<open>We continue working towards the main result of this section, that\ninfinite Boolean matrices form a relation algebra.\\<close>\n\nlemma mat_mult_var: \"(f \\<otimes> g) = (\\<lambda>i j. \\<Sum> {(f i k) * (g k j) | k. k \\<in> UNIV})\"\nby (rule ext)+ (simp add: mat_mult_def)\n\ntext \\<open>The following fact is related to proving the last relation algebra\naxiom in the matrix model. It is more complicated than necessary since finite\ninfima are not well developed in Isabelle. Instead we translate properties of\nfinite infima into properties of finite suprema by using Boolean algebra. For\nfinite suprema we have developed special-purpose theorems in the Kleene algebra\nfiles.\\<close>\n\nlemma mat_res_pointwise:\n  fixes i j :: \"'a::finite\"\n    and x :: \"('a, 'a, bool) matrix\"\n  shows \"(x\\<^sup>\\<dagger> \\<otimes> (x \\<otimes> y)\\<^sup>c) i j \\<le> (y\\<^sup>c) i j\"\nproof -\n  have \"\\<Sum>{(x\\<^sup>\\<dagger>) i k \\<and> ((x \\<otimes> y)\\<^sup>c) k j |k. k \\<in> UNIV} \\<le> (y\\<^sup>c) i j \\<longleftrightarrow> (\\<forall>k. ((x\\<^sup>\\<dagger>) i k \\<and> ((x \\<otimes> y)\\<^sup>c) k j) \\<le> (y\\<^sup>c) i j)\"\n    by (subst sum_sup) auto\n  also have \"\\<dots> \\<longleftrightarrow> (\\<forall>k. ((x\\<^sup>\\<dagger>) i k \\<and> - (x \\<otimes> y) k j) \\<le> (y\\<^sup>c) i j)\"\n    by (simp only: mat_complement_def)\n  also have \"\\<dots> \\<longleftrightarrow> (\\<forall>k. (x\\<^sup>\\<dagger>) i k \\<le> ((y\\<^sup>c) i j \\<or> (x \\<otimes> y) k j))\"\n    by auto\n  also have \"\\<dots> \\<longleftrightarrow> (\\<forall>k. (x\\<^sup>\\<dagger>) i k \\<le> (- y i j \\<or> (x \\<otimes> y) k j))\"\n    by (simp only: mat_complement_def)\n  also have \"\\<dots> \\<longleftrightarrow> (\\<forall>k. ((x\\<^sup>\\<dagger>) i k \\<and> y i j) \\<le> (x \\<otimes> y) k j)\"\n    by auto\n  also have \"\\<dots> \\<longleftrightarrow> (\\<forall>k. (x k i \\<and> y i j) \\<le> (x \\<otimes> y) k j)\"\n    by (simp add: mat_transpose_def)\n  also have \"\\<dots> \\<longleftrightarrow> (\\<forall>k. (x k i \\<and> y i j) \\<le> \\<Sum>{x k l \\<and> y l j |l. l \\<in> UNIV})\"\n    by (simp add: mat_mult_def times_bool_def)\n  also have \"\\<dots> \\<longleftrightarrow> (\\<forall>k. \\<Sum>{x k i \\<and> y i j} \\<le> \\<Sum>{x k l \\<and> y l j |l. l \\<in> UNIV})\"\n    by simp\n  also have \"\\<dots> \\<longleftrightarrow> True\"\n    by (intro iffI TrueI allI sum_intro[rule_format]) auto\n  moreover have \"(x\\<^sup>\\<dagger> \\<otimes> (x \\<otimes> y)\\<^sup>c) i j = \\<Sum>{(x\\<^sup>\\<dagger>) i k \\<and> ((x \\<otimes> y)\\<^sup>c) k j |k. k \\<in> UNIV}\"\n    by (subst mat_mult_def) (simp add: times_bool_def)\n  ultimately show ?thesis\n    by auto\nqed\n\ntext \\<open>Finally the main result of this section.\\<close>\n\ninterpretation matrix_ra: relation_algebra \"\\<lambda>f g. f \\<sqinter> g\\<^sup>c\" mat_complement \"(\\<sqinter>)\" \"(\\<le>)\" \"(<)\" \"(\\<oplus>)\" \"\\<lambda>i j. False\" \\<tau> \"(\\<otimes>)\" mat_transpose \\<epsilon>\nproof\n  fix x y z :: \"'a::finite \\<Rightarrow> 'a \\<Rightarrow> bool\"\n  show \"(\\<lambda>(i::'a) j::'a. False) \\<le> x\"\n    by (metis predicate2I)\n  show \"x \\<sqinter> x\\<^sup>c = (\\<lambda>i j. False)\"\n    by (metis matrix_ba.bot.extremum matrix_ba.inf_compl_bot rev_predicate2D)\n  show \"x \\<oplus> x\\<^sup>c = \\<tau>\"\n    by (fact matrix_ba.sup_compl_top)\n  show \"x \\<sqinter> y\\<^sup>c = x \\<sqinter> y\\<^sup>c\"\n    by (fact refl)\n  show \"x \\<otimes> y \\<otimes> z = x \\<otimes> (y \\<otimes> z)\"\n    by (metis mat_mult_assoc)\n  show \"x \\<otimes> \\<epsilon> = x\"\n    by (fact mat_oner)\n  show \"x \\<oplus> y \\<otimes> z = (x \\<otimes> z) \\<oplus> (y \\<otimes> z)\"\n    by (fact mat_distr)\n  show \"(x\\<^sup>\\<dagger>)\\<^sup>\\<dagger> = x\"\n    by (simp add: mat_transpose_def)\n  show \"(x \\<oplus> y)\\<^sup>\\<dagger> = x\\<^sup>\\<dagger> \\<oplus> y\\<^sup>\\<dagger>\"\n    by (simp add: mat_transpose_def mat_add_def)\n  show \"(x \\<otimes> y)\\<^sup>\\<dagger> = y\\<^sup>\\<dagger> \\<otimes> x\\<^sup>\\<dagger>\"\n    by (simp add: mat_transpose_def mat_mult_var times_bool_def conj_commute)\n  show \"x\\<^sup>\\<dagger> \\<otimes> (x \\<otimes> y)\\<^sup>c \\<le> y\\<^sup>c\"\n    by (metis le_funI2 mat_res_pointwise)\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/Relation_Algebra/Relation_Algebra_Models.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8539127492339909, "lm_q2_score": 0.8221891327004133, "lm_q1q2_score": 0.7020777826945205}}
{"text": "(*  Title:       Safe OCL\n    Author:      Denis Nikiforov, March 2019\n    Maintainer:  Denis Nikiforov <denis.nikif at gmail.com>\n    License:     LGPL\n*)\nchapter \\<open>Examples\\<close>\ntheory OCL_Examples\n  imports OCL_Normalization\nbegin\n\n(*** Classes ****************************************************************)\n\nsection \\<open>Classes\\<close>\n\ndatatype classes1 =\n  Object | Person | Employee | Customer | Project | Task | Sprint\n\ninductive subclass1 where\n  \"c \\<noteq> Object \\<Longrightarrow>\n   subclass1 c Object\"\n| \"subclass1 Employee Person\"\n| \"subclass1 Customer Person\"\n\ninstantiation classes1 :: semilattice_sup\nbegin\n\ndefinition \"(<) \\<equiv> subclass1\"\ndefinition \"(\\<le>) \\<equiv> subclass1\\<^sup>=\\<^sup>=\"\n\nfun sup_classes1 where\n  \"Object \\<squnion> _ = Object\"\n| \"Person \\<squnion> c = (if c = Person \\<or> c = Employee \\<or> c = Customer\n    then Person else Object)\"\n| \"Employee \\<squnion> c = (if c = Employee then Employee else\n    if c = Person \\<or> c = Customer then Person else Object)\"\n| \"Customer \\<squnion> c = (if c = Customer then Customer else\n    if c = Person \\<or> c = Employee then Person else Object)\"\n| \"Project \\<squnion> c = (if c = Project then Project else Object)\"\n| \"Task \\<squnion> c = (if c = Task then Task else Object)\"\n| \"Sprint \\<squnion> c = (if c = Sprint then Sprint else Object)\"\n\nlemma less_le_not_le_classes1:\n  \"c < d \\<longleftrightarrow> c \\<le> d \\<and> \\<not> d \\<le> c\"\n  for c d :: classes1\n  unfolding less_classes1_def less_eq_classes1_def\n  using subclass1.simps by auto\n\nlemma order_refl_classes1:\n  \"c \\<le> c\"\n  for c :: classes1\n  unfolding less_eq_classes1_def by simp\n\nlemma order_trans_classes1:\n  \"c \\<le> d \\<Longrightarrow> d \\<le> e \\<Longrightarrow> c \\<le> e\"\n  for c d e :: classes1\n  unfolding less_eq_classes1_def\n  using subclass1.simps by auto\n\nlemma antisym_classes1:\n  \"c \\<le> d \\<Longrightarrow> d \\<le> c \\<Longrightarrow> c = d\"\n  for c d :: classes1\n  unfolding less_eq_classes1_def\n  using subclass1.simps by auto\n\nlemma sup_ge1_classes1:\n  \"c \\<le> c \\<squnion> d\"\n  for c d :: classes1\n  by (induct c; auto simp add: less_eq_classes1_def less_classes1_def subclass1.simps)\n\nlemma sup_ge2_classes1:\n  \"d \\<le> c \\<squnion> d\"\n  for c d :: classes1\n  by (induct c; auto simp add: less_eq_classes1_def less_classes1_def subclass1.simps)\n\nlemma sup_least_classes1:\n  \"c \\<le> e \\<Longrightarrow> d \\<le> e \\<Longrightarrow> c \\<squnion> d \\<le> e\"\n  for c d e :: classes1\n  by (induct c; induct d;\n      auto simp add: less_eq_classes1_def less_classes1_def subclass1.simps)\n\ninstance\n  apply intro_classes\n  apply (simp add: less_le_not_le_classes1)\n  apply (simp add: order_refl_classes1)\n  apply (rule order_trans_classes1; auto)\n  apply (simp add: antisym_classes1)\n  apply (simp add: sup_ge1_classes1)\n  apply (simp add: sup_ge2_classes1)\n  by (simp add: sup_least_classes1)\n\nend\n\ncode_pred subclass1 .\n\nfun subclass1_fun where\n  \"subclass1_fun Object \\<C> = False\"\n| \"subclass1_fun Person \\<C> = (\\<C> = Object)\"\n| \"subclass1_fun Employee \\<C> = (\\<C> = Object \\<or> \\<C> = Person)\"\n| \"subclass1_fun Customer \\<C> = (\\<C> = Object \\<or> \\<C> = Person)\"\n| \"subclass1_fun Project \\<C> = (\\<C> = Object)\"\n| \"subclass1_fun Task \\<C> = (\\<C> = Object)\"\n| \"subclass1_fun Sprint \\<C> = (\\<C> = Object)\"\n\nlemma less_classes1_code [code]:\n  \"(<) = subclass1_fun\"\nproof (intro ext iffI)\n  fix \\<C> \\<D> :: \"classes1\"\n  show \"\\<C> < \\<D> \\<Longrightarrow> subclass1_fun \\<C> \\<D>\"\n    unfolding less_classes1_def\n    apply (erule subclass1.cases, auto)\n    using subclass1_fun.elims(3) by blast\n  show \"subclass1_fun \\<C> \\<D> \\<Longrightarrow> \\<C> < \\<D>\"\n    by (erule subclass1_fun.elims, auto simp add: less_classes1_def subclass1.intros)\nqed\n\nlemma less_eq_classes1_code [code]:\n  \"(\\<le>) = (\\<lambda>x y. subclass1_fun x y \\<or> x = y)\"\n  unfolding dual_order.order_iff_strict less_classes1_code\n  by auto\n\n(*** Object Model ***********************************************************)\n\nsection \\<open>Object Model\\<close>\n\nabbreviation \"\\<Gamma>\\<^sub>0 \\<equiv> fmempty :: classes1 type env\"\ndeclare [[coercion \"ObjectType :: classes1 \\<Rightarrow> classes1 basic_type\"]]\ndeclare [[coercion \"phantom :: String.literal \\<Rightarrow> classes1 enum\"]]\n\ninstantiation classes1 :: ocl_object_model\nbegin\n\ndefinition \"classes_classes1 \\<equiv>\n  {|Object, Person, Employee, Customer, Project, Task, Sprint|}\"\n\ndefinition \"attributes_classes1 \\<equiv> fmap_of_list [\n  (Person, fmap_of_list [\n    (STR ''name'', String[1] :: classes1 type)]),\n  (Employee, fmap_of_list [\n    (STR ''name'', String[1]),\n    (STR ''position'', String[1])]),\n  (Customer, fmap_of_list [\n    (STR ''vip'', Boolean[1])]),\n  (Project, fmap_of_list [\n    (STR ''name'', String[1]),\n    (STR ''cost'', Real[?])]),\n  (Task, fmap_of_list [\n    (STR ''description'', String[1])])]\"\n\nabbreviation \"assocs \\<equiv> [\n  STR ''ProjectManager'' \\<mapsto>\\<^sub>f [\n    STR ''projects'' \\<mapsto>\\<^sub>f (Project, 0::nat, \\<infinity>::enat, False, True),\n    STR ''manager'' \\<mapsto>\\<^sub>f (Employee, 1, 1, False, False)],\n  STR ''ProjectMember'' \\<mapsto>\\<^sub>f [\n    STR ''member_of'' \\<mapsto>\\<^sub>f (Project, 0, \\<infinity>, False, False),\n    STR ''members'' \\<mapsto>\\<^sub>f (Employee, 1, 20, True, True)],\n  STR ''ManagerEmployee'' \\<mapsto>\\<^sub>f [\n    STR ''line_manager'' \\<mapsto>\\<^sub>f (Employee, 0, 1, False, False),\n    STR ''project_manager'' \\<mapsto>\\<^sub>f (Employee, 0, \\<infinity>, False, False),\n    STR ''employees'' \\<mapsto>\\<^sub>f (Employee, 3, 7, False, False)],\n  STR ''ProjectCustomer'' \\<mapsto>\\<^sub>f [\n    STR ''projects'' \\<mapsto>\\<^sub>f (Project, 0, \\<infinity>, False, True),\n    STR ''customer'' \\<mapsto>\\<^sub>f (Customer, 1, 1, False, False)],\n  STR ''ProjectTask'' \\<mapsto>\\<^sub>f [\n    STR ''project'' \\<mapsto>\\<^sub>f (Project, 1, 1, False, False),\n    STR ''tasks'' \\<mapsto>\\<^sub>f (Task, 0, \\<infinity>, True, True)],\n  STR ''SprintTaskAssignee'' \\<mapsto>\\<^sub>f [\n    STR ''sprint'' \\<mapsto>\\<^sub>f (Sprint, 0, 10, False, True),\n    STR ''tasks'' \\<mapsto>\\<^sub>f (Task, 0, 5, False, True),\n    STR ''assignee'' \\<mapsto>\\<^sub>f (Employee, 0, 1, False, False)]]\"\n\ndefinition \"associations_classes1 \\<equiv> assocs\"\n\ndefinition \"association_classes_classes1 \\<equiv> fmempty :: classes1 \\<rightharpoonup>\\<^sub>f assoc\"\n\ntext \\<open>\n\\begin{verbatim}\ncontext Project\ndef: membersCount() : Integer[1] = members->size()\ndef: membersByName(mn : String[1]) : Set(Employee[1]) =\n       members->select(member | member.name = mn)\nstatic def: allProjects() : Set(Project[1]) =\n              Project[1].allInstances()\n\\end{verbatim}\\<close>\n\ndefinition \"operations_classes1 \\<equiv> [\n  (STR ''membersCount'', Project[1], [], Integer[1], False,\n   Some (OperationCall\n    (AssociationEndCall (Var STR ''self'') DotCall None STR ''members'')\n    ArrowCall CollectionSizeOp [])),\n  (STR ''membersByName'', Project[1], [(STR ''mn'', String[1], In)],\n    Set Employee[1], False,\n   Some (SelectIteratorCall\n    (AssociationEndCall (Var STR ''self'') DotCall None STR ''members'')\n    ArrowCall [STR ''member''] None\n    (OperationCall\n      (AttributeCall (Var STR ''member'') DotCall STR ''name'')\n      DotCall EqualOp [Var STR ''mn'']))),\n  (STR ''allProjects'', Project[1], [], Set Project[1], True,\n   Some (MetaOperationCall Project[1] AllInstancesOp))\n  ] :: (classes1 type, classes1 expr) oper_spec list\"\n\ndefinition \"literals_classes1 \\<equiv> fmap_of_list [\n  (STR ''E1'' :: classes1 enum, {|STR ''A'', STR ''B''|}),\n  (STR ''E2'', {|STR ''C'', STR ''D'', STR ''E''|})]\"\n\n\nlemma assoc_end_min_less_eq_max:\n  \"assoc |\\<in>| fmdom assocs \\<Longrightarrow>\n   fmlookup assocs assoc = Some ends \\<Longrightarrow>\n   role |\\<in>| fmdom ends  \\<Longrightarrow>\n   fmlookup ends role = Some end \\<Longrightarrow>\n   assoc_end_min end \\<le> assoc_end_max end\"\n  unfolding assoc_end_min_def assoc_end_max_def\n  using zero_enat_def one_enat_def numeral_eq_enat by auto\n\nlemma association_ends_unique:\n  assumes \"association_ends' classes assocs \\<C> from role end\\<^sub>1\"\n      and \"association_ends' classes assocs \\<C> from role end\\<^sub>2\"\n    shows \"end\\<^sub>1 = end\\<^sub>2\"\nproof -\n  have \"\\<not> association_ends_not_unique' classes assocs\" by eval\n  with assms show ?thesis\n    using association_ends_not_unique'.simps by blast\nqed\n\ninstance\n  apply standard\n  unfolding associations_classes1_def\n  using assoc_end_min_less_eq_max apply blast\n  using association_ends_unique by blast\n\nend\n\n(*** Simplification Rules ***************************************************)\n\nsection \\<open>Simplification Rules\\<close>\n\nlemma ex_alt_simps [simp]:\n  \"\\<exists>a. a\"\n  \"\\<exists>a. \\<not> a\"\n  \"(\\<exists>a. (a \\<longrightarrow> P) \\<and> a) = P\"\n  \"(\\<exists>a. \\<not> a \\<and> (\\<not> a \\<longrightarrow> P)) = P\"\n  by auto\n\ndeclare numeral_eq_enat [simp]\n\nlemmas basic_type_le_less [simp] = Orderings.order_class.le_less\n  for x y :: \"'a basic_type\"\n\ndeclare element_type_alt_simps [simp]\ndeclare update_element_type.simps [simp]\ndeclare to_unique_collection.simps [simp]\ndeclare to_nonunique_collection.simps [simp]\ndeclare to_ordered_collection.simps [simp]\n\ndeclare assoc_end_class_def [simp]\ndeclare assoc_end_min_def [simp]\ndeclare assoc_end_max_def [simp]\ndeclare assoc_end_ordered_def [simp]\ndeclare assoc_end_unique_def [simp]\n\ndeclare oper_name_def [simp]\ndeclare oper_context_def [simp]\ndeclare oper_params_def [simp]\ndeclare oper_result_def [simp]\ndeclare oper_static_def [simp]\ndeclare oper_body_def [simp]\n\ndeclare oper_in_params_def [simp]\ndeclare oper_out_params_def [simp]\n\ndeclare assoc_end_type_def [simp]\ndeclare oper_type_def [simp]\n\ndeclare op_type_alt_simps [simp]\ndeclare typing_alt_simps [simp]\ndeclare normalize_alt_simps [simp]\ndeclare nf_typing.simps [simp]\n\ndeclare subclass1.intros [intro]\ndeclare less_classes1_def [simp]\n\ndeclare literals_classes1_def [simp]\n\nlemma attribute_Employee_name [simp]:\n  \"attribute Employee STR ''name'' \\<D> \\<tau> =\n   (\\<D> = Employee \\<and> \\<tau> = String[1])\"\nproof -\n  have \"attribute Employee STR ''name'' Employee String[1]\"\n    by eval\n  thus ?thesis\n    using attribute_det by blast\nqed\n\nlemma association_end_Project_members [simp]:\n  \"association_end Project None STR ''members'' \\<D> \\<tau> =\n   (\\<D> = Project \\<and> \\<tau> = (Employee, 1, 20, True, True))\"\nproof -\n  have \"association_end Project None STR ''members''\n          Project (Employee, 1, 20, True, True)\"\n    by eval\n  thus ?thesis\n    using association_end_det by blast\nqed\n\nlemma association_end_Employee_projects_simp [simp]:\n  \"association_end Employee None STR ''projects'' \\<D> \\<tau> =\n   (\\<D> = Employee \\<and> \\<tau> = (Project, 0, \\<infinity>, False, True))\"\nproof -\n  have \"association_end Employee None STR ''projects''\n          Employee (Project, 0, \\<infinity>, False, True)\"\n    by eval\n  thus ?thesis\n    using association_end_det by blast\nqed\n\nlemma static_operation_Project_allProjects [simp]:\n  \"static_operation \\<langle>Project\\<rangle>\\<^sub>\\<T>[1] STR ''allProjects'' [] oper =\n   (oper = (STR ''allProjects'', \\<langle>Project\\<rangle>\\<^sub>\\<T>[1], [], Set \\<langle>Project\\<rangle>\\<^sub>\\<T>[1], True,\n     Some (MetaOperationCall \\<langle>Project\\<rangle>\\<^sub>\\<T>[1] AllInstancesOp)))\"\nproof -\n  have \"static_operation \\<langle>Project\\<rangle>\\<^sub>\\<T>[1] STR ''allProjects'' []\n    (STR ''allProjects'', \\<langle>Project\\<rangle>\\<^sub>\\<T>[1], [], Set \\<langle>Project\\<rangle>\\<^sub>\\<T>[1], True,\n     Some (MetaOperationCall \\<langle>Project\\<rangle>\\<^sub>\\<T>[1] AllInstancesOp))\"\n    by eval\n  thus ?thesis\n    using static_operation_det by blast\nqed\n\n(*** Basic Types ************************************************************)\n\nsection \\<open>Basic Types\\<close>\n\nsubsection \\<open>Positive Cases\\<close>\n\nlemma \"UnlimitedNatural < (Real :: classes1 basic_type)\" by simp\nlemma \"\\<langle>Employee\\<rangle>\\<^sub>\\<T> < \\<langle>Person\\<rangle>\\<^sub>\\<T>\" by auto\nlemma \"\\<langle>Person\\<rangle>\\<^sub>\\<T> \\<le> OclAny\" by simp\n\nsubsection \\<open>Negative Cases\\<close>\n\nlemma \"\\<not> String \\<le> (Boolean :: classes1 basic_type)\" by simp\n\n(*** Types ******************************************************************)\n\nsection \\<open>Types\\<close>\n\nsubsection \\<open>Positive Cases\\<close>\n\nlemma \"Integer[?] < (OclSuper :: classes1 type)\" by simp\nlemma \"Collection Real[?] < (OclSuper :: classes1 type)\" by simp\nlemma \"Set (Collection Boolean[1]) < (OclSuper :: classes1 type)\" by simp\nlemma \"Set (Bag Boolean[1]) < Set (Collection Boolean[?] :: classes1 type)\"\n  by simp\nlemma \"Tuple (fmap_of_list [(STR ''a'', Boolean[1]), (STR ''b'', Integer[1])]) <\n       Tuple (fmap_of_list [(STR ''a'', Boolean[?] :: classes1 type)])\" by eval\n\nlemma \"Integer[1] \\<squnion> (Real[?] :: classes1 type) = Real[?]\" by simp\nlemma \"Set Integer[1] \\<squnion> Set (Real[1] :: classes1 type) = Set Real[1]\" by simp\nlemma \"Set Integer[1] \\<squnion> Bag (Boolean[?] :: classes1 type) = Collection OclAny[?]\"\n  by simp\nlemma \"Set Integer[1] \\<squnion> (Real[1] :: classes1 type) = OclSuper\" by simp\n\nsubsection \\<open>Negative Cases\\<close>\n\nlemma \"\\<not> OrderedSet Boolean[1] < Set (Boolean[1] :: classes1 type)\" by simp\n\n(*** Typing *****************************************************************)\n\nsection \\<open>Typing\\<close>\n\nsubsection \\<open>Positive Cases\\<close>\n\ntext \\<open>\n\\<^verbatim>\\<open>E1::A : E1[1]\\<close>\\<close>\nlemma\n  \"\\<Gamma>\\<^sub>0 \\<turnstile> EnumLiteral STR ''E1'' STR ''A'' : (Enum STR ''E1'')[1]\"\n  by simp\n\ntext \\<open>\n\\<^verbatim>\\<open>true or false : Boolean[1]\\<close>\\<close>\nlemma\n  \"\\<Gamma>\\<^sub>0 \\<turnstile> OperationCall (BooleanLiteral True) DotCall OrOp\n    [BooleanLiteral False] : Boolean[1]\"\n  by simp\n\ntext \\<open>\n\\<^verbatim>\\<open>null and true : Boolean[?]\\<close>\\<close>\nlemma\n  \"\\<Gamma>\\<^sub>0 \\<turnstile> OperationCall (NullLiteral) DotCall AndOp\n    [BooleanLiteral True] : Boolean[?]\"\n  by simp\n\ntext \\<open>\n\\<^verbatim>\\<open>let x : Real[1] = 5 in x + 7 : Real[1]\\<close>\\<close>\nlemma\n  \"\\<Gamma>\\<^sub>0 \\<turnstile> Let (STR ''x'') (Some Real[1]) (IntegerLiteral 5)\n    (OperationCall (Var STR ''x'') DotCall PlusOp [IntegerLiteral 7]) : Real[1]\"\n  by simp\n\ntext \\<open>\n\\<^verbatim>\\<open>null.oclIsUndefined() : Boolean[1]\\<close>\\<close>\nlemma\n  \"\\<Gamma>\\<^sub>0 \\<turnstile> OperationCall (NullLiteral) DotCall OclIsUndefinedOp [] : Boolean[1]\"\n  by simp\n\ntext \\<open>\n\\<^verbatim>\\<open>Sequence{1..5, null}.oclIsUndefined() : Sequence(Boolean[1])\\<close>\\<close>\nlemma\n  \"\\<Gamma>\\<^sub>0 \\<turnstile> OperationCall (CollectionLiteral SequenceKind\n    [CollectionRange (IntegerLiteral 1) (IntegerLiteral 5),\n     CollectionItem NullLiteral])\n    DotCall OclIsUndefinedOp [] : Sequence Boolean[1]\"\n  by simp\n\ntext \\<open>\n\\<^verbatim>\\<open>Sequence{1..5}->product(Set{'a', 'b'})\n  : Set(Tuple(first: Integer[1], second: String[1]))\\<close>\\<close>\nlemma\n  \"\\<Gamma>\\<^sub>0 \\<turnstile> OperationCall (CollectionLiteral SequenceKind\n    [CollectionRange (IntegerLiteral 1) (IntegerLiteral 5)])\n    ArrowCall ProductOp\n    [CollectionLiteral SetKind\n      [CollectionItem (StringLiteral ''a''),\n       CollectionItem (StringLiteral ''b'')]] :\n    Set (Tuple (fmap_of_list [\n      (STR ''first'', Integer[1]), (STR ''second'', String[1])]))\"\n  by simp\n\ntext \\<open>\n\\<^verbatim>\\<open>Sequence{1..5, null}?->iterate(x, acc : Real[1] = 0 | acc + x)\n  : Real[1]\\<close>\\<close>\nlemma\n  \"\\<Gamma>\\<^sub>0 \\<turnstile> IterateCall (CollectionLiteral SequenceKind\n    [CollectionRange (IntegerLiteral 1) (IntegerLiteral 5),\n     CollectionItem NullLiteral]) SafeArrowCall\n    [STR ''x''] None\n    (STR ''acc'') (Some Real[1]) (IntegerLiteral 0)\n    (OperationCall (Var STR ''acc'') DotCall PlusOp [Var STR ''x'']) : Real[1]\"\n  by simp\n\ntext \\<open>\n\\<^verbatim>\\<open>Sequence{1..5, null}?->max() : Integer[1]\\<close>\\<close>\nlemma\n  \"\\<Gamma>\\<^sub>0 \\<turnstile> OperationCall (CollectionLiteral SequenceKind\n    [CollectionRange (IntegerLiteral 1) (IntegerLiteral 5),\n     CollectionItem NullLiteral])\n    SafeArrowCall CollectionMaxOp [] : Integer[1]\"\n  by simp\n\ntext \\<open>\n\\<^verbatim>\\<open>let x : Sequence(String[?]) = Sequence{'abc', 'zxc'} in\nx->any(it | it = 'test') : String[?]\\<close>\\<close>\nlemma\n  \"\\<Gamma>\\<^sub>0 \\<turnstile> Let (STR ''x'') (Some (Sequence String[?]))\n    (CollectionLiteral SequenceKind\n      [CollectionItem (StringLiteral ''abc''),\n       CollectionItem (StringLiteral ''zxc'')])\n    (AnyIteratorCall (Var STR ''x'') ArrowCall\n      [STR ''it''] None\n      (OperationCall (Var STR ''it'') DotCall EqualOp\n        [StringLiteral ''test''])) : String[?]\"\n  by simp\n\ntext \\<open>\n\\<^verbatim>\\<open>let x : Sequence(String[?]) = Sequence{'abc', 'zxc'} in\nx?->closure(it | it) : OrderedSet(String[1])\\<close>\\<close>\nlemma\n  \"\\<Gamma>\\<^sub>0 \\<turnstile> Let STR ''x'' (Some (Sequence String[?]))\n    (CollectionLiteral SequenceKind\n      [CollectionItem (StringLiteral ''abc''),\n       CollectionItem (StringLiteral ''zxc'')])\n    (ClosureIteratorCall (Var STR ''x'') SafeArrowCall\n      [STR ''it''] None\n      (Var STR ''it'')) : OrderedSet String[1]\"\n  by simp\n\ntext \\<open>\n\\<^verbatim>\\<open>context Employee:\nname : String[1]\\<close>\\<close>\nlemma\n  \"\\<Gamma>\\<^sub>0(STR ''self'' \\<mapsto>\\<^sub>f Employee[1]) \\<turnstile>\n    AttributeCall (Var STR ''self'') DotCall STR ''name'' : String[1]\"\n  by simp\n\ntext \\<open>\n\\<^verbatim>\\<open>context Employee:\nprojects : Set(Project[1])\\<close>\\<close>\nlemma\n  \"\\<Gamma>\\<^sub>0(STR ''self'' \\<mapsto>\\<^sub>f Employee[1]) \\<turnstile>\n    AssociationEndCall (Var STR ''self'') DotCall None\n      STR ''projects'' : Set Project[1]\"\n  by simp\n\ntext \\<open>\n\\<^verbatim>\\<open>context Employee:\nprojects.members : Bag(Employee[1])\\<close>\\<close>\nlemma\n  \"\\<Gamma>\\<^sub>0(STR ''self'' \\<mapsto>\\<^sub>f Employee[1]) \\<turnstile>\n    AssociationEndCall (AssociationEndCall (Var STR ''self'')\n        DotCall None STR ''projects'')\n      DotCall None STR ''members'' : Bag Employee[1]\"\n  by simp\n\ntext \\<open>\n\\<^verbatim>\\<open>Project[?].allInstances() : Set(Project[?])\\<close>\\<close>\nlemma\n  \"\\<Gamma>\\<^sub>0 \\<turnstile> MetaOperationCall Project[?] AllInstancesOp : Set Project[?]\"\n  by simp\n\ntext \\<open>\n\\<^verbatim>\\<open>Project[1]::allProjects() : Set(Project[1])\\<close>\\<close>\nlemma\n  \"\\<Gamma>\\<^sub>0 \\<turnstile> StaticOperationCall Project[1] STR ''allProjects'' [] : Set Project[1]\"\n  by simp\n\nsubsection \\<open>Negative Cases\\<close>\n\ntext \\<open>\n\\<^verbatim>\\<open>true = null\\<close>\\<close>\nlemma\n  \"\\<nexists>\\<tau>. \\<Gamma>\\<^sub>0 \\<turnstile> OperationCall (BooleanLiteral True) DotCall EqualOp\n    [NullLiteral] : \\<tau>\"\n  by simp\n\ntext \\<open>\n\\<^verbatim>\\<open>let x : Boolean[1] = 5 in x and true\\<close>\\<close>\nlemma\n  \"\\<nexists>\\<tau>. \\<Gamma>\\<^sub>0 \\<turnstile> Let STR ''x'' (Some Boolean[1]) (IntegerLiteral 5)\n    (OperationCall (Var STR ''x'') DotCall AndOp [BooleanLiteral True]) : \\<tau>\"\n  by simp\n\ntext \\<open>\n\\<^verbatim>\\<open>let x : Sequence(String[?]) = Sequence{'abc', 'zxc'} in\nx->closure(it | 1)\\<close>\\<close>\nlemma\n  \"\\<nexists>\\<tau>. \\<Gamma>\\<^sub>0 \\<turnstile> Let STR ''x'' (Some (Sequence String[?]))\n    (CollectionLiteral SequenceKind\n      [CollectionItem (StringLiteral ''abc''),\n       CollectionItem (StringLiteral ''zxc'')])\n    (ClosureIteratorCall (Var STR ''x'') ArrowCall [STR ''it''] None\n      (IntegerLiteral 1)) : \\<tau>\"\n  by simp\n\ntext \\<open>\n\\<^verbatim>\\<open>Sequence{1..5, null}->max()\\<close>\\<close>\nlemma\n  \"\\<nexists>\\<tau>. \\<Gamma>\\<^sub>0 \\<turnstile> OperationCall (CollectionLiteral SequenceKind\n    [CollectionRange (IntegerLiteral 1) (IntegerLiteral 5),\n     CollectionItem NullLiteral])\n    ArrowCall CollectionMaxOp [] : \\<tau>\"\nproof -\n  have \"\\<not> operation_defined (Integer[?] :: classes1 type) STR ''max'' [Integer[?]]\"\n    by eval\n  thus ?thesis by simp\nqed\n\n(*** Code *******************************************************************)\n\nsection \\<open>Code\\<close>\n\nsubsection \\<open>Positive Cases\\<close>\n\nvalues \"{(\\<D>, \\<tau>). attribute Employee STR ''name'' \\<D> \\<tau>}\"\nvalues \"{(\\<D>, end). association_end Employee None STR ''employees'' \\<D> end}\"\nvalues \"{(\\<D>, end). association_end Employee (Some STR ''project_manager'') STR ''employees'' \\<D> end}\"\nvalues \"{op. operation Project[1] STR ''membersCount'' [] op}\"\nvalues \"{op. operation Project[1] STR ''membersByName'' [String[1]] op}\"\nvalue \"has_literal STR ''E1'' STR ''A''\"\n\ntext \\<open>\n\\<^verbatim>\\<open>context Employee:\nprojects.members : Bag(Employee[1])\\<close>\\<close>\nvalues\n  \"{\\<tau>. \\<Gamma>\\<^sub>0(STR ''self'' \\<mapsto>\\<^sub>f Employee[1]) \\<turnstile>\n    AssociationEndCall (AssociationEndCall (Var STR ''self'')\n        DotCall None STR ''projects'')\n      DotCall None STR ''members'' : \\<tau>}\"\n\nsubsection \\<open>Negative Cases\\<close>\n\nvalues \"{(\\<D>, \\<tau>). attribute Employee STR ''name2'' \\<D> \\<tau>}\"\nvalue \"has_literal STR ''E1'' STR ''C''\"\n\ntext \\<open>\n\\<^verbatim>\\<open>Sequence{1..5, null}->max()\\<close>\\<close>\nvalues\n  \"{\\<tau>. \\<Gamma>\\<^sub>0 \\<turnstile> OperationCall (CollectionLiteral SequenceKind\n    [CollectionRange (IntegerLiteral 1) (IntegerLiteral 5),\n      CollectionItem NullLiteral])\n    ArrowCall CollectionMaxOp [] : \\<tau>}\"\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/Safe_OCL/OCL_Examples.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8539127529517043, "lm_q2_score": 0.8221891261650248, "lm_q1q2_score": 0.7020777801705325}}
{"text": "(*  Title:       Executable Transitive Closures of Finite Relations\n    Author:      Christian Sternagel <c.sternagel@gmail.com>\n                 Ren\u00e9 Thiemann       <rene.thiemann@uibk.ac.at>\n    Maintainer:  Christian Sternagel and Ren\u00e9 Thiemann\n    License:     LGPL\n*)\n\nsection \\<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": "diekmann", "repo": "topoS", "sha": "4303ebd95a501283c02fd513c109e645a48ad080", "save_path": "github-repos/isabelle/diekmann-topoS", "path": "github-repos/isabelle/diekmann-topoS/topoS-4303ebd95a501283c02fd513c109e645a48ad080/thy/Transitive-Closure/Transitive_Closure_Impl.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8221891174511732, "lm_q2_score": 0.8539127510928477, "lm_q1q2_score": 0.7020777712013317}}
{"text": "(*<*)theory CTLind imports CTL begin(*>*)\n\nsubsection{*CTL Revisited*}\n\ntext{*\\label{sec:CTL-revisited}\n\\index{CTL|(}%\nThe purpose of this section is twofold: to demonstrate\nsome of the induction principles and heuristics discussed above and to\nshow how inductive definitions can simplify proofs.\nIn \\S\\ref{sec:CTL} we gave a fairly involved proof of the correctness of a\nmodel checker for CTL\\@. In particular the proof of the\n@{thm[source]infinity_lemma} on the way to @{thm[source]AF_lemma2} is not as\nsimple as one might expect, due to the @{text SOME} operator\ninvolved. Below we give a simpler proof of @{thm[source]AF_lemma2}\nbased on an auxiliary inductive definition.\n\nLet us call a (finite or infinite) path \\emph{@{term A}-avoiding} if it does\nnot touch any node in the set @{term A}. Then @{thm[source]AF_lemma2} says\nthat if no infinite path from some state @{term s} is @{term A}-avoiding,\nthen @{prop\"s \\<in> lfp(af A)\"}. We prove this by inductively defining the set\n@{term\"Avoid s A\"} of states reachable from @{term s} by a finite @{term\nA}-avoiding path:\n% Second proof of opposite direction, directly by well-founded induction\n% on the initial segment of M that avoids A.\n*}\n\ninductive_set\n  Avoid :: \"state \\<Rightarrow> state set \\<Rightarrow> state set\"\n  for s :: state and A :: \"state set\"\nwhere\n    \"s \\<in> Avoid s A\"\n  | \"\\<lbrakk> t \\<in> Avoid s A; t \\<notin> A; (t,u) \\<in> M \\<rbrakk> \\<Longrightarrow> u \\<in> Avoid s A\"\n\ntext{*\nIt is easy to see that for any infinite @{term A}-avoiding path @{term f}\nwith @{prop\"f(0::nat) \\<in> Avoid s A\"} there is an infinite @{term A}-avoiding path\nstarting with @{term s} because (by definition of @{const Avoid}) there is a\nfinite @{term A}-avoiding path from @{term s} to @{term\"f(0::nat)\"}.\nThe proof is by induction on @{prop\"f(0::nat) \\<in> Avoid s A\"}. However,\nthis requires the following\nreformulation, as explained in \\S\\ref{sec:ind-var-in-prems} above;\nthe @{text rule_format} directive undoes the reformulation after the proof.\n*}\n\nlemma ex_infinite_path[rule_format]:\n  \"t \\<in> Avoid s A  \\<Longrightarrow>\n   \\<forall>f\\<in>Paths t. (\\<forall>i. f i \\<notin> A) \\<longrightarrow> (\\<exists>p\\<in>Paths s. \\<forall>i. p i \\<notin> A)\"\napply(erule Avoid.induct)\n apply(blast)\napply(clarify)\napply(drule_tac x = \"\\<lambda>i. case i of 0 \\<Rightarrow> t | Suc i \\<Rightarrow> f i\" in bspec)\napply(simp_all add: Paths_def split: nat.split)\ndone\n\ntext{*\\noindent\nThe base case (@{prop\"t = s\"}) is trivial and proved by @{text blast}.\nIn the induction step, we have an infinite @{term A}-avoiding path @{term f}\nstarting from @{term u}, a successor of @{term t}. Now we simply instantiate\nthe @{text\"\\<forall>f\\<in>Paths t\"} in the induction hypothesis by the path starting with\n@{term t} and continuing with @{term f}. That is what the above $\\lambda$-term\nexpresses.  Simplification shows that this is a path starting with @{term t} \nand that the instantiated induction hypothesis implies the conclusion.\n\nNow we come to the key lemma. Assuming that no infinite @{term A}-avoiding\npath starts from @{term s}, we want to show @{prop\"s \\<in> lfp(af A)\"}. For the\ninductive proof this must be generalized to the statement that every point @{term t}\n``between'' @{term s} and @{term A}, in other words all of @{term\"Avoid s A\"},\nis contained in @{term\"lfp(af A)\"}:\n*}\n\nlemma Avoid_in_lfp[rule_format(no_asm)]:\n  \"\\<forall>p\\<in>Paths s. \\<exists>i. p i \\<in> A \\<Longrightarrow> t \\<in> Avoid s A \\<longrightarrow> t \\<in> lfp(af A)\"\n\ntxt{*\\noindent\nThe proof is by induction on the ``distance'' between @{term t} and @{term\nA}. Remember that @{prop\"lfp(af A) = A \\<union> M\\<inverse> `` lfp(af A)\"}.\nIf @{term t} is already in @{term A}, then @{prop\"t \\<in> lfp(af A)\"} is\ntrivial. If @{term t} is not in @{term A} but all successors are in\n@{term\"lfp(af A)\"} (induction hypothesis), then @{prop\"t \\<in> lfp(af A)\"} is\nagain trivial.\n\nThe formal counterpart of this proof sketch is a well-founded induction\non~@{term M} restricted to @{term\"Avoid s A - A\"}, roughly speaking:\n@{term[display]\"{(y,x). (x,y) \\<in> M \\<and> x \\<in> Avoid s A \\<and> x \\<notin> A}\"}\nAs we shall see presently, the absence of infinite @{term A}-avoiding paths\nstarting from @{term s} implies well-foundedness of this relation. For the\nmoment we assume this and proceed with the induction:\n*}\n\napply(subgoal_tac \"wf{(y,x). (x,y) \\<in> M \\<and> x \\<in> Avoid s A \\<and> x \\<notin> A}\")\n apply(erule_tac a = t in wf_induct)\n apply(clarsimp)\n(*<*)apply(rename_tac t)(*>*)\n\ntxt{*\\noindent\n@{subgoals[display,indent=0,margin=65]}\nNow the induction hypothesis states that if @{prop\"t \\<notin> A\"}\nthen all successors of @{term t} that are in @{term\"Avoid s A\"} are in\n@{term\"lfp (af A)\"}. Unfolding @{term lfp} in the conclusion of the first\nsubgoal once, we have to prove that @{term t} is in @{term A} or all successors\nof @{term t} are in @{term\"lfp (af A)\"}.  But if @{term t} is not in @{term A},\nthe second \n@{const Avoid}-rule implies that all successors of @{term t} are in\n@{term\"Avoid s A\"}, because we also assume @{prop\"t \\<in> Avoid s A\"}.\nHence, by the induction hypothesis, all successors of @{term t} are indeed in\n@{term\"lfp(af A)\"}. Mechanically:\n*}\n\n apply(subst lfp_unfold[OF mono_af])\n apply(simp (no_asm) add: af_def)\n apply(blast intro: Avoid.intros)\n\ntxt{*\nHaving proved the main goal, we return to the proof obligation that the \nrelation used above is indeed well-founded. This is proved by contradiction: if\nthe relation is not well-founded then there exists an infinite @{term\nA}-avoiding path all in @{term\"Avoid s A\"}, by theorem\n@{thm[source]wf_iff_no_infinite_down_chain}:\n@{thm[display]wf_iff_no_infinite_down_chain[no_vars]}\nFrom lemma @{thm[source]ex_infinite_path} the existence of an infinite\n@{term A}-avoiding path starting in @{term s} follows, contradiction.\n*}\n\napply(erule contrapos_pp)\napply(simp add: wf_iff_no_infinite_down_chain)\napply(erule exE)\napply(rule ex_infinite_path)\napply(auto simp add: Paths_def)\ndone\n\ntext{*\nThe @{text\"(no_asm)\"} modifier of the @{text\"rule_format\"} directive in the\nstatement of the lemma means\nthat the assumption is left unchanged; otherwise the @{text\"\\<forall>p\"} \nwould be turned\ninto a @{text\"\\<And>p\"}, which would complicate matters below. As it is,\n@{thm[source]Avoid_in_lfp} is now\n@{thm[display]Avoid_in_lfp[no_vars]}\nThe main theorem is simply the corollary where @{prop\"t = s\"},\nwhen the assumption @{prop\"t \\<in> Avoid s A\"} is trivially true\nby the first @{const Avoid}-rule. Isabelle confirms this:%\n\\index{CTL|)}*}\n\ntheorem AF_lemma2:  \"{s. \\<forall>p \\<in> Paths s. \\<exists> i. p i \\<in> A} \\<subseteq> lfp(af A)\"\nby(auto elim: Avoid_in_lfp intro: Avoid.intros)\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/CTL/CTLind.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8080672227971211, "lm_q2_score": 0.8688267881258483, "lm_q1q2_score": 0.702070449772597}}
{"text": "section \\<open>Winning Regions\\<close>\n\ntheory WinningRegion\nimports\n  Main\n  WinningStrategy\nbegin\n\ntext \\<open>\n  Here we define winning regions of parity games.  The winning region for player \\<open>p\\<close> is the\n  set of nodes from which \\<open>p\\<close> has a positional winning strategy.\n\\<close>\n\ncontext ParityGame begin\n\ndefinition \"winning_region p \\<equiv> { v \\<in> V. \\<exists>\\<sigma>. strategy p \\<sigma> \\<and> winning_strategy p \\<sigma> v }\"\n\nlemma winning_regionI [intro]:\n  assumes \"v \\<in> V\" \"strategy p \\<sigma>\" \"winning_strategy p \\<sigma> v\"\n  shows \"v \\<in> winning_region p\"\n  using assms unfolding winning_region_def by blast\n\nlemma winning_region_in_V [simp]: \"winning_region p \\<subseteq> V\" unfolding winning_region_def by blast\n\nlemma winning_region_deadends:\n  assumes \"v \\<in> VV p\" \"deadend v\"\n  shows \"v \\<in> winning_region p**\"\nproof\n  show \"v \\<in> V\" using \\<open>v \\<in> VV p\\<close> by blast\n  show \"winning_strategy p** \\<sigma>_arbitrary v\" using assms winning_strategy_on_deadends by simp\nqed simp\n\nsubsection \\<open>Paths in Winning Regions\\<close>\n\nlemma (in vmc_path) paths_stay_in_winning_region:\n  assumes \\<sigma>': \"strategy p \\<sigma>'\" \"winning_strategy p \\<sigma>' v0\"\n    and \\<sigma>: \"\\<And>v. v \\<in> winning_region p \\<Longrightarrow> \\<sigma>' v = \\<sigma> v\"\n  shows \"lset P \\<subseteq> winning_region p\"\nproof\n  fix x assume \"x \\<in> lset P\"\n  thus \"x \\<in> winning_region p\" using assms vmc_path_axioms\n  proof (induct arbitrary: v0 rule: llist_set_induct)\n    case (find P v0)\n    interpret vmc_path G P v0 p \\<sigma> using find.prems(4) .\n    show ?case using P_v0 \\<sigma>'(1) find.prems(2) v0_V unfolding winning_region_def by blast\n  next\n    case (step P x v0)\n    interpret vmc_path G P v0 p \\<sigma> using step.prems(4) .\n    show ?case proof (cases)\n      assume \"lnull (ltl P)\"\n      thus ?thesis using P_lnull_ltl_LCons step.hyps(2) by auto\n    next\n      assume \"\\<not>lnull (ltl P)\"\n      then interpret vmc_path_no_deadend G P v0 p \\<sigma> using P_no_deadend_v0 by unfold_locales\n      have \"winning_strategy p \\<sigma>' w0\" proof (cases)\n        assume \"v0 \\<in> VV p\"\n        hence \"winning_strategy p \\<sigma>' (\\<sigma>' v0)\"\n          using strategy_extends_VVp local.step(4) step.prems(2) v0_no_deadend by blast\n        moreover have \"\\<sigma> v0 = w0\" using v0_conforms \\<open>v0 \\<in> VV p\\<close> by blast\n        moreover have \"\\<sigma>' v0 = \\<sigma> v0\"\n          using \\<sigma> assms(1) step.prems(2) v0_V unfolding winning_region_def by blast\n        ultimately show ?thesis by simp\n      next\n        assume \"v0 \\<notin> VV p\"\n        thus ?thesis using v0_V strategy_extends_VVpstar step(4) step.prems(2) by simp\n      qed\n      thus ?thesis using step.hyps(3) step(4) \\<sigma> vmc_path_ltl by blast\n    qed\n  qed\nqed\n\nlemma (in vmc_path) path_hits_winning_region_is_winning:\n  assumes \\<sigma>': \"strategy p \\<sigma>'\" \"\\<And>v. v \\<in> winning_region p \\<Longrightarrow> winning_strategy p \\<sigma>' v\"\n    and \\<sigma>: \"\\<And>v. v \\<in> winning_region p \\<Longrightarrow> \\<sigma>' v = \\<sigma> v\"\n    and P: \"lset P \\<inter> winning_region p \\<noteq> {}\"\n  shows \"winning_path p P\"\nproof-\n  obtain n where n: \"enat n < llength P\" \"P $ n \\<in> winning_region p\"\n    using P by (meson lset_intersect_lnth)\n  define P' where \"P' = ldropn n P\"\n  then interpret P': vmc_path G P' \"P $ n\" p \\<sigma>\n    unfolding P'_def using vmc_path_ldropn n(1) by blast\n  have \"winning_strategy p \\<sigma>' (P $ n)\" using \\<sigma>'(2) n(2) by blast\n  hence \"lset P' \\<subseteq> winning_region p\"\n    using P'.paths_stay_in_winning_region[OF \\<sigma>'(1) _ \\<sigma>]\n    by blast\n  hence \"\\<And>v. v \\<in> lset P' \\<Longrightarrow> \\<sigma> v = \\<sigma>' v\" using \\<sigma> by auto\n  hence \"path_conforms_with_strategy p P' \\<sigma>'\"\n    using path_conforms_with_strategy_irrelevant_updates P'.P_conforms\n    by blast\n  then interpret P': vmc_path G P' \"P $ n\" p \\<sigma>' using P'.conforms_to_another_strategy by blast\n  have \"winning_path p P'\" using \\<sigma>'(2) n(2) P'.vmc_path_axioms winning_strategy_def by blast\n  thus \"winning_path p P\" unfolding P'_def using winning_path_drop_add n(1) P_valid by blast\nqed\n\nsubsection \\<open>Irrelevant Updates\\<close>\n\ntext \\<open>Updating a winning strategy outside of the winning region is irrelevant.\\<close>\n\nlemma winning_strategy_updates:\n  assumes \\<sigma>: \"strategy p \\<sigma>\" \"winning_strategy p \\<sigma> v0\"\n    and v: \"v \\<notin> winning_region p\" \"v\\<rightarrow>w\"\n  shows \"winning_strategy p (\\<sigma>(v := w)) v0\"\nproof\n  fix P assume \"vmc_path G P v0 p (\\<sigma>(v := w))\"\n  then interpret vmc_path G P v0 p \"\\<sigma>(v := w)\" .\n  have \"\\<And>v'. v' \\<in> winning_region p \\<Longrightarrow> \\<sigma> v' = (\\<sigma>(v := w)) v'\" using v by auto\n  hence \"v \\<notin> lset P\" using v paths_stay_in_winning_region \\<sigma> unfolding winning_region_def by blast\n  hence \"path_conforms_with_strategy p P \\<sigma>\"\n    using P_conforms path_conforms_with_strategy_irrelevant' by blast\n  thus \"winning_path p P\" using conforms_to_another_strategy \\<sigma>(2) winning_strategy_def by blast\nqed\n\nsubsection \\<open>Extending Winning Regions\\<close>\n\nlemma winning_region_extends_VVp:\n  assumes v: \"v \\<in> VV p\" \"v\\<rightarrow>w\" and w: \"w \\<in> winning_region p\"\n  shows \"v \\<in> winning_region p\"\nproof (rule ccontr)\n  obtain \\<sigma> where \\<sigma>: \"strategy p \\<sigma>\" \"winning_strategy p \\<sigma> w\"\n    using w unfolding winning_region_def by blast\n  let ?\\<sigma> = \"\\<sigma>(v := w)\"\n  assume contra: \"v \\<notin> winning_region p\"\n  moreover have \"strategy p ?\\<sigma>\" using valid_strategy_updates \\<sigma>(1) \\<open>v\\<rightarrow>w\\<close> by blast\n  moreover hence \"winning_strategy p ?\\<sigma> v\"\n    using winning_strategy_updates \\<sigma> contra v strategy_extends_backwards_VVp\n    by auto\n  ultimately show False using \\<open>v\\<rightarrow>w\\<close> unfolding winning_region_def by auto\nqed\n\ntext \\<open>\n  Unfortunately, we cannot prove the corresponding theorem \\<open>winning_region_extends_VVpstar\\<close>\n  for @{term \"VV p**\"}-nodes yet.\n  First, we need to show that there exists a uniform winning strategy on @{term \"winning_region p\"}.\n  We will prove \\<open>winning_region_extends_VVpstar\\<close> as soon as we have this.\n\\<close>\n\nend \\<comment> \\<open>context ParityGame\\<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/Parity_Game/WinningRegion.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8688267762381844, "lm_q2_score": 0.8080672204860316, "lm_q1q2_score": 0.702070438158629}}
{"text": "theory Cantor_Set\nimports Main Real Series \"~~/src/HOL/Library/Product_Vector\"\nbegin\n\nsubsection {* Definition of the Cantor Set *}\n\ndefinition go_left :: \"real \\<Rightarrow> real\" where \"go_left x = x/3\"\ndefinition go_right :: \"real \\<Rightarrow> real\" where \"go_right x = 2/3 + x/3\"\n\nfun cantor_n where\n  \"cantor_n 0 = {0::real..1}\"\n| \"cantor_n (Suc n) = go_left ` cantor_n n \\<union> go_right ` cantor_n n\"\ndefinition \"cantor \\<equiv> \\<Inter>range cantor_n\"\n\nlemma cantor_bounds:\n  assumes \"x \\<in> cantor\"\n  shows \"0 \\<le> x \\<and> x \\<le> 1\"\nproof-\n  from assms have \"x \\<in> cantor_n 0\" by (auto simp add: cantor_def simp del: cantor_n.simps)\n  thus ?thesis by simp\nqed\n\nsubsection {* Representing reals from [0,1] to base n *}\n\nlocale ary =\n  fixes n :: nat\n  assumes ng1: \"n > 1\"\nbegin \n\ntext {*\nThe mod n is a trick to do something slightly more useful when the input has digits outside\nthe range.\n*}\ndefinition n_ary_series :: \"(nat \\<Rightarrow> nat) \\<Rightarrow> nat \\<Rightarrow> real\" where\n  \"n_ary_series f = (\\<lambda>k. real (f k mod n) * (1 / n) ^ Suc k)\"\ndeclare power_Suc[simp del]\n\ndefinition to_real :: \"(nat \\<Rightarrow> nat) \\<Rightarrow> real\"\n  where \"to_real = (\\<lambda> f. suminf (n_ary_series f))\"\n\n\nlemma summable_geometric': \"norm (c::real) < 1 \\<Longrightarrow> summable (\\<lambda>k. c ^ (Suc k))\"\n  apply (rule summable_ignore_initial_segment[of _ 1, simplified Suc_eq_plus1[symmetric]])\n  apply (rule summable_geometric)\n  by simp\n\nlemma suminf_geometric': \"norm (c::real) < 1 \\<Longrightarrow> (\\<Sum>n. c ^ Suc n) = c / (1 - c)\"\n  apply (subst suminf_minus_initial_segment[of _ 1, simplified Suc_eq_plus1[symmetric]])\n  apply (erule summable_geometric)\n  apply (subst suminf_geometric, simp, simp)\n  apply (subst mult_right_cancel[of \"1 - c\", symmetric])\n  by (auto simp:left_diff_distrib)\n\nlemma n_ary_series_div[simp]: \"n_ary_series f i / n = n_ary_series (\\<lambda> i. f (i - 1)) (Suc i)\"\n  unfolding n_ary_series_def\n  by (simp add: power_Suc)\n\ntext {* The n-ary representation of 1. *}\ndefinition \"period_one \\<equiv> n_ary_series (\\<lambda>_. n - 1)\"\n\nlemma period_one_summable[simp]: \"summable period_one\"\n  using ng1 by (auto simp:n_ary_series_def period_one_def intro!:summable_geometric' summable_mult)\n\nlemma suminf_period_one_1[simp]: \"suminf period_one = 1\"\n  using ng1\n  unfolding period_one_def n_ary_series_def\n  apply (subst suminf_mult)\n  apply (rule summable_geometric')\n  apply simp\n  apply (subst suminf_geometric')\n  by (auto simp:right_diff_distrib)\n\nlemma period_one_skip_initial_segment[simp]:\n  \"(\\<Sum>k. period_one (k + i)) = (1/n) ^ i * suminf period_one\"\n  by (subst suminf_mult[symmetric], simp, rule arg_cong[where f=suminf], auto simp:period_one_def n_ary_series_def power_Suc power_add)\n\nlemma n_ary_summable[simp]:\n  shows \"summable (n_ary_series f)\"\nproof (rule summableI_nonneg_bounded[where x=\"suminf period_one\"])\n  fix k\n  show \"0 \\<le> n_ary_series f k\" using assms by (auto simp: n_ary_series_def intro!:mult_nonneg_nonneg)\n  have \"setsum (n_ary_series f) {..<k} \\<le> setsum (period_one) {..<k}\"\n    using assms ng1\n    by (auto simp:n_ary_series_def period_one_def intro!:setsum_mono)\n       (metis Suc_pred mod_less_divisor neq0_conv not_less not_less_eq old.nat.distinct(2))\n  also have \"... \\<le> suminf period_one\" using assms\n    by -(intro setsum_le_suminf period_one_summable,\n         auto intro: simp:period_one_def n_ary_series_def)\n  finally show \"setsum (n_ary_series f) {..<k} \\<le> suminf period_one\" .\nqed\n\nlemma nary_pos[simp]: \"to_real f \\<ge> 0\"\n  unfolding to_real_def\n  by (rule suminf_nonneg, simp) (auto simp:n_ary_series_def)\n\nlemma nary_le_1[simp]:\n  shows \"to_real f \\<le> 1\"\nproof-\n  have \"suminf (n_ary_series f) \\<le> suminf period_one\"\n  proof (rule suminf_le, rule)\n    fix i\n    from ng1 have \"f i mod n < n\" by simp\n    thus \"n_ary_series f i \\<le> period_one i\" \n      unfolding n_ary_series_def period_one_def  by auto\n  next\n    show \"summable (n_ary_series f)\" by (rule n_ary_summable)\n  next\n    show \"summable period_one\" by (rule period_one_summable)\n  qed\n  also have \"\\<dots> = 1\" by (rule suminf_period_one_1)\n  finally show ?thesis unfolding to_real_def .\nqed\n\nsubsection {* The n-arity expansion of a real *}\n\nfun to_nary :: \"real \\<Rightarrow> (nat \\<Rightarrow> nat)\"\n where \"to_nary x i = (if x = 1 then n - 1 else natfloor (x * n^(Suc i)) mod n)\"\n\n(* Generalized Real.natfloor_div_nat, included in the main library since Oct 2014. *)\nlemma natfloor_div_nat:\n  assumes \"y > 0\"\n  shows \"natfloor (x / real y) = natfloor x div y\"\nproof-\n  have \"x \\<le> 0 \\<or> x \\<ge> 0 \\<and> x < 1 \\<or> 1 \\<le> x\" by arith\n  thus ?thesis\n  proof(elim conjE disjE)\n    assume *: \"1 \\<le> x\"\n    show ?thesis by (rule Real.natfloor_div_nat[OF * assms])\n  next\n    assume *: \"x \\<le> 0\"\n    moreover\n    from * assms have \"x / y \\<le> 0\" by (simp add: field_simps)\n    ultimately\n    show ?thesis by (simp add: natfloor_neg)\n  next\n    assume *: \"x \\<ge> 0\" \"x < 1\"\n    hence \"natfloor x = 0\" by (auto intro: natfloor_eq)\n    moreover\n    from * assms have \"x / y \\<ge> 0\" and \"x / y < 1\" by (auto simp add: field_simps)\n    hence \"natfloor (x/y) = 0\" by (auto intro: natfloor_eq)\n    ultimately\n    show ?thesis by simp\n  qed\nqed\n\nlemma natfloor_mod:\n  fixes x :: real\n  shows \"n * natfloor x + natfloor (n * x) mod n = natfloor (n * x)\"\nproof-\n  have \"natfloor (n * x) = n * (natfloor (n * x) div n) + natfloor (n * x) mod n\"\n    by (metis mod_div_equality2)\n  also have \"natfloor (n * x) div n = natfloor (n * x / n)\"\n    apply (rule natfloor_div_nat[symmetric])\n    using ng1 by auto\n  also have \"n * x / n = x\" using ng1 by simp\n  finally show ?thesis..\nqed\n\nlemma partial_n_ary:\n  fixes x :: real\n  assumes \"0 \\<le> x\" \"x < 1\"\n  shows \"setsum (n_ary_series (to_nary x)) {..<i} = natfloor (x * n^i) / n^i\"\nproof (induction i)\n  case 0\n  from assms have \"natfloor x = 0\" by (auto intro: natfloor_eq)\n  thus ?case by simp\nnext\n  case (Suc i)\n    have \"setsum (n_ary_series (to_nary x)) {..<Suc i}\n      =  setsum (n_ary_series (to_nary x)) {..<i} + n_ary_series (to_nary x) i\"\n     by simp\n   also have \"\\<dots> = natfloor (x * real (n ^ i)) / real (n ^ i) + n_ary_series (to_nary x) i\"\n     unfolding Suc.IH..\n   also have \"\\<dots> = natfloor (x * n ^ i) /  n ^ i + (natfloor (x * n ^ Suc i) mod n) / n ^ Suc i\"\n     using assms(2) by (simp add: n_ary_series_def field_simps)\n   also have \"\\<dots> = (n * natfloor (x * n ^ i) + natfloor (n * (x * n ^ i)) mod n) / n ^ Suc i\"\n     using ng1 by (simp add: field_simps power_Suc)\n   also have \"\\<dots> = natfloor (n * (x * n^i)) / n^Suc i\"\n     unfolding natfloor_mod..\n   also have \"\\<dots> = natfloor (x * n^(Suc i)) / n^Suc i\" by (simp add: power_Suc field_simps)\n   finally\n   show ?case.\nqed\n\nlemma bounded_0_inverse:\n  fixes f :: \"nat \\<Rightarrow> real\"\n  assumes \"x < 1\"\n  assumes \"c > 0\"\n  assumes \"\\<And> i. 0 \\<le> f i\"\n  assumes \"\\<And> i. f i \\<le> c * x^i\"\n  shows \"f ----> 0\"\nproof(rule tendsto_sandwich[OF eventually_sequentiallyI eventually_sequentiallyI])\n  fix n show \"0 \\<le> f n\" by fact\nnext\n  fix n show \"f n \\<le> c*x^n\" by fact\nnext\n  show \"(\\<lambda>x. 0) ----> 0\"  by (rule tendsto_const)\nnext\n  have \"0 \\<le> x\" by (metis assms(2-4) le_less_trans mult.commute mult_zero_left not_less power_one_right real_mult_le_cancel_iff1)\n  hence \"op ^ x ----> 0\" \n    by (rule LIMSEQ_realpow_zero[OF _ assms(1)])\n  thus \"(\\<lambda> i. c * x^i) ----> 0\"\n    by (rule tendsto_mult_right_zero)\nqed\n\nlemma to_real_to_nary:\n  fixes x :: real\n  assumes \"0 \\<le> x\" \"x \\<le>1\"\n  shows \"to_real (to_nary x) = x\"\nproof(cases \"x = 1\")\n  case False with assms(2) have \"x < 1\" by simp\n\n  have \"to_real (to_nary x) = lim (\\<lambda>i. setsum (n_ary_series (to_nary x)) {..<i})\"\n    unfolding to_real_def by (rule suminf_eq_lim)\n  also have \"\\<dots> = lim (\\<lambda>i. natfloor (x * n^i) / n^i)\"\n    unfolding partial_n_ary[OF assms(1) `x < 1` ] by simp\n  also have \"\\<dots> = x\"\n  proof(rule limI)\n    have \"(\\<lambda>i. x - (natfloor (x * (n ^ i))) / (n ^ i)) ----> 0\"\n    proof(rule bounded_0_inverse)\n      fix i\n      have \"natfloor (x * (n^i)) \\<le> x * (n^i)\" \n          using assms by (simp add: real_natfloor_le field_simps)\n      thus \"0 \\<le> x - natfloor (x * (n^i)) / (n^i)\" \n          using ng1 by (simp add: field_simps)\n    next\n      fix i \n      have \"x * (n^i) - natfloor (x * (n^i)) \\<le> 1\"\n         by (metis comm_monoid_diff_class.diff_cancel le_natfloor_eq_one less_eq_real_def natfloor_neg natfloor_one natfloor_subtract not_le power_0 power_eq_0_iff)\n      from divide_right_mono[OF this, where c = \"n^i\"] assms(1)\n      show \"x - natfloor (x * (n ^ i)) / (n ^ i) \\<le> 1 * (1/n)^i\"\n        using ng1 by (simp add: field_simps )\n    next\n      show \"1/n < 1\" using ng1 by auto\n    next\n      show \"0 < (1::real)\" by auto\n    qed\n    thus \"(\\<lambda>i. (natfloor (x * (n ^ i))) / (n ^ i)) ----> x\"\n      by (rule LIMSEQ_diff_approach_zero2[OF tendsto_const])\n  qed\n  finally show ?thesis.\nnext\n  case True\n  hence \"to_nary x = (\\<lambda>i. n - 1)\" by auto\n  thus ?thesis\n    unfolding to_real_def using True suminf_period_one_1[unfolded period_one_def] by simp\nqed\n\nlemma range_to_real:\n  shows \"range to_real = {0..1}\"\nproof(intro set_eqI iffI)\n  fix x :: real\n  assume \"x \\<in> {0..1}\" hence \"0 \\<le> x\" and \"x \\<le> 1\" by auto\n\n  have \"x = to_real (to_nary x)\"\n    by (rule to_real_to_nary[OF assms `0 \\<le> x` `x \\<le> 1`, symmetric])\n  then\n  show \"x \\<in> range to_real\" by auto\nqed auto\n\nend\n\ntext {* We only really need this with @{term \"n = 3\"} there: *}\ninterpretation ary 3 by default auto\n\nsubsection {* A cantor-like set on the representations *}\n\ndefinition r_go_left :: \"(nat \\<Rightarrow> nat) \\<Rightarrow> (nat \\<Rightarrow> nat)\"\n  where \"r_go_left f = (\\<lambda> i. if i = 0 then 0 else f (i - 1))\" \ndefinition r_go_right :: \"(nat \\<Rightarrow> nat) \\<Rightarrow> (nat \\<Rightarrow> nat)\"\n  where \"r_go_right f= (\\<lambda> i. if i = 0 then 2 else f (i - 1))\" \n\nfun r_cantor_n where\n  \"r_cantor_n 0 = UNIV\"\n| \"r_cantor_n (Suc n) = r_go_left ` r_cantor_n n \\<union> r_go_right ` r_cantor_n n\"\ndefinition \"r_cantor \\<equiv> \\<Inter>range r_cantor_n\"\n\nsubsection {* A bijection between the Cantor Set and a subset of ternary representations *}\n\nsubsubsection {* Recognizing the cantor sets via their digits *}\n\nlemma r_cantor_n_cantor_ary: \"f \\<in> r_cantor_n n \\<longleftrightarrow> (\\<forall>i<n. f i \\<in> {0,2})\"\nproof(intro iffI conjI)\n  fix n\n  assume \"f \\<in> r_cantor_n n\"\n  thus \"\\<forall>i<n. f i \\<in> {0,2}\"\n  proof(induction n arbitrary: f)\n    case (Suc n)\n    hence \"f \\<in> r_go_left ` r_cantor_n n \\<or> f \\<in> r_go_right ` r_cantor_n n\" by simp\n    then obtain f' where \"f' \\<in> r_cantor_n n\" and \"f = r_go_left f' \\<or> f = r_go_right f'\" by auto\n    from Suc.IH[OF this(1)]\n    have \"\\<forall>i<n. f' i \\<in> {0, 2}\".\n    hence \"\\<forall>i<n. f (Suc i) \\<in> {0, 2}\"\n      using `f = _ \\<or> f = _`\n      by (auto simp add:  r_go_left_def   r_go_right_def)\n    moreover\n    have \"f 0 \\<in> {0, 2}\"\n      using `f = _ \\<or> f = _`\n      by (auto simp add:  r_go_left_def   r_go_right_def)\n    ultimately\n    show ?case by (metis less_Suc_eq_0_disj)\n  qed simp\nnext\n  fix n\n  assume \"\\<forall>i<n. f i \\<in> {0, 2}\"\n  thus \"f \\<in> r_cantor_n n\"\n  proof(induction n arbitrary: f)\n    case 0 thus ?case by simp\n  next\n    case (Suc n)\n    hence \"f 0 = 0 \\<or> f 0 = 2\" by simp\n    hence \"f = r_go_left (\\<lambda> i. f (Suc i)) \\<or> f =  r_go_right (\\<lambda> i. f (Suc i))\"\n      by (auto simp add:  r_go_left_def   r_go_right_def)\n    moreover\n    from Suc.prems\n    have \"(\\<lambda> i. f (Suc i)) \\<in> r_cantor_n n\"\n      by (auto intro!: Suc.IH)\n    ultimately\n    show \"f \\<in> r_cantor_n (Suc n)\" by auto\n  qed\nqed\n\nlemma r_cantor_zero_or_two: \"f \\<in> r_cantor \\<longleftrightarrow> (\\<forall> i. f i \\<in> {0,2})\"\nproof-\n  have \"f \\<in> r_cantor \\<longleftrightarrow> (\\<forall>n. f \\<in> r_cantor_n n)\" by (auto simp add: r_cantor_def)\n  also have \"\\<dots> \\<longleftrightarrow> (\\<forall>n. (\\<forall>i<n. f i \\<in> {0,2}))\" unfolding r_cantor_n_cantor_ary..\n  also have \"\\<dots> \\<longleftrightarrow> (\\<forall>n. f n \\<in> {0,2})\" by auto\n  finally show ?thesis.\nqed\n\nsubsubsection {* @{term to_real} is continuous (in a sense) *}\n\nlemma n_ary_series_diff:\n  shows \"\\<bar>n_ary_series a k - n_ary_series b k\\<bar> \\<le> (1/3)^k\"\nproof-\n  have \"\\<bar>n_ary_series a k - n_ary_series b k\\<bar> = \\<bar>real (a k mod 3) - real(b k mod 3)\\<bar> * (1 / 3) ^ Suc k\"\n    unfolding n_ary_series_def by (auto simp add: field_simps)\n  also\n   have \"\\<bar>real (a k mod 3)\\<bar> < 3\" and  \"\\<bar>real (b k mod 3)\\<bar> < 3\" by auto\n  hence \"\\<bar>real (a k mod 3) - real(b k mod 3)\\<bar> \\<le> 3\" by auto\n  also have \"(3::real) * (1 / 3) ^ Suc k = (1/3)^k\" by (simp add: power_Suc field_simps)\n  finally show ?thesis by this auto\nqed\n\nlemma to_real_cont:\n  assumes \"\\<forall>j<n. a j = b j\"\n  shows \"\\<bar>to_real a - to_real b\\<bar> \\<le> 3 * (1 / 3) ^ n\"\nproof-\n  note sm' = summable_diff[OF n_ary_summable n_ary_summable]\n  have sm''': \"summable (\\<lambda>i. ((1 / 3)::real) ^ i)\" by (rule summable_geometric) simp\n  hence sm''': \"summable (\\<lambda>i.  (1/3 :: real) ^ (i + n))\" by (metis summable_iff_shift[where k = n])\n  hence sm'': \"summable (\\<lambda>i. \\<bar>n_ary_series a (i + n) - n_ary_series b (i + n)\\<bar>)\"\n    apply (rule summable_rabs_comparison_test[rotated])\n    using n_ary_series_diff\n    apply auto\n    done\n\n  have \"\\<bar>to_real a - to_real b\\<bar> = \\<bar>(\\<Sum>i. n_ary_series a i - n_ary_series b i)\\<bar>\"\n    unfolding to_real_def by (rule arg_cong[OF suminf_diff[OF n_ary_summable n_ary_summable]])\n  also have \"\\<dots> = \\<bar>(\\<Sum>i. n_ary_series a (i + n) - n_ary_series b (i + n)) + setsum (\\<lambda> i. n_ary_series a i - n_ary_series b i) {..<n}\\<bar>\"\n    by (rule arg_cong[OF suminf_split_initial_segment[OF sm']])\n  also have \"\\<dots> = \\<bar>(\\<Sum>i. n_ary_series a (i + n) - n_ary_series b (i + n))\\<bar>\"\n    using assms(1) by (auto simp add: n_ary_series_def)\n  also have \"\\<dots> \\<le> (\\<Sum>i. \\<bar>n_ary_series a (i + n) - n_ary_series b (i + n)\\<bar>)\"\n    by (rule summable_rabs[OF sm''])\n  also have \"\\<dots> \\<le> (\\<Sum>i. (1/3::real)^(i + n))\"\n    by (intro suminf_le[OF _ sm'' sm'''] allI n_ary_series_diff)\n  also have \"\\<dots> = (\\<Sum>i. (1/3::real)^i * (1/3::real)^n)\"\n    by (simp add: field_simps add: power_add)\n  also have \"\\<dots> = (\\<Sum>i. (1/3::real)^i) * (1/3::real)^n\"\n    by (rule suminf_mult2[symmetric, OF summable_geometric]) simp\n  also have \"\\<dots> = 1 / (1 - 1 / 3) * (1 / 3) ^ n\"\n    by (simp add: suminf_geometric) \n  also have \"\\<dots> \\<le> 3 *  (1 / 3) ^ n\" by (simp add: field_simps)\n  finally show ?thesis.\nqed\n\n\nsubsubsection {* Injectivity *}\n\nlemma to_real_inj_aux:\n  assumes cantor_at_i: \"a i \\<in> {0,2}\"  \"b i \\<in> {0,2}\" \n  assumes ord: \"a i < b i\" \"\\<forall>j<i. a j = b j\"\n  assumes eq: \"to_real a = to_real b\"\n  shows False\nproof-\n  have[simp]: \"a i = 0\" \"b i = 2\" using ord(1) cantor_at_i by auto\n  have[simp]: \"n_ary_series b i = 2 * (1/3) ^ Suc i\" by (auto simp:n_ary_series_def)\n\n  note sm = summable_ignore_initial_segment[OF n_ary_summable]\n            summable_ignore_initial_segment[OF period_one_summable]\n\n  have \"suminf (n_ary_series a) = (\\<Sum>n. n_ary_series a (n + i)) + setsum (n_ary_series a) {..<i}\"\n    by (rule suminf_split_initial_segment[OF n_ary_summable])\n  also have \"(\\<Sum>n. n_ary_series a (n + i)) = (\\<Sum>n. n_ary_series a (n + Suc i))\"\n    by (subst suminf_split_initial_segment[OF sm(1), where k=1]) (simp add:n_ary_series_def)\n  also have \"... \\<le> (\\<Sum>n. period_one (n + Suc i))\"\n    by (rule suminf_le[OF _ sm]) (auto simp add: n_ary_series_def period_one_def)\n  also have \"... = (1/3) ^ Suc i\" by (simp del: add_Suc_right)\n  also have \"... < 2 * (1/3) ^ Suc i\" by simp\n  also have \"... \\<le> (\\<Sum>n. n_ary_series b (n + i))\"\n  proof-\n    have \"0 \\<le> (\\<Sum>n. n_ary_series b (n + Suc i))\"\n    by (rule suminf_nonneg[OF sm(1)]) (simp add:n_ary_series_def)\n    thus ?thesis by (subst suminf_split_initial_segment[OF sm(1), where k=1]) auto\n  qed\n  also have \"... + setsum (n_ary_series  a) {..<i} = suminf (n_ary_series b)\"\n  proof-\n    have 1: \"setsum (n_ary_series a) {..<i} = setsum (n_ary_series b) {..<i}\" using ord(2) by (auto simp:n_ary_series_def)\n    show ?thesis by (subst 1) (rule suminf_split_initial_segment[OF n_ary_summable, symmetric])\n  qed\n  finally show False using eq unfolding to_real_def by auto\nqed\n\nlemma to_real_inj_next:\n  assumes cantor_at_i: \"a i \\<in> {0,2}\"  \"b i \\<in> {0,2}\" \n  assumes \"\\<forall>j<i. a j = b j\"\n  assumes eq: \"to_real a = to_real b\"\n  shows \"a i = b i\"\nproof(rule ccontr)\n  assume ne: \"a i \\<noteq> b i\"\n  hence \"a i < b i \\<or> b i < a i\" by auto\n  thus False\n  proof\n    assume *: \"a i < b i\"\n    show False by (rule to_real_inj_aux[OF assms(1,2) * assms(3,4)])\n  next\n    assume *: \"b i < a i\"\n    note assms(2,1) *\n    moreover\n    from assms(3) have \"\\<forall>j<i. b j = a j\" by auto\n    moreover\n    note eq[symmetric]\n    ultimately\n    show False by (rule to_real_inj_aux)\n  qed\nqed\n\nlemma to_real_inj: \"inj_on to_real r_cantor\"\nproof (rule inj_onI, rule)\n  fix a b i\n  assume asms: \"a \\<in> r_cantor\" \"b \\<in> r_cantor\" \"to_real a = to_real b\"\n\n  show \"a i = b i\"\n  proof(induction i rule: measure_induct)\n    fix i\n    \n    from asms(1,2)\n    have \"a i \\<in> {0,2}\" and \"b i \\<in> {0,2}\" unfolding r_cantor_zero_or_two by auto\n    moreover\n    assume \"\\<forall>j<i. a j = b j\"  \n    moreover\n    note `to_real _ = to_real _`\n    ultimately\n    show \"a i = b i\" by (rule to_real_inj_next)\n  qed\nqed\n\nsubsubsection {* Surjectivity *}\n\nlemma suminf_split_first:\n  assumes \"summable (f :: nat \\<Rightarrow> real)\"\n  shows \"suminf f = (\\<Sum>n. f (Suc n)) + f 0\"\n  using suminf_split_initial_segment[OF assms, of 1]\n  by simp\n\nlemma summable_changed:\n  assumes \"summable (f :: nat \\<Rightarrow> real)\"\n  shows \"summable (\\<lambda>i. if i = 0 then x else f i)\"\nusing assms summable_iff_shift[where k = 1 and f = f] summable_iff_shift[where k = 1 and f = \" (\\<lambda>i. if i = 0 then x else f i)\"] \nby simp\n  \nlemma suminf_shift:\n  assumes \"summable (f :: nat \\<Rightarrow> real)\"\n  shows \"x + (\\<Sum>i. f (Suc i)) = (\\<Sum>i. if i = 0 then x else f i)\"\n  by (simp add: suminf_split_first[OF summable_changed[OF assms]])\n\n\nlemma to_real_go_right[simp]:\n  shows \"go_right (to_real f) = to_real (r_go_right f)\"\nproof-\n  have \"go_right (to_real f) = 2/3 + to_real f / 3\" by (simp add: go_right_def)\n  also have \"\\<dots> = 2/3 + (\\<Sum>i. n_ary_series f i) / 3\" by (simp add: to_real_def)\n  also have \"\\<dots> = 2/3 + (\\<Sum>i. n_ary_series f i / 3)\" unfolding suminf_divide[OF n_ary_summable, symmetric]..\n  also have \"\\<dots> = 2/3 + (\\<Sum>i. n_ary_series (\\<lambda> i. f (i - 1)) (Suc i))\"\n    by (metis n_ary_series_div real_of_nat_numeral)\n  also have \"\\<dots> = (\\<Sum>i. if i = 0 then 2/3 else n_ary_series (\\<lambda> i. f (i - 1)) i)\"\n    by (rule suminf_shift[OF n_ary_summable])\n  also have \"\\<dots> = (\\<Sum>i. n_ary_series (\\<lambda> i. if i = 0 then 2 else f (i - 1)) i)\"\n    by (rule arg_cong[where f = suminf]) (auto simp add: n_ary_series_def power_Suc)\n  also have \"\\<dots> = (\\<Sum>i. n_ary_series (r_go_right f) i)\"\n    by (simp add: r_go_right_def)\n  also have \"\\<dots> = to_real (r_go_right f)\"\n    by (simp add: to_real_def)\n  finally show ?thesis.\nqed\n\n\nlemma to_real_go_left[simp]:\n  shows \"go_left (to_real f) = to_real (r_go_left f)\"\nproof-\n  have \"go_left (to_real f) = to_real f / 3\" by (simp add: go_left_def)\n  also have \"\\<dots> = (\\<Sum>i. n_ary_series f i) / 3\" by (simp add: to_real_def)\n  also have \"\\<dots> = (\\<Sum>i. n_ary_series f i / 3)\" by (rule suminf_divide[OF n_ary_summable, symmetric])\n  also have \"\\<dots> = (\\<Sum>i. n_ary_series (\\<lambda> i. f (i - 1)) (Suc i))\"\n    by (metis n_ary_series_div real_of_nat_numeral)\n  also have \"\\<dots> = 0 + (\\<Sum>i. n_ary_series (\\<lambda> i. f (i - 1)) (Suc i))\"\n    by simp\n  also have \"\\<dots> = (\\<Sum>i. if i = 0 then 0 else n_ary_series (\\<lambda> i. f (i - 1)) i)\"\n    by (rule suminf_shift[OF n_ary_summable])\n  also have \"\\<dots> = (\\<Sum>i. n_ary_series (\\<lambda> i. if i = 0 then 0 else f (i - 1)) i)\"\n    by (rule arg_cong[where f = suminf])  (auto simp add: n_ary_series_def)\n  also have \"\\<dots> = (\\<Sum>i. n_ary_series (r_go_left f) i)\"\n    by (simp add: r_go_left_def)\n  also have \"\\<dots> = to_real (r_go_left f)\"\n    by (simp add: to_real_def)\n  finally show ?thesis.\nqed\n\n\nlemma cantor_n_eq:  \"cantor_n n = to_real` r_cantor_n n\"\nproof(induction n)\n  case 0 \n  have \"cantor_n 0  = {0..1}\" by simp\n  also have \"\\<dots> = range to_real\" by (rule range_to_real[symmetric])\n  also have \"\\<dots> = to_real ` r_cantor_n 0\" by simp\n  finally show ?case.\nnext\n  case (Suc n)\n  have \"cantor_n (Suc n) = go_left ` cantor_n n \\<union> go_right ` cantor_n n\" by simp\n  also have \"\\<dots> = go_left ` (to_real ` r_cantor_n n) \\<union> go_right ` (to_real ` r_cantor_n n)\"\n    unfolding Suc.IH..\n  also have \"\\<dots> = to_real ` r_go_left ` r_cantor_n n \\<union> to_real ` r_go_right ` r_cantor_n n\"\n    by (simp add: image_image cong: image_cong)\n  also have \"\\<dots> = to_real ` (r_go_left ` r_cantor_n n \\<union> r_go_right ` r_cantor_n n)\" by auto\n  also have \"\\<dots> = to_real ` (r_cantor_n (Suc n))\" by simp\n  finally show ?case.\nqed\n\nlemma r_cantor_n_mono: \"n \\<le> m \\<Longrightarrow> r_cantor_n m \\<subseteq> r_cantor_n n\"\n  by (auto simp add: r_cantor_n_cantor_ary)\n\nlemma r_cantor_n_same_prefix:\n  assumes \"a \\<in> r_cantor_n n\" \"b \\<in> r_cantor_n n\"\n  assumes eq: \"to_real a = to_real b\"\n  shows \"\\<forall>j<n. a j = b j\"\n  using assms(1,2)\nproof(induction n)\n  case 0 show ?case by simp\nnext\n  case (Suc n)\n  from `a \\<in> r_cantor_n (Suc n)` `b \\<in> r_cantor_n (Suc n)`\n  have \"a n \\<in> {0,2}\" and \"b n \\<in> {0,2}\" unfolding r_cantor_n_cantor_ary by auto\n  moreover\n  from  `a \\<in> r_cantor_n (Suc n)` `b \\<in> r_cantor_n (Suc n)`\n  have \"a \\<in> r_cantor_n n\" and \"b \\<in> r_cantor_n n\"\n    using r_cantor_n_mono[where n = n and m = \"Suc n\"] by auto\n  hence \"\\<forall>j<n. a j = b j\" by (rule Suc.IH)\n  moreover\n  note eq\n  ultimately\n  have \"a n = b n\" by (rule to_real_inj_next)\n  with `\\<forall>j<n. a j = b j`\n  show ?case by (metis less_antisym)\nqed\n\ntheorem to_real_surj: \"to_real ` r_cantor = cantor\"\nproof\n  show \"to_real` r_cantor \\<subseteq> cantor\"\n  unfolding cantor_def r_cantor_def\n  by (auto simp add: cantor_n_eq)\nnext\n  show \"cantor \\<subseteq> to_real ` r_cantor\"\n  proof\n    fix x\n    assume \"x \\<in> cantor\"\n    hence \"\\<forall> n. \\<exists> f. f \\<in> r_cantor_n n \\<and> x = to_real f\"\n      by (auto simp add: cantor_def cantor_n_eq)\n    then obtain f where f: \"\\<And>n. f n \\<in> r_cantor_n n\" \"\\<And> n . x = to_real (f n)\" by metis\n\n    { fix n m :: nat\n      note f(1)\n      moreover\n      assume \"n \\<le> m\" with f(1)\n      have \"f m \\<in> r_cantor_n n\" by (metis r_cantor_n_mono subsetCE)\n      moreover\n      from f(2) have \"to_real (f n) = to_real (f m)\" by auto\n      ultimately\n      have \"\\<forall>j<n. f n j = f m j\" by (rule r_cantor_n_same_prefix)\n    }\n    note * = this\n    def f' == \"\\<lambda> n. f (Suc n) n\"\n    \n    have \"\\<forall> n. f' n \\<in> {0,2}\" using f(1) by (metis f'_def lessI r_cantor_n_cantor_ary)\n    hence \"f' \\<in> r_cantor\" unfolding r_cantor_zero_or_two.\n    moreover\n    have \"(\\<lambda> n. abs (to_real f' - to_real (f n))) ----> 0\"\n    proof(rule bounded_0_inverse)\n      fix n\n      show \"0 \\<le> \\<bar>to_real f' - to_real (f n)\\<bar>\" by simp\n      have \"\\<forall>j<n. f' j = f n j\"  by (auto simp add: f'_def *)\n      thus \"\\<bar>to_real f' - to_real (f n)\\<bar> \\<le> 3* (1/3)^n\" by (rule to_real_cont)\n    next\n      show \"1/3 < (1::real)\" and \"0 < (3::real)\" by auto\n    qed\n    hence \"(\\<lambda> n. to_real f' - to_real (f n)) ----> 0\" by (rule tendsto_rabs_zero_cancel)\n    hence \"(\\<lambda> n. to_real f' - x) ----> 0\" unfolding f(2)[symmetric].\n    hence \"x = to_real f'\" by (simp add: LIMSEQ_const_iff)\n    ultimately\n    show \"x \\<in> to_real ` r_cantor\" by auto\n  qed\nqed\n\nsubsubsection {* The bijection *}\n\ntheorem \"bij_betw to_real r_cantor cantor\"\n  by (rule bij_betw_imageI[OF to_real_inj to_real_surj])\n\nsubsection {* A space-filling curve *}\n\ndefinition \"homeomorphism f A B \\<equiv> bij_betw f A B \\<and> continuous_on A f \\<and> continuous_on B (the_inv_into A f)\"\n\nabbreviation \"from_real \\<equiv> the_inv_into r_cantor to_real\"\ndefinition \"fill_1 f i \\<equiv> f (2 * i)\"\ndefinition \"fill_2 f i \\<equiv> f (2 * i + 1)\"\n\ndefinition combine :: \"(nat \\<Rightarrow> nat) \\<Rightarrow> (nat \\<Rightarrow> nat) \\<Rightarrow> (nat \\<Rightarrow> nat)\"\n  where \"combine f g i = (if 2 dvd i then f (i div 2) else g ((i - 1) div 2))\"\n\nlemma combine_fill1_fill2:\n  \"combine (fill_1 f) (fill_2 f) = f\"\nproof\n  fix i  :: nat\n  show \"combine (fill_1 f) (fill_2 f) i = f i\"\n  proof(cases \"2 dvd i\")\n  case True\n    hence \"2 * (i div 2) = i\" by (rule dvd_mult_div_cancel)\n    thus ?thesis\n    using True unfolding fill_1_def fill_2_def combine_def by simp\n  next\n  case False\n    hence \"2 * ((i - 1) div 2) + 1 = i\" by arith\n    thus ?thesis\n    using False unfolding fill_1_def fill_2_def combine_def by simp\n  qed\nqed\n\nlemma fill_1_combine: \"fill_1 (combine x y) = x\"\n  by (auto simp add: fill_1_def combine_def)\n\nlemma fill_2_combine: \"fill_2 (combine x y) = y\"\n  by rule (auto simp add: fill_2_def combine_def, arith)\n  \n\ndefinition fill :: \"real \\<Rightarrow> real \\<times> real\" where\n  \"fill x \\<equiv> (to_real (fill_1 (from_real x)), to_real (fill_2 (from_real x)))\"\n\ndefinition unfill :: \"(real \\<times> real) \\<Rightarrow> real\" where\n  \"unfill p \\<equiv> to_real (combine (from_real (fst p)) (from_real (snd p)))\"\n\n\nlemma fill_1_r_cantor: \"f \\<in> r_cantor \\<Longrightarrow> fill_1 f \\<in> r_cantor\"\n    unfolding r_cantor_zero_or_two by (auto simp add: fill_1_def)\nlemma fill_2_r_cantor: \"f \\<in> r_cantor \\<Longrightarrow> fill_2 f \\<in> r_cantor\"\n    unfolding r_cantor_zero_or_two by (auto simp add: fill_2_def)\nlemma combine_r_cantor: \"x \\<in> r_cantor \\<Longrightarrow> y \\<in> r_cantor \\<Longrightarrow> combine x y \\<in> r_cantor\"\n    unfolding r_cantor_zero_or_two by (auto simp add: combine_def)\n\nlemma unfill_fill:\n  assumes \"x \\<in> cantor\"\n  shows \"unfill (fill x) = x\"\nproof-\n  from assms\n  have \"from_real x \\<in> r_cantor\"\n    by (metis order_refl the_inv_into_into to_real_inj to_real_surj)\n  from fill_1_r_cantor[OF this] fill_2_r_cantor[OF this]\n  show ?thesis\n    unfolding unfill_def fill_def\n    by (simp add: the_inv_into_f_f[OF to_real_inj] combine_fill1_fill2\n                  f_the_inv_into_f[OF to_real_inj] to_real_surj assms)\nqed\n\nlemma fill_unfill:\n  assumes \"x \\<in> cantor\" and \"y \\<in> cantor\"\n  shows \"fill (unfill (x,y)) = (x,y)\"\nproof-\n  from assms\n  have \"from_real x \\<in> r_cantor\" \"from_real y \\<in> r_cantor\"\n    by (metis order_refl the_inv_into_into to_real_inj to_real_surj)+\n  from combine_r_cantor[OF this]\n  show ?thesis\n    unfolding unfill_def fill_def\n    by (simp add: the_inv_into_f_f[OF to_real_inj] fill_1_combine fill_2_combine\n                  f_the_inv_into_f[OF to_real_inj] to_real_surj assms)\nqed\n\nlemma fill_inj: \"inj_on fill cantor\"\n  using unfill_fill by (metis inj_on_def)\n\ntheorem \"homeomorphism fill cantor (cantor \\<times> cantor)\"\n  apply (simp add:homeomorphism_def bij_betw_def fill_inj)\n  oops\n\nend\n", "meta": {"author": "Kha", "repo": "cantor-set", "sha": "7de726c83b536fd4a32c3fabfe5d7dc75dc142da", "save_path": "github-repos/isabelle/Kha-cantor-set", "path": "github-repos/isabelle/Kha-cantor-set/cantor-set-7de726c83b536fd4a32c3fabfe5d7dc75dc142da/Cantor_Set.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8688267762381844, "lm_q2_score": 0.8080672135527632, "lm_q1q2_score": 0.7020704321348198}}
{"text": "theory sse_operation_positive\n  imports sse_boolean_algebra\nbegin\nnitpick_params[assms=true, user_axioms=true, show_all, expect=genuine, format=3] (*default Nitpick settings*)\n\nsection \\<open>Positive semantic conditions for operations\\<close>\n\ntext\\<open>\\noindent{We define and interrelate some useful conditions on propositional functions which do not involve\nnegative-like properties (hence 'positive'). We focus on propositional functions which correspond to unary\nconnectives of the algebra (with type @{text \"\\<sigma>\\<Rightarrow>\\<sigma>\"}). We call such propositional functions 'operations'.}\\<close>\n\nsubsection \\<open>Definitions (finitary case)\\<close>\n\ntext\\<open>\\noindent{Monotonicity (MONO).}\\<close>\ndefinition \"MONO \\<phi> \\<equiv> \\<forall>A B. A \\<^bold>\\<preceq> B \\<longrightarrow> \\<phi> A \\<^bold>\\<preceq> \\<phi> B\" \nlemma MONO_ant: \"MONO \\<phi> \\<Longrightarrow> \\<forall>A B C. A \\<^bold>\\<preceq> B \\<longrightarrow> \\<phi>(B \\<^bold>\\<rightarrow> C) \\<^bold>\\<preceq> \\<phi>(A \\<^bold>\\<rightarrow> C)\" by (smt MONO_def conn)\nlemma MONO_cons: \"MONO \\<phi> \\<Longrightarrow> \\<forall>A B C. A \\<^bold>\\<preceq> B \\<longrightarrow> \\<phi>(C \\<^bold>\\<rightarrow> A) \\<^bold>\\<preceq> \\<phi>(C \\<^bold>\\<rightarrow> B)\" by (smt MONO_def conn)\nlemma MONO_dual: \"MONO \\<phi> \\<Longrightarrow> MONO \\<phi>\\<^sup>d\" by (smt MONO_def dual_def compl_def)\n\ntext\\<open>\\noindent{Extensive/expansive (EXP) and its dual (dEXP), aka. 'contractive'.}\\<close>\ndefinition \"EXP \\<phi>  \\<equiv> \\<forall>A. A \\<^bold>\\<preceq> \\<phi> A\" \ndefinition \"dEXP \\<phi> \\<equiv> \\<forall>A. \\<phi> A \\<^bold>\\<preceq> A\"\nlemma EXP_dual1: \"EXP \\<phi> \\<Longrightarrow> dEXP \\<phi>\\<^sup>d\" by (metis EXP_def dEXP_def dual_def compl_def)\nlemma EXP_dual2: \"dEXP \\<phi> \\<Longrightarrow> EXP \\<phi>\\<^sup>d\" by (metis EXP_def dEXP_def dual_def compl_def)\n\ntext\\<open>\\noindent{Idempotence (IDEM).}\\<close>\ndefinition \"IDEM \\<phi>  \\<equiv> \\<forall>A. (\\<phi> A) \\<^bold>\\<approx> \\<phi>(\\<phi> A)\"\ndefinition \"IDEMa \\<phi> \\<equiv> \\<forall>A. (\\<phi> A) \\<^bold>\\<preceq> \\<phi>(\\<phi> A)\"\ndefinition \"IDEMb \\<phi> \\<equiv> \\<forall>A. (\\<phi> A) \\<^bold>\\<succeq> \\<phi>(\\<phi> A)\"\nlemma IDEM_dual1: \"IDEMa \\<phi> \\<Longrightarrow> IDEMb \\<phi>\\<^sup>d\" unfolding dual_def IDEMa_def IDEMb_def compl_def by auto\nlemma IDEM_dual2: \"IDEMb \\<phi> \\<Longrightarrow> IDEMa \\<phi>\\<^sup>d\" unfolding dual_def IDEMa_def IDEMb_def compl_def by auto\nlemma IDEM_dual: \"IDEM \\<phi> = IDEM \\<phi>\\<^sup>d\" by (metis IDEM_def IDEM_dual1 IDEM_dual2 IDEMa_def IDEMb_def dual_symm)\n\ntext\\<open>\\noindent{Normality (NOR) and its dual (dNOR).}\\<close>\ndefinition \"NOR \\<phi>  \\<equiv> (\\<phi> \\<^bold>\\<bottom>) \\<^bold>\\<approx> \\<^bold>\\<bottom>\"\ndefinition \"dNOR \\<phi> \\<equiv> (\\<phi> \\<^bold>\\<top>) \\<^bold>\\<approx> \\<^bold>\\<top>\" \nlemma NOR_dual1: \"NOR \\<phi> = dNOR \\<phi>\\<^sup>d\" unfolding dual_def NOR_def dNOR_def top_def bottom_def compl_def by simp\nlemma NOR_dual2: \"dNOR \\<phi> = NOR \\<phi>\\<^sup>d\" unfolding dual_def NOR_def dNOR_def top_def bottom_def compl_def by simp\n\ntext\\<open>\\noindent{Distribution over meets or multiplicativity (MULT).}\\<close>\ndefinition \"MULT \\<phi>   \\<equiv> \\<forall>A B. \\<phi>(A \\<^bold>\\<and> B) \\<^bold>\\<approx> (\\<phi> A) \\<^bold>\\<and> (\\<phi> B)\" \ndefinition \"MULT_a \\<phi> \\<equiv> \\<forall>A B. \\<phi>(A \\<^bold>\\<and> B) \\<^bold>\\<preceq> (\\<phi> A) \\<^bold>\\<and> (\\<phi> B)\" \ndefinition \"MULT_b \\<phi> \\<equiv> \\<forall>A B. \\<phi>(A \\<^bold>\\<and> B) \\<^bold>\\<succeq> (\\<phi> A) \\<^bold>\\<and> (\\<phi> B)\" \n\ntext\\<open>\\noindent{Distribution over joins or additivity (ADDI).}\\<close>\ndefinition \"ADDI \\<phi>   \\<equiv> \\<forall>A B. \\<phi>(A \\<^bold>\\<or> B) \\<^bold>\\<approx> (\\<phi> A) \\<^bold>\\<or> (\\<phi> B)\" \ndefinition \"ADDI_a \\<phi> \\<equiv> \\<forall>A B. \\<phi>(A \\<^bold>\\<or> B) \\<^bold>\\<preceq> (\\<phi> A) \\<^bold>\\<or> (\\<phi> B)\"\ndefinition \"ADDI_b \\<phi> \\<equiv> \\<forall>A B. \\<phi>(A \\<^bold>\\<or> B) \\<^bold>\\<succeq> (\\<phi> A) \\<^bold>\\<or> (\\<phi> B)\" \n\n\nsubsection \\<open>Relations among conditions (finitary case)\\<close>\n\ntext\\<open>\\noindent{dEXP and dNOR entail NOR.}\\<close>\nlemma \"dEXP \\<phi> \\<Longrightarrow> dNOR \\<phi> \\<Longrightarrow> NOR \\<phi>\" by (meson bottom_def dEXP_def NOR_def)\n\ntext\\<open>\\noindent{EXP and NOR entail dNOR.}\\<close>\nlemma \"EXP \\<phi> \\<Longrightarrow> NOR \\<phi> \\<Longrightarrow> dNOR \\<phi>\" by (simp add: EXP_def dNOR_def top_def)\n\ntext\\<open>\\noindent{Interestingly, EXP and its dual allow for an alternative characterization of fixed-point operators.}\\<close>\nlemma EXP_fp:  \"EXP  \\<phi> \\<Longrightarrow> \\<phi>\\<^sup>f\\<^sup>p \\<^bold>\\<equiv> (\\<phi>\\<^sup>c \\<^bold>\\<squnion> id)\" by (smt id_def EXP_def dual_def dual_symm equal_op_def conn)\nlemma dEXP_fp: \"dEXP \\<phi> \\<Longrightarrow> \\<phi>\\<^sup>f\\<^sup>p \\<^bold>\\<equiv> (\\<phi> \\<^bold>\\<squnion> compl)\" by (smt dEXP_def equal_op_def conn)\n\ntext\\<open>\\noindent{MONO, MULT-a and ADDI-b are equivalent.}\\<close>\nlemma MONO_MULTa: \"MONO \\<phi> = MULT_a \\<phi>\" proof -\n  have lr: \"MONO \\<phi> \\<Longrightarrow> MULT_a \\<phi>\" by (smt MONO_def MULT_a_def meet_def)\n  have rl: \"MULT_a \\<phi> \\<Longrightarrow> MONO \\<phi>\" proof-\n    assume multa: \"MULT_a \\<phi>\"\n    { fix A B\n      { assume \"A \\<^bold>\\<preceq> B\"\n        hence \"A \\<^bold>\\<approx> A \\<^bold>\\<and> B\" unfolding conn by blast\n        hence \"\\<phi> A \\<^bold>\\<approx> \\<phi>(A \\<^bold>\\<and> B)\" unfolding conn by simp\n        moreover from multa have \"\\<phi>(A \\<^bold>\\<and> B) \\<^bold>\\<preceq> (\\<phi> A) \\<^bold>\\<and> (\\<phi> B)\" using MULT_a_def by metis\n        ultimately have \"\\<phi> A \\<^bold>\\<preceq> (\\<phi> A) \\<^bold>\\<and> (\\<phi> B)\" by blast\n        hence \"\\<phi> A \\<^bold>\\<preceq> (\\<phi> B)\" unfolding conn by blast\n      } hence \"A \\<^bold>\\<preceq> B \\<longrightarrow> \\<phi> A \\<^bold>\\<preceq> \\<phi> B\" by (rule impI)\n    } thus ?thesis by (simp add: MONO_def) qed\n  from lr rl show ?thesis by auto\nqed\nlemma MONO_ADDIb: \"MONO \\<phi> = ADDI_b \\<phi>\" proof -\n  have lr: \"MONO \\<phi> \\<Longrightarrow> ADDI_b \\<phi>\" by (smt ADDI_b_def MONO_def join_def)\n  have rl: \"ADDI_b \\<phi> \\<Longrightarrow> MONO \\<phi>\" proof -\n  assume addib: \"ADDI_b \\<phi>\"\n  { fix A B\n    { assume \"A \\<^bold>\\<preceq> B\"\n      hence \"B \\<^bold>\\<approx> A \\<^bold>\\<or> B\" unfolding conn by blast\n      hence \"\\<phi> B \\<^bold>\\<approx> \\<phi>(A \\<^bold>\\<or> B)\" unfolding conn by simp\n      moreover from addib have \"(\\<phi> A) \\<^bold>\\<or> (\\<phi> B) \\<^bold>\\<preceq> \\<phi>(A \\<^bold>\\<or> B)\" using ADDI_b_def by metis\n      ultimately have \"(\\<phi> A) \\<^bold>\\<or> (\\<phi> B) \\<^bold>\\<preceq> \\<phi> B\" by blast\n      hence \"\\<phi> A \\<^bold>\\<preceq> (\\<phi> B)\" unfolding conn by blast\n    } hence \"A \\<^bold>\\<preceq> B \\<longrightarrow> \\<phi> A \\<^bold>\\<preceq> \\<phi> B\" by (rule impI)\n  } thus ?thesis by (simp add: MONO_def) qed\n  from lr rl show ?thesis by auto\nqed\nlemma ADDIb_MULTa: \"ADDI_b \\<phi> = MULT_a \\<phi>\" using MONO_ADDIb MONO_MULTa by 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/Topological_Semantics/sse_operation_positive.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8688267728417086, "lm_q2_score": 0.808067204308405, "lm_q1q2_score": 0.7020704213584931}}
{"text": "(*  \n    Title:      Rank.thy\n    Author:     Jose Divas\u00f3n <jose.divasonm at unirioja.es>\n    Author:     Jes\u00fas Aransay <jesus-maria.aransay at unirioja.es>\n    Maintainer: Jose Divas\u00f3n <jose.divasonm at unirioja.es>\n*)\n\nheader{*Rank of a matrix*}\n\ntheory Rank\nimports \n      \"../Rank_Nullity_Theorem/Dim_Formula\"\nbegin\n\nsubsection{*Row rank, column rank and rank*}\n\ntext{*Definitions of row rank, column rank and rank*}\n\ndefinition row_rank :: \"'a::{field}^'n^'m=>nat\"\n  where \"row_rank A = vec.dim (row_space A)\"\n\ndefinition col_rank :: \"'a::{field}^'n^'m=>nat\"\n  where \"col_rank A = vec.dim (col_space A)\"\n\ndefinition rank :: \"'a::{field}^'n^'m=>nat\"\n  where \"rank A = row_rank A\"\n\nsubsection{*Properties*}\n\nlemma rrk_is_preserved:\nfixes A::\"'a::{field}^'cols^'rows::{finite, wellorder}\"\n  and P::\"'a::{field}^'rows::{finite, wellorder}^'rows::{finite, wellorder}\"\nassumes inv_P: \"invertible P\"\nshows \"row_rank A = row_rank (P**A)\"\nby (metis row_space_is_preserved row_rank_def inv_P)\n\nlemma crk_is_preserved:\nfixes A::\"'a::{field}^'cols::{finite, wellorder}^'rows\"\n  and P::\"'a::{field}^'rows^'rows\"\nassumes inv_P: \"invertible P\"\nshows \"col_rank A = col_rank (P**A)\"\n  using rank_nullity_theorem_matrices unfolding ncols_def \n  by (metis col_rank_def inv_P nat_add_left_cancel null_space_is_preserved) \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/Gauss_Jordan/Rank.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772482857831, "lm_q2_score": 0.8031738034238807, "lm_q1q2_score": 0.7020359479919721}}
{"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 + (\\<Squnion>z\\<in>elts y. f z) = (\\<Squnion>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 + (\\<Squnion>z\\<in>elts \\<alpha>. f z) = (\\<Squnion>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> (\\<Squnion>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> (\\<Squnion>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> (\\<Squnion>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> (\\<Squnion>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) = (\\<Squnion>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> = (\\<Squnion>x\\<in>elts x. succ (rank x)) \\<squnion> (\\<Squnion>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> = (\\<Squnion>z \\<in> elts y. rank x + succ (rank z))\"\n    proof -\n      have \"rank x \\<le> (\\<Squnion>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 + (\\<Squnion>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) = (\\<Squnion>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> = (\\<Squnion>\\<beta> \\<in> elts \\<mu>. \\<beta>)\"\n    by (simp add: Limit_eq_Sup_self)\n  also have \"\\<dots>  \\<le> (\\<Squnion>\\<beta> \\<in> elts \\<mu>. \\<alpha> + \\<beta>)\"\n    using Limit.IH by auto\n  also have \"\\<dots> = \\<alpha> + (\\<Squnion>\\<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 = (\\<Squnion>u\\<in>elts y. lift (x * u) x)\"\n  unfolding times_V_def  by (subst transrec) (force simp:)\n\nlemma elts_multE:\n  assumes \"z \\<in> elts (x * y)\" \n  obtains u v where \"u \\<in> elts x\" \"v \\<in> elts y\" \"z = x*v + u\" \n  using mult [of x y] lift_def assms by auto\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 = (\\<Squnion>u\\<in>elts (lift y z). lift (x * u) x)\"\n    using mult by blast\n  also have \"\\<dots> = (\\<Squnion>v\\<in>elts z. lift (x * (y + v)) x)\"\n    using lift_def by auto\n  also have \"\\<dots> = (\\<Squnion>v\\<in>elts z. lift (x * y + x * v) x)\"\n    using mult_lift_imp_distrib step.IH by auto\n  also have \"\\<dots> = (\\<Squnion>v\\<in>elts z. lift (x * y) (lift (x * v) x))\"\n    by (simp add: lift_lift)\n  also have \"\\<dots> = lift (x * y) (\\<Squnion>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 = (\\<Squnion>u\\<in>elts z. lift (x * y * u) (x * y))\"\n      using mult by blast\n    also have \"\\<dots> = (\\<Squnion>u\\<in>elts z. lift (x * (y * u)) (x * y))\"\n      using step.IH by auto\n    also have \"\\<dots> = (\\<Squnion>u\\<in>elts z. x * lift (y * u) y)\"\n      using mult_lift by auto\n    also have \"\\<dots> = x * (\\<Squnion>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) = (\\<Squnion>y\\<in>elts (\\<Squnion>u\\<in>elts y. lift (x * u) x). succ (rank y))\"\n    by (metis rank_Sup mult)\n  also have \"\\<dots> = (\\<Squnion>u\\<in>elts y. \\<Squnion>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> = (\\<Squnion>u\\<in>elts y. \\<Squnion>r\\<in>elts x. succ (rank (x * u) + rank r))\"\n    using rank_add_distrib by auto\n  also have \"\\<dots> = (\\<Squnion>u\\<in>elts y. \\<Squnion>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> = (\\<Squnion>u\\<in>elts y. rank x * rank u + rank x)\"\n  proof (rule SUP_cong)\n    show \"(\\<Squnion>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 \"(\\<Squnion>r\\<in>elts x. succ (rank x * rank u + rank r)) = rank x * rank u + (\\<Squnion>y\\<in>elts x. succ (rank y))\"\n      proof (rule order_antisym)\n        show \"(\\<Squnion>r\\<in>elts x. succ (rank x * rank u + rank r)) \\<le> rank x * rank u + (\\<Squnion>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 + (\\<Squnion>y\\<in>elts x. succ (rank y)) = (\\<Squnion>y\\<in>elts x. rank x * rank u + succ (rank y))\"\n          by (simp add: add_Sup_distrib False)\n        also have \"\\<dots> \\<le> (\\<Squnion>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 + (\\<Squnion>y\\<in>elts x. succ (rank y)) \\<le> (\\<Squnion>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 \\<le> 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        using plus_eq_lift succ.prems(3) by auto\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 show ?thesis\n            by (metis \\<open>r' \\<in> elts a\\<close> antisym le_TC_refl less_TC_iff order_refl succ.IH u_k v)\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      show \"a * x + r \\<le> a * y + s\"\n        by (simp add: Limit.prems)\n    qed (auto simp: Limit.prems)\n  qed\n  then show ?thesis\n    by (metis two_in_Vset Ord_rank Ord_VsetI rank_lt)\nqed\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 assms leD less_V_def mult_cancellation_half odiff_add_cancel order_refl)\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 mult_cancellation_less:\n  assumes lt: \"a*x + r < a*y + s\" and \"r \\<sqsubset> a\" \"s \\<sqsubset> a\"\n  obtains \"x < y\" | \"x = y\" \"r < s\"\nproof -\n  have \"x \\<le> y\"\n    by (meson assms dual_order.strict_implies_order mult_cancellation_half)\n  then consider \"x < y\" | \"x = y\"\n    using less_V_def by blast\n  with lt that show ?thesis by blast\nqed\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\n\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 = (\\<Squnion>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) = (\\<Squnion>r \\<in> elts (TC x). \\<Squnion>u \\<in> elts (TC y). set{x * u + r})\"\nproof (cases \"x = 0\")\n  case False\n  have *: \"TC(x * y) = (\\<Squnion>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) = (\\<Squnion>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> = (\\<Squnion>u \\<in> elts y. TC(x * u) \\<squnion> lift (x * u) (TC x))\"\n      by (simp add: TC_lift False)\n    also have \"\\<dots> = (\\<Squnion>u \\<in> elts y. (\\<Squnion>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> = (\\<Squnion>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\nlemma ordertype_Times:\n  assumes \"small A\" \"small B\" and r: \"wf r\" \"trans r\" \"total_on A r\" and s: \"wf s\" \"trans s\" \"total_on B s\"\n  shows \"ordertype (A\\<times>B) (r <*lex*> s) = ordertype B s * ordertype A r\" (is \"_ = ?\\<beta> * ?\\<alpha>\")\nproof (subst ordertype_eq_iff)\n  show \"Ord (?\\<beta> * ?\\<alpha>)\"\n    by (intro wf_Ord_ordertype Ord_mult r s; simp)\n  define f where \"f \\<equiv> \\<lambda>(x,y). ?\\<beta> * ordermap A r x + (ordermap B s y)\"\n  show \"\\<exists>f. bij_betw f (A \\<times> B) (elts (?\\<beta> * ?\\<alpha>)) \\<and> (\\<forall>x\\<in>A \\<times> B. \\<forall>y\\<in>A \\<times> B. (f x < f y) = ((x, y) \\<in> (r <*lex*> s)))\"\n    unfolding bij_betw_def\n  proof (intro exI conjI strip)\n    show \"inj_on f (A \\<times> B)\"\n    proof (clarsimp simp: f_def inj_on_def)\n      fix x y x' y'\n      assume \"x \\<in> A\" \"y \\<in> B\" \"x' \\<in> A\" \"y' \\<in> B\"\n        and eq: \"?\\<beta> * ordermap A r x + ordermap B s y = ?\\<beta> * ordermap A r x' + ordermap B s y'\"\n      have \"ordermap A r x = ordermap A r x' \\<and>\n            ordermap B s y = ordermap B s y'\"\n      proof (rule mult_cancellation_lemma [OF eq])\n        show \"ordermap B s y \\<sqsubset> ?\\<beta>\"\n          using ordermap_in_ordertype [OF \\<open>y \\<in> B\\<close>, of s] less_TC_iff \\<open>small B\\<close> by blast \n        show \"ordermap B s y' \\<sqsubset> ?\\<beta>\"\n          using ordermap_in_ordertype [OF \\<open>y' \\<in> B\\<close>, of s] less_TC_iff \\<open>small B\\<close> by blast \n      qed\n      then show \"x = x' \\<and> y = y'\"\n        using \\<open>x \\<in> A\\<close> \\<open>x' \\<in> A\\<close> \\<open>y \\<in> B\\<close> \\<open>y' \\<in> B\\<close> r s \\<open>small A\\<close> \\<open>small B\\<close> by auto\n    qed\n    show \"f ` (A \\<times> B) = elts (?\\<beta> * ?\\<alpha>)\" (is \"?lhs = ?rhs\")\n    proof \n      show \"f ` (A \\<times> B) \\<subseteq> elts (?\\<beta> * ?\\<alpha>)\"\n        apply (auto simp: f_def add_mult_less ordermap_in_ordertype wf_Ord_ordertype r s)\n        by (simp add: add_mult_less assms ordermap_in_ordertype wf_Ord_ordertype)\n      show \"elts (?\\<beta> * ?\\<alpha>) \\<subseteq> f ` (A \\<times> B)\"\n      proof (clarsimp simp: f_def image_iff elim !: elts_multE split: prod.split)\n        fix u v\n        assume u: \"u \\<in> elts (?\\<beta>)\" and v: \"v \\<in> elts ?\\<alpha>\"\n        have \"inv_into B (ordermap B s) u \\<in> B\"\n          by (simp add: inv_into_ordermap u)\n        moreover have \"inv_into A (ordermap A r) v \\<in> A\"\n          by (simp add: inv_into_ordermap v)\n        ultimately show \"\\<exists>x\\<in>A. \\<exists>y\\<in>B. ?\\<beta> * v + u = ?\\<beta> * ordermap A r x + ordermap B s y\"\n          by (metis \\<open>small A\\<close> \\<open>small B\\<close> bij_betw_inv_into_right ordermap_bij r(1) r(3) s(1) s(3) u v)\n      qed\n    qed\n  next\n    fix p q\n    assume \"p \\<in> A \\<times> B\" and \"q \\<in> A \\<times> B\"\n    then obtain u v x y where \\<section>: \"p = (u,v)\" \"u \\<in> A\" \"v \\<in> B\" \"q = (x,y)\" \"x \\<in> A\" \"y \\<in> B\"\n      by blast\n    show \"((f p) < f q) = ((p, q) \\<in> (r <*lex*> s))\"\n    proof\n      assume \"f p < f q\"\n      with \\<section> assms have \"(u, x) \\<in> r \\<or> u=x \\<and> (v, y) \\<in> s\"\n        apply (simp add: f_def)\n        by (metis Ord_add Ord_add_mult_iff Ord_mem_iff_lt Ord_mult wf_Ord_ordermap converse_ordermap_mono \n            ordermap_eq_iff ordermap_in_ordertype wf_Ord_ordertype)\n      then show \"(p,q) \\<in> (r <*lex*> s)\"\n        by (simp add: \\<section>)\n    next\n      assume \"(p,q) \\<in> (r <*lex*> s)\"\n      then have \"(u, x) \\<in> r \\<or> u = x \\<and> (v, y) \\<in> s\"\n        by (simp add: \\<section>)\n      then show \"f p < f q\"\n      proof\n        assume ux: \"(u, x) \\<in> r\"\n        have oo: \"\\<And>x. Ord (ordermap A r x)\" \"\\<And>y. Ord (ordermap B s y)\" \n          by (simp_all add: r s)\n        show \"f p < f q\"\n        proof (clarsimp simp: f_def split: prod.split)\n          fix a b a' b'\n          assume \"p = (a, b)\" and \"q = (a', b')\"\n          then have \"?\\<beta> * ordermap A r a + ordermap B s b < ?\\<beta> * ordermap A r a'\"\n            using ux assms \\<section>\n            by (metis Ord_mult wf_Ord_ordermap OrdmemD Pair_inject add_mult_less ordermap_in_ordertype ordermap_mono wf_Ord_ordertype)\n          also have \"\\<dots> \\<le> ?\\<beta> * ordermap A r a' + ordermap B s b'\"\n            by simp\n          finally show \"?\\<beta> * ordermap A r a + ordermap B s b < ?\\<beta> * ordermap A r a' + ordermap B s b'\" .\n        qed\n      next\n        assume \"u = x \\<and> (v, y) \\<in> s\"\n        then show \"f p < f q\"\n          using \\<section> assms by (fastforce simp: f_def split: prod.split intro: ordermap_mono_less)\n      qed \n    qed\n  qed \nqed (use assms small_Times in 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/ZFC_in_HOL/Kirby.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8740772318846386, "lm_q2_score": 0.8031737892899222, "lm_q1q2_score": 0.7020359224648312}}
{"text": "theory Basics\nimports Main\nbegin\n\nsection {* Basics *}\nsubsection {* Enumerated Types *}\nsubsubsection {* Days of the Week *}\n\ndatatype day =\n  monday\n  | tuesday\n  | wednesday\n  | thursday\n  | friday\n  | saturday\n  | sunday\n\ndefinition next_weekday :: \"day \\<Rightarrow> day\" where\n  \"next_weekday d \\<equiv> case d of\n    monday \\<Rightarrow> tuesday\n    | tuesday \\<Rightarrow> wednesday\n    | wednesday \\<Rightarrow> thursday\n    | friday \\<Rightarrow> monday\n    | saturday \\<Rightarrow> monday\n    | sunday \\<Rightarrow> monday\"\n\nvalue \"next_weekday friday\"\n  (* \\<Longrightarrow> \"monday\" :: \"day\" *)\nvalue \"next_weekday (next_weekday saturday)\"\n  (* \\<Longrightarrow> \"tuesday\" :: \"day\" *)\n\nlemma test_next_weekday:\n  \"(next_weekday (next_weekday saturday)) = tuesday\"\nusing next_weekday_def by simp\n\nsubsubsection {* Booleans *}\n\ndatatype bool = true | false\n\nfun negb :: \"bool \\<Rightarrow> bool\" where\n  \"negb true = false\"\n  | \"negb false = true\"\n\nfun andb :: \"bool \\<Rightarrow> bool \\<Rightarrow> bool\" where\n  \"andb true b2 = b2\"\n  | \"andb false _ = false\"\n\nfun orb :: \"bool \\<Rightarrow> bool \\<Rightarrow> bool\" where\n  \"orb true _ = true\"\n  | \"orb false b2 = b2\"\n\nlemma test_orb1: \"(orb true false) = true\" by simp\nlemma test_orb2: \"(orb false false) = false\" by simp\nlemma test_orb3: \"(orb false true) = true\" by simp\nlemma test_orb4: \"(orb true true) = true\" by simp\n\n(* Exercise: 1 star (nandb) *)\n\nfun nandb :: \"bool \\<Rightarrow> bool \\<Rightarrow> bool\" where\n  \"nandb true b2 = negb b2\"\n  | \"nandb false _ = true\"\n\nlemma test_nandb1: \"(nandb true false) = true\" by simp\nlemma test_nandb2: \"(nandb false false) = true\" by simp\nlemma test_nandb3: \"(nandb false true) = true\" by simp\nlemma test_nandb4: \"(nandb true true) = false\" by simp\n\n(* Exercise: 1 star (andb3) *)\n\nfun andb3 :: \"bool \\<Rightarrow> bool \\<Rightarrow> bool \\<Rightarrow> bool\" where\n  \"andb3 b1 b2 b3 = andb b1 (andb b2 b3)\"\n\nlemma test_andb31: \"(andb3 true true true) = true\" by simp\nlemma test_andb32: \"(andb3 false true true) = false\" by simp\nlemma test_andb33: \"(andb3 true false true) = false\" by simp\nlemma test_andb34: \"(andb3 true true false) = false\" by simp\n\nsubsubsection {* Function Types *}\n\nvalue \"true\"\n  (* \\<Longrightarrow> \"true\" :: \"Basics.bool\" *)\nvalue \"negb true\"\n  (* \\<Longrightarrow> \"false\" :: \"Basics.bool\" *)\nvalue \"negb\"\n  (* \\<Longrightarrow> \"_\" :: \"Basics.bool \\<Rightarrow> Basics.bool\"*)\n\nsubsubsection {* Numbers *}\n\ndatatype nat = zero | suc nat\n\nfun pred :: \"nat \\<Rightarrow> nat\" where\n  \"pred zero = zero\"\n  | \"pred (suc n') = n'\"\n\nfun minustwo :: \"nat \\<Rightarrow> nat\" where\n  \"minustwo zero = zero\"\n  | \"minustwo (suc zero) = zero\"\n  | \"minustwo (suc (suc n')) = n'\"\n\nvalue \"suc (suc (suc (suc zero)))\"\n  (* \\<Longrightarrow> \"suc (suc (suc (suc zero)))\" :: \"Basics.nat\" *)\nvalue \"minustwo (suc (suc (suc (suc zero))))\"\n  (* \\<Longrightarrow> \"suc (suc zero)\" :: \"Basics.nat\" *)\n\nvalue \"suc\"\n  (* \\<Longrightarrow> \"_\" :: \"Basics.nat \\<Rightarrow> Basics.nat\" *)\nvalue \"pred\"\n  (* \\<Longrightarrow> \"_\" :: \"Basics.nat \\<Rightarrow> Basics.nat\" *)\nvalue \"minustwo\"\n  (* \\<Longrightarrow> \"_\" :: \"Basics.nat \\<Rightarrow> Basics.nat\" *)\n\nfun evenb :: \"nat \\<Rightarrow> bool\" where\n  \"evenb zero = true\"\n  | \"evenb (suc zero) = false\"\n  | \"evenb (suc (suc b)) = evenb b\"\n\nfun oddb where \"oddb n = negb (evenb n)\"\n\nlemma test_oddb1: \"(oddb (suc zero)) = true\" by simp\nlemma test_oddb2: \"(oddb (suc (suc (suc (suc zero))))) = false\" by simp\n\nfun plus :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\" where\n  \"plus zero m = m\"\n  | \"plus (suc n') m = suc (plus n' m)\"\n\nvalue \"plus (suc (suc (suc zero))) (suc (suc zero))\"\n  (* \\<Longrightarrow> \"suc (suc (suc (suc (suc zero))))\" :: \"Basics.nat\" *)\n\nfun mult :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\" where\n  \"mult zero m = zero\"\n  | \"mult (suc n') m = plus m (mult n' m)\"\n\n(* test_mult1: \"3 * 3 = 9\" *)\nlemma test_mult1:\n  \"mult (suc (suc (suc zero))) (suc (suc (suc zero))) = (suc (suc (suc (suc (suc (suc (suc (suc (suc zero)))))))))\"\nby simp\n\nfun minus :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\" where\n  \"minus zero _ = zero\"\n  | \"minus (suc n) zero = suc n\"\n  | \"minus (suc n) (suc m) = minus n m\"\n\nfun exp :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\" where\n  \"exp base zero = suc zero\"\n  | \"exp base (suc p) = mult base (exp base p)\"\n\n(* Exercise: 1 star (factorial) *)\n\nfun factorial :: \"nat \\<Rightarrow> nat\" where\n  \"factorial zero = suc zero\"\n  | \"factorial (suc n) = mult (suc n) (factorial n)\"\n\nlemma test_factorial1: \"(factorial (suc (suc (suc zero)))) = suc (suc (suc (suc (suc (suc zero)))))\" by simp\n(* Example test_factorial2: (factorial 5) = (mult 10 12) *)\n\nno_notation\n  Groups.plus (infixl \"+\" 65) and\n  Product_Type.Times (infixr \"\\<times>\" 80)\n\nnotation\n  plus (infixl \"+\" 65) and\n  minus (infixl \"-\" 65) and\n  mult (infixl \"\\<times>\" 80)\n\nvalue \"(zero + suc zero) + suc zero\"\n  (* \\<Longrightarrow> \"suc (suc zero)\" :: \"Basics.nat\" *)\n\nfun beq_nat :: \"nat \\<Rightarrow> nat \\<Rightarrow> bool\" where\n  \"beq_nat zero zero = true\"\n  | \"beq_nat zero (suc m) = false\"\n  | \"beq_nat (suc n) zero = false\"\n  | \"beq_nat (suc n) (suc m) = beq_nat n m\"\n\nfun ble_nat :: \"nat \\<Rightarrow> nat \\<Rightarrow> bool\" where\n  \"ble_nat zero _ = true\"\n  | \"ble_nat (suc n) zero = false\"\n  | \"ble_nat (suc n) (suc m) = ble_nat n m\"\n\nlemma test_ble_nat1: \"ble_nat (suc (suc zero)) (suc (suc zero)) = true\" by simp\nlemma test_ble_nat2: \"ble_nat (suc (suc zero)) (suc (suc (suc (suc zero)))) = true\" by simp\nlemma test_ble_nat3: \"ble_nat (suc (suc (suc (suc zero)))) (suc (suc zero)) = false\" by simp\n\n(* Exercise: 2 stars (blt_nat) *)\n\nfun blt_nat :: \"nat \\<Rightarrow> nat \\<Rightarrow> bool\" where\n  \"blt_nat n m = andb (ble_nat n m) (negb (beq_nat n m))\"\n\nlemma test_blt_nat1: \"blt_nat (suc (suc zero)) (suc (suc zero)) = false\" by simp\nlemma test_blt_nat2: \"blt_nat (suc (suc zero)) (suc (suc (suc (suc zero)))) = true\" by simp\nlemma test_blt_nat3: \"blt_nat (suc (suc (suc (suc zero)))) (suc (suc zero)) = false\" by simp\n\nsubsection {* Proof by Simplification *}\n\ntheorem plus_O_n: \"\\<forall>(n :: nat). zero + n = n\" by simp\ntheorem plus_1_l: \"\\<forall>(n :: nat). (suc zero) + n = suc n\" by simp\ntheorem mult_0_l: \"\\<forall>(n :: nat). zero \\<times> n = zero\" by simp\n\nsubsection {* Proof by Rewriting *}\n\ntheorem plus_id_example: \"\\<forall>n m :: nat. n = m \\<longrightarrow> n + n = m + m\" by simp\n\n(* Exercise: 1 star (plus_id_exercise) *)\n\ntheorem plus_id_exercise: \"\\<forall>n m l :: nat. n = m \\<longrightarrow> m = l \\<longrightarrow> n + m = m + l\" by simp\ntheorem mult_0_plus: \"\\<forall>n m :: nat. (zero + n) \\<times> m = n \\<times> m\" by simp\n\n(* Exercise: 2 stars (mult_S_1) *)\n\ntheorem mult_S_1: \"\\<forall>n m :: nat. m = suc n \\<longrightarrow> m \\<times> (suc zero + n) = m \\<times> m\" by simp\n\nsubsection {* Proof by Case Analysis *}\n\ntheorem plus_1_neq_0: \"\\<forall>n :: nat. beq_nat (n + suc zero) zero = false\"\napply (rule allI) by (case_tac n, simp, simp)\n\ntheorem negb_involutive: \"\\<forall>b :: bool. negb (negb b) = b\"\napply (rule allI) by (case_tac b, simp, simp)\n\n(* Exercise: 1 star (zero_nbeq_plus_1) *)\n\ntheorem zero_nbeq_plus_1: \"\\<forall>n :: nat. beq_nat zero (n + suc zero) = false\"\napply (rule allI) by (case_tac n, simp, simp)\n\nsubsection {* More Exercises *}\n\n(* Exercise: 2 stars (boolean functions) *)\n\ntheorem identity_fn_applied_twice:\n  \"\\<forall>(f :: bool \\<Rightarrow> bool). (\\<forall>(x :: bool). f x = x) \\<longrightarrow> (\\<forall>(b :: bool). f (f b) = b)\"\nby simp\n\ntheorem negation_fn_applied_twice:\n  \"\\<forall>(f :: bool \\<Rightarrow> bool). (\\<forall>(x :: bool). f x = negb x) \\<longrightarrow> (\\<forall>(b :: bool). f (f b) = b)\"\napply auto by (case_tac b, simp, simp)\n\n(* Exercise: 2 stars (andb_eq_orb) *)\n\ntheorem andb_eq_orb: \"\\<forall>b c :: bool. (andb b c = orb b c) \\<longrightarrow> b = c\"\napply auto by (case_tac b, simp, simp)\n\n(* Exercise: 3 stars (binary) *)\n\ndatatype bin = zero | twice bin | twice_one bin\n\nfun incr :: \"bin \\<Rightarrow> bin\" where\n  \"incr bin.zero = twice_one bin.zero\"\n  | \"incr (twice n) = twice_one n\"\n  | \"incr (twice_one n) = twice (incr n)\"\n\nfun double :: \"nat \\<Rightarrow> nat\" where\n  \"double nat.zero = nat.zero\"\n  | \"double (suc n) = suc (suc (double n))\"\n\nfun bin_nat :: \"bin \\<Rightarrow> nat\" where\n  \"bin_nat bin.zero = nat.zero\"\n  | \"bin_nat (twice n) = double (bin_nat n)\"\n  | \"bin_nat (twice_one n) = suc (double (bin_nat n))\"\n\nlemma incr_nat_comm: \"\\<forall>b :: bin. bin_nat (incr b) = suc (bin_nat b)\"\napply auto by (induct_tac b, auto)\n\nsubsection {* Optional Material *}\n\nsubsubsection {* More on Notation *}\nsubsubsection {* Fixpoints and Structural Recursion *}\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/Basics.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391624034103, "lm_q2_score": 0.8128673155708975, "lm_q1q2_score": 0.7018228317149989}}
{"text": "theory Chapter4\nimports Main\nbegin\n\nvalue \"1 + 2\"\nvalue \"((\\<lambda>x. undefined)(a\\<^sub>1 := {a\\<^sub>1}, a\\<^sub>2 := {a\\<^sub>1, a\\<^sub>2})) a\\<^sub>1\" \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\n(* lemma \"\\<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  apply (rule allI, rule allI)\n  apply (rule impI)\n*)\n    \nthm conjI[OF refl[of \"a\"] refl[of \"b\"]]\n  \nlemma \"Suc(Suc(Suc a)) \\<le> b \\<Longrightarrow> a \\<le> b\"\n  by (drule Suc_leD, drule Suc_leD, drule Suc_leD, simp)\n\nlemma \"Suc(Suc(Suc a)) \\<le> b \\<Longrightarrow> a \\<le> b\"\n  by (rule Suc_leD, rule Suc_leD, rule Suc_leD, assumption)\n\ninductive ev :: \"nat \\<Rightarrow> bool\" where\n  ev0:  \"ev 0\" |\n  evSS: \"ev n \\<Longrightarrow> ev (n + 2)\"\n  \nfun odd :: \"nat \\<Rightarrow> bool\" where\n    \"odd 0 = False\"\n  | \"odd (Suc 0) = True\"\n  | \"odd (Suc(Suc n)) = odd 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 odd_evn_eq: \"odd n \\<Longrightarrow> \\<not>(evn n)\"\n  apply (induction rule: odd.induct)\n    by auto\n    \nlemma \"ev m \\<Longrightarrow> \\<not>odd m\"\n  apply (induction rule: ev.induct )\n  by simp_all\n    \nlemma \"\\<not> ev (Suc 0)\"\n  apply (rule notI)\n  apply (induction rule: ev.induct)\n    apply auto\n    sorry\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/Chapter4.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916099737806, "lm_q2_score": 0.8128673110375457, "lm_q1q2_score": 0.7018228163717645}}
{"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  theory TIP_prop_57\nimports \"../../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 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\nfun t2 :: \"Nat => Nat => Nat\" where\n\"t2 (Z) y = Z\"\n| \"t2 (S z) (Z) = S z\"\n| \"t2 (S z) (S x2) = t2 z x2\"\n\ntheorem property0 :\n  \"((drop n (take m xs)) = (take (t2 m n) (drop n 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/Isaplanner/Isaplanner/TIP_prop_57.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898203834278, "lm_q2_score": 0.7745833841649233, "lm_q1q2_score": 0.7017646610915665}}
{"text": "theory Star imports MainRLT\nbegin\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\nhide_fact (open) refl step  \\<comment> \\<open>names too generic\\<close>\n\nlemma star_trans:\n  \"star r x y \\<Longrightarrow> star r y z \\<Longrightarrow> star r x z\"\nproof(induction rule: star.induct)\n  case refl thus ?case .\nnext\n  case step thus ?case by (metis star.step)\nqed\n\nlemmas star_induct =\n  star.induct[of \"r:: 'a*'b \\<Rightarrow> 'a*'b \\<Rightarrow> bool\", split_format(complete)]\n\ndeclare star.refl[simp,intro]\n\nlemma star_step1[simp, intro]: \"r x y \\<Longrightarrow> star r x y\"\nby(metis star.refl star.step)\n\ncode_pred star .\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/Star.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.879146780175245, "lm_q2_score": 0.7981867873410141, "lm_q1q2_score": 0.7017233440692755}}
{"text": "(*  Title:      ZF/ex/Commutation.thy\n    Author:     Tobias Nipkow & Sidi Ould Ehmety\n    Copyright   1995  TU Muenchen\n\nCommutation theory for proving the Church Rosser theorem.\n*)\n\ntheory Commutation imports Main begin\n\ndefinition\n  square  :: \"[i, i, i, i] => o\" where\n  \"square(r,s,t,u) ==\n    (\\<forall>a b. <a,b> \\<in> r \\<longrightarrow> (\\<forall>c. <a, c> \\<in> s \\<longrightarrow> (\\<exists>x. <b,x> \\<in> t & <c,x> \\<in> u)))\"\n\ndefinition\n  commute :: \"[i, i] => o\" where\n  \"commute(r,s) == square(r,s,s,r)\"\n\ndefinition\n  diamond :: \"i=>o\" where\n  \"diamond(r)   == commute(r, r)\"\n\ndefinition\n  strip :: \"i=>o\" where\n  \"strip(r) == commute(r^*, r)\"\n\ndefinition\n  Church_Rosser :: \"i => o\" where\n  \"Church_Rosser(r) == (\\<forall>x y. <x,y> \\<in>  (r \\<union> converse(r))^* \\<longrightarrow>\n                        (\\<exists>z. <x,z> \\<in> r^* & <y,z> \\<in> r^*))\"\n\ndefinition\n  confluent :: \"i=>o\" where\n  \"confluent(r) == diamond(r^*)\"\n\n\nlemma square_sym: \"square(r,s,t,u) ==> square(s,r,u,t)\"\n  unfolding square_def by blast\n\nlemma square_subset: \"[| square(r,s,t,u); t \\<subseteq> t' |] ==> square(r,s,t',u)\"\n  unfolding square_def by blast\n\n\nlemma square_rtrancl:\n  \"square(r,s,s,t) ==> field(s)<=field(t) ==> square(r^*,s,s,t^*)\"\napply (unfold square_def, clarify)\napply (erule rtrancl_induct)\napply (blast intro: rtrancl_refl)\napply (blast intro: rtrancl_into_rtrancl)\ndone\n\n(* A special case of square_rtrancl_on *)\nlemma diamond_strip:\n  \"diamond(r) ==> strip(r)\"\napply (unfold diamond_def commute_def strip_def)\napply (rule square_rtrancl, simp_all)\ndone\n\n(*** commute ***)\n\nlemma commute_sym: \"commute(r,s) ==> commute(s,r)\"\n  unfolding commute_def by (blast intro: square_sym)\n\nlemma commute_rtrancl:\n  \"commute(r,s) ==> field(r)=field(s) ==> commute(r^*,s^*)\"\napply (unfold commute_def)\napply (rule square_rtrancl)\napply (rule square_sym [THEN square_rtrancl, THEN square_sym])\napply (simp_all add: rtrancl_field)\ndone\n\n\nlemma confluentD: \"confluent(r) ==> diamond(r^*)\"\nby (simp add: confluent_def)\n\nlemma strip_confluent: \"strip(r) ==> confluent(r)\"\napply (unfold strip_def confluent_def diamond_def)\napply (drule commute_rtrancl)\napply (simp_all add: rtrancl_field)\ndone\n\nlemma commute_Un: \"[| commute(r,t); commute(s,t) |] ==> commute(r \\<union> s, t)\"\n  unfolding commute_def square_def by blast\n\nlemma diamond_Un:\n     \"[| diamond(r); diamond(s); commute(r, s) |] ==> diamond(r \\<union> s)\"\n  unfolding diamond_def by (blast intro: commute_Un commute_sym)\n\nlemma diamond_confluent:\n    \"diamond(r) ==> confluent(r)\"\napply (unfold diamond_def confluent_def)\napply (erule commute_rtrancl, simp)\ndone\n\nlemma confluent_Un:\n \"[| confluent(r); confluent(s); commute(r^*, s^*);\n     relation(r); relation(s) |] ==> confluent(r \\<union> s)\"\napply (unfold confluent_def)\napply (rule rtrancl_Un_rtrancl [THEN subst], auto)\napply (blast dest: diamond_Un intro: diamond_confluent [THEN confluentD])\ndone\n\n\nlemma diamond_to_confluence:\n     \"[| diamond(r); s \\<subseteq> r; r<= s^* |] ==> confluent(s)\"\napply (drule rtrancl_subset [symmetric], assumption)\napply (simp_all add: confluent_def)\napply (blast intro: diamond_confluent [THEN confluentD])\ndone\n\n\n(*** Church_Rosser ***)\n\nlemma Church_Rosser1:\n     \"Church_Rosser(r) ==> confluent(r)\"\napply (unfold confluent_def Church_Rosser_def square_def\n              commute_def diamond_def, auto)\napply (drule converseI)\napply (simp (no_asm_use) add: rtrancl_converse [symmetric])\napply (drule_tac x = b in spec)\napply (drule_tac x1 = c in spec [THEN mp])\napply (rule_tac b = a in rtrancl_trans)\napply (blast intro: rtrancl_mono [THEN subsetD])+\ndone\n\n\nlemma Church_Rosser2:\n     \"confluent(r) ==> Church_Rosser(r)\"\napply (unfold confluent_def Church_Rosser_def square_def\n              commute_def diamond_def, auto)\napply (frule fieldI1)\napply (simp add: rtrancl_field)\napply (erule rtrancl_induct, auto)\napply (blast intro: rtrancl_refl)\napply (blast del: rtrancl_refl intro: r_into_rtrancl rtrancl_trans)+\ndone\n\n\nlemma Church_Rosser: \"Church_Rosser(r) \\<longleftrightarrow> confluent(r)\"\n  by (blast intro: Church_Rosser1 Church_Rosser2)\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/Commutation.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467801752451, "lm_q2_score": 0.7981867825403177, "lm_q1q2_score": 0.7017233398487588}}
{"text": "theory Exercise3\n  imports 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\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 rel_impl_star: \"r x y \\<Longrightarrow> star r x y\"\n  by (metis star.simps)\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\ntheorem star'_impl_star: \"star' r x y \\<Longrightarrow> star r x y\"\n  apply (induction rule: star'.induct)\n   apply (rule star.refl)\n  apply (metis star.simps star_trans)\n  done\n\nlemma rel_impl_star': \"r x y \\<Longrightarrow> star' r x y\"\n  by (metis star'.refl' star'.step')\n\n(* I couldn't figure out how to get these in place with \"rule[of foo]\",\n   but I saw others just did this lemma directly, so whatever. *)\nlemma star'_transpos_star_step: \"star' r y z \\<Longrightarrow> r x y \\<Longrightarrow> star' r x z\"\n  apply (induction rule: star'.induct)\n   apply (rule rel_impl_star')\n   apply simp\n  apply (metis 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 (rule star'_transpos_star_step)\n   apply simp_all\n  done\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/ch4/Exercise3.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467738423874, "lm_q2_score": 0.7981867873410141, "lm_q1q2_score": 0.7017233390144723}}
{"text": "theory Example_B\n  imports \"../Classifying_Markov_Chain_States\"\nbegin\n\nsection \\<open>Example B\\<close> text_raw \\<open>\\label{ex:B}\\<close>\n\ntext \\<open>\n\nWe now formalize the following Markov chain:\n\n\\begin{center}\n\\begin{tikzpicture}[thick]\n\n  \\begin{scope} [rotate = 45]\n    \\path [fill, color = gray!30] (7.5, -6) ellipse(3 and 1) ;\n  \\end{scope}\n\n  \\node (bot2)  at (7, -0.5) {} ;\n  \\node[draw, circle] (1) at ( 8, -0.5) {$0$} ;\n  \\node[draw, circle] (2) at ( 9,  0.5) {$1$} ;\n  \\node[draw, circle] (3) at (10,  1.5) {$2$} ;\n  \\node (inft) at (10.7, 2.6) {} ;\n  \\node (infb) at (11,   2) {} ;\n\n  \\node (inf1) at (10.5, 2) {} ;\n  \\node (inf2) at (11.5, 3) {} ;\n\n  \\path[->, >=latex]\n    (bot2) edge (1)\n    (1)    edge [loop below]   node [right] {$\\frac{2}{3}$} (1)\n           edge [bend left=30] node [above] {$\\frac{1}{3}$} (2)\n    (2)    edge [bend left=30] node [below] {$\\frac{2}{3}$} (1)\n           edge [bend left=30] node [above] {$\\frac{1}{3}$} (3)\n    (3)    edge [bend left=30] node [below] {$\\frac{2}{3}$} (2)\n           edge [bend left=30] node [above] {} (inft)\n    (infb)  edge [bend left=30] node [above] {} (3) ;\n\n  \\path (inf1) edge [loosely dotted] (inf2) ;\n\n\\end{tikzpicture}\n\\end{center}\n\nAs state space we have the set of natural numbers, the transition function @{term tau} has three\ncases:\n\n\\<close>\n\ndefinition K :: \"nat \\<Rightarrow> nat pmf\" where\n  \"K x = map_pmf (\\<lambda>True \\<Rightarrow> x + 1 | False \\<Rightarrow> x - 1) (bernoulli_pmf (1/3))\"\n\ntext \\<open>For the special case when @{term \"x = (0::nat)\"} we have @{term \"x - 1 = (0::nat)\"} and hence\n@{term \"tau 0 0 = 2 / 3\"}.\\<close>\n\ntext \\<open>We pack this transition function into a discrete Markov kernel.\\<close>\n\ntext \\<open>We call the locale of the Markov chain \\<open>B\\<close>, hence all constants and theorems\n  from this Markov chain get a \\<open>B\\<close> prefix.\\<close>\n\ninterpretation B: MC_syntax K .\n\nsubsection \\<open>Enabled, accessible and communicating states\\<close>\n\ntext \\<open>For each step the predecessor and the successor are enabled (in the @{term 0} case, the\npredecessor is again @{term 0}. Hence every state is accessible from everywhere and every states is\ncommunicating with each other state. Finally we know that the state space is an essential class.\\<close>\n\nlemma B_E_eq: \"set_pmf (K x) = {x - 1, x + 1}\"\n  by (auto simp: set_pmf_bernoulli K_def split: bool.split)\n\nlemma B_E_Suc: \"Suc x \\<in> set_pmf (K x)\" \"x \\<in> set_pmf (K (Suc x))\"\n  unfolding B_E_eq by auto\n\nlemma B_accessible[intro]: \"(i, j) \\<in> B.acc\"\nproof (cases i j rule: linorder_le_cases)\n  assume \"i \\<le> j\" then show ?thesis\n    by (induct rule: inc_induct) (auto intro: B_E_Suc converse_rtrancl_into_rtrancl)\nnext\n  assume \"j \\<le> i\" then show ?thesis\n    by (induct rule: dec_induct) (auto intro: B_E_Suc converse_rtrancl_into_rtrancl)\nqed\n\nlemma B_communicating[intro]: \"(i, j) \\<in> B.communicating\"\n  by (simp add: B.communicating_def B_accessible)\n\nlemma B_essential: \"B.essential_class UNIV\"\n  by (rule B.essential_classI2) auto\n\nsubsection \\<open>B is aperiodic\\<close>\n\nlemma B_aperiodic: \"B.aperiodic UNIV\"\n  unfolding B.aperiodic_def\nproof safe\n  have eq: \"\\<And>x'. (if x' = 0 then 1 else 0) = indicator {0} x'\" by auto\n\n  show \"UNIV \\<in> UNIV // B.communicating\"\n    using B_essential by (simp add: B.essential_class_def)\n  then have \"B.period UNIV = Gcd (B.period_set 0)\"\n    by (rule B.period_eq) simp\n  also have \"\\<dots> = 1\"\n    by (rule Gcd_nat_eq_one) (simp add: B.period_set_def B.p_Suc' B.p_0 eq measure_pmf_single pmf_positive_iff K_def set_pmf_bernoulli UNIV_bool)\n  finally show \"B.period UNIV = 1\" .\nqed\n\nsubsection \\<open>The stationary distribution \\<open>N\\<close>\\<close>\n\nabbreviation N :: \"nat pmf\" where\n  \"N \\<equiv> geometric_pmf (1 / 2)\"\n\nlemma stationary_distribution_N: \"B.stationary_distribution N\"\n  unfolding B.stationary_distribution_def\nproof (rule pmf_eqI)\n  fix a show \"pmf N a = pmf (bind_pmf N K) a\"\n    apply (simp add: pmf_bind K_def map_pmf_def)\n    apply (subst integral_measure_pmf[of \"{a - 1, a + 1}\"])\n    apply (auto split: split_indicator_asm nat.splits simp: minus_nat.diff_Suc)\n    done\nqed\n\nsubsection \\<open>Limit behavior and recurrence times\\<close>\n\nlemma limit: \"(B.p i j) \\<longlonglongrightarrow> (1/2)^Suc j\"\nproof -\n  have \"B.p i j \\<longlonglongrightarrow> pmf N j\"\n    by (rule B.stationary_distribution_imp_p_limit[OF B_aperiodic B_essential _ stationary_distribution_N])\n       auto\n  then show ?thesis\n    by (simp add: ac_simps)\nqed\n\nlemma pos_recurrent: \"B.pos_recurrent i\"\n  using B.stationary_distributionD(1)[OF B_essential _ stationary_distribution_N _] by auto\n\nlemma recurrence_time: \"B.U' i i = 2^Suc i\"\nproof -\n  have \"B.stat UNIV = N\"\n    using B.stationary_distributionD(2)[OF B_essential _ stationary_distribution_N _] by simp\n  then have \"2^Suc i = 1 / emeasure (B.stat UNIV) {i}\"\n    apply (simp add: field_simps emeasure_pmf_single pmf_positive)\n    apply (subst divide_ennreal[symmetric])\n    apply (auto simp: ennreal_mult ennreal_power[symmetric])\n    done\n  also have \"\\<dots> = B.U' i i\"\n    unfolding B.stat_def\n    by (subst emeasure_point_measure_finite2)\n       (simp_all add: B.U'_def)\n  finally show ?thesis\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/Evaluation/Markov_Models/ex/Example_B.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.819893340314393, "lm_q2_score": 0.8558511506439708, "lm_q1q2_score": 0.701706658713402}}
{"text": "(*  Title:      HOL/Groups_Big.thy\n    Author:     Tobias Nipkow, Lawrence C Paulson and Markus Wenzel\n                with contributions by Jeremy Avigad\n*)\n\nsection {* Big sum and product over finite (non-empty) sets *}\n\ntheory Groups_Big\nimports Finite_Set\nbegin\n\nsubsection {* Generic monoid operation over a set *}\n\nno_notation times (infixl \"*\" 70)\nno_notation Groups.one (\"1\")\n\nlocale comm_monoid_set = comm_monoid\nbegin\n\ninterpretation comp_fun_commute f\n  by default (simp add: fun_eq_iff left_commute)\n\ninterpretation comp?: comp_fun_commute \"f \\<circ> g\"\n  by (fact comp_comp_fun_commute)\n\ndefinition F :: \"('b \\<Rightarrow> 'a) \\<Rightarrow> 'b set \\<Rightarrow> 'a\"\nwhere\n  eq_fold: \"F g A = Finite_Set.fold (f \\<circ> g) 1 A\"\n\nlemma infinite [simp]:\n  \"\\<not> finite A \\<Longrightarrow> F g A = 1\"\n  by (simp add: eq_fold)\n\nlemma empty [simp]:\n  \"F g {} = 1\"\n  by (simp add: eq_fold)\n\nlemma insert [simp]:\n  assumes \"finite A\" and \"x \\<notin> A\"\n  shows \"F g (insert x A) = g x * F g A\"\n  using assms by (simp add: eq_fold)\n\nlemma remove:\n  assumes \"finite A\" and \"x \\<in> A\"\n  shows \"F g A = g x * F g (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 g (insert x A) = g x * F g (A - {x})\"\n  using assms by (cases \"x \\<in> A\") (simp_all add: remove insert_absorb)\n\nlemma neutral:\n  assumes \"\\<forall>x\\<in>A. g x = 1\"\n  shows \"F g A = 1\"\n  using assms by (induct A rule: infinite_finite_induct) simp_all\n\nlemma neutral_const [simp]:\n  \"F (\\<lambda>_. 1) A = 1\"\n  by (simp add: neutral)\n\nlemma union_inter:\n  assumes \"finite A\" and \"finite B\"\n  shows \"F g (A \\<union> B) * F g (A \\<inter> B) = F g A * F g B\"\n  -- {* The reversed orientation looks more natural, but LOOPS as a simprule! *}\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 commute [of _ \"g x\"] assoc left_commute)\nqed\n\ncorollary union_inter_neutral:\n  assumes \"finite A\" and \"finite B\"\n  and I0: \"\\<forall>x \\<in> A \\<inter> B. g x = 1\"\n  shows \"F g (A \\<union> B) = F g A * F g B\"\n  using assms by (simp add: union_inter [symmetric] neutral)\n\ncorollary union_disjoint:\n  assumes \"finite A\" and \"finite B\"\n  assumes \"A \\<inter> B = {}\"\n  shows \"F g (A \\<union> B) = F g A * F g B\"\n  using assms by (simp add: union_inter_neutral)\n\nlemma union_diff2:\n  assumes \"finite A\" and \"finite B\"\n  shows \"F g (A \\<union> B) = F g (A - B) * F g (B - A) * F g (A \\<inter> B)\"\nproof -\n  have \"A \\<union> B = A - B \\<union> (B - A) \\<union> A \\<inter> B\"\n    by auto\n  with assms show ?thesis by simp (subst union_disjoint, auto)+\nqed\n\nlemma subset_diff:\n  assumes \"B \\<subseteq> A\" and \"finite A\"\n  shows \"F g A = F g (A - B) * F g B\"\nproof -\n  from assms have \"finite (A - B)\" by auto\n  moreover from assms have \"finite B\" by (rule finite_subset)\n  moreover from assms have \"(A - B) \\<inter> B = {}\" by auto\n  ultimately have \"F g (A - B \\<union> B) = F g (A - B) * F g B\" by (rule union_disjoint)\n  moreover from assms have \"A \\<union> B = A\" by auto\n  ultimately show ?thesis by simp\nqed\n\nlemma setdiff_irrelevant:\n  assumes \"finite A\"\n  shows \"F g (A - {x. g x = z}) = F g A\"\n  using assms by (induct A) (simp_all add: insert_Diff_if) \n\nlemma not_neutral_contains_not_neutral:\n  assumes \"F g A \\<noteq> z\"\n  obtains a where \"a \\<in> A\" and \"g a \\<noteq> z\"\nproof -\n  from assms have \"\\<exists>a\\<in>A. g a \\<noteq> z\"\n  proof (induct A rule: infinite_finite_induct)\n    case (insert a A)\n    then show ?case by simp (rule, simp)\n  qed simp_all\n  with that show thesis by blast\nqed\n\n\n\nlemma cong:\n  assumes \"A = B\"\n  assumes g_h: \"\\<And>x. x \\<in> B \\<Longrightarrow> g x = h x\"\n  shows \"F g A = F h B\"\n  using g_h unfolding `A = B`\n  by (induct B rule: infinite_finite_induct) auto\n\nlemma strong_cong [cong]:\n  assumes \"A = B\" \"\\<And>x. x \\<in> B =simp=> g x = h x\"\n  shows \"F (\\<lambda>x. g x) A = F (\\<lambda>x. h x) B\"\n  by (rule cong) (insert assms, simp_all add: simp_implies_def)\n\nlemma reindex_cong:\n  assumes \"inj_on l B\"\n  assumes \"A = l ` B\"\n  assumes \"\\<And>x. x \\<in> B \\<Longrightarrow> g (l x) = h x\"\n  shows \"F g A = F h B\"\n  using assms by (simp add: reindex)\n\nlemma UNION_disjoint:\n  assumes \"finite I\" and \"\\<forall>i\\<in>I. finite (A i)\"\n  and \"\\<forall>i\\<in>I. \\<forall>j\\<in>I. i \\<noteq> j \\<longrightarrow> A i \\<inter> A j = {}\"\n  shows \"F g (UNION I A) = F (\\<lambda>x. F g (A x)) I\"\napply (insert assms)\napply (induct rule: finite_induct)\napply simp\napply atomize\napply (subgoal_tac \"\\<forall>i\\<in>Fa. x \\<noteq> i\")\n prefer 2 apply blast\napply (subgoal_tac \"A x Int UNION Fa A = {}\")\n prefer 2 apply blast\napply (simp add: union_disjoint)\ndone\n\nlemma Union_disjoint:\n  assumes \"\\<forall>A\\<in>C. finite A\" \"\\<forall>A\\<in>C. \\<forall>B\\<in>C. A \\<noteq> B \\<longrightarrow> A \\<inter> B = {}\"\n  shows \"F g (Union C) = (F \\<circ> F) g C\"\nproof cases\n  assume \"finite C\"\n  from UNION_disjoint [OF this assms]\n  show ?thesis by simp\nqed (auto dest: finite_UnionD intro: infinite)\n\nlemma distrib:\n  \"F (\\<lambda>x. g x * h x) A = F g A * F h A\"\n  using assms by (induct A rule: infinite_finite_induct) (simp_all add: assoc commute left_commute)\n\nlemma Sigma:\n  \"finite A \\<Longrightarrow> \\<forall>x\\<in>A. finite (B x) \\<Longrightarrow> F (\\<lambda>x. F (g x) (B x)) A = F (split g) (SIGMA x:A. B x)\"\napply (subst Sigma_def)\napply (subst UNION_disjoint, assumption, simp)\n apply blast\napply (rule cong)\napply rule\napply (simp add: fun_eq_iff)\napply (subst UNION_disjoint, simp, simp)\n apply blast\napply (simp add: comp_def)\ndone\n\nlemma related: \n  assumes Re: \"R 1 1\" \n  and Rop: \"\\<forall>x1 y1 x2 y2. R x1 x2 \\<and> R y1 y2 \\<longrightarrow> R (x1 * y1) (x2 * y2)\" \n  and fS: \"finite S\" and Rfg: \"\\<forall>x\\<in>S. R (h x) (g x)\"\n  shows \"R (F h S) (F g S)\"\n  using fS by (rule finite_subset_induct) (insert assms, auto)\n\nlemma mono_neutral_cong_left:\n  assumes \"finite T\" and \"S \\<subseteq> T\" and \"\\<forall>i \\<in> T - S. h i = 1\"\n  and \"\\<And>x. x \\<in> S \\<Longrightarrow> g x = h x\" shows \"F g S = F h T\"\nproof-\n  have eq: \"T = S \\<union> (T - S)\" using `S \\<subseteq> T` by blast\n  have d: \"S \\<inter> (T - S) = {}\" using `S \\<subseteq> T` by blast\n  from `finite T` `S \\<subseteq> T` have f: \"finite S\" \"finite (T - S)\"\n    by (auto intro: finite_subset)\n  show ?thesis using assms(4)\n    by (simp add: union_disjoint [OF f d, unfolded eq [symmetric]] neutral [OF assms(3)])\nqed\n\nlemma mono_neutral_cong_right:\n  \"\\<lbrakk> finite T; S \\<subseteq> T; \\<forall>i \\<in> T - S. g i = 1; \\<And>x. x \\<in> S \\<Longrightarrow> g x = h x \\<rbrakk>\n   \\<Longrightarrow> F g T = F h S\"\n  by (auto intro!: mono_neutral_cong_left [symmetric])\n\nlemma mono_neutral_left:\n  \"\\<lbrakk> finite T; S \\<subseteq> T; \\<forall>i \\<in> T - S. g i = 1 \\<rbrakk> \\<Longrightarrow> F g S = F g T\"\n  by (blast intro: mono_neutral_cong_left)\n\nlemma mono_neutral_right:\n  \"\\<lbrakk> finite T;  S \\<subseteq> T;  \\<forall>i \\<in> T - S. g i = 1 \\<rbrakk> \\<Longrightarrow> F g T = F g S\"\n  by (blast intro!: mono_neutral_left [symmetric])\n\nlemma reindex_bij_betw: \"bij_betw h S T \\<Longrightarrow> F (\\<lambda>x. g (h x)) S = F g T\"\n  by (auto simp: bij_betw_def reindex)\n\nlemma reindex_bij_witness:\n  assumes witness:\n    \"\\<And>a. a \\<in> S \\<Longrightarrow> i (j a) = a\"\n    \"\\<And>a. a \\<in> S \\<Longrightarrow> j a \\<in> T\"\n    \"\\<And>b. b \\<in> T \\<Longrightarrow> j (i b) = b\"\n    \"\\<And>b. b \\<in> T \\<Longrightarrow> i b \\<in> S\"\n  assumes eq:\n    \"\\<And>a. a \\<in> S \\<Longrightarrow> h (j a) = g a\"\n  shows \"F g S = F h T\"\nproof -\n  have \"bij_betw j S T\"\n    using bij_betw_byWitness[where A=S and f=j and f'=i and A'=T] witness by auto\n  moreover have \"F g S = F (\\<lambda>x. h (j x)) S\"\n    by (intro cong) (auto simp: eq)\n  ultimately show ?thesis\n    by (simp add: reindex_bij_betw)\nqed\n\nlemma reindex_bij_betw_not_neutral:\n  assumes fin: \"finite S'\" \"finite T'\"\n  assumes bij: \"bij_betw h (S - S') (T - T')\"\n  assumes nn:\n    \"\\<And>a. a \\<in> S' \\<Longrightarrow> g (h a) = z\"\n    \"\\<And>b. b \\<in> T' \\<Longrightarrow> g b = z\"\n  shows \"F (\\<lambda>x. g (h x)) S = F g T\"\nproof -\n  have [simp]: \"finite S \\<longleftrightarrow> finite T\"\n    using bij_betw_finite[OF bij] fin by auto\n\n  show ?thesis\n  proof cases\n    assume \"finite S\"\n    with nn have \"F (\\<lambda>x. g (h x)) S = F (\\<lambda>x. g (h x)) (S - S')\"\n      by (intro mono_neutral_cong_right) auto\n    also have \"\\<dots> = F g (T - T')\"\n      using bij by (rule reindex_bij_betw)\n    also have \"\\<dots> = F g T\"\n      using nn `finite S` by (intro mono_neutral_cong_left) auto\n    finally show ?thesis .\n  qed simp\nqed\n\nlemma reindex_nontrivial:\n  assumes \"finite A\"\n  and nz: \"\\<And>x y. x \\<in> A \\<Longrightarrow> y \\<in> A \\<Longrightarrow> x \\<noteq> y \\<Longrightarrow> h x = h y \\<Longrightarrow> g (h x) = 1\"\n  shows \"F g (h ` A) = F (g \\<circ> h) A\"\nproof (subst reindex_bij_betw_not_neutral [symmetric])\n  show \"bij_betw h (A - {x \\<in> A. (g \\<circ> h) x = 1}) (h ` A - h ` {x \\<in> A. (g \\<circ> h) x = 1})\"\n    using nz by (auto intro!: inj_onI simp: bij_betw_def)\nqed (insert `finite A`, auto)\n\nlemma reindex_bij_witness_not_neutral:\n  assumes fin: \"finite S'\" \"finite T'\"\n  assumes witness:\n    \"\\<And>a. a \\<in> S - S' \\<Longrightarrow> i (j a) = a\"\n    \"\\<And>a. a \\<in> S - S' \\<Longrightarrow> j a \\<in> T - T'\"\n    \"\\<And>b. b \\<in> T - T' \\<Longrightarrow> j (i b) = b\"\n    \"\\<And>b. b \\<in> T - T' \\<Longrightarrow> i b \\<in> S - S'\"\n  assumes nn:\n    \"\\<And>a. a \\<in> S' \\<Longrightarrow> g a = z\"\n    \"\\<And>b. b \\<in> T' \\<Longrightarrow> h b = z\"\n  assumes eq:\n    \"\\<And>a. a \\<in> S \\<Longrightarrow> h (j a) = g a\"\n  shows \"F g S = F h T\"\nproof -\n  have bij: \"bij_betw j (S - (S' \\<inter> S)) (T - (T' \\<inter> T))\"\n    using witness by (intro bij_betw_byWitness[where f'=i]) auto\n  have F_eq: \"F g S = F (\\<lambda>x. h (j x)) S\"\n    by (intro cong) (auto simp: eq)\n  show ?thesis\n    unfolding F_eq using fin nn eq\n    by (intro reindex_bij_betw_not_neutral[OF _ _ bij]) auto\nqed\n\nlemma delta: \n  assumes fS: \"finite S\"\n  shows \"F (\\<lambda>k. if k = a then b k else 1) S = (if a \\<in> S then b a else 1)\"\nproof-\n  let ?f = \"(\\<lambda>k. if k=a then b k else 1)\"\n  { assume a: \"a \\<notin> S\"\n    hence \"\\<forall>k\\<in>S. ?f k = 1\" by simp\n    hence ?thesis  using a 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 \"F ?f S = F ?f ?A * F ?f ?B\"\n      using union_disjoint [OF fAB dj, of ?f, unfolded eq [symmetric]]\n      by simp\n    then have ?thesis using a by simp }\n  ultimately show ?thesis by blast\nqed\n\nlemma delta': \n  assumes fS: \"finite S\"\n  shows \"F (\\<lambda>k. if a = k then b k else 1) S = (if a \\<in> S then b a else 1)\"\n  using delta [OF fS, of a b, symmetric] by (auto intro: cong)\n\nlemma If_cases:\n  fixes P :: \"'b \\<Rightarrow> bool\" and g h :: \"'b \\<Rightarrow> 'a\"\n  assumes fA: \"finite A\"\n  shows \"F (\\<lambda>x. if P x then h x else g x) A =\n    F h (A \\<inter> {x. P x}) * F g (A \\<inter> - {x. P x})\"\nproof -\n  have a: \"A = A \\<inter> {x. P x} \\<union> A \\<inter> -{x. P x}\" \n          \"(A \\<inter> {x. P x}) \\<inter> (A \\<inter> -{x. P x}) = {}\" \n    by blast+\n  from fA \n  have f: \"finite (A \\<inter> {x. P x})\" \"finite (A \\<inter> -{x. P x})\" by auto\n  let ?g = \"\\<lambda>x. if P x then h x else g x\"\n  from union_disjoint [OF f a(2), of ?g] a(1)\n  show ?thesis\n    by (subst (1 2) cong) simp_all\nqed\n\nlemma cartesian_product:\n   \"F (\\<lambda>x. F (g x) B) A = F (split g) (A <*> B)\"\napply (rule sym)\napply (cases \"finite A\") \n apply (cases \"finite B\") \n  apply (simp add: Sigma)\n apply (cases \"A={}\", simp)\n apply simp\napply (auto intro: infinite dest: finite_cartesian_productD2)\napply (cases \"B = {}\") apply (auto intro: infinite dest: finite_cartesian_productD1)\ndone\n\nlemma inter_restrict:\n  assumes \"finite A\"\n  shows \"F g (A \\<inter> B) = F (\\<lambda>x. if x \\<in> B then g x else 1) A\"\nproof -\n  let ?g = \"\\<lambda>x. if x \\<in> A \\<inter> B then g x else 1\"\n  have \"\\<forall>i\\<in>A - A \\<inter> B. (if i \\<in> A \\<inter> B then g i else 1) = 1\"\n   by simp\n  moreover have \"A \\<inter> B \\<subseteq> A\" by blast\n  ultimately have \"F ?g (A \\<inter> B) = F ?g A\" using `finite A`\n    by (intro mono_neutral_left) auto\n  then show ?thesis by simp\nqed\n\nlemma inter_filter:\n  \"finite A \\<Longrightarrow> F g {x \\<in> A. P x} = F (\\<lambda>x. if P x then g x else 1) A\"\n  by (simp add: inter_restrict [symmetric, of A \"{x. P x}\" g, simplified mem_Collect_eq] Int_def)\n\nlemma Union_comp:\n  assumes \"\\<forall>A \\<in> B. finite A\"\n    and \"\\<And>A1 A2 x. A1 \\<in> B \\<Longrightarrow> A2 \\<in> B  \\<Longrightarrow> A1 \\<noteq> A2 \\<Longrightarrow> x \\<in> A1 \\<Longrightarrow> x \\<in> A2 \\<Longrightarrow> g x = 1\"\n  shows \"F g (\\<Union>B) = (F \\<circ> F) g B\"\nusing assms proof (induct B rule: infinite_finite_induct)\n  case (infinite A)\n  then have \"\\<not> finite (\\<Union>A)\" by (blast dest: finite_UnionD)\n  with infinite show ?case by simp\nnext\n  case empty then show ?case by simp\nnext\n  case (insert A B)\n  then have \"finite A\" \"finite B\" \"finite (\\<Union>B)\" \"A \\<notin> B\"\n    and \"\\<forall>x\\<in>A \\<inter> \\<Union>B. g x = 1\"\n    and H: \"F g (\\<Union>B) = (F o F) g B\" by auto\n  then have \"F g (A \\<union> \\<Union>B) = F g A * F g (\\<Union>B)\"\n    by (simp add: union_inter_neutral)\n  with `finite B` `A \\<notin> B` show ?case\n    by (simp add: H)\nqed\n\nlemma commute:\n  \"F (\\<lambda>i. F (g i) B) A = F (\\<lambda>j. F (\\<lambda>i. g i j) A) B\"\n  unfolding cartesian_product\n  by (rule reindex_bij_witness [where i = \"\\<lambda>(i, j). (j, i)\" and j = \"\\<lambda>(i, j). (j, i)\"]) auto\n\nlemma commute_restrict:\n  \"finite A \\<Longrightarrow> finite B \\<Longrightarrow>\n    F (\\<lambda>x. F (g x) {y. y \\<in> B \\<and> R x y}) A = F (\\<lambda>y. F (\\<lambda>x. g x y) {x. x \\<in> A \\<and> R x y}) B\"\n  by (simp add: inter_filter) (rule commute)\n\nlemma Plus:\n  fixes A :: \"'b set\" and B :: \"'c set\"\n  assumes fin: \"finite A\" \"finite B\"\n  shows \"F g (A <+> B) = F (g \\<circ> Inl) A * F (g \\<circ> Inr) B\"\nproof -\n  have \"A <+> B = Inl ` A \\<union> Inr ` B\" by auto\n  moreover from fin have \"finite (Inl ` A :: ('b + 'c) set)\" \"finite (Inr ` B :: ('b + 'c) set)\"\n    by auto\n  moreover have \"Inl ` A \\<inter> Inr ` B = ({} :: ('b + 'c) set)\" by auto\n  moreover have \"inj_on (Inl :: 'b \\<Rightarrow> 'b + 'c) A\" \"inj_on (Inr :: 'c \\<Rightarrow> 'b + 'c) B\"\n    by (auto intro: inj_onI)\n  ultimately show ?thesis using fin\n    by (simp add: union_disjoint reindex)\nqed\n\nlemma same_carrier:\n  assumes \"finite C\"\n  assumes subset: \"A \\<subseteq> C\" \"B \\<subseteq> C\"\n  assumes trivial: \"\\<And>a. a \\<in> C - A \\<Longrightarrow> g a = 1\" \"\\<And>b. b \\<in> C - B \\<Longrightarrow> h b = 1\"\n  shows \"F g A = F h B \\<longleftrightarrow> F g C = F h C\"\nproof -\n  from `finite C` subset have\n    \"finite A\" and \"finite B\" and \"finite (C - A)\" and \"finite (C - B)\"\n    by (auto elim: finite_subset)\n  from subset have [simp]: \"A - (C - A) = A\" by auto\n  from subset have [simp]: \"B - (C - B) = B\" by auto\n  from subset have \"C = A \\<union> (C - A)\" by auto\n  then have \"F g C = F g (A \\<union> (C - A))\" by simp\n  also have \"\\<dots> = F g (A - (C - A)) * F g (C - A - A) * F g (A \\<inter> (C - A))\"\n    using `finite A` `finite (C - A)` by (simp only: union_diff2)\n  finally have P: \"F g C = F g A\" using trivial by simp\n  from subset have \"C = B \\<union> (C - B)\" by auto\n  then have \"F h C = F h (B \\<union> (C - B))\" by simp\n  also have \"\\<dots> = F h (B - (C - B)) * F h (C - B - B) * F h (B \\<inter> (C - B))\"\n    using `finite B` `finite (C - B)` by (simp only: union_diff2)\n  finally have Q: \"F h C = F h B\" using trivial by simp\n  from P Q show ?thesis by simp\nqed\n\nlemma same_carrierI:\n  assumes \"finite C\"\n  assumes subset: \"A \\<subseteq> C\" \"B \\<subseteq> C\"\n  assumes trivial: \"\\<And>a. a \\<in> C - A \\<Longrightarrow> g a = 1\" \"\\<And>b. b \\<in> C - B \\<Longrightarrow> h b = 1\"\n  assumes \"F g C = F h C\"\n  shows \"F g A = F h B\"\n  using assms same_carrier [of C A B] by simp\n\nend\n\nnotation times (infixl \"*\" 70)\nnotation Groups.one (\"1\")\n\n\nsubsection {* Generalized summation over a set *}\n\ncontext comm_monoid_add\nbegin\n\ndefinition setsum :: \"('b \\<Rightarrow> 'a) \\<Rightarrow> 'b set \\<Rightarrow> 'a\"\nwhere\n  \"setsum = comm_monoid_set.F plus 0\"\n\nsublocale setsum!: comm_monoid_set plus 0\nwhere\n  \"comm_monoid_set.F plus 0 = setsum\"\nproof -\n  show \"comm_monoid_set plus 0\" ..\n  then interpret setsum!: comm_monoid_set plus 0 .\n  from setsum_def show \"comm_monoid_set.F plus 0 = setsum\" by rule\nqed\n\nabbreviation\n  Setsum (\"\\<Sum>_\" [1000] 999) where\n  \"\\<Sum>A \\<equiv> setsum (%x. x) A\"\n\nend\n\ntext{* Now: lot's of fancy syntax. First, @{term \"setsum (%x. e) A\"} is\nwritten @{text\"\\<Sum>x\\<in>A. e\"}. *}\n\nsyntax\n  \"_setsum\" :: \"pttrn => 'a set => 'b => 'b::comm_monoid_add\"    (\"(3SUM _:_. _)\" [0, 51, 10] 10)\nsyntax (xsymbols)\n  \"_setsum\" :: \"pttrn => 'a set => 'b => 'b::comm_monoid_add\"    (\"(3\\<Sum>_\\<in>_. _)\" [0, 51, 10] 10)\nsyntax (HTML output)\n  \"_setsum\" :: \"pttrn => 'a set => 'b => 'b::comm_monoid_add\"    (\"(3\\<Sum>_\\<in>_. _)\" [0, 51, 10] 10)\n\ntranslations -- {* Beware of argument permutation! *}\n  \"SUM i:A. b\" == \"CONST setsum (%i. b) A\"\n  \"\\<Sum>i\\<in>A. b\" == \"CONST setsum (%i. b) A\"\n\ntext{* Instead of @{term\"\\<Sum>x\\<in>{x. P}. e\"} we introduce the shorter\n @{text\"\\<Sum>x|P. e\"}. *}\n\nsyntax\n  \"_qsetsum\" :: \"pttrn \\<Rightarrow> bool \\<Rightarrow> 'a \\<Rightarrow> 'a\" (\"(3SUM _ |/ _./ _)\" [0,0,10] 10)\nsyntax (xsymbols)\n  \"_qsetsum\" :: \"pttrn \\<Rightarrow> bool \\<Rightarrow> 'a \\<Rightarrow> 'a\" (\"(3\\<Sum>_ | (_)./ _)\" [0,0,10] 10)\nsyntax (HTML output)\n  \"_qsetsum\" :: \"pttrn \\<Rightarrow> bool \\<Rightarrow> 'a \\<Rightarrow> 'a\" (\"(3\\<Sum>_ | (_)./ _)\" [0,0,10] 10)\n\ntranslations\n  \"SUM x|P. t\" => \"CONST setsum (%x. t) {x. P}\"\n  \"\\<Sum>x|P. t\" => \"CONST setsum (%x. t) {x. P}\"\n\nprint_translation {*\nlet\n  fun setsum_tr' [Abs (x, Tx, t), Const (@{const_syntax Collect}, _) $ Abs (y, Ty, P)] =\n        if x <> y then raise Match\n        else\n          let\n            val x' = Syntax_Trans.mark_bound_body (x, Tx);\n            val t' = subst_bound (x', t);\n            val P' = subst_bound (x', P);\n          in\n            Syntax.const @{syntax_const \"_qsetsum\"} $ Syntax_Trans.mark_bound_abs (x, Tx) $ P' $ t'\n          end\n    | setsum_tr' _ = raise Match;\nin [(@{const_syntax setsum}, K setsum_tr')] end\n*}\n\ntext {* TODO generalization candidates *}\n\nlemma setsum_image_gen:\n  assumes fS: \"finite S\"\n  shows \"setsum g S = setsum (\\<lambda>y. setsum g {x. x \\<in> S \\<and> f x = y}) (f ` S)\"\nproof-\n  { fix x assume \"x \\<in> S\" then have \"{y. y\\<in> f`S \\<and> f x = y} = {f x}\" by auto }\n  hence \"setsum g S = setsum (\\<lambda>x. setsum (\\<lambda>y. g x) {y. y\\<in> f`S \\<and> f x = y}) S\"\n    by simp\n  also have \"\\<dots> = setsum (\\<lambda>y. setsum g {x. x \\<in> S \\<and> f x = y}) (f ` S)\"\n    by (rule setsum.commute_restrict [OF fS finite_imageI [OF fS]])\n  finally show ?thesis .\nqed\n\n\nsubsubsection {* Properties in more restricted classes of structures *}\n\nlemma setsum_Un: \"finite A ==> finite B ==>\n  (setsum f (A Un B) :: 'a :: ab_group_add) =\n   setsum f A + setsum f B - setsum f (A Int B)\"\nby (subst setsum.union_inter [symmetric], auto simp add: algebra_simps)\n\nlemma setsum_Un2:\n  assumes \"finite (A \\<union> B)\"\n  shows \"setsum f (A \\<union> B) = setsum f (A - B) + setsum f (B - A) + setsum f (A \\<inter> B)\"\nproof -\n  have \"A \\<union> B = A - B \\<union> (B - A) \\<union> A \\<inter> B\"\n    by auto\n  with assms show ?thesis by simp (subst setsum.union_disjoint, auto)+\nqed\n\nlemma setsum_diff1: \"finite A \\<Longrightarrow>\n  (setsum f (A - {a}) :: ('a::ab_group_add)) =\n  (if a:A then setsum f A - f a else setsum f A)\"\nby (erule finite_induct) (auto simp add: insert_Diff_if)\n\nlemma setsum_diff:\n  assumes le: \"finite A\" \"B \\<subseteq> A\"\n  shows \"setsum f (A - B) = setsum f A - ((setsum f B)::('a::ab_group_add))\"\nproof -\n  from le have finiteB: \"finite B\" using finite_subset by auto\n  show ?thesis using finiteB le\n  proof induct\n    case empty\n    thus ?case by auto\n  next\n    case (insert x F)\n    thus ?case using le finiteB \n      by (simp add: Diff_insert[where a=x and B=F] setsum_diff1 insert_absorb)\n  qed\nqed\n\nlemma setsum_mono:\n  assumes le: \"\\<And>i. i\\<in>K \\<Longrightarrow> f (i::'a) \\<le> ((g i)::('b::{comm_monoid_add, ordered_ab_semigroup_add}))\"\n  shows \"(\\<Sum>i\\<in>K. f i) \\<le> (\\<Sum>i\\<in>K. g i)\"\nproof (cases \"finite K\")\n  case True\n  thus ?thesis using le\n  proof induct\n    case empty\n    thus ?case by simp\n  next\n    case insert\n    thus ?case using add_mono by fastforce\n  qed\nnext\n  case False then show ?thesis by simp\nqed\n\nlemma setsum_strict_mono:\n  fixes f :: \"'a \\<Rightarrow> 'b::{ordered_cancel_ab_semigroup_add,comm_monoid_add}\"\n  assumes \"finite A\"  \"A \\<noteq> {}\"\n    and \"!!x. x:A \\<Longrightarrow> f x < g x\"\n  shows \"setsum f A < setsum g A\"\n  using assms\nproof (induct rule: finite_ne_induct)\n  case singleton thus ?case by simp\nnext\n  case insert thus ?case by (auto simp: add_strict_mono)\nqed\n\nlemma setsum_strict_mono_ex1:\nfixes f :: \"'a \\<Rightarrow> 'b::{comm_monoid_add, ordered_cancel_ab_semigroup_add}\"\nassumes \"finite A\" and \"ALL x:A. f x \\<le> g x\" and \"EX a:A. f a < g a\"\nshows \"setsum f A < setsum g A\"\nproof-\n  from assms(3) obtain a where a: \"a:A\" \"f a < g a\" by blast\n  have \"setsum f A = setsum f ((A-{a}) \\<union> {a})\"\n    by(simp add:insert_absorb[OF `a:A`])\n  also have \"\\<dots> = setsum f (A-{a}) + setsum f {a}\"\n    using `finite A` by(subst setsum.union_disjoint) auto\n  also have \"setsum f (A-{a}) \\<le> setsum g (A-{a})\"\n    by(rule setsum_mono)(simp add: assms(2))\n  also have \"setsum f {a} < setsum g {a}\" using a by simp\n  also have \"setsum g (A - {a}) + setsum g {a} = setsum g((A-{a}) \\<union> {a})\"\n    using `finite A` by(subst setsum.union_disjoint[symmetric]) auto\n  also have \"\\<dots> = setsum g A\" by(simp add:insert_absorb[OF `a:A`])\n  finally show ?thesis by (auto simp add: add_right_mono add_strict_left_mono)\nqed\n\nlemma setsum_negf:\n  \"setsum (%x. - (f x)::'a::ab_group_add) A = - setsum f A\"\nproof (cases \"finite A\")\n  case True thus ?thesis by (induct set: finite) auto\nnext\n  case False thus ?thesis by simp\nqed\n\nlemma setsum_subtractf:\n  \"setsum (%x. ((f x)::'a::ab_group_add) - g x) A =\n    setsum f A - setsum g A\"\n  using setsum.distrib [of f \"- g\" A] by (simp add: setsum_negf)\n\nlemma setsum_nonneg:\n  assumes nn: \"\\<forall>x\\<in>A. (0::'a::{ordered_ab_semigroup_add,comm_monoid_add}) \\<le> f x\"\n  shows \"0 \\<le> setsum f A\"\nproof (cases \"finite A\")\n  case True thus ?thesis using nn\n  proof induct\n    case empty then show ?case by simp\n  next\n    case (insert x F)\n    then have \"0 + 0 \\<le> f x + setsum f F\" by (blast intro: add_mono)\n    with insert show ?case by simp\n  qed\nnext\n  case False thus ?thesis by simp\nqed\n\nlemma setsum_nonpos:\n  assumes np: \"\\<forall>x\\<in>A. f x \\<le> (0::'a::{ordered_ab_semigroup_add,comm_monoid_add})\"\n  shows \"setsum f A \\<le> 0\"\nproof (cases \"finite A\")\n  case True thus ?thesis using np\n  proof induct\n    case empty then show ?case by simp\n  next\n    case (insert x F)\n    then have \"f x + setsum f F \\<le> 0 + 0\" by (blast intro: add_mono)\n    with insert show ?case by simp\n  qed\nnext\n  case False thus ?thesis by simp\nqed\n\nlemma setsum_nonneg_leq_bound:\n  fixes f :: \"'a \\<Rightarrow> 'b::{ordered_ab_group_add}\"\n  assumes \"finite s\" \"\\<And>i. i \\<in> s \\<Longrightarrow> f i \\<ge> 0\" \"(\\<Sum>i \\<in> s. f i) = B\" \"i \\<in> s\"\n  shows \"f i \\<le> B\"\nproof -\n  have \"0 \\<le> (\\<Sum> i \\<in> s - {i}. f i)\" and \"0 \\<le> f i\"\n    using assms by (auto intro!: setsum_nonneg)\n  moreover\n  have \"(\\<Sum> i \\<in> s - {i}. f i) + f i = B\"\n    using assms by (simp add: setsum_diff1)\n  ultimately show ?thesis by auto\nqed\n\nlemma setsum_nonneg_0:\n  fixes f :: \"'a \\<Rightarrow> 'b::{ordered_ab_group_add}\"\n  assumes \"finite s\" and pos: \"\\<And> i. i \\<in> s \\<Longrightarrow> f i \\<ge> 0\"\n  and \"(\\<Sum> i \\<in> s. f i) = 0\" and i: \"i \\<in> s\"\n  shows \"f i = 0\"\n  using setsum_nonneg_leq_bound[OF assms] pos[OF i] by auto\n\nlemma setsum_mono2:\nfixes f :: \"'a \\<Rightarrow> 'b :: ordered_comm_monoid_add\"\nassumes fin: \"finite B\" and sub: \"A \\<subseteq> B\" and nn: \"\\<And>b. b \\<in> B-A \\<Longrightarrow> 0 \\<le> f b\"\nshows \"setsum f A \\<le> setsum f B\"\nproof -\n  have \"setsum f A \\<le> setsum f A + setsum f (B-A)\"\n    by(simp add: add_increasing2[OF setsum_nonneg] nn Ball_def)\n  also have \"\\<dots> = setsum f (A \\<union> (B-A))\" using fin finite_subset[OF sub fin]\n    by (simp add: setsum.union_disjoint del:Un_Diff_cancel)\n  also have \"A \\<union> (B-A) = B\" using sub by blast\n  finally show ?thesis .\nqed\n\nlemma setsum_le_included:\n  fixes f :: \"'a \\<Rightarrow> 'b::ordered_comm_monoid_add\"\n  assumes \"finite s\" \"finite t\"\n  and \"\\<forall>y\\<in>t. 0 \\<le> g y\" \"(\\<forall>x\\<in>s. \\<exists>y\\<in>t. i y = x \\<and> f x \\<le> g y)\"\n  shows \"setsum f s \\<le> setsum g t\"\nproof -\n  have \"setsum f s \\<le> setsum (\\<lambda>y. setsum g {x. x\\<in>t \\<and> i x = y}) s\"\n  proof (rule setsum_mono)\n    fix y assume \"y \\<in> s\"\n    with assms obtain z where z: \"z \\<in> t\" \"y = i z\" \"f y \\<le> g z\" by auto\n    with assms show \"f y \\<le> setsum g {x \\<in> t. i x = y}\" (is \"?A y \\<le> ?B y\")\n      using order_trans[of \"?A (i z)\" \"setsum g {z}\" \"?B (i z)\", intro]\n      by (auto intro!: setsum_mono2)\n  qed\n  also have \"... \\<le> setsum (\\<lambda>y. setsum g {x. x\\<in>t \\<and> i x = y}) (i ` t)\"\n    using assms(2-4) by (auto intro!: setsum_mono2 setsum_nonneg)\n  also have \"... \\<le> setsum g t\"\n    using assms by (auto simp: setsum_image_gen[symmetric])\n  finally show ?thesis .\nqed\n\nlemma setsum_mono3: \"finite B ==> A <= B ==> \n    ALL x: B - A. \n      0 <= ((f x)::'a::{comm_monoid_add,ordered_ab_semigroup_add}) ==>\n        setsum f A <= setsum f B\"\n  apply (subgoal_tac \"setsum f B = setsum f A + setsum f (B - A)\")\n  apply (erule ssubst)\n  apply (subgoal_tac \"setsum f A + 0 <= setsum f A + setsum f (B - A)\")\n  apply simp\n  apply (rule add_left_mono)\n  apply (erule setsum_nonneg)\n  apply (subst setsum.union_disjoint [THEN sym])\n  apply (erule finite_subset, assumption)\n  apply (rule finite_subset)\n  prefer 2\n  apply assumption\n  apply (auto simp add: sup_absorb2)\ndone\n\nlemma setsum_right_distrib: \n  fixes f :: \"'a => ('b::semiring_0)\"\n  shows \"r * setsum f A = setsum (%n. r * f n) A\"\nproof (cases \"finite A\")\n  case True\n  thus ?thesis\n  proof induct\n    case empty thus ?case by simp\n  next\n    case (insert x A) thus ?case by (simp add: distrib_left)\n  qed\nnext\n  case False thus ?thesis by simp\nqed\n\nlemma setsum_left_distrib:\n  \"setsum f A * (r::'a::semiring_0) = (\\<Sum>n\\<in>A. f n * r)\"\nproof (cases \"finite A\")\n  case True\n  then show ?thesis\n  proof induct\n    case empty thus ?case by simp\n  next\n    case (insert x A) thus ?case by (simp add: distrib_right)\n  qed\nnext\n  case False thus ?thesis by simp\nqed\n\nlemma setsum_divide_distrib:\n  \"setsum f A / (r::'a::field) = (\\<Sum>n\\<in>A. f n / r)\"\nproof (cases \"finite A\")\n  case True\n  then show ?thesis\n  proof induct\n    case empty thus ?case by simp\n  next\n    case (insert x A) thus ?case by (simp add: add_divide_distrib)\n  qed\nnext\n  case False thus ?thesis by simp\nqed\n\nlemma setsum_abs[iff]: \n  fixes f :: \"'a => ('b::ordered_ab_group_add_abs)\"\n  shows \"abs (setsum f A) \\<le> setsum (%i. abs(f i)) A\"\nproof (cases \"finite A\")\n  case True\n  thus ?thesis\n  proof induct\n    case empty thus ?case by simp\n  next\n    case (insert x A)\n    thus ?case by (auto intro: abs_triangle_ineq order_trans)\n  qed\nnext\n  case False thus ?thesis by simp\nqed\n\nlemma setsum_abs_ge_zero[iff]: \n  fixes f :: \"'a => ('b::ordered_ab_group_add_abs)\"\n  shows \"0 \\<le> setsum (%i. abs(f i)) A\"\nproof (cases \"finite A\")\n  case True\n  thus ?thesis\n  proof induct\n    case empty thus ?case by simp\n  next\n    case (insert x A) thus ?case by auto\n  qed\nnext\n  case False thus ?thesis by simp\nqed\n\nlemma abs_setsum_abs[simp]: \n  fixes f :: \"'a => ('b::ordered_ab_group_add_abs)\"\n  shows \"abs (\\<Sum>a\\<in>A. abs(f a)) = (\\<Sum>a\\<in>A. abs(f a))\"\nproof (cases \"finite A\")\n  case True\n  thus ?thesis\n  proof induct\n    case empty thus ?case by simp\n  next\n    case (insert a A)\n    hence \"\\<bar>\\<Sum>a\\<in>insert a A. \\<bar>f a\\<bar>\\<bar> = \\<bar>\\<bar>f a\\<bar> + (\\<Sum>a\\<in>A. \\<bar>f a\\<bar>)\\<bar>\" by simp\n    also have \"\\<dots> = \\<bar>\\<bar>f a\\<bar> + \\<bar>\\<Sum>a\\<in>A. \\<bar>f a\\<bar>\\<bar>\\<bar>\"  using insert by simp\n    also have \"\\<dots> = \\<bar>f a\\<bar> + \\<bar>\\<Sum>a\\<in>A. \\<bar>f a\\<bar>\\<bar>\"\n      by (simp del: abs_of_nonneg)\n    also have \"\\<dots> = (\\<Sum>a\\<in>insert a A. \\<bar>f a\\<bar>)\" using insert by simp\n    finally show ?case .\n  qed\nnext\n  case False thus ?thesis by simp\nqed\n\nlemma setsum_diff1_ring: assumes \"finite A\" \"a \\<in> A\"\n  shows \"setsum f (A - {a}) = setsum f A - (f a::'a::ring)\"\n  unfolding setsum.remove [OF assms] by auto\n\nlemma setsum_product:\n  fixes f :: \"'a => ('b::semiring_0)\"\n  shows \"setsum f A * setsum g B = (\\<Sum>i\\<in>A. \\<Sum>j\\<in>B. f i * g j)\"\n  by (simp add: setsum_right_distrib setsum_left_distrib) (rule setsum.commute)\n\nlemma setsum_mult_setsum_if_inj:\nfixes f :: \"'a => ('b::semiring_0)\"\nshows \"inj_on (%(a,b). f a * g b) (A \\<times> B) ==>\n  setsum f A * setsum g B = setsum id {f a * g b|a b. a:A & b:B}\"\nby(auto simp: setsum_product setsum.cartesian_product\n        intro!:  setsum.reindex_cong[symmetric])\n\nlemma setsum_SucD: \"setsum f A = Suc n ==> EX a:A. 0 < f a\"\napply (case_tac \"finite A\")\n prefer 2 apply simp\napply (erule rev_mp)\napply (erule finite_induct, auto)\ndone\n\nlemma setsum_eq_0_iff [simp]:\n  \"finite F ==> (setsum f F = 0) = (ALL a:F. f a = (0::nat))\"\n  by (induct set: finite) auto\n\nlemma setsum_eq_Suc0_iff: \"finite A \\<Longrightarrow>\n  setsum f A = Suc 0 \\<longleftrightarrow> (EX a:A. f a = Suc 0 & (ALL b:A. a\\<noteq>b \\<longrightarrow> f b = 0))\"\napply(erule finite_induct)\napply (auto simp add:add_is_1)\ndone\n\nlemmas setsum_eq_1_iff = setsum_eq_Suc0_iff[simplified One_nat_def[symmetric]]\n\nlemma setsum_Un_nat: \"finite A ==> finite B ==>\n  (setsum f (A Un B) :: nat) = setsum f A + setsum f B - setsum f (A Int B)\"\n  -- {* For the natural numbers, we have subtraction. *}\nby (subst setsum.union_inter [symmetric], auto simp add: algebra_simps)\n\nlemma setsum_diff1_nat: \"(setsum f (A - {a}) :: nat) =\n  (if a:A then setsum f A - f a else setsum f A)\"\napply (case_tac \"finite A\")\n prefer 2 apply simp\napply (erule finite_induct)\n apply (auto simp add: insert_Diff_if)\napply (drule_tac a = a in mk_disjoint_insert, auto)\ndone\n\nlemma setsum_diff_nat: \nassumes \"finite B\" and \"B \\<subseteq> A\"\nshows \"(setsum f (A - B) :: nat) = (setsum f A) - (setsum f B)\"\nusing assms\nproof induct\n  show \"setsum f (A - {}) = (setsum f A) - (setsum f {})\" by simp\nnext\n  fix F x assume finF: \"finite F\" and xnotinF: \"x \\<notin> F\"\n    and xFinA: \"insert x F \\<subseteq> A\"\n    and IH: \"F \\<subseteq> A \\<Longrightarrow> setsum f (A - F) = setsum f A - setsum f F\"\n  from xnotinF xFinA have xinAF: \"x \\<in> (A - F)\" by simp\n  from xinAF have A: \"setsum f ((A - F) - {x}) = setsum f (A - F) - f x\"\n    by (simp add: setsum_diff1_nat)\n  from xFinA have \"F \\<subseteq> A\" by simp\n  with IH have \"setsum f (A - F) = setsum f A - setsum f F\" by simp\n  with A have B: \"setsum f ((A - F) - {x}) = setsum f A - setsum f F - f x\"\n    by simp\n  from xnotinF have \"A - insert x F = (A - F) - {x}\" by auto\n  with B have C: \"setsum f (A - insert x F) = setsum f A - setsum f F - f x\"\n    by simp\n  from finF xnotinF have \"setsum f (insert x F) = setsum f F + f x\" by simp\n  with C have \"setsum f (A - insert x F) = setsum f A - setsum f (insert x F)\"\n    by simp\n  thus \"setsum f (A - insert x F) = setsum f A - setsum f (insert x F)\" by simp\nqed\n\nlemma setsum_comp_morphism:\n  assumes \"h 0 = 0\" and \"\\<And>x y. h (x + y) = h x + h y\"\n  shows \"setsum (h \\<circ> g) A = h (setsum g A)\"\nproof (cases \"finite A\")\n  case False then show ?thesis by (simp add: assms)\nnext\n  case True then show ?thesis by (induct A) (simp_all add: assms)\nqed\n\nlemma (in comm_semiring_1) dvd_setsum:\n  \"(\\<And>a. a \\<in> A \\<Longrightarrow> d dvd f a) \\<Longrightarrow> d dvd setsum f A\"\n  by (induct A rule: infinite_finite_induct) simp_all\n\n\nsubsubsection {* Cardinality as special case of @{const setsum} *}\n\nlemma card_eq_setsum:\n  \"card A = setsum (\\<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 by (simp add: card.eq_fold setsum.eq_fold)\nqed\n\nlemma setsum_constant [simp]:\n  \"(\\<Sum>x \\<in> A. y) = of_nat (card A) * y\"\napply (cases \"finite A\")\napply (erule finite_induct)\napply (auto simp add: algebra_simps)\ndone\n\nlemma setsum_Suc: \"setsum (%x. Suc(f x)) A = setsum f A + card A\"\nusing setsum.distrib[of f \"%_. 1\" A] by(simp)\n\nlemma setsum_bounded:\n  assumes le: \"\\<And>i. i\\<in>A \\<Longrightarrow> f i \\<le> (K::'a::{semiring_1, ordered_ab_semigroup_add})\"\n  shows \"setsum f A \\<le> of_nat (card A) * K\"\nproof (cases \"finite A\")\n  case True\n  thus ?thesis using le setsum_mono[where K=A and g = \"%x. K\"] by simp\nnext\n  case False thus ?thesis by simp\nqed\n\nlemma card_UN_disjoint:\n  assumes \"finite I\" and \"\\<forall>i\\<in>I. finite (A i)\"\n    and \"\\<forall>i\\<in>I. \\<forall>j\\<in>I. i \\<noteq> j \\<longrightarrow> A i \\<inter> A j = {}\"\n  shows \"card (UNION I A) = (\\<Sum>i\\<in>I. card(A i))\"\nproof -\n  have \"(\\<Sum>i\\<in>I. card (A i)) = (\\<Sum>i\\<in>I. \\<Sum>x\\<in>A i. 1)\" by simp\n  with assms show ?thesis by (simp add: card_eq_setsum setsum.UNION_disjoint del: setsum_constant)\nqed\n\nlemma card_Union_disjoint:\n  \"finite C ==> (ALL A:C. finite A) ==>\n   (ALL A:C. ALL B:C. A \\<noteq> B --> A Int B = {})\n   ==> card (Union C) = setsum card C\"\napply (frule card_UN_disjoint [of C id])\napply simp_all\ndone\n\nlemma setsum_multicount_gen:\n  assumes \"finite s\" \"finite t\" \"\\<forall>j\\<in>t. (card {i\\<in>s. R i j} = k j)\"\n  shows \"setsum (\\<lambda>i. (card {j\\<in>t. R i j})) s = setsum k t\" (is \"?l = ?r\")\nproof-\n  have \"?l = setsum (\\<lambda>i. setsum (\\<lambda>x.1) {j\\<in>t. R i j}) s\" by auto\n  also have \"\\<dots> = ?r\" unfolding setsum.commute_restrict [OF assms(1-2)]\n    using assms(3) by auto\n  finally show ?thesis .\nqed\n\nlemma setsum_multicount:\n  assumes \"finite S\" \"finite T\" \"\\<forall>j\\<in>T. (card {i\\<in>S. R i j} = k)\"\n  shows \"setsum (\\<lambda>i. card {j\\<in>T. R i j}) S = k * card T\" (is \"?l = ?r\")\nproof-\n  have \"?l = setsum (\\<lambda>i. k) T\" by (rule setsum_multicount_gen) (auto simp: assms)\n  also have \"\\<dots> = ?r\" by (simp add: mult.commute)\n  finally show ?thesis by auto\nqed\n\nlemma (in ordered_comm_monoid_add) setsum_pos: \n  \"finite I \\<Longrightarrow> I \\<noteq> {} \\<Longrightarrow> (\\<And>i. i \\<in> I \\<Longrightarrow> 0 < f i) \\<Longrightarrow> 0 < setsum f I\"\n  by (induct I rule: finite_ne_induct) (auto intro: add_pos_pos)\n\n\nsubsubsection {* Cardinality of products *}\n\nlemma card_SigmaI [simp]:\n  \"\\<lbrakk> finite A; ALL a:A. finite (B a) \\<rbrakk>\n  \\<Longrightarrow> card (SIGMA x: A. B x) = (\\<Sum>a\\<in>A. card (B a))\"\nby(simp add: card_eq_setsum setsum.Sigma del:setsum_constant)\n\n(*\nlemma SigmaI_insert: \"y \\<notin> A ==>\n  (SIGMA x:(insert y A). B x) = (({y} <*> (B y)) \\<union> (SIGMA x: A. B x))\"\n  by auto\n*)\n\nlemma card_cartesian_product: \"card (A <*> B) = card(A) * card(B)\"\n  by (cases \"finite A \\<and> finite B\")\n    (auto simp add: card_eq_0_iff dest: finite_cartesian_productD1 finite_cartesian_productD2)\n\nlemma card_cartesian_product_singleton:  \"card({x} <*> A) = card(A)\"\nby (simp add: card_cartesian_product)\n\n\nsubsection {* Generalized product over a set *}\n\ncontext comm_monoid_mult\nbegin\n\ndefinition setprod :: \"('b \\<Rightarrow> 'a) \\<Rightarrow> 'b set \\<Rightarrow> 'a\"\nwhere\n  \"setprod = comm_monoid_set.F times 1\"\n\nsublocale setprod!: comm_monoid_set times 1\nwhere\n  \"comm_monoid_set.F times 1 = setprod\"\nproof -\n  show \"comm_monoid_set times 1\" ..\n  then interpret setprod!: comm_monoid_set times 1 .\n  from setprod_def show \"comm_monoid_set.F times 1 = setprod\" by rule\nqed\n\nabbreviation\n  Setprod (\"\\<Prod>_\" [1000] 999) where\n  \"\\<Prod>A \\<equiv> setprod (\\<lambda>x. x) A\"\n\nend\n\nsyntax\n  \"_setprod\" :: \"pttrn => 'a set => 'b => 'b::comm_monoid_mult\"  (\"(3PROD _:_. _)\" [0, 51, 10] 10)\nsyntax (xsymbols)\n  \"_setprod\" :: \"pttrn => 'a set => 'b => 'b::comm_monoid_mult\"  (\"(3\\<Prod>_\\<in>_. _)\" [0, 51, 10] 10)\nsyntax (HTML output)\n  \"_setprod\" :: \"pttrn => 'a set => 'b => 'b::comm_monoid_mult\"  (\"(3\\<Prod>_\\<in>_. _)\" [0, 51, 10] 10)\n\ntranslations -- {* Beware of argument permutation! *}\n  \"PROD i:A. b\" == \"CONST setprod (%i. b) A\" \n  \"\\<Prod>i\\<in>A. b\" == \"CONST setprod (%i. b) A\" \n\ntext{* Instead of @{term\"\\<Prod>x\\<in>{x. P}. e\"} we introduce the shorter\n @{text\"\\<Prod>x|P. e\"}. *}\n\nsyntax\n  \"_qsetprod\" :: \"pttrn \\<Rightarrow> bool \\<Rightarrow> 'a \\<Rightarrow> 'a\" (\"(3PROD _ |/ _./ _)\" [0,0,10] 10)\nsyntax (xsymbols)\n  \"_qsetprod\" :: \"pttrn \\<Rightarrow> bool \\<Rightarrow> 'a \\<Rightarrow> 'a\" (\"(3\\<Prod>_ | (_)./ _)\" [0,0,10] 10)\nsyntax (HTML output)\n  \"_qsetprod\" :: \"pttrn \\<Rightarrow> bool \\<Rightarrow> 'a \\<Rightarrow> 'a\" (\"(3\\<Prod>_ | (_)./ _)\" [0,0,10] 10)\n\ntranslations\n  \"PROD x|P. t\" => \"CONST setprod (%x. t) {x. P}\"\n  \"\\<Prod>x|P. t\" => \"CONST setprod (%x. t) {x. P}\"\n\ncontext comm_monoid_mult\nbegin\n\nlemma setprod_dvd_setprod: \n  \"(\\<And>a. a \\<in> A \\<Longrightarrow> f a dvd g a) \\<Longrightarrow> setprod f A dvd setprod g A\"\nproof (induct A rule: infinite_finite_induct)\n  case infinite then show ?case by (auto intro: dvdI)\nnext\n  case empty then show ?case by (auto intro: dvdI)\nnext\n  case (insert a A) then\n  have \"f a dvd g a\" and \"setprod f A dvd setprod g A\" by simp_all\n  then obtain r s where \"g a = f a * r\" and \"setprod g A = setprod f A * s\" by (auto elim!: dvdE)\n  then have \"g a * setprod g A = f a * setprod f A * (r * s)\" by (simp add: ac_simps)\n  with insert.hyps show ?case by (auto intro: dvdI)\nqed\n\nlemma setprod_dvd_setprod_subset:\n  \"finite B \\<Longrightarrow> A \\<subseteq> B \\<Longrightarrow> setprod f A dvd setprod f B\"\n  by (auto simp add: setprod.subset_diff ac_simps intro: dvdI)\n\nend\n\n\nsubsubsection {* Properties in more restricted classes of structures *}\n\ncontext comm_semiring_1\nbegin\n\nlemma dvd_setprod_eqI [intro]:\n  assumes \"finite A\" and \"a \\<in> A\" and \"b = f a\"\n  shows \"b dvd setprod f A\"\nproof -\n  from `finite A` have \"setprod f (insert a (A - {a})) = f a * setprod f (A - {a})\"\n    by (intro setprod.insert) auto\n  also from `a \\<in> A` have \"insert a (A - {a}) = A\" by blast\n  finally have \"setprod f A = f a * setprod f (A - {a})\" .\n  with `b = f a` show ?thesis by simp\nqed\n\nlemma dvd_setprodI [intro]:\n  assumes \"finite A\" and \"a \\<in> A\"\n  shows \"f a dvd setprod f A\"\n  using assms by auto\n\nlemma setprod_zero:\n  assumes \"finite A\" and \"\\<exists>a\\<in>A. f a = 0\"\n  shows \"setprod f A = 0\"\nusing assms proof (induct A)\n  case empty then show ?case by simp\nnext\n  case (insert a A)\n  then have \"f a = 0 \\<or> (\\<exists>a\\<in>A. f a = 0)\" by simp\n  then have \"f a * setprod f A = 0\" by rule (simp_all add: insert)\n  with insert show ?case by simp\nqed\n\nlemma setprod_dvd_setprod_subset2:\n  assumes \"finite B\" and \"A \\<subseteq> B\" and \"\\<And>a. a \\<in> A \\<Longrightarrow> f a dvd g a\"\n  shows \"setprod f A dvd setprod g B\"\nproof -\n  from assms have \"setprod f A dvd setprod g A\"\n    by (auto intro: setprod_dvd_setprod)\n  moreover from assms have \"setprod g A dvd setprod g B\"\n    by (auto intro: setprod_dvd_setprod_subset)\n  ultimately show ?thesis by (rule dvd_trans)\nqed\n\nend\n\nlemma setprod_zero_iff [simp]:\n  assumes \"finite A\"\n  shows \"setprod f A = (0::'a::{comm_semiring_1,no_zero_divisors}) \\<longleftrightarrow> (\\<exists>a\\<in>A. f a = 0)\"\n  using assms by (induct A) (auto simp: no_zero_divisors)\n\nlemma (in field) setprod_diff1:\n  \"finite A \\<Longrightarrow> f a \\<noteq> 0 \\<Longrightarrow>\n    (setprod f (A - {a})) = (if a \\<in> A then setprod f A / f a else setprod f A)\"\n  by (induct A rule: finite_induct) (auto simp add: insert_Diff_if)\n\nlemma (in field_inverse_zero) setprod_inversef: \n  \"finite A \\<Longrightarrow> setprod (inverse \\<circ> f) A = inverse (setprod f A)\"\n  by (induct A rule: finite_induct) simp_all\n\nlemma (in field_inverse_zero) setprod_dividef:\n  \"finite A \\<Longrightarrow> (\\<Prod>x\\<in>A. f x / g x) = setprod f A / setprod g A\"\n  using setprod_inversef [of A g] by (simp add: divide_inverse setprod.distrib)\n\nlemma setprod_Un:\n  fixes f :: \"'b \\<Rightarrow> 'a :: field\"\n  assumes \"finite A\" and \"finite B\"\n  and \"\\<forall>x\\<in>A \\<inter> B. f x \\<noteq> 0\"\n  shows \"setprod f (A \\<union> B) = setprod f A * setprod f B / setprod f (A \\<inter> B)\"\nproof -\n  from assms have \"setprod f A * setprod f B = setprod f (A \\<union> B) * setprod f (A \\<inter> B)\"\n    by (simp add: setprod.union_inter [symmetric, of A B])\n  with assms show ?thesis by simp\nqed\n\nlemma (in linordered_semidom) setprod_nonneg:\n  \"(\\<forall>a\\<in>A. 0 \\<le> f a) \\<Longrightarrow> 0 \\<le> setprod f A\"\n  by (induct A rule: infinite_finite_induct) simp_all\n\nlemma (in linordered_semidom) setprod_pos:\n  \"(\\<forall>a\\<in>A. 0 < f a) \\<Longrightarrow> 0 < setprod f A\"\n  by (induct A rule: infinite_finite_induct) simp_all\n\nlemma (in linordered_semidom) setprod_mono:\n  assumes \"\\<forall>i\\<in>A. 0 \\<le> f i \\<and> f i \\<le> g i\"\n  shows \"setprod f A \\<le> setprod g A\"\n  using assms by (induct A rule: infinite_finite_induct)\n    (auto intro!: setprod_nonneg mult_mono)\n\nlemma (in linordered_field) abs_setprod:\n  \"\\<bar>setprod f A\\<bar> = (\\<Prod>x\\<in>A. \\<bar>f x\\<bar>)\"\n  by (induct A rule: infinite_finite_induct) (simp_all add: abs_mult)\n\nlemma setprod_eq_1_iff [simp]:\n  \"finite A \\<Longrightarrow> setprod f A = 1 \\<longleftrightarrow> (\\<forall>a\\<in>A. f a = (1::nat))\"\n  by (induct A rule: finite_induct) simp_all\n\nlemma setprod_pos_nat:\n  \"finite A \\<Longrightarrow> (\\<forall>a\\<in>A. f a > (0::nat)) \\<Longrightarrow> setprod f A > 0\"\n  using setprod_zero_iff by (simp del: neq0_conv add: neq0_conv [symmetric])\n\nlemma setprod_pos_nat_iff [simp]:\n  \"finite A \\<Longrightarrow> setprod f A > 0 \\<longleftrightarrow> (\\<forall>a\\<in>A. f a > (0::nat))\"\n  using setprod_zero_iff by (simp del:neq0_conv add:neq0_conv [symmetric])\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/Groups_Big.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933447152497, "lm_q2_score": 0.855851143290548, "lm_q1q2_score": 0.7017066564508578}}
{"text": "theory Expressions\nimports Main\nbegin\n\n(* Defini\u00e7\u00e3o de algumas primitivas bin\u00e1rias sobre naturais e inteiros *)\nprimrec \"add\"::\"nat \\<Rightarrow> nat \\<Rightarrow> nat\" where\n  \"add x 0 = x\" |\n  \"add x (Suc y) = Suc (add x y)\"\n\nprimrec \"mult\"::\"nat \\<Rightarrow> nat \\<Rightarrow> nat\" where\n  \"mult x 0 = 0\" |\n  \"mult x (Suc y) = add x (mult x y)\"\n\ndefinition \"addi\"::\"int \\<Rightarrow> int \\<Rightarrow> int\" where\n  \"addi x y = x + y\"\n\ndefinition \"multi\"::\"int \\<Rightarrow> int \\<Rightarrow> int\" where\n  \"multi x y = x * y\"\n\n(* Defini\u00e7\u00e3o de um tipo indutivo para express\u00f5es sobre um tipo gen\u00e9rico *)\ndatatype 'a Exp = Const 'a\n                | Var nat\n                | App \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a\" \"'a Exp\" \"'a Exp\"\n\n(* Alguns termos da linguagem de express\u00f5es *)\nterm \"Var 0\"\nterm \"Const (1::int)\"\nterm \"Const (1::nat)\"\nterm \"App add (Var 0) (Const (1::nat))\"\nterm \"App mult (Var 0) (Const (1::nat))\"\nterm \"App addi (Var 0) (App multi (Const (1::int)) (Var 1))\"\n\n(* Primitiva recursiva que efetua a valora\u00e7\u00e3o de uma express\u00e3o *)\nprimrec eval :: \"'a Exp \\<Rightarrow> (nat \\<Rightarrow> 'a) \\<Rightarrow> 'a\" where\n    \"eval (Const b) env = b\" |\n    \"eval (Var x) env = env x\" |\n    \"eval (App f e1 e2) env = (f (eval e1 env) (eval e2 env))\"\n\nvalue \"eval (App add (Var 0) (Const 1)) (%x::nat. 2)\"\nvalue \"eval (App mult (Var 0) (Const (1::nat))) (%x::nat. 2)\"\nvalue \"eval (App addi (Var 0) (App multi (Const (1::int)) (Const (4::int)))) (%x::nat. 2)\"\nvalue \"eval (App multi (App addi (Var 0) (Const 2)) (Const 3)) (%x::nat. 2)\"\n\n(* Defini\u00e7\u00e3o de um tipo indutivo para instru\u00e7\u00f5es em uma pilha *)\ndatatype 'a Instr = IConst 'a\n                  | ILoad nat\n                  | IApp \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a\"\n\n(* Defini\u00e7\u00e3o de uma primitiva recursiva que compila uma express\u00e3o em uma lista de instru\u00e7\u00f5es *)\nprimrec compile :: \"'a Exp \\<Rightarrow> 'a Instr list\" where\n  \"compile (Const b) = [IConst b]\" |\n  \"compile (Var x) = [ILoad x]\" |\n  \"compile (App f e1 e2) = (compile e2) @ (compile e1 ) @ [IApp f]\"\n\nvalue \"compile (App add (Var 0) (Const 1))\"\nvalue \"compile (App multi (Var 0) (Const (1::int)))\"\nvalue \"compile (App addi (Var 0) (App multi (Const (1::int)) (Const (4::int))))\"\n\n(* Primitiva recursiva que executa uma lista de instru\u00e7\u00f5es *)\nprimrec exec :: \"'a Instr list \\<Rightarrow> (nat \\<Rightarrow> 'a) \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where\n  \"exec [] env vs = vs\" |\n  \"exec (i # is) env vs = (case i of\n      IConst v \\<Rightarrow> exec is env (v # vs)\n    | ILoad x  \\<Rightarrow> exec is env ((env x) # vs) \n    | IApp f   \\<Rightarrow> exec is env ((f (hd vs) (hd (tl vs))) # (tl (tl vs))))\"\n\nvalue \"exec [] (%x::nat. 1) []\"\nvalue \"exec (compile (App add (Var 0) (Const 1))) (%x::nat. 1) []\"\nvalue \"exec (compile (App multi (Var 0) (Const (1::int)))) (%x::nat. 1) []\"\nvalue \"exec (compile (App addi (Var 0) (App multi (Const (1::int)) (Const (4::int))))) (%x::nat. 1) []\"\n\n(* Prova da correture do compilador *)\n(* Extra\u00edda de \"Practical Theorem Proving with Isabelle/Isar Lecture Notes\", por Jeremy Siek *)\n\n(* Lema auxiliar  *)\nlemma exec_app [rule_format]:\n  \"\\<forall>vs. exec (xs@ys) s vs = exec ys s (exec xs s vs)\"\n  apply(induct xs, simp, auto)\n  apply(case_tac a, auto) done\n\n(* Prova do teorema *)\ntheorem \"\\<forall>vs. exec (compile e) env vs = (eval e env) # vs\"\n  proof (induct e)\n    fix v\n    show \"\\<forall>vs. exec (compile (Const v)) env vs = (eval (Const v) env) # vs\" by simp\n    next\n      fix x\n      show \"\\<forall>vs. exec (compile (Var x)) env vs = eval (Var x) env # vs\" by simp\n      next\n        fix f e1 e2\n          assume IH1: \"\\<forall>vs. exec (compile e1) env vs = eval e1 env # vs\"\n          and IH2: \"\\<forall>vs. exec (compile e2) env vs = eval e2 env # vs\"\n          show \"\\<forall>vs. exec (compile (App f e1 e2)) env vs = eval (App f e1 e2) env # vs\"\n          proof\n            fix vs\n              have \"exec (compile (App f e1 e2)) env vs = exec ((compile e2) @ (compile e1) @ [IApp f ]) env vs\" by simp also\n              have \"\\<dots> = exec ((compile e1) @ [IApp f ]) env (exec (compile e2) env vs)\" using exec_app by blast also\n              have \"\\<dots> = exec [IApp f] env (exec (compile e1) env (exec (compile e2) env vs))\" using exec_app by blast also\n              have \"\\<dots> = exec [IApp f ] env (exec (compile e1) env (eval e2 env # vs))\"  using IH2 by simp also\n              have \"\\<dots> = exec [IApp f ] env ((eval e1 env) # (eval e2 env # vs))\" using IH1 by simp also\n              have \"\\<dots> = (f (eval e1 env) (eval e2 env))#vs\" by simp also\n              have \"\\<dots> = eval (App f e1 e2) env # vs\" by simp\n              finally\n                show \"exec (compile (App f e1 e2)) env vs = eval (App f e1 e2) env # vs\" by blast\n          qed\n  qed\n", "meta": {"author": "taschetto", "repo": "formalMethods", "sha": "58a1eef1326ad463d8893d8604d7f246d64bf5ae", "save_path": "github-repos/isabelle/taschetto-formalMethods", "path": "github-repos/isabelle/taschetto-formalMethods/formalMethods-58a1eef1326ad463d8893d8604d7f246d64bf5ae/t1/Expressions.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511396138365, "lm_q2_score": 0.8198933381139645, "lm_q1q2_score": 0.7017066477866291}}
{"text": "(* Author: Tobias Nipkow *)\n\nsection \\<open>Tree Rotations\\<close>\n\ntheory Tree_Rotations\nimports \"HOL-Library.Tree\"\nbegin\n\ntext \\<open>How to transform a tree into a list and into any other tree (with the same @{const inorder})\nby rotations.\\<close>\n\nfun is_list :: \"'a tree \\<Rightarrow> bool\" where\n\"is_list (Node l _ r) = (l = Leaf \\<and> is_list r)\" |\n\"is_list Leaf = True\"\n\ntext \\<open>Termination proof via measure function. NB @{term \"size t - rlen t\"} works for\nthe actual rotation equation but not for the second equation.\\<close>\n\nfun rlen :: \"'a tree \\<Rightarrow> nat\" where\n\"rlen Leaf = 0\" |\n\"rlen (Node l x r) = rlen r + 1\"\n\nlemma rlen_le_size: \"rlen t \\<le> size t\"\nby(induction t) auto\n\n\nsubsection \\<open>Without positions\\<close>\n\nfunction (sequential) list_of :: \"'a tree \\<Rightarrow> 'a tree\" where\n\"list_of (Node (Node A a B) b C) = list_of (Node A a (Node B b C))\" |\n\"list_of (Node Leaf a A) = Node Leaf a (list_of A)\" |\n\"list_of Leaf = Leaf\"\nby pat_completeness auto\n\ntermination\nproof\n  let ?R = \"measure(\\<lambda>t. 2*size t - rlen t)\"\n  show \"wf ?R\" by (auto simp add: mlex_prod_def)\n\n  fix A a B b C\n  show \"(Node A a (Node B b C), Node (Node A a B) b C) \\<in> ?R\"\n    using rlen_le_size[of C] by(simp)\n\n  fix a A show \"(A, Node Leaf a A) \\<in> ?R\" using rlen_le_size[of A] by(simp)\nqed\n\nlemma is_list_rot: \"is_list(list_of t)\"\nby (induction t rule: list_of.induct) auto\n\nlemma inorder_rot: \"inorder(list_of t) = inorder t\"\nby (induction t rule: list_of.induct) auto\n\n\nsubsection \\<open>With positions\\<close>\n\ndatatype dir = L | R\n\ntype_synonym \"pos\" = \"dir list\"\n\nfunction (sequential) rotR_poss :: \"'a tree \\<Rightarrow> pos list\" where\n\"rotR_poss (Node (Node A a B) b C) = [] # rotR_poss (Node A a (Node B b C))\" |\n\"rotR_poss (Node Leaf a A) = map (Cons R) (rotR_poss A)\" |\n\"rotR_poss Leaf = []\"\nby pat_completeness auto\n\ntermination\nproof\n  let ?R = \"measure(\\<lambda>t. 2*size t - rlen t)\"\n  show \"wf ?R\" by (auto simp add: mlex_prod_def)\n\n  fix A a B b C\n  show \"(Node A a (Node B b C), Node (Node A a B) b C) \\<in> ?R\"\n    using rlen_le_size[of C] by(simp)\n\n  fix a A show \"(A, Node Leaf a A) \\<in> ?R\" using rlen_le_size[of A] by(simp)\nqed\n\nfun rotR :: \"'a tree \\<Rightarrow> 'a tree\" where\n\"rotR (Node (Node A a B) b C) = Node A a (Node B b C)\"\n\nfun rotL :: \"'a tree \\<Rightarrow> 'a tree\" where\n\"rotL (Node A a (Node B b C)) = Node (Node A a B) b C\"\n\nfun apply_at :: \"('a tree \\<Rightarrow> 'a tree) \\<Rightarrow> pos \\<Rightarrow> 'a tree \\<Rightarrow> 'a tree\" where\n  \"apply_at f [] t = f t\"\n| \"apply_at f (L # ds) (Node l a r) = Node (apply_at f ds l) a r\"\n| \"apply_at f (R # ds) (Node l a r) = Node l a (apply_at f ds r)\"\n\nfun apply_ats :: \"('a tree \\<Rightarrow> 'a tree) \\<Rightarrow> pos list \\<Rightarrow> 'a tree \\<Rightarrow> 'a tree\" where\n\"apply_ats _ [] t = t\" |\n\"apply_ats f (p#ps) t = apply_ats f ps (apply_at f p t)\"\n\nlemma apply_ats_append:\n  \"apply_ats f (ps\\<^sub>1 @ ps\\<^sub>2) t = apply_ats f ps\\<^sub>2 (apply_ats f ps\\<^sub>1 t)\"\nby (induction ps\\<^sub>1 arbitrary: t) auto\n\nabbreviation \"rotRs \\<equiv> apply_ats rotR\"\nabbreviation \"rotLs \\<equiv> apply_ats rotL\"\n\nlemma apply_ats_map_R: \"apply_ats f (map ((#) R) ps) \\<langle>l, a, r\\<rangle> = Node l a (apply_ats f ps r)\"\nby(induction ps arbitrary: r) auto\n\nlemma inorder_rotRs_poss: \"inorder (rotRs (rotR_poss t) t) = inorder t\"\napply(induction t rule: rotR_poss.induct)\napply(auto simp: apply_ats_map_R)\ndone\n\nlemma is_list_rotRs: \"is_list (rotRs (rotR_poss t) t)\"\napply(induction t rule: rotR_poss.induct)\napply(auto simp: apply_ats_map_R)\ndone\n\nlemma \"is_list (rotRs ps t) \\<longrightarrow> length ps \\<le> length(rotR_poss t)\"\nquickcheck[expect=counterexample]\noops\n\nlemma length_rotRs_poss: \"length (rotR_poss t) = size t - rlen t\"\nproof(induction t rule: rotR_poss.induct)\n  case (1 A a B b C)\n  then show ?case using rlen_le_size[of C] by simp\nqed auto\n\nlemma is_list_inorder_same:\n  \"is_list t1 \\<Longrightarrow> is_list t2 \\<Longrightarrow> inorder t1 = inorder t2 \\<Longrightarrow> t1 = t2\"\nproof(induction t1 arbitrary: t2)\n  case Leaf\n  then show ?case by simp\nnext\n  case Node\n  then show ?case by (cases t2) simp_all\nqed\n\nlemma rot_id: \"rotLs (rev (rotR_poss t)) (rotRs (rotR_poss t) t) = t\"\napply(induction t rule: rotR_poss.induct)\napply(auto simp: apply_ats_map_R rev_map apply_ats_append)\ndone\n\ncorollary tree_to_tree_rotations: assumes \"inorder t1 = inorder t2\"\nshows \"rotLs (rev (rotR_poss t2)) (rotRs (rotR_poss t1) t1) = t2\"\nproof -\n  have \"rotRs (rotR_poss t1) t1 = rotRs (rotR_poss t2) t2\" (is \"?L = ?R\")\n    by (simp add: assms inorder_rotRs_poss is_list_inorder_same is_list_rotRs)\n  hence \"rotLs (rev (rotR_poss t2)) ?L = rotLs (rev (rotR_poss t2)) ?R\"\n    by simp\n  also have \"\\<dots> = t2\" by(rule rot_id)\n  finally show ?thesis .\nqed\n\nlemma size_rlen_better_ub: \"size t - rlen t \\<le> size t - 1\"\nby (cases t) 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/Tree_Rotations.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933315126791, "lm_q2_score": 0.8558511414521922, "lm_q1q2_score": 0.701706643644167}}
{"text": "header {* Dijkstra's Algorithm *}\ntheory Dijkstra\n  imports \n  Graph \n  Dijkstra_Misc \n  \"../Collections/Refine_Dflt_ICF\"\n  Weight\nbegin\ntext {*\n  This theory defines Dijkstra's algorithm. First, a correct result of \n  Dijkstra's algorithm w.r.t. a graph and a start vertex is specified. \n  Then, the refinement \n  framework is used to specify Dijkstra's Algorithm, prove it correct, and\n  finally refine it to datatypes that are closer to an implementation than\n  the original specification.\n  *}\n\nsubsection \"Graph's for Dijkstra's Algorithm\"\n  text {* A graph annotated with weights. *}\n  locale weighted_graph = valid_graph G\n    for G :: \"('V,'W::weight) graph\"\n\nsubsection \"Specification of Correct Result\"\n  context weighted_graph\n  begin\n    text {*\n      A result of Dijkstra's algorithm is correct, if it is a map from nodes \n      @{text \"v\"} to the shortest path from the start node @{text \"v0\"} to \n      @{text \"v\"}. Iff there is no such path, the node is not in the map.\n      *}\n    definition is_shortest_path_map :: \"'V \\<Rightarrow> ('V \\<rightharpoonup> ('V,'W) path) \\<Rightarrow> bool\" \n      where\n      \"is_shortest_path_map v0 res \\<equiv> \\<forall>v\\<in>V. (case res v of\n        None \\<Rightarrow> \\<not>(\\<exists>p. is_path v0 p v) |\n        Some p \\<Rightarrow> is_path v0 p v \n                  \\<and> (\\<forall>p'. is_path v0 p' v \\<longrightarrow> path_weight p \\<le> path_weight p')\n      )\"\n  end\n\n  text {*\n    The following function returns the weight of an optional path,\n    where @{text \"None\"} is interpreted as infinity.\n    *}\n  fun path_weight' where\n    \"path_weight' None = top\" |\n    \"path_weight' (Some p) = Num (path_weight p)\"\n\nsubsection \"Dijkstra's Algorithm\"\n  text {*\n    The state in the main loop of the algorithm consists of a workset \n    @{text \"wl\"} of vertexes that still need to be explored, and a map \n    @{text \"res\"} that contains the current shortest path for each vertex.\n    *}\n  type_synonym ('V,'W) state = \"('V set) \\<times> ('V \\<rightharpoonup> ('V,'W) path)\"\n\n  text {*\n    The preconditions of Dijkstra's algorithm, i.e., that it operates on a \n    valid and finite graph, and that the start node is a node of the graph,\n    are summarized in a locale.\n    *}\n  locale Dijkstra = weighted_graph G \n    for G :: \"('V,'W::weight) graph\"+\n    fixes v0 :: 'V\n    assumes finite[simp,intro!]: \"finite V\" \"finite E\"\n    assumes v0_in_V[simp, intro!]: \"v0\\<in>V\"\n    assumes nonneg_weights[simp, intro]: \"(v,w,v')\\<in>edges G \\<Longrightarrow> 0\\<le>w\"\n  begin\n\n  text {* Paths have non-negative weights.*}\n  lemma path_nonneg_weight: \"is_path v p v' \\<Longrightarrow> 0 \\<le> path_weight p\"\n    by (induct rule: is_path.induct) auto\n\n  text {* Invariant of the main loop: \n    \\begin{itemize}\n      \\item The workset only contains nodes of the graph.\n      \\item If the result set contains a path for a node, it is actually a path,\n        and uses only intermediate vertices outside the workset.\n      \\item For all vertices outside the workset, the result map contains the \n        shortest path.\n      \\item For all vertices in the workset, the result map contains the\n        shortest path among all paths that only use intermediate vertices outside\n        the workset.\n    \\end{itemize}\n    *}\n  definition \"dinvar \\<sigma> \\<equiv> let (wl,res)=\\<sigma> in\n    wl \\<subseteq> V \\<and>\n    (\\<forall>v\\<in>V. \\<forall>p. res v = Some p \\<longrightarrow> is_path v0 p v \\<and> int_vertices p \\<subseteq> V-wl) \\<and>\n    (\\<forall>v\\<in>V-wl. \\<forall>p. is_path v0 p v \n       \\<longrightarrow> path_weight' (res v) \\<le> path_weight' (Some p)) \\<and>\n    (\\<forall>v\\<in>wl. \\<forall>p. is_path v0 p v \\<and> int_vertices p \\<subseteq> V-wl\n       \\<longrightarrow> path_weight' (res v) \\<le> path_weight' (Some p)\n    )\n    \"\n\n  text {* Sanity check: The invariant is strong enough to imply correctness \n    of result. *}\n  lemma invar_imp_correct: \"dinvar ({},res) \\<Longrightarrow> is_shortest_path_map v0 res\"\n    unfolding dinvar_def is_shortest_path_map_def\n    by (auto simp: infty_unbox split: option.split)\n\n  text {*\n    The initial workset contains all vertices. The initial result maps\n    @{text \"v0\"} to the empty path, and all other vertices to @{text \"None\"}.\n    *}\n  definition dinit :: \"('V,'W) state nres\" where\n    \"dinit \\<equiv> SPEC ( \\<lambda>(wl,res) . \n        wl=V \\<and> res v0 = Some [] \\<and> (\\<forall>v\\<in>V-{v0}. res v = None))\"\n\n  text {*\n    The initial state satisfies the invariant.\n    *}\n  lemma dinit_invar: \"dinit \\<le> SPEC dinvar\"\n    unfolding dinit_def\n    apply (intro refine_vcg)\n    apply (force simp: dinvar_def split: option.split)\n    done\n\n  text {*\n    In each iteration, the main loop of the algorithm pops a minimal node from\n    the workset, and then updates the result map accordingly.\n    *}\n\n  text {*\n    Pop a minimal node from the workset. The node is minimal in the sense that\n    the length of the current path for that node is minimal.\n    *}\n  definition pop_min :: \"('V,'W) state \\<Rightarrow> ('V \\<times> ('V,'W) state) nres\" where\n    \"pop_min \\<sigma> \\<equiv> do {\n      let (wl,res)=\\<sigma>;\n      ASSERT (wl\\<noteq>{}); \n      v \\<leftarrow> RES (least_map (path_weight' \\<circ> res) wl);\n      RETURN (v,(wl-{v},res))\n    }\"\n\n\n  text {*\n    Updating the result according to a node @{text \"v\"} is done by checking, \n    for each successor node, whether the path over @{text \"v\"} is shorter than \n    the path currently stored into the result map.\n    *}\n  inductive update_spec :: \"'V \\<Rightarrow> ('V,'W) state \\<Rightarrow> ('V,'W) state \\<Rightarrow> bool\"\n    where\n    \"\\<lbrakk> \\<forall>v'\\<in>V. \n      res' v' \\<in> least_map path_weight' (\n        { res v' } \\<union> { Some (p@[(v,w,v')]) | p w. res v = Some p \\<and> (v,w,v')\\<in>E }\n      )\n     \\<rbrakk> \\<Longrightarrow> update_spec v (wl,res) (wl,res')\"\n\n  text {*\n    In order to ease the refinement proof, we will assert the following \n    precondition for updating.\n    *}\n  definition update_pre :: \"'V \\<Rightarrow> ('V,'W) state \\<Rightarrow> bool\" where\n    \"update_pre v \\<sigma> \\<equiv> let (wl,res)=\\<sigma> in v\\<in>V \n      \\<and> (\\<forall>v'\\<in>V-wl. v'\\<noteq>v \\<longrightarrow> (\\<forall>p. is_path v0 p v' \n          \\<longrightarrow> path_weight' (res v') \\<le> path_weight' (Some p)))\n      \\<and> (\\<forall>v'\\<in>V. \\<forall>p. res v' = Some p \\<longrightarrow> is_path v0 p v')\"\n\n  definition update :: \"'V \\<Rightarrow> ('V,'W) state \\<Rightarrow> ('V,'W) state nres\" where \n    \"update v \\<sigma> \\<equiv> do {ASSERT (update_pre v \\<sigma>); SPEC (update_spec v \\<sigma>)}\"\n\n  text {* Finally, we define Dijkstra's algorithm: *}\n  definition dijkstra where\n    \"dijkstra \\<equiv> do {\n       \\<sigma>0\\<leftarrow>dinit; \n       (_,res) \\<leftarrow> WHILE\\<^sub>T\\<^bsup>dinvar\\<^esup> (\\<lambda>(wl,_). wl\\<noteq>{}) \n            (\\<lambda>\\<sigma>. \n              do { (v,\\<sigma>') \\<leftarrow> pop_min \\<sigma>; update v \\<sigma>' }\n            )\n            \\<sigma>0;\n       RETURN res }\n    \"\n\n  text {* The following theorem states (total) correctness of Dijkstra's \n    algorithm. *}\n\n  theorem dijkstra_correct: \"dijkstra \\<le> SPEC (is_shortest_path_map v0)\"\n    unfolding dijkstra_def\n    unfolding dinit_def\n    unfolding pop_min_def update_def [abs_def]\n    thm refine_vcg\n\n    apply (refine_rcg\n      WHILEIT_rule[where R=\"inv_image {(x,y). x<y} (card \\<circ> fst)\"]\n      refine_vcg \n    )\n\n    (* TODO/FIXME: Should we built in such massaging of the goal into \n        refine_rcg ?*)\n    apply (simp_all split: prod.split_asm)\n    apply (tactic {*\n      ALLGOALS ((REPEAT_DETERM o Hypsubst.bound_hyp_subst_tac @{context})\n      THEN' asm_full_simp_tac @{context}\n      )*})\n\n  proof -\n    fix wl res v\n    assume INV: \"dinvar (wl,res)\"\n    and LM: \"v\\<in>least_map (path_weight' \\<circ> res) wl\"\n    hence \"v\\<in>V\" unfolding dinvar_def by (auto dest: least_map_elemD)\n    moreover\n    from INV have \" \\<forall>v'\\<in>V - (wl-{v}). v' \\<noteq> v \\<longrightarrow> \n      (\\<forall>p. is_path v0 p v' \\<longrightarrow> path_weight' (res v') \\<le> Num (path_weight p))\"\n      by (auto simp: dinvar_def)\n    moreover from INV have \"\\<forall>v'\\<in>V. \\<forall>p. res v'=Some p \\<longrightarrow> is_path v0 p v'\"\n      by (auto simp: dinvar_def)\n    ultimately show \"update_pre v (wl-{v},res)\" by (auto simp: update_pre_def)\n  next\n    fix res\n    assume \"dinvar ({}, res)\"\n    thus \"is_shortest_path_map v0 res\"\n      by (rule invar_imp_correct)\n  next\n    show \"wf (inv_image {(x, y). x < y} (card \\<circ> fst))\" \n      by (blast intro: wf_less)\n  next\n    fix wl res v \\<sigma>''\n    assume \n      LM: \"v\\<in>least_map (path_weight' \\<circ> res) wl\" and \n      UD: \"update_spec v (wl-{v},res) \\<sigma>''\" and\n      INV: \"dinvar (wl,res)\" \n\n    from LM have \"v\\<in>wl\" by (auto dest: least_map_elemD)\n    moreover from UD have \"fst \\<sigma>'' = wl-{v}\" by (auto elim: update_spec.cases)\n    moreover from INV have \"finite wl\" \n      unfolding dinvar_def by (auto dest: finite_subset)\n    ultimately show \"card (fst \\<sigma>'') < card wl\" \n      apply simp\n      by (metis card_gt_0_iff diff_Suc_less empty_iff)\n  next\n    fix a and res :: \"'V \\<rightharpoonup> ('V,'W) path\"\n    assume \"a = V \\<and> res v0 = Some [] \\<and> (\\<forall>v\\<in>V-{v0}. res v = None)\"\n    thus \"dinvar (V,res)\"\n      by (force simp: dinvar_def split: option.split)\n  next\n    fix wl res\n    assume INV: \"dinvar (wl,res)\"\n    hence  \n      WL_SUBSET: \"wl \\<subseteq> V\" and\n      PATH_VALID: \"\\<forall>v\\<in>V. \\<forall>p. res v = Some p \n        \\<longrightarrow> is_path v0 p v \\<and> int_vertices p \\<subseteq> V - wl\" and\n      NWL_MIN: \"\\<forall>v\\<in>V - wl. \\<forall>p. is_path v0 p v \n        \\<longrightarrow> path_weight' (res v) \\<le> Num (path_weight p)\" and\n      WL_MIN: \"\\<forall>v\\<in>wl. \\<forall>p. is_path v0 p v \\<and> int_vertices p \\<subseteq> V - wl \n        \\<longrightarrow> path_weight' (res v) \\<le> Num (path_weight p)\"\n      unfolding dinvar_def by auto\n\n    fix v \\<sigma>''\n    assume V_LEAST: \"v\\<in>least_map (path_weight' o res) wl\" \n      and \"update_spec v (wl-{v},res) \\<sigma>''\"\n    then obtain res' where\n      [simp]: \"\\<sigma>''=(wl-{v},res')\"\n      and CONSIDERED_NEW_PATHS: \"\\<forall>v'\\<in>V. res' v' \\<in> least_map path_weight' \n        (insert (res v') \n              ({ Some (p@[(v,w,v')]) | p w. res v = Some p \\<and> (v,w,v')\\<in>E }))\"\n      by (auto elim!: update_spec.cases)\n      \n    from V_LEAST have V_MEM: \"v\\<in>wl\" by (blast intro: least_map_elemD)\n\n    show \"dinvar \\<sigma>''\"\n      apply (unfold dinvar_def, simp)\n      apply (intro conjI)\n    proof -\n      from WL_SUBSET show \"wl-{v} \\<subseteq> V\" by auto\n\n      show \"\\<forall>va\\<in>V. \\<forall>p. res' va = Some p \n        \\<longrightarrow> is_path v0 p va \\<and> int_vertices p \\<subseteq> V - (wl - {v})\"\n      proof (intro ballI conjI impI allI)\n        fix v' p\n        assume V'_MEM: \"v'\\<in>V\" and [simp]: \"res' v' = Some p\"\n        txt {* The new paths that we have added are valid and only use \n          intermediate vertices outside the workset. \n          \n          This proof works as follows: A path @{term \"res' v'\"} is either\n          the old path, or has been assembled as a path over node @{term v}.\n          In the former case the proposition follows straightforwardly from the\n          invariant for the old state. In the latter case we get, by the invariant\n          for the old state, that the path over node @{term v} is valid. \n          Then, we observe that appending an edge to a valid path yields a valid \n          path again. Also, adding @{term v} as intermediate node is legal, as we \n          just removed @{term v} from the workset.\n          *}\n        with CONSIDERED_NEW_PATHS have \"res' v' \\<in> (insert (res v') \n          ({ Some (p@[(v,w,v')]) | p w. res v = Some p \\<and> (v,w,v')\\<in>E }))\"\n          by (rule_tac least_map_elemD) blast\n        moreover {\n          assume [symmetric,simp]: \"res' v' = res v'\"\n          from V'_MEM PATH_VALID have \n            \"is_path v0 p v'\" \n            \"int_vertices p \\<subseteq> V - (wl-{v})\"\n            by force+\n        } moreover {\n          fix pv w\n          assume \"res' v' = Some (pv@[(v,w,v')])\" \n            and [simp]: \"res v = Some pv\" \n            and EDGE: \"(v,w,v')\\<in>E\"\n          hence [simp]: \"p = pv@[(v,w,v')]\" by simp\n          \n          from bspec[OF PATH_VALID set_rev_mp[OF V_MEM WL_SUBSET]] have \n            PATHV: \"is_path v0 pv v\" and IVV: \"int_vertices pv \\<subseteq> V - wl\" by auto\n          hence \n            \"is_path v0 p v'\" \n            \"int_vertices p \\<subseteq> V - (wl-{v})\"\n            by (auto simp: EDGE V'_MEM)\n        } \n        ultimately show \n          \"is_path v0 p v'\" \n          \"int_vertices p \\<subseteq> V - (wl-{v})\"\n          by blast+\n      qed\n\n      txt {*\n        We show that already the {\\em original} result stores the minimal \n        path for all vertices not in the {\\em new} workset. \n        For vertices also not in the original workset, this follows \n        straightforwardly from the invariant.\n        \n        For the vertex @{text v}, that has been removed from the\n        workset, we split a path @{text p'} to @{text v} at the point\n        @{text u} where it first enters the original workset.  \n\n        As we chose @{text v} to be the vertex in the workset with the\n        minimal weight, its weight is less than the current weight of\n        @{text u}.  As the vertices of the prefix of @{text p'} up to\n        @{text u} are not in the workset, the current weight of\n        @{text u} is less than the weight of the prefix of @{text\n        p'}, and thus less than the weight of @{text p'}. \n        Together, the current weight of @{text v} is less than the weight of\n        @{text p'}. *}\n      have RES_MIN: \"\\<forall>v\\<in>V - (wl - {v}). \\<forall>p. is_path v0 p v \n        \\<longrightarrow> path_weight' (res v) \\<le> Num (path_weight p)\"\n      proof (intro ballI allI impI)\n        fix v' p'\n        assume NOT_IN_WL: \"v' \\<in> V - (wl - {v})\" \n          and PATH: \"is_path v0 p' v'\"\n        hence [simp, intro!]: \"v'\\<in>V\" by auto\n\n        show \"path_weight' (res v') \\<le> Num (path_weight p')\"\n        proof (cases \"v' = v\")\n          assume NE[simp]: \"v'\\<noteq>v\"\n          from bspec[OF NWL_MIN, of v'] NOT_IN_WL PATH show\n            \"path_weight' (res v') \\<le> Num (path_weight p')\" by auto\n        next\n          assume EQ[simp]: \"v'=v\"\n          \n          from path_split_set'[OF PATH, of wl] V_MEM obtain p1 p2 u where\n            [simp]: \"p'=p1@p2\" \n              and P1: \"is_path v0 p1 u\" \n              and P2: \"is_path u p2 v'\" \n              and P1V: \"int_vertices p1 \\<subseteq> -wl\" \n              and [simp]: \"u\\<in>wl\"\n            by auto\n          \n          from least_map_leD[OF V_LEAST]\n          have \"path_weight' (res v') \\<le> path_weight' (res u)\"by auto\n          also from bspec[OF WL_MIN, of u] P1 P1V int_vertices_subset[OF P1]\n          have \"path_weight' (res u) \\<le> Num (path_weight p1)\" by auto\n          also have \"\\<dots> \\<le> Num (path_weight p')\" \n            using path_nonneg_weight[OF P2]\n            apply (auto simp: infty_unbox )\n            by (metis add_0_right add_left_mono)\n          finally show ?thesis .\n        qed\n      qed\n        \n      txt {* With the previous statement, we easily show the\n        third part of the invariant, as the new paths are not longer than the\n        old ones.\n        *}\n      show \"\\<forall>v\\<in>V - (wl - {v}). \\<forall>p. is_path v0 p v \n        \\<longrightarrow> path_weight' (res' v) \\<le> Num (path_weight p)\"\n      proof (intro allI ballI impI)\n        fix v' p\n        assume NOT_IN_WL: \"v' \\<in> V - (wl - {v})\" \n          and PATH: \"is_path v0 p v'\"\n        hence [simp, intro!]: \"v'\\<in>V\" by auto\n        from bspec[OF CONSIDERED_NEW_PATHS, of v']\n        have \"path_weight' (res' v') \\<le> path_weight' (res v')\"\n          by (auto dest: least_map_leD)\n        also from bspec[OF RES_MIN NOT_IN_WL] PATH \n        have \"path_weight' (res v') \\<le> Num (path_weight p)\" by blast\n        finally show \"path_weight' (res' v') \\<le> Num (path_weight p)\" .\n      qed\n\n      txt {*\n        Finally, we have to show that for nodes on the worklist,\n        the stored paths are not longer than any path using only nodes not\n        on the worklist. Compared to the situation before the step, those\n        path may also use the node @{text v}.\n        *}\n      show \"\\<forall>va\\<in>wl - {v}. \\<forall>p. \n        is_path v0 p va \\<and> int_vertices p \\<subseteq> V - (wl - {v}) \n        \\<longrightarrow> path_weight' (res' va) \\<le> Num (path_weight p)\"\n      proof (intro allI impI ballI, elim conjE)\n        fix v' p\n        assume IWS: \"v'\\<in>wl - {v}\" \n          and PATH: \"is_path v0 p v'\" \n          and VERTICES: \"int_vertices p \\<subseteq> V - (wl - {v})\"\n        from IWS WL_SUBSET have [simp, intro!]: \"v'\\<in>V\" by auto\n        \n        {\n          txt {*\n            If the path is empty, the proposition follows easily from the\n            invariant for the original states, as no intermediate nodes are \n            used at all.\n            *}\n          assume [simp]: \"p=[]\"\n          from bspec[OF CONSIDERED_NEW_PATHS, of v'] have\n            \"path_weight' (res' v') \\<le> path_weight' (res v')\"\n            using IWS WL_SUBSET by (auto dest: least_map_leD)\n          also have \"int_vertices p \\<subseteq> V-wl\" by auto\n          with WL_MIN IWS PATH \n          have \"path_weight' (res v') \\<le> Num (path_weight p)\"\n            by (auto simp del: path_weight_empty)\n          finally have \"path_weight' (res' v') \\<le> Num (path_weight p)\" .\n        } moreover {\n          fix p1 u w\n          assume [simp]: \"p = p1@[(u,w,v')]\"\n          txt {* If the path is not empty, we pick the last but one vertex, and\n            call it @{term u}.*}\n          from PATH have PATH1: \"is_path v0 p1 u\" and EDGE: \"(u,w,v')\\<in>E\" by auto\n          from VERTICES have NIV: \"u\\<in>V - (wl-{v})\" by simp\n          hence U_MEM[simp]: \"u\\<in>V\" by auto\n\n          txt {* From @{thm [source] RES_MIN}, we know that @{term \"res u\"} holds\n            the shortest path to @{term u}. Thus @{text p} is longer than the \n            path that is constructed by replacing the prefix of @{term p} by \n            {term \"res u\"}*}\n          from NIV RES_MIN PATH1 \n          have G: \"Num (path_weight p1) \\<ge> path_weight' (res u)\" by simp\n          then obtain pu where [simp]: \"res u = Some pu\" \n            by (cases \"res u\") (auto simp: infty_unbox)\n          from G have \"Num (path_weight p) \\<ge> path_weight' (res u) + Num w\"\n            by (auto simp: infty_unbox add_right_mono)\n          also \n          have \"path_weight' (res u) + Num w \\<ge> path_weight' (res' v')\"\n            txt {*\n              The remaining argument depends on wether @{term u} \n              equals @{term v}. \n              In the case @{term \"u\\<noteq>v\"}, all vertices of @{term \"res u\"} are\n              outside the original workset. Thus, appending the edge \n              @{term \"(u,w,v')\"} to @{term \"res u\"} yields a path to @{term v}\n              over intermediate nodes only outside the workset. By the invariant\n              for the original state, @{term \"res v'\"} is shorter than this path.\n              As a step does not replace paths by longer ones, also \n              @{term \"res' v'\"} is shorter.\n\n              In the case @{term \"u=v\"}, the step has\n              considered the path to @{text v'} over @{text v}, and thus the\n              result path is not longer.\n              *}\n          proof (cases \"u=v\")\n            assume \"u\\<noteq>v\"\n            with NIV have NIV': \"u\\<in>V-wl\" by auto\n            from bspec[OF PATH_VALID U_MEM] NIV'\n            have \"is_path v0 pu u\" and VU: \"int_vertices (pu@[(u,w,v')]) \\<subseteq> V-wl\" \n              by auto\n            with EDGE have PV': \"is_path v0 (pu@[(u,w,v')]) v'\" by auto\n            with bspec[OF WL_MIN, of v'] IWS VU have \n              \"path_weight' (res v') \\<le> Num (path_weight (pu@[(u,w,v')]))\"\n              by blast\n            hence \"path_weight' (res u) + Num w \\<ge> path_weight' (res v')\"\n              by (auto simp: infty_unbox)\n            also from CONSIDERED_NEW_PATHS have \n              \"path_weight' (res v') \\<ge> path_weight' (res' v')\"\n              by (auto dest: least_map_leD)\n            finally (order_trans[rotated]) show ?thesis .\n          next\n            assume [symmetric,simp]: \"u=v\"\n            from CONSIDERED_NEW_PATHS EDGE have \n              \"path_weight' (res' v') \\<le> path_weight' (Some (pu@[(v,w,v')]))\"\n              by (rule_tac least_map_leD) auto\n            thus ?thesis by (auto simp: infty_unbox)\n          qed\n          finally (order_trans[rotated]) have \n            \"path_weight' (res' v') \\<le> Num (path_weight p)\" .\n        } ultimately show \"path_weight' (res' v') \\<le> Num (path_weight p)\"\n          using PATH apply (cases p rule: rev_cases) by auto\n      qed\n    qed\n  qed\n\n  subsection {* Structural Refinement of Update *}\n  text {*\n    Now that we have proved correct the initial version of the algorithm, we start\n    refinement towards an efficient implementation.\n    *}\n\n  text {*\n    First, the update function is refined to iterate over each successor of the\n    selected node, and update the result on demand.\n    *}\n  definition uinvar \n    :: \"'V \\<Rightarrow> 'V set \\<Rightarrow> _ \\<Rightarrow> ('W\\<times>'V) set \\<Rightarrow> ('V,'W) state \\<Rightarrow> bool\" where\n    \"uinvar v wl res it \\<sigma> \\<equiv> let (wl',res')=\\<sigma> in wl'=wl \n    \\<and> (\\<forall>v'\\<in>V. \n      res' v' \\<in> least_map path_weight' (\n        { res v' } \\<union> { Some (p@[(v,w,v')]) | p w. res v = Some p \n          \\<and> (w,v') \\<in> succ G v - it }\n      ))\n    \\<and> (\\<forall>v'\\<in>V. \\<forall>p. res' v' = Some p \\<longrightarrow> is_path v0 p v')\n    \\<and> res' v = res v\n    \"\n\n  definition update' :: \"'V \\<Rightarrow> ('V,'W) state \\<Rightarrow> ('V,'W) state nres\" where \n    \"update' v \\<sigma> \\<equiv> do {\n      ASSERT (update_pre v \\<sigma>);\n      let (wl,res) = \\<sigma>;\n      let wv = path_weight' (res v);\n      let pv = res v;\n      FOREACH\\<^bsup>uinvar v wl res\\<^esup> (succ G v) (\\<lambda>(w',v') (wl,res). \n        if (wv + Num w' < path_weight' (res v')) then do {\n            ASSERT (v'\\<in>wl \\<and> pv\\<noteq>None); \n            RETURN (wl,res(v' \\<mapsto> the pv@[(v,w',v')]))\n        } else RETURN (wl,res)\n      ) (wl,res)}\"\n\n  lemma update'_refines:\n    assumes \"v'=v\" and \"\\<sigma>'=\\<sigma>\"\n    shows \"update' v' \\<sigma>' \\<le> \\<Down>Id (update v \\<sigma>)\"\n    apply (simp only: assms)\n    unfolding update'_def update_def\n    apply (refine_rcg refine_vcg)\n\n    (*apply (intro refine_vcg conjI)*)\n    apply (simp_all only: singleton_iff)\n  proof -\n    fix wl res\n    assume \"update_pre v (wl,res)\"\n    thus \"uinvar v wl res (succ G v) (wl,res)\"\n      by (simp add: uinvar_def update_pre_def)\n  next\n\n    fix wl res it wl' res' v' w'\n    assume PRE: \"update_pre v (wl,res)\"\n    assume INV: \"uinvar v wl res it (wl',res')\"\n    assume MEM: \"(w',v')\\<in>it\" \n    assume IT_SS: \"it\\<subseteq> succ G v\"\n    assume LESS: \"path_weight' (res v) + Num w' < path_weight' (res' v')\"\n\n    from PRE have [simp, intro!]: \"v\\<in>V\" by (simp add: update_pre_def)\n\n    from MEM IT_SS have [simp,intro!]: \"v'\\<in>V\" using succ_subset\n      by auto\n\n    from LESS obtain pv where [simp]: \"res v = Some pv\"\n      by (cases \"res v\") auto\n\n    thus \"res v \\<noteq> None\" by simp\n\n    have [simp]: \"wl'=wl\" and [simp]: \"res' v = res v\" \n      using INV unfolding uinvar_def by auto\n\n    from MEM IT_SS have EDGE[simp]: \"(v,w',v')\\<in>E\" \n      unfolding succ_def by auto\n    with INV have [simp]: \"is_path v0 pv v\"\n      unfolding uinvar_def by auto\n\n    have \"0\\<le>w'\" by (rule nonneg_weights[OF EDGE])\n    hence [simp]: \"v'\\<noteq>v\" using LESS\n      by auto\n    hence [simp]: \"v\\<noteq>v'\" by blast\n\n    show [simp]: \"v'\\<in>wl'\" proof (rule ccontr)\n      assume [simp]: \"v'\\<notin>wl'\"\n      hence [simp]: \"v'\\<in>V-wl\" and [simp]: \"v'\\<notin>wl\" by auto\n      note LESS\n      also\n      from INV have \"path_weight' (res' v') \\<le> path_weight' (res v')\"\n        unfolding uinvar_def by (auto dest: least_map_leD)      \n      also\n      from PRE have PW: \"\\<And>p. is_path v0 p v' \\<Longrightarrow> \n        path_weight' (res v') \\<le> path_weight' (Some p)\"\n        unfolding update_pre_def \n        by auto\n      have P: \"is_path v0 (pv@[(v,w',v')]) v'\" by simp\n      from PW[OF P] have \n        \"path_weight' (res v') \\<le> Num (path_weight (pv@[(v,w',v')]))\"\n        by auto\n      finally show False by (simp add: infty_unbox)\n    qed\n\n    show \"uinvar v wl res (it-{(w',v')}) (wl',res'(v'\\<mapsto>the (res v)@[(v,w',v')]))\"\n    proof -\n      have \"(res'(v'\\<mapsto>the (res v)@[(v,w',v')])) v = res' v\" by simp\n      moreover {\n        fix v'' assume VMEM: \"v''\\<in>V\"\n        have \"(res'(v'\\<mapsto>the (res v)@[(v,w',v')])) v'' \\<in> least_map path_weight' (\n          { res v'' } \\<union> { Some (p@[(v,w,v'')]) | p w. res v = Some p \n          \\<and> (w,v'') \\<in> succ G v - (it - {(w',v')}) }\n          ) \\<and> (\\<forall>p. (res'(v'\\<mapsto>the (res v)@[(v,w',v')])) v'' = Some p \n                \\<longrightarrow> is_path v0 p v'')\"\n        proof (cases \"v''=v'\")\n          case False[simp]\n          have \"{ Some (p@[(v,w,v'')]) | p w. res v = Some p \n          \\<and> (w,v'') \\<in> succ G v - (it - {(w',v')}) } = \n            { Some (p@[(v,w,v'')]) | p w. res v = Some p \n          \\<and> (w,v'') \\<in> succ G v - it }\"\n            by auto\n          with INV VMEM show ?thesis unfolding uinvar_def \n            by simp\n        next\n          case True[simp]\n          have EQ: \"{ res v'' } \\<union> { Some (p@[(v,w,v'')]) | p w. res v = Some p \n          \\<and> (w,v'') \\<in> succ G v - (it - {(w',v')}) } =\n          insert (Some (pv@[(v,w',v')])) (\n            { res v'' } \\<union> { Some (p@[(v,w,v'')]) | p w. res v = Some p \n          \\<and> (w,v'') \\<in> succ G v - it })\"\n            using MEM IT_SS\n            by auto\n          show ?thesis\n            apply (subst EQ)\n            apply simp\n            apply (rule least_map_insert_min)\n            apply (rule ballI)\n          proof -\n            fix r'\n            assume A: \n              \"r' \\<in> insert (res v') \n               {Some (pv @ [(v, w, v')]) |w. (w, v') \\<in> succ G v \\<and> (w, v') \\<notin> it}\"\n\n            from LESS have \n              \"path_weight' (Some (pv @ [(v, w', v')])) < path_weight' (res' v')\"\n              by (auto simp: infty_unbox)\n            also from INV[unfolded uinvar_def] have \n              \"res' v' \\<in> least_map path_weight' (\n                insert (res v') \n                {Some (pv @ [(v, w, v')]) |w. (w, v') \\<in> succ G v \\<and> (w, v') \\<notin> it}\n              )\"\n              by auto\n            with A have \"path_weight' (res' v') \\<le> path_weight' r'\"\n              by (auto dest: least_map_leD)\n            finally show \n              \"path_weight' (Some (pv @ [(v, w', v')])) \\<le> path_weight' r'\"\n              by simp\n          qed\n        qed\n      }\n      ultimately show ?thesis\n        unfolding uinvar_def Let_def \n        by auto\n    qed\n  next\n    fix wl res it w' v' wl' res'\n    assume INV: \"uinvar v wl res it (wl',res')\"\n    and NLESS: \"\\<not> path_weight' (res v) + Num w' < path_weight' (res' v')\"\n    and IN_IT: \"(w',v')\\<in>it\"\n    and IT_SS: \"it \\<subseteq> succ G v\"\n\n    from IN_IT IT_SS have [simp, intro!]: \"(w',v')\\<in>succ G v\" by auto\n    hence [simp,intro!]: \"v'\\<in>V\" using succ_subset\n      by auto\n\n    show \"uinvar v wl res (it - {(w',v')}) (wl',res')\"\n    proof (cases \"res v\")\n      case None [simp]\n      from INV show ?thesis\n        unfolding uinvar_def by auto\n    next\n      case (Some p) [simp]\n      {\n        fix v''\n        assume [simp, intro!]: \"v''\\<in>V\"\n        have \"res' v'' \\<in> least_map path_weight' (\n          { res v'' } \\<union> { Some (p@[(v,w,v'')]) | p w. res v = Some p \n          \\<and> (w,v'') \\<in> succ G v - (it - {(w',v')}) }\n          )\" (is \"_ \\<in> least_map path_weight' ?S\")\n        proof (cases \"v''=v'\")\n          case False with INV show ?thesis\n            unfolding uinvar_def by auto\n        next\n          case True[simp]\n          \n          have EQ: \"?S = insert (Some (p@[(v,w',v')])) (\n            { res v' } \\<union> { Some (p@[(v,w,v'')]) | p w. res v = Some p \n                            \\<and> (w,v'') \\<in> succ G v - it }\n            )\"\n            by auto\n          from NLESS have \n            \"path_weight' (res' v') \\<le> path_weight' (Some (p@[(v,w',v')]))\"\n            by (auto simp: infty_unbox)\n          thus ?thesis\n            apply (subst EQ)\n            apply (rule least_map_insert_nmin)\n            using INV unfolding uinvar_def apply auto []\n            apply simp\n            done\n        qed\n      } with INV\n      show ?thesis\n        unfolding uinvar_def by auto\n    qed\n  next\n    fix wl res \\<sigma>'\n\n    assume \"uinvar v wl res {} \\<sigma>'\" \n    thus \"update_spec v (wl,res) \\<sigma>'\"\n      unfolding uinvar_def\n      apply (cases \\<sigma>')\n      apply (auto intro: update_spec.intros simp: succ_def)\n      done\n  next\n    show \"finite (succ G v)\" by simp\n  qed\n\n  text {* We integrate the new update function into the main algorithm: *}\n  definition dijkstra' where\n    \"dijkstra' \\<equiv> do {\n      \\<sigma>0 \\<leftarrow> dinit; \n      (_,res) \\<leftarrow> WHILE\\<^sub>T\\<^bsup>dinvar\\<^esup> (\\<lambda>(wl,_). wl\\<noteq>{}) \n            (\\<lambda>\\<sigma>. do {(v,\\<sigma>') \\<leftarrow> pop_min \\<sigma>; update' v \\<sigma>'})\n            \\<sigma>0;\n      RETURN res\n    }\"\n\n\n  lemma dijkstra'_refines: \"dijkstra' \\<le> \\<Down>Id dijkstra\"\n  proof -\n    note [refine] = update'_refines\n    have [refine]: \"\\<And>\\<sigma> \\<sigma>'. \\<sigma>=\\<sigma>' \\<Longrightarrow> pop_min \\<sigma> \\<le> \\<Down>Id (pop_min \\<sigma>')\" by simp\n    show ?thesis\n      unfolding dijkstra_def dijkstra'_def\n      apply (refine_rcg)\n      apply simp_all\n      done\n  qed\nend\n\nsubsection {* Refinement to Cached Weights *}\ntext {*\n  Next, we refine the data types of the workset and the result map.\n  The workset becomes a map from nodes to their current weights.\n  The result map stores, in addition to the shortest path, also the\n  weight of the shortest path. Moreover, we store the shortest paths\n  in reversed order, which makes appending new edges more effcient.\n\n  These refinements allow to implement the workset as a priority queue,\n  and save recomputation of the path weights in the inner loop of the\n  algorithm.\n*}\n\ntype_synonym ('V,'W) mwl = \"('V \\<rightharpoonup> 'W infty)\"\ntype_synonym ('V,'W) mres = \"('V \\<rightharpoonup> (('V,'W) path \\<times> 'W))\"\ntype_synonym ('V,'W) mstate = \"('V,'W) mwl \\<times> ('V,'W) mres\"\n\ntext {*\n  Map a path with cached weight to one without cached weight.\n*}\nfun mpath' :: \"(('V,'W) path \\<times> 'W) option \\<rightharpoonup> ('V,'W) path\" where\n  \"mpath' None = None\" |\n  \"mpath' (Some (p,w)) = Some p\"\n\nfun mpath_weight' :: \"(('V,'W) path \\<times> 'W) option \\<Rightarrow> ('W::weight) infty\" where\n  \"mpath_weight' None = top\" |\n  \"mpath_weight' (Some (p,w)) = Num w\"\n\ncontext Dijkstra\nbegin\n  definition \\<alpha>w::\"('V,'W) mwl \\<Rightarrow> 'V set\" where \"\\<alpha>w \\<equiv> dom\"\n  definition \\<alpha>r::\"('V,'W) mres \\<Rightarrow> 'V \\<rightharpoonup> ('V,'W) path\" where \n    \"\\<alpha>r \\<equiv> \\<lambda>res v. case res v of None \\<Rightarrow> None | Some (p,w) \\<Rightarrow> Some (rev p)\"\n  definition \\<alpha>s:: \"('V,'W) mstate \\<Rightarrow> ('V,'W) state\" where\n    \"\\<alpha>s \\<equiv> map_prod \\<alpha>w \\<alpha>r\"\n\n  text {* Additional invariants for the new state. They guarantee that\n    the cached weights are consistent.*}\n  definition res_invarm :: \"('V \\<rightharpoonup> (('V,'W) path\\<times>'W)) \\<Rightarrow> bool\" where\n    \"res_invarm res \\<equiv> (\\<forall>v. case res v of \n        None \\<Rightarrow> True | \n        Some (p,w) \\<Rightarrow> w = path_weight (rev p))\"\n  definition dinvarm :: \"('V,'W) mstate \\<Rightarrow> bool\" where\n    \"dinvarm \\<sigma> \\<equiv> let (wl,res) = \\<sigma> in\n      (\\<forall>v\\<in>dom wl. the (wl v) = mpath_weight' (res v)) \\<and> res_invarm res\n    \"\n  lemma mpath_weight'_correct: \"\\<lbrakk>dinvarm (wl,res)\\<rbrakk> \\<Longrightarrow>\n    mpath_weight' (res v) = path_weight' (\\<alpha>r res v)\n    \"\n    unfolding dinvarm_def res_invarm_def \\<alpha>r_def\n    by (auto split: option.split option.split_asm)\n\n  lemma mpath'_correct: \"\\<lbrakk>dinvarm (wl,res)\\<rbrakk> \\<Longrightarrow>\n    mpath' (res v) = map_option rev (\\<alpha>r res v)\"\n    unfolding dinvarm_def \\<alpha>r_def\n    by (auto split: option.split option.split_asm)\n\n  lemma wl_weight_correct:\n    assumes INV: \"dinvarm (wl,res)\" \n    assumes WLV: \"wl v = Some w\" \n    shows \"path_weight' (\\<alpha>r res v) = w\"\n  proof -\n    from INV WLV have \"w = mpath_weight' (res v)\"\n      unfolding dinvarm_def by force\n    also from mpath_weight'_correct[OF INV] have \n      \"\\<dots> = path_weight' (\\<alpha>r res v)\" .\n    finally show ?thesis by simp\n  qed\n\n  text {* The initial state is constructed using an iterator: *}\n  definition mdinit :: \"('V,'W) mstate nres\" where\n    \"mdinit \\<equiv> do {\n      wl \\<leftarrow> FOREACH V (\\<lambda>v wl. RETURN (wl(v\\<mapsto>Infty))) Map.empty;\n      RETURN (wl(v0\\<mapsto>Num 0),[v0 \\<mapsto> ([],0)])\n    }\"\n\n  lemma mdinit_refines: \"mdinit \\<le> \\<Down>(build_rel \\<alpha>s dinvarm) dinit\"\n    unfolding mdinit_def dinit_def\n    apply (rule build_rel_SPEC)\n    apply (intro FOREACH_rule[where I=\"\\<lambda>it wl. (\\<forall>v\\<in>V-it. wl v = Some Infty) \\<and> \n      dom wl = V-it\"]\n           refine_vcg)\n    apply (auto \n      simp: \\<alpha>s_def \\<alpha>w_def \\<alpha>r_def dinvarm_def res_invarm_def infty_unbox\n      split: split_if_asm\n    )\n    done\n\n  text {* The new pop function: *}\n  definition \n    mpop_min :: \"('V,'W) mstate \\<Rightarrow> ('V \\<times> 'W infty \\<times> ('V,'W) mstate) nres\" \n    where\n    \"mpop_min \\<sigma> \\<equiv> do {\n      let (wl,res) = \\<sigma>; \n      (v,w,wl')\\<leftarrow>prio_pop_min wl;\n      RETURN (v,w,(wl',res))\n    }\"\n    \n  lemma mpop_min_refines:\n    \"\\<lbrakk> (\\<sigma>,\\<sigma>') \\<in> build_rel \\<alpha>s dinvarm \\<rbrakk> \\<Longrightarrow> \n      mpop_min \\<sigma> \\<le> \n       \\<Down>(build_rel \n          (\\<lambda>(v,w,\\<sigma>). (v,\\<alpha>s \\<sigma>)) \n          (\\<lambda>(v,w,\\<sigma>). dinvarm \\<sigma> \\<and> w = mpath_weight' (snd \\<sigma> v)))\n      (pop_min \\<sigma>')\"\n    -- \"The two algorithms are structurally different, so we use the\n      nofail/inres method to prove refinement.\"\n    unfolding mpop_min_def pop_min_def prio_pop_min_def\n\n    apply (rule pw_ref_svI)\n    apply rule\n    apply (auto simp add: refine_pw_simps \\<alpha>s_def \\<alpha>w_def refine_rel_defs\n      split: prod.split prod.split_asm)\n\n    apply (auto simp: dinvarm_def) []\n\n    apply (auto simp: mpath_weight'_correct wl_weight_correct) []\n\n    apply (auto \n      simp: wl_weight_correct \n      intro!: least_map.intros\n    ) []\n    done\n\n  text {* The new update function: *}\n  definition \"uinvarm v wl res it \\<sigma> \\<equiv> \n    uinvar v wl res it (\\<alpha>s \\<sigma>) \\<and> dinvarm \\<sigma>\"\n\n  definition mupdate :: \"'V \\<Rightarrow> 'W infty \\<Rightarrow> ('V,'W) mstate \\<Rightarrow> ('V,'W) mstate nres\"\n   where \n    \"mupdate v wv \\<sigma> \\<equiv> do {\n      ASSERT (update_pre v (\\<alpha>s \\<sigma>) \\<and> wv=mpath_weight' (snd \\<sigma> v));\n      let (wl,res) = \\<sigma>;\n      let pv = mpath' (res v);\n      FOREACH\\<^bsup>uinvarm v (\\<alpha>w wl) (\\<alpha>r res)\\<^esup> (succ G v) (\\<lambda>(w',v') (wl,res). \n        if (wv + Num w' < mpath_weight' (res v')) then do {\n          ASSERT (v'\\<in>dom wl \\<and> pv \\<noteq> None);\n          ASSERT (wv \\<noteq> Infty);\n          RETURN (wl(v'\\<mapsto>wv + Num w'),\n                    res(v' \\<mapsto> ((v,w',v')#the pv,val wv + w') ))\n        } else RETURN (wl,res)\n        ) (wl,res)\n    }\"\n\n  lemma mupdate_refines: \n    assumes SREF: \"(\\<sigma>,\\<sigma>')\\<in>build_rel \\<alpha>s dinvarm\"\n    assumes WV: \"wv = mpath_weight' (snd \\<sigma> v)\"\n    assumes VV': \"v'=v\"\n    shows \"mupdate v wv \\<sigma> \\<le> \\<Down>(build_rel \\<alpha>s dinvarm) (update' v' \\<sigma>')\"\n  proof (simp only: VV')\n    {\n      txt {* Show that IF-condition is a refinement: *}\n      fix wl res wl' res' it w' v'\n      assume \"uinvarm v (\\<alpha>w wl) (\\<alpha>r res) it (wl',res')\" \n        and \"dinvarm (wl,res)\"\n      hence \"mpath_weight' (res v) + Num w' < mpath_weight' (res' v') \\<longleftrightarrow>\n        path_weight' (\\<alpha>r res v) + Num w' < path_weight' (\\<alpha>r res' v')\"\n        unfolding uinvarm_def\n        by (auto simp add: mpath_weight'_correct)\n    } note COND_refine=this\n\n    {\n      txt {* THEN-case: *}\n      fix wl res wl' res' it w' v'\n      assume UINV: \"uinvarm v (\\<alpha>w wl) (\\<alpha>r res) it (wl',res')\"\n        and DINV: \"dinvarm (wl,res)\"\n        and \"mpath_weight' (res v) + Num w' < mpath_weight' (res' v')\"\n        and \"path_weight' (\\<alpha>r res v) + Num w' < path_weight' (\\<alpha>r res' v')\"\n        and V'MEM: \"v'\\<in>\\<alpha>w wl'\"\n        and NN: \"\\<alpha>r res v \\<noteq> None\"\n    \n      from NN obtain pv wv where\n        ARV: \"\\<alpha>r res v = Some (rev pv)\" and\n        RV: \"res v = Some (pv,wv)\" \n        unfolding \\<alpha>r_def by (auto split: option.split_asm)\n\n      with DINV have [simp]: \"wv = path_weight (rev pv)\"\n        unfolding dinvarm_def res_invarm_def by (auto split: option.split_asm)\n      \n      note [simp] = ARV RV\n\n      from V'MEM NN have \"v'\\<in>dom wl'\" (is \"?G1\") \n        and \"mpath' (res v) \\<noteq> None\" (is \"?G2\") \n        unfolding \\<alpha>w_def \\<alpha>r_def by (auto split: option.split_asm)\n    \n      hence \"\\<And>x. \\<alpha>w wl' = \\<alpha>w (wl'(v'\\<mapsto>x))\" by (auto simp: \\<alpha>w_def)\n      moreover have \"mpath' (res v) = map_option rev (\\<alpha>r res v)\" using DINV \n        by (simp add: mpath'_correct)\n      ultimately have\n        \"\\<alpha>w wl' = \\<alpha>w (wl'(v' \\<mapsto> mpath_weight' (res v) + Num w')) \n        \\<and> (\\<alpha>r res')(v' \\<mapsto> the (\\<alpha>r res v)@[(v, w', v')]) \n           = \\<alpha>r (res'(v' \\<mapsto> ((v, w', v')#the (mpath' (res v)), \n                 val (mpath_weight' (res v)) + w')))\" (is ?G3)\n        by (auto simp add: \\<alpha>r_def intro!: ext)\n      have\n        \"(dinvarm (wl'(v'\\<mapsto>mpath_weight' (res v) + Num w'),\n                           res'(v' \\<mapsto> ((v,w',v') # the (mpath' (res v)),\n                                       val (mpath_weight' (res v)) + w'\n                                      ))))\" (is ?G4)\n        using UINV unfolding uinvarm_def dinvarm_def res_invarm_def\n        by (auto simp: infty_unbox split: option.split option.split_asm)\n      note `?G1` `?G2` `?G3` `?G4`\n    } note THEN_refine=this\n\n\n    note [refine2] = inj_on_id\n\n    note [simp] = refine_rel_defs\n\n    show \"mupdate v wv \\<sigma> \\<le> \\<Down>(build_rel \\<alpha>s dinvarm) (update' v \\<sigma>')\" \n      using SREF WV\n      unfolding mupdate_def update'_def\n      apply -\n\n      apply (refine_rcg)\n\n      apply simp_all [3]\n      apply (simp add: \\<alpha>s_def uinvarm_def)\n      apply (simp_all add: \\<alpha>s_def COND_refine THEN_refine(1-2)) [3]\n      apply (rule ccontr,simp)\n      using THEN_refine(3,4)\n      apply (auto simp: \\<alpha>s_def) []\n      txt {*The ELSE-case is trivial:*}\n      apply simp\n      done\n  qed\n\n  text {* Finally, we assemble the refined algorithm: *}\n  definition mdijkstra where\n    \"mdijkstra \\<equiv> do {\n      \\<sigma>0 \\<leftarrow> mdinit; \n      (_,res) \\<leftarrow> WHILE\\<^sub>T\\<^bsup>dinvarm\\<^esup> (\\<lambda>(wl,_). dom wl\\<noteq>{}) \n            (\\<lambda>\\<sigma>. do { (v,wv,\\<sigma>') \\<leftarrow> mpop_min \\<sigma>; mupdate v wv \\<sigma>' } )\n            \\<sigma>0;\n      RETURN res\n    }\"\n\n  lemma mdijkstra_refines: \"mdijkstra \\<le> \\<Down>(build_rel \\<alpha>r res_invarm) dijkstra'\"\n  proof -\n    note [refine] = mdinit_refines mpop_min_refines mupdate_refines\n    show ?thesis\n      unfolding mdijkstra_def dijkstra'_def\n      apply (refine_rcg)\n      apply (simp_all split: prod.split\n        add: \\<alpha>s_def \\<alpha>w_def dinvarm_def refine_rel_defs)\n      done\n  qed\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/Dijkstra_Shortest_Path/Dijkstra.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8558511396138365, "lm_q2_score": 0.8198933315126791, "lm_q1q2_score": 0.7017066421369115}}
{"text": "(* Title:  Rtrancl_On.thy\n   Author: Lars Noschinski, TU M\u00fcnchen\n   Author: Ren\u00e9 Neumann, TU M\u00fcnchen\n*)\n\ntheory Rtrancl_On\nimports Main\nbegin\n\nsection \\<open>Reflexive-Transitive Closure on a Domain\\<close>\n\ntext \\<open>\n  In this section we introduce a variant of the reflexive-transitive closure\n  of a relation which is useful to formalize the reachability relation on\n  digraphs.\n\\<close>\n\ninductive_set\n  rtrancl_on :: \"'a set \\<Rightarrow> 'a rel \\<Rightarrow> 'a rel\"\n  for F :: \"'a set\" and r :: \"'a rel\"\nwhere\n    rtrancl_on_refl [intro!, Pure.intro!, simp]: \"a \\<in> F \\<Longrightarrow> (a, a) \\<in> rtrancl_on F r\"\n  | rtrancl_on_into_rtrancl_on [Pure.intro]:\n      \"(a, b) \\<in> rtrancl_on F r  \\<Longrightarrow> (b, c) \\<in> r \\<Longrightarrow> c \\<in> F\n      \\<Longrightarrow> (a, c) \\<in> rtrancl_on F r\"\n\ndefinition symcl :: \"'a rel \\<Rightarrow> 'a rel\" (\"(_\\<^sup>s)\" [1000] 999) where\n  \"symcl R = R \\<union> (\\<lambda>(a,b). (b,a)) ` R\"\n\nlemma in_rtrancl_on_in_F:\n  assumes \"(a,b) \\<in> rtrancl_on F r\" shows \"a \\<in> F\" \"b \\<in> F\"\n  using assms by induct auto\n\nlemma rtrancl_on_induct[consumes 1, case_names base step, induct set: rtrancl_on]:\n  assumes \"(a, b) \\<in> rtrancl_on F r\"\n    and \"a \\<in> F \\<Longrightarrow> P a\"\n        \"\\<And>y z. \\<lbrakk>(a, y) \\<in> rtrancl_on F r; (y,z) \\<in> r; y \\<in> F; z \\<in> F; P y\\<rbrakk> \\<Longrightarrow> P z\"\n  shows \"P b\"\n  using assms by (induct a b) (auto dest: in_rtrancl_on_in_F)\n\nlemma rtrancl_on_trans:\n  assumes \"(a,b) \\<in> rtrancl_on F r\" \"(b,c) \\<in> rtrancl_on F r\" shows \"(a,c) \\<in> rtrancl_on F r\"\n  using assms(2,1)\n  by induct (auto intro: rtrancl_on_into_rtrancl_on)\n\nlemma converse_rtrancl_on_into_rtrancl_on:\n  assumes \"(a,b) \\<in> r\" \"(b, c) \\<in> rtrancl_on F r\" \"a \\<in> F\"\n  shows \"(a, c) \\<in> rtrancl_on F r\"\nproof -\n  have \"b \\<in> F\" using \\<open>(b,c) \\<in> _\\<close> by (rule in_rtrancl_on_in_F)\n  show ?thesis\n    apply (rule rtrancl_on_trans)\n    apply (rule rtrancl_on_into_rtrancl_on)\n    apply (rule rtrancl_on_refl)\n    by fact+\nqed\n\nlemma rtrancl_on_converseI:\n  assumes \"(y, x) \\<in> rtrancl_on F r\" shows \"(x, y) \\<in> rtrancl_on F (r\\<inverse>)\"\n  using assms\nproof induct\n  case (step a b)\n  then have \"(b,b) \\<in> rtrancl_on F (r\\<inverse>)\" \"(b,a) \\<in> r\\<inverse>\" by auto\n  then show ?case using step\n    by (metis rtrancl_on_trans rtrancl_on_into_rtrancl_on)\nqed auto\n\ntheorem rtrancl_on_converseD:\n  assumes \"(y, x) \\<in> rtrancl_on F (r\\<inverse>)\" shows \"(x, y) \\<in> rtrancl_on F r\"\n  using assms by - (drule rtrancl_on_converseI, simp)\n\nlemma converse_rtrancl_on_induct[consumes 1, case_names base step, induct set: rtrancl_on]:\n  assumes major: \"(a, b) \\<in> rtrancl_on F r\"\n    and cases: \"b \\<in> F \\<Longrightarrow> P b\"\n       \"\\<And>x y. \\<lbrakk>(x,y) \\<in> r; (y,b) \\<in> rtrancl_on F r; x \\<in> F; y \\<in> F; P y\\<rbrakk> \\<Longrightarrow> P x\"\n  shows \"P a\"\n  using rtrancl_on_converseI[OF major] cases\n  by induct (auto intro: rtrancl_on_converseD)\n\nlemma converse_rtrancl_on_cases:\n  assumes \"(a, b) \\<in> rtrancl_on F r\"\n  obtains (base) \"a = b\" \"b \\<in> F\"\n    | (step) c where \"(a,c) \\<in> r\" \"(c,b) \\<in> rtrancl_on F r\"\n  using assms by induct auto\n\nlemma rtrancl_on_sym:\n  assumes \"sym r\" shows \"sym (rtrancl_on F r)\"\nusing assms by (auto simp: sym_conv_converse_eq intro: symI dest: rtrancl_on_converseI)\n\nlemma rtrancl_on_mono:\n  assumes \"s \\<subseteq> r\" \"F \\<subseteq> G\" \"(a,b) \\<in> rtrancl_on F s\" shows \"(a,b) \\<in> rtrancl_on G r\"\n  using assms(3,1,2)\nproof induct\n  case (step x y) show ?case\n    using step assms by (intro converse_rtrancl_on_into_rtrancl_on[OF _ step(5)]) auto\nqed auto\n\nlemma rtrancl_consistent_rtrancl_on:\n  assumes \"(a,b) \\<in> r\\<^sup>*\"\n  and \"a \\<in> F\" \"b \\<in> F\"\n  and consistent: \"\\<And>a b. \\<lbrakk> a \\<in> F; (a,b) \\<in> r \\<rbrakk> \\<Longrightarrow> b \\<in> F\"\n  shows \"(a,b) \\<in> rtrancl_on F r\"\n  using assms(1-3)\nproof (induction rule: converse_rtrancl_induct)\n  case (step y z) then have \"z \\<in> F\" by (rule_tac consistent) simp\n  with step have \"(z,b) \\<in> rtrancl_on F r\" by simp\n  with step.prems \\<open>(y,z) \\<in> r\\<close> \\<open>z \\<in> F\\<close> show ?case\n    using converse_rtrancl_on_into_rtrancl_on\n    by metis\nqed simp\n\nlemma rtrancl_on_rtranclI:\n  \"(a,b) \\<in> rtrancl_on F r \\<Longrightarrow> (a,b) \\<in> r\\<^sup>*\"\n  by (induct rule: rtrancl_on_induct) simp_all\n\nlemma rtrancl_on_sub_rtrancl:\n  \"rtrancl_on F r \\<subseteq> r^*\"\n  using rtrancl_on_rtranclI\n  by auto\n\n\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/Rtrancl_On.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8376199714402813, "lm_q2_score": 0.8376199653600372, "lm_q1q2_score": 0.7016072114626838}}
{"text": "theory Isolated\n  imports \"HOL-Analysis.Elementary_Metric_Spaces\"\n\nbegin\n\nsubsection \\<open>Isolate and discrete\\<close>\n\ndefinition (in topological_space) isolated_in:: \"'a \\<Rightarrow> 'a set \\<Rightarrow> bool\"  (infixr \"isolated'_in\" 60)\n  where \"x isolated_in S \\<longleftrightarrow> (x\\<in>S \\<and> (\\<exists>T. open T \\<and> T \\<inter> S = {x}))\"\n\ndefinition (in topological_space) discrete:: \"'a set \\<Rightarrow> bool\"\n  where \"discrete S \\<longleftrightarrow> (\\<forall>x\\<in>S. x isolated_in S)\"\n\ndefinition (in metric_space) uniform_discrete :: \"'a set \\<Rightarrow> bool\" where\n  \"uniform_discrete S \\<longleftrightarrow> (\\<exists>e>0. \\<forall>x\\<in>S. \\<forall>y\\<in>S. dist x y < e \\<longrightarrow> x = y)\"\n\nlemma discreteI: \"(\\<And>x. x \\<in> X \\<Longrightarrow> x isolated_in X ) \\<Longrightarrow> discrete X\"\n  unfolding discrete_def by auto\n\nlemma discreteD: \"discrete X \\<Longrightarrow> x \\<in> X \\<Longrightarrow> x isolated_in X \"\n  unfolding discrete_def by auto\n \nlemma uniformI1:\n  assumes \"e>0\" \"\\<And>x y. \\<lbrakk>x\\<in>S;y\\<in>S;dist x y<e\\<rbrakk> \\<Longrightarrow> x =y \"\n  shows \"uniform_discrete S\"\nunfolding uniform_discrete_def using assms by auto\n\nlemma uniformI2:\n  assumes \"e>0\" \"\\<And>x y. \\<lbrakk>x\\<in>S;y\\<in>S;x\\<noteq>y\\<rbrakk> \\<Longrightarrow> dist x y\\<ge>e \"\n  shows \"uniform_discrete S\"\nunfolding uniform_discrete_def using assms not_less by blast\n\nlemma isolated_in_islimpt_iff:\"(x isolated_in S) \\<longleftrightarrow> (\\<not> (x islimpt S) \\<and> x\\<in>S)\"\n  unfolding isolated_in_def islimpt_def by auto\n\nlemma isolated_in_dist_Ex_iff:\n  fixes x::\"'a::metric_space\"\n  shows \"x isolated_in S \\<longleftrightarrow> (x\\<in>S \\<and> (\\<exists>e>0. \\<forall>y\\<in>S. dist x y < e \\<longrightarrow> y=x))\"\nunfolding isolated_in_islimpt_iff islimpt_approachable by (metis dist_commute)\n\nlemma discrete_empty[simp]: \"discrete {}\"\n  unfolding discrete_def by auto\n\nlemma uniform_discrete_empty[simp]: \"uniform_discrete {}\"\n  unfolding uniform_discrete_def by (simp add: gt_ex)\n\nlemma isolated_in_insert:\n  fixes x :: \"'a::t1_space\"\n  shows \"x isolated_in (insert a S) \\<longleftrightarrow> x isolated_in S \\<or> (x=a \\<and> \\<not> (x islimpt S))\"\nby (meson insert_iff islimpt_insert isolated_in_islimpt_iff)\n\nlemma isolated_inI:\n  assumes \"x\\<in>S\" \"open T\" \"T \\<inter> S = {x}\"\n  shows   \"x isolated_in S\"\n  using assms unfolding isolated_in_def by auto\n\nlemma isolated_inE:\n  assumes \"x isolated_in S\"\n  obtains T where \"x \\<in> S\" \"open T\" \"T \\<inter> S = {x}\"\n  using assms that unfolding isolated_in_def by force\n\nlemma isolated_inE_dist:\n  assumes \"x isolated_in S\"\n  obtains d where \"d > 0\" \"\\<And>y. y \\<in> S \\<Longrightarrow> dist x y < d \\<Longrightarrow> y = x\"\n  by (meson assms isolated_in_dist_Ex_iff)\n\nlemma isolated_in_altdef: \n  \"x isolated_in S \\<longleftrightarrow> (x\\<in>S \\<and> eventually (\\<lambda>y. y \\<notin> S) (at x))\"\nproof \n  assume \"x isolated_in S\"\n  from isolated_inE[OF this] \n  obtain T where \"x \\<in> S\" and T:\"open T\" \"T \\<inter> S = {x}\"\n    by metis\n  have \"\\<forall>\\<^sub>F y in nhds x. y \\<in> T\"\n    apply (rule eventually_nhds_in_open)\n    using T by auto\n  then have  \"eventually (\\<lambda>y. y \\<in> T - {x}) (at x)\"\n    unfolding eventually_at_filter by eventually_elim auto\n  then have \"eventually (\\<lambda>y. y \\<notin> S) (at x)\"\n    by eventually_elim (use T in auto)\n  then show \" x \\<in> S \\<and> (\\<forall>\\<^sub>F y in at x. y \\<notin> S)\" using \\<open>x \\<in> S\\<close> by auto\nnext\n  assume \"x \\<in> S \\<and> (\\<forall>\\<^sub>F y in at x. y \\<notin> S)\" \n  then have \"\\<forall>\\<^sub>F y in at x. y \\<notin> S\" \"x\\<in>S\" by auto\n  from this(1) have \"eventually (\\<lambda>y. y \\<notin> S \\<or> y = x) (nhds x)\"\n    unfolding eventually_at_filter by eventually_elim auto\n  then obtain T where T:\"open T\" \"x \\<in> T\" \"(\\<forall>y\\<in>T. y \\<notin> S \\<or> y = x)\" \n    unfolding eventually_nhds by auto\n  with \\<open>x \\<in> S\\<close> have \"T \\<inter> S = {x}\"  \n    by fastforce\n  with \\<open>x\\<in>S\\<close> \\<open>open T\\<close>\n  show \"x isolated_in S\"\n    unfolding isolated_in_def by auto\nqed\n\nlemma discrete_altdef:\n  \"discrete S \\<longleftrightarrow> (\\<forall>x\\<in>S. \\<forall>\\<^sub>F y in at x. y \\<notin> S)\"\n  unfolding discrete_def isolated_in_altdef by auto\n\n(*\nTODO.\nOther than\n\n  uniform_discrete S \\<longrightarrow> discrete S\n  uniform_discrete S \\<longrightarrow> closed S\n\n, we should be able to prove\n\n  discrete S \\<and> closed S \\<longrightarrow> uniform_discrete S\n\nbut the proof (based on Tietze Extension Theorem) seems not very trivial to me. Informal proofs can be found in\n\nhttp://topology.auburn.edu/tp/reprints/v30/tp30120.pdf\nhttp://msp.org/pjm/1959/9-2/pjm-v9-n2-p19-s.pdf\n*)\n\nlemma uniform_discrete_imp_closed:\n  \"uniform_discrete S \\<Longrightarrow> closed S\"\n  by (meson discrete_imp_closed uniform_discrete_def)\n\nlemma uniform_discrete_imp_discrete:\n  \"uniform_discrete S \\<Longrightarrow> discrete S\"\n  by (metis discrete_def isolated_in_dist_Ex_iff uniform_discrete_def)\n\nlemma isolated_in_subset:\"x isolated_in S \\<Longrightarrow> T \\<subseteq> S \\<Longrightarrow> x\\<in>T \\<Longrightarrow> x isolated_in T\"\n  unfolding isolated_in_def by fastforce\n\nlemma discrete_subset[elim]: \"discrete S \\<Longrightarrow> T \\<subseteq> S \\<Longrightarrow> discrete T\"\n  unfolding discrete_def using islimpt_subset isolated_in_islimpt_iff by blast\n\nlemma uniform_discrete_subset[elim]: \"uniform_discrete S \\<Longrightarrow> T \\<subseteq> S \\<Longrightarrow> uniform_discrete T\"\n  by (meson subsetD uniform_discrete_def)\n\nlemma continuous_on_discrete: \"discrete S \\<Longrightarrow> continuous_on S f\"\n  unfolding continuous_on_topological by (metis discrete_def islimptI isolated_in_islimpt_iff)\n\nlemma uniform_discrete_insert: \"uniform_discrete (insert a S) \\<longleftrightarrow> uniform_discrete S\"\nproof\n  assume asm:\"uniform_discrete S\"\n  let ?thesis = \"uniform_discrete (insert a S)\"\n  have ?thesis when \"a\\<in>S\" using that asm by (simp add: insert_absorb)\n  moreover have ?thesis when \"S={}\" using that asm by (simp add: uniform_discrete_def)\n  moreover have ?thesis when \"a\\<notin>S\" \"S\\<noteq>{}\"\n  proof -\n    obtain e1 where \"e1>0\" and e1_dist:\"\\<forall>x\\<in>S. \\<forall>y\\<in>S. dist y x < e1 \\<longrightarrow> y = x\"\n      using asm unfolding uniform_discrete_def by auto\n    define e2 where \"e2 \\<equiv> min (setdist {a} S) e1\"\n    have \"closed S\" using asm uniform_discrete_imp_closed by auto\n    then have \"e2>0\"\n      by (smt (verit) \\<open>0 < e1\\<close> e2_def infdist_eq_setdist infdist_pos_not_in_closed that)\n    moreover have \"x = y\" if \"x\\<in>insert a S\" \"y\\<in>insert a S\" \"dist x y < e2\" for x y\n    proof (cases \"x=a \\<or> y=a\")\n      case True then show ?thesis\n        by (smt (verit, best) dist_commute e2_def infdist_eq_setdist infdist_le insertE that)\n    next\n      case False then show ?thesis\n        using e1_dist e2_def that by force\n    qed\n    ultimately show ?thesis unfolding uniform_discrete_def by meson\n  qed\n  ultimately show ?thesis by auto\nqed (simp add: subset_insertI uniform_discrete_subset)\n\nlemma discrete_compact_finite_iff:\n  fixes S :: \"'a::t1_space set\"\n  shows \"discrete S \\<and> compact S \\<longleftrightarrow> finite S\"\nproof\n  assume \"finite S\"\n  then have \"compact S\" using finite_imp_compact by auto\n  moreover have \"discrete S\"\n    unfolding discrete_def using isolated_in_islimpt_iff islimpt_finite[OF \\<open>finite S\\<close>] by auto\n  ultimately show \"discrete S \\<and> compact S\" by auto\nnext\n  assume \"discrete S \\<and> compact S\"\n  then show \"finite S\"\n    by (meson discrete_def Heine_Borel_imp_Bolzano_Weierstrass isolated_in_islimpt_iff order_refl)\nqed\n\nlemma uniform_discrete_finite_iff:\n  fixes S :: \"'a::heine_borel set\"\n  shows \"uniform_discrete S \\<and> bounded S \\<longleftrightarrow> finite S\"\nproof\n  assume \"uniform_discrete S \\<and> bounded S\"\n  then have \"discrete S\" \"compact S\"\n    using uniform_discrete_imp_discrete uniform_discrete_imp_closed compact_eq_bounded_closed\n    by auto\n  then show \"finite S\" using discrete_compact_finite_iff by auto\nnext\n  assume asm:\"finite S\"\n  let ?thesis = \"uniform_discrete S \\<and> bounded S\"\n  have ?thesis when \"S={}\" using that by auto\n  moreover have ?thesis when \"S\\<noteq>{}\"\n  proof -\n    have \"\\<forall>x. \\<exists>d>0. \\<forall>y\\<in>S. y \\<noteq> x \\<longrightarrow> d \\<le> dist x y\"\n      using finite_set_avoid[OF \\<open>finite S\\<close>] by auto\n    then obtain f where f_pos:\"f x>0\"\n        and f_dist: \"\\<forall>y\\<in>S. y \\<noteq> x \\<longrightarrow> f x \\<le> dist x y\"\n        if \"x\\<in>S\" for x\n      by metis\n    define f_min where \"f_min \\<equiv> Min (f ` S)\"\n    have \"f_min > 0\"\n      unfolding f_min_def\n      by (simp add: asm f_pos that)\n    moreover have \"\\<forall>x\\<in>S. \\<forall>y\\<in>S. f_min > dist x y \\<longrightarrow> x=y\"\n      using f_dist unfolding f_min_def\n      by (metis Min_le asm finite_imageI imageI le_less_trans linorder_not_less)\n    ultimately have \"uniform_discrete S\"\n      unfolding uniform_discrete_def by auto\n    moreover have \"bounded S\" using \\<open>finite S\\<close> by auto\n    ultimately show ?thesis by auto\n  qed\n  ultimately show ?thesis by blast\nqed\n\nlemma uniform_discrete_image_scale:\n  assumes \"uniform_discrete S\" and dist:\"\\<forall>x\\<in>S. \\<forall>y\\<in>S. dist x y = c * dist (f x) (f y)\"\n  shows \"uniform_discrete (f ` S)\"\nproof -\n  have ?thesis when \"S={}\" using that by auto\n  moreover have ?thesis when \"S\\<noteq>{}\" \"c\\<le>0\"\n  proof -\n    obtain x1 where \"x1\\<in>S\" using \\<open>S\\<noteq>{}\\<close> by auto\n    have ?thesis when \"S-{x1} = {}\"\n      using \\<open>x1 \\<in> S\\<close> subset_antisym that uniform_discrete_insert by fastforce\n    moreover have ?thesis when \"S-{x1} \\<noteq> {}\"\n    proof -\n      obtain x2 where \"x2\\<in>S-{x1}\" using \\<open>S-{x1} \\<noteq> {}\\<close> by auto\n      then have \"x2\\<in>S\" \"x1\\<noteq>x2\" by auto\n      then have \"dist x1 x2 > 0\" by auto\n      moreover have \"dist x1 x2 = c * dist (f x1) (f x2)\"\n        by (simp add: \\<open>x1 \\<in> S\\<close> \\<open>x2 \\<in> S\\<close> dist)\n      moreover have \"dist (f x2) (f x2) \\<ge> 0\" by auto\n      ultimately have False using \\<open>c\\<le>0\\<close> by (simp add: zero_less_mult_iff)\n      then show ?thesis by auto\n    qed\n    ultimately show ?thesis by auto\n  qed\n  moreover have ?thesis when \"S\\<noteq>{}\" \"c>0\"\n  proof -\n    obtain e1 where \"e1>0\" and e1_dist:\"\\<forall>x\\<in>S. \\<forall>y\\<in>S. dist y x < e1 \\<longrightarrow> y = x\"\n      using \\<open>uniform_discrete S\\<close> unfolding uniform_discrete_def by auto\n    define e where \"e \\<equiv> e1/c\"\n    have \"x1 = x2\" when \"x1 \\<in> f ` S\" \"x2 \\<in> f ` S\" and d: \"dist x1 x2 < e\" for x1 x2\n      by (smt (verit) \\<open>0 < c\\<close> d dist divide_right_mono e1_dist e_def imageE nonzero_mult_div_cancel_left that)\n    moreover have \"e>0\" using \\<open>e1>0\\<close> \\<open>c>0\\<close> unfolding e_def by auto\n    ultimately show ?thesis unfolding uniform_discrete_def by meson\n  qed\n  ultimately show ?thesis by fastforce\nqed\n\ndefinition sparse :: \"real \\<Rightarrow> 'a :: metric_space set \\<Rightarrow> bool\"\n  where \"sparse \\<epsilon> X \\<longleftrightarrow> (\\<forall>x\\<in>X. \\<forall>y\\<in>X-{x}. dist x y > \\<epsilon>)\"\n\nlemma sparse_empty [simp, intro]: \"sparse \\<epsilon> {}\"\n  by (auto simp: sparse_def)\n\nlemma sparseI [intro?]:\n  \"(\\<And>x y. x \\<in> X \\<Longrightarrow> y \\<in> X \\<Longrightarrow> x \\<noteq> y \\<Longrightarrow> dist x y > \\<epsilon>) \\<Longrightarrow> sparse \\<epsilon> X\"\n  unfolding sparse_def by auto\n\nlemma sparseD:\n  \"sparse \\<epsilon> X \\<Longrightarrow> x \\<in> X \\<Longrightarrow> y \\<in> X \\<Longrightarrow> x \\<noteq> y \\<Longrightarrow> dist x y > \\<epsilon>\"\n  unfolding sparse_def by auto\n\nlemma sparseD':\n  \"sparse \\<epsilon> X \\<Longrightarrow> x \\<in> X \\<Longrightarrow> y \\<in> X \\<Longrightarrow> dist x y \\<le> \\<epsilon> \\<Longrightarrow> x = y\"\n  unfolding sparse_def by force\n\nlemma sparse_singleton [simp, intro]: \"sparse \\<epsilon> {x}\"\n  by (auto simp: sparse_def)\n\ndefinition setdist_gt where \"setdist_gt \\<epsilon> X Y \\<longleftrightarrow> (\\<forall>x\\<in>X. \\<forall>y\\<in>Y. dist x y > \\<epsilon>)\"\n\nlemma setdist_gt_empty [simp]: \"setdist_gt \\<epsilon> {} Y\" \"setdist_gt \\<epsilon> X {}\"\n  by (auto simp: setdist_gt_def)\n\nlemma setdist_gtI: \"(\\<And>x y. x \\<in> X \\<Longrightarrow> y \\<in> Y \\<Longrightarrow> dist x y > \\<epsilon>) \\<Longrightarrow> setdist_gt \\<epsilon> X Y\"\n  unfolding setdist_gt_def by auto\n\nlemma setdist_gtD: \"setdist_gt \\<epsilon> X Y \\<Longrightarrow> x \\<in> X \\<Longrightarrow> y \\<in> Y \\<Longrightarrow> dist x y > \\<epsilon>\"\n  unfolding setdist_gt_def by auto \n\nlemma setdist_gt_setdist: \"\\<epsilon> < setdist A B \\<Longrightarrow> setdist_gt \\<epsilon> A B\"\n  unfolding setdist_gt_def using setdist_le_dist by fastforce\n\nlemma setdist_gt_mono: \"setdist_gt \\<epsilon>' A B \\<Longrightarrow> \\<epsilon> \\<le> \\<epsilon>' \\<Longrightarrow> A' \\<subseteq> A \\<Longrightarrow> B' \\<subseteq> B \\<Longrightarrow> setdist_gt \\<epsilon> A' B'\"\n  by (force simp: setdist_gt_def)\n  \nlemma setdist_gt_Un_left: \"setdist_gt \\<epsilon> (A \\<union> B) C \\<longleftrightarrow> setdist_gt \\<epsilon> A C \\<and> setdist_gt \\<epsilon> B C\"\n  by (auto simp: setdist_gt_def)\n\nlemma setdist_gt_Un_right: \"setdist_gt \\<epsilon> C (A \\<union> B) \\<longleftrightarrow> setdist_gt \\<epsilon> C A \\<and> setdist_gt \\<epsilon> C B\"\n  by (auto simp: setdist_gt_def)\n  \nlemma compact_closed_imp_eventually_setdist_gt_at_right_0:\n  assumes \"compact A\" \"closed B\" \"A \\<inter> B = {}\"\n  shows   \"eventually (\\<lambda>\\<epsilon>. setdist_gt \\<epsilon> A B) (at_right 0)\"\nproof (cases \"A = {} \\<or> B = {}\")\n  case False\n  hence \"setdist A B > 0\"\n    by (metis IntI assms empty_iff in_closed_iff_infdist_zero order_less_le setdist_attains_inf setdist_pos_le setdist_sym)\n  hence \"eventually (\\<lambda>\\<epsilon>. \\<epsilon> < setdist A B) (at_right 0)\"\n    using eventually_at_right_field by blast\n  thus ?thesis\n    by eventually_elim (auto intro: setdist_gt_setdist)\nqed auto \n\nlemma setdist_gt_symI: \"setdist_gt \\<epsilon> A B \\<Longrightarrow> setdist_gt \\<epsilon> B A\"\n  by (force simp: setdist_gt_def dist_commute)\n\nlemma setdist_gt_sym: \"setdist_gt \\<epsilon> A B \\<longleftrightarrow> setdist_gt \\<epsilon> B A\"\n  by (force simp: setdist_gt_def dist_commute)\n\nlemma eventually_setdist_gt_at_right_0_mult_iff:\n  assumes \"c > 0\"\n  shows   \"eventually (\\<lambda>\\<epsilon>. setdist_gt (c * \\<epsilon>) A B) (at_right 0) \\<longleftrightarrow>\n             eventually (\\<lambda>\\<epsilon>. setdist_gt \\<epsilon> A B) (at_right 0)\"\nproof -\n  have \"eventually (\\<lambda>\\<epsilon>. setdist_gt (c * \\<epsilon>) A B) (at_right 0) \\<longleftrightarrow>\n        eventually (\\<lambda>\\<epsilon>. setdist_gt \\<epsilon> A B) (filtermap ((*) c) (at_right 0))\"\n    by (simp add: eventually_filtermap)\n  also have \"filtermap ((*) c) (at_right 0) = at_right 0\"\n    by (subst filtermap_times_pos_at_right) (use assms in auto)\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/Analysis/Isolated.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8376199673867852, "lm_q2_score": 0.8376199653600372, "lm_q1q2_score": 0.7016072080673946}}
{"text": "theory HoareLogicLecture\nimports Main \"HOL-Hoare.Hoare_Logic\"\nbegin\n\nlemma \"VARS (z :: nat) (y::nat)\n {True}\n y := 1; z := 0;\n WHILE z \\<noteq> x\n INV { y = fact z }\n DO \n   z := z + 1;\n   y := y * z \n OD\n {y = fact x}\"\nby vcg_simp\n\n\nlemma \"VARS (z :: int) i\n {True}\n i := y;\n z := 0;\n WHILE i \\<noteq> 0\n INV { z = (y - i) * x }\n DO \n   z := z + x; \n   i := i - 1 \n OD\n {z = x * y}\"\napply vcg_simp\nby (simp add: algebra_simps)\n\n\nlemma \"VARS j R\n  { True }\n  j:= 0; R := [];\n  WHILE j < length A\n  INV { R = rev (take j A) }\n  DO \n    R := (A!j) # R;\n    j := j + 1\n  OD\n  { R = rev A }\"\nproof (vcg_simp)\n  show \"\\<And>j R. R = rev (take j A) \\<and> j < length A \\<Longrightarrow> A ! j # rev (take j A) = rev (take (Suc j) A)\"\n  proof (induct A)\n    case Nil thus ?case by simp\n  next\n    case (Cons a A') thus ?case by (cases \"j\", auto)    \n  qed\nqed\n\nlemma \"VARS j R\n  { True }\n  j:= 0; R := [];\n  WHILE j < length A\n  INV { R = rev (take j A) }\n  DO \n    R := (A!j) # R;\n    j := j + 1\n  OD\n  { R = rev A }\"\nproof (vcg_simp, simp add: take_Suc_conv_app_nth)\nqed\n\n\nend\n\n\n", "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/HoareLogicLecture.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199633332891, "lm_q2_score": 0.8376199653600371, "lm_q1q2_score": 0.7016072046721052}}
{"text": "section \\<open>Combining Spectral Radius Theory with Perron Frobenius theorem\\<close>\n\ntheory Spectral_Radius_Theory\nimports \n  Polynomial_Factorization.Square_Free_Factorization\n  Jordan_Normal_Form.Spectral_Radius\n  Jordan_Normal_Form.Char_Poly\n  Perron_Frobenius\n  \"HOL-Computational_Algebra.Field_as_Ring\"\nbegin\nabbreviation spectral_radius where \"spectral_radius \\<equiv> Spectral_Radius.spectral_radius\"\nhide_const (open) Module.smult\n\ntext \\<open>Via JNFs it has been proven that the growth of $A^k$ is polynomially bounded,\n  if all complex eigenvalues have a norm at most 1, i.e., the spectral radius must be\n  at most 1. Moreover, the degree of the polynomial growth can be \n  bounded by the order of those roots which have norm 1, cf. @{thm spectral_radius_poly_bound}.\\<close>\n\ntext \\<open>Perron Frobenius theorem tells us that for a real valued non negative matrix,\n  the largest eigenvalue is a real non-negative one. Hence, we only have to check, that all real \n  eigenvalues are at most one.\\<close> \n\ntext \\<open>We combine both theorems in the following. To be more precise,\n  the set-based complexity results from JNFs with the type-based\n  Perron Frobenius theorem in HMA are connected to obtain \n  a set based complexity criterion for real-valued\n  non-negative matrices, where one only investigated the real valued eigenvalues for\n  checking the eigenvalue-at-most-1 condition.  \n  Here, in the precondition of the roots of the polynomial, the type-system ensures\n  that we only have to look at real-valued eigenvalues, and can ignore the \n  complex-valued ones.\n\n  The linkage between set-and type-based is performed via HMA-connect.\\<close>\n\nlemma perron_frobenius_spectral_radius_complex: fixes A :: \"complex mat\"\n  assumes A: \"A \\<in> carrier_mat n n\"\n  and real_nonneg: \"real_nonneg_mat A\"\n  and ev_le_1: \"\\<And> x. poly (char_poly (map_mat Re A)) x = 0 \\<Longrightarrow> x \\<le> 1\"\n  and ev_order: \"\\<And> x. norm x = 1 \\<Longrightarrow> order x (char_poly A) \\<le> d\"\n  shows \"\\<exists>c1 c2. \\<forall>k. norm_bound (A ^\\<^sub>m k) (c1 + c2 * real k ^ (d - 1))\"\nproof (cases \"n = 0\")\n  case False\n  hence n: \"n > 0\" \"n \\<noteq> 0\" by auto\n  define sr where \"sr = spectral_radius A\"\n  note sr = spectral_radius_mem_max[OF A n(1), folded sr_def]\n  show ?thesis\n  proof (rule spectral_radius_poly_bound[OF A], unfold sr_def[symmetric])\n    let ?cr = \"complex_of_real\"\n    text \\<open>here is the transition from type-based perron-frobenius to set-based\\<close>\n    from perron_frobenius[untransferred, cancel_card_constraint, OF A real_nonneg n(2)]\n      obtain v where v: \"v \\<in> carrier_vec n\" and ev: \"eigenvector A v (?cr sr)\" and \n      rnn: \"real_nonneg_vec v\" unfolding sr_def by auto\n    define B where \"B = map_mat Re A\"\n    let ?A = \"map_mat ?cr B\"\n    have AB: \"A = ?A\" unfolding B_def \n      by (rule eq_matI, insert real_nonneg[unfolded real_nonneg_mat_def elements_mat_def], auto)\n    define w where \"w = map_vec Re v\"\n    let ?v = \"map_vec ?cr w\"\n    have vw: \"v = ?v\" unfolding w_def\n      by (rule eq_vecI, insert rnn[unfolded real_nonneg_vec_def vec_elements_def], auto)\n    have B: \"B \\<in> carrier_mat n n\" unfolding B_def using A by auto\n    from AB vw ev have ev: \"eigenvector ?A ?v (?cr sr)\" by simp\n    have \"eigenvector B w sr\"\n      by (rule of_real_hom.eigenvector_hom_rev[OF B ev])\n    hence \"eigenvalue B sr\" unfolding eigenvalue_def by blast\n    from ev_le_1[folded B_def, OF this[unfolded eigenvalue_root_char_poly[OF B]]]\n    show \"sr \\<le> 1\" .\n  next\n    fix ev\n    assume \"cmod ev = 1\"\n    thus \"order ev (char_poly A) \\<le> d\" by (rule ev_order)\n  qed\nnext\n  case True\n  with A show ?thesis\n    by (intro exI[of _ 0], auto simp: norm_bound_def)\nqed\n\ntext \\<open>The following lemma is the same as @{thm perron_frobenius_spectral_radius_complex}, \n  except that now the type @{typ real} is used instead of @{typ complex}.\\<close>\n\nlemma perron_frobenius_spectral_radius: fixes A :: \"real mat\"\n  assumes A: \"A \\<in> carrier_mat n n\"\n  and nonneg: \"nonneg_mat A\"\n  and ev_le_1: \"\\<forall> x. poly (char_poly A) x = 0 \\<longrightarrow> x \\<le> 1\"\n  and ev_order: \"\\<forall> x :: complex. norm x = 1 \\<longrightarrow> order x (map_poly of_real (char_poly A)) \\<le> d\"\n  shows \"\\<exists>c1 c2. \\<forall>k a. a \\<in> elements_mat (A ^\\<^sub>m k) \\<longrightarrow> abs a \\<le> (c1 + c2 * real k ^ (d - 1))\"\nproof -\n  let ?cr = \"complex_of_real\"\n  let ?B = \"map_mat ?cr A\"\n  have B: \"?B \\<in> carrier_mat n n\" using A by auto\n  have rnn: \"real_nonneg_mat ?B\" using nonneg unfolding real_nonneg_mat_def nonneg_mat_def\n    by (auto simp: elements_mat_def)\n  have id: \"map_mat Re ?B = A\"\n    by (rule eq_matI, auto)\n  have \"\\<exists>c1 c2. \\<forall>k. norm_bound (?B ^\\<^sub>m k) (c1 + c2 * real k ^ (d - 1))\"\n    by (rule perron_frobenius_spectral_radius_complex[OF B rnn], unfold id, \n    insert ev_le_1 ev_order, auto simp: of_real_hom.char_poly_hom[OF A])\n  then obtain c1 c2 where nb: \"\\<And> k. norm_bound (?B ^\\<^sub>m k) (c1 + c2 * real k ^ (d - 1))\" by auto\n  show ?thesis\n  proof (rule exI[of _ c1], rule exI[of _ c2], intro allI impI)\n    fix k a\n    assume \"a \\<in> elements_mat (A ^\\<^sub>m k)\"\n    with pow_carrier_mat[OF A] obtain i j where a: \"a = (A ^\\<^sub>m k) $$ (i,j)\" and ij: \"i < n\" \"j < n\"\n      unfolding elements_mat by force\n    from ij nb[of k] A have \"norm ((?B ^\\<^sub>m k) $$ (i,j)) \\<le> c1 + c2 * real k ^ (d - 1)\"\n      unfolding norm_bound_def by auto\n    also have \"(?B ^\\<^sub>m k) $$ (i,j) = ?cr a\"\n      unfolding of_real_hom.mat_hom_pow[OF A, symmetric] a using ij A by auto\n    also have \"norm (?cr a) = abs a\" by auto\n    finally show \"abs a \\<le> (c1 + c2 * real k ^ (d - 1))\" .\n  qed\nqed\n\ntext \\<open>We can also convert the set-based lemma @{thm perron_frobenius_spectral_radius}\n  to a type-based version.\\<close>\n\n\n\ntext \\<open>And of course, we can also transfer the type-based lemma back to a set-based setting, \n  only that -- without further case-analysis -- \n  we get the additional assumption @{term \"(n :: nat) \\<noteq> 0\"}.\\<close>\n\nlemma assumes \"A \\<in> carrier_mat n n\"\n  and \"nonneg_mat A\"\n  and \"\\<forall> x. poly (char_poly A) x = 0 \\<longrightarrow> x \\<le> 1\"\n  and \"\\<forall> x :: complex. norm x = 1 \\<longrightarrow> order x (map_poly of_real (char_poly A)) \\<le> d\"\n  and \"n \\<noteq> 0\"\n  shows \"\\<exists>c1 c2. \\<forall>k a. a \\<in> elements_mat (A ^\\<^sub>m k) \\<longrightarrow> abs a \\<le> (c1 + c2 * real k ^ (d - 1))\"\n  using perron_frobenius_spectral_type_based[untransferred, cancel_card_constraint, OF assms] .\n   \n\ntext \\<open>Note that the precondition eigenvalue-at-most-1 can easily be formulated as a cardinality\n  constraints which can be decided by Sturm's theorem. \n  And in order to obtain a bound on the order, one can \n  perform a square-free-factorization (via Yun's factorization algorithm) \n  of the characteristic polynomial into\n  $f_1^1 \\cdot \\ldots f_d^d$ where each $f_i$ has precisely the roots of order $i$.\\<close>\n\ncontext \n  fixes A :: \"real mat\" and c :: real and fis and n :: nat\n  assumes A: \"A \\<in> carrier_mat n n\"\n  and nonneg: \"nonneg_mat A\"\n  and yun: \"yun_factorization gcd (char_poly A) = (c,fis)\"\n  and ev_le_1: \"card {x. poly (char_poly A) x = 0 \\<and> x > 1} = 0\"\nbegin\n\ntext \\<open>Note that @{const yun_factorization} has an offset by 1, \n  so the pair @{term \"(f\\<^sub>i,i) \\<in> set fis\"} encodes @{term \"f\\<^sub>i^(Suc i)\"}.\\<close>\nlemma perron_frobenius_spectral_radius_yun: \n  assumes bnd: \"\\<And> f\\<^sub>i i. (f\\<^sub>i,i) \\<in> set fis \n    \\<Longrightarrow> (\\<exists> x :: complex. poly (map_poly of_real f\\<^sub>i) x = 0 \\<and> norm x = 1) \n    \\<Longrightarrow> Suc i \\<le> d\"\n  shows \"\\<exists>c1 c2. \\<forall>k a. a \\<in> elements_mat (A ^\\<^sub>m k) \\<longrightarrow> abs a \\<le> (c1 + c2 * real k ^ (d - 1))\"\nproof (rule perron_frobenius_spectral_radius[OF A nonneg]; intro allI impI)\n  let ?cr = complex_of_real\n  let ?cp = \"map_poly ?cr (char_poly A)\"\n  fix x :: complex\n  assume x: \"norm x = 1\"\n  have A0: \"char_poly A \\<noteq> 0\" using degree_monic_char_poly[OF A] by auto\n  interpret field_hom_0' ?cr by (standard, auto)\n  from A0 have cp0: \"?cp \\<noteq> 0\" by auto\n  obtain ox where ox: \"order x ?cp = ox\" by blast\n  note sff = square_free_factorization_order_root[OF yun_factorization(1)[OF \n    yun_factorization_hom[of \"char_poly A\", unfolded yun map_prod_def split]] cp0, of x ox, unfolded ox]\n  show \"order x ?cp \\<le> d\" unfolding ox\n  proof (cases ox)\n    case (Suc oo)\n    with sff obtain fi where mem: \"(fi,oo) \\<in> set fis\" and rt: \"poly (map_poly ?cr fi) x = 0\" by auto\n    from bnd[OF mem exI[of _ x], OF conjI[OF rt x]]\n    show \"ox \\<le> d\" unfolding Suc .\n  qed auto\nnext\n  let ?L = \"{x. poly (char_poly A) x = 0 \\<and> x > 1}\"\n  fix x :: real\n  assume rt: \"poly (char_poly A) x = 0\"\n  have \"finite ?L\"\n    by (rule finite_subset[OF _ poly_roots_finite[of \"char_poly A\"]],\n      insert degree_monic_char_poly[OF A], auto)\n  with ev_le_1 have \"?L = {}\" by simp\n  with rt show \"x \\<le> 1\" by auto\nqed\n\ntext \\<open>Note that the only remaining problem in applying \n  @{thm perron_frobenius_spectral_radius_yun} is to check the\n  condition @{term \"\\<exists> x :: complex. poly (map_poly of_real f\\<^sub>i) x = 0 \\<and> norm x = 1\"}.\n  Here, there are at least three possibilities.\n  First, one can just ignore this precondition and weaken the statement.\n  Second, one can apply Sturm's theorem to determine whether all roots are real.\n  This can be done by comparing the number of distinct real roots with the degree of @{term f\\<^sub>i},\n    since @{term f\\<^sub>i} is square-free. If all roots are real, then one can decide the criterion\n    by checking the only two possible real roots with norm equal to 1, namely 1 and -1.\n    If on the other hand there are complex roots, then we loose precision at this point.\n  Third, one uses a factorization algorithm (e.g., via complex algebraic numbers) to\n  precisely determine the complex roots and decide the condition.\n\n  The second approach is illustrated in the following theorem. Note that all preconditions --\n  including the ones from the context --\n  can easily be checked with the help of Sturm's method.\n  This method is used as a fast approximative technique in CeTA \\cite{CeTA}. Only if the desired degree\n  cannot be ensured by this method, the more costly complex algebraic number based \n  factorization is applied.\\<close>\n\nlemma perron_frobenius_spectral_radius_yun_real_roots: \n  assumes bnd: \"\\<And> f\\<^sub>i i. (f\\<^sub>i,i) \\<in> set fis \n    \\<Longrightarrow> card { x. poly f\\<^sub>i x = 0} \\<noteq> degree f\\<^sub>i \\<or> poly f\\<^sub>i 1 = 0 \\<or> poly f\\<^sub>i (-1) = 0 \n    \\<Longrightarrow> Suc i \\<le> d\"\n  shows \"\\<exists>c1 c2. \\<forall>k a. a \\<in> elements_mat (A ^\\<^sub>m k) \\<longrightarrow> abs a \\<le> (c1 + c2 * real k ^ (d - 1))\"\nproof (rule perron_frobenius_spectral_radius_yun)\n  fix fi i\n  let ?cr = complex_of_real\n  let ?cp = \"map_poly ?cr\"\n  assume fi: \"(fi, i) \\<in> set fis\"\n    and \"\\<exists> x. poly (map_poly ?cr fi) x = 0 \\<and> norm x = 1\"\n  then obtain x where rt: \"poly (?cp fi) x = 0\" and x: \"norm x = 1\" by auto\n  show \"Suc i \\<le> d\"\n  proof (rule bnd[OF fi])\n    consider (c) \"x \\<notin> \\<real>\" | (1) \"x = 1\" | (m1) \"x = -1\" | (r) \"x \\<in> \\<real>\" \"x \\<notin> {1, -1}\"\n      by (cases \"x \\<in> \\<real>\"; auto)\n    thus \"card {x. poly fi x = 0} \\<noteq> degree fi \\<or> poly fi 1 = 0 \\<or> poly fi (- 1) = 0\"\n    proof (cases)\n      case 1\n      from rt have \"poly fi 1 = 0\" \n        unfolding 1 by simp\n      thus ?thesis by simp\n    next\n      case m1\n      have id: \"-1 = ?cr (-1)\" by simp\n      from rt have \"poly fi (-1) = 0\"\n        unfolding m1 id of_real_hom.hom_zero[where 'a=complex,symmetric] of_real_hom.poly_map_poly by simp\n      thus ?thesis by simp\n    next\n      case r\n      then obtain y where xy: \"x = of_real y\" unfolding Reals_def by auto\n      from r(2)[unfolded xy] have y: \"y \\<notin> {1,-1}\" by auto\n      from x[unfolded xy] have \"abs y = 1\" by auto\n      with y have False by auto\n      thus ?thesis ..\n    next\n      case c\n      from yun_factorization(2)[OF yun] fi have \"monic fi\" by auto\n      hence fi: \"?cp fi \\<noteq> 0\" by auto\n      hence fin: \"finite {x. poly (?cp fi) x = 0}\" by (rule poly_roots_finite)\n      have \"?cr ` {x. poly (?cp fi) (?cr x) = 0} \\<subset> {x. poly (?cp fi) x = 0}\" (is \"?l \\<subset> ?r\")\n      proof (rule, force)\n        have \"x \\<in> ?r\" using rt by auto\n        moreover have \"x \\<notin> ?l\" using c unfolding Reals_def by auto\n        ultimately show \"?l \\<noteq> ?r\" by blast\n      qed\n      from psubset_card_mono[OF fin this] have \"card ?l < card ?r\" .\n      also have \"\\<dots> \\<le> degree (?cp fi)\" by (rule poly_roots_degree[OF fi])\n      also have \"\\<dots> = degree fi\" by simp\n      also have \"?l = ?cr ` {x. poly fi x = 0}\" by auto\n      also have \"card \\<dots> = card {x. poly fi x = 0}\"\n        by (rule card_image, auto simp: inj_on_def)\n      finally have \"card {x. poly fi x = 0} \\<noteq> degree fi\" by simp\n      thus ?thesis by auto\n    qed\n  qed\nqed \n\nend\n\nthm perron_frobenius_spectral_radius_yun_real_roots\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/Perron_Frobenius/Spectral_Radius_Theory.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8354835534888481, "lm_q2_score": 0.8397339756938818, "lm_q1q2_score": 0.7015839259980423}}
{"text": "theory cases_playground\nimports Main\nbegin\n\n(* example simple custom bools *)\n\ndatatype mybool = T | F\nprint_theorems\nthm mybool.induct\n\nfun not :: \"mybool \\<Rightarrow> mybool\" where\n  \"not T = F\" |\n  \"not F = T\"\n\nlemma \"not (not b) = b\" apply (cases b) apply simp by simp\n\nlemma\n  shows \"not (not b) = b\"\nproof (cases b)\ncase T\n  then show ?thesis by simp\nnext\n  case F\n  then show ?thesis by simp\nqed\n\n(* example Inductively defined predicates *)\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\n  shows \"ev n \\<Longrightarrow> evn n\"\nproof (induction rule: ev.induct)\n  case ev0\n  then show ?case by simp\nnext\n  case (evSS n)\n  then show ?case by simp\nqed\n\n(* failed to do it directly to it\nlemma\n  shows \"ev n \\<Longrightarrow> ev (n - 2)\"\nproof (cases n)\n    case ev0 then show \"ev (n - 2)\" by (simp add: ev.ev0)\n  next\n    case (evSS n') then show \"ev (n - 2)\" by (simp add: ev.evSS)\n  qed\nqed\n*)\n\nlemma\n  shows \"ev n \\<Longrightarrow> ev (n - 2)\"\nproof -\n  assume 0: \"ev n\"\n  from this show \"ev (n - 2)\"\n  proof (cases)\n    case ev0 then show \"ev (n - 2)\" by (simp add: ev.ev0)\n  next\n    case (evSS n') then show \"ev (n - 2)\" by (simp add: ev.evSS)\n  qed\nqed\n\nlemma\n  shows \"ev n \\<Longrightarrow> ev (n - 2)\"\nproof -\n  assume 0: \"ev n\"\n  from this show \"ev (n - 2)\"\n  proof (cases)\n    assume \"n = 0\" \n    then show \"ev (n - 2)\" by (simp add: ev.ev0)\n  next\n    fix n'\n    assume \"n = Suc (Suc n')\" \"ev n'\"\n    then show \"ev (n - 2)\" by (simp add: ev.evSS)\n  qed\nqed\n\nlemma\n  shows \"ev n \\<Longrightarrow> ev (n - 2)\"\nproof -\n  assume \"ev n\"\n  from this show \"ev (n - 2)\"\n  proof (cases)\n    case ev0\n    then show ?thesis using `ev n` by auto \n  next\n    case (evSS n)\n    then show ?thesis by simp \n  qed\nqed\n\nlemma\n  shows \"ev n \\<Longrightarrow> ev (n - 2)\"\nproof -\n  assume \"ev n\"\n  from this show \"ev (n - 2)\"\n  proof (cases rule: ev.cases)\n    case ev0\n    then show ?thesis by (simp add: ev.ev0)\n  next\n    case (evSS n)\n    then show ?thesis by simp\n  qed\nqed\n\n(* failed to unify manually for the argument ev ?a *)\nlemma\n  shows \"ev n \\<Longrightarrow> ev (n - 2)\"\nproof (cases rule: ev.cases)\n  show ?thesis by sorry\n  show ?thesis by sorry\n  show ?thesis by sorry\nqed\n\nlemma\n  shows \"ev n \\<Longrightarrow> ev (n - 2)\"\nproof (rule ev.cases)\n  show ?thesis by sorry\n  show ?thesis by sorry\n  show ?thesis by sorry\nqed\n\n(* but the manual unifications succeds here though *)\nlemma \"ev n \\<Longrightarrow> ev (n - 2)\"\n  thm ev.cases\n  apply (cases rule: ev.cases)\n    apply simp\n   apply simp\n  by simp\n\nthm ev.induct ev.cases\n(*\nNote that induction and cases is very similar except that induction introduces\nthe induction hypothesis after doing the unification, the ?Pn in this example.\n  ev ?x \\<Longrightarrow> ?P 0 \\<Longrightarrow> (\\<And>n. ev n \\<Longrightarrow> ?P n \\<Longrightarrow> ?P (Suc (Suc n))) \\<Longrightarrow> ?P ?x\n  ev ?a \\<Longrightarrow> (?a = 0 \\<Longrightarrow> ?P) \\<Longrightarrow> (\\<And>n. ?a = Suc (Suc n) \\<Longrightarrow> ev n \\<Longrightarrow> ?P) \\<Longrightarrow> ?P\n*)\n\n(* this does the unification for me *)\nlemma\n  shows \"ev n \\<Longrightarrow> ev (n - 2)\"\nproof (cases)\n  show ?thesis by sorry\n  show ?thesis by sorry\nqed\n\n(* Construct clashes *)\n\nlemma\n  shows \"\\<not> ev (Suc 0)\"\nproof (rule notI)\n  assume \"ev (Suc 0)\"\n  then show False \n  proof\n    show \"Suc 0 = 0 \\<Longrightarrow> False\" by simp\n    show \"\\<And>n. \\<lbrakk>Suc 0 = Suc (Suc n); ev n\\<rbrakk> \\<Longrightarrow> False\" by simp\n  qed\nqed\n\nlemma\n  shows \"ev (Suc 0) \\<Longrightarrow> P\"\nproof (cases P)\n  case True\n  then show ?thesis by assumption\nnext\n  case False\n  then show ?thesis\n  qed\n\nlemma\n  shows \"\\<not> ev (Suc 0)\"\nproof (rule notI)\n  assume \"ev (Suc 0)\"\n  then show False \n  proof (cases)\n  case ev0\n    then show ?case by blast\n  next\n    case evSS\n    then show ?case sorry\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/cases_playground.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835452961425, "lm_q2_score": 0.8397339656668286, "lm_q1q2_score": 0.7015839107409112}}
{"text": "(*  Title:      HOL/Limits.thy\n    Author:     Brian Huffman\n    Author:     Jacques D. Fleuriot, University of Cambridge\n    Author:     Lawrence C Paulson\n    Author:     Jeremy Avigad\n*)\n\nsection \\<open>Limits on Real Vector Spaces\\<close>\n\ntheory Limits\n  imports Real_Vector_Spaces\nbegin\n\nsubsection \\<open>Filter going to infinity norm\\<close>\n\ndefinition at_infinity :: \"'a::real_normed_vector filter\"\n  where \"at_infinity = (INF r. principal {x. r \\<le> norm x})\"\n\nlemma eventually_at_infinity: \"eventually P at_infinity \\<longleftrightarrow> (\\<exists>b. \\<forall>x. b \\<le> norm x \\<longrightarrow> P x)\"\n  unfolding at_infinity_def\n  by (subst eventually_INF_base)\n     (auto simp: subset_eq eventually_principal intro!: exI[of _ \"max a b\" for a b])\n\ncorollary eventually_at_infinity_pos:\n  \"eventually p at_infinity \\<longleftrightarrow> (\\<exists>b. 0 < b \\<and> (\\<forall>x. norm x \\<ge> b \\<longrightarrow> p x))\"\n  apply (simp add: eventually_at_infinity)\n  apply auto\n  apply (case_tac \"b \\<le> 0\")\n  using norm_ge_zero order_trans zero_less_one apply blast\n  apply force\n  done\n\nlemma at_infinity_eq_at_top_bot: \"(at_infinity :: real filter) = sup at_top at_bot\"\n  apply (simp add: filter_eq_iff eventually_sup eventually_at_infinity\n      eventually_at_top_linorder eventually_at_bot_linorder)\n  apply safe\n    apply (rule_tac x=\"b\" in exI)\n    apply simp\n   apply (rule_tac x=\"- b\" in exI)\n   apply simp\n  apply (rule_tac x=\"max (- Na) N\" in exI)\n  apply (auto simp: abs_real_def)\n  done\n\nlemma at_top_le_at_infinity: \"at_top \\<le> (at_infinity :: real filter)\"\n  unfolding at_infinity_eq_at_top_bot by simp\n\nlemma at_bot_le_at_infinity: \"at_bot \\<le> (at_infinity :: real filter)\"\n  unfolding at_infinity_eq_at_top_bot by simp\n\nlemma filterlim_at_top_imp_at_infinity: \"filterlim f at_top F \\<Longrightarrow> filterlim f at_infinity F\"\n  for f :: \"_ \\<Rightarrow> real\"\n  by (rule filterlim_mono[OF _ at_top_le_at_infinity order_refl])\n\nlemma lim_infinity_imp_sequentially: \"(f \\<longlongrightarrow> l) at_infinity \\<Longrightarrow> ((\\<lambda>n. f(n)) \\<longlongrightarrow> l) sequentially\"\n  by (simp add: filterlim_at_top_imp_at_infinity filterlim_compose filterlim_real_sequentially)\n\n\nsubsubsection \\<open>Boundedness\\<close>\n\ndefinition Bfun :: \"('a \\<Rightarrow> 'b::metric_space) \\<Rightarrow> 'a filter \\<Rightarrow> bool\"\n  where Bfun_metric_def: \"Bfun f F = (\\<exists>y. \\<exists>K>0. eventually (\\<lambda>x. dist (f x) y \\<le> K) F)\"\n\nabbreviation Bseq :: \"(nat \\<Rightarrow> 'a::metric_space) \\<Rightarrow> bool\"\n  where \"Bseq X \\<equiv> Bfun X sequentially\"\n\nlemma Bseq_conv_Bfun: \"Bseq X \\<longleftrightarrow> Bfun X sequentially\" ..\n\nlemma Bseq_ignore_initial_segment: \"Bseq X \\<Longrightarrow> Bseq (\\<lambda>n. X (n + k))\"\n  unfolding Bfun_metric_def by (subst eventually_sequentially_seg)\n\nlemma Bseq_offset: \"Bseq (\\<lambda>n. X (n + k)) \\<Longrightarrow> Bseq X\"\n  unfolding Bfun_metric_def by (subst (asm) eventually_sequentially_seg)\n\nlemma Bfun_def: \"Bfun f F \\<longleftrightarrow> (\\<exists>K>0. eventually (\\<lambda>x. norm (f x) \\<le> K) F)\"\n  unfolding Bfun_metric_def norm_conv_dist\nproof safe\n  fix y K\n  assume K: \"0 < K\" and *: \"eventually (\\<lambda>x. dist (f x) y \\<le> K) F\"\n  moreover have \"eventually (\\<lambda>x. dist (f x) 0 \\<le> dist (f x) y + dist 0 y) F\"\n    by (intro always_eventually) (metis dist_commute dist_triangle)\n  with * have \"eventually (\\<lambda>x. dist (f x) 0 \\<le> K + dist 0 y) F\"\n    by eventually_elim auto\n  with \\<open>0 < K\\<close> show \"\\<exists>K>0. eventually (\\<lambda>x. dist (f x) 0 \\<le> K) F\"\n    by (intro exI[of _ \"K + dist 0 y\"] add_pos_nonneg conjI zero_le_dist) auto\nqed (force simp del: norm_conv_dist [symmetric])\n\nlemma BfunI:\n  assumes K: \"eventually (\\<lambda>x. norm (f x) \\<le> K) F\"\n  shows \"Bfun f F\"\n  unfolding Bfun_def\nproof (intro exI conjI allI)\n  show \"0 < max K 1\" by simp\n  show \"eventually (\\<lambda>x. norm (f x) \\<le> max K 1) F\"\n    using K by (rule eventually_mono) simp\nqed\n\nlemma BfunE:\n  assumes \"Bfun f F\"\n  obtains B where \"0 < B\" and \"eventually (\\<lambda>x. norm (f x) \\<le> B) F\"\n  using assms unfolding Bfun_def by blast\n\nlemma Cauchy_Bseq: \"Cauchy X \\<Longrightarrow> Bseq X\"\n  unfolding Cauchy_def Bfun_metric_def eventually_sequentially\n  apply (erule_tac x=1 in allE)\n  apply simp\n  apply safe\n  apply (rule_tac x=\"X M\" in exI)\n  apply (rule_tac x=1 in exI)\n  apply (erule_tac x=M in allE)\n  apply simp\n  apply (rule_tac x=M in exI)\n  apply (auto simp: dist_commute)\n  done\n\n\nsubsubsection \\<open>Bounded Sequences\\<close>\n\nlemma BseqI': \"(\\<And>n. norm (X n) \\<le> K) \\<Longrightarrow> Bseq X\"\n  by (intro BfunI) (auto simp: eventually_sequentially)\n\nlemma BseqI2': \"\\<forall>n\\<ge>N. norm (X n) \\<le> K \\<Longrightarrow> Bseq X\"\n  by (intro BfunI) (auto simp: eventually_sequentially)\n\nlemma Bseq_def: \"Bseq X \\<longleftrightarrow> (\\<exists>K>0. \\<forall>n. norm (X n) \\<le> K)\"\n  unfolding Bfun_def eventually_sequentially\nproof safe\n  fix N K\n  assume \"0 < K\" \"\\<forall>n\\<ge>N. norm (X n) \\<le> K\"\n  then show \"\\<exists>K>0. \\<forall>n. norm (X n) \\<le> K\"\n    by (intro exI[of _ \"max (Max (norm ` X ` {..N})) K\"] max.strict_coboundedI2)\n       (auto intro!: imageI not_less[where 'a=nat, THEN iffD1] Max_ge simp: le_max_iff_disj)\nqed auto\n\nlemma BseqE: \"Bseq X \\<Longrightarrow> (\\<And>K. 0 < K \\<Longrightarrow> \\<forall>n. norm (X n) \\<le> K \\<Longrightarrow> Q) \\<Longrightarrow> Q\"\n  unfolding Bseq_def by auto\n\nlemma BseqD: \"Bseq X \\<Longrightarrow> \\<exists>K. 0 < K \\<and> (\\<forall>n. norm (X n) \\<le> K)\"\n  by (simp add: Bseq_def)\n\nlemma BseqI: \"0 < K \\<Longrightarrow> \\<forall>n. norm (X n) \\<le> K \\<Longrightarrow> Bseq X\"\n  by (auto simp add: Bseq_def)\n\nlemma Bseq_bdd_above: \"Bseq X \\<Longrightarrow> bdd_above (range X)\"\n  for X :: \"nat \\<Rightarrow> real\"\nproof (elim BseqE, intro bdd_aboveI2)\n  fix K n\n  assume \"0 < K\" \"\\<forall>n. norm (X n) \\<le> K\"\n  then show \"X n \\<le> K\"\n    by (auto elim!: allE[of _ n])\nqed\n\nlemma Bseq_bdd_above': \"Bseq X \\<Longrightarrow> bdd_above (range (\\<lambda>n. norm (X n)))\"\n  for X :: \"nat \\<Rightarrow> 'a :: real_normed_vector\"\nproof (elim BseqE, intro bdd_aboveI2)\n  fix K n\n  assume \"0 < K\" \"\\<forall>n. norm (X n) \\<le> K\"\n  then show \"norm (X n) \\<le> K\"\n    by (auto elim!: allE[of _ n])\nqed\n\nlemma Bseq_bdd_below: \"Bseq X \\<Longrightarrow> bdd_below (range X)\"\n  for X :: \"nat \\<Rightarrow> real\"\nproof (elim BseqE, intro bdd_belowI2)\n  fix K n\n  assume \"0 < K\" \"\\<forall>n. norm (X n) \\<le> K\"\n  then show \"- K \\<le> X n\"\n    by (auto elim!: allE[of _ n])\nqed\n\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  moreover from assms(2) obtain K where K: \"\\<And>n. norm (g n) \\<le> K\"\n    by (blast elim!: BseqE)\n  ultimately have \"norm (f n) \\<le> max K (Max {norm (f n) |n. n < N})\" for n\n    apply (cases \"n < N\")\n    subgoal by (rule max.coboundedI2, rule Max.coboundedI) auto\n    subgoal by (rule max.coboundedI1) (force intro: order.trans[OF N K])\n    done\n  then show ?thesis by (blast intro: BseqI')\nqed\n\nlemma lemma_NBseq_def: \"(\\<exists>K > 0. \\<forall>n. norm (X n) \\<le> K) \\<longleftrightarrow> (\\<exists>N. \\<forall>n. norm (X n) \\<le> real(Suc N))\"\nproof safe\n  fix K :: real\n  from reals_Archimedean2 obtain n :: nat where \"K < real n\" ..\n  then have \"K \\<le> real (Suc n)\" by auto\n  moreover assume \"\\<forall>m. norm (X m) \\<le> K\"\n  ultimately have \"\\<forall>m. norm (X m) \\<le> real (Suc n)\"\n    by (blast intro: order_trans)\n  then show \"\\<exists>N. \\<forall>n. norm (X n) \\<le> real (Suc N)\" ..\nnext\n  show \"\\<And>N. \\<forall>n. norm (X n) \\<le> real (Suc N) \\<Longrightarrow> \\<exists>K>0. \\<forall>n. norm (X n) \\<le> K\"\n    using of_nat_0_less_iff by blast\nqed\n\ntext \\<open>Alternative definition for \\<open>Bseq\\<close>.\\<close>\nlemma Bseq_iff: \"Bseq X \\<longleftrightarrow> (\\<exists>N. \\<forall>n. norm (X n) \\<le> real(Suc N))\"\n  by (simp add: Bseq_def) (simp add: lemma_NBseq_def)\n\nlemma lemma_NBseq_def2: \"(\\<exists>K > 0. \\<forall>n. norm (X n) \\<le> K) = (\\<exists>N. \\<forall>n. norm (X n) < real(Suc N))\"\n  apply (subst lemma_NBseq_def)\n  apply auto\n   apply (rule_tac x = \"Suc N\" in exI)\n   apply (rule_tac [2] x = N in exI)\n   apply auto\n   prefer 2 apply (blast intro: order_less_imp_le)\n  apply (drule_tac x = n in spec)\n  apply simp\n  done\n\ntext \\<open>Yet another definition for Bseq.\\<close>\nlemma Bseq_iff1a: \"Bseq X \\<longleftrightarrow> (\\<exists>N. \\<forall>n. norm (X n) < real (Suc N))\"\n  by (simp add: Bseq_def lemma_NBseq_def2)\n\nsubsubsection \\<open>A Few More Equivalence Theorems for Boundedness\\<close>\n\ntext \\<open>Alternative formulation for boundedness.\\<close>\nlemma Bseq_iff2: \"Bseq X \\<longleftrightarrow> (\\<exists>k > 0. \\<exists>x. \\<forall>n. norm (X n + - x) \\<le> k)\"\n  apply (unfold Bseq_def)\n  apply safe\n   apply (rule_tac [2] x = \"k + norm x\" in exI)\n   apply (rule_tac x = K in exI)\n   apply simp\n   apply (rule exI [where x = 0])\n   apply auto\n   apply (erule order_less_le_trans)\n   apply simp\n  apply (drule_tac x=n in spec)\n  apply (drule order_trans [OF norm_triangle_ineq2])\n  apply simp\n  done\n\ntext \\<open>Alternative formulation for boundedness.\\<close>\nlemma Bseq_iff3: \"Bseq X \\<longleftrightarrow> (\\<exists>k>0. \\<exists>N. \\<forall>n. norm (X n + - X N) \\<le> k)\"\n  (is \"?P \\<longleftrightarrow> ?Q\")\nproof\n  assume ?P\n  then obtain K where *: \"0 < K\" and **: \"\\<And>n. norm (X n) \\<le> K\"\n    by (auto simp add: Bseq_def)\n  from * have \"0 < K + norm (X 0)\" by (rule order_less_le_trans) simp\n  from ** have \"\\<forall>n. norm (X n - X 0) \\<le> K + norm (X 0)\"\n    by (auto intro: order_trans norm_triangle_ineq4)\n  then have \"\\<forall>n. norm (X n + - X 0) \\<le> K + norm (X 0)\"\n    by simp\n  with \\<open>0 < K + norm (X 0)\\<close> show ?Q by blast\nnext\n  assume ?Q\n  then show ?P by (auto simp add: Bseq_iff2)\nqed\n\nlemma BseqI2: \"\\<forall>n. k \\<le> f n \\<and> f n \\<le> K \\<Longrightarrow> Bseq f\"\n  for k K :: real\n  apply (simp add: Bseq_def)\n  apply (rule_tac x = \"(\\<bar>k\\<bar> + \\<bar>K\\<bar>) + 1\" in exI)\n  apply auto\n  apply (drule_tac x = n in spec)\n  apply arith\n  done\n\n\nsubsubsection \\<open>Upper Bounds and Lubs of Bounded Sequences\\<close>\n\nlemma Bseq_minus_iff: \"Bseq (\\<lambda>n. - (X n) :: 'a::real_normed_vector) \\<longleftrightarrow> Bseq X\"\n  by (simp add: Bseq_def)\n\nlemma Bseq_add:\n  fixes f :: \"nat \\<Rightarrow> 'a::real_normed_vector\"\n  assumes \"Bseq f\"\n  shows \"Bseq (\\<lambda>x. f x + c)\"\nproof -\n  from assms obtain K where K: \"\\<And>x. norm (f x) \\<le> K\"\n    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  then show ?thesis by (rule BseqI')\nqed\n\nlemma Bseq_add_iff: \"Bseq (\\<lambda>x. f x + c) \\<longleftrightarrow> Bseq f\"\n  for f :: \"nat \\<Rightarrow> 'a::real_normed_vector\"\n  using Bseq_add[of f c] Bseq_add[of \"\\<lambda>x. f x + c\" \"-c\"] by auto\n\nlemma Bseq_mult:\n  fixes f g :: \"nat \\<Rightarrow> 'a::real_normed_field\"\n  assumes \"Bseq f\" and \"Bseq g\"\n  shows \"Bseq (\\<lambda>x. f x * g x)\"\nproof -\n  from assms obtain K1 K2 where K: \"norm (f x) \\<le> K1\" \"K1 > 0\" \"norm (g x) \\<le> K2\" \"K2 > 0\"\n    for x\n    unfolding Bseq_def by blast\n  then have \"norm (f x * g x) \\<le> K1 * K2\" for x\n    by (auto simp: norm_mult intro!: mult_mono)\n  then show ?thesis by (rule BseqI')\nqed\n\nlemma Bfun_const [simp]: \"Bfun (\\<lambda>_. c) F\"\n  unfolding Bfun_metric_def by (auto intro!: exI[of _ c] exI[of _ \"1::real\"])\n\nlemma Bseq_cmult_iff:\n  fixes c :: \"'a::real_normed_field\"\n  assumes \"c \\<noteq> 0\"\n  shows \"Bseq (\\<lambda>x. c * f x) \\<longleftrightarrow> Bseq f\"\nproof\n  assume \"Bseq (\\<lambda>x. c * f x)\"\n  with Bfun_const have \"Bseq (\\<lambda>x. inverse c * (c * f x))\"\n    by (rule Bseq_mult)\n  with \\<open>c \\<noteq> 0\\<close> show \"Bseq f\"\n    by (simp add: divide_simps)\nqed (intro Bseq_mult Bfun_const)\n\nlemma Bseq_subseq: \"Bseq f \\<Longrightarrow> Bseq (\\<lambda>x. f (g x))\"\n  for f :: \"nat \\<Rightarrow> 'a::real_normed_vector\"\n  unfolding Bseq_def by auto\n\nlemma Bseq_Suc_iff: \"Bseq (\\<lambda>n. f (Suc n)) \\<longleftrightarrow> Bseq f\"\n  for f :: \"nat \\<Rightarrow> 'a::real_normed_vector\"\n  using Bseq_offset[of f 1] by (auto intro: Bseq_subseq)\n\nlemma increasing_Bseq_subseq_iff:\n  assumes \"\\<And>x y. x \\<le> y \\<Longrightarrow> norm (f x :: 'a::real_normed_vector) \\<le> norm (f y)\" \"subseq g\"\n  shows \"Bseq (\\<lambda>x. f (g x)) \\<longleftrightarrow> Bseq f\"\nproof\n  assume \"Bseq (\\<lambda>x. f (g x))\"\n  then obtain K where K: \"\\<And>x. norm (f (g x)) \\<le> K\"\n    unfolding Bseq_def by auto\n  {\n    fix x :: nat\n    from filterlim_subseq[OF assms(2)] obtain y where \"g y \\<ge> x\"\n      by (auto simp: filterlim_at_top eventually_at_top_linorder)\n    then have \"norm (f x) \\<le> norm (f (g y))\"\n      using assms(1) by blast\n    also have \"norm (f (g y)) \\<le> K\" by (rule K)\n    finally have \"norm (f x) \\<le> K\" .\n  }\n  then show \"Bseq f\" by (rule BseqI')\nqed (use Bseq_subseq[of f g] in simp_all)\n\nlemma nonneg_incseq_Bseq_subseq_iff:\n  fixes f :: \"nat \\<Rightarrow> real\"\n    and g :: \"nat \\<Rightarrow> nat\"\n  assumes \"\\<And>x. f x \\<ge> 0\" \"incseq f\" \"subseq g\"\n  shows \"Bseq (\\<lambda>x. f (g x)) \\<longleftrightarrow> Bseq f\"\n  using assms by (intro increasing_Bseq_subseq_iff) (auto simp: incseq_def)\n\nlemma Bseq_eq_bounded: \"range f \\<subseteq> {a..b} \\<Longrightarrow> Bseq f\"\n  for a b :: real\n  apply (simp add: subset_eq)\n  apply (rule BseqI'[where K=\"max (norm a) (norm b)\"])\n  apply (erule_tac x=n in allE)\n  apply auto\n  done\n\nlemma incseq_bounded: \"incseq X \\<Longrightarrow> \\<forall>i. X i \\<le> B \\<Longrightarrow> Bseq X\"\n  for B :: real\n  by (intro Bseq_eq_bounded[of X \"X 0\" B]) (auto simp: incseq_def)\n\nlemma decseq_bounded: \"decseq X \\<Longrightarrow> \\<forall>i. B \\<le> X i \\<Longrightarrow> Bseq X\"\n  for B :: real\n  by (intro Bseq_eq_bounded[of X B \"X 0\"]) (auto simp: decseq_def)\n\n\nsubsection \\<open>Bounded Monotonic Sequences\\<close>\n\nsubsubsection \\<open>A Bounded and Monotonic Sequence Converges\\<close>\n\n(* TODO: delete *)\n(* FIXME: one use in NSA/HSEQ.thy *)\nlemma Bmonoseq_LIMSEQ: \"\\<forall>n. m \\<le> n \\<longrightarrow> X n = X m \\<Longrightarrow> \\<exists>L. X \\<longlonglongrightarrow> L\"\n  apply (rule_tac x=\"X m\" in exI)\n  apply (rule filterlim_cong[THEN iffD2, OF refl refl _ tendsto_const])\n  unfolding eventually_sequentially\n  apply blast\n  done\n\n\nsubsection \\<open>Convergence to Zero\\<close>\n\ndefinition Zfun :: \"('a \\<Rightarrow> 'b::real_normed_vector) \\<Rightarrow> 'a filter \\<Rightarrow> bool\"\n  where \"Zfun f F = (\\<forall>r>0. eventually (\\<lambda>x. norm (f x) < r) F)\"\n\nlemma ZfunI: \"(\\<And>r. 0 < r \\<Longrightarrow> eventually (\\<lambda>x. norm (f x) < r) F) \\<Longrightarrow> Zfun f F\"\n  by (simp add: Zfun_def)\n\nlemma ZfunD: \"Zfun f F \\<Longrightarrow> 0 < r \\<Longrightarrow> eventually (\\<lambda>x. norm (f x) < r) F\"\n  by (simp add: Zfun_def)\n\nlemma Zfun_ssubst: \"eventually (\\<lambda>x. f x = g x) F \\<Longrightarrow> Zfun g F \\<Longrightarrow> Zfun f F\"\n  unfolding Zfun_def by (auto elim!: eventually_rev_mp)\n\nlemma Zfun_zero: \"Zfun (\\<lambda>x. 0) F\"\n  unfolding Zfun_def by simp\n\nlemma Zfun_norm_iff: \"Zfun (\\<lambda>x. norm (f x)) F = Zfun (\\<lambda>x. f x) F\"\n  unfolding Zfun_def by simp\n\nlemma Zfun_imp_Zfun:\n  assumes f: \"Zfun f F\"\n    and g: \"eventually (\\<lambda>x. norm (g x) \\<le> norm (f x) * K) F\"\n  shows \"Zfun (\\<lambda>x. g x) F\"\nproof (cases \"0 < K\")\n  case K: True\n  show ?thesis\n  proof (rule ZfunI)\n    fix r :: real\n    assume \"0 < r\"\n    then have \"0 < r / K\" using K by simp\n    then have \"eventually (\\<lambda>x. norm (f x) < r / K) F\"\n      using ZfunD [OF f] by blast\n    with g show \"eventually (\\<lambda>x. norm (g x) < r) F\"\n    proof eventually_elim\n      case (elim x)\n      then have \"norm (f x) * K < r\"\n        by (simp add: pos_less_divide_eq K)\n      then show ?case\n        by (simp add: order_le_less_trans [OF elim(1)])\n    qed\n  qed\nnext\n  case False\n  then have K: \"K \\<le> 0\" by (simp only: not_less)\n  show ?thesis\n  proof (rule ZfunI)\n    fix r :: real\n    assume \"0 < r\"\n    from g show \"eventually (\\<lambda>x. norm (g x) < r) F\"\n    proof eventually_elim\n      case (elim x)\n      also have \"norm (f x) * K \\<le> norm (f x) * 0\"\n        using K norm_ge_zero by (rule mult_left_mono)\n      finally show ?case\n        using \\<open>0 < r\\<close> by simp\n    qed\n  qed\nqed\n\nlemma Zfun_le: \"Zfun g F \\<Longrightarrow> \\<forall>x. norm (f x) \\<le> norm (g x) \\<Longrightarrow> Zfun f F\"\n  by (erule Zfun_imp_Zfun [where K = 1]) simp\n\nlemma Zfun_add:\n  assumes f: \"Zfun f F\"\n    and g: \"Zfun g F\"\n  shows \"Zfun (\\<lambda>x. f x + g x) F\"\nproof (rule ZfunI)\n  fix r :: real\n  assume \"0 < r\"\n  then have r: \"0 < r / 2\" by simp\n  have \"eventually (\\<lambda>x. norm (f x) < r/2) F\"\n    using f r by (rule ZfunD)\n  moreover\n  have \"eventually (\\<lambda>x. norm (g x) < r/2) F\"\n    using g r by (rule ZfunD)\n  ultimately\n  show \"eventually (\\<lambda>x. norm (f x + g x) < r) F\"\n  proof eventually_elim\n    case (elim x)\n    have \"norm (f x + g x) \\<le> norm (f x) + norm (g x)\"\n      by (rule norm_triangle_ineq)\n    also have \"\\<dots> < r/2 + r/2\"\n      using elim by (rule add_strict_mono)\n    finally show ?case\n      by simp\n  qed\nqed\n\nlemma Zfun_minus: \"Zfun f F \\<Longrightarrow> Zfun (\\<lambda>x. - f x) F\"\n  unfolding Zfun_def by simp\n\nlemma Zfun_diff: \"Zfun f F \\<Longrightarrow> Zfun g F \\<Longrightarrow> Zfun (\\<lambda>x. f x - g x) F\"\n  using Zfun_add [of f F \"\\<lambda>x. - g x\"] by (simp add: Zfun_minus)\n\nlemma (in bounded_linear) Zfun:\n  assumes g: \"Zfun g F\"\n  shows \"Zfun (\\<lambda>x. f (g x)) F\"\nproof -\n  obtain K where \"norm (f x) \\<le> norm x * K\" for x\n    using bounded by blast\n  then have \"eventually (\\<lambda>x. norm (f (g x)) \\<le> norm (g x) * K) F\"\n    by simp\n  with g show ?thesis\n    by (rule Zfun_imp_Zfun)\nqed\n\nlemma (in bounded_bilinear) Zfun:\n  assumes f: \"Zfun f F\"\n    and g: \"Zfun g F\"\n  shows \"Zfun (\\<lambda>x. f x ** g x) F\"\nproof (rule ZfunI)\n  fix r :: real\n  assume r: \"0 < r\"\n  obtain K where K: \"0 < K\"\n    and norm_le: \"norm (x ** y) \\<le> norm x * norm y * K\" for x y\n    using pos_bounded by blast\n  from K have K': \"0 < inverse K\"\n    by (rule positive_imp_inverse_positive)\n  have \"eventually (\\<lambda>x. norm (f x) < r) F\"\n    using f r by (rule ZfunD)\n  moreover\n  have \"eventually (\\<lambda>x. norm (g x) < inverse K) F\"\n    using g K' by (rule ZfunD)\n  ultimately\n  show \"eventually (\\<lambda>x. norm (f x ** g x) < r) F\"\n  proof eventually_elim\n    case (elim x)\n    have \"norm (f x ** g x) \\<le> norm (f x) * norm (g x) * K\"\n      by (rule norm_le)\n    also have \"norm (f x) * norm (g x) * K < r * inverse K * K\"\n      by (intro mult_strict_right_mono mult_strict_mono' norm_ge_zero elim K)\n    also from K have \"r * inverse K * K = r\"\n      by simp\n    finally show ?case .\n  qed\nqed\n\nlemma (in bounded_bilinear) Zfun_left: \"Zfun f F \\<Longrightarrow> Zfun (\\<lambda>x. f x ** a) F\"\n  by (rule bounded_linear_left [THEN bounded_linear.Zfun])\n\nlemma (in bounded_bilinear) Zfun_right: \"Zfun f F \\<Longrightarrow> Zfun (\\<lambda>x. a ** f x) F\"\n  by (rule bounded_linear_right [THEN bounded_linear.Zfun])\n\nlemmas Zfun_mult = bounded_bilinear.Zfun [OF bounded_bilinear_mult]\nlemmas Zfun_mult_right = bounded_bilinear.Zfun_right [OF bounded_bilinear_mult]\nlemmas Zfun_mult_left = bounded_bilinear.Zfun_left [OF bounded_bilinear_mult]\n\nlemma tendsto_Zfun_iff: \"(f \\<longlongrightarrow> a) F = Zfun (\\<lambda>x. f x - a) F\"\n  by (simp only: tendsto_iff Zfun_def dist_norm)\n\nlemma tendsto_0_le:\n  \"(f \\<longlongrightarrow> 0) F \\<Longrightarrow> eventually (\\<lambda>x. norm (g x) \\<le> norm (f x) * K) F \\<Longrightarrow> (g \\<longlongrightarrow> 0) F\"\n  by (simp add: Zfun_imp_Zfun tendsto_Zfun_iff)\n\n\nsubsubsection \\<open>Distance and norms\\<close>\n\nlemma tendsto_dist [tendsto_intros]:\n  fixes l m :: \"'a::metric_space\"\n  assumes f: \"(f \\<longlongrightarrow> l) F\"\n    and g: \"(g \\<longlongrightarrow> m) F\"\n  shows \"((\\<lambda>x. dist (f x) (g x)) \\<longlongrightarrow> dist l m) F\"\nproof (rule tendstoI)\n  fix e :: real\n  assume \"0 < e\"\n  then have e2: \"0 < e/2\" by simp\n  from tendstoD [OF f e2] tendstoD [OF g e2]\n  show \"eventually (\\<lambda>x. dist (dist (f x) (g x)) (dist l m) < e) F\"\n  proof (eventually_elim)\n    case (elim x)\n    then show \"dist (dist (f x) (g x)) (dist l m) < e\"\n      unfolding dist_real_def\n      using dist_triangle2 [of \"f x\" \"g x\" \"l\"]\n        and dist_triangle2 [of \"g x\" \"l\" \"m\"]\n        and dist_triangle3 [of \"l\" \"m\" \"f x\"]\n        and dist_triangle [of \"f x\" \"m\" \"g x\"]\n      by arith\n  qed\nqed\n\nlemma continuous_dist[continuous_intros]:\n  fixes f g :: \"_ \\<Rightarrow> 'a :: metric_space\"\n  shows \"continuous F f \\<Longrightarrow> continuous F g \\<Longrightarrow> continuous F (\\<lambda>x. dist (f x) (g x))\"\n  unfolding continuous_def by (rule tendsto_dist)\n\nlemma continuous_on_dist[continuous_intros]:\n  fixes f g :: \"_ \\<Rightarrow> 'a :: metric_space\"\n  shows \"continuous_on s f \\<Longrightarrow> continuous_on s g \\<Longrightarrow> continuous_on s (\\<lambda>x. dist (f x) (g x))\"\n  unfolding continuous_on_def by (auto intro: tendsto_dist)\n\nlemma tendsto_norm [tendsto_intros]: \"(f \\<longlongrightarrow> a) F \\<Longrightarrow> ((\\<lambda>x. norm (f x)) \\<longlongrightarrow> norm a) F\"\n  unfolding norm_conv_dist by (intro tendsto_intros)\n\nlemma continuous_norm [continuous_intros]: \"continuous F f \\<Longrightarrow> continuous F (\\<lambda>x. norm (f x))\"\n  unfolding continuous_def by (rule tendsto_norm)\n\nlemma continuous_on_norm [continuous_intros]:\n  \"continuous_on s f \\<Longrightarrow> continuous_on s (\\<lambda>x. norm (f x))\"\n  unfolding continuous_on_def by (auto intro: tendsto_norm)\n\nlemma tendsto_norm_zero: \"(f \\<longlongrightarrow> 0) F \\<Longrightarrow> ((\\<lambda>x. norm (f x)) \\<longlongrightarrow> 0) F\"\n  by (drule tendsto_norm) simp\n\nlemma tendsto_norm_zero_cancel: \"((\\<lambda>x. norm (f x)) \\<longlongrightarrow> 0) F \\<Longrightarrow> (f \\<longlongrightarrow> 0) F\"\n  unfolding tendsto_iff dist_norm by simp\n\nlemma tendsto_norm_zero_iff: \"((\\<lambda>x. norm (f x)) \\<longlongrightarrow> 0) F \\<longleftrightarrow> (f \\<longlongrightarrow> 0) F\"\n  unfolding tendsto_iff dist_norm by simp\n\nlemma tendsto_rabs [tendsto_intros]: \"(f \\<longlongrightarrow> l) F \\<Longrightarrow> ((\\<lambda>x. \\<bar>f x\\<bar>) \\<longlongrightarrow> \\<bar>l\\<bar>) F\"\n  for l :: real\n  by (fold real_norm_def) (rule tendsto_norm)\n\nlemma continuous_rabs [continuous_intros]:\n  \"continuous F f \\<Longrightarrow> continuous F (\\<lambda>x. \\<bar>f x :: real\\<bar>)\"\n  unfolding real_norm_def[symmetric] by (rule continuous_norm)\n\nlemma continuous_on_rabs [continuous_intros]:\n  \"continuous_on s f \\<Longrightarrow> continuous_on s (\\<lambda>x. \\<bar>f x :: real\\<bar>)\"\n  unfolding real_norm_def[symmetric] by (rule continuous_on_norm)\n\nlemma tendsto_rabs_zero: \"(f \\<longlongrightarrow> (0::real)) F \\<Longrightarrow> ((\\<lambda>x. \\<bar>f x\\<bar>) \\<longlongrightarrow> 0) F\"\n  by (fold real_norm_def) (rule tendsto_norm_zero)\n\nlemma tendsto_rabs_zero_cancel: \"((\\<lambda>x. \\<bar>f x\\<bar>) \\<longlongrightarrow> (0::real)) F \\<Longrightarrow> (f \\<longlongrightarrow> 0) F\"\n  by (fold real_norm_def) (rule tendsto_norm_zero_cancel)\n\nlemma tendsto_rabs_zero_iff: \"((\\<lambda>x. \\<bar>f x\\<bar>) \\<longlongrightarrow> (0::real)) F \\<longleftrightarrow> (f \\<longlongrightarrow> 0) F\"\n  by (fold real_norm_def) (rule tendsto_norm_zero_iff)\n\n\nsubsection \\<open>Topological Monoid\\<close>\n\nclass topological_monoid_add = topological_space + monoid_add +\n  assumes tendsto_add_Pair: \"LIM x (nhds a \\<times>\\<^sub>F nhds b). fst x + snd x :> nhds (a + b)\"\n\nclass topological_comm_monoid_add = topological_monoid_add + comm_monoid_add\n\nlemma tendsto_add [tendsto_intros]:\n  fixes a b :: \"'a::topological_monoid_add\"\n  shows \"(f \\<longlongrightarrow> a) F \\<Longrightarrow> (g \\<longlongrightarrow> b) F \\<Longrightarrow> ((\\<lambda>x. f x + g x) \\<longlongrightarrow> a + b) F\"\n  using filterlim_compose[OF tendsto_add_Pair, of \"\\<lambda>x. (f x, g x)\" a b F]\n  by (simp add: nhds_prod[symmetric] tendsto_Pair)\n\nlemma continuous_add [continuous_intros]:\n  fixes f g :: \"_ \\<Rightarrow> 'b::topological_monoid_add\"\n  shows \"continuous F f \\<Longrightarrow> continuous F g \\<Longrightarrow> continuous F (\\<lambda>x. f x + g x)\"\n  unfolding continuous_def by (rule tendsto_add)\n\nlemma continuous_on_add [continuous_intros]:\n  fixes f g :: \"_ \\<Rightarrow> 'b::topological_monoid_add\"\n  shows \"continuous_on s f \\<Longrightarrow> continuous_on s g \\<Longrightarrow> continuous_on s (\\<lambda>x. f x + g x)\"\n  unfolding continuous_on_def by (auto intro: tendsto_add)\n\nlemma tendsto_add_zero:\n  fixes f g :: \"_ \\<Rightarrow> 'b::topological_monoid_add\"\n  shows \"(f \\<longlongrightarrow> 0) F \\<Longrightarrow> (g \\<longlongrightarrow> 0) F \\<Longrightarrow> ((\\<lambda>x. f x + g x) \\<longlongrightarrow> 0) F\"\n  by (drule (1) tendsto_add) simp\n\nlemma tendsto_sum [tendsto_intros]:\n  fixes f :: \"'a \\<Rightarrow> 'b \\<Rightarrow> 'c::topological_comm_monoid_add\"\n  shows \"(\\<And>i. i \\<in> I \\<Longrightarrow> (f i \\<longlongrightarrow> a i) F) \\<Longrightarrow> ((\\<lambda>x. \\<Sum>i\\<in>I. f i x) \\<longlongrightarrow> (\\<Sum>i\\<in>I. a i)) F\"\n  by (induct I rule: infinite_finite_induct) (simp_all add: tendsto_add)\n\nlemma continuous_sum [continuous_intros]:\n  fixes f :: \"'a \\<Rightarrow> 'b::t2_space \\<Rightarrow> 'c::topological_comm_monoid_add\"\n  shows \"(\\<And>i. i \\<in> I \\<Longrightarrow> continuous F (f i)) \\<Longrightarrow> continuous F (\\<lambda>x. \\<Sum>i\\<in>I. f i x)\"\n  unfolding continuous_def by (rule tendsto_sum)\n\nlemma continuous_on_sum [continuous_intros]:\n  fixes f :: \"'a \\<Rightarrow> 'b::topological_space \\<Rightarrow> 'c::topological_comm_monoid_add\"\n  shows \"(\\<And>i. i \\<in> I \\<Longrightarrow> continuous_on S (f i)) \\<Longrightarrow> continuous_on S (\\<lambda>x. \\<Sum>i\\<in>I. f i x)\"\n  unfolding continuous_on_def by (auto intro: tendsto_sum)\n\ninstance nat :: topological_comm_monoid_add\n  by standard\n    (simp add: nhds_discrete principal_prod_principal filterlim_principal eventually_principal)\n\ninstance int :: topological_comm_monoid_add\n  by standard\n    (simp add: nhds_discrete principal_prod_principal filterlim_principal eventually_principal)\n\n\nsubsubsection \\<open>Topological group\\<close>\n\nclass topological_group_add = topological_monoid_add + group_add +\n  assumes tendsto_uminus_nhds: \"(uminus \\<longlongrightarrow> - a) (nhds a)\"\nbegin\n\nlemma tendsto_minus [tendsto_intros]: \"(f \\<longlongrightarrow> a) F \\<Longrightarrow> ((\\<lambda>x. - f x) \\<longlongrightarrow> - a) F\"\n  by (rule filterlim_compose[OF tendsto_uminus_nhds])\n\nend\n\nclass topological_ab_group_add = topological_group_add + ab_group_add\n\ninstance topological_ab_group_add < topological_comm_monoid_add ..\n\nlemma continuous_minus [continuous_intros]: \"continuous F f \\<Longrightarrow> continuous F (\\<lambda>x. - f x)\"\n  for f :: \"'a::t2_space \\<Rightarrow> 'b::topological_group_add\"\n  unfolding continuous_def by (rule tendsto_minus)\n\nlemma continuous_on_minus [continuous_intros]: \"continuous_on s f \\<Longrightarrow> continuous_on s (\\<lambda>x. - f x)\"\n  for f :: \"_ \\<Rightarrow> 'b::topological_group_add\"\n  unfolding continuous_on_def by (auto intro: tendsto_minus)\n\nlemma tendsto_minus_cancel: \"((\\<lambda>x. - f x) \\<longlongrightarrow> - a) F \\<Longrightarrow> (f \\<longlongrightarrow> a) F\"\n  for a :: \"'a::topological_group_add\"\n  by (drule tendsto_minus) simp\n\nlemma tendsto_minus_cancel_left:\n  \"(f \\<longlongrightarrow> - (y::_::topological_group_add)) F \\<longleftrightarrow> ((\\<lambda>x. - f x) \\<longlongrightarrow> y) F\"\n  using tendsto_minus_cancel[of f \"- y\" F]  tendsto_minus[of f \"- y\" F]\n  by auto\n\nlemma tendsto_diff [tendsto_intros]:\n  fixes a b :: \"'a::topological_group_add\"\n  shows \"(f \\<longlongrightarrow> a) F \\<Longrightarrow> (g \\<longlongrightarrow> b) F \\<Longrightarrow> ((\\<lambda>x. f x - g x) \\<longlongrightarrow> a - b) F\"\n  using tendsto_add [of f a F \"\\<lambda>x. - g x\" \"- b\"] by (simp add: tendsto_minus)\n\nlemma continuous_diff [continuous_intros]:\n  fixes f g :: \"'a::t2_space \\<Rightarrow> 'b::topological_group_add\"\n  shows \"continuous F f \\<Longrightarrow> continuous F g \\<Longrightarrow> continuous F (\\<lambda>x. f x - g x)\"\n  unfolding continuous_def by (rule tendsto_diff)\n\nlemma continuous_on_diff [continuous_intros]:\n  fixes f g :: \"_ \\<Rightarrow> 'b::topological_group_add\"\n  shows \"continuous_on s f \\<Longrightarrow> continuous_on s g \\<Longrightarrow> continuous_on s (\\<lambda>x. f x - g x)\"\n  unfolding continuous_on_def by (auto intro: tendsto_diff)\n\nlemma continuous_on_op_minus: \"continuous_on (s::'a::topological_group_add set) (op - x)\"\n  by (rule continuous_intros | simp)+\n\ninstance real_normed_vector < topological_ab_group_add\nproof\n  fix a b :: 'a\n  show \"((\\<lambda>x. fst x + snd x) \\<longlongrightarrow> a + b) (nhds a \\<times>\\<^sub>F nhds b)\"\n    unfolding tendsto_Zfun_iff add_diff_add\n    using tendsto_fst[OF filterlim_ident, of \"(a,b)\"] tendsto_snd[OF filterlim_ident, of \"(a,b)\"]\n    by (intro Zfun_add)\n       (auto simp add: tendsto_Zfun_iff[symmetric] nhds_prod[symmetric] intro!: tendsto_fst)\n  show \"(uminus \\<longlongrightarrow> - a) (nhds a)\"\n    unfolding tendsto_Zfun_iff minus_diff_minus\n    using filterlim_ident[of \"nhds a\"]\n    by (intro Zfun_minus) (simp add: tendsto_Zfun_iff)\nqed\n\nlemmas real_tendsto_sandwich = tendsto_sandwich[where 'b=real]\n\n\nsubsubsection \\<open>Linear operators and multiplication\\<close>\n\nlemma linear_times: \"linear (\\<lambda>x. c * x)\"\n  for c :: \"'a::real_algebra\"\n  by (auto simp: linearI distrib_left)\n\nlemma (in bounded_linear) tendsto: \"(g \\<longlongrightarrow> a) F \\<Longrightarrow> ((\\<lambda>x. f (g x)) \\<longlongrightarrow> f a) F\"\n  by (simp only: tendsto_Zfun_iff diff [symmetric] Zfun)\n\nlemma (in bounded_linear) continuous: \"continuous F g \\<Longrightarrow> continuous F (\\<lambda>x. f (g x))\"\n  using tendsto[of g _ F] by (auto simp: continuous_def)\n\nlemma (in bounded_linear) continuous_on: \"continuous_on s g \\<Longrightarrow> continuous_on s (\\<lambda>x. f (g x))\"\n  using tendsto[of g] by (auto simp: continuous_on_def)\n\nlemma (in bounded_linear) tendsto_zero: \"(g \\<longlongrightarrow> 0) F \\<Longrightarrow> ((\\<lambda>x. f (g x)) \\<longlongrightarrow> 0) F\"\n  by (drule tendsto) (simp only: zero)\n\nlemma (in bounded_bilinear) tendsto:\n  \"(f \\<longlongrightarrow> a) F \\<Longrightarrow> (g \\<longlongrightarrow> b) F \\<Longrightarrow> ((\\<lambda>x. f x ** g x) \\<longlongrightarrow> a ** b) F\"\n  by (simp only: tendsto_Zfun_iff prod_diff_prod Zfun_add Zfun Zfun_left Zfun_right)\n\nlemma (in bounded_bilinear) continuous:\n  \"continuous F f \\<Longrightarrow> continuous F g \\<Longrightarrow> continuous F (\\<lambda>x. f x ** g x)\"\n  using tendsto[of f _ F g] by (auto simp: continuous_def)\n\nlemma (in bounded_bilinear) continuous_on:\n  \"continuous_on s f \\<Longrightarrow> continuous_on s g \\<Longrightarrow> continuous_on s (\\<lambda>x. f x ** g x)\"\n  using tendsto[of f _ _ g] by (auto simp: continuous_on_def)\n\nlemma (in bounded_bilinear) tendsto_zero:\n  assumes f: \"(f \\<longlongrightarrow> 0) F\"\n    and g: \"(g \\<longlongrightarrow> 0) F\"\n  shows \"((\\<lambda>x. f x ** g x) \\<longlongrightarrow> 0) F\"\n  using tendsto [OF f g] by (simp add: zero_left)\n\nlemma (in bounded_bilinear) tendsto_left_zero:\n  \"(f \\<longlongrightarrow> 0) F \\<Longrightarrow> ((\\<lambda>x. f x ** c) \\<longlongrightarrow> 0) F\"\n  by (rule bounded_linear.tendsto_zero [OF bounded_linear_left])\n\nlemma (in bounded_bilinear) tendsto_right_zero:\n  \"(f \\<longlongrightarrow> 0) F \\<Longrightarrow> ((\\<lambda>x. c ** f x) \\<longlongrightarrow> 0) F\"\n  by (rule bounded_linear.tendsto_zero [OF bounded_linear_right])\n\nlemmas tendsto_of_real [tendsto_intros] =\n  bounded_linear.tendsto [OF bounded_linear_of_real]\n\nlemmas tendsto_scaleR [tendsto_intros] =\n  bounded_bilinear.tendsto [OF bounded_bilinear_scaleR]\n\nlemmas tendsto_mult [tendsto_intros] =\n  bounded_bilinear.tendsto [OF bounded_bilinear_mult]\n\nlemma tendsto_mult_left: \"(f \\<longlongrightarrow> l) F \\<Longrightarrow> ((\\<lambda>x. c * (f x)) \\<longlongrightarrow> c * l) F\"\n  for c :: \"'a::real_normed_algebra\"\n  by (rule tendsto_mult [OF tendsto_const])\n\nlemma tendsto_mult_right: \"(f \\<longlongrightarrow> l) F \\<Longrightarrow> ((\\<lambda>x. (f x) * c) \\<longlongrightarrow> l * c) F\"\n  for c :: \"'a::real_normed_algebra\"\n  by (rule tendsto_mult [OF _ tendsto_const])\n\nlemmas continuous_of_real [continuous_intros] =\n  bounded_linear.continuous [OF bounded_linear_of_real]\n\nlemmas continuous_scaleR [continuous_intros] =\n  bounded_bilinear.continuous [OF bounded_bilinear_scaleR]\n\nlemmas continuous_mult [continuous_intros] =\n  bounded_bilinear.continuous [OF bounded_bilinear_mult]\n\nlemmas continuous_on_of_real [continuous_intros] =\n  bounded_linear.continuous_on [OF bounded_linear_of_real]\n\nlemmas continuous_on_scaleR [continuous_intros] =\n  bounded_bilinear.continuous_on [OF bounded_bilinear_scaleR]\n\nlemmas continuous_on_mult [continuous_intros] =\n  bounded_bilinear.continuous_on [OF bounded_bilinear_mult]\n\nlemmas tendsto_mult_zero =\n  bounded_bilinear.tendsto_zero [OF bounded_bilinear_mult]\n\nlemmas tendsto_mult_left_zero =\n  bounded_bilinear.tendsto_left_zero [OF bounded_bilinear_mult]\n\nlemmas tendsto_mult_right_zero =\n  bounded_bilinear.tendsto_right_zero [OF bounded_bilinear_mult]\n\nlemma tendsto_power [tendsto_intros]: \"(f \\<longlongrightarrow> a) F \\<Longrightarrow> ((\\<lambda>x. f x ^ n) \\<longlongrightarrow> a ^ n) F\"\n  for f :: \"'a \\<Rightarrow> 'b::{power,real_normed_algebra}\"\n  by (induct n) (simp_all add: tendsto_mult)\n\nlemma continuous_power [continuous_intros]: \"continuous F f \\<Longrightarrow> continuous F (\\<lambda>x. (f x)^n)\"\n  for f :: \"'a::t2_space \\<Rightarrow> 'b::{power,real_normed_algebra}\"\n  unfolding continuous_def by (rule tendsto_power)\n\nlemma continuous_on_power [continuous_intros]:\n  fixes f :: \"_ \\<Rightarrow> 'b::{power,real_normed_algebra}\"\n  shows \"continuous_on s f \\<Longrightarrow> continuous_on s (\\<lambda>x. (f x)^n)\"\n  unfolding continuous_on_def by (auto intro: tendsto_power)\n\nlemma tendsto_prod [tendsto_intros]:\n  fixes f :: \"'a \\<Rightarrow> 'b \\<Rightarrow> 'c::{real_normed_algebra,comm_ring_1}\"\n  shows \"(\\<And>i. i \\<in> S \\<Longrightarrow> (f i \\<longlongrightarrow> L i) F) \\<Longrightarrow> ((\\<lambda>x. \\<Prod>i\\<in>S. f i x) \\<longlongrightarrow> (\\<Prod>i\\<in>S. L i)) F\"\n  by (induct S rule: infinite_finite_induct) (simp_all add: tendsto_mult)\n\nlemma continuous_prod [continuous_intros]:\n  fixes f :: \"'a \\<Rightarrow> 'b::t2_space \\<Rightarrow> 'c::{real_normed_algebra,comm_ring_1}\"\n  shows \"(\\<And>i. i \\<in> S \\<Longrightarrow> continuous F (f i)) \\<Longrightarrow> continuous F (\\<lambda>x. \\<Prod>i\\<in>S. f i x)\"\n  unfolding continuous_def by (rule tendsto_prod)\n\nlemma continuous_on_prod [continuous_intros]:\n  fixes f :: \"'a \\<Rightarrow> _ \\<Rightarrow> 'c::{real_normed_algebra,comm_ring_1}\"\n  shows \"(\\<And>i. i \\<in> S \\<Longrightarrow> continuous_on s (f i)) \\<Longrightarrow> continuous_on s (\\<lambda>x. \\<Prod>i\\<in>S. f i x)\"\n  unfolding continuous_on_def by (auto intro: tendsto_prod)\n\nlemma tendsto_of_real_iff:\n  \"((\\<lambda>x. of_real (f x) :: 'a::real_normed_div_algebra) \\<longlongrightarrow> of_real c) F \\<longleftrightarrow> (f \\<longlongrightarrow> c) F\"\n  unfolding tendsto_iff by simp\n\nlemma tendsto_add_const_iff:\n  \"((\\<lambda>x. c + f x :: 'a::real_normed_vector) \\<longlongrightarrow> c + d) F \\<longleftrightarrow> (f \\<longlongrightarrow> d) F\"\n  using tendsto_add[OF tendsto_const[of c], of f d]\n    and tendsto_add[OF tendsto_const[of \"-c\"], of \"\\<lambda>x. c + f x\" \"c + d\"] by auto\n\n\nsubsubsection \\<open>Inverse and division\\<close>\n\nlemma (in bounded_bilinear) Zfun_prod_Bfun:\n  assumes f: \"Zfun f F\"\n    and g: \"Bfun g F\"\n  shows \"Zfun (\\<lambda>x. f x ** g x) F\"\nproof -\n  obtain K where K: \"0 \\<le> K\"\n    and norm_le: \"\\<And>x y. norm (x ** y) \\<le> norm x * norm y * K\"\n    using nonneg_bounded by blast\n  obtain B where B: \"0 < B\"\n    and norm_g: \"eventually (\\<lambda>x. norm (g x) \\<le> B) F\"\n    using g by (rule BfunE)\n  have \"eventually (\\<lambda>x. norm (f x ** g x) \\<le> norm (f x) * (B * K)) F\"\n  using norm_g proof eventually_elim\n    case (elim x)\n    have \"norm (f x ** g x) \\<le> norm (f x) * norm (g x) * K\"\n      by (rule norm_le)\n    also have \"\\<dots> \\<le> norm (f x) * B * K\"\n      by (intro mult_mono' order_refl norm_g norm_ge_zero mult_nonneg_nonneg K elim)\n    also have \"\\<dots> = norm (f x) * (B * K)\"\n      by (rule mult.assoc)\n    finally show \"norm (f x ** g x) \\<le> norm (f x) * (B * K)\" .\n  qed\n  with f show ?thesis\n    by (rule Zfun_imp_Zfun)\nqed\n\nlemma (in bounded_bilinear) Bfun_prod_Zfun:\n  assumes f: \"Bfun f F\"\n    and g: \"Zfun g F\"\n  shows \"Zfun (\\<lambda>x. f x ** g x) F\"\n  using flip g f by (rule bounded_bilinear.Zfun_prod_Bfun)\n\nlemma Bfun_inverse_lemma:\n  fixes x :: \"'a::real_normed_div_algebra\"\n  shows \"r \\<le> norm x \\<Longrightarrow> 0 < r \\<Longrightarrow> norm (inverse x) \\<le> inverse r\"\n  apply (subst nonzero_norm_inverse)\n  apply clarsimp\n  apply (erule (1) le_imp_inverse_le)\n  done\n\nlemma Bfun_inverse:\n  fixes a :: \"'a::real_normed_div_algebra\"\n  assumes f: \"(f \\<longlongrightarrow> a) F\"\n  assumes a: \"a \\<noteq> 0\"\n  shows \"Bfun (\\<lambda>x. inverse (f x)) F\"\nproof -\n  from a have \"0 < norm a\" by simp\n  then have \"\\<exists>r>0. r < norm a\" by (rule dense)\n  then obtain r where r1: \"0 < r\" and r2: \"r < norm a\"\n    by blast\n  have \"eventually (\\<lambda>x. dist (f x) a < r) F\"\n    using tendstoD [OF f r1] by blast\n  then have \"eventually (\\<lambda>x. norm (inverse (f x)) \\<le> inverse (norm a - r)) F\"\n  proof eventually_elim\n    case (elim x)\n    then have 1: \"norm (f x - a) < r\"\n      by (simp add: dist_norm)\n    then have 2: \"f x \\<noteq> 0\" using r2 by auto\n    then have \"norm (inverse (f x)) = inverse (norm (f x))\"\n      by (rule nonzero_norm_inverse)\n    also have \"\\<dots> \\<le> inverse (norm a - r)\"\n    proof (rule le_imp_inverse_le)\n      show \"0 < norm a - r\"\n        using r2 by simp\n      have \"norm a - norm (f x) \\<le> norm (a - f x)\"\n        by (rule norm_triangle_ineq2)\n      also have \"\\<dots> = norm (f x - a)\"\n        by (rule norm_minus_commute)\n      also have \"\\<dots> < r\" using 1 .\n      finally show \"norm a - r \\<le> norm (f x)\"\n        by simp\n    qed\n    finally show \"norm (inverse (f x)) \\<le> inverse (norm a - r)\" .\n  qed\n  then show ?thesis by (rule BfunI)\nqed\n\nlemma tendsto_inverse [tendsto_intros]:\n  fixes a :: \"'a::real_normed_div_algebra\"\n  assumes f: \"(f \\<longlongrightarrow> a) F\"\n    and a: \"a \\<noteq> 0\"\n  shows \"((\\<lambda>x. inverse (f x)) \\<longlongrightarrow> inverse a) F\"\nproof -\n  from a have \"0 < norm a\" by simp\n  with f have \"eventually (\\<lambda>x. dist (f x) a < norm a) F\"\n    by (rule tendstoD)\n  then have \"eventually (\\<lambda>x. f x \\<noteq> 0) F\"\n    unfolding dist_norm by (auto elim!: eventually_mono)\n  with a have \"eventually (\\<lambda>x. inverse (f x) - inverse a =\n    - (inverse (f x) * (f x - a) * inverse a)) F\"\n    by (auto elim!: eventually_mono simp: inverse_diff_inverse)\n  moreover have \"Zfun (\\<lambda>x. - (inverse (f x) * (f x - a) * inverse a)) F\"\n    by (intro Zfun_minus Zfun_mult_left\n      bounded_bilinear.Bfun_prod_Zfun [OF bounded_bilinear_mult]\n      Bfun_inverse [OF f a] f [unfolded tendsto_Zfun_iff])\n  ultimately show ?thesis\n    unfolding tendsto_Zfun_iff by (rule Zfun_ssubst)\nqed\n\nlemma continuous_inverse:\n  fixes f :: \"'a::t2_space \\<Rightarrow> 'b::real_normed_div_algebra\"\n  assumes \"continuous F f\"\n    and \"f (Lim F (\\<lambda>x. x)) \\<noteq> 0\"\n  shows \"continuous F (\\<lambda>x. inverse (f x))\"\n  using assms unfolding continuous_def by (rule tendsto_inverse)\n\nlemma continuous_at_within_inverse[continuous_intros]:\n  fixes f :: \"'a::t2_space \\<Rightarrow> 'b::real_normed_div_algebra\"\n  assumes \"continuous (at a within s) f\"\n    and \"f a \\<noteq> 0\"\n  shows \"continuous (at a within s) (\\<lambda>x. inverse (f x))\"\n  using assms unfolding continuous_within by (rule tendsto_inverse)\n\nlemma isCont_inverse[continuous_intros, simp]:\n  fixes f :: \"'a::t2_space \\<Rightarrow> 'b::real_normed_div_algebra\"\n  assumes \"isCont f a\"\n    and \"f a \\<noteq> 0\"\n  shows \"isCont (\\<lambda>x. inverse (f x)) a\"\n  using assms unfolding continuous_at by (rule tendsto_inverse)\n\nlemma continuous_on_inverse[continuous_intros]:\n  fixes f :: \"'a::topological_space \\<Rightarrow> 'b::real_normed_div_algebra\"\n  assumes \"continuous_on s f\"\n    and \"\\<forall>x\\<in>s. f x \\<noteq> 0\"\n  shows \"continuous_on s (\\<lambda>x. inverse (f x))\"\n  using assms unfolding continuous_on_def by (blast intro: tendsto_inverse)\n\nlemma tendsto_divide [tendsto_intros]:\n  fixes a b :: \"'a::real_normed_field\"\n  shows \"(f \\<longlongrightarrow> a) F \\<Longrightarrow> (g \\<longlongrightarrow> b) F \\<Longrightarrow> b \\<noteq> 0 \\<Longrightarrow> ((\\<lambda>x. f x / g x) \\<longlongrightarrow> a / b) F\"\n  by (simp add: tendsto_mult tendsto_inverse divide_inverse)\n\nlemma continuous_divide:\n  fixes f g :: \"'a::t2_space \\<Rightarrow> 'b::real_normed_field\"\n  assumes \"continuous F f\"\n    and \"continuous F g\"\n    and \"g (Lim F (\\<lambda>x. x)) \\<noteq> 0\"\n  shows \"continuous F (\\<lambda>x. (f x) / (g x))\"\n  using assms unfolding continuous_def by (rule tendsto_divide)\n\nlemma continuous_at_within_divide[continuous_intros]:\n  fixes f g :: \"'a::t2_space \\<Rightarrow> 'b::real_normed_field\"\n  assumes \"continuous (at a within s) f\" \"continuous (at a within s) g\"\n    and \"g a \\<noteq> 0\"\n  shows \"continuous (at a within s) (\\<lambda>x. (f x) / (g x))\"\n  using assms unfolding continuous_within by (rule tendsto_divide)\n\nlemma isCont_divide[continuous_intros, simp]:\n  fixes f g :: \"'a::t2_space \\<Rightarrow> 'b::real_normed_field\"\n  assumes \"isCont f a\" \"isCont g a\" \"g a \\<noteq> 0\"\n  shows \"isCont (\\<lambda>x. (f x) / g x) a\"\n  using assms unfolding continuous_at by (rule tendsto_divide)\n\nlemma continuous_on_divide[continuous_intros]:\n  fixes f :: \"'a::topological_space \\<Rightarrow> 'b::real_normed_field\"\n  assumes \"continuous_on s f\" \"continuous_on s g\"\n    and \"\\<forall>x\\<in>s. g x \\<noteq> 0\"\n  shows \"continuous_on s (\\<lambda>x. (f x) / (g x))\"\n  using assms unfolding continuous_on_def by (blast intro: tendsto_divide)\n\nlemma tendsto_sgn [tendsto_intros]: \"(f \\<longlongrightarrow> l) F \\<Longrightarrow> l \\<noteq> 0 \\<Longrightarrow> ((\\<lambda>x. sgn (f x)) \\<longlongrightarrow> sgn l) F\"\n  for l :: \"'a::real_normed_vector\"\n  unfolding sgn_div_norm by (simp add: tendsto_intros)\n\nlemma continuous_sgn:\n  fixes f :: \"'a::t2_space \\<Rightarrow> 'b::real_normed_vector\"\n  assumes \"continuous F f\"\n    and \"f (Lim F (\\<lambda>x. x)) \\<noteq> 0\"\n  shows \"continuous F (\\<lambda>x. sgn (f x))\"\n  using assms unfolding continuous_def by (rule tendsto_sgn)\n\nlemma continuous_at_within_sgn[continuous_intros]:\n  fixes f :: \"'a::t2_space \\<Rightarrow> 'b::real_normed_vector\"\n  assumes \"continuous (at a within s) f\"\n    and \"f a \\<noteq> 0\"\n  shows \"continuous (at a within s) (\\<lambda>x. sgn (f x))\"\n  using assms unfolding continuous_within by (rule tendsto_sgn)\n\nlemma isCont_sgn[continuous_intros]:\n  fixes f :: \"'a::t2_space \\<Rightarrow> 'b::real_normed_vector\"\n  assumes \"isCont f a\"\n    and \"f a \\<noteq> 0\"\n  shows \"isCont (\\<lambda>x. sgn (f x)) a\"\n  using assms unfolding continuous_at by (rule tendsto_sgn)\n\nlemma continuous_on_sgn[continuous_intros]:\n  fixes f :: \"'a::topological_space \\<Rightarrow> 'b::real_normed_vector\"\n  assumes \"continuous_on s f\"\n    and \"\\<forall>x\\<in>s. f x \\<noteq> 0\"\n  shows \"continuous_on s (\\<lambda>x. sgn (f x))\"\n  using assms unfolding continuous_on_def by (blast intro: tendsto_sgn)\n\nlemma filterlim_at_infinity:\n  fixes f :: \"_ \\<Rightarrow> 'a::real_normed_vector\"\n  assumes \"0 \\<le> c\"\n  shows \"(LIM x F. f x :> at_infinity) \\<longleftrightarrow> (\\<forall>r>c. eventually (\\<lambda>x. r \\<le> norm (f x)) F)\"\n  unfolding filterlim_iff eventually_at_infinity\nproof safe\n  fix P :: \"'a \\<Rightarrow> bool\"\n  fix b\n  assume *: \"\\<forall>r>c. eventually (\\<lambda>x. r \\<le> norm (f x)) F\"\n  assume P: \"\\<forall>x. b \\<le> norm x \\<longrightarrow> P x\"\n  have \"max b (c + 1) > c\" by auto\n  with * have \"eventually (\\<lambda>x. max b (c + 1) \\<le> norm (f x)) F\"\n    by auto\n  then show \"eventually (\\<lambda>x. P (f x)) F\"\n  proof eventually_elim\n    case (elim x)\n    with P show \"P (f x)\" by auto\n  qed\nqed force\n\nlemma not_tendsto_and_filterlim_at_infinity:\n  fixes c :: \"'a::real_normed_vector\"\n  assumes \"F \\<noteq> bot\"\n    and \"(f \\<longlongrightarrow> c) F\"\n    and \"filterlim f at_infinity F\"\n  shows False\nproof -\n  from tendstoD[OF assms(2), of \"1/2\"]\n  have \"eventually (\\<lambda>x. dist (f x) c < 1/2) F\"\n    by simp\n  moreover\n  from filterlim_at_infinity[of \"norm c\" f F] assms(3)\n  have \"eventually (\\<lambda>x. norm (f x) \\<ge> norm c + 1) F\" by simp\n  ultimately have \"eventually (\\<lambda>x. False) F\"\n  proof eventually_elim\n    fix x\n    assume A: \"dist (f x) c < 1/2\"\n    assume \"norm (f x) \\<ge> norm c + 1\"\n    also have \"norm (f x) = dist (f x) 0\" by simp\n    also have \"\\<dots> \\<le> dist (f x) c + dist c 0\" by (rule dist_triangle)\n    finally show False using A by simp\n  qed\n  with assms show False by simp\nqed\n\nlemma filterlim_at_infinity_imp_not_convergent:\n  assumes \"filterlim f at_infinity sequentially\"\n  shows \"\\<not> convergent f\"\n  by (rule notI, rule not_tendsto_and_filterlim_at_infinity[OF _ _ assms])\n     (simp_all add: convergent_LIMSEQ_iff)\n\nlemma filterlim_at_infinity_imp_eventually_ne:\n  assumes \"filterlim f at_infinity F\"\n  shows \"eventually (\\<lambda>z. f z \\<noteq> c) F\"\nproof -\n  have \"norm c + 1 > 0\"\n    by (intro add_nonneg_pos) simp_all\n  with filterlim_at_infinity[OF order.refl, of f F] assms\n  have \"eventually (\\<lambda>z. norm (f z) \\<ge> norm c + 1) F\"\n    by blast\n  then show ?thesis\n    by eventually_elim auto\nqed\n\nlemma tendsto_of_nat [tendsto_intros]:\n  \"filterlim (of_nat :: nat \\<Rightarrow> 'a::real_normed_algebra_1) at_infinity sequentially\"\nproof (subst filterlim_at_infinity[OF order.refl], intro allI impI)\n  fix r :: real\n  assume r: \"r > 0\"\n  define n where \"n = nat \\<lceil>r\\<rceil>\"\n  from r have n: \"\\<forall>m\\<ge>n. of_nat m \\<ge> r\"\n    unfolding n_def by linarith\n  from eventually_ge_at_top[of n] show \"eventually (\\<lambda>m. norm (of_nat m :: 'a) \\<ge> r) sequentially\"\n    by eventually_elim (use n in simp_all)\nqed\n\n\nsubsection \\<open>Relate @{const at}, @{const at_left} and @{const at_right}\\<close>\n\ntext \\<open>\n  This lemmas are useful for conversion between @{term \"at x\"} to @{term \"at_left x\"} and\n  @{term \"at_right x\"} and also @{term \"at_right 0\"}.\n\\<close>\n\nlemmas filterlim_split_at_real = filterlim_split_at[where 'a=real]\n\nlemma filtermap_nhds_shift: \"filtermap (\\<lambda>x. x - d) (nhds a) = nhds (a - d)\"\n  for a d :: \"'a::real_normed_vector\"\n  by (rule filtermap_fun_inverse[where g=\"\\<lambda>x. x + d\"])\n    (auto intro!: tendsto_eq_intros filterlim_ident)\n\nlemma filtermap_nhds_minus: \"filtermap (\\<lambda>x. - x) (nhds a) = nhds (- a)\"\n  for a :: \"'a::real_normed_vector\"\n  by (rule filtermap_fun_inverse[where g=uminus])\n    (auto intro!: tendsto_eq_intros filterlim_ident)\n\nlemma filtermap_at_shift: \"filtermap (\\<lambda>x. x - d) (at a) = at (a - d)\"\n  for a d :: \"'a::real_normed_vector\"\n  by (simp add: filter_eq_iff eventually_filtermap eventually_at_filter filtermap_nhds_shift[symmetric])\n\nlemma filtermap_at_right_shift: \"filtermap (\\<lambda>x. x - d) (at_right a) = at_right (a - d)\"\n  for a d :: \"real\"\n  by (simp add: filter_eq_iff eventually_filtermap eventually_at_filter filtermap_nhds_shift[symmetric])\n\nlemma at_right_to_0: \"at_right a = filtermap (\\<lambda>x. x + a) (at_right 0)\"\n  for a :: real\n  using filtermap_at_right_shift[of \"-a\" 0] by simp\n\nlemma filterlim_at_right_to_0:\n  \"filterlim f F (at_right a) \\<longleftrightarrow> filterlim (\\<lambda>x. f (x + a)) F (at_right 0)\"\n  for a :: real\n  unfolding filterlim_def filtermap_filtermap at_right_to_0[of a] ..\n\nlemma eventually_at_right_to_0:\n  \"eventually P (at_right a) \\<longleftrightarrow> eventually (\\<lambda>x. P (x + a)) (at_right 0)\"\n  for a :: real\n  unfolding at_right_to_0[of a] by (simp add: eventually_filtermap)\n\nlemma filtermap_at_minus: \"filtermap (\\<lambda>x. - x) (at a) = at (- a)\"\n  for a :: \"'a::real_normed_vector\"\n  by (simp add: filter_eq_iff eventually_filtermap eventually_at_filter filtermap_nhds_minus[symmetric])\n\nlemma at_left_minus: \"at_left a = filtermap (\\<lambda>x. - x) (at_right (- a))\"\n  for a :: real\n  by (simp add: filter_eq_iff eventually_filtermap eventually_at_filter filtermap_nhds_minus[symmetric])\n\nlemma at_right_minus: \"at_right a = filtermap (\\<lambda>x. - x) (at_left (- a))\"\n  for a :: real\n  by (simp add: filter_eq_iff eventually_filtermap eventually_at_filter filtermap_nhds_minus[symmetric])\n\nlemma filterlim_at_left_to_right:\n  \"filterlim f F (at_left a) \\<longleftrightarrow> filterlim (\\<lambda>x. f (- x)) F (at_right (-a))\"\n  for a :: real\n  unfolding filterlim_def filtermap_filtermap at_left_minus[of a] ..\n\nlemma eventually_at_left_to_right:\n  \"eventually P (at_left a) \\<longleftrightarrow> eventually (\\<lambda>x. P (- x)) (at_right (-a))\"\n  for a :: real\n  unfolding at_left_minus[of a] by (simp add: eventually_filtermap)\n\nlemma filterlim_uminus_at_top_at_bot: \"LIM x at_bot. - x :: real :> at_top\"\n  unfolding filterlim_at_top eventually_at_bot_dense\n  by (metis leI minus_less_iff order_less_asym)\n\nlemma filterlim_uminus_at_bot_at_top: \"LIM x at_top. - x :: real :> at_bot\"\n  unfolding filterlim_at_bot eventually_at_top_dense\n  by (metis leI less_minus_iff order_less_asym)\n\nlemma at_top_mirror: \"at_top = filtermap uminus (at_bot :: real filter)\"\n  by (rule filtermap_fun_inverse[symmetric, of uminus])\n     (auto intro: filterlim_uminus_at_bot_at_top filterlim_uminus_at_top_at_bot)\n\nlemma at_bot_mirror: \"at_bot = filtermap uminus (at_top :: real filter)\"\n  unfolding at_top_mirror filtermap_filtermap by (simp add: filtermap_ident)\n\nlemma filterlim_at_top_mirror: \"(LIM x at_top. f x :> F) \\<longleftrightarrow> (LIM x at_bot. f (-x::real) :> F)\"\n  unfolding filterlim_def at_top_mirror filtermap_filtermap ..\n\nlemma filterlim_at_bot_mirror: \"(LIM x at_bot. f x :> F) \\<longleftrightarrow> (LIM x at_top. f (-x::real) :> F)\"\n  unfolding filterlim_def at_bot_mirror filtermap_filtermap ..\n\nlemma filterlim_uminus_at_top: \"(LIM x F. f x :> at_top) \\<longleftrightarrow> (LIM x F. - (f x) :: real :> at_bot)\"\n  using filterlim_compose[OF filterlim_uminus_at_bot_at_top, of f F]\n    and filterlim_compose[OF filterlim_uminus_at_top_at_bot, of \"\\<lambda>x. - f x\" F]\n  by auto\n\nlemma filterlim_uminus_at_bot: \"(LIM x F. f x :> at_bot) \\<longleftrightarrow> (LIM x F. - (f x) :: real :> at_top)\"\n  unfolding filterlim_uminus_at_top by simp\n\nlemma filterlim_inverse_at_top_right: \"LIM x at_right (0::real). inverse x :> at_top\"\n  unfolding filterlim_at_top_gt[where c=0] eventually_at_filter\nproof safe\n  fix Z :: real\n  assume [arith]: \"0 < Z\"\n  then have \"eventually (\\<lambda>x. x < inverse Z) (nhds 0)\"\n    by (auto simp add: eventually_nhds_metric dist_real_def intro!: exI[of _ \"\\<bar>inverse Z\\<bar>\"])\n  then show \"eventually (\\<lambda>x. x \\<noteq> 0 \\<longrightarrow> x \\<in> {0<..} \\<longrightarrow> Z \\<le> inverse x) (nhds 0)\"\n    by (auto elim!: eventually_mono simp: inverse_eq_divide field_simps)\nqed\n\nlemma tendsto_inverse_0:\n  fixes x :: \"_ \\<Rightarrow> 'a::real_normed_div_algebra\"\n  shows \"(inverse \\<longlongrightarrow> (0::'a)) at_infinity\"\n  unfolding tendsto_Zfun_iff diff_0_right Zfun_def eventually_at_infinity\nproof safe\n  fix r :: real\n  assume \"0 < r\"\n  show \"\\<exists>b. \\<forall>x. b \\<le> norm x \\<longrightarrow> norm (inverse x :: 'a) < r\"\n  proof (intro exI[of _ \"inverse (r / 2)\"] allI impI)\n    fix x :: 'a\n    from \\<open>0 < r\\<close> have \"0 < inverse (r / 2)\" by simp\n    also assume *: \"inverse (r / 2) \\<le> norm x\"\n    finally show \"norm (inverse x) < r\"\n      using * \\<open>0 < r\\<close>\n      by (subst nonzero_norm_inverse) (simp_all add: inverse_eq_divide field_simps)\n  qed\nqed\n\nlemma tendsto_add_filterlim_at_infinity:\n  fixes c :: \"'b::real_normed_vector\"\n    and F :: \"'a filter\"\n  assumes \"(f \\<longlongrightarrow> c) F\"\n    and \"filterlim g at_infinity F\"\n  shows \"filterlim (\\<lambda>x. f x + g x) at_infinity F\"\nproof (subst filterlim_at_infinity[OF order_refl], safe)\n  fix r :: real\n  assume r: \"r > 0\"\n  from assms(1) have \"((\\<lambda>x. norm (f x)) \\<longlongrightarrow> norm c) F\"\n    by (rule tendsto_norm)\n  then have \"eventually (\\<lambda>x. norm (f x) < norm c + 1) F\"\n    by (rule order_tendstoD) simp_all\n  moreover from r have \"r + norm c + 1 > 0\"\n    by (intro add_pos_nonneg) simp_all\n  with assms(2) have \"eventually (\\<lambda>x. norm (g x) \\<ge> r + norm c + 1) F\"\n    unfolding filterlim_at_infinity[OF order_refl]\n    by (elim allE[of _ \"r + norm c + 1\"]) simp_all\n  ultimately show \"eventually (\\<lambda>x. norm (f x + g x) \\<ge> r) F\"\n  proof eventually_elim\n    fix x :: 'a\n    assume A: \"norm (f x) < norm c + 1\" and B: \"r + norm c + 1 \\<le> norm (g x)\"\n    from A B have \"r \\<le> norm (g x) - norm (f x)\"\n      by simp\n    also have \"norm (g x) - norm (f x) \\<le> norm (g x + f x)\"\n      by (rule norm_diff_ineq)\n    finally show \"r \\<le> norm (f x + g x)\"\n      by (simp add: add_ac)\n  qed\nqed\n\nlemma tendsto_add_filterlim_at_infinity':\n  fixes c :: \"'b::real_normed_vector\"\n    and F :: \"'a filter\"\n  assumes \"filterlim f at_infinity F\"\n    and \"(g \\<longlongrightarrow> c) F\"\n  shows \"filterlim (\\<lambda>x. f x + g x) at_infinity F\"\n  by (subst add.commute) (rule tendsto_add_filterlim_at_infinity assms)+\n\nlemma filterlim_inverse_at_right_top: \"LIM x at_top. inverse x :> at_right (0::real)\"\n  unfolding filterlim_at\n  by (auto simp: eventually_at_top_dense)\n     (metis tendsto_inverse_0 filterlim_mono at_top_le_at_infinity order_refl)\n\nlemma filterlim_inverse_at_top:\n  \"(f \\<longlongrightarrow> (0 :: real)) F \\<Longrightarrow> eventually (\\<lambda>x. 0 < f x) F \\<Longrightarrow> LIM x F. inverse (f x) :> at_top\"\n  by (intro filterlim_compose[OF filterlim_inverse_at_top_right])\n     (simp add: filterlim_def eventually_filtermap eventually_mono at_within_def le_principal)\n\nlemma filterlim_inverse_at_bot_neg:\n  \"LIM x (at_left (0::real)). inverse x :> at_bot\"\n  by (simp add: filterlim_inverse_at_top_right filterlim_uminus_at_bot filterlim_at_left_to_right)\n\nlemma filterlim_inverse_at_bot:\n  \"(f \\<longlongrightarrow> (0 :: real)) F \\<Longrightarrow> eventually (\\<lambda>x. f x < 0) F \\<Longrightarrow> LIM x F. inverse (f x) :> at_bot\"\n  unfolding filterlim_uminus_at_bot inverse_minus_eq[symmetric]\n  by (rule filterlim_inverse_at_top) (simp_all add: tendsto_minus_cancel_left[symmetric])\n\nlemma at_right_to_top: \"(at_right (0::real)) = filtermap inverse at_top\"\n  by (intro filtermap_fun_inverse[symmetric, where g=inverse])\n     (auto intro: filterlim_inverse_at_top_right filterlim_inverse_at_right_top)\n\nlemma eventually_at_right_to_top:\n  \"eventually P (at_right (0::real)) \\<longleftrightarrow> eventually (\\<lambda>x. P (inverse x)) at_top\"\n  unfolding at_right_to_top eventually_filtermap ..\n\nlemma filterlim_at_right_to_top:\n  \"filterlim f F (at_right (0::real)) \\<longleftrightarrow> (LIM x at_top. f (inverse x) :> F)\"\n  unfolding filterlim_def at_right_to_top filtermap_filtermap ..\n\nlemma at_top_to_right: \"at_top = filtermap inverse (at_right (0::real))\"\n  unfolding at_right_to_top filtermap_filtermap inverse_inverse_eq filtermap_ident ..\n\nlemma eventually_at_top_to_right:\n  \"eventually P at_top \\<longleftrightarrow> eventually (\\<lambda>x. P (inverse x)) (at_right (0::real))\"\n  unfolding at_top_to_right eventually_filtermap ..\n\nlemma filterlim_at_top_to_right:\n  \"filterlim f F at_top \\<longleftrightarrow> (LIM x (at_right (0::real)). f (inverse x) :> F)\"\n  unfolding filterlim_def at_top_to_right filtermap_filtermap ..\n\nlemma filterlim_inverse_at_infinity:\n  fixes x :: \"_ \\<Rightarrow> 'a::{real_normed_div_algebra, division_ring}\"\n  shows \"filterlim inverse at_infinity (at (0::'a))\"\n  unfolding filterlim_at_infinity[OF order_refl]\nproof safe\n  fix r :: real\n  assume \"0 < r\"\n  then show \"eventually (\\<lambda>x::'a. r \\<le> norm (inverse x)) (at 0)\"\n    unfolding eventually_at norm_inverse\n    by (intro exI[of _ \"inverse r\"])\n       (auto simp: norm_conv_dist[symmetric] field_simps inverse_eq_divide)\nqed\n\nlemma filterlim_inverse_at_iff:\n  fixes g :: \"'a \\<Rightarrow> 'b::{real_normed_div_algebra, division_ring}\"\n  shows \"(LIM x F. inverse (g x) :> at 0) \\<longleftrightarrow> (LIM x F. g x :> at_infinity)\"\n  unfolding filterlim_def filtermap_filtermap[symmetric]\nproof\n  assume \"filtermap g F \\<le> at_infinity\"\n  then have \"filtermap inverse (filtermap g F) \\<le> filtermap inverse at_infinity\"\n    by (rule filtermap_mono)\n  also have \"\\<dots> \\<le> at 0\"\n    using tendsto_inverse_0[where 'a='b]\n    by (auto intro!: exI[of _ 1]\n        simp: le_principal eventually_filtermap filterlim_def at_within_def eventually_at_infinity)\n  finally show \"filtermap inverse (filtermap g F) \\<le> at 0\" .\nnext\n  assume \"filtermap inverse (filtermap g F) \\<le> at 0\"\n  then have \"filtermap inverse (filtermap inverse (filtermap g F)) \\<le> filtermap inverse (at 0)\"\n    by (rule filtermap_mono)\n  with filterlim_inverse_at_infinity show \"filtermap g F \\<le> at_infinity\"\n    by (auto intro: order_trans simp: filterlim_def filtermap_filtermap)\nqed\n\nlemma tendsto_mult_filterlim_at_infinity:\n  fixes c :: \"'a::real_normed_field\"\n  assumes  \"(f \\<longlongrightarrow> c) F\" \"c \\<noteq> 0\"\n  assumes \"filterlim g at_infinity F\"\n  shows \"filterlim (\\<lambda>x. f x * g x) at_infinity F\"\nproof -\n  have \"((\\<lambda>x. inverse (f x) * inverse (g x)) \\<longlongrightarrow> inverse c * 0) F\"\n    by (intro tendsto_mult tendsto_inverse assms filterlim_compose[OF tendsto_inverse_0])\n  then have \"filterlim (\\<lambda>x. inverse (f x) * inverse (g x)) (at (inverse c * 0)) F\"\n    unfolding filterlim_at\n    using assms\n    by (auto intro: filterlim_at_infinity_imp_eventually_ne tendsto_imp_eventually_ne eventually_conj)\n  then show ?thesis\n    by (subst filterlim_inverse_at_iff[symmetric]) simp_all\nqed  \n\nlemma tendsto_inverse_0_at_top: \"LIM x F. f x :> at_top \\<Longrightarrow> ((\\<lambda>x. inverse (f x) :: real) \\<longlongrightarrow> 0) F\"\n by (metis filterlim_at filterlim_mono[OF _ at_top_le_at_infinity order_refl] filterlim_inverse_at_iff)\n\nlemma real_tendsto_divide_at_top:\n  fixes c::\"real\"\n  assumes \"(f \\<longlongrightarrow> c) F\"\n  assumes \"filterlim g at_top F\"\n  shows \"((\\<lambda>x. f x / g x) \\<longlongrightarrow> 0) F\"\n  by (auto simp: divide_inverse_commute\n      intro!: tendsto_mult[THEN tendsto_eq_rhs] tendsto_inverse_0_at_top assms)\n\nlemma mult_nat_left_at_top: \"c > 0 \\<Longrightarrow> filterlim (\\<lambda>x. c * x) at_top sequentially\"\n  for c :: nat\n  by (rule filterlim_subseq) (auto simp: subseq_def)\n\nlemma mult_nat_right_at_top: \"c > 0 \\<Longrightarrow> filterlim (\\<lambda>x. x * c) at_top sequentially\"\n  for c :: nat\n  by (rule filterlim_subseq) (auto simp: subseq_def)\n\nlemma at_to_infinity: \"(at (0::'a::{real_normed_field,field})) = filtermap inverse at_infinity\"\nproof (rule antisym)\n  have \"(inverse \\<longlongrightarrow> (0::'a)) at_infinity\"\n    by (fact tendsto_inverse_0)\n  then show \"filtermap inverse at_infinity \\<le> at (0::'a)\"\n    apply (simp add: le_principal eventually_filtermap eventually_at_infinity filterlim_def at_within_def)\n    apply (rule_tac x=\"1\" in exI)\n    apply auto\n    done\nnext\n  have \"filtermap inverse (filtermap inverse (at (0::'a))) \\<le> filtermap inverse at_infinity\"\n    using filterlim_inverse_at_infinity unfolding filterlim_def\n    by (rule filtermap_mono)\n  then show \"at (0::'a) \\<le> filtermap inverse at_infinity\"\n    by (simp add: filtermap_ident filtermap_filtermap)\nqed\n\nlemma lim_at_infinity_0:\n  fixes l :: \"'a::{real_normed_field,field}\"\n  shows \"(f \\<longlongrightarrow> l) at_infinity \\<longleftrightarrow> ((f \\<circ> inverse) \\<longlongrightarrow> l) (at (0::'a))\"\n  by (simp add: tendsto_compose_filtermap at_to_infinity filtermap_filtermap)\n\nlemma lim_zero_infinity:\n  fixes l :: \"'a::{real_normed_field,field}\"\n  shows \"((\\<lambda>x. f(1 / x)) \\<longlongrightarrow> l) (at (0::'a)) \\<Longrightarrow> (f \\<longlongrightarrow> l) at_infinity\"\n  by (simp add: inverse_eq_divide lim_at_infinity_0 comp_def)\n\n\ntext \\<open>\n  We only show rules for multiplication and addition when the functions are either against a real\n  value or against infinity. Further rules are easy to derive by using @{thm\n  filterlim_uminus_at_top}.\n\\<close>\n\nlemma filterlim_tendsto_pos_mult_at_top:\n  assumes f: \"(f \\<longlongrightarrow> c) F\"\n    and c: \"0 < c\"\n    and g: \"LIM x F. g x :> at_top\"\n  shows \"LIM x F. (f x * g x :: real) :> at_top\"\n  unfolding filterlim_at_top_gt[where c=0]\nproof safe\n  fix Z :: real\n  assume \"0 < Z\"\n  from f \\<open>0 < c\\<close> have \"eventually (\\<lambda>x. c / 2 < f x) F\"\n    by (auto dest!: tendstoD[where e=\"c / 2\"] elim!: eventually_mono\n        simp: dist_real_def abs_real_def split: if_split_asm)\n  moreover from g have \"eventually (\\<lambda>x. (Z / c * 2) \\<le> g x) F\"\n    unfolding filterlim_at_top by auto\n  ultimately show \"eventually (\\<lambda>x. Z \\<le> f x * g x) F\"\n  proof eventually_elim\n    case (elim x)\n    with \\<open>0 < Z\\<close> \\<open>0 < c\\<close> have \"c / 2 * (Z / c * 2) \\<le> f x * g x\"\n      by (intro mult_mono) (auto simp: zero_le_divide_iff)\n    with \\<open>0 < c\\<close> show \"Z \\<le> f x * g x\"\n       by simp\n  qed\nqed\n\nlemma filterlim_at_top_mult_at_top:\n  assumes f: \"LIM x F. f x :> at_top\"\n    and g: \"LIM x F. g x :> at_top\"\n  shows \"LIM x F. (f x * g x :: real) :> at_top\"\n  unfolding filterlim_at_top_gt[where c=0]\nproof safe\n  fix Z :: real\n  assume \"0 < Z\"\n  from f have \"eventually (\\<lambda>x. 1 \\<le> f x) F\"\n    unfolding filterlim_at_top by auto\n  moreover from g have \"eventually (\\<lambda>x. Z \\<le> g x) F\"\n    unfolding filterlim_at_top by auto\n  ultimately show \"eventually (\\<lambda>x. Z \\<le> f x * g x) F\"\n  proof eventually_elim\n    case (elim x)\n    with \\<open>0 < Z\\<close> have \"1 * Z \\<le> f x * g x\"\n      by (intro mult_mono) (auto simp: zero_le_divide_iff)\n    then show \"Z \\<le> f x * g x\"\n       by simp\n  qed\nqed\n\nlemma filterlim_at_top_mult_tendsto_pos:\n  assumes f: \"(f \\<longlongrightarrow> c) F\"\n    and c: \"0 < c\"\n    and g: \"LIM x F. g x :> at_top\"\n  shows \"LIM x F. (g x * f x:: real) :> at_top\"\n  by (auto simp: mult.commute intro!: filterlim_tendsto_pos_mult_at_top f c g)\n\nlemma filterlim_tendsto_pos_mult_at_bot:\n  fixes c :: real\n  assumes \"(f \\<longlongrightarrow> c) F\" \"0 < c\" \"filterlim g at_bot F\"\n  shows \"LIM x F. f x * g x :> at_bot\"\n  using filterlim_tendsto_pos_mult_at_top[OF assms(1,2), of \"\\<lambda>x. - g x\"] assms(3)\n  unfolding filterlim_uminus_at_bot by simp\n\nlemma filterlim_tendsto_neg_mult_at_bot:\n  fixes c :: real\n  assumes c: \"(f \\<longlongrightarrow> c) F\" \"c < 0\" and g: \"filterlim g at_top F\"\n  shows \"LIM x F. f x * g x :> at_bot\"\n  using c filterlim_tendsto_pos_mult_at_top[of \"\\<lambda>x. - f x\" \"- c\" F, OF _ _ g]\n  unfolding filterlim_uminus_at_bot tendsto_minus_cancel_left by simp\n\nlemma filterlim_pow_at_top:\n  fixes f :: \"'a \\<Rightarrow> real\"\n  assumes \"0 < n\"\n    and f: \"LIM x F. f x :> at_top\"\n  shows \"LIM x F. (f x)^n :: real :> at_top\"\n  using \\<open>0 < n\\<close>\nproof (induct n)\n  case 0\n  then show ?case by simp\nnext\n  case (Suc n) with f show ?case\n    by (cases \"n = 0\") (auto intro!: filterlim_at_top_mult_at_top)\nqed\n\nlemma filterlim_pow_at_bot_even:\n  fixes f :: \"real \\<Rightarrow> real\"\n  shows \"0 < n \\<Longrightarrow> LIM x F. f x :> at_bot \\<Longrightarrow> even n \\<Longrightarrow> LIM x F. (f x)^n :> at_top\"\n  using filterlim_pow_at_top[of n \"\\<lambda>x. - f x\" F] by (simp add: filterlim_uminus_at_top)\n\nlemma filterlim_pow_at_bot_odd:\n  fixes f :: \"real \\<Rightarrow> real\"\n  shows \"0 < n \\<Longrightarrow> LIM x F. f x :> at_bot \\<Longrightarrow> odd n \\<Longrightarrow> LIM x F. (f x)^n :> at_bot\"\n  using filterlim_pow_at_top[of n \"\\<lambda>x. - f x\" F] by (simp add: filterlim_uminus_at_bot)\n\nlemma filterlim_tendsto_add_at_top:\n  assumes f: \"(f \\<longlongrightarrow> c) F\"\n    and g: \"LIM x F. g x :> at_top\"\n  shows \"LIM x F. (f x + g x :: real) :> at_top\"\n  unfolding filterlim_at_top_gt[where c=0]\nproof safe\n  fix Z :: real\n  assume \"0 < Z\"\n  from f have \"eventually (\\<lambda>x. c - 1 < f x) F\"\n    by (auto dest!: tendstoD[where e=1] elim!: eventually_mono simp: dist_real_def)\n  moreover from g have \"eventually (\\<lambda>x. Z - (c - 1) \\<le> g x) F\"\n    unfolding filterlim_at_top by auto\n  ultimately show \"eventually (\\<lambda>x. Z \\<le> f x + g x) F\"\n    by eventually_elim simp\nqed\n\nlemma LIM_at_top_divide:\n  fixes f g :: \"'a \\<Rightarrow> real\"\n  assumes f: \"(f \\<longlongrightarrow> a) F\" \"0 < a\"\n    and g: \"(g \\<longlongrightarrow> 0) F\" \"eventually (\\<lambda>x. 0 < g x) F\"\n  shows \"LIM x F. f x / g x :> at_top\"\n  unfolding divide_inverse\n  by (rule filterlim_tendsto_pos_mult_at_top[OF f]) (rule filterlim_inverse_at_top[OF g])\n\nlemma filterlim_at_top_add_at_top:\n  assumes f: \"LIM x F. f x :> at_top\"\n    and g: \"LIM x F. g x :> at_top\"\n  shows \"LIM x F. (f x + g x :: real) :> at_top\"\n  unfolding filterlim_at_top_gt[where c=0]\nproof safe\n  fix Z :: real\n  assume \"0 < Z\"\n  from f have \"eventually (\\<lambda>x. 0 \\<le> f x) F\"\n    unfolding filterlim_at_top by auto\n  moreover from g have \"eventually (\\<lambda>x. Z \\<le> g x) F\"\n    unfolding filterlim_at_top by auto\n  ultimately show \"eventually (\\<lambda>x. Z \\<le> f x + g x) F\"\n    by eventually_elim simp\nqed\n\nlemma tendsto_divide_0:\n  fixes f :: \"_ \\<Rightarrow> 'a::{real_normed_div_algebra, division_ring}\"\n  assumes f: \"(f \\<longlongrightarrow> c) F\"\n    and g: \"LIM x F. g x :> at_infinity\"\n  shows \"((\\<lambda>x. f x / g x) \\<longlongrightarrow> 0) F\"\n  using tendsto_mult[OF f filterlim_compose[OF tendsto_inverse_0 g]]\n  by (simp add: divide_inverse)\n\nlemma linear_plus_1_le_power:\n  fixes x :: real\n  assumes x: \"0 \\<le> x\"\n  shows \"real n * x + 1 \\<le> (x + 1) ^ n\"\nproof (induct n)\n  case 0\n  then show ?case by simp\nnext\n  case (Suc n)\n  from x have \"real (Suc n) * x + 1 \\<le> (x + 1) * (real n * x + 1)\"\n    by (simp add: field_simps)\n  also have \"\\<dots> \\<le> (x + 1)^Suc n\"\n    using Suc x by (simp add: mult_left_mono)\n  finally show ?case .\nqed\n\nlemma filterlim_realpow_sequentially_gt1:\n  fixes x :: \"'a :: real_normed_div_algebra\"\n  assumes x[arith]: \"1 < norm x\"\n  shows \"LIM n sequentially. x ^ n :> at_infinity\"\nproof (intro filterlim_at_infinity[THEN iffD2] allI impI)\n  fix y :: real\n  assume \"0 < y\"\n  have \"0 < norm x - 1\" by simp\n  then obtain N :: nat where \"y < real N * (norm x - 1)\"\n    by (blast dest: reals_Archimedean3)\n  also have \"\\<dots> \\<le> real N * (norm x - 1) + 1\"\n    by simp\n  also have \"\\<dots> \\<le> (norm x - 1 + 1) ^ N\"\n    by (rule linear_plus_1_le_power) simp\n  also have \"\\<dots> = norm x ^ N\"\n    by simp\n  finally have \"\\<forall>n\\<ge>N. y \\<le> norm x ^ n\"\n    by (metis order_less_le_trans power_increasing order_less_imp_le x)\n  then show \"eventually (\\<lambda>n. y \\<le> norm (x ^ n)) sequentially\"\n    unfolding eventually_sequentially\n    by (auto simp: norm_power)\nqed simp\n\n\nsubsection \\<open>Floor and Ceiling\\<close>\n\nlemma eventually_floor_less:\n  fixes f :: \"'a \\<Rightarrow> 'b::{order_topology,floor_ceiling}\"\n  assumes f: \"(f \\<longlongrightarrow> l) F\"\n    and l: \"l \\<notin> \\<int>\"\n  shows \"\\<forall>\\<^sub>F x in F. of_int (floor l) < f x\"\n  by (intro order_tendstoD[OF f]) (metis Ints_of_int antisym_conv2 floor_correct l)\n\nlemma eventually_less_ceiling:\n  fixes f :: \"'a \\<Rightarrow> 'b::{order_topology,floor_ceiling}\"\n  assumes f: \"(f \\<longlongrightarrow> l) F\"\n    and l: \"l \\<notin> \\<int>\"\n  shows \"\\<forall>\\<^sub>F x in F. f x < of_int (ceiling l)\"\n  by (intro order_tendstoD[OF f]) (metis Ints_of_int l le_of_int_ceiling less_le)\n\nlemma eventually_floor_eq:\n  fixes f::\"'a \\<Rightarrow> 'b::{order_topology,floor_ceiling}\"\n  assumes f: \"(f \\<longlongrightarrow> l) F\"\n    and l: \"l \\<notin> \\<int>\"\n  shows \"\\<forall>\\<^sub>F x in F. floor (f x) = floor l\"\n  using eventually_floor_less[OF assms] eventually_less_ceiling[OF assms]\n  by eventually_elim (meson floor_less_iff less_ceiling_iff not_less_iff_gr_or_eq)\n\nlemma eventually_ceiling_eq:\n  fixes f::\"'a \\<Rightarrow> 'b::{order_topology,floor_ceiling}\"\n  assumes f: \"(f \\<longlongrightarrow> l) F\"\n    and l: \"l \\<notin> \\<int>\"\n  shows \"\\<forall>\\<^sub>F x in F. ceiling (f x) = ceiling l\"\n  using eventually_floor_less[OF assms] eventually_less_ceiling[OF assms]\n  by eventually_elim (meson floor_less_iff less_ceiling_iff not_less_iff_gr_or_eq)\n\nlemma tendsto_of_int_floor:\n  fixes f::\"'a \\<Rightarrow> 'b::{order_topology,floor_ceiling}\"\n  assumes \"(f \\<longlongrightarrow> l) F\"\n    and \"l \\<notin> \\<int>\"\n  shows \"((\\<lambda>x. of_int (floor (f x)) :: 'c::{ring_1,topological_space}) \\<longlongrightarrow> of_int (floor l)) F\"\n  using eventually_floor_eq[OF assms]\n  by (simp add: eventually_mono topological_tendstoI)\n\nlemma tendsto_of_int_ceiling:\n  fixes f::\"'a \\<Rightarrow> 'b::{order_topology,floor_ceiling}\"\n  assumes \"(f \\<longlongrightarrow> l) F\"\n    and \"l \\<notin> \\<int>\"\n  shows \"((\\<lambda>x. of_int (ceiling (f x)):: 'c::{ring_1,topological_space}) \\<longlongrightarrow> of_int (ceiling l)) F\"\n  using eventually_ceiling_eq[OF assms]\n  by (simp add: eventually_mono topological_tendstoI)\n\nlemma continuous_on_of_int_floor:\n  \"continuous_on (UNIV - \\<int>::'a::{order_topology, floor_ceiling} set)\n    (\\<lambda>x. of_int (floor x)::'b::{ring_1, topological_space})\"\n  unfolding continuous_on_def\n  by (auto intro!: tendsto_of_int_floor)\n\nlemma continuous_on_of_int_ceiling:\n  \"continuous_on (UNIV - \\<int>::'a::{order_topology, floor_ceiling} set)\n    (\\<lambda>x. of_int (ceiling x)::'b::{ring_1, topological_space})\"\n  unfolding continuous_on_def\n  by (auto intro!: tendsto_of_int_ceiling)\n\n\nsubsection \\<open>Limits of Sequences\\<close>\n\nlemma [trans]: \"X = Y \\<Longrightarrow> Y \\<longlonglongrightarrow> z \\<Longrightarrow> X \\<longlonglongrightarrow> z\"\n  by simp\n\nlemma LIMSEQ_iff:\n  fixes L :: \"'a::real_normed_vector\"\n  shows \"(X \\<longlonglongrightarrow> L) = (\\<forall>r>0. \\<exists>no. \\<forall>n \\<ge> no. norm (X n - L) < r)\"\nunfolding lim_sequentially dist_norm ..\n\nlemma LIMSEQ_I: \"(\\<And>r. 0 < r \\<Longrightarrow> \\<exists>no. \\<forall>n\\<ge>no. norm (X n - L) < r) \\<Longrightarrow> X \\<longlonglongrightarrow> L\"\n  for L :: \"'a::real_normed_vector\"\n  by (simp add: LIMSEQ_iff)\n\nlemma LIMSEQ_D: \"X \\<longlonglongrightarrow> L \\<Longrightarrow> 0 < r \\<Longrightarrow> \\<exists>no. \\<forall>n\\<ge>no. norm (X n - L) < r\"\n  for L :: \"'a::real_normed_vector\"\n  by (simp add: LIMSEQ_iff)\n\nlemma LIMSEQ_linear: \"X \\<longlonglongrightarrow> x \\<Longrightarrow> l > 0 \\<Longrightarrow> (\\<lambda> n. X (n * l)) \\<longlonglongrightarrow> x\"\n  unfolding tendsto_def eventually_sequentially\n  by (metis div_le_dividend div_mult_self1_is_m le_trans mult.commute)\n\nlemma Bseq_inverse_lemma: \"r \\<le> norm x \\<Longrightarrow> 0 < r \\<Longrightarrow> norm (inverse x) \\<le> inverse r\"\n  for x :: \"'a::real_normed_div_algebra\"\n  apply (subst nonzero_norm_inverse, clarsimp)\n  apply (erule (1) le_imp_inverse_le)\n  done\n\nlemma Bseq_inverse: \"X \\<longlonglongrightarrow> a \\<Longrightarrow> a \\<noteq> 0 \\<Longrightarrow> Bseq (\\<lambda>n. inverse (X n))\"\n  for a :: \"'a::real_normed_div_algebra\"\n  by (rule Bfun_inverse)\n\n\ntext \\<open>Transformation of limit.\\<close>\n\nlemma Lim_transform: \"(g \\<longlongrightarrow> a) F \\<Longrightarrow> ((\\<lambda>x. f x - g x) \\<longlongrightarrow> 0) F \\<Longrightarrow> (f \\<longlongrightarrow> a) F\"\n  for a b :: \"'a::real_normed_vector\"\n  using tendsto_add [of g a F \"\\<lambda>x. f x - g x\" 0] by simp\n\nlemma Lim_transform2: \"(f \\<longlongrightarrow> a) F \\<Longrightarrow> ((\\<lambda>x. f x - g x) \\<longlongrightarrow> 0) F \\<Longrightarrow> (g \\<longlongrightarrow> a) F\"\n  for a b :: \"'a::real_normed_vector\"\n  by (erule Lim_transform) (simp add: tendsto_minus_cancel)\n\nproposition Lim_transform_eq: \"((\\<lambda>x. f x - g x) \\<longlongrightarrow> 0) F \\<Longrightarrow> (f \\<longlongrightarrow> a) F \\<longleftrightarrow> (g \\<longlongrightarrow> a) F\"\n  for a :: \"'a::real_normed_vector\"\n  using Lim_transform Lim_transform2 by blast\n\nlemma Lim_transform_eventually:\n  \"eventually (\\<lambda>x. f x = g x) net \\<Longrightarrow> (f \\<longlongrightarrow> l) net \\<Longrightarrow> (g \\<longlongrightarrow> l) net\"\n  apply (rule topological_tendstoI)\n  apply (drule (2) topological_tendstoD)\n  apply (erule (1) eventually_elim2)\n  apply simp\n  done\n\nlemma Lim_transform_within:\n  assumes \"(f \\<longlongrightarrow> l) (at x within S)\"\n    and \"0 < d\"\n    and \"\\<And>x'. x'\\<in>S \\<Longrightarrow> 0 < dist x' x \\<Longrightarrow> dist x' x < d \\<Longrightarrow> f x' = g x'\"\n  shows \"(g \\<longlongrightarrow> l) (at x within S)\"\nproof (rule Lim_transform_eventually)\n  show \"eventually (\\<lambda>x. f x = g x) (at x within S)\"\n    using assms by (auto simp: eventually_at)\n  show \"(f \\<longlongrightarrow> l) (at x within S)\"\n    by fact\nqed\n\ntext \\<open>Common case assuming being away from some crucial point like 0.\\<close>\nlemma Lim_transform_away_within:\n  fixes a b :: \"'a::t1_space\"\n  assumes \"a \\<noteq> b\"\n    and \"\\<forall>x\\<in>S. x \\<noteq> a \\<and> x \\<noteq> b \\<longrightarrow> f x = g x\"\n    and \"(f \\<longlongrightarrow> l) (at a within S)\"\n  shows \"(g \\<longlongrightarrow> l) (at a within S)\"\nproof (rule Lim_transform_eventually)\n  show \"(f \\<longlongrightarrow> l) (at a within S)\"\n    by fact\n  show \"eventually (\\<lambda>x. f x = g x) (at a within S)\"\n    unfolding eventually_at_topological\n    by (rule exI [where x=\"- {b}\"]) (simp add: open_Compl assms)\nqed\n\nlemma Lim_transform_away_at:\n  fixes a b :: \"'a::t1_space\"\n  assumes ab: \"a \\<noteq> b\"\n    and fg: \"\\<forall>x. x \\<noteq> a \\<and> x \\<noteq> b \\<longrightarrow> f x = g x\"\n    and fl: \"(f \\<longlongrightarrow> l) (at a)\"\n  shows \"(g \\<longlongrightarrow> l) (at a)\"\n  using Lim_transform_away_within[OF ab, of UNIV f g l] fg fl by simp\n\ntext \\<open>Alternatively, within an open set.\\<close>\nlemma Lim_transform_within_open:\n  assumes \"(f \\<longlongrightarrow> l) (at a within T)\"\n    and \"open s\" and \"a \\<in> s\"\n    and \"\\<And>x. x\\<in>s \\<Longrightarrow> x \\<noteq> a \\<Longrightarrow> f x = g x\"\n  shows \"(g \\<longlongrightarrow> l) (at a within T)\"\nproof (rule Lim_transform_eventually)\n  show \"eventually (\\<lambda>x. f x = g x) (at a within T)\"\n    unfolding eventually_at_topological\n    using assms by auto\n  show \"(f \\<longlongrightarrow> l) (at a within T)\" by fact\nqed\n\n\ntext \\<open>A congruence rule allowing us to transform limits assuming not at point.\\<close>\n\n(* FIXME: Only one congruence rule for tendsto can be used at a time! *)\n\nlemma Lim_cong_within(*[cong add]*):\n  assumes \"a = b\"\n    and \"x = y\"\n    and \"S = T\"\n    and \"\\<And>x. x \\<noteq> b \\<Longrightarrow> x \\<in> T \\<Longrightarrow> f x = g x\"\n  shows \"(f \\<longlongrightarrow> x) (at a within S) \\<longleftrightarrow> (g \\<longlongrightarrow> y) (at b within T)\"\n  unfolding tendsto_def eventually_at_topological\n  using assms by simp\n\nlemma Lim_cong_at(*[cong add]*):\n  assumes \"a = b\" \"x = y\"\n    and \"\\<And>x. x \\<noteq> a \\<Longrightarrow> f x = g x\"\n  shows \"((\\<lambda>x. f x) \\<longlongrightarrow> x) (at a) \\<longleftrightarrow> ((g \\<longlongrightarrow> y) (at a))\"\n  unfolding tendsto_def eventually_at_topological\n  using assms by simp\n\ntext \\<open>An unbounded sequence's inverse tends to 0.\\<close>\nlemma LIMSEQ_inverse_zero: \"\\<forall>r::real. \\<exists>N. \\<forall>n\\<ge>N. r < X n \\<Longrightarrow> (\\<lambda>n. inverse (X n)) \\<longlonglongrightarrow> 0\"\n  apply (rule filterlim_compose[OF tendsto_inverse_0])\n  apply (simp add: filterlim_at_infinity[OF order_refl] eventually_sequentially)\n  apply (metis abs_le_D1 linorder_le_cases linorder_not_le)\n  done\n\ntext \\<open>The sequence @{term \"1/n\"} tends to 0 as @{term n} tends to infinity.\\<close>\nlemma LIMSEQ_inverse_real_of_nat: \"(\\<lambda>n. inverse (real (Suc n))) \\<longlonglongrightarrow> 0\"\n  by (metis filterlim_compose tendsto_inverse_0 filterlim_mono order_refl filterlim_Suc\n      filterlim_compose[OF filterlim_real_sequentially] at_top_le_at_infinity)\n\ntext \\<open>\n  The sequence @{term \"r + 1/n\"} tends to @{term r} as @{term n} tends to\n  infinity is now easily proved.\n\\<close>\n\nlemma LIMSEQ_inverse_real_of_nat_add: \"(\\<lambda>n. r + inverse (real (Suc n))) \\<longlonglongrightarrow> r\"\n  using tendsto_add [OF tendsto_const LIMSEQ_inverse_real_of_nat] by auto\n\nlemma LIMSEQ_inverse_real_of_nat_add_minus: \"(\\<lambda>n. r + -inverse (real (Suc n))) \\<longlonglongrightarrow> r\"\n  using tendsto_add [OF tendsto_const tendsto_minus [OF LIMSEQ_inverse_real_of_nat]]\n  by auto\n\nlemma LIMSEQ_inverse_real_of_nat_add_minus_mult: \"(\\<lambda>n. r * (1 + - inverse (real (Suc n)))) \\<longlonglongrightarrow> r\"\n  using tendsto_mult [OF tendsto_const LIMSEQ_inverse_real_of_nat_add_minus [of 1]]\n  by auto\n\nlemma lim_inverse_n: \"((\\<lambda>n. inverse(of_nat n)) \\<longlongrightarrow> (0::'a::real_normed_field)) sequentially\"\n  using lim_1_over_n by (simp add: inverse_eq_divide)\n\nlemma LIMSEQ_Suc_n_over_n: \"(\\<lambda>n. of_nat (Suc n) / of_nat n :: 'a :: real_normed_field) \\<longlonglongrightarrow> 1\"\nproof (rule Lim_transform_eventually)\n  show \"eventually (\\<lambda>n. 1 + inverse (of_nat n :: 'a) = of_nat (Suc n) / of_nat n) sequentially\"\n    using eventually_gt_at_top[of \"0::nat\"]\n    by eventually_elim (simp add: field_simps)\n  have \"(\\<lambda>n. 1 + inverse (of_nat n) :: 'a) \\<longlonglongrightarrow> 1 + 0\"\n    by (intro tendsto_add tendsto_const lim_inverse_n)\n  then show \"(\\<lambda>n. 1 + inverse (of_nat n) :: 'a) \\<longlonglongrightarrow> 1\"\n    by simp\nqed\n\nlemma LIMSEQ_n_over_Suc_n: \"(\\<lambda>n. of_nat n / of_nat (Suc n) :: 'a :: real_normed_field) \\<longlonglongrightarrow> 1\"\nproof (rule Lim_transform_eventually)\n  show \"eventually (\\<lambda>n. inverse (of_nat (Suc n) / of_nat n :: 'a) =\n      of_nat n / of_nat (Suc n)) sequentially\"\n    using eventually_gt_at_top[of \"0::nat\"]\n    by eventually_elim (simp add: field_simps del: of_nat_Suc)\n  have \"(\\<lambda>n. inverse (of_nat (Suc n) / of_nat n :: 'a)) \\<longlonglongrightarrow> inverse 1\"\n    by (intro tendsto_inverse LIMSEQ_Suc_n_over_n) simp_all\n  then show \"(\\<lambda>n. inverse (of_nat (Suc n) / of_nat n :: 'a)) \\<longlonglongrightarrow> 1\"\n    by simp\nqed\n\n\nsubsection \\<open>Convergence on sequences\\<close>\n\nlemma convergent_cong:\n  assumes \"eventually (\\<lambda>x. f x = g x) sequentially\"\n  shows \"convergent f \\<longleftrightarrow> convergent g\"\n  unfolding convergent_def\n  by (subst filterlim_cong[OF refl refl assms]) (rule refl)\n\nlemma convergent_Suc_iff: \"convergent (\\<lambda>n. f (Suc n)) \\<longleftrightarrow> convergent f\"\n  by (auto simp: convergent_def LIMSEQ_Suc_iff)\n\nlemma convergent_ignore_initial_segment: \"convergent (\\<lambda>n. f (n + m)) = convergent f\"\nproof (induct m arbitrary: f)\n  case 0\n  then show ?case by simp\nnext\n  case (Suc m)\n  have \"convergent (\\<lambda>n. f (n + Suc m)) \\<longleftrightarrow> convergent (\\<lambda>n. f (Suc n + m))\"\n    by simp\n  also have \"\\<dots> \\<longleftrightarrow> convergent (\\<lambda>n. f (n + m))\"\n    by (rule convergent_Suc_iff)\n  also have \"\\<dots> \\<longleftrightarrow> convergent f\"\n    by (rule Suc)\n  finally show ?case .\nqed\n\nlemma convergent_add:\n  fixes X Y :: \"nat \\<Rightarrow> 'a::real_normed_vector\"\n  assumes \"convergent (\\<lambda>n. X n)\"\n    and \"convergent (\\<lambda>n. Y n)\"\n  shows \"convergent (\\<lambda>n. X n + Y n)\"\n  using assms unfolding convergent_def by (blast intro: tendsto_add)\n\nlemma convergent_sum:\n  fixes X :: \"'a \\<Rightarrow> nat \\<Rightarrow> 'b::real_normed_vector\"\n  shows \"(\\<And>i. i \\<in> A \\<Longrightarrow> convergent (\\<lambda>n. X i n)) \\<Longrightarrow> convergent (\\<lambda>n. \\<Sum>i\\<in>A. X i n)\"\n  by (induct A rule: infinite_finite_induct) (simp_all add: convergent_const convergent_add)\n\nlemma (in bounded_linear) convergent:\n  assumes \"convergent (\\<lambda>n. X n)\"\n  shows \"convergent (\\<lambda>n. f (X n))\"\n  using assms unfolding convergent_def by (blast intro: tendsto)\n\nlemma (in bounded_bilinear) convergent:\n  assumes \"convergent (\\<lambda>n. X n)\"\n    and \"convergent (\\<lambda>n. Y n)\"\n  shows \"convergent (\\<lambda>n. X n ** Y n)\"\n  using assms unfolding convergent_def by (blast intro: tendsto)\n\nlemma convergent_minus_iff: \"convergent X \\<longleftrightarrow> convergent (\\<lambda>n. - X n)\"\n  for X :: \"nat \\<Rightarrow> 'a::real_normed_vector\"\n  apply (simp add: convergent_def)\n  apply (auto dest: tendsto_minus)\n  apply (drule tendsto_minus)\n  apply auto\n  done\n\nlemma convergent_diff:\n  fixes X Y :: \"nat \\<Rightarrow> 'a::real_normed_vector\"\n  assumes \"convergent (\\<lambda>n. X n)\"\n  assumes \"convergent (\\<lambda>n. Y n)\"\n  shows \"convergent (\\<lambda>n. X n - Y n)\"\n  using assms unfolding convergent_def by (blast intro: tendsto_diff)\n\nlemma convergent_norm:\n  assumes \"convergent f\"\n  shows \"convergent (\\<lambda>n. norm (f n))\"\nproof -\n  from assms have \"f \\<longlonglongrightarrow> lim f\"\n    by (simp add: convergent_LIMSEQ_iff)\n  then have \"(\\<lambda>n. norm (f n)) \\<longlonglongrightarrow> norm (lim f)\"\n    by (rule tendsto_norm)\n  then show ?thesis\n    by (auto simp: convergent_def)\nqed\n\nlemma convergent_of_real:\n  \"convergent f \\<Longrightarrow> convergent (\\<lambda>n. of_real (f n) :: 'a::real_normed_algebra_1)\"\n  unfolding convergent_def by (blast intro!: tendsto_of_real)\n\nlemma convergent_add_const_iff:\n  \"convergent (\\<lambda>n. c + f n :: 'a::real_normed_vector) \\<longleftrightarrow> convergent f\"\nproof\n  assume \"convergent (\\<lambda>n. c + f n)\"\n  from convergent_diff[OF this convergent_const[of c]] show \"convergent f\"\n    by simp\nnext\n  assume \"convergent f\"\n  from convergent_add[OF convergent_const[of c] this] show \"convergent (\\<lambda>n. c + f n)\"\n    by simp\nqed\n\nlemma convergent_add_const_right_iff:\n  \"convergent (\\<lambda>n. f n + c :: 'a::real_normed_vector) \\<longleftrightarrow> convergent f\"\n  using convergent_add_const_iff[of c f] by (simp add: add_ac)\n\nlemma convergent_diff_const_right_iff:\n  \"convergent (\\<lambda>n. f n - c :: 'a::real_normed_vector) \\<longleftrightarrow> convergent f\"\n  using convergent_add_const_right_iff[of f \"-c\"] by (simp add: add_ac)\n\nlemma convergent_mult:\n  fixes X Y :: \"nat \\<Rightarrow> 'a::real_normed_field\"\n  assumes \"convergent (\\<lambda>n. X n)\"\n    and \"convergent (\\<lambda>n. Y n)\"\n  shows \"convergent (\\<lambda>n. X n * Y n)\"\n  using assms unfolding convergent_def by (blast intro: tendsto_mult)\n\nlemma convergent_mult_const_iff:\n  assumes \"c \\<noteq> 0\"\n  shows \"convergent (\\<lambda>n. c * f n :: 'a::real_normed_field) \\<longleftrightarrow> convergent f\"\nproof\n  assume \"convergent (\\<lambda>n. c * f n)\"\n  from assms convergent_mult[OF this convergent_const[of \"inverse c\"]]\n    show \"convergent f\" by (simp add: field_simps)\nnext\n  assume \"convergent f\"\n  from convergent_mult[OF convergent_const[of c] this] show \"convergent (\\<lambda>n. c * f n)\"\n    by simp\nqed\n\nlemma convergent_mult_const_right_iff:\n  fixes c :: \"'a::real_normed_field\"\n  assumes \"c \\<noteq> 0\"\n  shows \"convergent (\\<lambda>n. f n * c) \\<longleftrightarrow> convergent f\"\n  using convergent_mult_const_iff[OF assms, of f] by (simp add: mult_ac)\n\nlemma convergent_imp_Bseq: \"convergent f \\<Longrightarrow> Bseq f\"\n  by (simp add: Cauchy_Bseq convergent_Cauchy)\n\n\ntext \\<open>A monotone sequence converges to its least upper bound.\\<close>\n\nlemma LIMSEQ_incseq_SUP:\n  fixes X :: \"nat \\<Rightarrow> 'a::{conditionally_complete_linorder,linorder_topology}\"\n  assumes u: \"bdd_above (range X)\"\n    and X: \"incseq X\"\n  shows \"X \\<longlonglongrightarrow> (SUP i. X i)\"\n  by (rule order_tendstoI)\n    (auto simp: eventually_sequentially u less_cSUP_iff\n      intro: X[THEN incseqD] less_le_trans cSUP_lessD[OF u])\n\nlemma LIMSEQ_decseq_INF:\n  fixes X :: \"nat \\<Rightarrow> 'a::{conditionally_complete_linorder, linorder_topology}\"\n  assumes u: \"bdd_below (range X)\"\n    and X: \"decseq X\"\n  shows \"X \\<longlonglongrightarrow> (INF i. X i)\"\n  by (rule order_tendstoI)\n     (auto simp: eventually_sequentially u cINF_less_iff\n       intro: X[THEN decseqD] le_less_trans less_cINF_D[OF u])\n\ntext \\<open>Main monotonicity theorem.\\<close>\n\nlemma Bseq_monoseq_convergent: \"Bseq X \\<Longrightarrow> monoseq X \\<Longrightarrow> convergent X\"\n  for X :: \"nat \\<Rightarrow> real\"\n  by (auto simp: monoseq_iff convergent_def intro: LIMSEQ_decseq_INF LIMSEQ_incseq_SUP\n      dest: Bseq_bdd_above Bseq_bdd_below)\n\nlemma Bseq_mono_convergent: \"Bseq X \\<Longrightarrow> (\\<forall>m n. m \\<le> n \\<longrightarrow> X m \\<le> X n) \\<Longrightarrow> convergent X\"\n  for X :: \"nat \\<Rightarrow> real\"\n  by (auto intro!: Bseq_monoseq_convergent incseq_imp_monoseq simp: incseq_def)\n\nlemma monoseq_imp_convergent_iff_Bseq: \"monoseq f \\<Longrightarrow> convergent f \\<longleftrightarrow> Bseq f\"\n  for f :: \"nat \\<Rightarrow> real\"\n  using Bseq_monoseq_convergent[of f] convergent_imp_Bseq[of f] by blast\n\nlemma Bseq_monoseq_convergent'_inc:\n  fixes f :: \"nat \\<Rightarrow> real\"\n  shows \"Bseq (\\<lambda>n. f (n + M)) \\<Longrightarrow> (\\<And>m n. M \\<le> m \\<Longrightarrow> m \\<le> n \\<Longrightarrow> f m \\<le> f n) \\<Longrightarrow> convergent f\"\n  by (subst convergent_ignore_initial_segment [symmetric, of _ M])\n     (auto intro!: Bseq_monoseq_convergent simp: monoseq_def)\n\nlemma Bseq_monoseq_convergent'_dec:\n  fixes f :: \"nat \\<Rightarrow> real\"\n  shows \"Bseq (\\<lambda>n. f (n + M)) \\<Longrightarrow> (\\<And>m n. M \\<le> m \\<Longrightarrow> m \\<le> n \\<Longrightarrow> f m \\<ge> f n) \\<Longrightarrow> convergent f\"\n  by (subst convergent_ignore_initial_segment [symmetric, of _ M])\n    (auto intro!: Bseq_monoseq_convergent simp: monoseq_def)\n\nlemma Cauchy_iff: \"Cauchy X \\<longleftrightarrow> (\\<forall>e>0. \\<exists>M. \\<forall>m\\<ge>M. \\<forall>n\\<ge>M. norm (X m - X n) < e)\"\n  for X :: \"nat \\<Rightarrow> 'a::real_normed_vector\"\n  unfolding Cauchy_def dist_norm ..\n\nlemma CauchyI: \"(\\<And>e. 0 < e \\<Longrightarrow> \\<exists>M. \\<forall>m\\<ge>M. \\<forall>n\\<ge>M. norm (X m - X n) < e) \\<Longrightarrow> Cauchy X\"\n  for X :: \"nat \\<Rightarrow> 'a::real_normed_vector\"\n  by (simp add: Cauchy_iff)\n\nlemma CauchyD: \"Cauchy X \\<Longrightarrow> 0 < e \\<Longrightarrow> \\<exists>M. \\<forall>m\\<ge>M. \\<forall>n\\<ge>M. norm (X m - X n) < e\"\n  for X :: \"nat \\<Rightarrow> 'a::real_normed_vector\"\n  by (simp add: Cauchy_iff)\n\nlemma incseq_convergent:\n  fixes X :: \"nat \\<Rightarrow> real\"\n  assumes \"incseq X\"\n    and \"\\<forall>i. X i \\<le> B\"\n  obtains L where \"X \\<longlonglongrightarrow> L\" \"\\<forall>i. X i \\<le> L\"\nproof atomize_elim\n  from incseq_bounded[OF assms] \\<open>incseq X\\<close> Bseq_monoseq_convergent[of X]\n  obtain L where \"X \\<longlonglongrightarrow> L\"\n    by (auto simp: convergent_def monoseq_def incseq_def)\n  with \\<open>incseq X\\<close> show \"\\<exists>L. X \\<longlonglongrightarrow> L \\<and> (\\<forall>i. X i \\<le> L)\"\n    by (auto intro!: exI[of _ L] incseq_le)\nqed\n\nlemma decseq_convergent:\n  fixes X :: \"nat \\<Rightarrow> real\"\n  assumes \"decseq X\"\n    and \"\\<forall>i. B \\<le> X i\"\n  obtains L where \"X \\<longlonglongrightarrow> L\" \"\\<forall>i. L \\<le> X i\"\nproof atomize_elim\n  from decseq_bounded[OF assms] \\<open>decseq X\\<close> Bseq_monoseq_convergent[of X]\n  obtain L where \"X \\<longlonglongrightarrow> L\"\n    by (auto simp: convergent_def monoseq_def decseq_def)\n  with \\<open>decseq X\\<close> show \"\\<exists>L. X \\<longlonglongrightarrow> L \\<and> (\\<forall>i. L \\<le> X i)\"\n    by (auto intro!: exI[of _ L] decseq_le)\nqed\n\n\nsubsection \\<open>Power Sequences\\<close>\n\ntext \\<open>\n  The sequence @{term \"x^n\"} tends to 0 if @{term \"0\\<le>x\"} and @{term\n  \"x<1\"}.  Proof will use (NS) Cauchy equivalence for convergence and\n  also fact that bounded and monotonic sequence converges.\n\\<close>\n\nlemma Bseq_realpow: \"0 \\<le> x \\<Longrightarrow> x \\<le> 1 \\<Longrightarrow> Bseq (\\<lambda>n. x ^ n)\"\n  for x :: real\n  apply (simp add: Bseq_def)\n  apply (rule_tac x = 1 in exI)\n  apply (simp add: power_abs)\n  apply (auto dest: power_mono)\n  done\n\nlemma monoseq_realpow: \"0 \\<le> x \\<Longrightarrow> x \\<le> 1 \\<Longrightarrow> monoseq (\\<lambda>n. x ^ n)\"\n  for x :: real\n  apply (clarify intro!: mono_SucI2)\n  apply (cut_tac n = n and N = \"Suc n\" and a = x in power_decreasing)\n     apply auto\n  done\n\nlemma convergent_realpow: \"0 \\<le> x \\<Longrightarrow> x \\<le> 1 \\<Longrightarrow> convergent (\\<lambda>n. x ^ n)\"\n  for x :: real\n  by (blast intro!: Bseq_monoseq_convergent Bseq_realpow monoseq_realpow)\n\nlemma LIMSEQ_inverse_realpow_zero: \"1 < x \\<Longrightarrow> (\\<lambda>n. inverse (x ^ n)) \\<longlonglongrightarrow> 0\"\n  for x :: real\n  by (rule filterlim_compose[OF tendsto_inverse_0 filterlim_realpow_sequentially_gt1]) simp\n\nlemma LIMSEQ_realpow_zero:\n  fixes x :: real\n  assumes \"0 \\<le> x\" \"x < 1\"\n  shows \"(\\<lambda>n. x ^ n) \\<longlonglongrightarrow> 0\"\nproof (cases \"x = 0\")\n  case False\n  with \\<open>0 \\<le> x\\<close> have x0: \"0 < x\" by simp\n  then have \"1 < inverse x\"\n    using \\<open>x < 1\\<close> by (rule one_less_inverse)\n  then have \"(\\<lambda>n. inverse (inverse x ^ n)) \\<longlonglongrightarrow> 0\"\n    by (rule LIMSEQ_inverse_realpow_zero)\n  then show ?thesis by (simp add: power_inverse)\nnext\n  case True\n  show ?thesis\n    by (rule LIMSEQ_imp_Suc) (simp add: True)\nqed\n\nlemma LIMSEQ_power_zero: \"norm x < 1 \\<Longrightarrow> (\\<lambda>n. x ^ n) \\<longlonglongrightarrow> 0\"\n  for x :: \"'a::real_normed_algebra_1\"\n  apply (drule LIMSEQ_realpow_zero [OF norm_ge_zero])\n  apply (simp only: tendsto_Zfun_iff, erule Zfun_le)\n  apply (simp add: power_abs norm_power_ineq)\n  done\n\nlemma LIMSEQ_divide_realpow_zero: \"1 < x \\<Longrightarrow> (\\<lambda>n. a / (x ^ n) :: real) \\<longlonglongrightarrow> 0\"\n  by (rule tendsto_divide_0 [OF tendsto_const filterlim_realpow_sequentially_gt1]) simp\n\nlemma\n  tendsto_power_zero:\n  fixes x::\"'a::real_normed_algebra_1\"\n  assumes \"filterlim f at_top F\"\n  assumes \"norm x < 1\"\n  shows \"((\\<lambda>y. x ^ (f y)) \\<longlongrightarrow> 0) F\"\nproof (rule tendstoI)\n  fix e::real assume \"0 < e\"\n  from tendstoD[OF LIMSEQ_power_zero[OF \\<open>norm x < 1\\<close>] \\<open>0 < e\\<close>]\n  have \"\\<forall>\\<^sub>F xa in sequentially. norm (x ^ xa) < e\"\n    by simp\n  then obtain N where N: \"norm (x ^ n) < e\" if \"n \\<ge> N\" for n\n    by (auto simp: eventually_sequentially)\n  have \"\\<forall>\\<^sub>F i in F. f i \\<ge> N\"\n    using \\<open>filterlim f sequentially F\\<close>\n    by (simp add: filterlim_at_top)\n  then show \"\\<forall>\\<^sub>F i in F. dist (x ^ f i) 0 < e\"\n    by (eventually_elim) (auto simp: N)\nqed\n\ntext \\<open>Limit of @{term \"c^n\"} for @{term\"\\<bar>c\\<bar> < 1\"}.\\<close>\n\nlemma LIMSEQ_rabs_realpow_zero: \"\\<bar>c\\<bar> < 1 \\<Longrightarrow> (\\<lambda>n. \\<bar>c\\<bar> ^ n :: real) \\<longlonglongrightarrow> 0\"\n  by (rule LIMSEQ_realpow_zero [OF abs_ge_zero])\n\nlemma LIMSEQ_rabs_realpow_zero2: \"\\<bar>c\\<bar> < 1 \\<Longrightarrow> (\\<lambda>n. c ^ n :: real) \\<longlonglongrightarrow> 0\"\n  by (rule LIMSEQ_power_zero) simp\n\n\nsubsection \\<open>Limits of Functions\\<close>\n\nlemma LIM_eq: \"f \\<midarrow>a\\<rightarrow> L = (\\<forall>r>0. \\<exists>s>0. \\<forall>x. x \\<noteq> a \\<and> norm (x - a) < s \\<longrightarrow> norm (f x - L) < r)\"\n  for a :: \"'a::real_normed_vector\" and L :: \"'b::real_normed_vector\"\n  by (simp add: LIM_def dist_norm)\n\nlemma LIM_I:\n  \"(\\<And>r. 0 < r \\<Longrightarrow> \\<exists>s>0. \\<forall>x. x \\<noteq> a \\<and> norm (x - a) < s \\<longrightarrow> norm (f x - L) < r) \\<Longrightarrow> f \\<midarrow>a\\<rightarrow> L\"\n  for a :: \"'a::real_normed_vector\" and L :: \"'b::real_normed_vector\"\n  by (simp add: LIM_eq)\n\nlemma LIM_D: \"f \\<midarrow>a\\<rightarrow> L \\<Longrightarrow> 0 < r \\<Longrightarrow> \\<exists>s>0.\\<forall>x. x \\<noteq> a \\<and> norm (x - a) < s \\<longrightarrow> norm (f x - L) < r\"\n  for a :: \"'a::real_normed_vector\" and L :: \"'b::real_normed_vector\"\n  by (simp add: LIM_eq)\n\nlemma LIM_offset: \"f \\<midarrow>a\\<rightarrow> L \\<Longrightarrow> (\\<lambda>x. f (x + k)) \\<midarrow>(a - k)\\<rightarrow> L\"\n  for a :: \"'a::real_normed_vector\"\n  by (simp add: filtermap_at_shift[symmetric, of a k] filterlim_def filtermap_filtermap)\n\nlemma LIM_offset_zero: \"f \\<midarrow>a\\<rightarrow> L \\<Longrightarrow> (\\<lambda>h. f (a + h)) \\<midarrow>0\\<rightarrow> L\"\n  for a :: \"'a::real_normed_vector\"\n  by (drule LIM_offset [where k = a]) (simp add: add.commute)\n\nlemma LIM_offset_zero_cancel: \"(\\<lambda>h. f (a + h)) \\<midarrow>0\\<rightarrow> L \\<Longrightarrow> f \\<midarrow>a\\<rightarrow> L\"\n  for a :: \"'a::real_normed_vector\"\n  by (drule LIM_offset [where k = \"- a\"]) simp\n\nlemma LIM_offset_zero_iff: \"f \\<midarrow>a\\<rightarrow> L \\<longleftrightarrow> (\\<lambda>h. f (a + h)) \\<midarrow>0\\<rightarrow> L\"\n  for f :: \"'a :: real_normed_vector \\<Rightarrow> _\"\n  using LIM_offset_zero_cancel[of f a L] LIM_offset_zero[of f L a] by auto\n\nlemma LIM_zero: \"(f \\<longlongrightarrow> l) F \\<Longrightarrow> ((\\<lambda>x. f x - l) \\<longlongrightarrow> 0) F\"\n  for f :: \"'a::topological_space \\<Rightarrow> 'b::real_normed_vector\"\n  unfolding tendsto_iff dist_norm by simp\n\nlemma LIM_zero_cancel:\n  fixes f :: \"'a::topological_space \\<Rightarrow> 'b::real_normed_vector\"\n  shows \"((\\<lambda>x. f x - l) \\<longlongrightarrow> 0) F \\<Longrightarrow> (f \\<longlongrightarrow> l) F\"\nunfolding tendsto_iff dist_norm by simp\n\nlemma LIM_zero_iff: \"((\\<lambda>x. f x - l) \\<longlongrightarrow> 0) F = (f \\<longlongrightarrow> l) F\"\n  for f :: \"'a::metric_space \\<Rightarrow> 'b::real_normed_vector\"\n  unfolding tendsto_iff dist_norm by simp\n\nlemma LIM_imp_LIM:\n  fixes f :: \"'a::topological_space \\<Rightarrow> 'b::real_normed_vector\"\n  fixes g :: \"'a::topological_space \\<Rightarrow> 'c::real_normed_vector\"\n  assumes f: \"f \\<midarrow>a\\<rightarrow> l\"\n    and le: \"\\<And>x. x \\<noteq> a \\<Longrightarrow> norm (g x - m) \\<le> norm (f x - l)\"\n  shows \"g \\<midarrow>a\\<rightarrow> m\"\n  by (rule metric_LIM_imp_LIM [OF f]) (simp add: dist_norm le)\n\nlemma LIM_equal2:\n  fixes f g :: \"'a::real_normed_vector \\<Rightarrow> 'b::topological_space\"\n  assumes \"0 < R\"\n    and \"\\<And>x. x \\<noteq> a \\<Longrightarrow> norm (x - a) < R \\<Longrightarrow> f x = g x\"\n  shows \"g \\<midarrow>a\\<rightarrow> l \\<Longrightarrow> f \\<midarrow>a\\<rightarrow> l\"\n  by (rule metric_LIM_equal2 [OF assms]) (simp_all add: dist_norm)\n\nlemma LIM_compose2:\n  fixes a :: \"'a::real_normed_vector\"\n  assumes f: \"f \\<midarrow>a\\<rightarrow> b\"\n    and g: \"g \\<midarrow>b\\<rightarrow> c\"\n    and inj: \"\\<exists>d>0. \\<forall>x. x \\<noteq> a \\<and> norm (x - a) < d \\<longrightarrow> f x \\<noteq> b\"\n  shows \"(\\<lambda>x. g (f x)) \\<midarrow>a\\<rightarrow> c\"\n  by (rule metric_LIM_compose2 [OF f g inj [folded dist_norm]])\n\nlemma real_LIM_sandwich_zero:\n  fixes f g :: \"'a::topological_space \\<Rightarrow> real\"\n  assumes f: \"f \\<midarrow>a\\<rightarrow> 0\"\n    and 1: \"\\<And>x. x \\<noteq> a \\<Longrightarrow> 0 \\<le> g x\"\n    and 2: \"\\<And>x. x \\<noteq> a \\<Longrightarrow> g x \\<le> f x\"\n  shows \"g \\<midarrow>a\\<rightarrow> 0\"\nproof (rule LIM_imp_LIM [OF f]) (* FIXME: use tendsto_sandwich *)\n  fix x\n  assume x: \"x \\<noteq> a\"\n  with 1 have \"norm (g x - 0) = g x\" by simp\n  also have \"g x \\<le> f x\" by (rule 2 [OF x])\n  also have \"f x \\<le> \\<bar>f x\\<bar>\" by (rule abs_ge_self)\n  also have \"\\<bar>f x\\<bar> = norm (f x - 0)\" by simp\n  finally show \"norm (g x - 0) \\<le> norm (f x - 0)\" .\nqed\n\n\nsubsection \\<open>Continuity\\<close>\n\nlemma LIM_isCont_iff: \"(f \\<midarrow>a\\<rightarrow> f a) = ((\\<lambda>h. f (a + h)) \\<midarrow>0\\<rightarrow> f a)\"\n  for f :: \"'a::real_normed_vector \\<Rightarrow> 'b::topological_space\"\n  by (rule iffI [OF LIM_offset_zero LIM_offset_zero_cancel])\n\nlemma isCont_iff: \"isCont f x = (\\<lambda>h. f (x + h)) \\<midarrow>0\\<rightarrow> f x\"\n  for f :: \"'a::real_normed_vector \\<Rightarrow> 'b::topological_space\"\n  by (simp add: isCont_def LIM_isCont_iff)\n\nlemma isCont_LIM_compose2:\n  fixes a :: \"'a::real_normed_vector\"\n  assumes f [unfolded isCont_def]: \"isCont f a\"\n    and g: \"g \\<midarrow>f a\\<rightarrow> l\"\n    and inj: \"\\<exists>d>0. \\<forall>x. x \\<noteq> a \\<and> norm (x - a) < d \\<longrightarrow> f x \\<noteq> f a\"\n  shows \"(\\<lambda>x. g (f x)) \\<midarrow>a\\<rightarrow> l\"\n  by (rule LIM_compose2 [OF f g inj])\n\nlemma isCont_norm [simp]: \"isCont f a \\<Longrightarrow> isCont (\\<lambda>x. norm (f x)) a\"\n  for f :: \"'a::t2_space \\<Rightarrow> 'b::real_normed_vector\"\n  by (fact continuous_norm)\n\nlemma isCont_rabs [simp]: \"isCont f a \\<Longrightarrow> isCont (\\<lambda>x. \\<bar>f x\\<bar>) a\"\n  for f :: \"'a::t2_space \\<Rightarrow> real\"\n  by (fact continuous_rabs)\n\nlemma isCont_add [simp]: \"isCont f a \\<Longrightarrow> isCont g a \\<Longrightarrow> isCont (\\<lambda>x. f x + g x) a\"\n  for f :: \"'a::t2_space \\<Rightarrow> 'b::topological_monoid_add\"\n  by (fact continuous_add)\n\nlemma isCont_minus [simp]: \"isCont f a \\<Longrightarrow> isCont (\\<lambda>x. - f x) a\"\n  for f :: \"'a::t2_space \\<Rightarrow> 'b::real_normed_vector\"\n  by (fact continuous_minus)\n\nlemma isCont_diff [simp]: \"isCont f a \\<Longrightarrow> isCont g a \\<Longrightarrow> isCont (\\<lambda>x. f x - g x) a\"\n  for f :: \"'a::t2_space \\<Rightarrow> 'b::real_normed_vector\"\n  by (fact continuous_diff)\n\nlemma isCont_mult [simp]: \"isCont f a \\<Longrightarrow> isCont g a \\<Longrightarrow> isCont (\\<lambda>x. f x * g x) a\"\n  for f g :: \"'a::t2_space \\<Rightarrow> 'b::real_normed_algebra\"\n  by (fact continuous_mult)\n\nlemma (in bounded_linear) isCont: \"isCont g a \\<Longrightarrow> isCont (\\<lambda>x. f (g x)) a\"\n  by (fact continuous)\n\nlemma (in bounded_bilinear) isCont: \"isCont f a \\<Longrightarrow> isCont g a \\<Longrightarrow> isCont (\\<lambda>x. f x ** g x) a\"\n  by (fact continuous)\n\nlemmas isCont_scaleR [simp] =\n  bounded_bilinear.isCont [OF bounded_bilinear_scaleR]\n\nlemmas isCont_of_real [simp] =\n  bounded_linear.isCont [OF bounded_linear_of_real]\n\nlemma isCont_power [simp]: \"isCont f a \\<Longrightarrow> isCont (\\<lambda>x. f x ^ n) a\"\n  for f :: \"'a::t2_space \\<Rightarrow> 'b::{power,real_normed_algebra}\"\n  by (fact continuous_power)\n\nlemma isCont_sum [simp]: \"\\<forall>i\\<in>A. isCont (f i) a \\<Longrightarrow> isCont (\\<lambda>x. \\<Sum>i\\<in>A. f i x) a\"\n  for f :: \"'a \\<Rightarrow> 'b::t2_space \\<Rightarrow> 'c::topological_comm_monoid_add\"\n  by (auto intro: continuous_sum)\n\n\nsubsection \\<open>Uniform Continuity\\<close>\n\nlemma uniformly_continuous_on_def:\n  fixes f :: \"'a::metric_space \\<Rightarrow> 'b::metric_space\"\n  shows \"uniformly_continuous_on s f \\<longleftrightarrow>\n    (\\<forall>e>0. \\<exists>d>0. \\<forall>x\\<in>s. \\<forall>x'\\<in>s. dist x' x < d \\<longrightarrow> dist (f x') (f x) < e)\"\n  unfolding uniformly_continuous_on_uniformity\n    uniformity_dist filterlim_INF filterlim_principal eventually_inf_principal\n  by (force simp: Ball_def uniformity_dist[symmetric] eventually_uniformity_metric)\n\nabbreviation isUCont :: \"['a::metric_space \\<Rightarrow> 'b::metric_space] \\<Rightarrow> bool\"\n  where \"isUCont f \\<equiv> uniformly_continuous_on UNIV f\"\n\nlemma isUCont_def: \"isUCont f \\<longleftrightarrow> (\\<forall>r>0. \\<exists>s>0. \\<forall>x y. dist x y < s \\<longrightarrow> dist (f x) (f y) < r)\"\n  by (auto simp: uniformly_continuous_on_def dist_commute)\n\nlemma isUCont_isCont: \"isUCont f \\<Longrightarrow> isCont f x\"\n  by (drule uniformly_continuous_imp_continuous) (simp add: continuous_on_eq_continuous_at)\n\nlemma uniformly_continuous_on_Cauchy:\n  fixes f :: \"'a::metric_space \\<Rightarrow> 'b::metric_space\"\n  assumes \"uniformly_continuous_on S f\" \"Cauchy X\" \"\\<And>n. X n \\<in> S\"\n  shows \"Cauchy (\\<lambda>n. f (X n))\"\n  using assms\n  apply (simp only: uniformly_continuous_on_def)\n  apply (rule metric_CauchyI)\n  apply (drule_tac x=e in spec)\n  apply safe\n  apply (drule_tac e=d in metric_CauchyD)\n   apply safe\n  apply (rule_tac x=M in exI)\n  apply simp\n  done\n\nlemma isUCont_Cauchy: \"isUCont f \\<Longrightarrow> Cauchy X \\<Longrightarrow> Cauchy (\\<lambda>n. f (X n))\"\n  by (rule uniformly_continuous_on_Cauchy[where S=UNIV and f=f]) simp_all\n  \nlemma uniformly_continuous_imp_Cauchy_continuous:\n  fixes f :: \"'a::metric_space \\<Rightarrow> 'b::metric_space\"\n  shows \"\\<lbrakk>uniformly_continuous_on S f; Cauchy \\<sigma>; \\<And>n. (\\<sigma> n) \\<in> S\\<rbrakk> \\<Longrightarrow> Cauchy(f o \\<sigma>)\"\n  by (simp add: uniformly_continuous_on_def Cauchy_def) meson\n\nlemma (in bounded_linear) isUCont: \"isUCont f\"\n  unfolding isUCont_def dist_norm\nproof (intro allI impI)\n  fix r :: real\n  assume r: \"0 < r\"\n  obtain K where K: \"0 < K\" and norm_le: \"norm (f x) \\<le> norm x * K\" for x\n    using pos_bounded by blast\n  show \"\\<exists>s>0. \\<forall>x y. norm (x - y) < s \\<longrightarrow> norm (f x - f y) < r\"\n  proof (rule exI, safe)\n    from r K show \"0 < r / K\" by simp\n  next\n    fix x y :: 'a\n    assume xy: \"norm (x - y) < r / K\"\n    have \"norm (f x - f y) = norm (f (x - y))\" by (simp only: diff)\n    also have \"\\<dots> \\<le> norm (x - y) * K\" by (rule norm_le)\n    also from K xy have \"\\<dots> < r\" by (simp only: pos_less_divide_eq)\n    finally show \"norm (f x - f y) < r\" .\n  qed\nqed\n\nlemma (in bounded_linear) Cauchy: \"Cauchy X \\<Longrightarrow> Cauchy (\\<lambda>n. f (X n))\"\n  by (rule isUCont [THEN isUCont_Cauchy])\n\nlemma LIM_less_bound:\n  fixes f :: \"real \\<Rightarrow> real\"\n  assumes ev: \"b < x\" \"\\<forall> x' \\<in> { b <..< x}. 0 \\<le> f x'\" and \"isCont f x\"\n  shows \"0 \\<le> f x\"\nproof (rule tendsto_lowerbound)\n  show \"(f \\<longlongrightarrow> f x) (at_left x)\"\n    using \\<open>isCont f x\\<close> by (simp add: filterlim_at_split isCont_def)\n  show \"eventually (\\<lambda>x. 0 \\<le> f x) (at_left x)\"\n    using ev by (auto simp: eventually_at dist_real_def intro!: exI[of _ \"x - b\"])\nqed simp\n\n\nsubsection \\<open>Nested Intervals and Bisection -- Needed for Compactness\\<close>\n\nlemma nested_sequence_unique:\n  assumes \"\\<forall>n. f n \\<le> f (Suc n)\" \"\\<forall>n. g (Suc n) \\<le> g n\" \"\\<forall>n. f n \\<le> g n\" \"(\\<lambda>n. f n - g n) \\<longlonglongrightarrow> 0\"\n  shows \"\\<exists>l::real. ((\\<forall>n. f n \\<le> l) \\<and> f \\<longlonglongrightarrow> l) \\<and> ((\\<forall>n. l \\<le> g n) \\<and> g \\<longlonglongrightarrow> l)\"\nproof -\n  have \"incseq f\" unfolding incseq_Suc_iff by fact\n  have \"decseq g\" unfolding decseq_Suc_iff by fact\n  have \"f n \\<le> g 0\" for n\n  proof -\n    from \\<open>decseq g\\<close> have \"g n \\<le> g 0\"\n      by (rule decseqD) simp\n    with \\<open>\\<forall>n. f n \\<le> g n\\<close>[THEN spec, of n] show ?thesis\n      by auto\n  qed\n  then obtain u where \"f \\<longlonglongrightarrow> u\" \"\\<forall>i. f i \\<le> u\"\n    using incseq_convergent[OF \\<open>incseq f\\<close>] by auto\n  moreover have \"f 0 \\<le> g n\" for n\n  proof -\n    from \\<open>incseq f\\<close> have \"f 0 \\<le> f n\" by (rule incseqD) simp\n    with \\<open>\\<forall>n. f n \\<le> g n\\<close>[THEN spec, of n] show ?thesis\n      by simp\n  qed\n  then obtain l where \"g \\<longlonglongrightarrow> l\" \"\\<forall>i. l \\<le> g i\"\n    using decseq_convergent[OF \\<open>decseq g\\<close>] by auto\n  moreover note LIMSEQ_unique[OF assms(4) tendsto_diff[OF \\<open>f \\<longlonglongrightarrow> u\\<close> \\<open>g \\<longlonglongrightarrow> l\\<close>]]\n  ultimately show ?thesis by auto\nqed\n\nlemma Bolzano[consumes 1, case_names trans local]:\n  fixes P :: \"real \\<Rightarrow> real \\<Rightarrow> bool\"\n  assumes [arith]: \"a \\<le> b\"\n    and trans: \"\\<And>a b c. P a b \\<Longrightarrow> P b c \\<Longrightarrow> a \\<le> b \\<Longrightarrow> b \\<le> c \\<Longrightarrow> P a c\"\n    and local: \"\\<And>x. a \\<le> x \\<Longrightarrow> x \\<le> b \\<Longrightarrow> \\<exists>d>0. \\<forall>a b. a \\<le> x \\<and> x \\<le> b \\<and> b - a < d \\<longrightarrow> P a b\"\n  shows \"P a b\"\nproof -\n  define bisect where \"bisect =\n    rec_nat (a, b) (\\<lambda>n (x, y). if P x ((x+y) / 2) then ((x+y)/2, y) else (x, (x+y)/2))\"\n  define l u where \"l n = fst (bisect n)\" and \"u n = snd (bisect n)\" for n\n  have l[simp]: \"l 0 = a\" \"\\<And>n. l (Suc n) = (if P (l n) ((l n + u n) / 2) then (l n + u n) / 2 else l n)\"\n    and u[simp]: \"u 0 = b\" \"\\<And>n. u (Suc n) = (if P (l n) ((l n + u n) / 2) then u n else (l n + u n) / 2)\"\n    by (simp_all add: l_def u_def bisect_def split: prod.split)\n\n  have [simp]: \"l n \\<le> u n\" for n by (induct n) auto\n\n  have \"\\<exists>x. ((\\<forall>n. l n \\<le> x) \\<and> l \\<longlonglongrightarrow> x) \\<and> ((\\<forall>n. x \\<le> u n) \\<and> u \\<longlonglongrightarrow> x)\"\n  proof (safe intro!: nested_sequence_unique)\n    show \"l n \\<le> l (Suc n)\" \"u (Suc n) \\<le> u n\" for n\n      by (induct n) auto\n  next\n    have \"l n - u n = (a - b) / 2^n\" for n\n      by (induct n) (auto simp: field_simps)\n    then show \"(\\<lambda>n. l n - u n) \\<longlonglongrightarrow> 0\"\n      by (simp add: LIMSEQ_divide_realpow_zero)\n  qed fact\n  then obtain x where x: \"\\<And>n. l n \\<le> x\" \"\\<And>n. x \\<le> u n\" and \"l \\<longlonglongrightarrow> x\" \"u \\<longlonglongrightarrow> x\"\n    by auto\n  obtain d where \"0 < d\" and d: \"a \\<le> x \\<Longrightarrow> x \\<le> b \\<Longrightarrow> b - a < d \\<Longrightarrow> P a b\" for a b\n    using \\<open>l 0 \\<le> x\\<close> \\<open>x \\<le> u 0\\<close> local[of x] by auto\n\n  show \"P a b\"\n  proof (rule ccontr)\n    assume \"\\<not> P a b\"\n    have \"\\<not> P (l n) (u n)\" for n\n    proof (induct n)\n      case 0\n      then show ?case\n        by (simp add: \\<open>\\<not> P a b\\<close>)\n    next\n      case (Suc n)\n      with trans[of \"l n\" \"(l n + u n) / 2\" \"u n\"] show ?case\n        by auto\n    qed\n    moreover\n    {\n      have \"eventually (\\<lambda>n. x - d / 2 < l n) sequentially\"\n        using \\<open>0 < d\\<close> \\<open>l \\<longlonglongrightarrow> x\\<close> by (intro order_tendstoD[of _ x]) auto\n      moreover have \"eventually (\\<lambda>n. u n < x + d / 2) sequentially\"\n        using \\<open>0 < d\\<close> \\<open>u \\<longlonglongrightarrow> x\\<close> by (intro order_tendstoD[of _ x]) auto\n      ultimately have \"eventually (\\<lambda>n. P (l n) (u n)) sequentially\"\n      proof eventually_elim\n        case (elim n)\n        from add_strict_mono[OF this] have \"u n - l n < d\" by simp\n        with x show \"P (l n) (u n)\" by (rule d)\n      qed\n    }\n    ultimately show False by simp\n  qed\nqed\n\nlemma compact_Icc[simp, intro]: \"compact {a .. b::real}\"\nproof (cases \"a \\<le> b\", rule compactI)\n  fix C\n  assume C: \"a \\<le> b\" \"\\<forall>t\\<in>C. open t\" \"{a..b} \\<subseteq> \\<Union>C\"\n  define T where \"T = {a .. b}\"\n  from C(1,3) show \"\\<exists>C'\\<subseteq>C. finite C' \\<and> {a..b} \\<subseteq> \\<Union>C'\"\n  proof (induct rule: Bolzano)\n    case (trans a b c)\n    then have *: \"{a..c} = {a..b} \\<union> {b..c}\"\n      by auto\n    with trans obtain C1 C2\n      where \"C1\\<subseteq>C\" \"finite C1\" \"{a..b} \\<subseteq> \\<Union>C1\" \"C2\\<subseteq>C\" \"finite C2\" \"{b..c} \\<subseteq> \\<Union>C2\"\n      by auto\n    with trans show ?case\n      unfolding * by (intro exI[of _ \"C1 \\<union> C2\"]) auto\n  next\n    case (local x)\n    with C have \"x \\<in> \\<Union>C\" by auto\n    with C(2) obtain c where \"x \\<in> c\" \"open c\" \"c \\<in> C\"\n      by auto\n    then obtain e where \"0 < e\" \"{x - e <..< x + e} \\<subseteq> c\"\n      by (auto simp: open_dist dist_real_def subset_eq Ball_def abs_less_iff)\n    with \\<open>c \\<in> C\\<close> show ?case\n      by (safe intro!: exI[of _ \"e/2\"] exI[of _ \"{c}\"]) auto\n  qed\nqed simp\n\n\nlemma continuous_image_closed_interval:\n  fixes a b and f :: \"real \\<Rightarrow> real\"\n  defines \"S \\<equiv> {a..b}\"\n  assumes \"a \\<le> b\" and f: \"continuous_on S f\"\n  shows \"\\<exists>c d. f`S = {c..d} \\<and> c \\<le> d\"\nproof -\n  have S: \"compact S\" \"S \\<noteq> {}\"\n    using \\<open>a \\<le> b\\<close> by (auto simp: S_def)\n  obtain c where \"c \\<in> S\" \"\\<forall>d\\<in>S. f d \\<le> f c\"\n    using continuous_attains_sup[OF S f] by auto\n  moreover obtain d where \"d \\<in> S\" \"\\<forall>c\\<in>S. f d \\<le> f c\"\n    using continuous_attains_inf[OF S f] by auto\n  moreover have \"connected (f`S)\"\n    using connected_continuous_image[OF f] connected_Icc by (auto simp: S_def)\n  ultimately have \"f ` S = {f d .. f c} \\<and> f d \\<le> f c\"\n    by (auto simp: connected_iff_interval)\n  then show ?thesis\n    by auto\nqed\n\nlemma open_Collect_positive:\n  fixes f :: \"'a::t2_space \\<Rightarrow> real\"\n  assumes f: \"continuous_on s f\"\n  shows \"\\<exists>A. open A \\<and> A \\<inter> s = {x\\<in>s. 0 < f x}\"\n  using continuous_on_open_invariant[THEN iffD1, OF f, rule_format, of \"{0 <..}\"]\n  by (auto simp: Int_def field_simps)\n\nlemma open_Collect_less_Int:\n  fixes f g :: \"'a::t2_space \\<Rightarrow> real\"\n  assumes f: \"continuous_on s f\"\n    and g: \"continuous_on s g\"\n  shows \"\\<exists>A. open A \\<and> A \\<inter> s = {x\\<in>s. f x < g x}\"\n  using open_Collect_positive[OF continuous_on_diff[OF g f]] by (simp add: field_simps)\n\n\nsubsection \\<open>Boundedness of continuous functions\\<close>\n\ntext\\<open>By bisection, function continuous on closed interval is bounded above\\<close>\n\nlemma isCont_eq_Ub:\n  fixes f :: \"real \\<Rightarrow> 'a::linorder_topology\"\n  shows \"a \\<le> b \\<Longrightarrow> \\<forall>x::real. a \\<le> x \\<and> x \\<le> b \\<longrightarrow> isCont f x \\<Longrightarrow>\n    \\<exists>M. (\\<forall>x. a \\<le> x \\<and> x \\<le> b \\<longrightarrow> f x \\<le> M) \\<and> (\\<exists>x. a \\<le> x \\<and> x \\<le> b \\<and> f x = M)\"\n  using continuous_attains_sup[of \"{a..b}\" f]\n  by (auto simp add: continuous_at_imp_continuous_on Ball_def Bex_def)\n\nlemma isCont_eq_Lb:\n  fixes f :: \"real \\<Rightarrow> 'a::linorder_topology\"\n  shows \"a \\<le> b \\<Longrightarrow> \\<forall>x. a \\<le> x \\<and> x \\<le> b \\<longrightarrow> isCont f x \\<Longrightarrow>\n    \\<exists>M. (\\<forall>x. a \\<le> x \\<and> x \\<le> b \\<longrightarrow> M \\<le> f x) \\<and> (\\<exists>x. a \\<le> x \\<and> x \\<le> b \\<and> f x = M)\"\n  using continuous_attains_inf[of \"{a..b}\" f]\n  by (auto simp add: continuous_at_imp_continuous_on Ball_def Bex_def)\n\nlemma isCont_bounded:\n  fixes f :: \"real \\<Rightarrow> 'a::linorder_topology\"\n  shows \"a \\<le> b \\<Longrightarrow> \\<forall>x. a \\<le> x \\<and> x \\<le> b \\<longrightarrow> isCont f x \\<Longrightarrow> \\<exists>M. \\<forall>x. a \\<le> x \\<and> x \\<le> b \\<longrightarrow> f x \\<le> M\"\n  using isCont_eq_Ub[of a b f] by auto\n\nlemma isCont_has_Ub:\n  fixes f :: \"real \\<Rightarrow> 'a::linorder_topology\"\n  shows \"a \\<le> b \\<Longrightarrow> \\<forall>x. a \\<le> x \\<and> x \\<le> b \\<longrightarrow> isCont f x \\<Longrightarrow>\n    \\<exists>M. (\\<forall>x. a \\<le> x \\<and> x \\<le> b \\<longrightarrow> f x \\<le> M) \\<and> (\\<forall>N. N < M \\<longrightarrow> (\\<exists>x. a \\<le> x \\<and> x \\<le> b \\<and> N < f x))\"\n  using isCont_eq_Ub[of a b f] by auto\n\n(*HOL style here: object-level formulations*)\nlemma IVT_objl:\n  \"(f a \\<le> y \\<and> y \\<le> f b \\<and> a \\<le> b \\<and> (\\<forall>x. a \\<le> x \\<and> x \\<le> b \\<longrightarrow> isCont f x)) \\<longrightarrow>\n    (\\<exists>x. a \\<le> x \\<and> x \\<le> b \\<and> f x = y)\"\n  for a y :: real\n  by (blast intro: IVT)\n\nlemma IVT2_objl:\n  \"(f b \\<le> y \\<and> y \\<le> f a \\<and> a \\<le> b \\<and> (\\<forall>x. a \\<le> x \\<and> x \\<le> b \\<longrightarrow> isCont f x)) \\<longrightarrow>\n    (\\<exists>x. a \\<le> x \\<and> x \\<le> b \\<and> f x = y)\"\n  for b y :: real\n  by (blast intro: IVT2)\n\nlemma isCont_Lb_Ub:\n  fixes f :: \"real \\<Rightarrow> real\"\n  assumes \"a \\<le> b\" \"\\<forall>x. a \\<le> x \\<and> x \\<le> b \\<longrightarrow> isCont f x\"\n  shows \"\\<exists>L M. (\\<forall>x. a \\<le> x \\<and> x \\<le> b \\<longrightarrow> L \\<le> f x \\<and> f x \\<le> M) \\<and>\n    (\\<forall>y. L \\<le> y \\<and> y \\<le> M \\<longrightarrow> (\\<exists>x. a \\<le> x \\<and> x \\<le> b \\<and> (f x = y)))\"\nproof -\n  obtain M where M: \"a \\<le> M\" \"M \\<le> b\" \"\\<forall>x. a \\<le> x \\<and> x \\<le> b \\<longrightarrow> f x \\<le> f M\"\n    using isCont_eq_Ub[OF assms] by auto\n  obtain L where L: \"a \\<le> L\" \"L \\<le> b\" \"\\<forall>x. a \\<le> x \\<and> x \\<le> b \\<longrightarrow> f L \\<le> f x\"\n    using isCont_eq_Lb[OF assms] by auto\n  show ?thesis\n    using IVT[of f L _ M] IVT2[of f L _ M] M L assms\n    apply (rule_tac x=\"f L\" in exI)\n    apply (rule_tac x=\"f M\" in exI)\n    apply (cases \"L \\<le> M\")\n     apply simp\n     apply (metis order_trans)\n    apply simp\n    apply (metis order_trans)\n    done\nqed\n\n\ntext \\<open>Continuity of inverse function.\\<close>\n\nlemma isCont_inverse_function:\n  fixes f g :: \"real \\<Rightarrow> real\"\n  assumes d: \"0 < d\"\n    and inj: \"\\<forall>z. \\<bar>z-x\\<bar> \\<le> d \\<longrightarrow> g (f z) = z\"\n    and cont: \"\\<forall>z. \\<bar>z-x\\<bar> \\<le> d \\<longrightarrow> isCont f z\"\n  shows \"isCont g (f x)\"\nproof -\n  let ?A = \"f (x - d)\"\n  let ?B = \"f (x + d)\"\n  let ?D = \"{x - d..x + d}\"\n\n  have f: \"continuous_on ?D f\"\n    using cont by (intro continuous_at_imp_continuous_on ballI) auto\n  then have g: \"continuous_on (f`?D) g\"\n    using inj by (intro continuous_on_inv) auto\n\n  from d f have \"{min ?A ?B <..< max ?A ?B} \\<subseteq> f ` ?D\"\n    by (intro connected_contains_Ioo connected_continuous_image) (auto split: split_min split_max)\n  with g have \"continuous_on {min ?A ?B <..< max ?A ?B} g\"\n    by (rule continuous_on_subset)\n  moreover\n  have \"(?A < f x \\<and> f x < ?B) \\<or> (?B < f x \\<and> f x < ?A)\"\n    using d inj by (intro continuous_inj_imp_mono[OF _ _ f] inj_on_imageI2[of g, OF inj_onI]) auto\n  then have \"f x \\<in> {min ?A ?B <..< max ?A ?B}\"\n    by auto\n  ultimately\n  show ?thesis\n    by (simp add: continuous_on_eq_continuous_at)\nqed\n\nlemma isCont_inverse_function2:\n  fixes f g :: \"real \\<Rightarrow> real\"\n  shows\n    \"a < x \\<Longrightarrow> x < b \\<Longrightarrow>\n      \\<forall>z. a \\<le> z \\<and> z \\<le> b \\<longrightarrow> g (f z) = z \\<Longrightarrow>\n      \\<forall>z. a \\<le> z \\<and> z \\<le> b \\<longrightarrow> isCont f z \\<Longrightarrow> isCont g (f x)\"\n  apply (rule isCont_inverse_function [where f=f and d=\"min (x - a) (b - x)\"])\n  apply (simp_all add: abs_le_iff)\n  done\n\n(* need to rename second isCont_inverse *)\nlemma isCont_inv_fun:\n  fixes f g :: \"real \\<Rightarrow> real\"\n  shows \"0 < d \\<Longrightarrow> (\\<forall>z. \\<bar>z - x\\<bar> \\<le> d \\<longrightarrow> g (f z) = z) \\<Longrightarrow>\n    \\<forall>z. \\<bar>z - x\\<bar> \\<le> d \\<longrightarrow> isCont f z \\<Longrightarrow> isCont g (f x)\"\n  by (rule isCont_inverse_function)\n\ntext \\<open>Bartle/Sherbert: Introduction to Real Analysis, Theorem 4.2.9, p. 110.\\<close>\nlemma LIM_fun_gt_zero: \"f \\<midarrow>c\\<rightarrow> l \\<Longrightarrow> 0 < l \\<Longrightarrow> \\<exists>r. 0 < r \\<and> (\\<forall>x. x \\<noteq> c \\<and> \\<bar>c - x\\<bar> < r \\<longrightarrow> 0 < f x)\"\n  for f :: \"real \\<Rightarrow> real\"\n  apply (drule (1) LIM_D)\n  apply clarify\n  apply (rule_tac x = s in exI)\n  apply (simp add: abs_less_iff)\n  done\n\nlemma LIM_fun_less_zero: \"f \\<midarrow>c\\<rightarrow> l \\<Longrightarrow> l < 0 \\<Longrightarrow> \\<exists>r. 0 < r \\<and> (\\<forall>x. x \\<noteq> c \\<and> \\<bar>c - x\\<bar> < r \\<longrightarrow> f x < 0)\"\n  for f :: \"real \\<Rightarrow> real\"\n  apply (drule LIM_D [where r=\"-l\"])\n   apply simp\n  apply clarify\n  apply (rule_tac x = s in exI)\n  apply (simp add: abs_less_iff)\n  done\n\nlemma LIM_fun_not_zero: \"f \\<midarrow>c\\<rightarrow> l \\<Longrightarrow> l \\<noteq> 0 \\<Longrightarrow> \\<exists>r. 0 < r \\<and> (\\<forall>x. x \\<noteq> c \\<and> \\<bar>c - x\\<bar> < r \\<longrightarrow> f x \\<noteq> 0)\"\n  for f :: \"real \\<Rightarrow> real\"\n  using LIM_fun_gt_zero[of f l c] LIM_fun_less_zero[of f l c] by (auto simp add: neq_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/Limits.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.839733963661418, "lm_q2_score": 0.8354835411997897, "lm_q1q2_score": 0.701583905625577}}
{"text": "theory Computation\n  imports Main\nbegin\n\nlemma split_app: \"\\<And>xs ys xs' ys'. xs @ ys = xs' @ ys' \\<Longrightarrow> length xs \\<le> length xs' \\<Longrightarrow>\n  \\<exists>ds. xs' = xs @ ds\"\n  by (metis (full_types) append_eq_append_conv_if append_eq_conv_conj)\n\nlemma split_app': \"\\<And>xs ys xs' ys'. xs @ ys = xs' @ ys' \\<Longrightarrow> length xs \\<le> length xs' \\<Longrightarrow>\n  \\<exists>es. ys = es @ ys'\"\n  by (simp add: append_eq_append_conv_if)\n\nlemma app_decomp: \"length xs = length (ys @ ys') \\<Longrightarrow>\n  \\<exists>zs zs'. xs = zs @ zs' \\<and> length zs = length ys \\<and> length zs' = length ys'\"\n  by (metis append_eq_conv_conj length_drop length_rev rev_take)\n\nlemma singleton_dest: \"length xs = Suc 0 \\<Longrightarrow> \\<exists>x. xs = [x]\"\n  by (cases xs) auto\n\nlemma set_zip: \"set (zip xs ys) \\<subseteq> set xs \\<times> set ys\"\n  by (induction xs arbitrary: ys) (auto dest: set_zip_leftD set_zip_rightD)\n\nlemma map_ext:\n  assumes \"map f xs = ys @ ys'\"\n  shows \"\\<exists>zs zs'. xs = zs @ zs' \\<and> map f zs = ys \\<and> map f zs' = ys'\"\nproof -\n  define zs where \"zs = take (length ys) xs\"\n  define zs' where \"zs' = drop (length ys) xs\"\n  have \"xs = zs @ zs'\" \"map f zs = ys\" \"map f zs' = ys'\"\n    using iffD1[OF append_eq_conv_conj, OF assms[symmetric]]\n    by (auto simp add: zs_def zs'_def take_map drop_map)\n  then show ?thesis\n    by auto\nqed\n\nfun iter_concat :: \"nat \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where\n  \"iter_concat 0 xs = []\"\n| \"iter_concat (Suc n) xs = xs @ iter_concat n xs\"\n\nlemma iter_concat_length: \"length (iter_concat n xs) = n * length xs\"\n  by (induction n xs rule: iter_concat.induct) auto\n\nlemma card_finite_product_subset:\n  \"finite Q \\<Longrightarrow> QS' \\<subseteq> Q \\<times> Q \\<Longrightarrow> card QS' \\<le> card Q * card Q\"\n  by (metis card_cartesian_product card_mono finite_cartesian_product)\n\nlemma finite_bounded_lists: \"finite {bs :: ('b :: finite) list. length bs \\<le> n}\"\nproof (induction n)\n  case (Suc n)\n  have split: \"{bs :: 'b list. length bs \\<le> Suc n} = {bs. length bs \\<le> n} \\<union> {bs. length bs = Suc n}\"\n    by auto\n  have \"{bs :: 'b list. length bs = Suc n} \\<subseteq> (\\<Union>(b, bs) \\<in> UNIV \\<times> {bs. length bs \\<le> n}. {b # bs})\"\n  proof (rule subsetI)\n    fix x\n    assume \"x \\<in> {bs :: 'b list. length bs = Suc n}\"\n    then show \"x \\<in> (\\<Union>(b, bs)\\<in>UNIV \\<times> {bs. length bs \\<le> n}. {b # bs})\"\n      by (cases x) auto\n  qed\n  moreover have \"finite (\\<Union>(b, bs) \\<in> UNIV \\<times> {bs :: 'b list. length bs \\<le> n}. {b # bs})\"\n    using Suc by auto\n  ultimately have \"finite {bs :: 'b list. length bs = Suc n}\"\n    using infinite_super by blast\n  with Suc split show ?case\n    by auto\nqed auto\n\ndatatype 'a Al = Symb 'a | Blank\n\ndefinition \"safe_hd bs' = (case bs' of [] \\<Rightarrow> Blank | b # bs \\<Rightarrow> Symb b)\"\n\nlemma safe_hd_Nil: \"safe_hd [] = Blank\"\n  by (auto simp add: safe_hd_def)\n\nlemma safe_hd_Cons: \"safe_hd (x # xs) = Symb x\"\n  by (auto simp: safe_hd_def)\n\nlemma safe_hd_eq: \"xs = xs' @ (q, b) # xs'' \\<Longrightarrow>\n  safe_hd (map snd xs) = safe_hd (map snd (xs' @ (q, b) # xs'''))\"\n  by (auto simp add: safe_hd_def split: list.splits) (metis Cons_eq_append_conv nth_Cons_0)\n\nlemma safe_hd_app: \"safe_hd xs = safe_hd xs' \\<Longrightarrow> safe_hd (xs @ ys) = safe_hd (xs' @ ys)\"\n  by (auto simp add: safe_hd_def split: list.splits)\n\nlemma safe_hd_app': \"safe_hd ys = safe_hd ys' \\<Longrightarrow> safe_hd (xs @ ys) = safe_hd (xs @ ys')\"\n  by (auto simp add: safe_hd_def split: list.splits) (metis append_Nil hd_append2 list.sel(1))\n\nlemma safe_hd_app'': \"xs \\<noteq> [] \\<Longrightarrow> safe_hd (xs @ ys) = safe_hd (xs @ ys')\"\n  by (cases xs) (auto simp add: safe_hd_def split: list.splits)\n\nlemma safe_hd_app_Cons: \"safe_hd (xs @ x # ys) = safe_hd (xs @ x # ys')\"\n  by (cases xs) (auto simp add: safe_hd_def split: list.splits)\n\nlemma safe_hd_Nil_dest: \"safe_hd [] = safe_hd xs \\<Longrightarrow> xs = []\"\n  by (auto simp: safe_hd_def split: list.splits)\n\nlemma safe_hd_Cons_app: \"xs = x # xs' \\<Longrightarrow> safe_hd (xs @ ys) = Symb x\"\n  by (auto simp: safe_hd_def)\n\n(* Definition 1 *)\n\nlocale TDFA =\n  fixes init :: \"'s\"\n    and \\<delta> :: \"'s \\<Rightarrow> 'a Al \\<times> 'b Al \\<Rightarrow> ('s \\<times> bool \\<times> bool) option\"\n    and accept :: \"'s \\<Rightarrow> bool\"\n    and Q :: \"'s set\"\n  assumes finite_Q: \"finite Q\" and\n    init_in_Q: \"init \\<in> Q\" and\n    closed: \"q \\<in> Q \\<Longrightarrow> \\<delta> q z = Some (q', b1, b2) \\<Longrightarrow> q' \\<in> Q\" and\n    move_left: \"\\<delta> q (a, b) = Some (q', True, b2) \\<Longrightarrow> a \\<noteq> Blank\" and\n    move_right: \"\\<delta> q (a, b) = Some (q', b1, True) \\<Longrightarrow> b \\<noteq> Blank\" and\n    no_step: \"\\<delta> q (a, b) = Some (q', False, False) \\<Longrightarrow> False\"\nbegin\n\ninductive computation :: \"'s \\<Rightarrow> ('a list \\<times> 'a list) \\<times> ('b list \\<times> 'b list) \\<Rightarrow> 's \\<Rightarrow> bool\"\n  (\"_/\\<leadsto>_/_\" [64,64,64]63) where\n  base[intro]: \"q \\<leadsto>(([], as'), ([], bs')) q\"\n| step_TT[intro]: \"\\<delta> q (Symb a, Symb b) = Some (q', True, True) \\<Longrightarrow>\n  q' \\<leadsto>((as, as'), (bs, bs')) q'' \\<Longrightarrow> q \\<leadsto>((a # as, as'), (b # bs, bs')) q''\"\n| step_TF[intro]: \"\\<delta> q (Symb a, safe_hd (bs @ bs')) = Some (q', True, False) \\<Longrightarrow>\n  q' \\<leadsto>((as, as'), (bs, bs')) q'' \\<Longrightarrow> q \\<leadsto>((a # as, as'), (bs, bs')) q''\"\n| step_FT[intro]: \"\\<delta> q (safe_hd (as @ as'), Symb b) = Some (q', False, True) \\<Longrightarrow>\n  q' \\<leadsto>((as, as'), (bs, bs')) q'' \\<Longrightarrow> q \\<leadsto>((as, as'), (b # bs, bs')) q''\"\n\ndefinition \\<tau> :: \"('a list \\<times> 'b list) set\" where\n  \"\\<tau> = {(as, bs). \\<exists>q. init \\<leadsto>((as, []), (bs, [])) q \\<and> accept q}\"\n\nlemma step_TF_rev: \"q \\<leadsto>((as, a # as'), (bs, bs')) q' \\<Longrightarrow>\n  \\<delta> q' (Symb a, safe_hd bs') = Some (q'', True, False) \\<Longrightarrow> q \\<leadsto>((as @ [a], as'), (bs, bs')) q''\"\n  by (induction q \"((as, a # as'), (bs, bs'))\" q' arbitrary: as bs rule: computation.induct)\n     (auto simp: safe_hd_def)\n\nlemma step_FT_rev: \"q \\<leadsto>((as, as'), (bs, b' # bs')) q' \\<Longrightarrow>\n  \\<delta> q' (safe_hd as', Symb b') = Some (q'', False, True) \\<Longrightarrow> q \\<leadsto>((as, as'), (bs @ [b'], bs')) q''\"\n  by (induction q \"((as, as'), (bs, b' # bs'))\" q' arbitrary: as bs rule: computation.induct)\n     (auto simp: safe_hd_def)\n\nlemma comp_unreachable:\n  \"q \\<leadsto>((as, as'), (bs, bs')) q' \\<Longrightarrow> (\\<And>z. \\<delta> q z = None) \\<Longrightarrow> q = q'\"\n  by (auto elim: computation.cases)\n\nlemma comp_closed: \"q \\<leadsto>((as, as'), (bs, bs')) q' \\<Longrightarrow> q \\<in> Q \\<Longrightarrow> q' \\<in> Q\"\n  by (induction q \"((as, as'), (bs, bs'))\" q' arbitrary: as as' bs bs' rule: computation.induct)\n     (auto dest: closed)\n\nlemma no_computation_dest: \"q \\<leadsto>(([], as'), ([], bs')) q' \\<Longrightarrow> q = q'\"\n  by (auto elim: computation.cases)\n\nlemma comp_split: \"q \\<leadsto>((as @ as', as''), (bs, bs')) q' \\<Longrightarrow>\n  \\<exists>q'' cs cs'. bs = cs @ cs' \\<and> q \\<leadsto>((as, as' @ as''), (cs, cs' @ bs')) q'' \\<and>\n    q'' \\<leadsto>((as', as''), (cs', bs')) q'\"\nproof (induction q \"((as @ as', as''), (bs, bs'))\" q' arbitrary: as bs rule: computation.induct)\n  case (step_TT q a b q' as' bs q'')\n  then show ?case\n  proof (cases as)\n    case (Cons x xs)\n    show ?thesis\n      using step_TT(1,2,4) step_TT(3)[of xs]\n      by (auto simp: Cons) (metis append_Cons computation.step_TT)\n  qed fastforce\nnext\n  case (step_TF q a bs q' as q'')\n  then show ?case\n    by (cases as) fastforce+\nnext\n  case (step_FT q b q' bs q'')\n  then show ?case\n  proof (cases as)\n    case (Cons x xs)\n    then show ?thesis\n      using step_FT\n      by auto (metis Cons_eq_appendI computation.step_FT)\n  qed fastforce\nqed auto\n\nlemma comp_pull: \"q \\<leadsto>((u1, u1'), (v1, v1')) q'' \\<Longrightarrow> q \\<leadsto>((u1 @ u2, u3), (v1 @ v2, v3)) q' \\<Longrightarrow>\n  safe_hd u1' = safe_hd (u2 @ u3) \\<Longrightarrow> safe_hd v1' = safe_hd (v2 @ v3) \\<Longrightarrow>\n  q'' \\<leadsto>((u2, u3), (v2, v3)) q'\"\nproof (induction q \"((u1, u1'), (v1, v1'))\" q'' arbitrary: u1 v1 rule: computation.induct)\n  case (step_TT q a b q''' as bs q'')\n  have \"q''' \\<leadsto>((as @ u2, u3), bs @ v2, v3) q'\"\n    using step_TT(1,4)\n    by (auto simp: safe_hd_def elim: computation.cases)\n  then show ?case\n    by (rule step_TT(3)[OF _ step_TT(5,6)])\nnext\n  case (step_TF q a bs q''' as q'')\n  have \"q''' \\<leadsto>((as @ u2, u3), bs @ v2, v3) q'\"\n    using step_TF(1,4) safe_hd_Cons_app[of \"bs @ v2\" _ _ v3, simplified]\n    by (auto simp: safe_hd_app'[OF step_TF(6)] safe_hd_Cons elim: computation.cases)\n  then show ?case\n    by (rule step_TF(3)[OF _ step_TF(5,6)])\nnext\n  case (step_FT q as b q''' bs q'')\n  have \"q'''\\<leadsto>((as @ u2, u3), bs @ v2, v3)q'\"\n    using step_FT(1,4) safe_hd_Cons_app[of \"as @ u2\" _ _ u3, simplified]\n    by (auto simp: safe_hd_app'[OF step_FT(5)] safe_hd_Cons elim: computation.cases)\n  then show ?case\n    by (rule step_FT(3)[OF _ step_FT(5,6)])\nqed auto\n\nlemma comp_swap: \"q \\<leadsto>((as, a' # as'), (bs, bs')) q' \\<Longrightarrow> q \\<leadsto>((as, a' # as''), (bs, bs')) q'\"\n  by (induction q \"((as, a' # as'), (bs, bs'))\" q' arbitrary: as bs\n      rule: computation.induct)\n     (auto cong: safe_hd_app_Cons)\n\nlemma comp_swap': \"q \\<leadsto>((as, as'), (bs, b' # bs')) q' \\<Longrightarrow> q \\<leadsto>((as, as'), (bs, b' # bs'')) q'\"\n  by (induction q \"((as, as'), (bs, b' # bs'))\" q' arbitrary: as bs\n      rule: computation.induct)\n    (auto cong: safe_hd_app_Cons)\n\nlemma comp_swap_same_hd: \"q \\<leadsto>((as, as'), (bs, bs')) q' \\<Longrightarrow>\n  safe_hd as' = safe_hd as'' \\<Longrightarrow> safe_hd bs' = safe_hd bs'' \\<Longrightarrow>\n  q \\<leadsto>((as, as''), (bs, bs'')) q'\"\n  by (induction q \"((as, as'), (bs, bs'))\" q' arbitrary: as bs rule: computation.induct)\n     (auto cong: safe_hd_app')\n\nlemma comp_trans: \"q \\<leadsto>((as, as'), (bs, bs')) q' \\<Longrightarrow> q' \\<leadsto>((cs, cs'), (ds, ds')) q'' \\<Longrightarrow>\n  safe_hd as' = safe_hd (cs @ cs') \\<Longrightarrow> safe_hd bs' = safe_hd (ds @ ds') \\<Longrightarrow>\n  q \\<leadsto>((as @ cs, cs'), (bs @ ds, ds')) q''\"\n  apply (induction q \"((as, as'), (bs, bs'))\" q' arbitrary: as bs rule: computation.induct)\n  using safe_hd_app'\n  by (fastforce dest: safe_hd_Nil_dest)+\n\nlemma comp_swapR: \"q \\<leadsto>(([], as'), (bs, bs')) q' \\<Longrightarrow> q \\<leadsto>(([], as'), (bs, cs')) q'\"\n  by (induction q \"(([] :: 'a list, as'), (bs, bs'))\" q' arbitrary: bs rule: computation.induct)\n     (auto)\n\nlemma comp_transR:\n  assumes \"q \\<leadsto>(([], as'), (bs, bs')) q'\" \"q' \\<leadsto>(([], as'), (cs, bs'')) q''\"\n  shows \"q \\<leadsto>(([], as'), (bs @ cs, bs'')) q''\"\n  using comp_trans[OF comp_swapR[OF assms(1)] assms(2)]\n  by auto\n\nlemma fst_stepL: \"q\\<leadsto>(([], as'), (b # bs, bs'))q' \\<Longrightarrow>\n  \\<exists>q''. \\<delta> q (safe_hd as', Symb b) = Some (q'', False, True) \\<and> q'' \\<leadsto>(([], as'), (bs, bs')) q'\"\n  by (auto elim: computation.cases)\n\nlemma comp_splitL: \"q\\<leadsto>(([], as'), (cs @ cs', cs'')) q' \\<Longrightarrow>\n  \\<exists>q''. q \\<leadsto>(([], as'), (cs, cs' @ cs'')) q'' \\<and> q'' \\<leadsto>(([], as'), (cs', cs'')) q'\"\n  by (induction cs arbitrary: q) (fastforce dest!: fst_stepL)+\n\nlemma shift_compL: assumes \"r\\<leadsto>(([], w), (cs @ cs'), ds')t\" \"t\\<leadsto>((w, []), ds', [])r'\"\n  shows \"\\<exists>t''. r \\<leadsto>(([], w), (cs, cs' @ ds')) t'' \\<and> t'' \\<leadsto>((w, []), (cs' @ ds', [])) r'\"\nproof -\n  obtain t'' where t''_def: \"r \\<leadsto>(([], w), (cs, cs' @ ds')) t''\" \"t'' \\<leadsto>(([], w), (cs', ds')) t\"\n    using comp_splitL[OF assms(1)]\n    by auto\n  have comb: \"t'' \\<leadsto>((w, []), (cs' @ ds', [])) r'\"\n    using comp_trans[OF t''_def(2) assms(2)]\n    by auto\n  show ?thesis\n    using t''_def(1) comb\n    by auto\nqed\n\nlemma fst_stepR: \"q\\<leadsto>((a # as, as'), ([], bs'))q' \\<Longrightarrow>\n  \\<exists>q''. \\<delta> q (Symb a, safe_hd bs') = Some (q'', True, False) \\<and> q'' \\<leadsto>((as, as'), ([], bs')) q'\"\n  by (auto elim: computation.cases)\n\ninductive computation_ext ::\n  \"'s \\<Rightarrow> 's list \\<times> ('a list \\<times> 'a list) \\<times> ('b list \\<times> 'b list) \\<Rightarrow> 's \\<Rightarrow> bool\"\n  (\"_/\\<leadsto>e_/_\" [64,64,64]63) where\n  base_ext[intro]: \"q \\<leadsto>e([], ([], as'), ([], bs')) q\"\n| step_TT_ext[intro]: \"\\<delta> q (Symb a, Symb b) = Some (q', True, True) \\<Longrightarrow>\n  q' \\<leadsto>e(qs, (as, as'), (bs, bs')) q'' \\<Longrightarrow> q \\<leadsto>e(q' # qs, (a # as, as'), (b # bs, bs')) q''\"\n| step_TF_ext[intro]: \"\\<delta> q (Symb a, safe_hd (bs @ bs')) = Some (q', True, False) \\<Longrightarrow>\n  q' \\<leadsto>e(qs, (as, as'), (bs, bs')) q'' \\<Longrightarrow> q \\<leadsto>e(q' # qs, (a # as, as'), (bs, bs')) q''\"\n| step_FT_ext[intro]: \"\\<delta> q (safe_hd (as @ as'), Symb b) = Some (q', False, True) \\<Longrightarrow>\n  q' \\<leadsto>e(qs, (as, as'), (bs, bs')) q'' \\<Longrightarrow> q \\<leadsto>e(q' # qs, (as, as'), (b # bs, bs')) q''\"\n\nlemma comp_to_ext: \"q \\<leadsto>((as, as'), (bs, bs')) q' \\<Longrightarrow>\n  \\<exists>qs. q \\<leadsto>e(qs, (as, as'), (bs, bs')) q'\"\n  by (induction q \"((as, as'), (bs, bs'))\" q' arbitrary: as bs rule: computation.induct) auto\n\nlemma ext_to_comp: \"q \\<leadsto>e(qs, (as, as'), (bs, bs')) q' \\<Longrightarrow> q \\<leadsto>((as, as'), (bs, bs')) q'\"\n  by (induction q \"(qs, (as, as'), (bs, bs'))\" q' arbitrary: qs as bs rule: computation_ext.induct)\n     (auto)\n\nlemma ext_closed: \"q \\<leadsto>e(qs, (as, as'), (bs, bs')) q' \\<Longrightarrow> q \\<in> Q \\<Longrightarrow> set qs \\<subseteq> Q\"\n  apply (induction q \"(qs, (as, as'), (bs, bs'))\" q' arbitrary: qs as bs rule: computation_ext.induct)\n  using closed\n  by auto\n\nlemma comp_ext_trans: \"q \\<leadsto>e(qs, (as, as'), (bs, bs')) q' \\<Longrightarrow>\n  q' \\<leadsto>e(qs', (cs, cs'), (ds, ds')) q'' \\<Longrightarrow>\n  safe_hd as' = safe_hd (cs @ cs') \\<Longrightarrow> safe_hd bs' = safe_hd (ds @ ds') \\<Longrightarrow>\n  q \\<leadsto>e(qs @ qs', (as @ cs, cs'), (bs @ ds, ds')) q''\"\n  apply (induction q \"(qs, (as, as'), (bs, bs'))\" q' arbitrary: qs as bs rule: computation_ext.induct)\n  using safe_hd_app'\n  by (fastforce dest: safe_hd_Nil_dest)+\n\nlemma comp_ext_swapR: \"q \\<leadsto>e(qs, ([], as'), (bs, bs')) q' \\<Longrightarrow> q \\<leadsto>e(qs, ([], as'), (bs, cs')) q'\"\n  by (induction q \"(qs, ([] :: 'a list, as'), (bs, bs'))\" q' arbitrary: qs bs rule: computation_ext.induct)\n     (auto)\n\nlemma comp_ext_transR:\n  assumes \"q \\<leadsto>e(qs, ([], as'), (bs, bs')) q'\" \"q' \\<leadsto>e(qs', ([], as'), (cs, bs'')) q''\"\n  shows \"q \\<leadsto>e(qs @ qs', ([], as'), (bs @ cs, bs'')) q''\"\n  using comp_ext_trans[OF comp_ext_swapR[OF assms(1)] assms(2)]\n  by auto\n\nlemma ext_split: \"q \\<leadsto>e(qs @ q' # qs', ([], as'), (bs @ b # bs', bs'')) q'' \\<Longrightarrow>\n  length qs = length bs \\<Longrightarrow>\n  q \\<leadsto>e(qs @ [q'], ([], as'), (bs @ [b], bs' @ bs'')) q' \\<and> q' \\<leadsto>e(qs', ([], as'), (bs', bs'')) q''\"\nproof (induction q \"(qs @ q' # qs',  ([] :: 'a list, as'), (bs @ b # bs', bs''))\" q''\n    arbitrary: qs bs rule: computation_ext.induct)\n  case (step_FT_ext q b q'a qs bs q'' qsa bsa)\n  then show ?case\n    by (cases qsa; cases bsa) auto\nqed simp\n\nlemma ext_rem_loop:\n  assumes \"q \\<leadsto>e(qs @ q' # qs' @ q' # qs'', ([], as'), (bs @ b # bs' @ b' # bs'', bs''')) q''\"\n    \"length qs = length bs\" \"length qs' = length bs'\"\n  shows \"q \\<leadsto>e(qs @ q' # qs'', ([], as'), (bs @ b # bs'', bs''')) q''\"\nproof -\n  have split: \"q\\<leadsto>e(qs @ [q'], ([], as'), bs @ [b], (bs' @ b' # bs'') @ bs''')q'\"\n    \"q' \\<leadsto>e(qs' @ q' # qs'', ([], as'), bs' @ b' # bs'', bs''')q''\"\n    using ext_split[OF assms(1,2)]\n    by auto\n  have split': \"q'\\<leadsto>e(qs' @ [q'], ([], as'), bs' @ [b'], bs'' @ bs''')q'\"\n    \"q'\\<leadsto>e(qs'', ([], as'), bs'', bs''')q''\"\n    using ext_split[OF split(2)] assms(3)\n    by auto\n  show ?thesis\n    using comp_ext_transR[OF split(1) split'(2)]\n    by auto\nqed\n\nend\n\nlocale oTDFA = TDFA init \\<delta> accept Q\n  for init :: \"'s\"\n    and \\<delta> :: \"'s \\<Rightarrow> 'a Al \\<times> 'b Al \\<Rightarrow> ('s \\<times> bool \\<times> bool) option\"\n    and accept :: \"'s \\<Rightarrow> bool\"\n    and Q :: \"'s set\" +\n  assumes move_one: \"\\<delta> q (a, b) = Some (q', True, True) \\<Longrightarrow> False\"\nbegin\n\nlemma comp_ext_length: \"q \\<leadsto>e(qs, (as, as'), (bs, bs')) q' \\<Longrightarrow> length qs = length as + length bs\"\n  by (induction q \"(qs, (as, as'), (bs, bs'))\" q' arbitrary: qs as bs rule: computation_ext.induct)\n     (auto dest: move_one)\n\nlemma fst_step: \"q \\<leadsto>((a # as, as'), (b # bs, bs')) q' \\<Longrightarrow>\n  (\\<exists>q''. \\<delta> q (Symb a, Symb b) = Some (q'', True, False) \\<and> q'' \\<leadsto>((as, as'), (b # bs, bs')) q') \\<or>\n  (\\<exists>q''. \\<delta> q (Symb a, Symb b) = Some (q'', False, True) \\<and> q'' \\<leadsto>((a # as, as'), (bs, bs')) q')\"\n  by (auto simp: safe_hd_def dest: move_one elim: computation.cases)\n\nlemma split_outs: \"q \\<leadsto>((a # as, as'), (bs, bs')) q' \\<Longrightarrow>\n  \\<exists>r r' cs cs'. bs = cs @ cs' \\<and> q \\<leadsto>(([], a # as @ as'), (cs, cs' @ bs')) r \\<and>\n  \\<delta> r (Symb a, safe_hd (cs' @ bs')) = Some (r', True, False) \\<and> r' \\<leadsto>((as, as'), (cs', bs')) q'\"\nproof (induction bs arbitrary: q)\n  case Nil\n  then show ?case\n    using fst_stepR\n    by auto\nnext\n  case (Cons b bs'')\n  show ?case\n    using fst_step[OF Cons(2)]\n  proof (rule disjE)\n    assume \"\\<exists>q''. \\<delta> q (Symb a, Symb b) = Some (q'', True, False) \\<and>\n      q''\\<leadsto>((as, as'), b # bs'', bs')q'\"\n    then obtain r' where r'_def: \"\\<delta> q (Symb a, Symb b) = Some (r', True, False)\"\n      \"r'\\<leadsto>((as, as'), b # bs'', bs')q'\"\n      by auto\n    show \"\\<exists>r r' cs cs'. b # bs'' = cs @ cs' \\<and>\n      q\\<leadsto>(([], a # as @ as'), cs, cs' @ bs')r \\<and>\n      \\<delta> r (Symb a, safe_hd (cs' @ bs')) = Some (r', True, False) \\<and> r'\\<leadsto>((as, as'), cs', bs')q'\"\n      apply (rule exI[of _ q])\n      apply (rule exI[of _ r'])\n      apply (rule exI[of _ \"[]\"])\n      apply (auto simp: safe_hd_def r'_def)\n      done\n  next\n    assume \"\\<exists>q''. \\<delta> q (Symb a, Symb b) = Some (q'', False, True) \\<and>\n      q''\\<leadsto>((a # as, as'), bs'', bs')q'\"\n    then obtain s where s_def: \"\\<delta> q (Symb a, Symb b) = Some (s, False, True)\"\n      \"s\\<leadsto>((a # as, as'), bs'', bs')q'\"\n      by auto\n    obtain r r' cs cs' where split: \"bs'' = cs @ cs'\" \"s\\<leadsto>(([], a # as @ as'), cs, cs' @ bs')r\"\n      \"\\<delta> r (Symb a, safe_hd (cs' @ bs')) = Some (r', True, False)\" \"r'\\<leadsto>((as, as'), cs', bs')q'\"\n      using Cons(1)[OF s_def(2)]\n      by auto\n    have comp_q_s: \"q \\<leadsto>(([], a # as @ as'), ([b], bs'' @ bs')) s\"\n      apply (rule step_FT[OF _ base])\n      using s_def(1)\n      by (auto simp: safe_hd_def)\n    have comp_q_r: \"q \\<leadsto>(([], a # as @ as'), (b # cs, cs' @ bs')) r\"\n      using split(2) comp_trans[OF comp_q_s] comp_q_s\n      by (auto simp: split(1) split: list.splits)\n    show \"\\<exists>r r' cs cs'. b # bs'' = cs @ cs' \\<and> q\\<leadsto>(([], a # as @ as'), cs, cs' @ bs')r \\<and>\n      \\<delta> r (Symb a, safe_hd (cs' @ bs')) = Some (r', True, False) \\<and> r'\\<leadsto>((as, as'), cs', bs')q'\"\n      apply (rule exI[of _ r])\n      apply (rule exI[of _ r'])\n      apply (rule exI[of _ \"b # cs\"])\n      apply (rule exI[of _ cs'])\n      apply (auto simp: split comp_q_r)\n      done\n  qed\nqed\n\nlemma set_zip_upd: \"length xs = length ys \\<Longrightarrow> (\\<And>x y. (x, y) \\<in> set (zip xs ys) \\<Longrightarrow> \\<exists>x'. g x' y) \\<Longrightarrow>\n  \\<exists>xs'. length xs' = length ys \\<and> (\\<forall>(x', y) \\<in> set (zip xs' ys). g x' y)\"\nproof (induction xs ys rule: list_induct2)\n  case (Cons x xs y ys)\n  obtain x' where x'_def: \"g x' y\"\n    using Cons(3)\n    by auto\n  obtain xs' where xs'_def: \"length xs' = length ys\" \"\\<forall>(x', y) \\<in> set (zip xs' ys). g x' y\"\n    using Cons(2,3)\n    by auto\n  show ?case\n    using x'_def xs'_def\n    by (auto intro!: exI[of _ \"x' # xs'\"])\nqed auto\n\nlemma set_zip_upd4:\n  assumes \"length xs = length ys\"\n  shows \"(\\<And>x y z w. (x, y, z, w) \\<in> set (zip xs ys) \\<Longrightarrow> \\<exists>x'. g x' y z w) \\<Longrightarrow>\n    \\<exists>xs'. length xs' = length ys \\<and> (\\<forall>(x', y, z, w) \\<in> set (zip xs' ys). g x' y z w)\"\n  using set_zip_upd[OF assms, of \"\\<lambda>x' y. case y of (y', z, w) \\<Rightarrow> g x' y' z w\"]\n  by auto\n\nlemma split_outss:\n  assumes \"\\<And>w r r'. (w, r, r') \\<in> set ws \\<Longrightarrow> r \\<leadsto>((w, []), (u, [])) r'\"\n  shows \"\\<exists>cs cs' ts. u = cs @ cs' \\<and> length ts = length ws \\<and>\n    (\\<forall>(t, w, r, r') \\<in> set (zip ts ws). r \\<leadsto>(([], w), (cs, cs')) t \\<and> t \\<leadsto>((w, []), (cs', [])) r') \\<and>\n    (case concat (map fst ws) of [] \\<Rightarrow> cs' = [] | _ \\<Rightarrow> \\<exists>a \\<in> set (zip ts ws).\n      case a of (t, w, r, r') \\<Rightarrow> \\<exists>t'. \\<delta> t (safe_hd w, safe_hd cs') = Some (t', True, False))\"\n  using assms\nproof (induction ws)\n  case (Cons wrr' ws)\n  obtain w r r' where wrr'_def: \"wrr' = (w, r, r')\"\n    by (cases wrr') auto\n  obtain cs cs' ts where ws_def: \"u = cs @ cs'\" \"length ts = length ws\"\n    \"\\<And>t w r r'. (t, w, r, r') \\<in> set (zip ts ws) \\<Longrightarrow>\n      r \\<leadsto>(([], w), (cs, cs')) t \\<and> t \\<leadsto>((w, []), (cs', [])) r'\"\n    \"(case concat (map fst ws) of [] \\<Rightarrow> cs' = [] | _ \\<Rightarrow> \\<exists>a \\<in> set (zip ts ws).\n      case a of (t, w, r, r') \\<Rightarrow> \\<exists>t'. \\<delta> t (safe_hd w, safe_hd cs') = Some (t', True, False))\"\n    using Cons\n    by (auto split: prod.splits)\n  have comp: \"r \\<leadsto>((w, []), (u, [])) r'\"\n    using Cons(2)\n    by (auto simp: wrr'_def)\n  show ?case\n  proof (cases w)\n    case Nil\n    obtain t where t_def: \"r\\<leadsto>(([], []), cs, cs')t\" \"t\\<leadsto>(([], []), cs', [])r'\"\n      using comp_splitL[OF comp[unfolded Nil ws_def(1)]] ws_def\n      by auto\n    have concat_map_fst_Nil: \"(\\<forall>x \\<in> set ws. fst x = []) \\<Longrightarrow> concat (map fst ws) = []\"\n      by auto\n    have one_step: \"case concat (map fst (wrr' # ws)) of [] \\<Rightarrow> cs' = []\n      | _ \\<Rightarrow> \\<exists>a \\<in> set (zip (t # ts) (wrr' # ws)).\n        case a of (t, w, r, r') \\<Rightarrow> \\<exists>t'. \\<delta> t (safe_hd w, safe_hd cs') = Some (t', True, False)\"\n      using ws_def(4)\n      by (auto simp: wrr'_def Nil dest: concat_map_fst_Nil split: list.splits)\n    show ?thesis\n      apply (rule exI[of _ cs])\n      apply (rule exI[of _ cs'])\n      using ws_def(1,2,3) t_def one_step\n      by (auto simp: wrr'_def Nil intro!: exI[of _ \"t # ts\"])\n  next\n    case (Cons a as)\n    obtain t t' ds ds' where split: \"u = ds @ ds'\" \"r\\<leadsto>(([], a # as), ds, ds')t\"\n      \"\\<delta> t (Symb a, safe_hd ds') = Some (t', True, False)\" \"t'\\<leadsto>((as, []), ds', [])r'\"\n      \"t\\<leadsto>((a # as, []), ds', [])r'\"\n      using split_outs[OF comp[unfolded Cons]]\n      by fastforce\n    show ?thesis\n    proof (cases \"length ds \\<le> length cs\")\n      case True\n      obtain cs'' where cs''_def: \"cs = ds @ cs''\"\n        using ws_def(1) split(1) True split_app[of ds ds' cs cs']\n        by auto\n      have ds'_def: \"ds' = cs'' @ cs'\"\n        using ws_def(1)[unfolded split(1) cs''_def]\n        by auto\n      have ts_ts': \"\\<And>t w r r'. (t, w, r, r') \\<in> set (zip ts ws) \\<Longrightarrow>\n        \\<exists>t''. r \\<leadsto>(([], w), (ds, ds')) t'' \\<and> t'' \\<leadsto>((w, []), (ds', [])) r'\"\n        using ws_def(3) shift_compL[of _ _ ds cs'' cs', folded cs''_def ds'_def]\n        by fastforce\n      obtain ts' where ts'_def: \"length ts' = length ts\"\n        \"\\<And>t w r r'. (t, w, r, r') \\<in> set (zip ts' ws) \\<Longrightarrow>\n          r \\<leadsto>(([], w), (ds, ds')) t \\<and> t \\<leadsto>((w, []), (ds', [])) r'\"\n        using set_zip_upd4[OF ws_def(2) ts_ts'] ws_def(2)\n        by fastforce\n      show ?thesis\n        apply (rule exI[of _ ds])\n        apply (rule exI[of _ ds'])\n        using split(1) ts'_def(1) ws_def(2) split(2,3,5) ts'_def(2)\n        by (auto simp: wrr'_def Cons safe_hd_Cons intro!: exI[of _ \"t # ts'\"])\n    next\n      case False\n      obtain ds'' where ds''_def: \"ds = cs @ ds''\"\n        using ws_def(1) split(1) False split_app[of cs cs' ds ds']\n        by auto\n      have cs'_def: \"cs' = ds'' @ ds'\"\n        using ws_def(1)[unfolded split(1) ds''_def]\n        by auto\n      obtain t' where t'_def: \"r \\<leadsto>(([], a # as), (cs, cs')) t'\"\n        \"t' \\<leadsto>((a # as, []), (cs', [])) r'\"\n        using shift_compL[OF split(2)[unfolded ds''_def] split(5)]\n        by (auto simp: cs'_def)\n      have concat_map_fst_Cons: \"concat (map fst ws) \\<noteq> []\"\n        using False cs'_def ds''_def ws_def(4)\n        by force\n      show ?thesis\n        apply (rule exI[of _ cs])\n        apply (rule exI[of _ cs'])\n        using ws_def t'_def concat_map_fst_Cons\n        by (fastforce simp: wrr'_def Cons intro!: exI[of _ \"t' # ts\"] split: list.splits)\n    qed\n  qed\nqed auto\n\nlemma first_reaches:\n  assumes \"q \\<leadsto>((us @ us', us''), (vs @ vs', vs'')) q'\" \"us \\<noteq> [] \\<or> vs \\<noteq> []\"\n  shows \"(\\<exists>ws ws' q''. vs = ws @ ws' \\<and> ws' \\<noteq> [] \\<and>\n      q \\<leadsto>((us, us' @ us''), (ws, ws' @ vs' @ vs'')) q'' \\<and>\n      q'' \\<leadsto>((us', us''), (ws' @ vs', vs'')) q') \\<or>\n    (\\<exists>ws ws' q''. us = ws @ ws' \\<and> ws' \\<noteq> [] \\<and>\n      q \\<leadsto>((ws, ws' @ us' @ us''), (vs, vs' @ vs'')) q'' \\<and>\n      q'' \\<leadsto>((ws' @ us', us''), (vs', vs'')) q')\"\n  using assms\nproof (induction \"length us + length vs\" arbitrary: q us vs rule: nat_less_induct)\n  case 1\n  then have IH: \"\\<And>uss vss q. q \\<leadsto>((uss @ us', us''), (vss @ vs', vs'')) q' \\<Longrightarrow>\n    (uss \\<noteq> [] \\<or> vss \\<noteq> []) \\<Longrightarrow> length uss + length vss < length us + length vs \\<Longrightarrow>\n    (\\<exists>ws ws' q''. vss = ws @ ws' \\<and> ws' \\<noteq> [] \\<and>\n      q \\<leadsto>((uss, us' @ us''), (ws, ws' @ vs' @ vs'')) q'' \\<and>\n      q'' \\<leadsto>((us', us''), (ws' @ vs', vs'')) q') \\<or>\n    (\\<exists>ws ws' q''. uss = ws @ ws' \\<and> ws' \\<noteq> [] \\<and>\n      q \\<leadsto>((ws, ws' @ us' @ us''), (vss, vs' @ vs'')) q'' \\<and>\n      q'' \\<leadsto>((ws' @ us', us''), (vs', vs'')) q')\"\n    by auto\n  show ?case\n  proof (cases us)\n    case Nil\n    show ?thesis\n      apply (rule disjI1)\n      apply (rule exI[of _ \"[]\"])\n      using 1(2,3)\n      by (auto simp: Nil)\n  next\n    case u_def: (Cons u uss')\n    show ?thesis\n    proof (cases vs)\n      case Nil\n      show ?thesis\n        apply (rule disjI2)\n        apply (rule exI[of _ \"[]\"])\n        using 1(2)\n        by (auto simp: u_def Nil)\n    next\n      case v_def: (Cons v vss')\n      have assm: \"uss' \\<noteq> [] \\<or> vs \\<noteq> []\" \"us \\<noteq> [] \\<or> vss' \\<noteq> []\"\n        by (auto simp: u_def v_def)\n      obtain qm where step:\n        \"(\\<delta> q (Symb u, Symb v) = Some (qm, True, False) \\<and>\n          qm \\<leadsto>((uss' @ us', us''), (vs @ vs', vs'')) q') \\<or>\n        (\\<delta> q (Symb u, Symb v) = Some (qm, False, True) \\<and>\n          qm \\<leadsto>((us @ us', us''), (vss' @ vs', vs'')) q')\"\n        using fst_step[OF 1(2)[unfolded u_def v_def, simplified]]\n        by (auto simp: u_def v_def)\n      then show ?thesis\n      proof (rule disjE)\n        assume \"\\<delta> q (Symb u, Symb v) = Some (qm, True, False) \\<and>\n          qm \\<leadsto>((uss' @ us', us''), (vs @ vs', vs'')) q'\"\n        then have lassms: \"\\<delta> q (Symb u, Symb v) = Some (qm, True, False)\"\n          \"qm \\<leadsto>((uss' @ us', us''), (vs @ vs', vs'')) q'\"\n          by auto\n        show \"(\\<exists>ws ws' q''. vs = ws @ ws' \\<and> ws' \\<noteq> [] \\<and>\n            q\\<leadsto>((us, us' @ us''), ws, ws' @ vs' @ vs'')q'' \\<and>\n            q''\\<leadsto>((us', us''), ws' @ vs', vs'')q') \\<or>\n          (\\<exists>ws ws' q''. us = ws @ ws' \\<and> ws' \\<noteq> [] \\<and>\n            q\\<leadsto>((ws, ws' @ us' @ us''), vs, vs' @ vs'')q'' \\<and>\n            q''\\<leadsto>((ws' @ us', us''), vs', vs'')q')\"\n          using IH[OF lassms(2) assm(1), unfolded u_def, simplified]\n          apply (rule disjE)\n          subgoal\n            apply (rule disjI1)\n            using lassms(1)\n            apply auto\n            subgoal for ws ws' q''\n              apply (rule exI[of _ ws])\n              apply (rule exI[of _ ws'])\n              apply (auto simp: u_def intro!: exI[of _ q''])\n              apply (rule step_TF)\n               apply (auto simp: v_def safe_hd_def split: list.splits)\n              apply (metis append_Cons append_assoc list.inject)\n              done\n            done\n          subgoal\n            apply (rule disjI2)\n            using lassms(1)\n            apply (auto simp: u_def)\n            subgoal for ws ws' q''\n              apply (rule exI[of _ \"u # ws\"])\n              apply (rule exI[of _ ws'])\n              apply (auto simp: u_def v_def safe_hd_def intro!: exI[of _ q''])\n              done\n            done\n          done\n      next\n        assume \"\\<delta> q (Symb u, Symb v) = Some (qm, False, True) \\<and>\n          qm\\<leadsto>((us @ us', us''), vss' @ vs', vs'')q'\"\n        then have lassms: \"\\<delta> q (Symb u, Symb v) = Some (qm, False, True)\"\n          \"qm\\<leadsto>((us @ us', us''), vss' @ vs', vs'')q'\"\n          by auto\n        show \"(\\<exists>ws ws' q''. vs = ws @ ws' \\<and> ws' \\<noteq> [] \\<and>\n            q\\<leadsto>((us, us' @ us''), ws, ws' @ vs' @ vs'')q'' \\<and>\n            q''\\<leadsto>((us', us''), ws' @ vs', vs'')q') \\<or>\n          (\\<exists>ws ws' q''. us = ws @ ws' \\<and> ws' \\<noteq> [] \\<and>\n            q\\<leadsto>((ws, ws' @ us' @ us''), vs, vs' @ vs'')q'' \\<and>\n            q''\\<leadsto>((ws' @ us', us''), vs', vs'')q')\"\n          using IH[OF lassms(2) assm(2), unfolded v_def, simplified]\n          apply (rule disjE)\n          subgoal\n            apply (rule disjI1)\n            using lassms(1)\n            apply auto\n            subgoal for ws ws' q''\n              apply (rule exI[of _ \"v # ws\"])\n              apply (rule exI[of _ ws'])\n              apply (auto simp: u_def v_def safe_hd_def intro!: exI[of _ q''])\n              done\n            done\n          subgoal\n            apply (rule disjI2)\n            using lassms(1)\n            apply (auto simp: u_def)\n            subgoal for ws ws' q''\n              apply (rule exI[of _ ws])\n              apply (rule exI[of _ ws'])\n              apply (auto simp: v_def intro!: exI[of _ q''])\n              apply (rule step_FT)\n               apply (auto simp: safe_hd_def split: list.splits)\n              apply (metis append_Cons append_assoc list.inject)\n              done\n            done\n          done\n      qed\n    qed\n  qed\nqed\n\nlemma comp_to_states:\n  assumes \"q \\<leadsto>(([], as'), (bs, bs')) q'\" \"q \\<in> Q\"\n  shows \"\\<exists>qs. length qs = Suc (length bs) \\<and> qs ! 0 = q \\<and>\n  (qs ! (length bs)) \\<leadsto>(([], as'), ([], bs')) q' \\<and> set qs \\<subseteq> Q \\<and>\n  (\\<forall>i < length bs. \\<delta> (qs ! i) (safe_hd as', Symb (bs ! i)) = Some (qs ! (Suc i), False, True))\"\n  using assms\nproof (induction bs arbitrary: q)\n  case Nil\n  then show ?case\n    by (auto intro: exI[of _ \"[q]\"])\nnext\n  case (Cons b bs'')\n  obtain q'' where q''_def: \"\\<delta> q (safe_hd as', Symb b) = Some (q'', False, True)\"\n    \"q'' \\<leadsto>(([], as'), (bs'', bs')) q'\"\n    using fst_stepL[OF Cons(2)]\n    by auto\n  note q''_Q = closed[OF Cons(3) q''_def(1)]\n  obtain qs where qs_def: \"length qs = Suc (length bs'')\"\n    \"qs ! 0 = q''\" \"(qs ! length bs'') \\<leadsto>(([], as'), ([], bs')) q'\" \"set qs \\<subseteq> Q\"\n    \"\\<And>i. i < length bs'' \\<Longrightarrow>\n      \\<delta> (qs ! i) (safe_hd as', Symb (bs'' ! i)) = Some (qs ! Suc i, False, True)\"\n    using Cons(1)[OF q''_def(2) q''_Q]\n    by auto\n  show ?case\n    apply (rule exI[of _ \"q # qs\"])\n    using qs_def q''_def(1) Cons(3)\n    apply auto\n    subgoal for i\n      by (cases i) auto\n    done\nqed\n\nlemma states_to_comp:\n  assumes \"length qs = Suc (length bs) \\<and> qs ! 0 = q \\<and> qs ! (length bs) = q' \\<and> (\\<forall>i < length bs.\n    \\<delta> (qs ! i) (safe_hd as', Symb (bs ! i)) = Some (qs ! (Suc i), False, True))\"\n  shows \"q \\<leadsto>(([], as'), (bs, bs')) q'\"\n  using assms\nproof (induction bs arbitrary: qs q' bs' rule: rev_induct)\n  case (snoc b bs'')\n  obtain qs'' q'' where split: \"qs = qs'' @ [q'']\" \"length qs'' = Suc (length bs'')\"\n    using snoc(2)\n    by (cases qs rule: rev_cases) auto\n  have \"q \\<leadsto>(([], as'), (bs'', b # bs')) (qs ! (length bs''))\"\n    using snoc(1)[of qs''] snoc(2)\n    by (auto simp: split nth_append split: if_splits)\n  moreover have \"\\<delta> (qs ! (length bs'')) (safe_hd as', Symb b) = Some (q', False, True)\"\n    using snoc(2)\n    by auto\n  ultimately show ?case\n    by (auto intro: step_FT_rev)\nqed auto\n\nlemma det_comp: \"q\\<leadsto>((u0, u @ u''), (v0 @ x, x'))r \\<Longrightarrow> q\\<leadsto>((u0 @ u, u''), v0 @ v, v')nr' \\<Longrightarrow>\n  \\<exists>w w' nr. v = w @ w' \\<and> q\\<leadsto>((u0, u @ u''), v0 @ w, w' @ v')nr \\<and> nr\\<leadsto>((u, u''), (w', v'))nr'\"\nproof (induction q \"((u0, u @ u''), (v0 @ x, x'))\" r arbitrary: u0 v0 rule: computation.induct)\n  case (step_TT q a b q' as bs q'')\n  then show ?case\n    using move_one\n    by fastforce\nnext\n  case (step_TF q a q' as q'')\n  show ?case\n  proof (cases v0)\n    case Nil\n    show ?thesis\n      using comp_split[OF step_TF(4)]\n      by (auto simp: Nil)\n  next\n    case (Cons b v0')\n    have step: \"\\<delta> q (Symb a, safe_hd ((v0 @ v) @ v')) = Some (q', True, False)\"\n      using step_TF(1)\n      by (auto simp: Cons safe_hd_Cons)\n    have det_comp: \"q'\\<leadsto>((as @ u, u''), v0 @ v, v')nr'\"\n      apply (rule computation.cases[OF step_TF(4)])\n      using step\n      by (auto simp: safe_hd_Cons)\n    show ?thesis\n      using step_TF(3)[OF det_comp] step\n      by (fastforce simp: Cons)\n  qed\nnext\n  case (step_FT q a b q' v0' r')\n  show ?case\n  proof (cases v0)\n    case Nil\n    show ?thesis\n      using comp_split[OF step_FT(5)]\n      by (auto simp: Nil)\n  next\n    case (Cons b' v0'')\n    have v0'_def: \"v0' = v0'' @ x\"\n      using step_FT(4)\n      by (auto simp: Cons)\n    have step: \"\\<delta> q (safe_hd (a @ u @ u''), Symb b') = Some (q', False, True)\"\n      using step_FT(1,4)\n      by (auto simp: Cons)\n    have det_comp: \"q'\\<leadsto>((a @ u, u''), v0'' @ v, v')nr'\"\n      apply (rule computation.cases[OF step_FT(5)])\n      using step move_one\n         apply (auto simp: Cons safe_hd_Cons)\n      apply (metis append.assoc option.inject prod.inject safe_hd_Cons_app)\n      done\n    show ?thesis\n      using step_FT(3)[OF v0'_def det_comp] step\n      by (auto simp: Cons)\n  qed\nqed auto\n\nlemma det_comp_safe: \"init\\<leadsto>((u0 @ u, u''), v0 @ v, v')nr' \\<Longrightarrow> init\\<leadsto>((u0, u'), (v0 @ x, x'))r \\<Longrightarrow>\n  safe_hd (u @ u'') = safe_hd u' \\<Longrightarrow>\n  \\<exists>w w' nr. v = w @ w' \\<and> init\\<leadsto>((u0, u @ u''), v0 @ w, w' @ v')nr \\<and> nr\\<leadsto>((u, u''), (w', v'))nr'\"\n  apply (rule det_comp)\n  apply (rule comp_swap_same_hd)\n    apply auto\n  done\n\nend\n\ntype_synonym 's otdfa_s = \"'s + 's\"\n\ncontext TDFA\nbegin\n\ndefinition otdfa_init :: \"'s otdfa_s\" where\n  \"otdfa_init = Inl init\"\n\nfun otdfa_delta :: \"'s otdfa_s \\<Rightarrow> 'a Al \\<times> 'b Al \\<Rightarrow> ('s otdfa_s \\<times> bool \\<times> bool) option\" where\n  \"otdfa_delta (Inl q) (a, b) = (case \\<delta> q (a, b) of Some (q', b1, b2) \\<Rightarrow>\n    if b1 \\<and> b2 then Some (Inr q', True, False) else Some (Inl q', b1, b2)\n  | _ \\<Rightarrow> None)\"\n| \"otdfa_delta (Inr q) (a, Symb b) = Some (Inl q, False, True)\"\n| \"otdfa_delta (Inr q) (a, Blank) = None\"\n\nlemma otdfa_delta_Inr: \"otdfa_delta q z = Some (Inr q', b1, b2) \\<Longrightarrow>\n  \\<exists>q''. q = Inl q'' \\<and> \\<delta> q'' z = Some (q', True, True) \\<and> b1 \\<and> \\<not>b2\"\n  by (induction q z rule: otdfa_delta.induct) (auto split: option.splits if_splits)\n\ndefinition otdfa_accept :: \"'s otdfa_s \\<Rightarrow> bool\" where\n  \"otdfa_accept q = (case q of Inl q' \\<Rightarrow> accept q' | _ \\<Rightarrow> False)\"\n\ndefinition otdfa_Q :: \"'s otdfa_s set\" where\n  \"otdfa_Q = Inl ` Q \\<union> Inr ` Q\"\n\nlemma otdfa_finite_Q: \"finite otdfa_Q\"\n  using finite_Q\n  by (auto simp add: otdfa_Q_def)\n\nlemma otdfa_init_in_Q: \"otdfa_init \\<in> otdfa_Q\"\n  using init_in_Q\n  by (auto simp add: otdfa_init_def otdfa_Q_def)\n\nlemma otdfa_closed:\n  assumes \"otdfa_delta q z = Some (q', b1, b2)\" \"q \\<in> otdfa_Q\"\n  shows \"q' \\<in> otdfa_Q\"\n  using assms\n  by (induction q z rule: otdfa_delta.induct)\n     (auto simp: otdfa_Q_def split: option.splits prod.splits if_splits Al.splits dest: closed)\n\nlemma otdfa_move_left:\n  assumes \"otdfa_delta q (a, b) = Some (q', True, b2)\"\n  shows \"a \\<noteq> Blank\"\n  using assms move_left\n  by (induction q \"(a, b)\" rule: otdfa_delta.induct)\n     (auto split: option.splits prod.splits if_splits Al.splits)\n\nlemma otdfa_move_right:\n  assumes \"otdfa_delta q (a, b) = Some (q', b1, True)\"\n  shows \"b \\<noteq> Blank\"\n  using assms move_right\n  by (induction q \"(a, b)\" rule: otdfa_delta.induct)\n     (auto split: option.splits prod.splits if_splits Al.splits)\n\nlemma otdfa_no_step:\n  assumes \"otdfa_delta q (a, b) = Some (q', False, False)\"\n  shows \"False\"\n  using assms no_step\n  by (induction q \"(a, b)\" rule: otdfa_delta.induct)\n     (auto split: option.splits prod.splits if_splits Al.splits)\n\nlemma otdfa_move_one:\n  assumes \"otdfa_delta q (a, b) = Some (q', True, True)\"\n  shows \"False\"\n  using assms\n  by (induction q \"(a, b)\" rule: otdfa_delta.induct)\n     (auto split: option.splits prod.splits if_splits Al.splits)\n\ninterpretation otdfa: oTDFA otdfa_init otdfa_delta otdfa_accept otdfa_Q\n  using otdfa_finite_Q otdfa_init_in_Q otdfa_closed[rotated]\n        otdfa_move_left otdfa_move_right otdfa_no_step otdfa_move_one\n  apply unfold_locales\n        apply auto[6]\n   apply fastforce+\n  done\n\nlemma tdfa_comp_otdfa:\n  assumes \"q \\<leadsto>((as, as'), (bs, bs')) q'\"\n  shows \"otdfa.computation (Inl q) ((as, as'), (bs, bs')) (Inl q')\"\n  using assms\nproof (induction q \"((as, as'), (bs, bs'))\" q' arbitrary: as as' bs bs' rule: computation.induct)\n  case (step_TT q a b q' as as' bs bs' q'')\n  show ?case\n    by (rule otdfa.computation.intros(3)[rotated, OF otdfa.computation.intros(4),\n        rotated, OF step_TT(3)])\n       (auto simp: safe_hd_def step_TT(1))\nqed auto\n\nlemma otdfa_comp_tdfa:\n  assumes \"otdfa.computation r ((as, as'), (bs, bs')) (Inl q')\"\n    \"r = Inl q \\<or> (r = Inr q'' \\<and> \\<delta> q (Symb a, safe_hd (bs @ bs')) = Some (q'', True, True))\"\n  shows \"q \\<leadsto>(if r = Inr q'' then (a # as, as') else (as, as'), (bs, bs')) q'\"\n  using assms\nproof (induction r \"((as, as'), (bs, bs'))\" \"Inl q' :: 's otdfa_s\" arbitrary: q as bs q' a q''\n  rule: otdfa.computation.induct)\n  case base\n  then show ?case\n    by auto\nnext\n  case (step_TT r x b r' as bs)\n  show ?case\n    using otdfa_move_one[OF step_TT(1)]\n    by auto\nnext\n  case (step_TF r x bs r' as)\n  show ?case\n  proof (cases r')\n    case (Inl r'')\n    show ?thesis\n      using step_TF\n      by (fastforce simp: safe_hd_def Inl split: option.splits if_splits list.splits)\n  next\n    case (Inr r'')\n    show ?thesis\n      using step_TF\n      by (auto simp: safe_hd_def Inr split: option.splits if_splits list.splits)\n  qed\nnext\n  case (step_FT r as b r' bs)\n  then show ?case\n    by (fastforce simp: safe_hd_def split: option.splits if_splits)\nqed\n\nlemma tdfa_otdfa_comp: \"q \\<leadsto>((as, as'), (bs, bs')) q' \\<longleftrightarrow>\n  otdfa.computation (Inl q) ((as, as'), (bs, bs')) (Inl q')\"\n  using tdfa_comp_otdfa otdfa_comp_tdfa[of \"Inl q\"]\n  by auto\n\nlemma tdfa_equiv_otdfa: \"\\<tau> = otdfa.\\<tau>\"\n  unfolding \\<tau>_def otdfa.\\<tau>_def\n  unfolding otdfa_init_def otdfa_accept_def tdfa_otdfa_comp\n  by auto (auto split: sum.splits)\n\nend\n\nlocale kTDFA = TDFA init \\<delta> accept Q\n  for init :: \"'s\"\n    and \\<delta> :: \"'s \\<Rightarrow> 'a Al \\<times> 'b Al \\<Rightarrow> ('s \\<times> bool \\<times> bool) option\"\n    and accept :: \"'s \\<Rightarrow> bool\"\n    and Q :: \"'s set\" +\n  fixes kv :: nat\n  assumes kval: \"finite {bs. (as, bs) \\<in> \\<tau>}\" \"card {bs. (as, bs) \\<in> \\<tau>} \\<le> kv\"\n\nlemma distinct_conv_nth': \"distinct xs = (\\<forall>i < size xs. \\<forall>j < size xs. i < j \\<longrightarrow> xs ! i \\<noteq> xs ! j)\"\n  by (auto simp: distinct_conv_nth) (metis nat_neq_iff)\n\nlemma length_concat_replicate:\n  \"length (concat (replicate n xs)) = n * length xs\"\n  by (induction n) auto\n\nlocale koTDFA = oTDFA init \\<delta> accept Q + kTDFA init \\<delta> accept Q kv\n  for init :: \"'s\"\n  and \\<delta> :: \"'s \\<Rightarrow> 'a Al \\<times> 'b Al \\<Rightarrow> ('s \\<times> bool \\<times> bool) option\"\n  and accept :: \"'s \\<Rightarrow> bool\"\n  and Q :: \"'s set\"\n  and kv :: nat\nbegin\n\nlemma loop:\n  assumes \"init \\<leadsto>((as, us), (bs, vs @ vs')) q\" \"q \\<leadsto>(([], us), (vs, vs')) q\"\n    \"q \\<leadsto>((us, []), (vs', [])) qf\" \"accept qf\" \"vs \\<noteq> []\"\n  shows \"False\"\nproof -\n  define C where \"C = {bs. (as @ us, bs) \\<in> \\<tau>}\"\n  have finite_C: \"finite C\"\n    using kval\n    by (auto simp: C_def)\n  have comp: \"\\<And>n. q \\<leadsto>(([], us), (concat (replicate n vs), vs')) q\"\n    subgoal for n\n    proof (induction n)\n      case (Suc n)\n      show ?case\n        using comp_transR[OF assms(2) Suc] assms(2)\n        by fastforce\n    qed auto\n    done\n  have safe_hd_concat: \"\\<And>n. n \\<noteq> 0 \\<Longrightarrow>\n    safe_hd (vs @ vs') = safe_hd (concat (replicate n vs) @ vs')\"\n    using assms(5)\n    apply (cases vs)\n     apply (auto simp: safe_hd_def split: list.splits)\n    apply (smt Suc_pred append_Cons concat.simps(2) list.inject replicate_Suc)\n    done\n  have \"\\<And>n. n \\<noteq> 0 \\<Longrightarrow> init \\<leadsto>((as @ us, []), bs @ concat (replicate n vs) @ vs', []) qf\"\n    using comp_trans[OF comp_trans[OF assms(1) comp, OF _ safe_hd_concat] assms(3)] assms(5)\n    by fastforce\n  then have in_C: \"\\<And>n. n \\<noteq> 0 \\<Longrightarrow> bs @ concat (replicate n vs) @ vs' \\<in> C\"\n    using assms(4,5)\n    by (auto simp: \\<tau>_def C_def)\n  define f where \"f = (\\<lambda>n. bs @ concat (replicate n vs) @ vs')\"\n  have inj: \"inj f\"\n    apply (auto simp: inj_def f_def)\n    apply (drule arg_cong[of _ _ length])\n    using assms(5)\n    by (auto simp: length_concat_replicate)\n  have \"Suc kv = card (f ` {Suc 0..<Suc (Suc kv)})\"\n    using card_vimage_inj[OF inj, of \"f ` {1..<Suc (Suc kv)}\"] inj\n    by (auto simp: inj_vimage_image_eq[OF inj])\n  moreover have \"\\<dots> \\<le> card C\"\n    apply (rule card_mono[OF finite_C])\n    using in_C\n    by (auto simp: f_def)\n  finally show False\n    using kval(2)[of \"as @ us\", folded C_def]\n    by auto\nqed\n\nlemma state_bounded:\n  assumes \"init \\<leadsto>((as, us), (bs, vs @ vs')) q\" \"q \\<leadsto>(([], us), (vs, vs')) q'\"\n    \"q' \\<leadsto>((us, []), (vs', [])) qf\" \"accept qf\"\n  shows \"length vs \\<le> card Q\"\nproof (rule ccontr)\n  assume \"\\<not>length vs \\<le> card Q\"\n  then have len_vs: \"length vs \\<ge> Suc (card Q)\"\n    by auto\n  then have vs_not_Nil: \"vs \\<noteq> []\"\n    by (cases vs) auto\n  note q_Q = comp_closed[OF assms(1) init_in_Q]\n  obtain qs where qs_def: \"length qs = Suc (length vs)\"\n    \"qs ! 0 = q\" \"(qs ! length vs) \\<leadsto>(([], us), ([], vs')) q'\" \"set qs \\<subseteq> Q\"\n    \"\\<And>i. i < length vs \\<Longrightarrow> \\<delta> (qs ! i) (safe_hd us, Symb (vs ! i)) = Some (qs ! Suc i, False, True)\"\n    using comp_to_states[OF assms(2) q_Q]\n    by auto\n  obtain qs'' q'' where qs_split: \"qs = qs'' @ [q'']\"\n    using qs_def(1)\n    by (cases qs rule: rev_cases) auto\n  have set_qs'': \"set qs'' \\<subseteq> Q\"\n    using qs_def(4)\n    by (auto simp: qs_split)\n  note card_set_qs = card_mono[OF finite_Q set_qs'']\n  have \"length qs'' \\<ge> Suc (card (set qs''))\"\n    using card_set_qs len_vs qs_def(1)\n    by (auto simp: qs_split)\n  then obtain i j where \"i < j\" \"j < length qs''\" \"qs'' ! i = qs'' ! j\"\n    using distinct_card[of qs'']\n    by (auto simp: distinct_conv_nth')\n  then have ij_def: \"i < j\" \"Suc j < length qs\" \"qs ! i = qs ! j\"\n    by (auto simp: qs_def(1) qs_split nth_append)\n  have take_drop_i: \"take i vs @ drop i vs = vs\"\n    \"take (j - i) (drop i vs) @ drop j vs = drop i vs\"\n    using ij_def\n    by (auto simp: qs_def(1))\n       (smt append.assoc append_take_drop_id le_add_diff_inverse less_imp_le_nat same_append_eq\n        take_add)\n  define r where \"r = qs ! i\"\n  have min_vs_i_j_i: \"min (length vs - i) (j - i) = j - i\"\n    using ij_def\n    by (auto simp: min_def qs_def(1))\n  have comp_q_r: \"q \\<leadsto>(([], us), (take i vs, drop i vs @ vs')) r\"\n    apply (rule states_to_comp[of \"take (Suc i) qs\"])\n    using ij_def qs_def(5)\n    by (auto simp: qs_def(1,2) r_def) linarith\n  then have comp_init_r: \"init \\<leadsto>((as, us), bs @ take i vs, drop i vs @ vs') r\"\n    using comp_trans[OF assms(1) comp_q_r]\n    by (auto simp: take_drop_i append.assoc[symmetric])\n  have comp_r_r: \"r \\<leadsto>(([], us), (take (j - i) (drop i vs), drop j vs @ vs')) r\"\n    apply (rule states_to_comp[of \"take (Suc (j - i)) (drop i qs)\"])\n    using ij_def qs_def(5)\n    by (auto simp: r_def qs_def(1) min_vs_i_j_i)\n  have comp_r_q': \"r \\<leadsto>(([], us), (drop j vs, vs')) q'\"\n    apply (rule comp_trans[OF states_to_comp[of \"drop j qs\"] qs_def(3), simplified])\n    using ij_def qs_def(5)\n    by (auto simp: r_def qs_def(1))\n  have comp_r_qf: \"r \\<leadsto>((us, []), drop j vs @ vs', []) qf\"\n    using comp_trans[OF comp_r_q' assms(3)]\n    by auto\n  have \"drop j vs @ vs' \\<noteq> []\"\n    using ij_def\n    by (auto simp: qs_def(1))\n  then show \"False\"\n    using loop[OF _ comp_r_r comp_r_qf assms(4)] comp_init_r ij_def\n    by (auto simp: append.assoc[symmetric] take_drop_i qs_def(1))\nqed\n\nlemma lin_bounded: \"init \\<leadsto>((as, us), (bs, vs)) q \\<Longrightarrow> q \\<leadsto>((us, []), (vs, [])) qf \\<Longrightarrow>\n  accept qf \\<Longrightarrow> length vs \\<le> (length us + 1) * card Q\"\nproof (induction us arbitrary: as bs vs q)\n  case Nil\n  then show ?case\n    using state_bounded[OF _ _ base]\n    by auto\nnext\n  case (Cons u us')\n  obtain r r' cs cs' where split: \"vs = cs @ cs'\" \"q\\<leadsto>(([], u # us' @ []), cs, cs' @ [])r\"\n    \"\\<delta> r (Symb u, safe_hd (cs' @ [])) = Some (r', True, False)\" \"r'\\<leadsto>((us', []), cs', [])qf\"\n    using split_outs[OF Cons(3)]\n    by auto\n  have split': \"q\\<leadsto>(([], u # us'), cs, cs')r\"\n    using split(2)\n    by (cases cs) auto\n  have init_ext: \"init\\<leadsto>((as @ [u], us'), bs @ cs, cs')r'\"\n    using comp_trans[OF Cons(2) split'] split(2,3)\n    by (auto simp: split(1) safe_hd_def intro: step_TF_rev split: list.splits)\n  have comp_r_qf: \"r\\<leadsto>((u # us', []), cs', [])qf\"\n    using comp_trans[OF _ split(4) _ refl, of r \"[u]\" us' \"[]\"]\n      step_TF[OF _ base, simplified, OF split(3)[simplified]]\n    by auto\n  show ?case\n    using state_bounded[OF Cons(2)[unfolded split(1)] split' comp_r_qf Cons(4)]\n      Cons(1)[OF init_ext split(4) Cons(4)]\n    by (fastforce simp: split(1))\nqed\n\nend\n\nfun lcp :: \"'a list \\<Rightarrow> 'a list \\<Rightarrow> nat\" where\n  \"lcp [] _ = 0\"\n| \"lcp _ [] = 0\"\n| \"lcp (a # as) (b # bs) = (if a = b then Suc (lcp as bs) else 0)\"\n\ndefinition lcp_dist :: \"'a list \\<Rightarrow> 'a list \\<Rightarrow> nat\" where\n  \"lcp_dist as bs = length as + length bs - 2 * lcp as bs\"\n\nlemma lcp_le_min: \"lcp v1 v2 \\<le> min (length v1) (length v2)\"\n  by (induction v1 v2 rule: lcp.induct) auto\n\nlemma lcp_zero: \"lcp v1 v2 \\<ge> 0\"\n  by auto\n\nlemma lcp_app_le_max: \"lcp (v1 @ w1) (v2 @ w2) \\<le> lcp v1 v2 + max (length w1) (length w2)\"\nproof (induction v1 v2 rule: lcp.induct)\n  case (1 v2)\n  show ?case\n    using lcp_le_min trans_le_add1 max.coboundedI1\n    by fastforce\nnext\n  case (2 v v1)\n  show ?case\n    using lcp_le_min trans_le_add2 max.coboundedI2\n    by fastforce\nqed auto\n\nlemma lcp_le_sum: \"lcp v1 v2 \\<le> length v1 + length v2\"\n  using lcp_le_min trans_le_add1\n  by fastforce\n\nlemma lcp_le_app: \"lcp v1 v2 \\<le> lcp (v1 @ w1) (v2 @ w2)\"\n  by (induction v1 v2 rule: lcp.induct) auto\n\n\n\nlemma lcp_dist_app_le_sum: \"lcp_dist (v1 @ w1) (v2 @ w2) \\<le> lcp_dist v1 v2 + length w1 + length w2\"\n  using lcp_le_app[of v1 v2 w1 w2]\n  by (auto simp: lcp_dist_def)\n\nlemma lcp_app_le_max_diff: \"2 * lcp (v1 @ w1) (v2 @ w2) \\<le>\n  2 * lcp v1 v2 + length w1 + length w2 +\n  max (length w1 - length w2) (length w2 - length w1)\"\n  using lcp_app_le_max[of v1 w1 v2 w2] lcp_app_le_max[of v2 w2 v1 w1]\n  by auto\n\nlemma lcp_dist_le_app_sum: \"lcp_dist v1 v2 \\<le>\n  lcp_dist (v1 @ w1) (v2 @ w2) +\n  max (length w1 - length w2) (length w2 - length w1)\"\n  using lcp_app_le_max_diff[of v1 w1 v2 w2]\n  by (auto simp: lcp_dist_def)\n\nlemma lcp_dist_same_pref: \"lcp_dist (u @ v1) (u @ v2) = lcp_dist v1 v2\"\n  unfolding lcp_dist_def\n  by (induction u) auto\n\n(* Definition 2 *)\n\nlocale NFT =\n  fixes init :: \"'s\"\n    and \\<delta> :: \"'s \\<Rightarrow> 'a :: finite \\<Rightarrow> 's \\<times> 'b list \\<Rightarrow> bool\"\n    and accept :: \"'s \\<Rightarrow> bool\"\n    and Q :: \"'s set\"\n  assumes finite_Q: \"finite Q\"\n  and finite_\\<delta>: \"q \\<in> Q \\<Longrightarrow> finite {x. \\<delta> q a x}\"\n  and init_in_Q: \"init \\<in> Q\"\n  and \\<delta>_closed: \"q \\<in> Q \\<Longrightarrow> \\<delta> q a (q', bs) \\<Longrightarrow> q' \\<in> Q\"\nbegin\n\ninductive computation :: \"'s \\<Rightarrow> 'a list \\<times> 'b list \\<Rightarrow> 's \\<Rightarrow> bool\" (\"_/\\<leadsto>_/_\" [64,64,64]63) where\n  base[intro]: \"q \\<leadsto>([], []) q\"\n| step[intro]: \"\\<delta> q a (q', bs) \\<Longrightarrow> q' \\<leadsto>(as, bs') q'' \\<Longrightarrow> q \\<leadsto>(a # as, bs @ bs') q''\"\n\ndefinition \\<tau> :: \"('a list \\<times> 'b list) set\" where\n  \"\\<tau> = {(as, bs). \\<exists>q. init \\<leadsto>(as, bs) q \\<and> accept q}\"\n\n(* Definition 6 *)\n\ndefinition \"bv k t \\<longleftrightarrow> (\\<forall>f1 f2 q1 q2 a b1 b2 u v1 v2 w1 w2.\n  accept f1 \\<and> accept f2 \\<and> q1 \\<in> Q \\<and> q2 \\<in> Q \\<and>\n  init \\<leadsto>(a, u @ v1) q1 \\<and> q1 \\<leadsto>(b1, w1) f1 \\<and>\n  init \\<leadsto>(a, u @ v2) q2 \\<and> q2 \\<leadsto>(b2, w2) f2 \\<and>\n  length b1 + length b2 \\<le> k \\<longrightarrow> lcp_dist (v1 @ w1) (v2 @ w2) \\<le> t)\"\n\n(* Definition 8 *)\n\ndefinition active :: \"'s \\<Rightarrow> 'b list \\<Rightarrow> bool\" where\n  \"active q bs \\<longleftrightarrow> (\\<exists>q' as bs'. q \\<leadsto>(as, bs @ bs') q' \\<and> accept q')\"\n\ndefinition \"bounded K \\<equiv> \\<forall>q q' u v v'. init \\<leadsto>(u, v @ v') q \\<and> active q [] \\<and>\n  init \\<leadsto>(u, v) q' \\<and> active q' v' \\<longrightarrow> length v' \\<le> K\"\n\nlemma no_step: \"q \\<leadsto>(as, bs) q' \\<Longrightarrow> as = [] \\<Longrightarrow> bs = [] \\<and> q = q'\"\n  by (induction q \"(as, bs)\" q' rule: computation.induct) auto\n\nlemma one_step: \"\\<delta> q a (q', bs) \\<Longrightarrow> q \\<leadsto>([a], bs) q'\"\n  using computation.step by fastforce\n\nlemma step_dest: \"q \\<leadsto>([a], bs) q' \\<Longrightarrow> \\<delta> q a (q', bs)\"\n  apply (induction q \"([a], bs)\" q' rule: computation.induct)\n  using computation.cases by fastforce\n\nlemma comp_trans: \"q \\<leadsto>(as, bs) q' \\<Longrightarrow> q' \\<leadsto>(as', bs') q'' \\<Longrightarrow> q \\<leadsto>(as @ as', bs @ bs') q''\"\n  by (induction q \"(as, bs)\" q' arbitrary: as bs rule: computation.induct) auto\n\nlemma computation_snoc: \"q \\<leadsto>(as, bs) q' \\<Longrightarrow> \\<delta> q' a (q'', bs') \\<Longrightarrow> q \\<leadsto>(as @ [a], bs @ bs') q''\"\nproof -\n  assume assms: \"q \\<leadsto>(as, bs) q'\" \"\\<delta> q' a (q'', bs')\"\n  from assms(2) have \"q' \\<leadsto>([a], bs') q''\"\n    using step by fastforce\n  with assms(1) show \"q \\<leadsto>(as @ [a], bs @ bs') q''\"\n    using comp_trans by auto\nqed\n\nlemma computation_split: \"q \\<leadsto>(as @ as', bs'') q' \\<Longrightarrow>\n  \\<exists>q'' bs bs'. q \\<leadsto>(as, bs) q'' \\<and> q'' \\<leadsto>(as', bs') q' \\<and> bs'' = bs @ bs'\"\nproof (induction q \"(as @ as', bs'')\" q' arbitrary: as as' bs'' rule: computation.induct)\n  case (step q' bs q a asa bs' q'')\n  then show ?case\n  proof (cases as)\n    case (Cons x xs)\n    then show ?thesis\n      using step(1,2,4) step(3)[of xs as']\n      by force\n  qed auto\nqed auto\n\nlemma comp_rev_induct: \"q\\<leadsto>(as, bs) q' \\<Longrightarrow>\n  (\\<And>q. P q [] [] q) \\<Longrightarrow>\n  (\\<And>q a q' bs as bs' q''. P q as bs q'' \\<Longrightarrow> q\\<leadsto>(as, bs)q'' \\<Longrightarrow> \\<delta> q'' a (q', bs') \\<Longrightarrow>\n    P q (as @ [a]) (bs @ bs') q') \\<Longrightarrow>\n  P q as bs q'\"\nproof (induction as arbitrary: q bs q' rule: rev_induct)\n  case Nil\n  then show ?case\n    using no_step\n    by fastforce\nnext\n  case (snoc x xs)\n  obtain q'' cs cs' where split: \"q \\<leadsto>(xs, cs) q''\" \"q'' \\<leadsto>([x], cs') q'\" \"bs = cs @ cs'\"\n    using computation_split[OF snoc(2)] by auto\n  have P_xs: \"P q xs cs q''\"\n    using snoc(1)[OF split(1) snoc(3,4)] by auto\n  show ?case\n    using snoc(4)[OF P_xs split(1) step_dest[OF split(2)]]\n    by (auto simp add: split(3))\nqed\n\nlemma comp_closed: \"q \\<leadsto>(as, bs) q' \\<Longrightarrow> q \\<in> Q \\<Longrightarrow> q' \\<in> Q\"\n  by (induction q \"(as, bs)\" q' arbitrary: as bs rule: computation.induct)\n     (auto simp add: \\<delta>_closed)\n\ninductive computation_ext :: \"'s \\<Rightarrow> 'a list \\<times> ('s \\<times> 'b list) list \\<Rightarrow> 's \\<Rightarrow> bool\"\n    (\"_/\\<leadsto>e_/_\" [64,64,64]63) where\n  base_ext[intro]: \"q \\<leadsto>e([], []) q\"\n| step_ext[intro]: \"\\<delta> q a (q', bs) \\<Longrightarrow> q' \\<leadsto>e(as, qs) q'' \\<Longrightarrow> q \\<leadsto>e(a # as, (q', bs) # qs) q''\"\n\nlemma computation_ext_no_step: \"q \\<leadsto>e([], []) q' \\<Longrightarrow> q = q'\"\n  by (auto elim: computation_ext.cases)\n\nlemma computation_ext_Cons_dest: \"q\\<leadsto>e(a # as', qb # qbs')q' \\<Longrightarrow> \\<delta> q a qb\"\n  by (auto elim: computation_ext.cases)\n\nlemma computation_ext_trans: \"q \\<leadsto>e(as, qs) q' \\<Longrightarrow> q' \\<leadsto>e(as', qs') q'' \\<Longrightarrow>\n  q \\<leadsto>e(as @ as', qs @ qs') q''\"\n  by (induction q \"(as, qs)\" q' arbitrary: as qs rule: computation_ext.induct) auto\n\nlemma computation_ext_length: \"q \\<leadsto>e(as, qs) q' \\<Longrightarrow> length qs = length as\"\n  by (induction q \"(as, qs)\" q' arbitrary: as qs rule: computation_ext.induct) auto\n\nlemma computation_ext_sound: \"q \\<leadsto>e(as, qs) q' \\<Longrightarrow> q \\<leadsto>(as, concat (map snd qs)) q'\"\n  by (induction q \"(as, qs)\" q' arbitrary: as qs rule: computation_ext.induct) auto\n\nlemma computation_ext_complete: \"q \\<leadsto>(as, bs) q' \\<Longrightarrow>\n  \\<exists>qs. q \\<leadsto>e(as, qs) q' \\<and> bs = concat (map snd qs)\"\n  by (induction q \"(as, bs)\" q' arbitrary: as bs rule: computation.induct) auto\n\nlemma computation_ext_split: \"length as = length qbs \\<Longrightarrow>\n  q \\<leadsto>e(as @ a # as', qbs @ (q'', bs) # qbs') q' \\<Longrightarrow>\n  q \\<leadsto>e(as @ [a], qbs @ [(q'', bs)]) q'' \\<and> q'' \\<leadsto>e(as', qbs') q'\"\n  by (induction as qbs arbitrary: q rule: list_induct2) (auto elim: computation_ext.cases)\n\nlemma computation_ext_closed: \"q \\<leadsto>e(as, qs) q' \\<Longrightarrow> q \\<in> Q \\<Longrightarrow> (r, bs) \\<in> set qs \\<Longrightarrow> r \\<in> Q\"\n  by (induction q \"(as, qs)\" q' arbitrary: as qs rule: computation_ext.induct)\n     (auto simp add: \\<delta>_closed)\n\ndefinition all_trans :: \"('s \\<times> 'b list) set\" where\n  \"all_trans = {x. \\<exists>(q, a) \\<in> (Q \\<times> (UNIV :: 'a set)). \\<delta> q a x}\"\n\nlemma all_trans_finite: \"finite all_trans\"\nproof -\n  have fin_Q_UNIV: \"finite (Q \\<times> (UNIV :: 'a set))\"\n    using finite_Q by auto\n  have \"all_trans \\<subseteq> \\<Union>((\\<lambda>(q, a). {x. \\<delta> q a x}) ` (Q \\<times> (UNIV :: 'a set)))\"\n    unfolding all_trans_def by auto\n  moreover have \"finite (\\<Union>((\\<lambda>(q, a). {x. \\<delta> q a x}) ` (Q \\<times> (UNIV :: 'a set))))\"\n    using fin_Q_UNIV finite_\\<delta> by auto\n  ultimately show ?thesis\n    using infinite_super by blast\nqed\n\nlemma all_trans_step: \"q \\<in> Q \\<Longrightarrow> \\<delta> q a x \\<Longrightarrow> x \\<in> all_trans\"\n  unfolding all_trans_def by auto\n\n(* Definition 5 *)\n\ndefinition output_speed :: nat where\n  \"output_speed = Max (length ` snd ` all_trans \\<union> {1})\"\n\nlemma output_speed_step: \"q \\<in> Q \\<Longrightarrow> \\<delta> q a (q', bs) \\<Longrightarrow> length bs \\<le> output_speed\"\n  unfolding output_speed_def using all_trans_finite all_trans_step\n  by (metis Max_ge UnCI finite.emptyI finite.insertI finite_UnI finite_imageI image_eqI snd_conv)\n\nlemma output_speed_computation: \"q \\<leadsto>(as, bs) q' \\<Longrightarrow> q \\<in> Q \\<Longrightarrow>\n  length bs \\<le> length as * output_speed\"\n  apply (induction q \"(as, bs)\" q' arbitrary: as bs rule: computation.induct)\n  using output_speed_step \\<delta>_closed by (auto simp add: add_le_mono)\n\nlemma output_speed_ext_computation: \"q \\<leadsto>e(as, qbs) q' \\<Longrightarrow> q \\<in> Q \\<Longrightarrow> (q'', bs) \\<in> set qbs \\<Longrightarrow>\n  length bs \\<le> output_speed\"\n  apply (induction q \"(as, qbs)\" q' arbitrary: as qbs rule: computation_ext.induct)\n  using output_speed_step \\<delta>_closed by auto\n\nlemma output_speed_pos: \"output_speed \\<ge> 1\"\nproof -\n  have fin: \"finite (length ` snd ` all_trans \\<union> {1})\"\n    using all_trans_finite\n    by auto\n  show ?thesis\n    using Max_ge[OF fin, of 1]\n    by (auto simp add: output_speed_def)\nqed\n\nlemma computation_split_out: \"q \\<leadsto>(as'', bs @ bs') q' \\<Longrightarrow> q \\<in> Q \\<Longrightarrow>\n  \\<exists>q'' as as' cs cs'. q \\<leadsto>(as, cs) q'' \\<and> q'' \\<leadsto>(as', cs') q' \\<and> as'' = as @ as' \\<and>\n    bs @ bs' = cs @ cs' \\<and> length cs \\<le> length bs \\<and> length bs - length cs \\<le> output_speed\"\nproof (induction q \"(as'', bs @ bs')\" q' arbitrary: as'' bs bs' rule: computation.induct)\n  case (step q a q' bsa as bsa' q'')\n  from step(1,5) have length_bsa: \"length bsa \\<le> output_speed\"\n    using output_speed_step by auto\n  show ?case\n  proof (cases \"length bsa \\<le> length bs\")\n    case True\n    with step(4) obtain bsa'' where \"bs = bsa @ bsa''\"\n      by (metis append_eq_append_conv_if append_eq_conv_conj)\n    then show ?thesis\n      using step(1,2,4,5) step(3)[of bsa'' bs'] \\<delta>_closed by fastforce\n  next\n    case False\n    with step length_bsa have \"q\\<leadsto>([], [])q \\<and> q\\<leadsto>(a # as, bsa @ bsa')q'' \\<and> a # as = [] @ (a # as) \\<and>\n      bs @ bs' = [] @ (bsa @ bsa') \\<and> length [] \\<le> length bs \\<and> length bs - length [] \\<le> output_speed\"\n      using computation.step by fastforce\n    then show ?thesis\n      by blast\n  qed\nqed auto\n\nlemma computation_ext_rem:\n  assumes \"q \\<leadsto>e(as, qbs' @ (q', bs) # qbs'' @ (q', bs') # qbs''') q''\"\n  shows \"\\<exists>cs' cs'' cs''' c' c'' ds' bs'''.\n    q \\<leadsto>(cs' @ c' # cs''', ds' @ bs @ bs''') q'' \\<and>\n    ds' = concat (map snd qbs') \\<and> bs''' = concat (map snd qbs''') \\<and>\n    as = cs' @ c' # cs'' @ c'' # cs''' \\<and> length cs' = length qbs' \\<and>\n    length cs'' = length qbs'' \\<and> length cs''' = length qbs'''\"\nproof -\n  note len_as = computation_ext_length[OF assms(1), symmetric]\n  obtain as' as'' as''' a a' where\n    decomp': \"as = as' @ [a] @ as'' @ [a'] @ as'''\" \"length as' = length qbs'\"\n    \"length as'' = length qbs''\" \"length as''' = length qbs'''\"\n    using app_decomp[OF len_as]\n    by (auto dest!: app_decomp[of _ \"[(q', bs)]\" \"qbs'' @ [(q', bs')] @ qbs'''\", simplified]\n        app_decomp[of _ qbs'' \"[(q', bs')] @ qbs'''\", simplified]\n        app_decomp[of _ \"[(q', bs')]\" \"qbs'''\", simplified]\n        singleton_dest)\n  have assoc: \"q \\<leadsto>e(as' @ a # as'' @ [a'] @ as''',\n    qbs' @ (q', bs) # qbs'' @ [(q', bs')] @ qbs''') q''\"\n    using assms(1)[unfolded decomp']\n    by auto\n  have split: \"q \\<leadsto>e(as' @ [a], qbs' @ [(q', bs)]) q'\" \"q'\\<leadsto>e(as'' @ a' # as''',\n    qbs'' @ (q', bs') # qbs''') q''\"\n    using computation_ext_split[OF decomp'(2) assoc]\n    by auto\n  have split': \"q' \\<leadsto>e(as''', qbs''') q''\"\n    using computation_ext_split[OF decomp'(3) split(2)]\n    by auto\n  define ds' where \"ds' = concat (map snd qbs')\"\n  define bs''' where \"bs''' = concat (map snd qbs''')\"\n  have trans: \"q \\<leadsto>(as' @ [a], ds' @ bs) q'\"\n    using computation_ext_sound[OF split(1)]\n    by (auto simp add: ds'_def)\n  have trans': \"q' \\<leadsto>(as''', bs''') q''\"\n    using computation_ext_sound[OF split']\n    by (auto simp add: bs'''_def)\n  show ?thesis\n    using comp_trans[OF trans trans'] decomp'(2,3,4)\n    by (fastforce simp add: ds'_def bs'''_def decomp'(1))\nqed\n\nlemma computation_long_split: \"q \\<leadsto>(as, bs) q' \\<Longrightarrow> q \\<in> Q \\<Longrightarrow> length as \\<ge> 1 + card Q \\<Longrightarrow>\n  \\<exists>as' bs'. q \\<leadsto>(as', bs') q' \\<and> length as' < length as\"\nproof -\n  assume assms_comp: \"q \\<leadsto>(as, bs) q'\" \"q \\<in> Q\"\n  obtain qbs where qbs_def: \"q \\<leadsto>e(as, qbs) q'\" \"bs = concat (map snd qbs)\"\n    using computation_ext_complete[OF assms_comp(1)]\n    by auto\n  then have qbs_len: \"length qbs = length as\"\n    using computation_ext_length by auto\n  assume assms_len: \"length as \\<ge> 1 + card Q\"\n  define qs where \"qs = map fst qbs\"\n  have qs_sub: \"set qs \\<subseteq> Q\"\n    using computation_ext_closed[OF qbs_def(1) assms_comp(2)]\n    by (auto simp add: qs_def)\n  have not_distinct: \"\\<not>distinct qs\"\n  proof (rule ccontr)\n    assume \"\\<not>\\<not>distinct qs\"\n    then have contr: \"distinct qs\"\n      by auto\n    have card_qs: \"card (set qs) \\<ge> 1 + card Q\"\n      using distinct_card[OF contr] assms_len\n      by (auto simp add: qs_def qbs_len)\n    show \"False\"\n      using card_qs card_mono[OF finite_Q qs_sub]\n      by auto\n  qed\n  obtain q'' qs' qs'' qs''' where \"qs = qs' @ [q''] @ qs'' @ [q''] @ qs'''\"\n    using not_distinct_decomp[OF not_distinct]\n    by auto\n  then obtain qbs' qbs'' qbs''' bs bs' where\n    decomp: \"qbs = qbs' @ (q'', bs) # qbs'' @ (q'', bs') # qbs'''\"\n    using map_ext[of fst qbs qs' \"[q''] @ qs'' @ [q''] @ qs'''\"]\n          map_ext[of fst _ \"qs''\" \"[q''] @ qs'''\"]\n    by (fastforce simp add: qs_def)\n  show \"\\<exists>as' bs'. q \\<leadsto>(as', bs') q' \\<and> length as' < length as\"\n    using computation_ext_rem[OF qbs_def(1)[unfolded decomp(1)]]\n    by auto\nqed\n\nlemma comp_norm: \"q \\<leadsto>(as, bs) q' \\<Longrightarrow> q \\<in> Q \\<Longrightarrow> \\<exists>as' bs'. q \\<leadsto>(as', bs') q' \\<and> length as' \\<le> card Q\"\nproof (induction \"length as\" arbitrary: as bs rule: nat_less_induct)\n  case 1\n  then show ?case\n  proof (cases \"length as \\<le> card Q\")\n    case False\n    obtain as' bs' where nex: \"q \\<leadsto>(as', bs') q'\" \"length as' < length as\"\n      using computation_long_split[OF 1(2,3)] False\n      by auto\n    then show ?thesis\n      using 1(1,3)\n      by auto\n  qed auto\nqed\n\nlemma pumping: \"q \\<leadsto>(as, bs) q \\<Longrightarrow> q \\<leadsto>(iter_concat n as, iter_concat n bs) q\"\n  by (induction n) (auto intro: comp_trans)\n\nlemma active_comp: \"active q' bs \\<Longrightarrow> q \\<leadsto>(as, bs') q' \\<Longrightarrow> active q (bs' @ bs)\"\n  using comp_trans\n  by (fastforce simp add: active_def)\n\nlemma active_mono: \"active q (bs @ bs') \\<Longrightarrow> active q bs\"\n  unfolding active_def by auto\n\nlemma active_extend: \"q \\<leadsto>(as, bs @ bs') q' \\<Longrightarrow> active q' bs \\<Longrightarrow> active q bs\"\n  unfolding active_def using comp_trans by force\n\nlemma active_Nil_dest: \"active q [] \\<Longrightarrow> q \\<in> Q \\<Longrightarrow>\n  \\<exists>as bs' q'. q \\<leadsto>(as, bs') q' \\<and> accept q' \\<and> length as \\<le> card Q \\<and>\n    length bs' \\<le> card Q * output_speed\"\n  using comp_norm output_speed_computation\n  apply (auto simp add: active_def)\n  apply (meson dual_order.trans mult_le_mono1)\n  done\n\n(* Definition 4 *)\n\ndefinition sg :: nat where\n  \"sg = Max ((\\<lambda>q. Inf (length ` {as. \\<exists>bs q'. q \\<leadsto>(as, bs) q' \\<and> accept q'})) `\n    {q \\<in> Q. active q []})\"\n\nlemma sg_le_card:\n  assumes \"active init []\"\n  shows \"sg \\<le> card Q\"\nproof -\n  define Q' where \"Q' = {q \\<in> Q. active q []}\"\n  have Q'_props: \"finite Q'\" \"Q' \\<noteq> {}\"\n    using finite_Q assms(1) init_in_Q\n    by (auto simp add: active_def Q'_def)\n  have \"\\<And>q. q \\<in> Q' \\<Longrightarrow> Inf (length ` {as. \\<exists>bs q'. q\\<leadsto>(as, bs)q' \\<and> accept q'}) \\<le> card Q\"\n  proof -\n    fix q\n    assume in_Q': \"q \\<in> Q'\"\n    then obtain as bs q' where wit: \"q\\<leadsto>(as, bs)q'\" \"accept q'\" \"length as \\<le> card Q\"\n      using active_Nil_dest\n      unfolding Q'_def\n      by blast\n    then have len_as_in: \"length as \\<in> length ` {as. \\<exists>bs q'. q\\<leadsto>(as, bs)q' \\<and> accept q'}\"\n      by auto\n    show \"Inf (length ` {as. \\<exists>bs q'. q\\<leadsto>(as, bs)q' \\<and> accept q'}) \\<le> card Q\"\n      by (rule le_trans[OF cInf_lower[OF len_as_in] wit(3)]) auto\n  qed\n  then show ?thesis\n    using Q'_props\n    by (auto simp add: sg_def Q'_def[symmetric])\nqed\n\nlemma active_Nil_dest_sg:\n  assumes \"active q []\" \"q \\<in> Q\"\n  shows \"\\<exists>as bs' q'. q \\<leadsto>(as, bs') q' \\<and> accept q' \\<and> length as \\<le> sg \\<and>\n    length bs' \\<le> sg * output_speed\"\nproof -\n  define ass where \"ass = length ` {as. \\<exists>bs q'. q \\<leadsto>(as, bs) q' \\<and> accept q'}\"\n  have \"ass \\<noteq> {}\"\n    using assms(1)\n    by (auto simp add: ass_def active_def)\n  then have \"Inf ass \\<in> ass\"\n    using Inf_nat_def1\n    by auto\n  then obtain as bs q' where wit: \"q \\<leadsto>(as, bs) q'\" \"accept q'\" \"length as = Inf ass\"\n    by (auto simp add: ass_def)\n  moreover have \"Inf ass \\<le> sg\"\n    using assms finite_Q\n    by (auto simp add: ass_def sg_def)\n  ultimately show ?thesis\n    using output_speed_computation[OF wit(1) assms(2)]\n    by (auto simp add: mult.commute order_subst1 intro!: exI[of _ as] exI[of _ bs] exI[of _ q'])\nqed\n\nlemma active_dest:\n  assumes \"active q bs\" \"q \\<in> Q\"\n  shows \"\\<exists>as bs' q'. q \\<leadsto>(as, bs @ bs') q' \\<and> accept q' \\<and>\n    length bs' \\<le> (1 + sg) * output_speed\"\nproof -\n  obtain as bs' q' where act: \"q \\<leadsto>(as, bs @ bs') q'\" \"accept q'\"\n    using assms(1)\n    by (auto simp add: active_def)\n  then show ?thesis\n  proof (cases \"length bs' \\<ge> output_speed\")\n    case True\n    have app: \"bs @ bs' = (bs @ take output_speed bs') @ (drop output_speed bs')\"\n      using True\n      by auto\n    obtain q'' as' as'' cs cs' where split: \"q\\<leadsto>(as', cs)q''\" \"q''\\<leadsto>(as'', cs')q'\"\n      \"as = as' @ as''\"\n      \"(bs @ take output_speed bs') @ drop output_speed bs' = cs @ cs'\"\n      \"length cs \\<le> length (bs @ take output_speed bs')\"\n      \"length (bs @ take output_speed bs') - length cs \\<le> output_speed\"\n      using computation_split_out[OF act(1)[unfolded app] assms(2)]\n      by auto\n    obtain ds where ds_def: \"cs = bs @ ds\" \"length ds \\<le> output_speed\"\n      using split(5,6) True split_app[OF split(4)[unfolded app[symmetric]]]\n      by fastforce\n    note q''_Q = comp_closed[OF split(1) assms(2)]\n    have act_q'': \"active q'' []\"\n      using split(2) act(2)\n      by (auto simp add: active_def)\n    obtain es fs q''' where es_fs_def: \"q''\\<leadsto>(es, fs)q'''\" \"accept q'''\" \"length es \\<le> sg\"\n      using active_Nil_dest_sg[OF act_q'' q''_Q]\n      by auto\n    have fs_len: \"length fs \\<le> sg * output_speed\"\n      using output_speed_computation[OF es_fs_def(1) q''_Q] es_fs_def(3)\n      by (meson dual_order.trans mult_le_mono1)\n    show ?thesis\n      using comp_trans[OF split(1)[unfolded ds_def(1)] es_fs_def(1)] ds_def(2) fs_len es_fs_def(2)\n      by fastforce\n  qed fastforce\nqed\n\nlemma bounded_mono: \"K \\<le> K' \\<Longrightarrow> bounded K \\<Longrightarrow> bounded K'\"\n  by (fastforce simp add: bounded_def)\n\nlemma bounded_dest: \"\\<And>q q' u v v'. bounded K \\<Longrightarrow> init \\<leadsto>(u, v @ v') q \\<Longrightarrow> active q [] \\<Longrightarrow>\n  init \\<leadsto>(u, v) q' \\<Longrightarrow> active q' v' \\<Longrightarrow> length v' \\<le> K\"\n  by (auto simp add: bounded_def)\n\nend\n\nlocale bNFT = NFT init \\<delta> accept Q\n  for init :: \"'s\"\n  and \\<delta> :: \"'s \\<Rightarrow> 'a :: finite \\<Rightarrow> 's \\<times> ('b :: finite) list \\<Rightarrow> bool\"\n  and accept :: \"'s \\<Rightarrow> bool\"\n  and Q :: \"'s set\" +\nfixes K :: nat\nassumes bounded: \"bounded K\"\nbegin\n\nlemmas bounded' = bounded_dest[OF bounded]\n\nend\n\n(* Definition 3 *)\n\nlocale kNFT = NFT init \\<delta> accept Q\n  for init :: \"'s\"\n  and \\<delta> :: \"'s \\<Rightarrow> 'a :: finite \\<Rightarrow> 's \\<times> 'b list \\<Rightarrow> bool\"\n  and accept :: \"'s \\<Rightarrow> bool\"\n  and Q :: \"'s set\" +\nfixes kv :: nat\nassumes kval: \"finite {bs. (as, bs) \\<in> \\<tau>}\" \"card {bs. (as, bs) \\<in> \\<tau>} \\<le> kv\"\n\nlocale fNFT = NFT init \\<delta> accept Q\n  for init :: \"'s\"\n  and \\<delta> :: \"'s \\<Rightarrow> 'a :: finite \\<Rightarrow> 's \\<times> 'b list \\<Rightarrow> bool\"\n  and accept :: \"'s \\<Rightarrow> bool\"\n  and Q :: \"'s set\" +\nassumes functional: \"(x, y) \\<in> \\<tau> \\<Longrightarrow> (x, y') \\<in> \\<tau> \\<Longrightarrow> y = y'\"\nbegin\n\nlemma one_valued: \"finite {bs. (as, bs) \\<in> \\<tau>} \\<and> card {bs. (as, bs) \\<in> \\<tau>} \\<le> 1\"\nproof -\n  show \"finite {bs. (as, bs) \\<in> \\<tau>} \\<and> card {bs. (as, bs) \\<in> \\<tau>} \\<le> 1\"\n  proof (cases \"{bs. (as, bs) \\<in> \\<tau>} = {}\")\n    case False\n    then obtain bs where bs_def: \"(as, bs) \\<in> \\<tau>\"\n      by auto\n    have \"{bs. (as, bs) \\<in> \\<tau>} = {bs}\"\n      using functional[OF bs_def]\n      by (auto simp: bs_def)\n    then show ?thesis\n      by auto\n  qed auto\nqed\n\ninterpretation kNFT init \\<delta> accept Q 1\n  using one_valued\n  by unfold_locales auto\n\nend\n\nlocale uNFT = NFT init \\<delta> accept Q\n  for init :: \"'s\"\n  and \\<delta> :: \"'s \\<Rightarrow> 'a :: finite \\<Rightarrow> 's \\<times> 'b list \\<Rightarrow> bool\"\n  and accept :: \"'s \\<Rightarrow> bool\"\n  and Q :: \"'s set\" +\nassumes unambiguous: \"init \\<leadsto>e (as, qbs) f \\<Longrightarrow> accept f \\<Longrightarrow>\n  init \\<leadsto>e (as, qbs') f' \\<Longrightarrow> accept f' \\<Longrightarrow> qbs = qbs'\"\nbegin\n\nlemma functional: \"(as, bs) \\<in> \\<tau> \\<Longrightarrow> (as, bs') \\<in> \\<tau> \\<Longrightarrow> bs = bs'\"\n  using unambiguous\n  by (fastforce simp: \\<tau>_def dest!: computation_ext_complete)\n\ninterpretation fNFT init \\<delta> accept Q\n  using functional\n  by unfold_locales assumption\n\nend\n\nend", "meta": {"author": "stacs21", "repo": "automata", "sha": "ad3f66175122479d075b5ad9d996511035ea775a", "save_path": "github-repos/isabelle/stacs21-automata", "path": "github-repos/isabelle/stacs21-automata/automata-ad3f66175122479d075b5ad9d996511035ea775a/thys/Computation.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8354835371034368, "lm_q2_score": 0.8397339656668286, "lm_q1q2_score": 0.7015839038612179}}
{"text": "(*  Title:      ZF/Perm.thy\n    Author:     Lawrence C Paulson, Cambridge University Computer Laboratory\n    Copyright   1991  University of Cambridge\n\nThe theory underlying permutation groups\n  -- Composition of relations, the identity relation\n  -- Injections, surjections, bijections\n  -- Lemmas for the Schroeder-Bernstein Theorem\n*)\n\nsection\\<open>Injections, Surjections, Bijections, Composition\\<close>\n\ntheory Perm imports func begin\n\ndefinition\n  (*composition of relations and functions; NOT Suppes's relative product*)\n  comp     :: \"[i,i]=>i\"      (infixr \"O\" 60)  where\n    \"r O s == {xz \\<in> domain(s)*range(r) .\n               \\<exists>x y z. xz=<x,z> & <x,y>:s & <y,z>:r}\"\n\ndefinition\n  (*the identity function for A*)\n  id    :: \"i=>i\"  where\n    \"id(A) == (\\<lambda>x\\<in>A. x)\"\n\ndefinition\n  (*one-to-one functions from A to B*)\n  inj   :: \"[i,i]=>i\"  where\n    \"inj(A,B) == { f \\<in> A->B. \\<forall>w\\<in>A. \\<forall>x\\<in>A. f`w=f`x \\<longrightarrow> w=x}\"\n\ndefinition\n  (*onto functions from A to B*)\n  surj  :: \"[i,i]=>i\"  where\n    \"surj(A,B) == { f \\<in> A->B . \\<forall>y\\<in>B. \\<exists>x\\<in>A. f`x=y}\"\n\ndefinition\n  (*one-to-one and onto functions*)\n  bij   :: \"[i,i]=>i\"  where\n    \"bij(A,B) == inj(A,B) \\<inter> surj(A,B)\"\n\n\nsubsection\\<open>Surjective Function Space\\<close>\n\nlemma surj_is_fun: \"f \\<in> surj(A,B) ==> f \\<in> A->B\"\napply (unfold surj_def)\napply (erule CollectD1)\ndone\n\nlemma fun_is_surj: \"f \\<in> Pi(A,B) ==> f \\<in> surj(A,range(f))\"\napply (unfold surj_def)\napply (blast intro: apply_equality range_of_fun domain_type)\ndone\n\nlemma surj_range: \"f \\<in> surj(A,B) ==> range(f)=B\"\napply (unfold surj_def)\napply (best intro: apply_Pair elim: range_type)\ndone\n\ntext\\<open>A function with a right inverse is a surjection\\<close>\n\nlemma f_imp_surjective:\n    \"[| f \\<in> A->B;  !!y. y \\<in> B ==> d(y): A;  !!y. y \\<in> B ==> f`d(y) = y |]\n     ==> f \\<in> surj(A,B)\"\n  by (simp add: surj_def, blast)\n\nlemma lam_surjective:\n    \"[| !!x. x \\<in> A ==> c(x): B;\n        !!y. y \\<in> B ==> d(y): A;\n        !!y. y \\<in> B ==> c(d(y)) = y\n     |] ==> (\\<lambda>x\\<in>A. c(x)) \\<in> surj(A,B)\"\napply (rule_tac d = d in f_imp_surjective)\napply (simp_all add: lam_type)\ndone\n\ntext\\<open>Cantor's theorem revisited\\<close>\nlemma cantor_surj: \"f \\<notin> surj(A,Pow(A))\"\napply (unfold surj_def, safe)\napply (cut_tac cantor)\napply (best del: subsetI)\ndone\n\n\nsubsection\\<open>Injective Function Space\\<close>\n\nlemma inj_is_fun: \"f \\<in> inj(A,B) ==> f \\<in> A->B\"\napply (unfold inj_def)\napply (erule CollectD1)\ndone\n\ntext\\<open>Good for dealing with sets of pairs, but a bit ugly in use [used in AC]\\<close>\nlemma inj_equality:\n    \"[| <a,b>:f;  <c,b>:f;  f \\<in> inj(A,B) |] ==> a=c\"\napply (unfold inj_def)\napply (blast dest: Pair_mem_PiD)\ndone\n\nlemma inj_apply_equality: \"[| f \\<in> inj(A,B);  f`a=f`b;  a \\<in> A;  b \\<in> A |] ==> a=b\"\nby (unfold inj_def, blast)\n\ntext\\<open>A function with a left inverse is an injection\\<close>\n\nlemma f_imp_injective: \"[| f \\<in> A->B;  \\<forall>x\\<in>A. d(f`x)=x |] ==> f \\<in> inj(A,B)\"\napply (simp (no_asm_simp) add: inj_def)\napply (blast intro: subst_context [THEN box_equals])\ndone\n\nlemma lam_injective:\n    \"[| !!x. x \\<in> A ==> c(x): B;\n        !!x. x \\<in> A ==> d(c(x)) = x |]\n     ==> (\\<lambda>x\\<in>A. c(x)) \\<in> inj(A,B)\"\napply (rule_tac d = d in f_imp_injective)\napply (simp_all add: lam_type)\ndone\n\nsubsection\\<open>Bijections\\<close>\n\nlemma bij_is_inj: \"f \\<in> bij(A,B) ==> f \\<in> inj(A,B)\"\napply (unfold bij_def)\napply (erule IntD1)\ndone\n\nlemma bij_is_surj: \"f \\<in> bij(A,B) ==> f \\<in> surj(A,B)\"\napply (unfold bij_def)\napply (erule IntD2)\ndone\n\nlemma bij_is_fun: \"f \\<in> bij(A,B) ==> f \\<in> A->B\"\n  by (rule bij_is_inj [THEN inj_is_fun])\n\nlemma lam_bijective:\n    \"[| !!x. x \\<in> A ==> c(x): B;\n        !!y. y \\<in> B ==> d(y): A;\n        !!x. x \\<in> A ==> d(c(x)) = x;\n        !!y. y \\<in> B ==> c(d(y)) = y\n     |] ==> (\\<lambda>x\\<in>A. c(x)) \\<in> bij(A,B)\"\napply (unfold bij_def)\napply (blast intro!: lam_injective lam_surjective)\ndone\n\nlemma RepFun_bijective: \"(\\<forall>y\\<in>x. \\<exists>!y'. f(y') = f(y))\n      ==> (\\<lambda>z\\<in>{f(y). y \\<in> x}. THE y. f(y) = z) \\<in> bij({f(y). y \\<in> x}, x)\"\napply (rule_tac d = f in lam_bijective)\napply (auto simp add: the_equality2)\ndone\n\n\nsubsection\\<open>Identity Function\\<close>\n\nlemma idI [intro!]: \"a \\<in> A ==> <a,a> \\<in> id(A)\"\napply (unfold id_def)\napply (erule lamI)\ndone\n\nlemma idE [elim!]: \"[| p \\<in> id(A);  !!x.[| x \\<in> A; p=<x,x> |] ==> P |] ==>  P\"\nby (simp add: id_def lam_def, blast)\n\nlemma id_type: \"id(A) \\<in> A->A\"\napply (unfold id_def)\napply (rule lam_type, assumption)\ndone\n\nlemma id_conv [simp]: \"x \\<in> A ==> id(A)`x = x\"\napply (unfold id_def)\napply (simp (no_asm_simp))\ndone\n\nlemma id_mono: \"A<=B ==> id(A) \\<subseteq> id(B)\"\napply (unfold id_def)\napply (erule lam_mono)\ndone\n\nlemma id_subset_inj: \"A<=B ==> id(A): inj(A,B)\"\napply (simp add: inj_def id_def)\napply (blast intro: lam_type)\ndone\n\nlemmas id_inj = subset_refl [THEN id_subset_inj]\n\nlemma id_surj: \"id(A): surj(A,A)\"\napply (unfold id_def surj_def)\napply (simp (no_asm_simp))\ndone\n\nlemma id_bij: \"id(A): bij(A,A)\"\napply (unfold bij_def)\napply (blast intro: id_inj id_surj)\ndone\n\nlemma subset_iff_id: \"A \\<subseteq> B \\<longleftrightarrow> id(A) \\<in> A->B\"\napply (unfold id_def)\napply (force intro!: lam_type dest: apply_type)\ndone\n\ntext\\<open>@{term id} as the identity relation\\<close>\nlemma id_iff [simp]: \"<x,y> \\<in> id(A) \\<longleftrightarrow> x=y & y \\<in> A\"\nby auto\n\n\nsubsection\\<open>Converse of a Function\\<close>\n\nlemma inj_converse_fun: \"f \\<in> inj(A,B) ==> converse(f) \\<in> range(f)->A\"\napply (unfold inj_def)\napply (simp (no_asm_simp) add: Pi_iff function_def)\napply (erule CollectE)\napply (simp (no_asm_simp) add: apply_iff)\napply (blast dest: fun_is_rel)\ndone\n\ntext\\<open>Equations for converse(f)\\<close>\n\ntext\\<open>The premises are equivalent to saying that f is injective...\\<close>\nlemma left_inverse_lemma:\n     \"[| f \\<in> A->B;  converse(f): C->A;  a \\<in> A |] ==> converse(f)`(f`a) = a\"\nby (blast intro: apply_Pair apply_equality converseI)\n\nlemma left_inverse [simp]: \"[| f \\<in> inj(A,B);  a \\<in> A |] ==> converse(f)`(f`a) = a\"\nby (blast intro: left_inverse_lemma inj_converse_fun inj_is_fun)\n\nlemma left_inverse_eq:\n     \"[|f \\<in> inj(A,B); f ` x = y; x \\<in> A|] ==> converse(f) ` y = x\"\nby auto\n\nlemmas left_inverse_bij = bij_is_inj [THEN left_inverse]\n\nlemma right_inverse_lemma:\n     \"[| f \\<in> A->B;  converse(f): C->A;  b \\<in> C |] ==> f`(converse(f)`b) = b\"\nby (rule apply_Pair [THEN converseD [THEN apply_equality]], auto)\n\n(*Should the premises be f \\<in> surj(A,B), b \\<in> B for symmetry with left_inverse?\n  No: they would not imply that converse(f) was a function! *)\nlemma right_inverse [simp]:\n     \"[| f \\<in> inj(A,B);  b \\<in> range(f) |] ==> f`(converse(f)`b) = b\"\nby (blast intro: right_inverse_lemma inj_converse_fun inj_is_fun)\n\nlemma right_inverse_bij: \"[| f \\<in> bij(A,B);  b \\<in> B |] ==> f`(converse(f)`b) = b\"\nby (force simp add: bij_def surj_range)\n\nsubsection\\<open>Converses of Injections, Surjections, Bijections\\<close>\n\nlemma inj_converse_inj: \"f \\<in> inj(A,B) ==> converse(f): inj(range(f), A)\"\napply (rule f_imp_injective)\napply (erule inj_converse_fun, clarify)\napply (rule right_inverse)\n apply assumption\napply blast\ndone\n\nlemma inj_converse_surj: \"f \\<in> inj(A,B) ==> converse(f): surj(range(f), A)\"\nby (blast intro: f_imp_surjective inj_converse_fun left_inverse inj_is_fun\n                 range_of_fun [THEN apply_type])\n\ntext\\<open>Adding this as an intro! rule seems to cause looping\\<close>\nlemma bij_converse_bij [TC]: \"f \\<in> bij(A,B) ==> converse(f): bij(B,A)\"\napply (unfold bij_def)\napply (fast elim: surj_range [THEN subst] inj_converse_inj inj_converse_surj)\ndone\n\n\n\nsubsection\\<open>Composition of Two Relations\\<close>\n\ntext\\<open>The inductive definition package could derive these theorems for @{term\"r O s\"}\\<close>\n\nlemma compI [intro]: \"[| <a,b>:s; <b,c>:r |] ==> <a,c> \\<in> r O s\"\nby (unfold comp_def, blast)\n\nlemma compE [elim!]:\n    \"[| xz \\<in> r O s;\n        !!x y z. [| xz=<x,z>;  <x,y>:s;  <y,z>:r |] ==> P |]\n     ==> P\"\nby (unfold comp_def, blast)\n\nlemma compEpair:\n    \"[| <a,c> \\<in> r O s;\n        !!y. [| <a,y>:s;  <y,c>:r |] ==> P |]\n     ==> P\"\nby (erule compE, simp)\n\nlemma converse_comp: \"converse(R O S) = converse(S) O converse(R)\"\nby blast\n\n\nsubsection\\<open>Domain and Range -- see Suppes, Section 3.1\\<close>\n\ntext\\<open>Boyer et al., Set Theory in First-Order Logic, JAR 2 (1986), 287-327\\<close>\nlemma range_comp: \"range(r O s) \\<subseteq> range(r)\"\nby blast\n\nlemma range_comp_eq: \"domain(r) \\<subseteq> range(s) ==> range(r O s) = range(r)\"\nby (rule range_comp [THEN equalityI], blast)\n\nlemma domain_comp: \"domain(r O s) \\<subseteq> domain(s)\"\nby blast\n\nlemma domain_comp_eq: \"range(s) \\<subseteq> domain(r) ==> domain(r O s) = domain(s)\"\nby (rule domain_comp [THEN equalityI], blast)\n\nlemma image_comp: \"(r O s)``A = r``(s``A)\"\nby blast\n\nlemma inj_inj_range: \"f \\<in> inj(A,B) ==> f \\<in> inj(A,range(f))\"\n  by (auto simp add: inj_def Pi_iff function_def)\n\nlemma inj_bij_range: \"f \\<in> inj(A,B) ==> f \\<in> bij(A,range(f))\"\n  by (auto simp add: bij_def intro: inj_inj_range inj_is_fun fun_is_surj)\n\n\nsubsection\\<open>Other Results\\<close>\n\nlemma comp_mono: \"[| r'<=r; s'<=s |] ==> (r' O s') \\<subseteq> (r O s)\"\nby blast\n\ntext\\<open>composition preserves relations\\<close>\nlemma comp_rel: \"[| s<=A*B;  r<=B*C |] ==> (r O s) \\<subseteq> A*C\"\nby blast\n\ntext\\<open>associative law for composition\\<close>\nlemma comp_assoc: \"(r O s) O t = r O (s O t)\"\nby blast\n\n(*left identity of composition; provable inclusions are\n        id(A) O r \\<subseteq> r\n  and   [| r<=A*B; B<=C |] ==> r \\<subseteq> id(C) O r *)\nlemma left_comp_id: \"r<=A*B ==> id(B) O r = r\"\nby blast\n\n(*right identity of composition; provable inclusions are\n        r O id(A) \\<subseteq> r\n  and   [| r<=A*B; A<=C |] ==> r \\<subseteq> r O id(C) *)\nlemma right_comp_id: \"r<=A*B ==> r O id(A) = r\"\nby blast\n\n\nsubsection\\<open>Composition Preserves Functions, Injections, and Surjections\\<close>\n\nlemma comp_function: \"[| function(g);  function(f) |] ==> function(f O g)\"\nby (unfold function_def, blast)\n\ntext\\<open>Don't think the premises can be weakened much\\<close>\nlemma comp_fun: \"[| g \\<in> A->B;  f \\<in> B->C |] ==> (f O g) \\<in> A->C\"\napply (auto simp add: Pi_def comp_function Pow_iff comp_rel)\napply (subst range_rel_subset [THEN domain_comp_eq], auto)\ndone\n\n(*Thanks to the new definition of \"apply\", the premise f \\<in> B->C is gone!*)\nlemma comp_fun_apply [simp]:\n     \"[| g \\<in> A->B;  a \\<in> A |] ==> (f O g)`a = f`(g`a)\"\napply (frule apply_Pair, assumption)\napply (simp add: apply_def image_comp)\napply (blast dest: apply_equality)\ndone\n\ntext\\<open>Simplifies compositions of lambda-abstractions\\<close>\nlemma comp_lam:\n    \"[| !!x. x \\<in> A ==> b(x): B |]\n     ==> (\\<lambda>y\\<in>B. c(y)) O (\\<lambda>x\\<in>A. b(x)) = (\\<lambda>x\\<in>A. c(b(x)))\"\napply (subgoal_tac \"(\\<lambda>x\\<in>A. b(x)) \\<in> A -> B\")\n apply (rule fun_extension)\n   apply (blast intro: comp_fun lam_funtype)\n  apply (rule lam_funtype)\n apply simp\napply (simp add: lam_type)\ndone\n\nlemma comp_inj:\n     \"[| g \\<in> inj(A,B);  f \\<in> inj(B,C) |] ==> (f O g) \\<in> inj(A,C)\"\napply (frule inj_is_fun [of g])\napply (frule inj_is_fun [of f])\napply (rule_tac d = \"%y. converse (g) ` (converse (f) ` y)\" in f_imp_injective)\n apply (blast intro: comp_fun, simp)\ndone\n\nlemma comp_surj:\n    \"[| g \\<in> surj(A,B);  f \\<in> surj(B,C) |] ==> (f O g) \\<in> surj(A,C)\"\napply (unfold surj_def)\napply (blast intro!: comp_fun comp_fun_apply)\ndone\n\nlemma comp_bij:\n    \"[| g \\<in> bij(A,B);  f \\<in> bij(B,C) |] ==> (f O g) \\<in> bij(A,C)\"\napply (unfold bij_def)\napply (blast intro: comp_inj comp_surj)\ndone\n\n\nsubsection\\<open>Dual Properties of @{term inj} and @{term surj}\\<close>\n\ntext\\<open>Useful for proofs from\n    D Pastre.  Automatic theorem proving in set theory.\n    Artificial Intelligence, 10:1--27, 1978.\\<close>\n\nlemma comp_mem_injD1:\n    \"[| (f O g): inj(A,C);  g \\<in> A->B;  f \\<in> B->C |] ==> g \\<in> inj(A,B)\"\nby (unfold inj_def, force)\n\nlemma comp_mem_injD2:\n    \"[| (f O g): inj(A,C);  g \\<in> surj(A,B);  f \\<in> B->C |] ==> f \\<in> inj(B,C)\"\napply (unfold inj_def surj_def, safe)\napply (rule_tac x1 = x in bspec [THEN bexE])\napply (erule_tac [3] x1 = w in bspec [THEN bexE], assumption+, safe)\napply (rule_tac t = \"op ` (g) \" in subst_context)\napply (erule asm_rl bspec [THEN bspec, THEN mp])+\napply (simp (no_asm_simp))\ndone\n\nlemma comp_mem_surjD1:\n    \"[| (f O g): surj(A,C);  g \\<in> A->B;  f \\<in> B->C |] ==> f \\<in> surj(B,C)\"\napply (unfold surj_def)\napply (blast intro!: comp_fun_apply [symmetric] apply_funtype)\ndone\n\n\nlemma comp_mem_surjD2:\n    \"[| (f O g): surj(A,C);  g \\<in> A->B;  f \\<in> inj(B,C) |] ==> g \\<in> surj(A,B)\"\napply (unfold inj_def surj_def, safe)\napply (drule_tac x = \"f`y\" in bspec, auto)\napply (blast intro: apply_funtype)\ndone\n\nsubsubsection\\<open>Inverses of Composition\\<close>\n\ntext\\<open>left inverse of composition; one inclusion is\n        @{term \"f \\<in> A->B ==> id(A) \\<subseteq> converse(f) O f\"}\\<close>\nlemma left_comp_inverse: \"f \\<in> inj(A,B) ==> converse(f) O f = id(A)\"\napply (unfold inj_def, clarify)\napply (rule equalityI)\n apply (auto simp add: apply_iff, blast)\ndone\n\ntext\\<open>right inverse of composition; one inclusion is\n                @{term \"f \\<in> A->B ==> f O converse(f) \\<subseteq> id(B)\"}\\<close>\nlemma right_comp_inverse:\n    \"f \\<in> surj(A,B) ==> f O converse(f) = id(B)\"\napply (simp add: surj_def, clarify)\napply (rule equalityI)\napply (best elim: domain_type range_type dest: apply_equality2)\napply (blast intro: apply_Pair)\ndone\n\n\nsubsubsection\\<open>Proving that a Function is a Bijection\\<close>\n\nlemma comp_eq_id_iff:\n    \"[| f \\<in> A->B;  g \\<in> B->A |] ==> f O g = id(B) \\<longleftrightarrow> (\\<forall>y\\<in>B. f`(g`y)=y)\"\napply (unfold id_def, safe)\n apply (drule_tac t = \"%h. h`y \" in subst_context)\n apply simp\napply (rule fun_extension)\n  apply (blast intro: comp_fun lam_type)\n apply auto\ndone\n\nlemma fg_imp_bijective:\n    \"[| f \\<in> A->B;  g \\<in> B->A;  f O g = id(B);  g O f = id(A) |] ==> f \\<in> bij(A,B)\"\napply (unfold bij_def)\napply (simp add: comp_eq_id_iff)\napply (blast intro: f_imp_injective f_imp_surjective apply_funtype)\ndone\n\nlemma nilpotent_imp_bijective: \"[| f \\<in> A->A;  f O f = id(A) |] ==> f \\<in> bij(A,A)\"\nby (blast intro: fg_imp_bijective)\n\nlemma invertible_imp_bijective:\n     \"[| converse(f): B->A;  f \\<in> A->B |] ==> f \\<in> bij(A,B)\"\nby (simp add: fg_imp_bijective comp_eq_id_iff\n              left_inverse_lemma right_inverse_lemma)\n\nsubsubsection\\<open>Unions of Functions\\<close>\n\ntext\\<open>See similar theorems in func.thy\\<close>\n\ntext\\<open>Theorem by KG, proof by LCP\\<close>\nlemma inj_disjoint_Un:\n     \"[| f \\<in> inj(A,B);  g \\<in> inj(C,D);  B \\<inter> D = 0 |]\n      ==> (\\<lambda>a\\<in>A \\<union> C. if a \\<in> A then f`a else g`a) \\<in> inj(A \\<union> C, B \\<union> D)\"\napply (rule_tac d = \"%z. if z \\<in> B then converse (f) `z else converse (g) `z\"\n       in lam_injective)\napply (auto simp add: inj_is_fun [THEN apply_type])\ndone\n\nlemma surj_disjoint_Un:\n    \"[| f \\<in> surj(A,B);  g \\<in> surj(C,D);  A \\<inter> C = 0 |]\n     ==> (f \\<union> g) \\<in> surj(A \\<union> C, B \\<union> D)\"\napply (simp add: surj_def fun_disjoint_Un)\napply (blast dest!: domain_of_fun\n             intro!: fun_disjoint_apply1 fun_disjoint_apply2)\ndone\n\ntext\\<open>A simple, high-level proof; the version for injections follows from it,\n  using  @{term \"f \\<in> inj(A,B) \\<longleftrightarrow> f \\<in> bij(A,range(f))\"}\\<close>\nlemma bij_disjoint_Un:\n     \"[| f \\<in> bij(A,B);  g \\<in> bij(C,D);  A \\<inter> C = 0;  B \\<inter> D = 0 |]\n      ==> (f \\<union> g) \\<in> bij(A \\<union> C, B \\<union> D)\"\napply (rule invertible_imp_bijective)\napply (subst converse_Un)\napply (auto intro: fun_disjoint_Un bij_is_fun bij_converse_bij)\ndone\n\n\nsubsubsection\\<open>Restrictions as Surjections and Bijections\\<close>\n\nlemma surj_image:\n    \"f \\<in> Pi(A,B) ==> f \\<in> surj(A, f``A)\"\napply (simp add: surj_def)\napply (blast intro: apply_equality apply_Pair Pi_type)\ndone\n\nlemma surj_image_eq: \"f \\<in> surj(A, B) ==> f``A = B\"\n  by (auto simp add: surj_def image_fun) (blast dest: apply_type) \n\nlemma restrict_image [simp]: \"restrict(f,A) `` B = f `` (A \\<inter> B)\"\nby (auto simp add: restrict_def)\n\nlemma restrict_inj:\n    \"[| f \\<in> inj(A,B);  C<=A |] ==> restrict(f,C): inj(C,B)\"\napply (unfold inj_def)\napply (safe elim!: restrict_type2, auto)\ndone\n\nlemma restrict_surj: \"[| f \\<in> Pi(A,B);  C<=A |] ==> restrict(f,C): surj(C, f``C)\"\napply (insert restrict_type2 [THEN surj_image])\napply (simp add: restrict_image)\ndone\n\nlemma restrict_bij:\n    \"[| f \\<in> inj(A,B);  C<=A |] ==> restrict(f,C): bij(C, f``C)\"\napply (simp add: inj_def bij_def)\napply (blast intro: restrict_surj surj_is_fun)\ndone\n\n\nsubsubsection\\<open>Lemmas for Ramsey's Theorem\\<close>\n\nlemma inj_weaken_type: \"[| f \\<in> inj(A,B);  B<=D |] ==> f \\<in> inj(A,D)\"\napply (unfold inj_def)\napply (blast intro: fun_weaken_type)\ndone\n\nlemma inj_succ_restrict:\n     \"[| f \\<in> inj(succ(m), A) |] ==> restrict(f,m) \\<in> inj(m, A-{f`m})\"\napply (rule restrict_bij [THEN bij_is_inj, THEN inj_weaken_type], assumption, blast)\napply (unfold inj_def)\napply (fast elim: range_type mem_irrefl dest: apply_equality)\ndone\n\n\nlemma inj_extend:\n    \"[| f \\<in> inj(A,B);  a\\<notin>A;  b\\<notin>B |]\n     ==> cons(<a,b>,f) \\<in> inj(cons(a,A), cons(b,B))\"\napply (unfold inj_def)\napply (force intro: apply_type  simp add: fun_extend)\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/Perm.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339556397749, "lm_q2_score": 0.8354835330070838, "lm_q1q2_score": 0.7015838920439329}}
{"text": "(* author: Thiemann *)\n\nsection \\<open>Roots of Unity\\<close>\n\ntheory Roots_Unity\nimports\n  Polynomial_Factorization.Order_Polynomial\n  \"HOL-Computational_Algebra.Fundamental_Theorem_Algebra\"\n  Polynomial_Interpolation.Ring_Hom_Poly\nbegin\n\nlemma cis_mult_cmod_id: \"cis (Arg x) * of_real (cmod x) = x\"\n  using rcis_cmod_Arg[unfolded rcis_def] by (simp add: ac_simps)\n\nlemma rcis_mult_cis[simp]: \"rcis n a * cis b = rcis n (a + b)\" unfolding cis_rcis_eq rcis_mult by simp\nlemma rcis_div_cis[simp]: \"rcis n a / cis b = rcis n (a - b)\" unfolding cis_rcis_eq rcis_divide by simp\n\nlemma cis_plus_2pi[simp]: \"cis (x + 2 * pi) = cis x\" by (auto simp: complex_eq_iff)\nlemma cis_plus_2pi_neq_1: assumes x: \"0 < x\" \"x < 2 * pi\"\n  shows \"cis x \\<noteq> 1\"\nproof -\n  from x have \"cos x \\<noteq> 1\" by (smt cos_2pi_minus cos_monotone_0_pi cos_zero)\n  thus ?thesis by (auto simp: complex_eq_iff)\nqed\n\nlemma cis_times_2pi[simp]: \"cis (of_nat n * 2 * pi) = 1\"\nproof (induct n)\n  case (Suc n)\n  have \"of_nat (Suc n) * 2 * pi = of_nat n * 2 * pi + 2 * pi\" by (simp add: distrib_right)\n  also have \"cis \\<dots> = 1\" unfolding cis_plus_2pi Suc ..\n  finally show ?case .\nqed simp\n\nlemma cis_add_pi[simp]: \"cis (pi + x) = - cis x\"\n  by (auto simp: complex_eq_iff)\n\nlemma cis_3_pi_2[simp]: \"cis (pi * 3 / 2) = - \\<i>\"\nproof -\n  have \"cis (pi * 3 / 2) = cis (pi + pi / 2)\"\n    by (rule arg_cong[of _ _ cis], simp)\n  also have \"\\<dots> = - \\<i>\" unfolding cis_add_pi by simp\n  finally show ?thesis .\nqed\n\nlemma rcis_plus_2pi[simp]: \"rcis y (x + 2 * pi) = rcis y x\" unfolding rcis_def by simp\nlemma rcis_times_2pi[simp]: \"rcis r (of_nat n * 2 * pi) = of_real r\"\n  unfolding rcis_def cis_times_2pi by simp\n\nlemma arg_rcis_cis: assumes n: \"n > 0\" shows \"Arg (rcis n x) = Arg (cis x)\"\n  using Arg_bounded cis_Arg_unique cis_Arg complex_mod_rcis n rcis_def sgn_eq by auto\n\nlemma arg_eqD: assumes \"Arg (cis x) = Arg (cis y)\" \"-pi < x\" \"x \\<le> pi\" \"-pi < y\" \"y \\<le> pi\"\n  shows \"x = y\"\n  using assms(1) unfolding cis_Arg_unique[OF sgn_cis assms(2-3)] cis_Arg_unique[OF sgn_cis assms(4-5)] .\n\nlemma rcis_inj_on: assumes r: \"r \\<noteq> 0\" shows \"inj_on (rcis r) {0 ..< 2 * pi}\"\nproof (rule inj_onI, goal_cases)\n  case (1 x y)\n  from arg_cong[OF 1(3), of \"\\<lambda> x. x / r\"] have \"cis x = cis y\" using r by (simp add: rcis_def)\n  from arg_cong[OF this, of \"\\<lambda> x. inverse x\"] have \"cis (-x) = cis (-y)\" by simp\n  from arg_cong[OF this, of uminus] have *: \"cis (-x + pi) = cis (-y + pi)\"\n    by (auto simp: complex_eq_iff)\n  have \"- x + pi = - y + pi\"\n    by (rule arg_eqD[OF arg_cong[OF *, of Arg]], insert 1(1-2), auto)\n  thus ?case by simp\nqed\n\nlemma cis_inj_on: \"inj_on cis {0 ..< 2 * pi}\"\n  using rcis_inj_on[of 1] unfolding rcis_def by auto\n\ndefinition root_unity :: \"nat \\<Rightarrow> 'a :: comm_ring_1 poly\" where\n  \"root_unity n = monom 1 n - 1\"\n\nlemma poly_root_unity: \"poly (root_unity n) x = 0 \\<longleftrightarrow> x^n = 1\"\n  unfolding root_unity_def by (simp add: poly_monom)\n\nlemma degree_root_unity[simp]: \"degree (root_unity n) = n\" (is \"degree ?p = _\")\nproof -\n  have p: \"?p = monom 1 n + (-1)\" unfolding root_unity_def by auto\n  show ?thesis\n  proof (cases n)\n    case 0\n    thus ?thesis unfolding p by simp\n  next\n    case (Suc m)\n    show ?thesis unfolding p unfolding Suc\n      by (subst degree_add_eq_left, auto simp: degree_monom_eq)\n  qed\nqed\n\nlemma zero_root_unit[simp]: \"root_unity n = 0 \\<longleftrightarrow> n = 0\" (is \"?p = 0 \\<longleftrightarrow> _\")\nproof (cases \"n = 0\")\n  case True\n  thus ?thesis unfolding root_unity_def by simp\nnext\n  case False\n  from degree_root_unity[of n] False\n  have \"degree ?p \\<noteq> 0\" by auto\n  hence \"?p \\<noteq> 0\" by fastforce\n  thus ?thesis using False by auto\nqed\n\ndefinition prod_root_unity :: \"nat list \\<Rightarrow> 'a :: idom poly\" where\n  \"prod_root_unity ns = prod_list (map root_unity ns)\"\n\nlemma poly_prod_root_unity: \"poly (prod_root_unity ns) x = 0 \\<longleftrightarrow> (\\<exists>k\\<in>set ns. x ^ k = 1)\"\n  unfolding prod_root_unity_def\n  by (simp add: poly_prod_list prod_list_zero_iff o_def image_def poly_root_unity)\n\nlemma degree_prod_root_unity[simp]: \"0 \\<notin> set ns \\<Longrightarrow> degree (prod_root_unity ns) = sum_list ns\"\n  unfolding prod_root_unity_def\n  by (subst degree_prod_list_eq, auto simp: o_def)\n\nlemma zero_prod_root_unit[simp]: \"prod_root_unity ns = 0 \\<longleftrightarrow> 0 \\<in> set ns\"\n  unfolding prod_root_unity_def prod_list_zero_iff by auto\n\nlemma roots_of_unity: assumes n: \"n \\<noteq> 0\"\n  shows \"(\\<lambda> i. (cis (of_nat i * 2 * pi / n))) ` {0 ..< n} = { x :: complex. x ^ n = 1}\" (is \"?prod = ?Roots\")\n     \"{x. poly (root_unity n) x = 0} = { x :: complex. x ^ n = 1}\"\n     \"card { x :: complex. x ^ n = 1} = n\"\nproof (atomize(full), goal_cases)\n  case 1\n  let ?one = \"1 :: complex\"\n  let ?p = \"monom ?one n - 1\"\n  have degM: \"degree (monom ?one n) = n\" by (rule degree_monom_eq, simp)\n  have \"degree ?p = degree (monom ?one n + (-1))\" by simp\n  also have \"\\<dots> = degree (monom ?one n)\"\n    by (rule degree_add_eq_left, insert n, simp add: degM)\n  finally have degp: \"degree ?p = n\" unfolding degM .\n  with n have p: \"?p \\<noteq> 0\" by auto\n  have roots: \"?Roots = {x. poly ?p x = 0}\"\n    unfolding poly_diff poly_monom by simp\n  also have \"finite \\<dots>\" by (rule poly_roots_finite[OF p])\n  finally have fin: \"finite ?Roots\" .\n  have sub: \"?prod \\<subseteq> ?Roots\"\n  proof\n    fix x\n    assume \"x \\<in> ?prod\"\n    then obtain i where x: \"x = cis (real i * 2 * pi / n)\" by auto\n    have \"x ^ n = cis (real i * 2 * pi)\" unfolding x DeMoivre using n by simp\n    also have \"\\<dots> = 1\" by simp\n    finally show \"x \\<in> ?Roots\" by auto\n  qed\n  have Rn: \"card ?Roots \\<le> n\" unfolding roots\n    by (rule poly_roots_degree[of ?p, unfolded degp, OF p])\n  have \"\\<dots> = card {0 ..< n}\" by simp\n  also have \"\\<dots> = card ?prod\"\n  proof (rule card_image[symmetric], rule inj_onI, goal_cases)\n    case (1 x y)\n    {\n      fix m\n      assume \"m < n\"\n      hence \"real m < real n\" by simp\n      from mult_strict_right_mono[OF this, of \"2 * pi / real n\"] n\n      have \"real m * 2 * pi / real n < real n * 2 * pi / real n\" by simp\n      hence \"real m * 2 * pi / real n < 2 * pi\" using n by simp\n    } note [simp] = this\n    have 0: \"(1 :: real) \\<noteq> 0\" using n by auto\n    have \"real x * 2 * pi / real n = real y * 2 * pi / real n\"\n      by (rule inj_onD[OF rcis_inj_on 1(3)[unfolded cis_rcis_eq]], insert 1(1-2), auto)\n    with n show \"x = y\" by auto\n  qed\n  finally have cn:  \"card ?prod = n\" ..\n  with Rn have \"card ?prod \\<ge> card ?Roots\" by auto\n  with card_mono[OF fin sub] have card: \"card ?prod = card ?Roots\" by auto\n  have \"?prod = ?Roots\"\n    by (rule card_subset_eq[OF fin sub card])\n  from this roots[symmetric] cn[unfolded this]\n  show ?case unfolding root_unity_def by blast\nqed\n\nlemma poly_roots_dvd: fixes p :: \"'a :: field poly\"\n  assumes \"p \\<noteq> 0\" and \"degree p = n\"\n  and \"card {x. poly p x = 0} \\<ge> n\" and \"{x. poly p x = 0} \\<subseteq> {x. poly q x = 0}\"\nshows \"p dvd q\"\nproof -\n  from poly_roots_degree[OF assms(1)] assms(2-3) have \"card {x. poly p x = 0} = n\" by auto\n  from assms(1-2) this assms(4)\n  show ?thesis\n  proof (induct n arbitrary: p q)\n    case (0 p q)\n    from is_unit_iff_degree[OF 0(1)] 0(2) show ?case by blast\n  next\n    case (Suc n p q)\n    let ?P = \"{x. poly p x = 0}\"\n    let ?Q = \"{x. poly q x = 0}\"\n    from Suc(4-5) card_gt_0_iff[of ?P] obtain x where\n      x: \"poly p x = 0\" \"poly q x = 0\" and fin: \"finite ?P\" by auto\n    define r where \"r = [:-x, 1:]\"\n    from x[unfolded poly_eq_0_iff_dvd r_def[symmetric]] obtain p' q' where\n      p: \"p = r * p'\" and q: \"q = r * q'\" unfolding dvd_def by auto\n    from Suc(2) have \"degree p = degree r + degree p'\" unfolding p\n      by (subst degree_mult_eq, auto)\n    with Suc(3) have deg: \"degree p' = n\" unfolding r_def by auto\n    from Suc(2) p have p'0: \"p' \\<noteq> 0\" by auto\n    let ?P' = \"{x. poly p' x = 0}\"\n    let ?Q' = \"{x. poly q' x = 0}\"\n    have P: \"?P = insert x ?P'\" unfolding p poly_mult unfolding r_def by auto\n    have Q: \"?Q = insert x ?Q'\" unfolding q poly_mult unfolding r_def by auto\n    {\n      assume \"x \\<in> ?P'\"\n      hence \"?P = ?P'\" unfolding P by auto\n      from arg_cong[OF this, of card, unfolded Suc(4)] deg have False\n        using poly_roots_degree[OF p'0] by auto\n    } note xp' = this\n    hence xP': \"x \\<notin> ?P'\" by auto\n    have \"card ?P = Suc (card ?P')\" unfolding P\n      by (rule card_insert_disjoint[OF _ xP'], insert fin[unfolded P], auto)\n    with Suc(4) have card: \"card ?P' = n\" by auto\n    from Suc(5)[unfolded P Q] xP' have \"?P' \\<subseteq> ?Q'\" by auto\n    from Suc(1)[OF p'0 deg card this]\n    have IH: \"p' dvd q'\" .\n    show ?case unfolding p q using IH by simp\n  qed\nqed\n\nlemma root_unity_decomp: assumes n: \"n \\<noteq> 0\"\n  shows \"root_unity n =\n    prod_list (map (\\<lambda> i. [:-cis (of_nat i * 2 * pi / n), 1:]) [0 ..< n])\" (is \"?u = ?p\")\nproof -\n  have deg: \"degree ?u = n\" by simp\n  note main = roots_of_unity[OF n]\n  have dvd: \"?u dvd ?p\"\n  proof (rule poly_roots_dvd[OF _ deg])\n    show \"n \\<le> card {x. poly ?u x = 0}\" using main by auto\n    show \"?u \\<noteq> 0\" using n by auto\n    show \"{x. poly ?u x = 0} \\<subseteq> {x. poly ?p x = 0}\"\n      unfolding main(2) main(1)[symmetric] poly_prod_list prod_list_zero_iff by auto\n  qed\n  have deg': \"degree ?p = n\"\n    by (subst degree_prod_list_eq, auto simp: o_def sum_list_triv)\n  have mon: \"monic ?u\" using deg unfolding root_unity_def using n by auto\n  have mon': \"monic ?p\" by (rule monic_prod_list, auto)\n  from dvd[unfolded dvd_def] obtain f where puf: \"?p = ?u * f\" by auto\n  have \"degree ?p = degree ?u + degree f\" using mon' n unfolding puf\n    by (subst degree_mult_eq, auto)\n  with deg deg' have \"degree f = 0\" by auto\n  from degree0_coeffs[OF this] obtain a where f: \"f = [:a:]\" by blast\n  from arg_cong[OF puf, of lead_coeff] mon mon'\n  have \"a = 1\" unfolding puf f by (cases \"a = 0\", auto)\n  with f have f: \"f = 1\" by auto\n  with puf show ?thesis by auto\nqed\n\nlemma order_monic_linear: \"order x [:y,1:] = (if y + x = 0 then 1 else 0)\"\nproof (cases \"y + x = 0\")\n  case True\n  hence \"poly [:y,1:] x = 0\" by simp\n  from this[unfolded order_root] have \"order x [:y,1:] \\<noteq> 0\" by auto\n  moreover from order_degree[of \"[:y,1:]\" x] have \"order x [:y,1:] \\<le> 1\" by auto\n  ultimately show ?thesis unfolding True by auto\nnext\n  case False\n  hence \"poly [:y,1:] x \\<noteq> 0\" by auto\n  from order_0I[OF this] False show ?thesis by auto\nqed\n\nlemma order_root_unity: fixes x :: complex assumes n: \"n \\<noteq> 0\"\n  shows \"order x (root_unity n) = (if x^n = 1 then 1 else 0)\"\n  (is \"order _ ?u = _\")\nproof (cases \"x^n = 1\")\n  case False\n  with roots_of_unity(2)[OF n] have \"poly ?u x \\<noteq> 0\" by auto\n  from False order_0I[OF this] show ?thesis by auto\nnext\n  case True\n  let ?phi = \"\\<lambda> i :: nat. i * 2 * pi / n\"\n  from True roots_of_unity(1)[OF n] obtain i where i: \"i < n\"\n    and x: \"x = cis (?phi i)\" by force\n  from i have n_split: \"[0 ..< n] = [0 ..< i] @ i # [Suc i ..< n]\"\n    by (metis le_Suc_ex less_imp_le_nat not_le_imp_less not_less0 upt_add_eq_append upt_conv_Cons)\n  {\n    fix j\n    assume j: \"j < n \\<or> j < i\" and eq: \"cis (?phi i) = cis (?phi j)\"\n    from inj_onD[OF cis_inj_on eq] i j n have \"i = j\" by (auto simp: field_simps)\n  } note inj = this\n  have \"order x ?u = 1\" unfolding root_unity_decomp[OF n]\n    unfolding x n_split using inj\n    by (subst order_prod_list, force, fastforce simp: order_monic_linear)\n  with True show ?thesis by auto\nqed\n\nlemma order_prod_root_unity: assumes 0: \"0 \\<notin> set ks\"\n  shows \"order (x :: complex) (prod_root_unity ks) = length (filter (\\<lambda> k. x^k = 1) ks)\"\nproof -\n  have \"order x (prod_root_unity ks) = (\\<Sum>k\\<leftarrow>ks. order x (root_unity k))\"\n    unfolding prod_root_unity_def\n    by (subst order_prod_list, insert 0, auto simp: o_def)\n  also have \"\\<dots> = (\\<Sum>k\\<leftarrow>ks. (if x^k = 1 then 1 else 0))\"\n    by (rule arg_cong, rule map_cong, insert 0, force, intro order_root_unity, metis)\n  also have \"\\<dots> = length (filter (\\<lambda> k. x^k = 1) ks)\"\n    by (subst sum_list_map_filter'[symmetric], simp add: sum_list_triv)\n  finally show ?thesis .\nqed\n\nlemma root_unity_witness: fixes xs :: \"complex list\"\n  assumes \"prod_list (map (\\<lambda> x. [:-x,1:]) xs) = monom 1 n - 1\"\n  shows \"x^n = 1 \\<longleftrightarrow> x \\<in> set xs\"\nproof -\n  from assms have n0: \"n \\<noteq> 0\" by (cases \"n = 0\", auto simp: prod_list_zero_iff)\n  have \"x \\<in> set xs \\<longleftrightarrow> poly (prod_list (map (\\<lambda> x. [:-x,1:]) xs)) x = 0\"\n    unfolding poly_prod_list prod_list_zero_iff by auto\n  also have \"\\<dots> \\<longleftrightarrow> x^n = 1\" using roots_of_unity(2)[OF n0] unfolding assms root_unity_def by auto\n  finally show ?thesis by auto\nqed\n\nlemma root_unity_explicit: fixes x :: complex\n  shows\n    \"(x ^ 1 = 1) \\<longleftrightarrow> x = 1\"\n    \"(x ^ 2 = 1) \\<longleftrightarrow> (x \\<in> {1, -1})\"\n    \"(x ^ 3 = 1) \\<longleftrightarrow> (x \\<in> {1, Complex (-1/2) (sqrt 3 / 2), Complex (-1/2) (- sqrt 3 / 2)})\"\n    \"(x ^ 4 = 1) \\<longleftrightarrow> (x \\<in> {1, -1, \\<i>, - \\<i>})\"\nproof -\n  show \"(x ^ 1 = 1) \\<longleftrightarrow> x = 1\"\n    by (subst root_unity_witness[of \"[1]\"], code_simp, auto)\n  show \"(x ^ 2 = 1) \\<longleftrightarrow> (x \\<in> {1, -1})\"\n    by (subst root_unity_witness[of \"[1,-1]\"], code_simp, auto)\n  show \"(x ^ 4 = 1) \\<longleftrightarrow> (x \\<in> {1, -1, \\<i>, - \\<i>})\"\n    by (subst root_unity_witness[of \"[1,-1, \\<i>, - \\<i>]\"], code_simp, auto)\n  have 3: \"3 = Suc (Suc (Suc 0))\" \"1 = [:1:]\" by auto\n  show \"(x ^ 3 = 1) \\<longleftrightarrow> (x \\<in> {1, Complex (-1/2) (sqrt 3 / 2), Complex (-1/2) (- sqrt 3 / 2)})\"\n    by (subst root_unity_witness[of\n      \"[1, Complex (-1/2) (sqrt 3 / 2), Complex (-1/2) (- sqrt 3 / 2)]\"],\n      auto simp: 3 monom_altdef complex_mult complex_eq_iff)\nqed\n\ndefinition primitive_root_unity :: \"nat \\<Rightarrow> 'a :: power \\<Rightarrow> bool\" where\n  \"primitive_root_unity k x = (k \\<noteq> 0 \\<and> x^k = 1 \\<and> (\\<forall> k' < k. k' \\<noteq> 0 \\<longrightarrow> x^k' \\<noteq> 1))\"\n\nlemma primitive_root_unityD: assumes \"primitive_root_unity k x\"\n  shows \"k \\<noteq> 0\" \"x^k = 1\" \"k' \\<noteq> 0 \\<Longrightarrow> x^k' = 1 \\<Longrightarrow> k \\<le> k'\"\nproof -\n  note * = assms[unfolded primitive_root_unity_def]\n  from * have **: \"k' < k \\<Longrightarrow> k' \\<noteq> 0 \\<Longrightarrow> x ^ k' \\<noteq> 1\" by auto\n  show \"k \\<noteq> 0\" \"x^k = 1\" using * by auto\n  show \"k' \\<noteq> 0 \\<Longrightarrow> x^k' = 1 \\<Longrightarrow> k \\<le> k'\" using ** by force\nqed\n\nlemma primitive_root_unity_exists: assumes \"k \\<noteq> 0\" \"x ^ k = 1\"\n  shows \"\\<exists> k'. k' \\<le> k \\<and> primitive_root_unity k' x\"\nproof -\n  let ?P = \"\\<lambda> k. x ^ k = 1 \\<and> k \\<noteq> 0\"\n  define k' where \"k' = (LEAST k. ?P k)\"\n  from assms have Pk: \"\\<exists> k. ?P k\" by auto\n  from LeastI_ex[OF Pk, folded k'_def]\n  have \"k' \\<noteq> 0\" \"x ^ k' = 1\" by auto\n  with not_less_Least[of _ ?P, folded k'_def]\n  have \"primitive_root_unity k' x\" unfolding primitive_root_unity_def by auto\n  with primitive_root_unityD(3)[OF this assms]\n  show ?thesis by auto\nqed\n\nlemma primitive_root_unity_dvd: fixes x :: \"complex\"\n  assumes k: \"primitive_root_unity k x\"\n  shows \"x ^ n = 1 \\<longleftrightarrow> k dvd n\"\nproof\n  assume \"k dvd n\" then obtain j where n: \"n = k * j\" unfolding dvd_def by auto\n  have \"x ^ n = (x ^ k) ^ j\" unfolding n power_mult by simp\n  also have \"\\<dots> = 1\" unfolding primitive_root_unityD[OF k] by simp\n  finally show \"x ^ n = 1\" .\nnext\n  assume n: \"x ^ n = 1\"\n  note k = primitive_root_unityD[OF k]\n  show \"k dvd n\"\n  proof (cases \"n = 0\")\n    case n0: False\n    from k(3)[OF n0] n have nk: \"n \\<ge> k\" by force\n    from roots_of_unity[OF k(1)] k(2) obtain i :: nat where xk: \"x = cis (i * 2 * pi / k)\"\n      and ik: \"i < k\" by force\n    from roots_of_unity[OF n0] n obtain j :: nat where xn: \"x = cis (j * 2 * pi / n)\"\n      and jn: \"j < n\" by force\n    have cop: \"coprime i k\"\n    proof (rule gcd_eq_1_imp_coprime)\n      from k(1) have \"gcd i k \\<noteq> 0\" by auto\n      from gcd_coprime_exists[OF this] this obtain i' k' g where\n        *: \"i = i' * g\" \"k = k' * g\" \"g \\<noteq> 0\" and g: \"g = gcd i k\" by blast\n      from *(2) k(1) have k': \"k' \\<noteq> 0\" by auto\n      have \"x = cis (i * 2 * pi / k)\" by fact\n      also have \"i * 2 * pi / k = i' * 2 * pi / k'\" unfolding * using *(3) by auto\n      finally have \"x ^ k' = 1\" by (simp add: DeMoivre k')\n      with k(3)[OF k'] have \"k' \\<ge> k\" by linarith\n      moreover with * k(1) have \"g = 1\" by auto\n      then show \"gcd i k = 1\" by (simp add: g)\n    qed\n    from inj_onD[OF cis_inj_on xk[unfolded xn]] n0 k(1) ik jn\n    have \"j * real k = i * real n\" by (auto simp: field_simps)\n    hence \"real (j * k) = real (i * n)\" by simp\n    hence eq: \"j * k = i * n\" by linarith\n    with cop show \"k dvd n\"\n      by (metis coprime_commute coprime_dvd_mult_right_iff dvd_triv_right)\n  qed auto\nqed\n\nlemma primitive_root_unity_simple_computation:\n  \"primitive_root_unity k x  = (if k = 0 then False else\n     x ^ k = 1 \\<and> (\\<forall> i \\<in> {1 ..< k}. x ^ i \\<noteq> 1))\"\n  unfolding primitive_root_unity_def by auto\n\nlemma primitive_root_unity_explicit: fixes x :: complex\n  shows \"primitive_root_unity 1 x \\<longleftrightarrow> x = 1\"\n    \"primitive_root_unity 2 x \\<longleftrightarrow> x = -1\"\n    \"primitive_root_unity 3 x \\<longleftrightarrow> (x \\<in> {Complex (-1/2) (sqrt 3 / 2), Complex (-1/2) (- sqrt 3 / 2)})\"\n    \"primitive_root_unity 4 x \\<longleftrightarrow> (x \\<in> {\\<i>, - \\<i>})\"\nproof (atomize(full), goal_cases)\n  case 1\n  {\n    fix P :: \"nat \\<Rightarrow> bool\"\n    have *: \"{1 ..< 2 :: nat} = {1}\" \"{1 ..< 3 :: nat} = {1,2}\" \"{1 ..< 4 :: nat} = {1,2,3}\"\n      by code_simp+\n    have \"(\\<forall>i\\<in> {1 ..< 2}. P i) = P 1\" \"(\\<forall>i\\<in> {1 ..< 3}. P i) \\<longleftrightarrow> P 1 \\<and> P 2\"\n      \"(\\<forall>i\\<in> {1 ..< 4}. P i) \\<longleftrightarrow> P 1 \\<and> P 2 \\<and> P 3\"\n      unfolding * by auto\n  } note * = this\n  show ?case unfolding primitive_root_unity_simple_computation root_unity_explicit *\n    by (auto simp: complex_eq_iff)\nqed\n\nfunction decompose_prod_root_unity_main ::\n  \"'a :: field poly \\<Rightarrow> nat \\<Rightarrow> nat list \\<times> 'a poly\" where\n  \"decompose_prod_root_unity_main p k = (\n    if k = 0 then ([], p) else\n   let q = root_unity k in if q dvd p then if p = 0 then ([],0) else\n     map_prod (Cons k) id (decompose_prod_root_unity_main (p div q) k) else\n     decompose_prod_root_unity_main p (k - 1))\"\n  by pat_completeness auto\n\ntermination by (relation \"measure (\\<lambda> (p,k). degree p + k)\", auto simp: degree_div_less)\n\ndeclare decompose_prod_root_unity_main.simps[simp del]\n\nlemma decompose_prod_root_unity_main: fixes p :: \"complex poly\"\n  assumes p: \"p = prod_root_unity ks * f\"\n  and d: \"decompose_prod_root_unity_main p k = (ks',g)\"\n  and f: \"\\<And> x. cmod x = 1 \\<Longrightarrow> poly f x \\<noteq> 0\"\n  and k: \"\\<And> k'. k' > k \\<Longrightarrow> \\<not> root_unity k' dvd p\"\nshows \"p = prod_root_unity ks' * f \\<and> f = g \\<and> set ks = set ks'\"\n  using d p k\nproof (induct p k arbitrary: ks ks' rule: decompose_prod_root_unity_main.induct)\n  case (1 p k ks ks')\n  note p = 1(4)\n  note k = 1(5)\n  from k[of \"Suc k\"] have p0: \"p \\<noteq> 0\" by auto\n  hence \"p = 0 \\<longleftrightarrow> False\" by auto\n  note d = 1(3)[unfolded decompose_prod_root_unity_main.simps[of p k] this if_False Let_def]\n  from p0[unfolded p] have ks0: \"0 \\<notin> set ks\" by simp\n  from f[of 1] have f0: \"f \\<noteq> 0\" by auto\n  note IH = 1(1)[OF _ refl _ p0] 1(2)[OF _ refl]\n  show ?case\n  proof (cases \"k = 0\")\n    case True\n    with p k[unfolded this, of \"hd ks\"] p0 have \"ks = []\"\n      by (cases ks, auto simp: prod_root_unity_def)\n    with d p True show ?thesis by (auto simp: prod_root_unity_def)\n  next\n    case k0: False\n    note IH = IH[OF k0]\n    from k0 have \"k = 0 \\<longleftrightarrow> False\" by auto\n    note d = d[unfolded this if_False]\n    let ?u = \"root_unity k :: complex poly\"\n    show ?thesis\n    proof (cases \"?u dvd p\")\n      case True\n      note IH = IH(1)[OF True]\n      let ?call = \"decompose_prod_root_unity_main (p div ?u) k\"\n      from True d obtain Ks where rec: \"?call = (Ks,g)\" and ks': \"ks' = (k # Ks)\"\n        by (cases ?call, auto)\n      from True have \"?u dvd p \\<longleftrightarrow> True\" by simp\n      note d = d[unfolded this if_True rec]\n      let ?x = \"cis (2 * pi / k)\"\n      have rt: \"poly ?u ?x = 0\" unfolding poly_root_unity using cis_times_2pi[of 1]\n        by (simp add: DeMoivre)\n      with True have \"poly p ?x = 0\" unfolding dvd_def by auto\n      from this[unfolded p] f[of ?x] rt have \"poly (prod_root_unity ks) ?x = 0\"\n        unfolding poly_root_unity by auto\n      from this[unfolded poly_prod_root_unity] ks0 obtain k' where k': \"k' \\<in> set ks\"\n        and rt: \"?x ^ k' = 1\" and k'0: \"k' \\<noteq> 0\" by auto\n      let ?u' = \"root_unity k' :: complex poly\"\n      from k' rt k'0 have rtk': \"poly ?u' ?x = 0\" unfolding poly_root_unity by auto\n      {\n        let ?phi = \" k' * (2 * pi / k)\"\n        assume \"k' < k\"\n        hence \"0 < ?phi\" \"?phi < 2 * pi\" using k0 k'0 by (auto simp: field_simps)\n        from cis_plus_2pi_neq_1[OF this] rtk'\n        have False unfolding poly_root_unity DeMoivre ..\n      }\n      hence kk': \"k \\<le> k'\" by presburger\n      {\n        assume \"k' > k\"\n        from k[OF this, unfolded p]\n        have \"\\<not> ?u' dvd prod_root_unity ks\" using dvd_mult2 by auto\n        with k' have False unfolding prod_root_unity_def\n          using prod_list_dvd[of ?u' \"map root_unity ks\"] by auto\n      }\n      with kk' have kk': \"k' = k\" by presburger\n      with k' have \"k \\<in> set ks\" by auto\n      from split_list[OF this] obtain ks1 ks2 where ks: \"ks = ks1 @ k # ks2\" by auto\n      hence \"p div ?u = (?u * (prod_root_unity (ks1 @ ks2) * f)) div ?u\"\n        by (simp add: ac_simps p prod_root_unity_def)\n      also have \"\\<dots> = prod_root_unity (ks1 @ ks2) * f\"\n        by (rule nonzero_mult_div_cancel_left, insert k0, auto)\n      finally have id: \"p div ?u = prod_root_unity (ks1 @ ks2) * f\" .\n      from d have ks': \"ks' = k # Ks\" by auto\n      have \"k < k' \\<Longrightarrow> \\<not> root_unity k' dvd p div ?u\" for k'\n        using k[of k'] True by (metis dvd_div_mult_self dvd_mult2)\n      from IH[OF rec id this]\n      have id: \"p div root_unity k = prod_root_unity Ks * f\" and\n        *: \"f = g \\<and> set (ks1 @ ks2) = set Ks\" by auto\n      from arg_cong[OF id, of \"\\<lambda> x. x * ?u\"] True\n      have \"p = prod_root_unity Ks * f * root_unity k\" by auto\n      thus ?thesis using * unfolding ks ks' by (auto simp: prod_root_unity_def)\n    next\n      case False\n      from d False have \"decompose_prod_root_unity_main p (k - 1) = (ks',g)\" by auto\n      note IH = IH(2)[OF False this p]\n      have k: \"k - 1 < k' \\<Longrightarrow> \\<not> root_unity k' dvd p\" for k' using False k[of k'] k0\n        by (cases \"k' = k\", auto)\n      show ?thesis by (rule IH, insert False k, auto)\n    qed\n  qed\nqed\n\ndefinition \"decompose_prod_root_unity p = decompose_prod_root_unity_main p (degree p)\"\n\nlemma decompose_prod_root_unity: fixes p :: \"complex poly\"\n  assumes p: \"p = prod_root_unity ks * f\"\n  and d: \"decompose_prod_root_unity p = (ks',g)\"\n  and f: \"\\<And> x. cmod x = 1 \\<Longrightarrow> poly f x \\<noteq> 0\"\n  and p0: \"p \\<noteq> 0\"\nshows \"p = prod_root_unity ks' * f \\<and> f = g \\<and> set ks = set ks'\"\nproof (rule decompose_prod_root_unity_main[OF p d[unfolded decompose_prod_root_unity_def] f])\n  fix k\n  assume deg: \"degree p < k\"\n  hence \"degree p < degree (root_unity k)\" by simp\n  with p0 show \"\\<not> root_unity k dvd p\"\n    by (simp add: poly_divides_conv0)\nqed\n\nlemma (in comm_ring_hom) hom_root_unity: \"map_poly hom (root_unity n) = root_unity n\"\nproof -\n  interpret p: map_poly_comm_ring_hom hom ..\n  show ?thesis unfolding root_unity_def\n    by (simp add: hom_distribs)\nqed\n\nlemma (in idom_hom) hom_prod_root_unity: \"map_poly hom (prod_root_unity n) = prod_root_unity n\"\nproof -\n  interpret p: map_poly_comm_ring_hom hom ..\n  show ?thesis unfolding prod_root_unity_def p.hom_prod_list map_map o_def hom_root_unity ..\nqed\n\nlemma (in field_hom) hom_decompose_prod_root_unity_main:\n  \"decompose_prod_root_unity_main (map_poly hom p) k = map_prod id (map_poly hom)\n    (decompose_prod_root_unity_main p k)\"\nproof (induct p k rule: decompose_prod_root_unity_main.induct)\n  case (1 p k)\n  let ?h = \"map_poly hom\"\n  let ?p = \"?h p\"\n  let ?u = \"root_unity k :: 'a poly\"\n  let ?u' = \"root_unity k :: 'b poly\"\n  interpret p: map_poly_inj_idom_divide_hom hom ..\n  have u': \"?u' = ?h ?u\" unfolding hom_root_unity ..\n  note simp = decompose_prod_root_unity_main.simps\n  let ?rec1 = \"decompose_prod_root_unity_main (p div ?u) k\"\n  have 0: \"?p = 0 \\<longleftrightarrow> p = 0\" by simp\n  show ?case\n    unfolding simp[of ?p k] simp[of p k] if_distrib[of \"map_prod id ?h\"] Let_def u'\n    unfolding 0 p.hom_div[symmetric] p.hom_dvd_iff\n    by (rule if_cong[OF refl], force, rule if_cong[OF refl if_cong[OF refl]], force,\n     (subst 1(1), auto, cases ?rec1, auto)[1],\n     (subst 1(2), auto))\nqed\n\nlemma (in field_hom) hom_decompose_prod_root_unity:\n  \"decompose_prod_root_unity (map_poly hom p) = map_prod id (map_poly hom)\n    (decompose_prod_root_unity p)\"\n  unfolding decompose_prod_root_unity_def\n  by (subst hom_decompose_prod_root_unity_main, simp)\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/Perron_Frobenius/Roots_Unity.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256472515684, "lm_q2_score": 0.8333246015211008, "lm_q1q2_score": 0.701514022046156}}
{"text": "theory Missing_Multiset2\n  imports \"HOL-Library.Multiset\" \"HOL-Library.Permutation\" \"HOL-Library.Permutations\"\n    Containers.Containers_Auxiliary (* only for a lemma *)\nbegin\n\nsubsubsection \\<open>Missing muiltiset\\<close>\n\nlemma id_imp_bij:\n  assumes id: \"\\<And>x. f (f x) = x\" shows \"bij f\"\nproof (intro bijI injI surjI[of f, OF id])\n  fix x y assume \"f x = f y\"\n  then have \"f (f x) = f (f y)\" by auto\n  with id show \"x = y\" by auto\nqed\n\nlemma rel_mset_Zero_iff[simp]:\n  shows \"rel_mset rel {#} Y \\<longleftrightarrow> Y = {#}\" and \"rel_mset rel X {#} \\<longleftrightarrow> X = {#}\"\n  using rel_mset_Zero rel_mset_size by (fastforce, fastforce)\n\ndefinition \"is_mset_set X \\<equiv> \\<forall>x \\<in># X. count X x = 1\"\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  unfolding is_mset_set_def\n  by (meson count_mset_set(1) count_mset_set(2) count_mset_set(3) not_in_iff)\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, hide_lams) 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\n\n\n\nlemma count_image_mset:\n  shows \"count (image_mset f X) y = (\\<Sum>x | x \\<in># X \\<and> y = f x. count X x)\"\nproof(induct X)\n  case empty show ?case by auto\nnext\n  case (add x X)\n    define X' where \"X' \\<equiv> X + {#x#}\"\n    have \"(\\<Sum>z | z \\<in># X' \\<and> y = f z. count (X + {#x#}) z) =\n          (\\<Sum>z | z \\<in># X' \\<and> y = f z. count X z) + (\\<Sum>z | z \\<in># X' \\<and> y = f z. count {#x#} z)\"\n      unfolding plus_multiset.rep_eq sum.distrib..\n    also have split:\n      \"{z. z \\<in># X' \\<and> y = f z} =\n       {z. z \\<in># X' \\<and> y = f z \\<and> z \\<noteq> x} \\<union> {z. z \\<in># X' \\<and> y = f z \\<and> z = x}\" by blast\n    then have \"(\\<Sum>z | z \\<in># X' \\<and> y = f z. count {#x#} z) =\n      (\\<Sum>z | z \\<in># X' \\<and> y = f z \\<and> z = x. count {#x#} z)\"\n      unfolding split by (subst sum.union_disjoint, auto)\n    also have \"... = (if y = f x then 1 else 0)\" using card_eq_Suc_0_ex1 by (auto simp: X'_def)\n    also have \"(\\<Sum>z | z \\<in># X' \\<and> y = f z. count X z) = (\\<Sum>z | z \\<in># X \\<and> y = f z. count X z)\"\n    proof(cases \"x \\<in># X\")\n      case True then have \"z \\<in># X' \\<longleftrightarrow> z \\<in># X\" for z by (auto simp: X'_def)\n      then show ?thesis by auto \n    next\n      case False\n        have split: \"{z. z \\<in># X' \\<and> y = f z} = {z. z \\<in># X \\<and> y = f z} \\<union> {z. z = x \\<and> y = f z}\"\n          by (auto simp: X'_def)\n        also have \"sum (count X) ... = (\\<Sum>z | z \\<in># X \\<and> y = f z. count X z) + (\\<Sum>z | z = x \\<and> y = f z. count X z)\"\n          by (subst sum.union_disjoint, auto simp: False)\n        also with False have \"\\<And>z. z = x \\<and> y = f z \\<Longrightarrow> count X z = 0\" by (meson count_inI)\n        with sum.neutral_const have \"(\\<Sum>z | z = x \\<and> y = f z. count X z) = 0\" by auto\n        finally show ?thesis by auto\n    qed\n    also have \"... = count (image_mset f X) y\" using add by auto\n    finally show ?case by (simp add: X'_def)  \nqed\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      unfolding count_image_mset by auto\n    also from X' x' have \"... = 1\" by auto\n    finally show \"count (image_mset f X') y = 1\".\n  qed\nqed\n\n(* a variant for \"right\" *)\n\n\n  define ysa where \"ysa = take j ys' @ drop (Suc j) ys'\"\n  have \"mset ys' = {#y#} + mset ysa\"\n    unfolding ysa_def using j_len nth_j\n    by (metis Cons_nth_drop_Suc union_mset_add_mset_right add_mset_remove_trivial add_diff_cancel_left'\n        append_take_drop_id mset.simps(2) mset_append)\n  hence ms_y: \"mset ysa = mset ys\"\n    by (simp add: Cons.prems)\n  then obtain xsa where\n    len_a: \"length ysa = length xsa\" and ms_a: \"mset (zip xsa ysa) = mset (zip xs ys)\"\n    using Cons.hyps(2) by blast\n\n  define xs' where \"xs' = take j xsa @ x # drop j xsa\"\n  have ys': \"ys' = take j ysa @ y # drop j ysa\"\n    using ms_y j_len nth_j Cons.prems ysa_def\n    by (metis append_eq_append_conv append_take_drop_id diff_Suc_Suc Cons_nth_drop_Suc length_Cons\n      length_drop size_mset)\n  have j_len': \"j \\<le> length ysa\"\n    using j_len ys' ysa_def\n    by (metis add_Suc_right append_take_drop_id length_Cons length_append less_eq_Suc_le not_less)\n  have \"length ys' = length xs'\"\n    unfolding xs'_def using Cons.prems len_a ms_y\n    by (metis add_Suc_right append_take_drop_id length_Cons length_append mset_eq_length)\n  moreover have \"mset (zip xs' ys') = mset (zip (x # xs) (y # ys))\"\n    unfolding ys' xs'_def\n    apply (rule HOL.trans[OF mset_zip_take_Cons_drop_twice])\n    using j_len' by (auto simp: len_a ms_a)\n  ultimately show ?case\n    by blast\nqed\n\nlemma list_all2_reorder_right_invariance:\n  assumes rel: \"list_all2 R xs ys\" and ms_y: \"mset ys' = mset ys\"\n  shows \"\\<exists>xs'. list_all2 R xs' ys' \\<and> mset xs' = mset xs\"\nproof -\n  have len: \"length xs = length ys\"\n    using rel list_all2_conv_all_nth by auto\n  obtain xs' where\n    len': \"length xs' = length ys'\" and ms_xy: \"mset (zip xs' ys') = mset (zip xs ys)\"\n    using len ms_y by (metis ex_mset_zip_right)\n  have \"list_all2 R xs' ys'\"\n    using assms(1) len' ms_xy unfolding list_all2_iff by (blast dest: mset_eq_setD)\n  moreover have \"mset xs' = mset xs\"\n    using len len' ms_xy map_fst_zip mset_map by metis\n  ultimately show ?thesis\n    by blast\nqed\n\nlemma rel_mset_via_perm: \"rel_mset rel (mset xs) (mset ys) \\<longleftrightarrow> (\\<exists>zs. perm xs zs \\<and> list_all2 rel zs ys)\"\nproof (unfold rel_mset_def, intro iffI, goal_cases)\n  case 1\n  then obtain zs ws where zs: \"mset zs = mset xs\" and ws: \"mset ws = mset ys\" and zsws: \"list_all2 rel zs ws\" by auto\n  note list_all2_reorder_right_invariance[OF zsws ws[symmetric], unfolded zs mset_eq_perm]\n  then show ?case using perm_sym by auto\nnext\n  case 2\n  from this[folded mset_eq_perm] show ?case by force\nqed\n\nlemma rel_mset_free:\n  assumes rel: \"rel_mset rel X Y\" and xs: \"mset xs = X\"\n  shows \"\\<exists>ys. mset ys = Y \\<and> list_all2 rel xs ys\"\nproof-\n  from rel[unfolded rel_mset_def] obtain xs' ys'\n    where xs': \"mset xs' = X\" and ys': \"mset ys' = Y\" and xsys': \"list_all2 rel xs' ys'\" by auto\n  from xs' xs have \"mset xs = mset xs'\" by auto\n  from mset_eq_permutation[OF this]\n  obtain f where perm: \"f permutes {..<length xs'}\" and xs': \"permute_list f xs' = xs\".\n  then have [simp]: \"length xs' = length xs\" by auto\n  from permute_list_nth[OF perm, unfolded xs'] have *: \"\\<And>i. i < length xs \\<Longrightarrow> xs ! i = xs' ! f i\" by auto\n  note [simp] = list_all2_lengthD[OF xsys',symmetric]\n  note [simp] = atLeast0LessThan[symmetric]\n  note bij =  permutes_bij[OF perm]\n  define ys where \"ys \\<equiv> map (nth ys' \\<circ> f) [0..<length ys']\"\n  then have [simp]: \"length ys = length ys'\" by auto \n  have \"mset ys = mset (map (nth ys') (map f [0..<length ys']))\"\n   unfolding ys_def by auto\n  also have \"... = image_mset (nth ys') (image_mset f (mset [0..<length ys']))\"\n    by (simp add: multiset.map_comp)\n  also have \"(mset [0..<length ys']) = mset_set {0..<length ys'}\"\n    by (metis mset_sorted_list_of_multiset sorted_list_of_mset_set sorted_list_of_set_range) \n  also have \"image_mset f (...) = mset_set (f ` {..<length ys'})\"\n    using subset_inj_on[OF bij_is_inj[OF bij]] by (subst image_mset_mset_set, auto)\n  also have \"... = mset [0..<length ys']\" using perm by (simp add: permutes_image)\n  also have \"image_mset (nth ys') ... = mset ys'\" by(fold mset_map, unfold map_nth, auto)\n  finally have \"mset ys = Y\" using ys' by auto\n  moreover have \"list_all2 rel xs ys\"\n  proof(rule list_all2_all_nthI)\n    fix i assume i: \"i < length xs\"\n    with * have \"xs ! i = xs' ! f i\" by auto\n    also from i permutes_in_image[OF perm]\n    have \"rel (xs' ! f i) (ys' ! f i)\" by (intro list_all2_nthD[OF xsys'], auto)\n    finally show \"rel (xs ! i) (ys ! i)\" unfolding ys_def using i by simp\n  qed simp\n  ultimately show ?thesis by auto\nqed\n\nlemma rel_mset_split:\n  assumes rel: \"rel_mset rel (X1+X2) Y\"\n  shows \"\\<exists>Y1 Y2. Y = Y1 + Y2 \\<and> rel_mset rel X1 Y1 \\<and> rel_mset rel X2 Y2\"\nproof-\n  obtain xs1 where xs1: \"mset xs1 = X1\" using ex_mset by auto\n  obtain xs2 where xs2: \"mset xs2 = X2\" using ex_mset by auto\n  from xs1 xs2 have \"mset (xs1 @ xs2) = X1 + X2\" by auto\n  from rel_mset_free[OF rel this] obtain ys\n    where ys: \"mset ys = Y\" \"list_all2 rel (xs1 @ xs2) ys\" by auto\n  then obtain ys1 ys2\n    where ys12: \"ys = ys1 @ ys2\"\n      and xs1ys1: \"list_all2 rel xs1 ys1\"\n      and xs2ys2: \"list_all2 rel xs2 ys2\"\n    using list_all2_append1 by blast\n  from ys12 ys have \"Y = mset ys1 + mset ys2\" by auto\n  moreover from xs1 xs1ys1 have \"rel_mset rel X1 (mset ys1)\" unfolding rel_mset_def by auto\n  moreover from xs2 xs2ys2 have \"rel_mset rel X2 (mset ys2)\" unfolding rel_mset_def by auto\n  ultimately show ?thesis by (subst exI[of _ \"mset ys1\"], subst exI[of _ \"mset ys2\"],auto)\nqed\n\nlemma rel_mset_OO:\n  assumes AB: \"rel_mset R A B\" and BC: \"rel_mset S B C\"\n  shows \"rel_mset (R OO S) A C\"\nproof-\n  from AB obtain as bs where A_as: \"A = mset as\" and B_bs: \"B = mset bs\" and as_bs: \"list_all2 R as bs\"\n    by (auto simp: rel_mset_def)\n  from rel_mset_free[OF BC] B_bs obtain cs where C_cs: \"C = mset cs\" and bs_cs: \"list_all2 S bs cs\"\n    by auto\n  from list_all2_trans[OF _ as_bs bs_cs, of \"R OO S\"] A_as C_cs\n  show ?thesis by (auto simp: rel_mset_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/Berlekamp_Zassenhaus/Missing_Multiset2.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245994514084, "lm_q2_score": 0.8418256412990657, "lm_q1q2_score": 0.7015140153434689}}
{"text": "(* Title:      Matrix Model of Kleene Algebra\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>Matrices\\<close>\n\ntheory Matrix\nimports \"HOL-Library.Word\" Dioid\nbegin\n\ntext \\<open>In this section we formalise a perhaps more natural version of\nmatrices of fixed dimension ($m \\times n$-matrices). It is well known\nthat such matrices over a Kleene algebra form a Kleene\nalgebra~\\cite{conway71regular}.\\<close>\n\nsubsection \\<open>Type Definition\\<close>\n\ntypedef (overloaded) 'a atMost = \"{..<LENGTH('a::len)}\"\nby auto\n\ndeclare Rep_atMost_inject [simp]\n\nlemma UNIV_atMost:\n  \"(UNIV::'a atMost set) = Abs_atMost ` {..<LENGTH('a::len)}\"\n apply auto\n apply (rule Abs_atMost_induct)\n apply auto\ndone\n\nlemma finite_UNIV_atMost [simp]: \"finite (UNIV::('a::len) atMost set)\"\n  by (simp add: UNIV_atMost)\n\ntext \\<open>Our matrix type is similar to \\mbox{\\<open>'a^'n^'m\\<close>} from\n{\\em HOL/Multivariate\\_Analysis/Finite\\_Cartesian\\_Product.thy}, but\n(i)~we explicitly define a type constructor for matrices and square\nmatrices, and (ii)~in the definition of operations, e.g., matrix\nmultiplication, we impose weaker sort requirements on the element\ntype.\\<close>\n\ncontext notes [[typedef_overloaded]]\nbegin\n\ndatatype ('a,'m,'n) matrix = Matrix \"'m atMost \\<Rightarrow> 'n atMost \\<Rightarrow> 'a\"\n\ndatatype ('a,'m) sqmatrix = SqMatrix \"'m atMost \\<Rightarrow> 'm atMost \\<Rightarrow> 'a\"\n\nend\n\nfun sqmatrix_of_matrix where\n  \"sqmatrix_of_matrix (Matrix A) = SqMatrix A\"\n\nfun matrix_of_sqmatrix where\n  \"matrix_of_sqmatrix (SqMatrix A) = Matrix A\"\n\n\nsubsection \\<open>0 and 1\\<close>\n\ninstantiation matrix :: (zero,type,type) zero\nbegin\n  definition zero_matrix_def: \"0 \\<equiv> Matrix (\\<lambda>i j. 0)\"\n  instance ..\nend\n\ninstantiation sqmatrix :: (zero,type) zero\nbegin\n  definition zero_sqmatrix_def: \"0 \\<equiv> SqMatrix (\\<lambda>i j. 0)\"\n  instance ..\nend\n\ntext \\<open>Tricky sort issues: compare @{term one_matrix} with @{term\none_sqmatrix} \\dots\\<close>\n\ninstantiation matrix :: (\"{zero,one}\",len,len) one\nbegin\n  definition one_matrix_def:\n    \"1 \\<equiv> Matrix (\\<lambda>i j. if Rep_atMost i = Rep_atMost j then 1 else 0)\"\n  instance ..\nend\n\ninstantiation sqmatrix :: (\"{zero,one}\",type) one\nbegin\n  definition one_sqmatrix_def:\n    \"1 \\<equiv> SqMatrix (\\<lambda>i j. if i = j then 1 else 0)\"\n  instance ..\nend\n\n\nsubsection \\<open>Matrix Addition\\<close>\n\nfun matrix_plus where\n  \"matrix_plus (Matrix A) (Matrix B) = Matrix (\\<lambda>i j. A i j + B i j)\"\n\ninstantiation matrix :: (plus,type,type) plus\nbegin\n  definition plus_matrix_def: \"A + B \\<equiv> matrix_plus A B\"\n  instance ..\nend\n\nlemma plus_matrix_def' [simp]:\n  \"Matrix A + Matrix B = Matrix (\\<lambda>i j. A i j + B i j)\"\n  by (simp add: plus_matrix_def)\n\ninstantiation sqmatrix :: (plus,type) plus\nbegin\n  definition plus_sqmatrix_def:\n    \"A + B \\<equiv> sqmatrix_of_matrix (matrix_of_sqmatrix A + matrix_of_sqmatrix B)\"\n  instance ..\nend\n\nlemma plus_sqmatrix_def' [simp]:\n  \"SqMatrix A + SqMatrix B = SqMatrix (\\<lambda>i j. A i j + B i j)\"\n  by (simp add: plus_sqmatrix_def)\n\nlemma matrix_add_0_right [simp]:\n  \"A + 0 = (A::('a::monoid_add,'m,'n) matrix)\"\n  by (cases A, simp add: zero_matrix_def)\n\nlemma matrix_add_0_left [simp]:\n  \"0 + A = (A::('a::monoid_add,'m,'n) matrix)\"\n  by (cases A, simp add: zero_matrix_def)\n\nlemma matrix_add_commute [simp]:\n  \"(A::('a::ab_semigroup_add,'m,'n) matrix) + B = B + A\"\n  by (cases A, cases B, simp add: add.commute)\n\nlemma matrix_add_assoc:\n  \"(A::('a::semigroup_add,'m,'n) matrix) + B + C = A + (B + C)\"\n  by (cases A, cases B, cases C, simp add: add.assoc)\n\nlemma matrix_add_left_commute [simp]:\n  \"(A::('a::ab_semigroup_add,'m,'n) matrix) + (B + C) = B + (A + C)\"\n  by (metis matrix_add_assoc matrix_add_commute)\n\nlemma sqmatrix_add_0_right [simp]:\n  \"A + 0 = (A::('a::monoid_add,'m) sqmatrix)\"\n  by (cases A, simp add: zero_sqmatrix_def)\n\nlemma sqmatrix_add_0_left [simp]:\n  \"0 + A = (A::('a::monoid_add,'m) sqmatrix)\"\n  by (cases A, simp add: zero_sqmatrix_def)\n\nlemma sqmatrix_add_commute [simp]:\n  \"(A::('a::ab_semigroup_add,'m) sqmatrix) + B = B + A\"\n  by (cases A, cases B, simp add: add.commute)\n\nlemma sqmatrix_add_assoc:\n  \"(A::('a::semigroup_add,'m) sqmatrix) + B + C = A + (B + C)\"\n  by (cases A, cases B, cases C, simp add: add.assoc)\n\nlemma sqmatrix_add_left_commute [simp]:\n  \"(A::('a::ab_semigroup_add,'m) sqmatrix) + (B + C) = B + (A + C)\"\n  by (metis sqmatrix_add_commute sqmatrix_add_assoc)\n\n\nsubsection \\<open>Order (via Addition)\\<close>\n\ninstantiation matrix :: (plus,type,type) plus_ord\nbegin\n  definition less_eq_matrix_def:\n    \"(A::('a, 'b, 'c) matrix) \\<le> B \\<equiv> A + B = B\"\n  definition less_matrix_def:\n    \"(A::('a, 'b, 'c) matrix) < B \\<equiv> A \\<le> B \\<and> A \\<noteq> B\"\n\n  instance\n  proof\n    fix A B :: \"('a, 'b, 'c) matrix\"\n    show \"A \\<le> B \\<longleftrightarrow> A + B = B\"\n      by (metis less_eq_matrix_def)\n    show \"A < B \\<longleftrightarrow> A \\<le> B \\<and> A \\<noteq> B\"\n      by (metis less_matrix_def)\n  qed\nend\n\ninstantiation sqmatrix :: (plus,type) plus_ord\nbegin\n  definition less_eq_sqmatrix_def:\n    \"(A::('a, 'b) sqmatrix) \\<le> B \\<equiv> A + B = B\"\n  definition less_sqmatrix_def:\n    \"(A::('a, 'b) sqmatrix) < B \\<equiv> A \\<le> B \\<and> A \\<noteq> B\"\n\n  instance\n  proof\n    fix A B :: \"('a, 'b) sqmatrix\"\n    show \"A \\<le> B \\<longleftrightarrow> A + B = B\"\n      by (metis less_eq_sqmatrix_def)\n    show \"A < B \\<longleftrightarrow> A \\<le> B \\<and> A \\<noteq> B\"\n      by (metis less_sqmatrix_def)\n  qed\nend\n\n\nsubsection \\<open>Matrix Multiplication\\<close>\n\nfun matrix_times :: \"('a::{comm_monoid_add,times},'m,'k) matrix \\<Rightarrow> ('a,'k,'n) matrix \\<Rightarrow> ('a,'m,'n) matrix\" where\n  \"matrix_times (Matrix A) (Matrix B) = Matrix (\\<lambda>i j. sum (\\<lambda>k. A i k * B k j) (UNIV::'k atMost set))\"\n\nnotation matrix_times (infixl \"*\\<^sub>M\" 70)\n\ninstantiation sqmatrix :: (\"{comm_monoid_add,times}\",type) times\nbegin\n  definition times_sqmatrix_def:\n    \"A * B = sqmatrix_of_matrix (matrix_of_sqmatrix A *\\<^sub>M matrix_of_sqmatrix B)\"\n  instance ..\nend\n\nlemma times_sqmatrix_def' [simp]:\n  \"SqMatrix A * SqMatrix B = SqMatrix (\\<lambda>i j. sum (\\<lambda>k. A i k * B k j) (UNIV::'k atMost set))\"\n  by (simp add: times_sqmatrix_def)\n\nlemma matrix_mult_0_right [simp]:\n  \"(A::('a::{comm_monoid_add,mult_zero},'m,'n) matrix) *\\<^sub>M 0 = 0\"\n  by (cases A, simp add: zero_matrix_def)\n\nlemma matrix_mult_0_left [simp]:\n  \"0 *\\<^sub>M (A::('a::{comm_monoid_add,mult_zero},'m,'n) matrix) = 0\"\n  by (cases A, simp add: zero_matrix_def)\n\nlemma sum_delta_r_0 [simp]:\n  \"\\<lbrakk> finite S; j \\<notin> S \\<rbrakk> \\<Longrightarrow> (\\<Sum>k\\<in>S. f k * (if k = j then 1 else (0::'b::{semiring_0,monoid_mult}))) = 0\"\n  by (induct S rule: finite_induct, auto)\n\nlemma sum_delta_r_1 [simp]:\n  \"\\<lbrakk> finite S; j \\<in> S \\<rbrakk> \\<Longrightarrow> (\\<Sum>k\\<in>S. f k * (if k = j then 1 else (0::'b::{semiring_0,monoid_mult}))) = f j\"\n  by (induct S rule: finite_induct, auto)\n\nlemma matrix_mult_1_right [simp]:\n  \"(A::('a::{semiring_0,monoid_mult},'m::len,'n::len) matrix) *\\<^sub>M 1 = A\"\n  by (cases A, simp add: one_matrix_def)\n\nlemma sum_delta_l_0 [simp]:\n  \"\\<lbrakk> finite S; i \\<notin> S \\<rbrakk> \\<Longrightarrow> (\\<Sum>k\\<in>S. (if i = k then 1 else (0::'b::{semiring_0,monoid_mult})) * f k j) = 0\"\n  by (induct S rule: finite_induct, auto)\n\nlemma sum_delta_l_1 [simp]:\n  \"\\<lbrakk> finite S; i \\<in> S \\<rbrakk> \\<Longrightarrow> (\\<Sum>k\\<in>S. (if i = k then 1 else (0::'b::{semiring_0,monoid_mult})) * f k j) = f i j\"\n  by (induct S rule: finite_induct, auto)\n\nlemma matrix_mult_1_left [simp]:\n  \"1 *\\<^sub>M (A::('a::{semiring_0,monoid_mult},'m::len,'n::len) matrix) = A\"\n  by (cases A, simp add: one_matrix_def)\n\nlemma matrix_mult_assoc:\n  \"(A::('a::semiring_0,'m,'n) matrix) *\\<^sub>M B *\\<^sub>M C = A *\\<^sub>M (B *\\<^sub>M C)\"\n apply (cases A)\n apply (cases B)\n apply (cases C)\n apply (simp add: sum_distrib_right sum_distrib_left mult.assoc)\n apply (subst sum.swap)\n apply (rule refl)\ndone\n\nlemma matrix_mult_distrib_left:\n  \"(A::('a::{comm_monoid_add,semiring},'m,'n::len) matrix) *\\<^sub>M (B + C) = A *\\<^sub>M B + A *\\<^sub>M C\"\n  by (cases A, cases B, cases C, simp add: distrib_left sum.distrib)\n\nlemma matrix_mult_distrib_right:\n  \"((A::('a::{comm_monoid_add,semiring},'m,'n::len) matrix) + B) *\\<^sub>M C = A *\\<^sub>M C + B *\\<^sub>M C\"\n  by (cases A, cases B, cases C, simp add: distrib_right sum.distrib)\n\nlemma sqmatrix_mult_0_right [simp]:\n  \"(A::('a::{comm_monoid_add,mult_zero},'m) sqmatrix) * 0 = 0\"\n  by (cases A, simp add: zero_sqmatrix_def)\n\nlemma sqmatrix_mult_0_left [simp]:\n  \"0 * (A::('a::{comm_monoid_add,mult_zero},'m) sqmatrix) = 0\"\n  by (cases A, simp add: zero_sqmatrix_def)\n\nlemma sqmatrix_mult_1_right [simp]:\n  \"(A::('a::{semiring_0,monoid_mult},'m::len) sqmatrix) * 1 = A\"\n  by (cases A, simp add: one_sqmatrix_def)\n\nlemma sqmatrix_mult_1_left [simp]:\n  \"1 * (A::('a::{semiring_0,monoid_mult},'m::len) sqmatrix) = A\"\n  by (cases A, simp add: one_sqmatrix_def)\n\nlemma sqmatrix_mult_assoc:\n  \"(A::('a::{semiring_0,monoid_mult},'m) sqmatrix) * B * C = A * (B * C)\"\n apply (cases A)\n apply (cases B)\n apply (cases C)\n apply (simp add: sum_distrib_right sum_distrib_left mult.assoc)\n apply (subst sum.swap)\n apply (rule refl)\ndone\n\nlemma sqmatrix_mult_distrib_left:\n  \"(A::('a::{comm_monoid_add,semiring},'m::len) sqmatrix) * (B + C) = A * B + A * C\"\n  by (cases A, cases B, cases C, simp add: distrib_left sum.distrib)\n\nlemma sqmatrix_mult_distrib_right:\n  \"((A::('a::{comm_monoid_add,semiring},'m::len) sqmatrix) + B) * C = A * C + B * C\"\n  by (cases A, cases B, cases C, simp add: distrib_right sum.distrib)\n\n\nsubsection \\<open>Square-Matrix Model of Dioids\\<close>\n\ntext \\<open>The following subclass proofs are necessary to connect parts\nof our algebraic hierarchy to the hierarchy found in the Isabelle/HOL\nlibrary.\\<close>\n\nsubclass (in ab_near_semiring_one_zerol) comm_monoid_add\nproof\n  fix a :: 'a\n  show \"0 + a = a\"\n    by (fact add_zerol)\nqed\n\nsubclass (in semiring_one_zero) semiring_0\nproof\n  fix a :: 'a\n  show \"0 * a = 0\"\n    by (fact annil)\n  show \"a * 0 = 0\"\n    by (fact annir)\nqed\n\nsubclass (in ab_near_semiring_one) monoid_mult ..\n\ninstantiation sqmatrix :: (dioid_one_zero,len) dioid_one_zero\nbegin\n  instance\n  proof\n    fix A B C :: \"('a, 'b) sqmatrix\"\n    show \"A + B + C = A + (B + C)\"\n      by (fact sqmatrix_add_assoc)\n    show \"A + B = B + A\"\n      by (fact sqmatrix_add_commute)\n    show \"A * B * C = A * (B * C)\"\n      by (fact sqmatrix_mult_assoc)\n    show \"(A + B) * C = A * C + B * C\"\n      by (fact sqmatrix_mult_distrib_right)\n    show \"1 * A = A\"\n      by (fact sqmatrix_mult_1_left)\n    show \"A * 1 = A\"\n      by (fact sqmatrix_mult_1_right)\n    show \"0 + A = A\"\n      by (fact sqmatrix_add_0_left)\n    show \"0 * A = 0\"\n      by (fact sqmatrix_mult_0_left)\n    show \"A * 0 = 0\"\n      by (fact sqmatrix_mult_0_right)\n    show \"A + A = A\"\n      by (cases A, simp)\n    show \"A * (B + C) = A * B + A * C\"\n      by (fact sqmatrix_mult_distrib_left)\n  qed\nend\n\nsubsection \\<open>Kleene Star for Matrices\\<close>\n\ntext \\<open>We currently do not implement the Kleene star of matrices,\nsince this is complicated.\\<close>\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/Kleene_Algebra/Matrix.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.833324587033253, "lm_q2_score": 0.8418256512199033, "lm_q1q2_score": 0.7015140131568252}}
{"text": "(* Title: Negligible.thy\n  Author: Andreas Lochbihler, ETH Zurich *)\n\nsection \\<open>Negligibility\\<close>\n\ntheory Negligible imports\n  Complex_Main\n  Landau_Symbols.Landau_More\nbegin\n\nnamed_theorems negligible_intros\n\ndefinition negligible :: \"(nat \\<Rightarrow> real) \\<Rightarrow> bool\" (* TODO: generalise types? *)\nwhere \"negligible f \\<longleftrightarrow> (\\<forall>c>0. f \\<in> o(\\<lambda>x. inverse (x powr c)))\"\n\n\n\nlemma negligibleD:\n  \"\\<lbrakk> negligible f; c > 0 \\<rbrakk> \\<Longrightarrow> f \\<in> o(\\<lambda>x. inverse (x powr c))\"\nunfolding negligible_def by(simp)\n\nlemma negligibleD_real:\n  assumes \"negligible f\"\n  shows \"f \\<in> o(\\<lambda>x. inverse (x powr c))\"\nproof -\n  let ?c = \"max 1 c\"\n  have \"f \\<in> o(\\<lambda>x. inverse (x powr ?c))\" using assms by(rule negligibleD) simp\n  also have \"(\\<lambda>x. x powr c) \\<in> O(\\<lambda>x. real x powr max 1 c)\"\n    by(rule bigoI[where c=1])(auto simp add: eventually_at_top_linorder intro!: exI[where x=1] powr_mono)\n  then have \"(\\<lambda>x. inverse (real x powr max 1 c)) \\<in> O(\\<lambda>x. inverse (x powr c))\"\n    by(auto simp add: eventually_at_top_linorder exI[where x=1] intro: landau_o.big.inverse)\n  finally show ?thesis .\nqed\n\nlemma negligible_mono: \"\\<lbrakk> negligible g; f \\<in> O(g) \\<rbrakk> \\<Longrightarrow> negligible f\"\nby(rule negligibleI)(drule (1) negligibleD; erule (1) landau_o.big_small_trans)\n\nlemma negligible_le: \"\\<lbrakk> negligible g; \\<And>\\<eta>. \\<bar>f \\<eta>\\<bar> \\<le> g \\<eta> \\<rbrakk> \\<Longrightarrow> negligible f\"\nby(erule negligible_mono)(force intro: order_trans intro!: eventually_sequentiallyI landau_o.big_mono)\n\nlemma negligible_K0 [negligible_intros, simp, intro!]: \"negligible (\\<lambda>_. 0)\"\nby(rule negligibleI) simp\n\nlemma negligible_0 [negligible_intros, simp, intro!]: \"negligible 0\"\nby(simp add: zero_fun_def)\n\nlemma negligible_const_iff [simp]: \"negligible (\\<lambda>_. c :: real) \\<longleftrightarrow> c = 0\"\nby(auto simp add: negligible_def const_smallo_inverse_powr filterlim_real_sequentially dest!: spec[where x=1])\n\nlemma not_negligible_1: \"\\<not> negligible (\\<lambda>_. 1 :: real)\"\nby simp\n\nlemma negligible_plus [negligible_intros]:\n  \"\\<lbrakk> negligible f; negligible g \\<rbrakk> \\<Longrightarrow> negligible (\\<lambda>\\<eta>. f \\<eta> + g \\<eta>)\"\nby(auto intro!: negligibleI dest!: negligibleD intro: sum_in_smallo)\n\nlemma negligible_uminus [simp]: \"negligible (\\<lambda>\\<eta>. - f \\<eta>) \\<longleftrightarrow> negligible f\"\nby(simp add: negligible_def)\n\nlemma negligible_uminusI [negligible_intros]: \"negligible f \\<Longrightarrow> negligible (\\<lambda>\\<eta>. - f \\<eta>)\"\nby simp\n\nlemma negligible_minus [negligible_intros]:\n  \"\\<lbrakk> negligible f; negligible g \\<rbrakk> \\<Longrightarrow> negligible (\\<lambda>\\<eta>. f \\<eta> - g \\<eta>)\"\nby(auto simp add: uminus_add_conv_diff[symmetric] negligible_plus simp del: uminus_add_conv_diff)\n\nlemma negligible_cmult: \"negligible (\\<lambda>\\<eta>. c * f \\<eta>) \\<longleftrightarrow> negligible f \\<or> c = 0\"\nby(auto intro!: negligibleI dest!: negligibleD)\n\nlemma negligible_cmultI [negligible_intros]:\n  \"(c \\<noteq> 0 \\<Longrightarrow> negligible f) \\<Longrightarrow> negligible (\\<lambda>\\<eta>. c * f \\<eta>)\"\nby(auto simp add: negligible_cmult)\n\nlemma negligible_multc: \"negligible (\\<lambda>\\<eta>. f \\<eta> * c) \\<longleftrightarrow> negligible f \\<or> c = 0\"\nby(subst mult.commute)(simp add: negligible_cmult)\n\nlemma negligible_multcI [negligible_intros]:\n  \"(c \\<noteq> 0 \\<Longrightarrow> negligible f) \\<Longrightarrow> negligible (\\<lambda>\\<eta>. f \\<eta> * c)\"\nby(auto simp add: negligible_multc)\n\nlemma negligible_times [negligible_intros]:\n  assumes f: \"negligible f\"\n  and g: \"negligible g\"\n  shows \"negligible (\\<lambda>\\<eta>. f \\<eta> * g \\<eta> :: real)\"\nproof\n  fix c :: real\n  assume \"0 < c\"\n  hence \"0 < c / 2\" by simp\n  from negligibleD[OF f this] negligibleD[OF g this]\n  have \"(\\<lambda>\\<eta>. f \\<eta> * g \\<eta>) \\<in> o(\\<lambda>x. inverse (x powr (c / 2)) * inverse (x powr (c / 2)))\"\n    by(rule landau_o.small_mult)\n  also have \"\\<dots> = o(\\<lambda>x. inverse (x powr c))\"\n    by(rule landau_o.small.cong)(auto simp add: inverse_mult_distrib[symmetric] powr_add[symmetric] eventually_at_top_linorder intro!: exI[where x=1] simp del: inverse_mult_distrib)\n  finally show \"(\\<lambda>\\<eta>. f \\<eta> * g \\<eta>) \\<in> \\<dots>\" .\nqed\n\nlemma negligible_power [negligible_intros]:\n  assumes \"negligible f\"\n  and \"n > 0\"\n  shows \"negligible (\\<lambda>\\<eta>. f \\<eta> ^ n :: real)\"\nusing \\<open>n > 0\\<close>\nproof(induct n)\n  case (Suc n)\n  thus ?case using \\<open>negligible f\\<close> by(cases n)(simp_all add: negligible_times)\nqed simp\n\nlemma negligible_powr [negligible_intros]:\n  assumes f: \"negligible f\"\n  and p: \"p > 0\"         \n  shows \"negligible (\\<lambda>x. \\<bar>f x\\<bar> powr p :: real)\"\nproof\n  fix c :: real\n  let ?c = \"c / p\"\n  assume c: \"0 < c\"\n  with p have \"0 < ?c\" by simp\n  with f have \"f \\<in> o(\\<lambda>x. inverse (x powr ?c))\" by(rule negligibleD)\n  hence \"(\\<lambda>x. \\<bar>f x\\<bar> powr p) \\<in> o(\\<lambda>x. \\<bar>inverse (x powr ?c)\\<bar> powr p)\" using p by(rule smallo_powr)\n  also have \"\\<dots> = o(\\<lambda>x. inverse (x powr c))\"\n    apply(rule landau_o.small.cong) using p by(auto simp add: powr_powr)\n  finally show \"(\\<lambda>x. \\<bar>f x\\<bar> powr p) \\<in> \\<dots>\" .\nqed\n\nlemma negligible_abs [simp]: \"negligible (\\<lambda>x. \\<bar>f x\\<bar>) \\<longleftrightarrow> negligible f\"\nby(simp add: negligible_def)\n\nlemma negligible_absI [negligible_intros]: \"negligible f \\<Longrightarrow> negligible (\\<lambda>x. \\<bar>f x\\<bar>)\"\nby(simp)\n\nlemma negligible_powrI [negligible_intros]:\n  assumes \"0 \\<le> k\" \"k < 1\"\n  shows \"negligible (\\<lambda>x. k powr x)\"\nproof(cases \"k = 0\")\n  case True\n  thus ?thesis by simp\nnext\n  case False\n  show ?thesis\n  proof\n    fix c :: real\n    assume \"0 < c\"\n    then have \"(\\<lambda>x. real x powr c) \\<in> o(\\<lambda>x. inverse k powr real x)\" using assms False\n      by(intro powr_fast_growth_tendsto)(simp_all add: one_less_inverse_iff filterlim_real_sequentially)\n    then have \"(\\<lambda>x. inverse (k powr - real x)) \\<in> o(\\<lambda>x. inverse (real x powr c))\" using assms\n      by(intro landau_o.small.inverse)(auto simp add: False eventually_sequentially powr_minus intro: exI[where x=1])\n    also have \"(\\<lambda>x. inverse (k powr - real x)) = (\\<lambda>x. k powr real x)\" by(simp add: powr_minus)\n    finally show \"\\<dots> \\<in> o(\\<lambda>x. inverse (x powr c))\" .\n  qed\nqed\n\nlemma negligible_powerI [negligible_intros]:\n  fixes k :: real\n  assumes \"\\<bar>k\\<bar> < 1\"\n  shows \"negligible (\\<lambda>n. k ^ n)\"\nproof(cases \"k = 0\")\n  case True\n  show ?thesis using negligible_K0\n    by(rule negligible_mono)(auto intro: exI[where x=1] simp add: True eventually_at_top_linorder)\nnext\n  case False\n  hence \"0 < \\<bar>k\\<bar>\" by auto\n  from assms have \"negligible (\\<lambda>x. \\<bar>k\\<bar> powr real x)\" using negligible_powrI[of \"\\<bar>k\\<bar>\"] by simp\n  hence \"negligible (\\<lambda>x. \\<bar>k\\<bar> ^ x)\" using False\n    by(elim negligible_mono)(simp add: powr_realpow)\n  then show ?thesis by(simp add: power_abs[symmetric])\nqed\n\nlemma negligible_inverse_powerI [negligible_intros]: \"\\<bar>k\\<bar> > 1 \\<Longrightarrow> negligible (\\<lambda>\\<eta>. 1 / k ^ \\<eta>)\"\nusing negligible_powerI[of \"1 / k\"] by(simp add: power_one_over)\n\ninductive polynomial :: \"(nat \\<Rightarrow> real) \\<Rightarrow> bool\"\n  for f\nwhere \"f \\<in> O(\\<lambda>x. x powr n) \\<Longrightarrow> polynomial f\"\n\n\n\nlemma negligible_poly_times:\n  \"\\<lbrakk> f \\<in> O(\\<lambda>x. x powr n); negligible g \\<rbrakk> \\<Longrightarrow> negligible (\\<lambda>x. f x * g x)\"\nby(subst mult.commute)(rule negligible_times_poly)\n\nlemma negligible_times_polynomial [negligible_intros]:\n  \"\\<lbrakk> negligible f; polynomial g \\<rbrakk> \\<Longrightarrow> negligible (\\<lambda>x. f x * g x)\"\nby(clarsimp simp add: polynomial.simps negligible_times_poly)\n\nlemma negligible_polynomial_times [negligible_intros]:\n  \"\\<lbrakk> polynomial f; negligible g \\<rbrakk> \\<Longrightarrow> negligible (\\<lambda>x. f x * g x)\"\nby(clarsimp simp add: polynomial.simps negligible_poly_times)\n\nlemma negligible_divide_poly1:\n  \"\\<lbrakk> f \\<in> O(\\<lambda>x. x powr n); negligible (\\<lambda>\\<eta>. 1 / g \\<eta>) \\<rbrakk> \\<Longrightarrow> negligible (\\<lambda>\\<eta>. real (f \\<eta>) / g \\<eta>)\"\nby(drule (1) negligible_times_poly) simp\n\nlemma negligible_divide_polynomial1 [negligible_intros]:\n  \"\\<lbrakk> polynomial f; negligible (\\<lambda>\\<eta>. 1 / g \\<eta>) \\<rbrakk> \\<Longrightarrow> negligible (\\<lambda>\\<eta>. real (f \\<eta>) / g \\<eta>)\"\nby(clarsimp simp add: polynomial.simps negligible_divide_poly1)\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/CryptHOL/Negligible.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8418256393148982, "lm_q2_score": 0.8333245932423308, "lm_q1q2_score": 0.7015140084630526}}
{"text": "section \\<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\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", "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/List_Ins_Del.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8902942319436397, "lm_q2_score": 0.7879311856832191, "lm_q1q2_score": 0.7014905897822828}}
{"text": "theory Szip_iterates\n  imports Main \"$HIPSTER_HOME/IsaHipster\"\nbegin\n  \nsetup Tactic_Data.set_coinduct_sledgehammer  \ncodatatype (sset: 'a) Stream =\n  SCons (shd: 'a) (stl: \"'a Stream\")\ndatatype ('a, 'b) Pair2 = Pair2 'a 'b\nprimcorec szip :: \"'a Stream \\<Rightarrow> 'b Stream \\<Rightarrow> (('a, 'b) Pair2) Stream\" where\n  \"shd (szip s1 s2) = Pair2 (shd s1) (shd s2)\"\n| \"stl (szip s1 s2) = szip (stl s1) (stl s2)\"\n\nprimcorec siterate :: \"('a \\<Rightarrow> 'a) \\<Rightarrow> 'a \\<Rightarrow> 'a Stream\" where\n  \"shd (siterate f x) = x\"\n| \"stl (siterate f x) = siterate f (f x)\"  \n\nfun map_prod2 :: \"('a \\<Rightarrow> 'c) \\<Rightarrow> ('b \\<Rightarrow> 'd) \\<Rightarrow> ('a,'b) Pair2 \\<Rightarrow> ('c,'d) Pair2\" where\n\"map_prod2 f g (Pair2 a b) = Pair2 (f a) (g b)\"\n\ndatatype 'a Lst = \n  Emp\n  | Cons \"'a\" \"'a Lst\"\n    \nfun obsStream :: \"int \\<Rightarrow> 'a Stream \\<Rightarrow> 'a Lst\" where\n\"obsStream n s = (if (n \\<le> 0) then Emp else Cons (shd s) (obsStream (n - 1) (stl s)))\"\n\nhipster_obs Stream Lst obsStream szip siterate map_prod2\n(*  Proving: map_prod2 z z (Pair22 y x2) = Pair22 (z y) (z x2) *)\n\ntheorem szip_iterates:\n  \"szip (siterate f a) (siterate g b) = siterate (map_prod2 f g) (Pair2 a b)\"\n  by 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_Stream/Szip_iterates.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8962513786759491, "lm_q2_score": 0.7826624789529375, "lm_q1q2_score": 0.7014623257995062}}
{"text": "section \\<open> Multiplication Groups \\<close>\n\ntheory Groups_mult\n  imports Main\nbegin\n\ntext \\<open> The HOL standard library only has groups based on addition. Here, we build one based on\n  multiplication. \\<close>\n\nnotation times (infixl \"\\<cdot>\" 70)\n\nclass group_mult = inverse + monoid_mult +\n  assumes left_inverse: \"inverse a \\<cdot> a = 1\"\n  assumes multi_inverse_conv_div [simp]: \"a \\<cdot> (inverse b) = a / b\"\nbegin\n\nlemma div_conv_mult_inverse: \"a / b = a \\<cdot> (inverse b)\"\n  by simp\n\nsublocale mult: group times 1 inverse\n  by standard (simp_all add: left_inverse)\n\nlemma diff_self [simp]: \"a / a = 1\"\n  using mult.right_inverse by auto\n\nlemma mult_distrib_inverse [simp]: \"(a * b) / b = a\"\n  by (metis local.mult_1_right local.multi_inverse_conv_div mult.right_inverse mult_assoc)\n\nend\n\nclass ab_group_mult = comm_monoid_mult + group_mult\nbegin\n\nlemma mult_distrib_inverse' [simp]: \"(a * b) / a = b\"\n  using local.mult_distrib_inverse mult_commute by fastforce\n\nlemma inverse_distrib: \"inverse (a * b)  =  (inverse a) * (inverse b)\"\n  by (simp add: local.mult.inverse_distrib_swap mult_commute)\n\nlemma inverse_divide [simp]: \"inverse (a / b) = b / a\"\n  by (metis div_conv_mult_inverse inverse_distrib mult.commute mult.inverse_inverse)\n\nend\n\nabbreviation (input) npower :: \"'a::{power,inverse} \\<Rightarrow> nat \\<Rightarrow> 'a\"  (\"(_\\<^sup>-\\<^sup>_)\" [1000,999] 999) \n  where \"npower x n \\<equiv> inverse (x ^ 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/Physical_Quantities/Groups_mult.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8962513620489619, "lm_q2_score": 0.782662489091802, "lm_q1q2_score": 0.7014623218731584}}
{"text": "(*  Title:      HOL/Cardinals/Cardinal_Arithmetic.thy\n    Author:     Dmitriy Traytel, TU Muenchen\n    Copyright   2012\n\nCardinal arithmetic.\n*)\n\nsection \\<open>Cardinal Arithmetic\\<close>\n\ntheory Cardinal_Arithmetic\nimports Cardinal_Order_Relation\nbegin\n\nsubsection \\<open>Binary sum\\<close>\n\nlemma csum_Cnotzero2:\n  \"Cnotzero r2 \\<Longrightarrow> Cnotzero (r1 +c r2)\"\nunfolding csum_def\nby (metis Cnotzero_imp_not_empty Field_card_of Plus_eq_empty_conv card_of_card_order_on czeroE)\n\nlemma single_cone:\n  \"|{x}| =o cone\"\nproof -\n  let ?f = \"\\<lambda>x. ()\"\n  have \"bij_betw ?f {x} {()}\" unfolding bij_betw_def by auto\n  thus ?thesis unfolding cone_def using card_of_ordIso by blast\nqed\n\nlemma cone_Cnotzero: \"Cnotzero cone\"\nby (simp add: cone_not_czero Card_order_cone)\n\nlemma cone_ordLeq_ctwo: \"cone \\<le>o ctwo\"\nunfolding cone_def ctwo_def card_of_ordLeq[symmetric] by auto\n\nlemma csum_czero1: \"Card_order r \\<Longrightarrow> r +c czero =o r\"\n  unfolding czero_def csum_def Field_card_of\n  by (rule ordIso_transitive[OF ordIso_symmetric[OF card_of_Plus_empty1] card_of_Field_ordIso])\n\nlemma csum_czero2: \"Card_order r \\<Longrightarrow> czero +c r =o r\"\n  unfolding czero_def csum_def Field_card_of\n  by (rule ordIso_transitive[OF ordIso_symmetric[OF card_of_Plus_empty2] card_of_Field_ordIso])\n\n\nsubsection \\<open>Product\\<close>\n\nlemma Times_cprod: \"|A \\<times> B| =o |A| *c |B|\"\nby (simp only: cprod_def Field_card_of card_of_refl)\n\nlemma card_of_Times_singleton:\n  fixes A :: \"'a set\"\n  shows \"|A \\<times> {x}| =o |A|\"\nproof -\n  define f :: \"'a \\<times> 'b \\<Rightarrow> 'a\" where \"f = (\\<lambda>(a, b). a)\"\n  have \"A \\<subseteq> f ` (A \\<times> {x})\" unfolding f_def by (auto simp: image_iff)\n  hence \"bij_betw f (A \\<times> {x}) A\"  unfolding bij_betw_def inj_on_def f_def by fastforce\n  thus ?thesis using card_of_ordIso by blast\nqed\n\nlemma cprod_assoc: \"(r *c s) *c t =o r *c s *c t\"\n  unfolding cprod_def Field_card_of by (rule card_of_Times_assoc)\n\nlemma cprod_czero: \"r *c czero =o czero\"\n  unfolding cprod_def czero_def Field_card_of by (simp add: card_of_empty_ordIso)\n\nlemma cprod_cone: \"Card_order r \\<Longrightarrow> r *c cone =o r\"\n  unfolding cprod_def cone_def Field_card_of\n  by (drule card_of_Field_ordIso) (erule ordIso_transitive[OF card_of_Times_singleton])\n\n\nlemma ordLeq_cprod1: \"\\<lbrakk>Card_order p1; Cnotzero p2\\<rbrakk> \\<Longrightarrow> p1 \\<le>o p1 *c p2\"\nunfolding cprod_def by (metis Card_order_Times1 czeroI)\n\n\nsubsection \\<open>Exponentiation\\<close>\n\nlemma cexp_czero: \"r ^c czero =o cone\"\nunfolding cexp_def czero_def Field_card_of Func_empty by (rule single_cone)\n\nlemma Pow_cexp_ctwo:\n  \"|Pow A| =o ctwo ^c |A|\"\nunfolding ctwo_def cexp_def Field_card_of by (rule card_of_Pow_Func)\n\nlemma Cnotzero_cexp:\n  assumes \"Cnotzero q\" \n  shows \"Cnotzero (q ^c r)\"\nproof -\n  have \"Field q \\<noteq> {}\"\n    by (metis Card_order_iff_ordIso_card_of assms(1) czero_def)\n  then show ?thesis\n    by (simp add: card_of_ordIso_czero_iff_empty cexp_def)\nqed\n\nlemma Cinfinite_ctwo_cexp:\n  \"Cinfinite r \\<Longrightarrow> Cinfinite (ctwo ^c r)\"\nunfolding ctwo_def cexp_def cinfinite_def Field_card_of\nby (rule conjI, rule infinite_Func, auto)\n\nlemma cone_ordLeq_iff_Field:\n  assumes \"cone \\<le>o r\"\n  shows \"Field r \\<noteq> {}\"\nproof (rule ccontr)\n  assume \"\\<not> Field r \\<noteq> {}\"\n  hence \"Field r = {}\" by simp\n  thus False using card_of_empty3\n    card_of_mono2[OF assms] Cnotzero_imp_not_empty[OF cone_Cnotzero] by auto\nqed\n\nlemma cone_ordLeq_cexp: \"cone \\<le>o r1 \\<Longrightarrow> cone \\<le>o r1 ^c r2\"\nby (simp add: cexp_def cone_def Func_non_emp cone_ordLeq_iff_Field)\n\nlemma Card_order_czero: \"Card_order czero\"\nby (simp only: card_of_Card_order czero_def)\n\nlemma cexp_mono2'':\n  assumes 2: \"p2 \\<le>o r2\"\n  and n1: \"Cnotzero q\"\n  and n2: \"Card_order p2\"\n  shows \"q ^c p2 \\<le>o q ^c r2\"\nproof (cases \"p2 =o (czero :: 'a rel)\")\n  case True\n  hence \"q ^c p2 =o q ^c (czero :: 'a rel)\" using n1 n2 cexp_cong2 Card_order_czero by blast\n  also have \"q ^c (czero :: 'a rel) =o cone\" using cexp_czero by blast\n  also have \"cone \\<le>o q ^c r2\" using cone_ordLeq_cexp cone_ordLeq_Cnotzero n1 by blast\n  finally show ?thesis .\nnext\n  case False thus ?thesis using assms cexp_mono2' czeroI by metis\nqed\n\nlemma csum_cexp: \"\\<lbrakk>Cinfinite r1; Cinfinite r2; Card_order q; ctwo \\<le>o q\\<rbrakk> \\<Longrightarrow>\n  q ^c r1 +c q ^c r2 \\<le>o q ^c (r1 +c r2)\"\n  apply (rule csum_cinfinite_bound)\n  apply (metis cexp_mono2' cinfinite_def finite.emptyI ordLeq_csum1)\n  apply (metis cexp_mono2' cinfinite_def finite.emptyI ordLeq_csum2)\n  by (simp_all add: Card_order_cexp Cinfinite_csum1 Cinfinite_cexp cinfinite_cexp)\n\nlemma csum_cexp': \"\\<lbrakk>Cinfinite r; Card_order q; ctwo \\<le>o q\\<rbrakk> \\<Longrightarrow> q +c r \\<le>o q ^c r\"\napply (rule csum_cinfinite_bound)\n    apply (metis Cinfinite_Cnotzero ordLeq_cexp1)\n   apply (metis ordLeq_cexp2)\n  apply blast+\nby (metis Cinfinite_cexp)\n\nlemma card_of_Sigma_ordLeq_Cinfinite:\n  \"\\<lbrakk>Cinfinite r; |I| \\<le>o r; \\<forall>i \\<in> I. |A i| \\<le>o r\\<rbrakk> \\<Longrightarrow> |SIGMA i : I. A i| \\<le>o r\"\nunfolding cinfinite_def by (blast intro: card_of_Sigma_ordLeq_infinite_Field)\n\nlemma card_order_cexp:\n  assumes \"card_order r1\" \"card_order r2\"\n  shows \"card_order (r1 ^c r2)\"\nproof -\n  have \"Field r1 = UNIV\" \"Field r2 = UNIV\" using assms card_order_on_Card_order by auto\n  thus ?thesis unfolding cexp_def Func_def by simp\nqed\n\nlemma Cinfinite_ordLess_cexp:\n  assumes r: \"Cinfinite r\"\n  shows \"r <o r ^c r\"\nproof -\n  have \"r <o ctwo ^c r\" using r by (simp only: ordLess_ctwo_cexp)\n  also have \"ctwo ^c r \\<le>o r ^c r\"\n    by (rule cexp_mono1[OF ctwo_ordLeq_Cinfinite]) (auto simp: r ctwo_not_czero Card_order_ctwo)\n  finally show ?thesis .\nqed\n\nlemma infinite_ordLeq_cexp:\n  assumes \"Cinfinite r\"\n  shows \"r \\<le>o r ^c r\"\nby (rule ordLess_imp_ordLeq[OF Cinfinite_ordLess_cexp[OF assms]])\n\nlemma czero_cexp: \"Cnotzero r \\<Longrightarrow> czero ^c r =o czero\"\n  by (drule Cnotzero_imp_not_empty) (simp add: cexp_def czero_def card_of_empty_ordIso)\n\nlemma Func_singleton:\nfixes x :: 'b and A :: \"'a set\"\nshows \"|Func A {x}| =o |{x}|\"\nproof (rule ordIso_symmetric)\n  define f where [abs_def]: \"f y a = (if y = x \\<and> a \\<in> A then x else undefined)\" for y a\n  have \"Func A {x} \\<subseteq> f ` {x}\" unfolding f_def Func_def by (force simp: fun_eq_iff)\n  hence \"bij_betw f {x} (Func A {x})\" unfolding bij_betw_def inj_on_def f_def Func_def\n    by (auto split: if_split_asm)\n  thus \"|{x}| =o |Func A {x}|\" using card_of_ordIso by blast\nqed\n\nlemma cone_cexp: \"cone ^c r =o cone\"\n  unfolding cexp_def cone_def Field_card_of by (rule Func_singleton)\n\nlemma card_of_Func_squared:\n  fixes A :: \"'a set\"\n  shows \"|Func (UNIV :: bool set) A| =o |A \\<times> A|\"\nproof (rule ordIso_symmetric)\n  define f where \"f = (\\<lambda>(x::'a,y) b. if A = {} then undefined else if b then x else y)\"\n  have \"Func (UNIV :: bool set) A \\<subseteq> f ` (A \\<times> A)\" unfolding f_def Func_def\n    by (auto simp: image_iff fun_eq_iff split: option.splits if_split_asm) blast\n  hence \"bij_betw f (A \\<times> A) (Func (UNIV :: bool set) A)\"\n    unfolding bij_betw_def inj_on_def f_def Func_def by (auto simp: fun_eq_iff)\n  thus \"|A \\<times> A| =o |Func (UNIV :: bool set) A|\" using card_of_ordIso by blast\nqed\n\nlemma cexp_ctwo: \"r ^c ctwo =o r *c r\"\n  unfolding cexp_def ctwo_def cprod_def Field_card_of by (rule card_of_Func_squared)\n\nlemma card_of_Func_Plus:\n  fixes A :: \"'a set\" and B :: \"'b set\" and C :: \"'c set\"\n  shows \"|Func (A <+> B) C| =o |Func A C \\<times> Func B C|\"\nproof (rule ordIso_symmetric)\n  define f where \"f = (\\<lambda>(g :: 'a => 'c, h::'b \\<Rightarrow> 'c) ab. case ab of Inl a \\<Rightarrow> g a | Inr b \\<Rightarrow> h b)\"\n  define f' where \"f' = (\\<lambda>(f :: ('a + 'b) \\<Rightarrow> 'c). (\\<lambda>a. f (Inl a), \\<lambda>b. f (Inr b)))\"\n  have \"f ` (Func A C \\<times> Func B C) \\<subseteq> Func (A <+> B) C\"\n    unfolding Func_def f_def by (force split: sum.splits)\n  moreover have \"f' ` Func (A <+> B) C \\<subseteq> Func A C \\<times> Func B C\" unfolding Func_def f'_def by force\n  moreover have \"\\<forall>a \\<in> Func A C \\<times> Func B C. f' (f a) = a\" unfolding f'_def f_def Func_def by auto\n  moreover have \"\\<forall>a' \\<in> Func (A <+> B) C. f (f' a') = a'\" unfolding f'_def f_def Func_def\n    by (auto split: sum.splits)\n  ultimately have \"bij_betw f (Func A C \\<times> Func B C) (Func (A <+> B) C)\"\n    by (intro bij_betw_byWitness[of _ f' f])\n  thus \"|Func A C \\<times> Func B C| =o |Func (A <+> B) C|\" using card_of_ordIso by blast\nqed\n\nlemma cexp_csum: \"r ^c (s +c t) =o r ^c s *c r ^c t\"\n  unfolding cexp_def cprod_def csum_def Field_card_of by (rule card_of_Func_Plus)\n\n\nsubsection \\<open>Powerset\\<close>\n\ndefinition cpow where \"cpow r = |Pow (Field r)|\"\n\nlemma card_order_cpow: \"card_order r \\<Longrightarrow> card_order (cpow r)\"\nby (simp only: cpow_def Field_card_order Pow_UNIV card_of_card_order_on)\n\nlemma cpow_greater_eq: \"Card_order r \\<Longrightarrow> r \\<le>o cpow r\"\nby (rule ordLess_imp_ordLeq) (simp only: cpow_def Card_order_Pow)\n\nlemma Cinfinite_cpow: \"Cinfinite r \\<Longrightarrow> Cinfinite (cpow r)\"\nunfolding cpow_def cinfinite_def by (metis Field_card_of card_of_Card_order infinite_Pow)\n\nlemma Card_order_cpow: \"Card_order (cpow r)\"\nunfolding cpow_def by (rule card_of_Card_order)\n\nlemma cardSuc_ordLeq_cpow: \"Card_order r \\<Longrightarrow> cardSuc r \\<le>o cpow r\"\nunfolding cpow_def by (metis Card_order_Pow cardSuc_ordLess_ordLeq card_of_Card_order)\n\nlemma cpow_cexp_ctwo: \"cpow r =o ctwo ^c r\"\nunfolding cpow_def ctwo_def cexp_def Field_card_of by (rule card_of_Pow_Func)\n\nsubsection \\<open>Inverse image\\<close>\n\nlemma vimage_ordLeq:\nassumes \"|A| \\<le>o k\" and \"\\<forall> a \\<in> A. |vimage f {a}| \\<le>o k\" and \"Cinfinite k\"\nshows \"|vimage f A| \\<le>o k\"\nproof-\n  have \"vimage f A = (\\<Union>a \\<in> A. vimage f {a})\" by auto\n  also have \"|\\<Union>a \\<in> A. vimage f {a}| \\<le>o k\"\n  using UNION_Cinfinite_bound[OF assms] .\n  finally show ?thesis .\nqed\n\nsubsection \\<open>Maximum\\<close>\n\ndefinition cmax where\n  \"cmax r s =\n    (if cinfinite r \\<or> cinfinite s then czero +c r +c s\n     else natLeq_on (max (card (Field r)) (card (Field s))) +c czero)\"\n\nlemma cmax_com: \"cmax r s =o cmax s r\"\n  unfolding cmax_def\n  by (auto simp: max.commute intro: csum_cong2[OF csum_com] csum_cong2[OF czero_ordIso])\n\nlemma cmax1:\n  assumes \"Card_order r\" \"Card_order s\" \"s \\<le>o r\"\n  shows \"cmax r s =o r\"\nunfolding cmax_def proof (split if_splits, intro conjI impI)\n  assume \"cinfinite r \\<or> cinfinite s\"\n  hence Cinf: \"Cinfinite r\" using assms(1,3) by (metis cinfinite_mono)\n  have \"czero +c r +c s =o r +c s\" by (rule csum_czero2[OF Card_order_csum])\n  also have \"r +c s =o r\" by (rule csum_absorb1[OF Cinf assms(3)])\n  finally show \"czero +c r +c s =o r\" .\nnext\n  assume \"\\<not> (cinfinite r \\<or> cinfinite s)\"\n  hence fin: \"finite (Field r)\" and \"finite (Field s)\" unfolding cinfinite_def by simp_all\n  moreover\n  { from assms(2) have \"|Field s| =o s\" by (rule card_of_Field_ordIso)\n    also from assms(3) have \"s \\<le>o r\" .\n    also from assms(1) have \"r =o |Field r|\" by (rule ordIso_symmetric[OF card_of_Field_ordIso])\n    finally have \"|Field s| \\<le>o |Field r|\" .\n  }\n  ultimately have \"card (Field s) \\<le> card (Field r)\" by (subst sym[OF finite_card_of_iff_card2])\n  hence \"max (card (Field r)) (card (Field s)) = card (Field r)\" by (rule max_absorb1)\n  hence \"natLeq_on (max (card (Field r)) (card (Field s))) +c czero =\n    natLeq_on (card (Field r)) +c czero\" by simp\n  also have \"\\<dots> =o natLeq_on (card (Field r))\" by (rule csum_czero1[OF natLeq_on_Card_order])\n  also have \"natLeq_on (card (Field r)) =o |Field r|\"\n    by (rule ordIso_symmetric[OF finite_imp_card_of_natLeq_on[OF fin]])\n  also from assms(1) have \"|Field r| =o r\" by (rule card_of_Field_ordIso)\n  finally show \"natLeq_on (max (card (Field r)) (card (Field s))) +c czero =o r\" .\nqed\n\nlemma cmax2:\n  assumes \"Card_order r\" \"Card_order s\" \"r \\<le>o s\"\n  shows \"cmax r s =o s\"\n  by (metis assms cmax1 cmax_com ordIso_transitive)\n\nlemma csum_absorb2: \"Cinfinite r2 \\<Longrightarrow> r1 \\<le>o r2 \\<Longrightarrow> r1 +c r2 =o r2\"\n  by (metis csum_absorb2')\n\nlemma cprod_infinite2': \"\\<lbrakk>Cnotzero r1; Cinfinite r2; r1 \\<le>o r2\\<rbrakk> \\<Longrightarrow> r1 *c r2 =o r2\"\n  unfolding ordIso_iff_ordLeq\n  by (intro conjI cprod_cinfinite_bound ordLeq_cprod2 ordLeq_refl)\n    (auto dest!: ordIso_imp_ordLeq not_ordLeq_ordLess simp: czero_def Card_order_empty)\n\ncontext\n  fixes r s\n  assumes r: \"Cinfinite r\"\n  and     s: \"Cinfinite s\"\nbegin\n\nlemma cmax_csum: \"cmax r s =o r +c s\"\nproof (cases \"r \\<le>o s\")\n  case True\n  hence \"cmax r s =o s\" by (metis cmax2 r s)\n  also have \"s =o r +c s\" by (metis True csum_absorb2 ordIso_symmetric s)\n  finally show ?thesis .\nnext\n  case False\n  hence \"s \\<le>o r\" by (metis ordLeq_total r s card_order_on_def)\n  hence \"cmax r s =o r\" by (metis cmax1 r s)\n  also have \"r =o r +c s\" by (metis \\<open>s \\<le>o r\\<close> csum_absorb1 ordIso_symmetric r)\n  finally show ?thesis .\nqed\n\nlemma cmax_cprod: \"cmax r s =o r *c s\"\nproof (cases \"r \\<le>o s\")\n  case True\n  hence \"cmax r s =o s\" by (metis cmax2 r s)\n  also have \"s =o r *c s\" by (metis Cinfinite_Cnotzero True cprod_infinite2' ordIso_symmetric r s)\n  finally show ?thesis .\nnext\n  case False\n  hence \"s \\<le>o r\" by (metis ordLeq_total r s card_order_on_def)\n  hence \"cmax r s =o r\" by (metis cmax1 r s)\n  also have \"r =o r *c s\" by (metis Cinfinite_Cnotzero \\<open>s \\<le>o r\\<close> cprod_infinite1' ordIso_symmetric r s)\n  finally show ?thesis .\nqed\n\nend\n\nlemma Card_order_cmax:\nassumes r: \"Card_order r\" and s: \"Card_order s\"\nshows \"Card_order (cmax r s)\"\nunfolding cmax_def by (auto simp: Card_order_csum)\n\nlemma ordLeq_cmax:\nassumes r: \"Card_order r\" and s: \"Card_order s\"\nshows \"r \\<le>o cmax r s \\<and> s \\<le>o cmax r s\"\nproof-\n  {assume \"r \\<le>o s\"\n   hence ?thesis by (metis cmax2 ordIso_iff_ordLeq ordLeq_transitive r s)\n  }\n  moreover\n  {assume \"s \\<le>o r\"\n   hence ?thesis using cmax_com by (metis cmax2 ordIso_iff_ordLeq ordLeq_transitive r s)\n  }\n  ultimately show ?thesis using r s ordLeq_total unfolding card_order_on_def by auto\nqed\n\nlemmas ordLeq_cmax1 = ordLeq_cmax[THEN conjunct1] and\n       ordLeq_cmax2 = ordLeq_cmax[THEN conjunct2]\n\nlemma finite_cmax:\nassumes r: \"Card_order r\" and s: \"Card_order s\"\nshows \"finite (Field (cmax r s)) \\<longleftrightarrow> finite (Field r) \\<and> finite (Field s)\"\nproof-\n  {assume \"r \\<le>o s\"\n   hence ?thesis by (metis cmax2 ordIso_finite_Field ordLeq_finite_Field r s)\n  }\n  moreover\n  {assume \"s \\<le>o r\"\n   hence ?thesis by (metis cmax1 ordIso_finite_Field ordLeq_finite_Field r s)\n  }\n  ultimately show ?thesis using r s ordLeq_total unfolding card_order_on_def by auto\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/Cardinals/Cardinal_Arithmetic.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8962513731336202, "lm_q2_score": 0.7826624789529375, "lm_q1q2_score": 0.7014623214617334}}
{"text": "theory ex01\nimports Main\nbegin\n\nvalue \"2 + (2::nat)\"\n\nvalue \"(2::nat) * (5 + 3)\"\n\nvalue \"(3::nat) * 4 - 2 *(7 + 1)\"\n\nlemma \"(x::nat) + (y + z) = (x + y) + z\"\n  by auto\n\nlemma \"(x::nat) + y = y + x\"\n  apply auto\n  done\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\n\nvalue \"count [(1::nat), 1, 1] 1\"\n\ntheorem \"count xs x \\<le> length xs\"\n  apply(induct xs)\n   apply auto\n  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 [(1::nat),2,3,4] 5\"\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 [(1::nat),2,3,4] = [4,3,2,1]\"\n  by simp\n\nlemma reverse_snoc:\n  \"reverse (snoc xs y) = y # reverse xs\"\n  by (induct xs) auto\n\ntheorem \"reverse (reverse xs) = xs\"\n  apply(induct xs)\n   apply (auto simp add: reverse_snoc)\n  done\n\nend", "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/ex01.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513842182775, "lm_q2_score": 0.7826624688140726, "lm_q1q2_score": 0.701462321050307}}
{"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\nsection \\<open>Elementary Metric Spaces\\<close>\n\ntheory Elementary_Metric_Spaces\n  imports\n    Abstract_Topology_2\n    Metric_Arith\nbegin\n\nsubsection \\<open>Open and closed balls\\<close>\n\ndefinition\\<^marker>\\<open>tag important\\<close> ball :: \"'a::metric_space \\<Rightarrow> real \\<Rightarrow> 'a set\"\n  where \"ball x e = {y. dist x y < e}\"\n\ndefinition\\<^marker>\\<open>tag important\\<close> cball :: \"'a::metric_space \\<Rightarrow> real \\<Rightarrow> 'a set\"\n  where \"cball x e = {y. dist x y \\<le> e}\"\n\ndefinition\\<^marker>\\<open>tag important\\<close> sphere :: \"'a::metric_space \\<Rightarrow> real \\<Rightarrow> 'a set\"\n  where \"sphere x e = {y. dist x y = e}\"\n\nlemma mem_ball [simp, metric_unfold]: \"y \\<in> ball x e \\<longleftrightarrow> dist x y < e\"\n  by (simp add: ball_def)\n\nlemma mem_cball [simp, metric_unfold]: \"y \\<in> cball x e \\<longleftrightarrow> dist x y \\<le> e\"\n  by (simp add: cball_def)\n\nlemma mem_sphere [simp]: \"y \\<in> sphere x e \\<longleftrightarrow> dist x y = e\"\n  by (simp add: sphere_def)\n\nlemma ball_trivial [simp]: \"ball x 0 = {}\"\n  by (simp add: ball_def)\n\nlemma cball_trivial [simp]: \"cball x 0 = {x}\"\n  by (simp add: cball_def)\n\nlemma sphere_trivial [simp]: \"sphere x 0 = {x}\"\n  by (simp add: sphere_def)\n\nlemma disjoint_ballI: \"dist x y \\<ge> r+s \\<Longrightarrow> ball x r \\<inter> ball y s = {}\"\n  using dist_triangle_less_add not_le by fastforce\n\nlemma disjoint_cballI: \"dist x y > r + s \\<Longrightarrow> cball x r \\<inter> cball y s = {}\"\n  by (metis add_mono disjoint_iff_not_equal dist_triangle2 dual_order.trans leD mem_cball)\n\nlemma sphere_empty [simp]: \"r < 0 \\<Longrightarrow> sphere a r = {}\"\n  for a :: \"'a::metric_space\"\n  by auto\n\nlemma centre_in_ball [simp]: \"x \\<in> ball x e \\<longleftrightarrow> 0 < e\"\n  by simp\n\nlemma centre_in_cball [simp]: \"x \\<in> cball x e \\<longleftrightarrow> 0 \\<le> e\"\n  by simp\n\nlemma ball_subset_cball [simp, intro]: \"ball x e \\<subseteq> cball x e\"\n  by (simp add: subset_eq)\n\nlemma mem_ball_imp_mem_cball: \"x \\<in> ball y e \\<Longrightarrow> x \\<in> cball y e\"\n  by auto\n\nlemma sphere_cball [simp,intro]: \"sphere z r \\<subseteq> cball z r\"\n  by force\n\nlemma cball_diff_sphere: \"cball a r - sphere a r = ball a r\"\n  by auto\n\nlemma subset_ball[intro]: \"d \\<le> e \\<Longrightarrow> ball x d \\<subseteq> ball x e\"\n  by auto\n\nlemma subset_cball[intro]: \"d \\<le> e \\<Longrightarrow> cball x d \\<subseteq> cball x e\"\n  by auto\n\nlemma mem_ball_leI: \"x \\<in> ball y e \\<Longrightarrow> e \\<le> f \\<Longrightarrow> x \\<in> ball y f\"\n  by auto\n\nlemma mem_cball_leI: \"x \\<in> cball y e \\<Longrightarrow> e \\<le> f \\<Longrightarrow> x \\<in> cball y f\"\n  by auto\n\nlemma cball_trans: \"y \\<in> cball z b \\<Longrightarrow> x \\<in> cball y a \\<Longrightarrow> x \\<in> cball z (b + a)\"\n  by metric\n\nlemma ball_max_Un: \"ball a (max r s) = ball a r \\<union> ball a s\"\n  by auto\n\nlemma ball_min_Int: \"ball a (min r s) = ball a r \\<inter> ball a s\"\n  by auto\n\nlemma cball_max_Un: \"cball a (max r s) = cball a r \\<union> cball a s\"\n  by auto\n\nlemma cball_min_Int: \"cball a (min r s) = cball a r \\<inter> cball a s\"\n  by auto\n\nlemma cball_diff_eq_sphere: \"cball a r - ball a r =  sphere a r\"\n  by auto\n\nlemma open_ball [intro, simp]: \"open (ball x e)\"\nproof -\n  have \"open (dist x -` {..<e})\"\n    by (intro open_vimage open_lessThan continuous_intros)\n  also have \"dist x -` {..<e} = ball x e\"\n    by auto\n  finally show ?thesis .\nqed\n\nlemma open_contains_ball: \"open S \\<longleftrightarrow> (\\<forall>x\\<in>S. \\<exists>e>0. ball x e \\<subseteq> S)\"\n  by (simp add: open_dist subset_eq Ball_def dist_commute)\n\nlemma openI [intro?]: \"(\\<And>x. x\\<in>S \\<Longrightarrow> \\<exists>e>0. ball x e \\<subseteq> S) \\<Longrightarrow> open S\"\n  by (auto simp: open_contains_ball)\n\nlemma openE[elim?]:\n  assumes \"open S\" \"x\\<in>S\"\n  obtains e where \"e>0\" \"ball x e \\<subseteq> S\"\n  using assms unfolding open_contains_ball by auto\n\nlemma open_contains_ball_eq: \"open S \\<Longrightarrow> x\\<in>S \\<longleftrightarrow> (\\<exists>e>0. ball x e \\<subseteq> S)\"\n  by (metis open_contains_ball subset_eq centre_in_ball)\n\nlemma ball_eq_empty[simp]: \"ball x e = {} \\<longleftrightarrow> e \\<le> 0\"\n  unfolding mem_ball set_eq_iff\n  by (simp add: not_less) metric\n\nlemma ball_empty: \"e \\<le> 0 \\<Longrightarrow> ball x e = {}\" \n  by simp\n\nlemma closed_cball [iff]: \"closed (cball x e)\"\nproof -\n  have \"closed (dist x -` {..e})\"\n    by (intro closed_vimage closed_atMost continuous_intros)\n  also have \"dist x -` {..e} = cball x e\"\n    by auto\n  finally show ?thesis .\nqed\n\nlemma open_contains_cball: \"open S \\<longleftrightarrow> (\\<forall>x\\<in>S. \\<exists>e>0.  cball x e \\<subseteq> S)\"\nproof -\n  {\n    fix x and e::real\n    assume \"x\\<in>S\" \"e>0\" \"ball x e \\<subseteq> S\"\n    then have \"\\<exists>d>0. cball x d \\<subseteq> S\"\n      unfolding subset_eq by (rule_tac x=\"e/2\" in exI, auto)\n  }\n  moreover\n  {\n    fix x and e::real\n    assume \"x\\<in>S\" \"e>0\" \"cball x e \\<subseteq> S\"\n    then have \"\\<exists>d>0. ball x d \\<subseteq> S\"\n      using mem_ball_imp_mem_cball by blast\n  }\n  ultimately show ?thesis\n    unfolding open_contains_ball by auto\nqed\n\nlemma open_contains_cball_eq: \"open S \\<Longrightarrow> (\\<forall>x. x \\<in> S \\<longleftrightarrow> (\\<exists>e>0. cball x e \\<subseteq> S))\"\n  by (metis open_contains_cball subset_eq order_less_imp_le centre_in_cball)\n\nlemma eventually_nhds_ball: \"d > 0 \\<Longrightarrow> eventually (\\<lambda>x. x \\<in> ball z d) (nhds z)\"\n  by (rule eventually_nhds_in_open) simp_all\n\nlemma eventually_at_ball: \"d > 0 \\<Longrightarrow> eventually (\\<lambda>t. t \\<in> ball z d \\<and> t \\<in> A) (at z within A)\"\n  unfolding eventually_at by (intro exI[of _ d]) (simp_all add: dist_commute)\n\nlemma eventually_at_ball': \"d > 0 \\<Longrightarrow> eventually (\\<lambda>t. t \\<in> ball z d \\<and> t \\<noteq> z \\<and> t \\<in> A) (at z within A)\"\n  unfolding eventually_at by (intro exI[of _ d]) (simp_all add: dist_commute)\n\nlemma at_within_ball: \"e > 0 \\<Longrightarrow> dist x y < e \\<Longrightarrow> at y within ball x e = at y\"\n  by (subst at_within_open) auto\n\nlemma atLeastAtMost_eq_cball:\n  fixes a b::real\n  shows \"{a .. b} = cball ((a + b)/2) ((b - a)/2)\"\n  by (auto simp: dist_real_def field_simps)\n\nlemma cball_eq_atLeastAtMost:\n  fixes a b::real\n  shows \"cball a b = {a - b .. a + b}\"\n  by (auto simp: dist_real_def)\n\nlemma greaterThanLessThan_eq_ball:\n  fixes a b::real\n  shows \"{a <..< b} = ball ((a + b)/2) ((b - a)/2)\"\n  by (auto simp: dist_real_def field_simps)\n\nlemma ball_eq_greaterThanLessThan:\n  fixes a b::real\n  shows \"ball a b = {a - b <..< a + b}\"\n  by (auto simp: dist_real_def)\n\nlemma interior_ball [simp]: \"interior (ball x e) = ball x e\"\n  by (simp add: interior_open)\n\nlemma cball_eq_empty [simp]: \"cball x e = {} \\<longleftrightarrow> e < 0\"\n  apply (simp add: set_eq_iff not_le)\n  apply (metis zero_le_dist dist_self order_less_le_trans)\n  done\n\nlemma cball_empty [simp]: \"e < 0 \\<Longrightarrow> cball x e = {}\"\n  by simp\n\nlemma cball_sing:\n  fixes x :: \"'a::metric_space\"\n  shows \"e = 0 \\<Longrightarrow> cball x e = {x}\"\n  by simp\n\nlemma ball_divide_subset: \"d \\<ge> 1 \\<Longrightarrow> ball x (e/d) \\<subseteq> ball x e\"\n  by (metis ball_eq_empty div_by_1 frac_le linear subset_ball zero_less_one)\n\nlemma ball_divide_subset_numeral: \"ball x (e / numeral w) \\<subseteq> ball x e\"\n  using ball_divide_subset one_le_numeral by blast\n\nlemma cball_divide_subset: \"d \\<ge> 1 \\<Longrightarrow> cball x (e/d) \\<subseteq> cball x e\"\n  apply (cases \"e < 0\", simp add: field_split_simps)\n  by (metis div_by_1 frac_le less_numeral_extra(1) not_le order_refl subset_cball)\n\nlemma cball_divide_subset_numeral: \"cball x (e / numeral w) \\<subseteq> cball x e\"\n  using cball_divide_subset one_le_numeral by blast\n\nlemma cball_scale:\n  assumes \"a \\<noteq> 0\"\n  shows   \"(\\<lambda>x. a *\\<^sub>R x) ` cball c r = cball (a *\\<^sub>R c :: 'a :: real_normed_vector) (\\<bar>a\\<bar> * r)\"\nproof -\n  have 1: \"(\\<lambda>x. a *\\<^sub>R x) ` cball c r \\<subseteq> cball (a *\\<^sub>R c) (\\<bar>a\\<bar> * r)\" if \"a \\<noteq> 0\" for a r and c :: 'a\n  proof safe\n    fix x\n    assume x: \"x \\<in> cball c r\"\n    have \"dist (a *\\<^sub>R c) (a *\\<^sub>R x) = norm (a *\\<^sub>R c - a *\\<^sub>R x)\"\n      by (auto simp: dist_norm)\n    also have \"a *\\<^sub>R c - a *\\<^sub>R x = a *\\<^sub>R (c - x)\"\n      by (simp add: algebra_simps)\n    finally show \"a *\\<^sub>R x \\<in> cball (a *\\<^sub>R c) (\\<bar>a\\<bar> * r)\"\n      using that x by (auto simp: dist_norm)\n  qed\n\n  have \"cball (a *\\<^sub>R c) (\\<bar>a\\<bar> * r) = (\\<lambda>x. a *\\<^sub>R x) ` (\\<lambda>x. inverse a *\\<^sub>R x) ` cball (a *\\<^sub>R c) (\\<bar>a\\<bar> * r)\"\n    unfolding image_image using assms by simp\n  also have \"\\<dots> \\<subseteq> (\\<lambda>x. a *\\<^sub>R x) ` cball (inverse a *\\<^sub>R (a *\\<^sub>R c)) (\\<bar>inverse a\\<bar> * (\\<bar>a\\<bar> * r))\"\n    using assms by (intro image_mono 1) auto\n  also have \"\\<dots> = (\\<lambda>x. a *\\<^sub>R x) ` cball c r\"\n    using assms by (simp add: algebra_simps)\n  finally have \"cball (a *\\<^sub>R c) (\\<bar>a\\<bar> * r) \\<subseteq> (\\<lambda>x. a *\\<^sub>R x) ` cball c r\" .\n  moreover from assms have \"(\\<lambda>x. a *\\<^sub>R x) ` cball c r \\<subseteq> cball (a *\\<^sub>R c) (\\<bar>a\\<bar> * r)\"\n    by (intro 1) auto\n  ultimately show ?thesis by blast\nqed\n\nlemma ball_scale:\n  assumes \"a \\<noteq> 0\"\n  shows   \"(\\<lambda>x. a *\\<^sub>R x) ` ball c r = ball (a *\\<^sub>R c :: 'a :: real_normed_vector) (\\<bar>a\\<bar> * r)\"\nproof -\n  have 1: \"(\\<lambda>x. a *\\<^sub>R x) ` ball c r \\<subseteq> ball (a *\\<^sub>R c) (\\<bar>a\\<bar> * r)\" if \"a \\<noteq> 0\" for a r and c :: 'a\n  proof safe\n    fix x\n    assume x: \"x \\<in> ball c r\"\n    have \"dist (a *\\<^sub>R c) (a *\\<^sub>R x) = norm (a *\\<^sub>R c - a *\\<^sub>R x)\"\n      by (auto simp: dist_norm)\n    also have \"a *\\<^sub>R c - a *\\<^sub>R x = a *\\<^sub>R (c - x)\"\n      by (simp add: algebra_simps)\n    finally show \"a *\\<^sub>R x \\<in> ball (a *\\<^sub>R c) (\\<bar>a\\<bar> * r)\"\n      using that x by (auto simp: dist_norm)\n  qed\n\n  have \"ball (a *\\<^sub>R c) (\\<bar>a\\<bar> * r) = (\\<lambda>x. a *\\<^sub>R x) ` (\\<lambda>x. inverse a *\\<^sub>R x) ` ball (a *\\<^sub>R c) (\\<bar>a\\<bar> * r)\"\n    unfolding image_image using assms by simp\n  also have \"\\<dots> \\<subseteq> (\\<lambda>x. a *\\<^sub>R x) ` ball (inverse a *\\<^sub>R (a *\\<^sub>R c)) (\\<bar>inverse a\\<bar> * (\\<bar>a\\<bar> * r))\"\n    using assms by (intro image_mono 1) auto\n  also have \"\\<dots> = (\\<lambda>x. a *\\<^sub>R x) ` ball c r\"\n    using assms by (simp add: algebra_simps)\n  finally have \"ball (a *\\<^sub>R c) (\\<bar>a\\<bar> * r) \\<subseteq> (\\<lambda>x. a *\\<^sub>R x) ` ball c r\" .\n  moreover from assms have \"(\\<lambda>x. a *\\<^sub>R x) ` ball c r \\<subseteq> ball (a *\\<^sub>R c) (\\<bar>a\\<bar> * r)\"\n    by (intro 1) auto\n  ultimately show ?thesis by blast\nqed\n\nsubsection \\<open>Limit Points\\<close>\n\nlemma islimpt_approachable:\n  fixes x :: \"'a::metric_space\"\n  shows \"x islimpt S \\<longleftrightarrow> (\\<forall>e>0. \\<exists>x'\\<in>S. x' \\<noteq> x \\<and> dist x' x < e)\"\n  unfolding islimpt_iff_eventually eventually_at by fast\n\nlemma islimpt_approachable_le: \"x islimpt S \\<longleftrightarrow> (\\<forall>e>0. \\<exists>x'\\<in> S. x' \\<noteq> x \\<and> dist x' x \\<le> e)\"\n  for x :: \"'a::metric_space\"\n  unfolding islimpt_approachable\n  using approachable_lt_le2 [where f=\"\\<lambda>y. dist y x\" and P=\"\\<lambda>y. y \\<notin> S \\<or> y = x\" and Q=\"\\<lambda>x. True\"]\n  by auto\n\nlemma limpt_of_limpts: \"x islimpt {y. y islimpt S} \\<Longrightarrow> x islimpt S\"\n  for x :: \"'a::metric_space\"\n  apply (clarsimp simp add: islimpt_approachable)\n  apply (drule_tac x=\"e/2\" in spec)\n  apply (auto simp: simp del: less_divide_eq_numeral1)\n  apply (drule_tac x=\"dist x' x\" in spec)\n  apply (auto simp del: less_divide_eq_numeral1)\n  apply metric\n  done\n\nlemma closed_limpts:  \"closed {x::'a::metric_space. x islimpt S}\"\n  using closed_limpt limpt_of_limpts by blast\n\nlemma limpt_of_closure: \"x islimpt closure S \\<longleftrightarrow> x islimpt S\"\n  for x :: \"'a::metric_space\"\n  by (auto simp: closure_def islimpt_Un dest: limpt_of_limpts)\n\nlemma islimpt_eq_infinite_ball: \"x islimpt S \\<longleftrightarrow> (\\<forall>e>0. infinite(S \\<inter> ball x e))\"\n  apply (simp add: islimpt_eq_acc_point, safe)\n   apply (metis Int_commute open_ball centre_in_ball)\n  by (metis open_contains_ball Int_mono finite_subset inf_commute subset_refl)\n\nlemma islimpt_eq_infinite_cball: \"x islimpt S \\<longleftrightarrow> (\\<forall>e>0. infinite(S \\<inter> cball x e))\"\n  apply (simp add: islimpt_eq_infinite_ball, safe)\n   apply (meson Int_mono ball_subset_cball finite_subset order_refl)\n  by (metis open_ball centre_in_ball finite_Int inf.absorb_iff2 inf_assoc open_contains_cball_eq)\n\n\nsubsection \\<open>Perfect Metric Spaces\\<close>\n\nlemma perfect_choose_dist: \"0 < r \\<Longrightarrow> \\<exists>a. a \\<noteq> x \\<and> dist a x < r\"\n  for x :: \"'a::{perfect_space,metric_space}\"\n  using islimpt_UNIV [of x] by (simp add: islimpt_approachable)\n\nlemma cball_eq_sing:\n  fixes x :: \"'a::{metric_space,perfect_space}\"\n  shows \"cball x e = {x} \\<longleftrightarrow> e = 0\"\nproof (rule linorder_cases)\n  assume e: \"0 < e\"\n  obtain a where \"a \\<noteq> x\" \"dist a x < e\"\n    using perfect_choose_dist [OF e] by auto\n  then have \"a \\<noteq> x\" \"dist x a \\<le> e\"\n    by (auto simp: dist_commute)\n  with e show ?thesis by (auto simp: set_eq_iff)\nqed auto\n\n\nsubsection \\<open>?\\<close>\n\nlemma finite_ball_include:\n  fixes a :: \"'a::metric_space\"\n  assumes \"finite S\" \n  shows \"\\<exists>e>0. S \\<subseteq> ball a e\"\n  using assms\nproof induction\n  case (insert x S)\n  then obtain e0 where \"e0>0\" and e0:\"S \\<subseteq> ball a e0\" by auto\n  define e where \"e = max e0 (2 * dist a x)\"\n  have \"e>0\" unfolding e_def using \\<open>e0>0\\<close> by auto\n  moreover have \"insert x S \\<subseteq> ball a e\"\n    using e0 \\<open>e>0\\<close> unfolding e_def by auto\n  ultimately show ?case by auto\nqed (auto intro: zero_less_one)\n\nlemma finite_set_avoid:\n  fixes a :: \"'a::metric_space\"\n  assumes \"finite S\"\n  shows \"\\<exists>d>0. \\<forall>x\\<in>S. x \\<noteq> a \\<longrightarrow> d \\<le> dist a x\"\n  using assms\nproof induction\n  case (insert x S)\n  then obtain d where \"d > 0\" and d: \"\\<forall>x\\<in>S. x \\<noteq> a \\<longrightarrow> d \\<le> dist a x\"\n    by blast\n  show ?case\n  proof (cases \"x = a\")\n    case True\n    with \\<open>d > 0 \\<close>d show ?thesis by auto\n  next\n    case False\n    let ?d = \"min d (dist a x)\"\n    from False \\<open>d > 0\\<close> have dp: \"?d > 0\"\n      by auto\n    from d have d': \"\\<forall>x\\<in>S. x \\<noteq> a \\<longrightarrow> ?d \\<le> dist a x\"\n      by auto\n    with dp False show ?thesis\n      by (metis insert_iff le_less min_less_iff_conj not_less)\n  qed\nqed (auto intro: zero_less_one)\n\nlemma discrete_imp_closed:\n  fixes S :: \"'a::metric_space set\"\n  assumes e: \"0 < e\"\n    and d: \"\\<forall>x \\<in> S. \\<forall>y \\<in> S. dist y x < e \\<longrightarrow> y = x\"\n  shows \"closed S\"\nproof -\n  have False if C: \"\\<And>e. e>0 \\<Longrightarrow> \\<exists>x'\\<in>S. x' \\<noteq> x \\<and> dist x' x < e\" for x\n  proof -\n    from e have e2: \"e/2 > 0\" by arith\n    from C[rule_format, OF e2] obtain y where y: \"y \\<in> S\" \"y \\<noteq> x\" \"dist y x < e/2\"\n      by blast\n    from e2 y(2) have mp: \"min (e/2) (dist x y) > 0\"\n      by simp\n    from d y C[OF mp] show ?thesis\n      by metric\n  qed\n  then show ?thesis\n    by (metis islimpt_approachable closed_limpt [where 'a='a])\nqed\n\n\nsubsection \\<open>Interior\\<close>\n\nlemma mem_interior: \"x \\<in> interior S \\<longleftrightarrow> (\\<exists>e>0. ball x e \\<subseteq> S)\"\n  using open_contains_ball_eq [where S=\"interior S\"]\n  by (simp add: open_subset_interior)\n\nlemma mem_interior_cball: \"x \\<in> interior S \\<longleftrightarrow> (\\<exists>e>0. cball x e \\<subseteq> S)\"\n  by (meson ball_subset_cball interior_subset mem_interior open_contains_cball open_interior\n      subset_trans)\n\n\nsubsection \\<open>Frontier\\<close>\n\nlemma frontier_straddle:\n  fixes a :: \"'a::metric_space\"\n  shows \"a \\<in> frontier S \\<longleftrightarrow> (\\<forall>e>0. (\\<exists>x\\<in>S. dist a x < e) \\<and> (\\<exists>x. x \\<notin> S \\<and> dist a x < e))\"\n  unfolding frontier_def closure_interior\n  by (auto simp: mem_interior subset_eq ball_def)\n\n\nsubsection \\<open>Limits\\<close>\n\nproposition Lim: \"(f \\<longlongrightarrow> l) net \\<longleftrightarrow> trivial_limit net \\<or> (\\<forall>e>0. eventually (\\<lambda>x. dist (f x) l < e) net)\"\n  by (auto simp: tendsto_iff trivial_limit_eq)\n\ntext \\<open>Show that they yield usual definitions in the various cases.\\<close>\n\nproposition Lim_within_le: \"(f \\<longlongrightarrow> l)(at a within S) \\<longleftrightarrow>\n    (\\<forall>e>0. \\<exists>d>0. \\<forall>x\\<in>S. 0 < dist x a \\<and> dist x a \\<le> d \\<longrightarrow> dist (f x) l < e)\"\n  by (auto simp: tendsto_iff eventually_at_le)\n\nproposition Lim_within: \"(f \\<longlongrightarrow> l) (at a within S) \\<longleftrightarrow>\n    (\\<forall>e >0. \\<exists>d>0. \\<forall>x \\<in> S. 0 < dist x a \\<and> dist x a  < d \\<longrightarrow> dist (f x) l < e)\"\n  by (auto simp: tendsto_iff eventually_at)\n\ncorollary Lim_withinI [intro?]:\n  assumes \"\\<And>e. e > 0 \\<Longrightarrow> \\<exists>d>0. \\<forall>x \\<in> S. 0 < dist x a \\<and> dist x a < d \\<longrightarrow> dist (f x) l \\<le> e\"\n  shows \"(f \\<longlongrightarrow> l) (at a within S)\"\n  apply (simp add: Lim_within, clarify)\n  apply (rule ex_forward [OF assms [OF half_gt_zero]], auto)\n  done\n\nproposition Lim_at: \"(f \\<longlongrightarrow> l) (at a) \\<longleftrightarrow>\n    (\\<forall>e >0. \\<exists>d>0. \\<forall>x. 0 < dist x a \\<and> dist x a < d  \\<longrightarrow> dist (f x) l < e)\"\n  by (auto simp: tendsto_iff eventually_at)\n\nlemma Lim_transform_within_set:\n  fixes a :: \"'a::metric_space\" and l :: \"'b::metric_space\"\n  shows \"\\<lbrakk>(f \\<longlongrightarrow> l) (at a within S); eventually (\\<lambda>x. x \\<in> S \\<longleftrightarrow> x \\<in> T) (at a)\\<rbrakk>\n         \\<Longrightarrow> (f \\<longlongrightarrow> l) (at a within T)\"\napply (clarsimp simp: eventually_at Lim_within)\napply (drule_tac x=e in spec, clarify)\napply (rename_tac k)\napply (rule_tac x=\"min d k\" in exI, simp)\ndone\n\ntext \\<open>Another limit point characterization.\\<close>\n\nlemma limpt_sequential_inj:\n  fixes x :: \"'a::metric_space\"\n  shows \"x islimpt S \\<longleftrightarrow>\n         (\\<exists>f. (\\<forall>n::nat. f n \\<in> S - {x}) \\<and> inj f \\<and> (f \\<longlongrightarrow> x) sequentially)\"\n         (is \"?lhs = ?rhs\")\nproof\n  assume ?lhs\n  then have \"\\<forall>e>0. \\<exists>x'\\<in>S. x' \\<noteq> x \\<and> dist x' x < e\"\n    by (force simp: islimpt_approachable)\n  then obtain y where y: \"\\<And>e. e>0 \\<Longrightarrow> y e \\<in> S \\<and> y e \\<noteq> x \\<and> dist (y e) x < e\"\n    by metis\n  define f where \"f \\<equiv> rec_nat (y 1) (\\<lambda>n fn. y (min (inverse(2 ^ (Suc n))) (dist fn x)))\"\n  have [simp]: \"f 0 = y 1\"\n               \"f(Suc n) = y (min (inverse(2 ^ (Suc n))) (dist (f n) x))\" for n\n    by (simp_all add: f_def)\n  have f: \"f n \\<in> S \\<and> (f n \\<noteq> x) \\<and> dist (f n) x < inverse(2 ^ n)\" for n\n  proof (induction n)\n    case 0 show ?case\n      by (simp add: y)\n  next\n    case (Suc n) then show ?case\n      apply (auto simp: y)\n      by (metis half_gt_zero_iff inverse_positive_iff_positive less_divide_eq_numeral1(1) min_less_iff_conj y zero_less_dist_iff zero_less_numeral zero_less_power)\n  qed\n  show ?rhs\n  proof (rule_tac x=f in exI, intro conjI allI)\n    show \"\\<And>n. f n \\<in> S - {x}\"\n      using f by blast\n    have \"dist (f n) x < dist (f m) x\" if \"m < n\" for m n\n    using that\n    proof (induction n)\n      case 0 then show ?case by simp\n    next\n      case (Suc n)\n      then consider \"m < n\" | \"m = n\" using less_Suc_eq by blast\n      then show ?case\n      proof cases\n        assume \"m < n\"\n        have \"dist (f(Suc n)) x = dist (y (min (inverse(2 ^ (Suc n))) (dist (f n) x))) x\"\n          by simp\n        also have \"\\<dots> < dist (f n) x\"\n          by (metis dist_pos_lt f min.strict_order_iff min_less_iff_conj y)\n        also have \"\\<dots> < dist (f m) x\"\n          using Suc.IH \\<open>m < n\\<close> by blast\n        finally show ?thesis .\n      next\n        assume \"m = n\" then show ?case\n          by simp (metis dist_pos_lt f half_gt_zero_iff inverse_positive_iff_positive min_less_iff_conj y zero_less_numeral zero_less_power)\n      qed\n    qed\n    then show \"inj f\"\n      by (metis less_irrefl linorder_injI)\n    show \"f \\<longlonglongrightarrow> x\"\n      apply (rule tendstoI)\n      apply (rule_tac c=\"nat (ceiling(1/e))\" in eventually_sequentiallyI)\n      apply (rule less_trans [OF f [THEN conjunct2, THEN conjunct2]])\n      apply (simp add: field_simps)\n      by (meson le_less_trans mult_less_cancel_left not_le of_nat_less_two_power)\n  qed\nnext\n  assume ?rhs\n  then show ?lhs\n    by (fastforce simp add: islimpt_approachable lim_sequentially)\nqed\n\nlemma Lim_dist_ubound:\n  assumes \"\\<not>(trivial_limit net)\"\n    and \"(f \\<longlongrightarrow> l) net\"\n    and \"eventually (\\<lambda>x. dist a (f x) \\<le> e) net\"\n  shows \"dist a l \\<le> e\"\n  using assms by (fast intro: tendsto_le tendsto_intros)\n\n\nsubsection \\<open>Continuity\\<close>\n\ntext\\<open>Derive the epsilon-delta forms, which we often use as \"definitions\"\\<close>\n\nproposition continuous_within_eps_delta:\n  \"continuous (at x within s) f \\<longleftrightarrow> (\\<forall>e>0. \\<exists>d>0. \\<forall>x'\\<in> s.  dist x' x < d --> dist (f x') (f x) < e)\"\n  unfolding continuous_within and Lim_within  by fastforce\n\ncorollary continuous_at_eps_delta:\n  \"continuous (at x) f \\<longleftrightarrow> (\\<forall>e > 0. \\<exists>d > 0. \\<forall>x'. dist x' x < d \\<longrightarrow> dist (f x') (f x) < e)\"\n  using continuous_within_eps_delta [of x UNIV f] by simp\n\nlemma continuous_at_right_real_increasing:\n  fixes f :: \"real \\<Rightarrow> real\"\n  assumes nondecF: \"\\<And>x y. x \\<le> y \\<Longrightarrow> f x \\<le> f y\"\n  shows \"continuous (at_right a) f \\<longleftrightarrow> (\\<forall>e>0. \\<exists>d>0. f (a + d) - f a < e)\"\n  apply (simp add: greaterThan_def dist_real_def continuous_within Lim_within_le)\n  apply (intro all_cong ex_cong, safe)\n  apply (erule_tac x=\"a + d\" in allE, simp)\n  apply (simp add: nondecF field_simps)\n  apply (drule nondecF, simp)\n  done\n\nlemma continuous_at_left_real_increasing:\n  assumes nondecF: \"\\<And> x y. x \\<le> y \\<Longrightarrow> f x \\<le> ((f y) :: real)\"\n  shows \"(continuous (at_left (a :: real)) f) = (\\<forall>e > 0. \\<exists>delta > 0. f a - f (a - delta) < e)\"\n  apply (simp add: lessThan_def dist_real_def continuous_within Lim_within_le)\n  apply (intro all_cong ex_cong, safe)\n  apply (erule_tac x=\"a - d\" in allE, simp)\n  apply (simp add: nondecF field_simps)\n  apply (cut_tac x=\"a - d\" and y=x in nondecF, simp_all)\n  done\n\ntext\\<open>Versions in terms of open balls.\\<close>\n\nlemma continuous_within_ball:\n  \"continuous (at x within s) f \\<longleftrightarrow>\n    (\\<forall>e > 0. \\<exists>d > 0. f ` (ball x d \\<inter> s) \\<subseteq> ball (f x) e)\"\n  (is \"?lhs = ?rhs\")\nproof\n  assume ?lhs\n  {\n    fix e :: real\n    assume \"e > 0\"\n    then obtain d where d: \"d>0\" \"\\<forall>xa\\<in>s. 0 < dist xa x \\<and> dist xa x < d \\<longrightarrow> dist (f xa) (f x) < e\"\n      using \\<open>?lhs\\<close>[unfolded continuous_within Lim_within] by auto\n    {\n      fix y\n      assume \"y \\<in> f ` (ball x d \\<inter> s)\"\n      then have \"y \\<in> ball (f x) e\"\n        using d(2)\n        using \\<open>e > 0\\<close>\n        by (auto simp: dist_commute)\n    }\n    then have \"\\<exists>d>0. f ` (ball x d \\<inter> s) \\<subseteq> ball (f x) e\"\n      using \\<open>d > 0\\<close>\n      unfolding subset_eq ball_def by (auto simp: dist_commute)\n  }\n  then show ?rhs by auto\nnext\n  assume ?rhs\n  then show ?lhs\n    unfolding continuous_within Lim_within ball_def subset_eq\n    apply (auto simp: dist_commute)\n    apply (erule_tac x=e in allE, auto)\n    done\nqed\n\nlemma continuous_at_ball:\n  \"continuous (at x) f \\<longleftrightarrow> (\\<forall>e>0. \\<exists>d>0. f ` (ball x d) \\<subseteq> ball (f x) e)\" (is \"?lhs = ?rhs\")\nproof\n  assume ?lhs\n  then show ?rhs\n    unfolding continuous_at Lim_at subset_eq Ball_def Bex_def image_iff mem_ball\n    by (metis dist_commute dist_pos_lt dist_self)\nnext\n  assume ?rhs\n  then show ?lhs\n    unfolding continuous_at Lim_at subset_eq Ball_def Bex_def image_iff mem_ball\n    by (metis dist_commute)\nqed\n\ntext\\<open>Define setwise continuity in terms of limits within the set.\\<close>\n\nlemma continuous_on_iff:\n  \"continuous_on s f \\<longleftrightarrow>\n    (\\<forall>x\\<in>s. \\<forall>e>0. \\<exists>d>0. \\<forall>x'\\<in>s. dist x' x < d \\<longrightarrow> dist (f x') (f x) < e)\"\n  unfolding continuous_on_def Lim_within\n  by (metis dist_pos_lt dist_self)\n\nlemma continuous_within_E:\n  assumes \"continuous (at x within s) f\" \"e>0\"\n  obtains d where \"d>0\"  \"\\<And>x'. \\<lbrakk>x'\\<in> s; dist x' x \\<le> d\\<rbrakk> \\<Longrightarrow> dist (f x') (f x) < e\"\n  using assms apply (simp add: continuous_within_eps_delta)\n  apply (drule spec [of _ e], clarify)\n  apply (rule_tac d=\"d/2\" in that, auto)\n  done\n\nlemma continuous_onI [intro?]:\n  assumes \"\\<And>x e. \\<lbrakk>e > 0; x \\<in> s\\<rbrakk> \\<Longrightarrow> \\<exists>d>0. \\<forall>x'\\<in>s. dist x' x < d \\<longrightarrow> dist (f x') (f x) \\<le> e\"\n  shows \"continuous_on s f\"\napply (simp add: continuous_on_iff, clarify)\napply (rule ex_forward [OF assms [OF half_gt_zero]], auto)\ndone\n\ntext\\<open>Some simple consequential lemmas.\\<close>\n\nlemma continuous_onE:\n    assumes \"continuous_on s f\" \"x\\<in>s\" \"e>0\"\n    obtains d where \"d>0\"  \"\\<And>x'. \\<lbrakk>x' \\<in> s; dist x' x \\<le> d\\<rbrakk> \\<Longrightarrow> dist (f x') (f x) < e\"\n  using assms\n  apply (simp add: continuous_on_iff)\n  apply (elim ballE allE)\n  apply (auto intro: that [where d=\"d/2\" for d])\n  done\n\ntext\\<open>The usual transformation theorems.\\<close>\n\nlemma continuous_transform_within:\n  fixes f g :: \"'a::metric_space \\<Rightarrow> 'b::topological_space\"\n  assumes \"continuous (at x within s) f\"\n    and \"0 < d\"\n    and \"x \\<in> s\"\n    and \"\\<And>x'. \\<lbrakk>x' \\<in> s; dist x' x < d\\<rbrakk> \\<Longrightarrow> f x' = g x'\"\n  shows \"continuous (at x within s) g\"\n  using assms\n  unfolding continuous_within\n  by (force intro: Lim_transform_within)\n\n\nsubsection \\<open>Closure and Limit Characterization\\<close>\n\nlemma closure_approachable:\n  fixes S :: \"'a::metric_space set\"\n  shows \"x \\<in> closure S \\<longleftrightarrow> (\\<forall>e>0. \\<exists>y\\<in>S. dist y x < e)\"\n  apply (auto simp: closure_def islimpt_approachable)\n  apply (metis dist_self)\n  done\n\nlemma closure_approachable_le:\n  fixes S :: \"'a::metric_space set\"\n  shows \"x \\<in> closure S \\<longleftrightarrow> (\\<forall>e>0. \\<exists>y\\<in>S. dist y x \\<le> e)\"\n  unfolding closure_approachable\n  using dense by force\n\nlemma closure_approachableD:\n  assumes \"x \\<in> closure S\" \"e>0\"\n  shows \"\\<exists>y\\<in>S. dist x y < e\"\n  using assms unfolding closure_approachable by (auto simp: dist_commute)\n\nlemma closed_approachable:\n  fixes S :: \"'a::metric_space set\"\n  shows \"closed S \\<Longrightarrow> (\\<forall>e>0. \\<exists>y\\<in>S. dist y x < e) \\<longleftrightarrow> x \\<in> S\"\n  by (metis closure_closed closure_approachable)\n\nlemma closure_contains_Inf:\n  fixes S :: \"real set\"\n  assumes \"S \\<noteq> {}\" \"bdd_below S\"\n  shows \"Inf S \\<in> closure S\"\nproof -\n  have *: \"\\<forall>x\\<in>S. Inf S \\<le> x\"\n    using cInf_lower[of _ S] assms by metis\n  {\n    fix e :: real\n    assume \"e > 0\"\n    then have \"Inf S < Inf S + e\" by simp\n    with assms obtain x where \"x \\<in> S\" \"x < Inf S + e\"\n      by (subst (asm) cInf_less_iff) auto\n    with * have \"\\<exists>x\\<in>S. dist x (Inf S) < e\"\n      by (intro bexI[of _ x]) (auto simp: dist_real_def)\n  }\n  then show ?thesis unfolding closure_approachable by auto\nqed\n\nlemma closure_contains_Sup:\n  fixes S :: \"real set\"\n  assumes \"S \\<noteq> {}\" \"bdd_above S\"\n  shows \"Sup S \\<in> closure S\"\nproof -\n  have *: \"\\<forall>x\\<in>S. x \\<le> Sup S\"\n    using cSup_upper[of _ S] assms by metis\n  {\n    fix e :: real\n    assume \"e > 0\"\n    then have \"Sup S - e < Sup S\" by simp\n    with assms obtain x where \"x \\<in> S\" \"Sup S - e < x\"\n      by (subst (asm) less_cSup_iff) auto\n    with * have \"\\<exists>x\\<in>S. dist x (Sup S) < e\"\n      by (intro bexI[of _ x]) (auto simp: dist_real_def)\n  }\n  then show ?thesis unfolding closure_approachable by auto\nqed\n\nlemma not_trivial_limit_within_ball:\n  \"\\<not> trivial_limit (at x within S) \\<longleftrightarrow> (\\<forall>e>0. S \\<inter> ball x e - {x} \\<noteq> {})\"\n  (is \"?lhs \\<longleftrightarrow> ?rhs\")\nproof\n  show ?rhs if ?lhs\n  proof -\n    {\n      fix e :: real\n      assume \"e > 0\"\n      then obtain y where \"y \\<in> S - {x}\" and \"dist y x < e\"\n        using \\<open>?lhs\\<close> not_trivial_limit_within[of x S] closure_approachable[of x \"S - {x}\"]\n        by auto\n      then have \"y \\<in> S \\<inter> ball x e - {x}\"\n        unfolding ball_def by (simp add: dist_commute)\n      then have \"S \\<inter> ball x e - {x} \\<noteq> {}\" by blast\n    }\n    then show ?thesis by auto\n  qed\n  show ?lhs if ?rhs\n  proof -\n    {\n      fix e :: real\n      assume \"e > 0\"\n      then obtain y where \"y \\<in> S \\<inter> ball x e - {x}\"\n        using \\<open>?rhs\\<close> by blast\n      then have \"y \\<in> S - {x}\" and \"dist y x < e\"\n        unfolding ball_def by (simp_all add: dist_commute)\n      then have \"\\<exists>y \\<in> S - {x}. dist y x < e\"\n        by auto\n    }\n    then show ?thesis\n      using not_trivial_limit_within[of x S] closure_approachable[of x \"S - {x}\"]\n      by auto\n  qed\nqed\n\n\nsubsection \\<open>Boundedness\\<close>\n\n  (* FIXME: This has to be unified with BSEQ!! *)\ndefinition\\<^marker>\\<open>tag important\\<close> (in metric_space) bounded :: \"'a set \\<Rightarrow> bool\"\n  where \"bounded S \\<longleftrightarrow> (\\<exists>x e. \\<forall>y\\<in>S. dist x y \\<le> e)\"\n\nlemma bounded_subset_cball: \"bounded S \\<longleftrightarrow> (\\<exists>e x. S \\<subseteq> cball x e \\<and> 0 \\<le> e)\"\n  unfolding bounded_def subset_eq  by auto (meson order_trans zero_le_dist)\n\nlemma bounded_any_center: \"bounded S \\<longleftrightarrow> (\\<exists>e. \\<forall>y\\<in>S. dist a y \\<le> e)\"\n  unfolding bounded_def\n  by auto (metis add.commute add_le_cancel_right dist_commute dist_triangle_le)\n\nlemma bounded_iff: \"bounded S \\<longleftrightarrow> (\\<exists>a. \\<forall>x\\<in>S. norm x \\<le> a)\"\n  unfolding bounded_any_center [where a=0]\n  by (simp add: dist_norm)\n\nlemma bdd_above_norm: \"bdd_above (norm ` X) \\<longleftrightarrow> bounded X\"\n  by (simp add: bounded_iff bdd_above_def)\n\nlemma bounded_norm_comp: \"bounded ((\\<lambda>x. norm (f x)) ` S) = bounded (f ` S)\"\n  by (simp add: bounded_iff)\n\nlemma boundedI:\n  assumes \"\\<And>x. x \\<in> S \\<Longrightarrow> norm x \\<le> B\"\n  shows \"bounded S\"\n  using assms bounded_iff by blast\n\nlemma bounded_empty [simp]: \"bounded {}\"\n  by (simp add: bounded_def)\n\nlemma bounded_subset: \"bounded T \\<Longrightarrow> S \\<subseteq> T \\<Longrightarrow> bounded S\"\n  by (metis bounded_def subset_eq)\n\nlemma bounded_interior[intro]: \"bounded S \\<Longrightarrow> bounded(interior S)\"\n  by (metis bounded_subset interior_subset)\n\nlemma bounded_closure[intro]:\n  assumes \"bounded S\"\n  shows \"bounded (closure S)\"\nproof -\n  from assms obtain x and a where a: \"\\<forall>y\\<in>S. dist x y \\<le> a\"\n    unfolding bounded_def by auto\n  {\n    fix y\n    assume \"y \\<in> closure S\"\n    then obtain f where f: \"\\<forall>n. f n \\<in> S\"  \"(f \\<longlongrightarrow> y) sequentially\"\n      unfolding closure_sequential by auto\n    have \"\\<forall>n. f n \\<in> S \\<longrightarrow> dist x (f n) \\<le> a\" using a by simp\n    then have \"eventually (\\<lambda>n. dist x (f n) \\<le> a) sequentially\"\n      by (simp add: f(1))\n    then have \"dist x y \\<le> a\"\n      using Lim_dist_ubound f(2) trivial_limit_sequentially by blast\n  }\n  then show ?thesis\n    unfolding bounded_def by auto\nqed\n\nlemma bounded_closure_image: \"bounded (f ` closure S) \\<Longrightarrow> bounded (f ` S)\"\n  by (simp add: bounded_subset closure_subset image_mono)\n\nlemma bounded_cball[simp,intro]: \"bounded (cball x e)\"\n  unfolding bounded_def  using mem_cball by blast\n\nlemma bounded_ball[simp,intro]: \"bounded (ball x e)\"\n  by (metis ball_subset_cball bounded_cball bounded_subset)\n\nlemma bounded_Un[simp]: \"bounded (S \\<union> T) \\<longleftrightarrow> bounded S \\<and> bounded T\"\n  by (auto simp: bounded_def) (metis Un_iff bounded_any_center le_max_iff_disj)\n\nlemma bounded_Union[intro]: \"finite F \\<Longrightarrow> \\<forall>S\\<in>F. bounded S \\<Longrightarrow> bounded (\\<Union>F)\"\n  by (induct rule: finite_induct[of F]) auto\n\nlemma bounded_UN [intro]: \"finite A \\<Longrightarrow> \\<forall>x\\<in>A. bounded (B x) \\<Longrightarrow> bounded (\\<Union>x\\<in>A. B x)\"\n  by auto\n\nlemma bounded_insert [simp]: \"bounded (insert x S) \\<longleftrightarrow> bounded S\"\nproof -\n  have \"\\<forall>y\\<in>{x}. dist x y \\<le> 0\"\n    by simp\n  then have \"bounded {x}\"\n    unfolding bounded_def by fast\n  then show ?thesis\n    by (metis insert_is_Un bounded_Un)\nqed\n\nlemma bounded_subset_ballI: \"S \\<subseteq> ball x r \\<Longrightarrow> bounded S\"\n  by (meson bounded_ball bounded_subset)\n\nlemma bounded_subset_ballD:\n  assumes \"bounded S\" shows \"\\<exists>r. 0 < r \\<and> S \\<subseteq> ball x r\"\nproof -\n  obtain e::real and y where \"S \\<subseteq> cball y e\" \"0 \\<le> e\"\n    using assms by (auto simp: bounded_subset_cball)\n  then show ?thesis\n    by (intro exI[where x=\"dist x y + e + 1\"]) metric\nqed\n\nlemma finite_imp_bounded [intro]: \"finite S \\<Longrightarrow> bounded S\"\n  by (induct set: finite) simp_all\n\nlemma bounded_Int[intro]: \"bounded S \\<or> bounded T \\<Longrightarrow> bounded (S \\<inter> T)\"\n  by (metis Int_lower1 Int_lower2 bounded_subset)\n\nlemma bounded_diff[intro]: \"bounded S \\<Longrightarrow> bounded (S - T)\"\n  by (metis Diff_subset bounded_subset)\n\nlemma bounded_dist_comp:\n  assumes \"bounded (f ` S)\" \"bounded (g ` S)\"\n  shows \"bounded ((\\<lambda>x. dist (f x) (g x)) ` S)\"\nproof -\n  from assms obtain M1 M2 where *: \"dist (f x) undefined \\<le> M1\" \"dist undefined (g x) \\<le> M2\" if \"x \\<in> S\" for x\n    by (auto simp: bounded_any_center[of _ undefined] dist_commute)\n  have \"dist (f x) (g x) \\<le> M1 + M2\" if \"x \\<in> S\" for x\n    using *[OF that]\n    by metric\n  then show ?thesis\n    by (auto intro!: boundedI)\nqed\n\nlemma bounded_Times:\n  assumes \"bounded s\" \"bounded t\"\n  shows \"bounded (s \\<times> t)\"\nproof -\n  obtain x y a b where \"\\<forall>z\\<in>s. dist x z \\<le> a\" \"\\<forall>z\\<in>t. dist y z \\<le> b\"\n    using assms [unfolded bounded_def] by auto\n  then have \"\\<forall>z\\<in>s \\<times> t. dist (x, y) z \\<le> sqrt (a\\<^sup>2 + b\\<^sup>2)\"\n    by (auto simp: dist_Pair_Pair real_sqrt_le_mono add_mono power_mono)\n  then show ?thesis unfolding bounded_any_center [where a=\"(x, y)\"] by auto\nqed\n\n\nsubsection \\<open>Compactness\\<close>\n\nlemma compact_imp_bounded:\n  assumes \"compact U\"\n  shows \"bounded U\"\nproof -\n  have \"compact U\" \"\\<forall>x\\<in>U. open (ball x 1)\" \"U \\<subseteq> (\\<Union>x\\<in>U. ball x 1)\"\n    using assms by auto\n  then obtain D where D: \"D \\<subseteq> U\" \"finite D\" \"U \\<subseteq> (\\<Union>x\\<in>D. ball x 1)\"\n    by (metis compactE_image)\n  from \\<open>finite D\\<close> have \"bounded (\\<Union>x\\<in>D. ball x 1)\"\n    by (simp add: bounded_UN)\n  then show \"bounded U\" using \\<open>U \\<subseteq> (\\<Union>x\\<in>D. ball x 1)\\<close>\n    by (rule bounded_subset)\nqed\n\nlemma closure_Int_ball_not_empty:\n  assumes \"S \\<subseteq> closure T\" \"x \\<in> S\" \"r > 0\"\n  shows \"T \\<inter> ball x r \\<noteq> {}\"\n  using assms centre_in_ball closure_iff_nhds_not_empty by blast\n\nlemma compact_sup_maxdistance:\n  fixes S :: \"'a::metric_space set\"\n  assumes \"compact S\"\n    and \"S \\<noteq> {}\"\n  shows \"\\<exists>x\\<in>S. \\<exists>y\\<in>S. \\<forall>u\\<in>S. \\<forall>v\\<in>S. dist u v \\<le> dist x y\"\nproof -\n  have \"compact (S \\<times> S)\"\n    using \\<open>compact S\\<close> by (intro compact_Times)\n  moreover have \"S \\<times> S \\<noteq> {}\"\n    using \\<open>S \\<noteq> {}\\<close> by auto\n  moreover have \"continuous_on (S \\<times> S) (\\<lambda>x. dist (fst x) (snd x))\"\n    by (intro continuous_at_imp_continuous_on ballI continuous_intros)\n  ultimately show ?thesis\n    using continuous_attains_sup[of \"S \\<times> S\" \"\\<lambda>x. dist (fst x) (snd x)\"] by auto\nqed\n\n\nsubsubsection\\<open>Totally bounded\\<close>\n\nlemma cauchy_def: \"Cauchy S \\<longleftrightarrow> (\\<forall>e>0. \\<exists>N. \\<forall>m n. m \\<ge> N \\<and> n \\<ge> N \\<longrightarrow> dist (S m) (S n) < e)\"\n  unfolding Cauchy_def by metis\n\nproposition seq_compact_imp_totally_bounded:\n  assumes \"seq_compact S\"\n  shows \"\\<forall>e>0. \\<exists>k. finite k \\<and> k \\<subseteq> S \\<and> S \\<subseteq> (\\<Union>x\\<in>k. ball x e)\"\nproof -\n  { fix e::real assume \"e > 0\" assume *: \"\\<And>k. finite k \\<Longrightarrow> k \\<subseteq> S \\<Longrightarrow> \\<not> S \\<subseteq> (\\<Union>x\\<in>k. ball x e)\"\n    let ?Q = \"\\<lambda>x n r. r \\<in> S \\<and> (\\<forall>m < (n::nat). \\<not> (dist (x m) r < e))\"\n    have \"\\<exists>x. \\<forall>n::nat. ?Q x n (x n)\"\n    proof (rule dependent_wellorder_choice)\n      fix n x assume \"\\<And>y. y < n \\<Longrightarrow> ?Q x y (x y)\"\n      then have \"\\<not> S \\<subseteq> (\\<Union>x\\<in>x ` {0..<n}. ball x e)\"\n        using *[of \"x ` {0 ..< n}\"] by (auto simp: subset_eq)\n      then obtain z where z:\"z\\<in>S\" \"z \\<notin> (\\<Union>x\\<in>x ` {0..<n}. ball x e)\"\n        unfolding subset_eq by auto\n      show \"\\<exists>r. ?Q x n r\"\n        using z by auto\n    qed simp\n    then obtain x where \"\\<forall>n::nat. x n \\<in> S\" and x:\"\\<And>n m. m < n \\<Longrightarrow> \\<not> (dist (x m) (x n) < e)\"\n      by blast\n    then obtain l r where \"l \\<in> S\" and r:\"strict_mono  r\" and \"((x \\<circ> r) \\<longlongrightarrow> l) sequentially\"\n      using assms by (metis seq_compact_def)\n    then have \"Cauchy (x \\<circ> r)\"\n      using LIMSEQ_imp_Cauchy by auto\n    then obtain N::nat where \"\\<And>m n. N \\<le> m \\<Longrightarrow> N \\<le> n \\<Longrightarrow> dist ((x \\<circ> r) m) ((x \\<circ> r) n) < e\"\n      unfolding cauchy_def using \\<open>e > 0\\<close> by blast\n    then have False\n      using x[of \"r N\" \"r (N+1)\"] r by (auto simp: strict_mono_def) }\n  then show ?thesis\n    by metis\nqed\n\nsubsubsection\\<open>Heine-Borel theorem\\<close>\n\nproposition seq_compact_imp_Heine_Borel:\n  fixes S :: \"'a :: metric_space set\"\n  assumes \"seq_compact S\"\n  shows \"compact S\"\nproof -\n  from seq_compact_imp_totally_bounded[OF \\<open>seq_compact S\\<close>]\n  obtain f where f: \"\\<forall>e>0. finite (f e) \\<and> f e \\<subseteq> S \\<and> S \\<subseteq> (\\<Union>x\\<in>f e. ball x e)\"\n    unfolding choice_iff' ..\n  define K where \"K = (\\<lambda>(x, r). ball x r) ` ((\\<Union>e \\<in> \\<rat> \\<inter> {0 <..}. f e) \\<times> \\<rat>)\"\n  have \"countably_compact S\"\n    using \\<open>seq_compact S\\<close> by (rule seq_compact_imp_countably_compact)\n  then show \"compact S\"\n  proof (rule countably_compact_imp_compact)\n    show \"countable K\"\n      unfolding K_def using f\n      by (auto intro: countable_finite countable_subset countable_rat\n               intro!: countable_image countable_SIGMA countable_UN)\n    show \"\\<forall>b\\<in>K. open b\" by (auto simp: K_def)\n  next\n    fix T x\n    assume T: \"open T\" \"x \\<in> T\" and x: \"x \\<in> S\"\n    from openE[OF T] obtain e where \"0 < e\" \"ball x e \\<subseteq> T\"\n      by auto\n    then have \"0 < e/2\" \"ball x (e/2) \\<subseteq> T\"\n      by auto\n    from Rats_dense_in_real[OF \\<open>0 < e/2\\<close>] obtain r where \"r \\<in> \\<rat>\" \"0 < r\" \"r < e/2\"\n      by auto\n    from f[rule_format, of r] \\<open>0 < r\\<close> \\<open>x \\<in> S\\<close> obtain k where \"k \\<in> f r\" \"x \\<in> ball k r\"\n      by auto\n    from \\<open>r \\<in> \\<rat>\\<close> \\<open>0 < r\\<close> \\<open>k \\<in> f r\\<close> have \"ball k r \\<in> K\"\n      by (auto simp: K_def)\n    then show \"\\<exists>b\\<in>K. x \\<in> b \\<and> b \\<inter> S \\<subseteq> T\"\n    proof (rule bexI[rotated], safe)\n      fix y\n      assume \"y \\<in> ball k r\"\n      with \\<open>r < e/2\\<close> \\<open>x \\<in> ball k r\\<close> have \"dist x y < e\"\n        by (intro dist_triangle_half_r [of k _ e]) (auto simp: dist_commute)\n      with \\<open>ball x e \\<subseteq> T\\<close> show \"y \\<in> T\"\n        by auto\n    next\n      show \"x \\<in> ball k r\" by fact\n    qed\n  qed\nqed\n\nproposition compact_eq_seq_compact_metric:\n  \"compact (S :: 'a::metric_space set) \\<longleftrightarrow> seq_compact S\"\n  using compact_imp_seq_compact seq_compact_imp_Heine_Borel by blast\n\nproposition compact_def: \\<comment> \\<open>this is the definition of compactness in HOL Light\\<close>\n  \"compact (S :: 'a::metric_space set) \\<longleftrightarrow>\n   (\\<forall>f. (\\<forall>n. f n \\<in> S) \\<longrightarrow> (\\<exists>l\\<in>S. \\<exists>r::nat\\<Rightarrow>nat. strict_mono r \\<and> (f \\<circ> r) \\<longlonglongrightarrow> l))\"\n  unfolding compact_eq_seq_compact_metric seq_compact_def by auto\n\nsubsubsection \\<open>Complete the chain of compactness variants\\<close>\n\nproposition compact_eq_Bolzano_Weierstrass:\n  fixes S :: \"'a::metric_space set\"\n  shows \"compact S \\<longleftrightarrow> (\\<forall>T. infinite T \\<and> T \\<subseteq> S \\<longrightarrow> (\\<exists>x \\<in> S. x islimpt T))\"\n  using Bolzano_Weierstrass_imp_seq_compact Heine_Borel_imp_Bolzano_Weierstrass compact_eq_seq_compact_metric \n  by blast\n\nproposition Bolzano_Weierstrass_imp_bounded:\n  \"(\\<And>T. \\<lbrakk>infinite T; T \\<subseteq> S\\<rbrakk> \\<Longrightarrow> (\\<exists>x \\<in> S. x islimpt T)) \\<Longrightarrow> bounded S\"\n  using compact_imp_bounded unfolding compact_eq_Bolzano_Weierstrass by metis\n\n\nsubsection \\<open>Banach fixed point theorem\\<close>\n  \ntheorem banach_fix:\\<comment> \\<open>TODO: rename to \\<open>Banach_fix\\<close>\\<close>\n  assumes s: \"complete s\" \"s \\<noteq> {}\"\n    and c: \"0 \\<le> c\" \"c < 1\"\n    and f: \"f ` s \\<subseteq> s\"\n    and lipschitz: \"\\<forall>x\\<in>s. \\<forall>y\\<in>s. dist (f x) (f y) \\<le> c * dist x y\"\n  shows \"\\<exists>!x\\<in>s. f x = x\"\nproof -\n  from c have \"1 - c > 0\" by simp\n\n  from s(2) obtain z0 where z0: \"z0 \\<in> s\" by blast\n  define z where \"z n = (f ^^ n) z0\" for n\n  with f z0 have z_in_s: \"z n \\<in> s\" for n :: nat\n    by (induct n) auto\n  define d where \"d = dist (z 0) (z 1)\"\n\n  have fzn: \"f (z n) = z (Suc n)\" for n\n    by (simp add: z_def)\n  have cf_z: \"dist (z n) (z (Suc n)) \\<le> (c ^ n) * d\" for n :: nat\n  proof (induct n)\n    case 0\n    then show ?case\n      by (simp add: d_def)\n  next\n    case (Suc m)\n    with \\<open>0 \\<le> c\\<close> have \"c * dist (z m) (z (Suc m)) \\<le> c ^ Suc m * d\"\n      using mult_left_mono[of \"dist (z m) (z (Suc m))\" \"c ^ m * d\" c] by simp\n    then show ?case\n      using lipschitz[THEN bspec[where x=\"z m\"], OF z_in_s, THEN bspec[where x=\"z (Suc m)\"], OF z_in_s]\n      by (simp add: fzn mult_le_cancel_left)\n  qed\n\n  have cf_z2: \"(1 - c) * dist (z m) (z (m + n)) \\<le> (c ^ m) * d * (1 - c ^ n)\" for n m :: nat\n  proof (induct n)\n    case 0\n    show ?case by simp\n  next\n    case (Suc k)\n    from c have \"(1 - c) * dist (z m) (z (m + Suc k)) \\<le>\n        (1 - c) * (dist (z m) (z (m + k)) + dist (z (m + k)) (z (Suc (m + k))))\"\n      by (simp add: dist_triangle)\n    also from c cf_z[of \"m + k\"] have \"\\<dots> \\<le> (1 - c) * (dist (z m) (z (m + k)) + c ^ (m + k) * d)\"\n      by simp\n    also from Suc have \"\\<dots> \\<le> c ^ m * d * (1 - c ^ k) + (1 - c) * c ^ (m + k) * d\"\n      by (simp add: field_simps)\n    also have \"\\<dots> = (c ^ m) * (d * (1 - c ^ k) + (1 - c) * c ^ k * d)\"\n      by (simp add: power_add field_simps)\n    also from c have \"\\<dots> \\<le> (c ^ m) * d * (1 - c ^ Suc k)\"\n      by (simp add: field_simps)\n    finally show ?case by simp\n  qed\n\n  have \"\\<exists>N. \\<forall>m n. N \\<le> m \\<and> N \\<le> n \\<longrightarrow> dist (z m) (z n) < e\" if \"e > 0\" for e\n  proof (cases \"d = 0\")\n    case True\n    from \\<open>1 - c > 0\\<close> have \"(1 - c) * x \\<le> 0 \\<longleftrightarrow> x \\<le> 0\" for x\n      by (simp add: mult_le_0_iff)\n    with c cf_z2[of 0] True have \"z n = z0\" for n\n      by (simp add: z_def)\n    with \\<open>e > 0\\<close> show ?thesis by simp\n  next\n    case False\n    with zero_le_dist[of \"z 0\" \"z 1\"] have \"d > 0\"\n      by (metis d_def less_le)\n    with \\<open>1 - c > 0\\<close> \\<open>e > 0\\<close> have \"0 < e * (1 - c) / d\"\n      by simp\n    with c obtain N where N: \"c ^ N < e * (1 - c) / d\"\n      using real_arch_pow_inv[of \"e * (1 - c) / d\" c] by auto\n    have *: \"dist (z m) (z n) < e\" if \"m > n\" and as: \"m \\<ge> N\" \"n \\<ge> N\" for m n :: nat\n    proof -\n      from c \\<open>n \\<ge> N\\<close> have *: \"c ^ n \\<le> c ^ N\"\n        using power_decreasing[OF \\<open>n\\<ge>N\\<close>, of c] by simp\n      from c \\<open>m > n\\<close> have \"1 - c ^ (m - n) > 0\"\n        using power_strict_mono[of c 1 \"m - n\"] by simp\n      with \\<open>d > 0\\<close> \\<open>0 < 1 - c\\<close> have **: \"d * (1 - c ^ (m - n)) / (1 - c) > 0\"\n        by simp\n      from cf_z2[of n \"m - n\"] \\<open>m > n\\<close>\n      have \"dist (z m) (z n) \\<le> c ^ n * d * (1 - c ^ (m - n)) / (1 - c)\"\n        by (simp add: pos_le_divide_eq[OF \\<open>1 - c > 0\\<close>] mult.commute dist_commute)\n      also have \"\\<dots> \\<le> c ^ N * d * (1 - c ^ (m - n)) / (1 - c)\"\n        using mult_right_mono[OF * order_less_imp_le[OF **]]\n        by (simp add: mult.assoc)\n      also have \"\\<dots> < (e * (1 - c) / d) * d * (1 - c ^ (m - n)) / (1 - c)\"\n        using mult_strict_right_mono[OF N **] by (auto simp: mult.assoc)\n      also from c \\<open>d > 0\\<close> \\<open>1 - c > 0\\<close> have \"\\<dots> = e * (1 - c ^ (m - n))\"\n        by simp\n      also from c \\<open>1 - c ^ (m - n) > 0\\<close> \\<open>e > 0\\<close> have \"\\<dots> \\<le> e\"\n        using mult_right_le_one_le[of e \"1 - c ^ (m - n)\"] by auto\n      finally show ?thesis by simp\n    qed\n    have \"dist (z n) (z m) < e\" if \"N \\<le> m\" \"N \\<le> n\" for m n :: nat\n    proof (cases \"n = m\")\n      case True\n      with \\<open>e > 0\\<close> show ?thesis by simp\n    next\n      case False\n      with *[of n m] *[of m n] and that show ?thesis\n        by (auto simp: dist_commute nat_neq_iff)\n    qed\n    then show ?thesis by auto\n  qed\n  then have \"Cauchy z\"\n    by (simp add: cauchy_def)\n  then obtain x where \"x\\<in>s\" and x:\"(z \\<longlongrightarrow> x) sequentially\"\n    using s(1)[unfolded compact_def complete_def, THEN spec[where x=z]] and z_in_s by auto\n\n  define e where \"e = dist (f x) x\"\n  have \"e = 0\"\n  proof (rule ccontr)\n    assume \"e \\<noteq> 0\"\n    then have \"e > 0\"\n      unfolding e_def using zero_le_dist[of \"f x\" x]\n      by (metis dist_eq_0_iff dist_nz e_def)\n    then obtain N where N:\"\\<forall>n\\<ge>N. dist (z n) x < e/2\"\n      using x[unfolded lim_sequentially, THEN spec[where x=\"e/2\"]] by auto\n    then have N':\"dist (z N) x < e/2\" by auto\n    have *: \"c * dist (z N) x \\<le> dist (z N) x\"\n      unfolding mult_le_cancel_right2\n      using zero_le_dist[of \"z N\" x] and c\n      by (metis dist_eq_0_iff dist_nz order_less_asym less_le)\n    have \"dist (f (z N)) (f x) \\<le> c * dist (z N) x\"\n      using lipschitz[THEN bspec[where x=\"z N\"], THEN bspec[where x=x]]\n      using z_in_s[of N] \\<open>x\\<in>s\\<close>\n      using c\n      by auto\n    also have \"\\<dots> < e/2\"\n      using N' and c using * by auto\n    finally show False\n      unfolding fzn\n      using N[THEN spec[where x=\"Suc N\"]] and dist_triangle_half_r[of \"z (Suc N)\" \"f x\" e x]\n      unfolding e_def\n      by auto\n  qed\n  then have \"f x = x\" by (auto simp: e_def)\n  moreover have \"y = x\" if \"f y = y\" \"y \\<in> s\" for y\n  proof -\n    from \\<open>x \\<in> s\\<close> \\<open>f x = x\\<close> that have \"dist x y \\<le> c * dist x y\"\n      using lipschitz[THEN bspec[where x=x], THEN bspec[where x=y]] by simp\n    with c and zero_le_dist[of x y] have \"dist x y = 0\"\n      by (simp add: mult_le_cancel_right1)\n    then show ?thesis by simp\n  qed\n  ultimately show ?thesis\n    using \\<open>x\\<in>s\\<close> by blast\nqed\n\n\nsubsection \\<open>Edelstein fixed point theorem\\<close>\n\ntheorem Edelstein_fix:\n  fixes S :: \"'a::metric_space set\"\n  assumes S: \"compact S\" \"S \\<noteq> {}\"\n    and gs: \"(g ` S) \\<subseteq> S\"\n    and dist: \"\\<forall>x\\<in>S. \\<forall>y\\<in>S. x \\<noteq> y \\<longrightarrow> dist (g x) (g y) < dist x y\"\n  shows \"\\<exists>!x\\<in>S. g x = x\"\nproof -\n  let ?D = \"(\\<lambda>x. (x, x)) ` S\"\n  have D: \"compact ?D\" \"?D \\<noteq> {}\"\n    by (rule compact_continuous_image)\n       (auto intro!: S continuous_Pair continuous_ident simp: continuous_on_eq_continuous_within)\n\n  have \"\\<And>x y e. x \\<in> S \\<Longrightarrow> y \\<in> S \\<Longrightarrow> 0 < e \\<Longrightarrow> dist y x < e \\<Longrightarrow> dist (g y) (g x) < e\"\n    using dist by fastforce\n  then have \"continuous_on S g\"\n    by (auto simp: continuous_on_iff)\n  then have cont: \"continuous_on ?D (\\<lambda>x. dist ((g \\<circ> fst) x) (snd x))\"\n    unfolding continuous_on_eq_continuous_within\n    by (intro continuous_dist ballI continuous_within_compose)\n       (auto intro!: continuous_fst continuous_snd continuous_ident simp: image_image)\n\n  obtain a where \"a \\<in> S\" and le: \"\\<And>x. x \\<in> S \\<Longrightarrow> dist (g a) a \\<le> dist (g x) x\"\n    using continuous_attains_inf[OF D cont] by auto\n\n  have \"g a = a\"\n  proof (rule ccontr)\n    assume \"g a \\<noteq> a\"\n    with \\<open>a \\<in> S\\<close> gs have \"dist (g (g a)) (g a) < dist (g a) a\"\n      by (intro dist[rule_format]) auto\n    moreover have \"dist (g a) a \\<le> dist (g (g a)) (g a)\"\n      using \\<open>a \\<in> S\\<close> gs by (intro le) auto\n    ultimately show False by auto\n  qed\n  moreover have \"\\<And>x. x \\<in> S \\<Longrightarrow> g x = x \\<Longrightarrow> x = a\"\n    using dist[THEN bspec[where x=a]] \\<open>g a = a\\<close> and \\<open>a\\<in>S\\<close> by auto\n  ultimately show \"\\<exists>!x\\<in>S. g x = x\"\n    using \\<open>a \\<in> S\\<close> by blast\nqed\n\nsubsection \\<open>The diameter of a set\\<close>\n\ndefinition\\<^marker>\\<open>tag important\\<close> diameter :: \"'a::metric_space set \\<Rightarrow> real\" where\n  \"diameter S = (if S = {} then 0 else SUP (x,y)\\<in>S\\<times>S. dist x y)\"\n\nlemma diameter_empty [simp]: \"diameter{} = 0\"\n  by (auto simp: diameter_def)\n\nlemma diameter_singleton [simp]: \"diameter{x} = 0\"\n  by (auto simp: diameter_def)\n\nlemma diameter_le:\n  assumes \"S \\<noteq> {} \\<or> 0 \\<le> d\"\n    and no: \"\\<And>x y. \\<lbrakk>x \\<in> S; y \\<in> S\\<rbrakk> \\<Longrightarrow> norm(x - y) \\<le> d\"\n  shows \"diameter S \\<le> d\"\n  using assms\n  by (auto simp: dist_norm diameter_def intro: cSUP_least)\n\nlemma diameter_bounded_bound:\n  fixes S :: \"'a :: metric_space set\"\n  assumes S: \"bounded S\" \"x \\<in> S\" \"y \\<in> S\"\n  shows \"dist x y \\<le> diameter S\"\nproof -\n  from S obtain z d where z: \"\\<And>x. x \\<in> S \\<Longrightarrow> dist z x \\<le> d\"\n    unfolding bounded_def by auto\n  have \"bdd_above (case_prod dist ` (S\\<times>S))\"\n  proof (intro bdd_aboveI, safe)\n    fix a b\n    assume \"a \\<in> S\" \"b \\<in> S\"\n    with z[of a] z[of b] dist_triangle[of a b z]\n    show \"dist a b \\<le> 2 * d\"\n      by (simp add: dist_commute)\n  qed\n  moreover have \"(x,y) \\<in> S\\<times>S\" using S by auto\n  ultimately have \"dist x y \\<le> (SUP (x,y)\\<in>S\\<times>S. dist x y)\"\n    by (rule cSUP_upper2) simp\n  with \\<open>x \\<in> S\\<close> show ?thesis\n    by (auto simp: diameter_def)\nqed\n\nlemma diameter_lower_bounded:\n  fixes S :: \"'a :: metric_space set\"\n  assumes S: \"bounded S\"\n    and d: \"0 < d\" \"d < diameter S\"\n  shows \"\\<exists>x\\<in>S. \\<exists>y\\<in>S. d < dist x y\"\nproof (rule ccontr)\n  assume contr: \"\\<not> ?thesis\"\n  moreover have \"S \\<noteq> {}\"\n    using d by (auto simp: diameter_def)\n  ultimately have \"diameter S \\<le> d\"\n    by (auto simp: not_less diameter_def intro!: cSUP_least)\n  with \\<open>d < diameter S\\<close> show False by auto\nqed\n\nlemma diameter_bounded:\n  assumes \"bounded S\"\n  shows \"\\<forall>x\\<in>S. \\<forall>y\\<in>S. dist x y \\<le> diameter S\"\n    and \"\\<forall>d>0. d < diameter S \\<longrightarrow> (\\<exists>x\\<in>S. \\<exists>y\\<in>S. dist x y > d)\"\n  using diameter_bounded_bound[of S] diameter_lower_bounded[of S] assms\n  by auto\n\nlemma bounded_two_points: \"bounded S \\<longleftrightarrow> (\\<exists>e. \\<forall>x\\<in>S. \\<forall>y\\<in>S. dist x y \\<le> e)\"\n  by (meson bounded_def diameter_bounded(1))\n\nlemma diameter_compact_attained:\n  assumes \"compact S\"\n    and \"S \\<noteq> {}\"\n  shows \"\\<exists>x\\<in>S. \\<exists>y\\<in>S. dist x y = diameter S\"\nproof -\n  have b: \"bounded S\" using assms(1)\n    by (rule compact_imp_bounded)\n  then obtain x y where xys: \"x\\<in>S\" \"y\\<in>S\"\n    and xy: \"\\<forall>u\\<in>S. \\<forall>v\\<in>S. dist u v \\<le> dist x y\"\n    using compact_sup_maxdistance[OF assms] by auto\n  then have \"diameter S \\<le> dist x y\"\n    unfolding diameter_def\n    apply clarsimp\n    apply (rule cSUP_least, fast+)\n    done\n  then show ?thesis\n    by (metis b diameter_bounded_bound order_antisym xys)\nqed\n\nlemma diameter_ge_0:\n  assumes \"bounded S\"  shows \"0 \\<le> diameter S\"\n  by (metis all_not_in_conv assms diameter_bounded_bound diameter_empty dist_self order_refl)\n\nlemma diameter_subset:\n  assumes \"S \\<subseteq> T\" \"bounded T\"\n  shows \"diameter S \\<le> diameter T\"\nproof (cases \"S = {} \\<or> T = {}\")\n  case True\n  with assms show ?thesis\n    by (force simp: diameter_ge_0)\nnext\n  case False\n  then have \"bdd_above ((\\<lambda>x. case x of (x, xa) \\<Rightarrow> dist x xa) ` (T \\<times> T))\"\n    using \\<open>bounded T\\<close> diameter_bounded_bound by (force simp: bdd_above_def)\n  with False \\<open>S \\<subseteq> T\\<close> show ?thesis\n    apply (simp add: diameter_def)\n    apply (rule cSUP_subset_mono, auto)\n    done\nqed\n\nlemma diameter_closure:\n  assumes \"bounded S\"\n  shows \"diameter(closure S) = diameter S\"\nproof (rule order_antisym)\n  have \"False\" if \"diameter S < diameter (closure S)\"\n  proof -\n    define d where \"d = diameter(closure S) - diameter(S)\"\n    have \"d > 0\"\n      using that by (simp add: d_def)\n    then have \"diameter(closure(S)) - d / 2 < diameter(closure(S))\"\n      by simp\n    have dd: \"diameter (closure S) - d / 2 = (diameter(closure(S)) + diameter(S)) / 2\"\n      by (simp add: d_def field_split_simps)\n     have bocl: \"bounded (closure S)\"\n      using assms by blast\n    moreover have \"0 \\<le> diameter S\"\n      using assms diameter_ge_0 by blast\n    ultimately obtain x y where \"x \\<in> closure S\" \"y \\<in> closure S\" and xy: \"diameter(closure(S)) - d / 2 < dist x y\"\n      using diameter_bounded(2) [OF bocl, rule_format, of \"diameter(closure(S)) - d / 2\"] \\<open>d > 0\\<close> d_def by auto\n    then obtain x' y' where x'y': \"x' \\<in> S\" \"dist x' x < d/4\" \"y' \\<in> S\" \"dist y' y < d/4\"\n      using closure_approachable\n      by (metis \\<open>0 < d\\<close> zero_less_divide_iff zero_less_numeral)\n    then have \"dist x' y' \\<le> diameter S\"\n      using assms diameter_bounded_bound by blast\n    with x'y' have \"dist x y \\<le> d / 4 + diameter S + d / 4\"\n      by (meson add_mono_thms_linordered_semiring(1) dist_triangle dist_triangle3 less_eq_real_def order_trans)\n    then show ?thesis\n      using xy d_def by linarith\n  qed\n  then show \"diameter (closure S) \\<le> diameter S\"\n    by fastforce\n  next\n    show \"diameter S \\<le> diameter (closure S)\"\n      by (simp add: assms bounded_closure closure_subset diameter_subset)\nqed\n\nproposition Lebesgue_number_lemma:\n  assumes \"compact S\" \"\\<C> \\<noteq> {}\" \"S \\<subseteq> \\<Union>\\<C>\" and ope: \"\\<And>B. B \\<in> \\<C> \\<Longrightarrow> open B\"\n  obtains \\<delta> where \"0 < \\<delta>\" \"\\<And>T. \\<lbrakk>T \\<subseteq> S; diameter T < \\<delta>\\<rbrakk> \\<Longrightarrow> \\<exists>B \\<in> \\<C>. T \\<subseteq> B\"\nproof (cases \"S = {}\")\n  case True\n  then show ?thesis\n    by (metis \\<open>\\<C> \\<noteq> {}\\<close> zero_less_one empty_subsetI equals0I subset_trans that)\nnext\n  case False\n  { fix x assume \"x \\<in> S\"\n    then obtain C where C: \"x \\<in> C\" \"C \\<in> \\<C>\"\n      using \\<open>S \\<subseteq> \\<Union>\\<C>\\<close> by blast\n    then obtain r where r: \"r>0\" \"ball x (2*r) \\<subseteq> C\"\n      by (metis mult.commute mult_2_right not_le ope openE field_sum_of_halves zero_le_numeral zero_less_mult_iff)\n    then have \"\\<exists>r C. r > 0 \\<and> ball x (2*r) \\<subseteq> C \\<and> C \\<in> \\<C>\"\n      using C by blast\n  }\n  then obtain r where r: \"\\<And>x. x \\<in> S \\<Longrightarrow> r x > 0 \\<and> (\\<exists>C \\<in> \\<C>. ball x (2*r x) \\<subseteq> C)\"\n    by metis\n  then have \"S \\<subseteq> (\\<Union>x \\<in> S. ball x (r x))\"\n    by auto\n  then obtain \\<T> where \"finite \\<T>\" \"S \\<subseteq> \\<Union>\\<T>\" and \\<T>: \"\\<T> \\<subseteq> (\\<lambda>x. ball x (r x)) ` S\"\n    by (rule compactE [OF \\<open>compact S\\<close>]) auto\n  then obtain S0 where \"S0 \\<subseteq> S\" \"finite S0\" and S0: \"\\<T> = (\\<lambda>x. ball x (r x)) ` S0\"\n    by (meson finite_subset_image)\n  then have \"S0 \\<noteq> {}\"\n    using False \\<open>S \\<subseteq> \\<Union>\\<T>\\<close> by auto\n  define \\<delta> where \"\\<delta> = Inf (r ` S0)\"\n  have \"\\<delta> > 0\"\n    using \\<open>finite S0\\<close> \\<open>S0 \\<subseteq> S\\<close> \\<open>S0 \\<noteq> {}\\<close> r by (auto simp: \\<delta>_def finite_less_Inf_iff)\n  show ?thesis\n  proof\n    show \"0 < \\<delta>\"\n      by (simp add: \\<open>0 < \\<delta>\\<close>)\n    show \"\\<exists>B \\<in> \\<C>. T \\<subseteq> B\" if \"T \\<subseteq> S\" and dia: \"diameter T < \\<delta>\" for T\n    proof (cases \"T = {}\")\n      case True\n      then show ?thesis\n        using \\<open>\\<C> \\<noteq> {}\\<close> by blast\n    next\n      case False\n      then obtain y where \"y \\<in> T\" by blast\n      then have \"y \\<in> S\"\n        using \\<open>T \\<subseteq> S\\<close> by auto\n      then obtain x where \"x \\<in> S0\" and x: \"y \\<in> ball x (r x)\"\n        using \\<open>S \\<subseteq> \\<Union>\\<T>\\<close> S0 that by blast\n      have \"ball y \\<delta> \\<subseteq> ball y (r x)\"\n        by (metis \\<delta>_def \\<open>S0 \\<noteq> {}\\<close> \\<open>finite S0\\<close> \\<open>x \\<in> S0\\<close> empty_is_image finite_imageI finite_less_Inf_iff imageI less_irrefl not_le subset_ball)\n      also have \"... \\<subseteq> ball x (2*r x)\"\n        using x by metric\n      finally obtain C where \"C \\<in> \\<C>\" \"ball y \\<delta> \\<subseteq> C\"\n        by (meson r \\<open>S0 \\<subseteq> S\\<close> \\<open>x \\<in> S0\\<close> dual_order.trans subsetCE)\n      have \"bounded T\"\n        using \\<open>compact S\\<close> bounded_subset compact_imp_bounded \\<open>T \\<subseteq> S\\<close> by blast\n      then have \"T \\<subseteq> ball y \\<delta>\"\n        using \\<open>y \\<in> T\\<close> dia diameter_bounded_bound by fastforce\n      then show ?thesis\n        apply (rule_tac x=C in bexI)\n        using \\<open>ball y \\<delta> \\<subseteq> C\\<close> \\<open>C \\<in> \\<C>\\<close> by auto\n    qed\n  qed\nqed\n\n\nsubsection \\<open>Metric spaces with the Heine-Borel property\\<close>\n\ntext \\<open>\n  A metric space (or topological vector space) is said to have the\n  Heine-Borel property if every closed and bounded subset is compact.\n\\<close>\n\nclass heine_borel = metric_space +\n  assumes bounded_imp_convergent_subsequence:\n    \"bounded (range f) \\<Longrightarrow> \\<exists>l r. strict_mono (r::nat\\<Rightarrow>nat) \\<and> ((f \\<circ> r) \\<longlongrightarrow> l) sequentially\"\n\nproposition bounded_closed_imp_seq_compact:\n  fixes S::\"'a::heine_borel set\"\n  assumes \"bounded S\"\n    and \"closed S\"\n  shows \"seq_compact S\"\nproof (unfold seq_compact_def, clarify)\n  fix f :: \"nat \\<Rightarrow> 'a\"\n  assume f: \"\\<forall>n. f n \\<in> S\"\n  with \\<open>bounded S\\<close> have \"bounded (range f)\"\n    by (auto intro: bounded_subset)\n  obtain l r where r: \"strict_mono (r :: nat \\<Rightarrow> nat)\" and l: \"((f \\<circ> r) \\<longlongrightarrow> l) sequentially\"\n    using bounded_imp_convergent_subsequence [OF \\<open>bounded (range f)\\<close>] by auto\n  from f have fr: \"\\<forall>n. (f \\<circ> r) n \\<in> S\"\n    by simp\n  have \"l \\<in> S\" using \\<open>closed S\\<close> fr l\n    by (rule closed_sequentially)\n  show \"\\<exists>l\\<in>S. \\<exists>r. strict_mono r \\<and> ((f \\<circ> r) \\<longlongrightarrow> l) sequentially\"\n    using \\<open>l \\<in> S\\<close> r l by blast\nqed\n\nlemma compact_eq_bounded_closed:\n  fixes S :: \"'a::heine_borel set\"\n  shows \"compact S \\<longleftrightarrow> bounded S \\<and> closed S\"\n  using bounded_closed_imp_seq_compact compact_eq_seq_compact_metric compact_imp_bounded compact_imp_closed \n  by auto\n\nlemma bounded_infinite_imp_islimpt:\n  fixes S :: \"'a::heine_borel set\"\n  assumes \"T \\<subseteq> S\" \"bounded S\" \"infinite T\"\n  obtains x where \"x islimpt S\" \n  by (meson assms closed_limpt compact_eq_Bolzano_Weierstrass compact_eq_bounded_closed islimpt_subset) \n\nlemma compact_Inter:\n  fixes \\<F> :: \"'a :: heine_borel set set\"\n  assumes com: \"\\<And>S. S \\<in> \\<F> \\<Longrightarrow> compact S\" and \"\\<F> \\<noteq> {}\"\n  shows \"compact(\\<Inter> \\<F>)\"\n  using assms\n  by (meson Inf_lower all_not_in_conv bounded_subset closed_Inter compact_eq_bounded_closed)\n\nlemma compact_closure [simp]:\n  fixes S :: \"'a::heine_borel set\"\n  shows \"compact(closure S) \\<longleftrightarrow> bounded S\"\nby (meson bounded_closure bounded_subset closed_closure closure_subset compact_eq_bounded_closed)\n\ninstance\\<^marker>\\<open>tag important\\<close> real :: heine_borel\nproof\n  fix f :: \"nat \\<Rightarrow> real\"\n  assume f: \"bounded (range f)\"\n  obtain r :: \"nat \\<Rightarrow> nat\" where r: \"strict_mono r\" \"monoseq (f \\<circ> r)\"\n    unfolding comp_def by (metis seq_monosub)\n  then have \"Bseq (f \\<circ> r)\"\n    unfolding Bseq_eq_bounded using f\n    by (metis BseqI' bounded_iff comp_apply rangeI)\n  with r show \"\\<exists>l r. strict_mono r \\<and> (f \\<circ> r) \\<longlonglongrightarrow> l\"\n    using Bseq_monoseq_convergent[of \"f \\<circ> r\"] by (auto simp: convergent_def)\nqed\n\nlemma compact_lemma_general:\n  fixes f :: \"nat \\<Rightarrow> 'a\"\n  fixes proj::\"'a \\<Rightarrow> 'b \\<Rightarrow> 'c::heine_borel\" (infixl \"proj\" 60)\n  fixes unproj:: \"('b \\<Rightarrow> 'c) \\<Rightarrow> 'a\"\n  assumes finite_basis: \"finite basis\"\n  assumes bounded_proj: \"\\<And>k. k \\<in> basis \\<Longrightarrow> bounded ((\\<lambda>x. x proj k) ` range f)\"\n  assumes proj_unproj: \"\\<And>e k. k \\<in> basis \\<Longrightarrow> (unproj e) proj k = e k\"\n  assumes unproj_proj: \"\\<And>x. unproj (\\<lambda>k. x proj k) = x\"\n  shows \"\\<forall>d\\<subseteq>basis. \\<exists>l::'a. \\<exists> r::nat\\<Rightarrow>nat.\n    strict_mono r \\<and> (\\<forall>e>0. eventually (\\<lambda>n. \\<forall>i\\<in>d. dist (f (r n) proj i) (l proj i) < e) sequentially)\"\nproof safe\n  fix d :: \"'b set\"\n  assume d: \"d \\<subseteq> basis\"\n  with finite_basis have \"finite d\"\n    by (blast intro: finite_subset)\n  from this d show \"\\<exists>l::'a. \\<exists>r::nat\\<Rightarrow>nat. strict_mono r \\<and>\n    (\\<forall>e>0. eventually (\\<lambda>n. \\<forall>i\\<in>d. dist (f (r n) proj i) (l proj i) < e) sequentially)\"\n  proof (induct d)\n    case empty\n    then show ?case\n      unfolding strict_mono_def by auto\n  next\n    case (insert k d)\n    have k[intro]: \"k \\<in> basis\"\n      using insert by auto\n    have s': \"bounded ((\\<lambda>x. x proj k) ` range f)\"\n      using k\n      by (rule bounded_proj)\n    obtain l1::\"'a\" and r1 where r1: \"strict_mono r1\"\n      and lr1: \"\\<forall>e > 0. eventually (\\<lambda>n. \\<forall>i\\<in>d. dist (f (r1 n) proj i) (l1 proj i) < e) sequentially\"\n      using insert(3) using insert(4) by auto\n    have f': \"\\<forall>n. f (r1 n) proj k \\<in> (\\<lambda>x. x proj k) ` range f\"\n      by simp\n    have \"bounded (range (\\<lambda>i. f (r1 i) proj k))\"\n      by (metis (lifting) bounded_subset f' image_subsetI s')\n    then obtain l2 r2 where r2:\"strict_mono r2\" and lr2:\"((\\<lambda>i. f (r1 (r2 i)) proj k) \\<longlongrightarrow> l2) sequentially\"\n      using bounded_imp_convergent_subsequence[of \"\\<lambda>i. f (r1 i) proj k\"]\n      by (auto simp: o_def)\n    define r where \"r = r1 \\<circ> r2\"\n    have r:\"strict_mono r\"\n      using r1 and r2 unfolding r_def o_def strict_mono_def by auto\n    moreover\n    define l where \"l = unproj (\\<lambda>i. if i = k then l2 else l1 proj i)\"\n    {\n      fix e::real\n      assume \"e > 0\"\n      from lr1 \\<open>e > 0\\<close> have N1: \"eventually (\\<lambda>n. \\<forall>i\\<in>d. dist (f (r1 n) proj i) (l1 proj i) < e) sequentially\"\n        by blast\n      from lr2 \\<open>e > 0\\<close> have N2:\"eventually (\\<lambda>n. dist (f (r1 (r2 n)) proj k) l2 < e) sequentially\"\n        by (rule tendstoD)\n      from r2 N1 have N1': \"eventually (\\<lambda>n. \\<forall>i\\<in>d. dist (f (r1 (r2 n)) proj i) (l1 proj i) < e) sequentially\"\n        by (rule eventually_subseq)\n      have \"eventually (\\<lambda>n. \\<forall>i\\<in>(insert k d). dist (f (r n) proj i) (l proj i) < e) sequentially\"\n        using N1' N2\n        by eventually_elim (insert insert.prems, auto simp: l_def r_def o_def proj_unproj)\n    }\n    ultimately show ?case by auto\n  qed\nqed\n\nlemma bounded_fst: \"bounded s \\<Longrightarrow> bounded (fst ` s)\"\n  unfolding bounded_def\n  by (metis (erased, opaque_lifting) dist_fst_le image_iff order_trans)\n\nlemma bounded_snd: \"bounded s \\<Longrightarrow> bounded (snd ` s)\"\n  unfolding bounded_def\n  by (metis (no_types, opaque_lifting) dist_snd_le image_iff order.trans)\n\ninstance\\<^marker>\\<open>tag important\\<close> prod :: (heine_borel, heine_borel) heine_borel\nproof\n  fix f :: \"nat \\<Rightarrow> 'a \\<times> 'b\"\n  assume f: \"bounded (range f)\"\n  then have \"bounded (fst ` range f)\"\n    by (rule bounded_fst)\n  then have s1: \"bounded (range (fst \\<circ> f))\"\n    by (simp add: image_comp)\n  obtain l1 r1 where r1: \"strict_mono r1\" and l1: \"(\\<lambda>n. fst (f (r1 n))) \\<longlonglongrightarrow> l1\"\n    using bounded_imp_convergent_subsequence [OF s1] unfolding o_def by fast\n  from f have s2: \"bounded (range (snd \\<circ> f \\<circ> r1))\"\n    by (auto simp: image_comp intro: bounded_snd bounded_subset)\n  obtain l2 r2 where r2: \"strict_mono r2\" and l2: \"((\\<lambda>n. snd (f (r1 (r2 n)))) \\<longlongrightarrow> l2) sequentially\"\n    using bounded_imp_convergent_subsequence [OF s2]\n    unfolding o_def by fast\n  have l1': \"((\\<lambda>n. fst (f (r1 (r2 n)))) \\<longlongrightarrow> l1) sequentially\"\n    using LIMSEQ_subseq_LIMSEQ [OF l1 r2] unfolding o_def .\n  have l: \"((f \\<circ> (r1 \\<circ> r2)) \\<longlongrightarrow> (l1, l2)) sequentially\"\n    using tendsto_Pair [OF l1' l2] unfolding o_def by simp\n  have r: \"strict_mono (r1 \\<circ> r2)\"\n    using r1 r2 unfolding strict_mono_def by simp\n  show \"\\<exists>l r. strict_mono r \\<and> ((f \\<circ> r) \\<longlongrightarrow> l) sequentially\"\n    using l r by fast\nqed\n\n\nsubsection \\<open>Completeness\\<close>\n\nproposition (in metric_space) completeI:\n  assumes \"\\<And>f. \\<forall>n. f n \\<in> s \\<Longrightarrow> Cauchy f \\<Longrightarrow> \\<exists>l\\<in>s. f \\<longlonglongrightarrow> l\"\n  shows \"complete s\"\n  using assms unfolding complete_def by fast\n\nproposition (in metric_space) completeE:\n  assumes \"complete s\" and \"\\<forall>n. f n \\<in> s\" and \"Cauchy f\"\n  obtains l where \"l \\<in> s\" and \"f \\<longlonglongrightarrow> l\"\n  using assms unfolding complete_def by fast\n\n(* TODO: generalize to uniform spaces *)\nlemma compact_imp_complete:\n  fixes s :: \"'a::metric_space set\"\n  assumes \"compact s\"\n  shows \"complete s\"\nproof -\n  {\n    fix f\n    assume as: \"(\\<forall>n::nat. f n \\<in> s)\" \"Cauchy f\"\n    from as(1) obtain l r where lr: \"l\\<in>s\" \"strict_mono r\" \"(f \\<circ> r) \\<longlonglongrightarrow> l\"\n      using assms unfolding compact_def by blast\n\n    note lr' = seq_suble [OF lr(2)]\n    {\n      fix e :: real\n      assume \"e > 0\"\n      from as(2) obtain N where N:\"\\<forall>m n. N \\<le> m \\<and> N \\<le> n \\<longrightarrow> dist (f m) (f n) < e/2\"\n        unfolding cauchy_def\n        using \\<open>e > 0\\<close>\n        apply (erule_tac x=\"e/2\" in allE, auto)\n        done\n      from lr(3)[unfolded lim_sequentially, THEN spec[where x=\"e/2\"]]\n      obtain M where M:\"\\<forall>n\\<ge>M. dist ((f \\<circ> r) n) l < e/2\"\n        using \\<open>e > 0\\<close> by auto\n      {\n        fix n :: nat\n        assume n: \"n \\<ge> max N M\"\n        have \"dist ((f \\<circ> r) n) l < e/2\"\n          using n M by auto\n        moreover have \"r n \\<ge> N\"\n          using lr'[of n] n by auto\n        then have \"dist (f n) ((f \\<circ> r) n) < e/2\"\n          using N and n by auto\n        ultimately have \"dist (f n) l < e\" using n M\n          by metric\n      }\n      then have \"\\<exists>N. \\<forall>n\\<ge>N. dist (f n) l < e\" by blast\n    }\n    then have \"\\<exists>l\\<in>s. (f \\<longlongrightarrow> l) sequentially\" using \\<open>l\\<in>s\\<close>\n      unfolding lim_sequentially by auto\n  }\n  then show ?thesis unfolding complete_def by auto\nqed\n\nproposition compact_eq_totally_bounded:\n  \"compact s \\<longleftrightarrow> complete s \\<and> (\\<forall>e>0. \\<exists>k. finite k \\<and> s \\<subseteq> (\\<Union>x\\<in>k. ball x e))\"\n    (is \"_ \\<longleftrightarrow> ?rhs\")\nproof\n  assume assms: \"?rhs\"\n  then obtain k where k: \"\\<And>e. 0 < e \\<Longrightarrow> finite (k e)\" \"\\<And>e. 0 < e \\<Longrightarrow> s \\<subseteq> (\\<Union>x\\<in>k e. ball x e)\"\n    by (auto simp: choice_iff')\n\n  show \"compact s\"\n  proof cases\n    assume \"s = {}\"\n    then show \"compact s\" by (simp add: compact_def)\n  next\n    assume \"s \\<noteq> {}\"\n    show ?thesis\n      unfolding compact_def\n    proof safe\n      fix f :: \"nat \\<Rightarrow> 'a\"\n      assume f: \"\\<forall>n. f n \\<in> s\"\n\n      define e where \"e n = 1 / (2 * Suc n)\" for n\n      then have [simp]: \"\\<And>n. 0 < e n\" by auto\n      define B where \"B n U = (SOME b. infinite {n. f n \\<in> b} \\<and> (\\<exists>x. b \\<subseteq> ball x (e n) \\<inter> U))\" for n U\n      {\n        fix n U\n        assume \"infinite {n. f n \\<in> U}\"\n        then have \"\\<exists>b\\<in>k (e n). infinite {i\\<in>{n. f n \\<in> U}. f i \\<in> ball b (e n)}\"\n          using k f by (intro pigeonhole_infinite_rel) (auto simp: subset_eq)\n        then obtain a where\n          \"a \\<in> k (e n)\"\n          \"infinite {i \\<in> {n. f n \\<in> U}. f i \\<in> ball a (e n)}\" ..\n        then have \"\\<exists>b. infinite {i. f i \\<in> b} \\<and> (\\<exists>x. b \\<subseteq> ball x (e n) \\<inter> U)\"\n          by (intro exI[of _ \"ball a (e n) \\<inter> U\"] exI[of _ a]) (auto simp: ac_simps)\n        from someI_ex[OF this]\n        have \"infinite {i. f i \\<in> B n U}\" \"\\<exists>x. B n U \\<subseteq> ball x (e n) \\<inter> U\"\n          unfolding B_def by auto\n      }\n      note B = this\n\n      define F where \"F = rec_nat (B 0 UNIV) B\"\n      {\n        fix n\n        have \"infinite {i. f i \\<in> F n}\"\n          by (induct n) (auto simp: F_def B)\n      }\n      then have F: \"\\<And>n. \\<exists>x. F (Suc n) \\<subseteq> ball x (e n) \\<inter> F n\"\n        using B by (simp add: F_def)\n      then have F_dec: \"\\<And>m n. m \\<le> n \\<Longrightarrow> F n \\<subseteq> F m\"\n        using decseq_SucI[of F] by (auto simp: decseq_def)\n\n      obtain sel where sel: \"\\<And>k i. i < sel k i\" \"\\<And>k i. f (sel k i) \\<in> F k\"\n      proof (atomize_elim, unfold all_conj_distrib[symmetric], intro choice allI)\n        fix k i\n        have \"infinite ({n. f n \\<in> F k} - {.. i})\"\n          using \\<open>infinite {n. f n \\<in> F k}\\<close> by auto\n        from infinite_imp_nonempty[OF this]\n        show \"\\<exists>x>i. f x \\<in> F k\"\n          by (simp add: set_eq_iff not_le conj_commute)\n      qed\n\n      define t where \"t = rec_nat (sel 0 0) (\\<lambda>n i. sel (Suc n) i)\"\n      have \"strict_mono t\"\n        unfolding strict_mono_Suc_iff by (simp add: t_def sel)\n      moreover have \"\\<forall>i. (f \\<circ> t) i \\<in> s\"\n        using f by auto\n      moreover\n      have t: \"(f \\<circ> t) n \\<in> F n\" for n\n        by (cases n) (simp_all add: t_def sel)\n\n      have \"Cauchy (f \\<circ> t)\"\n      proof (safe intro!: metric_CauchyI exI elim!: nat_approx_posE)\n        fix r :: real and N n m\n        assume \"1 / Suc N < r\" \"Suc N \\<le> n\" \"Suc N \\<le> m\"\n        then have \"(f \\<circ> t) n \\<in> F (Suc N)\" \"(f \\<circ> t) m \\<in> F (Suc N)\" \"2 * e N < r\"\n          using F_dec t by (auto simp: e_def field_simps)\n        with F[of N] obtain x where \"dist x ((f \\<circ> t) n) < e N\" \"dist x ((f \\<circ> t) m) < e N\"\n          by (auto simp: subset_eq)\n        with \\<open>2 * e N < r\\<close> show \"dist ((f \\<circ> t) m) ((f \\<circ> t) n) < r\"\n          by metric\n      qed\n\n      ultimately show \"\\<exists>l\\<in>s. \\<exists>r. strict_mono r \\<and> (f \\<circ> r) \\<longlonglongrightarrow> l\"\n        using assms unfolding complete_def by blast\n    qed\n  qed\nqed (metis compact_imp_complete compact_imp_seq_compact seq_compact_imp_totally_bounded)\n\nlemma cauchy_imp_bounded:\n  assumes \"Cauchy s\"\n  shows \"bounded (range s)\"\nproof -\n  from assms obtain N :: nat where \"\\<forall>m n. N \\<le> m \\<and> N \\<le> n \\<longrightarrow> dist (s m) (s n) < 1\"\n    unfolding cauchy_def by force\n  then have N:\"\\<forall>n. N \\<le> n \\<longrightarrow> dist (s N) (s n) < 1\" by auto\n  moreover\n  have \"bounded (s ` {0..N})\"\n    using finite_imp_bounded[of \"s ` {1..N}\"] by auto\n  then obtain a where a:\"\\<forall>x\\<in>s ` {0..N}. dist (s N) x \\<le> a\"\n    unfolding bounded_any_center [where a=\"s N\"] by auto\n  ultimately show \"?thesis\"\n    unfolding bounded_any_center [where a=\"s N\"]\n    apply (rule_tac x=\"max a 1\" in exI, auto)\n    apply (erule_tac x=y in allE)\n    apply (erule_tac x=y in ballE, auto)\n    done\nqed\n\ninstance heine_borel < complete_space\nproof\n  fix f :: \"nat \\<Rightarrow> 'a\" assume \"Cauchy f\"\n  then have \"bounded (range f)\"\n    by (rule cauchy_imp_bounded)\n  then have \"compact (closure (range f))\"\n    unfolding compact_eq_bounded_closed by auto\n  then have \"complete (closure (range f))\"\n    by (rule compact_imp_complete)\n  moreover have \"\\<forall>n. f n \\<in> closure (range f)\"\n    using closure_subset [of \"range f\"] by auto\n  ultimately have \"\\<exists>l\\<in>closure (range f). (f \\<longlongrightarrow> l) sequentially\"\n    using \\<open>Cauchy f\\<close> unfolding complete_def by auto\n  then show \"convergent f\"\n    unfolding convergent_def by auto\nqed\n\nlemma complete_UNIV: \"complete (UNIV :: ('a::complete_space) set)\"\nproof (rule completeI)\n  fix f :: \"nat \\<Rightarrow> 'a\" assume \"Cauchy f\"\n  then have \"convergent f\" by (rule Cauchy_convergent)\n  then show \"\\<exists>l\\<in>UNIV. f \\<longlonglongrightarrow> l\" unfolding convergent_def by simp\nqed\n\nlemma complete_imp_closed:\n  fixes S :: \"'a::metric_space set\"\n  assumes \"complete S\"\n  shows \"closed S\"\nproof (unfold closed_sequential_limits, clarify)\n  fix f x assume \"\\<forall>n. f n \\<in> S\" and \"f \\<longlonglongrightarrow> x\"\n  from \\<open>f \\<longlonglongrightarrow> x\\<close> have \"Cauchy f\"\n    by (rule LIMSEQ_imp_Cauchy)\n  with \\<open>complete S\\<close> and \\<open>\\<forall>n. f n \\<in> S\\<close> obtain l where \"l \\<in> S\" and \"f \\<longlonglongrightarrow> l\"\n    by (rule completeE)\n  from \\<open>f \\<longlonglongrightarrow> x\\<close> and \\<open>f \\<longlonglongrightarrow> l\\<close> have \"x = l\"\n    by (rule LIMSEQ_unique)\n  with \\<open>l \\<in> S\\<close> show \"x \\<in> S\"\n    by simp\nqed\n\nlemma complete_Int_closed:\n  fixes S :: \"'a::metric_space set\"\n  assumes \"complete S\" and \"closed t\"\n  shows \"complete (S \\<inter> t)\"\nproof (rule completeI)\n  fix f assume \"\\<forall>n. f n \\<in> S \\<inter> t\" and \"Cauchy f\"\n  then have \"\\<forall>n. f n \\<in> S\" and \"\\<forall>n. f n \\<in> t\"\n    by simp_all\n  from \\<open>complete S\\<close> obtain l where \"l \\<in> S\" and \"f \\<longlonglongrightarrow> l\"\n    using \\<open>\\<forall>n. f n \\<in> S\\<close> and \\<open>Cauchy f\\<close> by (rule completeE)\n  from \\<open>closed t\\<close> and \\<open>\\<forall>n. f n \\<in> t\\<close> and \\<open>f \\<longlonglongrightarrow> l\\<close> have \"l \\<in> t\"\n    by (rule closed_sequentially)\n  with \\<open>l \\<in> S\\<close> and \\<open>f \\<longlonglongrightarrow> l\\<close> show \"\\<exists>l\\<in>S \\<inter> t. f \\<longlonglongrightarrow> l\"\n    by fast\nqed\n\nlemma complete_closed_subset:\n  fixes S :: \"'a::metric_space set\"\n  assumes \"closed S\" and \"S \\<subseteq> t\" and \"complete t\"\n  shows \"complete S\"\n  using assms complete_Int_closed [of t S] by (simp add: Int_absorb1)\n\nlemma complete_eq_closed:\n  fixes S :: \"('a::complete_space) set\"\n  shows \"complete S \\<longleftrightarrow> closed S\"\nproof\n  assume \"closed S\" then show \"complete S\"\n    using subset_UNIV complete_UNIV by (rule complete_closed_subset)\nnext\n  assume \"complete S\" then show \"closed S\"\n    by (rule complete_imp_closed)\nqed\n\nlemma convergent_eq_Cauchy:\n  fixes S :: \"nat \\<Rightarrow> 'a::complete_space\"\n  shows \"(\\<exists>l. (S \\<longlongrightarrow> l) sequentially) \\<longleftrightarrow> Cauchy S\"\n  unfolding Cauchy_convergent_iff convergent_def ..\n\nlemma convergent_imp_bounded:\n  fixes S :: \"nat \\<Rightarrow> 'a::metric_space\"\n  shows \"(S \\<longlongrightarrow> l) sequentially \\<Longrightarrow> bounded (range S)\"\n  by (intro cauchy_imp_bounded LIMSEQ_imp_Cauchy)\n\nlemma frontier_subset_compact:\n  fixes S :: \"'a::heine_borel set\"\n  shows \"compact S \\<Longrightarrow> frontier S \\<subseteq> S\"\n  using frontier_subset_closed compact_eq_bounded_closed\n  by blast\n\nlemma continuous_closed_imp_Cauchy_continuous:\n  fixes S :: \"('a::complete_space) set\"\n  shows \"\\<lbrakk>continuous_on S f; closed S; Cauchy \\<sigma>; \\<And>n. (\\<sigma> n) \\<in> S\\<rbrakk> \\<Longrightarrow> Cauchy(f \\<circ> \\<sigma>)\"\n  apply (simp add: complete_eq_closed [symmetric] continuous_on_sequentially)\n  by (meson LIMSEQ_imp_Cauchy complete_def)\n\nlemma banach_fix_type:\n  fixes f::\"'a::complete_space\\<Rightarrow>'a\"\n  assumes c:\"0 \\<le> c\" \"c < 1\"\n      and lipschitz:\"\\<forall>x. \\<forall>y. dist (f x) (f y) \\<le> c * dist x y\"\n  shows \"\\<exists>!x. (f x = x)\"\n  using assms banach_fix[OF complete_UNIV UNIV_not_empty assms(1,2) subset_UNIV, of f]\n  by auto\n\n\nsubsection\\<^marker>\\<open>tag unimportant\\<close>\\<open> Finite intersection property\\<close>\n\ntext\\<open>Also developed in HOL's toplogical spaces theory, but the Heine-Borel type class isn't available there.\\<close>\n\nlemma closed_imp_fip:\n  fixes S :: \"'a::heine_borel set\"\n  assumes \"closed S\"\n      and T: \"T \\<in> \\<F>\" \"bounded T\"\n      and clof: \"\\<And>T. T \\<in> \\<F> \\<Longrightarrow> closed T\"\n      and none: \"\\<And>\\<F>'. \\<lbrakk>finite \\<F>'; \\<F>' \\<subseteq> \\<F>\\<rbrakk> \\<Longrightarrow> S \\<inter> \\<Inter>\\<F>' \\<noteq> {}\"\n    shows \"S \\<inter> \\<Inter>\\<F> \\<noteq> {}\"\nproof -\n  have \"compact (S \\<inter> T)\"\n    using \\<open>closed S\\<close> clof compact_eq_bounded_closed T by blast\n  then have \"(S \\<inter> T) \\<inter> \\<Inter>\\<F> \\<noteq> {}\"\n    apply (rule compact_imp_fip)\n     apply (simp add: clof)\n    by (metis Int_assoc complete_lattice_class.Inf_insert finite_insert insert_subset none \\<open>T \\<in> \\<F>\\<close>)\n  then show ?thesis by blast\nqed\n\nlemma closed_imp_fip_compact:\n  fixes S :: \"'a::heine_borel set\"\n  shows\n   \"\\<lbrakk>closed S; \\<And>T. T \\<in> \\<F> \\<Longrightarrow> compact T;\n     \\<And>\\<F>'. \\<lbrakk>finite \\<F>'; \\<F>' \\<subseteq> \\<F>\\<rbrakk> \\<Longrightarrow> S \\<inter> \\<Inter>\\<F>' \\<noteq> {}\\<rbrakk>\n        \\<Longrightarrow> S \\<inter> \\<Inter>\\<F> \\<noteq> {}\"\nby (metis Inf_greatest closed_imp_fip compact_eq_bounded_closed empty_subsetI finite.emptyI inf.orderE)\n\nlemma closed_fip_Heine_Borel:\n  fixes \\<F> :: \"'a::heine_borel set set\"\n  assumes \"closed S\" \"T \\<in> \\<F>\" \"bounded T\"\n      and \"\\<And>T. T \\<in> \\<F> \\<Longrightarrow> closed T\"\n      and \"\\<And>\\<F>'. \\<lbrakk>finite \\<F>'; \\<F>' \\<subseteq> \\<F>\\<rbrakk> \\<Longrightarrow> \\<Inter>\\<F>' \\<noteq> {}\"\n    shows \"\\<Inter>\\<F> \\<noteq> {}\"\nproof -\n  have \"UNIV \\<inter> \\<Inter>\\<F> \\<noteq> {}\"\n    using assms closed_imp_fip [OF closed_UNIV] by auto\n  then show ?thesis by simp\nqed\n\nlemma compact_fip_Heine_Borel:\n  fixes \\<F> :: \"'a::heine_borel set set\"\n  assumes clof: \"\\<And>T. T \\<in> \\<F> \\<Longrightarrow> compact T\"\n      and none: \"\\<And>\\<F>'. \\<lbrakk>finite \\<F>'; \\<F>' \\<subseteq> \\<F>\\<rbrakk> \\<Longrightarrow> \\<Inter>\\<F>' \\<noteq> {}\"\n    shows \"\\<Inter>\\<F> \\<noteq> {}\"\nby (metis InterI all_not_in_conv clof closed_fip_Heine_Borel compact_eq_bounded_closed none)\n\nlemma compact_sequence_with_limit:\n  fixes f :: \"nat \\<Rightarrow> 'a::heine_borel\"\n  shows \"(f \\<longlongrightarrow> l) sequentially \\<Longrightarrow> compact (insert l (range f))\"\napply (simp add: compact_eq_bounded_closed, auto)\napply (simp add: convergent_imp_bounded)\nby (simp add: closed_limpt islimpt_insert sequence_unique_limpt)\n\n\nsubsection \\<open>Properties of Balls and Spheres\\<close>\n\nlemma compact_cball[simp]:\n  fixes x :: \"'a::heine_borel\"\n  shows \"compact (cball x e)\"\n  using compact_eq_bounded_closed bounded_cball closed_cball\n  by blast\n\nlemma compact_frontier_bounded[intro]:\n  fixes S :: \"'a::heine_borel set\"\n  shows \"bounded S \\<Longrightarrow> compact (frontier S)\"\n  unfolding frontier_def\n  using compact_eq_bounded_closed\n  by blast\n\nlemma compact_frontier[intro]:\n  fixes S :: \"'a::heine_borel set\"\n  shows \"compact S \\<Longrightarrow> compact (frontier S)\"\n  using compact_eq_bounded_closed compact_frontier_bounded\n  by blast\n\n\nsubsection \\<open>Distance from a Set\\<close>\n\nlemma distance_attains_sup:\n  assumes \"compact s\" \"s \\<noteq> {}\"\n  shows \"\\<exists>x\\<in>s. \\<forall>y\\<in>s. dist a y \\<le> dist a x\"\nproof (rule continuous_attains_sup [OF assms])\n  {\n    fix x\n    assume \"x\\<in>s\"\n    have \"(dist a \\<longlongrightarrow> dist a x) (at x within s)\"\n      by (intro tendsto_dist tendsto_const tendsto_ident_at)\n  }\n  then show \"continuous_on s (dist a)\"\n    unfolding continuous_on ..\nqed\n\ntext \\<open>For \\emph{minimal} distance, we only need closure, not compactness.\\<close>\n\nlemma distance_attains_inf:\n  fixes a :: \"'a::heine_borel\"\n  assumes \"closed s\" and \"s \\<noteq> {}\"\n  obtains x where \"x\\<in>s\" \"\\<And>y. y \\<in> s \\<Longrightarrow> dist a x \\<le> dist a y\"\nproof -\n  from assms obtain b where \"b \\<in> s\" by auto\n  let ?B = \"s \\<inter> cball a (dist b a)\"\n  have \"?B \\<noteq> {}\" using \\<open>b \\<in> s\\<close>\n    by (auto simp: dist_commute)\n  moreover have \"continuous_on ?B (dist a)\"\n    by (auto intro!: continuous_at_imp_continuous_on continuous_dist continuous_ident continuous_const)\n  moreover have \"compact ?B\"\n    by (intro closed_Int_compact \\<open>closed s\\<close> compact_cball)\n  ultimately obtain x where \"x \\<in> ?B\" \"\\<forall>y\\<in>?B. dist a x \\<le> dist a y\"\n    by (metis continuous_attains_inf)\n  with that show ?thesis by fastforce\nqed\n\n\nsubsection \\<open>Infimum Distance\\<close>\n\ndefinition\\<^marker>\\<open>tag important\\<close> \"infdist x A = (if A = {} then 0 else INF a\\<in>A. dist x a)\"\n\nlemma bdd_below_image_dist[intro, simp]: \"bdd_below (dist x ` A)\"\n  by (auto intro!: zero_le_dist)\n\nlemma infdist_notempty: \"A \\<noteq> {} \\<Longrightarrow> infdist x A = (INF a\\<in>A. dist x a)\"\n  by (simp add: infdist_def)\n\nlemma infdist_nonneg: \"0 \\<le> infdist x A\"\n  by (auto simp: infdist_def intro: cINF_greatest)\n\nlemma infdist_le: \"a \\<in> A \\<Longrightarrow> infdist x A \\<le> dist x a\"\n  by (auto intro: cINF_lower simp add: infdist_def)\n\nlemma infdist_le2: \"a \\<in> A \\<Longrightarrow> dist x a \\<le> d \\<Longrightarrow> infdist x A \\<le> d\"\n  by (auto intro!: cINF_lower2 simp add: infdist_def)\n\nlemma infdist_zero[simp]: \"a \\<in> A \\<Longrightarrow> infdist a A = 0\"\n  by (auto intro!: antisym infdist_nonneg infdist_le2)\n\nlemma infdist_Un_min:\n  assumes \"A \\<noteq> {}\" \"B \\<noteq> {}\"\n  shows \"infdist x (A \\<union> B) = min (infdist x A) (infdist x B)\"\nusing assms by (simp add: infdist_def cINF_union inf_real_def)\n\nlemma infdist_triangle: \"infdist x A \\<le> infdist y A + dist x y\"\nproof (cases \"A = {}\")\n  case True\n  then show ?thesis by (simp add: infdist_def)\nnext\n  case False\n  then obtain a where \"a \\<in> A\" by auto\n  have \"infdist x A \\<le> Inf {dist x y + dist y a |a. a \\<in> A}\"\n  proof (rule cInf_greatest)\n    from \\<open>A \\<noteq> {}\\<close> show \"{dist x y + dist y a |a. a \\<in> A} \\<noteq> {}\"\n      by simp\n    fix d\n    assume \"d \\<in> {dist x y + dist y a |a. a \\<in> A}\"\n    then obtain a where d: \"d = dist x y + dist y a\" \"a \\<in> A\"\n      by auto\n    show \"infdist x A \\<le> d\"\n      unfolding infdist_notempty[OF \\<open>A \\<noteq> {}\\<close>]\n    proof (rule cINF_lower2)\n      show \"a \\<in> A\" by fact\n      show \"dist x a \\<le> d\"\n        unfolding d by (rule dist_triangle)\n    qed simp\n  qed\n  also have \"\\<dots> = dist x y + infdist y A\"\n  proof (rule cInf_eq, safe)\n    fix a\n    assume \"a \\<in> A\"\n    then show \"dist x y + infdist y A \\<le> dist x y + dist y a\"\n      by (auto intro: infdist_le)\n  next\n    fix i\n    assume inf: \"\\<And>d. d \\<in> {dist x y + dist y a |a. a \\<in> A} \\<Longrightarrow> i \\<le> d\"\n    then have \"i - dist x y \\<le> infdist y A\"\n      unfolding infdist_notempty[OF \\<open>A \\<noteq> {}\\<close>] using \\<open>a \\<in> A\\<close>\n      by (intro cINF_greatest) (auto simp: field_simps)\n    then show \"i \\<le> dist x y + infdist y A\"\n      by simp\n  qed\n  finally show ?thesis by simp\nqed\n\nlemma infdist_triangle_abs: \"\\<bar>infdist x A - infdist y A\\<bar> \\<le> dist x y\"\n  by (metis (full_types) abs_diff_le_iff diff_le_eq dist_commute infdist_triangle)\n\nlemma in_closure_iff_infdist_zero:\n  assumes \"A \\<noteq> {}\"\n  shows \"x \\<in> closure A \\<longleftrightarrow> infdist x A = 0\"\nproof\n  assume \"x \\<in> closure A\"\n  show \"infdist x A = 0\"\n  proof (rule ccontr)\n    assume \"infdist x A \\<noteq> 0\"\n    with infdist_nonneg[of x A] have \"infdist x A > 0\"\n      by auto\n    then have \"ball x (infdist x A) \\<inter> closure A = {}\"\n      apply auto\n      apply (metis \\<open>x \\<in> closure A\\<close> closure_approachable dist_commute infdist_le not_less)\n      done\n    then have \"x \\<notin> closure A\"\n      by (metis \\<open>0 < infdist x A\\<close> centre_in_ball disjoint_iff_not_equal)\n    then show False using \\<open>x \\<in> closure A\\<close> by simp\n  qed\nnext\n  assume x: \"infdist x A = 0\"\n  then obtain a where \"a \\<in> A\"\n    by atomize_elim (metis all_not_in_conv assms)\n  show \"x \\<in> closure A\"\n    unfolding closure_approachable\n    apply safe\n  proof (rule ccontr)\n    fix e :: real\n    assume \"e > 0\"\n    assume \"\\<not> (\\<exists>y\\<in>A. dist y x < e)\"\n    then have \"infdist x A \\<ge> e\" using \\<open>a \\<in> A\\<close>\n      unfolding infdist_def\n      by (force simp: dist_commute intro: cINF_greatest)\n    with x \\<open>e > 0\\<close> show False by auto\n  qed\nqed\n\nlemma in_closed_iff_infdist_zero:\n  assumes \"closed A\" \"A \\<noteq> {}\"\n  shows \"x \\<in> A \\<longleftrightarrow> infdist x A = 0\"\nproof -\n  have \"x \\<in> closure A \\<longleftrightarrow> infdist x A = 0\"\n    by (rule in_closure_iff_infdist_zero) fact\n  with assms show ?thesis by simp\nqed\n\nlemma infdist_pos_not_in_closed:\n  assumes \"closed S\" \"S \\<noteq> {}\" \"x \\<notin> S\"\n  shows \"infdist x S > 0\"\nusing in_closed_iff_infdist_zero[OF assms(1) assms(2), of x] assms(3) infdist_nonneg le_less by fastforce\n\nlemma\n  infdist_attains_inf:\n  fixes X::\"'a::heine_borel set\"\n  assumes \"closed X\"\n  assumes \"X \\<noteq> {}\"\n  obtains x where \"x \\<in> X\" \"infdist y X = dist y x\"\nproof -\n  have \"bdd_below (dist y ` X)\"\n    by auto\n  from distance_attains_inf[OF assms, of y]\n  obtain x where INF: \"x \\<in> X\" \"\\<And>z. z \\<in> X \\<Longrightarrow> dist y x \\<le> dist y z\" by auto\n  have \"infdist y X = dist y x\"\n    by (auto simp: infdist_def assms\n      intro!: antisym cINF_lower[OF _ \\<open>x \\<in> X\\<close>] cINF_greatest[OF assms(2) INF(2)])\n  with \\<open>x \\<in> X\\<close> show ?thesis ..\nqed\n\n\ntext \\<open>Every metric space is a T4 space:\\<close>\n\ninstance metric_space \\<subseteq> t4_space\nproof\n  fix S T::\"'a set\" assume H: \"closed S\" \"closed T\" \"S \\<inter> T = {}\"\n  consider \"S = {}\" | \"T = {}\" | \"S \\<noteq> {} \\<and> T \\<noteq> {}\" by auto\n  then show \"\\<exists>U V. open U \\<and> open V \\<and> S \\<subseteq> U \\<and> T \\<subseteq> V \\<and> U \\<inter> V = {}\"\n  proof (cases)\n    case 1\n    show ?thesis\n      apply (rule exI[of _ \"{}\"], rule exI[of _ UNIV]) using 1 by auto\n  next\n    case 2\n    show ?thesis\n      apply (rule exI[of _ UNIV], rule exI[of _ \"{}\"]) using 2 by auto\n  next\n    case 3\n    define U where \"U = (\\<Union>x\\<in>S. ball x ((infdist x T)/2))\"\n    have A: \"open U\" unfolding U_def by auto\n    have \"infdist x T > 0\" if \"x \\<in> S\" for x\n      using H that 3 by (auto intro!: infdist_pos_not_in_closed)\n    then have B: \"S \\<subseteq> U\" unfolding U_def by auto\n    define V where \"V = (\\<Union>x\\<in>T. ball x ((infdist x S)/2))\"\n    have C: \"open V\" unfolding V_def by auto\n    have \"infdist x S > 0\" if \"x \\<in> T\" for x\n      using H that 3 by (auto intro!: infdist_pos_not_in_closed)\n    then have D: \"T \\<subseteq> V\" unfolding V_def by auto\n\n    have \"(ball x ((infdist x T)/2)) \\<inter> (ball y ((infdist y S)/2)) = {}\" if \"x \\<in> S\" \"y \\<in> T\" for x y\n    proof auto\n      fix z assume H: \"dist x z * 2 < infdist x T\" \"dist y z * 2 < infdist y S\"\n      have \"2 * dist x y \\<le> 2 * dist x z + 2 * dist y z\"\n        by metric\n      also have \"... < infdist x T + infdist y S\"\n        using H by auto\n      finally have \"dist x y < infdist x T \\<or> dist x y < infdist y S\"\n        by auto\n      then show False\n        using infdist_le[OF \\<open>x \\<in> S\\<close>, of y] infdist_le[OF \\<open>y \\<in> T\\<close>, of x] by (auto simp add: dist_commute)\n    qed\n    then have E: \"U \\<inter> V = {}\"\n      unfolding U_def V_def by auto\n    show ?thesis\n      apply (rule exI[of _ U], rule exI[of _ V]) using A B C D E by auto\n  qed\nqed\n\nlemma tendsto_infdist [tendsto_intros]:\n  assumes f: \"(f \\<longlongrightarrow> l) F\"\n  shows \"((\\<lambda>x. infdist (f x) A) \\<longlongrightarrow> infdist l A) F\"\nproof (rule tendstoI)\n  fix e ::real\n  assume \"e > 0\"\n  from tendstoD[OF f this]\n  show \"eventually (\\<lambda>x. dist (infdist (f x) A) (infdist l A) < e) F\"\n  proof (eventually_elim)\n    fix x\n    from infdist_triangle[of l A \"f x\"] infdist_triangle[of \"f x\" A l]\n    have \"dist (infdist (f x) A) (infdist l A) \\<le> dist (f x) l\"\n      by (simp add: dist_commute dist_real_def)\n    also assume \"dist (f x) l < e\"\n    finally show \"dist (infdist (f x) A) (infdist l A) < e\" .\n  qed\nqed\n\nlemma continuous_infdist[continuous_intros]:\n  assumes \"continuous F f\"\n  shows \"continuous F (\\<lambda>x. infdist (f x) A)\"\n  using assms unfolding continuous_def by (rule tendsto_infdist)\n\nlemma continuous_on_infdist [continuous_intros]:\n  assumes \"continuous_on S f\"\n  shows \"continuous_on S (\\<lambda>x. infdist (f x) A)\"\nusing assms unfolding continuous_on by (auto intro: tendsto_infdist)\n\nlemma compact_infdist_le:\n  fixes A::\"'a::heine_borel set\"\n  assumes \"A \\<noteq> {}\"\n  assumes \"compact A\"\n  assumes \"e > 0\"\n  shows \"compact {x. infdist x A \\<le> e}\"\nproof -\n  from continuous_closed_vimage[of \"{0..e}\" \"\\<lambda>x. infdist x A\"]\n    continuous_infdist[OF continuous_ident, of _ UNIV A]\n  have \"closed {x. infdist x A \\<le> e}\" by (auto simp: vimage_def infdist_nonneg)\n  moreover\n  from assms obtain x0 b where b: \"\\<And>x. x \\<in> A \\<Longrightarrow> dist x0 x \\<le> b\" \"closed A\"\n    by (auto simp: compact_eq_bounded_closed bounded_def)\n  {\n    fix y\n    assume \"infdist y A \\<le> e\"\n    moreover\n    from infdist_attains_inf[OF \\<open>closed A\\<close> \\<open>A \\<noteq> {}\\<close>, of y]\n    obtain z where \"z \\<in> A\" \"infdist y A = dist y z\" by blast\n    ultimately\n    have \"dist x0 y \\<le> b + e\" using b by metric\n  } then\n  have \"bounded {x. infdist x A \\<le> e}\"\n    by (auto simp: bounded_any_center[where a=x0] intro!: exI[where x=\"b + e\"])\n  ultimately show \"compact {x. infdist x A \\<le> e}\"\n    by (simp add: compact_eq_bounded_closed)\nqed\n\n\nsubsection \\<open>Separation between Points and Sets\\<close>\n\nproposition separate_point_closed:\n  fixes s :: \"'a::heine_borel set\"\n  assumes \"closed s\" and \"a \\<notin> s\"\n  shows \"\\<exists>d>0. \\<forall>x\\<in>s. d \\<le> dist a x\"\nproof (cases \"s = {}\")\n  case True\n  then show ?thesis by(auto intro!: exI[where x=1])\nnext\n  case False\n  from assms obtain x where \"x\\<in>s\" \"\\<forall>y\\<in>s. dist a x \\<le> dist a y\"\n    using \\<open>s \\<noteq> {}\\<close> by (blast intro: distance_attains_inf [of s a])\n  with \\<open>x\\<in>s\\<close> show ?thesis using dist_pos_lt[of a x] and\\<open>a \\<notin> s\\<close>\n    by blast\nqed\n\nproposition separate_compact_closed:\n  fixes s t :: \"'a::heine_borel set\"\n  assumes \"compact s\"\n    and t: \"closed t\" \"s \\<inter> t = {}\"\n  shows \"\\<exists>d>0. \\<forall>x\\<in>s. \\<forall>y\\<in>t. d \\<le> dist x y\"\nproof cases\n  assume \"s \\<noteq> {} \\<and> t \\<noteq> {}\"\n  then have \"s \\<noteq> {}\" \"t \\<noteq> {}\" by auto\n  let ?inf = \"\\<lambda>x. infdist x t\"\n  have \"continuous_on s ?inf\"\n    by (auto intro!: continuous_at_imp_continuous_on continuous_infdist continuous_ident)\n  then obtain x where x: \"x \\<in> s\" \"\\<forall>y\\<in>s. ?inf x \\<le> ?inf y\"\n    using continuous_attains_inf[OF \\<open>compact s\\<close> \\<open>s \\<noteq> {}\\<close>] by auto\n  then have \"0 < ?inf x\"\n    using t \\<open>t \\<noteq> {}\\<close> in_closed_iff_infdist_zero by (auto simp: less_le infdist_nonneg)\n  moreover have \"\\<forall>x'\\<in>s. \\<forall>y\\<in>t. ?inf x \\<le> dist x' y\"\n    using x by (auto intro: order_trans infdist_le)\n  ultimately show ?thesis by auto\nqed (auto intro!: exI[of _ 1])\n\nproposition separate_closed_compact:\n  fixes s t :: \"'a::heine_borel set\"\n  assumes \"closed s\"\n    and \"compact t\"\n    and \"s \\<inter> t = {}\"\n  shows \"\\<exists>d>0. \\<forall>x\\<in>s. \\<forall>y\\<in>t. d \\<le> dist x y\"\nproof -\n  have *: \"t \\<inter> s = {}\"\n    using assms(3) by auto\n  show ?thesis\n    using separate_compact_closed[OF assms(2,1) *] by (force simp: dist_commute)\nqed\n\nproposition compact_in_open_separated:\n  fixes A::\"'a::heine_borel set\"\n  assumes \"A \\<noteq> {}\"\n  assumes \"compact A\"\n  assumes \"open B\"\n  assumes \"A \\<subseteq> B\"\n  obtains e where \"e > 0\" \"{x. infdist x A \\<le> e} \\<subseteq> B\"\nproof atomize_elim\n  have \"closed (- B)\" \"compact A\" \"- B \\<inter> A = {}\"\n    using assms by (auto simp: open_Diff compact_eq_bounded_closed)\n  from separate_closed_compact[OF this]\n  obtain d'::real where d': \"d'>0\" \"\\<And>x y. x \\<notin> B \\<Longrightarrow> y \\<in> A \\<Longrightarrow> d' \\<le> dist x y\"\n    by auto\n  define d where \"d = d' / 2\"\n  hence \"d>0\" \"d < d'\" using d' by auto\n  with d' have d: \"\\<And>x y. x \\<notin> B \\<Longrightarrow> y \\<in> A \\<Longrightarrow> d < dist x y\"\n    by force\n  show \"\\<exists>e>0. {x. infdist x A \\<le> e} \\<subseteq> B\"\n  proof (rule ccontr)\n    assume \"\\<nexists>e. 0 < e \\<and> {x. infdist x A \\<le> e} \\<subseteq> B\"\n    with \\<open>d > 0\\<close> obtain x where x: \"infdist x A \\<le> d\" \"x \\<notin> B\"\n      by auto\n    from assms have \"closed A\" \"A \\<noteq> {}\" by (auto simp: compact_eq_bounded_closed)\n    from infdist_attains_inf[OF this]\n    obtain y where y: \"y \\<in> A\" \"infdist x A = dist x y\"\n      by auto\n    have \"dist x y \\<le> d\" using x y by simp\n    also have \"\\<dots> < dist x y\" using y d x by auto\n    finally show False by simp\n  qed\nqed\n\n\nsubsection \\<open>Uniform Continuity\\<close>\n\nlemma uniformly_continuous_onE:\n  assumes \"uniformly_continuous_on s f\" \"0 < e\"\n  obtains d where \"d>0\" \"\\<And>x x'. \\<lbrakk>x\\<in>s; x'\\<in>s; dist x' x < d\\<rbrakk> \\<Longrightarrow> dist (f x') (f x) < e\"\nusing assms\nby (auto simp: uniformly_continuous_on_def)\n\nlemma uniformly_continuous_on_sequentially:\n  \"uniformly_continuous_on s f \\<longleftrightarrow> (\\<forall>x y. (\\<forall>n. x n \\<in> s) \\<and> (\\<forall>n. y n \\<in> s) \\<and>\n    (\\<lambda>n. dist (x n) (y n)) \\<longlonglongrightarrow> 0 \\<longrightarrow> (\\<lambda>n. dist (f(x n)) (f(y n))) \\<longlonglongrightarrow> 0)\" (is \"?lhs = ?rhs\")\nproof\n  assume ?lhs\n  {\n    fix x y\n    assume x: \"\\<forall>n. x n \\<in> s\"\n      and y: \"\\<forall>n. y n \\<in> s\"\n      and xy: \"((\\<lambda>n. dist (x n) (y n)) \\<longlongrightarrow> 0) sequentially\"\n    {\n      fix e :: real\n      assume \"e > 0\"\n      then obtain d where \"d > 0\" and d: \"\\<forall>x\\<in>s. \\<forall>x'\\<in>s. dist x' x < d \\<longrightarrow> dist (f x') (f x) < e\"\n        using \\<open>?lhs\\<close>[unfolded uniformly_continuous_on_def, THEN spec[where x=e]] by auto\n      obtain N where N: \"\\<forall>n\\<ge>N. dist (x n) (y n) < d\"\n        using xy[unfolded lim_sequentially dist_norm] and \\<open>d>0\\<close> by auto\n      {\n        fix n\n        assume \"n\\<ge>N\"\n        then have \"dist (f (x n)) (f (y n)) < e\"\n          using N[THEN spec[where x=n]]\n          using d[THEN bspec[where x=\"x n\"], THEN bspec[where x=\"y n\"]]\n          using x and y\n          by (simp add: dist_commute)\n      }\n      then have \"\\<exists>N. \\<forall>n\\<ge>N. dist (f (x n)) (f (y n)) < e\"\n        by auto\n    }\n    then have \"((\\<lambda>n. dist (f(x n)) (f(y n))) \\<longlongrightarrow> 0) sequentially\"\n      unfolding lim_sequentially and dist_real_def by auto\n  }\n  then show ?rhs by auto\nnext\n  assume ?rhs\n  {\n    assume \"\\<not> ?lhs\"\n    then obtain e where \"e > 0\" \"\\<forall>d>0. \\<exists>x\\<in>s. \\<exists>x'\\<in>s. dist x' x < d \\<and> \\<not> dist (f x') (f x) < e\"\n      unfolding uniformly_continuous_on_def by auto\n    then obtain fa where fa:\n      \"\\<forall>x. 0 < x \\<longrightarrow> fst (fa x) \\<in> s \\<and> snd (fa x) \\<in> s \\<and> dist (fst (fa x)) (snd (fa x)) < x \\<and> \\<not> dist (f (fst (fa x))) (f (snd (fa x))) < e\"\n      using choice[of \"\\<lambda>d x. d>0 \\<longrightarrow> fst x \\<in> s \\<and> snd x \\<in> s \\<and> dist (snd x) (fst x) < d \\<and> \\<not> dist (f (snd x)) (f (fst x)) < e\"]\n      unfolding Bex_def\n      by (auto simp: dist_commute)\n    define x where \"x n = fst (fa (inverse (real n + 1)))\" for n\n    define y where \"y n = snd (fa (inverse (real n + 1)))\" for n\n    have xyn: \"\\<forall>n. x n \\<in> s \\<and> y n \\<in> s\"\n      and xy0: \"\\<forall>n. dist (x n) (y n) < inverse (real n + 1)\"\n      and fxy:\"\\<forall>n. \\<not> dist (f (x n)) (f (y n)) < e\"\n      unfolding x_def and y_def using fa\n      by auto\n    {\n      fix e :: real\n      assume \"e > 0\"\n      then obtain N :: nat where \"N \\<noteq> 0\" and N: \"0 < inverse (real N) \\<and> inverse (real N) < e\"\n        unfolding real_arch_inverse[of e] by auto\n      {\n        fix n :: nat\n        assume \"n \\<ge> N\"\n        then have \"inverse (real n + 1) < inverse (real N)\"\n          using of_nat_0_le_iff and \\<open>N\\<noteq>0\\<close> by auto\n        also have \"\\<dots> < e\" using N by auto\n        finally have \"inverse (real n + 1) < e\" by auto\n        then have \"dist (x n) (y n) < e\"\n          using xy0[THEN spec[where x=n]] by auto\n      }\n      then have \"\\<exists>N. \\<forall>n\\<ge>N. dist (x n) (y n) < e\" by auto\n    }\n    then have \"\\<forall>e>0. \\<exists>N. \\<forall>n\\<ge>N. dist (f (x n)) (f (y n)) < e\"\n      using \\<open>?rhs\\<close>[THEN spec[where x=x], THEN spec[where x=y]] and xyn\n      unfolding lim_sequentially dist_real_def by auto\n    then have False using fxy and \\<open>e>0\\<close> by auto\n  }\n  then show ?lhs\n    unfolding uniformly_continuous_on_def by blast\nqed\n\n\nsubsection \\<open>Continuity on a Compact Domain Implies Uniform Continuity\\<close>\n\ntext\\<open>From the proof of the Heine-Borel theorem: Lemma 2 in section 3.7, page 69 of\nJ. C. Burkill and H. Burkill. A Second Course in Mathematical Analysis (CUP, 2002)\\<close>\n\nlemma Heine_Borel_lemma:\n  assumes \"compact S\" and Ssub: \"S \\<subseteq> \\<Union>\\<G>\" and opn: \"\\<And>G. G \\<in> \\<G> \\<Longrightarrow> open G\"\n  obtains e where \"0 < e\" \"\\<And>x. x \\<in> S \\<Longrightarrow> \\<exists>G \\<in> \\<G>. ball x e \\<subseteq> G\"\nproof -\n  have False if neg: \"\\<And>e. 0 < e \\<Longrightarrow> \\<exists>x \\<in> S. \\<forall>G \\<in> \\<G>. \\<not> ball x e \\<subseteq> G\"\n  proof -\n    have \"\\<exists>x \\<in> S. \\<forall>G \\<in> \\<G>. \\<not> ball x (1 / Suc n) \\<subseteq> G\" for n\n      using neg by simp\n    then obtain f where \"\\<And>n. f n \\<in> S\" and fG: \"\\<And>G n. G \\<in> \\<G> \\<Longrightarrow> \\<not> ball (f n) (1 / Suc n) \\<subseteq> G\"\n      by metis\n    then obtain l r where \"l \\<in> S\" \"strict_mono r\" and to_l: \"(f \\<circ> r) \\<longlonglongrightarrow> l\"\n      using \\<open>compact S\\<close> compact_def that by metis\n    then obtain G where \"l \\<in> G\" \"G \\<in> \\<G>\"\n      using Ssub by auto\n    then obtain e where \"0 < e\" and e: \"\\<And>z. dist z l < e \\<Longrightarrow> z \\<in> G\"\n      using opn open_dist by blast\n    obtain N1 where N1: \"\\<And>n. n \\<ge> N1 \\<Longrightarrow> dist (f (r n)) l < e/2\"\n      using to_l apply (simp add: lim_sequentially)\n      using \\<open>0 < e\\<close> half_gt_zero that by blast\n    obtain N2 where N2: \"of_nat N2 > 2/e\"\n      using reals_Archimedean2 by blast\n    obtain x where \"x \\<in> ball (f (r (max N1 N2))) (1 / real (Suc (r (max N1 N2))))\" and \"x \\<notin> G\"\n      using fG [OF \\<open>G \\<in> \\<G>\\<close>, of \"r (max N1 N2)\"] by blast\n    then have \"dist (f (r (max N1 N2))) x < 1 / real (Suc (r (max N1 N2)))\"\n      by simp\n    also have \"... \\<le> 1 / real (Suc (max N1 N2))\"\n      apply (simp add: field_split_simps del: max.bounded_iff)\n      using \\<open>strict_mono r\\<close> seq_suble by blast\n    also have \"... \\<le> 1 / real (Suc N2)\"\n      by (simp add: field_simps)\n    also have \"... < e/2\"\n      using N2 \\<open>0 < e\\<close> by (simp add: field_simps)\n    finally have \"dist (f (r (max N1 N2))) x < e/2\" .\n    moreover have \"dist (f (r (max N1 N2))) l < e/2\"\n      using N1 max.cobounded1 by blast\n    ultimately have \"dist x l < e\"\n      by metric\n    then show ?thesis\n      using e \\<open>x \\<notin> G\\<close> by blast\n  qed\n  then show ?thesis\n    by (meson that)\nqed\n\nlemma compact_uniformly_equicontinuous:\n  assumes \"compact S\"\n      and cont: \"\\<And>x e. \\<lbrakk>x \\<in> S; 0 < e\\<rbrakk>\n                        \\<Longrightarrow> \\<exists>d. 0 < d \\<and>\n                                (\\<forall>f \\<in> \\<F>. \\<forall>x' \\<in> S. dist x' x < d \\<longrightarrow> dist (f x') (f x) < e)\"\n      and \"0 < e\"\n  obtains d where \"0 < d\"\n                  \"\\<And>f x x'. \\<lbrakk>f \\<in> \\<F>; x \\<in> S; x' \\<in> S; dist x' x < d\\<rbrakk> \\<Longrightarrow> dist (f x') (f x) < e\"\nproof -\n  obtain d where d_pos: \"\\<And>x e. \\<lbrakk>x \\<in> S; 0 < e\\<rbrakk> \\<Longrightarrow> 0 < d x e\"\n     and d_dist : \"\\<And>x x' e f. \\<lbrakk>dist x' x < d x e; x \\<in> S; x' \\<in> S; 0 < e; f \\<in> \\<F>\\<rbrakk> \\<Longrightarrow> dist (f x') (f x) < e\"\n    using cont by metis\n  let ?\\<G> = \"((\\<lambda>x. ball x (d x (e/2))) ` S)\"\n  have Ssub: \"S \\<subseteq> \\<Union> ?\\<G>\"\n    by clarsimp (metis d_pos \\<open>0 < e\\<close> dist_self half_gt_zero_iff)\n  then obtain k where \"0 < k\" and k: \"\\<And>x. x \\<in> S \\<Longrightarrow> \\<exists>G \\<in> ?\\<G>. ball x k \\<subseteq> G\"\n    by (rule Heine_Borel_lemma [OF \\<open>compact S\\<close>]) auto\n  moreover have \"dist (f v) (f u) < e\" if \"f \\<in> \\<F>\" \"u \\<in> S\" \"v \\<in> S\" \"dist v u < k\" for f u v\n  proof -\n    obtain G where \"G \\<in> ?\\<G>\" \"u \\<in> G\" \"v \\<in> G\"\n      using k that\n      by (metis \\<open>dist v u < k\\<close> \\<open>u \\<in> S\\<close> \\<open>0 < k\\<close> centre_in_ball subsetD dist_commute mem_ball)\n    then obtain w where w: \"dist w u < d w (e/2)\" \"dist w v < d w (e/2)\" \"w \\<in> S\"\n      by auto\n    with that d_dist have \"dist (f w) (f v) < e/2\"\n      by (metis \\<open>0 < e\\<close> dist_commute half_gt_zero)\n    moreover\n    have \"dist (f w) (f u) < e/2\"\n      using that d_dist w by (metis \\<open>0 < e\\<close> dist_commute divide_pos_pos zero_less_numeral)\n    ultimately show ?thesis\n      using dist_triangle_half_r by blast\n  qed\n  ultimately show ?thesis using that by blast\nqed\n\ncorollary compact_uniformly_continuous:\n  fixes f :: \"'a :: metric_space \\<Rightarrow> 'b :: metric_space\"\n  assumes f: \"continuous_on S f\" and S: \"compact S\"\n  shows \"uniformly_continuous_on S f\"\n  using f\n    unfolding continuous_on_iff uniformly_continuous_on_def\n    by (force intro: compact_uniformly_equicontinuous [OF S, of \"{f}\"])\n\n\nsubsection\\<^marker>\\<open>tag unimportant\\<close>\\<open> Theorems relating continuity and uniform continuity to closures\\<close>\n\nlemma continuous_on_closure:\n   \"continuous_on (closure S) f \\<longleftrightarrow>\n    (\\<forall>x e. x \\<in> closure S \\<and> 0 < e\n           \\<longrightarrow> (\\<exists>d. 0 < d \\<and> (\\<forall>y. y \\<in> S \\<and> dist y x < d \\<longrightarrow> dist (f y) (f x) < e)))\"\n   (is \"?lhs = ?rhs\")\nproof\n  assume ?lhs then show ?rhs\n    unfolding continuous_on_iff  by (metis Un_iff closure_def)\nnext\n  assume R [rule_format]: ?rhs\n  show ?lhs\n  proof\n    fix x and e::real\n    assume \"0 < e\" and x: \"x \\<in> closure S\"\n    obtain \\<delta>::real where \"\\<delta> > 0\"\n                   and \\<delta>: \"\\<And>y. \\<lbrakk>y \\<in> S; dist y x < \\<delta>\\<rbrakk> \\<Longrightarrow> dist (f y) (f x) < e/2\"\n      using R [of x \"e/2\"] \\<open>0 < e\\<close> x by auto\n    have \"dist (f y) (f x) \\<le> e\" if y: \"y \\<in> closure S\" and dyx: \"dist y x < \\<delta>/2\" for y\n    proof -\n      obtain \\<delta>'::real where \"\\<delta>' > 0\"\n                      and \\<delta>': \"\\<And>z. \\<lbrakk>z \\<in> S; dist z y < \\<delta>'\\<rbrakk> \\<Longrightarrow> dist (f z) (f y) < e/2\"\n        using R [of y \"e/2\"] \\<open>0 < e\\<close> y by auto\n      obtain z where \"z \\<in> S\" and z: \"dist z y < min \\<delta>' \\<delta> / 2\"\n        using closure_approachable y\n        by (metis \\<open>0 < \\<delta>'\\<close> \\<open>0 < \\<delta>\\<close> divide_pos_pos min_less_iff_conj zero_less_numeral)\n      have \"dist (f z) (f y) < e/2\"\n        using \\<delta>' [OF \\<open>z \\<in> S\\<close>] z \\<open>0 < \\<delta>'\\<close> by metric\n      moreover have \"dist (f z) (f x) < e/2\"\n        using \\<delta>[OF \\<open>z \\<in> S\\<close>] z dyx by metric\n      ultimately show ?thesis\n        by metric\n    qed\n    then show \"\\<exists>d>0. \\<forall>x'\\<in>closure S. dist x' x < d \\<longrightarrow> dist (f x') (f x) \\<le> e\"\n      by (rule_tac x=\"\\<delta>/2\" in exI) (simp add: \\<open>\\<delta> > 0\\<close>)\n  qed\nqed\n\nlemma continuous_on_closure_sequentially:\n  fixes f :: \"'a::metric_space \\<Rightarrow> 'b :: metric_space\"\n  shows\n   \"continuous_on (closure S) f \\<longleftrightarrow>\n    (\\<forall>x a. a \\<in> closure S \\<and> (\\<forall>n. x n \\<in> S) \\<and> x \\<longlonglongrightarrow> a \\<longrightarrow> (f \\<circ> x) \\<longlonglongrightarrow> f a)\"\n   (is \"?lhs = ?rhs\")\nproof -\n  have \"continuous_on (closure S) f \\<longleftrightarrow>\n           (\\<forall>x \\<in> closure S. continuous (at x within S) f)\"\n    by (force simp: continuous_on_closure continuous_within_eps_delta)\n  also have \"... = ?rhs\"\n    by (force simp: continuous_within_sequentially)\n  finally show ?thesis .\nqed\n\nlemma uniformly_continuous_on_closure:\n  fixes f :: \"'a::metric_space \\<Rightarrow> 'b::metric_space\"\n  assumes ucont: \"uniformly_continuous_on S f\"\n      and cont: \"continuous_on (closure S) f\"\n    shows \"uniformly_continuous_on (closure S) f\"\nunfolding uniformly_continuous_on_def\nproof (intro allI impI)\n  fix e::real\n  assume \"0 < e\"\n  then obtain d::real\n    where \"d>0\"\n      and d: \"\\<And>x x'. \\<lbrakk>x\\<in>S; x'\\<in>S; dist x' x < d\\<rbrakk> \\<Longrightarrow> dist (f x') (f x) < e/3\"\n    using ucont [unfolded uniformly_continuous_on_def, rule_format, of \"e/3\"] by auto\n  show \"\\<exists>d>0. \\<forall>x\\<in>closure S. \\<forall>x'\\<in>closure S. dist x' x < d \\<longrightarrow> dist (f x') (f x) < e\"\n  proof (rule exI [where x=\"d/3\"], clarsimp simp: \\<open>d > 0\\<close>)\n    fix x y\n    assume x: \"x \\<in> closure S\" and y: \"y \\<in> closure S\" and dyx: \"dist y x * 3 < d\"\n    obtain d1::real where \"d1 > 0\"\n           and d1: \"\\<And>w. \\<lbrakk>w \\<in> closure S; dist w x < d1\\<rbrakk> \\<Longrightarrow> dist (f w) (f x) < e/3\"\n      using cont [unfolded continuous_on_iff, rule_format, of \"x\" \"e/3\"] \\<open>0 < e\\<close> x by auto\n     obtain x' where \"x' \\<in> S\" and x': \"dist x' x < min d1 (d / 3)\"\n        using closure_approachable [of x S]\n        by (metis \\<open>0 < d1\\<close> \\<open>0 < d\\<close> divide_pos_pos min_less_iff_conj x zero_less_numeral)\n    obtain d2::real where \"d2 > 0\"\n           and d2: \"\\<forall>w \\<in> closure S. dist w y < d2 \\<longrightarrow> dist (f w) (f y) < e/3\"\n      using cont [unfolded continuous_on_iff, rule_format, of \"y\" \"e/3\"] \\<open>0 < e\\<close> y by auto\n    obtain y' where \"y' \\<in> S\" and y': \"dist y' y < min d2 (d / 3)\"\n      using closure_approachable [of y S]\n      by (metis \\<open>0 < d2\\<close> \\<open>0 < d\\<close> divide_pos_pos min_less_iff_conj y zero_less_numeral)\n    have \"dist x' x < d/3\" using x' by auto\n    then have \"dist x' y' < d\"\n      using dyx y' by metric\n    then have \"dist (f x') (f y') < e/3\"\n      by (rule d [OF \\<open>y' \\<in> S\\<close> \\<open>x' \\<in> S\\<close>])\n    moreover have \"dist (f x') (f x) < e/3\" using \\<open>x' \\<in> S\\<close> closure_subset x' d1\n      by (simp add: closure_def)\n    moreover have \"dist (f y') (f y) < e/3\" using \\<open>y' \\<in> S\\<close> closure_subset y' d2\n      by (simp add: closure_def)\n    ultimately show \"dist (f y) (f x) < e\" by metric\n  qed\nqed\n\nlemma uniformly_continuous_on_extension_at_closure:\n  fixes f::\"'a::metric_space \\<Rightarrow> 'b::complete_space\"\n  assumes uc: \"uniformly_continuous_on X f\"\n  assumes \"x \\<in> closure X\"\n  obtains l where \"(f \\<longlongrightarrow> l) (at x within X)\"\nproof -\n  from assms obtain xs where xs: \"xs \\<longlonglongrightarrow> x\" \"\\<And>n. xs n \\<in> X\"\n    by (auto simp: closure_sequential)\n\n  from uniformly_continuous_on_Cauchy[OF uc LIMSEQ_imp_Cauchy, OF xs]\n  obtain l where l: \"(\\<lambda>n. f (xs n)) \\<longlonglongrightarrow> l\"\n    by atomize_elim (simp only: convergent_eq_Cauchy)\n\n  have \"(f \\<longlongrightarrow> l) (at x within X)\"\n  proof (safe intro!: Lim_within_LIMSEQ)\n    fix xs'\n    assume \"\\<forall>n. xs' n \\<noteq> x \\<and> xs' n \\<in> X\"\n      and xs': \"xs' \\<longlonglongrightarrow> x\"\n    then have \"xs' n \\<noteq> x\" \"xs' n \\<in> X\" for n by auto\n\n    from uniformly_continuous_on_Cauchy[OF uc LIMSEQ_imp_Cauchy, OF \\<open>xs' \\<longlonglongrightarrow> x\\<close> \\<open>xs' _ \\<in> X\\<close>]\n    obtain l' where l': \"(\\<lambda>n. f (xs' n)) \\<longlonglongrightarrow> l'\"\n      by atomize_elim (simp only: convergent_eq_Cauchy)\n\n    show \"(\\<lambda>n. f (xs' n)) \\<longlonglongrightarrow> l\"\n    proof (rule tendstoI)\n      fix e::real assume \"e > 0\"\n      define e' where \"e' \\<equiv> e/2\"\n      have \"e' > 0\" using \\<open>e > 0\\<close> by (simp add: e'_def)\n\n      have \"\\<forall>\\<^sub>F n in sequentially. dist (f (xs n)) l < e'\"\n        by (simp add: \\<open>0 < e'\\<close> l tendstoD)\n      moreover\n      from uc[unfolded uniformly_continuous_on_def, rule_format, OF \\<open>e' > 0\\<close>]\n      obtain d where d: \"d > 0\" \"\\<And>x x'. x \\<in> X \\<Longrightarrow> x' \\<in> X \\<Longrightarrow> dist x x' < d \\<Longrightarrow> dist (f x) (f x') < e'\"\n        by auto\n      have \"\\<forall>\\<^sub>F n in sequentially. dist (xs n) (xs' n) < d\"\n        by (auto intro!: \\<open>0 < d\\<close> order_tendstoD tendsto_eq_intros xs xs')\n      ultimately\n      show \"\\<forall>\\<^sub>F n in sequentially. dist (f (xs' n)) l < e\"\n      proof eventually_elim\n        case (elim n)\n        have \"dist (f (xs' n)) l \\<le> dist (f (xs n)) (f (xs' n)) + dist (f (xs n)) l\"\n          by metric\n        also have \"dist (f (xs n)) (f (xs' n)) < e'\"\n          by (auto intro!: d xs \\<open>xs' _ \\<in> _\\<close> elim)\n        also note \\<open>dist (f (xs n)) l < e'\\<close>\n        also have \"e' + e' = e\" by (simp add: e'_def)\n        finally show ?case by simp\n      qed\n    qed\n  qed\n  thus ?thesis ..\nqed\n\nlemma uniformly_continuous_on_extension_on_closure:\n  fixes f::\"'a::metric_space \\<Rightarrow> 'b::complete_space\"\n  assumes uc: \"uniformly_continuous_on X f\"\n  obtains g where \"uniformly_continuous_on (closure X) g\" \"\\<And>x. x \\<in> X \\<Longrightarrow> f x = g x\"\n    \"\\<And>Y h x. X \\<subseteq> Y \\<Longrightarrow> Y \\<subseteq> closure X \\<Longrightarrow> continuous_on Y h \\<Longrightarrow> (\\<And>x. x \\<in> X \\<Longrightarrow> f x = h x) \\<Longrightarrow> x \\<in> Y \\<Longrightarrow> h x = g x\"\nproof -\n  from uc have cont_f: \"continuous_on X f\"\n    by (simp add: uniformly_continuous_imp_continuous)\n  obtain y where y: \"(f \\<longlongrightarrow> y x) (at x within X)\" if \"x \\<in> closure X\" for x\n    apply atomize_elim\n    apply (rule choice)\n    using uniformly_continuous_on_extension_at_closure[OF assms]\n    by metis\n  let ?g = \"\\<lambda>x. if x \\<in> X then f x else y x\"\n\n  have \"uniformly_continuous_on (closure X) ?g\"\n    unfolding uniformly_continuous_on_def\n  proof safe\n    fix e::real assume \"e > 0\"\n    define e' where \"e' \\<equiv> e / 3\"\n    have \"e' > 0\" using \\<open>e > 0\\<close> by (simp add: e'_def)\n    from uc[unfolded uniformly_continuous_on_def, rule_format, OF \\<open>0 < e'\\<close>]\n    obtain d where \"d > 0\" and d: \"\\<And>x x'. x \\<in> X \\<Longrightarrow> x' \\<in> X \\<Longrightarrow> dist x' x < d \\<Longrightarrow> dist (f x') (f x) < e'\"\n      by auto\n    define d' where \"d' = d / 3\"\n    have \"d' > 0\" using \\<open>d > 0\\<close> by (simp add: d'_def)\n    show \"\\<exists>d>0. \\<forall>x\\<in>closure X. \\<forall>x'\\<in>closure X. dist x' x < d \\<longrightarrow> dist (?g x') (?g x) < e\"\n    proof (safe intro!: exI[where x=d'] \\<open>d' > 0\\<close>)\n      fix x x' assume x: \"x \\<in> closure X\" and x': \"x' \\<in> closure X\" and dist: \"dist x' x < d'\"\n      then obtain xs xs' where xs: \"xs \\<longlonglongrightarrow> x\" \"\\<And>n. xs n \\<in> X\"\n        and xs': \"xs' \\<longlonglongrightarrow> x'\" \"\\<And>n. xs' n \\<in> X\"\n        by (auto simp: closure_sequential)\n      have \"\\<forall>\\<^sub>F n in sequentially. dist (xs' n) x' < d'\"\n        and \"\\<forall>\\<^sub>F n in sequentially. dist (xs n) x < d'\"\n        by (auto intro!: \\<open>0 < d'\\<close> order_tendstoD tendsto_eq_intros xs xs')\n      moreover\n      have \"(\\<lambda>x. f (xs x)) \\<longlonglongrightarrow> y x\" if \"x \\<in> closure X\" \"x \\<notin> X\" \"xs \\<longlonglongrightarrow> x\" \"\\<And>n. xs n \\<in> X\" for xs x\n        using that not_eventuallyD\n        by (force intro!: filterlim_compose[OF y[OF \\<open>x \\<in> closure X\\<close>]] simp: filterlim_at)\n      then have \"(\\<lambda>x. f (xs' x)) \\<longlonglongrightarrow> ?g x'\" \"(\\<lambda>x. f (xs x)) \\<longlonglongrightarrow> ?g x\"\n        using x x'\n        by (auto intro!: continuous_on_tendsto_compose[OF cont_f] simp: xs' xs)\n      then have \"\\<forall>\\<^sub>F n in sequentially. dist (f (xs' n)) (?g x') < e'\"\n        \"\\<forall>\\<^sub>F n in sequentially. dist (f (xs n)) (?g x) < e'\"\n        by (auto intro!: \\<open>0 < e'\\<close> order_tendstoD tendsto_eq_intros)\n      ultimately\n      have \"\\<forall>\\<^sub>F n in sequentially. dist (?g x') (?g x) < e\"\n      proof eventually_elim\n        case (elim n)\n        have \"dist (?g x') (?g x) \\<le>\n          dist (f (xs' n)) (?g x') + dist (f (xs' n)) (f (xs n)) + dist (f (xs n)) (?g x)\"\n          by (metis add.commute add_le_cancel_left dist_commute dist_triangle dist_triangle_le)\n        also\n        from \\<open>dist (xs' n) x' < d'\\<close> \\<open>dist x' x < d'\\<close> \\<open>dist (xs n) x < d'\\<close>\n        have \"dist (xs' n) (xs n) < d\" unfolding d'_def by metric\n        with \\<open>xs _ \\<in> X\\<close> \\<open>xs' _ \\<in> X\\<close> have \"dist (f (xs' n)) (f (xs n)) < e'\"\n          by (rule d)\n        also note \\<open>dist (f (xs' n)) (?g x') < e'\\<close>\n        also note \\<open>dist (f (xs n)) (?g x) < e'\\<close>\n        finally show ?case by (simp add: e'_def)\n      qed\n      then show \"dist (?g x') (?g x) < e\" by simp\n    qed\n  qed\n  moreover have \"f x = ?g x\" if \"x \\<in> X\" for x using that by simp\n  moreover\n  {\n    fix Y h x\n    assume Y: \"x \\<in> Y\" \"X \\<subseteq> Y\" \"Y \\<subseteq> closure X\" and cont_h: \"continuous_on Y h\"\n      and extension: \"(\\<And>x. x \\<in> X \\<Longrightarrow> f x = h x)\"\n    {\n      assume \"x \\<notin> X\"\n      have \"x \\<in> closure X\" using Y by auto\n      then obtain xs where xs: \"xs \\<longlonglongrightarrow> x\" \"\\<And>n. xs n \\<in> X\"\n        by (auto simp: closure_sequential)\n      from continuous_on_tendsto_compose[OF cont_h xs(1)] xs(2) Y\n      have hx: \"(\\<lambda>x. f (xs x)) \\<longlonglongrightarrow> h x\"\n        by (auto simp: subsetD extension)\n      then have \"(\\<lambda>x. f (xs x)) \\<longlonglongrightarrow> y x\"\n        using \\<open>x \\<notin> X\\<close> not_eventuallyD xs(2)\n        by (force intro!: filterlim_compose[OF y[OF \\<open>x \\<in> closure X\\<close>]] simp: filterlim_at xs)\n      with hx have \"h x = y x\" by (rule LIMSEQ_unique)\n    } then\n    have \"h x = ?g x\"\n      using extension by auto\n  }\n  ultimately show ?thesis ..\nqed\n\nlemma bounded_uniformly_continuous_image:\n  fixes f :: \"'a :: heine_borel \\<Rightarrow> 'b :: heine_borel\"\n  assumes \"uniformly_continuous_on S f\" \"bounded S\"\n  shows \"bounded(f ` S)\"\n  by (metis (no_types, lifting) assms bounded_closure_image compact_closure compact_continuous_image compact_eq_bounded_closed image_cong uniformly_continuous_imp_continuous uniformly_continuous_on_extension_on_closure)\n\n\nsubsection \\<open>With Abstract Topology (TODO: move and remove dependency?)\\<close>\n\nlemma openin_contains_ball:\n    \"openin (top_of_set T) S \\<longleftrightarrow>\n     S \\<subseteq> T \\<and> (\\<forall>x \\<in> S. \\<exists>e. 0 < e \\<and> ball x e \\<inter> T \\<subseteq> S)\"\n    (is \"?lhs = ?rhs\")\nproof\n  assume ?lhs\n  then show ?rhs\n    apply (simp add: openin_open)\n    apply (metis Int_commute Int_mono inf.cobounded2 open_contains_ball order_refl subsetCE)\n    done\nnext\n  assume ?rhs\n  then show ?lhs\n    apply (simp add: openin_euclidean_subtopology_iff)\n    by (metis (no_types) Int_iff dist_commute inf.absorb_iff2 mem_ball)\nqed\n\nlemma openin_contains_cball:\n   \"openin (top_of_set T) S \\<longleftrightarrow>\n        S \\<subseteq> T \\<and> (\\<forall>x \\<in> S. \\<exists>e. 0 < e \\<and> cball x e \\<inter> T \\<subseteq> S)\"\n    (is \"?lhs = ?rhs\")\nproof\n  assume ?lhs\n  then show ?rhs\n    by (force simp add: openin_contains_ball intro: exI [where x=\"_/2\"])\nnext\n  assume ?rhs\n  then show ?lhs\n    by (force simp add: openin_contains_ball)\nqed\n\n\nsubsection \\<open>Closed Nest\\<close>\n\ntext \\<open>Bounded closed nest property (proof does not use Heine-Borel)\\<close>\n\nlemma bounded_closed_nest:\n  fixes S :: \"nat \\<Rightarrow> ('a::heine_borel) set\"\n  assumes \"\\<And>n. closed (S n)\"\n      and \"\\<And>n. S n \\<noteq> {}\"\n      and \"\\<And>m n. m \\<le> n \\<Longrightarrow> S n \\<subseteq> S m\"\n      and \"bounded (S 0)\"\n  obtains a where \"\\<And>n. a \\<in> S n\"\nproof -\n  from assms(2) obtain x where x: \"\\<forall>n. x n \\<in> S n\"\n    using choice[of \"\\<lambda>n x. x \\<in> S n\"] by auto\n  from assms(4,1) have \"seq_compact (S 0)\"\n    by (simp add: bounded_closed_imp_seq_compact)\n  then obtain l r where lr: \"l \\<in> S 0\" \"strict_mono r\" \"(x \\<circ> r) \\<longlonglongrightarrow> l\"\n    using x and assms(3) unfolding seq_compact_def by blast\n  have \"\\<forall>n. l \\<in> S n\"\n  proof\n    fix n :: nat\n    have \"closed (S n)\"\n      using assms(1) by simp\n    moreover have \"\\<forall>i. (x \\<circ> r) i \\<in> S i\"\n      using x and assms(3) and lr(2) [THEN seq_suble] by auto\n    then have \"\\<forall>i. (x \\<circ> r) (i + n) \\<in> S n\"\n      using assms(3) by (fast intro!: le_add2)\n    moreover have \"(\\<lambda>i. (x \\<circ> r) (i + n)) \\<longlonglongrightarrow> l\"\n      using lr(3) by (rule LIMSEQ_ignore_initial_segment)\n    ultimately show \"l \\<in> S n\"\n      by (rule closed_sequentially)\n  qed\n  then show ?thesis \n    using that by blast\nqed\n\ntext \\<open>Decreasing case does not even need compactness, just completeness.\\<close>\n\nlemma decreasing_closed_nest:\n  fixes S :: \"nat \\<Rightarrow> ('a::complete_space) set\"\n  assumes \"\\<And>n. closed (S n)\"\n          \"\\<And>n. S n \\<noteq> {}\"\n          \"\\<And>m n. m \\<le> n \\<Longrightarrow> S n \\<subseteq> S m\"\n          \"\\<And>e. e>0 \\<Longrightarrow> \\<exists>n. \\<forall>x\\<in>S n. \\<forall>y\\<in>S n. dist x y < e\"\n  obtains a where \"\\<And>n. a \\<in> S n\"\nproof -\n  have \"\\<forall>n. \\<exists>x. x \\<in> S n\"\n    using assms(2) by auto\n  then have \"\\<exists>t. \\<forall>n. t n \\<in> S n\"\n    using choice[of \"\\<lambda>n x. x \\<in> S n\"] by auto\n  then obtain t where t: \"\\<forall>n. t n \\<in> S n\" by auto\n  {\n    fix e :: real\n    assume \"e > 0\"\n    then obtain N where N: \"\\<forall>x\\<in>S N. \\<forall>y\\<in>S N. dist x y < e\"\n      using assms(4) by blast\n    {\n      fix m n :: nat\n      assume \"N \\<le> m \\<and> N \\<le> n\"\n      then have \"t m \\<in> S N\" \"t n \\<in> S N\"\n        using assms(3) t unfolding  subset_eq t by blast+\n      then have \"dist (t m) (t n) < e\"\n        using N by auto\n    }\n    then have \"\\<exists>N. \\<forall>m n. N \\<le> m \\<and> N \\<le> n \\<longrightarrow> dist (t m) (t n) < e\"\n      by auto\n  }\n  then have \"Cauchy t\"\n    unfolding cauchy_def by auto\n  then obtain l where l:\"(t \\<longlongrightarrow> l) sequentially\"\n    using complete_UNIV unfolding complete_def by auto\n  { fix n :: nat\n    { fix e :: real\n      assume \"e > 0\"\n      then obtain N :: nat where N: \"\\<forall>n\\<ge>N. dist (t n) l < e\"\n        using l[unfolded lim_sequentially] by auto\n      have \"t (max n N) \\<in> S n\"\n        by (meson assms(3) contra_subsetD max.cobounded1 t)\n      then have \"\\<exists>y\\<in>S n. dist y l < e\"\n        using N max.cobounded2 by blast\n    }\n    then have \"l \\<in> S n\"\n      using closed_approachable[of \"S n\" l] assms(1) by auto\n  }\n  then show ?thesis\n    using that by blast\nqed\n\ntext \\<open>Strengthen it to the intersection actually being a singleton.\\<close>\n\nlemma decreasing_closed_nest_sing:\n  fixes S :: \"nat \\<Rightarrow> 'a::complete_space set\"\n  assumes \"\\<And>n. closed(S n)\"\n          \"\\<And>n. S n \\<noteq> {}\"\n          \"\\<And>m n. m \\<le> n \\<Longrightarrow> S n \\<subseteq> S m\"\n          \"\\<And>e. e>0 \\<Longrightarrow> \\<exists>n. \\<forall>x \\<in> (S n). \\<forall> y\\<in>(S n). dist x y < e\"\n  shows \"\\<exists>a. \\<Inter>(range S) = {a}\"\nproof -\n  obtain a where a: \"\\<forall>n. a \\<in> S n\"\n    using decreasing_closed_nest[of S] using assms by auto\n  { fix b\n    assume b: \"b \\<in> \\<Inter>(range S)\"\n    { fix e :: real\n      assume \"e > 0\"\n      then have \"dist a b < e\"\n        using assms(4) and b and a by blast\n    }\n    then have \"dist a b = 0\"\n      by (metis dist_eq_0_iff dist_nz less_le)\n  }\n  with a have \"\\<Inter>(range S) = {a}\"\n    unfolding image_def by auto\n  then show ?thesis ..\nqed\n\nsubsection\\<^marker>\\<open>tag unimportant\\<close> \\<open>Making a continuous function avoid some value in a neighbourhood\\<close>\n\nlemma continuous_within_avoid:\n  fixes f :: \"'a::metric_space \\<Rightarrow> 'b::t1_space\"\n  assumes \"continuous (at x within s) f\"\n    and \"f x \\<noteq> a\"\n  shows \"\\<exists>e>0. \\<forall>y \\<in> s. dist x y < e --> f y \\<noteq> a\"\nproof -\n  obtain U where \"open U\" and \"f x \\<in> U\" and \"a \\<notin> U\"\n    using t1_space [OF \\<open>f x \\<noteq> a\\<close>] by fast\n  have \"(f \\<longlongrightarrow> f x) (at x within s)\"\n    using assms(1) by (simp add: continuous_within)\n  then have \"eventually (\\<lambda>y. f y \\<in> U) (at x within s)\"\n    using \\<open>open U\\<close> and \\<open>f x \\<in> U\\<close>\n    unfolding tendsto_def by fast\n  then have \"eventually (\\<lambda>y. f y \\<noteq> a) (at x within s)\"\n    using \\<open>a \\<notin> U\\<close> by (fast elim: eventually_mono)\n  then show ?thesis\n    using \\<open>f x \\<noteq> a\\<close> by (auto simp: dist_commute eventually_at)\nqed\n\nlemma continuous_at_avoid:\n  fixes f :: \"'a::metric_space \\<Rightarrow> 'b::t1_space\"\n  assumes \"continuous (at x) f\"\n    and \"f x \\<noteq> a\"\n  shows \"\\<exists>e>0. \\<forall>y. dist x y < e \\<longrightarrow> f y \\<noteq> a\"\n  using assms continuous_within_avoid[of x UNIV f a] by simp\n\nlemma continuous_on_avoid:\n  fixes f :: \"'a::metric_space \\<Rightarrow> 'b::t1_space\"\n  assumes \"continuous_on s f\"\n    and \"x \\<in> s\"\n    and \"f x \\<noteq> a\"\n  shows \"\\<exists>e>0. \\<forall>y \\<in> s. dist x y < e \\<longrightarrow> f y \\<noteq> a\"\n  using assms(1)[unfolded continuous_on_eq_continuous_within, THEN bspec[where x=x],\n    OF assms(2)] continuous_within_avoid[of x s f a]\n  using assms(3)\n  by auto\n\nlemma continuous_on_open_avoid:\n  fixes f :: \"'a::metric_space \\<Rightarrow> 'b::t1_space\"\n  assumes \"continuous_on s f\"\n    and \"open s\"\n    and \"x \\<in> s\"\n    and \"f x \\<noteq> a\"\n  shows \"\\<exists>e>0. \\<forall>y. dist x y < e \\<longrightarrow> f y \\<noteq> a\"\n  using assms(1)[unfolded continuous_on_eq_continuous_at[OF assms(2)], THEN bspec[where x=x], OF assms(3)]\n  using continuous_at_avoid[of x f a] assms(4)\n  by auto\n\nsubsection \\<open>Consequences for Real Numbers\\<close>\n\nlemma closed_contains_Inf:\n  fixes S :: \"real set\"\n  shows \"S \\<noteq> {} \\<Longrightarrow> bdd_below S \\<Longrightarrow> closed S \\<Longrightarrow> Inf S \\<in> S\"\n  by (metis closure_contains_Inf closure_closed)\n\nlemma closed_subset_contains_Inf:\n  fixes A C :: \"real set\"\n  shows \"closed C \\<Longrightarrow> A \\<subseteq> C \\<Longrightarrow> A \\<noteq> {} \\<Longrightarrow> bdd_below A \\<Longrightarrow> Inf A \\<in> C\"\n  by (metis closure_contains_Inf closure_minimal subset_eq)\n\nlemma closed_contains_Sup:\n  fixes S :: \"real set\"\n  shows \"S \\<noteq> {} \\<Longrightarrow> bdd_above S \\<Longrightarrow> closed S \\<Longrightarrow> Sup S \\<in> S\"\n  by (subst closure_closed[symmetric], assumption, rule closure_contains_Sup)\n\nlemma closed_subset_contains_Sup:\n  fixes A C :: \"real set\"\n  shows \"closed C \\<Longrightarrow> A \\<subseteq> C \\<Longrightarrow> A \\<noteq> {} \\<Longrightarrow> bdd_above A \\<Longrightarrow> Sup A \\<in> C\"\n  by (metis closure_contains_Sup closure_minimal subset_eq)\n\nlemma atLeastAtMost_subset_contains_Inf:\n  fixes A :: \"real set\" and a b :: real\n  shows \"A \\<noteq> {} \\<Longrightarrow> a \\<le> b \\<Longrightarrow> A \\<subseteq> {a..b} \\<Longrightarrow> Inf A \\<in> {a..b}\"\n  by (rule closed_subset_contains_Inf)\n     (auto intro: closed_real_atLeastAtMost intro!: bdd_belowI[of A a])\n\nlemma bounded_real: \"bounded (S::real set) \\<longleftrightarrow> (\\<exists>a. \\<forall>x\\<in>S. \\<bar>x\\<bar> \\<le> a)\"\n  by (simp add: bounded_iff)\n\nlemma bounded_imp_bdd_above: \"bounded S \\<Longrightarrow> bdd_above (S :: real set)\"\n  by (auto simp: bounded_def bdd_above_def dist_real_def)\n     (metis abs_le_D1 abs_minus_commute diff_le_eq)\n\nlemma bounded_imp_bdd_below: \"bounded S \\<Longrightarrow> bdd_below (S :: real set)\"\n  by (auto simp: bounded_def bdd_below_def dist_real_def)\n     (metis abs_le_D1 add.commute diff_le_eq)\n\nlemma bounded_has_Sup:\n  fixes S :: \"real set\"\n  assumes \"bounded S\"\n    and \"S \\<noteq> {}\"\n  shows \"\\<forall>x\\<in>S. x \\<le> Sup S\"\n    and \"\\<forall>b. (\\<forall>x\\<in>S. x \\<le> b) \\<longrightarrow> Sup S \\<le> b\"\nproof\n  show \"\\<forall>b. (\\<forall>x\\<in>S. x \\<le> b) \\<longrightarrow> Sup S \\<le> b\"\n    using assms by (metis cSup_least)\nqed (metis cSup_upper assms(1) bounded_imp_bdd_above)\n\nlemma Sup_insert:\n  fixes S :: \"real set\"\n  shows \"bounded S \\<Longrightarrow> Sup (insert x S) = (if S = {} then x else max x (Sup S))\"\n  by (auto simp: bounded_imp_bdd_above sup_max cSup_insert_If)\n\nlemma bounded_has_Inf:\n  fixes S :: \"real set\"\n  assumes \"bounded S\"\n    and \"S \\<noteq> {}\"\n  shows \"\\<forall>x\\<in>S. x \\<ge> Inf S\"\n    and \"\\<forall>b. (\\<forall>x\\<in>S. x \\<ge> b) \\<longrightarrow> Inf S \\<ge> b\"\nproof\n  show \"\\<forall>b. (\\<forall>x\\<in>S. x \\<ge> b) \\<longrightarrow> Inf S \\<ge> b\"\n    using assms by (metis cInf_greatest)\nqed (metis cInf_lower assms(1) bounded_imp_bdd_below)\n\nlemma Inf_insert:\n  fixes S :: \"real set\"\n  shows \"bounded S \\<Longrightarrow> Inf (insert x S) = (if S = {} then x else min x (Inf S))\"\n  by (auto simp: bounded_imp_bdd_below inf_min cInf_insert_If)\n\nlemma open_real:\n  fixes s :: \"real set\"\n  shows \"open s \\<longleftrightarrow> (\\<forall>x \\<in> s. \\<exists>e>0. \\<forall>x'. \\<bar>x' - x\\<bar> < e --> x' \\<in> s)\"\n  unfolding open_dist dist_norm by simp\n\nlemma islimpt_approachable_real:\n  fixes s :: \"real set\"\n  shows \"x islimpt s \\<longleftrightarrow> (\\<forall>e>0. \\<exists>x'\\<in> s. x' \\<noteq> x \\<and> \\<bar>x' - x\\<bar> < e)\"\n  unfolding islimpt_approachable dist_norm by simp\n\nlemma closed_real:\n  fixes s :: \"real set\"\n  shows \"closed s \\<longleftrightarrow> (\\<forall>x. (\\<forall>e>0.  \\<exists>x' \\<in> s. x' \\<noteq> x \\<and> \\<bar>x' - x\\<bar> < e) \\<longrightarrow> x \\<in> s)\"\n  unfolding closed_limpt islimpt_approachable dist_norm by simp\n\nlemma continuous_at_real_range:\n  fixes f :: \"'a::real_normed_vector \\<Rightarrow> real\"\n  shows \"continuous (at x) f \\<longleftrightarrow> (\\<forall>e>0. \\<exists>d>0. \\<forall>x'. norm(x' - x) < d --> \\<bar>f x' - f x\\<bar> < e)\"\n  unfolding continuous_at\n  unfolding Lim_at\n  unfolding dist_norm\n  apply auto\n  apply (erule_tac x=e in allE, auto)\n  apply (rule_tac x=d in exI, auto)\n  apply (erule_tac x=x' in allE, auto)\n  apply (erule_tac x=e in allE, auto)\n  done\n\nlemma continuous_on_real_range:\n  fixes f :: \"'a::real_normed_vector \\<Rightarrow> real\"\n  shows \"continuous_on s f \\<longleftrightarrow>\n    (\\<forall>x \\<in> s. \\<forall>e>0. \\<exists>d>0. (\\<forall>x' \\<in> s. norm(x' - x) < d \\<longrightarrow> \\<bar>f x' - f x\\<bar> < e))\"\n  unfolding continuous_on_iff dist_norm by simp\n\nlemma continuous_on_closed_Collect_le:\n  fixes f g :: \"'a::topological_space \\<Rightarrow> real\"\n  assumes f: \"continuous_on s f\" and g: \"continuous_on s g\" and s: \"closed s\"\n  shows \"closed {x \\<in> s. f x \\<le> g x}\"\nproof -\n  have \"closed ((\\<lambda>x. g x - f x) -` {0..} \\<inter> s)\"\n    using closed_real_atLeast continuous_on_diff [OF g f]\n    by (simp add: continuous_on_closed_vimage [OF s])\n  also have \"((\\<lambda>x. g x - f x) -` {0..} \\<inter> s) = {x\\<in>s. f x \\<le> g x}\"\n    by auto\n  finally show ?thesis .\nqed\n\nlemma continuous_le_on_closure:\n  fixes a::real\n  assumes f: \"continuous_on (closure s) f\"\n      and x: \"x \\<in> closure(s)\"\n      and xlo: \"\\<And>x. x \\<in> s ==> f(x) \\<le> a\"\n    shows \"f(x) \\<le> a\"\n  using image_closure_subset [OF f, where T=\" {x. x \\<le> a}\" ] assms\n    continuous_on_closed_Collect_le[of \"UNIV\" \"\\<lambda>x. x\" \"\\<lambda>x. a\"]\n  by auto\n\nlemma continuous_ge_on_closure:\n  fixes a::real\n  assumes f: \"continuous_on (closure s) f\"\n      and x: \"x \\<in> closure(s)\"\n      and xlo: \"\\<And>x. x \\<in> s ==> f(x) \\<ge> a\"\n    shows \"f(x) \\<ge> a\"\n  using image_closure_subset [OF f, where T=\" {x. a \\<le> x}\"] assms\n    continuous_on_closed_Collect_le[of \"UNIV\" \"\\<lambda>x. a\" \"\\<lambda>x. x\"]\n  by auto\n\n\nsubsection\\<open>The infimum of the distance between two sets\\<close>\n\ndefinition\\<^marker>\\<open>tag important\\<close> setdist :: \"'a::metric_space set \\<Rightarrow> 'a set \\<Rightarrow> real\" where\n  \"setdist s t \\<equiv>\n       (if s = {} \\<or> t = {} then 0\n        else Inf {dist x y| x y. x \\<in> s \\<and> y \\<in> t})\"\n\nlemma setdist_empty1 [simp]: \"setdist {} t = 0\"\n  by (simp add: setdist_def)\n\nlemma setdist_empty2 [simp]: \"setdist t {} = 0\"\n  by (simp add: setdist_def)\n\nlemma setdist_pos_le [simp]: \"0 \\<le> setdist s t\"\n  by (auto simp: setdist_def ex_in_conv [symmetric] intro: cInf_greatest)\n\nlemma le_setdistI:\n  assumes \"s \\<noteq> {}\" \"t \\<noteq> {}\" \"\\<And>x y. \\<lbrakk>x \\<in> s; y \\<in> t\\<rbrakk> \\<Longrightarrow> d \\<le> dist x y\"\n    shows \"d \\<le> setdist s t\"\n  using assms\n  by (auto simp: setdist_def Set.ex_in_conv [symmetric] intro: cInf_greatest)\n\nlemma setdist_le_dist: \"\\<lbrakk>x \\<in> s; y \\<in> t\\<rbrakk> \\<Longrightarrow> setdist s t \\<le> dist x y\"\n  unfolding setdist_def\n  by (auto intro!: bdd_belowI [where m=0] cInf_lower)\n\nlemma le_setdist_iff:\n        \"d \\<le> setdist S T \\<longleftrightarrow>\n        (\\<forall>x \\<in> S. \\<forall>y \\<in> T. d \\<le> dist x y) \\<and> (S = {} \\<or> T = {} \\<longrightarrow> d \\<le> 0)\"\n  apply (cases \"S = {} \\<or> T = {}\")\n  apply (force simp add: setdist_def)\n  apply (intro iffI conjI)\n  using setdist_le_dist apply fastforce\n  apply (auto simp: intro: le_setdistI)\n  done\n\nlemma setdist_ltE:\n  assumes \"setdist S T < b\" \"S \\<noteq> {}\" \"T \\<noteq> {}\"\n    obtains x y where \"x \\<in> S\" \"y \\<in> T\" \"dist x y < b\"\nusing assms\nby (auto simp: not_le [symmetric] le_setdist_iff)\n\nlemma setdist_refl: \"setdist S S = 0\"\n  apply (cases \"S = {}\")\n  apply (force simp add: setdist_def)\n  apply (rule antisym [OF _ setdist_pos_le])\n  apply (metis all_not_in_conv dist_self setdist_le_dist)\n  done\n\nlemma setdist_sym: \"setdist S T = setdist T S\"\n  by (force simp: setdist_def dist_commute intro!: arg_cong [where f=Inf])\n\nlemma setdist_triangle: \"setdist S T \\<le> setdist S {a} + setdist {a} T\"\nproof (cases \"S = {} \\<or> T = {}\")\n  case True then show ?thesis\n    using setdist_pos_le by fastforce\nnext\n  case False\n  then have \"\\<And>x. x \\<in> S \\<Longrightarrow> setdist S T - dist x a \\<le> setdist {a} T\"\n    apply (intro le_setdistI)\n    apply (simp_all add: algebra_simps)\n    apply (metis dist_commute dist_triangle3 order_trans [OF setdist_le_dist])\n    done\n  then have \"setdist S T - setdist {a} T \\<le> setdist S {a}\"\n    using False by (fastforce intro: le_setdistI)\n  then show ?thesis\n    by (simp add: algebra_simps)\nqed\n\nlemma setdist_singletons [simp]: \"setdist {x} {y} = dist x y\"\n  by (simp add: setdist_def)\n\nlemma setdist_Lipschitz: \"\\<bar>setdist {x} S - setdist {y} S\\<bar> \\<le> dist x y\"\n  apply (subst setdist_singletons [symmetric])\n  by (metis abs_diff_le_iff diff_le_eq setdist_triangle setdist_sym)\n\nlemma continuous_at_setdist [continuous_intros]: \"continuous (at x) (\\<lambda>y. (setdist {y} S))\"\n  by (force simp: continuous_at_eps_delta dist_real_def intro: le_less_trans [OF setdist_Lipschitz])\n\nlemma continuous_on_setdist [continuous_intros]: \"continuous_on T (\\<lambda>y. (setdist {y} S))\"\n  by (metis continuous_at_setdist continuous_at_imp_continuous_on)\n\nlemma uniformly_continuous_on_setdist: \"uniformly_continuous_on T (\\<lambda>y. (setdist {y} S))\"\n  by (force simp: uniformly_continuous_on_def dist_real_def intro: le_less_trans [OF setdist_Lipschitz])\n\nlemma setdist_subset_right: \"\\<lbrakk>T \\<noteq> {}; T \\<subseteq> u\\<rbrakk> \\<Longrightarrow> setdist S u \\<le> setdist S T\"\n  apply (cases \"S = {} \\<or> u = {}\", force)\n  apply (auto simp: setdist_def intro!: bdd_belowI [where m=0] cInf_superset_mono)\n  done\n\nlemma setdist_subset_left: \"\\<lbrakk>S \\<noteq> {}; S \\<subseteq> T\\<rbrakk> \\<Longrightarrow> setdist T u \\<le> setdist S u\"\n  by (metis setdist_subset_right setdist_sym)\n\nlemma setdist_closure_1 [simp]: \"setdist (closure S) T = setdist S T\"\nproof (cases \"S = {} \\<or> T = {}\")\n  case True then show ?thesis by force\nnext\n  case False\n  { fix y\n    assume \"y \\<in> T\"\n    have \"continuous_on (closure S) (\\<lambda>a. dist a y)\"\n      by (auto simp: continuous_intros dist_norm)\n    then have *: \"\\<And>x. x \\<in> closure S \\<Longrightarrow> setdist S T \\<le> dist x y\"\n      by (fast intro: setdist_le_dist \\<open>y \\<in> T\\<close> continuous_ge_on_closure)\n  } note * = this\n  show ?thesis\n    apply (rule antisym)\n     using False closure_subset apply (blast intro: setdist_subset_left)\n    using False * apply (force intro!: le_setdistI)\n    done\nqed\n\nlemma setdist_closure_2 [simp]: \"setdist T (closure S) = setdist T S\"\n  by (metis setdist_closure_1 setdist_sym)\n\nlemma setdist_eq_0I: \"\\<lbrakk>x \\<in> S; x \\<in> T\\<rbrakk> \\<Longrightarrow> setdist S T = 0\"\n  by (metis antisym dist_self setdist_le_dist setdist_pos_le)\n\nlemma setdist_unique:\n  \"\\<lbrakk>a \\<in> S; b \\<in> T; \\<And>x y. x \\<in> S \\<and> y \\<in> T ==> dist a b \\<le> dist x y\\<rbrakk>\n   \\<Longrightarrow> setdist S T = dist a b\"\n  by (force simp add: setdist_le_dist le_setdist_iff intro: antisym)\n\nlemma setdist_le_sing: \"x \\<in> S ==> setdist S T \\<le> setdist {x} T\"\n  using setdist_subset_left by auto\n\nlemma infdist_eq_setdist: \"infdist x A = setdist {x} A\"\n  by (simp add: infdist_def setdist_def Setcompr_eq_image)\n\nlemma setdist_eq_infdist: \"setdist A B = (if A = {} then 0 else INF a\\<in>A. infdist a B)\"\nproof -\n  have \"Inf {dist x y |x y. x \\<in> A \\<and> y \\<in> B} = (INF x\\<in>A. Inf (dist x ` B))\"\n    if \"b \\<in> B\" \"a \\<in> A\" for a b\n  proof (rule order_antisym)\n    have \"Inf {dist x y |x y. x \\<in> A \\<and> y \\<in> B} \\<le> Inf (dist x ` B)\"\n      if  \"b \\<in> B\" \"a \\<in> A\" \"x \\<in> A\" for x \n    proof -\n      have *: \"\\<And>b'. b' \\<in> B \\<Longrightarrow> Inf {dist x y |x y. x \\<in> A \\<and> y \\<in> B} \\<le> dist x b'\"\n        by (metis (mono_tags, lifting) ex_in_conv setdist_def setdist_le_dist that(3))\n      show ?thesis\n        using that by (subst conditionally_complete_lattice_class.le_cInf_iff) (auto simp: *)+\n    qed\n    then show \"Inf {dist x y |x y. x \\<in> A \\<and> y \\<in> B} \\<le> (INF x\\<in>A. Inf (dist x ` B))\"\n      using that\n      by (subst conditionally_complete_lattice_class.le_cInf_iff) (auto simp: bdd_below_def)\n  next\n    have *: \"\\<And>x y. \\<lbrakk>b \\<in> B; a \\<in> A; x \\<in> A; y \\<in> B\\<rbrakk> \\<Longrightarrow> \\<exists>a\\<in>A. Inf (dist a ` B) \\<le> dist x y\"\n      by (meson bdd_below_image_dist cINF_lower)\n    show \"(INF x\\<in>A. Inf (dist x ` B)) \\<le> Inf {dist x y |x y. x \\<in> A \\<and> y \\<in> B}\"\n    proof (rule conditionally_complete_lattice_class.cInf_mono)\n      show \"bdd_below ((\\<lambda>x. Inf (dist x ` B)) ` A)\"\n        by (metis (no_types, lifting) bdd_belowI2 ex_in_conv infdist_def infdist_nonneg that(1))\n    qed (use that in \\<open>auto simp: *\\<close>)\n  qed\n  then show ?thesis\n    by (auto simp: setdist_def infdist_def)\nqed\n\nlemma infdist_mono:\n  assumes \"A \\<subseteq> B\" \"A \\<noteq> {}\"\n  shows \"infdist x B \\<le> infdist x A\"\n  by (simp add: assms infdist_eq_setdist setdist_subset_right)\n\nlemma infdist_singleton [simp]:\n  \"infdist x {y} = dist x y\"\n  by (simp add: infdist_eq_setdist)\n\nproposition setdist_attains_inf:\n  assumes \"compact B\" \"B \\<noteq> {}\"\n  obtains y where \"y \\<in> B\" \"setdist A B = infdist y A\"\nproof (cases \"A = {}\")\n  case True\n  then show thesis\n    by (metis assms diameter_compact_attained infdist_def setdist_def that)\nnext\n  case False\n  obtain y where \"y \\<in> B\" and min: \"\\<And>y'. y' \\<in> B \\<Longrightarrow> infdist y A \\<le> infdist y' A\"\n    by (metis continuous_attains_inf [OF assms continuous_on_infdist] continuous_on_id)\n  show thesis\n  proof\n    have \"setdist A B = (INF y\\<in>B. infdist y A)\"\n      by (metis \\<open>B \\<noteq> {}\\<close> setdist_eq_infdist setdist_sym)\n    also have \"\\<dots> = infdist y A\"\n    proof (rule order_antisym)\n      show \"(INF y\\<in>B. infdist y A) \\<le> infdist y A\"\n      proof (rule cInf_lower)\n        show \"infdist y A \\<in> (\\<lambda>y. infdist y A) ` B\"\n          using \\<open>y \\<in> B\\<close> by blast\n        show \"bdd_below ((\\<lambda>y. infdist y A) ` B)\"\n          by (meson bdd_belowI2 infdist_nonneg)\n      qed\n    next\n      show \"infdist y A \\<le> (INF y\\<in>B. infdist y A)\"\n        by (simp add: \\<open>B \\<noteq> {}\\<close> cINF_greatest min)\n    qed\n    finally show \"setdist A B = infdist y A\" .\n  qed (fact \\<open>y \\<in> B\\<close>)\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/Analysis/Elementary_Metric_Spaces.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951182587158, "lm_q2_score": 0.8311430436757313, "lm_q1q2_score": 0.7013975571326403}}
{"text": "chapter {* camr project *}\n\ntheory Term imports Main Unification begin\n(* assignment 5 *)\n(* (a) *)\n\n(* definition of messages *)\ntype_synonym var = string\ntype_synonym const = string\ndatatype msg =\nHash msg | Concat msg msg | Sym_encrypt msg msg | Pub_encrypt msg msg | Sign msg msg\n| Const const | Variable var\n(* Pub_encrypt content key  and so on*)\n\n(* (b) *)\n(* embedding *)\ndatatype symbol =\nSHash | SConcat | SSym_encrypt | SPub_encrypt | SSign | SConst const\nfun arity :: \"symbol \\<Rightarrow> nat\" where\n\"arity SHash = 1\"\n| \"arity SConcat = 2\"\n| \"arity SSym_encrypt = 2\"\n| \"arity SPub_encrypt = 2\"\n| \"arity SSign = 2\"\n| \"arity (SConst _) = 0\"\n\n(* (c) *)\ntype_synonym msg_term = \"(symbol, var) term\"\n\nfun embed :: \"msg \\<Rightarrow> msg_term\" where\n\"embed (Hash x) = Fun SHash [embed x]\"\n| \"embed (Concat x y) = Fun SConcat [embed x, embed y]\"\n| \"embed (Sym_encrypt x y) = Fun SSym_encrypt [embed x, embed y]\"\n| \"embed (Pub_encrypt x y) = Fun SPub_encrypt [embed x, embed y]\"\n| \"embed (Sign x y) = Fun SSign [embed x, embed y]\"\n| \"embed (Const x) = Fun (SConst x) []\"\n| \"embed (Variable x) = Var x\"\n\nfun msg_of_term :: \"msg_term \\<Rightarrow> msg\" where\n\"msg_of_term (Fun SHash [x]) = Hash (msg_of_term x)\"\n| \"msg_of_term (Fun SConcat [x, y]) = Concat (msg_of_term x) (msg_of_term y)\"\n| \"msg_of_term (Fun SSym_encrypt [x, y]) = Sym_encrypt (msg_of_term x) (msg_of_term y)\"\n| \"msg_of_term (Fun SPub_encrypt [x, y]) = Pub_encrypt (msg_of_term x) (msg_of_term y)\"\n| \"msg_of_term (Fun SSign [x, y]) = Sign (msg_of_term x) (msg_of_term y)\"\n| \"msg_of_term (Fun (SConst x) []) = Const x\"\n| \"msg_of_term (Var x) = Variable x\"\n\n(* embedding lemmas *)\nlemma wf_term_embed [simp]: \"wf_term arity (embed msg)\"\nproof(induction msg)\nqed(auto intro:wf_term.intros)\n\nlemma msg_of_term_embed [simp]: \"msg_of_term (embed x) = x\"\nproof(induction x)\nqed auto\n\nlemma embed_msg_of_term [simp]: \"wf_term arity x \\<Longrightarrow> embed (msg_of_term x) = x\"\nproof(induction rule:wf_term.induct)\ncase (wf_term_intro_var uu)\nthen show ?case by auto\nnext\ncase (wf_term_intro_fun l f)\n  then show ?case\n(* arity goes up to 2 so pattern match on up to 2 elements of l*)\n  proof(cases f;cases l;(cases \"tl l\")?)\n  qed(auto simp add:\"wf_term_intro_fun.IH\")\nqed\n\n(* (c) : transfer of various functions via embedding \n   naming convention: ${fn} \\<rightarrow> ${fn}_msg_*)\n(* fv *)\ndefinition fv_msg:: \"msg \\<Rightarrow> var set\" where\n\"fv_msg m = fv (embed m)\"\n\nlemma fv_msg_simps:\n\"fv_msg (Hash x) = fv_msg x\"\n\"fv_msg (Concat x y) = fv_msg x \\<union> fv_msg y\"\n\"fv_msg (Pub_encrypt x y) = fv_msg x \\<union> fv_msg y\"\n\"fv_msg (Sym_encrypt x y) = fv_msg x \\<union> fv_msg y\"\n\"fv_msg (Sign x y) = fv_msg x \\<union> fv_msg y\"\n\"fv_msg (Variable z) = {z}\"\n\"fv_msg (Const z) = {}\"\n  by(auto simp add:fv_msg_def)\n\n(* substs *)\ntype_synonym subst_msg = \"var \\<Rightarrow> msg\"\ndefinition embed_subst :: \"subst_msg \\<Rightarrow> (var \\<Rightarrow> msg_term)\" where\n\"embed_subst s = embed o s\"\ndefinition subst_from_embed :: \"(var \\<Rightarrow> msg_term) \\<Rightarrow> subst_msg\"  where\n\"subst_from_embed s = msg_of_term o s\"\n\nlemma embed_subst_from_embed [simp]: \"wf_subst arity x \\<Longrightarrow> embed_subst (subst_from_embed x) = x\"\nproof(induction rule:wf_subst.induct)\n  case (1 \\<sigma>)\n  then show ?case by(auto simp add:fun_eq_iff embed_subst_def subst_from_embed_def)\nqed\n\nlemma wf_subst_embed_subst[simp]: \"wf_subst arity (embed_subst s)\"\n  by(auto intro!:wf_subst.intros simp add:embed_subst_def)\n\nlemma wf_term_embed_subst[simp]: \"wf_term arity (embed_subst s x)\"\n  by(auto simp add:embed_subst_def intro:wf_term.intros)\n\nlemma subst_from_embed_embed_subst[simp]:\"subst_from_embed (embed_subst s) = s\"\n  by(auto simp add:embed_subst_def subst_from_embed_def)\n\nlemma embed_subst_Variable[simp]:\"embed_subst Variable = Var\"\n  by(auto simp add:embed_subst_def)\n\nlemma subst_from_embed_Var[simp]:\"subst_from_embed Var = Variable\"\n  by(auto simp add:subst_from_embed_def)\n\n(* sapply *)\ndefinition sapply_msg :: \"subst_msg \\<Rightarrow> msg \\<Rightarrow> msg\" where\n\"sapply_msg s m = msg_of_term (sapply (embed_subst s) (embed m))\"\n\nlemma sapply_msg_simps:\n\"sapply_msg s (Hash x) = Hash (sapply_msg s x)\"\n\"sapply_msg s (Concat x y) = Concat (sapply_msg s x) (sapply_msg s y)\"\n\"sapply_msg s (Sym_encrypt x y) = Sym_encrypt (sapply_msg s x) (sapply_msg s y)\"\n\"sapply_msg s (Pub_encrypt x y) = Pub_encrypt (sapply_msg s x) (sapply_msg s y)\"\n\"sapply_msg s (Sign x y) = Sign (sapply_msg s x) (sapply_msg s y)\"\n\"sapply_msg s (Const z) = Const z\"\n\"sapply_msg Variable x = x\"\n  by(auto simp add:sapply_msg_def)\n\n(* scomp *)\ndefinition scomp_msg:: \"subst_msg \\<Rightarrow> subst_msg \\<Rightarrow> subst_msg\" where\n\"scomp_msg s t = subst_from_embed ((embed_subst s) \\<circ>s (embed_subst t))\"\n\nlemma embed_scomp_wf: \"wf_subst arity ((embed_subst t) \\<circ>s (embed_subst s))\"\n  by(simp add:wf_subst_scomp)\n\nlemma sapply_msg_scomp_msg:\n\"sapply_msg (scomp_msg t s) c = sapply_msg t (sapply_msg s c)\" (is \"?lhs = ?rhs\")\n  by(auto simp add:sapply_msg_def scomp_msg_def embed_scomp_wf wf_term_sapply)\n\nlemma scomp_variable[simp]: \"scomp_msg Variable s = s\" \"scomp_msg s Variable = s\"\n  by(simp_all add:scomp_msg_def)\n\nlemma scomp_msg_assoc: \"scomp_msg (scomp_msg a b) c = scomp_msg a (scomp_msg b c)\" (is \"?lhs = ?rhs\")\n  by(simp_all add:scomp_msg_def embed_scomp_wf scomp_assoc)\n\n(* equations *)\ntype_synonym eq_msg = \"msg \\<times> msg\"\nfun embed_eq :: \"eq_msg \\<Rightarrow> (symbol, var) equation\" where\n\"embed_eq (a, b) = (embed a, embed b)\"\nfun eq_from_embed:: \"(symbol, var) equation \\<Rightarrow> eq_msg\" where\n\"eq_from_embed (a, b) = (msg_of_term a, msg_of_term b)\"\n\nlemma wf_embed_eq [simp]:\"wf_eq arity (embed_eq e)\" by(cases e; auto intro:wf_eq.intros)\nlemma wf_embed_eqs [simp]:\"wf_eqs arity (map embed_eq l)\"\nproof(rule wf_eqs.intros)\nqed simp\nlemma \"embed_eq_eq_from_embed\" [simp]: \"wf_eq arity e \\<Longrightarrow> embed_eq (eq_from_embed e) = e\"\nproof(cases e)\n  case (Pair a b)\n  assume \"wf_eq arity e\"\n  then have x:\"wf_eq arity (a, b)\" by(simp add:Pair)\n  then have \"wf_term arity a\" by(cases rule:wf_eq.cases; auto)\n  moreover from x have \"wf_term arity b\" by(cases rule:wf_eq.cases; auto)\n  ultimately show \"embed_eq (eq_from_embed e) = e\"\n    by(auto simp add:Pair)\nqed\nlemma \"eq_from_embed_embed_eq\" [simp]: \"eq_from_embed (embed_eq e) = e\"\n  by(cases e;auto)\n\n(* unifies *)\ndefinition unifies_msg :: \"subst_msg \\<Rightarrow> eq_msg \\<Rightarrow> bool\" where\n  \"unifies_msg s eq = unifies (embed_subst s) (embed_eq eq)\"\n\n(* unifiess *)\ndefinition unifiess_msg :: \"subst_msg \\<Rightarrow> eq_msg list \\<Rightarrow> bool\" where\n  \"unifiess_msg s eqs = unifiess (embed_subst s) (map embed_eq eqs)\"\n\nlemma unifiess_msgE: \"unifiess_msg s eqs \\<Longrightarrow> ((\\<And> eq. eq \\<in> set eqs \\<Longrightarrow> unifies_msg s eq) \\<Longrightarrow> P) \\<Longrightarrow> P\"\n  by(auto simp add:unifies_msg_def unifiess_msg_def unifiess_def)\n\nlemma unifies_msgE: \"unifies_msg s (a, b) \\<Longrightarrow> (sapply_msg s a = sapply_msg s b \\<Longrightarrow> P) \\<Longrightarrow> P\"\n  apply(simp add:unifies_msg_def)\n  apply(cases rule:unifies.cases)\n   apply(auto simp add:sapply_msg_def)\n  done\n\n(* unify *)\nfun bind:: \"('a\\<Rightarrow>'b) \\<Rightarrow> 'a option \\<Rightarrow> 'b option\" where\n\"bind f x = (case x of None \\<Rightarrow> None | (Some x) \\<Rightarrow> Some (f x))\"\n\ndefinition unify_msg :: \"eq_msg list \\<Rightarrow> subst_msg option\" where\n\"unify_msg eqs = bind subst_from_embed (unify (map embed_eq eqs))\"\n\n\n(* (e) *)\nlemma unify_msg_return: \"unify_msg l = Some \\<sigma> \\<Longrightarrow> unifiess_msg \\<sigma> l\"\nproof -\n  let ?s=\"map embed_eq l\"\n  assume returns:\"unify_msg l = Some \\<sigma>\"\n(* first we need to show that x is well formed *)\n  then obtain x where xdef:\"unify ?s = Some x\" and sigmadef:\"\\<sigma> = subst_from_embed x\"\n    by(auto simp add:unify_msg_def unifiess_msg_def split:option.split_asm)\n  have \"wf_eqs arity ?s\" \n    by(auto intro!:wf_eqs.intros wf_eq.intros)\n  from xdef and this have \"wf_subst arity x\" by(rule wf_subst_unify)\n(* now we can use the embedding easily *)\n  show ?thesis\n    apply(auto simp add:unify_msg_def xdef sigmadef unifiess_msg_def)\n    apply(rule unify_return)\n  apply(simp only:xdef `wf_subst arity x` embed_subst_from_embed)\n    done\nqed\n\n(* (f) *)\nfun fv_eq_msg:: \"eq_msg \\<Rightarrow> var set\" where\n\"fv_eq_msg (a, b) = fv_msg a \\<union> fv_msg b\"\ndefinition fv_eqs_msg:: \"eq_msg list \\<Rightarrow> var set\" where\n\"fv_eqs_msg l = fv_eqs (map embed_eq l)\"\n\nlemma fv_eqs_msg_fv_msg: \"fv_eqs_msg l = (\\<Union> x \\<in> set l. fv_eq_msg x)\"\n  by(auto simp add:fv_eqs_msg_def fv_msg_def)\n\nfun sapply_eq_msg:: \"subst_msg \\<Rightarrow> eq_msg \\<Rightarrow> eq_msg\" where\n\"sapply_eq_msg s (a, b) = (sapply_msg s a, sapply_msg s b)\"\ndefinition sapply_eqs_msg:: \"subst_msg \\<Rightarrow> eq_msg list \\<Rightarrow> eq_msg list\" where\n\"sapply_eqs_msg s l = map eq_from_embed (sapply_eqs (embed_subst s) (map embed_eq l))\"\n\nlemma \"sapply_eqs_msg s l = map (sapply_eq_msg s) l\"\n  by(auto simp add:sapply_eqs_msg_def sapply_msg_def)\n\ndefinition sdom_msg:: \"subst_msg \\<Rightarrow> var set\" where\n\"sdom_msg s = sdom (embed_subst s)\"\ndefinition sran_msg:: \"subst_msg \\<Rightarrow> msg set\" where\n\"sran_msg s = image msg_of_term (sran (embed_subst s))\"\ndefinition svran_msg:: \"subst_msg \\<Rightarrow> var set\" where\n\"svran_msg s = svran (embed_subst s)\"\n\nlemma sdom_msgI: \"s x \\<noteq> Variable x \\<Longrightarrow> x \\<in> sdom_msg s\"\n    by(cases \"s x\")(auto simp add:sdom_msg_def sdom_def embed_subst_def embed_def)\nlemma sdom_msg_def_real: \"sdom_msg s = {x.  s x \\<noteq> Variable x}\"\nproof(rule equalityI)\n  show \"sdom_msg s \\<subseteq> {x. s x \\<noteq> Variable x}\"\n    by(auto simp add:sdom_msg_def sdom_def embed_subst_def embed_def intro:sdom_msgI)\nnext\n  show \"{x. s x \\<noteq> Variable x} \\<subseteq> sdom_msg s\"\n    by(auto intro:sdom_msgI)\nqed\n\nlemma embed_neg_inj:\"embed x \\<noteq> embed y \\<Longrightarrow> x \\<noteq> y\"\n  by(auto)\n\nlemma sran_msg_def_real:  \"sran_msg s = {s x | x. x \\<in> sdom_msg s}\"\nproof(rule equalityI;rule subsetI)\n  fix x\n  assume \"x \\<in> sran_msg s\"\n  then obtain v where dom:\"v\\<in>sdom_msg s\" and xdef:\"embed x = (embed_subst s) v\" by(auto simp add:sran_def sdom_msg_def sran_msg_def)\n\n  from xdef have \"msg_of_term (embed x)=msg_of_term ((embed_subst s) v)\" by(simp)\n  then have \"x=s v\" by(simp add:embed_subst_def)\n\n  from this and dom show \"x \\<in> {s x |x. x \\<in> sdom_msg s}\" by(auto)\nnext\n  fix t\n  assume \"t \\<in> {s x |x. x \\<in> sdom_msg s}\"\n  then obtain x where tdef:\"t=s x\" and dom:\"x \\<in> sdom_msg s\" by(auto)\n  from dom have \"x \\<in> sdom (embed_subst s)\" by(simp add: sdom_msg_def)\n  moreover from tdef have \"t = msg_of_term ((embed_subst s) x)\" by(simp add:embed_subst_def)\n  ultimately show \"t \\<in> sran_msg s\"\n    by(auto simp add:sran_msg_def sran_def)\nqed\n\nlemma wf_term_sran[simp]:\"wf_subst arity s \\<Longrightarrow> x\\<in>sran s \\<Longrightarrow> wf_term arity x\"\n  by(auto simp add:sran_def wf_subst.simps)\n\nlemma svran_msg_def_real: \"svran_msg s = (\\<Union> t \\<in> sran_msg s. fv_msg t)\"\nproof(rule equalityI;rule subsetI)\n  fix x\n  assume \"x \\<in> svran_msg s\"\n  then obtain t where xdef:\"x \\<in> fv t\" and tdef:\"t \\<in> sran (embed_subst s)\"by(auto simp add:svran_msg_def svran_def)\n  have \"wf_subst arity (embed_subst s)\" by simp\n  from this and tdef have \"wf_term arity t\" by(rule wf_term_sran)\n  from this and xdef and tdef have \"x \\<in> fv_msg (msg_of_term t)\" and \"msg_of_term t \\<in> sran_msg s\"\n    by(auto simp add:sran_msg_def fv_msg_def)\n  then show \"x \\<in> (\\<Union> t \\<in> sran_msg s. fv_msg t)\" by auto\nnext\n  fix x\n  assume \"x\\<in>(\\<Union> t \\<in> sran_msg s. fv_msg t)\"\n  then obtain t where tdef:\"t\\<in> (sran_msg s)\" and xdef:\"x \\<in> fv(embed t)\" by(auto simp add:fv_msg_def) \n  from tdef have \"embed t \\<in> sran (embed_subst s)\" by(auto simp add:sran_msg_def sran_def)\n  from this and xdef show \"x \\<in> svran_msg s\" by(auto simp add:svran_msg_def svran_def)\nqed\n\nlemma sdom_msg_simp: \"sdom_msg (Variable(x:=Const y)) = {x}\" (is \"sdom_msg ?s = _\")\n  by(auto simp add:sdom_msg_def_real)\n\nlemma fv_sapply_sdom_svran_msg: \"fv_msg (sapply_msg s t) \\<subseteq> ((fv_msg t) - (sdom_msg s)) \\<union> (svran_msg s)\"\n(is \"?lhs \\<subseteq> ?rhs\")\nproof(rule subsetI)\n  fix x\n  let ?s = \"embed_subst s\"\n  let ?t = \"embed t\"\n  assume \"x \\<in> fv_msg (sapply_msg s t)\"\n  then have \"x \\<in> fv (?s \\<cdot> ?t)\"\n    by(simp add:sdom_msg_def sapply_msg_def svran_msg_def fv_msg_def wf_term_sapply)\n  then have \"x \\<in> (fv (Term.embed t) - sdom (embed_subst s)) \\<union> svran (embed_subst s)\"\n    by(rule fv_sapply_sdom_svran)\n  then show \"x \\<in> ?rhs\" \n    by(simp add:sdom_msg_def sapply_msg_def svran_msg_def fv_msg_def wf_term_sapply)\nqed\n\nlemma l3_msg:\n  fixes \\<sigma> :: \"subst_msg\" \n    and l :: \"eq_msg list\"\n  assumes \"unify_msg l = Some s\"\n  shows \"fv_eqs_msg (sapply_eqs_msg s l) \\<subseteq> fv_eqs_msg l\"\n    and \"sdom_msg s \\<subseteq> fv_eqs_msg l\"\n    and \"svran_msg s \\<subseteq> fv_eqs_msg l\"\n    and \"sdom_msg s \\<inter> svran_msg s = {}\"\nproof -\n  let ?l' = \"map embed_eq l\"\n  from assms obtain s'\n    where return:\"unify ?l' = Some s'\" and sdef:\"s = subst_from_embed s'\"\n    by(auto simp add:unify_msg_def sdom_msg_def split:option.split_asm)\n  have wf:\"wf_eqs arity ?l'\" by simp\n  from return  and this have wfs:\"wf_subst arity s'\" by(rule wf_subst_unify)\n\n(* goal 1*)\n  from return have \"fv_eqs (sapply_eqs s' ?l') \\<subseteq> fv_eqs ?l'\" by(rule 3)\n  then  show  \"fv_eqs_msg (sapply_eqs_msg s l) \\<subseteq> fv_eqs_msg l\"\n    by(simp add:sapply_eqs_msg_def wf_eq_sapply_eq fv_eqs_msg_def sdef wf wfs)\n(*goal 2*)\n  from return have \"sdom s' \\<subseteq> fv_eqs ?l'\" by(rule 3)\n  then show \"sdom_msg s \\<subseteq> fv_eqs_msg l\"\n    by(simp add:sdom_msg_def fv_eqs_msg_def sdef wfs)\n\n(* goal 3*)\n  from return have \"svran s' \\<subseteq> fv_eqs ?l'\" by(rule 3)\n  then show \"svran_msg s \\<subseteq> fv_eqs_msg l\"\n    by(simp add:svran_msg_def fv_eqs_msg_def sdef wfs)\n      (*goal 4*)\n  from return have \"sdom s' \\<inter> svran s' = {}\" by(rule 3)\n  then show \"sdom_msg s \\<inter> svran_msg s = {}\"\n    by(simp add:sdom_msg_def svran_msg_def fv_eqs_msg_def sdef wfs)\nqed\n\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/Term.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951025545426, "lm_q2_score": 0.8311430520409023, "lm_q1q2_score": 0.7013975511395528}}
{"text": "section \\<open>The watchdog module\\<close>\n\ntheory Watchdog\n  imports Main\nbegin\n\ntext \\<open>The watchdog chain is given by a list of scheduled events,\n  each event is specified by an event code, and the time it should be\n  triggered, which is the number of ticks *after* the previous event is\n  triggered.\n\n  For example, the following watchdog chain:\n\n  [(1, 10), (1, 5), (2, 0), (1, 0), (3, 5)]\n\n  means trigger event 1 after 10 ticks, trigger event 1 (again) after another\n  5 ticks, followed immediately by event 2 and event 1. Finally, trigger\n  event 3 after 5 ticks after that.\n\\<close>\n\ntype_synonym task_id = nat\n\ntype_synonym watchdog_chain = \"(task_id \\<times> nat) list\"\n\nsubsection \\<open>Event time\\<close>\n\ntext \\<open>The watchdog should satisfy the property that:\n\n  If an event (e, n) is inserted, then the event e should be triggered\n  after exactly n ticks (the output after the nth tick should include e).\n  \n  Assume that for each event e, there is at most one entry of the form (e, _)\n  in the chain. Then the chain abstract to a single integer, which is the trigger\n  time for the event.\n\\<close>\nfun event_time :: \"watchdog_chain \\<Rightarrow> task_id \\<Rightarrow> nat option\" where\n  \"event_time [] i = None\"\n| \"event_time (e # es) i =\n   (if fst e = i then Some (snd e)\n    else case event_time es i of None \\<Rightarrow> None | Some k \\<Rightarrow> Some (k + snd e))\"\n\nvalue \"event_time [(1, 5), (2, 5)] 1\"\nvalue \"event_time [(1, 5), (2, 5)] 2\"\nvalue \"event_time [(1, 5), (2, 5)] 3\"\n\ntext \\<open>Count the total time up to a certain index\\<close>\nfun watchdog_total_upto :: \"watchdog_chain \\<Rightarrow> nat \\<Rightarrow> nat\" where\n  \"watchdog_total_upto [] i = 0\"\n| \"watchdog_total_upto ((evt_id, n) # rest) 0 = 0\"\n| \"watchdog_total_upto ((evt_id, n) # rest) (Suc i) = n + watchdog_total_upto rest i\"\n\nvalue \"watchdog_total_upto [(0, 1), (0, 2)] 0\"\nvalue \"watchdog_total_upto [(0, 1), (0, 2)] 1\"\nvalue \"watchdog_total_upto [(0, 1), (0, 2)] 2\"\n\nlemma watchdog_total_upto_0 [simp]:\n  \"watchdog_total_upto s 0 = 0\"\n  apply (cases s) by auto\n\nlemma watchdog_total_upto_Suc:\n  \"i < length s \\<Longrightarrow> watchdog_total_upto s (Suc i) = watchdog_total_upto s i + snd (s ! i)\"\nproof (induct s arbitrary: i)\n  case Nil\n  then show ?case by auto\nnext\n  case (Cons pn tbl)\n  then show ?case\n    apply (cases pn) apply (cases i) by auto\nqed\n\nlemma watchdog_total_upto_take:\n  \"i \\<le> length es \\<Longrightarrow> watchdog_total_upto (take i es) i = watchdog_total_upto es i\"\nproof (induction es arbitrary: i)\n  case Nil\n  then show ?case by auto\nnext\n  case (Cons p es)\n  show ?case\n  proof (cases i)\n    case 0\n    then show ?thesis by auto\n  next\n    case (Suc i')\n    show ?thesis\n    proof (cases p)\n      case (Pair k v)\n      show ?thesis\n        unfolding Pair Suc apply auto\n        apply (rule Cons(1))\n        using Cons(2) Suc by auto\n    qed\n  qed\nqed\n\nlemma event_time_Suc_None:\n  \"event_time (p # es) evt_id = None \\<Longrightarrow> event_time es evt_id = None\"\n  apply auto apply (cases \"fst p = evt_id\") apply auto\n  apply (cases \"event_time es evt_id = None\") by auto\n\nlemma event_time_append1:\n  \"event_time es evt_id = None \\<Longrightarrow>\n   event_time (es @ es2) evt_id = (\n     case event_time es2 evt_id of\n       None \\<Rightarrow> None\n     | Some n \\<Rightarrow> Some (n + watchdog_total_upto es (length es)))\"\nproof (induction es)\n  case Nil\n  show ?case\n    apply (cases \"event_time es2 evt_id\") by auto\nnext\n  case (Cons p es)\n  show ?case\n  proof (cases p)\n    case (Pair k v)\n    have b1: \"k \\<noteq> evt_id\"\n      using Cons(2) unfolding Pair by auto\n    have b2: \"event_time es evt_id = None\"\n      using event_time_Suc_None Cons(2) by auto\n    have b3: \"event_time (es @ es2) evt_id =\n      (case event_time es2 evt_id of\n             None \\<Rightarrow> None \n           | Some n \\<Rightarrow> Some (n + watchdog_total_upto es (length es)))\"\n      using Cons(1) b2 by auto\n    show ?thesis\n      unfolding Pair using b1 b3\n      apply (cases \"event_time es2 evt_id\") by auto\n  qed\nqed\n\nlemma event_time_append2:\n  \"event_time es evt_id = Some n \\<Longrightarrow>\n   event_time (es @ es2) evt_id = Some n\"\nproof (induction es arbitrary: n)\n  case Nil\n  then show ?case by auto\nnext\n  case (Cons p es)\n  show ?case\n  proof (cases p)\n    case (Pair k v)\n    show ?thesis\n    proof (cases \"k = evt_id\")\n      case True\n      then show ?thesis\n        unfolding Pair using Cons.prems Pair by auto\n    next\n      case False\n      have b1: \"event_time es evt_id = Some (n - v)\" \"n \\<ge> v\"\n        using Cons(2) unfolding Pair using False apply auto\n         apply (cases \"event_time es evt_id\") apply auto\n        apply (cases \"event_time es evt_id\") by auto\n      have b2: \"event_time (es @ es2) evt_id = Some (n - v)\"\n        using Cons(1) b1 by auto\n      show ?thesis\n        unfolding Pair by (auto simp add: False b1 b2)\n    qed\n  qed\nqed\n\nlemma event_time_take_None:\n  \"event_time es evt_id = None \\<Longrightarrow> event_time (take i es) evt_id = None\"\nproof (induction es arbitrary: i)\n  case Nil\n  then show ?case by auto\nnext\n  case (Cons p es)\n  show ?case\n  proof (cases i)\n    case 0\n    then show ?thesis by auto\n  next\n    case (Suc i')\n    have a1: \"event_time es evt_id = None\"\n      using Cons(2) event_time_Suc_None by auto\n    have a2: \"event_time (take i' es) evt_id = None\"\n      using a1 Cons(1) by auto\n    show ?thesis\n      unfolding Suc apply (auto simp add: a2)\n      using Cons(2) by auto\n  qed\nqed\n\nlemma event_time_take_Some:\n  assumes \"event_time (take i es) evt_id = Some n\"\n  shows \"event_time es evt_id = Some n\"\nproof -\n  have a1: \"es = (take i es) @ (drop i es)\"\n    by auto\n  show ?thesis\n    apply (subst a1) apply (rule event_time_append2)\n    using assms by auto\nqed\n\nsubsection \\<open>Validity properties\\<close>\n\ntext \\<open>Invariant to be maintained between operations:\n  number of times each event ID appears is at most one.\n\\<close>\nfun occurs_atmost_one :: \"watchdog_chain \\<Rightarrow> task_id \\<Rightarrow> bool\" where\n  \"occurs_atmost_one [] evt_id = True\"\n| \"occurs_atmost_one ((k, v) # es) evt_id = \n    (if k = evt_id then event_time es evt_id = None else occurs_atmost_one es evt_id)\"\n\ntext \\<open>Invariant to be maintained between operations:\n  if watchdog is nonempty, then the first time value is nonzero.\n\\<close>\ndefinition valid_watchdog :: \"watchdog_chain \\<Rightarrow> bool\" where\n  \"valid_watchdog es \\<longleftrightarrow>\n    (length es > 0 \\<longrightarrow> snd (es ! 0) > 0) \\<and>\n    (\\<forall>evt_id. occurs_atmost_one es evt_id)\"\n\nlemma occurs_atmost_one_None:\n  \"event_time es evt_id = None \\<Longrightarrow> occurs_atmost_one es evt_id\"\n  apply (induction es) apply auto\n  subgoal for i n es'\n    apply (cases \"event_time es' evt_id\") by auto\n  done\n\nlemma occurs_atmost_one_Cons:\n  \"occurs_atmost_one (e # es) evt_id \\<Longrightarrow> occurs_atmost_one es evt_id\"\n  apply (cases e) apply auto\n  subgoal for i n\n    apply (cases \"i = evt_id\")\n    by (auto simp add: occurs_atmost_one_None)\n  done\n\nsubsection \\<open>Add position\\<close>\n\ntext \\<open>Preparation for watchdog_add: determine the position to add an event.\\<close>\nfun watchdog_add_pos :: \"watchdog_chain \\<Rightarrow> nat \\<Rightarrow> nat\" where\n  \"watchdog_add_pos [] n = 0\"\n| \"watchdog_add_pos ((ev, k) # rest) n =\n    (if n > k then 1 + watchdog_add_pos rest (n - k)\n     else 0)\"\n\nvalue \"watchdog_add_pos [(0, 1), (0, 2)] 1\"\nvalue \"watchdog_add_pos [(0, 1), (0, 2)] 2\"\nvalue \"watchdog_add_pos [(0, 1), (0, 2)] 4\"\n\nlemma watchdog_add_pos_prop1:\n  \"watchdog_add_pos s n \\<le> length s\"\n  apply (induct s arbitrary: n) by auto\n\nlemma watchdog_add_pos_prop2:\n  \"n > 0 \\<Longrightarrow> watchdog_add_pos s n = length s \\<Longrightarrow> n > watchdog_total_upto s (length s)\"\nproof (induct s arbitrary: n)\n  case Nil\n  then show ?case by auto\nnext\n  case (Cons p s)\n  show ?case\n  proof (cases p)\n    case (Pair ev k)\n    have a1: \"(if k < n then 1 + watchdog_add_pos s (n - k) else 0) = Suc (length s)\"\n      using Cons(3) unfolding Pair by auto\n    have a2: \"k < n\"\n      using a1 by (meson nat.distinct(1))\n    have a3: \"watchdog_add_pos s (n - k) = length s\"\n      using a1 a2 by auto\n    have a4: \"watchdog_total_upto s (length s) < n - k\"\n      using Cons(1) a2 a3 by auto\n    show ?thesis\n      apply (auto simp add: Pair) using a2 a4 by auto \n  qed\nqed\n\nlemma watchdog_add_pos_prop3:\n  \"n > 0 \\<Longrightarrow> watchdog_add_pos s n < length s \\<Longrightarrow>\n   n \\<le> watchdog_total_upto s (Suc (watchdog_add_pos s n)) \\<and>\n   n > watchdog_total_upto s (watchdog_add_pos s n)\"\nproof (induct s arbitrary: n)\n  case Nil\n  then show ?case by auto\nnext\n  case (Cons p rest)\n  show ?case\n  proof (cases p)\n    case (Pair ev k)\n    show ?thesis\n      apply (auto simp add: Pair)\n        apply (smt Cons.hyps Cons.prems(2) One_nat_def Pair add.commute le_add_diff_inverse\n                   le_neq_implies_less less_imp_le_nat list.size(4) nat_add_left_cancel_le\n                   nat_neq_iff watchdog_add_pos.simps(2) zero_less_diff)\n       apply (metis Cons.hyps le_add_diff_inverse le_neq_implies_less less_imp_le_nat\n                   nat_add_left_cancel_less watchdog_add_pos_prop1 watchdog_add_pos_prop2 zero_less_diff)\n      by (simp add: Cons.prems(1))\n  qed\nqed\n\nlemma watchdog_add_fun_range:\n  \"n > 0 \\<Longrightarrow> i < Suc (watchdog_add_pos s n) \\<Longrightarrow> n > watchdog_total_upto s i \\<and> i \\<le> length s\"\nproof (induct s arbitrary: i n)\n  case Nil\n  then show ?case by auto\nnext\n  case (Cons p s)\n  show ?case\n  proof (cases p)\n    case (Pair ev k)\n    have a1: \"i < Suc (if k < n then 1 + watchdog_add_pos s (n - k) else 0)\"\n      using Cons(3) by (auto simp add: Pair)\n    show ?thesis\n    proof (cases i)\n      case 0\n      then show ?thesis\n        by (auto simp add: Pair Cons)\n    next\n      case (Suc i')\n      have a2: \"k < n\"\n        using a1 Suc less_one by fastforce\n      have a3: \"i < Suc (1 + watchdog_add_pos s (n - k))\"\n        using a1 a2 by auto\n      have b1: \"i' < Suc (watchdog_add_pos s (n - k))\"\n        using a3 Suc by auto\n      have b2: \"watchdog_total_upto s i' < n - k \\<and> i' \\<le> length s\"\n        using Cons(1)[of \"n - k\" i'] b1 a2 by auto\n      show ?thesis\n        apply (auto simp add: Pair Suc)\n        using b2 by auto\n    qed      \n  qed\nqed\n\nlemma watchdog_add_fun_range2:\n  \"n > 0 \\<Longrightarrow> i = Suc (watchdog_add_pos s n) \\<Longrightarrow>\n   (n > watchdog_total_upto s (length s) \\<and> i = Suc (length s)) \\<or>\n   (n \\<le> watchdog_total_upto s i \\<and> n > watchdog_total_upto s (watchdog_add_pos s n) \\<and> i \\<le> length s)\"\nproof (induct s arbitrary: i n)\n  case Nil\n  then show ?case by auto\nnext\n  case (Cons p s)\n  show ?case\n  proof (cases p)\n    case (Pair ev k)\n    have a1: \"i = Suc (if k < n then 1 + watchdog_add_pos s (n - k) else 0)\"\n      using Cons(3) by (auto simp add: Pair)\n    show ?thesis\n    proof (cases i)\n      case 0\n      then show ?thesis using a1 by auto\n    next\n      case (Suc i')\n      have b1: \"i' = (if k < n then 1 + watchdog_add_pos s (n - k) else 0)\"\n        using a1 Suc by auto\n      show ?thesis\n      proof (cases i')\n        case 0\n        have \"k \\<ge> n\"\n          using b1 0 not_le by fastforce\n        then show ?thesis\n          by (metis 0 Cons.prems(1,2) Suc_inject Suc_leI length_Cons Suc watchdog_add_pos_prop3 zero_less_Suc)\n      next\n        case (Suc i2)\n        have c1: \"k < n\"\n          using b1 Suc by (meson nat.distinct(1))\n        have c2: \"i' = Suc (watchdog_add_pos s (n - k))\"\n          using b1 c1 by auto\n        have c3: \"watchdog_total_upto s (length s) < n - k \\<and> i' = Suc (length s) \\<or> n - k \\<le> watchdog_total_upto s i' \\<and> i' \\<le> length s\"\n          using Cons(1)[of \"n - k\" i'] c1 c2 by auto\n        have c4: \"k + watchdog_total_upto s (length s) < n \\<longleftrightarrow> watchdog_total_upto s (length s) < n - k\"\n          using c1 by auto\n        have c5: \"i = Suc (Suc (length s)) \\<longleftrightarrow> i' = Suc (length s)\"\n          using \\<open>i = Suc i'\\<close> by auto\n        show ?thesis\n          apply (auto simp add: c4 c5)\n             apply (metis (mono_tags, lifting) Cons.prems(1) Cons.prems(2) Pair Suc_inject a1 c1 c2 c3 c4\n              le_imp_less_Suc length_Cons plus_1_eq_Suc watchdog_add_pos_prop3 watchdog_total_upto.simps(3))\n          using Cons.prems(2) a1 c1 c2 c3 watchdog_add_pos_prop3 apply auto[1]\n           apply (simp add: Cons.prems(1) Cons.prems(2) watchdog_add_fun_range)\n            apply (metis Cons.prems(1) Cons.prems(2) not_le watchdog_add_fun_range)\n          using Cons.prems(1) watchdog_add_fun_range apply blast\n          using a1 c2 c3 plus_1_eq_Suc by auto\n      qed\n    qed\n  qed\nqed\n\nsubsection \\<open>Add function\\<close>\n\ntext \\<open>Add the given event to the chain. This requires modifying the event\n  immediately after the added event. For example, adding (1, 7) to the\n  chain [(1, 5), (1, 5)] yields [(1, 5), (1, 2), (1, 3)].\n\n  Note events are triggered in the first-in-first-out (FIFO) order.\n  For example, if the current chain is:\n\n  [(1, 10), (1, 5), (2, 0), (3, 5)],\n\n  then the new event (1, 15) should be added after (2, 0).\n\\<close>\nfun watchdog_add :: \"task_id \\<Rightarrow> nat \\<Rightarrow> watchdog_chain \\<Rightarrow> watchdog_chain\" where\n  \"watchdog_add evt_id n [] = [(evt_id, n)]\"\n| \"watchdog_add evt_id n ((k, v) # es) =\n    (if n > v then\n       (k, v) # watchdog_add evt_id (n - v) es\n     else\n       (evt_id, n) # (k, v - n) # es)\"\n\nvalue \"watchdog_add 1 15 [(1, 10), (1, 5), (2, 0), (3, 5)]\"\nvalue \"watchdog_add 1 17 [(1, 10), (1, 5), (2, 0), (3, 5)]\"\n\ntheorem watchdog_add_prop1:\n  \"n > watchdog_total_upto es (length es) \\<Longrightarrow>\n   watchdog_add evt_id n es = es @ [(evt_id, n - watchdog_total_upto es (length es))]\"\nproof (induction es arbitrary: n)\n  case Nil\n  then show ?case by auto\nnext\n  case (Cons e es)\n  show ?case\n  proof (cases e)\n    case (Pair k v)\n    have a1: \"v < n\"\n      using Cons(2) unfolding Pair by auto\n    have a2: \"watchdog_total_upto es (length es) < n - v\"\n      using Cons(2) unfolding Pair by auto\n    have a3: \"watchdog_add evt_id (n - v) es = es @ [(evt_id, n - v - watchdog_total_upto es (length es))]\"\n      using Cons(1) a2 by auto\n    show ?thesis\n      unfolding Pair using a1 a3 by auto\n  qed\nqed\n\ntheorem watchdog_add_prop2:\n  \"n > 0 \\<Longrightarrow> i < length es \\<Longrightarrow>\n   i = watchdog_add_pos es n \\<Longrightarrow> \n   watchdog_add evt_id n es =\n    (take i es) @ [(evt_id, n - watchdog_total_upto es i)] @\n    (drop i (es[i := (fst (es ! i), snd (es ! i) - (n - watchdog_total_upto es i))]))\"\nproof (induction es arbitrary: i n)\n  case Nil\n  then show ?case by auto\nnext\n  case (Cons e es)\n  show ?case\n  proof (cases e)\n    case (Pair k v)\n    show ?thesis\n    proof (cases i)\n      case 0\n      have \"v \\<ge> n\"\n        using Cons(4) unfolding Pair 0\n        using Cons.prems(3) Pair less_Suc_eq_0_disj old.prod.exhaust by fastforce\n      then show ?thesis unfolding Pair 0 by auto\n    next\n      case (Suc i')\n      show ?thesis\n      proof (cases \"v < n\")\n        case True\n        have a1: \"n - v > 0\"\n          using True by auto\n        have a2: \"i' < length es\"\n          using Cons(3) Suc by auto\n        have a3: \"i' = watchdog_add_pos es (n - v)\"\n          using Cons(4) unfolding Pair using True Suc by auto\n        have a4: \"watchdog_add evt_id (n - v) es = take i' es @\n                    [(evt_id, (n - v) - watchdog_total_upto es i')] @\n                    drop i' (es[i' := (fst (es ! i'), snd (es ! i') - ((n - v) - watchdog_total_upto es i'))])\"\n          using Cons(1)[OF a1 a2 a3] by auto\n        show ?thesis\n          by (simp add: Pair True a4 local.Suc)\n      next\n        case False\n        then show ?thesis\n          by (simp add: Cons.prems(3) Pair)\n      qed\n    qed\n  qed\nqed\n\ntheorem watchdog_add1:\n  assumes \"event_time es evt_id = None\"\n    and \"n > 0\"\n  shows \"event_time (watchdog_add evt_id n es) evt_id = Some n\"\nproof -\n  let ?i=\"watchdog_add_pos es n\"\n  have a1: \"(n > watchdog_total_upto es (length es) \\<and> Suc ?i = Suc (length es)) \\<or>\n            (n \\<le> watchdog_total_upto es (Suc ?i) \\<and> n > watchdog_total_upto es ?i \\<and> Suc ?i \\<le> length es)\"\n    using watchdog_add_fun_range2 assms by auto\n  have a2: ?thesis\n    if \"watchdog_total_upto es (length es) < n\" \"Suc ?i = Suc (length es)\"\n    unfolding watchdog_add_prop1[OF that(1)]\n    using assms(1) that(1) event_time_append1 by auto\n  have a3: ?thesis\n    if \"n \\<le> watchdog_total_upto es (Suc ?i)\" \"n > watchdog_total_upto es ?i\" \"Suc ?i \\<le> length es\"\n  proof -\n    have b1: \"?i < length es\"\n      using that(3) by auto\n    have b2: \"watchdog_add evt_id n es = take ?i es @\n              [(evt_id, n - watchdog_total_upto es ?i)] @\n              drop ?i (es[?i := (fst (es ! ?i), snd (es ! ?i) - (n - watchdog_total_upto es ?i))])\"\n      using watchdog_add_prop2[OF assms(2) b1] by auto\n    have b3: \"event_time (take ?i es) evt_id = None\"\n      using event_time_take_None assms(1) by auto\n    have b4: \"watchdog_total_upto (take ?i es) (length (take ?i es)) = watchdog_total_upto es ?i\"\n      by (metis b1 leD length_take less_or_eq_imp_le min_def watchdog_total_upto_take)\n    show ?thesis\n      unfolding b2 using event_time_append1[OF b3]\n      unfolding b4 using that(2) by auto\n  qed\n  show ?thesis\n    using a1 a2 a3 by auto\nqed\n\nlemma event_time_decr0_None:\n  assumes \"event_time es evt_id = None\"\n    and \"length es > 0\"\n  shows \"event_time (es[0 := (fst (es ! 0), snd (es ! 0) - k)]) evt_id = None\"\nproof (cases es)\n  case Nil\n  then show ?thesis by auto\nnext\n  case (Cons p es')\n  show ?thesis\n  proof (cases p)\n    case (Pair k v)\n    have a1: \"k \\<noteq> evt_id\" \"event_time es' evt_id = None\"\n      using assms unfolding Cons Pair\n      using event_time_Suc_None by auto\n    show ?thesis\n      unfolding Cons Pair by (auto simp add: a1)\n  qed\nqed\n\nlemma event_time_decr0_Some:\n  assumes \"event_time es evt_id = Some a\"\n    and \"length es > 0\"\n    and \"k \\<le> snd (es ! 0)\"\n  shows \"event_time (es[0 := (fst (es ! 0), snd (es ! 0) - k)]) evt_id = Some (a - k)\"\nproof (cases es)\n  case Nil\n  then show ?thesis using assms(2) by auto\nnext\n  case (Cons p es')\n  show ?thesis\n  proof (cases p)\n    case (Pair k v)\n    show ?thesis\n    proof (cases \"k = evt_id\")\n      case True\n      have \"v = a\"\n        using assms(1) unfolding Cons Pair True by auto\n      then show ?thesis\n        unfolding Pair Cons True by auto\n    next\n      case False\n      have \"event_time es' evt_id = Some (a - v)\" \"a \\<ge> v\"\n        using assms(1) unfolding Cons Pair using False apply auto\n         apply (cases \"event_time es' evt_id\") apply auto\n        apply (cases \"event_time es' evt_id\") by auto\n      then show ?thesis\n        unfolding Pair Cons using False assms(3)\n        by (simp add: Pair local.Cons)\n    qed\n  qed\nqed\n\nlemma watchdog_add2_helper1:\n  assumes \"i < length es\"\n    and \"event_time (drop i es) evt_id = None\"\n  shows \"event_time (drop i (es[i := (fst (es ! i), snd (es ! i) - k)])) evt_id = None\"\nproof -\n  let ?es'=\"drop i es\"\n  have a1: \"drop i (es[i := (fst (es ! i), snd (es ! i) - k)]) =\n            ?es'[0 := (fst (?es' ! 0), snd (?es' ! 0) - k)]\"\n    by (simp add: assms(1) drop_update_swap le_eq_less_or_eq)\n  show ?thesis\n    unfolding a1\n    apply (rule event_time_decr0_None)\n    using assms by auto\nqed\n\nlemma watchdog_add2_helper2:\n  assumes \"i < length es\"\n    and \"event_time (drop i es) evt_id = Some a\"\n    and \"k \\<le> snd (es ! i)\"\n  shows \"event_time (drop i (es[i := (fst (es ! i), snd (es ! i) - k)])) evt_id = Some (a - k)\"\nproof -\n  let ?es'=\"drop i es\"\n  have a1: \"drop i (es[i := (fst (es ! i), snd (es ! i) - k)]) =\n            ?es'[0 := (fst (?es' ! 0), snd (?es' ! 0) - k)]\"\n    by (simp add: assms(1) drop_update_swap le_eq_less_or_eq)\n  show ?thesis\n    unfolding a1\n    apply (rule event_time_decr0_Some)\n    using assms by auto\nqed\n\ntheorem watchdog_add2:\n  assumes \"evt_id \\<noteq> evt_id2\"\n    and \"n > 0\"\n  shows \"event_time (watchdog_add evt_id n es) evt_id2 = event_time es evt_id2\"\nproof -\n  let ?i=\"watchdog_add_pos es n\"\n  have a1: \"(n > watchdog_total_upto es (length es) \\<and> Suc ?i = Suc (length es)) \\<or>\n            (n \\<le> watchdog_total_upto es (Suc ?i) \\<and> n > watchdog_total_upto es ?i \\<and> Suc ?i \\<le> length es)\"\n    using watchdog_add_fun_range2 assms by auto\n  have a2: ?thesis\n    if \"n > watchdog_total_upto es (length es)\" \"Suc ?i = Suc (length es)\"\n    unfolding watchdog_add_prop1[OF that(1)]\n    apply (cases \"event_time es evt_id2 = None\")\n    by (auto simp add: event_time_append1 event_time_append2 assms)\n  have a3: ?thesis\n    if \"n \\<le> watchdog_total_upto es (Suc ?i)\" \"n > watchdog_total_upto es ?i\" \"Suc ?i \\<le> length es\"\n  proof -\n    have b1: \"?i < length es\"\n      using that(3) by auto\n    have b2: \"watchdog_add evt_id n es = take ?i es @\n                [(evt_id, n - watchdog_total_upto es ?i)] @\n                drop ?i (es[?i := (fst (es ! ?i), snd (es ! ?i) - (n - watchdog_total_upto es ?i))])\"\n      using watchdog_add_prop2[OF assms(2) b1] by auto\n    show ?thesis\n    proof (cases \"event_time (take ?i es) evt_id2\")\n      case None\n      note None1 = None\n      show ?thesis\n      proof (cases \"event_time (drop ?i es) evt_id2\")\n        case None\n        have c1: \"event_time (drop ?i (es[?i := (fst (es ! ?i), snd (es ! ?i) - k)])) evt_id2 = None\" for k\n          by (rule watchdog_add2_helper1[OF b1 None])\n        have c2: \"es = take ?i es @ drop ?i es\"\n          by auto\n        have c3: \"event_time es evt_id2 = None\"\n          apply (subst c2) apply (subst event_time_append1[OF None1])\n          by (auto simp add: None)\n        show ?thesis\n          unfolding b2 event_time_append1[OF None1]\n          by (auto simp add: assms(1) c1 c3)\n      next\n        case (Some a)\n        have ineq: \"n - watchdog_total_upto es ?i \\<le> snd (es ! ?i)\"\n          using that(1) unfolding watchdog_total_upto_Suc[OF b1]\n          by auto\n        have ineq2: \"a \\<ge> n - watchdog_total_upto es ?i\"\n        proof -\n          have c1: \"drop ?i es = (es ! ?i) # drop (?i + 1) es\"\n            using b1 by (simp add: Cons_nth_drop_Suc)\n          have \"a \\<ge> snd (es ! ?i)\"\n            using Some(1) unfolding c1 apply auto\n            apply (cases \"fst (es ! ?i) = evt_id2\") apply auto\n            apply (cases \"event_time (drop (Suc ?i) es) evt_id2\") by auto\n          then show ?thesis\n            using ineq by auto\n        qed\n        have c1: \"event_time (drop ?i (es[?i := (fst (es ! ?i), snd (es ! ?i) - k)])) evt_id2 = Some (a - k)\"\n          if \"k \\<le> snd (es ! ?i)\" for k\n          by (rule watchdog_add2_helper2[OF b1 Some that])\n        have c2: \"es = take ?i es @ drop ?i es\"\n          by auto\n        have c3: \"watchdog_total_upto (take ?i es) (min (length es) ?i) = watchdog_total_upto es ?i\"\n          by (simp add: min.absorb2 watchdog_add_pos_prop1 watchdog_total_upto_take)\n        have c4: \"event_time es evt_id2 = Some (a + watchdog_total_upto es ?i)\"\n          apply (subst c2) apply (subst event_time_append1[OF None1])\n          by (auto simp add: Some c3)\n        show ?thesis\n          unfolding b2 event_time_append1[OF None1]\n          apply (auto simp add: assms(1) c1[OF ineq] c3 c4)\n          using ineq2 by auto\n      qed        \n    next\n      case (Some a)\n      show ?thesis\n        unfolding b2 event_time_append2[OF Some]\n        using event_time_take_Some[OF Some] by auto\n    qed\n  qed\n  show ?thesis\n    using a1 a2 a3 by auto\nqed\n\nlemma watchdog_add_full:\n  assumes \"event_time es evt_id = None\"\n    and \"n > 0\"\n  shows \"event_time (watchdog_add evt_id n es) = event_time es(evt_id \\<mapsto> n)\"\n  apply (rule ext)\n  subgoal for evt_id'\n    apply auto\n     apply (rule watchdog_add1[OF assms])\n    apply (rule watchdog_add2)\n    using assms(2) by auto\n  done\n\nlemma watchdog_add_valid:\n  assumes \"event_time es evt_id = None\"\n    and \"n > 0\"\n    and \"valid_watchdog es\"\n  shows \"valid_watchdog (watchdog_add evt_id n es)\"\nproof -\n  have a: \"\\<forall>i. occurs_atmost_one es i \\<Longrightarrow> event_time es evt_id = None \\<Longrightarrow>\n           occurs_atmost_one (watchdog_add evt_id n es) evt_id'\" for evt_id'\n  proof (induction es arbitrary: n)\n    case Nil\n    then show ?case by auto\n  next\n    case (Cons pair es')\n    show ?case\n    proof (cases pair)\n      case (Pair p n')\n      have a1: \"\\<forall>a. occurs_atmost_one es' a\"\n        using Cons.prems(1) occurs_atmost_one_Cons by blast\n      have a2: \"event_time es' evt_id = None\"\n        using Cons.prems(2) event_time_Suc_None by auto\n      have a3: \"occurs_atmost_one (watchdog_add evt_id n'' es') evt_id'\" for n''\n        using Cons(1) a1 a2 by auto\n      show ?thesis\n        unfolding Pair watchdog_add.simps\n        apply (cases \"n' < n\")\n        subgoal apply (auto simp add: a3)\n          by (metis Cons(2,3) Pair event_time.simps(2) fst_conv occurs_atmost_one.simps(2)\n                    option.distinct(1) watchdog_add2 zero_less_diff)\n        subgoal apply auto\n          using Cons.prems(2) Pair apply auto[1]\n          using Cons.prems(1) Pair apply auto[1]\n          apply (cases \"event_time es' evt_id'\")\n          using Cons Pair by auto\n        done\n    qed\n  qed\n  show ?thesis\n    unfolding valid_watchdog_def\n    apply auto\n    subgoal\n      apply (cases es)\n      using assms(3) by (auto simp add: valid_watchdog_def assms(2))\n    subgoal for evt_id'\n      using a assms by (auto simp add: valid_watchdog_def)\n    done\nqed\n\nsubsection \\<open>Extract zero function\\<close>\n\ntext \\<open>Extract zero from head of watchdog chain. Helper function for watchdog_tick\\<close>\nfun extract_zero :: \"watchdog_chain \\<Rightarrow> task_id list \\<times> watchdog_chain\" where\n  \"extract_zero [] = ([], [])\"\n| \"extract_zero (e # es) =\n   (if snd e = 0 then\n      let (out_es, es') = extract_zero es in\n      (fst e # out_es, es')\n    else\n      ([], e # es))\"\n\nvalue \"extract_zero [(0, 10), (1, 5)]\"\nvalue \"extract_zero [(1, 0), (0, 10), (1, 5)]\"\nvalue \"extract_zero [(1, 0), (2, 0), (0, 10), (1, 0)]\"\n\nlemma extract_zero_None:\n  \"event_time es evt_id = None \\<Longrightarrow>\n   evt_id \\<notin> set (fst (extract_zero es)) \\<and> event_time (snd (extract_zero es)) evt_id = None\"\nproof (induction es)\n  case Nil\n  then show ?case by auto\nnext\n  case (Cons p es)\n  show ?case\n  proof (cases p)\n    case (Pair k v)\n    have a1: \"k \\<noteq> evt_id\"\n      using Cons(2) unfolding Pair by auto\n    have a2: \"event_time es evt_id = None\"\n      using event_time_Suc_None[OF Cons(2)] by auto\n    have a3: \"evt_id \\<notin> set (fst (extract_zero es))\" \"event_time (snd (extract_zero es)) evt_id = None\"\n      using a2 Cons(1) by auto\n    show ?thesis\n      unfolding Pair using a1 Cons(1) apply (auto simp add: a2)\n       apply (cases \"extract_zero es\") using a3 apply auto\n      apply (cases \"extract_zero es\") by auto\n  qed\nqed\n\nlemma extract_zero1:\n  \"occurs_atmost_one es evt_id \\<Longrightarrow>\n   event_time es evt_id = Some 0 \\<Longrightarrow>\n   evt_id \\<in> set (fst (extract_zero es)) \\<and> event_time (snd (extract_zero es)) evt_id = None\"\nproof (induction es)\n  case Nil\n  then show ?case by auto\nnext\n  case (Cons p es)\n  show ?case\n  proof (cases p)\n    case (Pair k v)\n    have \"v = 0\"\n      using Cons(3) unfolding Pair apply auto\n      apply (cases \"k = evt_id\") apply auto\n      apply (cases \"event_time es evt_id\") by auto \n    show ?thesis\n    proof (cases \"k = evt_id\")\n      case True\n      have a1: \"event_time es evt_id = None\"\n        using Cons(2) unfolding Pair using True by auto\n      show ?thesis unfolding Pair using \\<open>v = 0\\<close> apply auto\n         apply (cases \"extract_zero es\") using True apply auto\n        apply (cases \"extract_zero es\") using True apply auto\n        using a1 extract_zero_None snd_conv by fastforce\n    next\n      case False\n      have a1: \"event_time es evt_id = Some 0\"\n        using Cons(3) unfolding Pair using False apply auto\n        apply (cases \"event_time es evt_id\") by auto\n      have a2: \"occurs_atmost_one es evt_id\"\n        using Cons(2) unfolding Pair using False by auto\n      have a3: \"evt_id \\<in> set (fst (extract_zero es))\" \"event_time (snd (extract_zero es)) evt_id = None\"\n        using Cons(1) a1 a2 by auto\n      have a4: \"v = 0\"\n        using Cons(3) unfolding Pair using False apply auto\n        apply (cases \"event_time es evt_id\") by auto\n      show ?thesis\n        unfolding Pair apply (auto simp add: a4)\n         apply (cases \"extract_zero es\") using a3 apply auto\n        apply (cases \"extract_zero es\") by auto\n    qed\n  qed\nqed\n\nlemma extract_zero2:\n  \"occurs_atmost_one es evt_id \\<Longrightarrow>\n   event_time es evt_id = Some n \\<Longrightarrow>\n   n > 0 \\<Longrightarrow>\n   evt_id \\<notin> set (fst (extract_zero es)) \\<and> event_time (snd (extract_zero es)) evt_id = Some n\"\nproof (induction es)\n  case Nil\n  then show ?case by auto\nnext\n  case (Cons p es)\n  show ?case\n  proof (cases p)\n    case (Pair k v)\n    show ?thesis\n    proof (cases \"k = evt_id\")\n      case True\n      have a1: \"v = n\"\n        using Cons(3) unfolding Pair using True by auto\n      show ?thesis\n        using True unfolding Pair using a1 Cons(4) by auto\n    next\n      case False\n      note False1 = False\n      have a1: \"occurs_atmost_one es evt_id\"\n        using Cons(2) unfolding Pair using False by auto\n      have a2: \"event_time es evt_id = Some (n - v)\" \"n \\<ge> v\"\n        using Cons(3) unfolding Pair using False apply auto\n         apply (cases \"event_time es evt_id\") apply auto\n        apply (cases \"event_time es evt_id\") by auto\n      show ?thesis\n      proof (cases \"v = 0\")\n        case True\n        have b1: \"evt_id \\<notin> set (fst (extract_zero es))\" \"event_time (snd (extract_zero es)) evt_id = Some n\"\n          using Cons(1)[OF a1] a2 Cons(4) True by auto\n        show ?thesis unfolding Pair using False1 True apply auto\n           apply (cases \"extract_zero es\") using b1 apply auto\n          apply (cases \"extract_zero es\") by auto\n      next\n        case False\n        show ?thesis\n          unfolding Pair using False False1 a2 by auto\n      qed\n    qed\n  qed\nqed\n\nfun count_zero :: \"watchdog_chain \\<Rightarrow> nat\" where\n  \"count_zero [] = 0\"\n| \"count_zero ((k, v) # es) = (if v = 0 then 1 + count_zero es else 0)\"\n\nlemma count_zero_length:\n  \"count_zero es \\<le> length es\"\n  apply (induction es) by auto\n\nlemma count_zero_iff:\n  \"i < count_zero es \\<Longrightarrow> i < length es \\<and> snd (es ! i) = 0\"\nproof (induction es arbitrary: i)\n  case Nil\n  then show ?case by auto\nnext\n  case (Cons p es)\n  show ?case\n    apply (cases p) apply auto\n    using Cons.prems count_zero_length less_le_trans apply force\n    by (metis Cons.IH Cons.prems One_nat_def Suc_diff_Suc Suc_less_eq count_zero.simps(2) diff_zero\n              not_gr_zero not_less_zero nth_Cons' plus_1_eq_Suc snd_conv)\nqed\n\nlemma count_zero_iff2:\n  \"i = count_zero es \\<Longrightarrow> i = length es \\<or> snd (es ! i) \\<noteq> 0\"\nproof (induction es arbitrary: i)\n  case Nil\n  then show ?case by auto\nnext\n  case (Cons p es)\n  then show ?case\n    apply (cases p) by auto\nqed\n\nlemma count_zero_Suc:\n  \"i \\<le> count_zero es \\<Longrightarrow> i < length es \\<Longrightarrow> snd (es ! i) = 0 \\<Longrightarrow> i < count_zero es\"\n  using count_zero_iff2[of i es] by fastforce\n\nlemma extract_zero_array:\n  \"extract_zero es = (map fst (take (count_zero es) es), drop (count_zero es) es)\"\nproof (induction es)\n  case Nil\n  then show ?case by auto\nnext\n  case (Cons p es')\n  show ?case\n    apply auto\n      apply (metis (no_types, lifting) Cons.IH count_zero.simps(2) drop_Suc_Cons list.simps(9)\n                   old.prod.case plus_1_eq_Suc surjective_pairing take_Suc_Cons)\n    using count_zero_iff apply fastforce\n    by (metis count_zero_iff drop_Cons' neq0_conv nth_Cons_0)\nqed\n\nsubsection \\<open>Decrement-head operation\\<close>\n\ntext \\<open>Decrement the head of the chain by n. Helper function for tick\\<close>\nfun decr_head :: \"nat \\<Rightarrow> watchdog_chain \\<Rightarrow> watchdog_chain\" where\n  \"decr_head n [] = []\"\n| \"decr_head n ((k, v) # es) = (k, v - n) # es\"\n\nlemma decr_head_atmost_one:\n  \"occurs_atmost_one es evt_id \\<Longrightarrow>\n   occurs_atmost_one (decr_head n es) evt_id\"\nproof (induction es)\n  case Nil\n  then show ?case by auto\nnext\n  case (Cons p es)\n  show ?case\n  proof (cases p)\n    case (Pair k v)\n    show ?thesis\n      unfolding Pair using Cons(2) unfolding Pair by auto\n  qed  \nqed\n\nlemma decr_head_None:\n  \"event_time es evt_id = None \\<Longrightarrow>\n   event_time (decr_head n es) evt_id = None\"\nproof (induction es)\n  case Nil\n  then show ?case by auto\nnext\n  case (Cons p es)\n  show ?case\n  proof (cases p)\n    case (Pair k v)\n    have a1: \"k \\<noteq> evt_id\"\n      using Cons(2) unfolding Pair by auto\n    have a2: \"event_time es evt_id = None\"\n      using Cons(2) unfolding Pair using a1 apply auto\n      apply (cases \"event_time es evt_id\") by auto\n    show ?thesis\n      unfolding Pair using a1 a2 by auto\n  qed\nqed\n\nlemma decr_head_Some:\n  \"event_time es evt_id = Some a \\<Longrightarrow>\n   n \\<le> snd (es ! 0) \\<Longrightarrow>\n   event_time (decr_head n es) evt_id = Some (a - n)\"\nproof (induction es)\n  case Nil\n  then show ?case by auto\nnext\n  case (Cons p es)\n  show ?case\n  proof (cases p)\n    case (Pair k v)\n    show ?thesis\n    proof (cases \"k = evt_id\")\n      case True\n      have \"v = a\"\n        using Cons(2) unfolding Pair using True by auto\n      then show ?thesis\n        unfolding Pair using True by auto\n    next\n      case False\n      have a1: \"event_time es evt_id = Some (a - v)\" \"v \\<le> a\"\n        using Cons(2) unfolding Pair using False apply auto\n         apply (cases \"event_time es evt_id\") apply auto\n        apply (cases \"event_time es evt_id\") by auto\n      show ?thesis\n        using Cons(3) unfolding Pair using False a1 by auto\n    qed\n  qed\nqed\n\nsubsection \\<open>Tick operation\\<close>\n\ntext \\<open>Perform one tick on the watchdog chain. Return the list of\n  events triggered.\\<close>\ndefinition watchdog_tick :: \"watchdog_chain \\<Rightarrow> task_id list \\<times> watchdog_chain\" where\n  \"watchdog_tick es = extract_zero (decr_head 1 es)\"\n\nvalue \"watchdog_tick [(1, 10)]\"\nvalue \"watchdog_tick [(1, 1), (2, 10)]\"\nvalue \"watchdog_tick [(1, 1), (2, 0), (0, 5)]\"\n\ntheorem watchdog_tick_None:\n  assumes \"event_time es evt_id = None\"\n  shows \"evt_id \\<notin> set (fst (watchdog_tick es)) \\<and>\n         event_time (snd (watchdog_tick es)) evt_id = None\"\n  unfolding watchdog_tick_def\n  apply (rule extract_zero_None)\n  by (rule decr_head_None[OF assms(1)])\n\ntheorem watchdog_tick_triv:\n  assumes \"valid_watchdog es\"\n  shows \"event_time es evt_id \\<noteq> Some 0\"\nproof (cases es)\n  case Nil\n  then show ?thesis by auto\nnext\n  case (Cons p es')\n  show ?thesis\n  proof (cases p)\n    case (Pair i n)\n    have a: \"n > 0\"\n      using assms(1) unfolding valid_watchdog_def Cons Pair by auto\n    show ?thesis\n      unfolding Cons Pair using a apply auto\n      apply (cases \"event_time es' evt_id\")\n      by auto\n  qed\nqed\n\ntheorem watchdog_tick1:\n  assumes \"valid_watchdog es\"\n    and \"event_time es evt_id = Some 1\"\n  shows \"evt_id \\<in> set (fst (watchdog_tick es)) \\<and>\n         event_time (snd (watchdog_tick es)) evt_id = None\"\nproof -\n  have a1: \"event_time (decr_head 1 es) evt_id = Some (1 - 1)\"\n    apply (rule decr_head_Some)\n    using assms(1,2) unfolding valid_watchdog_def by auto\n  show ?thesis\n    unfolding watchdog_tick_def\n    apply (rule extract_zero1)\n     apply (rule decr_head_atmost_one)\n    using a1 assms(1) unfolding valid_watchdog_def by auto\nqed\n\ntheorem watchdog_tick2:\n  assumes \"valid_watchdog es\"\n    and \"event_time es evt_id = Some n\"\n    and \"n > 1\"\n  shows \"evt_id \\<notin> set (fst (watchdog_tick es)) \\<and>\n         event_time (snd (watchdog_tick es)) evt_id = Some (n - 1)\"\nproof -\n  have nonNil: \"length es \\<noteq> 0\"\n    using assms(2) by auto\n  show ?thesis\n    unfolding watchdog_tick_def\n    apply (rule extract_zero2)\n      apply (rule decr_head_atmost_one)\n    using assms(1) unfolding valid_watchdog_def apply auto[1]\n     apply (rule decr_head_Some[OF assms(2)])\n    using assms(1,3) unfolding valid_watchdog_def\n    using nonNil by auto\nqed\n\nlemma extract_zero_valid:\n  \"\\<forall>i. occurs_atmost_one es i \\<Longrightarrow> valid_watchdog (snd (extract_zero es))\"\nproof (induction es)\n  case Nil\n  then show ?case by (auto simp add: valid_watchdog_def)\nnext\n  case (Cons pair es)\n  show ?case\n  proof (cases pair)\n    case (Pair p n)\n    show ?thesis\n      apply (auto simp add: Cons Pair)\n       apply (cases \"extract_zero es\")\n       apply auto\n      using Cons.IH Cons.prems occurs_atmost_one_Cons apply fastforce\n      using Cons.prems Pair valid_watchdog_def by auto\n  qed\nqed\n\ntheorem watchdog_tick_valid:\n  assumes \"valid_watchdog es\"\n  shows \"valid_watchdog (snd (watchdog_tick es))\"\nproof -\n  have a: \"occurs_atmost_one (decr_head 1 es) evt_id\" for evt_id\n    apply (rule decr_head_atmost_one)\n    using assms unfolding valid_watchdog_def by auto\n  show ?thesis\n    unfolding watchdog_tick_def\n    apply (rule extract_zero_valid)\n    using a by auto\nqed\n\ntheorem watchdog_tick_distinct:\n  \"\\<forall>i. occurs_atmost_one es i \\<Longrightarrow> distinct (fst (extract_zero es))\"\nproof (induction es)\n  case Nil\n  then show ?case by auto\nnext\n  case (Cons pair es')\n  show ?case\n  proof (cases pair)\n    case (Pair p n)\n    have a: \"\\<forall>a. occurs_atmost_one es' a\"\n      using Cons.prems occurs_atmost_one_Cons by blast\n    have b: \"distinct (fst (extract_zero es'))\"\n      using Cons(1) a by auto\n    show ?thesis\n      unfolding Pair\n      apply (cases \"extract_zero es'\")\n      using b apply auto\n      by (metis Cons.prems Pair extract_zero_None fst_conv occurs_atmost_one.simps(2))\n  qed\nqed\n\nsubsection \\<open>Increment-head operation\\<close>\n\ntext \\<open>Increment the head of the chain by n. Helper function for watchdog_remove\\<close>\nfun increment_head :: \"nat \\<Rightarrow> watchdog_chain \\<Rightarrow> watchdog_chain\" where\n  \"increment_head n [] = []\"\n| \"increment_head n ((k, v) # es) = (k, v + n) # es\"\n\nvalue \"increment_head 3 []\"\nvalue \"increment_head 3 [(1, 2), (2, 0)]\"\n\nsubsection \\<open>Remove operation\\<close>\n\ntext \\<open>Remove event i from the watchdog chain. Assume event i\n  occurs (exactly) once in the chain.\\<close>\nfun watchdog_remove :: \"task_id \\<Rightarrow> watchdog_chain \\<Rightarrow> watchdog_chain\" where\n  \"watchdog_remove i [] = []\"\n| \"watchdog_remove i (e # es) =\n    (if fst e = i then\n      increment_head (snd e) es\n    else e # watchdog_remove i es)\"\n\nvalue \"watchdog_remove 1 [(1, 5), (2, 5)]\"\nvalue \"watchdog_remove 1 [(2, 5), (1, 5)]\"\nvalue \"watchdog_remove 1 [(2, 5), (1, 5), (0, 5)]\"\n\ntext \\<open>Returns the location of first occurrence of evt_id.\n  Returns None if evt_id is not found.\n\\<close>\nfun watchdog_remove_pos :: \"task_id \\<Rightarrow> watchdog_chain \\<Rightarrow> nat option\" where\n  \"watchdog_remove_pos evt_id [] = None\"\n| \"watchdog_remove_pos evt_id (p # s) =\n    (if fst p = evt_id then Some 0\n     else case watchdog_remove_pos evt_id s of\n       None \\<Rightarrow> None\n     | Some i \\<Rightarrow> Some (i + 1))\"\n\nlemma watchdog_remove_pos_Suc: \n  \"0 < length s0 \\<Longrightarrow>\n   watchdog_remove_pos evt_id s0 = None \\<longleftrightarrow>\n   watchdog_remove_pos evt_id (tl s0) = None \\<and> evt_id \\<noteq> fst (hd s0)\"\n  by (induction s0, auto, force)\n\nlemma watchdog_remove_pos_Suc1: \n  \"0 < length s0 \\<Longrightarrow>\n   watchdog_remove_pos evt_id (tl s0) = Some i \\<and> evt_id \\<noteq> fst (hd s0) \\<longleftrightarrow>\n   watchdog_remove_pos evt_id s0 = Some (i + 1)\"\nproof (induct s0)\n  case Nil\n  then show ?case by auto\nnext\n  case (Cons s es)\n  then show ?case apply auto\n     apply (cases \"watchdog_remove_pos evt_id es\") by auto\nqed\n\nlemma watchdog_remove_pos_le:\n  \"watchdog_remove_pos evt_id s0 = Some i \\<Longrightarrow> i < length s0\"\nproof (induct s0 arbitrary: i)\n  case Nil\n  then show ?case by auto\nnext\n  case (Cons s es)\n  show ?case\n    apply (cases i)\n     apply auto\n    using Cons.hyps Cons.prems watchdog_remove_pos_Suc1 by fastforce\nqed\n\nlemma watchdog_remove_pos_Suc2:\n  \"0 < length s0 \\<Longrightarrow>\n   watchdog_remove_pos evt_id (tl s0) = Some i \\<and> evt_id \\<noteq> fst (hd s0) \\<and> i < length (tl s0) \\<longleftrightarrow>\n   watchdog_remove_pos evt_id s0 = Some (i + 1)\"\nproof (induct s0 arbitrary: i)\n  case Nil\n  then show ?case by auto\nnext\n  case (Cons s es)\n  show ?case \n    using Cons(2) watchdog_remove_pos_Suc1[of \"s#es\" \"evt_id\" \"i\"] watchdog_remove_pos_le[of \"evt_id\" \"es\" \"i\"]\n    by auto\nqed\n\nlemma es_not_empty:\n  \"watchdog_remove_pos evt_id (s # es) = Some (Suc n) \\<Longrightarrow> 0 < length es\"\nproof (induct n)\n  case 0\n  then show ?case apply auto\n    by (metis \"0.prems\" watchdog_remove_pos_le length_Cons list.size(3) nat_less_le)\nnext\n  case (Suc n)\n  then show ?case apply auto\n    by (metis Zero_not_Suc watchdog_remove_pos.simps(1) option.distinct(1) option.inject option.simps(4))\nqed\n\n\nlemma watchdog_remove_pos_evtid1:\n  \"watchdog_remove_pos evt_id s0 = None \\<longleftrightarrow> (\\<forall>i<length s0. evt_id \\<noteq> fst (s0 ! i))\"\nproof (induct s0)\n  case Nil\n  then show ?case by auto\nnext\n  case (Cons s es)\n  have a1: \"(watchdog_remove_pos evt_id (s # es) = None) = \n  (watchdog_remove_pos evt_id (es) = None \\<and> evt_id \\<noteq> fst (s))\"\n    using Cons watchdog_remove_pos_Suc \n    by auto\n  have a2: \"watchdog_remove_pos evt_id (s #es) = None \\<Longrightarrow> (\\<forall>i<length es. evt_id \\<noteq> fst (es ! i))\"\n    using Cons a1 \n    by force\n  have a3: \"watchdog_remove_pos evt_id (s #es) = None \\<Longrightarrow>  (\\<forall>i<length (s # es). evt_id \\<noteq> fst ((s # es) ! i))\"\n    using Cons a1 a2\n    by (simp add: nth_Cons')\n  show ?case\n    using Cons a1 a3\n    by auto\nqed\n\nlemma watchdog_remove_pos_evtid2:\n  \"watchdog_remove_pos evt_id s0 = Some n \\<longleftrightarrow>\n   (\\<forall>i<n. evt_id \\<noteq> fst (s0 ! i)) \\<and> evt_id = fst (s0 ! n) \\<and> n < length s0\"\nproof (induct s0 arbitrary: n)\n  case Nil\n  then show ?case by auto\nnext\n  case (Cons s es)\n  show ?case\n  proof(induct n)\n    case 0\n    then show ?case \n      apply auto\n      apply (cases \"watchdog_remove_pos evt_id es\")\n      apply simp \n      by simp\n  next\n    case (Suc n)\n    have a1: \"(watchdog_remove_pos evt_id (s # es) = Some (Suc n)) =\n    (watchdog_remove_pos evt_id (es) = Some n \\<and> evt_id \\<noteq> fst (s) \\<and> n < length es)\"\n      using Cons watchdog_remove_pos_Suc2\n      by (metis Suc_eq_plus1 length_Cons less_Suc_eq_0_disj list.sel(1) list.sel(3))\n    have a2: \"0 < length es \\<Longrightarrow> (watchdog_remove_pos evt_id (s # es) = Some (Suc n)) =\n    ((\\<forall>i<n. evt_id \\<noteq> fst (es ! i)) \\<and> evt_id = fst (es ! n) \\<and> evt_id \\<noteq> fst (s) \\<and> n < length es)\"\n      using a1 Cons by blast\n    have a3: \"0 < length es \\<Longrightarrow> (watchdog_remove_pos evt_id (s # es) = Some (Suc n)) =\n    ((\\<forall>i<(Suc n). evt_id \\<noteq> fst ((s # es) ! i)) \\<and> evt_id = fst ((s # es) ! (Suc n)) \\<and> n < length es)\"\n      using a2 \n      by (metis less_Suc_eq_0_disj nth_Cons_0 nth_Cons_Suc)\n    have a4: \"(watchdog_remove_pos evt_id (s # es) = Some (Suc n)) =\n    ((\\<forall>i<(Suc n). evt_id \\<noteq> fst ((s # es) ! i)) \\<and> evt_id = fst ((s # es) ! (Suc n)) \\<and> n < length es)\"\n      using a3 es_not_empty\n      by fastforce\n    have a5: \"(watchdog_remove_pos evt_id (s # es) = Some (Suc n)) =\n    ((\\<forall>i<(Suc n). evt_id \\<noteq> fst ((s # es) ! i)) \\<and> evt_id = fst ((s # es) ! (Suc n)) \\<and> \n    (Suc n < length (s # es)) \\<and> n < length es)\"\n      using a4 \n      using Cons.hyps a1 es_not_empty by auto\n    show ?case\n      using a5 Cons Suc \n      by simp\n  qed\nqed\n\nlemma watchdog_remove_pos_some_fst:\n  \"watchdog_remove_pos evt_id s0 = Some n \\<Longrightarrow> \\<forall>i. i < n \\<longrightarrow> fst (s0 ! i) \\<noteq> fst (s0 ! n)\"\nproof (induct s0 arbitrary: n)\n  case Nil\n  then show ?case by auto\nnext\n  case (Cons s es)\n  then show ?case\n    by (metis (no_types, lifting) watchdog_remove_pos_evtid2)\nqed\n\ndefinition remove_chain_pos_fun :: \"nat \\<Rightarrow> watchdog_chain \\<Rightarrow> watchdog_chain\" where\n  \"remove_chain_pos_fun i es = (\n    if i \\<ge> length es then\n      es\n    else if i = length es - 1 then\n      take i es\n    else\n      take i es @ drop (i + 1) (es[(i + 1) := (fst (es!(i+1)), snd (es!(i+1)) + snd (es!i))]))\"\n\nvalue \"remove_chain_pos_fun 0 [(2, 5)]\"\nvalue \"remove_chain_pos_fun 1 [(2, 5), (1, 5), (0, 5)]\"\nvalue \"remove_chain_pos_fun 2 [(2, 5), (1, 5), (0, 5)]\"\nvalue \"remove_chain_pos_fun 3 [(2, 5), (1, 5), (0, 5)]\"\n\nlemma remove_chain_pos_prop1:\n  \"take (length s) ((k, v) # s) = remove_chain_pos_fun (length s) ((k, v) # s)\"\nproof (induct s)\n  case Nil\n  then show ?case apply auto\n    by (simp add: remove_chain_pos_fun_def)\nnext\n  case (Cons s es)\n  then show ?case\n    by (metis add_diff_cancel_left' length_Cons plus_1_eq_Suc remove_chain_pos_fun_def take_all)\nqed\n\nlemma remove_chain_pos_Suc [simp]:\n  \"remove_chain_pos_fun (Suc n) ((a, b) # s # es) = (a, b) # (remove_chain_pos_fun n (s # es))\"\nproof (induct n arbitrary: s)\n  case 0\n  then show ?case \n    by (simp add: remove_chain_pos_fun_def)\nnext\n  case (Suc n)\n  then show ?case \n    unfolding remove_chain_pos_fun_def\n    by auto\nqed\n\nlemma remove_chain_pos_prop2:\n  \"(take n ((a', b') # es) @ drop n es)[n := (fst ((take n ((a', b') # es) @ drop n es) ! n), \n   snd (((a', b') # es) ! n) + snd (es ! n))] = remove_chain_pos_fun n ((a', b') # es)\"\nproof(induct n arbitrary: es)\n  case 0\n  then show ?case apply auto\n    unfolding remove_chain_pos_fun_def apply auto\n    by (simp add: add.commute)\nnext\n  case (Suc n)\n  then show ?case apply auto\n    unfolding remove_chain_pos_fun_def apply auto\n     apply (metis take_Suc_Cons)\n    by (smt Cons_nth_drop_Suc Suc_leI add.commute diff_cancel2 diff_diff_cancel drop_update_swap \n        length_drop length_rev list_update_append nat_le_linear nat_less_le nth_append_length \n        plus_1_eq_Suc rev_take)\nqed\n\ndefinition watchdog_remove2 :: \"task_id \\<Rightarrow> watchdog_chain \\<Rightarrow> watchdog_chain\" where\n  \"watchdog_remove2 evt_id s =\n    (case watchdog_remove_pos evt_id s of\n       None \\<Rightarrow> s\n     | Some n \\<Rightarrow> remove_chain_pos_fun n s)\"\n\nlemma watchdog_remove_pos_None:\n  \"watchdog_remove_pos evt_id es = None \\<Longrightarrow> event_time es evt_id = None\"\nproof (induction es)\n  case Nil\n  then show ?case by auto\nnext\n  case (Cons a es)\n  then show ?case\n    apply (cases \"watchdog_remove_pos evt_id es\")\n    by auto\nqed\n\nlemma watchdog_remove_None:\n  \"watchdog_remove_pos evt_id s0 = None \\<Longrightarrow> s0 = watchdog_remove evt_id s0\"\n  apply (induction s0) apply auto by fastforce\n\nlemma watchdog_remove2_correct:\n  \"watchdog_remove2 evt_id s0 = watchdog_remove evt_id s0\"\nproof (induction s0)\n  case Nil\n  then show ?case\n    by (auto simp add: watchdog_remove2_def)\nnext\n  case (Cons s s0)\n  show ?case\n  proof (cases \"fst s = evt_id\")\n    case True\n    then show ?thesis\n      apply (auto simp add: watchdog_remove2_def remove_chain_pos_fun_def)\n      apply (cases s0) by auto\n  next\n    case False\n    then show ?thesis\n      apply (auto simp add: watchdog_remove2_def)\n      apply (cases \"watchdog_remove_pos evt_id s0\")\n       apply (auto simp add: watchdog_remove_None)\n      by (metis Cons.IH watchdog_remove_pos.elims option.case(2) option.distinct(1) prod.collapse\n                remove_chain_pos_Suc watchdog_remove2_def)\n  qed\nqed\n\nlemma event_time_None_intro:\n  \"k < length es \\<Longrightarrow> \\<forall>i<k. evt_id \\<noteq> fst (es ! i) \\<Longrightarrow> event_time (take k es) evt_id = None\"\nproof (induction k)\n  case 0\n  then show ?case by auto\nnext\n  case (Suc k)\n  have a1: \"take (Suc k) es = take k es @ [es ! k]\"\n    by (simp add: Suc.prems(1) Suc_lessD take_Suc_conv_app_nth)\n  have a2: \"event_time (take k es) evt_id = None\"\n    using Suc by auto\n  show ?case\n    using Suc a1 apply auto\n    unfolding event_time_append1[OF a2]\n    by auto\nqed\n\nlemma occurs_atmost_one_drop:\n  \"occurs_atmost_one es evt_id \\<Longrightarrow> occurs_atmost_one (drop n es) evt_id\"\n  apply (induction n)\n  apply auto\n  by (metis drop_Nil drop_Suc hd_Cons_tl occurs_atmost_one_Cons tl_drop)\n\nlemma event_time_incr0_None:\n  assumes \"event_time es evt_id = None\"\n  shows \"event_time (es[0 := (fst (es ! 0), snd (es ! 0) + k)]) evt_id = None\"\nproof (cases es)\n  case Nil\n  then show ?thesis by auto\nnext\n  case (Cons p es')\n  show ?thesis\n  proof (cases p)\n    case (Pair k v)\n    have a1: \"k \\<noteq> evt_id\" \"event_time es' evt_id = None\"\n      using assms unfolding Cons Pair\n      using event_time_Suc_None by auto\n    show ?thesis\n      unfolding Cons Pair by (auto simp add: a1)\n  qed\nqed\n\ntheorem watchdog_remove_prop1:\n  assumes \"occurs_atmost_one es evt_id\"\n    and \"event_time es evt_id = Some k\"\n  shows \"event_time (watchdog_remove evt_id es) evt_id = None\"\nproof -\n  have \"watchdog_remove_pos evt_id es \\<noteq> None\"\n    using assms watchdog_remove_pos_None by fastforce\n  then obtain k where a1: \"watchdog_remove_pos evt_id es = Some k\"\n    by auto\n  then have a2: \"\\<forall>i<k. evt_id \\<noteq> fst (es ! i)\" \"evt_id = fst (es ! k)\" \"k < length es\"\n    using watchdog_remove_pos_evtid2 assms(2) by auto\n  have a3: \"watchdog_remove evt_id es = remove_chain_pos_fun k es\"\n    unfolding watchdog_remove2_correct[symmetric] watchdog_remove2_def\n    by (simp add: a1)\n  show ?thesis\n  proof (cases \"k = length es - 1\")\n    case True\n    show ?thesis\n    proof -\n      have b1: \"watchdog_remove evt_id es = take (length es - 1) es\"\n        unfolding a3 remove_chain_pos_fun_def\n        using a2(3) True by auto\n      show ?thesis\n        unfolding b1\n        apply (rule event_time_None_intro)\n        using a2 by (auto simp add: True)\n    qed\n  next\n    case False\n    show ?thesis\n    proof -\n      have c1: \"watchdog_remove evt_id es =\n                take k es @ drop (Suc k) (es[Suc k := (fst (es ! Suc k), snd (es ! Suc k) + snd (es ! k))])\"\n        unfolding a3 remove_chain_pos_fun_def\n        using a2(3) False by auto\n      have c2: \"event_time (take k es) evt_id = None\"\n        apply (rule event_time_None_intro)\n        using a2 by auto\n      have c3: \"occurs_atmost_one (drop k es) evt_id\"\n        by (rule occurs_atmost_one_drop[OF assms(1)])\n      have c4: \"drop k es = es ! k # drop (Suc k) es\"\n        by (simp add: Cons_nth_drop_Suc a2(3))\n      have c5: \"event_time (drop (Suc k) es) evt_id = None\"\n        using c3 unfolding c4 apply (cases \"es ! k\")\n        by (auto simp add: a2(2))\n      let ?es'=\"drop (Suc k) es\"\n      have c6: \"drop (Suc k) (es[Suc k := (fst (es ! Suc k), snd (es ! Suc k) + snd (es ! k))]) =\n                ?es'[0 := (fst (?es' ! 0), snd (?es' ! 0) + snd (es ! k))]\"\n        by (metis (no_types, hide_lams) a2(3) add.commute add.left_neutral add_diff_cancel_right'\n              diff_le_self drop_update_swap not_less not_less_eq nth_drop)\n      have c7: \"event_time (drop (Suc k) (es[Suc k := (fst (es ! Suc k), snd (es ! Suc k) + snd (es ! k))])) evt_id = None\"\n        unfolding c6 apply (rule event_time_incr0_None)\n        apply (rule c5) using False a2(3) done\n      show ?thesis\n        unfolding c1 event_time_append1[OF c2]\n        using c7 by auto\n    qed\n  qed\nqed\n\nlemma event_time_incr0_Some:\n  assumes \"event_time es evt_id = Some a\"\n  shows \"event_time (es[0 := (fst (es ! 0), snd (es ! 0) + k)]) evt_id = Some (a + k)\"\nproof (cases es)\n  case Nil\n  then show ?thesis using assms by auto\nnext\n  case (Cons p es')\n  show ?thesis\n  proof (cases p)\n    case (Pair k v)\n    show ?thesis\n    proof (cases \"k = evt_id\")\n      case True\n      have \"v = a\"\n        using assms(1) unfolding Cons Pair True by auto\n      then show ?thesis\n        unfolding Pair Cons True by auto\n    next\n      case False\n      have \"event_time es' evt_id = Some (a - v)\" \"a \\<ge> v\"\n        using assms unfolding Cons Pair using False apply auto\n         apply (cases \"event_time es' evt_id\") apply auto\n        apply (cases \"event_time es' evt_id\") by auto\n      then show ?thesis\n        unfolding Pair Cons using False\n        by (simp add: Pair local.Cons)\n    qed\n  qed\nqed\n\ntheorem watchdog_remove_prop2:\n  assumes \"evt_id \\<noteq> evt_id2\"\n    and \"event_time es evt_id = Some k\"\n  shows \"event_time (watchdog_remove evt_id es) evt_id2 = event_time es evt_id2\"\nproof -\n  have \"watchdog_remove_pos evt_id es \\<noteq> None\"\n    using assms watchdog_remove_pos_None by fastforce\n  then obtain k where a1: \"watchdog_remove_pos evt_id es = Some k\"\n    by auto\n  then have a2: \"\\<forall>i<k. evt_id \\<noteq> fst (es ! i)\" \"evt_id = fst (es ! k)\" \"k < length es\"\n    using watchdog_remove_pos_evtid2 assms(2) by auto\n  have a3: \"watchdog_remove evt_id es = remove_chain_pos_fun k es\"\n    unfolding watchdog_remove2_correct[symmetric] watchdog_remove2_def\n    by (simp add: a1)\n  show ?thesis\n  proof (cases \"k = length es - 1\")\n    case True\n    show ?thesis\n    proof -\n      have b1: \"watchdog_remove evt_id es = take (length es - 1) es\"\n        unfolding a3 remove_chain_pos_fun_def\n        using a2(3) True by auto\n      show ?thesis\n      proof (cases \"event_time (take (length es - 1) es) evt_id2\")\n        case None\n        have c1: \"es = take (length es - 1) es @ [es ! (length es - 1)]\"\n          by (metis a2(3) butlast_conv_take gr_implies_not_zero last_conv_nth length_0_conv snoc_eq_iff_butlast)\n        show ?thesis\n          unfolding b1 None\n          apply (subst c1)\n          unfolding event_time_append1[OF None]\n          using True a2(2) assms(1) by auto\n      next\n        case (Some a)\n        show ?thesis\n          unfolding b1 Some\n          by (metis Some event_time_take_Some)\n      qed\n    qed\n  next\n    case False\n    show ?thesis\n    proof -\n      have c1: \"watchdog_remove evt_id es =\n                take k es @ drop (Suc k) (es[Suc k := (fst (es ! Suc k), snd (es ! Suc k) + snd (es ! k))])\"\n        unfolding a3 remove_chain_pos_fun_def\n        using a2(3) False by auto\n      have c2: \"event_time (take k es) evt_id = None\"\n        apply (rule event_time_None_intro)\n        using a2 by auto\n      have c3: \"event_time es evt_id2 = event_time ((take k es) @ (drop k es)) evt_id2\"\n        by auto\n      show ?thesis\n      proof (cases \"event_time (take k es) evt_id2\")\n        case None\n        note None1 = None\n        let ?es'=\"drop (Suc k) es\"\n        have c4: \"drop (Suc k) (es[Suc k := (fst (es ! Suc k), snd (es ! Suc k) + snd (es ! k))]) =\n                  ?es'[0 := (fst (?es' ! 0), snd (?es' ! 0) + snd (es ! k))]\"\n          by (metis (no_types, hide_lams) a2(3) add.commute add.left_neutral add_diff_cancel_right'\n                diff_le_self drop_update_swap not_less not_less_eq nth_drop)\n        show ?thesis\n        proof (cases \"event_time (drop k es) evt_id2\")\n          case None\n          have d1: \"event_time es evt_id2 = None\"\n            by (metis None None1 append_take_drop_id event_time_append1 option.simps(4))\n          show ?thesis\n            unfolding c1 d1\n            apply (subst event_time_append1[OF None1])\n            apply (subst c4)\n            by (metis (no_types, lifting) Cons_nth_drop_Suc None a2(3)\n                  event_time_Suc_None event_time_incr0_None option.case_eq_if)\n        next\n          case (Some n)\n          have e1: \"event_time es evt_id2 = Some (n + watchdog_total_upto (take k es) (length (take k es)))\"\n            unfolding c3\n            apply (subst event_time_append1[OF None1])\n            using Some by auto\n          have e2: \"drop k es = es ! k # drop (Suc k) es\"\n            by (simp add: Cons_nth_drop_Suc a2(3))\n          have e3: \"fst (es ! k) \\<noteq> evt_id2\"\n            using a2(2) assms(1) by auto\n          have e4: \"n \\<ge> snd (es ! k) \\<and> event_time (drop (Suc k) es) evt_id2 = Some (n - snd (es ! k))\"\n            using Some unfolding e2\n            apply (auto simp add: e3)\n            by (cases \"event_time (drop (Suc k) es) evt_id2\", auto)+\n          have e5: \"event_time (drop (Suc k) (es[Suc k := (fst (es ! Suc k), snd (es ! Suc k) + snd (es ! k))])) evt_id2 = Some (n - snd (es ! k) + snd (es ! k))\"\n            unfolding c4\n            apply (rule event_time_incr0_Some)\n            using e4 apply auto done\n          show ?thesis\n            unfolding c1 e1\n            apply (subst event_time_append1[OF None])\n            using Some apply (auto simp add: e5)\n            using e4 by auto\n        qed\n      next\n        case (Some a)\n        then show ?thesis\n          unfolding c1\n          by (metis event_time_append2 event_time_take_Some)\n      qed\n    qed\n  qed\nqed\n\nlemma event_time_to_watchdog_remove_pos_None:\n  \"event_time es evt_id = None \\<Longrightarrow> watchdog_remove_pos evt_id es = None\"\n  apply (induction es)\n   apply auto\n  subgoal for p n es'\n    apply (cases \"event_time es' evt_id\")\n    by auto\n  done\n\ntheorem watchdog_remove_same:\n  assumes \"event_time es evt_id = None\"\n  shows \"watchdog_remove evt_id es = es\"\n  unfolding watchdog_remove2_correct[symmetric] watchdog_remove2_def\n  by (simp add: assms event_time_to_watchdog_remove_pos_None)\n\ntheorem watchdog_remove_prop1':\n  assumes \"occurs_atmost_one es evt_id\"\n  shows \"event_time (watchdog_remove evt_id es) evt_id = None\"\n  by (metis assms event_time_to_watchdog_remove_pos_None option.exhaust option.simps(4)\n            watchdog_remove2_correct watchdog_remove2_def watchdog_remove_prop1)\n\ntheorem watchdog_remove_prop2':\n  assumes \"evt_id \\<noteq> evt_id2\"\n  shows \"event_time (watchdog_remove evt_id es) evt_id2 = event_time es evt_id2\"\n  using assms watchdog_remove_prop2 watchdog_remove_same by fastforce\n\ntheorem watchdog_remove_valid:\n  assumes \"valid_watchdog es\"\n  shows \"valid_watchdog (watchdog_remove evt_id es)\"\nproof -\n  have a: \"occurs_atmost_one es evt_id' \\<Longrightarrow>\n           occurs_atmost_one (watchdog_remove evt_id es) evt_id'\" for evt_id'\n  proof (induction es)\n    case Nil\n    then show ?case by auto\n  next\n    case (Cons pair es')\n    have a1: \"occurs_atmost_one es' evt_id'\"\n      using Cons.prems occurs_atmost_one_Cons by blast\n    have a2: \"occurs_atmost_one (watchdog_remove evt_id es') evt_id'\"      \n      using Cons(1) a1 by auto\n    show ?case\n    proof (cases pair)\n      case (Pair p n)\n      show ?thesis\n        apply (auto simp add: Cons Pair a2)\n          apply (metis a1 increment_head.simps occurs_atmost_one.elims(2) occurs_atmost_one.simps(2))\n        using Cons(2) unfolding Pair apply auto\n         apply (subst watchdog_remove_prop2')\n           apply auto\n        by (metis increment_head.elims occurs_atmost_one.simps(2))\n    qed\n  qed\n  show ?thesis\n    unfolding valid_watchdog_def\n    apply auto\n    subgoal\n      apply (cases es)\n       apply simp subgoal for pair es'\n        apply (cases pair)\n        subgoal for p n\n          apply auto\n           apply (metis (no_types, lifting) add_eq_0_iff_both_eq_0 assms(1) event_time.simps(2) gr0I\n                    increment_head.elims nth_Cons_0 snd_conv watchdog_tick_triv)\n          using assms(1) valid_watchdog_def by auto\n        done\n      done\n    subgoal for evt_id'\n      apply (rule a)\n      using assms(1) unfolding valid_watchdog_def by auto\n    done\nqed\n\nend\n", "meta": {"author": "bzhan", "repo": "EventSystem", "sha": "3499867fd8fbf9b8d6acf80a0791f279b553ce15", "save_path": "github-repos/isabelle/bzhan-EventSystem", "path": "github-repos/isabelle/bzhan-EventSystem/EventSystem-3499867fd8fbf9b8d6acf80a0791f279b553ce15/Watchdog.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8438950868503681, "lm_q2_score": 0.8311430436757313, "lm_q1q2_score": 0.7013975310278106}}
{"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.*)\n  theory TIP_prop_77\nimports \"../../Test_Base\"\nbegin\n\ndatatype 'a list = nil2 | cons2 \"'a\" \"'a list\"\n\ndatatype Nat = Z | S \"Nat\"\n\nfun x :: \"bool => bool => bool\" where\n\"x True z = z\"\n| \"x False z = False\"\n\nfun t2 :: \"Nat => Nat => bool\" where\n\"t2 (Z) z = True\"\n| \"t2 (S z2) (Z) = False\"\n| \"t2 (S z2) (S x2) = t2 z2 x2\"\n\nfun insort :: \"Nat => Nat list => Nat list\" where\n\"insort y (nil2) = cons2 y (nil2)\"\n| \"insort y (cons2 z2 xs) =\n     (if t2 y z2 then cons2 y (cons2 z2 xs) else cons2 z2 (insort y xs))\"\n\nfun sorted :: \"Nat list => bool\" where\n\"sorted (nil2) = True\"\n| \"sorted (cons2 z (nil2)) = True\"\n| \"sorted (cons2 z (cons2 y2 ys)) =\n     x (t2 z y2) (sorted (cons2 y2 ys))\"\n\ntheorem property0 :\n  \"((sorted xs) ==> (sorted (insort y 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/Isaplanner/Isaplanner/TIP_prop_77.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972684083608, "lm_q2_score": 0.8056321983146848, "lm_q1q2_score": 0.7013811911945874}}
{"text": "theory ConcreteSemantics_7_Ex1\n  imports Main \"~~/src/HOL/IMP/Big_Step\" \"~~/src/HOL/IMP/Small_Step\"\nbegin\n\n(* Exercise 7.1. *)\n(* type_synonym vname = string\ndatatype aexp = N int | V vname | Plus aexp aexp *)\n\nfun assigned :: \"com \\<Rightarrow> vname set\" where\n\"assigned SKIP = {}\" |\n\"assigned (Assign vname aexp) = {vname}\"|\n\"assigned (Seq com1 com2) = (assigned com1) \\<union> (assigned com2)\"|\n\"assigned (If bexp com1 com2) = (assigned com1) \\<union> (assigned com2)\"|\n\"assigned (While bexp com) = assigned com\"\n\n(* Try to prove by induction on t, but failed. *)\nlemma \"\\<lbrakk>(c, s) \\<Rightarrow> t; x \\<notin> assigned c\\<rbrakk> \\<Longrightarrow> s x = t x\"\napply(induction rule:big_step_induct)\napply(auto)\ndone\n\n\n(* Exercise 7.2. *)\nfun skip :: \"com \\<Rightarrow> bool\" where\n\"skip SKIP = True\" |\n\"skip (Assign vname aexp) = False\"|\n\"skip (Seq com1 com2) = (skip com1 \\<and> skip com2)\"|\n\"skip (If bexp com1 com2) = (skip com1 \\<and> skip com2)\"|\n\"skip (While bexp com) = False\"\n(* \n\u8a3c\u660e\u3067\u304d\u306a\u3044\u3068\u601d\u3063\u305f\u3089\u3001\u660e\u3089\u304b\u306bWhile\u306fskip like \u3058\u3083\u306a\u3044\u3067\u3057\u3087\n\"skip (While bexp com) = skip com\"\n\u3082\u3061\u308d\u3093\u3001bexp\u306e\u5024\u304cfalse\u3060\u3063\u305f\u3089\u3001skip like\u306b\u306a\u308b\u304c\u3001\u3057\u304b\u3057\u3001\u74b0\u5883\u304c\u3053\u3053\u3067\u306f\u5909\u6570\u306b\u542b\u307e\u308c\u3066\u3044\u306a\u3044\u306e\u3067\u3001False\u3068\u4e00\u5f8b\u306b\u5224\u5b9a\u3057\u305f\u307b\u3046\u304c\u3044\u3044\u3002\n*)\n\nlemma \"skip c \\<Longrightarrow> c \\<sim> SKIP\"\napply(induction c)\napply(simp_all)\napply fastforce\n by (meson Big_Step.IfE big_step.IfFalse big_step.IfTrue)\n(* apply (meson BigStep.IfE IfFalse IfTrue)\ndone *)\n\n\n(* Exercise 7.3. *)\nfun deskip :: \"com \\<Rightarrow> com\" where\n\"deskip SKIP = SKIP\" |\n\"deskip (Assign vname aexp) = (Assign vname aexp)\"|\n\"deskip (Seq com1 com2) = (if deskip com1 = SKIP then deskip com2 else (if deskip com2 = SKIP then deskip com1 else (Seq (deskip com1) (deskip com2))))\"|\n\"deskip (If bexp com1 com2) = (If bexp (deskip com1) (deskip com2))\"|\n\"deskip (While bexp com) = While bexp (deskip com)\"\n\nlemma \"deskip c \\<sim> c\"\nproof(induction c)\n  case SKIP\n  then show ?case by simp\nnext\n  case (Assign x1 x2)\n  then show ?case by simp\nnext\n  case (Seq c1 c2)\n  (* deskip c1 \\<sim> c1 \\<Longrightarrow> deskip c2 \\<sim> c2 \\<Longrightarrow> deskip (c1;; c2) \\<sim> c1;; c2 *)\n  (* have \"deskip (c1;; c2) \\<sim> c1;; c2\" sledgehammer *)\n  have \"deskip (c1;; c2) \\<sim> (deskip c1;; deskip c2)\" by auto\n  moreover have \"deskip c1 ;; deskip c2 \\<sim> c1 ;; c2 \" using Seq.IH(1) Seq.IH(2) by blast\n  ultimately show ?case by auto\nnext\n  case (If x1 c1 c2)\n  then show ?case by auto\nnext\n  case (While x1 c)\n  then show ?case using sim_while_cong_aux by auto\nqed\n(* apply(induction c rule: deskip.induct)\napply(simp_all)\nsledgehammer\napply(simp add: sim_while_cong) *)\n\n\n(* Exercise 7.4. *)\n\ntext \\<open> Complete the definition with two rules for Plus that model a left-to-right\nevaluation strategy: reduce the first argument with \\<leadsto> if possible, reduce the\nsecond argument with \\<leadsto> if the first argument is a number \\<close>\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\nlemma \"(a, s) \\<leadsto> a' \\<Longrightarrow> aval a s = aval a' s\"\napply(induction rule: astep.induct[split_format(complete)])\napply(auto)\ndone\n\n(* \u4f55\u3082\u308f\u304b\u3089\u305a\u306b\u8a3c\u660e\u304c\u7d42\u308f\u3063\u305f *)\n\n\n(* Exercise 7.5 *)\nlemma \"IF And b1 b2 THEN c1 ELSE c2 \\<sim> IF b1 THEN IF b2 THEN c1 ELSE c2 ELSE c2\"\nusing IfTrue by fastforce\n\n(* lemma \"WHILE And b1 b2 DO c \\<sim> WHILE b1 DO WHILE b2 DO c\"\n(* apply(induction \"WHILE b2 DO c\" rule: big_step_induct) *)\nsorry *)\n(* `c` \u304c `SKIP` \u306e\u6642\u306f\u9055\u304f\u306a\u3044\u304b\uff1f *)\n\n(* lemma \"\\<not> (WHILE And b1 b2 DO c \\<sim> WHILE b1 DO WHILE b2 DO c)\"\napply(induction \"WHILE b1 DO WHILE b2 DO c\" rule: big_step_induct) *)\n\n(* abbreviation\n  equiv_c :: \"com \\<Rightarrow> com \\<Rightarrow> bool\" (infix \"\\<sim>\" 50) where\n  \"c \\<sim> c' \\<equiv> (\\<forall>s t. (c,s) \\<Rightarrow> t  =  (c',s) \\<Rightarrow> t)\" *)\n(* lemma \\<exists> s t. (WHILE And b1 b2 DO c, s) \\<Rightarrow> t \\<and>  *)\n\n(* lemma \"\\<not> (\\<forall> s t c. (WHILE And b1 b2 DO c, s) \\<Rightarrow> t = (WHILE b1 DO WHILE b2 DO c, s) \\<Rightarrow> t)\"\nproof \n  assume \"\\<forall> s t c. (WHILE And b1 b2 DO c, s) \\<Rightarrow> t = (WHILE b1 DO WHILE b2 DO c, s) \\<Rightarrow> t\"\n\n  thus False sorry\nqed *)\n(* \u4e0a\u8a18\u3060\u3068\u675f\u7e1b\u304c\u591a\u3044\u304b\u3089\u3060\u3081\u3002 *)\n\nlemma \"\\<not> (WHILE And (Bc True) (Bc False) DO SKIP \\<sim> WHILE (Bc True) DO WHILE (Bc False) DO SKIP)\"\nproof \nassume asm: \"(WHILE And (Bc True) (Bc False) DO SKIP \\<sim> WHILE (Bc True) DO WHILE (Bc False) DO SKIP)\"\nhave \"(WHILE And (Bc True) (Bc False) DO SKIP, s) \\<Rightarrow> s\" by (simp add: WhileFalse)\nthen have \"(WHILE (Bc True) DO WHILE (Bc False) DO SKIP, s) \\<Rightarrow> s\" by (simp add: asm)\nthen show False 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 b1 b2 = Not (And (Not b1) (Not b2))\"\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  from a show ?thesis by (induction ?C s t rule: big_step_induct, auto)\nqed\n\nlemma wowow: \"\\<forall> s t. (WHILE Or b1 b2 DO c, s) \\<Rightarrow> t \\<longrightarrow> (WHILE Or b1 b2 DO c;;WHILE b1 DO c,  s) \\<Rightarrow> t\"\n  proof -\n      {fix s t\n      assume terminates: \"(WHILE Or b1 b2 DO c, s) \\<Rightarrow> t\"\n      hence \"\\<not> bval (Or b1 b2) t\" using while_terminates_then_cond_false by auto\n      hence \"(WHILE b1 DO c, t) \\<Rightarrow> t\" by (auto simp add: Or_def)\n      from this have \"(WHILE Or b1 b2 DO c;; WHILE b1 DO c, s) \\<Rightarrow> t\" using terminates by auto\n      } thus ?thesis by auto\n  qed\n\nlemma wowwo:\"\\<forall> s t. (WHILE Or b1 b2 DO c;;WHILE b1 DO c,  s) \\<Rightarrow> t \\<longrightarrow> (WHILE Or b1 b2 DO c, s) \\<Rightarrow> t\"\nproof -\n{fix s t\nassume terminates: \"(WHILE Or b1 b2 DO c;;WHILE b1 DO c, s) \\<Rightarrow> t\"\nthen obtain t1 where seq1: \"(WHILE Or b1 b2 DO c, s) \\<Rightarrow> t1\" and seq2: \"(WHILE b1 DO c, t1) \\<Rightarrow> t\" by auto\nhence \"\\<not> bval (Or b1 b2) t1\" using while_terminates_then_cond_false by auto\nhence nb1: \"\\<not> bval b1 t1\"  by (simp add: Or_def)\nhence \"t1 = t\" using seq2 by auto\nhence \"(WHILE Or b1 b2 DO c, s) \\<Rightarrow> t\" using terminates seq1 seq2 nb1 by auto}\nthus ?thesis by auto\nqed\n\nlemma \"WHILE Or b1 b2 DO c \\<sim> WHILE Or b1 b2 DO c;;WHILE b1 DO c\"\nby (meson wowow wowwo)\n\n(* Exercise 7.6. *)\ndefinition  Do:: \"com \\<Rightarrow> bexp \\<Rightarrow> com\" (\"(DO _/ WHILE _)\"  [0, 61] 61)where\n\"DO cmd WHILE b = cmd;;WHILE b DO cmd\"\n\nfun dewhile :: \"com => com\" where\n\"dewhile SKIP = SKIP\" |\n\"dewhile (Assign vname aexp) = (Assign vname aexp)\"|\n\"dewhile (Seq com1 com2) =  Seq (dewhile com1) (dewhile com2)\"|\n\"dewhile (If bexp com1 com2) = (If bexp (dewhile com1) (dewhile com2))\"|\n\"dewhile (While bexp com) = IF Not bexp THEN SKIP ELSE (DO dewhile com WHILE bexp)\" \n\n(* WhileFalse: \"\\<not>bval b s \\<Longrightarrow> (WHILE b DO c,s) \\<Rightarrow> s\" |\nWhileTrue:\n\"\\<lbrakk> bval b s\\<^sub>1;  (c,s\\<^sub>1) \\<Rightarrow> s\\<^sub>2;  (WHILE b DO c, s\\<^sub>2) \\<Rightarrow> s\\<^sub>3 \\<rbrakk> \n\\<Longrightarrow> (WHILE b DO c, s\\<^sub>1) \\<Rightarrow> s\\<^sub>3\" *)\n\nlemma \"dewhile c \\<sim> c\" \napply(induction c)\napply(auto)\napply (smt Big_Step.SeqE Do_def WhileTrue sim_while_cong)\nby (metis Big_Step.IfE Do_def big_step.IfFalse big_step.IfTrue bval.simps(2) sim_while_cong_aux while_unfold)\n(* apply (smt Do_def SeqE WhileTrue sim_while_cong)\nby (metis Do_def IfE IfFalse IfTrue bval.simps(2) sim_while_cong_aux while_unfold) *)\n\nlemma \"dewhile c \\<sim> c\" \nproof (induction c)\n  case SKIP\n  then show ?case by simp\nnext\n  case (Assign x1 x2)\n  then show ?case by simp\nnext\n  case (Seq c1 c2)\n  then show ?case by auto\nnext\n  case (If x1 c1 c2)\n  then show ?case by auto\nnext\n  case (While x1 c)\n  hence \"WHILE x1 DO c \\<sim> WHILE x1 DO dewhile c\"  by (simp add: sim_while_cong)\n  then show ?case using Do_def while_unfold by auto\n  (* by (metis Do_def IfE IfFalse IfTrue bval.simps(2) dewhile.simps(5) while_unfold) *)\nqed\n\n(* Exercise 7.7. *)\nlemma \"\\<lbrakk> C 0 = c;; d; \\<forall> n. (C n, S n) \\<rightarrow> (C (Suc n), S (Suc n))\\<rbrakk>\n      \\<Longrightarrow>  (\\<forall> n. \\<exists> c1 c2.\n            C n = c1;; d \\<and>\n            C (Suc n) = c2;; d \\<and> (c1, S n) \\<rightarrow> (c2, S (Suc n))) \\<or>\n          (\\<exists> k. C k = SKIP;; d)\"\nproof cases\n  assume a: \"(\\<exists> k. C k = SKIP;; d)\"\n  thus ?thesis by blast\nnext\n  assume nega: \"\\<not> (\\<exists> k. C k = SKIP;; d)\"\n  assume c0: \"C 0 = c;; d\" and cnsn:\"\\<forall> n. (C n, S n) \\<rightarrow> (C (Suc n), S (Suc n))\"\n  have \"\\<forall>n. \\<exists>c1 c2. C n = c1;; d \\<and> C (Suc n) = c2;; d \\<and> (c1, S n) \\<rightarrow> (c2, S (Suc n))\"\n  proof \n    fix i\n    show \"\\<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      then show ?case  by (metis Pair_inject Small_Step.SeqE c0 cnsn nega)\n    next\n      case (Suc i)\n      (* \u5e30\u7d0d\u6cd5\u306e\u4eee\u5b9a *)\n      then obtain c1 c2 where ih:\"C i = c1;; d \\<and> C (Suc i) = c2;; d \\<and> (c1, S i) \\<rightarrow> (c2, S (Suc i))\" by auto\n      then obtain c3 where \"C(Suc(Suc i)) = c3;; d\" by (metis Pair_inject Small_Step.SeqE cnsn nega)\n      then have \"C (Suc i) = c2;;d \\<and> C(Suc (Suc i)) = c3;;d \\<and> (c2, S (Suc i)) \\<rightarrow> (c3, S(Suc(Suc i)))\" by (metis Pair_inject Small_Step.SeqE cnsn com.inject(2) ih nega)\n      then show ?case by blast\n    qed\n  qed\n  thus ?thesis by simp\nqed\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/ConcreteSemanticsChapter7/ex7/ConcreteSemantics_7_Ex1.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321936479701, "lm_q2_score": 0.870597270087091, "lm_q1q2_score": 0.7013811884841974}}
{"text": "(* Author: Xingyuan Zhang, Chunhan Wu, Christian Urban *)\ntheory Myhill_2\n  imports Myhill_1 \"~~/src/HOL/Library/Sublist\"\nbegin\n\nsection {* Second direction of MN: @{text \"regular language \\<Rightarrow> finite partition\"} *}\n\nsubsection {* Tagging functions *}\n\ndefinition \n   tag_eq :: \"('a list \\<Rightarrow> 'b) \\<Rightarrow> ('a list \\<times> 'a list) set\" (\"=_=\")\nwhere\n   \"=tag= \\<equiv> {(x, y). tag x = tag y}\"\n\nabbreviation\n   tag_eq_applied :: \"'a list \\<Rightarrow> ('a list \\<Rightarrow> 'b) \\<Rightarrow> 'a list \\<Rightarrow> bool\" (\"_ =_= _\")\nwhere\n   \"x =tag= y \\<equiv> (x, y) \\<in> =tag=\"\n\n\n\nlemma refined_intro:\n  assumes \"\\<And>x y z. \\<lbrakk>x =tag= y; x @ z \\<in> A\\<rbrakk> \\<Longrightarrow> y @ z \\<in> A\"\n  shows \"=tag= \\<subseteq> \\<approx>A\"\nusing assms unfolding str_eq_def tag_eq_def\napply(clarify, simp (no_asm_use))\nby metis\n\nlemma finite_eq_tag_rel:\n  assumes rng_fnt: \"finite (range tag)\"\n  shows \"finite (UNIV // =tag=)\"\nproof -\n  let \"?f\" =  \"\\<lambda>X. tag ` X\" and ?A = \"(UNIV // =tag=)\"\n  have \"finite (?f ` ?A)\" \n  proof -\n    have \"range ?f \\<subseteq> (Pow (range tag))\" unfolding Pow_def by auto\n    moreover \n    have \"finite (Pow (range tag))\" using rng_fnt by simp\n    ultimately \n    have \"finite (range ?f)\" unfolding image_def by (blast intro: finite_subset)\n    moreover\n    have \"?f ` ?A \\<subseteq> range ?f\" by auto\n    ultimately show \"finite (?f ` ?A)\" by (rule rev_finite_subset) \n  qed\n  moreover\n  have \"inj_on ?f ?A\"\n  proof -\n    { fix X Y\n      assume X_in: \"X \\<in> ?A\"\n        and  Y_in: \"Y \\<in> ?A\"\n        and  tag_eq: \"?f X = ?f Y\"\n      then obtain x y \n        where \"x \\<in> X\" \"y \\<in> Y\" \"tag x = tag y\"\n        unfolding quotient_def Image_def image_def tag_eq_def\n        by (simp) (blast)\n      with X_in Y_in \n      have \"X = Y\"\n        unfolding quotient_def tag_eq_def by auto\n    } \n    then show \"inj_on ?f ?A\" unfolding inj_on_def by auto\n  qed\n  ultimately show \"finite (UNIV // =tag=)\" by (rule finite_imageD)\nqed\n\nlemma refined_partition_finite:\n  assumes fnt: \"finite (UNIV // R1)\"\n  and refined: \"R1 \\<subseteq> R2\"\n  and eq1: \"equiv UNIV R1\" and eq2: \"equiv UNIV R2\"\n  shows \"finite (UNIV // R2)\"\nproof -\n  let ?f = \"\\<lambda>X. {R1 `` {x} | x. x \\<in> X}\" \n    and ?A = \"UNIV // R2\" and ?B = \"UNIV // R1\"\n  have \"?f ` ?A \\<subseteq> Pow ?B\"\n    unfolding image_def Pow_def quotient_def by auto\n  moreover\n  have \"finite (Pow ?B)\" using fnt by simp\n  ultimately  \n  have \"finite (?f ` ?A)\" by (rule finite_subset)\n  moreover\n  have \"inj_on ?f ?A\"\n  proof -\n    { fix X Y\n      assume X_in: \"X \\<in> ?A\" and Y_in: \"Y \\<in> ?A\" and eq_f: \"?f X = ?f Y\"\n      from quotientE [OF X_in]\n      obtain x where \"X = R2 `` {x}\" by blast\n      with equiv_class_self[OF eq2] have x_in: \"x \\<in> X\" by simp\n      then have \"R1 ``{x} \\<in> ?f X\" by auto\n      with eq_f have \"R1 `` {x} \\<in> ?f Y\" by simp\n      then obtain y \n        where y_in: \"y \\<in> Y\" and eq_r1_xy: \"R1 `` {x} = R1 `` {y}\" by auto\n      with eq_equiv_class[OF _ eq1] \n      have \"(x, y) \\<in> R1\" by blast\n      with refined have \"(x, y) \\<in> R2\" by auto\n      with quotient_eqI [OF eq2 X_in Y_in x_in y_in]\n      have \"X = Y\" .\n    } \n    then show \"inj_on ?f ?A\" unfolding inj_on_def by blast \n  qed\n  ultimately show \"finite (UNIV // R2)\" by (rule finite_imageD)\nqed\n\nlemma tag_finite_imageD:\n  assumes rng_fnt: \"finite (range tag)\" \n  and     refined: \"=tag=  \\<subseteq> \\<approx>A\"\n  shows \"finite (UNIV // \\<approx>A)\"\nproof (rule_tac refined_partition_finite [of \"=tag=\"])\n  show \"finite (UNIV // =tag=)\" by (rule finite_eq_tag_rel[OF rng_fnt])\nnext\n  show \"=tag= \\<subseteq> \\<approx>A\" using refined .\nnext\n  show \"equiv UNIV =tag=\"\n  and  \"equiv UNIV (\\<approx>A)\" \n    unfolding equiv_def str_eq_def tag_eq_def refl_on_def sym_def trans_def\n    by auto\nqed\n\n\nsubsection {* Base cases: @{const Zero}, @{const One} and @{const Atom} *}\n\n\n\nlemma quot_zero_finiteI [intro]:\n  shows \"finite (UNIV // \\<approx>{})\"\nunfolding quot_zero_eq by simp\n\n\nlemma quot_one_subset:\n  shows \"UNIV // \\<approx>{[]} \\<subseteq> {{[]}, UNIV - {[]}}\"\nproof\n  fix x\n  assume \"x \\<in> UNIV // \\<approx>{[]}\"\n  then obtain y where h: \"x = {z. y \\<approx>{[]} z}\" \n    unfolding quotient_def Image_def by blast\n  { assume \"y = []\"\n    with h have \"x = {[]}\" by (auto simp: str_eq_def)\n    then have \"x \\<in> {{[]}, UNIV - {[]}}\" by simp }\n  moreover\n  { assume \"y \\<noteq> []\"\n    with h have \"x = UNIV - {[]}\" by (auto simp: str_eq_def)\n    then have \"x \\<in> {{[]}, UNIV - {[]}}\" by simp }\n  ultimately show \"x \\<in> {{[]}, UNIV - {[]}}\" by blast\nqed\n\nlemma quot_one_finiteI [intro]:\n  shows \"finite (UNIV // \\<approx>{[]})\"\nby (rule finite_subset[OF quot_one_subset]) (simp)\n\n\nlemma quot_atom_subset:\n  \"UNIV // (\\<approx>{[c]}) \\<subseteq> {{[]},{[c]}, UNIV - {[], [c]}}\"\nproof \n  fix x \n  assume \"x \\<in> UNIV // \\<approx>{[c]}\"\n  then obtain y where h: \"x = {z. (y, z) \\<in> \\<approx>{[c]}}\" \n    unfolding quotient_def Image_def by blast\n  show \"x \\<in> {{[]},{[c]}, UNIV - {[], [c]}}\"\n  proof -\n    { assume \"y = []\" hence \"x = {[]}\" using h \n        by (auto simp: str_eq_def) } \n    moreover \n    { assume \"y = [c]\" hence \"x = {[c]}\" using h \n        by (auto dest!: spec[where x = \"[]\"] simp: str_eq_def) } \n    moreover \n    { assume \"y \\<noteq> []\" and \"y \\<noteq> [c]\"\n      hence \"\\<forall> z. (y @ z) \\<noteq> [c]\" by (case_tac y, auto)\n      moreover have \"\\<And> p. (p \\<noteq> [] \\<and> p \\<noteq> [c]) = (\\<forall> q. p @ q \\<noteq> [c])\" \n        by (case_tac p, auto)\n      ultimately have \"x = UNIV - {[],[c]}\" using h\n        by (auto simp add: str_eq_def)\n    } \n    ultimately show ?thesis by blast\n  qed\nqed\n\nlemma quot_atom_finiteI [intro]:\n  shows \"finite (UNIV // \\<approx>{[c]})\"\nby (rule finite_subset[OF quot_atom_subset]) (simp)\n\n\nsubsection {* Case for @{const Plus} *}\n\ndefinition \n  tag_Plus :: \"'a lang \\<Rightarrow> 'a lang \\<Rightarrow> 'a list \\<Rightarrow> ('a lang \\<times> 'a lang)\"\nwhere\n  \"tag_Plus A B \\<equiv> \\<lambda>x. (\\<approx>A `` {x}, \\<approx>B `` {x})\"\n\nlemma quot_plus_finiteI [intro]:\n  assumes finite1: \"finite (UNIV // \\<approx>A)\"\n  and     finite2: \"finite (UNIV // \\<approx>B)\"\n  shows \"finite (UNIV // \\<approx>(A \\<union> B))\"\nproof (rule_tac tag = \"tag_Plus A B\" in tag_finite_imageD)\n  have \"finite ((UNIV // \\<approx>A) \\<times> (UNIV // \\<approx>B))\" \n    using finite1 finite2 by auto\n  then show \"finite (range (tag_Plus A B))\"\n    unfolding tag_Plus_def quotient_def\n    by (rule rev_finite_subset) (auto)\nnext\n  show \"=tag_Plus A B= \\<subseteq> \\<approx>(A \\<union> B)\"\n    unfolding tag_eq_def tag_Plus_def str_eq_def by auto\nqed\n\n\nsubsection {* Case for @{text \"Times\"} *}\n\ndefinition\n  \"Partitions x \\<equiv> {(x\\<^sub>p, x\\<^sub>s). x\\<^sub>p @ x\\<^sub>s = x}\"\n\nlemma conc_partitions_elim:\n  assumes \"x \\<in> A \\<cdot> B\"\n  shows \"\\<exists>(u, v) \\<in> Partitions x. u \\<in> A \\<and> v \\<in> B\"\nusing assms unfolding conc_def Partitions_def\nby auto\n\nlemma conc_partitions_intro:\n  assumes \"(u, v) \\<in> Partitions x \\<and> u \\<in> A \\<and>  v \\<in> B\"\n  shows \"x \\<in> A \\<cdot> B\"\nusing assms unfolding conc_def Partitions_def\nby auto\n\nlemma equiv_class_member:\n  assumes \"x \\<in> A\"\n  and \"\\<approx>A `` {x} = \\<approx>A `` {y}\" \n  shows \"y \\<in> A\"\nusing assms\napply(simp)\napply(simp add: str_eq_def)\napply(metis append_Nil2)\ndone\n\ndefinition \n  tag_Times :: \"'a lang \\<Rightarrow> 'a lang \\<Rightarrow> 'a list \\<Rightarrow> 'a lang \\<times> 'a lang set\"\nwhere\n  \"tag_Times A B \\<equiv> \\<lambda>x. (\\<approx>A `` {x}, {(\\<approx>B `` {x\\<^sub>s}) | x\\<^sub>p x\\<^sub>s. x\\<^sub>p \\<in> A \\<and> (x\\<^sub>p, x\\<^sub>s) \\<in> Partitions x})\"\n\nlemma tag_Times_injI:\n  assumes a: \"tag_Times A B x = tag_Times A B y\"\n  and     c: \"x @ z \\<in> A \\<cdot> B\"\n  shows \"y @ z \\<in> A \\<cdot> B\"\nproof -\n  from c obtain u v where \n    h1: \"(u, v) \\<in> Partitions (x @ z)\" and\n    h2: \"u \\<in> A\" and\n    h3: \"v \\<in> B\" by (auto dest: conc_partitions_elim)\n  from h1 have \"x @ z = u @ v\" unfolding Partitions_def by simp\n  then obtain us \n    where \"(x = u @ us \\<and> us @ z = v) \\<or> (x @ us = u \\<and> z = us @ v)\"\n    by (auto simp add: append_eq_append_conv2)\n  moreover\n  { assume eq: \"x = u @ us\" \"us @ z = v\"\n    have \"(\\<approx>B `` {us}) \\<in> snd (tag_Times A B x)\"\n      unfolding Partitions_def tag_Times_def using h2 eq \n      by (auto simp add: str_eq_def)\n    then have \"(\\<approx>B `` {us}) \\<in> snd (tag_Times A B y)\"\n      using a by simp\n    then obtain u' us' where\n      q1: \"u' \\<in> A\" and\n      q2: \"\\<approx>B `` {us} = \\<approx>B `` {us'}\" and\n      q3: \"(u', us') \\<in> Partitions y\" \n      unfolding tag_Times_def by auto\n    from q2 h3 eq \n    have \"us' @ z \\<in> B\"\n      unfolding Image_def str_eq_def by auto\n    then have \"y @ z \\<in> A \\<cdot> B\" using q1 q3 \n      unfolding Partitions_def by auto\n  }\n  moreover\n  { assume eq: \"x @ us = u\" \"z = us @ v\"\n    have \"(\\<approx>A `` {x}) = fst (tag_Times A B x)\" \n      by (simp add: tag_Times_def)\n    then have \"(\\<approx>A `` {x}) = fst (tag_Times A B y)\"\n      using a by simp\n    then have \"\\<approx>A `` {x} = \\<approx>A `` {y}\" \n      by (simp add: tag_Times_def)\n    moreover \n    have \"x @ us \\<in> A\" using h2 eq by simp\n    ultimately \n    have \"y @ us \\<in> A\" using equiv_class_member \n      unfolding Image_def str_eq_def by blast\n    then have \"(y @ us) @ v \\<in> A \\<cdot> B\" \n      using h3 unfolding conc_def by blast\n    then have \"y @ z \\<in> A \\<cdot> B\" using eq by simp \n  }\n  ultimately show \"y @ z \\<in> A \\<cdot> B\" by blast\nqed\n\nlemma quot_conc_finiteI [intro]:\n  assumes fin1: \"finite (UNIV // \\<approx>A)\" \n  and     fin2: \"finite (UNIV // \\<approx>B)\" \n  shows \"finite (UNIV // \\<approx>(A \\<cdot> B))\"\nproof (rule_tac tag = \"tag_Times A B\" in tag_finite_imageD)\n  have \"\\<And>x y z. \\<lbrakk>tag_Times A B x = tag_Times A B y; x @ z \\<in> A \\<cdot> B\\<rbrakk> \\<Longrightarrow> y @ z \\<in> A \\<cdot> B\"\n    by (rule tag_Times_injI)\n       (auto simp add: tag_Times_def tag_eq_def)\n  then show \"=tag_Times A B= \\<subseteq> \\<approx>(A \\<cdot> B)\"\n    by (rule refined_intro)\n       (auto simp add: tag_eq_def)\nnext\n  have *: \"finite ((UNIV // \\<approx>A) \\<times> (Pow (UNIV // \\<approx>B)))\" \n    using fin1 fin2 by auto\n  show \"finite (range (tag_Times A B))\" \n    unfolding tag_Times_def\n    apply(rule finite_subset[OF _ *])\n    unfolding quotient_def\n    by auto\nqed\n\n\nsubsection {* Case for @{const \"Star\"} *}\n\nlemma star_partitions_elim:\n  assumes \"x @ z \\<in> A\\<star>\" \"x \\<noteq> []\"\n  shows \"\\<exists>(u, v) \\<in> Partitions (x @ z). prefix u x \\<and> u \\<in> A\\<star> \\<and> v \\<in> A\\<star>\"\nproof -\n  have \"([], x @ z) \\<in> Partitions (x @ z)\" \"prefix [] x\" \"[] \\<in> A\\<star>\" \"x @ z \\<in> A\\<star>\"\n    using assms by (auto simp add: Partitions_def prefix_def)\n  then show \"\\<exists>(u, v) \\<in> Partitions (x @ z). prefix u x \\<and> u \\<in> A\\<star> \\<and> v \\<in> A\\<star>\"\n    by blast\nqed\n\nlemma finite_set_has_max2: \n  \"\\<lbrakk>finite A; A \\<noteq> {}\\<rbrakk> \\<Longrightarrow> \\<exists> max \\<in> A. \\<forall> a \\<in> A. length a \\<le> length max\"\napply(induct rule:finite.induct)\napply(simp)\nby (metis (no_types) all_not_in_conv insert_iff linorder_le_cases order_trans)\n\nlemma finite_prefix_set: \n  shows \"finite {xa. prefix xa (x::'a list)}\"\napply (induct x rule:rev_induct, simp)\napply (subgoal_tac \"{xa. prefix xa (xs @ [x])} = {xa. prefix xa xs} \\<union> {xs}\")\nby (auto simp:prefix_def)\n\nlemma append_eq_cases:\n  assumes a: \"x @ y = m @ n\" \"m \\<noteq> []\"  \n  shows \"prefixeq x m \\<or> prefix m x\"\nunfolding prefixeq_def prefix_def using a\nby (auto simp add: append_eq_append_conv2)\n\nlemma star_spartitions_elim2:\n  assumes a: \"x @ z \\<in> A\\<star>\" \n  and     b: \"x \\<noteq> []\"\n  shows \"\\<exists>(u, v) \\<in> Partitions x. \\<exists> (u', v') \\<in> Partitions z. prefix u x \\<and> u \\<in> A\\<star> \\<and> v @ u' \\<in> A \\<and> v' \\<in> A\\<star>\"\nproof -\n  def S \\<equiv> \"{u | u v. (u, v) \\<in> Partitions x \\<and> prefix u x \\<and> u \\<in> A\\<star> \\<and> v @ z \\<in> A\\<star>}\"\n  have \"finite {u. prefix u x}\" by (rule finite_prefix_set)\n  then have \"finite S\" unfolding S_def\n    by (rule rev_finite_subset) (auto)\n  moreover \n  have \"S \\<noteq> {}\" using a b unfolding S_def Partitions_def\n    by (auto simp: prefix_def)\n  ultimately have \"\\<exists> u_max \\<in> S. \\<forall> u \\<in> S. length u \\<le> length u_max\"  \n    using finite_set_has_max2 by blast\n  then obtain u_max v \n    where h0: \"(u_max, v) \\<in> Partitions x\"\n    and h1: \"prefix u_max x\" \n    and h2: \"u_max \\<in> A\\<star>\" \n    and h3: \"v @ z \\<in> A\\<star>\"  \n    and h4: \"\\<forall> u v. (u, v) \\<in> Partitions x \\<and> prefix u x \\<and> u \\<in> A\\<star> \\<and> v @ z \\<in> A\\<star> \\<longrightarrow> length u \\<le> length u_max\"\n    unfolding S_def Partitions_def by blast\n  have q: \"v \\<noteq> []\" using h0 h1 b unfolding Partitions_def by auto\n  from h3 obtain a b\n    where i1: \"(a, b) \\<in> Partitions (v @ z)\"\n    and   i2: \"a \\<in> A\"\n    and   i3: \"b \\<in> A\\<star>\"\n    and   i4: \"a \\<noteq> []\"\n    unfolding Partitions_def\n    using q by (auto dest: star_decom)\n  have \"prefixeq v a\"\n  proof (rule ccontr)\n    assume a: \"\\<not>(prefixeq v a)\"\n    from i1 have i1': \"a @ b = v @ z\" unfolding Partitions_def by simp\n    then have \"prefixeq a v \\<or> prefix v a\" using append_eq_cases q by blast\n    then have q: \"prefix a v\" using a unfolding prefix_def prefixeq_def by auto\n    then obtain as where eq: \"a @ as = v\" unfolding prefix_def prefixeq_def by auto\n    have \"(u_max @ a, as) \\<in> Partitions x\" using eq h0 unfolding Partitions_def by auto\n    moreover\n    have \"prefix (u_max @ a) x\" using h0 eq q unfolding Partitions_def prefix_def prefixeq_def by auto\n    moreover\n    have \"u_max @ a \\<in> A\\<star>\" using i2 h2 by simp\n    moreover\n    have \"as @ z \\<in> A\\<star>\" using i1' i2 i3 eq by auto\n    ultimately have \"length (u_max @ a) \\<le> length u_max\" using h4 by blast\n    with i4 show \"False\" by auto\n  qed\n  with i1 obtain za zb\n    where k1: \"v @ za = a\"\n    and   k2: \"(za, zb) \\<in> Partitions z\" \n    and   k4: \"zb = b\" \n    unfolding Partitions_def prefix_def\n    by (auto simp add: append_eq_append_conv2)\n  show \"\\<exists> (u, v) \\<in> Partitions x. \\<exists> (u', v') \\<in> Partitions z. prefix u x \\<and> u \\<in> A\\<star> \\<and> v @ u' \\<in> A \\<and> v' \\<in> A\\<star>\"\n    using h0 h1 h2 i2 i3 k1 k2 k4 unfolding Partitions_def by blast\nqed\n\ndefinition \n  tag_Star :: \"'a lang \\<Rightarrow> 'a list \\<Rightarrow> ('a lang) set\"\nwhere\n  \"tag_Star A \\<equiv> \\<lambda>x. {\\<approx>A `` {v} | u v. prefix u x \\<and> u \\<in> A\\<star> \\<and> (u, v) \\<in> Partitions x}\"\n\nlemma tag_Star_non_empty_injI:\n  assumes a: \"tag_Star A x = tag_Star A y\"\n  and     c: \"x @ z \\<in> A\\<star>\"\n  and     d: \"x \\<noteq> []\"\n  shows \"y @ z \\<in> A\\<star>\"\nproof -\n  obtain u v u' v' \n    where a1: \"(u,  v) \\<in> Partitions x\" \"(u', v')\\<in> Partitions z\"\n    and   a2: \"prefix u x\"\n    and   a3: \"u \\<in> A\\<star>\"\n    and   a4: \"v @ u' \\<in> A\" \n    and   a5: \"v' \\<in> A\\<star>\"\n    using c d by (auto dest: star_spartitions_elim2)\n  have \"(\\<approx>A) `` {v} \\<in> tag_Star A x\" \n    apply(simp add: tag_Star_def Partitions_def str_eq_def)\n    using a1 a2 a3 by (auto simp add: Partitions_def)\n  then have \"(\\<approx>A) `` {v} \\<in> tag_Star A y\" using a by simp\n  then obtain u1 v1 \n    where b1: \"v \\<approx>A v1\"\n    and   b3: \"u1 \\<in> A\\<star>\"\n    and   b4: \"(u1, v1) \\<in> Partitions y\"\n    unfolding tag_Star_def by auto\n  have c: \"v1 @ u' \\<in> A\\<star>\" using b1 a4 unfolding str_eq_def by simp\n  have \"u1 @ (v1 @ u') @ v' \\<in> A\\<star>\"\n    using b3 c a5 by (simp only: append_in_starI)\n  then show \"y @ z \\<in> A\\<star>\" using b4 a1 \n    unfolding Partitions_def by auto\nqed\n    \nlemma tag_Star_empty_injI:\n  assumes a: \"tag_Star A x = tag_Star A y\"\n  and     c: \"x @ z \\<in> A\\<star>\"\n  and     d: \"x = []\"\n  shows \"y @ z \\<in> A\\<star>\"\nproof -\n  from a have \"{} = tag_Star A y\" unfolding tag_Star_def using d by auto \n  then have \"y = []\"\n    unfolding tag_Star_def Partitions_def prefix_def prefixeq_def\n    by (auto) (metis Nil_in_star append_self_conv2)\n  then show \"y @ z \\<in> A\\<star>\" using c d by simp\nqed\n\nlemma quot_star_finiteI [intro]:\n  assumes finite1: \"finite (UNIV // \\<approx>A)\"\n  shows \"finite (UNIV // \\<approx>(A\\<star>))\"\nproof (rule_tac tag = \"tag_Star A\" in tag_finite_imageD)\n  have \"\\<And>x y z. \\<lbrakk>tag_Star A x = tag_Star A y; x @ z \\<in> A\\<star>\\<rbrakk> \\<Longrightarrow> y @ z \\<in> A\\<star>\"\n    by (case_tac \"x = []\") (blast intro: tag_Star_empty_injI tag_Star_non_empty_injI)+\n  then show \"=(tag_Star A)= \\<subseteq> \\<approx>(A\\<star>)\"\n    by (rule refined_intro) (auto simp add: tag_eq_def)\nnext\n  have *: \"finite (Pow (UNIV // \\<approx>A))\" \n     using finite1 by auto\n  show \"finite (range (tag_Star A))\"\n    unfolding tag_Star_def \n    by (rule finite_subset[OF _ *])\n       (auto simp add: quotient_def)\nqed\n\nsubsection {* The conclusion of the second direction *}\n\nlemma Myhill_Nerode2:\n  fixes r::\"'a rexp\"\n  shows \"finite (UNIV // \\<approx>(lang r))\"\nby (induct r) (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/Myhill-Nerode/Myhill_2.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972684083608, "lm_q2_score": 0.8056321936479701, "lm_q1q2_score": 0.7013811871317583}}
{"text": "section \\<open>Monotonic Boolean Transformers\\<close>\n\ntheory Mono_Bool_Tran\nimports\n  LatticeProperties.Complete_Lattice_Prop\n  LatticeProperties.Conj_Disj\nbegin\n\ntext\\<open>\nThe type of monotonic transformers is the type associated to the set of monotonic\nfunctions from a partially ordered set (poset) to itself. The type of monotonic\ntransformers with the pointwise extended order is also a poset. \nThe monotonic transformers with composition and identity \nform a monoid, and the monoid operation is compatible with the order.\n\nGradually we extend the algebraic structure of monotonic transformers to\nlattices, and complete lattices. We also introduce a dual operator \n($(\\mathsf{dual}\\;f) p = - f (-p)$) on monotonic transformers over\na boolean algebra. However the monotonic transformers over a boolean\nalgebra are not closed to the pointwise extended negation operator.\n\nFinally we introduce an iteration operator on monotonic transformers\nover a complete lattice.\n\\<close>\n\nunbundle lattice_syntax\n\nlemma Inf_comp_fun:\n  \"\\<Sqinter>M \\<circ> f = (\\<Sqinter>m\\<in>M. m \\<circ> f)\"\n  by (simp add: fun_eq_iff image_comp)\n\nlemma INF_comp_fun:\n  \"(\\<Sqinter>a\\<in>A. g a) \\<circ> f = (\\<Sqinter>a\\<in>A. g a \\<circ> f)\"\n  by (simp add: fun_eq_iff image_comp)\n\nlemma Sup_comp_fun:\n  \"\\<Squnion>M \\<circ> f = (\\<Squnion>m\\<in>M. m \\<circ> f)\"\n  by (simp add: fun_eq_iff image_comp)\n\nlemma SUP_comp_fun:\n  \"(\\<Squnion>a\\<in>A. g a) \\<circ> f = (\\<Squnion>a\\<in>A. g a \\<circ> f)\"\n  by (simp add: fun_eq_iff image_comp)\n\nlemma (in order) mono_const [simp]:\n  \"mono (\\<lambda>_. c)\"\n  by (auto intro: monoI)\n\nlemma (in order) mono_id [simp]:\n  \"mono id\"\n  by (auto intro: order_class.monoI)\n\nlemma (in order) mono_comp [simp]:\n  \"mono f \\<Longrightarrow> mono g \\<Longrightarrow> mono (f \\<circ> g)\"\n  by (auto intro!: monoI elim!: monoE order_class.monoE)\n\nlemma (in bot) mono_bot [simp]:\n  \"mono \\<bottom>\"\n  by (auto intro: monoI)\n\nlemma (in top) mono_top [simp]:\n  \"mono \\<top>\"\n  by (auto intro: monoI)\n\nlemma (in semilattice_inf) mono_inf [simp]:\n  assumes \"mono f\" and \"mono g\"\n  shows \"mono (f \\<sqinter> g)\"\nproof\n  fix a b\n  assume \"a \\<le> b\"\n  have \"f a \\<sqinter> g a \\<le> f a\" by simp\n  also from \\<open>mono f\\<close> \\<open>a \\<le> b\\<close> have \"\\<dots> \\<le> f b\" by (auto elim: monoE)\n  finally have *: \"f a \\<sqinter> g a \\<le> f b\" .\n  have \"f a \\<sqinter> g a \\<le> g a\" by simp\n  also from \\<open>mono g\\<close> \\<open>a \\<le> b\\<close> have \"\\<dots> \\<le> g b\" by (auto elim: monoE)\n  finally have **: \"f a \\<sqinter> g a \\<le> g b\" .\n  from * ** show \"(f \\<sqinter> g) a \\<le> (f \\<sqinter> g) b\" by auto\nqed\n\nlemma (in semilattice_sup) mono_sup [simp]:\n  assumes \"mono f\" and \"mono g\"\n  shows \"mono (f \\<squnion> g)\"\nproof\n  fix a b\n  assume \"a \\<le> b\"\n  from \\<open>mono f\\<close> \\<open>a \\<le> b\\<close> have \"f a \\<le> f b\" by (auto elim: monoE)\n  also have \"f b \\<le> f b \\<squnion> g b\" by simp\n  finally have *: \"f a \\<le> f b \\<squnion> g b\" .\n  from \\<open>mono g\\<close> \\<open>a \\<le> b\\<close> have \"g a \\<le> g b\" by (auto elim: monoE)\n  also have \"g b \\<le> f b \\<squnion> g b\" by simp\n  finally have **: \"g a \\<le> f b \\<squnion> g b\" .\n  from * ** show \"(f \\<squnion> g) a \\<le> (f \\<squnion> g) b\" by auto\nqed\n\nlemma (in complete_lattice) mono_Inf [simp]:\n  assumes \"A \\<subseteq> {f :: 'a \\<Rightarrow> 'b:: complete_lattice. mono f}\"\n  shows \"mono (\\<Sqinter>A)\"\nproof\n  fix a b\n  assume \"a \\<le> b\"\n  { fix f\n    assume \"f \\<in> A\"\n    with assms have \"mono f\" by auto\n    with \\<open>a \\<le> b\\<close> have \"f a \\<le> f b\" by (auto elim: monoE)\n  }\n  then have \"(\\<Sqinter>f\\<in>A. f a) \\<le> (\\<Sqinter>f\\<in>A. f b)\"\n    by (auto intro: complete_lattice_class.INF_greatest complete_lattice_class.INF_lower2)\n  then show \"(\\<Sqinter>A) a \\<le> (\\<Sqinter>A) b\" by simp\nqed\n\nlemma (in complete_lattice) mono_Sup [simp]:\n  assumes \"A \\<subseteq> {f :: 'a \\<Rightarrow> 'b:: complete_lattice. mono f}\"\n  shows \"mono (\\<Squnion>A)\"\nproof\n  fix a b\n  assume \"a \\<le> b\"\n  { fix f\n    assume \"f \\<in> A\"\n    with assms have \"mono f\" by auto\n    with \\<open>a \\<le> b\\<close> have \"f a \\<le> f b\" by (auto elim: monoE)\n  }\n  then have \"(\\<Squnion>f\\<in>A. f a) \\<le> (\\<Squnion>f\\<in>A. f b)\"\n    by (auto intro: complete_lattice_class.SUP_least complete_lattice_class.SUP_upper2)\n  then show \"(\\<Squnion>A) a \\<le> (\\<Squnion>A) b\" by simp\nqed\n\ntypedef (overloaded) 'a MonoTran = \"{f::'a::order \\<Rightarrow> 'a . mono f}\"\nproof\n  show \"id \\<in> ?MonoTran\" by simp\nqed\n\n\n\nsetup_lifting type_definition_MonoTran\n\ninstantiation MonoTran :: (order) order\nbegin\n\nlift_definition less_eq_MonoTran :: \"'a MonoTran \\<Rightarrow> 'a MonoTran \\<Rightarrow> bool\"\n  is less_eq .\n\nlift_definition less_MonoTran :: \"'a MonoTran \\<Rightarrow> 'a MonoTran \\<Rightarrow> bool\"\n  is less .\n\ninstance\n  by intro_classes (transfer, auto intro: order_antisym)+\n\nend\n\ninstantiation MonoTran :: (order) monoid_mult\nbegin\n\nlift_definition one_MonoTran :: \"'a MonoTran\"\n  is id\n  by (fact mono_id)\n\nlift_definition times_MonoTran :: \"'a MonoTran \\<Rightarrow> 'a MonoTran \\<Rightarrow> 'a MonoTran\"\n  is comp\n  by (fact mono_comp)\n\ninstance\n  by intro_classes (transfer, auto)+\n\nend\n\ninstantiation MonoTran :: (order_bot) order_bot\nbegin\n\nlift_definition bot_MonoTran :: \"'a MonoTran\"\n  is \\<bottom>\n  by (fact mono_bot)\n\ninstance\n  by intro_classes (transfer, simp)\n\nend\n\ninstantiation MonoTran :: (order_top) order_top\nbegin\n\nlift_definition top_MonoTran :: \"'a MonoTran\"\n  is \\<top>\n  by (fact mono_top)\n\ninstance\n  by intro_classes (transfer, simp)\n\nend\n\ninstantiation MonoTran :: (lattice) lattice\nbegin\n\nlift_definition inf_MonoTran :: \"'a MonoTran \\<Rightarrow> 'a MonoTran \\<Rightarrow> 'a MonoTran\"\n  is inf\n  by (fact mono_inf)\n\nlift_definition sup_MonoTran :: \"'a MonoTran \\<Rightarrow> 'a MonoTran \\<Rightarrow> 'a MonoTran\"\n  is sup\n  by (fact mono_sup)\n\ninstance\n  by intro_classes (transfer, simp)+\n\nend\n\ninstance MonoTran :: (distrib_lattice) distrib_lattice\n  by intro_classes (transfer, rule sup_inf_distrib1)\n\ninstantiation MonoTran :: (complete_lattice) complete_lattice\nbegin\n\nlift_definition Inf_MonoTran :: \"'a MonoTran set \\<Rightarrow> 'a MonoTran\"\n  is Inf\n  by (rule mono_Inf) auto\n\nlift_definition Sup_MonoTran :: \"'a MonoTran set \\<Rightarrow> 'a MonoTran\"\n  is Sup\n  by (rule mono_Sup) auto\n\ninstance\n  by intro_classes (transfer, simp add: Inf_lower Sup_upper Inf_greatest Sup_least)+\n\nend\n\ncontext includes lifting_syntax\nbegin\n\n\n\nlemma [transfer_rule]:\n  \"(rel_set A ===> (A ===> pcr_MonoTran HOL.eq) ===> pcr_MonoTran HOL.eq) (\\<lambda>A f. \\<Squnion>(f ` A)) (\\<lambda>A f. \\<Squnion>(f ` A))\"\n  by transfer_prover\n\nend\n\ninstance MonoTran :: (complete_distrib_lattice) complete_distrib_lattice\nproof (intro_classes, transfer)\n  fix A :: \"('a \\<Rightarrow> 'a) set set\"\n  assume \" \\<forall>A\\<in>A. Ball A mono\"\n  from this have [simp]: \"{f ` A |f. \\<forall>Y\\<in>A. f Y \\<in> Y} = {x. (\\<exists>f. (\\<forall>x. (\\<forall>x\\<in>x. mono x) \\<longrightarrow> mono (f x)) \\<and> x = f ` A \\<and> (\\<forall>Y\\<in>A. f Y \\<in> Y)) \\<and> (\\<forall>x\\<in>x. mono x)}\"\n    apply safe\n      apply (rule_tac x = \"\\<lambda> x . if x \\<in> A then f x else \\<bottom>\" in exI)\n      apply (simp add: if_split image_def)\n    by blast+\n\n  show \" \\<Sqinter>(Sup ` A) \\<le> \\<Squnion>(Inf ` {x. (\\<exists>f\\<in>Collect (pred_fun (\\<lambda>A. Ball A mono) mono). x = f ` A \\<and> (\\<forall>Y\\<in>A. f Y \\<in> Y)) \\<and> Ball x mono})\"\n    by (simp add: Inf_Sup)\nqed\n\n\n\ndefinition\n  \"dual_fun (f::'a::boolean_algebra \\<Rightarrow> 'a) = uminus \\<circ> f \\<circ> uminus\"\n\nlemma dual_fun_apply [simp]:\n  \"dual_fun f p = - f (- p)\"\n  by (simp add: dual_fun_def)\n\nlemma mono_dual_fun [simp]:\n  \"mono f \\<Longrightarrow> mono (dual_fun f)\"\n  apply (rule monoI)\n  apply (erule monoE)\n  apply auto\n  done\n\nlemma (in order) mono_inf_fun [simp]:\n  fixes x :: \"'b::semilattice_inf\"\n  shows \"mono (inf x)\"\n  by (auto intro!: order_class.monoI semilattice_inf_class.inf_mono)\n\nlemma (in order) mono_sup_fun [simp]:\n  fixes x :: \"'b::semilattice_sup\"\n  shows \"mono (sup x)\"\n  by (auto intro!: order_class.monoI semilattice_sup_class.sup_mono)\n\nlemma mono_comp_fun:\n  fixes f :: \"'a::order \\<Rightarrow> 'b::order\"\n  shows \"mono f \\<Longrightarrow> mono ((\\<circ>) f)\"\n  by (rule monoI) (auto simp add: le_fun_def elim: monoE)\n\ndefinition\n  \"Omega_fun f g = inf g \\<circ> comp f\"\n\nlemma Omega_fun_apply [simp]:\n  \"Omega_fun f g h p = (g p \\<sqinter> f (h p))\"\n  by (simp add: Omega_fun_def)\n\nlemma mono_Omega_fun [simp]:\n  \"mono f \\<Longrightarrow> mono (Omega_fun f g)\"\n  unfolding Omega_fun_def\n  by (auto intro: mono_comp mono_comp_fun)\n\nlemma mono_mono_Omega_fun [simp]:\n  fixes f :: \"'b::order \\<Rightarrow> 'a::semilattice_inf\" and g :: \"'c::semilattice_inf \\<Rightarrow> 'a\"\n  shows \"mono f \\<Longrightarrow> mono g \\<Longrightarrow> mono_mono (Omega_fun f g)\"\n  apply (auto simp add: mono_mono_def Omega_fun_def)\n  apply (rule mono_comp)\n  apply (rule mono_inf_fun)\n  apply (rule mono_comp_fun)\n  apply assumption\n  done\n\ndefinition \n  \"omega_fun f = lfp (Omega_fun f id)\"\n\ndefinition\n  \"star_fun f = gfp (Omega_fun f id)\"\n\nlemma mono_omega_fun [simp]:\n  fixes f :: \"'a::complete_lattice \\<Rightarrow> 'a\"\n  assumes \"mono f\"\n  shows \"mono (omega_fun f)\"\nproof\n  fix a b :: 'a\n  assume \"a \\<le> b\"\n  from assms have \"mono (lfp (Omega_fun f id))\"\n    by (auto intro: mono_mono_Omega_fun)\n  with \\<open>a \\<le> b\\<close> show \"omega_fun f a \\<le> omega_fun f b\"\n    by (auto simp add: omega_fun_def elim: monoE)\nqed\n\nlemma mono_star_fun [simp]:\n  fixes f :: \"'a::complete_lattice \\<Rightarrow> 'a\"\n  assumes \"mono f\"\n  shows \"mono (star_fun f)\"\nproof\n  fix a b :: 'a\n  assume \"a \\<le> b\"\n  from assms have \"mono (gfp (Omega_fun f id))\"\n    by (auto intro: mono_mono_Omega_fun)\n  with \\<open>a \\<le> b\\<close> show \"star_fun f a \\<le> star_fun f b\"\n    by (auto simp add: star_fun_def elim: monoE)\nqed\n\nlemma lfp_omega_lowerbound:\n  \"mono f \\<Longrightarrow> Omega_fun f g A \\<le> A \\<Longrightarrow> omega_fun f \\<circ> g \\<le> A\"\n  apply (simp add: omega_fun_def)\n  apply (rule_tac P = \"\\<lambda> x . x \\<circ> g \\<le> A\" and f = \"Omega_fun f id\" in lfp_ordinal_induct)\n  apply simp_all\n  apply (simp add: le_fun_def o_def inf_fun_def id_def Omega_fun_def)\n  apply auto\n  apply (rule_tac y = \"f (A x) \\<sqinter> g x\" in order_trans)\n  apply simp_all\n  apply (rule_tac y = \"f (S (g x))\" in order_trans)\n  apply simp_all\n  apply (simp add: mono_def) apply (auto simp add: ac_simps)\n  apply (unfold Sup_comp_fun)\n  apply (rule SUP_least)\n  by auto\n\nlemma gfp_omega_upperbound:\n  \"mono f \\<Longrightarrow> A \\<le> Omega_fun f g A \\<Longrightarrow> A \\<le> star_fun f \\<circ> g\"\n  apply (simp add: star_fun_def)\n  apply (rule_tac P = \"\\<lambda> x . A \\<le> x \\<circ> g\" and f = \"Omega_fun f id\" in gfp_ordinal_induct)\n  apply simp_all\n  apply (simp add: le_fun_def o_def inf_fun_def id_def Omega_fun_def)\n  apply auto\n  apply (rule_tac y = \"f (A x) \\<sqinter> g x\" in order_trans)\n  apply simp_all\n  apply (rule_tac y = \"f (A x)\" in order_trans)\n  apply simp_all\n  apply (simp add: mono_def)\n  apply (unfold Inf_comp_fun)\n  apply (rule INF_greatest)\n  by auto\n\nlemma lfp_omega_greatest:\n  assumes \"\\<And>u. Omega_fun f g u \\<le> u \\<Longrightarrow> A \\<le> u\"\n  shows \"A \\<le> omega_fun f \\<circ> g\"\n  apply (unfold omega_fun_def)\n  apply (simp add: lfp_def)\n  apply (unfold Inf_comp_fun)\n  apply (rule INF_greatest)\n  apply simp\n  apply (rule assms)\n  apply (simp add: le_fun_def)\n  done\n\nlemma gfp_star_least:\n  assumes \"\\<And>u. u \\<le> Omega_fun f g u \\<Longrightarrow> u \\<le> A\"\n  shows \"star_fun f \\<circ> g \\<le> A\"\n  apply (unfold star_fun_def)\n  apply (simp add: gfp_def)\n  apply (unfold Sup_comp_fun)\n  apply (rule SUP_least)\n  apply simp\n  apply (rule assms)\n  apply (simp add: le_fun_def)\n  done\n\nlemma lfp_omega:\n  \"mono f \\<Longrightarrow> omega_fun f \\<circ> g = lfp (Omega_fun f g)\"\n  apply (rule antisym)\n  apply (rule lfp_omega_lowerbound)\n  apply simp_all\n  apply (simp add: lfp_def)\n  apply (rule Inf_greatest)\n  apply safe\n  apply (rule_tac y = \"Omega_fun f g x\" in order_trans)\n  apply simp_all\n  apply (rule_tac f = \" Omega_fun f g\" in monoD)\n  apply simp_all\n  apply (rule Inf_lower)\n  apply simp\n  apply (rule lfp_omega_greatest)\n  apply (simp add: lfp_def)\n  apply (rule Inf_lower)\n  by simp\n\nlemma gfp_star:\n  \"mono f \\<Longrightarrow> star_fun f \\<circ> g = gfp (Omega_fun f g)\"\n  apply (rule antisym)\n  apply (rule gfp_star_least)\n  apply (simp add: gfp_def)\n  apply (rule Sup_upper, simp)\n  apply (rule gfp_omega_upperbound)\n  apply simp_all\n  apply (simp add: gfp_def)\n  apply (rule Sup_least)\n  apply safe\n  apply (rule_tac y = \"Omega_fun f g x\" in order_trans)\n  apply simp_all\n  apply (rule_tac f = \" Omega_fun f g\" in monoD)\n  apply simp_all\n  apply (rule Sup_upper)\n  by simp\n\ndefinition\n  \"assert_fun p q = (p \\<sqinter> q :: 'a::semilattice_inf)\"\n\nlemma mono_assert_fun [simp]:\n  \"mono (assert_fun p)\"\n  apply (simp add: assert_fun_def mono_def, safe)\n  by (rule_tac y = x in order_trans, simp_all)\n\nlemma assert_fun_le_id [simp]: \"assert_fun p \\<le> id\"\n  by (simp add: assert_fun_def id_def le_fun_def)\n\nlemma assert_fun_disjunctive [simp]: \"assert_fun (p::'a::distrib_lattice) \\<in> Apply.disjunctive\"\n  by (simp add: assert_fun_def Apply.disjunctive_def inf_sup_distrib)\n\ndefinition\n  \"assertion_fun = range assert_fun\"\n  \nlemma assert_cont:\n  \"(x :: 'a::boolean_algebra \\<Rightarrow> 'a)  \\<le> id \\<Longrightarrow> x \\<in> Apply.disjunctive \\<Longrightarrow> x = assert_fun (x \\<top>)\"\n  apply (rule antisym)\n  apply (simp_all add: le_fun_def assert_fun_def, safe)\n  apply (rule_tac f = x in  monoD, simp_all)\n  apply (subgoal_tac \"x top = sup (x xa) (x (-xa))\")\n  apply simp\n  apply (subst inf_sup_distrib)\n  apply simp\n  apply (rule_tac y = \"inf (- xa) xa\" in order_trans)\n  supply [[simproc del: boolean_algebra_cancel_inf]]\n  apply (simp del: compl_inf_bot)\n  apply (rule_tac y = \"x (- xa)\" in order_trans)\n  apply simp\n  apply simp\n  apply simp\n  apply (cut_tac x = x and y = xa and z = \"-xa\" in Apply.disjunctiveD, simp)\n  apply (subst (asm) sup_commute)\n  apply (subst (asm) compl_sup_top)\n  by simp\n\nlemma assertion_fun_disj_less_one: \"assertion_fun = Apply.disjunctive \\<inter> {x::'a::boolean_algebra \\<Rightarrow> 'a . x \\<le> id}\"\n  apply safe\n  apply (simp_all add: assertion_fun_def, auto simp add: image_def)\n  apply (rule_tac x = \"x \\<top>\" in exI)\n  by (rule assert_cont, simp_all)\n\nlemma assert_fun_dual: \"((assert_fun p) o \\<top>) \\<sqinter> (dual_fun (assert_fun p)) = assert_fun p\"\n  by (simp add: fun_eq_iff inf_fun_def dual_fun_def o_def assert_fun_def top_fun_def inf_sup_distrib)\n\nlemma assertion_fun_dual: \"x \\<in> assertion_fun \\<Longrightarrow> (x o \\<top>) \\<sqinter> (dual_fun x) = x\"\n  by (simp add: assertion_fun_def, safe, simp add: assert_fun_dual)\n\nlemma assertion_fun_MonoTran [simp]: \"x \\<in> assertion_fun \\<Longrightarrow> mono x\"\n  by (unfold assertion_fun_def, auto)\n\nlemma assertion_fun_le_one [simp]: \"x \\<in> assertion_fun \\<Longrightarrow> x \\<le> id\"\n  by (unfold assertion_fun_def, auto)\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/MonoBoolTranAlgebra/Mono_Bool_Tran.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972549785201, "lm_q2_score": 0.8056321936479701, "lm_q1q2_score": 0.7013811763122464}}
{"text": "theory TS_To_XC\n  imports TS_To_XC_aux\nbegin\n\nsection \"useful definitions and the reduction function\"\n\ndefinition literal_sets\n  :: \"'a three_sat  \\<Rightarrow> 'a xc_element set set\" where\n\"literal_sets F = {{l}| l. l \\<in> (literals_of_sat F)}\"\n\ndefinition clauses_with_literals \n  :: \"'a three_sat \\<Rightarrow> 'a xc_element set set\" where\n\"clauses_with_literals F = {{C c, l} |c l. C c \\<in> (clauses_of_sat F) \\<and> l \\<in> (literals_of_sat F) \n        \\<and> l \\<in> {L a c | a. a \\<in> c}}\"\n\ndefinition var_true_literals\n  :: \"'a three_sat \\<Rightarrow> 'a xc_element set set\" where \n\"var_true_literals F = \n  {{V v} \\<union> {l. l \\<in> (literals_of_sat F) \n  \\<and> (\\<exists>c. C c\\<in> (clauses_of_sat F) \\<and> L (Neg v) c = l)} |v. V v \\<in> (vars_of_sat F)}\"\n\ndefinition var_false_literals\n    :: \"'a three_sat \\<Rightarrow> 'a xc_element set set\" where \n\"var_false_literals F = \n  {{V v} \\<union> {l. l \\<in> (literals_of_sat F) \n  \\<and> (\\<exists>c. C c\\<in> (clauses_of_sat F) \\<and> L (Pos v) c = l)} |v. V v \\<in> (vars_of_sat F)}\"\n\nabbreviation \"comp_X F \\<equiv> \n  vars_of_sat F \\<union> clauses_of_sat F \\<union> literals_of_sat F\"\nabbreviation \"comp_S F \\<equiv> \n    literal_sets F \\<union> clauses_with_literals F \n  \\<union> var_true_literals F \\<union> var_false_literals F\"\n\ndefinition ts_xc :: \"'a three_sat \\<Rightarrow> 'a xc_element set * 'a xc_element set set\" where \n\"ts_xc F = (comp_X F, comp_S F)\"\n\nlemma ts_xc_is_collection: \"\\<Union> (comp_S F) \\<subseteq> (comp_X F)\"\nproof -\n  let ?vars = \"vars_of_sat F\"\n  let ?clauses = \"clauses_of_sat F\"\n  let ?literals = \"literals_of_sat F\"\n\n  let ?ls = \"literal_sets F\"\n  let ?cs = \"clauses_with_literals F\"\n  let ?vt = \"var_true_literals F\"\n  let ?vf = \"var_false_literals F\"\n\n  have x_part: \"(comp_X F) = ?vars \\<union> ?clauses \\<union> ?literals\"\n    using ts_xc_def[of F] \n    by (auto simp: Let_def)\n  have s_part: \"(comp_S F) = ?ls \\<union> ?cs \\<union> ?vt \\<union> ?vf\"\n    using ts_xc_def[of F] \n    by (auto simp: Let_def)\n  have \"\\<Union>?ls = ?literals\" \n    unfolding literal_sets_def \n    by blast \n  moreover have \"\\<Union>?cs \\<subseteq> ?literals \\<union> ?clauses\" \n    unfolding clauses_with_literals_def \n    by blast\n  moreover have \"\\<Union>?vt \\<subseteq> ?literals \\<union> ?vars\"\n    unfolding var_true_literals_def \n    by blast\n  moreover have \"\\<Union>?vf \\<subseteq> ?literals \\<union> ?vars\" \n    unfolding var_false_literals_def \n    by blast\n  ultimately have \"\\<Union> (?ls \\<union> ?cs \\<union> ?vt \\<union> ?vf) \\<subseteq> ?vars \\<union> ?clauses \\<union> ?literals\"\n    by blast\n  with x_part s_part show ?thesis \n    by force\nqed \n\nsection \"the proof for the soundness\"\n\nsubsection \"the construction of the cover\"\n\ndefinition constr_cover_clause\n  :: \"'a lit set \\<Rightarrow> ('a \\<Rightarrow> bool) \\<Rightarrow> 'a xc_element set set\" where \n\"constr_cover_clause c \\<sigma> = \n  (SOME s. \\<exists>p \\<in> c. (\\<sigma>\\<up>) p \\<and> s = {{C c, L p c}} \\<union> {{L q c} | q. q \\<in> c \\<and> q \\<noteq> p \\<and> (\\<sigma>\\<up>) q})\" \n\nlemma constr_cover_clause_unfold:\nassumes \"\\<sigma> \\<Turnstile> F\" \"c \\<in> set F\"\nshows \"\\<exists>p\\<in>c. (\\<sigma>\\<up>) p \\<and> constr_cover_clause c \\<sigma> = {{C c, L p c}} \\<union> {{L q c} | q. q \\<in> c \\<and> q \\<noteq> p \\<and> (\\<sigma>\\<up>) q}\"\nproof- \n  from assms have \"\\<exists>p \\<in>c. (\\<sigma>\\<up>) p\"\n    unfolding models_def lift_def \n    by blast\n  thus \"\\<exists>p\\<in>c. (\\<sigma>\\<up>) p \\<and> constr_cover_clause c \\<sigma> = {{C c, L p c}} \\<union> {{L q c} | q. q \\<in> c \\<and> q \\<noteq> p \\<and> (\\<sigma>\\<up>) q}\"\n   unfolding constr_cover_clause_def\n   apply auto\n   apply (rule someI_ex)\n   by blast\nqed \n  \ndefinition vars_sets \n  :: \"'a three_sat \\<Rightarrow> ('a \\<Rightarrow> bool) \\<Rightarrow> 'a xc_element set set\" where \n\"vars_sets F \\<sigma> =\n  {x_set | x_set. \\<exists>x \\<in> vars F.\n       (if (\\<sigma>\\<up>) (Pos x) then (V x) \\<in> x_set \\<and> x_set \\<in> var_true_literals F\n        else (V x) \\<in> x_set \\<and> x_set \\<in> var_false_literals F)}\"\n\ndefinition clause_sets\n  :: \"'a three_sat \\<Rightarrow> ('a \\<Rightarrow> bool) \\<Rightarrow> 'a xc_element set set set\" where \n  \"clause_sets F \\<sigma> = \n      {constr_cover_clause c \\<sigma> |c. c \\<in> set F}\"\n\ndefinition constr_cover \n  :: \"'a three_sat \\<Rightarrow> ('a \\<Rightarrow> bool) \\<Rightarrow> 'a xc_element set set\" where \n\"constr_cover F \\<sigma> \\<equiv> \n  (if F \\<in> cnf_sat \n  then vars_sets F \\<sigma> \\<union> \\<Union> (clause_sets F \\<sigma>)\n  else {})\"\n\nsubsubsection \"The constructed set is a collection\"\n\nlemma constr_cover_clause_is_collection:\nassumes \"\\<sigma> \\<Turnstile> F\" \"c \\<in> set F\"\n shows \"constr_cover_clause c \\<sigma> \\<subseteq> (comp_S F)\"\nproof standard\n  let ?s = \"constr_cover_clause c \\<sigma>\"\n  fix x   \n  assume prem: \"x \\<in> ?s\"\n  from assms have \"\\<exists>p \\<in>c. (\\<sigma>\\<up>) p\"\n    unfolding models_def lift_def \n    by blast\n  from assms have  \"\\<exists>p\\<in>c. (\\<sigma>\\<up>) p \\<and> ?s = {{C c, L p c}} \\<union> {{L q c} | q. q \\<in> c \\<and> q \\<noteq> p \\<and> (\\<sigma>\\<up>) q}\"\n   using constr_cover_clause_unfold \n   by blast\n  then obtain p where \n    p_def: \"?s = {{C c, L p c}} \\<union> {{L q c} | q. q \\<in> c \\<and> q \\<noteq> p \\<and> (\\<sigma>\\<up>) q}\" \n      \"(\\<sigma>\\<up>) p\" \"p \\<in> c\"\n     using \\<open>\\<exists>p \\<in>c. (\\<sigma>\\<up>) p\\<close> by blast\n  with assms(2) have \"\\<forall>p \\<in> c. {L p c} \\<in> literal_sets F\"\n    unfolding literal_sets_def literals_of_sat_def \n    by fastforce\n  hence \"\\<forall>p \\<in> c. {{L q c} | q. q \\<in> c \\<and> q \\<noteq> p \\<and> (\\<sigma>\\<up>) q} \\<subseteq> literal_sets F\"\n    by blast\n  moreover from assms(2) have \"\\<forall>p \\<in> c. {C c, L p c} \\<in> clauses_with_literals F\"\n    unfolding clauses_with_literals_def literals_of_sat_def\n    by force \n  ultimately have \"x \\<in> (literal_sets F \\<union> clauses_with_literals F)\"\n    using prem p_def\n    by auto\n  then show \"x \\<in> comp_S F\" \n    by blast\nqed\n\nlemma constr_cover_is_collection:\n  \"\\<sigma> \\<Turnstile> F \\<Longrightarrow> constr_cover F \\<sigma> \\<subseteq> (comp_S F)\"\nunfolding constr_cover_def vars_sets_def clause_sets_def\napply auto\nusing constr_cover_clause_is_collection \nby blast\n\nsubsubsection \"The constructed set is a cover\"\n\nparagraph \"covers all variables\"\nlemma vars_in_vars_set_aux1:\n  \"\\<forall>x\\<in>vars_sets F \\<sigma>. \\<exists>v \\<in> vars F. V v \\<in> x\"\nunfolding vars_sets_def \nby auto\n\nlemma vars_in_vars_set_aux2:\n  \"\\<forall>v\\<in> vars F. \\<exists>x \\<in> var_true_literals F. V v \\<in> x\"\nunfolding var_true_literals_def vars_of_sat_def\nby auto\n\nlemma vars_in_vars_set_aux3:\n  \"\\<forall>v\\<in> vars F. \\<exists>x \\<in> var_false_literals F. V v \\<in> x\"\nunfolding var_false_literals_def vars_of_sat_def\nby auto\n\nlemmas vars_in_vars_set_aux=\nvars_in_vars_set_aux1 vars_in_vars_set_aux2 vars_in_vars_set_aux3\n\nlemma vars_in_vars_set:\n  \"vars_of_sat F \\<subseteq> \\<Union> (vars_sets F \\<sigma>)\"\nunfolding vars_of_sat_def vars_sets_def \nusing vars_in_vars_set_aux \nby (auto, meson)\n\nparagraph \"covers all clauses\"\n\nlemma clause_in_clause_set_aux:\nassumes \"\\<sigma> \\<Turnstile> F\" \"c \\<in> set F\"\nshows  \"C c \\<in> \\<Union>(constr_cover_clause c \\<sigma>)\" \nusing constr_cover_clause_unfold [OF assms]\nby fastforce\n\nlemma clause_in_clause_set:\nassumes \"\\<sigma> \\<Turnstile> F\"\nshows \"clauses_of_sat F \\<subseteq> \\<Union> (\\<Union>(clause_sets F \\<sigma>))\"\nunfolding clause_sets_def  clauses_of_sat_def\nusing clause_in_clause_set_aux[OF assms] \nby (auto, fastforce)\n\nparagraph \"covers all false literals\"\n\nlemma double_neg_id: \n  \"\\<not> (\\<sigma>\\<up>) (Neg a) \\<longleftrightarrow> (\\<sigma>\\<up>) (Pos a)\"\nunfolding models_def lift_def\nby simp\n\nlemma false_literal_in_vars_sets_aux:\nassumes \"\\<not> (\\<sigma>\\<up>) x\" \"x \\<in> c\" \"c \\<in> set F\"\nshows \" \\<exists>s \\<in> vars_sets F \\<sigma>. L x c \\<in> s\"\nproof (cases x) \n  case (Pos a)\n  then show ?thesis\n  proof -\n    let ?s = \"{V a} \\<union> {l \\<in> literals_of_sat F. \\<exists>c. C c \\<in> clauses_of_sat F \\<and> L (Pos a) c = l}\"\n    \n    have \"a \\<in> vars F\"\n      using assms(2-3) Pos by (force simp add: vars_correct)\n    moreover then have \"?s \\<in> var_false_literals F\"\n      unfolding var_false_literals_def vars_of_sat_def\n      by blast\n    moreover have \"\\<not> (\\<sigma>\\<up>) (Pos a)\"\n      using Pos assms(1) by blast\n    ultimately have \"?s \\<in> vars_sets F \\<sigma>\" \n      unfolding vars_sets_def \n      by force\n    moreover have \"L x c \\<in> ?s\"\n      using Pos assms(2-3) by simp\n    ultimately show ?thesis \n      by meson\n  qed \nnext\n  case (Neg b)\n  then show ?thesis\n  proof -\n    let ?s = \"{V b} \\<union> {l \\<in> literals_of_sat F. \\<exists>c. C c \\<in> clauses_of_sat F \\<and> L (Neg b) c = l}\"\n    have \"b \\<in> vars F\"\n      using assms(2-3) Neg by (force simp add: vars_correct)\n    moreover then have \"?s \\<in> var_true_literals F\"\n      unfolding var_true_literals_def vars_of_sat_def\n      by blast\n    moreover have \"(\\<sigma>\\<up>) (Pos b)\"\n      using Neg assms(1) \n      by (force simp add: double_neg_id)\n    ultimately have \"?s \\<in> vars_sets F \\<sigma>\" \n      unfolding vars_sets_def \n      by force\n    moreover have \"L x c \\<in> ?s\"\n      using Neg assms(2-3) by simp\n    ultimately show ?thesis \n      by meson\n  qed \nqed\n\nlemma false_literal_in_vars_sets:\n\"\\<lbrakk>\\<not> (\\<sigma>\\<up>) x; x \\<in> c; c \\<in> set F\\<rbrakk> \\<Longrightarrow> L x c \\<in> \\<Union>(vars_sets F \\<sigma>)\"\nusing false_literal_in_vars_sets_aux \nby fast\n\nparagraph \"covers all true literals\"\n\nlemma true_literals_in_clause_sets_aux:\nassumes \"\\<sigma> \\<Turnstile> F\" \"(\\<sigma>\\<up>) x\" \"x \\<in> c\" \"c \\<in> set F\"\nshows \"L x c \\<in> \\<Union>(constr_cover_clause c \\<sigma>)\"\nproof -\nlet ?s = \"constr_cover_clause c \\<sigma>\"\n\nfrom constr_cover_clause_unfold[OF assms(1) assms(4)]\nhave \"\\<exists>p\\<in>c. (\\<sigma>\\<up>) p \\<and> ?s = {{C c, L p c}} \\<union> {{L q c} |q. q \\<in> c \\<and> q \\<noteq> p \\<and> (\\<sigma>\\<up>) q}\"\n  by blast\nthen obtain p where p_def:\n\"p \\<in> c\" \"(\\<sigma>\\<up>) p\" \"?s = {{C c, L p c}} \\<union> {{L q c} |q. q \\<in> c \\<and> q \\<noteq> p \\<and> (\\<sigma>\\<up>) q}\"\n  by blast \nhence \"\\<Union>?s = {C c} \\<union> {L q c|q. q \\<in> c \\<and> (\\<sigma>\\<up>) q}\"\n  by blast\nthen show ?thesis \n  using assms(2-3) by blast\nqed\n\nlemma true_literals_in_clause_sets:\n\"\\<lbrakk>\\<sigma> \\<Turnstile> F;(\\<sigma>\\<up>) x; x \\<in> c; c \\<in> set F\\<rbrakk> \\<Longrightarrow> L x c \\<in> \\<Union> (\\<Union>(clause_sets F \\<sigma>))\"\nunfolding clause_sets_def\nusing true_literals_in_clause_sets_aux \nby fast\n\nparagraph \"Integration of all true and false literals\"\n\nlemma literals_in_construction_aux:\nassumes \"\\<sigma> \\<Turnstile> F\" \"x \\<in> c\" \"c \\<in> set F\" \"F \\<in> cnf_sat\"\nshows \"L x c \\<in> \\<Union>(constr_cover F \\<sigma>)\"\nproof (cases \"(\\<sigma>\\<up>) x\")\n  case True\n  with assms have \"L x c \\<in> \\<Union> (\\<Union>(clause_sets F \\<sigma>))\"\n    using true_literals_in_clause_sets \n    by blast\n  then show ?thesis\n    unfolding constr_cover_def \n    using assms(4) \n    by simp\nnext\n  case False\n  with assms have \"L x c \\<in> \\<Union>(vars_sets F \\<sigma>)\"\n    using false_literal_in_vars_sets \n    by blast\n  then show ?thesis\n    unfolding constr_cover_def \n    using assms(4) \n    by simp\nqed\n\n\ncorollary literals_in_construction: \n\"\\<sigma> \\<Turnstile> F \\<Longrightarrow> literals_of_sat F \\<subseteq> \\<Union>(constr_cover F \\<sigma>)\"\nproof - \n  assume \"\\<sigma> \\<Turnstile> F\" \n  hence \"F \\<in> cnf_sat\" \n    unfolding cnf_sat_def sat_def \n    by blast\n  with \\<open>\\<sigma> \\<Turnstile> F\\<close> have \"\\<forall>c\\<in>set F. \\<forall>x\\<in>c.  L x c \\<in> \\<Union> (constr_cover F \\<sigma>)\"\n    using literals_in_construction_aux \n    by blast\n  then show \"literals_of_sat F \\<subseteq> \\<Union>(constr_cover F \\<sigma>)\"\n    unfolding literals_of_sat_def \n    by fastforce\nqed \n\nsubsubsection \"The constructed sets are pairwise disjoint\"\n\nparagraph \"clause_sets are disjoint\"\n\nlemma clause_sets_disj:\nassumes \"\\<sigma> \\<Turnstile> F\" \nshows  \"disjoint (\\<Union> (clause_sets F \\<sigma>))\"\n  unfolding clause_sets_def \n  apply (rule disjointI)\n  apply (auto)\n  using constr_cover_clause_unfold[OF assms] \n  apply (smt (z3) Un_iff empty_iff insertE mem_Collect_eq \n    xc_element.simps(2) xc_element.simps(3) xc_element.simps(9))+\n  done \n\nparagraph \"vars_sets are disjoint\"\n\nabbreviation \"true_literals v F \\<equiv> {V v} \\<union> {l. l \\<in> (literals_of_sat F) \n  \\<and> (\\<exists>c. C c\\<in> (clauses_of_sat F) \\<and> L (Neg v) c = l)}\"\nabbreviation \"false_literals v F \\<equiv> {V v} \\<union> {l. l \\<in> (literals_of_sat F) \n  \\<and> (\\<exists>c. C c\\<in> (clauses_of_sat F) \\<and> L (Pos v) c = l)}\"\n\nlemma true_false_literals_noteq: \n  \"v \\<in> vars F \\<Longrightarrow> true_literals v F \\<noteq> false_literals v F\"\nproof -\n  assume \"v \\<in> vars F\"\n  then have \"(v \\<in> var ` \\<Union> (set F))\"\n    using vars_correct[of v F] by blast \n  then have \"\\<exists>c\\<in> set F. v \\<in> var ` c\"\n    by blast\n  have \"\\<exists>c. C c \\<in> (clauses_of_sat F) \\<and>\n    (L (Neg v) c \\<in> (literals_of_sat F) \\<or> L (Pos v) c \\<in> (literals_of_sat F))\"\n    unfolding literals_of_sat_def clauses_of_sat_def\n    using comp_literals_correct[of F \"{}\"] \n    apply auto\n    using \\<open>\\<exists>c\\<in> set F. v \\<in> var ` c\\<close> \n    by (metis imageE var.elims)\n  then show  \"true_literals v F \\<noteq> false_literals v F\" \n    by fast\nqed \n\nlemma true_literals_not_in_false:\n  \"v \\<in> vars F \\<Longrightarrow> \\<forall>u\\<in> vars F. true_literals v F \\<noteq> false_literals u F\"\nproof \n  fix u \n  assume  \"v \\<in> vars F\" \"u \\<in> vars F\"  \n  have \"\\<forall>x\\<in> true_literals v F. x = V v \\<or> (\\<exists>c. x = L (Neg v) c)\"\n    by blast\n  moreover have \"\\<forall>x\\<in> false_literals u F. x = V u \\<or> (\\<exists>c. x = L (Pos u) c)\"\n    by blast \n  ultimately show \"true_literals v F \\<noteq> false_literals u F\" \n    apply (cases \"v\\<noteq>u\")\n    using true_false_literals_noteq[OF \\<open>v \\<in> vars F\\<close>] \n    by blast+ \nqed \n \n\nlemma false_literals_not_in_true:\n  \"v \\<in> vars F \\<Longrightarrow> \\<forall>u\\<in> vars F. false_literals v F \\<noteq> true_literals u F\"\nproof \n  fix u \n  assume  \"v \\<in> vars F\" \"u \\<in> vars F\"  \n  have \"\\<forall>x\\<in> true_literals v F. x = V v \\<or> (\\<exists>c. x = L (Neg v) c)\"\n    by blast\n  moreover have \"\\<forall>x\\<in> false_literals u F. x = V u \\<or> (\\<exists>c. x = L (Pos u) c)\"\n    by blast \n  ultimately show \"false_literals v F \\<noteq> true_literals u F\" \n    apply (cases \"v\\<noteq>u\")\n    using true_false_literals_noteq[OF \\<open>v \\<in> vars F\\<close>] by blast+ \nqed \n \n\nlemma vars_sets_true_assignment:\n\"\\<lbrakk>(\\<sigma>\\<up>) (Pos v); v \\<in> vars F\\<rbrakk> \\<Longrightarrow> true_literals v F \\<in> vars_sets F \\<sigma> \\<and> false_literals v F \\<notin> vars_sets F \\<sigma>\"\nproof standard\n  assume \"(\\<sigma>\\<up>) (Pos v)\" \"v \\<in> vars F\"\n  have \"true_literals v F \\<in> var_true_literals F\"\n    unfolding var_true_literals_def vars_of_sat_def\n    using \\<open>v \\<in> vars F\\<close> \n    by blast\n  then show \"true_literals v F \\<in> vars_sets F \\<sigma>\"\n    unfolding vars_sets_def\n    using \\<open>(\\<sigma>\\<up>) (Pos v)\\<close> \\<open>v \\<in> vars F\\<close> \n    by auto\n  from \\<open>v \\<in> vars F\\<close> have \"false_literals v F \\<notin> var_true_literals F\"\n    unfolding var_true_literals_def vars_of_sat_def\n    using false_literals_not_in_true \n    by force\n  then show \"false_literals v F \\<notin> vars_sets F \\<sigma>\"\n    unfolding vars_sets_def\n    using \\<open>(\\<sigma>\\<up>) (Pos v)\\<close> \\<open>v \\<in> vars F\\<close> \n    by auto\nqed \n\nlemma vars_sets_false_assignment:\n\"\\<lbrakk>\\<not> (\\<sigma>\\<up>) (Pos v); v \\<in> vars F\\<rbrakk> \\<Longrightarrow> true_literals v F \\<notin> vars_sets F \\<sigma> \\<and> false_literals v F \\<in> vars_sets F \\<sigma>\"\nproof standard\n  assume \"\\<not> (\\<sigma>\\<up>) (Pos v)\" \"v \\<in> vars F\"\n  have \"false_literals v F \\<in> var_false_literals F\"\n    unfolding var_false_literals_def vars_of_sat_def\n    using \\<open>v \\<in> vars F\\<close> \n    by blast\n  then show \"false_literals v F \\<in> vars_sets F \\<sigma>\"\n    unfolding vars_sets_def\n    using \\<open>\\<not> (\\<sigma>\\<up>) (Pos v)\\<close> \\<open>v \\<in> vars F\\<close> \n    by fastforce \n  from \\<open>v \\<in> vars F\\<close> have \"true_literals v F \\<notin> var_false_literals F\"\n    unfolding var_false_literals_def vars_of_sat_def\n    using true_literals_not_in_false \n    by force\n  then show \"true_literals v F \\<notin> vars_sets F \\<sigma>\"\n    unfolding vars_sets_def\n    using \\<open>\\<not> (\\<sigma>\\<up>) (Pos v)\\<close> \\<open>v \\<in> vars F\\<close> \n    by auto\nqed \n\nlemma vars_sets_bipartite:\n  \"v \\<in> vars F \n    \\<Longrightarrow> (true_literals v F \\<notin> vars_sets F \\<sigma> \\<and> false_literals v F \\<in> vars_sets F \\<sigma>) \n        \\<or> (true_literals v F \\<in> vars_sets F \\<sigma> \\<and> false_literals v F \\<notin> vars_sets F \\<sigma>)\"\n  using vars_sets_false_assignment vars_sets_true_assignment \n  by fast\n\nlemma vars_sets_subset:\n  \"vars_sets F \\<sigma> \\<subseteq> (var_true_literals F \\<union> var_false_literals F)\"\n  unfolding vars_sets_def var_true_literals_def var_false_literals_def\n  by auto\n\nlemma var_true_literals_disj:\n  \"disjoint (var_true_literals F)\"\n  apply (rule disjointI)\n  unfolding var_true_literals_def\n  by auto\n\nlemma var_false_literals_disj:\n  \"disjoint (var_false_literals F)\"\n  apply (rule disjointI)\n  unfolding var_false_literals_def\n  by auto\n\nlemma vars_sets_disj_aux:\nassumes \"A \\<in> vars_sets F \\<sigma>\"\nshows \"\\<forall>s\\<in>vars_sets F \\<sigma>. s \\<noteq> A \\<longrightarrow> s \\<inter> A = {}\"\nproof \n  fix s\n  assume \"s \\<in> vars_sets F \\<sigma>\"\n  show \"s \\<noteq> A \\<longrightarrow> s \\<inter> A = {}\"\n  proof \n    assume \"s \\<noteq> A\"\n    consider \n      \"s \\<in> var_false_literals F \\<and> A \\<in> var_false_literals F\" |\n      \"s \\<in> var_false_literals F \\<and> A \\<in> var_true_literals F \\<or> \n        s \\<in> var_true_literals F \\<and> A \\<in> var_false_literals F\" |\n      \"s \\<in> var_true_literals F \\<and> A \\<in> var_true_literals F\"\n        using vars_sets_subset assms \\<open>s \\<in> vars_sets F \\<sigma>\\<close> \n        by blast\n    then show \"s \\<inter> A = {}\"\n    proof (cases)\n      case 1\n      then show ?thesis\n      using disjointD var_false_literals_disj \\<open>s \\<noteq> A\\<close> \n      by blast\n    next\n      case 2\n      then show ?thesis\n      unfolding var_false_literals_def var_true_literals_def vars_of_sat_def\n      using assms \\<open>s \\<in> vars_sets F \\<sigma>\\<close> vars_sets_bipartite \n      by fast\n    next\n      case 3\n      then show ?thesis \n      using disjointD var_true_literals_disj \\<open>s \\<noteq> A\\<close> \n      by blast\n    qed\n  qed \nqed \n\nlemma vars_sets_disj:\n\"disjoint (vars_sets F \\<sigma>)\"\n  apply (rule disjointI)\n  using vars_sets_disj_aux \n  by blast\n\nparagraph \"clause sets and var sets are disjoint to each other\"\n\nlemma vars_sets_only_false_literals_aux:\n\"\\<forall>s\\<in>vars_sets F \\<sigma>. \\<forall>x \\<in> s. x \\<in> vars_of_sat F \\<or> (x \\<in> literals_of_sat F \\<and> \\<not>(\\<sigma>\\<Up>) x)\"\nunfolding vars_sets_def\napply auto \nunfolding var_false_literals_def var_true_literals_def\nusing double_neg_id \nby fastforce+\n\ncorollary vars_sets_only_false_literals:\n\"\\<forall>x\\<in>\\<Union>(vars_sets F \\<sigma>). x \\<in> vars_of_sat F \\<or> (x \\<in> literals_of_sat F \\<and> \\<not>(\\<sigma>\\<Up>) x)\"\nusing vars_sets_only_false_literals_aux \nby blast\n\nlemma constr_cover_clause_only_true_literals_aux1:\nassumes \"\\<sigma> \\<Turnstile> F\" \"c \\<in> set F\"\nshows \"\\<forall>s\\<in> constr_cover_clause c \\<sigma>. \\<forall>x\\<in>s. x \\<in> clauses_of_sat F \\<or> (x \\<in> literals_of_sat F \\<and> (\\<sigma>\\<Up>) x)\"\nproof  auto\n  fix s x\n  assume prems: \"s \\<in> constr_cover_clause c \\<sigma>\" \"x \\<in> s\" \"x \\<notin> clauses_of_sat F\"\n  obtain p where p_def:\"p \\<in> c\" \"(\\<sigma>\\<up>) p\"\n  \"constr_cover_clause c \\<sigma> = {{C c, L p c}} \\<union> {{L q c} |q. q \\<in> c \\<and> q \\<noteq> p \\<and> (\\<sigma>\\<up>) q}\"\n    using constr_cover_clause_unfold[OF assms] \n    by blast \n  hence \"x \\<in> {L q c |q. q \\<in> c \\<and> (\\<sigma>\\<up>) q}\"\n    using prems assms unfolding clauses_of_sat_def \n    by blast\n  with assms(2) show \"(\\<sigma>\\<Up>) x\" \"x \\<in> literals_of_sat F\"\n    unfolding literals_of_sat_def\n    by fastforce+  \nqed\n\ncorollary constr_cover_clause_only_true_literals_aux2:\nassumes \"\\<sigma> \\<Turnstile> F\"\nshows \"\\<forall>s\\<in> \\<Union>(clause_sets F \\<sigma>). \\<forall>x\\<in>s. x \\<in> clauses_of_sat F \\<or> (x \\<in> literals_of_sat F \\<and> (\\<sigma>\\<Up>) x)\"\nunfolding clause_sets_def\nusing constr_cover_clause_only_true_literals_aux1[OF assms]\nby blast\n\ncorollary constr_cover_clause_only_true_literals:\nassumes \"\\<sigma> \\<Turnstile> F\"\nshows \"\\<forall>x\\<in> \\<Union>(\\<Union>(clause_sets F \\<sigma>)). x \\<in> clauses_of_sat F \\<or> (x \\<in> literals_of_sat F \\<and> (\\<sigma>\\<Up>) x)\"\nusing constr_cover_clause_only_true_literals_aux2[OF assms]\nby blast\n\nlemma vars_clauses_set_disj:\nassumes \"\\<sigma> \\<Turnstile> F\" \nshows \"\\<Union>(vars_sets F \\<sigma>) \\<inter> \\<Union> (\\<Union> (clause_sets F \\<sigma>)) = {}\"\nusing assms constr_cover_clause_only_true_literals vars_sets_only_false_literals\nunfolding vars_of_sat_def clauses_of_sat_def literals_of_sat_def\nby fastforce\n\ncorollary constr_cover_disj:\n\"\\<sigma> \\<Turnstile> F \\<Longrightarrow> disjoint ((vars_sets F \\<sigma>) \\<union> (\\<Union> (clause_sets F \\<sigma>)))\"\nusing disjoint_union vars_sets_disj clause_sets_disj vars_clauses_set_disj\nby blast  \n\nsubsection \"The soundness lemma\"\n  \nlemma ts_xc_sound_aux:\n  \"\\<sigma> \\<Turnstile> F \\<Longrightarrow> cover (constr_cover F \\<sigma>) (comp_X F)\"\n  unfolding cover_def\n  proof\n    assume prems: \"\\<sigma> \\<Turnstile> F\" \n    show \"\\<Union> (constr_cover F \\<sigma>) = comp_X F\"\n    proof (standard, goal_cases)\n      case 1\n      have \"constr_cover F \\<sigma> \\<subseteq> comp_S F\"\n        using constr_cover_is_collection prems by blast \n      moreover have \"F \\<in> cnf_sat\"\n        unfolding cnf_sat_def sat_def\n        using prems by blast\n      ultimately show ?case\n        using ts_xc_is_collection by blast\n    next\n      case 2\n      have \"F \\<in> cnf_sat\"\n        unfolding cnf_sat_def sat_def\n        using prems by blast\n      have \"vars_of_sat F \\<subseteq> \\<Union> (constr_cover F \\<sigma>)\"\n        unfolding constr_cover_def\n        using vars_in_vars_set \\<open>F \\<in> cnf_sat\\<close>\n        by auto \n      moreover have \"clauses_of_sat F \\<subseteq> \\<Union> (constr_cover F \\<sigma>)\"\n        unfolding constr_cover_def \n        using clause_in_clause_set[OF prems(1)] \\<open>F \\<in> cnf_sat\\<close>\n        by auto\n      moreover have \"literals_of_sat F \\<subseteq> \\<Union> (constr_cover F \\<sigma>)\"  \n        using prems literals_in_construction \n        by blast\n      ultimately show ?case \n        by blast\n    qed\n  next\n    assume prems: \"\\<sigma> \\<Turnstile> F\" \n    have \"F \\<in> cnf_sat\"\n      unfolding cnf_sat_def sat_def\n      using prems by blast\n    show \"disjoint (constr_cover F \\<sigma>)\"\n      unfolding constr_cover_def \n      using prems constr_cover_disj \n      by auto\n  qed \n\nlemma ts_xc_sound:\n  \"F \\<in> cnf_sat \\<Longrightarrow> ts_xc F \\<in> exact_cover\"\n  proof (goal_cases) \n    let ?X = \"comp_X F\"\n    let ?S = \"comp_S F\"\n  case 1\n    hence prems: \"\\<exists>\\<sigma>. \\<sigma> \\<Turnstile> F\" \n      unfolding cnf_sat_def sat_def\n      by blast\n    then obtain \\<sigma> where sig_def: \"\\<sigma> \\<Turnstile> F\"\n      by blast\n    have \"(?X, ?S) \\<in> exact_cover\"\n      apply (rule exact_cover_I)\n      apply (rule constr_cover_is_collection[OF sig_def])\n      apply (rule ts_xc_is_collection)\n      apply (rule ts_xc_sound_aux[OF sig_def])\n      done \n    then show ?case \n      unfolding ts_xc_def \n      by simp\n  qed\n\nsection \"The proof of the completeness\"\n\ndefinition \"constr_model S' F = \n(\\<lambda>x. \n    if (\\<exists>s \\<in> S'. \\<exists>c \\<in> set F. s = {C c, L (Pos x) c} \\<and> (Pos x) \\<in> c) \n    then True\n    else if (\\<exists>s \\<in> S'. \\<exists>c \\<in> set F. s = {C c, L (Neg x) c} \\<and> (Neg x) \\<in> c)\n    then False\n    else False)\"\n\nlemma clause_only_binary:\n  \"\\<forall>c \\<in> clauses_of_sat F. \\<forall>s\\<in>(comp_S F). c \\<in> s \\<longrightarrow> s \\<in> clauses_with_literals F\"\nproof standard\n  fix c \n  assume prems: \"c \\<in> clauses_of_sat F\"\n  hence \"\\<forall>s \\<in> literal_sets F. c \\<notin> s\"\n        \"\\<forall>s \\<in> var_true_literals F. c \\<notin> s\"\n        \"\\<forall>s \\<in> var_false_literals F. c \\<notin> s\"\n    unfolding literal_sets_def var_true_literals_def var_false_literals_def\n      clauses_of_sat_def literals_of_sat_def\n    by fastforce+\n  then show \"\\<forall>s\\<in>(comp_S F). c \\<in> s \\<longrightarrow> s \\<in> clauses_with_literals F\"\n    by blast\nqed \n\n\nlemma clauses_with_literals_satisfiability:\n  \"s \\<in> clauses_with_literals F \\<Longrightarrow> C c \\<in> s \\<Longrightarrow> (\\<exists>l \\<in> c. s = {C c, L l c})\"\n  unfolding clauses_with_literals_def\n  by blast\n\nlemma constr_model_exists:\n  \"\\<lbrakk>S' \\<subseteq> S; cover S' X; ts_xc F = (X, S)\\<rbrakk> \n    \\<Longrightarrow> (\\<forall>c\\<in> set F. \\<exists>s\\<in> S'. \\<exists>l \\<in> c. s = {C c, L l c})\"\nproof\n  fix c \n  assume \"S' \\<subseteq> S\" \"cover S' X\" \"ts_xc F = (X, S)\" \n  \"c \\<in> set F\"\n  from \\<open>c \\<in> set F\\<close> have \"C c \\<in> clauses_of_sat F\"\n    unfolding clauses_of_sat_def \n    by simp \n  moreover from \\<open>ts_xc F = (X, S)\\<close> \n  have \"S = comp_S F\" \"X = comp_X F\"\n    unfolding ts_xc_def \n    by force+\n  ultimately \n  have prem: \"\\<forall>s\\<in>S. C c \\<in> s \\<longrightarrow> s \\<in> clauses_with_literals F\"\n    using clause_only_binary \n    by blast\n\n  from \\<open>C c \\<in> clauses_of_sat F\\<close> \\<open>X = comp_X F\\<close>\n  have \"C c \\<in> X\" \n    by fastforce\n  with \\<open>cover S' X\\<close> have \"\\<exists>s \\<in> S'. C c \\<in> s\"\n    unfolding cover_def \n    by blast\n  moreover from \\<open>S' \\<subseteq> S\\<close>\n  have \"\\<forall>s \\<in> S'. C c \\<in> s \\<longrightarrow> s \\<in> clauses_with_literals F\"\n    using prem\n    by blast\n  ultimately obtain s where \"s \\<in> S'\" \"C c \\<in> s\" \"s \\<in> clauses_with_literals F\"\n    by blast\n  hence \"(\\<exists>l \\<in> c. s = {C c, L l c})\"\n    using clauses_with_literals_satisfiability\n    by blast\n  with \\<open>s \\<in> S'\\<close> show \"\\<exists>s \\<in> S'. \\<exists>l\\<in>c. s = {C c, L l c}\"\n    by blast\nqed \n\nlemma vars_only_in_true_false_literals:\nassumes \"s \\<in> comp_S F\" \"V x \\<in> s\"\nshows \"s = true_literals x F \\<or> s = false_literals x F\"\nproof -\nhave \"V x \\<notin> \\<Union>(literal_sets F)\"\n  unfolding literal_sets_def literals_of_sat_def\n  by force \nwith assms(2) have limit1: \"s \\<notin> literal_sets F\"\n  by fastforce \n\nhave \"V x \\<notin> \\<Union>(clauses_with_literals F)\"\n  unfolding clauses_with_literals_def clauses_of_sat_def\n  by blast\nwith assms(2) have limit2: \"s \\<notin> clauses_with_literals F\"\n  by fastforce\n\nfrom limit1 limit2 assms(1)\nhave \"s \\<in> var_true_literals F \\<or> s \\<in> var_false_literals F\"\n  by blast\nthen consider \"s \\<in> var_true_literals F\" | \"s \\<in> var_false_literals F\"\n  by blast\nthen show ?thesis\n  proof (cases)\n    case 1\n    with assms(2) have \"s = true_literals x F\"\n      unfolding var_true_literals_def\n      by fastforce\n    then show ?thesis \n      by blast\n  next\n    case 2\n    with assms(2) have \"s = false_literals x F\"\n      unfolding var_false_literals_def\n      by fastforce\n    then show ?thesis\n      by blast\n  qed\nqed \n\nlemma constr_model_disj_aux:\nassumes  \"cover S' (comp_X F)\" \"S' \\<subseteq> (comp_S F)\" \"{C c, L (Pos x) c} \\<in> S'\"\nshows \"\\<not>(\\<exists>c'. {C c', L (Neg x) c'} \\<in> S')\"\nproof \n  assume \"\\<exists>c'. {C c', L (Neg x) c'} \\<in> S'\"\n  then obtain c' where c'_def: \"{C c', L (Neg x) c'} \\<in> S'\"\n    by blast\n  show \"False\"\n  proof (cases \"c = c'\")\n    case True\n    from assms(1) have \"disjoint S'\"\n      unfolding cover_def\n      by blast\n    with c'_def assms(3) disjointD True \n    show ?thesis\n      by blast\n  next\n    case False\n    from assms(1) assms(3) c'_def \n    have \"C c \\<in> comp_X F\" \"C c' \\<in> comp_X F\"\n      unfolding cover_def\n      by blast+\n    hence \"C c \\<in> clauses_of_sat F\" \"C c' \\<in> clauses_of_sat F\"\n      unfolding vars_of_sat_def literals_of_sat_def\n      by simp+\n\n    moreover from assms(2-3) c'_def\n    have \"{C c, L (Pos x) c} \\<in> comp_S F\" \"{C c', L (Neg x) c'} \\<in> comp_S F\"\n      by blast+\n    ultimately have\n    \"{C c, L (Pos x) c} \\<in> clauses_with_literals F\"\n    \"{C c', L (Neg x) c'} \\<in> clauses_with_literals F\"\n      using clause_only_binary\n      by blast+\n    hence c_x_unfold:\n    \"C c \\<in> clauses_of_sat F\" \"C c' \\<in> clauses_of_sat F\"\n    \"Pos x \\<in> c\" \"Neg x \\<in> c'\"\n      unfolding clauses_with_literals_def\n      by (simp add: doubleton_eq_iff)+\n    with \\<open>C c \\<in> clauses_of_sat F\\<close> have \"x \\<in> vars F\"\n      unfolding clauses_of_sat_def vars_correct \n      by force\n    hence \"V x \\<in> vars_of_sat F\"\n      unfolding vars_of_sat_def\n      by simp\n    then have \"V x \\<in> comp_X F\"\n      by simp\n    with assms(1) have \"\\<exists>s \\<in> S'. V x \\<in> s\"\n      unfolding cover_def \n      by blast\n    then obtain s where s_def: \"s \\<in> S'\" \"V x \\<in> s\"\n      by blast\n    hence \"s \\<in> comp_S F\"\n      using assms(2) \n      by blast\n    with \\<open>V x \\<in> s\\<close> have \n    \"s = true_literals x F \\<or> s = false_literals x F\"\n      using vars_only_in_true_false_literals[of s F x]\n      by fastforce\n    then consider \"s = true_literals x F\" | \"s = false_literals x F\"\n      by blast\n    then show ?thesis\n    proof (cases)\n      case 1\n      have \"L (Neg x) c' \\<in> comp_literals F {}\"\n        using c_x_unfold \n        unfolding clauses_of_sat_def\n        by auto\n      hence \"L (Neg x) c' \\<in> true_literals x F\"\n        by simp\n      moreover have \"L (Neg x) c' \\<in> {C c', L (Neg x) c'}\"\n        by blast\n      moreover from assms(1)\n      have \"disjoint S'\"\n        unfolding cover_def \n        by blast\n      ultimately show ?thesis\n        using disjointD[of S', OF _ c'_def s_def(1)] 1\n        by blast\n    next\n      case 2\n      have \"L (Pos x) c \\<in> comp_literals F {}\"\n        using c_x_unfold \n        unfolding clauses_of_sat_def\n        by auto\n      hence \"L (Pos x) c \\<in> false_literals x F\"\n        by simp\n      moreover have \"L (Pos x) c \\<in> {C c, L (Pos x) c}\"\n        by blast\n      moreover from assms(1)\n      have \"disjoint S'\"\n        unfolding cover_def \n        by blast\n      ultimately show ?thesis\n        using disjointD[of S', OF _ assms(3) s_def(1)] 2\n        by blast\n    qed\n  qed\nqed \n\nlemma ts_xc_complete:\n  \"ts_xc F \\<in> exact_cover \\<Longrightarrow> F \\<in> cnf_sat\"\nproof -\n  let ?X = \"comp_X F\"\n  let ?S = \"comp_S F\"\n\n  assume \"ts_xc F \\<in> exact_cover\"\n  then have \"ts_xc F = (?X, ?S)\"\n    unfolding ts_xc_def \n    by simp \n  with \\<open>ts_xc F \\<in> exact_cover\\<close> \n  have \"\\<exists>S' \\<subseteq> ?S. cover S' ?X\"\n    using exact_cover_D ts_xc_is_collection\n    by metis \n  then obtain S' where S'_def: \"cover S' ?X\" \"S' \\<subseteq> ?S\" \n    by blast\n  with \\<open>ts_xc F = (?X, ?S)\\<close> \n  have prem: \"\\<forall>c\\<in> set F. \\<exists>s\\<in> S'. \\<exists>l \\<in> c. s = {C c, L l c}\"\n   using constr_model_exists[of S' ?S ?X]\n   by presburger\n\n   let ?\\<sigma> = \"constr_model S' F\"\n   have \"\\<forall>c\\<in> set F. \\<exists>s\\<in> S'. \\<exists>l \\<in> c. s = {C c, L l c} \\<and> (?\\<sigma> \\<up>) l\"\n   proof \n     fix c \n     assume \"c \\<in> set F\"\n     then have \"\\<exists>s\\<in> S'. \\<exists>l \\<in> c. s = {C c, L l c}\"\n       using prem \n       by blast\n     then obtain s l where s_def: \"s \\<in> S'\" \"l \\<in> c\" \"s = {C c, L l c}\"\n       by blast\n     \n     have \"(?\\<sigma>\\<up>) l\"\n      unfolding constr_model_def lift_def\n      apply (cases l)\n      using s_def \\<open>c \\<in> set F\\<close> apply force \n      apply auto \n      using constr_model_disj_aux[OF S'_def] s_def\n      by blast\n     with s_def \\<open>c \\<in> set F\\<close> \n     show \"\\<exists>s\\<in>S'. \\<exists>l\\<in>c. s = {C c, L l c} \\<and> (?\\<sigma>\\<up>) l\"\n       by blast\n   qed \n   then have \"?\\<sigma> \\<Turnstile> F\"\n     unfolding models_def \n     by blast\n   then show ?thesis\n     unfolding cnf_sat_def sat_def\n     by blast\nqed\n\ntheorem is_reduction_ts_xc:\n\"is_reduction ts_xc cnf_sat exact_cover\"\n  unfolding is_reduction_def \n  using ts_xc_sound ts_xc_complete\n  by blast\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/original_work/TS_To_XC/TS_To_XC.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045937171068, "lm_q2_score": 0.7905303186696747, "lm_q1q2_score": 0.7013621301963837}}
{"text": "(*  Title:       Limit\n    Author:      Eugene W. Stark <stark@cs.stonybrook.edu>, 2016\n    Maintainer:  Eugene W. Stark <stark@cs.stonybrook.edu>\n*)\n\nchapter Limit\n\ntheory Limit\nimports FreeCategory DiscreteCategory Adjunction\nbegin\n\n  text\\<open>\n    This theory defines the notion of limit in terms of diagrams and cones and relates\n    it to the concept of a representation of a functor.  The diagonal functor associated\n    with a diagram shape @{term J} is defined and it is shown that a right adjoint to\n    the diagonal functor gives limits of shape @{term J} and that a category has limits\n    of shape @{term J} if and only if the diagonal functor is a left adjoint functor.\n    Products and equalizers are defined as special cases of limits, and it is shown\n    that a category with equalizers has limits of shape @{term J} if it has products\n    indexed by the sets of objects and arrows of @{term J}.\n    The existence of limits in a set category is investigated, and it is shown that\n    every set category has equalizers and that a set category @{term S} has @{term I}-indexed\n    products if and only if the universe of @{term S} ``admits @{term I}-indexed tupling.''\n    The existence of limits in functor categories is also developed, showing that\n    limits in functor categories are ``determined pointwise'' and that a functor category\n    @{term \"[A, B]\"} has limits of shape @{term J} if @{term B} does.\n    Finally, it is shown that the Yoneda functor preserves limits.\n\n    This theory concerns itself only with limits; I have made no attempt to consider colimits.\n    Although it would be possible to rework the entire development in dual form,\n    it is possible that there is a more efficient way to dualize at least parts of it without\n    repeating all the work.  This is something that deserves further thought.\n\\<close>\n\n  section \"Representations of Functors\"\n\n  text\\<open>\n    A representation of a contravariant functor \\<open>F: Cop \\<rightarrow> S\\<close>, where @{term S}\n    is a set category that is the target of a hom-functor for @{term C}, consists of\n    an object @{term a} of @{term C} and a natural isomorphism @{term \"\\<Phi>: Y a \\<rightarrow> F\"},\n    where \\<open>Y: C \\<rightarrow> [Cop, S]\\<close> is the Yoneda functor.\n\\<close>\n\n  locale representation_of_functor =\n    C: category C +\n    Cop: dual_category C +\n    S: set_category S +\n    F: \"functor\" Cop.comp S F +\n    Hom: hom_functor C S \\<phi> +\n    Ya: yoneda_functor_fixed_object C S \\<phi> a +\n    natural_isomorphism Cop.comp S \\<open>Ya.Y a\\<close> F \\<Phi>\n  for C :: \"'c comp\"      (infixr \"\\<cdot>\" 55)\n  and S :: \"'s comp\"      (infixr \"\\<cdot>\\<^sub>S\" 55)\n  and \\<phi> :: \"'c * 'c \\<Rightarrow> 'c \\<Rightarrow> 's\"\n  and F :: \"'c \\<Rightarrow> 's\"\n  and a :: 'c\n  and \\<Phi> :: \"'c \\<Rightarrow> 's\"\n  begin\n\n     abbreviation Y where \"Y \\<equiv> Ya.Y\"\n     abbreviation \\<psi> where \"\\<psi> \\<equiv> Hom.\\<psi>\"\n\n  end\n\n  text\\<open>\n    Two representations of the same functor are uniquely isomorphic.\n\\<close>\n\n  locale two_representations_one_functor =\n    C: category C +\n    Cop: dual_category C +\n    S: set_category S +\n    F: set_valued_functor Cop.comp S F +\n    yoneda_functor C S \\<phi> +\n    Ya: yoneda_functor_fixed_object C S \\<phi> a +\n    Ya': yoneda_functor_fixed_object C S \\<phi> a' +\n    \\<Phi>: representation_of_functor C S \\<phi> F a \\<Phi> +\n    \\<Phi>': representation_of_functor C S \\<phi> F a' \\<Phi>'\n  for C :: \"'c comp\"      (infixr \"\\<cdot>\" 55)\n  and S :: \"'s comp\"      (infixr \"\\<cdot>\\<^sub>S\" 55)\n  and F :: \"'c \\<Rightarrow> 's\"\n  and \\<phi> :: \"'c * 'c \\<Rightarrow> 'c \\<Rightarrow> 's\"\n  and a :: 'c\n  and \\<Phi> :: \"'c \\<Rightarrow> 's\"\n  and a' :: 'c\n  and \\<Phi>' :: \"'c \\<Rightarrow> 's\"\n  begin\n\n    interpretation \\<Psi>: inverse_transformation Cop.comp S \\<open>Y a\\<close> F \\<Phi> ..\n    interpretation \\<Psi>': inverse_transformation Cop.comp S \\<open>Y a'\\<close> F \\<Phi>' ..\n    interpretation \\<Phi>\\<Psi>': vertical_composite Cop.comp S \\<open>Y a\\<close> F \\<open>Y a'\\<close> \\<Phi> \\<Psi>'.map ..\n    interpretation \\<Phi>'\\<Psi>: vertical_composite Cop.comp S \\<open>Y a'\\<close> F \\<open>Y a\\<close> \\<Phi>' \\<Psi>.map ..\n\n    lemma are_uniquely_isomorphic:\n      shows \"\\<exists>!\\<phi>. \\<guillemotleft>\\<phi> : a \\<rightarrow> a'\\<guillemotright> \\<and> C.iso \\<phi> \\<and> map \\<phi> = Cop_S.MkArr (Y a) (Y a') \\<Phi>\\<Psi>'.map\"\n    proof -\n      have \"natural_isomorphism Cop.comp S (Y a) F \\<Phi>\" ..\n      moreover have \"natural_isomorphism Cop.comp S F (Y a') \\<Psi>'.map\" ..\n      ultimately have 1: \"natural_isomorphism Cop.comp S (Y a) (Y a') \\<Phi>\\<Psi>'.map\"\n        using NaturalTransformation.natural_isomorphisms_compose by blast\n      interpret \\<Phi>\\<Psi>': natural_isomorphism Cop.comp S \\<open>Y a\\<close> \\<open>Y a'\\<close> \\<Phi>\\<Psi>'.map\n        using 1 by auto\n\n      have \"natural_isomorphism Cop.comp S (Y a') F \\<Phi>'\" ..\n      moreover have \"natural_isomorphism Cop.comp S F (Y a) \\<Psi>.map\" ..\n      ultimately have 2: \"natural_isomorphism Cop.comp S (Y a') (Y a) \\<Phi>'\\<Psi>.map\"\n        using NaturalTransformation.natural_isomorphisms_compose by blast\n      interpret \\<Phi>'\\<Psi>: natural_isomorphism Cop.comp S \\<open>Y a'\\<close> \\<open>Y a\\<close> \\<Phi>'\\<Psi>.map\n        using 2 by auto\n\n      interpret \\<Phi>\\<Psi>'_\\<Phi>'\\<Psi>: inverse_transformations Cop.comp S \\<open>Y a\\<close> \\<open>Y a'\\<close> \\<Phi>\\<Psi>'.map \\<Phi>'\\<Psi>.map\n      proof\n        fix x\n        assume X: \"Cop.ide x\"\n        show \"S.inverse_arrows (\\<Phi>\\<Psi>'.map x) (\\<Phi>'\\<Psi>.map x)\"\n        proof\n          have 1: \"S.arr (\\<Phi>\\<Psi>'.map x) \\<and> \\<Phi>\\<Psi>'.map x = \\<Psi>'.map x \\<cdot>\\<^sub>S \\<Phi> x\"\n            using X \\<Phi>\\<Psi>'.preserves_reflects_arr [of x]\n            by (simp add: \\<Phi>\\<Psi>'.map_simp_2)\n          have 2: \"S.arr (\\<Phi>'\\<Psi>.map x) \\<and> \\<Phi>'\\<Psi>.map x = \\<Psi>.map x \\<cdot>\\<^sub>S \\<Phi>' x\"\n            using X \\<Phi>'\\<Psi>.preserves_reflects_arr [of x]\n            by (simp add: \\<Phi>'\\<Psi>.map_simp_1)\n          show \"S.ide (\\<Phi>\\<Psi>'.map x \\<cdot>\\<^sub>S \\<Phi>'\\<Psi>.map x)\"\n            using 1 2 X \\<Psi>.is_natural_2 \\<Psi>'.inverts_components \\<Psi>.inverts_components\n            by (metis S.inverse_arrows_def S.inverse_arrows_compose)\n          show \"S.ide (\\<Phi>'\\<Psi>.map x \\<cdot>\\<^sub>S \\<Phi>\\<Psi>'.map x)\"\n            using 1 2 X \\<Psi>'.inverts_components \\<Psi>.inverts_components\n            by (metis S.inverse_arrows_def S.inverse_arrows_compose)\n        qed\n      qed\n\n      have \"Cop_S.inverse_arrows (Cop_S.MkArr (Y a) (Y a') \\<Phi>\\<Psi>'.map)\n                                 (Cop_S.MkArr (Y a') (Y a) \\<Phi>'\\<Psi>.map)\"\n      proof -\n        have Ya: \"functor Cop.comp S (Y a)\" ..\n        have Ya': \"functor Cop.comp S (Y a')\" ..\n        have \\<Phi>\\<Psi>': \"natural_transformation Cop.comp S (Y a) (Y a') \\<Phi>\\<Psi>'.map\" ..\n        have \\<Phi>'\\<Psi>: \"natural_transformation Cop.comp S (Y a') (Y a) \\<Phi>'\\<Psi>.map\" ..\n        show ?thesis\n        proof (intro Cop_S.inverse_arrowsI)\n          have 0: \"inverse_transformations Cop.comp S (Y a) (Y a') \\<Phi>\\<Psi>'.map \\<Phi>'\\<Psi>.map\" ..\n          have 1: \"Cop_S.antipar (Cop_S.MkArr (Y a) (Y a') \\<Phi>\\<Psi>'.map)\n                                 (Cop_S.MkArr (Y a') (Y a) \\<Phi>'\\<Psi>.map)\"\n            using Ya Ya' \\<Phi>\\<Psi>' \\<Phi>'\\<Psi> Cop_S.dom_char Cop_S.cod_char Cop_S.seqI\n                  Cop_S.arr_MkArr Cop_S.cod_MkArr Cop_S.dom_MkArr\n            by presburger\n          show \"Cop_S.ide (Cop_S.comp (Cop_S.MkArr (Y a) (Y a') \\<Phi>\\<Psi>'.map)\n                                      (Cop_S.MkArr (Y a') (Y a) \\<Phi>'\\<Psi>.map))\"\n            using 0 1 NaturalTransformation.inverse_transformations_inverse(2) Cop_S.comp_MkArr\n            by (metis Cop_S.cod_MkArr Cop_S.ide_char' Cop_S.seqE)\n          show \"Cop_S.ide (Cop_S.comp (Cop_S.MkArr (Y a') (Y a) \\<Phi>'\\<Psi>.map)\n                                      (Cop_S.MkArr (Y a) (Y a') \\<Phi>\\<Psi>'.map))\"\n            using 0 1 NaturalTransformation.inverse_transformations_inverse(1) Cop_S.comp_MkArr\n            by (metis Cop_S.cod_MkArr Cop_S.ide_char' Cop_S.seqE)\n        qed\n      qed\n      hence 3: \"Cop_S.iso (Cop_S.MkArr (Y a) (Y a') \\<Phi>\\<Psi>'.map)\" using Cop_S.isoI by blast\n      hence \"Cop_S.arr (Cop_S.MkArr (Y a) (Y a') \\<Phi>\\<Psi>'.map)\" using Cop_S.iso_is_arr by blast\n      hence \"Cop_S.in_hom (Cop_S.MkArr (Y a) (Y a') \\<Phi>\\<Psi>'.map) (map a) (map a')\"\n        using Ya.ide_a Ya'.ide_a Cop_S.dom_char Cop_S.cod_char by auto\n      hence \"\\<exists>f. \\<guillemotleft>f : a \\<rightarrow> a'\\<guillemotright> \\<and> map f = Cop_S.MkArr (Y a) (Y a') \\<Phi>\\<Psi>'.map\"\n        using Ya.ide_a Ya'.ide_a is_full Y_def Cop_S.iso_is_arr full_functor.is_full\n        by auto     \n      from this obtain \\<phi>\n        where \\<phi>: \"\\<guillemotleft>\\<phi> : a \\<rightarrow> a'\\<guillemotright> \\<and> map \\<phi> = Cop_S.MkArr (Y a) (Y a') \\<Phi>\\<Psi>'.map\"\n        by blast\n      from \\<phi> have \"C.iso \\<phi>\"\n        using 3 reflects_iso [of \\<phi> a a'] by simp\n      hence EX: \"\\<exists>\\<phi>. \\<guillemotleft>\\<phi> : a \\<rightarrow> a'\\<guillemotright> \\<and> C.iso \\<phi> \\<and> map \\<phi> = Cop_S.MkArr (Y a) (Y a') \\<Phi>\\<Psi>'.map\"\n        using \\<phi> by blast\n      have\n        UN: \"\\<And>\\<phi>'. \\<guillemotleft>\\<phi>' : a \\<rightarrow> a'\\<guillemotright> \\<and> map \\<phi>' = Cop_S.MkArr (Y a) (Y a') \\<Phi>\\<Psi>'.map \\<Longrightarrow> \\<phi>' = \\<phi>\"\n      proof -\n        fix \\<phi>'\n        assume \\<phi>': \"\\<guillemotleft>\\<phi>' : a \\<rightarrow> a'\\<guillemotright> \\<and> map \\<phi>' = Cop_S.MkArr (Y a) (Y a') \\<Phi>\\<Psi>'.map\"\n        have \"C.par \\<phi> \\<phi>' \\<and> map \\<phi> = map \\<phi>'\" using \\<phi> \\<phi>' by auto\n        thus \"\\<phi>' = \\<phi>\" using is_faithful by fast\n      qed\n      from EX UN show ?thesis by auto\n    qed\n\n  end\n\n  section \"Diagrams and Cones\"\n\n  text\\<open>\n    A \\emph{diagram} in a category @{term C} is a functor \\<open>D: J \\<rightarrow> C\\<close>.\n    We refer to the category @{term J} as the diagram \\emph{shape}.\n    Note that in the usual expositions of category theory that use set theory\n    as their foundations, the shape @{term J} of a diagram is required to be\n    a ``small'' category, where smallness means that the collection of objects\n    of @{term J}, as well as each of the ``homs,'' is a set.\n    However, in HOL there is no class of all sets, so it is not meaningful\n    to speak of @{term J} as ``small'' in any kind of absolute sense.\n    There is likely a meaningful notion of smallness of @{term J}\n    \\emph{relative to} @{term C} (the result below that states that a set\n    category has @{term I}-indexed products if and only if its universe\n    ``admits @{term I}-indexed tuples'' is suggestive of how this might\n    be defined), but I haven't fully explored this idea at present.\n\\<close>\n\n  locale diagram =\n    C: category C +\n    J: category J +\n    \"functor\" J C D\n  for J :: \"'j comp\"      (infixr \"\\<cdot>\\<^sub>J\" 55)\n  and C :: \"'c comp\"      (infixr \"\\<cdot>\" 55)\n  and D :: \"'j \\<Rightarrow> 'c\"\n  begin\n\n    notation J.in_hom (\"\\<guillemotleft>_ : _ \\<rightarrow>\\<^sub>J _\\<guillemotright>\")\n\n  end\n \n  lemma comp_diagram_functor:\n  assumes \"diagram J C D\" and \"functor J' J F\"\n  shows \"diagram J' C (D o F)\"\n    by (meson assms(1) assms(2) diagram_def functor.axioms(1) functor_comp)\n    \n  text\\<open>\n    A \\emph{cone} over a diagram \\<open>D: J \\<rightarrow> C\\<close> is a natural transformation\n    from a constant functor to @{term D}.  The value of the constant functor is\n    the \\emph{apex} of the cone.\n\\<close>\n\n  locale cone =\n    C: category C +\n    J: category J +\n    D: diagram J C D +\n    A: constant_functor J C a +\n    natural_transformation J C A.map D \\<chi>\n  for J :: \"'j comp\"      (infixr \"\\<cdot>\\<^sub>J\" 55)\n  and C :: \"'c comp\"      (infixr \"\\<cdot>\" 55)\n  and D :: \"'j \\<Rightarrow> 'c\"\n  and a :: 'c\n  and \\<chi> :: \"'j \\<Rightarrow> 'c\"\n  begin\n\n    lemma ide_apex:\n    shows \"C.ide a\"\n      using A.value_is_ide by auto\n\n    lemma component_in_hom:\n    assumes \"J.arr j\"\n    shows \"\\<guillemotleft>\\<chi> j : a \\<rightarrow> D (J.cod j)\\<guillemotright>\"\n      using assms by auto\n\n  end\n\n  text\\<open>\n    A cone over diagram @{term D} is transformed into a cone over diagram @{term \"D o F\"}\n    by pre-composing with @{term F}.\n\\<close>\n\n  lemma comp_cone_functor:\n  assumes \"cone J C D a \\<chi>\" and \"functor J' J F\"\n  shows \"cone J' C (D o F) a (\\<chi> o F)\"\n  proof -\n    interpret \\<chi>: cone J C D a \\<chi> using assms(1) by auto\n    interpret F: \"functor\" J' J F using assms(2) by auto\n    interpret A': constant_functor J' C a\n      apply unfold_locales using \\<chi>.A.value_is_ide by auto\n    have 1: \"\\<chi>.A.map o F = A'.map\"\n      using \\<chi>.A.map_def A'.map_def \\<chi>.J.not_arr_null by auto\n    interpret \\<chi>': natural_transformation J' C A'.map \\<open>D o F\\<close> \\<open>\\<chi> o F\\<close>\n      using 1 horizontal_composite F.natural_transformation_axioms\n            \\<chi>.natural_transformation_axioms\n      by fastforce\n    show \"cone J' C (D o F) a (\\<chi> o F)\" ..\n  qed\n\n  text\\<open>\n    A cone over diagram @{term D} can be transformed into a cone over a diagram @{term D'}\n    by post-composing with a natural transformation from @{term D} to @{term D'}.\n\\<close>\n\n  lemma vcomp_transformation_cone:\n  assumes \"cone J C D a \\<chi>\"\n  and \"natural_transformation J C D D' \\<tau>\"\n  shows \"cone J C D' a (vertical_composite.map J C \\<chi> \\<tau>)\"\n  proof -\n    interpret \\<chi>: cone J C D a \\<chi> using assms(1) by auto\n    interpret \\<tau>: natural_transformation J C D D' \\<tau> using assms(2) by auto\n    interpret \\<tau>o\\<chi>: vertical_composite J C \\<chi>.A.map D D' \\<chi> \\<tau> ..\n    interpret \\<tau>o\\<chi>: cone J C D' a \\<tau>o\\<chi>.map ..\n    show ?thesis ..\n  qed\n\n  context \"functor\"\n  begin\n\n    lemma preserves_diagrams:\n    fixes J :: \"'j comp\"\n    assumes \"diagram J A D\"\n    shows \"diagram J B (F o D)\"\n    proof -\n      interpret D: diagram J A D using assms by auto\n      interpret FoD: composite_functor J A B D F ..\n      show \"diagram J B (F o D)\" ..\n    qed\n\n    lemma preserves_cones:\n    fixes J :: \"'j comp\"\n    assumes \"cone J A D a \\<chi>\"\n    shows \"cone J B (F o D) (F a) (F o \\<chi>)\"\n    proof -\n      interpret \\<chi>: cone J A D a \\<chi> using assms by auto\n      interpret Fa: constant_functor J B \\<open>F a\\<close>\n        apply unfold_locales using \\<chi>.ide_apex by auto\n      have 1: \"F o \\<chi>.A.map = Fa.map\"\n      proof\n        fix f\n        show \"(F \\<circ> \\<chi>.A.map) f = Fa.map f\"\n          using is_extensional Fa.is_extensional \\<chi>.A.is_extensional\n          by (cases \"\\<chi>.J.arr f\", simp_all)\n      qed\n      interpret \\<chi>': natural_transformation J B Fa.map \\<open>F o D\\<close> \\<open>F o \\<chi>\\<close>\n        using 1 horizontal_composite \\<chi>.natural_transformation_axioms\n              natural_transformation_axioms\n        by fastforce\n      show \"cone J B (F o D) (F a) (F o \\<chi>)\" ..\n    qed\n\n  end\n\n  context diagram\n  begin\n\n    abbreviation cone\n    where \"cone a \\<chi> \\<equiv> Limit.cone J C D a \\<chi>\"\n\n    abbreviation cones :: \"'c \\<Rightarrow> ('j \\<Rightarrow> 'c) set\"\n    where \"cones a \\<equiv> { \\<chi>. cone a \\<chi> }\"\n\n    text\\<open>\n      An arrow @{term \"f \\<in> C.hom a' a\"} induces by composition a transformation from\n      cones with apex @{term a} to cones with apex @{term a'}.  This transformation\n      is functorial in @{term f}.\n\\<close>\n\n    abbreviation cones_map :: \"'c \\<Rightarrow> ('j \\<Rightarrow> 'c) \\<Rightarrow> ('j \\<Rightarrow> 'c)\"\n    where \"cones_map f \\<equiv> (\\<lambda>\\<chi> \\<in> cones (C.cod f). \\<lambda>j. if J.arr j then \\<chi> j \\<cdot> f else C.null)\"\n\n    lemma cones_map_mapsto:\n    assumes \"C.arr f\"\n    shows \"cones_map f \\<in>\n             extensional (cones (C.cod f)) \\<inter> (cones (C.cod f) \\<rightarrow> cones (C.dom f))\"\n    proof\n      show \"cones_map f \\<in> extensional (cones (C.cod f))\" by blast\n      show \"cones_map f \\<in> cones (C.cod f) \\<rightarrow> cones (C.dom f)\"\n      proof\n        fix \\<chi>\n        assume \"\\<chi> \\<in> cones (C.cod f)\"\n        hence \\<chi>: \"cone (C.cod f) \\<chi>\" by auto\n        interpret \\<chi>: cone J C D \\<open>C.cod f\\<close> \\<chi> using \\<chi> by auto\n        interpret B: constant_functor J C \\<open>C.dom f\\<close>\n          apply unfold_locales using assms by auto\n        have \"cone (C.dom f) (\\<lambda>j. if J.arr j then \\<chi> j \\<cdot> f else C.null)\"\n          using assms B.value_is_ide \\<chi>.is_natural_1 \\<chi>.is_natural_2\n          apply (unfold_locales, auto)\n          using \\<chi>.is_natural_1\n           apply (metis C.comp_assoc)\n          using \\<chi>.is_natural_2 C.comp_arr_dom\n          by (metis J.arr_cod_iff_arr J.cod_cod C.comp_assoc)\n        thus \"(\\<lambda>j. if J.arr j then \\<chi> j \\<cdot> f else C.null) \\<in> cones (C.dom f)\" by auto\n      qed\n    qed\n\n    lemma cones_map_ide:\n    assumes \"\\<chi> \\<in> cones a\"\n    shows \"cones_map a \\<chi> = \\<chi>\"\n    proof -\n      interpret \\<chi>: cone J C D a \\<chi> using assms by auto\n      show ?thesis\n      proof\n        fix j\n        show \"cones_map a \\<chi> j = \\<chi> j\"\n          using assms \\<chi>.A.value_is_ide \\<chi>.preserves_hom C.comp_arr_dom \\<chi>.is_extensional\n          by (cases \"J.arr j\", auto)\n      qed\n    qed\n\n    lemma cones_map_comp:\n    assumes \"C.seq f g\"\n    shows \"cones_map (f \\<cdot> g) = restrict (cones_map g o cones_map f) (cones (C.cod f))\"\n    proof (intro restr_eqI)\n      show \"cones (C.cod (f \\<cdot> g)) = cones (C.cod f)\" using assms by simp\n      show \"\\<And>\\<chi>. \\<chi> \\<in> cones (C.cod (f \\<cdot> g)) \\<Longrightarrow>\n                  (\\<lambda>j. if J.arr j then \\<chi> j \\<cdot> f \\<cdot> g else C.null) = (cones_map g o cones_map f) \\<chi>\"\n      proof -\n        fix \\<chi>\n        assume \\<chi>: \"\\<chi> \\<in> cones (C.cod (f \\<cdot> g))\"\n        show \"(\\<lambda>j. if J.arr j then \\<chi> j \\<cdot> f \\<cdot> g else C.null) = (cones_map g o cones_map f) \\<chi>\"\n        proof -\n          have \"((cones_map g) o (cones_map f)) \\<chi> = cones_map g (cones_map f \\<chi>)\"\n            by force\n          also have \"... = (\\<lambda>j. if J.arr j then\n                              (\\<lambda>j. if J.arr j then \\<chi> j \\<cdot> f else C.null) j \\<cdot> g else C.null)\"\n          proof\n            fix j\n            have \"cone (C.dom f) (cones_map f \\<chi>)\"\n              using assms \\<chi> cones_map_mapsto by (elim C.seqE, force)\n            thus \"cones_map g (cones_map f \\<chi>) j =\n                  (if J.arr j then C (if J.arr j then \\<chi> j \\<cdot> f else C.null) g else C.null)\"\n              using \\<chi> assms by auto\n          qed\n          also have \"... = (\\<lambda>j. if J.arr j then \\<chi> j \\<cdot> f \\<cdot> g else C.null)\"\n          proof -\n            have \"\\<And>j. J.arr j \\<Longrightarrow> (\\<chi> j \\<cdot> f) \\<cdot> g = \\<chi> j \\<cdot> f \\<cdot> g\"\n            proof -\n              interpret \\<chi>: cone J C D \\<open>C.cod f\\<close> \\<chi> using assms \\<chi> by auto\n              fix j\n              assume j: \"J.arr j\"\n              show \"(\\<chi> j \\<cdot> f) \\<cdot> g = \\<chi> j \\<cdot> f \\<cdot> g\"\n                using assms C.comp_assoc by simp\n            qed\n            thus ?thesis by auto\n          qed\n          finally show ?thesis by auto\n        qed\n      qed\n    qed\n\n  end\n\n  text\\<open>\n    Changing the apex of a cone by pre-composing with an arrow @{term f} commutes\n    with changing the diagram of a cone by post-composing with a natural transformation.\n\\<close>\n\n  lemma cones_map_vcomp:\n  assumes \"diagram J C D\" and \"diagram J C D'\"\n  and \"natural_transformation J C D D' \\<tau>\"\n  and \"cone J C D a \\<chi>\"\n  and f: \"partial_magma.in_hom C f a' a\"\n  shows \"diagram.cones_map J C D' f (vertical_composite.map J C \\<chi> \\<tau>)\n           = vertical_composite.map J C (diagram.cones_map J C D f \\<chi>) \\<tau>\"\n  proof -\n    interpret D: diagram J C D using assms(1) by auto\n    interpret D': diagram J C D' using assms(2) by auto\n    interpret \\<tau>: natural_transformation J C D D' \\<tau> using assms(3) by auto\n    interpret \\<chi>: cone J C D a \\<chi> using assms(4) by auto\n    interpret \\<tau>o\\<chi>: vertical_composite J C \\<chi>.A.map D D' \\<chi> \\<tau> ..\n    interpret \\<tau>o\\<chi>: cone J C D' a \\<tau>o\\<chi>.map ..\n    interpret \\<chi>f: cone J C D a' \\<open>D.cones_map f \\<chi>\\<close>\n      using f \\<chi>.cone_axioms D.cones_map_mapsto by blast\n    interpret \\<tau>o\\<chi>f: vertical_composite J C \\<chi>f.A.map D D' \\<open>D.cones_map f \\<chi>\\<close> \\<tau> ..\n    interpret \\<tau>o\\<chi>_f: cone J C D' a' \\<open>D'.cones_map f \\<tau>o\\<chi>.map\\<close>\n      using f \\<tau>o\\<chi>.cone_axioms D'.cones_map_mapsto [of f] by blast\n    write C (infixr \"\\<cdot>\" 55)\n    show \"D'.cones_map f \\<tau>o\\<chi>.map = \\<tau>o\\<chi>f.map\"\n    proof (intro NaturalTransformation.eqI)\n      show \"natural_transformation J C \\<chi>f.A.map D' (D'.cones_map f \\<tau>o\\<chi>.map)\" ..\n      show \"natural_transformation J C \\<chi>f.A.map D' \\<tau>o\\<chi>f.map\" ..\n      show \"\\<And>j. D.J.ide j \\<Longrightarrow> D'.cones_map f \\<tau>o\\<chi>.map j = \\<tau>o\\<chi>f.map j\"\n      proof -\n        fix j\n        assume j: \"D.J.ide j\"\n        have \"D'.cones_map f \\<tau>o\\<chi>.map j = \\<tau>o\\<chi>.map j \\<cdot> f\"\n          using f \\<tau>o\\<chi>.cone_axioms \\<tau>o\\<chi>.map_simp_2 \\<tau>o\\<chi>.is_extensional by auto\n        also have \"... = (\\<tau> j \\<cdot> \\<chi> (D.J.dom j)) \\<cdot> f\"\n          using j \\<tau>o\\<chi>.map_simp_2 by simp\n        also have \"... = \\<tau> j \\<cdot> \\<chi> (D.J.dom j) \\<cdot> f\"\n          using D.C.comp_assoc by simp\n        also have \"... = \\<tau>o\\<chi>f.map j\"\n          using j f \\<chi>.cone_axioms \\<tau>o\\<chi>f.map_simp_2 by auto\n        finally show \"D'.cones_map f \\<tau>o\\<chi>.map j = \\<tau>o\\<chi>f.map j\" by auto\n      qed\n    qed\n  qed\n\n  text\\<open>\n    Given a diagram @{term D}, we can construct a contravariant set-valued functor,\n    which takes each object @{term a} of @{term C} to the set of cones over @{term D}\n    with apex @{term a}, and takes each arrow @{term f} of @{term C} to the function\n    on cones over @{term D} induced by pre-composition with @{term f}.\n    For this, we need to introduce a set category @{term S} whose universe is large\n    enough to contain all the cones over @{term D}, and we need to have an explicit\n    correspondence between cones and elements of the universe of @{term S}.\n    A set category @{term S} equipped with an injective mapping\n    @{term_type \"\\<iota> :: ('j => 'c) => 's\"} serves this purpose.\n\\<close>\n  locale cones_functor =\n    C: category C +\n    Cop: dual_category C +\n    J: category J +\n    D: diagram J C D +\n    S: concrete_set_category S UNIV \\<iota>\n  for J :: \"'j comp\"      (infixr \"\\<cdot>\\<^sub>J\" 55)\n  and C :: \"'c comp\"      (infixr \"\\<cdot>\" 55)\n  and D :: \"'j \\<Rightarrow> 'c\"\n  and S :: \"'s comp\"      (infixr \"\\<cdot>\\<^sub>S\" 55)\n  and \\<iota> :: \"('j \\<Rightarrow> 'c) \\<Rightarrow> 's\"\n  begin\n\n    notation S.in_hom     (\"\\<guillemotleft>_ : _ \\<rightarrow>\\<^sub>S _\\<guillemotright>\")\n\n    abbreviation \\<o> where \"\\<o> \\<equiv> S.\\<o>\"\n\n    definition map :: \"'c \\<Rightarrow> 's\"\n    where \"map = (\\<lambda>f. if C.arr f then\n                        S.mkArr (\\<iota> ` D.cones (C.cod f)) (\\<iota> ` D.cones (C.dom f))\n                                (\\<iota> o D.cones_map f o \\<o>)\n                      else S.null)\"\n\n    lemma map_simp [simp]:\n    assumes \"C.arr f\"\n    shows \"map f = S.mkArr (\\<iota> ` D.cones (C.cod f)) (\\<iota> ` D.cones (C.dom f))\n                           (\\<iota> o D.cones_map f o \\<o>)\"\n      using assms map_def by auto\n\n    lemma arr_map:\n    assumes \"C.arr f\"\n    shows \"S.arr (map f)\"\n    proof -\n      have \"\\<iota> o D.cones_map f o \\<o> \\<in> \\<iota> ` D.cones (C.cod f) \\<rightarrow> \\<iota> ` D.cones (C.dom f)\"\n        using assms D.cones_map_mapsto by force\n      thus ?thesis using assms S.\\<iota>_mapsto by auto\n    qed\n\n    lemma map_ide:\n    assumes \"C.ide a\"\n    shows \"map a = S.mkIde (\\<iota> ` D.cones a)\"\n    proof -\n      have \"map a = S.mkArr (\\<iota> ` D.cones a) (\\<iota> ` D.cones a) (\\<iota> o D.cones_map a o \\<o>)\"\n        using assms map_simp by force\n      also have \"... = S.mkArr (\\<iota> ` D.cones a) (\\<iota> ` D.cones a) (\\<lambda>x. x)\"\n        using S.\\<iota>_mapsto D.cones_map_ide by force\n      also have \"... = S.mkIde (\\<iota> ` D.cones a)\"\n        using assms S.mkIde_as_mkArr S.\\<iota>_mapsto by blast\n      finally show ?thesis by auto\n    qed\n\n    lemma map_preserves_dom:\n    assumes \"Cop.arr f\"\n    shows \"map (Cop.dom f) = S.dom (map f)\"\n      using assms arr_map map_ide by auto\n\n    lemma map_preserves_cod:\n    assumes \"Cop.arr f\"\n    shows \"map (Cop.cod f) = S.cod (map f)\"\n      using assms arr_map map_ide by auto\n\n    lemma map_preserves_comp:\n    assumes \"Cop.seq g f\"\n    shows \"map (g \\<cdot>\\<^sup>o\\<^sup>p f) = map g \\<cdot>\\<^sub>S map f\"\n    proof -\n      have 0: \"S.seq (map g) (map f)\"\n        using assms arr_map [of f] arr_map [of g] map_simp\n        by (intro S.seqI, auto)\n      have \"map (g \\<cdot>\\<^sup>o\\<^sup>p f) = S.mkArr (\\<iota> ` D.cones (C.cod f)) (\\<iota> ` D.cones (C.dom g))\n                                   ((\\<iota> o D.cones_map g o \\<o>) o (\\<iota> o D.cones_map f o \\<o>))\"\n      proof -\n        have 1: \"S.arr (map (g \\<cdot>\\<^sup>o\\<^sup>p f))\"\n          using assms arr_map [of \"C f g\"] by simp\n        have \"map (g \\<cdot>\\<^sup>o\\<^sup>p f) = S.mkArr (\\<iota> ` D.cones (C.cod f)) (\\<iota> ` D.cones (C.dom g))\n                                     (\\<iota> o D.cones_map (C f g) o \\<o>)\"\n          using assms map_simp [of \"C f g\"] by simp\n        also have \"... = S.mkArr (\\<iota> ` D.cones (C.cod f)) (\\<iota> ` D.cones (C.dom g))\n                                 ((\\<iota> o D.cones_map g o \\<o>) o (\\<iota> o D.cones_map f o \\<o>))\"\n          using assms 1 calculation D.cones_map_mapsto D.cones_map_comp by auto\n        finally show ?thesis by blast\n      qed\n      also have \"... = map g \\<cdot>\\<^sub>S map f\"\n        using assms 0 by (elim S.seqE, auto)\n      finally show ?thesis by auto\n    qed\n\n    lemma is_functor:\n    shows \"functor Cop.comp S map\"\n      apply (unfold_locales)\n      using map_def arr_map map_preserves_dom map_preserves_cod map_preserves_comp\n      by auto\n    \n  end\n\n  sublocale cones_functor \\<subseteq> \"functor\" Cop.comp S map using is_functor by auto\n  sublocale cones_functor \\<subseteq> set_valued_functor Cop.comp S map ..\n\n  section Limits\n\n  subsection \"Limit Cones\"\n\n  text\\<open>\n    A \\emph{limit cone} for a diagram @{term D} is a cone @{term \\<chi>} over @{term D}\n    with the universal property that any other cone @{term \\<chi>'} over the diagram @{term D}\n    factors uniquely through @{term \\<chi>}.\n\\<close>\n\n  locale limit_cone =\n    C: category C +\n    J: category J +\n    D: diagram J C D +\n    cone J C D a \\<chi>\n  for J :: \"'j comp\"      (infixr \"\\<cdot>\\<^sub>J\" 55)\n  and C :: \"'c comp\"      (infixr \"\\<cdot>\" 55)\n  and D :: \"'j \\<Rightarrow> 'c\"\n  and a :: 'c\n  and \\<chi> :: \"'j \\<Rightarrow> 'c\" +\n  assumes is_universal: \"cone J C D a' \\<chi>' \\<Longrightarrow> \\<exists>!f. \\<guillemotleft>f : a' \\<rightarrow> a\\<guillemotright> \\<and> D.cones_map f \\<chi> = \\<chi>'\"\n  begin\n\n    definition induced_arrow :: \"'c \\<Rightarrow> ('j \\<Rightarrow> 'c) \\<Rightarrow> 'c\"\n    where \"induced_arrow a' \\<chi>' = (THE f. \\<guillemotleft>f : a' \\<rightarrow> a\\<guillemotright> \\<and> D.cones_map f \\<chi> = \\<chi>')\"\n\n    lemma induced_arrowI:\n    assumes \\<chi>': \"\\<chi>' \\<in> D.cones a'\"\n    shows \"\\<guillemotleft>induced_arrow a' \\<chi>' : a' \\<rightarrow> a\\<guillemotright>\"\n    and \"D.cones_map (induced_arrow a' \\<chi>') \\<chi> = \\<chi>'\"\n    proof -\n      have \"\\<exists>!f. \\<guillemotleft>f : a' \\<rightarrow> a\\<guillemotright> \\<and> D.cones_map f \\<chi> = \\<chi>'\"\n        using assms \\<chi>' is_universal by simp\n      hence 1: \"\\<guillemotleft>induced_arrow a' \\<chi>' : a' \\<rightarrow> a\\<guillemotright> \\<and> D.cones_map (induced_arrow a' \\<chi>') \\<chi> = \\<chi>'\"\n        using theI' [of \"\\<lambda>f. \\<guillemotleft>f : a' \\<rightarrow> a\\<guillemotright> \\<and> D.cones_map f \\<chi> = \\<chi>'\"] induced_arrow_def\n        by presburger\n      show \"\\<guillemotleft>induced_arrow a' \\<chi>' : a' \\<rightarrow> a\\<guillemotright>\" using 1 by simp\n      show \"D.cones_map (induced_arrow a' \\<chi>') \\<chi> = \\<chi>'\" using 1 by simp\n    qed\n\n    lemma cones_map_induced_arrow:\n    shows \"induced_arrow a' \\<in> D.cones a' \\<rightarrow> C.hom a' a\"\n    and \"\\<And>\\<chi>'. \\<chi>' \\<in> D.cones a' \\<Longrightarrow> D.cones_map (induced_arrow a' \\<chi>') \\<chi> = \\<chi>'\"\n      using induced_arrowI by auto\n\n    lemma induced_arrow_cones_map:\n    assumes \"C.ide a'\"\n    shows \"(\\<lambda>f. D.cones_map f \\<chi>) \\<in> C.hom a' a \\<rightarrow> D.cones a'\"\n    and \"\\<And>f. \\<guillemotleft>f : a' \\<rightarrow> a\\<guillemotright> \\<Longrightarrow> induced_arrow a' (D.cones_map f \\<chi>) = f\"\n    proof -\n      have a': \"C.ide a'\" using assms by (simp add: cone.ide_apex)\n      have cone_\\<chi>: \"cone J C D a \\<chi>\" ..\n      show \"(\\<lambda>f. D.cones_map f \\<chi>) \\<in> C.hom a' a \\<rightarrow> D.cones a'\"\n        using cone_\\<chi> D.cones_map_mapsto by blast\n      fix f\n      assume f: \"\\<guillemotleft>f : a' \\<rightarrow> a\\<guillemotright>\"\n      show \"induced_arrow a' (D.cones_map f \\<chi>) = f\"\n      proof -\n        have \"D.cones_map f \\<chi> \\<in> D.cones a'\"\n          using f cone_\\<chi> D.cones_map_mapsto by blast\n        hence \"\\<exists>!f'. \\<guillemotleft>f' : a' \\<rightarrow> a\\<guillemotright> \\<and> D.cones_map f' \\<chi> = D.cones_map f \\<chi>\"\n          using assms is_universal by auto\n        thus ?thesis\n          using f induced_arrow_def\n                the1_equality [of \"\\<lambda>f'. \\<guillemotleft>f' : a' \\<rightarrow> a\\<guillemotright> \\<and> D.cones_map f' \\<chi> = D.cones_map f \\<chi>\"]\n          by presburger\n      qed\n    qed\n\n    text\\<open>\n      For a limit cone @{term \\<chi>} with apex @{term a}, for each object @{term a'} the\n      hom-set @{term \"C.hom a' a\"} is in bijective correspondence with the set of cones\n      with apex @{term a'}.\n\\<close>\n\n    lemma bij_betw_hom_and_cones:\n    assumes \"C.ide a'\"\n    shows \"bij_betw (\\<lambda>f. D.cones_map f \\<chi>) (C.hom a' a) (D.cones a')\"\n    proof (intro bij_betwI)\n      show \"(\\<lambda>f. D.cones_map f \\<chi>) \\<in> C.hom a' a \\<rightarrow> D.cones a'\"\n        using assms induced_arrow_cones_map by blast\n      show \"induced_arrow a' \\<in> D.cones a' \\<rightarrow> C.hom a' a\"\n        using assms cones_map_induced_arrow by blast\n      show \"\\<And>f. f \\<in> C.hom a' a \\<Longrightarrow> induced_arrow a' (D.cones_map f \\<chi>) = f\"\n        using assms induced_arrow_cones_map by blast\n      show \"\\<And>\\<chi>'. \\<chi>' \\<in> D.cones a' \\<Longrightarrow> D.cones_map (induced_arrow a' \\<chi>') \\<chi> = \\<chi>'\"\n        using assms cones_map_induced_arrow by blast\n    qed\n\n    lemma induced_arrow_eqI:\n    assumes \"D.cone a' \\<chi>'\" and \"\\<guillemotleft>f : a' \\<rightarrow> a\\<guillemotright>\" and \"D.cones_map f \\<chi> = \\<chi>'\"\n    shows \"induced_arrow a' \\<chi>' = f\"\n      using assms is_universal induced_arrow_def\n            the1_equality [of \"\\<lambda>f. f \\<in> C.hom a' a \\<and> D.cones_map f \\<chi> = \\<chi>'\" f]\n      by simp\n\n    lemma induced_arrow_self:\n    shows \"induced_arrow a \\<chi> = a\"\n    proof -\n      have \"\\<guillemotleft>a : a \\<rightarrow> a\\<guillemotright> \\<and> D.cones_map a \\<chi> = \\<chi>\"\n        using ide_apex cone_axioms D.cones_map_ide by force\n      thus ?thesis using induced_arrow_eqI cone_axioms by auto\n    qed\n\n  end\n\n  context diagram\n  begin\n\n    abbreviation limit_cone\n    where \"limit_cone a \\<chi> \\<equiv> Limit.limit_cone J C D a \\<chi>\"\n\n    text\\<open>\n      A diagram @{term D} has object @{term a} as a limit if @{term a} is the apex\n      of some limit cone over @{term D}.\n\\<close>\n\n    abbreviation has_as_limit :: \"'c \\<Rightarrow> bool\"\n    where \"has_as_limit a \\<equiv> (\\<exists>\\<chi>. limit_cone a \\<chi>)\"\n\n    abbreviation has_limit\n    where \"has_limit \\<equiv> (\\<exists>a \\<chi>. limit_cone a \\<chi>)\"\n\n    definition some_limit :: 'c\n    where \"some_limit = (SOME a. \\<exists>\\<chi>. limit_cone a \\<chi>)\"\n\n    definition some_limit_cone :: \"'j \\<Rightarrow> 'c\"\n    where \"some_limit_cone = (SOME \\<chi>. limit_cone some_limit \\<chi>)\"\n\n    lemma limit_cone_some_limit_cone:\n    assumes has_limit\n    shows \"limit_cone some_limit some_limit_cone\"\n    proof -\n      have \"\\<exists>a. has_as_limit a\" using assms by simp\n      hence \"has_as_limit some_limit\"\n        using some_limit_def someI_ex [of \"\\<lambda>a. \\<exists>\\<chi>. limit_cone a \\<chi>\"] by simp\n      thus \"limit_cone some_limit some_limit_cone\"\n        using assms some_limit_cone_def someI_ex [of \"\\<lambda>\\<chi>. limit_cone some_limit \\<chi>\"]\n        by simp\n    qed\n\n    lemma ex_limitE:\n    assumes \"\\<exists>a. has_as_limit a\"\n    obtains a \\<chi> where \"limit_cone a \\<chi>\"\n      using assms someI_ex by blast\n\n  end\n\n  subsection \"Limits by Representation\"\n\n  text\\<open>\n    A limit for a diagram D can also be given by a representation \\<open>(a, \\<Phi>)\\<close>\n    of the cones functor.\n\\<close>\n\n  locale representation_of_cones_functor =\n    C: category C +\n    Cop: dual_category C +\n    J: category J +\n    D: diagram J C D +\n    S: concrete_set_category S UNIV \\<iota> +\n    Cones: cones_functor J C D S \\<iota> +\n    Hom: hom_functor C S \\<phi> +\n    representation_of_functor C S \\<phi> Cones.map a \\<Phi>\n  for J :: \"'j comp\"      (infixr \"\\<cdot>\\<^sub>J\" 55)\n  and C :: \"'c comp\"      (infixr \"\\<cdot>\" 55)\n  and D :: \"'j \\<Rightarrow> 'c\"\n  and S :: \"'s comp\"      (infixr \"\\<cdot>\\<^sub>S\" 55)\n  and \\<phi> :: \"'c * 'c \\<Rightarrow> 'c \\<Rightarrow> 's\"\n  and \\<iota> :: \"('j \\<Rightarrow> 'c) \\<Rightarrow> 's\"\n  and a :: 'c\n  and \\<Phi> :: \"'c \\<Rightarrow> 's\"\n\n  subsection \"Putting it all Together\"\n\n  text\\<open>\n    A ``limit situation'' combines and connects the ways of presenting a limit.\n\\<close>\n\n  locale limit_situation =\n    C: category C +\n    Cop: dual_category C +\n    J: category J +\n    D: diagram J C D +\n    S: concrete_set_category S UNIV \\<iota> +\n    Cones: cones_functor J C D S \\<iota> +\n    Hom: hom_functor C S \\<phi> +\n    \\<Phi>: representation_of_functor C S \\<phi> Cones.map a \\<Phi> +\n    \\<chi>: limit_cone J C D a \\<chi>\n  for J :: \"'j comp\"      (infixr \"\\<cdot>\\<^sub>J\" 55)\n  and C :: \"'c comp\"      (infixr \"\\<cdot>\" 55)\n  and D :: \"'j \\<Rightarrow> 'c\"\n  and S :: \"'s comp\"      (infixr \"\\<cdot>\\<^sub>S\" 55)\n  and \\<phi> :: \"'c * 'c \\<Rightarrow> 'c \\<Rightarrow> 's\"\n  and \\<iota> :: \"('j \\<Rightarrow> 'c) \\<Rightarrow> 's\"\n  and a :: 'c\n  and \\<Phi> :: \"'c \\<Rightarrow> 's\"\n  and \\<chi> :: \"'j \\<Rightarrow> 'c\" +\n  assumes \\<chi>_in_terms_of_\\<Phi>: \"\\<chi> = S.\\<o> (S.Fun (\\<Phi> a) (\\<phi> (a, a) a))\"\n  and \\<Phi>_in_terms_of_\\<chi>:\n     \"Cop.ide a' \\<Longrightarrow> \\<Phi> a' = S.mkArr (Hom.set (a', a)) (\\<iota> ` D.cones a')\n                                    (\\<lambda>x. \\<iota> (D.cones_map (Hom.\\<psi> (a', a) x) \\<chi>))\"\n\n  text (in limit_situation) \\<open>\n    The assumption @{prop \\<chi>_in_terms_of_\\<Phi>} states that the universal cone @{term \\<chi>} is obtained\n    by applying the function @{term \"S.Fun (\\<Phi> a)\"} to the identity @{term a} of\n    @{term[source=true] C} (after taking into account the necessary coercions).\n\\<close>\n\n  text (in limit_situation) \\<open>\n    The assumption @{prop \\<Phi>_in_terms_of_\\<chi>} states that the component of @{term \\<Phi>} at @{term a'}\n    is the arrow of @{term[source=true] S} corresponding to the function that takes an arrow\n    @{term \"f \\<in> C.hom a' a\"} and produces the cone with vertex @{term a'} obtained\n    by transforming the universal cone @{term \\<chi>} by @{term f}.\n\\<close>\n\n  subsection \"Limit Cones Induce Limit Situations\"\n\n  text\\<open>\n    To obtain a limit situation from a limit cone, we need to introduce a set category\n    that is large enough to contain the hom-sets of @{term C} as well as the cones\n    over @{term D}.  We use the category of @{typ \"('c + ('j \\<Rightarrow> 'c))\"}-sets for this.\n\\<close>\n\n  context limit_cone\n  begin\n\n    interpretation Cop: dual_category C ..\n    interpretation CopxC: product_category Cop.comp C ..\n    interpretation S: set_category \\<open>SetCat.comp :: ('c + ('j \\<Rightarrow> 'c)) setcat.arr comp\\<close>\n      using SetCat.is_set_category by auto\n\n    interpretation S: concrete_set_category \\<open>SetCat.comp :: ('c + ('j \\<Rightarrow> 'c)) setcat.arr comp\\<close>\n                                            UNIV \\<open>UP o Inr\\<close>\n      apply unfold_locales\n      using UP_mapsto\n       apply auto[1]\n      using inj_UP inj_Inr inj_compose\n      by metis\n\n    notation SetCat.comp      (infixr \"\\<cdot>\\<^sub>S\" 55)\n\n    interpretation Cones: cones_functor J C D \\<open>SetCat.comp :: ('c + ('j \\<Rightarrow> 'c)) setcat.arr comp\\<close>\n                                        \\<open>UP o Inr\\<close> ..\n\n    interpretation Hom: hom_functor C \\<open>SetCat.comp :: ('c + ('j \\<Rightarrow> 'c)) setcat.arr comp\\<close>\n                                      \\<open>\\<lambda>_. UP o Inl\\<close>\n      apply (unfold_locales)\n      using UP_mapsto\n       apply auto[1]\n      using SetCat.inj_UP injD inj_onI inj_Inl inj_compose\n      by (metis (no_types, lifting))\n\n    interpretation Y: yoneda_functor C \\<open>SetCat.comp :: ('c + ('j \\<Rightarrow> 'c)) setcat.arr comp\\<close>\n                                     \\<open>\\<lambda>_. UP o Inl\\<close> ..\n    interpretation Ya: yoneda_functor_fixed_object\n                         C \\<open>SetCat.comp :: ('c + ('j \\<Rightarrow> 'c)) setcat.arr comp\\<close>\n                         \\<open>\\<lambda>_. UP o Inl\\<close> a\n      apply (unfold_locales) using ide_apex by auto\n\n    abbreviation inl :: \"'c \\<Rightarrow> 'c + ('j \\<Rightarrow> 'c)\" where \"inl \\<equiv> Inl\"\n    abbreviation inr :: \"('j \\<Rightarrow> 'c) \\<Rightarrow> 'c + ('j \\<Rightarrow> 'c)\" where \"inr \\<equiv> Inr\"\n    abbreviation \\<iota> where \"\\<iota> \\<equiv> UP o inr\"\n    abbreviation \\<o> where \"\\<o> \\<equiv> Cones.\\<o>\"\n    abbreviation \\<phi> where \"\\<phi> \\<equiv> \\<lambda>_. UP o inl\"\n    abbreviation \\<psi> where \"\\<psi> \\<equiv> Hom.\\<psi>\"\n    abbreviation Y where \"Y \\<equiv> Y.Y\"\n\n    lemma Ya_ide:\n    assumes a': \"C.ide a'\"\n    shows \"Y a a' = S.mkIde (Hom.set (a', a))\"\n      using assms ide_apex Y.Y_simp Hom.map_ide by simp\n\n    lemma Ya_arr:\n    assumes g: \"C.arr g\"\n    shows \"Y a g = S.mkArr (Hom.set (C.cod g, a)) (Hom.set (C.dom g, a))\n                           (\\<phi> (C.dom g, a) o Cop.comp g o \\<psi> (C.cod g, a))\"\n      using ide_apex g Y.Y_ide_arr [of a g \"C.dom g\" \"C.cod g\"] by auto\n\n    lemma cone_\\<chi> [simp]:\n    shows \"\\<chi> \\<in> D.cones a\"\n      using cone_axioms by simp\n    \n    text\\<open>\n      For each object @{term a'} of @{term[source=true] C} we have a function mapping\n      @{term \"C.hom a' a\"} to the set of cones over @{term D} with apex @{term a'},\n      which takes @{term \"f \\<in> C.hom a' a\"} to \\<open>\\<chi>f\\<close>, where \\<open>\\<chi>f\\<close> is the cone obtained by\n      composing @{term \\<chi>} with @{term f} (after accounting for coercions to and from the\n      universe of @{term S}).  The corresponding arrows of @{term S} are the\n      components of a natural isomorphism from @{term \"Y a\"} to \\<open>Cones\\<close>.\n\\<close>\n\n    definition \\<Phi>o :: \"'c \\<Rightarrow> ('c + ('j \\<Rightarrow> 'c)) setcat.arr\"\n    where\n      \"\\<Phi>o a' = S.mkArr (Hom.set (a', a)) (\\<iota> ` D.cones a') (\\<lambda>x. \\<iota> (D.cones_map (\\<psi> (a', a) x) \\<chi>))\"\n\n    lemma \\<Phi>o_in_hom:\n    assumes a': \"C.ide a'\"\n    shows \"\\<guillemotleft>\\<Phi>o a' : S.mkIde (Hom.set (a', a)) \\<rightarrow>\\<^sub>S S.mkIde (\\<iota> ` D.cones a')\\<guillemotright>\"\n    proof -\n      have \" \\<guillemotleft>S.mkArr (Hom.set (a', a)) (\\<iota> ` D.cones a') (\\<lambda>x. \\<iota> (D.cones_map (\\<psi> (a', a) x) \\<chi>)) :\n                 S.mkIde (Hom.set (a', a)) \\<rightarrow>\\<^sub>S S.mkIde (\\<iota> ` D.cones a')\\<guillemotright>\"\n      proof -\n        have \"(\\<lambda>x. \\<iota> (D.cones_map (\\<psi> (a', a) x) \\<chi>)) \\<in> Hom.set (a', a) \\<rightarrow> \\<iota> ` D.cones a'\"\n        proof\n          fix x\n          assume x: \"x \\<in> Hom.set (a', a)\"\n          hence \"\\<guillemotleft>\\<psi> (a', a) x : a' \\<rightarrow> a\\<guillemotright>\"\n            using ide_apex a' Hom.\\<psi>_mapsto by auto\n          hence \"D.cones_map (\\<psi> (a', a) x) \\<chi> \\<in> D.cones a'\"\n            using ide_apex a' x D.cones_map_mapsto cone_\\<chi> by force\n          thus \"\\<iota> (D.cones_map (\\<psi> (a', a) x) \\<chi>) \\<in> \\<iota> ` D.cones a'\" by simp\n        qed\n        moreover have \"Hom.set (a', a) \\<subseteq> S.Univ\"\n          using ide_apex a' Hom.set_subset_Univ by auto\n        moreover have \"\\<iota> ` D.cones a' \\<subseteq> S.Univ\"\n          using UP_mapsto by auto\n        ultimately show ?thesis using S.mkArr_in_hom by simp\n      qed\n      thus ?thesis using \\<Phi>o_def [of a'] by auto\n    qed\n\n    interpretation \\<Phi>: transformation_by_components\n                        Cop.comp SetCat.comp \\<open>Y a\\<close> Cones.map \\<Phi>o\n    proof\n      fix a'\n      assume A': \"Cop.ide a'\"\n      show \"\\<guillemotleft>\\<Phi>o a' : Y a a' \\<rightarrow>\\<^sub>S Cones.map a'\\<guillemotright>\"\n        using A' Ya_ide \\<Phi>o_in_hom Cones.map_ide by auto\n      next\n      fix g\n      assume g: \"Cop.arr g\"\n      show \"\\<Phi>o (Cop.cod g) \\<cdot>\\<^sub>S Y a g = Cones.map g \\<cdot>\\<^sub>S \\<Phi>o (Cop.dom g)\"\n      proof -\n        let ?A = \"Hom.set (C.cod g, a)\"\n        let ?B = \"Hom.set (C.dom g, a)\"\n        let ?B' = \"\\<iota> ` D.cones (C.cod g)\"\n        let ?C = \"\\<iota> ` D.cones (C.dom g)\"\n        let ?F = \"\\<phi> (C.dom g, a) o Cop.comp g o \\<psi> (C.cod g, a)\"\n        let ?F' = \"\\<iota> o D.cones_map g o \\<o>\"\n        let ?G = \"\\<lambda>x. \\<iota> (D.cones_map (\\<psi> (C.dom g, a) x) \\<chi>)\"\n        let ?G' = \"\\<lambda>x. \\<iota> (D.cones_map (\\<psi> (C.cod g, a) x) \\<chi>)\"\n        have \"S.arr (Y a g) \\<and> Y a g = S.mkArr ?A ?B ?F\"\n          using ide_apex g Ya.preserves_arr Ya_arr by fastforce\n        moreover have \"S.arr (\\<Phi>o (Cop.cod g))\"\n          using g \\<Phi>o_in_hom [of \"Cop.cod g\"] by auto\n        moreover have \"\\<Phi>o (Cop.cod g) = S.mkArr ?B ?C ?G\"\n          using g \\<Phi>o_def [of \"C.dom g\"] by auto\n        moreover have \"S.seq (\\<Phi>o (Cop.cod g)) (Y a g)\"\n          using ide_apex g \\<Phi>o_in_hom [of \"Cop.cod g\"] by auto\n        ultimately have 1: \"S.seq (\\<Phi>o (Cop.cod g)) (Y a g) \\<and>\n                            \\<Phi>o (Cop.cod g) \\<cdot>\\<^sub>S Y a g = S.mkArr ?A ?C (?G o ?F)\"\n          using S.comp_mkArr [of ?A ?B ?F ?C ?G] by argo\n\n        have \"Cones.map g = S.mkArr (\\<iota> ` D.cones (C.cod g)) (\\<iota> ` D.cones (C.dom g)) ?F'\"\n          using g Cones.map_simp by fastforce\n        moreover have \"\\<Phi>o (Cop.dom g) = S.mkArr ?A ?B' ?G'\"\n          using g \\<Phi>o_def by fastforce\n        moreover have \"S.seq (Cones.map g) (\\<Phi>o (Cop.dom g))\"\n          using g Cones.preserves_hom [of g \"C.cod g\" \"C.dom g\"] \\<Phi>o_in_hom [of \"Cop.dom g\"]\n          by force\n        ultimately have\n          2: \"S.seq (Cones.map g) (\\<Phi>o (Cop.dom g)) \\<and>\n              Cones.map g \\<cdot>\\<^sub>S \\<Phi>o (Cop.dom g) = S.mkArr ?A ?C (?F' o ?G')\"\n          using S.seqI' [of \"\\<Phi>o (Cop.dom g)\" \"Cones.map g\"] by force\n\n        have \"\\<Phi>o (Cop.cod g) \\<cdot>\\<^sub>S Y a g = S.mkArr ?A ?C (?G o ?F)\"\n          using 1 by auto\n        also have \"... = S.mkArr ?A ?C (?F' o ?G')\"\n        proof (intro S.mkArr_eqI')\n          show \"S.arr (S.mkArr ?A ?C (?G o ?F))\" using 1 by force\n          show \"\\<And>x. x \\<in> ?A \\<Longrightarrow> (?G o ?F) x = (?F' o ?G') x\"\n          proof -\n            fix x\n            assume x: \"x \\<in> ?A\"\n            hence 1: \"\\<guillemotleft>\\<psi> (C.cod g, a) x : C.cod g \\<rightarrow> a\\<guillemotright>\"\n              using ide_apex g Hom.\\<psi>_mapsto [of \"C.cod g\" a] by auto\n            have \"(?G o ?F) x = \\<iota> (D.cones_map (\\<psi> (C.dom g, a)\n                                  (\\<phi> (C.dom g, a) (\\<psi> (C.cod g, a) x \\<cdot> g))) \\<chi>)\"\n            proof - (* Why is it so balky with this proof? *)\n              have \"(?G o ?F) x = ?G (?F x)\" by simp\n              also have \"... = \\<iota> (D.cones_map (\\<psi> (C.dom g, a)\n                                     (\\<phi> (C.dom g, a) (\\<psi> (C.cod g, a) x \\<cdot> g))) \\<chi>)\"\n              proof -\n                have \"?F x = \\<phi> (C.dom g, a) (\\<psi> (C.cod g, a) x \\<cdot> g)\" by simp\n                thus ?thesis by presburger (* presburger 5ms, metis 797ms! Why? *)\n              qed\n              finally show ?thesis by auto\n            qed\n            also have \"... = \\<iota> (D.cones_map (\\<psi> (C.cod g, a) x \\<cdot> g) \\<chi>)\"\n            proof -\n              have \"\\<guillemotleft>\\<psi> (C.cod g, a) x \\<cdot> g : C.dom g \\<rightarrow> a\\<guillemotright>\" using g 1 by auto\n              thus ?thesis using Hom.\\<psi>_\\<phi> by presburger\n            qed\n            also have \"... = \\<iota> (D.cones_map g (D.cones_map (\\<psi> (C.cod g, a) x) \\<chi>))\"\n              using g x 1 cone_\\<chi> D.cones_map_comp [of \"\\<psi> (C.cod g, a) x\" g] by fastforce\n            also have \"... = \\<iota> (D.cones_map g (\\<o> (\\<iota> (D.cones_map (\\<psi> (C.cod g, a) x) \\<chi>))))\"\n              using 1 cone_\\<chi> D.cones_map_mapsto S.\\<o>_\\<iota> by simp\n            also have \"... = (?F' o ?G') x\" by simp\n            finally show \"(?G o ?F) x = (?F' o ?G') x\" by auto\n          qed\n        qed\n        also have \"... = Cones.map g \\<cdot>\\<^sub>S \\<Phi>o (Cop.dom g)\"\n          using 2 by auto\n       finally show ?thesis by auto\n      qed\n    qed\n\n    interpretation \\<Phi>: set_valued_transformation\n                        Cop.comp SetCat.comp \\<open>Y a\\<close> Cones.map \\<Phi>.map ..\n                                            \n    interpretation \\<Phi>: natural_isomorphism Cop.comp SetCat.comp \\<open>Y a\\<close> Cones.map \\<Phi>.map\n    proof\n      fix a'\n      assume a': \"Cop.ide a'\"\n      show \"S.iso (\\<Phi>.map a')\"\n      proof -\n        let ?F = \"\\<lambda>x. \\<iota> (D.cones_map (\\<psi> (a', a) x) \\<chi>)\"\n        have bij: \"bij_betw ?F (Hom.set (a', a)) (\\<iota> ` D.cones a')\"\n        proof -\n          have \"\\<And>x x'. \\<lbrakk> x \\<in> Hom.set (a', a); x' \\<in> Hom.set (a', a);\n                         \\<iota> (D.cones_map (\\<psi> (a', a) x) \\<chi>) = \\<iota> (D.cones_map (\\<psi> (a', a) x') \\<chi>) \\<rbrakk>\n                            \\<Longrightarrow> x = x'\"\n          proof -\n            fix x x'\n            assume x: \"x \\<in> Hom.set (a', a)\" and x': \"x' \\<in> Hom.set (a', a)\"\n            and xx': \"\\<iota> (D.cones_map (\\<psi> (a', a) x) \\<chi>) = \\<iota> (D.cones_map (\\<psi> (a', a) x') \\<chi>)\"\n            have \\<psi>x: \"\\<guillemotleft>\\<psi> (a', a) x : a' \\<rightarrow> a\\<guillemotright>\" using x ide_apex a' Hom.\\<psi>_mapsto by auto\n            have \\<psi>x': \"\\<guillemotleft>\\<psi> (a', a) x' : a' \\<rightarrow> a\\<guillemotright>\" using x' ide_apex a' Hom.\\<psi>_mapsto by auto\n            have 1: \"\\<exists>!f. \\<guillemotleft>f : a' \\<rightarrow> a\\<guillemotright> \\<and> \\<iota> (D.cones_map f \\<chi>) = \\<iota> (D.cones_map (\\<psi> (a', a) x) \\<chi>)\"\n            proof -\n              have \"D.cones_map (\\<psi> (a', a) x) \\<chi> \\<in> D.cones a'\"\n                using \\<psi>x a' cone_\\<chi> D.cones_map_mapsto by force\n              hence 2: \"\\<exists>!f. \\<guillemotleft>f : a' \\<rightarrow> a\\<guillemotright> \\<and> D.cones_map f \\<chi> = D.cones_map (\\<psi> (a', a) x) \\<chi>\"\n                using a' is_universal by simp\n              show \"\\<exists>!f. \\<guillemotleft>f : a' \\<rightarrow> a\\<guillemotright> \\<and> \\<iota> (D.cones_map f \\<chi>) = \\<iota> (D.cones_map (\\<psi> (a', a) x) \\<chi>)\"\n              proof -\n                have \"\\<And>f. \\<iota> (D.cones_map f \\<chi>) = \\<iota> (D.cones_map (\\<psi> (a', a) x) \\<chi>)\n                             \\<longleftrightarrow> D.cones_map f \\<chi> = D.cones_map (\\<psi> (a', a) x) \\<chi>\"\n                proof -\n                  fix f :: 'c\n                  have \"D.cones_map f \\<chi> = D.cones_map (\\<psi> (a', a) x) \\<chi>\n                           \\<longrightarrow> \\<iota> (D.cones_map f \\<chi>) = \\<iota> (D.cones_map (\\<psi> (a', a) x) \\<chi>)\"\n                    by simp\n                  thus \"(\\<iota> (D.cones_map f \\<chi>) = \\<iota> (D.cones_map (\\<psi> (a', a) x) \\<chi>))\n                            = (D.cones_map f \\<chi> = D.cones_map (\\<psi> (a', a) x) \\<chi>)\"\n                    by (meson S.inj_\\<iota> injD)\n                qed\n                thus ?thesis using 2 by auto\n              qed\n            qed\n            have 2: \"\\<exists>!x''. x'' \\<in> Hom.set (a', a) \\<and>\n                            \\<iota> (D.cones_map (\\<psi> (a', a) x'') \\<chi>) = \\<iota> (D.cones_map (\\<psi> (a', a) x) \\<chi>)\"\n            proof -\n              from 1 obtain f'' where\n                  f'': \"\\<guillemotleft>f'' : a' \\<rightarrow> a\\<guillemotright> \\<and> \\<iota> (D.cones_map f'' \\<chi>) = \\<iota> (D.cones_map (\\<psi> (a', a) x) \\<chi>)\"\n                by blast\n              have \"\\<phi> (a', a) f'' \\<in> Hom.set (a', a) \\<and>\n                    \\<iota> (D.cones_map (\\<psi> (a', a) (\\<phi> (a', a) f'')) \\<chi>) = \\<iota> (D.cones_map (\\<psi> (a', a) x) \\<chi>)\"\n              proof\n                show \"\\<phi> (a', a) f'' \\<in> Hom.set (a', a)\" using f'' Hom.set_def by auto\n                show \"\\<iota> (D.cones_map (\\<psi> (a', a) (\\<phi> (a', a) f'')) \\<chi>) =\n                         \\<iota> (D.cones_map (\\<psi> (a', a) x) \\<chi>)\"\n                  using f'' Hom.\\<psi>_\\<phi> by presburger\n              qed\n              moreover have\n                 \"\\<And>x''. x'' \\<in> Hom.set (a', a) \\<and>\n                         \\<iota> (D.cones_map (\\<psi> (a', a) x'') \\<chi>) = \\<iota> (D.cones_map (\\<psi> (a', a) x) \\<chi>)\n                             \\<Longrightarrow> x'' = \\<phi> (a', a) f''\"\n              proof -\n                fix x''\n                assume x'': \"x'' \\<in> Hom.set (a', a) \\<and>\n                             \\<iota> (D.cones_map (\\<psi> (a', a) x'') \\<chi>) = \\<iota> (D.cones_map (\\<psi> (a', a) x) \\<chi>)\"\n                hence \"\\<guillemotleft>\\<psi> (a', a) x'' : a' \\<rightarrow> a\\<guillemotright> \\<and>\n                       \\<iota> (D.cones_map (\\<psi> (a', a) x'') \\<chi>) = \\<iota> (D.cones_map (\\<psi> (a', a) x) \\<chi>)\"\n                  using ide_apex a' Hom.set_def Hom.\\<psi>_mapsto [of a' a] by auto\n                hence \"\\<phi> (a', a) (\\<psi> (a', a) x'') = \\<phi> (a', a) f''\"\n                  using 1 f'' by auto\n                thus \"x'' = \\<phi> (a', a) f''\"\n                  using ide_apex a' x'' Hom.\\<phi>_\\<psi> by simp\n              qed\n              ultimately show ?thesis\n                using ex1I [of \"\\<lambda>x'. x' \\<in> Hom.set (a', a) \\<and>\n                                     \\<iota> (D.cones_map (\\<psi> (a', a) x') \\<chi>) =\n                                        \\<iota> (D.cones_map (\\<psi> (a', a) x) \\<chi>)\"\n                               \"\\<phi> (a', a) f''\"]\n                by simp\n            qed\n            thus \"x = x'\" using x x' xx' by auto\n          qed\n          hence \"inj_on ?F (Hom.set (a', a))\"\n            using inj_onI [of \"Hom.set (a', a)\" ?F] by auto \n          moreover have \"?F ` Hom.set (a', a) = \\<iota> ` D.cones a'\"\n          proof\n            show \"?F ` Hom.set (a', a) \\<subseteq> \\<iota> ` D.cones a'\"\n            proof\n              fix X'\n              assume X': \"X' \\<in> ?F ` Hom.set (a', a)\"\n              from this obtain x' where x': \"x' \\<in> Hom.set (a', a) \\<and> ?F x' = X'\" by blast\n              show \"X' \\<in> \\<iota> ` D.cones a'\"\n              proof -\n                have \"X' = \\<iota> (D.cones_map (\\<psi> (a', a) x') \\<chi>)\" using x' by blast\n                hence \"X' = \\<iota> (D.cones_map (\\<psi> (a', a) x') \\<chi>)\" using x' by force\n                moreover have \"\\<guillemotleft>\\<psi> (a', a) x' : a' \\<rightarrow> a\\<guillemotright>\"\n                  using ide_apex a' x' Hom.set_def Hom.\\<psi>_\\<phi> by auto\n                ultimately show ?thesis\n                  using x' cone_\\<chi> D.cones_map_mapsto by force\n              qed\n            qed\n            show \"\\<iota> ` D.cones a' \\<subseteq> ?F ` Hom.set (a', a)\"\n            proof\n              fix X'\n              assume X': \"X' \\<in> \\<iota> ` D.cones a'\"\n              hence \"\\<o> X' \\<in> \\<o> ` \\<iota> ` D.cones a'\" by simp\n              with S.\\<o>_\\<iota> have \"\\<o> X' \\<in> D.cones a'\"\n                by auto\n              hence \"\\<exists>!f. \\<guillemotleft>f : a' \\<rightarrow> a\\<guillemotright> \\<and> D.cones_map f \\<chi> = \\<o> X'\"\n                using a' is_universal by simp\n              from this obtain f where \"\\<guillemotleft>f : a' \\<rightarrow> a\\<guillemotright> \\<and> D.cones_map f \\<chi> = \\<o> X'\"\n                by auto\n              hence f: \"\\<guillemotleft>f : a' \\<rightarrow> a\\<guillemotright> \\<and> \\<iota> (D.cones_map f \\<chi>) = X'\"\n                using X' S.\\<iota>_\\<o> by auto\n              have \"X' = ?F (\\<phi> (a', a) f)\"\n                using f Hom.\\<psi>_\\<phi> by presburger\n              thus \"X' \\<in> ?F ` Hom.set (a', a)\"\n                using f Hom.set_def by force\n            qed\n          qed\n          ultimately show ?thesis\n            using bij_betw_def [of ?F \"Hom.set (a', a)\" \"\\<iota> ` D.cones a'\"] inj_on_def by auto\n        qed\n        let ?f = \"S.mkArr (Hom.set (a', a)) (\\<iota> ` D.cones a') ?F\"\n        have iso: \"S.iso ?f\"\n        proof -\n          have \"?F \\<in> Hom.set (a', a) \\<rightarrow> \\<iota> ` D.cones a'\"\n            using bij bij_betw_imp_funcset by fast\n          hence \"S.arr ?f\"\n            using ide_apex a' Hom.set_subset_Univ S.\\<iota>_mapsto S.arr_mkArr by auto\n          thus ?thesis using bij S.iso_char by fastforce\n        qed\n        moreover have \"?f = \\<Phi>.map a'\"\n          using a' \\<Phi>o_def by force\n        finally show ?thesis by auto\n      qed\n    qed\n\n    interpretation R: representation_of_functor\n                         C \\<open>SetCat.comp :: ('c + ('j \\<Rightarrow> 'c)) setcat.arr comp\\<close>\n                         \\<phi> Cones.map a \\<Phi>.map ..\n\n    lemma \\<chi>_in_terms_of_\\<Phi>:\n    shows \"\\<chi> = \\<o> (\\<Phi>.FUN a (\\<phi> (a, a) a))\"\n    proof -\n      have \"\\<Phi>.FUN a (\\<phi> (a, a) a) = \n              (\\<lambda>x \\<in> Hom.set (a, a). \\<iota> (D.cones_map (\\<psi> (a, a) x) \\<chi>)) (\\<phi> (a, a) a)\"\n        using ide_apex S.Fun_mkArr \\<Phi>.map_simp_ide \\<Phi>o_def \\<Phi>.preserves_reflects_arr [of a]\n        by simp\n      also have \"... = \\<iota> (D.cones_map a \\<chi>)\"\n      proof -\n        have \"\\<phi> (a, a) a \\<in> Hom.set (a, a)\"\n          using ide_apex Hom.\\<phi>_mapsto by fastforce\n        hence \"(\\<lambda>x \\<in> Hom.set (a, a). \\<iota> (D.cones_map (\\<psi> (a, a) x) \\<chi>)) (\\<phi> (a, a) a)\n                  = \\<iota> (D.cones_map (\\<psi> (a, a) (\\<phi> (a, a) a)) \\<chi>)\"\n          using restrict_apply' [of \"\\<phi> (a, a) a\" \"Hom.set (a, a)\"] by blast\n        also have \"... = \\<iota> (D.cones_map a \\<chi>)\"\n        proof -\n          have \"\\<psi> (a, a) (\\<phi> (a, a) a) = a\"\n            using ide_apex Hom.\\<psi>_\\<phi> [of a a a] by fastforce\n          thus ?thesis by metis\n        qed\n        finally show ?thesis by auto\n      qed\n      finally have \"\\<Phi>.FUN a (\\<phi> (a, a) a) = \\<iota> (D.cones_map a \\<chi>)\" by auto\n      also have \"... = \\<iota> \\<chi>\"\n        using ide_apex D.cones_map_ide [of \\<chi> a] cone_\\<chi> by simp\n      finally have \"\\<Phi>.FUN a (\\<phi> (a, a) a) = \\<iota> \\<chi>\" by blast\n      hence \"\\<o> (\\<Phi>.FUN a (\\<phi> (a, a) a)) = \\<o> (\\<iota> \\<chi>)\" by simp\n      thus ?thesis using cone_\\<chi> S.\\<o>_\\<iota> by simp\n    qed\n\n    abbreviation Hom\n    where \"Hom \\<equiv> Hom.map\"\n\n    abbreviation \\<Phi>\n    where \"\\<Phi> \\<equiv> \\<Phi>.map\"\n\n    lemma induces_limit_situation:\n    shows \"limit_situation J C D (SetCat.comp :: ('c + ('j \\<Rightarrow> 'c)) setcat.arr comp) \\<phi> \\<iota> a \\<Phi> \\<chi>\"\n    proof\n      show \"\\<chi> = \\<o> (\\<Phi>.FUN a (\\<phi> (a, a) a))\" using \\<chi>_in_terms_of_\\<Phi> by auto\n      fix a'\n      show \"Cop.ide a' \\<Longrightarrow> \\<Phi>.map a' = S.mkArr (Hom.set (a', a)) (\\<iota> ` D.cones a')\n                                              (\\<lambda>x. \\<iota> (D.cones_map (\\<psi> (a', a) x) \\<chi>))\"\n        using \\<Phi>.map_simp_ide \\<Phi>o_def [of a'] by force\n    qed\n\n    no_notation SetCat.comp      (infixr \"\\<cdot>\\<^sub>S\" 55)\n\n  end\n\n  sublocale limit_cone \\<subseteq> limit_situation J C D \"SetCat.comp :: ('c + ('j \\<Rightarrow> 'c)) setcat.arr comp\"\n                                         \\<phi> \\<iota> a \\<Phi> \\<chi>\n    using induces_limit_situation by auto\n\n  subsection \"Representations of the Cones Functor Induce Limit Situations\"\n\n  context representation_of_cones_functor\n  begin\n\n    interpretation \\<Phi>: set_valued_transformation Cop.comp S \\<open>Y a\\<close> Cones.map \\<Phi> ..\n    interpretation \\<Psi>: inverse_transformation Cop.comp S \\<open>Y a\\<close> Cones.map \\<Phi> ..\n    interpretation \\<Psi>: set_valued_transformation Cop.comp S Cones.map \\<open>Y a\\<close> \\<Psi>.map ..\n\n    abbreviation \\<o>\n    where \"\\<o> \\<equiv> Cones.\\<o>\"\n\n    abbreviation \\<chi>\n    where \"\\<chi> \\<equiv> \\<o> (S.Fun (\\<Phi> a) (\\<phi> (a, a) a))\"\n\n    lemma Cones_SET_eq_\\<iota>_img_cones:\n    assumes \"C.ide a'\"\n    shows \"Cones.SET a' = \\<iota> ` D.cones a'\"\n    proof -\n      have \"\\<iota> ` D.cones a' \\<subseteq> S.Univ\" using S.\\<iota>_mapsto by auto\n      thus ?thesis using assms Cones.map_ide by auto\n    qed\n\n    lemma \\<iota>\\<chi>:\n    shows \"\\<iota> \\<chi> = S.Fun (\\<Phi> a) (\\<phi> (a, a) a)\"\n    proof -\n      have \"S.Fun (\\<Phi> a) (\\<phi> (a, a) a) \\<in> Cones.SET a\"\n        using Ya.ide_a Hom.\\<phi>_mapsto S.Fun_mapsto [of \"\\<Phi> a\"] Hom.set_map by fastforce\n      thus ?thesis\n        using Ya.ide_a Cones_SET_eq_\\<iota>_img_cones by auto\n    qed\n\n    interpretation \\<chi>: cone J C D a \\<chi>\n    proof -\n      have \"\\<iota> \\<chi> \\<in> \\<iota> ` D.cones a\"\n        using Ya.ide_a \\<iota>\\<chi> S.Fun_mapsto [of \"\\<Phi> a\"] Hom.\\<phi>_mapsto Hom.set_map\n              Cones_SET_eq_\\<iota>_img_cones by fastforce\n      thus \"D.cone a \\<chi>\"\n        by (metis S.\\<o>_\\<iota> UNIV_I imageE mem_Collect_eq)\n    qed\n\n    lemma cone_\\<chi>:\n    shows \"D.cone a \\<chi>\" ..\n\n    lemma \\<Phi>_FUN_simp:\n    assumes a': \"C.ide a'\" and x: \"x \\<in> Hom.set (a', a)\"\n    shows \"\\<Phi>.FUN a' x = Cones.FUN (\\<psi> (a', a) x) (\\<iota> \\<chi>)\"\n    proof -\n      have \\<psi>x: \"\\<guillemotleft>\\<psi> (a', a) x : a' \\<rightarrow> a\\<guillemotright>\"\n        using Ya.ide_a a' x Hom.\\<psi>_mapsto by blast\n      have \\<phi>a: \"\\<phi> (a, a) a \\<in> Hom.set (a, a)\" using Ya.ide_a Hom.\\<phi>_mapsto by fastforce\n      have \"\\<Phi>.FUN a' x = (\\<Phi>.FUN a' o Ya.FUN (\\<psi> (a', a) x)) (\\<phi> (a, a) a)\"\n      proof -\n        have \"\\<phi> (a', a) (a \\<cdot> \\<psi> (a', a) x) = x\"\n          using Ya.ide_a a' x \\<psi>x Hom.\\<phi>_\\<psi> C.comp_cod_arr by fastforce\n        moreover have \"S.arr (S.mkArr (Hom.set (a, a)) (Hom.set (a', a))\n                             (\\<phi> (a', a) \\<circ> Cop.comp (\\<psi> (a', a) x) \\<circ> \\<psi> (a, a)))\"\n          using Ya.ide_a a' Hom.set_subset_Univ Hom.\\<psi>_mapsto [of a a] Hom.\\<phi>_mapsto \\<psi>x\n          by force\n        ultimately show ?thesis\n          using Ya.ide_a a' x Ya.Y_ide_arr \\<psi>x \\<phi>a C.ide_in_hom by auto\n      qed\n      also have \"... = (Cones.FUN (\\<psi> (a', a) x) o \\<Phi>.FUN a) (\\<phi> (a, a) a)\"\n      proof -\n        have \"(\\<Phi>.FUN a' o Ya.FUN (\\<psi> (a', a) x)) (\\<phi> (a, a) a)\n                = S.Fun (\\<Phi> a' \\<cdot>\\<^sub>S Y a (\\<psi> (a', a) x)) (\\<phi> (a, a) a)\"\n          using \\<psi>x a' \\<phi>a Ya.ide_a Ya.map_simp Hom.set_map by (elim C.in_homE, auto)\n        also have \"... = S.Fun (S (Cones.map (\\<psi> (a', a) x)) (\\<Phi> a)) (\\<phi> (a, a) a)\"\n          using \\<psi>x is_natural_1 [of \"\\<psi> (a', a) x\"] is_natural_2 [of \"\\<psi> (a', a) x\"] by auto\n        also have \"... = (Cones.FUN (\\<psi> (a', a) x) o \\<Phi>.FUN a) (\\<phi> (a, a) a)\"\n        proof -\n          have \"S.seq (Cones.map (\\<psi> (a', a) x)) (\\<Phi> a)\"\n            using Ya.ide_a \\<psi>x Cones.map_preserves_dom [of \"\\<psi> (a', a) x\"]\n            apply (intro S.seqI)\n              apply auto[2]\n            by fastforce\n          thus ?thesis\n            using Ya.ide_a \\<phi>a Hom.set_map by auto\n        qed\n        finally show ?thesis by simp\n      qed\n      also have \"... = Cones.FUN (\\<psi> (a', a) x) (\\<iota> \\<chi>)\" using \\<iota>\\<chi> by simp\n      finally show ?thesis by auto\n    qed\n\n    lemma \\<chi>_is_universal:\n    assumes \"D.cone a' \\<chi>'\"\n    shows \"\\<guillemotleft>\\<psi> (a', a) (\\<Psi>.FUN a' (\\<iota> \\<chi>')) : a' \\<rightarrow> a\\<guillemotright>\"\n    and \"D.cones_map (\\<psi> (a', a) (\\<Psi>.FUN a' (\\<iota> \\<chi>'))) \\<chi> = \\<chi>'\"\n    and \"\\<lbrakk> \\<guillemotleft>f' : a' \\<rightarrow> a\\<guillemotright>; D.cones_map f' \\<chi> = \\<chi>' \\<rbrakk> \\<Longrightarrow> f' = \\<psi> (a', a) (\\<Psi>.FUN a' (\\<iota> \\<chi>'))\"\n    proof -\n      interpret \\<chi>': cone J C D a' \\<chi>' using assms by auto\n      have a': \"C.ide a'\" using \\<chi>'.ide_apex by simp\n      have \\<iota>\\<chi>': \"\\<iota> \\<chi>' \\<in> Cones.SET a'\" using assms a' Cones_SET_eq_\\<iota>_img_cones by auto\n      let ?f = \"\\<psi> (a', a) (\\<Psi>.FUN a' (\\<iota> \\<chi>'))\"\n      have A: \"\\<Psi>.FUN a' (\\<iota> \\<chi>') \\<in> Hom.set (a', a)\"\n      proof -\n        have \"\\<Psi>.FUN a' \\<in> Cones.SET a' \\<rightarrow> Ya.SET a'\"\n          using a' \\<Psi>.preserves_hom [of a' a' a'] S.Fun_mapsto [of \"\\<Psi>.map a'\"] by fastforce\n        thus ?thesis using a' \\<iota>\\<chi>' Ya.ide_a Hom.set_map by auto\n      qed\n      show f: \"\\<guillemotleft>?f : a' \\<rightarrow> a\\<guillemotright>\" using A a' Ya.ide_a Hom.\\<psi>_mapsto [of a' a] by auto\n      have E: \"\\<And>f. \\<guillemotleft>f : a' \\<rightarrow> a\\<guillemotright> \\<Longrightarrow> Cones.FUN f (\\<iota> \\<chi>) = \\<Phi>.FUN a' (\\<phi> (a', a) f)\"\n      proof -\n        fix f\n        assume f: \"\\<guillemotleft>f : a' \\<rightarrow> a\\<guillemotright>\"\n        have \"\\<phi> (a', a) f \\<in> Hom.set (a', a)\"\n          using a' Ya.ide_a f Hom.\\<phi>_mapsto by auto\n        thus \"Cones.FUN f (\\<iota> \\<chi>) = \\<Phi>.FUN a' (\\<phi> (a', a) f)\"\n          using a' f \\<Phi>_FUN_simp by simp\n      qed\n      have I: \"\\<Phi>.FUN a' (\\<Psi>.FUN a' (\\<iota> \\<chi>')) = \\<iota> \\<chi>'\"\n      proof -\n        have \"\\<Phi>.FUN a' (\\<Psi>.FUN a' (\\<iota> \\<chi>')) =\n              compose (\\<Psi>.DOM a') (\\<Phi>.FUN a') (\\<Psi>.FUN a') (\\<iota> \\<chi>')\"\n          using a' \\<iota>\\<chi>' Cones.map_ide \\<Psi>.preserves_hom [of a' a' a'] by force\n        also have \"... = (\\<lambda>x \\<in> \\<Psi>.DOM a'. x) (\\<iota> \\<chi>')\"\n          using a' \\<Psi>.inverts_components S.inverse_arrows_char by force\n        also have \"... = \\<iota> \\<chi>'\"\n          using a' \\<iota>\\<chi>' Cones.map_ide \\<Psi>.preserves_hom [of a' a' a'] by force\n        finally show ?thesis by auto\n      qed\n      show f\\<chi>: \"D.cones_map ?f \\<chi> = \\<chi>'\"\n      proof -\n        have \"D.cones_map ?f \\<chi> = (\\<o> o Cones.FUN ?f o \\<iota>) \\<chi>\"\n          using f Cones.preserves_arr [of ?f] cone_\\<chi>\n          by (cases \"D.cone a \\<chi>\", auto)\n        also have \"... = \\<chi>'\"\n           using f Ya.ide_a a' A E I by auto\n        finally show ?thesis by auto\n      qed\n      show \"\\<lbrakk> \\<guillemotleft>f' : a' \\<rightarrow> a\\<guillemotright>; D.cones_map f' \\<chi> = \\<chi>' \\<rbrakk> \\<Longrightarrow> f' = ?f\"\n      proof -\n        assume f': \"\\<guillemotleft>f' : a' \\<rightarrow> a\\<guillemotright>\" and f'\\<chi>: \"D.cones_map f' \\<chi> = \\<chi>'\"\n        show \"f' = ?f\"\n        proof -\n          have 1: \"\\<phi> (a', a) f' \\<in> Hom.set (a', a) \\<and> \\<phi> (a', a) ?f \\<in> Hom.set (a', a)\"\n            using Ya.ide_a a' f f' Hom.\\<phi>_mapsto by auto\n          have \"S.iso (\\<Phi> a')\" using \\<chi>'.ide_apex components_are_iso by auto\n          hence 2: \"S.arr (\\<Phi> a') \\<and> bij_betw (\\<Phi>.FUN a') (Hom.set (a', a)) (Cones.SET a')\"\n            using Ya.ide_a a' S.iso_char Hom.set_map by auto\n          have \"\\<Phi>.FUN a' (\\<phi> (a', a) f') = \\<Phi>.FUN a' (\\<phi> (a', a) ?f)\"\n          proof -\n            have \"\\<Phi>.FUN a' (\\<phi> (a', a) ?f) = \\<iota> \\<chi>'\"\n              using A I Hom.\\<phi>_\\<psi> Ya.ide_a a' by simp\n            also have \"... = Cones.FUN f' (\\<iota> \\<chi>)\"\n              using f f' A E cone_\\<chi> Cones.preserves_arr f\\<chi> f'\\<chi> by (elim C.in_homE, auto)\n            also have \"... = \\<Phi>.FUN a' (\\<phi> (a', a) f')\"\n              using f' E by simp\n            finally show ?thesis by argo\n          qed\n          moreover have \"inj_on (\\<Phi>.FUN a') (Hom.set (a', a))\"\n            using 2 bij_betw_imp_inj_on by blast\n          ultimately have 3: \"\\<phi> (a', a) f' = \\<phi> (a', a) ?f\"\n            using 1 inj_on_def [of \"\\<Phi>.FUN a'\" \"Hom.set (a', a)\"] by blast\n          show ?thesis\n          proof -\n            have \"f' = \\<psi> (a', a) (\\<phi> (a', a) f')\"\n              using Ya.ide_a a' f' Hom.\\<psi>_\\<phi> by simp\n            also have \"... = \\<psi> (a', a) (\\<Psi>.FUN a' (\\<iota> \\<chi>'))\"\n              using Ya.ide_a a' Hom.\\<psi>_\\<phi> A 3 by simp\n            finally show ?thesis by blast\n          qed\n        qed\n      qed\n    qed\n\n    interpretation \\<chi>: limit_cone J C D a \\<chi>\n    proof\n      show \"\\<And>a' \\<chi>'. D.cone a' \\<chi>' \\<Longrightarrow> \\<exists>!f. \\<guillemotleft>f : a' \\<rightarrow> a\\<guillemotright> \\<and> D.cones_map f \\<chi> = \\<chi>'\"\n      proof -\n        fix a' \\<chi>'\n        assume 1: \"D.cone a' \\<chi>'\"\n        show \"\\<exists>!f. \\<guillemotleft>f : a' \\<rightarrow> a\\<guillemotright> \\<and> D.cones_map f \\<chi> = \\<chi>'\"\n        proof\n          show \"\\<guillemotleft>\\<psi> (a', a) (\\<Psi>.FUN a' (\\<iota> \\<chi>')) : a' \\<rightarrow> a\\<guillemotright> \\<and>\n                D.cones_map (\\<psi> (a', a) (\\<Psi>.FUN a' (\\<iota> \\<chi>'))) \\<chi> = \\<chi>'\"\n            using 1 \\<chi>_is_universal by blast\n          show \"\\<And>f. \\<guillemotleft>f : a' \\<rightarrow> a\\<guillemotright> \\<and> D.cones_map f \\<chi> = \\<chi>' \\<Longrightarrow> f = \\<psi> (a', a) (\\<Psi>.FUN a' (\\<iota> \\<chi>'))\"\n            using 1 \\<chi>_is_universal by blast\n        qed\n      qed\n    qed\n\n    lemma \\<chi>_is_limit_cone:\n    shows \"D.limit_cone a \\<chi>\" ..\n\n    lemma induces_limit_situation:\n    shows \"limit_situation J C D S \\<phi> \\<iota> a \\<Phi> \\<chi>\"\n    proof\n      show \"\\<chi> = \\<chi>\" by simp\n      fix a'\n      assume a': \"Cop.ide a'\"\n      let ?F = \"\\<lambda>x. \\<iota> (D.cones_map (\\<psi> (a', a) x) \\<chi>)\"\n      show \"\\<Phi> a' = S.mkArr (Hom.set (a', a)) (\\<iota> ` D.cones a') ?F\"\n      proof -\n        have 1: \"\\<guillemotleft>\\<Phi> a' : S.mkIde (Hom.set (a', a)) \\<rightarrow>\\<^sub>S S.mkIde (\\<iota> ` D.cones a')\\<guillemotright>\"\n          using a' Cones.map_ide Ya.ide_a by auto\n        moreover have \"\\<Phi>.DOM a' = Hom.set (a', a)\"\n          using 1 Hom.set_subset_Univ a' Ya.ide_a by (elim S.in_homE, auto)\n        moreover have \"\\<Phi>.COD a' = \\<iota> ` D.cones a'\"\n          using a' Cones_SET_eq_\\<iota>_img_cones by fastforce\n        ultimately have 2: \"\\<Phi> a' = S.mkArr (Hom.set (a', a)) (\\<iota> ` D.cones a') (\\<Phi>.FUN a')\"\n          using S.mkArr_Fun [of \"\\<Phi> a'\"] by fastforce\n        also have \"... = S.mkArr (Hom.set (a', a)) (\\<iota> ` D.cones a') ?F\"\n        proof\n          show \"S.arr (S.mkArr (Hom.set (a', a)) (\\<iota> ` D.cones a') (\\<Phi>.FUN a'))\"\n            using 1 2 by auto\n          show \"\\<And>x. x \\<in> Hom.set (a', a) \\<Longrightarrow> \\<Phi>.FUN a' x = ?F x\"\n          proof -\n            fix x\n            assume x: \"x \\<in> Hom.set (a', a)\"\n            hence \\<psi>x: \"\\<guillemotleft>\\<psi> (a', a) x : a' \\<rightarrow> a\\<guillemotright>\"\n              using a' Ya.ide_a Hom.\\<psi>_mapsto by auto\n            show \"\\<Phi>.FUN a' x = ?F x\"\n            proof -\n              have \"\\<Phi>.FUN a' x = Cones.FUN (\\<psi> (a', a) x) (\\<iota> \\<chi>)\"\n                using a' x \\<Phi>_FUN_simp by simp\n              also have \"... = restrict (\\<iota> o D.cones_map (\\<psi> (a', a) x) o \\<o>) (\\<iota> ` D.cones a) (\\<iota> \\<chi>)\"\n                using \\<psi>x Cones.map_simp Cones.preserves_arr [of \"\\<psi> (a', a) x\"] S.Fun_mkArr\n                by (elim C.in_homE, auto)\n              also have \"... = ?F x\" using cone_\\<chi> by simp\n              ultimately show ?thesis by simp\n            qed\n          qed\n        qed\n        finally show \"\\<Phi> a' = S.mkArr (Hom.set (a', a)) (\\<iota> ` D.cones a') ?F\" by auto\n      qed\n    qed\n\n  end\n\n  sublocale representation_of_cones_functor \\<subseteq> limit_situation J C D S \\<phi> \\<iota> a \\<Phi> \\<chi>\n    using induces_limit_situation by auto\n\n  section \"Categories with Limits\"\n\n  context category\n  begin\n\n    text\\<open>\n      A category @{term[source=true] C} has limits of shape @{term J} if every diagram of shape\n      @{term J} admits a limit cone.\n\\<close>\n\n    definition has_limits_of_shape\n    where \"has_limits_of_shape J \\<equiv> \\<forall>D. diagram J C D \\<longrightarrow> (\\<exists>a \\<chi>. limit_cone J C D a \\<chi>)\"\n\n    text\\<open>\n      A category has limits at a type @{typ 'j} if it has limits of shape @{term J}\n      for every category @{term J} whose arrows are of type @{typ 'j}.\n\\<close>\n\n    definition has_limits\n    where \"has_limits (_ :: 'j) \\<equiv> \\<forall>J :: 'j comp. category J \\<longrightarrow> has_limits_of_shape J\"\n\n    lemma has_limits_preserved_by_isomorphism:\n    assumes \"has_limits_of_shape J\" and \"isomorphic_categories J J'\"\n    shows \"has_limits_of_shape J'\"\n    proof -\n      interpret J: category J\n        using assms(2) isomorphic_categories_def isomorphic_categories_axioms_def by auto\n      interpret J': category J'\n        using assms(2) isomorphic_categories_def isomorphic_categories_axioms_def by auto\n      from assms(2) obtain \\<phi> \\<psi> where IF: \"inverse_functors J J' \\<phi> \\<psi>\"\n        using isomorphic_categories_def isomorphic_categories_axioms_def by blast\n      interpret IF: inverse_functors J J' \\<phi> \\<psi> using IF by auto\n      have \\<psi>\\<phi>: \"\\<psi> o \\<phi> = J.map\" using IF.inv by metis\n      have \\<phi>\\<psi>: \"\\<phi> o \\<psi> = J'.map\" using IF.inv' by metis\n      have \"\\<And>D'. diagram J' C D' \\<Longrightarrow> \\<exists>a \\<chi>. limit_cone J' C D' a \\<chi>\"\n      proof -\n        fix D'\n        assume D': \"diagram J' C D'\"\n        interpret D': diagram J' C D' using D' by auto\n        interpret D: composite_functor J J' C \\<phi> D' ..\n        interpret D: diagram J C \\<open>D' o \\<phi>\\<close> ..\n        have D: \"diagram J C (D' o \\<phi>)\" ..\n        from assms(1) obtain a \\<chi> where \\<chi>: \"D.limit_cone a \\<chi>\"\n          using D has_limits_of_shape_def by blast\n        interpret \\<chi>: limit_cone J C \\<open>D' o \\<phi>\\<close> a \\<chi> using \\<chi> by auto\n        interpret A': constant_functor J' C a\n          using \\<chi>.ide_apex by (unfold_locales, auto)\n        have \\<chi>o\\<psi>: \"cone J' C (D' o \\<phi> o \\<psi>) a (\\<chi> o \\<psi>)\"\n          using comp_cone_functor IF.G.functor_axioms \\<chi>.cone_axioms by fastforce\n        hence \\<chi>o\\<psi>: \"cone J' C D' a (\\<chi> o \\<psi>)\"\n          using \\<phi>\\<psi> by (metis D'.functor_axioms Fun.comp_assoc comp_functor_identity)\n        interpret \\<chi>o\\<psi>: cone J' C D' a \\<open>\\<chi> o \\<psi>\\<close> using \\<chi>o\\<psi> by auto\n        interpret \\<chi>o\\<psi>: limit_cone J' C D' a \\<open>\\<chi> o \\<psi>\\<close>\n        proof\n          fix a' \\<chi>'\n          assume \\<chi>': \"D'.cone a' \\<chi>'\"\n          interpret \\<chi>': cone J' C D' a' \\<chi>' using \\<chi>' by auto\n          have \\<chi>'o\\<phi>: \"cone J C (D' o \\<phi>) a' (\\<chi>' o \\<phi>)\"\n            using \\<chi>' comp_cone_functor IF.F.functor_axioms by fastforce\n          interpret \\<chi>'o\\<phi>: cone J C \\<open>D' o \\<phi>\\<close> a' \\<open>\\<chi>' o \\<phi>\\<close> using \\<chi>'o\\<phi> by auto\n          have \"cone J C (D' o \\<phi>) a' (\\<chi>' o \\<phi>)\" ..\n          hence 1: \"\\<exists>!f. \\<guillemotleft>f : a' \\<rightarrow> a\\<guillemotright> \\<and> D.cones_map f \\<chi> = \\<chi>' o \\<phi>\"\n            using \\<chi>.is_universal by simp\n          show \"\\<exists>!f. \\<guillemotleft>f : a' \\<rightarrow> a\\<guillemotright> \\<and> D'.cones_map f (\\<chi> o \\<psi>) = \\<chi>'\"\n          proof\n            let ?f = \"THE f. \\<guillemotleft>f : a' \\<rightarrow> a\\<guillemotright> \\<and> D.cones_map f \\<chi> = \\<chi>' o \\<phi>\"\n            have f: \"\\<guillemotleft>?f : a' \\<rightarrow> a\\<guillemotright> \\<and> D.cones_map ?f \\<chi> = \\<chi>' o \\<phi>\"\n              using 1 theI' [of \"\\<lambda>f. \\<guillemotleft>f : a' \\<rightarrow> a\\<guillemotright> \\<and> D.cones_map f \\<chi> = \\<chi>' o \\<phi>\"] by blast\n            have f_in_hom: \"\\<guillemotleft>?f : a' \\<rightarrow> a\\<guillemotright>\" using f by blast\n            have \"D'.cones_map ?f (\\<chi> o \\<psi>) = \\<chi>'\"\n            proof\n              fix j'\n              have \"\\<not>J'.arr j' \\<Longrightarrow> D'.cones_map ?f (\\<chi> o \\<psi>) j' = \\<chi>' j'\"\n              proof -\n                assume j': \"\\<not>J'.arr j'\"\n                have \"D'.cones_map ?f (\\<chi> o \\<psi>) j' = null\"\n                  using j' f_in_hom \\<chi>o\\<psi> by fastforce\n                thus ?thesis\n                  using j' \\<chi>'.is_extensional by simp\n              qed\n              moreover have \"J'.arr j' \\<Longrightarrow> D'.cones_map ?f (\\<chi> o \\<psi>) j' = \\<chi>' j'\"\n              proof -\n                assume j': \"J'.arr j'\"\n                have \"D'.cones_map ?f (\\<chi> o \\<psi>) j' = \\<chi> (\\<psi> j') \\<cdot> ?f\"\n                  using j' f \\<chi>o\\<psi> by fastforce\n                also have \"... = D.cones_map ?f \\<chi> (\\<psi> j')\"\n                  using j' f_in_hom \\<chi> \\<chi>.cone_\\<chi> by fastforce\n                also have \"... = \\<chi>' j'\"\n                  using j' f \\<chi> \\<phi>\\<psi> Fun.comp_def J'.map_simp by metis\n                finally show \"D'.cones_map ?f (\\<chi> o \\<psi>) j' = \\<chi>' j'\" by auto\n              qed\n              ultimately show \"D'.cones_map ?f (\\<chi> o \\<psi>) j' = \\<chi>' j'\" by blast\n            qed\n            thus \"\\<guillemotleft>?f : a' \\<rightarrow> a\\<guillemotright> \\<and> D'.cones_map ?f (\\<chi> o \\<psi>) = \\<chi>'\" using f by auto\n            fix f'\n            assume f': \"\\<guillemotleft>f' : a' \\<rightarrow> a\\<guillemotright> \\<and> D'.cones_map f' (\\<chi> o \\<psi>) = \\<chi>'\"\n            have \"D.cones_map f' \\<chi> = \\<chi>' o \\<phi>\"\n            proof\n              fix j\n              have \"\\<not>J.arr j \\<Longrightarrow> D.cones_map f' \\<chi> j = (\\<chi>' o \\<phi>) j\"\n                using f' \\<chi> \\<chi>'o\\<phi>.is_extensional \\<chi>.cone_\\<chi> mem_Collect_eq restrict_apply by auto\n              moreover have \"J.arr j \\<Longrightarrow> D.cones_map f' \\<chi> j = (\\<chi>' o \\<phi>) j\"\n              proof -\n                assume j: \"J.arr j\"\n                have \"D.cones_map f' \\<chi> j = C (\\<chi> j) f'\"\n                  using j f' \\<chi>.cone_\\<chi> by auto\n                also have \"... = C ((\\<chi> o \\<psi>) (\\<phi> j)) f'\"\n                  using j f' \\<psi>\\<phi> by (metis comp_apply J.map_simp)\n                also have \"... = D'.cones_map f' (\\<chi> o \\<psi>) (\\<phi> j)\"\n                  using j f' \\<chi>o\\<psi> by fastforce\n                also have \"... = (\\<chi>' o \\<phi>) j\"\n                  using j f' by auto\n                finally show \"D.cones_map f' \\<chi> j = (\\<chi>' o \\<phi>) j\" by auto\n              qed\n              ultimately show \"D.cones_map f' \\<chi> j = (\\<chi>' o \\<phi>) j\" by blast\n            qed\n            hence \"\\<guillemotleft>f' : a' \\<rightarrow> a\\<guillemotright> \\<and> D.cones_map f' \\<chi> = \\<chi>' o \\<phi>\"\n              using f' by auto\n            moreover have \"\\<And>P x x'. (\\<exists>!x. P x) \\<and> P x \\<and> P x' \\<Longrightarrow> x = x'\"\n              by auto\n            ultimately show \"f' = ?f\" using 1 f by blast\n          qed\n        qed\n        have \"limit_cone J' C D' a (\\<chi> o \\<psi>)\" ..\n        thus \"\\<exists>a \\<chi>. limit_cone J' C D' a \\<chi>\" by blast\n      qed\n      thus ?thesis using has_limits_of_shape_def by auto\n    qed\n\n  end\n\n  subsection \"Diagonal Functors\"\n\n  text\\<open>\n    The existence of limits can also be expressed in terms of adjunctions: a category @{term C}\n    has limits of shape @{term J} if the diagonal functor taking each object @{term a}\n    in @{term C} to the constant-@{term a} diagram and each arrow \\<open>f \\<in> C.hom a a'\\<close>\n    to the constant-@{term f} natural transformation between diagrams is a left adjoint functor.\n\\<close>\n\n  locale diagonal_functor =\n    C: category C +\n    J: category J +\n    J_C: functor_category J C\n  for J :: \"'j comp\"      (infixr \"\\<cdot>\\<^sub>J\" 55)\n  and C :: \"'c comp\"      (infixr \"\\<cdot>\" 55)\n  begin\n\n    notation J.in_hom     (\"\\<guillemotleft>_ : _ \\<rightarrow>\\<^sub>J _\\<guillemotright>\")\n    notation J_C.comp     (infixr \"\\<cdot>\\<^sub>[\\<^sub>J\\<^sub>,\\<^sub>C\\<^sub>]\" 55)\n    notation J_C.in_hom   (\"\\<guillemotleft>_ : _ \\<rightarrow>\\<^sub>[\\<^sub>J\\<^sub>,\\<^sub>C\\<^sub>] _\\<guillemotright>\")\n\n    definition map :: \"'c \\<Rightarrow> ('j, 'c) J_C.arr\"\n    where \"map f = (if C.arr f then J_C.MkArr (constant_functor.map J C (C.dom f))\n                                              (constant_functor.map J C (C.cod f))\n                                              (constant_transformation.map J C f)\n                               else J_C.null)\"\n\n    lemma is_functor:\n    shows \"functor C J_C.comp map\"\n    proof\n      fix f\n      show \"\\<not> C.arr f \\<Longrightarrow> local.map f = J_C.null\"\n        using map_def by simp\n      assume f: \"C.arr f\"\n      interpret Dom_f: constant_functor J C \\<open>C.dom f\\<close>\n        using f by (unfold_locales, auto)\n      interpret Cod_f: constant_functor J C \\<open>C.cod f\\<close>\n        using f by (unfold_locales, auto)\n      interpret Fun_f: constant_transformation J C f\n        using f by (unfold_locales, auto)\n      show 1: \"J_C.arr (map f)\"\n        using f map_def by (simp add: Fun_f.natural_transformation_axioms)\n      show \"J_C.dom (map f) = map (C.dom f)\"\n      proof -\n        have \"constant_transformation J C (C.dom f)\"\n          apply unfold_locales using f by auto\n        hence \"constant_transformation.map J C (C.dom f) = Dom_f.map\"\n          using Dom_f.map_def constant_transformation.map_def [of J C \"C.dom f\"] by auto\n        thus ?thesis using f 1 by (simp add: map_def J_C.dom_char)\n      qed\n      show \"J_C.cod (map f) = map (C.cod f)\"\n      proof -\n        have \"constant_transformation J C (C.cod f)\"\n          apply unfold_locales using f by auto\n        hence \"constant_transformation.map J C (C.cod f) = Cod_f.map\"\n          using Cod_f.map_def constant_transformation.map_def [of J C \"C.cod f\"] by auto\n        thus ?thesis using f 1 by (simp add: map_def J_C.cod_char)\n      qed\n      next\n      fix f g\n      assume g: \"C.seq g f\"\n      have f: \"C.arr f\" using g by auto\n      interpret Dom_f: constant_functor J C \\<open>C.dom f\\<close>\n        using f by (unfold_locales, auto)\n      interpret Cod_f: constant_functor J C \\<open>C.cod f\\<close>\n        using f by (unfold_locales, auto)\n      interpret Fun_f: constant_transformation J C f\n        using f by (unfold_locales, auto)\n      interpret Cod_g: constant_functor J C \\<open>C.cod g\\<close>\n        using g by (unfold_locales, auto)\n      interpret Fun_g: constant_transformation J C g\n        using g by (unfold_locales, auto)\n      interpret Fun_g: natural_transformation J C Cod_f.map Cod_g.map Fun_g.map\n        apply unfold_locales\n        using f g C.seqE [of g f] C.comp_arr_dom C.comp_cod_arr Fun_g.is_extensional by auto\n      interpret Fun_fg: vertical_composite\n                          J C Dom_f.map Cod_f.map Cod_g.map Fun_f.map Fun_g.map ..\n      have 1: \"J_C.arr (map f)\"\n        using f map_def by (simp add: Fun_f.natural_transformation_axioms)\n      show \"map (g \\<cdot> f) = map g \\<cdot>\\<^sub>[\\<^sub>J\\<^sub>,\\<^sub>C\\<^sub>] map f\"\n      proof -\n        have \"map (C g f) = J_C.MkArr Dom_f.map Cod_g.map\n                                      (constant_transformation.map J C (C g f))\"\n          using f g map_def by simp\n        also have \"... = J_C.MkArr Dom_f.map Cod_g.map (\\<lambda>j. if J.arr j then C g f else C.null)\"\n        proof -\n          have \"constant_transformation J C (g \\<cdot> f)\"\n            apply unfold_locales using g by auto\n          thus ?thesis using constant_transformation.map_def by metis\n        qed\n        also have \"... = J_C.comp (J_C.MkArr Cod_f.map Cod_g.map Fun_g.map)\n                                  (J_C.MkArr Dom_f.map Cod_f.map Fun_f.map)\"\n        proof -\n          have \"J_C.MkArr Cod_f.map Cod_g.map Fun_g.map \\<cdot>\\<^sub>[\\<^sub>J\\<^sub>,\\<^sub>C\\<^sub>]\n                J_C.MkArr Dom_f.map Cod_f.map Fun_f.map\n                  = J_C.MkArr Dom_f.map Cod_g.map Fun_fg.map\"\n            using J_C.comp_char J_C.comp_MkArr Fun_f.natural_transformation_axioms\n                  Fun_g.natural_transformation_axioms\n            by blast\n          also have \"... = J_C.MkArr Dom_f.map Cod_g.map\n                                     (\\<lambda>j. if J.arr j then g \\<cdot> f else C.null)\"\n          proof -\n            have \"Fun_fg.map = (\\<lambda>j. if J.arr j then g \\<cdot> f else C.null)\"\n              using 1 f g Fun_fg.map_def by auto\n            thus ?thesis by auto\n          qed\n          finally show ?thesis by auto\n        qed\n        also have \"... = map g \\<cdot>\\<^sub>[\\<^sub>J\\<^sub>,\\<^sub>C\\<^sub>] map f\"\n          using f g map_def by fastforce\n        finally show ?thesis by auto\n      qed\n    qed\n\n  end\n\n  sublocale diagonal_functor \\<subseteq> \"functor\" C J_C.comp map\n    using is_functor by auto\n\n  context diagonal_functor\n  begin\n\n    text\\<open>\n      The objects of @{term J_C} correspond bijectively to diagrams of shape @{term J}\n      in @{term C}.\n\\<close>\n\n    lemma ide_determines_diagram:\n    assumes \"J_C.ide d\"\n    shows \"diagram J C (J_C.Map d)\" and \"J_C.MkIde (J_C.Map d) = d\"\n    proof -\n      interpret \\<delta>: natural_transformation J C \\<open>J_C.Map d\\<close> \\<open>J_C.Map d\\<close> \\<open>J_C.Map d\\<close>\n        using assms J_C.ide_char J_C.arr_MkArr by fastforce\n      interpret D: \"functor\" J C \\<open>J_C.Map d\\<close> ..\n      show \"diagram J C (J_C.Map d)\" ..\n      show \"J_C.MkIde (J_C.Map d) = d\"\n        using assms J_C.ide_char by (metis J_C.ideD(1) J_C.MkArr_Map)\n    qed\n\n    lemma diagram_determines_ide:\n    assumes \"diagram J C D\"\n    shows \"J_C.ide (J_C.MkIde D)\" and \"J_C.Map (J_C.MkIde D) = D\"\n    proof -\n      interpret D: diagram J C D using assms by auto\n      show \"J_C.ide (J_C.MkIde D)\" using J_C.ide_char\n        using D.functor_axioms J_C.ide_MkIde by auto\n      thus \"J_C.Map (J_C.MkIde D) = D\"\n        using J_C.in_homE by simp\n    qed\n\n    lemma bij_betw_ide_diagram:\n    shows \"bij_betw J_C.Map (Collect J_C.ide) (Collect (diagram J C))\"\n    proof (intro bij_betwI)\n      show \"J_C.Map \\<in> Collect J_C.ide \\<rightarrow> Collect (diagram J C)\"\n        using ide_determines_diagram by blast\n      show \"J_C.MkIde \\<in> Collect (diagram J C) \\<rightarrow> Collect J_C.ide\"\n        using diagram_determines_ide by blast\n      show \"\\<And>d. d \\<in> Collect J_C.ide \\<Longrightarrow> J_C.MkIde (J_C.Map d) = d\"\n        using ide_determines_diagram by blast\n      show \"\\<And>D. D \\<in> Collect (diagram J C) \\<Longrightarrow> J_C.Map (J_C.MkIde D) = D\"\n        using diagram_determines_ide by blast\n    qed\n\n    text\\<open>\n      Arrows from from the diagonal functor correspond bijectively to cones.\n\\<close>\n\n    lemma arrow_determines_cone:\n    assumes \"J_C.ide d\" and \"arrow_from_functor C J_C.comp map a d x\"\n    shows \"cone J C (J_C.Map d) a (J_C.Map x)\"\n    and \"J_C.MkArr (constant_functor.map J C a) (J_C.Map d) (J_C.Map x) = x\"\n    proof -\n      interpret D: diagram J C \\<open>J_C.Map d\\<close>\n        using assms ide_determines_diagram by auto\n      interpret x: arrow_from_functor C J_C.comp map a d x\n        using assms by auto\n      interpret A: constant_functor J C a\n        using x.arrow by (unfold_locales, auto)\n      interpret \\<alpha>: constant_transformation J C a\n        using x.arrow by (unfold_locales, auto)\n      have Dom_x: \"J_C.Dom x = A.map\"\n      proof -\n        have \"J_C.dom x = map a\" using x.arrow by blast\n        hence \"J_C.Map (J_C.dom x) = J_C.Map (map a)\" by simp\n        hence \"J_C.Dom x = J_C.Map (map a)\"\n          using A.value_is_ide x.arrow J_C.in_homE by (metis J_C.Map_dom)\n        moreover have \"J_C.Map (map a) = \\<alpha>.map\"\n          using A.value_is_ide preserves_ide map_def by simp\n        ultimately show ?thesis using \\<alpha>.map_def A.map_def by auto\n      qed\n      have Cod_x: \"J_C.Cod x = J_C.Map d\"\n        using x.arrow by auto\n      interpret \\<chi>: natural_transformation J C A.map \\<open>J_C.Map d\\<close> \\<open>J_C.Map x\\<close>\n        using x.arrow J_C.arr_char [of x] Dom_x Cod_x by force\n      show \"D.cone a (J_C.Map x)\" ..\n      show \"J_C.MkArr A.map (J_C.Map d) (J_C.Map x) = x\"\n        using x.arrow Dom_x Cod_x \\<chi>.natural_transformation_axioms\n        by (intro J_C.arr_eqI, auto)\n    qed\n\n    lemma cone_determines_arrow:\n    assumes \"J_C.ide d\" and \"cone J C (J_C.Map d) a \\<chi>\"\n    shows \"arrow_from_functor C J_C.comp map a d\n             (J_C.MkArr (constant_functor.map J C a) (J_C.Map d) \\<chi>)\"\n    and \"J_C.Map (J_C.MkArr (constant_functor.map J C a) (J_C.Map d) \\<chi>) = \\<chi>\"\n    proof -\n       interpret \\<chi>: cone J C \\<open>J_C.Map d\\<close> a \\<chi> using assms(2) by auto\n       let ?x = \"J_C.MkArr \\<chi>.A.map (J_C.Map d) \\<chi>\"\n       interpret x: arrow_from_functor C J_C.comp map a d ?x\n       proof\n         have \"\\<guillemotleft>J_C.MkArr \\<chi>.A.map (J_C.Map d) \\<chi> :\n                  J_C.MkIde \\<chi>.A.map \\<rightarrow>\\<^sub>[\\<^sub>J\\<^sub>,\\<^sub>C\\<^sub>] J_C.MkIde (J_C.Map d)\\<guillemotright>\"\n           using \\<chi>.natural_transformation_axioms by auto\n         moreover have \"J_C.MkIde \\<chi>.A.map = map a\"\n           using \\<chi>.A.value_is_ide map_def \\<chi>.A.map_def C.ide_char\n           by (metis (no_types, lifting) J_C.dom_MkArr preserves_arr preserves_dom)\n         moreover have \"J_C.MkIde (J_C.Map d) = d\"\n           using assms ide_determines_diagram(2) by simp\n         ultimately show \"C.ide a \\<and> \\<guillemotleft>J_C.MkArr \\<chi>.A.map (J_C.Map d) \\<chi> : map a \\<rightarrow>\\<^sub>[\\<^sub>J\\<^sub>,\\<^sub>C\\<^sub>] d\\<guillemotright>\"\n           using \\<chi>.A.value_is_ide by simp\n       qed\n       show \"arrow_from_functor C J_C.comp map a d ?x\" ..\n       show \"J_C.Map (J_C.MkArr (constant_functor.map J C a) (J_C.Map d) \\<chi>) = \\<chi>\"\n         by (simp add: \\<chi>.natural_transformation_axioms)\n    qed\n\n    text\\<open>\n      Transforming a cone by composing at the apex with an arrow @{term g} corresponds,\n      via the preceding bijections, to composition in \\<open>[J, C]\\<close> with the image of @{term g}\n      under the diagonal functor.\n\\<close>\n\n    lemma cones_map_is_composition:\n    assumes \"\\<guillemotleft>g : a' \\<rightarrow> a\\<guillemotright>\" and \"cone J C D a \\<chi>\"\n    shows \"J_C.MkArr (constant_functor.map J C a') D (diagram.cones_map J C D g \\<chi>)\n             = J_C.MkArr (constant_functor.map J C a) D \\<chi> \\<cdot>\\<^sub>[\\<^sub>J\\<^sub>,\\<^sub>C\\<^sub>] map g\"\n    proof -\n      interpret A: constant_transformation J C a\n        using assms(1) by (unfold_locales, auto)\n      interpret \\<chi>: cone J C D a \\<chi> using assms(2) by auto\n      have cone_\\<chi>: \"cone J C D a \\<chi>\" ..\n      interpret A': constant_transformation J C a'\n        using assms(1) by (unfold_locales, auto)\n      let ?\\<chi>' = \"\\<chi>.D.cones_map g \\<chi>\"\n      interpret \\<chi>': cone J C D a' ?\\<chi>'\n        using assms(1) cone_\\<chi> \\<chi>.D.cones_map_mapsto by blast\n      let ?x = \"J_C.MkArr \\<chi>.A.map D \\<chi>\"\n      let ?x' = \"J_C.MkArr \\<chi>'.A.map D ?\\<chi>'\"\n      show \"?x' = J_C.comp ?x (map g)\"\n      proof (intro J_C.arr_eqI)\n        have x: \"J_C.arr ?x\"\n          using \\<chi>.natural_transformation_axioms J_C.arr_char [of ?x] by simp\n        show x': \"J_C.arr ?x'\"\n          using \\<chi>'.natural_transformation_axioms J_C.arr_char [of ?x'] by simp\n        have 3: \"\\<guillemotleft>?x : map a \\<rightarrow>\\<^sub>[\\<^sub>J\\<^sub>,\\<^sub>C\\<^sub>] J_C.MkIde D\\<guillemotright>\"\n        proof -\n          have 1: \"map a = J_C.MkIde A.map\"\n            using \\<chi>.ide_apex A.equals_dom_if_value_is_ide A.equals_cod_if_value_is_ide map_def\n            by auto\n          have \"J_C.arr ?x\" using x by blast\n          moreover have \"J_C.dom ?x = map a\"\n            using x J_C.dom_char 1 x \\<chi>.ide_apex A.equals_dom_if_value_is_ide \\<chi>.D.functor_axioms\n                    J_C.ide_char\n            by auto\n          moreover have \"J_C.cod ?x = J_C.MkIde D\" using x J_C.cod_char by auto\n          ultimately show ?thesis by fast\n        qed\n        have 4: \"\\<guillemotleft>?x' : map a' \\<rightarrow>\\<^sub>[\\<^sub>J\\<^sub>,\\<^sub>C\\<^sub>] J_C.MkIde D\\<guillemotright>\"\n        proof -\n          have 1: \"map a' = J_C.MkIde A'.map\"\n            using \\<chi>'.ide_apex A'.equals_dom_if_value_is_ide A'.equals_cod_if_value_is_ide map_def\n            by auto\n          have \"J_C.arr ?x'\" using x' by blast\n          moreover have \"J_C.dom ?x' = map a'\"\n            using x' J_C.dom_char 1 x' \\<chi>'.ide_apex A'.equals_dom_if_value_is_ide \\<chi>.D.functor_axioms\n                    J_C.ide_char\n            by force\n          moreover have \"J_C.cod ?x' = J_C.MkIde D\" using x' J_C.cod_char by auto\n          ultimately show ?thesis by fast\n        qed\n        have seq_xg: \"J_C.seq ?x (map g)\"\n          using assms(1) 3 preserves_hom [of g] by (intro J_C.seqI', auto)\n        show 2: \"J_C.seq ?x (map g)\"\n          using seq_xg J_C.seqI' by blast\n        show \"J_C.Dom ?x' = J_C.Dom (?x \\<cdot>\\<^sub>[\\<^sub>J\\<^sub>,\\<^sub>C\\<^sub>] map g)\"\n        proof -\n          have \"J_C.Dom ?x' = J_C.Dom (J_C.dom ?x')\"\n            using x' J_C.Dom_dom by simp\n          also have \"... = J_C.Dom (map a')\"\n            using 4 by force\n          also have \"... = J_C.Dom (J_C.dom (?x \\<cdot>\\<^sub>[\\<^sub>J\\<^sub>,\\<^sub>C\\<^sub>] map g))\"\n            using assms(1) 2 by auto\n          also have \"... = J_C.Dom (?x \\<cdot>\\<^sub>[\\<^sub>J\\<^sub>,\\<^sub>C\\<^sub>] map g)\"\n            using seq_xg J_C.Dom_dom J_C.seqI' by blast\n          finally show ?thesis by auto\n        qed\n        show \"J_C.Cod ?x' = J_C.Cod (?x \\<cdot>\\<^sub>[\\<^sub>J\\<^sub>,\\<^sub>C\\<^sub>] map g)\"\n        proof -\n          have \"J_C.Cod ?x' = J_C.Cod (J_C.cod ?x')\"\n            using x' J_C.Cod_cod by simp\n          also have \"... = J_C.Cod (J_C.MkIde D)\"\n            using 4 by force\n          also have \"... = J_C.Cod (J_C.cod (?x \\<cdot>\\<^sub>[\\<^sub>J\\<^sub>,\\<^sub>C\\<^sub>] map g))\"\n            using 2 3 J_C.cod_comp J_C.in_homE by metis\n          also have \"... = J_C.Cod (?x \\<cdot>\\<^sub>[\\<^sub>J\\<^sub>,\\<^sub>C\\<^sub>] map g)\"\n            using seq_xg J_C.Cod_cod J_C.seqI' by blast\n          finally show ?thesis by auto\n        qed\n        show \"J_C.Map ?x' = J_C.Map (?x \\<cdot>\\<^sub>[\\<^sub>J\\<^sub>,\\<^sub>C\\<^sub>] map g)\"\n        proof -\n          interpret g: constant_transformation J C g\n            apply unfold_locales using assms(1) by auto\n          interpret \\<chi>og: vertical_composite J C A'.map \\<chi>.A.map D g.map \\<chi>\n            using assms(1) C.comp_arr_dom C.comp_cod_arr A'.is_extensional g.is_extensional\n            apply (unfold_locales, auto)\n            by (elim J.seqE, auto)\n          have \"J_C.Map (?x \\<cdot>\\<^sub>[\\<^sub>J\\<^sub>,\\<^sub>C\\<^sub>] map g) = \\<chi>og.map\"\n            using assms(1) 2 J_C.comp_char map_def by auto\n          also have \"... = J_C.Map ?x'\"\n            using x' \\<chi>og.map_def J_C.arr_char [of ?x'] natural_transformation.is_extensional\n                  assms(1) cone_\\<chi> \\<chi>og.map_simp_2\n            by fastforce\n          finally show ?thesis by auto\n        qed\n      qed\n    qed\n\n    text\\<open>\n      Coextension along an arrow from a functor is equivalent to a transformation of cones.\n\\<close>\n\n    lemma coextension_iff_cones_map:\n    assumes x: \"arrow_from_functor C J_C.comp map a d x\"\n    and g: \"\\<guillemotleft>g : a' \\<rightarrow> a\\<guillemotright>\"\n    and x': \"\\<guillemotleft>x' : map a' \\<rightarrow>\\<^sub>[\\<^sub>J\\<^sub>,\\<^sub>C\\<^sub>] d\\<guillemotright>\"\n    shows \"arrow_from_functor.is_coext C J_C.comp map a x a' x' g\n              \\<longleftrightarrow> J_C.Map x' = diagram.cones_map J C (J_C.Map d) g (J_C.Map x)\"\n    proof -\n      interpret x: arrow_from_functor C J_C.comp map a d x\n        using assms by auto\n      interpret A': constant_functor J C a'\n        using assms(2) by (unfold_locales, auto)\n      have x': \"arrow_from_functor C J_C.comp map a' d x'\"\n        using A'.value_is_ide assms(3) by (unfold_locales, blast)\n      have d: \"J_C.ide d\" using J_C.ide_cod x.arrow by blast\n      let ?D = \"J_C.Map d\"\n      let ?\\<chi> = \"J_C.Map x\"\n      let ?\\<chi>' = \"J_C.Map x'\"\n      interpret D: diagram J C ?D\n        using ide_determines_diagram J_C.ide_cod x.arrow by blast\n      interpret \\<chi>: cone J C ?D a ?\\<chi>\n        using assms(1) d arrow_determines_cone by simp\n      interpret \\<gamma>: constant_transformation J C g\n        using g \\<chi>.ide_apex by (unfold_locales, auto)\n      interpret \\<chi>og: vertical_composite J C A'.map \\<chi>.A.map ?D \\<gamma>.map ?\\<chi>\n        using g C.comp_arr_dom C.comp_cod_arr \\<gamma>.is_extensional by (unfold_locales, auto)\n      show ?thesis\n      proof\n        assume 0: \"x.is_coext a' x' g\"\n        show \"?\\<chi>' = D.cones_map g ?\\<chi>\"\n        proof -\n          have 1: \"x' = x \\<cdot>\\<^sub>[\\<^sub>J\\<^sub>,\\<^sub>C\\<^sub>] map g\"\n            using 0 x.is_coext_def by blast\n          hence \"?\\<chi>' = J_C.Map x'\"\n            using 0 x.is_coext_def by fast\n          moreover have \"... = D.cones_map g ?\\<chi>\"\n          proof -\n            have \"J_C.MkArr A'.map (J_C.Map d) (D.cones_map g (J_C.Map x)) = x \\<cdot>\\<^sub>[\\<^sub>J\\<^sub>,\\<^sub>C\\<^sub>] map g\"\n              using d g cones_map_is_composition arrow_determines_cone(2) \\<chi>.cone_axioms\n                    x.arrow_from_functor_axioms\n              by auto\n            hence f1: \"J_C.MkArr A'.map (J_C.Map d) (D.cones_map g (J_C.Map x)) = x'\"\n              by (metis 1)\n            have \"J_C.arr (J_C.MkArr A'.map (J_C.Map d) (D.cones_map g (J_C.Map x)))\"\n              using 1 d g cones_map_is_composition preserves_arr arrow_determines_cone(2)\n                    \\<chi>.cone_axioms x.arrow_from_functor_axioms assms(3)\n              by auto\n            thus ?thesis\n              using f1 by auto\n          qed\n          ultimately show ?thesis by blast\n        qed\n        next\n        assume X': \"?\\<chi>' = D.cones_map g ?\\<chi>\"\n        show \"x.is_coext a' x' g\"\n        proof -\n          have 4: \"J_C.seq x (map g)\"\n            using g x.arrow mem_Collect_eq preserves_arr preserves_cod\n            by (elim C.in_homE, auto)\n          hence 1: \"x \\<cdot>\\<^sub>[\\<^sub>J\\<^sub>,\\<^sub>C\\<^sub>] map g =\n                   J_C.MkArr (J_C.Dom (map g)) (J_C.Cod x)\n                             (vertical_composite.map J C (J_C.Map (map g)) ?\\<chi>)\"\n            using J_C.comp_char [of x \"map g\"] by simp\n          have 2: \"vertical_composite.map J C (J_C.Map (map g)) ?\\<chi> = \\<chi>og.map\"\n            by (simp add: map_def \\<gamma>.value_is_arr \\<gamma>.natural_transformation_axioms)\n          have 3: \"... = D.cones_map g ?\\<chi>\"\n            using g \\<chi>og.map_simp_2 \\<chi>.cone_axioms \\<chi>og.is_extensional by auto\n          have \"J_C.MkArr A'.map ?D ?\\<chi>' = J_C.comp x (map g)\"\n          proof -\n            have f1: \"A'.map = J_C.Dom (map g)\"\n              using \\<gamma>.natural_transformation_axioms map_def g by auto\n            have \"J_C.Map d = J_C.Cod x\"\n              using x.arrow by auto\n            thus ?thesis using f1 X' 1 2 3 by argo\n          qed\n          moreover have \"J_C.MkArr A'.map ?D ?\\<chi>' = x'\"\n            using d x' arrow_determines_cone by blast\n          ultimately show ?thesis\n            using g x.is_coext_def by simp\n        qed\n      qed\n    qed\n\n  end\n\n  locale right_adjoint_to_diagonal_functor =\n    C: category C +\n    J: category J +\n    J_C: functor_category J C +\n    \\<Delta>: diagonal_functor J C +\n    \"functor\" J_C.comp C G +\n    Adj: meta_adjunction J_C.comp C \\<Delta>.map G \\<phi> \\<psi>\n  for J :: \"'j comp\"      (infixr \"\\<cdot>\\<^sub>J\" 55)\n  and C :: \"'c comp\"      (infixr \"\\<cdot>\" 55)\n  and G :: \"('j, 'c) functor_category.arr \\<Rightarrow> 'c\"\n  and \\<phi> :: \"'c \\<Rightarrow> ('j, 'c) functor_category.arr \\<Rightarrow> 'c\"\n  and \\<psi> :: \"('j, 'c) functor_category.arr \\<Rightarrow> 'c \\<Rightarrow> ('j, 'c) functor_category.arr\" +\n  assumes adjoint: \"adjoint_functors J_C.comp C \\<Delta>.map G\"\n  begin\n\n    text\\<open>\n      A right adjoint @{term G} to a diagonal functor maps each object @{term d} of\n      \\<open>[J, C]\\<close> (corresponding to a diagram @{term D} of shape @{term J} in @{term C}\n      to an object of @{term C}.  This object is the limit object, and the component at @{term d}\n      of the counit of the adjunction determines the limit cone.\n\\<close>\n\n    lemma gives_limit_cones:\n    assumes \"diagram J C D\"\n    shows \"limit_cone J C D (G (J_C.MkIde D)) (J_C.Map (Adj.\\<epsilon> (J_C.MkIde D)))\"\n    proof -\n      interpret D: diagram J C D using assms by auto\n      let ?d = \"J_C.MkIde D\"\n      let ?a = \"G ?d\"\n      let ?x = \"Adj.\\<epsilon> ?d\"\n      let ?\\<chi> = \"J_C.Map ?x\"\n      have \"diagram J C D\" ..\n      hence 1: \"J_C.ide ?d\" using \\<Delta>.diagram_determines_ide by auto\n      hence 2: \"J_C.Map (J_C.MkIde D) = D\"\n        using assms 1 J_C.in_homE \\<Delta>.diagram_determines_ide(2) by simp\n      interpret x: terminal_arrow_from_functor C J_C.comp \\<Delta>.map ?a ?d ?x\n        apply unfold_locales\n         apply (metis (no_types, lifting) \"1\" preserves_ide Adj.\\<epsilon>_in_terms_of_\\<psi>\n                Adj.\\<epsilon>o_def Adj.\\<epsilon>o_in_hom)\n        by (metis 1 Adj.has_terminal_arrows_from_functor(1)\n                  terminal_arrow_from_functor.is_terminal)\n      have 3: \"arrow_from_functor C J_C.comp \\<Delta>.map ?a ?d ?x\" ..\n      interpret \\<chi>: cone J C D ?a ?\\<chi>\n        using 1 2 3 \\<Delta>.arrow_determines_cone [of ?d] by auto\n      have cone_\\<chi>: \"D.cone ?a ?\\<chi>\" ..\n      interpret \\<chi>: limit_cone J C D ?a ?\\<chi>\n      proof\n        fix a' \\<chi>'\n        assume cone_\\<chi>': \"D.cone a' \\<chi>'\"\n        interpret \\<chi>': cone J C D a' \\<chi>' using cone_\\<chi>' by auto\n        let ?x' = \"J_C.MkArr \\<chi>'.A.map D \\<chi>'\"\n        interpret x': arrow_from_functor C J_C.comp \\<Delta>.map a' ?d ?x'\n          using 1 2 by (metis \\<Delta>.cone_determines_arrow(1) cone_\\<chi>')\n        have \"arrow_from_functor C J_C.comp \\<Delta>.map a' ?d ?x'\" ..\n        hence 4: \"\\<exists>!g. x.is_coext a' ?x' g\"\n          using x.is_terminal by simp\n        have 5: \"\\<And>g. \\<guillemotleft>g : a' \\<rightarrow>\\<^sub>C ?a\\<guillemotright> \\<Longrightarrow> x.is_coext a' ?x' g \\<longleftrightarrow> D.cones_map g ?\\<chi> = \\<chi>'\"\n        proof -\n          fix g\n          assume g: \"\\<guillemotleft>g : a' \\<rightarrow>\\<^sub>C ?a\\<guillemotright>\"\n          show \"x.is_coext a' ?x' g \\<longleftrightarrow> D.cones_map g ?\\<chi> = \\<chi>'\"\n          proof -\n            have \"\\<guillemotleft>?x' : \\<Delta>.map a' \\<rightarrow>\\<^sub>[\\<^sub>J\\<^sub>,\\<^sub>C\\<^sub>] ?d\\<guillemotright>\"\n              using x'.arrow by simp\n            thus ?thesis\n              using 3 g \\<Delta>.coextension_iff_cones_map [of ?a ?d]\n              by (metis (no_types, lifting) 1 2 \\<Delta>.cone_determines_arrow(2) cone_\\<chi>')\n          qed\n        qed\n        have 6: \"\\<And>g. x.is_coext a' ?x' g \\<Longrightarrow> \\<guillemotleft>g : a' \\<rightarrow>\\<^sub>C ?a\\<guillemotright>\"\n          using x.is_coext_def by simp\n        show \"\\<exists>!g. \\<guillemotleft>g : a' \\<rightarrow>\\<^sub>C ?a\\<guillemotright> \\<and> D.cones_map g ?\\<chi> = \\<chi>'\"\n        proof -\n          have \"\\<exists>g. \\<guillemotleft>g : a' \\<rightarrow>\\<^sub>C ?a\\<guillemotright> \\<and> D.cones_map g ?\\<chi> = \\<chi>'\"\n            using 4 5 6 by meson\n          thus ?thesis\n            using 4 5 6 by blast\n        qed\n      qed\n      show \"D.limit_cone ?a ?\\<chi>\" ..\n    qed\n\n    corollary gives_limits:\n    assumes \"diagram J C D\"\n    shows \"diagram.has_as_limit J C D (G (J_C.MkIde D))\"\n      using assms gives_limit_cones by fastforce\n\n  end\n\n  lemma (in category) has_limits_iff_left_adjoint_diagonal:\n  assumes \"category J\"\n  shows \"has_limits_of_shape J \\<longleftrightarrow>\n           left_adjoint_functor C (functor_category.comp J C) (diagonal_functor.map J C)\"\n  proof -\n    interpret J: category J using assms by auto\n    interpret J_C: functor_category J C ..\n    interpret \\<Delta>: diagonal_functor J C ..\n    show ?thesis\n    proof\n      assume A: \"left_adjoint_functor C J_C.comp \\<Delta>.map\"\n      interpret \\<Delta>: left_adjoint_functor C J_C.comp \\<Delta>.map using A by auto\n      interpret Adj: meta_adjunction J_C.comp C \\<Delta>.map \\<Delta>.G \\<Delta>.\\<phi> \\<Delta>.\\<psi>\n        using \\<Delta>.induces_meta_adjunction by auto\n      have \"meta_adjunction J_C.comp C \\<Delta>.map \\<Delta>.G \\<Delta>.\\<phi> \\<Delta>.\\<psi>\" ..\n      hence 1: \"adjoint_functors J_C.comp C \\<Delta>.map \\<Delta>.G\"\n        using adjoint_functors_def by blast\n      interpret G: right_adjoint_to_diagonal_functor J C \\<Delta>.G \\<Delta>.\\<phi> \\<Delta>.\\<psi>\n        using 1 by (unfold_locales, auto)\n      have \"\\<And>D. diagram J C D \\<Longrightarrow> \\<exists>a. diagram.has_as_limit J C D a\"\n        using A G.gives_limits by blast\n      hence \"\\<And>D. diagram J C D \\<Longrightarrow> \\<exists>a \\<chi>. limit_cone J C D a \\<chi>\"\n        by metis\n      thus \"has_limits_of_shape J\" using has_limits_of_shape_def by blast\n      next\n      text\\<open>\n        If @{term \"has_limits J\"}, then every diagram @{term D} from @{term J} to\n        @{term[source=true] C} has a limit cone.\n        This means that, for every object @{term d} of the functor category\n        \\<open>[J, C]\\<close>, there exists an object @{term a} of @{term C} and a terminal arrow from\n        \\<open>\\<Delta> a\\<close> to @{term d} in \\<open>[J, C]\\<close>.  The terminal arrow is given by the\n        limit cone.\n\\<close>\n      assume A: \"has_limits_of_shape J\"\n      show \"left_adjoint_functor C J_C.comp \\<Delta>.map\"\n      proof\n        fix d\n        assume D: \"J_C.ide d\"\n        interpret D: diagram J C \\<open>J_C.Map d\\<close>\n          using D \\<Delta>.ide_determines_diagram by auto\n        let ?D = \"J_C.Map d\"\n        have \"diagram J C (J_C.Map d)\" ..\n        from this obtain a \\<chi> where limit: \"limit_cone J C ?D a \\<chi>\"\n          using A has_limits_of_shape_def by blast\n        interpret A: constant_functor J C a\n          using limit by (simp add: Limit.cone_def limit_cone_def)\n        interpret \\<chi>: limit_cone J C ?D a \\<chi> using limit by auto\n        have cone_\\<chi>: \"cone J C ?D a \\<chi>\" ..\n        let ?x = \"J_C.MkArr A.map ?D \\<chi>\"\n        interpret x: arrow_from_functor C J_C.comp \\<Delta>.map a d ?x\n          using D cone_\\<chi> \\<Delta>.cone_determines_arrow by auto\n        have \"terminal_arrow_from_functor C J_C.comp \\<Delta>.map a d ?x\"\n        proof\n          show \"\\<And>a' x'. arrow_from_functor C J_C.comp \\<Delta>.map a' d x' \\<Longrightarrow> \\<exists>!g. x.is_coext a' x' g\"\n          proof -\n            fix a' x'\n            assume x': \"arrow_from_functor C J_C.comp \\<Delta>.map a' d x'\"\n            interpret x': arrow_from_functor C J_C.comp \\<Delta>.map a' d x' using x' by auto\n            interpret A': constant_functor J C a'\n              by (unfold_locales, simp add: x'.arrow)\n            let ?\\<chi>' = \"J_C.Map x'\"\n            interpret \\<chi>': cone J C ?D a' ?\\<chi>'\n              using D x' \\<Delta>.arrow_determines_cone by auto\n            have cone_\\<chi>': \"cone J C ?D a' ?\\<chi>'\" ..\n            let ?g = \"\\<chi>.induced_arrow a' ?\\<chi>'\"\n            show \"\\<exists>!g. x.is_coext a' x' g\"\n            proof\n              show \"x.is_coext a' x' ?g\"\n              proof (unfold x.is_coext_def)\n                have 1: \"\\<guillemotleft>?g : a' \\<rightarrow> a\\<guillemotright> \\<and> D.cones_map ?g \\<chi> = ?\\<chi>'\"\n                  using \\<chi>.induced_arrow_def \\<chi>.is_universal cone_\\<chi>'\n                        theI' [of \"\\<lambda>f. \\<guillemotleft>f : a' \\<rightarrow> a\\<guillemotright> \\<and> D.cones_map f \\<chi> = ?\\<chi>'\"]\n                  by presburger\n                hence 2: \"x' = ?x \\<cdot>\\<^sub>[\\<^sub>J\\<^sub>,\\<^sub>C\\<^sub>] \\<Delta>.map ?g\"\n                proof -\n                  have \"x' = J_C.MkArr A'.map ?D ?\\<chi>'\"\n                    using D \\<Delta>.arrow_determines_cone(2) x'.arrow_from_functor_axioms by auto\n                  thus ?thesis\n                    using 1 cone_\\<chi> \\<Delta>.cones_map_is_composition [of ?g a' a ?D \\<chi>] by simp\n                qed\n                show \"\\<guillemotleft>?g : a' \\<rightarrow> a\\<guillemotright> \\<and> x' = ?x \\<cdot>\\<^sub>[\\<^sub>J\\<^sub>,\\<^sub>C\\<^sub>] \\<Delta>.map ?g\"\n                  using 1 2 by auto\n              qed\n              next\n              fix g\n              assume X: \"x.is_coext a' x' g\"\n              show \"g = ?g\"\n              proof -\n                have \"\\<guillemotleft>g : a' \\<rightarrow> a\\<guillemotright> \\<and> D.cones_map g \\<chi> = ?\\<chi>'\"\n                proof\n                  show G: \"\\<guillemotleft>g : a' \\<rightarrow> a\\<guillemotright>\" using X x.is_coext_def by blast\n                  show \"D.cones_map g \\<chi> = ?\\<chi>'\"\n                  proof -\n                    have \"?\\<chi>' = J_C.Map (?x \\<cdot>\\<^sub>[\\<^sub>J\\<^sub>,\\<^sub>C\\<^sub>] \\<Delta>.map g)\"\n                      using X x.is_coext_def [of a' x' g] by fast\n                    also have \"... = D.cones_map g \\<chi>\"\n                    proof -\n                      interpret map_g: constant_transformation J C g\n                        using G by (unfold_locales, auto)\n                      interpret \\<chi>': vertical_composite J C\n                                      map_g.F.map A.map \\<open>\\<chi>.\\<Phi>.Ya.Cop_S.Map d\\<close>\n                                      map_g.map \\<chi>\n                      proof (intro_locales)\n                        have \"map_g.G.map = A.map\"\n                          using G by blast\n                        thus \"natural_transformation_axioms J (\\<cdot>) map_g.F.map A.map map_g.map\"\n                          using map_g.natural_transformation_axioms\n                          by (simp add: natural_transformation_def)\n                      qed\n                      have \"J_C.Map (?x \\<cdot>\\<^sub>[\\<^sub>J\\<^sub>,\\<^sub>C\\<^sub>] \\<Delta>.map g) = vertical_composite.map J C map_g.map \\<chi>\"\n                      proof -\n                        have \"J_C.seq ?x (\\<Delta>.map g)\"\n                          using G x.arrow by auto\n                        thus ?thesis\n                          using G \\<Delta>.map_def J_C.Map_comp' [of ?x \"\\<Delta>.map g\"] by auto\n                      qed\n                      also have \"... = D.cones_map g \\<chi>\"\n                        using G cone_\\<chi> \\<chi>'.map_def map_g.map_def \\<chi>.is_natural_2 \\<chi>'.map_simp_2\n                        by auto\n                      finally show ?thesis by blast\n                    qed\n                    finally show ?thesis by auto\n                  qed\n                qed\n                thus ?thesis\n                  using cone_\\<chi>' \\<chi>.is_universal \\<chi>.induced_arrow_def\n                        theI_unique [of \"\\<lambda>g. \\<guillemotleft>g : a' \\<rightarrow> a\\<guillemotright> \\<and> D.cones_map g \\<chi> = ?\\<chi>'\" g]\n                  by presburger\n              qed\n            qed\n          qed\n        qed\n        thus \"\\<exists>a x. terminal_arrow_from_functor C J_C.comp \\<Delta>.map a d x\" by auto\n      qed\n    qed\n  qed\n\n  section \"Right Adjoint Functors Preserve Limits\"\n\n  context right_adjoint_functor\n  begin\n\n    lemma preserves_limits:\n    fixes J :: \"'j comp\"\n    assumes \"diagram J C E\" and \"diagram.has_as_limit J C E a\"\n    shows \"diagram.has_as_limit J D (G o E) (G a)\"\n    proof -\n      text\\<open>\n        From the assumption that @{term E} has a limit, obtain a limit cone @{term \\<chi>}.\n\\<close>\n      interpret J: category J using assms(1) diagram_def by auto\n      interpret E: diagram J C E using assms(1) by auto\n      from assms(2) obtain \\<chi> where \\<chi>: \"limit_cone J C E a \\<chi>\" by auto\n      interpret \\<chi>: limit_cone J C E a \\<chi> using \\<chi> by auto\n      have a: \"C.ide a\" using \\<chi>.ide_apex by auto\n      text\\<open>\n        Form the @{term E}-image \\<open>GE\\<close> of the diagram @{term E}.\n\\<close>\n      interpret GE: composite_functor J C D E G ..\n      interpret GE: diagram J D GE.map ..\n      text\\<open>Let \\<open>G\\<chi>\\<close> be the @{term G}-image of the cone @{term \\<chi>},\n             and note that it is a cone over \\<open>GE\\<close>.\\<close>\n      let ?G\\<chi> = \"G o \\<chi>\"\n      interpret G\\<chi>: cone J D GE.map \\<open>G a\\<close> ?G\\<chi>\n        using \\<chi>.cone_axioms preserves_cones by blast\n      text\\<open>\n        Claim that \\<open>G\\<chi>\\<close> is a limit cone for diagram \\<open>GE\\<close>.\n\\<close>\n      interpret G\\<chi>: limit_cone J D GE.map \\<open>G a\\<close> ?G\\<chi>\n      proof\n        text \\<open>\n          Let @{term \\<kappa>} be an arbitrary cone over \\<open>GE\\<close>.\n\\<close>\n        fix b \\<kappa>\n        assume \\<kappa>: \"GE.cone b \\<kappa>\"\n        interpret \\<kappa>: cone J D GE.map b \\<kappa> using \\<kappa> by auto\n        interpret Fb: constant_functor J C \\<open>F b\\<close>\n          apply unfold_locales\n          by (meson F_is_functor \\<kappa>.ide_apex functor.preserves_ide)\n        interpret Adj: meta_adjunction C D F G \\<phi> \\<psi>\n          using induces_meta_adjunction by auto\n        text\\<open>\n          For each arrow @{term j} of @{term J}, let @{term \"\\<chi>' j\"} be defined to be\n          the adjunct of @{term \"\\<chi> j\"}.  We claim that @{term \\<chi>'} is a cone over @{term E}.\n\\<close>\n        let ?\\<chi>' = \"\\<lambda>j. if J.arr j then Adj.\\<epsilon> (C.cod (E j)) \\<cdot>\\<^sub>C F (\\<kappa> j) else C.null\"\n        have cone_\\<chi>': \"E.cone (F b) ?\\<chi>'\"\n        proof\n          show \"\\<And>j. \\<not>J.arr j \\<Longrightarrow> ?\\<chi>' j = C.null\" by simp\n          fix j\n          assume j: \"J.arr j\"\n          show \"C.dom (?\\<chi>' j) = Fb.map (J.dom j)\" using j \\<psi>_in_hom by simp\n          show \"C.cod (?\\<chi>' j) = E (J.cod j)\" using j \\<psi>_in_hom by simp\n          show \"E j \\<cdot>\\<^sub>C ?\\<chi>' (J.dom j) = ?\\<chi>' j\"\n          proof -\n            have \"E j \\<cdot>\\<^sub>C ?\\<chi>' (J.dom j) = (E j \\<cdot>\\<^sub>C Adj.\\<epsilon> (E (J.dom j))) \\<cdot>\\<^sub>C F (\\<kappa> (J.dom j))\"\n              using j C.comp_assoc by simp\n            also have \"... = Adj.\\<epsilon> (E (J.cod j)) \\<cdot>\\<^sub>C F (\\<kappa> j)\"\n            proof -\n              have \"(E j \\<cdot>\\<^sub>C Adj.\\<epsilon> (E (J.dom j))) \\<cdot>\\<^sub>C F (\\<kappa> (J.dom j))\n                       = (Adj.\\<epsilon> (C.cod (E j)) \\<cdot>\\<^sub>C Adj.FG.map (E j)) \\<cdot>\\<^sub>C F (\\<kappa> (J.dom j))\"\n                using j Adj.\\<epsilon>.naturality [of \"E j\"] by fastforce\n              also have \"... = Adj.\\<epsilon> (C.cod (E j)) \\<cdot>\\<^sub>C Adj.FG.map (E j) \\<cdot>\\<^sub>C F (\\<kappa> (J.dom j))\"\n                using C.comp_assoc by simp\n              also have \"... = Adj.\\<epsilon> (E (J.cod j)) \\<cdot>\\<^sub>C F (\\<kappa> j)\"\n              proof -\n                have \"Adj.FG.map (E j) \\<cdot>\\<^sub>C F (\\<kappa> (J.dom j)) = F (GE.map j \\<cdot>\\<^sub>D \\<kappa> (J.dom j))\"\n                  using j by simp\n                hence \"Adj.FG.map (E j) \\<cdot>\\<^sub>C F (\\<kappa> (J.dom j)) = F (\\<kappa> j)\"\n                  using j \\<kappa>.is_natural_1 by metis\n                thus ?thesis using j by simp\n              qed\n              finally show ?thesis by auto\n            qed\n            also have \"... = ?\\<chi>' j\"\n              using j by simp\n            finally show ?thesis by auto\n          qed\n          show \"?\\<chi>' (J.cod j) \\<cdot>\\<^sub>C Fb.map j = ?\\<chi>' j\"\n          proof -\n            have \"?\\<chi>' (J.cod j) \\<cdot>\\<^sub>C Fb.map j = Adj.\\<epsilon> (E (J.cod j)) \\<cdot>\\<^sub>C F (\\<kappa> (J.cod j))\"\n              using j Fb.value_is_ide Adj.\\<epsilon>.preserves_hom C.comp_arr_dom [of \"F (\\<kappa> (J.cod j))\"]\n                    C.comp_assoc\n              by simp\n            also have \"... = Adj.\\<epsilon> (E (J.cod j)) \\<cdot>\\<^sub>C F (\\<kappa> j)\"\n              using j \\<kappa>.is_natural_1 \\<kappa>.is_natural_2 Adj.\\<epsilon>.naturality J.arr_cod_iff_arr\n              by (metis J.cod_cod \\<kappa>.A.map_simp)\n            also have \"... = ?\\<chi>' j\" using j by simp\n            finally show ?thesis by auto\n          qed\n        qed\n        text\\<open>\n          Using the universal property of the limit cone @{term \\<chi>}, obtain the unique arrow\n          @{term f} that transforms @{term \\<chi>} into @{term \\<chi>'}.\n\\<close>\n        from this \\<chi>.is_universal [of \"F b\" ?\\<chi>'] obtain f\n          where f: \"\\<guillemotleft>f : F b \\<rightarrow>\\<^sub>C a\\<guillemotright> \\<and> E.cones_map f \\<chi> = ?\\<chi>'\"\n          by auto\n        text\\<open>\n          Let @{term g} be the adjunct of @{term f}, and show that @{term g} transforms\n          @{term G\\<chi>} into @{term \\<kappa>}.\n\\<close>\n        let ?g = \"G f \\<cdot>\\<^sub>D Adj.\\<eta> b\"\n        have 1: \"\\<guillemotleft>?g : b \\<rightarrow>\\<^sub>D G a\\<guillemotright>\" using f \\<kappa>.ide_apex by fastforce\n        moreover have \"GE.cones_map ?g ?G\\<chi> = \\<kappa>\"\n        proof\n          fix j\n          have \"\\<not>J.arr j \\<Longrightarrow> GE.cones_map ?g ?G\\<chi> j = \\<kappa> j\"\n            using 1 G\\<chi>.cone_axioms \\<kappa>.is_extensional by auto\n          moreover have \"J.arr j \\<Longrightarrow> GE.cones_map ?g ?G\\<chi> j = \\<kappa> j\"\n          proof -\n            fix j\n            assume j: \"J.arr j\"\n            have \"GE.cones_map ?g ?G\\<chi> j = G (\\<chi> j) \\<cdot>\\<^sub>D ?g\"\n              using j 1 G\\<chi>.cone_axioms mem_Collect_eq restrict_apply by auto\n            also have \"... = G (\\<chi> j \\<cdot>\\<^sub>C f) \\<cdot>\\<^sub>D Adj.\\<eta> b\"\n              using j f \\<chi>.preserves_hom [of j \"J.dom j\" \"J.cod j\"] D.comp_assoc by fastforce\n            also have \"... = G (E.cones_map f \\<chi> j) \\<cdot>\\<^sub>D Adj.\\<eta> b\"\n            proof -\n              have \"\\<chi> j \\<cdot>\\<^sub>C f = Adj.\\<epsilon> (C.cod (E j)) \\<cdot>\\<^sub>C F (\\<kappa> j)\"\n              proof -\n                have \"E.cone (C.cod f) \\<chi>\"\n                  using f \\<chi>.cone_axioms by blast\n                hence \"\\<chi> j \\<cdot>\\<^sub>C f = E.cones_map f \\<chi> j\"\n                  using \\<chi>.is_extensional by simp\n                also have \"... = Adj.\\<epsilon> (C.cod (E j)) \\<cdot>\\<^sub>C F (\\<kappa> j)\"\n                  using j f by simp\n                finally show ?thesis by blast\n              qed\n              thus ?thesis\n                using f mem_Collect_eq restrict_apply Adj.F.is_extensional by simp\n            qed\n            also have \"... = (G (Adj.\\<epsilon> (C.cod (E j))) \\<cdot>\\<^sub>D Adj.\\<eta> (D.cod (GE.map j))) \\<cdot>\\<^sub>D \\<kappa> j\"\n              using j f Adj.\\<eta>.naturality [of \"\\<kappa> j\"] D.comp_assoc by auto\n            also have \"... = D.cod (\\<kappa> j) \\<cdot>\\<^sub>D \\<kappa> j\"\n              using j Adj.\\<eta>\\<epsilon>.triangle_G Adj.\\<epsilon>_in_terms_of_\\<psi> Adj.\\<epsilon>o_def\n                      Adj.\\<eta>_in_terms_of_\\<phi> Adj.\\<eta>o_def Adj.unit_counit_G\n              by fastforce\n            also have \"... = \\<kappa> j\"\n              using j D.comp_cod_arr by simp\n            finally show \"GE.cones_map ?g ?G\\<chi> j = \\<kappa> j\" by metis\n          qed\n          ultimately show \"GE.cones_map ?g ?G\\<chi> j = \\<kappa> j\" by auto\n        qed\n        ultimately have \"\\<guillemotleft>?g : b \\<rightarrow>\\<^sub>D G a\\<guillemotright> \\<and> GE.cones_map ?g ?G\\<chi> = \\<kappa>\" by auto\n        text\\<open>\n          It remains to be shown that @{term g} is the unique such arrow.\n          Given any @{term g'} that transforms @{term G\\<chi>} into @{term \\<kappa>},\n          its adjunct transforms @{term \\<chi>} into @{term \\<chi>'}.\n          The adjunct of @{term g'} is therefore equal to @{term f},\n          which implies @{term g'} = @{term g}.\n\\<close>\n        moreover have \"\\<And>g'. \\<guillemotleft>g' : b \\<rightarrow>\\<^sub>D G a\\<guillemotright> \\<and> GE.cones_map g' ?G\\<chi> = \\<kappa> \\<Longrightarrow> g' = ?g\"\n        proof -\n          fix g'\n          assume g': \"\\<guillemotleft>g' : b \\<rightarrow>\\<^sub>D G a\\<guillemotright> \\<and> GE.cones_map g' ?G\\<chi> = \\<kappa>\"\n          have 1: \"\\<guillemotleft>\\<psi> a g' : F b \\<rightarrow>\\<^sub>C a\\<guillemotright>\"\n            using g' a \\<psi>_in_hom by simp\n          have 2: \"E.cones_map (\\<psi> a g') \\<chi> = ?\\<chi>'\"\n          proof\n            fix j\n            have \"\\<not>J.arr j \\<Longrightarrow> E.cones_map (\\<psi> a g') \\<chi> j = ?\\<chi>' j\"\n              using 1 \\<chi>.cone_axioms by auto\n            moreover have \"J.arr j \\<Longrightarrow> E.cones_map (\\<psi> a g') \\<chi> j = ?\\<chi>' j\"\n            proof -\n              fix j\n              assume j: \"J.arr j\"\n              have \"E.cones_map (\\<psi> a g') \\<chi> j = \\<chi> j \\<cdot>\\<^sub>C \\<psi> a g'\"\n                using 1 \\<chi>.cone_axioms \\<chi>.is_extensional by auto\n              also have \"... = (\\<chi> j \\<cdot>\\<^sub>C Adj.\\<epsilon> a) \\<cdot>\\<^sub>C F g'\"\n                using j a g' Adj.\\<psi>_in_terms_of_\\<epsilon> C.comp_assoc Adj.\\<epsilon>_def by auto\n              also have \"... = (Adj.\\<epsilon> (C.cod (E j)) \\<cdot>\\<^sub>C F (G (\\<chi> j))) \\<cdot>\\<^sub>C F g'\"\n                using j a g' Adj.\\<epsilon>.naturality [of \"\\<chi> j\"] by simp\n              also have \"... = Adj.\\<epsilon> (C.cod (E j)) \\<cdot>\\<^sub>C F (\\<kappa> j)\"\n                using j a g' G\\<chi>.cone_axioms C.comp_assoc by auto\n              finally show \"E.cones_map (\\<psi> a g') \\<chi> j = ?\\<chi>' j\" by (simp add: j)\n            qed\n            ultimately show \"E.cones_map (\\<psi> a g') \\<chi> j = ?\\<chi>' j\" by auto\n          qed\n          have \"\\<psi> a g' = f\"\n          proof -\n            have \"\\<exists>!f. \\<guillemotleft>f : F b \\<rightarrow>\\<^sub>C a\\<guillemotright> \\<and> E.cones_map f \\<chi> = ?\\<chi>'\"\n              using cone_\\<chi>' \\<chi>.is_universal by simp\n            moreover have \"\\<guillemotleft>\\<psi> a g' : F b \\<rightarrow>\\<^sub>C a\\<guillemotright> \\<and> E.cones_map (\\<psi> a g') \\<chi> = ?\\<chi>'\"\n              using 1 2 by simp\n            ultimately show ?thesis\n              using ex1E [of \"\\<lambda>f. \\<guillemotleft>f : F b \\<rightarrow>\\<^sub>C a\\<guillemotright> \\<and> E.cones_map f \\<chi> = ?\\<chi>'\" \"\\<psi> a g' = f\"]\n              using 1 2 Adj.\\<epsilon>.is_extensional C.comp_null(2) C.ex_un_null \\<chi>.cone_axioms f\n                    mem_Collect_eq restrict_apply\n              by blast\n          qed\n          hence \"\\<phi> b (\\<psi> a g') = \\<phi> b f\" by auto\n          hence \"g' = \\<phi> b f\" using \\<chi>.ide_apex g' by (simp add: \\<phi>_\\<psi>)\n          moreover have \"?g = \\<phi> b f\" using f Adj.\\<phi>_in_terms_of_\\<eta> \\<kappa>.ide_apex Adj.\\<eta>_def by auto\n          ultimately show \"g' = ?g\" by argo\n        qed\n        ultimately show \"\\<exists>!g. \\<guillemotleft>g : b \\<rightarrow>\\<^sub>D G a\\<guillemotright> \\<and> GE.cones_map g ?G\\<chi> = \\<kappa>\" by blast\n      qed\n      have \"GE.limit_cone (G a) ?G\\<chi>\" ..\n      thus ?thesis by auto\n    qed\n\n  end\n\n  section \"Special Kinds of Limits\"\n\n  subsection \"Terminal Objects\"\n\n  text\\<open>\n   An object of a category @{term C} is a terminal object if and only if it is a limit of the\n   empty diagram in @{term C}.\n\\<close>\n\n  locale empty_diagram =\n    diagram J C D\n  for J :: \"'j comp\"      (infixr \"\\<cdot>\\<^sub>J\" 55)\n  and C :: \"'c comp\"      (infixr \"\\<cdot>\" 55)\n  and D :: \"'j \\<Rightarrow> 'c\" +\n  assumes is_empty: \"\\<not>J.arr j\"\n  begin\n\n    lemma has_as_limit_iff_terminal:\n    shows \"has_as_limit a \\<longleftrightarrow> C.terminal a\"\n    proof\n      assume a: \"has_as_limit a\"\n      show \"C.terminal a\"\n      proof\n        have \"\\<exists>\\<chi>. limit_cone a \\<chi>\" using a by auto\n        from this obtain \\<chi> where \\<chi>: \"limit_cone a \\<chi>\" by blast\n        interpret \\<chi>: limit_cone J C D a \\<chi> using \\<chi> by auto\n        have cone_\\<chi>: \"cone a \\<chi>\" ..\n        show \"C.ide a\" using \\<chi>.ide_apex by auto\n        have 1: \"\\<chi> = (\\<lambda>j. C.null)\" using is_empty \\<chi>.is_extensional by auto\n        show \"\\<And>a'. C.ide a' \\<Longrightarrow> \\<exists>!f. \\<guillemotleft>f : a' \\<rightarrow> a\\<guillemotright>\"\n        proof -\n          fix a'\n          assume a': \"C.ide a'\"\n          interpret A': constant_functor J C a'\n            apply unfold_locales using a' by auto\n          let ?\\<chi>' = \"\\<lambda>j. C.null\"\n          have cone_\\<chi>': \"cone a' ?\\<chi>'\"\n            using a' is_empty apply unfold_locales by auto\n          hence \"\\<exists>!f. \\<guillemotleft>f : a' \\<rightarrow> a\\<guillemotright> \\<and> cones_map f \\<chi> = ?\\<chi>'\"\n            using \\<chi>.is_universal by force\n          moreover have \"\\<And>f. \\<guillemotleft>f : a' \\<rightarrow> a\\<guillemotright> \\<Longrightarrow> cones_map f \\<chi> = ?\\<chi>'\"\n            using 1 cone_\\<chi> by auto\n          ultimately show \"\\<exists>!f. \\<guillemotleft>f : a' \\<rightarrow> a\\<guillemotright>\" by blast\n        qed\n      qed\n      next\n      assume a: \"C.terminal a\"\n      show \"has_as_limit a\"\n      proof -\n        let ?\\<chi> = \"\\<lambda>j. C.null\"\n        have \"C.ide a\" using a C.terminal_def by simp\n        interpret A: constant_functor J C a\n          apply unfold_locales using \\<open>C.ide a\\<close> by simp\n        interpret \\<chi>: cone J C D a ?\\<chi>\n          using \\<open>C.ide a\\<close> is_empty by (unfold_locales, auto)\n        have cone_\\<chi>: \"cone a ?\\<chi>\" .. \n        have 1: \"\\<And>a' \\<chi>'. cone a' \\<chi>' \\<Longrightarrow> \\<chi>' = (\\<lambda>j. C.null)\"\n        proof -\n          fix a' \\<chi>'\n          assume \\<chi>': \"cone a' \\<chi>'\"\n          interpret \\<chi>': cone J C D a' \\<chi>' using \\<chi>' by auto\n          show \"\\<chi>' = (\\<lambda>j. C.null)\"\n            using is_empty \\<chi>'.is_extensional by metis\n        qed\n        have \"limit_cone a ?\\<chi>\"\n        proof\n          fix a' \\<chi>'\n          assume \\<chi>': \"cone a' \\<chi>'\"\n          have 2: \"\\<chi>' = (\\<lambda>j. C.null)\" using 1 \\<chi>' by simp\n          interpret \\<chi>': cone J C D a' \\<chi>' using \\<chi>' by auto\n          have \"\\<exists>!f. \\<guillemotleft>f : a' \\<rightarrow> a\\<guillemotright>\" using a C.terminal_def \\<chi>'.ide_apex by simp\n          moreover have \"\\<And>f. \\<guillemotleft>f : a' \\<rightarrow> a\\<guillemotright> \\<Longrightarrow> cones_map f ?\\<chi> = \\<chi>'\"\n           using 1 2 cones_map_mapsto cone_\\<chi> \\<chi>'.cone_axioms mem_Collect_eq by blast\n          ultimately show \"\\<exists>!f. \\<guillemotleft>f : a' \\<rightarrow> a\\<guillemotright> \\<and> cones_map f (\\<lambda>j. C.null) = \\<chi>'\"\n            by blast\n        qed\n        thus ?thesis by auto\n      qed\n    qed\n\n  end\n\n  subsection \"Products\"\n\n  text\\<open>\n    A \\emph{product} in a category @{term C} is a limit of a discrete diagram in @{term C}.\n\\<close>\n\n  locale discrete_diagram =\n    J: category J +\n    diagram J C D\n  for J :: \"'j comp\"      (infixr \"\\<cdot>\\<^sub>J\" 55)\n  and C :: \"'c comp\"      (infixr \"\\<cdot>\" 55)\n  and D :: \"'j \\<Rightarrow> 'c\" +\n  assumes is_discrete: \"J.arr = J.ide\"\n  begin\n\n    abbreviation mkCone\n    where \"mkCone F \\<equiv> (\\<lambda>j. if J.arr j then F j else C.null)\"\n\n    lemma cone_mkCone:\n    assumes \"C.ide a\" and \"\\<And>j. J.arr j \\<Longrightarrow> \\<guillemotleft>F j : a \\<rightarrow> D j\\<guillemotright>\"\n    shows \"cone a (mkCone F)\"\n    proof -\n      interpret A: constant_functor J C a\n        apply unfold_locales using assms(1) by auto\n      show \"cone a (mkCone F)\"\n        using assms(2) is_discrete\n        apply unfold_locales\n            apply auto\n         apply (metis C.in_homE C.comp_cod_arr)\n        using C.comp_arr_ide by fastforce\n    qed\n\n    lemma mkCone_cone:\n    assumes \"cone a \\<pi>\"\n    shows \"mkCone \\<pi> = \\<pi>\"\n    proof -\n      interpret \\<pi>: cone J C D a \\<pi>\n        using assms by auto\n      show \"mkCone \\<pi> = \\<pi>\" using \\<pi>.is_extensional by auto\n    qed\n\n  end\n\n  text\\<open>\n    The following locale defines a discrete diagram in a category @{term C},\n    given an index set @{term I} and a function @{term D} mapping @{term I}\n    to objects of @{term C}.  Here we obtain the diagram shape @{term J}\n    using a discrete category construction that allows us to directly identify\n    the objects of @{term J} with the elements of @{term I}, however this construction\n    can only be applied in case the set @{term I} is not the universe of its\n    element type.\n\\<close>\n\n  locale discrete_diagram_from_map =\n    J: discrete_category I null +\n    C: category C\n  for I :: \"'i set\"\n  and C :: \"'c comp\"      (infixr \"\\<cdot>\" 55)\n  and D :: \"'i \\<Rightarrow> 'c\"\n  and null :: 'i +\n  assumes maps_to_ide: \"i \\<in> I \\<Longrightarrow> C.ide (D i)\"\n  begin\n\n    definition map\n    where \"map j \\<equiv> if J.arr j then D j else C.null\"\n\n  end\n\n  sublocale discrete_diagram_from_map \\<subseteq> discrete_diagram J.comp C map\n    using map_def maps_to_ide J.arr_char J.Null_not_in_Obj J.null_char\n    by (unfold_locales, auto)\n\n  locale product_cone =\n    J: category J +\n    C: category C +\n    D: discrete_diagram J C D +\n    limit_cone J C D a \\<pi>\n  for J :: \"'j comp\"      (infixr \"\\<cdot>\\<^sub>J\" 55)\n  and C :: \"'c comp\"      (infixr \"\\<cdot>\" 55)\n  and D :: \"'j \\<Rightarrow> 'c\"\n  and a :: 'c\n  and \\<pi> :: \"'j \\<Rightarrow> 'c\"\n  begin\n\n    lemma is_cone:\n    shows \"D.cone a \\<pi>\" ..\n\n    text\\<open>\n      The following versions of @{prop is_universal} and @{prop induced_arrowI}\n      from the \\<open>limit_cone\\<close> locale are specialized to the case in which the\n      underlying diagram is a product diagram.\n\\<close>\n\n    lemma is_universal':\n    assumes \"C.ide b\" and \"\\<And>j. J.arr j \\<Longrightarrow> \\<guillemotleft>F j: b \\<rightarrow> D j\\<guillemotright>\"\n    shows \"\\<exists>!f. \\<guillemotleft>f : b \\<rightarrow> a\\<guillemotright> \\<and> (\\<forall>j. J.arr j \\<longrightarrow> \\<pi> j \\<cdot> f = F j)\"\n    proof -\n      let ?\\<chi> = \"D.mkCone F\"\n      interpret B: constant_functor J C b\n        apply unfold_locales using assms(1) by auto\n      have cone_\\<chi>: \"D.cone b ?\\<chi>\"\n        using assms D.is_discrete\n        apply unfold_locales\n            apply auto\n         apply (meson C.comp_ide_arr C.ide_in_hom C.seqI' D.preserves_ide)\n        using C.comp_arr_dom by blast\n      interpret \\<chi>: cone J C D b ?\\<chi> using cone_\\<chi> by auto\n      have \"\\<exists>!f. \\<guillemotleft>f : b \\<rightarrow> a\\<guillemotright> \\<and> D.cones_map f \\<pi> = ?\\<chi>\"\n        using cone_\\<chi> is_universal by force\n      moreover have\n           \"\\<And>f. \\<guillemotleft>f : b \\<rightarrow> a\\<guillemotright> \\<Longrightarrow> D.cones_map f \\<pi> = ?\\<chi> \\<longleftrightarrow> (\\<forall>j. J.arr j \\<longrightarrow> \\<pi> j \\<cdot> f = F j)\"\n      proof -\n        fix f\n        assume f: \"\\<guillemotleft>f : b \\<rightarrow> a\\<guillemotright>\"\n        show \"D.cones_map f \\<pi> = ?\\<chi> \\<longleftrightarrow> (\\<forall>j. J.arr j \\<longrightarrow> \\<pi> j \\<cdot> f = F j)\"\n        proof\n          assume 1: \"D.cones_map f \\<pi> = ?\\<chi>\"\n          show \"\\<forall>j. J.arr j \\<longrightarrow> \\<pi> j \\<cdot> f = F j\"\n          proof -\n            have \"\\<And>j. J.arr j \\<Longrightarrow> \\<pi> j \\<cdot> f = F j\"\n            proof -\n              fix j\n              assume j: \"J.arr j\"\n              have \"\\<pi> j \\<cdot> f = D.cones_map f \\<pi> j\"\n                using j f cone_axioms by force\n              also have \"... = F j\" using j 1 by simp\n              finally show \"\\<pi> j \\<cdot> f = F j\" by auto\n            qed\n            thus ?thesis by auto\n          qed\n          next\n          assume 1: \"\\<forall>j. J.arr j \\<longrightarrow> \\<pi> j \\<cdot> f = F j\"\n          show \"D.cones_map f \\<pi> = ?\\<chi>\"\n            using 1 f is_cone \\<chi>.is_extensional D.is_discrete is_cone cone_\\<chi> by auto\n        qed\n      qed\n      ultimately show ?thesis by blast\n    qed\n\n    abbreviation induced_arrow' :: \"'c \\<Rightarrow> ('j \\<Rightarrow> 'c) \\<Rightarrow> 'c\"\n    where \"induced_arrow' b F \\<equiv> induced_arrow b (D.mkCone F)\"\n\n    lemma induced_arrowI':\n    assumes \"C.ide b\" and \"\\<And>j. J.arr j \\<Longrightarrow> \\<guillemotleft>F j : b \\<rightarrow> D j\\<guillemotright>\"\n    shows \"\\<And>j. J.arr j \\<Longrightarrow> \\<pi> j \\<cdot> induced_arrow' b F = F j\"\n    proof -\n      interpret B: constant_functor J C b\n        apply unfold_locales using assms(1) by auto\n      interpret \\<chi>: cone J C D b \\<open>D.mkCone F\\<close>\n        using assms D.cone_mkCone by blast\n      have cone_\\<chi>: \"D.cone b (D.mkCone F)\" ..\n      hence 1: \"D.cones_map (induced_arrow' b F) \\<pi> = D.mkCone F\"\n        using induced_arrowI by blast\n      fix j\n      assume j: \"J.arr j\"\n      have \"\\<pi> j \\<cdot> induced_arrow' b F = D.cones_map (induced_arrow' b F) \\<pi> j\"\n        using induced_arrowI(1) cone_\\<chi> is_cone is_extensional by force\n      also have \"... = F j\"\n        using j 1 by auto\n      finally show \"\\<pi> j \\<cdot> induced_arrow' b F = F j\"\n        by auto\n    qed\n\n  end\n\n  context discrete_diagram\n  begin\n\n    lemma product_coneI:\n    assumes \"limit_cone a \\<pi>\" \n    shows \"product_cone J C D a \\<pi>\"\n    proof -\n      interpret L: limit_cone J C D a \\<pi>\n        using assms by auto\n      show \"product_cone J C D a \\<pi>\" ..\n    qed\n\n  end\n\n  context category\n  begin\n\n    definition has_as_product\n    where \"has_as_product J D a \\<equiv> (\\<exists>\\<pi>. product_cone J C D a \\<pi>)\"\n\n    text\\<open>\n      A category has @{term I}-indexed products for an @{typ 'i}-set @{term I}\n      if every @{term I}-indexed discrete diagram has a product.\n      In order to reap the benefits of being able to directly identify the elements\n      of a set I with the objects of discrete category it generates (thereby avoiding\n      the use of coercion maps), it is necessary to assume that @{term \"I \\<noteq> UNIV\"}.\n      If we want to assert that a category has products indexed by the universe of\n      some type @{typ 'i}, we have to pass to a larger type, such as @{typ \"'i option\"}.\n\\<close>\n\n    definition has_products\n    where \"has_products (I :: 'i set) \\<equiv>\n             I \\<noteq> UNIV \\<and>\n             (\\<forall>J D. discrete_diagram J C D \\<and> Collect (partial_magma.arr J) = I\n                      \\<longrightarrow> (\\<exists>a. has_as_product J D a))\"\n\n    lemma ex_productE:\n    assumes \"\\<exists>a. has_as_product J D a\"\n    obtains a \\<pi> where \"product_cone J C D a \\<pi>\"\n      using assms has_as_product_def someI_ex [of \"\\<lambda>a. has_as_product J D a\"] by metis\n\n    lemma has_products_if_has_limits:\n    assumes \"has_limits (undefined :: 'j)\" and \"I \\<noteq> (UNIV :: 'j set)\"\n    shows \"has_products I\"\n    proof -\n      have \"\\<And>J D. \\<lbrakk> discrete_diagram J C D; Collect (partial_magma.arr J) = I \\<rbrakk>\n                   \\<Longrightarrow> (\\<exists>a. has_as_product J D a)\"\n      proof -\n        fix J :: \"'j comp\" and D\n        assume D: \"discrete_diagram J C D\"\n        interpret J: category J\n          using D discrete_diagram.axioms by auto\n        interpret D: discrete_diagram J C D\n          using D by auto\n        assume J: \"Collect J.arr = I\"\n        obtain a \\<pi> where \\<pi>: \"D.limit_cone a \\<pi>\"\n          using assms(1) J has_limits_def has_limits_of_shape_def [of J]\n                D.diagram_axioms J.category_axioms\n          by metis\n        have \"product_cone J C D a \\<pi>\"\n          using \\<pi> D.product_coneI by auto\n        hence \"has_as_product J D a\"\n          using has_as_product_def by blast\n        thus \"\\<exists>a. has_as_product J D a\"\n          by auto\n      qed\n      thus ?thesis\n        unfolding has_products_def using assms(2) by auto\n    qed\n\n  end\n\n  subsection \"Equalizers\"\n\n  text\\<open>\n    An \\emph{equalizer} in a category @{term C} is a limit of a parallel pair\n    of arrows in @{term C}.\n\\<close>\n\n  locale parallel_pair_diagram =\n    J: parallel_pair +\n    C: category C\n  for C :: \"'c comp\"      (infixr \"\\<cdot>\" 55)\n  and f0 :: 'c\n  and f1 :: 'c +\n  assumes is_parallel: \"C.par f0 f1\"\n  begin\n\n    no_notation J.comp   (infixr \"\\<cdot>\" 55)\n    notation J.comp      (infixr \"\\<cdot>\\<^sub>J\" 55)\n\n    definition map\n    where \"map \\<equiv> (\\<lambda>j. if j = J.Zero then C.dom f0\n                       else if j = J.One then C.cod f0\n                       else if j = J.j0 then f0\n                       else if j = J.j1 then f1\n                       else C.null)\"\n\n    lemma map_simp:\n    shows \"map J.Zero = C.dom f0\"\n    and \"map J.One = C.cod f0\"\n    and \"map J.j0 = f0\"\n    and \"map J.j1 = f1\"\n    proof -\n      show \"map J.Zero = C.dom f0\"\n        using map_def by metis\n      show \"map J.One = C.cod f0\"\n        using map_def J.Zero_not_eq_One by metis\n      show \"map J.j0 = f0\"\n        using map_def J.Zero_not_eq_j0 J.One_not_eq_j0 by metis\n      show \"map J.j1 = f1\"\n        using map_def J.Zero_not_eq_j1 J.One_not_eq_j1 J.j0_not_eq_j1 by metis\n    qed\n\n  end\n\n  sublocale parallel_pair_diagram \\<subseteq> diagram J.comp C map\n    apply unfold_locales\n        apply (simp add: J.arr_char map_def)\n    using map_def is_parallel J.arr_char J.cod_simp J.dom_simp\n       apply auto[2]\n  proof -\n    show 1: \"\\<And>j. J.arr j \\<Longrightarrow> C.cod (map j) = map (J.cod j)\"\n    proof -\n      fix j\n      assume j: \"J.arr j\"\n      show \"C.cod (map j) = map (J.cod j)\"\n      proof -\n        have \"j = J.Zero \\<or> j = J.One \\<Longrightarrow> ?thesis\" using is_parallel map_def by auto\n        moreover have \"j = J.j0 \\<or> j = J.j1 \\<Longrightarrow> ?thesis\"\n          using is_parallel map_def J.Zero_not_eq_j0 J.One_not_eq_j0 J.Zero_not_eq_One\n                J.Zero_not_eq_j1 J.One_not_eq_j1 J.Zero_not_eq_One J.cod_simp\n          by presburger\n        ultimately show ?thesis using j J.arr_char by fast\n      qed\n    qed\n    next\n    fix j j'\n    assume jj': \"J.seq j' j\"\n    show \"map (j' \\<cdot>\\<^sub>J j) = map j' \\<cdot> map j\"\n    proof -\n      have 1: \"(j = J.Zero \\<and> j' \\<noteq> J.One) \\<or> (j \\<noteq> J.Zero \\<and> j' = J.One)\"\n        using jj' J.seq_char by blast\n      moreover have \"j = J.Zero \\<and> j' \\<noteq> J.One \\<Longrightarrow> ?thesis\"\n        using jj' map_def is_parallel J.arr_char J.cod_simp J.dom_simp J.seq_char\n        by (metis (no_types, lifting) C.arr_dom_iff_arr C.comp_arr_dom C.dom_dom\n            J.comp_arr_dom)\n      moreover have \"j \\<noteq> J.Zero \\<and> j' = J.One \\<Longrightarrow> ?thesis\"\n        using jj' J.ide_char map_def J.Zero_not_eq_One is_parallel\n        by (metis (no_types, lifting) C.arr_cod_iff_arr C.comp_arr_dom C.comp_cod_arr\n            C.comp_ide_arr C.ext C.ide_cod J.comp_simp(2))\n      ultimately show ?thesis by blast\n    qed\n  qed\n\n  context parallel_pair_diagram\n  begin\n\n    definition mkCone\n    where \"mkCone e \\<equiv> \\<lambda>j. if J.arr j then if j = J.Zero then e else f0 \\<cdot> e else C.null\"\n\n    abbreviation is_equalized_by\n    where \"is_equalized_by e \\<equiv> C.seq f0 e \\<and> f0 \\<cdot> e = f1 \\<cdot> e\"\n\n    abbreviation has_as_equalizer\n    where \"has_as_equalizer e \\<equiv> limit_cone (C.dom e) (mkCone e)\"\n\n    lemma cone_mkCone:\n    assumes \"is_equalized_by e\"\n    shows \"cone (C.dom e) (mkCone e)\"\n    proof -\n      interpret E: constant_functor J.comp C \\<open>C.dom e\\<close>\n        apply unfold_locales using assms by auto\n      show \"cone (C.dom e) (mkCone e)\"\n        using assms mkCone_def apply unfold_locales\n            apply auto[2]\n        using C.dom_comp C.seqE C.cod_comp J.Zero_not_eq_One J.arr_char' J.cod_char map_def\n          apply (metis (no_types, lifting) C.not_arr_null parallel_pair.cod_simp(1) preserves_arr)\n      proof -\n        fix j\n        assume j: \"J.arr j\"\n        show \"map j \\<cdot> mkCone e (J.dom j) = mkCone e j\"\n        proof -\n          have 1: \"\\<forall>a. if a = J.Zero then map a = C.dom f0\n                        else if a = J.One then map a = C.cod f0\n                        else if a = J.j0 then map a = f0\n                        else if a = J.j1 then map a = f1\n                        else map a = C.null\"\n            using map_def by auto\n          hence 2: \"map j = f1 \\<or> j = J.One \\<or> j = J.Zero \\<or> j = J.j0\"\n            using j parallel_pair.arr_char by meson\n          have \"j = J.Zero \\<or> map j \\<cdot> mkCone e (J.dom j) = mkCone e j\"\n            using assms j 1 2 mkCone_def C.cod_comp\n            by (metis (no_types, lifting) C.comp_cod_arr J.arr_char J.dom_simp(2-4) is_parallel)\n          thus ?thesis\n            using assms 1 j\n            by (metis (no_types, lifting) C.comp_cod_arr C.seqE mkCone_def J.dom_simp(1))\n        qed\n        next\n        show \"\\<And>j. J.arr j \\<Longrightarrow> mkCone e (J.cod j) \\<cdot> E.map j = mkCone e j\"\n        proof -\n          fix j\n          assume j: \"J.arr j\"\n          have \"J.cod j = J.Zero \\<Longrightarrow> mkCone e (J.cod j) \\<cdot> E.map j = mkCone e j\"\n            unfolding mkCone_def\n            using assms j J.arr_char J.cod_char C.comp_arr_dom mkCone_def J.Zero_not_eq_One\n            by (metis (no_types, lifting) C.seqE E.map_simp)\n          moreover have \"J.cod j \\<noteq> J.Zero \\<Longrightarrow> mkCone e (J.cod j) \\<cdot> E.map j = mkCone e j\"\n            unfolding mkCone_def\n            using assms j C.comp_arr_dom by auto\n          ultimately show \"mkCone e (J.cod j) \\<cdot> E.map j = mkCone e j\" by blast\n        qed\n      qed\n    qed\n\n    lemma is_equalized_by_cone:\n    assumes \"cone a \\<chi>\"\n    shows \"is_equalized_by (\\<chi> (J.Zero))\"\n    proof -\n      interpret \\<chi>: cone J.comp C map a \\<chi>\n        using assms by auto\n      show ?thesis\n        using assms J.arr_char J.dom_char J.cod_char\n              J.One_not_eq_j0 J.One_not_eq_j1 J.Zero_not_eq_j0 J.Zero_not_eq_j1 J.j0_not_eq_j1\n        by (metis (no_types, lifting) Limit.cone_def \\<chi>.is_natural_1 \\<chi>.naturality\n            \\<chi>.preserves_reflects_arr constant_functor.map_simp map_simp(3) map_simp(4))\n    qed\n\n    lemma mkCone_cone:\n    assumes \"cone a \\<chi>\"\n    shows \"mkCone (\\<chi> J.Zero) = \\<chi>\"\n    proof -\n      interpret \\<chi>: cone J.comp C map a \\<chi>\n        using assms by auto\n      have 1: \"is_equalized_by (\\<chi> J.Zero)\"\n        using assms is_equalized_by_cone by blast\n      show ?thesis\n      proof\n        fix j\n        have \"j = J.Zero \\<Longrightarrow> mkCone (\\<chi> J.Zero) j = \\<chi> j\"\n          using mkCone_def \\<chi>.is_extensional by simp\n        moreover have \"j = J.One \\<or> j = J.j0 \\<or> j = J.j1 \\<Longrightarrow> mkCone (\\<chi> J.Zero) j = \\<chi> j\"\n          using J.arr_char J.cod_char J.dom_char J.seq_char mkCone_def\n                \\<chi>.is_natural_1 \\<chi>.is_natural_2 \\<chi>.A.map_simp map_def\n          by (metis (no_types, lifting) J.Zero_not_eq_j0 J.dom_simp(2))\n        ultimately have \"J.arr j \\<Longrightarrow> mkCone (\\<chi> J.Zero) j = \\<chi> j\"\n          using J.arr_char by auto\n        thus \"mkCone (\\<chi> J.Zero) j = \\<chi> j\"\n          using mkCone_def \\<chi>.is_extensional by fastforce\n      qed\n    qed\n\n  end\n\n  locale equalizer_cone =\n    J: parallel_pair +\n    C: category C +\n    D: parallel_pair_diagram C f0 f1 +\n    limit_cone J.comp C D.map \"C.dom e\" \"D.mkCone e\"\n  for C :: \"'c comp\"      (infixr \"\\<cdot>\" 55)\n  and f0 :: 'c\n  and f1 :: 'c\n  and e :: 'c\n  begin\n\n    lemma equalizes:\n    shows \"D.is_equalized_by e\"\n    proof\n      show 1: \"C.seq f0 e\"\n      proof (intro C.seqI)\n        show \"C.arr e\" using ide_apex C.arr_dom_iff_arr by fastforce\n        show \"C.arr f0\"\n          using D.map_simp D.preserves_arr J.arr_char by metis\n        show \"C.dom f0 = C.cod e\"\n          using J.arr_char J.ide_char D.mkCone_def D.map_simp preserves_cod [of J.Zero]\n          by auto\n      qed\n      hence 2: \"C.seq f1 e\"\n        using D.is_parallel by fastforce\n      show \"f0 \\<cdot> e = f1 \\<cdot> e\"\n        using D.map_simp D.mkCone_def J.arr_char naturality [of J.j0] naturality [of J.j1]\n        by force\n    qed\n\n    lemma is_universal':\n    assumes \"D.is_equalized_by e'\"\n    shows \"\\<exists>!h. \\<guillemotleft>h : C.dom e' \\<rightarrow> C.dom e\\<guillemotright> \\<and> e \\<cdot> h = e'\"\n    proof -\n      have \"D.cone (C.dom e') (D.mkCone e')\"\n        using assms D.cone_mkCone by blast\n      moreover have 0: \"D.cone (C.dom e) (D.mkCone e)\" ..\n      ultimately have 1: \"\\<exists>!h. \\<guillemotleft>h : C.dom e' \\<rightarrow> C.dom e\\<guillemotright> \\<and>\n                               D.cones_map h (D.mkCone e) = D.mkCone e'\"\n        using is_universal [of \"C.dom e'\" \"D.mkCone e'\"] by auto\n      have 2: \"\\<And>h. \\<guillemotleft>h : C.dom e' \\<rightarrow> C.dom e\\<guillemotright> \\<Longrightarrow>\n                    D.cones_map h (D.mkCone e) = D.mkCone e' \\<longleftrightarrow> e \\<cdot> h = e'\"\n      proof -\n        fix h\n        assume h: \"\\<guillemotleft>h : C.dom e' \\<rightarrow> C.dom e\\<guillemotright>\"\n        show \"D.cones_map h (D.mkCone e) = D.mkCone e' \\<longleftrightarrow> e \\<cdot> h = e'\"\n        proof\n          assume 3: \"D.cones_map h (D.mkCone e) = D.mkCone e'\"\n          show \"e \\<cdot> h = e'\"\n          proof -\n            have \"e' = D.mkCone e' J.Zero\"\n              using D.mkCone_def J.arr_char by simp\n            also have \"... = D.cones_map h (D.mkCone e) J.Zero\"\n              using 3 by simp\n            also have \"... = e \\<cdot> h\"\n              using 0 h D.mkCone_def J.arr_char by auto\n            finally show ?thesis by auto\n          qed\n          next\n          assume e': \"e \\<cdot> h = e'\"\n          show \"D.cones_map h (D.mkCone e) = D.mkCone e'\"\n          proof\n            fix j\n            have \"\\<not>J.arr j \\<Longrightarrow> D.cones_map h (D.mkCone e) j = D.mkCone e' j\"\n              using h cone_axioms D.mkCone_def by auto\n            moreover have \"j = J.Zero \\<Longrightarrow> D.cones_map h (D.mkCone e) j = D.mkCone e' j\"\n              using h e' cone_\\<chi> D.mkCone_def J.arr_char [of J.Zero] by force\n            moreover have\n                \"J.arr j \\<and> j \\<noteq> J.Zero \\<Longrightarrow> D.cones_map h (D.mkCone e) j = D.mkCone e' j\"\n            proof -\n              assume j: \"J.arr j \\<and> j \\<noteq> J.Zero\"\n              have \"D.cones_map h (D.mkCone e) j = C (D.mkCone e j) h\"\n                using j h equalizes D.mkCone_def D.cone_mkCone J.arr_char\n                      J.Zero_not_eq_One J.Zero_not_eq_j0 J.Zero_not_eq_j1\n                by auto\n              also have \"... = (f0 \\<cdot> e) \\<cdot> h\"\n                using j D.mkCone_def J.arr_char J.Zero_not_eq_One J.Zero_not_eq_j0\n                      J.Zero_not_eq_j1\n                by auto\n              also have \"... = f0 \\<cdot> e \\<cdot> h\"\n                using h equalizes C.comp_assoc by blast\n              also have \"... = D.mkCone e' j\"\n                using j e' h equalizes D.mkCone_def J.arr_char [of J.One] J.Zero_not_eq_One\n                by auto\n              finally show ?thesis by auto\n            qed\n            ultimately show \"D.cones_map h (D.mkCone e) j = D.mkCone e' j\" by blast\n          qed\n        qed\n      qed\n      thus ?thesis using 1 by blast\n    qed\n\n    lemma induced_arrowI':\n    assumes \"D.is_equalized_by e'\"\n    shows \"\\<guillemotleft>induced_arrow (C.dom e') (D.mkCone e') : C.dom e' \\<rightarrow> C.dom e\\<guillemotright>\"\n    and \"e \\<cdot> induced_arrow (C.dom e') (D.mkCone e') = e'\"\n    proof -\n      interpret A': constant_functor J.comp C \\<open>C.dom e'\\<close>\n        using assms by (unfold_locales, auto)\n      have cone: \"D.cone (C.dom e') (D.mkCone e')\"\n        using assms D.cone_mkCone [of e'] by blast\n      have \"e \\<cdot> induced_arrow (C.dom e') (D.mkCone e') =\n              D.cones_map (induced_arrow (C.dom e') (D.mkCone e')) (D.mkCone e) J.Zero\"\n        using cone induced_arrowI(1) D.mkCone_def J.arr_char cone_\\<chi> by force\n      also have \"... = e'\"\n      proof -\n        have\n            \"D.cones_map (induced_arrow (C.dom e') (D.mkCone e')) (D.mkCone e) = D.mkCone e'\"\n          using cone induced_arrowI by blast\n        thus ?thesis\n          using J.arr_char D.mkCone_def by simp\n      qed\n      finally have 1: \"e \\<cdot> induced_arrow (C.dom e') (D.mkCone e') = e'\"\n        by auto\n      show \"\\<guillemotleft>induced_arrow (C.dom e') (D.mkCone e') : C.dom e' \\<rightarrow> C.dom e\\<guillemotright>\"\n        using 1 cone induced_arrowI by simp\n      show \"e \\<cdot> induced_arrow (C.dom e') (D.mkCone e') = e'\"\n        using 1 cone induced_arrowI by simp\n    qed\n\n  end\n\n  context category\n  begin\n\n    definition has_as_equalizer\n    where \"has_as_equalizer f0 f1 e \\<equiv> par f0 f1 \\<and> parallel_pair_diagram.has_as_equalizer C f0 f1 e\"\n\n    definition has_equalizers\n    where \"has_equalizers = (\\<forall>f0 f1. par f0 f1 \\<longrightarrow> (\\<exists>e. has_as_equalizer f0 f1 e))\"\n\n  end\n\n  section \"Limits by Products and Equalizers\"\n \n  text\\<open>\n    A category with equalizers has limits of shape @{term J} if it has products\n    indexed by the set of arrows of @{term J} and the set of objects of @{term J}.\n    The proof is patterned after \\cite{MacLane}, Theorem 2, page 109:\n    \\begin{quotation}\n       ``The limit of \\<open>F: J \\<rightarrow> C\\<close> is the equalizer \\<open>e\\<close>\n       of \\<open>f, g: \\<Pi>\\<^sub>i F\\<^sub>i \\<rightarrow> \\<Pi>\\<^sub>u F\\<^sub>c\\<^sub>o\\<^sub>d \\<^sub>u (u \\<in> arr J, i \\<in> J)\\<close>\n       where \\<open>p\\<^sub>u f = p\\<^sub>c\\<^sub>o\\<^sub>d \\<^sub>u\\<close>, \\<open>p\\<^sub>u g = F\\<^sub>u o p\\<^sub>d\\<^sub>o\\<^sub>m \\<^sub>u\\<close>;\n       the limiting cone \\<open>\\<mu>\\<close> is \\<open>\\<mu>\\<^sub>j = p\\<^sub>j e\\<close>, for \\<open>j \\<in> J\\<close>.''\n    \\end{quotation}\n\\<close>\n\n  locale category_with_equalizers =\n    category C\n  for C :: \"'c comp\"      (infixr \"\\<cdot>\" 55) +\n  assumes has_equalizers: \"has_equalizers\"\n  begin\n\n    lemma has_limits_if_has_products:\n    fixes J :: \"'j comp\"  (infixr \"\\<cdot>\\<^sub>J\" 55)\n    assumes \"category J\" and \"has_products (Collect (partial_magma.ide J))\"\n    and \"has_products (Collect (partial_magma.arr J))\"\n    shows \"has_limits_of_shape J\"\n    proof (unfold has_limits_of_shape_def)\n      interpret J: category J using assms(1) by auto\n      have \"\\<And>D. diagram J C D \\<Longrightarrow> (\\<exists>a \\<chi>. limit_cone J C D a \\<chi>)\"\n      proof -\n        fix D\n        assume D: \"diagram J C D\"\n        interpret D: diagram J C D using D by auto\n\n        text\\<open>\n          First, construct the two required products and their cones.\n\\<close>\n        interpret Obj: discrete_category \\<open>Collect J.ide\\<close> J.null\n          using J.not_arr_null J.ideD(1) mem_Collect_eq by (unfold_locales, blast)\n        interpret \\<Delta>o: discrete_diagram_from_map \\<open>Collect J.ide\\<close> C D J.null\n          using D.preserves_ide by (unfold_locales, auto)\n        have \"\\<exists>p. has_as_product Obj.comp \\<Delta>o.map p\"\n          using assms(2) \\<Delta>o.diagram_axioms has_products_def Obj.arr_char\n          by (metis (no_types, lifting) Collect_cong \\<Delta>o.discrete_diagram_axioms mem_Collect_eq)\n        from this obtain \\<Pi>o \\<pi>o where \\<pi>o: \"product_cone Obj.comp C \\<Delta>o.map \\<Pi>o \\<pi>o\"\n           using ex_productE [of Obj.comp \\<Delta>o.map] by auto\n        interpret \\<pi>o: product_cone Obj.comp C \\<Delta>o.map \\<Pi>o \\<pi>o using \\<pi>o by auto\n        have \\<pi>o_in_hom: \"\\<And>j. Obj.arr j \\<Longrightarrow> \\<guillemotleft>\\<pi>o j : \\<Pi>o \\<rightarrow> D j\\<guillemotright>\"\n          using \\<pi>o.preserves_dom \\<pi>o.preserves_cod \\<Delta>o.map_def by auto\n\n        interpret Arr: discrete_category \\<open>Collect J.arr\\<close> J.null\n          using J.not_arr_null by (unfold_locales, blast)\n        interpret \\<Delta>a: discrete_diagram_from_map \\<open>Collect J.arr\\<close> C \\<open>D o J.cod\\<close> J.null\n          by (unfold_locales, auto)\n        have \"\\<exists>p. has_as_product Arr.comp \\<Delta>a.map p\"\n          using assms(3) has_products_def [of \"Collect J.arr\"] \\<Delta>a.discrete_diagram_axioms\n          by blast\n        from this obtain \\<Pi>a \\<pi>a where \\<pi>a: \"product_cone Arr.comp C \\<Delta>a.map \\<Pi>a \\<pi>a\"\n          using ex_productE [of Arr.comp \\<Delta>a.map] by auto\n        interpret \\<pi>a: product_cone Arr.comp C \\<Delta>a.map \\<Pi>a \\<pi>a using \\<pi>a by auto\n        have \\<pi>a_in_hom: \"\\<And>j. Arr.arr j \\<Longrightarrow> \\<guillemotleft>\\<pi>a j : \\<Pi>a \\<rightarrow> D (J.cod j)\\<guillemotright>\"\n          using \\<pi>a.preserves_cod \\<pi>a.preserves_dom \\<Delta>a.map_def by auto\n\n        text\\<open>\n           Next, construct a parallel pair of arrows \\<open>f, g: \\<Pi>o \\<rightarrow> \\<Pi>a\\<close>\n           that expresses the commutativity constraints imposed by the diagram.\n\\<close>\n        interpret \\<Pi>o: constant_functor Arr.comp C \\<Pi>o\n          using \\<pi>o.ide_apex by (unfold_locales, auto)\n        let ?\\<chi> = \"\\<lambda>j. if Arr.arr j then \\<pi>o (J.cod j) else null\"\n        interpret \\<chi>: cone Arr.comp C \\<Delta>a.map \\<Pi>o ?\\<chi>\n          using \\<pi>o.ide_apex \\<pi>o_in_hom \\<Delta>a.map_def \\<Delta>o.map_def \\<Delta>o.is_discrete \\<pi>o.is_natural_2\n                comp_cod_arr\n          by (unfold_locales, auto)\n\n        let ?f = \"\\<pi>a.induced_arrow \\<Pi>o ?\\<chi>\"\n        have f_in_hom: \"\\<guillemotleft>?f : \\<Pi>o \\<rightarrow> \\<Pi>a\\<guillemotright>\"\n          using \\<chi>.cone_axioms \\<pi>a.induced_arrowI by blast\n        have f_map: \"\\<Delta>a.cones_map ?f \\<pi>a = ?\\<chi>\"\n          using \\<chi>.cone_axioms \\<pi>a.induced_arrowI by blast\n        have ff: \"\\<And>j. J.arr j \\<Longrightarrow> \\<pi>a j \\<cdot> ?f = \\<pi>o (J.cod j)\"\n        proof -\n          fix j\n          assume j: \"J.arr j\"\n          have \"\\<pi>a j \\<cdot> ?f = \\<Delta>a.cones_map ?f \\<pi>a j\"\n            using f_in_hom \\<pi>a.is_cone \\<pi>a.is_extensional by auto\n          also have \"... = \\<pi>o (J.cod j)\"\n            using j f_map by fastforce\n          finally show \"\\<pi>a j \\<cdot> ?f = \\<pi>o (J.cod j)\" by auto\n        qed\n\n        let ?\\<chi>' = \"\\<lambda>j. if Arr.arr j then D j \\<cdot> \\<pi>o (J.dom j) else null\"\n        interpret \\<chi>': cone Arr.comp C \\<Delta>a.map \\<Pi>o ?\\<chi>'\n          using \\<pi>o.ide_apex \\<pi>o_in_hom \\<Delta>o.map_def \\<Delta>a.map_def comp_arr_dom comp_cod_arr\n          by (unfold_locales, auto)\n        let ?g = \"\\<pi>a.induced_arrow \\<Pi>o ?\\<chi>'\"\n        have g_in_hom: \"\\<guillemotleft>?g : \\<Pi>o \\<rightarrow> \\<Pi>a\\<guillemotright>\"\n          using \\<chi>'.cone_axioms \\<pi>a.induced_arrowI by blast\n        have g_map: \"\\<Delta>a.cones_map ?g \\<pi>a = ?\\<chi>'\"\n          using \\<chi>'.cone_axioms \\<pi>a.induced_arrowI by blast\n        have gg: \"\\<And>j. J.arr j \\<Longrightarrow> \\<pi>a j \\<cdot> ?g = D j \\<cdot> \\<pi>o (J.dom j)\"\n        proof -\n          fix j\n          assume j: \"J.arr j\"\n          have \"\\<pi>a j \\<cdot> ?g = \\<Delta>a.cones_map ?g \\<pi>a j\"\n            using g_in_hom \\<pi>a.is_cone \\<pi>a.is_extensional by force\n          also have \"... = D j \\<cdot> \\<pi>o (J.dom j)\"\n            using j g_map by fastforce\n          finally show \"\\<pi>a j \\<cdot> ?g = D j \\<cdot> \\<pi>o (J.dom j)\" by auto\n        qed\n\n        interpret PP: parallel_pair_diagram C ?f ?g\n          using f_in_hom g_in_hom\n          by (elim in_homE, unfold_locales, auto)\n\n        from PP.is_parallel obtain e where equ: \"PP.has_as_equalizer e\"\n          using has_equalizers has_equalizers_def has_as_equalizer_def by blast\n        interpret EQU: limit_cone PP.J.comp C PP.map \\<open>dom e\\<close> \\<open>PP.mkCone e\\<close>\n          using equ by auto\n        interpret EQU: equalizer_cone C ?f ?g e ..\n\n        text\\<open>\n          An arrow @{term h} with @{term \"cod h = \\<Pi>o\"} equalizes @{term f} and @{term g}\n          if and only if it satisfies the commutativity condition required for a cone over\n          @{term D}.\n\\<close>\n        have E: \"\\<And>h. \\<guillemotleft>h : dom h \\<rightarrow> \\<Pi>o\\<guillemotright> \\<Longrightarrow>\n                   ?f \\<cdot> h = ?g \\<cdot> h \\<longleftrightarrow> (\\<forall>j. J.arr j \\<longrightarrow> ?\\<chi> j \\<cdot> h = ?\\<chi>' j \\<cdot> h)\"\n        proof\n          fix h\n          assume h: \"\\<guillemotleft>h : dom h \\<rightarrow> \\<Pi>o\\<guillemotright>\"\n          show \"?f \\<cdot> h = ?g \\<cdot> h \\<Longrightarrow> \\<forall>j. J.arr j \\<longrightarrow> ?\\<chi> j \\<cdot> h = ?\\<chi>' j \\<cdot> h\"\n          proof -\n            assume E: \"?f \\<cdot> h = ?g \\<cdot> h\"\n            have \"\\<And>j. J.arr j \\<Longrightarrow> ?\\<chi> j \\<cdot> h = ?\\<chi>' j \\<cdot> h\"\n            proof -\n              fix j\n              assume j: \"J.arr j\"\n              have \"?\\<chi> j \\<cdot> h = \\<Delta>a.cones_map ?f \\<pi>a j \\<cdot> h\"\n                using j f_map by fastforce\n              also have \"... = \\<pi>a j \\<cdot> ?f \\<cdot> h\"\n                using j f_in_hom \\<Delta>a.map_def \\<pi>a.cone_\\<chi> comp_assoc by auto\n              also have \"... = \\<pi>a j \\<cdot> ?g \\<cdot> h\"\n                using j E by simp\n              also have \"... = \\<Delta>a.cones_map ?g \\<pi>a j \\<cdot> h\"\n                using j g_in_hom \\<Delta>a.map_def \\<pi>a.cone_\\<chi> comp_assoc by auto\n              also have \"... = ?\\<chi>' j \\<cdot> h\"\n                using j g_map by force\n              finally show \"?\\<chi> j \\<cdot> h = ?\\<chi>' j \\<cdot> h\" by auto\n            qed\n            thus \"\\<forall>j. J.arr j \\<longrightarrow> ?\\<chi> j \\<cdot> h = ?\\<chi>' j \\<cdot> h\" by blast\n          qed\n          show \"\\<forall>j. J.arr j \\<longrightarrow> ?\\<chi> j \\<cdot> h = ?\\<chi>' j \\<cdot> h \\<Longrightarrow> ?f \\<cdot> h = ?g \\<cdot> h\"\n          proof -\n            assume 1: \"\\<forall>j. J.arr j \\<longrightarrow> ?\\<chi> j \\<cdot> h = ?\\<chi>' j \\<cdot> h\"\n            have 2: \"\\<And>j. j \\<in> Collect J.arr \\<Longrightarrow> \\<pi>a j \\<cdot> ?f \\<cdot> h = \\<pi>a j \\<cdot> ?g \\<cdot> h\"\n            proof -\n              fix j\n              assume j: \"j \\<in> Collect J.arr\"\n              have \"\\<pi>a j \\<cdot> ?f \\<cdot> h = (\\<pi>a j \\<cdot> ?f) \\<cdot> h\"\n                using comp_assoc by simp\n              also have \"... = ?\\<chi> j \\<cdot> h\"\n              proof -\n                have \"\\<pi>a j \\<cdot> ?f = \\<Delta>a.cones_map ?f \\<pi>a j\"\n                  using j f_in_hom \\<pi>a.cone_axioms \\<Delta>a.map_def \\<pi>a.cone_\\<chi> by auto\n                thus ?thesis using f_map by fastforce\n              qed\n              also have \"... = ?\\<chi>' j \\<cdot> h\"\n                using 1 j by auto\n              also have \"... = (\\<pi>a j \\<cdot> ?g) \\<cdot> h\"\n              proof -\n                have \"\\<pi>a j \\<cdot> ?g = \\<Delta>a.cones_map ?g \\<pi>a j\"\n                  using j g_in_hom \\<pi>a.cone_axioms \\<Delta>a.map_def \\<pi>a.cone_\\<chi> by auto\n                thus ?thesis using g_map by simp\n              qed\n              also have \"... = \\<pi>a j \\<cdot> ?g \\<cdot> h\"\n                using comp_assoc by simp\n              finally show \"\\<pi>a j \\<cdot> ?f \\<cdot> h = \\<pi>a j \\<cdot> ?g \\<cdot> h\"\n                by auto\n            qed\n            show \"C ?f h = C ?g h\"\n            proof -\n              have \"\\<And>j. Arr.arr j \\<Longrightarrow> \\<guillemotleft>\\<pi>a j \\<cdot> ?f \\<cdot> h : dom h \\<rightarrow> \\<Delta>a.map j\\<guillemotright>\"\n                using f_in_hom h \\<pi>a_in_hom by (elim in_homE, auto)\n              hence 3: \"\\<exists>!k. \\<guillemotleft>k : dom h \\<rightarrow> \\<Pi>a\\<guillemotright> \\<and> (\\<forall>j. Arr.arr j \\<longrightarrow> \\<pi>a j \\<cdot> k = \\<pi>a j \\<cdot> ?f \\<cdot> h)\"\n                using h \\<pi>a \\<pi>a.is_universal' [of \"dom h\" \"\\<lambda>j. \\<pi>a j \\<cdot> ?f \\<cdot> h\"] \\<Delta>a.map_def\n                      ide_dom [of h]\n                by blast\n              have 4: \"\\<And>P x x'. \\<exists>!k. P k x \\<Longrightarrow> P x x \\<Longrightarrow> P x' x \\<Longrightarrow> x' = x\" by auto\n              let ?P = \"\\<lambda> k x. \\<guillemotleft>k : dom h \\<rightarrow> \\<Pi>a\\<guillemotright> \\<and>\n                               (\\<forall>j. j \\<in> Collect J.arr \\<longrightarrow> \\<pi>a j \\<cdot> k = \\<pi>a j \\<cdot> x)\"\n              have \"?P (?g \\<cdot> h) (?g \\<cdot> h)\"\n                using g_in_hom h by force\n              moreover have \"?P (?f \\<cdot> h) (?g \\<cdot> h)\"\n                using 2 f_in_hom g_in_hom h by force\n              ultimately show ?thesis\n                using 3 4 [of ?P \"?f \\<cdot> h\" \"?g \\<cdot> h\"] by auto\n            qed\n          qed\n        qed\n        have E': \"\\<And>e. \\<guillemotleft>e : dom e \\<rightarrow> \\<Pi>o\\<guillemotright> \\<Longrightarrow>\n                   ?f \\<cdot> e = ?g \\<cdot> e \\<longleftrightarrow>\n                   (\\<forall>j. J.arr j \\<longrightarrow>\n                           (D (J.cod j) \\<cdot> \\<pi>o (J.cod j) \\<cdot> e) \\<cdot> dom e = D j \\<cdot> \\<pi>o (J.dom j) \\<cdot> e)\"\n        proof -\n          have 1: \"\\<And>e j. \\<guillemotleft>e : dom e \\<rightarrow> \\<Pi>o\\<guillemotright> \\<Longrightarrow> J.arr j \\<Longrightarrow>\n                          ?\\<chi> j \\<cdot> e = (D (J.cod j) \\<cdot> \\<pi>o (J.cod j) \\<cdot> e) \\<cdot> dom e\"\n          proof -\n            fix e j\n            assume e: \"\\<guillemotleft>e : dom e \\<rightarrow> \\<Pi>o\\<guillemotright>\"\n            assume j: \"J.arr j\"\n            have \"\\<guillemotleft>\\<pi>o (J.cod j) \\<cdot> e : dom e \\<rightarrow> D (J.cod j)\\<guillemotright>\"\n              using e j \\<pi>o_in_hom by auto\n            thus \"?\\<chi> j \\<cdot> e = (D (J.cod j) \\<cdot> \\<pi>o (J.cod j) \\<cdot> e) \\<cdot> dom e\"\n              using j comp_arr_dom comp_cod_arr by (elim in_homE, auto)\n          qed\n          have 2: \"\\<And>e j. \\<guillemotleft>e : dom e \\<rightarrow> \\<Pi>o\\<guillemotright> \\<Longrightarrow> J.arr j \\<Longrightarrow> ?\\<chi>' j \\<cdot> e = D j \\<cdot> \\<pi>o (J.dom j) \\<cdot> e\"\n          proof -\n            fix e j\n            assume e: \"\\<guillemotleft>e : dom e \\<rightarrow> \\<Pi>o\\<guillemotright>\"\n            assume j: \"J.arr j\"\n            show \"?\\<chi>' j \\<cdot> e = D j \\<cdot> \\<pi>o (J.dom j) \\<cdot> e\"\n              using j comp_assoc by fastforce\n          qed\n          show \"\\<And>e. \\<guillemotleft>e : dom e \\<rightarrow> \\<Pi>o\\<guillemotright> \\<Longrightarrow>\n                   ?f \\<cdot> e = ?g \\<cdot> e \\<longleftrightarrow>\n                     (\\<forall>j. J.arr j \\<longrightarrow>\n                           (D (J.cod j) \\<cdot> \\<pi>o (J.cod j) \\<cdot> e) \\<cdot> dom e = D j \\<cdot> \\<pi>o (J.dom j) \\<cdot> e)\"\n            using 1 2 E by presburger\n        qed\n        text\\<open>\n          The composites of @{term e} with the projections from the product @{term \\<Pi>o}\n          determine a limit cone @{term \\<mu>} for @{term D}.  The component of @{term \\<mu>}\n          at an object @{term j} of @{term[source=true] J} is the composite @{term \"C (\\<pi>o j) e\"}.\n          However, we need to extend @{term \\<mu>} to all arrows @{term j} of @{term[source=true] J},\n          so the correct definition is @{term \"\\<mu> j = C (D j) (C (\\<pi>o (J.dom j)) e)\"}.\n\\<close>\n        have e_in_hom: \"\\<guillemotleft>e : dom e \\<rightarrow> \\<Pi>o\\<guillemotright>\"\n          using EQU.equalizes f_in_hom in_homI\n          by (metis (no_types, lifting) seqE in_homE)\n        have e_map: \"C ?f e = C ?g e\"\n          using EQU.equalizes f_in_hom in_homI by fastforce\n        interpret domE: constant_functor J C \\<open>dom e\\<close>\n          using e_in_hom by (unfold_locales, auto)\n        let ?\\<mu> = \"\\<lambda>j. if J.arr j then D j \\<cdot> \\<pi>o (J.dom j) \\<cdot> e else null\"\n        have \\<mu>: \"\\<And>j. J.arr j \\<Longrightarrow> \\<guillemotleft>?\\<mu> j : dom e \\<rightarrow> D (J.cod j)\\<guillemotright>\"\n        proof -\n          fix j\n          assume j: \"J.arr j\"\n          show \"\\<guillemotleft>?\\<mu> j : dom e \\<rightarrow> D (J.cod j)\\<guillemotright>\"\n            using j e_in_hom \\<pi>o_in_hom [of \"J.dom j\"] by auto\n        qed\n        interpret \\<mu>: cone J C D \\<open>dom e\\<close> ?\\<mu>\n          apply unfold_locales\n              apply simp\n        proof -\n          fix j\n          assume j: \"J.arr j\"\n          show \"dom (?\\<mu> j) = domE.map (J.dom j)\" using j \\<mu> domE.map_simp by force\n          show \"cod (?\\<mu> j) = D (J.cod j)\" using j \\<mu> D.preserves_cod by blast\n          show \"D j \\<cdot> ?\\<mu> (J.dom j) = ?\\<mu> j\"\n            using j \\<mu> [of \"J.dom j\"] comp_cod_arr apply simp\n            by (elim in_homE, auto)\n          show \"?\\<mu> (J.cod j) \\<cdot> domE.map j = ?\\<mu> j\"\n            using j e_map E' by (simp add: e_in_hom)\n        qed\n        text\\<open>\n          If @{term \\<tau>} is any cone over @{term D} then @{term \\<tau>} restricts to a cone over\n          @{term \\<Delta>o} for which the induced arrow to @{term \\<Pi>o} equalizes @{term f} and @{term g}.\n\\<close>\n        have R: \"\\<And>a \\<tau>. cone J C D a \\<tau> \\<Longrightarrow>\n                        cone Obj.comp C \\<Delta>o.map a (\\<Delta>o.mkCone \\<tau>) \\<and>\n                        ?f \\<cdot> \\<pi>o.induced_arrow a (\\<Delta>o.mkCone \\<tau>)\n                           = ?g \\<cdot> \\<pi>o.induced_arrow a (\\<Delta>o.mkCone \\<tau>)\"\n        proof -\n          fix a \\<tau>\n          assume cone_\\<tau>: \"cone J C D a \\<tau>\"\n          interpret \\<tau>: cone J C D a \\<tau> using cone_\\<tau> by auto\n          interpret A: constant_functor Obj.comp C a\n            using \\<tau>.ide_apex by (unfold_locales, auto)\n          interpret \\<tau>o: cone Obj.comp C \\<Delta>o.map a \\<open>\\<Delta>o.mkCone \\<tau>\\<close>\n            using A.value_is_ide \\<Delta>o.map_def comp_cod_arr comp_arr_dom\n            by (unfold_locales, auto)\n          let ?e = \"\\<pi>o.induced_arrow a (\\<Delta>o.mkCone \\<tau>)\"\n          have mkCone_\\<tau>: \"\\<Delta>o.mkCone \\<tau> \\<in> \\<Delta>o.cones a\"\n          proof -\n            have \"\\<And>j. Obj.arr j \\<Longrightarrow> \\<guillemotleft>\\<tau> j : a \\<rightarrow> \\<Delta>o.map j\\<guillemotright>\"\n              using Obj.arr_char \\<tau>.A.map_def \\<Delta>o.map_def by force\n            thus ?thesis\n              using \\<tau>.ide_apex \\<Delta>o.cone_mkCone by simp\n          qed\n          have e: \"\\<guillemotleft>?e : a \\<rightarrow> \\<Pi>o\\<guillemotright>\"\n            using mkCone_\\<tau> \\<pi>o.induced_arrowI by simp\n          have ee: \"\\<And>j. J.ide j \\<Longrightarrow> \\<pi>o j \\<cdot> ?e = \\<tau> j\"\n          proof -\n            fix j\n            assume j: \"J.ide j\"\n            have \"\\<pi>o j \\<cdot> ?e = \\<Delta>o.cones_map ?e \\<pi>o j\"\n              using j e \\<pi>o.cone_axioms by force\n            also have \"... = \\<Delta>o.mkCone \\<tau> j\"\n              using j mkCone_\\<tau> \\<pi>o.induced_arrowI [of \"\\<Delta>o.mkCone \\<tau>\" a] by fastforce\n            also have \"... = \\<tau> j\"\n              using j by simp\n            finally show \"\\<pi>o j \\<cdot> ?e = \\<tau> j\" by auto\n          qed\n          have \"\\<And>j. J.arr j \\<Longrightarrow>\n                      (D (J.cod j) \\<cdot> \\<pi>o (J.cod j) \\<cdot> ?e) \\<cdot> dom ?e = D j \\<cdot> \\<pi>o (J.dom j) \\<cdot> ?e\"\n          proof -\n            fix j\n            assume j: \"J.arr j\"\n            have 1: \"\\<guillemotleft>\\<pi>o (J.cod j) : \\<Pi>o \\<rightarrow> D (J.cod j)\\<guillemotright>\" using j \\<pi>o_in_hom by simp\n            have 2: \"(D (J.cod j) \\<cdot> \\<pi>o (J.cod j) \\<cdot> ?e) \\<cdot> dom ?e\n                        = D (J.cod j) \\<cdot> \\<pi>o (J.cod j) \\<cdot> ?e\"\n            proof -\n              have \"seq (D (J.cod j)) (\\<pi>o (J.cod j))\"\n                using j 1 by auto\n              moreover have \"seq (\\<pi>o (J.cod j)) ?e\"\n                using j e by fastforce\n              ultimately show ?thesis using comp_arr_dom by auto\n            qed\n            also have 3: \"... = \\<pi>o (J.cod j) \\<cdot> ?e\"\n              using j e 1 comp_cod_arr by (elim in_homE, auto)\n            also have \"... = D j \\<cdot> \\<pi>o (J.dom j) \\<cdot> ?e\"\n              using j e ee 2 3 \\<tau>.naturality \\<tau>.A.map_simp \\<tau>.ide_apex comp_cod_arr by auto\n            finally show \"(D (J.cod j) \\<cdot> \\<pi>o (J.cod j) \\<cdot> ?e) \\<cdot> dom ?e = D j \\<cdot> \\<pi>o (J.dom j) \\<cdot> ?e\"\n              by auto\n          qed\n          hence \"C ?f ?e = C ?g ?e\"\n            using E' \\<pi>o.induced_arrowI \\<tau>o.cone_axioms mem_Collect_eq by blast\n          thus \"cone Obj.comp C \\<Delta>o.map a (\\<Delta>o.mkCone \\<tau>) \\<and> C ?f ?e = C ?g ?e\"\n            using \\<tau>o.cone_axioms by auto\n        qed\n        text\\<open>\n          Finally, show that @{term \\<mu>} is a limit cone.\n\\<close>\n        interpret \\<mu>: limit_cone J C D \\<open>dom e\\<close> ?\\<mu>\n        proof\n          fix a \\<tau>\n          assume cone_\\<tau>: \"cone J C D a \\<tau>\"\n          interpret \\<tau>: cone J C D a \\<tau> using cone_\\<tau> by auto\n          interpret A: constant_functor Obj.comp C a\n            apply unfold_locales using \\<tau>.ide_apex by auto\n          have cone_\\<tau>o: \"cone Obj.comp C \\<Delta>o.map a (\\<Delta>o.mkCone \\<tau>)\"\n            using A.value_is_ide \\<Delta>o.map_def D.preserves_ide comp_cod_arr comp_arr_dom\n                  \\<tau>.preserves_hom\n            by (unfold_locales, auto)\n          show \"\\<exists>!h. \\<guillemotleft>h : a \\<rightarrow> dom e\\<guillemotright> \\<and> D.cones_map h ?\\<mu> = \\<tau>\"\n          proof\n            let ?e' = \"\\<pi>o.induced_arrow a (\\<Delta>o.mkCone \\<tau>)\"\n            have e'_in_hom: \"\\<guillemotleft>?e' : a \\<rightarrow> \\<Pi>o\\<guillemotright>\"\n              using cone_\\<tau> R \\<pi>o.induced_arrowI by auto\n            have e'_map: \"?f \\<cdot> ?e' = ?g \\<cdot> ?e' \\<and> \\<Delta>o.cones_map ?e' \\<pi>o = \\<Delta>o.mkCone \\<tau>\"\n              using cone_\\<tau> R \\<pi>o.induced_arrowI [of \"\\<Delta>o.mkCone \\<tau>\" a] by auto\n            have equ: \"PP.is_equalized_by ?e'\"\n              using e'_map e'_in_hom f_in_hom seqI' by blast\n            let ?h = \"EQU.induced_arrow a (PP.mkCone ?e')\"\n            have h_in_hom: \"\\<guillemotleft>?h : a \\<rightarrow> dom e\\<guillemotright>\"\n              using EQU.induced_arrowI PP.cone_mkCone [of ?e'] e'_in_hom equ by fastforce\n            have h_map: \"PP.cones_map ?h (PP.mkCone e) = PP.mkCone ?e'\"\n              using EQU.induced_arrowI [of \"PP.mkCone ?e'\" a] PP.cone_mkCone [of ?e']\n                    e'_in_hom equ\n              by fastforce\n            have 3: \"D.cones_map ?h ?\\<mu> = \\<tau>\"\n            proof\n              fix j\n              have \"\\<not>J.arr j \\<Longrightarrow> D.cones_map ?h ?\\<mu> j = \\<tau> j\"\n                using h_in_hom \\<mu>.cone_axioms cone_\\<tau> \\<tau>.is_extensional by force\n              moreover have \"J.arr j \\<Longrightarrow> D.cones_map ?h ?\\<mu> j = \\<tau> j\"\n              proof -\n                fix j\n                assume j: \"J.arr j\"\n                have 1: \"\\<guillemotleft>\\<pi>o (J.dom j) \\<cdot> e : dom e \\<rightarrow> D (J.dom j)\\<guillemotright>\"\n                  using j e_in_hom \\<pi>o_in_hom [of \"J.dom j\"] by auto\n                have \"D.cones_map ?h ?\\<mu> j = ?\\<mu> j \\<cdot> ?h\"\n                  using h_in_hom j \\<mu>.cone_axioms by auto\n                also have \"... = D j \\<cdot> (\\<pi>o (J.dom j) \\<cdot> e) \\<cdot> ?h\"\n                  using j comp_assoc by simp\n                also have \"... = D j \\<cdot> \\<tau> (J.dom j)\"\n                proof -\n                  have \"(\\<pi>o (J.dom j) \\<cdot> e) \\<cdot> ?h = \\<tau> (J.dom j)\"\n                  proof -\n                    have \"(\\<pi>o (J.dom j) \\<cdot> e) \\<cdot> ?h = \\<pi>o (J.dom j) \\<cdot> e \\<cdot> ?h\"\n                      using j 1 e_in_hom h_in_hom \\<pi>o arrI comp_assoc by auto\n                    also have \"... = \\<pi>o (J.dom j) \\<cdot> ?e'\"\n                      using equ e'_in_hom EQU.induced_arrowI' [of ?e']\n                      by (elim in_homE, auto)\n                    also have \"... = \\<Delta>o.cones_map ?e' \\<pi>o (J.dom j)\"\n                      using j e'_in_hom \\<pi>o.cone_axioms by (elim in_homE, auto)\n                    also have \"... = \\<tau> (J.dom j)\"\n                      using j e'_map by simp\n                    finally show ?thesis by auto\n                  qed\n                  thus ?thesis by simp\n                qed\n                also have \"... = \\<tau> j\"\n                  using j \\<tau>.is_natural_1 by simp\n                finally show \"D.cones_map ?h ?\\<mu> j = \\<tau> j\" by auto\n              qed\n              ultimately show \"D.cones_map ?h ?\\<mu> j = \\<tau> j\" by auto\n            qed\n            show \"\\<guillemotleft>?h : a \\<rightarrow> dom e\\<guillemotright> \\<and> D.cones_map ?h ?\\<mu> = \\<tau>\"\n              using h_in_hom 3 by simp\n            show \"\\<And>h'. \\<guillemotleft>h' : a \\<rightarrow> dom e\\<guillemotright> \\<and> D.cones_map h' ?\\<mu> = \\<tau> \\<Longrightarrow> h' = ?h\"\n            proof -\n              fix h'\n              assume h': \"\\<guillemotleft>h' : a \\<rightarrow> dom e\\<guillemotright> \\<and> D.cones_map h' ?\\<mu> = \\<tau>\"\n              have h'_in_hom: \"\\<guillemotleft>h' : a \\<rightarrow> dom e\\<guillemotright>\" using h' by simp\n              have h'_map: \"D.cones_map h' ?\\<mu> = \\<tau>\" using h' by simp\n              show \"h' = ?h\"\n              proof -\n                have 1: \"\\<guillemotleft>e \\<cdot> h' : a \\<rightarrow> \\<Pi>o\\<guillemotright> \\<and> ?f \\<cdot> e \\<cdot> h' = ?g \\<cdot> e \\<cdot> h' \\<and>\n                         \\<Delta>o.cones_map (C e h') \\<pi>o = \\<Delta>o.mkCone \\<tau>\"\n                proof -\n                  have 2: \"\\<guillemotleft>e \\<cdot> h' : a \\<rightarrow> \\<Pi>o\\<guillemotright>\" using h'_in_hom e_in_hom by auto\n                  moreover have \"?f \\<cdot> e \\<cdot> h' = ?g \\<cdot> e \\<cdot> h'\"\n                  proof -\n                    have \"?f \\<cdot> e \\<cdot> h' = (?f \\<cdot> e) \\<cdot> h'\"\n                      using comp_assoc by auto\n                    also have \"... = ?g \\<cdot> e \\<cdot> h'\"\n                      using EQU.equalizes comp_assoc by auto\n                    finally show ?thesis by auto\n                  qed\n                  moreover have \"\\<Delta>o.cones_map (e \\<cdot> h') \\<pi>o = \\<Delta>o.mkCone \\<tau>\"\n                  proof\n                    have \"\\<Delta>o.cones_map (e \\<cdot> h') \\<pi>o = \\<Delta>o.cones_map h' (\\<Delta>o.cones_map e \\<pi>o)\"\n                      using \\<pi>o.cone_axioms e_in_hom h'_in_hom \\<Delta>o.cones_map_comp [of e h']\n                      by fastforce\n                    fix j\n                    have \"\\<not>Obj.arr j \\<Longrightarrow> \\<Delta>o.cones_map (e \\<cdot> h') \\<pi>o j = \\<Delta>o.mkCone \\<tau> j\"\n                      using 2 e_in_hom h'_in_hom \\<pi>o.cone_axioms by auto\n                    moreover have \"Obj.arr j \\<Longrightarrow> \\<Delta>o.cones_map (e \\<cdot> h') \\<pi>o j = \\<Delta>o.mkCone \\<tau> j\"\n                    proof -\n                      assume j: \"Obj.arr j\"\n                      have \"\\<Delta>o.cones_map (e \\<cdot> h') \\<pi>o j = \\<pi>o j \\<cdot> e \\<cdot> h'\"\n                        using 2 j \\<pi>o.cone_axioms by auto\n                      also have \"... = (\\<pi>o j \\<cdot> e) \\<cdot> h'\"\n                        using comp_assoc by auto\n                      also have \"... = \\<Delta>o.mkCone ?\\<mu> j \\<cdot> h'\"\n                        using j e_in_hom \\<pi>o_in_hom comp_ide_arr [of \"D j\" \"\\<pi>o j \\<cdot> e\"]\n                        by fastforce\n                      also have \"... = \\<Delta>o.mkCone \\<tau> j\"\n                        using j h' \\<mu>.cone_axioms mem_Collect_eq by auto\n                      finally show \"\\<Delta>o.cones_map (e \\<cdot> h') \\<pi>o j = \\<Delta>o.mkCone \\<tau> j\" by auto\n                    qed\n                    ultimately show \"\\<Delta>o.cones_map (e \\<cdot> h') \\<pi>o j = \\<Delta>o.mkCone \\<tau> j\" by auto\n                  qed\n                  ultimately show ?thesis by auto\n                qed\n                have \"\\<guillemotleft>e \\<cdot> h' : a \\<rightarrow> \\<Pi>o\\<guillemotright>\" using 1 by simp\n                moreover have \"e \\<cdot> h' = ?e'\"\n                  using 1 cone_\\<tau>o e'_in_hom e'_map \\<pi>o.is_universal \\<pi>o by blast\n                ultimately show \"h' = ?h\"\n                  using 1 h'_in_hom h'_map EQU.is_universal' [of \"e \\<cdot> h'\"]\n                        EQU.induced_arrowI' [of ?e'] equ\n                  by (elim in_homE, auto)\n              qed\n            qed\n          qed\n        qed\n        have \"limit_cone J C D (dom e) ?\\<mu>\" ..\n        thus \"\\<exists>a \\<mu>. limit_cone J C D a \\<mu>\" by auto\n      qed\n      thus \"\\<forall>D. diagram J C D \\<longrightarrow> (\\<exists>a \\<mu>. limit_cone J C D a \\<mu>)\" by blast\n    qed\n\n  end\n\n  section \"Limits in a Set Category\"\n\n  text\\<open>\n    In this section, we consider the special case of limits in a set category.\n\\<close>\n\n  locale diagram_in_set_category =\n    J: category J +\n    S: set_category S +\n    diagram J S D\n  for J :: \"'j comp\"      (infixr \"\\<cdot>\\<^sub>J\" 55)\n  and S :: \"'s comp\"      (infixr \"\\<cdot>\" 55)\n  and D :: \"'j \\<Rightarrow> 's\"\n  begin\n\n    notation S.in_hom (\"\\<guillemotleft>_ : _ \\<rightarrow> _\\<guillemotright>\")\n\n    text\\<open>\n      An object @{term a} of a set category @{term[source=true] S} is a limit of a diagram in\n      @{term[source=true] S} if and only if there is a bijection between the set\n      @{term \"S.hom S.unity a\"} of points of @{term a} and the set of cones over the diagram\n      that have apex @{term S.unity}.\n\\<close>\n\n    lemma limits_are_sets_of_cones:\n    shows \"has_as_limit a \\<longleftrightarrow> S.ide a \\<and> (\\<exists>\\<phi>. bij_betw \\<phi> (S.hom S.unity a) (cones S.unity))\"\n    proof\n      text\\<open>\n        If \\<open>has_limit a\\<close>, then by the universal property of the limit cone,\n        composition in @{term[source=true] S} yields a bijection between @{term \"S.hom S.unity a\"}\n        and @{term \"cones S.unity\"}.\n\\<close>\n      assume a: \"has_as_limit a\"\n      hence \"S.ide a\"\n        using limit_cone_def cone.ide_apex by metis\n      from a obtain \\<chi> where \\<chi>: \"limit_cone a \\<chi>\" by auto\n      interpret \\<chi>: limit_cone J S D a \\<chi> using \\<chi> by auto\n      have \"bij_betw (\\<lambda>f. cones_map f \\<chi>) (S.hom S.unity a) (cones S.unity)\"\n        using \\<chi>.bij_betw_hom_and_cones S.ide_unity by simp\n      thus \"S.ide a \\<and> (\\<exists>\\<phi>. bij_betw \\<phi> (S.hom S.unity a) (cones S.unity))\"\n        using \\<open>S.ide a\\<close> by blast\n      next\n      text\\<open>\n        Conversely, an arbitrary bijection @{term \\<phi>} between @{term \"S.hom S.unity a\"}\n        and cones unity extends pointwise to a natural bijection @{term \"\\<Phi> a'\"} between\n        @{term \"S.hom a' a\"} and @{term \"cones a'\"}, showing that @{term a} is a limit.\n\n        In more detail, the hypotheses give us a correspondence between points of @{term a}\n        and cones with apex @{term \"S.unity\"}.  We extend this to a correspondence between\n        functions to @{term a} and general cones, with each arrow from @{term a'} to @{term a}\n        determining a cone with apex @{term a'}.  If @{term \"f \\<in> hom a' a\"} then composition\n        with @{term f} takes each point @{term y} of @{term a'} to the point @{term \"S f y\"}\n        of @{term a}.  To this we may apply the given bijection @{term \\<phi>} to obtain\n        @{term \"\\<phi> (S f y) \\<in> cones S.unity\"}.  The component @{term \"\\<phi> (S f y) j\"} at @{term j}\n        of this cone is a point of @{term \"S.cod (D j)\"}.  Thus, @{term \"f \\<in> hom a' a\"} determines\n        a cone @{term \\<chi>f} with apex @{term a'} whose component at @{term j} is the\n        unique arrow @{term \"\\<chi>f j\"} of @{term[source=true] S} such that\n        @{term \"\\<chi>f j \\<in> hom a' (cod (D j))\"} and @{term \"S (\\<chi>f j) y = \\<phi> (S f y) j\"}\n        for all points @{term y} of @{term a'}.\n        The cone @{term \\<chi>a} corresponding to @{term \"a \\<in> S.hom a a\"} is then a limit cone.\n\\<close>\n      assume a: \"S.ide a \\<and> (\\<exists>\\<phi>. bij_betw \\<phi> (S.hom S.unity a) (cones S.unity))\"\n      hence ide_a: \"S.ide a\" by auto\n      show \"has_as_limit a\"\n      proof -\n        from a obtain \\<phi> where \\<phi>: \"bij_betw \\<phi> (S.hom S.unity a) (cones S.unity)\" by blast\n        have X: \"\\<And>f j y. \\<lbrakk> \\<guillemotleft>f : S.dom f \\<rightarrow> a\\<guillemotright>; J.arr j; \\<guillemotleft>y : S.unity \\<rightarrow> S.dom f\\<guillemotright> \\<rbrakk>\n                                \\<Longrightarrow> \\<guillemotleft>\\<phi> (f \\<cdot> y) j : S.unity \\<rightarrow> S.cod (D j)\\<guillemotright>\"\n        proof -\n          fix f j y\n          assume f: \"\\<guillemotleft>f : S.dom f \\<rightarrow> a\\<guillemotright>\" and j: \"J.arr j\" and y: \"\\<guillemotleft>y : S.unity \\<rightarrow> S.dom f\\<guillemotright>\"\n          interpret \\<chi>: cone J S D S.unity \\<open>\\<phi> (S f y)\\<close>\n            using f y \\<phi> bij_betw_imp_funcset funcset_mem by blast\n          show \"\\<guillemotleft>\\<phi> (f \\<cdot> y) j : S.unity \\<rightarrow> S.cod (D j)\\<guillemotright>\" using j by auto\n        qed\n        text\\<open>\n          We want to define the component @{term \"\\<chi>j \\<in> S.hom (S.dom f) (S.cod (D j))\"}\n          at @{term j} of a cone by specifying how it acts by composition on points\n          @{term \"y \\<in> S.hom S.unity (S.dom f)\"}.  We can do this because @{term[source=true] S}\n          is a set category.\n\\<close>\n        let ?P = \"\\<lambda>f j \\<chi>j. \\<guillemotleft>\\<chi>j : S.dom f \\<rightarrow> S.cod (D j)\\<guillemotright> \\<and>\n                           (\\<forall>y. \\<guillemotleft>y : S.unity \\<rightarrow> S.dom f\\<guillemotright> \\<longrightarrow> \\<chi>j \\<cdot> y = \\<phi> (f \\<cdot> y) j)\"\n        let ?\\<chi> = \"\\<lambda>f j. if J.arr j then (THE \\<chi>j. ?P f j \\<chi>j) else S.null\"\n        have \\<chi>: \"\\<And>f j. \\<lbrakk> \\<guillemotleft>f : S.dom f \\<rightarrow> a\\<guillemotright>; J.arr j \\<rbrakk> \\<Longrightarrow> ?P f j (?\\<chi> f j)\"\n        proof -\n          fix b f j\n          assume f: \"\\<guillemotleft>f : S.dom f \\<rightarrow> a\\<guillemotright>\" and j: \"J.arr j\"\n          interpret B: constant_functor J S \\<open>S.dom f\\<close>\n            using f by (unfold_locales, auto)\n          have \"(\\<lambda>y. \\<phi> (f \\<cdot> y) j) \\<in> S.hom S.unity (S.dom f) \\<rightarrow> S.hom S.unity (S.cod (D j))\"\n            using f j X Pi_I' by simp\n          hence \"\\<exists>!\\<chi>j. ?P f j \\<chi>j\"\n            using f j S.fun_complete' [of \"S.dom f\" \"S.cod (D j)\" \"\\<lambda>y. \\<phi> (f \\<cdot> y) j\"]\n            by (elim S.in_homE, auto)\n          thus \"?P f j (?\\<chi> f j)\" using j theI' [of \"?P f j\"] by simp\n        qed\n        text\\<open>\n          The arrows @{term \"\\<chi> f j\"} are in fact the components of a cone with apex\n          @{term \"S.dom f\"}.\n\\<close>\n        have cone: \"\\<And>f. \\<guillemotleft>f : S.dom f \\<rightarrow> a\\<guillemotright> \\<Longrightarrow> cone (S.dom f) (?\\<chi> f)\"\n        proof -\n          fix f\n          assume f: \"\\<guillemotleft>f : S.dom f \\<rightarrow> a\\<guillemotright>\"\n          interpret B: constant_functor J S \\<open>S.dom f\\<close>\n            using f by (unfold_locales, auto)\n          show \"cone (S.dom f) (?\\<chi> f)\"\n          proof\n            show \"\\<And>j. \\<not>J.arr j \\<Longrightarrow> ?\\<chi> f j = S.null\" by simp\n            fix j\n            assume j: \"J.arr j\"\n            have 0: \"\\<guillemotleft>?\\<chi> f j : S.dom f \\<rightarrow> S.cod (D j)\\<guillemotright>\" using f j \\<chi> by simp\n            show \"S.dom (?\\<chi> f j) = B.map (J.dom j)\" using f j \\<chi> by auto\n            show \"S.cod (?\\<chi> f j) = D (J.cod j)\" using f j \\<chi> by auto\n            have par1: \"S.par (D j \\<cdot> ?\\<chi> f (J.dom j)) (?\\<chi> f j)\"\n              using f j 0 \\<chi> [of f \"J.dom j\"] by (elim S.in_homE, auto)\n            have par2: \"S.par (?\\<chi> f (J.cod j) \\<cdot> B.map j) (?\\<chi> f j)\"\n              using f j 0 \\<chi> [of f \"J.cod j\"] by (elim S.in_homE, auto)\n            have nat: \"\\<And>y. \\<guillemotleft>y : S.unity \\<rightarrow> S.dom f\\<guillemotright> \\<Longrightarrow>\n                              (D j \\<cdot> ?\\<chi> f (J.dom j)) \\<cdot> y = ?\\<chi> f j \\<cdot> y \\<and>\n                              (?\\<chi> f (J.cod j) \\<cdot> B.map j) \\<cdot> y = ?\\<chi> f j \\<cdot> y\"\n            proof -\n              fix y\n              assume y: \"\\<guillemotleft>y : S.unity \\<rightarrow> S.dom f\\<guillemotright>\"\n              show \"(D j \\<cdot> ?\\<chi> f (J.dom j)) \\<cdot> y = ?\\<chi> f j \\<cdot> y \\<and>\n                    (?\\<chi> f (J.cod j) \\<cdot> B.map j) \\<cdot> y = ?\\<chi> f j \\<cdot> y\"\n              proof\n                have 1: \"\\<phi> (f \\<cdot> y) \\<in> cones S.unity\"\n                  using f y \\<phi> bij_betw_imp_funcset PiE\n                        S.seqI S.cod_comp S.dom_comp mem_Collect_eq\n                  by fastforce\n                interpret \\<chi>: cone J S D S.unity \\<open>\\<phi> (f \\<cdot> y)\\<close>\n                  using 1 by simp\n                have \"(D j \\<cdot> ?\\<chi> f (J.dom j)) \\<cdot> y = D j \\<cdot> ?\\<chi> f (J.dom j) \\<cdot> y\"\n                  using S.comp_assoc by simp\n                also have \"... = D j \\<cdot> \\<phi> (f \\<cdot> y) (J.dom j)\"\n                  using f y \\<chi> \\<chi>.is_extensional by simp\n                also have \"... = \\<phi> (f \\<cdot> y) j\" using j by auto\n                also have \"... = ?\\<chi> f j \\<cdot> y\"\n                  using f j y \\<chi> by force\n                finally show \"(D j \\<cdot> ?\\<chi> f (J.dom j)) \\<cdot> y = ?\\<chi> f j \\<cdot> y\" by auto\n                have \"(?\\<chi> f (J.cod j) \\<cdot> B.map j) \\<cdot> y = ?\\<chi> f (J.cod j) \\<cdot> y\"\n                  using j B.map_simp par2 B.value_is_ide S.comp_arr_ide\n                  by (metis (no_types, lifting))\n                also have \"... = \\<phi> (f \\<cdot> y) (J.cod j)\"\n                  using f y \\<chi> \\<chi>.is_extensional by simp\n                also have \"... = \\<phi> (f \\<cdot> y) j\"\n                  using j \\<chi>.is_natural_2\n                  by (metis J.arr_cod \\<chi>.A.map_simp J.cod_cod)\n                also have \"... = ?\\<chi> f j \\<cdot> y\"\n                  using f y \\<chi> \\<chi>.is_extensional by simp\n                finally show \"(?\\<chi> f (J.cod j) \\<cdot> B.map j) \\<cdot> y = ?\\<chi> f j \\<cdot> y\" by auto\n              qed\n            qed\n            show \"D j \\<cdot> ?\\<chi> f (J.dom j) = ?\\<chi> f j\"\n              using par1 nat 0\n              apply (intro S.arr_eqI' [of \"D j \\<cdot> ?\\<chi> f (J.dom j)\" \"?\\<chi> f j\"])\n               apply force\n              by auto\n            show \"?\\<chi> f (J.cod j) \\<cdot> B.map j = ?\\<chi> f j\"\n              using par2 nat 0 f j \\<chi>\n              apply (intro S.arr_eqI' [of \"?\\<chi> f (J.cod j) \\<cdot> B.map j\" \"?\\<chi> f j\"])\n               apply force\n              by (metis (no_types, lifting) S.in_homE)\n          qed\n        qed\n        interpret \\<chi>a: cone J S D a \\<open>?\\<chi> a\\<close> using a cone [of a] by fastforce\n        text\\<open>\n          Finally, show that \\<open>\\<chi> a\\<close> is a limit cone.\n\\<close>\n        interpret \\<chi>a: limit_cone J S D a \\<open>?\\<chi> a\\<close>\n        proof\n          fix a' \\<chi>'\n          assume cone_\\<chi>': \"cone a' \\<chi>'\"\n          interpret \\<chi>': cone J S D a' \\<chi>' using cone_\\<chi>' by auto\n          show \"\\<exists>!f. \\<guillemotleft>f : a' \\<rightarrow> a\\<guillemotright> \\<and> cones_map f (?\\<chi> a) = \\<chi>'\"\n          proof\n            let ?\\<psi> = \"inv_into (S.hom S.unity a) \\<phi>\"\n            have \\<psi>: \"?\\<psi> \\<in> cones S.unity \\<rightarrow> S.hom S.unity a\"\n              using \\<phi> bij_betw_inv_into bij_betwE by blast\n            let ?P = \"\\<lambda>f. \\<guillemotleft>f : a' \\<rightarrow> a\\<guillemotright> \\<and>\n                          (\\<forall>y. y \\<in> S.hom S.unity a' \\<longrightarrow> f \\<cdot> y = ?\\<psi> (cones_map y \\<chi>'))\"\n            have 1: \"\\<exists>!f. ?P f\"\n            proof -\n              have \"(\\<lambda>y. ?\\<psi> (cones_map y \\<chi>')) \\<in> S.hom S.unity a' \\<rightarrow> S.hom S.unity a\"\n              proof\n                fix x\n                assume \"x \\<in> S.hom S.unity a'\"\n                hence \"\\<guillemotleft>x : S.unity \\<rightarrow> a'\\<guillemotright>\" by simp\n                hence \"cones_map x \\<in> cones a' \\<rightarrow> cones S.unity\"\n                  using cones_map_mapsto [of x] by (elim S.in_homE, auto)\n                hence \"cones_map x \\<chi>' \\<in> cones S.unity\"\n                  using cone_\\<chi>' by blast\n                thus \"?\\<psi> (cones_map x \\<chi>') \\<in> S.hom S.unity a\"\n                  using \\<psi> by auto\n              qed\n              thus ?thesis\n                using S.fun_complete' a \\<chi>'.ide_apex by simp\n            qed\n            let ?f = \"THE f. ?P f\"\n            have f: \"?P ?f\" using 1 theI' [of ?P] by simp\n            have f_in_hom: \"\\<guillemotleft>?f : a' \\<rightarrow> a\\<guillemotright>\" using f by simp\n            have f_map: \"cones_map ?f (?\\<chi> a) = \\<chi>'\"\n            proof -\n              have 1: \"cone a' (cones_map ?f (?\\<chi> a))\"\n              proof -\n                have \"cones_map ?f \\<in> cones a \\<rightarrow> cones a'\"\n                  using f_in_hom cones_map_mapsto [of ?f] by (elim S.in_homE, auto)\n                hence \"cones_map ?f (?\\<chi> a) \\<in> cones a'\"\n                  using \\<chi>a.cone_axioms by blast\n                thus ?thesis by simp\n              qed\n              interpret f\\<chi>a: cone J S D a' \\<open>cones_map ?f (?\\<chi> a)\\<close>\n                using 1 by simp\n              show ?thesis\n              proof\n                fix j\n                have \"\\<not>J.arr j \\<Longrightarrow> cones_map ?f (?\\<chi> a) j = \\<chi>' j\"\n                  using 1 \\<chi>'.is_extensional f\\<chi>a.is_extensional by presburger\n                moreover have \"J.arr j \\<Longrightarrow> cones_map ?f (?\\<chi> a) j = \\<chi>' j\"\n                proof -\n                  assume j: \"J.arr j\"\n                  show \"cones_map ?f (?\\<chi> a) j = \\<chi>' j\"\n                  proof (intro S.arr_eqI' [of \"cones_map ?f (?\\<chi> a) j\" \"\\<chi>' j\"])\n                    show par: \"S.par (cones_map ?f (?\\<chi> a) j) (\\<chi>' j)\"\n                      using j \\<chi>'.preserves_cod \\<chi>'.preserves_dom \\<chi>'.preserves_reflects_arr\n                            f\\<chi>a.preserves_cod f\\<chi>a.preserves_dom f\\<chi>a.preserves_reflects_arr\n                      by presburger\n                    fix y\n                    assume \"\\<guillemotleft>y : S.unity \\<rightarrow> S.dom (cones_map ?f (?\\<chi> a) j)\\<guillemotright>\"\n                    hence y: \"\\<guillemotleft>y : S.unity \\<rightarrow> a'\\<guillemotright>\"\n                      using j f\\<chi>a.preserves_dom by simp\n                    have 1: \"\\<guillemotleft>?\\<chi> a j : a \\<rightarrow> D (J.cod j)\\<guillemotright>\"\n                      using j \\<chi>a.preserves_hom by force\n                    have 2: \"\\<guillemotleft>?f \\<cdot> y : S.unity \\<rightarrow> a\\<guillemotright>\"\n                      using f_in_hom y by blast\n                    have \"cones_map ?f (?\\<chi> a) j \\<cdot> y = (?\\<chi> a j \\<cdot> ?f) \\<cdot> y\"\n                    proof -\n                      have \"S.cod ?f = a\" using f_in_hom by blast\n                      thus ?thesis using j \\<chi>a.cone_axioms by simp\n                    qed\n                    also have \"... = ?\\<chi> a j \\<cdot> ?f \\<cdot> y\"\n                      using 1 j y f_in_hom S.comp_assoc S.seqI' by blast\n                    also have \"... = \\<phi> (a \\<cdot> ?f \\<cdot> y) j\"\n                      using 1 2 ide_a f j y \\<chi> [of a] by (simp add: S.ide_in_hom)\n                    also have \"... = \\<phi> (?f \\<cdot> y) j\"\n                      using a 2 y S.comp_cod_arr by (elim S.in_homE, auto)\n                    also have \"... = \\<phi> (?\\<psi> (cones_map y \\<chi>')) j\"\n                      using j y f by simp\n                    also have \"... = cones_map y \\<chi>' j\"\n                    proof -\n                      have \"cones_map y \\<chi>' \\<in> cones S.unity\"\n                        using cone_\\<chi>' y cones_map_mapsto by force\n                      hence \"\\<phi> (?\\<psi> (cones_map y \\<chi>')) = cones_map y \\<chi>'\"\n                        using \\<phi> bij_betw_inv_into_right [of \\<phi>] by simp\n                      thus ?thesis by auto\n                    qed\n                    also have \"... = \\<chi>' j \\<cdot> y\"\n                      using cone_\\<chi>' j y by auto\n                    finally show \"cones_map ?f (?\\<chi> a) j \\<cdot> y = \\<chi>' j \\<cdot> y\"\n                      by auto\n                  qed\n                qed\n                ultimately show \"cones_map ?f (?\\<chi> a) j = \\<chi>' j\" by blast\n              qed\n            qed\n            show \"\\<guillemotleft>?f : a' \\<rightarrow> a\\<guillemotright> \\<and> cones_map ?f (?\\<chi> a) = \\<chi>'\"\n              using f_in_hom f_map by simp\n            show \"\\<And>f'. \\<guillemotleft>f' : a' \\<rightarrow> a\\<guillemotright> \\<and> cones_map f' (?\\<chi> a) = \\<chi>' \\<Longrightarrow> f' = ?f\"\n            proof -\n              fix f'\n              assume f': \"\\<guillemotleft>f' : a' \\<rightarrow> a\\<guillemotright> \\<and> cones_map f' (?\\<chi> a) = \\<chi>'\"\n              have f'_in_hom: \"\\<guillemotleft>f' : a' \\<rightarrow> a\\<guillemotright>\" using f' by simp\n              have f'_map: \"cones_map f' (?\\<chi> a) = \\<chi>'\" using f' by simp\n              show \"f' = ?f\"\n              proof (intro S.arr_eqI' [of f' ?f])\n                show \"S.par f' ?f\"\n                  using f_in_hom f'_in_hom by (elim S.in_homE, auto)\n                show \"\\<And>y'. \\<guillemotleft>y' : S.unity \\<rightarrow> S.dom f'\\<guillemotright> \\<Longrightarrow> f' \\<cdot> y' = ?f \\<cdot> y'\"\n                proof -\n                  fix y'\n                  assume y': \"\\<guillemotleft>y' : S.unity \\<rightarrow> S.dom f'\\<guillemotright>\"\n                  have 0: \"\\<phi> (f' \\<cdot> y') = cones_map y' \\<chi>'\"\n                  proof\n                    fix j\n                    have 1: \"\\<guillemotleft>f' \\<cdot> y' : S.unity \\<rightarrow> a\\<guillemotright>\" using f'_in_hom y' by auto\n                    hence 2: \"\\<phi> (f' \\<cdot> y') \\<in> cones S.unity\"\n                      using \\<phi> bij_betw_imp_funcset [of \\<phi> \"S.hom S.unity a\" \"cones S.unity\"]\n                      by auto\n                    interpret \\<chi>'': cone J S D S.unity \\<open>\\<phi> (f' \\<cdot> y')\\<close> using 2 by auto\n                    have \"\\<not>J.arr j \\<Longrightarrow> \\<phi> (f' \\<cdot> y') j = cones_map y' \\<chi>' j\"\n                      using f' y' cone_\\<chi>' \\<chi>''.is_extensional mem_Collect_eq restrict_apply\n                      by (elim S.in_homE, auto)\n                    moreover have \"J.arr j \\<Longrightarrow> \\<phi> (f' \\<cdot> y') j = cones_map y' \\<chi>' j\"\n                    proof -\n                      assume j: \"J.arr j\"\n                      have 3: \"\\<guillemotleft>?\\<chi> a j : a \\<rightarrow> D (J.cod j)\\<guillemotright>\"\n                        using j \\<chi>a.preserves_hom by force\n                      have \"\\<phi> (f' \\<cdot> y') j = \\<phi> (a \\<cdot> f' \\<cdot> y') j\"\n                        using a f' y' j S.comp_cod_arr by (elim S.in_homE, auto)\n                      also have \"... = ?\\<chi> a j \\<cdot> f' \\<cdot> y'\"\n                        using 1 3 \\<chi> [of a] a f' y' j by fastforce\n                      also have \"... = (?\\<chi> a j \\<cdot> f') \\<cdot> y'\"\n                        using S.comp_assoc by simp\n                      also have \"... = cones_map f' (?\\<chi> a) j \\<cdot> y'\"\n                        using f' y' j \\<chi>a.cone_axioms by auto\n                      also have \"... = \\<chi>' j \\<cdot> y'\"\n                        using f' by blast\n                      also have \"... = cones_map y' \\<chi>' j\"\n                        using y' j cone_\\<chi>' f' mem_Collect_eq restrict_apply by force\n                      finally show \"\\<phi> (f' \\<cdot> y') j = cones_map y' \\<chi>' j\" by auto\n                    qed\n                    ultimately show \"\\<phi> (f' \\<cdot> y') j = cones_map y' \\<chi>' j\" by auto\n                  qed\n                  hence \"f' \\<cdot> y' = ?\\<psi> (cones_map y' \\<chi>')\"\n                    using \\<phi> f'_in_hom y' S.comp_in_homI\n                          bij_betw_inv_into_left [of \\<phi> \"S.hom S.unity a\" \"cones S.unity\" \"f' \\<cdot> y'\"]\n                    by (elim S.in_homE, auto)\n                  moreover have \"?f \\<cdot> y' = ?\\<psi> (cones_map y' \\<chi>')\"\n                    using \\<phi> 0 1 f f_in_hom f'_in_hom y' S.comp_in_homI\n                          bij_betw_inv_into_left [of \\<phi> \"S.hom S.unity a\" \"cones S.unity\" \"?f \\<cdot> y'\"]\n                    by (elim S.in_homE, auto)\n                  ultimately show \"f' \\<cdot> y' = ?f \\<cdot> y'\" by auto\n                qed\n              qed\n            qed\n          qed\n        qed\n        have \"limit_cone a (?\\<chi> a)\" ..\n        thus ?thesis by auto\n      qed\n    qed\n\n  end\n\n  context set_category\n  begin\n\n    text\\<open>\n      A set category has an equalizer for any parallel pair of arrows.\n\\<close>\n\n    lemma has_equalizers:\n    shows \"has_equalizers\"\n    proof (unfold has_equalizers_def)\n      have \"\\<And>f0 f1. par f0 f1 \\<Longrightarrow> \\<exists>e. has_as_equalizer f0 f1 e\"\n      proof -\n        fix f0 f1\n        assume par: \"par f0 f1\"\n        interpret J: parallel_pair .\n        interpret PP: parallel_pair_diagram S f0 f1\n          apply unfold_locales using par by auto\n        interpret PP: diagram_in_set_category J.comp S PP.map ..\n        text\\<open>\n          Let @{term a} be the object corresponding to the set of all images of equalizing points\n          of @{term \"dom f0\"}, and let @{term e} be the inclusion of @{term a} in @{term \"dom f0\"}.\n\\<close>\n        let ?a = \"mkIde (img ` {e. e \\<in> hom unity (dom f0) \\<and> f0 \\<cdot> e = f1 \\<cdot> e})\"\n        have \"{e. e \\<in> hom unity (dom f0) \\<and> f0 \\<cdot> e = f1 \\<cdot> e} \\<subseteq> hom unity (dom f0)\"\n          by auto\n        hence 1: \"img ` {e. e \\<in> hom unity (dom f0) \\<and> f0 \\<cdot> e = f1 \\<cdot> e} \\<subseteq> Univ\"\n          using img_point_in_Univ by auto\n        have ide_a: \"ide ?a\" using 1 by auto\n        have set_a: \"set ?a = img ` {e. e \\<in> hom unity (dom f0) \\<and> f0 \\<cdot> e = f1 \\<cdot> e}\"\n          using 1 by simp\n        have incl_in_a: \"incl_in ?a (dom f0)\"\n        proof -\n          have \"ide (dom f0)\"\n            using PP.is_parallel by simp\n          moreover have \"set ?a \\<subseteq> set (dom f0)\"\n          proof -\n            have \"set ?a = img ` {e. e \\<in> hom unity (dom f0) \\<and> f0 \\<cdot> e = f1 \\<cdot> e}\"\n              using img_point_in_Univ set_a by blast\n            thus ?thesis\n              using imageE img_point_elem_set mem_Collect_eq subsetI by auto\n          qed\n          ultimately show ?thesis\n            using incl_in_def \\<open>ide ?a\\<close> by simp\n        qed\n        text\\<open>\n          Then @{term \"set a\"} is in bijective correspondence with @{term \"PP.cones unity\"}.\n\\<close>\n        let ?\\<phi> = \"\\<lambda>t. PP.mkCone (mkPoint (dom f0) t)\"\n        let ?\\<psi> = \"\\<lambda>\\<chi>. img (\\<chi> (J.Zero))\"\n        have bij: \"bij_betw ?\\<phi> (set ?a) (PP.cones unity)\"\n        proof (intro bij_betwI)\n          show \"?\\<phi> \\<in> set ?a \\<rightarrow> PP.cones unity\"\n          proof\n            fix t\n            assume t: \"t \\<in> set ?a\"\n            hence 1: \"t \\<in> img ` {e. e \\<in> hom unity (dom f0) \\<and> f0 \\<cdot> e = f1 \\<cdot> e}\"\n              using set_a by blast\n            then have 2: \"mkPoint (dom f0) t \\<in> hom unity (dom f0)\"\n              using mkPoint_in_hom imageE mem_Collect_eq mkPoint_img(2) by auto\n            with 1 have 3: \"mkPoint (dom f0) t \\<in> {e. e \\<in> hom unity (dom f0) \\<and> f0 \\<cdot> e = f1 \\<cdot> e}\"\n              using mkPoint_img(2) by auto\n            then have \"PP.is_equalized_by (mkPoint (dom f0) t)\"\n              using CollectD par by fastforce\n            thus \"PP.mkCone (mkPoint (dom f0) t) \\<in> PP.cones unity\"\n              using 2 PP.cone_mkCone [of \"mkPoint (dom f0) t\"] by auto\n          qed\n          show \"?\\<psi> \\<in> PP.cones unity \\<rightarrow> set ?a\"\n          proof\n            fix \\<chi>\n            assume \\<chi>: \"\\<chi> \\<in> PP.cones unity\"\n            interpret \\<chi>: cone J.comp S PP.map unity \\<chi> using \\<chi> by auto\n            have \"\\<chi> (J.Zero) \\<in> hom unity (dom f0) \\<and> f0 \\<cdot> \\<chi> (J.Zero) = f1 \\<cdot> \\<chi> (J.Zero)\"\n              using \\<chi> PP.map_def PP.is_equalized_by_cone J.arr_char by auto\n            hence \"img (\\<chi> (J.Zero)) \\<in> set ?a\"\n              using set_a by simp\n            thus \"?\\<psi> \\<chi> \\<in> set ?a\" by blast\n          qed\n          show \"\\<And>t. t \\<in> set ?a \\<Longrightarrow> ?\\<psi> (?\\<phi> t) = t\"\n            using set_a J.arr_char PP.mkCone_def imageE mem_Collect_eq mkPoint_img(2)\n            by auto\n          show \"\\<And>\\<chi>. \\<chi> \\<in> PP.cones unity \\<Longrightarrow> ?\\<phi> (?\\<psi> \\<chi>) = \\<chi>\"\n          proof -\n            fix \\<chi>\n            assume \\<chi>: \"\\<chi> \\<in> PP.cones unity\"\n            interpret \\<chi>: cone J.comp S PP.map unity \\<chi> using \\<chi> by auto\n            have 1: \"\\<chi> (J.Zero) \\<in> hom unity (dom f0) \\<and> f0 \\<cdot> \\<chi> (J.Zero) = f1 \\<cdot> \\<chi> (J.Zero)\"\n              using \\<chi> PP.map_def PP.is_equalized_by_cone J.arr_char by auto\n            hence \"img (\\<chi> (J.Zero)) \\<in> set ?a\"\n              using set_a by simp\n            hence \"img (\\<chi> (J.Zero)) \\<in> set (dom f0)\"\n              using incl_in_a incl_in_def by auto\n            hence \"mkPoint (dom f0) (img (\\<chi> J.Zero)) = \\<chi> J.Zero\"\n              using 1 mkPoint_img(2) by blast\n            hence \"?\\<phi> (?\\<psi> \\<chi>) = PP.mkCone (\\<chi> J.Zero)\" by simp\n            also have \"... = \\<chi>\"\n              using \\<chi> PP.mkCone_cone by simp\n            finally show \"?\\<phi> (?\\<psi> \\<chi>) = \\<chi>\" by auto\n          qed\n        qed\n        text\\<open>\n          It follows that @{term a} is a limit of \\<open>PP\\<close>, and that the limit cone gives an\n          equalizer of @{term f0} and @{term f1}.\n\\<close>\n        have \"\\<exists>\\<mu>. bij_betw \\<mu> (hom unity ?a) (set ?a)\"\n          using bij_betw_points_and_set ide_a by auto\n        from this obtain \\<mu> where \\<mu>: \"bij_betw \\<mu> (hom unity ?a) (set ?a)\" by blast\n        have \"bij_betw (?\\<phi> o \\<mu>) (hom unity ?a) (PP.cones unity)\"\n          using bij \\<mu> bij_betw_comp_iff by blast\n        hence \"\\<exists>\\<phi>. bij_betw \\<phi> (hom unity ?a) (PP.cones unity)\" by auto\n        hence \"PP.has_as_limit ?a\"\n          using ide_a PP.limits_are_sets_of_cones by simp\n        from this obtain \\<epsilon> where \\<epsilon>: \"limit_cone J.comp S PP.map ?a \\<epsilon>\" by auto\n        interpret \\<epsilon>: limit_cone J.comp S PP.map ?a \\<epsilon> using \\<epsilon> by auto\n        have \"PP.mkCone (\\<epsilon> (J.Zero)) = \\<epsilon>\"\n          using \\<epsilon> PP.mkCone_cone \\<epsilon>.cone_axioms by simp\n        moreover have \"dom (\\<epsilon> (J.Zero)) = ?a\"\n          using J.ide_char \\<epsilon>.preserves_hom \\<epsilon>.A.map_def by simp\n        ultimately have \"PP.has_as_equalizer (\\<epsilon> J.Zero)\"\n          using \\<epsilon> by simp\n        thus \"\\<exists>e. has_as_equalizer f0 f1 e\"\n          using par has_as_equalizer_def by auto   \n      qed\n      thus \"\\<forall>f0 f1. par f0 f1 \\<longrightarrow> (\\<exists>e. has_as_equalizer f0 f1 e)\" by auto\n    qed\n\n  end\n\n  sublocale set_category \\<subseteq> category_with_equalizers S\n    apply unfold_locales using has_equalizers by auto\n\n  context set_category\n  begin\n\n    text\\<open>\n      The aim of the next results is to characterize the conditions under which a set\n      category has products.  In a traditional development of category theory,\n      one shows that the category \\textbf{Set} of \\emph{all} sets has all small\n      (\\emph{i.e.}~set-indexed) products.  In the present context we do not have a\n      category of \\emph{all} sets, but rather only a category of all sets with\n      elements at a particular type.  Clearly, we cannot expect such a category\n      to have products indexed by arbitrarily large sets.  The existence of\n      @{term I}-indexed products in a set category @{term[source=true] S} implies that the universe\n      \\<open>S.Univ\\<close> of @{term[source=true] S} must be large enough to admit the formation of\n      @{term I}-tuples of its elements.  Conversely, for a set category @{term[source=true] S}\n      the ability to form @{term I}-tuples in @{term Univ} implies that\n      @{term[source=true] S} has @{term I}-indexed products.  Below we make this precise by\n      defining the notion of when a set category @{term[source=true] S}\n      ``admits @{term I}-indexed tupling'' and we show that @{term[source=true] S}\n      has @{term I}-indexed products if and only if it admits @{term I}-indexed tupling.\n\n      The definition of ``@{term[source=true] S} admits @{term I}-indexed tupling'' says that\n      there is an injective map, from the space of extensional functions from\n      @{term I} to @{term Univ}, to @{term Univ}.  However for a convenient\n      statement and proof of the desired result, the definition of extensional\n      function from theory @{theory \"HOL-Library.FuncSet\"} needs to be modified.\n      The theory @{theory \"HOL-Library.FuncSet\"} uses the definite, but arbitrarily chosen value\n      @{term undefined} as the value to be assumed by an extensional function outside\n      of its domain.  In the context of the \\<open>set_category\\<close>, though, it is\n      more natural to use \\<open>S.unity\\<close>, which is guaranteed to be an element of the\n      universe of @{term[source=true] S}, for this purpose.  Doing things that way makes it\n      simpler to establish a bijective correspondence between cones over @{term D} with apex\n      @{term unity} and the set of extensional functions @{term d} that map\n      each arrow @{term j} of @{term J} to an element @{term \"d j\"} of @{term \"set (D j)\"}.\n      Possibly it makes sense to go back and make this change in \\<open>set_category\\<close>,\n      but that would mean completely abandoning @{theory \"HOL-Library.FuncSet\"} and essentially\n      introducing a duplicate version for use with \\<open>set_category\\<close>.\n      As a compromise, what I have done here is to locally redefine the few notions from\n      @{theory \"HOL-Library.FuncSet\"} that I need in order to prove the next set of results.\n\\<close>\n\n    definition extensional\n    where \"extensional A \\<equiv> {f. \\<forall>x. x \\<notin> A \\<longrightarrow> f x = unity}\"\n\n    abbreviation PiE\n    where \"PiE A B \\<equiv> Pi A B \\<inter> extensional A\"\n\n    abbreviation restrict\n    where \"restrict f A \\<equiv> \\<lambda>x. if x \\<in> A then f x else unity\"\n\n    lemma extensionalI [intro]:\n    assumes \"\\<And>x. x \\<notin> A \\<Longrightarrow> f x = unity\"\n    shows \"f \\<in> extensional A\"\n      using assms extensional_def by auto\n\n    lemma extensional_arb:\n    assumes \"f \\<in> extensional A\" and \"x \\<notin> A\"\n    shows \"f x = unity\"\n      using assms extensional_def by fast\n\n    lemma extensional_monotone:\n    assumes \"A \\<subseteq> B\"\n    shows \"extensional A \\<subseteq> extensional B\"\n    proof\n      fix f\n      assume f: \"f \\<in> extensional A\"\n      have 1: \"\\<forall>x. x \\<notin> A \\<longrightarrow> f x = unity\" using f extensional_def by fast\n      hence \"\\<forall>x. x \\<notin> B \\<longrightarrow> f x = unity\" using assms by auto\n      thus \"f \\<in> extensional B\" using extensional_def by blast\n    qed\n\n    lemma 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\n  end\n\n  locale discrete_diagram_in_set_category =\n    S: set_category S +\n    discrete_diagram J S D +\n    diagram_in_set_category J S D\n  for J :: \"'j comp\"      (infixr \"\\<cdot>\\<^sub>J\" 55)\n  and S :: \"'s comp\"      (infixr \"\\<cdot>\" 55)\n  and D :: \"'j \\<Rightarrow> 's\"\n  begin\n\n    text\\<open>\n      For @{term D} a discrete diagram in a set category, there is a bijective correspondence\n      between cones over @{term D} with apex unity and the set of extensional functions @{term d}\n      that map each arrow @{term j} of @{term[source=true] J} to an element of\n      @{term \"S.set (D j)\"}.\n\\<close>\n\n    abbreviation I\n    where \"I \\<equiv> Collect J.arr\"\n\n    definition funToCone\n    where \"funToCone F \\<equiv> \\<lambda>j. if J.arr j then S.mkPoint (D j) (F j) else S.null\"\n\n    definition coneToFun\n    where \"coneToFun \\<chi> \\<equiv> \\<lambda>j. if J.arr j then S.img (\\<chi> j) else S.unity\"\n\n    lemma funToCone_mapsto:\n    shows \"funToCone \\<in> S.PiE I (S.set o D) \\<rightarrow> cones S.unity\"\n    proof\n      fix F\n      assume F: \"F \\<in> S.PiE I (S.set o D)\"\n      interpret U: constant_functor J S S.unity\n        apply unfold_locales using S.ide_unity by auto\n      have 1: \"S.ide (S.mkIde S.Univ)\" by simp\n      have \"cone S.unity (funToCone F)\"\n      proof\n        show \"\\<And>j. \\<not>J.arr j \\<Longrightarrow> funToCone F j = S.null\"\n          using funToCone_def by simp\n        fix j\n        assume j: \"J.arr j\"\n        have \"funToCone F j = S.mkPoint (D j) (F j)\"\n          using j funToCone_def by simp\n        moreover have \"... \\<in> S.hom S.unity (D j)\"\n          using F j is_discrete S.img_mkPoint(1) [of \"D j\"] by force\n        ultimately have 2: \"funToCone F j \\<in> S.hom S.unity (D j)\" by auto\n        show 3: \"S.dom (funToCone F j) = U.map (J.dom j)\"\n          using 2 j U.map_simp by auto\n        show 4: \"S.cod (funToCone F j) = D (J.cod j)\"\n          using 2 j is_discrete by auto\n        show \"D j \\<cdot> funToCone F (J.dom j) = funToCone F j\"\n          using 2 j is_discrete S.comp_cod_arr by auto\n        show \"funToCone F (J.cod j) \\<cdot> (U.map j) = funToCone F j\"\n          using 3 j is_discrete U.map_simp S.arr_dom_iff_arr S.comp_arr_dom U.preserves_arr\n          by (metis J.ide_char)\n      qed\n      thus \"funToCone F \\<in> cones S.unity\" by auto\n    qed\n\n    lemma coneToFun_mapsto:\n    shows \"coneToFun \\<in> cones S.unity \\<rightarrow> S.PiE I (S.set o D)\"\n    proof\n      fix \\<chi>\n      assume \\<chi>: \"\\<chi> \\<in> cones S.unity\"\n      interpret \\<chi>: cone J S D S.unity \\<chi> using \\<chi> by auto\n      show \"coneToFun \\<chi> \\<in> S.PiE I (S.set o D)\"\n      proof\n        show \"coneToFun \\<chi> \\<in> Pi I (S.set o D)\"\n          using S.mkPoint_img(1) coneToFun_def is_discrete \\<chi>.component_in_hom\n          by (simp add: S.img_point_elem_set restrict_apply')\n        show \"coneToFun \\<chi> \\<in> S.extensional I\"\n        proof\n          fix x\n          show \"x \\<notin> I \\<Longrightarrow> coneToFun \\<chi> x = S.unity\"\n            using coneToFun_def by simp\n        qed\n      qed\n    qed\n\n    lemma funToCone_coneToFun:\n    assumes \"\\<chi> \\<in> cones S.unity\"\n    shows \"funToCone (coneToFun \\<chi>) = \\<chi>\"\n    proof\n      interpret \\<chi>: cone J S D S.unity \\<chi> using assms by auto\n      fix j\n      have \"\\<not>J.arr j \\<Longrightarrow> funToCone (coneToFun \\<chi>) j = \\<chi> j\"\n        using funToCone_def \\<chi>.is_extensional by simp\n      moreover have \"J.arr j \\<Longrightarrow> funToCone (coneToFun \\<chi>) j = \\<chi> j\"\n        using funToCone_def coneToFun_def S.mkPoint_img(2) is_discrete \\<chi>.component_in_hom\n        by auto\n      ultimately show \"funToCone (coneToFun \\<chi>) j = \\<chi> j\" by blast\n    qed\n\n    lemma coneToFun_funToCone:\n    assumes \"F \\<in> S.PiE I (S.set o D)\"\n    shows \"coneToFun (funToCone F) = F\"\n    proof\n      fix i\n      have \"i \\<notin> I \\<Longrightarrow> coneToFun (funToCone F) i = F i\"\n        using assms coneToFun_def S.extensional_arb [of F I i] by auto\n      moreover have \"i \\<in> I \\<Longrightarrow> coneToFun (funToCone F) i = F i\"\n      proof -\n        assume i: \"i \\<in> I\"\n        have \"coneToFun (funToCone F) i = S.img (funToCone F i)\"\n          using i coneToFun_def by simp\n        also have \"... = S.img (S.mkPoint (D i) (F i))\"\n          using i funToCone_def by auto\n        also have \"... = F i\"\n          using assms i is_discrete S.img_mkPoint(2) by force\n        finally show \"coneToFun (funToCone F) i = F i\" by auto\n      qed\n      ultimately show \"coneToFun (funToCone F) i = F i\" by auto\n    qed\n\n    lemma bij_coneToFun:\n    shows \"bij_betw coneToFun (cones S.unity) (S.PiE I (S.set o D))\"\n      using coneToFun_mapsto funToCone_mapsto funToCone_coneToFun coneToFun_funToCone\n            bij_betwI\n      by blast\n\n    lemma bij_funToCone:\n    shows \"bij_betw funToCone (S.PiE I (S.set o D)) (cones S.unity)\"\n      using coneToFun_mapsto funToCone_mapsto funToCone_coneToFun coneToFun_funToCone\n            bij_betwI\n      by blast\n \n  end\n\n  context set_category\n  begin\n\n    text\\<open>\n      A set category admits @{term I}-indexed tupling if there is an injective map that takes\n      each extensional function from @{term I} to @{term Univ} to an element of @{term Univ}.\n\\<close>\n\n    definition admits_tupling\n    where \"admits_tupling I \\<equiv> \\<exists>\\<pi>. \\<pi> \\<in> PiE I (\\<lambda>_. Univ) \\<rightarrow> Univ \\<and> inj_on \\<pi> (PiE I (\\<lambda>_. Univ))\"\n\n    lemma admits_tupling_monotone:\n    assumes \"admits_tupling I\" and \"I' \\<subseteq> I\"\n    shows \"admits_tupling I'\"\n    proof -\n      from assms(1) obtain \\<pi>\n      where \\<pi>: \"\\<pi> \\<in> PiE I (\\<lambda>_. Univ) \\<rightarrow> Univ \\<and> inj_on \\<pi> (PiE I (\\<lambda>_. Univ))\"\n        using admits_tupling_def by metis\n      have \"\\<pi> \\<in> PiE I' (\\<lambda>_. Univ) \\<rightarrow> Univ\"\n      proof\n        fix f\n        assume f: \"f \\<in> PiE I' (\\<lambda>_. Univ)\"\n        have \"f \\<in> PiE I (\\<lambda>_. Univ)\"\n          using assms(2) f extensional_def [of I'] terminal_unity extensional_monotone by auto\n        thus \"\\<pi> f \\<in> Univ\" using \\<pi> by auto\n      qed\n      moreover have \"inj_on \\<pi> (PiE I' (\\<lambda>_. Univ))\"\n      proof -\n        have 1: \"\\<And>F A A'. inj_on F A \\<and> A' \\<subseteq> A \\<Longrightarrow> inj_on F A'\"\n          using subset_inj_on by blast\n        moreover have \"PiE I' (\\<lambda>_. Univ) \\<subseteq> PiE I (\\<lambda>_. Univ)\"\n          using assms(2) extensional_def [of I'] terminal_unity by auto\n        ultimately show ?thesis using \\<pi> assms(2) by blast\n      qed\n      ultimately show ?thesis using admits_tupling_def by metis\n    qed\n\n    lemma has_products_iff_admits_tupling:\n    fixes I :: \"'i set\"\n    shows \"has_products I \\<longleftrightarrow> I \\<noteq> UNIV \\<and> admits_tupling I\"\n    proof\n      text\\<open>\n        If @{term[source=true] S} has @{term I}-indexed products, then for every @{term I}-indexed\n        discrete diagram @{term D} in @{term[source=true] S} there is an object @{term \\<Pi>D}\n        of @{term[source=true] S} whose points are in bijective correspondence with the set of\n        cones over @{term D} with apex @{term unity}.  In particular this is true for\n        the diagram @{term D} that assigns to each element of @{term I} the\n        ``universal object'' @{term \"mkIde Univ\"}.\n\\<close>\n      assume has_products: \"has_products I\"\n      have I: \"I \\<noteq> UNIV\" using has_products has_products_def by auto\n      interpret J: discrete_category I \\<open>SOME x. x \\<notin> I\\<close>\n        using I someI_ex [of \"\\<lambda>x. x \\<notin> I\"] by (unfold_locales, auto)\n      let ?D = \"\\<lambda>i. mkIde Univ\"\n      interpret D: discrete_diagram_from_map I S ?D \\<open>SOME j. j \\<notin> I\\<close>\n        using J.not_arr_null J.arr_char\n        by (unfold_locales, auto)\n      interpret D: discrete_diagram_in_set_category J.comp S D.map ..\n      have \"discrete_diagram J.comp S D.map\" ..\n      from this obtain \\<Pi>D \\<chi> where \\<chi>: \"product_cone J.comp S D.map \\<Pi>D \\<chi>\"\n        using has_products has_products_def [of I] ex_productE [of \"J.comp\" D.map]\n              D.diagram_axioms\n        by blast\n      interpret \\<chi>: product_cone J.comp S D.map \\<Pi>D \\<chi>\n        using \\<chi> by auto\n      have \"D.has_as_limit \\<Pi>D\"\n        using \\<chi>.limit_cone_axioms by auto\n      hence \\<Pi>D: \"ide \\<Pi>D \\<and> (\\<exists>\\<phi>. bij_betw \\<phi> (hom unity \\<Pi>D) (D.cones unity))\"\n        using D.limits_are_sets_of_cones by simp\n      from this obtain \\<phi> where \\<phi>: \"bij_betw \\<phi> (hom unity \\<Pi>D) (D.cones unity)\"\n        by blast\n      have \\<phi>': \"inv_into (hom unity \\<Pi>D) \\<phi> \\<in> D.cones unity \\<rightarrow> hom unity \\<Pi>D \\<and>\n                inj_on (inv_into (hom unity \\<Pi>D) \\<phi>) (D.cones unity)\"\n        using \\<phi> bij_betw_inv_into bij_betw_imp_inj_on bij_betw_imp_funcset by blast\n      let ?\\<pi> = \"img o (inv_into (hom unity \\<Pi>D) \\<phi>) o D.funToCone\"\n      have 1: \"D.funToCone \\<in> PiE I (set o D.map) \\<rightarrow> D.cones unity\"\n        using D.funToCone_mapsto extensional_def [of I] by auto\n      have 2: \"inv_into (hom unity \\<Pi>D) \\<phi> \\<in> D.cones unity \\<rightarrow> hom unity \\<Pi>D\"\n        using \\<phi>' by auto\n      have 3: \"img \\<in> hom unity \\<Pi>D \\<rightarrow> Univ\"\n        using img_point_in_Univ by blast\n      have 4: \"inj_on D.funToCone (PiE I (set o D.map))\"\n      proof -\n        have \"D.I = I\" by auto\n        thus ?thesis\n          using D.bij_funToCone bij_betw_imp_inj_on by auto\n      qed\n      have 5: \"inj_on (inv_into (hom unity \\<Pi>D) \\<phi>) (D.cones unity)\"\n        using \\<phi>' by auto\n      have 6: \"inj_on img (hom unity \\<Pi>D)\"\n        using \\<Pi>D bij_betw_points_and_set bij_betw_imp_inj_on [of img \"hom unity \\<Pi>D\" \"set \\<Pi>D\"]\n        by simp\n      have \"?\\<pi> \\<in> PiE I (set o D.map) \\<rightarrow> Univ\"\n        using 1 2 3 by force\n      moreover have \"inj_on ?\\<pi> (PiE I (set o D.map))\"\n      proof -\n        have 7: \"\\<And>A B C D F G H. F \\<in> A \\<rightarrow> B \\<and> G \\<in> B \\<rightarrow> C \\<and> H \\<in> C \\<rightarrow> D\n                      \\<and> inj_on F A \\<and> inj_on G B \\<and> inj_on H C\n                    \\<Longrightarrow> inj_on (H o G o F) A\"\n        proof (intro inj_onI)\n          fix A :: \"'a set\" and B :: \"'b set\" and C :: \"'c set\" and D :: \"'d set\"\n          and F :: \"'a \\<Rightarrow> 'b\" and G :: \"'b \\<Rightarrow> 'c\" and H :: \"'c \\<Rightarrow> 'd\"\n          assume a1: \"F \\<in> A \\<rightarrow> B \\<and> G \\<in> B \\<rightarrow> C \\<and> H \\<in> C \\<rightarrow> D \\<and>\n                      inj_on F A \\<and> inj_on G B \\<and> inj_on H C\"\n          fix a a'\n          assume a: \"a \\<in> A\" and a': \"a' \\<in> A\" and eq: \"(H o G o F) a = (H o G o F) a'\"\n          have \"H (G (F a)) = H (G (F a'))\" using eq by simp\n          moreover have \"G (F a) \\<in> C \\<and> G (F a') \\<in> C\" using a a' a1 by auto\n          ultimately have \"G (F a) = G (F a')\" using a1 inj_onD by metis\n          moreover have \"F a \\<in> B \\<and> F a' \\<in> B\" using a a' a1 by auto\n          ultimately have \"F a = F a'\" using a1 inj_onD by metis\n          thus \"a = a'\" using a a' a1 inj_onD by metis\n        qed\n        show ?thesis\n          using 1 2 3 4 5 6 7 [of D.funToCone \"PiE I (set o D.map)\" \"D.cones unity\"\n                                  \"inv_into (hom unity \\<Pi>D) \\<phi>\" \"hom unity \\<Pi>D\"\n                                  img Univ]\n          by fastforce\n      qed\n      moreover have \"PiE I (set o D.map) = PiE I (\\<lambda>x. Univ)\"\n      proof -\n        have \"\\<And>i. i \\<in> I \\<Longrightarrow> (set o D.map) i = Univ\"\n          using J.arr_char D.map_def by simp\n        thus ?thesis by blast\n      qed\n      ultimately have \"?\\<pi> \\<in> (PiE I (\\<lambda>x. Univ)) \\<rightarrow> Univ \\<and> inj_on ?\\<pi> (PiE I (\\<lambda>x. Univ))\"\n        by auto\n      thus \"I \\<noteq> UNIV \\<and> admits_tupling I\"\n        using I admits_tupling_def by auto\n      next\n      assume ex_\\<pi>: \"I \\<noteq> UNIV \\<and> admits_tupling I\"\n      show \"has_products I\"\n      proof (unfold has_products_def)\n        from ex_\\<pi> obtain \\<pi>\n        where \\<pi>: \"\\<pi> \\<in> (PiE I (\\<lambda>x. Univ)) \\<rightarrow> Univ \\<and> inj_on \\<pi> (PiE I (\\<lambda>x. Univ))\"\n          using admits_tupling_def by metis\n        text\\<open>\n          Given an @{term I}-indexed discrete diagram @{term D}, obtain the object @{term \\<Pi>D}\n          of @{term[source=true] S} corresponding to the set @{term \"\\<pi> ` PiE I D\"} of all\n          @{term \"\\<pi> d\"} where \\<open>d \\<in> d \\<in> J \\<rightarrow>\\<^sub>E Univ\\<close> and @{term \"d i \\<in> D i\"}\n          for all @{term \"i \\<in> I\"}.\n          The elements of @{term \\<Pi>D} are in bijective correspondence with the set of cones\n          over @{term D}, hence @{term \\<Pi>D} is a limit of @{term D}.\n\\<close>\n        have \"\\<And>J D. discrete_diagram J S D \\<and> Collect (partial_magma.arr J) = I\n                 \\<Longrightarrow> \\<exists>\\<Pi>D. has_as_product J D \\<Pi>D\"\n        proof\n          fix J :: \"'i comp\" and D\n          assume D: \"discrete_diagram J S D \\<and> Collect (partial_magma.arr J) = I\"\n          interpret J: category J\n            using D discrete_diagram.axioms(1) by blast\n          interpret D: discrete_diagram J S D\n            using D by simp\n          interpret D: discrete_diagram_in_set_category J S D ..\n          let ?\\<Pi>D = \"mkIde (\\<pi> ` PiE I (set o D))\"\n          have 0: \"ide ?\\<Pi>D\"\n          proof -\n            have \"set o D \\<in> I \\<rightarrow> Pow Univ\"\n              using Pow_iff incl_in_def o_apply elem_set_implies_incl_in\n                    set_subset_Univ subsetI\n              by (metis (mono_tags, lifting) Pi_I')\n            hence \"\\<pi> ` PiE I (set o D) \\<subseteq> Univ\"\n              using \\<pi> by blast\n            thus ?thesis using \\<pi> ide_mkIde by simp\n          qed\n          hence set_\\<Pi>D: \"\\<pi> ` PiE I (set o D) = set ?\\<Pi>D\"\n            using 0 ide_in_hom by auto\n          text\\<open>\n            The elements of @{term \\<Pi>D} are all values of the form @{term \"\\<pi> d\"},\n            where @{term d} satisfies @{term \"d i \\<in> set (D i)\"} for all @{term \"i \\<in> I\"}.\n            Such @{term d} correspond bijectively to cones.\n            Since @{term \\<pi>} is injective, the values @{term \"\\<pi> d\"} correspond bijectively to cones.\n\\<close>\n          let ?\\<phi> = \"mkPoint ?\\<Pi>D o \\<pi> o D.coneToFun\"\n          let ?\\<phi>' = \"D.funToCone o inv_into (PiE I (set o D)) \\<pi> o img\"\n          have 1: \"\\<pi> \\<in> PiE I (set o D) \\<rightarrow> set ?\\<Pi>D \\<and> inj_on \\<pi> (PiE I (set o D))\"\n          proof -\n            have \"PiE I (set o D) \\<subseteq> PiE I (\\<lambda>x. Univ)\"\n              using set_subset_Univ elem_set_implies_incl_in elem_set_implies_set_eq_singleton\n                    incl_in_def PiE_mono\n              by (metis comp_apply subsetI)\n            thus ?thesis using \\<pi> subset_inj_on set_\\<Pi>D Pi_I' imageI by fastforce\n          qed\n          have 2: \"inv_into (PiE I (set o D)) \\<pi> \\<in> set ?\\<Pi>D \\<rightarrow> PiE I (set o D)\"\n          proof\n            fix y\n            assume y: \"y \\<in> set ?\\<Pi>D\"\n            have \"y \\<in> \\<pi> ` (PiE I (set o D))\" using y set_\\<Pi>D by auto\n            thus \"inv_into (PiE I (set o D)) \\<pi> y \\<in> PiE I (set o D)\"\n              using inv_into_into [of y \\<pi> \"PiE I (set o D)\"] by simp\n          qed\n          have 3: \"\\<And>x. x \\<in> set ?\\<Pi>D \\<Longrightarrow> \\<pi> (inv_into (PiE I (set o D)) \\<pi> x) = x\"\n            using set_\\<Pi>D by (simp add: f_inv_into_f)\n          have 4: \"\\<And>d. d \\<in> PiE I (set o D) \\<Longrightarrow> inv_into (PiE I (set o D)) \\<pi> (\\<pi> d) = d\"\n            using 1 by auto\n          have 5: \"D.I = I\"\n            using D by auto\n          have \"bij_betw ?\\<phi> (D.cones unity) (hom unity ?\\<Pi>D)\"\n          proof (intro bij_betwI)\n            show \"?\\<phi> \\<in> D.cones unity \\<rightarrow> hom unity ?\\<Pi>D\"\n            proof\n              fix \\<chi>\n              assume \\<chi>: \"\\<chi> \\<in> D.cones unity\"\n              show \"?\\<phi> \\<chi> \\<in> hom unity ?\\<Pi>D\"\n                using \\<chi> 0 1 5 D.coneToFun_mapsto mkPoint_in_hom [of ?\\<Pi>D]\n                by (simp, blast)\n            qed\n            show \"?\\<phi>' \\<in> hom unity ?\\<Pi>D \\<rightarrow> D.cones unity\"\n            proof\n              fix x\n              assume x: \"x \\<in> hom unity ?\\<Pi>D\"\n              hence \"img x \\<in> set ?\\<Pi>D\"\n                using img_point_elem_set by blast\n              hence \"inv_into (PiE I (set o D)) \\<pi> (img x) \\<in> Pi I (set \\<circ> D) \\<inter> local.extensional I\"\n                using 2 by blast\n              thus \"?\\<phi>' x \\<in> D.cones unity\"\n                using 5 D.funToCone_mapsto by auto\n            qed\n            show \"\\<And>x. x \\<in> hom unity ?\\<Pi>D \\<Longrightarrow> ?\\<phi> (?\\<phi>' x) = x\"\n            proof -\n              fix x\n              assume x: \"x \\<in> hom unity ?\\<Pi>D\"\n              show \"?\\<phi> (?\\<phi>' x) = x\"\n              proof -\n                have \"D.coneToFun (D.funToCone (inv_into (PiE I (set o D)) \\<pi> (img x)))\n                          = inv_into (PiE I (set o D)) \\<pi> (img x)\"\n                  using x 1 5 img_point_elem_set set_\\<Pi>D D.coneToFun_funToCone by force\n                hence \"\\<pi> (D.coneToFun (D.funToCone (inv_into (PiE I (set o D)) \\<pi> (img x))))\n                          = img x\"\n                  using x 3 img_point_elem_set set_\\<Pi>D by force\n                thus ?thesis using x 0 mkPoint_img by auto\n              qed\n            qed\n            show \"\\<And>\\<chi>. \\<chi> \\<in> D.cones unity \\<Longrightarrow> ?\\<phi>' (?\\<phi> \\<chi>) = \\<chi>\"\n            proof -\n              fix \\<chi>\n              assume \\<chi>: \"\\<chi> \\<in> D.cones unity\"\n              show \"?\\<phi>' (?\\<phi> \\<chi>) = \\<chi>\"\n              proof -\n                have \"img (mkPoint ?\\<Pi>D (\\<pi> (D.coneToFun \\<chi>))) = \\<pi> (D.coneToFun \\<chi>)\"\n                  using \\<chi> 0 1 5 D.coneToFun_mapsto img_mkPoint(2) by blast\n                hence \"inv_into (PiE I (set o D)) \\<pi> (img (mkPoint ?\\<Pi>D (\\<pi> (D.coneToFun \\<chi>))))\n                         = D.coneToFun \\<chi>\"\n                  using \\<chi> D.coneToFun_mapsto 4 5 by (metis PiE)\n                hence \"D.funToCone (inv_into (PiE I (set o D)) \\<pi>\n                                             (img (mkPoint ?\\<Pi>D (\\<pi> (D.coneToFun \\<chi>)))))\n                         = \\<chi>\"\n                  using \\<chi> D.funToCone_coneToFun by auto\n                thus ?thesis by auto\n              qed\n            qed\n          qed\n          hence \"bij_betw (inv_into (D.cones unity) ?\\<phi>) (hom unity ?\\<Pi>D) (D.cones unity)\"\n            using bij_betw_inv_into by blast\n          hence \"\\<exists>\\<phi>. bij_betw \\<phi> (hom unity ?\\<Pi>D) (D.cones unity)\" by blast\n          hence \"D.has_as_limit ?\\<Pi>D\"\n            using \\<open>ide ?\\<Pi>D\\<close> D.limits_are_sets_of_cones by simp\n          from this obtain \\<chi> where \\<chi>: \"limit_cone J S D ?\\<Pi>D \\<chi>\" by blast\n          interpret \\<chi>: limit_cone J S D ?\\<Pi>D \\<chi> using \\<chi> by auto\n          interpret P: product_cone J S D ?\\<Pi>D \\<chi>\n            using \\<chi> D.product_coneI by blast\n          have \"product_cone J S D ?\\<Pi>D \\<chi>\" ..\n          thus \"has_as_product J D ?\\<Pi>D\"\n            using has_as_product_def by auto\n        qed\n        thus \"I \\<noteq> UNIV \\<and>\n              (\\<forall>J D. discrete_diagram J S D \\<and> Collect (partial_magma.arr J) = I\n                  \\<longrightarrow> (\\<exists>\\<Pi>D. has_as_product J D \\<Pi>D))\"\n          using ex_\\<pi> by blast\n      qed\n    qed\n\n    text\\<open>\n      Characterization of the completeness properties enjoyed by a set category:\n      A set category @{term[source=true] S} has all limits at a type @{typ 'j},\n      if and only if @{term[source=true] S} admits @{term I}-indexed tupling\n      for all @{typ 'j}-sets @{term I} such that @{term \"I \\<noteq> UNIV\"}.\n\\<close>\n\n    theorem has_limits_iff_admits_tupling:\n    shows \"has_limits (undefined :: 'j) \\<longleftrightarrow> (\\<forall>I :: 'j set. I \\<noteq> UNIV \\<longrightarrow> admits_tupling I)\"\n    proof\n      assume has_limits: \"has_limits (undefined :: 'j)\"\n      show \"\\<forall>I :: 'j set. I \\<noteq> UNIV \\<longrightarrow> admits_tupling I\"\n        using has_limits has_products_if_has_limits has_products_iff_admits_tupling by blast\n      next\n      assume admits_tupling: \"\\<forall>I :: 'j set. I \\<noteq> UNIV \\<longrightarrow> admits_tupling I\"\n      show \"has_limits (undefined :: 'j)\"\n      proof -\n        have 1: \"\\<And>I :: 'j set. I \\<noteq> UNIV \\<Longrightarrow> has_products I\"\n          using admits_tupling has_products_iff_admits_tupling by auto\n        have \"\\<And>J :: 'j comp. category J \\<Longrightarrow> has_products (Collect (partial_magma.arr J))\"\n        proof -\n          fix J :: \"'j comp\"\n          assume J: \"category J\"\n          interpret J: category J using J by auto\n          have \"Collect J.arr \\<noteq> UNIV\" using J.not_arr_null by blast\n          thus \"has_products (Collect J.arr)\"\n            using 1 by simp\n        qed\n        hence \"\\<And>J :: 'j comp. category J \\<Longrightarrow> has_limits_of_shape J\"\n        proof -\n          fix J :: \"'j comp\"\n          assume J: \"category J\"\n          interpret J: category J using J by auto\n          show \"has_limits_of_shape J\"\n          proof -\n            have \"Collect J.arr \\<noteq> UNIV\" using J.not_arr_null by fast\n            moreover have \"Collect J.ide \\<noteq> UNIV\" using J.not_arr_null by blast\n            ultimately show ?thesis\n              using 1 has_limits_if_has_products J.category_axioms by metis\n          qed\n        qed\n        thus \"has_limits (undefined :: 'j)\"\n          using has_limits_def by metis\n      qed\n    qed\n\n  end\n\n  section \"Limits in Functor Categories\"\n\n  text\\<open>\n    In this section, we consider the special case of limits in functor categories,\n    with the objective of showing that limits in a functor category \\<open>[A, B]\\<close>\n    are given pointwise, and that \\<open>[A, B]\\<close> has all limits that @{term B} has.\n\\<close>\n\n  locale parametrized_diagram =\n    J: category J +\n    A: category A +\n    B: category B +\n    JxA: product_category J A +\n    binary_functor J A B D\n  for J :: \"'j comp\"      (infixr \"\\<cdot>\\<^sub>J\" 55)\n  and A :: \"'a comp\"      (infixr \"\\<cdot>\\<^sub>A\" 55)\n  and B :: \"'b comp\"      (infixr \"\\<cdot>\\<^sub>B\" 55)\n  and D :: \"'j * 'a \\<Rightarrow> 'b\"\n  begin\n\n    (* Notation for A.in_hom and B.in_hom is being inherited, but from where? *)\n    notation J.in_hom     (\"\\<guillemotleft>_ : _ \\<rightarrow>\\<^sub>J _\\<guillemotright>\")\n    notation JxA.comp     (infixr \"\\<cdot>\\<^sub>J\\<^sub>x\\<^sub>A\" 55)\n    notation JxA.in_hom   (\"\\<guillemotleft>_ : _ \\<rightarrow>\\<^sub>J\\<^sub>x\\<^sub>A _\\<guillemotright>\")\n\n    text\\<open>\n      A choice of limit cone for each diagram \\<open>D (-, a)\\<close>, where @{term a}\n      is an object of @{term[source=true] A}, extends to a functor \\<open>L: A \\<rightarrow> B\\<close>,\n      where the action of @{term L} on arrows of @{term[source=true] A} is determined by\n      universality.\n\\<close>\n\n    abbreviation L\n    where \"L \\<equiv> \\<lambda>l \\<chi>. \\<lambda>a. if A.arr a then\n                            limit_cone.induced_arrow J B (\\<lambda>j. D (j, A.cod a))\n                              (l (A.cod a)) (\\<chi> (A.cod a))\n                              (l (A.dom a)) (vertical_composite.map J B\n                                               (\\<chi> (A.dom a)) (\\<lambda>j. D (j, a)))\n                          else B.null\"\n\n    abbreviation P\n    where \"P \\<equiv> \\<lambda>l \\<chi>. \\<lambda>a f. \\<guillemotleft>f : l (A.dom a) \\<rightarrow>\\<^sub>B l (A.cod a)\\<guillemotright> \\<and>\n                           diagram.cones_map J B (\\<lambda>j. D (j, A.cod a)) f (\\<chi> (A.cod a)) =\n                           vertical_composite.map J B (\\<chi> (A.dom a)) (\\<lambda>j. D (j, a))\"\n\n    lemma L_arr:\n    assumes \"\\<forall>a. A.ide a \\<longrightarrow> limit_cone J B (\\<lambda>j. D (j, a)) (l a) (\\<chi> a)\"\n    shows \"\\<And>a. A.arr a \\<Longrightarrow> (\\<exists>!f. P l \\<chi> a f) \\<and> P l \\<chi> a (L l \\<chi> a)\"\n    proof\n      fix a\n      assume a: \"A.arr a\"\n      interpret \\<chi>_dom_a: limit_cone J B \\<open>\\<lambda>j. D (j, A.dom a)\\<close> \\<open>l (A.dom a)\\<close> \\<open>\\<chi> (A.dom a)\\<close>\n        using a assms by auto\n      interpret \\<chi>_cod_a: limit_cone J B \\<open>\\<lambda>j. D (j, A.cod a)\\<close> \\<open>l (A.cod a)\\<close> \\<open>\\<chi> (A.cod a)\\<close>\n        using a assms by auto\n      interpret Da: natural_transformation J B \\<open>\\<lambda>j. D (j, A.dom a)\\<close> \\<open>\\<lambda>j. D (j, A.cod a)\\<close>\n                                               \\<open>\\<lambda>j. D (j, a)\\<close>\n        using a fixing_arr_gives_natural_transformation_2 by simp\n      interpret Dao\\<chi>_dom_a: vertical_composite J B\n                              \\<chi>_dom_a.A.map \\<open>\\<lambda>j. D (j, A.dom a)\\<close> \\<open>\\<lambda>j. D (j, A.cod a)\\<close>\n                              \\<open>\\<chi> (A.dom a)\\<close> \\<open>\\<lambda>j. D (j, a)\\<close> ..\n      interpret Dao\\<chi>_dom_a: cone J B \\<open>\\<lambda>j. D (j, A.cod a)\\<close> \\<open>l (A.dom a)\\<close> Dao\\<chi>_dom_a.map ..\n      show \"P l \\<chi> a (L l \\<chi> a)\"\n        using a Dao\\<chi>_dom_a.cone_axioms\n              \\<chi>_cod_a.induced_arrowI [of Dao\\<chi>_dom_a.map \"l (A.dom a)\"]\n        by auto\n      show \"\\<exists>!f. P l \\<chi> a f\"\n        using \\<chi>_cod_a.is_universal Dao\\<chi>_dom_a.cone_axioms by blast\n    qed\n\n    lemma L_ide:\n    assumes \"\\<forall>a. A.ide a \\<longrightarrow> limit_cone J B (\\<lambda>j. D (j, a)) (l a) (\\<chi> a)\"\n    shows \"\\<And>a. A.ide a \\<Longrightarrow> L l \\<chi> a = l a\"\n    proof -\n      let ?L = \"L l \\<chi>\"\n      let ?P = \"P l \\<chi>\"\n      fix a\n      assume a: \"A.ide a\"\n      interpret \\<chi>a: limit_cone J B \\<open>\\<lambda>j. D (j, a)\\<close> \\<open>l a\\<close> \\<open>\\<chi> a\\<close> using a assms by auto\n      have Pa: \"?P a = (\\<lambda>f. f \\<in> B.hom (l a) (l a) \\<and>\n                            diagram.cones_map J B (\\<lambda>j. D (j, a)) f (\\<chi> a) = \\<chi> a)\"\n        using a vcomp_ide_dom \\<chi>a.natural_transformation_axioms by simp\n      have \"?P a (?L a)\" using assms a L_arr [of l \\<chi> a] by fastforce\n      moreover have \"?P a (l a)\"\n      proof -\n        have \"?P a (l a) \\<longleftrightarrow> l a \\<in> B.hom (l a) (l a) \\<and> \\<chi>a.D.cones_map (l a) (\\<chi> a) = \\<chi> a\"\n          using Pa by meson\n        thus ?thesis\n          using a \\<chi>a.ide_apex \\<chi>a.cone_axioms \\<chi>a.D.cones_map_ide [of \"\\<chi> a\" \"l a\"] by force\n      qed\n      moreover have \"\\<exists>!f. ?P a f\"\n        using a Pa \\<chi>a.is_universal \\<chi>a.cone_axioms by force\n      ultimately show \"?L a = l a\" by blast\n    qed\n\n    lemma chosen_limits_induce_functor:\n    assumes \"\\<forall>a. A.ide a \\<longrightarrow> limit_cone J B (\\<lambda>j. D (j, a)) (l a) (\\<chi> a)\"\n    shows \"functor A B (L l \\<chi>)\"\n    proof -\n      let ?L = \"L l \\<chi>\"\n      let ?P = \"\\<lambda>a. \\<lambda>f. \\<guillemotleft>f : l (A.dom a) \\<rightarrow>\\<^sub>B l (A.cod a)\\<guillemotright> \\<and>\n                        diagram.cones_map J B (\\<lambda>j. D (j, A.cod a)) f (\\<chi> (A.cod a))\n                             = vertical_composite.map J B (\\<chi> (A.dom a)) (\\<lambda>j. D (j, a))\"\n      interpret L: \"functor\" A B ?L\n        apply unfold_locales\n        using assms L_arr [of l] L_ide\n            apply auto[4]\n      proof -\n        fix a' a\n        assume 1: \"A.arr (A a' a)\"\n        have a: \"A.arr a\" using 1 by auto\n        have a': \"\\<guillemotleft>a' : A.cod a \\<rightarrow>\\<^sub>A A.cod a'\\<guillemotright>\" using 1 by auto\n        have a'a: \"A.seq a' a\" using 1 by auto\n        interpret \\<chi>_dom_a: limit_cone J B \\<open>\\<lambda>j. D (j, A.dom a)\\<close> \\<open>l (A.dom a)\\<close> \\<open>\\<chi> (A.dom a)\\<close>\n          using a assms by auto\n        interpret \\<chi>_cod_a: limit_cone J B \\<open>\\<lambda>j. D (j, A.cod a)\\<close> \\<open>l (A.cod a)\\<close> \\<open>\\<chi> (A.cod a)\\<close>\n          using a'a assms by auto\n        interpret \\<chi>_dom_a'a: limit_cone J B \\<open>\\<lambda>j. D (j, A.dom (a' \\<cdot>\\<^sub>A a))\\<close> \\<open>l (A.dom (a' \\<cdot>\\<^sub>A a))\\<close>\n                                            \\<open>\\<chi> (A.dom (a' \\<cdot>\\<^sub>A a))\\<close>\n          using a'a assms by auto\n        interpret \\<chi>_cod_a'a: limit_cone J B \\<open>\\<lambda>j. D (j, A.cod (a' \\<cdot>\\<^sub>A a))\\<close> \\<open>l (A.cod (a' \\<cdot>\\<^sub>A a))\\<close>\n                                            \\<open>\\<chi> (A.cod (a' \\<cdot>\\<^sub>A a))\\<close>\n          using a'a assms by auto\n        interpret Da: natural_transformation J B \\<open>\\<lambda>j. D (j, A.dom a)\\<close> \\<open>\\<lambda>j. D (j, A.cod a)\\<close>\n                                                 \\<open>\\<lambda>j. D (j, a)\\<close>\n          using a fixing_arr_gives_natural_transformation_2 by simp\n        interpret Da': natural_transformation J B \\<open>\\<lambda>j. D (j, A.cod a)\\<close> \\<open>\\<lambda>j. D (j, A.cod (a' \\<cdot>\\<^sub>A a))\\<close>\n                                                  \\<open>\\<lambda>j. D (j, a')\\<close>\n          using a a'a fixing_arr_gives_natural_transformation_2 by fastforce\n        interpret Da'o\\<chi>_cod_a: vertical_composite J B\n                                 \\<chi>_cod_a.A.map \\<open>\\<lambda>j. D (j, A.cod a)\\<close> \\<open>\\<lambda>j. D (j, A.cod (a' \\<cdot>\\<^sub>A a))\\<close>\n                                 \\<open>\\<chi> (A.cod a)\\<close> \\<open>\\<lambda>j. D (j, a')\\<close>..\n        interpret Da'o\\<chi>_cod_a: cone J B \\<open>\\<lambda>j. D (j, A.cod (a' \\<cdot>\\<^sub>A a))\\<close> \\<open>l (A.cod a)\\<close> Da'o\\<chi>_cod_a.map ..\n        interpret Da'a: natural_transformation J B\n                          \\<open>\\<lambda>j. D (j, A.dom (a' \\<cdot>\\<^sub>A a))\\<close> \\<open>\\<lambda>j. D (j, A.cod (a' \\<cdot>\\<^sub>A a))\\<close>\n                          \\<open>\\<lambda>j. D (j, a' \\<cdot>\\<^sub>A a)\\<close>\n          using a'a fixing_arr_gives_natural_transformation_2 [of \"a' \\<cdot>\\<^sub>A a\"] by auto\n        interpret Da'ao\\<chi>_dom_a'a:\n            vertical_composite J B \\<chi>_dom_a'a.A.map \\<open>\\<lambda>j. D (j, A.dom (a' \\<cdot>\\<^sub>A a))\\<close>\n                                   \\<open>\\<lambda>j. D (j, A.cod (a' \\<cdot>\\<^sub>A a))\\<close> \\<open>\\<chi> (A.dom (a' \\<cdot>\\<^sub>A a))\\<close>\n                                   \\<open>\\<lambda>j. D (j, a' \\<cdot>\\<^sub>A a)\\<close> ..\n        interpret Da'ao\\<chi>_dom_a'a: cone J B \\<open>\\<lambda>j. D (j, A.cod (a' \\<cdot>\\<^sub>A a))\\<close>\n                                       \\<open>l (A.dom (a' \\<cdot>\\<^sub>A a))\\<close> Da'ao\\<chi>_dom_a'a.map ..\n        show \"?L (a' \\<cdot>\\<^sub>A a) = ?L a' \\<cdot>\\<^sub>B ?L a\"\n        proof -\n          have \"?P (a' \\<cdot>\\<^sub>A a) (?L (a' \\<cdot>\\<^sub>A a))\" using assms a'a L_arr [of l \\<chi> \"a' \\<cdot>\\<^sub>A a\"] by fastforce\n          moreover have \"?P (a' \\<cdot>\\<^sub>A a) (?L a' \\<cdot>\\<^sub>B ?L a)\"\n          proof\n            have La: \"\\<guillemotleft>?L a : l (A.dom a) \\<rightarrow>\\<^sub>B l (A.cod a)\\<guillemotright>\"\n              using assms a L_arr by fast\n            moreover have La': \"\\<guillemotleft>?L a' : l (A.cod a) \\<rightarrow>\\<^sub>B l (A.cod a')\\<guillemotright>\"\n              using assms a a' L_arr [of l \\<chi> a'] by auto\n            ultimately have seq: \"B.seq (?L a') (?L a)\" by (elim B.in_homE, auto)\n            thus La'_La: \"\\<guillemotleft>?L a' \\<cdot>\\<^sub>B ?L a : l (A.dom (a' \\<cdot>\\<^sub>A a)) \\<rightarrow>\\<^sub>B l (A.cod (a' \\<cdot>\\<^sub>A a))\\<guillemotright>\"\n              using a a' 1 La La' by (intro B.comp_in_homI, auto)\n            show \"\\<chi>_cod_a'a.D.cones_map (?L a' \\<cdot>\\<^sub>B ?L a) (\\<chi> (A.cod (a' \\<cdot>\\<^sub>A a)))\n                    = Da'ao\\<chi>_dom_a'a.map\"\n            proof -\n              have \"\\<chi>_cod_a'a.D.cones_map (?L a' \\<cdot>\\<^sub>B ?L a) (\\<chi> (A.cod (a' \\<cdot>\\<^sub>A a)))\n                       = (\\<chi>_cod_a'a.D.cones_map (?L a) o \\<chi>_cod_a'a.D.cones_map (?L a'))\n                           (\\<chi> (A.cod a'))\"\n              proof -\n                have \"\\<chi>_cod_a'a.D.cones_map (?L a' \\<cdot>\\<^sub>B ?L a) (\\<chi> (A.cod (a' \\<cdot>\\<^sub>A a))) =\n                      restrict (\\<chi>_cod_a'a.D.cones_map (?L a) \\<circ> \\<chi>_cod_a'a.D.cones_map (?L a'))\n                               (\\<chi>_cod_a'a.D.cones (B.cod (?L a')))\n                               (\\<chi> (A.cod (a' \\<cdot>\\<^sub>A a)))\"\n                  using seq \\<chi>_cod_a'a.cone_axioms \\<chi>_cod_a'a.D.cones_map_comp [of \"?L a'\" \"?L a\"]\n                  by argo\n                also have \"... = (\\<chi>_cod_a'a.D.cones_map (?L a) o \\<chi>_cod_a'a.D.cones_map (?L a'))\n                                 (\\<chi> (A.cod a'))\"\n                proof -\n                  have \"\\<chi> (A.cod a') \\<in> \\<chi>_cod_a'a.D.cones (l (A.cod a'))\"\n                    using \\<chi>_cod_a'a.cone_axioms a'a by simp\n                  moreover have \"B.cod (?L a') = l (A.cod a')\"\n                    using assms a' L_arr [of l] by auto\n                  ultimately show ?thesis\n                    using a' a'a by simp\n                qed\n                finally show ?thesis by blast\n              qed\n              also have \"... = \\<chi>_cod_a'a.D.cones_map (?L a)\n                                   (\\<chi>_cod_a'a.D.cones_map (?L a') (\\<chi> (A.cod a')))\"\n                  by simp\n              also have \"... = \\<chi>_cod_a'a.D.cones_map (?L a) Da'o\\<chi>_cod_a.map\"\n              proof -\n                have \"?P a' (?L a')\" using assms a' L_arr [of l \\<chi> a'] by fast\n                moreover have\n                    \"?P a' = (\\<lambda>f. f \\<in> B.hom (l (A.cod a)) (l (A.cod a')) \\<and>\n                                  \\<chi>_cod_a'a.D.cones_map f (\\<chi> (A.cod a')) = Da'o\\<chi>_cod_a.map)\"\n                  using a'a by force\n                ultimately show ?thesis using a'a by force\n              qed\n              also have \"... = vertical_composite.map J B\n                                 (\\<chi>_cod_a.D.cones_map (?L a) (\\<chi> (A.cod a)))\n                                 (\\<lambda>j. D (j, a'))\"\n                using assms \\<chi>_cod_a.D.diagram_axioms \\<chi>_cod_a'a.D.diagram_axioms\n                      Da'.natural_transformation_axioms \\<chi>_cod_a.cone_axioms La\n                      cones_map_vcomp [of J B \"\\<lambda>j. D (j, A.cod a)\" \"\\<lambda>j. D (j, A.cod (a' \\<cdot>\\<^sub>A a))\"\n                                          \"\\<lambda>j. D (j, a')\" \"l (A.cod a)\" \"\\<chi> (A.cod a)\"\n                                          \"?L a\" \"l (A.dom a)\"]\n                by blast\n              also have \"... = vertical_composite.map J B\n                                 (vertical_composite.map J B (\\<chi> (A.dom a)) (\\<lambda>j. D (j, a)))\n                                 (\\<lambda>j. D (j, a'))\"\n                using assms a L_arr by presburger\n              also have \"... = vertical_composite.map J B (\\<chi> (A.dom a))\n                                 (vertical_composite.map J B (\\<lambda>j. D (j, a)) (\\<lambda>j. D (j, a')))\"\n                using a'a Da.natural_transformation_axioms Da'.natural_transformation_axioms\n                      \\<chi>_dom_a.natural_transformation_axioms\n                      vcomp_assoc [of J B \\<chi>_dom_a.A.map \"\\<lambda>j. D (j, A.dom a)\" \"\\<chi> (A.dom a)\"\n                                      \"\\<lambda>j. D (j, A.cod a)\" \"\\<lambda>j. D (j, a)\"\n                                      \"\\<lambda>j. D (j, A.cod a')\" \"\\<lambda>j. D (j, a')\"]\n                by auto\n              also have\n                  \"... = vertical_composite.map J B (\\<chi> (A.dom (a' \\<cdot>\\<^sub>A a))) (\\<lambda>j. D (j, a' \\<cdot>\\<^sub>A a))\"\n                using a'a preserves_comp_2 by simp\n              finally show ?thesis by auto\n            qed\n          qed\n          moreover have \"\\<exists>!f. ?P (a' \\<cdot>\\<^sub>A a) f\"\n            using \\<chi>_cod_a'a.is_universal\n                    [of \"l (A.dom (a' \\<cdot>\\<^sub>A a))\"\n                        \"vertical_composite.map J B (\\<chi> (A.dom (a' \\<cdot>\\<^sub>A a))) (\\<lambda>j. D (j, a' \\<cdot>\\<^sub>A a))\"]\n                  Da'ao\\<chi>_dom_a'a.cone_axioms\n            by fast\n          ultimately show ?thesis by blast\n        qed\n      qed\n      show ?thesis ..\n    qed\n\n  end\n\n  locale diagram_in_functor_category =\n    A: category A +\n    B: category B +\n    A_B: functor_category A B +\n    diagram J A_B.comp D\n  for A :: \"'a comp\"      (infixr \"\\<cdot>\\<^sub>A\" 55)\n  and B :: \"'b comp\"      (infixr \"\\<cdot>\\<^sub>B\" 55)\n  and J :: \"'j comp\"      (infixr \"\\<cdot>\\<^sub>J\" 55)\n  and D :: \"'j \\<Rightarrow> ('a, 'b) functor_category.arr\"\n  begin\n\n    interpretation JxA: product_category J A ..\n    interpretation A_BxA: product_category A_B.comp A ..\n    interpretation E: evaluation_functor A B ..\n    interpretation Curry: currying J A B ..\n\n    notation JxA.comp     (infixr \"\\<cdot>\\<^sub>J\\<^sub>x\\<^sub>A\" 55)\n    notation JxA.in_hom   (\"\\<guillemotleft>_ : _ \\<rightarrow>\\<^sub>J\\<^sub>x\\<^sub>A _\\<guillemotright>\")\n\n    text\\<open>\n      Evaluation of a functor or natural transformation from @{term[source=true] J}\n      to \\<open>[A, B]\\<close> at an arrow @{term a} of @{term[source=true] A}.\n\\<close>\n\n    abbreviation at\n    where \"at a \\<tau> \\<equiv> \\<lambda>j. Curry.uncurry \\<tau> (j, a)\"\n\n    lemma at_simp:\n    assumes \"A.arr a\" and \"J.arr j\" and \"A_B.arr (\\<tau> j)\"\n    shows \"at a \\<tau> j = A_B.Map (\\<tau> j) a\"\n      using assms Curry.uncurry_def E.map_simp by simp\n\n    lemma functor_at_ide_is_functor:\n    assumes \"functor J A_B.comp F\" and \"A.ide a\"\n    shows \"functor J B (at a F)\"\n    proof -\n      interpret uncurry_F: \"functor\" JxA.comp B \\<open>Curry.uncurry F\\<close>\n        using assms(1) Curry.uncurry_preserves_functors by simp\n      interpret uncurry_F: binary_functor J A B \\<open>Curry.uncurry F\\<close> ..\n      show ?thesis using assms(2) uncurry_F.fixing_ide_gives_functor_2 by simp\n    qed\n\n    lemma functor_at_arr_is_transformation:\n    assumes \"functor J A_B.comp F\" and \"A.arr a\"\n    shows \"natural_transformation J B (at (A.dom a) F) (at (A.cod a) F) (at a F)\"\n    proof -\n      interpret uncurry_F: \"functor\" JxA.comp B \\<open>Curry.uncurry F\\<close>\n        using assms(1) Curry.uncurry_preserves_functors by simp\n      interpret uncurry_F: binary_functor J A B \\<open>Curry.uncurry F\\<close> ..\n      show ?thesis\n        using assms(2) uncurry_F.fixing_arr_gives_natural_transformation_2 by simp\n    qed\n\n    lemma transformation_at_ide_is_transformation:\n    assumes \"natural_transformation J A_B.comp F G \\<tau>\" and \"A.ide a\"\n    shows \"natural_transformation J B (at a F) (at a G) (at a \\<tau>)\"\n    proof -\n      interpret \\<tau>: natural_transformation J A_B.comp F G \\<tau> using assms(1) by auto\n      interpret uncurry_F: \"functor\" JxA.comp B \\<open>Curry.uncurry F\\<close>\n        using Curry.uncurry_preserves_functors \\<tau>.F.functor_axioms by simp\n      interpret uncurry_f: binary_functor J A B \\<open>Curry.uncurry F\\<close> ..\n      interpret uncurry_G: \"functor\" JxA.comp B \\<open>Curry.uncurry G\\<close>\n        using Curry.uncurry_preserves_functors \\<tau>.G.functor_axioms by simp\n      interpret uncurry_G: binary_functor J A B \\<open>Curry.uncurry G\\<close> ..\n      interpret uncurry_\\<tau>: natural_transformation\n                             JxA.comp B \\<open>Curry.uncurry F\\<close> \\<open>Curry.uncurry G\\<close> \\<open>Curry.uncurry \\<tau>\\<close>\n        using Curry.uncurry_preserves_transformations \\<tau>.natural_transformation_axioms\n        by simp\n      interpret uncurry_\\<tau>: binary_functor_transformation J A B\n                            \\<open>Curry.uncurry F\\<close> \\<open>Curry.uncurry G\\<close> \\<open>Curry.uncurry \\<tau>\\<close> ..\n      show ?thesis\n        using assms(2) uncurry_\\<tau>.fixing_ide_gives_natural_transformation_2 by simp\n    qed\n\n    lemma constant_at_ide_is_constant:\n    assumes \"cone x \\<chi>\" and a: \"A.ide a\"\n    shows \"at a (constant_functor.map J A_B.comp x) =\n           constant_functor.map J B (A_B.Map x a)\"\n    proof -\n      interpret \\<chi>: cone J A_B.comp D x \\<chi> using assms(1) by auto\n      have x: \"A_B.ide x\" using \\<chi>.ide_apex by auto\n      interpret Fun_x: \"functor\" A B \\<open>A_B.Map x\\<close>\n        using x A_B.ide_char by simp\n      interpret Da: \"functor\" J B \\<open>at a D\\<close>\n        using a functor_at_ide_is_functor functor_axioms by blast\n      interpret Da: diagram J B \\<open>at a D\\<close> ..\n      interpret Xa: constant_functor J B \\<open>A_B.Map x a\\<close>\n        using a Fun_x.preserves_ide [of a] by (unfold_locales, simp)\n      show \"at a \\<chi>.A.map = Xa.map\"\n        using a x Curry.uncurry_def E.map_def Xa.is_extensional by auto\n    qed\n\n    lemma at_ide_is_diagram:\n    assumes a: \"A.ide a\"\n    shows \"diagram J B (at a D)\"\n    proof -\n      interpret Da: \"functor\" J B \"at a D\"\n        using a functor_at_ide_is_functor functor_axioms by simp\n      show ?thesis ..\n    qed\n\n    lemma cone_at_ide_is_cone:\n    assumes \"cone x \\<chi>\" and a: \"A.ide a\"\n    shows \"diagram.cone J B (at a D) (A_B.Map x a) (at a \\<chi>)\"\n    proof -\n      interpret \\<chi>: cone J A_B.comp D x \\<chi> using assms(1) by auto\n      have x: \"A_B.ide x\" using \\<chi>.ide_apex by auto\n      interpret Fun_x: \"functor\" A B \\<open>A_B.Map x\\<close>\n        using x A_B.ide_char by simp\n      interpret Da: diagram J B \\<open>at a D\\<close> using a at_ide_is_diagram by auto\n      interpret Xa: constant_functor J B \\<open>A_B.Map x a\\<close>\n        using a by (unfold_locales, simp)\n      interpret \\<chi>a: natural_transformation J B Xa.map \\<open>at a D\\<close> \\<open>at a \\<chi>\\<close>\n        using assms(1) x a transformation_at_ide_is_transformation \\<chi>.natural_transformation_axioms\n              constant_at_ide_is_constant\n        by fastforce\n      interpret \\<chi>a: cone J B \\<open>at a D\\<close> \\<open>A_B.Map x a\\<close> \\<open>at a \\<chi>\\<close> ..\n      show cone_\\<chi>a: \"Da.cone (A_B.Map x a) (at a \\<chi>)\" ..\n    qed\n\n    lemma at_preserves_comp:\n    assumes \"A.seq a' a\"\n    shows \"at (A a' a) D = vertical_composite.map J B (at a D) (at a' D)\"\n    proof -\n      interpret Da: natural_transformation J B \\<open>at (A.dom a) D\\<close> \\<open>at (A.cod a) D\\<close> \\<open>at a D\\<close>\n        using assms functor_at_arr_is_transformation functor_axioms by blast\n      interpret Da': natural_transformation J B \\<open>at (A.cod a) D\\<close> \\<open>at (A.cod a') D\\<close> \\<open>at a' D\\<close>\n        using assms functor_at_arr_is_transformation [of D a'] functor_axioms by fastforce\n      interpret Da'oDa: vertical_composite J B \\<open>at (A.dom a) D\\<close> \\<open>at (A.cod a) D\\<close> \\<open>at (A.cod a') D\\<close>\n                                               \\<open>at a D\\<close> \\<open>at a' D\\<close> ..\n      interpret Da'a: natural_transformation J B \\<open>at (A.dom a) D\\<close> \\<open>at (A.cod a') D\\<close> \\<open>at (a' \\<cdot>\\<^sub>A a) D\\<close>\n        using assms functor_at_arr_is_transformation [of D \"a' \\<cdot>\\<^sub>A a\"] functor_axioms by simp\n      show \"at (a' \\<cdot>\\<^sub>A a) D = Da'oDa.map\"\n      proof (intro NaturalTransformation.eqI)\n        show \"natural_transformation J B (at (A.dom a) D) (at (A.cod a') D) Da'oDa.map\" ..\n        show \"natural_transformation J B (at (A.dom a) D) (at (A.cod a') D) (at (a' \\<cdot>\\<^sub>A a) D)\" ..\n        show \"\\<And>j. J.ide j \\<Longrightarrow> at (a' \\<cdot>\\<^sub>A a) D j = Da'oDa.map j\"\n        proof -\n          fix j\n          assume j: \"J.ide j\"\n          interpret Dj: \"functor\" A B \\<open>A_B.Map (D j)\\<close>\n            using j preserves_ide A_B.ide_char by simp\n          show \"at (a' \\<cdot>\\<^sub>A a) D j = Da'oDa.map j\"\n            using assms j Dj.preserves_comp at_simp Da'oDa.map_simp_ide by auto\n        qed\n      qed\n    qed\n\n    lemma cones_map_pointwise:\n    assumes \"cone x \\<chi>\" and \"cone x' \\<chi>'\"\n    and f: \"f \\<in> A_B.hom x' x\"\n    shows \"cones_map f \\<chi> = \\<chi>' \\<longleftrightarrow>\n             (\\<forall>a. A.ide a \\<longrightarrow> diagram.cones_map J B (at a D) (A_B.Map f a) (at a \\<chi>) = at a \\<chi>')\"\n    proof\n      interpret \\<chi>: cone J A_B.comp D x \\<chi> using assms(1) by auto\n      interpret \\<chi>': cone J A_B.comp D x' \\<chi>' using assms(2) by auto\n      have x: \"A_B.ide x\" using \\<chi>.ide_apex by auto\n      have x': \"A_B.ide x'\" using \\<chi>'.ide_apex by auto\n      interpret \\<chi>f: cone J A_B.comp D x' \\<open>cones_map f \\<chi>\\<close>\n        using x' f assms(1) cones_map_mapsto by blast\n      interpret Fun_x: \"functor\" A B \\<open>A_B.Map x\\<close> using x A_B.ide_char by simp\n      interpret Fun_x': \"functor\" A B \\<open>A_B.Map x'\\<close> using x' A_B.ide_char by simp\n      show \"cones_map f \\<chi> = \\<chi>' \\<Longrightarrow>\n              (\\<forall>a. A.ide a \\<longrightarrow> diagram.cones_map J B (at a D) (A_B.Map f a) (at a \\<chi>) = at a \\<chi>')\"\n      proof -\n        assume \\<chi>': \"cones_map f \\<chi> = \\<chi>'\"\n        have \"\\<And>a. A.ide a \\<Longrightarrow> diagram.cones_map J B (at a D) (A_B.Map f a) (at a \\<chi>) = at a \\<chi>'\"\n        proof -\n          fix a\n          assume a: \"A.ide a\"\n          interpret Da: diagram J B \\<open>at a D\\<close> using a at_ide_is_diagram by auto\n          interpret \\<chi>a: cone J B \\<open>at a D\\<close> \\<open>A_B.Map x a\\<close> \\<open>at a \\<chi>\\<close>\n            using a assms(1) cone_at_ide_is_cone by simp\n          interpret \\<chi>'a: cone J B \\<open>at a D\\<close> \\<open>A_B.Map x' a\\<close> \\<open>at a \\<chi>'\\<close>\n            using a assms(2) cone_at_ide_is_cone by simp\n          have 1: \"\\<guillemotleft>A_B.Map f a : A_B.Map x' a \\<rightarrow>\\<^sub>B A_B.Map x a\\<guillemotright>\"\n            using f a A_B.arr_char A_B.Map_cod A_B.Map_dom mem_Collect_eq\n                  natural_transformation.preserves_hom A.ide_in_hom\n            by (metis (no_types, lifting) A_B.in_homE)\n          interpret \\<chi>fa: cone J B \\<open>at a D\\<close> \\<open>A_B.Map x' a\\<close> \\<open>Da.cones_map (A_B.Map f a) (at a \\<chi>)\\<close>\n            using 1 \\<chi>a.cone_axioms Da.cones_map_mapsto by force\n          show \"Da.cones_map (A_B.Map f a) (at a \\<chi>) = at a \\<chi>'\"\n          proof\n            fix j\n            have \"\\<not>J.arr j \\<Longrightarrow> Da.cones_map (A_B.Map f a) (at a \\<chi>) j = at a \\<chi>' j\"\n              using \\<chi>'a.is_extensional \\<chi>fa.is_extensional [of j] by simp\n            moreover have \"J.arr j \\<Longrightarrow> Da.cones_map (A_B.Map f a) (at a \\<chi>) j = at a \\<chi>' j\"\n              using a f 1 \\<chi>.cone_axioms \\<chi>a.cone_axioms at_simp apply simp\n              apply (elim A_B.in_homE B.in_homE, auto)\n              using \\<chi>' \\<chi>.A.map_simp A_B.Map_comp [of \"\\<chi> j\" f a a] by auto\n            ultimately show \"Da.cones_map (A_B.Map f a) (at a \\<chi>) j = at a \\<chi>' j\" by blast\n          qed\n        qed\n        thus \"\\<forall>a. A.ide a \\<longrightarrow> diagram.cones_map J B (at a D) (A_B.Map f a) (at a \\<chi>) = at a \\<chi>'\"\n          by simp\n      qed\n      show \"\\<forall>a. A.ide a \\<longrightarrow> diagram.cones_map J B (at a D) (A_B.Map f a) (at a \\<chi>) = at a \\<chi>'\n              \\<Longrightarrow> cones_map f \\<chi> = \\<chi>'\"\n      proof -\n        assume A:\n            \"\\<forall>a. A.ide a \\<longrightarrow> diagram.cones_map J B (at a D) (A_B.Map f a) (at a \\<chi>) = at a \\<chi>'\"\n        show \"cones_map f \\<chi> = \\<chi>'\"\n        proof (intro NaturalTransformation.eqI)\n          show \"natural_transformation J A_B.comp \\<chi>'.A.map D (cones_map f \\<chi>)\" ..\n          show \"natural_transformation J A_B.comp \\<chi>'.A.map D \\<chi>'\" ..\n          show \"\\<And>j. J.ide j \\<Longrightarrow> cones_map f \\<chi> j = \\<chi>' j\"\n          proof (intro A_B.arr_eqI)\n            fix j\n            assume j: \"J.ide j\"\n            show 1: \"A_B.arr (cones_map f \\<chi> j)\"\n              using j \\<chi>f.preserves_reflects_arr by simp\n            show \"A_B.arr (\\<chi>' j)\" using j by auto\n            have Dom_\\<chi>f_j: \"A_B.Dom (cones_map f \\<chi> j) = A_B.Map x'\"\n              using x' j 1 A_B.Map_dom \\<chi>'.A.map_simp [of \"J.dom j\"] \\<chi>f.preserves_dom J.ide_in_hom\n              by (metis (no_types, lifting) J.ideD(2) \\<chi>f.preserves_reflects_arr)\n            also have Dom_\\<chi>'_j: \"... = A_B.Dom (\\<chi>' j)\"\n              using x' j A_B.Map_dom [of \"\\<chi>' j\"] \\<chi>'.preserves_hom \\<chi>'.A.map_simp by simp\n            finally show \"A_B.Dom (cones_map f \\<chi> j) = A_B.Dom (\\<chi>' j)\" by auto\n            have Cod_\\<chi>f_j: \"A_B.Cod (cones_map f \\<chi> j) = A_B.Map (D (J.cod j))\"\n              using j A_B.Map_cod [of \"cones_map f \\<chi> j\"] A_B.cod_char J.ide_in_hom\n                    \\<chi>f.preserves_hom [of j \"J.dom j\" \"J.cod j\"]\n              by (metis (no_types, lifting) \"1\" J.ideD(1) \\<chi>f.preserves_cod)\n            also have Cod_\\<chi>'_j: \"... = A_B.Cod (\\<chi>' j)\"\n              using j A_B.Map_cod [of \"\\<chi>' j\"] \\<chi>'.preserves_hom by simp\n            finally show \"A_B.Cod (cones_map f \\<chi> j) = A_B.Cod (\\<chi>' j)\" by auto\n            show \"A_B.Map (cones_map f \\<chi> j) = A_B.Map (\\<chi>' j)\"\n            proof (intro NaturalTransformation.eqI)\n              interpret \\<chi>fj: natural_transformation A B \\<open>A_B.Map x'\\<close> \\<open>A_B.Map (D (J.cod j))\\<close>\n                                                    \\<open>A_B.Map (cones_map f \\<chi> j)\\<close>\n                using j \\<chi>f.preserves_reflects_arr A_B.arr_char [of \"cones_map f \\<chi> j\"]\n                      Dom_\\<chi>f_j Cod_\\<chi>f_j\n                by simp\n              show \"natural_transformation A B (A_B.Map x') (A_B.Map (D (J.cod j)))\n                                           (A_B.Map (cones_map f \\<chi> j))\" ..\n              interpret \\<chi>'j: natural_transformation A B \\<open>A_B.Map x'\\<close> \\<open>A_B.Map (D (J.cod j))\\<close>\n                                                   \\<open>A_B.Map (\\<chi>' j)\\<close>\n                using j A_B.arr_char [of \"\\<chi>' j\"] Dom_\\<chi>'_j Cod_\\<chi>'_j by simp\n              show \"natural_transformation A B (A_B.Map x') (A_B.Map (D (J.cod j)))\n                                           (A_B.Map (\\<chi>' j))\" ..\n              show \"\\<And>a. A.ide a \\<Longrightarrow> A_B.Map (cones_map f \\<chi> j) a = A_B.Map (\\<chi>' j) a\"\n              proof -\n                fix a\n                assume a: \"A.ide a\"\n                interpret Da: diagram J B \\<open>at a D\\<close> using a at_ide_is_diagram by auto\n                have cone_\\<chi>a: \"Da.cone (A_B.Map x a) (at a \\<chi>)\"\n                  using a assms(1) cone_at_ide_is_cone by simp\n                interpret \\<chi>a: cone J B \\<open>at a D\\<close> \\<open>A_B.Map x a\\<close> \\<open>at a \\<chi>\\<close>\n                  using cone_\\<chi>a by auto\n                interpret Fun_f: natural_transformation A B \\<open>A_B.Dom f\\<close> \\<open>A_B.Cod f\\<close> \\<open>A_B.Map f\\<close>\n                  using f A_B.arr_char by fast\n                have fa: \"A_B.Map f a \\<in> B.hom (A_B.Map x' a) (A_B.Map x a)\"\n                  using a f Fun_f.preserves_hom A.ide_in_hom by auto\n                have \"A_B.Map (cones_map f \\<chi> j) a = Da.cones_map (A_B.Map f a) (at a \\<chi>) j\"\n                proof -\n                  have \"A_B.Map (cones_map f \\<chi> j) a = A_B.Map (A_B.comp (\\<chi> j) f) a\"\n                    using assms(1) f \\<chi>.is_extensional by auto\n                  also have \"... = B (A_B.Map (\\<chi> j) a) (A_B.Map f a)\"\n                    using f j a \\<chi>.preserves_hom A.ide_in_hom J.ide_in_hom A_B.Map_comp\n                          \\<chi>.A.map_simp\n                    by (metis (no_types, lifting) A.comp_ide_self A.ideD(1) A_B.seqI'\n                        J.ideD(1) mem_Collect_eq)\n                  also have \"... = Da.cones_map (A_B.Map f a) (at a \\<chi>) j\"\n                    using j a cone_\\<chi>a fa Curry.uncurry_def E.map_simp by auto\n                  finally show ?thesis by auto\n                qed\n                also have \"... = at a \\<chi>' j\" using j a A by simp\n                also have \"... = A_B.Map (\\<chi>' j) a\"\n                  using j Curry.uncurry_def E.map_simp \\<chi>'j.is_extensional by simp\n                finally show \"A_B.Map (cones_map f \\<chi> j) a = A_B.Map (\\<chi>' j) a\" by auto\n              qed\n            qed\n          qed\n        qed\n      qed\n    qed\n       \n    text\\<open>\n      If @{term \\<chi>} is a cone with apex @{term a} over @{term D}, then @{term \\<chi>}\n      is a limit cone if, for each object @{term x} of @{term X}, the cone obtained\n      by evaluating @{term \\<chi>} at @{term x} is a limit cone with apex @{term \"A_B.Map a x\"}\n      for the diagram in @{term C} obtained by evaluating @{term D} at @{term x}.\n\\<close>\n\n    lemma cone_is_limit_if_pointwise_limit:\n    assumes cone_\\<chi>: \"cone x \\<chi>\"\n    and \"\\<forall>a. A.ide a \\<longrightarrow> diagram.limit_cone J B (at a D) (A_B.Map x a) (at a \\<chi>)\"\n    shows \"limit_cone x \\<chi>\"\n    proof -\n      interpret \\<chi>: cone J A_B.comp D x \\<chi> using assms by auto\n      have x: \"A_B.ide x\" using \\<chi>.ide_apex by auto\n      show \"limit_cone x \\<chi>\"\n      proof\n        fix x' \\<chi>'\n        assume cone_\\<chi>': \"cone x' \\<chi>'\"\n        interpret \\<chi>': cone J A_B.comp D x' \\<chi>' using cone_\\<chi>' by auto\n        have x': \"A_B.ide x'\" using \\<chi>'.ide_apex by auto\n        text\\<open>\n          The universality of the limit cone \\<open>at a \\<chi>\\<close> yields, for each object\n          \\<open>a\\<close> of \\<open>A\\<close>, a unique arrow \\<open>fa\\<close> that transforms\n          \\<open>at a \\<chi>\\<close> to \\<open>at a \\<chi>'\\<close>.\n\\<close>\n        have EU: \"\\<And>a. A.ide a \\<Longrightarrow>\n                        \\<exists>!fa. fa \\<in> B.hom (A_B.Map x' a) (A_B.Map x a) \\<and>\n                                   diagram.cones_map J B (at a D) fa (at a \\<chi>) = at a \\<chi>'\"\n        proof -\n          fix a\n          assume a: \"A.ide a\"\n          interpret Da: diagram J B \\<open>at a D\\<close> using a at_ide_is_diagram by auto\n          interpret \\<chi>a: limit_cone J B \\<open>at a D\\<close> \\<open>A_B.Map x a\\<close> \\<open>at a \\<chi>\\<close>\n            using assms(2) a by auto\n          interpret \\<chi>'a: cone J B \\<open>at a D\\<close> \\<open>A_B.Map x' a\\<close> \\<open>at a \\<chi>'\\<close>\n            using a cone_\\<chi>' cone_at_ide_is_cone by auto\n          have \"Da.cone (A_B.Map x' a) (at a \\<chi>')\" ..\n          thus \"\\<exists>!fa. fa \\<in> B.hom (A_B.Map x' a) (A_B.Map x a) \\<and>\n                      Da.cones_map fa (at a \\<chi>) = at a \\<chi>'\"\n            using \\<chi>a.is_universal by simp\n        qed\n        text\\<open>\n          Our objective is to show the existence of a unique arrow \\<open>f\\<close> that transforms\n          \\<open>\\<chi>\\<close> into \\<open>\\<chi>'\\<close>.  We obtain \\<open>f\\<close> by bundling the arrows \\<open>fa\\<close>\n          of \\<open>C\\<close> and proving that this yields a natural transformation from \\<open>X\\<close>\n          to \\<open>C\\<close>, hence an arrow of \\<open>[X, C]\\<close>.\n\\<close>\n        show \"\\<exists>!f. \\<guillemotleft>f : x' \\<rightarrow>\\<^sub>[\\<^sub>A\\<^sub>,\\<^sub>B\\<^sub>] x\\<guillemotright> \\<and> cones_map f \\<chi> = \\<chi>'\"\n        proof\n          let ?P = \"\\<lambda>a fa. \\<guillemotleft>fa : A_B.Map x' a \\<rightarrow>\\<^sub>B A_B.Map x a\\<guillemotright> \\<and>\n                           diagram.cones_map J B (at a D) fa (at a \\<chi>) = at a \\<chi>'\"\n          have AaPa: \"\\<And>a. A.ide a \\<Longrightarrow> ?P a (THE fa. ?P a fa)\"\n          proof -\n            fix a\n            assume a: \"A.ide a\"\n            have \"\\<exists>!fa. ?P a fa\" using a EU by simp\n            thus \"?P a (THE fa. ?P a fa)\" using a theI' [of \"?P a\"] by fastforce\n          qed\n          have AaPa_in_hom:\n              \"\\<And>a. A.ide a \\<Longrightarrow> \\<guillemotleft>THE fa. ?P a fa : A_B.Map x' a \\<rightarrow>\\<^sub>B A_B.Map x a\\<guillemotright>\"\n            using AaPa by blast\n          have AaPa_map:\n                  \"\\<And>a. A.ide a \\<Longrightarrow>\n                       diagram.cones_map J B (at a D) (THE fa. ?P a fa) (at a \\<chi>) = at a \\<chi>'\"\n            using AaPa by blast\n          let ?Fun_f = \"\\<lambda>a. if A.ide a then (THE fa. ?P a fa) else B.null\"\n          interpret Fun_x: \"functor\" A B \\<open>\\<lambda>a. A_B.Map x a\\<close>\n            using x A_B.ide_char by simp\n          interpret Fun_x': \"functor\" A B \\<open>\\<lambda>a. A_B.Map x' a\\<close>\n            using x' A_B.ide_char by simp\n          text\\<open>\n            The arrows \\<open>Fun_f a\\<close> are the components of a natural transformation.\n            It is more work to verify the naturality than it seems like it ought to be.\n\\<close>\n          interpret \\<phi>: transformation_by_components A B\n                         \\<open>\\<lambda>a. A_B.Map x' a\\<close> \\<open>\\<lambda>a. A_B.Map x a\\<close> ?Fun_f\n          proof\n            fix a\n            assume a: \"A.ide a\"\n            show \"\\<guillemotleft>?Fun_f a : A_B.Map x' a \\<rightarrow>\\<^sub>B A_B.Map x a\\<guillemotright>\" using a AaPa by simp\n            next\n            fix a\n            assume a: \"A.arr a\"\n            text\\<open>\n\\newcommand\\xdom{\\mathop{\\rm dom}}\n\\newcommand\\xcod{\\mathop{\\rm cod}}\n$$\\xymatrix{\n  {x_{\\xdom a}} \\drtwocell\\omit{\\omit(A)} \\ar[d]_{\\chi_{\\xdom a}} \\ar[r]^{x_a} & {x_{\\xcod a}}\n     \\ar[d]^{\\chi_{\\xcod a}} \\\\\n  {D_{\\xdom a}} \\ar[r]^{D_a} & {D_{\\xcod a}} \\\\\n  {x'_{\\xdom a}} \\urtwocell\\omit{\\omit(B)} \\ar@/^5em/[uu]^{f_{\\xdom a}}_{\\hspace{1em}(C)} \\ar[u]^{\\chi'_{\\xdom a}}\n     \\ar[r]_{x'_a} & {x'_{\\xcod a}} \\ar[u]_{x'_{\\xcod a}} \\ar@/_5em/[uu]_{f_{\\xcod a}}\n}$$\n\\<close>\n            let ?x_dom_a = \"A_B.Map x (A.dom a)\"\n            let ?x_cod_a = \"A_B.Map x (A.cod a)\"\n            let ?x_a = \"A_B.Map x a\"\n            have x_a: \"\\<guillemotleft>?x_a : ?x_dom_a \\<rightarrow>\\<^sub>B ?x_cod_a\\<guillemotright>\"\n              using a x A_B.ide_char by auto\n            have x_dom_a: \"B.ide ?x_dom_a\" using a by simp\n            have x_cod_a: \"B.ide ?x_cod_a\" using a by simp\n            let ?x'_dom_a = \"A_B.Map x' (A.dom a)\"\n            let ?x'_cod_a = \"A_B.Map x' (A.cod a)\"\n            let ?x'_a = \"A_B.Map x' a\"\n            have x'_a: \"\\<guillemotleft>?x'_a : ?x'_dom_a \\<rightarrow>\\<^sub>B ?x'_cod_a\\<guillemotright>\"\n              using a x' A_B.ide_char by auto\n            have x'_dom_a: \"B.ide ?x'_dom_a\" using a by simp\n            have x'_cod_a: \"B.ide ?x'_cod_a\" using a by simp\n            let ?f_dom_a = \"?Fun_f (A.dom a)\"\n            let ?f_cod_a = \"?Fun_f (A.cod a)\"\n            have f_dom_a: \"\\<guillemotleft>?f_dom_a : ?x'_dom_a \\<rightarrow>\\<^sub>B ?x_dom_a\\<guillemotright>\" using a AaPa by simp\n            have f_cod_a: \"\\<guillemotleft>?f_cod_a : ?x'_cod_a \\<rightarrow>\\<^sub>B ?x_cod_a\\<guillemotright>\" using a AaPa by simp\n            interpret D_dom_a: diagram J B \\<open>at (A.dom a) D\\<close> using a at_ide_is_diagram by simp\n            interpret D_cod_a: diagram J B \\<open>at (A.cod a) D\\<close> using a at_ide_is_diagram by simp\n            interpret Da: natural_transformation J B \\<open>at (A.dom a) D\\<close> \\<open>at (A.cod a) D\\<close> \\<open>at a D\\<close>\n              using a functor_axioms functor_at_arr_is_transformation by simp\n            interpret \\<chi>_dom_a: limit_cone J B \\<open>at (A.dom a) D\\<close> \\<open>A_B.Map x (A.dom a)\\<close>\n                                              \\<open>at (A.dom a) \\<chi>\\<close>\n              using assms(2) a by auto\n            interpret \\<chi>_cod_a: limit_cone J B \\<open>at (A.cod a) D\\<close> \\<open>A_B.Map x (A.cod a)\\<close>\n                                              \\<open>at (A.cod a) \\<chi>\\<close>\n              using assms(2) a by auto\n            interpret \\<chi>'_dom_a: cone J B \\<open>at (A.dom a) D\\<close> \\<open>A_B.Map x' (A.dom a)\\<close> \\<open>at (A.dom a) \\<chi>'\\<close>\n              using a cone_\\<chi>' cone_at_ide_is_cone by auto\n            interpret \\<chi>'_cod_a: cone J B \\<open>at (A.cod a) D\\<close> \\<open>A_B.Map x' (A.cod a)\\<close> \\<open>at (A.cod a) \\<chi>'\\<close>\n              using a cone_\\<chi>' cone_at_ide_is_cone by auto\n            text\\<open>\n              Now construct cones with apexes \\<open>x_dom_a\\<close> and \\<open>x'_dom_a\\<close>\n              over @{term \"at (A.cod a) D\"} by forming the vertical composites of\n              @{term \"at (A.dom a) \\<chi>\"} and @{term \"at (A.cod a) \\<chi>'\"} with the natural\n              transformation @{term \"at a D\"}.\n\\<close>\n            interpret Dao\\<chi>_dom_a: vertical_composite J B\n                                    \\<chi>_dom_a.A.map \\<open>at (A.dom a) D\\<close> \\<open>at (A.cod a) D\\<close>\n                                    \\<open>at (A.dom a) \\<chi>\\<close> \\<open>at a D\\<close> ..\n            interpret Dao\\<chi>_dom_a: cone J B \\<open>at (A.cod a) D\\<close> ?x_dom_a Dao\\<chi>_dom_a.map\n              using \\<chi>_dom_a.cone_axioms Da.natural_transformation_axioms vcomp_transformation_cone\n              by metis\n            interpret Dao\\<chi>'_dom_a: vertical_composite J B\n                                     \\<chi>'_dom_a.A.map \\<open>at (A.dom a) D\\<close> \\<open>at (A.cod a) D\\<close>\n                                     \\<open>at (A.dom a) \\<chi>'\\<close> \\<open>at a D\\<close> ..\n            interpret Dao\\<chi>'_dom_a: cone J B \\<open>at (A.cod a) D\\<close> ?x'_dom_a Dao\\<chi>'_dom_a.map\n              using \\<chi>'_dom_a.cone_axioms Da.natural_transformation_axioms vcomp_transformation_cone\n              by metis\n            have Dao\\<chi>_dom_a: \"D_cod_a.cone ?x_dom_a Dao\\<chi>_dom_a.map\" ..\n            have Dao\\<chi>'_dom_a: \"D_cod_a.cone ?x'_dom_a Dao\\<chi>'_dom_a.map\" ..\n            text\\<open>\n              These cones are also obtained by transforming the cones @{term \"at (A.cod a) \\<chi>\"}\n              and @{term \"at (A.cod a) \\<chi>'\"} by \\<open>x_a\\<close> and \\<open>x'_a\\<close>, respectively.\n\\<close>\n            have A: \"Dao\\<chi>_dom_a.map = D_cod_a.cones_map ?x_a (at (A.cod a) \\<chi>)\"\n            proof\n              fix j\n              have \"\\<not>J.arr j \\<Longrightarrow> Dao\\<chi>_dom_a.map j = D_cod_a.cones_map ?x_a (at (A.cod a) \\<chi>) j\"\n                using Dao\\<chi>_dom_a.is_extensional \\<chi>_cod_a.cone_axioms x_a by force\n              moreover have\n                   \"J.arr j \\<Longrightarrow> Dao\\<chi>_dom_a.map j = D_cod_a.cones_map ?x_a (at (A.cod a) \\<chi>) j\"\n              proof -\n                assume j: \"J.arr j\"\n                have \"Dao\\<chi>_dom_a.map j = at a D j \\<cdot>\\<^sub>B at (A.dom a) \\<chi> (J.dom j)\"\n                  using j Dao\\<chi>_dom_a.map_simp_2 by simp\n                also have \"... = A_B.Map (D j) a \\<cdot>\\<^sub>B A_B.Map (\\<chi> (J.dom j)) (A.dom a)\"\n                  using a j at_simp by simp\n                also have \"... = A_B.Map (A_B.comp (D j) (\\<chi> (J.dom j))) a\"\n                  using a j A_B.Map_comp\n                  by (metis (no_types, lifting) A.comp_arr_dom \\<chi>.is_natural_1\n                      \\<chi>.preserves_reflects_arr)\n                also have \"... = A_B.Map (A_B.comp (\\<chi> (J.cod j)) (\\<chi>.A.map j)) a\"\n                  using a j \\<chi>.naturality by simp\n                also have \"... = A_B.Map (\\<chi> (J.cod j)) (A.cod a) \\<cdot>\\<^sub>B A_B.Map x a\"\n                  using a j x A_B.Map_comp\n                  by (metis (no_types, lifting) A.comp_cod_arr \\<chi>.A.map_simp \\<chi>.is_natural_2\n                            \\<chi>.preserves_reflects_arr)\n                also have \"... = at (A.cod a) \\<chi> (J.cod j) \\<cdot>\\<^sub>B A_B.Map x a\"\n                  using a j at_simp by simp\n                also have \"... = at (A.cod a) \\<chi> j \\<cdot>\\<^sub>B A_B.Map x a\"\n                  using a j \\<chi>_cod_a.is_natural_2 \\<chi>_cod_a.A.map_simp\n                  by (metis J.arr_cod_iff_arr J.cod_cod)\n                also have \"... = D_cod_a.cones_map ?x_a (at (A.cod a) \\<chi>) j\"\n                  using a j x \\<chi>_cod_a.cone_axioms preserves_cod by simp\n                finally show ?thesis by blast\n              qed\n              ultimately show \"Dao\\<chi>_dom_a.map j = D_cod_a.cones_map ?x_a (at (A.cod a) \\<chi>) j\"\n                by blast\n            qed\n            have B: \"Dao\\<chi>'_dom_a.map = D_cod_a.cones_map ?x'_a (at (A.cod a) \\<chi>')\"\n            proof\n              fix j\n              have\n                  \"\\<not>J.arr j \\<Longrightarrow> Dao\\<chi>'_dom_a.map j = D_cod_a.cones_map ?x'_a (at (A.cod a) \\<chi>') j\"\n                using Dao\\<chi>'_dom_a.is_extensional \\<chi>'_cod_a.cone_axioms x'_a by force\n              moreover have\n                  \"J.arr j \\<Longrightarrow> Dao\\<chi>'_dom_a.map j = D_cod_a.cones_map ?x'_a (at (A.cod a) \\<chi>') j\"\n              proof -\n                assume j: \"J.arr j\"\n                have \"Dao\\<chi>'_dom_a.map j = at a D j \\<cdot>\\<^sub>B at (A.dom a) \\<chi>' (J.dom j)\"\n                  using j Dao\\<chi>'_dom_a.map_simp_2 by simp\n                also have \"... = A_B.Map (D j) a \\<cdot>\\<^sub>B A_B.Map (\\<chi>' (J.dom j)) (A.dom a)\"\n                  using a j at_simp by simp\n                also have \"... = A_B.Map (A_B.comp (D j) (\\<chi>' (J.dom j))) a\"\n                  using a j A_B.Map_comp\n                  by (metis (no_types, lifting) A.comp_arr_dom \\<chi>'.is_natural_1\n                      \\<chi>'.preserves_reflects_arr)\n                also have \"... = A_B.Map (A_B.comp (\\<chi>' (J.cod j)) (\\<chi>'.A.map j)) a\"\n                  using a j \\<chi>'.naturality by simp\n                also have \"... = A_B.Map (\\<chi>' (J.cod j)) (A.cod a) \\<cdot>\\<^sub>B A_B.Map x' a\"\n                  using a j x' A_B.Map_comp\n                  by (metis (no_types, lifting) A.comp_cod_arr \\<chi>'.A.map_simp \\<chi>'.is_natural_2\n                            \\<chi>'.preserves_reflects_arr)\n                also have \"... = at (A.cod a) \\<chi>' (J.cod j) \\<cdot>\\<^sub>B A_B.Map x' a\"\n                  using a j at_simp by simp\n                also have \"... = at (A.cod a) \\<chi>' j \\<cdot>\\<^sub>B A_B.Map x' a\"\n                  using a j \\<chi>'_cod_a.is_natural_2 \\<chi>'_cod_a.A.map_simp\n                  by (metis J.arr_cod_iff_arr J.cod_cod)\n                also have \"... = D_cod_a.cones_map ?x'_a (at (A.cod a) \\<chi>') j\"\n                  using a j x' \\<chi>'_cod_a.cone_axioms preserves_cod by simp\n                finally show ?thesis by blast\n              qed\n              ultimately show\n                  \"Dao\\<chi>'_dom_a.map j = D_cod_a.cones_map ?x'_a (at (A.cod a) \\<chi>') j\"\n                by blast\n            qed\n            text\\<open>\n              Next, we show that \\<open>f_dom_a\\<close>, which is the unique arrow that transforms\n              \\<open>\\<chi>_dom_a\\<close> into \\<open>\\<chi>'_dom_a\\<close>, is also the unique arrow that transforms\n              \\<open>Dao\\<chi>_dom_a\\<close> into \\<open>Dao\\<chi>'_dom_a\\<close>.\n\\<close>\n            have C: \"D_cod_a.cones_map ?f_dom_a Dao\\<chi>_dom_a.map = Dao\\<chi>'_dom_a.map\"\n            proof (intro NaturalTransformation.eqI)\n              show \"natural_transformation\n                      J B \\<chi>'_dom_a.A.map (at (A.cod a) D) Dao\\<chi>'_dom_a.map\" ..\n              show \"natural_transformation J B \\<chi>'_dom_a.A.map (at (A.cod a) D)\n                      (D_cod_a.cones_map ?f_dom_a Dao\\<chi>_dom_a.map)\"\n              proof -\n                interpret \\<kappa>: cone J B \\<open>at (A.cod a) D\\<close> ?x'_dom_a\n                                  \\<open>D_cod_a.cones_map ?f_dom_a Dao\\<chi>_dom_a.map\\<close>\n                proof -\n                  have 1: \"\\<And>b b' f. \\<lbrakk> f \\<in> B.hom b' b; D_cod_a.cone b Dao\\<chi>_dom_a.map \\<rbrakk>\n                                     \\<Longrightarrow> D_cod_a.cone b' (D_cod_a.cones_map f Dao\\<chi>_dom_a.map)\"\n                    using D_cod_a.cones_map_mapsto by blast\n                  have \"D_cod_a.cone ?x_dom_a Dao\\<chi>_dom_a.map\" ..\n                  thus \"D_cod_a.cone ?x'_dom_a (D_cod_a.cones_map ?f_dom_a Dao\\<chi>_dom_a.map)\"\n                    using f_dom_a 1 by simp\n                qed\n                show ?thesis ..\n              qed\n              show \"\\<And>j. J.ide j \\<Longrightarrow>\n                          D_cod_a.cones_map ?f_dom_a Dao\\<chi>_dom_a.map j = Dao\\<chi>'_dom_a.map j\"\n              proof -\n                fix j\n                assume j: \"J.ide j\"\n                have \"D_cod_a.cones_map ?f_dom_a Dao\\<chi>_dom_a.map j =\n                      Dao\\<chi>_dom_a.map j \\<cdot>\\<^sub>B ?f_dom_a\"\n                  using j f_dom_a Dao\\<chi>_dom_a.cone_axioms\n                  by (elim B.in_homE, auto)\n                also have \"... = (at a D j \\<cdot>\\<^sub>B at (A.dom a) \\<chi> j) \\<cdot>\\<^sub>B ?f_dom_a\"\n                  using j Dao\\<chi>_dom_a.map_simp_ide by simp\n                also have \"... = at a D j \\<cdot>\\<^sub>B at (A.dom a) \\<chi> j \\<cdot>\\<^sub>B ?f_dom_a\"\n                  using B.comp_assoc by simp\n                also have \"... = at a D j \\<cdot>\\<^sub>B D_dom_a.cones_map ?f_dom_a (at (A.dom a) \\<chi>) j\"\n                  using j \\<chi>_dom_a.cone_axioms f_dom_a\n                  by (elim B.in_homE, auto)\n                also have \"... = at a D j \\<cdot>\\<^sub>B at (A.dom a) \\<chi>' j\"\n                  using a AaPa A.ide_dom by presburger\n                also have \"... = Dao\\<chi>'_dom_a.map j\"\n                  using j Dao\\<chi>'_dom_a.map_simp_ide by simp\n                finally show\n                    \"D_cod_a.cones_map ?f_dom_a Dao\\<chi>_dom_a.map j = Dao\\<chi>'_dom_a.map j\"\n                  by auto\n              qed\n            qed\n            text\\<open>\n              Naturality amounts to showing that \\<open>C f_cod_a x'_a = C x_a f_dom_a\\<close>.\n              To do this, we show that both arrows transform @{term \"at (A.cod a) \\<chi>\"}\n              into \\<open>Dao\\<chi>'_cod_a\\<close>, thus they are equal by the universality of\n              @{term \"at (A.cod a) \\<chi>\"}.\n\\<close>\n            have \"\\<exists>!fa. \\<guillemotleft>fa : ?x'_dom_a \\<rightarrow>\\<^sub>B ?x_cod_a\\<guillemotright> \\<and>\n                        D_cod_a.cones_map fa (at (A.cod a) \\<chi>) = Dao\\<chi>'_dom_a.map\"\n              using Dao\\<chi>'_dom_a.cone_axioms a \\<chi>_cod_a.is_universal [of ?x'_dom_a Dao\\<chi>'_dom_a.map]\n              by fast\n            moreover have\n                 \"?f_cod_a \\<cdot>\\<^sub>B ?x'_a \\<in> B.hom ?x'_dom_a ?x_cod_a \\<and>\n                  D_cod_a.cones_map (?f_cod_a \\<cdot>\\<^sub>B ?x'_a) (at (A.cod a) \\<chi>) = Dao\\<chi>'_dom_a.map\"\n            proof\n              show \"?f_cod_a \\<cdot>\\<^sub>B ?x'_a \\<in> B.hom ?x'_dom_a ?x_cod_a\"\n                using f_cod_a x'_a by blast\n              show \"D_cod_a.cones_map (?f_cod_a \\<cdot>\\<^sub>B ?x'_a) (at (A.cod a) \\<chi>) = Dao\\<chi>'_dom_a.map\"\n              proof -\n                have 1: \"B.arr (?f_cod_a \\<cdot>\\<^sub>B ?x'_a)\"\n                  using f_cod_a x'_a by (elim B.in_homE, auto)\n                hence \"D_cod_a.cones_map (?f_cod_a \\<cdot>\\<^sub>B ?x'_a) (at (A.cod a) \\<chi>)\n                         = restrict (D_cod_a.cones_map ?x'_a o D_cod_a.cones_map ?f_cod_a)\n                                    (D_cod_a.cones (?x_cod_a))\n                                    (at (A.cod a) \\<chi>)\"\n                  using D_cod_a.cones_map_comp [of ?f_cod_a ?x'_a] f_cod_a\n                  by (elim B.in_homE, auto)\n                also have \"... = D_cod_a.cones_map ?x'_a\n                                   (D_cod_a.cones_map ?f_cod_a (at (A.cod a) \\<chi>))\"\n                  using \\<chi>_cod_a.cone_axioms by simp\n                also have \"... = Dao\\<chi>'_dom_a.map\"\n                  using a B AaPa_map A.ide_cod by presburger\n                finally show ?thesis by auto\n              qed\n            qed\n            moreover have\n                 \"?x_a \\<cdot>\\<^sub>B ?f_dom_a \\<in> B.hom ?x'_dom_a ?x_cod_a \\<and>\n                  D_cod_a.cones_map (?x_a \\<cdot>\\<^sub>B ?f_dom_a) (at (A.cod a) \\<chi>) = Dao\\<chi>'_dom_a.map\"\n            proof\n              show \"?x_a \\<cdot>\\<^sub>B ?f_dom_a \\<in> B.hom ?x'_dom_a ?x_cod_a\"\n                using f_dom_a x_a by blast\n              show \"D_cod_a.cones_map (?x_a \\<cdot>\\<^sub>B ?f_dom_a) (at (A.cod a) \\<chi>) = Dao\\<chi>'_dom_a.map\"\n              proof -\n                have\n                    \"D_cod_a.cones (B.cod (A_B.Map x a)) = D_cod_a.cones (A_B.Map x (A.cod a))\"\n                  using a x by simp\n                moreover have \"B.seq ?x_a ?f_dom_a\"\n                  using f_dom_a x_a by (elim B.in_homE, auto)\n                ultimately have\n                     \"D_cod_a.cones_map (?x_a \\<cdot>\\<^sub>B ?f_dom_a) (at (A.cod a) \\<chi>)\n                         = restrict (D_cod_a.cones_map ?f_dom_a o D_cod_a.cones_map ?x_a)\n                                    (D_cod_a.cones (?x_cod_a))\n                                    (at (A.cod a) \\<chi>)\"\n                  using D_cod_a.cones_map_comp [of ?x_a ?f_dom_a] x_a by argo\n                also have \"... = D_cod_a.cones_map ?f_dom_a\n                                   (D_cod_a.cones_map ?x_a (at (A.cod a) \\<chi>))\"\n                  using \\<chi>_cod_a.cone_axioms by simp\n                also have \"... = Dao\\<chi>'_dom_a.map\"\n                  using A C a AaPa by argo\n                finally show ?thesis by blast\n              qed\n            qed\n            ultimately show \"?f_cod_a \\<cdot>\\<^sub>B ?x'_a = ?x_a \\<cdot>\\<^sub>B ?f_dom_a\"\n              using a \\<chi>_cod_a.is_universal by blast\n          qed\n          text\\<open>\n            The arrow from @{term x'} to @{term x} in \\<open>[A, B]\\<close> determined by\n            the natural transformation \\<open>\\<phi>\\<close> transforms @{term \\<chi>} into @{term \\<chi>'}.\n            Moreover, it is the unique such arrow, since the components of \\<open>\\<phi>\\<close>\n            are each determined by universality.\n\\<close>\n          let ?f = \"A_B.MkArr (\\<lambda>a. A_B.Map x' a) (\\<lambda>a. A_B.Map x a) \\<phi>.map\"\n          have f_in_hom: \"?f \\<in> A_B.hom x' x\"\n          proof -\n            have arr_f: \"A_B.arr ?f\"\n              using x' x A_B.arr_MkArr \\<phi>.natural_transformation_axioms by simp\n            moreover have \"A_B.MkIde (\\<lambda>a. A_B.Map x a) = x\"\n              using x A_B.ide_char A_B.MkArr_Map A_B.in_homE A_B.ide_in_hom by metis\n            moreover have \"A_B.MkIde (\\<lambda>a. A_B.Map x' a) = x'\"\n              using x' A_B.ide_char A_B.MkArr_Map A_B.in_homE A_B.ide_in_hom by metis\n            ultimately show ?thesis\n              using A_B.dom_char A_B.cod_char by auto\n          qed\n          have Fun_f: \"\\<And>a. A.ide a \\<Longrightarrow> A_B.Map ?f a = (THE fa. ?P a fa)\"\n            using f_in_hom \\<phi>.map_simp_ide by fastforce\n          have cones_map_f: \"cones_map ?f \\<chi> = \\<chi>'\"\n            using AaPa Fun_f at_ide_is_diagram assms(2) x x' cone_\\<chi> cone_\\<chi>' f_in_hom Fun_f\n                  cones_map_pointwise\n            by presburger\n          show \"\\<guillemotleft>?f : x' \\<rightarrow>\\<^sub>[\\<^sub>A\\<^sub>,\\<^sub>B\\<^sub>] x\\<guillemotright> \\<and> cones_map ?f \\<chi> = \\<chi>'\" using f_in_hom cones_map_f by auto\n          show \"\\<And>f'. \\<guillemotleft>f' : x' \\<rightarrow>\\<^sub>[\\<^sub>A\\<^sub>,\\<^sub>B\\<^sub>] x\\<guillemotright> \\<and> cones_map f' \\<chi> = \\<chi>' \\<Longrightarrow> f' = ?f\"\n          proof -\n            fix f'\n            assume f': \"\\<guillemotleft>f' : x' \\<rightarrow>\\<^sub>[\\<^sub>A\\<^sub>,\\<^sub>B\\<^sub>] x\\<guillemotright> \\<and> cones_map f' \\<chi> = \\<chi>'\"\n            have 0: \"\\<And>a. A.ide a \\<Longrightarrow>\n                           diagram.cones_map J B (at a D) (A_B.Map f' a) (at a \\<chi>) = at a \\<chi>'\"\n              using f' cone_\\<chi> cone_\\<chi>' cones_map_pointwise by blast\n            have \"f' = A_B.MkArr (A_B.Dom f') (A_B.Cod f') (A_B.Map f')\"\n              using f' A_B.MkArr_Map by auto\n            also have \"... = ?f\"\n            proof (intro A_B.MkArr_eqI)\n              show \"A_B.arr (A_B.MkArr (A_B.Dom f') (A_B.Cod f') (A_B.Map f'))\"\n                using f' calculation by blast\n              show 1: \"A_B.Dom f' = A_B.Map x'\" using f' A_B.Map_dom by auto\n              show 2: \"A_B.Cod f' = A_B.Map x\" using f' A_B.Map_cod by auto\n              show \"A_B.Map f' = \\<phi>.map\"\n              proof (intro NaturalTransformation.eqI)\n                show \"natural_transformation A B (A_B.Map x') (A_B.Map x) \\<phi>.map\" ..\n                show \"natural_transformation A B (A_B.Map x') (A_B.Map x) (A_B.Map f')\"\n                  using f' 1 2 A_B.arr_char [of f'] by auto\n                show \"\\<And>a. A.ide a \\<Longrightarrow> A_B.Map f' a = \\<phi>.map a\"\n                proof -\n                  fix a\n                  assume a: \"A.ide a\"\n                  interpret Da: diagram J B \\<open>at a D\\<close> using a at_ide_is_diagram by auto\n                  interpret Fun_f': natural_transformation A B \\<open>A_B.Dom f'\\<close> \\<open>A_B.Cod f'\\<close>\n                                                           \\<open>A_B.Map f'\\<close>\n                    using f' A_B.arr_char by fast\n                  have \"A_B.Map f' a \\<in> B.hom (A_B.Map x' a) (A_B.Map x a)\"\n                    using a f' Fun_f'.preserves_hom A.ide_in_hom by auto\n                  hence \"?P a (A_B.Map f' a)\" using a 0 [of a] by simp\n                  moreover have \"?P a (\\<phi>.map a)\"\n                    using a \\<phi>.map_simp_ide Fun_f AaPa by presburger\n                  ultimately show \"A_B.Map f' a = \\<phi>.map a\" using a EU by blast\n                qed\n              qed\n            qed\n            finally show \"f' = ?f\" by auto\n          qed\n        qed\n      qed\n    qed\n\n  end\n\n  context functor_category\n  begin\n\n    text\\<open>\n      A functor category \\<open>[A, B]\\<close> has limits of shape @{term[source=true] J}\n      whenever @{term B} has limits of shape @{term[source=true] J}.\n\\<close>\n\n    lemma has_limits_of_shape_if_target_does:\n    assumes \"category (J :: 'j comp)\"\n    and \"B.has_limits_of_shape J\"\n    shows \"has_limits_of_shape J\"\n    proof (unfold has_limits_of_shape_def)\n      have \"\\<And>D. diagram J comp D \\<Longrightarrow> (\\<exists>x \\<chi>. limit_cone J comp D x \\<chi>)\"\n      proof -\n        fix D\n        assume D: \"diagram J comp D\"\n        interpret J: category J using assms(1) by auto\n        interpret JxA: product_category J A ..\n        interpret D: diagram J comp D using D by auto\n        interpret D: diagram_in_functor_category A B J D ..\n        interpret Curry: currying J A B ..\n        text\\<open>\n          Given diagram @{term D} in \\<open>[A, B]\\<close>, choose for each object \\<open>a\\<close>\n          of \\<open>A\\<close> a limit cone \\<open>(la, \\<chi>a)\\<close> for \\<open>at a D\\<close> in \\<open>B\\<close>.\n\\<close>\n        let ?l = \"\\<lambda>a. diagram.some_limit J B (D.at a D)\"\n        let ?\\<chi> = \"\\<lambda>a. diagram.some_limit_cone J B (D.at a D)\"\n        have l\\<chi>: \"\\<And>a. A.ide a \\<Longrightarrow> diagram.limit_cone J B (D.at a D) (?l a) (?\\<chi> a)\"\n        proof -\n          fix a\n          assume a: \"A.ide a\"\n          interpret Da: diagram J B \\<open>D.at a D\\<close>\n            using a D.at_ide_is_diagram by blast\n          show \"limit_cone J B (D.at a D) (?l a) (?\\<chi> a)\"\n            using assms(2) B.has_limits_of_shape_def Da.diagram_axioms\n                  Da.limit_cone_some_limit_cone\n            by auto\n        qed\n        text\\<open>\n          The choice of limit cones induces a limit functor from \\<open>A\\<close> to \\<open>B\\<close>.\n\\<close>\n        interpret uncurry_D: diagram JxA.comp B \"Curry.uncurry D\"\n        proof -\n          interpret \"functor\" JxA.comp B \\<open>Curry.uncurry D\\<close>\n            using D.functor_axioms Curry.uncurry_preserves_functors by simp\n          interpret binary_functor J A B \\<open>Curry.uncurry D\\<close> ..\n          show \"diagram JxA.comp B (Curry.uncurry D)\" ..\n        qed\n        interpret uncurry_D: parametrized_diagram J A B \\<open>Curry.uncurry D\\<close> ..\n        let ?L = \"uncurry_D.L ?l ?\\<chi>\"\n        let ?P = \"uncurry_D.P ?l ?\\<chi>\"\n        interpret L: \"functor\" A B ?L\n          using l\\<chi> uncurry_D.chosen_limits_induce_functor [of ?l ?\\<chi>] by simp\n        have L_ide: \"\\<And>a. A.ide a \\<Longrightarrow> ?L a = ?l a\"\n          using uncurry_D.L_ide [of ?l ?\\<chi>] l\\<chi> by blast\n        have L_arr: \"\\<And>a. A.arr a \\<Longrightarrow> (\\<exists>!f. ?P a f) \\<and> ?P a (?L a)\"\n          using uncurry_D.L_arr [of ?l ?\\<chi>] l\\<chi> by blast\n        have L_arr_in_hom: \"\\<And>a. A.arr a \\<Longrightarrow> \\<guillemotleft>?L a : ?l (A.dom a) \\<rightarrow>\\<^sub>B ?l (A.cod a)\\<guillemotright>\"\n          using L_arr by blast\n        have L_map: \"\\<And>a. A.arr a \\<Longrightarrow> uncurry_D.P ?l ?\\<chi> a (uncurry_D.L ?l ?\\<chi> a)\"\n          using L_arr by blast\n        text\\<open>\n          The functor \\<open>L\\<close> extends to a functor \\<open>L'\\<close> from \\<open>JxA\\<close>\n          to \\<open>B\\<close> that is constant on \\<open>J\\<close>.\n\\<close>\n        let ?L' = \"\\<lambda>ja. if JxA.arr ja then ?L (snd ja) else B.null\"\n        let ?P' = \"\\<lambda>ja. ?P (snd ja)\"\n        interpret L': \"functor\" JxA.comp B ?L'\n          apply unfold_locales\n          using L.preserves_arr L.preserves_dom L.preserves_cod\n              apply auto[4]\n          using L.preserves_comp JxA.comp_char by (elim JxA.seqE, auto)\n        have \"\\<And>ja. JxA.arr ja \\<Longrightarrow> (\\<exists>!f. ?P' ja f) \\<and> ?P' ja (?L' ja)\"\n        proof -\n          fix ja\n          assume ja: \"JxA.arr ja\"\n          have \"A.arr (snd ja)\" using ja by blast\n          thus \"(\\<exists>!f. ?P' ja f) \\<and> ?P' ja (?L' ja)\"\n            using ja L_arr by presburger\n        qed\n        hence L'_arr: \"\\<And>ja. JxA.arr ja \\<Longrightarrow> ?P' ja (?L' ja)\" by blast\n        have L'_arr_in_hom:\n             \"\\<And>ja. JxA.arr ja \\<Longrightarrow> \\<guillemotleft>?L' ja : ?l (A.dom (snd ja)) \\<rightarrow>\\<^sub>B ?l (A.cod (snd ja))\\<guillemotright>\"\n          using L'_arr by simp\n        have L'_ide: \"\\<And>ja. \\<lbrakk> J.arr (fst ja); A.ide (snd ja) \\<rbrakk> \\<Longrightarrow> ?L' ja = ?l (snd ja)\"\n          using L_ide l\\<chi> by force\n        have L'_arr_map:\n             \"\\<And>ja. JxA.arr ja \\<Longrightarrow> uncurry_D.P ?l ?\\<chi> (snd ja) (uncurry_D.L ?l ?\\<chi> (snd ja))\"\n           using L'_arr by presburger\n        text\\<open>\n          The map that takes an object \\<open>(j, a)\\<close> of \\<open>JxA\\<close> to the component\n          \\<open>\\<chi> a j\\<close> of the limit cone \\<open>\\<chi> a\\<close> is a natural transformation\n          from \\<open>L\\<close> to uncurry \\<open>D\\<close>.\n\\<close>\n        let ?\\<chi>' = \"\\<lambda>ja. ?\\<chi> (snd ja) (fst ja)\"\n        interpret \\<chi>': transformation_by_components JxA.comp B ?L' \\<open>Curry.uncurry D\\<close> ?\\<chi>'\n        proof\n          fix ja\n          assume ja: \"JxA.ide ja\"\n          let ?j = \"fst ja\"\n          let ?a = \"snd ja\"\n          interpret \\<chi>a: limit_cone J B \\<open>D.at ?a D\\<close> \\<open>?l ?a\\<close> \\<open>?\\<chi> ?a\\<close>\n            using ja l\\<chi> by blast\n          show \"\\<guillemotleft>?\\<chi>' ja : ?L' ja \\<rightarrow>\\<^sub>B Curry.uncurry D ja\\<guillemotright>\"\n            using ja L'_ide [of ja] by force\n          next\n          fix ja\n          assume ja: \"JxA.arr ja\"\n          let ?j = \"fst ja\"\n          let ?a = \"snd ja\"\n          have j: \"J.arr ?j\" using ja by simp\n          have a: \"A.arr ?a\" using ja by simp\n          interpret D_dom_a: diagram J B \\<open>D.at (A.dom ?a) D\\<close>\n            using a D.at_ide_is_diagram by auto\n          interpret D_cod_a: diagram J B \\<open>D.at (A.cod ?a) D\\<close>\n            using a D.at_ide_is_diagram by auto\n          interpret Da: natural_transformation J B \\<open>D.at (A.dom ?a) D\\<close> \\<open>D.at (A.cod ?a) D\\<close>\n                                                   \\<open>D.at ?a D\\<close>\n            using a D.functor_axioms D.functor_at_arr_is_transformation by simp\n          interpret \\<chi>_dom_a: limit_cone J B \\<open>D.at (A.dom ?a) D\\<close> \\<open>?l (A.dom ?a)\\<close> \\<open>?\\<chi> (A.dom ?a)\\<close>\n            using a l\\<chi> by simp\n          interpret \\<chi>_cod_a: limit_cone J B \\<open>D.at (A.cod ?a) D\\<close> \\<open>?l (A.cod ?a)\\<close> \\<open>?\\<chi> (A.cod ?a)\\<close>\n            using a l\\<chi> by simp\n          interpret Dao\\<chi>_dom_a: vertical_composite J B\n                                  \\<chi>_dom_a.A.map \\<open>D.at (A.dom ?a) D\\<close> \\<open>D.at (A.cod ?a) D\\<close>\n                                  \\<open>?\\<chi> (A.dom ?a)\\<close> \\<open>D.at ?a D\\<close> ..\n          interpret Dao\\<chi>_dom_a: cone J B \\<open>D.at (A.cod ?a) D\\<close> \\<open>?l (A.dom ?a)\\<close> Dao\\<chi>_dom_a.map ..\n          show \"?\\<chi>' (JxA.cod ja) \\<cdot>\\<^sub>B ?L' ja = B (Curry.uncurry D ja) (?\\<chi>' (JxA.dom ja))\"\n          proof -\n            have \"?\\<chi>' (JxA.cod ja) \\<cdot>\\<^sub>B ?L' ja = ?\\<chi> (A.cod ?a) (J.cod ?j) \\<cdot>\\<^sub>B ?L' ja\"\n              using ja by fastforce\n            also have \"... = D_cod_a.cones_map (?L' ja) (?\\<chi> (A.cod ?a)) (J.cod ?j)\"\n              using ja L'_arr_map [of ja] \\<chi>_cod_a.cone_axioms by auto\n            also have \"... = Dao\\<chi>_dom_a.map (J.cod ?j)\"\n              using ja \\<chi>_cod_a.induced_arrowI Dao\\<chi>_dom_a.cone_axioms L'_arr by presburger\n            also have \"... = D.at ?a D (J.cod ?j) \\<cdot>\\<^sub>B D_dom_a.some_limit_cone (J.cod ?j)\"\n              using ja Dao\\<chi>_dom_a.map_simp_ide by fastforce\n            also have \"... = D.at ?a D (J.cod ?j) \\<cdot>\\<^sub>B D.at (A.dom ?a) D ?j \\<cdot>\\<^sub>B ?\\<chi>' (JxA.dom ja)\"\n              using ja \\<chi>_dom_a.naturality \\<chi>_dom_a.ide_apex apply simp\n              by (metis B.comp_arr_ide \\<chi>_dom_a.preserves_reflects_arr)\n            also have \"... = (D.at ?a D (J.cod ?j) \\<cdot>\\<^sub>B D.at (A.dom ?a) D ?j) \\<cdot>\\<^sub>B ?\\<chi>' (JxA.dom ja)\"\n            proof -\n              have \"B.seq (D.at ?a D (J.cod ?j)) (D.at (A.dom ?a) D ?j)\"\n                using j ja by auto\n              moreover have \"B.seq (D.at (A.dom ?a) D ?j) (?\\<chi>' (JxA.dom ja))\"\n                using j ja by fastforce\n              ultimately show ?thesis using B.comp_assoc by force\n            qed\n            also have \"... = B (D.at ?a D ?j) (?\\<chi>' (JxA.dom ja))\"\n            proof -\n              have \"D.at ?a D (J.cod ?j) \\<cdot>\\<^sub>B D.at (A.dom ?a) D ?j =\n                      Map (D (J.cod ?j)) ?a \\<cdot>\\<^sub>B Map (D ?j) (A.dom ?a)\"\n                using ja D.at_simp by auto\n              also have \"... = Map (comp (D (J.cod ?j)) (D ?j)) (?a \\<cdot>\\<^sub>A A.dom ?a)\"\n                using ja Map_comp D.preserves_hom\n                by (metis (mono_tags, lifting) A.comp_arr_dom D.natural_transformation_axioms\n                    D.preserves_arr a j natural_transformation.is_natural_2)\n              also have \"... = D.at ?a D ?j\"\n                using ja D.at_simp dom_char A.comp_arr_dom by force\n              finally show ?thesis by auto\n           qed\n           also have \"... = Curry.uncurry D ja \\<cdot>\\<^sub>B ?\\<chi>' (JxA.dom ja)\"\n             using Curry.uncurry_def by simp\n           finally show ?thesis by auto\n         qed\n       qed\n       text\\<open>\n         Since \\<open>\\<chi>'\\<close> is constant on \\<open>J\\<close>, \\<open>curry \\<chi>'\\<close> is a cone over \\<open>D\\<close>.\n\\<close>\n       interpret constL: constant_functor J comp \\<open>MkIde ?L\\<close>\n       proof\n         show \"ide (MkIde ?L)\"\n           using L.natural_transformation_axioms MkArr_in_hom ide_in_hom L.functor_axioms\n           by blast\n       qed\n       (* TODO: This seems a little too involved. *)\n       have curry_L': \"constL.map = Curry.curry ?L' ?L' ?L'\"\n       proof\n         fix j\n         have \"\\<not>J.arr j \\<Longrightarrow> constL.map j = Curry.curry ?L' ?L' ?L' j\"\n           using Curry.curry_def constL.is_extensional by simp\n         moreover have \"J.arr j \\<Longrightarrow> constL.map j = Curry.curry ?L' ?L' ?L' j\"\n         proof -\n           assume j: \"J.arr j\"\n           show \"constL.map j = Curry.curry ?L' ?L' ?L' j\"\n           proof -\n             have \"constL.map j = MkIde ?L\" using j constL.map_simp by simp\n             moreover have \"... = MkArr ?L ?L ?L\" by simp\n             moreover have \"... = MkArr (\\<lambda>a. ?L' (J.dom j, a)) (\\<lambda>a. ?L' (J.cod j, a))\n                                        (\\<lambda>a. ?L' (j, a))\"\n               using j constL.value_is_ide in_homE ide_in_hom by (intro MkArr_eqI, auto)\n             moreover have \"... = Curry.curry ?L' ?L' ?L' j\"\n               using j Curry.curry_def by auto\n             ultimately show ?thesis by force\n           qed\n         qed\n         ultimately show \"constL.map j = Curry.curry ?L' ?L' ?L' j\" by blast\n       qed\n       hence uncurry_constL: \"Curry.uncurry constL.map = ?L'\"\n         using L'.natural_transformation_axioms Curry.uncurry_curry by simp\n       interpret curry_\\<chi>': natural_transformation J comp constL.map D\n                             \\<open>Curry.curry ?L' (Curry.uncurry D) \\<chi>'.map\\<close>\n       proof -\n         have 1: \"Curry.curry (Curry.uncurry D) (Curry.uncurry D) (Curry.uncurry D) = D\"\n           using Curry.curry_uncurry D.functor_axioms D.natural_transformation_axioms\n           by blast\n         thus \"natural_transformation J comp constL.map D\n                 (Curry.curry ?L' (Curry.uncurry D) \\<chi>'.map)\"\n           using Curry.curry_preserves_transformations curry_L' \\<chi>'.natural_transformation_axioms\n           by force\n       qed\n       interpret curry_\\<chi>': cone J comp D \\<open>MkIde ?L\\<close> \\<open>Curry.curry ?L' (Curry.uncurry D) \\<chi>'.map\\<close> ..\n       text\\<open>\n         The value of \\<open>curry_\\<chi>'\\<close> at each object \\<open>a\\<close> of \\<open>A\\<close> is the\n         limit cone \\<open>\\<chi> a\\<close>, hence \\<open>curry_\\<chi>'\\<close> is a limit cone.\n\\<close>\n       have 1: \"\\<And>a. A.ide a \\<Longrightarrow> D.at a (Curry.curry ?L' (Curry.uncurry D) \\<chi>'.map) = ?\\<chi> a\"\n       proof -\n         fix a\n         assume a: \"A.ide a\"\n         have \"D.at a (Curry.curry ?L' (Curry.uncurry D) \\<chi>'.map) =\n                 (\\<lambda>j. Curry.uncurry (Curry.curry ?L' (Curry.uncurry D) \\<chi>'.map) (j, a))\"\n           using a by simp\n         moreover have \"... = (\\<lambda>j. \\<chi>'.map (j, a))\"\n           using a Curry.uncurry_curry \\<chi>'.natural_transformation_axioms by simp\n         moreover have \"... = ?\\<chi> a\"\n         proof (intro NaturalTransformation.eqI)\n           interpret \\<chi>a: limit_cone J B \\<open>D.at a D\\<close> \\<open>?l a\\<close> \\<open>?\\<chi> a\\<close> using a l\\<chi> by simp\n           interpret \\<chi>': binary_functor_transformation J A B ?L' \\<open>Curry.uncurry D\\<close> \\<chi>'.map ..\n           show \"natural_transformation J B \\<chi>a.A.map (D.at a D) (?\\<chi> a)\" ..\n           show \"natural_transformation J B \\<chi>a.A.map (D.at a D) (\\<lambda>j. \\<chi>'.map (j, a))\"\n           proof -\n             have \"\\<chi>a.A.map = (\\<lambda>j. ?L' (j, a))\"\n               using a \\<chi>a.A.map_def L'_ide by auto\n             thus ?thesis\n               using a \\<chi>'.fixing_ide_gives_natural_transformation_2 by simp\n           qed\n           fix j\n           assume j: \"J.ide j\"\n           show \"\\<chi>'.map (j, a) = ?\\<chi> a j\"\n             using a j \\<chi>'.map_simp_ide by simp\n         qed\n         ultimately show \"D.at a (Curry.curry ?L' (Curry.uncurry D) \\<chi>'.map) = ?\\<chi> a\" by simp\n       qed\n       hence 2: \"\\<And>a. A.ide a \\<Longrightarrow> diagram.limit_cone J B (D.at a D) (?l a)\n                                (D.at a (Curry.curry ?L' (Curry.uncurry D) \\<chi>'.map))\"\n         using l\\<chi> by simp\n       hence \"limit_cone J comp D (MkIde ?L) (Curry.curry ?L' (Curry.uncurry D) \\<chi>'.map)\"\n       proof -\n         have \"\\<And>a. A.ide a \\<Longrightarrow> Map (MkIde ?L) a = ?l a\"\n           using L.functor_axioms L_ide by simp\n         thus ?thesis\n           using 1 2 curry_\\<chi>'.cone_axioms curry_L' D.cone_is_limit_if_pointwise_limit by simp\n       qed\n       thus \"\\<exists>x \\<chi>. limit_cone J comp D x \\<chi>\" by blast\n     qed\n     thus \"\\<forall>D. diagram J comp D \\<longrightarrow> (\\<exists>x \\<chi>. limit_cone J comp D x \\<chi>)\" by blast\n    qed\n\n    lemma has_limits_if_target_does:\n    assumes \"B.has_limits (undefined :: 'j)\"\n    shows \"has_limits (undefined :: 'j)\"\n      using assms B.has_limits_def has_limits_def has_limits_of_shape_if_target_does by fast\n\n  end\n\n  section \"The Yoneda Functor Preserves Limits\"\n\n  text\\<open>\n    In this section, we show that the Yoneda functor from \\<open>C\\<close> to \\<open>[Cop, S]\\<close>\n    preserves limits.\n\\<close>\n\n  context yoneda_functor\n  begin\n\n    lemma preserves_limits:\n    fixes J :: \"'j comp\"\n    assumes \"diagram J C D\" and \"diagram.has_as_limit J C D a\"\n    shows \"diagram.has_as_limit J Cop_S.comp (map o D) (map a)\"\n    proof -\n      text\\<open>\n        The basic idea of the proof is as follows:\n        If \\<open>\\<chi>\\<close> is a limit cone in \\<open>C\\<close>, then for every object \\<open>a'\\<close>\n        of \\<open>Cop\\<close> the evaluation of \\<open>Y o \\<chi>\\<close> at \\<open>a'\\<close> is a limit cone\n        in \\<open>S\\<close>.  By the results on limits in functor categories,\n        this implies that \\<open>Y o \\<chi>\\<close> is a limit cone in \\<open>[Cop, S]\\<close>.\n\\<close>\n      interpret J: category J using assms(1) diagram_def by auto\n      interpret D: diagram J C D using assms(1) by auto\n      from assms(2) obtain \\<chi> where \\<chi>: \"D.limit_cone a \\<chi>\" by blast\n      interpret \\<chi>: limit_cone J C D a \\<chi> using \\<chi> by auto\n      have a: \"C.ide a\" using \\<chi>.ide_apex by auto\n      interpret YoD: diagram J Cop_S.comp \\<open>map o D\\<close>\n        using D.diagram_axioms functor_axioms preserves_diagrams [of J D] by simp\n      interpret YoD: diagram_in_functor_category Cop.comp S J \\<open>map o D\\<close> ..\n      interpret Yo\\<chi>: cone J Cop_S.comp \\<open>map o D\\<close> \\<open>map a\\<close> \\<open>map o \\<chi>\\<close>\n        using \\<chi>.cone_axioms preserves_cones by blast\n      have \"\\<And>a'. C.ide a' \\<Longrightarrow>\n                   limit_cone J S (YoD.at a' (map o D))\n                                  (Cop_S.Map (map a) a') (YoD.at a' (map o \\<chi>))\"\n      proof -\n        fix a'\n        assume a': \"C.ide a'\"\n        interpret A': constant_functor J C a'\n          using a' by (unfold_locales, auto)\n        interpret YoD_a': diagram J S \\<open>YoD.at a' (map o D)\\<close>\n          using a' YoD.at_ide_is_diagram by simp\n        interpret Yo\\<chi>_a': cone J S \\<open>YoD.at a' (map o D)\\<close>\n                                   \\<open>Cop_S.Map (map a) a'\\<close> \\<open>YoD.at a' (map o \\<chi>)\\<close>\n          using a' YoD.cone_at_ide_is_cone Yo\\<chi>.cone_axioms by fastforce\n        have eval_at_ide: \"\\<And>j. J.ide j \\<Longrightarrow> YoD.at a' (map \\<circ> D) j = Hom.map (a', D j)\"\n        proof -\n          fix j\n          assume j: \"J.ide j\"\n          have \"YoD.at a' (map \\<circ> D) j = Cop_S.Map (map (D j)) a'\"\n            using a' j YoD.at_simp YoD.preserves_arr [of j] by auto\n          also have \"... = Y (D j) a'\" using Y_def by simp\n          also have \"... = Hom.map (a', D j)\" using a' j D.preserves_arr by simp\n          finally show \"YoD.at a' (map \\<circ> D) j = Hom.map (a', D j)\" by auto\n        qed\n        have eval_at_arr: \"\\<And>j. J.arr j \\<Longrightarrow> YoD.at a' (map \\<circ> \\<chi>) j = Hom.map (a', \\<chi> j)\"\n        proof -\n          fix j\n          assume j: \"J.arr j\"\n          have \"YoD.at a' (map \\<circ> \\<chi>) j = Cop_S.Map ((map o \\<chi>) j) a'\"\n            using a' j YoD.at_simp [of a' j \"map o \\<chi>\"] preserves_arr by fastforce\n          also have \"... = Y (\\<chi> j) a'\" using Y_def by simp\n            also have \"... = Hom.map (a', \\<chi> j)\" using a' j by simp\n          finally show \"YoD.at a' (map \\<circ> \\<chi>) j = Hom.map (a', \\<chi> j)\" by auto\n        qed\n        have Fun_map_a_a': \"Cop_S.Map (map a) a' = Hom.map (a', a)\"\n          using a a' map_simp preserves_arr [of a] by simp\n        show \"limit_cone J S (YoD.at a' (map o D))\n                             (Cop_S.Map (map a) a') (YoD.at a' (map o \\<chi>))\"\n        proof\n          fix x \\<sigma>\n          assume \\<sigma>: \"YoD_a'.cone x \\<sigma>\"\n          interpret \\<sigma>: cone J S \\<open>YoD.at a' (map o D)\\<close> x \\<sigma> using \\<sigma> by auto\n          have x: \"S.ide x\" using \\<sigma>.ide_apex by simp\n          text\\<open>\n            For each object \\<open>j\\<close> of \\<open>J\\<close>, the component \\<open>\\<sigma> j\\<close>\n            is an arrow in \\<open>S.hom x (Hom.map (a', D j))\\<close>.\n            Each element \\<open>e \\<in> S.set x\\<close> therefore determines an arrow\n            \\<open>\\<psi> (a', D j) (S.Fun (\\<sigma> j) e) \\<in> C.hom a' (D j)\\<close>.\n            These arrows are the components of a cone \\<open>\\<kappa> e\\<close> over @{term D}\n            with apex @{term a'}.\n\\<close>\n          have \\<sigma>j: \"\\<And>j. J.ide j \\<Longrightarrow> \\<guillemotleft>\\<sigma> j : x \\<rightarrow>\\<^sub>S Hom.map (a', D j)\\<guillemotright>\"\n            using eval_at_ide \\<sigma>.preserves_hom J.ide_in_hom by force\n          have \\<kappa>: \"\\<And>e. e \\<in> S.set x \\<Longrightarrow>\n                        transformation_by_components\n                          J C A'.map D (\\<lambda>j. \\<psi> (a', D j) (S.Fun (\\<sigma> j) e))\"\n          proof -\n            fix e\n            assume e: \"e \\<in> S.set x\"\n            show \"transformation_by_components J C A'.map D (\\<lambda>j. \\<psi> (a', D j) (S.Fun (\\<sigma> j) e))\"\n            proof\n              fix j\n              assume j: \"J.ide j\"\n              show \"\\<guillemotleft>\\<psi> (a', D j) (S.Fun (\\<sigma> j) e) : A'.map j \\<rightarrow> D j\\<guillemotright>\"\n                using e j S.Fun_mapsto [of \"\\<sigma> j\"] A'.preserves_ide Hom.set_map eval_at_ide\n                      Hom.\\<psi>_mapsto [of \"A'.map j\" \"D j\"]\n                by force\n              next\n              fix j\n              assume j: \"J.arr j\"\n              show \"\\<psi> (a', D (J.cod j)) (S.Fun (\\<sigma> (J.cod j)) e) \\<cdot> A'.map j =\n                    D j \\<cdot> \\<psi> (a', D (J.dom j)) (S.Fun (\\<sigma> (J.dom j)) e)\"\n              proof -\n                have 1: \"Y (D j) a' = \n                          S.mkArr (Hom.set (a', D (J.dom j))) (Hom.set (a', D (J.cod j)))\n                                  (\\<phi> (a', D (J.cod j)) \\<circ> C (D j) \\<circ> \\<psi> (a', D (J.dom j)))\"\n                  using j a' D.preserves_hom\n                        Y_arr_ide [of a' \"D j\" \"D (J.dom j)\" \"D (J.cod j)\"]\n                  by blast\n                have \"\\<psi> (a', D (J.cod j)) (S.Fun (\\<sigma> (J.cod j)) e) \\<cdot> A'.map j =\n                      \\<psi> (a', D (J.cod j)) (S.Fun (\\<sigma> (J.cod j)) e) \\<cdot> a'\"\n                  using A'.map_simp j by simp\n                also have \"... = \\<psi> (a', D (J.cod j)) (S.Fun (\\<sigma> (J.cod j)) e)\"\n                proof -\n                  have \"\\<psi> (a', D (J.cod j)) (S.Fun (\\<sigma> (J.cod j)) e) \\<in> C.hom a' (D (J.cod j))\"\n                    using a' e j Hom.\\<psi>_mapsto [of \"A'.map j\" \"D (J.cod j)\"] A'.map_simp\n                          S.Fun_mapsto [of \"\\<sigma> (J.cod j)\"] Hom.set_map eval_at_ide\n                    by auto\n                  thus ?thesis\n                    using C.comp_arr_dom by fastforce\n                qed\n                also have \"... = \\<psi> (a', D (J.cod j)) (S.Fun (Y (D j) a') (S.Fun (\\<sigma> (J.dom j)) e))\"\n                proof -\n                  have \"S.Fun (Y (D j) a') (S.Fun (\\<sigma> (J.dom j)) e) =\n                        (S.Fun (Y (D j) a') o S.Fun (\\<sigma> (J.dom j))) e\"\n                    by simp\n                  also have \"... = S.Fun (Y (D j) a' \\<cdot>\\<^sub>S \\<sigma> (J.dom j)) e\"\n                    using a' e j Y_arr_ide(1) S.in_homE \\<sigma>j eval_at_ide S.Fun_comp by force\n                  also have \"... = S.Fun (\\<sigma> (J.cod j)) e\"\n                    using a' j x \\<sigma>.is_natural_2 \\<sigma>.A.map_simp S.comp_arr_dom J.arr_cod_iff_arr\n                          J.cod_cod YoD.preserves_arr \\<sigma>.is_natural_1 YoD.at_simp\n                    by auto\n                  finally have\n                      \"S.Fun (Y (D j) a') (S.Fun (\\<sigma> (J.dom j)) e) = S.Fun (\\<sigma> (J.cod j)) e\"\n                    by auto\n                  thus ?thesis by simp\n                qed\n                also have \"... = D j \\<cdot> \\<psi> (a', D (J.dom j)) (S.Fun (\\<sigma> (J.dom j)) e)\"\n                proof -\n                  have \"e \\<in> S.Dom (\\<sigma> (J.dom j))\"\n                    using e j by simp\n                  hence \"S.Fun (\\<sigma> (J.dom j)) e \\<in> S.Cod (\\<sigma> (J.dom j))\"\n                    using e j S.Fun_mapsto [of \"\\<sigma> (J.dom j)\"] by auto\n                  hence 2: \"S.Fun (\\<sigma> (J.dom j)) e \\<in> Hom.set (a', D (J.dom j))\"\n                  proof -\n                    have \"YoD.at a' (map \\<circ> D) (J.dom j) = S.mkIde (Hom.set (a', D (J.dom j)))\"\n                      using a' j YoD.at_simp by (simp add: eval_at_ide)\n                    moreover have \"S.Cod (\\<sigma> (J.dom j)) = Hom.set (a', D (J.dom j))\"\n                      using a' e j Hom.set_map YoD.at_simp eval_at_ide by simp\n                    ultimately show ?thesis\n                      using a' e j \\<sigma>j S.Fun_mapsto [of \"\\<sigma> (J.dom j)\"] Hom.set_map\n                      by auto\n                  qed\n                  hence \"S.Fun (Y (D j) a') (S.Fun (\\<sigma> (J.dom j)) e) =\n                         \\<phi> (a', D (J.cod j)) (D j \\<cdot> \\<psi> (a', D (J.dom j)) (S.Fun (\\<sigma> (J.dom j)) e))\"\n                  proof -\n                    have \"S.Fun (\\<sigma> (J.dom j)) e \\<in> Hom.set (a', D (J.dom j))\"\n                      using a' e j \\<sigma>j S.Fun_mapsto [of \"\\<sigma> (J.dom j)\"] Hom.set_map\n                      by (auto simp add: eval_at_ide)\n                    hence \"C.arr (\\<psi> (a', D (J.dom j)) (S.Fun (\\<sigma> (J.dom j)) e)) \\<and>\n                           C.dom (\\<psi> (a', D (J.dom j)) (S.Fun (\\<sigma> (J.dom j)) e)) = a'\"\n                      using a' j Hom.\\<psi>_mapsto [of a' \"D (J.dom j)\"] by auto\n                    thus ?thesis\n                      using a' e j 2 Hom.Fun_map C.comp_arr_dom by force\n                  qed\n                  moreover have \"D j \\<cdot> \\<psi> (a', D (J.dom j)) (S.Fun (\\<sigma> (J.dom j)) e)\n                                   \\<in> C.hom a' (D (J.cod j))\"\n                  proof -\n                    have \"\\<psi> (a', D (J.dom j)) (S.Fun (\\<sigma> (J.dom j)) e) \\<in> C.hom a' (D (J.dom j))\"\n                      using a' e j Hom.\\<psi>_mapsto [of a' \"D (J.dom j)\"] eval_at_ide\n                            S.Fun_mapsto [of \"\\<sigma> (J.dom j)\"] Hom.set_map\n                      by auto\n                    thus ?thesis using j D.preserves_hom by blast\n                  qed\n                  ultimately show ?thesis using a' j Hom.\\<psi>_\\<phi> by simp\n                qed\n                finally show ?thesis by auto\n              qed\n            qed\n          qed\n          let ?\\<kappa> = \"\\<lambda>e. transformation_by_components.map J C A'.map\n                          (\\<lambda>j. \\<psi> (a', D j) (S.Fun (\\<sigma> j) e))\"\n          have cone_\\<kappa>e: \"\\<And>e. e \\<in> S.set x \\<Longrightarrow> D.cone a' (?\\<kappa> e)\"\n          proof -\n            fix e\n            assume e: \"e \\<in> S.set x\"\n            interpret \\<kappa>e: transformation_by_components J C A'.map D\n                            \\<open>\\<lambda>j. \\<psi> (a', D j) (S.Fun (\\<sigma> j) e)\\<close>\n              using e \\<kappa> by blast\n            show \"D.cone a' (?\\<kappa> e)\" ..\n          qed\n          text\\<open>\n            Since \\<open>\\<kappa> e\\<close> is a cone for each element \\<open>e\\<close> of \\<open>S.set x\\<close>,\n            by the universal property of the limit cone \\<open>\\<chi>\\<close> there is a unique arrow\n            \\<open>fe \\<in> C.hom a' a\\<close> that transforms \\<open>\\<chi>\\<close> to \\<open>\\<kappa> e\\<close>.\n\\<close>\n          have ex_fe: \"\\<And>e. e \\<in> S.set x \\<Longrightarrow> \\<exists>!fe. \\<guillemotleft>fe : a' \\<rightarrow> a\\<guillemotright> \\<and> D.cones_map fe \\<chi> = ?\\<kappa> e\"\n            using cone_\\<kappa>e \\<chi>.is_universal by simp\n          text\\<open>\n            The map taking \\<open>e \\<in> S.set x\\<close> to \\<open>fe \\<in> C.hom a' a\\<close>\n            determines an arrow \\<open>f \\<in> S.hom x (Hom (a', a))\\<close> that\n            transforms the cone obtained by evaluating \\<open>Y o \\<chi>\\<close> at \\<open>a'\\<close>\n            to the cone \\<open>\\<sigma>\\<close>.\n\\<close>\n          let ?f = \"S.mkArr (S.set x) (Hom.set (a', a))\n                            (\\<lambda>e. \\<phi> (a', a) (\\<chi>.induced_arrow a' (?\\<kappa> e)))\"\n          have 0: \"(\\<lambda>e. \\<phi> (a', a) (\\<chi>.induced_arrow a' (?\\<kappa> e))) \\<in> S.set x \\<rightarrow> Hom.set (a', a)\"\n          proof\n            fix e\n            assume e: \"e \\<in> S.set x\"\n            interpret \\<kappa>e: cone J C D a' \\<open>?\\<kappa> e\\<close> using e cone_\\<kappa>e by simp\n            have \"\\<chi>.induced_arrow a' (?\\<kappa> e) \\<in> C.hom a' a\"\n              using a a' e ex_fe \\<chi>.induced_arrowI \\<kappa>e.cone_axioms by simp\n            thus \"\\<phi> (a', a) (\\<chi>.induced_arrow a' (?\\<kappa> e)) \\<in> Hom.set (a', a)\"\n              using a a' Hom.\\<phi>_mapsto by auto\n          qed\n          hence f: \"\\<guillemotleft>?f : x \\<rightarrow>\\<^sub>S Hom.map (a', a)\\<guillemotright>\"\n            using a a' x \\<sigma>.ide_apex S.mkArr_in_hom [of \"S.set x\" \"Hom.set (a', a)\"]\n                  Hom.set_subset_Univ\n            by simp\n          have \"YoD_a'.cones_map ?f (YoD.at a' (map o \\<chi>)) = \\<sigma>\"\n          proof (intro NaturalTransformation.eqI)\n            show \"natural_transformation J S \\<sigma>.A.map (YoD.at a' (map o D)) \\<sigma>\"\n              using \\<sigma>.natural_transformation_axioms by auto\n            have 1: \"S.cod ?f = Cop_S.Map (map a) a'\"\n              using f Fun_map_a_a' by force\n            interpret YoD_a'of: cone J S \\<open>YoD.at a' (map o D)\\<close> x\n                                     \\<open>YoD_a'.cones_map ?f (YoD.at a' (map o \\<chi>))\\<close>\n            proof -\n              have \"YoD_a'.cone (S.cod ?f) (YoD.at a' (map o \\<chi>))\"\n                using a a' f Yo\\<chi>_a'.cone_axioms preserves_arr [of a] by auto\n              hence \"YoD_a'.cone (S.dom ?f) (YoD_a'.cones_map ?f (YoD.at a' (map o \\<chi>)))\"\n                using f YoD_a'.cones_map_mapsto S.arrI by blast\n              thus \"cone J S (YoD.at a' (map o D)) x\n                                        (YoD_a'.cones_map ?f (YoD.at a' (map o \\<chi>)))\"\n                using f by auto\n            qed\n            show \"natural_transformation J S \\<sigma>.A.map (YoD.at a' (map o D))\n                                         (YoD_a'.cones_map ?f (YoD.at a' (map o \\<chi>)))\" ..\n            fix j\n            assume j: \"J.ide j\"\n            have \"YoD_a'.cones_map ?f (YoD.at a' (map o \\<chi>)) j = YoD.at a' (map o \\<chi>) j \\<cdot>\\<^sub>S ?f\"\n              using f j Fun_map_a_a' Yo\\<chi>_a'.cone_axioms by fastforce\n            also have \"... = \\<sigma> j\"\n            proof (intro S.arr_eqI)\n              show \"S.par (YoD.at a' (map o \\<chi>) j \\<cdot>\\<^sub>S ?f) (\\<sigma> j)\"\n                using 1 f j x YoD_a'.preserves_hom by fastforce\n              show \"S.Fun (YoD.at a' (map o \\<chi>) j \\<cdot>\\<^sub>S ?f) = S.Fun (\\<sigma> j)\"\n              proof\n                fix e\n                have \"e \\<notin> S.set x \\<Longrightarrow> S.Fun (YoD.at a' (map o \\<chi>) j \\<cdot>\\<^sub>S ?f) e = S.Fun (\\<sigma> j) e\"\n                proof -\n                  assume e: \"e \\<notin> S.set x\"\n                  have \"S.Fun (YoD.at a' (map o \\<chi>) j \\<cdot>\\<^sub>S ?f) e = undefined\"\n                    using 1 e f j x S.Fun_mapsto by fastforce\n                  also have \"... = S.Fun (\\<sigma> j) e\"\n                  proof -\n                    have \"\\<guillemotleft>\\<sigma> j : x \\<rightarrow>\\<^sub>S YoD.at a' (map \\<circ> D) (J.cod j)\\<guillemotright>\"\n                      using j \\<sigma>.A.map_simp by force\n                    thus ?thesis\n                      using e j S.Fun_mapsto [of \"\\<sigma> j\"] extensional_arb [of \"S.Fun (\\<sigma> j)\"]\n                      by fastforce\n                  qed\n                  finally show ?thesis by auto\n                qed\n                moreover have \"e \\<in> S.set x \\<Longrightarrow>\n                                  S.Fun (YoD.at a' (map o \\<chi>) j \\<cdot>\\<^sub>S ?f) e = S.Fun (\\<sigma> j) e\"\n                proof -\n                  assume e: \"e \\<in> S.set x\"\n                  interpret \\<kappa>e: transformation_by_components J C A'.map D\n                                  \\<open>\\<lambda>j. \\<psi> (a', D j) (S.Fun (\\<sigma> j) e)\\<close>\n                    using e \\<kappa> by blast\n                  interpret \\<kappa>e: cone J C D a' \\<open>?\\<kappa> e\\<close> using e cone_\\<kappa>e by simp\n                  have induced_arrow: \"\\<chi>.induced_arrow a' (?\\<kappa> e) \\<in> C.hom a' a\"\n                    using a a' e ex_fe \\<chi>.induced_arrowI \\<kappa>e.cone_axioms by simp\n                  have \"S.Fun (YoD.at a' (map o \\<chi>) j \\<cdot>\\<^sub>S ?f) e =\n                          restrict (S.Fun (YoD.at a' (map o \\<chi>) j) o S.Fun ?f) (S.set x) e\"\n                    using 1 e f j S.Fun_comp YoD_a'.preserves_hom by force\n                  also have \"... = (\\<phi> (a', D j) o C (\\<chi> j) o \\<psi> (a', a)) (S.Fun ?f e)\"\n                    using j a' f e Hom.map_simp_2 S.Fun_mkArr Hom.preserves_arr [of \"(a', \\<chi> j)\"]\n                          eval_at_arr\n                    by (elim S.in_homE, auto)\n                  also have \"... = (\\<phi> (a', D j) o C (\\<chi> j) o \\<psi> (a', a))\n                                     (\\<phi> (a', a) (\\<chi>.induced_arrow a' (?\\<kappa> e)))\"\n                    using e f S.Fun_mkArr by fastforce\n                  also have \"... = \\<phi> (a', D j) (D.cones_map (\\<chi>.induced_arrow a' (?\\<kappa> e)) \\<chi> j)\"\n                      using a a' e j 0 Hom.\\<psi>_\\<phi> induced_arrow \\<chi>.cone_axioms\n                      by auto\n                  also have \"... = \\<phi> (a', D j) (?\\<kappa> e j)\"\n                    using \\<chi>.induced_arrowI \\<kappa>e.cone_axioms by fastforce\n                  also have \"... = \\<phi> (a', D j) (\\<psi> (a', D j) (S.Fun (\\<sigma> j) e))\"\n                    using j \\<kappa>e.map_def [of j] by simp\n                  also have \"... = S.Fun (\\<sigma> j) e\"\n                  proof -\n                    have \"S.Fun (\\<sigma> j) e \\<in> Hom.set (a', D j)\"\n                      using a' e j S.Fun_mapsto [of \"\\<sigma> j\"] eval_at_ide Hom.set_map by auto\n                    thus ?thesis\n                      using a' j Hom.\\<phi>_\\<psi> C.ide_in_hom J.ide_in_hom by blast\n                  qed\n                  finally show \"S.Fun (YoD.at a' (map o \\<chi>) j \\<cdot>\\<^sub>S ?f) e = S.Fun (\\<sigma> j) e\"\n                    by auto\n                qed\n                ultimately show \"S.Fun (YoD.at a' (map o \\<chi>) j \\<cdot>\\<^sub>S ?f) e = S.Fun (\\<sigma> j) e\"\n                  by auto\n              qed\n            qed\n            finally show \"YoD_a'.cones_map ?f (YoD.at a' (map o \\<chi>)) j = \\<sigma> j\" by auto\n          qed\n          hence ff: \"?f \\<in> S.hom x (Hom.map (a', a)) \\<and>\n                     YoD_a'.cones_map ?f (YoD.at a' (map o \\<chi>)) = \\<sigma>\"\n            using f by auto\n          text\\<open>\n            Any other arrow \\<open>f' \\<in> S.hom x (Hom.map (a', a))\\<close> that\n            transforms the cone obtained by evaluating \\<open>Y o \\<chi>\\<close> at @{term a'}\n            to the cone @{term \\<sigma>}, must equal \\<open>f\\<close>, showing that \\<open>f\\<close>\n            is unique.\n\\<close>\n          moreover have \"\\<And>f'. \\<guillemotleft>f' : x \\<rightarrow>\\<^sub>S Hom.map (a', a)\\<guillemotright> \\<and>\n                              YoD_a'.cones_map f' (YoD.at a' (map o \\<chi>)) = \\<sigma>\n                                \\<Longrightarrow> f' = ?f\"\n          proof -\n            fix f'\n            assume f': \"\\<guillemotleft>f' : x \\<rightarrow>\\<^sub>S Hom.map (a', a)\\<guillemotright> \\<and>\n                        YoD_a'.cones_map f' (YoD.at a' (map o \\<chi>)) = \\<sigma>\"\n            show \"f' = ?f\"\n            proof (intro S.arr_eqI)\n              show par: \"S.par f' ?f\" using f f' by (elim S.in_homE, auto)\n              show \"S.Fun f' = S.Fun ?f\"\n              proof\n                fix e\n                have \"e \\<notin> S.set x \\<Longrightarrow> S.Fun f' e = S.Fun ?f e\"\n                  using f f' x S.Fun_mapsto extensional_arb by fastforce\n                moreover have \"e \\<in> S.set x \\<Longrightarrow> S.Fun f' e = S.Fun ?f e\"\n                proof -\n                  assume e: \"e \\<in> S.set x\"\n                  have 1: \"\\<guillemotleft>\\<psi> (a', a) (S.Fun f' e) : a' \\<rightarrow> a\\<guillemotright>\"\n                  proof -\n                    have \"S.Fun f' e \\<in> S.Cod f'\"\n                      using a a' e f' S.Fun_mapsto by auto\n                    hence \"S.Fun f' e \\<in> Hom.set (a', a)\"\n                      using a a' f' Hom.set_map by auto\n                    thus ?thesis\n                      using a a' e f' S.Fun_mapsto Hom.\\<psi>_mapsto Hom.set_map by blast\n                  qed\n                  have 2: \"\\<guillemotleft>\\<psi> (a', a) (S.Fun ?f e) : a' \\<rightarrow> a\\<guillemotright>\"\n                  proof -\n                    have \"S.Fun ?f e \\<in> S.Cod ?f\"\n                      using a a' e f S.Fun_mapsto by force\n                    hence \"S.Fun ?f e \\<in> Hom.set (a', a)\"\n                      using a a' f Hom.set_map by auto\n                    thus ?thesis\n                      using a a' e f' S.Fun_mapsto Hom.\\<psi>_mapsto Hom.set_map by blast\n                  qed\n                  interpret \\<chi>ofe: cone J C D a' \\<open>D.cones_map (\\<psi> (a', a) (S.Fun ?f e)) \\<chi>\\<close>\n                  proof -\n                    have \"D.cones_map (\\<psi> (a', a) (S.Fun ?f e)) \\<in> D.cones a \\<rightarrow> D.cones a'\"\n                      using 2 D.cones_map_mapsto [of \"\\<psi> (a', a) (S.Fun ?f e)\"]\n                      by (elim C.in_homE, auto)\n                    thus \"cone J C D a' (D.cones_map (\\<psi> (a', a) (S.Fun ?f e)) \\<chi>)\"\n                      using \\<chi>.cone_axioms by blast\n                  qed\n                  have f'e: \"S.Fun f' e \\<in> Hom.set (a', a)\"\n                    using a a' e f' x S.Fun_mapsto [of f'] Hom.set_map by fastforce\n                  have fe: \"S.Fun ?f e \\<in> Hom.set (a', a)\"\n                    using e f by (elim S.in_homE, auto)\n                  have A: \"\\<And>h j. h \\<in> C.hom a' a \\<Longrightarrow> J.arr j \\<Longrightarrow>\n                                   S.Fun (YoD.at a' (map o \\<chi>) j) (\\<phi> (a', a) h)\n                                     = \\<phi> (a', D (J.cod j)) (\\<chi> j \\<cdot> h)\"\n                  proof -\n                    fix h j\n                    assume j: \"J.arr j\"\n                    assume h: \"h \\<in> C.hom a' a\"\n                    have \"S.Fun (YoD.at a' (map o \\<chi>) j) = S.Fun (Y (\\<chi> j) a')\"\n                      using a' j YoD.at_simp Y_def Yo\\<chi>.preserves_reflects_arr [of j]\n                      by simp\n                    also have \"... = restrict (\\<phi> (a', D (J.cod j)) \\<circ> C (\\<chi> j) \\<circ> \\<psi> (a', a))\n                                              (Hom.set (a', a))\"\n                    proof -\n                      have \"S.arr (Y (\\<chi> j) a') \\<and>\n                            Y (\\<chi> j) a' = S.mkArr (Hom.set (a', a)) (Hom.set (a', D (J.cod j)))\n                                                 (\\<phi> (a', D (J.cod j)) \\<circ> C (\\<chi> j) \\<circ> \\<psi> (a', a))\"\n                        using a' j \\<chi>.preserves_hom [of j \"J.dom j\" \"J.cod j\"]\n                              Y_arr_ide [of a' \"\\<chi> j\" a \"D (J.cod j)\"] \\<chi>.A.map_simp\n                        by auto\n                      thus ?thesis\n                        using S.Fun_mkArr by metis\n                    qed\n                    finally have \"S.Fun (YoD.at a' (map o \\<chi>) j)\n                                    = restrict (\\<phi> (a', D (J.cod j)) \\<circ> C (\\<chi> j) \\<circ> \\<psi> (a', a))\n                                               (Hom.set (a', a))\"\n                      by auto\n                    hence \"S.Fun (YoD.at a' (map o \\<chi>) j) (\\<phi> (a', a) h)\n                              = (\\<phi> (a', D (J.cod j)) \\<circ> C (\\<chi> j) \\<circ> \\<psi> (a', a)) (\\<phi> (a', a) h)\"\n                      using a a' h Hom.\\<phi>_mapsto by auto\n                    also have \"... = \\<phi> (a', D (J.cod j)) (\\<chi> j \\<cdot> h)\"\n                      using a a' h Hom.\\<psi>_\\<phi> by simp\n                    finally show \"S.Fun (YoD.at a' (map o \\<chi>) j) (\\<phi> (a', a) h)\n                                    = \\<phi> (a', D (J.cod j)) (\\<chi> j \\<cdot> h)\"\n                      by auto\n                  qed\n                  have \"D.cones_map (\\<psi> (a', a) (S.Fun f' e)) \\<chi> =\n                        D.cones_map (\\<psi> (a', a) (S.Fun ?f e)) \\<chi>\"\n                  proof\n                    fix j\n                    have \"\\<not>J.arr j \\<Longrightarrow> D.cones_map (\\<psi> (a', a) (S.Fun f' e)) \\<chi> j =\n                                       D.cones_map (\\<psi> (a', a) (S.Fun ?f e)) \\<chi> j\"\n                      using 1 2 \\<chi>.cone_axioms by (elim C.in_homE, auto)\n                    moreover have \"J.arr j \\<Longrightarrow> D.cones_map (\\<psi> (a', a) (S.Fun f' e)) \\<chi> j =\n                                               D.cones_map (\\<psi> (a', a) (S.Fun ?f e)) \\<chi> j\"\n                    proof -\n                      assume j: \"J.arr j\"\n                      have 3: \"S.Fun (YoD.at a' (map o \\<chi>) j) (S.Fun f' e) = S.Fun (\\<sigma> j) e\"\n                        using Fun_map_a_a' a a' j f' e x Yo\\<chi>_a'.A.map_simp eval_at_ide\n                              Yo\\<chi>_a'.cone_axioms\n                        by auto\n                      have 4: \"S.Fun (YoD.at a' (map o \\<chi>) j) (S.Fun ?f e) = S.Fun (\\<sigma> j) e\"\n                      proof -\n                        have \"S.Fun (YoD.at a' (map o \\<chi>) j) (S.Fun ?f e)\n                                = (S.Fun (YoD.at a' (map o \\<chi>) j) o S.Fun ?f) e\"\n                          by simp\n                        also have \"... = S.Fun (YoD.at a' (map o \\<chi>) j \\<cdot>\\<^sub>S ?f) e\"\n                          using Fun_map_a_a' a a' j f e x Yo\\<chi>_a'.A.map_simp eval_at_ide\n                          by auto\n                        also have \"... = S.Fun (\\<sigma> j) e\"\n                        proof -\n                          have \"YoD.at a' (map o \\<chi>) j \\<cdot>\\<^sub>S ?f =\n                                YoD_a'.cones_map ?f (YoD.at a' (map o \\<chi>)) j\"\n                            using j f Yo\\<chi>_a'.cone_axioms Fun_map_a_a' by auto\n                          thus ?thesis using j ff by argo\n                        qed\n                        finally show ?thesis by auto\n                      qed\n                      have \"D.cones_map (\\<psi> (a', a) (S.Fun f' e)) \\<chi> j =\n                              \\<chi> j \\<cdot> \\<psi> (a', a) (S.Fun f' e)\"\n                        using j 1 \\<chi>.cone_axioms by auto\n                      also have \"... = \\<psi> (a', D (J.cod j)) (S.Fun (\\<sigma> j) e)\"\n                      proof -\n                        have \"\\<psi> (a', D (J.cod j)) (S.Fun (YoD.at a' (map o \\<chi>) j) (S.Fun f' e)) =\n                                \\<psi> (a', D (J.cod j))\n                                  (\\<phi> (a', D (J.cod j)) (\\<chi> j \\<cdot> \\<psi> (a', a) (S.Fun f' e)))\"\n                          using j a a' f'e A Hom.\\<phi>_\\<psi> Hom.\\<psi>_mapsto by force\n                        moreover have \"\\<chi> j \\<cdot> \\<psi> (a', a) (S.Fun f' e) \\<in> C.hom a' (D (J.cod j))\"\n                          using a a' j f'e Hom.\\<psi>_mapsto \\<chi>.preserves_hom [of j \"J.dom j\" \"J.cod j\"]\n                                \\<chi>.A.map_simp\n                          by auto\n                        ultimately show ?thesis\n                          using a a' 3 4 Hom.\\<psi>_\\<phi> by auto\n                      qed\n                      also have \"... = \\<chi> j \\<cdot> \\<psi> (a', a) (S.Fun ?f e)\"\n                      proof -\n                        have \"S.Fun (YoD.at a' (map o \\<chi>) j) (S.Fun ?f e) =\n                                \\<phi> (a', D (J.cod j)) (\\<chi> j \\<cdot> \\<psi> (a', a) (S.Fun ?f e))\"\n                          using j a a' fe A [of \"\\<psi> (a', a) (S.Fun ?f e)\" j] Hom.\\<phi>_\\<psi> Hom.\\<psi>_mapsto\n                          by auto\n                        hence \"\\<psi> (a', D (J.cod j)) (S.Fun (YoD.at a' (map o \\<chi>) j) (S.Fun ?f e)) =\n                                \\<psi> (a', D (J.cod j))\n                                  (\\<phi> (a', D (J.cod j)) (\\<chi> j \\<cdot> \\<psi> (a', a) (S.Fun ?f e)))\"\n                          by simp\n                        moreover have \"\\<chi> j \\<cdot> \\<psi> (a', a) (S.Fun ?f e) \\<in> C.hom a' (D (J.cod j))\"\n                          using a a' j fe Hom.\\<psi>_mapsto \\<chi>.preserves_hom [of j \"J.dom j\" \"J.cod j\"]\n                                \\<chi>.A.map_simp\n                          by auto\n                        ultimately show ?thesis\n                          using a a' 3 4 Hom.\\<psi>_\\<phi> by auto\n                      qed\n                      also have \"... = D.cones_map (\\<psi> (a', a) (S.Fun ?f e)) \\<chi> j\"\n                        using j 2 \\<chi>.cone_axioms by force\n                      finally show \"D.cones_map (\\<psi> (a', a) (S.Fun f' e)) \\<chi> j =\n                                    D.cones_map (\\<psi> (a', a) (S.Fun ?f e)) \\<chi> j\"\n                        by auto\n                    qed\n                    ultimately show \"D.cones_map (\\<psi> (a', a) (S.Fun f' e)) \\<chi> j =\n                                     D.cones_map (\\<psi> (a', a) (S.Fun ?f e)) \\<chi> j\"\n                      by auto\n                  qed\n                  hence \"\\<psi> (a', a) (S.Fun f' e) = \\<psi> (a', a) (S.Fun ?f e)\"\n                    using 1 2 \\<chi>ofe.cone_axioms \\<chi>.cone_axioms \\<chi>.is_universal by blast\n                  hence \"\\<phi> (a', a) (\\<psi> (a', a) (S.Fun f' e)) = \\<phi> (a', a) (\\<psi> (a', a) (S.Fun ?f e))\"\n                    by simp\n                  thus \"S.Fun f' e = S.Fun ?f e\"\n                    using a a' fe f'e Hom.\\<phi>_\\<psi> by force\n                qed\n                ultimately show \"S.Fun f' e = S.Fun ?f e\" by auto\n              qed\n            qed\n          qed\n          ultimately have \"\\<exists>!f. \\<guillemotleft>f : x \\<rightarrow>\\<^sub>S Hom.map (a', a)\\<guillemotright> \\<and>\n                                YoD_a'.cones_map f (YoD.at a' (map o \\<chi>)) = \\<sigma>\"\n            using ex1I [of \"\\<lambda>f. S.in_hom x (Hom.map (a', a)) f \\<and>\n                                YoD_a'.cones_map f (YoD.at a' (map o \\<chi>)) = \\<sigma>\"]\n            by blast\n          thus \"\\<exists>!f. \\<guillemotleft>f : x \\<rightarrow>\\<^sub>S Cop_S.Map (map a) a'\\<guillemotright> \\<and>\n                     YoD_a'.cones_map f (YoD.at a' (map o \\<chi>)) = \\<sigma>\"\n            using a a' Y_def [of a] by simp\n        qed\n      qed\n      thus \"YoD.has_as_limit (map a)\"\n        using YoD.cone_is_limit_if_pointwise_limit Yo\\<chi>.cone_axioms by auto\n    qed\n\n  end\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/Category3/Limit.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8872045847699186, "lm_q2_score": 0.7905303186696748, "lm_q1q2_score": 0.7013621231233603}}
{"text": "theory Chapter5\nimports 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\ninductive iter :: \"('a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> nat \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> bool\" for r where\niter_0: \"iter r 0 x x\" |\niter_Suc: \"r x y \\<Longrightarrow> iter r n y z \\<Longrightarrow> iter r (Suc n) x z\"\n\ntext\\<open>\n\\section*{Chapter 5}\n\n\\exercise\nGive a readable, structured proof of the following lemma:\n\\<close>\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\"\n(* your definition/proof here *)\nproof (cases \"T x y\")\n  assume \"T x y\"\n  thus ?thesis by auto\nnext\n  assume \"\\<not>(T x y)\"\n  hence \"T y x\" using T by auto\n  hence \"A y x\" using TA by auto\n  hence \"x = y\" using A `A x y` by auto\n  hence \"T x y\" using `T y x` `A y x` by auto\n  thus ?thesis by auto\nqed\n\ntext\\<open>\nEach step should use at most one of the assumptions @{text T}, @{text A}\nor @{text TA}.\n\\endexercise\n\n\\exercise\nGive a readable, structured proof of the following lemma:\n\\<close>\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)\"\n(* your definition/proof here *)\nproof cases\n  assume \"2 dvd (length xs)\"\n  hence \"\\<exists>k. 2 * k = (length xs)\" by auto\n  then obtain k where \"2 * k = (length xs)\" by auto\n  then moreover obtain ys zs where \"(ys = (take k xs)) \\<and> (zs = (drop k xs))\" by auto\n  ultimately have \"length ys = length zs \\<and> xs = ys @ zs\" by auto\n  then show ?thesis by auto\nnext\n  assume \"\\<not>(2 dvd (length xs))\"\n  hence \"\\<exists>k. (2 * k + 1) = (length xs)\" by (metis oddE)\n  then obtain k where \"2 * k + 1 = (length xs)\" by auto\n  then moreover obtain ys zs where \"(ys = (take (k + 1) xs)) \\<and> (zs = (drop (k + 1) xs))\" by auto\n  ultimately have \"length ys = length zs + 1 \\<and> xs = ys @ zs\" by auto\n  then show ?thesis by auto\nqed\n\ntext\\<open>\nHint: There are predefined functions @{const take} and {const drop} of type\n@{typ \"nat \\<Rightarrow> 'a list \\<Rightarrow> 'a list\"} such that @{text\"take k [x\\<^sub>1,\\<dots>] = [x\\<^sub>1,\\<dots>,x\\<^sub>k]\"}\nand @{text\"drop k [x\\<^sub>1,\\<dots>] = [x\\<^bsub>k+1\\<^esub>,\\<dots>]\"}. Let sledgehammer find and apply\nthe relevant @{const take} and @{const drop} lemmas for you.\n\\endexercise\n\n\\exercise\nGive a structured proof by rule inversion:\n\\<close>\ninductive ev :: \"nat \\<Rightarrow> bool\" where\nev0: \"ev 0\" |\nevSS: \"ev n \\<Longrightarrow> ev(Suc(Suc n))\"\n\nlemma assumes a: \"ev(Suc(Suc n))\" shows \"ev n\"\nproof -\n  show ?thesis using assms\n  proof cases\n    case evSS\n    then show ?thesis by auto\n  qed\nqed\n\ntext\\<open>\n\\exercise\nGive a structured proof by rule inversions:\n\\<close>\n\nlemma \"\\<not> ev(Suc(Suc(Suc 0)))\"\nproof \n  assume \"ev (Suc (Suc (Suc 0)))\" \n  then show False using ev.cases by auto\nqed\n\ntext\\<open>\nIf there are no cases to be proved you can close\na proof immediateley with \\isacom{qed}.\n\\endexercise\n\n\\exercise\nRecall predicate @{const star} from Section 4.5 and @{const iter}\nfrom Exercise~\\ref{exe:iter}.\n\\<close>\n\nlemma \"iter r n x y \\<Longrightarrow> star r x y\"\nproof (induction n x y rule: iter.induct)\n  case (iter_0 x)\n  then show \"star r x x\" by (simp add: star.refl)\nnext\n  case (iter_Suc x y n z)\n  have \"star r y z\" using iter_Suc.IH by simp\n  moreover have \"r x y\" using iter_Suc.hyps by simp\n  ultimately show \"star r x z\" by (simp add: star.refl star.step)\nqed\n\ntext\\<open>\nProve this lemma in a structured style, do not just sledgehammer each case of the\nrequired induction.\n\\endexercise\n\n\\exercise\nDefine a recursive function\n\\<close>\n\nfun elems :: \"'a list \\<Rightarrow> 'a set\" where\n\"elems Nil = {}\" |\n\"elems (x#xs) = {x} \\<union> (elems xs)\"\n(* your definition/proof here *)\n\ntext\\<open> that collects all elements of a list into a set. Prove \\<close>\n\nlemma \"x \\<in> elems xs \\<Longrightarrow> \\<exists>ys zs. xs = ys @ x # zs \\<and> x \\<notin> elems ys\"\nproof (cases xs)\n  case (Cons a list)\n  then show ?thesis\n  proof cases\n    assume \"a = x\"\n    moreover obtain ys where ys: \"(ys::'a list) = []\" by auto\n    moreover obtain zs where zs: \"zs = xs\" by auto\n    moreover have \"x \\<notin> elems ys\" by (simp add: calculation(2))\n    moreover have idk: \"xs = ys @ zs\" using ys zs by auto\n    ultimately show ?thesis using local.Cons by fastforce\n  next\n    show ?thesis proof -\n      assume 0: \"xs = a#list \\<and> a \\<noteq> x\"\n      assume IH: \"(x \\<in> elems xs \\<Longrightarrow> \\<exists>ys zs. xs = ys @ x # zs \\<and> x \\<notin> elems ys)\"\n      assume 1: \"x \\<in> elems xs\"\n      then obtain ys ys1 zs zs1 where \n        \"x \\<notin> elems ys\" \n        \"ys = a#ys1\" \n        \"xs = a#ys1 @ zs\"\n        \"zs = x#zs1\"\n        using 0 IH by (metis append_eq_Cons_conv list.inject local.Cons)\n      hence \"xs = ys @ x # zs1 \\<and> x \\<notin> elems ys\" by simp\n      thus show ?thesis sorry\n    qed\n  qed\nqed\n\ntext\\<open>\n\\endexercise\n\n\\exercise\nExtend Exercise~\\ref{exe:cfg} with a function that checks if some\n\\mbox{@{text \"alpha list\"}} is a balanced\nstring of parentheses. More precisely, define a recursive function \\<close>\n(* your definition/proof here *)\nfun balanced :: \"nat \\<Rightarrow> alpha list \\<Rightarrow> bool\" where\n(* your definition/proof here *)\n\ntext\\<open> such that @{term\"balanced n w\"}\nis true iff (informally) @{text\"a\\<^sup>n @ w \\<in> S\"}. Formally, prove \\<close>\n\ncorollary \"balanced n w \\<longleftrightarrow> S (replicate n a @ w)\"\n\n\ntext\\<open> where @{const replicate} @{text\"::\"} @{typ\"nat \\<Rightarrow> 'a \\<Rightarrow> 'a list\"} is predefined\nand @{term\"replicate n x\"} yields the list @{text\"[x, \\<dots>, x]\"} of length @{text n}.\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/Chapter5.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7799928951399099, "lm_q2_score": 0.899121388082479, "lm_q1q2_score": 0.7013082945726673}}
{"text": "theory Pugh\n imports \"HOL-Analysis.Analysis\"\nbegin\n\n(*\nproblem_number:2_12a\nnatural language statement:\nLet $(p_n)$ be a sequence and $f:\\mathbb{N}\\to\\mathbb{N}$ a bijection. The sequence $(q_k)_{k\\in\\mathbb{N}}$ with $q_k=p_{f(k)}$ is called a rearrangement of $(p_n)$. Show that if $f$ is an injection, the limit of a sequence is unaffected by rearrangement.\nlean statement:\ntheorem exercise_2_12a (f : \\<nat> \\<rightarrow> \\<nat>) (p : \\<nat> \\<rightarrow> \\<real>) (a : \\<real>)\n  (hf : injective f) (hp : tendsto p at_top (\ud835\udcdd a)) :\n  tendsto (\\<lambda> n, p (f n)) at_top (\ud835\udcdd a) :=\n\ncodex statement:\ntheorem lim_of_rearrangement_of_injective:\n  fixes f::\"nat \\<Rightarrow> nat\" and p::\"nat \\<Rightarrow> 'a::real_normed_vector\"\n  assumes \"inj f\" \"convergent p\"\n  shows \"convergent (\\<lambda>n. p (f n))\"\nOur comment on the codex statement: a start, but the real meaning was not preserved\n *)\ntheorem exercise_2_12a: \n  fixes f::\"nat \\<Rightarrow> nat\" and p::\"nat \\<Rightarrow> 'a::real_normed_vector\"\n  assumes \"inj f\"\n  shows \"(\\<lambda>n. p (f n)) \\<longlonglongrightarrow> a  \\<longleftrightarrow>  p \\<longlonglongrightarrow> a\"\n  oops\n\n\n(*\nproblem_number:2_12b\nnatural language statement:\nLet $(p_n)$ be a sequence and $f:\\mathbb{N}\\to\\mathbb{N}$ a bijection. The sequence $(q_k)_{k\\in\\mathbb{N}}$ with $q_k=p_{f(k)}$ is called a rearrangement of $(p_n)$. Show that if $f$ is a surjection, the limit of a sequence is unaffected by rearrangement.\nlean statement:\ntheorem exercise_2_12b (f : \\<nat> \\<rightarrow> \\<nat>) (p : \\<nat> \\<rightarrow> \\<real>) (a : \\<real>)\n  (hf : surjective f) (hp : tendsto p at_top (\ud835\udcdd a)) :\n  tendsto (\\<lambda> n, p (f n)) at_top (\ud835\udcdd a) :=\n\ncodex statement:\ntheorem lim_of_rearrangement_of_surjection:\n  fixes f::\"nat \\<Rightarrow> nat\" and p::\"nat \\<Rightarrow> 'a::real_normed_vector\"\n  assumes \"bij f\" \"surj f\" \"\\<forall>n. p n = q (f n)\" \"convergent p\"\n  shows \"convergent q \\<and> lim p = lim q\"\nOur comment on the codex statement: <YOU CAN LEAVE YOUR COMMENT HERE>\n *)\ntheorem exercise_2_12b: (*The informal versions of both exercises are ambiguous: is it given that the original sequence converges?*)\n  fixes f::\"nat \\<Rightarrow> nat\" and p::\"nat \\<Rightarrow> 'a::real_normed_vector\"\n  assumes \"surj f\"\n  shows \"(\\<lambda>n. p (f n)) \\<longlonglongrightarrow> a  \\<longleftrightarrow>  p \\<longlonglongrightarrow> a\"\n  oops\n\n\n(*\nproblem_number:2_26\nnatural language statement:\nProve that a set $U \\subset M$ is open if and only if none of its points are limits of its complement.\nlean statement:\ntheorem exercise_2_26 {M : Type*} [topological_space M]\n  (U : set M) : is_open U \\<longleftrightarrow> \\<forall> x \\<in> U, \\<not> cluster_pt x (\ud835\udcdf U\u1d9c) :=\n\ncodex statement:\ntheorem open_iff_no_limit_point_of_complement:\n  fixes U::\"'a::metric_space set\"\n  shows \"open U \\<longleftrightarrow> \\<forall>x\\<in>U. \\<not>(x islimpt (-U))\"\nOur comment on the codex statement:  Syntactically correct, but with the addition of parentheses, good (type class version)\n *)\ntheorem exercise_2_26: \n  fixes U::\"'a::metric_space set\"\n  shows \"open U \\<longleftrightarrow> (\\<forall>x\\<in>U. \\<not>(x islimpt (-U)))\"\n  oops\n\n\n(*\nproblem_number:2_29\nnatural language statement:\nLet $\\mathcal{T}$ be the collection of open subsets of a metric space $\\mathrm{M}$, and $\\mathcal{K}$ the collection of closed subsets. Show that there is a bijection from $\\mathcal{T}$ onto $\\mathcal{K}$.\nlean statement:\ntheorem exercise_2_29 (M : Type* ) [metric_space M]\n  (O C : set (set M))\n  (hO : O = {s | is_open s})\n  (hC : C = {s | is_closed s}) :\n  \\<exists> f : O \\<rightarrow> C, bijective f :=\n\ncodex statement:\ntheorem bijection_open_closed:\n  fixes M::\"'a::metric_space set\"\n  shows \"bij_betw (\\<lambda>U. closure U) (open_sets M) (closed_sets M)\"\nOur comment on the codex statement:  interesting but clearly wrong guess of the bijection (which must be complementation)\n *)\ntheorem exercise_2_29: \n  fixes M::\"'a::metric_space set\"\n  shows \"\\<exists>f. bij_betw f {S. open S} {S. closed S}\"\n  oops\n\n\n(*\nproblem_number:2_32a\nnatural language statement:\nShow that every subset of $\\mathbb{N}$ is clopen.\nlean statement:\ntheorem exercise_2_32a (A : set \\<nat>) : is_clopen A :=\n\ncodex statement:\ntheorem clopen_of_subset_nat:\n  fixes A::\"nat set\"\n  shows \"closed_in (top_of_set UNIV) A \\<and> open_in (top_of_set UNIV) A\"\nOur comment on the codex statement: close, but it didn't know about discrete_topology\n *)\ntheorem exercise_2_32a: \n  fixes A::\"nat set\"\n    shows \"closedin (discrete_topology UNIV) A \\<and> openin (discrete_topology UNIV) A\"\n  by simp\n\n\n(*\nproblem_number:2_41\nnatural language statement:\nLet $\\|\\cdot\\|$ be any norm on $\\mathbb{R}^{m}$ and let $B=\\left\\{x \\in \\mathbb{R}^{m}:\\|x\\| \\leq 1\\right\\}$. Prove that $B$ is compact.\nlean statement:\ntheorem exercise_2_41 (m : \\<nat>) {X : Type*} [normed_space \\<real> ((fin m) \\<rightarrow> \\<real>)] :\n  is_compact (metric.closed_ball 0 1) :=\n\ncodex statement:\ntheorem compact_of_norm_leq_one:\n  fixes m::nat and f::\"nat \\<Rightarrow> real\"\n  assumes \"norm f \\<le> 1\"\n  shows \"compact {x::'a::euclidean_space. \\<forall>i. norm (x$i) \\<le> f i}\"\nOur comment on the codex statement: seemingly inserted its own definition of norm, and we can't capture \"any norm\"\n *)\ntheorem exercise_2_41: \n  shows \"compact {x. norm x \\<le> 1}\"\n  oops\n\n\n(*\nproblem_number:2_46\nnatural language statement:\nAssume that $A, B$ are compact, disjoint, nonempty subsets of $M$. Prove that there are $a_0 \\in A$ and $b_0 \\in B$ such that for all $a \\in A$ and $b \\in B$ we have $d(a_0, b_0) \\leq d(a, b)$.\nlean statement:\ntheorem exercise_2_46 {M : Type*} [metric_space M]\n  {A B : set M} (hA : is_compact A) (hB : is_compact B)\n  (hAB : disjoint A B) (hA\u2080 : A \\<noteq> \\<emptyset>) (hB\u2080 : B \\<noteq> \\<emptyset>) :\n  \\<exists> a\u2080 b\u2080, a\u2080 \\<in> A \\<and> b\u2080 \\<in> B \\<and> \\<forall> (a : M) (b : M),\n  a \\<in> A \\<rightarrow> b \\<in> B \\<rightarrow> dist a\u2080 b\u2080 \\<le> dist a b :=\n\ncodex statement:\ntheorem exists_min_distance_of_compact_disjoint_nonempty:\n  fixes A B::\"'a::metric_space set\"\n  assumes \"compact A\" \"compact B\" \"A \\<inter> B = {}\" \"A \\<noteq> {}\" \"B \\<noteq> {}\"\n  shows \"\\<exists>a b. a\\<in>A \\<and> b\\<in>B \\<and> (\\<forall>a'\\<in>A. \\<forall>b'\\<in>B. dist a b \\<le> dist a' b')\"\nOur comment on the codex statement: perfect!\n *)\ntheorem exercise_2_46: \n  fixes A B::\"'a::metric_space set\"\n  assumes \"compact A\" \"compact B\" \"A \\<inter> B = {}\" \"A \\<noteq> {}\" \"B \\<noteq> {}\"\n  shows \"\\<exists>a0 b0. a0\\<in>A \\<and> b0\\<in>B \\<and> (\\<forall>a\\<in>A. \\<forall>b\\<in>B. dist a0 b0 \\<le> dist a b)\"\n  oops\n\n\n(*\nproblem_number:2_48\nnatural language statement:\nProve that there is an embedding of the line as a closed subset of the plane, and there is an embedding of the line as a bounded subset of the plane, but there is no embedding of the line as a closed and bounded subset of the plane.\nlean statement:\n\ncodex statement:\ntheorem exists_embedding_of_line_as_closed_subset_of_plane:\n  fixes f::\"real \\<Rightarrow> 'a::euclidean_space\"\n  assumes \"continuous_on UNIV f\" \"inj_on f UNIV\" \"f ` UNIV \\<subseteq> (UNIV::'a set)\"\n  shows \"closedin (subtopology euclidean (UNIV::'a set)) (f ` UNIV)\"\nOur comment on the codex statement: <YOU CAN LEAVE YOUR COMMENT HERE>\n *)\ntheorem exercise_2_48: \n  shows \"\\<exists>f::real \\<Rightarrow> complex. inj f \\<and> closed (range f)\"\n        \"\\<exists>f::real \\<Rightarrow> complex. inj f \\<and> bounded (range f)\"\n        \"\\<nexists>f::real \\<Rightarrow> complex. inj f \\<and> closed (range f) \\<and> bounded (range f)\"\n  oops\n\n\n(*\nproblem_number:2_56\nnatural language statement:\nProve that the 2-sphere is not homeomorphic to the plane.\nlean statement:\n\ncodex statement:\ntheorem sphere_not_homeomorphic_to_plane:\n  fixes S::\"real^2 set\"\n  assumes \"S homeomorphic (sphere (0,1))\"\n  shows False\nOur comment on the codex statement: <YOU CAN LEAVE YOUR COMMENT HERE>\n *)\ntheorem exercise_2_56: \"\\<not> sphere (0::real^3) 1 homeomorphic (UNIV::complex set)\"\n  oops\n\n\n(*\nproblem_number:2_57\nnatural language statement:\nShow that if $S$ is connected, it is not true in general that its interior is connected.\nlean statement:\ntheorem exercise_2_57 {X : Type*} [topological_space X]\n  : \\<exists> (S : set X), is_connected S \\<and> \\<not> is_connected (interior S) :=\n\ncodex statement:\ntheorem interior_not_connected_of_connected:\n  fixes S::\"'a::euclidean_space set\"\n  assumes \"connected S\"\n  shows \"\\<exists>T. open T \\<and> connected T \\<and> interior T \\<subseteq> S \\<and> interior T \\<noteq> \\<emptyset> \\<and> interior T \\<noteq> S\"\nOur comment on the codex statement: <YOU CAN LEAVE YOUR COMMENT HERE>\n *)\ntheorem exercise_2_57: \n    shows \"\\<exists>S. connectedin X S \\<and> \\<not> connectedin X (X interior_of S)\"\noops\n\n\n(*\nproblem_number:2_79\nnatural language statement:\nProve that if $M$ is nonempty compact, locally path-connected and connected then it is path-connected.\nlean statement:\ntheorem exercise_2_79\n  {M : Type*} [topological_space M] [compact_space M]\n  [loc_path_connected_space M] (hM : nonempty M)\n  (hM : connected_space M) : path_connected_space M :=\n\ncodex statement:\ntheorem path_connected_of_nonempty_compact_locally_path_connected_connected:\n  fixes M::\"'a::topological_space set\"\n  assumes \"compact M\" \"nonempty M\" \"locally path_connected M\" \"connected M\"\n  shows \"path_connected M\"\nOur comment on the codex statement:  This version does not need the first two assumptions (why is the second one ever required)\n *)\ntheorem exercise_2_79: \n  fixes M::\"'a::topological_space set\"\n  assumes \"compact M\" \"M\\<noteq>{}\" \"locally path_connected M\" \"connected M\"\n  shows \"path_connected M\"\n  by (simp add: assms(3) assms(4) connected_component_eq_self path_component_eq_connected_component_set path_connected_component_set)\n\n\n(*\nproblem_number:2_85\nnatural language statement:\nSuppose that $M$ is compact and that $\\mathcal{U}$ is an open covering of $M$ which is redundant in the sense that each $p \\in M$ is contained in at least two members of $\\mathcal{U}$. Show that $\\mathcal{U}$ reduces to a finite subcovering with the same property.\nlean statement:\ntheorem exercise_2_85\n  (M : Type* ) [topological_space M] [compact_space M]\n  (U : set (set M)) (hU : \\<forall> p, \\<exists> (U_1 U_2 \\<in> U), p \\<in> U_1 \\<and> p \\<in> U_2 \\<and> U_1 \\<noteq> U_2) :\n  \\<exists> (V : set (set M)), set.finite V \\<and>\n  \\<forall> p, \\<exists> (V_1 V_2 \\<in> V), p \\<in> V_1 \\<and> p \\<in> V_2 \\<and> V_1 \\<noteq> V_2 :=\n\ncodex statement:\ntheorem finite_subcovering_of_redundant_open_covering:\n  fixes M::\"'a::metric_space set\" and U::\"'a set set\"\n  assumes \"compact M\" \"\\<forall>p\\<in>M. \\<exists>U_1 U_2. U_1\\<in>U \\<and> U_2\\<in>U \\<and> p\\<in>U_1 \\<and> p\\<in>U_2\"\n  shows \"\\<exists>U'. finite U' \\<and> U' \\<subseteq> U \\<and> \\<forall>p\\<in>M. \\<exists>U_1 U_2. U_1\\<in>U' \\<and> U_2\\<in>U' \\<and> p\\<in>U_1 \\<and> p\\<in>U_2\"\nOur comment on the codex statement:  very good except for missing parentheses\n *)\ntheorem exercise_2_85: \n  fixes M::\"'a::metric_space set\" and \\<U>::\"'a set set\"\n  assumes \"compact M\" \"\\<forall>p\\<in>M. \\<exists>V W. V\\<in>\\<U> \\<and> W\\<in>\\<U> \\<and> p\\<in>V \\<and> p\\<in>W\"\n  shows \"\\<exists>\\<U>'. finite \\<U>' \\<and> \\<U>' \\<subseteq> \\<U> \\<and> (\\<forall>p\\<in>M. \\<exists>V W. V\\<in>\\<U>' \\<and> W\\<in>\\<U>' \\<and> p\\<in>V \\<and> p\\<in>W)\"\n  oops\n\n\n(*\nproblem_number:2_92\nnatural language statement:\nGive a direct proof that the nested decreasing intersection of nonempty covering compact sets is nonempty.\nlean statement:\ntheorem exercise_2_92 {\\<alpha> : Type*} [topological_space \\<alpha>]\n  {s : \\<nat> \\<rightarrow> set \\<alpha>}\n  (hs : \\<forall> i, is_compact (s i))\n  (hs : \\<forall> i, (s i).nonempty)\n  (hs : \\<forall> i, (s i) \\<supset> (s (i + 1))) :\n  (\\<Inter> i, s i).nonempty :=\n\ncodex statement:\ntheorem nonempty_intersection_of_nested_compact_covering_sets:\n  fixes K::\"nat \\<Rightarrow> 'a::metric_space set\"\n  assumes \"\\<forall>n. compact (K n)\" \"\\<forall>n. K n \\<subseteq> K (Suc n)\" \"\\<forall>n. K n \\<noteq> {}\"\n  shows \"\\<exists>x. \\<forall>n. x \\<in> K n\"\nOur comment on the codex statement:  the sunset inclusion was in the wrong direction! (What does \"covering\" mean here?)\n *)\ntheorem exercise_2_92: \n  fixes K::\"nat \\<Rightarrow> 'a::metric_space set\"\n  assumes \"\\<forall>n. compact (K n)\" \"\\<forall>n. K (Suc n) \\<subseteq> K n\" \"\\<forall>n. K n \\<noteq> {}\"\n  shows \"\\<exists>x. \\<forall>n. x \\<in> K n\"\n  oops\n\n\n(*\nproblem_number:2_109\nnatural language statement:\nA metric on $M$ is an ultrametric if for all $x, y, z \\in M$, $d(x, z) \\leq \\max \\{d(x, y), d(y, z)\\} .$ Show that a metric space with an ultrametric is totally disconnected.\nlean statement:\ntheorem exercise_2_109\n  {M : Type*} [metric_space M]\n  (h : \\<forall> x y z : M, dist x z = max (dist x y) (dist y z)) :\n  totally_disconnected_space M :=\n\ncodex statement:\ntheorem totally_disconnected_of_ultrametric:\n  fixes M::\"'a::metric_space metric\"\n  assumes \"\\<forall>x y z. dist x z \\<le> max (dist x y) (dist y z)\"\n  shows \"totally_disconnected (UNIV::'a set)\"\nOur comment on the codex statement: <YOU CAN LEAVE YOUR COMMENT HERE>\n *)\ntheorem exercise_2_109: undefined oops\n\n\n(*\nproblem_number:2_126\nnatural language statement:\nSuppose that $E$ is an uncountable subset of $\\mathbb{R}$. Prove that there exists a point $p \\in \\mathbb{R}$ at which $E$ condenses.\nlean statement:\ntheorem exercise_2_126 {E : set \\<real>}\n  (hE : \\<not> set.countable E) : \\<exists> (p : \\<real>), cluster_pt p (\ud835\udcdf E) :=\n\ncodex statement:\ntheorem exists_condensation_point_of_uncountable_subset:\n  fixes E::\"real set\"\n  assumes \"uncountable E\"\n  shows \"\\<exists>p. condensation_point E p\"\nOur comment on the codex statement: <YOU CAN LEAVE YOUR COMMENT HERE>\n *)\ntheorem exercise_2_126: \n  fixes E::\"real set\"\n  assumes \"uncountable E\"\n  shows \"\\<exists>p. p islimpt E\"\n  oops\n\n\n(*\nproblem_number:2_137\nnatural language statement:\nLet $P$ be a closed perfect subset of a separable complete metric space $M$. Prove that each point of $P$ is a condensation point of $P$.\nlean statement:\ntheorem exercise_2_137\n  {M : Type*} [metric_space M] [separable_space M] [complete_space M]\n  {P : set M} (hP : is_closed P)\n  (hP' : is_closed P \\<and> P = {x | cluster_pt x (\ud835\udcdf P)}) :\n  \\<forall> x \\<in> P, \\<forall> n \\<in> (\ud835\udcdd x), \\<not> set.countable n :=\n\ncodex statement:\ntheorem condensation_point_of_closed_perfect_subset:\n  fixes P::\"'a::metric_space set\"\n  assumes \"closed P\" \"perfect P\" \"separable (UNIV::'a set)\"\n  shows \"\\<forall>x\\<in>P. condensation_point P x\"\nOur comment on the codex statement: <YOU CAN LEAVE YOUR COMMENT HERE>\n *)\ntheorem exercise_2_137: undefined oops\n\n\n(*\nproblem_number:2_138\nnatural language statement:\nGiven a Cantor space $M \\subset R^2$, given a line segment $[p, q] \\subset R^2$ with $p, q \\not\\in M$, and given an $\\epsilon > 0$, prove that there exists a path $A$ in the $\\epsilon$-neighborhood of $[p, q]$ that joins $p$ to $q$ and is disjoint from $M$.\nlean statement:\n\ncodex statement:\ntheorem exists_path_disjoint_of_Cantor_space:\n  fixes M::\"real set\" and p q::\"real^2\" and \\<epsilon>::real\n  assumes \"Cantor_space M\" \"p \\<in> (UNIV::real^2 set) - M\" \"q \\<in> (UNIV::real^2 set) - M\" \"\\<epsilon> > 0\"\n  shows \"\\<exists>A. path A \\<and> path_image A \\<subseteq> ball p \\<epsilon> \\<union> ball q \\<epsilon> \\<and> pathstart A = p \\<and> pathfinish A = q \\<and> path_image A \\<inter> M = {}\"\nOur comment on the codex statement: <YOU CAN LEAVE YOUR COMMENT HERE>\n *)\ntheorem exercise_2_138: undefined oops\n\n\n\n(*\nproblem_number:3_1\nnatural language statement:\nAssume that $f \\colon \\mathbb{R} \\rightarrow \\mathbb{R}$ satisfies $|f(t)-f(x)| \\leq|t-x|^{2}$ for all $t, x$. Prove that $f$ is constant.\nlean statement:\ntheorem exercise_3_1 {f : \\<real> \\<rightarrow> \\<real>}\n  (hf : \\<forall> x y, |f x - f y| \\<le> |x - y| ^ 2) :\n  \\<exists> c, f = \\<lambda> x, c :=\n\ncodex statement:\ntheorem constant_of_abs_diff_leq_square_diff:\n  fixes f::\"real \\<Rightarrow> real\"\n  assumes \"\\<forall>x t. abs (f t - f x) \\<le> (abs (t - x))^2\"\n  shows \"f constant_on UNIV\"\nOur comment on the codex statement: <YOU CAN LEAVE YOUR COMMENT HERE>\n *)\ntheorem exercise_3_1: \n  fixes f::\"real \\<Rightarrow> real\"\n  assumes \"\\<forall>x t. \\<bar>f t - f x\\<bar> \\<le> \\<bar>t - x\\<bar>^2\"\n  shows \"f constant_on UNIV\"\n  oops\n\n\n(*\nproblem_number:3_4\nnatural language statement:\nProve that $\\sqrt{n+1}-\\sqrt{n} \\rightarrow 0$ as $n \\rightarrow \\infty$.\nlean statement:\ntheorem exercise_3_4 (n : \\<nat>) :\n  tendsto (\\<lambda> n, (sqrt (n + 1) - sqrt n)) at_top (\ud835\udcdd 0) :=\n\ncodex statement:\ntheorem sqrt_succ_sub_sqrt_tendsto_zero:\n  shows \"(\\<Sum>i=0..n. 1/(sqrt (real (Suc i)) + sqrt (real i))) \\<longrightarrow> 0\"\nOur comment on the codex statement: This went completely wrong!\n *)\ntheorem exercise_3_4: \n  shows \"(\\<lambda>n. sqrt (real (Suc n)) - sqrt (real n)) \\<longlonglongrightarrow> 0\"\n  oops\n\n\n(*\nproblem_number:3_11a\nnatural language statement:\nLet $f \\colon (a, b) \\rightarrow \\mathbb{R}$ be given.  If $f''(x)$ exists, prove that \\[\\lim_{h \\rightarrow 0} \\frac{f(x - h) - 2f(x) + f(x + h)}{h^2} = f''(x).\\]\nlean statement:\ntheorem exercise_3_11a\n  {f : \\<real> \\<rightarrow> \\<real>} {a b x : \\<real>}\n  (h1 : differentiable_within_at \\<real> f (set.Ioo a b) x)\n  (h2 : differentiable_within_at \\<real> (deriv f) (set.Ioo a b) x) :\n  \\<exists> l, tendsto (\\<lambda> h, (f (x - h) - 2 * f x + f (x + h)) / h ^ 2) (\ud835\udcdd 0) (\ud835\udcdd l)\n  \\<and> deriv (deriv f) x = l :=\n\ncodex statement:\ntheorem limit_of_diff_of_diff_eq_diff_of_diff:\n  fixes f::\"real \\<Rightarrow> real\"\n  assumes \"\\<forall>x. (f has_real_derivative f' x) (at x)\" \"\\<forall>x. (f has_real_derivative f'' x) (at x)\"\n  shows \"(f'' ---> f'' x) (at x)\"\nOur comment on the codex statement:  Conclusion completely wrong\n *)\ntheorem exercise_3_11a: \n  fixes f::\"real \\<Rightarrow> real\"\n  assumes \"a < x\" \"x < b\" \n    and \"(f has_derivative f') (at x within {a<..<b})\" \n    and \"(f' has_derivative f'') (at x within {a<..<b})\"\n  shows \"((\\<lambda>h. (f (x - h) - 2 * f x + f (x + h)) / h ^ 2) \\<longlongrightarrow> f'' x) (at 0)\"\n  oops\n\n\n(*\nproblem_number:3_17c-i\nnatural language statement:\nShow that the bump function $\\beta(x)=e^{2} e(1-x) \\cdot e(x+1)$ is smooth.\nlean statement:\n\ncodex statement:\ntheorem smooth_of_bump_function:\n  fixes x::real\n  assumes \"x\\<in>{-1..1}\"\n  shows \"\\<forall>n. (\\<partial>^n) (\\<lambda>x. exp 2 * exp (-x) * exp (x+1)) x = exp 2 * exp (-x) * exp (x+1)\"\nOur comment on the codex statement: <YOU CAN LEAVE YOUR COMMENT HERE>\n *)\ntheorem \"exercise_3_17c-i\": undefined oops (* we have no way to express smoothness*)\n\n\n(*\nproblem_number:3_17c-ii\nnatural language statement:\nShow that the bump function $\\beta(x)=e^{2} e(1-x) \\cdot e(x+1)$ is identically 0 outside the interval $(-1, 1)$.\nlean statement:\n\ncodex statement:\ntheorem bump_function_is_zero_outside_interval:\n  fixes x::real\n  shows \"x\\<le>-1 \\<or> x\\<ge>1 \\<longrightarrow> (\\<lambda>x. exp 2 * exp (-x) * exp (x+1)) x = 0\"\nOur comment on the codex statement: <YOU CAN LEAVE YOUR COMMENT HERE>\n *)\ntheorem \"exercise_3_17c-ii\": undefined oops (* impossible to interpret this formula, and the conclusion seems to be false*)\n\n\n(*\nproblem_number:3_18\nnatural language statement:\nLet $L$ be any closed set in $\\mathbb{R}$. Prove that there is a smooth function $f \\colon \\mathbb{R} \\rightarrow [0, 1]$ such that $f(x) = 0$ if and only if $x \\in L$.\nlean statement:\n\ncodex statement:\ntheorem exists_smooth_function_of_closed_set:\n  fixes L::\"real set\"\n  assumes \"closed L\"\n  shows \"\\<exists>f. (\\<forall>x. f x = 0 \\<longleftrightarrow> x\\<in>L) \\<and> (\\<forall>x. f differentiable (at x))\"\nOur comment on the codex statement: <YOU CAN LEAVE YOUR COMMENT HERE>\n *)\ntheorem exercise_3_18: undefined oops (* we have no way to express smoothness*)\n\n\n(*\nproblem_number:3_43a\nnatural language statement:\nLet $\\psi(x) = x \\sin 1/x$ for $0 < x \\leq 1$ and $\\psi(0) = 0$.  If $f \\colon [-1, 1] \\rightarrow \\mathbb{R}$ is Riemann integrable, prove that $f \\circ \\psi$ is Riemann integrable.\nlean statement:\n\ncodex statement:\ntheorem riemann_integrable_of_riemann_integrable_comp:\n  fixes f::\"real \\<Rightarrow> real\" and \\<psi>::\"real \\<Rightarrow> real\"\n  assumes \"continuous_on {0..1} \\<psi>\" \"f integrable_on {-1..1}\"\n  shows \"(f \\<circ> \\<psi>) integrable_on {0..1}\"\nOur comment on the codex statement: <YOU CAN LEAVE YOUR COMMENT HERE>\n *)\ntheorem exercise_3_43a: undefined oops (* we do not have Riemann integrals*)\n\n\n(*\nproblem_number:3_53\nnatural language statement:\nGiven $f, g \\in \\mathcal{R}$, prove that $\\max(f, g)$ and $\\min(f, g)$ are Riemann integrable, where $\\max(f, g)(x) = \\max(f(x), g(x))$ and $\\min(f, g)(x) = \\min(f(x), g(x))$.\nlean statement:\n\ncodex statement:\ntheorem max_min_integrable:\n  fixes f g::\"real \\<Rightarrow> real\"\n  assumes \"f integrable_on {a..b}\" \"g integrable_on {a..b}\"\n  shows \"(\\<lambda>x. max (f x) (g x)) integrable_on {a..b}\" \"(\\<lambda>x. min (f x) (g x)) integrable_on {a..b}\"\nOur comment on the codex statement: <YOU CAN LEAVE YOUR COMMENT HERE>\n *)\ntheorem exercise_3_53: undefined oops(* we do not have Riemann integrals*)\n\n\n(*\nproblem_number:3_59\nnatural language statement:\nProve that if $a_n \\geq 0$ and $\\sum a_n$ converges then $\\sum \\sqrt{a_n}/n$ converges.\nlean statement:\n\ncodex statement:\ntheorem convergent_of_convergent_sum_sqrt_div_n:\n  fixes a::\"nat \\<Rightarrow> real\"\n  assumes \"\\<forall>n. 0 \\<le> a n\" \"summable a\"\n  shows \"summable (\\<lambda>n. sqrt (a n) / n)\"\nOur comment on the codex statement: Perfect!\n *)\ntheorem exercise_3_59: \n  fixes a::\"nat \\<Rightarrow> real\"\n  assumes \"\\<forall>n. 0 \\<le> a n\" \"summable a\"\n  shows \"summable (\\<lambda>n. sqrt (a n) / n)\"\n  oops\n\n\n(*\nproblem_number:3_63\nnatural language statement:\nProve that $\\sum 1/k(\\log(k))^p$ converges when $p > 1$ and diverges when $p \\leq 1$.\nlean statement:\ntheorem exercise_3_63a (p : \\<real>) (f : \\<nat> \\<rightarrow> \\<real>) (hp : p > 1)\n  (h : f = \\<lambda> k, (1 : \\<real>) / (k * (log k) ^ p)) :\n  \\<exists> l, tendsto f at_top (\ud835\udcdd l) :=\n\ncodex statement:\ntheorem sum_of_inverse_log_pow_p_converges_of_p_gt_1:\n  fixes p::real\n  assumes \"p > 1\"\n  shows \"summable (\\<lambda>n. 1 / (real n * (log (real n)) ^ p))\"\nOur comment on the codex statement:  correct except for log (should be ln) and ^ (should be powr)\n *)\ntheorem exercise_3_63a: \n  fixes p::real\n  assumes \"p > 1\"\n  shows \"summable (\\<lambda>n. 1 / (real n * (ln (real n) powr p)))\"\n  oops\n\ntheorem exercise_3_63b: \n  fixes p::real\n  assumes \"p \\<le> 1\"\n  shows \"\\<not> summable (\\<lambda>n. 1 / (real n * (ln (real n) powr p)))\"\n  oops\n\n\n\n(*\nproblem_number:4_15a\nnatural language statement:\nA continuous, strictly increasing function $\\mu \\colon (0, \\infty) \\rightarrow (0, \\infty)$ is a modulus of continuity if $\\mu(s) \\rightarrow 0$ as $s \\rightarrow 0$. A function $f \\colon [a, b] \\rightarrow \\mathbb{R}$ has modulus of continuity $\\mu$ if $|f(s) - f(t)| \\leq \\mu(|s - t|)$ for all $s, t \\in [a, b]$. Prove that a function is uniformly continuous if and only if it has a modulus of continuity.\nlean statement:\ntheorem exercise_4_15a {\\<alpha> : Type*}\n  (a b : \\<real>) (F : set (\\<real> \\<rightarrow> \\<real>)) :\n  (\\<forall> (x : \\<real>) (\\<epsilon> > 0), \\<exists> (U \\<in> (\ud835\udcdd x)),\n  (\\<forall> (y z \\<in> U) (f : \\<real> \\<rightarrow> \\<real>), f \\<in> F \\<rightarrow> (dist (f y) (f z) < \\<epsilon>)))\n  \\<longleftrightarrow>\n  \\<exists> (\\<mu> : \\<real> \\<rightarrow> \\<real>), \\<forall> (x : \\<real>), (0 : \\<real>) \\<le> \\<mu> x \\<and> tendsto \\<mu> (\ud835\udcdd 0) (\ud835\udcdd 0) \\<and>\n  (\\<forall> (s t : \\<real>) (f : \\<real> \\<rightarrow> \\<real>), f \\<in> F \\<rightarrow> |(f s) - (f t)| \\<le> \\<mu> (|s - t|)) :=\n\ncodex statement:\ntheorem uniform_continuous_iff_has_modulus_of_continuity:\n  fixes f::\"'a::metric_space \\<Rightarrow> 'b::metric_space\" and \\<mu>::\"'a \\<Rightarrow> 'b\"\n  assumes \"continuous_on UNIV \\<mu>\" \"strict_mono \\<mu>\" \"\\<mu> \\<longrightarrow> 0 at_top\" \"\\<forall>s t. s \\<in> UNIV \\<longrightarrow> t \\<in> UNIV \\<longrightarrow> dist s t \\<le> \\<mu> (dist s t)\"\n  shows \"uniformly_continuous_on UNIV f\"\nOur comment on the codex statement: <YOU CAN LEAVE YOUR COMMENT HERE>\n *)\n\ndefinition \"is_modulus_continuity \n  \\<equiv> \\<lambda> \\<mu>. continuous_on {0<..} \\<mu> \\<and> strict_mono_on {0<..} \\<mu> \\<and> \\<mu> \\<in> {0<..} \\<rightarrow> {0<..} \\<and> (\\<mu> \\<longlongrightarrow> 0) (at 0 within {0<..})\"\n\ndefinition \"has_modulus_continuity \n  \\<equiv> \\<lambda> \\<mu> f a b. is_modulus_continuity \\<mu> \\<and> (\\<forall>x \\<in> {a..b}. \\<forall>y \\<in> {a..b}. \\<bar>f x - f y\\<bar> \\<le> \\<mu>\\<bar>x-y\\<bar>)\"\n\ntheorem exercise_4_15a: \n  fixes f::\"real \\<Rightarrow> real\"\n  shows \"uniformly_continuous_on {a..b} f \\<longleftrightarrow> (\\<exists>\\<mu>. has_modulus_continuity \\<mu> f a b)\"\n  oops\n\n\n(*\nproblem_number:4_15b\nnatural language statement:\nA continuous, strictly increasing function $\\mu \\colon (0, \\infty) \\rightarrow (0, \\infty)$ is a modulus of continuity if $\\mu(s) \\rightarrow 0$ as $s \\rightarrow 0$. A function $f \\colon [a, b] \\rightarrow \\mathbb{R}$ has modulus of continuity $\\mu$ if $|f(s) - f(t)| \\leq \\mu(|s - t|)$ for all $s, t \\in [a, b]$. Prove that a family of functions is equicontinuous if and only if its members.\nlean statement:\n\ncodex statement:\ntheorem equicontinuous_of_modulus_of_continuity:\n  fixes f::\"'a::metric_space \\<Rightarrow> 'b::metric_space\" and g::\"'a::metric_space \\<Rightarrow> 'b::metric_space\"\n  assumes \"\\<forall>x. continuous (at x) f\" \"\\<forall>x. continuous (at x) g\" \"\\<forall>x. continuous (at x within s) f\" \"\\<forall>x. continuous (at x within s) g\"\n  shows \"uniformly_continuous_on s f\" \"uniformly_continuous_on s g\"\nOur comment on the codex statement: <YOU CAN LEAVE YOUR COMMENT HERE>\n *)\ntheorem exercise_4_15b: \n  fixes \\<F>::\"(real \\<Rightarrow> real) set\"\n  assumes \"a<b\"\n  shows \"(\\<forall>e>0. \\<exists>d>0. \\<forall>f \\<in> \\<F>. \\<forall>x \\<in> {a..b}. \\<forall>x' \\<in> {a..b}. \\<bar>x'-x\\<bar> < d \\<longrightarrow> \\<bar>f x' - f x\\<bar> < e)\n     \\<longleftrightarrow> (\\<exists>\\<mu>. \\<forall>f \\<in> \\<F>. has_modulus_continuity \\<mu> f a b)\"\n  oops\n\n\n(*\nproblem_number:4_19\nnatural language statement:\nIf $M$ is compact and $A$ is dense in $M$, prove that for each $\\delta > 0$ there is a finite subset $\\{a_1, \\ldots , a_k\\} \\subset A$ which is $\\delta$-dense in $M$ in the sense that each $x \\in M$ lies within distance $\\delta$ of at least one of the points $a_1,\\ldots, a_k$.\nlean statement:\ntheorem exercise_4_19 {M : Type*} [metric_space M]\n  [compact_space M] (A : set M) (hA : dense A) (\\<delta> : \\<real>) (h\\<delta> : \\<delta> > 0) :\n  \\<exists> (A_fin : set M), A_fin \\<subset> A \\<and> set.finite A_fin \\<and> \\<forall> (x : M), \\<exists> i \\<in> A_fin, dist x i < \\<delta> :=\n\ncodex statement:\ntheorem exists_finite_delta_dense_of_compact_dense:\n  fixes M::\"'a::metric_space set\" and A::\"'a set\"\n  assumes \"compact M\" \"A \\<subseteq> M\" \"dense A\"\n  shows \"\\<exists>A'. finite A' \\<and> A' \\<subseteq> A \\<and> \\<forall>x\\<in>M. \\<exists>a\\<in>A'. dist x a < \\<delta>\"\nOur comment on the codex statement: <YOU CAN LEAVE YOUR COMMENT HERE>\n *)\ntheorem exercise_4_19: \n  fixes M::\"'a::metric_space set\" and A::\"'a set\"\n  assumes \"compact M\" \"A \\<subseteq> M\" \"M \\<subseteq> closure A\" \"\\<delta> > 0\"\n  shows \"\\<exists>A'. finite A' \\<and> A' \\<subseteq> A \\<and> (\\<forall>x\\<in>M. \\<exists>a\\<in>A'. dist x a < \\<delta>)\"\n  oops\n\n\n(*\nproblem_number:4_36a\nnatural language statement:\nSuppose that the ODE $x' = f(x)$ on $\\mathbb{R}$ is bounded, $|f(x)| \\leq M$ for all x. Prove that no solution of the ODE escapes to infinity in finite time.\nlean statement:\n\ncodex statement:\ntheorem no_solution_escapes_to_infinity_in_finite_time:\n  fixes f::\"real \\<Rightarrow> real\"\n  assumes \"\\<forall>x. abs (f x) \\<le> M\"\n  shows \"\\<forall>x0 t. \\<exists>x. x0 + t * f x0 = x\"\nOur comment on the codex statement: <YOU CAN LEAVE YOUR COMMENT HERE>\n *)\ntheorem exercise_4_36a: undefined oops\n\n\n(*\nproblem_number:4_42\nnatural language statement:\nProve that $\\mathbb{R}$ cannot be expressed as the countable union of Cantor sets.\nlean statement:\n\ncodex statement:\ntheorem cantor_set_not_union_of_countable_cantor_sets:\n  fixes C::\"real set\"\n  assumes \"\\<forall>x\\<in>C. \\<exists>a b. x = a + b \\<and> a \\<in> cantor \\<and> b \\<in> cantor\" \"countable C\"\n  shows \"False\"\nOur comment on the codex statement: <YOU CAN LEAVE YOUR COMMENT HERE>\n *)\ntheorem exercise_4_42: undefined oops(* we do not have a formalisation of Cantor sets*)\n\n\n(*\nproblem_number:5_2\nnatural language statement:\nLet $L$ be the vector space of continuous linear transformations from a normed space $V$ to a normed space $W$. Show that the operator norm makes $L$ a normed space.\nlean statement:\ntheorem exercise_5_2 {V : Type*} [normed_add_comm_group V]\n  [normed_space \\<complex> V] {W : Type*} [normed_add_comm_group W] [normed_space \\<complex> W] :\n  normed_space \\<complex> (continuous_linear_map (id \\<complex>) V W) :=\n\ncodex statement:\ntheorem norm_of_linear_transformation_is_norm:\n  fixes V::\"'a::real_normed_vector normed_vector\" and W::\"'b::real_normed_vector normed_vector\"\n  assumes \"linear f\"\n  shows \"norm f = \\<parallel>f\\<parallel>\"\nOur comment on the codex statement: <YOU CAN LEAVE YOUR COMMENT HERE>\n *)\ntheorem exercise_5_2: undefined oops\n\n\n(*\nproblem_number:5_20\nnatural language statement:\nAssume that $U$ is a connected open subset of $\\mathbb{R}^n$ and $f \\colon U \\rightarrow \\mathbb{R}^m$ is differentiable everywhere on $U$. If $(Df)_p = 0$ for all $p \\in U$, show that $f$ is constant.\nlean statement:\n\ncodex statement:\ntheorem constant_of_differentiable_zero:\n  fixes f::\"'a::euclidean_space \\<Rightarrow> 'b::euclidean_space\"\n  assumes \"connected U\" \"open U\" \"\\<forall>x\\<in>U. f differentiable (at x)\" \"\\<forall>x\\<in>U. (D f) x = 0\"\n  shows \"f constant_on U\"\nOur comment on the codex statement:  not bad, but we have no D!\n *)\n\ntheorem exercise_5_20: \n  fixes f::\"'a::euclidean_space \\<Rightarrow> 'b::euclidean_space\"\n  assumes \"connected U\" \"open U\" \"\\<forall>x\\<in>U. (f has_derivative (\\<lambda>x. 0)) (at x)\" \n  shows \"f constant_on U\"\n  by (smt (verit, best) assms constant_on_def has_derivative_zero_unique_connected)\n\n\n(*\nproblem_number:5_22\nnatural language statement:\nIf $Y$ is a metric space and $f \\colon [a, b] \\times Y \\rightarrow \\mathbb{R}$ is continuous, show that $F(y) = \\int^b_a f(x,y) dx$ is continuous.\nlean statement:\n\ncodex statement:\ntheorem continuous_of_continuous_integral:\n  fixes f::\"'a::metric_space \\<Rightarrow> 'b::metric_space \\<Rightarrow> 'c::metric_space\"\n  assumes \"continuous_on (UNIV::'a set) (\\<lambda>y. \\<integral> {a..b} (f x y) dx)\"\n  shows \"continuous_on (UNIV::'b set) (\\<lambda>y. \\<integral> {a..b} (f x y) dx)\"\nOur comment on the codex statement:  Wrong all the way\n *)\ntheorem exercise_5_22:   (*Lebesgue integrals seem to be expected here*)\n  fixes f::\"real * 'a::metric_space \\<Rightarrow> real\"\n  assumes \"continuous_on UNIV f\"\n    shows \"\\<forall>y\\<in>Y. integrable (lebesgue_on {a..b}) (\\<lambda>x. f (x,y))\" \"continuous_on Y (\\<lambda>y. integral\\<^sup>L (lebesgue_on {a..b}) (\\<lambda>x. f (x,y)))\"\n  oops\n\n\n(*\nproblem_number:5_43a\nnatural language statement:\nSuppose that $T \\colon R^n \\rightarrow R^m$ has rank $k$.  Show there exists a $\\delta > 0$ such that if $S \\colon R^n \\rightarrow R^m$ and $||S - T|| < \\delta$ then $S$ has rank $\\geq k$.\nlean statement:\n\ncodex statement:\ntheorem exists_delta_of_rank_leq_rank_of_norm_lt_delta:\n  fixes T::\"'a::euclidean_space \\<Rightarrow> 'b::euclidean_space\" and S::\"'a::euclidean_space \\<Rightarrow> 'b::euclidean_space\"\n  assumes \"linear T\" \"linear S\" \"rank T = k\"\n  shows \"\\<exists>\\<delta>>0. \\<forall>S. linear S \\<longrightarrow> (\\<parallel>S - T\\<parallel> < \\<delta> \\<longrightarrow> rank S \\<ge> k)\"\nOur comment on the codex statement: <YOU CAN LEAVE YOUR COMMENT HERE>\n *)\ntheorem exercise_5_43a: undefined oops\n\n\n(*\nproblem_number:6_38\nnatural language statement:\nIf $f$ and $g$ are integrable prove that their maximum and minimum are integrable.\nlean statement:\n\ncodex statement:\ntheorem integrable_max_min:\n  fixes f g::\"'a::euclidean_space \\<Rightarrow> 'b::banach\"\n  assumes \"integrable M f\" \"integrable M g\"\n  shows \"integrable M (\\<lambda>x. max (f x) (g x))\" \"integrable M (\\<lambda>x. min (f x) (g x))\"\nOur comment on the codex statement: <YOU CAN LEAVE YOUR COMMENT HERE>\n *)\ntheorem exercise_6_38: \n  fixes f g::\"'a::euclidean_space \\<Rightarrow> real\"\n  assumes \"integrable M f\" \"integrable M g\"\n  shows \"integrable M (\\<lambda>x. max (f x) (g x))\" \"integrable M (\\<lambda>x. min (f x) (g x))\"\n  using assms by blast+\n\n(*\nproblem_number:6_39\nnatural language statement:\nSuppose that $f$ and $g$ are measurable and their squares are integrable. Prove that $fg$ is measurable, integrable, and $\\int fg \\leq \\sqrt{\\int f^2} \\sqrt{\\int g^2}$.\nlean statement:\n\ncodex statement:\ntheorem integrable_of_integrable_square:\n  fixes f g::\"'a::euclidean_space \\<Rightarrow> real\"\n  assumes \"integrable lborel f\" \"integrable lborel g\"\n  shows \"integrable lborel (\\<lambda>x. f x * g x)\"\nOur comment on the codex statement: <YOU CAN LEAVE YOUR COMMENT HERE>\n *)\ntheorem exercise_6_39: \n  fixes f g::\"'a::euclidean_space \\<Rightarrow> real\"\n  assumes \"f \\<in> borel_measurable borel\" \"integrable lborel (\\<lambda>x. f x ^ 2)\" \n  assumes \"g \\<in> borel_measurable borel\" \"integrable lborel (\\<lambda>x. g x ^ 2)\"\n  shows \"(\\<lambda>x. f x * g x) \\<in> borel_measurable borel\" \"integrable lborel (\\<lambda>x. f x * g x)\" \n        \"integral\\<^sup>L lborel (\\<lambda>x. f x * g x) \\<le> sqrt (integral\\<^sup>L lborel (\\<lambda>x. f x ^ 2)) * sqrt (integral\\<^sup>L lborel (\\<lambda>x. g x ^ 2))\"\n   apply (simp add: borel_measurable_times assms)\n  oops\n\n\n(*\nproblem_number:6_43\nnatural language statement:\nProve that $g(y) = \\int_0^\\infty e^{-x} \\sin(x + y) dx$ is differentiable and find $g'(y)$.\nlean statement:\n\ncodex statement:\ntheorem diff_integral_of_exp_sin:\n  fixes y::real\n  shows \"((\\<lambda>x. exp (-x) * sin (x + y)) has_vector_derivative (exp (-y) * cos y)) (at y)\"\nOur comment on the codex statement: Rather scrambled\n *)\ntheorem exercise_6_43: \n  fixes y::real\n  shows \"(\\<lambda>y::real. integral\\<^sup>L (lebesgue_on {0<..}) (\\<lambda>x. exp (-x) * sin (x + y))) differentiable_on {0<..}\"\n  oops\n\n\n(*\nproblem_number:6_49a\nnatural language statement:\nProve that $f \\colon \\mathbb{R} \\rightarrow \\mathbb{R}$ is Lebesgue measurable if and only if the preimage of every Borel set is a Lebesgue measurable.\nlean statement:\n\ncodex statement:\ntheorem lebesgue_measurable_of_preimage_borel_is_lebesgue_measurable:\n  fixes f::\"'a::euclidean_space \\<Rightarrow> 'b::euclidean_space\"\n  assumes \"\\<forall>s. borel_measurable s \\<longrightarrow> borel_measurable (f -` s)\"\n  shows \"lebesgue_measurable f\"\nOur comment on the codex statement:  not completely wrong\n *)\ntheorem exercise_6_49a:  (*Not sure I have formalised measurable sets and functions correctly*)\n  assumes \"\\<forall>S. S \\<in> fmeasurable borel \\<longrightarrow> (f -` S) \\<in> fmeasurable borel\"\n  shows \"f \\<in> measurable borel borel\"\n  oops\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/Pugh.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681013541613, "lm_q2_score": 0.8175744828610095, "lm_q1q2_score": 0.7012893118792984}}
{"text": "(* Author: Anthony Bordg, University of Cambridge, apdb3@cam.ac.uk *)\n\nsection \\<open>Complex Vectors\\<close>\n\ntheory Complex_Vectors\nimports \n  Quantum\n  VectorSpace.VectorSpace\nbegin\n\n\nsubsection \\<open>The Vector Space of Complex Vectors of Dimension n\\<close>\n\ndefinition module_cpx_vec:: \"nat \\<Rightarrow> (complex, complex vec) module\" where\n\"module_cpx_vec n \\<equiv> module_vec TYPE(complex) n\"\n\ndefinition cpx_rng:: \"complex ring\" where\n\"cpx_rng \\<equiv> \\<lparr>carrier = UNIV, mult = (*), one = 1, zero = 0, add = (+)\\<rparr>\"\n\nlemma cpx_cring_is_field [simp]:\n  \"field cpx_rng\"\n  apply unfold_locales\n                   apply (auto intro: right_inverse simp: cpx_rng_def Units_def field_simps)\n  by (metis add.right_neutral add_diff_cancel_left' add_uminus_conv_diff)\n\nlemma cpx_abelian_monoid [simp]:\n  \"abelian_monoid cpx_rng\"\n  using cpx_cring_is_field\n  by (simp add: field_def abelian_group_def cring_def domain_def ring_def)\n\nlemma vecspace_cpx_vec [simp]:\n  \"vectorspace cpx_rng (module_cpx_vec n)\"\n  apply unfold_locales\n                      apply (auto simp: cpx_rng_def module_cpx_vec_def module_vec_def Units_def field_simps)\n    apply (auto intro: right_inverse add_inv_exists_vec)\n  by (metis add.right_neutral add_diff_cancel_left' add_uminus_conv_diff)\n\n\n\ndefinition state_basis:: \"nat \\<Rightarrow> nat \\<Rightarrow> complex vec\" where\n\"state_basis n i \\<equiv> unit_vec (2^n) i\"\n\ndefinition unit_vectors:: \"nat \\<Rightarrow> (complex vec) set\" where\n\"unit_vectors n \\<equiv> {unit_vec n i | i::nat. 0 \\<le> i \\<and> i < n}\"\n\nlemma unit_vectors_carrier_vec [simp]:\n  \"unit_vectors n \\<subseteq> carrier_vec n\"\n  using unit_vectors_def by auto\n\nlemma (in Module.module) finsum_over_singleton [simp]:\n  assumes \"f x \\<in> carrier M\"\n  shows \"finsum M f {x} = f x\"\n  using assms by simp\n\nlemma lincomb_over_singleton [simp]:\n  assumes \"x \\<in> carrier_vec n\" and \"f \\<in> {x} \\<rightarrow> UNIV\"\n  shows \"module.lincomb (module_cpx_vec n) f {x} = f x \\<cdot>\\<^sub>v x\" \n  using assms module.lincomb_def module_cpx_vec module_cpx_vec_def module.finsum_over_singleton\n  by (smt module_vec_simps(3) module_vec_simps(4) smult_carrier_vec)\n\nlemma dim_vec_lincomb [simp]:\n  assumes \"finite F\" and \"f: F \\<rightarrow> UNIV\" and \"F \\<subseteq> carrier_vec n\"\n  shows \"dim_vec (module.lincomb (module_cpx_vec n) f F) = n\"\n  using assms\nproof(induct F)\n  case empty\n  show \"dim_vec (module.lincomb (module_cpx_vec n) f {}) = n\"\n  proof -\n    have \"module.lincomb (module_cpx_vec n) f {} = 0\\<^sub>v n\"\n      using module.lincomb_def abelian_monoid.finsum_empty module_cpx_vec_def vecspace_cpx_vec vectorspace_def\n      by (smt abelian_group_def Module.module_def module_vec_simps(2))\n    thus ?thesis by simp\n  qed\nnext\n  case (insert x F)\n  hence \"module.lincomb (module_cpx_vec n) f (insert x F) = \n    (f x \\<cdot>\\<^sub>v x) \\<oplus>\\<^bsub>module_cpx_vec n\\<^esub> module.lincomb (module_cpx_vec n) f F\"\n    using module_cpx_vec_def module_vec_def module_cpx_vec module.lincomb_insert cpx_rng_def insert_subset\n    by (smt Pi_I' UNIV_I Un_insert_right module_vec_simps(4) partial_object.select_convs(1) sup_bot.comm_neutral)\n  hence \"dim_vec (module.lincomb (module_cpx_vec n) f (insert x F)) = \n    dim_vec (module.lincomb (module_cpx_vec n) f F)\"\n    using index_add_vec by (simp add: module_cpx_vec_def module_vec_simps(1))\n  thus \"dim_vec (module.lincomb (module_cpx_vec n) f (insert x F)) = n\"\n    using insert.hyps(3) insert.prems(2) by simp\nqed\n\nlemma lincomb_vec_index [simp]:\n  assumes \"finite F\" and a2:\"i < n\" and \"F \\<subseteq> carrier_vec n\" and \"f: F \\<rightarrow> UNIV\"\n  shows \"module.lincomb (module_cpx_vec n) f F $ i = (\\<Sum>v\\<in>F. f v * (v $ i))\"\n  using assms\nproof(induct F)\n  case empty\n  then show \"module.lincomb (module_cpx_vec n) f {} $ i = (\\<Sum>v\\<in>{}. f v * v $ i)\"\n    apply auto\n    using a2 module.lincomb_def abelian_monoid.finsum_empty module_cpx_vec_def\n    by (metis (mono_tags) abelian_group_def index_zero_vec(1) module_cpx_vec Module.module_def module_vec_simps(2))\nnext\n  case(insert x F)\n  have \"module.lincomb (module_cpx_vec n) f (insert x F) = \n      f x \\<cdot>\\<^sub>v x \\<oplus>\\<^bsub>module_cpx_vec n\\<^esub> module.lincomb (module_cpx_vec n) f F\"\n    using module.lincomb_insert module_cpx_vec insert.hyps(1) module_cpx_vec_def module_vec_def\n      insert.prems(2) insert.hyps(2) insert.prems(3) insert_def\n    by (smt Pi_I' UNIV_I Un_insert_right cpx_rng_def insert_subset module_vec_simps(4) \n        partial_object.select_convs(1) sup_bot.comm_neutral)\n  then have \"module.lincomb (module_cpx_vec n) f (insert x F) $ i = \n      (f x \\<cdot>\\<^sub>v x) $ i + module.lincomb (module_cpx_vec n) f F $ i\"\n    using index_add_vec(1) a2 dim_vec_lincomb\n    by (metis Pi_split_insert_domain  insert.hyps(1) insert.prems(2) insert.prems(3) insert_subset \n        module_cpx_vec_def module_vec_simps(1))\n  hence \"module.lincomb (module_cpx_vec n) f (insert x F) $ i = f x * x $ i + (\\<Sum>v\\<in>F. f v * v $ i)\"\n    using index_smult_vec a2 insert.prems(2) insert_def insert.hyps(3) by auto\n  with insert show \"module.lincomb (module_cpx_vec n) f (insert x F) $ i = (\\<Sum>v\\<in>insert x F. f v * v $ i)\"\n    by auto\nqed\n\nlemma unit_vectors_is_lin_indpt [simp]:\n  \"module.lin_indpt cpx_rng (module_cpx_vec n) (unit_vectors n)\"\nproof\n  assume \"module.lin_dep cpx_rng (module_cpx_vec n) (unit_vectors n)\"\n  hence \"\\<exists>A a v. (finite A \\<and> A \\<subseteq> (unit_vectors n) \\<and> (a \\<in> A \\<rightarrow> UNIV) \\<and> \n    (module.lincomb (module_cpx_vec n) a A = \\<zero>\\<^bsub>module_cpx_vec n\\<^esub>) \\<and> (v \\<in> A) \\<and> (a v \\<noteq> \\<zero>\\<^bsub>cpx_rng\\<^esub>))\"\n    using module.lin_dep_def cpx_rng_def module_cpx_vec by (smt Pi_UNIV UNIV_I)\n  moreover obtain A and a and v where f1:\"finite A\" and f2:\"A \\<subseteq> (unit_vectors n)\" and \"a \\<in> A \\<rightarrow> UNIV\" \n    and f4:\"module.lincomb (module_cpx_vec n) a A = \\<zero>\\<^bsub>module_cpx_vec n\\<^esub>\" and f5:\"v \\<in> A\" and \n    f6:\"a v \\<noteq> \\<zero>\\<^bsub>cpx_rng\\<^esub>\"\n    using calculation by blast\n  moreover obtain i where f7:\"v = unit_vec n i\" and f8:\"i < n\"\n    using unit_vectors_def calculation by auto\n  ultimately have f9:\"module.lincomb (module_cpx_vec n) a A $ i = (\\<Sum>u\\<in>A. a u * (u $ i))\"\n    using lincomb_vec_index \n    by (smt carrier_dim_vec index_unit_vec(3) mem_Collect_eq subset_iff sum.cong unit_vectors_def)\n  moreover have \"\\<forall>u\\<in>A.\\<forall>j<n. u = unit_vec n j \\<longrightarrow> j \\<noteq> i \\<longrightarrow> a u * (u $ i) = 0\"\n    using unit_vectors_def index_unit_vec by (simp add: f8)\n  then have \"(\\<Sum>u\\<in>A. a u * (u $ i)) = (\\<Sum>u\\<in>A. if u=v then a v * v $ i else 0)\"\n    using f2 unit_vectors_def f7 by (smt mem_Collect_eq subsetCE sum.cong)\n  also have \"\\<dots> = a v * (v $ i)\"\n    using abelian_monoid.finsum_singleton[of cpx_rng v A \"\\<lambda>u\\<in>A. a u * (u $ i)\"] cpx_abelian_monoid\n      f5 f1 cpx_rng_def by simp\n  also have \"\\<dots> = a v\"\n    using f7 index_unit_vec f8 by simp\n  also have \"\\<dots> \\<noteq> 0\"\n    using f6 by (simp add: cpx_rng_def)\n  finally show False\n    using f4 module_cpx_vec_def module_vec_def index_zero_vec f8 f9 by (simp add: module_vec_simps(2))\nqed\n\nlemma unit_vectors_is_genset [simp]:\n  \"module.gen_set cpx_rng (module_cpx_vec n) (unit_vectors n)\"\nproof\n  show \"module.span cpx_rng (module_cpx_vec n) (unit_vectors n) \\<subseteq> carrier (module_cpx_vec n)\"\n    using module.span_def dim_vec_lincomb carrier_vec_def cpx_rng_def\n    by (smt Collect_mono index_unit_vec(3) module.span_is_subset2 module_cpx_vec module_cpx_vec_def \n        module_vec_simps(3) unit_vectors_def)\nnext\n  show \"carrier (module_cpx_vec n) \\<subseteq> module.span cpx_rng (module_cpx_vec n) (unit_vectors n)\"\n  proof\n    fix v\n    assume a1:\"v \\<in> carrier (module_cpx_vec n)\"\n    define A a lc where \"A = {unit_vec n i ::complex vec| i::nat. i < n \\<and> v $ i \\<noteq> 0}\" and \n      \"a = (\\<lambda>u\\<in>A. u \\<bullet> v)\" and \"lc = module.lincomb (module_cpx_vec n) a A\"\n    then have f1:\"finite A\" by simp\n    have f2:\"A \\<subseteq> carrier_vec n\"\n      using carrier_vec_def A_def by auto\n    have f3:\"a \\<in> A \\<rightarrow> UNIV\"\n      using a_def by simp\n    then have f4:\"dim_vec v = dim_vec lc\"\n      using f1 f2 f3 a1 module_cpx_vec_def dim_vec_lincomb lc_def by (simp add: module_vec_simps(3))\n    then have f5:\"i < n \\<Longrightarrow> lc $ i = (\\<Sum>u\\<in>A. u \\<bullet> v * u $ i)\" for i\n      using lincomb_vec_index lc_def a_def f1 f2 f3 by simp\n    then have \"i < n \\<Longrightarrow> j < n \\<Longrightarrow> j \\<noteq> i \\<Longrightarrow> unit_vec n j \\<bullet> v * unit_vec n j $ i = 0\" for i j by simp\n    then have \"i < n \\<Longrightarrow> lc $ i = (\\<Sum>u\\<in>A. if u = unit_vec n i then v $ i else 0)\" for i\n      using a1 A_def f5 scalar_prod_left_unit\n      by (smt f4 carrier_vecI dim_vec_lincomb f1 f2 f3 index_unit_vec(2) lc_def \n          mem_Collect_eq mult.right_neutral sum.cong)\n    then have \"i < n \\<Longrightarrow> lc $ i = v $ i\" for i\n      using abelian_monoid.finsum_singleton[of cpx_rng i] A_def cpx_rng_def by simp\n    then have f6:\"v = lc\"\n      using eq_vecI f4 dim_vec_lincomb f1 f2 lc_def by auto\n    have \"A \\<subseteq> unit_vectors n\"\n      using A_def unit_vectors_def by auto\n    thus \"v \\<in> module.span cpx_rng (module_cpx_vec n) (unit_vectors n)\"\n      using f6 module.span_def[of cpx_rng \"module_cpx_vec n\"] lc_def f1 f2 cpx_rng_def module_cpx_vec\n      by (smt Pi_I' UNIV_I mem_Collect_eq partial_object.select_convs(1))\n  qed\nqed\n    \nlemma unit_vectors_is_basis [simp]:\n  \"vectorspace.basis cpx_rng (module_cpx_vec n) (unit_vectors n)\"\nproof -\n  fix n\n  have \"unit_vectors n \\<subseteq> carrier (module_cpx_vec n)\"\n    using unit_vectors_def module_cpx_vec_def module_vec_simps(3) by fastforce\n  then show ?thesis\n    using vectorspace.basis_def unit_vectors_is_lin_indpt unit_vectors_is_genset vecspace_cpx_vec\n    by(smt carrier_dim_vec index_unit_vec(3) mem_Collect_eq module_cpx_vec_def module_vec_simps(3) \n        subsetI unit_vectors_def)\nqed\n\nlemma state_qbit_is_lincomb [simp]:\n  \"state_qbit n = \n  {module.lincomb (module_cpx_vec (2^n)) a A|a A. \n    finite A \\<and> A\\<subseteq>(unit_vectors (2^n)) \\<and> a\\<in> A \\<rightarrow> UNIV \\<and> \\<parallel>module.lincomb (module_cpx_vec (2^n)) a A\\<parallel> = 1}\"\nproof\n  show \"state_qbit n\n    \\<subseteq> {module.lincomb (module_cpx_vec (2^n)) a A |a A.\n        finite A \\<and> A \\<subseteq> unit_vectors (2^n) \\<and> a \\<in> A \\<rightarrow> UNIV \\<and> \\<parallel>module.lincomb (module_cpx_vec (2^n)) a A\\<parallel> = 1}\"\n  proof\n    fix v\n    assume a1:\"v \\<in> state_qbit n\"\n    then show \"v \\<in> {module.lincomb (module_cpx_vec (2^n)) a A |a A.\n               finite A \\<and> A \\<subseteq> unit_vectors (2^n) \\<and> a \\<in> A \\<rightarrow> UNIV \\<and> \\<parallel>module.lincomb (module_cpx_vec (2^n)) a A\\<parallel> = 1}\"\n    proof -\n      obtain a and A where \"finite A\" and \"a\\<in> A \\<rightarrow> UNIV\" and \"A \\<subseteq> unit_vectors (2^n)\" and \n        \"v = module.lincomb (module_cpx_vec (2^n)) a A\"\n        using a1 state_qbit_def unit_vectors_is_basis vectorspace.basis_def module.span_def \n        vecspace_cpx_vec module_cpx_vec module_cpx_vec_def module_vec_def carrier_vec_def\n        by(smt Pi_UNIV UNIV_I mem_Collect_eq module_vec_simps(3))\n      thus ?thesis\n        using a1 state_qbit_def by auto\n    qed\n  qed\n  show \"{module.lincomb (module_cpx_vec (2 ^ n)) a A |a A.\n     finite A \\<and> A \\<subseteq> unit_vectors (2 ^ n) \\<and> a \\<in> A \\<rightarrow> UNIV \\<and> \\<parallel>module.lincomb (module_cpx_vec (2 ^ n)) a A\\<parallel> = 1}\n    \\<subseteq> state_qbit n\"\n  proof\n    fix v\n    assume \"v \\<in> {module.lincomb (module_cpx_vec (2 ^ n)) a A |a A.\n              finite A \\<and> A \\<subseteq> unit_vectors (2 ^ n) \\<and> a \\<in> A \\<rightarrow> UNIV \\<and> \\<parallel>module.lincomb (module_cpx_vec (2 ^ n)) a A\\<parallel> = 1}\"\n    then show \"v \\<in> state_qbit n\"\n      using state_qbit_def dim_vec_lincomb unit_vectors_carrier_vec by(smt mem_Collect_eq order_trans)\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/Isabelle_Marries_Dirac/Complex_Vectors.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8577681013541613, "lm_q2_score": 0.8175744806385543, "lm_q1q2_score": 0.7012893099729473}}
{"text": "section \"Binomial Heaps\"\n\ntheory BinomialHeap\nimports Main \"HOL-Library.Multiset\" \"Eval_Base.Eval_Base\"\nbegin\n\nlocale BinomialHeapStruc_loc\nbegin\n\nsubsection \\<open>Datatype Definition\\<close>\n\ntext \\<open>Binomial heaps are lists of binomial trees.\\<close>\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 \\<open>Combine two binomial trees (of rank $r$) to one (of rank $r+1$).\\<close>\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 \\<open>Return a multiset with all (element, priority) pairs from a queue.\\<close>\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  apply2(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  apply2(induct q)\n  apply(simp)\n  apply(simp add: union_ac)\ndone\n\nsubsubsection \"Invariant\"\n\ntext \\<open>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\\<close>\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 \\<open>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\\<close>\n\ntext \\<open>First part: All trees of the queue satisfy the tree invariant:\\<close>\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 \\<open>Second part: Trees have distinct rank, and are ordered by \n  ascending rank:\\<close>\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 \\<open>Invariant for binomial queues:\\<close>\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\nproof2(induct r arbitrary: e a ts)\n  case 0\n  then show ?case by simp\nnext\n  case (Suc r)\n  from Suc(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 Suc(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 Suc(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)\"\napply2(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'\"\napply2(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)\"\napply2(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'])\" \nproof2 (induct bq)\n  case Nil\n  then show ?case by (simp add: invar_def)\nnext\n  case (Cons a bq)\n  from \\<open>invar (a # bq)\\<close> have \"invar bq\" by (rule invar_cons_down)\n  with Cons have \"invar (bq @ [t'])\" by simp\n  with Cons show ?case by (cases bq) (simp_all add: invar_def)\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_mset(queue_to_multiset ts). a \\<le> snd x)\"\n\ntext \\<open>The invariant for trees implies heap order.\\<close>\nlemma tree_invar_heap_ordered:\n  assumes \"tree_invar t\"\n  shows \"heap_ordered t\"\nproof (cases t)\n  case (Node e a nat list)\n  with assms show ?thesis\n  proof2 (induct nat arbitrary: t e a list)\n    case 0\n    then show ?case by simp\n  next\n    case (Suc nat t)\n    then 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 Suc(1)[OF O(1) t1] Suc(1)[OF O(2) t2]\n    show ?case by (cases \"a1 \\<le> a2\") auto\n  qed\nqed\n\nsubsubsection \"Height and Length\"\ntext \\<open>\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\\<close>\n\ntext \\<open>Height of a tree and queue\\<close>\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\n  done\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\"\nproof2 (induct r arbitrary: e a ts)\n  case 0\n  then show ?case by simp\nnext\n  case (Suc r)\n  from Suc(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    Suc(1)[OF inv1] Suc(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\"\nproof2 (induct r arbitrary: e a ts)\n  case 0\n  then show ?case by simp\nnext\n  case (Suc r)\n  from Suc(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 Suc(1)[OF inv1] Suc(1)[OF inv2] Suc(2) show ?case\n    by (cases \"a1 \\<le> a2\") simp_all\nqed\n\ntext \\<open>A binomial tree of height $h$ contains exactly $2^{h}$ elements\\<close>\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  by (cases t) (simp only: tree_rank_estimate BinomialTree.sel(3)) \n\n\nlemma invar_butlast: \"invar (bq @ [t]) \\<Longrightarrow> invar bq\"\n  unfolding invar_def\n  apply2 (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  apply2 (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))\"\nproof2 (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 [simp]: (Cons xxs xx)\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_sum_list: \n  \"size (queue_to_multiset bq) = sum_list (map (size \\<circ> tree_to_multiset) bq)\"\n  apply2 (induct bq) by simp_all\n\ntext \\<open>\n  A binomial heap of length $l$ contains at least $2^l - 1$ elements. \n\\<close>\ntheorem queue_length_estimate_lower: \n  \"invar bq \\<Longrightarrow> (size (queue_to_multiset bq)) \\<ge> 2^(length bq) - 1\"\nproof2 (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_sum_list)\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::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::nat) ^ length (xs @ [x]) = (2::nat) ^ (length xs) + (2::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 \\<open>Operations\\<close>\n\nsubsubsection \"Empty\"\nlemma empty_correct[simp]: \n  \"invar Nil\"\n  \"queue_to_multiset Nil = {#}\"\n  by (simp_all add: invar_def)\n  \ntext \\<open>The empty multiset is represented by exactly the empty queue\\<close>\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 \\<open>Inserts a binomial tree into a binomial queue, such that the queue \n  does not contain two trees of same rank.\\<close>\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 \\<open>Inserts an element with priority into the queue.\\<close>\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: \"queue_invar q \\<Longrightarrow>\n  queue_to_multiset (insert e a q) = queue_to_multiset q + {# (e,a) #}\"\nby(simp add: ins_mset union_ac insert_def)\n\nlemma ins_queue_invar: \"\\<lbrakk>tree_invar t; queue_invar q\\<rbrakk> \\<Longrightarrow> queue_invar (ins t q)\"\nproof2 (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 [simp]: True\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 \\<open>tree_invar t\\<close> 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'))\"\n  apply(auto)\n  apply2(induct bq arbitrary: t t')\n  apply(simp add: rank_link)\nproof goal_cases\n  case prems: (1 a bq t t')\n  thus ?case\n    apply(cases \"rank (link t' t) = rank a\")\n    apply(auto simp add: rank_link)\n  proof goal_cases\n    case 1\n    note * = this and \\<open>\\<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))\\<close>[of a \"(link t' t)\"] \n    show ?case\n    proof (cases \"rank (hd (ins (link (link t' t) a) bq)) = rank a\")\n      case True\n      with * show ?thesis by simp\n    next\n      case False\n      with * have \"rank a \\<le> rank (hd (ins (link (link t' t) a) bq))\" \n        by (simp add: rank_link)\n      with * show ?thesis 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> [])\"\n  apply2(induct bq arbitrary: t)\n  apply(auto)\nproof goal_cases\n  case prems: (1 a bq t)\n  hence r: \"rank (link t a) = rank a + 1\" by (simp add: rank_link)\n  from prems r and prems(1)[of \"(link t a)\"] show ?case by (cases bq) auto\nqed\n\nlemma rank_invar_ins: \"rank_invar bq \\<Longrightarrow> rank_invar (ins t bq)\"\n  apply2(induct bq arbitrary: t)\n  apply(simp)\n  apply(auto)\nproof goal_cases\n  case prems: (1 a bq t)\n  hence inv: \"rank_invar (ins t bq)\" by (cases bq) simp_all\n  from prems have hd: \"bq \\<noteq> [] \\<Longrightarrow> rank a < rank (hd bq)\"  \n    by (cases bq) auto\n  from prems 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 prems 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 prems and inv and hd show ?case by (auto simp add: rank_invar_hd_cons)\nnext\n  case prems: (2 a bq t)\n  hence inv: \"rank_invar bq\" by (cases bq) simp_all\n  with prems and prems(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 \\<open>Melds two queues.\\<close>\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')\"\nproof2 (induct q q' rule: meld.induct)\n  case 1\n  then show ?case by simp\nnext\n  case 2\n  then show ?case by simp\nnext\n  case (3 t1 bq1 t2 bq2)\n  consider (lt) \"rank t1 < rank t2\" | (gt) \"rank t1 > rank t2\" | (eq) \"rank t1 = rank t2\"\n    by atomize_elim auto\n  then show ?case\n  proof cases\n    case lt\n    from 3(4) have inv_bq1: \"queue_invar bq1\" by simp\n    from 3(4) have inv_t1: \"tree_invar t1\" by simp\n    from 3(1)[OF lt inv_bq1 3(5)] inv_t1 lt\n    show ?thesis by simp\n  next\n    case gt\n    from 3(5) have inv_bq2: \"queue_invar bq2\" by simp\n    from 3(5) have inv_t2: \"tree_invar t2\" by simp\n    from gt have \"\\<not> rank t1 < rank t2\" by simp\n    from 3(2)[OF this gt 3(4) inv_bq2] inv_t2 gt\n    show ?thesis by simp\n  next\n    case eq\n    from 3(4) have inv_bq1: \"queue_invar bq1\" by simp\n    from 3(4) have inv_t1: \"tree_invar t1\" by simp\n    from 3(5) have inv_bq2: \"queue_invar bq2\" by simp\n    from 3(5) have inv_t2: \"tree_invar t2\" by simp\n    note inv_link = link_tree_invar[OF inv_t1 inv_t2 eq]\n    from eq have *: \"\\<not> rank t1 < rank t2\" \"\\<not> rank t2 < rank t1\" by simp_all\n    note inv_meld = 3(3)[OF * inv_bq1 inv_bq2]\n    from ins_queue_invar[OF inv_link inv_meld] *\n    show ?thesis by simp\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))\"\n  apply2(induct bq arbitrary: t)\n  apply(auto)\nproof goal_cases\n  case prems: (1 a bq t)\n  hence inv: \"rank_invar bq\" by (cases bq) simp_all\n  from prems have r: \"rank (link t a) = rank a + 1\" by (simp add: rank_link)\n  with prems and inv and prems(1)[of \"(link t a)\"] show ?case by (cases bq) auto\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))\"\nproof2 (induct bq1 bq2 rule: meld.induct)\n  case 1\n  then show ?case by simp\nnext\n  case 2\n  then show ?case by simp\nnext\n  case (3 t1 bq1 t2 bq2)\n  from 3 have inv1: \"rank_invar bq1\" by (cases bq1) simp_all\n  from 3 have inv2: \"rank_invar bq2\" by (cases bq2) simp_all\n  \n  from inv1 and inv2 and 3 show ?case\n  proof (auto, goal_cases)\n    let ?t = \"t2\"\n    let ?bq = \"bq2\"\n    let ?meld = \"rank t2 < rank (hd (meld (t1 # bq1) bq2))\"\n    case prems: 1\n    hence \"?bq \\<noteq> [] \\<Longrightarrow> rank ?t < rank (hd ?bq)\" \n      by (simp add: rank_invar_not_empty_hd)\n    with prems have ne: \"?bq \\<noteq> [] \\<Longrightarrow> ?meld\" by simp\n    from prems have \"?bq = [] \\<Longrightarrow> ?meld\" by simp\n    with ne have \"?meld\" by (cases \"?bq = []\")\n    with prems show ?case by (simp add: rank_invar_hd_cons)\n  next \\<comment> \\<open>analog\\<close>\n    let ?t = \"t1\"\n    let ?bq = \"bq1\"\n    let ?meld = \"rank t1 < rank (hd (meld bq1 (t2 # bq2)))\"\n    case prems: 2\n    hence \"?bq \\<noteq> [] \\<Longrightarrow> rank ?t < rank (hd ?bq)\" \n      by (simp add: rank_invar_not_empty_hd)\n    with prems have ne: \"?bq \\<noteq> [] \\<Longrightarrow> ?meld\" by simp\n    from prems have \"?bq = [] \\<Longrightarrow> ?meld\" by simp\n    with ne have \"?meld\" by (cases \"?bq = []\")\n    with prems show ?case by (simp add: rank_invar_hd_cons)\n  next\n    case 3\n    thus ?case by (simp add: rank_invar_ins)\n  next\n    case prems: 4 (* Ab hier wirds h\u00e4sslich *)\n    then 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 prems\n    have mm: \"min (rank (hd bq1)) (rank (hd bq2)) \\<le> rank (hd (meld bq1 bq2))\"\n      by simp\n    from \\<open>rank_invar (t1 # bq1)\\<close> have \"bq1 \\<noteq> [] \\<Longrightarrow> rank t1 < rank (hd bq1)\" \n      by (simp add: rank_invar_not_empty_hd)\n    with prems have r1: \"bq1 \\<noteq> [] \\<Longrightarrow> rank t2 < rank (hd bq1)\" by simp\n    from \\<open>rank_invar (t2 # bq2)\\<close> \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 \\<open>rank_invar (meld bq1 bq2)\\<close> \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'\"\napply2(induct q q' rule: meld.induct)\n  by(auto simp add: link_tree_invar meld_queue_invar ins_mset union_ac)\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 \\<open>Finds the tree containing the minimal element.\\<close>\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)\"\nproof2 (induct bq)\n  case Nil\n  then show ?case by simp\nnext\n  case (Cons _ bq)\n  then show ?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  apply2 (induct bq) by (simp, cases t, auto) \n\nlemma heap_ordered_single: \n\"heap_ordered t = (\\<forall>x \\<in> set_mset (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  apply2 (induct xs rule: getMinTree.induct) by simp_all \n\nlemma getMinTree_min_tree:\n  \"t \\<in> set bq  \\<Longrightarrow> prio (getMinTree bq) \\<le> prio t\"\n  apply2(induct bq arbitrary: t rule: getMinTree.induct) \n  apply simp   \n  defer\n  apply simp\nproof goal_cases\n  case prems: (1 t v va ta)\n  thus ?case\n    apply (cases \"ta = t\")\n    apply auto[1] \n    apply (metis getMinTree_cons prems(1) prems(3) set_ConsD xt1(6))\n    done\nqed\n\nlemma getMinTree_min_prio:\n  assumes \"queue_invar bq\"\n    and \"y \\<in> set_mset (queue_to_multiset bq)\"\n  shows \"prio (getMinTree bq) \\<le> snd y\"\nproof -\n  from assms have \"bq \\<noteq> []\" by (cases bq) simp_all\n  with assms have \"\\<exists> t \\<in> set bq. (y \\<in> set_mset ((tree_to_multiset t)))\"\n  proof2 (induct bq)\n    case Nil\n    then show ?case by simp\n  next\n    case (Cons a bq)\n    thus ?case\n      apply(cases \"y \\<in> set_mset (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_mset (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 assms(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 ?thesis by simp\nqed\n\ntext \\<open>Finds the minimal Element in the queue.\\<close>\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_mset (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_mset (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 \\<open>Removes the first tree, which has the priority $a$ within his root.\\<close>\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 \\<open>Returns the queue without the minimal element.\\<close>\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 \\<subseteq># queue_to_multiset q\"\nproof2(induct q)\n  case Nil\n  then show ?case by simp\nnext\n  case (Cons a q)\n  show ?case\n  proof (cases \"t = a\")\n    case True\n    then show ?thesis by simp\n  next\n    case False\n    with Cons have t_in_q: \"t \\<in> set q\" by simp\n    have \"queue_to_multiset q \\<subseteq># queue_to_multiset (a # q)\"\n      by simp\n    from subset_mset.order_trans[OF Cons(1)[OF t_in_q] this] show ?thesis .\n  qed\nqed\n  \n\n\nlemma remove1Prio_remove1[simp]: \n  \"remove1Prio (prio (getMinTree bq)) bq = remove1 (getMinTree bq) bq\"\nproof2 (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      apply2 (induct bq rule: getMinTree.induct) by auto\n    from ne False have \"prio t \\<noteq> prio (getMinTree bq)\" \n      apply2 (induct bq rule: getMinTree.induct) by 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)\"\nproof (cases q)\n  case Nil\n  with assms show ?thesis by simp\nnext\n  case Cons\n  from NE and mintree_exists[of q] INV \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 INV, of \"getMinTree q\"]\n  from meld_queue_invar[OF inv_rev inv_rem] show ?thesis\n    by (simp add: deleteMin_def Let_def)\nqed\n\nlemma children_rank_less: \n  assumes \"tree_invar t\"\n  shows \"\\<forall>t' \\<in> set (children t). rank t' < rank t\"\nproof (cases t)\n  case (Node e a nat list)\n  with assms show ?thesis\n  proof2 (induct nat arbitrary: t e a list) \n    case 0\n    then show ?case by simp\n  next\n    case (Suc nat)\n    then obtain e1 a1 ts1 e2 a2 ts2 where \n      O: \"tree_invar (Node e1 a1 nat ts1)\" \"tree_invar (Node e2 a2 nat ts2)\"\n        \"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 Suc(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 Suc(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 Suc(3) p1 p2 ch_id show ?case by simp\n  qed\nqed\n\nlemma strong_rev_children:\n  assumes \"tree_invar t\"\n  shows \"invar (rev (children t))\"\n  unfolding invar_def\nproof (cases t)\n  case (Node e a nat list)\n  with assms show \"queue_invar (rev (children t)) \\<and> rank_invar (rev (children t))\"\n  proof2 (induct \"nat\" arbitrary: t e a list)\n    case 0\n    then show ?case by simp\n  next\n    case (Suc nat)\n    then obtain e1 a1 ts1 e2 a2 ts2 where \n      O: \"tree_invar (Node e1 a1 nat ts1)\" \"tree_invar (Node e2 a2 nat ts2)\"\n        \"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 Suc(1)[of \"Node e1 a1 nat ts1\" \"e1\" \"a1\" \"ts1\"]\n    have rev_ts1: \"invar (rev ts1)\" by (simp add: invar_def)\n    from O children_rank_less[of \"Node e1 a1 nat ts1\"]\n    have  \"\\<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 Suc(1)[of \"Node e2 a2 nat ts2\" \"e2\" \"a2\" \"ts2\"]\n    have rev_ts2: \"invar (rev ts2)\" by (simp add: invar_def)\n    from O children_rank_less[of \"Node e2 a2 nat ts2\"]\n    have \"\\<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  apply2(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)\" \nproof2 (induct bq arbitrary: t) \n  case Nil\n  then show ?case by simp\nnext\n  case (Cons a bq) \n  show ?case \n  proof (cases \"t=a\")\n    case True\n    from Cons(2) have \"invar bq\" by (rule invar_cons_down)\n    with True show ?thesis by simp\n  next\n    case False\n    from Cons(2) have \"invar bq\" by (rule invar_cons_down)\n    with Cons(1)[of \"t\"] have si1: \"invar (remove1 t bq)\" .\n    from False have \"invar (remove1 t (a # bq)) = invar (a # (remove1 t bq))\"\n      by simp\n    show ?thesis\n    proof (cases \"remove1 t bq\")\n      case Nil\n      with si1 Cons(2) False show ?thesis by (simp add: invar_def)\n    next\n      case Cons': (Cons aa list)\n      from Cons have \"tree_invar a\" by (simp add: invar_def)\n      from Cons first_less[of \"a\" \"bq\"] have \"\\<forall>t \\<in> set (remove1 t bq). rank a < rank t\"\n        by (metis notin_set_remove1 invar_def) \n      with Cons' have \"rank a < rank aa\" by simp\n      with si1 Cons(2) False Cons' invar_cons_up[of \"aa\" \"list\" \"a\"] show ?thesis\n        by (simp add: invar_def)\n    qed\n  qed\nqed  \n\ntheorem deleteMin_invar:\n  assumes \"invar bq\"\n    and \"bq \\<noteq> []\"\n  shows \"invar (deleteMin bq)\"\nproof -\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 assms 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\"]\n  have m1: \"invar (rev (children (getMinTree bq)))\" .\n  from strong_remove1[of \"bq\" \"getMinTree bq\"] assms(1)\n  have 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 \"invar (meld (rev (children (getMinTree bq))) (remove1 (getMinTree bq) bq))\" .\n  with eq show ?thesis ..\nqed\n\nlemma children_mset: \"queue_to_multiset (children t) = \n  tree_to_multiset t - {# (val t, prio t) #}\"\nproof (cases t)\n  case (Node e a nat list)\n  thus ?thesis apply2 (induct list) by simp_all\nqed\n\nlemma deleteMin_mset:\n  assumes \"queue_invar q\"\n    and \"q \\<noteq> Nil\"\n  shows \"queue_to_multiset (deleteMin q) = queue_to_multiset q - {# (findMin q) #}\"\nproof -\n  from assms mintree_exists[of \"q\"] have min_in_q: \"getMinTree q \\<in> set q\" by auto\n  with assms(1) have inv_min: \"tree_invar (getMinTree q)\" \n    by (simp add: queue_invar_def)\n  from assms(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 assms(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)) #} \\<subseteq># ?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_subset_eq_multiset_union_diff_commute[OF min_subset_q, of \"?MT\"]\n  show ?thesis 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 (overloaded) ('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 \\<open>\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 \\<open>'a\\<close>.\n\\<close>\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_mset (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 \\<open>Correctness lemmas to be used with simplifier\\<close>\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 \\<open>\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} \\<open>BinomialHeap.empty_correct\\<close>:\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} \\<open>BinomialHeap.isEmpty_correct\\<close>:\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} \\<open>BinomialHeap.insert_correct\\<close>:\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} \\<open>BinomialHeap.findMin_correct\\<close>:\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} \\<open>BinomialHeap.deleteMin_correct\\<close>:\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} \\<open>BinomialHeap.meld_correct\\<close>:\n    @{thm [display] BinomialHeap.meld_correct[no_vars]}\n\n\\<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/Evaluation/Binomial-Heaps/BinomialHeap.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681049901037, "lm_q2_score": 0.8175744761936437, "lm_q1q2_score": 0.7012893091328983}}
{"text": "theory le\nimports Main\n        \"../data/Natu\"\n        \"$HIPSTER_HOME/IsaHipster\"\n\nbegin\n\nfun le :: \"Nat => Nat => bool\" where\n  \"le Z     y      = True\"\n| \"le y Z      = False\"\n| \"le (S z) (S x2) = le z x2\"\n\n(*hipster le*)\n\nlemma lemma_a [thy_expl]: \"le x2 x2 = True\"\nby (hipster_induct_schemes le.simps)\n\nlemma lemma_aa [thy_expl]: \"le x2 (S x2) = True\"\nby (hipster_induct_schemes le.simps)\n\nlemma lemma_ab [thy_expl]: \"le (S x2) x2 = False\"\nby (hipster_induct_schemes le.simps)\n\n(*hipster_cond le*)\nlemma lemma_ac [thy_expl]: \"le x2 y2 \\<Longrightarrow> le x2 (S y2) = True\"\nby (hipster_induct_schemes le.simps)\n\nlemma lemma_ad [thy_expl]: \"le y2 x2 \\<Longrightarrow> le (S x2) y2 = False\"\nby (hipster_induct_schemes le.simps)\n\n(* false\nlemma unknown [thy_expl]: \"le y y \\<and> le x z \\<Longrightarrow> le x (S Z) = le x (S y)\"\noops *)\n\nlemma lemma_ae [thy_expl]: \"le y x \\<and> le x y \\<Longrightarrow> x = y\"\nby (hipster_induct_schemes le.simps Nat.exhaust)\n\nML \\<open>\nfun rprems_tac ctxt = Goal.norm_hhf_tac ctxt THEN' CSUBGOAL (fn (goal, i) =>\n      let\n        fun non_atomic (Const (\"==>\", _) $ _ $ _) = true\n          | non_atomic (Const (\"all\", _) $ _) = true\n          | non_atomic _ = false;\n\n        val ((_, goal'), ctxt') = Variable.focus_cterm goal ctxt;\n        val goal'' = Drule.cterm_rule \n          (singleton (Variable.export ctxt' ctxt)) goal';\n        val Rs = filter (non_atomic o Thm.term_of) \n          (Drule.strip_imp_prems goal'');\n        val _ = @{print} Rs\n        val _ = @{print} goal''\n\n        val ethms = Rs |> map (fn R =>\n          (Raw_Simplifier.norm_hhf ctxt' (Thm.trivial R)));\n      in eresolve_tac ethms i end\n  );\\<close>\n\nlemma le_trans [thy_expl]: \"le z y \\<and> le x z \\<Longrightarrow> le x y = True\"\nby (hipster_induct_schemes le.simps Nat.exhaust)\n(*\napply(induct x y arbitrary: z rule: le.induct) (* or: x, z *)\napply(simp_all)\napply(metis le.simps Nat.exhaust thy_expl)\napply(metis le.simps Nat.exhaust thy_expl)\n\nby (hipster_induct_schemes le.simps Nat.exhaust)*)\n(*\napply(induct x arbitrary: y rule: le.induct) (* or: x, z *)\napply(simp_all)\napply(metis le.simps  thy_expl)\nby(metis le.simps Nat.exhaust thy_expl)*)\n\n(* false\nlemma unknown [thy_expl]: \"le x z \\<and> le z z \\<Longrightarrow> le x (S y) = True\"\noops *)\n\nend\n\n", "meta": {"author": "moajohansson", "repo": "IsaHipster", "sha": "91f6ea3f1166a9de547722ece6445fe843ad89b4", "save_path": "github-repos/isabelle/moajohansson-IsaHipster", "path": "github-repos/isabelle/moajohansson-IsaHipster/IsaHipster-91f6ea3f1166a9de547722ece6445fe843ad89b4/benchmark/funcs/le.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680977182187, "lm_q2_score": 0.8175744806385542, "lm_q1q2_score": 0.7012893070002932}}
{"text": "(*  Title:      HOL/Library/Function_Algebras.thy\n    Author:     Jeremy Avigad and Kevin Donnelly; Florian Haftmann, TUM\n*)\n\nsection \\<open>Pointwise instantiation of functions to algebra type classes\\<close>\n\ntheory Function_Algebras\nimports Main\nbegin\n\ntext \\<open>Pointwise operations\\<close>\n\ninstantiation \"fun\" :: (type, plus) plus\nbegin\n\ndefinition \"f + g = (\\<lambda>x. f x + g x)\"\ninstance ..\n\nend\n\nlemma plus_fun_apply [simp]:\n  \"(f + g) x = f x + g x\"\n  by (simp add: plus_fun_def)\n\ninstantiation \"fun\" :: (type, zero) zero\nbegin\n\ndefinition \"0 = (\\<lambda>x. 0)\"\ninstance ..\n\nend\n\nlemma zero_fun_apply [simp]:\n  \"0 x = 0\"\n  by (simp add: zero_fun_def)\n\ninstantiation \"fun\" :: (type, times) times\nbegin\n\ndefinition \"f * g = (\\<lambda>x. f x * g x)\"\ninstance ..\n\nend\n\nlemma times_fun_apply [simp]:\n  \"(f * g) x = f x * g x\"\n  by (simp add: times_fun_def)\n\ninstantiation \"fun\" :: (type, one) one\nbegin\n\ndefinition \"1 = (\\<lambda>x. 1)\"\ninstance ..\n\nend\n\nlemma one_fun_apply [simp]:\n  \"1 x = 1\"\n  by (simp add: one_fun_def)\n\n\ntext \\<open>Additive structures\\<close>\n\ninstance \"fun\" :: (type, semigroup_add) semigroup_add\n  by standard (simp add: fun_eq_iff add.assoc)\n\ninstance \"fun\" :: (type, cancel_semigroup_add) cancel_semigroup_add\n  by standard (simp_all add: fun_eq_iff)\n\ninstance \"fun\" :: (type, ab_semigroup_add) ab_semigroup_add\n  by standard (simp add: fun_eq_iff add.commute)\n\ninstance \"fun\" :: (type, cancel_ab_semigroup_add) cancel_ab_semigroup_add\n  by standard (simp_all add: fun_eq_iff diff_diff_eq)\n\ninstance \"fun\" :: (type, monoid_add) monoid_add\n  by standard (simp_all add: fun_eq_iff)\n\ninstance \"fun\" :: (type, comm_monoid_add) comm_monoid_add\n  by standard simp\n\ninstance \"fun\" :: (type, cancel_comm_monoid_add) cancel_comm_monoid_add ..\n\ninstance \"fun\" :: (type, group_add) group_add\n  by standard (simp_all add: fun_eq_iff)\n\ninstance \"fun\" :: (type, ab_group_add) ab_group_add\n  by standard simp_all\n\n\ntext \\<open>Multiplicative structures\\<close>\n\ninstance \"fun\" :: (type, semigroup_mult) semigroup_mult\n  by standard (simp add: fun_eq_iff mult.assoc)\n\ninstance \"fun\" :: (type, ab_semigroup_mult) ab_semigroup_mult\n  by standard (simp add: fun_eq_iff mult.commute)\n\ninstance \"fun\" :: (type, monoid_mult) monoid_mult\n  by standard (simp_all add: fun_eq_iff)\n\ninstance \"fun\" :: (type, comm_monoid_mult) comm_monoid_mult\n  by standard simp\n\n\ntext \\<open>Misc\\<close>\n\ninstance \"fun\" :: (type, \"Rings.dvd\") \"Rings.dvd\" ..\n\ninstance \"fun\" :: (type, mult_zero) mult_zero\n  by standard (simp_all add: fun_eq_iff)\n\ninstance \"fun\" :: (type, zero_neq_one) zero_neq_one\n  by standard (simp add: fun_eq_iff)\n\n\ntext \\<open>Ring structures\\<close>\n\ninstance \"fun\" :: (type, semiring) semiring\n  by standard (simp_all add: fun_eq_iff algebra_simps)\n\ninstance \"fun\" :: (type, comm_semiring) comm_semiring\n  by standard (simp add: fun_eq_iff  algebra_simps)\n\ninstance \"fun\" :: (type, semiring_0) semiring_0 ..\n\ninstance \"fun\" :: (type, comm_semiring_0) comm_semiring_0 ..\n\ninstance \"fun\" :: (type, semiring_0_cancel) semiring_0_cancel ..\n\ninstance \"fun\" :: (type, comm_semiring_0_cancel) comm_semiring_0_cancel ..\n\ninstance \"fun\" :: (type, semiring_1) semiring_1 ..\n\nlemma numeral_fun: \\<^marker>\\<open>contributor \\<open>Akihisa Yamada\\<close>\\<close>\n  \\<open>numeral n = (\\<lambda>x::'a. numeral n)\\<close>\n  by (induction n) (simp_all only: numeral.simps plus_fun_def, simp_all)\n\nlemma numeral_fun_apply [simp]: \\<^marker>\\<open>contributor \\<open>Akihisa Yamada\\<close>\\<close>\n  \\<open>numeral n x = numeral n\\<close>\n  by (simp add: numeral_fun)\n\nlemma of_nat_fun: \"of_nat n = (\\<lambda>x::'a. of_nat n)\"\nproof -\n  have comp: \"comp = (\\<lambda>f g x. f (g x))\"\n    by (rule ext)+ simp\n  have plus_fun: \"plus = (\\<lambda>f g x. f x + g x)\"\n    by (rule ext, rule ext) (fact plus_fun_def)\n  have \"of_nat n = (comp (plus (1::'b)) ^^ n) (\\<lambda>x::'a. 0)\"\n    by (simp add: of_nat_def plus_fun zero_fun_def one_fun_def comp)\n  also have \"... = comp ((plus 1) ^^ n) (\\<lambda>x::'a. 0)\"\n    by (simp only: comp_funpow)\n  finally show ?thesis by (simp add: of_nat_def comp)\nqed\n\nlemma of_nat_fun_apply [simp]:\n  \"of_nat n x = of_nat n\"\n  by (simp add: of_nat_fun)\n\ninstance \"fun\" :: (type, comm_semiring_1) comm_semiring_1 ..\n\ninstance \"fun\" :: (type, semiring_1_cancel) semiring_1_cancel ..\n\ninstance \"fun\" :: (type, comm_semiring_1_cancel) comm_semiring_1_cancel\n  by standard (auto simp add: times_fun_def algebra_simps)\n\ninstance \"fun\" :: (type, semiring_char_0) semiring_char_0\nproof\n  from inj_of_nat have \"inj (\\<lambda>n (x::'a). of_nat n :: 'b)\"\n    by (rule inj_fun)\n  then have \"inj (\\<lambda>n. of_nat n :: 'a \\<Rightarrow> 'b)\"\n    by (simp add: of_nat_fun)\n  then show \"inj (of_nat :: nat \\<Rightarrow> 'a \\<Rightarrow> 'b)\" .\nqed\n\ninstance \"fun\" :: (type, ring) ring ..\n\ninstance \"fun\" :: (type, comm_ring) comm_ring ..\n\ninstance \"fun\" :: (type, ring_1) ring_1 ..\n\ninstance \"fun\" :: (type, comm_ring_1) comm_ring_1 ..\n\ninstance \"fun\" :: (type, ring_char_0) ring_char_0 ..\n\n\ntext \\<open>Ordered structures\\<close>\n\ninstance \"fun\" :: (type, ordered_ab_semigroup_add) ordered_ab_semigroup_add\n  by standard (auto simp add: le_fun_def intro: add_left_mono)\n\ninstance \"fun\" :: (type, ordered_cancel_ab_semigroup_add) ordered_cancel_ab_semigroup_add ..\n\ninstance \"fun\" :: (type, ordered_ab_semigroup_add_imp_le) ordered_ab_semigroup_add_imp_le\n  by standard (simp add: le_fun_def)\n\ninstance \"fun\" :: (type, ordered_comm_monoid_add) ordered_comm_monoid_add ..\n\ninstance \"fun\" :: (type, ordered_cancel_comm_monoid_add) ordered_cancel_comm_monoid_add ..\n\ninstance \"fun\" :: (type, ordered_ab_group_add) ordered_ab_group_add ..\n\ninstance \"fun\" :: (type, ordered_semiring) ordered_semiring\n  by standard (auto simp add: le_fun_def intro: mult_left_mono mult_right_mono)\n\ninstance \"fun\" :: (type, dioid) dioid\nproof standard\n  fix a b :: \"'a \\<Rightarrow> 'b\"\n  show \"a \\<le> b \\<longleftrightarrow> (\\<exists>c. b = a + c)\"\n    unfolding le_fun_def plus_fun_def fun_eq_iff choice_iff[symmetric, of \"\\<lambda>x c. b x = a x + c\"]\n    by (intro arg_cong[where f=All] ext canonically_ordered_monoid_add_class.le_iff_add)\nqed\n\ninstance \"fun\" :: (type, ordered_comm_semiring) ordered_comm_semiring\n  by standard (fact mult_left_mono)\n\ninstance \"fun\" :: (type, ordered_cancel_semiring) ordered_cancel_semiring ..\n\ninstance \"fun\" :: (type, ordered_cancel_comm_semiring) ordered_cancel_comm_semiring ..\n\ninstance \"fun\" :: (type, ordered_ring) ordered_ring ..\n\ninstance \"fun\" :: (type, ordered_comm_ring) ordered_comm_ring ..\n\n\nlemmas func_plus = plus_fun_def\nlemmas func_zero = zero_fun_def\nlemmas func_times = times_fun_def\nlemmas func_one = one_fun_def\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/Library/Function_Algebras.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8577680904463333, "lm_q2_score": 0.8175744850834648, "lm_q1q2_score": 0.7012893048676878}}
{"text": "(*  Gauss-Jordan elimination for matrices represented as functions\n    Author: Tobias Nipkow\n*)\nheader {* Gauss-Jordan elimination algorithm *}\ntheory Gauss_Jordan_Elim_Fun\nimports Main\nbegin\n\ntext{* Matrices are functions: *}\n\ntype_synonym 'a matrix = \"nat \\<Rightarrow> nat \\<Rightarrow> 'a\"\n\ntext{* 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 @{text\nn}. It indicates that the matrix @{text A} has @{text n} rows and columns.\nIn fact, @{text A} is the augmented matrix with @{text \"n+1\"} columns. Column\n@{text n} is the ``right-hand side'', i.e.\\ the constant vector @{text\nb}. The result is the unit matrix augmented with the solution in column\n@{text n}; see the correctness theorem below. *}\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{* Some auxiliary functions: *}\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 `?L` 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 `?L` assms False show ?thesis\n           by(fastforce simp add: solution_def Fun.swap_def)\n       next\n         assume \"i\\<noteq>p2\"\n         with `i\\<noteq>p1` `?L` `i<n` 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: setsum_divide_distrib[symmetric] eq_divide_eq field_simps)\n apply simp\napply (simp add: setsum_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 setsum_subtractf setsum_right_distrib[symmetric])\napply(clarsimp)\napply(case_tac \"i=p\")\n apply simp\napply (auto simp add: field_simps setsum_subtractf setsum_right_distrib[symmetric] all_conj_distrib)\ndone\n\nsubsection{* Correctness *}\n\ntext{* The correctness proof: *}\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 setsum.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 `gauss_jordan A (Suc m) = Some B`\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 `Suc m \\<le> n` 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 `m\\<le>n` this rec] `m<n` 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 `i<m`] 2\n      have \"(\\<Sum>j = 0..<m. A i j * y j) = A i n\"\n        by (auto intro!: setsum.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 `q < m`\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: setsum_right_distrib field_simps)\n\n\n\nsubsection{* Complete *}\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 `Suc m \\<le> n` have \"m\\<le>n\" and \"m<Suc m\" by arith+\n  from non_null_if_pivot[OF Suc.prems(2) `m<Suc m`]\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: dropWhile_eq_Nil_conv)\n       (metis atLeast0LessThan 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 setsum_subtractf setsum_divide_distrib\n                    setsum_right_distrib)\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: setsum_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 `i \\<noteq> p` 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 setsum_subtractf lem1 lem2 setsum_divide_distrib[symmetric]\n                     split: if_splits)\n          with `A p m \\<noteq> 0` show ?thesis unfolding `i = m`\n            by simp (simp add: field_simps)\n        next\n          assume \"i \\<noteq> m\"\n          then have \"i < m\" using `i < Suc m` 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 field_simps setsum_subtractf lem1 lem2 setsum_divide_distrib[symmetric]\n                     split: if_splits)\n          with `A p m \\<noteq> 0` show ?thesis\n            by simp (simp add: field_simps)\n        qed\n      qed\n    qed\n    with `usolution A (Suc m) n x`\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 `m\\<le>n` this] 1 show ?case by(simp)\nqed\n\ntext{* Future work: extend the proof to matrix inversion. *}\n\nhide_const (open) unit\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-Elim-Fun/Gauss_Jordan_Elim_Fun.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680904463333, "lm_q2_score": 0.817574478416099, "lm_q1q2_score": 0.7012892991486341}}
{"text": "(*  \n    Title:      Least_Squares_Approximation.thy\n    Author:     Jose Divas\u00f3n <jose.divasonm at unirioja.es>\n    Author:     Jes\u00fas Aransay <jesus-maria.aransay at unirioja.es>\n*)\n\nsection\\<open>Least Squares Approximation\\<close>\n\ntheory Least_Squares_Approximation\nimports\n QR_Decomposition\nbegin\n\nsubsection\\<open>Second part of the Fundamental Theorem of Linear Algebra\\<close>\n\ntext\\<open>See @{url \"http://en.wikipedia.org/wiki/Fundamental_theorem_of_linear_algebra\"}\\<close>\n\nlemma null_space_orthogonal_complement_row_space:\n  fixes A::\"real^'cols^'rows::{finite,wellorder}\"\n  shows \"null_space A = orthogonal_complement (row_space A)\"\nproof (unfold null_space_def orthogonal_complement_def, auto)\n  fix x xa assume Ax: \"A *v x = 0\" and xa: \"xa \\<in> row_space A\"\n  obtain y where y: \"xa = transpose A *v y\" using xa unfolding row_space_eq by blast\n  have \"y v* A = xa\"\n    using transpose_vector y by fastforce\n  thus \"orthogonal x xa\" unfolding orthogonal_def\n    using Ax dot_lmul_matrix inner_commute inner_zero_right\n    by (metis Ax dot_lmul_matrix inner_commute inner_zero_right)\nnext\n  fix x assume xa: \"\\<forall>xa\\<in>row_space A. orthogonal x xa\"\n  show \"A *v x = 0\"\n    using xa unfolding row_space_eq orthogonal_def\n    by (auto, metis transpose_transpose dot_lmul_matrix inner_eq_zero_iff transpose_vector)\nqed\n\nlemma left_null_space_orthogonal_complement_col_space:\n  fixes A::\"real^'cols::{finite,wellorder}^'rows\"\n  shows \"left_null_space A = orthogonal_complement (col_space A)\"\n  using null_space_orthogonal_complement_row_space[of \"transpose A\"]\n  unfolding left_null_space_eq_null_space_transpose\n  unfolding col_space_eq_row_space_transpose .\n\n\nsubsection\\<open>Least Squares Approximation\\<close>\n\ntext\\<open>See @{url \"https://people.math.osu.edu/husen.1/teaching/571/least_squares.pdf\"}\\<close>\n\ntext\\<open>Part 3 of the Theorem 1.7 in the previous website.\\<close>\n\nlemma least_squares_approximation:\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  and not_eq: \"proj_onto v X \\<noteq> y\"\n  and y: \"y \\<in> S\"\n  shows \"norm (v - proj_onto v X) < norm (v - y)\"\nproof -\n  have S_eq_spanX: \"S = span X\"\n    using X span_X span_subspace subspace_S by auto\n  let ?p=\"proj_onto v X\"\n  have not_0: \"(norm(?p - y))^2 \\<noteq> 0\"\n    by (metis (lifting) eq_iff_diff_eq_0 norm_eq_zero not_eq power_eq_0_iff)\n  have \"norm (v-y)^2 = norm (v - ?p + ?p - y)^2\" by auto\n  also have \"... = norm ((v - ?p) + (?p - y))^2\" \n    unfolding add.assoc[symmetric] by simp\n  also have \"... = (norm (v - ?p))^2 + (norm(?p - y))^2\"\n  proof (rule phytagorean_theorem_norm, rule in_orthogonal_complement_imp_orthogonal) \n    show \"?p - y \\<in> S\" unfolding proj_onto_def proj_def[abs_def]\n    proof (rule subspace_diff[OF subspace_S _ y],\n        rule subspace_sum[OF subspace_S])\n      show \"x \\<in> X \\<Longrightarrow> (v \\<bullet> x / (x \\<bullet> x)) *\\<^sub>R x \\<in> S\" for x\n        by (metis S_eq_spanX X rev_subsetD span_mul)\n    qed\n    show \"v - ?p \\<in> orthogonal_complement S\"\n      using v_minus_p_orthogonal_complement assms by auto        \n  qed\n  finally have \"norm (v-?p)^2 < norm (v-y)^2\" using not_0 by fastforce\n  thus ?thesis by (metis (full_types) norm_gt_square power2_norm_eq_inner)\nqed\n\n\nlemma least_squares_approximation2:\n  fixes S::\"'a::{euclidean_space} set\"\n  assumes subspace_S: \"subspace S\"\n  and y: \"y \\<in> S\"\n  shows \"\\<exists>p\\<in>S. norm (v - p) \\<le> norm (v - y) \\<and> (v-p) \\<in> orthogonal_complement S\"\nproof -\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 subspace_S)\n  let ?p=\"proj_onto v X\"\n  show ?thesis \n  proof (rule bexI[of _ ?p], rule conjI)\n    show \"norm (v - proj_onto v X) \\<le> norm (v - y)\"\n    proof (cases \"?p=y\")\n      case True thus \"norm (v - ?p) \\<le> norm (v - y)\" by simp\n    next\n      case False\n      have \"norm (v - ?p) < norm (v - y)\" \n        by (rule least_squares_approximation[OF subspace_S ind_X X span_X o False y])\n      thus \"norm (v - ?p) \\<le> norm (v - y)\" by simp\n    qed\n    show \"?p \\<in> S\"\n      using [[unfold_abs_def = false]]\n    proof (unfold proj_onto_def proj_def, rule subspace_sum)\n      show \"subspace S\" using subspace_S .\n      show \"x\\<in>X \\<Longrightarrow> proj v x \\<in> S\" for x\n        by (simp add: proj_def X rev_subsetD subspace_S subspace_mul)\n    qed\n    show \"v - ?p\\<in> orthogonal_complement S\"\n      by (rule v_minus_p_orthogonal_complement[OF subspace_S ind_X X span_X o])\n  qed\nqed\n\ncorollary least_squares_approximation3:\n  fixes S::\"'a::{euclidean_space} set\"\n  assumes subspace_S: \"subspace S\"\n  shows \"\\<exists>p\\<in>S. \\<forall>y\\<in>S. norm (v - p) \\<le> norm (v - y) \\<and> (v-p) \\<in> orthogonal_complement S\"\nproof -\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 subspace_S)\n  let ?p=\"proj_onto v X\"\n  show ?thesis\n  proof (rule bexI[of _ ?p], auto)\n    fix y assume y: \"y\\<in>S\"\n    show \"norm (v - ?p) \\<le> norm (v - y)\"\n    proof (cases \"?p=y\")\n      case True thus ?thesis by simp\n    next\n      case False\n      have \"norm (v - ?p) < norm (v - y)\"\n        by (rule least_squares_approximation[OF subspace_S ind_X X span_X o False y])\n      thus ?thesis by simp\n    qed\n    show \"v - ?p \\<in> orthogonal_complement S\"\n      by (rule v_minus_p_orthogonal_complement[OF subspace_S ind_X X span_X o])\n  next\n    show \"?p \\<in> S\" \n    proof (unfold proj_onto_def, rule subspace_sum)\n      show \"subspace S\" using subspace_S .\n      show \"x \\<in> X \\<Longrightarrow> proj v x \\<in> S\" for x\n        by (metis Projections.proj_def X subset_iff subspace_S subspace_mul)\n    qed\n  qed\nqed\n\nlemma norm_least_squares:\n  fixes A::\"real^'cols::{finite,wellorder}^'rows\"\n  shows \"\\<exists>x. \\<forall>x'. norm (b - A *v x) \\<le> norm (b - A *v x')\"\nproof -\n  have \"\\<exists>p\\<in>col_space A. \\<forall>y\\<in>col_space A. norm (b - p) \\<le> norm (b - y) \\<and> (b-p) \\<in> orthogonal_complement (col_space A)\"\n    using least_squares_approximation3[OF subspace_col_space[of A, unfolded subspace_vec_eq]] .\n  from this obtain p where p: \"p \\<in> col_space A\" and least: \"\\<forall>y\\<in>col_space A. norm (b - p) \\<le> norm (b - y)\"\n    and bp_orthogonal: \"(b-p) \\<in> orthogonal_complement (col_space A)\"\n    by blast\n  obtain x where x: \"p = A *v x\" using p unfolding col_space_eq by blast\n  show ?thesis \n  proof (rule exI[of _ x], auto)\n    fix x'\n    have \"A *v x' \\<in> col_space A\" unfolding col_space_eq by auto\n    thus \"norm (b - A *v x) \\<le> norm (b - A *v x')\" using least unfolding x by auto\n  qed\nqed\n\ndefinition \"set_least_squares_approximation A b = {x. \\<forall>y. norm (b - A *v x) \\<le> norm (b - A *v y)}\"\n\ncorollary least_squares_approximation4:\n  fixes S::\"'a::{euclidean_space} set\"\n  assumes subspace_S: \"subspace S\"\n  shows \"\\<exists>!p\\<in>S. \\<forall>y\\<in>S-{p}. norm (v - p) < norm (v - y)\"\nproof (auto)\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 subspace_S)\n  let ?p=\"sum (proj v) X\"\n  show \"\\<exists>p. p \\<in> S \\<and> (\\<forall>y\\<in>S - {p}. norm (v - p) < norm (v - y))\"\n  proof (rule exI[of _ ?p], rule conjI,  rule subspace_sum)\n    show \"subspace S\" using subspace_S .\n    show \"x \\<in> X \\<Longrightarrow> proj v x \\<in> S\" for x\n      by (metis Projections.proj_def X subset_iff subspace_S subspace_mul)\n    show \"\\<forall>y\\<in>S - {?p}. norm (v - ?p) < norm (v - y)\" \n      using X ind_X least_squares_approximation  o span_X subspace_S proj_onto_def\n      by (metis (mono_tags) Diff_iff singletonI)\n  qed\n  fix p y\n  assume p: \"p \\<in> S\"\n    and \"\\<forall>y\\<in>S - {p}. norm (v - p) < norm (v - y)\"\n    and \"y \\<in> S\"\n    and \"\\<forall>ya\\<in>S - {y}. norm (v - y) < norm (v - ya)\"\n  thus \"p = y\" by (metis member_remove not_less_iff_gr_or_eq remove_def)\nqed\n\n\ncorollary least_squares_approximation4':\n  fixes S::\"'a::{euclidean_space} set\"\n  assumes subspace_S: \"subspace S\"\n  shows \"\\<exists>!p\\<in>S. \\<forall>y\\<in>S. norm (v - p) \\<le> norm (v - y)\"\nproof (auto)\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 subspace_S)\n  let ?p=\"sum (proj v) X\"\n  show \"\\<exists>p. p \\<in> S \\<and> (\\<forall>y\\<in>S. norm (v - p) \\<le> norm (v - y))\"\n  proof (rule exI[of _ ?p], rule conjI, rule subspace_sum)\n    show \"subspace S\" using subspace_S .\n    show \"x \\<in> X \\<Longrightarrow> proj v x \\<in> S\" for x\n      by (metis Projections.proj_def X subset_iff subspace_S subspace_mul)\n    show \"\\<forall>y\\<in>S. norm (v - ?p) \\<le> norm (v - y)\"\n      by (metis (mono_tags) proj_onto_def X dual_order.refl ind_X \n         least_squares_approximation less_imp_le o span_X subspace_S)\n  qed\n  fix p y\n  assume p: \"p \\<in> S\" and p': \"\\<forall>y\\<in>S. norm (v - p) \\<le> norm (v - y)\"\n    and y: \"y \\<in> S\" and y': \"\\<forall>ya\\<in>S. norm (v - y) \\<le> norm (v - ya)\"\n  obtain a where a: \"a\\<in>S\" and a': \"\\<forall>y\\<in>S-{a}. norm (v - a) < norm (v - y)\"\n    and a_uniq: \"\\<forall>b. (b\\<in>S \\<and> (\\<forall>c\\<in>S-{b}. norm (v - b) < norm (v - c))) \\<longrightarrow> b=a\"\n    using least_squares_approximation4[OF subspace_S]\n    by metis\n  have \"p=a\" using p p' a_uniq leD  by (metis a a' member_remove remove_def)\n  moreover have \"y=a\" using y y' a_uniq\n    by (metis a a' leD member_remove remove_def)\n  ultimately show \"p = y\" by simp\nqed\n\ncorollary least_squares_approximation5:\n  fixes S::\"'a::{euclidean_space} set\"\n  assumes subspace_S: \"subspace S\"\n  shows \"\\<exists>!p\\<in>S. \\<forall>y\\<in>S-{p}. norm (v - p) < norm (v - y) \\<and> v-p \\<in> orthogonal_complement S\"\nproof (auto)\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 subspace_S)\n  let ?p=\"sum (proj v) X\"\n  show \"\\<exists>p. p \\<in> S \\<and> (\\<forall>y\\<in>S - {p}. norm (v - p) < norm (v - y) \\<and> v - p \\<in> orthogonal_complement S)\"\n  proof (rule exI[of _ ?p], rule conjI, rule subspace_sum)\n    show \"subspace S\" using subspace_S .\n    show \"x \\<in> X \\<Longrightarrow> proj v x \\<in> S\" for x\n      by (simp add: Projections.proj_def X rev_subsetD subspace_S subspace_mul)\n    have \"\\<forall>y\\<in>S - {?p}. norm (v - ?p) < norm (v - y)\" \n      using least_squares_approximation[OF subspace_S ind_X X span_X o]\n      unfolding proj_onto_def\n      by (metis (no_types) member_remove remove_def)\n    moreover have \"v - ?p \\<in> orthogonal_complement S\" \n      by (metis (no_types) X ind_X o span_X subspace_S v_minus_p_orthogonal_complement proj_onto_def)\n    ultimately show \"\\<forall>y\\<in>S - {?p}. norm (v - ?p) < norm (v - y) \\<and> v - ?p \\<in> orthogonal_complement S\"\n      by auto\n  qed\n  fix p y\n  assume p: \"p \\<in> S\" and p': \"\\<forall>y\\<in>S - {p}. norm (v - p) < norm (v - y) \\<and> v - p \\<in> orthogonal_complement S\"\n    and y: \"y \\<in> S\" and y': \"\\<forall>ya\\<in>S - {y}. norm (v - y) < norm (v - ya) \\<and> v - y \\<in> orthogonal_complement S\"\n  show \"p=y\"\n    by (metis least_squares_approximation4 p p' subspace_S y y')\nqed\n\ncorollary least_squares_approximation5':\n  fixes S::\"'a::{euclidean_space} set\"\n  assumes subspace_S: \"subspace S\"\n  shows \"\\<exists>!p\\<in>S. \\<forall>y\\<in>S. norm (v - p) \\<le> norm (v - y) \\<and> v-p \\<in> orthogonal_complement S\"\n  by (metis least_squares_approximation3 least_squares_approximation4' subspace_S)\n\ncorollary least_squares_approximation6:\n  fixes S::\"'a::{euclidean_space} set\"\n  assumes subspace_S: \"subspace S\"\n  and \"p\\<in>S\"\n  and \"\\<forall>y\\<in>S. norm (v - p) \\<le> norm (v - y)\"\n  shows \"v-p \\<in> orthogonal_complement S\"\nproof -\n  obtain a where a: \"a\\<in>S\" and a': \"\\<forall>y\\<in>S. norm (v - a) \\<le> norm (v - y) \\<and> v-a \\<in> orthogonal_complement S\"\n    and \"\\<forall>b. (b\\<in>S \\<and> (\\<forall>y\\<in>S. norm (v - b) \\<le> norm (v - y) \\<and> v-b \\<in> orthogonal_complement S)) \\<longrightarrow> b=a\"\n    using least_squares_approximation5'[OF subspace_S] by metis\n  have \"p=a\"\n    by (metis a a' assms(2) assms(3) least_squares_approximation4' subspace_S)\n  thus ?thesis using a' by (metis assms(2))\nqed\n\n\ncorollary least_squares_approximation7:\n  fixes S::\"'a::{euclidean_space} set\"\n  assumes subspace_S: \"subspace S\"\n  and \"v - p \\<in> orthogonal_complement S\"\n  and \"p\\<in>S\"\n  and \"y \\<in> S\"\n  shows \"norm (v - p) \\<le> norm (v - y)\" \nproof (cases \"y=p\")\n  case True thus ?thesis by simp\nnext\n  case False\n  have \"norm (v - y)^2 = norm ((v - p) + (p - y))^2\"\n    by (metis (hide_lams, no_types) add_diff_cancel_left add_ac(1) add_diff_add add_diff_cancel)\n  also have \"... = norm (v - p)^2 + norm (p - y)^2\" \n  proof (rule phytagorean_theorem_norm, rule in_orthogonal_complement_imp_orthogonal)\n    show \"p - y \\<in> S\" by (metis assms(3) assms(4) subspace_S subspace_diff)\n    show \"v - p \\<in> orthogonal_complement S\" by (metis assms(2)) \n  qed\n  finally have \"norm (v - p)^2 \\<le> norm (v - y)^2\" by auto\n  thus \"norm (v - p)\\<le> norm (v - y)\" by (metis norm_ge_zero power2_le_imp_le)\nqed\n\n\nlemma in_set_least_squares_approximation:\n  fixes A::\"real^'cols::{finite, wellorder}^'rows\"\n  assumes o: \"A *v x - b \\<in> orthogonal_complement (col_space A)\"\n  shows \"(x \\<in> set_least_squares_approximation A b)\"\nproof (unfold set_least_squares_approximation_def, auto)\n  fix y \n  show \" norm (b - A *v x) \\<le> norm (b - A *v y)\"\n  proof (rule least_squares_approximation7)\n    show \"subspace (col_space A)\" using subspace_col_space[of A, unfolded subspace_vec_eq] .\n    show \"b - A *v x \\<in> orthogonal_complement (col_space A)\"\n      using o subspace_orthogonal_complement[of \"(col_space A)\"]\n      using minus_diff_eq subspace_neg by metis\n    show \"A *v x \\<in> col_space A\" unfolding col_space_eq[of A] by auto\n    show \"A *v y \\<in> col_space A\" unfolding col_space_eq by auto\n  qed\nqed\n\n\n\n\nlemma in_set_least_squares_approximation_eq_full_rank:\n  fixes A::\"real^'cols::mod_type^'rows::mod_type\"\n  assumes r: \"rank A = ncols A\"\n  shows \"(x \\<in> set_least_squares_approximation A b) = (x = matrix_inv (transpose A ** A)**transpose A *v b)\"\nproof -\n  have int_tA: \"invertible (transpose A ** A)\" using invertible_transpose_mult[OF r] .\n  show ?thesis\n  proof \n    fix x assume \"x \\<in> set_least_squares_approximation A b\"\n    hence \"transpose A ** A *v x = transpose A *v b\" using in_set_least_squares_approximation_eq by auto\n    thus \"x = matrix_inv (transpose A ** A) ** transpose A *v b\"\n      by (metis int_tA matrix_inv_left matrix_vector_mul_assoc matrix_vector_mul_lid)\n  next\n    fix x assume \"x = matrix_inv (transpose A ** A) ** transpose A *v b\"\n    hence \"transpose A ** A *v x = transpose A *v b\"\n      by (metis int_tA matrix_inv_right matrix_vector_mul_assoc matrix_vector_mul_lid)\n    thus \"x \\<in> set_least_squares_approximation A b\" unfolding in_set_least_squares_approximation_eq .\n  qed\nqed\n\n\n\nlemma in_set_least_squares_approximation_eq_full_rank_QR:\n  fixes A::\"real^'cols::{mod_type}^'rows::{mod_type}\"\n  assumes r: \"rank A = ncols A\"\n  shows \"(x \\<in> set_least_squares_approximation A b) = ((snd (QR_decomposition A)) *v x = transpose (fst (QR_decomposition A)) *v b)\"\nproof -\n  let ?Q = \"fst (QR_decomposition A)\"\n  let ?R = \"snd (QR_decomposition A)\"\n  have inv_tR: \"invertible (transpose ?R)\"\n    by (metis invertible_snd_QR_decomposition invertible_transpose r)\n  have inv_inv_tR: \"invertible (matrix_inv (transpose ?R))\"\n    by (metis inv_tR invertible_fst_Gauss_Jordan_PA matrix_inv_Gauss_Jordan_PA)\n  have \"(x \\<in> set_least_squares_approximation A b) = (transpose A ** A *v x = transpose A *v b)\"\n    using in_set_least_squares_approximation_eq .\n  also have \"... = (transpose (?Q ** ?R) ** (?Q ** ?R) *v x = transpose (?Q ** ?R) *v b)\"\n    using QR_decomposition_mult[OF r] by simp\n  also have \"... = (transpose ?R ** transpose ?Q **  (?Q ** ?R) *v x  = transpose ?R ** transpose ?Q *v b)\"\n    by (metis (hide_lams, no_types) matrix_transpose_mul)\n  also have \"... = (transpose ?R *v (transpose ?Q ** (?Q ** ?R) *v x)  = transpose ?R *v (transpose ?Q *v b))\"\n    by (metis (hide_lams, no_types) matrix_vector_mul_assoc)\n  also have \"... = (matrix_inv (transpose ?R) *v (transpose ?R *v (transpose ?Q ** (?Q ** ?R) *v x))  \n    = matrix_inv (transpose ?R) *v (transpose ?R *v (transpose ?Q *v b)))\"\n    using inv_matrix_vector_mul_left[OF inv_inv_tR] by auto\n  also have \"... = ((matrix_inv (transpose ?R) ** transpose ?R) *v (transpose ?Q ** (?Q ** ?R) *v x)  \n    = (matrix_inv (transpose ?R) ** transpose ?R) *v (transpose ?Q *v b))\"\n    by (metis (hide_lams, no_types) matrix_vector_mul_assoc)\n  also have \"... = (transpose ?Q ** (?Q ** ?R) *v x = transpose ?Q *v b)\"\n    unfolding matrix_inv_left[OF inv_tR]\n    unfolding matrix_vector_mul_lid ..\n  also have \"... = ((transpose ?Q ** ?Q) ** ?R *v x = transpose ?Q *v b)\"\n    by (metis (hide_lams, no_types) matrix_mul_assoc)\n  also have \"... = (?R *v x = transpose ?Q *v b)\"\n    unfolding orthogonal_matrix_fst_QR_decomposition[OF r]\n    unfolding matrix_mul_lid ..\n  finally show \"(x \\<in> set_least_squares_approximation A b) = (?R *v x = (transpose ?Q) *v b)\" .\nqed\n\n(*TODO: Maybe demonstrate that in this case there's only one solution.*)\ncorollary in_set_least_squares_approximation_eq_full_rank_QR2:\n  fixes A::\"real^'cols::{mod_type}^'rows::{mod_type}\"\n  assumes r: \"rank A = ncols A\"\n  shows \"(x \\<in> set_least_squares_approximation A b) = (x = matrix_inv (snd (QR_decomposition A)) ** transpose (fst (QR_decomposition A)) *v b)\"\nproof -\n  let ?Q = \"fst (QR_decomposition A)\"\n  let ?R = \"snd (QR_decomposition A)\"\n  have inv_R: \"invertible ?R\" by (metis invertible_snd_QR_decomposition r)\n  have \"(x \\<in> set_least_squares_approximation A b) = (?R *v x = transpose ?Q *v b)\"\n    using in_set_least_squares_approximation_eq_full_rank_QR[OF r] .\n  also have \"... = (matrix_inv ?R ** ?R *v x = matrix_inv ?R ** transpose ?Q *v b)\"\n    by (metis (hide_lams, no_types) Gauss_Jordan_PA_eq calculation fst_Gauss_Jordan_PA inv_R \n      inv_matrix_vector_mul_left invertible_fst_Gauss_Jordan_PA matrix_inv_Gauss matrix_vector_mul_assoc)\n  also have \"... = (x = matrix_inv ?R ** transpose ?Q *v b)\"\n    by (metis inv_R matrix_inv_left matrix_vector_mul_lid)\n  finally show \"(x \\<in> set_least_squares_approximation A b) = (x = matrix_inv ?R ** transpose ?Q *v b)\" .\nqed\n\nlemma set_least_squares_approximation_unique_solution:\n  fixes A::\"real^'cols::{mod_type}^'rows::{mod_type}\"\n  assumes r: \"rank A = ncols A\"\n  shows \"(set_least_squares_approximation A b) = {matrix_inv (transpose A ** A)**transpose A *v b}\"\n  by (metis (hide_lams, mono_tags) empty_iff in_set_least_squares_approximation_eq_full_rank\n    empty_iff insertI1 r subsetI subset_singletonD)\n\nlemma set_least_squares_approximation_unique_solution_QR:\n  fixes A::\"real^'cols::{mod_type}^'rows::{mod_type}\"\n  assumes r: \"rank A = ncols A\"\n  shows \"(set_least_squares_approximation A b) = {matrix_inv (snd (QR_decomposition A)) ** transpose (fst (QR_decomposition A)) *v b}\"\n  by (metis (hide_lams, mono_tags) empty_iff in_set_least_squares_approximation_eq_full_rank_QR2 insertI1 r subsetI subset_singletonD)\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/Least_Squares_Approximation.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8577680977182187, "lm_q2_score": 0.8175744673038222, "lm_q1q2_score": 0.7012892955621856}}
{"text": "theory ANiceLimit\n  imports  \"HOL-Real_Asymp.Real_Asymp\"\nbegin\n\n(* With help from Manuel Eberl on Zulip *)\n\n(* Reminder of different forms:\n\ntranslations\n  \"LIM x F1. f :> F2\" == \"CONST filterlim (\\<lambda>x. f) F2 F1\"\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\n*)\n\n\nlemma \\<open>filterlim (\\<lambda>x::real. (1 + 1 / x) powr x) (nhds (exp 1)) at_top\\<close>\n  by real_asymp\n\nlemma x1:\n  fixes a::real \n  assumes \"a > 0\" \n  shows \"((\\<lambda>x. a powr x) \\<longlongrightarrow> 1) (at_right 0)\"\n(*  shows \"filterlim (\\<lambda>x::real. a powr x) (at_right 1) (at_right 0)\"*)\nusing assms by real_asymp\n\nlemma \"a \\<in> {0<..<1} \\<Longrightarrow> filterlim (\\<lambda>x::real. a powr x) (at_left 1) (at_right 0)\"\n      \"a > 1 \\<Longrightarrow> filterlim (\\<lambda>x::real. a powr x) (at_right 1) (at_right 0)\"\n  by real_asymp+\n\n\nsledgehammer_params[debug=true,timeout=600]\n\n\nlemma  xx2:\n  fixes a::real \n  assumes \"a > 0\" \n  shows \"LIM (x::real) at_right 0. a powr x :> nhds 1\"  using x1 assms by simp\n\n\nlemma xx3:\n fixes a::real \n  assumes \"a > 0\" \n  shows \"((\\<lambda>x. a powr x) has_real_derivative ln a * a powr x) (at x)\"\nproof -\n  have \"((\\<lambda>_. a) has_real_derivative 0) (at x)\" by simp\n  moreover have \"((\\<lambda>x. x) has_real_derivative 1) (at x)\" by simp\n  ultimately show ?thesis using   DERIV_powr[of \"\\<lambda>_.a\" 0 x \"\\<lambda>x. x\" 1] assms \n    by (simp add: mult.commute)\nqed\n\nlemma  xx:\n  fixes a::real \n  assumes \"a > 0\" \n  shows \"LIM x at_right 0. (a powr x - 1) / x :> nhds (ln a)\"\nproof -\n  let ?f' = \"\\<lambda>x. (ln a) * (a powr x)\" \n  let ?g' = \"\\<lambda>_. 1::real\"\n  show ?thesis \nproof(rule lhopital_right_0)\n  show \"((\\<lambda>x. a powr x - 1) \\<longlongrightarrow> 0) (at_right 0)\" using assms by real_asymp\n  show \" ((\\<lambda>x. x) \\<longlongrightarrow> 0) (at_right 0)\" using assms by simp\n  show \" \\<forall>\\<^sub>F x in at_right 0. x \\<noteq> 0\"  \n    using eventually_at_filter not_eventuallyD by blast\n  show \" \\<forall>\\<^sub>F x::real in at_right 0. ?g' x \\<noteq> (0::real)\"   \n    unfolding eventually_at_filter apply(eventually_elim,rule,rule)\n    by simp\n             \n  show \"\\<forall>\\<^sub>F x in at_right 0. ((\\<lambda>x. a powr x - 1) has_real_derivative ?f' x) (at x)\" \n    unfolding eventually_at_filter apply(eventually_elim,rule)\n  proof \n    fix x::real\n    assume \"x \\<noteq> 0\" and \"x \\<in> {0<..}\"\n    show \"((\\<lambda>x. a powr x - 1) has_real_derivative ln a * a powr x) (at x) \"\n      using xx3 assms DERIV_minus DERIV_add sorry\n  qed\n  show \" \\<forall>\\<^sub>F x in at_right 0. ((\\<lambda>x. x) has_real_derivative ?g' x) (at x)\"  \n    by simp\n  show \" LIM x at_right 0. ?f' x / ?g' x :> nhds  (ln a)\"  using assms by real_asymp\nqed\nqed\n\nlemma yy:\n  fixes a b :: real\n  assumes \"a > 0\" \"b > 0\"\n  shows   \"((\\<lambda>x. ((a powr (1/x) + b powr (1/x)) / 2) powr x) \\<longlongrightarrow> exp ((ln a + ln b) / 2)) at_top\"\n  using assms by real_asymp\n\n\nlemma bob:\n  fixes f::\"nat \\<Rightarrow> real\" and g::\"real \\<Rightarrow> real\"\n  assumes  \"\\<forall>n. f n = g n\" and  \"(g \\<longlongrightarrow> c) at_top\"\n  shows \"f \\<longlonglongrightarrow> c\"\n  using assms tendsto_cong[of g f at_top c] \n  by (smt eventually_elim2 filterlim_iff filterlim_real_sequentially)\n\nlemma \n  fixes a::real and b::real\n  assumes \"a > 0\" and \"b > 0\"\n  shows \"(\\<lambda>n. ( (root  n a + root n b )  / 2)^n) \\<longlonglongrightarrow> (sqrt(a*b))\"\nproof -\n  have \"(\\<lambda>n. ( (root  n a + root n b )  / 2)^n) = ((\\<lambda>x. ((a powr (1/x) + b powr (1/x)) / 2) powr x))\" sorry\n  moreover have \"(sqrt(a*b)) = exp ((ln a + ln b) / 2)\" sorry\n  ultimately show ?thesis using yy[OF assms] bob by force\nqed\n  \n\n\n\n\n\nend\n\n", "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/ANiceLimit.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.865224072151174, "lm_q2_score": 0.810478913248044, "lm_q1q2_score": 0.7012458657131307}}
{"text": "theory Isar_Demo\nimports Complex_Main\nbegin\n\nsection \"An introductory 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\ntext \\<open>A bit shorter:\\<close>\n\nlemma \"\\<not> surj(f :: 'a \\<Rightarrow> 'a set)\"\nproof\n  assume 0: \"surj f\"\n  from 0 have 1: \"\\<exists>a. {x. x \\<notin> f x} = f a\" by(auto simp: surj_def)\n  from 1 show \"False\" by blast\nqed\n\nsubsection \\<open>\"this\", \"then\", \"hence\" and \"thus\\<close>\n\ntext \\<open>Avoid labels, use \"this\"\\<close>\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 simp: surj_def)\n  from this show \"False\" by blast\nqed\n\ntext \\<open>\"then\" = \"from this\"\\<close>\n\nlemma \"\\<not> surj(f :: 'a \\<Rightarrow> 'a set)\"\nproof\n  assume \"surj f\"\n  then have \"\\<exists>a. {x. x \\<notin> f x} = f a\" by(auto simp: surj_def)\n  then show \"False\" by blast\nqed\n\ntext \\<open>\"hence\" = \"then have\", \"thus\" = \"then show\"\\<close>\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  thus \"False\" by blast\nqed\n\n\nsubsection \\<open>Structured statements: \"fixes\", \"assumes\", \"shows\"\\<close>\n\nlemma\n  fixes f :: \"'a \\<Rightarrow> 'a set\"\n  assumes s: \"surj f\"\n  shows \"False\"\nproof -  (* no automatic proof step! *)\n  have \"\\<exists> a. {x. x \\<notin> f x} = f a\" using s\n    by(auto simp: surj_def)\n  thus \"False\" by blast\nqed\n\n\nsection \"Proof patterns\"\n\nlemma \"P \\<longleftrightarrow> Q\"\nproof\n  assume \"P\"\n  show \"Q\" sorry\nnext\n  assume \"Q\"\n  show \"P\" sorry\nqed\n\nlemma \"A = (B::'a set)\"\nproof\n  show \"A \\<subseteq> B\" sorry\nnext\n  show \"B \\<subseteq> A\" sorry\nqed\n\nlemma \"A \\<subseteq> B\"\nproof\n  fix a\n  assume \"a \\<in> A\"\n  show \"a \\<in> B\" sorry\nqed\n\ntext \"Contradiction\"\\<section>\n\nlemma P\nproof (rule ccontr)\n  assume \"\\<not>P\"\n  show \"False\" sorry\nqed\n\ntext \"Case distinction\"\n\nlemma \"R\"\nproof cases\n  assume \"P\"\n  show \"R\" sorry\nnext\n  assume \"\\<not> P\"\n  show \"R\" sorry\nqed\n\nlemma \"R\"\nproof -\n  have \"P \\<or> Q\" sorry\n  then show \"R\"\n  proof\n    assume \"P\"\n    show \"R\" sorry\n  next\n    assume \"Q\"\n    show \"R\" sorry\n  qed\nqed\n\n\ntext \\<open>\"obtain\" example\\<close>\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\ntext \\<open>Interactive exercise:\\<close>\n\nlemma assumes \"\\<exists>x. \\<forall>y. P x y\" shows \"\\<forall>y. \\<exists>x. P x y\"\nsorry\n\n\nsubsection \\<open>(In)Equation Chains\\<close>\n\nlemma \"(0::real) \\<le> x^2 + y^2 - 2*x*y\"\nproof -\n  have \"0 \\<le> (x - y)^2\" by simp\n  also have \"\\<dots> = x^2 + y^2 - 2*x*y\"\n    by(simp add: numeral_eq_Suc algebra_simps)\n  finally show \"0 \\<le> x^2 + y^2 - 2*x*y\" .\nqed\n\ntext \\<open>Interactive exercise:\\<close>\n\nlemma\n  fixes x y :: real\n  assumes \"x \\<ge> y\" \"y > 0\"\n  shows \"(x - y) ^ 2 \\<le> x^2 - y^2\"\nproof -\n  have \"(x - y) ^ 2 = x^2 + y^2 - 2*x*y\"\n    by(simp add: numeral_eq_Suc algebra_simps)\n  show \"(x - y) ^ 2 \\<le> x^2 - y^2\" sorry\nqed\n\n\nsection \"Streamlining proofs\"\n\nsubsection \"Pattern matching and ?-variables\"\n\ntext \\<open>Show \\<open>\\<exists>\\<close>\\<close>\n\nlemma \"\\<exists> xs. length xs = 0\" (is \"\\<exists> xs. ?P xs\")\nproof\n  show \"?P([])\" by simp\nqed\n\ntext \\<open>Multiple EX easier with forward proof:\\<close>\n\nlemma \"\\<exists> x y :: int. x < z & z < y\" (is \"\\<exists> x y. ?P x y\")\nproof -\n  have \"?P (z - 1) (z + 1)\" by arith\n  thus ?thesis by blast\nqed\n\n\nsubsection \"Quoting facts\"\n\nlemma assumes \"x < (0::int)\" shows \"x*x > 0\"\nproof -\n  from `x<0` show ?thesis by(metis mult_neg_neg)\nqed\n\n\nsubsection \"Example: Top Down Proof Development\"\n\nlemma \"\\<exists>ys zs. xs = ys @ zs \\<and>\n          (length ys = length zs \\<or> length ys = length zs + 1)\"\nsorry\n\n\n\nsection \"Solutions to interactive exercises\"\n\nlemma assumes \"\\<exists>x. \\<forall>y. P x y\" shows \"\\<forall>y. \\<exists>x. P x y\"\nproof\n  fix b\n  from assms obtain a where 0: \"\\<forall>y. P a y\" by blast\n  show \"\\<exists>x. P x b\"\n  proof\n    show \"P a b\" using 0 by blast\n  qed\nqed\n\nlemma fixes x y :: real assumes \"x \\<ge> y\" \"y > 0\"\nshows \"(x - y) ^ 2 \\<le> x^2 - y^2\"\nproof -\n  have \"(x - y) ^ 2 = x^2 + y^2 - 2*x*y\"\n    by(simp add: numeral_eq_Suc algebra_simps)\n  also have \"\\<dots> \\<le> x^2 + y^2 - 2*y*y\"\n    using assms by(simp)\n  also have \"\\<dots> = x^2 - y^2\"\n    by(simp add: numeral_eq_Suc)\n  finally show ?thesis .\nqed\n\nsubsection \"Example: Top Down Proof Development\"\n\ntext \\<open>The key idea: case distinction on length:\\<close>\n\nlemma \"\\<exists>ys zs. xs = ys @ zs \\<and> (length ys = length zs \\<or> length ys = length zs + 1)\"\nproof cases\n  assume \"EX n. length xs = n+n\"\n  show ?thesis sorry\nnext\n  assume \"\\<not> (EX n. length xs = n+n)\"\n  show ?thesis sorry\nqed\n\ntext \\<open>A proof skeleton:\\<close>\n\nlemma \"\\<exists>ys zs. xs = ys @ zs \\<and> (length ys = length zs \\<or> length ys = length zs + 1)\"\nproof cases\n  assume \"\\<exists>n. length xs = n+n\"\n  then obtain n where \"length xs = n+n\" by blast\n  let ?ys = \"take n xs\"\n  let ?zs = \"take n (drop n xs)\"\n  have \"xs = ?ys @ ?zs \\<and> length ?ys = length ?zs\" sorry\n  thus ?thesis by blast\nnext\n  assume \"\\<not> (\\<exists>n. length xs = n+n)\"\n  then obtain n where \"length xs = Suc(n+n)\" sorry\n  let ?ys = \"take (Suc n) xs\"\n  let ?zs = \"take n (drop (Suc n) xs)\"\n  have \"xs = ?ys @ ?zs \\<and> length ?ys = length ?zs + 1\" sorry\n  then show ?thesis by blast\nqed\n\ntext \"The complete proof:\"\n\nlemma \"\\<exists>ys zs. xs = ys @ zs \\<and> (length ys = length zs \\<or> length ys = length zs + 1)\"\nproof cases\n  assume \"\\<exists>n. length xs = n+n\"\n  then obtain n where \"length xs = n+n\" by blast\n  let ?ys = \"take n xs\"\n  let ?zs = \"take n (drop n xs)\"\n  have \"xs = ?ys @ ?zs \\<and> length ?ys = length ?zs\"\n    by (simp add: `length xs = n + n`)\n  thus ?thesis by blast\nnext\n  assume \"\\<not> (\\<exists>n. length xs = n+n)\"\n  hence \"\\<exists>n. length xs = Suc(n+n)\" by arith\n  then obtain n where l: \"length xs = Suc(n+n)\" by blast\n  let ?ys = \"take (Suc n) xs\"\n  let ?zs = \"take n (drop (Suc n) xs)\"\n  have \"xs = ?ys @ ?zs \\<and> length ?ys = length ?zs + 1\" by (simp add: l)\n  thus ?thesis by blast\nqed\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/Isar_Demo.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.8757869932689566, "lm_q1q2_score": 0.7012356410501169}}
{"text": "(*\n  File:    Factorizations.thy\n  Author:  Manuel Eberl, TU M\u00fcnchen\n*)\nsection \\<open>Factorizations of polynomials\\<close>\ntheory Factorizations\nimports\n  Complex_Main\n  Linear_Recurrences_Misc\n  \"HOL-Computational_Algebra.Computational_Algebra\"\n  \"HOL-Computational_Algebra.Polynomial_Factorial\"\nbegin\n\ntext \\<open>\n  We view a factorisation of a polynomial as a pair consisting of the leading coefficient\n  and a list of roots with multiplicities. This gives us a factorization into factors of\n  the form $(X - c) ^ {n+1}$.\n\\<close>\ndefinition interp_factorization where\n  \"interp_factorization = (\\<lambda>(a,cs). Polynomial.smult a (\\<Prod>(c,n)\\<leftarrow>cs. [:-c,1:] ^ Suc n))\"\n\ntext \\<open>\n  An alternative way to factorise is as a pair of the leading coefficient and\n  factors of the form $(1 - cX) ^ {n+1}$.\n\\<close>\ndefinition interp_alt_factorization where\n  \"interp_alt_factorization = (\\<lambda>(a,cs). Polynomial.smult a (\\<Prod>(c,n)\\<leftarrow>cs. [:1,-c:] ^ Suc n))\"\n\ndefinition is_factorization_of where\n  \"is_factorization_of fctrs p =\n     (interp_factorization fctrs = p \\<and> distinct (map fst (snd fctrs)))\"\n\ndefinition is_alt_factorization_of where\n  \"is_alt_factorization_of fctrs p =\n     (interp_alt_factorization fctrs = p \\<and> 0 \\<notin> set (map fst (snd fctrs)) \\<and>\n     distinct (map fst (snd fctrs)))\"\n\ntext \\<open>\n  Regular and alternative factorisations are related by reflecting the polynomial.\n\\<close>\nlemma interp_factorization_reflect:\n  assumes \"(0::'a::idom) \\<notin> fst ` set (snd fctrs)\"\n  shows   \"reflect_poly (interp_factorization fctrs) = interp_alt_factorization fctrs\"\nproof -\n  have \"reflect_poly (interp_factorization fctrs) =\n          Polynomial.smult (fst fctrs) (\\<Prod>x\\<leftarrow>snd fctrs. reflect_poly [:- fst x, 1:] ^ Suc (snd x))\"\n    by (simp add: interp_factorization_def interp_alt_factorization_def case_prod_unfold\n             reflect_poly_smult reflect_poly_prod_list reflect_poly_power o_def del: power_Suc)\n  also have \"map (\\<lambda>x. reflect_poly [:- fst x, 1:] ^ Suc (snd x)) (snd fctrs) =\n               map (\\<lambda>x. [:1, - fst x:] ^ Suc (snd x)) (snd fctrs)\"\n    using assms by (intro list.map_cong0, subst reflect_poly_pCons) auto\n  also have \"Polynomial.smult (fst fctrs) (prod_list \\<dots>) = interp_alt_factorization fctrs\"\n    by (simp add: interp_alt_factorization_def case_prod_unfold)\n  finally show ?thesis .\nqed\n\nlemma interp_alt_factorization_reflect:\n  assumes \"(0::'a::idom) \\<notin> fst ` set (snd fctrs)\"\n  shows   \"reflect_poly (interp_alt_factorization fctrs) = interp_factorization fctrs\"\nproof -\n  have \"reflect_poly (interp_alt_factorization fctrs) =\n          Polynomial.smult (fst fctrs) (\\<Prod>x\\<leftarrow>snd fctrs. reflect_poly [:1, - fst x:] ^ Suc (snd x))\"\n    by (simp add: interp_factorization_def interp_alt_factorization_def case_prod_unfold\n             reflect_poly_smult reflect_poly_prod_list reflect_poly_power o_def del: power_Suc)\n  also have \"map (\\<lambda>x. reflect_poly [:1, - fst x:] ^ Suc (snd x)) (snd fctrs) =\n               map (\\<lambda>x. [:- fst x, 1:] ^ Suc (snd x)) (snd fctrs)\"\n  proof (intro list.map_cong0, clarsimp simp del: power_Suc, goal_cases)\n    fix c n assume \"(c, n) \\<in> set (snd fctrs)\"\n    with assms have \"c \\<noteq> 0\" by force\n    thus \"reflect_poly [:1, -c:] ^ Suc n = [:-c, 1:] ^ Suc n\"\n      by (simp add: reflect_poly_pCons del: power_Suc)\n  qed\n  also have \"Polynomial.smult (fst fctrs) (prod_list \\<dots>) = interp_factorization fctrs\"\n    by (simp add: interp_factorization_def case_prod_unfold)\n  finally show ?thesis .\nqed\n\n\nlemma coeff_0_interp_factorization:\n  \"coeff (interp_factorization fctrs) 0 = (0 :: 'a :: idom) \\<longleftrightarrow>\n     fst fctrs = 0 \\<or> 0 \\<in> fst ` set (snd fctrs)\"\n  by (force simp: interp_factorization_def case_prod_unfold coeff_0_prod_list o_def\n                  coeff_0_power prod_list_zero_iff simp del: power_Suc)\n\nlemma reflect_factorization:\n  assumes \"coeff p 0 \\<noteq> (0::'a::idom)\"\n  assumes \"is_factorization_of fctrs p\"\n  shows   \"is_alt_factorization_of fctrs (reflect_poly p)\"\n  using assms by (force simp: interp_factorization_reflect is_factorization_of_def\n                    is_alt_factorization_of_def coeff_0_interp_factorization)\n\nlemma reflect_factorization':\n  assumes \"coeff p 0 \\<noteq> (0::'a::idom)\"\n  assumes \"is_alt_factorization_of fctrs p\"\n  shows   \"is_factorization_of fctrs (reflect_poly p)\"\n  using assms by (force simp: interp_alt_factorization_reflect is_factorization_of_def\n                    is_alt_factorization_of_def coeff_0_interp_factorization)\n\nlemma zero_in_factorization_iff:\n  assumes \"is_factorization_of fctrs p\"\n  shows   \"coeff p 0 = 0 \\<longleftrightarrow> p = 0 \\<or> (0::'a::idom) \\<in> fst ` set (snd fctrs)\"\nproof (cases \"p = 0\")\n  assume \"p \\<noteq> 0\"\n  with assms have [simp]: \"fst fctrs \\<noteq> 0\"\n    by (auto simp: is_factorization_of_def interp_factorization_def case_prod_unfold)\n  from assms have \"p = interp_factorization fctrs\" by (simp add: is_factorization_of_def)\n  also have \"coeff \\<dots> 0 = 0 \\<longleftrightarrow> 0 \\<in> fst ` set (snd fctrs)\"\n    by (force simp add: interp_factorization_def case_prod_unfold coeff_0_prod_list\n                        prod_list_zero_iff o_def coeff_0_power)\n  finally show ?thesis using \\<open>p \\<noteq> 0\\<close> by blast\nnext\n  assume p: \"p = 0\"\n  with assms have \"interp_factorization fctrs = 0\" by (simp add: is_factorization_of_def)\n  also have \"interp_factorization fctrs = 0 \\<longleftrightarrow>\n                 fst fctrs = 0 \\<or> (\\<Prod>(c,n)\\<leftarrow>snd fctrs. [:-c,1:]^Suc n) = 0\"\n    by (simp add: interp_factorization_def case_prod_unfold)\n  also have \"(\\<Prod>(c,n)\\<leftarrow>snd fctrs. [:-c,1:]^Suc n) = 0 \\<longleftrightarrow> False\"\n    by (auto simp: prod_list_zero_iff simp del: power_Suc)\n  finally show ?thesis by (simp add: \\<open>p = 0\\<close>)\nqed\n\nlemma poly_prod_list [simp]: \"poly (prod_list ps) x = prod_list (map (\\<lambda>p. poly p x) ps)\"\n  by (induction ps) auto\n\nlemma is_factorization_of_roots:\n  fixes a :: \"'a :: idom\"\n  assumes \"is_factorization_of (a, fctrs) p\" \"p \\<noteq> 0\"\n  shows   \"set (map fst fctrs) = {x. poly p x = 0}\"\n  using assms\n  by (force simp: is_factorization_of_def interp_factorization_def o_def\n        case_prod_unfold prod_list_zero_iff simp del: power_Suc)\n\nlemma (in monoid_mult) prod_list_prod_nth: \"prod_list xs = (\\<Prod>i<length xs. xs ! i)\"\n  by (induction xs) (auto simp: prod.lessThan_Suc_shift simp del: prod.lessThan_Suc)\n\nlemma order_prod:\n  assumes \"\\<And>x. x \\<in> A \\<Longrightarrow> f x \\<noteq> 0\"\n  assumes \"\\<And>x y. x \\<in> A \\<Longrightarrow> y \\<in> A \\<Longrightarrow> x \\<noteq> y \\<Longrightarrow> coprime (f x) (f y)\"\n  shows   \"order c (prod f A) = (\\<Sum>x\\<in>A. order c (f x))\"\n  using assms\nproof (induction A rule: infinite_finite_induct)\n  case (insert x A)\n  from insert.hyps have \"order c (prod f (insert x A)) = order c (f x * prod f A)\"\n    by simp\n  also have \"\\<dots> = order c (f x) + order c (prod f A)\"\n    using insert.prems and insert.hyps by (intro order_mult) auto\n  also have \"order c (prod f A) = (\\<Sum>x\\<in>A. order c (f x))\"\n    using insert.prems and insert.hyps by (intro insert.IH) auto\n  finally show ?case using insert.hyps by simp\nqed auto\n\nlemma is_factorization_of_order:\n  fixes p :: \"'a :: field_gcd poly\"\n  assumes \"p \\<noteq> 0\"\n  assumes \"is_factorization_of (a, fctrs) p\"\n  assumes \"(c, n) \\<in> set fctrs\"\n  shows   \"order c p = Suc n\"\nproof -\n  from assms have distinct: \"distinct (map fst (fctrs))\"\n    by (simp add: is_factorization_of_def)\n  from assms have [simp]: \"a \\<noteq> 0\"\n    by (auto simp: is_factorization_of_def interp_factorization_def)\n  from assms(2) have \"p = interp_factorization (a, fctrs)\"\n    unfolding is_factorization_of_def by simp\n  also have \"order c \\<dots> = order c (\\<Prod>(c,n)\\<leftarrow>fctrs. [:-c, 1:] ^ Suc n)\"\n    unfolding interp_factorization_def by (simp add: order_smult)\n  also have \"(\\<Prod>(c,n)\\<leftarrow>fctrs. [:-c, 1:] ^ Suc n) =\n               (\\<Prod>i\\<in>{..<length fctrs}. [:-fst (fctrs ! i), 1:] ^ Suc (snd (fctrs ! i)))\"\n    by (simp add: prod_list_prod_nth case_prod_unfold)\n  also have \"order c \\<dots> =\n               (\\<Sum>x<length fctrs. order c ([:- fst (fctrs ! x), 1:] ^ Suc (snd (fctrs ! x))))\"\n  proof (rule order_prod)\n    fix i\n    assume \"i \\<in> {..<length fctrs}\"\n    then show \"[:- fst (fctrs ! i), 1:] ^ Suc (snd (fctrs ! i)) \\<noteq> 0\"\n      by (simp only: power_eq_0_iff) simp\n  next\n    fix i j :: nat\n    assume \"i \\<noteq> j\" \"i \\<in> {..<length fctrs}\" \"j \\<in> {..<length fctrs}\"\n    then have \"fst (fctrs ! i) \\<noteq> fst (fctrs ! j)\"\n      using nth_eq_iff_index_eq [OF distinct, of i j] by simp\n    then show \"coprime ([:- fst (fctrs ! i), 1:] ^ Suc (snd (fctrs ! i)))\n      ([:- fst (fctrs ! j), 1:] ^ Suc (snd (fctrs ! j)))\"\n      by (simp only: coprime_power_left_iff coprime_power_right_iff)\n        (auto simp add: coprime_linear_poly)\n  qed\n  also have \"\\<dots> = (\\<Sum>(c',n')\\<leftarrow>fctrs. order c ([:-c', 1:] ^ Suc n'))\"\n    by (simp add: sum_list_sum_nth case_prod_unfold atLeast0LessThan)\n  also have \"\\<dots> = (\\<Sum>(c',n')\\<leftarrow>fctrs. if c = c' then Suc n' else 0)\"\n    by (intro arg_cong[OF map_cong]) (auto simp add: order_power_n_n order_0I simp del: power_Suc)\n  also have \"\\<dots> = (\\<Sum>x\\<leftarrow>fctrs. if x = (c, n) then Suc (snd x) else 0)\"\n    using distinct assms by (intro arg_cong[OF map_cong]) (force simp: distinct_map inj_on_def)+\n  also from distinct have \"\\<dots> = (\\<Sum>x\\<in>set fctrs. if x = (c, n) then Suc (snd x) else 0)\"\n    by (intro sum_list_distinct_conv_sum_set) (simp_all add: distinct_map)\n  also from assms have \"\\<dots> = Suc n\" by simp\n  finally show ?thesis .\nqed\n\n\ntext \\<open>\n  For complex polynomials, a factorisation in the above sense always exists.\n\\<close>\nlemma complex_factorization_exists:\n  \"\\<exists>fctrs. is_factorization_of fctrs (p :: complex poly)\"\nproof (cases \"p = 0\")\n  case True\n  thus ?thesis\n    by (intro exI[of _ \"(0, [])\"]) (auto simp: is_factorization_of_def interp_factorization_def)\nnext\n  case False\n  hence \"\\<exists>xs. set xs = {x. poly p x = 0} \\<and> distinct xs\"\n    by (intro finite_distinct_list poly_roots_finite)\n  then obtain xs where [simp]: \"set xs = {x. poly p x = 0}\" \"distinct xs\" by blast\n  have \"interp_factorization (lead_coeff p, map (\\<lambda>x. (x, order x p - 1)) xs) =\n          smult (lead_coeff p) (\\<Prod>x\\<leftarrow>xs. [:- x, 1:] ^ Suc (order x p - 1))\"\n    by (simp add: interp_factorization_def o_def)\n  also have \"(\\<Prod>x\\<leftarrow>xs. [:- x, 1:] ^ Suc (order x p - 1)) =\n               (\\<Prod>x|poly p x = 0. [:- x, 1:] ^ Suc (order x p - 1))\"\n    by (subst prod.distinct_set_conv_list [symmetric]) simp_all\n  also have \"\\<dots> = (\\<Prod>x|poly p x = 0. [:- x, 1:] ^ order x p)\"\n  proof (intro prod.cong refl, goal_cases)\n    case (1 x)\n    with False have \"order x p \\<noteq> 0\" by (subst (asm) order_root) auto\n    hence *: \"Suc (order x p - 1) = order x p\" by simp\n    show ?case by (simp only: *)\n  qed\n  also have \"smult (lead_coeff p) \\<dots> = p\"\n    by (rule complex_poly_decompose)\n  finally have \"is_factorization_of (lead_coeff p, map (\\<lambda>x. (x, order x p - 1)) xs) p\"\n    by (auto simp: is_factorization_of_def o_def)\n  thus ?thesis ..\nqed\n\ntext \\<open>\n  By reflecting the polynomial, this means that for complex polynomials with non-zero\n  constant coefficient, the alternative factorisation also exists.\n\\<close>\ncorollary complex_alt_factorization_exists:\n  assumes \"coeff p 0 \\<noteq> 0\"\n  shows   \"\\<exists>fctrs. is_alt_factorization_of fctrs (p :: complex poly)\"\nproof -\n  from assms have \"coeff (reflect_poly p) 0 \\<noteq> 0\"\n    by auto\n  moreover from complex_factorization_exists [of \"reflect_poly p\"]\n  obtain fctrs where \"is_factorization_of fctrs (reflect_poly p)\" ..\n  ultimately have \"is_alt_factorization_of fctrs (reflect_poly (reflect_poly p))\"\n    by (rule reflect_factorization)\n  also from assms have \"reflect_poly (reflect_poly p) = p\"\n    by simp\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/Linear_Recurrences/Factorizations.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424528443251, "lm_q2_score": 0.8289388083214155, "lm_q1q2_score": 0.7012345287692702}}
{"text": "theory RelUtils\n  imports Main \"HOL.Transitive_Closure\"\nbegin\n\n\\<comment> \\<open>NOTE added definition.\\<close>\ndefinition reflexive where \n  \"reflexive R \\<equiv> \\<forall>x. R x x\"\n\n\\<comment> \\<open>NOTE translation of 'TC' in relationScript.sml:69.\\<close>\n\\<comment> \\<open>TODO can we replace this with something from 'HOL.Transitive\\_Closure'?\\<close>\ndefinition TC where\n  \"TC R a b \\<equiv> (\\<forall>P. (\\<forall>x y. R x y \\<longrightarrow> P x y) \\<and> (\\<forall>x y z. P x y \\<and> P y z \\<longrightarrow> P x z) \\<longrightarrow> P a b)\"\n\n\\<comment> \\<open>NOTE adapts transitive closure definitions of Isabelle and HOL4.\\<close>\nlemma TC_equiv_tranclp: \"TC R a b \\<longleftrightarrow> (R\\<^sup>+\\<^sup>+ a b)\"\nproof -\n  {\n    have \"TC R a b \\<Longrightarrow> (R\\<^sup>+\\<^sup>+ a b)\"\n      unfolding TC_def \n      using tranclp.r_into_trancl tranclp_trans\n      by metis\n  }\n  moreover \n  {\n    have \"(R\\<^sup>+\\<^sup>+ a b) \\<Longrightarrow> TC R a b\" proof(induction rule: tranclp.induct)\n      case (r_into_trancl a b)\n      then show ?case by(subst TC_def; auto)\n    next\n      case (trancl_into_trancl a b c)\n      then show ?case unfolding TC_def by blast\n    qed \n  }\n  ultimately show ?thesis\n    by fast\nqed\n\nlemma TC_IMP_NOT_TC_CONJ_1:\n  fixes R P  and  x y\n  assumes \"\\<not>(R\\<^sup>+\\<^sup>+ x y)\"\n  shows \"\\<not>((\\<lambda>x y. R x y \\<and> P x y)\\<^sup>+\\<^sup>+ x y)\"\nproof -\n  from assms(1) have 1: \"\\<not>TC R x y\"\n    using TC_equiv_tranclp\n    by fast\n  {\n    assume P: \"\\<not>TC R x y\"\n    then obtain P where a: \"(\\<forall>x y. R x y \\<longrightarrow> P x y) \\<and> (\\<forall>x y z. P x y \\<and> P y z \\<longrightarrow> P x z) \\<longrightarrow> \\<not>P x y\" \n      unfolding TC_def\n      by blast\n    {\n      assume P_1: \"(\\<forall>x y. R x y \\<longrightarrow> P x y)\" \"(\\<forall>x y z. P x y \\<and> P y z \\<longrightarrow> P x z)\"\n      then have \"(\\<forall>x y. R x y \\<and> P x y \\<longrightarrow> P x y)\" \"(\\<forall>x y z. P x y \\<and> P y z \\<longrightarrow> P x z)\"\n        by blast+\n      moreover from a and P_1 have \"\\<not>P x y\"\n        by blast\n      then have \"\\<exists>P. (\\<forall>x y. R x y \\<and> P x y \\<longrightarrow> P x y) \\<and> (\\<forall>x y z. P x y \\<and> P y z \\<longrightarrow> P x z) \\<longrightarrow> \\<not>P x y\"\n        by blast\n    }\n    then have \"\\<exists>P. \n      (\\<forall>x y. R x y \\<and> P x y \\<longrightarrow> P x y) \\<and> (\\<forall>x y z. P x y \\<and> P y z \\<longrightarrow> P x z) \\<longrightarrow> \\<not>P x y\" \n      by blast \n  }\n  note 2 = this\n  {\n    from 1 2 have \"\\<exists>P. \n      (\\<forall>x y. R x y \\<and> P x y \\<longrightarrow> P x y) \\<and> (\\<forall>x y z. P x y \\<and> P y z \\<longrightarrow> P x z) \\<longrightarrow> \\<not>P x y\" \n      by blast\n    then have \"\\<not>TC (\\<lambda>x y. R x y \\<and> P x y) x y\" \n      unfolding TC_def  \n      by (metis assms tranclp.r_into_trancl tranclp_trans)\n    then have \"\\<not>(\\<lambda>x y. R x y \\<and> P x y)\\<^sup>+\\<^sup>+ x y\" \n      using TC_equiv_tranclp\n      by fast\n  }\n  then show ?thesis\n    by blast\nqed\n\nlemma TC_IMP_NOT_TC_CONJ:\n  fixes R R' P x y\n  assumes \"\\<forall>x y. P x y \\<longrightarrow> R' x y \\<longrightarrow> R x y\" \"\\<not>R\\<^sup>+\\<^sup>+ x y\"\n  shows \"\\<not>(\\<lambda>x y. R' x y \\<and> P x y)\\<^sup>+\\<^sup>+ x y\" \nproof -\n  from assms(2)\n  have 1: \"\\<not>(\\<lambda>x y. R x y \\<and> P x  y)\\<^sup>+\\<^sup>+ x y\"\n    using TC_IMP_NOT_TC_CONJ_1[where P=\"\\<lambda>x y. P x y\"]\n    by blast\n  {\n    {\n      from 1 have  \"\\<not>TC (\\<lambda>x y. R x y \\<and> P x  y) x y\" \n        using TC_equiv_tranclp \n        by fast\n      then have \"\\<exists>Pa.\n      (\\<forall>x y. R x y \\<and> P x y \\<longrightarrow> Pa x y) \\<and> (\\<forall>x y z. Pa x y \\<and> Pa y z \\<longrightarrow> Pa x z) \n      \\<longrightarrow> \\<not>Pa x y\"\n        unfolding TC_def\n        by blast\n    }\n    then obtain Pa where a: \n      \"(\\<forall>x y. R x y \\<and> P x y \\<longrightarrow> Pa x y) \\<and> (\\<forall>x y z. Pa x y \\<and> Pa y z \\<longrightarrow> Pa x z) \\<longrightarrow> \\<not>Pa x y\"\n      by blast\n    then have \"\\<not>(\\<forall>Pa. (\\<forall>x y. R' x y \\<and> P x y \\<longrightarrow> Pa x y) \\<and> (\\<forall>x y z. Pa x y \\<and> Pa y z \\<longrightarrow> Pa x z) \\<longrightarrow> Pa x y)\"\n      by (metis assms(1) assms(2) tranclp.r_into_trancl tranclp_trans) \n    then have \"\\<not>TC (\\<lambda>x y. R' x y \\<and> P x y) x y\" \n      unfolding TC_def\n      by blast\n  }\n  then show ?thesis\n    using TC_equiv_tranclp\n    by fast\nqed\n\n\\<comment> \\<open>NOTE added lemma (relationScript.sml:314)\\<close> \nlemma TC_INDUCT:\n  fixes R :: \"'a \\<Rightarrow> 'a \\<Rightarrow> bool\" and P\n  assumes \"(\\<forall>x y. R x y \\<longrightarrow> P x y)\" \"(\\<forall>x y z. P x y \\<and> P y z \\<longrightarrow> P x z)\" \n  shows \"\\<forall>u v. (TC R) u v \\<longrightarrow> P u v\"\n  using assms\n  unfolding TC_def\n  by metis\n\nlemma REFL_IMP_3_CONJ_1:\n  fixes R P x y\n  assumes \"((\\<lambda>x y. R x y \\<and> P x y)\\<^sup>+\\<^sup>+ x y)\"\n  shows \"R\\<^sup>+\\<^sup>+ x y\" \n  using assms \nproof -\n  show ?thesis\n    using assms TC_IMP_NOT_TC_CONJ_1\n    by fast\nqed\n\nlemma REFL_IMP_3_CONJ:\n  fixes R'\n  assumes \"reflexive R'\" \n  shows \"(\\<forall>P x y. \n    (R'\\<^sup>+\\<^sup>+ x y) \\<longrightarrow> ( ((\\<lambda>x y. R' x y \\<and> P x \\<and> P y)\\<^sup>+\\<^sup>+ x y) \\<or> (\\<exists>z. \\<not>P z \\<and> R'\\<^sup>+\\<^sup>+ x z \\<and> R'\\<^sup>+\\<^sup>+ z y)))\"\nproof -\n  {\n    fix P\n    {\n      have \"\\<forall>x y. R' x y \\<longrightarrow> (\\<lambda>x y. R' x y \\<and> P x \\<and> P y)\\<^sup>+\\<^sup>+ x y \\<or> (\\<exists>z. \\<not> P z \\<and> R'\\<^sup>+\\<^sup>+ x z \\<and> R'\\<^sup>+\\<^sup>+ z y)\" \n      proof (auto)\n        fix x y\n        assume P: \"R' x y\" \"\\<forall>z. R'\\<^sup>+\\<^sup>+ x z \\<longrightarrow> P z \\<or> \\<not> R'\\<^sup>+\\<^sup>+ z y\"\n        then show \"(\\<lambda>x y. R' x y \\<and> P x \\<and> P y)\\<^sup>+\\<^sup>+ x y\"\n        proof -\n          have a: \"\\<And>a. \\<not> R' x a \\<or> \\<not> R' a y \\<or> P a\"\n            using P(2)\n            by blast\n          have \"reflexive R'\"\n            by (meson assms)\n          then show ?thesis\n            using a P(1)\n            by (simp add: reflexive_def tranclp.r_into_trancl)\n        qed\n      qed\n    }\n    moreover {\n      have \"\\<forall>x y z. ((\\<lambda>x y. R' x y \\<and> P x \\<and> P y)\\<^sup>+\\<^sup>+ x y \\<or> (\\<exists>z. \\<not> P z \\<and> R'\\<^sup>+\\<^sup>+ x z \\<and> R'\\<^sup>+\\<^sup>+ z y)) \\<and>\n         ((\\<lambda>x y. R' x y \\<and> P x \\<and> P y)\\<^sup>+\\<^sup>+ y z \\<or> (\\<exists>za. \\<not> P za \\<and> R'\\<^sup>+\\<^sup>+ y za \\<and> R'\\<^sup>+\\<^sup>+ za z)) \\<longrightarrow>\n         (\\<lambda>x y. R' x y \\<and> P x \\<and> P y)\\<^sup>+\\<^sup>+ x z \\<or> (\\<exists>za. \\<not> P za \\<and> R'\\<^sup>+\\<^sup>+ x za \\<and> R'\\<^sup>+\\<^sup>+ za z)\" \n      proof (auto)\n        fix x y z za\n        assume P: \"\\<forall>za. R'\\<^sup>+\\<^sup>+ x za \\<longrightarrow> P za \\<or> \\<not> R'\\<^sup>+\\<^sup>+ za z\" \"(\\<lambda>x y. R' x y \\<and> P x \\<and> P y)\\<^sup>+\\<^sup>+ x y\"\n          \"\\<not> P za\" \"R'\\<^sup>+\\<^sup>+ y za\" \"R'\\<^sup>+\\<^sup>+ za z\" \n        then show \"(\\<lambda>x y. R' x y \\<and> P x \\<and> P y)\\<^sup>+\\<^sup>+ x z\"\n          using P\n          by (meson P rtranclp_tranclp_tranclp TC_IMP_NOT_TC_CONJ_1  tranclp_into_rtranclp)\n      next \n        fix x y z za\n        assume P: \"\\<forall>za. R'\\<^sup>+\\<^sup>+ x za \\<longrightarrow> P za \\<or> \\<not> R'\\<^sup>+\\<^sup>+ za z\" \"\\<not> P za\" \"R'\\<^sup>+\\<^sup>+ x za\" \"R'\\<^sup>+\\<^sup>+ za y\" \n          \"(\\<lambda>x y. R' x y \\<and> P x \\<and> P y)\\<^sup>+\\<^sup>+ y z\" \n        then show \"(\\<lambda>x y. R' x y \\<and> P x \\<and> P y)\\<^sup>+\\<^sup>+ x z\"\n          by (meson P TC_IMP_NOT_TC_CONJ_1 tranclp_trans)\n      qed\n    }\n    ultimately have \"\\<forall>u v. \n      TC R' u v \n      \\<longrightarrow> (\\<lambda>x y. R' x y \\<and> P x \\<and> P y)\\<^sup>+\\<^sup>+ u v \\<or> (\\<exists>z. \\<not> P z \\<and> R'\\<^sup>+\\<^sup>+ u z \\<and> R'\\<^sup>+\\<^sup>+ z v)\"\n      using TC_INDUCT[where R=\"R'\" and\n          P=\"\\<lambda>x y. ( ((\\<lambda>x y. R' x y \\<and> P x \\<and> P y)\\<^sup>+\\<^sup>+ x y) \\<or> (\\<exists>z. \\<not>P z \\<and> R'\\<^sup>+\\<^sup>+ x z \\<and> R'\\<^sup>+\\<^sup>+ z y))\"]\n      by fast\n  }\n  then show ?thesis \n    by (simp add: TC_equiv_tranclp)\nqed\n\n\n\n\\<comment> \\<open>NOTE \n  This is not a trivial translation: 'TC\\_INDUCT' in relationScript.sml:314 differs significantly\nfrom 'trancl\\_induct' and 'trancl\\_trans\\_induct' in Transitive\\_Closure:375, 391\\<close>\nlemma TC_CASES1_NEQ:\n  fixes R x z\n  assumes \"R\\<^sup>+\\<^sup>+ x z\"\n  shows \"R x z \\<or> (\\<exists>y :: 'a. \\<not>(x = y) \\<and> \\<not>(y = z) \\<and> R x y \\<and> R\\<^sup>+\\<^sup>+ y z)\"\nproof -\n  {\n    fix u v\n    have \"\\<forall>x y. R x y \\<longrightarrow> R x y \\<or> (\\<exists>ya. x \\<noteq> ya \\<and> ya \\<noteq> y \\<and> R x ya \\<and> R\\<^sup>+\\<^sup>+ ya y)\"\n      by meson\n    moreover have \"\\<forall>x y z. \n      (R x y \\<or> (\\<exists>ya. x \\<noteq> ya \\<and> ya \\<noteq> y \\<and> R x ya \\<and> R\\<^sup>+\\<^sup>+ ya y)) \n      \\<and> (R y z \\<or> (\\<exists>ya. y \\<noteq> ya \\<and> ya \\<noteq> z \\<and> R y ya \\<and> R\\<^sup>+\\<^sup>+ ya z)) \n      \\<longrightarrow> R x z \\<or> (\\<exists>y. x \\<noteq> y \\<and> y \\<noteq> z \\<and> R x y \\<and> R\\<^sup>+\\<^sup>+ y z)\"\n      by (metis tranclp.r_into_trancl tranclp_trans)\n    ultimately have \"TC R u v \\<longrightarrow> R u v \\<or> (\\<exists>y. u \\<noteq> y \\<and> y \\<noteq> v \\<and> R u y \\<and> R\\<^sup>+\\<^sup>+ y v)\" \n      using TC_INDUCT[where P=\"\\<lambda>x z. R x z \\<or> (\\<exists>y :: 'a. \\<not>(x = y) \\<and> \\<not>(y = z) \\<and> R x y \\<and> R\\<^sup>+\\<^sup>+ y z)\"]\n      by blast\n  }\n  then show ?thesis \n    using assms TC_equiv_tranclp\n    by (simp add: TC_equiv_tranclp)\nqed\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/Factored_Transition_System_Bounding/RelUtils.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8289388083214156, "lm_q2_score": 0.8459424373085146, "lm_q1q2_score": 0.7012345158910339}}
{"text": "(*  Title:       Tensor Product of Matrices\n    Author:      T. V. H. Prathamesh (prathamesh@imsc.res.in)\n    Maintainer:  T. V. H. Prathamesh\n*)\n\ntext\\<open>\nWe define Tensor Product of Matrics and prove properties such as associativity and mixed product \nproperty(distributivity) of the tensor product.\\<close>\n\nsection\\<open>Tensor Product of Matrices\\<close>\n\ntheory Matrix_Tensor\nimports Matrix.Utility Matrix.Matrix_Legacy\nbegin\n\n\nsubsection\\<open>Defining the Tensor Product\\<close>\n\n\n\ntext\\<open>We define a multiplicative locale here - mult, \nwhere the multiplication satisfies commutativity, \nassociativity and contains a left and right identity\\<close>\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\\<open>times a v , gives us the product of the vector v with \nmultiplied pointwise with a\\<close>\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\"\n by(induction v)(auto simp add:left_id)\n\nlemma times_vector_id: \"times v [id] = [v]\"\n by(simp add:right_id)\n\nlemma preserving_length: \"length (times n y) = (length y)\"\n by(induction y)(auto)\n\ntext\\<open>vec$\\_$vec$\\_$Tensor is the tensor product of two vectors. It is \nillustrated by the following relation\n \n$vec\\_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)$\\<close>\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\"\n by(induction v)(auto simp add:left_id)\n\nlemma vec_vec_Tensor_right_id: \"vec_vec_Tensor v [id] = v\"\n by(induction v)(auto simp add:right_id)\n\ntheorem vec_vec_Tensor_length : \n \"(length(vec_vec_Tensor x y)) = (length x)*(length y)\"\n by(induction x)(auto simp add: preserving_length)\n\ntheorem vec_length: assumes \"vec m x\" and \"vec n y\"\nshows \"vec (m*n) (vec_vec_Tensor x y)\"\n apply(simp add:vec_def)\n apply(simp add:vec_vec_Tensor_length)\n apply (metis assms(1) assms(2) vec_def)\n done\n\n\ntext\\<open>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$)\\<close>\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 by(induction v)(auto simp add: times_scalar_id)\n\nlemma vec_mat_Tensor_matrix_id: \"vec_mat_Tensor  v [[id]] = [v]\"\n by(induction v)(auto simp add: right_id)\n\ntheorem vec_mat_Tensor_length: \n \"length(vec_mat_Tensor xs ys) = length ys\"\n by(induction ys)(auto)\n\ntheorem length_matrix: \n assumes \"mat nr nc (y#ys)\" and \"length v = k\"\n     and \"(vec_mat_Tensor v (y#ys) = x#xs)\" \n shows \"(vec (nr*k) x)\" \nproof-\n have \"vec_mat_Tensor v (y#ys) = (vec_vec_Tensor v y)#(vec_mat_Tensor v ys)\"  \n       using vec_mat_Tensor_def assms by auto\n also have \"(vec_vec_Tensor v y) = x\" using assms by auto\n also have \"length y = nr\" using assms mat_def \n       by (metis in_set_member member_rec(1) vec_def)\n from this\n   have \"length (vec_vec_Tensor v y) = nr*k\" \n       using assms vec_vec_Tensor_length  by auto\n from this \n   have \"length x = nr*k\" by (simp add: \\<open>vec_vec_Tensor v y = x\\<close>)\n from this \n   have \"vec (nr*k) x\" using vec_def by auto\n from this \n   show ?thesis by auto\nqed\n\nlemma matrix_set_list: \n assumes \"mat nr nc M\" \n     and \"length v = k\"\n     and \" x \\<in> set M\" \n shows \"\\<exists>ys.\\<exists>zs.(ys@x#zs = M)\" \n 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: \n assumes \"m \\<noteq> []\"\n shows \"length (reduct m) +1  = (length m)\"\n apply(auto)\n by (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-\n have \"(length M = nc)\" using mat_def assms by metis\n from this \n   have \"nc = 0\" using assms by auto\n from this \n   show ?thesis by simp\nqed\n\nlemma vec_uniqueness: \n assumes \"vec m v\" \n     and \"vec n v\" \n shows \"m = n\"\n using vec_def assms(1) assms(2)  by metis\n\nlemma mat_uniqueness: \n assumes \"mat nr1 nc M\" \n and \"mat nr2 nc M\" and \"z = hd M\" and \"M \\<noteq> []\"\n shows \"(\\<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 \n           by (metis hd_in_set)\n have \"Ball (set M) (vec nr1)\" using mat_def assms(1) by auto \n then 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 then have step2: \"((x \\<in> (set M)) \\<longrightarrow> (vec nr2 x))\" using Ball_def assms by auto\n from step1 and step2 \n   have step3:\"\\<forall>x.((x \\<in> (set M))\\<longrightarrow> ((vec nr1 x)\\<and> (vec nr2 x)))\"\n   by (metis \\<open>Ball (set M) (vec nr1)\\<close> \\<open>Ball (set M) (vec nr2)\\<close>)\n have \"((vec nr1 x)\\<and> (vec nr2 x)) \\<longrightarrow> (nr1 = nr2)\" using vec_uniqueness by auto\n with step3  \n   have \"(\\<forall>x.((x \\<in> (set M)) \\<longrightarrow>((nr1 = nr2))))\" by (metis vec_uniqueness) \n then\n   have \"(\\<forall>x\\<in>(set M).(nr1 = nr2))\" by auto \n then \n     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-\n have \"set M = {}\" using mat_def assms  empty_set  by auto\n then have \"Ball (set M) (vec 0)\" using Ball_def by auto\n then have \"mat 0 nc M\" using mat_def assms(1) assms(2) gen_length_code(1) length_code\n by (metis (full_types) )\n then 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\\<open>row\\_length gives the length of the first row of a matrix. For a `valid'\nmatrix, it is equal to the number of rows\\<close>\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: \n \"row_length [] =0\" \n using row_length_def by (metis )\n\nlemma row_length_Null: \n \"row_length [[]] =0\" \n using row_length_def by auto\n\nlemma row_length_vect_mat: \n \"row_length (vec_mat_Tensor v m)  = length v*(row_length m)\"\nproof(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  then 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   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   list.distinct(1)  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\\<open>Tensor is the tensor product of matrices\\<close>\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 by(induction xs)(auto)\n\ntext\\<open>Tensor commutes with left and right identity\\<close>\n\nlemma Tensor_left_id: \"  [[id]] \\<otimes> xs = xs\"\n by(induction xs)(auto simp add:times_scalar_id)\n\nlemma Tensor_right_id: \"  xs \\<otimes> [[id]] = xs\"\n by(induction xs)(auto simp add: vec_vec_Tensor_right_id)\n\ntext\\<open>row$\\_$length of tensor product of matrices is the product of \ntheir respective row lengths\\<close>\n\nlemma row_length_mat: \n    \"(row_length (m1\\<otimes>m2)) = (row_length m1)*(row_length m2)\"\nproof(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  row_length_Nil   \n    by auto\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   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\\<open>for every valid matrix can also be written in the following form\\<close>\n\ntheorem matrix_row_length: \n assumes \"mat nr nc M\" \n shows \"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  list.distinct(1) by auto\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  list.distinct(1) \n         by auto\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   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))\"\nproof(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    then 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  list.distinct(1) \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    hence \"mat (length (vec_vec_Tensor v a)) (length (a # M)) [vec_vec_Tensor v a]\"\n      by (simp add: Nil mat_def vec_def)\n    hence\n        \"mat (row_length (a#M) * length v) \n             (length (vec_mat_Tensor v (a#M))) \n             (vec_mat_Tensor v (a#M))\"\n      using 1 4 6 by (simp add: mult.commute)\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  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  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   Cons list.distinct(1) 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 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 by auto  \n    have 5:\"length (vec_vec_Tensor v a) = (length a)*(length v)\" \n           using   vec_vec_Tensor_length by auto  \n    then have 6:\" vec ((length a)*(length v)) (vec_vec_Tensor v a)\" \n           using vec_vec_Tensor_length vec_def by (metis (full_types))\n    have 7:\"(length a) = (row_length (a#M))\" \n           using row_length_def   list.distinct(1) by auto \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_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) 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  by auto\n    have 8: \"length (vec_mat_Tensor v (a#M)) = length (a#M)\" \n           using vec_mat_Tensor_length 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    then show ?thesis by auto\n    qed\n    with  hyp  show ?case by auto  \n qed\n\ntext\\<open>The following theorem  gives length of tensor product of two matrices\\<close>\n\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)\n case Nil\n  show ?thesis using Nil append.simps(1) by auto\n next\n case (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\\<open>The following theorem proves that tensor product of two valid matrices\nis a valid matrix\\<close>\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  list.distinct(1) by auto\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 by auto\n    then show ?thesis by (simp add: mult.commute)\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  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 Cons by auto \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 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\nqed\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)\" \n using nth_append  by metis\n\nlemma append_simpl2: \"i \\<ge>(length xs) \\<longrightarrow> (xs@ys)!i = (ys!(i- (length xs)))\" \n using nth_append less_asym  leD  by metis\n\nlemma append_simpl3: \n assumes \"i > (length y)\"\n shows \" (i <((length (z#zs))*(length y))) \n                  \\<longrightarrow> (i - (length y))< (length zs)*(length y)\"\nproof-\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\" \nproof-\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\"\nproof-\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 less_int_code(1) by auto\n then  have \"(a div b) = ((a - b) div b) + 1\" \n     by auto\n then show ?thesis \n     by auto\nqed\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\"\nproof-\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\nqed\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 mod int n = int (m mod n)\"\n  by (simp add: of_nat_mod)\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:\n assumes \" (y \\<noteq> [])\"\n shows \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\nqed\n\ntext\\<open>a few more results that will be used later on\\<close>\n\nlemma nat_int:  \"nat (int x + int y) = x + y\"\n using 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)))\"  \nproof-\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\nqed\n\n\n\nlemma row_length_eq:\n \"(mat  (row_length (a#b#N))  (length (a#b#N)) (a#b#N)) \n   \\<longrightarrow> \n    (row_length (a#b#N) = (row_length (b#N)))\" \nproof-\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\\<open>The following theorem tells us the relationship between entries of \nvec\\_mat\\_Tensor v M and entries of v and M respectivety\\<close>\n\ntheorem vec_mat_Tensor_elements: \n \"\\<forall>i.\\<forall>j.\n  (((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) \n               = 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 mult.commute \n          by (simp add: mult.commute vec_vec_Tensor_elements)\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 mult.commute by metis\n       have \"(j>0) \\<longrightarrow> ((nat ((int j) + -1)) < (length (b#N))) \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 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))   \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 mult.commute)\n   qed\n from this show ?case by auto\n qed\n\ntext\\<open>The following theorem tells us about the relationship between\nentries of tensor products of two matrices and the entries of matrices\\<close>\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 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 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  mult.commute by metis\n   from this show ?case by (metis mult.commute)\n qed\n   \n\ntext\\<open>we restate the theorem in two different forms for convenience \nof reuse\\<close>\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\\<open>the following lemmas are useful in proving associativity of tensor\nproducts\\<close>\n\nlemma div_left_ineq:\n assumes \"(x::nat) < y*z\" \n shows \" (x div z) < y\"\nproof(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 div_mult_mod_eq \n          add_leD1 assms minus_mod_eq_div_mult [symmetric] le_diff_conv2 mod_less_eq_dividend not_less\n          by metis \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 div_self less_nat_zero_code mult_zero_left \n          mult.commute mod_div_mult_eq\n          by auto\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 mult.commute   by (metis)\n\ntext\\<open>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\\<close>\n\nlemma col_vec_mat_Tensor_prelim:\n \" \\<forall>j.(j < (length M) \n     \\<longrightarrow>\n      col (vec_mat_Tensor v M) j = vec_vec_Tensor v (col M j))\"\n unfolding col_def \n apply(rule allI)\n proof(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\n qed\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\n shows \"\\<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 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  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                   add.commute nat_div neq0_conv div_add_self1 le_add_diff_inverse      \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 mult.commute by metis\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\n qed\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  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) 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 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  row_length_def 2 Nil row_Cons \n                   row_empty times.simps(1) 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 \"2\" Cons_0 Cons_1 local.Cons 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) 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\\<open>The following lemma gives us a formula for the row of a tensor of \ntwo matrices\\<close>\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_in_set list.distinct(1) \n                        rotate1.simps(2) set_rotate1\n                        by auto\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\n qed  \n\nlemma  effective_row_formula:\n fixes M1 and M2\n assumes \"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 shows \"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  using assms row_formula by auto\n\nlemma alt_effective_matrix_tensor_elements:\n \" (((i<((row_length M2)*(row_length M3)))\n \\<and>(j < (length M2)*(length M3)))\n \\<and>(mat (row_length M2) (length M2) M2)\n \\<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)) \n        \\<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 div_mult_mod_eq)  \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_div_decomp by blast\n  then obtain m where \"( ?x = m*c + ?z)\"\n         by auto\n  then have \"(a - m1*(b*c)) = m*c + ?z\"\n        using  \\<open>a mod (b * c) = a - m1 * (b * c)\\<close>   by (metis)\n  then have \"a = m1*b*c + m*c + ?z\"\n        using \\<open>a = m1 * (b * c) + a mod (b * c)\\<close> \\<open>a mod (b * c) \n        = m * c + a mod (b * c) mod c\\<close>\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 mult.commute) \n  let ?y = \"(a mod c)\"\n  have \"\\<exists>n. a = n*(c) + ?y\"\n        by (metis \"1\" \\<open>a mod (b * c) = m * c + a mod (b * c) mod c\\<close> mod_mult_self3)  \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 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        using calculation(2) less_imp_diff_less by blast\n  ultimately have \"?y - ?z = 0\"\n        by (metis dvd_imp_mod_0 mod_less)\n  then show ?thesis using False \n        by (metis \"1\" mod_add_right_eq mod_mult_self2 add.commute mult.commute)\nqed\n\nlemma mod_div_relation:\"((a::nat) mod (b*c)) div c = (a div c) mod b\"\nproof(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       using mod_div_decomp by blast\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       using  div_add1_eq mod_add_self1 mod_add_self2 \n       mod_by_0 mod_div_trivial mod_prop1 mod_self\n       by (metis)\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 nonzero_mult_div_cancel_left mult.commute neq0_conv)\n   have \"\\<exists>y. a div c = (y*b) + ((a div c) mod b)\"\n       by (metis add.commute mod_div_mult_eq)\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 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 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 nonzero_mult_div_cancel_right neq0_conv)\n   then have \"b > (a mod (b*c)) div c\"\n      by (metis calculation div_right_ineq mult.commute)\n   with F_4 F_5 \n    have F_6:\"((a div c) mod b)-((a mod (b*c)) div c) = 0\"\n      using less_imp_diff_less nat_dvd_not_less by blast\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 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  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  nonzero_mult_div_cancel_right neq0_conv)\n   then have \"b > (a mod (b*c)) div c\"\n     by (metis calculation div_right_ineq  mult.commute)\n   with F_7 F_8 \n    have \"((a mod (b*c)) div c) - ((a div c) mod b) = 0\"\n      by (metis F_2 cancel_comm_monoid_add_class.diff_cancel mod_if mod_mult_self3)\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\\<open>The following lemma proves that the tensor product of matrices\nis associative\\<close>\n\nlemma associativity:\n fixes M1 M2 M3\n shows\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>\n           M1 \\<otimes> (M2 \\<otimes> M3) = (M1 \\<otimes> M2) \\<otimes> M3\" (is \"?x \\<Longrightarrow>?l = ?r\")\nproof-\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        using mult.assoc length_Tensor by auto \n   moreover have \" length (M1 \\<otimes> M2) = (length M1)* (length M2)\"\n        by (metis length_Tensor)\n   ultimately  show ?thesis using mult.assoc length_Tensor by auto\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 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 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 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 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.((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 \"\\<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: \n       \"\\<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 \n            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 mult.assoc \n            by (simp add: length_Tensor row_length_mat  semigroup_mult_class.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 by metis \n  ultimately show ?thesis using row_length_mat length_Tensor by (metis mult.assoc)\n qed\n ultimately show ?thesis using mat_eqI by blast\nqed     \n  \nend\n\nlemma \" \\<And>(a::nat) b.(times  a  b) =(times  b  a)\"\n by auto\n\nsubsection\\<open>Associativity and Distributive properties\\<close>\n\nlocale plus_mult = \n mult + \n fixes zer::\"'a\"\n fixes g::\" 'a \\<Rightarrow> 'a \\<Rightarrow> 'a \" (infixl \"+\" 60)\n fixes inver::\"'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 (inver x)) = zer\"\n assumes plus_right_inverse: \"(g (inver x) x) = zer\"\n \n\ncontext plus_mult\nbegin\n\nlemma fixes M1 M2 M3\n      shows \"(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\\<open>matrix$\\_$mult refers to multiplication of matrices in the locale \nplus\\_mult\\<close>\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:\n assumes \"mat nr1 nc1 M\" and \"mat nr2 nc2 M\" and \"M \\<noteq> []\"\n shows \"nr1 = nr2\" and \"nc1 = nc2\"\nproof(cases M)\n case Nil\n  show \"nr1 = nr2\" using assms(3) Nil by auto\n next\n case (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\n next\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: \n assumes \"m1 \\<noteq> []\"\n  and  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\\<open>the following definition checks if the given four matrices\n are such that the compositions in the mixed-product property which\n will be proved, hold true. It further checks that the matrices are \n non empty and valid\\<close>\n\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:\n 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> []\"\nproof-\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 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:\n assumes 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))\"\nproof-\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\"\n shows\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\"\n shows\n  \"(\\<forall>i <((row_length M1)*(row_length M2)).\n    \\<forall>j < ((length M1)*(length M2))\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\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\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> [])\" \n   and \"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 \\<open>length A2 * length B2 = length (A1 \\<circ> A2 \\<otimes> B1 \\<circ> B2)\\<close> \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 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 blast\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 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 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 blast\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> [])\"    \n         and 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 by auto\n\n\nlemma zip_Nil:\"zip [] [] = []\"\n using zip_def by auto\n\nlemma zer_left_mult:\"f zer x = zer\"\nproof-\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) + (inver (f zer x)) = (f zer x) + (f zer x) + (inver (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 by auto\n    with Cons_3 Cons_4 Cons_5 show ?thesis using assoc by auto\n   qed\n   then show ?case by auto\n qed\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\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 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 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 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    then show ?thesis \n          using Cons_6 Cons_7 \\<open>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)\\<close> \n          by (metis Cons_3 Cons_4 )\n   qed\n   then show ?case by auto\n qed\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)\"\nproof(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:\n fixes A1 A2 B1 B2 i j\n assumes 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    and i:\"i<(row_length A1)*(row_length B1)\" and j:\"j< (length A2)*(length B2)\"\n shows \"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))) \n           \\<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))\" \nproof- \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:\n    \"\\<forall>i j. ((i<(row_length A1)*(row_length B1))\\<and>(j<(length A2)*(length B2))) \n     \\<longrightarrow>\n      (((A1 \\<circ> A2)\\<otimes>(B1 \\<circ>  B2))!j!i \n                = (scalar_product \n                    (row A1 (i div (row_length B1))) (col A2  (j div (length B2))))\n                   *(scalar_product \n                      (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))) \n                           = 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))) \n                             = 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_eqI by blast\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 using application wf1 wf2 wf3 by blast\n \n\ntext\\<open>The following theorem gives us the distributivity relation of tensor\nproduct with matrix multiplication\\<close>\n\ntheorem distributivity: \n assumes  \"matrix_match A1 A2 B1 B2\"\n shows \"((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 \n          using application by blast\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/Matrix_Tensor/Matrix_Tensor.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8289388083214156, "lm_q2_score": 0.8459424353665382, "lm_q1q2_score": 0.7012345142812544}}
{"text": "(*\n  File:     Quick_Sort_Average_Case.thy\n  Author:   Manuel Eberl <manuel@pruvisto.org>\n\n  Definition and average-case analysis of the standard deterministic QuickSort algorithm\n*)\nsection \\<open>Average case analysis of deterministic QuickSort\\<close>\ntheory Quick_Sort_Average_Case\n  imports Randomised_Quick_Sort\nbegin\n  \nsubsection \\<open>Definition of deterministic QuickSort\\<close>\n  \ntext \\<open>\n  This is the functional description of the standard variant of deterministic QuickSort that \n  always chooses the first list element as the pivot as given by Hoare in 1962~\\<^cite>\\<open>\"hoare\"\\<close>. \n  For a list that is already sorted, this leads to $n(n-1)$ \n  comparisons, but as is well known, the average case is not that bad.\n\\<close>\nfun quicksort :: \"('a \\<times> 'a) set \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where\n  \"quicksort _ [] = []\"\n| \"quicksort R (x # xs) = \n     quicksort R (filter (\\<lambda>y. (y,x) \\<in> R) xs) @ [x] @ quicksort R (filter (\\<lambda>y. (y,x) \\<notin> R) xs)\"\n\ntext \\<open>\n  We can easily show that this QuickSort is correct:\n\\<close>\ntheorem mset_quicksort [simp]: \"mset (quicksort R xs) = mset xs\"\n  by (induction R xs rule: quicksort.induct) (simp_all)\n\ncorollary set_quicksort [simp]: \"set (quicksort R xs) = set xs\"\n  by (induction R xs rule: quicksort.induct) auto\n\ntheorem sorted_wrt_quicksort: \n  assumes \"trans R\" and \"total_on (set xs) R\" and \"\\<And>x. x \\<in> set xs \\<Longrightarrow> (x, x) \\<in> R\"\n  shows   \"sorted_wrt R (quicksort R xs)\"\nusing assms\nproof (induction R xs rule: quicksort.induct)\n  case (2 R x xs)\n  have total: \"(a, b) \\<in> R\" if \"(b, a) \\<notin> R\" \"a \\<in> set (x#xs)\" \"b \\<in> set (x#xs)\" for a b\n    using \"2.prems\" that unfolding total_on_def by (cases \"a = b\") auto\n    \n  have *: \"sorted_wrt R (quicksort R (filter (\\<lambda>y. (y,x) \\<in> R) xs))\"\n          \"sorted_wrt R (quicksort R (filter (\\<lambda>y. (y,x) \\<notin> R) xs))\"\n    by ((rule 2 total_on_subset[OF \\<open>total_on (set (x#xs)) R\\<close>]) | force)+\n  show ?case\n    by (auto intro!: sorted_wrt_append sorted_wrt.intros \\<open>trans R\\<close> * \n             intro: transD[OF \\<open>trans R\\<close>] dest!: total simp: total_on_def)\nqed auto\n\ncorollary sorted_wrt_quicksort':\n  assumes \"linorder_on A R\" and \"set xs \\<subseteq> A\"\n  shows   \"sorted_wrt R (quicksort R xs)\"\n  by (rule sorted_wrt_quicksort)\n     (insert assms, auto simp: linorder_on_def refl_on_def dest: total_on_subset)\n\ntext \\<open>\n  We now define another version of QuickSort that is identical to the previous one but also \n  counts the number of comparisons that were made.\n\\<close>\nfun quicksort' :: \"('a \\<times> 'a) set \\<Rightarrow> 'a list \\<Rightarrow> 'a list \\<times> nat\" where\n  \"quicksort' _ [] = ([], 0)\"\n| \"quicksort' R (x # xs) = (\n     let (ls, rs)  = partition (\\<lambda>y. (y,x) \\<in> R) xs;\n         (ls', n1) = quicksort' R ls;\n         (rs', n2) = quicksort' R rs\n     in\n         (ls' @ [x] @ rs', length xs + n1 + n2))\"\n\ntext \\<open>\n  For convenience, we also define a function that computes only the number of comparisons that \n  were made and not the result list.\n\\<close>\nfun qs_cost :: \"('a \\<times> 'a) set \\<Rightarrow> 'a list \\<Rightarrow> nat\" where\n  \"qs_cost _ [] = 0\"\n| \"qs_cost R (x # xs) = \n     length xs + qs_cost R (filter (\\<lambda>y. (y,x)\\<in>R) xs) + qs_cost R (filter (\\<lambda>y. (y,x)\\<notin>R) xs)\"\n\n\ntext \\<open>\n  It is obvious that the original QuickSort and the cost function are the projections \n  of the cost-counting QuickSort.\n\\<close>  \nlemma fst_quicksort' [simp]: \"fst (quicksort' R xs) = quicksort R xs\"\n  by (induction R xs rule: quicksort.induct) (simp_all add: case_prod_unfold Let_def o_def)\n\nlemma snd_quicksort' [simp]: \"snd (quicksort' R xs) = qs_cost R xs\"\n  by (induction R xs rule: quicksort.induct) (simp_all add: case_prod_unfold Let_def o_def)\n\n    \nsubsection \\<open>Analysis\\<close>\n\ntext \\<open>\n  We will reduce the average-case analysis to showing that it is essentially equivalent to \n  the randomised QuickSort we analysed earlier. Similar, but more direct analyses are given \n  by Hoare~\\<^cite>\\<open>\"hoare\"\\<close> and Sedgewick~\\<^cite>\\<open>\"sedgewick\"\\<close>. \n\n  The proof is relatively straightforward -- but still a bit messy. We show that the cost \n  distribution of QuickSort run on a random permutation of a set of size $n$ is exactly the same \n  as that of randomised QuickSort being run on any fixed list of size $n$ (which we analysed \n  before):  \n\\<close>\ntheorem qs_cost_average_conv_rqs_cost:\n  assumes \"finite A\" and \"linorder_on B R\" and \"A \\<subseteq> B\"\n  shows   \"map_pmf (qs_cost R) (pmf_of_set (permutations_of_set A)) = rqs_cost (card A)\"\nusing assms(1,3)\nproof (induction A rule: finite_psubset_induct)\n  case (psubset A)\n  show ?case\n  proof (cases \"A = {}\")\n    case True\n    thus ?thesis by (simp add: pmf_of_set_singleton)\n  next\n    case False\n    note A = \\<open>finite A\\<close> \\<open>A \\<noteq> {}\\<close>\n    define n where \"n = card A - 1\"\n    from A have \"pmf_of_set (permutations_of_set A) = \n      do {x \\<leftarrow> pmf_of_set A; xs \\<leftarrow> pmf_of_set (permutations_of_set (A - {x})); return_pmf (x#xs)}\"\n      by (rule random_permutation_of_set)\n    also have \"map_pmf (qs_cost R) \\<dots> =\n                 do {\n                   x \\<leftarrow> pmf_of_set A;\n                   xs \\<leftarrow> pmf_of_set (permutations_of_set (A - {x}));\n                   return_pmf (length xs + qs_cost R [y\\<leftarrow>xs. (y,x)\\<in>R] + qs_cost R [y\\<leftarrow>xs. (y,x)\\<notin>R])\n                 }\" by (simp add: map_bind_pmf)\n    also have \"\\<dots> = map_pmf (\\<lambda>m. n + m) (\n          do {\n            x \\<leftarrow> pmf_of_set A;\n            xs \\<leftarrow> pmf_of_set (permutations_of_set (A - {x}));\n            return_pmf (qs_cost R [y\\<leftarrow>xs. (y,x)\\<in>R] + qs_cost R [y\\<leftarrow>xs. (y,x)\\<notin>R])\n          })\" (is \"_ = map_pmf _ ?X\") using A unfolding n_def map_bind_pmf\n      by (intro bind_pmf_cong map_pmf_cong refl) (auto simp: length_finite_permutations_of_set)\n    also have \"?X = do {\n                      x \\<leftarrow> pmf_of_set A;\n                      (ls,rs) \\<leftarrow> map_pmf (partition (\\<lambda>y. (y,x)\\<in>R)) \n                                   (pmf_of_set (permutations_of_set (A - {x})));\n                      return_pmf (qs_cost R ls + qs_cost R rs)\n                    }\" by (simp add: bind_map_pmf o_def)\n    also have \"\\<dots> = do {\n                      x \\<leftarrow> pmf_of_set A;\n                      (n1, n2) \\<leftarrow> pair_pmf \n                        (rqs_cost (linorder_rank R A x)) (rqs_cost (n - linorder_rank R A x));\n                      return_pmf (n1 + n2)}\"\n    proof (intro bind_pmf_cong refl, goal_cases)\n      case (1 x)\n      have \"map_pmf (partition (\\<lambda>y. (y,x)\\<in>R)) (pmf_of_set (permutations_of_set (A - {x})))\n              \\<bind> (\\<lambda>(ls, rs). return_pmf (qs_cost R ls + qs_cost R rs)) = \n            map_pmf (\\<lambda>(n1, n2). n1 + n2) (pair_pmf\n              (map_pmf (qs_cost R) (pmf_of_set (permutations_of_set {xa \\<in> A - {x}. (xa, x) \\<in> R})))\n              (map_pmf (qs_cost R) (pmf_of_set (permutations_of_set {xa \\<in> A - {x}. (xa, x) \\<notin> R}))))\"\n        (is \"_ = map_pmf _ (pair_pmf ?X ?Y)\")\n        by (subst partition_random_permutations)\n           (simp_all add: map_pmf_def case_prod_unfold bind_return_pmf bind_assoc_pmf pair_pmf_def A)\n      also {\n        have \"{xa \\<in> A - {x}. (xa, x) \\<in> R} \\<subseteq> A - {x}\" by blast\n        also have \"\\<dots> \\<subset> A\" using 1 A by auto\n        finally have subset: \"{xa \\<in> A - {x}. (xa, x) \\<in> R} \\<subset> A\" .\n        also have \"\\<dots> \\<subseteq> B\" by fact\n        finally have \"?X = rqs_cost (card {xa \\<in> A - {x}. (xa, x) \\<in> R})\" using subset\n          by (intro psubset.IH) auto\n        also have \"card {xa \\<in> A - {x}. (xa, x) \\<in> R} = linorder_rank R A x\"\n          by (simp add: linorder_rank_def)\n        finally have \"?X = rqs_cost \\<dots>\" .\n      }\n      also {\n        have \"{xa \\<in> A - {x}. (xa, x) \\<notin> R} \\<subseteq> A - {x}\" by blast\n        also have \"\\<dots> \\<subset> A\" using 1 A by auto\n        finally have subset: \"{xa \\<in> A - {x}. (xa, x) \\<notin> R} \\<subset> A\" .\n        also have \"\\<dots> \\<subseteq> B\" by fact\n        finally have \"?Y = rqs_cost (card {xa \\<in> A - {x}. (xa, x) \\<notin> R})\" using subset\n          by (intro psubset.IH) auto\n        also {\n          have \"card ({y\\<in>A-{x}. (y,x)\\<in>R} \\<union> {y\\<in>A-{x}. (y,x)\\<notin>R}) = \n                  linorder_rank R A x + card {xa \\<in> A - {x}. (xa, x) \\<notin> R}\"\n            unfolding linorder_rank_def using A by (intro card_Un_disjoint) auto\n          also have \"{y\\<in>A-{x}. (y,x)\\<in>R} \\<union> {y\\<in>A-{x}. (y,x)\\<notin>R} = A - {x}\" by blast\n          also have \"card \\<dots> = n\" using A 1 by (simp add: n_def)\n          finally have \"card {xa \\<in> A - {x}. (xa, x) \\<notin> R} = n - linorder_rank R A x\" by simp\n        }\n        finally have \"?Y = rqs_cost (n - linorder_rank R A x)\" .\n      }\n      finally show ?case by (simp add: case_prod_unfold map_pmf_def)\n    qed\n    also have \"\\<dots> = do {\n                      i \\<leftarrow> map_pmf (linorder_rank R A) (pmf_of_set A);\n                      (n1, n2) \\<leftarrow> pair_pmf (rqs_cost i) (rqs_cost (n - i));\n                      return_pmf (n1 + n2)\n                    }\" by (simp add: bind_map_pmf)\n    also have \"map_pmf (linorder_rank R A) (pmf_of_set A) = pmf_of_set {..<card A}\"\n      by (intro map_pmf_of_set_bij_betw bij_betw_linorder_rank[OF assms(2)] A psubset.prems)\n    also from A have \"card A > 0\" by (intro Nat.gr0I) auto\n    hence \"{..<card A} = {..n}\" by (auto simp: n_def)\n    also have \"map_pmf (\\<lambda>m. n + m) (\n                 do {\n                      i \\<leftarrow> pmf_of_set {..n};\n                      (n1, n2) \\<leftarrow> pair_pmf (rqs_cost i) (rqs_cost (n - i));\n                      return_pmf (n1 + n2)\n                    }) = rqs_cost (Suc n)\"\n      by (simp add: pair_pmf_def map_bind_pmf case_prod_unfold\n                    bind_assoc_pmf bind_return_pmf add_ac)\n    also from A have \"card A > 0\" by (intro Nat.gr0I) auto\n    hence \"Suc n = card A\" by (simp add: n_def)\n    finally show ?thesis .\n  qed\nqed\n\ntext \\<open>\n  We therefore have the same expectation as well. (Note that we showed \n  @{thm rqs_cost_exp_eq [no_vars]} and @{thm rqs_cost_exp_asymp_equiv [no_vars]} before.\n\\<close>\ncorollary expectation_qs_cost: \n  assumes \"finite A\" and \"linorder_on B R\" and \"A \\<subseteq> B\"\n  defines \"random_list \\<equiv> pmf_of_set (permutations_of_set A)\"\n  shows   \"measure_pmf.expectation (map_pmf (qs_cost R) random_list) real = \n             rqs_cost_exp (card A)\"\n  unfolding random_list_def\n  by (subst qs_cost_average_conv_rqs_cost[OF assms(1-3)]) (simp add: expectation_rqs_cost)\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/Quick_Sort_Cost/Quick_Sort_Average_Case.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.8840392817460333, "lm_q1q2_score": 0.7011368154333069}}
{"text": "theory ExF004\nimports Main \nbegin \n\n\n  \ntheorem \"(\\<forall>x. \\<exists>y. P x y) \\<or> (\\<exists>x. \\<forall>y. \\<not>P x y)\" \nproof - \n  {\n    assume a:\"\\<not>((\\<forall>x. \\<exists>y. P x y) \\<or> (\\<exists>x. \\<forall>y. \\<not>P x y) )\"\n    {\n      assume \"\\<forall>x. \\<exists>y. P x y\"\n      hence \"(\\<forall>x. \\<exists>y. P x y) \\<or> (\\<exists>x. \\<forall>y. \\<not>P x y)\" ..\n      with a have False ..\n    }\n    hence  b:\"\\<not>(\\<forall>x. \\<exists>y. P x y)\" by (rule notI)\n    {\n      assume c:\"\\<not>(\\<exists>x. \\<forall>y. \\<not>P x y)\"\n      {\n        fix aa\n        {\n          assume d:\"\\<not>(\\<exists>y. P aa y)\"    \n          {\n            fix bb \n            {\n              assume \"P aa bb\"\n              hence \"\\<exists>y. P aa y\" by (rule exI)\n              with d have False by contradiction\n            }\n            hence \"\\<not>P aa bb\" by (rule notI)\n          }\n          hence \"\\<forall>y. \\<not>P aa y\" by (rule allI)\n          hence \"\\<exists>x. \\<forall>y. \\<not>P x y\" by (rule exI)\n          with c have False by contradiction\n        }\n        hence \"\\<not>\\<not>(\\<exists>y. P aa y)\" by (rule notI)\n        hence \"\\<exists>y. P aa y\" by (rule notnotD)\n      }\n      hence \"\\<forall>x. \\<exists>y. P x y\" by (rule allI)\n      with b have False by contradiction\n    }\n    hence \"\\<not>\\<not>(\\<exists>x. \\<forall>y. \\<not>P x y)\" by (rule notI)\n    hence \"\\<exists>x. \\<forall>y. \\<not>P x y\" by (rule notnotD)\n    hence \"(\\<forall>x. \\<exists>y. P x y) \\<or> (\\<exists>x. \\<forall>y. \\<not>P x y)\"  by (rule disjI2)\n    with a have False by contradiction\n  }\n  hence \"\\<not>\\<not>((\\<forall>x. \\<exists>y. P x y) \\<or> (\\<exists>x. \\<forall>y. \\<not>P x y))\" by (rule notI)\n  thus ?thesis by (rule notnotD)\nqed\n  \n      \n      \n          \n      \n          \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/FOL/ExF004.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206686206199, "lm_q2_score": 0.7772998611746912, "lm_q1q2_score": 0.7010628105093926}}
{"text": "(*  Title:      HOL/Computational_Algebra/Factorial_Ring.thy\n    Author:     Manuel Eberl, TU Muenchen\n    Author:     Florian Haftmann, TU Muenchen\n*)\n\nsection \\<open>Factorial (semi)rings\\<close>\n\ntheory Factorial_Ring\nimports\n  Main\n  \"HOL-Library.Multiset\"\nbegin\n\nsubsection \\<open>Irreducible and prime elements\\<close>\n\ncontext comm_semiring_1\nbegin\n\ndefinition irreducible :: \"'a \\<Rightarrow> bool\" where\n  \"irreducible p \\<longleftrightarrow> p \\<noteq> 0 \\<and> \\<not>p dvd 1 \\<and> (\\<forall>a b. p = a * b \\<longrightarrow> a dvd 1 \\<or> b dvd 1)\"\n\nlemma not_irreducible_zero [simp]: \"\\<not>irreducible 0\"\n  by (simp add: irreducible_def)\n\nlemma irreducible_not_unit: \"irreducible p \\<Longrightarrow> \\<not>p dvd 1\"\n  by (simp add: irreducible_def)\n\nlemma not_irreducible_one [simp]: \"\\<not>irreducible 1\"\n  by (simp add: irreducible_def)\n\nlemma irreducibleI:\n  \"p \\<noteq> 0 \\<Longrightarrow> \\<not>p dvd 1 \\<Longrightarrow> (\\<And>a b. p = a * b \\<Longrightarrow> a dvd 1 \\<or> b dvd 1) \\<Longrightarrow> irreducible p\"\n  by (simp add: irreducible_def)\n\nlemma irreducibleD: \"irreducible p \\<Longrightarrow> p = a * b \\<Longrightarrow> a dvd 1 \\<or> b dvd 1\"\n  by (simp add: irreducible_def)\n\nlemma irreducible_mono:\n  assumes irr: \"irreducible b\" and \"a dvd b\" \"\\<not>a dvd 1\"\n  shows   \"irreducible a\"\nproof (rule irreducibleI)\n  fix c d assume \"a = c * d\"\n  from assms obtain k where [simp]: \"b = a * k\" by auto\n  from \\<open>a = c * d\\<close> have \"b = c * d * k\"\n    by simp\n  hence \"c dvd 1 \\<or> (d * k) dvd 1\"\n    using irreducibleD[OF irr, of c \"d * k\"] by (auto simp: mult.assoc)\n  thus \"c dvd 1 \\<or> d dvd 1\"\n    by auto\nqed (use assms in \\<open>auto simp: irreducible_def\\<close>)\n\ndefinition prime_elem :: \"'a \\<Rightarrow> bool\" where\n  \"prime_elem p \\<longleftrightarrow> p \\<noteq> 0 \\<and> \\<not>p dvd 1 \\<and> (\\<forall>a b. p dvd (a * b) \\<longrightarrow> p dvd a \\<or> p dvd b)\"\n\nlemma not_prime_elem_zero [simp]: \"\\<not>prime_elem 0\"\n  by (simp add: prime_elem_def)\n\nlemma prime_elem_not_unit: \"prime_elem p \\<Longrightarrow> \\<not>p dvd 1\"\n  by (simp add: prime_elem_def)\n\nlemma prime_elemI:\n    \"p \\<noteq> 0 \\<Longrightarrow> \\<not>p dvd 1 \\<Longrightarrow> (\\<And>a b. p dvd (a * b) \\<Longrightarrow> p dvd a \\<or> p dvd b) \\<Longrightarrow> prime_elem p\"\n  by (simp add: prime_elem_def)\n\nlemma prime_elem_dvd_multD:\n    \"prime_elem p \\<Longrightarrow> p dvd (a * b) \\<Longrightarrow> p dvd a \\<or> p dvd b\"\n  by (simp add: prime_elem_def)\n\nlemma prime_elem_dvd_mult_iff:\n  \"prime_elem p \\<Longrightarrow> p dvd (a * b) \\<longleftrightarrow> p dvd a \\<or> p dvd b\"\n  by (auto simp: prime_elem_def)\n\nlemma not_prime_elem_one [simp]:\n  \"\\<not> prime_elem 1\"\n  by (auto dest: prime_elem_not_unit)\n\nlemma prime_elem_not_zeroI:\n  assumes \"prime_elem p\"\n  shows \"p \\<noteq> 0\"\n  using assms by (auto intro: ccontr)\n\nlemma prime_elem_dvd_power:\n  \"prime_elem p \\<Longrightarrow> p dvd x ^ n \\<Longrightarrow> p dvd x\"\n  by (induction n) (auto dest: prime_elem_dvd_multD intro: dvd_trans[of _ 1])\n\nlemma prime_elem_dvd_power_iff:\n  \"prime_elem p \\<Longrightarrow> n > 0 \\<Longrightarrow> p dvd x ^ n \\<longleftrightarrow> p dvd x\"\n  by (auto dest: prime_elem_dvd_power intro: dvd_trans)\n\nlemma prime_elem_imp_nonzero [simp]:\n  \"ASSUMPTION (prime_elem x) \\<Longrightarrow> x \\<noteq> 0\"\n  unfolding ASSUMPTION_def by (rule prime_elem_not_zeroI)\n\nlemma prime_elem_imp_not_one [simp]:\n  \"ASSUMPTION (prime_elem x) \\<Longrightarrow> x \\<noteq> 1\"\n  unfolding ASSUMPTION_def by auto\n\nend\n\n\nlemma (in normalization_semidom) irreducible_cong:\n  assumes \"normalize a = normalize b\"\n  shows   \"irreducible a \\<longleftrightarrow> irreducible b\"\nproof (cases \"a = 0 \\<or> a dvd 1\")\n  case True\n  hence \"\\<not>irreducible a\" by (auto simp: irreducible_def)\n  from True have \"normalize a = 0 \\<or> normalize a dvd 1\"\n    by auto\n  also note assms\n  finally have \"b = 0 \\<or> b dvd 1\" by simp\n  hence \"\\<not>irreducible b\" by (auto simp: irreducible_def)\n  with \\<open>\\<not>irreducible a\\<close> show ?thesis by simp\nnext\n  case False\n  hence b: \"b \\<noteq> 0\" \"\\<not>is_unit b\" using assms\n    by (auto simp: is_unit_normalize[of b])\n  show ?thesis\n  proof\n    assume \"irreducible a\"\n    thus \"irreducible b\"\n      by (rule irreducible_mono) (use assms False b in \\<open>auto dest: associatedD2\\<close>)\n  next\n    assume \"irreducible b\"\n    thus \"irreducible a\"\n      by (rule irreducible_mono) (use assms False b in \\<open>auto dest: associatedD1\\<close>)\n  qed\nqed\n\nlemma (in normalization_semidom) associatedE1:\n  assumes \"normalize a = normalize b\"\n  obtains u where \"is_unit u\" \"a = u * b\"\nproof (cases \"a = 0\")\n  case [simp]: False\n  from assms have [simp]: \"b \\<noteq> 0\" by auto\n  show ?thesis\n  proof (rule that)\n    show \"is_unit (unit_factor a div unit_factor b)\"\n      by auto\n    have \"unit_factor a div unit_factor b * b = unit_factor a * (b div unit_factor b)\"\n      using \\<open>b \\<noteq> 0\\<close> unit_div_commute unit_div_mult_swap unit_factor_is_unit by metis\n    also have \"b div unit_factor b = normalize b\" by simp\n    finally show \"a = unit_factor a div unit_factor b * b\"\n      by (metis assms unit_factor_mult_normalize)\n  qed\nnext\n  case [simp]: True\n  hence [simp]: \"b = 0\"\n    using assms[symmetric] by auto\n  show ?thesis\n    by (intro that[of 1]) auto\nqed\n\nlemma (in normalization_semidom) associatedE2:\n  assumes \"normalize a = normalize b\"\n  obtains u where \"is_unit u\" \"b = u * a\"\nproof -\n  from assms have \"normalize b = normalize a\"\n    by simp\n  then obtain u where \"is_unit u\" \"b = u * a\"\n    by (elim associatedE1)\n  thus ?thesis using that by blast\nqed\n  \n\n(* TODO Move *)\nlemma (in normalization_semidom) normalize_power_normalize:\n  \"normalize (normalize x ^ n) = normalize (x ^ n)\"\nproof (induction n)\n  case (Suc n)\n  have \"normalize (normalize x ^ Suc n) = normalize (x * normalize (normalize x ^ n))\"\n    by simp\n  also note Suc.IH\n  finally show ?case by simp\nqed auto\n\ncontext algebraic_semidom\nbegin\n\nlemma prime_elem_imp_irreducible:\n  assumes \"prime_elem p\"\n  shows   \"irreducible p\"\nproof (rule irreducibleI)\n  fix a b\n  assume p_eq: \"p = a * b\"\n  with assms have nz: \"a \\<noteq> 0\" \"b \\<noteq> 0\" by auto\n  from p_eq have \"p dvd a * b\" by simp\n  with \\<open>prime_elem p\\<close> have \"p dvd a \\<or> p dvd b\" by (rule prime_elem_dvd_multD)\n  with \\<open>p = a * b\\<close> have \"a * b dvd 1 * b \\<or> a * b dvd a * 1\" by auto\n  thus \"a dvd 1 \\<or> b dvd 1\"\n    by (simp only: dvd_times_left_cancel_iff[OF nz(1)] dvd_times_right_cancel_iff[OF nz(2)])\nqed (insert assms, simp_all add: prime_elem_def)\n\nlemma (in algebraic_semidom) unit_imp_no_irreducible_divisors:\n  assumes \"is_unit x\" \"irreducible p\"\n  shows   \"\\<not>p dvd x\"\nproof (rule notI)\n  assume \"p dvd x\"\n  with \\<open>is_unit x\\<close> have \"is_unit p\"\n    by (auto intro: dvd_trans)\n  with \\<open>irreducible p\\<close> show False\n    by (simp add: irreducible_not_unit)\nqed\n\nlemma unit_imp_no_prime_divisors:\n  assumes \"is_unit x\" \"prime_elem p\"\n  shows   \"\\<not>p dvd x\"\n  using unit_imp_no_irreducible_divisors[OF assms(1) prime_elem_imp_irreducible[OF assms(2)]] .\n\nlemma prime_elem_mono:\n  assumes \"prime_elem p\" \"\\<not>q dvd 1\" \"q dvd p\"\n  shows   \"prime_elem q\"\nproof -\n  from \\<open>q dvd p\\<close> obtain r where r: \"p = q * r\" by (elim dvdE)\n  hence \"p dvd q * r\" by simp\n  with \\<open>prime_elem p\\<close> have \"p dvd q \\<or> p dvd r\" by (rule prime_elem_dvd_multD)\n  hence \"p dvd q\"\n  proof\n    assume \"p dvd r\"\n    then obtain s where s: \"r = p * s\" by (elim dvdE)\n    from r have \"p * 1 = p * (q * s)\" by (subst (asm) s) (simp add: mult_ac)\n    with \\<open>prime_elem p\\<close> have \"q dvd 1\"\n      by (subst (asm) mult_cancel_left) auto\n    with \\<open>\\<not>q dvd 1\\<close> show ?thesis by contradiction\n  qed\n\n  show ?thesis\n  proof (rule prime_elemI)\n    fix a b assume \"q dvd (a * b)\"\n    with \\<open>p dvd q\\<close> have \"p dvd (a * b)\" by (rule dvd_trans)\n    with \\<open>prime_elem p\\<close> have \"p dvd a \\<or> p dvd b\" by (rule prime_elem_dvd_multD)\n    with \\<open>q dvd p\\<close> show \"q dvd a \\<or> q dvd b\" by (blast intro: dvd_trans)\n  qed (insert assms, auto)\nqed\n\nlemma irreducibleD':\n  assumes \"irreducible a\" \"b dvd a\"\n  shows   \"a dvd b \\<or> is_unit b\"\nproof -\n  from assms obtain c where c: \"a = b * c\" by (elim dvdE)\n  from irreducibleD[OF assms(1) this] have \"is_unit b \\<or> is_unit c\" .\n  thus ?thesis by (auto simp: c mult_unit_dvd_iff)\nqed\n\nlemma irreducibleI':\n  assumes \"a \\<noteq> 0\" \"\\<not>is_unit a\" \"\\<And>b. b dvd a \\<Longrightarrow> a dvd b \\<or> is_unit b\"\n  shows   \"irreducible a\"\nproof (rule irreducibleI)\n  fix b c assume a_eq: \"a = b * c\"\n  hence \"a dvd b \\<or> is_unit b\" by (intro assms) simp_all\n  thus \"is_unit b \\<or> is_unit c\"\n  proof\n    assume \"a dvd b\"\n    hence \"b * c dvd b * 1\" by (simp add: a_eq)\n    moreover from \\<open>a \\<noteq> 0\\<close> a_eq have \"b \\<noteq> 0\" by auto\n    ultimately show ?thesis by (subst (asm) dvd_times_left_cancel_iff) auto\n  qed blast\nqed (simp_all add: assms(1,2))\n\nlemma irreducible_altdef:\n  \"irreducible x \\<longleftrightarrow> x \\<noteq> 0 \\<and> \\<not>is_unit x \\<and> (\\<forall>b. b dvd x \\<longrightarrow> x dvd b \\<or> is_unit b)\"\n  using irreducibleI'[of x] irreducibleD'[of x] irreducible_not_unit[of x] by auto\n\nlemma prime_elem_multD:\n  assumes \"prime_elem (a * b)\"\n  shows \"is_unit a \\<or> is_unit b\"\nproof -\n  from assms have \"a \\<noteq> 0\" \"b \\<noteq> 0\" by (auto dest!: prime_elem_not_zeroI)\n  moreover from assms prime_elem_dvd_multD [of \"a * b\"] have \"a * b dvd a \\<or> a * b dvd b\"\n    by auto\n  ultimately show ?thesis\n    using dvd_times_left_cancel_iff [of a b 1]\n      dvd_times_right_cancel_iff [of b a 1]\n    by auto\nqed\n\nlemma prime_elemD2:\n  assumes \"prime_elem p\" and \"a dvd p\" and \"\\<not> is_unit a\"\n  shows \"p dvd a\"\nproof -\n  from \\<open>a dvd p\\<close> obtain b where \"p = a * b\" ..\n  with \\<open>prime_elem p\\<close> prime_elem_multD \\<open>\\<not> is_unit a\\<close> have \"is_unit b\" by auto\n  with \\<open>p = a * b\\<close> show ?thesis\n    by (auto simp add: mult_unit_dvd_iff)\nqed\n\nlemma prime_elem_dvd_prod_msetE:\n  assumes \"prime_elem p\"\n  assumes dvd: \"p dvd prod_mset A\"\n  obtains a where \"a \\<in># A\" and \"p dvd a\"\nproof -\n  from dvd have \"\\<exists>a. a \\<in># A \\<and> p dvd a\"\n  proof (induct A)\n    case empty then show ?case\n    using \\<open>prime_elem p\\<close> by (simp add: prime_elem_not_unit)\n  next\n    case (add a A)\n    then have \"p dvd a * prod_mset A\" by simp\n    with \\<open>prime_elem p\\<close> consider (A) \"p dvd prod_mset A\" | (B) \"p dvd a\"\n      by (blast dest: prime_elem_dvd_multD)\n    then show ?case proof cases\n      case B then show ?thesis by auto\n    next\n      case A\n      with add.hyps obtain b where \"b \\<in># A\" \"p dvd b\"\n        by auto\n      then show ?thesis by auto\n    qed\n  qed\n  with that show thesis by blast\n\nqed\n\ncontext\nbegin\n\nlemma prime_elem_powerD:\n  assumes \"prime_elem (p ^ n)\"\n  shows   \"prime_elem p \\<and> n = 1\"\nproof (cases n)\n  case (Suc m)\n  note assms\n  also from Suc have \"p ^ n = p * p^m\" by simp\n  finally have \"is_unit p \\<or> is_unit (p^m)\" by (rule prime_elem_multD)\n  moreover from assms have \"\\<not>is_unit p\" by (simp add: prime_elem_def is_unit_power_iff)\n  ultimately have \"is_unit (p ^ m)\" by simp\n  with \\<open>\\<not>is_unit p\\<close> have \"m = 0\" by (simp add: is_unit_power_iff)\n  with Suc assms show ?thesis by simp\nqed (insert assms, simp_all)\n\nlemma prime_elem_power_iff:\n  \"prime_elem (p ^ n) \\<longleftrightarrow> prime_elem p \\<and> n = 1\"\n  by (auto dest: prime_elem_powerD)\n\nend\n\nlemma irreducible_mult_unit_left:\n  \"is_unit a \\<Longrightarrow> irreducible (a * p) \\<longleftrightarrow> irreducible p\"\n  by (auto simp: irreducible_altdef mult.commute[of a] is_unit_mult_iff\n        mult_unit_dvd_iff dvd_mult_unit_iff)\n\nlemma prime_elem_mult_unit_left:\n  \"is_unit a \\<Longrightarrow> prime_elem (a * p) \\<longleftrightarrow> prime_elem p\"\n  by (auto simp: prime_elem_def mult.commute[of a] is_unit_mult_iff mult_unit_dvd_iff)\n\nlemma prime_elem_dvd_cases:\n  assumes pk: \"p*k dvd m*n\" and p: \"prime_elem p\"\n  shows \"(\\<exists>x. k dvd x*n \\<and> m = p*x) \\<or> (\\<exists>y. k dvd m*y \\<and> n = p*y)\"\nproof -\n  have \"p dvd m*n\" using dvd_mult_left pk by blast\n  then consider \"p dvd m\" | \"p dvd n\"\n    using p prime_elem_dvd_mult_iff by blast\n  then show ?thesis\n  proof cases\n    case 1 then obtain a where \"m = p * a\" by (metis dvd_mult_div_cancel)\n      then have \"\\<exists>x. k dvd x * n \\<and> m = p * x\"\n        using p pk by (auto simp: mult.assoc)\n    then show ?thesis ..\n  next\n    case 2 then obtain b where \"n = p * b\" by (metis dvd_mult_div_cancel)\n    with p pk have \"\\<exists>y. k dvd m*y \\<and> n = p*y\"\n      by (metis dvd_mult_right dvd_times_left_cancel_iff mult.left_commute mult_zero_left)\n    then show ?thesis ..\n  qed\nqed\n\nlemma prime_elem_power_dvd_prod:\n  assumes pc: \"p^c dvd m*n\" and p: \"prime_elem p\"\n  shows \"\\<exists>a b. a+b = c \\<and> p^a dvd m \\<and> p^b dvd n\"\nusing pc\nproof (induct c arbitrary: m n)\n  case 0 show ?case by simp\nnext\n  case (Suc c)\n  consider x where \"p^c dvd x*n\" \"m = p*x\" | y where \"p^c dvd m*y\" \"n = p*y\"\n    using prime_elem_dvd_cases [of _ \"p^c\", OF _ p] Suc.prems by force\n  then show ?case\n  proof cases\n    case (1 x)\n    with Suc.hyps[of x n] obtain a b where \"a + b = c \\<and> p ^ a dvd x \\<and> p ^ b dvd n\" by blast\n    with 1 have \"Suc a + b = Suc c \\<and> p ^ Suc a dvd m \\<and> p ^ b dvd n\"\n      by (auto intro: mult_dvd_mono)\n    thus ?thesis by blast\n  next\n    case (2 y)\n    with Suc.hyps[of m y] obtain a b where \"a + b = c \\<and> p ^ a dvd m \\<and> p ^ b dvd y\" by blast\n    with 2 have \"a + Suc b = Suc c \\<and> p ^ a dvd m \\<and> p ^ Suc b dvd n\"\n      by (auto intro: mult_dvd_mono)\n    with Suc.hyps [of m y] show \"\\<exists>a b. a + b = Suc c \\<and> p ^ a dvd m \\<and> p ^ b dvd n\"\n      by blast\n  qed\nqed\n\nlemma prime_elem_power_dvd_cases:\n  assumes \"p ^ c dvd m * n\" and \"a + b = Suc c\" and \"prime_elem p\"\n  shows \"p ^ a dvd m \\<or> p ^ b dvd n\"\nproof -\n  from assms obtain r s\n    where \"r + s = c \\<and> p ^ r dvd m \\<and> p ^ s dvd n\"\n    by (blast dest: prime_elem_power_dvd_prod)\n  moreover with assms have\n    \"a \\<le> r \\<or> b \\<le> s\" by arith\n  ultimately show ?thesis by (auto intro: power_le_dvd)\nqed\n\nlemma prime_elem_not_unit' [simp]:\n  \"ASSUMPTION (prime_elem x) \\<Longrightarrow> \\<not>is_unit x\"\n  unfolding ASSUMPTION_def by (rule prime_elem_not_unit)\n\nlemma prime_elem_dvd_power_iff:\n  assumes \"prime_elem p\"\n  shows \"p dvd a ^ n \\<longleftrightarrow> p dvd a \\<and> n > 0\"\n  using assms by (induct n) (auto dest: prime_elem_not_unit prime_elem_dvd_multD)\n\nlemma prime_power_dvd_multD:\n  assumes \"prime_elem p\"\n  assumes \"p ^ n dvd a * b\" and \"n > 0\" and \"\\<not> p dvd a\"\n  shows \"p ^ n dvd b\"\n  using \\<open>p ^ n dvd a * b\\<close> and \\<open>n > 0\\<close>\nproof (induct n arbitrary: b)\n  case 0 then show ?case by simp\nnext\n  case (Suc n) show ?case\n  proof (cases \"n = 0\")\n    case True with Suc \\<open>prime_elem p\\<close> \\<open>\\<not> p dvd a\\<close> show ?thesis\n      by (simp add: prime_elem_dvd_mult_iff)\n  next\n    case False then have \"n > 0\" by simp\n    from \\<open>prime_elem p\\<close> have \"p \\<noteq> 0\" by auto\n    from Suc.prems have *: \"p * p ^ n dvd a * b\"\n      by simp\n    then have \"p dvd a * b\"\n      by (rule dvd_mult_left)\n    with Suc \\<open>prime_elem p\\<close> \\<open>\\<not> p dvd a\\<close> have \"p dvd b\"\n      by (simp add: prime_elem_dvd_mult_iff)\n    moreover define c where \"c = b div p\"\n    ultimately have b: \"b = p * c\" by simp\n    with * have \"p * p ^ n dvd p * (a * c)\"\n      by (simp add: ac_simps)\n    with \\<open>p \\<noteq> 0\\<close> have \"p ^ n dvd a * c\"\n      by simp\n    with Suc.hyps \\<open>n > 0\\<close> have \"p ^ n dvd c\"\n      by blast\n    with \\<open>p \\<noteq> 0\\<close> show ?thesis\n      by (simp add: b)\n  qed\nqed\n\nend\n\n\nsubsection \\<open>Generalized primes: normalized prime elements\\<close>\n\ncontext normalization_semidom\nbegin\n\nlemma irreducible_normalized_divisors:\n  assumes \"irreducible x\" \"y dvd x\" \"normalize y = y\"\n  shows   \"y = 1 \\<or> y = normalize x\"\nproof -\n  from assms have \"is_unit y \\<or> x dvd y\" by (auto simp: irreducible_altdef)\n  thus ?thesis\n  proof (elim disjE)\n    assume \"is_unit y\"\n    hence \"normalize y = 1\" by (simp add: is_unit_normalize)\n    with assms show ?thesis by simp\n  next\n    assume \"x dvd y\"\n    with \\<open>y dvd x\\<close> have \"normalize y = normalize x\" by (rule associatedI)\n    with assms show ?thesis by simp\n  qed\nqed\n\nlemma irreducible_normalize_iff [simp]: \"irreducible (normalize x) = irreducible x\"\n  using irreducible_mult_unit_left[of \"1 div unit_factor x\" x]\n  by (cases \"x = 0\") (simp_all add: unit_div_commute)\n\nlemma prime_elem_normalize_iff [simp]: \"prime_elem (normalize x) = prime_elem x\"\n  using prime_elem_mult_unit_left[of \"1 div unit_factor x\" x]\n  by (cases \"x = 0\") (simp_all add: unit_div_commute)\n\nlemma prime_elem_associated:\n  assumes \"prime_elem p\" and \"prime_elem q\" and \"q dvd p\"\n  shows \"normalize q = normalize p\"\nusing \\<open>q dvd p\\<close> proof (rule associatedI)\n  from \\<open>prime_elem q\\<close> have \"\\<not> is_unit q\"\n    by (auto simp add: prime_elem_not_unit)\n  with \\<open>prime_elem p\\<close> \\<open>q dvd p\\<close> show \"p dvd q\"\n    by (blast intro: prime_elemD2)\nqed\n\ndefinition prime :: \"'a \\<Rightarrow> bool\" where\n  \"prime p \\<longleftrightarrow> prime_elem p \\<and> normalize p = p\"\n\nlemma not_prime_0 [simp]: \"\\<not>prime 0\" by (simp add: prime_def)\n\nlemma not_prime_unit: \"is_unit x \\<Longrightarrow> \\<not>prime x\"\n  using prime_elem_not_unit[of x] by (auto simp add: prime_def)\n\nlemma not_prime_1 [simp]: \"\\<not>prime 1\" by (simp add: not_prime_unit)\n\nlemma primeI: \"prime_elem x \\<Longrightarrow> normalize x = x \\<Longrightarrow> prime x\"\n  by (simp add: prime_def)\n\nlemma prime_imp_prime_elem [dest]: \"prime p \\<Longrightarrow> prime_elem p\"\n  by (simp add: prime_def)\n\nlemma normalize_prime: \"prime p \\<Longrightarrow> normalize p = p\"\n  by (simp add: prime_def)\n\nlemma prime_normalize_iff [simp]: \"prime (normalize p) \\<longleftrightarrow> prime_elem p\"\n  by (auto simp add: prime_def)\n\nlemma prime_power_iff:\n  \"prime (p ^ n) \\<longleftrightarrow> prime p \\<and> n = 1\"\n  by (auto simp: prime_def prime_elem_power_iff)\n\nlemma prime_imp_nonzero [simp]:\n  \"ASSUMPTION (prime x) \\<Longrightarrow> x \\<noteq> 0\"\n  unfolding ASSUMPTION_def prime_def by auto\n\nlemma prime_imp_not_one [simp]:\n  \"ASSUMPTION (prime x) \\<Longrightarrow> x \\<noteq> 1\"\n  unfolding ASSUMPTION_def by auto\n\nlemma prime_not_unit' [simp]:\n  \"ASSUMPTION (prime x) \\<Longrightarrow> \\<not>is_unit x\"\n  unfolding ASSUMPTION_def prime_def by auto\n\nlemma prime_normalize' [simp]: \"ASSUMPTION (prime x) \\<Longrightarrow> normalize x = x\"\n  unfolding ASSUMPTION_def prime_def by simp\n\nlemma unit_factor_prime: \"prime x \\<Longrightarrow> unit_factor x = 1\"\n  using unit_factor_normalize[of x] unfolding prime_def by auto\n\nlemma unit_factor_prime' [simp]: \"ASSUMPTION (prime x) \\<Longrightarrow> unit_factor x = 1\"\n  unfolding ASSUMPTION_def by (rule unit_factor_prime)\n\nlemma prime_imp_prime_elem' [simp]: \"ASSUMPTION (prime x) \\<Longrightarrow> prime_elem x\"\n  by (simp add: prime_def ASSUMPTION_def)\n\nlemma prime_dvd_multD: \"prime p \\<Longrightarrow> p dvd a * b \\<Longrightarrow> p dvd a \\<or> p dvd b\"\n  by (intro prime_elem_dvd_multD) simp_all\n\nlemma prime_dvd_mult_iff: \"prime p \\<Longrightarrow> p dvd a * b \\<longleftrightarrow> p dvd a \\<or> p dvd b\"\n  by (auto dest: prime_dvd_multD)\n\nlemma prime_dvd_power:\n  \"prime p \\<Longrightarrow> p dvd x ^ n \\<Longrightarrow> p dvd x\"\n  by (auto dest!: prime_elem_dvd_power simp: prime_def)\n\nlemma prime_dvd_power_iff:\n  \"prime p \\<Longrightarrow> n > 0 \\<Longrightarrow> p dvd x ^ n \\<longleftrightarrow> p dvd x\"\n  by (subst prime_elem_dvd_power_iff) simp_all\n\nlemma prime_dvd_prod_mset_iff: \"prime p \\<Longrightarrow> p dvd prod_mset A \\<longleftrightarrow> (\\<exists>x. x \\<in># A \\<and> p dvd x)\"\n  by (induction A) (simp_all add: prime_elem_dvd_mult_iff prime_imp_prime_elem, blast+)\n\nlemma prime_dvd_prod_iff: \"finite A \\<Longrightarrow> prime p \\<Longrightarrow> p dvd prod f A \\<longleftrightarrow> (\\<exists>x\\<in>A. p dvd f x)\"\n  by (auto simp: prime_dvd_prod_mset_iff prod_unfold_prod_mset)\n\nlemma primes_dvd_imp_eq:\n  assumes \"prime p\" \"prime q\" \"p dvd q\"\n  shows   \"p = q\"\nproof -\n  from assms have \"irreducible q\" by (simp add: prime_elem_imp_irreducible prime_def)\n  from irreducibleD'[OF this \\<open>p dvd q\\<close>] assms have \"q dvd p\" by simp\n  with \\<open>p dvd q\\<close> have \"normalize p = normalize q\" by (rule associatedI)\n  with assms show \"p = q\" by simp\nqed\n\nlemma prime_dvd_prod_mset_primes_iff:\n  assumes \"prime p\" \"\\<And>q. q \\<in># A \\<Longrightarrow> prime q\"\n  shows   \"p dvd prod_mset A \\<longleftrightarrow> p \\<in># A\"\nproof -\n  from assms(1) have \"p dvd prod_mset A \\<longleftrightarrow> (\\<exists>x. x \\<in># A \\<and> p dvd x)\" by (rule prime_dvd_prod_mset_iff)\n  also from assms have \"\\<dots> \\<longleftrightarrow> p \\<in># A\" by (auto dest: primes_dvd_imp_eq)\n  finally show ?thesis .\nqed\n\nlemma prod_mset_primes_dvd_imp_subset:\n  assumes \"prod_mset A dvd prod_mset B\" \"\\<And>p. p \\<in># A \\<Longrightarrow> prime p\" \"\\<And>p. p \\<in># B \\<Longrightarrow> prime p\"\n  shows   \"A \\<subseteq># B\"\nusing assms\nproof (induction A arbitrary: B)\n  case empty\n  thus ?case by simp\nnext\n  case (add p A B)\n  hence p: \"prime p\" by simp\n  define B' where \"B' = B - {#p#}\"\n  from add.prems have \"p dvd prod_mset B\" by (simp add: dvd_mult_left)\n  with add.prems have \"p \\<in># B\"\n    by (subst (asm) (2) prime_dvd_prod_mset_primes_iff) simp_all\n  hence B: \"B = B' + {#p#}\" by (simp add: B'_def)\n  from add.prems p have \"A \\<subseteq># B'\" by (intro add.IH) (simp_all add: B)\n  thus ?case by (simp add: B)\nqed\n\nlemma prod_mset_dvd_prod_mset_primes_iff:\n  assumes \"\\<And>x. x \\<in># A \\<Longrightarrow> prime x\" \"\\<And>x. x \\<in># B \\<Longrightarrow> prime x\"\n  shows   \"prod_mset A dvd prod_mset B \\<longleftrightarrow> A \\<subseteq># B\"\n  using assms by (auto intro: prod_mset_subset_imp_dvd prod_mset_primes_dvd_imp_subset)\n\nlemma is_unit_prod_mset_primes_iff:\n  assumes \"\\<And>x. x \\<in># A \\<Longrightarrow> prime x\"\n  shows   \"is_unit (prod_mset A) \\<longleftrightarrow> A = {#}\"\n  by (auto simp add: is_unit_prod_mset_iff)\n    (meson all_not_in_conv assms not_prime_unit set_mset_eq_empty_iff)\n\nlemma prod_mset_primes_irreducible_imp_prime:\n  assumes irred: \"irreducible (prod_mset A)\"\n  assumes A: \"\\<And>x. x \\<in># A \\<Longrightarrow> prime x\"\n  assumes B: \"\\<And>x. x \\<in># B \\<Longrightarrow> prime x\"\n  assumes C: \"\\<And>x. x \\<in># C \\<Longrightarrow> prime x\"\n  assumes dvd: \"prod_mset A dvd prod_mset B * prod_mset C\"\n  shows   \"prod_mset A dvd prod_mset B \\<or> prod_mset A dvd prod_mset C\"\nproof -\n  from dvd have \"prod_mset A dvd prod_mset (B + C)\"\n    by simp\n  with A B C have subset: \"A \\<subseteq># B + C\"\n    by (subst (asm) prod_mset_dvd_prod_mset_primes_iff) auto\n  define A1 and A2 where \"A1 = A \\<inter># B\" and \"A2 = A - A1\"\n  have \"A = A1 + A2\" unfolding A1_def A2_def\n    by (rule sym, intro subset_mset.add_diff_inverse) simp_all\n  from subset have \"A1 \\<subseteq># B\" \"A2 \\<subseteq># C\"\n    by (auto simp: A1_def A2_def Multiset.subset_eq_diff_conv Multiset.union_commute)\n  from \\<open>A = A1 + A2\\<close> have \"prod_mset A = prod_mset A1 * prod_mset A2\" by simp\n  from irred and this have \"is_unit (prod_mset A1) \\<or> is_unit (prod_mset A2)\"\n    by (rule irreducibleD)\n  with A have \"A1 = {#} \\<or> A2 = {#}\" unfolding A1_def A2_def\n    by (subst (asm) (1 2) is_unit_prod_mset_primes_iff) (auto dest: Multiset.in_diffD)\n  with dvd \\<open>A = A1 + A2\\<close> \\<open>A1 \\<subseteq># B\\<close> \\<open>A2 \\<subseteq># C\\<close> show ?thesis\n    by (auto intro: prod_mset_subset_imp_dvd)\nqed\n\nlemma prod_mset_primes_finite_divisor_powers:\n  assumes A: \"\\<And>x. x \\<in># A \\<Longrightarrow> prime x\"\n  assumes B: \"\\<And>x. x \\<in># B \\<Longrightarrow> prime x\"\n  assumes \"A \\<noteq> {#}\"\n  shows   \"finite {n. prod_mset A ^ n dvd prod_mset B}\"\nproof -\n  from \\<open>A \\<noteq> {#}\\<close> obtain x where x: \"x \\<in># A\" by blast\n  define m where \"m = count B x\"\n  have \"{n. prod_mset A ^ n dvd prod_mset B} \\<subseteq> {..m}\"\n  proof safe\n    fix n assume dvd: \"prod_mset A ^ n dvd prod_mset B\"\n    from x have \"x ^ n dvd prod_mset A ^ n\" by (intro dvd_power_same dvd_prod_mset)\n    also note dvd\n    also have \"x ^ n = prod_mset (replicate_mset n x)\" by simp\n    finally have \"replicate_mset n x \\<subseteq># B\"\n      by (rule prod_mset_primes_dvd_imp_subset) (insert A B x, simp_all split: if_splits)\n    thus \"n \\<le> m\" by (simp add: count_le_replicate_mset_subset_eq m_def)\n  qed\n  moreover have \"finite {..m}\" by simp\n  ultimately show ?thesis by (rule finite_subset)\nqed\n\nend\n\n\nsubsection \\<open>In a semiring with GCD, each irreducible element is a prime element\\<close>\n\ncontext semiring_gcd\nbegin\n\nlemma irreducible_imp_prime_elem_gcd:\n  assumes \"irreducible x\"\n  shows   \"prime_elem x\"\nproof (rule prime_elemI)\n  fix a b assume \"x dvd a * b\"\n  from dvd_productE[OF this] obtain y z where yz: \"x = y * z\" \"y dvd a\" \"z dvd b\" .\n  from \\<open>irreducible x\\<close> and \\<open>x = y * z\\<close> have \"is_unit y \\<or> is_unit z\" by (rule irreducibleD)\n  with yz show \"x dvd a \\<or> x dvd b\"\n    by (auto simp: mult_unit_dvd_iff mult_unit_dvd_iff')\nqed (insert assms, auto simp: irreducible_not_unit)\n\nlemma prime_elem_imp_coprime:\n  assumes \"prime_elem p\" \"\\<not>p dvd n\"\n  shows   \"coprime p n\"\nproof (rule coprimeI)\n  fix d assume \"d dvd p\" \"d dvd n\"\n  show \"is_unit d\"\n  proof (rule ccontr)\n    assume \"\\<not>is_unit d\"\n    from \\<open>prime_elem p\\<close> and \\<open>d dvd p\\<close> and this have \"p dvd d\"\n      by (rule prime_elemD2)\n    from this and \\<open>d dvd n\\<close> have \"p dvd n\" by (rule dvd_trans)\n    with \\<open>\\<not>p dvd n\\<close> show False by contradiction\n  qed\nqed\n\nlemma prime_imp_coprime:\n  assumes \"prime p\" \"\\<not>p dvd n\"\n  shows   \"coprime p n\"\n  using assms by (simp add: prime_elem_imp_coprime)\n\nlemma prime_elem_imp_power_coprime:\n  \"prime_elem p \\<Longrightarrow> \\<not> p dvd a \\<Longrightarrow> coprime a (p ^ m)\"\n  by (cases \"m > 0\") (auto dest: prime_elem_imp_coprime simp add: ac_simps)\n\nlemma prime_imp_power_coprime:\n  \"prime p \\<Longrightarrow> \\<not> p dvd a \\<Longrightarrow> coprime a (p ^ m)\"\n  by (rule prime_elem_imp_power_coprime) simp_all\n\nlemma prime_elem_divprod_pow:\n  assumes p: \"prime_elem p\" and ab: \"coprime a b\" and pab: \"p^n dvd a * b\"\n  shows   \"p^n dvd a \\<or> p^n dvd b\"\n  using assms\nproof -\n  from p have \"\\<not> is_unit p\"\n    by simp\n  with ab p have \"\\<not> p dvd a \\<or> \\<not> p dvd b\"\n    using not_coprimeI by blast\n  with p have \"coprime (p ^ n) a \\<or> coprime (p ^ n) b\"\n    by (auto dest: prime_elem_imp_power_coprime simp add: ac_simps)\n  with pab show ?thesis\n    by (auto simp add: coprime_dvd_mult_left_iff coprime_dvd_mult_right_iff)\nqed\n\nlemma primes_coprime:\n  \"prime p \\<Longrightarrow> prime q \\<Longrightarrow> p \\<noteq> q \\<Longrightarrow> coprime p q\"\n  using prime_imp_coprime primes_dvd_imp_eq by blast\n\nend\n\n\nsubsection \\<open>Factorial semirings: algebraic structures with unique prime factorizations\\<close>\n\nclass factorial_semiring = normalization_semidom +\n  assumes prime_factorization_exists:\n    \"x \\<noteq> 0 \\<Longrightarrow> \\<exists>A. (\\<forall>x. x \\<in># A \\<longrightarrow> prime_elem x) \\<and> normalize (prod_mset A) = normalize x\"\n\ntext \\<open>Alternative characterization\\<close>\n\nlemma (in normalization_semidom) factorial_semiring_altI_aux:\n  assumes finite_divisors: \"\\<And>x. x \\<noteq> 0 \\<Longrightarrow> finite {y. y dvd x \\<and> normalize y = y}\"\n  assumes irreducible_imp_prime_elem: \"\\<And>x. irreducible x \\<Longrightarrow> prime_elem x\"\n  assumes \"x \\<noteq> 0\"\n  shows   \"\\<exists>A. (\\<forall>x. x \\<in># A \\<longrightarrow> prime_elem x) \\<and> normalize (prod_mset A) = normalize x\"\nusing \\<open>x \\<noteq> 0\\<close>\nproof (induction \"card {b. b dvd x \\<and> normalize b = b}\" arbitrary: x rule: less_induct)\n  case (less a)\n  let ?fctrs = \"\\<lambda>a. {b. b dvd a \\<and> normalize b = b}\"\n  show ?case\n  proof (cases \"is_unit a\")\n    case True\n    thus ?thesis by (intro exI[of _ \"{#}\"]) (auto simp: is_unit_normalize)\n  next\n    case False\n    show ?thesis\n    proof (cases \"\\<exists>b. b dvd a \\<and> \\<not>is_unit b \\<and> \\<not>a dvd b\")\n      case False\n      with \\<open>\\<not>is_unit a\\<close> less.prems have \"irreducible a\" by (auto simp: irreducible_altdef)\n      hence \"prime_elem a\" by (rule irreducible_imp_prime_elem)\n      thus ?thesis by (intro exI[of _ \"{#normalize a#}\"]) auto\n    next\n      case True\n      then obtain b where b: \"b dvd a\" \"\\<not> is_unit b\" \"\\<not> a dvd b\" by auto\n      from b have \"?fctrs b \\<subseteq> ?fctrs a\" by (auto intro: dvd_trans)\n      moreover from b have \"normalize a \\<notin> ?fctrs b\" \"normalize a \\<in> ?fctrs a\" by simp_all\n      hence \"?fctrs b \\<noteq> ?fctrs a\" by blast\n      ultimately have \"?fctrs b \\<subset> ?fctrs a\" by (subst subset_not_subset_eq) blast\n      with finite_divisors[OF \\<open>a \\<noteq> 0\\<close>] have \"card (?fctrs b) < card (?fctrs a)\"\n        by (rule psubset_card_mono)\n      moreover from \\<open>a \\<noteq> 0\\<close> b have \"b \\<noteq> 0\" by auto\n      ultimately have \"\\<exists>A. (\\<forall>x. x \\<in># A \\<longrightarrow> prime_elem x) \\<and> normalize (prod_mset A) = normalize b\"\n        by (intro less) auto\n      then obtain A where A: \"(\\<forall>x. x \\<in># A \\<longrightarrow> prime_elem x) \\<and> normalize (\\<Prod>\\<^sub># A) = normalize b\"\n        by auto\n\n      define c where \"c = a div b\"\n      from b have c: \"a = b * c\" by (simp add: c_def)\n      from less.prems c have \"c \\<noteq> 0\" by auto\n      from b c have \"?fctrs c \\<subseteq> ?fctrs a\" by (auto intro: dvd_trans)\n      moreover have \"normalize a \\<notin> ?fctrs c\"\n      proof safe\n        assume \"normalize a dvd c\"\n        hence \"b * c dvd 1 * c\" by (simp add: c)\n        hence \"b dvd 1\" by (subst (asm) dvd_times_right_cancel_iff) fact+\n        with b show False by simp\n      qed\n      with \\<open>normalize a \\<in> ?fctrs a\\<close> have \"?fctrs a \\<noteq> ?fctrs c\" by blast\n      ultimately have \"?fctrs c \\<subset> ?fctrs a\" by (subst subset_not_subset_eq) blast\n      with finite_divisors[OF \\<open>a \\<noteq> 0\\<close>] have \"card (?fctrs c) < card (?fctrs a)\"\n        by (rule psubset_card_mono)\n      with \\<open>c \\<noteq> 0\\<close> have \"\\<exists>A. (\\<forall>x. x \\<in># A \\<longrightarrow> prime_elem x) \\<and> normalize (prod_mset A) = normalize c\"\n        by (intro less) auto\n      then obtain B where B: \"(\\<forall>x. x \\<in># B \\<longrightarrow> prime_elem x) \\<and> normalize (\\<Prod>\\<^sub># B) = normalize c\"\n        by auto\n\n      show ?thesis\n      proof (rule exI[of _ \"A + B\"]; safe)\n        have \"normalize (prod_mset (A + B)) =\n                normalize (normalize (prod_mset A) * normalize (prod_mset B))\"\n          by simp\n        also have \"\\<dots> = normalize (b * c)\"\n          by (simp only: A B) auto\n        also have \"b * c = a\"\n          using c by simp\n        finally show \"normalize (prod_mset (A + B)) = normalize a\" .\n      next\n      qed (use A B in auto)\n    qed\n  qed\nqed\n\nlemma factorial_semiring_altI:\n  assumes finite_divisors: \"\\<And>x::'a. x \\<noteq> 0 \\<Longrightarrow> finite {y. y dvd x \\<and> normalize y = y}\"\n  assumes irreducible_imp_prime: \"\\<And>x::'a. irreducible x \\<Longrightarrow> prime_elem x\"\n  shows   \"OFCLASS('a :: normalization_semidom, factorial_semiring_class)\"\n  by intro_classes (rule factorial_semiring_altI_aux[OF assms])\n\ntext \\<open>Properties\\<close>\n\ncontext factorial_semiring\nbegin\n\nlemma prime_factorization_exists':\n  assumes \"x \\<noteq> 0\"\n  obtains A where \"\\<And>x. x \\<in># A \\<Longrightarrow> prime x\" \"normalize (prod_mset A) = normalize x\"\nproof -\n  from prime_factorization_exists[OF assms] obtain A\n    where A: \"\\<And>x. x \\<in># A \\<Longrightarrow> prime_elem x\" \"normalize (prod_mset A) = normalize x\" by blast\n  define A' where \"A' = image_mset normalize A\"\n  have \"normalize (prod_mset A') = normalize (prod_mset A)\"\n    by (simp add: A'_def normalize_prod_mset_normalize)\n  also note A(2)\n  finally have \"normalize (prod_mset A') = normalize x\" by simp\n  moreover from A(1) have \"\\<forall>x. x \\<in># A' \\<longrightarrow> prime x\" by (auto simp: prime_def A'_def)\n  ultimately show ?thesis by (intro that[of A']) blast\nqed\n\nlemma irreducible_imp_prime_elem:\n  assumes \"irreducible x\"\n  shows   \"prime_elem x\"\nproof (rule prime_elemI)\n  fix a b assume dvd: \"x dvd a * b\"\n  from assms have \"x \\<noteq> 0\" by auto\n  show \"x dvd a \\<or> x dvd b\"\n  proof (cases \"a = 0 \\<or> b = 0\")\n    case False\n    hence \"a \\<noteq> 0\" \"b \\<noteq> 0\" by blast+\n    note nz = \\<open>x \\<noteq> 0\\<close> this\n    from nz[THEN prime_factorization_exists'] obtain A B C\n      where ABC:\n        \"\\<And>z. z \\<in># A \\<Longrightarrow> prime z\"\n        \"normalize (\\<Prod>\\<^sub># A) = normalize x\"\n        \"\\<And>z. z \\<in># B \\<Longrightarrow> prime z\"\n        \"normalize (\\<Prod>\\<^sub># B) = normalize a\"\n        \"\\<And>z. z \\<in># C \\<Longrightarrow> prime z\"\n        \"normalize (\\<Prod>\\<^sub># C) = normalize b\"\n      by this blast\n\n    have \"irreducible (prod_mset A)\"\n      by (subst irreducible_cong[OF ABC(2)]) fact\n    moreover have \"normalize (prod_mset A) dvd\n                     normalize (normalize (prod_mset B) * normalize (prod_mset C))\"\n      unfolding ABC using dvd by simp\n    hence \"prod_mset A dvd prod_mset B * prod_mset C\"\n      unfolding normalize_mult_normalize_left normalize_mult_normalize_right by simp\n    ultimately have \"prod_mset A dvd prod_mset B \\<or> prod_mset A dvd prod_mset C\"\n      by (intro prod_mset_primes_irreducible_imp_prime) (use ABC in auto)\n    hence \"normalize (prod_mset A) dvd normalize (prod_mset B) \\<or>\n           normalize (prod_mset A) dvd normalize (prod_mset C)\" by simp\n    thus ?thesis unfolding ABC by simp\n  qed auto\nqed (use assms in \\<open>simp_all add: irreducible_def\\<close>)\n\nlemma finite_divisor_powers:\n  assumes \"y \\<noteq> 0\" \"\\<not>is_unit x\"\n  shows   \"finite {n. x ^ n dvd y}\"\nproof (cases \"x = 0\")\n  case True\n  with assms have \"{n. x ^ n dvd y} = {0}\" by (auto simp: power_0_left)\n  thus ?thesis by simp\nnext\n  case False\n  note nz = this \\<open>y \\<noteq> 0\\<close>\n  from nz[THEN prime_factorization_exists'] obtain A B\n    where AB:\n      \"\\<And>z. z \\<in># A \\<Longrightarrow> prime z\"\n      \"normalize (\\<Prod>\\<^sub># A) = normalize x\"\n      \"\\<And>z. z \\<in># B \\<Longrightarrow> prime z\"\n      \"normalize (\\<Prod>\\<^sub># B) = normalize y\"\n    by this blast\n\n  from AB assms have \"A \\<noteq> {#}\" by (auto simp: normalize_1_iff)\n  from AB(2,4) prod_mset_primes_finite_divisor_powers [of A B, OF AB(1,3) this]\n    have \"finite {n. prod_mset A ^ n dvd prod_mset B}\" by simp\n  also have \"{n. prod_mset A ^ n dvd prod_mset B} =\n             {n. normalize (normalize (prod_mset A) ^ n) dvd normalize (prod_mset B)}\"\n    unfolding normalize_power_normalize by simp\n  also have \"\\<dots> = {n. x ^ n dvd y}\"\n    unfolding AB unfolding normalize_power_normalize by simp\n  finally show ?thesis .\nqed\n\nlemma finite_prime_divisors:\n  assumes \"x \\<noteq> 0\"\n  shows   \"finite {p. prime p \\<and> p dvd x}\"\nproof -\n  from prime_factorization_exists'[OF assms] obtain A\n    where A: \"\\<And>z. z \\<in># A \\<Longrightarrow> prime z\" \"normalize (\\<Prod>\\<^sub># A) = normalize x\" by this blast\n  have \"{p. prime p \\<and> p dvd x} \\<subseteq> set_mset A\"\n  proof safe\n    fix p assume p: \"prime p\" and dvd: \"p dvd x\"\n    from dvd have \"p dvd normalize x\" by simp\n    also from A have \"normalize x = normalize (prod_mset A)\" by simp\n    finally have \"p dvd prod_mset A\"\n      by simp\n    thus  \"p \\<in># A\" using p A\n      by (subst (asm) prime_dvd_prod_mset_primes_iff)\n  qed\n  moreover have \"finite (set_mset A)\" by simp\n  ultimately show ?thesis by (rule finite_subset)\nqed\n\nlemma infinite_unit_divisor_powers:\n assumes \"y \\<noteq> 0\"\n assumes \"is_unit x\"\n shows \"infinite {n. x^n dvd y}\"\nproof -\n from \\<open>is_unit x\\<close> have \"is_unit (x^n)\" for n\n   using is_unit_power_iff by auto\n hence \"x^n dvd y\" for n\n   by auto\n hence \"{n. x^n dvd y} = UNIV\"\n   by auto\n thus ?thesis\n   by auto\nqed\n\ncorollary is_unit_iff_infinite_divisor_powers:\n assumes \"y \\<noteq> 0\"\n shows \"is_unit x \\<longleftrightarrow> infinite {n. x^n dvd y}\"\n using infinite_unit_divisor_powers finite_divisor_powers assms by auto\n\nlemma prime_elem_iff_irreducible: \"prime_elem x \\<longleftrightarrow> irreducible x\"\n  by (blast intro: irreducible_imp_prime_elem prime_elem_imp_irreducible)\n\nlemma prime_divisor_exists:\n  assumes \"a \\<noteq> 0\" \"\\<not>is_unit a\"\n  shows   \"\\<exists>b. b dvd a \\<and> prime b\"\nproof -\n  from prime_factorization_exists'[OF assms(1)]\n  obtain A where A: \"\\<And>z. z \\<in># A \\<Longrightarrow> prime z\" \"normalize (\\<Prod>\\<^sub># A) = normalize a\"\n    by this blast\n  with assms have \"A \\<noteq> {#}\" by auto\n  then obtain x where \"x \\<in># A\" by blast\n  with A(1) have *: \"x dvd normalize (prod_mset A)\" \"prime x\"\n    by (auto simp: dvd_prod_mset)\n  hence \"x dvd a\" by (simp add: A(2))\n  with * show ?thesis by blast\nqed\n\nlemma prime_divisors_induct [case_names zero unit factor]:\n  assumes \"P 0\" \"\\<And>x. is_unit x \\<Longrightarrow> P x\" \"\\<And>p x. prime p \\<Longrightarrow> P x \\<Longrightarrow> P (p * x)\"\n  shows   \"P x\"\nproof (cases \"x = 0\")\n  case False\n  from prime_factorization_exists'[OF this]\n  obtain A where A: \"\\<And>z. z \\<in># A \\<Longrightarrow> prime z\" \"normalize (\\<Prod>\\<^sub># A) = normalize x\"\n    by this blast\n  from A obtain u where u: \"is_unit u\" \"x = u * prod_mset A\"\n    by (elim associatedE2)\n\n  from A(1) have \"P (u * prod_mset A)\"\n  proof (induction A)\n    case (add p A)\n    from add.prems have \"prime p\" by simp\n    moreover from add.prems have \"P (u * prod_mset A)\" by (intro add.IH) simp_all\n    ultimately have \"P (p * (u * prod_mset A))\" by (rule assms(3))\n    thus ?case by (simp add: mult_ac)\n  qed (simp_all add: assms False u)\n  with A u show ?thesis by simp\nqed (simp_all add: assms(1))\n\nlemma no_prime_divisors_imp_unit:\n  assumes \"a \\<noteq> 0\" \"\\<And>b. b dvd a \\<Longrightarrow> normalize b = b \\<Longrightarrow> \\<not> prime_elem b\"\n  shows \"is_unit a\"\nproof (rule ccontr)\n  assume \"\\<not>is_unit a\"\n  from prime_divisor_exists[OF assms(1) this] obtain b where \"b dvd a\" \"prime b\" by auto\n  with assms(2)[of b] show False by (simp add: prime_def)\nqed\n\nlemma prime_divisorE:\n  assumes \"a \\<noteq> 0\" and \"\\<not> is_unit a\"\n  obtains p where \"prime p\" and \"p dvd a\"\n  using assms no_prime_divisors_imp_unit unfolding prime_def by blast\n\ndefinition multiplicity :: \"'a \\<Rightarrow> 'a \\<Rightarrow> nat\" where\n  \"multiplicity p x = (if finite {n. p ^ n dvd x} then Max {n. p ^ n dvd x} else 0)\"\n\nlemma multiplicity_dvd: \"p ^ multiplicity p x dvd x\"\nproof (cases \"finite {n. p ^ n dvd x}\")\n  case True\n  hence \"multiplicity p x = Max {n. p ^ n dvd x}\"\n    by (simp add: multiplicity_def)\n  also have \"\\<dots> \\<in> {n. p ^ n dvd x}\"\n    by (rule Max_in) (auto intro!: True exI[of _ \"0::nat\"])\n  finally show ?thesis by simp\nqed (simp add: multiplicity_def)\n\nlemma multiplicity_dvd': \"n \\<le> multiplicity p x \\<Longrightarrow> p ^ n dvd x\"\n  by (rule dvd_trans[OF le_imp_power_dvd multiplicity_dvd])\n\ncontext\n  fixes x p :: 'a\n  assumes xp: \"x \\<noteq> 0\" \"\\<not>is_unit p\"\nbegin\n\nlemma multiplicity_eq_Max: \"multiplicity p x = Max {n. p ^ n dvd x}\"\n  using finite_divisor_powers[OF xp] by (simp add: multiplicity_def)\n\nlemma multiplicity_geI:\n  assumes \"p ^ n dvd x\"\n  shows   \"multiplicity p x \\<ge> n\"\nproof -\n  from assms have \"n \\<le> Max {n. p ^ n dvd x}\"\n    by (intro Max_ge finite_divisor_powers xp) simp_all\n  thus ?thesis by (subst multiplicity_eq_Max)\nqed\n\nlemma multiplicity_lessI:\n  assumes \"\\<not>p ^ n dvd x\"\n  shows   \"multiplicity p x < n\"\nproof (rule ccontr)\n  assume \"\\<not>(n > multiplicity p x)\"\n  hence \"p ^ n dvd x\" by (intro multiplicity_dvd') simp\n  with assms show False by contradiction\nqed\n\nlemma power_dvd_iff_le_multiplicity:\n  \"p ^ n dvd x \\<longleftrightarrow> n \\<le> multiplicity p x\"\n  using multiplicity_geI[of n] multiplicity_lessI[of n] by (cases \"p ^ n dvd x\") auto\n\nlemma multiplicity_eq_zero_iff:\n  shows   \"multiplicity p x = 0 \\<longleftrightarrow> \\<not>p dvd x\"\n  using power_dvd_iff_le_multiplicity[of 1] by auto\n\nlemma multiplicity_gt_zero_iff:\n  shows   \"multiplicity p x > 0 \\<longleftrightarrow> p dvd x\"\n  using power_dvd_iff_le_multiplicity[of 1] by auto\n\nlemma multiplicity_decompose:\n  \"\\<not>p dvd (x div p ^ multiplicity p x)\"\nproof\n  assume *: \"p dvd x div p ^ multiplicity p x\"\n  have \"x = x div p ^ multiplicity p x * (p ^ multiplicity p x)\"\n    using multiplicity_dvd[of p x] by simp\n  also from * have \"x div p ^ multiplicity p x = (x div p ^ multiplicity p x div p) * p\" by simp\n  also have \"x div p ^ multiplicity p x div p * p * p ^ multiplicity p x =\n               x div p ^ multiplicity p x div p * p ^ Suc (multiplicity p x)\"\n    by (simp add: mult_assoc)\n  also have \"p ^ Suc (multiplicity p x) dvd \\<dots>\" by (rule dvd_triv_right)\n  finally show False by (subst (asm) power_dvd_iff_le_multiplicity) simp\nqed\n\nlemma multiplicity_decompose':\n  obtains y where \"x = p ^ multiplicity p x * y\" \"\\<not>p dvd y\"\n  using that[of \"x div p ^ multiplicity p x\"]\n  by (simp add: multiplicity_decompose multiplicity_dvd)\n\nend\n\nlemma multiplicity_zero [simp]: \"multiplicity p 0 = 0\"\n  by (simp add: multiplicity_def)\n\nlemma prime_elem_multiplicity_eq_zero_iff:\n  \"prime_elem p \\<Longrightarrow> x \\<noteq> 0 \\<Longrightarrow> multiplicity p x = 0 \\<longleftrightarrow> \\<not>p dvd x\"\n  by (rule multiplicity_eq_zero_iff) simp_all\n\nlemma prime_multiplicity_other:\n  assumes \"prime p\" \"prime q\" \"p \\<noteq> q\"\n  shows   \"multiplicity p q = 0\"\n  using assms by (subst prime_elem_multiplicity_eq_zero_iff) (auto dest: primes_dvd_imp_eq)\n\nlemma prime_multiplicity_gt_zero_iff:\n  \"prime_elem p \\<Longrightarrow> x \\<noteq> 0 \\<Longrightarrow> multiplicity p x > 0 \\<longleftrightarrow> p dvd x\"\n  by (rule multiplicity_gt_zero_iff) simp_all\n\nlemma multiplicity_unit_left: \"is_unit p \\<Longrightarrow> multiplicity p x = 0\"\n  by (simp add: multiplicity_def is_unit_power_iff unit_imp_dvd)\n\nlemma multiplicity_unit_right:\n  assumes \"is_unit x\"\n  shows   \"multiplicity p x = 0\"\nproof (cases \"is_unit p \\<or> x = 0\")\n  case False\n  with multiplicity_lessI[of x p 1] this assms\n    show ?thesis by (auto dest: dvd_unit_imp_unit)\nqed (auto simp: multiplicity_unit_left)\n\nlemma multiplicity_one [simp]: \"multiplicity p 1 = 0\"\n  by (rule multiplicity_unit_right) simp_all\n\nlemma multiplicity_eqI:\n  assumes \"p ^ n dvd x\" \"\\<not>p ^ Suc n dvd x\"\n  shows   \"multiplicity p x = n\"\nproof -\n  consider \"x = 0\" | \"is_unit p\" | \"x \\<noteq> 0\" \"\\<not>is_unit p\" by blast\n  thus ?thesis\n  proof cases\n    assume xp: \"x \\<noteq> 0\" \"\\<not>is_unit p\"\n    from xp assms(1) have \"multiplicity p x \\<ge> n\" by (intro multiplicity_geI)\n    moreover from assms(2) xp have \"multiplicity p x < Suc n\" by (intro multiplicity_lessI)\n    ultimately show ?thesis by simp\n  next\n    assume \"is_unit p\"\n    hence \"is_unit (p ^ Suc n)\" by (simp add: is_unit_power_iff del: power_Suc)\n    hence \"p ^ Suc n dvd x\" by (rule unit_imp_dvd)\n    with \\<open>\\<not>p ^ Suc n dvd x\\<close> show ?thesis by contradiction\n  qed (insert assms, simp_all)\nqed\n\n\ncontext\n  fixes x p :: 'a\n  assumes xp: \"x \\<noteq> 0\" \"\\<not>is_unit p\"\nbegin\n\nlemma multiplicity_times_same:\n  assumes \"p \\<noteq> 0\"\n  shows   \"multiplicity p (p * x) = Suc (multiplicity p x)\"\nproof (rule multiplicity_eqI)\n  show \"p ^ Suc (multiplicity p x) dvd p * x\"\n    by (auto intro!: mult_dvd_mono multiplicity_dvd)\n  from xp assms show \"\\<not> p ^ Suc (Suc (multiplicity p x)) dvd p * x\"\n    using power_dvd_iff_le_multiplicity[OF xp, of \"Suc (multiplicity p x)\"] by simp\nqed\n\nend\n\nlemma multiplicity_same_power': \"multiplicity p (p ^ n) = (if p = 0 \\<or> is_unit p then 0 else n)\"\nproof -\n  consider \"p = 0\" | \"is_unit p\" |\"p \\<noteq> 0\" \"\\<not>is_unit p\" by blast\n  thus ?thesis\n  proof cases\n    assume \"p \\<noteq> 0\" \"\\<not>is_unit p\"\n    thus ?thesis by (induction n) (simp_all add: multiplicity_times_same)\n  qed (simp_all add: power_0_left multiplicity_unit_left)\nqed\n\nlemma multiplicity_same_power:\n  \"p \\<noteq> 0 \\<Longrightarrow> \\<not>is_unit p \\<Longrightarrow> multiplicity p (p ^ n) = n\"\n  by (simp add: multiplicity_same_power')\n\nlemma multiplicity_prime_elem_times_other:\n  assumes \"prime_elem p\" \"\\<not>p dvd q\"\n  shows   \"multiplicity p (q * x) = multiplicity p x\"\nproof (cases \"x = 0\")\n  case False\n  show ?thesis\n  proof (rule multiplicity_eqI)\n    have \"1 * p ^ multiplicity p x dvd q * x\"\n      by (intro mult_dvd_mono multiplicity_dvd) simp_all\n    thus \"p ^ multiplicity p x dvd q * x\" by simp\n  next\n    define n where \"n = multiplicity p x\"\n    from assms have \"\\<not>is_unit p\" by simp\n    from multiplicity_decompose'[OF False this]\n    obtain y where y [folded n_def]: \"x = p ^ multiplicity p x * y\" \"\\<not> p dvd y\" .\n    from y have \"p ^ Suc n dvd q * x \\<longleftrightarrow> p ^ n * p dvd p ^ n * (q * y)\" by (simp add: mult_ac)\n    also from assms have \"\\<dots> \\<longleftrightarrow> p dvd q * y\" by simp\n    also have \"\\<dots> \\<longleftrightarrow> p dvd q \\<or> p dvd y\" by (rule prime_elem_dvd_mult_iff) fact+\n    also from assms y have \"\\<dots> \\<longleftrightarrow> False\" by simp\n    finally show \"\\<not>(p ^ Suc n dvd q * x)\" by blast\n  qed\nqed simp_all\n\nlemma multiplicity_self:\n  assumes \"p \\<noteq> 0\" \"\\<not>is_unit p\"\n  shows   \"multiplicity p p = 1\"\nproof -\n  from assms have \"multiplicity p p = Max {n. p ^ n dvd p}\"\n    by (simp add: multiplicity_eq_Max)\n  also from assms have \"p ^ n dvd p \\<longleftrightarrow> n \\<le> 1\" for n\n    using dvd_power_iff[of p n 1] by auto\n  hence \"{n. p ^ n dvd p} = {..1}\" by auto\n  also have \"\\<dots> = {0,1}\" by auto\n  finally show ?thesis by simp\nqed\n\nlemma multiplicity_times_unit_left:\n  assumes \"is_unit c\"\n  shows   \"multiplicity (c * p) x = multiplicity p x\"\nproof -\n  from assms have \"{n. (c * p) ^ n dvd x} = {n. p ^ n dvd x}\"\n    by (subst mult.commute) (simp add: mult_unit_dvd_iff power_mult_distrib is_unit_power_iff)\n  thus ?thesis by (simp add: multiplicity_def)\nqed\n\nlemma multiplicity_times_unit_right:\n  assumes \"is_unit c\"\n  shows   \"multiplicity p (c * x) = multiplicity p x\"\nproof -\n  from assms have \"{n. p ^ n dvd c * x} = {n. p ^ n dvd x}\"\n    by (subst mult.commute) (simp add: dvd_mult_unit_iff)\n  thus ?thesis by (simp add: multiplicity_def)\nqed\n\nlemma multiplicity_normalize_left [simp]:\n  \"multiplicity (normalize p) x = multiplicity p x\"\nproof (cases \"p = 0\")\n  case [simp]: False\n  have \"normalize p = (1 div unit_factor p) * p\"\n    by (simp add: unit_div_commute is_unit_unit_factor)\n  also have \"multiplicity \\<dots> x = multiplicity p x\"\n    by (rule multiplicity_times_unit_left) (simp add: is_unit_unit_factor)\n  finally show ?thesis .\nqed simp_all\n\nlemma multiplicity_normalize_right [simp]:\n  \"multiplicity p (normalize x) = multiplicity p x\"\nproof (cases \"x = 0\")\n  case [simp]: False\n  have \"normalize x = (1 div unit_factor x) * x\"\n    by (simp add: unit_div_commute is_unit_unit_factor)\n  also have \"multiplicity p \\<dots> = multiplicity p x\"\n    by (rule multiplicity_times_unit_right) (simp add: is_unit_unit_factor)\n  finally show ?thesis .\nqed simp_all\n\nlemma multiplicity_prime [simp]: \"prime_elem p \\<Longrightarrow> multiplicity p p = 1\"\n  by (rule multiplicity_self) auto\n\nlemma multiplicity_prime_power [simp]: \"prime_elem p \\<Longrightarrow> multiplicity p (p ^ n) = n\"\n  by (subst multiplicity_same_power') auto\n\nlift_definition prime_factorization :: \"'a \\<Rightarrow> 'a multiset\" is\n  \"\\<lambda>x p. if prime p then multiplicity p x else 0\"\nproof -\n  fix x :: 'a\n  show \"finite {p. 0 < (if prime p then multiplicity p x else 0)}\" (is \"finite ?A\")\n  proof (cases \"x = 0\")\n    case False\n    from False have \"?A \\<subseteq> {p. prime p \\<and> p dvd x}\"\n      by (auto simp: multiplicity_gt_zero_iff)\n    moreover from False have \"finite {p. prime p \\<and> p dvd x}\"\n      by (rule finite_prime_divisors)\n    ultimately show ?thesis by (rule finite_subset)\n  qed simp_all\nqed\n\nabbreviation prime_factors :: \"'a \\<Rightarrow> 'a set\" where\n  \"prime_factors a \\<equiv> set_mset (prime_factorization a)\"\n\nlemma count_prime_factorization_nonprime:\n  \"\\<not>prime p \\<Longrightarrow> count (prime_factorization x) p = 0\"\n  by transfer simp\n\nlemma count_prime_factorization_prime:\n  \"prime p \\<Longrightarrow> count (prime_factorization x) p = multiplicity p x\"\n  by transfer simp\n\nlemma count_prime_factorization:\n  \"count (prime_factorization x) p = (if prime p then multiplicity p x else 0)\"\n  by transfer simp\n\nlemma dvd_imp_multiplicity_le:\n  assumes \"a dvd b\" \"b \\<noteq> 0\"\n  shows   \"multiplicity p a \\<le> multiplicity p b\"\nproof (cases \"is_unit p\")\n  case False\n  with assms show ?thesis\n    by (intro multiplicity_geI ) (auto intro: dvd_trans[OF multiplicity_dvd' assms(1)])\nqed (insert assms, auto simp: multiplicity_unit_left)\n\nlemma prime_power_inj:\n  assumes \"prime a\" \"a ^ m = a ^ n\"\n  shows   \"m = n\"\nproof -\n  have \"multiplicity a (a ^ m) = multiplicity a (a ^ n)\" by (simp only: assms)\n  thus ?thesis using assms by (subst (asm) (1 2) multiplicity_prime_power) simp_all\nqed\n\nlemma prime_power_inj':\n  assumes \"prime p\" \"prime q\"\n  assumes \"p ^ m = q ^ n\" \"m > 0\" \"n > 0\"\n  shows   \"p = q\" \"m = n\"\nproof -\n  from assms have \"p ^ 1 dvd p ^ m\" by (intro le_imp_power_dvd) simp\n  also have \"p ^ m = q ^ n\" by fact\n  finally have \"p dvd q ^ n\" by simp\n  with assms have \"p dvd q\" using prime_dvd_power[of p q] by simp\n  with assms show \"p = q\" by (simp add: primes_dvd_imp_eq)\n  with assms show \"m = n\" by (simp add: prime_power_inj)\nqed\n\nlemma prime_power_eq_one_iff [simp]: \"prime p \\<Longrightarrow> p ^ n = 1 \\<longleftrightarrow> n = 0\"\n  using prime_power_inj[of p n 0] by auto\n\nlemma one_eq_prime_power_iff [simp]: \"prime p \\<Longrightarrow> 1 = p ^ n \\<longleftrightarrow> n = 0\"\n  using prime_power_inj[of p 0 n] by auto\n\nlemma prime_power_inj'':\n  assumes \"prime p\" \"prime q\"\n  shows   \"p ^ m = q ^ n \\<longleftrightarrow> (m = 0 \\<and> n = 0) \\<or> (p = q \\<and> m = n)\"\n  using assms \n  by (cases \"m = 0\"; cases \"n = 0\")\n     (auto dest: prime_power_inj'[OF assms])\n\nlemma prime_factorization_0 [simp]: \"prime_factorization 0 = {#}\"\n  by (simp add: multiset_eq_iff count_prime_factorization)\n\nlemma prime_factorization_empty_iff:\n  \"prime_factorization x = {#} \\<longleftrightarrow> x = 0 \\<or> is_unit x\"\nproof\n  assume *: \"prime_factorization x = {#}\"\n  {\n    assume x: \"x \\<noteq> 0\" \"\\<not>is_unit x\"\n    {\n      fix p assume p: \"prime p\"\n      have \"count (prime_factorization x) p = 0\" by (simp add: *)\n      also from p have \"count (prime_factorization x) p = multiplicity p x\"\n        by (rule count_prime_factorization_prime)\n      also from x p have \"\\<dots> = 0 \\<longleftrightarrow> \\<not>p dvd x\" by (simp add: multiplicity_eq_zero_iff)\n      finally have \"\\<not>p dvd x\" .\n    }\n    with prime_divisor_exists[OF x] have False by blast\n  }\n  thus \"x = 0 \\<or> is_unit x\" by blast\nnext\n  assume \"x = 0 \\<or> is_unit x\"\n  thus \"prime_factorization x = {#}\"\n  proof\n    assume x: \"is_unit x\"\n    {\n      fix p assume p: \"prime p\"\n      from p x have \"multiplicity p x = 0\"\n        by (subst multiplicity_eq_zero_iff)\n           (auto simp: multiplicity_eq_zero_iff dest: unit_imp_no_prime_divisors)\n    }\n    thus ?thesis by (simp add: multiset_eq_iff count_prime_factorization)\n  qed simp_all\nqed\n\nlemma prime_factorization_unit:\n  assumes \"is_unit x\"\n  shows   \"prime_factorization x = {#}\"\nproof (rule multiset_eqI)\n  fix p :: 'a\n  show \"count (prime_factorization x) p = count {#} p\"\n  proof (cases \"prime p\")\n    case True\n    with assms have \"multiplicity p x = 0\"\n      by (subst multiplicity_eq_zero_iff)\n         (auto simp: multiplicity_eq_zero_iff dest: unit_imp_no_prime_divisors)\n    with True show ?thesis by (simp add: count_prime_factorization_prime)\n  qed (simp_all add: count_prime_factorization_nonprime)\nqed\n\nlemma prime_factorization_1 [simp]: \"prime_factorization 1 = {#}\"\n  by (simp add: prime_factorization_unit)\n\nlemma prime_factorization_times_prime:\n  assumes \"x \\<noteq> 0\" \"prime p\"\n  shows   \"prime_factorization (p * x) = {#p#} + prime_factorization x\"\nproof (rule multiset_eqI)\n  fix q :: 'a\n  consider \"\\<not>prime q\" | \"p = q\" | \"prime q\" \"p \\<noteq> q\" by blast\n  thus \"count (prime_factorization (p * x)) q = count ({#p#} + prime_factorization x) q\"\n  proof cases\n    assume q: \"prime q\" \"p \\<noteq> q\"\n    with assms primes_dvd_imp_eq[of q p] have \"\\<not>q dvd p\" by auto\n    with q assms show ?thesis\n      by (simp add: multiplicity_prime_elem_times_other count_prime_factorization)\n  qed (insert assms, auto simp: count_prime_factorization multiplicity_times_same)\nqed\n\nlemma prod_mset_prime_factorization_weak:\n  assumes \"x \\<noteq> 0\"\n  shows   \"normalize (prod_mset (prime_factorization x)) = normalize x\"\n  using assms\nproof (induction x rule: prime_divisors_induct)\n  case (factor p x)\n  have \"normalize (prod_mset (prime_factorization (p * x))) =\n          normalize (p * normalize (prod_mset (prime_factorization x)))\"\n    using factor.prems factor.hyps by (simp add: prime_factorization_times_prime)\n  also have \"normalize (prod_mset (prime_factorization x)) = normalize x\"\n    by (rule factor.IH) (use factor in auto)\n  finally show ?case by simp\nqed (auto simp: prime_factorization_unit is_unit_normalize)\n\nlemma in_prime_factors_iff:\n  \"p \\<in> prime_factors x \\<longleftrightarrow> x \\<noteq> 0 \\<and> p dvd x \\<and> prime p\"\nproof -\n  have \"p \\<in> prime_factors x \\<longleftrightarrow> count (prime_factorization x) p > 0\" by simp\n  also have \"\\<dots> \\<longleftrightarrow> x \\<noteq> 0 \\<and> p dvd x \\<and> prime p\"\n   by (subst count_prime_factorization, cases \"x = 0\")\n      (auto simp: multiplicity_eq_zero_iff multiplicity_gt_zero_iff)\n  finally show ?thesis .\nqed\n\nlemma in_prime_factors_imp_prime [intro]:\n  \"p \\<in> prime_factors x \\<Longrightarrow> prime p\"\n  by (simp add: in_prime_factors_iff)\n\nlemma in_prime_factors_imp_dvd [dest]:\n  \"p \\<in> prime_factors x \\<Longrightarrow> p dvd x\"\n  by (simp add: in_prime_factors_iff)\n\nlemma prime_factorsI:\n  \"x \\<noteq> 0 \\<Longrightarrow> prime p \\<Longrightarrow> p dvd x \\<Longrightarrow> p \\<in> prime_factors x\"\n  by (auto simp: in_prime_factors_iff)\n\nlemma prime_factors_dvd:\n  \"x \\<noteq> 0 \\<Longrightarrow> prime_factors x = {p. prime p \\<and> p dvd x}\"\n  by (auto intro: prime_factorsI)\n\nlemma prime_factors_multiplicity:\n  \"prime_factors n = {p. prime p \\<and> multiplicity p n > 0}\"\n  by (cases \"n = 0\") (auto simp add: prime_factors_dvd prime_multiplicity_gt_zero_iff)\n\nlemma prime_factorization_prime:\n  assumes \"prime p\"\n  shows   \"prime_factorization p = {#p#}\"\nproof (rule multiset_eqI)\n  fix q :: 'a\n  consider \"\\<not>prime q\" | \"q = p\" | \"prime q\" \"q \\<noteq> p\" by blast\n  thus \"count (prime_factorization p) q = count {#p#} q\"\n    by cases (insert assms, auto dest: primes_dvd_imp_eq\n                simp: count_prime_factorization multiplicity_self multiplicity_eq_zero_iff)\nqed\n\nlemma prime_factorization_prod_mset_primes:\n  assumes \"\\<And>p. p \\<in># A \\<Longrightarrow> prime p\"\n  shows   \"prime_factorization (prod_mset A) = A\"\n  using assms\nproof (induction A)\n  case (add p A)\n  from add.prems[of 0] have \"0 \\<notin># A\" by auto\n  hence \"prod_mset A \\<noteq> 0\" by auto\n  with add show ?case\n    by (simp_all add: mult_ac prime_factorization_times_prime Multiset.union_commute)\nqed simp_all\n\nlemma prime_factorization_cong:\n  \"normalize x = normalize y \\<Longrightarrow> prime_factorization x = prime_factorization y\"\n  by (simp add: multiset_eq_iff count_prime_factorization\n                multiplicity_normalize_right [of _ x, symmetric]\n                multiplicity_normalize_right [of _ y, symmetric]\n           del:  multiplicity_normalize_right)\n\nlemma prime_factorization_unique:\n  assumes \"x \\<noteq> 0\" \"y \\<noteq> 0\"\n  shows   \"prime_factorization x = prime_factorization y \\<longleftrightarrow> normalize x = normalize y\"\nproof\n  assume \"prime_factorization x = prime_factorization y\"\n  hence \"prod_mset (prime_factorization x) = prod_mset (prime_factorization y)\" by simp\n  hence \"normalize (prod_mset (prime_factorization x)) =\n         normalize (prod_mset (prime_factorization y))\"\n    by (simp only: )\n  with assms show \"normalize x = normalize y\"\n    by (simp add: prod_mset_prime_factorization_weak)\nqed (rule prime_factorization_cong)\n\nlemma prime_factorization_normalize [simp]:\n  \"prime_factorization (normalize x) = prime_factorization x\"\n  by (cases \"x = 0\", simp, subst prime_factorization_unique) auto\n\nlemma prime_factorization_eqI_strong:\n  assumes \"\\<And>p. p \\<in># P \\<Longrightarrow> prime p\" \"prod_mset P = n\"\n  shows   \"prime_factorization n = P\"\n  using prime_factorization_prod_mset_primes[of P] assms by simp\n\nlemma prime_factorization_eqI:\n  assumes \"\\<And>p. p \\<in># P \\<Longrightarrow> prime p\" \"normalize (prod_mset P) = normalize n\"\n  shows   \"prime_factorization n = P\"\nproof -\n  have \"P = prime_factorization (normalize (prod_mset P))\"\n    using prime_factorization_prod_mset_primes[of P] assms(1) by simp\n  with assms(2) show ?thesis by simp\nqed\n\nlemma prime_factorization_mult:\n  assumes \"x \\<noteq> 0\" \"y \\<noteq> 0\"\n  shows   \"prime_factorization (x * y) = prime_factorization x + prime_factorization y\"\nproof -\n  have \"normalize (prod_mset (prime_factorization x) * prod_mset (prime_factorization y)) =\n          normalize (normalize (prod_mset (prime_factorization x)) *\n                     normalize (prod_mset (prime_factorization y)))\"\n    by (simp only: normalize_mult_normalize_left normalize_mult_normalize_right)\n  also have \"\\<dots> = normalize (x * y)\"\n    by (subst (1 2) prod_mset_prime_factorization_weak) (use assms in auto)\n  finally show ?thesis\n    by (intro prime_factorization_eqI) auto\nqed\n\nlemma prime_factorization_prod:\n  assumes \"finite A\" \"\\<And>x. x \\<in> A \\<Longrightarrow> f x \\<noteq> 0\"\n  shows   \"prime_factorization (prod f A) = (\\<Sum>n\\<in>A. prime_factorization (f n))\"\n  using assms by (induction A rule: finite_induct)\n                 (auto simp: Sup_multiset_empty prime_factorization_mult)\n\nlemma prime_elem_multiplicity_mult_distrib:\n  assumes \"prime_elem p\" \"x \\<noteq> 0\" \"y \\<noteq> 0\"\n  shows   \"multiplicity p (x * y) = multiplicity p x + multiplicity p y\"\nproof -\n  have \"multiplicity p (x * y) = count (prime_factorization (x * y)) (normalize p)\"\n    by (subst count_prime_factorization_prime) (simp_all add: assms)\n  also from assms\n    have \"prime_factorization (x * y) = prime_factorization x + prime_factorization y\"\n      by (intro prime_factorization_mult)\n  also have \"count \\<dots> (normalize p) =\n    count (prime_factorization x) (normalize p) + count (prime_factorization y) (normalize p)\"\n    by simp\n  also have \"\\<dots> = multiplicity p x + multiplicity p y\"\n    by (subst (1 2) count_prime_factorization_prime) (simp_all add: assms)\n  finally show ?thesis .\nqed\n\nlemma prime_elem_multiplicity_prod_mset_distrib:\n  assumes \"prime_elem p\" \"0 \\<notin># A\"\n  shows   \"multiplicity p (prod_mset A) = sum_mset (image_mset (multiplicity p) A)\"\n  using assms by (induction A) (auto simp: prime_elem_multiplicity_mult_distrib)\n\nlemma prime_elem_multiplicity_power_distrib:\n  assumes \"prime_elem p\" \"x \\<noteq> 0\"\n  shows   \"multiplicity p (x ^ n) = n * multiplicity p x\"\n  using assms prime_elem_multiplicity_prod_mset_distrib [of p \"replicate_mset n x\"]\n  by simp\n\nlemma prime_elem_multiplicity_prod_distrib:\n  assumes \"prime_elem p\" \"0 \\<notin> f ` A\" \"finite A\"\n  shows   \"multiplicity p (prod f A) = (\\<Sum>x\\<in>A. multiplicity p (f x))\"\nproof -\n  have \"multiplicity p (prod f A) = (\\<Sum>x\\<in>#mset_set A. multiplicity p (f x))\"\n    using assms by (subst prod_unfold_prod_mset)\n                   (simp_all add: prime_elem_multiplicity_prod_mset_distrib sum_unfold_sum_mset\n                      multiset.map_comp o_def)\n  also from \\<open>finite A\\<close> have \"\\<dots> = (\\<Sum>x\\<in>A. multiplicity p (f x))\"\n    by (induction A rule: finite_induct) simp_all\n  finally show ?thesis .\nqed\n\nlemma multiplicity_distinct_prime_power:\n  \"prime p \\<Longrightarrow> prime q \\<Longrightarrow> p \\<noteq> q \\<Longrightarrow> multiplicity p (q ^ n) = 0\"\n  by (subst prime_elem_multiplicity_power_distrib) (auto simp: prime_multiplicity_other)\n\nlemma prime_factorization_prime_power:\n  \"prime p \\<Longrightarrow> prime_factorization (p ^ n) = replicate_mset n p\"\n  by (induction n)\n     (simp_all add: prime_factorization_mult prime_factorization_prime Multiset.union_commute)\n\nlemma prime_factorization_subset_iff_dvd:\n  assumes [simp]: \"x \\<noteq> 0\" \"y \\<noteq> 0\"\n  shows   \"prime_factorization x \\<subseteq># prime_factorization y \\<longleftrightarrow> x dvd y\"\nproof -\n  have \"x dvd y \\<longleftrightarrow>\n    normalize (prod_mset (prime_factorization x)) dvd normalize (prod_mset (prime_factorization y))\"\n    using assms by (subst (1 2) prod_mset_prime_factorization_weak) auto\n  also have \"\\<dots> \\<longleftrightarrow> prime_factorization x \\<subseteq># prime_factorization y\"\n    by (auto intro!: prod_mset_primes_dvd_imp_subset prod_mset_subset_imp_dvd)\n  finally show ?thesis ..\nqed\n\nlemma prime_factorization_subset_imp_dvd:\n  \"x \\<noteq> 0 \\<Longrightarrow> (prime_factorization x \\<subseteq># prime_factorization y) \\<Longrightarrow> x dvd y\"\n  by (cases \"y = 0\") (simp_all add: prime_factorization_subset_iff_dvd)\n\nlemma prime_factorization_divide:\n  assumes \"b dvd a\"\n  shows   \"prime_factorization (a div b) = prime_factorization a - prime_factorization b\"\nproof (cases \"a = 0\")\n  case [simp]: False\n  from assms have [simp]: \"b \\<noteq> 0\" by auto\n  have \"prime_factorization ((a div b) * b) = prime_factorization (a div b) + prime_factorization b\"\n    by (intro prime_factorization_mult) (insert assms, auto elim!: dvdE)\n  with assms show ?thesis by simp\nqed simp_all\n\nlemma zero_not_in_prime_factors [simp]: \"0 \\<notin> prime_factors x\"\n  by (auto dest: in_prime_factors_imp_prime)\n\nlemma prime_prime_factors:\n  \"prime p \\<Longrightarrow> prime_factors p = {p}\"\n  by (drule prime_factorization_prime) simp\n\nlemma prime_factors_product:\n  \"x \\<noteq> 0 \\<Longrightarrow> y \\<noteq> 0 \\<Longrightarrow> prime_factors (x * y) = prime_factors x \\<union> prime_factors y\"\n  by (simp add: prime_factorization_mult)\n\nlemma dvd_prime_factors [intro]:\n  \"y \\<noteq> 0 \\<Longrightarrow> x dvd y \\<Longrightarrow> prime_factors x \\<subseteq> prime_factors y\"\n  by (intro set_mset_mono, subst prime_factorization_subset_iff_dvd) auto\n\n(* RENAMED multiplicity_dvd *)\nlemma multiplicity_le_imp_dvd:\n  assumes \"x \\<noteq> 0\" \"\\<And>p. prime p \\<Longrightarrow> multiplicity p x \\<le> multiplicity p y\"\n  shows   \"x dvd y\"\nproof (cases \"y = 0\")\n  case False\n  from assms this have \"prime_factorization x \\<subseteq># prime_factorization y\"\n    by (intro mset_subset_eqI) (auto simp: count_prime_factorization)\n  with assms False show ?thesis by (subst (asm) prime_factorization_subset_iff_dvd)\nqed auto\n\nlemma dvd_multiplicity_eq:\n  \"x \\<noteq> 0 \\<Longrightarrow> y \\<noteq> 0 \\<Longrightarrow> x dvd y \\<longleftrightarrow> (\\<forall>p. multiplicity p x \\<le> multiplicity p y)\"\n  by (auto intro: dvd_imp_multiplicity_le multiplicity_le_imp_dvd)\n\nlemma multiplicity_eq_imp_eq:\n  assumes \"x \\<noteq> 0\" \"y \\<noteq> 0\"\n  assumes \"\\<And>p. prime p \\<Longrightarrow> multiplicity p x = multiplicity p y\"\n  shows   \"normalize x = normalize y\"\n  using assms by (intro associatedI multiplicity_le_imp_dvd) simp_all\n\nlemma prime_factorization_unique':\n  assumes \"\\<forall>p \\<in># M. prime p\" \"\\<forall>p \\<in># N. prime p\" \"(\\<Prod>i \\<in># M. i) = (\\<Prod>i \\<in># N. i)\"\n  shows   \"M = N\"\nproof -\n  have \"prime_factorization (\\<Prod>i \\<in># M. i) = prime_factorization (\\<Prod>i \\<in># N. i)\"\n    by (simp only: assms)\n  also from assms have \"prime_factorization (\\<Prod>i \\<in># M. i) = M\"\n    by (subst prime_factorization_prod_mset_primes) simp_all\n  also from assms have \"prime_factorization (\\<Prod>i \\<in># N. i) = N\"\n    by (subst prime_factorization_prod_mset_primes) simp_all\n  finally show ?thesis .\nqed\n\nlemma prime_factorization_unique'':\n  assumes \"\\<forall>p \\<in># M. prime p\" \"\\<forall>p \\<in># N. prime p\" \"normalize (\\<Prod>i \\<in># M. i) = normalize (\\<Prod>i \\<in># N. i)\"\n  shows   \"M = N\"\nproof -\n  have \"prime_factorization (normalize (\\<Prod>i \\<in># M. i)) =\n        prime_factorization (normalize (\\<Prod>i \\<in># N. i))\"\n    by (simp only: assms)\n  also from assms have \"prime_factorization (normalize (\\<Prod>i \\<in># M. i)) = M\"\n    by (subst prime_factorization_normalize, subst prime_factorization_prod_mset_primes) simp_all\n  also from assms have \"prime_factorization (normalize (\\<Prod>i \\<in># N. i)) = N\"\n    by (subst prime_factorization_normalize, subst prime_factorization_prod_mset_primes) simp_all\n  finally show ?thesis .\nqed\n\nlemma multiplicity_cong:\n  \"(\\<And>r. p ^ r dvd a \\<longleftrightarrow> p ^ r dvd b) \\<Longrightarrow> multiplicity p a = multiplicity p b\"\n  by (simp add: multiplicity_def)\n\nlemma not_dvd_imp_multiplicity_0:\n  assumes \"\\<not>p dvd x\"\n  shows   \"multiplicity p x = 0\"\nproof -\n  from assms have \"multiplicity p x < 1\"\n    by (intro multiplicity_lessI) auto\n  thus ?thesis by simp\nqed\n\nlemma multiplicity_zero_left [simp]: \"multiplicity 0 x = 0\"\n by (cases \"x = 0\") (auto intro: not_dvd_imp_multiplicity_0)\n\nlemma inj_on_Prod_primes:\n  assumes \"\\<And>P p. P \\<in> A \\<Longrightarrow> p \\<in> P \\<Longrightarrow> prime p\"\n  assumes \"\\<And>P. P \\<in> A \\<Longrightarrow> finite P\"\n  shows   \"inj_on Prod A\"\nproof (rule inj_onI)\n  fix P Q assume PQ: \"P \\<in> A\" \"Q \\<in> A\" \"\\<Prod>P = \\<Prod>Q\"\n  with prime_factorization_unique'[of \"mset_set P\" \"mset_set Q\"] assms[of P] assms[of Q]\n    have \"mset_set P = mset_set Q\" by (auto simp: prod_unfold_prod_mset)\n    with assms[of P] assms[of Q] PQ show \"P = Q\" by simp\nqed\n\nlemma divides_primepow_weak:\n  assumes \"prime p\" and \"a dvd p ^ n\"\n  obtains m where \"m \\<le> n\" and \"normalize a = normalize (p ^ m)\"\nproof -\n  from assms have \"a \\<noteq> 0\"\n    by auto\n  with assms\n  have \"normalize (prod_mset (prime_factorization a)) dvd\n          normalize (prod_mset (prime_factorization (p ^ n)))\"\n    by (subst (1 2) prod_mset_prime_factorization_weak) auto\n  then have \"prime_factorization a \\<subseteq># prime_factorization (p ^ n)\"\n    by (simp add: in_prime_factors_imp_prime prod_mset_dvd_prod_mset_primes_iff)\n  with assms have \"prime_factorization a \\<subseteq># replicate_mset n p\"\n    by (simp add: prime_factorization_prime_power)\n  then obtain m where \"m \\<le> n\" and \"prime_factorization a = replicate_mset m p\"\n    by (rule msubseteq_replicate_msetE)\n  then have *: \"normalize (prod_mset (prime_factorization a)) =\n                  normalize (prod_mset (replicate_mset m p))\" by metis\n  also have \"normalize (prod_mset (prime_factorization a)) = normalize a\"\n    using \\<open>a \\<noteq> 0\\<close> by (simp add: prod_mset_prime_factorization_weak)\n  also have \"prod_mset (replicate_mset m p) = p ^ m\"\n    by simp\n  finally show ?thesis using \\<open>m \\<le> n\\<close> \n    by (intro that[of m])\nqed\n\nlemma divide_out_primepow_ex:\n  assumes \"n \\<noteq> 0\" \"\\<exists>p\\<in>prime_factors n. P p\"\n  obtains p k n' where \"P p\" \"prime p\" \"p dvd n\" \"\\<not>p dvd n'\" \"k > 0\" \"n = p ^ k * n'\"\nproof -\n  from assms obtain p where p: \"P p\" \"prime p\" \"p dvd n\"\n    by auto\n  define k where \"k = multiplicity p n\"\n  define n' where \"n' = n div p ^ k\"\n  have n': \"n = p ^ k * n'\" \"\\<not>p dvd n'\"\n    using assms p multiplicity_decompose[of n p]\n    by (auto simp: n'_def k_def multiplicity_dvd)\n  from n' p have \"k > 0\" by (intro Nat.gr0I) auto\n  with n' p that[of p n' k] show ?thesis by auto\nqed\n\nlemma divide_out_primepow:\n  assumes \"n \\<noteq> 0\" \"\\<not>is_unit n\"\n  obtains p k n' where \"prime p\" \"p dvd n\" \"\\<not>p dvd n'\" \"k > 0\" \"n = p ^ k * n'\"\n  using divide_out_primepow_ex[OF assms(1), of \"\\<lambda>_. True\"] prime_divisor_exists[OF assms] assms\n        prime_factorsI by metis\n\n\nsubsection \\<open>GCD and LCM computation with unique factorizations\\<close>\n\ndefinition \"gcd_factorial a b = (if a = 0 then normalize b\n     else if b = 0 then normalize a\n     else normalize (prod_mset (prime_factorization a \\<inter># prime_factorization b)))\"\n\ndefinition \"lcm_factorial a b = (if a = 0 \\<or> b = 0 then 0\n     else normalize (prod_mset (prime_factorization a \\<union># prime_factorization b)))\"\n\ndefinition \"Gcd_factorial A =\n  (if A \\<subseteq> {0} then 0 else normalize (prod_mset (Inf (prime_factorization ` (A - {0})))))\"\n\ndefinition \"Lcm_factorial A =\n  (if A = {} then 1\n   else if 0 \\<notin> A \\<and> subset_mset.bdd_above (prime_factorization ` (A - {0})) then\n     normalize (prod_mset (Sup (prime_factorization ` A)))\n   else\n     0)\"\n\nlemma prime_factorization_gcd_factorial:\n  assumes [simp]: \"a \\<noteq> 0\" \"b \\<noteq> 0\"\n  shows   \"prime_factorization (gcd_factorial a b) = prime_factorization a \\<inter># prime_factorization b\"\nproof -\n  have \"prime_factorization (gcd_factorial a b) =\n          prime_factorization (prod_mset (prime_factorization a \\<inter># prime_factorization b))\"\n    by (simp add: gcd_factorial_def)\n  also have \"\\<dots> = prime_factorization a \\<inter># prime_factorization b\"\n    by (subst prime_factorization_prod_mset_primes) auto\n  finally show ?thesis .\nqed\n\nlemma prime_factorization_lcm_factorial:\n  assumes [simp]: \"a \\<noteq> 0\" \"b \\<noteq> 0\"\n  shows   \"prime_factorization (lcm_factorial a b) = prime_factorization a \\<union># prime_factorization b\"\nproof -\n  have \"prime_factorization (lcm_factorial a b) =\n          prime_factorization (prod_mset (prime_factorization a \\<union># prime_factorization b))\"\n    by (simp add: lcm_factorial_def)\n  also have \"\\<dots> = prime_factorization a \\<union># prime_factorization b\"\n    by (subst prime_factorization_prod_mset_primes) auto\n  finally show ?thesis .\nqed\n\nlemma prime_factorization_Gcd_factorial:\n  assumes \"\\<not>A \\<subseteq> {0}\"\n  shows   \"prime_factorization (Gcd_factorial A) = Inf (prime_factorization ` (A - {0}))\"\nproof -\n  from assms obtain x where x: \"x \\<in> A - {0}\" by auto\n  hence \"Inf (prime_factorization ` (A - {0})) \\<subseteq># prime_factorization x\"\n    by (intro subset_mset.cInf_lower) simp_all\n  hence \"\\<forall>y. y \\<in># Inf (prime_factorization ` (A - {0})) \\<longrightarrow> y \\<in> prime_factors x\"\n    by (auto dest: mset_subset_eqD)\n  with in_prime_factors_imp_prime[of _ x]\n    have \"\\<forall>p. p \\<in># Inf (prime_factorization ` (A - {0})) \\<longrightarrow> prime p\" by blast\n  with assms show ?thesis\n    by (simp add: Gcd_factorial_def prime_factorization_prod_mset_primes)\nqed\n\nlemma prime_factorization_Lcm_factorial:\n  assumes \"0 \\<notin> A\" \"subset_mset.bdd_above (prime_factorization ` A)\"\n  shows   \"prime_factorization (Lcm_factorial A) = Sup (prime_factorization ` A)\"\nproof (cases \"A = {}\")\n  case True\n  hence \"prime_factorization ` A = {}\" by auto\n  also have \"Sup \\<dots> = {#}\" by (simp add: Sup_multiset_empty)\n  finally show ?thesis by (simp add: Lcm_factorial_def)\nnext\n  case False\n  have \"\\<forall>y. y \\<in># Sup (prime_factorization ` A) \\<longrightarrow> prime y\"\n    by (auto simp: in_Sup_multiset_iff assms)\n  with assms False show ?thesis\n    by (simp add: Lcm_factorial_def prime_factorization_prod_mset_primes)\nqed\n\nlemma gcd_factorial_commute: \"gcd_factorial a b = gcd_factorial b a\"\n  by (simp add: gcd_factorial_def multiset_inter_commute)\n\nlemma gcd_factorial_dvd1: \"gcd_factorial a b dvd a\"\nproof (cases \"a = 0 \\<or> b = 0\")\n  case False\n  hence \"gcd_factorial a b \\<noteq> 0\" by (auto simp: gcd_factorial_def)\n  with False show ?thesis\n    by (subst prime_factorization_subset_iff_dvd [symmetric])\n       (auto simp: prime_factorization_gcd_factorial)\nqed (auto simp: gcd_factorial_def)\n\nlemma gcd_factorial_dvd2: \"gcd_factorial a b dvd b\"\n  by (subst gcd_factorial_commute) (rule gcd_factorial_dvd1)\n\nlemma normalize_gcd_factorial [simp]: \"normalize (gcd_factorial a b) = gcd_factorial a b\"\n  by (simp add: gcd_factorial_def)\n\nlemma normalize_lcm_factorial [simp]: \"normalize (lcm_factorial a b) = lcm_factorial a b\"\n  by (simp add: lcm_factorial_def)\n\nlemma gcd_factorial_greatest: \"c dvd gcd_factorial a b\" if \"c dvd a\" \"c dvd b\" for a b c\nproof (cases \"a = 0 \\<or> b = 0\")\n  case False\n  with that have [simp]: \"c \\<noteq> 0\" by auto\n  let ?p = \"prime_factorization\"\n  from that False have \"?p c \\<subseteq># ?p a\" \"?p c \\<subseteq># ?p b\"\n    by (simp_all add: prime_factorization_subset_iff_dvd)\n  hence \"prime_factorization c \\<subseteq>#\n           prime_factorization (prod_mset (prime_factorization a \\<inter># prime_factorization b))\"\n    using False by (subst prime_factorization_prod_mset_primes) auto\n  with False show ?thesis\n    by (auto simp: gcd_factorial_def prime_factorization_subset_iff_dvd [symmetric])\nqed (auto simp: gcd_factorial_def that)\n\nlemma lcm_factorial_gcd_factorial:\n  \"lcm_factorial a b = normalize (a * b div gcd_factorial a b)\" for a b\nproof (cases \"a = 0 \\<or> b = 0\")\n  case False\n  let ?p = \"prime_factorization\"\n  have 1: \"normalize x * normalize y dvd z \\<longleftrightarrow> x * y dvd z\" for x y z :: 'a\n  proof -\n    have \"normalize (normalize x * normalize y) dvd z \\<longleftrightarrow> x * y dvd z\"\n      unfolding normalize_mult_normalize_left normalize_mult_normalize_right by simp\n    thus ?thesis unfolding normalize_dvd_iff by simp\n  qed\n\n  have \"?p (a * b) = (?p a \\<union># ?p b) + (?p a \\<inter># ?p b)\"\n    using False by (subst prime_factorization_mult) (auto intro!: multiset_eqI)\n  hence \"normalize (prod_mset (?p (a * b))) =\n           normalize (prod_mset ((?p a \\<union># ?p b) + (?p a \\<inter># ?p b)))\"\n    by (simp only:)\n  hence *: \"normalize (a * b) = normalize (lcm_factorial a b * gcd_factorial a b)\" using False\n    by (subst (asm) prod_mset_prime_factorization_weak)\n       (auto simp: lcm_factorial_def gcd_factorial_def)\n\n  have [simp]: \"gcd_factorial a b dvd a * b\" \"lcm_factorial a b dvd a * b\"\n    using associatedD2[OF *] by auto\n  from False have [simp]: \"gcd_factorial a b \\<noteq> 0\" \"lcm_factorial a b \\<noteq> 0\"\n    by (auto simp: gcd_factorial_def lcm_factorial_def)\n  \n  show ?thesis\n    by (rule associated_eqI)\n       (use * in \\<open>auto simp: dvd_div_iff_mult div_dvd_iff_mult dest: associatedD1 associatedD2\\<close>)\nqed (auto simp: lcm_factorial_def)\n\nlemma normalize_Gcd_factorial:\n  \"normalize (Gcd_factorial A) = Gcd_factorial A\"\n  by (simp add: Gcd_factorial_def)\n\nlemma Gcd_factorial_eq_0_iff:\n  \"Gcd_factorial A = 0 \\<longleftrightarrow> A \\<subseteq> {0}\"\n  by (auto simp: Gcd_factorial_def in_Inf_multiset_iff split: if_splits)\n\nlemma Gcd_factorial_dvd:\n  assumes \"x \\<in> A\"\n  shows   \"Gcd_factorial A dvd x\"\nproof (cases \"x = 0\")\n  case False\n  with assms have \"prime_factorization (Gcd_factorial A) = Inf (prime_factorization ` (A - {0}))\"\n    by (intro prime_factorization_Gcd_factorial) auto\n  also from False assms have \"\\<dots> \\<subseteq># prime_factorization x\"\n    by (intro subset_mset.cInf_lower) auto\n  finally show ?thesis\n    by (subst (asm) prime_factorization_subset_iff_dvd)\n       (insert assms False, auto simp: Gcd_factorial_eq_0_iff)\nqed simp_all\n\nlemma Gcd_factorial_greatest:\n  assumes \"\\<And>y. y \\<in> A \\<Longrightarrow> x dvd y\"\n  shows   \"x dvd Gcd_factorial A\"\nproof (cases \"A \\<subseteq> {0}\")\n  case False\n  from False obtain y where \"y \\<in> A\" \"y \\<noteq> 0\" by auto\n  with assms[of y] have nz: \"x \\<noteq> 0\" by auto\n  from nz assms have \"prime_factorization x \\<subseteq># prime_factorization y\" if \"y \\<in> A - {0}\" for y\n    using that by (subst prime_factorization_subset_iff_dvd) auto\n  with False have \"prime_factorization x \\<subseteq># Inf (prime_factorization ` (A - {0}))\"\n    by (intro subset_mset.cInf_greatest) auto\n  also from False have \"\\<dots> = prime_factorization (Gcd_factorial A)\"\n    by (rule prime_factorization_Gcd_factorial [symmetric])\n  finally show ?thesis\n    by (subst (asm) prime_factorization_subset_iff_dvd)\n       (insert nz False, auto simp: Gcd_factorial_eq_0_iff)\nqed (simp_all add: Gcd_factorial_def)\n\nlemma normalize_Lcm_factorial:\n  \"normalize (Lcm_factorial A) = Lcm_factorial A\"\n  by (simp add: Lcm_factorial_def)\n\nlemma Lcm_factorial_eq_0_iff:\n  \"Lcm_factorial A = 0 \\<longleftrightarrow> 0 \\<in> A \\<or> \\<not>subset_mset.bdd_above (prime_factorization ` A)\"\n  by (auto simp: Lcm_factorial_def in_Sup_multiset_iff)\n\nlemma dvd_Lcm_factorial:\n  assumes \"x \\<in> A\"\n  shows   \"x dvd Lcm_factorial A\"\nproof (cases \"0 \\<notin> A \\<and> subset_mset.bdd_above (prime_factorization ` A)\")\n  case True\n  with assms have [simp]: \"0 \\<notin> A\" \"x \\<noteq> 0\" \"A \\<noteq> {}\" by auto\n  from assms True have \"prime_factorization x \\<subseteq># Sup (prime_factorization ` A)\"\n    by (intro subset_mset.cSup_upper) auto\n  also have \"\\<dots> = prime_factorization (Lcm_factorial A)\"\n    by (rule prime_factorization_Lcm_factorial [symmetric]) (insert True, simp_all)\n  finally show ?thesis\n    by (subst (asm) prime_factorization_subset_iff_dvd)\n       (insert True, auto simp: Lcm_factorial_eq_0_iff)\nqed (insert assms, auto simp: Lcm_factorial_def)\n\nlemma Lcm_factorial_least:\n  assumes \"\\<And>y. y \\<in> A \\<Longrightarrow> y dvd x\"\n  shows   \"Lcm_factorial A dvd x\"\nproof -\n  consider \"A = {}\" | \"0 \\<in> A\" | \"x = 0\" | \"A \\<noteq> {}\" \"0 \\<notin> A\" \"x \\<noteq> 0\" by blast\n  thus ?thesis\n  proof cases\n    assume *: \"A \\<noteq> {}\" \"0 \\<notin> A\" \"x \\<noteq> 0\"\n    hence nz: \"x \\<noteq> 0\" if \"x \\<in> A\" for x using that by auto\n    from * have bdd: \"subset_mset.bdd_above (prime_factorization ` A)\"\n      by (intro subset_mset.bdd_aboveI[of _ \"prime_factorization x\"])\n         (auto simp: prime_factorization_subset_iff_dvd nz dest: assms)\n    have \"prime_factorization (Lcm_factorial A) = Sup (prime_factorization ` A)\"\n      by (rule prime_factorization_Lcm_factorial) fact+\n    also from * have \"\\<dots> \\<subseteq># prime_factorization x\"\n      by (intro subset_mset.cSup_least)\n         (auto simp: prime_factorization_subset_iff_dvd nz dest: assms)\n    finally show ?thesis\n      by (subst (asm) prime_factorization_subset_iff_dvd)\n         (insert * bdd, auto simp: Lcm_factorial_eq_0_iff)\n  qed (auto simp: Lcm_factorial_def dest: assms)\nqed\n\nlemmas gcd_lcm_factorial =\n  gcd_factorial_dvd1 gcd_factorial_dvd2 gcd_factorial_greatest\n  normalize_gcd_factorial lcm_factorial_gcd_factorial\n  normalize_Gcd_factorial Gcd_factorial_dvd Gcd_factorial_greatest\n  normalize_Lcm_factorial dvd_Lcm_factorial Lcm_factorial_least\n\nend\n\nclass factorial_semiring_gcd = factorial_semiring + gcd + Gcd +\n  assumes gcd_eq_gcd_factorial: \"gcd a b = gcd_factorial a b\"\n  and     lcm_eq_lcm_factorial: \"lcm a b = lcm_factorial a b\"\n  and     Gcd_eq_Gcd_factorial: \"Gcd A = Gcd_factorial A\"\n  and     Lcm_eq_Lcm_factorial: \"Lcm A = Lcm_factorial A\"\nbegin\n\nlemma prime_factorization_gcd:\n  assumes [simp]: \"a \\<noteq> 0\" \"b \\<noteq> 0\"\n  shows   \"prime_factorization (gcd a b) = prime_factorization a \\<inter># prime_factorization b\"\n  by (simp add: gcd_eq_gcd_factorial prime_factorization_gcd_factorial)\n\nlemma prime_factorization_lcm:\n  assumes [simp]: \"a \\<noteq> 0\" \"b \\<noteq> 0\"\n  shows   \"prime_factorization (lcm a b) = prime_factorization a \\<union># prime_factorization b\"\n  by (simp add: lcm_eq_lcm_factorial prime_factorization_lcm_factorial)\n\nlemma prime_factorization_Gcd:\n  assumes \"Gcd A \\<noteq> 0\"\n  shows   \"prime_factorization (Gcd A) = Inf (prime_factorization ` (A - {0}))\"\n  using assms\n  by (simp add: prime_factorization_Gcd_factorial Gcd_eq_Gcd_factorial Gcd_factorial_eq_0_iff)\n\nlemma prime_factorization_Lcm:\n  assumes \"Lcm A \\<noteq> 0\"\n  shows   \"prime_factorization (Lcm A) = Sup (prime_factorization ` A)\"\n  using assms\n  by (simp add: prime_factorization_Lcm_factorial Lcm_eq_Lcm_factorial Lcm_factorial_eq_0_iff)\n\nlemma prime_factors_gcd [simp]: \n  \"a \\<noteq> 0 \\<Longrightarrow> b \\<noteq> 0 \\<Longrightarrow> prime_factors (gcd a b) = \n     prime_factors a \\<inter> prime_factors b\"\n  by (subst prime_factorization_gcd) auto\n\nlemma prime_factors_lcm [simp]: \n  \"a \\<noteq> 0 \\<Longrightarrow> b \\<noteq> 0 \\<Longrightarrow> prime_factors (lcm a b) = \n     prime_factors a \\<union> prime_factors b\"\n  by (subst prime_factorization_lcm) auto\n\nsubclass semiring_gcd\n  by (standard, unfold gcd_eq_gcd_factorial lcm_eq_lcm_factorial)\n     (rule gcd_lcm_factorial; assumption)+\n\nsubclass semiring_Gcd\n  by (standard, unfold Gcd_eq_Gcd_factorial Lcm_eq_Lcm_factorial)\n     (rule gcd_lcm_factorial; assumption)+\n\nlemma\n  assumes \"x \\<noteq> 0\" \"y \\<noteq> 0\"\n  shows gcd_eq_factorial':\n          \"gcd x y = normalize (\\<Prod>p \\<in> prime_factors x \\<inter> prime_factors y.\n                          p ^ min (multiplicity p x) (multiplicity p y))\" (is \"_ = ?rhs1\")\n    and lcm_eq_factorial':\n          \"lcm x y = normalize (\\<Prod>p \\<in> prime_factors x \\<union> prime_factors y.\n                          p ^ max (multiplicity p x) (multiplicity p y))\" (is \"_ = ?rhs2\")\nproof -\n  have \"gcd x y = gcd_factorial x y\" by (rule gcd_eq_gcd_factorial)\n  also have \"\\<dots> = ?rhs1\"\n    by (auto simp: gcd_factorial_def assms prod_mset_multiplicity\n          count_prime_factorization_prime\n          intro!: arg_cong[of _ _ normalize] dest: in_prime_factors_imp_prime intro!: prod.cong)\n  finally show \"gcd x y = ?rhs1\" .\n  have \"lcm x y = lcm_factorial x y\" by (rule lcm_eq_lcm_factorial)\n  also have \"\\<dots> = ?rhs2\"\n    by (auto simp: lcm_factorial_def assms prod_mset_multiplicity\n          count_prime_factorization_prime intro!: arg_cong[of _ _ normalize] \n          dest: in_prime_factors_imp_prime intro!: prod.cong)\n  finally show \"lcm x y = ?rhs2\" .\nqed\n\nlemma\n  assumes \"x \\<noteq> 0\" \"y \\<noteq> 0\" \"prime p\"\n  shows   multiplicity_gcd: \"multiplicity p (gcd x y) = min (multiplicity p x) (multiplicity p y)\"\n    and   multiplicity_lcm: \"multiplicity p (lcm x y) = max (multiplicity p x) (multiplicity p y)\"\nproof -\n  have \"gcd x y = gcd_factorial x y\" by (rule gcd_eq_gcd_factorial)\n  also from assms have \"multiplicity p \\<dots> = min (multiplicity p x) (multiplicity p y)\"\n    by (simp add: count_prime_factorization_prime [symmetric] prime_factorization_gcd_factorial)\n  finally show \"multiplicity p (gcd x y) = min (multiplicity p x) (multiplicity p y)\" .\n  have \"lcm x y = lcm_factorial x y\" by (rule lcm_eq_lcm_factorial)\n  also from assms have \"multiplicity p \\<dots> = max (multiplicity p x) (multiplicity p y)\"\n    by (simp add: count_prime_factorization_prime [symmetric] prime_factorization_lcm_factorial)\n  finally show \"multiplicity p (lcm x y) = max (multiplicity p x) (multiplicity p y)\" .\nqed\n\nlemma gcd_lcm_distrib:\n  \"gcd x (lcm y z) = lcm (gcd x y) (gcd x z)\"\nproof (cases \"x = 0 \\<or> y = 0 \\<or> z = 0\")\n  case True\n  thus ?thesis\n    by (auto simp: lcm_proj1_if_dvd lcm_proj2_if_dvd)\nnext\n  case False\n  hence \"normalize (gcd x (lcm y z)) = normalize (lcm (gcd x y) (gcd x z))\"\n    by (intro associatedI prime_factorization_subset_imp_dvd)\n       (auto simp: lcm_eq_0_iff prime_factorization_gcd prime_factorization_lcm\n          subset_mset.inf_sup_distrib1)\n  thus ?thesis by simp\nqed\n\nlemma lcm_gcd_distrib:\n  \"lcm x (gcd y z) = gcd (lcm x y) (lcm x z)\"\nproof (cases \"x = 0 \\<or> y = 0 \\<or> z = 0\")\n  case True\n  thus ?thesis\n    by (auto simp: lcm_proj1_if_dvd lcm_proj2_if_dvd)\nnext\n  case False\n  hence \"normalize (lcm x (gcd y z)) = normalize (gcd (lcm x y) (lcm x z))\"\n    by (intro associatedI prime_factorization_subset_imp_dvd)\n       (auto simp: lcm_eq_0_iff prime_factorization_gcd prime_factorization_lcm\n          subset_mset.sup_inf_distrib1)\n  thus ?thesis by simp\nqed\n\nend\n\nclass factorial_ring_gcd = factorial_semiring_gcd + idom\nbegin\n\nsubclass ring_gcd ..\n\nsubclass idom_divide ..\n\nend\n\n\nclass factorial_semiring_multiplicative =\n  factorial_semiring + normalization_semidom_multiplicative\nbegin\n\nlemma normalize_prod_mset_primes:\n  \"(\\<And>p. p \\<in># A \\<Longrightarrow> prime p) \\<Longrightarrow> normalize (prod_mset A) = prod_mset A\"\nproof (induction A)\n  case (add p A)\n  hence \"prime p\" by simp\n  hence \"normalize p = p\" by simp\n  with add show ?case by (simp add: normalize_mult)\nqed simp_all\n\nlemma prod_mset_prime_factorization:\n  assumes \"x \\<noteq> 0\"\n  shows   \"prod_mset (prime_factorization x) = normalize x\"\n  using assms\n  by (induction x rule: prime_divisors_induct)\n     (simp_all add: prime_factorization_unit prime_factorization_times_prime\n                    is_unit_normalize normalize_mult)\n\nlemma prime_decomposition: \"unit_factor x * prod_mset (prime_factorization x) = x\"\n  by (cases \"x = 0\") (simp_all add: prod_mset_prime_factorization)\n\nlemma prod_prime_factors:\n  assumes \"x \\<noteq> 0\"\n  shows   \"(\\<Prod>p \\<in> prime_factors x. p ^ multiplicity p x) = normalize x\"\nproof -\n  have \"normalize x = prod_mset (prime_factorization x)\"\n    by (simp add: prod_mset_prime_factorization assms)\n  also have \"\\<dots> = (\\<Prod>p \\<in> prime_factors x. p ^ count (prime_factorization x) p)\"\n    by (subst prod_mset_multiplicity) simp_all\n  also have \"\\<dots> = (\\<Prod>p \\<in> prime_factors x. p ^ multiplicity p x)\"\n    by (intro prod.cong)\n      (simp_all add: assms count_prime_factorization_prime in_prime_factors_imp_prime)\n  finally show ?thesis ..\nqed\n\nlemma prime_factorization_unique'':\n  assumes S_eq: \"S = {p. 0 < f p}\"\n    and \"finite S\"\n    and S: \"\\<forall>p\\<in>S. prime p\" \"normalize 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)\"\nproof\n  define A where \"A = Abs_multiset f\"\n  from \\<open>finite S\\<close> S(1) have \"(\\<Prod>p\\<in>S. p ^ f p) \\<noteq> 0\" by auto\n  with S(2) have nz: \"n \\<noteq> 0\" by auto\n  from S_eq \\<open>finite S\\<close> have count_A: \"count A = f\"\n    unfolding A_def by (subst multiset.Abs_multiset_inverse) simp_all\n  from S_eq count_A have set_mset_A: \"set_mset A = S\"\n    by (simp only: set_mset_def)\n  from S(2) have \"normalize n = (\\<Prod>p\\<in>S. p ^ f p)\" .\n  also have \"\\<dots> = prod_mset A\" by (simp add: prod_mset_multiplicity S_eq set_mset_A count_A)\n  also from nz have \"normalize n = prod_mset (prime_factorization n)\"\n    by (simp add: prod_mset_prime_factorization)\n  finally have \"prime_factorization (prod_mset A) =\n                  prime_factorization (prod_mset (prime_factorization n))\" by simp\n  also from S(1) have \"prime_factorization (prod_mset A) = A\"\n    by (intro prime_factorization_prod_mset_primes) (auto simp: set_mset_A)\n  also have \"prime_factorization (prod_mset (prime_factorization n)) = prime_factorization n\"\n    by (intro prime_factorization_prod_mset_primes) auto\n  finally show \"S = prime_factors n\" by (simp add: set_mset_A [symmetric])\n\n  show \"(\\<forall>p. prime p \\<longrightarrow> f p = multiplicity p n)\"\n  proof safe\n    fix p :: 'a assume p: \"prime p\"\n    have \"multiplicity p n = multiplicity p (normalize n)\" by simp\n    also have \"normalize n = prod_mset A\"\n      by (simp add: prod_mset_multiplicity S_eq set_mset_A count_A S)\n    also from p set_mset_A S(1)\n    have \"multiplicity p \\<dots> = sum_mset (image_mset (multiplicity p) A)\"\n      by (intro prime_elem_multiplicity_prod_mset_distrib) auto\n    also from S(1) p\n    have \"image_mset (multiplicity p) A = image_mset (\\<lambda>q. if p = q then 1 else 0) A\"\n      by (intro image_mset_cong) (auto simp: set_mset_A multiplicity_self prime_multiplicity_other)\n    also have \"sum_mset \\<dots> = f p\"\n      by (simp add: semiring_1_class.sum_mset_delta' count_A)\n    finally show \"f p = multiplicity p n\" ..\n  qed\nqed\n\nlemma divides_primepow:\n  assumes \"prime p\" and \"a dvd p ^ n\"\n  obtains m where \"m \\<le> n\" and \"normalize a = p ^ m\"\n  using divides_primepow_weak[OF assms] that assms\n  by (auto simp add: normalize_power)\n\nlemma Ex_other_prime_factor:\n  assumes \"n \\<noteq> 0\" and \"\\<not>(\\<exists>k. normalize n = p ^ k)\" \"prime p\"\n  shows   \"\\<exists>q\\<in>prime_factors n. q \\<noteq> p\"\nproof (rule ccontr)\n  assume *: \"\\<not>(\\<exists>q\\<in>prime_factors n. q \\<noteq> p)\"\n  have \"normalize n = (\\<Prod>p\\<in>prime_factors n. p ^ multiplicity p n)\"\n    using assms(1) by (intro prod_prime_factors [symmetric]) auto\n  also from * have \"\\<dots> = (\\<Prod>p\\<in>{p}. p ^ multiplicity p n)\"\n    using assms(3) by (intro prod.mono_neutral_left) (auto simp: prime_factors_multiplicity)\n  finally have \"normalize n = p ^ multiplicity p n\" by auto\n  with assms show False by auto\nqed\n\ntext \\<open>Now a string of results due to Jakub K\u0105dzio\u0142ka\\<close>\n\nlemma multiplicity_dvd_iff_dvd:\n assumes \"x \\<noteq> 0\"\n shows \"p^k dvd x \\<longleftrightarrow> p^k dvd p^multiplicity p x\"\nproof (cases \"is_unit p\")\n case True\n then have \"is_unit (p^k)\"\n   using is_unit_power_iff by simp\n hence \"p^k dvd x\"\n   by auto\n moreover from \\<open>is_unit p\\<close> have \"p^k dvd p^multiplicity p x\"\n   using multiplicity_unit_left is_unit_power_iff by simp\n ultimately show ?thesis by simp\nnext\n case False\n show ?thesis\n proof (cases \"p = 0\")\n   case True\n   then have \"p^multiplicity p x = 1\"\n     by simp\n   moreover have \"p^k dvd x \\<Longrightarrow> k = 0\"\n   proof (rule ccontr)\n     assume \"p^k dvd x\" and \"k \\<noteq> 0\"\n     with \\<open>p = 0\\<close> have \"p^k = 0\" by auto\n     with \\<open>p^k dvd x\\<close> have \"0 dvd x\" by auto\n     hence \"x = 0\" by auto\n     with \\<open>x \\<noteq> 0\\<close> show False by auto\n   qed\n   ultimately show ?thesis\n     by (auto simp add: is_unit_power_iff \\<open>\\<not> is_unit p\\<close>)\n next\n   case False\n   with \\<open>x \\<noteq> 0\\<close> \\<open>\\<not> is_unit p\\<close> show ?thesis\n     by (simp add: power_dvd_iff_le_multiplicity dvd_power_iff multiplicity_same_power)\n qed\nqed\n\nlemma multiplicity_decomposeI:\n assumes \"x = p^k * x'\" and \"\\<not> p dvd x'\" and \"p \\<noteq> 0\"\n shows \"multiplicity p x = k\"\n  using assms local.multiplicity_eqI local.power_Suc2 by force\n\nlemma multiplicity_sum_lt:\n assumes \"multiplicity p a < multiplicity p b\" \"a \\<noteq> 0\" \"b \\<noteq> 0\"\n shows \"multiplicity p (a + b) = multiplicity p a\"\nproof -\n let ?vp = \"multiplicity p\"\n have unit: \"\\<not> is_unit p\"\n proof\n   assume \"is_unit p\"\n   then have \"?vp a = 0\" and \"?vp b = 0\" using multiplicity_unit_left by auto\n   with assms show False by auto\n qed\n\n from multiplicity_decompose' obtain a' where a': \"a = p^?vp a * a'\" \"\\<not> p dvd a'\"\n   using unit assms by metis\n from multiplicity_decompose' obtain b' where b': \"b = p^?vp b * b'\"\n   using unit assms by metis\n\n show \"?vp (a + b) = ?vp a\"\n proof (rule multiplicity_decomposeI)\n   let ?k = \"?vp b - ?vp a\"\n   from assms have k: \"?k > 0\" by simp\n   with b' have \"b = p^?vp a * p^?k * b'\"\n     by (simp flip: power_add)\n   with a' show *: \"a + b = p^?vp a * (a' + p^?k * b')\"\n     by (simp add: ac_simps distrib_left)\n   moreover show \"\\<not> p dvd a' + p^?k * b'\"\n     using a' k dvd_add_left_iff by auto\n   show \"p \\<noteq> 0\" using assms by auto\n qed\nqed\n\ncorollary multiplicity_sum_min:\n assumes \"multiplicity p a \\<noteq> multiplicity p b\" \"a \\<noteq> 0\" \"b \\<noteq> 0\"\n shows \"multiplicity p (a + b) = min (multiplicity p a) (multiplicity p b)\"\nproof -\n let ?vp = \"multiplicity p\"\n from assms have \"?vp a < ?vp b \\<or> ?vp a > ?vp b\"\n   by auto\n then show ?thesis\n   by (metis assms multiplicity_sum_lt min.commute add_commute min.strict_order_iff)    \nqed\n\nend\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/Computational_Algebra/Factorial_Ring.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8479677699040321, "lm_q2_score": 0.8267117983401363, "lm_q1q2_score": 0.7010249599918373}}
{"text": "theory HOModel\nimports Main\nbegin\n\ndeclare split_if_asm [split] -- {* perform default perform case splitting on conditionals *}\n\nsection {* Heard-Of Algorithms *}\n\nsubsection {* The Consensus Problem *}\n\ntext {*\n  We are interested in the verification of fault-tolerant distributed algorithms.\n  The Consensus problem is paradigmatic in this area. Stated\n  informally, it assumes that all processes participating in the algorithm\n  initially propose some value, and that they may at some point decide some value.\n  It is required that every process eventually decides, and that all processes\n  must decide the same value.\n\n  More formally, we represent runs of algorithms as @{text \\<omega>}-sequences of\n  configurations (vectors of process states). Hence, a run is modeled as\n  a function of type @{text \"nat \\<Rightarrow> 'proc \\<Rightarrow> 'pst\"} where type variables \n  @{text \"'proc\"} and @{text \"'pst\"} represent types of processes and process\n  states, respectively. The Consensus property is expressed with respect\n  to a collection @{text \"vals\"} of initially proposed values (one per process) \n  and an observer function @{text \"dec::'pst \\<Rightarrow> val option\"} that retrieves the decision\n  (if any) from a process state. The Consensus problem is stated as the conjunction\n  of the following properties:\n  \\begin{description}\n  \\item[Integrity.] Processes can only decide initially proposed values.\n  \\item[Agreement.] Whenever processes @{text p} and @{text q} decide,\n    their decision values must be the same. (In particular, process @{text p}\n    may never change the value it decides, which is referred to as Irrevocability.)\n  \\item[Termination.] Every process decides eventually.\n  \\end{description}\n\n  The above properties are sometimes only required of non-faulty processes, since\n  nothing can be required of a faulty process.\n  The Heard-Of model does not attribute faults to processes, and therefore the\n  above formulation is appropriate in this framework.\n*}\n\ntype_synonym\n  ('proc,'pst) run = \"nat \\<Rightarrow> 'proc \\<Rightarrow> 'pst\"\n\ndefinition\n  consensus :: \"('proc \\<Rightarrow> 'val) \\<Rightarrow> ('pst \\<Rightarrow> 'val option) \\<Rightarrow> ('proc,'pst) run \\<Rightarrow> bool\"\nwhere\n  \"consensus vals dec rho \\<equiv>\n     (\\<forall>n p v. dec (rho n p) = Some v \\<longrightarrow> v \\<in> range vals)\n   \\<and> (\\<forall>m n p q v w. dec (rho m p) = Some v \\<and> dec (rho n q) = Some w \n         \\<longrightarrow> v = w)\n   \\<and> (\\<forall>p. \\<exists>n. dec (rho n p) \\<noteq> None)\"\n\ntext {*\n  A variant of the Consensus problem replaces the Integrity requirement by\n  \\begin{description}\n  \\item[Validity.] If all processes initially propose the same value @{text \"v\"}\n    then every process may only decide @{text \"v\"}.\n  \\end{description}\n*}\n\ndefinition weak_consensus where\n  \"weak_consensus vals dec rho \\<equiv>\n     (\\<forall>v. (\\<forall>p. vals p = v) \\<longrightarrow> (\\<forall>n p w. dec (rho n p) = Some w \\<longrightarrow> w = v))\n   \\<and> (\\<forall>m n p q v w. dec (rho m p) = Some v \\<and> dec (rho n q) = Some w \n         \\<longrightarrow> v = w)\n   \\<and> (\\<forall>p. \\<exists>n. dec (rho n p) \\<noteq> None)\"\n\ntext {*\n  Clearly, @{text \"consensus\"} implies @{text \"weak_consensus\"}.\n*}\n\nlemma consensus_then_weak_consensus:\n  assumes \"consensus vals dec rho\"\n  shows \"weak_consensus vals dec rho\"\n  using assms by (auto simp: consensus_def weak_consensus_def image_def)\n\ntext {*\n  Over Boolean values (``binary Consensus''), @{text weak_consensus}\n  implies @{text consensus}, hence the two problems are equivalent.\n  In fact, this theorem holds more generally whenever at most two\n  different values are proposed initially (i.e., @{text \"card (range vals) \\<le> 2\"}).\n*}\n\nlemma binary_weak_consensus_then_consensus:\n  assumes bc: \"weak_consensus (vals::'proc \\<Rightarrow> bool) dec rho\"\n  shows \"consensus vals dec rho\"\nproof -\n  { -- {* Show the Integrity property, the other conjuncts are the same. *}\n    fix n p v\n    assume dec: \"dec (rho n p) = Some v\"\n    have \"v \\<in> range vals\"\n    proof (cases \"\\<exists>w. \\<forall>p. vals p = w\")\n      case True\n      then obtain w where w: \"\\<forall>p. vals p = w\" ..\n      with bc have \"dec (rho n p) \\<in> {Some w, None}\" by (auto simp: weak_consensus_def)\n      with dec w show ?thesis by (auto simp: image_def)\n    next\n      case False\n      -- {* In this case both possible values occur in @{text \"vals\"}, and the result is trivial. *}\n      thus ?thesis by (auto simp: image_def)\n    qed\n  } note integrity = this\n  from bc show ?thesis\n    unfolding consensus_def weak_consensus_def by (auto elim!: integrity)\nqed\n\ntext {*\n  The algorithms that we are going to verify solve the Consensus or weak Consensus\n  problem, under different hypotheses about the kinds and number of faults.\n*}\n\n\nsubsection {* A Generic Representation of Heard-Of Algorithms *}\n\ntext {*\n  Charron-Bost and Schiper~\\cite{charron:heardof} introduce\n  the Heard-Of (HO) model for representing fault-tolerant\n  distributed algorithms. In this model, algorithms execute in communication-closed\n  rounds: at any round~$r$, processes only receive messages that were sent for\n  that round. For every process~$p$ and round~$r$, the ``heard-of set'' $HO(p,r)$\n  denotes the set of processes from which~$p$ receives a message in round~$r$.\n  Since every process is assumed to send a message to all processes in each round,\n  the complement of $HO(p,r)$ represents the set of faults that may affect~$p$ in\n  round~$r$ (messages that were not received, e.g. because the sender crashed,\n  because of a network problem etc.).\n\n  The HO model expresses hypotheses on the faults tolerated by an algorithm\n  through ``communication predicates'' that constrain the sets $HO(p,r)$\n  that may occur during an execution. Charron-Bost and Schiper show that\n  standard fault models can be represented in this form.\n\n  The original HO model is sufficient for representing algorithms\n  tolerating benign failures such as process crashes or message loss. A later\n  extension for algorithms tolerating Byzantine (or value) failures~\\cite{biely:tolerating} \n  adds a second collection of sets $SHO(p,r) \\subseteq HO(p,r)$ that contain those\n  processes $q$ from which process $p$ receives the message that $q$ was indeed\n  supposed to send for round $r$ according to the algorithm. In other words, \n  messages from processes in $HO(p,r) \\setminus SHO(p,r)$ were corrupted, be it\n  due to errors during message transmission or because of the sender was faulty or\n  lied deliberately. For both benign and Byzantine errors, the HO model registers\n  the fault but does not try to identify the faulty component (i.e., designate the\n  sending or receiving process, or the communication channel as the ``culprit'').\n\n  Executions of HO algorithms are defined with respect to collections\n  $HO(p,r)$ and $SHO(p,r)$. However, the code of a process does not have\n  access to these sets. In particular, process $p$ has no way of determining\n  if a message it received from another process $q$ corresponds to what $q$\n  should have sent or if it has been corrupted.\n\n  Certain algorithms rely on the assignment of ``coordinator'' processes for\n  each round. Just as the collections $HO(p,r)$, the definitions assume an\n  external coordinator assignment such that $coord(p,r)$ denotes the coordinator\n  of process $p$ and round $r$. Again, the correctness of algorithms may depend\n  on hypotheses about coordinator assignments -- e.g., it may be assumed that\n  processes agree sufficiently often on who the current coordinator is.\n\n  The following definitions provide a generic representation of HO and SHO algorithms\n  in Isabelle/HOL. A (coordinated) HO algorithm is described by the following parameters:\n  \\begin{itemize}\n  \\item a finite type @{text 'proc} of processes,\n  \\item a type @{text 'pst} of local process states,\n  \\item a type @{text 'msg} of messages sent in the course of the algorithm,\n  \\item a predicate @{text CinitState} such that @{text \"CinitState p st crd\"} is\n    true precisely of the initial states @{text st} of process @{text p}, assuming\n    that @{text crd} is the initial coordinator of @{text p},\n  \\item a function @{text sendMsg} where @{text \"sendMsg r p q st\"} yields\n    the message that process @{text p} sends to process @{text q} at round\n    @{text r}, given its local state @{text st}, and\n  \\item a predicate @{text CnextState} where @{text \"CnextState r p st msgs crd st'\"}\n    characterizes the successor states @{text st'} of process @{text p} at round\n    @{text r}, given current state @{text st}, the vector\n    @{text \"msgs :: 'proc \\<Rightarrow> 'msg option\"} of messages that @{text p} received at\n    round @{text r} (@{text \"msgs q = None\"} indicates that no message has been\n    received from process @{text q}),\n    and process @{text crd} as the coordinator for the following round.\n  \\end{itemize}\n  Note that every process can store the coordinator for the current round in its\n  local state, and it is therefore not necessary to make the coordinator a parameter\n  of the message sending function @{text sendMsg}.\n\n  We represent an algorithm by a record as follows.\n*}\n\nrecord ('proc, 'pst, 'msg) CHOAlgorithm =\n  CinitState ::  \"'proc \\<Rightarrow> 'pst \\<Rightarrow> 'proc \\<Rightarrow> bool\"\n  sendMsg ::   \"nat \\<Rightarrow> 'proc \\<Rightarrow> 'proc \\<Rightarrow> 'pst \\<Rightarrow> 'msg\"\n  CnextState :: \"nat \\<Rightarrow> 'proc \\<Rightarrow> 'pst \\<Rightarrow> ('proc \\<Rightarrow> 'msg option) \\<Rightarrow> 'proc \\<Rightarrow> 'pst \\<Rightarrow> bool\"\n\ntext {*\n  For non-coordinated HO algorithms, the coordinator argument of functions\n  @{text CinitState} and @{text CnextState} is irrelevant, and we\n  define utility functions that omit that argument.\n*}\n\ndefinition isNCAlgorithm where\n  \"isNCAlgorithm alg \\<equiv> \n      (\\<forall>p st crd crd'. CinitState alg p st crd = CinitState alg p st crd')\n   \\<and> (\\<forall>r p st msgs crd crd' st'. CnextState alg r p st msgs crd st'\n                               = CnextState alg r p st msgs crd' st')\"\n\ndefinition initState where\n  \"initState alg p st \\<equiv> CinitState alg p st undefined\"\n\ndefinition nextState where\n  \"nextState alg r p st msgs st' \\<equiv> CnextState alg r p st msgs undefined st'\"\n\ntext {*\n  A \\emph{heard-of assignment} associates a set of processes with each\n  process. The following type is used to represent the collections $HO(p,r)$\n  and $SHO(p,r)$ for fixed round $r$.\n%\n  Similarly, a \\emph{coordinator assignment} associates a process (its coordinator)\n  to each process.\n*}\n\ntype_synonym\n  'proc HO = \"'proc \\<Rightarrow> 'proc set\"\n\ntype_synonym\n  'proc coord = \"'proc \\<Rightarrow> 'proc\"\n\ntext {*\n  An execution of an HO algorithm is defined with respect to HO and SHO\n  assignments that indicate, for every round @{text r} and every process @{text p},\n  from which sender processes @{text p} receives messages (resp., uncorrupted\n  messages) at round @{text r}.\n\n%% That's the intention, but we don't enforce this in the definitions.\n%  Obviously, SHO sets are always included in HO sets, for the same process and round.\n\n  The following definitions formalize this idea. We define ``coarse-grained''\n  executions whose unit of atomicity is the round of execution. At each round,\n  the entire collection of processes performs a transition according to the\n  @{text CnextState} function of the algorithm. Consequently, a system state is\n  simply described by a configuration, i.e. a function assigning a process state\n  to every process. This definition of executions may appear surprising for an\n  asynchronous distributed system, but it simplifies system verification,\n  compared to a ``fine-grained'' execution model that records individual events\n  such as message sending and reception or local transitions. We will justify\n  later why the ``coarse-grained'' model is sufficient for verifying interesting\n  correctness properties of HO algorithms.\n\n  The predicate @{text CSHOinitConfig} describes the possible initial configurations\n  for algorithm @{text A} (remember that a configuration is a function that assigns\n  local states to every process).\n*}\n\ndefinition CHOinitConfig where\n  \"CHOinitConfig A cfg (coord::'proc coord) \\<equiv> \\<forall>p. CinitState A p (cfg p) (coord p)\"\n\ntext {*\n  Given the current configuration @{text cfg} and the HO and SHO sets @{text HOp}\n  and @{text SHOp} for process @{text p} at round @{text r}, the function\n  @{text SHOmsgVectors} computes the set of possible vectors of messages that\n  process @{text p} may receive. For processes @{text \"q \\<notin> HOp\"}, @{text p} \n  receives no message (represented as value @{text None}). For processes\n  @{text \"q \\<in> SHOp\"}, @{text p} receives the message that @{text q} computed\n  according to the @{text sendMsg} function of the algorithm. For the remaining\n  processes @{text \"q \\<in> HOp - SHOp\"}, @{text p} may receive some arbitrary value.\n*}\n\ndefinition SHOmsgVectors where\n  \"SHOmsgVectors A r p cfg HOp SHOp \\<equiv>\n   {\\<mu>. (\\<forall>q. q \\<in> HOp \\<longleftrightarrow> \\<mu> q \\<noteq> None)\n     \\<and> (\\<forall>q. q \\<in> SHOp \\<inter> HOp \\<longrightarrow> \\<mu> q = Some (sendMsg A r q p (cfg q)))}\"\n\ntext {*\n  Predicate @{text CSHOnextConfig} uses the preceding function and the algorithm's\n  @{text CnextState} function to characterize the possible successor configurations\n  in a coarse-grained step, and predicate @{text CSHORun} defines (coarse-grained)\n  executions @{text rho} of an HO algorithm.\n*}\n\ndefinition CSHOnextConfig where\n  \"CSHOnextConfig A r cfg HO SHO coord cfg' \\<equiv>\n   \\<forall>p. \\<exists>\\<mu> \\<in> SHOmsgVectors A r p cfg (HO p) (SHO p).\n          CnextState A r p (cfg p) \\<mu> (coord p) (cfg' p)\"\n\ndefinition CSHORun where\n  \"CSHORun A rho HOs SHOs coords \\<equiv>\n     CHOinitConfig A (rho 0) (coords 0)\n   \\<and> (\\<forall>r. CSHOnextConfig A r (rho r) (HOs r) (SHOs r) (coords (Suc r))\n                             (rho (Suc r)))\"\n\ntext {*\n  For non-coordinated algorithms. the @{text coord} arguments of the above functions\n  are irrelevant. We define similar functions that omit that argument, and relate\n  them to the above utility functions for these algorithms.\n*}\n\ndefinition HOinitConfig where\n  \"HOinitConfig A cfg \\<equiv> CHOinitConfig A cfg (\\<lambda>q. undefined)\"\n\n\n\ndefinition SHOnextConfig where\n  \"SHOnextConfig A r cfg HO SHO cfg' \\<equiv>\n   CSHOnextConfig A r cfg HO SHO (\\<lambda>q. undefined) cfg'\"\n\nlemma SHOnextConfig_eq:\n  \"SHOnextConfig A r cfg HO SHO cfg' =\n   (\\<forall>p. \\<exists>\\<mu> \\<in> SHOmsgVectors A r p cfg (HO p) (SHO p).\n             nextState A r p (cfg p) \\<mu> (cfg' p))\"\n  by (auto simp: SHOnextConfig_def CSHOnextConfig_def SHOmsgVectors_def nextState_def)\n\ndefinition SHORun where\n  \"SHORun A rho HOs SHOs \\<equiv>\n   CSHORun A rho HOs SHOs (\\<lambda>r q. undefined)\"\n\nlemma SHORun_eq:\n  \"SHORun A rho HOs SHOs =\n     (HOinitConfig A (rho 0)\n   \\<and> (\\<forall>r. SHOnextConfig A r (rho r) (HOs r) (SHOs r) (rho (Suc r))))\"\n  by (auto simp: SHORun_def CSHORun_def HOinitConfig_def SHOnextConfig_def)\n\ntext {*\n  Algorithms designed to tolerate benign failures are not subject to\n  message corruption, and therefore the SHO sets are irrelevant (more formally,\n  each SHO set equals the corresponding HO set). We define corresponding\n  special cases of the definitions of successor configurations and of runs,\n  and prove that these are equivalent to simpler definitions that will be more\n  useful in proofs. In particular, the vector of messages received by a process\n  in a benign execution is uniquely determined from the current configuration\n  and the HO sets.\n*}\n\ndefinition HOrcvdMsgs where\n  \"HOrcvdMsgs A r p HO cfg \\<equiv>\n   \\<lambda>q. if q \\<in> HO then Some (sendMsg A r q p (cfg q)) else None\"\n\nlemma SHOmsgVectors_HO:\n  \"SHOmsgVectors A r p cfg HO HO = {HOrcvdMsgs A r p HO cfg}\"\n  unfolding SHOmsgVectors_def HOrcvdMsgs_def by auto\n\ntext {* With coordinators *}\n\ndefinition CHOnextConfig where\n  \"CHOnextConfig A r cfg HO coord cfg' \\<equiv> \n   CSHOnextConfig A r cfg HO HO coord cfg'\"\n\nlemma CHOnextConfig_eq:\n  \"CHOnextConfig A r cfg HO coord cfg' =\n   (\\<forall>p. CnextState A r p (cfg p) (HOrcvdMsgs A r p (HO p) cfg) \n                   (coord p) (cfg' p))\"\n  by (auto simp: CHOnextConfig_def CSHOnextConfig_def SHOmsgVectors_HO)\n\ndefinition CHORun where\n  \"CHORun A rho HOs coords \\<equiv> CSHORun A rho HOs HOs coords\"\n\nlemma CHORun_eq:\n  \"CHORun A rho HOs coords = \n     (CHOinitConfig A (rho 0) (coords 0)\n      \\<and> (\\<forall>r. CHOnextConfig A r (rho r) (HOs r) (coords (Suc r)) (rho (Suc r))))\"\n  by (auto simp: CHORun_def CSHORun_def CHOinitConfig_def CHOnextConfig_def)\n\ntext {* Without coordinators *}\ndefinition HOnextConfig where\n  \"HOnextConfig A r cfg HO cfg' \\<equiv> SHOnextConfig A r cfg HO HO cfg'\"\n\nlemma HOnextConfig_eq:\n  \"HOnextConfig A r cfg HO cfg' =\n   (\\<forall>p. nextState A r p (cfg p) (HOrcvdMsgs A r p (HO p) cfg) (cfg' p))\"\n  by (auto simp: HOnextConfig_def SHOnextConfig_eq SHOmsgVectors_HO)\n\ndefinition HORun where\n  \"HORun A rho HOs \\<equiv> SHORun A rho HOs HOs\"\n\nlemma HORun_eq:\n  \"HORun A rho HOs = \n   (  HOinitConfig A (rho 0)\n    \\<and> (\\<forall>r. HOnextConfig A r (rho r) (HOs r) (rho (Suc r))))\"\n  by (auto simp: HORun_def SHORun_eq HOnextConfig_def)\n\n\ntext {*\n  The following derived proof rules are immediate consequences of\n  the definition of @{text CHORun}; they simplify automatic reasoning.\n*}\n\nlemma CHORun_0:\n  assumes \"CHORun A rho HOs coords\" \n      and \"\\<And>cfg. CHOinitConfig A cfg (coords 0) \\<Longrightarrow> P cfg\"\n  shows \"P (rho 0)\"\nusing assms unfolding CHORun_eq by blast\n\nlemma CHORun_Suc:\n  assumes \"CHORun A rho HOs coords\"\n  and \"\\<And>r. CHOnextConfig A r (rho r) (HOs r) (coords (Suc r)) (rho (Suc r))\n            \\<Longrightarrow> P r\"\n  shows \"P n\"\nusing assms unfolding CHORun_eq by blast\n\nlemma CHORun_induct:\n  assumes run: \"CHORun A rho HOs coords\"\n  and init: \"CHOinitConfig A (rho 0) (coords 0) \\<Longrightarrow> P 0\"\n  and step: \"\\<And>r. \\<lbrakk> P r; CHOnextConfig A r (rho r) (HOs r) (coords (Suc r)) \n                                      (rho (Suc r)) \\<rbrakk> \\<Longrightarrow> P (Suc r)\"\n  shows \"P n\"\nusing run unfolding CHORun_eq by (induct n, auto elim: init step)\n\ntext {*\n  Because algorithms will not operate for arbitrary HO, SHO, and coordinator\n  assignments, these are constrained by a \\emph{communication predicate}.\n  For convenience, we split this predicate into a \\emph{per Round} part that\n  is expected to hold at every round and a \\emph{global} part that must hold\n  of the sequence of (S)HO assignments and may thus express liveness assumptions.\n\n  In the parlance of~\\cite{charron:heardof}, a \\emph{HO machine} is an HO algorithm\n  augmented with a communication predicate. We therefore define (C)(S)HO machines as\n  the corresponding extensions of the record defining an HO algorithm.\n*}\n\nrecord ('proc, 'pst, 'msg) HOMachine = \"('proc, 'pst, 'msg) CHOAlgorithm\" +\n  HOcommPerRd::\"'proc HO \\<Rightarrow> bool\"\n  HOcommGlobal::\"(nat \\<Rightarrow> 'proc HO) \\<Rightarrow> bool\"\n\nrecord ('proc, 'pst, 'msg) CHOMachine = \"('proc, 'pst, 'msg) CHOAlgorithm\" +\n  CHOcommPerRd::\"nat \\<Rightarrow> 'proc HO \\<Rightarrow> 'proc coord \\<Rightarrow> bool\"\n  CHOcommGlobal::\"(nat \\<Rightarrow> 'proc HO) \\<Rightarrow> (nat \\<Rightarrow> 'proc coord) \\<Rightarrow> bool\"\n\nrecord ('proc, 'pst, 'msg) SHOMachine = \"('proc, 'pst, 'msg) CHOAlgorithm\" +\n  SHOcommPerRd::\"('proc HO) \\<Rightarrow> ('proc HO) \\<Rightarrow> bool\"\n  SHOcommGlobal::\"(nat \\<Rightarrow> 'proc HO) \\<Rightarrow> (nat \\<Rightarrow> 'proc HO) \\<Rightarrow> bool\"\n\nrecord ('proc, 'pst, 'msg) CSHOMachine = \"('proc, 'pst, 'msg) CHOAlgorithm\" +\n  CSHOcommPerRd::\"('proc HO) \\<Rightarrow> ('proc HO) \\<Rightarrow> 'proc coord \\<Rightarrow> bool\"\n  CSHOcommGlobal::\"(nat \\<Rightarrow> 'proc HO) \\<Rightarrow> (nat \\<Rightarrow> 'proc HO)\n                                     \\<Rightarrow> (nat \\<Rightarrow> 'proc coord) \\<Rightarrow> bool\"\n\nend -- {* theory HOModel *}\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/HOModel.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8267117855317474, "lm_q2_score": 0.847967764140929, "lm_q1q2_score": 0.701024944366311}}
{"text": "(*  Title:      HOL/ex/Induction_Schema.thy\n    Author:     Alexander Krauss, TU Muenchen\n*)\n\nsection {* Examples of automatically derived induction rules *}\n\ntheory Induction_Schema\nimports Main\nbegin\n\nsubsection {* Some simple induction principles on nat *}\n\nlemma nat_standard_induct: (* cf. Nat.thy *)\n  \"\\<lbrakk>P 0; \\<And>n. P n \\<Longrightarrow> P (Suc n)\\<rbrakk> \\<Longrightarrow> P x\"\nby induction_schema (pat_completeness, lexicographic_order)\n\nlemma nat_induct2:\n  \"\\<lbrakk> P 0; P (Suc 0); \\<And>k. P k ==> P (Suc k) ==> P (Suc (Suc k)) \\<rbrakk>\n  \\<Longrightarrow> P n\"\nby induction_schema (pat_completeness, lexicographic_order)\n\nlemma minus_one_induct:\n  \"\\<lbrakk>\\<And>n::nat. (n \\<noteq> 0 \\<Longrightarrow> P (n - 1)) \\<Longrightarrow> P n\\<rbrakk> \\<Longrightarrow> P x\"\nby induction_schema (pat_completeness, lexicographic_order)\n\ntheorem diff_induct: (* cf. Nat.thy *)\n  \"(!!x. P x 0) ==> (!!y. P 0 (Suc y)) ==>\n    (!!x y. P x y ==> P (Suc x) (Suc y)) ==> P m n\"\nby induction_schema (pat_completeness, lexicographic_order)\n\nlemma list_induct2': (* cf. List.thy *)\n  \"\\<lbrakk> P [] [];\n  \\<And>x xs. P (x#xs) [];\n  \\<And>y ys. P [] (y#ys);\n   \\<And>x xs y ys. P xs ys  \\<Longrightarrow> P (x#xs) (y#ys) \\<rbrakk>\n \\<Longrightarrow> P xs ys\"\nby induction_schema (pat_completeness, lexicographic_order)\n\ntheorem even_odd_induct:\n  assumes \"R 0\"\n  assumes \"Q 0\"\n  assumes \"\\<And>n. Q n \\<Longrightarrow> R (Suc n)\"\n  assumes \"\\<And>n. R n \\<Longrightarrow> Q (Suc n)\"\n  shows \"R n\" \"Q n\"\n  using assms\nby induction_schema (pat_completeness+, lexicographic_order)\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/ex/Induction_Schema.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677583778257, "lm_q2_score": 0.8267117876664789, "lm_q1q2_score": 0.7010249414120691}}
{"text": "(*  Author: Lukas Bulwahn <lukas.bulwahn-at-gmail.com> *)\n\nsection \\<open>Injections from A to B up to a Permutation of A\\<close>\n\ntheory Twelvefold_Way_Entry5\nimports\n  Equiv_Relations_on_Functions\nbegin\n\nsubsection \\<open>Definition of Bijections\\<close>\n\ndefinition subset_of :: \"'a set \\<Rightarrow> ('a  \\<Rightarrow> 'b) set \\<Rightarrow> 'b set\"\nwhere\n  \"subset_of A F = univ (\\<lambda>f. f ` A) F\"\n\ndefinition functions_of :: \"'a set \\<Rightarrow> 'b set \\<Rightarrow> ('a \\<Rightarrow> 'b) set\"\nwhere\n  \"functions_of A B = {f \\<in> A \\<rightarrow>\\<^sub>E B. f ` A = B}\"\n\nsubsection \\<open>Properties for Bijections\\<close>\n\nlemma functions_of_eq:\n  assumes \"finite A\"\n  assumes \"f \\<in> {f \\<in> A \\<rightarrow>\\<^sub>E B. inj_on f A}\"\n  shows \"functions_of A (f ` A) = domain_permutation A B `` {f}\"\nproof\n  have bij: \"bij_betw f A (f ` A)\"\n    using assms by (simp add: bij_betw_imageI)\n  show \"functions_of A (f ` A) \\<subseteq> domain_permutation A B `` {f}\"\n  proof\n    fix f'\n    assume \"f' \\<in> functions_of A (f ` A)\"\n    from this have \"f' \\<in> A \\<rightarrow>\\<^sub>E f ` A\" and \"f' ` A = f ` A\"\n      unfolding functions_of_def by auto\n    from this assms have \"f' \\<in> A \\<rightarrow>\\<^sub>E B\" and \"inj_on f A\"\n      using PiE_mem by fastforce+\n    moreover have \"\\<exists>p. p permutes A \\<and> (\\<forall>x\\<in>A. f x = f' (p x))\"\n    proof\n      let ?p = \"\\<lambda>x. if x \\<in> A then inv_into A f' (f x) else x\"\n      show \"?p permutes A \\<and> (\\<forall>x\\<in>A. f x = f' (?p x))\"\n      proof\n        show \"?p permutes A\"\n        proof (rule bij_imp_permutes)\n          show \"bij_betw ?p A A\"\n          proof (rule bij_betw_imageI)\n            show \"inj_on ?p A\"\n            proof (rule inj_onI)\n              fix a a'\n              assume \"a \\<in> A\" \"a' \\<in> A\" \"?p a = ?p a'\"\n              from this have \"inv_into A f' (f a) = inv_into A f' (f a')\" by auto\n              from this \\<open>a \\<in> A\\<close> \\<open>a' \\<in> A\\<close> \\<open>f' ` A = f ` A\\<close> have \"f a = f a'\"\n                using inv_into_injective by fastforce\n              from this \\<open>a \\<in> A\\<close> \\<open>a' \\<in> A\\<close> show \"a = a'\"\n                by (metis bij bij_betw_inv_into_left)\n            qed\n          next\n            show \"?p ` A = A\"\n            proof\n              show \"?p ` A \\<subseteq> A\"\n                using \\<open>f' ` A = f ` A\\<close> by (simp add: image_subsetI inv_into_into)\n            next\n              show \"A \\<subseteq> ?p ` A\"\n              proof\n                fix a\n                assume \"a \\<in> A\"\n                have \"inj_on f' A\"\n                  using \\<open>finite A\\<close> \\<open>f' ` A = f ` A\\<close> \\<open>inj_on f A\\<close>\n                  by (simp add: card_image eq_card_imp_inj_on)\n                from \\<open>a \\<in> A\\<close> \\<open>f' ` A = f ` A\\<close> have \"inv_into A f (f' a) \\<in> A\"\n                  by (metis image_eqI inv_into_into)\n                moreover have \"a = inv_into A f' (f (inv_into A f (f' a)))\"\n                  using \\<open>a \\<in> A\\<close> \\<open>f' ` A = f ` A\\<close> \\<open>inj_on f' A\\<close>\n                  by (metis f_inv_into_f image_eqI inv_into_f_f)\n                ultimately show \"a \\<in> ?p ` A\" by auto\n              qed\n            qed\n          qed\n        next\n          fix x\n          assume \"x \\<notin> A\"\n          from this show \"?p x = x\" by simp\n        qed\n      next\n        from \\<open>f' ` A = f ` A\\<close> show \"\\<forall>x\\<in>A. f x = f' (?p x)\"\n          by (simp add: f_inv_into_f)\n      qed\n    qed\n    moreover have \"f \\<in> A \\<rightarrow>\\<^sub>E B\" using assms by auto\n    ultimately show \"f' \\<in> domain_permutation A B `` {f}\"\n      unfolding domain_permutation_def by auto\n  qed\nnext\n  show \"domain_permutation A B `` {f} \\<subseteq> functions_of A (f ` A)\"\n  proof\n    fix f'\n    assume \"f' \\<in> domain_permutation A B `` {f}\"\n    from this obtain p where p: \"p permutes A\" \"\\<forall>x\\<in>A. f x = f' (p x)\"\n      and \"f \\<in> A \\<rightarrow>\\<^sub>E B\" \"f' \\<in> A \\<rightarrow>\\<^sub>E B\"\n      unfolding domain_permutation_def by auto\n    have \"f' ` A = f ` A\"\n    proof\n      show \"f' ` A \\<subseteq> f ` A\"\n      proof\n        fix x\n        assume \"x \\<in> f' ` A\"\n        from this obtain x' where \"x = f' x'\" and \"x' \\<in> A\" ..\n        from this have \"x = f (inv p x')\"\n          using p by (metis (mono_tags, lifting) permutes_in_image permutes_inverses(1))\n        moreover have \"inv p x' \\<in> A\"\n          using p \\<open>x' \\<in> A\\<close> by (simp add: permutes_in_image permutes_inv)\n        ultimately show \"x \\<in> f ` A\" ..\n      qed\n    next\n      show \"f ` A \\<subseteq> f' ` A\"\n        using p permutes_in_image by fastforce\n    qed\n    moreover from this \\<open>f' \\<in> A \\<rightarrow>\\<^sub>E B\\<close> have \"f' \\<in> A \\<rightarrow>\\<^sub>E f ` A\" by auto\n    ultimately show \"f' \\<in> functions_of A (f ` A)\"\n      unfolding functions_of_def by auto\n  qed\nqed\n\nlemma subset_of:\n  assumes \"F \\<in> {f \\<in> A \\<rightarrow>\\<^sub>E B. inj_on f A} // domain_permutation A B\"\n  shows \"subset_of A F \\<subseteq> B\" and \"card (subset_of A F) = card A\"\nproof -\n  from assms obtain f where F_eq: \"F = (domain_permutation A B) `` {f}\"\n    and f: \"f \\<in> A \\<rightarrow>\\<^sub>E B\" \"inj_on f A\"\n    using mem_Collect_eq quotientE by force\n  from this have \"subset_of A (domain_permutation A B `` {f}) = f ` A\"\n    using equiv_domain_permutation image_respects_domain_permutation\n    unfolding subset_of_def by (intro univ_commute') auto\n  from this f F_eq show \"subset_of A F \\<subseteq> B\" and \"card (subset_of A F) = card A\"\n    by (auto simp add: card_image)\nqed\n\nlemma functions_of:\n  assumes \"finite A\" \"finite B\" \"X \\<subseteq> B\" \"card X = card A\"\n  shows \"functions_of A X \\<in> {f \\<in> A \\<rightarrow>\\<^sub>E B. inj_on f A} // domain_permutation A B\"\nproof -\n  from assms obtain f where f: \"f \\<in> A \\<rightarrow>\\<^sub>E X \\<and> bij_betw f A X\"\n    using \\<open>finite A\\<close> \\<open>finite B\\<close> by (metis finite_same_card_bij_on_ext_funcset finite_subset)\n  from this have \"X = f ` A\" by (simp add: bij_betw_def)\n  from f \\<open>X \\<subseteq> B\\<close> have \"f \\<in> {f \\<in> A \\<rightarrow>\\<^sub>E B. inj_on f A}\"\n    by (auto simp add: bij_betw_imp_inj_on)\n  have \"functions_of A X = domain_permutation A B `` {f}\"\n    using \\<open>finite A\\<close> \\<open>X = f ` A\\<close> \\<open>f \\<in> {f \\<in> A \\<rightarrow>\\<^sub>E B. inj_on f A}\\<close>\n    by (simp add: functions_of_eq)\n  from this show \"functions_of A X \\<in> {f \\<in> A \\<rightarrow>\\<^sub>E B. inj_on f A} // domain_permutation A B\"\n    using \\<open>f \\<in> {f \\<in> A \\<rightarrow>\\<^sub>E B. inj_on f A}\\<close> by (auto intro: quotientI)\nqed\n\nlemma subset_of_functions_of:\n  assumes \"finite A\" \"finite X\" \"card A = card X\"\n  shows \"subset_of A (functions_of A X) = X\"\nproof -\n  from assms obtain f where \"f \\<in> A \\<rightarrow>\\<^sub>E X\" and \"bij_betw f A X\"\n    using finite_same_card_bij_on_ext_funcset by blast\n  from this have subset_of: \"subset_of A (domain_permutation A X `` {f}) = f ` A\"\n    using equiv_domain_permutation image_respects_domain_permutation\n    unfolding subset_of_def by (intro univ_commute') auto\n  from \\<open>bij_betw f A X\\<close> have \"inj_on f A\" and \"f ` A = X\"\n    by (auto simp add: bij_betw_def)\n  have \"subset_of A (functions_of A X) = subset_of A (functions_of A (f ` A))\"\n    using \\<open>f ` A = X\\<close> by simp\n  also have \"\\<dots> = subset_of A (domain_permutation A X `` {f})\"\n    using \\<open>finite A\\<close> \\<open>inj_on f A\\<close> \\<open>f \\<in> A \\<rightarrow>\\<^sub>E X\\<close> by (auto simp add: functions_of_eq)\n  also have \"\\<dots> = f ` A\"\n    using \\<open>inj_on f A\\<close> \\<open>f \\<in> A \\<rightarrow>\\<^sub>E X\\<close> by (simp add: subset_of)\n  also have \"\\<dots> = X\"\n    using \\<open>f ` A = X\\<close> by simp\n  finally show ?thesis .\nqed\n\n\n\nsubsection \\<open>Bijections\\<close>\n\nlemma bij_betw_subset_of:\n  assumes \"finite A\" \"finite B\"\n  shows \"bij_betw (subset_of A) ({f \\<in> A \\<rightarrow>\\<^sub>E B. inj_on f A} // domain_permutation A B) {X. X \\<subseteq> B \\<and> card X = card A}\"\nproof (rule bij_betw_byWitness[where f'=\"functions_of A\"])\n  show \"\\<forall>F\\<in>{f \\<in> A \\<rightarrow>\\<^sub>E B. inj_on f A} // domain_permutation A B. functions_of A (subset_of A F) = F\"\n    using \\<open>finite A\\<close> functions_of_subset_of by auto\n  show \"\\<forall>X\\<in>{X. X \\<subseteq> B \\<and> card X = card A}. subset_of A (functions_of A X) = X\"\n    using subset_of_functions_of \\<open>finite A\\<close> \\<open>finite B\\<close>\n    by (metis (mono_tags) finite_subset mem_Collect_eq)\n  show \"subset_of A ` ({f \\<in> A \\<rightarrow>\\<^sub>E B. inj_on f A} // domain_permutation A B) \\<subseteq> {X. X \\<subseteq> B \\<and> card X = card A}\"\n    using subset_of by fastforce\n  show \"functions_of A ` {X. X \\<subseteq> B \\<and> card X = card A} \\<subseteq> {f \\<in> A \\<rightarrow>\\<^sub>E B. inj_on f A} // domain_permutation A B\"\n    using \\<open>finite A\\<close> \\<open>finite B\\<close> functions_of by auto\nqed\n\nlemma bij_betw_functions_of:\n  assumes \"finite A\" \"finite B\"\n  shows \"bij_betw (functions_of A) {X. X \\<subseteq> B \\<and> card X = card A} ({f \\<in> A \\<rightarrow>\\<^sub>E B. inj_on f A} // domain_permutation A B)\"\nproof (rule bij_betw_byWitness[where f'=\"subset_of A\"])\n  show \"\\<forall>F\\<in>{f \\<in> A \\<rightarrow>\\<^sub>E B. inj_on f A} // domain_permutation A B. functions_of A (subset_of A F) = F\"\n    using \\<open>finite A\\<close> functions_of_subset_of by auto\n  show \"\\<forall>X\\<in>{X. X \\<subseteq> B \\<and> card X = card A}. subset_of A (functions_of A X) = X\"\n    using subset_of_functions_of \\<open>finite A\\<close> \\<open>finite B\\<close>\n    by (metis (mono_tags) finite_subset mem_Collect_eq)\n  show \"subset_of A ` ({f \\<in> A \\<rightarrow>\\<^sub>E B. inj_on f A} // domain_permutation A B) \\<subseteq> {X. X \\<subseteq> B \\<and> card X = card A}\"\n    using subset_of by fastforce\n  show \"functions_of A ` {X. X \\<subseteq> B \\<and> card X = card A} \\<subseteq> {f \\<in> A \\<rightarrow>\\<^sub>E B. inj_on f A} // domain_permutation A B\"\n    using \\<open>finite A\\<close> \\<open>finite B\\<close> functions_of by auto\nqed\n\nlemma bij_betw_mset_set:\n  shows \"bij_betw mset_set {A. finite A} {M. \\<forall>x. count M x \\<le> 1}\"\nproof (rule bij_betw_byWitness[where f'=\"set_mset\"])\n  show \"\\<forall>A\\<in>{A. finite A}. set_mset (mset_set A) = A\" by auto\n  show \"\\<forall>M\\<in>{M. \\<forall>x. count M x \\<le> 1}. mset_set (set_mset M) = M\"\n    by (auto simp add: mset_set_set_mset')\n  show \"mset_set ` {A. finite A} \\<subseteq> {M. \\<forall>x. count M x \\<le> 1}\"\n    using nat_le_linear by fastforce\n  show \"set_mset ` {M. \\<forall>x. count M x \\<le> 1} \\<subseteq> {A. finite A}\" by auto\nqed\n\nlemma bij_betw_mset_set_card:\n  assumes \"finite A\"\n  shows \"bij_betw mset_set {X. X \\<subseteq> A \\<and> card X = k} {M. M \\<subseteq># mset_set A \\<and> size M = k}\"\nproof (rule bij_betw_byWitness[where f'=\"set_mset\"])\n  show \"\\<forall>X\\<in>{X. X \\<subseteq> A \\<and> card X = k}. set_mset (mset_set X) = X\"\n    using \\<open>finite A\\<close> rev_finite_subset[of A] by auto\n  show \"\\<forall>M\\<in>{M. M \\<subseteq># mset_set A \\<and> size M = k}. mset_set (set_mset M) = M\"\n    by (auto simp add: mset_set_set_mset)\n  show \"mset_set ` {X. X \\<subseteq> A \\<and> card X = k} \\<subseteq> {M. M \\<subseteq># mset_set A \\<and> size M = k}\"\n    using \\<open>finite A\\<close> rev_finite_subset[of A]\n    by (auto simp add: mset_set_subseteq_mset_set)\n  show \"set_mset ` {M. M \\<subseteq># mset_set A \\<and> size M = k} \\<subseteq> {X. X \\<subseteq> A \\<and> card X = k}\"\n    using assms mset_subset_eqD card_set_mset by fastforce\nqed\n\nlemma bij_betw_mset_set_card':\n  assumes \"finite A\"\n  shows \"bij_betw mset_set {X. X \\<subseteq> A \\<and> card X = k} {M. set_mset M \\<subseteq> A \\<and> size M = k \\<and> (\\<forall>x. count M x \\<le> 1)}\"\nproof (rule bij_betw_byWitness[where f'=\"set_mset\"])\n  show \"\\<forall>X\\<in>{X. X \\<subseteq> A \\<and> card X = k}. set_mset (mset_set X) = X\"\n    using \\<open>finite A\\<close> rev_finite_subset[of A] by auto\n  show \"\\<forall>M\\<in>{M. set_mset M \\<subseteq> A \\<and> size M = k \\<and> (\\<forall>x. count M x \\<le> 1)}. mset_set (set_mset M) = M\"\n    by (auto simp add: mset_set_set_mset')\n  show \"mset_set ` {X. X \\<subseteq> A \\<and> card X = k} \\<subseteq> {M. set_mset M \\<subseteq> A \\<and> size M = k \\<and> (\\<forall>x. count M x \\<le> 1)}\"\n    using \\<open>finite A\\<close> rev_finite_subset[of A] by (auto simp add: count_mset_set_leq')\n  show \"set_mset ` {M. set_mset M \\<subseteq> A \\<and> size M = k \\<and> (\\<forall>x. count M x \\<le> 1)} \\<subseteq> {X. X \\<subseteq> A \\<and> card X = k}\"\n    by (auto simp add: card_set_mset')\nqed\n\nsubsection \\<open>Cardinality\\<close>\n\nlemma card_injective_functions_domain_permutation:\n  assumes \"finite A\" \"finite B\"\n  shows \"card ({f \\<in> A \\<rightarrow>\\<^sub>E B. inj_on f A} // domain_permutation A B) = card B choose card A\"\nproof -\n  have \"bij_betw (subset_of A) ({f \\<in> A \\<rightarrow>\\<^sub>E B. inj_on f A} // domain_permutation A B) {X. X \\<subseteq> B \\<and> card X = card A}\"\n    using \\<open>finite A\\<close> \\<open>finite B\\<close> by (rule bij_betw_subset_of)\n  from this have \"card ({f \\<in> A \\<rightarrow>\\<^sub>E B. inj_on f A} // domain_permutation A B) = card {X. X \\<subseteq> B \\<and> card X = card A}\"\n    by (rule bij_betw_same_card)\n  also have \"card {X. X \\<subseteq> B \\<and> card X = card A} = card B choose card A\"\n    using \\<open>finite B\\<close> by (rule n_subsets)\n  finally show ?thesis .\nqed\n\nlemma card_multiset_only_sets:\n  assumes \"finite A\"\n  shows \"card {M. M \\<subseteq># mset_set A \\<and> size M = k} = card A choose k\"\nproof -\n  have \"bij_betw mset_set {X. X \\<subseteq> A \\<and> card X = k} {M. M \\<subseteq># mset_set A \\<and> size M = k}\"\n    using \\<open>finite A\\<close> by (rule bij_betw_mset_set_card)\n  from this have \"card {M. M \\<subseteq># mset_set A \\<and> size M = k} = card {X. X \\<subseteq> A \\<and> card X = k}\"\n    by (simp add: bij_betw_same_card)\n  also have \" card {X. X \\<subseteq> A \\<and> card X = k} = card A choose k\"\n    using \\<open>finite A\\<close> by (rule n_subsets)\n  finally show ?thesis .\nqed\n\nlemma card_multiset_only_sets':\n  assumes \"finite A\"\n  shows \"card {M. set_mset M \\<subseteq> A \\<and> size M = k \\<and> (\\<forall>x. count M x \\<le> 1)} = card A choose k\"\nproof -\n  from \\<open>finite A\\<close> have \"{M. set_mset M \\<subseteq> A \\<and> size M = k \\<and> (\\<forall>x. count M x \\<le> 1)} =\n    {M. M \\<subseteq># mset_set A \\<and> size M = k}\"\n    using msubset_mset_set_iff by auto\n  from this \\<open>finite A\\<close> card_multiset_only_sets show ?thesis 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/Twelvefold_Way/Twelvefold_Way_Entry5.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8596637433190939, "lm_q2_score": 0.8152324848629215, "lm_q1q2_score": 0.7008258096125857}}
{"text": "theory Zp_compact\nimports padic_int_topology\nbegin\n\n(**************************************************************************************************)\n(**************************************************************************************************)\n(*******************************   SEQUENTIAL COMPACTNESS  ****************************************)\n(*******************************          OF ZP            ****************************************)\n(**************************************************************************************************)\n(**************************************************************************************************)\n\ncontext padic_int_poly\nbegin\n\n(*The refinement of a sequence by a function nat \\<Rightarrow> nat*)\ndefinition take_subseq :: \"(nat \\<Rightarrow> 'a) \\<Rightarrow> (nat \\<Rightarrow> nat) \\<Rightarrow> (nat \\<Rightarrow> 'a)\" where\n\"take_subseq s f = (\\<lambda>k. s (f k))\"\n\n(*Predicate for increasing function on the natural numbers*)\ndefinition is_increasing :: \"(nat \\<Rightarrow> nat) \\<Rightarrow> bool\" where\n\"is_increasing f = (\\<forall> n m::nat. n>m \\<longrightarrow> (f n) > (f m))\"\n\n(*Elimination and introduction lemma for increasing functions*)\nlemma is_increasingI:\n  assumes \"\\<And> n m::nat. n>m \\<Longrightarrow> (f n) > (f m)\"\n  shows \"is_increasing f\"\n  unfolding is_increasing_def \n  using assms \n  by blast \n\nlemma is_increasingE: \n  assumes \"is_increasing f\"\n  assumes \" n> m\"\n  shows \"f n > f m\"\n  using assms\n  unfolding is_increasing_def \n  by blast \n\n(*The subsequence predicate*)\ndefinition is_subseq_of :: \"(nat \\<Rightarrow> 'a) \\<Rightarrow> (nat \\<Rightarrow> 'a) \\<Rightarrow> bool\" where\n\"is_subseq_of s s' = (\\<exists>(f::nat \\<Rightarrow> nat). is_increasing f \\<and> s' = take_subseq s f)\"\n\n(*Subsequence introduction lemma*)\nlemma is_subseqI:\n  assumes \"is_increasing f\"\n  assumes \"s' = take_subseq s f\"\n  shows \"is_subseq_of s s'\"\n  using assms \n  unfolding is_subseq_of_def \n  by auto \n\n(*Given a sequence and a predicate, returns the function nat\\<Rightarrow>nat which represents the increasing\nsequences of indices n on which P (s n) holds.*)\n\nprimrec filtering_function :: \"(nat \\<Rightarrow>'a) \\<Rightarrow> ('a \\<Rightarrow> bool) \\<Rightarrow> nat \\<Rightarrow> nat\" where\n\"filtering_function s P (0::nat) = (LEAST k::nat. P (s k))\"|\n\"filtering_function s P (Suc n) = (LEAST k:: nat. (P (s k)) \\<and> k > (filtering_function s P n))\"   \n\nlemma filtering_func_pre_increasing:\n  assumes \"\\<forall>n::nat. \\<exists>m. m > n \\<and> P (s m)\"\n  shows \"filtering_function s P n < filtering_function s P (Suc n)\" \n  apply(auto)\nproof(induction n)\n  case 0\n  have \"\\<exists>k. P (s k)\" using assms(1) by blast\n  then have \"\\<exists>k::nat. (LEAST k::nat. (P (s k))) \\<ge> 0\" \n    by blast\n  obtain k where \"(LEAST k::nat. (P (s k))) = k\" by simp\n  have \"\\<exists>l. l = (LEAST l::nat. (P (s l) \\<and> l > k))\" \n    by simp\n  thus ?case\n    by (metis (no_types, lifting) LeastI assms)\nnext\n  case (Suc n)\n  then show ?case\n    by (metis (no_types, lifting) LeastI assms)\nqed\n\nlemma filtering_func_increasing:\n  assumes \"\\<forall>n::nat. \\<exists>m. m > n \\<and> P (s m)\"\n  shows \"is_increasing (filtering_function s P)\" \n  by (metis assms filtering_func_pre_increasing is_increasingI lift_Suc_mono_less) \n\n\ndefinition filtered_sequence :: \"(nat \\<Rightarrow> 'a) \\<Rightarrow> ('a \\<Rightarrow> bool) \\<Rightarrow> (nat \\<Rightarrow> 'a)\" where\n\"filtered_sequence s P = take_subseq s (filtering_function s P)\"\n\nlemma filter_exist:\n  assumes \"is_closed_seq s\"\n  assumes \"\\<forall>n::nat. \\<exists>m. m > n \\<and> P (s m)\"\n  shows \"\\<And>m. n\\<le>m \\<Longrightarrow> P (s (filtering_function s P n))\"\nproof(induct n)\n  case 0\n  then show ?case \n    using LeastI assms(2) by force\nnext\n  case (Suc n)\n  then show ?case \n    by (smt LeastI assms(2) filtering_function.simps(2))\nqed\n(* In a filtered sequence, every element satisfies the given predicate *)\n\nlemma fil_seq_pred:\n  assumes \"is_closed_seq s\"\n  assumes \"s' = filtered_sequence s P\"\n  assumes \"\\<forall>n::nat. \\<exists>m. m > n \\<and> P (s m)\"\n  shows \"\\<And>m::nat. P (s' m)\" sorry\n(*proof-\n  have \"\\<exists>k. P (s k)\" using assms(3) \n    by blast\n  fix m\n  obtain k where kdef: \"k = filtering_function s P m\" by auto \n  have \"\\<exists>k. P (s k)\" \n    using assms(3) by auto\n  then have \"P (s k)\" \n    sledgehammer\n  then have \"s' m = s k\"\n    by (simp add: assms(2) filtered_sequence_def kdef take_subseq_def)\n  hence \"P (s' m)\" \n    by (simp add: \\<open>P (s k)\\<close>)\n  thus \"\\<And>m. P (s' m)\" using  assms(2) assms(3) dual_order.strict_trans filter_exist filtered_sequence_def\n      lessI less_Suc_eq_le take_subseq_def sledgehammer\n    \nqed*)\n\n\ndefinition kth_res_equals :: \"nat \\<Rightarrow> int \\<Rightarrow> (padic_int  \\<Rightarrow> bool)\" (\"Pr _  _\") where\n\"kth_res_equals k n a = (a k = n)\"\n\n(*The characteristic function of the underlying set of a sequence*)\ndefinition indicator:: \"(nat \\<Rightarrow> 'a) \\<Rightarrow> ('a  \\<Rightarrow> bool)\" where\n\"indicator s a = (\\<exists>n::nat. s n = a)\"\n  \n\n(*Every filtering function is the indicator of the sequence that it filters\nlemma filtering_function_is_indicator:\n  assumes \"s' = filtered_sequence s P\"\n  assumes \"is_subseq s s'\"\n  shows \"P = indicator s'\"\n  sorry*)\n\n(*choice function for a subsequence with constant kth residue. Could be made constructive by \nchoosing the LEAST n if we wanted.*)\ndefinition equal_res_choice :: \"nat \\<Rightarrow> padic_int_seq \\<Rightarrow> padic_int_seq\" (\"Cseq _ _\") where\n\"equal_res_choice k s = (SOME s'::(padic_int_seq). (\\<exists> n. is_subseq_of s s' \\<and> s' \n  = (filtered_sequence s (Pr k n)) \\<and> (\\<forall>m. s' m k = n)))\" \n\n(*The constant kth residue value for the sequence obtained by the previous function*)\ndefinition equal_res_choice_res :: \"nat \\<Rightarrow> padic_int_seq \\<Rightarrow> int\" (\"Cres\") where\n\"equal_res_choice_res k s = (THE n. (\\<forall> m. (Cseq k s) m k = n))\" \n\ndefinition maps_to_n:: \"nat \\<Rightarrow> (nat \\<Rightarrow> int) \\<Rightarrow> bool\" where\n\"maps_to_n n f = (\\<forall>(k::nat). f k \\<in> {0..n})\"\n\ndefinition drop :: \"nat \\<Rightarrow> (nat \\<Rightarrow> int) \\<Rightarrow> (nat \\<Rightarrow> int)\" where\n\"drop k f n = (if (f n)=k then 0 else f n)\"\n \nlemma maps_to_nE:\n  assumes \"maps_to_n n f\"\n  shows \"(f k) \\<in> {0..n}\"\n  using assms\n  unfolding maps_to_n_def\n  by blast\n \nlemma maps_to_nI:\n  assumes \"\\<And>n. f n \\<in>{0 .. k}\"\n  shows \"maps_to_n k f\"\n  using assms maps_to_n_def by auto\n \n \nlemma maps_to_n_drop:\n  assumes \"maps_to_n (Suc n) f\"\n  shows \"maps_to_n n (drop (Suc n) f)\"\n(*proof(rule maps_to_nI)*)\nproof-\n  fix k\n  have \"drop (Suc n) f k \\<in> {0..n}\"\n  proof(cases \"f k = Suc n\")\n    case True\n    then have \"drop (Suc n) f k = 0\"\n      unfolding drop_def by auto\n    then show ?thesis \n      using assms local.drop_def maps_to_n_def by auto\n  next\n    case False\n    then show ?thesis\n      using assms atLeast0_atMost_Suc maps_to_n_def drop_def\n      by auto\n  qed\n  then have \"\\<And>k. drop (Suc n) f k \\<in> {0..n}\" \n    using assms local.drop_def maps_to_n_def by auto\n    then show \"maps_to_n n (drop (Suc n) f)\" using maps_to_nI\n      using maps_to_n_def by blast\n  qed\n \nlemma drop_eq_f:\n  assumes \"maps_to_n (Suc n) f\"\n  assumes \"\\<not> (\\<forall>m. \\<exists>n. n>m \\<and> (f n = (Suc k)))\"\n  shows \"\\<exists>N. \\<forall>n. n>N \\<longrightarrow> f n = drop (Suc k) f n\"\nproof-\n  have \"\\<exists>m. \\<forall>n. n \\<le> m \\<or> (f n) \\<noteq> (Suc k)\"\n    using assms\n    by (meson Suc_le_eq nat_le_linear)\n  then have \"\\<exists>m. \\<forall>n. n \\<le> m \\<or> (f n)  = drop (Suc k) f n\"\n    using drop_def by auto\n  then show ?thesis\n    by (meson less_Suc_eq_le order.asym)\nqed\n \nlemma maps_to_n_infinite_seq:\n  shows \"\\<And>f. maps_to_n k f \\<Longrightarrow> \\<exists>l. \\<forall>m. \\<exists>n. n>m \\<and> (f n = l)\"\nproof(induction k)\n  case 0  \n  then have \"\\<And>n. f n \\<in> {0}\"\n    using maps_to_nE[of 0 f] by auto\n  then show \" \\<exists>l. \\<forall>m. \\<exists>n. m < n \\<and> f n = l\"\n    by blast\nnext\n  case (Suc k)\n  assume IH: \"\\<And>f. maps_to_n k f \\<Longrightarrow> \\<exists>l. \\<forall>m. \\<exists>n. m < n \\<and> f n = l\"\n  fix f\n  assume A: \"maps_to_n (Suc k) f\"\n  show \"\\<exists>l. \\<forall>m. \\<exists>n. n>m \\<and> (f n = l)\"\n  proof(cases \" \\<forall>m. \\<exists>n. n>m \\<and> (f n = (Suc k))\")\n    case True\n    then show ?thesis by blast\n  next\n    case False\n    then obtain N where N_def: \"\\<forall>n. n>N \\<longrightarrow> f n = drop (Suc k) f n\"\n      using drop_eq_f drop_def\n      by fastforce\n    have \" maps_to_n k (drop (Suc k) f) \"\n      by (simp add: A maps_to_n_drop)\n    then have \" \\<exists>l. \\<forall>m. \\<exists>n. m < n \\<and> (drop (Suc k) f) n = l\"\n      using IH by blast\n    then obtain l where l_def: \"\\<forall>m. \\<exists>n. m < n \\<and> (drop (Suc k) f) n = l\"\n      by blast\n    have \"\\<forall>m. \\<exists>n. n>m \\<and> (f n = l)\"\n      apply auto\n    proof-\n      fix m\n      show \"\\<exists>n>m. f n = l\"\n      proof-\n        obtain n where N'_def: \"(max m N) < n \\<and> (drop (Suc k) f) n = l\"\n          using l_def by blast\n        have \"f n =  (drop (Suc k) f) n\"\n          using N'_def N_def\n          by simp\n        then show ?thesis\n          using N'_def by auto\n      qed\n    qed\n    then show ?thesis\n      by blast\n  qed\nqed\n\ndefinition index_to_residue :: \"padic_int_seq \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> int\" where\n\"index_to_residue s k m = ((s m) k)\"\n\n\nlemma seq_maps_to_n:\n  assumes \"is_closed_seq s\"\n  shows \"\\<And>m. maps_to_n ((p^k)-1) (index_to_residue s k)\"\nproof-\n  have A1: \"\\<And>m. (s m) \\<in> carrier Z\\<^sub>p\" \n    using assms is_closed_seq_def by auto\n  have \"\\<And>m. (s m k) \\<in> {0..(p^k -1)}\" \n    by (metis A1 le_refl r_Zp r_range)\n  have \"\\<And>m. index_to_residue s k m = s m k\" using index_to_residue_def \n    using \\<open>\\<And>m. s m k \\<in> {0..int (p ^ k - 1)}\\<close> by auto\n  thus \"\\<And>m. maps_to_n ((p^k)-1) (index_to_residue s k)\" \n    by (metis \\<open>\\<And>m. s m k \\<in> {0..int (p ^ k - 1)}\\<close> atLeastAtMost_iff  \n        maps_to_n_def)\nqed\n\nlemma seq_pr_inc:\n  assumes \"is_closed_seq s\"\n  shows \"\\<exists>l. \\<forall>m. \\<exists>n > m. (Pr k l) (s n)\"\nproof-\n  fix k l m\n  have \"(Pr k l) (s m) \\<Longrightarrow> (s m) k = l\" \n    by (simp add: kth_res_equals_def)\n  have \"\\<And>k. s m k = index_to_residue s k m\" \n    by (simp add: index_to_residue_def)\n  have A1: \"maps_to_n (p^k - 1) (index_to_residue s k)\" using seq_maps_to_n assms by blast\n  then have \"\\<And>m. s m k \\<in> {0..(p^k - 1)}\" \n    by (metis index_to_residue_def maps_to_nE)\n  have \"maps_to_n (p^k - 1) (index_to_residue s k) \\<Longrightarrow>  \\<exists>l. \\<forall>m. \\<exists>n. n>m \\<and> (index_to_residue s k n = l)\" \n    by (simp add: maps_to_n_infinite_seq)\n  hence \"\\<exists>l. \\<forall>m. \\<exists>n. n > m \\<and>  (index_to_residue s k n = l)\" using A1 by simp\n  hence \"\\<exists>l. \\<forall>m. \\<exists>n. n > m \\<and>  (s n k = l)\" \n    by (simp add: index_to_residue_def)\n  thus \"\\<exists>l. \\<forall>m. \\<exists>n > m. (Pr k l) (s n)\" \n    using kth_res_equals_def by auto\nqed\n\n\nlemma Pr_subseq:\n  assumes \"is_closed_seq s\"\n  shows \"\\<exists>n. is_subseq_of s (filtered_sequence s (Pr k n)) \\<and> (\\<forall>m. (filtered_sequence s (Pr k n)) m k = n)\"\nproof-\n  obtain l where l_def: \" \\<forall> m. \\<exists>n > m. (Pr k l) (s n)\"\n    using assms seq_pr_inc by blast\n  have 0: \"is_subseq_of s (filtered_sequence s (Pr k l))\"\n    unfolding filtered_sequence_def\n  proof(rule is_subseqI)\n    let ?f = \"(filtering_function s Pr k  l)\"\n    show \"is_increasing ?f\"\n      using l_def \n      by (simp add: filtering_func_increasing)\n    show \"take_subseq s (filtering_function s Pr k  l) = take_subseq s (filtering_function s Pr k  l)\"\n      by auto\n  qed\n  have 1: \" (\\<forall>m. (filtered_sequence s (Pr k l)) m k = l)\"\n   using l_def \n   by (meson assms kth_res_equals_def fil_seq_pred padic_integers_axioms)\n  show ?thesis using 0 1 by blast \nqed\n\nlemma Cseq_prop_0: \n  assumes \"is_closed_seq s\"\n  shows \"\\<exists>l. (((Cseq k s) = filtered_sequence s (Pr k l)) \\<and> (is_subseq_of s (Cseq k s)) \\<and> (\\<forall>m.(Cseq k s) m k = l))\"\nproof-\n  have \" \\<exists>n. (is_subseq_of s (filtered_sequence s Pr k  n) \\<and> (\\<forall>m. (filtered_sequence s Pr k  n) m k = n))\"\n    by (simp add: Pr_subseq assms)\n  then have \"\\<exists>s'. (\\<exists>n. (is_subseq_of s s') \\<and> (s' = filtered_sequence s Pr k  n) \\<and> (\\<forall>m. s' m k = n))\"\n    by blast\n  then show ?thesis\n  using equal_res_choice_def[of k s]   \n      by (smt equal_res_choice_def someI_ex)\nqed\n\nlemma Cseq_prop_1: \n  assumes \"is_closed_seq s\"\n  shows \"(\\<forall>m.(Cseq k s) m k = (Cres k s) )\"\n  using Cseq_prop_0[of s] equal_res_choice_res_def[of k s]\n  by (smt assms equal_res_choice_def equal_res_choice_res_def the_equality)\n\nlemma Cres_range:\n  assumes \"is_closed_seq s\"\n  assumes \"k > 0\"\n  shows \"Cres k s \\<in> carrier R k\"\nproof-\n  have 0: \"is_closed_seq (Cseq k s)\"\n    by (metis (no_types, hide_lams) Cseq_prop_0 assms(1) \n        filtered_sequence_def is_closedI is_closed_simp take_subseq_def)\n  have 1: \"(Cseq k s) 0 k \\<in>  carrier R k\"\n    using 0  is_closed_seq_def padic_integers_axioms padic_set_simp0 \n    using padic_int_poly.is_closed_simp padic_int_poly_axioms by auto\n\n  then show  ?thesis\n  using assms Cseq_prop_1[of s k] \n  by (simp add: \\<open>is_closed_seq s\\<close>)\nqed\n\nfun res_seq ::\"padic_int_seq \\<Rightarrow> nat \\<Rightarrow>  padic_int_seq\" where\n\"res_seq s 0 = s\"|\n\"res_seq s (Suc k) = Cseq (Suc k) (res_seq s k)\"\n\nlemma res_seq_res:\n  assumes \"is_closed_seq s\"\n  shows \"is_closed_seq (res_seq s k)\"\n  apply(induction k)\n  apply (simp add: assms)\n  by (smt is_subseq_of_def Cseq_prop_0 is_closed_seq_def \n      padic_integers_axioms res_seq.simps(2) take_subseq_def)\n\nlemma res_seq_res':\n  assumes \"is_closed_seq s\"\n  shows \"\\<And>n. res_seq s (Suc k) n (Suc k) = Cres (Suc k) (res_seq s k)\"\n  using assms res_seq_res[of s k] Cseq_prop_1[of \"(res_seq s k)\" \"Suc k\" ] \n  by simp\n\nlemma res_seq_subseq: \n  assumes \"is_closed_seq s\"\n  shows \"is_subseq_of (res_seq s k) (res_seq s (Suc k))\"\n  by (metis assms  Cseq_prop_0 res_seq_res  \n      res_seq.simps(2))\n\n(**)\nlemma is_increasing_id[simp]:\n\"is_increasing (\\<lambda> n. n)\"\n  by (simp add: is_increasingI)\n\nlemma is_increasing_comp:\n  assumes \"is_increasing f\"\n  assumes \"is_increasing g\"\n  shows \"is_increasing (f \\<circ> g)\"\n  using assms(1) assms(2) is_increasing_def \n  by auto\n\nlemma is_increasing_imp_geq_id[simp]:\n  assumes  \"is_increasing f\"\n  shows \"f n \\<ge>n\"\n  apply(induction n)\n  apply simp\n  by (metis (mono_tags, lifting) assms is_increasing_def\n      leD lessI not_less_eq_eq order_less_le_subst2)\n\nlemma is_subseq_ofE:\n  assumes \"is_closed_seq s\"\n  assumes \"is_subseq_of s s'\"\n  shows \"\\<exists>k. k \\<ge> n \\<and> s' n = s k\"\nproof-\n  obtain f where \"is_increasing f \\<and> s' = take_subseq s f\"\n    using assms(2) is_subseq_of_def by blast\n  then have  \" f n \\<ge> n \\<and> s' n = s (f n)\"\n    unfolding take_subseq_def \n    by simp\n  then show ?thesis by blast \nqed\n\n\nlemma is_subseq_of_id:\n  assumes \"is_closed_seq s\"\n  shows \"is_subseq_of s s\"\nproof-\n  have \"s = take_subseq s (\\<lambda>n. n)\"\n    unfolding take_subseq_def \n    by auto \n  then show ?thesis using is_increasing_id\n    using is_subseqI \n    by blast\nqed\n\nlemma is_subseq_of_trans:\n  assumes \"is_closed_seq s\"\n  assumes \"is_subseq_of s s'\"\n  assumes \"is_subseq_of s' s''\"\n  shows \"is_subseq_of s s''\"\nproof-\n  obtain f where f_def: \"is_increasing f \\<and> s' = take_subseq s f\"\n    using assms(2) is_subseq_of_def \n    by blast\n  obtain g where g_def: \"is_increasing g \\<and> s'' = take_subseq s' g\"\n    using assms(3) is_subseq_of_def \n    by blast\n  have \"s'' = take_subseq s (f \\<circ> g)\"\n  proof\n    fix x\n    show \"s'' x = take_subseq s (f \\<circ> g) x\"\n      using f_def g_def unfolding take_subseq_def\n      by auto\n  qed\n  then show ?thesis \n    using f_def g_def is_increasing_comp is_subseq_of_def \n    by blast\nqed\n\nlemma res_seq_subseq':\n  assumes \"is_closed_seq s\"\n  shows \"is_subseq_of s (res_seq s k)\"\nproof(induction k)\n  case 0\n  then show ?case using is_subseq_of_id \n    by (simp add: assms)\nnext\n  case (Suc k)\n  fix k\n  assume \"is_subseq_of s (res_seq s k)\"\n  then show \"is_subseq_of s (res_seq s (Suc k)) \"\n    using assms is_subseq_of_trans res_seq_subseq \n    by blast\nqed\n\nlemma res_seq_subseq'':\n  assumes \"is_closed_seq s\"\n  shows \"is_subseq_of (res_seq s n) (res_seq s (n + k))\"\n  apply(induction k)\n  apply (simp add: assms is_subseq_of_id res_seq_res)\n  using add_Suc_right assms is_subseq_of_trans res_seq_res res_seq_subseq by presburger\n(**)\n\ndefinition acc_point :: \"padic_int_seq \\<Rightarrow> padic_int\" where\n\"acc_point s k = (if (k = 0) then (0::int) else ((res_seq s k) 0 k))\"\n\nlemma res_seq_res_1:\n  assumes \"is_closed_seq s\"\n  shows \"res_seq s (Suc k) 0 k = res_seq s k 0 k\"\nproof-\n  obtain n where  n_def: \"res_seq s (Suc k) 0 = res_seq s k n\" \n    by (metis assms is_subseq_of_def res_seq_subseq take_subseq_def)\n  have \"res_seq s (Suc k) 0 k = res_seq s k n k\"\n    using n_def by auto\n  thus ?thesis \n    by (metis (no_types, hide_lams)  Cseq_prop_1 Zp_is_cring  assms cring_def  is_closed_simp \n        monoid.nat_pow_0 monoid.r_one n_def of_nat_0 of_nat_le_0_iff p_pow_factor res_seq.elims \n        res_seq_res ring_def)\nqed\n\nlemma acc_point_cres:\n  assumes \"is_closed_seq s\"\n  shows \"(acc_point s (Suc k)) = (Cres (Suc k) (res_seq s k))\" \nproof-\n  have \"Suc k > 0\" by simp\n  have \"(res_seq s (Suc k)) = Cseq (Suc k) (res_seq s k)\" (*(Cseq k s) m k = (Cres k s) )\"*)\n    by simp\n  then have \"(Cseq (Suc k) (res_seq s k)) 0 (Suc k) = Cres (Suc k)  (res_seq s k)\" \n    using assms res_seq_res' padic_integers_axioms by auto\n  have \"acc_point s (Suc k) = res_seq s (Suc k) 0 (Suc k)\" using acc_point_def by simp\n  then have \"acc_point s (Suc k) = (Cseq (Suc k) (res_seq s k)) 0 (Suc k)\"\n    by simp\n  thus ?thesis \n    by (simp add: \\<open>(Cseq (Suc k) (res_seq s k)) 0 (Suc k) = Cres (Suc k) (res_seq s k)\\<close>)\nqed\n\nlemma acc_point_res:\n  assumes \"is_closed_seq s\"\n  shows \"res (int p ^ k) (acc_point s (Suc k)) = acc_point s k\"\nproof(cases \"k = 0\")\n  case True\n  then show ?thesis \n    by (metis Res_0' acc_point_def of_nat_power r_range')\nnext\n  case False\n  assume \"k \\<noteq> 0\"  show \"res (int p ^ k) (acc_point s (Suc k)) = acc_point s k\" \n    by (metis False acc_point_def assms is_closed_simp lessI less_imp_le nat.distinct(1) \n        of_nat_power res_seq_res_1  r_Zp res_seq_res)\nqed\n\nlemma acc_point_closed:\n  assumes \"is_closed_seq s\"\n  shows \"acc_point s \\<in>  carrier Z\\<^sub>p\" \nproof-\n  have \"acc_point s \\<in> padic_set p\"\n  proof(rule padic_set_mem)\n    show \"\\<And>m. acc_point s m \\<in> carrier (residue_ring (int p ^ m))\"\n    proof-\n      fix m\n      show \"acc_point s m \\<in> carrier (residue_ring (int p ^ m))\"\n      proof(cases \"m = 0\")\n        case True\n        then show ?thesis \n          by (simp add: acc_point_def residue_ring_def)\n      next\n        case False\n        assume \"m \\<noteq> 0\" \n        then have \"acc_point s m = res_seq s m 0 m\" (*\"res_seq s (Suc k) = Cseq (Suc k) (res_seq s k)\"*)\n          by (simp add: acc_point_def)\n        (*then have \"res_seq s m 0 m = Cres 0 (Cseq m (res_seq s (m-1)))\" sledgehammer*)\n        then show ?thesis  using Cres_range[of \"(Cseq (m-1) s)\" m] acc_point_def[of s m] \n          by (metis acc_point_res assms of_nat_power r_range')\n      qed\n    qed\n    show \"\\<And>m n. m < n \\<Longrightarrow> res (int p ^ m) (acc_point s n) = acc_point s m\"\n    proof-\n      fix m n::nat \n      assume A: \"m < n\"\n      show \"res (int p ^ m) (acc_point s n) = acc_point s m\"\n      proof-\n        obtain l where l_def: \"l = n - m - 1\"\n          by simp\n        have \"res (int p ^ m) (acc_point s (Suc (m + l))) = acc_point s m\"\n        proof(induction l)\n          case 0\n          then show ?case \n            by (simp add: acc_point_res assms)\n        next\n          case (Suc l)\n          then show ?case \n            by (metis acc_point_def add_Suc_right assms is_closed_simp le_add1 nat.distinct(1) \n                of_nat_power res_seq_res_1  r_Zp res_seq_res)\n        qed\n        then show ?thesis \n          by (metis A Suc_diff_Suc Suc_eq_plus1 add_Suc_right add_diff_inverse_nat diff_diff_left \n              l_def le_less_trans less_not_refl order_less_imp_le)\n      qed\n    qed\n  qed\n  then show ?thesis \n    by (simp add: Z\\<^sub>p_def)\nqed\n\n(*Choice function for a subsequence of s which converges to a, if it exists*)\nfun convergent_subseq_fun :: \"padic_int_seq \\<Rightarrow> padic_int \\<Rightarrow> (nat \\<Rightarrow> nat)\" where\n\"convergent_subseq_fun s a 0 = 0\"|\n\"convergent_subseq_fun s a (Suc n) = (SOME k. k > (convergent_subseq_fun s a n)\n                                                \\<and> (s k (Suc n)) = a (Suc n))\"\n\ndefinition convergent_subseq :: \"padic_int_seq \\<Rightarrow> padic_int_seq\" where\n\"convergent_subseq s = take_subseq s (convergent_subseq_fun s (acc_point s))\"\n\nlemma increasing_conv_induction_0_pre:\n  assumes \"is_closed_seq s\"\n  assumes \"a = acc_point s\"\n  shows \"\\<exists>k > convergent_subseq_fun s a n. (s k (Suc n)) = a (Suc n)\"\nproof-\n  obtain l::nat where \"l > 0 \" by blast\n  have \"is_subseq_of s (res_seq s (Suc n))\" \n    using assms(1) res_seq_subseq' by blast\n  then obtain m where \"s m = res_seq s (Suc n) l \\<and> m \\<ge> l\" \n    by (metis is_increasing_imp_geq_id is_subseq_of_def take_subseq_def )\n    \n  have \"a (Suc n) = res_seq s (Suc n) 0 (Suc n)\" \n    by (simp add: acc_point_def assms(2))\n  have \"s m (Suc n) = a (Suc n)\" \n    by (metis \\<open>a (Suc n) = res_seq s (Suc n) 0 (Suc n)\\<close> \\<open>s m = res_seq s (Suc n) l \\<and> l \\<le> m\\<close> assms(1) res_seq_res')\n  \n  thus ?thesis \n    using \\<open>0 < l\\<close> \\<open>s m = res_seq s (Suc n) l \\<and> l \\<le> m\\<close> less_le_trans  \\<open>s m (Suc n) = a (Suc n)\\<close> \n    by (metis \\<open>a (Suc n) = res_seq s (Suc n) 0 (Suc n)\\<close> \\<open>is_subseq_of s (res_seq s (Suc n))\\<close>\n        assms(1) lessI is_subseq_ofE res_seq_res' )\nqed\n\n  \n\nlemma increasing_conv_subseq_fun_0:\n  assumes \"is_closed_seq s\"\n  assumes \"\\<exists>s'. s' = convergent_subseq s\"\n  assumes \"a = acc_point s\"\n  shows \"convergent_subseq_fun s a (Suc n) > convergent_subseq_fun s a n\"\n  apply(auto) \nproof(induction n)\n  case 0\n  have \"convergent_subseq_fun s a 0 = 0\" by simp\n  then show ?case \n    by (smt assms(1) assms(3) less_Suc_eq less_Suc_eq_0_disj increasing_conv_induction_0_pre padic_integers_axioms someI_ex)\nnext\n  case (Suc k)\n  then show ?case \n    by (metis (mono_tags, lifting) assms(1) assms(3) increasing_conv_induction_0_pre someI_ex) \n  qed\n\nlemma increasing_conv_subseq_fun:\n  assumes \"is_closed_seq s\"\n  assumes \"a = acc_point s\"\n  assumes \"\\<exists>s'. s' = convergent_subseq s\"\n  shows \"is_increasing (convergent_subseq_fun s a)\"\n    by (metis assms(1) assms(2) increasing_conv_subseq_fun_0 is_increasingI lift_Suc_mono_less)\n\nlemma convergent_subseq_is_subseq:\n  assumes \"is_closed_seq s\"\n  shows \"is_subseq_of s (convergent_subseq s)\" \n  using assms convergent_subseq_def increasing_conv_subseq_fun is_subseqI by blast\n\nlemma is_closed_seq_conv_subseq:\n  assumes \"is_closed_seq s\"\n  shows \"is_closed_seq (convergent_subseq s)\"  \n  by (simp add: assms convergent_subseq_def take_subseq_def)\n\nlemma convergent_sequence_res:\n  assumes \"is_closed_seq s\"\n  assumes \"a = acc_point s\"\n  shows \"convergent_subseq s l l = res (p ^ l) (acc_point s l)\"\nproof-\n  have \"\\<exists>k. convergent_subseq s l =  s k \\<and> s k l = a l\" \n  proof-\n    have \"convergent_subseq s l = s (convergent_subseq_fun s a l)\" \n      by (simp add: assms(2) convergent_subseq_def take_subseq_def)\n    obtain k where kdef: \"(convergent_subseq_fun s a l) = k\" \n      by simp\n    have \"convergent_subseq s l = s k\" \n      by (simp add: \\<open>convergent_subseq s l = s (convergent_subseq_fun s a l)\\<close> kdef)\n    have \"s k l = a l\"\n    proof(cases \"l = 0\")\n      case True\n      then show ?thesis \n        by (metis acc_point_def assms(1) assms(2) is_closed_simp of_nat_0 ord_pos zero_below_ord zero_vals)\n    next\n      case False\n      have \"0 < l\"\n        using False by blast\n      then have \"k > convergent_subseq_fun s a (l-1)\" \n        by (metis One_nat_def Suc_pred assms(1) assms(2) increasing_conv_subseq_fun_0 kdef)\n      then have \"s k l = a l\" using kdef \n        assms(1) assms(2) convergent_subseq_fun.simps(2) increasing_conv_induction_0_pre \n        padic_integers_axioms someI_ex One_nat_def  \\<open>0 < l\\<close> increasing_conv_induction_0_pre \n        by (smt Suc_diff_1)\n   \n      then show ?thesis\n        by simp\n    qed\n    then have \"convergent_subseq s l =  s k \\<and> s k l = a l\" \n      using \\<open>convergent_subseq s l = s k\\<close> by blast\n    thus ?thesis \n      by blast\n  qed\n  thus ?thesis \n    using acc_point_closed assms(1) assms(2) r_Zp by auto\nqed\n\nlemma convergent_subsequence_is_convergent:\n  assumes \"is_closed_seq s\"\n  assumes \"a = acc_point s\"\n  shows \"converges_to (convergent_subseq s) (acc_point s)\" (*\\<And>n. \\<exists>N. \\<forall>k > N. s k n = a n\"*) \nproof(rule converges_toI)\n  show \"acc_point s \\<in> carrier Z\\<^sub>p\"\n    using acc_point_closed assms  by blast\n  show \"is_closed_seq (convergent_subseq s)\" using is_closed_seq_conv_subseq assms by simp\n  show \"\\<And>n. \\<exists>N. \\<forall>k>N. convergent_subseq s k n = acc_point s n\" \n  proof-\n    fix n\n    show \"\\<exists>N. \\<forall>k>N. convergent_subseq s k n = acc_point s n\"\n    proof(induction n)\n      case 0\n      then show ?case  by (metis (mono_tags, hide_lams) acc_point_def assms convergent_subseq_def is_closed_seq_def of_nat_0 ord_pos take_subseq_def zero_below_ord zero_vals)\n    next\n      case (Suc n)\n      have \"acc_point s (Suc n) = res_seq s (Suc n) 0 (Suc n)\"\n        by (simp add: acc_point_def)\n      obtain k where kdef: \"convergent_subseq_fun s a (Suc n) = k\" by simp\n      have \"Suc n > 0\" by simp\n      then have \"k > (convergent_subseq_fun s a n)\" \n        using assms(1) assms(2) increasing_conv_subseq_fun_0 kdef by blast \n      then have \" k > (convergent_subseq_fun s a n) \\<and> (s k (Suc n)) = a (Suc n)\" using kdef \n        by (metis (mono_tags, lifting) assms(1) assms(2) convergent_subseq_fun.simps(2) increasing_conv_induction_0_pre someI_ex)\n      have \"s k (Suc n) = a (Suc n)\" \n        using \\<open>convergent_subseq_fun s a n < k \\<and> s k (Suc n) = a (Suc n)\\<close> by blast\n      then have \"convergent_subseq s (Suc n) (Suc n) = a (Suc n)\" \n        by (metis assms(2) convergent_subseq_def kdef take_subseq_def)\n      then have \"\\<forall>l > n.  convergent_subseq s l (Suc n) = a (Suc n)\" \n        by (metis Suc_leI \\<open>is_closed_seq (convergent_subseq s)\\<close> acc_point_closed assms(1) assms(2) convergent_sequence_res is_closed_simp le_refl r_Zp)\n      then show ?case \n        using assms(2) by blast\n    qed\n  qed\nqed\n    \n\n\ntheorem Zp_is_compact:\n  assumes \"is_closed_seq s\"\n  shows \"\\<exists>s'. is_subseq_of s s' \\<and> (converges_to s' (acc_point s))\" \n  using assms convergent_subseq_is_subseq convergent_subsequence_is_convergent by blast\n\nend\nend", "meta": {"author": "AaronCrighton", "repo": "Padics", "sha": "b451038d52193e2c351fe4a44c30c87586335656", "save_path": "github-repos/isabelle/AaronCrighton-Padics", "path": "github-repos/isabelle/AaronCrighton-Padics/Padics-b451038d52193e2c351fe4a44c30c87586335656/Zp_compact.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8807970873650401, "lm_q2_score": 0.7956581000631542, "lm_q1q2_score": 0.7008133370740278}}
{"text": "theory Subseq\n  imports Main Seq2less\nbegin\n\n(* Here we play with sub-sequences of 2-less sequences. *)\n\n(* Removal of one element from a sequence. *)\n\n(* lt_all: removal of one element (first,last,middle) preserves lt_all. *)\n\nlemma subseq_lt_all_remove_first:\n  \"lt_all x (h#t) \\<longrightarrow> lt_all x t\"\n  by simp\n\nlemma subseq_lt_all_remove_last:\n  \"lt_all x (s@[l]) \\<longrightarrow> lt_all x s\"\n  apply (induction s)\n  by auto\n\nlemma subseq_lt_all_remove_middle:\n  \"lt_all x (s@h#t) \\<longrightarrow> lt_all x (s@t)\"\n  apply (induction s)\n  by auto\n\n(* lt_2less: removal of one element (first,last,middle) preserves is_2less. *)\n\nlemma subseq_remove_first:\n  \"is_2less (h#t) \\<longrightarrow> is_2less t\"\n  by auto\n\nlemma subseq_remove_last:\n  \"is_2less (s@[x]) \\<longrightarrow> is_2less s\"\n  apply (induction s arbitrary: x)\n  apply simp\n  using subseq_lt_all_remove_last\n  by auto\n\nlemma subseq_remove_middle:\n  \"is_2less (s@x#t) \\<longrightarrow> is_2less (s@t)\"\n  apply (induction s arbitrary: t x)\n  using subseq_remove_last\n  apply simp\n  using subseq_lt_all_remove_middle\n  by (metis append_Cons is_2less.simps(2))\n\n(* Removal of a subsequence from a sequence. *)\n\n(* lt_all: removal of subsequence preserves lt_all *)\n\nlemma subseq_lt_all_prefix:\n  \"lt_all a (s@t) \\<longrightarrow> lt_all a s\"\n  apply (induction s)\n  by auto\n\nlemma subseq_lt_all_postfix:\n  \"lt_all a (s@t) \\<longrightarrow> lt_all a t\"\n  apply (induction s)\n  by auto\n\nlemma subseq_lt_all:\n  \"lt_all a (s@t) \\<longrightarrow> lt_all a s \\<and> lt_all a t\"\n  using subseq_lt_all_prefix subseq_lt_all_postfix\n  by blast\n\n(* is_2less: removal of subsequence preserves is_2less *)\n\nlemma subseq_postfix:\n  \"is_2less (s@t) \\<longrightarrow> is_2less t\"\n  apply (induction s arbitrary: t)\n  apply simp\n  using subseq_remove_first\n  by (metis append_Cons)\n\nlemma subseq_prefix:\n  \"is_2less (s@t) \\<longrightarrow> is_2less s\"\n  apply (induction t arbitrary: s)\n  apply simp\n  using subseq_remove_last subseq_lt_all_remove_last\n  by (metis (no_types, hide_lams) Cons_eq_appendI append_eq_appendI self_append_conv2)\n\ncorollary subseq_split_2:\n  \"is_2less (s@t) \\<longrightarrow> is_2less s \\<and> is_2less t\"\n  using subseq_prefix subseq_postfix\n  by blast\n\ncorollary subseq_split_3:\n  \"is_2less (p@s@t) \\<longrightarrow> is_2less p \\<and> is_2less s \\<and> is_2less t\"\n  using subseq_prefix subseq_postfix\n  by blast\n\nlemma subseq_infix:\n  \"is_2less (p@s@t) \\<longrightarrow> is_2less (p@t)\"\n  apply (induction s)\n  apply simp\n  using subseq_remove_middle\n  by auto\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/Subseq.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970779778824, "lm_q2_score": 0.7956581073313276, "lm_q1q2_score": 0.7008133360068457}}
{"text": "subsection\\<open>Okamoto \\<open>\\<Sigma>\\<close>-protocol\\<close>\n\ntheory Okamoto_Sigma_Commit imports\n  Commitment_Schemes\n  Sigma_Protocols\n  Cyclic_Group_Ext\n  Discrete_Log\n  \"HOL.GCD\"\n  Number_Theory_Aux\n  Uniform_Sampling \nbegin \n\nlocale okamoto_base = \n  fixes \\<G> :: \"'grp cyclic_group\" (structure)\n    and x :: nat\n  assumes prime_order: \"prime (order \\<G>)\"\nbegin\n\ndefinition \"g' = \\<^bold>g [^] x\"\n\nlemma order_gt_1: \"order \\<G> > 1\" \n  using prime_order \n  using prime_gt_1_nat by blast\n\nlemma order_gt_0 [simp]:\"order \\<G> > 0\" \n  using order_gt_1 by simp\n\ndefinition \"response r w e = do {\n  let (r1,r2) = r;\n  let (x1,x2) = w;\n  let z1 = (e * x1 + r1) mod (order \\<G>);\n  let z2 = (e * x2 + r2) mod (order \\<G>);\n  return_spmf ((z1,z2))}\"\n\nlemma lossless_response: \"lossless_spmf (response r w e)\"\n  by(simp add: response_def split_def)\n\ntype_synonym witness = \"nat \\<times> nat\"\ntype_synonym rand = \"nat \\<times> nat\"\ntype_synonym 'grp' msg = \"'grp'\"\ntype_synonym response = \"(nat \\<times> nat)\"\ntype_synonym challenge = nat\ntype_synonym 'grp' pub_in = \"'grp'\"\n\ndefinition init :: \"'grp pub_in \\<Rightarrow> witness \\<Rightarrow> (rand \\<times> 'grp msg) spmf\"\n  where \"init y w = do {\n    let (x1,x2) = w; \n    r1 \\<leftarrow> sample_uniform (order \\<G>);\n    r2 \\<leftarrow> sample_uniform (order \\<G>);\n    return_spmf ((r1,r2), \\<^bold>g [^] r1 \\<otimes> g' [^] r2)}\"\n\nlemma lossless_init: \"lossless_spmf (init h  w)\"\n  by(simp add: init_def)\n\ndefinition check :: \"'grp pub_in \\<Rightarrow> 'grp msg \\<Rightarrow> challenge \\<Rightarrow> response \\<Rightarrow> bool\"\n  where \"check h a e z = (\\<^bold>g [^] (fst z) \\<otimes> g' [^] (snd z) = a \\<otimes> (h [^] e) \\<and> a \\<in> carrier \\<G>)\"\n\ndefinition R :: \"('grp pub_in \\<times> witness) set\"\n  where \"R \\<equiv> {(h, w). (h = \\<^bold>g [^] (fst w) \\<otimes> g' [^] (snd w))}\"\n\ndefinition G :: \"('grp pub_in \\<times> witness) spmf\"\n  where \"G = do {\n    w1 \\<leftarrow> sample_uniform (order \\<G>);\n    w2 \\<leftarrow> sample_uniform (order \\<G>);\n    return_spmf (\\<^bold>g [^] w1 \\<otimes> g' [^] w2 , (w1,w2))}\"\n\ndefinition \"challenge_space = {..< order \\<G>}\"\n\nlemma lossless_G: \"lossless_spmf G\"\n  by(simp add: G_def)\n\ndefinition S2 :: \"'grp pub_in \\<Rightarrow> challenge \\<Rightarrow> ('grp msg, response) sim_out spmf\"\n  where \"S2 h c = do {\n    z1 \\<leftarrow> sample_uniform  (order \\<G>);\n    z2 \\<leftarrow> sample_uniform  (order \\<G>);\n  let a =  (\\<^bold>g [^] z1 \\<otimes> g' [^] z2) \\<otimes> (inv h [^] c); \n  return_spmf (a, (z1,z2))}\"\n\ndefinition R2 :: \"'grp pub_in \\<Rightarrow> witness \\<Rightarrow> challenge \\<Rightarrow> ('grp msg, challenge, response) conv_tuple spmf\"\n  where \"R2 h w c = do { \n    let (x1,x2) = w; \n    r1 \\<leftarrow> sample_uniform (order \\<G>);\n    r2 \\<leftarrow> sample_uniform (order \\<G>);\n    let z1 = (c * x1 + r1) mod (order \\<G>);\n    let z2 = (c * x2 + r2) mod (order \\<G>);\n    return_spmf (\\<^bold>g [^] r1 \\<otimes> g' [^] r2 ,c,(z1,z2))}\"\n\ndefinition ss_adversary :: \"'grp \\<Rightarrow> ('grp msg, challenge, response) conv_tuple \\<Rightarrow> ('grp msg, challenge, response) conv_tuple \\<Rightarrow> (nat \\<times> nat) spmf\"\n  where \"ss_adversary y c1 c2 = do {\n    let (a, e, (z1,z2)) = c1;\n    let (a', e', (z1',z2')) = c2;\n    return_spmf (if (e > e') then (nat ((int z1 - int z1') * inverse (e - e') (order \\<G>) mod order \\<G>)) else \n                      (nat ((int z1' - int z1) * inverse (e' - e) (order \\<G>) mod order \\<G>)), \n                 if (e > e') then (nat ((int z2  - int z2') * inverse (e - e') (order \\<G>) mod order \\<G>)) else \n                      (nat ((int z2' - int z2) * inverse (e' - e) (order \\<G>) mod order \\<G>)))}\"\n\ndefinition \"valid_pub = carrier \\<G>\"\nend\n\nlocale okamoto = okamoto_base + cyclic_group \\<G>\nbegin\n\nlemma g'_in_carrier [simp]: \"g' \\<in> carrier \\<G>\" \n  using g'_def by auto\n\nsublocale \\<Sigma>_protocols_base: \\<Sigma>_protocols_base init response check R S2 ss_adversary challenge_space valid_pub \n  by unfold_locales (auto simp add: R_def valid_pub_def)\n\nlemma \"\\<Sigma>_protocols_base.R h w c = R2 h w c\"\n  by(simp add: \\<Sigma>_protocols_base.R_def R2_def; simp add: init_def split_def response_def)\n\nlemma completeness: \n  shows \"\\<Sigma>_protocols_base.completeness\"\nproof-\n  have \"(\\<^bold>g [^] ((e * fst w' + y) mod order \\<G>) \\<otimes> g' [^] ((e * snd w' + ya) mod order \\<G>) = \\<^bold>g [^] y \\<otimes> g' [^] ya \\<otimes> (\\<^bold>g [^] fst w' \\<otimes> g' [^] snd w') [^] e)\" \n    for e y ya :: nat and w' :: \"nat \\<times> nat\"\n  proof-\n    have \"\\<^bold>g [^] ((e * fst w' + y) mod order \\<G>) \\<otimes> g' [^] ((e * snd w' + ya) mod order \\<G>) = \\<^bold>g [^] ((y + e * fst w')) \\<otimes> g' [^] ((ya + e * snd w'))\"\n      by (simp add: cyclic_group.pow_carrier_mod cyclic_group_axioms g'_def add.commute pow_generator_mod)\n    also have \"... = \\<^bold>g [^] y \\<otimes> \\<^bold>g [^] (e * fst w') \\<otimes> g' [^] ya \\<otimes> g' [^] (e * snd w')\" \n      by (simp add: g'_def m_assoc nat_pow_mult)\n    also have \"... = \\<^bold>g [^] y \\<otimes> g' [^] ya \\<otimes> \\<^bold>g [^] (e * fst w') \\<otimes> g' [^] (e * snd w')\" \n      by (smt add.commute g'_def generator_closed m_assoc nat_pow_closed nat_pow_mult nat_pow_pow)\n    also have \"... = \\<^bold>g [^] y \\<otimes> g' [^] ya \\<otimes> ((\\<^bold>g [^] fst w') [^] e \\<otimes> (g' [^] snd w') [^] e)\" \n      by (simp add: m_assoc mult.commute nat_pow_pow)\n    also have \"... =  \\<^bold>g [^] y \\<otimes> g' [^] ya \\<otimes> ((\\<^bold>g [^] fst w' \\<otimes> g' [^] snd w') [^] e)\"   \n      by (smt power_distrib g'_def generator_closed mult.commute nat_pow_closed nat_pow_mult nat_pow_pow)\n    ultimately show ?thesis by simp\n  qed\n  thus ?thesis \n  unfolding \\<Sigma>_protocols_base.completeness_def \\<Sigma>_protocols_base.completeness_game_def\n  by(simp add: R_def challenge_space_def init_def check_def response_def split_def bind_spmf_const)\nqed\n\nlemma hvzk_z_r:\n  assumes r1: \"r1 < order \\<G>\" \n  shows \"r1 = ((r1 + c * (x1 :: nat)) mod (order \\<G>) + order \\<G> * c * x1 - c * x1) mod (order \\<G>)\"\nproof(cases \"x1 = 0\")\n  case True\n  then show ?thesis using r1 by simp\nnext\n  case x1_neq_0: False\n  have z1_eq: \"[(r1 + c * x1) mod (order \\<G>) + order \\<G> * c * x1 = r1 + c * x1] (mod (order \\<G>))\"\n    using gr_implies_not_zero order_gt_1\n    by (simp add: Groups.mult_ac(1) cong_def)\n  hence \"[(r1 + c * x1) mod (order \\<G>) + order \\<G> * c * x1 - c * x1 = r1] (mod (order \\<G>))\" \n  proof(cases \"c = 0\")\n    case True\n    then show ?thesis \n      using z1_eq by auto\n  next\n    case False\n    have \"order \\<G> * c * x1 - c * x1 > 0\" using x1_neq_0 False \n      using prime_gt_1_nat prime_order by auto \n    thus ?thesis \n      by (smt Groups.add_ac(2) add_diff_inverse_nat cong_add_lcancel_nat diff_is_0_eq le_simps(1) neq0_conv trans_less_add2 z1_eq zero_less_diff)\n  qed\n  thus ?thesis \n    by (simp add: r1 cong_def)\nqed\n\nlemma hvzk_z1_r1_tuple_rewrite: \n  assumes r1: \"r1 < order \\<G>\" \n  shows \"(\\<^bold>g [^] r1 \\<otimes> g' [^] r2, c, (r1 + c * x1) mod order \\<G>, (r2 + c * x2) mod order \\<G>) = \n              (\\<^bold>g [^] (((r1 + c * x1) mod order \\<G> + order \\<G> * c * x1 - c * x1) mod order \\<G>)  \n                  \\<otimes> g' [^] r2, c, (r1 + c * x1) mod order \\<G>, (r2 + c * x2) mod order \\<G>)\"\nproof-\n  have \"\\<^bold>g [^] r1 = \\<^bold>g [^] (((r1 + c * x1) mod order \\<G> + order \\<G> * c * x1 - c * x1) mod order \\<G>)\"\n    using assms hvzk_z_r by simp\n  thus ?thesis by argo\nqed\n\nlemma hvzk_z2_r2_tuple_rewrite: \n  assumes \"xb < order \\<G>\" \n  shows \"(\\<^bold>g [^] (((x' + xa * x1) mod order \\<G> + order \\<G> * xa * x1 - xa * x1) mod order \\<G>) \n            \\<otimes> g' [^] xb, xa, (x' + xa * x1) mod order \\<G>, (xb + xa * x2) mod order \\<G>) =\n               (\\<^bold>g [^] (((x' + xa * x1) mod order \\<G> + order \\<G> * xa * x1 - xa * x1) mod order \\<G>) \n                \\<otimes> g' [^] (((xb + xa * x2) mod order \\<G> + order \\<G> * xa * x2 - xa * x2) mod order \\<G>), xa, (x' + xa * x1) mod order \\<G>, (xb + xa * x2) mod order \\<G>)\"\nproof-\n  have \"g' [^] xb = g' [^] (((xb + xa * x2) mod order \\<G> + order \\<G> * xa * x2 - xa * x2) mod order \\<G>)\"\n    using hvzk_z_r assms by simp\n    thus ?thesis by argo\nqed\n\nlemma hvzk_sim_inverse_rewrite: \n  assumes h: \"h =  \\<^bold>g [^] (x1 :: nat) \\<otimes> g' [^] (x2 :: nat)\"\n  shows \"\\<^bold>g [^] (((z1::nat) + order \\<G> * c * x1 - c * x1) mod (order \\<G>)) \n            \\<otimes> g' [^] (((z2::nat) + order \\<G> * c * x2 - c * x2) mod (order \\<G>))\n                = (\\<^bold>g [^] z1 \\<otimes> g' [^] z2) \\<otimes> (inv h [^] c)\"\n(is \"?lhs = ?rhs\")\nproof-\n  have in_carrier1: \"(g' [^] x2) [^] c \\<in> carrier \\<G>\" by simp \n  have in_carrier2: \"(\\<^bold>g [^] x1) [^] c \\<in> carrier \\<G>\" by simp\n  have pow_distrib1: \"order \\<G> * c * x1 - c * x1 = (order \\<G> - 1) * c * x1\" \n    and pow_distrib2: \"order \\<G> * c * x2 - c * x2 = (order \\<G> - 1) * c * x2\" \n    using assms by (simp add: diff_mult_distrib)+\n  have \"?lhs = \\<^bold>g [^] (z1 + order \\<G> * c * x1 - c * x1) \\<otimes> g' [^] (z2 + order \\<G> * c  * x2 - c * x2)\"\n    by (simp add: pow_carrier_mod)\n  also have \"... = \\<^bold>g [^] (z1 + (order \\<G> * c * x1 - c * x1)) \\<otimes> g' [^] (z2 + (order \\<G> * c * x2 - c * x2))\" \n    using h \n    by (smt Nat.add_diff_assoc diff_zero le_simps(1) nat_0_less_mult_iff neq0_conv pow_distrib1 pow_distrib2 prime_gt_1_nat prime_order zero_less_diff)\n  also have \"... =  \\<^bold>g [^] z1 \\<otimes> \\<^bold>g [^] (order \\<G> * c * x1 - c * x1) \\<otimes> g' [^] z2 \\<otimes> g' [^] (order \\<G> * c * x2 - c * x2)\"\n    using nat_pow_mult \n    by (simp add: m_assoc) \n  also have \"... = \\<^bold>g [^] z1 \\<otimes> g' [^] z2 \\<otimes> \\<^bold>g [^] (order \\<G> * c * x1 - c * x1) \\<otimes> g' [^] (order \\<G> * c * x2 - c * x2)\"\n    by (smt add.commute g'_def generator_closed m_assoc nat_pow_closed nat_pow_mult nat_pow_pow)\n  also have \"... = \\<^bold>g [^] z1 \\<otimes> g' [^] z2 \\<otimes> \\<^bold>g [^] ((order \\<G> - 1) * c * x1) \\<otimes> g' [^] ((order \\<G> - 1) * c * x2)\" \n    using pow_distrib1 pow_distrib2 by argo\n  also have \"... = \\<^bold>g [^] z1 \\<otimes> g' [^] z2 \\<otimes> (\\<^bold>g [^] (order \\<G> - 1)) [^] (c * x1) \\<otimes> (g' [^] ((order \\<G> - 1))) [^] (c * x2)\" \n    by (simp add: more_arith_simps(11) nat_pow_pow)\n  also have \"... = \\<^bold>g [^] z1 \\<otimes> g' [^] z2 \\<otimes> (inv (\\<^bold>g [^] c)) [^] x1 \\<otimes> (inv (g' [^] c)) [^] x2\"\n    using assms neg_power_inverse  inverse_pow_pow nat_pow_pow prime_gt_1_nat prime_order by auto\n  also have \"... = \\<^bold>g [^] z1 \\<otimes> g' [^] z2 \\<otimes> (inv ((\\<^bold>g [^] c) [^] x1)) \\<otimes> (inv ((g' [^] c) [^] x2))\" \n    by (simp add: inverse_pow_pow)\n  also have \"... = \\<^bold>g [^] z1 \\<otimes> g' [^] z2 \\<otimes> ((inv ((\\<^bold>g [^] x1) [^] c)) \\<otimes> (inv ((g' [^] x2) [^] c)))\" \n    by (simp add: mult.commute cyclic_group_assoc nat_pow_pow)\n  also have \"... = \\<^bold>g [^] z1 \\<otimes> g' [^] z2 \\<otimes> inv ((\\<^bold>g [^] x1) [^] c \\<otimes> (g' [^] x2) [^] c)\"\n    using inverse_split in_carrier2 in_carrier1 by simp\n  also have \"... = \\<^bold>g [^] z1 \\<otimes> g' [^] z2 \\<otimes> inv (h [^] c)\" \n    using h  cyclic_group_commute monoid_comm_monoidI \n    by (simp add: pow_mult_distrib)\n  ultimately show ?thesis \n    by (simp add: h inverse_pow_pow)\nqed\n\nlemma hv_zk: \n  assumes \"h =  \\<^bold>g [^] x1 \\<otimes> g' [^] x2\"\n  shows \"\\<Sigma>_protocols_base.R h (x1,x2) c = \\<Sigma>_protocols_base.S h c\"\n  including monad_normalisation\nproof-\n  have \"\\<Sigma>_protocols_base.R h (x1,x2) c = do { \n    r1 \\<leftarrow> sample_uniform (order \\<G>);\n    r2 \\<leftarrow> sample_uniform (order \\<G>);\n    let z1 = (r1 + c * x1) mod (order \\<G>);\n    let z2 = (r2 + c * x2) mod (order \\<G>);\n    return_spmf ( \\<^bold>g [^] r1 \\<otimes> g' [^] r2 ,c,(z1,z2))}\"\n      by(simp add: \\<Sigma>_protocols_base.R_def R2_def; simp add: add.commute init_def split_def response_def)\n    also have \"... = do { \n    r2 \\<leftarrow> sample_uniform (order \\<G>);\n    z1 \\<leftarrow> map_spmf (\\<lambda> r1. (r1 + c * x1) mod (order \\<G>)) (sample_uniform (order \\<G>));\n    let z2 = (r2 + c * x2) mod (order \\<G>);\n    return_spmf (\\<^bold>g [^] ((z1 + order \\<G> * c * x1 - c * x1) mod (order \\<G>)) \\<otimes> g' [^] r2 ,c,(z1,z2))}\"\n      by(simp add: bind_map_spmf o_def Let_def hvzk_z1_r1_tuple_rewrite assms cong: bind_spmf_cong_simp)\n  also have \"... = do { \n    z1 \\<leftarrow> map_spmf (\\<lambda> r1. (r1 + c * x1) mod (order \\<G>)) (sample_uniform (order \\<G>));\n    z2 \\<leftarrow> map_spmf (\\<lambda> r2. (r2 + c * x2) mod (order \\<G>)) (sample_uniform (order \\<G>));\n    return_spmf (\\<^bold>g [^] ((z1 + order \\<G> * c * x1 - c * x1) mod (order \\<G>)) \\<otimes> g' [^] ((z2 + order \\<G> * c * x2 - c * x2) mod (order \\<G>)) ,c,(z1,z2))}\"\n    by(simp add: bind_map_spmf o_def Let_def hvzk_z2_r2_tuple_rewrite cong: bind_spmf_cong_simp)\n  also have \"... = do { \n    z1 \\<leftarrow> map_spmf (\\<lambda> r1. (c * x1 + r1) mod (order \\<G>)) (sample_uniform (order \\<G>));\n    z2 \\<leftarrow> map_spmf (\\<lambda> r2. (c * x2 + r2) mod (order \\<G>)) (sample_uniform (order \\<G>));\n    return_spmf (\\<^bold>g [^] ((z1 + order \\<G> * c * x1 - c * x1) mod (order \\<G>)) \\<otimes> g' [^] ((z2 + order \\<G> * c * x2 - c * x2) mod (order \\<G>)) ,c,(z1,z2))}\"\n    by(simp add: add.commute)\n  also have \"... = do { \n    z1 \\<leftarrow> (sample_uniform (order \\<G>));\n    z2 \\<leftarrow> (sample_uniform (order \\<G>));\n    return_spmf (\\<^bold>g [^] ((z1 + order \\<G> * c * x1 - c * x1) mod (order \\<G>)) \\<otimes> g' [^] ((z2 + order \\<G> * c * x2 - c * x2) mod (order \\<G>)) ,c,(z1,z2))}\"\n      by(simp add: samp_uni_plus_one_time_pad)\n  also have \"... = do { \n    z1 \\<leftarrow> (sample_uniform (order \\<G>));\n    z2 \\<leftarrow> (sample_uniform (order \\<G>));\n    return_spmf ((\\<^bold>g [^] z1 \\<otimes> g' [^] z2) \\<otimes> (inv h [^] c) ,c,(z1,z2))}\"\n      by(simp add: hvzk_sim_inverse_rewrite assms cong: bind_spmf_cong_simp) \n  ultimately show ?thesis \n    by(simp add: \\<Sigma>_protocols_base.S_def S2_def bind_map_spmf map_spmf_conv_bind_spmf)\nqed\n\nlemma HVZK: \n  shows \"\\<Sigma>_protocols_base.HVZK\"\n  unfolding \\<Sigma>_protocols_base.HVZK_def \n  apply(auto simp add: R_def challenge_space_def hv_zk S2_def check_def valid_pub_def)\n  by (metis (no_types, lifting) cyclic_group_commute g'_in_carrier generator_closed inv_closed inv_solve_left inverse_pow_pow m_closed nat_pow_closed)\n\nlemma ss_rewrite:\n  assumes \"h \\<in> carrier \\<G>\"\n    and \"a \\<in> carrier \\<G>\"\n    and \"e < order \\<G>\" \n    and \"\\<^bold>g [^] z1 \\<otimes> g' [^] z1' = a \\<otimes> h [^] e\"\n    and \"e' < e\"\n    and \"\\<^bold>g [^] z2 \\<otimes> g' [^] z2' = a \\<otimes> h [^] e' \"\n  shows \"h = \\<^bold>g [^] ((int z1 - int z2) * fst (bezw (e - e') (order \\<G>)) mod int (order \\<G>)) \\<otimes> g' [^] ((int z1' - int z2') * fst (bezw (e - e') (order \\<G>)) mod int (order \\<G>))\"\nproof-\n  have gcd: \"gcd (e - e') (order \\<G>) = 1\"\n    using prime_field assms prime_order by simp \n  have \"\\<^bold>g [^] z1 \\<otimes> g' [^] z1' \\<otimes> inv (h [^] e) = a\" \n    by (simp add: inv_solve_right' assms)\n  moreover have \"\\<^bold>g [^] z2 \\<otimes> g' [^] z2' \\<otimes> inv (h [^] e') = a\" \n    by (simp add: assms inv_solve_right')\n  ultimately have \"\\<^bold>g [^] z2 \\<otimes> g' [^] z2' \\<otimes> inv (h [^] e') = \\<^bold>g [^] z1 \\<otimes> g' [^] z1' \\<otimes> inv (h [^] e)\"\n    using g'_def by (simp add: nat_pow_pow)\n  moreover obtain t :: nat where t: \"h = \\<^bold>g [^] t\" \n    using assms generatorE by blast\n  ultimately have \"\\<^bold>g [^] z2 \\<otimes> \\<^bold>g [^] (x * z2') \\<otimes> \\<^bold>g [^] (t * e) = \\<^bold>g [^] z1 \\<otimes> \\<^bold>g [^] (x * z1') \\<otimes> (\\<^bold>g [^] (t * e'))\" \n    using assms(2) assms(4) cyclic_group_commute m_assoc g'_def nat_pow_pow by auto\n  hence \"\\<^bold>g [^] (z2 + x * z2' + t * e) = \\<^bold>g [^] (z1 + x * z1' + t * e')\"  \n    by (simp add: nat_pow_mult)\n  hence \"[z2 + x * z2' + t * e = z1 + x * z1' + t * e'] (mod order \\<G>)\"\n    using group_eq_pow_eq_mod order_gt_0 by blast\n  hence \"[int z2 + int x * int z2' + int t * int e = int z1 + int x * int z1' + int t * int e'] (mod order \\<G>)\"\n    using cong_int_iff by force\n  hence \"[int z1 + int x * int z1' - int z2 - int x * int z2' = int t * int e - int t * int e'] (mod order \\<G>)\"\n    by (smt cong_diff_iff_cong_0 cong_sym)\n  hence \"[int z1 + int x * int z1' - int z2 - int x * int z2' = int t * (e - e')] (mod order \\<G>)\"\n    using int_distrib(4) assms by (simp add: of_nat_diff)\n  hence \"[(int z1 + int x * int z1' - int z2 - int x * int z2') * fst (bezw (e - e') (order \\<G>)) = int t * (e - e') * fst (bezw (e - e') (order \\<G>))] (mod order \\<G>)\"\n    using cong_scalar_right by blast\n  hence \"[(int z1 + int x * int z1' - int z2 - int x * int z2') * fst (bezw (e - e') (order \\<G>)) = int t * ((e - e') * fst (bezw (e - e') (order \\<G>)))] (mod order \\<G>)\"\n    by (simp add: mult.assoc)\n  hence \"[(int z1 + int x * int z1' - int z2 - int x * int z2') * fst (bezw (e - e') (order \\<G>)) = int t * 1] (mod order \\<G>)\"\n    by (metis (no_types, hide_lams) cong_scalar_left cong_trans inverse gcd)\n  hence \"[(int z1 - int z2 + int x * int z1' - int x * int z2') * fst (bezw (e - e') (order \\<G>)) = int t] (mod order \\<G>)\"\n    by smt\n  hence \"[(int z1 - int z2 + int x * (int z1' - int z2')) * fst (bezw (e - e') (order \\<G>)) = int t] (mod order \\<G>)\"\n    by (simp add: Rings.ring_distribs(4) add_diff_eq)\n  hence \"[nat ((int z1 - int z2 + int x * (int z1' - int z2')) * fst (bezw (e - e') (order \\<G>)) mod (order \\<G>)) = int t] (mod order \\<G>)\"\n    by auto\n  hence \"\\<^bold>g [^] (nat ((int z1 - int z2 + int x * (int z1' - int z2')) * fst (bezw (e - e') (order \\<G>)) mod (order \\<G>))) = \\<^bold>g [^] t\"\n    using cong_int_iff finite_carrier pow_generator_eq_iff_cong by blast\n  hence \"\\<^bold>g [^] ((int z1 - int z2 + int x * (int z1' - int z2')) * fst (bezw (e - e') (order \\<G>))) = \\<^bold>g [^] t\"\n    using pow_generator_mod_int by auto\n  hence \"\\<^bold>g [^] ((int z1 - int z2) * fst (bezw (e - e') (order \\<G>)) + int x * (int z1' - int z2') * fst (bezw (e - e') (order \\<G>))) = \\<^bold>g [^] t\"\n    by (metis Rings.ring_distribs(2) t)\n  hence \"\\<^bold>g [^] ((int z1 - int z2) * fst (bezw (e - e') (order \\<G>))) \\<otimes> \\<^bold>g [^] (int x * (int z1' - int z2') * fst (bezw (e - e') (order \\<G>))) = \\<^bold>g [^] t\"\n    using int_pow_mult by auto\n  thus ?thesis \n    by (metis (mono_tags, hide_lams) g'_def generator_closed int_pow_int int_pow_pow mod_mult_right_eq more_arith_simps(11) pow_generator_mod_int t)\nqed\n\nlemma \n  assumes h_mem: \"h \\<in> carrier \\<G>\" \n    and a_mem: \"a \\<in> carrier \\<G>\" \n    and a: \"\\<^bold>g [^] fst z \\<otimes> g' [^] snd z = a \\<otimes> h [^] e\"\n    and a': \"\\<^bold>g [^] fst z' \\<otimes> g' [^] snd z' = a \\<otimes> h [^] e'\"\n    and e_e'_mod: \"e' mod order \\<G> < e mod order \\<G>\"\n  shows \"h = \\<^bold>g [^] ((int (fst z) - int (fst z')) * fst (bezw ((e mod order \\<G> - e' mod order \\<G>) mod order \\<G>) (order \\<G>)) mod int (order \\<G>)) \n              \\<otimes> g' [^] ((int (snd z) - int (snd z')) * fst (bezw ((e mod order \\<G> - e' mod order \\<G>) mod order \\<G>) (order \\<G>)) mod int (order \\<G>))\"\nproof-\n  have gcd: \"gcd ((e mod order \\<G> - e' mod order \\<G>) mod order \\<G>) (order \\<G>) = 1\"\n    using prime_field \n    by (simp add: assms less_imp_diff_less linorder_not_le prime_order)\n  have \"\\<^bold>g [^] fst z \\<otimes> g' [^] snd z \\<otimes> inv (h [^] e) = a\" \n    using a h_mem a_mem by (simp add: inv_solve_right')\n  moreover have \"\\<^bold>g [^] fst z' \\<otimes> g' [^] snd z' \\<otimes> inv (h [^] e') = a\" \n    using a h_mem a_mem by (simp add: assms(4) inv_solve_right')\n  ultimately have \"\\<^bold>g [^] fst z \\<otimes> \\<^bold>g [^] (x * snd z) \\<otimes> inv (h [^] e) = \\<^bold>g [^] fst z' \\<otimes> \\<^bold>g [^] (x * snd z') \\<otimes> inv (h [^] e')\"\n    using g'_def by (simp add: nat_pow_pow)\n  moreover obtain t :: nat where t: \"h = \\<^bold>g [^] t\" \n    using h_mem generatorE by blast\n  ultimately have \"\\<^bold>g [^] fst z \\<otimes> \\<^bold>g [^] (x * snd z) \\<otimes> \\<^bold>g [^] (t * e') = \\<^bold>g [^] fst z' \\<otimes> \\<^bold>g [^] (x * snd z') \\<otimes> \\<^bold>g [^] (t * e)\"\n    using a_mem assms(3) assms(4) cyclic_group_assoc cyclic_group_commute g'_def nat_pow_pow by auto\n  hence \"\\<^bold>g [^] (fst z + x * snd z + t * e') = \\<^bold>g [^] (fst z' + x * snd z' + t * e)\"\n    by (simp add: nat_pow_mult)\n  hence \"[fst z + x * snd z + t * e' = fst z' + x * snd z' + t * e] (mod order \\<G>)\"\n    using group_eq_pow_eq_mod order_gt_0 by blast\n  hence \"[int (fst z) + int x * int (snd z) + int t * int e' = int (fst z') + int x * int (snd z') + int t * int e] (mod order \\<G>)\"\n    using cong_int_iff by force\n  hence \"[int (fst z) - int (fst z') + int x * int (snd z) - int x * int (snd z') =  int t * int e - int t  * int e'] (mod order \\<G>)\"\n    by (smt cong_diff_iff_cong_0)\n  hence \"[int (fst z) - int (fst z') + int x * (int (snd z) - int (snd z')) =  int t * (int e -  int e')] (mod order \\<G>)\"\n  proof -\n    have \"[int (fst z) + (int (x * snd z) - (int (fst z') + int (x * snd z'))) = int t * (int e - int e')] (mod int (order \\<G>))\"\n      by (simp add: Rings.ring_distribs(4) \\<open>[int (fst z) - int (fst z') + int x * int (snd z) - int x * int (snd z') = int t * int e - int t * int e'] (mod int (order \\<G>))\\<close> add_diff_add add_diff_eq)\n    then have \"\\<exists>i. [int (fst z) + (int x * int (snd z) - (int (fst z') + i * int (snd z'))) = int t * (int e - int e') + int (snd z') * (int x - i)] (mod int (order \\<G>))\"\n      by (metis (no_types) add.commute arith_simps(49) cancel_comm_monoid_add_class.diff_cancel int_ops(7) mult_eq_0_iff)\n    then have \"\\<exists>i. [int (fst z) - int (fst z') + (int x * (int (snd z) - int (snd z')) + i) = int t * (int e - int e') + i] (mod int (order \\<G>))\"\n      by (metis (no_types) add_diff_add add_diff_eq mult_diff_mult mult_of_nat_commute)\n    then show ?thesis\n      by (metis (no_types) add.assoc cong_add_rcancel)\n  qed\n  hence \"[int (fst z) - int (fst z') + int x * (int (snd z) - int (snd z')) =  int t * (int e mod order \\<G> - int e' mod order \\<G>) mod order \\<G>] (mod order \\<G>)\"\n    by (metis (mono_tags, lifting) cong_def mod_diff_eq mod_mod_trivial mod_mult_right_eq)\n  hence \"[int (fst z) - int (fst z') + int x * (int (snd z) - int (snd z')) =  int t * (e mod order \\<G> - e' mod order \\<G>) mod order \\<G>] (mod order \\<G>)\"\n    using e_e'_mod \n    by (simp add: int_ops(9) of_nat_diff)\n  hence \"[(int (fst z) - int (fst z') + int x * (int (snd z) - int (snd z'))) \n            * fst (bezw ((e mod order \\<G> - e' mod order \\<G>) mod order \\<G>) (order \\<G>)) mod order \\<G> \n               =  int t * (e mod order \\<G> - e' mod order \\<G>) mod order \\<G> \n                  * fst (bezw ((e mod order \\<G> - e' mod order \\<G>) mod order \\<G>) (order \\<G>)) mod order \\<G>] (mod order \\<G>)\"\n    using cong_cong_mod_int cong_scalar_right by blast\n  hence \"[(int (fst z) - int (fst z') + int x * (int (snd z) - int (snd z'))) \n            * fst (bezw ((e mod order \\<G> - e' mod order \\<G>) mod order \\<G>) (order \\<G>)) mod order \\<G> \n               =  int t * ((e mod order \\<G> - e' mod order \\<G>) mod order \\<G> \n                  * fst (bezw ((e mod order \\<G> - e' mod order \\<G>) mod order \\<G>) (order \\<G>)) mod order \\<G>)] (mod order \\<G>)\"\n    by (metis (no_types, lifting) Groups.mult_ac(1) cong_mod_right less_imp_diff_less mod_less mod_mult_left_eq mod_mult_right_eq order_gt_0 unique_euclidean_semiring_numeral_class.pos_mod_bound)\n  hence \"[(int (fst z) - int (fst z') + int x * (int (snd z) - int (snd z'))) \n            * fst (bezw ((e mod order \\<G> - e' mod order \\<G>) mod order \\<G>) (order \\<G>)) mod order \\<G> \n               =  int t * 1] (mod order \\<G>)\"\n    using inverse gcd \n    by (smt Num.of_nat_simps(5) Number_Theory_Aux.inverse cong_def mod_mult_right_eq more_arith_simps(6) of_nat_1)\n  hence \"[((int (fst z) - int (fst z')) + (int x * (int (snd z) - int (snd z')))) \n            * fst (bezw ((e mod order \\<G> - e' mod order \\<G>) mod order \\<G>) (order \\<G>)) mod order \\<G> \n               = int t] (mod order \\<G>)\"\n    by auto\n  hence \"[(int (fst z) - int (fst z')) * (fst (bezw ((e mod order \\<G> - e' mod order \\<G>) mod order \\<G>) (order \\<G>)) mod order \\<G>) + (int x * (int (snd z) - int (snd z'))) \n            * (fst (bezw ((e mod order \\<G> - e' mod order \\<G>) mod order \\<G>) (order \\<G>)) mod order \\<G>) \n               = int t] (mod order \\<G>)\"\n    by (metis (no_types, hide_lams) cong_mod_left distrib_right mod_mult_right_eq)\n  hence \"[(int (fst z) - int (fst z')) * fst (bezw ((e mod order \\<G> - e' mod order \\<G>) mod order \\<G>) (order \\<G>)) mod order \\<G> + (int x * (int (snd z) - int (snd z'))) \n            * (fst (bezw ((e mod order \\<G> - e' mod order \\<G>) mod order \\<G>) (order \\<G>)) mod order \\<G>) \n               = t] (mod order \\<G>)\"\n  proof -\n    have \"[(int (fst z) - int (fst z')) * fst (bezw ((e mod order \\<G> - e' mod order \\<G>) mod order \\<G>) (order \\<G>)) = (int (fst z) - int (fst z')) * (fst (bezw ((e mod order \\<G> - e' mod order \\<G>) mod order \\<G>) (order \\<G>)) mod int (order \\<G>))] (mod int (order \\<G>))\"\n      by (metis (no_types) cong_def mod_mult_right_eq)\n    then show ?thesis\n      by (meson \\<open>[(int (fst z) - int (fst z')) * (fst (bezw ((e mod order \\<G> - e' mod order \\<G>) mod order \\<G>) (order \\<G>)) mod int (order \\<G>)) + int x * (int (snd z) - int (snd z')) * (fst (bezw ((e mod order \\<G> - e' mod order \\<G>) mod order \\<G>) (order \\<G>)) mod int (order \\<G>)) = int t] (mod int (order \\<G>))\\<close> cong_add_rcancel cong_mod_left cong_trans)\n  qed\n  hence \"[(int (fst z) - int (fst z')) * fst (bezw ((e mod order \\<G> - e' mod order \\<G>) mod order \\<G>) (order \\<G>)) mod order \\<G> + (int x * (int (snd z) - int (snd z'))) \n            * fst (bezw ((e mod order \\<G> - e' mod order \\<G>) mod order \\<G>) (order \\<G>)) mod order \\<G>\n               = t] (mod order \\<G>)\"\n  proof -\n    have \"int x * ((int (snd z) - int (snd z')) * (fst (bezw ((e mod order \\<G> - e' mod order \\<G>) mod order \\<G>) (order \\<G>)) mod int (order \\<G>))) mod int (order \\<G>) = int x * ((int (snd z) - int (snd z')) * fst (bezw ((e mod order \\<G> - e' mod order \\<G>) mod order \\<G>) (order \\<G>))) mod int (order \\<G>) mod int (order \\<G>)\"\n      by (metis (no_types) mod_mod_trivial mod_mult_right_eq)\n    then have \"[int x * ((int (snd z) - int (snd z')) * fst (bezw ((e mod order \\<G> - e' mod order \\<G>) mod order \\<G>) (order \\<G>))) mod int (order \\<G>) = int x * ((int (snd z) - int (snd z')) * (fst (bezw ((e mod order \\<G> - e' mod order \\<G>) mod order \\<G>) (order \\<G>)) mod int (order \\<G>)))] (mod int (order \\<G>))\"\n      by (metis (no_types) cong_def)\n    then have \"[(int (fst z) - int (fst z')) * fst (bezw ((e mod order \\<G> - e' mod order \\<G>) mod order \\<G>) (order \\<G>)) mod int (order \\<G>) + int x * ((int (snd z) - int (snd z')) * fst (bezw ((e mod order \\<G> - e' mod order \\<G>) mod order \\<G>) (order \\<G>))) mod int (order \\<G>) = (int (fst z) - int (fst z')) * fst (bezw ((e mod order \\<G> - e' mod order \\<G>) mod order \\<G>) (order \\<G>)) mod int (order \\<G>) + int x * (int (snd z) - int (snd z')) * (fst (bezw ((e mod order \\<G> - e' mod order \\<G>) mod order \\<G>) (order \\<G>)) mod int (order \\<G>))] (mod int (order \\<G>))\"\n      by (metis (no_types) Groups.mult_ac(1) cong_add cong_refl)\n    then have \"[(int (fst z) - int (fst z')) * fst (bezw ((e mod order \\<G> - e' mod order \\<G>) mod order \\<G>) (order \\<G>)) mod int (order \\<G>) + int x * ((int (snd z) - int (snd z')) * fst (bezw ((e mod order \\<G> - e' mod order \\<G>) mod order \\<G>) (order \\<G>))) mod int (order \\<G>) = int t] (mod int (order \\<G>))\"\n      using \\<open>[(int (fst z) - int (fst z')) * fst (bezw ((e mod order \\<G> - e' mod order \\<G>) mod order \\<G>) (order \\<G>)) mod int (order \\<G>) + int x * (int (snd z) - int (snd z')) * (fst (bezw ((e mod order \\<G> - e' mod order \\<G>) mod order \\<G>) (order \\<G>)) mod int (order \\<G>)) = int t] (mod int (order \\<G>))\\<close> cong_trans by blast\n    then show ?thesis\n      by (metis (no_types) Groups.mult_ac(1))\n  qed\n  hence \"\\<^bold>g [^] ((int (fst z) - int (fst z')) * fst (bezw ((e mod order \\<G> - e' mod order \\<G>) mod order \\<G>) (order \\<G>)) mod order \\<G> + (int x * (int (snd z) - int (snd z'))) \n            * fst (bezw ((e mod order \\<G> - e' mod order \\<G>) mod order \\<G>) (order \\<G>)) mod order \\<G>)\n               = \\<^bold>g [^] t\"\n    by (metis cong_def int_pow_int pow_generator_mod_int)\n  hence \"\\<^bold>g [^] ((int (fst z) - int (fst z')) * fst (bezw ((e mod order \\<G> - e' mod order \\<G>) mod order \\<G>) (order \\<G>)) mod order \\<G>) \\<otimes> \\<^bold>g [^] ((int x * (int (snd z) - int (snd z'))) \n            * fst (bezw ((e mod order \\<G> - e' mod order \\<G>) mod order \\<G>) (order \\<G>)) mod order \\<G>)\n               = \\<^bold>g [^] t\"\n    using int_pow_mult by auto\n  hence \"\\<^bold>g [^] ((int (fst z) - int (fst z')) * fst (bezw ((e mod order \\<G> - e' mod order \\<G>) mod order \\<G>) (order \\<G>)) mod order \\<G>) \\<otimes> \\<^bold>g [^] ((int x * ((int (snd z) - int (snd z'))) \n            * fst (bezw ((e mod order \\<G> - e' mod order \\<G>) mod order \\<G>) (order \\<G>)) mod order \\<G>))\n               = \\<^bold>g [^] t\"\n    by blast\n  hence \"\\<^bold>g [^] ((int (fst z) - int (fst z')) * fst (bezw ((e mod order \\<G> - e' mod order \\<G>) mod order \\<G>) (order \\<G>)) mod order \\<G>) \\<otimes> g' [^] ((((int (snd z) - int (snd z'))) \n            * fst (bezw ((e mod order \\<G> - e' mod order \\<G>) mod order \\<G>) (order \\<G>)) mod order \\<G>))\n               = \\<^bold>g [^] t\"\n    by (smt g'_def cyclic_group.generator_closed int_pow_int int_pow_pow mod_mult_right_eq more_arith_simps(11) okamoto_axioms okamoto_def pow_generator_mod_int)\n  thus ?thesis using t by simp\nqed\n\nlemma special_soundness:\n  shows \"\\<Sigma>_protocols_base.special_soundness\"       \n  unfolding \\<Sigma>_protocols_base.special_soundness_def \n  by(auto simp add: valid_pub_def check_def R_def ss_adversary_def Let_def ss_rewrite challenge_space_def split_def)\n\ntheorem \\<Sigma>_protocol: \n  shows \"\\<Sigma>_protocols_base.\\<Sigma>_protocol\"\n  by(simp add: \\<Sigma>_protocols_base.\\<Sigma>_protocol_def completeness HVZK special_soundness)\n\nsublocale okamoto_\\<Sigma>_commit: \\<Sigma>_protocols_to_commitments init response check R S2 ss_adversary challenge_space valid_pub G \n  apply unfold_locales\n  apply(auto simp add: \\<Sigma>_protocol)\n  by(auto simp add: G_def R_def lossless_init lossless_response)\n\nsublocale dis_log: dis_log \\<G> \n  unfolding dis_log_def by simp\n\nsublocale dis_log_alt: dis_log_alt \\<G> x \n  unfolding dis_log_alt_def \n  by(simp add:)\n\nlemma reduction_to_dis_log:\n  shows \"okamoto_\\<Sigma>_commit.rel_advantage \\<A> = dis_log.advantage (dis_log_alt.adversary2 \\<A>)\"\nproof-\n  have exp_rewrite: \"\\<^bold>g [^] w1 \\<otimes> g' [^] w2 =  \\<^bold>g [^] (w1 + x * w2)\" for w1 w2 :: nat\n    by (simp add: nat_pow_mult nat_pow_pow g'_def)\n  have \"okamoto_\\<Sigma>_commit.rel_game \\<A> = TRY do {\n    w1 \\<leftarrow> sample_uniform (order \\<G>);\n    w2 \\<leftarrow> sample_uniform (order \\<G>);\n    let h = (\\<^bold>g [^] w1 \\<otimes> g' [^] w2);\n    (w1',w2') \\<leftarrow> \\<A> h;\n    return_spmf (h = \\<^bold>g [^] w1' \\<otimes> g' [^] w2')} ELSE return_spmf False\"\n    unfolding okamoto_\\<Sigma>_commit.rel_game_def\n    by(simp add: Let_def split_def R_def G_def)\n  also have \"... = TRY do {\n    w1 \\<leftarrow> sample_uniform (order \\<G>);\n    w2 \\<leftarrow> sample_uniform (order \\<G>);\n    let w = (w1 + x * w2) mod (order \\<G>);\n    let h = \\<^bold>g [^] w;\n    (w1',w2') \\<leftarrow> \\<A> h;\n    return_spmf (h = \\<^bold>g [^] w1' \\<otimes> g' [^] w2')} ELSE return_spmf False\"\n    using g'_def exp_rewrite pow_generator_mod by simp\n  also have \"... = TRY do {\n    w2 \\<leftarrow> sample_uniform (order \\<G>);\n    w \\<leftarrow> map_spmf (\\<lambda> w1. (x * w2 + w1) mod (order \\<G>)) (sample_uniform (order \\<G>));\n    let h = \\<^bold>g [^] w;\n    (w1',w2') \\<leftarrow> \\<A> h;\n    return_spmf (h = \\<^bold>g [^] w1' \\<otimes> g' [^] w2')} ELSE return_spmf False\"\n    including monad_normalisation\n    by(simp add: bind_map_spmf o_def Let_def add.commute)\n  also have \"... = TRY do {\n    w2 :: nat \\<leftarrow> sample_uniform (order \\<G>);\n    w \\<leftarrow> sample_uniform (order \\<G>);\n    let h = \\<^bold>g [^] w;\n    (w1',w2') \\<leftarrow> \\<A> h;\n    return_spmf (h = \\<^bold>g [^] w1' \\<otimes> g' [^] w2')} ELSE return_spmf False\"\n    using samp_uni_plus_one_time_pad add.commute by simp\n  also have \"... = TRY do {\n    w \\<leftarrow> sample_uniform (order \\<G>);\n    let h = \\<^bold>g [^] w;\n    (w1',w2') \\<leftarrow> \\<A> h;\n    return_spmf (h = \\<^bold>g [^] w1' \\<otimes> g' [^] w2')} ELSE return_spmf False\"\n    by(simp add: bind_spmf_const)\n  also have \"... = dis_log_alt.dis_log2 \\<A>\"\n    apply(simp add: dis_log_alt.dis_log2_def Let_def dis_log_alt.g'_def g'_def)\n    apply(intro try_spmf_cong)\n     apply(intro bind_spmf_cong[OF refl]; clarsimp?)\n     apply auto\n    using exp_rewrite pow_generator_mod g'_def \n     apply (metis group_eq_pow_eq_mod okamoto_axioms okamoto_base.order_gt_0 okamoto_def)\n    using exp_rewrite g'_def order_gt_0_iff_finite pow_generator_eq_iff_cong by auto\n  ultimately have \"okamoto_\\<Sigma>_commit.rel_game \\<A> = dis_log_alt.dis_log2 \\<A>\"\n    by simp\n  hence \"okamoto_\\<Sigma>_commit.rel_advantage \\<A> = dis_log_alt.advantage2 \\<A>\"\n    by(simp add: okamoto_\\<Sigma>_commit.rel_advantage_def dis_log_alt.advantage2_def)\n  thus ?thesis\n    by (simp add: dis_log_alt_reductions.dis_log_adv2 cyclic_group_axioms dis_log_alt.dis_log_alt_axioms dis_log_alt_reductions.intro)\nqed\n\nlemma commitment_correct: \"okamoto_\\<Sigma>_commit.abstract_com.correct\"\n  by(simp add: okamoto_\\<Sigma>_commit.commit_correct)\n\nlemma \"okamoto_\\<Sigma>_commit.abstract_com.perfect_hiding_ind_cpa \\<A>\"\n  using okamoto_\\<Sigma>_commit.perfect_hiding by blast\n\n\n\nend\n\nlocale okamoto_asymp = \n  fixes \\<G> :: \"nat \\<Rightarrow> 'grp cyclic_group\"\n    and x :: nat\n  assumes okamoto: \"\\<And>\\<eta>. okamoto (\\<G> \\<eta>)\"\nbegin\n\nsublocale okamoto \"\\<G> \\<eta>\" for \\<eta> \n  by(simp add: okamoto)\n\ntext\\<open>The \\<open>\\<Sigma>\\<close>-protocol statement comes easily in the asympotic setting.\\<close>\n\ntheorem sigma_protocol:\n  shows \"\\<Sigma>_protocols_base.\\<Sigma>_protocol n\"\n  by(simp add: \\<Sigma>_protocol)\n\ntext\\<open>We now show the statements of security for the commitment scheme in the asymptotic setting, the main difference is that\nwe are able to show the binding advantage is negligible in the security parameter.\\<close>\n\nlemma asymp_correct: \"okamoto_\\<Sigma>_commit.abstract_com.correct n\" \n  using  okamoto_\\<Sigma>_commit.commit_correct by simp\n\nlemma asymp_perfect_hiding: \"okamoto_\\<Sigma>_commit.abstract_com.perfect_hiding_ind_cpa n (\\<A> n)\"\n  using okamoto_\\<Sigma>_commit.perfect_hiding by blast\n\n\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/Sigma_Commit_Crypto/Okamoto_Sigma_Commit.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797124237604, "lm_q2_score": 0.7690802317779601, "lm_q1q2_score": 0.7007703044222408}}
{"text": "(* Title:      Antidomain Semirings\n   Author:     Victor B. F. Gomes, Walter Guttmann, Peter H\u00f6fner, 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>Antidomain Semirings\\<close>\n\ntheory Antidomain_Semiring\nimports Domain_Semiring\nbegin\n\nsubsection \\<open>Antidomain Monoids\\<close>\n\ntext \\<open>We axiomatise antidomain monoids, using the axioms of~\\cite{DesharnaisJipsenStruth}.\\<close>\n\nclass antidomain_op =\n  fixes antidomain_op :: \"'a \\<Rightarrow> 'a\" (\"ad\")\n\nclass antidomain_left_monoid = monoid_mult + antidomain_op +\n  assumes am1 [simp]: \"ad x \\<cdot> x = ad 1\"\n  and am2: \"ad x \\<cdot> ad y = ad y \\<cdot> ad x\"\n  and am3 [simp]: \"ad (ad x) \\<cdot> x = x\"\n  and am4 [simp]: \"ad (x \\<cdot> y) \\<cdot> ad (x \\<cdot> ad y) = ad x\"\n  and am5 [simp]: \"ad (x \\<cdot> y) \\<cdot> x \\<cdot> ad y = ad (x \\<cdot> y) \\<cdot> x\"\n\nbegin\n\nno_notation domain_op (\"d\")\nno_notation zero_class.zero (\"0\")\n\ntext \\<open>We define a zero element and operations of domain and addition.\\<close>\n\ndefinition a_zero :: \"'a\" (\"0\") where\n  \"0 = ad 1\"\n\ndefinition am_d :: \"'a \\<Rightarrow> 'a\" (\"d\") where\n   \"d x = ad (ad x)\"\n\ndefinition am_add_op :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a\" (infixl \"\\<oplus>\" 65) where\n  \"x \\<oplus> y \\<equiv> ad (ad x \\<cdot> ad y)\"\n\nlemma a_d_zero [simp]: \"ad x \\<cdot> d x = 0\"\n  by (metis am1 am2 a_zero_def am_d_def)\n\nlemma a_d_one [simp]: \"d x \\<oplus> ad x = 1\"\n  by (metis am1 am3 mult_1_right am_d_def am_add_op_def)\n\nlemma n_annil [simp]: \"0 \\<cdot> x = 0\"\nproof -\n  have \"0 \\<cdot> x = d x \\<cdot> ad x \\<cdot> x\"\n    by (simp add: a_zero_def am_d_def)\n  also have \"... = d x \\<cdot> 0\"\n    by (metis am1 mult_assoc a_zero_def)\n  thus ?thesis\n    by (metis am1 am2 am3 mult_assoc a_zero_def)\nqed\n\nlemma a_mult_idem [simp]: \"ad x \\<cdot> ad x = ad x\"\nproof -\n  have \"ad x \\<cdot> ad x = ad (1 \\<cdot> x) \\<cdot> 1 \\<cdot> ad x\"\n    by simp\n  also have \"... = ad (1 \\<cdot> x) \\<cdot> 1\"\n    using am5 by blast\n  finally show ?thesis\n    by simp\nqed\n\nlemma a_add_idem [simp]: \"ad x \\<oplus> ad x = ad x\"\n  by (metis am1 am3 am4 mult_1_right am_add_op_def)\n\ntext \\<open>The next three axioms suffice to show that the domain elements form a Boolean algebra.\\<close>\n\nlemma a_add_comm: \"x \\<oplus> y = y \\<oplus> x\"\n  using am2 am_add_op_def by auto\n\nlemma a_add_assoc: \"x \\<oplus> (y \\<oplus> z) = (x \\<oplus> y) \\<oplus> z\"\nproof -\n  have \"\\<And>x y. ad x \\<cdot> ad (x \\<cdot> y) = ad x\"\n    by (metis a_mult_idem am2 am4 mult_assoc)\n  thus ?thesis\n    by (metis a_add_comm am_add_op_def local.am3 local.am4 mult_assoc)\nqed\n\nlemma huntington [simp]: \"ad (x \\<oplus> y) \\<oplus> ad (x \\<oplus> ad y) = ad x\"\n  using a_add_idem am_add_op_def by auto\n\nlemma a_absorb1 [simp]: \"(ad x \\<oplus> ad y) \\<cdot> ad x = ad x\"\n  by (metis a_add_idem a_mult_idem am4 mult_assoc am_add_op_def)\n\nlemma a_absorb2 [simp]: \"ad x \\<oplus> ad x \\<cdot> ad y = ad x\"\nproof -\n  have \"ad (ad x) \\<cdot> ad (ad x \\<cdot> ad y) = ad (ad x)\"\n    by (metis (no_types) a_mult_idem local.am4 local.mult.semigroup_axioms semigroup.assoc)\n  then show ?thesis\n    using a_add_idem am_add_op_def by auto\nqed\n\ntext \\<open>The distributivity laws remain to be proved; our proofs follow those of Maddux~\\cite{Maddux}.\\<close>\n\nlemma prod_split [simp]: \"ad x \\<cdot> ad y \\<oplus> ad x \\<cdot> d y = ad x\"\n  using a_add_idem am_d_def am_add_op_def by auto\n\nlemma sum_split [simp]: \"(ad x \\<oplus> ad y) \\<cdot> (ad x \\<oplus> d y) = ad x\"\n  using a_add_idem am_d_def am_add_op_def by fastforce\n\nlemma a_comp_simp [simp]: \"(ad x \\<oplus> ad y) \\<cdot> d x = ad y \\<cdot> d x\"\nproof -\n  have f1: \"(ad x \\<oplus> ad y) \\<cdot> d x = ad (ad (ad x) \\<cdot> ad (ad y)) \\<cdot> ad (ad x) \\<cdot> ad (ad (ad y))\"\n    by (simp add: am_add_op_def am_d_def)\n  have f2: \"ad y = ad (ad (ad y))\"\n    using a_add_idem am_add_op_def by auto\n  have \"ad y = ad (ad (ad x) \\<cdot> ad (ad y)) \\<cdot> ad y\"\n    by (metis (no_types) a_absorb1 a_add_comm am_add_op_def)\n  then show ?thesis\n    using f2 f1 by (simp add: am_d_def local.am2 local.mult.semigroup_axioms semigroup.assoc)\nqed\n\nlemma a_distrib1: \"ad x \\<cdot> (ad y \\<oplus> ad z) = ad x \\<cdot> ad y \\<oplus> ad x \\<cdot> ad z\"\nproof -\n  have f1: \"\\<And>a. ad (ad (ad (a::'a)) \\<cdot> ad (ad a)) = ad a\"\n    using a_add_idem am_add_op_def by auto\n  have f2: \"\\<And>a aa. ad ((a::'a) \\<cdot> aa) \\<cdot> (a \\<cdot> ad aa) = ad (a \\<cdot> aa) \\<cdot> a\"\n    using local.am5 mult_assoc by auto\n  have f3: \"\\<And>a. ad (ad (ad (a::'a))) = ad a\"\n    using f1 by simp\n  have \"\\<And>a. ad (a::'a) \\<cdot> ad a = ad a\"\n    by simp\n  then have \"\\<And>a aa. ad (ad (ad (a::'a) \\<cdot> ad aa)) = ad aa \\<cdot> ad a\"\n    using f3 f2 by (metis (no_types) local.am2 local.am4 mult_assoc)\n  then have  \"ad x \\<cdot> (ad y \\<oplus> ad z) = ad x \\<cdot> (ad y \\<oplus> ad z) \\<cdot> ad y \\<oplus> ad x \\<cdot> (ad y \\<oplus> ad z) \\<cdot> d y\"\n    using am_add_op_def am_d_def local.am2 local.am4 by presburger\n  also have \"... = ad x \\<cdot> ad y \\<oplus> ad x \\<cdot> (ad y \\<oplus> ad z) \\<cdot> d y\"\n    by (simp add: mult_assoc)\n  also have \"... = ad x \\<cdot> ad y \\<oplus> ad x \\<cdot> ad z \\<cdot> d y\"\n    by (simp add: mult_assoc)\n  also have \"... = ad x \\<cdot> ad y \\<oplus> ad x \\<cdot> ad y \\<cdot> ad z \\<oplus> ad x \\<cdot> ad z \\<cdot> d y\"\n    by (metis a_add_idem a_mult_idem local.am4 mult_assoc am_add_op_def)\n  also have \"... = ad x \\<cdot> ad y \\<oplus> (ad x \\<cdot> ad z \\<cdot> ad y \\<oplus> ad x \\<cdot> ad z \\<cdot> d y)\"\n    by (metis am2 mult_assoc a_add_assoc)\n  finally show ?thesis\n    by (metis a_add_idem a_mult_idem am4 am_d_def am_add_op_def)\nqed\n\nlemma a_distrib2: \"ad x \\<oplus> ad y \\<cdot> ad z = (ad x \\<oplus> ad y) \\<cdot> (ad x \\<oplus> ad z)\"\nproof -\n  have f1: \"\\<And>a aa ab. ad (ad (ad (a::'a) \\<cdot> ad aa) \\<cdot> ad (ad a \\<cdot> ad ab)) = ad a \\<cdot> ad (ad (ad aa) \\<cdot> ad (ad ab))\"\n    using a_distrib1 am_add_op_def by auto\n  have \"\\<And>a. ad (ad (ad (a::'a))) = ad a\"\n    by (metis a_absorb2 a_mult_idem am_add_op_def)\n  then have \"ad (ad (ad x) \\<cdot> ad (ad y)) \\<cdot> ad (ad (ad x) \\<cdot> ad (ad z)) = ad (ad (ad x) \\<cdot> ad (ad y \\<cdot> ad z))\"\n    using f1 by (metis (full_types))\n  then show ?thesis\n    by (simp add: am_add_op_def)\nqed\n\nlemma aa_loc [simp]: \"d (x \\<cdot> d y) = d (x \\<cdot> y)\"\nproof -\n  have f1: \"x \\<cdot> d y \\<cdot> y = x \\<cdot> y\"\n    by (metis am3 mult_assoc am_d_def)\n  have f2: \"\\<And>w z. ad (w \\<cdot> z) \\<cdot> (w \\<cdot> ad z) = ad (w \\<cdot> z) \\<cdot> w\"\n    by (metis am5 mult_assoc)\n  hence f3: \"\\<And>z. ad (x \\<cdot> y) \\<cdot> (x \\<cdot> z) = ad (x \\<cdot> y) \\<cdot> (x \\<cdot> (ad (ad (ad y) \\<cdot> y) \\<cdot> z))\"\n    using f1 by (metis (no_types) mult_assoc am_d_def)\n  have \"ad (x \\<cdot> ad (ad y)) \\<cdot> (x \\<cdot> y) = 0\" using f1\n    by (metis am1 mult_assoc n_annil a_zero_def am_d_def)\n  thus ?thesis\n    by (metis a_d_zero am_d_def f3 local.am1 local.am2 local.am3 local.am4)\nqed\n\nlemma a_loc [simp]: \"ad (x \\<cdot> d y) = ad (x \\<cdot> y)\"\nproof -\n  have \"\\<And>a. ad (ad (ad (a::'a))) = ad a\"\n    using am_add_op_def am_d_def prod_split by auto\n  then show ?thesis\n    by (metis (full_types) aa_loc am_d_def)\nqed\n\nlemma d_a_export [simp]: \"d (ad x \\<cdot> y) = ad x \\<cdot> d y\"\nproof -\n  have f1: \"\\<And>a aa. ad ((a::'a) \\<cdot> ad (ad aa)) = ad (a \\<cdot> aa)\"\n    using a_loc am_d_def by auto\n  have \"\\<And>a. ad (ad (a::'a) \\<cdot> a) = 1\"\n    using a_d_one am_add_op_def am_d_def by auto\n  then have \"\\<And>a aa. ad (ad (ad (a::'a) \\<cdot> ad aa)) = ad a \\<cdot> ad aa\"\n    using f1 by (metis a_distrib2 am_add_op_def local.mult_1_left)\n  then show ?thesis\n    using f1 by (metis (no_types) am_d_def)\nqed\n\ntext \\<open>Every antidomain monoid is a domain monoid.\\<close>\n\nsublocale dm: domain_monoid am_d \"(\\<cdot>)\" 1\n  apply (unfold_locales)\n  apply (simp add: am_d_def)\n  apply simp\n  using am_d_def d_a_export apply auto[1]\n  by (simp add: am_d_def local.am2)\n\nlemma ds_ord_iso1: \"x \\<sqsubseteq> y \\<Longrightarrow> z \\<cdot> x \\<sqsubseteq> z \\<cdot> y\"\n(*nitpick [expect=genuine]*)\noops\n\nlemma a_very_costrict: \"ad x = 1 \\<longleftrightarrow> x = 0\"\nproof\n  assume a: \"ad x = 1\"\n  hence \"0 = ad x \\<cdot> x\"\n    using a_zero_def by force\n  thus \"x = 0\"\n    by (simp add: a)\nnext\n  assume \"x = 0\"\n  thus \"ad x = 1\"\n    using a_zero_def am_d_def dm.dom_one by auto\nqed\n\nlemma a_weak_loc: \"x \\<cdot> y = 0 \\<longleftrightarrow> x \\<cdot> d y = 0\"\nproof -\n  have \"x \\<cdot> y = 0 \\<longleftrightarrow> ad (x \\<cdot> y) = 1\"\n    by (simp add: a_very_costrict)\n  also have \"... \\<longleftrightarrow> ad (x \\<cdot> d y) = 1\"\n    by simp\n  finally show ?thesis\n    using a_very_costrict by blast\nqed\n\nlemma a_closure [simp]: \"d (ad x) = ad x\"\n  using a_add_idem am_add_op_def am_d_def by auto\n\nlemma a_d_mult_closure [simp]: \"d (ad x \\<cdot> ad y) = ad x \\<cdot> ad y\"\n  by simp\n\nlemma kat_3': \"d x \\<cdot> y \\<cdot> ad z = 0 \\<Longrightarrow> d x \\<cdot> y = d x \\<cdot> y \\<cdot> d z\"\n  by (metis dm.dom_one local.am5 local.mult_1_left a_zero_def am_d_def)\n\nlemma s4 [simp]: \"ad x \\<cdot> ad (ad x \\<cdot> y) = ad x \\<cdot> ad y\"\nproof -\n  have \"\\<And>a aa. ad (a::'a) \\<cdot> ad (ad aa) = ad (ad (ad a \\<cdot> aa))\"\n    using am_d_def d_a_export by presburger\n  then have \"\\<And>a aa. ad (ad (a::'a)) \\<cdot> ad aa = ad (ad (ad aa \\<cdot> a))\"\n    using local.am2 by presburger\n  then show ?thesis\n    by (metis a_comp_simp a_d_mult_closure am_add_op_def am_d_def local.am2)\nqed\n\nend\n\nclass antidomain_monoid = antidomain_left_monoid +\n  assumes am6 [simp]: \"x \\<cdot> ad 1 = ad 1\"\n\nbegin\n\nlemma kat_3_equiv: \"d x \\<cdot> y \\<cdot> ad z = 0 \\<longleftrightarrow> d x \\<cdot> y = d x \\<cdot> y \\<cdot> d z\"\n  apply standard\n  apply (metis kat_3')\n  by (simp add: mult_assoc a_zero_def am_d_def)\n\nno_notation a_zero (\"0\")\nno_notation am_d (\"d\")\n\nend\n\nsubsection \\<open>Antidomain Near-Semirings\\<close>\n\ntext \\<open>We define antidomain near-semirings. We do not consider units separately. The axioms are taken from~\\cite{DesharnaisStruthAMAST}.\\<close>\n\nnotation zero_class.zero (\"0\")\n\nclass antidomain_near_semiring = ab_near_semiring_one_zerol + antidomain_op + plus_ord +\n  assumes ans1 [simp]: \"ad x \\<cdot> x = 0\"\n  and ans2 [simp]: \"ad (x \\<cdot> y) + ad (x \\<cdot> ad (ad y)) = ad (x \\<cdot> ad (ad y))\"\n  and ans3 [simp]: \"ad (ad x) + ad x = 1\"\n  and ans4 [simp]: \"ad (x + y) = ad x \\<cdot> ad y\"\n\nbegin\n\ndefinition ans_d :: \"'a \\<Rightarrow> 'a\" (\"d\") where\n   \"d x = ad (ad x)\"\n\nlemma a_a_one [simp]: \"d 1 = 1\"\nproof -\n  have \"d 1 = d 1 + 0\"\n    by simp\n  also have \"... = d 1 + ad 1\"\n    by (metis ans1 mult_1_right)\n  finally show ?thesis\n    by (simp add: ans_d_def)\nqed\n\nlemma a_very_costrict': \"ad x = 1 \\<longleftrightarrow> x = 0\"\nproof\n  assume \"ad x = 1\"\n  hence \"x = ad x \\<cdot> x\"\n    by simp\n  thus \"x = 0\"\n    by auto\nnext\n  assume \"x = 0\"\n  hence \"ad x = ad 0\"\n    by blast\n  thus \"ad x = 1\"\n    by (metis a_a_one ans_d_def local.ans1 local.mult_1_right)\nqed\n\nlemma one_idem [simp]: \"1 + 1 = 1\"\nproof -\n  have \"1 + 1 = d 1 + d 1\"\n    by simp\n  also have \"... = ad (ad 1 \\<cdot> 1) + ad (ad 1 \\<cdot> d 1)\"\n    using a_a_one ans_d_def by auto\n  also have \"... = ad (ad 1 \\<cdot> d 1)\"\n    using ans_d_def local.ans2 by presburger\n  also have \"... = ad (ad 1 \\<cdot> 1)\"\n    by simp\n  also have \"... = d 1\"\n    by (simp add: ans_d_def)\n  finally show ?thesis\n    by simp\nqed\n\ntext \\<open>Every antidomain near-semiring is automatically a dioid, and therefore ordered.\\<close>\n\nsubclass near_dioid_one_zerol\nproof\n  show \"\\<And>x. x + x = x\"\n  proof -\n    fix x\n    have \"x + x = 1 \\<cdot> x + 1 \\<cdot> x\"\n      by simp\n    also have \"... = (1 + 1) \\<cdot> x\"\n      using distrib_right' by presburger\n    finally show \"x + x = x\"\n      by simp\n  qed\nqed\n\nlemma d1_a [simp]: \"d x \\<cdot> x = x\"\nproof -\n  have \"x = (d x + ad x) \\<cdot> x\"\n    by (simp add: ans_d_def)\n  also have \"... = d x \\<cdot> x + ad x \\<cdot> x\"\n    using distrib_right' by blast\n  also have \"... = d x \\<cdot> x + 0\"\n    by simp\n  finally show ?thesis\n    by auto\nqed\n\nlemma a_comm: \"ad x \\<cdot> ad y = ad y \\<cdot> ad x\"\n  using add_commute ans4 by fastforce\n\nlemma a_subid: \"ad x \\<le> 1\"\n  using local.ans3 local.join.sup_ge2 by fastforce\n\nlemma a_subid_aux1: \"ad x \\<cdot> y \\<le> y\"\n  using a_subid mult_isor by fastforce\n\nlemma a_subdist: \"ad (x + y) \\<le> ad x\"\n  by (metis a_subid_aux1 ans4 add_comm)\n\nlemma a_antitone: \"x \\<le> y \\<Longrightarrow> ad y \\<le> ad x\"\n  using a_subdist local.order_prop by auto\n\n\n\nlemma a_gla1: \"ad x \\<cdot> y = 0 \\<Longrightarrow> ad x \\<le> ad y\"\nproof -\n  assume \"ad x \\<cdot> y = 0\"\n  hence a: \"ad x \\<cdot> d y = 0\"\n    by (metis a_subid a_very_costrict' ans_d_def local.ans2 local.join.sup.order_iff)\n  have \"ad x = (d y + ad y ) \\<cdot> ad x\"\n    by (simp add: ans_d_def)\n  also have \"... = d y \\<cdot> ad x + ad y \\<cdot> ad x\"\n    using distrib_right' by blast\n  also have \"... = ad x \\<cdot> d y + ad x \\<cdot> ad y\"\n    using a_comm ans_d_def by auto\n  also have \"... = ad x \\<cdot> ad y\"\n    by (simp add: a)\n  finally show \"ad x \\<le> ad y\"\n    by (metis a_subid_aux1)\nqed\n\nlemma a_gla2: \"ad x \\<le> ad y \\<Longrightarrow> ad x \\<cdot> y = 0\"\nproof -\n  assume \"ad x \\<le> ad y\"\n  hence \"ad x \\<cdot> y \\<le> ad y \\<cdot> y\"\n    using mult_isor by blast\n  thus ?thesis\n    by (simp add: join.le_bot)\nqed\n\nlemma a2_eq [simp]: \"ad (x \\<cdot> d y) = ad (x \\<cdot> y)\"\nproof (rule antisym)\n  show \"ad (x \\<cdot> y) \\<le> ad (x \\<cdot> d y)\"\n    by (simp add: ans_d_def local.less_eq_def)\nnext\n  show \"ad (x \\<cdot> d y) \\<le> ad (x \\<cdot> y)\"\n    by (metis a_gla1 a_mul_d ans1 d1_a mult_assoc)\nqed\n\nlemma a_export' [simp]: \"ad (ad x \\<cdot> y) = d x + ad y\"\nproof (rule antisym)\n  have \"ad (ad x \\<cdot> y) \\<cdot> ad x \\<cdot> d y = 0\"\n    by (simp add: a_gla2 local.mult.semigroup_axioms semigroup.assoc)\n  hence a: \"ad (ad x \\<cdot> y) \\<cdot> d y \\<le> ad (ad x)\"\n    by (metis a_comm a_gla1 ans4 mult_assoc ans_d_def)\n  have \"ad (ad x \\<cdot> y) = ad (ad x \\<cdot> y) \\<cdot> d y + ad (ad x \\<cdot> y) \\<cdot> ad y\"\n    by (metis (no_types) add_commute ans3 ans4 distrib_right' mult_onel ans_d_def)\n  thus \"ad (ad x \\<cdot> y) \\<le> d x + ad y\"\n    by (metis a_subid_aux1 a join.sup_mono ans_d_def)\nnext\n  show \"d x + ad y \\<le> ad (ad x \\<cdot> y)\"\n    by (metis a2_eq a_antitone a_comm a_subid_aux1 join.sup_least ans_d_def)\nqed\n\ntext \\<open>Every antidomain near-semiring is a domain near-semiring.\\<close>\n\nsublocale dnsz: domain_near_semiring_one_zerol \"(+)\" \"(\\<cdot>)\" 1 0 \"ans_d\" \"(\\<le>)\" \"(<)\"\n  apply (unfold_locales)\n  apply simp\n  using a2_eq ans_d_def apply auto[1]\n  apply (simp add: a_subid ans_d_def local.join.sup_absorb2)\n  apply (simp add: ans_d_def)\n  apply (simp add: a_comm ans_d_def)\n  using a_a_one a_very_costrict' ans_d_def by force\n\nlemma a_idem [simp]: \"ad x \\<cdot> ad x = ad x\"\nproof -\n  have \"ad x = (d x + ad x ) \\<cdot> ad x\"\n    by (simp add: ans_d_def)\n  also have \"... = d x \\<cdot> ad x + ad x \\<cdot> ad x\"\n    using distrib_right' by blast\n  finally show ?thesis\n    by (simp add: ans_d_def)\nqed\n\nlemma a_3_var [simp]: \"ad x \\<cdot> ad y \\<cdot> (x + y) = 0\"\n  by (metis ans1 ans4)\n\nlemma a_3 [simp]: \"ad x \\<cdot> ad y \\<cdot> d (x + y) = 0\"\n  by (metis a_mul_d ans4)\n\nlemma a_closure' [simp]: \"d (ad x) = ad x\"\nproof -\n  have \"d (ad x) = ad (1 \\<cdot> d x)\"\n    by (simp add: ans_d_def)\n  also have \"... = ad (1 \\<cdot> x)\"\n    using a2_eq by blast\n  finally show ?thesis\n    by simp\nqed\n\ntext \\<open>The following counterexamples show that some of the antidomain monoid axioms do not need to hold.\\<close>\n\nlemma \"x \\<cdot> ad 1 = ad 1\"\n(*nitpick [expect=genuine]*)\noops\n\nlemma \"ad (x \\<cdot> y) \\<cdot> ad (x \\<cdot> ad y) = ad x\"\n(*nitpick [expect=genuine]*)\noops\n\nlemma \"ad (x \\<cdot> y) \\<cdot> ad (x \\<cdot> ad y) = ad x\"\n(*nitpick [expect=genuine]*)\noops\n\nlemma phl_seq_inv: \"d v \\<cdot> x \\<cdot> y \\<cdot> ad w = 0 \\<Longrightarrow> \\<exists>z. d v \\<cdot> x \\<cdot> d z = 0 \\<and> ad z \\<cdot> y \\<cdot> ad w = 0\"\nproof -\n  assume \"d v \\<cdot> x \\<cdot> y \\<cdot> ad w = 0\"\n  hence \"d v \\<cdot> x \\<cdot> d (y \\<cdot> ad w) = 0 \\<and> ad (y \\<cdot> ad w) \\<cdot> y \\<cdot> ad w = 0\"\n    by (metis dnsz.dom_weakly_local local.ans1 mult_assoc)\n  thus \"\\<exists>z. d v \\<cdot> x \\<cdot> d z = 0 \\<and> ad z \\<cdot> y \\<cdot> ad w = 0\"\n    by blast\nqed\n\nlemma a_fixpoint: \"ad x = x \\<Longrightarrow> (\\<forall>y. y = 0)\"\nproof -\n  assume a1: \"ad x = x\"\n  { fix aa :: 'a\n    have \"aa = 0\"\n      using a1 by (metis (no_types) a_mul_d ans_d_def local.annil local.ans3 local.join.sup.idem local.mult_1_left)\n  }\n  then show ?thesis\n    by blast\nqed\n\nno_notation ans_d (\"d\")\n\nend\n\nsubsection \\<open>Antidomain Pre-Dioids\\<close>\n\ntext \\<open>Antidomain pre-diods are based on a different set of axioms, which are again taken from~\\cite{DesharnaisStruthAMAST}.\\<close>\n\nclass antidomain_pre_dioid = pre_dioid_one_zerol + antidomain_op +\n  assumes apd1 [simp]: \"ad x \\<cdot> x = 0\"\n  and apd2 [simp]: \"ad (x \\<cdot> y) \\<le> ad (x \\<cdot> ad (ad y))\"\n  and apd3 [simp]: \"ad (ad x) + ad x = 1\"\n\nbegin\n\ndefinition apd_d :: \"'a \\<Rightarrow> 'a\" (\"d\") where\n   \"d x = ad (ad x)\"\n\nlemma a_very_costrict'': \"ad x = 1 \\<longleftrightarrow> x = 0\"\n  by (metis add_commute local.add_zerol local.antisym local.apd1 local.apd3 local.join.bot_least local.mult_1_right local.phl_skip)\n\nlemma a_subid': \"ad x \\<le> 1\"\n  using local.apd3 local.join.sup_ge2 by fastforce\n\nlemma d1_a' [simp]: \"d x \\<cdot> x = x\"\nproof -\n  have \"x = (d x + ad x) \\<cdot> x\"\n    by (simp add: apd_d_def)\n  also have \"... = d x \\<cdot> x + ad x \\<cdot> x\"\n    using distrib_right' by blast\n  also have \"... = d x \\<cdot> x + 0\"\n    by simp\n  finally show ?thesis\n    by auto\nqed\n\nlemma a_subid_aux1': \"ad x \\<cdot> y \\<le> y\"\n  using a_subid' mult_isor by fastforce\n\nlemma a_mul_d' [simp]: \"ad x \\<cdot> d x = 0\"\nproof -\n  have \"1 = ad (ad x \\<cdot> x)\"\n    using a_very_costrict'' by force\n  thus ?thesis\n    by (metis a_subid' a_very_costrict'' apd_d_def local.antisym local.apd2)\nqed\n\n\n\nlemma meet_ord_def: \"ad x \\<le> ad y \\<longleftrightarrow> ad x \\<cdot> ad y = ad x\"\n  by (metis a_d_closed a_subid_aux1' d1_a' eq_iff mult_1_right mult_isol)\n\nlemma d_weak_loc: \"x \\<cdot> y = 0 \\<longleftrightarrow> x \\<cdot> d y = 0\"\nproof -\n  have \"x \\<cdot> y = 0 \\<longleftrightarrow> ad (x \\<cdot> y) = 1\"\n    by (simp add: a_very_costrict'')\n  also have \"... \\<longleftrightarrow> ad (x \\<cdot> d y) = 1\"\n    by (metis apd1 apd2 a_subid' apd_d_def d1_a' eq_iff mult_1_left mult_assoc)\n  finally show ?thesis\n    by (simp add: a_very_costrict'')\nqed\n\nlemma gla_1: \"ad x \\<cdot> y = 0 \\<Longrightarrow> ad x \\<le> ad y\"\nproof -\n  assume \"ad x \\<cdot> y = 0\"\n  hence a: \"ad x \\<cdot> d y = 0\"\n    using d_weak_loc by force\n  hence \"d y = ad x \\<cdot> d y + d y\"\n    by simp\n  also have \"... = (1 + ad x) \\<cdot> d y\"\n    using join.sup_commute by auto\n  also have \"... = (d x + ad x) \\<cdot> d y\"\n    using apd_d_def calculation by auto\n  also have \"... = d x \\<cdot> d y\"\n    by (simp add: a join.sup_commute)\n  finally have \"d y \\<le> d x\"\n    by (metis apd_d_def a_subid' mult_1_right mult_isol)\n  hence \"d y \\<cdot> ad x = 0\"\n    by (metis apd_d_def a_d_closed a_mul_d' distrib_right' less_eq_def no_trivial_inverse)\n  hence \"ad x = ad y \\<cdot> ad x\"\n    by (metis apd_d_def apd3 add_0_left distrib_right' mult_1_left)\n  thus \"ad x \\<le> ad y\"\n    by (metis add_commute apd3 mult_oner subdistl)\nqed\n\nlemma a2_eq' [simp]: \"ad (x \\<cdot> d y) = ad (x \\<cdot> y)\"\nproof (rule antisym)\n  show \"ad (x \\<cdot> y) \\<le> ad (x \\<cdot> d y)\"\n    by (simp add: apd_d_def)\nnext\n  show \"ad (x \\<cdot> d y) \\<le> ad (x \\<cdot> y)\"\n    by (metis gla_1 apd1 a_mul_d' d1_a' mult_assoc)\nqed\n\nlemma a_supdist_var: \"ad (x + y) \\<le> ad x\"\n  by (metis gla_1 apd1 join.le_bot subdistl)\n\nlemma a_antitone': \"x \\<le> y \\<Longrightarrow> ad y \\<le> ad x\"\n  using a_supdist_var local.order_prop by auto\n\nlemma a_comm_var: \"ad x \\<cdot> ad y \\<le> ad y \\<cdot> ad x\"\nproof -\n  have \"ad x \\<cdot> ad y = d (ad x \\<cdot> ad y) \\<cdot> ad x \\<cdot> ad y\"\n    by (simp add: mult_assoc)\n  also have \"... \\<le> d (ad x \\<cdot> ad y) \\<cdot> ad x\"\n    using a_subid' mult_isol by fastforce\n  also have \"... \\<le> d (ad y) \\<cdot> ad x\"\n    by (simp add: a_antitone' a_subid_aux1' apd_d_def local.mult_isor)\n  finally show ?thesis\n    by simp\nqed\n\nlemma a_comm': \"ad x \\<cdot> ad y = ad y \\<cdot> ad x\"\n  by (simp add: a_comm_var eq_iff)\n\nlemma a_closed [simp]: \"d (ad x \\<cdot> ad y) = ad x \\<cdot> ad y\"\nproof -\n  have f1: \"\\<And>x y. ad x \\<le> ad (ad y \\<cdot> x)\"\n    by (simp add: a_antitone' a_subid_aux1')\n  have \"\\<And>x y. d (ad x \\<cdot> y) \\<le> ad x\"\n    by (metis a2_eq' a_antitone' a_comm' a_d_closed apd_d_def f1)\n  hence \"\\<And>x y. d (ad x \\<cdot> y) \\<cdot> y = ad x \\<cdot> y\"\n    by (metis d1_a' meet_ord_def mult_assoc apd_d_def)\n  thus ?thesis\n    by (metis f1 a_comm' apd_d_def meet_ord_def)\nqed\n\nlemma a_export'' [simp]: \"ad (ad x \\<cdot> y) = d x + ad y\"\nproof (rule antisym)\n  have \"ad (ad x \\<cdot> y) \\<cdot> ad x \\<cdot> d y = 0\"\n    using d_weak_loc mult_assoc by fastforce\n  hence a: \"ad (ad x \\<cdot> y) \\<cdot> d y \\<le> d x\"\n    by (metis a_closed a_comm' apd_d_def gla_1 mult_assoc)\n  have \"ad (ad x \\<cdot> y) = ad (ad x \\<cdot> y) \\<cdot> d y + ad (ad x \\<cdot> y) \\<cdot> ad y\"\n    by (metis apd3 a_comm' d1_a' distrib_right' mult_1_right apd_d_def)\n  thus \"ad (ad x \\<cdot> y) \\<le> d x + ad y\"\n    by (metis a_subid_aux1' a join.sup_mono)\nnext\n  have \"ad y \\<le> ad (ad x \\<cdot> y)\"\n    by (simp add: a_antitone' a_subid_aux1')\n  thus \"d x + ad y \\<le> ad (ad x \\<cdot> y)\"\n    by (metis apd_d_def a_mul_d' d1_a' gla_1 apd1 join.sup_least mult_assoc)\nqed\n\nlemma d1_sum_var: \"x + y \\<le> (d x + d y) \\<cdot> (x + y)\"\nproof -\n  have \"x + y = d x \\<cdot> x + d y \\<cdot> y\"\n    by simp\n  also have \"... \\<le> (d x + d y) \\<cdot> x + (d x + d y) \\<cdot> y\"\n    using local.distrib_right' local.join.sup_ge1 local.join.sup_ge2 local.join.sup_mono by presburger\n  finally show ?thesis\n    using order_trans subdistl_var by blast\nqed\n\nlemma a4': \"ad (x + y) = ad x \\<cdot> ad y\"\nproof (rule antisym)\n  show \"ad (x + y) \\<le> ad x \\<cdot> ad y\"\n    by (metis a_d_closed a_supdist_var add_commute d1_a' local.mult_isol_var)\n  hence \"ad x \\<cdot> ad y = ad x \\<cdot> ad y + ad (x + y)\"\n    using less_eq_def add_commute by simp\n  also have \"... = ad (ad (ad x \\<cdot> ad y) \\<cdot> (x + y))\"\n    by (metis a_closed a_export'')\n  finally show \"ad x \\<cdot> ad y \\<le> ad (x + y)\"\n    using a_antitone' apd_d_def d1_sum_var by auto\nqed\n\ntext \\<open>Antidomain pre-dioids are domain pre-dioids and antidomain near-semirings, but still not antidomain monoids.\\<close>\n\nsublocale dpdz: domain_pre_dioid_one_zerol \"(+)\" \"(\\<cdot>)\" 1 0 \"(\\<le>)\" \"(<)\" \"\\<lambda>x. ad (ad x)\"\n  apply (unfold_locales)\n  using apd_d_def d1_a' apply auto[1]\n  using a2_eq' apd_d_def apply auto[1]\n  apply (simp add: a_subid')\n  apply (simp add: a4' apd_d_def)\n  by (metis a_mul_d' a_very_costrict'' apd_d_def local.mult_onel)\n\nsubclass antidomain_near_semiring\n  apply (unfold_locales)\n  apply simp\n  using local.apd2 local.less_eq_def apply blast\n  apply simp\n  by (simp add: a4')\n\nlemma a_supdist: \"ad (x + y) \\<le> ad x + ad y\"\n  using a_supdist_var local.join.le_supI1 by auto\n\nlemma a_gla: \"ad x \\<cdot> y = 0 \\<longleftrightarrow> ad x \\<le> ad y\"\n  using gla_1 a_gla2 by blast\n\nlemma a_subid_aux2: \"x \\<cdot> ad y \\<le> x\"\n  using a_subid' mult_isol by fastforce\n\nlemma a42_var: \"d x \\<cdot> d y \\<le> ad (ad x + ad y)\"\n  by (simp add: apd_d_def)\n\nlemma d1_weak [simp]: \"(d x + d y) \\<cdot> x = x\"\nproof -\n  have \"(d x + d y) \\<cdot> x = (1 + d y) \\<cdot> x\"\n    by simp\n  thus ?thesis\n   by (metis add_commute apd_d_def dpdz.dnso3 local.mult_1_left)\nqed\n\nlemma \"x \\<cdot> ad 1 = ad 1\"\n(*nitpick [expect=genuine]*)\noops\n\nlemma \"ad x \\<cdot> (y + z) = ad x \\<cdot> y + ad x \\<cdot> z\"\n(*nitpick [expect=genuine]*)\noops\n\nlemma \"ad (x \\<cdot> y) \\<cdot> ad (x \\<cdot> ad y) = ad x\"\n(*nitpick [expect=genuine]*)\noops\n\nlemma \"ad (x \\<cdot> y) \\<cdot> ad (x \\<cdot> ad y) = ad x\"\n(*nitpick [expect=genuine]*)\noops\n\nno_notation apd_d (\"d\")\n\nend\n\nsubsection \\<open>Antidomain Semirings\\<close>\n\ntext \\<open>Antidomain semirings are direct expansions of antidomain pre-dioids, but do not require idempotency of addition. Hence we give a slightly different axiomatisation, following~\\cite{DesharnaisStruthSCP}.\\<close>\n\nclass antidomain_semiringl = semiring_one_zerol + plus_ord + antidomain_op +\n  assumes as1 [simp]: \"ad x \\<cdot> x = 0\"\n  and as2 [simp]: \"ad (x \\<cdot> y) + ad (x \\<cdot> ad (ad y)) = ad (x \\<cdot> ad (ad y))\"\n  and as3 [simp]: \"ad (ad x) + ad x = 1\"\n\nbegin\n\ndefinition ads_d :: \"'a \\<Rightarrow> 'a\" (\"d\") where\n  \"d x = ad (ad x)\"\n\nlemma one_idem': \"1 + 1 = 1\"\n  by (metis as1 as2 as3 add_zeror mult.right_neutral)\n\ntext \\<open>Every antidomain semiring is a dioid and an antidomain pre-dioid.\\<close>\n\nsubclass dioid\n  by (standard, metis distrib_left mult.right_neutral one_idem')\n\nsubclass antidomain_pre_dioid\n  by (unfold_locales, auto simp: local.less_eq_def)\n\nlemma am5_lem [simp]: \"ad (x \\<cdot> y) \\<cdot> ad (x \\<cdot> ad y) = ad x\"\nproof -\n  have \"ad (x \\<cdot> y ) \\<cdot> ad (x \\<cdot> ad y) = ad (x \\<cdot> d y) \\<cdot> ad (x \\<cdot> ad y)\"\n    using ads_d_def local.a2_eq' local.apd_d_def by auto\n  also have \"... = ad (x \\<cdot> d y + x \\<cdot> ad y)\"\n    using ans4 by presburger\n  also have \"... = ad (x \\<cdot> (d y + ad y))\"\n    using distrib_left by presburger\n  finally show ?thesis\n    by (simp add: ads_d_def)\nqed\n\nlemma am6_lem [simp]: \"ad (x \\<cdot> y) \\<cdot> x \\<cdot> ad y = ad (x \\<cdot> y) \\<cdot> x\"\nproof -\n  fix x y\n  have \"ad (x \\<cdot> y) \\<cdot> x \\<cdot> ad y = ad (x \\<cdot> y) \\<cdot> x \\<cdot> ad y + 0\"\n    by simp\n  also have \"... = ad (x \\<cdot> y) \\<cdot> x \\<cdot> ad y + ad (x \\<cdot> d y) \\<cdot> x \\<cdot> d y\"\n    using ans1 mult_assoc by presburger\n  also have \"... = ad (x \\<cdot> y) \\<cdot> x \\<cdot> (ad y + d y)\"\n    using ads_d_def local.a2_eq' local.apd_d_def local.distrib_left by auto\n  finally show \"ad (x \\<cdot> y) \\<cdot> x \\<cdot> ad y = ad (x \\<cdot> y) \\<cdot> x\"\n    using add_commute ads_d_def local.as3 by auto\nqed\n\nlemma a_zero [simp]: \"ad 0 = 1\"\n  by (simp add: local.a_very_costrict'')\n\nlemma a_one [simp]: \"ad 1 = 0\"\n  using a_zero local.dpdz.dpd5 by blast\n\nsubclass antidomain_left_monoid\n  by (unfold_locales, auto simp:  local.a_comm')\n\ntext \\<open>Every antidomain left semiring is a domain left semiring.\\<close>\n\nno_notation domain_semiringl_class.fd (\"( |_\\<rangle> _)\" [61,81] 82)\n\ndefinition fdia :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a\" (\"( |_\\<rangle> _)\" [61,81] 82) where\n  \"|x\\<rangle> y = ad (ad (x \\<cdot> y))\"\n\nsublocale ds: domain_semiringl \"(+)\" \"(\\<cdot>)\" 1 0 \"\\<lambda>x. ad (ad x)\" \"(\\<le>)\" \"(<)\"\n  rewrites \"ds.fd x y \\<equiv> fdia x y\"\nproof -\n  show \"class.domain_semiringl (+) (\\<cdot>) 1 0 (\\<lambda>x. ad (ad x)) (\\<le>) (<) \"\n    by (unfold_locales, auto simp: local.dpdz.dpd4 ans_d_def)\n  then interpret ds: domain_semiringl \"(+)\" \"(\\<cdot>)\" 1 0 \"\\<lambda>x. ad (ad x)\" \"(\\<le>)\" \"(<)\" .\n  show \"ds.fd x y \\<equiv> fdia x y\"\n    by (auto simp: fdia_def ds.fd_def)\nqed\n\nlemma fd_eq_fdia [simp]: \"domain_semiringl.fd (\\<cdot>) d x y \\<equiv> fdia x y\"\nproof -\n  have \"class.domain_semiringl (+) (\\<cdot>) 1 0 d (\\<le>) (<)\"\n    by (unfold_locales, auto simp: ads_d_def local.ans_d_def)\n  hence \"domain_semiringl.fd (\\<cdot>) d x y = d ((\\<cdot>) x y)\"\n    by (rule domain_semiringl.fd_def)\n  also have \"... = ds.fd x y\"\n    by (simp add: ds.fd_def ads_d_def)\n  finally show \"domain_semiringl.fd (\\<cdot>) d x y \\<equiv> |x\\<rangle> y\"\n    by auto\nqed\n\nend\n\nclass antidomain_semiring = antidomain_semiringl + semiring_one_zero\n\nbegin\n\ntext \\<open>Every antidomain semiring is an antidomain monoid.\\<close>\n\nsubclass antidomain_monoid\n  by (standard, metis ans1 mult_1_right annir)\n\nlemma \"a_zero = 0\"\n  by (simp add: local.a_zero_def)\n\nsublocale ds: domain_semiring \"(+)\" \"(\\<cdot>)\" 1 0 \"\\<lambda>x. ad (ad x)\" \"(\\<le>)\" \"(<)\"\n  rewrites \"ds.fd x y \\<equiv> fdia x y\"\n  by unfold_locales\n\nend\n\nsubsection \\<open>The Boolean Algebra of Domain Elements\\<close>\n\ntypedef (overloaded) 'a a2_element = \"{x :: 'a :: antidomain_semiring. x = d x}\"\n  by (rule_tac x=1 in exI, auto simp: ads_d_def)\n\nsetup_lifting type_definition_a2_element\n\ninstantiation a2_element :: (antidomain_semiring) boolean_algebra\n\nbegin\n\nlift_definition less_eq_a2_element :: \"'a a2_element \\<Rightarrow> 'a a2_element \\<Rightarrow> bool\" is \"(\\<le>)\" .\n\nlift_definition less_a2_element :: \"'a a2_element \\<Rightarrow> 'a a2_element \\<Rightarrow> bool\" is \"(<)\" .\n\nlift_definition bot_a2_element :: \"'a a2_element\" is 0\n  by (simp add: ads_d_def)\n\nlift_definition top_a2_element :: \"'a a2_element\" is 1\n  by (simp add: ads_d_def)\n\nlift_definition inf_a2_element :: \"'a a2_element \\<Rightarrow> 'a a2_element \\<Rightarrow> 'a a2_element\" is \"(\\<cdot>)\"\n  by (metis (no_types, lifting) ads_d_def dpdz.dom_mult_closed)\n\nlift_definition sup_a2_element :: \"'a a2_element \\<Rightarrow> 'a a2_element \\<Rightarrow> 'a a2_element\" is \"(+)\"\n  by (metis ads_d_def ds.dsr5)\n\nlift_definition minus_a2_element :: \"'a a2_element \\<Rightarrow> 'a a2_element \\<Rightarrow> 'a a2_element\" is \"\\<lambda>x y. x \\<cdot> ad y\"\n  by (metis (no_types, lifting) ads_d_def dpdz.domain_export'')\n\nlift_definition uminus_a2_element :: \"'a a2_element \\<Rightarrow> 'a a2_element\" is antidomain_op\n  by (simp add: ads_d_def)\n\ninstance\n  apply (standard; transfer)\n  apply (simp add: less_le_not_le)\n  apply simp\n  apply auto[1]\n  apply simp\n  apply (metis a_subid_aux2 ads_d_def)\n  apply (metis a_subid_aux1' ads_d_def)\n  apply (metis (no_types, lifting) ads_d_def dpdz.dom_glb)\n  apply simp\n  apply simp\n  apply simp\n  apply simp\n  apply (metis a_subid' ads_d_def)\n  apply (metis (no_types, lifting) ads_d_def dpdz.dom_distrib)\n  apply (metis ads_d_def ans1)\n  apply (metis ads_d_def ans3)\n  by simp\n\nend\n\nsubsection \\<open>Further Properties\\<close>\n\ncontext antidomain_semiringl\n\nbegin\n\nlemma a_2_var: \"ad x \\<cdot> d y = 0 \\<longleftrightarrow> ad x \\<le> ad y\"\n  using local.a_gla local.ads_d_def local.dpdz.dom_weakly_local by auto\n\ntext \\<open>The following two lemmas give the Galois connection of Heyting algebras.\\<close>\n\nlemma da_shunt1: \"x \\<le> d y + z \\<Longrightarrow> x \\<cdot> ad y \\<le> z\"\nproof -\n  assume \"x \\<le> d y + z\"\n  hence \"x \\<cdot> ad y \\<le> (d y + z) \\<cdot> ad y\"\n    using mult_isor by blast\n  also have \"... = d y \\<cdot> ad y + z \\<cdot> ad y\"\n    by simp\n  also have \"... \\<le> z\"\n    by (simp add: a_subid_aux2 ads_d_def)\n  finally show \"x \\<cdot> ad y \\<le> z\"\n    by simp\nqed\n\nlemma da_shunt2: \"x \\<le> ad y + z \\<Longrightarrow> x \\<cdot> d y \\<le> z\"\n  using da_shunt1 local.a_add_idem local.ads_d_def am_add_op_def by auto\n\nlemma d_a_galois1: \"d x \\<cdot> ad y \\<le> d z \\<longleftrightarrow> d x \\<le> d z + d y\"\n  by (metis add_assoc local.a_gla local.ads_d_def local.am2 local.ans4 local.ans_d_def local.dnsz.dnso4)\n\nlemma d_a_galois2: \"d x \\<cdot> d y \\<le> d z \\<longleftrightarrow> d x \\<le> d z + ad y\"\nproof -\n  have \"\\<And>a aa. ad ((a::'a) \\<cdot> ad (ad aa)) = ad (a \\<cdot> aa)\"\n    using local.a2_eq' local.apd_d_def by force\n  then show ?thesis\n    by (metis d_a_galois1 local.a_export' local.ads_d_def local.ans_d_def)\nqed\n\nlemma d_cancellation_1: \"d x \\<le> d y + d x \\<cdot> ad y\"\nproof -\n  have a: \"d (d x \\<cdot> ad y) = ad y \\<cdot> d x\"\n    using local.a_closure' local.ads_d_def local.am2 local.ans_d_def by auto\n  hence \"d x \\<le> d (d x \\<cdot> ad y) + d y\"\n    using d_a_galois1 local.a_comm_var local.ads_d_def by fastforce\n  thus ?thesis\n    using a add_commute local.ads_d_def local.am2 by auto\nqed\n\nlemma d_cancellation_2: \"(d z + d y) \\<cdot> ad y \\<le> d z\"\n  by (simp add: da_shunt1)\n\nlemma a_de_morgan: \"ad (ad x \\<cdot> ad y) = d (x + y)\"\n  by (simp add: local.ads_d_def)\n\nlemma a_de_morgan_var_3: \"ad (d x + d y) = ad x \\<cdot> ad y\"\n  using local.a_add_idem local.ads_d_def am_add_op_def by auto\n\nlemma a_de_morgan_var_4: \"ad (d x \\<cdot> d y) = ad x + ad y\"\n  using local.a_add_idem local.ads_d_def am_add_op_def by auto\n\nlemma a_4: \"ad x \\<le> ad (x \\<cdot> y)\"\n  using local.a_add_idem local.a_antitone' local.dpdz.domain_1'' am_add_op_def by fastforce\n\nlemma a_6: \"ad (d x \\<cdot> y) = ad x + ad y\"\n  using a_de_morgan_var_4 local.ads_d_def by auto\n\nlemma a_7: \"d x \\<cdot> ad (d y + d z) = d x \\<cdot> ad y \\<cdot> ad z\"\n  using a_de_morgan_var_3 local.mult.semigroup_axioms semigroup.assoc by fastforce\n\nlemma a_d_add_closure [simp]: \"d (ad x + ad y) = ad x + ad y\"\n  using local.a_add_idem local.ads_d_def am_add_op_def by auto\n\nlemma d_6 [simp]: \"d x + ad x \\<cdot> d y = d x + d y\"\nproof -\n  have \"ad (ad x \\<cdot> (x + ad y)) = d (x + y)\"\n    by (simp add: distrib_left ads_d_def)\n  thus ?thesis\n    by (simp add: local.ads_d_def local.ans_d_def)\nqed\n\nlemma d_7 [simp]: \"ad x + d x \\<cdot> ad y = ad x + ad y\"\n  by (metis a_d_add_closure local.ads_d_def local.ans4 local.s4)\n\nlemma a_mult_add: \"ad x \\<cdot> (y + x) = ad x \\<cdot> y\"\n  by (simp add: distrib_left)\n\nlemma kat_2: \"y \\<cdot> ad z \\<le> ad x \\<cdot> y \\<Longrightarrow> d x \\<cdot> y \\<cdot> ad z = 0\"\nproof -\n  assume a: \"y \\<cdot> ad z \\<le> ad x \\<cdot> y\"\n  hence \"d x \\<cdot> y \\<cdot> ad z \\<le> d x \\<cdot> ad x \\<cdot> y\"\n    using local.mult_isol mult_assoc by presburger\n  thus ?thesis\n    using local.join.le_bot ads_d_def by auto\nqed\n\nlemma kat_3: \"d x \\<cdot> y \\<cdot> ad z = 0 \\<Longrightarrow> d x \\<cdot> y = d x \\<cdot> y \\<cdot> d z\"\n  using local.a_zero_def local.ads_d_def local.am_d_def local.kat_3' by auto\n\nlemma kat_4: \"d x \\<cdot> y = d x \\<cdot> y \\<cdot> d z \\<Longrightarrow> d x \\<cdot> y \\<le> y \\<cdot> d z\"\n  using a_subid_aux1 mult_assoc ads_d_def by auto\n\nlemma kat_2_equiv: \"y \\<cdot> ad z \\<le> ad x \\<cdot> y \\<longleftrightarrow> d x \\<cdot> y \\<cdot> ad z = 0\"\nproof\n  assume \"y \\<cdot> ad z \\<le> ad x \\<cdot> y\"\n  thus \"d x \\<cdot> y \\<cdot> ad z = 0\"\n    by (simp add: kat_2)\nnext\n  assume 1: \"d x \\<cdot> y \\<cdot> ad z = 0\"\n  have \"y \\<cdot> ad z = (d x + ad x) \\<cdot> y \\<cdot> ad z\"\n    by (simp add: local.ads_d_def)\n  also have \"... = d x \\<cdot> y \\<cdot> ad z + ad x \\<cdot> y \\<cdot> ad z\"\n    using local.distrib_right by presburger\n  also have \"... = ad x \\<cdot> y \\<cdot> ad z\"\n    using \"1\" by auto\n  also have \"... \\<le> ad x \\<cdot> y\"\n    by (simp add: local.a_subid_aux2)\n  finally show \"y \\<cdot> ad z \\<le> ad x \\<cdot> y\" .\nqed\n\nlemma kat_4_equiv: \"d x \\<cdot> y = d x \\<cdot> y \\<cdot> d z \\<longleftrightarrow> d x \\<cdot> y \\<le> y \\<cdot> d z\"\n  using local.ads_d_def local.dpdz.d_preserves_equation by auto\n\nlemma kat_3_equiv_opp: \"ad z \\<cdot> y \\<cdot> d x = 0 \\<longleftrightarrow> y \\<cdot> d x = d z \\<cdot> y \\<cdot> d x\"\nproof -\n  have \"ad z \\<cdot> (y \\<cdot> d x) = 0 \\<longrightarrow> (ad z \\<cdot> y \\<cdot> d x = 0) = (y \\<cdot> d x = d z \\<cdot> y \\<cdot> d x)\"\n    by (metis (no_types, hide_lams) add_commute local.add_zerol local.ads_d_def local.as3 local.distrib_right' local.mult_1_left mult_assoc)\n  thus ?thesis\n    by (metis a_4 local.a_add_idem local.a_gla2 local.ads_d_def mult_assoc am_add_op_def)\nqed\n\nlemma kat_4_equiv_opp: \"y \\<cdot> d x = d z \\<cdot> y \\<cdot> d x \\<longleftrightarrow> y \\<cdot> d x \\<le> d z \\<cdot> y\"\n  using kat_2_equiv kat_3_equiv_opp local.ads_d_def by auto\n\nsubsection \\<open>Forward Box and Diamond Operators\\<close>\n\nlemma fdemodalisation22: \"|x\\<rangle> y \\<le> d z \\<longleftrightarrow> ad z \\<cdot> x \\<cdot> d y = 0\"\nproof -\n  have \"|x\\<rangle> y \\<le> d z \\<longleftrightarrow> d (x \\<cdot> y) \\<le> d z\"\n    by (simp add: fdia_def ads_d_def)\n  also have \"... \\<longleftrightarrow> ad z \\<cdot> d (x \\<cdot> y) = 0\"\n    by (metis add_commute local.a_gla local.ads_d_def local.ans4)\n  also have \"... \\<longleftrightarrow> ad z \\<cdot> x \\<cdot> y = 0\"\n    using dpdz.dom_weakly_local mult_assoc ads_d_def by auto\n  finally show ?thesis\n    using dpdz.dom_weakly_local ads_d_def by auto\nqed\n\nlemma dia_diff_var: \"|x\\<rangle> y \\<le> |x\\<rangle> (d y \\<cdot> ad z) + |x\\<rangle> z\"\nproof -\n  have 1: \"|x\\<rangle> (d y \\<cdot> d z) \\<le> |x\\<rangle> (1 \\<cdot> d z)\"\n    using dpdz.dom_glb_eq ds.fd_subdist fdia_def ads_d_def by force\n  have \"|x\\<rangle> y = |x\\<rangle> (d y \\<cdot> (ad z + d z))\"\n    by (metis as3 add_comm ds.fdia_d_simp mult_1_right ads_d_def)\n  also have \"... = |x\\<rangle> (d y \\<cdot> ad z) + |x\\<rangle> (d y \\<cdot> d z)\"\n    by (simp add: local.distrib_left local.ds.fdia_add1)\n  also have \"... \\<le> |x\\<rangle> (d y \\<cdot> ad z) + |x\\<rangle> (1 \\<cdot> d z)\"\n    using \"1\" local.join.sup.mono by blast\n  finally show ?thesis\n    by (simp add: fdia_def ads_d_def)\nqed\n\nlemma dia_diff: \"|x\\<rangle> y \\<cdot> ad ( |x\\<rangle> z ) \\<le> |x\\<rangle> (d y \\<cdot> ad z)\"\n  using fdia_def dia_diff_var d_a_galois2 ads_d_def by metis\n\nlemma fdia_export_2: \"ad y \\<cdot> |x\\<rangle> z = |ad y \\<cdot> x\\<rangle> z\"\n  using local.am_d_def local.d_a_export local.fdia_def mult_assoc by auto\n\nlemma fdia_split: \"|x\\<rangle> y = d z \\<cdot> |x\\<rangle> y + ad z \\<cdot> |x\\<rangle> y\"\n  by (metis mult_onel ans3 distrib_right ads_d_def)\n\ndefinition fbox :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a\" (\"( |_] _)\" [61,81] 82) where\n  \"|x] y = ad (x \\<cdot> ad y)\"\n\ntext \\<open>The next lemmas establish the De Morgan duality between boxes and diamonds.\\<close>\n\nlemma fdia_fbox_de_morgan_2: \"ad ( |x\\<rangle> y) = |x] ad y\"\n  using fbox_def local.a_closure local.a_loc local.am_d_def local.fdia_def by auto\n\nlemma fbox_simp: \"|x] y = |x] d y\"\n  using fbox_def local.a_add_idem local.ads_d_def am_add_op_def by auto\n\nlemma fbox_dom [simp]: \"|x] 0 = ad x\"\n  by (simp add: fbox_def)\n\nlemma fbox_add1: \"|x] (d y \\<cdot> d z) = |x] y \\<cdot> |x] z\"\n  using a_de_morgan_var_4 fbox_def local.distrib_left by auto\n\nlemma fbox_add2: \"|x + y] z = |x] z \\<cdot> |y] z\"\n  by (simp add: fbox_def)\n\nlemma fbox_mult: \"|x \\<cdot> y] z = |x] |y] z\"\n  using fbox_def local.a2_eq' local.apd_d_def mult_assoc by auto\n\nlemma fbox_zero [simp]: \"|0] x = 1\"\n  by (simp add: fbox_def)\n\nlemma fbox_one [simp]: \"|1] x = d x\"\n  by (simp add: fbox_def ads_d_def)\n\nlemma fbox_iso: \"d x \\<le> d y \\<Longrightarrow> |z] x \\<le> |z] y\"\nproof -\n  assume \"d x \\<le> d y\"\n  hence \"ad y \\<le> ad x\"\n    using local.a_add_idem local.a_antitone' local.ads_d_def am_add_op_def by fastforce\n  hence \"z \\<cdot> ad y \\<le> z \\<cdot> ad x\"\n    by (simp add: mult_isol)\n  thus \"|z] x \\<le> |z] y\"\n    by (simp add: fbox_def a_antitone')\nqed\n\nlemma fbox_antitone_var: \"x \\<le> y \\<Longrightarrow> |y] z \\<le> |x] z\"\n  by (simp add: fbox_def a_antitone mult_isor)\n\nlemma fbox_subdist_1: \"|x] (d y \\<cdot> d z) \\<le> |x] y\"\n  using a_de_morgan_var_4 fbox_def local.a_supdist_var local.distrib_left by force\n\nlemma fbox_subdist_2: \"|x] y \\<le>|x] (d y + d z)\"\n  by (simp add: fbox_iso ads_d_def)\n\n\n\nlemma fbox_diff_var: \"|x] (d y + ad z) \\<cdot> |x] z \\<le> |x] y\"\nproof -\n  have \"ad (ad y) \\<cdot> ad (ad z) = ad (ad z + ad y)\"\n    using local.dpdz.dsg4 by auto\n  then have \"d (d (d y + ad z) \\<cdot> d z) \\<le> d y\"\n    by (simp add: local.a_subid_aux1' local.ads_d_def)\n  then show ?thesis\n    by (metis fbox_add1 fbox_iso)\nqed\n\nlemma fbox_diff: \"|x] (d y + ad z) \\<le> |x] y + ad ( |x] z )\"\nproof -\n  have f1: \"\\<And>a. ad (ad (ad (a::'a))) = ad a\"\n    using local.a_closure' local.ans_d_def by force\n  have f2: \"\\<And>a aa. ad (ad (a::'a)) + ad aa = ad (ad a \\<cdot> aa)\"\n    using local.ans_d_def by auto\n  have f3: \"\\<And>a aa. ad ((a::'a) + aa) = ad (aa + a)\"\n    by (simp add: local.am2)\n  then have f4: \"\\<And>a aa. ad (ad (ad (a::'a) \\<cdot> aa)) = ad (ad aa + a)\"\n    using f2 f1 by (metis (no_types) local.ans4)\n  have f5: \"\\<And>a aa ab. ad ((a::'a) \\<cdot> (aa + ab)) = ad (a \\<cdot> (ab + aa))\"\n    using f3 local.distrib_left by presburger\n  have f6: \"\\<And>a aa. ad (ad (ad (a::'a) + aa)) = ad (ad aa \\<cdot> a)\"\n    using f3 f1 by fastforce\n  have \"ad (x \\<cdot> ad (y + ad z)) \\<le> ad (ad (x \\<cdot> ad z) \\<cdot> (x \\<cdot> ad y))\"\n    using f5 f2 f1 by (metis (no_types) a_mult_add fbox_def fbox_subdist_1 local.a_gla2 local.ads_d_def local.ans4 local.distrib_left local.gla_1 mult_assoc)\n  then show ?thesis\n    using f6 f4 f3 f1 by (simp add: fbox_def local.ads_d_def)\nqed\n\nend\n\ncontext antidomain_semiring\n\nbegin\n\nlemma kat_1: \"d x \\<cdot> y \\<le> y \\<cdot> d z \\<Longrightarrow> y \\<cdot> ad z \\<le> ad x \\<cdot> y\"\nproof -\n  assume a: \"d x \\<cdot> y \\<le> y \\<cdot> d z\"\n  have \"y \\<cdot> ad z = d x \\<cdot> y \\<cdot> ad z + ad x \\<cdot> y \\<cdot> ad z\"\n    by (metis local.ads_d_def local.as3 local.distrib_right local.mult_1_left)\n  also have \"... \\<le> y \\<cdot> (d z \\<cdot> ad z) + ad x \\<cdot> y \\<cdot> ad z\"\n    by (metis a add_iso mult_isor mult_assoc)\n  also have \"... = ad x \\<cdot> y \\<cdot> ad z\"\n    by (simp add: ads_d_def)\n  finally show \"y \\<cdot> ad z \\<le> ad x \\<cdot> y\"\n    using local.a_subid_aux2 local.dual_order.trans by blast\nqed\n\nlemma kat_1_equiv: \"d x \\<cdot> y \\<le> y \\<cdot> d z \\<longleftrightarrow> y \\<cdot> ad z \\<le> ad x \\<cdot> y\"\n  using kat_1 kat_2 kat_3 kat_4 by blast\n\nlemma kat_3_equiv': \"d x \\<cdot> y \\<cdot> ad z = 0 \\<longleftrightarrow> d x \\<cdot> y = d x \\<cdot> y \\<cdot> d z\"\n  by (simp add: kat_1_equiv local.kat_2_equiv local.kat_4_equiv)\n\nlemma kat_1_equiv_opp: \"y \\<cdot> d x \\<le> d z \\<cdot> y \\<longleftrightarrow> ad z \\<cdot> y \\<le> y \\<cdot> ad x\"\n  by (metis kat_1_equiv local.a_closure' local.ads_d_def local.ans_d_def)\n\nlemma kat_2_equiv_opp: \"ad z \\<cdot> y \\<le> y \\<cdot> ad x \\<longleftrightarrow> ad z \\<cdot> y \\<cdot> d x = 0\"\n  by (simp add: kat_1_equiv_opp local.kat_3_equiv_opp local.kat_4_equiv_opp)\n\nlemma fbox_one_1 [simp]: \"|x] 1 = 1\"\n  by (simp add: fbox_def)\n\nlemma fbox_demodalisation3: \"d y \\<le> |x] d z \\<longleftrightarrow> d y \\<cdot> x \\<le> x \\<cdot> d z\"\n  by (simp add: fbox_def a_gla kat_2_equiv_opp mult_assoc ads_d_def)\n\nend\n\nsubsection \\<open>Antidomain Kleene Algebras\\<close>\n\nclass antidomain_left_kleene_algebra = antidomain_semiringl + left_kleene_algebra_zerol\n\nbegin\n\nsublocale dka: domain_left_kleene_algebra \"(+)\" \"(\\<cdot>)\" 1 0 d \"(\\<le>)\" \"(<)\" star\n  rewrites \"domain_semiringl.fd (\\<cdot>) d x y \\<equiv> |x\\<rangle> y\"\n  by (unfold_locales, auto simp add: local.ads_d_def ans_d_def)\n\n\n\nlemma fbox_star_unfold [simp]: \"|1] z \\<cdot> |x] |x\\<^sup>\\<star>] z = |x\\<^sup>\\<star>] z\"\nproof -\n  have \"ad (ad z + x \\<cdot> (x\\<^sup>\\<star> \\<cdot> ad z)) = ad (x\\<^sup>\\<star> \\<cdot> ad z)\"\n    using local.conway.dagger_unfoldl_distr mult_assoc by auto\n  then show ?thesis\n    using local.a_closure' local.ans_d_def local.fbox_def local.fdia_def local.fdia_fbox_de_morgan_2 by fastforce\nqed\n\nlemma fbox_star_unfold_var [simp]: \"d z \\<cdot> |x] |x\\<^sup>\\<star>] z = |x\\<^sup>\\<star>] z\"\n  using fbox_star_unfold by auto\n\nlemma fbox_star_unfoldr [simp]: \"|1] z \\<cdot> |x\\<^sup>\\<star>] |x] z = |x\\<^sup>\\<star>] z\"\n  by (metis fbox_star_unfold fbox_mult star_slide_var)\n\nlemma fbox_star_unfoldr_var [simp]: \"d z \\<cdot> |x\\<^sup>\\<star>] |x] z = |x\\<^sup>\\<star>] z\"\n  using fbox_star_unfoldr by auto\n\nlemma fbox_star_induct_var: \"d y \\<le> |x] y \\<Longrightarrow> d y \\<le> |x\\<^sup>\\<star>] y\"\nproof -\n  assume a1: \"d y \\<le> |x] y\"\n  have \"\\<And>a. ad (ad (ad (a::'a))) = ad a\"\n    using local.a_closure' local.ans_d_def by auto\n  then have \"ad (ad (x\\<^sup>\\<star> \\<cdot> ad y)) \\<le> ad y\"\n    using a1 by (metis dka.fdia_star_induct local.a_export' local.ads_d_def local.ans4 local.ans_d_def local.eq_refl local.fbox_def local.fdia_def local.meet_ord_def)\n  then have \"ad (ad y + ad (x\\<^sup>\\<star> \\<cdot> ad y)) = zero_class.zero\"\n    by (metis (no_types) add_commute local.a_2_var local.ads_d_def local.ans4)\n  then show ?thesis\n    using local.a_2_var local.ads_d_def local.fbox_def by auto\nqed\n\nlemma fbox_star_induct: \"d y \\<le> d z \\<cdot> |x] y \\<Longrightarrow> d y \\<le> |x\\<^sup>\\<star>] z\"\nproof -\n  assume a1: \"d y \\<le> d z \\<cdot> |x] y\"\n  hence a: \"d y \\<le> d z\" and \"d y \\<le> |x] y\"\n    apply (metis local.a_subid_aux2 local.dual_order.trans local.fbox_def)\n    using a1 dka.dom_subid_aux2 local.dual_order.trans by blast\n  hence \"d y \\<le> |x\\<^sup>\\<star>] y\"\n    using fbox_star_induct_var by blast\n  thus ?thesis\n    using a local.fbox_iso local.order.trans by blast\nqed\n\nlemma fbox_star_induct_eq: \"d z \\<cdot> |x] y = d y \\<Longrightarrow> d y \\<le> |x\\<^sup>\\<star>] z\"\n  by (simp add: fbox_star_induct)\n\nlemma fbox_export_1: \"ad y + |x] y = |d y \\<cdot> x] y\"\n  by (simp add: local.a_6 local.fbox_def mult_assoc)\n\nlemma fbox_export_2: \"d y + |x] y = |ad y \\<cdot> x] y\"\n  by (simp add: local.ads_d_def local.ans_d_def local.fbox_def mult_assoc)\n\nend\n\nclass antidomain_kleene_algebra = antidomain_semiring + kleene_algebra\n\nbegin\n\nsubclass antidomain_left_kleene_algebra ..\n\nlemma \"d p \\<le> |(d t \\<cdot> x)\\<^sup>\\<star> \\<cdot> ad t] (d q \\<cdot> ad t) \\<Longrightarrow> d p \\<le> |d t \\<cdot> x] d q\"\n(*nitpick [expect=genuine]*)\noops\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/Antidomain_Semiring.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473647220786, "lm_q2_score": 0.8031738034238806, "lm_q1q2_score": 0.700646550830631}}
{"text": "(*\n  Theory: Poisson.thy\n  Author: Manuel Eberl\n*)\n\nheader {* Poisson Distribution *}\n\ntheory Poisson\nimports Probability PDF_Misc\nbegin\n\nclass poisson = linordered_semiring +\n  fixes poisson_density :: \"real \\<Rightarrow> 'a \\<Rightarrow> ereal\"\n  fixes poisson_density' :: \"real \\<Rightarrow> 'a \\<Rightarrow> real\"\n  assumes measurable_poisson_density[measurable]: \n            \"split poisson_density \\<in> borel_measurable (borel \\<Otimes>\\<^sub>M count_space UNIV)\"\n  assumes poisson_density_ge_0: \"rate \\<ge> 0 \\<Longrightarrow> poisson_density rate x \\<ge> 0\"\n  assumes poisson_density_of_neg_eq_0: \"x < 0 \\<Longrightarrow> poisson_density rate x = 0\"\n  assumes poisson_density_integral_eq_1: \n            \"rate \\<ge> 0 \\<Longrightarrow> (\\<integral>\\<^sup>+x. poisson_density rate x \\<partial>count_space UNIV) = 1\"\n  assumes poisson_density_real[simp]: \"real (poisson_density rate x) = poisson_density' rate x\"\n  assumes poisson_density'_ereal[simp]: \"ereal (poisson_density' rate x) = poisson_density rate x\"\nbegin\n\n  definition \"poisson_space rate \\<equiv> density (count_space UNIV) (poisson_density rate)\"\n\n  lemma poisson_density'_ge_0: \"rate \\<ge> 0 \\<Longrightarrow> poisson_density' rate x \\<ge> 0\"\n    using poisson_density_ge_0 \n    by (simp add: poisson_density'_ereal[symmetric] del: poisson_density'_ereal)\n\n  lemma poisson_density'_of_neg_eq_0: \"x < 0 \\<Longrightarrow> poisson_density' rate x = 0\"\n    using poisson_density_of_neg_eq_0 \n    by (simp add: poisson_density'_ereal[symmetric] del: poisson_density'_ereal)\n\n  lemma space_poisson_space: \"space (poisson_space rate) = UNIV\"\n    unfolding poisson_space_def by simp\n\n  lemma sets_poisson_space: \"sets (poisson_space rate) = UNIV\"\n    unfolding poisson_space_def by simp\n\n  lemma emeasure_poisson_space: \n      \"emeasure (poisson_space rate) A = \n         \\<integral>\\<^sup>+x. poisson_density rate x * indicator A x \\<partial>count_space UNIV\"\n    by (simp add: poisson_space_def emeasure_density)\n\n  lemma prob_space_poisson[intro]: \"rate \\<ge> 0 \\<Longrightarrow> prob_space (poisson_space rate)\"\n    by (auto intro!: prob_spaceI \n             simp: poisson_density_integral_eq_1 emeasure_poisson_space space_poisson_space)\n\n  lemma measurable_poisson_space_eq1[simp]:\n    \"measurable (poisson_space rate) N = measurable (count_space UNIV) N\"\n    by (intro measurable_cong_sets) (simp_all add: sets_poisson_space)\n\n  lemma measurable_poisson_space_eq2[simp]:\n    \"measurable M (poisson_space rate) = measurable M (count_space UNIV)\"\n    by (intro measurable_cong_sets) (simp_all add: sets_poisson_space)\n\nend\n\n\nlemma poisson_density_nat_integral_eq_1:\n  assumes \"rate \\<ge> 0\"\n  shows \"(\\<integral>\\<^sup>+(x::nat). rate ^ x / fact x * exp (-rate) \\<partial>count_space UNIV) = 1\"\nproof-\n  have summable: \"summable (\\<lambda>x::nat. rate ^ x / fact x)\" using summable_exp\n      by (simp add: field_simps field_divide_inverse[symmetric])\n  have \"(\\<integral>\\<^sup>+(x::nat). rate ^ x / fact x * exp (-rate) \\<partial>count_space UNIV) =\n            exp (-rate) * (\\<integral>\\<^sup>+(x::nat). rate ^ x / fact x \\<partial>count_space UNIV)\"\n      by (simp add: field_simps nn_integral_cmult[symmetric])\n  also from assms have \"(\\<integral>\\<^sup>+(x::nat). rate ^ x / fact x \\<partial>count_space UNIV) = (\\<Sum>x. rate ^ x / fact x)\"\n      by (simp_all add: nn_integral_count_space_nat\n                        suminf_ereal summable suminf_ereal_finite)\n  also have \"... = exp rate\" unfolding exp_def\n      by (simp add: field_simps field_divide_inverse[symmetric] transfer_int_nat_factorial)\n  also have \"ereal (exp (-rate)) * ereal (exp rate) = 1\" by (simp add: mult_exp_exp)\n  finally show ?thesis .\nqed\n\ninstantiation nat :: poisson\nbegin\n  definition poisson_density_nat :: \"real \\<Rightarrow> nat \\<Rightarrow> ereal\" where\n    \"poisson_density_nat rate k = rate ^ k / fact k * exp (-rate)\"\n  definition poisson_density'_nat :: \"real \\<Rightarrow> nat \\<Rightarrow> real\" where\n    \"poisson_density'_nat rate k = rate ^ k / fact k * exp (-rate)\"\n\n  instance proof\n    show \"split (poisson_density :: _ \\<Rightarrow> nat \\<Rightarrow> _) \\<in> borel_measurable (borel \\<Otimes>\\<^sub>M count_space UNIV)\"\n      unfolding poisson_density_nat_def[abs_def] by measurable\n  next\n    fix rate :: real assume \"rate \\<ge> 0\"\n    thus \"(\\<integral>\\<^sup>+(x::nat). poisson_density rate x \\<partial>count_space UNIV) = 1\"\n      unfolding poisson_density_nat_def\n      by (rule poisson_density_nat_integral_eq_1)\n  qed (simp_all add: poisson_density_nat_def poisson_density'_nat_def)\nend\n\ninstantiation int :: poisson\nbegin\n  definition poisson_density_int :: \"real \\<Rightarrow> int \\<Rightarrow> ereal\" where\n    \"poisson_density_int rate k = rate ^ (nat k) / fact k * exp (-rate)\"\n  definition poisson_density'_int :: \"real \\<Rightarrow> int \\<Rightarrow> real\" where\n    \"poisson_density'_int rate k = rate ^ (nat k) / fact k * exp (-rate)\"\n\n  instance proof\n    show \"split (poisson_density :: _ \\<Rightarrow> int \\<Rightarrow> _) \\<in> borel_measurable (borel \\<Otimes>\\<^sub>M count_space UNIV)\"\n      unfolding poisson_density_int_def[abs_def] by measurable\n  next\n    fix rate :: real assume r: \"rate \\<ge> 0\"\n    have \"(\\<integral>\\<^sup>+(x::int). poisson_density rate x \\<partial>count_space UNIV) =\n              \\<integral>\\<^sup>+(x::int). rate ^ nat x / real (fact x) * exp (-rate) \\<partial>count_space UNIV\"\n      unfolding poisson_density_int_def by simp\n    also from r have \"... = \\<integral>\\<^sup>+(x::nat). rate ^ x / real (fact x) * exp (-rate) \\<partial>count_space UNIV\"\n      by (simp add: nn_integral_nat_int transfer_int_nat_factorial)\n    also from r have \"... = 1\" by (rule poisson_density_nat_integral_eq_1)\n    finally show \"(\\<integral>\\<^sup>+(x::int). poisson_density rate x \\<partial>count_space UNIV) = 1\" .\n  qed (simp_all add: poisson_density_int_def poisson_density'_int_def)\nend\n\nlemma transfer_nat_int_poisson_density:\n  \"(x::int) \\<ge> 0 \\<Longrightarrow> poisson_density rate (nat x) = poisson_density rate x\"\n  unfolding poisson_density_nat_def poisson_density_int_def\n  by (simp add: transfer_nat_int_factorial)\n\ndeclare transfer_morphism_nat_int[transfer add return: transfer_nat_int_poisson_density]\n\nlemma transfer_int_nat_poisson_density:\n  \"poisson_density rate (int x) = poisson_density rate x\"\n  unfolding poisson_density_nat_def poisson_density_int_def\n  by (simp add: transfer_int_nat_factorial)\n\ndeclare transfer_morphism_int_nat[transfer add return: transfer_int_nat_poisson_density]\n\n\nlemma poisson_space_nat_distr:\n  assumes \"rate \\<ge> 0\"\n  shows \"poisson_space rate = distr (poisson_space rate) (count_space UNIV) (nat :: int \\<Rightarrow> nat)\"\n    (is \"?M1 = ?M2\")\nproof (intro measure_eqI)\n  fix X :: \"nat set\" assume X: \"X \\<in> sets (poisson_space rate)\"\n  have [simp]: \"\\<And>x. indicator (nat -` X) x = indicator X (nat x)\" by (simp add: indicator_def)\n  from X and assms \n    have \"emeasure ?M1 X = \\<integral>\\<^sup>+ x. poisson_density rate x * indicator X x \\<partial>count_space UNIV\"\n    by (simp add: sets_poisson_space emeasure_poisson_space)\n  also from assms have \"... = \\<integral>\\<^sup>+ x. poisson_density rate x * indicator X (nat x) \\<partial>count_space UNIV\"\n    by (subst nn_integral_nat_int)\n       (simp_all add: transfer_int_nat_poisson_density poisson_density_ge_0 \n                      poisson_density_of_neg_eq_0)\n  also from X have \"... = emeasure ?M2 X\"\n    by (simp add: emeasure_distr emeasure_poisson_space space_poisson_space)\n  finally show \"emeasure ?M1 X = emeasure ?M2 X\" .\nqed (simp add: sets_poisson_space)\n\nlemma poisson_space_int_distr:\n  assumes \"rate \\<ge> 0\"\n  shows \"poisson_space rate = distr (poisson_space rate) (count_space UNIV) (int :: nat \\<Rightarrow> int)\"\n    (is \"?M1 = ?M2\")\nproof (intro measure_eqI)\n  fix X :: \"int set\" assume X: \"X \\<in> sets (poisson_space rate)\"\n  have [simp]: \"\\<And>x. indicator (int -` X) x = indicator X (int x)\" by (simp add: indicator_def)\n  from X and assms \n    have \"emeasure ?M1 X = \\<integral>\\<^sup>+ x. poisson_density rate x * indicator X x \\<partial>count_space UNIV\"\n    by (simp add: sets_poisson_space emeasure_poisson_space)\n  also from assms have \"... = \\<integral>\\<^sup>+ x. poisson_density rate x * indicator X (int x) \\<partial>count_space UNIV\"\n    by (subst nn_integral_nat_int)\n       (simp_all add: transfer_int_nat_poisson_density poisson_density_ge_0 \n                      poisson_density_of_neg_eq_0)\n  also from X have \"... = emeasure ?M2 X\"\n    by (simp add: emeasure_distr emeasure_poisson_space space_poisson_space)\n  finally show \"emeasure ?M1 X = emeasure ?M2 X\" .\nqed (simp add: sets_poisson_space)\n\n\n(*\nlemma expectation_poisson_nat:\n  fixes M :: \"'a measure\" and X :: \"'a \\<Rightarrow> nat\"\n  assumes \"prob_space M\" \n  assumes r: \"rate \\<ge> 0\" and dist: \"distributed M (count_space UNIV) X (poisson_density rate)\"\n  shows \"integral\\<^sup>L M (\\<lambda>x. real (X x)) = rate\"\nproof-\n  from r have [simp]: \"\\<And>x::nat. poisson_density' rate x * real x \\<ge> 0\"\n    by (case_tac \"x \\<ge> 0\") (simp_all add: poisson_density'_ge_0 poisson_density'_of_neg_eq_0)\n  have \"(\\<integral>\\<^sup>+(x::nat). ereal (- (poisson_density' rate x * real x)) \\<partial>count_space UNIV) = 0\"\n    by (subst nn_integral_0_iff_AE, simp) \n       (auto simp: poisson_density'_ge_0 intro!: AE_I'[of \"{}\"])\n  moreover {\n    from r have \"1 = (\\<integral>\\<^sup>+(x::nat). ereal (poisson_density' rate x) \\<partial>count_space UNIV)\"\n      by (simp add: poisson_density_integral_eq_1)\n    also from r have \"... = (\\<Sum>x. ereal (poisson_density' rate x))\"\n       by (subst nn_integral_count_space_nat) (simp_all add: poisson_density_ge_0)\n    finally have A: \"(\\<Sum>x. ereal (poisson_density' rate x)) = 1\" ..\n    with r have B: \"summable (poisson_density' rate)\"\n      by (intro summable_ereal) (simp_all add: poisson_density'_ge_0)\n    hence \"(\\<Sum>x. poisson_density' rate x) = exp (-rate) + (\\<Sum>x. poisson_density' rate (x+1))\"\n      by (subst suminf_split_initial_segment[where k = 1]) (simp_all add: poisson_density'_nat_def)\n    also have \"(\\<Sum>x. poisson_density' rate (x+1)) = rate * (\\<Sum>x. poisson_density' rate (x+1) * (x + 1))\"\n  }\n\n  interpret prob_space M by fact\n  from dist have \"expectation (\\<lambda>x. real (X x)) = \n                      integral\\<^sup>L (distr M (count_space UNIV) X) real\"\n    unfolding distributed_def by (subst integral_distr) simp_all\n  also from dist have \"distr M (count_space UNIV) X = \n                           density (count_space UNIV) (poisson_density' rate)\"\n    unfolding distributed_def by simp\n  also from r and dist \n    have \"integral\\<^sup>L ... real = \n              integral\\<^sup>L (count_space UNIV) (\\<lambda>x::nat. poisson_density' rate x * real x)\"\n    by (subst integral_density) (simp_all add: poisson_density'_ge_0)\n  also \n  hence \"integral\\<^sup>L (count_space UNIV) (\\<lambda>x::nat. poisson_density' rate x * real x) = \n             (\\<Sum>x. poisson_density' rate x * real x)\"\napply (intro integral_count_space_nat)\napply (unfold integrable_def)\napply auto\napply (subst (asm) times_ereal.simps[symmetric])\napply (subst (asm) poisson_density'_ereal)\napply simp\n  also have \"(\\<lambda>x::nat. poisson_density' rate x * real x) = T\"\napply (simp add: poisson_density'_nat_def)\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/Density_Compiler/Poisson.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473647220786, "lm_q2_score": 0.8031737987125612, "lm_q1q2_score": 0.700646546720724}}
{"text": "(* Title:      Minimum Spanning Tree Algorithms\n   Author:     Walter Guttmann\n   Maintainer: Walter Guttmann <walter.guttmann at canterbury.ac.nz>\n*)\n\nsection \\<open>Minimum Spanning Tree Algorithms\\<close>\n\ntext \\<open>\nIn this theory we prove the total-correctness of Kruskal's and Prim's minimum spanning tree algorithms.\nSpecifications and algorithms work in Stone-Kleene relation algebras extended by operations for aggregation and minimisation.\nThe algorithms are implemented in a simple imperative language and their proof uses Hoare Logic.\nThe correctness proofs are discussed in \\cite{Guttmann2016c,Guttmann2018a,Guttmann2018b}.\n\\<close>\n\ntheory Minimum_Spanning_Trees\n\nimports Hoare_Logic Aggregation_Algebras\n\nbegin\n\nno_notation\n  trancl (\"(_\\<^sup>+)\" [1000] 999)\n\ncontext m_kleene_algebra\nbegin\n\nsubsection \\<open>Kruskal's Minimum Spanning Tree Algorithm\\<close>\n\ntext \\<open>\nThe total-correctness proof of Kruskal's minimum spanning tree algorithm uses the following steps \\cite{Guttmann2018b}.\nWe first establish that the algorithm terminates and constructs a spanning tree.\nThis is a constructive proof of the existence of a spanning tree; any spanning tree algorithm could be used for this.\nWe then conclude that a minimum spanning tree exists.\nThis is necessary to establish the invariant for the actual correctness proof, which shows that Kruskal's algorithm produces a minimum spanning tree.\n\\<close>\n\ndefinition \"spanning_forest f g \\<equiv> forest f \\<and> f \\<le> --g \\<and> components g \\<le> forest_components f \\<and> regular f\"\ndefinition \"minimum_spanning_forest f g \\<equiv> spanning_forest f g \\<and> (\\<forall>u . spanning_forest u g \\<longrightarrow> sum (f \\<sqinter> g) \\<le> sum (u \\<sqinter> g))\"\ndefinition \"kruskal_spanning_invariant f g h \\<equiv> symmetric g \\<and> h = h\\<^sup>T \\<and> g \\<sqinter> --h = h \\<and> spanning_forest f (-h \\<sqinter> g)\"\ndefinition \"kruskal_invariant f g h \\<equiv> kruskal_spanning_invariant f g h \\<and> (\\<exists>w . minimum_spanning_forest w g \\<and> f \\<le> w \\<squnion> w\\<^sup>T)\"\n\ntext \\<open>\nWe first show two verification conditions which are used in both correctness proofs.\n\\<close>\n\nlemma kruskal_vc_1:\n  assumes \"symmetric g\"\n    shows \"kruskal_spanning_invariant bot g g\"\nproof (unfold kruskal_spanning_invariant_def, intro conjI)\n  show \"symmetric g\"\n    using assms by simp\nnext\n  show \"g = g\\<^sup>T\"\n    using assms by simp\nnext\n  show \"g \\<sqinter> --g = g\"\n    using inf.sup_monoid.add_commute selection_closed_id by simp\nnext\n  show \"spanning_forest bot (-g \\<sqinter> g)\"\n    using star.circ_transitive_equal spanning_forest_def by simp\nqed\n\nlemma kruskal_vc_2:\n  assumes \"kruskal_spanning_invariant f g h\"\n      and \"h \\<noteq> bot\"\n      and \"card { x . regular x \\<and> x \\<le> --h } = n\"\n    shows \"(minarc h \\<le> -forest_components f \\<longrightarrow> kruskal_spanning_invariant ((f \\<sqinter> -(top * minarc h * f\\<^sup>T\\<^sup>\\<star>)) \\<squnion> (f \\<sqinter> top * minarc h * f\\<^sup>T\\<^sup>\\<star>)\\<^sup>T \\<squnion> minarc h) g (h \\<sqinter> -minarc h \\<sqinter> -minarc h\\<^sup>T)\n                                               \\<and> card { x . regular x \\<and> x \\<le> --h \\<and> x \\<le> -minarc h \\<and> x \\<le> -minarc h\\<^sup>T } < n) \\<and>\n           (\\<not> minarc h \\<le> -forest_components f \\<longrightarrow> kruskal_spanning_invariant f g (h \\<sqinter> -minarc h \\<sqinter> -minarc h\\<^sup>T)\n                                                 \\<and> card { x . regular x \\<and> x \\<le> --h \\<and> x \\<le> -minarc h \\<and> x \\<le> -minarc h\\<^sup>T } < n)\"\nproof -\n  let ?e = \"minarc h\"\n  let ?f = \"(f \\<sqinter> -(top * ?e * f\\<^sup>T\\<^sup>\\<star>)) \\<squnion> (f \\<sqinter> top * ?e * f\\<^sup>T\\<^sup>\\<star>)\\<^sup>T \\<squnion> ?e\"\n  let ?h = \"h \\<sqinter> -?e \\<sqinter> -?e\\<^sup>T\"\n  let ?F = \"forest_components f\"\n  let ?n1 = \"card { x . regular x \\<and> x \\<le> --h }\"\n  let ?n2 = \"card { x . regular x \\<and> x \\<le> --h \\<and> x \\<le> -?e \\<and> x \\<le> -?e\\<^sup>T }\"\n  have 1: \"regular f \\<and> regular ?e\"\n    by (metis assms(1) kruskal_spanning_invariant_def spanning_forest_def minarc_regular)\n  hence 2: \"regular ?f \\<and> regular ?F \\<and> regular (?e\\<^sup>T)\"\n    using regular_closed_star regular_conv_closed regular_mult_closed by simp\n  have 3: \"\\<not> ?e \\<le> -?e\"\n    using assms(2) inf.orderE minarc_bot_iff by fastforce\n  have \"?n2 < ?n1\"\n    apply (rule psubset_card_mono)\n    using finite_regular apply simp\n    using 1 3 kruskal_spanning_invariant_def minarc_below by auto\n  hence 4: \"?n2 < n\"\n    using assms(3) by simp\n  show \"(?e \\<le> -?F \\<longrightarrow> kruskal_spanning_invariant ?f g ?h \\<and> ?n2 < n) \\<and> (\\<not> ?e \\<le> -?F \\<longrightarrow> kruskal_spanning_invariant f g ?h \\<and> ?n2 < n)\"\n  proof (rule conjI)\n    have 5: \"injective ?f\"\n      apply (rule kruskal_injective_inv)\n      using assms(1) kruskal_spanning_invariant_def spanning_forest_def apply simp\n      apply (simp add: covector_mult_closed)\n      apply (simp add: comp_associative comp_isotone star.right_plus_below_circ)\n      apply (meson mult_left_isotone order_lesseq_imp star_outer_increasing top.extremum)\n      using assms(1,2) kruskal_spanning_invariant_def kruskal_injective_inv_2 minarc_arc spanning_forest_def apply simp\n      using assms(2) arc_injective minarc_arc apply blast\n      using assms(1,2) kruskal_spanning_invariant_def kruskal_injective_inv_3 minarc_arc spanning_forest_def by simp\n    show \"?e \\<le> -?F \\<longrightarrow> kruskal_spanning_invariant ?f g ?h \\<and> ?n2 < n\"\n    proof\n      assume 6: \"?e \\<le> -?F\"\n      have 7: \"equivalence ?F\"\n        using assms(1) kruskal_spanning_invariant_def forest_components_equivalence spanning_forest_def by simp\n      have \"?e\\<^sup>T * top * ?e\\<^sup>T = ?e\\<^sup>T\"\n        using assms(2) by (simp add: arc_top_arc minarc_arc)\n      hence \"?e\\<^sup>T * top * ?e\\<^sup>T \\<le> -?F\"\n        using 6 7 conv_complement conv_isotone by fastforce\n      hence 8: \"?e * ?F * ?e = bot\"\n        using le_bot triple_schroeder_p by simp\n      show \"kruskal_spanning_invariant ?f g ?h \\<and> ?n2 < n\"\n      proof (unfold kruskal_spanning_invariant_def, intro conjI)\n        show \"symmetric g\"\n          using assms(1) kruskal_spanning_invariant_def by simp\n      next\n        show \"?h = ?h\\<^sup>T\"\n          using assms(1) by (simp add: conv_complement conv_dist_inf inf_commute inf_left_commute kruskal_spanning_invariant_def)\n      next\n        show \"g \\<sqinter> --?h = ?h\"\n          using 1 2 by (metis (hide_lams) assms(1) kruskal_spanning_invariant_def inf_assoc pp_dist_inf)\n      next\n        show \"spanning_forest ?f (-?h \\<sqinter> g)\"\n        proof (unfold spanning_forest_def, intro conjI)\n          show \"injective ?f\"\n            using 5 by simp\n        next\n          show \"acyclic ?f\"\n            apply (rule kruskal_acyclic_inv)\n            using assms(1) kruskal_spanning_invariant_def spanning_forest_def apply simp\n            apply (simp add: covector_mult_closed)\n            using 8 assms(1) kruskal_spanning_invariant_def spanning_forest_def kruskal_acyclic_inv_1 apply simp\n            using 8 apply (metis comp_associative mult_left_sub_dist_sup_left star.circ_loop_fixpoint sup_commute le_bot)\n            using 6 by (simp add: p_antitone_iff)\n        next\n          show \"?f \\<le> --(-?h \\<sqinter> g)\"\n            apply (rule kruskal_subgraph_inv)\n            using assms(1) kruskal_spanning_invariant_def spanning_forest_def apply simp\n            using assms(1) apply (metis kruskal_spanning_invariant_def minarc_below order.trans pp_isotone_inf)\n            using assms(1) kruskal_spanning_invariant_def apply simp\n            using assms(1) kruskal_spanning_invariant_def by simp\n        next\n          show \"components (-?h \\<sqinter> g) \\<le> forest_components ?f\"\n            apply (rule kruskal_spanning_inv)\n            using 5 apply simp\n            using 1 regular_closed_star regular_conv_closed regular_mult_closed apply simp\n            using 1 apply simp\n            using assms(1) kruskal_spanning_invariant_def spanning_forest_def by simp\n        next\n          show \"regular ?f\"\n            using 2 by simp\n        qed\n      next\n        show \"?n2 < n\"\n          using 4 by simp\n      qed\n    qed\n  next\n    show \"\\<not> ?e \\<le> -?F \\<longrightarrow> kruskal_spanning_invariant f g ?h \\<and> ?n2 < n\"\n    proof\n      assume \"\\<not> ?e \\<le> -?F\"\n      hence 9: \"?e \\<le> ?F\"\n        using 2 assms(2) arc_in_partition minarc_arc by fastforce\n      show \"kruskal_spanning_invariant f g ?h \\<and> ?n2 < n\"\n      proof (unfold kruskal_spanning_invariant_def, intro conjI)\n        show \"symmetric g\"\n          using assms(1) kruskal_spanning_invariant_def by simp\n      next\n        show \"?h = ?h\\<^sup>T\"\n          using assms(1) by (simp add: conv_complement conv_dist_inf inf_commute inf_left_commute kruskal_spanning_invariant_def)\n      next\n        show \"g \\<sqinter> --?h = ?h\"\n          using 1 2 by (metis (hide_lams) assms(1) kruskal_spanning_invariant_def inf_assoc pp_dist_inf)\n      next\n        show \"spanning_forest f (-?h \\<sqinter> g)\"\n        proof (unfold spanning_forest_def, intro conjI)\n          show \"injective f\"\n            using assms(1) kruskal_spanning_invariant_def spanning_forest_def by simp\n        next\n          show \"acyclic f\"\n            using assms(1) kruskal_spanning_invariant_def spanning_forest_def by simp\n        next\n          have \"f \\<le> --(-h \\<sqinter> g)\"\n            using assms(1) kruskal_spanning_invariant_def spanning_forest_def by simp\n          also have \"... \\<le> --(-?h \\<sqinter> g)\"\n            using comp_inf.mult_right_isotone inf.sup_monoid.add_commute inf_left_commute p_antitone_inf pp_isotone by presburger\n          finally show \"f \\<le> --(-?h \\<sqinter> g)\"\n            by simp\n        next\n          show \"components (-?h \\<sqinter> g) \\<le> ?F\"\n            apply (rule kruskal_spanning_inv_1)\n            using 9 apply simp\n            using 1 apply simp\n            using assms(1) kruskal_spanning_invariant_def spanning_forest_def apply simp\n            using assms(1) kruskal_spanning_invariant_def forest_components_equivalence spanning_forest_def by simp\n        next\n          show \"regular f\"\n            using 1 by simp\n        qed\n      next\n        show \"?n2 < n\"\n          using 4 by simp\n      qed\n    qed\n  qed\nqed\n\ntext \\<open>\nThe following result shows that Kruskal's algorithm terminates and constructs a spanning tree.\nWe cannot yet show that this is a minimum spanning tree.\n\\<close>\n\ntheorem kruskal_spanning:\n  \"VARS e f h\n  [ symmetric g ]\n  f := bot;\n  h := g;\n  WHILE h \\<noteq> bot\n    INV { kruskal_spanning_invariant f g h }\n    VAR { card { x . regular x \\<and> x \\<le> --h } }\n     DO e := minarc h;\n        IF e \\<le> -forest_components f THEN\n          f := (f \\<sqinter> -(top * e * f\\<^sup>T\\<^sup>\\<star>)) \\<squnion> (f \\<sqinter> top * e * f\\<^sup>T\\<^sup>\\<star>)\\<^sup>T \\<squnion> e\n        ELSE\n          SKIP\n        FI;\n        h := h \\<sqinter> -e \\<sqinter> -e\\<^sup>T\n     OD\n  [ spanning_forest f g ]\"\n  apply vcg_tc_simp\n  using kruskal_vc_1 apply simp\n  using kruskal_vc_2 apply blast\n  using kruskal_spanning_invariant_def by auto\n\ntext \\<open>\nBecause we have shown total correctness, we conclude that a spanning tree exists.\n\\<close>\n\nlemma kruskal_exists_spanning:\n  \"symmetric g \\<Longrightarrow> \\<exists>f . spanning_forest f g\"\n  using tc_extract_function kruskal_spanning by blast\n\ntext \\<open>\nThis implies that a minimum spanning tree exists, which is used in the subsequent correctness proof.\n\\<close>\n\nlemma kruskal_exists_minimal_spanning:\n  assumes \"symmetric g\"\n    shows \"\\<exists>f . minimum_spanning_forest f g\"\nproof -\n  let ?s = \"{ f . spanning_forest f g }\"\n  have \"\\<exists>m\\<in>?s . \\<forall>z\\<in>?s . sum (m \\<sqinter> g) \\<le> sum (z \\<sqinter> g)\"\n    apply (rule finite_set_minimal)\n    using finite_regular spanning_forest_def apply simp\n    using assms kruskal_exists_spanning apply simp\n    using sum_linear by simp\n  thus ?thesis\n    using minimum_spanning_forest_def by simp\nqed\n\ntext \\<open>\nKruskal's minimum spanning tree algorithm terminates and is correct.\nThis is the same algorithm that is used in the previous correctness proof, with the same precondition and variant, but with a different invariant and postcondition.\n\\<close>\n\ntheorem kruskal:\n  \"VARS e f h\n  [ symmetric g ]\n  f := bot;\n  h := g;\n  WHILE h \\<noteq> bot\n    INV { kruskal_invariant f g h }\n    VAR { card { x . regular x \\<and> x \\<le> --h } }\n     DO e := minarc h;\n        IF e \\<le> -forest_components f THEN\n          f := (f \\<sqinter> -(top * e * f\\<^sup>T\\<^sup>\\<star>)) \\<squnion> (f \\<sqinter> top * e * f\\<^sup>T\\<^sup>\\<star>)\\<^sup>T \\<squnion> e\n        ELSE\n          SKIP\n        FI;\n        h := h \\<sqinter> -e \\<sqinter> -e\\<^sup>T\n     OD\n  [ minimum_spanning_forest f g ]\"\nproof vcg_tc_simp\n  assume \"symmetric g\"\n  thus \"kruskal_invariant bot g g\"\n    using kruskal_vc_1 kruskal_exists_minimal_spanning kruskal_invariant_def by simp\nnext\n  fix n f h\n  let ?e = \"minarc h\"\n  let ?f = \"(f \\<sqinter> -(top * ?e * f\\<^sup>T\\<^sup>\\<star>)) \\<squnion> (f \\<sqinter> top * ?e * f\\<^sup>T\\<^sup>\\<star>)\\<^sup>T \\<squnion> ?e\"\n  let ?h = \"h \\<sqinter> -?e \\<sqinter> -?e\\<^sup>T\"\n  let ?F = \"forest_components f\"\n  let ?n1 = \"card { x . regular x \\<and> x \\<le> --h }\"\n  let ?n2 = \"card { x . regular x \\<and> x \\<le> --h \\<and> x \\<le> -?e \\<and> x \\<le> -?e\\<^sup>T }\"\n  assume 1: \"kruskal_invariant f g h \\<and> h \\<noteq> bot \\<and> ?n1 = n\"\n  from 1 obtain w where 2: \"minimum_spanning_forest w g \\<and> f \\<le> w \\<squnion> w\\<^sup>T\"\n    using kruskal_invariant_def by auto\n  hence 3: \"regular f \\<and> regular w \\<and> regular ?e\"\n    using 1 by (metis kruskal_invariant_def kruskal_spanning_invariant_def minimum_spanning_forest_def spanning_forest_def minarc_regular)\n  show \"(?e \\<le> -?F \\<longrightarrow> kruskal_invariant ?f g ?h \\<and> ?n2 < n) \\<and> (\\<not> ?e \\<le> -?F \\<longrightarrow> kruskal_invariant f g ?h \\<and> ?n2 < n)\"\n  proof (rule conjI)\n    show \"?e \\<le> -?F \\<longrightarrow> kruskal_invariant ?f g ?h \\<and> ?n2 < n\"\n    proof\n      assume 4: \"?e \\<le> -?F\"\n      have 5: \"equivalence ?F\"\n        using 1 kruskal_invariant_def kruskal_spanning_invariant_def forest_components_equivalence spanning_forest_def by simp\n      have \"?e\\<^sup>T * top * ?e\\<^sup>T = ?e\\<^sup>T\"\n        using 1 by (simp add: arc_top_arc minarc_arc)\n      hence \"?e\\<^sup>T * top * ?e\\<^sup>T \\<le> -?F\"\n        using 4 5 conv_complement conv_isotone by fastforce\n      hence 6: \"?e * ?F * ?e = bot\"\n        using le_bot triple_schroeder_p by simp\n      show \"kruskal_invariant ?f g ?h \\<and> ?n2 < n\"\n      proof (unfold kruskal_invariant_def, intro conjI)\n        show \"kruskal_spanning_invariant ?f g ?h\"\n          using 1 4 kruskal_vc_2 kruskal_invariant_def by simp\n      next\n        show \"\\<exists>w . minimum_spanning_forest w g \\<and> ?f \\<le> w \\<squnion> w\\<^sup>T\"\n        proof\n          let ?p = \"w \\<sqinter> top * ?e * w\\<^sup>T\\<^sup>\\<star>\"\n          let ?v = \"(w \\<sqinter> -(top * ?e * w\\<^sup>T\\<^sup>\\<star>)) \\<squnion> ?p\\<^sup>T\"\n          have 7: \"regular ?p\"\n            using 3 regular_closed_star regular_conv_closed regular_mult_closed by simp\n          have 8: \"injective ?v\"\n            apply (rule kruskal_exchange_injective_inv_1)\n            using 2 minimum_spanning_forest_def spanning_forest_def apply simp\n            apply (simp add: covector_mult_closed)\n            apply (simp add: comp_associative comp_isotone star.right_plus_below_circ)\n            using 1 2 kruskal_injective_inv_3 minarc_arc minimum_spanning_forest_def spanning_forest_def by simp\n          have 9: \"components g \\<le> forest_components ?v\"\n            apply (rule kruskal_exchange_spanning_inv_1)\n            using 8 apply simp\n            using 7 apply simp\n            using 2 minimum_spanning_forest_def spanning_forest_def by simp\n          have 10: \"spanning_forest ?v g\"\n          proof (unfold spanning_forest_def, intro conjI)\n            show \"injective ?v\"\n              using 8 by simp\n          next\n            show \"acyclic ?v\"\n              apply (rule kruskal_exchange_acyclic_inv_1)\n              using 2 minimum_spanning_forest_def spanning_forest_def apply simp\n              by (simp add: covector_mult_closed)\n          next\n            show \"?v \\<le> --g\"\n              apply (rule sup_least)\n              using 2 inf.coboundedI1 minimum_spanning_forest_def spanning_forest_def apply simp\n              using 1 2 by (metis kruskal_invariant_def kruskal_spanning_invariant_def conv_complement conv_dist_inf order.trans inf.absorb2 inf.cobounded1 minimum_spanning_forest_def spanning_forest_def)\n          next\n            show \"components g \\<le> forest_components ?v\"\n              using 9 by simp\n          next\n            show \"regular ?v\"\n              using 3 regular_closed_star regular_conv_closed regular_mult_closed by simp\n          qed\n          have 11: \"sum (?v \\<sqinter> g) = sum (w \\<sqinter> g)\"\n          proof -\n            have \"sum (?v \\<sqinter> g) = sum (w \\<sqinter> -(top * ?e * w\\<^sup>T\\<^sup>\\<star>) \\<sqinter> g) + sum (?p\\<^sup>T \\<sqinter> g)\"\n              using 2 by (metis conv_complement conv_top epm_8 inf_import_p inf_top_right regular_closed_top vector_top_closed minimum_spanning_forest_def spanning_forest_def sum_disjoint)\n            also have \"... = sum (w \\<sqinter> -(top * ?e * w\\<^sup>T\\<^sup>\\<star>) \\<sqinter> g) + sum (?p \\<sqinter> g)\"\n              using 1 kruskal_invariant_def kruskal_spanning_invariant_def sum_symmetric by simp\n            also have \"... = sum (((w \\<sqinter> -(top * ?e * w\\<^sup>T\\<^sup>\\<star>)) \\<squnion> ?p) \\<sqinter> g)\"\n              using inf_commute inf_left_commute sum_disjoint by simp\n            also have \"... = sum (w \\<sqinter> g)\"\n              using 3 7 maddux_3_11_pp by simp\n            finally show ?thesis\n              by simp\n          qed\n          have 12: \"?v \\<squnion> ?v\\<^sup>T = w \\<squnion> w\\<^sup>T\"\n          proof -\n            have \"?v \\<squnion> ?v\\<^sup>T = (w \\<sqinter> -?p) \\<squnion> ?p\\<^sup>T \\<squnion> (w\\<^sup>T \\<sqinter> -?p\\<^sup>T) \\<squnion> ?p\"\n              using conv_complement conv_dist_inf conv_dist_sup inf_import_p sup_assoc by simp\n            also have \"... = w \\<squnion> w\\<^sup>T\"\n              using 3 7 conv_complement conv_dist_inf inf_import_p maddux_3_11_pp sup_monoid.add_assoc sup_monoid.add_commute by simp\n            finally show ?thesis\n              by simp\n          qed\n          have 13: \"?v * ?e\\<^sup>T = bot\"\n            apply (rule kruskal_reroot_edge)\n            using 1 apply (simp add: minarc_arc)\n            using 2 minimum_spanning_forest_def spanning_forest_def by simp\n          have \"?v \\<sqinter> ?e \\<le> ?v \\<sqinter> top * ?e\"\n            using inf.sup_right_isotone top_left_mult_increasing by simp\n          also have \"... \\<le> ?v * (top * ?e)\\<^sup>T\"\n            using covector_restrict_comp_conv covector_mult_closed vector_top_closed by simp\n          finally have 14: \"?v \\<sqinter> ?e = bot\"\n            using 13 by (metis conv_dist_comp mult_assoc le_bot mult_left_zero)\n          let ?d = \"?v \\<sqinter> top * ?e\\<^sup>T * ?v\\<^sup>T\\<^sup>\\<star> \\<sqinter> ?F * ?e\\<^sup>T * top \\<sqinter> top * ?e * -?F\"\n          let ?w = \"(?v \\<sqinter> -?d) \\<squnion> ?e\"\n          have 15: \"regular ?d\"\n            using 3 regular_closed_star regular_conv_closed regular_mult_closed by simp\n          have 16: \"?F \\<le> -?d\"\n            apply (rule kruskal_edge_between_components_1)\n            using 5 apply simp\n            using 1 conv_dist_comp minarc_arc mult_assoc by simp\n          have 17: \"f \\<squnion> f\\<^sup>T \\<le> (?v \\<sqinter> -?d \\<sqinter> -?d\\<^sup>T) \\<squnion> (?v\\<^sup>T \\<sqinter> -?d \\<sqinter> -?d\\<^sup>T)\"\n            apply (rule kruskal_edge_between_components_2)\n            using 16 apply simp\n            using 1 kruskal_invariant_def kruskal_spanning_invariant_def spanning_forest_def apply simp\n            using 2 12 by (metis conv_dist_sup conv_involutive conv_isotone le_supI sup_commute)\n          show \"minimum_spanning_forest ?w g \\<and> ?f \\<le> ?w \\<squnion> ?w\\<^sup>T\"\n          proof (intro conjI)\n            have 18: \"?e\\<^sup>T \\<le> ?v\\<^sup>\\<star>\"\n              apply (rule kruskal_edge_arc_1[where g=g and h=h])\n              using minarc_below apply simp\n              using 1 apply (metis kruskal_invariant_def kruskal_spanning_invariant_def inf_le1)\n              using 1 kruskal_invariant_def kruskal_spanning_invariant_def apply simp\n              using 9 apply simp\n              using 13 by simp\n            have 19: \"arc ?d\"\n              apply (rule kruskal_edge_arc)\n              using 5 apply simp\n              using 10 spanning_forest_def apply blast\n              using 1 apply (simp add: minarc_arc)\n              using 3 apply (metis conv_complement pp_dist_star regular_mult_closed)\n              using 2 8 12 apply (simp add: kruskal_forest_components_inf)\n              using 10 spanning_forest_def apply simp\n              using 13 apply simp\n              using 6 apply simp\n              using 18 by simp\n            show \"minimum_spanning_forest ?w g\"\n            proof (unfold minimum_spanning_forest_def, intro conjI)\n              have \"(?v \\<sqinter> -?d) * ?e\\<^sup>T \\<le> ?v * ?e\\<^sup>T\"\n                using inf_le1 mult_left_isotone by simp\n              hence \"(?v \\<sqinter> -?d) * ?e\\<^sup>T = bot\"\n                using 13 le_bot by simp\n              hence 20: \"?e * (?v \\<sqinter> -?d)\\<^sup>T = bot\"\n                using conv_dist_comp conv_involutive conv_bot by force\n              have 21: \"injective ?w\"\n                apply (rule injective_sup)\n                using 8 apply (simp add: injective_inf_closed)\n                using 20 apply simp\n                using 1 arc_injective minarc_arc by blast\n              show \"spanning_forest ?w g\"\n              proof (unfold spanning_forest_def, intro conjI)\n                show \"injective ?w\"\n                  using 21 by simp\n              next\n                show \"acyclic ?w\"\n                  apply (rule kruskal_exchange_acyclic_inv_2)\n                  using 10 spanning_forest_def apply blast\n                  using 8 apply simp\n                  using inf.coboundedI1 apply simp\n                  using 19 apply simp\n                  using 1 apply (simp add: minarc_arc)\n                  using inf.cobounded2 inf.coboundedI1 apply simp\n                  using 13 by simp\n              next\n                have \"?w \\<le> ?v \\<squnion> ?e\"\n                  using inf_le1 sup_left_isotone by simp\n                also have \"... \\<le> --g \\<squnion> ?e\"\n                  using 10 sup_left_isotone spanning_forest_def by blast\n                also have \"... \\<le> --g \\<squnion> --h\"\n                  by (simp add: le_supI2 minarc_below)\n                also have \"... = --g\"\n                  using 1 by (metis kruskal_invariant_def kruskal_spanning_invariant_def pp_isotone_inf sup.orderE)\n                finally show \"?w \\<le> --g\"\n                  by simp\n              next\n                have 22: \"?d \\<le> (?v \\<sqinter> -?d)\\<^sup>T\\<^sup>\\<star> * ?e\\<^sup>T * top\"\n                  apply (rule kruskal_exchange_spanning_inv_2)\n                  using 8 apply simp\n                  using 13 apply (metis semiring.mult_not_zero star_absorb star_simulation_right_equal)\n                  using 17 apply simp\n                  by (simp add: inf.coboundedI1)\n                have \"components g \\<le> forest_components ?v\"\n                  using 10 spanning_forest_def by auto\n                also have \"... \\<le> forest_components ?w\"\n                  apply (rule kruskal_exchange_forest_components_inv)\n                  using 21 apply simp\n                  using 15 apply simp\n                  using 1 apply (simp add: arc_top_arc minarc_arc)\n                  apply (simp add: inf.coboundedI1)\n                  using 13 apply simp\n                  using 8 apply simp\n                  apply (simp add: le_infI1)\n                  using 22 by simp\n                finally show \"components g \\<le> forest_components ?w\"\n                  by simp\n              next\n                show \"regular ?w\"\n                  using 3 7 regular_conv_closed by simp\n              qed\n            next\n              have 23: \"?e \\<sqinter> g \\<noteq> bot\"\n                using 1 by (metis kruskal_invariant_def kruskal_spanning_invariant_def comp_inf.semiring.mult_zero_right inf.sup_monoid.add_assoc inf.sup_monoid.add_commute minarc_bot_iff minarc_meet_bot)\n              have \"g \\<sqinter> -h \\<le> (g \\<sqinter> -h)\\<^sup>\\<star>\"\n                using star.circ_increasing by simp\n              also have \"... \\<le> (--(g \\<sqinter> -h))\\<^sup>\\<star>\"\n                using pp_increasing star_isotone by blast\n              also have \"... \\<le> ?F\"\n                using 1 kruskal_invariant_def kruskal_spanning_invariant_def inf.sup_monoid.add_commute spanning_forest_def by simp\n              finally have 24: \"g \\<sqinter> -h \\<le> ?F\"\n                by simp\n              have \"?d \\<le> --g\"\n                using 10 inf.coboundedI1 spanning_forest_def by blast\n              hence \"?d \\<le> --g \\<sqinter> -?F\"\n                using 16 inf.boundedI p_antitone_iff by simp\n              also have \"... = --(g \\<sqinter> -?F)\"\n                by simp\n              also have \"... \\<le> --h\"\n                using 24 p_shunting_swap pp_isotone by fastforce\n              finally have 25: \"?d \\<le> --h\"\n                by simp\n              have \"?d = bot \\<longrightarrow> top = bot\"\n                using 19 by (metis mult_left_zero mult_right_zero)\n              hence \"?d \\<noteq> bot\"\n                using 1 le_bot by auto\n              hence 26: \"?d \\<sqinter> h \\<noteq> bot\"\n                using 25 by (metis inf.absorb_iff2 inf_commute pseudo_complement)\n              have \"sum (?e \\<sqinter> g) = sum (?e \\<sqinter> --h \\<sqinter> g)\"\n                by (simp add: inf.absorb1 minarc_below)\n              also have \"... = sum (?e \\<sqinter> h)\"\n                using 1 by (metis kruskal_invariant_def kruskal_spanning_invariant_def inf.left_commute inf.sup_monoid.add_commute)\n              also have \"... \\<le> sum (?d \\<sqinter> h)\"\n                using 19 26 minarc_min by simp\n              also have \"... = sum (?d \\<sqinter> (--h \\<sqinter> g))\"\n                using 1 kruskal_invariant_def kruskal_spanning_invariant_def inf_commute by simp\n              also have \"... = sum (?d \\<sqinter> g)\"\n                using 25 by (simp add: inf.absorb2 inf_assoc inf_commute)\n              finally have 27: \"sum (?e \\<sqinter> g) \\<le> sum (?d \\<sqinter> g)\"\n                by simp\n              have \"?v \\<sqinter> ?e \\<sqinter> -?d = bot\"\n                using 14 by simp\n              hence \"sum (?w \\<sqinter> g) = sum (?v \\<sqinter> -?d \\<sqinter> g) + sum (?e \\<sqinter> g)\"\n                using sum_disjoint inf_commute inf_assoc by simp\n              also have \"... \\<le> sum (?v \\<sqinter> -?d \\<sqinter> g) + sum (?d \\<sqinter> g)\"\n                using 23 27 sum_plus_right_isotone by simp\n              also have \"... = sum (((?v \\<sqinter> -?d) \\<squnion> ?d) \\<sqinter> g)\"\n                using sum_disjoint inf_le2 pseudo_complement by simp\n              also have \"... = sum ((?v \\<squnion> ?d) \\<sqinter> (-?d \\<squnion> ?d) \\<sqinter> g)\"\n                by (simp add: sup_inf_distrib2)\n              also have \"... = sum ((?v \\<squnion> ?d) \\<sqinter> g)\"\n                using 15 by (metis inf_top_right stone)\n              also have \"... = sum (?v \\<sqinter> g)\"\n                by (simp add: inf.sup_monoid.add_assoc)\n              finally have \"sum (?w \\<sqinter> g) \\<le> sum (?v \\<sqinter> g)\"\n                by simp\n              thus \"\\<forall>u . spanning_forest u g \\<longrightarrow> sum (?w \\<sqinter> g) \\<le> sum (u \\<sqinter> g)\"\n                using 2 11 minimum_spanning_forest_def by auto\n            qed\n          next\n            have \"?f \\<le> f \\<squnion> f\\<^sup>T \\<squnion> ?e\"\n              using conv_dist_inf inf_le1 sup_left_isotone sup_mono by presburger\n            also have \"... \\<le> (?v \\<sqinter> -?d \\<sqinter> -?d\\<^sup>T) \\<squnion> (?v\\<^sup>T \\<sqinter> -?d \\<sqinter> -?d\\<^sup>T) \\<squnion> ?e\"\n              using 17 sup_left_isotone by simp\n            also have \"... \\<le> (?v \\<sqinter> -?d) \\<squnion> (?v\\<^sup>T \\<sqinter> -?d \\<sqinter> -?d\\<^sup>T) \\<squnion> ?e\"\n              using inf.cobounded1 sup_inf_distrib2 by presburger\n            also have \"... = ?w \\<squnion> (?v\\<^sup>T \\<sqinter> -?d \\<sqinter> -?d\\<^sup>T)\"\n              by (simp add: sup_assoc sup_commute)\n            also have \"... \\<le> ?w \\<squnion> (?v\\<^sup>T \\<sqinter> -?d\\<^sup>T)\"\n              using inf.sup_right_isotone inf_assoc sup_right_isotone by simp\n            also have \"... \\<le> ?w \\<squnion> ?w\\<^sup>T\"\n              using conv_complement conv_dist_inf conv_dist_sup sup_right_isotone by simp\n            finally show \"?f \\<le> ?w \\<squnion> ?w\\<^sup>T\"\n              by simp\n          qed\n        qed\n      next\n        show \"?n2 < n\"\n          using 1 kruskal_vc_2 kruskal_invariant_def by auto\n      qed\n    qed\n  next\n    show \"\\<not> ?e \\<le> -?F \\<longrightarrow> kruskal_invariant f g ?h \\<and> ?n2 < n\"\n      using 1 kruskal_vc_2 kruskal_invariant_def by auto\n  qed\nnext\n  fix f g h\n  assume 28: \"kruskal_invariant f g h \\<and> h = bot\"\n  hence 29: \"spanning_forest f g\"\n    using kruskal_invariant_def kruskal_spanning_invariant_def by auto\n  from 28 obtain w where 30: \"minimum_spanning_forest w g \\<and> f \\<le> w \\<squnion> w\\<^sup>T\"\n    using kruskal_invariant_def by auto\n  hence \"w = w \\<sqinter> --g\"\n    by (simp add: inf.absorb1 minimum_spanning_forest_def spanning_forest_def)\n  also have \"... \\<le> w \\<sqinter> components g\"\n    by (metis inf.sup_right_isotone star.circ_increasing)\n  also have \"... \\<le> w \\<sqinter> f\\<^sup>T\\<^sup>\\<star> * f\\<^sup>\\<star>\"\n    using 29 spanning_forest_def inf.sup_right_isotone by simp\n  also have \"... \\<le> f \\<squnion> f\\<^sup>T\"\n    apply (rule cancel_separate_6[where z=w and y=\"w\\<^sup>T\"])\n    using 30 minimum_spanning_forest_def spanning_forest_def apply simp\n    using 30 apply (metis conv_dist_inf conv_dist_sup conv_involutive inf.cobounded2 inf.orderE)\n    using 30 apply (simp add: sup_commute)\n    using 30 minimum_spanning_forest_def spanning_forest_def apply simp\n    using 30 by (metis acyclic_star_below_complement comp_inf.mult_right_isotone inf_p le_bot minimum_spanning_forest_def spanning_forest_def)\n  finally have 31: \"w \\<le> f \\<squnion> f\\<^sup>T\"\n    by simp\n  have \"sum (f \\<sqinter> g) = sum ((w \\<squnion> w\\<^sup>T) \\<sqinter> (f \\<sqinter> g))\"\n    using 30 by (metis inf_absorb2 inf.assoc)\n  also have \"... = sum (w \\<sqinter> (f \\<sqinter> g)) + sum (w\\<^sup>T \\<sqinter> (f \\<sqinter> g))\"\n    using 30 inf.commute acyclic_asymmetric sum_disjoint minimum_spanning_forest_def spanning_forest_def by simp\n  also have \"... = sum (w \\<sqinter> (f \\<sqinter> g)) + sum (w \\<sqinter> (f\\<^sup>T \\<sqinter> g\\<^sup>T))\"\n    by (metis conv_dist_inf conv_involutive sum_conv)\n  also have \"... = sum (f \\<sqinter> (w \\<sqinter> g)) + sum (f\\<^sup>T \\<sqinter> (w \\<sqinter> g))\"\n    using 28 inf.commute inf.assoc kruskal_invariant_def kruskal_spanning_invariant_def by simp\n  also have \"... = sum ((f \\<squnion> f\\<^sup>T) \\<sqinter> (w \\<sqinter> g))\"\n    using 29 acyclic_asymmetric inf.sup_monoid.add_commute sum_disjoint spanning_forest_def by simp\n  also have \"... = sum (w \\<sqinter> g)\"\n    using 31 by (metis inf_absorb2 inf.assoc)\n  finally show \"minimum_spanning_forest f g\"\n    using 29 30 minimum_spanning_forest_def by simp\nqed\n\nsubsection \\<open>Prim's Minimum Spanning Tree Algorithm\\<close>\n\ntext \\<open>\nThe total-correctness proof of Prim's minimum spanning tree algorithm has the same overall structure as the proof of Kruskal's algorithm.\nThe partial-correctness proof is discussed in \\cite{Guttmann2016c,Guttmann2018a}.\n\\<close>\n\nabbreviation \"component g r \\<equiv> r\\<^sup>T * (--g)\\<^sup>\\<star>\"\ndefinition \"spanning_tree t g r \\<equiv> forest t \\<and> t \\<le> (component g r)\\<^sup>T * (component g r) \\<sqinter> --g \\<and> component g r \\<le> r\\<^sup>T * t\\<^sup>\\<star> \\<and> regular t\"\ndefinition \"minimum_spanning_tree t g r \\<equiv> spanning_tree t g r \\<and> (\\<forall>u . spanning_tree u g r \\<longrightarrow> sum (t \\<sqinter> g) \\<le> sum (u \\<sqinter> g))\"\ndefinition \"prim_precondition g r \\<equiv> g = g\\<^sup>T \\<and> injective r \\<and> vector r \\<and> regular r\"\ndefinition \"prim_spanning_invariant t v g r \\<equiv> prim_precondition g r \\<and> v\\<^sup>T = r\\<^sup>T * t\\<^sup>\\<star> \\<and> spanning_tree t (v * v\\<^sup>T \\<sqinter> g) r\"\ndefinition \"prim_invariant t v g r \\<equiv> prim_spanning_invariant t v g r \\<and> (\\<exists>w . minimum_spanning_tree w g r \\<and> t \\<le> w)\"\n\nlemma span_tree_split:\n  assumes \"vector r\"\n    shows \"t \\<le> (component g r)\\<^sup>T * (component g r) \\<sqinter> --g \\<longleftrightarrow> (t \\<le> (component g r)\\<^sup>T \\<and> t \\<le> component g r \\<and> t \\<le> --g)\"\nproof -\n  have \"(component g r)\\<^sup>T * (component g r) = (component g r)\\<^sup>T \\<sqinter> component g r\"\n    by (metis assms conv_involutive covector_mult_closed vector_conv_covector vector_covector)\n  thus ?thesis\n    by simp\nqed\n\nlemma span_tree_component:\n  assumes \"spanning_tree t g r\"\n    shows \"component g r = component t r\"\n  using assms by (simp add: antisym mult_right_isotone star_isotone spanning_tree_def)\n\ntext \\<open>\nWe first show three verification conditions which are used in both correctness proofs.\n\\<close>\n\nlemma prim_vc_1:\n  assumes \"prim_precondition g r\"\n    shows \"prim_spanning_invariant bot r g r\"\nproof (unfold prim_spanning_invariant_def, intro conjI)\n  show \"prim_precondition g r\"\n    using assms by simp\nnext\n  show \"r\\<^sup>T = r\\<^sup>T * bot\\<^sup>\\<star>\"\n    by (simp add: star_absorb)\nnext\n  let ?ss = \"r * r\\<^sup>T \\<sqinter> g\"\n  show \"spanning_tree bot ?ss r\"\n  proof (unfold spanning_tree_def, intro conjI)\n    show \"injective bot\"\n      by simp\n  next\n    show \"acyclic bot\"\n      by simp\n  next\n    show \"bot \\<le> (component ?ss r)\\<^sup>T * (component ?ss r) \\<sqinter> --?ss\"\n      by simp\n  next\n    have \"component ?ss r \\<le> component (r * r\\<^sup>T) r\"\n      by (simp add: mult_right_isotone star_isotone)\n    also have \"... \\<le> r\\<^sup>T * 1\\<^sup>\\<star>\"\n      using assms by (metis inf.eq_iff p_antitone regular_one_closed star_sub_one prim_precondition_def)\n    also have \"... = r\\<^sup>T * bot\\<^sup>\\<star>\"\n      by (simp add: star.circ_zero star_one)\n    finally show \"component ?ss r \\<le> r\\<^sup>T * bot\\<^sup>\\<star>\"\n      .\n  next\n    show \"regular bot\"\n      by simp\n  qed\nqed\n\nlemma prim_vc_2:\n  assumes \"prim_spanning_invariant t v g r\"\n      and \"v * -v\\<^sup>T \\<sqinter> g \\<noteq> bot\"\n      and \"card { x . regular x \\<and> x \\<le> component g r \\<and> x \\<le> -v\\<^sup>T } = n\"\n    shows \"prim_spanning_invariant (t \\<squnion> minarc (v * -v\\<^sup>T \\<sqinter> g)) (v \\<squnion> minarc (v * -v\\<^sup>T \\<sqinter> g)\\<^sup>T * top) g r \\<and> card { x . regular x \\<and> x \\<le> component g r \\<and> x \\<le> -(v \\<squnion> minarc (v * -v\\<^sup>T \\<sqinter> g)\\<^sup>T * top)\\<^sup>T } < n\"\nproof -\n  let ?vcv = \"v * -v\\<^sup>T \\<sqinter> g\"\n  let ?e = \"minarc ?vcv\"\n  let ?t = \"t \\<squnion> ?e\"\n  let ?v = \"v \\<squnion> ?e\\<^sup>T * top\"\n  let ?c = \"component g r\"\n  let ?g = \"--g\"\n  let ?n1 = \"card { x . regular x \\<and> x \\<le> ?c \\<and> x \\<le> -v\\<^sup>T }\"\n  let ?n2 = \"card { x . regular x \\<and> x \\<le> ?c \\<and> x \\<le> -?v\\<^sup>T }\"\n  have 1: \"regular v \\<and> regular (v * v\\<^sup>T) \\<and> regular (?v * ?v\\<^sup>T) \\<and> regular (top * ?e)\"\n    using assms(1) by (metis prim_spanning_invariant_def spanning_tree_def prim_precondition_def regular_conv_closed regular_closed_star regular_mult_closed conv_involutive regular_closed_top regular_closed_sup minarc_regular)\n  hence 2: \"t \\<le> v * v\\<^sup>T \\<sqinter> ?g\"\n    using assms(1) by (metis prim_spanning_invariant_def spanning_tree_def inf_pp_commute inf.boundedE)\n  hence 3: \"t \\<le> v * v\\<^sup>T\"\n    by simp\n  have 4: \"t \\<le> ?g\"\n    using 2 by simp\n  have 5: \"?e \\<le> v * -v\\<^sup>T \\<sqinter> ?g\"\n    using 1 by (metis minarc_below pp_dist_inf regular_mult_closed regular_closed_p)\n  hence 6: \"?e \\<le> v * -v\\<^sup>T\"\n    by simp\n  have 7: \"vector v\"\n    using assms(1) prim_spanning_invariant_def prim_precondition_def by (simp add: covector_mult_closed vector_conv_covector)\n  hence 8: \"?e \\<le> v\"\n    using 6 by (metis conv_complement inf.boundedE vector_complement_closed vector_covector)\n  have 9: \"?e * t = bot\"\n    using 3 6 7 et(1) by blast\n  have 10: \"?e * t\\<^sup>T = bot\"\n    using 3 6 7 et(2) by simp\n  have 11: \"arc ?e\"\n    using assms(2) minarc_arc by simp\n  have \"r\\<^sup>T \\<le> r\\<^sup>T * t\\<^sup>\\<star>\"\n    by (metis mult_right_isotone order_refl semiring.mult_not_zero star.circ_separate_mult_1 star_absorb)\n  hence 12: \"r\\<^sup>T \\<le> v\\<^sup>T\"\n    using assms(1) by (simp add: prim_spanning_invariant_def)\n  have 13: \"vector r \\<and> injective r \\<and> v\\<^sup>T = r\\<^sup>T * t\\<^sup>\\<star>\"\n    using assms(1) prim_spanning_invariant_def prim_precondition_def minimum_spanning_tree_def spanning_tree_def reachable_restrict by simp\n  have \"g = g\\<^sup>T\"\n    using assms(1) prim_invariant_def prim_spanning_invariant_def prim_precondition_def by simp\n  hence 14: \"?g\\<^sup>T = ?g\"\n    using conv_complement by simp\n  show \"prim_spanning_invariant ?t ?v g r \\<and> ?n2 < n\"\n  proof (rule conjI)\n    show \"prim_spanning_invariant ?t ?v g r\"\n    proof (unfold prim_spanning_invariant_def, intro conjI)\n      show \"prim_precondition g r\"\n        using assms(1) prim_spanning_invariant_def by simp\n    next\n      show \"?v\\<^sup>T = r\\<^sup>T * ?t\\<^sup>\\<star>\"\n        using assms(1) 6 7 9 by (simp add: reachable_inv prim_spanning_invariant_def prim_precondition_def spanning_tree_def)\n    next\n      let ?G = \"?v * ?v\\<^sup>T \\<sqinter> g\"\n      show \"spanning_tree ?t ?G r\"\n      proof (unfold spanning_tree_def, intro conjI)\n        show \"injective ?t\"\n          using assms(1) 10 11 by (simp add: injective_inv prim_spanning_invariant_def spanning_tree_def)\n      next\n        show \"acyclic ?t\"\n          using assms(1) 3 6 7 acyclic_inv prim_spanning_invariant_def spanning_tree_def by simp\n      next\n        show \"?t \\<le> (component ?G r)\\<^sup>T * (component ?G r) \\<sqinter> --?G\"\n          using 1 2 5 7 13 prim_subgraph_inv inf_pp_commute mst_subgraph_inv_2 by auto\n      next\n        show \"component (?v * ?v\\<^sup>T \\<sqinter> g) r \\<le> r\\<^sup>T * ?t\\<^sup>\\<star>\"\n        proof -\n          have 15: \"r\\<^sup>T * (v * v\\<^sup>T \\<sqinter> ?g)\\<^sup>\\<star> \\<le> r\\<^sup>T * t\\<^sup>\\<star>\"\n            using assms(1) 1 by (metis prim_spanning_invariant_def spanning_tree_def inf_pp_commute)\n          have \"component (?v * ?v\\<^sup>T \\<sqinter> g) r = r\\<^sup>T * (?v * ?v\\<^sup>T \\<sqinter> ?g)\\<^sup>\\<star>\"\n            using 1 by simp\n          also have \"... \\<le> r\\<^sup>T * ?t\\<^sup>\\<star>\"\n            using 2 6 7 11 12 13 14 15 by (metis span_inv)\n          finally show ?thesis\n            .\n        qed\n      next\n        show \"regular ?t\"\n          using assms(1) by (metis prim_spanning_invariant_def spanning_tree_def regular_closed_sup minarc_regular)\n      qed\n    qed\n  next\n    have 16: \"top * ?e \\<le> ?c\"\n    proof -\n      have \"top * ?e = top * ?e\\<^sup>T * ?e\"\n        using 11 by (metis arc_top_edge mult_assoc)\n      also have \"... \\<le> v\\<^sup>T * ?e\"\n        using 7 8 by (metis conv_dist_comp conv_isotone mult_left_isotone symmetric_top_closed)\n      also have \"... \\<le> v\\<^sup>T * ?g\"\n        using 5 mult_right_isotone by auto\n      also have \"... = r\\<^sup>T * t\\<^sup>\\<star> * ?g\"\n        using 13 by simp\n      also have \"... \\<le> r\\<^sup>T * ?g\\<^sup>\\<star> * ?g\"\n        using 4 by (simp add: mult_left_isotone mult_right_isotone star_isotone)\n      also have \"... \\<le> ?c\"\n        by (simp add: comp_associative mult_right_isotone star.right_plus_below_circ)\n      finally show ?thesis\n        by simp\n    qed\n    have 17: \"top * ?e \\<le> -v\\<^sup>T\"\n      using 6 7 by (simp add: schroeder_4_p vTeT)\n    have 18: \"\\<not> top * ?e \\<le> -(top * ?e)\"\n      by (metis assms(2) inf.orderE minarc_bot_iff conv_complement_sub_inf inf_p inf_top.left_neutral p_bot symmetric_top_closed vector_top_closed)\n    have 19: \"-?v\\<^sup>T = -v\\<^sup>T \\<sqinter> -(top * ?e)\"\n      by (simp add: conv_dist_comp conv_dist_sup)\n    hence 20: \"\\<not> top * ?e \\<le> -?v\\<^sup>T\"\n      using 18 by simp\n    have \"?n2 < ?n1\"\n      apply (rule psubset_card_mono)\n      using finite_regular apply simp\n      using 1 16 17 19 20 by auto\n    thus \"?n2 < n\"\n      using assms(3) by simp\n  qed\nqed\n\nlemma prim_vc_3:\n  assumes \"prim_spanning_invariant t v g r\"\n      and \"v * -v\\<^sup>T \\<sqinter> g = bot\"\n    shows \"spanning_tree t g r\"\nproof -\n  let ?g = \"--g\"\n  have 1: \"regular v \\<and> regular (v * v\\<^sup>T)\"\n    using assms(1) by (metis prim_spanning_invariant_def spanning_tree_def prim_precondition_def regular_conv_closed regular_closed_star regular_mult_closed conv_involutive)\n  have 2: \"v * -v\\<^sup>T \\<sqinter> ?g = bot\"\n    using assms(2) pp_inf_bot_iff pp_pp_inf_bot_iff by simp\n  have 3: \"v\\<^sup>T = r\\<^sup>T * t\\<^sup>\\<star> \\<and> vector v\"\n    using assms(1) by (simp add: covector_mult_closed prim_invariant_def prim_spanning_invariant_def vector_conv_covector prim_precondition_def)\n  have 4: \"t \\<le> v * v\\<^sup>T \\<sqinter> ?g\"\n    using assms(1) 1 by (metis prim_spanning_invariant_def inf_pp_commute spanning_tree_def inf.boundedE)\n  have \"r\\<^sup>T * (v * v\\<^sup>T \\<sqinter> ?g)\\<^sup>\\<star> \\<le> r\\<^sup>T * t\\<^sup>\\<star>\"\n    using assms(1) 1 by (metis prim_spanning_invariant_def inf_pp_commute spanning_tree_def)\n  hence 5: \"component g r = v\\<^sup>T\"\n    using 1 2 3 4 by (metis span_post)\n  have \"regular (v * v\\<^sup>T)\"\n    using assms(1) by (metis prim_spanning_invariant_def spanning_tree_def prim_precondition_def regular_conv_closed regular_closed_star regular_mult_closed conv_involutive)\n  hence 6: \"t \\<le> v * v\\<^sup>T \\<sqinter> ?g\"\n    by (metis assms(1) prim_spanning_invariant_def spanning_tree_def inf_pp_commute inf.boundedE)\n  show \"spanning_tree t g r\"\n    apply (unfold spanning_tree_def, intro conjI)\n    using assms(1) prim_spanning_invariant_def spanning_tree_def apply simp\n    using assms(1) prim_spanning_invariant_def spanning_tree_def apply simp\n    using 5 6 apply simp\n    using assms(1) 5 prim_spanning_invariant_def apply simp\n    using assms(1) prim_spanning_invariant_def spanning_tree_def by simp\nqed\n\ntext \\<open>\nThe following result shows that Prim's algorithm terminates and constructs a spanning tree.\nWe cannot yet show that this is a minimum spanning tree.\n\\<close>\n\ntheorem prim_spanning:\n  \"VARS t v e\n  [ prim_precondition g r ]\n  t := bot;\n  v := r;\n  WHILE v * -v\\<^sup>T \\<sqinter> g \\<noteq> bot\n    INV { prim_spanning_invariant t v g r }\n    VAR { card { x . regular x \\<and> x \\<le> component g r \\<sqinter> -v\\<^sup>T } }\n     DO e := minarc (v * -v\\<^sup>T \\<sqinter> g);\n        t := t \\<squnion> e;\n        v := v \\<squnion> e\\<^sup>T * top\n     OD\n  [ spanning_tree t g r ]\"\n  apply vcg_tc_simp\n  apply (simp add: prim_vc_1)\n  using prim_vc_2 apply blast\n  using prim_vc_3 by auto\n\ntext \\<open>\nBecause we have shown total correctness, we conclude that a spanning tree exists.\n\\<close>\n\nlemma prim_exists_spanning:\n  \"prim_precondition g r \\<Longrightarrow> \\<exists>t . spanning_tree t g r\"\n  using tc_extract_function prim_spanning by blast\n\ntext \\<open>\nThis implies that a minimum spanning tree exists, which is used in the subsequent correctness proof.\n\\<close>\n\n\n\ntext \\<open>\nPrim's minimum spanning tree algorithm terminates and is correct.\nThis is the same algorithm that is used in the previous correctness proof, with the same precondition and variant, but with a different invariant and postcondition.\n\\<close>\n\ntheorem prim:\n  \"VARS t v e\n  [ prim_precondition g r \\<and> (\\<exists>w . minimum_spanning_tree w g r) ]\n  t := bot;\n  v := r;\n  WHILE v * -v\\<^sup>T \\<sqinter> g \\<noteq> bot\n    INV { prim_invariant t v g r }\n    VAR { card { x . regular x \\<and> x \\<le> component g r \\<sqinter> -v\\<^sup>T } }\n     DO e := minarc (v * -v\\<^sup>T \\<sqinter> g);\n        t := t \\<squnion> e;\n        v := v \\<squnion> e\\<^sup>T * top\n     OD\n  [ minimum_spanning_tree t g r ]\"\nproof vcg_tc_simp\n  assume \"prim_precondition g r \\<and> (\\<exists>w . minimum_spanning_tree w g r)\"\n  thus \"prim_invariant bot r g r\"\n    using prim_invariant_def prim_vc_1 by simp\nnext\n  fix t v n\n  let ?vcv = \"v * -v\\<^sup>T \\<sqinter> g\"\n  let ?vv = \"v * v\\<^sup>T \\<sqinter> g\"\n  let ?e = \"minarc ?vcv\"\n  let ?t = \"t \\<squnion> ?e\"\n  let ?v = \"v \\<squnion> ?e\\<^sup>T * top\"\n  let ?c = \"component g r\"\n  let ?g = \"--g\"\n  let ?n1 = \"card { x . regular x \\<and> x \\<le> ?c \\<and> x \\<le> -v\\<^sup>T }\"\n  let ?n2 = \"card { x . regular x \\<and> x \\<le> ?c \\<and> x \\<le> -?v\\<^sup>T }\"\n  assume 1: \"prim_invariant t v g r \\<and> ?vcv \\<noteq> bot \\<and> ?n1 = n\"\n  hence 2: \"regular v \\<and> regular (v * v\\<^sup>T)\"\n    by (metis (no_types, hide_lams) prim_invariant_def prim_spanning_invariant_def spanning_tree_def prim_precondition_def regular_conv_closed regular_closed_star regular_mult_closed conv_involutive)\n  have 3: \"t \\<le> v * v\\<^sup>T \\<sqinter> ?g\"\n    using 1 2 by (metis (no_types, hide_lams) prim_invariant_def prim_spanning_invariant_def spanning_tree_def inf_pp_commute inf.boundedE)\n  hence 4: \"t \\<le> v * v\\<^sup>T\"\n    by simp\n  have 5: \"t \\<le> ?g\"\n    using 3 by simp\n  have 6: \"?e \\<le> v * -v\\<^sup>T \\<sqinter> ?g\"\n    using 2 by (metis minarc_below pp_dist_inf regular_mult_closed regular_closed_p)\n  hence 7: \"?e \\<le> v * -v\\<^sup>T\"\n    by simp\n  have 8: \"vector v\"\n    using 1 prim_invariant_def prim_spanning_invariant_def prim_precondition_def by (simp add: covector_mult_closed vector_conv_covector)\n  have 9: \"arc ?e\"\n    using 1 minarc_arc by simp\n  from 1 obtain w where 10: \"minimum_spanning_tree w g r \\<and> t \\<le> w\"\n    by (metis prim_invariant_def)\n  hence 11: \"vector r \\<and> injective r \\<and> v\\<^sup>T = r\\<^sup>T * t\\<^sup>\\<star> \\<and> forest w \\<and> t \\<le> w \\<and> w \\<le> ?c\\<^sup>T * ?c \\<sqinter> ?g \\<and> r\\<^sup>T * (?c\\<^sup>T * ?c \\<sqinter> ?g)\\<^sup>\\<star> \\<le> r\\<^sup>T * w\\<^sup>\\<star>\"\n    using 1 2 prim_invariant_def prim_spanning_invariant_def prim_precondition_def minimum_spanning_tree_def spanning_tree_def reachable_restrict by simp\n  hence 12: \"w * v \\<le> v\"\n    using predecessors_reachable reachable_restrict by auto\n  have 13: \"g = g\\<^sup>T\"\n    using 1 prim_invariant_def prim_spanning_invariant_def prim_precondition_def by simp\n  hence 14: \"?g\\<^sup>T = ?g\"\n    using conv_complement by simp\n  show \"prim_invariant ?t ?v g r \\<and> ?n2 < n\"\n  proof (unfold prim_invariant_def, intro conjI)\n    show \"prim_spanning_invariant ?t ?v g r\"\n      using 1 prim_invariant_def prim_vc_2 by blast\n  next\n    show \"\\<exists>w . minimum_spanning_tree w g r \\<and> ?t \\<le> w\"\n    proof\n      let ?f = \"w \\<sqinter> v * -v\\<^sup>T \\<sqinter> top * ?e * w\\<^sup>T\\<^sup>\\<star>\"\n      let ?p = \"w \\<sqinter> -v * -v\\<^sup>T \\<sqinter> top * ?e * w\\<^sup>T\\<^sup>\\<star>\"\n      let ?fp = \"w \\<sqinter> -v\\<^sup>T \\<sqinter> top * ?e * w\\<^sup>T\\<^sup>\\<star>\"\n      let ?w = \"(w \\<sqinter> -?fp) \\<squnion> ?p\\<^sup>T \\<squnion> ?e\"\n      have 15: \"regular ?f \\<and> regular ?fp \\<and> regular ?w\"\n        using 2 10 by (metis regular_conv_closed regular_closed_star regular_mult_closed regular_closed_top regular_closed_inf regular_closed_sup minarc_regular minimum_spanning_tree_def spanning_tree_def)\n      show \"minimum_spanning_tree ?w g r \\<and> ?t \\<le> ?w\"\n      proof (intro conjI)\n        show \"minimum_spanning_tree ?w g r\"\n        proof (unfold minimum_spanning_tree_def, intro conjI)\n          show \"spanning_tree ?w g r\"\n          proof (unfold spanning_tree_def, intro conjI)\n            show \"injective ?w\"\n              using 7 8 9 11 exchange_injective by blast\n          next\n            show \"acyclic ?w\"\n              using 7 8 11 12 exchange_acyclic by blast\n          next\n            show \"?w \\<le> ?c\\<^sup>T * ?c \\<sqinter> --g\"\n            proof -\n              have 16: \"w \\<sqinter> -?fp \\<le> ?c\\<^sup>T * ?c \\<sqinter> --g\"\n                using 10 by (simp add: le_infI1 minimum_spanning_tree_def spanning_tree_def)\n              have \"?p\\<^sup>T \\<le> w\\<^sup>T\"\n                by (simp add: conv_isotone inf.sup_monoid.add_assoc)\n              also have \"... \\<le> (?c\\<^sup>T * ?c \\<sqinter> --g)\\<^sup>T\"\n                using 11 conv_order by simp\n              also have \"... = ?c\\<^sup>T * ?c \\<sqinter> --g\"\n                using 2 14 conv_dist_comp conv_dist_inf by simp\n              finally have 17: \"?p\\<^sup>T \\<le> ?c\\<^sup>T * ?c \\<sqinter> --g\"\n                .\n              have \"?e \\<le> ?c\\<^sup>T * ?c \\<sqinter> ?g\"\n                using 5 6 11 mst_subgraph_inv by auto\n              thus ?thesis\n                using 16 17 by simp\n            qed\n          next\n            show \"?c \\<le> r\\<^sup>T * ?w\\<^sup>\\<star>\"\n            proof -\n              have \"?c \\<le> r\\<^sup>T * w\\<^sup>\\<star>\"\n                using 10 minimum_spanning_tree_def spanning_tree_def by simp\n              also have \"... \\<le> r\\<^sup>T * ?w\\<^sup>\\<star>\"\n                using 4 7 8 10 11 12 15 by (metis mst_reachable_inv)\n              finally show ?thesis\n                .\n            qed\n          next\n            show \"regular ?w\"\n              using 15 by simp\n          qed\n        next\n          have 18: \"?f \\<squnion> ?p = ?fp\"\n            using 2 8 epm_1 by fastforce\n          have \"arc (w \\<sqinter> --v * -v\\<^sup>T \\<sqinter> top * ?e * w\\<^sup>T\\<^sup>\\<star>)\"\n            using 5 6 8 9 11 12 reachable_restrict arc_edge by auto\n          hence 19: \"arc ?f\"\n            using 2 by simp\n          hence \"?f = bot \\<longrightarrow> top = bot\"\n            by (metis mult_left_zero mult_right_zero)\n          hence \"?f \\<noteq> bot\"\n            using 1 le_bot by auto\n          hence \"?f \\<sqinter> v * -v\\<^sup>T \\<sqinter> ?g \\<noteq> bot\"\n            using 2 11 by (simp add: inf.absorb1 le_infI1)\n          hence \"g \\<sqinter> (?f \\<sqinter> v * -v\\<^sup>T) \\<noteq> bot\"\n            using inf_commute pp_inf_bot_iff by simp\n          hence 20: \"?f \\<sqinter> ?vcv \\<noteq> bot\"\n            by (simp add: inf_assoc inf_commute)\n          hence 21: \"?f \\<sqinter> g = ?f \\<sqinter> ?vcv\"\n            using 2 by (simp add: inf_assoc inf_commute inf_left_commute)\n          have 22: \"?e \\<sqinter> g = minarc ?vcv \\<sqinter> ?vcv\"\n            using 7 by (simp add: inf.absorb2 inf.assoc inf.commute)\n          hence 23: \"sum (?e \\<sqinter> g) \\<le> sum (?f \\<sqinter> g)\"\n            using 15 19 20 21 by (simp add: minarc_min)\n          have \"?e \\<noteq> bot\"\n            using 20 comp_inf.semiring.mult_not_zero semiring.mult_not_zero by blast\n          hence 24: \"?e \\<sqinter> g \\<noteq> bot\"\n            using 22 minarc_meet_bot by auto\n          have \"sum (?w \\<sqinter> g) = sum (w \\<sqinter> -?fp \\<sqinter> g) + sum (?p\\<^sup>T \\<sqinter> g) + sum (?e \\<sqinter> g)\"\n            using 7 8 10 by (metis sum_disjoint_3 epm_8 epm_9 epm_10 minimum_spanning_tree_def spanning_tree_def)\n          also have \"... = sum (((w \\<sqinter> -?fp) \\<squnion> ?p\\<^sup>T) \\<sqinter> g) + sum (?e \\<sqinter> g)\"\n            using 11 by (metis epm_8 sum_disjoint)\n          also have \"... \\<le> sum (((w \\<sqinter> -?fp) \\<squnion> ?p\\<^sup>T) \\<sqinter> g) + sum (?f \\<sqinter> g)\"\n            using 23 24 by (simp add: sum_plus_right_isotone)\n          also have \"... = sum (w \\<sqinter> -?fp \\<sqinter> g) + sum (?p\\<^sup>T \\<sqinter> g) + sum (?f \\<sqinter> g)\"\n            using 11 by (metis epm_8 sum_disjoint)\n          also have \"... = sum (w \\<sqinter> -?fp \\<sqinter> g) + sum (?p \\<sqinter> g) + sum (?f \\<sqinter> g)\"\n            using 13 sum_symmetric by auto\n          also have \"... = sum (((w \\<sqinter> -?fp) \\<squnion> ?p \\<squnion> ?f) \\<sqinter> g)\"\n            using 2 8 by (metis sum_disjoint_3 epm_11 epm_12 epm_13)\n          also have \"... = sum (w \\<sqinter> g)\"\n            using 2 8 15 18 epm_2 by force\n          finally have \"sum (?w \\<sqinter> g) \\<le> sum (w \\<sqinter> g)\"\n            .\n          thus \"\\<forall>u . spanning_tree u g r \\<longrightarrow> sum (?w \\<sqinter> g) \\<le> sum (u \\<sqinter> g)\"\n            using 10 order_lesseq_imp minimum_spanning_tree_def by auto\n        qed\n      next\n        show \"?t \\<le> ?w\"\n          using 4 8 10 mst_extends_new_tree by simp\n      qed\n    qed\n  next\n    show \"?n2 < n\"\n      using 1 prim_invariant_def prim_vc_2 by auto\n  qed\nnext\n  fix t v\n  let ?g = \"--g\"\n  assume 25: \"prim_invariant t v g r \\<and> v * -v\\<^sup>T \\<sqinter> g = bot\"\n  hence 26: \"regular v\"\n    by (metis prim_invariant_def prim_spanning_invariant_def spanning_tree_def prim_precondition_def regular_conv_closed regular_closed_star regular_mult_closed conv_involutive)\n  from 25 obtain w where 27: \"minimum_spanning_tree w g r \\<and> t \\<le> w\"\n    by (metis prim_invariant_def)\n  have \"spanning_tree t g r\"\n    using 25 prim_invariant_def prim_vc_3 by blast\n  hence \"component g r = v\\<^sup>T\"\n    by (metis 25 prim_invariant_def span_tree_component prim_spanning_invariant_def spanning_tree_def)\n  hence 28: \"w \\<le> v * v\\<^sup>T\"\n    using 26 27 by (simp add: minimum_spanning_tree_def spanning_tree_def inf_pp_commute)\n  have \"vector r \\<and> injective r \\<and> forest w\"\n    using 25 27 by (simp add: prim_invariant_def prim_spanning_invariant_def prim_precondition_def minimum_spanning_tree_def spanning_tree_def)\n  hence \"w = t\"\n    using 25 27 28 prim_invariant_def prim_spanning_invariant_def mst_post by blast\n  thus \"minimum_spanning_tree t g r\"\n    using 27 by simp\nqed\n\nend\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/Aggregation_Algebras/Minimum_Spanning_Trees.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.872347368040789, "lm_q2_score": 0.803173791645582, "lm_q1q2_score": 0.7006465432213645}}
{"text": "theory Horner_Eval\nimports \"Intervals\"\nbegin\n\n(* Function and lemmas for evaluating polynomials via the horner scheme.\n   Because interval multiplication is not distributive, interval polynomials\n   expressed as a sum of monomials are not equivalent to their respective horner form.\n   The functions and lemmas in this theory can be used to express interval\n   polynomials in horner form and prove facts about them. *)\nfun horner_eval'\nwhere \"horner_eval' f x v 0 = v\"\n    | \"horner_eval' f x v (Suc i) = horner_eval' f x (f i + x * v) i\"\n    \nfun horner_eval\nwhere \"horner_eval f x n = horner_eval' f x 0 n\"\n\nlemmas [simp del] = horner_eval.simps\n\nlemma horner_eval_cong:\nassumes \"\\<And>i. i < n \\<Longrightarrow> f i = g i\"\nassumes \"x = y\"\nassumes \"n = m\"\nshows \"horner_eval f x n = horner_eval g y m\"\nproof-\n  {\n    fix v have \"horner_eval' f x v n = horner_eval' g x v n\"\n      using assms(1) by (induction n arbitrary: v, simp_all)\n  }\n  thus ?thesis\n    by (simp add: assms(2,3) horner_eval.simps)\nqed\n    \nlemma horner_eval_eq_setsum:\nfixes x::\"'a::linordered_idom\"\nshows \"horner_eval f x n = (\\<Sum>i<n. f i * x^i)\"\nproof-\n  {\n    fix v have \"horner_eval' f x v n = (\\<Sum>i<n. f i * x^i) + v*x^n\"\n      by (induction n arbitrary: v, simp_all add: distrib_left mult.commute)\n  }\n  thus ?thesis by (simp add: horner_eval.simps)\nqed\n\nlemma horner_eval_Suc[simp]:\nfixes x::\"'a::linordered_idom\"\nshows \"horner_eval f x (Suc n) = horner_eval f x n + (f n) * x^n\"\nunfolding horner_eval_eq_setsum\nby simp\n\nlemma horner_eval_Suc'[simp]:\nfixes x::\"'a::{comm_monoid_add, times}\"\nshows \"horner_eval f x (Suc n) = f 0 + x * (horner_eval (\\<lambda>i. f (Suc i)) x n)\"\nproof-\n  {\n    fix v have \"horner_eval' f x v (Suc n) = f 0 + x * horner_eval' (\\<lambda>i. f (Suc i)) x v n\"\n    by (induction n arbitrary: v, simp_all)\n  }\n  thus ?thesis by (simp add: horner_eval.simps)\nqed\n\nlemma horner_eval_0[simp]:\nshows \"horner_eval f x 0 = 0\"\nby (simp add: horner_eval.simps)\n\nlemma horner_eval_interval:\nfixes x::\"'a::linordered_idom\"\nassumes \"\\<And>i. i < n \\<Longrightarrow> f i \\<in> set_of (g i)\"\nassumes \"x \\<in> set_of I\"\nshows \"horner_eval f x n \\<in> set_of (horner_eval g I n)\"\nproof-\n  {\n    fix v::'a and V::\"'a interval\"\n    assume \"v \\<in> set_of V\"\n    hence \"horner_eval' f x v n \\<in> set_of (horner_eval' g I V n)\"\n      using assms\n      apply(induction n arbitrary: v V)\n      apply(simp)\n      proof(goal_cases Suc)\n        case (Suc n v V)\n        show ?case\n          apply(simp, rule Suc(1)[OF set_of_add_mono[OF _ set_of_mult_mono]])\n          using Suc(2,3,4)\n          by (simp_all)\n      qed\n  }\n  thus ?thesis by (simp add: horner_eval.simps zero_interval_def)\nqed\n\nlemma horner_eval_interval_subset:\nfixes I::\"real interval\"\nassumes \"set_of I \\<subseteq> set_of J\"\nshows \"set_of (horner_eval f I n) \\<subseteq> set_of (horner_eval f J n)\"\nusing assms\nby (induction n arbitrary: f, simp_all add: set_of_add_inc_right set_of_mul_inc)\n\nend\n", "meta": {"author": "ctraut", "repo": "Taylor-Models-Isabelle", "sha": "371c28301f16209228defdc62a066532f8be6e6b", "save_path": "github-repos/isabelle/ctraut-Taylor-Models-Isabelle", "path": "github-repos/isabelle/ctraut-Taylor-Models-Isabelle/Taylor-Models-Isabelle-371c28301f16209228defdc62a066532f8be6e6b/Horner_Eval.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8670357701094303, "lm_q2_score": 0.8080672181749422, "lm_q1q2_score": 0.7006231828104961}}
{"text": " (* Author:     Johannes Hoelzl, TU Muenchen\n   Coercions removed by Dmitriy Traytel *)\n\nsection \\<open>Prove Real Valued Inequalities by Computation\\<close>\n\ntheory Approximation\nimports\n  Complex_Main\n  \"~~/src/HOL/Library/Float\"\n  Dense_Linear_Order\n  \"~~/src/HOL/Library/Code_Target_Numeral\"\nkeywords \"approximate\" :: diag\nbegin\n\ndeclare powr_numeral [simp]\ndeclare powr_neg_one [simp]\ndeclare powr_neg_numeral [simp]\n\nsection \"Horner Scheme\"\n\nsubsection \\<open>Define auxiliary helper \\<open>horner\\<close> function\\<close>\n\nprimrec horner :: \"(nat \\<Rightarrow> nat) \\<Rightarrow> (nat \\<Rightarrow> nat \\<Rightarrow> nat) \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> real \\<Rightarrow> real\" where\n\"horner F G 0 i k x       = 0\" |\n\"horner F G (Suc n) i k x = 1 / k - x * horner F G n (F i) (G i k) x\"\n\nlemma horner_schema':\n  fixes x :: real and a :: \"nat \\<Rightarrow> real\"\n  shows \"a 0 - x * (\\<Sum> i=0..<n. (-1)^i * a (Suc i) * x^i) = (\\<Sum> i=0..<Suc n. (-1)^i * a i * x^i)\"\nproof -\n  have shift_pow: \"\\<And>i. - (x * ((-1)^i * a (Suc i) * x ^ i)) = (-1)^(Suc i) * a (Suc i) * x ^ (Suc i)\"\n    by auto\n  show ?thesis\n    unfolding sum_distrib_left shift_pow uminus_add_conv_diff [symmetric] sum_negf[symmetric]\n    sum_head_upt_Suc[OF zero_less_Suc]\n    sum.reindex[OF inj_Suc, unfolded comp_def, symmetric, of \"\\<lambda> n. (-1)^n  *a n * x^n\"] by auto\nqed\n\nlemma horner_schema:\n  fixes f :: \"nat \\<Rightarrow> nat\" and G :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\" and F :: \"nat \\<Rightarrow> nat\"\n  assumes f_Suc: \"\\<And>n. f (Suc n) = G ((F ^^ n) s) (f n)\"\n  shows \"horner F G n ((F ^^ j') s) (f j') x = (\\<Sum> j = 0..< n. (- 1) ^ j * (1 / (f (j' + j))) * x ^ j)\"\nproof (induct n arbitrary: j')\n  case 0\n  then show ?case by auto\nnext\n  case (Suc n)\n  show ?case unfolding horner.simps Suc[where j'=\"Suc j'\", unfolded funpow.simps comp_def f_Suc]\n    using horner_schema'[of \"\\<lambda> j. 1 / (f (j' + j))\"] by auto\nqed\n\nlemma horner_bounds':\n  fixes lb :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> float \\<Rightarrow> float\" and ub :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> float \\<Rightarrow> float\"\n  assumes \"0 \\<le> real_of_float x\" and f_Suc: \"\\<And>n. f (Suc n) = G ((F ^^ n) s) (f n)\"\n    and lb_0: \"\\<And> i k x. lb 0 i k x = 0\"\n    and lb_Suc: \"\\<And> n i k x. lb (Suc n) i k x = float_plus_down prec\n        (lapprox_rat prec 1 k)\n        (- float_round_up prec (x * (ub n (F i) (G i k) x)))\"\n    and ub_0: \"\\<And> i k x. ub 0 i k x = 0\"\n    and ub_Suc: \"\\<And> n i k x. ub (Suc n) i k x = float_plus_up prec\n        (rapprox_rat prec 1 k)\n        (- float_round_down prec (x * (lb n (F i) (G i k) x)))\"\n  shows \"(lb n ((F ^^ j') s) (f j') x) \\<le> horner F G n ((F ^^ j') s) (f j') x \\<and>\n         horner F G n ((F ^^ j') s) (f j') x \\<le> (ub n ((F ^^ j') s) (f j') x)\"\n  (is \"?lb n j' \\<le> ?horner n j' \\<and> ?horner n j' \\<le> ?ub n j'\")\nproof (induct n arbitrary: j')\n  case 0\n  thus ?case unfolding lb_0 ub_0 horner.simps by auto\nnext\n  case (Suc n)\n  thus ?case using lapprox_rat[of prec 1 \"f j'\"] using rapprox_rat[of 1 \"f j'\" prec]\n    Suc[where j'=\"Suc j'\"] \\<open>0 \\<le> real_of_float x\\<close>\n    by (auto intro!: add_mono mult_left_mono float_round_down_le float_round_up_le\n      order_trans[OF add_mono[OF _ float_plus_down_le]]\n      order_trans[OF _ add_mono[OF _ float_plus_up_le]]\n      simp add: lb_Suc ub_Suc field_simps f_Suc)\nqed\n\nsubsection \"Theorems for floating point functions implementing the horner scheme\"\n\ntext \\<open>\n\nHere @{term_type \"f :: nat \\<Rightarrow> nat\"} is the sequence defining the Taylor series, the coefficients are\nall alternating and reciprocs. We use @{term G} and @{term F} to describe the computation of @{term f}.\n\n\\<close>\n\nlemma horner_bounds:\n  fixes F :: \"nat \\<Rightarrow> nat\" and G :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\"\n  assumes \"0 \\<le> real_of_float x\" and f_Suc: \"\\<And>n. f (Suc n) = G ((F ^^ n) s) (f n)\"\n    and lb_0: \"\\<And> i k x. lb 0 i k x = 0\"\n    and lb_Suc: \"\\<And> n i k x. lb (Suc n) i k x = float_plus_down prec\n        (lapprox_rat prec 1 k)\n        (- float_round_up prec (x * (ub n (F i) (G i k) x)))\"\n    and ub_0: \"\\<And> i k x. ub 0 i k x = 0\"\n    and ub_Suc: \"\\<And> n i k x. ub (Suc n) i k x = float_plus_up prec\n        (rapprox_rat prec 1 k)\n        (- float_round_down prec (x * (lb n (F i) (G i k) x)))\"\n  shows \"(lb n ((F ^^ j') s) (f j') x) \\<le> (\\<Sum>j=0..<n. (- 1) ^ j * (1 / (f (j' + j))) * (x ^ j))\"\n      (is \"?lb\")\n    and \"(\\<Sum>j=0..<n. (- 1) ^ j * (1 / (f (j' + j))) * (x ^ j)) \\<le> (ub n ((F ^^ j') s) (f j') x)\"\n      (is \"?ub\")\nproof -\n  have \"?lb  \\<and> ?ub\"\n    using horner_bounds'[where lb=lb, OF \\<open>0 \\<le> real_of_float x\\<close> f_Suc lb_0 lb_Suc ub_0 ub_Suc]\n    unfolding horner_schema[where f=f, OF f_Suc] by simp\n  thus \"?lb\" and \"?ub\" by auto\nqed\n\nlemma horner_bounds_nonpos:\n  fixes F :: \"nat \\<Rightarrow> nat\" and G :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\"\n  assumes \"real_of_float x \\<le> 0\" and f_Suc: \"\\<And>n. f (Suc n) = G ((F ^^ n) s) (f n)\"\n    and lb_0: \"\\<And> i k x. lb 0 i k x = 0\"\n    and lb_Suc: \"\\<And> n i k x. lb (Suc n) i k x = float_plus_down prec\n        (lapprox_rat prec 1 k)\n        (float_round_down prec (x * (ub n (F i) (G i k) x)))\"\n    and ub_0: \"\\<And> i k x. ub 0 i k x = 0\"\n    and ub_Suc: \"\\<And> n i k x. ub (Suc n) i k x = float_plus_up prec\n        (rapprox_rat prec 1 k)\n        (float_round_up prec (x * (lb n (F i) (G i k) x)))\"\n  shows \"(lb n ((F ^^ j') s) (f j') x) \\<le> (\\<Sum>j=0..<n. (1 / (f (j' + j))) * real_of_float x ^ j)\" (is \"?lb\")\n    and \"(\\<Sum>j=0..<n. (1 / (f (j' + j))) * real_of_float x ^ j) \\<le> (ub n ((F ^^ j') s) (f j') x)\" (is \"?ub\")\nproof -\n  have diff_mult_minus: \"x - y * z = x + - y * z\" for x y z :: float by simp\n  have sum_eq: \"(\\<Sum>j=0..<n. (1 / (f (j' + j))) * real_of_float x ^ j) =\n    (\\<Sum>j = 0..<n. (- 1) ^ j * (1 / (f (j' + j))) * real_of_float (- x) ^ j)\"\n    by (auto simp add: field_simps power_mult_distrib[symmetric])\n  have \"0 \\<le> real_of_float (-x)\" using assms by auto\n  from horner_bounds[where G=G and F=F and f=f and s=s and prec=prec\n    and lb=\"\\<lambda> n i k x. lb n i k (-x)\" and ub=\"\\<lambda> n i k x. ub n i k (-x)\",\n    unfolded lb_Suc ub_Suc diff_mult_minus,\n    OF this f_Suc lb_0 _ ub_0 _]\n  show \"?lb\" and \"?ub\" unfolding minus_minus sum_eq\n    by (auto simp: minus_float_round_up_eq minus_float_round_down_eq)\nqed\n\n\nsubsection \\<open>Selectors for next even or odd number\\<close>\n\ntext \\<open>\nThe horner scheme computes alternating series. To get the upper and lower bounds we need to\nguarantee to access a even or odd member. To do this we use @{term get_odd} and @{term get_even}.\n\\<close>\n\ndefinition get_odd :: \"nat \\<Rightarrow> nat\" where\n  \"get_odd n = (if odd n then n else (Suc n))\"\n\ndefinition get_even :: \"nat \\<Rightarrow> nat\" where\n  \"get_even n = (if even n then n else (Suc n))\"\n\nlemma get_odd[simp]: \"odd (get_odd n)\"\n  unfolding get_odd_def by (cases \"odd n\") auto\n\nlemma get_even[simp]: \"even (get_even n)\"\n  unfolding get_even_def by (cases \"even n\") auto\n\nlemma get_odd_ex: \"\\<exists> k. Suc k = get_odd n \\<and> odd (Suc k)\"\n  by (auto simp: get_odd_def odd_pos intro!: exI[of _ \"n - 1\"])\n\nlemma get_even_double: \"\\<exists>i. get_even n = 2 * i\"\n  using get_even by (blast elim: evenE)\n\nlemma get_odd_double: \"\\<exists>i. get_odd n = 2 * i + 1\"\n  using get_odd by (blast elim: oddE)\n\n\nsection \"Power function\"\n\ndefinition float_power_bnds :: \"nat \\<Rightarrow> nat \\<Rightarrow> float \\<Rightarrow> float \\<Rightarrow> float * float\" where\n\"float_power_bnds prec n l u =\n  (if 0 < l then (power_down_fl prec l n, power_up_fl prec u n)\n  else if odd n then\n    (- power_up_fl prec \\<bar>l\\<bar> n,\n      if u < 0 then - power_down_fl prec \\<bar>u\\<bar> n else power_up_fl prec u n)\n  else if u < 0 then (power_down_fl prec \\<bar>u\\<bar> n, power_up_fl prec \\<bar>l\\<bar> n)\n  else (0, power_up_fl prec (max \\<bar>l\\<bar> \\<bar>u\\<bar>) n))\"\n\nlemma le_minus_power_downI: \"0 \\<le> x \\<Longrightarrow> x ^ n \\<le> - a \\<Longrightarrow> a \\<le> - power_down prec x n\"\n  by (subst le_minus_iff) (auto intro: power_down_le power_mono_odd)\n\nlemma float_power_bnds:\n  \"(l1, u1) = float_power_bnds prec n l u \\<Longrightarrow> x \\<in> {l .. u} \\<Longrightarrow> (x::real) ^ n \\<in> {l1..u1}\"\n  by (auto\n    simp: float_power_bnds_def max_def real_power_up_fl real_power_down_fl minus_le_iff\n    split: if_split_asm\n    intro!: power_up_le power_down_le le_minus_power_downI\n    intro: power_mono_odd power_mono power_mono_even zero_le_even_power)\n\nlemma bnds_power:\n  \"\\<forall>(x::real) l u. (l1, u1) = float_power_bnds prec n l u \\<and> x \\<in> {l .. u} \\<longrightarrow>\n    l1 \\<le> x ^ n \\<and> x ^ n \\<le> u1\"\n  using float_power_bnds by auto\n\nsection \\<open>Approximation utility functions\\<close>\n\ndefinition bnds_mult :: \"nat \\<Rightarrow> float \\<Rightarrow> float \\<Rightarrow> float \\<Rightarrow> float \\<Rightarrow> float \\<times> float\" where\n  \"bnds_mult prec a1 a2 b1 b2 =\n      (float_plus_down prec (nprt a1 * pprt b2)\n          (float_plus_down prec (nprt a2 * nprt b2)\n            (float_plus_down prec (pprt a1 * pprt b1) (pprt a2 * nprt b1))),\n        float_plus_up prec (pprt a2 * pprt b2)\n            (float_plus_up prec (pprt a1 * nprt b2)\n              (float_plus_up prec (nprt a2 * pprt b1) (nprt a1 * nprt b1))))\"\n\nlemma bnds_mult:\n  fixes prec :: nat and a1 aa2 b1 b2 :: float\n  assumes \"(l, u) = bnds_mult prec a1 a2 b1 b2\"\n  assumes \"a \\<in> {real_of_float a1..real_of_float a2}\"\n  assumes \"b \\<in> {real_of_float b1..real_of_float b2}\"\n  shows   \"a * b \\<in> {real_of_float l..real_of_float u}\"\nproof -\n  from assms have \"real_of_float l \\<le> a * b\" \n    by (intro order.trans[OF _ mult_ge_prts[of a1 a a2 b1 b b2]])\n       (auto simp: bnds_mult_def intro!: float_plus_down_le)\n  moreover from assms have \"real_of_float u \\<ge> a * b\" \n    by (intro order.trans[OF mult_le_prts[of a1 a a2 b1 b b2]])\n       (auto simp: bnds_mult_def intro!: float_plus_up_le)\n  ultimately show ?thesis by simp\nqed\n\ndefinition map_bnds :: \"(nat \\<Rightarrow> float \\<Rightarrow> float) \\<Rightarrow> (nat \\<Rightarrow> float \\<Rightarrow> float) \\<Rightarrow>\n                           nat \\<Rightarrow> (float \\<times> float) \\<Rightarrow> (float \\<times> float)\" where\n  \"map_bnds lb ub prec = (\\<lambda>(l,u). (lb prec l, ub prec u))\"\n\nlemma map_bnds:\n  assumes \"(lf, uf) = map_bnds lb ub prec (l, u)\"\n  assumes \"mono f\"\n  assumes \"x \\<in> {real_of_float l..real_of_float u}\"\n  assumes \"real_of_float (lb prec l) \\<le> f (real_of_float l)\"\n  assumes \"real_of_float (ub prec u) \\<ge> f (real_of_float u)\"\n  shows   \"f x \\<in> {real_of_float lf..real_of_float uf}\"\nproof -\n  from assms have \"real_of_float lf = real_of_float (lb prec l)\"\n    by (simp add: map_bnds_def)\n  also have \"real_of_float (lb prec l) \\<le> f (real_of_float l)\"  by fact\n  also from assms have \"\\<dots> \\<le> f x\"\n    by (intro monoD[OF \\<open>mono f\\<close>]) auto\n  finally have lf: \"real_of_float lf \\<le> f x\" .\n\n  from assms have \"f x \\<le> f (real_of_float u)\"\n    by (intro monoD[OF \\<open>mono f\\<close>]) auto\n  also have \"\\<dots> \\<le> real_of_float (ub prec u)\" by fact\n  also from assms have \"\\<dots> = real_of_float uf\"\n    by (simp add: map_bnds_def)\n  finally have uf: \"f x \\<le> real_of_float uf\" .\n\n  from lf uf show ?thesis by simp\nqed\n\n\nsection \"Square root\"\n\ntext \\<open>\nThe square root computation is implemented as newton iteration. As first first step we use the\nnearest power of two greater than the square root.\n\\<close>\n\nfun sqrt_iteration :: \"nat \\<Rightarrow> nat \\<Rightarrow> float \\<Rightarrow> float\" where\n\"sqrt_iteration prec 0 x = Float 1 ((bitlen \\<bar>mantissa x\\<bar> + exponent x) div 2 + 1)\" |\n\"sqrt_iteration prec (Suc m) x = (let y = sqrt_iteration prec m x\n                                  in Float 1 (- 1) * float_plus_up prec y (float_divr prec x y))\"\n\nlemma compute_sqrt_iteration_base[code]:\n  shows \"sqrt_iteration prec n (Float m e) =\n    (if n = 0 then Float 1 ((if m = 0 then 0 else bitlen \\<bar>m\\<bar> + e) div 2 + 1)\n    else (let y = sqrt_iteration prec (n - 1) (Float m e) in\n      Float 1 (- 1) * float_plus_up prec y (float_divr prec (Float m e) y)))\"\n  using bitlen_Float by (cases n) simp_all\n\nfunction ub_sqrt lb_sqrt :: \"nat \\<Rightarrow> float \\<Rightarrow> float\" where\n\"ub_sqrt prec x = (if 0 < x then (sqrt_iteration prec prec x)\n              else if x < 0 then - lb_sqrt prec (- x)\n                            else 0)\" |\n\"lb_sqrt prec x = (if 0 < x then (float_divl prec x (sqrt_iteration prec prec x))\n              else if x < 0 then - ub_sqrt prec (- x)\n                            else 0)\"\nby pat_completeness auto\ntermination by (relation \"measure (\\<lambda> v. let (prec, x) = case_sum id id v in (if x < 0 then 1 else 0))\", auto)\n\ndeclare lb_sqrt.simps[simp del]\ndeclare ub_sqrt.simps[simp del]\n\nlemma sqrt_ub_pos_pos_1:\n  assumes \"sqrt x < b\" and \"0 < b\" and \"0 < x\"\n  shows \"sqrt x < (b + x / b)/2\"\nproof -\n  from assms have \"0 < (b - sqrt x)\\<^sup>2 \" by simp\n  also have \"\\<dots> = b\\<^sup>2 - 2 * b * sqrt x + (sqrt x)\\<^sup>2\" by algebra\n  also have \"\\<dots> = b\\<^sup>2 - 2 * b * sqrt x + x\" using assms by simp\n  finally have \"0 < b\\<^sup>2 - 2 * b * sqrt x + x\" .\n  hence \"0 < b / 2 - sqrt x + x / (2 * b)\" using assms\n    by (simp add: field_simps power2_eq_square)\n  thus ?thesis by (simp add: field_simps)\nqed\n\nlemma sqrt_iteration_bound:\n  assumes \"0 < real_of_float x\"\n  shows \"sqrt x < sqrt_iteration prec n x\"\nproof (induct n)\n  case 0\n  show ?case\n  proof (cases x)\n    case (Float m e)\n    hence \"0 < m\"\n      using assms\n      apply (auto simp: sign_simps)\n      by (meson not_less powr_ge_pzero)\n    hence \"0 < sqrt m\" by auto\n\n    have int_nat_bl: \"(nat (bitlen m)) = bitlen m\"\n      using bitlen_nonneg by auto\n\n    have \"x = (m / 2^nat (bitlen m)) * 2 powr (e + (nat (bitlen m)))\"\n      unfolding Float by (auto simp: powr_realpow[symmetric] field_simps powr_add)\n    also have \"\\<dots> < 1 * 2 powr (e + nat (bitlen m))\"\n    proof (rule mult_strict_right_mono, auto)\n      show \"m < 2^nat (bitlen m)\"\n        using bitlen_bounds[OF \\<open>0 < m\\<close>, THEN conjunct2]\n        unfolding of_int_less_iff[of m, symmetric] by auto\n    qed\n    finally have \"sqrt x < sqrt (2 powr (e + bitlen m))\"\n      unfolding int_nat_bl by auto\n    also have \"\\<dots> \\<le> 2 powr ((e + bitlen m) div 2 + 1)\"\n    proof -\n      let ?E = \"e + bitlen m\"\n      have E_mod_pow: \"2 powr (?E mod 2) < 4\"\n      proof (cases \"?E mod 2 = 1\")\n        case True\n        thus ?thesis by auto\n      next\n        case False\n        have \"0 \\<le> ?E mod 2\" by auto\n        have \"?E mod 2 < 2\" by auto\n        from this[THEN zless_imp_add1_zle]\n        have \"?E mod 2 \\<le> 0\" using False by auto\n        from xt1(5)[OF \\<open>0 \\<le> ?E mod 2\\<close> this]\n        show ?thesis by auto\n      qed\n      hence \"sqrt (2 powr (?E mod 2)) < sqrt (2 * 2)\"\n        by (auto simp del: real_sqrt_four)\n      hence E_mod_pow: \"sqrt (2 powr (?E mod 2)) < 2\" by auto\n\n      have E_eq: \"2 powr ?E = 2 powr (?E div 2 + ?E div 2 + ?E mod 2)\"\n        by auto\n      have \"sqrt (2 powr ?E) = sqrt (2 powr (?E div 2) * 2 powr (?E div 2) * 2 powr (?E mod 2))\"\n        unfolding E_eq unfolding powr_add[symmetric] by (metis of_int_add)\n      also have \"\\<dots> = 2 powr (?E div 2) * sqrt (2 powr (?E mod 2))\"\n        unfolding real_sqrt_mult[of _ \"2 powr (?E mod 2)\"] real_sqrt_abs2 by auto\n      also have \"\\<dots> < 2 powr (?E div 2) * 2 powr 1\"\n        by (rule mult_strict_left_mono) (auto intro: E_mod_pow)\n      also have \"\\<dots> = 2 powr (?E div 2 + 1)\"\n        unfolding add.commute[of _ 1] powr_add[symmetric] by simp\n      finally show ?thesis by auto\n    qed\n    finally show ?thesis using \\<open>0 < m\\<close>\n      unfolding Float\n      by (subst compute_sqrt_iteration_base) (simp add: ac_simps)\n  qed\nnext\n  case (Suc n)\n  let ?b = \"sqrt_iteration prec n x\"\n  have \"0 < sqrt x\"\n    using \\<open>0 < real_of_float x\\<close> by auto\n  also have \"\\<dots> < real_of_float ?b\"\n    using Suc .\n  finally have \"sqrt x < (?b + x / ?b)/2\"\n    using sqrt_ub_pos_pos_1[OF Suc _ \\<open>0 < real_of_float x\\<close>] by auto\n  also have \"\\<dots> \\<le> (?b + (float_divr prec x ?b))/2\"\n    by (rule divide_right_mono, auto simp add: float_divr)\n  also have \"\\<dots> = (Float 1 (- 1)) * (?b + (float_divr prec x ?b))\"\n    by simp\n  also have \"\\<dots> \\<le> (Float 1 (- 1)) * (float_plus_up prec ?b (float_divr prec x ?b))\"\n    by (auto simp add: algebra_simps float_plus_up_le)\n  finally show ?case\n    unfolding sqrt_iteration.simps Let_def distrib_left .\nqed\n\nlemma sqrt_iteration_lower_bound:\n  assumes \"0 < real_of_float x\"\n  shows \"0 < real_of_float (sqrt_iteration prec n x)\" (is \"0 < ?sqrt\")\nproof -\n  have \"0 < sqrt x\" using assms by auto\n  also have \"\\<dots> < ?sqrt\" using sqrt_iteration_bound[OF assms] .\n  finally show ?thesis .\nqed\n\nlemma lb_sqrt_lower_bound:\n  assumes \"0 \\<le> real_of_float x\"\n  shows \"0 \\<le> real_of_float (lb_sqrt prec x)\"\nproof (cases \"0 < x\")\n  case True\n  hence \"0 < real_of_float x\" and \"0 \\<le> x\"\n    using \\<open>0 \\<le> real_of_float x\\<close> by auto\n  hence \"0 < sqrt_iteration prec prec x\"\n    using sqrt_iteration_lower_bound by auto\n  hence \"0 \\<le> real_of_float (float_divl prec x (sqrt_iteration prec prec x))\"\n    using float_divl_lower_bound[OF \\<open>0 \\<le> x\\<close>] unfolding less_eq_float_def by auto\n  thus ?thesis\n    unfolding lb_sqrt.simps using True by auto\nnext\n  case False\n  with \\<open>0 \\<le> real_of_float x\\<close> have \"real_of_float x = 0\" by auto\n  thus ?thesis\n    unfolding lb_sqrt.simps by auto\nqed\n\nlemma bnds_sqrt': \"sqrt x \\<in> {(lb_sqrt prec x) .. (ub_sqrt prec x)}\"\nproof -\n  have lb: \"lb_sqrt prec x \\<le> sqrt x\" if \"0 < x\" for x :: float\n  proof -\n    from that have \"0 < real_of_float x\" and \"0 \\<le> real_of_float x\" by auto\n    hence sqrt_gt0: \"0 < sqrt x\" by auto\n    hence sqrt_ub: \"sqrt x < sqrt_iteration prec prec x\"\n      using sqrt_iteration_bound by auto\n    have \"(float_divl prec x (sqrt_iteration prec prec x)) \\<le>\n          x / (sqrt_iteration prec prec x)\" by (rule float_divl)\n    also have \"\\<dots> < x / sqrt x\"\n      by (rule divide_strict_left_mono[OF sqrt_ub \\<open>0 < real_of_float x\\<close>\n               mult_pos_pos[OF order_less_trans[OF sqrt_gt0 sqrt_ub] sqrt_gt0]])\n    also have \"\\<dots> = sqrt x\"\n      unfolding inverse_eq_iff_eq[of _ \"sqrt x\", symmetric]\n                sqrt_divide_self_eq[OF \\<open>0 \\<le> real_of_float x\\<close>, symmetric] by auto\n    finally show ?thesis\n      unfolding lb_sqrt.simps if_P[OF \\<open>0 < x\\<close>] by auto\n  qed\n  have ub: \"sqrt x \\<le> ub_sqrt prec x\" if \"0 < x\" for x :: float\n  proof -\n    from that have \"0 < real_of_float x\" by auto\n    hence \"0 < sqrt x\" by auto\n    hence \"sqrt x < sqrt_iteration prec prec x\"\n      using sqrt_iteration_bound by auto\n    then show ?thesis\n      unfolding ub_sqrt.simps if_P[OF \\<open>0 < x\\<close>] by auto\n  qed\n  show ?thesis\n    using lb[of \"-x\"] ub[of \"-x\"] lb[of x] ub[of x]\n    by (auto simp add: lb_sqrt.simps ub_sqrt.simps real_sqrt_minus)\nqed\n\nlemma bnds_sqrt: \"\\<forall>(x::real) lx ux.\n  (l, u) = (lb_sqrt prec lx, ub_sqrt prec ux) \\<and> x \\<in> {lx .. ux} \\<longrightarrow> l \\<le> sqrt x \\<and> sqrt x \\<le> u\"\nproof ((rule allI) +, rule impI, erule conjE, rule conjI)\n  fix x :: real\n  fix lx ux\n  assume \"(l, u) = (lb_sqrt prec lx, ub_sqrt prec ux)\"\n    and x: \"x \\<in> {lx .. ux}\"\n  hence l: \"l = lb_sqrt prec lx \" and u: \"u = ub_sqrt prec ux\" by auto\n\n  have \"sqrt lx \\<le> sqrt x\" using x by auto\n  from order_trans[OF _ this]\n  show \"l \\<le> sqrt x\" unfolding l using bnds_sqrt'[of lx prec] by auto\n\n  have \"sqrt x \\<le> sqrt ux\" using x by auto\n  from order_trans[OF this]\n  show \"sqrt x \\<le> u\" unfolding u using bnds_sqrt'[of ux prec] by auto\nqed\n\n\nsection \"Arcus tangens and \\<pi>\"\n\nsubsection \"Compute arcus tangens series\"\n\ntext \\<open>\nAs first step we implement the computation of the arcus tangens series. This is only valid in the range\n@{term \"{-1 :: real .. 1}\"}. This is used to compute \\<pi> and then the entire arcus tangens.\n\\<close>\n\nfun ub_arctan_horner :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> float \\<Rightarrow> float\"\nand lb_arctan_horner :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> float \\<Rightarrow> float\" where\n  \"ub_arctan_horner prec 0 k x = 0\"\n| \"ub_arctan_horner prec (Suc n) k x = float_plus_up prec\n      (rapprox_rat prec 1 k) (- float_round_down prec (x * (lb_arctan_horner prec n (k + 2) x)))\"\n| \"lb_arctan_horner prec 0 k x = 0\"\n| \"lb_arctan_horner prec (Suc n) k x = float_plus_down prec\n      (lapprox_rat prec 1 k) (- float_round_up prec (x * (ub_arctan_horner prec n (k + 2) x)))\"\n\nlemma arctan_0_1_bounds':\n  assumes \"0 \\<le> real_of_float y\" \"real_of_float y \\<le> 1\"\n    and \"even n\"\n  shows \"arctan (sqrt y) \\<in>\n      {(sqrt y * lb_arctan_horner prec n 1 y) .. (sqrt y * ub_arctan_horner prec (Suc n) 1 y)}\"\nproof -\n  let ?c = \"\\<lambda>i. (- 1) ^ i * (1 / (i * 2 + (1::nat)) * sqrt y ^ (i * 2 + 1))\"\n  let ?S = \"\\<lambda>n. \\<Sum> i=0..<n. ?c i\"\n\n  have \"0 \\<le> sqrt y\" using assms by auto\n  have \"sqrt y \\<le> 1\" using assms by auto\n  from \\<open>even n\\<close> obtain m where \"2 * m = n\" by (blast elim: evenE)\n\n  have \"arctan (sqrt y) \\<in> { ?S n .. ?S (Suc n) }\"\n  proof (cases \"sqrt y = 0\")\n    case True\n    then show ?thesis by simp\n  next\n    case False\n    hence \"0 < sqrt y\" using \\<open>0 \\<le> sqrt y\\<close> by auto\n    hence prem: \"0 < 1 / (0 * 2 + (1::nat)) * sqrt y ^ (0 * 2 + 1)\" by auto\n\n    have \"\\<bar> sqrt y \\<bar> \\<le> 1\"  using \\<open>0 \\<le> sqrt y\\<close> \\<open>sqrt y \\<le> 1\\<close> by auto\n    from mp[OF summable_Leibniz(2)[OF zeroseq_arctan_series[OF this]\n      monoseq_arctan_series[OF this]] prem, THEN spec, of m, unfolded \\<open>2 * m = n\\<close>]\n    show ?thesis unfolding arctan_series[OF \\<open>\\<bar> sqrt y \\<bar> \\<le> 1\\<close>] Suc_eq_plus1 atLeast0LessThan .\n  qed\n  note arctan_bounds = this[unfolded atLeastAtMost_iff]\n\n  have F: \"\\<And>n. 2 * Suc n + 1 = 2 * n + 1 + 2\" by auto\n\n  note bounds = horner_bounds[where s=1 and f=\"\\<lambda>i. 2 * i + 1\" and j'=0\n    and lb=\"\\<lambda>n i k x. lb_arctan_horner prec n k x\"\n    and ub=\"\\<lambda>n i k x. ub_arctan_horner prec n k x\",\n    OF \\<open>0 \\<le> real_of_float y\\<close> F lb_arctan_horner.simps ub_arctan_horner.simps]\n\n  have \"(sqrt y * lb_arctan_horner prec n 1 y) \\<le> arctan (sqrt y)\"\n  proof -\n    have \"(sqrt y * lb_arctan_horner prec n 1 y) \\<le> ?S n\"\n      using bounds(1) \\<open>0 \\<le> sqrt y\\<close>\n      apply (simp only: power_add power_one_right mult.assoc[symmetric] sum_distrib_right[symmetric])\n      apply (simp only: mult.commute[where 'a=real] mult.commute[of _ \"2::nat\"] power_mult)\n      apply (auto intro!: mult_left_mono)\n      done\n    also have \"\\<dots> \\<le> arctan (sqrt y)\" using arctan_bounds ..\n    finally show ?thesis .\n  qed\n  moreover\n  have \"arctan (sqrt y) \\<le> (sqrt y * ub_arctan_horner prec (Suc n) 1 y)\"\n  proof -\n    have \"arctan (sqrt y) \\<le> ?S (Suc n)\" using arctan_bounds ..\n    also have \"\\<dots> \\<le> (sqrt y * ub_arctan_horner prec (Suc n) 1 y)\"\n      using bounds(2)[of \"Suc n\"] \\<open>0 \\<le> sqrt y\\<close>\n      apply (simp only: power_add power_one_right mult.assoc[symmetric] sum_distrib_right[symmetric])\n      apply (simp only: mult.commute[where 'a=real] mult.commute[of _ \"2::nat\"] power_mult)\n      apply (auto intro!: mult_left_mono)\n      done\n    finally show ?thesis .\n  qed\n  ultimately show ?thesis by auto\nqed\n\nlemma arctan_0_1_bounds:\n  assumes \"0 \\<le> real_of_float y\" \"real_of_float y \\<le> 1\"\n  shows \"arctan (sqrt y) \\<in>\n    {(sqrt y * lb_arctan_horner prec (get_even n) 1 y) ..\n      (sqrt y * ub_arctan_horner prec (get_odd n) 1 y)}\"\n  using\n    arctan_0_1_bounds'[OF assms, of n prec]\n    arctan_0_1_bounds'[OF assms, of \"n + 1\" prec]\n    arctan_0_1_bounds'[OF assms, of \"n - 1\" prec]\n  by (auto simp: get_even_def get_odd_def odd_pos\n    simp del: ub_arctan_horner.simps lb_arctan_horner.simps)\n\nlemma arctan_lower_bound:\n  assumes \"0 \\<le> x\"\n  shows \"x / (1 + x\\<^sup>2) \\<le> arctan x\" (is \"?l x \\<le> _\")\nproof -\n  have \"?l x - arctan x \\<le> ?l 0 - arctan 0\"\n    using assms\n    by (intro DERIV_nonpos_imp_nonincreasing[where f=\"\\<lambda>x. ?l x - arctan x\"])\n      (auto intro!: derivative_eq_intros simp: add_nonneg_eq_0_iff field_simps)\n  thus ?thesis by simp\nqed\n\nlemma arctan_divide_mono: \"0 < x \\<Longrightarrow> x \\<le> y \\<Longrightarrow> arctan y / y \\<le> arctan x / x\"\n  by (rule DERIV_nonpos_imp_nonincreasing[where f=\"\\<lambda>x. arctan x / x\"])\n    (auto intro!: derivative_eq_intros divide_nonpos_nonneg\n      simp: inverse_eq_divide arctan_lower_bound)\n\nlemma arctan_mult_mono: \"0 \\<le> x \\<Longrightarrow> x \\<le> y \\<Longrightarrow> x * arctan y \\<le> y * arctan x\"\n  using arctan_divide_mono[of x y] by (cases \"x = 0\") (simp_all add: field_simps)\n\nlemma arctan_mult_le:\n  assumes \"0 \\<le> x\" \"x \\<le> y\" \"y * z \\<le> arctan y\"\n  shows \"x * z \\<le> arctan x\"\nproof (cases \"x = 0\")\n  case True\n  then show ?thesis by simp\nnext\n  case False\n  with assms have \"z \\<le> arctan y / y\" by (simp add: field_simps)\n  also have \"\\<dots> \\<le> arctan x / x\" using assms \\<open>x \\<noteq> 0\\<close> by (auto intro!: arctan_divide_mono)\n  finally show ?thesis using assms \\<open>x \\<noteq> 0\\<close> by (simp add: field_simps)\nqed\n\nlemma arctan_le_mult:\n  assumes \"0 < x\" \"x \\<le> y\" \"arctan x \\<le> x * z\"\n  shows \"arctan y \\<le> y * z\"\nproof -\n  from assms have \"arctan y / y \\<le> arctan x / x\" by (auto intro!: arctan_divide_mono)\n  also have \"\\<dots> \\<le> z\" using assms by (auto simp: field_simps)\n  finally show ?thesis using assms by (simp add: field_simps)\nqed\n\nlemma arctan_0_1_bounds_le:\n  assumes \"0 \\<le> x\" \"x \\<le> 1\" \"0 < real_of_float xl\" \"real_of_float xl \\<le> x * x\" \"x * x \\<le> real_of_float xu\" \"real_of_float xu \\<le> 1\"\n  shows \"arctan x \\<in>\n      {x * lb_arctan_horner p1 (get_even n) 1 xu .. x * ub_arctan_horner p2 (get_odd n) 1 xl}\"\nproof -\n  from assms have \"real_of_float xl \\<le> 1\" \"sqrt (real_of_float xl) \\<le> x\" \"x \\<le> sqrt (real_of_float xu)\" \"0 \\<le> real_of_float xu\"\n    \"0 \\<le> real_of_float xl\" \"0 < sqrt (real_of_float xl)\"\n    by (auto intro!: real_le_rsqrt real_le_lsqrt simp: power2_eq_square)\n  from arctan_0_1_bounds[OF \\<open>0 \\<le> real_of_float xu\\<close>  \\<open>real_of_float xu \\<le> 1\\<close>]\n  have \"sqrt (real_of_float xu) * real_of_float (lb_arctan_horner p1 (get_even n) 1 xu) \\<le> arctan (sqrt (real_of_float xu))\"\n    by simp\n  from arctan_mult_le[OF \\<open>0 \\<le> x\\<close> \\<open>x \\<le> sqrt _\\<close>  this]\n  have \"x * real_of_float (lb_arctan_horner p1 (get_even n) 1 xu) \\<le> arctan x\" .\n  moreover\n  from arctan_0_1_bounds[OF \\<open>0 \\<le> real_of_float xl\\<close>  \\<open>real_of_float xl \\<le> 1\\<close>]\n  have \"arctan (sqrt (real_of_float xl)) \\<le> sqrt (real_of_float xl) * real_of_float (ub_arctan_horner p2 (get_odd n) 1 xl)\"\n    by simp\n  from arctan_le_mult[OF \\<open>0 < sqrt xl\\<close> \\<open>sqrt xl \\<le> x\\<close> this]\n  have \"arctan x \\<le> x * real_of_float (ub_arctan_horner p2 (get_odd n) 1 xl)\" .\n  ultimately show ?thesis by simp\nqed\n\nlemma arctan_0_1_bounds_round:\n  assumes \"0 \\<le> real_of_float x\" \"real_of_float x \\<le> 1\"\n  shows \"arctan x \\<in>\n      {real_of_float x * lb_arctan_horner p1 (get_even n) 1 (float_round_up (Suc p2) (x * x)) ..\n        real_of_float x * ub_arctan_horner p3 (get_odd n) 1 (float_round_down (Suc p4) (x * x))}\"\n  using assms\n  apply (cases \"x > 0\")\n   apply (intro arctan_0_1_bounds_le)\n   apply (auto simp: float_round_down.rep_eq float_round_up.rep_eq\n    intro!: truncate_up_le1 mult_le_one truncate_down_le truncate_up_le truncate_down_pos\n      mult_pos_pos)\n  done\n\n\nsubsection \"Compute \\<pi>\"\n\ndefinition ub_pi :: \"nat \\<Rightarrow> float\" where\n  \"ub_pi prec =\n    (let\n      A = rapprox_rat prec 1 5 ;\n      B = lapprox_rat prec 1 239\n    in ((Float 1 2) * float_plus_up prec\n      ((Float 1 2) * float_round_up prec (A * (ub_arctan_horner prec (get_odd (prec div 4 + 1)) 1\n        (float_round_down (Suc prec) (A * A)))))\n      (- float_round_down prec (B * (lb_arctan_horner prec (get_even (prec div 14 + 1)) 1\n        (float_round_up (Suc prec) (B * B)))))))\"\n\ndefinition lb_pi :: \"nat \\<Rightarrow> float\" where\n  \"lb_pi prec =\n    (let\n      A = lapprox_rat prec 1 5 ;\n      B = rapprox_rat prec 1 239\n    in ((Float 1 2) * float_plus_down prec\n      ((Float 1 2) * float_round_down prec (A * (lb_arctan_horner prec (get_even (prec div 4 + 1)) 1\n        (float_round_up (Suc prec) (A * A)))))\n      (- float_round_up prec (B * (ub_arctan_horner prec (get_odd (prec div 14 + 1)) 1\n        (float_round_down (Suc prec) (B * B)))))))\"\n\nlemma pi_boundaries: \"pi \\<in> {(lb_pi n) .. (ub_pi n)}\"\nproof -\n  have machin_pi: \"pi = 4 * (4 * arctan (1 / 5) - arctan (1 / 239))\"\n    unfolding machin[symmetric] by auto\n\n  {\n    fix prec n :: nat\n    fix k :: int\n    assume \"1 < k\" hence \"0 \\<le> k\" and \"0 < k\" and \"1 \\<le> k\" by auto\n    let ?k = \"rapprox_rat prec 1 k\"\n    let ?kl = \"float_round_down (Suc prec) (?k * ?k)\"\n    have \"1 div k = 0\" using div_pos_pos_trivial[OF _ \\<open>1 < k\\<close>] by auto\n\n    have \"0 \\<le> real_of_float ?k\" by (rule order_trans[OF _ rapprox_rat]) (auto simp add: \\<open>0 \\<le> k\\<close>)\n    have \"real_of_float ?k \\<le> 1\"\n      by (auto simp add: \\<open>0 < k\\<close> \\<open>1 \\<le> k\\<close> less_imp_le\n        intro!: mult_le_one order_trans[OF _ rapprox_rat] rapprox_rat_le1)\n    have \"1 / k \\<le> ?k\" using rapprox_rat[where x=1 and y=k] by auto\n    hence \"arctan (1 / k) \\<le> arctan ?k\" by (rule arctan_monotone')\n    also have \"\\<dots> \\<le> (?k * ub_arctan_horner prec (get_odd n) 1 ?kl)\"\n      using arctan_0_1_bounds_round[OF \\<open>0 \\<le> real_of_float ?k\\<close> \\<open>real_of_float ?k \\<le> 1\\<close>]\n      by auto\n    finally have \"arctan (1 / k) \\<le> ?k * ub_arctan_horner prec (get_odd n) 1 ?kl\" .\n  } note ub_arctan = this\n\n  {\n    fix prec n :: nat\n    fix k :: int\n    assume \"1 < k\" hence \"0 \\<le> k\" and \"0 < k\" by auto\n    let ?k = \"lapprox_rat prec 1 k\"\n    let ?ku = \"float_round_up (Suc prec) (?k * ?k)\"\n    have \"1 div k = 0\" using div_pos_pos_trivial[OF _ \\<open>1 < k\\<close>] by auto\n    have \"1 / k \\<le> 1\" using \\<open>1 < k\\<close> by auto\n    have \"0 \\<le> real_of_float ?k\" using lapprox_rat_nonneg[where x=1 and y=k, OF zero_le_one \\<open>0 \\<le> k\\<close>]\n      by (auto simp add: \\<open>1 div k = 0\\<close>)\n    have \"0 \\<le> real_of_float (?k * ?k)\" by simp\n    have \"real_of_float ?k \\<le> 1\" using lapprox_rat by (rule order_trans, auto simp add: \\<open>1 / k \\<le> 1\\<close>)\n    hence \"real_of_float (?k * ?k) \\<le> 1\" using \\<open>0 \\<le> real_of_float ?k\\<close> by (auto intro!: mult_le_one)\n\n    have \"?k \\<le> 1 / k\" using lapprox_rat[where x=1 and y=k] by auto\n\n    have \"?k * lb_arctan_horner prec (get_even n) 1 ?ku \\<le> arctan ?k\"\n      using arctan_0_1_bounds_round[OF \\<open>0 \\<le> real_of_float ?k\\<close> \\<open>real_of_float ?k \\<le> 1\\<close>]\n      by auto\n    also have \"\\<dots> \\<le> arctan (1 / k)\" using \\<open>?k \\<le> 1 / k\\<close> by (rule arctan_monotone')\n    finally have \"?k * lb_arctan_horner prec (get_even n) 1 ?ku \\<le> arctan (1 / k)\" .\n  } note lb_arctan = this\n\n  have \"pi \\<le> ub_pi n \"\n    unfolding ub_pi_def machin_pi Let_def times_float.rep_eq Float_num\n    using lb_arctan[of 239] ub_arctan[of 5] powr_realpow[of 2 2]\n    by (intro mult_left_mono float_plus_up_le float_plus_down_le)\n      (auto intro!: mult_left_mono float_round_down_le float_round_up_le diff_mono)\n  moreover have \"lb_pi n \\<le> pi\"\n    unfolding lb_pi_def machin_pi Let_def times_float.rep_eq Float_num\n    using lb_arctan[of 5] ub_arctan[of 239]\n    by (intro mult_left_mono float_plus_up_le float_plus_down_le)\n      (auto intro!: mult_left_mono float_round_down_le float_round_up_le diff_mono)\n  ultimately show ?thesis by auto\nqed\n\n\nsubsection \"Compute arcus tangens in the entire domain\"\n\nfunction lb_arctan :: \"nat \\<Rightarrow> float \\<Rightarrow> float\" and ub_arctan :: \"nat \\<Rightarrow> float \\<Rightarrow> float\" where\n  \"lb_arctan prec x =\n    (let\n      ub_horner = \\<lambda> x. float_round_up prec\n        (x *\n          ub_arctan_horner prec (get_odd (prec div 4 + 1)) 1 (float_round_down (Suc prec) (x * x)));\n      lb_horner = \\<lambda> x. float_round_down prec\n        (x *\n          lb_arctan_horner prec (get_even (prec div 4 + 1)) 1 (float_round_up (Suc prec) (x * x)))\n    in\n      if x < 0 then - ub_arctan prec (-x)\n      else if x \\<le> Float 1 (- 1) then lb_horner x\n      else if x \\<le> Float 1 1 then\n        Float 1 1 *\n        lb_horner\n          (float_divl prec x\n            (float_plus_up prec 1\n              (ub_sqrt prec (float_plus_up prec 1 (float_round_up prec (x * x))))))\n      else let inv = float_divr prec 1 x in\n        if inv > 1 then 0\n        else float_plus_down prec (lb_pi prec * Float 1 (- 1)) ( - ub_horner inv))\"\n\n| \"ub_arctan prec x =\n    (let\n      lb_horner = \\<lambda> x. float_round_down prec\n        (x *\n          lb_arctan_horner prec (get_even (prec div 4 + 1)) 1 (float_round_up (Suc prec) (x * x))) ;\n      ub_horner = \\<lambda> x. float_round_up prec\n        (x *\n          ub_arctan_horner prec (get_odd (prec div 4 + 1)) 1 (float_round_down (Suc prec) (x * x)))\n    in if x < 0 then - lb_arctan prec (-x)\n    else if x \\<le> Float 1 (- 1) then ub_horner x\n    else if x \\<le> Float 1 1 then\n      let y = float_divr prec x\n        (float_plus_down\n          (Suc prec) 1 (lb_sqrt prec (float_plus_down prec 1 (float_round_down prec (x * x)))))\n      in if y > 1 then ub_pi prec * Float 1 (- 1) else Float 1 1 * ub_horner y\n    else float_plus_up prec (ub_pi prec * Float 1 (- 1)) ( - lb_horner (float_divl prec 1 x)))\"\nby pat_completeness auto\ntermination\nby (relation \"measure (\\<lambda> v. let (prec, x) = case_sum id id v in (if x < 0 then 1 else 0))\", auto)\n\ndeclare ub_arctan_horner.simps[simp del]\ndeclare lb_arctan_horner.simps[simp del]\n\nlemma lb_arctan_bound':\n  assumes \"0 \\<le> real_of_float x\"\n  shows \"lb_arctan prec x \\<le> arctan x\"\nproof -\n  have \"\\<not> x < 0\" and \"0 \\<le> x\"\n    using \\<open>0 \\<le> real_of_float x\\<close> by (auto intro!: truncate_up_le )\n\n  let \"?ub_horner x\" =\n      \"x * ub_arctan_horner prec (get_odd (prec div 4 + 1)) 1 (float_round_down (Suc prec) (x * x))\"\n    and \"?lb_horner x\" =\n      \"x * lb_arctan_horner prec (get_even (prec div 4 + 1)) 1 (float_round_up (Suc prec) (x * x))\"\n\n  show ?thesis\n  proof (cases \"x \\<le> Float 1 (- 1)\")\n    case True\n    hence \"real_of_float x \\<le> 1\" by simp\n    from arctan_0_1_bounds_round[OF \\<open>0 \\<le> real_of_float x\\<close> \\<open>real_of_float x \\<le> 1\\<close>]\n    show ?thesis\n      unfolding lb_arctan.simps Let_def if_not_P[OF \\<open>\\<not> x < 0\\<close>] if_P[OF True] using \\<open>0 \\<le> x\\<close>\n      by (auto intro!: float_round_down_le)\n  next\n    case False\n    hence \"0 < real_of_float x\" by auto\n    let ?R = \"1 + sqrt (1 + real_of_float x * real_of_float x)\"\n    let ?sxx = \"float_plus_up prec 1 (float_round_up prec (x * x))\"\n    let ?fR = \"float_plus_up prec 1 (ub_sqrt prec ?sxx)\"\n    let ?DIV = \"float_divl prec x ?fR\"\n\n    have divisor_gt0: \"0 < ?R\" by (auto intro: add_pos_nonneg)\n\n    have \"sqrt (1 + x*x) \\<le> sqrt ?sxx\"\n      by (auto simp: float_plus_up.rep_eq plus_up_def float_round_up.rep_eq intro!: truncate_up_le)\n    also have \"\\<dots> \\<le> ub_sqrt prec ?sxx\"\n      using bnds_sqrt'[of ?sxx prec] by auto\n    finally\n    have \"sqrt (1 + x*x) \\<le> ub_sqrt prec ?sxx\" .\n    hence \"?R \\<le> ?fR\" by (auto simp: float_plus_up.rep_eq plus_up_def intro!: truncate_up_le)\n    hence \"0 < ?fR\" and \"0 < real_of_float ?fR\" using \\<open>0 < ?R\\<close> by auto\n\n    have monotone: \"?DIV \\<le> x / ?R\"\n    proof -\n      have \"?DIV \\<le> real_of_float x / ?fR\" by (rule float_divl)\n      also have \"\\<dots> \\<le> x / ?R\" by (rule divide_left_mono[OF \\<open>?R \\<le> ?fR\\<close> \\<open>0 \\<le> real_of_float x\\<close> mult_pos_pos[OF order_less_le_trans[OF divisor_gt0 \\<open>?R \\<le> real_of_float ?fR\\<close>] divisor_gt0]])\n      finally show ?thesis .\n    qed\n\n    show ?thesis\n    proof (cases \"x \\<le> Float 1 1\")\n      case True\n      have \"x \\<le> sqrt (1 + x * x)\"\n        using real_sqrt_sum_squares_ge2[where x=1, unfolded numeral_2_eq_2] by auto\n      also note \\<open>\\<dots> \\<le> (ub_sqrt prec ?sxx)\\<close>\n      finally have \"real_of_float x \\<le> ?fR\"\n        by (auto simp: float_plus_up.rep_eq plus_up_def intro!: truncate_up_le)\n      moreover have \"?DIV \\<le> real_of_float x / ?fR\"\n        by (rule float_divl)\n      ultimately have \"real_of_float ?DIV \\<le> 1\"\n        unfolding divide_le_eq_1_pos[OF \\<open>0 < real_of_float ?fR\\<close>, symmetric] by auto\n\n      have \"0 \\<le> real_of_float ?DIV\"\n        using float_divl_lower_bound[OF \\<open>0 \\<le> x\\<close>] \\<open>0 < ?fR\\<close>\n        unfolding less_eq_float_def by auto\n\n      from arctan_0_1_bounds_round[OF \\<open>0 \\<le> real_of_float (?DIV)\\<close> \\<open>real_of_float (?DIV) \\<le> 1\\<close>]\n      have \"Float 1 1 * ?lb_horner ?DIV \\<le> 2 * arctan ?DIV\"\n        by simp\n      also have \"\\<dots> \\<le> 2 * arctan (x / ?R)\"\n        using arctan_monotone'[OF monotone] by (auto intro!: mult_left_mono arctan_monotone')\n      also have \"2 * arctan (x / ?R) = arctan x\"\n        using arctan_half[symmetric] unfolding numeral_2_eq_2 power_Suc2 power_0 mult_1_left .\n      finally show ?thesis\n        unfolding lb_arctan.simps Let_def if_not_P[OF \\<open>\\<not> x < 0\\<close>]\n          if_not_P[OF \\<open>\\<not> x \\<le> Float 1 (- 1)\\<close>] if_P[OF True]\n        by (auto simp: float_round_down.rep_eq\n          intro!: order_trans[OF mult_left_mono[OF truncate_down]])\n    next\n      case False\n      hence \"2 < real_of_float x\" by auto\n      hence \"1 \\<le> real_of_float x\" by auto\n\n      let \"?invx\" = \"float_divr prec 1 x\"\n      have \"0 \\<le> arctan x\" using arctan_monotone'[OF \\<open>0 \\<le> real_of_float x\\<close>]\n        using arctan_tan[of 0, unfolded tan_zero] by auto\n\n      show ?thesis\n      proof (cases \"1 < ?invx\")\n        case True\n        show ?thesis\n          unfolding lb_arctan.simps Let_def if_not_P[OF \\<open>\\<not> x < 0\\<close>]\n            if_not_P[OF \\<open>\\<not> x \\<le> Float 1 (- 1)\\<close>] if_not_P[OF False] if_P[OF True]\n          using \\<open>0 \\<le> arctan x\\<close> by auto\n      next\n        case False\n        hence \"real_of_float ?invx \\<le> 1\" by auto\n        have \"0 \\<le> real_of_float ?invx\"\n          by (rule order_trans[OF _ float_divr]) (auto simp add: \\<open>0 \\<le> real_of_float x\\<close>)\n\n        have \"1 / x \\<noteq> 0\" and \"0 < 1 / x\"\n          using \\<open>0 < real_of_float x\\<close> by auto\n\n        have \"arctan (1 / x) \\<le> arctan ?invx\"\n          unfolding one_float.rep_eq[symmetric] by (rule arctan_monotone', rule float_divr)\n        also have \"\\<dots> \\<le> ?ub_horner ?invx\"\n          using arctan_0_1_bounds_round[OF \\<open>0 \\<le> real_of_float ?invx\\<close> \\<open>real_of_float ?invx \\<le> 1\\<close>]\n          by (auto intro!: float_round_up_le)\n        also note float_round_up\n        finally have \"pi / 2 - float_round_up prec (?ub_horner ?invx) \\<le> arctan x\"\n          using \\<open>0 \\<le> arctan x\\<close> arctan_inverse[OF \\<open>1 / x \\<noteq> 0\\<close>]\n          unfolding sgn_pos[OF \\<open>0 < 1 / real_of_float x\\<close>] le_diff_eq by auto\n        moreover\n        have \"lb_pi prec * Float 1 (- 1) \\<le> pi / 2\"\n          unfolding Float_num times_divide_eq_right mult_1_left using pi_boundaries by simp\n        ultimately\n        show ?thesis\n          unfolding lb_arctan.simps Let_def if_not_P[OF \\<open>\\<not> x < 0\\<close>]\n            if_not_P[OF \\<open>\\<not> x \\<le> Float 1 (- 1)\\<close>] if_not_P[OF \\<open>\\<not> x \\<le> Float 1 1\\<close>] if_not_P[OF False]\n          by (auto intro!: float_plus_down_le)\n      qed\n    qed\n  qed\nqed\n\nlemma ub_arctan_bound':\n  assumes \"0 \\<le> real_of_float x\"\n  shows \"arctan x \\<le> ub_arctan prec x\"\nproof -\n  have \"\\<not> x < 0\" and \"0 \\<le> x\"\n    using \\<open>0 \\<le> real_of_float x\\<close> by auto\n\n  let \"?ub_horner x\" =\n    \"float_round_up prec (x * ub_arctan_horner prec (get_odd (prec div 4 + 1)) 1 (float_round_down (Suc prec) (x * x)))\"\n  let \"?lb_horner x\" =\n    \"float_round_down prec (x * lb_arctan_horner prec (get_even (prec div 4 + 1)) 1 (float_round_up (Suc prec) (x * x)))\"\n\n  show ?thesis\n  proof (cases \"x \\<le> Float 1 (- 1)\")\n    case True\n    hence \"real_of_float x \\<le> 1\" by auto\n    show ?thesis\n      unfolding ub_arctan.simps Let_def if_not_P[OF \\<open>\\<not> x < 0\\<close>] if_P[OF True]\n      using arctan_0_1_bounds_round[OF \\<open>0 \\<le> real_of_float x\\<close> \\<open>real_of_float x \\<le> 1\\<close>]\n      by (auto intro!: float_round_up_le)\n  next\n    case False\n    hence \"0 < real_of_float x\" by auto\n    let ?R = \"1 + sqrt (1 + real_of_float x * real_of_float x)\"\n    let ?sxx = \"float_plus_down prec 1 (float_round_down prec (x * x))\"\n    let ?fR = \"float_plus_down (Suc prec) 1 (lb_sqrt prec ?sxx)\"\n    let ?DIV = \"float_divr prec x ?fR\"\n\n    have sqr_ge0: \"0 \\<le> 1 + real_of_float x * real_of_float x\"\n      using sum_power2_ge_zero[of 1 \"real_of_float x\", unfolded numeral_2_eq_2] by auto\n    hence \"0 \\<le> real_of_float (1 + x*x)\" by auto\n\n    hence divisor_gt0: \"0 < ?R\" by (auto intro: add_pos_nonneg)\n\n    have \"lb_sqrt prec ?sxx \\<le> sqrt ?sxx\"\n      using bnds_sqrt'[of ?sxx] by auto\n    also have \"\\<dots> \\<le> sqrt (1 + x*x)\"\n      by (auto simp: float_plus_down.rep_eq plus_down_def float_round_down.rep_eq truncate_down_le)\n    finally have \"lb_sqrt prec ?sxx \\<le> sqrt (1 + x*x)\" .\n    hence \"?fR \\<le> ?R\"\n      by (auto simp: float_plus_down.rep_eq plus_down_def truncate_down_le)\n    have \"0 < real_of_float ?fR\"\n      by (auto simp: float_plus_down.rep_eq plus_down_def float_round_down.rep_eq\n        intro!: truncate_down_ge1 lb_sqrt_lower_bound order_less_le_trans[OF zero_less_one]\n        truncate_down_nonneg add_nonneg_nonneg)\n    have monotone: \"x / ?R \\<le> (float_divr prec x ?fR)\"\n    proof -\n      from divide_left_mono[OF \\<open>?fR \\<le> ?R\\<close> \\<open>0 \\<le> real_of_float x\\<close> mult_pos_pos[OF divisor_gt0 \\<open>0 < real_of_float ?fR\\<close>]]\n      have \"x / ?R \\<le> x / ?fR\" .\n      also have \"\\<dots> \\<le> ?DIV\" by (rule float_divr)\n      finally show ?thesis .\n    qed\n\n    show ?thesis\n    proof (cases \"x \\<le> Float 1 1\")\n      case True\n      show ?thesis\n      proof (cases \"?DIV > 1\")\n        case True\n        have \"pi / 2 \\<le> ub_pi prec * Float 1 (- 1)\"\n          unfolding Float_num times_divide_eq_right mult_1_left using pi_boundaries by auto\n        from order_less_le_trans[OF arctan_ubound this, THEN less_imp_le]\n        show ?thesis\n          unfolding ub_arctan.simps Let_def if_not_P[OF \\<open>\\<not> x < 0\\<close>]\n            if_not_P[OF \\<open>\\<not> x \\<le> Float 1 (- 1)\\<close>] if_P[OF \\<open>x \\<le> Float 1 1\\<close>] if_P[OF True] .\n      next\n        case False\n        hence \"real_of_float ?DIV \\<le> 1\" by auto\n\n        have \"0 \\<le> x / ?R\"\n          using \\<open>0 \\<le> real_of_float x\\<close> \\<open>0 < ?R\\<close> unfolding zero_le_divide_iff by auto\n        hence \"0 \\<le> real_of_float ?DIV\"\n          using monotone by (rule order_trans)\n\n        have \"arctan x = 2 * arctan (x / ?R)\"\n          using arctan_half unfolding numeral_2_eq_2 power_Suc2 power_0 mult_1_left .\n        also have \"\\<dots> \\<le> 2 * arctan (?DIV)\"\n          using arctan_monotone'[OF monotone] by (auto intro!: mult_left_mono)\n        also have \"\\<dots> \\<le> (Float 1 1 * ?ub_horner ?DIV)\" unfolding Float_num\n          using arctan_0_1_bounds_round[OF \\<open>0 \\<le> real_of_float ?DIV\\<close> \\<open>real_of_float ?DIV \\<le> 1\\<close>]\n          by (auto intro!: float_round_up_le)\n        finally show ?thesis\n          unfolding ub_arctan.simps Let_def if_not_P[OF \\<open>\\<not> x < 0\\<close>]\n            if_not_P[OF \\<open>\\<not> x \\<le> Float 1 (- 1)\\<close>] if_P[OF \\<open>x \\<le> Float 1 1\\<close>] if_not_P[OF False] .\n      qed\n    next\n      case False\n      hence \"2 < real_of_float x\" by auto\n      hence \"1 \\<le> real_of_float x\" by auto\n      hence \"0 < real_of_float x\" by auto\n      hence \"0 < x\" by auto\n\n      let \"?invx\" = \"float_divl prec 1 x\"\n      have \"0 \\<le> arctan x\"\n        using arctan_monotone'[OF \\<open>0 \\<le> real_of_float x\\<close>] and arctan_tan[of 0, unfolded tan_zero] by auto\n\n      have \"real_of_float ?invx \\<le> 1\"\n        unfolding less_float_def\n        by (rule order_trans[OF float_divl])\n          (auto simp add: \\<open>1 \\<le> real_of_float x\\<close> divide_le_eq_1_pos[OF \\<open>0 < real_of_float x\\<close>])\n      have \"0 \\<le> real_of_float ?invx\"\n        using \\<open>0 < x\\<close> by (intro float_divl_lower_bound) auto\n\n      have \"1 / x \\<noteq> 0\" and \"0 < 1 / x\"\n        using \\<open>0 < real_of_float x\\<close> by auto\n\n      have \"(?lb_horner ?invx) \\<le> arctan (?invx)\"\n        using arctan_0_1_bounds_round[OF \\<open>0 \\<le> real_of_float ?invx\\<close> \\<open>real_of_float ?invx \\<le> 1\\<close>]\n        by (auto intro!: float_round_down_le)\n      also have \"\\<dots> \\<le> arctan (1 / x)\"\n        unfolding one_float.rep_eq[symmetric] by (rule arctan_monotone') (rule float_divl)\n      finally have \"arctan x \\<le> pi / 2 - (?lb_horner ?invx)\"\n        using \\<open>0 \\<le> arctan x\\<close> arctan_inverse[OF \\<open>1 / x \\<noteq> 0\\<close>]\n        unfolding sgn_pos[OF \\<open>0 < 1 / x\\<close>] le_diff_eq by auto\n      moreover\n      have \"pi / 2 \\<le> ub_pi prec * Float 1 (- 1)\"\n        unfolding Float_num times_divide_eq_right mult_1_right\n        using pi_boundaries by auto\n      ultimately\n      show ?thesis\n        unfolding ub_arctan.simps Let_def if_not_P[OF \\<open>\\<not> x < 0\\<close>]\n          if_not_P[OF \\<open>\\<not> x \\<le> Float 1 (- 1)\\<close>] if_not_P[OF False]\n        by (auto intro!: float_round_up_le float_plus_up_le)\n    qed\n  qed\nqed\n\nlemma arctan_boundaries: \"arctan x \\<in> {(lb_arctan prec x) .. (ub_arctan prec x)}\"\nproof (cases \"0 \\<le> x\")\n  case True\n  hence \"0 \\<le> real_of_float x\" by auto\n  show ?thesis\n    using ub_arctan_bound'[OF \\<open>0 \\<le> real_of_float x\\<close>] lb_arctan_bound'[OF \\<open>0 \\<le> real_of_float x\\<close>]\n    unfolding atLeastAtMost_iff by auto\nnext\n  case False\n  let ?mx = \"-x\"\n  from False have \"x < 0\" and \"0 \\<le> real_of_float ?mx\"\n    by auto\n  hence bounds: \"lb_arctan prec ?mx \\<le> arctan ?mx \\<and> arctan ?mx \\<le> ub_arctan prec ?mx\"\n    using ub_arctan_bound'[OF \\<open>0 \\<le> real_of_float ?mx\\<close>] lb_arctan_bound'[OF \\<open>0 \\<le> real_of_float ?mx\\<close>] by auto\n  show ?thesis\n    unfolding minus_float.rep_eq arctan_minus lb_arctan.simps[where x=x]\n      ub_arctan.simps[where x=x] Let_def if_P[OF \\<open>x < 0\\<close>]\n    unfolding atLeastAtMost_iff using bounds[unfolded minus_float.rep_eq arctan_minus]\n    by (simp add: arctan_minus)\nqed\n\nlemma bnds_arctan: \"\\<forall> (x::real) lx ux. (l, u) = (lb_arctan prec lx, ub_arctan prec ux) \\<and> x \\<in> {lx .. ux} \\<longrightarrow> l \\<le> arctan x \\<and> arctan x \\<le> u\"\nproof (rule allI, rule allI, rule allI, rule impI)\n  fix x :: real\n  fix lx ux\n  assume \"(l, u) = (lb_arctan prec lx, ub_arctan prec ux) \\<and> x \\<in> {lx .. ux}\"\n  hence l: \"lb_arctan prec lx = l \"\n    and u: \"ub_arctan prec ux = u\"\n    and x: \"x \\<in> {lx .. ux}\"\n    by auto\n  show \"l \\<le> arctan x \\<and> arctan x \\<le> u\"\n  proof\n    show \"l \\<le> arctan x\"\n    proof -\n      from arctan_boundaries[of lx prec, unfolded l]\n      have \"l \\<le> arctan lx\" by (auto simp del: lb_arctan.simps)\n      also have \"\\<dots> \\<le> arctan x\" using x by (auto intro: arctan_monotone')\n      finally show ?thesis .\n    qed\n    show \"arctan x \\<le> u\"\n    proof -\n      have \"arctan x \\<le> arctan ux\" using x by (auto intro: arctan_monotone')\n      also have \"\\<dots> \\<le> u\" using arctan_boundaries[of ux prec, unfolded u] by (auto simp del: ub_arctan.simps)\n      finally show ?thesis .\n    qed\n  qed\nqed\n\n\nsection \"Sinus and Cosinus\"\n\nsubsection \"Compute the cosinus and sinus series\"\n\nfun ub_sin_cos_aux :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> float \\<Rightarrow> float\"\nand lb_sin_cos_aux :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> float \\<Rightarrow> float\" where\n  \"ub_sin_cos_aux prec 0 i k x = 0\"\n| \"ub_sin_cos_aux prec (Suc n) i k x = float_plus_up prec\n    (rapprox_rat prec 1 k) (-\n      float_round_down prec (x * (lb_sin_cos_aux prec n (i + 2) (k * i * (i + 1)) x)))\"\n| \"lb_sin_cos_aux prec 0 i k x = 0\"\n| \"lb_sin_cos_aux prec (Suc n) i k x = float_plus_down prec\n    (lapprox_rat prec 1 k) (-\n      float_round_up prec (x * (ub_sin_cos_aux prec n (i + 2) (k * i * (i + 1)) x)))\"\n\nlemma cos_aux:\n  shows \"(lb_sin_cos_aux prec n 1 1 (x * x)) \\<le> (\\<Sum> i=0..<n. (- 1) ^ i * (1/(fact (2 * i))) * x ^(2 * i))\" (is \"?lb\")\n  and \"(\\<Sum> i=0..<n. (- 1) ^ i * (1/(fact (2 * i))) * x^(2 * i)) \\<le> (ub_sin_cos_aux prec n 1 1 (x * x))\" (is \"?ub\")\nproof -\n  have \"0 \\<le> real_of_float (x * x)\" by auto\n  let \"?f n\" = \"fact (2 * n) :: nat\"\n  have f_eq: \"?f (Suc n) = ?f n * ((\\<lambda>i. i + 2) ^^ n) 1 * (((\\<lambda>i. i + 2) ^^ n) 1 + 1)\" for n\n  proof -\n    have \"\\<And>m. ((\\<lambda>i. i + 2) ^^ n) m = m + 2 * n\" by (induct n) auto\n    then show ?thesis by auto\n  qed\n  from horner_bounds[where lb=\"lb_sin_cos_aux prec\" and ub=\"ub_sin_cos_aux prec\" and j'=0,\n    OF \\<open>0 \\<le> real_of_float (x * x)\\<close> f_eq lb_sin_cos_aux.simps ub_sin_cos_aux.simps]\n  show ?lb and ?ub\n    by (auto simp add: power_mult power2_eq_square[of \"real_of_float x\"])\nqed\n\nlemma lb_sin_cos_aux_zero_le_one: \"lb_sin_cos_aux prec n i j 0 \\<le> 1\"\n  by (cases j n rule: nat.exhaust[case_product nat.exhaust])\n    (auto intro!: float_plus_down_le order_trans[OF lapprox_rat])\n\nlemma one_le_ub_sin_cos_aux: \"odd n \\<Longrightarrow> 1 \\<le> ub_sin_cos_aux prec n i (Suc 0) 0\"\n  by (cases n) (auto intro!: float_plus_up_le order_trans[OF _ rapprox_rat])\n\nlemma cos_boundaries:\n  assumes \"0 \\<le> real_of_float x\" and \"x \\<le> pi / 2\"\n  shows \"cos x \\<in> {(lb_sin_cos_aux prec (get_even n) 1 1 (x * x)) .. (ub_sin_cos_aux prec (get_odd n) 1 1 (x * x))}\"\nproof (cases \"real_of_float x = 0\")\n  case False\n  hence \"real_of_float x \\<noteq> 0\" by auto\n  hence \"0 < x\" and \"0 < real_of_float x\"\n    using \\<open>0 \\<le> real_of_float x\\<close> by auto\n  have \"0 < x * x\"\n    using \\<open>0 < x\\<close> by simp\n\n  have morph_to_if_power: \"(\\<Sum> i=0..<n. (-1::real) ^ i * (1/(fact (2 * i))) * x ^ (2 * i)) =\n    (\\<Sum> i = 0 ..< 2 * n. (if even(i) then ((- 1) ^ (i div 2))/((fact i)) else 0) * x ^ i)\"\n    (is \"?sum = ?ifsum\") for x n\n  proof -\n    have \"?sum = ?sum + (\\<Sum> j = 0 ..< n. 0)\" by auto\n    also have \"\\<dots> =\n      (\\<Sum> j = 0 ..< n. (- 1) ^ ((2 * j) div 2) / ((fact (2 * j))) * x ^(2 * j)) + (\\<Sum> j = 0 ..< n. 0)\" by auto\n    also have \"\\<dots> = (\\<Sum> i = 0 ..< 2 * n. if even i then (- 1) ^ (i div 2) / ((fact i)) * x ^ i else 0)\"\n      unfolding sum_split_even_odd atLeast0LessThan ..\n    also have \"\\<dots> = (\\<Sum> i = 0 ..< 2 * n. (if even i then (- 1) ^ (i div 2) / ((fact i)) else 0) * x ^ i)\"\n      by (rule sum.cong) auto\n    finally show ?thesis .\n  qed\n\n  { fix n :: nat assume \"0 < n\"\n    hence \"0 < 2 * n\" by auto\n    obtain t where \"0 < t\" and \"t < real_of_float x\" and\n      cos_eq: \"cos x = (\\<Sum> i = 0 ..< 2 * n. (if even(i) then ((- 1) ^ (i div 2))/((fact i)) else 0) * (real_of_float x) ^ i)\n      + (cos (t + 1/2 * (2 * n) * pi) / (fact (2*n))) * (real_of_float x)^(2*n)\"\n      (is \"_ = ?SUM + ?rest / ?fact * ?pow\")\n      using Maclaurin_cos_expansion2[OF \\<open>0 < real_of_float x\\<close> \\<open>0 < 2 * n\\<close>]\n      unfolding cos_coeff_def atLeast0LessThan by auto\n\n    have \"cos t * (- 1) ^ n = cos t * cos (n * pi) + sin t * sin (n * pi)\" by auto\n    also have \"\\<dots> = cos (t + n * pi)\" by (simp add: cos_add)\n    also have \"\\<dots> = ?rest\" by auto\n    finally have \"cos t * (- 1) ^ n = ?rest\" .\n    moreover\n    have \"t \\<le> pi / 2\" using \\<open>t < real_of_float x\\<close> and \\<open>x \\<le> pi / 2\\<close> by auto\n    hence \"0 \\<le> cos t\" using \\<open>0 < t\\<close> and cos_ge_zero by auto\n    ultimately have even: \"even n \\<Longrightarrow> 0 \\<le> ?rest\" and odd: \"odd n \\<Longrightarrow> 0 \\<le> - ?rest \" by auto\n\n    have \"0 < ?fact\" by auto\n    have \"0 < ?pow\" using \\<open>0 < real_of_float x\\<close> by auto\n\n    {\n      assume \"even n\"\n      have \"(lb_sin_cos_aux prec n 1 1 (x * x)) \\<le> ?SUM\"\n        unfolding morph_to_if_power[symmetric] using cos_aux by auto\n      also have \"\\<dots> \\<le> cos x\"\n      proof -\n        from even[OF \\<open>even n\\<close>] \\<open>0 < ?fact\\<close> \\<open>0 < ?pow\\<close>\n        have \"0 \\<le> (?rest / ?fact) * ?pow\" by simp\n        thus ?thesis unfolding cos_eq by auto\n      qed\n      finally have \"(lb_sin_cos_aux prec n 1 1 (x * x)) \\<le> cos x\" .\n    } note lb = this\n\n    {\n      assume \"odd n\"\n      have \"cos x \\<le> ?SUM\"\n      proof -\n        from \\<open>0 < ?fact\\<close> and \\<open>0 < ?pow\\<close> and odd[OF \\<open>odd n\\<close>]\n        have \"0 \\<le> (- ?rest) / ?fact * ?pow\"\n          by (metis mult_nonneg_nonneg divide_nonneg_pos less_imp_le)\n        thus ?thesis unfolding cos_eq by auto\n      qed\n      also have \"\\<dots> \\<le> (ub_sin_cos_aux prec n 1 1 (x * x))\"\n        unfolding morph_to_if_power[symmetric] using cos_aux by auto\n      finally have \"cos x \\<le> (ub_sin_cos_aux prec n 1 1 (x * x))\" .\n    } note ub = this and lb\n  } note ub = this(1) and lb = this(2)\n\n  have \"cos x \\<le> (ub_sin_cos_aux prec (get_odd n) 1 1 (x * x))\"\n    using ub[OF odd_pos[OF get_odd] get_odd] .\n  moreover have \"(lb_sin_cos_aux prec (get_even n) 1 1 (x * x)) \\<le> cos x\"\n  proof (cases \"0 < get_even n\")\n    case True\n    show ?thesis using lb[OF True get_even] .\n  next\n    case False\n    hence \"get_even n = 0\" by auto\n    have \"- (pi / 2) \\<le> x\"\n      by (rule order_trans[OF _ \\<open>0 < real_of_float x\\<close>[THEN less_imp_le]]) auto\n    with \\<open>x \\<le> pi / 2\\<close> show ?thesis\n      unfolding \\<open>get_even n = 0\\<close> lb_sin_cos_aux.simps minus_float.rep_eq zero_float.rep_eq\n      using cos_ge_zero by auto\n  qed\n  ultimately show ?thesis by auto\nnext\n  case True\n  hence \"x = 0\"\n    by transfer\n  thus ?thesis\n    using lb_sin_cos_aux_zero_le_one one_le_ub_sin_cos_aux\n    by simp\nqed\n\nlemma sin_aux:\n  assumes \"0 \\<le> real_of_float x\"\n  shows \"(x * lb_sin_cos_aux prec n 2 1 (x * x)) \\<le>\n      (\\<Sum> i=0..<n. (- 1) ^ i * (1/(fact (2 * i + 1))) * x^(2 * i + 1))\" (is \"?lb\")\n    and \"(\\<Sum> i=0..<n. (- 1) ^ i * (1/(fact (2 * i + 1))) * x^(2 * i + 1)) \\<le>\n      (x * ub_sin_cos_aux prec n 2 1 (x * x))\" (is \"?ub\")\nproof -\n  have \"0 \\<le> real_of_float (x * x)\" by auto\n  let \"?f n\" = \"fact (2 * n + 1) :: nat\"\n  have f_eq: \"?f (Suc n) = ?f n * ((\\<lambda>i. i + 2) ^^ n) 2 * (((\\<lambda>i. i + 2) ^^ n) 2 + 1)\" for n\n  proof -\n    have F: \"\\<And>m. ((\\<lambda>i. i + 2) ^^ n) m = m + 2 * n\" by (induct n) auto\n    show ?thesis\n      unfolding F by auto\n  qed\n  from horner_bounds[where lb=\"lb_sin_cos_aux prec\" and ub=\"ub_sin_cos_aux prec\" and j'=0,\n    OF \\<open>0 \\<le> real_of_float (x * x)\\<close> f_eq lb_sin_cos_aux.simps ub_sin_cos_aux.simps]\n  show \"?lb\" and \"?ub\" using \\<open>0 \\<le> real_of_float x\\<close>\n    apply (simp_all only: power_add power_one_right mult.assoc[symmetric] sum_distrib_right[symmetric])\n    apply (simp_all only: mult.commute[where 'a=real] of_nat_fact)\n    apply (auto intro!: mult_left_mono simp add: power_mult power2_eq_square[of \"real_of_float x\"])\n    done\nqed\n\nlemma sin_boundaries:\n  assumes \"0 \\<le> real_of_float x\"\n    and \"x \\<le> pi / 2\"\n  shows \"sin x \\<in> {(x * lb_sin_cos_aux prec (get_even n) 2 1 (x * x)) .. (x * ub_sin_cos_aux prec (get_odd n) 2 1 (x * x))}\"\nproof (cases \"real_of_float x = 0\")\n  case False\n  hence \"real_of_float x \\<noteq> 0\" by auto\n  hence \"0 < x\" and \"0 < real_of_float x\"\n    using \\<open>0 \\<le> real_of_float x\\<close> by auto\n  have \"0 < x * x\"\n    using \\<open>0 < x\\<close> by simp\n\n  have sum_morph: \"(\\<Sum>j = 0 ..< n. (- 1) ^ (((2 * j + 1) - Suc 0) div 2) / ((fact (2 * j + 1))) * x ^(2 * j + 1)) =\n    (\\<Sum> i = 0 ..< 2 * n. (if even(i) then 0 else ((- 1) ^ ((i - Suc 0) div 2))/((fact i))) * x ^ i)\"\n    (is \"?SUM = _\") for x :: real and n\n  proof -\n    have pow: \"!!i. x ^ (2 * i + 1) = x * x ^ (2 * i)\"\n      by auto\n    have \"?SUM = (\\<Sum> j = 0 ..< n. 0) + ?SUM\"\n      by auto\n    also have \"\\<dots> = (\\<Sum> i = 0 ..< 2 * n. if even i then 0 else (- 1) ^ ((i - Suc 0) div 2) / ((fact i)) * x ^ i)\"\n      unfolding sum_split_even_odd atLeast0LessThan ..\n    also have \"\\<dots> = (\\<Sum> i = 0 ..< 2 * n. (if even i then 0 else (- 1) ^ ((i - Suc 0) div 2) / ((fact i))) * x ^ i)\"\n      by (rule sum.cong) auto\n    finally show ?thesis .\n  qed\n\n  { fix n :: nat assume \"0 < n\"\n    hence \"0 < 2 * n + 1\" by auto\n    obtain t where \"0 < t\" and \"t < real_of_float x\" and\n      sin_eq: \"sin x = (\\<Sum> i = 0 ..< 2 * n + 1. (if even(i) then 0 else ((- 1) ^ ((i - Suc 0) div 2))/((fact i))) * (real_of_float x) ^ i)\n      + (sin (t + 1/2 * (2 * n + 1) * pi) / (fact (2*n + 1))) * (real_of_float x)^(2*n + 1)\"\n      (is \"_ = ?SUM + ?rest / ?fact * ?pow\")\n      using Maclaurin_sin_expansion3[OF \\<open>0 < 2 * n + 1\\<close> \\<open>0 < real_of_float x\\<close>]\n      unfolding sin_coeff_def atLeast0LessThan by auto\n\n    have \"?rest = cos t * (- 1) ^ n\"\n      unfolding sin_add cos_add of_nat_add distrib_right distrib_left by auto\n    moreover\n    have \"t \\<le> pi / 2\"\n      using \\<open>t < real_of_float x\\<close> and \\<open>x \\<le> pi / 2\\<close> by auto\n    hence \"0 \\<le> cos t\"\n      using \\<open>0 < t\\<close> and cos_ge_zero by auto\n    ultimately have even: \"even n \\<Longrightarrow> 0 \\<le> ?rest\" and odd: \"odd n \\<Longrightarrow> 0 \\<le> - ?rest\"\n      by auto\n\n    have \"0 < ?fact\"\n      by (simp del: fact_Suc)\n    have \"0 < ?pow\"\n      using \\<open>0 < real_of_float x\\<close> by (rule zero_less_power)\n\n    {\n      assume \"even n\"\n      have \"(x * lb_sin_cos_aux prec n 2 1 (x * x)) \\<le>\n            (\\<Sum> i = 0 ..< 2 * n. (if even(i) then 0 else ((- 1) ^ ((i - Suc 0) div 2))/((fact i))) * (real_of_float x) ^ i)\"\n        using sin_aux[OF \\<open>0 \\<le> real_of_float x\\<close>] unfolding sum_morph[symmetric] by auto\n      also have \"\\<dots> \\<le> ?SUM\" by auto\n      also have \"\\<dots> \\<le> sin x\"\n      proof -\n        from even[OF \\<open>even n\\<close>] \\<open>0 < ?fact\\<close> \\<open>0 < ?pow\\<close>\n        have \"0 \\<le> (?rest / ?fact) * ?pow\" by simp\n        thus ?thesis unfolding sin_eq by auto\n      qed\n      finally have \"(x * lb_sin_cos_aux prec n 2 1 (x * x)) \\<le> sin x\" .\n    } note lb = this\n\n    {\n      assume \"odd n\"\n      have \"sin x \\<le> ?SUM\"\n      proof -\n        from \\<open>0 < ?fact\\<close> and \\<open>0 < ?pow\\<close> and odd[OF \\<open>odd n\\<close>]\n        have \"0 \\<le> (- ?rest) / ?fact * ?pow\"\n          by (metis mult_nonneg_nonneg divide_nonneg_pos less_imp_le)\n        thus ?thesis unfolding sin_eq by auto\n      qed\n      also have \"\\<dots> \\<le> (\\<Sum> i = 0 ..< 2 * n. (if even(i) then 0 else ((- 1) ^ ((i - Suc 0) div 2))/((fact i))) * (real_of_float x) ^ i)\"\n         by auto\n      also have \"\\<dots> \\<le> (x * ub_sin_cos_aux prec n 2 1 (x * x))\"\n        using sin_aux[OF \\<open>0 \\<le> real_of_float x\\<close>] unfolding sum_morph[symmetric] by auto\n      finally have \"sin x \\<le> (x * ub_sin_cos_aux prec n 2 1 (x * x))\" .\n    } note ub = this and lb\n  } note ub = this(1) and lb = this(2)\n\n  have \"sin x \\<le> (x * ub_sin_cos_aux prec (get_odd n) 2 1 (x * x))\"\n    using ub[OF odd_pos[OF get_odd] get_odd] .\n  moreover have \"(x * lb_sin_cos_aux prec (get_even n) 2 1 (x * x)) \\<le> sin x\"\n  proof (cases \"0 < get_even n\")\n    case True\n    show ?thesis\n      using lb[OF True get_even] .\n  next\n    case False\n    hence \"get_even n = 0\" by auto\n    with \\<open>x \\<le> pi / 2\\<close> \\<open>0 \\<le> real_of_float x\\<close>\n    show ?thesis\n      unfolding \\<open>get_even n = 0\\<close> ub_sin_cos_aux.simps minus_float.rep_eq\n      using sin_ge_zero by auto\n  qed\n  ultimately show ?thesis by auto\nnext\n  case True\n  show ?thesis\n  proof (cases \"n = 0\")\n    case True\n    thus ?thesis\n      unfolding \\<open>n = 0\\<close> get_even_def get_odd_def\n      using \\<open>real_of_float x = 0\\<close> lapprox_rat[where x=\"-1\" and y=1] by auto\n  next\n    case False\n    with not0_implies_Suc obtain m where \"n = Suc m\" by blast\n    thus ?thesis\n      unfolding \\<open>n = Suc m\\<close> get_even_def get_odd_def\n      using \\<open>real_of_float x = 0\\<close> rapprox_rat[where x=1 and y=1] lapprox_rat[where x=1 and y=1]\n      by (cases \"even (Suc m)\") auto\n  qed\nqed\n\n\nsubsection \"Compute the cosinus in the entire domain\"\n\ndefinition lb_cos :: \"nat \\<Rightarrow> float \\<Rightarrow> float\" where\n\"lb_cos prec x = (let\n    horner = \\<lambda> x. lb_sin_cos_aux prec (get_even (prec div 4 + 1)) 1 1 (x * x) ;\n    half = \\<lambda> x. if x < 0 then - 1 else float_plus_down prec (Float 1 1 * x * x) (- 1)\n  in if x < Float 1 (- 1) then horner x\nelse if x < 1          then half (horner (x * Float 1 (- 1)))\n                       else half (half (horner (x * Float 1 (- 2)))))\"\n\ndefinition ub_cos :: \"nat \\<Rightarrow> float \\<Rightarrow> float\" where\n\"ub_cos prec x = (let\n    horner = \\<lambda> x. ub_sin_cos_aux prec (get_odd (prec div 4 + 1)) 1 1 (x * x) ;\n    half = \\<lambda> x. float_plus_up prec (Float 1 1 * x * x) (- 1)\n  in if x < Float 1 (- 1) then horner x\nelse if x < 1          then half (horner (x * Float 1 (- 1)))\n                       else half (half (horner (x * Float 1 (- 2)))))\"\n\nlemma lb_cos:\n  assumes \"0 \\<le> real_of_float x\" and \"x \\<le> pi\"\n  shows \"cos x \\<in> {(lb_cos prec x) .. (ub_cos prec x)}\" (is \"?cos x \\<in> {(?lb x) .. (?ub x) }\")\nproof -\n  have x_half[symmetric]: \"cos x = 2 * cos (x / 2) * cos (x / 2) - 1\" for x :: real\n  proof -\n    have \"cos x = cos (x / 2 + x / 2)\"\n      by auto\n    also have \"\\<dots> = cos (x / 2) * cos (x / 2) + sin (x / 2) * sin (x / 2) - sin (x / 2) * sin (x / 2) + cos (x / 2) * cos (x / 2) - 1\"\n      unfolding cos_add by auto\n    also have \"\\<dots> = 2 * cos (x / 2) * cos (x / 2) - 1\"\n      by algebra\n    finally show ?thesis .\n  qed\n\n  have \"\\<not> x < 0\" using \\<open>0 \\<le> real_of_float x\\<close> by auto\n  let \"?ub_horner x\" = \"ub_sin_cos_aux prec (get_odd (prec div 4 + 1)) 1 1 (x * x)\"\n  let \"?lb_horner x\" = \"lb_sin_cos_aux prec (get_even (prec div 4 + 1)) 1 1 (x * x)\"\n  let \"?ub_half x\" = \"float_plus_up prec (Float 1 1 * x * x) (- 1)\"\n  let \"?lb_half x\" = \"if x < 0 then - 1 else float_plus_down prec (Float 1 1 * x * x) (- 1)\"\n\n  show ?thesis\n  proof (cases \"x < Float 1 (- 1)\")\n    case True\n    hence \"x \\<le> pi / 2\"\n      using pi_ge_two by auto\n    show ?thesis\n      unfolding lb_cos_def[where x=x] ub_cos_def[where x=x]\n        if_not_P[OF \\<open>\\<not> x < 0\\<close>] if_P[OF \\<open>x < Float 1 (- 1)\\<close>] Let_def\n      using cos_boundaries[OF \\<open>0 \\<le> real_of_float x\\<close> \\<open>x \\<le> pi / 2\\<close>] .\n  next\n    case False\n    { fix y x :: float let ?x2 = \"(x * Float 1 (- 1))\"\n      assume \"y \\<le> cos ?x2\" and \"-pi \\<le> x\" and \"x \\<le> pi\"\n      hence \"- (pi / 2) \\<le> ?x2\" and \"?x2 \\<le> pi / 2\"\n        using pi_ge_two unfolding Float_num by auto\n      hence \"0 \\<le> cos ?x2\"\n        by (rule cos_ge_zero)\n\n      have \"(?lb_half y) \\<le> cos x\"\n      proof (cases \"y < 0\")\n        case True\n        show ?thesis\n          using cos_ge_minus_one unfolding if_P[OF True] by auto\n      next\n        case False\n        hence \"0 \\<le> real_of_float y\" by auto\n        from mult_mono[OF \\<open>y \\<le> cos ?x2\\<close> \\<open>y \\<le> cos ?x2\\<close> \\<open>0 \\<le> cos ?x2\\<close> this]\n        have \"real_of_float y * real_of_float y \\<le> cos ?x2 * cos ?x2\" .\n        hence \"2 * real_of_float y * real_of_float y \\<le> 2 * cos ?x2 * cos ?x2\"\n          by auto\n        hence \"2 * real_of_float y * real_of_float y - 1 \\<le> 2 * cos (x / 2) * cos (x / 2) - 1\"\n          unfolding Float_num by auto\n        thus ?thesis\n          unfolding if_not_P[OF False] x_half Float_num\n          by (auto intro!: float_plus_down_le)\n      qed\n    } note lb_half = this\n\n    { fix y x :: float let ?x2 = \"(x * Float 1 (- 1))\"\n      assume ub: \"cos ?x2 \\<le> y\" and \"- pi \\<le> x\" and \"x \\<le> pi\"\n      hence \"- (pi / 2) \\<le> ?x2\" and \"?x2 \\<le> pi / 2\"\n        using pi_ge_two unfolding Float_num by auto\n      hence \"0 \\<le> cos ?x2\" by (rule cos_ge_zero)\n\n      have \"cos x \\<le> (?ub_half y)\"\n      proof -\n        have \"0 \\<le> real_of_float y\"\n          using \\<open>0 \\<le> cos ?x2\\<close> ub by (rule order_trans)\n        from mult_mono[OF ub ub this \\<open>0 \\<le> cos ?x2\\<close>]\n        have \"cos ?x2 * cos ?x2 \\<le> real_of_float y * real_of_float y\" .\n        hence \"2 * cos ?x2 * cos ?x2 \\<le> 2 * real_of_float y * real_of_float y\"\n          by auto\n        hence \"2 * cos (x / 2) * cos (x / 2) - 1 \\<le> 2 * real_of_float y * real_of_float y - 1\"\n          unfolding Float_num by auto\n        thus ?thesis\n          unfolding x_half Float_num\n          by (auto intro!: float_plus_up_le)\n      qed\n    } note ub_half = this\n\n    let ?x2 = \"x * Float 1 (- 1)\"\n    let ?x4 = \"x * Float 1 (- 1) * Float 1 (- 1)\"\n\n    have \"-pi \\<le> x\"\n      using pi_ge_zero[THEN le_imp_neg_le, unfolded minus_zero] \\<open>0 \\<le> real_of_float x\\<close>\n      by (rule order_trans)\n\n    show ?thesis\n    proof (cases \"x < 1\")\n      case True\n      hence \"real_of_float x \\<le> 1\" by auto\n      have \"0 \\<le> real_of_float ?x2\" and \"?x2 \\<le> pi / 2\"\n        using pi_ge_two \\<open>0 \\<le> real_of_float x\\<close> using assms by auto\n      from cos_boundaries[OF this]\n      have lb: \"(?lb_horner ?x2) \\<le> ?cos ?x2\" and ub: \"?cos ?x2 \\<le> (?ub_horner ?x2)\"\n        by auto\n\n      have \"(?lb x) \\<le> ?cos x\"\n      proof -\n        from lb_half[OF lb \\<open>-pi \\<le> x\\<close> \\<open>x \\<le> pi\\<close>]\n        show ?thesis\n          unfolding lb_cos_def[where x=x] Let_def\n          using \\<open>\\<not> x < 0\\<close> \\<open>\\<not> x < Float 1 (- 1)\\<close> \\<open>x < 1\\<close> by auto\n      qed\n      moreover have \"?cos x \\<le> (?ub x)\"\n      proof -\n        from ub_half[OF ub \\<open>-pi \\<le> x\\<close> \\<open>x \\<le> pi\\<close>]\n        show ?thesis\n          unfolding ub_cos_def[where x=x] Let_def\n          using \\<open>\\<not> x < 0\\<close> \\<open>\\<not> x < Float 1 (- 1)\\<close> \\<open>x < 1\\<close> by auto\n      qed\n      ultimately show ?thesis by auto\n    next\n      case False\n      have \"0 \\<le> real_of_float ?x4\" and \"?x4 \\<le> pi / 2\"\n        using pi_ge_two \\<open>0 \\<le> real_of_float x\\<close> \\<open>x \\<le> pi\\<close> unfolding Float_num by auto\n      from cos_boundaries[OF this]\n      have lb: \"(?lb_horner ?x4) \\<le> ?cos ?x4\" and ub: \"?cos ?x4 \\<le> (?ub_horner ?x4)\"\n        by auto\n\n      have eq_4: \"?x2 * Float 1 (- 1) = x * Float 1 (- 2)\"\n        by transfer simp\n\n      have \"(?lb x) \\<le> ?cos x\"\n      proof -\n        have \"-pi \\<le> ?x2\" and \"?x2 \\<le> pi\"\n          using pi_ge_two \\<open>0 \\<le> real_of_float x\\<close> \\<open>x \\<le> pi\\<close> by auto\n        from lb_half[OF lb_half[OF lb this] \\<open>-pi \\<le> x\\<close> \\<open>x \\<le> pi\\<close>, unfolded eq_4]\n        show ?thesis\n          unfolding lb_cos_def[where x=x] if_not_P[OF \\<open>\\<not> x < 0\\<close>]\n            if_not_P[OF \\<open>\\<not> x < Float 1 (- 1)\\<close>] if_not_P[OF \\<open>\\<not> x < 1\\<close>] Let_def .\n      qed\n      moreover have \"?cos x \\<le> (?ub x)\"\n      proof -\n        have \"-pi \\<le> ?x2\" and \"?x2 \\<le> pi\"\n          using pi_ge_two \\<open>0 \\<le> real_of_float x\\<close> \\<open> x \\<le> pi\\<close> by auto\n        from ub_half[OF ub_half[OF ub this] \\<open>-pi \\<le> x\\<close> \\<open>x \\<le> pi\\<close>, unfolded eq_4]\n        show ?thesis\n          unfolding ub_cos_def[where x=x] if_not_P[OF \\<open>\\<not> x < 0\\<close>]\n            if_not_P[OF \\<open>\\<not> x < Float 1 (- 1)\\<close>] if_not_P[OF \\<open>\\<not> x < 1\\<close>] Let_def .\n      qed\n      ultimately show ?thesis by auto\n    qed\n  qed\nqed\n\nlemma lb_cos_minus:\n  assumes \"-pi \\<le> x\"\n    and \"real_of_float x \\<le> 0\"\n  shows \"cos (real_of_float(-x)) \\<in> {(lb_cos prec (-x)) .. (ub_cos prec (-x))}\"\nproof -\n  have \"0 \\<le> real_of_float (-x)\" and \"(-x) \\<le> pi\"\n    using \\<open>-pi \\<le> x\\<close> \\<open>real_of_float x \\<le> 0\\<close> by auto\n  from lb_cos[OF this] show ?thesis .\nqed\n\ndefinition bnds_cos :: \"nat \\<Rightarrow> float \\<Rightarrow> float \\<Rightarrow> float * float\" where\n\"bnds_cos prec lx ux = (let\n    lpi = float_round_down prec (lb_pi prec) ;\n    upi = float_round_up prec (ub_pi prec) ;\n    k = floor_fl (float_divr prec (lx + lpi) (2 * lpi)) ;\n    lx = float_plus_down prec lx (- k * 2 * (if k < 0 then lpi else upi)) ;\n    ux = float_plus_up prec ux (- k * 2 * (if k < 0 then upi else lpi))\n  in   if - lpi \\<le> lx \\<and> ux \\<le> 0    then (lb_cos prec (-lx), ub_cos prec (-ux))\n  else if 0 \\<le> lx \\<and> ux \\<le> lpi      then (lb_cos prec ux, ub_cos prec lx)\n  else if - lpi \\<le> lx \\<and> ux \\<le> lpi  then (min (lb_cos prec (-lx)) (lb_cos prec ux), Float 1 0)\n  else if 0 \\<le> lx \\<and> ux \\<le> 2 * lpi  then (Float (- 1) 0, max (ub_cos prec lx) (ub_cos prec (- (ux - 2 * lpi))))\n  else if -2 * lpi \\<le> lx \\<and> ux \\<le> 0 then (Float (- 1) 0, max (ub_cos prec (lx + 2 * lpi)) (ub_cos prec (-ux)))\n                                 else (Float (- 1) 0, Float 1 0))\"\n\nlemma floor_int: obtains k :: int where \"real_of_int k = (floor_fl f)\"\n  by (simp add: floor_fl_def)\n\nlemma cos_periodic_nat[simp]:\n  fixes n :: nat\n  shows \"cos (x + n * (2 * pi)) = cos x\"\nproof (induct n arbitrary: x)\n  case 0\n  then show ?case by simp\nnext\n  case (Suc n)\n  have split_pi_off: \"x + (Suc n) * (2 * pi) = (x + n * (2 * pi)) + 2 * pi\"\n    unfolding Suc_eq_plus1 of_nat_add of_int_1 distrib_right by auto\n  show ?case\n    unfolding split_pi_off using Suc by auto\nqed\n\nlemma cos_periodic_int[simp]:\n  fixes i :: int\n  shows \"cos (x + i * (2 * pi)) = cos x\"\nproof (cases \"0 \\<le> i\")\n  case True\n  hence i_nat: \"real_of_int i = nat i\" by auto\n  show ?thesis\n    unfolding i_nat by auto\nnext\n  case False\n    hence i_nat: \"i = - real (nat (-i))\" by auto\n  have \"cos x = cos (x + i * (2 * pi) - i * (2 * pi))\"\n    by auto\n  also have \"\\<dots> = cos (x + i * (2 * pi))\"\n    unfolding i_nat mult_minus_left diff_minus_eq_add by (rule cos_periodic_nat)\n  finally show ?thesis by auto\nqed\n\nlemma bnds_cos: \"\\<forall>(x::real) lx ux. (l, u) =\n  bnds_cos prec lx ux \\<and> x \\<in> {lx .. ux} \\<longrightarrow> l \\<le> cos x \\<and> cos x \\<le> u\"\nproof (rule allI | rule impI | erule conjE)+\n  fix x :: real\n  fix lx ux\n  assume bnds: \"(l, u) = bnds_cos prec lx ux\" and x: \"x \\<in> {lx .. ux}\"\n\n  let ?lpi = \"float_round_down prec (lb_pi prec)\"\n  let ?upi = \"float_round_up prec (ub_pi prec)\"\n  let ?k = \"floor_fl (float_divr prec (lx + ?lpi) (2 * ?lpi))\"\n  let ?lx2 = \"(- ?k * 2 * (if ?k < 0 then ?lpi else ?upi))\"\n  let ?ux2 = \"(- ?k * 2 * (if ?k < 0 then ?upi else ?lpi))\"\n  let ?lx = \"float_plus_down prec lx ?lx2\"\n  let ?ux = \"float_plus_up prec ux ?ux2\"\n\n  obtain k :: int where k: \"k = real_of_float ?k\"\n    by (rule floor_int)\n\n  have upi: \"pi \\<le> ?upi\" and lpi: \"?lpi \\<le> pi\"\n    using float_round_up[of \"ub_pi prec\" prec] pi_boundaries[of prec]\n      float_round_down[of prec \"lb_pi prec\"]\n    by auto\n  hence \"lx + ?lx2 \\<le> x - k * (2 * pi) \\<and> x - k * (2 * pi) \\<le> ux + ?ux2\"\n    using x\n    by (cases \"k = 0\")\n      (auto intro!: add_mono\n        simp add: k [symmetric] uminus_add_conv_diff [symmetric]\n        simp del: float_of_numeral uminus_add_conv_diff)\n  hence \"?lx \\<le> x - k * (2 * pi) \\<and> x - k * (2 * pi) \\<le> ?ux\"\n    by (auto intro!: float_plus_down_le float_plus_up_le)\n  note lx = this[THEN conjunct1] and ux = this[THEN conjunct2]\n  hence lx_less_ux: \"?lx \\<le> real_of_float ?ux\" by (rule order_trans)\n\n  { assume \"- ?lpi \\<le> ?lx\" and x_le_0: \"x - k * (2 * pi) \\<le> 0\"\n    with lpi[THEN le_imp_neg_le] lx\n    have pi_lx: \"- pi \\<le> ?lx\" and lx_0: \"real_of_float ?lx \\<le> 0\"\n      by simp_all\n\n    have \"(lb_cos prec (- ?lx)) \\<le> cos (real_of_float (- ?lx))\"\n      using lb_cos_minus[OF pi_lx lx_0] by simp\n    also have \"\\<dots> \\<le> cos (x + (-k) * (2 * pi))\"\n      using cos_monotone_minus_pi_0'[OF pi_lx lx x_le_0]\n      by (simp only: uminus_float.rep_eq of_int_minus\n        cos_minus mult_minus_left) simp\n    finally have \"(lb_cos prec (- ?lx)) \\<le> cos x\"\n      unfolding cos_periodic_int . }\n  note negative_lx = this\n\n  { assume \"0 \\<le> ?lx\" and pi_x: \"x - k * (2 * pi) \\<le> pi\"\n    with lx\n    have pi_lx: \"?lx \\<le> pi\" and lx_0: \"0 \\<le> real_of_float ?lx\"\n      by auto\n\n    have \"cos (x + (-k) * (2 * pi)) \\<le> cos ?lx\"\n      using cos_monotone_0_pi_le[OF lx_0 lx pi_x]\n      by (simp only: of_int_minus\n        cos_minus mult_minus_left) simp\n    also have \"\\<dots> \\<le> (ub_cos prec ?lx)\"\n      using lb_cos[OF lx_0 pi_lx] by simp\n    finally have \"cos x \\<le> (ub_cos prec ?lx)\"\n      unfolding cos_periodic_int . }\n  note positive_lx = this\n\n  { assume pi_x: \"- pi \\<le> x - k * (2 * pi)\" and \"?ux \\<le> 0\"\n    with ux\n    have pi_ux: \"- pi \\<le> ?ux\" and ux_0: \"real_of_float ?ux \\<le> 0\"\n      by simp_all\n\n    have \"cos (x + (-k) * (2 * pi)) \\<le> cos (real_of_float (- ?ux))\"\n      using cos_monotone_minus_pi_0'[OF pi_x ux ux_0]\n      by (simp only: uminus_float.rep_eq of_int_minus\n          cos_minus mult_minus_left) simp\n    also have \"\\<dots> \\<le> (ub_cos prec (- ?ux))\"\n      using lb_cos_minus[OF pi_ux ux_0, of prec] by simp\n    finally have \"cos x \\<le> (ub_cos prec (- ?ux))\"\n      unfolding cos_periodic_int . }\n  note negative_ux = this\n\n  { assume \"?ux \\<le> ?lpi\" and x_ge_0: \"0 \\<le> x - k * (2 * pi)\"\n    with lpi ux\n    have pi_ux: \"?ux \\<le> pi\" and ux_0: \"0 \\<le> real_of_float ?ux\"\n      by simp_all\n\n    have \"(lb_cos prec ?ux) \\<le> cos ?ux\"\n      using lb_cos[OF ux_0 pi_ux] by simp\n    also have \"\\<dots> \\<le> cos (x + (-k) * (2 * pi))\"\n      using cos_monotone_0_pi_le[OF x_ge_0 ux pi_ux]\n      by (simp only: of_int_minus\n        cos_minus mult_minus_left) simp\n    finally have \"(lb_cos prec ?ux) \\<le> cos x\"\n      unfolding cos_periodic_int . }\n  note positive_ux = this\n\n  show \"l \\<le> cos x \\<and> cos x \\<le> u\"\n  proof (cases \"- ?lpi \\<le> ?lx \\<and> ?ux \\<le> 0\")\n    case True\n    with bnds have l: \"l = lb_cos prec (-?lx)\" and u: \"u = ub_cos prec (-?ux)\"\n      by (auto simp add: bnds_cos_def Let_def)\n    from True lpi[THEN le_imp_neg_le] lx ux\n    have \"- pi \\<le> x - k * (2 * pi)\" and \"x - k * (2 * pi) \\<le> 0\"\n      by auto\n    with True negative_ux negative_lx show ?thesis\n      unfolding l u by simp\n  next\n    case 1: False\n    show ?thesis\n    proof (cases \"0 \\<le> ?lx \\<and> ?ux \\<le> ?lpi\")\n      case True with bnds 1\n      have l: \"l = lb_cos prec ?ux\"\n        and u: \"u = ub_cos prec ?lx\"\n        by (auto simp add: bnds_cos_def Let_def)\n      from True lpi lx ux\n      have \"0 \\<le> x - k * (2 * pi)\" and \"x - k * (2 * pi) \\<le> pi\"\n        by auto\n      with True positive_ux positive_lx show ?thesis\n        unfolding l u by simp\n    next\n      case 2: False\n      show ?thesis\n      proof (cases \"- ?lpi \\<le> ?lx \\<and> ?ux \\<le> ?lpi\")\n        case Cond: True\n        with bnds 1 2 have l: \"l = min (lb_cos prec (-?lx)) (lb_cos prec ?ux)\"\n          and u: \"u = Float 1 0\"\n          by (auto simp add: bnds_cos_def Let_def)\n        show ?thesis\n          unfolding u l using negative_lx positive_ux Cond\n          by (cases \"x - k * (2 * pi) < 0\") (auto simp add: real_of_float_min)\n      next\n        case 3: False\n        show ?thesis\n        proof (cases \"0 \\<le> ?lx \\<and> ?ux \\<le> 2 * ?lpi\")\n          case Cond: True\n          with bnds 1 2 3\n          have l: \"l = Float (- 1) 0\"\n            and u: \"u = max (ub_cos prec ?lx) (ub_cos prec (- (?ux - 2 * ?lpi)))\"\n            by (auto simp add: bnds_cos_def Let_def)\n\n          have \"cos x \\<le> real_of_float u\"\n          proof (cases \"x - k * (2 * pi) < pi\")\n            case True\n            hence \"x - k * (2 * pi) \\<le> pi\" by simp\n            from positive_lx[OF Cond[THEN conjunct1] this] show ?thesis\n              unfolding u by (simp add: real_of_float_max)\n          next\n            case False\n            hence \"pi \\<le> x - k * (2 * pi)\" by simp\n            hence pi_x: \"- pi \\<le> x - k * (2 * pi) - 2 * pi\" by simp\n\n            have \"?ux \\<le> 2 * pi\"\n              using Cond lpi by auto\n            hence \"x - k * (2 * pi) - 2 * pi \\<le> 0\"\n              using ux by simp\n\n            have ux_0: \"real_of_float (?ux - 2 * ?lpi) \\<le> 0\"\n              using Cond by auto\n\n            from 2 and Cond have \"\\<not> ?ux \\<le> ?lpi\" by auto\n            hence \"- ?lpi \\<le> ?ux - 2 * ?lpi\" by auto\n            hence pi_ux: \"- pi \\<le> (?ux - 2 * ?lpi)\"\n              using lpi[THEN le_imp_neg_le] by auto\n\n            have x_le_ux: \"x - k * (2 * pi) - 2 * pi \\<le> (?ux - 2 * ?lpi)\"\n              using ux lpi by auto\n            have \"cos x = cos (x + (-k) * (2 * pi) + (-1::int) * (2 * pi))\"\n              unfolding cos_periodic_int ..\n            also have \"\\<dots> \\<le> cos ((?ux - 2 * ?lpi))\"\n              using cos_monotone_minus_pi_0'[OF pi_x x_le_ux ux_0]\n              by (simp only: minus_float.rep_eq of_int_minus of_int_1\n                mult_minus_left mult_1_left) simp\n            also have \"\\<dots> = cos ((- (?ux - 2 * ?lpi)))\"\n              unfolding uminus_float.rep_eq cos_minus ..\n            also have \"\\<dots> \\<le> (ub_cos prec (- (?ux - 2 * ?lpi)))\"\n              using lb_cos_minus[OF pi_ux ux_0] by simp\n            finally show ?thesis unfolding u by (simp add: real_of_float_max)\n          qed\n          thus ?thesis unfolding l by auto\n        next\n          case 4: False\n          show ?thesis\n          proof (cases \"-2 * ?lpi \\<le> ?lx \\<and> ?ux \\<le> 0\")\n            case Cond: True\n            with bnds 1 2 3 4 have l: \"l = Float (- 1) 0\"\n              and u: \"u = max (ub_cos prec (?lx + 2 * ?lpi)) (ub_cos prec (-?ux))\"\n              by (auto simp add: bnds_cos_def Let_def)\n\n            have \"cos x \\<le> u\"\n            proof (cases \"-pi < x - k * (2 * pi)\")\n              case True\n              hence \"-pi \\<le> x - k * (2 * pi)\" by simp\n              from negative_ux[OF this Cond[THEN conjunct2]] show ?thesis\n                unfolding u by (simp add: real_of_float_max)\n            next\n              case False\n              hence \"x - k * (2 * pi) \\<le> -pi\" by simp\n              hence pi_x: \"x - k * (2 * pi) + 2 * pi \\<le> pi\" by simp\n\n              have \"-2 * pi \\<le> ?lx\" using Cond lpi by auto\n\n              hence \"0 \\<le> x - k * (2 * pi) + 2 * pi\" using lx by simp\n\n              have lx_0: \"0 \\<le> real_of_float (?lx + 2 * ?lpi)\"\n                using Cond lpi by auto\n\n              from 1 and Cond have \"\\<not> -?lpi \\<le> ?lx\" by auto\n              hence \"?lx + 2 * ?lpi \\<le> ?lpi\" by auto\n              hence pi_lx: \"(?lx + 2 * ?lpi) \\<le> pi\"\n                using lpi[THEN le_imp_neg_le] by auto\n\n              have lx_le_x: \"(?lx + 2 * ?lpi) \\<le> x - k * (2 * pi) + 2 * pi\"\n                using lx lpi by auto\n\n              have \"cos x = cos (x + (-k) * (2 * pi) + (1 :: int) * (2 * pi))\"\n                unfolding cos_periodic_int ..\n              also have \"\\<dots> \\<le> cos ((?lx + 2 * ?lpi))\"\n                using cos_monotone_0_pi_le[OF lx_0 lx_le_x pi_x]\n                by (simp only: minus_float.rep_eq of_int_minus of_int_1\n                  mult_minus_left mult_1_left) simp\n              also have \"\\<dots> \\<le> (ub_cos prec (?lx + 2 * ?lpi))\"\n                using lb_cos[OF lx_0 pi_lx] by simp\n              finally show ?thesis unfolding u by (simp add: real_of_float_max)\n            qed\n            thus ?thesis unfolding l by auto\n          next\n            case False\n            with bnds 1 2 3 4 show ?thesis\n              by (auto simp add: bnds_cos_def Let_def)\n          qed\n        qed\n      qed\n    qed\n  qed\nqed\n\n\nsection \"Exponential function\"\n\nsubsection \"Compute the series of the exponential function\"\n\nfun ub_exp_horner :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> float \\<Rightarrow> float\"\n  and lb_exp_horner :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> float \\<Rightarrow> float\"\nwhere\n\"ub_exp_horner prec 0 i k x       = 0\" |\n\"ub_exp_horner prec (Suc n) i k x = float_plus_up prec\n    (rapprox_rat prec 1 (int k)) (float_round_up prec (x * lb_exp_horner prec n (i + 1) (k * i) x))\" |\n\"lb_exp_horner prec 0 i k x       = 0\" |\n\"lb_exp_horner prec (Suc n) i k x = float_plus_down prec\n    (lapprox_rat prec 1 (int k)) (float_round_down prec (x * ub_exp_horner prec n (i + 1) (k * i) x))\"\n\nlemma bnds_exp_horner:\n  assumes \"real_of_float x \\<le> 0\"\n  shows \"exp x \\<in> {lb_exp_horner prec (get_even n) 1 1 x .. ub_exp_horner prec (get_odd n) 1 1 x}\"\nproof -\n  have f_eq: \"fact (Suc n) = fact n * ((\\<lambda>i::nat. i + 1) ^^ n) 1\" for n\n  proof -\n    have F: \"\\<And> m. ((\\<lambda>i. i + 1) ^^ n) m = n + m\"\n      by (induct n) auto\n    show ?thesis\n      unfolding F by auto\n  qed\n\n  note bounds = horner_bounds_nonpos[where f=\"fact\" and lb=\"lb_exp_horner prec\" and ub=\"ub_exp_horner prec\" and j'=0 and s=1,\n    OF assms f_eq lb_exp_horner.simps ub_exp_horner.simps]\n\n  have \"lb_exp_horner prec (get_even n) 1 1 x \\<le> exp x\"\n  proof -\n    have \"lb_exp_horner prec (get_even n) 1 1 x \\<le> (\\<Sum>j = 0..<get_even n. 1 / (fact j) * real_of_float x ^ j)\"\n      using bounds(1) by auto\n    also have \"\\<dots> \\<le> exp x\"\n    proof -\n      obtain t where \"\\<bar>t\\<bar> \\<le> \\<bar>real_of_float x\\<bar>\" and \"exp x = (\\<Sum>m = 0..<get_even n. real_of_float x ^ m / (fact m)) + exp t / (fact (get_even n)) * (real_of_float x) ^ (get_even n)\"\n        using Maclaurin_exp_le unfolding atLeast0LessThan by blast\n      moreover have \"0 \\<le> exp t / (fact (get_even n)) * (real_of_float x) ^ (get_even n)\"\n        by (auto simp: zero_le_even_power)\n      ultimately show ?thesis using get_odd exp_gt_zero by auto\n    qed\n    finally show ?thesis .\n  qed\n  moreover\n  have \"exp x \\<le> ub_exp_horner prec (get_odd n) 1 1 x\"\n  proof -\n    have x_less_zero: \"real_of_float x ^ get_odd n \\<le> 0\"\n    proof (cases \"real_of_float x = 0\")\n      case True\n      have \"(get_odd n) \\<noteq> 0\" using get_odd[THEN odd_pos] by auto\n      thus ?thesis unfolding True power_0_left by auto\n    next\n      case False hence \"real_of_float x < 0\" using \\<open>real_of_float x \\<le> 0\\<close> by auto\n      show ?thesis by (rule less_imp_le, auto simp add: \\<open>real_of_float x < 0\\<close>)\n    qed\n    obtain t where \"\\<bar>t\\<bar> \\<le> \\<bar>real_of_float x\\<bar>\"\n      and \"exp x = (\\<Sum>m = 0..<get_odd n. (real_of_float x) ^ m / (fact m)) + exp t / (fact (get_odd n)) * (real_of_float x) ^ (get_odd n)\"\n      using Maclaurin_exp_le unfolding atLeast0LessThan by blast\n    moreover have \"exp t / (fact (get_odd n)) * (real_of_float x) ^ (get_odd n) \\<le> 0\"\n      by (auto intro!: mult_nonneg_nonpos divide_nonpos_pos simp add: x_less_zero)\n    ultimately have \"exp x \\<le> (\\<Sum>j = 0..<get_odd n. 1 / (fact j) * real_of_float x ^ j)\"\n      using get_odd exp_gt_zero by auto\n    also have \"\\<dots> \\<le> ub_exp_horner prec (get_odd n) 1 1 x\"\n      using bounds(2) by auto\n    finally show ?thesis .\n  qed\n  ultimately show ?thesis by auto\nqed\n\nlemma ub_exp_horner_nonneg: \"real_of_float x \\<le> 0 \\<Longrightarrow>\n  0 \\<le> real_of_float (ub_exp_horner prec (get_odd n) (Suc 0) (Suc 0) x)\"\n  using bnds_exp_horner[of x prec n]\n  by (intro order_trans[OF exp_ge_zero]) auto\n\n\nsubsection \"Compute the exponential function on the entire domain\"\n\nfunction ub_exp :: \"nat \\<Rightarrow> float \\<Rightarrow> float\" and lb_exp :: \"nat \\<Rightarrow> float \\<Rightarrow> float\" where\n\"lb_exp prec x =\n  (if 0 < x then float_divl prec 1 (ub_exp prec (-x))\n  else\n    let\n      horner = (\\<lambda> x. let  y = lb_exp_horner prec (get_even (prec + 2)) 1 1 x in\n        if y \\<le> 0 then Float 1 (- 2) else y)\n    in\n      if x < - 1 then\n        power_down_fl prec (horner (float_divl prec x (- floor_fl x))) (nat (- int_floor_fl x))\n      else horner x)\" |\n\"ub_exp prec x =\n  (if 0 < x then float_divr prec 1 (lb_exp prec (-x))\n  else if x < - 1 then\n    power_up_fl prec\n      (ub_exp_horner prec (get_odd (prec + 2)) 1 1\n        (float_divr prec x (- floor_fl x))) (nat (- int_floor_fl x))\n  else ub_exp_horner prec (get_odd (prec + 2)) 1 1 x)\"\n  by pat_completeness auto\ntermination\n  by (relation \"measure (\\<lambda> v. let (prec, x) = case_sum id id v in (if 0 < x then 1 else 0))\") auto\n\nlemma exp_m1_ge_quarter: \"(1 / 4 :: real) \\<le> exp (- 1)\"\nproof -\n  have eq4: \"4 = Suc (Suc (Suc (Suc 0)))\" by auto\n  have \"1 / 4 = (Float 1 (- 2))\"\n    unfolding Float_num by auto\n  also have \"\\<dots> \\<le> lb_exp_horner 3 (get_even 3) 1 1 (- 1)\"\n    by (subst less_eq_float.rep_eq [symmetric]) code_simp\n  also have \"\\<dots> \\<le> exp (- 1 :: float)\"\n    using bnds_exp_horner[where x=\"- 1\"] by auto\n  finally show ?thesis\n    by simp\nqed\n\nlemma lb_exp_pos:\n  assumes \"\\<not> 0 < x\"\n  shows \"0 < lb_exp prec x\"\nproof -\n  let \"?lb_horner x\" = \"lb_exp_horner prec (get_even (prec + 2)) 1 1 x\"\n  let \"?horner x\" = \"let y = ?lb_horner x in if y \\<le> 0 then Float 1 (- 2) else y\"\n  have pos_horner: \"0 < ?horner x\" for x\n    unfolding Let_def by (cases \"?lb_horner x \\<le> 0\") auto\n  moreover have \"0 < real_of_float ((?horner x) ^ num)\" for x :: float and num :: nat\n  proof -\n    have \"0 < real_of_float (?horner x) ^ num\" using \\<open>0 < ?horner x\\<close> by simp\n    also have \"\\<dots> = (?horner x) ^ num\" by auto\n    finally show ?thesis .\n  qed\n  ultimately show ?thesis\n    unfolding lb_exp.simps if_not_P[OF \\<open>\\<not> 0 < x\\<close>] Let_def\n    by (cases \"floor_fl x\", cases \"x < - 1\")\n      (auto simp: real_power_up_fl real_power_down_fl intro!: power_up_less power_down_pos)\nqed\n\nlemma exp_boundaries':\n  assumes \"x \\<le> 0\"\n  shows \"exp x \\<in> { (lb_exp prec x) .. (ub_exp prec x)}\"\nproof -\n  let \"?lb_exp_horner x\" = \"lb_exp_horner prec (get_even (prec + 2)) 1 1 x\"\n  let \"?ub_exp_horner x\" = \"ub_exp_horner prec (get_odd (prec + 2)) 1 1 x\"\n\n  have \"real_of_float x \\<le> 0\" and \"\\<not> x > 0\"\n    using \\<open>x \\<le> 0\\<close> by auto\n  show ?thesis\n  proof (cases \"x < - 1\")\n    case False\n    hence \"- 1 \\<le> real_of_float x\" by auto\n    show ?thesis\n    proof (cases \"?lb_exp_horner x \\<le> 0\")\n      case True\n      from \\<open>\\<not> x < - 1\\<close>\n      have \"- 1 \\<le> real_of_float x\" by auto\n      hence \"exp (- 1) \\<le> exp x\"\n        unfolding exp_le_cancel_iff .\n      from order_trans[OF exp_m1_ge_quarter this] have \"Float 1 (- 2) \\<le> exp x\"\n        unfolding Float_num .\n      with True show ?thesis\n        using bnds_exp_horner \\<open>real_of_float x \\<le> 0\\<close> \\<open>\\<not> x > 0\\<close> \\<open>\\<not> x < - 1\\<close> by auto\n    next\n      case False\n      thus ?thesis\n        using bnds_exp_horner \\<open>real_of_float x \\<le> 0\\<close> \\<open>\\<not> x > 0\\<close> \\<open>\\<not> x < - 1\\<close> by (auto simp add: Let_def)\n    qed\n  next\n    case True\n    let ?num = \"nat (- int_floor_fl x)\"\n\n    have \"real_of_int (int_floor_fl x) < - 1\"\n      using int_floor_fl[of x] \\<open>x < - 1\\<close> by simp\n    hence \"real_of_int (int_floor_fl x) < 0\" by simp\n    hence \"int_floor_fl x < 0\" by auto\n    hence \"1 \\<le> - int_floor_fl x\" by auto\n    hence \"0 < nat (- int_floor_fl x)\" by auto\n    hence \"0 < ?num\"  by auto\n    hence \"real ?num \\<noteq> 0\" by auto\n    have num_eq: \"real ?num = - int_floor_fl x\"\n      using \\<open>0 < nat (- int_floor_fl x)\\<close> by auto\n    have \"0 < - int_floor_fl x\"\n      using \\<open>0 < ?num\\<close>[unfolded of_nat_less_iff[symmetric]] by simp\n    hence \"real_of_int (int_floor_fl x) < 0\"\n      unfolding less_float_def by auto\n    have fl_eq: \"real_of_int (- int_floor_fl x) = real_of_float (- floor_fl x)\"\n      by (simp add: floor_fl_def int_floor_fl_def)\n    from \\<open>0 < - int_floor_fl x\\<close> have \"0 \\<le> real_of_float (- floor_fl x)\"\n      by (simp add: floor_fl_def int_floor_fl_def)\n    from \\<open>real_of_int (int_floor_fl x) < 0\\<close> have \"real_of_float (floor_fl x) < 0\"\n      by (simp add: floor_fl_def int_floor_fl_def)\n    have \"exp x \\<le> ub_exp prec x\"\n    proof -\n      have div_less_zero: \"real_of_float (float_divr prec x (- floor_fl x)) \\<le> 0\"\n        using float_divr_nonpos_pos_upper_bound[OF \\<open>real_of_float x \\<le> 0\\<close> \\<open>0 \\<le> real_of_float (- floor_fl x)\\<close>]\n        unfolding less_eq_float_def zero_float.rep_eq .\n\n      have \"exp x = exp (?num * (x / ?num))\"\n        using \\<open>real ?num \\<noteq> 0\\<close> by auto\n      also have \"\\<dots> = exp (x / ?num) ^ ?num\"\n        unfolding exp_real_of_nat_mult ..\n      also have \"\\<dots> \\<le> exp (float_divr prec x (- floor_fl x)) ^ ?num\"\n        unfolding num_eq fl_eq\n        by (rule power_mono, rule exp_le_cancel_iff[THEN iffD2], rule float_divr) auto\n      also have \"\\<dots> \\<le> (?ub_exp_horner (float_divr prec x (- floor_fl x))) ^ ?num\"\n        unfolding real_of_float_power\n        by (rule power_mono, rule bnds_exp_horner[OF div_less_zero, unfolded atLeastAtMost_iff, THEN conjunct2], auto)\n      also have \"\\<dots> \\<le> real_of_float (power_up_fl prec (?ub_exp_horner (float_divr prec x (- floor_fl x))) ?num)\"\n        by (auto simp add: real_power_up_fl intro!: power_up ub_exp_horner_nonneg div_less_zero)\n      finally show ?thesis\n        unfolding ub_exp.simps if_not_P[OF \\<open>\\<not> 0 < x\\<close>] if_P[OF \\<open>x < - 1\\<close>] floor_fl_def Let_def .\n    qed\n    moreover\n    have \"lb_exp prec x \\<le> exp x\"\n    proof -\n      let ?divl = \"float_divl prec x (- floor_fl x)\"\n      let ?horner = \"?lb_exp_horner ?divl\"\n\n      show ?thesis\n      proof (cases \"?horner \\<le> 0\")\n        case False\n        hence \"0 \\<le> real_of_float ?horner\" by auto\n\n        have div_less_zero: \"real_of_float (float_divl prec x (- floor_fl x)) \\<le> 0\"\n          using \\<open>real_of_float (floor_fl x) < 0\\<close> \\<open>real_of_float x \\<le> 0\\<close>\n          by (auto intro!: order_trans[OF float_divl] divide_nonpos_neg)\n\n        have \"(?lb_exp_horner (float_divl prec x (- floor_fl x))) ^ ?num \\<le>\n          exp (float_divl prec x (- floor_fl x)) ^ ?num\"\n          using \\<open>0 \\<le> real_of_float ?horner\\<close>[unfolded floor_fl_def[symmetric]]\n            bnds_exp_horner[OF div_less_zero, unfolded atLeastAtMost_iff, THEN conjunct1]\n          by (auto intro!: power_mono)\n        also have \"\\<dots> \\<le> exp (x / ?num) ^ ?num\"\n          unfolding num_eq fl_eq\n          using float_divl by (auto intro!: power_mono simp del: uminus_float.rep_eq)\n        also have \"\\<dots> = exp (?num * (x / ?num))\"\n          unfolding exp_real_of_nat_mult ..\n        also have \"\\<dots> = exp x\"\n          using \\<open>real ?num \\<noteq> 0\\<close> by auto\n        finally show ?thesis\n          using False\n          unfolding lb_exp.simps if_not_P[OF \\<open>\\<not> 0 < x\\<close>] if_P[OF \\<open>x < - 1\\<close>]\n            int_floor_fl_def Let_def if_not_P[OF False]\n          by (auto simp: real_power_down_fl intro!: power_down_le)\n      next\n        case True\n        have \"power_down_fl prec (Float 1 (- 2))  ?num \\<le> (Float 1 (- 2)) ^ ?num\"\n          by (metis Float_le_zero_iff less_imp_le linorder_not_less\n            not_numeral_le_zero numeral_One power_down_fl)\n        then have \"power_down_fl prec (Float 1 (- 2))  ?num \\<le> real_of_float (Float 1 (- 2)) ^ ?num\"\n          by simp\n        also\n        have \"real_of_float (floor_fl x) \\<noteq> 0\" and \"real_of_float (floor_fl x) \\<le> 0\"\n          using \\<open>real_of_float (floor_fl x) < 0\\<close> by auto\n        from divide_right_mono_neg[OF floor_fl[of x] \\<open>real_of_float (floor_fl x) \\<le> 0\\<close>, unfolded divide_self[OF \\<open>real_of_float (floor_fl x) \\<noteq> 0\\<close>]]\n        have \"- 1 \\<le> x / (- floor_fl x)\"\n          unfolding minus_float.rep_eq by auto\n        from order_trans[OF exp_m1_ge_quarter this[unfolded exp_le_cancel_iff[where x=\"- 1\", symmetric]]]\n        have \"Float 1 (- 2) \\<le> exp (x / (- floor_fl x))\"\n          unfolding Float_num .\n        hence \"real_of_float (Float 1 (- 2)) ^ ?num \\<le> exp (x / (- floor_fl x)) ^ ?num\"\n          by (metis Float_num(5) power_mono zero_le_divide_1_iff zero_le_numeral)\n        also have \"\\<dots> = exp x\"\n          unfolding num_eq fl_eq exp_real_of_nat_mult[symmetric]\n          using \\<open>real_of_float (floor_fl x) \\<noteq> 0\\<close> by auto\n        finally show ?thesis\n          unfolding lb_exp.simps if_not_P[OF \\<open>\\<not> 0 < x\\<close>] if_P[OF \\<open>x < - 1\\<close>]\n            int_floor_fl_def Let_def if_P[OF True] real_of_float_power .\n      qed\n    qed\n    ultimately show ?thesis by auto\n  qed\nqed\n\nlemma exp_boundaries: \"exp x \\<in> { lb_exp prec x .. ub_exp prec x }\"\nproof -\n  show ?thesis\n  proof (cases \"0 < x\")\n    case False\n    hence \"x \\<le> 0\" by auto\n    from exp_boundaries'[OF this] show ?thesis .\n  next\n    case True\n    hence \"-x \\<le> 0\" by auto\n\n    have \"lb_exp prec x \\<le> exp x\"\n    proof -\n      from exp_boundaries'[OF \\<open>-x \\<le> 0\\<close>]\n      have ub_exp: \"exp (- real_of_float x) \\<le> ub_exp prec (-x)\"\n        unfolding atLeastAtMost_iff minus_float.rep_eq by auto\n\n      have \"float_divl prec 1 (ub_exp prec (-x)) \\<le> 1 / ub_exp prec (-x)\"\n        using float_divl[where x=1] by auto\n      also have \"\\<dots> \\<le> exp x\"\n        using ub_exp[unfolded inverse_le_iff_le[OF order_less_le_trans[OF exp_gt_zero ub_exp]\n          exp_gt_zero, symmetric]]\n        unfolding exp_minus nonzero_inverse_inverse_eq[OF exp_not_eq_zero] inverse_eq_divide\n        by auto\n      finally show ?thesis\n        unfolding lb_exp.simps if_P[OF True] .\n    qed\n    moreover\n    have \"exp x \\<le> ub_exp prec x\"\n    proof -\n      have \"\\<not> 0 < -x\" using \\<open>0 < x\\<close> by auto\n\n      from exp_boundaries'[OF \\<open>-x \\<le> 0\\<close>]\n      have lb_exp: \"lb_exp prec (-x) \\<le> exp (- real_of_float x)\"\n        unfolding atLeastAtMost_iff minus_float.rep_eq by auto\n\n      have \"exp x \\<le> (1 :: float) / lb_exp prec (-x)\"\n        using lb_exp lb_exp_pos[OF \\<open>\\<not> 0 < -x\\<close>, of prec]\n        by (simp del: lb_exp.simps add: exp_minus field_simps)\n      also have \"\\<dots> \\<le> float_divr prec 1 (lb_exp prec (-x))\"\n        using float_divr .\n      finally show ?thesis\n        unfolding ub_exp.simps if_P[OF True] .\n    qed\n    ultimately show ?thesis\n      by auto\n  qed\nqed\n\nlemma bnds_exp: \"\\<forall>(x::real) lx ux. (l, u) =\n  (lb_exp prec lx, ub_exp prec ux) \\<and> x \\<in> {lx .. ux} \\<longrightarrow> l \\<le> exp x \\<and> exp x \\<le> u\"\nproof (rule allI, rule allI, rule allI, rule impI)\n  fix x :: real and lx ux\n  assume \"(l, u) = (lb_exp prec lx, ub_exp prec ux) \\<and> x \\<in> {lx .. ux}\"\n  hence l: \"lb_exp prec lx = l \" and u: \"ub_exp prec ux = u\" and x: \"x \\<in> {lx .. ux}\"\n    by auto\n  show \"l \\<le> exp x \\<and> exp x \\<le> u\"\n  proof\n    show \"l \\<le> exp x\"\n    proof -\n      from exp_boundaries[of lx prec, unfolded l]\n      have \"l \\<le> exp lx\" by (auto simp del: lb_exp.simps)\n      also have \"\\<dots> \\<le> exp x\" using x by auto\n      finally show ?thesis .\n    qed\n    show \"exp x \\<le> u\"\n    proof -\n      have \"exp x \\<le> exp ux\" using x by auto\n      also have \"\\<dots> \\<le> u\" using exp_boundaries[of ux prec, unfolded u] by (auto simp del: ub_exp.simps)\n      finally show ?thesis .\n    qed\n  qed\nqed\n\n\nsection \"Logarithm\"\n\nsubsection \"Compute the logarithm series\"\n\nfun ub_ln_horner :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> float \\<Rightarrow> float\"\nand lb_ln_horner :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> float \\<Rightarrow> float\" where\n\"ub_ln_horner prec 0 i x       = 0\" |\n\"ub_ln_horner prec (Suc n) i x = float_plus_up prec\n    (rapprox_rat prec 1 (int i)) (- float_round_down prec (x * lb_ln_horner prec n (Suc i) x))\" |\n\"lb_ln_horner prec 0 i x       = 0\" |\n\"lb_ln_horner prec (Suc n) i x = float_plus_down prec\n    (lapprox_rat prec 1 (int i)) (- float_round_up prec (x * ub_ln_horner prec n (Suc i) x))\"\n\nlemma ln_bounds:\n  assumes \"0 \\<le> x\"\n    and \"x < 1\"\n  shows \"(\\<Sum>i=0..<2*n. (- 1) ^ i * (1 / real (i + 1)) * x ^ (Suc i)) \\<le> ln (x + 1)\" (is \"?lb\")\n  and \"ln (x + 1) \\<le> (\\<Sum>i=0..<2*n + 1. (- 1) ^ i * (1 / real (i + 1)) * x ^ (Suc i))\" (is \"?ub\")\nproof -\n  let \"?a n\" = \"(1/real (n +1)) * x ^ (Suc n)\"\n\n  have ln_eq: \"(\\<Sum> i. (- 1) ^ i * ?a i) = ln (x + 1)\"\n    using ln_series[of \"x + 1\"] \\<open>0 \\<le> x\\<close> \\<open>x < 1\\<close> by auto\n\n  have \"norm x < 1\" using assms by auto\n  have \"?a \\<longlonglongrightarrow> 0\" unfolding Suc_eq_plus1[symmetric] inverse_eq_divide[symmetric]\n    using tendsto_mult[OF LIMSEQ_inverse_real_of_nat LIMSEQ_Suc[OF LIMSEQ_power_zero[OF \\<open>norm x < 1\\<close>]]] by auto\n  have \"0 \\<le> ?a n\" for n\n    by (rule mult_nonneg_nonneg) (auto simp: \\<open>0 \\<le> x\\<close>)\n  have \"?a (Suc n) \\<le> ?a n\" for n\n    unfolding inverse_eq_divide[symmetric]\n  proof (rule mult_mono)\n    show \"0 \\<le> x ^ Suc (Suc n)\"\n      by (auto simp add: \\<open>0 \\<le> x\\<close>)\n    have \"x ^ Suc (Suc n) \\<le> x ^ Suc n * 1\"\n      unfolding power_Suc2 mult.assoc[symmetric]\n      by (rule mult_left_mono, fact less_imp_le[OF \\<open>x < 1\\<close>]) (auto simp: \\<open>0 \\<le> x\\<close>)\n    thus \"x ^ Suc (Suc n) \\<le> x ^ Suc n\" by auto\n  qed auto\n  from summable_Leibniz'(2,4)[OF \\<open>?a \\<longlonglongrightarrow> 0\\<close> \\<open>\\<And>n. 0 \\<le> ?a n\\<close>, OF \\<open>\\<And>n. ?a (Suc n) \\<le> ?a n\\<close>, unfolded ln_eq]\n  show ?lb and ?ub\n    unfolding atLeast0LessThan by auto\nqed\n\nlemma ln_float_bounds:\n  assumes \"0 \\<le> real_of_float x\"\n    and \"real_of_float x < 1\"\n  shows \"x * lb_ln_horner prec (get_even n) 1 x \\<le> ln (x + 1)\" (is \"?lb \\<le> ?ln\")\n    and \"ln (x + 1) \\<le> x * ub_ln_horner prec (get_odd n) 1 x\" (is \"?ln \\<le> ?ub\")\nproof -\n  obtain ev where ev: \"get_even n = 2 * ev\" using get_even_double ..\n  obtain od where od: \"get_odd n = 2 * od + 1\" using get_odd_double ..\n\n  let \"?s n\" = \"(- 1) ^ n * (1 / real (1 + n)) * (real_of_float x)^(Suc n)\"\n\n  have \"?lb \\<le> sum ?s {0 ..< 2 * ev}\"\n    unfolding power_Suc2 mult.assoc[symmetric] times_float.rep_eq sum_distrib_right[symmetric]\n    unfolding mult.commute[of \"real_of_float x\"] ev \n    using horner_bounds(1)[where G=\"\\<lambda> i k. Suc k\" and F=\"\\<lambda>x. x\" and f=\"\\<lambda>x. x\" \n                    and lb=\"\\<lambda>n i k x. lb_ln_horner prec n k x\" \n                    and ub=\"\\<lambda>n i k x. ub_ln_horner prec n k x\" and j'=1 and n=\"2*ev\",\n      OF \\<open>0 \\<le> real_of_float x\\<close> refl lb_ln_horner.simps ub_ln_horner.simps] \\<open>0 \\<le> real_of_float x\\<close>\n    unfolding real_of_float_power\n    by (rule mult_right_mono)\n  also have \"\\<dots> \\<le> ?ln\"\n    using ln_bounds(1)[OF \\<open>0 \\<le> real_of_float x\\<close> \\<open>real_of_float x < 1\\<close>] by auto\n  finally show \"?lb \\<le> ?ln\" .\n\n  have \"?ln \\<le> sum ?s {0 ..< 2 * od + 1}\"\n    using ln_bounds(2)[OF \\<open>0 \\<le> real_of_float x\\<close> \\<open>real_of_float x < 1\\<close>] by auto\n  also have \"\\<dots> \\<le> ?ub\"\n    unfolding power_Suc2 mult.assoc[symmetric] times_float.rep_eq sum_distrib_right[symmetric]\n    unfolding mult.commute[of \"real_of_float x\"] od\n    using horner_bounds(2)[where G=\"\\<lambda> i k. Suc k\" and F=\"\\<lambda>x. x\" and f=\"\\<lambda>x. x\" and lb=\"\\<lambda>n i k x. lb_ln_horner prec n k x\" and ub=\"\\<lambda>n i k x. ub_ln_horner prec n k x\" and j'=1 and n=\"2*od+1\",\n      OF \\<open>0 \\<le> real_of_float x\\<close> refl lb_ln_horner.simps ub_ln_horner.simps] \\<open>0 \\<le> real_of_float x\\<close>\n    unfolding real_of_float_power\n    by (rule mult_right_mono)\n  finally show \"?ln \\<le> ?ub\" .\nqed\n\nlemma ln_add:\n  fixes x :: real\n  assumes \"0 < x\" and \"0 < y\"\n  shows \"ln (x + y) = ln x + ln (1 + y / x)\"\nproof -\n  have \"x \\<noteq> 0\" using assms by auto\n  have \"x + y = x * (1 + y / x)\"\n    unfolding distrib_left times_divide_eq_right nonzero_mult_div_cancel_left[OF \\<open>x \\<noteq> 0\\<close>]\n    by auto\n  moreover\n  have \"0 < y / x\" using assms by auto\n  hence \"0 < 1 + y / x\" by auto\n  ultimately show ?thesis\n    using ln_mult assms by auto\nqed\n\n\nsubsection \"Compute the logarithm of 2\"\n\ndefinition ub_ln2 where \"ub_ln2 prec = (let third = rapprox_rat (max prec 1) 1 3\n                                        in float_plus_up prec\n                                          ((Float 1 (- 1) * ub_ln_horner prec (get_odd prec) 1 (Float 1 (- 1))))\n                                           (float_round_up prec (third * ub_ln_horner prec (get_odd prec) 1 third)))\"\ndefinition lb_ln2 where \"lb_ln2 prec = (let third = lapprox_rat prec 1 3\n                                        in float_plus_down prec\n                                          ((Float 1 (- 1) * lb_ln_horner prec (get_even prec) 1 (Float 1 (- 1))))\n                                           (float_round_down prec (third * lb_ln_horner prec (get_even prec) 1 third)))\"\n\nlemma ub_ln2: \"ln 2 \\<le> ub_ln2 prec\" (is \"?ub_ln2\")\n  and lb_ln2: \"lb_ln2 prec \\<le> ln 2\" (is \"?lb_ln2\")\nproof -\n  let ?uthird = \"rapprox_rat (max prec 1) 1 3\"\n  let ?lthird = \"lapprox_rat prec 1 3\"\n\n  have ln2_sum: \"ln 2 = ln (1/2 + 1) + ln (1 / 3 + 1::real)\"\n    using ln_add[of \"3 / 2\" \"1 / 2\"] by auto\n  have lb3: \"?lthird \\<le> 1 / 3\" using lapprox_rat[of prec 1 3] by auto\n  hence lb3_ub: \"real_of_float ?lthird < 1\" by auto\n  have lb3_lb: \"0 \\<le> real_of_float ?lthird\" using lapprox_rat_nonneg[of 1 3] by auto\n  have ub3: \"1 / 3 \\<le> ?uthird\" using rapprox_rat[of 1 3] by auto\n  hence ub3_lb: \"0 \\<le> real_of_float ?uthird\" by auto\n\n  have lb2: \"0 \\<le> real_of_float (Float 1 (- 1))\" and ub2: \"real_of_float (Float 1 (- 1)) < 1\"\n    unfolding Float_num by auto\n\n  have \"0 \\<le> (1::int)\" and \"0 < (3::int)\" by auto\n  have ub3_ub: \"real_of_float ?uthird < 1\"\n    by (simp add: Float.compute_rapprox_rat Float.compute_lapprox_rat rapprox_posrat_less1)\n\n  have third_gt0: \"(0 :: real) < 1 / 3 + 1\" by auto\n  have uthird_gt0: \"0 < real_of_float ?uthird + 1\" using ub3_lb by auto\n  have lthird_gt0: \"0 < real_of_float ?lthird + 1\" using lb3_lb by auto\n\n  show ?ub_ln2\n    unfolding ub_ln2_def Let_def ln2_sum Float_num(4)[symmetric]\n  proof (rule float_plus_up_le, rule add_mono, fact ln_float_bounds(2)[OF lb2 ub2])\n    have \"ln (1 / 3 + 1) \\<le> ln (real_of_float ?uthird + 1)\"\n      unfolding ln_le_cancel_iff[OF third_gt0 uthird_gt0] using ub3 by auto\n    also have \"\\<dots> \\<le> ?uthird * ub_ln_horner prec (get_odd prec) 1 ?uthird\"\n      using ln_float_bounds(2)[OF ub3_lb ub3_ub] .\n    also note float_round_up\n    finally show \"ln (1 / 3 + 1) \\<le> float_round_up prec (?uthird * ub_ln_horner prec (get_odd prec) 1 ?uthird)\" .\n  qed\n  show ?lb_ln2\n    unfolding lb_ln2_def Let_def ln2_sum Float_num(4)[symmetric]\n  proof (rule float_plus_down_le, rule add_mono, fact ln_float_bounds(1)[OF lb2 ub2])\n    have \"?lthird * lb_ln_horner prec (get_even prec) 1 ?lthird \\<le> ln (real_of_float ?lthird + 1)\"\n      using ln_float_bounds(1)[OF lb3_lb lb3_ub] .\n    note float_round_down_le[OF this]\n    also have \"\\<dots> \\<le> ln (1 / 3 + 1)\"\n      unfolding ln_le_cancel_iff[OF lthird_gt0 third_gt0]\n      using lb3 by auto\n    finally show \"float_round_down prec (?lthird * lb_ln_horner prec (get_even prec) 1 ?lthird) \\<le>\n      ln (1 / 3 + 1)\" .\n  qed\nqed\n\n\nsubsection \"Compute the logarithm in the entire domain\"\n\nfunction ub_ln :: \"nat \\<Rightarrow> float \\<Rightarrow> float option\" and lb_ln :: \"nat \\<Rightarrow> float \\<Rightarrow> float option\" where\n\"ub_ln prec x = (if x \\<le> 0          then None\n            else if x < 1          then Some (- the (lb_ln prec (float_divl (max prec 1) 1 x)))\n            else let horner = \\<lambda>x. float_round_up prec (x * ub_ln_horner prec (get_odd prec) 1 x) in\n                 if x \\<le> Float 3 (- 1) then Some (horner (x - 1))\n            else if x < Float 1 1  then Some (float_round_up prec (horner (Float 1 (- 1)) + horner (x * rapprox_rat prec 2 3 - 1)))\n                                   else let l = bitlen (mantissa x) - 1 in\n                                        Some (float_plus_up prec (float_round_up prec (ub_ln2 prec * (Float (exponent x + l) 0))) (horner (Float (mantissa x) (- l) - 1))))\" |\n\"lb_ln prec x = (if x \\<le> 0          then None\n            else if x < 1          then Some (- the (ub_ln prec (float_divr prec 1 x)))\n            else let horner = \\<lambda>x. float_round_down prec (x * lb_ln_horner prec (get_even prec) 1 x) in\n                 if x \\<le> Float 3 (- 1) then Some (horner (x - 1))\n            else if x < Float 1 1  then Some (float_round_down prec (horner (Float 1 (- 1)) +\n                                              horner (max (x * lapprox_rat prec 2 3 - 1) 0)))\n                                   else let l = bitlen (mantissa x) - 1 in\n                                        Some (float_plus_down prec (float_round_down prec (lb_ln2 prec * (Float (exponent x + l) 0))) (horner (Float (mantissa x) (- l) - 1))))\"\n  by pat_completeness auto\n\ntermination\nproof (relation \"measure (\\<lambda> v. let (prec, x) = case_sum id id v in (if x < 1 then 1 else 0))\", auto)\n  fix prec and x :: float\n  assume \"\\<not> real_of_float x \\<le> 0\" and \"real_of_float x < 1\" and \"real_of_float (float_divl (max prec (Suc 0)) 1 x) < 1\"\n  hence \"0 < real_of_float x\" \"1 \\<le> max prec (Suc 0)\" \"real_of_float x < 1\"\n    by auto\n  from float_divl_pos_less1_bound[OF \\<open>0 < real_of_float x\\<close> \\<open>real_of_float x < 1\\<close>[THEN less_imp_le] \\<open>1 \\<le> max prec (Suc 0)\\<close>]\n  show False\n    using \\<open>real_of_float (float_divl (max prec (Suc 0)) 1 x) < 1\\<close> by auto\nnext\n  fix prec x\n  assume \"\\<not> real_of_float x \\<le> 0\" and \"real_of_float x < 1\" and \"real_of_float (float_divr prec 1 x) < 1\"\n  hence \"0 < x\" by auto\n  from float_divr_pos_less1_lower_bound[OF \\<open>0 < x\\<close>, of prec] \\<open>real_of_float x < 1\\<close> show False\n    using \\<open>real_of_float (float_divr prec 1 x) < 1\\<close> by auto\nqed\n\nlemma float_pos_eq_mantissa_pos: \"x > 0 \\<longleftrightarrow> mantissa x > 0\"\n  apply (subst Float_mantissa_exponent[of x, symmetric])\n  apply (auto simp add: zero_less_mult_iff zero_float_def  dest: less_zeroE)\n  apply (metis not_le powr_ge_pzero)\n  done\n\nlemma Float_pos_eq_mantissa_pos: \"Float m e > 0 \\<longleftrightarrow> m > 0\"\n  using powr_gt_zero[of 2 \"e\"]\n  by (auto simp add: zero_less_mult_iff zero_float_def simp del: powr_gt_zero dest: less_zeroE)\n\nlemma Float_representation_aux:\n  fixes m e\n  defines \"x \\<equiv> Float m e\"\n  assumes \"x > 0\"\n  shows \"Float (exponent x + (bitlen (mantissa x) - 1)) 0 = Float (e + (bitlen m - 1)) 0\" (is ?th1)\n    and \"Float (mantissa x) (- (bitlen (mantissa x) - 1)) = Float m ( - (bitlen m - 1))\"  (is ?th2)\nproof -\n  from assms have mantissa_pos: \"m > 0\" \"mantissa x > 0\"\n    using Float_pos_eq_mantissa_pos[of m e] float_pos_eq_mantissa_pos[of x] by simp_all\n  thus ?th1\n    using bitlen_Float[of m e] assms\n    by (auto simp add: zero_less_mult_iff intro!: arg_cong2[where f=Float])\n  have \"x \\<noteq> float_of 0\"\n    unfolding zero_float_def[symmetric] using \\<open>0 < x\\<close> by auto\n  from denormalize_shift[OF assms(1) this] guess i . note i = this\n\n  have \"2 powr (1 - (real_of_int (bitlen (mantissa x)) + real_of_int i)) =\n    2 powr (1 - (real_of_int (bitlen (mantissa x)))) * inverse (2 powr (real i))\"\n    by (simp add: powr_minus[symmetric] powr_add[symmetric] field_simps)\n  hence \"real_of_int (mantissa x) * 2 powr (1 - real_of_int (bitlen (mantissa x))) =\n    (real_of_int (mantissa x) * 2 ^ i) * 2 powr (1 - real_of_int (bitlen (mantissa x * 2 ^ i)))\"\n    using \\<open>mantissa x > 0\\<close> by (simp add: powr_realpow)\n  then show ?th2\n    unfolding i by transfer auto\nqed\n\nlemma compute_ln[code]:\n  fixes m e\n  defines \"x \\<equiv> Float m e\"\n  shows \"ub_ln prec x = (if x \\<le> 0          then None\n              else if x < 1          then Some (- the (lb_ln prec (float_divl (max prec 1) 1 x)))\n            else let horner = \\<lambda>x. float_round_up prec (x * ub_ln_horner prec (get_odd prec) 1 x) in\n                 if x \\<le> Float 3 (- 1) then Some (horner (x - 1))\n            else if x < Float 1 1  then Some (float_round_up prec (horner (Float 1 (- 1)) + horner (x * rapprox_rat prec 2 3 - 1)))\n                                   else let l = bitlen m - 1 in\n                                        Some (float_plus_up prec (float_round_up prec (ub_ln2 prec * (Float (e + l) 0))) (horner (Float m (- l) - 1))))\"\n    (is ?th1)\n  and \"lb_ln prec x = (if x \\<le> 0          then None\n            else if x < 1          then Some (- the (ub_ln prec (float_divr prec 1 x)))\n            else let horner = \\<lambda>x. float_round_down prec (x * lb_ln_horner prec (get_even prec) 1 x) in\n                 if x \\<le> Float 3 (- 1) then Some (horner (x - 1))\n            else if x < Float 1 1  then Some (float_round_down prec (horner (Float 1 (- 1)) +\n                                              horner (max (x * lapprox_rat prec 2 3 - 1) 0)))\n                                   else let l = bitlen m - 1 in\n                                        Some (float_plus_down prec (float_round_down prec (lb_ln2 prec * (Float (e + l) 0))) (horner (Float m (- l) - 1))))\"\n    (is ?th2)\nproof -\n  from assms Float_pos_eq_mantissa_pos have \"x > 0 \\<Longrightarrow> m > 0\"\n    by simp\n  thus ?th1 ?th2\n    using Float_representation_aux[of m e]\n    unfolding x_def[symmetric]\n    by (auto dest: not_le_imp_less)\nqed\n\nlemma ln_shifted_float:\n  assumes \"0 < m\"\n  shows \"ln (Float m e) = ln 2 * (e + (bitlen m - 1)) + ln (Float m (- (bitlen m - 1)))\"\nproof -\n  let ?B = \"2^nat (bitlen m - 1)\"\n  define bl where \"bl = bitlen m - 1\"\n  have \"0 < real_of_int m\" and \"\\<And>X. (0 :: real) < 2^X\" and \"0 < (2 :: real)\" and \"m \\<noteq> 0\"\n    using assms by auto\n  hence \"0 \\<le> bl\" by (simp add: bitlen_alt_def bl_def)\n  show ?thesis\n  proof (cases \"0 \\<le> e\")\n    case True\n    thus ?thesis\n      unfolding bl_def[symmetric] using \\<open>0 < real_of_int m\\<close> \\<open>0 \\<le> bl\\<close>\n      apply (simp add: ln_mult)\n      apply (cases \"e=0\")\n        apply (cases \"bl = 0\", simp_all add: powr_minus ln_inverse ln_powr)\n        apply (cases \"bl = 0\", simp_all add: powr_minus ln_inverse ln_powr field_simps)\n      done\n  next\n    case False\n    hence \"0 < -e\" by auto\n    have lne: \"ln (2 powr real_of_int e) = ln (inverse (2 powr - e))\"\n      by (simp add: powr_minus)\n    hence pow_gt0: \"(0::real) < 2^nat (-e)\"\n      by auto\n    hence inv_gt0: \"(0::real) < inverse (2^nat (-e))\"\n      by auto\n    show ?thesis\n      using False unfolding bl_def[symmetric]\n      using \\<open>0 < real_of_int m\\<close> \\<open>0 \\<le> bl\\<close>\n      by (auto simp add: lne ln_mult ln_powr ln_div field_simps)\n  qed\nqed\n\nlemma ub_ln_lb_ln_bounds':\n  assumes \"1 \\<le> x\"\n  shows \"the (lb_ln prec x) \\<le> ln x \\<and> ln x \\<le> the (ub_ln prec x)\"\n    (is \"?lb \\<le> ?ln \\<and> ?ln \\<le> ?ub\")\nproof (cases \"x < Float 1 1\")\n  case True\n  hence \"real_of_float (x - 1) < 1\" and \"real_of_float x < 2\" by auto\n  have \"\\<not> x \\<le> 0\" and \"\\<not> x < 1\" using \\<open>1 \\<le> x\\<close> by auto\n  hence \"0 \\<le> real_of_float (x - 1)\" using \\<open>1 \\<le> x\\<close> by auto\n\n  have [simp]: \"(Float 3 (- 1)) = 3 / 2\" by simp\n\n  show ?thesis\n  proof (cases \"x \\<le> Float 3 (- 1)\")\n    case True\n    show ?thesis\n      unfolding lb_ln.simps\n      unfolding ub_ln.simps Let_def\n      using ln_float_bounds[OF \\<open>0 \\<le> real_of_float (x - 1)\\<close> \\<open>real_of_float (x - 1) < 1\\<close>, of prec]\n        \\<open>\\<not> x \\<le> 0\\<close> \\<open>\\<not> x < 1\\<close> True\n      by (auto intro!: float_round_down_le float_round_up_le)\n  next\n    case False\n    hence *: \"3 / 2 < x\" by auto\n\n    with ln_add[of \"3 / 2\" \"x - 3 / 2\"]\n    have add: \"ln x = ln (3 / 2) + ln (real_of_float x * 2 / 3)\"\n      by (auto simp add: algebra_simps diff_divide_distrib)\n\n    let \"?ub_horner x\" = \"float_round_up prec (x * ub_ln_horner prec (get_odd prec) 1 x)\"\n    let \"?lb_horner x\" = \"float_round_down prec (x * lb_ln_horner prec (get_even prec) 1 x)\"\n\n    { have up: \"real_of_float (rapprox_rat prec 2 3) \\<le> 1\"\n        by (rule rapprox_rat_le1) simp_all\n      have low: \"2 / 3 \\<le> rapprox_rat prec 2 3\"\n        by (rule order_trans[OF _ rapprox_rat]) simp\n      from mult_less_le_imp_less[OF * low] *\n      have pos: \"0 < real_of_float (x * rapprox_rat prec 2 3 - 1)\" by auto\n\n      have \"ln (real_of_float x * 2/3)\n        \\<le> ln (real_of_float (x * rapprox_rat prec 2 3 - 1) + 1)\"\n      proof (rule ln_le_cancel_iff[symmetric, THEN iffD1])\n        show \"real_of_float x * 2 / 3 \\<le> real_of_float (x * rapprox_rat prec 2 3 - 1) + 1\"\n          using * low by auto\n        show \"0 < real_of_float x * 2 / 3\" using * by simp\n        show \"0 < real_of_float (x * rapprox_rat prec 2 3 - 1) + 1\" using pos by auto\n      qed\n      also have \"\\<dots> \\<le> ?ub_horner (x * rapprox_rat prec 2 3 - 1)\"\n      proof (rule float_round_up_le, rule ln_float_bounds(2))\n        from mult_less_le_imp_less[OF \\<open>real_of_float x < 2\\<close> up] low *\n        show \"real_of_float (x * rapprox_rat prec 2 3 - 1) < 1\" by auto\n        show \"0 \\<le> real_of_float (x * rapprox_rat prec 2 3 - 1)\" using pos by auto\n      qed\n     finally have \"ln x \\<le> ?ub_horner (Float 1 (-1))\n          + ?ub_horner ((x * rapprox_rat prec 2 3 - 1))\"\n        using ln_float_bounds(2)[of \"Float 1 (- 1)\" prec prec] add\n        by (auto intro!: add_mono float_round_up_le)\n      note float_round_up_le[OF this, of prec]\n    }\n    moreover\n    { let ?max = \"max (x * lapprox_rat prec 2 3 - 1) 0\"\n\n      have up: \"lapprox_rat prec 2 3 \\<le> 2/3\"\n        by (rule order_trans[OF lapprox_rat], simp)\n\n      have low: \"0 \\<le> real_of_float (lapprox_rat prec 2 3)\"\n        using lapprox_rat_nonneg[of 2 3 prec] by simp\n\n      have \"?lb_horner ?max\n        \\<le> ln (real_of_float ?max + 1)\"\n      proof (rule float_round_down_le, rule ln_float_bounds(1))\n        from mult_less_le_imp_less[OF \\<open>real_of_float x < 2\\<close> up] * low\n        show \"real_of_float ?max < 1\" by (cases \"real_of_float (lapprox_rat prec 2 3) = 0\",\n          auto simp add: real_of_float_max)\n        show \"0 \\<le> real_of_float ?max\" by (auto simp add: real_of_float_max)\n      qed\n      also have \"\\<dots> \\<le> ln (real_of_float x * 2/3)\"\n      proof (rule ln_le_cancel_iff[symmetric, THEN iffD1])\n        show \"0 < real_of_float ?max + 1\" by (auto simp add: real_of_float_max)\n        show \"0 < real_of_float x * 2/3\" using * by auto\n        show \"real_of_float ?max + 1 \\<le> real_of_float x * 2/3\" using * up\n          by (cases \"0 < real_of_float x * real_of_float (lapprox_posrat prec 2 3) - 1\",\n              auto simp add: max_def)\n      qed\n      finally have \"?lb_horner (Float 1 (- 1)) + ?lb_horner ?max \\<le> ln x\"\n        using ln_float_bounds(1)[of \"Float 1 (- 1)\" prec prec] add\n        by (auto intro!: add_mono float_round_down_le)\n      note float_round_down_le[OF this, of prec]\n    }\n    ultimately\n    show ?thesis unfolding lb_ln.simps unfolding ub_ln.simps Let_def\n      using \\<open>\\<not> x \\<le> 0\\<close> \\<open>\\<not> x < 1\\<close> True False by auto\n  qed\nnext\n  case False\n  hence \"\\<not> x \\<le> 0\" and \"\\<not> x < 1\" \"0 < x\" \"\\<not> x \\<le> Float 3 (- 1)\"\n    using \\<open>1 \\<le> x\\<close> by auto\n  show ?thesis\n  proof -\n    define m where \"m = mantissa x\"\n    define e where \"e = exponent x\"\n    from Float_mantissa_exponent[of x] have Float: \"x = Float m e\"\n      by (simp add: m_def e_def)\n    let ?s = \"Float (e + (bitlen m - 1)) 0\"\n    let ?x = \"Float m (- (bitlen m - 1))\"\n\n    have \"0 < m\" and \"m \\<noteq> 0\" using \\<open>0 < x\\<close> Float powr_gt_zero[of 2 e]\n      apply (auto simp add: zero_less_mult_iff)\n      using not_le powr_ge_pzero apply blast\n      done\n    define bl where \"bl = bitlen m - 1\"\n    hence \"bl \\<ge> 0\"\n      using \\<open>m > 0\\<close> by (simp add: bitlen_alt_def)\n    have \"1 \\<le> Float m e\"\n      using \\<open>1 \\<le> x\\<close> Float unfolding less_eq_float_def by auto\n    from bitlen_div[OF \\<open>0 < m\\<close>] float_gt1_scale[OF \\<open>1 \\<le> Float m e\\<close>] \\<open>bl \\<ge> 0\\<close>\n    have x_bnds: \"0 \\<le> real_of_float (?x - 1)\" \"real_of_float (?x - 1) < 1\"\n      unfolding bl_def[symmetric]\n      by (auto simp: powr_realpow[symmetric] field_simps)\n         (auto simp : powr_minus field_simps)\n\n    {\n      have \"float_round_down prec (lb_ln2 prec * ?s) \\<le> ln 2 * (e + (bitlen m - 1))\"\n          (is \"real_of_float ?lb2 \\<le> _\")\n        apply (rule float_round_down_le)\n        unfolding nat_0 power_0 mult_1_right times_float.rep_eq\n        using lb_ln2[of prec]\n      proof (rule mult_mono)\n        from float_gt1_scale[OF \\<open>1 \\<le> Float m e\\<close>]\n        show \"0 \\<le> real_of_float (Float (e + (bitlen m - 1)) 0)\" by simp\n      qed auto\n      moreover\n      from ln_float_bounds(1)[OF x_bnds]\n      have \"float_round_down prec ((?x - 1) * lb_ln_horner prec (get_even prec) 1 (?x - 1)) \\<le> ln ?x\" (is \"real_of_float ?lb_horner \\<le> _\")\n        by (auto intro!: float_round_down_le)\n      ultimately have \"float_plus_down prec ?lb2 ?lb_horner \\<le> ln x\"\n        unfolding Float ln_shifted_float[OF \\<open>0 < m\\<close>, of e] by (auto intro!: float_plus_down_le)\n    }\n    moreover\n    {\n      from ln_float_bounds(2)[OF x_bnds]\n      have \"ln ?x \\<le> float_round_up prec ((?x - 1) * ub_ln_horner prec (get_odd prec) 1 (?x - 1))\"\n          (is \"_ \\<le> real_of_float ?ub_horner\")\n        by (auto intro!: float_round_up_le)\n      moreover\n      have \"ln 2 * (e + (bitlen m - 1)) \\<le> float_round_up prec (ub_ln2 prec * ?s)\"\n          (is \"_ \\<le> real_of_float ?ub2\")\n        apply (rule float_round_up_le)\n        unfolding nat_0 power_0 mult_1_right times_float.rep_eq\n        using ub_ln2[of prec]\n      proof (rule mult_mono)\n        from float_gt1_scale[OF \\<open>1 \\<le> Float m e\\<close>]\n        show \"0 \\<le> real_of_int (e + (bitlen m - 1))\" by auto\n        have \"0 \\<le> ln (2 :: real)\" by simp\n        thus \"0 \\<le> real_of_float (ub_ln2 prec)\" using ub_ln2[of prec] by arith\n      qed auto\n      ultimately have \"ln x \\<le> float_plus_up prec ?ub2 ?ub_horner\"\n        unfolding Float ln_shifted_float[OF \\<open>0 < m\\<close>, of e]\n        by (auto intro!: float_plus_up_le)\n    }\n    ultimately show ?thesis\n      unfolding lb_ln.simps\n      unfolding ub_ln.simps\n      unfolding if_not_P[OF \\<open>\\<not> x \\<le> 0\\<close>] if_not_P[OF \\<open>\\<not> x < 1\\<close>]\n        if_not_P[OF False] if_not_P[OF \\<open>\\<not> x \\<le> Float 3 (- 1)\\<close>] Let_def\n      unfolding plus_float.rep_eq e_def[symmetric] m_def[symmetric]\n      by simp\n  qed\nqed\n\nlemma ub_ln_lb_ln_bounds:\n  assumes \"0 < x\"\n  shows \"the (lb_ln prec x) \\<le> ln x \\<and> ln x \\<le> the (ub_ln prec x)\"\n    (is \"?lb \\<le> ?ln \\<and> ?ln \\<le> ?ub\")\nproof (cases \"x < 1\")\n  case False\n  hence \"1 \\<le> x\"\n    unfolding less_float_def less_eq_float_def by auto\n  show ?thesis\n    using ub_ln_lb_ln_bounds'[OF \\<open>1 \\<le> x\\<close>] .\nnext\n  case True\n  have \"\\<not> x \\<le> 0\" using \\<open>0 < x\\<close> by auto\n  from True have \"real_of_float x \\<le> 1\" \"x \\<le> 1\"\n    by simp_all\n  have \"0 < real_of_float x\" and \"real_of_float x \\<noteq> 0\"\n    using \\<open>0 < x\\<close> by auto\n  hence A: \"0 < 1 / real_of_float x\" by auto\n\n  {\n    let ?divl = \"float_divl (max prec 1) 1 x\"\n    have A': \"1 \\<le> ?divl\" using float_divl_pos_less1_bound[OF \\<open>0 < real_of_float x\\<close> \\<open>real_of_float x \\<le> 1\\<close>] by auto\n    hence B: \"0 < real_of_float ?divl\" by auto\n\n    have \"ln ?divl \\<le> ln (1 / x)\" unfolding ln_le_cancel_iff[OF B A] using float_divl[of _ 1 x] by auto\n    hence \"ln x \\<le> - ln ?divl\" unfolding nonzero_inverse_eq_divide[OF \\<open>real_of_float x \\<noteq> 0\\<close>, symmetric] ln_inverse[OF \\<open>0 < real_of_float x\\<close>] by auto\n    from this ub_ln_lb_ln_bounds'[OF A', THEN conjunct1, THEN le_imp_neg_le]\n    have \"?ln \\<le> - the (lb_ln prec ?divl)\" unfolding uminus_float.rep_eq by (rule order_trans)\n  } moreover\n  {\n    let ?divr = \"float_divr prec 1 x\"\n    have A': \"1 \\<le> ?divr\" using float_divr_pos_less1_lower_bound[OF \\<open>0 < x\\<close> \\<open>x \\<le> 1\\<close>] unfolding less_eq_float_def less_float_def by auto\n    hence B: \"0 < real_of_float ?divr\" by auto\n\n    have \"ln (1 / x) \\<le> ln ?divr\" unfolding ln_le_cancel_iff[OF A B] using float_divr[of 1 x] by auto\n    hence \"- ln ?divr \\<le> ln x\" unfolding nonzero_inverse_eq_divide[OF \\<open>real_of_float x \\<noteq> 0\\<close>, symmetric] ln_inverse[OF \\<open>0 < real_of_float x\\<close>] by auto\n    from ub_ln_lb_ln_bounds'[OF A', THEN conjunct2, THEN le_imp_neg_le] this\n    have \"- the (ub_ln prec ?divr) \\<le> ?ln\" unfolding uminus_float.rep_eq by (rule order_trans)\n  }\n  ultimately show ?thesis unfolding lb_ln.simps[where x=x]  ub_ln.simps[where x=x]\n    unfolding if_not_P[OF \\<open>\\<not> x \\<le> 0\\<close>] if_P[OF True] by auto\nqed\n\nlemma lb_ln:\n  assumes \"Some y = lb_ln prec x\"\n  shows \"y \\<le> ln x\" and \"0 < real_of_float x\"\nproof -\n  have \"0 < x\"\n  proof (rule ccontr)\n    assume \"\\<not> 0 < x\"\n    hence \"x \\<le> 0\"\n      unfolding less_eq_float_def less_float_def by auto\n    thus False\n      using assms by auto\n  qed\n  thus \"0 < real_of_float x\" by auto\n  have \"the (lb_ln prec x) \\<le> ln x\"\n    using ub_ln_lb_ln_bounds[OF \\<open>0 < x\\<close>] ..\n  thus \"y \\<le> ln x\"\n    unfolding assms[symmetric] by auto\nqed\n\nlemma ub_ln:\n  assumes \"Some y = ub_ln prec x\"\n  shows \"ln x \\<le> y\" and \"0 < real_of_float x\"\nproof -\n  have \"0 < x\"\n  proof (rule ccontr)\n    assume \"\\<not> 0 < x\"\n    hence \"x \\<le> 0\" by auto\n    thus False\n      using assms by auto\n  qed\n  thus \"0 < real_of_float x\" by auto\n  have \"ln x \\<le> the (ub_ln prec x)\"\n    using ub_ln_lb_ln_bounds[OF \\<open>0 < x\\<close>] ..\n  thus \"ln x \\<le> y\"\n    unfolding assms[symmetric] by auto\nqed\n\nlemma bnds_ln: \"\\<forall>(x::real) lx ux. (Some l, Some u) =\n  (lb_ln prec lx, ub_ln prec ux) \\<and> x \\<in> {lx .. ux} \\<longrightarrow> l \\<le> ln x \\<and> ln x \\<le> u\"\nproof (rule allI, rule allI, rule allI, rule impI)\n  fix x :: real\n  fix lx ux\n  assume \"(Some l, Some u) = (lb_ln prec lx, ub_ln prec ux) \\<and> x \\<in> {lx .. ux}\"\n  hence l: \"Some l = lb_ln prec lx \" and u: \"Some u = ub_ln prec ux\" and x: \"x \\<in> {lx .. ux}\"\n    by auto\n\n  have \"ln ux \\<le> u\" and \"0 < real_of_float ux\"\n    using ub_ln u by auto\n  have \"l \\<le> ln lx\" and \"0 < real_of_float lx\" and \"0 < x\"\n    using lb_ln[OF l] x by auto\n\n  from ln_le_cancel_iff[OF \\<open>0 < real_of_float lx\\<close> \\<open>0 < x\\<close>] \\<open>l \\<le> ln lx\\<close>\n  have \"l \\<le> ln x\"\n    using x unfolding atLeastAtMost_iff by auto\n  moreover\n  from ln_le_cancel_iff[OF \\<open>0 < x\\<close> \\<open>0 < real_of_float ux\\<close>] \\<open>ln ux \\<le> real_of_float u\\<close>\n  have \"ln x \\<le> u\"\n    using x unfolding atLeastAtMost_iff by auto\n  ultimately show \"l \\<le> ln x \\<and> ln x \\<le> u\" ..\nqed\n\n\nsection \\<open>Real power function\\<close>\n\ndefinition bnds_powr :: \"nat \\<Rightarrow> float \\<Rightarrow> float \\<Rightarrow> float \\<Rightarrow> float \\<Rightarrow> (float \\<times> float) option\" where\n  \"bnds_powr prec l1 u1 l2 u2 = (\n     if l1 = 0 \\<and> u1 = 0 then\n       Some (0, 0)\n     else if l1 = 0 \\<and> l2 \\<ge> 1 then\n       let uln = the (ub_ln prec u1)\n       in  Some (0, ub_exp prec (float_round_up prec (uln * (if uln \\<ge> 0 then u2 else l2))))\n     else if l1 \\<le> 0 then\n       None\n     else\n       Some (map_bnds lb_exp ub_exp prec \n               (bnds_mult prec (the (lb_ln prec l1)) (the (ub_ln prec u1)) l2 u2)))\"\n\nlemmas [simp del] = lb_exp.simps ub_exp.simps\n\nlemma mono_exp_real: \"mono (exp :: real \\<Rightarrow> real)\"\n  by (auto simp: mono_def)\n\nlemma ub_exp_nonneg: \"real_of_float (ub_exp prec x) \\<ge> 0\"\nproof -\n  have \"0 \\<le> exp (real_of_float x)\" by simp\n  also from exp_boundaries[of x prec] \n    have \"\\<dots> \\<le> real_of_float (ub_exp prec x)\" by simp\n  finally show ?thesis .\nqed\n\nlemma bnds_powr:\n  assumes lu: \"Some (l, u) = bnds_powr prec l1 u1 l2 u2\"\n  assumes x: \"x \\<in> {real_of_float l1..real_of_float u1}\"\n  assumes y: \"y \\<in> {real_of_float l2..real_of_float u2}\"\n  shows   \"x powr y \\<in> {real_of_float l..real_of_float u}\"\nproof -\n  consider \"l1 = 0\" \"u1 = 0\" | \"l1 = 0\" \"u1 \\<noteq> 0\" \"l2 \\<ge> 1\" | \n           \"l1 \\<le> 0\" \"\\<not>(l1 = 0 \\<and> (u1 = 0 \\<or> l2 \\<ge> 1))\" | \"l1 > 0\" by force\n  thus ?thesis\n  proof cases\n    assume \"l1 = 0\" \"u1 = 0\"\n    with x lu show ?thesis by (auto simp: bnds_powr_def)\n  next\n    assume A: \"l1 = 0\" \"u1 \\<noteq> 0\" \"l2 \\<ge> 1\"\n    define uln where \"uln = the (ub_ln prec u1)\"\n    show ?thesis\n    proof (cases \"x = 0\")\n      case False\n      with A x y have \"x powr y = exp (ln x * y)\" by (simp add: powr_def)\n      also {\n        from A x False have \"ln x \\<le> ln (real_of_float u1)\" by simp\n        also from ub_ln_lb_ln_bounds[of u1 prec] A y x False\n          have \"ln (real_of_float u1) \\<le> real_of_float uln\" by (simp add: uln_def del: lb_ln.simps)\n        also from A x y have \"\\<dots> * y \\<le> real_of_float uln * (if uln \\<ge> 0 then u2 else l2)\"\n          by (auto intro: mult_left_mono mult_left_mono_neg)\n        also have \"\\<dots> \\<le> real_of_float (float_round_up prec (uln * (if uln \\<ge> 0 then u2 else l2)))\"\n          by (simp add: float_round_up_le)\n        finally have \"ln x * y \\<le> \\<dots>\" using A y by - simp\n      }\n      also have \"exp (real_of_float (float_round_up prec (uln * (if uln \\<ge> 0 then u2 else l2)))) \\<le>\n                   real_of_float (ub_exp prec (float_round_up prec\n                       (uln * (if uln \\<ge> 0 then u2 else l2))))\"\n        using exp_boundaries by simp\n      finally show ?thesis using A x y lu \n        by (simp add: bnds_powr_def uln_def Let_def del: lb_ln.simps ub_ln.simps)\n    qed (insert x y lu A, simp_all add: bnds_powr_def Let_def ub_exp_nonneg\n                                   del: lb_ln.simps ub_ln.simps)\n  next\n    assume \"l1 \\<le> 0\" \"\\<not>(l1 = 0 \\<and> (u1 = 0 \\<or> l2 \\<ge> 1))\"\n    with lu show ?thesis by (simp add: bnds_powr_def split: if_split_asm)\n  next\n    assume l1: \"l1 > 0\"\n    obtain lm um where lmum:\n      \"(lm, um) = bnds_mult prec (the (lb_ln prec l1)) (the (ub_ln prec u1)) l2 u2\"\n      by (cases \"bnds_mult prec (the (lb_ln prec l1)) (the (ub_ln prec u1)) l2 u2\") simp\n    with l1 have \"(l, u) = map_bnds lb_exp ub_exp prec (lm, um)\"\n      using lu by (simp add: bnds_powr_def del: lb_ln.simps ub_ln.simps split: if_split_asm)\n    hence \"exp (ln x * y) \\<in> {real_of_float l..real_of_float u}\"\n    proof (rule map_bnds[OF _ mono_exp_real], goal_cases)\n      case 1\n      let ?lln = \"the (lb_ln prec l1)\" and ?uln = \"the (ub_ln prec u1)\"\n      from ub_ln_lb_ln_bounds[of l1 prec] ub_ln_lb_ln_bounds[of u1 prec] x l1\n        have \"real_of_float ?lln \\<le> ln (real_of_float l1) \\<and> \n              ln (real_of_float u1) \\<le> real_of_float ?uln\"\n        by (auto simp del: lb_ln.simps ub_ln.simps)\n      moreover from l1 x have \"ln (real_of_float l1) \\<le> ln x \\<and> ln x \\<le> ln (real_of_float u1)\"\n        by auto\n      ultimately have ln: \"real_of_float ?lln \\<le> ln x \\<and> ln x \\<le> real_of_float ?uln\" by simp\n      from lmum show ?case\n        by (rule bnds_mult) (insert y ln, simp_all)\n    qed (insert exp_boundaries[of lm prec] exp_boundaries[of um prec], simp_all)\n    with x l1 show ?thesis\n      by (simp add: powr_def mult_ac)\n  qed\nqed\n\n\nsection \"Implement floatarith\"\n\nsubsection \"Define syntax and semantics\"\n\ndatatype floatarith\n  = Add floatarith floatarith\n  | Minus floatarith\n  | Mult floatarith floatarith\n  | Inverse floatarith\n  | Cos floatarith\n  | Arctan floatarith\n  | Abs floatarith\n  | Max floatarith floatarith\n  | Min floatarith floatarith\n  | Pi\n  | Sqrt floatarith\n  | Exp floatarith\n  | Powr floatarith floatarith\n  | Ln floatarith\n  | Power floatarith nat\n  | Floor floatarith\n  | Var nat\n  | Num float\n\nfun interpret_floatarith :: \"floatarith \\<Rightarrow> real list \\<Rightarrow> real\" where\n\"interpret_floatarith (Add a b) vs   = (interpret_floatarith a vs) + (interpret_floatarith b vs)\" |\n\"interpret_floatarith (Minus a) vs    = - (interpret_floatarith a vs)\" |\n\"interpret_floatarith (Mult a b) vs   = (interpret_floatarith a vs) * (interpret_floatarith b vs)\" |\n\"interpret_floatarith (Inverse a) vs  = inverse (interpret_floatarith a vs)\" |\n\"interpret_floatarith (Cos a) vs      = cos (interpret_floatarith a vs)\" |\n\"interpret_floatarith (Arctan a) vs   = arctan (interpret_floatarith a vs)\" |\n\"interpret_floatarith (Min a b) vs    = min (interpret_floatarith a vs) (interpret_floatarith b vs)\" |\n\"interpret_floatarith (Max a b) vs    = max (interpret_floatarith a vs) (interpret_floatarith b vs)\" |\n\"interpret_floatarith (Abs a) vs      = \\<bar>interpret_floatarith a vs\\<bar>\" |\n\"interpret_floatarith Pi vs           = pi\" |\n\"interpret_floatarith (Sqrt a) vs     = sqrt (interpret_floatarith a vs)\" |\n\"interpret_floatarith (Exp a) vs      = exp (interpret_floatarith a vs)\" |\n\"interpret_floatarith (Powr a b) vs   = interpret_floatarith a vs powr interpret_floatarith b vs\" |\n\"interpret_floatarith (Ln a) vs       = ln (interpret_floatarith a vs)\" |\n\"interpret_floatarith (Power a n) vs  = (interpret_floatarith a vs)^n\" |\n\"interpret_floatarith (Floor a) vs      = floor (interpret_floatarith a vs)\" |\n\"interpret_floatarith (Num f) vs      = f\" |\n\"interpret_floatarith (Var n) vs     = vs ! n\"\n\nlemma interpret_floatarith_divide:\n  \"interpret_floatarith (Mult a (Inverse b)) vs =\n    (interpret_floatarith a vs) / (interpret_floatarith b vs)\"\n  unfolding divide_inverse interpret_floatarith.simps ..\n\nlemma interpret_floatarith_diff:\n  \"interpret_floatarith (Add a (Minus b)) vs =\n    (interpret_floatarith a vs) - (interpret_floatarith b vs)\"\n  unfolding interpret_floatarith.simps by simp\n\nlemma interpret_floatarith_sin:\n  \"interpret_floatarith (Cos (Add (Mult Pi (Num (Float 1 (- 1)))) (Minus a))) vs =\n    sin (interpret_floatarith a vs)\"\n  unfolding sin_cos_eq interpret_floatarith.simps\n    interpret_floatarith_divide interpret_floatarith_diff\n  by auto\n\n\nsubsection \"Implement approximation function\"\n\nfun lift_bin :: \"(float * float) option \\<Rightarrow> (float * float) option \\<Rightarrow> (float \\<Rightarrow> float \\<Rightarrow> float \\<Rightarrow> float \\<Rightarrow> (float * float) option) \\<Rightarrow> (float * float) option\" where\n\"lift_bin (Some (l1, u1)) (Some (l2, u2)) f = f l1 u1 l2 u2\" |\n\"lift_bin a b f = None\"\n\nfun lift_bin' :: \"(float * float) option \\<Rightarrow> (float * float) option \\<Rightarrow> (float \\<Rightarrow> float \\<Rightarrow> float \\<Rightarrow> float \\<Rightarrow> (float * float)) \\<Rightarrow> (float * float) option\" where\n\"lift_bin' (Some (l1, u1)) (Some (l2, u2)) f = Some (f l1 u1 l2 u2)\" |\n\"lift_bin' a b f = None\"\n\nfun lift_un :: \"(float * float) option \\<Rightarrow> (float \\<Rightarrow> float \\<Rightarrow> ((float option) * (float option))) \\<Rightarrow> (float * float) option\" where\n\"lift_un (Some (l1, u1)) f = (case (f l1 u1) of (Some l, Some u) \\<Rightarrow> Some (l, u)\n                                             | t \\<Rightarrow> None)\" |\n\"lift_un b f = None\"\n\nfun lift_un' :: \"(float * float) option \\<Rightarrow> (float \\<Rightarrow> float \\<Rightarrow> (float * float)) \\<Rightarrow> (float * float) option\" where\n\"lift_un' (Some (l1, u1)) f = Some (f l1 u1)\" |\n\"lift_un' b f = None\"\n\ndefinition bounded_by :: \"real list \\<Rightarrow> (float \\<times> float) option list \\<Rightarrow> bool\" where \n  \"bounded_by xs vs \\<longleftrightarrow>\n  (\\<forall> i < length vs. case vs ! i of None \\<Rightarrow> True\n         | Some (l, u) \\<Rightarrow> xs ! i \\<in> { real_of_float l .. real_of_float u })\"\n                                                                     \nlemma bounded_byE:\n  assumes \"bounded_by xs vs\"\n  shows \"\\<And> i. i < length vs \\<Longrightarrow> case vs ! i of None \\<Rightarrow> True\n         | Some (l, u) \\<Rightarrow> xs ! i \\<in> { real_of_float l .. real_of_float u }\"\n  using assms bounded_by_def by blast\n\nlemma bounded_by_update:\n  assumes \"bounded_by xs vs\"\n    and bnd: \"xs ! i \\<in> { real_of_float l .. real_of_float u }\"\n  shows \"bounded_by xs (vs[i := Some (l,u)])\"\nproof -\n  {\n    fix j\n    let ?vs = \"vs[i := Some (l,u)]\"\n    assume \"j < length ?vs\"\n    hence [simp]: \"j < length vs\" by simp\n    have \"case ?vs ! j of None \\<Rightarrow> True | Some (l, u) \\<Rightarrow> xs ! j \\<in> { real_of_float l .. real_of_float u }\"\n    proof (cases \"?vs ! j\")\n      case (Some b)\n      thus ?thesis\n      proof (cases \"i = j\")\n        case True\n        thus ?thesis using \\<open>?vs ! j = Some b\\<close> and bnd by auto\n      next\n        case False\n        thus ?thesis using \\<open>bounded_by xs vs\\<close> unfolding bounded_by_def by auto\n      qed\n    qed auto\n  }\n  thus ?thesis unfolding bounded_by_def by auto\nqed\n\nlemma bounded_by_None: \"bounded_by xs (replicate (length xs) None)\"\n  unfolding bounded_by_def by auto\n\nfun approx approx' :: \"nat \\<Rightarrow> floatarith \\<Rightarrow> (float * float) option list \\<Rightarrow> (float * float) option\" where\n\"approx' prec a bs          = (case (approx prec a bs) of Some (l, u) \\<Rightarrow> Some (float_round_down prec l, float_round_up prec u) | None \\<Rightarrow> None)\" |\n\"approx prec (Add a b) bs   =\n  lift_bin' (approx' prec a bs) (approx' prec b bs)\n    (\\<lambda> l1 u1 l2 u2. (float_plus_down prec l1 l2, float_plus_up prec u1 u2))\" |\n\"approx prec (Minus a) bs   = lift_un' (approx' prec a bs) (\\<lambda> l u. (-u, -l))\" |\n\"approx prec (Mult a b) bs  =\n  lift_bin' (approx' prec a bs) (approx' prec b bs) (bnds_mult prec)\" |\n\"approx prec (Inverse a) bs = lift_un (approx' prec a bs) (\\<lambda> l u. if (0 < l \\<or> u < 0) then (Some (float_divl prec 1 u), Some (float_divr prec 1 l)) else (None, None))\" |\n\"approx prec (Cos a) bs     = lift_un' (approx' prec a bs) (bnds_cos prec)\" |\n\"approx prec Pi bs          = Some (lb_pi prec, ub_pi prec)\" |\n\"approx prec (Min a b) bs   = lift_bin' (approx' prec a bs) (approx' prec b bs) (\\<lambda> l1 u1 l2 u2. (min l1 l2, min u1 u2))\" |\n\"approx prec (Max a b) bs   = lift_bin' (approx' prec a bs) (approx' prec b bs) (\\<lambda> l1 u1 l2 u2. (max l1 l2, max u1 u2))\" |\n\"approx prec (Abs a) bs     = lift_un' (approx' prec a bs) (\\<lambda>l u. (if l < 0 \\<and> 0 < u then 0 else min \\<bar>l\\<bar> \\<bar>u\\<bar>, max \\<bar>l\\<bar> \\<bar>u\\<bar>))\" |\n\"approx prec (Arctan a) bs  = lift_un' (approx' prec a bs) (\\<lambda> l u. (lb_arctan prec l, ub_arctan prec u))\" |\n\"approx prec (Sqrt a) bs    = lift_un' (approx' prec a bs) (\\<lambda> l u. (lb_sqrt prec l, ub_sqrt prec u))\" |\n\"approx prec (Exp a) bs     = lift_un' (approx' prec a bs) (\\<lambda> l u. (lb_exp prec l, ub_exp prec u))\" |\n\"approx prec (Powr a b) bs  = lift_bin (approx' prec a bs) (approx' prec b bs) (bnds_powr prec)\" |\n\"approx prec (Ln a) bs      = lift_un (approx' prec a bs) (\\<lambda> l u. (lb_ln prec l, ub_ln prec u))\" |\n\"approx prec (Power a n) bs = lift_un' (approx' prec a bs) (float_power_bnds prec n)\" |\n\"approx prec (Floor a) bs = lift_un' (approx' prec a bs) (\\<lambda> l u. (floor_fl l, floor_fl u))\" |\n\"approx prec (Num f) bs     = Some (f, f)\" |\n\"approx prec (Var i) bs    = (if i < length bs then bs ! i else None)\"\n\nlemma approx_approx':\n  assumes Pa: \"\\<And>l u. Some (l, u) = approx prec a vs \\<Longrightarrow>\n      l \\<le> interpret_floatarith a xs \\<and> interpret_floatarith a xs \\<le> u\"\n    and approx': \"Some (l, u) = approx' prec a vs\"\n  shows \"l \\<le> interpret_floatarith a xs \\<and> interpret_floatarith a xs \\<le> u\"\nproof -\n  obtain l' u' where S: \"Some (l', u') = approx prec a vs\"\n    using approx' unfolding approx'.simps by (cases \"approx prec a vs\") auto\n  have l': \"l = float_round_down prec l'\" and u': \"u = float_round_up prec u'\"\n    using approx' unfolding approx'.simps S[symmetric] by auto\n  show ?thesis unfolding l' u'\n    using order_trans[OF Pa[OF S, THEN conjunct2] float_round_up[of u']]\n    using order_trans[OF float_round_down[of _ l'] Pa[OF S, THEN conjunct1]] by auto\nqed\n\nlemma lift_bin_ex:\n  assumes lift_bin_Some: \"Some (l, u) = lift_bin a b f\"\n  shows \"\\<exists> l1 u1 l2 u2. Some (l1, u1) = a \\<and> Some (l2, u2) = b\"\nproof (cases a)\n  case None\n  hence \"None = lift_bin a b f\"\n    unfolding None lift_bin.simps ..\n  thus ?thesis\n    using lift_bin_Some by auto\nnext\n  case (Some a')\n  show ?thesis\n  proof (cases b)\n    case None\n    hence \"None = lift_bin a b f\"\n      unfolding None lift_bin.simps ..\n    thus ?thesis using lift_bin_Some by auto\n  next\n    case (Some b')\n    obtain la ua where a': \"a' = (la, ua)\"\n      by (cases a') auto\n    obtain lb ub where b': \"b' = (lb, ub)\"\n      by (cases b') auto\n    thus ?thesis\n      unfolding \\<open>a = Some a'\\<close> \\<open>b = Some b'\\<close> a' b' by auto\n  qed\nqed\n\nlemma lift_bin_f:\n  assumes lift_bin_Some: \"Some (l, u) = lift_bin (g a) (g b) f\"\n    and Pa: \"\\<And>l u. Some (l, u) = g a \\<Longrightarrow> P l u a\"\n    and Pb: \"\\<And>l u. Some (l, u) = g b \\<Longrightarrow> P l u b\"\n  shows \"\\<exists> l1 u1 l2 u2. P l1 u1 a \\<and> P l2 u2 b \\<and> Some (l, u) = f l1 u1 l2 u2\"\nproof -\n  obtain l1 u1 l2 u2\n    where Sa: \"Some (l1, u1) = g a\"\n      and Sb: \"Some (l2, u2) = g b\"\n    using lift_bin_ex[OF assms(1)] by auto\n  have lu: \"Some (l, u) = f l1 u1 l2 u2\"\n    using lift_bin_Some[unfolded Sa[symmetric] Sb[symmetric] lift_bin.simps] by auto\n  thus ?thesis\n    using Pa[OF Sa] Pb[OF Sb] by auto\nqed\n\nlemma lift_bin:\n  assumes lift_bin_Some: \"Some (l, u) = lift_bin (approx' prec a bs) (approx' prec b bs) f\"\n    and Pa: \"\\<And>l u. Some (l, u) = approx prec a bs \\<Longrightarrow>\n      real_of_float l \\<le> interpret_floatarith a xs \\<and> interpret_floatarith a xs \\<le> real_of_float u\" (is \"\\<And>l u. _ = ?g a \\<Longrightarrow> ?P l u a\")\n    and Pb: \"\\<And>l u. Some (l, u) = approx prec b bs \\<Longrightarrow>\n      real_of_float l \\<le> interpret_floatarith b xs \\<and> interpret_floatarith b xs \\<le> real_of_float u\"\n  shows \"\\<exists>l1 u1 l2 u2. (real_of_float l1 \\<le> interpret_floatarith a xs \\<and> interpret_floatarith a xs \\<le> real_of_float u1) \\<and>\n                       (real_of_float l2 \\<le> interpret_floatarith b xs \\<and> interpret_floatarith b xs \\<le> real_of_float u2) \\<and>\n                       Some (l, u) = (f l1 u1 l2 u2)\"\nproof -\n  { fix l u assume \"Some (l, u) = approx' prec a bs\"\n    with approx_approx'[of prec a bs, OF _ this] Pa\n    have \"l \\<le> interpret_floatarith a xs \\<and> interpret_floatarith a xs \\<le> u\" by auto } note Pa = this\n  { fix l u assume \"Some (l, u) = approx' prec b bs\"\n    with approx_approx'[of prec b bs, OF _ this] Pb\n    have \"l \\<le> interpret_floatarith b xs \\<and> interpret_floatarith b xs \\<le> u\" by auto } note Pb = this\n\n  from lift_bin_f[where g=\"\\<lambda>a. approx' prec a bs\" and P = ?P, OF lift_bin_Some, OF Pa Pb]\n  show ?thesis by auto\nqed\n\nlemma lift_bin'_ex:\n  assumes lift_bin'_Some: \"Some (l, u) = lift_bin' a b f\"\n  shows \"\\<exists> l1 u1 l2 u2. Some (l1, u1) = a \\<and> Some (l2, u2) = b\"\nproof (cases a)\n  case None\n  hence \"None = lift_bin' a b f\"\n    unfolding None lift_bin'.simps ..\n  thus ?thesis\n    using lift_bin'_Some by auto\nnext\n  case (Some a')\n  show ?thesis\n  proof (cases b)\n    case None\n    hence \"None = lift_bin' a b f\"\n      unfolding None lift_bin'.simps ..\n    thus ?thesis using lift_bin'_Some by auto\n  next\n    case (Some b')\n    obtain la ua where a': \"a' = (la, ua)\"\n      by (cases a') auto\n    obtain lb ub where b': \"b' = (lb, ub)\"\n      by (cases b') auto\n    thus ?thesis\n      unfolding \\<open>a = Some a'\\<close> \\<open>b = Some b'\\<close> a' b' by auto\n  qed\nqed\n\nlemma lift_bin'_f:\n  assumes lift_bin'_Some: \"Some (l, u) = lift_bin' (g a) (g b) f\"\n    and Pa: \"\\<And>l u. Some (l, u) = g a \\<Longrightarrow> P l u a\"\n    and Pb: \"\\<And>l u. Some (l, u) = g b \\<Longrightarrow> P l u b\"\n  shows \"\\<exists> l1 u1 l2 u2. P l1 u1 a \\<and> P l2 u2 b \\<and> l = fst (f l1 u1 l2 u2) \\<and> u = snd (f l1 u1 l2 u2)\"\nproof -\n  obtain l1 u1 l2 u2\n    where Sa: \"Some (l1, u1) = g a\"\n      and Sb: \"Some (l2, u2) = g b\"\n    using lift_bin'_ex[OF assms(1)] by auto\n  have lu: \"(l, u) = f l1 u1 l2 u2\"\n    using lift_bin'_Some[unfolded Sa[symmetric] Sb[symmetric] lift_bin'.simps] by auto\n  have \"l = fst (f l1 u1 l2 u2)\" and \"u = snd (f l1 u1 l2 u2)\"\n    unfolding lu[symmetric] by auto\n  thus ?thesis\n    using Pa[OF Sa] Pb[OF Sb] by auto\nqed\n\nlemma lift_bin':\n  assumes lift_bin'_Some: \"Some (l, u) = lift_bin' (approx' prec a bs) (approx' prec b bs) f\"\n    and Pa: \"\\<And>l u. Some (l, u) = approx prec a bs \\<Longrightarrow>\n      l \\<le> interpret_floatarith a xs \\<and> interpret_floatarith a xs \\<le> u\" (is \"\\<And>l u. _ = ?g a \\<Longrightarrow> ?P l u a\")\n    and Pb: \"\\<And>l u. Some (l, u) = approx prec b bs \\<Longrightarrow>\n      l \\<le> interpret_floatarith b xs \\<and> interpret_floatarith b xs \\<le> u\"\n  shows \"\\<exists>l1 u1 l2 u2. (l1 \\<le> interpret_floatarith a xs \\<and> interpret_floatarith a xs \\<le> u1) \\<and>\n                       (l2 \\<le> interpret_floatarith b xs \\<and> interpret_floatarith b xs \\<le> u2) \\<and>\n                       l = fst (f l1 u1 l2 u2) \\<and> u = snd (f l1 u1 l2 u2)\"\nproof -\n  { fix l u assume \"Some (l, u) = approx' prec a bs\"\n    with approx_approx'[of prec a bs, OF _ this] Pa\n    have \"l \\<le> interpret_floatarith a xs \\<and> interpret_floatarith a xs \\<le> u\" by auto } note Pa = this\n  { fix l u assume \"Some (l, u) = approx' prec b bs\"\n    with approx_approx'[of prec b bs, OF _ this] Pb\n    have \"l \\<le> interpret_floatarith b xs \\<and> interpret_floatarith b xs \\<le> u\" by auto } note Pb = this\n\n  from lift_bin'_f[where g=\"\\<lambda>a. approx' prec a bs\" and P = ?P, OF lift_bin'_Some, OF Pa Pb]\n  show ?thesis by auto\nqed\n\nlemma lift_un'_ex:\n  assumes lift_un'_Some: \"Some (l, u) = lift_un' a f\"\n  shows \"\\<exists> l u. Some (l, u) = a\"\nproof (cases a)\n  case None\n  hence \"None = lift_un' a f\"\n    unfolding None lift_un'.simps ..\n  thus ?thesis\n    using lift_un'_Some by auto\nnext\n  case (Some a')\n  obtain la ua where a': \"a' = (la, ua)\"\n    by (cases a') auto\n  thus ?thesis\n    unfolding \\<open>a = Some a'\\<close> a' by auto\nqed\n\nlemma lift_un'_f:\n  assumes lift_un'_Some: \"Some (l, u) = lift_un' (g a) f\"\n    and Pa: \"\\<And>l u. Some (l, u) = g a \\<Longrightarrow> P l u a\"\n  shows \"\\<exists> l1 u1. P l1 u1 a \\<and> l = fst (f l1 u1) \\<and> u = snd (f l1 u1)\"\nproof -\n  obtain l1 u1 where Sa: \"Some (l1, u1) = g a\"\n    using lift_un'_ex[OF assms(1)] by auto\n  have lu: \"(l, u) = f l1 u1\"\n    using lift_un'_Some[unfolded Sa[symmetric] lift_un'.simps] by auto\n  have \"l = fst (f l1 u1)\" and \"u = snd (f l1 u1)\"\n    unfolding lu[symmetric] by auto\n  thus ?thesis\n    using Pa[OF Sa] by auto\nqed\n\nlemma lift_un':\n  assumes lift_un'_Some: \"Some (l, u) = lift_un' (approx' prec a bs) f\"\n    and Pa: \"\\<And>l u. Some (l, u) = approx prec a bs \\<Longrightarrow>\n      l \\<le> interpret_floatarith a xs \\<and> interpret_floatarith a xs \\<le> u\"\n      (is \"\\<And>l u. _ = ?g a \\<Longrightarrow> ?P l u a\")\n  shows \"\\<exists>l1 u1. (l1 \\<le> interpret_floatarith a xs \\<and> interpret_floatarith a xs \\<le> u1) \\<and>\n    l = fst (f l1 u1) \\<and> u = snd (f l1 u1)\"\nproof -\n  have Pa: \"l \\<le> interpret_floatarith a xs \\<and> interpret_floatarith a xs \\<le> u\"\n    if \"Some (l, u) = approx' prec a bs\" for l u\n    using approx_approx'[of prec a bs, OF _ that] Pa\n     by auto\n  from lift_un'_f[where g=\"\\<lambda>a. approx' prec a bs\" and P = ?P, OF lift_un'_Some, OF Pa]\n  show ?thesis by auto\nqed\n\nlemma lift_un'_bnds:\n  assumes bnds: \"\\<forall> (x::real) lx ux. (l, u) = f lx ux \\<and> x \\<in> { lx .. ux } \\<longrightarrow> l \\<le> f' x \\<and> f' x \\<le> u\"\n    and lift_un'_Some: \"Some (l, u) = lift_un' (approx' prec a bs) f\"\n    and Pa: \"\\<And>l u. Some (l, u) = approx prec a bs \\<Longrightarrow>\n      l \\<le> interpret_floatarith a xs \\<and> interpret_floatarith a xs \\<le> u\"\n  shows \"real_of_float l \\<le> f' (interpret_floatarith a xs) \\<and> f' (interpret_floatarith a xs) \\<le> real_of_float u\"\nproof -\n  from lift_un'[OF lift_un'_Some Pa]\n  obtain l1 u1 where \"l1 \\<le> interpret_floatarith a xs\"\n    and \"interpret_floatarith a xs \\<le> u1\"\n    and \"l = fst (f l1 u1)\"\n    and \"u = snd (f l1 u1)\"\n    by blast\n  hence \"(l, u) = f l1 u1\" and \"interpret_floatarith a xs \\<in> {l1 .. u1}\"\n    by auto\n  thus ?thesis\n    using bnds by auto\nqed\n\nlemma lift_un_ex:\n  assumes lift_un_Some: \"Some (l, u) = lift_un a f\"\n  shows \"\\<exists>l u. Some (l, u) = a\"\nproof (cases a)\n  case None\n  hence \"None = lift_un a f\"\n    unfolding None lift_un.simps ..\n  thus ?thesis\n    using lift_un_Some by auto\nnext\n  case (Some a')\n  obtain la ua where a': \"a' = (la, ua)\"\n    by (cases a') auto\n  thus ?thesis\n    unfolding \\<open>a = Some a'\\<close> a' by auto\nqed\n\nlemma lift_un_f:\n  assumes lift_un_Some: \"Some (l, u) = lift_un (g a) f\"\n    and Pa: \"\\<And>l u. Some (l, u) = g a \\<Longrightarrow> P l u a\"\n  shows \"\\<exists> l1 u1. P l1 u1 a \\<and> Some l = fst (f l1 u1) \\<and> Some u = snd (f l1 u1)\"\nproof -\n  obtain l1 u1 where Sa: \"Some (l1, u1) = g a\"\n    using lift_un_ex[OF assms(1)] by auto\n  have \"fst (f l1 u1) \\<noteq> None \\<and> snd (f l1 u1) \\<noteq> None\"\n  proof (rule ccontr)\n    assume \"\\<not> (fst (f l1 u1) \\<noteq> None \\<and> snd (f l1 u1) \\<noteq> None)\"\n    hence or: \"fst (f l1 u1) = None \\<or> snd (f l1 u1) = None\" by auto\n    hence \"lift_un (g a) f = None\"\n    proof (cases \"fst (f l1 u1) = None\")\n      case True\n      then obtain b where b: \"f l1 u1 = (None, b)\"\n        by (cases \"f l1 u1\") auto\n      thus ?thesis\n        unfolding Sa[symmetric] lift_un.simps b by auto\n    next\n      case False\n      hence \"snd (f l1 u1) = None\"\n        using or by auto\n      with False obtain b where b: \"f l1 u1 = (Some b, None)\"\n        by (cases \"f l1 u1\") auto\n      thus ?thesis\n        unfolding Sa[symmetric] lift_un.simps b by auto\n    qed\n    thus False\n      using lift_un_Some by auto\n  qed\n  then obtain a' b' where f: \"f l1 u1 = (Some a', Some b')\"\n    by (cases \"f l1 u1\") auto\n  from lift_un_Some[unfolded Sa[symmetric] lift_un.simps f]\n  have \"Some l = fst (f l1 u1)\" and \"Some u = snd (f l1 u1)\"\n    unfolding f by auto\n  thus ?thesis\n    unfolding Sa[symmetric] lift_un.simps using Pa[OF Sa] by auto\nqed\n\nlemma lift_un:\n  assumes lift_un_Some: \"Some (l, u) = lift_un (approx' prec a bs) f\"\n    and Pa: \"\\<And>l u. Some (l, u) = approx prec a bs \\<Longrightarrow>\n        l \\<le> interpret_floatarith a xs \\<and> interpret_floatarith a xs \\<le> u\"\n      (is \"\\<And>l u. _ = ?g a \\<Longrightarrow> ?P l u a\")\n  shows \"\\<exists>l1 u1. (l1 \\<le> interpret_floatarith a xs \\<and> interpret_floatarith a xs \\<le> u1) \\<and>\n                  Some l = fst (f l1 u1) \\<and> Some u = snd (f l1 u1)\"\nproof -\n  have Pa: \"l \\<le> interpret_floatarith a xs \\<and> interpret_floatarith a xs \\<le> u\"\n    if \"Some (l, u) = approx' prec a bs\" for l u\n    using approx_approx'[of prec a bs, OF _ that] Pa by auto\n  from lift_un_f[where g=\"\\<lambda>a. approx' prec a bs\" and P = ?P, OF lift_un_Some, OF Pa]\n  show ?thesis by auto\nqed\n\nlemma lift_un_bnds:\n  assumes bnds: \"\\<forall>(x::real) lx ux. (Some l, Some u) = f lx ux \\<and> x \\<in> { lx .. ux } \\<longrightarrow> l \\<le> f' x \\<and> f' x \\<le> u\"\n    and lift_un_Some: \"Some (l, u) = lift_un (approx' prec a bs) f\"\n    and Pa: \"\\<And>l u. Some (l, u) = approx prec a bs \\<Longrightarrow>\n      l \\<le> interpret_floatarith a xs \\<and> interpret_floatarith a xs \\<le> u\"\n  shows \"real_of_float l \\<le> f' (interpret_floatarith a xs) \\<and> f' (interpret_floatarith a xs) \\<le> real_of_float u\"\nproof -\n  from lift_un[OF lift_un_Some Pa]\n  obtain l1 u1 where \"l1 \\<le> interpret_floatarith a xs\"\n    and \"interpret_floatarith a xs \\<le> u1\"\n    and \"Some l = fst (f l1 u1)\"\n    and \"Some u = snd (f l1 u1)\"\n    by blast\n  hence \"(Some l, Some u) = f l1 u1\" and \"interpret_floatarith a xs \\<in> {l1 .. u1}\"\n    by auto\n  thus ?thesis\n    using bnds by auto\nqed\n\nlemma approx:\n  assumes \"bounded_by xs vs\"\n    and \"Some (l, u) = approx prec arith vs\" (is \"_ = ?g arith\")\n  shows \"l \\<le> interpret_floatarith arith xs \\<and> interpret_floatarith arith xs \\<le> u\" (is \"?P l u arith\")\n  using \\<open>Some (l, u) = approx prec arith vs\\<close>\nproof (induct arith arbitrary: l u)\n  case (Add a b)\n  from lift_bin'[OF Add.prems[unfolded approx.simps]] Add.hyps\n  obtain l1 u1 l2 u2 where \"l = float_plus_down prec l1 l2\"\n    and \"u = float_plus_up prec u1 u2\" \"l1 \\<le> interpret_floatarith a xs\"\n    and \"interpret_floatarith a xs \\<le> u1\" \"l2 \\<le> interpret_floatarith b xs\"\n    and \"interpret_floatarith b xs \\<le> u2\"\n    unfolding fst_conv snd_conv by blast\n  thus ?case\n    unfolding interpret_floatarith.simps by (auto intro!: float_plus_up_le float_plus_down_le)\nnext\n  case (Minus a)\n  from lift_un'[OF Minus.prems[unfolded approx.simps]] Minus.hyps\n  obtain l1 u1 where \"l = -u1\" \"u = -l1\"\n    and \"l1 \\<le> interpret_floatarith a xs\" \"interpret_floatarith a xs \\<le> u1\"\n    unfolding fst_conv snd_conv by blast\n  thus ?case\n    unfolding interpret_floatarith.simps using minus_float.rep_eq by auto\nnext\n  case (Mult a b)\n  from lift_bin'[OF Mult.prems[unfolded approx.simps]] Mult.hyps\n  obtain l1 u1 l2 u2\n    where l: \"l = fst (bnds_mult prec l1 u1 l2 u2)\"\n    and u: \"u = snd (bnds_mult prec l1 u1 l2 u2)\"\n    and a: \"l1 \\<le> interpret_floatarith a xs\" \"interpret_floatarith a xs \\<le> u1\"\n    and b: \"l2 \\<le> interpret_floatarith b xs\" \"interpret_floatarith b xs \\<le> u2\" unfolding fst_conv snd_conv by blast\n  from l u have lu: \"(l, u) = bnds_mult prec l1 u1 l2 u2\" by simp\n  from bnds_mult[OF lu] a b show ?case by simp\nnext\n  case (Inverse a)\n  from lift_un[OF Inverse.prems[unfolded approx.simps], unfolded if_distrib[of fst] if_distrib[of snd] fst_conv snd_conv] Inverse.hyps\n  obtain l1 u1 where l': \"Some l = (if 0 < l1 \\<or> u1 < 0 then Some (float_divl prec 1 u1) else None)\"\n    and u': \"Some u = (if 0 < l1 \\<or> u1 < 0 then Some (float_divr prec 1 l1) else None)\"\n    and l1: \"l1 \\<le> interpret_floatarith a xs\"\n    and u1: \"interpret_floatarith a xs \\<le> u1\"\n    by blast\n  have either: \"0 < l1 \\<or> u1 < 0\"\n  proof (rule ccontr)\n    assume P: \"\\<not> (0 < l1 \\<or> u1 < 0)\"\n    show False\n      using l' unfolding if_not_P[OF P] by auto\n  qed\n  moreover have l1_le_u1: \"real_of_float l1 \\<le> real_of_float u1\"\n    using l1 u1 by auto\n  ultimately have \"real_of_float l1 \\<noteq> 0\" and \"real_of_float u1 \\<noteq> 0\"\n    by auto\n\n  have inv: \"inverse u1 \\<le> inverse (interpret_floatarith a xs)\n           \\<and> inverse (interpret_floatarith a xs) \\<le> inverse l1\"\n  proof (cases \"0 < l1\")\n    case True\n    hence \"0 < real_of_float u1\" and \"0 < real_of_float l1\" \"0 < interpret_floatarith a xs\"\n      using l1_le_u1 l1 by auto\n    show ?thesis\n      unfolding inverse_le_iff_le[OF \\<open>0 < real_of_float u1\\<close> \\<open>0 < interpret_floatarith a xs\\<close>]\n        inverse_le_iff_le[OF \\<open>0 < interpret_floatarith a xs\\<close> \\<open>0 < real_of_float l1\\<close>]\n      using l1 u1 by auto\n  next\n    case False\n    hence \"u1 < 0\"\n      using either by blast\n    hence \"real_of_float u1 < 0\" and \"real_of_float l1 < 0\" \"interpret_floatarith a xs < 0\"\n      using l1_le_u1 u1 by auto\n    show ?thesis\n      unfolding inverse_le_iff_le_neg[OF \\<open>real_of_float u1 < 0\\<close> \\<open>interpret_floatarith a xs < 0\\<close>]\n        inverse_le_iff_le_neg[OF \\<open>interpret_floatarith a xs < 0\\<close> \\<open>real_of_float l1 < 0\\<close>]\n      using l1 u1 by auto\n  qed\n\n  from l' have \"l = float_divl prec 1 u1\"\n    by (cases \"0 < l1 \\<or> u1 < 0\") auto\n  hence \"l \\<le> inverse u1\"\n    unfolding nonzero_inverse_eq_divide[OF \\<open>real_of_float u1 \\<noteq> 0\\<close>]\n    using float_divl[of prec 1 u1] by auto\n  also have \"\\<dots> \\<le> inverse (interpret_floatarith a xs)\"\n    using inv by auto\n  finally have \"l \\<le> inverse (interpret_floatarith a xs)\" .\n  moreover\n  from u' have \"u = float_divr prec 1 l1\"\n    by (cases \"0 < l1 \\<or> u1 < 0\") auto\n  hence \"inverse l1 \\<le> u\"\n    unfolding nonzero_inverse_eq_divide[OF \\<open>real_of_float l1 \\<noteq> 0\\<close>]\n    using float_divr[of 1 l1 prec] by auto\n  hence \"inverse (interpret_floatarith a xs) \\<le> u\"\n    by (rule order_trans[OF inv[THEN conjunct2]])\n  ultimately show ?case\n    unfolding interpret_floatarith.simps using l1 u1 by auto\nnext\n  case (Abs x)\n  from lift_un'[OF Abs.prems[unfolded approx.simps], unfolded fst_conv snd_conv] Abs.hyps\n  obtain l1 u1 where l': \"l = (if l1 < 0 \\<and> 0 < u1 then 0 else min \\<bar>l1\\<bar> \\<bar>u1\\<bar>)\"\n    and u': \"u = max \\<bar>l1\\<bar> \\<bar>u1\\<bar>\"\n    and l1: \"l1 \\<le> interpret_floatarith x xs\"\n    and u1: \"interpret_floatarith x xs \\<le> u1\"\n    by blast\n  thus ?case\n    unfolding l' u'\n    by (cases \"l1 < 0 \\<and> 0 < u1\") (auto simp add: real_of_float_min real_of_float_max)\nnext\n  case (Min a b)\n  from lift_bin'[OF Min.prems[unfolded approx.simps], unfolded fst_conv snd_conv] Min.hyps\n  obtain l1 u1 l2 u2 where l': \"l = min l1 l2\" and u': \"u = min u1 u2\"\n    and l1: \"l1 \\<le> interpret_floatarith a xs\" and u1: \"interpret_floatarith a xs \\<le> u1\"\n    and l1: \"l2 \\<le> interpret_floatarith b xs\" and u1: \"interpret_floatarith b xs \\<le> u2\"\n    by blast\n  thus ?case\n    unfolding l' u' by (auto simp add: real_of_float_min)\nnext\n  case (Max a b)\n  from lift_bin'[OF Max.prems[unfolded approx.simps], unfolded fst_conv snd_conv] Max.hyps\n  obtain l1 u1 l2 u2 where l': \"l = max l1 l2\" and u': \"u = max u1 u2\"\n    and l1: \"l1 \\<le> interpret_floatarith a xs\" and u1: \"interpret_floatarith a xs \\<le> u1\"\n    and l1: \"l2 \\<le> interpret_floatarith b xs\" and u1: \"interpret_floatarith b xs \\<le> u2\"\n    by blast\n  thus ?case\n    unfolding l' u' by (auto simp add: real_of_float_max)\nnext\n  case (Cos a)\n  with lift_un'_bnds[OF bnds_cos] show ?case by auto\nnext\n  case (Arctan a)\n  with lift_un'_bnds[OF bnds_arctan] show ?case by auto\nnext\n  case Pi\n  with pi_boundaries show ?case by auto\nnext\n  case (Sqrt a)\n  with lift_un'_bnds[OF bnds_sqrt] show ?case by auto\nnext\n  case (Exp a)\n  with lift_un'_bnds[OF bnds_exp] show ?case by auto\nnext\n  case (Powr a b)\n  from lift_bin[OF Powr.prems[unfolded approx.simps]] Powr.hyps\n    obtain l1 u1 l2 u2 where lu: \"Some (l, u) = bnds_powr prec l1 u1 l2 u2\"\n      and l1: \"l1 \\<le> interpret_floatarith a xs\" and u1: \"interpret_floatarith a xs \\<le> u1\"\n      and l2: \"l2 \\<le> interpret_floatarith b xs\" and u2: \"interpret_floatarith b xs \\<le> u2\"\n      by blast\n  from bnds_powr[OF lu] l1 u1 l2 u2\n    show ?case by simp\nnext\n  case (Ln a)\n  with lift_un_bnds[OF bnds_ln] show ?case by auto\nnext\n  case (Power a n)\n  with lift_un'_bnds[OF bnds_power] show ?case by auto\nnext\n  case (Floor a)\n  from lift_un'[OF Floor.prems[unfolded approx.simps] Floor.hyps]\n  show ?case by (auto simp: floor_fl.rep_eq floor_mono)\nnext\n  case (Num f)\n  thus ?case by auto\nnext\n  case (Var n)\n  from this[symmetric] \\<open>bounded_by xs vs\\<close>[THEN bounded_byE, of n]\n  show ?case by (cases \"n < length vs\") auto\nqed\n\ndatatype form = Bound floatarith floatarith floatarith form\n              | Assign floatarith floatarith form\n              | Less floatarith floatarith\n              | LessEqual floatarith floatarith\n              | AtLeastAtMost floatarith floatarith floatarith\n              | Conj form form\n              | Disj form form\n\nfun interpret_form :: \"form \\<Rightarrow> real list \\<Rightarrow> bool\" where\n\"interpret_form (Bound x a b f) vs = (interpret_floatarith x vs \\<in> { interpret_floatarith a vs .. interpret_floatarith b vs } \\<longrightarrow> interpret_form f vs)\" |\n\"interpret_form (Assign x a f) vs  = (interpret_floatarith x vs = interpret_floatarith a vs \\<longrightarrow> interpret_form f vs)\" |\n\"interpret_form (Less a b) vs      = (interpret_floatarith a vs < interpret_floatarith b vs)\" |\n\"interpret_form (LessEqual a b) vs = (interpret_floatarith a vs \\<le> interpret_floatarith b vs)\" |\n\"interpret_form (AtLeastAtMost x a b) vs = (interpret_floatarith x vs \\<in> { interpret_floatarith a vs .. interpret_floatarith b vs })\" |\n\"interpret_form (Conj f g) vs \\<longleftrightarrow> interpret_form f vs \\<and> interpret_form g vs\" |\n\"interpret_form (Disj f g) vs \\<longleftrightarrow> interpret_form f vs \\<or> interpret_form g vs\"\n\nfun approx_form' and approx_form :: \"nat \\<Rightarrow> form \\<Rightarrow> (float * float) option list \\<Rightarrow> nat list \\<Rightarrow> bool\" where\n\"approx_form' prec f 0 n l u bs ss = approx_form prec f (bs[n := Some (l, u)]) ss\" |\n\"approx_form' prec f (Suc s) n l u bs ss =\n  (let m = (l + u) * Float 1 (- 1)\n   in (if approx_form' prec f s n l m bs ss then approx_form' prec f s n m u bs ss else False))\" |\n\"approx_form prec (Bound (Var n) a b f) bs ss =\n   (case (approx prec a bs, approx prec b bs)\n   of (Some (l, _), Some (_, u)) \\<Rightarrow> approx_form' prec f (ss ! n) n l u bs ss\n    | _ \\<Rightarrow> False)\" |\n\"approx_form prec (Assign (Var n) a f) bs ss =\n   (case (approx prec a bs)\n   of (Some (l, u)) \\<Rightarrow> approx_form' prec f (ss ! n) n l u bs ss\n    | _ \\<Rightarrow> False)\" |\n\"approx_form prec (Less a b) bs ss =\n   (case (approx prec a bs, approx prec b bs)\n   of (Some (l, u), Some (l', u')) \\<Rightarrow> float_plus_up prec u (-l') < 0\n    | _ \\<Rightarrow> False)\" |\n\"approx_form prec (LessEqual a b) bs ss =\n   (case (approx prec a bs, approx prec b bs)\n   of (Some (l, u), Some (l', u')) \\<Rightarrow> float_plus_up prec u (-l') \\<le> 0\n    | _ \\<Rightarrow> False)\" |\n\"approx_form prec (AtLeastAtMost x a b) bs ss =\n   (case (approx prec x bs, approx prec a bs, approx prec b bs)\n   of (Some (lx, ux), Some (l, u), Some (l', u')) \\<Rightarrow> float_plus_up prec u (-lx) \\<le> 0 \\<and> float_plus_up prec ux (-l') \\<le> 0\n    | _ \\<Rightarrow> False)\" |\n\"approx_form prec (Conj a b) bs ss \\<longleftrightarrow> approx_form prec a bs ss \\<and> approx_form prec b bs ss\" |\n\"approx_form prec (Disj a b) bs ss \\<longleftrightarrow> approx_form prec a bs ss \\<or> approx_form prec b bs ss\" |\n\"approx_form _ _ _ _ = False\"\n\nlemma lazy_conj: \"(if A then B else False) = (A \\<and> B)\" by simp\n\nlemma approx_form_approx_form':\n  assumes \"approx_form' prec f s n l u bs ss\"\n    and \"(x::real) \\<in> { l .. u }\"\n  obtains l' u' where \"x \\<in> { l' .. u' }\"\n    and \"approx_form prec f (bs[n := Some (l', u')]) ss\"\nusing assms proof (induct s arbitrary: l u)\n  case 0\n  from this(1)[of l u] this(2,3)\n  show thesis by auto\nnext\n  case (Suc s)\n\n  let ?m = \"(l + u) * Float 1 (- 1)\"\n  have \"real_of_float l \\<le> ?m\" and \"?m \\<le> real_of_float u\"\n    unfolding less_eq_float_def using Suc.prems by auto\n\n  with \\<open>x \\<in> { l .. u }\\<close>\n  have \"x \\<in> { l .. ?m} \\<or> x \\<in> { ?m .. u }\" by auto\n  thus thesis\n  proof (rule disjE)\n    assume *: \"x \\<in> { l .. ?m }\"\n    with Suc.hyps[OF _ _ *] Suc.prems\n    show thesis by (simp add: Let_def lazy_conj)\n  next\n    assume *: \"x \\<in> { ?m .. u }\"\n    with Suc.hyps[OF _ _ *] Suc.prems\n    show thesis by (simp add: Let_def lazy_conj)\n  qed\nqed\n\nlemma approx_form_aux:\n  assumes \"approx_form prec f vs ss\"\n    and \"bounded_by xs vs\"\n  shows \"interpret_form f xs\"\nusing assms proof (induct f arbitrary: vs)\n  case (Bound x a b f)\n  then obtain n\n    where x_eq: \"x = Var n\" by (cases x) auto\n\n  with Bound.prems obtain l u' l' u\n    where l_eq: \"Some (l, u') = approx prec a vs\"\n    and u_eq: \"Some (l', u) = approx prec b vs\"\n    and approx_form': \"approx_form' prec f (ss ! n) n l u vs ss\"\n    by (cases \"approx prec a vs\", simp) (cases \"approx prec b vs\", auto)\n\n  have \"interpret_form f xs\"\n    if \"xs ! n \\<in> { interpret_floatarith a xs .. interpret_floatarith b xs }\"\n  proof -\n    from approx[OF Bound.prems(2) l_eq] and approx[OF Bound.prems(2) u_eq] that\n    have \"xs ! n \\<in> { l .. u}\" by auto\n\n    from approx_form_approx_form'[OF approx_form' this]\n    obtain lx ux where bnds: \"xs ! n \\<in> { lx .. ux }\"\n      and approx_form: \"approx_form prec f (vs[n := Some (lx, ux)]) ss\" .\n\n    from \\<open>bounded_by xs vs\\<close> bnds have \"bounded_by xs (vs[n := Some (lx, ux)])\"\n      by (rule bounded_by_update)\n    with Bound.hyps[OF approx_form] show ?thesis\n      by blast\n  qed\n  thus ?case\n    using interpret_form.simps x_eq and interpret_floatarith.simps by simp\nnext\n  case (Assign x a f)\n  then obtain n where x_eq: \"x = Var n\"\n    by (cases x) auto\n\n  with Assign.prems obtain l u\n    where bnd_eq: \"Some (l, u) = approx prec a vs\"\n    and x_eq: \"x = Var n\"\n    and approx_form': \"approx_form' prec f (ss ! n) n l u vs ss\"\n    by (cases \"approx prec a vs\") auto\n\n  have \"interpret_form f xs\"\n    if bnds: \"xs ! n = interpret_floatarith a xs\"\n  proof -\n    from approx[OF Assign.prems(2) bnd_eq] bnds\n    have \"xs ! n \\<in> { l .. u}\" by auto\n    from approx_form_approx_form'[OF approx_form' this]\n    obtain lx ux where bnds: \"xs ! n \\<in> { lx .. ux }\"\n      and approx_form: \"approx_form prec f (vs[n := Some (lx, ux)]) ss\" .\n\n    from \\<open>bounded_by xs vs\\<close> bnds have \"bounded_by xs (vs[n := Some (lx, ux)])\"\n      by (rule bounded_by_update)\n    with Assign.hyps[OF approx_form] show ?thesis\n      by blast\n  qed\n  thus ?case\n    using interpret_form.simps x_eq and interpret_floatarith.simps by simp\nnext\n  case (Less a b)\n  then obtain l u l' u'\n    where l_eq: \"Some (l, u) = approx prec a vs\"\n      and u_eq: \"Some (l', u') = approx prec b vs\"\n      and inequality: \"real_of_float (float_plus_up prec u (-l')) < 0\"\n    by (cases \"approx prec a vs\", auto, cases \"approx prec b vs\", auto)\n  from le_less_trans[OF float_plus_up inequality]\n    approx[OF Less.prems(2) l_eq] approx[OF Less.prems(2) u_eq]\n  show ?case by auto\nnext\n  case (LessEqual a b)\n  then obtain l u l' u'\n    where l_eq: \"Some (l, u) = approx prec a vs\"\n      and u_eq: \"Some (l', u') = approx prec b vs\"\n      and inequality: \"real_of_float (float_plus_up prec u (-l')) \\<le> 0\"\n    by (cases \"approx prec a vs\", auto, cases \"approx prec b vs\", auto)\n  from order_trans[OF float_plus_up inequality]\n    approx[OF LessEqual.prems(2) l_eq] approx[OF LessEqual.prems(2) u_eq]\n  show ?case by auto\nnext\n  case (AtLeastAtMost x a b)\n  then obtain lx ux l u l' u'\n    where x_eq: \"Some (lx, ux) = approx prec x vs\"\n    and l_eq: \"Some (l, u) = approx prec a vs\"\n    and u_eq: \"Some (l', u') = approx prec b vs\"\n    and inequality: \"real_of_float (float_plus_up prec u (-lx)) \\<le> 0\" \"real_of_float (float_plus_up prec ux (-l')) \\<le> 0\"\n    by (cases \"approx prec x vs\", auto,\n      cases \"approx prec a vs\", auto,\n      cases \"approx prec b vs\", auto)\n  from order_trans[OF float_plus_up inequality(1)] order_trans[OF float_plus_up inequality(2)]\n    approx[OF AtLeastAtMost.prems(2) l_eq] approx[OF AtLeastAtMost.prems(2) u_eq] approx[OF AtLeastAtMost.prems(2) x_eq]\n  show ?case by auto\nqed auto\n\nlemma approx_form:\n  assumes \"n = length xs\"\n    and \"approx_form prec f (replicate n None) ss\"\n  shows \"interpret_form f xs\"\n  using approx_form_aux[OF _ bounded_by_None] assms by auto\n\n\nsubsection \\<open>Implementing Taylor series expansion\\<close>\n\nfun isDERIV :: \"nat \\<Rightarrow> floatarith \\<Rightarrow> real list \\<Rightarrow> bool\" where\n\"isDERIV x (Add a b) vs         = (isDERIV x a vs \\<and> isDERIV x b vs)\" |\n\"isDERIV x (Mult a b) vs        = (isDERIV x a vs \\<and> isDERIV x b vs)\" |\n\"isDERIV x (Minus a) vs         = isDERIV x a vs\" |\n\"isDERIV x (Inverse a) vs       = (isDERIV x a vs \\<and> interpret_floatarith a vs \\<noteq> 0)\" |\n\"isDERIV x (Cos a) vs           = isDERIV x a vs\" |\n\"isDERIV x (Arctan a) vs        = isDERIV x a vs\" |\n\"isDERIV x (Min a b) vs         = False\" |\n\"isDERIV x (Max a b) vs         = False\" |\n\"isDERIV x (Abs a) vs           = False\" |\n\"isDERIV x Pi vs                = True\" |\n\"isDERIV x (Sqrt a) vs          = (isDERIV x a vs \\<and> interpret_floatarith a vs > 0)\" |\n\"isDERIV x (Exp a) vs           = isDERIV x a vs\" |\n\"isDERIV x (Powr a b) vs        =\n    (isDERIV x a vs \\<and> isDERIV x b vs \\<and> interpret_floatarith a vs > 0)\" |\n\"isDERIV x (Ln a) vs            = (isDERIV x a vs \\<and> interpret_floatarith a vs > 0)\" |\n\"isDERIV x (Floor a) vs         = (isDERIV x a vs \\<and> interpret_floatarith a vs \\<notin> \\<int>)\" |\n\"isDERIV x (Power a 0) vs       = True\" |\n\"isDERIV x (Power a (Suc n)) vs = isDERIV x a vs\" |\n\"isDERIV x (Num f) vs           = True\" |\n\"isDERIV x (Var n) vs          = True\"\n\nfun DERIV_floatarith :: \"nat \\<Rightarrow> floatarith \\<Rightarrow> floatarith\" where\n\"DERIV_floatarith x (Add a b)         = Add (DERIV_floatarith x a) (DERIV_floatarith x b)\" |\n\"DERIV_floatarith x (Mult a b)        = Add (Mult a (DERIV_floatarith x b)) (Mult (DERIV_floatarith x a) b)\" |\n\"DERIV_floatarith x (Minus a)         = Minus (DERIV_floatarith x a)\" |\n\"DERIV_floatarith x (Inverse a)       = Minus (Mult (DERIV_floatarith x a) (Inverse (Power a 2)))\" |\n\"DERIV_floatarith x (Cos a)           = Minus (Mult (Cos (Add (Mult Pi (Num (Float 1 (- 1)))) (Minus a))) (DERIV_floatarith x a))\" |\n\"DERIV_floatarith x (Arctan a)        = Mult (Inverse (Add (Num 1) (Power a 2))) (DERIV_floatarith x a)\" |\n\"DERIV_floatarith x (Min a b)         = Num 0\" |\n\"DERIV_floatarith x (Max a b)         = Num 0\" |\n\"DERIV_floatarith x (Abs a)           = Num 0\" |\n\"DERIV_floatarith x Pi                = Num 0\" |\n\"DERIV_floatarith x (Sqrt a)          = (Mult (Inverse (Mult (Sqrt a) (Num 2))) (DERIV_floatarith x a))\" |\n\"DERIV_floatarith x (Exp a)           = Mult (Exp a) (DERIV_floatarith x a)\" |\n\"DERIV_floatarith x (Powr a b)        =\n   Mult (Powr a b) (Add (Mult (DERIV_floatarith x b) (Ln a)) (Mult (Mult (DERIV_floatarith x a) b) (Inverse a)))\" |\n\"DERIV_floatarith x (Ln a)            = Mult (Inverse a) (DERIV_floatarith x a)\" |\n\"DERIV_floatarith x (Power a 0)       = Num 0\" |\n\"DERIV_floatarith x (Power a (Suc n)) = Mult (Num (Float (int (Suc n)) 0)) (Mult (Power a n) (DERIV_floatarith x a))\" |\n\"DERIV_floatarith x (Floor a)         = Num 0\" |\n\"DERIV_floatarith x (Num f)           = Num 0\" |\n\"DERIV_floatarith x (Var n)          = (if x = n then Num 1 else Num 0)\"\n\nlemma has_real_derivative_powr':\n  fixes f g :: \"real \\<Rightarrow> real\"\n  assumes \"(f has_real_derivative f') (at x)\"\n  assumes \"(g has_real_derivative g') (at x)\"\n  assumes \"f x > 0\"\n  defines \"h \\<equiv> \\<lambda>x. f x powr g x * (g' * ln (f x) + f' * g x / f x)\"\n  shows   \"((\\<lambda>x. f x powr g x) has_real_derivative h x) (at x)\"\nproof (subst DERIV_cong_ev[OF refl _ refl])\n  from assms have \"isCont f x\"\n    by (simp add: DERIV_continuous)\n  hence \"f \\<midarrow>x\\<rightarrow> f x\" by (simp add: continuous_at)\n  with \\<open>f x > 0\\<close> have \"eventually (\\<lambda>x. f x > 0) (nhds x)\"\n    by (auto simp: tendsto_at_iff_tendsto_nhds dest: order_tendstoD)\n  thus \"eventually (\\<lambda>x. f x powr g x = exp (g x * ln (f x))) (nhds x)\"\n    by eventually_elim (simp add: powr_def)\nnext\n  from assms show \"((\\<lambda>x. exp (g x * ln (f x))) has_real_derivative h x) (at x)\"\n    by (auto intro!: derivative_eq_intros simp: h_def powr_def)\nqed\n\nlemma DERIV_floatarith:\n  assumes \"n < length vs\"\n  assumes isDERIV: \"isDERIV n f (vs[n := x])\"\n  shows \"DERIV (\\<lambda> x'. interpret_floatarith f (vs[n := x'])) x :>\n               interpret_floatarith (DERIV_floatarith n f) (vs[n := x])\"\n   (is \"DERIV (?i f) x :> _\")\nusing isDERIV\nproof (induct f arbitrary: x)\n  case (Inverse a)\n  thus ?case\n    by (auto intro!: derivative_eq_intros simp add: algebra_simps power2_eq_square)\nnext\n  case (Cos a)\n  thus ?case\n    by (auto intro!: derivative_eq_intros\n           simp del: interpret_floatarith.simps(5)\n           simp add: interpret_floatarith_sin interpret_floatarith.simps(5)[of a])\nnext\n  case (Power a n)\n  thus ?case\n    by (cases n) (auto intro!: derivative_eq_intros simp del: power_Suc)\nnext\n  case (Floor a)\n  thus ?case\n    by (auto intro!: derivative_eq_intros DERIV_isCont floor_has_real_derivative)\nnext\n  case (Ln a)\n  thus ?case by (auto intro!: derivative_eq_intros simp add: divide_inverse)\nnext\n  case (Var i)\n  thus ?case using \\<open>n < length vs\\<close> by auto\nnext\n  case (Powr a b)\n  note [derivative_intros] = has_real_derivative_powr'\n  from Powr show ?case\n    by (auto intro!: derivative_eq_intros simp: field_simps)\nqed (auto intro!: derivative_eq_intros)\n\ndeclare approx.simps[simp del]\n\nfun isDERIV_approx :: \"nat \\<Rightarrow> nat \\<Rightarrow> floatarith \\<Rightarrow> (float * float) option list \\<Rightarrow> bool\" where\n\"isDERIV_approx prec x (Add a b) vs         = (isDERIV_approx prec x a vs \\<and> isDERIV_approx prec x b vs)\" |\n\"isDERIV_approx prec x (Mult a b) vs        = (isDERIV_approx prec x a vs \\<and> isDERIV_approx prec x b vs)\" |\n\"isDERIV_approx prec x (Minus a) vs         = isDERIV_approx prec x a vs\" |\n\"isDERIV_approx prec x (Inverse a) vs       =\n  (isDERIV_approx prec x a vs \\<and> (case approx prec a vs of Some (l, u) \\<Rightarrow> 0 < l \\<or> u < 0 | None \\<Rightarrow> False))\" |\n\"isDERIV_approx prec x (Cos a) vs           = isDERIV_approx prec x a vs\" |\n\"isDERIV_approx prec x (Arctan a) vs        = isDERIV_approx prec x a vs\" |\n\"isDERIV_approx prec x (Min a b) vs         = False\" |\n\"isDERIV_approx prec x (Max a b) vs         = False\" |\n\"isDERIV_approx prec x (Abs a) vs           = False\" |\n\"isDERIV_approx prec x Pi vs                = True\" |\n\"isDERIV_approx prec x (Sqrt a) vs          =\n  (isDERIV_approx prec x a vs \\<and> (case approx prec a vs of Some (l, u) \\<Rightarrow> 0 < l | None \\<Rightarrow> False))\" |\n\"isDERIV_approx prec x (Exp a) vs           = isDERIV_approx prec x a vs\" |\n\"isDERIV_approx prec x (Powr a b) vs        =\n  (isDERIV_approx prec x a vs \\<and> isDERIV_approx prec x b vs \\<and> (case approx prec a vs of Some (l, u) \\<Rightarrow> 0 < l | None \\<Rightarrow> False))\" |\n\"isDERIV_approx prec x (Ln a) vs            =\n  (isDERIV_approx prec x a vs \\<and> (case approx prec a vs of Some (l, u) \\<Rightarrow> 0 < l | None \\<Rightarrow> False))\" |\n\"isDERIV_approx prec x (Power a 0) vs       = True\" |\n\"isDERIV_approx prec x (Floor a) vs         =\n  (isDERIV_approx prec x a vs \\<and> (case approx prec a vs of Some (l, u) \\<Rightarrow> l > floor u \\<and> u < ceiling l | None \\<Rightarrow> False))\" |\n\"isDERIV_approx prec x (Power a (Suc n)) vs = isDERIV_approx prec x a vs\" |\n\"isDERIV_approx prec x (Num f) vs           = True\" |\n\"isDERIV_approx prec x (Var n) vs           = True\"\n\nlemma isDERIV_approx:\n  assumes \"bounded_by xs vs\"\n    and isDERIV_approx: \"isDERIV_approx prec x f vs\"\n  shows \"isDERIV x f xs\"\n  using isDERIV_approx\nproof (induct f)\n  case (Inverse a)\n  then obtain l u where approx_Some: \"Some (l, u) = approx prec a vs\"\n    and *: \"0 < l \\<or> u < 0\"\n    by (cases \"approx prec a vs\") auto\n  with approx[OF \\<open>bounded_by xs vs\\<close> approx_Some]\n  have \"interpret_floatarith a xs \\<noteq> 0\" by auto\n  thus ?case using Inverse by auto\nnext\n  case (Ln a)\n  then obtain l u where approx_Some: \"Some (l, u) = approx prec a vs\"\n    and *: \"0 < l\"\n    by (cases \"approx prec a vs\") auto\n  with approx[OF \\<open>bounded_by xs vs\\<close> approx_Some]\n  have \"0 < interpret_floatarith a xs\" by auto\n  thus ?case using Ln by auto\nnext\n  case (Sqrt a)\n  then obtain l u where approx_Some: \"Some (l, u) = approx prec a vs\"\n    and *: \"0 < l\"\n    by (cases \"approx prec a vs\") auto\n  with approx[OF \\<open>bounded_by xs vs\\<close> approx_Some]\n  have \"0 < interpret_floatarith a xs\" by auto\n  thus ?case using Sqrt by auto\nnext\n  case (Power a n)\n  thus ?case by (cases n) auto\nnext\n  case (Powr a b)\n  from Powr obtain l1 u1 where a: \"Some (l1, u1) = approx prec a vs\" and pos: \"0 < l1\"\n    by (cases \"approx prec a vs\") auto\n  with approx[OF \\<open>bounded_by xs vs\\<close> a]\n    have \"0 < interpret_floatarith a xs\" by auto\n  with Powr show ?case by auto\nnext\n  case (Floor a)\n  then obtain l u where approx_Some: \"Some (l, u) = approx prec a vs\"\n    and \"real_of_int \\<lfloor>real_of_float u\\<rfloor> < real_of_float l\" \"real_of_float u < real_of_int \\<lceil>real_of_float l\\<rceil>\"\n    and \"isDERIV x a xs\"\n    by (cases \"approx prec a vs\") auto\n  with approx[OF \\<open>bounded_by xs vs\\<close> approx_Some] le_floor_iff\n  show ?case\n    by (force elim!: Ints_cases)\nqed auto\n\nlemma bounded_by_update_var:\n  assumes \"bounded_by xs vs\"\n    and \"vs ! i = Some (l, u)\"\n    and bnd: \"x \\<in> { real_of_float l .. real_of_float u }\"\n  shows \"bounded_by (xs[i := x]) vs\"\nproof (cases \"i < length xs\")\n  case False\n  thus ?thesis\n    using \\<open>bounded_by xs vs\\<close> by auto\nnext\n  case True\n  let ?xs = \"xs[i := x]\"\n  from True have \"i < length ?xs\" by auto\n  have \"case vs ! j of None \\<Rightarrow> True | Some (l, u) \\<Rightarrow> ?xs ! j \\<in> {real_of_float l .. real_of_float u}\"\n    if \"j < length vs\" for j\n  proof (cases \"vs ! j\")\n    case None\n    then show ?thesis by simp\n  next\n    case (Some b)\n    thus ?thesis\n    proof (cases \"i = j\")\n      case True\n      thus ?thesis using \\<open>vs ! i = Some (l, u)\\<close> Some and bnd \\<open>i < length ?xs\\<close>\n        by auto\n    next\n      case False\n      thus ?thesis\n        using \\<open>bounded_by xs vs\\<close>[THEN bounded_byE, OF \\<open>j < length vs\\<close>] Some by auto\n    qed\n  qed\n  thus ?thesis\n    unfolding bounded_by_def by auto\nqed\n\nlemma isDERIV_approx':\n  assumes \"bounded_by xs vs\"\n    and vs_x: \"vs ! x = Some (l, u)\"\n    and X_in: \"X \\<in> {real_of_float l .. real_of_float u}\"\n    and approx: \"isDERIV_approx prec x f vs\"\n  shows \"isDERIV x f (xs[x := X])\"\nproof -\n  from bounded_by_update_var[OF \\<open>bounded_by xs vs\\<close> vs_x X_in] approx\n  show ?thesis by (rule isDERIV_approx)\nqed\n\nlemma DERIV_approx:\n  assumes \"n < length xs\"\n    and bnd: \"bounded_by xs vs\"\n    and isD: \"isDERIV_approx prec n f vs\"\n    and app: \"Some (l, u) = approx prec (DERIV_floatarith n f) vs\" (is \"_ = approx _ ?D _\")\n  shows \"\\<exists>(x::real). l \\<le> x \\<and> x \\<le> u \\<and>\n             DERIV (\\<lambda> x. interpret_floatarith f (xs[n := x])) (xs!n) :> x\"\n         (is \"\\<exists> x. _ \\<and> _ \\<and> DERIV (?i f) _ :> _\")\nproof (rule exI[of _ \"?i ?D (xs!n)\"], rule conjI[OF _ conjI])\n  let \"?i f\" = \"\\<lambda>x. interpret_floatarith f (xs[n := x])\"\n  from approx[OF bnd app]\n  show \"l \\<le> ?i ?D (xs!n)\" and \"?i ?D (xs!n) \\<le> u\"\n    using \\<open>n < length xs\\<close> by auto\n  from DERIV_floatarith[OF \\<open>n < length xs\\<close>, of f \"xs!n\"] isDERIV_approx[OF bnd isD]\n  show \"DERIV (?i f) (xs!n) :> (?i ?D (xs!n))\"\n    by simp\nqed\n\nlemma lift_bin_aux:\n  assumes lift_bin_Some: \"Some (l, u) = lift_bin a b f\"\n  obtains l1 u1 l2 u2\n  where \"a = Some (l1, u1)\"\n    and \"b = Some (l2, u2)\"\n    and \"f l1 u1 l2 u2 = Some (l, u)\"\n  using assms by (cases a, simp, cases b, simp, auto)\n\n\nfun approx_tse where\n\"approx_tse prec n 0 c k f bs = approx prec f bs\" |\n\"approx_tse prec n (Suc s) c k f bs =\n  (if isDERIV_approx prec n f bs then\n    lift_bin (approx prec f (bs[n := Some (c,c)]))\n             (approx_tse prec n s c (Suc k) (DERIV_floatarith n f) bs)\n             (\\<lambda> l1 u1 l2 u2. approx prec\n                 (Add (Var 0)\n                      (Mult (Inverse (Num (Float (int k) 0)))\n                                 (Mult (Add (Var (Suc (Suc 0))) (Minus (Num c)))\n                                       (Var (Suc 0))))) [Some (l1, u1), Some (l2, u2), bs!n])\n  else approx prec f bs)\"\n\nlemma bounded_by_Cons:\n  assumes bnd: \"bounded_by xs vs\"\n    and x: \"x \\<in> { real_of_float l .. real_of_float u }\"\n  shows \"bounded_by (x#xs) ((Some (l, u))#vs)\"\nproof -\n  have \"case ((Some (l,u))#vs) ! i of Some (l, u) \\<Rightarrow> (x#xs)!i \\<in> { real_of_float l .. real_of_float u } | None \\<Rightarrow> True\"\n    if *: \"i < length ((Some (l, u))#vs)\" for i\n  proof (cases i)\n    case 0\n    with x show ?thesis by auto\n  next\n    case (Suc i)\n    with * have \"i < length vs\" by auto\n    from bnd[THEN bounded_byE, OF this]\n    show ?thesis unfolding Suc nth_Cons_Suc .\n  qed\n  thus ?thesis\n    by (auto simp add: bounded_by_def)\nqed\n\nlemma approx_tse_generic:\n  assumes \"bounded_by xs vs\"\n    and bnd_c: \"bounded_by (xs[x := c]) vs\"\n    and \"x < length vs\" and \"x < length xs\"\n    and bnd_x: \"vs ! x = Some (lx, ux)\"\n    and ate: \"Some (l, u) = approx_tse prec x s c k f vs\"\n  shows \"\\<exists> n. (\\<forall> m < n. \\<forall> (z::real) \\<in> {lx .. ux}.\n      DERIV (\\<lambda> y. interpret_floatarith ((DERIV_floatarith x ^^ m) f) (xs[x := y])) z :>\n            (interpret_floatarith ((DERIV_floatarith x ^^ (Suc m)) f) (xs[x := z])))\n   \\<and> (\\<forall> (t::real) \\<in> {lx .. ux}.  (\\<Sum> i = 0..<n. inverse (real (\\<Prod> j \\<in> {k..<k+i}. j)) *\n                  interpret_floatarith ((DERIV_floatarith x ^^ i) f) (xs[x := c]) *\n                  (xs!x - c)^i) +\n      inverse (real (\\<Prod> j \\<in> {k..<k+n}. j)) *\n      interpret_floatarith ((DERIV_floatarith x ^^ n) f) (xs[x := t]) *\n      (xs!x - c)^n \\<in> {l .. u})\" (is \"\\<exists> n. ?taylor f k l u n\")\n  using ate\nproof (induct s arbitrary: k f l u)\n  case 0\n  {\n    fix t::real assume \"t \\<in> {lx .. ux}\"\n    note bounded_by_update_var[OF \\<open>bounded_by xs vs\\<close> bnd_x this]\n    from approx[OF this 0[unfolded approx_tse.simps]]\n    have \"(interpret_floatarith f (xs[x := t])) \\<in> {l .. u}\"\n      by (auto simp add: algebra_simps)\n  }\n  thus ?case by (auto intro!: exI[of _ 0])\nnext\n  case (Suc s)\n  show ?case\n  proof (cases \"isDERIV_approx prec x f vs\")\n    case False\n    note ap = Suc.prems[unfolded approx_tse.simps if_not_P[OF False]]\n    {\n      fix t::real assume \"t \\<in> {lx .. ux}\"\n      note bounded_by_update_var[OF \\<open>bounded_by xs vs\\<close> bnd_x this]\n      from approx[OF this ap]\n      have \"(interpret_floatarith f (xs[x := t])) \\<in> {l .. u}\"\n        by (auto simp add: algebra_simps)\n    }\n    thus ?thesis by (auto intro!: exI[of _ 0])\n  next\n    case True\n    with Suc.prems\n    obtain l1 u1 l2 u2\n      where a: \"Some (l1, u1) = approx prec f (vs[x := Some (c,c)])\"\n        and ate: \"Some (l2, u2) = approx_tse prec x s c (Suc k) (DERIV_floatarith x f) vs\"\n        and final: \"Some (l, u) = approx prec\n          (Add (Var 0)\n               (Mult (Inverse (Num (Float (int k) 0)))\n                     (Mult (Add (Var (Suc (Suc 0))) (Minus (Num c)))\n                           (Var (Suc 0))))) [Some (l1, u1), Some (l2, u2), vs!x]\"\n      by (auto elim!: lift_bin_aux)\n\n    from bnd_c \\<open>x < length xs\\<close>\n    have bnd: \"bounded_by (xs[x:=c]) (vs[x:= Some (c,c)])\"\n      by (auto intro!: bounded_by_update)\n\n    from approx[OF this a]\n    have f_c: \"interpret_floatarith ((DERIV_floatarith x ^^ 0) f) (xs[x := c]) \\<in> { l1 .. u1 }\"\n              (is \"?f 0 (real_of_float c) \\<in> _\")\n      by auto\n\n    have funpow_Suc[symmetric]: \"(f ^^ Suc n) x = (f ^^ n) (f x)\"\n      for f :: \"'a \\<Rightarrow> 'a\" and n :: nat and x :: 'a\n      by (induct n) auto\n    from Suc.hyps[OF ate, unfolded this] obtain n\n      where DERIV_hyp: \"\\<And>m z. \\<lbrakk> m < n ; (z::real) \\<in> { lx .. ux } \\<rbrakk> \\<Longrightarrow>\n        DERIV (?f (Suc m)) z :> ?f (Suc (Suc m)) z\"\n      and hyp: \"\\<forall>t \\<in> {real_of_float lx .. real_of_float ux}.\n        (\\<Sum> i = 0..<n. inverse (real (\\<Prod> j \\<in> {Suc k..<Suc k + i}. j)) * ?f (Suc i) c * (xs!x - c)^i) +\n          inverse (real (\\<Prod> j \\<in> {Suc k..<Suc k + n}. j)) * ?f (Suc n) t * (xs!x - c)^n \\<in> {l2 .. u2}\"\n          (is \"\\<forall> t \\<in> _. ?X (Suc k) f n t \\<in> _\")\n      by blast\n\n    have DERIV: \"DERIV (?f m) z :> ?f (Suc m) z\"\n      if \"m < Suc n\" and bnd_z: \"z \\<in> { lx .. ux }\" for m and z::real\n    proof (cases m)\n      case 0\n      with DERIV_floatarith[OF \\<open>x < length xs\\<close>\n        isDERIV_approx'[OF \\<open>bounded_by xs vs\\<close> bnd_x bnd_z True]]\n      show ?thesis by simp\n    next\n      case (Suc m')\n      hence \"m' < n\"\n        using \\<open>m < Suc n\\<close> by auto\n      from DERIV_hyp[OF this bnd_z] show ?thesis\n        using Suc by simp\n    qed\n\n    have \"\\<And>k i. k < i \\<Longrightarrow> {k ..< i} = insert k {Suc k ..< i}\" by auto\n    hence prod_head_Suc: \"\\<And>k i. \\<Prod>{k ..< k + Suc i} = k * \\<Prod>{Suc k ..< Suc k + i}\"\n      by auto\n    have sum_move0: \"\\<And>k F. sum F {0..<Suc k} = F 0 + sum (\\<lambda> k. F (Suc k)) {0..<k}\"\n      unfolding sum_shift_bounds_Suc_ivl[symmetric]\n      unfolding sum_head_upt_Suc[OF zero_less_Suc] ..\n    define C where \"C = xs!x - c\"\n\n    {\n      fix t::real assume t: \"t \\<in> {lx .. ux}\"\n      hence \"bounded_by [xs!x] [vs!x]\"\n        using \\<open>bounded_by xs vs\\<close>[THEN bounded_byE, OF \\<open>x < length vs\\<close>]\n        by (cases \"vs!x\", auto simp add: bounded_by_def)\n\n      with hyp[THEN bspec, OF t] f_c\n      have \"bounded_by [?f 0 c, ?X (Suc k) f n t, xs!x] [Some (l1, u1), Some (l2, u2), vs!x]\"\n        by (auto intro!: bounded_by_Cons)\n      from approx[OF this final, unfolded atLeastAtMost_iff[symmetric]]\n      have \"?X (Suc k) f n t * (xs!x - real_of_float c) * inverse k + ?f 0 c \\<in> {l .. u}\"\n        by (auto simp add: algebra_simps)\n      also have \"?X (Suc k) f n t * (xs!x - real_of_float c) * inverse (real k) + ?f 0 c =\n               (\\<Sum> i = 0..<Suc n. inverse (real (\\<Prod> j \\<in> {k..<k+i}. j)) * ?f i c * (xs!x - c)^i) +\n               inverse (real (\\<Prod> j \\<in> {k..<k+Suc n}. j)) * ?f (Suc n) t * (xs!x - c)^Suc n\" (is \"_ = ?T\")\n        unfolding funpow_Suc C_def[symmetric] sum_move0 prod_head_Suc\n        by (auto simp add: algebra_simps)\n          (simp only: mult.left_commute [of _ \"inverse (real k)\"] sum_distrib_left [symmetric])\n      finally have \"?T \\<in> {l .. u}\" .\n    }\n    thus ?thesis using DERIV by blast\n  qed\nqed\n\nlemma prod_fact: \"real (\\<Prod> {1..<1 + k}) = fact (k :: nat)\"\n  by (simp add: fact_prod atLeastLessThanSuc_atLeastAtMost)\n\nlemma approx_tse:\n  assumes \"bounded_by xs vs\"\n    and bnd_x: \"vs ! x = Some (lx, ux)\"\n    and bnd_c: \"real_of_float c \\<in> {lx .. ux}\"\n    and \"x < length vs\" and \"x < length xs\"\n    and ate: \"Some (l, u) = approx_tse prec x s c 1 f vs\"\n  shows \"interpret_floatarith f xs \\<in> {l .. u}\"\nproof -\n  define F where [abs_def]: \"F n z =\n    interpret_floatarith ((DERIV_floatarith x ^^ n) f) (xs[x := z])\" for n z\n  hence F0: \"F 0 = (\\<lambda> z. interpret_floatarith f (xs[x := z]))\" by auto\n\n  hence \"bounded_by (xs[x := c]) vs\" and \"x < length vs\" \"x < length xs\"\n    using \\<open>bounded_by xs vs\\<close> bnd_x bnd_c \\<open>x < length vs\\<close> \\<open>x < length xs\\<close>\n    by (auto intro!: bounded_by_update_var)\n\n  from approx_tse_generic[OF \\<open>bounded_by xs vs\\<close> this bnd_x ate]\n  obtain n\n    where DERIV: \"\\<forall> m z. m < n \\<and> real_of_float lx \\<le> z \\<and> z \\<le> real_of_float ux \\<longrightarrow> DERIV (F m) z :> F (Suc m) z\"\n    and hyp: \"\\<And> (t::real). t \\<in> {lx .. ux} \\<Longrightarrow>\n           (\\<Sum> j = 0..<n. inverse(fact j) * F j c * (xs!x - c)^j) +\n             inverse ((fact n)) * F n t * (xs!x - c)^n\n             \\<in> {l .. u}\" (is \"\\<And> t. _ \\<Longrightarrow> ?taylor t \\<in> _\")\n    unfolding F_def atLeastAtMost_iff[symmetric] prod_fact\n    by blast\n\n  have bnd_xs: \"xs ! x \\<in> { lx .. ux }\"\n    using \\<open>bounded_by xs vs\\<close>[THEN bounded_byE, OF \\<open>x < length vs\\<close>] bnd_x by auto\n\n  show ?thesis\n  proof (cases n)\n    case 0\n    thus ?thesis\n      using hyp[OF bnd_xs] unfolding F_def by auto\n  next\n    case (Suc n')\n    show ?thesis\n    proof (cases \"xs ! x = c\")\n      case True\n      from True[symmetric] hyp[OF bnd_xs] Suc show ?thesis\n        unfolding F_def Suc sum_head_upt_Suc[OF zero_less_Suc] sum_shift_bounds_Suc_ivl\n        by auto\n    next\n      case False\n      have \"lx \\<le> real_of_float c\" \"real_of_float c \\<le> ux\" \"lx \\<le> xs!x\" \"xs!x \\<le> ux\"\n        using Suc bnd_c \\<open>bounded_by xs vs\\<close>[THEN bounded_byE, OF \\<open>x < length vs\\<close>] bnd_x by auto\n      from taylor[OF zero_less_Suc, of F, OF F0 DERIV[unfolded Suc] this False]\n      obtain t::real where t_bnd: \"if xs ! x < c then xs ! x < t \\<and> t < c else c < t \\<and> t < xs ! x\"\n        and fl_eq: \"interpret_floatarith f (xs[x := xs ! x]) =\n           (\\<Sum>m = 0..<Suc n'. F m c / (fact m) * (xs ! x - c) ^ m) +\n           F (Suc n') t / (fact (Suc n')) * (xs ! x - c) ^ Suc n'\"\n        unfolding atLeast0LessThan by blast\n\n      from t_bnd bnd_xs bnd_c have *: \"t \\<in> {lx .. ux}\"\n        by (cases \"xs ! x < c\") auto\n\n      have \"interpret_floatarith f (xs[x := xs ! x]) = ?taylor t\"\n        unfolding fl_eq Suc by (auto simp add: algebra_simps divide_inverse)\n      also have \"\\<dots> \\<in> {l .. u}\"\n        using * by (rule hyp)\n      finally show ?thesis\n        by simp\n    qed\n  qed\nqed\n\nfun approx_tse_form' where\n\"approx_tse_form' prec t f 0 l u cmp =\n  (case approx_tse prec 0 t ((l + u) * Float 1 (- 1)) 1 f [Some (l, u)]\n     of Some (l, u) \\<Rightarrow> cmp l u | None \\<Rightarrow> False)\" |\n\"approx_tse_form' prec t f (Suc s) l u cmp =\n  (let m = (l + u) * Float 1 (- 1)\n   in (if approx_tse_form' prec t f s l m cmp then\n      approx_tse_form' prec t f s m u cmp else False))\"\n\nlemma approx_tse_form':\n  fixes x :: real\n  assumes \"approx_tse_form' prec t f s l u cmp\"\n    and \"x \\<in> {l .. u}\"\n  shows \"\\<exists>l' u' ly uy. x \\<in> {l' .. u'} \\<and> real_of_float l \\<le> l' \\<and> u' \\<le> real_of_float u \\<and> cmp ly uy \\<and>\n    approx_tse prec 0 t ((l' + u') * Float 1 (- 1)) 1 f [Some (l', u')] = Some (ly, uy)\"\n  using assms\nproof (induct s arbitrary: l u)\n  case 0\n  then obtain ly uy\n    where *: \"approx_tse prec 0 t ((l + u) * Float 1 (- 1)) 1 f [Some (l, u)] = Some (ly, uy)\"\n    and **: \"cmp ly uy\" by (auto elim!: case_optionE)\n  with 0 show ?case by auto\nnext\n  case (Suc s)\n  let ?m = \"(l + u) * Float 1 (- 1)\"\n  from Suc.prems\n  have l: \"approx_tse_form' prec t f s l ?m cmp\"\n    and u: \"approx_tse_form' prec t f s ?m u cmp\"\n    by (auto simp add: Let_def lazy_conj)\n\n  have m_l: \"real_of_float l \\<le> ?m\" and m_u: \"?m \\<le> real_of_float u\"\n    unfolding less_eq_float_def using Suc.prems by auto\n  with \\<open>x \\<in> { l .. u }\\<close> consider \"x \\<in> { l .. ?m}\" | \"x \\<in> {?m .. u}\"\n    by atomize_elim auto\n  thus ?case\n  proof cases\n    case 1\n    from Suc.hyps[OF l this]\n    obtain l' u' ly uy where\n      \"x \\<in> {l' .. u'} \\<and> real_of_float l \\<le> l' \\<and> real_of_float u' \\<le> ?m \\<and> cmp ly uy \\<and>\n        approx_tse prec 0 t ((l' + u') * Float 1 (- 1)) 1 f [Some (l', u')] = Some (ly, uy)\"\n      by blast\n    with m_u show ?thesis\n      by (auto intro!: exI)\n  next\n    case 2\n    from Suc.hyps[OF u this]\n    obtain l' u' ly uy where\n      \"x \\<in> { l' .. u' } \\<and> ?m \\<le> real_of_float l' \\<and> u' \\<le> real_of_float u \\<and> cmp ly uy \\<and>\n        approx_tse prec 0 t ((l' + u') * Float 1 (- 1)) 1 f [Some (l', u')] = Some (ly, uy)\"\n      by blast\n    with m_u show ?thesis\n      by (auto intro!: exI)\n  qed\nqed\n\nlemma approx_tse_form'_less:\n  fixes x :: real\n  assumes tse: \"approx_tse_form' prec t (Add a (Minus b)) s l u (\\<lambda> l u. 0 < l)\"\n    and x: \"x \\<in> {l .. u}\"\n  shows \"interpret_floatarith b [x] < interpret_floatarith a [x]\"\nproof -\n  from approx_tse_form'[OF tse x]\n  obtain l' u' ly uy\n    where x': \"x \\<in> {l' .. u'}\"\n    and \"real_of_float l \\<le> real_of_float l'\"\n    and \"real_of_float u' \\<le> real_of_float u\" and \"0 < ly\"\n    and tse: \"approx_tse prec 0 t ((l' + u') * Float 1 (- 1)) 1 (Add a (Minus b)) [Some (l', u')] = Some (ly, uy)\"\n    by blast\n\n  hence \"bounded_by [x] [Some (l', u')]\"\n    by (auto simp add: bounded_by_def)\n  from approx_tse[OF this _ _ _ _ tse[symmetric], of l' u'] x'\n  have \"ly \\<le> interpret_floatarith a [x] - interpret_floatarith b [x]\"\n    by auto\n  from order_less_le_trans[OF _ this, of 0] \\<open>0 < ly\\<close> show ?thesis\n    by auto\nqed\n\nlemma approx_tse_form'_le:\n  fixes x :: real\n  assumes tse: \"approx_tse_form' prec t (Add a (Minus b)) s l u (\\<lambda> l u. 0 \\<le> l)\"\n    and x: \"x \\<in> {l .. u}\"\n  shows \"interpret_floatarith b [x] \\<le> interpret_floatarith a [x]\"\nproof -\n  from approx_tse_form'[OF tse x]\n  obtain l' u' ly uy\n    where x': \"x \\<in> {l' .. u'}\"\n    and \"l \\<le> real_of_float l'\"\n    and \"real_of_float u' \\<le> u\" and \"0 \\<le> ly\"\n    and tse: \"approx_tse prec 0 t ((l' + u') * Float 1 (- 1)) 1 (Add a (Minus b)) [Some (l', u')] = Some (ly, uy)\"\n    by blast\n\n  hence \"bounded_by [x] [Some (l', u')]\" by (auto simp add: bounded_by_def)\n  from approx_tse[OF this _ _ _ _ tse[symmetric], of l' u'] x'\n  have \"ly \\<le> interpret_floatarith a [x] - interpret_floatarith b [x]\"\n    by auto\n  from order_trans[OF _ this, of 0] \\<open>0 \\<le> ly\\<close> show ?thesis\n    by auto\nqed\n\nfun approx_tse_concl where\n\"approx_tse_concl prec t (Less lf rt) s l u l' u' \\<longleftrightarrow>\n    approx_tse_form' prec t (Add rt (Minus lf)) s l u' (\\<lambda> l u. 0 < l)\" |\n\"approx_tse_concl prec t (LessEqual lf rt) s l u l' u' \\<longleftrightarrow>\n    approx_tse_form' prec t (Add rt (Minus lf)) s l u' (\\<lambda> l u. 0 \\<le> l)\" |\n\"approx_tse_concl prec t (AtLeastAtMost x lf rt) s l u l' u' \\<longleftrightarrow>\n    (if approx_tse_form' prec t (Add x (Minus lf)) s l u' (\\<lambda> l u. 0 \\<le> l) then\n      approx_tse_form' prec t (Add rt (Minus x)) s l u' (\\<lambda> l u. 0 \\<le> l) else False)\" |\n\"approx_tse_concl prec t (Conj f g) s l u l' u' \\<longleftrightarrow>\n    approx_tse_concl prec t f s l u l' u' \\<and> approx_tse_concl prec t g s l u l' u'\" |\n\"approx_tse_concl prec t (Disj f g) s l u l' u' \\<longleftrightarrow>\n    approx_tse_concl prec t f s l u l' u' \\<or> approx_tse_concl prec t g s l u l' u'\" |\n\"approx_tse_concl _ _ _ _ _ _ _ _ \\<longleftrightarrow> False\"\n\ndefinition\n  \"approx_tse_form prec t s f =\n    (case f of\n      Bound x a b f \\<Rightarrow>\n        x = Var 0 \\<and>\n        (case (approx prec a [None], approx prec b [None]) of\n          (Some (l, u), Some (l', u')) \\<Rightarrow> approx_tse_concl prec t f s l u l' u'\n        | _ \\<Rightarrow> False)\n    | _ \\<Rightarrow> False)\"\n\nlemma approx_tse_form:\n  assumes \"approx_tse_form prec t s f\"\n  shows \"interpret_form f [x]\"\nproof (cases f)\n  case f_def: (Bound i a b f')\n  with assms obtain l u l' u'\n    where a: \"approx prec a [None] = Some (l, u)\"\n    and b: \"approx prec b [None] = Some (l', u')\"\n    unfolding approx_tse_form_def by (auto elim!: case_optionE)\n\n  from f_def assms have \"i = Var 0\"\n    unfolding approx_tse_form_def by auto\n  hence i: \"interpret_floatarith i [x] = x\" by auto\n\n  {\n    let ?f = \"\\<lambda>z. interpret_floatarith z [x]\"\n    assume \"?f i \\<in> { ?f a .. ?f b }\"\n    with approx[OF _ a[symmetric], of \"[x]\"] approx[OF _ b[symmetric], of \"[x]\"]\n    have bnd: \"x \\<in> { l .. u'}\" unfolding bounded_by_def i by auto\n\n    have \"interpret_form f' [x]\"\n      using assms[unfolded f_def]\n    proof (induct f')\n      case (Less lf rt)\n      with a b\n      have \"approx_tse_form' prec t (Add rt (Minus lf)) s l u' (\\<lambda> l u. 0 < l)\"\n        unfolding approx_tse_form_def by auto\n      from approx_tse_form'_less[OF this bnd]\n      show ?case using Less by auto\n    next\n      case (LessEqual lf rt)\n      with f_def a b assms\n      have \"approx_tse_form' prec t (Add rt (Minus lf)) s l u' (\\<lambda> l u. 0 \\<le> l)\"\n        unfolding approx_tse_form_def by auto\n      from approx_tse_form'_le[OF this bnd]\n      show ?case using LessEqual by auto\n    next\n      case (AtLeastAtMost x lf rt)\n      with f_def a b assms\n      have \"approx_tse_form' prec t (Add rt (Minus x)) s l u' (\\<lambda> l u. 0 \\<le> l)\"\n        and \"approx_tse_form' prec t (Add x (Minus lf)) s l u' (\\<lambda> l u. 0 \\<le> l)\"\n        unfolding approx_tse_form_def lazy_conj by (auto split: if_split_asm)\n      from approx_tse_form'_le[OF this(1) bnd] approx_tse_form'_le[OF this(2) bnd]\n      show ?case using AtLeastAtMost by auto\n    qed (auto simp: f_def approx_tse_form_def elim!: case_optionE)\n  }\n  thus ?thesis unfolding f_def by auto\nqed (insert assms, auto simp add: approx_tse_form_def)\n\ntext \\<open>@{term approx_form_eval} is only used for the {\\tt value}-command.\\<close>\n\nfun approx_form_eval :: \"nat \\<Rightarrow> form \\<Rightarrow> (float * float) option list \\<Rightarrow> (float * float) option list\" where\n\"approx_form_eval prec (Bound (Var n) a b f) bs =\n   (case (approx prec a bs, approx prec b bs)\n   of (Some (l, _), Some (_, u)) \\<Rightarrow> approx_form_eval prec f (bs[n := Some (l, u)])\n    | _ \\<Rightarrow> bs)\" |\n\"approx_form_eval prec (Assign (Var n) a f) bs =\n   (case (approx prec a bs)\n   of (Some (l, u)) \\<Rightarrow> approx_form_eval prec f (bs[n := Some (l, u)])\n    | _ \\<Rightarrow> bs)\" |\n\"approx_form_eval prec (Less a b) bs = bs @ [approx prec a bs, approx prec b bs]\" |\n\"approx_form_eval prec (LessEqual a b) bs = bs @ [approx prec a bs, approx prec b bs]\" |\n\"approx_form_eval prec (AtLeastAtMost x a b) bs =\n   bs @ [approx prec x bs, approx prec a bs, approx prec b bs]\" |\n\"approx_form_eval _ _ bs = bs\"\n\n\nsubsection \\<open>Implement proof method \\texttt{approximation}\\<close>\n\noracle approximation_oracle = \\<open>fn (thy, t) =>\nlet\n  fun bad t = error (\"Bad term: \" ^ Syntax.string_of_term_global thy t);\n\n  fun term_of_bool true = @{term True}\n    | term_of_bool false = @{term False};\n\n  val mk_int = HOLogic.mk_number @{typ int} o @{code integer_of_int};\n  fun dest_int (@{term int_of_integer} $ j) = @{code int_of_integer} (snd (HOLogic.dest_number j))\n    | dest_int i = @{code int_of_integer} (snd (HOLogic.dest_number i));\n\n  fun term_of_float (@{code Float} (k, l)) =\n    @{term Float} $ mk_int k $ mk_int l;\n\n  fun term_of_float_float_option NONE = @{term \"None :: (float \\<times> float) option\"}\n    | term_of_float_float_option (SOME ff) = @{term \"Some :: float \\<times> float \\<Rightarrow> _\"}\n        $ HOLogic.mk_prod (apply2 term_of_float ff);\n\n  val term_of_float_float_option_list =\n    HOLogic.mk_list @{typ \"(float \\<times> float) option\"} o map term_of_float_float_option;\n\n  fun nat_of_term t = @{code nat_of_integer}\n    (HOLogic.dest_nat t handle TERM _ => snd (HOLogic.dest_number t));\n\n  fun float_of_term (@{term Float} $ k $ l) =\n        @{code Float} (dest_int k, dest_int l)\n    | float_of_term t = bad t;\n\n  fun floatarith_of_term (@{term Add} $ a $ b) = @{code Add} (floatarith_of_term a, floatarith_of_term b)\n    | floatarith_of_term (@{term Minus} $ a) = @{code Minus} (floatarith_of_term a)\n    | floatarith_of_term (@{term Mult} $ a $ b) = @{code Mult} (floatarith_of_term a, floatarith_of_term b)\n    | floatarith_of_term (@{term Inverse} $ a) = @{code Inverse} (floatarith_of_term a)\n    | floatarith_of_term (@{term Cos} $ a) = @{code Cos} (floatarith_of_term a)\n    | floatarith_of_term (@{term Arctan} $ a) = @{code Arctan} (floatarith_of_term a)\n    | floatarith_of_term (@{term Abs} $ a) = @{code Abs} (floatarith_of_term a)\n    | floatarith_of_term (@{term Max} $ a $ b) = @{code Max} (floatarith_of_term a, floatarith_of_term b)\n    | floatarith_of_term (@{term Min} $ a $ b) = @{code Min} (floatarith_of_term a, floatarith_of_term b)\n    | floatarith_of_term @{term Pi} = @{code Pi}\n    | floatarith_of_term (@{term Sqrt} $ a) = @{code Sqrt} (floatarith_of_term a)\n    | floatarith_of_term (@{term Exp} $ a) = @{code Exp} (floatarith_of_term a)\n    | floatarith_of_term (@{term Powr} $ a $ b) = @{code Powr} (floatarith_of_term a, floatarith_of_term b)\n    | floatarith_of_term (@{term Ln} $ a) = @{code Ln} (floatarith_of_term a)\n    | floatarith_of_term (@{term Power} $ a $ n) =\n        @{code Power} (floatarith_of_term a, nat_of_term n)\n    | floatarith_of_term (@{term Floor} $ a) = @{code Floor} (floatarith_of_term a)\n    | floatarith_of_term (@{term Var} $ n) = @{code Var} (nat_of_term n)\n    | floatarith_of_term (@{term Num} $ m) = @{code Num} (float_of_term m)\n    | floatarith_of_term t = bad t;\n\n  fun form_of_term (@{term Bound} $ a $ b $ c $ p) = @{code Bound}\n        (floatarith_of_term a, floatarith_of_term b, floatarith_of_term c, form_of_term p)\n    | form_of_term (@{term Assign} $ a $ b $ p) = @{code Assign}\n        (floatarith_of_term a, floatarith_of_term b, form_of_term p)\n    | form_of_term (@{term Less} $ a $ b) = @{code Less}\n        (floatarith_of_term a, floatarith_of_term b)\n    | form_of_term (@{term LessEqual} $ a $ b) = @{code LessEqual}\n        (floatarith_of_term a, floatarith_of_term b)\n    | form_of_term (@{term Conj} $ a $ b) = @{code Conj}\n        (form_of_term a, form_of_term b)\n    | form_of_term (@{term Disj} $ a $ b) = @{code Disj}\n        (form_of_term a, form_of_term b)\n    | form_of_term (@{term AtLeastAtMost} $ a $ b $ c) = @{code AtLeastAtMost}\n        (floatarith_of_term a, floatarith_of_term b, floatarith_of_term c)\n    | form_of_term t = bad t;\n\n  fun float_float_option_of_term @{term \"None :: (float \\<times> float) option\"} = NONE\n    | float_float_option_of_term (@{term \"Some :: float \\<times> float \\<Rightarrow> _\"} $ ff) =\n        SOME (apply2 float_of_term (HOLogic.dest_prod ff))\n    | float_float_option_of_term (@{term approx'} $ n $ a $ ffs) = @{code approx'}\n        (nat_of_term n) (floatarith_of_term a) (float_float_option_list_of_term ffs)\n    | float_float_option_of_term t = bad t\n  and float_float_option_list_of_term\n        (@{term \"replicate :: _ \\<Rightarrow> (float \\<times> float) option \\<Rightarrow> _\"} $ n $ @{term \"None :: (float \\<times> float) option\"}) =\n          @{code replicate} (nat_of_term n) NONE\n    | float_float_option_list_of_term (@{term approx_form_eval} $ n $ p $ ffs) =\n        @{code approx_form_eval} (nat_of_term n) (form_of_term p) (float_float_option_list_of_term ffs)\n    | float_float_option_list_of_term t = map float_float_option_of_term\n        (HOLogic.dest_list t);\n\n  val nat_list_of_term = map nat_of_term o HOLogic.dest_list ;\n\n  fun bool_of_term (@{term approx_form} $ n $ p $ ffs $ ms) = @{code approx_form}\n        (nat_of_term n) (form_of_term p) (float_float_option_list_of_term ffs) (nat_list_of_term ms)\n    | bool_of_term (@{term approx_tse_form} $ m $ n $ q $ p) =\n        @{code approx_tse_form} (nat_of_term m) (nat_of_term n) (nat_of_term q) (form_of_term p)\n    | bool_of_term t = bad t;\n\n  fun eval t = case fastype_of t\n   of @{typ bool} =>\n        (term_of_bool o bool_of_term) t\n    | @{typ \"(float \\<times> float) option\"} =>\n        (term_of_float_float_option o float_float_option_of_term) t\n    | @{typ \"(float \\<times> float) option list\"} =>\n        (term_of_float_float_option_list o float_float_option_list_of_term) t\n    | _ => bad t;\n\n  val normalize = eval o Envir.beta_norm o Envir.eta_long [];\n\nin Thm.global_cterm_of thy (Logic.mk_equals (t, normalize t)) end\n\\<close>\n\nlemma intervalE: \"a \\<le> x \\<and> x \\<le> b \\<Longrightarrow> \\<lbrakk> x \\<in> { a .. b } \\<Longrightarrow> P\\<rbrakk> \\<Longrightarrow> P\"\n  by auto\n\nlemma meta_eqE: \"x \\<equiv> a \\<Longrightarrow> \\<lbrakk> x = a \\<Longrightarrow> P\\<rbrakk> \\<Longrightarrow> P\"\n  by auto\n\nnamed_theorems approximation_preproc\n\nlemma approximation_preproc_floatarith[approximation_preproc]:\n  \"0 = real_of_float 0\"\n  \"1 = real_of_float 1\"\n  \"0 = Float 0 0\"\n  \"1 = Float 1 0\"\n  \"numeral a = Float (numeral a) 0\"\n  \"numeral a = real_of_float (numeral a)\"\n  \"x - y = x + - y\"\n  \"x / y = x * inverse y\"\n  \"ceiling x = - floor (- x)\"\n  \"log x y = ln y * inverse (ln x)\"\n  \"sin x = cos (pi / 2 - x)\"\n  \"tan x = sin x / cos x\"\n  by (simp_all add: inverse_eq_divide ceiling_def log_def sin_cos_eq tan_def real_of_float_eq)\n\nlemma approximation_preproc_int[approximation_preproc]:\n  \"real_of_int 0 = real_of_float 0\"\n  \"real_of_int 1 = real_of_float 1\"\n  \"real_of_int (i + j) = real_of_int i + real_of_int j\"\n  \"real_of_int (- i) = - real_of_int i\"\n  \"real_of_int (i - j) = real_of_int i - real_of_int j\"\n  \"real_of_int (i * j) = real_of_int i * real_of_int j\"\n  \"real_of_int (i div j) = real_of_int (floor (real_of_int i / real_of_int j))\"\n  \"real_of_int (min i j) = min (real_of_int i) (real_of_int j)\"\n  \"real_of_int (max i j) = max (real_of_int i) (real_of_int j)\"\n  \"real_of_int (abs i) = abs (real_of_int i)\"\n  \"real_of_int (i ^ n) = (real_of_int i) ^ n\"\n  \"real_of_int (numeral a) = real_of_float (numeral a)\"\n  \"i mod j = i - i div j * j\"\n  \"i = j \\<longleftrightarrow> real_of_int i = real_of_int j\"\n  \"i \\<le> j \\<longleftrightarrow> real_of_int i \\<le> real_of_int j\"\n  \"i < j \\<longleftrightarrow> real_of_int i < real_of_int j\"\n  \"i \\<in> {j .. k} \\<longleftrightarrow> real_of_int i \\<in> {real_of_int j .. real_of_int k}\"\n  by (simp_all add: floor_divide_of_int_eq minus_div_mult_eq_mod [symmetric])\n\nlemma approximation_preproc_nat[approximation_preproc]:\n  \"real 0 = real_of_float 0\"\n  \"real 1 = real_of_float 1\"\n  \"real (i + j) = real i + real j\"\n  \"real (i - j) = max (real i - real j) 0\"\n  \"real (i * j) = real i * real j\"\n  \"real (i div j) = real_of_int (floor (real i / real j))\"\n  \"real (min i j) = min (real i) (real j)\"\n  \"real (max i j) = max (real i) (real j)\"\n  \"real (i ^ n) = (real i) ^ n\"\n  \"real (numeral a) = real_of_float (numeral a)\"\n  \"i mod j = i - i div j * j\"\n  \"n = m \\<longleftrightarrow> real n = real m\"\n  \"n \\<le> m \\<longleftrightarrow> real n \\<le> real m\"\n  \"n < m \\<longleftrightarrow> real n < real m\"\n  \"n \\<in> {m .. l} \\<longleftrightarrow> real n \\<in> {real m .. real l}\"\n  by (simp_all add: real_div_nat_eq_floor_of_divide minus_div_mult_eq_mod [symmetric])\n\nML_file \"approximation.ML\"\n\nmethod_setup approximation = \\<open>\n  let\n    val free =\n      Args.context -- Args.term >> (fn (_, Free (n, _)) => n | (ctxt, t) =>\n        error (\"Bad free variable: \" ^ Syntax.string_of_term ctxt t));\n  in\n    Scan.lift Parse.nat --\n    Scan.optional (Scan.lift (Args.$$$ \"splitting\" |-- Args.colon)\n      |-- Parse.and_list' (free --| Scan.lift (Args.$$$ \"=\") -- Scan.lift Parse.nat)) [] --\n    Scan.option (Scan.lift (Args.$$$ \"taylor\" |-- Args.colon) |--\n    (free |-- Scan.lift (Args.$$$ \"=\") |-- Scan.lift Parse.nat)) >>\n    (fn ((prec, splitting), taylor) => fn ctxt =>\n      SIMPLE_METHOD' (Approximation.approximation_tac prec splitting taylor ctxt))\n  end\n\\<close> \"real number approximation\"\n\n\nsection \"Quickcheck Generator\"\n\nlemma approximation_preproc_push_neg[approximation_preproc]:\n  fixes a b::real\n  shows\n    \"\\<not> (a < b) \\<longleftrightarrow> b \\<le> a\"\n    \"\\<not> (a \\<le> b) \\<longleftrightarrow> b < a\"\n    \"\\<not> (a = b) \\<longleftrightarrow> b < a \\<or> a < b\"\n    \"\\<not> (p \\<and> q) \\<longleftrightarrow> \\<not> p \\<or> \\<not> q\"\n    \"\\<not> (p \\<or> q) \\<longleftrightarrow> \\<not> p \\<and> \\<not> q\"\n    \"\\<not> \\<not> q \\<longleftrightarrow> q\"\n  by auto\n\nML_file \"approximation_generator.ML\"\nsetup \"Approximation_Generator.setup\"\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/Approximation.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8670357460591569, "lm_q2_score": 0.8080672089305841, "lm_q1q2_score": 0.7006231553610697}}
{"text": "(*\n  File:       Prime Number Theorem.thy\n  Authors:    Manuel Eberl (TU M\u00fcnchen), Larry Paulson (University of Cambridge)\n\n  A proof of the Prime Number Theorem and some related properties\n*)\nsection \\<open>The Prime Number Theorem\\<close>\ntheory Prime_Number_Theorem\nimports \n  Newman_Ingham_Tauberian\n  Prime_Counting_Functions\nbegin\n\n(*<*)\nunbundle prime_counting_notation\n(*>*)\n\nsubsection \\<open>Constructing Newman's function\\<close>\n\ntext \\<open>\n  Starting from Mertens' first theorem, i.\\,e.\\ $\\mathfrak M(x) = \\ln x + O(1)$, we now \n  want to derive that $\\mathfrak M(x) = \\ln x + c + o(1)$. This result is considerably stronger\n  and it implies the Prime Number Theorem quite directly.\n\n  In order to do this, we define the Dirichlet series\n  \\[f(s) = \\sum_{n=1}^\\infty \\frac{\\mathfrak{M}(n)}{n^s}\\ .\\]\n  We will prove that this series extends meromorphically to $\\mathfrak{R}(s)\\geq 1$ and\n  apply Ingham's theorem to it (after we subtracted its pole at $s = 1$).\n\\<close>\ndefinition fds_newman where\n  \"fds_newman = fds (\\<lambda>n. complex_of_real (\\<MM> n))\"\n\nlemma fds_nth_newman:\n  \"fds_nth fds_newman n = of_real (\\<MM> n)\"\n  by (simp add: fds_newman_def fds_nth_fds)\n\nlemma norm_fds_nth_newman:\n  \"norm (fds_nth fds_newman n) = \\<MM> n\"\n  unfolding fds_nth_newman norm_of_real\n  by (intro abs_of_nonneg sum_nonneg divide_nonneg_pos) (auto dest: prime_ge_1_nat)\n\ntext \\<open>\n  The Dirichlet series $f(s) + \\zeta'(s)$ has the coefficients $\\mathfrak{M}(n) - \\ln n$,\n  so by Mertens' first theorem, $f(s) + \\zeta'(s)$ has bounded coefficients.\n\\<close>\nlemma bounded_coeffs_newman_minus_deriv_zeta:\n  defines \"f \\<equiv> fds_newman + fds_deriv fds_zeta\"\n  shows   \"Bseq (\\<lambda>n. fds_nth f n)\"\nproof -\n  have \"(\\<lambda>n. \\<MM> (real n) - ln (real n)) \\<in> O(\\<lambda>_. 1)\"\n    using mertens_bounded by (rule landau_o.big.compose) real_asymp\n  from natfun_bigo_1E[OF this, of 1]\n    obtain c where c: \"c \\<ge> 1\" \"\\<And>n. \\<bar>\\<MM> (real n) - ln (real n)\\<bar> \\<le> c\" by auto\n\n  show ?thesis\n  proof (intro BseqI[of c] allI)\n    fix n :: nat\n    show \"norm (fds_nth f n) \\<le> c\"\n    proof (cases \"n = 0\")\n      case False\n      hence \"fds_nth f n = of_real (\\<MM> n - ln n)\"\n        by (simp add: f_def fds_nth_newman fds_nth_deriv fds_nth_zeta scaleR_conv_of_real)\n      also from \\<open>n \\<noteq> 0\\<close> have \"norm \\<dots> \\<le> c\"\n        using c(2)[of n] by (simp add: in_Reals_norm)\n      finally show ?thesis .\n    qed (insert c, auto)\n  qed (insert c, auto)\nqed\n\ntext \\<open>\n  A Dirichlet series with bounded coefficients converges for all $s$ with\n  $\\mathfrak{R}(s)>1$ and so does $\\zeta'(s)$, so we can conclude that $f(s)$ does as well.\n\\<close>\nlemma abs_conv_abscissa_newman: \"abs_conv_abscissa fds_newman \\<le> 1\"\n  and conv_abscissa_newman:     \"conv_abscissa fds_newman \\<le> 1\"\nproof -\n  define f where \"f = fds_newman + fds_deriv fds_zeta\"\n  have \"abs_conv_abscissa f \\<le> 1\"\n    using bounded_coeffs_newman_minus_deriv_zeta unfolding f_def\n    by (rule bounded_coeffs_imp_abs_conv_abscissa_le_1)\n  hence \"abs_conv_abscissa (f - fds_deriv fds_zeta) \\<le> 1\"\n    by (intro abs_conv_abscissa_diff_leI) (auto simp: abs_conv_abscissa_deriv)\n  also have \"f - fds_deriv fds_zeta = fds_newman\" by (simp add: f_def)\n  finally show \"abs_conv_abscissa fds_newman \\<le> 1\" .\n  from conv_le_abs_conv_abscissa and this show \"conv_abscissa fds_newman \\<le> 1\"\n    by (rule order.trans)\nqed\n\ntext \\<open>\n  We now change the order of summation to obtain an alternative form of $f(s)$ in terms of a \n  sum of Hurwitz $\\zeta$ functions.\n\\<close>\nlemma eval_fds_newman_conv_infsetsum:\n  assumes s: \"Re s > 1\"\n  shows   \"eval_fds fds_newman s = (\\<Sum>\\<^sub>ap | prime p. (ln (real p) / real p) * hurwitz_zeta p s)\"\n          \"(\\<lambda>p. ln (real p) / real p * hurwitz_zeta p s) abs_summable_on {p. prime p}\"\nproof -\n  from s have conv: \"fds_abs_converges fds_newman s\"\n    by (intro fds_abs_converges le_less_trans[OF abs_conv_abscissa_newman]) auto\n  define f where \"f = (\\<lambda>n p. ln (real p) / real p / of_nat n powr s)\"\n\n  have eq: \"(\\<Sum>\\<^sub>an\\<in>{p..}. f n p) = ln (real p) / real p * hurwitz_zeta p s\" if \"prime p\" for p\n  proof -\n    have \"(\\<Sum>\\<^sub>an\\<in>{p..}. f n p) = (\\<Sum>\\<^sub>ax\\<in>{p..}. (ln (real p) / of_nat p) * (1 / of_nat x powr s))\"\n      by (simp add: f_def)\n    also have \"\\<dots> = (ln (real p) / of_nat p) * (\\<Sum>\\<^sub>ax\\<in>{p..}. 1 / of_nat x powr s)\"\n      using abs_summable_hurwitz_zeta[of s 0 p] that s\n      by (intro infsetsum_cmult_right) (auto dest: prime_gt_0_nat)\n    also have \"(\\<Sum>\\<^sub>ax\\<in>{p..}. 1 / of_nat x powr s) = hurwitz_zeta p s\"\n      using s that by (subst hurwitz_zeta_nat_conv_infsetsum(2))\n                      (auto dest: prime_gt_0_nat simp: field_simps powr_minus)\n    finally show ?thesis .\n  qed\n\n  have norm_f: \"norm (f n p) = ln p / p / n powr Re s\" if \"prime p\" for n p :: nat\n    by (auto simp: f_def norm_divide norm_mult norm_powr_real_powr)\n  from conv have \"(\\<lambda>n. norm (fds_nth fds_newman n / n powr s)) abs_summable_on UNIV\"\n    by (intro abs_summable_on_normI) (simp add: fds_abs_converges_altdef')\n  also have \"(\\<lambda>n. norm (fds_nth fds_newman n / n powr s)) =\n               (\\<lambda>n. \\<Sum>p | prime p \\<and> p \\<le> n. norm (f n p))\"\n    by (auto simp: norm_divide norm_fds_nth_newman sum_divide_distrib primes_M_def\n                   prime_sum_upto_def norm_mult norm_f norm_powr_real_powr intro!: sum.cong)\n  finally have summable1: \"(\\<lambda>(n,p). f n p) abs_summable_on (SIGMA n:UNIV. {p. prime p \\<and> p \\<le> n})\"\n    using conv by (subst abs_summable_on_Sigma_iff) auto\n  also have \"?this \\<longleftrightarrow> (\\<lambda>(p,n). f n p) abs_summable_on\n                         (\\<lambda>(n,p). (p,n)) ` (SIGMA n:UNIV. {p. prime p \\<and> p \\<le> n})\"\n    by (subst abs_summable_on_reindex_iff [symmetric]) (auto simp: case_prod_unfold inj_on_def)\n  also have \"(\\<lambda>(n,p). (p,n)) ` (SIGMA n:UNIV. {p. prime p \\<and> p \\<le> n}) =\n               (SIGMA p:{p. prime p}. {p..})\" by auto\n  finally have summable2: \"(\\<lambda>(p,n). f n p) abs_summable_on \\<dots>\" .\n  from abs_summable_on_Sigma_project1'[OF this]\n    have \"(\\<lambda>p. \\<Sum>\\<^sub>an\\<in>{p..}. f n p) abs_summable_on {p. prime p}\" by auto\n  also have \"?this \\<longleftrightarrow> (\\<lambda>p. ln (real p) / real p * hurwitz_zeta p s) abs_summable_on {p. prime p}\"\n    by (intro abs_summable_on_cong eq) auto\n  finally show \\<dots> .\n\n  have \"eval_fds fds_newman s =\n          (\\<Sum>\\<^sub>an. \\<Sum>p | prime p \\<and> p \\<le> n. ln (real p) / real p / of_nat n powr s)\"\n    using conv by (simp add: eval_fds_altdef fds_nth_newman sum_divide_distrib\n                             primes_M_def prime_sum_upto_def)\n  also have \"\\<dots> = (\\<Sum>\\<^sub>an. \\<Sum>\\<^sub>ap | prime p \\<and> p \\<le> n. f n p)\"\n    unfolding f_def by (subst infsetsum_finite) auto\n  also have \"\\<dots> = (\\<Sum>\\<^sub>a(n, p) \\<in> (SIGMA n:UNIV. {p. prime p \\<and> p \\<le> n}). f n p)\"\n    using summable1 by (subst infsetsum_Sigma) auto\n  also have \"\\<dots> = (\\<Sum>\\<^sub>a(p, n) \\<in> (\\<lambda>(n,p). (p, n)) ` (SIGMA n:UNIV. {p. prime p \\<and> p \\<le> n}). f n p)\"\n    by (subst infsetsum_reindex) (auto simp: case_prod_unfold inj_on_def)\n  also have \"(\\<lambda>(n,p). (p, n)) ` (SIGMA n:UNIV. {p. prime p \\<and> p \\<le> n}) =\n               (SIGMA p:{p. prime p}. {p..})\" by auto\n  also have \"(\\<Sum>\\<^sub>a(p,n)\\<in>\\<dots>. f n p) = (\\<Sum>\\<^sub>ap | prime p. \\<Sum>\\<^sub>an\\<in>{p..}. f n p)\"\n    using summable2 by (subst infsetsum_Sigma) auto\n  also have \"(\\<Sum>\\<^sub>ap | prime p. \\<Sum>\\<^sub>an\\<in>{p..}. f n p) =\n               (\\<Sum>\\<^sub>ap | prime p. ln (real p) / real p * hurwitz_zeta p s)\"\n    by (intro infsetsum_cong eq) auto\n  finally show \"eval_fds fds_newman s =\n                  (\\<Sum>\\<^sub>ap | prime p. (ln (real p) / real p) * hurwitz_zeta p s)\" .\nqed\n\n\ntext \\<open>\n  We now define a meromorphic continuation of $f(s)$ on $\\mathfrak{R}(s) > \\frac{1}{2}$.\n\n  To construct $f(s)$, we express it as\n  \\[f(s) = \\frac{1}{z-1}\\left(\\bar f(s) - \\frac{\\zeta'(s)}{\\zeta(s)}\\right)\\ ,\\]\n  where $\\bar f(s)$ (which we shall call \\<open>pre_newman\\<close>) is a function that is analytic on\n  $\\Re(s) > \\frac{1}{2}$, which can be shown fairly easily using the Weierstra\u00df M test.\n  \n  $\\zeta'(s)/\\zeta(s)$ is meromorphic except for a single pole at $s = 1$ and one $k$-th order\n  pole for any $k$-th order zero of $\\zeta$, but for the Prime Number Theorem, we are only\n  concerned with the area $\\mathfrak{R}(s) \\geq 1$, where $\\zeta$ does not have any zeros.\n\n  Taken together, this means that $f(s)$ is analytic for $\\mathfrak{R}(s)\\geq 1$ except for a\n  double pole at $s = 1$, which we will take care of later.\n\\<close>\n\ncontext\n  fixes A :: \"nat \\<Rightarrow> complex \\<Rightarrow> complex\" and B :: \"nat \\<Rightarrow> complex \\<Rightarrow> complex\"\n  defines \"A \\<equiv> (\\<lambda>p s. (s - 1) * pre_zeta (real p) s - \n                         of_nat p / (of_nat p powr s * (of_nat p powr s - 1)))\"\n  defines \"B \\<equiv> (\\<lambda>p s. of_real (ln (real p)) / of_nat p * A p s)\"\nbegin\n\ndefinition pre_newman :: \"complex \\<Rightarrow> complex\" where\n  \"pre_newman s = (\\<Sum>p. if prime p then B p s else 0)\"\n\ndefinition newman where \"newman s = 1 / (s - 1) * (pre_newman s - deriv zeta s / zeta s)\"\n\ntext \\<open>\n  The sum used in the definition of \\<open>pre_newman\\<close> converges uniformly on any disc within the\n  half-space with $\\mathfrak{R}(s) > \\frac{1}{2}$ by the Weierstra\u00df M test.\n\\<close>\nlemma uniform_limit_pre_newman:\n  assumes r: \"r \\<ge> 0\" \"Re s - r > 1 / 2\"\n  shows \"uniform_limit (cball s r)\n           (\\<lambda>n s. \\<Sum>p<n. if prime p then B p s else 0) pre_newman at_top\"\nproof -\n  from r have Re: \"Re z > 1 / 2\" if \"dist s z \\<le> r\" for z\n    using abs_Re_le_cmod[of \"s - z\"] r that\n    by (auto simp: dist_norm abs_if split: if_splits)\n\n  define x where \"x = Re s - r\" \\<comment> \\<open>The lower bound for the real part in the disc\\<close>\n  from r Re have \"x > 1 / 2\" by (auto simp: x_def)\n\n  \\<comment> \\<open>The following sequence \\<open>M\\<close> bounds the summand, and it is obviously $O(n^{-1-\\epsilon})$\n      and therefore summable\\<close>\n  define C where \"C = (norm s + r + 1) * (norm s + r) / x\"\n  define M where \"M = (\\<lambda>p::nat. ln p * (C / p powr (x + 1) + 1 / (p powr x * (p powr x - 1))))\"\n\n  show ?thesis unfolding pre_newman_def\n  proof (intro Weierstrass_m_test_ev[OF eventually_mono[OF eventually_gt_at_top[of 1]]] ballI)\n    show \"summable M\"\n    proof (rule summable_comparison_test_bigo)\n      define \\<epsilon> where \"\\<epsilon> = min (2 * x - 1) x / 2\"\n      from \\<open>x > 1 / 2\\<close> have \\<epsilon>: \"\\<epsilon> > 0\" \"1 + \\<epsilon> < 2 * x\" \"1 + \\<epsilon> < x + 1\"\n        by (auto simp: \\<epsilon>_def min_def field_simps)\n      show \"M \\<in> O(\\<lambda>n. n powr (- 1 - \\<epsilon>))\" unfolding M_def distrib_left\n        by (intro sum_in_bigo) (use \\<epsilon> in real_asymp)+\n      from \\<epsilon> show \"summable (\\<lambda>n. norm (n powr (- 1 - \\<epsilon>)))\"\n        by (simp add: summable_real_powr_iff)\n    qed\n  next\n    fix p :: nat and z assume p: \"p > 1\" and z: \"z \\<in> cball s r\"\n    from z r Re[of z] have x: \"Re z \\<ge> x\" \"x > 1 / 2\" and \"Re z > 1 / 2\"\n      using abs_Re_le_cmod[of \"s - z\"] by (auto simp: x_def algebra_simps dist_norm)\n    have norm_z: \"norm z \\<le> norm s + r\"\n      using z norm_triangle_ineq2[of z s] r by (auto simp: dist_norm norm_minus_commute)\n    from \\<open>p > 1\\<close> and x and r have \"M p \\<ge> 0\"\n      by (auto simp: C_def M_def intro!: mult_nonneg_nonneg add_nonneg_nonneg divide_nonneg_pos)\n\n    have bound: \"norm ((z - 1) * pre_zeta p z) \\<le> \n                   norm (z - 1) * (norm z / (Re z * p powr Re z))\"\n      using pre_zeta_bound'[of z p] p \\<open>Re z > 1 / 2\\<close>\n      unfolding norm_mult by (intro mult_mono pre_zeta_bound) auto\n\n    have \"norm (B p z) = ln p / p * norm (A p z)\"\n      unfolding B_def using \\<open>p > 1\\<close> by (simp add: B_def norm_mult norm_divide)\n    also have \"\\<dots> \\<le> ln p / p * (norm (z - 1) * norm z / Re z / p powr Re z + \n                                 p / (p powr Re z * (p powr Re z - 1)))\"\n      unfolding A_def using \\<open>p > 1\\<close> and \\<open>Re z > 1 / 2\\<close> and bound\n      by (intro mult_left_mono order.trans[OF norm_triangle_ineq4 add_mono] mult_left_mono)\n         (auto simp: norm_divide norm_mult norm_powr_real_powr\n               intro!: divide_left_mono order.trans[OF _ norm_triangle_ineq2])\n    also have \"\\<dots> = ln p * (norm (z - 1) * norm z / Re z / p powr (Re z + 1) + \n                            1 / (p powr Re z * (p powr Re z - 1)))\"\n      using \\<open>p > 1\\<close> by (simp add: field_simps powr_add powr_minus)\n    also have \"norm (z - 1) * norm z / Re z / p powr (Re z + 1) \\<le> C / p powr (x + 1)\"\n      unfolding C_def using r \\<open>Re z > 1 / 2\\<close> norm_z p x\n      by (intro mult_mono frac_le powr_mono order.trans[OF norm_triangle_ineq4]) auto\n    also have \"1 / (p powr Re z * (p powr Re z - 1)) \\<le>\n                 1 / (p powr x * (p powr x - 1))\" using \\<open>p > 1\\<close> x\n      by (intro divide_left_mono mult_mono powr_mono diff_right_mono mult_pos_pos)\n         (auto simp: ge_one_powr_ge_zero)\n    finally have \"norm (B p z) \\<le> M p\"\n      using \\<open>p > 1\\<close> by (simp add: mult_left_mono M_def)\n    with \\<open>M p \\<ge> 0\\<close> show \"norm (if prime p then B p z else 0) \\<le> M p\" by simp\n  qed\nqed\n\nlemma sums_pre_newman: \"Re s > 1 / 2 \\<Longrightarrow> (\\<lambda>p. if prime p then B p s else 0) sums pre_newman s\"\n  using tendsto_uniform_limitI[OF uniform_limit_pre_newman[of 0 s]] by (auto simp: sums_def)\n\nlemma analytic_pre_newman [THEN analytic_on_subset, analytic_intros]:\n  \"pre_newman analytic_on {s. Re s > 1 / 2}\"\nproof -\n  have holo: \"(\\<lambda>s::complex. if prime p then B p s else 0) holomorphic_on X\"\n    if \"X \\<subseteq> {s. Re s > 1 / 2}\" for X and p :: nat using that\n    by (cases \"prime p\")\n       (auto intro!: holomorphic_intros simp: B_def A_def dest!: prime_gt_1_nat)\n  have holo': \"pre_newman holomorphic_on ball s r\" if r: \"r \\<ge> 0\" \"Re s - r > 1 / 2\" for s r\n  proof -\n    from r have Re: \"Re z > 1 / 2\" if \"dist s z \\<le> r\" for z\n      using abs_Re_le_cmod[of \"s - z\"] r that by (auto simp: dist_norm abs_if split: if_splits)\n    show ?thesis\n      by (rule holomorphic_uniform_limit[OF _ uniform_limit_pre_newman[of r s]])\n         (insert that Re, auto intro!: always_eventually holomorphic_on_imp_continuous_on\n                                       holomorphic_intros holo)\n  qed\n  show ?thesis unfolding analytic_on_def\n  proof safe\n    fix s assume \"Re s > 1 / 2\"\n    thus \"\\<exists>r>0. pre_newman holomorphic_on ball s r\"\n      by (intro exI[of _ \"(Re s - 1 / 2) / 2\"] conjI holo') (auto simp: field_simps)\n  qed\nqed\n\nlemma holomorphic_pre_newman [holomorphic_intros]:\n  \"X \\<subseteq> {s. Re s > 1 / 2} \\<Longrightarrow> pre_newman holomorphic_on X\"\n  using analytic_pre_newman by (rule analytic_imp_holomorphic)\n\nlemma eval_fds_newman:\n  assumes s: \"Re s > 1\"\n  shows   \"eval_fds fds_newman s = newman s\"\nproof -\n  have eq: \"(ln (real p) / real p) * hurwitz_zeta p s =\n              1 / (s - 1) * (ln (real p) / (p powr s - 1) + B p s)\"\n    if p: \"prime p\" for p\n  proof -\n    have \"(ln (real p) / real p) * hurwitz_zeta p s =\n            ln (real p) / real p * (p powr (1 - s) / (s - 1) + pre_zeta p s)\"\n      using s by (auto simp add: hurwitz_zeta_def)\n    also have \"\\<dots> = 1 / (s - 1) * (ln (real p) / (p powr s - 1) + B p s)\"\n      using p s by (simp add: divide_simps powr_diff B_def)\n                   (auto simp: A_def field_simps dest: prime_gt_1_nat)?\n    finally show ?thesis .\n  qed\n\n  have \"(\\<lambda>p. (ln (real p) / real p) * hurwitz_zeta p s) abs_summable_on {p. prime p}\"\n    using s by (intro eval_fds_newman_conv_infsetsum)\n  hence \"(\\<lambda>p. 1 / (s - 1) * (ln (real p) / (p powr s - 1) + B p s))\n            abs_summable_on {p. prime p}\"\n    by (subst (asm) abs_summable_on_cong[OF eq refl]) auto\n  hence summable:\n    \"(\\<lambda>p. ln (real p) / (p powr s - 1) + B p s) abs_summable_on {p. prime p}\"\n    using s by (subst (asm) abs_summable_on_cmult_right_iff) auto\n\n  from s have [simp]: \"s \\<noteq> 1\" by auto\n  have \"eval_fds fds_newman s =\n          (\\<Sum>\\<^sub>ap | prime p. (ln (real p) / real p) * hurwitz_zeta p s)\"\n    using s by (rule eval_fds_newman_conv_infsetsum)\n  also have \"\\<dots> = (\\<Sum>\\<^sub>ap | prime p. 1 / (s - 1) * (ln (real p) / (p powr s - 1) + B p s))\"\n    by (intro infsetsum_cong eq) auto\n  also have \"\\<dots> = 1 / (s - 1) * (\\<Sum>\\<^sub>ap | prime p. ln (real p) / (p powr s - 1) + B p s)\"\n    (is \"_ = _ * ?S\") by (rule infsetsum_cmult_right[OF summable])\n  also have \"?S = (\\<Sum>p. if prime p then \n                      ln (real p) / (p powr s - 1) + B p s else 0)\"\n    by (subst infsetsum_nat[OF summable]) auto\n  also have \"\\<dots> = (\\<Sum>p. (if prime p then ln (real p) / (p powr s - 1) else 0) + \n                        (if prime p then B p s else 0))\"\n    by (intro suminf_cong) auto\n  also have \"\\<dots> = pre_newman s - deriv zeta s / zeta s\"\n    using sums_pre_newman[of s] sums_logderiv_zeta[of s] s\n    by (subst suminf_add [symmetric]) (auto simp: sums_iff)\n  finally show ?thesis by (simp add: newman_def)\nqed\n\nend\n\ntext \\<open>\n  Next, we shall attempt to get rid of the pole by subtracting suitable multiples of $\\zeta(s)$\n  and $\\zeta'(s)$. To this end, we shall first prove the following alternative definition of \n  $\\zeta'(s)$:\n\\<close>\nlemma deriv_zeta_eq':\n  assumes \"0 < Re s\" \"s \\<noteq> 1\"\n  shows \"deriv zeta s = deriv (\\<lambda>z. pre_zeta 1 z * (z - 1)) s / (s - 1) -\n                          (pre_zeta 1 s * (s - 1) + 1) / (s - 1)\\<^sup>2\"\n    (is \"_ = ?rhs\")\nproof (rule DERIV_imp_deriv)\n  have [derivative_intros]: \"(pre_zeta 1 has_field_derivative deriv (pre_zeta 1) s) (at s)\"\n    by (intro holomorphic_derivI[of _ UNIV] holomorphic_intros) auto\n  have *: \"deriv (\\<lambda>z. pre_zeta 1 z * (z - 1)) s = deriv (pre_zeta 1) s * (s - 1) + pre_zeta 1 s\"\n    by (subst deriv_mult)\n       (auto intro!: holomorphic_on_imp_differentiable_at[of _ UNIV] holomorphic_intros)\n  hence \"((\\<lambda>s. pre_zeta 1 s + 1 / (s - 1)) has_field_derivative\n           deriv (pre_zeta 1) s - 1 / ((s - 1) * (s - 1))) (at s)\"\n    using assms by (auto intro!: derivative_eq_intros)\n  also have \"deriv (pre_zeta 1) s - 1 / ((s - 1) * (s - 1)) = ?rhs\"\n    using * assms by (simp add: divide_simps power2_eq_square, simp add: field_simps)\n  also have \"((\\<lambda>s. pre_zeta 1 s + 1 / (s - 1)) has_field_derivative ?rhs) (at s) \\<longleftrightarrow>\n               (zeta has_field_derivative ?rhs) (at s)\"\n    using assms\n    by (intro has_field_derivative_cong_ev eventually_mono[OF t1_space_nhds[of _ 1]])\n       (auto simp: zeta_def hurwitz_zeta_def)\n  finally show \\<dots> .\nqed\n\ntext \\<open>\n  From this, it follows that $(s - 1) \\zeta'(s) - \\zeta'(s) / \\zeta(s)$ is analytic \n  for $\\mathfrak{R}(s) \\geq 1$:\n\\<close>\nlemma analytic_zeta_derivdiff:\n  obtains a where\n    \"(\\<lambda>z. if z = 1 then a else (z - 1) * deriv zeta z - deriv zeta z / zeta z)\n          analytic_on {s. Re s \\<ge> 1}\" \nproof \n  have neq: \"pre_zeta 1 z * (z - 1) + 1 \\<noteq> 0\" if \"Re z \\<ge> 1\" for z\n    using zeta_Re_ge_1_nonzero[of z] that\n    by (cases \"z = 1\") (auto simp: zeta_def hurwitz_zeta_def divide_simps)\n  let ?g = \"\\<lambda>z. (1 - inverse (pre_zeta 1 z * (z - 1) + 1)) * ((z - 1) *\n                deriv ((\\<lambda>u. pre_zeta 1 u * (u - 1))) z - (pre_zeta 1 z * (z - 1) + 1))\"\n  show \"(\\<lambda>z. if z = 1 then deriv ?g 1 else (z - 1) * deriv zeta z - deriv zeta z / zeta z)\n          analytic_on {s. Re s \\<ge> 1}\" (is \"?f analytic_on _\")\n  proof (rule pole_theorem_analytic_0)\n    show \"?g analytic_on {s. 1 \\<le> Re s}\" using neq\n      by (auto intro!: analytic_intros)\n  next\n    show \"\\<exists>d>0. \\<forall>w\\<in>ball z d - {1}. ?g w = (w - 1) * ?f w\"\n      if z: \"z \\<in> {s. 1 \\<le> Re s}\" for z\n    proof -\n      have *: \"isCont (\\<lambda>z. pre_zeta 1 z * (z - 1) + 1) z\"\n        by (auto intro!: continuous_intros)\n       obtain e where \"e > 0\" and e: \"\\<And>y. dist z y < e \\<Longrightarrow> pre_zeta (Suc 0) y * (y-1) + 1 \\<noteq> 0\"\n         using continuous_at_avoid [OF * neq[of z]] z by auto\n      show ?thesis\n      proof (intro exI ballI conjI)\n        fix w\n        assume w: \"w \\<in> ball z (min e 1) - {1}\"\n        then have \"Re w > 0\"\n          using complex_Re_le_cmod [of \"z-w\"] z by (simp add: dist_norm)\n        with w show \"?g w = (w - 1) * (if w = 1 then deriv ?g 1 else\n                        (w - 1) * deriv zeta w - deriv zeta w / zeta w)\"\n          by (subst (1 2) deriv_zeta_eq', \n              simp_all add: zeta_def hurwitz_zeta_def divide_simps e power2_eq_square)\n             (simp_all add: algebra_simps)?\n      qed (use \\<open>e > 0\\<close> in auto)\n    qed\n  qed auto\nqed\n\ntext \\<open>\n  Finally, $f(s) + \\zeta'(s) + c\\zeta(s)$ is analytic.\n\\<close>\nlemma analytic_newman_variant:\n  obtains c a where\n     \"(\\<lambda>z. if z = 1 then a else newman z + deriv zeta z + c * zeta z) analytic_on {s. Re s \\<ge> 1}\"\nproof -\n  obtain c where (* -euler_mascheroni *)\n    c: \"(\\<lambda>z. if z = 1 then c else (z - 1) * deriv zeta z - deriv zeta z / zeta z)\n        analytic_on {s. Re s \\<ge> 1}\"\n    using analytic_zeta_derivdiff by blast\n  let ?g = \"\\<lambda>z. pre_newman z +\n          (if z = 1 then c\n           else (z - 1) * deriv zeta z -\n                deriv zeta z / zeta z) - (c + pre_newman 1) * (pre_zeta 1 z * (z - 1) + 1)\"\n  have \"(\\<lambda>z. if z = 1 then deriv ?g 1 else newman z + deriv zeta z + (-(c + pre_newman 1)) * zeta z)\n        analytic_on {s. Re s \\<ge> 1}\"  (is \"?f analytic_on _\")\n  proof (rule pole_theorem_analytic_0)\n    show \"?g analytic_on {s. 1 \\<le> Re s}\"\n      by (intro c analytic_intros) auto\n  next\n    show \"\\<exists>d>0. \\<forall>w\\<in>ball z d - {1}. ?g w = (w - 1) * ?f w\"\n      if \"z \\<in> {s. 1 \\<le> Re s}\" for z using that\n      by (intro exI[of _ 1], simp_all add: newman_def divide_simps zeta_def hurwitz_zeta_def)\n         (auto simp: field_simps)?\n  qed auto\n  with that show ?thesis by blast\nqed\n\n\nsubsection \\<open>The asymptotic expansion of \\<open>\\<MM>\\<close>\\<close>\n\ntext \\<open>\n  Our next goal is to show the key result that $\\mathfrak{M}(x) = \\ln n + c + o(1)$.\n\n  As a first step, we invoke Ingham's Tauberian theorem on the function we have\n  just defined and obtain that the sum\n  \\[\\sum\\limits_{n=1}^\\infty \\frac{\\mathfrak{M}(n) - \\ln n + c}{n}\\]\n  exists.\n\\<close>\nlemma mertens_summable:\n  obtains c :: real where \"summable (\\<lambda>n. (\\<MM> n - ln n + c) / n)\"\nproof -\n  (* c = euler_mascheroni - pre_newman 1 *)\n  from analytic_newman_variant obtain c a where\n    analytic: \"(\\<lambda>z. if z = 1 then a else newman z + deriv zeta z + c * zeta z)\n                 analytic_on {s. Re s \\<ge> 1}\" .\n  define f where \"f = (\\<lambda>z. if z = 1 then a else newman z + deriv zeta z + c * zeta z)\"\n  have analytic: \"f analytic_on {s. Re s \\<ge> 1}\" using analytic by (simp add: f_def)\n  define F where \"F = fds_newman + fds_deriv fds_zeta + fds_const c * fds_zeta\"\n\n  note le = conv_abscissa_add_leI conv_abscissa_deriv_le conv_abscissa_newman conv_abscissa_mult_const_left\n  note intros = le le[THEN le_less_trans] le[THEN order.trans] fds_converges\n  have eval_F: \"eval_fds F s = f s\" if s: \"Re s > 1\" for s\n  proof -\n    have \"eval_fds F s = eval_fds (fds_newman + fds_deriv fds_zeta) s +\n                           eval_fds (fds_const c * fds_zeta) s\"\n      unfolding F_def using s by (subst eval_fds_add) (auto intro!: intros)\n    also have \"\\<dots> = f s\" using s unfolding f_def\n      by (subst eval_fds_add)\n         (auto intro!: intros simp: eval_fds_newman eval_fds_deriv_zeta eval_fds_mult eval_fds_zeta)\n    finally show ?thesis .\n  qed\n\n  have conv: \"fds_converges F s\" if \"Re s \\<ge> 1\" for s\n  proof (rule Newman_Ingham_1)\n    have \"(\\<lambda>n. \\<MM> (real n) - ln (real n)) \\<in> O(\\<lambda>_. 1)\"\n      using mertens_bounded by (rule landau_o.big.compose) real_asymp\n    from natfun_bigo_1E[OF this, of 1]\n      obtain c' where c': \"c' \\<ge> 1\" \"\\<And>n. \\<bar>\\<MM> (real n) - ln (real n)\\<bar> \\<le> c'\" by auto\n    have \"Bseq (fds_nth F)\"\n    proof (intro BseqI allI)\n      fix n :: nat\n      show \"norm (fds_nth F n) \\<le> (c' + norm c)\" unfolding F_def using c'\n        by (auto simp: fds_nth_zeta fds_nth_deriv fds_nth_newman scaleR_conv_of_real in_Reals_norm\n                 intro!: order.trans[OF norm_triangle_ineq] add_mono)\n    qed (insert c', auto intro: add_pos_nonneg)\n    thus \"fds_nth F \\<in> O(\\<lambda>_. 1)\" by (simp add: natfun_bigo_iff_Bseq)\n  next\n    show \"f analytic_on {s. Re s \\<ge> 1}\" by fact\n  next\n    show \"eval_fds F s = f s\" if \"Re s > 1\" for s using that by (rule eval_F)\n  qed (insert that, auto simp: F_def intro!: intros)\n  from conv[of 1] have \"summable (\\<lambda>n. fds_nth F n / of_nat n)\"\n    unfolding fds_converges_def by auto\n  also have \"?this \\<longleftrightarrow> summable (\\<lambda>n. (\\<MM> n - Ln n + c) / n)\"\n    by (intro summable_cong eventually_mono[OF eventually_gt_at_top[of 0]])\n       (auto simp: F_def fds_nth_newman fds_nth_deriv fds_nth_zeta scaleR_conv_of_real\n             intro!: sum.cong dest: prime_gt_0_nat)\n  finally have \"summable (\\<lambda>n. (\\<MM> n - Re (Ln (of_nat n)) + Re c) / n)\"\n    by (auto dest: summable_Re)\n  also have \"?this \\<longleftrightarrow> summable (\\<lambda>n. (\\<MM> n - ln n + Re c) / n)\"\n    by (intro summable_cong eventually_mono[OF eventually_gt_at_top[of 0]]) (auto intro!: sum.cong)\n  finally show ?thesis using that[of \"Re c\"] by blast\nqed\n\ntext \\<open>\n  Next, we prove a lemma given by Newman stating that if the sum $\\sum a_n / n$ exists and\n  $a_n + \\ln n$ is nondecreasing, then $a_n$ must tend to 0. Unfortunately, the proof is\n  rather tedious, but so is the paper version by Newman.\n\\<close>\nlemma sum_goestozero_lemma:\n  fixes d::real\n  assumes d: \"\\<bar>\\<Sum>i = M..N. a i / i\\<bar> < d\" and le: \"\\<And>n. a n + ln n \\<le> a (Suc n) + ln (Suc n)\"\n      and \"0 < M\" \"M < N\"\n    shows \"a M \\<le> d * N / (real N - real M) + (real N - real M) / M \\<and>\n          -a N \\<le> d * N / (real N - real M) + (real N - real M) / M\"\nproof -\n  have \"0 \\<le> d\"\n    using assms by linarith+\n  then have \"0 \\<le> d * N / (N - M + 1)\" by simp\n  then have le_dN: \"\\<lbrakk>0 \\<le> x \\<Longrightarrow> x \\<le> d * N / (N - M + 1)\\<rbrakk> \\<Longrightarrow> x \\<le> d * N / (N - M + 1)\" for x::real\n    by linarith\n  have le_a_ln: \"a m + ln m \\<le> a n + ln n\" if \"n \\<ge> m\" for n m\n    by (rule transitive_stepwise_le) (use le that in auto)\n  have *: \"x \\<le> b \\<and> y \\<le> b\" if \"a \\<le> b\" \"x \\<le> a\" \"y \\<le> a\" for a b x y::real\n    using that by linarith\n  show ?thesis\n  proof (rule *)\n    show \"d * N / (N - M) + ln (N / M) \\<le> d * N / (real N - real M) + (real N - real M) / M\"\n      using \\<open>0 < M\\<close> \\<open>M < N\\<close> ln_le_minus_one [of \"N / M\"]\n      by (simp add: of_nat_diff) (simp add: divide_simps)\n  next\n    have \"a M - ln (N / M) \\<le> (d * N) / (N - M + 1)\"\n    proof (rule le_dN)\n      assume 0: \"0 \\<le> a M - ln (N / M)\"\n      have \"(Suc N - M) * (a M - ln (N / M)) / N = (\\<Sum>i = M..N. (a M - ln (N / M)) / N)\"\n        by simp\n      also have \"\\<dots> \\<le> (\\<Sum>i = M..N. a i / i)\"\n      proof (rule sum_mono)\n        fix i\n        assume i: \"i \\<in> {M..N}\"\n        with \\<open>0 < M\\<close> have \"0 < i\" by auto\n        have \"(a M - ln (N / M)) / N \\<le> (a M - ln (N / M)) / i\"\n          using 0 using i \\<open>0 < M\\<close> by (simp add: frac_le_eq divide_simps mult_left_mono)\n        also have \"a M + ln (real M) \\<le> a i + ln (real N)\"\n          by (rule order.trans[OF le_a_ln[of M i]]) (use i assms in auto)\n        hence \"(a M - ln (N / M)) / i \\<le> a i / real i\"\n          using assms i by (intro divide_right_mono) (auto simp: ln_div field_simps)\n        finally show \"(a M - ln (N / M)) / real N \\<le> a i / real i\" .\n      qed\n      finally have \"((Suc N) - M) * (a M - ln (N / M)) / N \\<le> \\<bar>\\<Sum>i = M..N. a i / i\\<bar>\"\n        by simp\n      also have \"\\<dots> \\<le> d\" using d by simp\n      finally have \"((Suc N) - M) * (a M - ln (N / M)) / N \\<le> d\" .\n      then show ?thesis\n        using \\<open>M < N\\<close>  by (simp add: of_nat_diff field_simps)\n    qed\n    also have \"\\<dots> \\<le> d * N / (N - M)\"\n      using assms(1,4) by (simp add: field_simps)\n    finally show \"a M \\<le> d * N / (N - M) + ln (N / M)\" by simp\n  next\n    have \"- a N - ln (N / M) \\<le> (d * N) / (N - M + 1)\"\n    proof (rule le_dN)\n      assume 0: \"0 \\<le> - a N - ln (N / M)\"\n      have \"(\\<Sum>i = M..N. a i / i) \\<le> (\\<Sum>i = M..N. (a N + ln (N / M)) / N)\"\n      proof (rule sum_mono)\n        fix i\n        assume i: \"i \\<in> {M..N}\"\n        with \\<open>0 < M\\<close> have \"0 < i\" by auto\n        have \"a i + ln (real M) \\<le> a N + ln (real N)\"\n          by (rule order.trans[OF _ le_a_ln[of i N]]) (use i assms in auto)\n        hence \"a i / i \\<le> (a N + ln (N / M)) / i\"\n          using assms(3,4) by (intro divide_right_mono) (auto simp: field_simps ln_div)\n        also have \"\\<dots> \\<le> (a N + ln (N / M)) / N\"\n          using i \\<open>i > 0\\<close> 0 by (intro divide_left_mono_neg) auto\n        finally show \"a i / i \\<le> (a N + ln (N / M)) / N\" .\n      qed\n      also have \"\\<dots> = ((Suc N) - M) * (a N + ln (N / M)) / N\"\n        by simp\n      finally have \"(\\<Sum>i = M..N. a i / i) \\<le> (real (Suc N) - real M) * (a N + ln (N / M)) / N\"\n        using \\<open>M < N\\<close> by (simp add: of_nat_diff)\n      then have \"-((real (Suc N) - real M) * (a N + ln (N / M)) / N) \\<le> \\<bar>\\<Sum>i = M..N. a i / i\\<bar>\"\n        by linarith\n      also have \"\\<dots> \\<le> d\" using d by simp\n      finally have \"- ((real (Suc N) - real M) * (a N + ln (N / M)) / N) \\<le> d\" .\n      then show ?thesis\n        using \\<open>M < N\\<close>  by (simp add: of_nat_diff field_simps)\n    qed\n    also have \"\\<dots> \\<le> d * N / real (N - M)\"\n      using \\<open>0 < M\\<close> \\<open>M < N\\<close> \\<open>0 \\<le> d\\<close> by (simp add: field_simps)\n    finally show \"-a N \\<le> d * N / real (N - M) + ln (N / M)\" by simp\n  qed\nqed\n\nproposition sum_goestozero_theorem:\n  assumes summ: \"summable (\\<lambda>i. a i / i)\"\n      and le:   \"\\<And>n. a n + ln n \\<le> a (Suc n) + ln (Suc n)\"\n    shows \"a \\<longlonglongrightarrow> 0\"\nproof (clarsimp simp: lim_sequentially)\n  fix r::real\n  assume \"r > 0\"\n  have *: \"\\<exists>n0. \\<forall>n\\<ge>n0. \\<bar>a n\\<bar> < \\<epsilon>\" if \\<epsilon>: \"0 < \\<epsilon>\" \"\\<epsilon> < 1\" for \\<epsilon>\n  proof -\n    have \"0 < (\\<epsilon> / 8)\\<^sup>2\" using \\<open>0 < \\<epsilon>\\<close>  by simp\n    then obtain N0 where N0: \"\\<And>m n. m \\<ge> N0 \\<Longrightarrow> norm (\\<Sum>k=m..n. (\\<lambda>i. a i / i) k) < (\\<epsilon> / 8)\\<^sup>2\"\n      by (metis summable_partial_sum_bound summ)\n    obtain N1 where \"real N1 > 4 / \\<epsilon>\"\n      using reals_Archimedean2[of \"4 / \\<epsilon>\"] \\<epsilon> by auto\n    hence \"N1 \\<noteq> 0\" and N1: \"1 / real N1 < \\<epsilon> / 4\" using \\<epsilon>\n      by (auto simp: divide_simps mult_ac intro: Nat.gr0I)\n\n    have \"\\<bar>a n\\<bar> < \\<epsilon>\" if n: \"n \\<ge> 2 * N0 + N1 + 7\" for n\n    proof -\n      define k where \"k = \\<lfloor>n * \\<epsilon>/4\\<rfloor>\"\n      have \"n * \\<epsilon> / 4 > 1\" and \"n * \\<epsilon> / 4 \\<le> n / 4\" and \"n / 4 < n\"\n        using less_le_trans[OF N1, of \"n / N1 * \\<epsilon> / 4\"] \\<open>N1 \\<noteq> 0\\<close> \\<epsilon> n by (auto simp: field_simps)\n      hence k: \"k > 0\" \"4 * k \\<le> n\" \"nat k < n\" \"(n * \\<epsilon> / 4) - 1 < k\" \"k \\<le> (n * \\<epsilon> / 4)\"\n        unfolding k_def by linarith+\n\n      have \"-a n < \\<epsilon>\"\n      proof -\n        have \"N0 \\<le> n - nat k\"\n          using n k by linarith\n        then have *: \"\\<bar>\\<Sum>k = n - nat k .. n. a k / k\\<bar> < (\\<epsilon> / 8)\\<^sup>2\"\n          using N0 [of \"n - nat k\" n] by simp\n        have \"-a n \\<le> (\\<epsilon> / 8)\\<^sup>2 * n / \\<lfloor>n * \\<epsilon> / 4\\<rfloor> + \\<lfloor>n * \\<epsilon> / 4\\<rfloor> / (n - k)\"\n          using sum_goestozero_lemma [OF * le, THEN conjunct2] k by (simp add: of_nat_diff k_def)\n        also have \"\\<dots>< \\<epsilon>\"\n        proof -\n          have \"\\<epsilon> / 16 * n / k < 2\"\n            using k by (auto simp: field_simps)\n          then have \"\\<epsilon> * (\\<epsilon> / 16 * n / k) < \\<epsilon> * 2\"\n            using \\<epsilon> mult_less_cancel_left_pos by blast\n          then have \"(\\<epsilon> / 8)\\<^sup>2 * n / k < \\<epsilon> / 2\"\n            by (simp add: field_simps power2_eq_square)\n          moreover have \"k / (n - k) < \\<epsilon> / 2\"\n          proof -\n            have \"(\\<epsilon> + 2) * k < 4 * k\" using k \\<epsilon> by simp\n            also have \"\\<dots> \\<le> \\<epsilon> * real n\" using k by (auto simp: field_simps)\n            finally show ?thesis using k by (auto simp: field_simps)\n          qed\n          ultimately show ?thesis unfolding k_def by linarith\n        qed\n        finally show ?thesis .\n      qed\n      moreover have \"a n < \\<epsilon>\"\n      proof -\n        have \"N0 \\<le> n\" using n k by linarith\n        then have *: \"\\<bar>\\<Sum>k = n .. n + nat k. a k / k\\<bar> < (\\<epsilon>/8)\\<^sup>2\"\n          using N0 [of n \"n + nat k\"] by simp\n        have \"a n \\<le> (\\<epsilon>/8)\\<^sup>2 * (n + nat k) / k + k / n\"\n          using sum_goestozero_lemma [OF * le, THEN conjunct1] k by (simp add: of_nat_diff)\n        also have \"\\<dots>< \\<epsilon>\"\n        proof -\n          have \"4 \\<le> 28 * real_of_int k\" using k by linarith\n          then have \"\\<epsilon>/16 * n / k < 2\" using k by (auto simp: field_simps)\n          have \"\\<epsilon> * (real n + k) < 32 * k\"\n          proof -\n            have \"\\<epsilon> * n / 4 < k + 1\" by (simp add: mult.commute k_def)\n            then have \"\\<epsilon> * n < 4 * k + 4\" by (simp add: divide_simps)\n            also have \"\\<dots> \\<le> 8 * k\" using k by auto\n            finally have 1: \"\\<epsilon> * real n < 8 * k\" .\n            have 2: \"\\<epsilon> * k < k\" using k \\<epsilon> by simp\n            show ?thesis using k add_strict_mono [OF 1 2] by (simp add: algebra_simps)\n        qed\n          then have \"(\\<epsilon> / 8)\\<^sup>2 * real (n + nat k) / k < \\<epsilon> / 2\"\n            using \\<epsilon> k by (simp add: divide_simps mult_less_0_iff power2_eq_square)\n          moreover have \"k / n < \\<epsilon> / 2\"\n            using k \\<epsilon> by (auto simp: k_def field_simps)\n          ultimately show ?thesis by linarith\n        qed\n        finally show ?thesis .\n      qed\n      ultimately show ?thesis by force\n    qed\n    then show ?thesis by blast\n  qed\n  show \"\\<exists>n0. \\<forall>n\\<ge>n0. \\<bar>a n\\<bar> < r\"\n    using * [of \"min r (1/5)\"] \\<open>0 < r\\<close> by force\nqed\n\n\ntext \\<open>\n  This leads us to the main intermediate result:\n\\<close>\nlemma Mertens_convergent: \"convergent (\\<lambda>n::nat. \\<MM> n - ln n)\"\nproof -\n  obtain c where c: \"summable (\\<lambda>n. (\\<MM> n - ln n + c) / n)\"\n    by (blast intro: mertens_summable)\n  then obtain l where l: \"(\\<lambda>n. (\\<MM> n - ln n + c) / n) sums l\"\n    by (auto simp: summable_def)\n  have *: \"(\\<lambda>n. \\<MM> n - ln n + c) \\<longlonglongrightarrow> 0\"\n    by (rule sum_goestozero_theorem[OF c]) auto\n  hence \"(\\<lambda>n. \\<MM> n - ln n) \\<longlonglongrightarrow> -c\"\n    by (simp add: tendsto_iff dist_norm)\n  thus ?thesis by (rule convergentI)\nqed\n\ncorollary \\<MM>_minus_ln_limit:\n  obtains c where \"((\\<lambda>x::real. \\<MM> x - ln x) \\<longlongrightarrow> c) at_top\"\nproof -\n  from Mertens_convergent obtain c where \"(\\<lambda>n. \\<MM> n - ln n) \\<longlonglongrightarrow> c\"\n    by (auto simp: convergent_def)\n  hence 1: \"((\\<lambda>x::real. \\<MM> (nat \\<lfloor>x\\<rfloor>) - ln (nat \\<lfloor>x\\<rfloor>)) \\<longlongrightarrow> c) at_top\" \n    by (rule filterlim_compose) real_asymp\n  have 2: \"((\\<lambda>x::real. ln (nat \\<lfloor>x\\<rfloor>) - ln x) \\<longlongrightarrow> 0) at_top\"\n    by real_asymp\n  have 3: \"((\\<lambda>x. \\<MM> x - ln x) \\<longlongrightarrow> c) at_top\"\n    using tendsto_add[OF 1 2] by simp\n  with that show ?thesis by blast\nqed\n\n\nsubsection \\<open>The asymptotics of the prime-counting functions\\<close>\n\ntext \\<open>\n  We will now use the above result to prove the asymptotics of the prime-counting functions\n  $\\vartheta(x) \\sim x$, $\\psi(x) \\sim x$, and $\\pi(x) \\sim x / \\ln x$. The last of these is \n  typically called the Prime Number Theorem, but since these functions can be expressed in terms \n  of one another quite easily, knowing the asymptotics of any of them immediately gives the \n  asymptotics of the other ones.\n\n  In this sense, all of the above are equivalent formulations of the Prime Number Theorem.\n  The one we shall tackle first, due to its strong connection to the $\\mathfrak{M}$ function, is\n  $\\vartheta(x) \\sim x$.\n\n  We know that $\\mathfrak{M}(x)$ has the asymptotic expansion\n  $\\mathfrak{M}(x) = \\ln x + c + o(1)$. We also know that\n  \\[\\vartheta(x) = x\\mathfrak{M}(x) - \\int\\nolimits_2^x \\mathfrak{M}(t) \\,\\mathrm{d}t\\ .\\]\n  Substituting in the above asymptotic equation, we obtain:\n  \\begin{align*}\n  \\vartheta(x) &= x\\ln x + cx + o(x) - \\int\\nolimits_2^x \\ln t + c + o(1) \\,\\mathrm{d}t\\\\\n            &= x\\ln x + cx + o(x) - (x\\ln x - x + cx + o(x))\\\\\n            &= x + o(x)\n  \\end{align*}\n  In conclusion, $\\vartheta(x) \\sim x$.\n\\<close>\ntheorem \\<theta>_asymptotics: \"\\<theta> \\<sim>[at_top] (\\<lambda>x. x)\"\nproof -\n  from \\<MM>_minus_ln_limit obtain c where c: \"((\\<lambda>x. \\<MM> x - ln x) \\<longlongrightarrow> c) at_top\"\n    by auto\n  define r where \"r = (\\<lambda>x. \\<MM> x - ln x - c)\"\n  have \\<MM>_expand: \"\\<MM> = (\\<lambda>x. ln x + c + r x)\"\n    by (simp add: r_def)\n  have r: \"r \\<in> o(\\<lambda>_. 1)\" unfolding r_def\n    using tendsto_add[OF c tendsto_const[of \"-c\"]] by (intro smalloI_tendsto) auto\n\n  define r' where \"r' = (\\<lambda>x. integral {2..x} r)\"\n  have integrable_r: \"r integrable_on {x..y}\"\n    if \"2 \\<le> x\" for x y :: real using that unfolding r_def\n    by (intro integrable_diff integrable_primes_M)\n       (auto intro!: integrable_continuous_real continuous_intros)\n  hence integral: \"(r has_integral r' x) {2..x}\" if \"x \\<ge> 2\" for x\n    by (auto simp: has_integral_iff r'_def)\n  have r': \"r' \\<in> o(\\<lambda>x. x)\" using integrable_r unfolding r'_def\n    by (intro integral_smallo[OF r]) (auto simp: filterlim_ident)\n\n  define C where \"C = 2 * (c + ln 2 - 1)\"\n  have \"\\<theta> \\<sim>[at_top] (\\<lambda>x. x + (r x * x + C - r' x))\"\n  proof (intro asymp_equiv_refl_ev eventually_mono[OF eventually_gt_at_top])\n    fix x :: real assume x: \"x > 2\"\n    have \"(\\<MM> has_integral ((x * ln x - x + c * x) - (2 * ln 2 - 2 + c * 2) + r' x)) {2..x}\"\n      unfolding \\<MM>_expand using x\n      by (intro has_integral_add[OF fundamental_theorem_of_calculus integral])\n         (auto simp flip: has_field_derivative_iff_has_vector_derivative\n               intro!: derivative_eq_intros continuous_intros)\n    from has_integral_unique[OF \\<theta>_conv_\\<MM>_integral this]\n      show \"\\<theta> x = x + (r x * x + C - r' x)\" using x\n      by (simp add: field_simps \\<MM>_expand C_def)\n  qed\n  also have \"(\\<lambda>x. r x * x + C - r' x) \\<in> o(\\<lambda>x. x)\"\n  proof (intro sum_in_smallo r)\n    show \"(\\<lambda>_. C) \\<in> o(\\<lambda>x. x)\" by real_asymp\n  qed (insert landau_o.small_big_mult[OF r, of \"\\<lambda>x. x\"] r', simp_all)\n  hence \"(\\<lambda>x. x + (r x * x + C - r' x)) \\<sim>[at_top] (\\<lambda>x. x)\"\n    by (subst asymp_equiv_add_right) auto\n  finally show ?thesis by auto\nqed\n\ntext \\<open>\n  The various other forms of the Prime Number Theorem follow as simple corollaries.\n\\<close>\ncorollary \\<psi>_asymptotics: \"\\<psi> \\<sim>[at_top] (\\<lambda>x. x)\"\n  using \\<theta>_asymptotics PNT4_imp_PNT5 by simp\n  \ncorollary prime_number_theorem: \"\\<pi> \\<sim>[at_top] (\\<lambda>x. x / ln x)\"\n  using \\<theta>_asymptotics PNT4_imp_PNT1 by simp\n\ncorollary ln_\\<pi>_asymptotics: \"(\\<lambda>x. ln (\\<pi> x)) \\<sim>[at_top] ln\"\n  using prime_number_theorem PNT1_imp_PNT1' by simp\n\ncorollary \\<pi>_ln_\\<pi>_asymptotics: \"(\\<lambda>x. \\<pi> x * ln (\\<pi> x)) \\<sim>[at_top] (\\<lambda>x. x)\"\n  using prime_number_theorem PNT1_imp_PNT2 by simp\n\ncorollary nth_prime_asymptotics: \"(\\<lambda>n. real (nth_prime n)) \\<sim>[at_top] (\\<lambda>n. real n * ln (real n))\"\n  using \\<pi>_ln_\\<pi>_asymptotics PNT2_imp_PNT3 by simp\n\n\ntext \\<open>\n  The following versions use a little less notation.\n\\<close>\ncorollary prime_number_theorem': \"((\\<lambda>x. \\<pi> x / (x / ln x)) \\<longlongrightarrow> 1) at_top\"\n  using prime_number_theorem\n  by (rule asymp_equivD_strong[OF _ eventually_mono[OF eventually_gt_at_top[of 1]]]) auto\n\ncorollary prime_number_theorem'':\n  \"(\\<lambda>x. card {p. prime p \\<and> real p \\<le> x}) \\<sim>[at_top] (\\<lambda>x. x / ln x)\"\nproof -\n  have \"\\<pi> = (\\<lambda>x. card {p. prime p \\<and> real p \\<le> x})\"\n    by (intro ext) (simp add: \\<pi>_def prime_sum_upto_def)\n  with prime_number_theorem show ?thesis by simp\nqed\n\ncorollary prime_number_theorem''':\n  \"(\\<lambda>n. card {p. prime p \\<and> p \\<le> n}) \\<sim>[at_top] (\\<lambda>n. real n / ln (real n))\"\nproof -\n  have \"(\\<lambda>n. card {p. prime p \\<and> real p \\<le> real n}) \\<sim>[at_top] (\\<lambda>n. real n / ln (real n))\"\n    using prime_number_theorem''\n    by (rule asymp_equiv_compose') (simp add: filterlim_real_sequentially)\n  thus ?thesis by simp\nqed\n\n(*<*)\nunbundle no_prime_counting_notation\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/Prime_Number_Theorem/Prime_Number_Theorem.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528170040853, "lm_q2_score": 0.8221891392358015, "lm_q1q2_score": 0.7004663532821053}}
{"text": "(* Author: Tobias Nipkow *)\n(* Todo: minimal ipl of almost complete trees *)\n\nsection \\<open>Binary Tree\\<close>\n\ntheory Tree\nimports MainRLT\nbegin\n\ndatatype 'a tree =\n  Leaf (\"\\<langle>\\<rangle>\") |\n  Node \"'a tree\" (\"value\": 'a) \"'a tree\" (\"(1\\<langle>_,/ _,/ _\\<rangle>)\")\ndatatype_compat tree\n\nprimrec left :: \"'a tree \\<Rightarrow> 'a tree\" where\n\"left (Node l v r) = l\" |\n\"left Leaf = Leaf\"\n\nprimrec right :: \"'a tree \\<Rightarrow> 'a tree\" where\n\"right (Node l v r) = r\" |\n\"right Leaf = Leaf\"\n\ntext\\<open>Counting the number of leaves rather than nodes:\\<close>\n\nfun size1 :: \"'a tree \\<Rightarrow> nat\" where\n\"size1 \\<langle>\\<rangle> = 1\" |\n\"size1 \\<langle>l, x, r\\<rangle> = size1 l + size1 r\"\n\nfun subtrees :: \"'a tree \\<Rightarrow> 'a tree set\" where\n\"subtrees \\<langle>\\<rangle> = {\\<langle>\\<rangle>}\" |\n\"subtrees (\\<langle>l, a, r\\<rangle>) = {\\<langle>l, a, r\\<rangle>} \\<union> subtrees l \\<union> subtrees r\"\n\nfun mirror :: \"'a tree \\<Rightarrow> 'a tree\" where\n\"mirror \\<langle>\\<rangle> = Leaf\" |\n\"mirror \\<langle>l,x,r\\<rangle> = \\<langle>mirror r, x, mirror l\\<rangle>\"\n\nclass height = fixes height :: \"'a \\<Rightarrow> nat\"\n\ninstantiation tree :: (type)height\nbegin\n\nfun height_tree :: \"'a tree => nat\" where\n\"height Leaf = 0\" |\n\"height (Node l a r) = max (height l) (height r) + 1\"\n\ninstance ..\n\nend\n\nfun min_height :: \"'a tree \\<Rightarrow> nat\" where\n\"min_height Leaf = 0\" |\n\"min_height (Node l _ r) = min (min_height l) (min_height r) + 1\"\n\nfun complete :: \"'a tree \\<Rightarrow> bool\" where\n\"complete Leaf = True\" |\n\"complete (Node l x r) = (height l = height r \\<and> complete l \\<and> complete r)\"\n\ntext \\<open>Almost complete:\\<close>\ndefinition acomplete :: \"'a tree \\<Rightarrow> bool\" where\n\"acomplete t = (height t - min_height t \\<le> 1)\"\n\ntext \\<open>Weight balanced:\\<close>\nfun wbalanced :: \"'a tree \\<Rightarrow> bool\" where\n\"wbalanced Leaf = True\" |\n\"wbalanced (Node l x r) = (abs(int(size l) - int(size r)) \\<le> 1 \\<and> wbalanced l \\<and> wbalanced r)\"\n\ntext \\<open>Internal path length:\\<close>\nfun ipl :: \"'a tree \\<Rightarrow> nat\" where\n\"ipl Leaf = 0 \" |\n\"ipl (Node l _ r) = ipl l + size l + ipl r + size r\"\n\nfun preorder :: \"'a tree \\<Rightarrow> 'a list\" where\n\"preorder \\<langle>\\<rangle> = []\" |\n\"preorder \\<langle>l, x, r\\<rangle> = x # preorder l @ preorder r\"\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\ntext\\<open>A linear version avoiding append:\\<close>\nfun inorder2 :: \"'a tree \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where\n\"inorder2 \\<langle>\\<rangle> xs = xs\" |\n\"inorder2 \\<langle>l, x, r\\<rangle> xs = inorder2 l (x # inorder2 r xs)\"\n\nfun postorder :: \"'a tree \\<Rightarrow> 'a list\" where\n\"postorder \\<langle>\\<rangle> = []\" |\n\"postorder \\<langle>l, x, r\\<rangle> = postorder l @ postorder r @ [x]\"\n\ntext\\<open>Binary Search Tree:\\<close>\nfun bst_wrt :: \"('a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> 'a tree \\<Rightarrow> bool\" where\n\"bst_wrt P \\<langle>\\<rangle> \\<longleftrightarrow> True\" |\n\"bst_wrt P \\<langle>l, a, r\\<rangle> \\<longleftrightarrow>\n (\\<forall>x\\<in>set_tree l. P x a) \\<and> (\\<forall>x\\<in>set_tree r. P a x) \\<and> bst_wrt P l \\<and> bst_wrt P r\"\n\nabbreviation bst :: \"('a::linorder) tree \\<Rightarrow> bool\" where\n\"bst \\<equiv> bst_wrt (<)\"\n\nfun (in linorder) heap :: \"'a tree \\<Rightarrow> bool\" where\n\"heap Leaf = True\" |\n\"heap (Node l m r) =\n  ((\\<forall>x \\<in> set_tree l \\<union> set_tree r. m \\<le> x) \\<and> heap l \\<and> heap r)\"\n\n\nsubsection \\<open>\\<^const>\\<open>map_tree\\<close>\\<close>\n\nlemma eq_map_tree_Leaf[simp]: \"map_tree f t = Leaf \\<longleftrightarrow> t = Leaf\"\nby (rule tree.map_disc_iff)\n\nlemma eq_Leaf_map_tree[simp]: \"Leaf = map_tree f t \\<longleftrightarrow> t = Leaf\"\nby (cases t) auto\n\n\nsubsection \\<open>\\<^const>\\<open>size\\<close>\\<close>\n\nlemma size1_size: \"size1 t = size t + 1\"\nby (induction t) simp_all\n\nlemma size1_ge0[simp]: \"0 < size1 t\"\nby (simp add: size1_size)\n\nlemma eq_size_0[simp]: \"size t = 0 \\<longleftrightarrow> t = Leaf\"\nby(cases t) auto\n\nlemma eq_0_size[simp]: \"0 = size t \\<longleftrightarrow> t = Leaf\"\nby(cases t) auto\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 size_map_tree[simp]: \"size (map_tree f t) = size t\"\nby (induction t) auto\n\nlemma size1_map_tree[simp]: \"size1 (map_tree f t) = size1 t\"\nby (simp add: size1_size)\n\n\nsubsection \\<open>\\<^const>\\<open>set_tree\\<close>\\<close>\n\nlemma eq_set_tree_empty[simp]: \"set_tree t = {} \\<longleftrightarrow> t = Leaf\"\nby (cases t) auto\n\nlemma eq_empty_set_tree[simp]: \"{} = set_tree t \\<longleftrightarrow> t = Leaf\"\nby (cases t) auto\n\nlemma finite_set_tree[simp]: \"finite(set_tree t)\"\nby(induction t) auto\n\n\nsubsection \\<open>\\<^const>\\<open>subtrees\\<close>\\<close>\n\nlemma neq_subtrees_empty[simp]: \"subtrees t \\<noteq> {}\"\nby (cases t)(auto)\n\nlemma neq_empty_subtrees[simp]: \"{} \\<noteq> subtrees t\"\nby (cases t)(auto)\n\nlemma size_subtrees: \"s \\<in> subtrees t \\<Longrightarrow> size s \\<le> size t\"\nby(induction t)(auto)\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 \\<open>\\<^const>\\<open>height\\<close> and \\<^const>\\<open>min_height\\<close>\\<close>\n\nlemma eq_height_0[simp]: \"height t = 0 \\<longleftrightarrow> t = Leaf\"\nby(cases t) auto\n\nlemma eq_0_height[simp]: \"0 = height t \\<longleftrightarrow> t = Leaf\"\nby(cases t) auto\n\nlemma height_map_tree[simp]: \"height (map_tree f t) = height t\"\nby (induction t) auto\n\nlemma height_le_size_tree: \"height t \\<le> size (t::'a tree)\"\nby (induction t) auto\n\nlemma size1_height: \"size1 t \\<le> 2 ^ height (t::'a tree)\"\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 \"size1(Node l a r) = size1 l + size1 r\" by simp\n    also have \"\\<dots> \\<le> 2 ^ height l + 2 ^ height r\" using Node.IH by arith\n    also have \"\\<dots> \\<le> 2 ^ height r + 2 ^ height r\" using True by simp\n    also have \"\\<dots> = 2 ^ height (Node l a r)\"\n      using True by (auto simp: max_def mult_2)\n    finally show ?thesis .\n  next\n    case False\n    have \"size1(Node l a r) = size1 l + size1 r\" by simp\n    also have \"\\<dots> \\<le> 2 ^ height l + 2 ^ height r\" using Node.IH by arith\n    also have \"\\<dots> \\<le> 2 ^ height l + 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\ncorollary size_height: \"size t \\<le> 2 ^ height (t::'a tree) - 1\"\nusing size1_height[of t, unfolded size1_size] by(arith)\n\nlemma height_subtrees: \"s \\<in> subtrees t \\<Longrightarrow> height s \\<le> height t\"\nby (induction t) auto\n\n\nlemma min_height_le_height: \"min_height t \\<le> height t\"\nby(induction t) auto\n\nlemma min_height_map_tree[simp]: \"min_height (map_tree f t) = min_height t\"\nby (induction t) auto\n\nlemma min_height_size1: \"2 ^ min_height t \\<le> size1 t\"\nproof(induction t)\n  case (Node l a r)\n  have \"(2::nat) ^ min_height (Node l a r) \\<le> 2 ^ min_height l + 2 ^ min_height r\"\n    by (simp add: min_def)\n  also have \"\\<dots> \\<le> size1(Node l a r)\" using Node.IH by simp\n  finally show ?case .\nqed simp\n\n\nsubsection \\<open>\\<^const>\\<open>complete\\<close>\\<close>\n\nlemma complete_iff_height: \"complete t \\<longleftrightarrow> (min_height t = height t)\"\napply(induction t)\n apply simp\napply (simp add: min_def max_def)\nby (metis le_antisym le_trans min_height_le_height)\n\nlemma size1_if_complete: \"complete t \\<Longrightarrow> size1 t = 2 ^ height t\"\nby (induction t) auto\n\nlemma size_if_complete: \"complete t \\<Longrightarrow> size t = 2 ^ height t - 1\"\nusing size1_if_complete[simplified size1_size] by fastforce\n\nlemma size1_height_if_incomplete:\n  \"\\<not> complete t \\<Longrightarrow> size1 t < 2 ^ height t\"\nproof(induction t)\n  case Leaf thus ?case by simp\nnext\n  case (Node l x r)\n  have 1: ?case if h: \"height l < height r\"\n    using h size1_height[of l] size1_height[of r] power_strict_increasing[OF h, of \"2::nat\"]\n    by(auto simp: max_def simp del: power_strict_increasing_iff)\n  have 2: ?case if h: \"height l > height r\"\n    using h size1_height[of l] size1_height[of r] power_strict_increasing[OF h, of \"2::nat\"]\n    by(auto simp: max_def simp del: power_strict_increasing_iff)\n  have 3: ?case if h: \"height l = height r\" and c: \"\\<not> complete l\"\n    using h size1_height[of r] Node.IH(1)[OF c] by(simp)\n  have 4: ?case if h: \"height l = height r\" and c: \"\\<not> complete r\"\n    using h size1_height[of l] Node.IH(2)[OF c] by(simp)\n  from 1 2 3 4 Node.prems show ?case apply (simp add: max_def) by linarith\nqed\n\nlemma complete_iff_min_height: \"complete t \\<longleftrightarrow> (height t = min_height t)\"\nby(auto simp add: complete_iff_height)\n\nlemma min_height_size1_if_incomplete:\n  \"\\<not> complete t \\<Longrightarrow> 2 ^ min_height t < size1 t\"\nproof(induction t)\n  case Leaf thus ?case by simp\nnext\n  case (Node l x r)\n  have 1: ?case if h: \"min_height l < min_height r\"\n    using h min_height_size1[of l] min_height_size1[of r] power_strict_increasing[OF h, of \"2::nat\"]\n    by(auto simp: max_def simp del: power_strict_increasing_iff)\n  have 2: ?case if h: \"min_height l > min_height r\"\n    using h min_height_size1[of l] min_height_size1[of r] power_strict_increasing[OF h, of \"2::nat\"]\n    by(auto simp: max_def simp del: power_strict_increasing_iff)\n  have 3: ?case if h: \"min_height l = min_height r\" and c: \"\\<not> complete l\"\n    using h min_height_size1[of r] Node.IH(1)[OF c] by(simp add: complete_iff_min_height)\n  have 4: ?case if h: \"min_height l = min_height r\" and c: \"\\<not> complete r\"\n    using h min_height_size1[of l] Node.IH(2)[OF c] by(simp add: complete_iff_min_height)\n  from 1 2 3 4 Node.prems show ?case\n    by (fastforce simp: complete_iff_min_height[THEN iffD1])\nqed\n\nlemma complete_if_size1_height: \"size1 t = 2 ^ height t \\<Longrightarrow> complete t\"\nusing  size1_height_if_incomplete by fastforce\n\nlemma complete_if_size1_min_height: \"size1 t = 2 ^ min_height t \\<Longrightarrow> complete t\"\nusing min_height_size1_if_incomplete by fastforce\n\nlemma complete_iff_size1: \"complete t \\<longleftrightarrow> size1 t = 2 ^ height t\"\nusing complete_if_size1_height size1_if_complete by blast\n\n\nsubsection \\<open>\\<^const>\\<open>acomplete\\<close>\\<close>\n\nlemma acomplete_subtreeL: \"acomplete (Node l x r) \\<Longrightarrow> acomplete l\"\nby(simp add: acomplete_def)\n\nlemma acomplete_subtreeR: \"acomplete (Node l x r) \\<Longrightarrow> acomplete r\"\nby(simp add: acomplete_def)\n\nlemma acomplete_subtrees: \"\\<lbrakk> acomplete t; s \\<in> subtrees t \\<rbrakk> \\<Longrightarrow> acomplete s\"\nusing [[simp_depth_limit=1]]\nby(induction t arbitrary: s)\n  (auto simp add: acomplete_subtreeL acomplete_subtreeR)\n\ntext\\<open>Balanced trees have optimal height:\\<close>\n\nlemma acomplete_optimal:\nfixes t :: \"'a tree\" and t' :: \"'b tree\"\nassumes \"acomplete t\" \"size t \\<le> size t'\" shows \"height t \\<le> height t'\"\nproof (cases \"complete t\")\n  case True\n  have \"(2::nat) ^ height t \\<le> 2 ^ height t'\"\n  proof -\n    have \"2 ^ height t = size1 t\"\n      using True by (simp add: size1_if_complete)\n    also have \"\\<dots> \\<le> size1 t'\" using assms(2) by(simp add: size1_size)\n    also have \"\\<dots> \\<le> 2 ^ height t'\" by (rule size1_height)\n    finally show ?thesis .\n  qed\n  thus ?thesis by (simp)\nnext\n  case False\n  have \"(2::nat) ^ min_height t < 2 ^ height t'\"\n  proof -\n    have \"(2::nat) ^ min_height t < size1 t\"\n      by(rule min_height_size1_if_incomplete[OF False])\n    also have \"\\<dots> \\<le> size1 t'\" using assms(2) by (simp add: size1_size)\n    also have \"\\<dots> \\<le> 2 ^ height t'\"  by(rule size1_height)\n    finally have \"(2::nat) ^ min_height t < (2::nat) ^ height t'\" .\n    thus ?thesis .\n  qed\n  hence *: \"min_height t < height t'\" by simp\n  have \"min_height t + 1 = height t\"\n    using min_height_le_height[of t] assms(1) False\n    by (simp add: complete_iff_height acomplete_def)\n  with * show ?thesis by arith\nqed\n\n\nsubsection \\<open>\\<^const>\\<open>wbalanced\\<close>\\<close>\n\nlemma wbalanced_subtrees: \"\\<lbrakk> wbalanced t; s \\<in> subtrees t \\<rbrakk> \\<Longrightarrow> wbalanced s\"\nusing [[simp_depth_limit=1]] by(induction t arbitrary: s) auto\n\n\nsubsection \\<open>\\<^const>\\<open>ipl\\<close>\\<close>\n\ntext \\<open>The internal path length of a tree:\\<close>\n\nlemma ipl_if_complete_int:\n  \"complete t \\<Longrightarrow> int(ipl t) = (int(height t) - 2) * 2^(height t) + 2\"\napply(induction t)\n apply simp\napply simp\napply (simp add: algebra_simps size_if_complete of_nat_diff)\ndone\n\n\nsubsection \"List of entries\"\n\nlemma eq_inorder_Nil[simp]: \"inorder t = [] \\<longleftrightarrow> t = Leaf\"\nby (cases t) auto\n\nlemma eq_Nil_inorder[simp]: \"[] = inorder t \\<longleftrightarrow> t = Leaf\"\nby (cases t) auto\n\nlemma set_inorder[simp]: \"set (inorder t) = set_tree t\"\nby (induction t) auto\n\nlemma set_preorder[simp]: \"set (preorder t) = set_tree t\"\nby (induction t) auto\n\nlemma set_postorder[simp]: \"set (postorder t) = set_tree t\"\nby (induction t) auto\n\nlemma length_preorder[simp]: \"length (preorder t) = size t\"\nby (induction t) auto\n\nlemma length_inorder[simp]: \"length (inorder t) = size t\"\nby (induction t) auto\n\nlemma length_postorder[simp]: \"length (postorder t) = size t\"\nby (induction t) auto\n\nlemma preorder_map: \"preorder (map_tree f t) = map f (preorder t)\"\nby (induction t) auto\n\nlemma inorder_map: \"inorder (map_tree f t) = map f (inorder t)\"\nby (induction t) auto\n\nlemma postorder_map: \"postorder (map_tree f t) = map f (postorder t)\"\nby (induction t) auto\n\nlemma inorder2_inorder: \"inorder2 t xs = inorder t @ xs\"\nby (induction t arbitrary: xs) auto\n\n\nsubsection \\<open>Binary Search Tree\\<close>\n\nlemma bst_wrt_mono: \"(\\<And>x y. P x y \\<Longrightarrow> Q x y) \\<Longrightarrow> bst_wrt P t \\<Longrightarrow> bst_wrt Q t\"\nby (induction t) (auto)\n\nlemma bst_wrt_le_if_bst: \"bst t \\<Longrightarrow> bst_wrt (\\<le>) t\"\nusing bst_wrt_mono less_imp_le by blast\n\nlemma bst_wrt_le_iff_sorted: \"bst_wrt (\\<le>) t \\<longleftrightarrow> sorted (inorder t)\"\napply (induction t)\n apply(simp)\nby (fastforce simp: sorted_append intro: less_imp_le less_trans)\n\nlemma bst_iff_sorted_wrt_less: \"bst t \\<longleftrightarrow> sorted_wrt (<) (inorder t)\"\napply (induction t)\n apply simp\napply (fastforce simp: sorted_wrt_append)\ndone\n\n\nsubsection \\<open>\\<^const>\\<open>heap\\<close>\\<close>\n\n\nsubsection \\<open>\\<^const>\\<open>mirror\\<close>\\<close>\n\nlemma mirror_Leaf[simp]: \"mirror t = \\<langle>\\<rangle> \\<longleftrightarrow> t = \\<langle>\\<rangle>\"\nby (induction t) simp_all\n\nlemma Leaf_mirror[simp]: \"\\<langle>\\<rangle> = mirror t \\<longleftrightarrow> t = \\<langle>\\<rangle>\"\nusing mirror_Leaf by fastforce\n\nlemma size_mirror[simp]: \"size(mirror t) = size t\"\nby (induction t) simp_all\n\nlemma size1_mirror[simp]: \"size1(mirror t) = size1 t\"\nby (simp add: size1_size)\n\nlemma height_mirror[simp]: \"height(mirror t) = height t\"\nby (induction t) simp_all\n\nlemma min_height_mirror [simp]: \"min_height (mirror t) = min_height t\"\nby (induction t) simp_all  \n\nlemma ipl_mirror [simp]: \"ipl (mirror t) = ipl t\"\nby (induction t) simp_all\n\nlemma inorder_mirror: \"inorder(mirror t) = rev(inorder t)\"\nby (induction t) simp_all\n\nlemma map_mirror: \"map_tree f (mirror t) = mirror (map_tree f t)\"\nby (induction t) simp_all\n\nlemma mirror_mirror[simp]: \"mirror(mirror t) = t\"\nby (induction t) 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/Library/Tree.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8221891479496523, "lm_q2_score": 0.8519527963298947, "lm_q1q2_score": 0.7004663437077998}}
{"text": "theory \"Hales_Jewett\"\n  imports Main \"HOL-Library.Disjoint_Sets\" \"HOL-Library.FuncSet\"\nbegin\n\nsection \\<open>Preliminaries\\<close>\n\ntext \\<open>\n  The Hales--Jewett Theorem is at its core a statement about sets of tuples called the\n$n$-dimensional cube over $t$ elements (denoted by $C^n_t$); i.e.\\ the set $\\{0,\\ldots,t - 1\\}^n$, where \n$\\{0,\\ldots,t - 1\\}$ is called the base. \n  We represent tuples by functions $f : \\{0,\\ldots,n - 1\\} \\rightarrow \\{0,\\ldots,t - 1\\}$ because\nthey're easier to deal with. The set of tuples then becomes the function space \n$\\{0,\\ldots,t - 1\\}^{\\{0,\\ldots,n - 1\\}}$.\n  Furthermore, $r$-colourings of the cube are represented by mappings from the function space to the\nset $\\{0,\\ldots, r-1\\}$.\n\\<close>\n\nsubsection \\<open>The $n$-dimensional cube over $t$ elements\\<close>\n\ntext \\<open>\n  Function spaces in Isabelle are supported by the library component FuncSet.\n  In essence, \\<^prop>\\<open>f \\<in> A \\<rightarrow>\\<^sub>E B\\<close> means \\<^prop>\\<open>a \\<in> A \\<Longrightarrow> f a \\<in> B\\<close> and \\<^prop>\\<open>a \\<notin> A \\<Longrightarrow> f a = undefined\\<close>\n\\<close>\n\ntext \\<open>The (canonical) $n$-dimensional cube over $t$ elements is defined in the following using the variables:\n\n\\begin{tabular}{lcp{8cm}}\n$n$:& \\<^typ>\\<open>nat\\<close>& dimension\\\\\n$t$:& \\<^typ>\\<open>nat\\<close>& number of elements\\\\\n\\end{tabular}\\<close>\ndefinition cube :: \"nat \\<Rightarrow> nat \\<Rightarrow> (nat \\<Rightarrow> nat) set\"\n  where \"cube n t \\<equiv> {..<n} \\<rightarrow>\\<^sub>E {..<t}\"\n\ntext \\<open>\n  For any function $f$ whose image under a set $A$ is a subset of another set $B$, there's\na unique function $g$ in the function space $B^A$ that equals $f$ everywhere in $A$.\n  The function $g$ is usually written as $f|_A$ in the mathematical literature.\n\\<close>\nlemma PiE_uniqueness: \"f ` A \\<subseteq> B \\<Longrightarrow> \\<exists>!g \\<in> A\n\\<rightarrow>\\<^sub>E B. \\<forall>a\\<in>A. g a = f a\"\n  using exI[of \"\\<lambda>x. x \\<in> A \\<rightarrow>\\<^sub>E B \\<and> (\\<forall>a\\<in>A. x a = f a)\"\n      \"restrict f A\"] PiE_ext PiE_iff by fastforce\n\n\ntext \\<open>Any prefix of length $j$ of an $n$-tuple (i.e.\\ element of $C^n_t$) is a $j$-tuple\n(i.e.\\ element of $C^j_t$).\\<close>\nlemma cube_restrict: \n  assumes \"j < n\" \n    and \"y \\<in> cube n t\" \n  shows \"(\\<lambda>g \\<in> {..<j}. y g) \\<in> cube j t\" using assms unfolding cube_def by force\n\ntext \\<open>Narrowing down the obvious fact $B^A \\subseteq C^A$ if $B \\subseteq C$ to a specific case for cubes. \\<close>\nlemma cube_subset: \"cube n t \\<subseteq> cube n (t + 1)\"\n  unfolding cube_def using PiE_mono[of \"{..<n}\" \"\\<lambda>x. {..<t}\" \"\\<lambda>x. {..<t+1}\"]\n  by simp \n\ntext \\<open>A simplifying definition for the 0-dimensional cube.\\<close>\nlemma cube0_alt_def: \"cube 0 t = {\\<lambda>x. undefined}\"\n  unfolding cube_def by simp\n\ntext \\<open>\n  The cardinality of the \\<open>n\\<close>-dimensional over \\<open>t\\<close> elements is simply a consequence of the overarching \ndefinition of the cardinality of function spaces (over finite sets).\\<close>\nlemma cube_card: \"card ({..<n::nat} \\<rightarrow>\\<^sub>E {..<t::nat}) = t ^ n\"\n  by (simp add: card_PiE)\n\ntext \\<open>A simplifying definition for the \\<open>n\\<close>-dimensional cube over \na single element, i.e.\\ the single \\<open>n\\<close>-dimensional point \\<open>(0, \\<dots>, 0)\\<close>.\\<close>\nlemma cube1_alt_def: \"cube n 1 = {\\<lambda>x\\<in>{..<n}. 0}\" unfolding cube_def by (simp add: lessThan_Suc)\n\nsubsection \\<open>Lines\\<close>\n\ntext \\<open>The property of being a line in $C^n_t$ is defined in the following using the variables:\n\n\\begin{tabular}{llp{8cm}}\n$L$:& \\<^typ>\\<open>nat \\<Rightarrow> (nat \\<Rightarrow> nat)\\<close>& line\\\\\n$n$:& \\<^typ>\\<open>nat\\<close>& dimension of cube\\\\\n$t$:& \\<^typ>\\<open>nat\\<close>& the size of the cube's base\\\\\n\\end{tabular}\\<close>\ndefinition is_line :: \"(nat \\<Rightarrow> (nat \\<Rightarrow> nat)) \\<Rightarrow> nat \\<Rightarrow>\nnat \\<Rightarrow> bool\"\n  where \"is_line L n t \\<equiv> (L \\<in> {..<t} \\<rightarrow>\\<^sub>E cube n t \\<and>\n  ((\\<forall>j<n. (\\<forall>x<t. \\<forall>y<t. L x j =  L y j) \\<or> (\\<forall>s<t. L s j = s))\n  \\<and> (\\<exists>j < n. (\\<forall>s < t. L s j = s))))\"\n\ntext \\<open>We introduce an elimination rule to relate lines with the more general definition of a\nsubspace (see below). \\<close>\nlemma is_line_elim_t_1:\n  assumes \"is_line L n t\" and \"t = 1\"\n  obtains B\\<^sub>0 B\\<^sub>1\n  where \"B\\<^sub>0 \\<union> B\\<^sub>1 = {..<n} \\<and> B\\<^sub>0 \\<inter> B\\<^sub>1 = {} \\<and>\n  B\\<^sub>0 \\<noteq> {} \\<and> (\\<forall>j \\<in> B\\<^sub>1. (\\<forall>x<t. \\<forall>y<t. L x j = L y\n  j)) \\<and> (\\<forall>j \\<in> B\\<^sub>0. (\\<forall>s<t. L s j = s))\"\nproof -\n  define B0 where \"B0 = {..<n}\"\n  define B1 where \"B1 = ({}::nat set)\"\n  have \"B0 \\<union> B1 = {..<n}\" unfolding B0_def B1_def by simp\n  moreover have \"B0 \\<inter> B1 = {}\" unfolding B0_def B1_def by simp\n  moreover have \"B0 \\<noteq> {}\" using assms unfolding B0_def is_line_def by auto\n  moreover have \"(\\<forall>j \\<in> B1. (\\<forall>x<t. \\<forall>y<t. L x j = L y j))\" unfolding B1_def by simp\n  moreover have \"(\\<forall>j \\<in> B0. (\\<forall>s<t. L s j = s))\" using assms(1, 2) cube1_alt_def\n    unfolding B0_def is_line_def by auto\n  ultimately show ?thesis using that by simp\nqed\n\n\ntext \\<open>The next two lemmas are used to simplify proofs by enabling us to use the resulting\nfacts directly. This avoids having to unfold the definition of \\<^const>\\<open>is_line\\<close> each\ntime.\\<close>\nlemma line_points_in_cube: \n  assumes \"is_line L n t\" \n    and \"s < t\" \n  shows \"L s \\<in> cube n t\"\n  using assms unfolding cube_def is_line_def\n  by auto     \n\nlemma line_points_in_cube_unfolded:\n  assumes \"is_line L n t\" \n    and \"s < t\" \n    and \"j < n\" \n  shows \"L s j \\<in> {..<t}\" \n  using assms line_points_in_cube unfolding cube_def by blast\n\ntext \\<open>The incrementation of all elements of a set is defined in the following using the variables:\n\n\\begin{tabular}{llp{8cm}}\n$n$:& \\<^typ>\\<open>nat\\<close>& increment size\\\\\n$S$:& \\<^typ>\\<open>nat set\\<close>& set\\\\\n\\end{tabular}\\<close>\ndefinition set_incr :: \"nat \\<Rightarrow> nat set \\<Rightarrow> nat set\"\n  where\n  \t\"set_incr n S \\<equiv> (\\<lambda>a. a + n) ` S\"\n\nlemma set_incr_disjnt: \n  assumes \"disjnt A B\" \n  shows \"disjnt (set_incr n A) (set_incr n B)\" \n  using assms unfolding disjnt_def set_incr_def by force\n\nlemma set_incr_disjoint_family: \n  assumes \"disjoint_family_on B {..k}\" \n  shows \" disjoint_family_on (\\<lambda>i. set_incr n (B i)) {..k}\" \n  using assms set_incr_disjnt unfolding disjoint_family_on_def by (meson disjnt_def)\n\nlemma set_incr_altdef: \"set_incr n S = (+) n ` S\"\n  by (auto simp: set_incr_def)\n\nlemma set_incr_image:\n  assumes \"(\\<Union>i\\<in>{..k}. B i) = {..<n}\"\n  shows \"(\\<Union>i\\<in>{..k}. set_incr m (B i)) = {m..<m+n}\"\n  using assms by (simp add: set_incr_altdef add.commute flip: image_UN atLeast0LessThan)\n\ntext \\<open>Each tuple of dimension $k+1$ can be split into a tuple of dimension $1$ (the first\nentry) and a tuple of dimension $k$ (the remaining entries).\\<close>\nlemma split_cube: \n  assumes \"x \\<in> cube (k+1) t\" \n  shows \"(\\<lambda>y \\<in> {..<1}. x y) \\<in> cube 1 t\" \n    and \"(\\<lambda>y \\<in> {..<k}. x (y + 1)) \\<in> cube k t\"\n  using assms unfolding cube_def by auto\n\nsubsection \\<open>Subspaces\\<close>\n\ntext \\<open>The property of being a $k$-dimensional subspace of $C^n_t$ is defined in the following using the variables:\n\n\\begin{tabular}{llp{8cm}}\n$S$:& \\<^typ>\\<open>(nat \\<Rightarrow> nat) \\<Rightarrow> (nat \\<Rightarrow> nat)\\<close>& the subspace\\\\\n$k$:& \\<^typ>\\<open>nat\\<close>& the dimension of the subspace\\\\\n$n$:& \\<^typ>\\<open>nat\\<close>& the dimension of the cube\\\\\n$t$:& \\<^typ>\\<open>nat\\<close>& the size of the cube's base\n\\end{tabular}\\<close>\ndefinition is_subspace\n  where \"is_subspace S k n t \\<equiv> (\\<exists>B f. disjoint_family_on B {..k} \\<and> \\<Union>(B `\n  {..k}) = {..<n} \\<and> ({} \\<notin> B ` {..<k}) \\<and> f \\<in> (B k) \\<rightarrow>\\<^sub>E {..<t}\n  \\<and> S \\<in> (cube k t) \\<rightarrow>\\<^sub>E (cube n t) \\<and> (\\<forall>y \\<in> cube k t.\n  (\\<forall>i \\<in> B k. S y i = f i) \\<and> (\\<forall>j<k. \\<forall>i \\<in> B j. (S y) i = y j)))\"\n\ntext \\<open>A $k$-dimensional subspace of $C^n_t$ can be thought of as an embedding of the $C^k_t$\ninto $C^n_t$, akin to how a $k$-dimensional vector subspace of $\\mathbf{R}^n$ may be thought of as\nan embedding of $\\mathbf{R}^k$ into $\\mathbf{R}^n$.\\<close> \nlemma subspace_inj_on_cube: \n  assumes \"is_subspace S k n t\" \n  shows \"inj_on S (cube k t)\"\nproof \n\tfix x y\n\tassume a: \"x \\<in> cube k t\" \"y \\<in> cube k t\" \"S x = S y\"\n\tfrom assms obtain B f where Bf_props: \"disjoint_family_on B {..k} \\<and> \\<Union>(B ` {..k}) =\n    {..<n} \\<and> ({} \\<notin> B ` {..<k}) \\<and> f \\<in> (B k) \\<rightarrow>\\<^sub>E {..<t} \\<and>\n    S \\<in> (cube k t) \\<rightarrow>\\<^sub>E (cube n t) \\<and> (\\<forall>y \\<in> cube k t.\n    (\\<forall>i \\<in> B k. S y i = f i) \\<and> (\\<forall>j<k. \\<forall>i \\<in> B j. (S y) i = y j))\"\n    unfolding is_subspace_def by auto\n\thave \"\\<forall>i<k. x i = y i\"\n\tproof (intro allI impI)\n\t\tfix j assume \"j < k\"\n\t  then have \"B j \\<noteq> {}\" using Bf_props by auto\n\t  then obtain i where i_prop: \"i \\<in> B j\" by blast\n\t  then have \"y j = S y i\" using Bf_props a(2) \\<open>j < k\\<close> by auto\n\t  also have \" ... = S x i\" using a by simp\n\t  also have \" ... = x j\" using Bf_props a(1) \\<open>j < k\\<close> i_prop by blast\n\t  finally show \"x j = y j\" by simp\n\tqed\n\tthen show \"x = y\" using a(1,2) unfolding cube_def by (meson PiE_ext lessThan_iff)\nqed\n\ntext \\<open>The following is required to handle base cases in the key lemmas.\\<close>\nlemma dim0_subspace_ex: \n  assumes \"t > 0\" \n  shows \"\\<exists>S. is_subspace S 0 n t\"\nproof-\n  define B where \"B \\<equiv> (\\<lambda>x::nat. undefined)(0:={..<n})\"\n\n  have \"{..<t} \\<noteq> {}\" using assms by auto\n  then have \"\\<exists>f. f \\<in> (B 0) \\<rightarrow>\\<^sub>E {..<t}\" \n    by (meson PiE_eq_empty_iff all_not_in_conv)\n  then obtain f where f_prop: \"f \\<in> (B 0) \\<rightarrow>\\<^sub>E {..<t}\" by blast\n  define S where \"S \\<equiv> (\\<lambda>x::(nat \\<Rightarrow> nat). undefined)((\\<lambda>x. undefined):=f)\"\n\n  have \"disjoint_family_on B {..0}\" unfolding disjoint_family_on_def by simp\n  moreover have \"\\<Union>(B ` {..0}) = {..<n}\" unfolding B_def by simp\n  moreover have \"({} \\<notin> B ` {..<0})\" by simp\n  moreover have \"S \\<in> (cube 0 t) \\<rightarrow>\\<^sub>E (cube n t)\"\n    using f_prop PiE_I unfolding B_def cube_def S_def by auto\n  moreover have \"(\\<forall>y \\<in> cube 0 t. (\\<forall>i \\<in> B 0. S y i = f i) \\<and>\n  (\\<forall>j<0. \\<forall>i \\<in> B j. (S y) i = y j))\" unfolding cube_def S_def by force\n  ultimately have \"is_subspace S 0 n t\" using f_prop unfolding is_subspace_def by blast\n  then show \"\\<exists>S. is_subspace S 0 n t\" by auto\nqed\n\nsubsection \\<open>Equivalence classes\\<close>\ntext \\<open>Defining the equivalence classes of \\<^term>\\<open>cube n (t + 1)\\<close>:\n\\<open>{classes n t 0, \\<dots>, classes n t n}\\<close>\\<close>\ndefinition classes\n  where \"classes n t \\<equiv> (\\<lambda>i. {x . x \\<in> (cube n (t + 1)) \\<and> (\\<forall>u \\<in>\n  {(n-i)..<n}. x u = t) \\<and> t \\<notin> x ` {..<(n - i)}})\"\n\nlemma classes_subset_cube: \"classes n t i \\<subseteq> cube n (t+1)\" unfolding classes_def by blast\n\ndefinition layered_subspace\n  where \"layered_subspace S k n t r \\<chi> \\<equiv> (is_subspace S k n (t + 1)  \\<and> (\\<forall>i\n  \\<in> {..k}. \\<exists>c<r. \\<forall>x \\<in> classes k t i. \\<chi> (S x) = c)) \\<and> \\<chi> \\<in>\n  cube n (t + 1) \\<rightarrow>\\<^sub>E {..<r}\"\n\nlemma layered_eq_classes: \n  assumes \"layered_subspace S k n t r \\<chi>\" \n  shows \"\\<forall>i \\<in> {..k}. \\<forall>x \\<in> classes k t i. \\<forall>y \\<in> classes k t i.\n  \\<chi> (S x) = \\<chi> (S y)\" \nproof (safe)\n  fix i x y\n  assume a: \"i \\<le> k\" \"x \\<in> classes k t i\" \"y \\<in> classes k t i\"\n  then obtain c where \"c < r \\<and> \\<chi> (S x) = c \\<and> \\<chi> (S y) = c\" using assms unfolding\n      layered_subspace_def by fast\n  then show \"\\<chi> (S x) = \\<chi> (S y)\" by simp\nqed\n\nlemma dim0_layered_subspace_ex: \n  assumes \"\\<chi> \\<in> (cube n (t + 1)) \\<rightarrow>\\<^sub>E {..<r::nat}\" \n  shows \"\\<exists>S. layered_subspace S (0::nat) n t r \\<chi>\"\nproof-\n  obtain S where S_prop: \"is_subspace S (0::nat) n (t+1)\" using dim0_subspace_ex by auto\n  have \"classes (0::nat) t 0 = cube 0 (t+1)\" unfolding classes_def by simp\n  moreover have \"(\\<forall>i \\<in> {..0::nat}. \\<exists>c<r. \\<forall>x \\<in> classes (0::nat) t i. \\<chi> (S x) = c)\"\n  proof(safe)\n    fix i\n    have \"\\<forall>x \\<in> classes 0 t 0. \\<chi> (S x) = \\<chi> (S (\\<lambda>x. undefined))\" using cube0_alt_def \n      using \\<open>classes 0 t 0 = cube 0 (t + 1)\\<close> by auto\n    moreover have \"S (\\<lambda>x. undefined) \\<in> cube n (t+1)\" using S_prop cube0_alt_def\n      unfolding is_subspace_def by auto\n    moreover have \"\\<chi> (S (\\<lambda>x. undefined)) < r\" using assms calculation by auto\n    ultimately show \"\\<exists>c<r. \\<forall>x\\<in>classes 0 t 0. \\<chi> (S x) = c\" by auto\n  qed\n  ultimately have \"layered_subspace S 0 n t r \\<chi>\" using S_prop assms unfolding layered_subspace_def by blast\n  then show \"\\<exists>S. layered_subspace S (0::nat) n t r \\<chi>\" by auto\nqed\n\nlemma disjoint_family_onI [intro]:\n  assumes \"\\<And>m n. m \\<in> S \\<Longrightarrow> n \\<in> S \\<Longrightarrow> m \\<noteq> n\n  \\<Longrightarrow> A m \\<inter> A n = {}\"\n  shows   \"disjoint_family_on A S\"\n  using assms by (auto simp: disjoint_family_on_def)\n\nlemma fun_ex: \"a \\<in> A \\<Longrightarrow> b \\<in> B \\<Longrightarrow> \\<exists>f \\<in> A\n\\<rightarrow>\\<^sub>E B. f a = b\" \nproof-\n  assume assms: \"a \\<in> A\" \"b \\<in> B\"\n  then obtain g where g_def: \"g \\<in> A \\<rightarrow> B \\<and> g a = b\" by fast\n  then have \"restrict g A \\<in> A \\<rightarrow>\\<^sub>E B \\<and> (restrict g A) a = b\" using assms(1) by auto\n  then show ?thesis by blast\nqed\n\nlemma ex_bij_betw_nat_finite_2: \n  assumes \"card A = n\" \n    and \"n > 0\" \n  shows \"\\<exists>f. bij_betw f A {..<n}\"\n  using assms ex_bij_betw_finite_nat[of A] atLeast0LessThan card_ge_0_finite by auto\n\nlemma one_dim_cube_eq_nat_set: \"bij_betw (\\<lambda>f. f 0) (cube 1 k) {..<k}\"\nproof (unfold bij_betw_def)\n  have *: \"(\\<lambda>f. f 0) ` cube 1 k = {..<k}\"\n  proof(safe)\n    fix x f\n    assume \"f \\<in> cube 1 k\"\n    then show \"f 0 < k\" unfolding cube_def by blast\n  next\n    fix x\n    assume \"x < k\"\n    then have \"x \\<in> {..<k}\" by simp\n    moreover have \"0 \\<in> {..<1::nat}\" by simp\n    ultimately have \"\\<exists>y \\<in> {..<1::nat} \\<rightarrow>\\<^sub>E {..<k}. y 0 = x\" using\n        fun_ex[of \"0\" \"{..<1::nat}\" \"x\" \"{..<k}\"] by auto \n    then show \"x \\<in> (\\<lambda>f. f 0) ` cube 1 k\" unfolding cube_def by blast\n  qed\n  moreover \n  {\n    have \"card (cube 1 k) = k\" using cube_card by (simp add: cube_def)\n    moreover have \"card {..<k} = k\" by simp\n    ultimately have \"inj_on (\\<lambda>f. f 0) (cube 1 k)\" using * eq_card_imp_inj_on[of \"cube 1 k\" \"\\<lambda>f. f 0\"] \n      by force\n  }\n  ultimately show \"inj_on (\\<lambda>f. f 0) (cube 1 k) \\<and> (\\<lambda>f. f 0) ` cube 1 k = {..<k}\" by simp\nqed\n\ntext \\<open>An alternative introduction rule for the $\\exists!x$ quantifier, which means \"there\nexists exactly one $x$\".\\<close>\nlemma ex1I_alt: \"(\\<exists>x. P x \\<and> (\\<forall>y. P y \\<longrightarrow> x = y)) \\<Longrightarrow> (\\<exists>!x. P x)\" \n  by auto\nlemma nat_set_eq_one_dim_cube: \"bij_betw (\\<lambda>x. \\<lambda>y\\<in>{..<1::nat}. x) {..<k::nat} (cube 1 k)\"\nproof (unfold bij_betw_def)\n  have *: \"(\\<lambda>x. \\<lambda>y\\<in>{..<1::nat}. x) ` {..<k} = cube 1 k\"\n  proof (safe)\n    fix x y\n    assume \"y < k\"\n    then show \"(\\<lambda>z\\<in>{..<1}. y) \\<in> cube 1 k\" unfolding cube_def by simp\n  next\n    fix x\n    assume \"x \\<in> cube 1 k\"\n    have \"x = (\\<lambda>z. \\<lambda>y\\<in>{..<1::nat}. z) (x 0::nat)\" \n    proof\n      fix j \n      consider \"j \\<in> {..<1}\" | \"j \\<notin> {..<1::nat}\" by linarith\n      then show \"x j = (\\<lambda>z. \\<lambda>y\\<in>{..<1::nat}. z) (x 0::nat) j\" using \\<open>x\n      \\<in> cube 1 k\\<close> unfolding cube_def by auto\n    qed\n    moreover have \"x 0 \\<in> {..<k}\" using \\<open>x \\<in> cube 1 k\\<close> by (auto simp add: cube_def)\n    ultimately show \"x \\<in> (\\<lambda>z. \\<lambda>y\\<in>{..<1}. z) ` {..<k}\"  by blast\n  qed\n  moreover\n  {\n    have \"card (cube 1 k) = k\" using cube_card by (simp add: cube_def)\n    moreover have \"card {..<k} = k\" by simp\n    ultimately have  \"inj_on (\\<lambda>x. \\<lambda>y\\<in>{..<1::nat}. x) {..<k}\" using *\n        eq_card_imp_inj_on[of \"{..<k}\" \"\\<lambda>x. \\<lambda>y\\<in>{..<1::nat}. x\"] by force\n  }\n  ultimately show \"inj_on (\\<lambda>x. \\<lambda>y\\<in>{..<1::nat}. x) {..<k} \\<and> (\\<lambda>x.\n  \\<lambda>y\\<in>{..<1::nat}. x) ` {..<k} = cube 1 k\" by blast\nqed\n\ntext \\<open>A bijection $f$ between domains $A_1$ and $A_2$ creates a correspondence between\nfunctions in $A_1 \\rightarrow B$ and $A_2 \\rightarrow B$.\\<close>\nlemma bij_domain_PiE:\n  assumes \"bij_betw f A1 A2\" \n    and \"g \\<in> A2 \\<rightarrow>\\<^sub>E B\"\n  shows \"(restrict (g \\<circ> f) A1) \\<in> A1 \\<rightarrow>\\<^sub>E B\"\n  using bij_betwE assms by fastforce\n\ntext \\<open>The following three lemmas relate lines to $1$-dimensional subspaces (in the natural\nway). This is a direct consequence of the elimination rule \\<open>is_line_elim\\<close> introduced\nabove.\\<close>\nlemma line_is_dim1_subspace_t_1: \n  assumes \"n > 0\" \n    and \"is_line L n 1\"\n  shows \"is_subspace (restrict (\\<lambda>y. L (y 0)) (cube 1 1)) 1 n 1\"\nproof -\n  obtain B\\<^sub>0 B\\<^sub>1 where B_props: \"B\\<^sub>0 \\<union> B\\<^sub>1 = {..<n} \\<and> B\\<^sub>0\n  \\<inter> B\\<^sub>1 = {} \\<and> B\\<^sub>0 \\<noteq> {} \\<and> (\\<forall>j \\<in> B\\<^sub>1.\n  (\\<forall>x<1. \\<forall>y<1. L x j = L y j)) \\<and> (\\<forall>j \\<in> B\\<^sub>0. (\\<forall>s<1. L\n  s j = s))\" using is_line_elim_t_1[of L n 1] assms by auto\n  define B where \"B \\<equiv> (\\<lambda>i::nat. {}::nat set)(0:=B\\<^sub>0, 1:=B\\<^sub>1)\" \n  define f where \"f \\<equiv> (\\<lambda>i \\<in> B 1. L 0 i)\"\n  have *: \"L 0 \\<in> {..<n} \\<rightarrow>\\<^sub>E {..<1}\" using assms(2) unfolding cube_def is_line_def by auto\n  have \"disjoint_family_on B {..1}\" unfolding B_def using B_props \n    by (simp add: Int_commute disjoint_family_onI)\n  moreover have \"\\<Union> (B ` {..1}) = {..<n}\" unfolding B_def using B_props by auto\n  moreover have \"{} \\<notin> B ` {..<1}\" unfolding B_def using B_props by auto\n  moreover have \" f \\<in> B 1 \\<rightarrow>\\<^sub>E {..<1}\" using * calculation(2) unfolding f_def by auto\n  moreover have \"(restrict (\\<lambda>y. L (y 0)) (cube 1 1)) \\<in> cube 1 1 \\<rightarrow>\\<^sub>E cube n 1\" \n    using assms(2) cube1_alt_def unfolding is_line_def by auto\n  moreover have \"(\\<forall>y\\<in>cube 1 1. (\\<forall>i\\<in>B 1. (restrict (\\<lambda>y. L (y 0)) (cube 1 1)) y i = f i) \n  \\<and> (\\<forall>j<1. \\<forall>i\\<in>B j. (restrict (\\<lambda>y. L (y 0)) (cube 1 1)) y i = y j))\" \n    using cube1_alt_def B_props * unfolding B_def f_def by auto\n  ultimately show ?thesis unfolding is_subspace_def by blast \nqed\n\nlemma line_is_dim1_subspace_t_ge_1: \n  assumes \"n > 0\"\n    and \"t > 1\"\n    and \"is_line L n t\"\n  shows \"is_subspace (restrict (\\<lambda>y. L (y 0)) (cube 1 t)) 1 n t\"\nproof -\n  let ?B1 = \"{i::nat . i < n \\<and> (\\<forall>x<t. \\<forall>y<t. L x i =  L y i)}\"\n  let ?B0 = \"{i::nat . i < n \\<and> (\\<forall>s < t. L s i = s)}\"\n  define B where \"B \\<equiv> (\\<lambda>i::nat. {}::nat set)(0:=?B0, 1:=?B1)\"\n  let ?L = \"(\\<lambda>y \\<in> cube 1 t. L (y 0))\"\n  have \"?B0 \\<noteq> {}\" using assms(3) unfolding is_line_def by simp\n\n  have L1: \"?B0 \\<union> ?B1 = {..<n}\" using assms(3) unfolding is_line_def by auto\n  {\n    have \"(\\<forall>s < t. L s i = s) \\<longrightarrow> \\<not>(\\<forall>x<t. \\<forall>y<t. L x i =\n    L y i)\" if \"i < n\" for i using assms(2) less_trans by auto \n    then have *:\"i \\<notin> ?B0\" if \"i \\<in> ?B1\" for i using that by blast\n  }\n  moreover\n  {\n    have \"(\\<forall>x<t. \\<forall>y<t. L x i =  L y i) \\<longrightarrow> \\<not>(\\<forall>s < t. L s i = s)\" \n      if \"i < n\" for i using that calculation by blast\n    then have **: \"\\<forall>i \\<in> ?B0. i \\<notin> ?B1\" \n      by blast\n  }\n  ultimately have L2: \"?B0 \\<inter> ?B1 = {}\" by blast\n\n  let ?f = \"(\\<lambda>i. if i \\<in> B 1 then L 0 i else undefined)\"\n  {\n    have \"{..1::nat} = {0, 1}\" by auto\n    then have \"\\<Union>(B ` {..1::nat}) = B 0 \\<union> B 1\" by simp\n    then have \"\\<Union>(B ` {..1::nat}) = ?B0 \\<union> ?B1\" unfolding B_def by simp\n    then have A1: \"disjoint_family_on B {..1::nat}\" using L2 \n      by (simp add: B_def Int_commute disjoint_family_onI)\n  }\n  moreover\n  {\n    have \"\\<Union>(B ` {..1::nat}) = B 0 \\<union> B 1\" unfolding B_def by auto\n    then have \"\\<Union>(B ` {..1::nat}) = {..<n}\" using L1 unfolding B_def by simp\n  }\n  moreover\n  {\n    have \"\\<forall>i \\<in> {..<1::nat}. B i \\<noteq> {}\" \n      using \\<open>{i. i < n \\<and> (\\<forall>s<t. L s i = s)} \\<noteq> {}\\<close> fun_upd_same lessThan_iff less_one \n      unfolding B_def by auto\n    then have \"{} \\<notin> B ` {..<1::nat}\" by blast\n  }\n  moreover \n  {\n    have \"?f \\<in> (B 1) \\<rightarrow>\\<^sub>E {..<t}\" \n    proof\n      fix i\n      assume asm: \"i \\<in> (B 1)\"\n      have \"L a b \\<in> {..<t}\" if \"a < t\" and \"b < n\" for a b using assms(3) that unfolding is_line_def cube_def by auto\n      then have \"L 0 i \\<in> {..<t}\" using assms(2) asm calculation(2) by blast\n      then show \"?f i \\<in> {..<t}\" using asm by presburger\n    qed (auto)\n  }\n\n  moreover\n  {\n    have \"L \\<in> {..<t} \\<rightarrow>\\<^sub>E (cube n t)\" using assms(3) by (simp add: is_line_def)\n    then have \"?L \\<in> (cube 1 t) \\<rightarrow>\\<^sub>E (cube n t)\"\n      using bij_domain_PiE[of \"(\\<lambda>f. f 0)\" \"(cube 1 t)\" \"{..<t}\" \"L\" \"cube n t\"] one_dim_cube_eq_nat_set[of \"t\"] \n      by auto\n  }\n  moreover\n  {\n    have \"\\<forall>y \\<in> cube 1 t. (\\<forall>i \\<in> B 1. ?L y i = ?f i) \\<and> (\\<forall>j < 1.\n    \\<forall>i \\<in> B j. (?L y) i = y j)\"\n    proof\n      fix y \n      assume \"y \\<in> cube 1 t\"\n      then have \"y 0 \\<in> {..<t}\" unfolding cube_def by blast\n\n      have \"(\\<forall>i \\<in> B 1. ?L y i = ?f i)\"\n      proof\n        fix i\n        assume \"i \\<in> B 1\"\n        then have \"?f i = L 0 i\" \n          by meson\n        moreover have \"?L y i = L (y 0) i\" using \\<open>y \\<in> cube 1 t\\<close> by simp\n        moreover have \"L (y 0) i = L 0 i\" \n        proof -\n          have \"i \\<in> ?B1\" using \\<open>i \\<in> B 1\\<close> unfolding B_def fun_upd_def by presburger\n          then have \"(\\<forall>x<t. \\<forall>y<t. L x i = L y i)\" by blast\n          then show \"L (y 0) i = L 0 i\" using \\<open>y 0 \\<in> {..<t}\\<close> by blast\n        qed\n        ultimately show \"?L y i = ?f i\" by simp\n      qed\n\n      moreover have \"(?L y) i = y j\" if \"j < 1\" and \"i \\<in> B j\" for i j\n      proof-\n        have \"i \\<in> B 0\" using that by blast\n        then have \"i \\<in> ?B0\" unfolding B_def by auto \n        then have \"(\\<forall>s < t. L s i = s)\" by blast\n        moreover have \"y 0 < t\" using \\<open>y \\<in> cube 1 t\\<close> unfolding cube_def by auto\n        ultimately have \"L (y 0) i = y 0\" by simp\n        then show \"?L y i = y j\" using that using \\<open>y \\<in> cube 1 t\\<close> by force\n      qed\n\n      ultimately show \"(\\<forall>i \\<in> B 1. ?L y i = ?f i) \\<and> (\\<forall>j < 1. \\<forall>i\n      \\<in> B j. (?L y) i = y j)\" \n        by blast\n    qed\n  }\n  ultimately show \"is_subspace ?L 1 n t\" unfolding is_subspace_def by blast\nqed\n\nlemma line_is_dim1_subspace: \n  assumes \"n > 0\" \n    and \"t > 0\" \n    and \"is_line L n t\"\n  shows \"is_subspace (restrict (\\<lambda>y. L (y 0)) (cube 1 t)) 1 n t\"\n  using line_is_dim1_subspace_t_1[of n L] line_is_dim1_subspace_t_ge_1[of n t L] assms not_less_iff_gr_or_eq by blast\n\ntext \\<open>The key property of the existence of a minimal dimension $N$, such that for any\n$r$-colouring in $C^{N'}_t$ (for $N' \\geq N$) there exists a monochromatic line is defined in the\nfollowing using the variables:\n\n\\begin{tabular}{llp{8cm}}\n$r$:& \\<^typ>\\<open>nat\\<close>& the number of colours\\\\\n$t$:& \\<^typ>\\<open>nat\\<close>& the size of of the base\n\\end{tabular}\\<close>\ndefinition hj \n  where \"hj r t \\<equiv> (\\<exists>N>0. \\<forall>N' \\<ge> N. \\<forall>\\<chi>. \\<chi> \\<in> (cube N'\n  t) \\<rightarrow>\\<^sub>E {..<r::nat} \\<longrightarrow> (\\<exists>L. \\<exists>c<r. is_line L N' t\n  \\<and> (\\<forall>y \\<in> L ` {..<t}. \\<chi> y = c)))\"\n\ntext \\<open>The key property of the existence of a minimal dimension $N$, such that for any\n$r$-colouring in $C^{N'}_t$ (for $N' \\geq N$) there exists a layered subspace of dimension $k$ is\ndefined in the following using the variables:\n\n\\begin{tabular}{llp{8cm}}\n$r$:& \\<^typ>\\<open>nat\\<close>& the number of colours\\\\\n$t$:& \\<^typ>\\<open>nat\\<close>& the size of of the base\\\\\n$k$:& \\<^typ>\\<open>nat\\<close>& the dimension of the subspace\n\\end{tabular}\\<close>\ndefinition lhj\n  where \"lhj r t k \\<equiv> (\\<exists>N > 0. \\<forall>N' \\<ge> N. \\<forall>\\<chi>. \\<chi> \\<in>\n  (cube N' (t + 1)) \\<rightarrow>\\<^sub>E {..<r::nat} \\<longrightarrow> (\\<exists>S.\n  layered_subspace S k N' t r \\<chi>))\"\n\ntext \\<open>We state some useful facts about $1$-dimensional subspaces.\\<close>\nlemma dim1_subspace_elims: \n  assumes \"disjoint_family_on B {..1::nat}\" and \"\\<Union>(B ` {..1::nat}) = {..<n}\" and \"({}\n  \\<notin> B ` {..<1::nat})\" and  \"f \\<in> (B 1) \\<rightarrow>\\<^sub>E {..<t}\" and \"S \\<in> (cube 1\n  t) \\<rightarrow>\\<^sub>E (cube n t)\" and \"(\\<forall>y \\<in> cube 1 t. (\\<forall>i \\<in> B 1. S y i\n  = f i) \\<and> (\\<forall>j<1. \\<forall>i \\<in> B j. (S y) i = y j))\"\n  shows \"B 0 \\<union> B 1 = {..<n}\"\n    and \"B 0 \\<inter> B 1 = {}\"\n    and \"(\\<forall>y \\<in> cube 1 t. (\\<forall>i \\<in> B 1. S y i = f i) \\<and> (\\<forall>i \\<in> B 0. (S y) i = y 0))\"\n    and \"B 0 \\<noteq> {}\"\nproof -\n  have \"{..1} = {0::nat, 1}\" by auto\n  then show \"B 0 \\<union> B 1 = {..<n}\"  using assms(2) by simp\nnext\n  show \"B 0 \\<inter> B 1 = {}\" using assms(1) unfolding disjoint_family_on_def by simp\nnext\n  show \"(\\<forall>y \\<in> cube 1 t. (\\<forall>i \\<in> B 1. S y i = f i) \\<and> (\\<forall>i \\<in> B 0. (S y) i = y 0))\" \n    using assms(6) by simp\nnext\n  show \"B 0 \\<noteq> {}\" using assms(3) by auto\nqed\n\ntext \\<open>We state some properties of cubes.\\<close>\nlemma cube_props:\n  assumes \"s < t\"\n  shows \"\\<exists>p \\<in> cube 1 t. p 0 = s\"\n    and \"(SOME p. p \\<in> cube 1 t \\<and> p 0 = s) 0 = s\"\n    and \"(\\<lambda>s\\<in>{..<t}. S (SOME p. p\\<in>cube 1 t \\<and> p 0 = s)) s =\n    (\\<lambda>s\\<in>{..<t}. S (SOME p. p\\<in>cube 1 t \\<and> p 0 = s)) ((SOME p. p \\<in> cube 1 t\n    \\<and> p 0 = s) 0)\"\n    and \"(SOME p. p \\<in> cube 1 t \\<and> p 0 = s) \\<in> cube 1 t\"\nproof -\n  show 1: \"\\<exists>p \\<in> cube 1 t. p 0 = s\" using assms unfolding cube_def by (simp add: fun_ex)\n  show 2: \"(SOME p. p \\<in> cube 1 t \\<and> p 0 = s) 0 = s\" using assms 1 someI_ex[of \"\\<lambda>x. x\n  \\<in> cube 1 t \\<and> x 0 = s\"] by blast \n  show 3: \"(\\<lambda>s\\<in>{..<t}. S (SOME p. p\\<in>cube 1 t \\<and> p 0 = s)) s =\n  (\\<lambda>s\\<in>{..<t}. S (SOME p. p\\<in>cube 1 t \\<and> p 0 = s)) ((SOME p. p \\<in> cube 1 t\n  \\<and> p 0 = s) 0)\" using 2 by simp\n  show 4: \"(SOME p. p \\<in> cube 1 t \\<and> p 0 = s) \\<in> cube 1 t\" using 1 someI_ex[of\n        \"\\<lambda>p. p \\<in> cube 1 t \\<and> p 0 = s\"] assms by blast\nqed\n\ntext \\<open>The following lemma relates $1$-dimensional subspaces to lines, thus establishing a\nbidirectional correspondence between the two together with\n\\<open>line_is_dim1_subspace\\<close>.\\<close>\nlemma dim1_subspace_is_line: \n  assumes \"t > 0\" \n    and \"is_subspace S 1 n t\" \n  shows   \"is_line (\\<lambda>s\\<in>{..<t}. S (SOME p. p\\<in>cube 1 t \\<and> p 0 = s)) n t\"\nproof-\n  define L where \"L \\<equiv> (\\<lambda>s\\<in>{..<t}. S (SOME p. p\\<in>cube 1 t \\<and> p 0 = s))\"\n  have \"{..1} = {0::nat, 1}\" by auto\n  obtain B f where Bf_props: \"disjoint_family_on B {..1::nat} \\<and> \\<Union>(B ` {..1::nat}) =\n  {..<n} \\<and> ({} \\<notin> B ` {..<1::nat}) \\<and> f \\<in> (B 1) \\<rightarrow>\\<^sub>E {..<t}\n  \\<and> S \\<in> (cube 1 t) \\<rightarrow>\\<^sub>E (cube n t) \\<and> (\\<forall>y \\<in> cube 1 t.\n  (\\<forall>i \\<in> B 1. S y i = f i) \\<and> (\\<forall>j<1. \\<forall>i \\<in> B j. (S y) i = y j))\"\n    using assms(2) unfolding is_subspace_def by auto\n  then have 1: \"B 0 \\<union> B 1 = {..<n} \\<and> B 0 \\<inter> B 1 = {}\" using dim1_subspace_elims(1,\n        2)[of B n f t S] by simp\n\n  have \"L \\<in> {..<t} \\<rightarrow>\\<^sub>E cube n t\"\n  proof\n    fix s assume a: \"s \\<in> {..<t}\"\n    then have \"L s = S (SOME p. p\\<in>cube 1 t \\<and> p 0 = s)\" unfolding L_def by simp\n    moreover have \"(SOME p. p\\<in>cube 1 t \\<and> p 0 = s) \\<in> cube 1 t\" using cube_props(1) a\n        someI_ex[of \"\\<lambda>p. p \\<in> cube 1 t \\<and> p 0 = s\"] by blast\n    moreover have \"S (SOME p. p\\<in>cube 1 t \\<and> p 0 = s) \\<in> cube n t\"\n      using assms(2) calculation(2) is_subspace_def by auto\n    ultimately show \"L s \\<in> cube n t\" by simp\n  next\n    fix s assume a: \"s \\<notin> {..<t}\"\n    then show \"L s = undefined\" unfolding L_def by simp\n  qed\n  moreover have \"(\\<forall>x<t. \\<forall>y<t. L x j = L y j) \\<or> (\\<forall>s<t. L s j = s)\" if \"j < n\" for j\n  proof-\n    consider \"j \\<in> B 0\" | \"j \\<in> B 1\" using \\<open>j < n\\<close> 1 by blast \n    then show \"(\\<forall>x<t. \\<forall>y<t. L x j = L y j) \\<or> (\\<forall>s<t. L s j = s)\"\n    proof (cases)\n      case 1\n      have \"L s j = s\" if \"s < t\" for s\n      proof-\n        have \"\\<forall>y \\<in> cube 1 t. (S y) j = y 0\" using Bf_props 1 by simp\n        then show \"L s j = s\" using that cube_props(2,4)  unfolding L_def by auto\n      qed\n      then show ?thesis by blast\n    next\n      case 2\n      have \"L x j = L y j\" if \"x < t\" and \"y < t\" for x y\n      proof-\n        have *: \"S y j = f j\" if \"y \\<in> cube 1 t\" for y using 2 that Bf_props by simp\n        then have \"L y j = f j\" using that(2) cube_props(2,4) lessThan_iff restrict_apply unfolding L_def by fastforce\n        moreover from * have \"L x j = f j\" using that(1) cube_props(2,4) lessThan_iff restrict_apply unfolding L_def \n          by fastforce\n        ultimately show \"L x j = L y j\" by simp\n      qed\n      then show ?thesis by blast\n    qed\n  qed\n  moreover have \"(\\<exists>j<n. \\<forall>s<t. (L s j = s))\"\n  proof -\n    obtain j where j_prop: \"j \\<in> B 0 \\<and> j < n\" using Bf_props by blast\n    then have \"(S y) j = y 0\" if \"y \\<in> cube 1 t\" for y using that Bf_props by auto\n    then have \"L s j = s\" if \"s < t\" for s using that cube_props(2,4) unfolding L_def by auto\n    then show \"\\<exists>j<n. \\<forall>s<t. (L s j = s)\" using j_prop by blast\n  qed\n  ultimately show \"is_line (\\<lambda>s\\<in>{..<t}. S (SOME p. p\\<in>cube 1 t \\<and> p 0 = s)) n t\" \n    unfolding L_def is_line_def by auto\nqed\n\nlemma bij_unique_inv: \n  assumes \"bij_betw f A B\"  \n    and \"x \\<in> B\"\n  shows \"\\<exists>!y \\<in> A. (the_inv_into A f) x = y\" \n  using assms unfolding bij_betw_def inj_on_def the_inv_into_def \n  by blast\n\nlemma inv_into_cube_props:\n  assumes \"s < t\"\n  shows \"the_inv_into (cube 1 t) (\\<lambda>f. f 0) s \\<in> cube 1 t\" \n    and \"the_inv_into (cube 1 t) (\\<lambda>f. f 0) s 0 = s\"\n  using assms bij_unique_inv one_dim_cube_eq_nat_set f_the_inv_into_f_bij_betw\n  by fastforce+\n\nlemma some_inv_into: \n  assumes \"s < t\" \n  shows \"(SOME p. p\\<in>cube 1 t \\<and> p 0 = s) = (the_inv_into (cube 1 t) (\\<lambda>f. f 0) s)\"\n  using inv_into_cube_props[of s t] one_dim_cube_eq_nat_set[of t] assms unfolding bij_betw_def inj_on_def by auto\n\nlemma some_inv_into_2: \n  assumes \"s < t\" \n  shows \"(SOME p. p\\<in>cube 1 (t+1) \\<and> p 0 = s) = (the_inv_into (cube 1 t) (\\<lambda>f. f 0) s)\"\nproof-\n  have *: \"(SOME p. p\\<in>cube 1 (t+1) \\<and> p 0 = s) \\<in> cube 1 (t+1)\" using cube_props assms by simp\n  then have \"(SOME p. p\\<in>cube 1 (t+1) \\<and> p 0 = s) 0 = s\" using cube_props assms by simp\n  moreover\n  {\n    have \"(SOME p. p\\<in>cube 1 (t+1) \\<and> p 0 = s) ` {..<1} \\<subseteq> {..<t}\" using calculation assms by force\n    then have \"(SOME p. p\\<in>cube 1 (t+1) \\<and> p 0 = s) \\<in> cube 1 t\" using * unfolding cube_def by auto  \n  }\n  moreover have \"inj_on (\\<lambda>f. f 0) (cube 1 t)\" using one_dim_cube_eq_nat_set[of t] \n    unfolding bij_betw_def inj_on_def by auto \n  ultimately show \"(SOME p. p\\<in>cube 1 (t+1) \\<and> p 0 = s) = (the_inv_into (cube 1 t) (\\<lambda>f. f 0) s)\" \n    using the_inv_into_f_eq [of \"\\<lambda>f. f 0\" \"cube 1 t\" \"(SOME p. p\\<in>cube 1 (t+1) \\<and> p 0 = s)\" s] by auto\nqed\n\nlemma dim1_layered_subspace_as_line:\n  assumes \"t > 0\"\n    and \"layered_subspace S 1 n t r \\<chi>\"\n  shows \"\\<exists>c1 c2. c1<r \\<and> c2<r \\<and> (\\<forall>s<t. \\<chi> (S (SOME p. p\\<in>cube 1\n  (t+1) \\<and> p 0 = s)) = c1) \\<and> \\<chi> (S (SOME p. p\\<in>cube 1 (t+1) \\<and> p 0 = t)) = c2\"\nproof -\n  have \"x u < t\" if \"x \\<in> classes 1 t 0\" and \"u < 1\" for x u \n  proof -\n    have \"x \\<in> cube 1 (t+1)\" using that unfolding classes_def by blast\n    then have \"x u \\<in> {..<t+1}\" using that unfolding cube_def by blast\n    then have \"x u \\<in> {..<t}\" using that\n      using that less_Suc_eq unfolding classes_def by auto\n    then show \"x u < t\" by simp\n  qed\n  then have \"classes 1 t 0 \\<subseteq> cube 1 t\" unfolding cube_def classes_def by auto\n  moreover have \"cube 1 t \\<subseteq> classes 1 t 0\" using cube_subset[of 1 t] unfolding cube_def classes_def by auto\n  ultimately have X: \"classes 1 t 0 = cube 1 t\" by blast\n\n  obtain c1 where c1_prop: \"c1 < r \\<and> (\\<forall>x\\<in>classes 1 t 0. \\<chi> (S x) = c1)\" using assms(2) \n    unfolding layered_subspace_def by blast\n  then have \"(\\<chi> (S x) = c1)\" if \"x \\<in> cube 1 t\" for x using X that by blast\n  then have \"\\<chi> (S (the_inv_into (cube 1 t) (\\<lambda>f. f 0) s)) = c1\" if \"s < t\" for s \n    using one_dim_cube_eq_nat_set[of t] by (meson that bij_betwE bij_betw_the_inv_into lessThan_iff)\n  then have K1: \"\\<chi> (S (SOME p. p\\<in>cube 1 (t+1) \\<and> p 0 = s)) = c1\" if \"s < t\" for s \n    using that some_inv_into_2 by simp\n\n  have *: \"\\<exists>c<r. \\<forall>x \\<in> classes 1 t 1. \\<chi> (S x) = c\" \n    using assms(2) unfolding layered_subspace_def by blast\n\n  have \"x 0 = t\" if \"x \\<in> classes 1 t 1\" for x using that unfolding classes_def by simp\n  moreover have \"\\<exists>!x \\<in> cube 1 (t+1). x 0 = t\" using one_dim_cube_eq_nat_set[of \"t+1\"] \n    unfolding bij_betw_def inj_on_def using inv_into_cube_props(1) inv_into_cube_props(2) by force \n  moreover have **: \"\\<exists>!x. x  \\<in> classes 1 t 1\" unfolding classes_def using calculation(2) by simp\n  ultimately have \"the_inv_into (cube 1 (t+1)) (\\<lambda>f. f 0) t \\<in> classes 1 t 1\" \n    using inv_into_cube_props[of t \"t+1\"] unfolding classes_def by simp\n\n  then have \"\\<exists>c2. c2 < r \\<and> \\<chi> (S (the_inv_into (cube 1 (t+1)) (\\<lambda>f. f 0) t)) = c2\" \n    using * ** by blast\n  then have K2: \"\\<exists>c2. c2 < r \\<and> \\<chi> (S (SOME p. p\\<in>cube 1 (t+1) \\<and> p 0 = t)) = c2\" \n    using some_inv_into by simp\n\n  from K1 K2 show ?thesis \n    using c1_prop by blast\nqed\n\nlemma dim1_layered_subspace_mono_line: \n  assumes \"t > 0\" \n    and \"layered_subspace S 1 n t r \\<chi>\"\n  shows \"\\<forall>s<t. \\<forall>l<t.  \\<chi> (S (SOME p. p\\<in>cube 1 (t+1) \\<and> p 0 = s)) =\n  \\<chi> (S (SOME p. p\\<in>cube 1 (t+1) \\<and> p 0 = l)) \\<and>  \\<chi> (S (SOME p. p\\<in>cube 1\n  (t+1) \\<and> p 0 = s)) < r\"\n  using dim1_layered_subspace_as_line[of t S n r \\<chi>] assms by auto  \n\ndefinition join :: \"(nat \\<Rightarrow> 'a) \\<Rightarrow> (nat \\<Rightarrow> 'a) \\<Rightarrow> nat\n\\<Rightarrow> nat \\<Rightarrow> (nat \\<Rightarrow> 'a)\"\n  where\n    \"join f g n m \\<equiv> (\\<lambda>x. if x \\<in> {..<n} then f x else (if x \\<in> {n..<n+m} then g\n    (x - n) else undefined))\"\n\nlemma join_cubes: \n  assumes \"f \\<in> cube n (t+1)\" \n    and \"g \\<in> cube m (t+1)\"\n  shows \"join f g n m \\<in> cube (n+m) (t+1)\"\nproof (unfold cube_def; intro PiE_I)\n  fix i\n  assume \"i \\<in> {..<n+m}\"\n  then consider \"i < n\" | \"i \\<ge> n \\<and> i < n+m\" by fastforce\n  then show \"join f g n m i \\<in> {..<t + 1}\"\n  proof (cases)\n    case 1\n    then have \"join f g n m i = f i\" unfolding join_def by simp\n    moreover have \"f i \\<in> {..<t+1}\" using assms(1) 1 unfolding cube_def by blast\n    ultimately show ?thesis by simp\n  next\n    case 2\n    then have \"join f g n m i = g (i - n)\" unfolding join_def by simp\n    moreover have \"i - n \\<in> {..<m}\" using 2 by auto\n    moreover have \"g (i - n) \\<in> {..<t+1}\" using calculation(2) assms(2) unfolding cube_def by blast\n    ultimately show ?thesis by simp\n  qed\nnext\n  fix i\n  assume \"i \\<notin> {..<n+m}\"\n  then show \"join f g n m i = undefined\" unfolding join_def by simp\nqed\n\nlemma subspace_elems_embed: \n  assumes \"is_subspace S k n t\"\n  shows \"S ` (cube k t) \\<subseteq> cube n t\"\n  using assms unfolding cube_def is_subspace_def by blast\n\n\nsection \\<open>Core proofs\\<close>\ntext\\<open>The numbering of the theorems has been borrowed from the textbook~\\<^cite>\\<open>\"thebook\"\\<close>.\\<close>\n\nsubsection \\<open>Theorem 4\\<close>\nsubsubsection \\<open>Base case of Theorem 4\\<close>\nlemma hj_imp_lhj_base: \n  fixes r t\n  assumes \"t > 0\"\n    and \"\\<And>r'. hj r' t\" \n  shows \"lhj r t 1\"\nproof-\n  from assms(2) obtain N where N_def: \"N > 0 \\<and> (\\<forall>N' \\<ge> N. \\<forall>\\<chi>. \\<chi>\n  \\<in> (cube N' t) \\<rightarrow>\\<^sub>E {..<r::nat} \\<longrightarrow> (\\<exists>L. \\<exists>c<r.\n  is_line L N' t \\<and> (\\<forall>y \\<in> L ` {..<t}. \\<chi> y = c)))\" unfolding hj_def by blast\n\n  have \"(\\<exists>S. is_subspace S 1 N' (t + 1) \\<and> (\\<forall>i \\<in> {..1}. \\<exists>c < r.\n  (\\<forall>x \\<in> classes 1 t i. \\<chi> (S x) = c)))\" if asm: \"N' \\<ge> N\" \"\\<chi> \\<in> (cube N'\n  (t + 1)) \\<rightarrow>\\<^sub>E {..<r::nat}\" for N' \\<chi>\n  proof-\n    have N'_props: \"N' > 0 \\<and> (\\<forall>\\<chi>. \\<chi> \\<in> (cube N' t) \\<rightarrow>\\<^sub>E\n    {..<r::nat} \\<longrightarrow> (\\<exists>L. \\<exists>c<r. is_line L N' t \\<and> (\\<forall>y \\<in>\n    L ` {..<t}. \\<chi> y = c)))\" using asm N_def by simp\n    let ?chi_t = \"\\<lambda>x \\<in> cube N' t. \\<chi> x\"\n    have \"?chi_t \\<in> cube N' t \\<rightarrow>\\<^sub>E {..<r::nat}\" using cube_subset asm by auto\n    then obtain L where L_def: \"is_line L N' t \\<and> (\\<exists>c<r.  (\\<forall>y \\<in> L ` {..<t}. ?chi_t y = c))\" \n      using N'_props by blast\n\n    have \"is_subspace (restrict (\\<lambda>y. L (y 0)) (cube 1 t)) 1 N' t\" using line_is_dim1_subspace N'_props L_def \n      using assms(1) by auto \n    then obtain B f where Bf_defs: \"disjoint_family_on B {..1} \\<and> \\<Union>(B ` {..1}) = {..<N'}\n    \\<and> ({} \\<notin> B ` {..<1}) \\<and> f \\<in> (B 1) \\<rightarrow>\\<^sub>E {..<t} \\<and>\n    (restrict (\\<lambda>y. L (y 0)) (cube 1 t)) \\<in> (cube 1 t) \\<rightarrow>\\<^sub>E (cube N' t)\n    \\<and> (\\<forall>y \\<in> cube 1 t. (\\<forall>i \\<in> B 1. (restrict (\\<lambda>y. L (y 0)) (cube\n    1 t)) y i = f i) \\<and> (\\<forall>j<1. \\<forall>i \\<in> B j. ((restrict (\\<lambda>y. L (y 0))\n    (cube 1 t)) y) i = y j))\" unfolding is_subspace_def by auto \n\n    have \"{..1::nat} = {0, 1}\" by auto\n    then have B_props: \"B 0 \\<union> B 1 = {..<N'} \\<and> (B 0 \\<inter> B 1 = {})\" \n      using Bf_defs unfolding disjoint_family_on_def by auto\n    define L' where \"L' \\<equiv> L(t:=(\\<lambda>j. if j \\<in> B 1 then L (t - 1) j else (if j \\<in>\n    B 0 then t else undefined)))\"\n    text \\<open>\\<open>S1\\<close> is the corresponding $1$-dimensional subspace of \\<open>L'\\<close>.\\<close>\n    define S1 where \"S1 \\<equiv> restrict (\\<lambda>y. L' (y (0::nat))) (cube 1 (t+1))\"\n    have line_prop: \"is_line L' N' (t + 1)\"\n    proof-\n      have A1: \"L' \\<in> {..<t+1} \\<rightarrow>\\<^sub>E cube N' (t + 1)\" \n      proof\n        fix x\n        assume asm: \"x \\<in> {..<t + 1}\"\n        then show \"L' x \\<in> cube N' (t + 1)\"\n        proof (cases \"x < t\")\n          case True\n          then have \"L' x = L x\" by (simp add: L'_def)\n          then have \"L' x \\<in> cube N' t\" using L_def True unfolding is_line_def by auto\n          then show \"L' x \\<in> cube N' (t + 1)\" using cube_subset by blast\n        next\n          case False\n          then have \"x = t\" using asm by simp\n          show \"L' x \\<in> cube N' (t + 1)\"\n          proof(unfold cube_def, intro PiE_I)\n            fix j\n            assume \"j \\<in> {..<N'}\"\n            have \"j \\<in> B 1 \\<or> j \\<in> B 0 \\<or> j \\<notin> (B 0 \\<union> B 1)\" by blast\n            then show \"L' x j \\<in> {..<t + 1}\"\n            proof (elim disjE)\n              assume \"j \\<in> B 1\"\n              then have \"L' x j = L (t - 1) j\" \n                by (simp add: \\<open>x = t\\<close> L'_def)\n              have \"L (t - 1) \\<in> cube N' t\" using line_points_in_cube L_def \n                by (meson assms(1) diff_less less_numeral_extra(1))\n              then have \"L (t - 1) j < t\" using \\<open>j \\<in> {..<N'}\\<close> unfolding cube_def by auto \n              then show \"L' x j \\<in> {..<t + 1}\" using \\<open>L' x j = L (t - 1) j\\<close> by simp\n            next\n              assume \"j \\<in> B 0\"\n              then have \"j \\<notin> B 1\" using Bf_defs unfolding disjoint_family_on_def by auto\n              then have \"L' x j = t\"  by (simp add: \\<open>j \\<in> B 0\\<close> \\<open>x = t\\<close> L'_def)\n              then show \"L' x j \\<in> {..<t + 1}\" by simp\n            next\n              assume a: \"j \\<notin> (B 0 \\<union> B 1)\"\n              have \"{..1::nat} = {0, 1}\" by auto\n              then have \"B 0 \\<union> B 1 = (\\<Union>(B ` {..1::nat}))\" by simp\n              then have \"B 0 \\<union> B 1 = {..<N'}\" using Bf_defs unfolding partition_on_def by simp\n              then have \"\\<not>(j \\<in> {..<N'})\" using a by simp\n              then have False using \\<open>j \\<in> {..<N'}\\<close> by simp\n              then show ?thesis by simp\n            qed\n          next\n            fix j \n            assume \"j \\<notin> {..<N'}\"\n            then have \"j \\<notin> (B 0) \\<and> j \\<notin> B 1\" using Bf_defs unfolding partition_on_def by auto\n            then show \"L' x j = undefined\" using \\<open>x = t\\<close> by (simp add: L'_def)\n          qed\n        qed\n      next\n        fix x\n        assume asm: \"x \\<notin> {..<t+1}\" \n        then have \"x \\<notin> {..<t} \\<and> x \\<noteq> t\" by simp\n        then show \"L' x = undefined\" using L_def unfolding L'_def is_line_def by auto\n      qed\n      have A2: \"(\\<exists>j<N'. (\\<forall>s < (t + 1). L' s j = s))\"\n      proof (cases \"t = 1\")\n        case True\n        obtain j where j_prop: \"j \\<in> B 0 \\<and> j < N'\" using Bf_defs by blast\n        then have \"L' s j = L s j\" if \"s < t\" for s using that by (auto simp: L'_def)\n        moreover have \"L s j = 0\" if \"s < t\" for s  using that True L_def j_prop line_points_in_cube_unfolded[of L N' t]\n          by simp\n        moreover have \"L' s j = s\" if \"s < t\" for s using True calculation that by simp\n        moreover have \"L' t j = t\" using j_prop B_props by (auto simp: L'_def)\n        ultimately show ?thesis unfolding L'_def using j_prop by auto\n      next\n        case False\n        then show ?thesis\n        proof-\n          have \"(\\<exists>j<N'. (\\<forall>s < t. L' s j = s))\" using L_def unfolding is_line_def by (auto simp: L'_def)\n          then obtain j where j_def: \"j < N' \\<and> (\\<forall>s < t. L' s j = s)\" by blast\n          have \"j \\<notin> B 1\"\n          proof \n            assume a:\"j \\<in> B 1\"\n            then have \"(restrict (\\<lambda>y. L (y 0)) (cube 1 t)) y j = f j\" if \"y \\<in> cube 1 t\" for y \n              using Bf_defs that by simp\n            then have \"L (y 0) j = f j\" if \"y \\<in> cube 1 t\" for y using that by simp\n            moreover have \"\\<exists>!i. i < t \\<and> y 0 = i\" if \"y \\<in> cube 1 t\" for y \n              using that one_dim_cube_eq_nat_set[of \"t\"] unfolding bij_betw_def by blast\n            moreover have \"\\<exists>!y. y \\<in> cube 1 t \\<and> y 0 = i\" if \"i < t\" for i \n            proof (intro ex1I_alt)\n              define y where \"y \\<equiv> (\\<lambda>x::nat. \\<lambda>y\\<in>{..<1::nat}. x)\" \n              have \"y i \\<in> (cube 1 t)\" using that unfolding cube_def y_def by simp\n              moreover have \"y i 0 = i\" unfolding y_def by simp\n              moreover have \"z = y i\" if \"z \\<in> cube 1 t\" and \"z 0 = i\" for z\n              proof (rule ccontr)\n                assume \"z \\<noteq> y i\" \n                then obtain l where l_prop: \"z l \\<noteq> y i l\" by blast\n                consider \"l \\<in> {..<1::nat}\" | \"l \\<notin> {..<1::nat}\" by blast\n                then show False\n                proof cases\n                  case 1\n                  then show ?thesis using l_prop that(2) unfolding y_def by auto\n                next\n                  case 2\n                  then have \"z l = undefined\" using that unfolding cube_def by blast\n                  moreover have \"y i l = undefined\" unfolding y_def using 2 by auto\n                  ultimately show ?thesis using l_prop by presburger\n                qed\n              qed\n              ultimately show \"\\<exists>y. (y \\<in> cube 1 t \\<and> y 0 = i) \\<and> (\\<forall>ya. ya\n              \\<in> cube 1 t \\<and> ya 0 = i \\<longrightarrow> y = ya)\" by blast\n            qed\n\n            moreover have \"L i j = f j\" if \"i < t\" for i using that calculation by blast\n            moreover have \"(\\<exists>j<N'. (\\<forall>s < t. L s j = s))\" using\n                \\<open>(\\<exists>j<N'. (\\<forall>s < t. L' s j = s))\\<close> by (auto simp: L'_def)\n            ultimately show False using False\n              by (metis (no_types, lifting) L'_def assms(1) fun_upd_apply j_def less_one nat_neq_iff)\n          qed\n          then have \"j \\<in> B 0\" using \\<open>j \\<notin> B 1\\<close> j_def B_props by auto\n\n          then have \"L' t j = t\" using \\<open>j \\<notin> B 1\\<close> by (auto simp: L'_def)\n          then have \"L' s j = s\" if \"s < t + 1\" for s using j_def that by (auto simp: L'_def)\n          then show ?thesis using j_def by blast\n        qed\n      qed\n      have A3: \"(\\<forall>x<t+1. \\<forall>y<t+1. L' x j =  L' y j) \\<or> (\\<forall>s<t+1. L' s j = s)\" if \"j < N'\" for j \n      proof-\n        consider \"j \\<in> B 1\" | \"j \\<in> B 0\" using \\<open>j < N'\\<close> B_props by auto\n        then show \"(\\<forall>x<t+1. \\<forall>y<t+1. L' x j =  L' y j) \\<or> (\\<forall>s<t+1. L' s j = s)\"\n        proof (cases)\n          case 1\n          then have \"(restrict (\\<lambda>y. L (y 0)) (cube 1 t)) y j = f j\" if \"y \\<in> cube 1 t\" for y \n            using that Bf_defs by simp\n          moreover have \"\\<exists>!i. i < t \\<and> y 0 = i\" if \"y \\<in> cube 1 t\" for y \n            using that one_dim_cube_eq_nat_set[of \"t\"] unfolding bij_betw_def by blast\n          moreover have \"\\<exists>!y. y \\<in> cube 1 t \\<and> y 0 = i\" if \"i < t\" for i \n          proof (intro ex1I_alt)\n            define y where \"y \\<equiv> (\\<lambda>x::nat. \\<lambda>y\\<in>{..<1::nat}. x)\" \n            have \"y i \\<in> (cube 1 t)\" using that unfolding cube_def y_def by simp\n            moreover have \"y i 0 = i\" unfolding y_def by auto\n            moreover have \"z = y i\" if \"z \\<in> cube 1 t\" and \"z 0 = i\" for z\n            proof (rule ccontr)\n              assume \"z \\<noteq> y i\" \n              then obtain l where l_prop: \"z l \\<noteq> y i l\" by blast\n              consider \"l \\<in> {..<1::nat}\" | \"l \\<notin> {..<1::nat}\" by blast\n              then show False\n              proof cases\n                case 1\n                then show ?thesis using l_prop that(2) unfolding y_def by auto\n              next\n                case 2\n                then have \"z l = undefined\" using that unfolding cube_def by blast\n                moreover have \"y i l = undefined\" unfolding y_def using 2 by auto\n                ultimately show ?thesis using l_prop by presburger\n              qed\n            qed\n            ultimately show \"\\<exists>y. (y \\<in> cube 1 t \\<and> y 0 = i) \\<and> (\\<forall>ya. ya\n            \\<in> cube 1 t \\<and> ya 0 = i \\<longrightarrow> y = ya)\" by blast\n\n          qed\n          moreover have \"L i j = f j\" if \"i < t\" for i using calculation that by force\n          moreover have  \"L i j = L x j\" if \"x < t\" \"i < t\" for x i using that calculation by simp\n          moreover have \"L' x j = L x j\" if \"x < t\" for x using that fun_upd_other[of x t L\n                \"\\<lambda>j. if j \\<in> B 1 then L (t - 1) j else if j \\<in> B 0 then t else undefined\"]\n            unfolding L'_def by simp\n          ultimately have *: \"L' x j = L' y j\" if \"x < t\" \"y < t\" for x y using that by presburger\n\n          have \"L' t j = L' (t - 1) j\" using \\<open>j \\<in> B 1\\<close> by (auto simp: L'_def)\n          also have \"... = L' x j\" if \"x < t\" for x using * by (simp add: assms(1) that)\n          finally have **: \"L' t j = L' x j\" if \"x < t\" for x using that by auto\n          have \"L' x j = L' y j\" if \"x < t + 1\" \"y < t + 1\" for x y \n          proof-\n            consider \"x < t \\<and> y = t\" | \"y < t \\<and> x = t\" | \"x = t \\<and> y = t\" | \"x < t \\<and> y < t\" \n              using \\<open>x < t + 1\\<close> \\<open>y < t + 1\\<close> by linarith\n            then show \"L' x j = L' y j\" \n            proof cases\n              case 1\n              then show ?thesis using ** by auto\n            next\n              case 2\n              then show ?thesis using ** by auto\n            next\n              case 3\n              then show ?thesis by simp\n            next\n              case 4\n              then show ?thesis using * by auto\n            qed\n          qed\n          then show ?thesis by blast\n        next\n          case 2\n          then have \"\\<forall>y \\<in> cube 1 t. ((restrict (\\<lambda>y. L (y 0)) (cube 1 t)) y) j = y 0\" \n            using \\<open>j \\<in> B 0\\<close> Bf_defs by auto\n          then have \"\\<forall>y \\<in> cube 1 t. L (y 0) j = y 0\"  by auto\n          moreover have \"\\<exists>!y. y \\<in> cube 1 t \\<and> y 0 = i\" if \"i < t\" for i \n          proof (intro ex1I_alt)\n            define y where \"y \\<equiv> (\\<lambda>x::nat. \\<lambda>y\\<in>{..<1::nat}. x)\" \n            have \"y i \\<in> (cube 1 t)\" using that unfolding cube_def y_def by simp\n            moreover have \"y i 0 = i\" unfolding y_def by auto\n            moreover have \"z = y i\" if \"z \\<in> cube 1 t\" and \"z 0 = i\" for z\n            proof (rule ccontr)\n              assume \"z \\<noteq> y i\" \n              then obtain l where l_prop: \"z l \\<noteq> y i l\" by blast\n              consider \"l \\<in> {..<1::nat}\" | \"l \\<notin> {..<1::nat}\" by blast\n              then show False\n              proof cases\n                case 1\n                then show ?thesis using l_prop that(2) unfolding y_def by auto\n              next\n                case 2\n                then have \"z l = undefined\" using that unfolding cube_def by blast\n                moreover have \"y i l = undefined\" unfolding y_def using 2 by auto\n                ultimately show ?thesis using l_prop by presburger\n              qed\n            qed\n            ultimately show \"\\<exists>y. (y \\<in> cube 1 t \\<and> y 0 = i) \\<and> (\\<forall>ya. ya\n            \\<in> cube 1 t \\<and> ya 0 = i \\<longrightarrow> y = ya)\" by blast\n\n          qed\n          ultimately have \"L s j = s\" if \"s < t\" for s using that by blast\n          then have \"L' s j = s\" if \"s < t\" for s using that by (auto simp: L'_def)\n          moreover have \"L' t j = t\" using 2 B_props by (auto simp: L'_def)\n          ultimately have \"L' s j = s\" if \"s < t+1\" for s using that by (auto simp: L'_def)\n          then show ?thesis by blast\n        qed\n      qed\n      from A1 A2 A3 show ?thesis unfolding is_line_def by simp\n    qed\n    then have F1: \"is_subspace S1 1 N' (t + 1)\" unfolding S1_def \n      using line_is_dim1_subspace[of \"N'\" \"t+1\"] N'_props assms(1) by force\n    moreover have F2: \"\\<exists>c < r. (\\<forall>x \\<in> classes 1 t i. \\<chi> (S1 x) = c)\" if \"i \\<le> 1\" for i\n    proof-\n      have \"\\<exists>c < r. (\\<forall>y \\<in> L' ` {..<t}. ?chi_t y = c)\" unfolding L'_def using L_def by fastforce\n      have \"\\<forall>x \\<in> (L ` {..<t}). x \\<in> cube N' t\" using L_def \n        using line_points_in_cube by blast\n      then have \"\\<forall>x \\<in> (L' ` {..<t}). x \\<in> cube N' t\" by (auto simp: L'_def)\n      then have *:\"\\<forall>x \\<in> (L' ` {..<t}). \\<chi> x = ?chi_t x\" by simp\n      then have \"?chi_t ` (L' ` {..<t}) = \\<chi> ` (L' ` {..<t})\" by force\n      then have \"\\<exists>c < r. (\\<forall>y \\<in> L' ` {..<t}. \\<chi> y = c)\" using\n          \\<open>\\<exists>c < r. (\\<forall>y \\<in> L' ` {..<t}. ?chi_t y = c)\\<close> by fastforce\n      then obtain linecol where lc_def: \"linecol < r \\<and> (\\<forall>y \\<in> L' ` {..<t}. \\<chi> y = linecol)\" by blast\n      consider \"i = 0\" | \"i = 1\" using \\<open>i \\<le> 1\\<close> by linarith\n      then show \"\\<exists>c < r. (\\<forall>x \\<in> classes 1 t i. \\<chi> (S1 x) = c)\"\n      proof (cases)\n        case 1\n        assume \"i = 0\"\n        have *: \"\\<forall>a t. a \\<in> {..<t+1} \\<and> a \\<noteq> t \\<longleftrightarrow> a \\<in> {..<(t::nat)}\" by auto\n        from \\<open>i = 0\\<close> have \"classes 1 t 0 = {x . x \\<in> (cube 1 (t + 1)) \\<and>\n        (\\<forall>u \\<in> {((1::nat) - 0)..<1}. x u = t) \\<and> t \\<notin> x ` {..<(1 - (0::nat))}}\"\n          using classes_def by simp\n        also have \"... = {x . x \\<in> cube 1 (t+1) \\<and> t \\<notin> x ` {..<(1::nat)}}\" by simp\n        also have \"... = {x . x \\<in> cube 1 (t+1) \\<and> (x 0 \\<noteq> t)}\" by blast \n        also have \" ... = {x . x \\<in> cube 1 (t+1) \\<and> (x 0 \\<in> {..<t+1} \\<and> x 0 \\<noteq> t)}\" \n          unfolding cube_def by blast\n        also have \" ... = {x . x \\<in> cube 1 (t+1) \\<and> (x 0 \\<in> {..<t})}\" using * by simp\n        finally have redef: \"classes 1 t 0 = {x . x \\<in> cube 1 (t+1) \\<and> (x 0 \\<in> {..<t})}\" by simp\n        have \"{x 0 | x . x \\<in> classes 1 t 0} \\<subseteq> {..<t}\" using redef by auto\n        moreover have \"{..<t} \\<subseteq> {x 0 | x . x \\<in> classes 1 t 0}\" \n        proof\n          fix x assume x: \"x \\<in> {..<t}\"\n          hence \"\\<exists>a\\<in>cube 1 t. a 0 = x\"\n            unfolding cube_def by (intro fun_ex) auto\n          then show \"x \\<in> {x 0 |x. x \\<in> classes 1 t 0}\"\n            using x cube_subset unfolding redef by auto\n        qed\n        ultimately have **: \"{x 0 | x . x \\<in> classes 1 t 0} = {..<t}\" by blast\n\n        have \"\\<chi> (S1 x) = linecol\" if \"x \\<in> classes 1 t 0\" for x\n        proof-\n          have \"x \\<in> cube 1 (t+1)\" unfolding classes_def using that redef by blast\n          then have \"S1 x = L' (x 0)\" unfolding S1_def by simp\n          moreover have \"x 0 \\<in> {..<t}\" using ** using \\<open>x \\<in> classes 1 t 0\\<close> by blast\n          ultimately show \"\\<chi> (S1 x) = linecol\" using lc_def using fun_upd_triv image_eqI by blast\n        qed\n        then show ?thesis using lc_def \\<open>i = 0\\<close> by auto\n      next\n        case 2 \n        assume \"i = 1\"\n        have \"classes 1 t 1 = {x . x \\<in> (cube 1 (t + 1)) \\<and> (\\<forall>u \\<in> {0::nat..<1}. x\n        u = t) \\<and> t \\<notin> x ` {..<0}}\" unfolding classes_def by simp\n        also have \" ... = {x . x \\<in> cube 1 (t+1) \\<and> (\\<forall>u \\<in> {0}. x u = t)}\" by simp\n        finally have redef: \"classes 1 t 1 = {x . x \\<in> cube 1 (t+1) \\<and> (x 0 = t)}\" by auto\n        have \"\\<forall>s \\<in> {..<t+1}. \\<exists>!x \\<in> cube 1 (t+1). (\\<lambda>p.\n        \\<lambda>y\\<in>{..<1::nat}. p) s = x\" using nat_set_eq_one_dim_cube[of \"t+1\"] \n          unfolding bij_betw_def by blast\n        then have \"\\<exists>!x \\<in>cube 1 (t+1). (\\<lambda>p. \\<lambda>y\\<in>{..<1::nat}. p) t = x\" by auto\n        then obtain x where x_prop: \"x \\<in> cube 1 (t+1)\" and \"(\\<lambda>p.\n        \\<lambda>y\\<in>{..<1::nat}. p) t = x\" and \"\\<forall>z \\<in> cube 1 (t+1). (\\<lambda>p.\n        \\<lambda>y\\<in>{..<1::nat}. p) t = z \\<longrightarrow> z = x\" by blast\n        then have \"(\\<lambda>p. \\<lambda>y\\<in>{0}. p)  t  = x \\<and> (\\<forall>z \\<in> cube 1\n        (t+1). (\\<lambda>p. \\<lambda>y\\<in>{0}. p) t = z \\<longrightarrow> z = x)\"  by force\n        then have *:\"((\\<lambda>p. \\<lambda>y\\<in>{0}. p) t) 0  = x 0 \\<and> (\\<forall>z \\<in> cube\n        1 (t+1). (\\<lambda>p. \\<lambda>y\\<in>{0}. p) t  = z  \\<longrightarrow> z = x)\"  \n          using x_prop by force\n\n        then have \"\\<exists>!y \\<in> cube 1 (t + 1). y 0 = t\" \n        proof (intro ex1I_alt)\n          define y where \"y \\<equiv> (\\<lambda>x::nat. \\<lambda>y\\<in>{..<1::nat}. x)\" \n          have \"y t \\<in> (cube 1 (t + 1))\" unfolding cube_def y_def by simp \n          moreover have \"y t 0 = t\" unfolding y_def by auto\n          moreover have \"z = y t\" if \"z \\<in> cube 1 (t + 1)\" and \"z 0 = t\" for z\n          proof (rule ccontr)\n            assume \"z \\<noteq> y t\" \n            then obtain l where l_prop: \"z l \\<noteq> y t l\" by blast\n            consider \"l \\<in> {..<1::nat}\" | \"l \\<notin> {..<1::nat}\" by blast\n            then show False\n            proof cases\n              case 1\n              then show ?thesis using l_prop that(2) unfolding y_def by auto\n            next\n              case 2\n              then have \"z l = undefined\" using that unfolding cube_def by blast\n              moreover have \"y t l = undefined\" unfolding y_def using 2 by auto\n              ultimately show ?thesis using l_prop by presburger\n            qed\n          qed\n          ultimately show \"\\<exists>y. (y \\<in> cube 1 (t + 1) \\<and> y 0 = t) \\<and> (\\<forall>ya.\n          ya \\<in> cube 1 (t + 1) \\<and> ya 0 = t \\<longrightarrow> y = ya)\" by blast\n        qed\n        then have \"\\<exists>!x \\<in> classes 1 t 1. True\" using redef by simp\n        then obtain x where x_def: \"x \\<in> classes 1 t 1 \\<and> (\\<forall>y \\<in> classes 1 t 1. x = y)\" by auto\n\n        have \"\\<chi> (S1 y) < r\" if \"y \\<in> classes 1 t 1\" for y\n        proof-\n          have \"y = x\" using x_def that by auto\n          then have \"\\<chi> (S1 y) = \\<chi> (S1 x)\" by auto\n          moreover have \"S1 x \\<in> cube N' (t+1)\" unfolding S1_def is_line_def \n            using line_prop line_points_in_cube redef x_def by fastforce\n          ultimately show \"\\<chi> (S1 y) < r\" using asm unfolding cube_def by auto\n        qed\n        then show ?thesis using lc_def \\<open>i = 1\\<close> using x_def by fast\n      qed\n    qed\n    ultimately show \"(\\<exists>S. is_subspace S 1 N' (t + 1) \\<and> (\\<forall>i \\<in> {..1}.\n    \\<exists>c < r. (\\<forall>x \\<in> classes 1 t i. \\<chi> (S x) = c)))\" by blast\n  qed\n  then show ?thesis using N_def unfolding layered_subspace_def lhj_def by auto\nqed\n\nsubsubsection \\<open>Induction step of theorem 4\\<close>\ntext \\<open>The proof has four parts:\n\\begin{enumerate}\n\\item We obtain two layered subspaces of dimension 1 and k (respectively), whose existence is\nguaranteed by the assumption \\<^const>\\<open>lhj\\<close> (i.e.\\ the induction hypothesis).\nAdditionally, we prove some useful facts about these.\n\\item We construct a \\<open>k+1\\<close>-dimensional subspace with the goal of showing that it is layered.\n\\item We prove that our construction is a subspace in the first place.\n\\item We prove that it is a layered subspace.\n\\end{enumerate}\\<close>\n\nlemma hj_imp_lhj_step: \n  fixes   r k\n  assumes \"t > 0\"\n    and \"k \\<ge> 1\"\n    and \"True\" \n    and \"(\\<And>r k'. k' \\<le> k \\<Longrightarrow> lhj r t k')\" \n    and \"r > 0\"\n  shows   \"lhj r t (k+1)\"\nproof-\n  obtain m where m_props: \"(m > 0 \\<and> (\\<forall>M' \\<ge> m. \\<forall>\\<chi>. \\<chi> \\<in> (cube\n  M' (t + 1)) \\<rightarrow>\\<^sub>E {..<r::nat} \\<longrightarrow> (\\<exists>S. layered_subspace S k\n  M' t r \\<chi>)))\" using assms(4)[of \"k\" \"r\"] unfolding lhj_def  by blast\n  define s where \"s \\<equiv> r^((t + 1)^m)\"\n  obtain n' where n'_props: \"(n' > 0 \\<and> (\\<forall>N \\<ge> n'. \\<forall>\\<chi>. \\<chi> \\<in>\n  (cube N (t + 1)) \\<rightarrow>\\<^sub>E {..<s::nat} \\<longrightarrow> (\\<exists>S. layered_subspace\n  S 1 N t s \\<chi>)))\" using assms(2) assms(4)[of \"1\" \"s\"] unfolding lhj_def by auto \n\n  have \"(\\<exists>T. layered_subspace T (k + 1) (M') t r \\<chi>)\" if \\<chi>_prop: \"\\<chi> \\<in> cube\n  M' (t + 1) \\<rightarrow>\\<^sub>E {..<r}\" and M'_prop: \"M' \\<ge> n' + m\" for \\<chi> M'\n  proof -\n    define d where \"d \\<equiv> M' - (n' + m)\"\n    define n where \"n \\<equiv> n' + d\"\n    have \"n \\<ge> n'\" unfolding n_def d_def by simp\n    have \"n + m = M'\" unfolding n_def d_def using M'_prop by simp\n    have line_subspace_s: \"\\<exists>S. layered_subspace S 1 n t s \\<chi> \\<and> is_line\n    (\\<lambda>s\\<in>{..<t+1}. S (SOME p. p\\<in>cube 1 (t+1) \\<and> p 0 = s)) n (t+1)\" if \"\\<chi>\n    \\<in> (cube n (t + 1)) \\<rightarrow>\\<^sub>E {..<s::nat}\" for \\<chi> \n    proof-\n      have \"\\<exists>S. layered_subspace S 1 n t s \\<chi>\" using that n'_props \\<open>n \\<ge> n'\\<close> by blast\n      then obtain L where \"layered_subspace L 1 n t s \\<chi>\" by blast\n      then have \"is_subspace L 1 n (t+1)\" unfolding layered_subspace_def by simp\n      then have \"is_line (\\<lambda>s\\<in>{..<t+1}. L (SOME p. p\\<in>cube 1 (t+1) \\<and> p 0 = s)) n (t + 1)\" \n        using dim1_subspace_is_line[of \"t+1\" \"L\" \"n\"] assms(1) by simp\n      then show \"\\<exists>S. layered_subspace S 1 n t s \\<chi> \\<and> is_line (\\<lambda>s\\<in>{..<t\n      + 1}. S (SOME p. p \\<in> cube 1 (t+1) \\<and> p 0 = s)) n (t + 1)\" using\n        \\<open>layered_subspace L 1 n t s \\<chi>\\<close> by auto\n    qed\n\n    paragraph \\<open>Part 1: Obtaining the subspaces \\<open>L\\<close> and \\<open>S\\<close>\\\\\\<close>\n    text \\<open>Recall that @{term lhj} claims the existence of a layered subspace for any colouring\n    (of a fixed size, where the size of a colouring refers to the number of colours). Therefore, the\n    colourings have to be defined first, before the layered subspaces can be obtained. The colouring\n    \\<open>\\<chi>L\\<close> here is $\\chi^*$ in the book~\\<^cite>\\<open>\"thebook\"\\<close>, an\n    \\<open>s\\<close>-colouring; see the fact \\<open>s_coloured\\<close> a couple of lines\n    below.\\<close>\n\n    define \\<chi>L where \"\\<chi>L \\<equiv> (\\<lambda>x \\<in> cube n (t+1). (\\<lambda>y \\<in> cube m\n    (t + 1). \\<chi> (join x y n m)))\"\n    have A: \"\\<forall>x \\<in> cube n (t+1). \\<forall>y \\<in> cube m (t+1). \\<chi> (join x y n m) \\<in> {..<r}\"\n    proof(safe)\n      fix x y\n      assume \"x \\<in> cube n (t+1)\" \"y \\<in> cube m (t+1)\"\n      then have \"join x y n m \\<in> cube (n+m) (t+1)\" using join_cubes[of x n t y m] by simp\n      then show \"\\<chi> (join x y n m) < r\" using \\<chi>_prop \\<open>n + m = M'\\<close> by blast \n    qed\n    have \\<chi>L_prop: \"\\<chi>L \\<in> cube n (t+1) \\<rightarrow>\\<^sub>E cube m (t+1) \\<rightarrow>\\<^sub>E {..<r}\" \n      using A by (auto simp: \\<chi>L_def)\n\n    have \"card (cube m (t+1) \\<rightarrow>\\<^sub>E {..<r}) = (card {..<r}) ^ (card (cube m (t+1)))\" \n      using card_PiE[of \"cube m (t + 1)\" \"\\<lambda>_. {..<r}\"] by (simp add: cube_def finite_PiE)\n    also have \"... = r ^ (card (cube m (t+1)))\" by simp\n    also have \"... = r ^ ((t+1)^m)\" using cube_card unfolding cube_def by simp\n    finally have \"card (cube m (t+1) \\<rightarrow>\\<^sub>E {..<r}) = r ^ ((t+1)^m)\" .\n    then have s_coloured: \"card (cube m (t+1) \\<rightarrow>\\<^sub>E {..<r}) = s\" unfolding s_def by simp\n    have \"s > 0\" using assms(5) unfolding s_def by simp\n    then obtain \\<phi> where \\<phi>_prop: \"bij_betw \\<phi> (cube m (t+1) \\<rightarrow>\\<^sub>E {..<r}) {..<s}\" \n      using assms(5) ex_bij_betw_nat_finite_2[of \"cube m (t+1) \\<rightarrow>\\<^sub>E {..<r}\" \"s\"] s_coloured by blast\n    define \\<chi>L_s where \"\\<chi>L_s \\<equiv> (\\<lambda>x\\<in>cube n (t+1). \\<phi> (\\<chi>L x))\"\n    have \"\\<chi>L_s \\<in> cube n (t+1) \\<rightarrow>\\<^sub>E {..<s}\"\n    proof\n      fix x assume a: \"x \\<in> cube n (t+1)\"\n      then have \"\\<chi>L_s x = \\<phi> (\\<chi>L x)\" unfolding \\<chi>L_s_def by simp\n      moreover have \"\\<chi>L x \\<in> (cube m (t+1) \\<rightarrow>\\<^sub>E {..<r})\" \n        using a \\<chi>L_def \\<chi>L_prop unfolding \\<chi>L_def by blast\n      moreover have \"\\<phi> (\\<chi>L x) \\<in> {..<s}\" using \\<phi>_prop calculation(2) unfolding bij_betw_def by blast\n      ultimately show \"\\<chi>L_s x \\<in> {..<s}\" by auto\n    qed (auto simp: \\<chi>L_s_def)\n    text \\<open>L is the layered line which we obtain from the monochromatic line guaranteed to\n    exist by the assumption \\<open>hj s t\\<close>.\\<close>\n    then obtain L where L_prop: \"layered_subspace L 1 n t s \\<chi>L_s\" using line_subspace_s by blast\n    define L_line where \"L_line \\<equiv> (\\<lambda>s\\<in>{..<t+1}. L (SOME p. p\\<in>cube 1 (t+1) \\<and> p 0 = s))\"\n    have L_line_base_prop: \"\\<forall>s \\<in> {..<t+1}. L_line s \\<in> cube n (t+1)\" \n      using assms(1) dim1_subspace_is_line[of \"t+1\" \"L\" \"n\"] L_prop line_points_in_cube[of L_line n \"t+1\"] \n      unfolding layered_subspace_def L_line_def by auto\n\n    text \\<open>Here, \\<open>\\<chi>S\\<close> is $\\chi^{**}$ in the book~\\<^cite>\\<open>\"thebook\"\\<close>, an r-colouring.\\<close>\n    define \\<chi>S where \"\\<chi>S \\<equiv> (\\<lambda>y\\<in>cube m (t+1). \\<chi> (join (L_line 0) y n m))\"\n    have \"\\<chi>S \\<in> (cube m (t + 1)) \\<rightarrow>\\<^sub>E {..<r::nat}\"\n    proof\n    \tfix x assume a: \"x \\<in> cube m (t+1)\"\n    \tthen have \"\\<chi>S x = \\<chi> (join (L_line 0) x n m)\" unfolding \\<chi>S_def by simp\n    \tmoreover have \"L_line 0 = L (SOME p. p\\<in>cube 1 (t+1) \\<and> p 0 = 0)\" \n    \t  using L_prop assms(1) unfolding L_line_def by simp\n    \tmoreover have \"(SOME p. p\\<in>cube 1 (t+1) \\<and> p 0 = 0) \\<in> cube 1 (t+1)\" using cube_props(4)[of 0 \"t+1\"] \n    \t  using assms(1) by auto\n    \tmoreover have \"L \\<in> cube 1 (t+1) \\<rightarrow>\\<^sub>E cube n (t+1)\" \n    \t  using L_prop unfolding layered_subspace_def is_subspace_def by blast\n    \tmoreover have \"L (SOME p. p\\<in>cube 1 (t+1) \\<and> p 0 = 0) \\<in> cube n (t+1)\" \n    \t  using calculation (3,4) unfolding cube_def by auto\n    \tmoreover have \"join (L_line 0) x n m \\<in> cube (n + m) (t+1)\" using join_cubes a calculation(2, 5) by auto\n    \tultimately show \"\\<chi>S x \\<in> {..<r}\" using A a by fastforce\n    qed (auto simp: \\<chi>S_def)\n    text \\<open>\\<open>S\\<close> is the $k$-dimensional layered subspace that arises as a\n    consequence of the induction hypothesis. Note that the colouring is \\<open>\\<chi>S\\<close>, an\n    \\<open>r\\<close>-colouring.\\<close>\n    then obtain S where S_prop: \"layered_subspace S k m t r \\<chi>S\" using assms(4) m_props by blast\n    text \\<open>Remark: \\<open>L_Line i\\<close> returns the i-th point of the line.\\<close>\n\n    paragraph \\<open>Part 2: Constructing the $(k+1)$-dimensional subspace \\<open>T\\<close>\\\\\\<close>\n\n    text \\<open>Below, \\<open>Tset\\<close> is the set as defined in the book~\\<^cite>\\<open>\"thebook\"\\<close>. It\n    represents the $(k+1)$-dimensional subspace. In this construction, subspaces (e.g.\n    \\<open>T\\<close>) are functions whose image is a set. See the fact \\<open>im_T_eq_Tset\\<close>\n    below.\\<close>\n\n    text\\<open>Having obtained our subspaces \\<open>S\\<close> and \\<open>L\\<close>, we define the\n    $(k+1)$-dimensional subspace very straightforwardly Namely, T = L \\times S. Since we represent\n    tuples by function sets, we need an appropriate operator that mirrors the Cartesian product\n    $\\times$ for these. We call this \\<open>join\\<close> and define it for elements of a function\n    set.\\<close> \n    define Tset where \"Tset \\<equiv> {join (L_line i) s n m | i s . i \\<in> {..<t+1} \\<and> s \\<in> S ` (cube k (t+1))}\"\n    define T' where \"T' \\<equiv> (\\<lambda>x \\<in> cube 1 (t+1). \\<lambda>y \\<in> cube k (t+1). join\n    (L_line (x 0)) (S y) n m)\"\n    have T'_prop: \"T' \\<in> cube 1 (t+1) \\<rightarrow>\\<^sub>E cube k (t+1) \\<rightarrow>\\<^sub>E cube (n + m) (t+1)\"\n    proof\n      fix x assume a: \"x \\<in> cube 1 (t+1)\"\n      show \"T' x \\<in> cube k (t + 1) \\<rightarrow>\\<^sub>E cube (n + m) (t + 1)\"\n      proof\n        fix y assume b: \"y \\<in> cube k (t+1)\"\n        then have \"T' x y = join (L_line (x 0)) (S y) n m\" using a unfolding T'_def by simp\n        moreover have \"L_line (x 0) \\<in> cube n (t+1)\" using a L_line_base_prop unfolding cube_def by blast\n        moreover have \"S y \\<in> cube m (t+1)\" \n          using subspace_elems_embed[of \"S\" \"k\" \"m\" \"t+1\"] S_prop b unfolding layered_subspace_def by blast\n        ultimately show \"T' x y \\<in> cube (n + m) (t + 1)\" using join_cubes by presburger\n      next\n      qed (unfold T'_def; use a in simp)\n   \tqed (auto simp: T'_def)\n\n    define T where \"T \\<equiv> (\\<lambda>x \\<in> cube (k + 1) (t+1). T' (\\<lambda>y \\<in> {..<1}. x\n    y) (\\<lambda>y \\<in> {..<k}. x (y + 1)))\"\n   \thave T_prop: \"T \\<in> cube (k+1) (t+1) \\<rightarrow>\\<^sub>E cube (n+m) (t+1)\"\n   \tproof\n   \t  fix x assume a: \"x \\<in> cube (k+1) (t+1)\"\n   \t  then have \"T x = T' (\\<lambda>y \\<in> {..<1}. x y) (\\<lambda>y \\<in> {..<k}. x (y + 1))\" unfolding T_def by auto\n   \t  moreover have \"(\\<lambda>y \\<in> {..<1}. x y) \\<in> cube 1 (t+1)\" using a unfolding cube_def by auto\n   \t  moreover have \"(\\<lambda>y \\<in> {..<k}. x (y + 1)) \\<in> cube k (t+1)\" using a unfolding cube_def by auto\n   \t  moreover have \"T' (\\<lambda>y \\<in> {..<1}. x y) (\\<lambda>y \\<in> {..<k}. x (y + 1)) \\<in> cube (n + m) (t+1)\" \n        using T'_prop calculation unfolding T'_def by blast\n   \t  ultimately show \"T x \\<in> cube (n + m) (t+1)\" by argo\n   \tqed (auto simp: T_def)\n\n   \thave im_T_eq_Tset: \"T ` cube (k+1) (t+1) = Tset\"\n   \tproof\n   \t  show \"T ` cube (k + 1) (t + 1) \\<subseteq> Tset\"\n   \t  proof\n   \t    fix x assume \"x \\<in> T ` cube (k+1) (t+1)\"\n   \t    then obtain y where y_prop: \"y \\<in> cube (k+1) (t+1) \\<and> x = T y\" by blast\n   \t    then have \"T y = T' (\\<lambda>i \\<in> {..<1}. y i) (\\<lambda>i \\<in> {..<k}. y (i + 1))\" unfolding T_def by simp\n   \t    moreover have \"(\\<lambda>i \\<in> {..<1}. y i) \\<in> cube 1 (t+1)\" using y_prop unfolding cube_def by auto\n   \t    moreover have \"(\\<lambda>i \\<in> {..<k}. y (i + 1)) \\<in> cube k (t+1)\" using y_prop unfolding cube_def by auto\n        moreover have \" T' (\\<lambda>i \\<in> {..<1}. y i) (\\<lambda>i \\<in> {..<k}. y (i + 1)) =\n        join (L_line ((\\<lambda>i \\<in> {..<1}. y i) 0)) (S (\\<lambda>i \\<in> {..<k}. y (i + 1))) n m\" \n          using calculation unfolding T'_def by auto\n        ultimately have *: \"T y = join (L_line ((\\<lambda>i \\<in> {..<1}. y i) 0)) \n                                       (S (\\<lambda>i \\<in> {..<k}. y (i + 1))) n m\" by simp\n\n   \t    have \"(\\<lambda>i \\<in> {..<1}. y i) 0 \\<in> {..<t+1}\" using y_prop unfolding cube_def by auto\n   \t    moreover have \"S (\\<lambda>i \\<in> {..<k}. y (i + 1)) \\<in> S ` (cube k (t+1))\" \n   \t      using \\<open>(\\<lambda>i\\<in>{..<k}. y (i + 1)) \\<in> cube k (t + 1)\\<close> by blast\n   \t    ultimately have \"T y \\<in> Tset\" using * unfolding Tset_def by blast\n   \t    then show \"x \\<in> Tset\" using y_prop by simp\n   \t  qed\n\n   \t  show \"Tset \\<subseteq> T ` cube (k + 1) (t + 1)\" \n   \t  proof\n   \t    fix x assume \"x \\<in> Tset\"\n        then obtain i sx sxinv where isx_prop: \"x = join (L_line i) sx n m \\<and> i \\<in> {..<t+1}\n        \\<and> sx \\<in> S ` (cube k (t+1)) \\<and> sxinv \\<in> cube k (t+1) \\<and> S sxinv = sx\"\n          unfolding Tset_def by blast\n   \t    let ?f1 = \"(\\<lambda>j \\<in> {..<1::nat}. i)\"\n   \t    let ?f2 = \"sxinv\"\n   \t    have \"?f1 \\<in> cube 1 (t+1)\" using isx_prop unfolding cube_def by simp\n   \t    moreover have \"?f2 \\<in> cube k (t+1)\" using isx_prop by blast\n   \t    moreover have \"x = join (L_line (?f1 0)) (S ?f2) n m\" by (simp add: isx_prop)\n   \t    ultimately have *: \"x = T' ?f1 ?f2\" unfolding T'_def by simp \n\n   \t    define f where \"f \\<equiv> (\\<lambda>j \\<in> {1..<k+1}. ?f2 (j - 1))(0:=i)\"\n   \t    have \"f \\<in> cube (k+1) (t+1)\"\n   \t    proof (unfold cube_def; intro PiE_I)\n   \t      fix j assume \"j \\<in> {..<k+1}\"\n   \t      then consider \"j = 0\" | \"j \\<in> {1..<k+1}\" by fastforce\n   \t      then show \"f j \\<in> {..<t+1}\"\n   \t      proof (cases)\n   \t        case 1\n   \t        then have \"f j = i\" unfolding f_def by simp\n   \t        then show ?thesis using isx_prop by simp\n   \t      next\n   \t        case 2\n   \t        then have \"j - 1 \\<in> {..<k}\" by auto\n   \t        moreover have \"f j = ?f2 (j - 1)\" using 2 unfolding f_def by simp\n   \t        moreover have \"?f2 (j - 1) \\<in> {..<t+1}\" using calculation(1) isx_prop unfolding cube_def by blast\n   \t        ultimately show ?thesis by simp\n   \t      qed\n   \t    qed (auto simp: f_def)\n   \t    have \"?f1 = (\\<lambda>j \\<in> {..<1}. f j)\" unfolding f_def using isx_prop by auto\n   \t    moreover have \"?f2 = (\\<lambda>j\\<in>{..<k}. f (j+1))\" \n          using calculation isx_prop unfolding cube_def f_def by fastforce\n   \t    ultimately have \"T' ?f1 ?f2 = T f\" using \\<open>f \\<in> cube (k+1) (t+1)\\<close> unfolding T_def by simp\n   \t    then show \"x \\<in> T ` cube (k + 1) (t + 1)\" using * \n   \t      using \\<open>f \\<in> cube (k + 1) (t + 1)\\<close> by blast\n   \t  qed\n\n\n   \tqed\n   \thave \"Tset \\<subseteq> cube (n + m) (t+1)\"\n   \tproof\n   \t  fix x assume a: \"x\\<in>Tset\"\n      then obtain i sx where isx_props: \"x = join (L_line i) sx n m \\<and> i \\<in> {..<t+1} \\<and>\n      sx \\<in> S ` (cube k (t+1))\" unfolding Tset_def by blast\n   \t  then have \"L_line i \\<in> cube n (t+1)\" using L_line_base_prop by blast\n   \t  moreover have \"sx \\<in> cube m (t+1)\" \n        using subspace_elems_embed[of \"S\" \"k\" \"m\" \"t+1\"] S_prop isx_props unfolding layered_subspace_def by blast\n   \t  ultimately show \"x \\<in> cube (n + m) (t+1)\" using join_cubes[of \"L_line i\" \"n\" \"t\" sx m] isx_props by simp \n   \tqed\n\n\n   \tparagraph \\<open>Part 3: Proving that \\<open>T\\<close> is a subspace\\\\\\<close>\n\n    text \\<open>To prove something is a subspace, we have to provide the \\<open>B\\<close> and \\<open>f\\<close>\n    satisfying the subspace properties. \n    We construct \\<open>BT\\<close> and \\<open>fT\\<close> from \\<open>BS\\<close>, \\<open>fS\\<close> and\n    \\<open>BL\\<close>, \\<open>fL\\<close>, which correspond to the $k$-dimensional subspace \\<open>S\\<close> \n    and the $1$-dimensional subspace (i.e.\\ line) \\<open>L\\<close>, respectively.\\<close>\n    obtain BS fS where BfS_props: \"disjoint_family_on BS {..k}\" \"\\<Union>(BS ` {..k}) = {..<m}\" \"({}\n    \\<notin> BS ` {..<k})\" \" fS \\<in> (BS k) \\<rightarrow>\\<^sub>E {..<t+1}\" \"S \\<in> (cube k (t+1))\n    \\<rightarrow>\\<^sub>E (cube m (t+1)) \" \"(\\<forall>y \\<in> cube k (t+1). (\\<forall>i \\<in> BS k.\n    S y i = fS i) \\<and> (\\<forall>j<k. \\<forall>i \\<in> BS j. (S y) i = y j))\" using S_prop\n      unfolding layered_subspace_def is_subspace_def by auto\n\n    obtain BL fL where BfL_props: \"disjoint_family_on BL {..1}\" \"\\<Union>(BL ` {..1}) = {..<n}\"\n      \"({} \\<notin> BL ` {..<1})\" \"fL \\<in> (BL 1) \\<rightarrow>\\<^sub>E {..<t+1}\" \"L \\<in> (cube 1\n    (t+1)) \\<rightarrow>\\<^sub>E (cube n (t+1))\" \"(\\<forall>y \\<in> cube 1 (t+1). (\\<forall>i \\<in>\n    BL 1. L y i = fL i) \\<and> (\\<forall>j<1. \\<forall>i \\<in> BL j. (L y) i = y j))\" using L_prop\n      unfolding layered_subspace_def is_subspace_def by auto\n\n   \tdefine Bstat where \"Bstat \\<equiv> set_incr n (BS k) \\<union> BL 1\"\n   \tdefine Bvar where \"Bvar \\<equiv> (\\<lambda>i::nat. (if i = 0 then BL 0 else set_incr n (BS (i - 1))))\"\n   \tdefine BT where \"BT \\<equiv> (\\<lambda>i \\<in> {..<k+1}. Bvar i)((k+1):=Bstat)\"\n    define fT where \"fT \\<equiv> (\\<lambda>x. (if x \\<in> BL 1 then fL x else (if x \\<in> set_incr n\n    (BS k) then fS (x - n) else undefined)))\"\n\n   \thave fact1: \"set_incr n (BS k) \\<inter> BL 1 = {}\"  using BfL_props BfS_props unfolding set_incr_def by auto\n   \thave fact2: \"BL 0 \\<inter> (\\<Union>i\\<in>{..<k}. set_incr n (BS i)) = {}\" \n      using BfL_props BfS_props unfolding set_incr_def by auto\n   \thave fact3: \"\\<forall>i \\<in> {..<k}. BL 0 \\<inter> set_incr n (BS i) = {}\" \n      using BfL_props BfS_props unfolding set_incr_def by auto\n    have fact4: \"\\<forall>i \\<in> {..<k+1}. \\<forall>j \\<in> {..<k+1}. i \\<noteq> j\n    \\<longrightarrow> set_incr n (BS i) \\<inter> set_incr n (BS j) = {}\" \n      using set_incr_disjoint_family[of BS k] BfS_props unfolding disjoint_family_on_def by simp \n   \thave fact5: \"\\<forall>i \\<in> {..<k+1}. Bvar i \\<inter> Bstat = {}\"\n   \tproof\n   \t  fix i assume a: \"i \\<in> {..<k+1}\"\n   \t  show \"Bvar i \\<inter> Bstat = {}\"\n   \t  proof (cases i)\n   \t    case 0\n   \t    then have \"Bvar i = BL 0\" unfolding Bvar_def by simp\n   \t    moreover have \"BL 0 \\<inter> BL 1 = {}\" using BfL_props unfolding disjoint_family_on_def by simp\n   \t    moreover have \"set_incr n (BS k) \\<inter> BL 0 = {}\" using BfL_props BfS_props unfolding set_incr_def by auto\n   \t    ultimately show ?thesis unfolding Bstat_def by blast\n   \t  next\n   \t    case (Suc nat)\n   \t    then have \"Bvar i = set_incr n (BS nat)\" unfolding Bvar_def by simp\n   \t    moreover have \"set_incr n (BS nat) \\<inter> BL 1 = {}\" using BfS_props BfL_props a Suc unfolding set_incr_def \n          by auto\n   \t    moreover have \"set_incr n (BS nat) \\<inter> set_incr n (BS k) = {}\" using a Suc fact4 by simp\n   \t    ultimately show ?thesis unfolding Bstat_def by blast\n   \t  qed\n   \tqed\n\n   \ttext \\<open>The facts \\<open>F1\\<close>, ..., \\<open>F5\\<close> are the disjuncts in the subspace definition.\\<close>\n    have \"Bvar ` {..<k+1} = BL ` {..<1} \\<union> Bvar ` {1..<k+1}\" unfolding Bvar_def by force\n    also have \" ... = BL ` {..<1} \\<union> {set_incr n (BS i) | i . i \\<in> {..<k}} \" unfolding Bvar_def by fastforce  \n    moreover have \"{} \\<notin> BL ` {..<1}\" using BfL_props by auto\n    moreover have \"{} \\<notin> {set_incr n (BS i) | i . i \\<in> {..<k}}\" using BfS_props(2, 3) set_incr_def by fastforce\n    ultimately have \"{} \\<notin> Bvar ` {..<k+1}\" by simp\n    then have F1: \"{} \\<notin> BT ` {..<k+1}\" unfolding BT_def by simp\n    moreover\n    {\n      have F2_aux: \"disjoint_family_on Bvar {..<k+1}\"\n      proof (unfold disjoint_family_on_def; safe)\n        fix m n x assume a: \"m < k + 1\" \"n < k + 1\" \"m \\<noteq> n\" \"x \\<in> Bvar m\" \"x \\<in> Bvar n\"\n        show \"x \\<in> {}\"\n        proof (cases \"n\")\n          case 0\n          then show ?thesis using a fact3 unfolding Bvar_def by auto\n        next\n          case (Suc nnat)\n          then have *: \"n = Suc nnat\" by simp\n          then show ?thesis \n          proof (cases m)\n            case 0\n            then show ?thesis using a fact3 unfolding Bvar_def by auto\n          next\n            case (Suc mnat)\n            then show ?thesis using a fact4  * unfolding Bvar_def by fastforce\n          qed\n        qed\n      qed\n\n      have F2: \"disjoint_family_on BT {..k+1}\"\n      proof\n        fix m n assume a: \"m\\<in>{..k+1}\" \"n\\<in>{..k+1}\" \"m \\<noteq> n\"\n        have \"\\<forall>x. x \\<in> BT m \\<inter> BT n \\<longrightarrow> x \\<in> {}\" \n        proof (intro allI impI)\n          fix x assume b: \"x \\<in> BT m \\<inter> BT n\"\n          have \"m < k + 1 \\<and> n < k + 1 \\<or> m = k + 1 \\<and> n = k + 1 \\<or> m < k + 1 \n          \\<and> n = k + 1 \\<or> m = k + 1 \\<and> n < k + 1\" using a le_eq_less_or_eq by auto\n          then show \"x \\<in> {}\"\n          proof (elim disjE)\n            assume c: \"m < k + 1 \\<and> n < k + 1\"\n            then have \"BT m = Bvar m \\<and> BT n = Bvar n\" unfolding BT_def by simp\n            then show \"x \\<in> {}\" using a b c fact4 F2_aux unfolding Bvar_def disjoint_family_on_def by auto\n          qed (use a b fact5 in \\<open>auto simp: BT_def\\<close>)\n        qed\n        then show \"BT m \\<inter> BT n = {}\" by auto\n      qed\n    }\n    moreover have F3: \"\\<Union>(BT ` {..k+1}) = {..<n + m}\"\n    proof \n      show \"\\<Union> (BT ` {..k + 1}) \\<subseteq> {..<n + m}\"\n      proof\n        fix x assume \"x \\<in> \\<Union> (BT ` {..k + 1})\"\n        then obtain i where i_prop: \"i \\<in> {..k+1} \\<and> x \\<in> BT i\" by blast\n        then consider \"i = k +1\" | \"i \\<in> {..<k+1}\" by fastforce\n        then show \"x \\<in> {..<n + m}\"\n        proof (cases)\n          case 1\n          then have \"x \\<in> Bstat\" using i_prop unfolding BT_def by simp\n          then have \"x \\<in> BL 1 \\<or> x \\<in> set_incr n (BS k)\" unfolding Bstat_def by blast\n          then have \"x \\<in> {..<n} \\<or> x \\<in> {n..<n+m}\" using BfL_props BfS_props(2) set_incr_image[of BS k m n] \n            by blast\n          then show ?thesis by auto\n        next\n          case 2\n          then have \"x \\<in> Bvar i\" using i_prop unfolding BT_def by simp\n          then have \"x \\<in> BL 0 \\<or> x \\<in> set_incr n (BS (i - 1))\" unfolding Bvar_def by presburger\n          then show ?thesis\n          proof (elim disjE)\n            assume \"x \\<in> BL 0\"\n            then have \"x \\<in> {..<n}\" using BfL_props by auto\n            then show \"x \\<in> {..<n + m}\" by simp\n          next\n            assume a: \"x \\<in> set_incr n (BS (i - 1))\"\n            then have \"i - 1 \\<le> k\" \n              by (meson atMost_iff i_prop le_diff_conv) \n            then have \"set_incr n (BS (i - 1)) \\<subseteq> {n..<n+m}\" using set_incr_image[of BS k m n] BfS_props \n              by auto\n            then show \"x \\<in> {..<n+m}\" using a by auto\n          qed\n        qed\n      qed\n    next\n      show \"{..<n + m} \\<subseteq> \\<Union> (BT ` {..k + 1})\"\n      proof \n        fix x assume \"x \\<in> {..<n + m}\"\n        then consider \"x \\<in> {..<n}\" | \"x \\<in> {n..<n+m}\" by fastforce\n        then show \"x \\<in> \\<Union> (BT ` {..k + 1})\"\n        proof (cases)\n          case 1\n          have *: \"{..1::nat} = {0, 1::nat}\" by auto\n          from 1 have \"x \\<in> \\<Union> (BL ` {..1::nat})\" using BfL_props by simp\n          then have \"x \\<in> BL 0 \\<or> x \\<in> BL 1\" using * by simp\n          then show ?thesis \n          proof (elim disjE)\n            assume \"x \\<in> BL 0\"\n            then have \"x \\<in> Bvar 0\" unfolding Bvar_def by simp\n            then have \"x \\<in> BT 0\" unfolding BT_def by simp\n            then show \"x \\<in> \\<Union> (BT ` {..k + 1})\" by auto\n          next\n            assume \"x \\<in> BL 1\"\n            then have \"x \\<in> Bstat\" unfolding Bstat_def by simp\n            then have \"x \\<in> BT (k+1)\" unfolding BT_def by simp\n            then show \"x \\<in> \\<Union> (BT ` {..k + 1})\" by auto\n          qed\n        next\n          case 2\n          then have \"x \\<in> (\\<Union>i\\<le>k. set_incr n (BS i))\" using set_incr_image[of BS k m n] BfS_props by simp\n          then obtain i where i_prop: \"i \\<le> k \\<and> x \\<in> set_incr n (BS i)\" by blast\n          then consider \"i = k\" | \"i < k\" by fastforce\n          then show ?thesis\n          proof (cases)\n            case 1\n            then have \"x \\<in> Bstat\" unfolding Bstat_def using i_prop by auto\n            then have \"x \\<in> BT (k+1)\" unfolding BT_def by simp\n            then show ?thesis by auto\n          next\n            case 2\n            then have \"x \\<in> Bvar (i + 1)\" unfolding Bvar_def using i_prop by simp\n            then have \"x \\<in> BT (i + 1)\" unfolding BT_def using 2 by force\n            then show ?thesis using 2 by auto\n          qed\n        qed\n      qed\n    qed\n\n    moreover have F4: \"fT \\<in> (BT (k+1)) \\<rightarrow>\\<^sub>E {..<t+1}\"\n    proof\n      fix x assume \"x \\<in> BT (k+1)\"\n      then have \"x \\<in> Bstat\" unfolding BT_def by simp\n      then have \"x \\<in> BL 1 \\<or> x \\<in> set_incr n (BS k)\" unfolding Bstat_def by auto\n      then show \"fT x \\<in> {..<t + 1}\"\n      proof (elim disjE)\n        assume \"x \\<in> BL 1\"\n        then have \"fT x = fL x\" unfolding fT_def by simp\n        then show \"fT x \\<in> {..<t+1}\" using BfL_props \\<open>x \\<in> BL 1\\<close> by auto\n      next\n        assume a: \"x \\<in> set_incr n (BS k)\"\n        then have \"fT x = fS (x - n)\" using fact1 unfolding fT_def by auto\n        moreover have \"x - n \\<in> BS k\" using a unfolding set_incr_def by auto\n        ultimately show \"fT x \\<in> {..<t+1}\" using BfS_props by auto\n      qed\n    qed(auto simp: BT_def Bstat_def fT_def)\n    moreover have F5: \"((\\<forall>i \\<in> BT (k + 1). T y i = fT i) \\<and> (\\<forall>j<k+1.\n    \\<forall>i \\<in> BT j. (T y) i = y j))\" if \"y \\<in> cube (k + 1) (t + 1)\" for y\n    proof(intro conjI allI impI ballI)\n      fix i assume \"i \\<in> BT (k + 1)\"\n      then have \"i \\<in> Bstat\" unfolding BT_def by simp\n      then consider \"i \\<in> set_incr n (BS k)\" |  \"i \\<in> BL 1\" unfolding Bstat_def by blast\n      then show \"T y i = fT i\"\n      proof (cases)\n        case 1\n        then have \"\\<exists>s<m. i = n + s\" unfolding set_incr_def using BfS_props(2) by auto\n        then obtain s where s_prop: \"s < m \\<and> i = n + s\" by blast\n        then have *: \" i \\<in> {n..<n+m}\" by simp\n        have \"i \\<notin> BL 1\" using 1 fact1 by auto\n        then have \"fT i = fS (i - n)\" using 1 unfolding fT_def by simp\n        then have **: \"fT i = fS s\" using s_prop by simp\n\n        have XX: \"(\\<lambda>z \\<in> {..<k}. y (z + 1)) \\<in> cube k (t+1)\" using split_cube that by simp\n        have XY: \"s \\<in> BS k\" using  s_prop  1 unfolding set_incr_def by auto\n\n        from that have \"T y i = (T' (\\<lambda>z \\<in> {..<1}. y z) (\\<lambda>z \\<in> {..<k}. y (z + 1))) i\" \n          unfolding T_def by auto\n        also have \"... = (join (L_line ((\\<lambda>z \\<in> {..<1}. y z) 0)) (S (\\<lambda>z \\<in>\n        {..<k}. y (z + 1))) n m) i\" using split_cube that unfolding T'_def by simp\n        also have \"... = (join (L_line (y 0)) (S (\\<lambda>z \\<in> {..<k}. y (z + 1))) n m) i\" by simp\n        also have \"... = (S (\\<lambda>z \\<in> {..<k}. y (z + 1))) s\" using * s_prop unfolding join_def by simp\n        also have \"... = fS s\" using XX XY BfS_props(6) by blast\n        finally show ?thesis using ** by simp\n      next\n        case 2\n        have XZ: \"y 0 \\<in> {..<t+1}\" using that unfolding cube_def by auto\n        have XY: \"i \\<in> {..<n}\" using 2 BfL_props(2) by blast\n        have XX: \"(\\<lambda>z \\<in> {..<1}. y z)  \\<in> cube 1 (t+1)\" using that split_cube by simp\n\n        have some_eq_restrict: \"(SOME p. p\\<in>cube 1 (t+1) \\<and> p 0 = ((\\<lambda>z \\<in> {..<1}.\n        y z) 0)) = (\\<lambda>z \\<in> {..<1}. y z)\"\n        proof \n          show \"restrict y {..<1} \\<in> cube 1 (t + 1) \\<and> restrict y {..<1} 0 = restrict y {..<1} 0\" \n            using XX by simp\n        next\n          fix p\n          assume \"p \\<in> cube 1 (t+1) \\<and> p 0 = restrict y {..<1} 0\"\n          moreover have \"p u = restrict y {..<1} u\" if \"u \\<notin> {..<1}\" for u \n            using that calculation XX unfolding cube_def \n            using PiE_arb[of \"restrict y {..<1}\" \"{..<1}\" \"\\<lambda>x. {..<t + 1}\" u] \n              PiE_arb[of p \"{..<1}\" \"\\<lambda>x. {..<t + 1}\" u] by simp\n          ultimately show \"p = restrict y {..<1}\" by auto \n        qed\n\n        from that have \"T y i = (T' (\\<lambda>z \\<in> {..<1}. y z) (\\<lambda>z \\<in> {..<k}. y (z + 1))) i\" \n          unfolding T_def by auto\n        also have \"... = (join (L_line ((\\<lambda>z \\<in> {..<1}. y z) 0)) (S (\\<lambda>z \\<in> {..<k}. y (z + 1))) n m) i\" \n          using split_cube that unfolding T'_def by simp\n        also have \"... = (L_line ((\\<lambda>z \\<in> {..<1}. y z) 0)) i\" using XY unfolding join_def by simp\n        also have \"... = L (SOME p. p\\<in>cube 1 (t+1) \\<and> p 0 = ((\\<lambda>z \\<in> {..<1}. y z) 0)) i\" \n          using XZ unfolding L_line_def by auto\n        also have \"... = L (\\<lambda>z \\<in> {..<1}. y z) i\" using some_eq_restrict by simp\n        also have \"... = fL i\" using BfL_props(6) XX 2 by blast\n        also have \"... = fT i\" using 2 unfolding fT_def by simp\n        finally show ?thesis .\n      qed\n    next\n      fix j i assume \"j < k + 1\" \"i \\<in> BT j\"\n      then have i_prop: \"i \\<in> Bvar j\" unfolding BT_def by auto\n      consider \"j = 0\" | \"j > 0\" by auto\n      then show \"T y i = y j\"\n      proof cases\n        case 1\n        then have \"i \\<in> BL 0\" using i_prop unfolding Bvar_def by auto\n        then have XY: \"i \\<in> {..<n}\" using 1 BfL_props(2) by blast\n        have XX: \"(\\<lambda>z \\<in> {..<1}. y z)  \\<in> cube 1 (t+1)\" using that split_cube by simp\n        have XZ: \"y 0 \\<in> {..<t+1}\" using that unfolding cube_def by auto\n\n        have some_eq_restrict: \"(SOME p. p\\<in>cube 1 (t+1) \\<and> p 0 = ((\\<lambda>z \\<in> {..<1}.\n        y z) 0)) = (\\<lambda>z \\<in> {..<1}. y z)\"\n        proof \n          show \"restrict y {..<1} \\<in> cube 1 (t + 1) \\<and> restrict y {..<1} 0 = restrict y {..<1} 0\" using XX by simp\n        next\n          fix p\n          assume \"p \\<in> cube 1 (t+1) \\<and> p 0 = restrict y {..<1} 0\"\n          moreover have \"p u = restrict y {..<1} u\" if \"u \\<notin> {..<1}\" for u \n            using that calculation XX unfolding cube_def \n            using PiE_arb[of \"restrict y {..<1}\" \"{..<1}\" \"\\<lambda>x. {..<t + 1}\" u] \n              PiE_arb[of p \"{..<1}\" \"\\<lambda>x. {..<t + 1}\" u] by simp\n          ultimately show \"p = restrict y {..<1}\" by auto \n        qed\n\n        from that have \"T y i = (T' (\\<lambda>z \\<in> {..<1}. y z) (\\<lambda>z \\<in> {..<k}. y (z + 1))) i\" \n          unfolding T_def by auto\n        also have \"... = (join (L_line ((\\<lambda>z \\<in> {..<1}. y z) 0)) (S (\\<lambda>z \\<in> {..<k}. y (z + 1))) n m) i\"\n          using split_cube that unfolding T'_def by simp\n        also have \"... = (L_line ((\\<lambda>z \\<in> {..<1}. y z) 0)) i\" using XY unfolding join_def by simp\n        also have \"... = L (SOME p. p\\<in>cube 1 (t+1) \\<and> p 0 = ((\\<lambda>z \\<in> {..<1}. y z) 0)) i\" \n          using XZ unfolding L_line_def by auto\n        also have \"... = L (\\<lambda>z \\<in> {..<1}. y z) i\" using some_eq_restrict by simp\n        also have \"... =  (\\<lambda>z \\<in> {..<1}. y z) j\" using BfL_props(6) XX 1  \\<open>i \\<in> BL 0\\<close> by blast\n        also have \"... = (\\<lambda>z \\<in> {..<1}. y z) 0\" using 1 by blast\n        also have \"... = y 0\" by simp\n        also have \"... = y j\" using 1 by simp\n        finally show ?thesis .\n      next\n        case 2\n        then have \"i \\<in> set_incr n (BS (j - 1))\" using i_prop unfolding Bvar_def by simp\n        then have \"\\<exists>s<m. n + s = i\" using BfS_props(2) \\<open>j < k + 1\\<close> unfolding set_incr_def by force \n        then obtain s where s_prop: \"s < m\" \"i = s + n\" by auto\n        then have *: \" i \\<in> {n..<n+m}\" by simp\n\n        have XX: \"(\\<lambda>z \\<in> {..<k}. y (z + 1)) \\<in> cube k (t+1)\" using split_cube that by simp\n        have XY: \"s \\<in> BS (j - 1)\" using s_prop 2 \\<open>i \\<in> set_incr n (BS (j - 1))\\<close> \n          unfolding set_incr_def by force\n\n        from that have \"T y i = (T' (\\<lambda>z \\<in> {..<1}. y z) (\\<lambda>z \\<in> {..<k}. y (z + 1))) i\" \n          unfolding T_def by auto\n        also have \"... = (join (L_line ((\\<lambda>z \\<in> {..<1}. y z) 0)) (S (\\<lambda>z \\<in> {..<k}. y (z + 1))) n m) i\" \n          using split_cube that unfolding T'_def by simp\n        also have \"... = (join (L_line (y 0)) (S (\\<lambda>z \\<in> {..<k}. y (z + 1))) n m) i\" by simp\n        also have \"... = (S (\\<lambda>z \\<in> {..<k}. y (z + 1))) s\" using * s_prop unfolding join_def by simp\n        also have \"... = (\\<lambda>z \\<in> {..<k}. y (z + 1)) (j-1)\" \n          using XX XY BfS_props(6) 2 \\<open>j < k + 1\\<close> by auto\n        also have \"... = y j\" using 2 \\<open>j < k + 1\\<close> by force\n        finally show ?thesis .\n      qed\n    qed\n\n    ultimately have subspace_T: \"is_subspace T (k+1) (n+m) (t+1)\" unfolding is_subspace_def using T_prop by metis\n\n    paragraph \\<open>Part 4: Proving \\<open>T\\<close> is layered\\\\\\<close>\n    text \\<open>The following redefinition of the classes makes proving the layered property easier.\\<close>\n    define T_class where \"T_class \\<equiv> (\\<lambda>j\\<in>{..k}. {join (L_line i) s n m | i s . i\n    \\<in> {..<t} \\<and> s \\<in> S ` (classes k t j)})(k+1:= {join (L_line t) (SOME s. s \\<in> S `\n    (cube m (t+1))) n m})\"\n    have classprop: \"T_class j = T ` classes (k + 1) t j\" if j_prop: \"j \\<le> k\" for j\n    proof\n      show \"T_class j \\<subseteq> T ` classes (k + 1) t j\"\n      proof\n        fix x assume \"x \\<in> T_class j\"\n        from that have \"T_class j = {join (L_line i) s n m | i s . i \\<in> {..<t} \\<and> s \\<in> S ` (classes k t j)}\" \n          unfolding T_class_def by simp\n        then obtain i s where is_defs: \"x = join (L_line i) s n m \\<and> i < t \\<and> s \\<in> S ` (classes k t j)\" \n          using \\<open>x \\<in> T_class j\\<close> unfolding T_class_def by auto\n        moreover have *:\"classes k t j \\<subseteq> cube k (t+1)\" unfolding classes_def by simp\n        moreover have \"\\<exists>!y. y \\<in> classes k t j \\<and> s = S y\" \n          using subspace_inj_on_cube[of S k m \"t+1\"] S_prop inj_onD[of S \"cube k (t+1)\"] calculation \n          unfolding layered_subspace_def inj_on_def by blast\n        ultimately obtain y where y_prop: \"y \\<in> classes k t j \\<and> s = S y \\<and>\n        (\\<forall>z\\<in>classes k t j. s = S z \\<longrightarrow> y = z)\" by auto\n\n        define p where \"p \\<equiv> join (\\<lambda>g\\<in>{..<1}. i) y 1 k\"\n        have \"(\\<lambda>g\\<in>{..<1}. i) \\<in> cube 1 (t+1)\" using is_defs unfolding cube_def by simp\n        then have p_in_cube: \"p \\<in> cube (k + 1) (t+1)\" \n          using join_cubes[of \"(\\<lambda>g\\<in>{..<1}. i)\" 1 t y k] y_prop * unfolding p_def by auto\n        then have **: \"p 0 = i \\<and> (\\<forall>l < k. p (l + 1) = y l)\" unfolding p_def join_def by simp \n\n        have \"t \\<notin> y ` {..<(k - j)}\" using y_prop unfolding classes_def by simp\n        then have \"\\<forall>u < k - j. y u \\<noteq> t\" by auto\n        then have \"\\<forall>u < k - j. p (u + 1) \\<noteq> t\" using ** by simp\n        moreover have \"p 0 \\<noteq> t\" using is_defs ** by simp\n        moreover have \"\\<forall>u < k - j + 1. p u \\<noteq> t\" \n          using calculation by (auto simp: algebra_simps less_Suc_eq_0_disj)\n        ultimately have \"\\<forall>u < (k + 1) - j. p u \\<noteq> t\" using that by auto\n        then have A1: \"t \\<notin> p ` {..<((k+1) - j)}\" by blast\n\n\n        have \"p u = t\" if \"u \\<in> {k - j + 1..<k+1}\" for u \n        proof -\n          from that have \"u - 1 \\<in> {k - j..<k}\" by auto\n          then have \"y (u - 1) = t\" using y_prop unfolding classes_def by blast\n          then show \"p u = t\" using ** that \\<open>u - 1 \\<in> {k - j..<k}\\<close> by auto\n        qed\n        then have A2: \"\\<forall>u\\<in>{(k+1) - j..<k+1}. p u = t\" using that by auto\n\n        from A1 A2 p_in_cube have \"p \\<in> classes (k+1) t j\" unfolding classes_def by blast\n\n        moreover have \"x = T p\"\n        proof-\n          have loc_useful:\"(\\<lambda>y \\<in> {..<k}. p (y + 1)) = (\\<lambda>z \\<in> {..<k}. y z)\" using ** by auto\n          have \"T p = T' (\\<lambda>y \\<in> {..<1}. p y) (\\<lambda>y \\<in> {..<k}. p (y + 1))\" \n            using p_in_cube unfolding T_def by auto\n\n          have \"T' (\\<lambda>y \\<in> {..<1}. p y) (\\<lambda>y \\<in> {..<k}. p (y + 1)) \n                = join (L_line ((\\<lambda>y \\<in> {..<1}. p y) 0)) (S (\\<lambda>y \\<in> {..<k}. p (y + 1))) n m\" \n            using split_cube p_in_cube unfolding T'_def by simp\n          also have \"... = join (L_line (p 0)) (S (\\<lambda>y \\<in> {..<k}. p (y + 1))) n m\" by simp\n          also have \"... = join (L_line i) (S (\\<lambda>y \\<in> {..<k}. p (y + 1))) n m\" by (simp add: **)\n          also have \"... = join (L_line i) (S (\\<lambda>z \\<in> {..<k}. y z)) n m\" using loc_useful by simp\n          also have \"... = join (L_line i) (S y) n m\" using y_prop * unfolding cube_def by auto\n          also have \"... = x\" using is_defs y_prop by simp\n          finally show \"x = T p\" \n            using \\<open>T p = T' (restrict p {..<1}) (\\<lambda>y\\<in>{..<k}. p (y + 1))\\<close> by presburger\n        qed\n        ultimately show \"x \\<in> T ` classes (k + 1) t j\" by blast\n      qed\n    next\n      show \"T ` classes (k + 1) t j \\<subseteq> T_class j\"\n      proof\n        fix x assume \"x \\<in> T ` classes (k+1) t j\"\n        then obtain y where y_prop: \"y \\<in> classes (k+1) t j \\<and> T y = x\" by blast\n        then have y_props: \"(\\<forall>u \\<in> {((k+1)-j)..<k+1}. y u = t) \\<and> t \\<notin> y ` {..<(k+1) - j }\" \n          unfolding classes_def by blast\n\n        define z where \"z \\<equiv> (\\<lambda>v \\<in> {..<k}. y (v+1))\" \n        have \"z \\<in> cube k (t+1)\" using  y_prop classes_subset_cube[of \"k+1\" t j] unfolding z_def cube_def by auto\n        moreover\n        {\n          have \"z ` {..<k - j} = y ` ((+) 1 ` {..<k-j}) \"  unfolding z_def by fastforce\n          also have \"... = y ` {1..<k-j+1}\" by (simp add: atLeastLessThanSuc_atLeastAtMost image_Suc_lessThan)\n          also have \"... = y ` {1..<(k+1)-j}\" using j_prop by auto\n          finally have \"z ` {..<k - j} \\<subseteq> y ` {..<(k+1)-j}\" by auto\n          then have \"t \\<notin> z ` {..<k - j}\" using y_props by blast\n\n        }\n        moreover have \"\\<forall>u \\<in> {k-j..<k}. z u = t\" unfolding z_def using y_props by auto\n        ultimately have z_in_classes: \"z \\<in> classes k t j\" unfolding classes_def by blast\n\n        have \"y 0 \\<noteq> t\"\n        proof-\n          from that have \"0 \\<in> {..<k + 1 - j}\" by simp\n          then show \"y 0 \\<noteq> t\" using y_props by blast\n        qed\n        then have tr: \"y 0 < t\" using y_prop classes_subset_cube[of \"k+1\" t j] unfolding cube_def by fastforce\n\n        have \"(\\<lambda>g \\<in> {..<1}. y g) \\<in> cube 1 (t+1)\" \n          using y_prop classes_subset_cube[of \"k+1\" t j] cube_restrict[of 1 \"(k+1)\" y \"t+1\"] assms(2) by auto\n        then have \"T y = T' (\\<lambda>g \\<in> {..<1}. y g) z\" using y_prop classes_subset_cube[of \"k+1\" t j] \n          unfolding T_def z_def by auto\n        also have \" ... = join (L_line ((\\<lambda>g \\<in> {..<1}. y g) 0)) (S z) n m\" \n          unfolding T'_def \n          using \\<open>(\\<lambda>g \\<in> {..<1}. y g) \\<in> cube 1 (t+1)\\<close> \\<open>z \\<in> cube k (t+1)\\<close> \n          by auto\n        also have \" ... = join (L_line (y 0)) (S z) n m\" by simp\n        also have \" ... \\<in> T_class j\" using tr z_in_classes that unfolding T_class_def by force\n        finally show \"x \\<in> T_class j\" using y_prop by simp\n      qed\n    qed\n\n    text \\<open>The core case $i \\leq k$. The case $i = k+1$ is trivial since $k+1$ has only one point.\\<close>\n    have \"\\<chi> x = \\<chi> y \\<and> \\<chi> x < r\" if a: \"i \\<le> k\" \"x \\<in> T ` classes (k+1) t i\"\n      \"y \\<in> T ` classes (k+1) t i\" for i x y\n    proof-\n      from a have *: \"T ` classes (k+1) t i = T_class i\" by (simp add: classprop)\n      then have  \"x \\<in> T_class i \" using that by simp\n      moreover have **: \"T_class i = {join (L_line l) s n m | l s . l \\<in> {..<t} \\<and> s \\<in> S ` (classes k t i)}\" \n        using a unfolding T_class_def by simp\n      ultimately obtain xs xi where xdefs: \"x = join (L_line xi) xs n m \\<and> xi < t \\<and> xs \\<in> S ` (classes k t i)\"\n        by blast\n\n      from * ** obtain ys yi where ydefs: \"y = join (L_line yi) ys n m \\<and> yi < t \\<and> ys \\<in> S ` (classes k t i)\"\n        using a by auto\n\n      have \"(L_line xi) \\<in> cube n (t+1)\" using L_line_base_prop xdefs by simp\n      moreover have \"xs \\<in> cube m (t+1)\" \n        using xdefs S_prop subspace_elems_embed imageE image_subset_iff mem_Collect_eq \n        unfolding layered_subspace_def classes_def by blast\n      ultimately have AA1: \"\\<chi> x = \\<chi>L (L_line xi) xs\" using xdefs unfolding \\<chi>L_def by simp\n\n      have \"(L_line yi) \\<in> cube n (t+1)\" using L_line_base_prop ydefs by simp\n      moreover have \"ys \\<in> cube m (t+1)\" \n        using ydefs S_prop subspace_elems_embed imageE image_subset_iff mem_Collect_eq \n        unfolding layered_subspace_def classes_def by blast\n      ultimately have AA2: \"\\<chi> y = \\<chi>L (L_line yi) ys\" using ydefs unfolding \\<chi>L_def by simp\n\n      have \"\\<forall>s<t. \\<forall>l < t. \\<chi>L_s (L (SOME p. p\\<in>cube 1 (t+1) \\<and> p 0 = s))\n      = \\<chi>L_s (L (SOME p. p\\<in>cube 1 (t+1) \\<and> p 0 = l))\" using\n        dim1_layered_subspace_mono_line[of t L n s \\<chi>L_s] L_prop assms(1) by blast\n      then have key_aux: \"\\<chi>L_s (L_line s) = \\<chi>L_s (L_line l)\" if \"s \\<in> {..<t}\" \"l \\<in> {..<t}\" for s l \n        using that unfolding L_line_def \n        by (metis (no_types, lifting) add.commute \n            lessThan_iff less_Suc_eq plus_1_eq_Suc restrict_apply)\n      have key: \"\\<chi>L (L_line s) = \\<chi>L (L_line l)\" if \"s < t\" \"l < t\" for s l\n      proof-\n        have L1: \"\\<chi>L (L_line s) \\<in> cube m (t + 1) \\<rightarrow>\\<^sub>E {..<r}\" unfolding \\<chi>L_def \n          using A L_line_base_prop \\<open>s < t\\<close> by simp\n        have L2: \"\\<chi>L (L_line l) \\<in> cube m (t + 1) \\<rightarrow>\\<^sub>E {..<r}\" unfolding \\<chi>L_def \n          using A L_line_base_prop \\<open>l < t\\<close> by simp\n        have \"\\<phi> (\\<chi>L (L_line s)) = \\<chi>L_s (L_line s)\" unfolding \\<chi>L_s_def \n          using \\<open>s < t\\<close> L_line_base_prop by simp\n        also have \" ... =  \\<chi>L_s (L_line l)\" using key_aux \\<open>s <t\\<close> \\<open>l < t\\<close> by blast\n        also have \" ... = \\<phi> (\\<chi>L (L_line l))\" unfolding \\<chi>L_s_def using L_line_base_prop \\<open>l<t\\<close>\n          by simp\n        finally have \"\\<phi> (\\<chi>L (L_line s)) = \\<phi> (\\<chi>L (L_line l))\" by simp\n        then show \"\\<chi>L (L_line s) = \\<chi>L (L_line l)\" \n          using \\<phi>_prop L_line_base_prop L1 L2 unfolding bij_betw_def inj_on_def by blast\n      qed\n      then have \"\\<chi>L (L_line xi) xs = \\<chi>L (L_line 0) xs\" using xdefs assms(1) by metis\n      also have \" ... =  \\<chi>S xs\" unfolding \\<chi>S_def \\<chi>L_def using xdefs L_line_base_prop by auto\n      also have \" ... = \\<chi>S ys\" using xdefs ydefs layered_eq_classes[of S k m t r \\<chi>S] S_prop a by blast\n      also have \" ... = \\<chi>L (L_line 0) ys\"  unfolding \\<chi>S_def \\<chi>L_def using xdefs L_line_base_prop \n        by auto\n      also have \" ... = \\<chi>L (L_line yi) ys\" using ydefs key assms(1) by metis\n      finally have core_prop: \"\\<chi>L (L_line xi) xs =  \\<chi>L (L_line yi) ys\" by simp\n      then have \"\\<chi> x = \\<chi> y\" using AA1 AA2 by simp      \n      then show \" \\<chi> x = \\<chi> y \\<and> \\<chi> x < r\" \n        using xdefs AA1 key assms(1) A \n          \\<open>L_line xi \\<in> cube n (t + 1)\\<close> \\<open>xs \\<in> cube m (t + 1)\\<close> by blast\n    qed\n    then have \"\\<exists>c<r. \\<forall>x \\<in> T ` classes (k+1) t i. \\<chi> x = c\" if \"i \\<le> k\" for i\n      using that assms(5) by blast\n\n    moreover have \"\\<exists>c<r. \\<forall>x \\<in> T ` classes (k+1) t (k+1). \\<chi> x = c\"\n    proof -\n      have \"\\<forall>x \\<in> classes (k+1) t (k+1). \\<forall>u < k + 1. x u = t\" unfolding classes_def by auto\n      have \"(\\<lambda>u. t) ` {..<k + 1} \\<subseteq> {..<t + 1}\" by auto\n      then have \"\\<exists>!y \\<in> cube (k+1) (t+1). (\\<forall>u < k + 1. y u = t)\" \n        using PiE_uniqueness[of \"(\\<lambda>u. t)\" \"{..<k+1}\" \"{..<t+1}\"] unfolding cube_def by auto\n      then have \"\\<exists>!y \\<in> classes (k+1) t (k+1). (\\<forall>u < k + 1. y u = t)\" \n        unfolding classes_def using classes_subset_cube[of \"k+1\" t \"k+1\"] by auto\n      then have \"\\<exists>!y. y \\<in> classes (k+1) t (k+1)\" \n        using \\<open>\\<forall>x \\<in> classes (k+1) t (k+1). \\<forall>u < k + 1. x u = t\\<close> by auto\n      have \"\\<exists>c<r. \\<forall>y \\<in> classes (k+1) t (k+1). \\<chi> (T y) = c\" \n      proof -\n        have \"\\<forall>y \\<in> classes (k+1) t (k+1). T y \\<in> cube (n+m) (t+1)\" using T_prop classes_subset_cube\n          by blast\n        then have \"\\<forall>y \\<in> classes (k+1) t (k+1). \\<chi> (T y) < r\" using \\<chi>_prop \n          unfolding n_def d_def using M'_prop by auto \n        then show \"\\<exists>c<r. \\<forall>y \\<in> classes (k+1) t (k+1). \\<chi> (T y) = c\" \n          using \\<open>\\<exists>!y. y \\<in> classes (k+1) t (k+1)\\<close> by blast\n      qed\n      then show \"\\<exists>c<r. \\<forall>x \\<in> T ` classes (k+1) t (k+1). \\<chi> x = c\" by blast\n    qed\n    ultimately have \"\\<exists>c<r. \\<forall>x \\<in> T ` classes (k+1) t i. \\<chi> x = c\" if \"i \\<le> k + 1\" for i \n      using that by (metis Suc_eq_plus1 le_Suc_eq)\n    then have \"\\<exists>c<r. \\<forall>x \\<in> classes (k+1) t i. \\<chi> (T x) = c\" if \"i \\<le> k + 1\" for i \n      using that by simp\n    then have \"layered_subspace T (k+1) (n + m) t r \\<chi>\" using subspace_T that(1) \\<open>n + m = M'\\<close> \n      unfolding layered_subspace_def by blast\n  \tthen show ?thesis using \\<open>n + m = M'\\<close> by blast \n  qed\n  then show ?thesis unfolding lhj_def \n    using m_props \n      exI[of \"\\<lambda>M. \\<forall>M'\\<ge>M. \\<forall>\\<chi>. \\<chi> \\<in> cube M' (t + 1)\n      \\<rightarrow>\\<^sub>E {..<r} \\<longrightarrow> (\\<exists>S. layered_subspace S (k + 1) M' t r\n      \\<chi>)\" m]\n    by blast\nqed\n\ntheorem hj_imp_lhj: \n  fixes k \n  assumes \"\\<And>r'. hj r' t\" \n  shows \"lhj r t k\"\nproof (induction k arbitrary: r rule: less_induct)\n  case (less k)\n  consider \"k = 0\" | \"k = 1\" | \"k \\<ge> 2\" by linarith\n  then show ?case\n  proof (cases)\n    case 1\n    then show ?thesis using dim0_layered_subspace_ex unfolding lhj_def by auto\n  next\n    case 2\n    then show ?thesis\n    proof (cases \"t > 0\")\n      case True\n      then show ?thesis using hj_imp_lhj_base[of \"t\"] assms 2 by blast\n    next\n      case False\n      then show ?thesis using assms unfolding hj_def lhj_def cube_def by fastforce\n    qed\n  next\n    case 3\n    note less\n    then show ?thesis\n    proof (cases \"t > 0 \\<and> r > 0\")\n    \tcase True\n    \tthen show ?thesis  using hj_imp_lhj_step[of t \"k-1\" r]\n    \t  using assms less.IH 3 One_nat_def Suc_pred by fastforce\n    next\n      case False\n      then consider \"t = 0\" | \"t > 0 \\<and> r = 0\" | \"t = 0 \\<and> r = 0\" by fastforce\n      then show ?thesis\n      proof cases\n        case 1\n        then show ?thesis using assms unfolding hj_def lhj_def cube_def by fastforce\n      next\n        case 2\n        then obtain N where N_props: \"N > 0\" \"\\<forall>N'\\<ge>N. \\<forall>\\<chi> \\<in> cube N' t\n        \\<rightarrow>\\<^sub>E {..<r}. (\\<exists>L c. c < r \\<and> is_line L N' t \\<and> (\\<forall>y\n        \\<in> L ` {..<t}. \\<chi> y = c))\" using assms[of r] unfolding hj_def by force\n        have \"cube N' (t + 1) \\<rightarrow>\\<^sub>E {..<r} = {}\" if \"N' \\<ge> N\" for N'\n        proof-\n          have \"cube N' t \\<noteq> {}\" using N_props(2) that 2 by fastforce  \n          then have \"cube N' (t + 1) \\<noteq> {}\" using cube_subset[of N' t] by blast\n          then show ?thesis using 2 by blast\n        qed\n        then show ?thesis unfolding lhj_def using N_props(1) by blast\n      next\n        case 3\n        then have \"(\\<exists>L c. c < r \\<and> is_line L N' t \\<and> (\\<forall>y \\<in> L ` {..<t}. \\<chi> y = c))\n        \\<Longrightarrow> False\" for N' \\<chi> by blast\n        then have False using assms 3 unfolding hj_def cube_def by fastforce\n        then show ?thesis by blast\n      qed\n\n    qed\n  qed\nqed\n\n\nsubsection \\<open>Theorem 5\\<close>\n\ntext \\<open>We provide a way to construct a monochromatic line in $C^n_{t + 1}$ from a $k$-dimensional $k$-coloured\nlayered subspace \\<open>S\\<close> in $C^n_{t + 1}$.\nThe idea is to rely on the fact that there are $k+1$ classes in \\<open>S\\<close>, but only $k$ colours. It thus follows\nfrom the Pigeonhole Principle that two classes must share the same colour. The way classes are defined allows for a\nstraightforward construction of a line with points only from those two classes. Thus we have our monochromatic\nline.\\<close>\ntheorem layered_subspace_to_mono_line: \n  assumes \"layered_subspace S k n t k \\<chi>\" \n    and \"t > 0\"  \n  shows \"(\\<exists>L. \\<exists>c<k. is_line L n (t+1) \\<and> (\\<forall>y \\<in> L ` {..<t+1}. \\<chi> y = c))\"\nproof-\n  define x where \"x \\<equiv> (\\<lambda>i\\<in>{..k}. \\<lambda>j\\<in>{..<k}. (if j < k - i then 0 else t))\"\n\n  have A: \"x i \\<in> cube k (t + 1)\" if \"i \\<le> k\" for i using that unfolding cube_def x_def by simp\n  then have \"S (x i) \\<in> cube n (t+1)\" if \"i \\<le> k\" for i using that assms(1) \n    unfolding layered_subspace_def is_subspace_def by fast\n\n  have \"\\<chi> \\<in> cube n (t + 1) \\<rightarrow>\\<^sub>E {..<k}\" using assms unfolding layered_subspace_def by linarith\n  then have \"\\<chi> ` (cube n (t+1)) \\<subseteq> {..<k}\" by blast\n  then have \"card (\\<chi> ` (cube n (t+1))) \\<le> card {..<k}\" \n    by (meson card_mono finite_lessThan)\n  then have *: \"card (\\<chi> ` (cube n (t+1))) \\<le> k\" by auto\n  have \"k > 0\" using assms(1) unfolding layered_subspace_def by auto\n  have \"inj_on x {..k}\"\n  proof -\n    have *:\"x i1 (k - i2) \\<noteq> x i2 (k - i2)\" if \"i1 \\<le> k\" \"i2 \\<le> k\" \"i1 \\<noteq> i2\" \"i1 < i2\" for i1 i2 \n      using that assms(2) unfolding x_def by auto \n    have \"\\<exists>j<k. x i1 j \\<noteq> x i2 j\" if \"i1 \\<le> k\" \"i2 \\<le> k\" \"i1 \\<noteq> i2\" for i1 i2\n    proof (cases \"i1 \\<le> i2\")\n      case True\n      then have \"k - i2 < k\" \n        using \\<open>0 < k\\<close> that(3) by linarith\n      then show ?thesis using that * \n        by (meson True nat_less_le)\n    next\n      case False\n      then have \"i2 < i1\" by simp\n      then show ?thesis using that *[of i2 i1] \\<open>k > 0\\<close>  \n        by (metis diff_less gr_implies_not0 le0 nat_less_le)\n    qed\n    then have \"x i1 \\<noteq> x i2\" if \"i1 \\<le> k\" \"i2 \\<le> k\" \"i1 \\<noteq> i2\" \"i1 < i2\" for i1 i2 using that \n      by fastforce\n    then show ?thesis unfolding inj_on_def  by (metis atMost_iff linorder_cases)\n  qed\n  then have \"card (x ` {..k}) = card {..k}\" using card_image by blast\n  then have B: \"card (x ` {..k}) = k+1\" by simp\n  have \"x ` {..k} \\<subseteq> cube k (t+1)\" using A by blast\n  then have \"S ` x ` {..k} \\<subseteq> S ` cube k (t+1)\" by fast\n  also have \"... \\<subseteq> cube n (t+1)\" \n    by (meson assms(1) layered_subspace_def subspace_elems_embed)\n  finally have \"S ` x ` {..k} \\<subseteq> cube n (t+1)\" by blast\n  then have \"\\<chi> ` S ` x ` {..k} \\<subseteq> \\<chi> ` cube n (t+1)\" by auto\n  then have \"card (\\<chi> ` S ` x ` {..k}) \\<le> card (\\<chi> ` cube n (t+1))\" \n    by (simp add: card_mono cube_def finite_PiE)\n  also have \" ... \\<le> k\" using * by blast\n  also have \" ... < k + 1\" by auto\n  also have \" ... = card {..k}\" by simp\n  also have \" ... = card (x ` {..k})\" using B by auto\n  also have \" ... = card (S ` x ` {..k})\" \n    using subspace_inj_on_cube[of S k n \"t+1\"] card_image[of S \"x ` {..k}\"] \n      inj_on_subset[of S \"cube k (t+1)\" \"x ` {..k}\"]  assms(1) \\<open>x ` {..k} \\<subseteq> cube k (t + 1)\\<close> \n    unfolding layered_subspace_def by simp\n  finally have \"card (\\<chi> ` S ` x ` {..k}) < card (S ` x ` {..k})\" by blast\n  then have \"\\<not>inj_on \\<chi> (S ` x ` {..k})\" using pigeonhole[of \\<chi> \"S ` x ` {..k}\"] by blast\n  then have \"\\<exists>a b. a \\<in> S ` x ` {..k} \\<and> b \\<in> S ` x ` {..k} \\<and> a \\<noteq> b \\<and> \\<chi> a =\n  \\<chi> b\" unfolding inj_on_def by auto\n  then obtain ax bx where ab_props: \"ax \\<in> S ` x ` {..k} \\<and> bx \\<in> S ` x ` {..k} \\<and> ax \\<noteq> bx \\<and>\n  \\<chi> ax = \\<chi> bx\" by blast\n  then have \"\\<exists>u v. u \\<in> {..k} \\<and> v \\<in> {..k} \\<and> u \\<noteq> v \\<and> \\<chi> (S (x u)) = \\<chi> (S (x\n  v))\" by blast\n  then obtain u v where uv_props: \"u \\<in> {..k} \\<and> v \\<in> {..k} \\<and> u < v \\<and> \\<chi> (S (x u)) \n    = \\<chi> (S (x v))\" by (metis linorder_cases)\n\n  let ?f = \"\\<lambda>s. (\\<lambda>i \\<in> {..<k}. if i < k - v then 0 else (if i < k - u then s else t))\"\n  define y where \"y \\<equiv> (\\<lambda>s \\<in> {..t}. S (?f s))\"\n\n  have line1: \"?f s \\<in> cube k (t+1)\" if \"s \\<le> t\" for s unfolding cube_def using that by auto\n\n  have f_cube: \"?f j \\<in> cube k (t+1)\" if \"j < t+1\" for j using line1 that by simp\n  have f_classes_u: \"?f j \\<in> classes k t u\" if j_prop: \"j < t\" for j\n    using that j_prop uv_props f_cube unfolding classes_def by auto\n  have f_classes_v: \"?f j \\<in> classes k t v\" if j_prop: \"j = t\" for j\n    using that j_prop uv_props assms(2) f_cube unfolding classes_def by auto\n\n  obtain B f where Bf_props: \"disjoint_family_on B {..k}\" \"\\<Union>(B ` {..k}) = {..<n}\" \"({} \\<notin> B ` {..<k})\" \n    \"f \\<in> (B k) \\<rightarrow>\\<^sub>E {..<t+1}\" \"S \\<in> (cube k (t+1)) \\<rightarrow>\\<^sub>E (cube n (t+1))\" \n    \"(\\<forall>y \\<in> cube k (t+1). (\\<forall>i \\<in> B k. S y i = f i) \\<and> (\\<forall>j<k. \\<forall>i \\<in> B j. \n      (S y) i = y j))\" \n      using assms(1) unfolding layered_subspace_def is_subspace_def by auto\n\n  have \"y \\<in> {..<t+1} \\<rightarrow>\\<^sub>E cube n (t+1)\" unfolding y_def using line1 \\<open>S ` cube k (t + 1)\n  \\<subseteq> cube n (t + 1)\\<close> by auto\n  moreover have \"(\\<forall>u<t+1. \\<forall>v<t+1. y u j = y v j) \\<or> (\\<forall>s<t+1. y s j = s)\" \n    if j_prop: \"j<n\" for j \n  proof-\n    show \"(\\<forall>u<t+1. \\<forall>v<t+1. y u j = y v j) \\<or> (\\<forall>s<t+1. y s j = s)\"\n    proof -\n      consider \"j \\<in> B k\" | \"\\<exists>ii<k. j \\<in> B ii\" using Bf_props(2) j_prop \n        by (metis UN_E atMost_iff le_neq_implies_less lessThan_iff)\n      then have \"y a j = y b j \\<or> y s j = s\" if \"a < t + 1\" \"b < t +1\" \"s < t +1\" for a b s\n      proof cases\n        case 1\n        then have \"y a j = S (?f a) j\" using that(1) unfolding y_def by auto\n        also have \" ... = f j\" using Bf_props(6) f_cube 1 that(1) by auto\n        also have \" ... = S (?f b) j\" using Bf_props(6) f_cube 1 that(2) by auto\n        also have \" ... = y b j\" using that(2) unfolding y_def by simp\n        finally show ?thesis by simp\n      next\n        case 2\n        then obtain ii where ii_prop:\" ii < k \\<and> j \\<in> B ii\" by blast\n        then consider \"ii < k - v\" | \"ii \\<ge> k - v \\<and> ii < k - u\" | \"ii \\<ge> k - u \\<and> ii < k\" using not_less\n          by blast\n        then show ?thesis\n        proof cases\n          case 1\n          then have \"y a j = S (?f a) j\" using that(1) unfolding y_def by auto\n          also have \" ... = (?f a) ii\" using Bf_props(6) f_cube that(1) ii_prop by auto\n          also have \" ... = 0\" using 1 by (simp add: ii_prop)\n          also have \" ... = (?f b) ii\" using 1 by (simp add: ii_prop)\n          also have \" ... = S (?f b) j\" using Bf_props(6) f_cube that(2) ii_prop by auto\n          also have \" ... = y b j\" using that(2) unfolding y_def by auto\n          finally show ?thesis by simp\n        next\n          case 2\n          then have \"y s j = S (?f s) j\" using that(3) unfolding y_def by auto\n          also have \" ... = (?f s) ii\" using Bf_props(6) f_cube that(3) ii_prop by auto\n          also have \" ... = s\" using 2 by (simp add: ii_prop)\n          finally show ?thesis by simp\n        next\n          case 3\n          then have \"y a j = S (?f a) j\" using that(1) unfolding y_def by auto\n          also have \" ... = (?f a) ii\" using Bf_props(6) f_cube that(1) ii_prop by auto\n          also have \" ... = t\" using 3 uv_props by auto\n          also have \" ... = (?f b) ii\" using 3 uv_props by auto\n          also have \" ... = S (?f b) j\" using Bf_props(6) f_cube that(2) ii_prop by auto\n          also have \" ... = y b j\" using that(2) unfolding y_def by auto\n          finally show ?thesis by simp\n        qed\n      qed\n      then show ?thesis by blast\n    qed\n  qed\n  moreover have \"\\<exists>j < n. \\<forall>s<t+1. y s j = s\"\n  proof -\n    have \"k > 0\" using uv_props by simp\n    have \"k - v < k\" using uv_props by auto\n    have \"k - v < k - u\" using uv_props by auto\n    then have \"B (k - v) \\<noteq> {}\" using Bf_props(3) uv_props by auto\n    then obtain j where j_prop: \"j \\<in> B (k - v) \\<and> j < n\" using Bf_props(2) uv_props by force\n    then have \"y s j = s\" if \"s<t+1\" for s\n    proof\n      have \"y s j = S (?f s) j\" using that unfolding y_def by auto\n      also have \" ... = (?f s) (k - v)\" using Bf_props(6) f_cube that j_prop \\<open>k - v < k\\<close> by fast\n      also have \" ... = s\" using that j_prop \\<open>k - v < k - u\\<close> by simp\n      finally show ?thesis .\n    qed\n    then show \"\\<exists>j < n. \\<forall>s<t+1. y s j = s\" using j_prop by blast\n  qed\n  ultimately have Z1: \"is_line y n (t+1)\" unfolding is_line_def by blast\n  moreover \n  {\n    have k_colour: \"\\<chi> e < k\" if \"e \\<in> y ` {..<t+1}\" for e \n      using \\<open>y \\<in> {..<t+1} \\<rightarrow>\\<^sub>E cube n (t + 1)\\<close> \\<open>\\<chi> \\<in> cube n (t + 1)\n      \\<rightarrow>\\<^sub>E {..<k}\\<close> that by auto\n    have \"\\<chi> e1 = \\<chi> e2 \\<and> \\<chi> e1 < k\" if \"e1 \\<in> y ` {..<t+1}\" \"e2 \\<in> y ` {..<t+1}\" for e1 e2 \n    proof  \n      from that obtain i1 i2 where i_props: \"i1 < t + 1\" \"i2 < t + 1\" \"e1 = y i1\" \"e2 = y i2\" by blast \n      from i_props(1,2) have \"\\<chi> (y i1) = \\<chi> (y i2)\"\n      proof (induction i1 i2 rule: linorder_wlog)\n        case (le a b)\n        then show ?case\n        proof (cases \"a = b\")\n          case True\n          then show ?thesis by blast\n        next\n          case False\n          then have \"a < b\" using le by linarith\n          then consider \"b = t\" | \"b < t\" using le.prems(2) by linarith\n          then show ?thesis\n          proof cases\n            case 1\n            then have \"y b \\<in> S ` classes k t v\" \n            proof -\n              have \"y b = S (?f b)\" unfolding y_def using \\<open>b = t\\<close> by auto\n              moreover have \"?f b \\<in> classes k t v\" using \\<open>b = t\\<close> f_classes_v by blast\n              ultimately show \"y b \\<in> S ` classes k t v\" by blast\n            qed\n            moreover have \"x u \\<in> classes k t u\"\n            proof -\n              have \"x u cord = t\" if \"cord \\<in> {k - u..<k}\" for cord using uv_props that unfolding x_def by simp \n              moreover \n              {  \n                have \"x u cord \\<noteq> t\" if \"cord \\<in> {..<k - u}\" for cord \n                  using uv_props that assms(2) unfolding x_def by auto\n                then have \"t \\<notin> x u ` {..<k - u}\" by blast\n              }\n              ultimately show \"x u \\<in> classes k t u\" unfolding classes_def \n                using \\<open>x ` {..k} \\<subseteq> cube k (t + 1)\\<close> uv_props by blast\n            qed\n            moreover have \"x v \\<in> classes k t v\"\n            proof -\n              have \"x v cord = t\" if \"cord \\<in> {k - v..<k}\" for cord using uv_props that unfolding x_def by simp \n              moreover \n              {  \n                have \"x v cord \\<noteq> t\" if \"cord \\<in> {..<k - v}\" for cord \n                  using uv_props that assms(2) unfolding x_def by auto\n                then have \"t \\<notin> x v ` {..<k - v}\" by blast\n              }\n              ultimately show \"x v \\<in> classes k t v\" unfolding classes_def \n                using \\<open>x ` {..k} \\<subseteq> cube k (t + 1)\\<close> uv_props by blast\n            qed\n            moreover have \"\\<chi> (y b) = \\<chi> (S (x v))\" \n              using assms(1) calculation(1, 3) unfolding layered_subspace_def by (metis imageE uv_props)\n            moreover have \"y a \\<in> S ` classes k t u\" \n            proof -\n              have \"y a = S (?f a)\" unfolding y_def using \\<open>a < b\\<close> 1 by simp\n              moreover have \"?f a \\<in> classes k t u\" using \\<open>a < b\\<close> 1 f_classes_u by blast\n              ultimately show \"y a \\<in> S ` classes k t u\" by blast\n            qed\n            moreover have \"\\<chi> (y a) = \\<chi> (S (x u))\" using assms(1) calculation(2, 5) \n              unfolding layered_subspace_def by (metis imageE uv_props)\n            ultimately have \"\\<chi> (y a) = \\<chi> (y b)\" using uv_props by simp\n            then show ?thesis by blast\n          next\n            case 2\n            then have \"a < t\" using \\<open>a < b\\<close> less_trans by blast\n            then have \"y a \\<in> S ` classes k t u\"\n            proof -\n              have \"y a = S (?f a)\" unfolding y_def using \\<open>a < t\\<close> by auto\n              moreover have \"?f a \\<in> classes k t u\" using \\<open>a < t\\<close> f_classes_u by blast\n              ultimately show \"y a \\<in> S ` classes k t u\" by blast\n            qed\n            moreover have \"y b \\<in> S ` classes k t u\"\n            proof -\n              have \"y b = S (?f b)\" unfolding y_def using \\<open>b < t\\<close> by auto\n              moreover have \"?f b \\<in> classes k t u\" using \\<open>b < t\\<close> f_classes_u by blast\n              ultimately show \"y b \\<in> S ` classes k t u\" by blast\n            qed\n            ultimately have \"\\<chi> (y a) = \\<chi> (y b)\" using assms(1) uv_props unfolding layered_subspace_def \n              by (metis imageE)\n            then show ?thesis by blast\n          qed\n        qed\n      next\n        case (sym a b)\n        then show ?case by presburger\n      qed\n      then show \"\\<chi> e1 = \\<chi> e2\" using i_props(3,4) by blast\n    qed (use that(1) k_colour in blast)\n    then have Z2: \"\\<exists>c < k. \\<forall>e \\<in> y ` {..<t+1}. \\<chi> e = c\"\n      by (meson image_eqI lessThan_iff less_add_one)\n  }\n  ultimately show \"\\<exists>L c. c < k \\<and> is_line L n (t + 1) \\<and> (\\<forall>y\\<in>L ` {..<t + 1}. \\<chi> y = c)\" \n    by blast\n\nqed\n\nsubsection \\<open>Corollary 6\\<close>\ncorollary lhj_imp_hj: \n  assumes \"(\\<And>r k. lhj r t k)\" \n    and \"t>0\" \n  shows \"(hj r (t+1))\"\n  using assms(1)[of r r] assms(2) unfolding lhj_def hj_def using layered_subspace_to_mono_line[of _ r _ t] by metis\n\nsubsection \\<open>Main result\\<close>\n\nsubsubsection \\<open>Edge cases and auxiliary lemmas\\<close>\nlemma single_point_line: \n  assumes \"N > 0\" \n  shows \"is_line (\\<lambda>s\\<in>{..<1}. \\<lambda>a\\<in>{..<N}. 0) N 1\"\n  using assms unfolding is_line_def cube_def by auto\n\nlemma single_point_line_is_monochromatic: \n  assumes \"\\<chi> \\<in> cube N 1 \\<rightarrow>\\<^sub>E {..<r}\" \"N > 0\" \n  shows \"(\\<exists>c < r. is_line (\\<lambda>s\\<in>{..<1}. \\<lambda>a\\<in>{..<N}. 0) N 1 \\<and> (\\<forall>i \\<in>\n  (\\<lambda>s\\<in>{..<1}. \\<lambda>a\\<in>{..<N}. 0) ` {..<1}. \\<chi> i = c))\"\nproof -\n  have \"is_line (\\<lambda>s\\<in>{..<1}. \\<lambda>a\\<in>{..<N}. 0) N 1\" using assms(2) single_point_line by blast\n  moreover have \"\\<exists>c < r. \\<chi> ((\\<lambda>s\\<in>{..<1}. \\<lambda>a\\<in>{..<N}. 0) j) = c\" \n    if \"(j::nat) < 1\" for j using assms line_points_in_cube calculation that unfolding cube_def by blast\n  ultimately show ?thesis by auto\nqed\n\n\nlemma hj_r_nonzero_t_0: \n  assumes \"r > 0\" \n  shows \"hj r 0\"\nproof-\n  have \"(\\<exists>L c. c < r \\<and> is_line L N' 0 \\<and> (\\<forall>y \\<in> L ` {..<0::nat}. \\<chi> y = c))\" \n    if \"N' \\<ge> 1\" \"\\<chi> \\<in> cube N' 0 \\<rightarrow>\\<^sub>E {..<r}\" for N' \\<chi> using assms is_line_def that(1) by fastforce\n  then show ?thesis unfolding hj_def by auto\nqed\n\ntext \\<open>Any cube over 1 element always has a single point, which also forms the only line in the cube. Since it's a\nsingle point line, it's trivially monochromatic. We show the result for dimension 1.\\<close>\nlemma hj_t_1: \"hj r 1\"\n  unfolding hj_def \nproof-\n  let ?N = 1\n  have \"\\<exists>L c. c < r \\<and> is_line L N' 1 \\<and> (\\<forall>y\\<in>L ` {..<1}. \\<chi> y = c)\" if \"N' \\<ge> ?N\" \"\\<chi> \\<in> cube N' 1 \\<rightarrow>\\<^sub>E {..<r}\" for N' \\<chi> \n    using single_point_line_is_monochromatic[of \\<chi> N' r] that by force\n  then show \"\\<exists>N>0. \\<forall>N'\\<ge>N. \\<forall>\\<chi>. \\<chi> \\<in> cube N' 1 \\<rightarrow>\\<^sub>E {..<r} \\<longrightarrow> (\\<exists>L c. c < r \\<and> is_line L N' 1 \\<and> (\\<forall>y\\<in>L ` {..<1}. \\<chi> y = c))\" \n    by blast\nqed\n\nsubsubsection \\<open>Main theorem\\<close>\ntext \\<open>We state the main result \\<^prop>\\<open>hj r t\\<close>. The explanation for the choice of assumption is\noffered subsequently.\\<close>\ntheorem hales_jewett:\n  assumes \"\\<not>(r = 0 \\<and> t = 0)\" \n  shows \"hj r t\"\n  using assms\nproof (induction t arbitrary: r)\n  case 0\n  then show ?case using hj_r_nonzero_t_0[of r] by blast\nnext\n  case (Suc t)\n  then show ?case using hj_t_1[of r] hj_imp_lhj[of t] lhj_imp_hj[of t r] by auto\nqed\ntext \\<open>We offer a justification for having excluded the special case $r = t = 0$ from the statement of the main\ntheorem \\<open>hales_jewett\\<close>. The exclusion is a consequence of the fact that colourings are defined as members\nof the function set \\<open>cube n t \\<rightarrow>\\<^sub>E {..<r}\\<close>, which for $r = t = 0$ means there's a dummy\ncolouring \\<^term>\\<open>\\<lambda>x. undefined\\<close>, even though \\<^prop>\\<open>cube n 0 = {}\\<close> for $n > 0$.\nHence, in this case, no line exists at all (let alone one monochromatic under the aforementioned colouring). This means\n\\<^prop>\\<open>hj 0 0 \\<Longrightarrow> False\\<close>---but only because of the quirky behaviour of the FuncSet\n\\<open>cube n t \\<rightarrow>\\<^sub>E {..<r}\\<close>. This could have been circumvented by letting colourings $\\chi$ be\narbitrary functions constraint only by \\<^prop>\\<open>\\<chi> ` cube n t \\<subseteq> {..<r}\\<close>. We avoided this in\norder to have consistency with the cube's definition, for which FuncSets were crucial because the proof heavily relies\non arguments about the cardinality of the cube. he constraint \\<^prop>\\<open>x ` {..<n} \\<subseteq> {..<t}\\<close> for\nelements \\<open>x\\<close> of $C^n_t$ would not have sufficed there, as there are infinitely many functions over the\nnaturals satisfying it.\\<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/Hales_Jewett/Hales_Jewett.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8519528019683105, "lm_q2_score": 0.8221891392358015, "lm_q1q2_score": 0.7004663409198545}}
{"text": "section \\<open>Cauchy's Integral Formula\\<close>\ntheory Cauchy_Integral_Formula\n  imports Winding_Numbers\nbegin\n\nsubsection\\<open>Proof\\<close>\n\nlemma Cauchy_integral_formula_weak:\n    assumes S: \"convex S\" and \"finite k\" and conf: \"continuous_on S f\"\n        and fcd: \"(\\<And>x. x \\<in> interior S - k \\<Longrightarrow> f field_differentiable at x)\"\n        and z: \"z \\<in> interior S - k\" and vpg: \"valid_path \\<gamma>\"\n        and pasz: \"path_image \\<gamma> \\<subseteq> S - {z}\" and loop: \"pathfinish \\<gamma> = pathstart \\<gamma>\"\n      shows \"((\\<lambda>w. f w / (w - z)) has_contour_integral (2*pi * \\<i> * winding_number \\<gamma> z * f z)) \\<gamma>\"\nproof -\n  let ?fz = \"\\<lambda>w. (f w - f z)/(w - z)\"\n  obtain f' where f': \"(f has_field_derivative f') (at z)\"\n    using fcd [OF z] by (auto simp: field_differentiable_def)\n  have pas: \"path_image \\<gamma> \\<subseteq> S\" and znotin: \"z \\<notin> path_image \\<gamma>\" using pasz by blast+\n  have c: \"continuous (at x within S) (\\<lambda>w. if w = z then f' else (f w - f z) / (w - z))\" if \"x \\<in> S\" for x\n  proof (cases \"x = z\")\n    case True then show ?thesis\n      using LIM_equal [of \"z\" ?fz \"\\<lambda>w. if w = z then f' else ?fz w\"] has_field_derivativeD [OF f'] \n      by (force simp add: continuous_within Lim_at_imp_Lim_at_within)\n  next\n    case False\n    then have dxz: \"dist x z > 0\" by auto\n    have cf: \"continuous (at x within S) f\"\n      using conf continuous_on_eq_continuous_within that by blast\n    have \"continuous (at x within S) (\\<lambda>w. (f w - f z) / (w - z))\"\n      by (rule cf continuous_intros | simp add: False)+\n    then show ?thesis\n      using continuous_transform_within [OF _ dxz that] by (force simp: dist_commute)\n  qed\n  have fink': \"finite (insert z k)\" using \\<open>finite k\\<close> by blast\n  have *: \"((\\<lambda>w. if w = z then f' else ?fz w) has_contour_integral 0) \\<gamma>\"\n  proof (rule Cauchy_theorem_convex [OF _ S fink' _ vpg pas loop])\n    show \"(\\<lambda>w. if w = z then f' else ?fz w) field_differentiable at w\" \n      if \"w \\<in> interior S - insert z k\" for w\n    proof (rule field_differentiable_transform_within)\n      show \"(\\<lambda>w. ?fz w) field_differentiable at w\"\n        using that by (intro derivative_intros fcd; simp)\n    qed (use that in \\<open>auto simp add: dist_pos_lt dist_commute\\<close>)\n  qed (use c in \\<open>force simp: continuous_on_eq_continuous_within\\<close>)\n  show ?thesis\n    apply (rule has_contour_integral_eq)\n    using znotin has_contour_integral_add [OF has_contour_integral_lmul [OF has_contour_integral_winding_number [OF vpg znotin], of \"f z\"] *]\n    apply (auto simp: ac_simps divide_simps)\n    done\nqed\n\ntheorem Cauchy_integral_formula_convex_simple:\n  assumes \"convex S\" and holf: \"f holomorphic_on S\" and \"z \\<in> interior S\" \"valid_path \\<gamma>\" \"path_image \\<gamma> \\<subseteq> S - {z}\"\n      \"pathfinish \\<gamma> = pathstart \\<gamma>\"\n    shows \"((\\<lambda>w. f w / (w - z)) has_contour_integral (2*pi * \\<i> * winding_number \\<gamma> z * f z)) \\<gamma>\"\nproof -\n  have \"\\<And>x. x \\<in> interior S \\<Longrightarrow> f field_differentiable at x\"\n    using holf at_within_interior holomorphic_onD interior_subset by fastforce\n  then show ?thesis\n    using assms\n    by (intro Cauchy_integral_formula_weak [where k = \"{}\"]) (auto simp: holomorphic_on_imp_continuous_on)\nqed\n\ntext\\<open> Hence the Cauchy formula for points inside a circle.\\<close>\n\ntheorem Cauchy_integral_circlepath:\n  assumes contf: \"continuous_on (cball z r) f\" and holf: \"f holomorphic_on (ball z r)\" and wz: \"norm(w - z) < r\"\n  shows \"((\\<lambda>u. f u/(u - w)) has_contour_integral (2 * of_real pi * \\<i> * f w))\n         (circlepath z r)\"\nproof -\n  have \"r > 0\"\n    using assms le_less_trans norm_ge_zero by blast\n  have \"((\\<lambda>u. f u / (u - w)) has_contour_integral (2 * pi) * \\<i> * winding_number (circlepath z r) w * f w)\n        (circlepath z r)\"\n  proof (rule Cauchy_integral_formula_weak [where S = \"cball z r\" and k = \"{}\"])\n    show \"\\<And>x. x \\<in> interior (cball z r) - {} \\<Longrightarrow>\n         f field_differentiable at x\"\n      using holf holomorphic_on_imp_differentiable_at by auto\n    have \"w \\<notin> sphere z r\"\n      by simp (metis dist_commute dist_norm not_le order_refl wz)\n    then show \"path_image (circlepath z r) \\<subseteq> cball z r - {w}\"\n      using \\<open>r > 0\\<close> by (auto simp add: cball_def sphere_def)\n  qed (use wz in \\<open>simp_all add: dist_norm norm_minus_commute contf\\<close>)\n  then show ?thesis\n    by (simp add: winding_number_circlepath assms)\nqed\n\ncorollary\\<^marker>\\<open>tag unimportant\\<close> Cauchy_integral_circlepath_simple:\n  assumes \"f holomorphic_on cball z r\" \"norm(w - z) < r\"\n  shows \"((\\<lambda>u. f u/(u - w)) has_contour_integral (2 * of_real pi * \\<i> * f w))\n         (circlepath z r)\"\nusing assms by (force simp: holomorphic_on_imp_continuous_on holomorphic_on_subset Cauchy_integral_circlepath)\n\nsubsection\\<^marker>\\<open>tag unimportant\\<close> \\<open>General stepping result for derivative formulas\\<close>\n\nlemma Cauchy_next_derivative:\n  assumes \"continuous_on (path_image \\<gamma>) f'\"\n      and leB: \"\\<And>t. t \\<in> {0..1} \\<Longrightarrow> norm (vector_derivative \\<gamma> (at t)) \\<le> B\"\n      and int: \"\\<And>w. w \\<in> S - path_image \\<gamma> \\<Longrightarrow> ((\\<lambda>u. f' u / (u - w)^k) has_contour_integral f w) \\<gamma>\"\n      and k: \"k \\<noteq> 0\"\n      and \"open S\"\n      and \\<gamma>: \"valid_path \\<gamma>\"\n      and w: \"w \\<in> S - path_image \\<gamma>\"\n    shows \"(\\<lambda>u. f' u / (u - w)^(Suc k)) contour_integrable_on \\<gamma>\"\n      and \"(f has_field_derivative (k * contour_integral \\<gamma> (\\<lambda>u. f' u/(u - w)^(Suc k))))\n           (at w)\"  (is \"?thes2\")\nproof -\n  have \"open (S - path_image \\<gamma>)\" using \\<open>open S\\<close> closed_valid_path_image \\<gamma> by blast\n  then obtain d where \"d>0\" and d: \"ball w d \\<subseteq> S - path_image \\<gamma>\" using w\n    using open_contains_ball by blast\n  have [simp]: \"\\<And>n. cmod (1 + of_nat n) = 1 + of_nat n\"\n    by (metis norm_of_nat of_nat_Suc)\n  have cint: \"\\<And>x. \\<lbrakk>x \\<noteq> w; cmod (x - w) < d\\<rbrakk>\n         \\<Longrightarrow> (\\<lambda>z. (f' z / (z - x) ^ k - f' z / (z - w) ^ k) / (x * k - w * k)) contour_integrable_on \\<gamma>\"\n    using int w d\n    apply (intro contour_integrable_div contour_integrable_diff has_contour_integral_integrable)\n    by (force simp: dist_norm norm_minus_commute)\n  have 1: \"\\<forall>\\<^sub>F n in at w. (\\<lambda>x. f' x * (inverse (x - n) ^ k - inverse (x - w) ^ k) / (n - w) / of_nat k)\n                         contour_integrable_on \\<gamma>\"\n    unfolding eventually_at\n    apply (rule_tac x=d in exI)\n    apply (simp add: \\<open>d > 0\\<close> dist_norm field_simps cint)\n    done\n  have bim_g: \"bounded (image f' (path_image \\<gamma>))\"\n    by (simp add: compact_imp_bounded compact_continuous_image compact_valid_path_image assms)\n  then obtain C where \"C > 0\" and C: \"\\<And>x. \\<lbrakk>0 \\<le> x; x \\<le> 1\\<rbrakk> \\<Longrightarrow> cmod (f' (\\<gamma> x)) \\<le> C\"\n    by (force simp: bounded_pos path_image_def)\n  have twom: \"\\<forall>\\<^sub>F n in at w.\n               \\<forall>x\\<in>path_image \\<gamma>.\n                cmod ((inverse (x - n) ^ k - inverse (x - w) ^ k) / (n - w) / k - inverse (x - w) ^ Suc k) < e\"\n         if \"0 < e\" for e\n  proof -\n    have *: \"cmod ((inverse (x - u) ^ k - inverse (x - w) ^ k) / ((u - w) * k) - inverse (x - w) ^ Suc k)   < e\"\n            if x: \"x \\<in> path_image \\<gamma>\" and \"u \\<noteq> w\" and uwd: \"cmod (u - w) < d/2\"\n                and uw_less: \"cmod (u - w) < e * (d/2) ^ (k+2) / (1 + real k)\"\n            for u x\n    proof -\n      define ff where [abs_def]:\n        \"ff n w =\n          (if n = 0 then inverse(x - w)^k\n           else if n = 1 then k / (x - w)^(Suc k)\n           else (k * of_real(Suc k)) / (x - w)^(k + 2))\" for n :: nat and w\n      have km1: \"\\<And>z::complex. z \\<noteq> 0 \\<Longrightarrow> z ^ (k - Suc 0) = z ^ k / z\"\n        by (simp add: field_simps) (metis Suc_pred \\<open>k \\<noteq> 0\\<close> neq0_conv power_Suc)\n      have ff1: \"(ff i has_field_derivative ff (Suc i) z) (at z within ball w (d/2))\"\n              if \"z \\<in> ball w (d/2)\" \"i \\<le> 1\" for i z\n      proof -\n        have \"z \\<notin> path_image \\<gamma>\"\n          using \\<open>x \\<in> path_image \\<gamma>\\<close> d that ball_divide_subset_numeral by blast\n        then have xz[simp]: \"x \\<noteq> z\" using \\<open>x \\<in> path_image \\<gamma>\\<close> by blast\n        then have neq: \"x * x + z * z \\<noteq> x * (z * 2)\"\n          by (blast intro: dest!: sum_sqs_eq)\n        with xz have \"\\<And>v. v \\<noteq> 0 \\<Longrightarrow> (x * x + z * z) * v \\<noteq> (x * (z * 2) * v)\" by auto\n        then have neqq: \"\\<And>v. v \\<noteq> 0 \\<Longrightarrow> x * (x * v) + z * (z * v) \\<noteq> x * (z * (2 * v))\"\n          by (simp add: algebra_simps)\n        show ?thesis using \\<open>i \\<le> 1\\<close>\n          apply (simp add: ff_def dist_norm Nat.le_Suc_eq km1, safe)\n          apply (rule derivative_eq_intros | simp add: km1 | simp add: field_simps neq neqq)+\n          done\n      qed\n      { fix a::real and b::real assume ab: \"a > 0\" \"b > 0\"\n        then have \"k * (1 + real k) * (1 / a) \\<le> k * (1 + real k) * (4 / b) \\<longleftrightarrow> b \\<le> 4 * a\"\n          by (subst mult_le_cancel_left_pos)\n            (use \\<open>k \\<noteq> 0\\<close> in \\<open>auto simp: divide_simps\\<close>)\n        with ab have \"real k * (1 + real k) / a \\<le> (real k * 4 + real k * real k * 4) / b \\<longleftrightarrow> b \\<le> 4 * a\"\n          by (simp add: field_simps)\n      } note canc = this\n      have ff2: \"cmod (ff (Suc 1) v) \\<le> real (k * (k + 1)) / (d/2) ^ (k + 2)\"\n                if \"v \\<in> ball w (d/2)\" for v\n      proof -\n        have lessd: \"\\<And>z. cmod (\\<gamma> z - v) < d/2 \\<Longrightarrow> cmod (w - \\<gamma> z) < d\"\n          by (metis that norm_minus_commute norm_triangle_half_r dist_norm mem_ball)\n        have \"d/2 \\<le> cmod (x - v)\" using d x that\n          using lessd d x\n          by (auto simp add: dist_norm path_image_def ball_def not_less [symmetric] del: divide_const_simps)\n        then have \"d \\<le> cmod (x - v) * 2\"\n          by (simp add: field_split_simps)\n        then have dpow_le: \"d ^ (k+2) \\<le> (cmod (x - v) * 2) ^ (k+2)\"\n          using \\<open>0 < d\\<close> order_less_imp_le power_mono by blast\n        have \"x \\<noteq> v\" using that\n          using \\<open>x \\<in> path_image \\<gamma>\\<close> ball_divide_subset_numeral d by fastforce\n        then show ?thesis\n        using \\<open>d > 0\\<close> apply (simp add: ff_def norm_mult norm_divide norm_power dist_norm canc)\n        using dpow_le apply (simp add: field_split_simps)\n        done\n      qed\n      have ub: \"u \\<in> ball w (d/2)\"\n        using uwd by (simp add: dist_commute dist_norm)\n      have \"cmod (inverse (x - u) ^ k - (inverse (x - w) ^ k + of_nat k * (u - w) / ((x - w) * (x - w) ^ k)))\n                  \\<le> (real k * 4 + real k * real k * 4) * (cmod (u - w) * cmod (u - w)) / (d * (d * (d/2) ^ k))\"\n        using complex_Taylor [OF _ ff1 ff2 _ ub, of w, simplified]\n        by (simp add: ff_def \\<open>0 < d\\<close>)\n      then have \"cmod (inverse (x - u) ^ k - (inverse (x - w) ^ k + of_nat k * (u - w) / ((x - w) * (x - w) ^ k)))\n                  \\<le> (cmod (u - w) * real k) * (1 + real k) * cmod (u - w) / (d/2) ^ (k+2)\"\n        by (simp add: field_simps)\n      then have \"cmod (inverse (x - u) ^ k - (inverse (x - w) ^ k + of_nat k * (u - w) / ((x - w) * (x - w) ^ k)))\n                 / (cmod (u - w) * real k)\n                  \\<le> (1 + real k) * cmod (u - w) / (d/2) ^ (k+2)\"\n        using \\<open>k \\<noteq> 0\\<close> \\<open>u \\<noteq> w\\<close> by (simp add: mult_ac zero_less_mult_iff pos_divide_le_eq)\n      also have \"\\<dots> < e\"\n        using uw_less \\<open>0 < d\\<close> by (simp add: mult_ac divide_simps)\n      finally have e: \"cmod (inverse (x-u)^k - (inverse (x-w)^k + of_nat k * (u-w) / ((x-w) * (x-w)^k)))\n                        / cmod ((u - w) * real k)   <   e\"\n        by (simp add: norm_mult)\n      have \"x \\<noteq> u\"\n        using uwd \\<open>0 < d\\<close> x d by (force simp: dist_norm ball_def norm_minus_commute)\n      show ?thesis\n        apply (rule le_less_trans [OF _ e])\n        using \\<open>k \\<noteq> 0\\<close> \\<open>x \\<noteq> u\\<close> \\<open>u \\<noteq> w\\<close>\n        apply (simp add: field_simps norm_divide [symmetric])\n        done\n    qed\n    show ?thesis\n      unfolding eventually_at\n      apply (rule_tac x = \"min (d/2) ((e*(d/2)^(k + 2))/(Suc k))\" in exI)\n      apply (force simp: \\<open>d > 0\\<close> dist_norm that simp del: power_Suc intro: *)\n      done\n  qed\n  have 2: \"uniform_limit (path_image \\<gamma>) (\\<lambda>n x. f' x * (inverse (x - n) ^ k - inverse (x - w) ^ k) / (n - w) / of_nat k) (\\<lambda>x. f' x / (x - w) ^ Suc k) (at w)\"\n    unfolding uniform_limit_iff dist_norm\n  proof clarify\n    fix e::real\n    assume \"0 < e\"\n    have *: \"cmod (f' (\\<gamma> x) * (inverse (\\<gamma> x - u) ^ k - inverse (\\<gamma> x - w) ^ k) / ((u - w) * k) -\n                        f' (\\<gamma> x) / ((\\<gamma> x - w) * (\\<gamma> x - w) ^ k)) < e\"\n              if ec: \"cmod ((inverse (\\<gamma> x - u) ^ k - inverse (\\<gamma> x - w) ^ k) / ((u - w) * k) -\n                      inverse (\\<gamma> x - w) * inverse (\\<gamma> x - w) ^ k) < e / C\"\n                 and x: \"0 \\<le> x\" \"x \\<le> 1\"\n              for u x\n    proof (cases \"(f' (\\<gamma> x)) = 0\")\n      case True then show ?thesis by (simp add: \\<open>0 < e\\<close>)\n    next\n      case False\n      have \"cmod (f' (\\<gamma> x) * (inverse (\\<gamma> x - u) ^ k - inverse (\\<gamma> x - w) ^ k) / ((u - w) * k) -\n                        f' (\\<gamma> x) / ((\\<gamma> x - w) * (\\<gamma> x - w) ^ k)) =\n            cmod (f' (\\<gamma> x) * ((inverse (\\<gamma> x - u) ^ k - inverse (\\<gamma> x - w) ^ k) / ((u - w) * k) -\n                             inverse (\\<gamma> x - w) * inverse (\\<gamma> x - w) ^ k))\"\n        by (simp add: field_simps)\n      also have \"\\<dots> = cmod (f' (\\<gamma> x)) *\n                       cmod ((inverse (\\<gamma> x - u) ^ k - inverse (\\<gamma> x - w) ^ k) / ((u - w) * k) -\n                             inverse (\\<gamma> x - w) * inverse (\\<gamma> x - w) ^ k)\"\n        by (simp add: norm_mult)\n      also have \"\\<dots> < cmod (f' (\\<gamma> x)) * (e/C)\"\n        using False mult_strict_left_mono [OF ec] by force\n      also have \"\\<dots> \\<le> e\" using C\n        by (metis False \\<open>0 < e\\<close> frac_le less_eq_real_def mult.commute pos_le_divide_eq x zero_less_norm_iff)\n      finally show ?thesis .\n    qed\n    show \"\\<forall>\\<^sub>F n in at w.\n              \\<forall>x\\<in>path_image \\<gamma>.\n               cmod (f' x * (inverse (x - n) ^ k - inverse (x - w) ^ k) / (n - w) / of_nat k - f' x / (x - w) ^ Suc k) < e\"\n      using twom [OF divide_pos_pos [OF \\<open>0 < e\\<close> \\<open>C > 0\\<close>]]   unfolding path_image_def\n      by (force intro: * elim: eventually_mono)\n  qed\n  show \"(\\<lambda>u. f' u / (u - w) ^ (Suc k)) contour_integrable_on \\<gamma>\"\n    by (rule contour_integral_uniform_limit [OF 1 2 leB \\<gamma>]) auto\n  have *: \"(\\<lambda>n. contour_integral \\<gamma> (\\<lambda>x. f' x * (inverse (x - n) ^ k - inverse (x - w) ^ k) / (n - w) / k))\n           \\<midarrow>w\\<rightarrow> contour_integral \\<gamma> (\\<lambda>u. f' u / (u - w) ^ (Suc k))\"\n    by (rule contour_integral_uniform_limit [OF 1 2 leB \\<gamma>]) auto\n  have **: \"contour_integral \\<gamma> (\\<lambda>x. f' x * (inverse (x - u) ^ k - inverse (x - w) ^ k) / ((u - w) * k)) =\n              (f u - f w) / (u - w) / k\"\n    if \"dist u w < d\" for u\n  proof -\n    have u: \"u \\<in> S - path_image \\<gamma>\"\n      by (metis subsetD d dist_commute mem_ball that)\n    have \\<section>: \"((\\<lambda>x. f' x * inverse (x - u) ^ k) has_contour_integral f u) \\<gamma>\"\n            \"((\\<lambda>x. f' x * inverse (x - w) ^ k) has_contour_integral f w) \\<gamma>\"\n      using u w by (simp_all add: field_simps int)\n    show ?thesis\n      apply (rule contour_integral_unique)\n      apply (simp add: diff_divide_distrib algebra_simps \\<section> has_contour_integral_diff has_contour_integral_div)\n      done\n  qed\n  show ?thes2\n    apply (simp add: has_field_derivative_iff del: power_Suc)\n    apply (rule Lim_transform_within [OF tendsto_mult_left [OF *] \\<open>0 < d\\<close> ])\n    apply (simp add: \\<open>k \\<noteq> 0\\<close> **)\n    done\nqed\n\nlemma Cauchy_next_derivative_circlepath:\n  assumes contf: \"continuous_on (path_image (circlepath z r)) f\"\n      and int: \"\\<And>w. w \\<in> ball z r \\<Longrightarrow> ((\\<lambda>u. f u / (u - w)^k) has_contour_integral g w) (circlepath z r)\"\n      and k: \"k \\<noteq> 0\"\n      and w: \"w \\<in> ball z r\"\n    shows \"(\\<lambda>u. f u / (u - w)^(Suc k)) contour_integrable_on (circlepath z r)\"\n           (is \"?thes1\")\n      and \"(g has_field_derivative (k * contour_integral (circlepath z r) (\\<lambda>u. f u/(u - w)^(Suc k)))) (at w)\"\n           (is \"?thes2\")\nproof -\n  have \"r > 0\" using w\n    using ball_eq_empty by fastforce\n  have wim: \"w \\<in> ball z r - path_image (circlepath z r)\"\n    using w by (auto simp: dist_norm)\n  show ?thes1 ?thes2\n    by (rule Cauchy_next_derivative [OF contf _ int k open_ball valid_path_circlepath wim, where B = \"2 * pi * \\<bar>r\\<bar>\"];\n        auto simp: vector_derivative_circlepath norm_mult)+\nqed\n\n\ntext\\<open> In particular, the first derivative formula.\\<close>\n\nlemma Cauchy_derivative_integral_circlepath:\n  assumes contf: \"continuous_on (cball z r) f\"\n      and holf: \"f holomorphic_on ball z r\"\n      and w: \"w \\<in> ball z r\"\n    shows \"(\\<lambda>u. f u/(u - w)^2) contour_integrable_on (circlepath z r)\"\n           (is \"?thes1\")\n      and \"(f has_field_derivative (1 / (2 * of_real pi * \\<i>) * contour_integral(circlepath z r) (\\<lambda>u. f u / (u - w)^2))) (at w)\"\n           (is \"?thes2\")\nproof -\n  have [simp]: \"r \\<ge> 0\" using w\n    using ball_eq_empty by fastforce\n  have f: \"continuous_on (path_image (circlepath z r)) f\"\n    by (rule continuous_on_subset [OF contf]) (force simp: cball_def sphere_def)\n  have int: \"\\<And>w. dist z w < r \\<Longrightarrow>\n                 ((\\<lambda>u. f u / (u - w)) has_contour_integral (\\<lambda>x. 2 * of_real pi * \\<i> * f x) w) (circlepath z r)\"\n    by (rule Cauchy_integral_circlepath [OF contf holf]) (simp add: dist_norm norm_minus_commute)\n  show ?thes1\n    apply (simp add: power2_eq_square)\n    apply (rule Cauchy_next_derivative_circlepath [OF f _ _ w, where k=1, simplified])\n    apply (blast intro: int)\n    done\n  have \"((\\<lambda>x. 2 * of_real pi * \\<i> * f x) has_field_derivative contour_integral (circlepath z r) (\\<lambda>u. f u / (u - w)^2)) (at w)\"\n    apply (simp add: power2_eq_square)\n    apply (rule Cauchy_next_derivative_circlepath [OF f _ _ w, where k=1 and g = \"\\<lambda>x. 2 * of_real pi * \\<i> * f x\", simplified])\n    apply (blast intro: int)\n    done\n  then have fder: \"(f has_field_derivative contour_integral (circlepath z r) (\\<lambda>u. f u / (u - w)^2) / (2 * of_real pi * \\<i>)) (at w)\"\n    by (rule DERIV_cdivide [where f = \"\\<lambda>x. 2 * of_real pi * \\<i> * f x\" and c = \"2 * of_real pi * \\<i>\", simplified])\n  show ?thes2\n    by simp (rule fder)\nqed\n\nsubsection\\<open>Existence of all higher derivatives\\<close>\n\nproposition derivative_is_holomorphic:\n  assumes \"open S\"\n      and fder: \"\\<And>z. z \\<in> S \\<Longrightarrow> (f has_field_derivative f' z) (at z)\"\n    shows \"f' holomorphic_on S\"\nproof -\n  have *: \"\\<exists>h. (f' has_field_derivative h) (at z)\" if \"z \\<in> S\" for z\n  proof -\n    obtain r where \"r > 0\" and r: \"cball z r \\<subseteq> S\"\n      using open_contains_cball \\<open>z \\<in> S\\<close> \\<open>open S\\<close> by blast\n    then have holf_cball: \"f holomorphic_on cball z r\"\n      unfolding holomorphic_on_def\n      using field_differentiable_at_within field_differentiable_def fder by fastforce\n    then have \"continuous_on (path_image (circlepath z r)) f\"\n      using \\<open>r > 0\\<close> by (force elim: holomorphic_on_subset [THEN holomorphic_on_imp_continuous_on])\n    then have contfpi: \"continuous_on (path_image (circlepath z r)) (\\<lambda>x. 1/(2 * of_real pi*\\<i>) * f x)\"\n      by (auto intro: continuous_intros)+\n    have contf_cball: \"continuous_on (cball z r) f\" using holf_cball\n      by (simp add: holomorphic_on_imp_continuous_on holomorphic_on_subset)\n    have holf_ball: \"f holomorphic_on ball z r\" using holf_cball\n      using ball_subset_cball holomorphic_on_subset by blast\n    { fix w  assume w: \"w \\<in> ball z r\"\n      have intf: \"(\\<lambda>u. f u / (u - w)\\<^sup>2) contour_integrable_on circlepath z r\"\n        by (blast intro: w Cauchy_derivative_integral_circlepath [OF contf_cball holf_ball])\n      have fder': \"(f has_field_derivative 1 / (2 * of_real pi * \\<i>) * contour_integral (circlepath z r) (\\<lambda>u. f u / (u - w)\\<^sup>2))\n                  (at w)\"\n        by (blast intro: w Cauchy_derivative_integral_circlepath [OF contf_cball holf_ball])\n      have f'_eq: \"f' w = contour_integral (circlepath z r) (\\<lambda>u. f u / (u - w)\\<^sup>2) / (2 * of_real pi * \\<i>)\"\n        using fder' ball_subset_cball r w by (force intro: DERIV_unique [OF fder])\n      have \"((\\<lambda>u. f u / (u - w)\\<^sup>2 / (2 * of_real pi * \\<i>)) has_contour_integral\n                contour_integral (circlepath z r) (\\<lambda>u. f u / (u - w)\\<^sup>2) / (2 * of_real pi * \\<i>))\n                (circlepath z r)\"\n        by (rule has_contour_integral_div [OF has_contour_integral_integral [OF intf]])\n      then have \"((\\<lambda>u. f u / (2 * of_real pi * \\<i> * (u - w)\\<^sup>2)) has_contour_integral\n                contour_integral (circlepath z r) (\\<lambda>u. f u / (u - w)\\<^sup>2) / (2 * of_real pi * \\<i>))\n                (circlepath z r)\"\n        by (simp add: algebra_simps)\n      then have \"((\\<lambda>u. f u / (2 * of_real pi * \\<i> * (u - w)\\<^sup>2)) has_contour_integral f' w) (circlepath z r)\"\n        by (simp add: f'_eq)\n    } note * = this\n    show ?thesis\n      using Cauchy_next_derivative_circlepath [OF contfpi, of 2 f'] \\<open>0 < r\\<close> *\n      using centre_in_ball mem_ball by force\n  qed\n  show ?thesis\n    by (simp add: holomorphic_on_open [OF \\<open>open S\\<close>] *)\nqed\n\nlemma holomorphic_deriv [holomorphic_intros]:\n    \"\\<lbrakk>f holomorphic_on S; open S\\<rbrakk> \\<Longrightarrow> (deriv f) holomorphic_on S\"\nby (metis DERIV_deriv_iff_field_differentiable at_within_open derivative_is_holomorphic holomorphic_on_def)\n\nlemma analytic_deriv [analytic_intros]: \"f analytic_on S \\<Longrightarrow> (deriv f) analytic_on S\"\n  using analytic_on_holomorphic holomorphic_deriv by auto\n\nlemma holomorphic_higher_deriv [holomorphic_intros]: \"\\<lbrakk>f holomorphic_on S; open S\\<rbrakk> \\<Longrightarrow> (deriv ^^ n) f holomorphic_on S\"\n  by (induction n) (auto simp: holomorphic_deriv)\n\nlemma analytic_higher_deriv [analytic_intros]: \"f analytic_on S \\<Longrightarrow> (deriv ^^ n) f analytic_on S\"\n  unfolding analytic_on_def using holomorphic_higher_deriv by blast\n\nlemma has_field_derivative_higher_deriv:\n     \"\\<lbrakk>f holomorphic_on S; open S; x \\<in> S\\<rbrakk>\n      \\<Longrightarrow> ((deriv ^^ n) f has_field_derivative (deriv ^^ (Suc n)) f x) (at x)\"\nby (metis (no_types, opaque_lifting) DERIV_deriv_iff_field_differentiable at_within_open comp_apply\n         funpow.simps(2) holomorphic_higher_deriv holomorphic_on_def)\n  \nlemma higher_deriv_cmult:\n  assumes \"f holomorphic_on A\" \"x \\<in> A\" \"open A\"\n  shows   \"(deriv ^^ j) (\\<lambda>x. c * f x) x = c * (deriv ^^ j) f x\"\n  using assms\nproof (induction j arbitrary: f x)\n  case (Suc j f x)\n  have \"deriv ((deriv ^^ j) (\\<lambda>x. c * f x)) x = deriv (\\<lambda>x. c * (deriv ^^ j) f x) x\"\n    using eventually_nhds_in_open[of A x] assms(2,3) Suc.prems\n    by (intro deriv_cong_ev refl) (auto elim!: eventually_mono simp: Suc.IH)\n  also have \"\\<dots> = c * deriv ((deriv ^^ j) f) x\" using Suc.prems assms(2,3)\n    by (intro deriv_cmult holomorphic_on_imp_differentiable_at holomorphic_higher_deriv) auto\n  finally show ?case by simp\nqed simp_all\n\nlemma valid_path_compose_holomorphic:\n  assumes \"valid_path g\" and holo:\"f holomorphic_on S\" and \"open S\" \"path_image g \\<subseteq> S\"\n  shows \"valid_path (f \\<circ> g)\"\n  by (meson assms holomorphic_deriv holomorphic_on_imp_continuous_on holomorphic_on_imp_differentiable_at\n      holomorphic_on_subset subsetD valid_path_compose)\n\nsubsection\\<open>Morera's theorem\\<close>\n\nlemma Morera_local_triangle_ball:\n  assumes \"\\<And>z. z \\<in> S\n          \\<Longrightarrow> \\<exists>e a. 0 < e \\<and> z \\<in> ball a e \\<and> continuous_on (ball a e) f \\<and>\n                    (\\<forall>b c. closed_segment b c \\<subseteq> ball a e\n                           \\<longrightarrow> contour_integral (linepath a b) f +\n                               contour_integral (linepath b c) f +\n                               contour_integral (linepath c a) f = 0)\"\n  shows \"f analytic_on S\"\nproof -\n  { fix z  assume \"z \\<in> S\"\n    with assms obtain e a where\n            \"0 < e\" and z: \"z \\<in> ball a e\" and contf: \"continuous_on (ball a e) f\"\n        and 0: \"\\<And>b c. closed_segment b c \\<subseteq> ball a e\n                      \\<Longrightarrow> contour_integral (linepath a b) f +\n                          contour_integral (linepath b c) f +\n                          contour_integral (linepath c a) f = 0\"\n      by blast\n    have az: \"dist a z < e\" using mem_ball z by blast\n    have \"\\<exists>e>0. f holomorphic_on ball z e\"\n    proof (intro exI conjI)\n      show \"f holomorphic_on ball z (e - dist a z)\"\n      proof (rule holomorphic_on_subset)\n        show \"ball z (e - dist a z) \\<subseteq> ball a e\"\n          by (simp add: dist_commute ball_subset_ball_iff)\n        have sub_ball: \"\\<And>y. dist a y < e \\<Longrightarrow> closed_segment a y \\<subseteq> ball a e\"\n          by (meson \\<open>0 < e\\<close> centre_in_ball convex_ball convex_contains_segment mem_ball)\n        show \"f holomorphic_on ball a e\"\n          using triangle_contour_integrals_starlike_primitive [OF contf _ open_ball, of a]\n            derivative_is_holomorphic[OF open_ball]\n          by (force simp add: 0 \\<open>0 < e\\<close> sub_ball)\n      qed\n    qed (simp add: az)\n  }\n  then show ?thesis\n    by (simp add: analytic_on_def)\nqed\n\nlemma Morera_local_triangle:\n  assumes \"\\<And>z. z \\<in> S\n          \\<Longrightarrow> \\<exists>t. open t \\<and> z \\<in> t \\<and> continuous_on t f \\<and>\n                  (\\<forall>a b c. convex hull {a,b,c} \\<subseteq> t\n                              \\<longrightarrow> contour_integral (linepath a b) f +\n                                  contour_integral (linepath b c) f +\n                                  contour_integral (linepath c a) f = 0)\"\n  shows \"f analytic_on S\"\nproof -\n  { fix z  assume \"z \\<in> S\"\n    with assms obtain t where\n            \"open t\" and z: \"z \\<in> t\" and contf: \"continuous_on t f\"\n        and 0: \"\\<And>a b c. convex hull {a,b,c} \\<subseteq> t\n                      \\<Longrightarrow> contour_integral (linepath a b) f +\n                          contour_integral (linepath b c) f +\n                          contour_integral (linepath c a) f = 0\"\n      by force\n    then obtain e where \"e>0\" and e: \"ball z e \\<subseteq> t\"\n      using open_contains_ball by blast\n    have [simp]: \"continuous_on (ball z e) f\" using contf\n      using continuous_on_subset e by blast\n    have eq0: \"\\<And>b c. closed_segment b c \\<subseteq> ball z e \\<Longrightarrow>\n                         contour_integral (linepath z b) f +\n                         contour_integral (linepath b c) f +\n                         contour_integral (linepath c z) f = 0\"\n      by (meson 0 z \\<open>0 < e\\<close> centre_in_ball closed_segment_subset convex_ball dual_order.trans e starlike_convex_subset)\n    have \"\\<exists>e a. 0 < e \\<and> z \\<in> ball a e \\<and> continuous_on (ball a e) f \\<and>\n                (\\<forall>b c. closed_segment b c \\<subseteq> ball a e \\<longrightarrow>\n                       contour_integral (linepath a b) f + contour_integral (linepath b c) f + contour_integral (linepath c a) f = 0)\"\n      using \\<open>e > 0\\<close> eq0 by force\n  }\n  then show ?thesis\n    by (simp add: Morera_local_triangle_ball)\nqed\n\nproposition Morera_triangle:\n    \"\\<lbrakk>continuous_on S f; open S;\n      \\<And>a b c. convex hull {a,b,c} \\<subseteq> S\n              \\<longrightarrow> contour_integral (linepath a b) f +\n                  contour_integral (linepath b c) f +\n                  contour_integral (linepath c a) f = 0\\<rbrakk>\n     \\<Longrightarrow> f analytic_on S\"\n  using Morera_local_triangle by blast\n\nsubsection\\<open>Combining theorems for higher derivatives including Leibniz rule\\<close>\n\nlemma higher_deriv_linear [simp]:\n    \"(deriv ^^ n) (\\<lambda>w. c*w) = (\\<lambda>z. if n = 0 then c*z else if n = 1 then c else 0)\"\n  by (induction n) auto\n\nlemma higher_deriv_const [simp]: \"(deriv ^^ n) (\\<lambda>w. c) = (\\<lambda>w. if n=0 then c else 0)\"\n  by (induction n) auto\n\nlemma higher_deriv_ident [simp]:\n     \"(deriv ^^ n) (\\<lambda>w. w) z = (if n = 0 then z else if n = 1 then 1 else 0)\"\nproof (induction n)\n  case (Suc n)\n  then show ?case by (metis higher_deriv_linear lambda_one)\nqed auto\n\nlemma higher_deriv_id [simp]:\n     \"(deriv ^^ n) id z = (if n = 0 then z else if n = 1 then 1 else 0)\"\n  by (simp add: id_def)\n\nlemma has_complex_derivative_funpow_1:\n     \"\\<lbrakk>(f has_field_derivative 1) (at z); f z = z\\<rbrakk> \\<Longrightarrow> (f^^n has_field_derivative 1) (at z)\"\nproof (induction n)\n  case 0\n  then show ?case\n    by (simp add: id_def)\nnext\n  case (Suc n)\n  then show ?case\n    by (metis DERIV_chain funpow_Suc_right mult.right_neutral)\nqed\n\nlemma higher_deriv_uminus:\n  assumes \"f holomorphic_on S\" \"open S\" and z: \"z \\<in> S\"\n    shows \"(deriv ^^ n) (\\<lambda>w. -(f w)) z = - ((deriv ^^ n) f z)\"\nusing z\nproof (induction n arbitrary: z)\n  case 0 then show ?case by simp\nnext\n  case (Suc n z)\n  have *: \"((deriv ^^ n) f has_field_derivative deriv ((deriv ^^ n) f) z) (at z)\"\n    using Suc.prems assms has_field_derivative_higher_deriv by auto\n  have \"\\<And>x. x \\<in> S \\<Longrightarrow> - (deriv ^^ n) f x = (deriv ^^ n) (\\<lambda>w. - f w) x\"\n    by (auto simp add: Suc)\n  then have \"((deriv ^^ n) (\\<lambda>w. - f w) has_field_derivative - deriv ((deriv ^^ n) f) z) (at z)\"\n    using  has_field_derivative_transform_within_open [of \"\\<lambda>w. -((deriv ^^ n) f w)\"]\n    using \"*\" DERIV_minus Suc.prems \\<open>open S\\<close> by blast\n  then show ?case\n    by (simp add: DERIV_imp_deriv)\nqed\n\nlemma higher_deriv_add:\n  fixes z::complex\n  assumes \"f holomorphic_on S\" \"g holomorphic_on S\" \"open S\" and z: \"z \\<in> S\"\n    shows \"(deriv ^^ n) (\\<lambda>w. f w + g w) z = (deriv ^^ n) f z + (deriv ^^ n) g z\"\nusing z\nproof (induction n arbitrary: z)\n  case 0 then show ?case by simp\nnext\n  case (Suc n z)\n  have *: \"((deriv ^^ n) f has_field_derivative deriv ((deriv ^^ n) f) z) (at z)\"\n          \"((deriv ^^ n) g has_field_derivative deriv ((deriv ^^ n) g) z) (at z)\"\n    using Suc.prems assms has_field_derivative_higher_deriv by auto\n  have \"\\<And>x. x \\<in> S \\<Longrightarrow> (deriv ^^ n) f x + (deriv ^^ n) g x = (deriv ^^ n) (\\<lambda>w. f w + g w) x\"\n    by (auto simp add: Suc)\n  then have \"((deriv ^^ n) (\\<lambda>w. f w + g w) has_field_derivative\n        deriv ((deriv ^^ n) f) z + deriv ((deriv ^^ n) g) z) (at z)\"\n    using  has_field_derivative_transform_within_open [of \"\\<lambda>w. (deriv ^^ n) f w + (deriv ^^ n) g w\"]\n    using \"*\" Deriv.field_differentiable_add Suc.prems \\<open>open S\\<close> by blast\n  then show ?case\n    by (simp add: DERIV_imp_deriv)\nqed\n\nlemma higher_deriv_diff:\n  fixes z::complex\n  assumes \"f holomorphic_on S\" \"g holomorphic_on S\" \"open S\" \"z \\<in> S\"\n    shows \"(deriv ^^ n) (\\<lambda>w. f w - g w) z = (deriv ^^ n) f z - (deriv ^^ n) g z\"\n  unfolding diff_conv_add_uminus higher_deriv_add\n  using assms higher_deriv_add higher_deriv_uminus holomorphic_on_minus by presburger\n\nlemma Suc_choose: \"Suc n choose k = (n choose k) + (if k = 0 then 0 else (n choose (k - 1)))\"\n  by (cases k) simp_all\n\nlemma higher_deriv_mult:\n  fixes z::complex\n  assumes \"f holomorphic_on S\" \"g holomorphic_on S\" \"open S\" and z: \"z \\<in> S\"\n    shows \"(deriv ^^ n) (\\<lambda>w. f w * g w) z =\n           (\\<Sum>i = 0..n. of_nat (n choose i) * (deriv ^^ i) f z * (deriv ^^ (n - i)) g z)\"\nusing z\nproof (induction n arbitrary: z)\n  case 0 then show ?case by simp\nnext\n  case (Suc n z)\n  have *: \"\\<And>n. ((deriv ^^ n) f has_field_derivative deriv ((deriv ^^ n) f) z) (at z)\"\n          \"\\<And>n. ((deriv ^^ n) g has_field_derivative deriv ((deriv ^^ n) g) z) (at z)\"\n    using Suc.prems assms has_field_derivative_higher_deriv by auto\n  have sumeq: \"(\\<Sum>i = 0..n.\n               of_nat (n choose i) * (deriv ((deriv ^^ i) f) z * (deriv ^^ (n - i)) g z + deriv ((deriv ^^ (n - i)) g) z * (deriv ^^ i) f z)) =\n            g z * deriv ((deriv ^^ n) f) z + (\\<Sum>i = 0..n. (deriv ^^ i) f z * (of_nat (Suc n choose i) * (deriv ^^ (Suc n - i)) g z))\"\n    apply (simp add: Suc_choose algebra_simps sum.distrib)\n    apply (subst (4) sum_Suc_reindex)\n    apply (auto simp: algebra_simps Suc_diff_le intro: sum.cong)\n    done\n  have \"((deriv ^^ n) (\\<lambda>w. f w * g w) has_field_derivative\n         (\\<Sum>i = 0..Suc n. (Suc n choose i) * (deriv ^^ i) f z * (deriv ^^ (Suc n - i)) g z))\n        (at z)\"\n    apply (rule has_field_derivative_transform_within_open\n        [of \"\\<lambda>w. (\\<Sum>i = 0..n. of_nat (n choose i) * (deriv ^^ i) f w * (deriv ^^ (n - i)) g w)\" _ _ S])\n       apply (simp add: algebra_simps)\n       apply (rule derivative_eq_intros | simp)+\n           apply (auto intro: DERIV_mult * \\<open>open S\\<close> Suc.prems Suc.IH [symmetric])\n    by (metis (no_types, lifting) mult.commute sum.cong sumeq)\n  then show ?case\n    unfolding funpow.simps o_apply\n    by (simp add: DERIV_imp_deriv)\nqed\n\nlemma higher_deriv_transform_within_open:\n  fixes z::complex\n  assumes \"f holomorphic_on S\" \"g holomorphic_on S\" \"open S\" and z: \"z \\<in> S\"\n      and fg: \"\\<And>w. w \\<in> S \\<Longrightarrow> f w = g w\"\n    shows \"(deriv ^^ i) f z = (deriv ^^ i) g z\"\nusing z\nby (induction i arbitrary: z)\n   (auto simp: fg intro: complex_derivative_transform_within_open holomorphic_higher_deriv assms)\n\nlemma higher_deriv_compose_linear:\n  fixes z::complex\n  assumes f: \"f holomorphic_on T\" and S: \"open S\" and T: \"open T\" and z: \"z \\<in> S\"\n      and fg: \"\\<And>w. w \\<in> S \\<Longrightarrow> u * w \\<in> T\"\n    shows \"(deriv ^^ n) (\\<lambda>w. f (u * w)) z = u^n * (deriv ^^ n) f (u * z)\"\nusing z\nproof (induction n arbitrary: z)\n  case 0 then show ?case by simp\nnext\n  case (Suc n z)\n  have holo0: \"f holomorphic_on (*) u ` S\"\n    by (meson fg f holomorphic_on_subset image_subset_iff)\n  have holo2: \"(deriv ^^ n) f holomorphic_on (*) u ` S\"\n    by (meson f fg holomorphic_higher_deriv holomorphic_on_subset image_subset_iff T)\n  have holo3: \"(\\<lambda>z. u ^ n * (deriv ^^ n) f (u * z)) holomorphic_on S\"\n    by (intro holo2 holomorphic_on_compose [where g=\"(deriv ^^ n) f\", unfolded o_def] holomorphic_intros)\n  have \"(*) u holomorphic_on S\" \"f holomorphic_on (*) u ` S\"\n    by (rule holo0 holomorphic_intros)+\n  then have holo1: \"(\\<lambda>w. f (u * w)) holomorphic_on S\"\n    by (rule holomorphic_on_compose [where g=f, unfolded o_def])\n  have \"deriv ((deriv ^^ n) (\\<lambda>w. f (u * w))) z = deriv (\\<lambda>z. u^n * (deriv ^^ n) f (u*z)) z\"\n  proof (rule complex_derivative_transform_within_open [OF _ holo3 S Suc.prems])\n    show \"(deriv ^^ n) (\\<lambda>w. f (u * w)) holomorphic_on S\"\n      by (rule holomorphic_higher_deriv [OF holo1 S])\n  qed (simp add: Suc.IH)\n  also have \"\\<dots> = u^n * deriv (\\<lambda>z. (deriv ^^ n) f (u * z)) z\"\n  proof -\n    have \"(deriv ^^ n) f analytic_on T\"\n      by (simp add: analytic_on_open f holomorphic_higher_deriv T)\n    then have \"(\\<lambda>w. (deriv ^^ n) f (u * w)) analytic_on S\"\n    proof -\n      have \"(deriv ^^ n) f \\<circ> (*) u holomorphic_on S\"\n        by (simp add: holo2 holomorphic_on_compose)\n      then show ?thesis\n        by (simp add: S analytic_on_open o_def)\n    qed\n    then show ?thesis\n      by (intro deriv_cmult analytic_on_imp_differentiable_at [OF _ Suc.prems])\n  qed\n  also have \"\\<dots> = u * u ^ n * deriv ((deriv ^^ n) f) (u * z)\"\n  proof -\n    have \"(deriv ^^ n) f field_differentiable at (u * z)\"\n      using Suc.prems T f fg holomorphic_higher_deriv holomorphic_on_imp_differentiable_at by blast\n    then show ?thesis\n      by (simp add: deriv_compose_linear)\n  qed\n  finally show ?case\n    by simp\nqed\n\nlemma higher_deriv_add_at:\n  assumes \"f analytic_on {z}\" \"g analytic_on {z}\"\n    shows \"(deriv ^^ n) (\\<lambda>w. f w + g w) z = (deriv ^^ n) f z + (deriv ^^ n) g z\"\n  using analytic_at_two assms higher_deriv_add by blast\n\nlemma higher_deriv_diff_at:\n  assumes \"f analytic_on {z}\" \"g analytic_on {z}\"\n    shows \"(deriv ^^ n) (\\<lambda>w. f w - g w) z = (deriv ^^ n) f z - (deriv ^^ n) g z\"\n  using analytic_at_two assms higher_deriv_diff by blast\n\nlemma higher_deriv_uminus_at:\n   \"f analytic_on {z}  \\<Longrightarrow> (deriv ^^ n) (\\<lambda>w. -(f w)) z = - ((deriv ^^ n) f z)\"\n  using higher_deriv_uminus by (auto simp: analytic_at)\n\nlemma higher_deriv_mult_at:\n  assumes \"f analytic_on {z}\" \"g analytic_on {z}\"\n    shows \"(deriv ^^ n) (\\<lambda>w. f w * g w) z =\n           (\\<Sum>i = 0..n. of_nat (n choose i) * (deriv ^^ i) f z * (deriv ^^ (n - i)) g z)\"\n  using analytic_at_two assms higher_deriv_mult by blast\n\n\ntext\\<open> Nonexistence of isolated singularities and a stronger integral formula.\\<close>\n\nproposition no_isolated_singularity:\n  fixes z::complex\n  assumes f: \"continuous_on S f\" and holf: \"f holomorphic_on (S - K)\" and S: \"open S\" and K: \"finite K\"\n    shows \"f holomorphic_on S\"\nproof -\n  { fix z\n    assume \"z \\<in> S\" and cdf: \"\\<And>x. x \\<in> S - K \\<Longrightarrow> f field_differentiable at x\"\n    have \"f field_differentiable at z\"\n    proof (cases \"z \\<in> K\")\n      case False then show ?thesis by (blast intro: cdf \\<open>z \\<in> S\\<close>)\n    next\n      case True\n      with finite_set_avoid [OF K, of z]\n      obtain d where \"d>0\" and d: \"\\<And>x. \\<lbrakk>x\\<in>K; x \\<noteq> z\\<rbrakk> \\<Longrightarrow> d \\<le> dist z x\"\n        by blast\n      obtain e where \"e>0\" and e: \"ball z e \\<subseteq> S\"\n        using  S \\<open>z \\<in> S\\<close> by (force simp: open_contains_ball)\n      have fde: \"continuous_on (ball z (min d e)) f\"\n        by (metis Int_iff ball_min_Int continuous_on_subset e f subsetI)\n      have cont: \"{a,b,c} \\<subseteq> ball z (min d e) \\<Longrightarrow> continuous_on (convex hull {a, b, c}) f\" for a b c\n        by (simp add: hull_minimal continuous_on_subset [OF fde])\n      have fd: \"\\<lbrakk>{a,b,c} \\<subseteq> ball z (min d e); x \\<in> interior (convex hull {a, b, c}) - K\\<rbrakk>\n            \\<Longrightarrow> f field_differentiable at x\" for a b c x\n        by (metis cdf Diff_iff Int_iff ball_min_Int subsetD convex_ball e interior_mono interior_subset subset_hull)\n      obtain g where \"\\<And>w. w \\<in> ball z (min d e) \\<Longrightarrow> (g has_field_derivative f w) (at w within ball z (min d e))\"\n        apply (rule contour_integral_convex_primitive\n                     [OF convex_ball fde Cauchy_theorem_triangle_cofinite [OF _ K]])\n        using cont fd by auto\n      then have \"f holomorphic_on ball z (min d e)\"\n        by (metis open_ball at_within_open derivative_is_holomorphic)\n      then show ?thesis\n        unfolding holomorphic_on_def\n        by (metis open_ball \\<open>0 < d\\<close> \\<open>0 < e\\<close> at_within_open centre_in_ball min_less_iff_conj)\n    qed\n  }\n  with holf S K show ?thesis\n    by (simp add: holomorphic_on_open open_Diff finite_imp_closed field_differentiable_def [symmetric])\nqed\n\nlemma no_isolated_singularity':\n  fixes z::complex\n  assumes f: \"\\<And>z. z \\<in> K \\<Longrightarrow> (f \\<longlongrightarrow> f z) (at z within S)\"\n      and holf: \"f holomorphic_on (S - K)\" and S: \"open S\" and K: \"finite K\"\n    shows \"f holomorphic_on S\"\nproof (rule no_isolated_singularity[OF _ assms(2-)])\n  show \"continuous_on S f\" unfolding continuous_on_def\n  proof\n    fix z assume z: \"z \\<in> S\"\n    have \"continuous_on (S - K) f\"\n      using holf holomorphic_on_imp_continuous_on by auto\n    then show \"(f \\<longlongrightarrow> f z) (at z within S)\"\n      by (metis Diff_iff K S at_within_interior continuous_on_def f finite_imp_closed interior_eq open_Diff z)\n  qed\nqed\n\nproposition Cauchy_integral_formula_convex:\n  assumes S: \"convex S\" and K: \"finite K\" and contf: \"continuous_on S f\"\n    and fcd: \"(\\<And>x. x \\<in> interior S - K \\<Longrightarrow> f field_differentiable at x)\"\n    and z: \"z \\<in> interior S\" and vpg: \"valid_path \\<gamma>\"\n    and pasz: \"path_image \\<gamma> \\<subseteq> S - {z}\" and loop: \"pathfinish \\<gamma> = pathstart \\<gamma>\"\n  shows \"((\\<lambda>w. f w / (w - z)) has_contour_integral (2*pi * \\<i> * winding_number \\<gamma> z * f z)) \\<gamma>\"\nproof -\n  have *: \"\\<And>x. x \\<in> interior S \\<Longrightarrow> f field_differentiable at x\"\n    unfolding holomorphic_on_open [symmetric] field_differentiable_def\n    using no_isolated_singularity [where S = \"interior S\"]\n    by (meson K contf continuous_at_imp_continuous_on continuous_on_interior fcd\n          field_differentiable_at_within field_differentiable_def holomorphic_onI\n          holomorphic_on_imp_differentiable_at open_interior)\n  show ?thesis\n    by (rule Cauchy_integral_formula_weak [OF S finite.emptyI contf]) (use * assms in auto)\nqed\n\ntext\\<open> Formula for higher derivatives.\\<close>\n\nlemma Cauchy_has_contour_integral_higher_derivative_circlepath:\n  assumes contf: \"continuous_on (cball z r) f\"\n      and holf: \"f holomorphic_on ball z r\"\n      and w: \"w \\<in> ball z r\"\n    shows \"((\\<lambda>u. f u / (u - w) ^ (Suc k)) has_contour_integral ((2 * pi * \\<i>) / (fact k) * (deriv ^^ k) f w))\n           (circlepath z r)\"\nusing w\nproof (induction k arbitrary: w)\n  case 0 then show ?case\n    using assms by (auto simp: Cauchy_integral_circlepath dist_commute dist_norm)\nnext\n  case (Suc k)\n  have [simp]: \"r > 0\" using w\n    using ball_eq_empty by fastforce\n  have f: \"continuous_on (path_image (circlepath z r)) f\"\n    by (rule continuous_on_subset [OF contf]) (force simp: cball_def sphere_def less_imp_le)\n  obtain X where X: \"((\\<lambda>u. f u / (u - w) ^ Suc (Suc k)) has_contour_integral X) (circlepath z r)\"\n    using Cauchy_next_derivative_circlepath(1) [OF f Suc.IH _ Suc.prems]\n    by (auto simp: contour_integrable_on_def)\n  then have con: \"contour_integral (circlepath z r) ((\\<lambda>u. f u / (u - w) ^ Suc (Suc k))) = X\"\n    by (rule contour_integral_unique)\n  have \"\\<And>n. ((deriv ^^ n) f has_field_derivative deriv ((deriv ^^ n) f) w) (at w)\"\n    using Suc.prems assms has_field_derivative_higher_deriv by auto\n  then have dnf_diff: \"\\<And>n. (deriv ^^ n) f field_differentiable (at w)\"\n    by (force simp: field_differentiable_def)\n  have \"deriv (\\<lambda>w. complex_of_real (2 * pi) * \\<i> / (fact k) * (deriv ^^ k) f w) w =\n          of_nat (Suc k) * contour_integral (circlepath z r) (\\<lambda>u. f u / (u - w) ^ Suc (Suc k))\"\n    by (force intro!: DERIV_imp_deriv Cauchy_next_derivative_circlepath [OF f Suc.IH _ Suc.prems])\n  also have \"\\<dots> = of_nat (Suc k) * X\"\n    by (simp only: con)\n  finally have \"deriv (\\<lambda>w. ((2 * pi) * \\<i> / (fact k)) * (deriv ^^ k) f w) w = of_nat (Suc k) * X\" .\n  then have \"((2 * pi) * \\<i> / (fact k)) * deriv (\\<lambda>w. (deriv ^^ k) f w) w = of_nat (Suc k) * X\"\n    by (metis deriv_cmult dnf_diff)\n  then have \"deriv (\\<lambda>w. (deriv ^^ k) f w) w = of_nat (Suc k) * X / ((2 * pi) * \\<i> / (fact k))\"\n    by (simp add: field_simps)\n  then show ?case\n  using of_nat_eq_0_iff X by fastforce\nqed\n\nlemma Cauchy_higher_derivative_integral_circlepath:\n  assumes contf: \"continuous_on (cball z r) f\"\n      and holf: \"f holomorphic_on ball z r\"\n      and w: \"w \\<in> ball z r\"\n    shows \"(\\<lambda>u. f u / (u - w)^(Suc k)) contour_integrable_on (circlepath z r)\"\n           (is \"?thes1\")\n      and \"(deriv ^^ k) f w = (fact k) / (2 * pi * \\<i>) * contour_integral(circlepath z r) (\\<lambda>u. f u/(u - w)^(Suc k))\"\n           (is \"?thes2\")\nproof -\n  have *: \"((\\<lambda>u. f u / (u - w) ^ Suc k) has_contour_integral (2 * pi) * \\<i> / (fact k) * (deriv ^^ k) f w)\n           (circlepath z r)\"\n    using Cauchy_has_contour_integral_higher_derivative_circlepath [OF assms]\n    by simp\n  show ?thes1 using *\n    using contour_integrable_on_def by blast\n  show ?thes2\n    unfolding contour_integral_unique [OF *] by (simp add: field_split_simps)\nqed\n\ncorollary Cauchy_contour_integral_circlepath:\n  assumes \"continuous_on (cball z r) f\" \"f holomorphic_on ball z r\" \"w \\<in> ball z r\"\n  shows \"contour_integral(circlepath z r) (\\<lambda>u. f u/(u - w)^(Suc k)) = (2 * pi * \\<i>) * (deriv ^^ k) f w / (fact k)\"\n  by (simp add: Cauchy_higher_derivative_integral_circlepath [OF assms])\n\nlemma Cauchy_contour_integral_circlepath_2:\n  assumes \"continuous_on (cball z r) f\" \"f holomorphic_on ball z r\" \"w \\<in> ball z r\"\n    shows \"contour_integral(circlepath z r) (\\<lambda>u. f u/(u - w)^2) = (2 * pi * \\<i>) * deriv f w\"\n  using Cauchy_contour_integral_circlepath [OF assms, of 1]\n  by (simp add: power2_eq_square)\n\n\nsubsection\\<open>A holomorphic function is analytic, i.e. has local power series\\<close>\n\ntheorem holomorphic_power_series:\n  assumes holf: \"f holomorphic_on ball z r\"\n      and w: \"w \\<in> ball z r\"\n    shows \"((\\<lambda>n. (deriv ^^ n) f z / (fact n) * (w - z)^n) sums f w)\"\nproof -\n  \\<comment> \\<open>Replacing \\<^term>\\<open>r\\<close> and the original (weak) premises with stronger ones\\<close>\n  obtain r where \"r > 0\" and holfc: \"f holomorphic_on cball z r\" and w: \"w \\<in> ball z r\"\n  proof\n    have \"cball z ((r + dist w z) / 2) \\<subseteq> ball z r\"\n      using w by (simp add: dist_commute field_sum_of_halves subset_eq)\n    then show \"f holomorphic_on cball z ((r + dist w z) / 2)\"\n      by (rule holomorphic_on_subset [OF holf])\n    have \"r > 0\"\n      using w by clarsimp (metis dist_norm le_less_trans norm_ge_zero)\n    then show \"0 < (r + dist w z) / 2\"\n      by simp (use zero_le_dist [of w z] in linarith)\n  qed (use w in \\<open>auto simp: dist_commute\\<close>)\n  then have holf: \"f holomorphic_on ball z r\"\n    using ball_subset_cball holomorphic_on_subset by blast\n  have contf: \"continuous_on (cball z r) f\"\n    by (simp add: holfc holomorphic_on_imp_continuous_on)\n  have cint: \"\\<And>k. (\\<lambda>u. f u / (u - z) ^ Suc k) contour_integrable_on circlepath z r\"\n    by (rule Cauchy_higher_derivative_integral_circlepath [OF contf holf]) (simp add: \\<open>0 < r\\<close>)\n  obtain B where \"0 < B\" and B: \"\\<And>u. u \\<in> cball z r \\<Longrightarrow> norm(f u) \\<le> B\"\n    by (metis (no_types) bounded_pos compact_cball compact_continuous_image compact_imp_bounded contf image_eqI)\n  obtain k where k: \"0 < k\" \"k \\<le> r\" and wz_eq: \"norm(w - z) = r - k\"\n             and kle: \"\\<And>u. norm(u - z) = r \\<Longrightarrow> k \\<le> norm(u - w)\"\n  proof\n    show \"\\<And>u. cmod (u - z) = r \\<Longrightarrow> r - dist z w \\<le> cmod (u - w)\"\n      by (metis add_diff_eq diff_add_cancel dist_norm norm_diff_ineq)\n  qed (use w in \\<open>auto simp: dist_norm norm_minus_commute\\<close>)\n  have ul: \"uniform_limit (sphere z r) (\\<lambda>n x. (\\<Sum>k<n. (w - z) ^ k * (f x / (x - z) ^ Suc k))) (\\<lambda>x. f x / (x - w)) sequentially\"\n    unfolding uniform_limit_iff dist_norm\n  proof clarify\n    fix e::real\n    assume \"0 < e\"\n    have rr: \"0 \\<le> (r - k) / r\" \"(r - k) / r < 1\" using  k by auto\n    obtain n where n: \"((r - k) / r) ^ n < e / B * k\"\n      using real_arch_pow_inv [of \"e/B*k\" \"(r - k)/r\"] \\<open>0 < e\\<close> \\<open>0 < B\\<close> k by force\n    have \"norm ((\\<Sum>k<N. (w - z) ^ k * f u / (u - z) ^ Suc k) - f u / (u - w)) < e\"\n         if \"n \\<le> N\" and r: \"r = dist z u\"  for N u\n    proof -\n      have N: \"((r - k) / r) ^ N < e / B * k\"\n        using le_less_trans [OF power_decreasing n]\n        using \\<open>n \\<le> N\\<close> k by auto\n      have u [simp]: \"(u \\<noteq> z) \\<and> (u \\<noteq> w)\"\n        using \\<open>0 < r\\<close> r w by auto\n      have wzu_not1: \"(w - z) / (u - z) \\<noteq> 1\"\n        by (metis (no_types) dist_norm divide_eq_1_iff less_irrefl mem_ball norm_minus_commute r w)\n      have \"norm ((\\<Sum>k<N. (w - z) ^ k * f u / (u - z) ^ Suc k) * (u - w) - f u)\n            = norm ((\\<Sum>k<N. (((w - z) / (u - z)) ^ k)) * f u * (u - w) / (u - z) - f u)\"\n        unfolding sum_distrib_right sum_divide_distrib power_divide by (simp add: algebra_simps)\n      also have \"\\<dots> = norm ((((w - z) / (u - z)) ^ N - 1) * (u - w) / (((w - z) / (u - z) - 1) * (u - z)) - 1) * norm (f u)\"\n        using \\<open>0 < B\\<close>\n        apply (auto simp: geometric_sum [OF wzu_not1])\n        apply (simp add: field_simps norm_mult [symmetric])\n        done\n      also have \"\\<dots> = norm ((u-z) ^ N * (w - u) - ((w - z) ^ N - (u-z) ^ N) * (u-w)) / (r ^ N * norm (u-w)) * norm (f u)\"\n        using \\<open>0 < r\\<close> r by (simp add: divide_simps norm_mult norm_divide norm_power dist_norm norm_minus_commute)\n      also have \"\\<dots> = norm ((w - z) ^ N * (w - u)) / (r ^ N * norm (u - w)) * norm (f u)\"\n        by (simp add: algebra_simps)\n      also have \"\\<dots> = norm (w - z) ^ N * norm (f u) / r ^ N\"\n        by (simp add: norm_mult norm_power norm_minus_commute)\n      also have \"\\<dots> \\<le> (((r - k)/r)^N) * B\"\n        using \\<open>0 < r\\<close> w k\n        by (simp add: B divide_simps mult_mono r wz_eq)\n      also have \"\\<dots> < e * k\"\n        using \\<open>0 < B\\<close> N by (simp add: divide_simps)\n      also have \"\\<dots> \\<le> e * norm (u - w)\"\n        using r kle \\<open>0 < e\\<close> by (simp add: dist_commute dist_norm)\n      finally show ?thesis\n        by (simp add: field_split_simps norm_divide del: power_Suc)\n    qed\n    with \\<open>0 < r\\<close> show \"\\<forall>\\<^sub>F n in sequentially. \\<forall>x\\<in>sphere z r.\n                norm ((\\<Sum>k<n. (w - z) ^ k * (f x / (x - z) ^ Suc k)) - f x / (x - w)) < e\"\n      by (auto simp: mult_ac less_imp_le eventually_sequentially Ball_def)\n  qed\n  have \\<section>: \"\\<And>x k. k\\<in> {..<x} \\<Longrightarrow>\n           (\\<lambda>u. (w - z) ^ k * (f u / (u - z) ^ Suc k)) contour_integrable_on circlepath z r\"\n    using contour_integrable_lmul [OF cint, of \"(w - z) ^ a\" for a] by (simp add: field_simps)\n  have eq: \"\\<forall>\\<^sub>F x in sequentially.\n             contour_integral (circlepath z r) (\\<lambda>u. \\<Sum>k<x. (w - z) ^ k * (f u / (u - z) ^ Suc k)) =\n             (\\<Sum>k<x. contour_integral (circlepath z r) (\\<lambda>u. f u / (u - z) ^ Suc k) * (w - z) ^ k)\"\n    apply (rule eventuallyI)\n    apply (subst contour_integral_sum, simp)\n    apply (simp_all only: \\<section> contour_integral_lmul cint algebra_simps)\n    done\n  have \"\\<And>u k. k \\<in> {..<u} \\<Longrightarrow> (\\<lambda>x. f x / (x - z) ^ Suc k) contour_integrable_on circlepath z r\"\n    using \\<open>0 < r\\<close> by (force intro!: Cauchy_higher_derivative_integral_circlepath [OF contf holf])\n  then have \"\\<And>u. (\\<lambda>y. \\<Sum>k<u. (w - z) ^ k * (f y / (y - z) ^ Suc k)) contour_integrable_on circlepath z r\"\n    by (intro contour_integrable_sum contour_integrable_lmul, simp)\n  then have \"(\\<lambda>k. contour_integral (circlepath z r) (\\<lambda>u. f u/(u - z)^(Suc k)) * (w - z)^k)\n        sums contour_integral (circlepath z r) (\\<lambda>u. f u/(u - w))\"\n    unfolding sums_def using \\<open>0 < r\\<close> \n    by (intro Lim_transform_eventually [OF _ eq] contour_integral_uniform_limit_circlepath [OF eventuallyI ul]) auto\n  then have \"(\\<lambda>k. contour_integral (circlepath z r) (\\<lambda>u. f u/(u - z)^(Suc k)) * (w - z)^k)\n             sums (2 * of_real pi * \\<i> * f w)\"\n    using w by (auto simp: dist_commute dist_norm contour_integral_unique [OF Cauchy_integral_circlepath_simple [OF holfc]])\n  then have \"(\\<lambda>k. contour_integral (circlepath z r) (\\<lambda>u. f u / (u - z) ^ Suc k) * (w - z)^k / (\\<i> * (of_real pi * 2)))\n            sums ((2 * of_real pi * \\<i> * f w) / (\\<i> * (complex_of_real pi * 2)))\"\n    by (rule sums_divide)\n  then have \"(\\<lambda>n. (w - z) ^ n * contour_integral (circlepath z r) (\\<lambda>u. f u / (u - z) ^ Suc n) / (\\<i> * (of_real pi * 2)))\n            sums f w\"\n    by (simp add: field_simps)\n  then show ?thesis\n    by (simp add: field_simps \\<open>0 < r\\<close> Cauchy_higher_derivative_integral_circlepath [OF contf holf])\nqed\n\nsubsection\\<open>The Liouville theorem and the Fundamental Theorem of Algebra\\<close>\n\ntext\\<open> These weak Liouville versions don't even need the derivative formula.\\<close>\n\nlemma Liouville_weak_0:\n  assumes holf: \"f holomorphic_on UNIV\" and inf: \"(f \\<longlongrightarrow> 0) at_infinity\"\n    shows \"f z = 0\"\nproof (rule ccontr)\n  assume fz: \"f z \\<noteq> 0\"\n  with inf [unfolded Lim_at_infinity, rule_format, of \"norm(f z)/2\"]\n  obtain B where B: \"\\<And>x. B \\<le> cmod x \\<Longrightarrow> norm (f x) * 2 < cmod (f z)\"\n    by (auto simp: dist_norm)\n  define R where \"R = 1 + \\<bar>B\\<bar> + norm z\"\n  have \"R > 0\"\n    unfolding R_def by (smt (verit) norm_ge_zero)\n  have *: \"((\\<lambda>u. f u / (u - z)) has_contour_integral 2 * complex_of_real pi * \\<i> * f z) (circlepath z R)\"\n    using continuous_on_subset holf  holomorphic_on_subset \\<open>0 < R\\<close>\n    by (force intro: holomorphic_on_imp_continuous_on Cauchy_integral_circlepath)\n  have \"cmod (x - z) = R \\<Longrightarrow> cmod (f x) * 2 < cmod (f z)\" for x\n    unfolding R_def by (rule B) (use norm_triangle_ineq4 [of x z] in auto)\n  with \\<open>R > 0\\<close> fz show False\n    using has_contour_integral_bound_circlepath [OF *, of \"norm(f z)/2/R\"]\n    by (auto simp: less_imp_le norm_mult norm_divide field_split_simps)\nqed\n\nproposition Liouville_weak:\n  assumes \"f holomorphic_on UNIV\" and \"(f \\<longlongrightarrow> l) at_infinity\"\n    shows \"f z = l\"\n  using Liouville_weak_0 [of \"\\<lambda>z. f z - l\"]\n  by (simp add: assms holomorphic_on_diff LIM_zero)\n\nproposition Liouville_weak_inverse:\n  assumes \"f holomorphic_on UNIV\" and unbounded: \"\\<And>B. eventually (\\<lambda>x. norm (f x) \\<ge> B) at_infinity\"\n    obtains z where \"f z = 0\"\nproof -\n  { assume f: \"\\<And>z. f z \\<noteq> 0\"\n    have 1: \"(\\<lambda>x. 1 / f x) holomorphic_on UNIV\"\n      by (simp add: holomorphic_on_divide assms f)\n    have 2: \"((\\<lambda>x. 1 / f x) \\<longlongrightarrow> 0) at_infinity\"\n    proof (rule tendstoI [OF eventually_mono])\n      fix e::real\n      assume \"e > 0\"\n      show \"eventually (\\<lambda>x. 2/e \\<le> cmod (f x)) at_infinity\"\n        by (rule_tac B=\"2/e\" in unbounded)\n    qed (simp add: dist_norm norm_divide field_split_simps)\n    have False\n      using Liouville_weak_0 [OF 1 2] f by simp\n  }\n  then show ?thesis\n    using that by blast\nqed\n\ntext\\<open> In particular we get the Fundamental Theorem of Algebra.\\<close>\n\ntheorem fundamental_theorem_of_algebra:\n    fixes a :: \"nat \\<Rightarrow> complex\"\n  assumes \"a 0 = 0 \\<or> (\\<exists>i \\<in> {1..n}. a i \\<noteq> 0)\"\n  obtains z where \"(\\<Sum>i\\<le>n. a i * z^i) = 0\"\nusing assms\nproof (elim disjE bexE)\n  assume \"a 0 = 0\" then show ?thesis\n    by (auto simp: that [of 0])\nnext\n  fix i\n  assume i: \"i \\<in> {1..n}\" and nz: \"a i \\<noteq> 0\"\n  have 1: \"(\\<lambda>z. \\<Sum>i\\<le>n. a i * z^i) holomorphic_on UNIV\"\n    by (rule holomorphic_intros)+\n  show thesis\n  proof (rule Liouville_weak_inverse [OF 1])\n    show \"\\<forall>\\<^sub>F x in at_infinity. B \\<le> cmod (\\<Sum>i\\<le>n. a i * x ^ i)\" for B\n      using i nz by (intro polyfun_extremal exI[of _ i]) auto\n  qed (use that in auto)\nqed\n\nsubsection\\<open>Weierstrass convergence theorem\\<close>\n\nlemma holomorphic_uniform_limit:\n  assumes cont: \"eventually (\\<lambda>n. continuous_on (cball z r) (f n) \\<and> (f n) holomorphic_on ball z r) F\"\n      and ulim: \"uniform_limit (cball z r) f g F\"\n      and F:  \"\\<not> trivial_limit F\"\n  obtains \"continuous_on (cball z r) g\" \"g holomorphic_on ball z r\"\nproof (cases r \"0::real\" rule: linorder_cases)\n  case less then show ?thesis by (force simp: ball_empty less_imp_le continuous_on_def holomorphic_on_def intro: that)\nnext\n  case equal then show ?thesis\n    by (force simp: holomorphic_on_def intro: that)\nnext\n  case greater\n  have contg: \"continuous_on (cball z r) g\"\n    using cont uniform_limit_theorem [OF eventually_mono ulim F]  by blast\n  have \"path_image (circlepath z r) \\<subseteq> cball z r\"\n    using \\<open>0 < r\\<close> by auto\n  then have 1: \"continuous_on (path_image (circlepath z r)) (\\<lambda>x. 1 / (2 * complex_of_real pi * \\<i>) * g x)\"\n    by (intro continuous_intros continuous_on_subset [OF contg])\n  have 2: \"((\\<lambda>u. 1 / (2 * of_real pi * \\<i>) * g u / (u - w) ^ 1) has_contour_integral g w) (circlepath z r)\"\n       if w: \"w \\<in> ball z r\" for w\n  proof -\n    define d where \"d = (r - norm(w - z))\"\n    have \"0 < d\"  \"d \\<le> r\" using w by (auto simp: norm_minus_commute d_def dist_norm)\n    have dle: \"\\<And>u. cmod (z - u) = r \\<Longrightarrow> d \\<le> cmod (u - w)\"\n      unfolding d_def by (metis add_diff_eq diff_add_cancel norm_diff_ineq norm_minus_commute)\n    have ev_int: \"\\<forall>\\<^sub>F n in F. (\\<lambda>u. f n u / (u - w)) contour_integrable_on circlepath z r\"\n      using w\n      by (auto intro: eventually_mono [OF cont] Cauchy_higher_derivative_integral_circlepath [where k=0, simplified])\n    have \"\\<And>e. \\<lbrakk>0 < r; 0 < d; 0 < e\\<rbrakk>\n         \\<Longrightarrow> \\<forall>\\<^sub>F n in F.\n                \\<forall>x\\<in>sphere z r.\n                   x \\<noteq> w \\<longrightarrow>\n                   cmod (f n x - g x) < e * cmod (x - w)\"\n      apply (rule_tac e1=\"e * d\" in eventually_mono [OF uniform_limitD [OF ulim]])\n       apply (force simp: dist_norm intro: dle mult_left_mono less_le_trans)+\n      done\n    then have ul_less: \"uniform_limit (sphere z r) (\\<lambda>n x. f n x / (x - w)) (\\<lambda>x. g x / (x - w)) F\"\n      using greater \\<open>0 < d\\<close>\n      by (auto simp add: uniform_limit_iff dist_norm norm_divide diff_divide_distrib [symmetric] divide_simps)\n    have g_cint: \"(\\<lambda>u. g u/(u - w)) contour_integrable_on circlepath z r\"\n      by (rule contour_integral_uniform_limit_circlepath [OF ev_int ul_less F \\<open>0 < r\\<close>])\n    have cif_tends_cig: \"((\\<lambda>n. contour_integral(circlepath z r) (\\<lambda>u. f n u / (u - w))) \\<longlongrightarrow> contour_integral(circlepath z r) (\\<lambda>u. g u/(u - w))) F\"\n      by (rule contour_integral_uniform_limit_circlepath [OF ev_int ul_less F \\<open>0 < r\\<close>])\n    have f_tends_cig: \"((\\<lambda>n. 2 * of_real pi * \\<i> * f n w) \\<longlongrightarrow> contour_integral (circlepath z r) (\\<lambda>u. g u / (u - w))) F\"\n    proof (rule Lim_transform_eventually)\n      show \"\\<forall>\\<^sub>F x in F. contour_integral (circlepath z r) (\\<lambda>u. f x u / (u - w))\n                     = 2 * of_real pi * \\<i> * f x w\"\n        using w\\<open>0 < d\\<close> d_def\n        by (auto intro: eventually_mono [OF cont contour_integral_unique [OF Cauchy_integral_circlepath]])\n    qed (auto simp: cif_tends_cig)\n    have \"\\<And>e. 0 < e \\<Longrightarrow> \\<forall>\\<^sub>F n in F. dist (f n w) (g w) < e\"\n      by (rule eventually_mono [OF uniform_limitD [OF ulim]]) (use w in auto)\n    then have \"((\\<lambda>n. 2 * of_real pi * \\<i> * f n w) \\<longlongrightarrow> 2 * of_real pi * \\<i> * g w) F\"\n      by (rule tendsto_mult_left [OF tendstoI])\n    then have \"((\\<lambda>u. g u / (u - w)) has_contour_integral 2 * of_real pi * \\<i> * g w) (circlepath z r)\"\n      using has_contour_integral_integral [OF g_cint] tendsto_unique [OF F f_tends_cig] w\n      by fastforce\n    then have \"((\\<lambda>u. g u / (2 * of_real pi * \\<i> * (u - w))) has_contour_integral g w) (circlepath z r)\"\n      using has_contour_integral_div [where c = \"2 * of_real pi * \\<i>\"]\n      by (force simp: field_simps)\n    then show ?thesis\n      by (simp add: dist_norm)\n  qed\n  show ?thesis\n    using Cauchy_next_derivative_circlepath(2) [OF 1 2, simplified]\n    by (fastforce simp add: holomorphic_on_open contg intro: that)\nqed\n\n\ntext\\<open> Version showing that the limit is the limit of the derivatives.\\<close>\n\nproposition has_complex_derivative_uniform_limit:\n  fixes z::complex\n  assumes cont: \"eventually (\\<lambda>n. continuous_on (cball z r) (f n) \\<and>\n                               (\\<forall>w \\<in> ball z r. ((f n) has_field_derivative (f' n w)) (at w))) F\"\n      and ulim: \"uniform_limit (cball z r) f g F\"\n      and F:  \"\\<not> trivial_limit F\" and \"0 < r\"\n  obtains g' where\n      \"continuous_on (cball z r) g\"\n      \"\\<And>w. w \\<in> ball z r \\<Longrightarrow> (g has_field_derivative (g' w)) (at w) \\<and> ((\\<lambda>n. f' n w) \\<longlongrightarrow> g' w) F\"\nproof -\n  let ?conint = \"contour_integral (circlepath z r)\"\n  have g: \"continuous_on (cball z r) g\" \"g holomorphic_on ball z r\"\n    by (rule holomorphic_uniform_limit [OF eventually_mono [OF cont] ulim F];\n             auto simp: holomorphic_on_open field_differentiable_def)+\n  then obtain g' where g': \"\\<And>x. x \\<in> ball z r \\<Longrightarrow> (g has_field_derivative g' x) (at x)\"\n    using DERIV_deriv_iff_has_field_derivative\n    by (fastforce simp add: holomorphic_on_open)\n  then have derg: \"\\<And>x. x \\<in> ball z r \\<Longrightarrow> deriv g x = g' x\"\n    by (simp add: DERIV_imp_deriv)\n  have tends_f'n_g': \"((\\<lambda>n. f' n w) \\<longlongrightarrow> g' w) F\" if w: \"w \\<in> ball z r\" for w\n  proof -\n    have eq_f': \"?conint (\\<lambda>x. f n x / (x - w)\\<^sup>2) - ?conint (\\<lambda>x. g x / (x - w)\\<^sup>2) = (f' n w - g' w) * (2 * of_real pi * \\<i>)\"\n             if cont_fn: \"continuous_on (cball z r) (f n)\"\n             and fnd: \"\\<And>w. w \\<in> ball z r \\<Longrightarrow> (f n has_field_derivative f' n w) (at w)\" for n\n    proof -\n      have hol_fn: \"f n holomorphic_on ball z r\"\n        using fnd by (force simp: holomorphic_on_open)\n      have \"(f n has_field_derivative 1 / (2 * of_real pi * \\<i>) * ?conint (\\<lambda>u. f n u / (u - w)\\<^sup>2)) (at w)\"\n        by (rule Cauchy_derivative_integral_circlepath [OF cont_fn hol_fn w])\n      then have f': \"f' n w = 1 / (2 * of_real pi * \\<i>) * ?conint (\\<lambda>u. f n u / (u - w)\\<^sup>2)\"\n        using DERIV_unique [OF fnd] w by blast\n      show ?thesis\n        by (simp add: f' Cauchy_contour_integral_circlepath_2 [OF g w] derg [OF w] field_split_simps)\n    qed\n    define d where \"d = (r - norm(w - z))^2\"\n    have \"d > 0\"\n      using w by (simp add: dist_commute dist_norm d_def)\n    have dle: \"d \\<le> cmod ((y - w)\\<^sup>2)\" if \"r = cmod (z - y)\" for y\n    proof -\n      have \"cmod (w - z) \\<le> cmod (z - y)\"\n        by (metis dist_commute dist_norm mem_ball order_less_imp_le that w)\n      moreover have \"cmod (z - y) - cmod (w - z) \\<le> cmod (y - w)\"\n        by (metis diff_add_cancel diff_diff_eq2 norm_minus_commute norm_triangle_ineq2)\n      ultimately show ?thesis\n        using that by (simp add: d_def norm_power power_mono)\n    qed\n    have 1: \"\\<forall>\\<^sub>F n in F. (\\<lambda>x. f n x / (x - w)\\<^sup>2) contour_integrable_on circlepath z r\"\n      by (force simp: holomorphic_on_open intro: w Cauchy_derivative_integral_circlepath eventually_mono [OF cont])\n    have 2: \"uniform_limit (sphere z r) (\\<lambda>n x. f n x / (x - w)\\<^sup>2) (\\<lambda>x. g x / (x - w)\\<^sup>2) F\"\n      unfolding uniform_limit_iff\n    proof clarify\n      fix e::real\n      assume \"e > 0\"\n      with \\<open>r > 0\\<close> \n      have \"\\<forall>\\<^sub>F n in F. \\<forall>x. x \\<noteq> w \\<longrightarrow> cmod (z - x) = r \\<longrightarrow> cmod (f n x - g x) < e * cmod ((x - w)\\<^sup>2)\"\n        by (force simp: \\<open>0 < d\\<close> dist_norm dle intro: less_le_trans eventually_mono [OF uniform_limitD [OF ulim], of \"e*d\"])\n      with \\<open>r > 0\\<close> \\<open>e > 0\\<close> \n      show \"\\<forall>\\<^sub>F n in F. \\<forall>x\\<in>sphere z r. dist (f n x / (x - w)\\<^sup>2) (g x / (x - w)\\<^sup>2) < e\"\n        by (simp add: norm_divide field_split_simps sphere_def dist_norm)\n    qed\n    have \"((\\<lambda>n. contour_integral (circlepath z r) (\\<lambda>x. f n x / (x - w)\\<^sup>2))\n             \\<longlongrightarrow> contour_integral (circlepath z r) ((\\<lambda>x. g x / (x - w)\\<^sup>2))) F\"\n      by (rule contour_integral_uniform_limit_circlepath [OF 1 2 F \\<open>0 < r\\<close>])\n    then have tendsto_0: \"((\\<lambda>n. 1 / (2 * of_real pi * \\<i>) * (?conint (\\<lambda>x. f n x / (x - w)\\<^sup>2) - ?conint (\\<lambda>x. g x / (x - w)\\<^sup>2))) \\<longlongrightarrow> 0) F\"\n      using Lim_null by (force intro!: tendsto_mult_right_zero)\n    have \"((\\<lambda>n. f' n w - g' w) \\<longlongrightarrow> 0) F\"\n      apply (rule Lim_transform_eventually [OF tendsto_0])\n      apply (force simp: divide_simps intro: eq_f' eventually_mono [OF cont])\n      done\n    then show ?thesis using Lim_null by blast\n  qed\n  obtain g' where \"\\<And>w. w \\<in> ball z r \\<Longrightarrow> (g has_field_derivative (g' w)) (at w) \\<and> ((\\<lambda>n. f' n w) \\<longlongrightarrow> g' w) F\"\n      by (blast intro: tends_f'n_g' g')\n  then show ?thesis using g\n    using that by blast\nqed\n\n\nsubsection\\<^marker>\\<open>tag unimportant\\<close> \\<open>Some more simple/convenient versions for applications\\<close>\n\nlemma holomorphic_uniform_sequence:\n  assumes S: \"open S\"\n      and hol_fn: \"\\<And>n. (f n) holomorphic_on S\"\n      and ulim_g: \"\\<And>x. x \\<in> S \\<Longrightarrow> \\<exists>d. 0 < d \\<and> cball x d \\<subseteq> S \\<and> uniform_limit (cball x d) f g sequentially\"\n  shows \"g holomorphic_on S\"\nproof -\n  have \"\\<exists>f'. (g has_field_derivative f') (at z)\" if \"z \\<in> S\" for z\n  proof -\n    obtain r where \"0 < r\" and r: \"cball z r \\<subseteq> S\"\n               and ul: \"uniform_limit (cball z r) f g sequentially\"\n      using ulim_g [OF \\<open>z \\<in> S\\<close>] by blast\n    have *: \"\\<forall>\\<^sub>F n in sequentially. continuous_on (cball z r) (f n) \\<and> f n holomorphic_on ball z r\"\n      by (smt (verit, best) ball_subset_cball hol_fn holomorphic_on_imp_continuous_on \n          holomorphic_on_subset not_eventuallyD r)\n    show ?thesis\n      using \\<open>0 < r\\<close> centre_in_ball ul\n      by (auto simp: holomorphic_on_open intro: holomorphic_uniform_limit [OF *])\n  qed\n  with S show ?thesis\n    by (simp add: holomorphic_on_open)\nqed\n\nlemma has_complex_derivative_uniform_sequence:\n  fixes S :: \"complex set\"\n  assumes S: \"open S\"\n      and hfd: \"\\<And>n x. x \\<in> S \\<Longrightarrow> ((f n) has_field_derivative f' n x) (at x)\"\n      and ulim_g: \"\\<And>x. x \\<in> S\n             \\<Longrightarrow> \\<exists>d. 0 < d \\<and> cball x d \\<subseteq> S \\<and> uniform_limit (cball x d) f g sequentially\"\n  shows \"\\<exists>g'. \\<forall>x \\<in> S. (g has_field_derivative g' x) (at x) \\<and> ((\\<lambda>n. f' n x) \\<longlongrightarrow> g' x) sequentially\"\nproof -\n  have y: \"\\<exists>y. (g has_field_derivative y) (at z) \\<and> (\\<lambda>n. f' n z) \\<longlonglongrightarrow> y\" if \"z \\<in> S\" for z\n  proof -\n    obtain r where \"0 < r\" and r: \"cball z r \\<subseteq> S\"\n               and ul: \"uniform_limit (cball z r) f g sequentially\"\n      using ulim_g [OF \\<open>z \\<in> S\\<close>] by blast\n    have *: \"\\<forall>\\<^sub>F n in sequentially. continuous_on (cball z r) (f n) \\<and>\n                                   (\\<forall>w \\<in> ball z r. ((f n) has_field_derivative (f' n w)) (at w))\"\n    proof (intro eventuallyI conjI ballI)\n      show \"continuous_on (cball z r) (f x)\" for x\n        by (meson S continuous_on_subset hfd holomorphic_on_imp_continuous_on holomorphic_on_open r)\n      show \"w \\<in> ball z r \\<Longrightarrow> (f x has_field_derivative f' x w) (at w)\" for w x\n        using ball_subset_cball hfd r by blast\n    qed\n    show ?thesis\n      by (rule has_complex_derivative_uniform_limit [OF *, of g]) (use \\<open>0 < r\\<close> ul in \\<open>force+\\<close>)\n  qed\n  show ?thesis\n    by (rule bchoice) (blast intro: y)\nqed\n\nsubsection\\<open>On analytic functions defined by a series\\<close>\n\nlemma series_and_derivative_comparison:\n  fixes S :: \"complex set\"\n  assumes S: \"open S\"\n      and h: \"summable h\"\n      and hfd: \"\\<And>n x. x \\<in> S \\<Longrightarrow> (f n has_field_derivative f' n x) (at x)\"\n      and to_g: \"\\<forall>\\<^sub>F n in sequentially. \\<forall>x\\<in>S. norm (f n x) \\<le> h n\"\n  obtains g g' where \"\\<forall>x \\<in> S. ((\\<lambda>n. f n x) sums g x) \\<and> ((\\<lambda>n. f' n x) sums g' x) \\<and> (g has_field_derivative g' x) (at x)\"\nproof -\n  obtain g where g: \"uniform_limit S (\\<lambda>n x. \\<Sum>i<n. f i x) g sequentially\"\n    using Weierstrass_m_test_ev [OF to_g h]  by force\n  have *: \"\\<exists>d>0. cball x d \\<subseteq> S \\<and> uniform_limit (cball x d) (\\<lambda>n x. \\<Sum>i<n. f i x) g sequentially\"\n    if \"x \\<in> S\" for x\n    using open_contains_cball [of \"S\"] \\<open>x \\<in> S\\<close> S g uniform_limit_on_subset by blast\n  have \"\\<And>x. x \\<in> S \\<Longrightarrow> (\\<lambda>n. \\<Sum>i<n. f i x) \\<longlonglongrightarrow> g x\"\n    by (metis tendsto_uniform_limitI [OF g])\n  moreover have \"\\<exists>g'. \\<forall>x\\<in>S. (g has_field_derivative g' x) (at x) \\<and> (\\<lambda>n. \\<Sum>i<n. f' i x) \\<longlonglongrightarrow> g' x\"\n    by (rule has_complex_derivative_uniform_sequence [OF S]) (auto intro: * hfd DERIV_sum)+\n  ultimately show ?thesis\n    by (metis sums_def that)\nqed\n\ntext\\<open>A version where we only have local uniform/comparative convergence.\\<close>\n\nlemma series_and_derivative_comparison_local:\n  fixes S :: \"complex set\"\n  assumes S: \"open S\"\n      and hfd: \"\\<And>n x. x \\<in> S \\<Longrightarrow> (f n has_field_derivative f' n x) (at x)\"\n      and to_g: \"\\<And>x. x \\<in> S \\<Longrightarrow> \\<exists>d h. 0 < d \\<and> summable h \\<and> (\\<forall>\\<^sub>F n in sequentially. \\<forall>y\\<in>ball x d \\<inter> S. norm (f n y) \\<le> h n)\"\n  shows \"\\<exists>g g'. \\<forall>x \\<in> S. ((\\<lambda>n. f n x) sums g x) \\<and> ((\\<lambda>n. f' n x) sums g' x) \\<and> (g has_field_derivative g' x) (at x)\"\nproof -\n  have \"\\<exists>y. (\\<lambda>n. f n z) sums (\\<Sum>n. f n z) \\<and> (\\<lambda>n. f' n z) sums y \\<and> ((\\<lambda>x. \\<Sum>n. f n x) has_field_derivative y) (at z)\"\n       if \"z \\<in> S\" for z\n  proof -\n    obtain d h where \"0 < d\" \"summable h\" and le_h: \"\\<forall>\\<^sub>F n in sequentially. \\<forall>y\\<in>ball z d \\<inter> S. norm (f n y) \\<le> h n\"\n      using to_g \\<open>z \\<in> S\\<close> by meson\n    then obtain r where \"r>0\" and r: \"ball z r \\<subseteq> ball z d \\<inter> S\" using \\<open>z \\<in> S\\<close> S\n      by (metis Int_iff open_ball centre_in_ball open_Int open_contains_ball_eq)\n    have 1: \"open (ball z d \\<inter> S)\"\n      by (simp add: open_Int S)\n    have 2: \"\\<And>n x. x \\<in> ball z d \\<inter> S \\<Longrightarrow> (f n has_field_derivative f' n x) (at x)\"\n      by (auto simp: hfd)\n    obtain g g' where gg': \"\\<forall>x \\<in> ball z d \\<inter> S. ((\\<lambda>n. f n x) sums g x) \\<and>\n                                    ((\\<lambda>n. f' n x) sums g' x) \\<and> (g has_field_derivative g' x) (at x)\"\n      by (auto intro: le_h series_and_derivative_comparison [OF 1 \\<open>summable h\\<close> hfd])\n    then have \"(\\<lambda>n. f' n z) sums g' z\"\n      by (meson \\<open>0 < r\\<close> centre_in_ball contra_subsetD r)\n    moreover have \"(\\<lambda>n. f n z) sums (\\<Sum>n. f n z)\"\n      using  summable_sums centre_in_ball \\<open>0 < d\\<close> \\<open>summable h\\<close> le_h\n      by (metis (full_types) Int_iff gg' summable_def that)\n    moreover have \"((\\<lambda>x. \\<Sum>n. f n x) has_field_derivative g' z) (at z)\"\n      by (metis (no_types, lifting) \"1\" r \\<open>0 < r\\<close> gg' has_field_derivative_transform_within_open \n          open_contains_ball_eq sums_unique)\n    ultimately show ?thesis by auto\n  qed\n  then show ?thesis\n    by meson\nqed\n\n\ntext\\<open>Sometimes convenient to compare with a complex series of positive reals. (?)\\<close>\n\nlemma series_and_derivative_comparison_complex:\n  fixes S :: \"complex set\"\n  assumes S: \"open S\"\n      and hfd: \"\\<And>n x. x \\<in> S \\<Longrightarrow> (f n has_field_derivative f' n x) (at x)\"\n      and to_g: \"\\<And>x. x \\<in> S \\<Longrightarrow> \\<exists>d h. 0 < d \\<and> summable h \\<and> range h \\<subseteq> \\<real>\\<^sub>\\<ge>\\<^sub>0 \\<and> (\\<forall>\\<^sub>F n in sequentially. \\<forall>y\\<in>ball x d \\<inter> S. cmod(f n y) \\<le> cmod (h n))\"\n  shows \"\\<exists>g g'. \\<forall>x \\<in> S. ((\\<lambda>n. f n x) sums g x) \\<and> ((\\<lambda>n. f' n x) sums g' x) \\<and> (g has_field_derivative g' x) (at x)\"\napply (rule series_and_derivative_comparison_local [OF S hfd], assumption)\napply (rule ex_forward [OF to_g], assumption)\napply (erule exE)\napply (rule_tac x=\"Re \\<circ> h\" in exI)\napply (force simp: summable_Re o_def nonneg_Reals_cmod_eq_Re image_subset_iff)\ndone\n\ntext\\<open>Sometimes convenient to compare with a complex series of positive reals. (?)\\<close>\nlemma series_differentiable_comparison_complex:\n  fixes S :: \"complex set\"\n  assumes S: \"open S\"\n    and hfd: \"\\<And>n x. x \\<in> S \\<Longrightarrow> f n field_differentiable (at x)\"\n    and to_g: \"\\<And>x. x \\<in> S \\<Longrightarrow> \\<exists>d h. 0 < d \\<and> summable h \\<and> range h \\<subseteq> \\<real>\\<^sub>\\<ge>\\<^sub>0 \\<and> (\\<forall>\\<^sub>F n in sequentially. \\<forall>y\\<in>ball x d \\<inter> S. cmod(f n y) \\<le> cmod (h n))\"\n  obtains g where \"\\<forall>x \\<in> S. ((\\<lambda>n. f n x) sums g x) \\<and> g field_differentiable (at x)\"\nproof -\n  have hfd': \"\\<And>n x. x \\<in> S \\<Longrightarrow> (f n has_field_derivative deriv (f n) x) (at x)\"\n    using hfd field_differentiable_derivI by blast\n  show ?thesis\n    by (metis field_differentiable_def that series_and_derivative_comparison_complex [OF S hfd' to_g]) \nqed\n\ntext\\<open>In particular, a power series is analytic inside circle of convergence.\\<close>\n\nlemma power_series_and_derivative_0:\n  fixes a :: \"nat \\<Rightarrow> complex\" and r::real\n  assumes \"summable (\\<lambda>n. a n * r^n)\"\n    shows \"\\<exists>g g'. \\<forall>z. cmod z < r \\<longrightarrow>\n             ((\\<lambda>n. a n * z^n) sums g z) \\<and> ((\\<lambda>n. of_nat n * a n * z^(n - 1)) sums g' z) \\<and> (g has_field_derivative g' z) (at z)\"\nproof (cases \"0 < r\")\n  case True\n    have der: \"\\<And>n z. ((\\<lambda>x. a n * x ^ n) has_field_derivative of_nat n * a n * z ^ (n - 1)) (at z)\"\n      by (rule derivative_eq_intros | simp)+\n    have y_le: \"cmod y \\<le> cmod (of_real r + of_real (cmod z)) / 2\" \n      if \"cmod (z - y) * 2 < r - cmod z\" for z y\n      by (smt (verit, best) field_sum_of_halves norm_minus_commute norm_of_real norm_triangle_ineq2 of_real_add that)\n    have \"summable (\\<lambda>n. a n * complex_of_real r ^ n)\"\n      using assms \\<open>r > 0\\<close> by simp\n    moreover have \"\\<And>z. cmod z < r \\<Longrightarrow> cmod ((of_real r + of_real (cmod z)) / 2) < cmod (of_real r)\"\n      using \\<open>r > 0\\<close>\n      by (simp flip: of_real_add)\n    ultimately have sum: \"\\<And>z. cmod z < r \\<Longrightarrow> summable (\\<lambda>n. of_real (cmod (a n)) * ((of_real r + complex_of_real (cmod z)) / 2) ^ n)\"\n      by (rule power_series_conv_imp_absconv_weak)\n    have \"\\<exists>g g'. \\<forall>z \\<in> ball 0 r. (\\<lambda>n.  (a n) * z ^ n) sums g z \\<and>\n               (\\<lambda>n. of_nat n * (a n) * z ^ (n - 1)) sums g' z \\<and> (g has_field_derivative g' z) (at z)\"\n      apply (rule series_and_derivative_comparison_complex [OF open_ball der])\n      apply (rule_tac x=\"(r - norm z)/2\" in exI)\n      apply (rule_tac x=\"\\<lambda>n. of_real(norm(a n)*((r + norm z)/2)^n)\" in exI)\n      using \\<open>r > 0\\<close>\n      apply (auto simp: sum eventually_sequentially norm_mult norm_power dist_norm intro!: mult_left_mono power_mono y_le)\n      done\n  then show ?thesis\n    by (simp add: ball_def)\nnext\n  case False then show ?thesis\n    unfolding not_less using less_le_trans norm_not_less_zero by blast\nqed\n\nproposition\\<^marker>\\<open>tag unimportant\\<close> power_series_and_derivative:\n  fixes a :: \"nat \\<Rightarrow> complex\" and r::real\n  assumes \"summable (\\<lambda>n. a n * r^n)\"\n    obtains g g' where \"\\<forall>z \\<in> ball w r.\n             ((\\<lambda>n. a n * (z - w) ^ n) sums g z) \\<and> ((\\<lambda>n. of_nat n * a n * (z - w) ^ (n - 1)) sums g' z) \\<and>\n              (g has_field_derivative g' z) (at z)\"\n  using power_series_and_derivative_0 [OF assms]\n  apply clarify\n  apply (rule_tac g=\"(\\<lambda>z. g(z - w))\" in that)\n  using DERIV_shift [where z=\"-w\"]\n  apply (auto simp: norm_minus_commute Ball_def dist_norm)\n  done\n\nproposition\\<^marker>\\<open>tag unimportant\\<close> power_series_holomorphic:\n  assumes \"\\<And>w. w \\<in> ball z r \\<Longrightarrow> ((\\<lambda>n. a n*(w - z)^n) sums f w)\"\n    shows \"f holomorphic_on ball z r\"\nproof -\n  have \"\\<exists>f'. (f has_field_derivative f') (at w)\" if w: \"dist z w < r\" for w\n  proof -\n    have wz: \"cmod (w - z) < r\" using w\n      by (auto simp: field_split_simps dist_norm norm_minus_commute)\n    then have \"0 \\<le> r\"\n      by (meson less_eq_real_def norm_ge_zero order_trans)\n    have inb: \"z + complex_of_real ((dist z w + r) / 2) \\<in> ball z r\"\n      using w by (simp add: dist_norm \\<open>0\\<le>r\\<close> flip: of_real_add)\n    have sum: \"summable (\\<lambda>n. a n * of_real (((cmod (z - w) + r) / 2) ^ n))\"\n      using assms [OF inb] by (force simp: summable_def dist_norm)\n    obtain g g' where gg': \"\\<And>u. u \\<in> ball z ((cmod (z - w) + r) / 2) \\<Longrightarrow>\n                               (\\<lambda>n. a n * (u - z) ^ n) sums g u \\<and>\n                               (\\<lambda>n. of_nat n * a n * (u - z) ^ (n - 1)) sums g' u \\<and> (g has_field_derivative g' u) (at u)\"\n      by (rule power_series_and_derivative [OF sum, of z]) fastforce\n    have [simp]: \"g u = f u\" if \"cmod (u - w) < (r - cmod (z - w)) / 2\" for u\n    proof -\n      have less: \"cmod (z - u) * 2 < cmod (z - w) + r\"\n        using that dist_triangle2 [of z u w]\n        by (simp add: dist_norm [symmetric] algebra_simps)\n      have \"(\\<lambda>n. a n * (u - z) ^ n) sums g u\" \"(\\<lambda>n. a n * (u - z) ^ n) sums f u\"\n        using gg' [of u] less w by (auto simp: assms dist_norm)\n      then show ?thesis\n        by (metis sums_unique2)\n    qed\n    have \"(f has_field_derivative g' w) (at w)\"\n      by (rule has_field_derivative_transform_within [where d=\"(r - norm(z - w))/2\"])\n      (use w gg' [of w] in \\<open>(force simp: dist_norm)+\\<close>)\n    then show ?thesis ..\n  qed\n  then show ?thesis by (simp add: holomorphic_on_open)\nqed\n\ncorollary holomorphic_iff_power_series:\n     \"f holomorphic_on ball z r \\<longleftrightarrow>\n      (\\<forall>w \\<in> ball z r. (\\<lambda>n. (deriv ^^ n) f z / (fact n) * (w - z)^n) sums f w)\"\n  apply (intro iffI ballI holomorphic_power_series, assumption+)\n  apply (force intro: power_series_holomorphic [where a = \"\\<lambda>n. (deriv ^^ n) f z / (fact n)\"])\n  done\n\nlemma power_series_analytic:\n     \"(\\<And>w. w \\<in> ball z r \\<Longrightarrow> (\\<lambda>n. a n*(w - z)^n) sums f w) \\<Longrightarrow> f analytic_on ball z r\"\n  by (force simp: analytic_on_open intro!: power_series_holomorphic)\n\nlemma analytic_iff_power_series:\n     \"f analytic_on ball z r \\<longleftrightarrow>\n      (\\<forall>w \\<in> ball z r. (\\<lambda>n. (deriv ^^ n) f z / (fact n) * (w - z)^n) sums f w)\"\n  by (simp add: analytic_on_open holomorphic_iff_power_series)\n\nsubsection\\<^marker>\\<open>tag unimportant\\<close> \\<open>Equality between holomorphic functions, on open ball then connected set\\<close>\n\nlemma holomorphic_fun_eq_on_ball:\n   \"\\<lbrakk>f holomorphic_on ball z r; g holomorphic_on ball z r;\n     w \\<in> ball z r;\n     \\<And>n. (deriv ^^ n) f z = (deriv ^^ n) g z\\<rbrakk>\n     \\<Longrightarrow> f w = g w\"\n  by (auto simp: holomorphic_iff_power_series sums_unique2 [of \"\\<lambda>n. (deriv ^^ n) f z / (fact n) * (w - z)^n\"])\n\nlemma holomorphic_fun_eq_0_on_ball:\n   \"\\<lbrakk>f holomorphic_on ball z r;  w \\<in> ball z r;\n     \\<And>n. (deriv ^^ n) f z = 0\\<rbrakk>\n     \\<Longrightarrow> f w = 0\"\n  using holomorphic_fun_eq_on_ball [where g = \"\\<lambda>z. 0\"] by simp\n\nlemma holomorphic_fun_eq_0_on_connected:\n  assumes holf: \"f holomorphic_on S\" and \"open S\"\n      and cons: \"connected S\"\n      and der: \"\\<And>n. (deriv ^^ n) f z = 0\"\n      and \"z \\<in> S\" \"w \\<in> S\"\n    shows \"f w = 0\"\nproof -\n  have *: \"ball x e \\<subseteq> (\\<Inter>n. {w \\<in> S. (deriv ^^ n) f w = 0})\"\n    if \"\\<forall>u. (deriv ^^ u) f x = 0\" \"ball x e \\<subseteq> S\" for x e\n  proof -\n    have \"(deriv ^^ m) ((deriv ^^ n) f) x = 0\" for m n\n      by (metis funpow_add o_apply that(1))\n    then have \"\\<And>x' n. dist x x' < e \\<Longrightarrow> (deriv ^^ n) f x' = 0\"\n      using \\<open>open S\\<close> \n      by (meson holf holomorphic_fun_eq_0_on_ball holomorphic_higher_deriv holomorphic_on_subset mem_ball that(2))\n    with that show ?thesis by auto\n  qed\n  obtain e where \"e>0\" and e: \"ball w e \\<subseteq> S\" using openE [OF \\<open>open S\\<close> \\<open>w \\<in> S\\<close>] .\n  then have holfb: \"f holomorphic_on ball w e\"\n    using holf holomorphic_on_subset by blast\n  have \"open (\\<Inter>n. {w \\<in> S. (deriv ^^ n) f w = 0})\"\n    using \\<open>open S\\<close>\n    apply (simp add: open_contains_ball Ball_def image_iff)\n    by (metis (mono_tags) \"*\" mem_Collect_eq)\n  then have \"openin (top_of_set S) (\\<Inter>n. {w \\<in> S. (deriv ^^ n) f w = 0})\"\n    by (force intro: open_subset)\n  moreover have \"closedin (top_of_set S) (\\<Inter>n. {w \\<in> S. (deriv ^^ n) f w = 0})\"\n    using assms\n    by (auto intro: continuous_closedin_preimage_constant holomorphic_on_imp_continuous_on holomorphic_higher_deriv)\n  moreover have \"(\\<Inter>n. {w \\<in> S. (deriv ^^ n) f w = 0}) = S \\<Longrightarrow> f w = 0\"\n    using \\<open>e>0\\<close> e by (force intro: holomorphic_fun_eq_0_on_ball [OF holfb])\n  ultimately show ?thesis\n    using cons der \\<open>z \\<in> S\\<close>\n    by (auto simp add: connected_clopen)\nqed\n\nlemma holomorphic_fun_eq_on_connected:\n  assumes \"f holomorphic_on S\" \"g holomorphic_on S\" and \"open S\"  \"connected S\"\n      and \"\\<And>n. (deriv ^^ n) f z = (deriv ^^ n) g z\"\n      and \"z \\<in> S\" \"w \\<in> S\"\n    shows \"f w = g w\"\nproof (rule holomorphic_fun_eq_0_on_connected [of \"\\<lambda>x. f x - g x\" S z, simplified])\n  show \"(\\<lambda>x. f x - g x) holomorphic_on S\"\n    by (intro assms holomorphic_intros)\n  show \"\\<And>n. (deriv ^^ n) (\\<lambda>x. f x - g x) z = 0\"\n    using assms higher_deriv_diff by auto\nqed (use assms in auto)\n\nlemma holomorphic_fun_eq_const_on_connected:\n  assumes holf: \"f holomorphic_on S\" and \"open S\"\n      and cons: \"connected S\"\n      and der: \"\\<And>n. 0 < n \\<Longrightarrow> (deriv ^^ n) f z = 0\"\n      and \"z \\<in> S\" \"w \\<in> S\"\n    shows \"f w = f z\"\nproof (rule holomorphic_fun_eq_0_on_connected [of \"\\<lambda>w. f w - f z\" S z, simplified])\n  show \"(\\<lambda>w. f w - f z) holomorphic_on S\"\n    by (intro assms holomorphic_intros)\n  show \"\\<And>n. (deriv ^^ n) (\\<lambda>w. f w - f z) z = 0\"\n    by (subst higher_deriv_diff) (use assms in \\<open>auto intro: holomorphic_intros\\<close>)\nqed (use assms in auto)\n\nsubsection\\<^marker>\\<open>tag unimportant\\<close> \\<open>Some basic lemmas about poles/singularities\\<close>\n\nlemma pole_lemma:\n  assumes holf: \"f holomorphic_on S\" and a: \"a \\<in> interior S\"\n    shows \"(\\<lambda>z. if z = a then deriv f a\n                 else (f z - f a) / (z - a)) holomorphic_on S\" (is \"?F holomorphic_on S\")\nproof -\n  have *: \"?F field_differentiable (at u within S)\" if \"u \\<in> S\" \"u \\<noteq> a\" for u\n  proof -\n    have fcd: \"f field_differentiable at u within S\"\n      using holf holomorphic_on_def by (simp add: \\<open>u \\<in> S\\<close>)\n    have cd: \"(\\<lambda>z. (f z - f a) / (z - a)) field_differentiable at u within S\"\n      by (rule fcd derivative_intros | simp add: that)+\n    have \"0 < dist a u\" using that dist_nz by blast\n    then show ?thesis\n      by (rule field_differentiable_transform_within [OF _ _ _ cd]) (auto simp: \\<open>u \\<in> S\\<close>)\n  qed\n  moreover\n  have \"?F field_differentiable at a\" if \"0 < e\" \"ball a e \\<subseteq> S\" for e\n  proof -\n    have holfb: \"f holomorphic_on ball a e\"\n      by (rule holomorphic_on_subset [OF holf \\<open>ball a e \\<subseteq> S\\<close>])\n    have 2: \"?F holomorphic_on ball a e - {a}\"\n      using mem_ball that\n      by (auto simp add: holomorphic_on_def simp flip: field_differentiable_def intro: * field_differentiable_within_subset)\n    have \"isCont (\\<lambda>z. if z = a then deriv f a else (f z - f a) / (z - a)) x\"\n            if \"dist a x < e\" for x\n    proof (cases \"x=a\")\n      case True\n      then have \"f field_differentiable at a\"\n        using holfb \\<open>0 < e\\<close> holomorphic_on_imp_differentiable_at by auto\n      with True show ?thesis\n        by (smt (verit) DERIV_deriv_iff_field_differentiable LIM_equal continuous_at has_field_derivativeD)\n    next\n      case False with 2 that show ?thesis\n        by (simp add: field_differentiable_imp_continuous_at holomorphic_on_imp_differentiable_at open_Diff)\n    qed\n    then have 1: \"continuous_on (ball a e) ?F\"\n      by (clarsimp simp:  continuous_on_eq_continuous_at)\n    have \"?F holomorphic_on ball a e\"\n      by (auto intro: no_isolated_singularity [OF 1 2])\n    with that show ?thesis\n      by (simp add: holomorphic_on_open field_differentiable_def [symmetric]\n                    field_differentiable_at_within)\n  qed\n  ultimately show ?thesis\n    by (metis (no_types, lifting) holomorphic_onI a field_differentiable_at_within interior_subset openE open_interior subset_iff)\nqed\n\nlemma pole_theorem:\n  assumes holg: \"g holomorphic_on S\" and a: \"a \\<in> interior S\"\n      and eq: \"\\<And>z. z \\<in> S - {a} \\<Longrightarrow> g z = (z - a) * f z\"\n    shows \"(\\<lambda>z. if z = a then deriv g a\n                 else f z - g a/(z - a)) holomorphic_on S\"\n  using pole_lemma [OF holg a]\n  by (rule holomorphic_transform) (simp add: eq field_split_simps)\n\nlemma pole_lemma_open:\n  assumes \"f holomorphic_on S\" \"open S\"\n    shows \"(\\<lambda>z. if z = a then deriv f a else (f z - f a)/(z - a)) holomorphic_on S\"\nproof (cases \"a \\<in> S\")\n  case True with assms interior_eq pole_lemma\n    show ?thesis by fastforce\nnext\n  case False with assms show ?thesis\n    apply (simp add: holomorphic_on_def field_differentiable_def [symmetric], clarify)\n    apply (rule field_differentiable_transform_within [where f = \"\\<lambda>z. (f z - f a)/(z - a)\" and d = 1])\n    apply (rule derivative_intros | force)+\n    done\nqed\n\nlemma pole_theorem_open:\n  assumes holg: \"g holomorphic_on S\" and S: \"open S\"\n      and eq: \"\\<And>z. z \\<in> S - {a} \\<Longrightarrow> g z = (z - a) * f z\"\n    shows \"(\\<lambda>z. if z = a then deriv g a\n                 else f z - g a/(z - a)) holomorphic_on S\"\n  using pole_lemma_open [OF holg S]\n  by (rule holomorphic_transform) (auto simp: eq divide_simps)\n\nlemma pole_theorem_0:\n  assumes holg: \"g holomorphic_on S\" and a: \"a \\<in> interior S\"\n      and eq: \"\\<And>z. z \\<in> S - {a} \\<Longrightarrow> g z = (z - a) * f z\"\n      and [simp]: \"f a = deriv g a\" \"g a = 0\"\n    shows \"f holomorphic_on S\"\n  using pole_theorem [OF holg a eq]\n  by (rule holomorphic_transform) (auto simp: eq field_split_simps)\n\nlemma pole_theorem_open_0:\n  assumes holg: \"g holomorphic_on S\" and S: \"open S\"\n      and eq: \"\\<And>z. z \\<in> S - {a} \\<Longrightarrow> g z = (z - a) * f z\"\n      and [simp]: \"f a = deriv g a\" \"g a = 0\"\n    shows \"f holomorphic_on S\"\n  using pole_theorem_open [OF holg S eq]\n  by (rule holomorphic_transform) (auto simp: eq field_split_simps)\n\nlemma pole_theorem_analytic:\n  assumes g: \"g analytic_on S\"\n      and eq: \"\\<And>z. z \\<in> S\n             \\<Longrightarrow> \\<exists>d. 0 < d \\<and> (\\<forall>w \\<in> ball z d - {a}. g w = (w - a) * f w)\"\n    shows \"(\\<lambda>z. if z = a then deriv g a else f z - g a/(z - a)) analytic_on S\" (is \"?F analytic_on S\")\n  unfolding analytic_on_def\nproof\n  fix x\n  assume \"x \\<in> S\"\n  with g obtain e where \"0 < e\" and e: \"g holomorphic_on ball x e\"\n    by (auto simp add: analytic_on_def)\n  obtain d where \"0 < d\" and d: \"\\<And>w. w \\<in> ball x d - {a} \\<Longrightarrow> g w = (w - a) * f w\"\n    using \\<open>x \\<in> S\\<close> eq by blast\n  have \"?F holomorphic_on ball x (min d e)\"\n    using d e \\<open>x \\<in> S\\<close> by (fastforce simp: holomorphic_on_subset subset_ball intro!: pole_theorem_open)\n  then show \"\\<exists>e>0. ?F holomorphic_on ball x e\"\n    using \\<open>0 < d\\<close> \\<open>0 < e\\<close> not_le by fastforce\nqed\n\nlemma pole_theorem_analytic_0:\n  assumes g: \"g analytic_on S\"\n      and eq: \"\\<And>z. z \\<in> S \\<Longrightarrow> \\<exists>d. 0 < d \\<and> (\\<forall>w \\<in> ball z d - {a}. g w = (w - a) * f w)\"\n      and [simp]: \"f a = deriv g a\" \"g a = 0\"\n    shows \"f analytic_on S\"\nproof -\n  have [simp]: \"(\\<lambda>z. if z = a then deriv g a else f z - g a / (z - a)) = f\"\n    by auto\n  show ?thesis\n    using pole_theorem_analytic [OF g eq] by simp\nqed\n\nlemma pole_theorem_analytic_open_superset:\n  assumes g: \"g analytic_on S\" and \"S \\<subseteq> T\" \"open T\"\n      and eq: \"\\<And>z. z \\<in> T - {a} \\<Longrightarrow> g z = (z - a) * f z\"\n    shows \"(\\<lambda>z. if z = a then deriv g a\n                 else f z - g a/(z - a)) analytic_on S\"\nproof (rule pole_theorem_analytic [OF g])\n  fix z\n  assume \"z \\<in> S\"\n  then obtain e where \"0 < e\" and e: \"ball z e \\<subseteq> T\"\n    using assms openE by blast\n  then show \"\\<exists>d>0. \\<forall>w\\<in>ball z d - {a}. g w = (w - a) * f w\"\n    using eq by auto\nqed\n\nlemma pole_theorem_analytic_open_superset_0:\n  assumes g: \"g analytic_on S\" \"S \\<subseteq> T\" \"open T\" \"\\<And>z. z \\<in> T - {a} \\<Longrightarrow> g z = (z - a) * f z\"\n      and [simp]: \"f a = deriv g a\" \"g a = 0\"\n    shows \"f analytic_on S\"\nproof -\n  have [simp]: \"(\\<lambda>z. if z = a then deriv g a else f z - g a / (z - a)) = f\"\n    by auto\n  have \"(\\<lambda>z. if z = a then deriv g a else f z - g a/(z - a)) analytic_on S\"\n    by (rule pole_theorem_analytic_open_superset [OF g])\n  then show ?thesis by simp\nqed\n\n\nsubsection\\<open>General, homology form of Cauchy's theorem\\<close>\n\ntext\\<open>Proof is based on Dixon's, as presented in Lang's \"Complex Analysis\" book (page 147).\\<close>\n\nlemma contour_integral_continuous_on_linepath_2D:\n  assumes \"open U\" and cont_dw: \"\\<And>w. w \\<in> U \\<Longrightarrow> F w contour_integrable_on (linepath a b)\"\n      and cond_uu: \"continuous_on (U \\<times> U) (\\<lambda>(x,y). F x y)\"\n      and abu: \"closed_segment a b \\<subseteq> U\"\n    shows \"continuous_on U (\\<lambda>w. contour_integral (linepath a b) (F w))\"\nproof -\n  have *: \"\\<exists>d>0. \\<forall>x'\\<in>U. dist x' w < d \\<longrightarrow>\n                         dist (contour_integral (linepath a b) (F x'))\n                              (contour_integral (linepath a b) (F w)) \\<le> \\<epsilon>\"\n          if \"w \\<in> U\" \"0 < \\<epsilon>\" \"a \\<noteq> b\" for w \\<epsilon>\n  proof -\n    obtain \\<delta> where \"\\<delta>>0\" and \\<delta>: \"cball w \\<delta> \\<subseteq> U\" using open_contains_cball \\<open>open U\\<close> \\<open>w \\<in> U\\<close> by force\n    let ?TZ = \"cball w \\<delta>  \\<times> closed_segment a b\"\n    have \"uniformly_continuous_on ?TZ (\\<lambda>(x,y). F x y)\"\n    proof (rule compact_uniformly_continuous)\n      show \"continuous_on ?TZ (\\<lambda>(x,y). F x y)\"\n        by (rule continuous_on_subset[OF cond_uu]) (use SigmaE \\<delta> abu in blast)\n      show \"compact ?TZ\"\n        by (simp add: compact_Times)\n    qed\n    then obtain \\<eta> where \"\\<eta>>0\"\n        and \\<eta>: \"\\<And>x x'. \\<lbrakk>x\\<in>?TZ; x'\\<in>?TZ; dist x' x < \\<eta>\\<rbrakk> \\<Longrightarrow>\n                         dist ((\\<lambda>(x,y). F x y) x') ((\\<lambda>(x,y). F x y) x) < \\<epsilon>/norm(b - a)\"\n      using \\<open>0 < \\<epsilon>\\<close> \\<open>a \\<noteq> b\\<close>\n      by (auto elim: uniformly_continuous_onE [where e = \"\\<epsilon>/norm(b - a)\"])\n    have \\<eta>: \"\\<lbrakk>norm (w - x1) \\<le> \\<delta>;   x2 \\<in> closed_segment a b;\n              norm (w - x1') \\<le> \\<delta>;  x2' \\<in> closed_segment a b; norm ((x1', x2') - (x1, x2)) < \\<eta>\\<rbrakk>\n              \\<Longrightarrow> norm (F x1' x2' - F x1 x2) \\<le> \\<epsilon> / cmod (b - a)\"\n             for x1 x2 x1' x2'\n      using \\<eta> [of \"(x1,x2)\" \"(x1',x2')\"] by (force simp: dist_norm)\n    have le_ee: \"cmod (contour_integral (linepath a b) (\\<lambda>x. F x' x - F w x)) \\<le> \\<epsilon>\"\n                if \"x' \\<in> U\" \"cmod (x' - w) < \\<delta>\" \"cmod (x' - w) < \\<eta>\"  for x'\n    proof -\n      have \"(\\<lambda>x. F x' x - F w x) contour_integrable_on linepath a b\"\n        by (simp add: \\<open>w \\<in> U\\<close> cont_dw contour_integrable_diff that)\n      then have \"cmod (contour_integral (linepath a b) (\\<lambda>x. F x' x - F w x)) \\<le> \\<epsilon>/norm(b - a) * norm(b - a)\"\n        using has_contour_integral_bound_linepath [OF has_contour_integral_integral _ \\<eta>]\n        using \\<open>0 < \\<epsilon>\\<close> \\<open>0 < \\<delta>\\<close> that by (force simp: norm_minus_commute)\n      also have \"\\<dots> = \\<epsilon>\" using \\<open>a \\<noteq> b\\<close> by simp\n      finally show ?thesis .\n    qed\n    show ?thesis\n      apply (rule_tac x=\"min \\<delta> \\<eta>\" in exI)\n      using \\<open>0 < \\<delta>\\<close> \\<open>0 < \\<eta>\\<close>\n      by (auto simp: dist_norm contour_integral_diff [OF cont_dw cont_dw, symmetric] \\<open>w \\<in> U\\<close> intro: le_ee)\n  qed\n  show ?thesis\n  proof (cases \"a=b\")\n    case False\n    show ?thesis\n      by (rule continuous_onI) (use False in \\<open>auto intro: *\\<close>)\n  qed auto\nqed\n\ntext\\<open>This version has \\<^term>\\<open>polynomial_function \\<gamma>\\<close> as an additional assumption.\\<close>\nlemma Cauchy_integral_formula_global_weak:\n  assumes \"open U\" and holf: \"f holomorphic_on U\"\n        and z: \"z \\<in> U\" and \\<gamma>: \"polynomial_function \\<gamma>\"\n        and pasz: \"path_image \\<gamma> \\<subseteq> U - {z}\" and loop: \"pathfinish \\<gamma> = pathstart \\<gamma>\"\n        and zero: \"\\<And>w. w \\<notin> U \\<Longrightarrow> winding_number \\<gamma> w = 0\"\n      shows \"((\\<lambda>w. f w / (w - z)) has_contour_integral (2*pi * \\<i> * winding_number \\<gamma> z * f z)) \\<gamma>\"\nproof -\n  obtain \\<gamma>' where pf\\<gamma>': \"polynomial_function \\<gamma>'\" and \\<gamma>': \"\\<And>x. (\\<gamma> has_vector_derivative (\\<gamma>' x)) (at x)\"\n    using has_vector_derivative_polynomial_function [OF \\<gamma>] by blast\n  then have \"bounded(path_image \\<gamma>')\"\n    by (simp add: path_image_def compact_imp_bounded compact_continuous_image continuous_on_polymonial_function)\n  then obtain B where \"B>0\" and B: \"\\<And>x. x \\<in> path_image \\<gamma>' \\<Longrightarrow> norm x \\<le> B\"\n    using bounded_pos by force\n  define d where [abs_def]: \"d z w = (if w = z then deriv f z else (f w - f z)/(w - z))\" for z w\n  define v where \"v = {w. w \\<notin> path_image \\<gamma> \\<and> winding_number \\<gamma> w = 0}\"\n  have \"path \\<gamma>\" \"valid_path \\<gamma>\" using \\<gamma>\n    by (auto simp: path_polynomial_function valid_path_polynomial_function)\n  then have ov: \"open v\"\n    by (simp add: v_def open_winding_number_levelsets loop)\n  have uv_Un: \"U \\<union> v = UNIV\"\n    using pasz zero by (auto simp: v_def)\n  have conf: \"continuous_on U f\"\n    by (metis holf holomorphic_on_imp_continuous_on)\n  have hol_d: \"(d y) holomorphic_on U\" if \"y \\<in> U\" for y\n  proof -\n    have *: \"(\\<lambda>c. if c = y then deriv f y else (f c - f y) / (c - y)) holomorphic_on U\"\n      by (simp add: holf pole_lemma_open \\<open>open U\\<close>)\n    then have \"isCont (\\<lambda>x. if x = y then deriv f y else (f x - f y) / (x - y)) y\"\n      using at_within_open field_differentiable_imp_continuous_at holomorphic_on_def that \\<open>open U\\<close> by fastforce\n    then have \"continuous_on U (d y)\"\n      using \"*\" d_def holomorphic_on_imp_continuous_on by auto\n    moreover have \"d y holomorphic_on U - {y}\"\n    proof -\n      have \"(\\<lambda>w. if w = y then deriv f y else (f w - f y) / (w - y)) field_differentiable at w\"\n        if \"w \\<in> U - {y}\" for w\n      proof (rule field_differentiable_transform_within)\n        show \"(\\<lambda>w. (f w - f y) / (w - y)) field_differentiable at w\"\n          using that \\<open>open U\\<close> holf \n          by (auto intro!: holomorphic_on_imp_differentiable_at derivative_intros)\n        show \"dist w y > 0\"\n          using that by auto\n      qed (auto simp: dist_commute)\n      then show ?thesis\n        unfolding field_differentiable_def by (simp add: d_def holomorphic_on_open \\<open>open U\\<close> open_delete)\n    qed\n    ultimately show ?thesis\n      by (rule no_isolated_singularity) (auto simp: \\<open>open U\\<close>)\n  qed\n  have cint_fxy: \"(\\<lambda>x. (f x - f y) / (x - y)) contour_integrable_on \\<gamma>\" if \"y \\<notin> path_image \\<gamma>\" for y\n  proof (rule contour_integrable_holomorphic_simple [where S = \"U-{y}\"])\n    show \"(\\<lambda>x. (f x - f y) / (x - y)) holomorphic_on U - {y}\"\n      by (force intro: holomorphic_intros holomorphic_on_subset [OF holf])\n    show \"path_image \\<gamma> \\<subseteq> U - {y}\"\n      using pasz that by blast\n  qed (auto simp: \\<open>open U\\<close> open_delete \\<open>valid_path \\<gamma>\\<close>)\n  define h where\n    \"h z = (if z \\<in> U then contour_integral \\<gamma> (d z) else contour_integral \\<gamma> (\\<lambda>w. f w/(w - z)))\" for z\n  have U: \"((d z) has_contour_integral h z) \\<gamma>\" if \"z \\<in> U\" for z\n  proof -\n    have \"d z holomorphic_on U\"\n      by (simp add: hol_d that)\n    with that show ?thesis\n      by (metis Diff_subset \\<open>valid_path \\<gamma>\\<close> \\<open>open U\\<close> contour_integrable_holomorphic_simple h_def has_contour_integral_integral pasz subset_trans)\n  qed\n  have V: \"((\\<lambda>w. f w / (w - z)) has_contour_integral h z) \\<gamma>\" if z: \"z \\<in> v\" for z\n  proof -\n    have 0: \"0 = (f z) * 2 * of_real (2 * pi) * \\<i> * winding_number \\<gamma> z\"\n      using v_def z by auto\n    then have \"((\\<lambda>x. 1 / (x - z)) has_contour_integral 0) \\<gamma>\"\n     using z v_def  has_contour_integral_winding_number [OF \\<open>valid_path \\<gamma>\\<close>] by fastforce\n    then have \"((\\<lambda>x. f z * (1 / (x - z))) has_contour_integral 0) \\<gamma>\"\n      using has_contour_integral_lmul by fastforce\n    then have \"((\\<lambda>x. f z / (x - z)) has_contour_integral 0) \\<gamma>\"\n      by (simp add: field_split_simps)\n    moreover have \"((\\<lambda>x. (f x - f z) / (x - z)) has_contour_integral contour_integral \\<gamma> (d z)) \\<gamma>\"\n      using z\n      apply (simp add: v_def)\n      apply (metis (no_types, lifting) contour_integrable_eq d_def has_contour_integral_eq has_contour_integral_integral cint_fxy)\n      done\n    ultimately have *: \"((\\<lambda>x. f z / (x - z) + (f x - f z) / (x - z)) has_contour_integral (0 + contour_integral \\<gamma> (d z))) \\<gamma>\"\n      by (rule has_contour_integral_add)\n    have \"((\\<lambda>w. f w / (w - z)) has_contour_integral contour_integral \\<gamma> (d z)) \\<gamma>\"\n      if \"z \\<in> U\"\n      using * by (auto simp: divide_simps has_contour_integral_eq)\n    moreover have \"((\\<lambda>w. f w / (w - z)) has_contour_integral contour_integral \\<gamma> (\\<lambda>w. f w / (w - z))) \\<gamma>\"\n      if \"z \\<notin> U\"\n    proof (rule has_contour_integral_integral [OF contour_integrable_holomorphic_simple [where S=U]])\n      show \"(\\<lambda>w. f w / (w - z)) holomorphic_on U\"\n        by (rule holomorphic_intros assms | use that in force)+\n    qed (use \\<open>open U\\<close> pasz \\<open>valid_path \\<gamma>\\<close> in auto)\n    ultimately show ?thesis\n      using z by (simp add: h_def)\n  qed\n  have znot: \"z \\<notin> path_image \\<gamma>\"\n    using pasz by blast\n  obtain d0 where \"d0>0\" and d0: \"\\<And>x y. x \\<in> path_image \\<gamma> \\<Longrightarrow> y \\<in> - U \\<Longrightarrow> d0 \\<le> dist x y\"\n    using separate_compact_closed [of \"path_image \\<gamma>\" \"-U\"] pasz \\<open>open U\\<close> \\<open>path \\<gamma>\\<close> compact_path_image\n    by blast    \n  obtain dd where \"0 < dd\" and dd: \"{y + k | y k. y \\<in> path_image \\<gamma> \\<and> k \\<in> ball 0 dd} \\<subseteq> U\"\n  proof\n    show \"0 < d0 / 2\" using \\<open>0 < d0\\<close> by auto\n  qed (use \\<open>0 < d0\\<close> d0 in \\<open>force simp: dist_norm\\<close>)\n  define T where \"T \\<equiv> {y + k |y k. y \\<in> path_image \\<gamma> \\<and> k \\<in> cball 0 (dd / 2)}\"\n  have \"\\<And>x x'. \\<lbrakk>x \\<in> path_image \\<gamma>; dist x x' * 2 < dd\\<rbrakk> \\<Longrightarrow> \\<exists>y k. x' = y + k \\<and> y \\<in> path_image \\<gamma> \\<and> dist 0 k * 2 \\<le> dd\"\n    apply (rule_tac x=x in exI)\n    apply (rule_tac x=\"x'-x\" in exI)\n    apply (force simp: dist_norm)\n    done\n  then have subt: \"path_image \\<gamma> \\<subseteq> interior T\"\n    using \\<open>0 < dd\\<close> \n    apply (clarsimp simp add: mem_interior T_def)\n    apply (rule_tac x=\"dd/2\" in exI, auto)\n    done\n  have \"compact T\"\n    unfolding T_def\n    using \\<open>valid_path \\<gamma>\\<close> compact_cball compact_sums compact_valid_path_image by blast\n  have T: \"T \\<subseteq> U\"\n    unfolding T_def using \\<open>0 < dd\\<close> dd by fastforce\n  obtain L where \"L>0\"\n           and L: \"\\<And>f B. \\<lbrakk>f holomorphic_on interior T; \\<And>z. z\\<in>interior T \\<Longrightarrow> cmod (f z) \\<le> B\\<rbrakk> \\<Longrightarrow>\n                         cmod (contour_integral \\<gamma> f) \\<le> L * B\"\n      using contour_integral_bound_exists [OF open_interior \\<open>valid_path \\<gamma>\\<close> subt]\n      by blast\n  have \"bounded(f ` T)\"\n    by (meson \\<open>compact T\\<close> compact_continuous_image compact_imp_bounded conf continuous_on_subset T)\n  then obtain D where \"D>0\" and D: \"\\<And>x. x \\<in> T \\<Longrightarrow> norm (f x) \\<le> D\"\n    by (auto simp: bounded_pos)\n  obtain C where \"C>0\" and C: \"\\<And>x. x \\<in> T \\<Longrightarrow> norm x \\<le> C\"\n    using \\<open>compact T\\<close> bounded_pos compact_imp_bounded by force\n  have \"dist (h y) 0 \\<le> e\" if \"0 < e\" and le: \"D * L / e + C \\<le> cmod y\" for e y\n  proof -\n    have \"D * L / e > 0\"  using \\<open>D>0\\<close> \\<open>L>0\\<close> \\<open>e>0\\<close> by simp\n    with le have ybig: \"norm y > C\" by force\n    with C have \"y \\<notin> T\"  by force\n    then have ynot: \"y \\<notin> path_image \\<gamma>\"\n      using subt interior_subset by blast\n    have [simp]: \"winding_number \\<gamma> y = 0\"\n    proof (rule winding_number_zero_outside)\n      show \"path_image \\<gamma> \\<subseteq> cball 0 C\"\n        by (meson C interior_subset mem_cball_0 subset_eq subt)\n    qed (use ybig loop \\<open>path \\<gamma>\\<close> in auto)\n    have [simp]: \"h y = contour_integral \\<gamma> (\\<lambda>w. f w/(w - y))\"\n      by (rule contour_integral_unique [symmetric]) (simp add: v_def ynot V)\n    have holint: \"(\\<lambda>w. f w / (w - y)) holomorphic_on interior T\"\n    proof (intro holomorphic_intros)\n      show \"f holomorphic_on interior T\"\n        using holf holomorphic_on_subset interior_subset T by blast\n    qed (use \\<open>y \\<notin> T\\<close> interior_subset in auto)\n    have leD: \"cmod (f z / (z - y)) \\<le> D * (e / L / D)\" if z: \"z \\<in> interior T\" for z\n    proof -\n      have \"D * L / e + cmod z \\<le> cmod y\"\n        using le C [of z] z using interior_subset by force\n      then have DL2: \"D * L / e \\<le> cmod (z - y)\"\n        using norm_triangle_ineq2 [of y z] by (simp add: norm_minus_commute)\n      have \"cmod (f z / (z - y)) = cmod (f z) * inverse (cmod (z - y))\"\n        by (simp add: norm_mult norm_inverse Fields.field_class.field_divide_inverse)\n      also have \"\\<dots> \\<le> D * (e / L / D)\"\n      proof (rule mult_mono)\n        show \"cmod (f z) \\<le> D\"\n          using D interior_subset z by blast \n        show \"inverse (cmod (z - y)) \\<le> e / L / D\" \"D \\<ge> 0\"\n          using \\<open>L>0\\<close> \\<open>e>0\\<close> \\<open>D>0\\<close> DL2 by (auto simp: norm_divide field_split_simps)\n      qed auto\n      finally show ?thesis .\n    qed\n    have \"dist (h y) 0 = cmod (contour_integral \\<gamma> (\\<lambda>w. f w / (w - y)))\"\n      by (simp add: dist_norm)\n    also have \"\\<dots> \\<le> L * (D * (e / L / D))\"\n      by (rule L [OF holint leD])\n    also have \"\\<dots> = e\"\n      using  \\<open>L>0\\<close> \\<open>0 < D\\<close> by auto\n    finally show ?thesis .\n  qed\n  then have \"(h \\<longlongrightarrow> 0) at_infinity\"\n    by (meson Lim_at_infinityI)\n  moreover have \"h holomorphic_on UNIV\"\n  proof -\n    have con_ff: \"continuous (at (x,z)) (\\<lambda>(x,y). (f y - f x) / (y - x))\"\n                 if \"x \\<in> U\" \"z \\<in> U\" \"x \\<noteq> z\" for x z\n      using that conf\n      apply (simp add: split_def continuous_on_eq_continuous_at \\<open>open U\\<close>)\n      apply (simp | rule continuous_intros continuous_within_compose2 [where g=f])+\n      done\n    have con_fstsnd: \"continuous_on UNIV (\\<lambda>x. (fst x - snd x) ::complex)\"\n      by (rule continuous_intros)+\n    have open_uu_Id: \"open (U \\<times> U - Id)\"\n    proof (rule open_Diff)\n      show \"open (U \\<times> U)\"\n        by (simp add: open_Times \\<open>open U\\<close>)\n      show \"closed (Id :: complex rel)\"\n        using continuous_closed_preimage_constant [OF con_fstsnd closed_UNIV, of 0]\n        by (auto simp: Id_fstsnd_eq algebra_simps)\n    qed\n    have con_derf: \"continuous (at z) (deriv f)\" if \"z \\<in> U\" for z\n      by (meson analytic_at analytic_at_imp_isCont assms(1) holf holomorphic_deriv that)\n    have tendsto_f': \"((\\<lambda>(x,y). if y = x then deriv f (x)\n                                else (f (y) - f (x)) / (y - x)) \\<longlongrightarrow> deriv f x)\n                      (at (x, x) within U \\<times> U)\" if \"x \\<in> U\" for x\n    proof (rule Lim_withinI)\n      fix e::real assume \"0 < e\"\n      obtain k1 where \"k1>0\" and k1: \"\\<And>x'. norm (x' - x) \\<le> k1 \\<Longrightarrow> norm (deriv f x' - deriv f x) < e\"\n        using \\<open>0 < e\\<close> continuous_within_E [OF con_derf [OF \\<open>x \\<in> U\\<close>]]\n        by (metis UNIV_I dist_norm)\n      obtain k2 where \"k2>0\" and k2: \"ball x k2 \\<subseteq> U\"\n        by (blast intro: openE [OF \\<open>open U\\<close>] \\<open>x \\<in> U\\<close>)\n      have neq: \"norm ((f z' - f x') / (z' - x') - deriv f x) \\<le> e\"\n                    if \"z' \\<noteq> x'\" and less_k1: \"norm (x'-x, z'-x) < k1\" and less_k2: \"norm (x'-x, z'-x) < k2\"\n                 for x' z'\n      proof -\n        have cs_less: \"w \\<in> closed_segment x' z' \\<Longrightarrow> cmod (w - x) \\<le> norm (x'-x, z'-x)\" for w\n          using segment_furthest_le [of w x' z' x]\n          by (metis (no_types) dist_commute dist_norm norm_fst_le norm_snd_le order_trans)\n        have derf_le: \"w \\<in> closed_segment x' z' \\<Longrightarrow> z' \\<noteq> x' \\<Longrightarrow> cmod (deriv f w - deriv f x) \\<le> e\" for w\n          by (blast intro: cs_less less_k1 k1 [unfolded divide_const_simps dist_norm] less_imp_le le_less_trans)\n        have f_has_der: \"\\<And>x. x \\<in> U \\<Longrightarrow> (f has_field_derivative deriv f x) (at x within U)\"\n          by (metis DERIV_deriv_iff_field_differentiable at_within_open holf holomorphic_on_def \\<open>open U\\<close>)\n        have \"closed_segment x' z' \\<subseteq> U\"\n          by (rule order_trans [OF _ k2]) (simp add: cs_less  le_less_trans [OF _ less_k2] dist_complex_def norm_minus_commute subset_iff)\n        then have cint_derf: \"(deriv f has_contour_integral f z' - f x') (linepath x' z')\"\n          using contour_integral_primitive [OF f_has_der valid_path_linepath] pasz  by simp\n        then have *: \"((\\<lambda>x. deriv f x / (z' - x')) has_contour_integral (f z' - f x') / (z' - x')) (linepath x' z')\"\n          by (rule has_contour_integral_div)\n        have \"norm ((f z' - f x') / (z' - x') - deriv f x) \\<le> e/norm(z' - x') * norm(z' - x')\"\n          apply (rule has_contour_integral_bound_linepath [OF has_contour_integral_diff [OF *]])\n          using has_contour_integral_div [where c = \"z' - x'\", OF has_contour_integral_const_linepath [of \"deriv f x\" z' x']]\n                 \\<open>e > 0\\<close>  \\<open>z' \\<noteq> x'\\<close>\n          apply (auto simp: norm_divide divide_simps derf_le)\n          done\n        also have \"\\<dots> \\<le> e\" using \\<open>0 < e\\<close> by simp\n        finally show ?thesis .\n      qed\n      show \"\\<exists>d>0. \\<forall>xa\\<in>U \\<times> U.\n                  0 < dist xa (x, x) \\<and> dist xa (x, x) < d \\<longrightarrow>\n                  dist (case xa of (x, y) \\<Rightarrow> if y = x then deriv f x else (f y - f x) / (y - x)) (deriv f x) \\<le> e\"\n        apply (rule_tac x=\"min k1 k2\" in exI)\n        using \\<open>k1>0\\<close> \\<open>k2>0\\<close> \\<open>e>0\\<close>\n        by (force simp: dist_norm neq intro: dual_order.strict_trans2 k1 less_imp_le norm_fst_le)\n    qed\n    have con_pa_f: \"continuous_on (path_image \\<gamma>) f\"\n      by (meson holf holomorphic_on_imp_continuous_on holomorphic_on_subset interior_subset subt T)\n    have le_B: \"\\<And>T. T \\<in> {0..1} \\<Longrightarrow> cmod (vector_derivative \\<gamma> (at T)) \\<le> B\"\n      using \\<gamma>' B by (simp add: path_image_def vector_derivative_at rev_image_eqI)\n    have f_has_cint: \"\\<And>w. w \\<in> v - path_image \\<gamma> \\<Longrightarrow> ((\\<lambda>u. f u / (u - w) ^ 1) has_contour_integral h w) \\<gamma>\"\n      by (simp add: V)\n    have cond_uu: \"continuous_on (U \\<times> U) (\\<lambda>(x,y). d x y)\"\n      apply (simp add: continuous_on_eq_continuous_within d_def continuous_within tendsto_f')\n      apply (simp add: tendsto_within_open_NO_MATCH open_Times \\<open>open U\\<close>, clarify)\n      apply (rule Lim_transform_within_open [OF _ open_uu_Id, where f = \"(\\<lambda>(x,y). (f y - f x) / (y - x))\"])\n      using con_ff\n      apply (auto simp: continuous_within)\n      done\n    have hol_dw: \"(\\<lambda>z. d z w) holomorphic_on U\" if \"w \\<in> U\" for w\n    proof -\n      have \"continuous_on U ((\\<lambda>(x,y). d x y) \\<circ> (\\<lambda>z. (w,z)))\"\n        by (rule continuous_on_compose continuous_intros continuous_on_subset [OF cond_uu] | force intro: that)+\n      then have *: \"continuous_on U (\\<lambda>z. if w = z then deriv f z else (f w - f z) / (w - z))\"\n        by (rule rev_iffD1 [OF _ continuous_on_cong [OF refl]]) (simp add: d_def field_simps)\n      have **: \"(\\<lambda>z. if w = z then deriv f z else (f w - f z) / (w - z)) field_differentiable at x\"\n        if \"x \\<in> U\" \"x \\<noteq> w\" for x\n      proof (rule_tac f = \"\\<lambda>x. (f w - f x)/(w - x)\" and d = \"dist x w\" in field_differentiable_transform_within)\n        show \"(\\<lambda>x. (f w - f x) / (w - x)) field_differentiable at x\"\n          using that \\<open>open U\\<close>\n          by (intro derivative_intros holomorphic_on_imp_differentiable_at [OF holf]; force)\n      qed (use that \\<open>open U\\<close> in \\<open>auto simp: dist_commute\\<close>)\n      show ?thesis\n        unfolding d_def\n      proof (rule no_isolated_singularity [OF * _ \\<open>open U\\<close>])\n        show \"(\\<lambda>z. if w = z then deriv f z else (f w - f z) / (w - z)) holomorphic_on U - {w}\"\n          by (auto simp: field_differentiable_def [symmetric] holomorphic_on_open open_Diff \\<open>open U\\<close> **)\n      qed auto\n    qed\n    { fix a b\n      assume abu: \"closed_segment a b \\<subseteq> U\"\n      have cont_cint_d: \"continuous_on U (\\<lambda>w. contour_integral (linepath a b) (\\<lambda>z. d z w))\"\n      proof (rule contour_integral_continuous_on_linepath_2D [OF \\<open>open U\\<close> _ _ abu])\n        show \"\\<And>w. w \\<in> U \\<Longrightarrow> (\\<lambda>z. d z w) contour_integrable_on (linepath a b)\"\n          by (metis abu hol_dw continuous_on_subset contour_integrable_continuous_linepath holomorphic_on_imp_continuous_on)\n        show \"continuous_on (U \\<times> U) (\\<lambda>(x, y). d y x)\"\n          by (auto intro: continuous_on_swap_args cond_uu)\n      qed\n      have cont_cint_d\\<gamma>: \"continuous_on {0..1} ((\\<lambda>w. contour_integral (linepath a b) (\\<lambda>z. d z w)) \\<circ> \\<gamma>)\"\n      proof (rule continuous_on_compose)\n        show \"continuous_on {0..1} \\<gamma>\"\n          using \\<open>path \\<gamma>\\<close> path_def by blast\n        show \"continuous_on (\\<gamma> ` {0..1}) (\\<lambda>w. contour_integral (linepath a b) (\\<lambda>z. d z w))\"\n          using pasz unfolding path_image_def\n          by (auto intro!: continuous_on_subset [OF cont_cint_d])\n      qed\n      have \"continuous_on {0..1} (\\<lambda>x. vector_derivative \\<gamma> (at x))\"\n        using pf\\<gamma>' by (simp add: continuous_on_polymonial_function vector_derivative_at [OF \\<gamma>'])\n      then      have cint_cint: \"(\\<lambda>w. contour_integral (linepath a b) (\\<lambda>z. d z w)) contour_integrable_on \\<gamma>\"\n        apply (simp add: contour_integrable_on)\n        apply (rule integrable_continuous_real)\n        by (rule continuous_on_mult [OF cont_cint_d\\<gamma> [unfolded o_def]])\n      have \"contour_integral (linepath a b) h = contour_integral (linepath a b) (\\<lambda>z. contour_integral \\<gamma> (d z))\"\n        using abu  by (force simp: h_def intro: contour_integral_eq)\n      also have \"\\<dots> =  contour_integral \\<gamma> (\\<lambda>w. contour_integral (linepath a b) (\\<lambda>z. d z w))\"\n      proof (rule contour_integral_swap)\n        show \"continuous_on (path_image (linepath a b) \\<times> path_image \\<gamma>) (\\<lambda>(y1, y2). d y1 y2)\"\n          using abu pasz by (auto intro: continuous_on_subset [OF cond_uu])\n        show \"continuous_on {0..1} (\\<lambda>t. vector_derivative (linepath a b) (at t))\"\n          by (auto intro!: continuous_intros)\n        show \"continuous_on {0..1} (\\<lambda>t. vector_derivative \\<gamma> (at t))\"\n          by (metis \\<gamma>' continuous_on_eq path_def path_polynomial_function pf\\<gamma>' vector_derivative_at)\n      qed (use \\<open>valid_path \\<gamma>\\<close> in auto)\n      finally have cint_h_eq:\n          \"contour_integral (linepath a b) h =\n                    contour_integral \\<gamma> (\\<lambda>w. contour_integral (linepath a b) (\\<lambda>z. d z w))\" .\n      note cint_cint cint_h_eq\n    } note cint_h = this\n    have conthu: \"continuous_on U h\"\n    proof (simp add: continuous_on_sequentially, clarify)\n      fix a x\n      assume x: \"x \\<in> U\" and au: \"\\<forall>n. a n \\<in> U\" and ax: \"a \\<longlonglongrightarrow> x\"\n      then have A1: \"\\<forall>\\<^sub>F n in sequentially. d (a n) contour_integrable_on \\<gamma>\"\n        by (meson U contour_integrable_on_def eventuallyI)\n      obtain dd where \"dd>0\" and dd: \"cball x dd \\<subseteq> U\" using open_contains_cball \\<open>open U\\<close> x by force\n      have A2: \"uniform_limit (path_image \\<gamma>) (\\<lambda>n. d (a n)) (d x) sequentially\"\n        unfolding uniform_limit_iff dist_norm\n      proof clarify\n        fix ee::real\n        assume \"0 < ee\"\n        show \"\\<forall>\\<^sub>F n in sequentially. \\<forall>\\<xi>\\<in>path_image \\<gamma>. cmod (d (a n) \\<xi> - d x \\<xi>) < ee\"\n        proof -\n          let ?ddpa = \"{(w,z) |w z. w \\<in> cball x dd \\<and> z \\<in> path_image \\<gamma>}\"\n          have \"uniformly_continuous_on ?ddpa (\\<lambda>(x,y). d x y)\"\n          proof (rule compact_uniformly_continuous [OF continuous_on_subset[OF cond_uu]])\n            show \"compact {(w, z) |w z. w \\<in> cball x dd \\<and> z \\<in> path_image \\<gamma>}\"\n              using \\<open>valid_path \\<gamma>\\<close>\n              by (auto simp: compact_Times compact_valid_path_image simp del: mem_cball)\n          qed (use dd pasz in auto)\n          then obtain kk where \"kk>0\"\n            and kk: \"\\<And>x x'. \\<lbrakk>x \\<in> ?ddpa; x' \\<in> ?ddpa; dist x' x < kk\\<rbrakk> \\<Longrightarrow>\n                             dist ((\\<lambda>(x,y). d x y) x') ((\\<lambda>(x,y). d x y) x) < ee\"\n            by (rule uniformly_continuous_onE [where e = ee]) (use \\<open>0 < ee\\<close> in auto)\n          have kk: \"\\<lbrakk>norm (w - x) \\<le> dd; z \\<in> path_image \\<gamma>; norm ((w, z) - (x, z)) < kk\\<rbrakk> \\<Longrightarrow> norm (d w z - d x z) < ee\"\n            for  w z\n            using \\<open>dd>0\\<close> kk [of \"(x,z)\" \"(w,z)\"] by (force simp: norm_minus_commute dist_norm)\n          obtain no where \"\\<forall>n\\<ge>no. dist (a n) x < min dd kk\"\n            using ax unfolding lim_sequentially\n            by (meson \\<open>0 < dd\\<close> \\<open>0 < kk\\<close> min_less_iff_conj)\n          then show ?thesis\n            using \\<open>dd > 0\\<close> \\<open>kk > 0\\<close> by (fastforce simp: eventually_sequentially kk dist_norm)\n        qed\n      qed\n      have \"(\\<lambda>n. contour_integral \\<gamma> (d (a n))) \\<longlonglongrightarrow> contour_integral \\<gamma> (d x)\"\n        by (rule contour_integral_uniform_limit [OF A1 A2 le_B]) (auto simp: \\<open>valid_path \\<gamma>\\<close>)\n      then have tendsto_hx: \"(\\<lambda>n. contour_integral \\<gamma> (d (a n))) \\<longlonglongrightarrow> h x\"\n        by (simp add: h_def x)\n      then show \"(h \\<circ> a) \\<longlonglongrightarrow> h x\"\n        by (simp add: h_def x au o_def)\n    qed\n    show ?thesis\n    proof (simp add: holomorphic_on_open field_differentiable_def [symmetric], clarify)\n      fix z0\n      consider \"z0 \\<in> v\" | \"z0 \\<in> U\" using uv_Un by blast\n      then show \"h field_differentiable at z0\"\n      proof cases\n        assume \"z0 \\<in> v\" then show ?thesis\n          using Cauchy_next_derivative [OF con_pa_f le_B f_has_cint _ ov] V f_has_cint \\<open>valid_path \\<gamma>\\<close>\n          by (auto simp: field_differentiable_def v_def)\n      next\n        assume \"z0 \\<in> U\" then\n        obtain e where \"e>0\" and e: \"ball z0 e \\<subseteq> U\" by (blast intro: openE [OF \\<open>open U\\<close>])\n        have *: \"contour_integral (linepath a b) h + contour_integral (linepath b c) h + contour_integral (linepath c a) h = 0\"\n                if abc_subset: \"convex hull {a, b, c} \\<subseteq> ball z0 e\"  for a b c\n        proof -\n          have *: \"\\<And>x1 x2 z. z \\<in> U \\<Longrightarrow> closed_segment x1 x2 \\<subseteq> U \\<Longrightarrow> (\\<lambda>w. d w z) contour_integrable_on linepath x1 x2\"\n            using  hol_dw holomorphic_on_imp_continuous_on \\<open>open U\\<close>\n            by (auto intro!: contour_integrable_holomorphic_simple)\n          have abc: \"closed_segment a b \\<subseteq> U\"  \"closed_segment b c \\<subseteq> U\"  \"closed_segment c a \\<subseteq> U\"\n            using that e segments_subset_convex_hull by fastforce+\n          have eq0: \"\\<And>w. w \\<in> U \\<Longrightarrow> contour_integral (linepath a b +++ linepath b c +++ linepath c a) (\\<lambda>z. d z w) = 0\"\n          proof (rule contour_integral_unique [OF Cauchy_theorem_triangle])\n            show \"\\<And>w. w \\<in> U \\<Longrightarrow> (\\<lambda>z. d z w) holomorphic_on convex hull {a, b, c}\"\n              using e abc_subset by (auto intro: holomorphic_on_subset [OF hol_dw])\n          qed\n          have \"contour_integral \\<gamma>\n                   (\\<lambda>x. contour_integral (linepath a b) (\\<lambda>z. d z x) +\n                        (contour_integral (linepath b c) (\\<lambda>z. d z x) +\n                         contour_integral (linepath c a) (\\<lambda>z. d z x)))  =  0\"\n            apply (rule contour_integral_eq_0)\n            using abc pasz U\n            apply (subst contour_integral_join [symmetric], auto intro: eq0 *)+\n            done\n          then show ?thesis\n            by (simp add: cint_h abc contour_integrable_add contour_integral_add [symmetric] add_ac)\n        qed\n        show ?thesis\n          using e \\<open>e > 0\\<close> \n          by (auto intro!: holomorphic_on_imp_differentiable_at [OF _ open_ball] analytic_imp_holomorphic\n                           Morera_triangle continuous_on_subset [OF conthu] *)\n      qed\n    qed\n  qed\n  ultimately have [simp]: \"h z = 0\" for z\n    by (meson Liouville_weak)\n  have \"((\\<lambda>w. 1 / (w - z)) has_contour_integral complex_of_real (2 * pi) * \\<i> * winding_number \\<gamma> z) \\<gamma>\"\n    by (rule has_contour_integral_winding_number [OF \\<open>valid_path \\<gamma>\\<close> znot])\n  then have \"((\\<lambda>w. f z * (1 / (w - z))) has_contour_integral complex_of_real (2 * pi) * \\<i> * winding_number \\<gamma> z * f z) \\<gamma>\"\n    by (metis mult.commute has_contour_integral_lmul)\n  then have 1: \"((\\<lambda>w. f z / (w - z)) has_contour_integral complex_of_real (2 * pi) * \\<i> * winding_number \\<gamma> z * f z) \\<gamma>\"\n    by (simp add: field_split_simps)\n  moreover have 2: \"((\\<lambda>w. (f w - f z) / (w - z)) has_contour_integral 0) \\<gamma>\"\n    using U [OF z] pasz d_def by (force elim: has_contour_integral_eq [where g = \"\\<lambda>w. (f w - f z)/(w - z)\"])\n  show ?thesis\n    using has_contour_integral_add [OF 1 2]  by (simp add: diff_divide_distrib)\nqed\n\ntheorem Cauchy_integral_formula_global:\n    assumes S: \"open S\" and holf: \"f holomorphic_on S\"\n        and z: \"z \\<in> S\" and vpg: \"valid_path \\<gamma>\"\n        and pasz: \"path_image \\<gamma> \\<subseteq> S - {z}\" and loop: \"pathfinish \\<gamma> = pathstart \\<gamma>\"\n        and zero: \"\\<And>w. w \\<notin> S \\<Longrightarrow> winding_number \\<gamma> w = 0\"\n      shows \"((\\<lambda>w. f w / (w - z)) has_contour_integral (2*pi * \\<i> * winding_number \\<gamma> z * f z)) \\<gamma>\"\nproof -\n  have \"path \\<gamma>\" using vpg by (blast intro: valid_path_imp_path)\n  have hols: \"(\\<lambda>w. f w / (w - z)) holomorphic_on S - {z}\" \"(\\<lambda>w. 1 / (w - z)) holomorphic_on S - {z}\"\n    by (rule holomorphic_intros holomorphic_on_subset [OF holf] | force)+\n  then have cint_fw: \"(\\<lambda>w. f w / (w - z)) contour_integrable_on \\<gamma>\"\n    by (meson contour_integrable_holomorphic_simple holomorphic_on_imp_continuous_on open_delete S vpg pasz)\n  obtain d where \"d>0\"\n      and d: \"\\<And>g h. \\<lbrakk>valid_path g; valid_path h; \\<forall>t\\<in>{0..1}. cmod (g t - \\<gamma> t) < d \\<and> cmod (h t - \\<gamma> t) < d;\n                     pathstart h = pathstart g \\<and> pathfinish h = pathfinish g\\<rbrakk>\n                     \\<Longrightarrow> path_image h \\<subseteq> S - {z} \\<and> (\\<forall>f. f holomorphic_on S - {z} \\<longrightarrow> contour_integral h f = contour_integral g f)\"\n    using contour_integral_nearby_ends [OF _ \\<open>path \\<gamma>\\<close> pasz] S by (simp add: open_Diff) metis\n  obtain p where polyp: \"polynomial_function p\"\n             and ps: \"pathstart p = pathstart \\<gamma>\" and pf: \"pathfinish p = pathfinish \\<gamma>\" and led: \"\\<forall>t\\<in>{0..1}. cmod (p t - \\<gamma> t) < d\"\n    using path_approx_polynomial_function [OF \\<open>path \\<gamma>\\<close> \\<open>d > 0\\<close>] by metis\n  then have ploop: \"pathfinish p = pathstart p\" using loop by auto\n  have vpp: \"valid_path p\"  using polyp valid_path_polynomial_function by blast\n  have [simp]: \"z \\<notin> path_image \\<gamma>\" using pasz by blast\n  have paps: \"path_image p \\<subseteq> S - {z}\" and cint_eq: \"(\\<And>f. f holomorphic_on S - {z} \\<Longrightarrow> contour_integral p f = contour_integral \\<gamma> f)\"\n    using pf ps led d [OF vpg vpp] \\<open>d > 0\\<close> by auto\n  have wn_eq: \"winding_number p z = winding_number \\<gamma> z\"\n    using vpp paps\n    by (simp add: subset_Diff_insert vpg valid_path_polynomial_function winding_number_valid_path cint_eq hols)\n  have \"winding_number p w = winding_number \\<gamma> w\" if \"w \\<notin> S\" for w\n  proof -\n    have hol: \"(\\<lambda>v. 1 / (v - w)) holomorphic_on S - {z}\"\n      using that by (force intro: holomorphic_intros holomorphic_on_subset [OF holf])\n   have \"w \\<notin> path_image p\" \"w \\<notin> path_image \\<gamma>\" using paps pasz that by auto\n   then show ?thesis\n    using vpp vpg by (simp add: subset_Diff_insert valid_path_polynomial_function winding_number_valid_path cint_eq [OF hol])\n  qed\n  then have wn0: \"\\<And>w. w \\<notin> S \\<Longrightarrow> winding_number p w = 0\"\n    by (simp add: zero)\n  show ?thesis\n    using Cauchy_integral_formula_global_weak [OF S holf z polyp paps ploop wn0] hols\n    by (metis wn_eq cint_eq has_contour_integral_eqpath cint_fw cint_eq)\nqed\n\ntheorem Cauchy_theorem_global:\n    assumes S: \"open S\" and holf: \"f holomorphic_on S\"\n        and vpg: \"valid_path \\<gamma>\" and loop: \"pathfinish \\<gamma> = pathstart \\<gamma>\"\n        and pas: \"path_image \\<gamma> \\<subseteq> S\"\n        and zero: \"\\<And>w. w \\<notin> S \\<Longrightarrow> winding_number \\<gamma> w = 0\"\n      shows \"(f has_contour_integral 0) \\<gamma>\"\nproof -\n  obtain z where \"z \\<in> S\" and znot: \"z \\<notin> path_image \\<gamma>\"\n  proof -\n    have \"path_image \\<gamma> \\<noteq> S\"\n      by (metis compact_valid_path_image vpg compact_open path_image_nonempty S)\n    with pas show ?thesis by (blast intro: that)\n  qed\n  then have pasz: \"path_image \\<gamma> \\<subseteq> S - {z}\" using pas by blast\n  have hol: \"(\\<lambda>w. (w - z) * f w) holomorphic_on S\"\n    by (rule holomorphic_intros holf)+\n  show ?thesis\n    using Cauchy_integral_formula_global [OF S hol \\<open>z \\<in> S\\<close> vpg pasz loop zero]\n    by (auto simp: znot elim!: has_contour_integral_eq)\nqed\n\ncorollary Cauchy_theorem_global_outside:\n    assumes \"open S\" \"f holomorphic_on S\" \"valid_path \\<gamma>\"  \"pathfinish \\<gamma> = pathstart \\<gamma>\" \"path_image \\<gamma> \\<subseteq> S\"\n            \"\\<And>w. w \\<notin> S \\<Longrightarrow> w \\<in> outside(path_image \\<gamma>)\"\n      shows \"(f has_contour_integral 0) \\<gamma>\"\nby (metis Cauchy_theorem_global assms winding_number_zero_in_outside valid_path_imp_path)\n\nlemma simply_connected_imp_winding_number_zero:\n  assumes \"simply_connected S\" \"path g\"\n           \"path_image g \\<subseteq> S\" \"pathfinish g = pathstart g\" \"z \\<notin> S\"\n    shows \"winding_number g z = 0\"\nproof -\n  have hom: \"homotopic_loops S g (linepath (pathstart g) (pathstart g))\"\n    by (meson assms homotopic_paths_imp_homotopic_loops pathfinish_linepath simply_connected_eq_contractible_path)\n  then have \"homotopic_paths (- {z}) g (linepath (pathstart g) (pathstart g))\"\n    by (meson \\<open>z \\<notin> S\\<close> homotopic_loops_imp_homotopic_paths_null homotopic_paths_subset subset_Compl_singleton)\n  then have \"winding_number g z = winding_number(linepath (pathstart g) (pathstart g)) z\"\n    by (rule winding_number_homotopic_paths)\n  also have \"\\<dots> = 0\"\n    using assms by (force intro: winding_number_trivial)\n  finally show ?thesis .\nqed\n\nlemma Cauchy_theorem_simply_connected:\n  assumes \"open S\" \"simply_connected S\" \"f holomorphic_on S\" \"valid_path g\"\n           \"path_image g \\<subseteq> S\" \"pathfinish g = pathstart g\"\n    shows \"(f has_contour_integral 0) g\"\n  by (meson assms Cauchy_theorem_global simply_connected_imp_winding_number_zero valid_path_imp_path)\n\nproposition\\<^marker>\\<open>tag unimportant\\<close> holomorphic_logarithm_exists:\n  assumes A: \"convex A\" \"open A\"\n      and f: \"f holomorphic_on A\" \"\\<And>x. x \\<in> A \\<Longrightarrow> f x \\<noteq> 0\"\n      and z0: \"z0 \\<in> A\"\n    obtains g where \"g holomorphic_on A\" and \"\\<And>x. x \\<in> A \\<Longrightarrow> exp (g x) = f x\"\nproof -\n  note f' = holomorphic_derivI [OF f(1) A(2)]\n  obtain g where g: \"\\<And>x. x \\<in> A \\<Longrightarrow> (g has_field_derivative deriv f x / f x) (at x)\"\n  proof (rule holomorphic_convex_primitive' [OF A])\n    show \"(\\<lambda>x. deriv f x / f x) holomorphic_on A\"\n      by (intro holomorphic_intros f A)\n  qed (auto simp: A at_within_open[of _ A])\n  define h where \"h = (\\<lambda>x. -g z0 + ln (f z0) + g x)\"\n  from g and A have g_holo: \"g holomorphic_on A\"\n    by (auto simp: holomorphic_on_def at_within_open[of _ A] field_differentiable_def)\n  hence h_holo: \"h holomorphic_on A\"\n    by (auto simp: h_def intro!: holomorphic_intros)\n    note [simp] = at_within_open[OF _ \\<open>open A\\<close>]\n    have \"\\<exists>c. \\<forall>x\\<in>A. f x / exp (h x) - 1 = c\"\n      using \\<open>convex A\\<close> z0 f \n      by (force simp: h_def exp_diff field_simps intro!: has_field_derivative_zero_constant derivative_eq_intros g f')\n  then obtain c where c: \"\\<And>x. x \\<in> A \\<Longrightarrow> f x / exp (h x) - 1 = c\"\n    by blast\n  from c[OF z0] and z0 and f have \"c = 0\"\n    by (simp add: h_def)\n  with c have \"\\<And>x. x \\<in> A \\<Longrightarrow> exp (h x) = f x\" by simp\n  from that[OF h_holo this] show ?thesis .\nqed\n\n\n(* FIXME mv to Cauchy_Integral_Theorem.thy *)\nsubsection\\<open>Cauchy's inequality and more versions of Liouville\\<close>\n\nlemma Cauchy_higher_deriv_bound:\n    assumes holf: \"f holomorphic_on (ball z r)\"\n        and contf: \"continuous_on (cball z r) f\"\n        and fin : \"\\<And>w. w \\<in> ball z r \\<Longrightarrow> f w \\<in> ball y B0\"\n        and \"0 < r\" and \"0 < n\"\n      shows \"norm ((deriv ^^ n) f z) \\<le> (fact n) * B0 / r^n\"\nproof -\n  have \"0 < B0\" using \\<open>0 < r\\<close> fin [of z]\n    by (metis ball_eq_empty ex_in_conv fin not_less)\n  have le_B0: \"cmod (f w - y) \\<le> B0\" if \"cmod (w - z) \\<le> r\" for w\n  proof (rule continuous_on_closure_norm_le [of \"ball z r\" \"\\<lambda>w. f w - y\"], use \\<open>0 < r\\<close> in simp_all)\n    show \"continuous_on (cball z r) (\\<lambda>w. f w - y)\"\n      by (intro continuous_intros contf)\n    show \"dist z w \\<le> r\"\n      by (simp add: dist_commute dist_norm that)\n    qed (use fin in \\<open>auto simp: dist_norm less_eq_real_def norm_minus_commute\\<close>)\n  have \"(deriv ^^ n) f z = (deriv ^^ n) (\\<lambda>w. f w) z - (deriv ^^ n) (\\<lambda>w. y) z\"\n    using \\<open>0 < n\\<close> by simp\n  also have \"... = (deriv ^^ n) (\\<lambda>w. f w - y) z\"\n    by (rule higher_deriv_diff [OF holf, symmetric]) (auto simp: \\<open>0 < r\\<close>)\n  finally have \"(deriv ^^ n) f z = (deriv ^^ n) (\\<lambda>w. f w - y) z\" .\n  have contf': \"continuous_on (cball z r) (\\<lambda>u. f u - y)\"\n    by (rule contf continuous_intros)+\n  have holf': \"(\\<lambda>u. (f u - y)) holomorphic_on (ball z r)\"\n    by (simp add: holf holomorphic_on_diff)\n  define a where \"a = (2 * pi)/(fact n)\"\n  have \"0 < a\"  by (simp add: a_def)\n  have \"B0/r^(Suc n)*2 * pi * r = a*((fact n)*B0/r^n)\"\n    using \\<open>0 < r\\<close> by (simp add: a_def field_split_simps)\n  have der_dif: \"(deriv ^^ n) (\\<lambda>w. f w - y) z = (deriv ^^ n) f z\"\n    using \\<open>0 < r\\<close> \\<open>0 < n\\<close>\n    by (auto simp: higher_deriv_diff [OF holf holomorphic_on_const])\n  have \"norm ((2 * of_real pi * \\<i>)/(fact n) * (deriv ^^ n) (\\<lambda>w. f w - y) z)\n        \\<le> (B0/r^(Suc n)) * (2 * pi * r)\"\n    apply (rule has_contour_integral_bound_circlepath [of \"(\\<lambda>u. (f u - y)/(u - z)^(Suc n))\" _ z])\n    using Cauchy_has_contour_integral_higher_derivative_circlepath [OF contf' holf']\n    using \\<open>0 < B0\\<close> \\<open>0 < r\\<close>\n    apply (auto simp: norm_divide norm_mult norm_power divide_simps le_B0)\n    done\n  then show ?thesis\n    using \\<open>0 < r\\<close>\n    by (auto simp: norm_divide norm_mult norm_power field_simps der_dif le_B0)\nqed\n\nlemma Cauchy_inequality:\n    assumes holf: \"f holomorphic_on (ball \\<xi> r)\"\n        and contf: \"continuous_on (cball \\<xi> r) f\"\n        and \"0 < r\"\n        and nof: \"\\<And>x. norm(\\<xi>-x) = r \\<Longrightarrow> norm(f x) \\<le> B\"\n      shows \"norm ((deriv ^^ n) f \\<xi>) \\<le> (fact n) * B / r^n\"\nproof -\n  obtain x where \"norm (\\<xi>-x) = r\"\n    by (metis \\<open>0 < r\\<close> dist_norm order_less_imp_le vector_choose_dist)\n  then have \"0 \\<le> B\"\n    by (metis nof norm_not_less_zero not_le order_trans)\n  have \"\\<xi> \\<in> ball \\<xi> r\"\n    using \\<open>0 < r\\<close> by simp\n  then have  \"((\\<lambda>u. f u / (u-\\<xi>) ^ Suc n) has_contour_integral (2 * pi) * \\<i> / fact n * (deriv ^^ n) f \\<xi>)\n         (circlepath \\<xi> r)\"\n    by (rule Cauchy_has_contour_integral_higher_derivative_circlepath [OF contf holf])\n  have \"norm ((2 * pi * \\<i>)/(fact n) * (deriv ^^ n) f \\<xi>) \\<le> (B / r^(Suc n)) * (2 * pi * r)\"\n  proof (rule has_contour_integral_bound_circlepath)\n    have \"\\<xi> \\<in> ball \\<xi> r\"\n      using \\<open>0 < r\\<close> by simp\n    then show  \"((\\<lambda>u. f u / (u-\\<xi>) ^ Suc n) has_contour_integral (2 * pi) * \\<i> / fact n * (deriv ^^ n) f \\<xi>)\n         (circlepath \\<xi> r)\"\n      by (rule Cauchy_has_contour_integral_higher_derivative_circlepath [OF contf holf])\n    show \"\\<And>x. cmod (x-\\<xi>) = r \\<Longrightarrow> cmod (f x / (x-\\<xi>) ^ Suc n) \\<le> B / r ^ Suc n\"\n      using \\<open>0 \\<le> B\\<close> \\<open>0 < r\\<close>\n      by (simp add: norm_divide norm_power nof frac_le norm_minus_commute del: power_Suc)\n  qed (use \\<open>0 \\<le> B\\<close> \\<open>0 < r\\<close> in auto)\n  then show ?thesis using \\<open>0 < r\\<close>\n    by (simp add: norm_divide norm_mult field_simps)\nqed\n\nlemma Liouville_polynomial:\n    assumes holf: \"f holomorphic_on UNIV\"\n        and nof: \"\\<And>z. A \\<le> norm z \\<Longrightarrow> norm(f z) \\<le> B * norm z ^ n\"\n      shows \"f \\<xi> = (\\<Sum>k\\<le>n. (deriv^^k) f 0 / fact k * \\<xi> ^ k)\"\nproof (cases rule: le_less_linear [THEN disjE])\n  assume \"B \\<le> 0\"\n  then have \"\\<And>z. A \\<le> norm z \\<Longrightarrow> norm(f z) = 0\"\n    by (metis nof less_le_trans zero_less_mult_iff neqE norm_not_less_zero norm_power not_le)\n  then have f0: \"(f \\<longlongrightarrow> 0) at_infinity\"\n    using Lim_at_infinity by force\n  then have [simp]: \"f = (\\<lambda>w. 0)\"\n    using Liouville_weak [OF holf, of 0]\n    by (simp add: eventually_at_infinity f0) meson\n  show ?thesis by simp\nnext\n  assume \"0 < B\"\n  have \"((\\<lambda>k. (deriv ^^ k) f 0 / (fact k) * (\\<xi> - 0)^k) sums f \\<xi>)\"\n  proof (rule holomorphic_power_series [where r = \"norm \\<xi> + 1\"])\n    show \"f holomorphic_on ball 0 (cmod \\<xi> + 1)\" \"\\<xi> \\<in> ball 0 (cmod \\<xi> + 1)\"\n      using holf holomorphic_on_subset by auto\n  qed\n  then have sumsf: \"((\\<lambda>k. (deriv ^^ k) f 0 / (fact k) * \\<xi>^k) sums f \\<xi>)\" by simp\n  have \"(deriv ^^ k) f 0 / fact k * \\<xi> ^ k = 0\" if \"k>n\" for k\n  proof (cases \"(deriv ^^ k) f 0 = 0\")\n    case True then show ?thesis by simp\n  next\n    case False\n    define w where \"w = complex_of_real (fact k * B / cmod ((deriv ^^ k) f 0) + (\\<bar>A\\<bar> + 1))\"\n    have \"1 \\<le> abs (fact k * B / cmod ((deriv ^^ k) f 0) + (\\<bar>A\\<bar> + 1))\"\n      using \\<open>0 < B\\<close> by simp\n    then have wge1: \"1 \\<le> norm w\"\n      by (metis norm_of_real w_def)\n    then have \"w \\<noteq> 0\" by auto\n    have kB: \"0 < fact k * B\"\n      using \\<open>0 < B\\<close> by simp\n    then have \"0 \\<le> fact k * B / cmod ((deriv ^^ k) f 0)\"\n      by simp\n    then have wgeA: \"A \\<le> cmod w\"\n      by (simp only: w_def norm_of_real)\n    have \"fact k * B / cmod ((deriv ^^ k) f 0) < abs (fact k * B / cmod ((deriv ^^ k) f 0) + (\\<bar>A\\<bar> + 1))\"\n      using \\<open>0 < B\\<close> by simp\n    then have wge: \"fact k * B / cmod ((deriv ^^ k) f 0) < norm w\"\n      by (metis norm_of_real w_def)\n    then have \"fact k * B / norm w < cmod ((deriv ^^ k) f 0)\"\n      using False by (simp add: field_split_simps mult.commute split: if_split_asm)\n    also have \"... \\<le> fact k * (B * norm w ^ n) / norm w ^ k\"\n    proof (rule Cauchy_inequality)\n      show \"f holomorphic_on ball 0 (cmod w)\"\n        using holf holomorphic_on_subset by force\n      show \"continuous_on (cball 0 (cmod w)) f\"\n        using holf holomorphic_on_imp_continuous_on holomorphic_on_subset by blast\n      show \"\\<And>x. cmod (0 - x) = cmod w \\<Longrightarrow> cmod (f x) \\<le> B * cmod w ^ n\"\n        by (metis nof wgeA dist_0_norm dist_norm)\n    qed (use \\<open>w \\<noteq> 0\\<close> in auto)\n    also have \"... = fact k * B / cmod w ^ (k-n)\"\n      using \\<open>k>n\\<close> by (simp add: divide_simps flip: power_add)\n    finally have \"fact k * B / cmod w < fact k * B / cmod w ^ (k - n)\" .\n    then have \"1 / cmod w < 1 / cmod w ^ (k - n)\"\n      by (metis kB divide_inverse inverse_eq_divide mult_less_cancel_left_pos)\n    then have \"cmod w ^ (k - n) < cmod w\"\n      by (smt (verit, best) \\<open>w \\<noteq> 0\\<close> frac_le zero_less_norm_iff)\n    with self_le_power [OF wge1] show ?thesis\n      by (meson diff_is_0_eq not_gr0 not_le that)\n  qed\n  then have \"(deriv ^^ (k + Suc n)) f 0 / fact (k + Suc n) * \\<xi> ^ (k + Suc n) = 0\" for k\n    using not_less_eq by blast\n  then have \"(\\<lambda>i. (deriv ^^ (i + Suc n)) f 0 / fact (i + Suc n) * \\<xi> ^ (i + Suc n)) sums 0\"\n    by (rule sums_0)\n  with sums_split_initial_segment [OF sumsf, where n = \"Suc n\"]\n  show ?thesis\n    using atLeast0AtMost lessThan_Suc_atMost sums_unique2 by fastforce\nqed\n\ntext\\<open>Every bounded entire function is a constant function.\\<close>\ntheorem Liouville_theorem:\n  assumes holf: \"f holomorphic_on UNIV\"\n    and bf: \"bounded (range f)\"\n  shows \"f constant_on UNIV\"\n  using Liouville_polynomial [OF holf, of 0 _ 0, simplified]\n  by (metis bf bounded_iff constant_on_def rangeI)\n\ntext\\<open>A holomorphic function f has only isolated zeros unless f is 0.\\<close>\n\nlemma powser_0_nonzero:\n  fixes a :: \"nat \\<Rightarrow> 'a::{real_normed_field,banach}\"\n  assumes r: \"0 < r\"\n      and sm: \"\\<And>x. norm (x-\\<xi>) < r \\<Longrightarrow> (\\<lambda>n. a n * (x-\\<xi>) ^ n) sums (f x)\"\n      and [simp]: \"f \\<xi> = 0\"\n      and m0: \"a m \\<noteq> 0\" and \"m>0\"\n  obtains s where \"0 < s\" and \"\\<And>z. z \\<in> cball \\<xi> s - {\\<xi>} \\<Longrightarrow> f z \\<noteq> 0\"\nproof -\n  have \"r \\<le> conv_radius a\"\n    using sm sums_summable by (auto simp: le_conv_radius_iff [where \\<xi>=\\<xi>])\n  obtain m where am: \"a m \\<noteq> 0\" and az [simp]: \"(\\<And>n. n<m \\<Longrightarrow> a n = 0)\"\n  proof\n    show \"a (LEAST n. a n \\<noteq> 0) \\<noteq> 0\"\n      by (metis (mono_tags, lifting) m0 LeastI)\n  qed (fastforce dest!: not_less_Least)\n  define b where \"b i = a (i+m) / a m\" for i\n  define g where \"g x = suminf (\\<lambda>i. b i * (x-\\<xi>) ^ i)\" for x\n  have [simp]: \"b 0 = 1\"\n    by (simp add: am b_def)\n  { fix x::'a\n    assume \"norm (x-\\<xi>) < r\"\n    then have \"(\\<lambda>n. (a m * (x-\\<xi>)^m) * (b n * (x-\\<xi>)^n)) sums (f x)\"\n      using am az sm sums_zero_iff_shift [of m \"(\\<lambda>n. a n * (x-\\<xi>) ^ n)\" \"f x\"]\n      by (simp add: b_def monoid_mult_class.power_add algebra_simps)\n    then have \"x \\<noteq> \\<xi> \\<Longrightarrow> (\\<lambda>n. b n * (x-\\<xi>)^n) sums (f x / (a m * (x-\\<xi>)^m))\"\n      using am by (simp add: sums_mult_D)\n  } note bsums = this\n  then have  \"norm (x-\\<xi>) < r \\<Longrightarrow> summable (\\<lambda>n. b n * (x-\\<xi>)^n)\" for x\n    using sums_summable by (cases \"x=\\<xi>\") auto\n  then have \"r \\<le> conv_radius b\"\n    by (simp add: le_conv_radius_iff [where \\<xi>=\\<xi>])\n  then have \"r/2 < conv_radius b\"\n    using not_le order_trans r by fastforce\n  then have \"continuous_on (cball \\<xi> (r/2)) g\"\n    using powser_continuous_suminf [of \"r/2\" b \\<xi>] by (simp add: g_def)\n  then obtain s where \"s>0\"  \"\\<And>x. \\<lbrakk>norm (x-\\<xi>) \\<le> s; norm (x-\\<xi>) \\<le> r/2\\<rbrakk> \\<Longrightarrow> dist (g x) (g \\<xi>) < 1/2\"\n  proof (rule continuous_onE)\n    show \"\\<xi> \\<in> cball \\<xi> (r / 2)\" \"1/2 > (0::real)\"\n      using r by auto\n  qed (auto simp: dist_commute dist_norm)\n  moreover have \"g \\<xi> = 1\"\n    by (simp add: g_def)\n  ultimately have gnz: \"\\<And>x. \\<lbrakk>norm (x-\\<xi>) \\<le> s; norm (x-\\<xi>) \\<le> r/2\\<rbrakk> \\<Longrightarrow> (g x) \\<noteq> 0\"\n    by fastforce\n  have \"f x \\<noteq> 0\" if \"x \\<noteq> \\<xi>\" \"norm (x-\\<xi>) \\<le> s\" \"norm (x-\\<xi>) \\<le> r/2\" for x\n    using bsums [of x] that gnz [of x] r sums_iff unfolding g_def by fastforce\n  then show ?thesis\n    apply (rule_tac s=\"min s (r/2)\" in that)\n    using \\<open>0 < r\\<close> \\<open>0 < s\\<close> by (auto simp: dist_commute dist_norm)\nqed\n\nsubsection \\<open>Complex functions and power series\\<close>\n\ntext \\<open>\n  The following defines the power series expansion of a complex function at a given point\n  (assuming that it is analytic at that point).\n\\<close>\ndefinition\\<^marker>\\<open>tag important\\<close> fps_expansion :: \"(complex \\<Rightarrow> complex) \\<Rightarrow> complex \\<Rightarrow> complex fps\" where\n  \"fps_expansion f z0 = Abs_fps (\\<lambda>n. (deriv ^^ n) f z0 / fact n)\"\n\nlemma fps_expansion_cong:\n  assumes \"\\<forall>\\<^sub>F w in nhds x. f w =g w\"\n  shows \"fps_expansion f x = fps_expansion g x\"\n  unfolding fps_expansion_def using assms higher_deriv_cong_ev by fastforce \n\nlemma\n  fixes r :: ereal\n  assumes \"f holomorphic_on eball z0 r\"\n  shows   conv_radius_fps_expansion: \"fps_conv_radius (fps_expansion f z0) \\<ge> r\"\n    and   eval_fps_expansion: \"\\<And>z. z \\<in> eball z0 r \\<Longrightarrow> eval_fps (fps_expansion f z0) (z - z0) = f z\"\n    and   eval_fps_expansion': \"\\<And>z. norm z < r \\<Longrightarrow> eval_fps (fps_expansion f z0) z = f (z0 + z)\"\nproof -\n  have \"(\\<lambda>n. fps_nth (fps_expansion f z0) n * (z - z0) ^ n) sums f z\"\n    if \"z \\<in> ball z0 r'\" \"ereal r' < r\" for z r'\n  proof -\n    have \"f holomorphic_on ball z0 r'\"\n      using holomorphic_on_subset[OF _ ball_eball_mono] assms that by force\n    then show ?thesis\n      using fps_expansion_def holomorphic_power_series that by auto\n  qed\n  hence *: \"(\\<lambda>n. fps_nth (fps_expansion f z0) n * (z - z0) ^ n) sums f z\"\n    if \"z \\<in> eball z0 r\" for z\n    using that by (subst (asm) eball_conv_UNION_balls) blast\n  show \"fps_conv_radius (fps_expansion f z0) \\<ge> r\" unfolding fps_conv_radius_def\n  proof (rule conv_radius_geI_ex)\n    fix r' :: real assume r': \"r' > 0\" \"ereal r' < r\"\n    thus \"\\<exists>z. norm z = r' \\<and> summable (\\<lambda>n. fps_nth (fps_expansion f z0) n * z ^ n)\"\n      using *[of \"z0 + of_real r'\"]\n      by (intro exI[of _ \"of_real r'\"]) (auto simp: summable_def dist_norm)\n  qed\n  show \"eval_fps (fps_expansion f z0) (z - z0) = f z\" if \"z \\<in> eball z0 r\" for z\n    using *[OF that] by (simp add: eval_fps_def sums_iff)\n  show \"eval_fps (fps_expansion f z0) z = f (z0 + z)\" if \"ereal (norm z) < r\" for z\n    using *[of \"z0 + z\"] and that by (simp add: eval_fps_def sums_iff dist_norm)\nqed\n\n\ntext \\<open>\n  We can now show several more facts about power series expansions (at least in the complex case)\n  with relative ease that would have been trickier without complex analysis.\n\\<close>\nlemma\n  fixes f :: \"complex fps\" and r :: ereal\n  assumes \"\\<And>z. ereal (norm z) < r \\<Longrightarrow> eval_fps f z \\<noteq> 0\"\n  shows   fps_conv_radius_inverse: \"fps_conv_radius (inverse f) \\<ge> min r (fps_conv_radius f)\"\n    and   eval_fps_inverse: \"\\<And>z. ereal (norm z) < fps_conv_radius f \\<Longrightarrow> ereal (norm z) < r \\<Longrightarrow> \n                               eval_fps (inverse f) z = inverse (eval_fps f z)\"\nproof -\n  define R where \"R = min (fps_conv_radius f) r\"\n  have *: \"fps_conv_radius (inverse f) \\<ge> min r (fps_conv_radius f) \\<and> \n          (\\<forall>z\\<in>eball 0 (min (fps_conv_radius f) r). eval_fps (inverse f) z = inverse (eval_fps f z))\"\n  proof (cases \"min r (fps_conv_radius f) > 0\")\n    case True\n    define f' where \"f' = fps_expansion (\\<lambda>z. inverse (eval_fps f z)) 0\"\n    have holo: \"(\\<lambda>z. inverse (eval_fps f z)) holomorphic_on eball 0 (min r (fps_conv_radius f))\"\n      using assms by (intro holomorphic_intros) auto\n    from holo have radius: \"fps_conv_radius f' \\<ge> min r (fps_conv_radius f)\"\n      unfolding f'_def by (rule conv_radius_fps_expansion)\n    have eval_f': \"eval_fps f' z = inverse (eval_fps f z)\" \n      if \"norm z < fps_conv_radius f\" \"norm z < r\" for z\n      using that unfolding f'_def by (subst eval_fps_expansion'[OF holo]) auto\n  \n    have \"f * f' = 1\"\n    proof (rule eval_fps_eqD)\n      from radius and True have \"0 < min (fps_conv_radius f) (fps_conv_radius f')\"\n        by (auto simp: min_def split: if_splits)\n      also have \"\\<dots> \\<le> fps_conv_radius (f * f')\" by (rule fps_conv_radius_mult)\n      finally show \"\\<dots> > 0\" .\n    next\n      from True have \"R > 0\" by (auto simp: R_def)\n      hence \"eventually (\\<lambda>z. z \\<in> eball 0 R) (nhds 0)\"\n        by (intro eventually_nhds_in_open) (auto simp: zero_ereal_def)\n      thus \"eventually (\\<lambda>z. eval_fps (f * f') z = eval_fps 1 z) (nhds 0)\"\n      proof eventually_elim\n        case (elim z)\n        hence \"eval_fps (f * f') z = eval_fps f z * eval_fps f' z\"\n          using radius by (intro eval_fps_mult) \n                          (auto simp: R_def min_def split: if_splits intro: less_trans)\n        also have \"eval_fps f' z = inverse (eval_fps f z)\"\n          using elim by (intro eval_f') (auto simp: R_def)\n        also from elim have \"eval_fps f z \\<noteq> 0\"\n          by (intro assms) (auto simp: R_def)\n        hence \"eval_fps f z * inverse (eval_fps f z) = eval_fps 1 z\" \n          by simp\n        finally show \"eval_fps (f * f') z = eval_fps 1 z\" .\n      qed\n    qed simp_all\n    hence \"f' = inverse f\"\n      by (intro fps_inverse_unique [symmetric]) (simp_all add: mult_ac)\n    with eval_f' and radius show ?thesis by simp\n  next\n    case False\n    hence *: \"eball 0 R = {}\" \n      by (intro eball_empty) (auto simp: R_def min_def split: if_splits)\n    show ?thesis\n    proof safe\n      from False have \"min r (fps_conv_radius f) \\<le> 0\"\n        by (simp add: min_def)\n      also have \"0 \\<le> fps_conv_radius (inverse f)\"\n        by (simp add: fps_conv_radius_def conv_radius_nonneg)\n      finally show \"min r (fps_conv_radius f) \\<le> \\<dots>\" .\n    qed (unfold * [unfolded R_def], auto)\n  qed\n\n  from * show \"fps_conv_radius (inverse f) \\<ge> min r (fps_conv_radius f)\" by blast\n  from * show \"eval_fps (inverse f) z = inverse (eval_fps f z)\" \n    if \"ereal (norm z) < fps_conv_radius f\" \"ereal (norm z) < r\" for z\n    using that by auto\nqed\n\nlemma\n  fixes f g :: \"complex fps\" and r :: ereal\n  defines \"R \\<equiv> Min {r, fps_conv_radius f, fps_conv_radius g}\"\n  assumes \"fps_conv_radius f > 0\" \"fps_conv_radius g > 0\" \"r > 0\"\n  assumes nz: \"\\<And>z. z \\<in> eball 0 r \\<Longrightarrow> eval_fps g z \\<noteq> 0\"\n  shows   fps_conv_radius_divide': \"fps_conv_radius (f / g) \\<ge> R\"\n    and   eval_fps_divide':\n            \"ereal (norm z) < R \\<Longrightarrow> eval_fps (f / g) z = eval_fps f z / eval_fps g z\"\nproof -\n  from nz[of 0] and \\<open>r > 0\\<close> have nz': \"fps_nth g 0 \\<noteq> 0\" \n    by (auto simp: eval_fps_at_0 zero_ereal_def)\n  have \"R \\<le> min r (fps_conv_radius g)\"\n    by (auto simp: R_def intro: min.coboundedI2)\n  also have \"min r (fps_conv_radius g) \\<le> fps_conv_radius (inverse g)\"\n    by (intro fps_conv_radius_inverse assms) (auto simp: zero_ereal_def)\n  finally have radius: \"fps_conv_radius (inverse g) \\<ge> R\" .\n  have \"R \\<le> min (fps_conv_radius f) (fps_conv_radius (inverse g))\"\n    by (intro radius min.boundedI) (auto simp: R_def intro: min.coboundedI1 min.coboundedI2)\n  also have \"\\<dots> \\<le> fps_conv_radius (f * inverse g)\"\n    by (rule fps_conv_radius_mult)\n  also have \"f * inverse g = f / g\"\n    by (intro fps_divide_unit [symmetric] nz')\n  finally show \"fps_conv_radius (f / g) \\<ge> R\" .\n\n  assume z: \"ereal (norm z) < R\"\n  have \"eval_fps (f * inverse g) z = eval_fps f z * eval_fps (inverse g) z\"\n    using radius by (intro eval_fps_mult less_le_trans[OF z])\n                    (auto simp: R_def intro: min.coboundedI1 min.coboundedI2)\n  also have \"eval_fps (inverse g) z = inverse (eval_fps g z)\" using \\<open>r > 0\\<close>\n    by (intro eval_fps_inverse[where r = r] less_le_trans[OF z] nz)\n       (auto simp: R_def intro: min.coboundedI1 min.coboundedI2)\n  also have \"f * inverse g = f / g\" by fact\n  finally show \"eval_fps (f / g) z = eval_fps f z / eval_fps g z\" \n    by (simp add: field_split_simps)\nqed\n\nlemma\n  fixes f g :: \"complex fps\" and r :: ereal\n  defines \"R \\<equiv> Min {r, fps_conv_radius f, fps_conv_radius g}\"\n  assumes \"subdegree g \\<le> subdegree f\"\n  assumes \"fps_conv_radius f > 0\" \"fps_conv_radius g > 0\" \"r > 0\"\n  assumes \"\\<And>z. z \\<in> eball 0 r \\<Longrightarrow> z \\<noteq> 0 \\<Longrightarrow> eval_fps g z \\<noteq> 0\"\n  shows   fps_conv_radius_divide: \"fps_conv_radius (f / g) \\<ge> R\"\n    and   eval_fps_divide:\n            \"ereal (norm z) < R \\<Longrightarrow> c = fps_nth f (subdegree g) / fps_nth g (subdegree g) \\<Longrightarrow>\n               eval_fps (f / g) z = (if z = 0 then c else eval_fps f z / eval_fps g z)\"\nproof -\n  define f' g' where \"f' = fps_shift (subdegree g) f\" and \"g' = fps_shift (subdegree g) g\"\n  have f_eq: \"f = f' * fps_X ^ subdegree g\" and g_eq: \"g = g' * fps_X ^ subdegree g\"\n    unfolding f'_def g'_def by (rule subdegree_decompose' le_refl | fact)+\n  have subdegree: \"subdegree f' = subdegree f - subdegree g\" \"subdegree g' = 0\"\n    using assms(2) by (simp_all add: f'_def g'_def)\n  have [simp]: \"fps_conv_radius f' = fps_conv_radius f\" \"fps_conv_radius g' = fps_conv_radius g\"\n    by (simp_all add: f'_def g'_def)\n  have [simp]: \"fps_nth f' 0 = fps_nth f (subdegree g)\"\n               \"fps_nth g' 0 = fps_nth g (subdegree g)\" by (simp_all add: f'_def g'_def)\n  have g_nz: \"g \\<noteq> 0\"\n  proof -\n    define z :: complex where \"z = (if r = \\<infinity> then 1 else of_real (real_of_ereal r / 2))\"\n    from \\<open>r > 0\\<close> have \"z \\<in> eball 0 r\"\n      by (cases r) (auto simp: z_def eball_def)\n    moreover have \"z \\<noteq> 0\" using \\<open>r > 0\\<close> \n      by (cases r) (auto simp: z_def)\n    ultimately have \"eval_fps g z \\<noteq> 0\" by (rule assms(6))\n    thus \"g \\<noteq> 0\" by auto\n  qed\n  have fg: \"f / g = f' * inverse g'\"\n    by (subst f_eq, subst (2) g_eq) (insert g_nz, simp add: fps_divide_unit)\n\n  have g'_nz: \"eval_fps g' z \\<noteq> 0\" if z: \"norm z < min r (fps_conv_radius g)\" for z\n  proof (cases \"z = 0\")\n    case False\n    with assms and z have \"eval_fps g z \\<noteq> 0\" by auto\n    also from z have \"eval_fps g z = eval_fps g' z * z ^ subdegree g\"\n      by (subst g_eq) (auto simp: eval_fps_mult)\n    finally show ?thesis by auto\n  qed (use \\<open>g \\<noteq> 0\\<close> in \\<open>auto simp: g'_def eval_fps_at_0\\<close>)\n\n  have \"R \\<le> min (min r (fps_conv_radius g)) (fps_conv_radius g')\"\n    by (auto simp: R_def min.coboundedI1 min.coboundedI2)\n  also have \"\\<dots> \\<le> fps_conv_radius (inverse g')\"\n    using g'_nz by (rule fps_conv_radius_inverse)\n  finally have conv_radius_inv: \"R \\<le> fps_conv_radius (inverse g')\" .\n  hence \"R \\<le> fps_conv_radius (f' * inverse g')\"\n    by (intro order.trans[OF _ fps_conv_radius_mult])\n       (auto simp: R_def intro: min.coboundedI1 min.coboundedI2)\n  thus \"fps_conv_radius (f / g) \\<ge> R\" by (simp add: fg)\n\n  fix z c :: complex assume z: \"ereal (norm z) < R\"\n  assume c: \"c = fps_nth f (subdegree g) / fps_nth g (subdegree g)\"\n  show \"eval_fps (f / g) z = (if z = 0 then c else eval_fps f z / eval_fps g z)\"\n  proof (cases \"z = 0\")\n    case False\n    from z and conv_radius_inv have \"ereal (norm z) < fps_conv_radius (inverse g')\"\n      by simp\n    with z have \"eval_fps (f / g) z = eval_fps f' z * eval_fps (inverse g') z\"\n      unfolding fg by (subst eval_fps_mult) (auto simp: R_def)\n    also have \"eval_fps (inverse g') z = inverse (eval_fps g' z)\"\n      using z by (intro eval_fps_inverse[of \"min r (fps_conv_radius g')\"] g'_nz) (auto simp: R_def)\n    also have \"eval_fps f' z * \\<dots> = eval_fps f z / eval_fps g z\"\n      using z False assms(2) by (simp add: f'_def g'_def eval_fps_shift R_def)\n    finally show ?thesis using False by simp\n  qed (simp_all add: eval_fps_at_0 fg field_simps c)\nqed\n\nlemma has_fps_expansion_fps_expansion [intro]:\n  assumes \"open A\" \"0 \\<in> A\" \"f holomorphic_on A\"\n  shows   \"f has_fps_expansion fps_expansion f 0\"\nproof -\n  from assms obtain r where \"r > 0 \" and r: \"ball 0 r \\<subseteq> A\"\n    by (auto simp: open_contains_ball)\n  with assms have holo: \"f holomorphic_on eball 0 (ereal r)\" \n    by auto\n  have \"r \\<le> fps_conv_radius (fps_expansion f 0)\"\n    using holo by (intro conv_radius_fps_expansion) auto\n  then have \"\\<dots> > 0\"\n    by (simp add: ereal_le_less \\<open>r > 0\\<close> zero_ereal_def) \n  moreover have \"eventually (\\<lambda>z. z \\<in> ball 0 r) (nhds 0)\"\n    using \\<open>r > 0\\<close> by (intro eventually_nhds_in_open) auto\n  hence \"eventually (\\<lambda>z. eval_fps (fps_expansion f 0) z = f z) (nhds 0)\"\n    by eventually_elim (subst eval_fps_expansion'[OF holo], auto)\n  ultimately show ?thesis using \\<open>r > 0\\<close> by (auto simp: has_fps_expansion_def)\nqed\n\nlemma fps_conv_radius_tan:\n  fixes c :: complex\n  assumes \"c \\<noteq> 0\"\n  shows   \"fps_conv_radius (fps_tan c) \\<ge> pi / (2 * norm c)\"\nproof -\n  have \"fps_conv_radius (fps_tan c) \\<ge> \n          Min {pi / (2 * norm c), fps_conv_radius (fps_sin c), fps_conv_radius (fps_cos c)}\"\n    unfolding fps_tan_def\n  proof (rule fps_conv_radius_divide)\n    fix z :: complex assume \"z \\<in> eball 0 (pi / (2 * norm c))\"\n    with cos_eq_zero_imp_norm_ge[of \"c*z\"] assms \n      show \"eval_fps (fps_cos  c) z \\<noteq> 0\" by (auto simp: norm_mult field_simps)\n  qed (insert assms, auto)\n  thus ?thesis by (simp add: min_def)\nqed\n\nlemma eval_fps_tan:\n  fixes c :: complex\n  assumes \"norm z < pi / (2 * norm c)\"\n  shows   \"eval_fps (fps_tan c) z = tan (c * z)\"\nproof (cases \"c = 0\")\n  case False\n  show ?thesis unfolding fps_tan_def\n  proof (subst eval_fps_divide'[where r = \"pi / (2 * norm c)\"])\n    fix z :: complex assume \"z \\<in> eball 0 (pi / (2 * norm c))\"\n    with cos_eq_zero_imp_norm_ge[of \"c*z\"] assms \n    show \"eval_fps (fps_cos  c) z \\<noteq> 0\" using False by (auto simp: norm_mult field_simps)\n  qed (use False assms in \\<open>auto simp: field_simps tan_def\\<close>)\nqed 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/HOL/Complex_Analysis/Cauchy_Integral_Formula.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8519528019683106, "lm_q2_score": 0.8221891370573388, "lm_q1q2_score": 0.7004663390639071}}
{"text": "(*\n  File: Rat.thy\n  Author: Bohua Zhan\n\n  Construction of the rational numbers (as pairs of integers (a,b) where b is\n  nonzero, under the equivalence relation (a,b) ~ (c,d) when a * d = b * c.\n*)\n\ntheory Rat\n  imports Int Field\nbegin\n\nsection \\<open>Definition of rational numbers\\<close>\n\ndefinition rat_rel_space :: i where [rewrite]:\n  \"rat_rel_space = carrier(\\<int>)\\<times>pos_elts(\\<int>)\"\n\ndefinition rat_rel :: i where [rewrite]:\n  \"rat_rel = Equiv(rat_rel_space, \\<lambda>p q. let \\<langle>a,b\\<rangle> = p; \\<langle>c,d\\<rangle> = q in a *\\<^sub>\\<int> d = b *\\<^sub>\\<int> c)\"\nnotation rat_rel (\"\\<R>\")\n\nlemma rat_rel_spaceI [typing]: \"x \\<in> int \\<Longrightarrow> y >\\<^sub>\\<int> \\<zero>\\<^sub>\\<int> \\<Longrightarrow> \\<langle>x,y\\<rangle> \\<in>. \\<R>\" by auto2\nlemma rat_rel_spaceI' [typing]: \"x \\<in> int \\<Longrightarrow> \\<langle>x,\\<one>\\<^sub>\\<int>\\<rangle> \\<in>. \\<R>\" by auto2\nlemma rat_rel_spaceD [forward]: \"p \\<in>. \\<R> \\<Longrightarrow> p = \\<langle>fst(p),snd(p)\\<rangle> \\<and> fst(p) \\<in> int \\<and> snd(p) >\\<^sub>\\<int> \\<zero>\\<^sub>\\<int>\" by auto2\nsetup {* del_prfstep_thm @{thm rat_rel_space_def} *}\n\nlemma rat_rel_trans [backward1]:\n  \"a1 \\<in>. \\<int> \\<Longrightarrow> a2 \\<in>. \\<int> \\<Longrightarrow> b1 \\<in>. \\<int> \\<Longrightarrow> b2 \\<in>. \\<int> \\<Longrightarrow> c1 \\<in>. \\<int> \\<Longrightarrow> c2 \\<in>. \\<int> \\<Longrightarrow> b2 \\<noteq> \\<zero>\\<^sub>\\<int> \\<Longrightarrow>\n   a1 *\\<^sub>\\<int> b2 = a2 *\\<^sub>\\<int> b1 \\<Longrightarrow> b1 *\\<^sub>\\<int> c2 = b2 *\\<^sub>\\<int> c1 \\<Longrightarrow> a1 *\\<^sub>\\<int> c2 = a2 *\\<^sub>\\<int> c1\"\n@proof\n  @have \"(a1 *\\<^sub>\\<int> c2) *\\<^sub>\\<int> b2 = (a1 *\\<^sub>\\<int> b2) *\\<^sub>\\<int> c2\"\n  @have \"(a2 *\\<^sub>\\<int> b1) *\\<^sub>\\<int> c2 = a2 *\\<^sub>\\<int> (b1 *\\<^sub>\\<int> c2)\"\n  @have \"a2 *\\<^sub>\\<int> (b2 *\\<^sub>\\<int> c1) = (a2 *\\<^sub>\\<int> c1) *\\<^sub>\\<int> b2\"\n@qed\n\nlemma rat_rel_is_rel [typing]: \"\\<R> \\<in> equiv_space(rat_rel_space)\" by auto2\nsetup {* del_prfstep_thm @{thm rat_rel_trans} *}\n\nlemma rat_rel_eval:\n  \"x \\<in>. \\<R> \\<Longrightarrow> y \\<in>. \\<R> \\<Longrightarrow> x \\<sim>\\<^sub>\\<R> y \\<longleftrightarrow> (fst(x) *\\<^sub>\\<int> snd(y) = snd(x) *\\<^sub>\\<int> fst(y))\" by auto2\nsetup {* add_rewrite_rule_cond @{thm rat_rel_eval} [with_cond \"?x \\<noteq> ?y\"] *}\nsetup {* del_prfstep_thm @{thm rat_rel_def} *}\n\ndefinition rat :: i where [rewrite_bidir]:\n  \"rat = carrier(\\<R>) // \\<R>\"\n  \nabbreviation Rat :: \"i \\<Rightarrow> i\" where \"Rat(p) \\<equiv> equiv_class(\\<R>,p)\"\n\nsection \\<open>Rationals as a ring\\<close>\n\ndefinition rat_mult_raw :: \"i \\<Rightarrow> i \\<Rightarrow> i\" where [rewrite]:\n  \"rat_mult_raw(p,q) = \\<langle>fst(p)*\\<^sub>\\<int>fst(q),snd(p)*\\<^sub>\\<int>snd(q)\\<rangle>\"\nsetup {* register_wellform_data (\"rat_mult_raw(p,q)\", [\"p \\<in>. \\<R>\", \"q \\<in>. \\<R>\"]) *}\n\nlemma rat_mult_raw_eval [rewrite]: \"rat_mult_raw(\\<langle>a,b\\<rangle>,\\<langle>c,d\\<rangle>) = \\<langle>a*\\<^sub>\\<int>c, b*\\<^sub>\\<int>d\\<rangle>\" by auto2\nsetup {* del_prfstep_thm @{thm rat_mult_raw_def} *}\n\ndefinition rat_add_raw :: \"i \\<Rightarrow> i \\<Rightarrow> i\" where [rewrite]:\n  \"rat_add_raw(p,q) = \\<langle>fst(p)*\\<^sub>\\<int>snd(q)+\\<^sub>\\<int>snd(p)*\\<^sub>\\<int>fst(q), snd(p)*\\<^sub>\\<int>snd(q)\\<rangle>\"\nsetup {* register_wellform_data (\"rat_add_raw(p,q)\", [\"p \\<in>. \\<R>\", \"q \\<in>. \\<R>\"]) *}\n\nlemma rat_add_raw_eval [rewrite]: \"rat_add_raw(\\<langle>a,b\\<rangle>,\\<langle>c,d\\<rangle>) = \\<langle>a*\\<^sub>\\<int>d+\\<^sub>\\<int>b*\\<^sub>\\<int>c, b*\\<^sub>\\<int>d\\<rangle>\" by auto2\nsetup {* del_prfstep_thm @{thm rat_add_raw_def} *}\n\ndefinition nonneg_rat_raw :: \"i \\<Rightarrow> o\" where [rewrite]:\n  \"nonneg_rat_raw(p) \\<longleftrightarrow> fst(p) \\<ge>\\<^sub>\\<int> \\<zero>\\<^sub>\\<int>\"\n\ndefinition nonneg_rat :: \"i \\<Rightarrow> o\" where [rewrite]:\n  \"nonneg_rat(x) \\<longleftrightarrow> nonneg_rat_raw(rep(\\<R>,x))\"\n\ndefinition nonneg_rats :: i where [rewrite]:\n  \"nonneg_rats = {x\\<in>rat. nonneg_rat(x)}\"\n\ndefinition rat_ring :: i where [rewrite]:\n  \"rat_ring = Ring(rat, Rat(\\<langle>\\<zero>\\<^sub>\\<int>,\\<one>\\<^sub>\\<int>\\<rangle>), \\<lambda>x y. Rat(rat_add_raw(rep(\\<R>,x), rep(\\<R>,y))),\n                        Rat(\\<langle>\\<one>\\<^sub>\\<int>,\\<one>\\<^sub>\\<int>\\<rangle>), \\<lambda>x y. Rat(rat_mult_raw(rep(\\<R>,x), rep(\\<R>,y))))\"\n\nlemma rat_ring_is_ring_raw [forward]: \"ring_form(rat_ring)\" by auto2\n\ndefinition rat_ord_ring :: i  (\"\\<rat>\") where [rewrite]:\n  \"rat_ord_ring = ord_ring_from_nonneg(rat_ring, nonneg_rats)\"\n\nlemma rat_is_ring_raw [forward]: \"is_ring_raw(\\<rat>)\" by auto2\nlemma rat_carrier [rewrite_bidir]: \"carrier(\\<rat>) = rat\" by auto2\nlemma rat_evals [rewrite]:\n  \"\\<zero>\\<^sub>\\<rat> = Rat(\\<langle>\\<zero>\\<^sub>\\<int>,\\<one>\\<^sub>\\<int>\\<rangle>)\"\n  \"\\<one>\\<^sub>\\<rat> = Rat(\\<langle>\\<one>\\<^sub>\\<int>,\\<one>\\<^sub>\\<int>\\<rangle>)\"\n  \"x \\<in>. \\<rat> \\<Longrightarrow> y \\<in>. \\<rat> \\<Longrightarrow> x +\\<^sub>\\<rat> y = Rat(rat_add_raw(rep(\\<R>,x), rep(\\<R>,y)))\"\n  \"x \\<in>. \\<rat> \\<Longrightarrow> y \\<in>. \\<rat> \\<Longrightarrow> x *\\<^sub>\\<rat> y = Rat(rat_mult_raw(rep(\\<R>,x), rep(\\<R>,y)))\" by auto2+\n\nlemma rat_is_ord_field_prep [forward]:\n  \"is_field(\\<rat>) \\<Longrightarrow> nonneg_compat(\\<rat>,nonneg_rats) \\<Longrightarrow> is_ord_field(\\<rat>)\" by auto2\n    \nsetup {* fold del_prfstep_thm [@{thm rat_ring_def}, @{thm rat_ord_ring_def}] *}\n    \nlemma rat_zero_raw_mem [typing]: \"\\<langle>\\<zero>\\<^sub>\\<int>,\\<one>\\<^sub>\\<int>\\<rangle> \\<in>. \\<R>\" by auto2\nlemma rat_one_raw_mem [typing]: \"\\<langle>\\<one>\\<^sub>\\<int>,\\<one>\\<^sub>\\<int>\\<rangle> \\<in>. \\<R>\" by auto2\n\nlemma rat_choose_rep: \"r \\<in>. \\<rat> \\<Longrightarrow> r = Rat(rep(\\<R>,r))\" by auto2\nsetup {* add_rewrite_rule_cond @{thm rat_choose_rep} [with_filt (size1_filter \"r\")] *}\n\nsection \\<open>Multiplication on rationals\\<close>\n\nlemma rat_mult_raw_type [typing]:\n  \"\\<langle>a,b\\<rangle> \\<in>. \\<R> \\<Longrightarrow> \\<langle>c,d\\<rangle> \\<in>. \\<R> \\<Longrightarrow> rat_mult_raw(\\<langle>a,b\\<rangle>,\\<langle>c,d\\<rangle>) \\<in>. \\<R>\" by auto2\n\nlemma rat_mult_eval [rewrite]:\n  \"x \\<in>. \\<R> \\<Longrightarrow> y \\<in>. \\<R> \\<Longrightarrow> Rat(x) *\\<^sub>\\<rat> Rat(y) = Rat(rat_mult_raw(x,y))\"\n@proof\n  @have \"compat_meta_bin1(\\<R>, rat_mult_raw)\" @with\n    @have (@rule) \"\\<forall>a b c d a' b'. \\<langle>c,d\\<rangle> \\<in>. \\<R> \\<longrightarrow> \\<langle>a',b'\\<rangle> \\<sim>\\<^sub>\\<R> \\<langle>a,b\\<rangle> \\<longrightarrow>\n                   rat_mult_raw(\\<langle>a',b'\\<rangle>,\\<langle>c,d\\<rangle>) \\<sim>\\<^sub>\\<R> rat_mult_raw(\\<langle>a,b\\<rangle>,\\<langle>c,d\\<rangle>)\" @with\n      @have \"(a' *\\<^sub>\\<int> c) *\\<^sub>\\<int> (b *\\<^sub>\\<int> d) = (a' *\\<^sub>\\<int> b) *\\<^sub>\\<int> (c *\\<^sub>\\<int> d)\"\n      @have \"(b' *\\<^sub>\\<int> d) *\\<^sub>\\<int> (a *\\<^sub>\\<int> c) = (b' *\\<^sub>\\<int> a) *\\<^sub>\\<int> (c *\\<^sub>\\<int> d)\"\n    @end\n  @end\n  @have \"compat_meta_bin2(\\<R>, rat_mult_raw)\" @with\n    @have (@rule) \"\\<forall>a b c d c' d'. \\<langle>a,b\\<rangle> \\<in>. \\<R> \\<longrightarrow> \\<langle>c',d'\\<rangle> \\<sim>\\<^sub>\\<R> \\<langle>c,d\\<rangle> \\<longrightarrow>\n                   rat_mult_raw(\\<langle>a,b\\<rangle>,\\<langle>c',d'\\<rangle>) \\<sim>\\<^sub>\\<R> rat_mult_raw(\\<langle>a,b\\<rangle>,\\<langle>c,d\\<rangle>)\" @with\n      @have \"(a *\\<^sub>\\<int> c') *\\<^sub>\\<int> (b *\\<^sub>\\<int> d) = (a *\\<^sub>\\<int> b) *\\<^sub>\\<int> (c' *\\<^sub>\\<int> d)\"\n      @have \"(b *\\<^sub>\\<int> d') *\\<^sub>\\<int> (a *\\<^sub>\\<int> c) = (a *\\<^sub>\\<int> b) *\\<^sub>\\<int> (d' *\\<^sub>\\<int> c)\"\n    @end\n  @end\n  @have \"compat_meta_bin(\\<R>, rat_mult_raw)\"\n@qed\nsetup {* del_prfstep_thm @{thm rat_evals(4)} *}\n\nlemma rat_mult_comm [forward]: \"is_times_comm(\\<rat>)\" by auto2\nlemma rat_mult_assoc [forward]: \"is_times_assoc(\\<rat>)\" by auto2\n\nsection \\<open>Addition on rationals\\<close>\n\nlemma rat_add_raw_type [typing]:\n  \"\\<langle>a,b\\<rangle> \\<in>. \\<R> \\<Longrightarrow> \\<langle>c,d\\<rangle> \\<in>. \\<R> \\<Longrightarrow> rat_add_raw(\\<langle>a,b\\<rangle>,\\<langle>c,d\\<rangle>) \\<in>. \\<R>\" by auto2\n\nlemma rat_add_eval [rewrite]:\n  \"x \\<in>. \\<R> \\<Longrightarrow> y \\<in>. \\<R> \\<Longrightarrow> Rat(x) +\\<^sub>\\<rat> Rat(y) = Rat(rat_add_raw(x,y))\"\n@proof\n  @have \"compat_meta_bin1(\\<R>, rat_add_raw)\" @with\n    @have (@rule) \"\\<forall>a b c d a' b'. \\<langle>c,d\\<rangle> \\<in>. \\<R> \\<longrightarrow> \\<langle>a',b'\\<rangle> \\<sim>\\<^sub>\\<R> \\<langle>a,b\\<rangle> \\<longrightarrow>\n                   rat_add_raw(\\<langle>a',b'\\<rangle>,\\<langle>c,d\\<rangle>) \\<sim>\\<^sub>\\<R> rat_add_raw(\\<langle>a,b\\<rangle>,\\<langle>c,d\\<rangle>)\" @with\n      @have \"(a'*\\<^sub>\\<int>d +\\<^sub>\\<int> b'*\\<^sub>\\<int>c) *\\<^sub>\\<int> (b*\\<^sub>\\<int>d) = (a'*\\<^sub>\\<int>b)*\\<^sub>\\<int>d*\\<^sub>\\<int>d +\\<^sub>\\<int> b*\\<^sub>\\<int>b'*\\<^sub>\\<int>c*\\<^sub>\\<int>d\"\n      @have \"(b'*\\<^sub>\\<int>d) *\\<^sub>\\<int> (a*\\<^sub>\\<int>d +\\<^sub>\\<int> b*\\<^sub>\\<int>c) = (b'*\\<^sub>\\<int>a)*\\<^sub>\\<int>d*\\<^sub>\\<int>d +\\<^sub>\\<int> b*\\<^sub>\\<int>b'*\\<^sub>\\<int>c*\\<^sub>\\<int>d\"\n    @end\n  @end\n  @have \"compat_meta_bin2(\\<R>, rat_add_raw)\" @with\n    @have (@rule) \"\\<forall>a b c d c' d'. \\<langle>a,b\\<rangle> \\<in>. \\<R> \\<longrightarrow> \\<langle>c',d'\\<rangle> \\<sim>\\<^sub>\\<R> \\<langle>c,d\\<rangle> \\<longrightarrow>\n                   rat_add_raw(\\<langle>a,b\\<rangle>,\\<langle>c',d'\\<rangle>) \\<sim>\\<^sub>\\<R> rat_add_raw(\\<langle>a,b\\<rangle>,\\<langle>c,d\\<rangle>)\" @with\n      @have \"(a*\\<^sub>\\<int>d' +\\<^sub>\\<int> b*\\<^sub>\\<int>c') *\\<^sub>\\<int> (b*\\<^sub>\\<int>d) = (c'*\\<^sub>\\<int>d)*\\<^sub>\\<int>b*\\<^sub>\\<int>b +\\<^sub>\\<int> a*\\<^sub>\\<int>b*\\<^sub>\\<int>d*\\<^sub>\\<int>d'\"\n      @have \"(b*\\<^sub>\\<int>d') *\\<^sub>\\<int> (a*\\<^sub>\\<int>d +\\<^sub>\\<int> b*\\<^sub>\\<int>c)  = (d'*\\<^sub>\\<int>c)*\\<^sub>\\<int>b*\\<^sub>\\<int>b +\\<^sub>\\<int> a*\\<^sub>\\<int>b*\\<^sub>\\<int>d*\\<^sub>\\<int>d'\"\n    @end\n  @end\n  @have \"compat_meta_bin(\\<R>, rat_add_raw)\"\n@qed\nsetup {* del_prfstep_thm @{thm rat_evals(3)} *}\n\nlemma rat_add_comm [forward]: \"is_plus_comm(\\<rat>)\" by auto2\n\nlemma rat_add_raw_assoc [rewrite]:\n  \"\\<langle>a,b\\<rangle> \\<in>. \\<R> \\<Longrightarrow> \\<langle>c,d\\<rangle> \\<in>. \\<R> \\<Longrightarrow> \\<langle>e,f\\<rangle> \\<in>. \\<R> \\<Longrightarrow>\n   rat_add_raw(rat_add_raw(\\<langle>a,b\\<rangle>,\\<langle>c,d\\<rangle>),\\<langle>e,f\\<rangle>) = rat_add_raw(\\<langle>a,b\\<rangle>,rat_add_raw(\\<langle>c,d\\<rangle>,\\<langle>e,f\\<rangle>))\"\n@proof\n  @have \"(a*\\<^sub>\\<int>d +\\<^sub>\\<int> b*\\<^sub>\\<int>c) *\\<^sub>\\<int> f +\\<^sub>\\<int> (b*\\<^sub>\\<int>d)*\\<^sub>\\<int>e = a*\\<^sub>\\<int>(d*\\<^sub>\\<int>f) +\\<^sub>\\<int> b *\\<^sub>\\<int> (c*\\<^sub>\\<int>f +\\<^sub>\\<int> d*\\<^sub>\\<int>e)\"\n@qed\n\nlemma rat_add_assoc [forward]: \"is_plus_assoc(\\<rat>)\" by auto2\nsetup {* del_prfstep_thm @{thm rat_add_raw_assoc} *}\n\nlemma rat_distrib_l_raw [resolve]:\n  \"\\<langle>a,b\\<rangle> \\<in>. \\<R> \\<Longrightarrow> \\<langle>c,d\\<rangle> \\<in>. \\<R> \\<Longrightarrow> \\<langle>e,f\\<rangle> \\<in>. \\<R> \\<Longrightarrow>\n   rat_mult_raw(\\<langle>a,b\\<rangle>,rat_add_raw(\\<langle>c,d\\<rangle>,\\<langle>e,f\\<rangle>)) \\<sim>\\<^sub>\\<R> rat_add_raw(rat_mult_raw(\\<langle>a,b\\<rangle>,\\<langle>c,d\\<rangle>),rat_mult_raw(\\<langle>a,b\\<rangle>,\\<langle>e,f\\<rangle>))\"\n@proof\n  @have \"a*\\<^sub>\\<int>(c*\\<^sub>\\<int>f+\\<^sub>\\<int>d*\\<^sub>\\<int>e) *\\<^sub>\\<int> ((b*\\<^sub>\\<int>d)*\\<^sub>\\<int>(b*\\<^sub>\\<int>f)) = b*\\<^sub>\\<int>(d*\\<^sub>\\<int>f) *\\<^sub>\\<int> ((a*\\<^sub>\\<int>c)*\\<^sub>\\<int>(b*\\<^sub>\\<int>f) +\\<^sub>\\<int> (b*\\<^sub>\\<int>d)*\\<^sub>\\<int>(a*\\<^sub>\\<int>e))\"\n@qed\n\nlemma rat_distrib_l [forward]: \"is_left_distrib(\\<rat>)\" by auto2\nsetup {* del_prfstep_thm @{thm rat_distrib_l_raw} *}\n\nsection \\<open>0 and 1\\<close>\n  \nlemma rat_is_add_id [forward]: \"is_add_id(\\<rat>)\" by auto2\nlemma rat_is_mult_id [forward]: \"is_mult_id(\\<rat>)\" by auto2\nlemma rat_zero_neq_one [resolve]: \"\\<zero>\\<^sub>\\<rat> \\<noteq> \\<one>\\<^sub>\\<rat>\" by auto2\n\nsection \\<open>Negation on rationals\\<close>\n  \ndefinition rat_neg_raw :: \"i \\<Rightarrow> i\" where [rewrite]:\n  \"rat_neg_raw(p) = \\<langle>-\\<^sub>\\<int> fst(p), snd(p)\\<rangle>\"\n  \ndefinition rat_neg :: \"i \\<Rightarrow> i\" where [rewrite]:\n  \"rat_neg(x) = Rat(rat_neg_raw(rep(\\<R>,x)))\"\n  \nlemma rat_neg_typing [typing]: \"x \\<in>. \\<rat> \\<Longrightarrow> rat_neg(x) \\<in>. \\<rat>\" by auto2\n\nlemma rat_add_raw_eval_eq_denom [rewrite]:\n  \"\\<langle>p,r\\<rangle> \\<in>. \\<R> \\<Longrightarrow> \\<langle>q,r\\<rangle> \\<in>. \\<R> \\<Longrightarrow> Rat(\\<langle>p,r\\<rangle>) +\\<^sub>\\<rat> Rat(\\<langle>q,r\\<rangle>) = Rat(\\<langle>p+\\<^sub>\\<int>q, r\\<rangle>)\"\n@proof @have \"(p*\\<^sub>\\<int>r +\\<^sub>\\<int> r*\\<^sub>\\<int>q) *\\<^sub>\\<int> r = r *\\<^sub>\\<int> r *\\<^sub>\\<int> (p +\\<^sub>\\<int> q)\" @qed\n\nlemma rat_equiv_class_zero [rewrite]: \"q >\\<^sub>\\<int> \\<zero>\\<^sub>\\<int> \\<Longrightarrow> Rat(\\<langle>\\<zero>\\<^sub>\\<int>,q\\<rangle>) = \\<zero>\\<^sub>\\<rat>\" by auto2\n\nlemma rat_has_add_inverse [forward]: \"has_add_inverse(\\<rat>)\"\n@proof @have \"\\<forall>x\\<in>.\\<rat>. x +\\<^sub>\\<rat> rat_neg(x) = \\<zero>\\<^sub>\\<rat>\" @qed\n\nlemma rat_is_comm_ring [forward]: \"is_comm_ring(\\<rat>)\" by auto2\n\nsection \\<open>Inverse in rationals\\<close>\n\ndefinition rat_inverse_raw :: \"i \\<Rightarrow> i\" where [rewrite]:\n  \"rat_inverse_raw(p) = (if fst(p) >\\<^sub>\\<int> \\<zero>\\<^sub>\\<int> then \\<langle>snd(p),fst(p)\\<rangle> else \\<langle>-\\<^sub>\\<int> snd(p), -\\<^sub>\\<int> fst(p)\\<rangle>)\"\nsetup {* register_wellform_data (\"rat_inverse_raw(p)\", [\"p \\<in>. \\<R>\"]) *}\n  \nlemma rat_inverse_raw_eval [rewrite]:\n  \"\\<langle>a,b\\<rangle> \\<in>. \\<R> \\<Longrightarrow> a >\\<^sub>\\<int> \\<zero>\\<^sub>\\<int> \\<Longrightarrow> rat_inverse_raw(\\<langle>a,b\\<rangle>) = \\<langle>b,a\\<rangle>\"\n  \"\\<langle>a,b\\<rangle> \\<in>. \\<R> \\<Longrightarrow> a <\\<^sub>\\<int> \\<zero>\\<^sub>\\<int> \\<Longrightarrow> rat_inverse_raw(\\<langle>a,b\\<rangle>) = \\<langle>-\\<^sub>\\<int> b, -\\<^sub>\\<int> a\\<rangle>\" by auto2+\nsetup {* del_prfstep_thm @{thm rat_inverse_raw_def} *}\n\nlemma rat_inverse_raw_type [typing]:\n  \"\\<langle>a,b\\<rangle> \\<in>. \\<R> \\<Longrightarrow> a \\<noteq> \\<zero>\\<^sub>\\<int> \\<Longrightarrow> rat_inverse_raw(\\<langle>a,b\\<rangle>) \\<in>. \\<R>\"\n@proof @case \"a >\\<^sub>\\<int> \\<zero>\\<^sub>\\<int>\" @qed\n\ndefinition rat_inverse :: \"i \\<Rightarrow> i\" where [rewrite]:\n  \"rat_inverse(r) = Rat(rat_inverse_raw(rep(\\<R>,r)))\"\n\nlemma rat_equiv_zero [rewrite]:\n  \"\\<langle>a,b\\<rangle> \\<in>. \\<R> \\<Longrightarrow> Rat(\\<langle>a,b\\<rangle>) = \\<zero>\\<^sub>\\<rat> \\<longleftrightarrow> a = \\<zero>\\<^sub>\\<int>\" by auto2\n\nlemma rat_inverse_typing [typing]:\n  \"x \\<in>. \\<rat> \\<Longrightarrow> x \\<noteq> \\<zero>\\<^sub>\\<rat> \\<Longrightarrow> rat_inverse(x) \\<in>. \\<rat>\" by auto2\n\nlemma rat_inverse_raw_mult_inv [rewrite]:\n  \"\\<langle>p,q\\<rangle> \\<in>. \\<R> \\<Longrightarrow> p \\<noteq> \\<zero>\\<^sub>\\<int> \\<Longrightarrow> Rat(rat_mult_raw(\\<langle>p,q\\<rangle>,rat_inverse_raw(\\<langle>p,q\\<rangle>))) = \\<one>\\<^sub>\\<rat>\"\n@proof @case \"p >\\<^sub>\\<int> \\<zero>\\<^sub>\\<int>\" @qed\n\nlemma rat_is_field [forward]: \"is_field(\\<rat>)\"\n@proof @have \"\\<forall>x\\<in>.\\<rat>. x \\<noteq> \\<zero>\\<^sub>\\<rat> \\<longrightarrow> x *\\<^sub>\\<rat> rat_inverse(x) = \\<one>\\<^sub>\\<rat>\" @qed\n\nsection \\<open>Nonnegative rationals\\<close>\n\nlemma nonneg_rat_eval [rewrite]:\n  \"x \\<in>. \\<R> \\<Longrightarrow> nonneg_rat(Rat(x)) \\<longleftrightarrow> nonneg_rat_raw(x)\" by auto2\nsetup {* del_prfstep_thm @{thm nonneg_rat_def} *}\n\nlemma rat_neg_eval [rewrite]: \"x \\<in>. \\<R> \\<Longrightarrow> -\\<^sub>\\<rat> Rat(x) = Rat(rat_neg_raw(x))\"\n@proof @have \"Rat(x) +\\<^sub>\\<rat> Rat(rat_neg_raw(x)) = \\<zero>\\<^sub>\\<rat>\" @qed\n\nlemma rat_nonneg_compat [resolve]: \"nonneg_compat(\\<rat>, nonneg_rats)\" by auto2\nsetup {* fold del_prfstep_thm [\n  @{thm nonneg_rat_eval}, @{thm nonneg_rat_raw_def}, @{thm nonneg_rats_def}] *}\n\nlemma rat_is_ord_field [forward]: \"is_ord_field(\\<rat>)\"\n@proof @have \"nonneg_compat(\\<rat>, nonneg_rats)\" @qed\nsetup {* del_prfstep_thm @{thm rat_is_ord_field_prep} *}\n\nsection \\<open>Rational as a quotient of two integers\\<close>\n\nlemma rat_of_nat [rewrite]:\n  \"n \\<in> nat \\<Longrightarrow> of_nat(\\<rat>,n) = Rat(\\<langle>of_nat(\\<int>,n),1\\<^sub>\\<int>\\<rangle>)\"\n@proof @var_induct \"n \\<in> nat\" @qed\n\nlemma rat_diff_raw_eval [rewrite]:\n  \"\\<langle>p,r\\<rangle> \\<in>. \\<R> \\<Longrightarrow> \\<langle>q,r\\<rangle> \\<in>. \\<R> \\<Longrightarrow> Rat(\\<langle>p,r\\<rangle>) -\\<^sub>\\<rat> Rat(\\<langle>q,r\\<rangle>) = Rat(\\<langle>p-\\<^sub>\\<int>q, r\\<rangle>)\"\n@proof\n  @have \"Rat(\\<langle>p,r\\<rangle>) -\\<^sub>\\<rat> Rat(\\<langle>q,r\\<rangle>) = Rat(\\<langle>p,r\\<rangle>) +\\<^sub>\\<rat> (-\\<^sub>\\<rat> Rat(\\<langle>q,r\\<rangle>))\"\n  @have \"p -\\<^sub>\\<int> q = p +\\<^sub>\\<int> (-\\<^sub>\\<int> q)\"\n@qed\n\nlemma rat_of_int [rewrite]: \"z \\<in> int \\<Longrightarrow> of_int(\\<rat>,z) = Rat(\\<langle>z,1\\<^sub>\\<int>\\<rangle>)\"\n@proof @obtain \"a\\<in>.\\<nat>\" \"b\\<in>.\\<nat>\" where \"z = of_nat(\\<int>,a) -\\<^sub>\\<int> of_nat(\\<int>,b)\" @qed\n\nlemma rat_inverse_eval [rewrite]:\n  \"\\<langle>a,b\\<rangle> \\<in>. \\<R> \\<Longrightarrow> a >\\<^sub>\\<int> \\<zero>\\<^sub>\\<int> \\<Longrightarrow> inv(\\<rat>,Rat(\\<langle>a,b\\<rangle>)) = Rat(\\<langle>b,a\\<rangle>)\"\n@proof @have \"Rat(\\<langle>a,b\\<rangle>) *\\<^sub>\\<rat> Rat(\\<langle>b,a\\<rangle>) = \\<one>\\<^sub>\\<rat>\" @qed\n\nlemma rat_div_eval [rewrite]:\n  \"\\<langle>a,b\\<rangle> \\<in>. \\<R> \\<Longrightarrow> \\<langle>c,d\\<rangle> \\<in>. \\<R> \\<Longrightarrow> c >\\<^sub>\\<int> \\<zero>\\<^sub>\\<int> \\<Longrightarrow> Rat(\\<langle>a,b\\<rangle>) /\\<^sub>\\<rat> Rat(\\<langle>c,d\\<rangle>) = Rat(\\<langle>a*\\<^sub>\\<int>d,b*\\<^sub>\\<int>c\\<rangle>)\"\n@proof @have \"Rat(\\<langle>a,b\\<rangle>) /\\<^sub>\\<rat> Rat(\\<langle>c,d\\<rangle>) = Rat(\\<langle>a,b\\<rangle>) *\\<^sub>\\<rat> inv(\\<rat>,Rat(\\<langle>c,d\\<rangle>))\" @qed\n\nlemma rat_is_quotient [backward]:\n  \"r \\<in>. \\<rat> \\<Longrightarrow> \\<exists>a\\<in>.\\<int>. \\<exists>b>\\<^sub>\\<int>0\\<^sub>\\<int>. r = of_int(\\<rat>,a) /\\<^sub>\\<rat> of_int(\\<rat>,b)\"\n@proof\n  @let \"p = rep(\\<R>,r)\"\n  @have \"r = of_int(\\<rat>,fst(p)) /\\<^sub>\\<rat> of_int(\\<rat>,snd(p))\"\n@qed\n\nsetup {* fold del_prfstep_thm [@{thm rat_neg_eval}, @{thm rat_neg_raw_def}] *}\n\nsection \\<open>Definition of of\\_rat\\<close>\n  \ndefinition of_rat_raw :: \"i \\<Rightarrow> i \\<Rightarrow> i\" where [rewrite]:\n  \"of_rat_raw(R,p) = of_int(R,fst(p)) /\\<^sub>R of_int(R,snd(p))\"\n\nlemma of_rat_raw_eval [rewrite]: \"of_rat_raw(R,\\<langle>a,b\\<rangle>) = of_int(R,a) /\\<^sub>R of_int(R,b)\" by auto2\nsetup {* del_prfstep_thm @{thm of_rat_raw_def} *}\n\nlemma field_switch_sides4 [resolve]:\n  \"is_field(R) \\<Longrightarrow> a \\<in>. R \\<Longrightarrow> b \\<in> units(R) \\<Longrightarrow> c \\<in>. R \\<Longrightarrow> d \\<in> units(R) \\<Longrightarrow>\n   a *\\<^sub>R d = b *\\<^sub>R c \\<Longrightarrow> a /\\<^sub>R b = c /\\<^sub>R d\"\n@proof\n  @have \"(a /\\<^sub>R b) *\\<^sub>R (b *\\<^sub>R d) = (c /\\<^sub>R d) *\\<^sub>R (b *\\<^sub>R d)\" @have \"b *\\<^sub>R d \\<in> units(R)\"\n@qed\n\ndefinition of_rat :: \"i \\<Rightarrow> i \\<Rightarrow> i\" where [rewrite]:\n  \"of_rat(R,r) = of_rat_raw(R,rep(\\<R>,r))\"\nsetup {* register_wellform_data (\"of_rat(R,r)\", [\"r \\<in>. \\<rat>\"]) *}\n\nlemma of_rat_eval [rewrite]:\n  \"is_ord_field(R) \\<Longrightarrow> x \\<in>. \\<R> \\<Longrightarrow> of_rat(R,Rat(x)) = of_rat_raw(R,x)\"\n@proof\n  @have (@rule) \"\\<forall>a b c d. \\<langle>a,b\\<rangle> \\<sim>\\<^sub>\\<R> \\<langle>c,d\\<rangle> \\<longrightarrow> of_rat_raw(R,\\<langle>a,b\\<rangle>) = of_rat_raw(R,\\<langle>c,d\\<rangle>)\" @with\n    @have \"of_int(R,d) \\<noteq> of_int(R,0\\<^sub>\\<int>)\"\n    @have \"of_int(R,a) *\\<^sub>R of_int(R,d) = of_int(R,b) *\\<^sub>R of_int(R,c)\"\n  @end\n@qed\nsetup {* del_prfstep_thm @{thm of_rat_def} *}\n\nlemma of_int_is_unit [typing]:\n  \"is_ord_field(R) \\<Longrightarrow> x >\\<^sub>\\<int> \\<zero>\\<^sub>\\<int> \\<Longrightarrow> of_int(R,x) \\<in> units(R)\" by auto2\n\nlemma of_rat_type [typing]:\n  \"is_ord_field(R) \\<Longrightarrow> r \\<in>. \\<rat> \\<Longrightarrow> of_rat(R,r) \\<in>. R\" by auto2\n\nlemma of_rat_eval_quotient [rewrite]:\n  \"is_ord_field(R) \\<Longrightarrow> x \\<in>. \\<int> \\<Longrightarrow> y >\\<^sub>\\<int> 0\\<^sub>\\<int> \\<Longrightarrow>\n   of_rat(R,of_int(\\<rat>,x) /\\<^sub>\\<rat> of_int(\\<rat>,y)) = of_int(R,x) /\\<^sub>R of_int(R,y)\" by auto2\n\nlemma of_rat_is_zero [forward]:\n  \"is_ord_field(R) \\<Longrightarrow> x \\<in>. \\<rat> \\<Longrightarrow> of_rat(R,x) = 0\\<^sub>R \\<Longrightarrow> x = 0\\<^sub>\\<rat>\"\n@proof\n  @obtain \"a\\<in>.\\<int>\" b where \"b>\\<^sub>\\<int>0\\<^sub>\\<int>\" \"x = of_int(\\<rat>,a) /\\<^sub>\\<rat> of_int(\\<rat>,b)\"\n  @have \"of_int(R,a) = of_int(R,0\\<^sub>\\<int>)\"\n@qed\n  \nlemma of_rat_of_int [rewrite]:\n  \"is_ord_field(R) \\<Longrightarrow> x \\<in>. \\<int> \\<Longrightarrow> of_rat(R,of_int(\\<rat>,x)) = of_int(R,x)\" by auto2\n\nlemma of_rat_of_nat [rewrite]:\n  \"is_ord_field(R) \\<Longrightarrow> n \\<in> nat \\<Longrightarrow> of_rat(R,of_nat(\\<rat>,n)) = of_nat(R,n)\" by auto2\n\nsetup {* fold del_prfstep_thm [@{thm of_rat_eval}, @{thm rat_of_nat}, @{thm rat_of_int}] *}\nsetup {* fold del_prfstep_thm [@{thm rat_def}, @{thm rat_rel_spaceI}, @{thm rat_rel_spaceD}] *}\nsetup {* fold del_prfstep_thm @{thms rat_evals(1-2)} *}\nsetup {* fold del_prfstep_thm [@{thm rat_choose_rep}, @{thm rat_inverse_eval},\n  @{thm rat_div_eval}, @{thm rat_mult_eval}, @{thm rat_add_eval}] *}\nno_notation rat_rel (\"\\<R>\")\nhide_const Rat\n\nsection \\<open>Further properties\\<close>\n  \nlemma of_rat_mult [rewrite_bidir]:\n  \"is_ord_field(R) \\<Longrightarrow> x \\<in>. \\<rat> \\<Longrightarrow> y \\<in>. \\<rat> \\<Longrightarrow> of_rat(R,x) *\\<^sub>R of_rat(R,y) = of_rat(R,x *\\<^sub>\\<rat> y)\"\n@proof\n  @obtain \"a\\<in>.\\<int>\" b where \"b>\\<^sub>\\<int>0\\<^sub>\\<int>\" \"x = of_int(\\<rat>,a) /\\<^sub>\\<rat> of_int(\\<rat>,b)\"\n  @obtain \"c\\<in>.\\<int>\" d where \"d>\\<^sub>\\<int>0\\<^sub>\\<int>\" \"y = of_int(\\<rat>,c) /\\<^sub>\\<rat> of_int(\\<rat>,d)\"\n  @let \"qa = of_int(\\<rat>,a)\" \"qb = of_int(\\<rat>,b)\" \"qc = of_int(\\<rat>,c)\" \"qd = of_int(\\<rat>,d)\"\n  @let \"ra = of_int(R,a)\" \"rb = of_int(R,b)\" \"rc = of_int(R,c)\" \"rd = of_int(R,d)\"\n  @have \"(qa /\\<^sub>\\<rat> qb) *\\<^sub>\\<rat> (qc /\\<^sub>\\<rat> qd) = (qa *\\<^sub>\\<rat> qc) /\\<^sub>\\<rat> (qb *\\<^sub>\\<rat> qd)\"\n  @have \"(ra /\\<^sub>R rb) *\\<^sub>R (rc /\\<^sub>R rd) = (ra *\\<^sub>R rc) /\\<^sub>R (rb *\\<^sub>R rd)\"\n@qed\n\nlemma of_rat_inverse [rewrite_bidir]:\n  \"is_ord_field(R) \\<Longrightarrow> x \\<in> units(\\<rat>) \\<Longrightarrow> inv(R,of_rat(R,x)) = of_rat(R,inv(\\<rat>,x))\"\n@proof @have \"of_rat(R,inv(\\<rat>,x)) *\\<^sub>R of_rat(R,x) = \\<one>\\<^sub>R\" @qed\n\nlemma of_rat_add [rewrite_bidir]:\n  \"is_ord_field(R) \\<Longrightarrow> x \\<in>. \\<rat> \\<Longrightarrow> y \\<in>. \\<rat> \\<Longrightarrow> of_rat(R,x) +\\<^sub>R of_rat(R,y) = of_rat(R,x +\\<^sub>\\<rat> y)\"\n@proof\n  @obtain \"a\\<in>.\\<int>\" b where \"b>\\<^sub>\\<int>0\\<^sub>\\<int>\" \"x = of_int(\\<rat>,a) /\\<^sub>\\<rat> of_int(\\<rat>,b)\"\n  @obtain \"c\\<in>.\\<int>\" d where \"d>\\<^sub>\\<int>0\\<^sub>\\<int>\" \"y = of_int(\\<rat>,c) /\\<^sub>\\<rat> of_int(\\<rat>,d)\"\n  @let \"qa = of_int(\\<rat>,a)\" \"qb = of_int(\\<rat>,b)\" \"qc = of_int(\\<rat>,c)\" \"qd = of_int(\\<rat>,d)\"\n  @let \"ra = of_int(R,a)\" \"rb = of_int(R,b)\" \"rc = of_int(R,c)\" \"rd = of_int(R,d)\"\n  @have \"(qa /\\<^sub>\\<rat> qb) +\\<^sub>\\<rat> (qc /\\<^sub>\\<rat> qd) = (qa *\\<^sub>\\<rat> qd +\\<^sub>\\<rat> qb *\\<^sub>\\<rat> qc) /\\<^sub>\\<rat> (qb *\\<^sub>\\<rat> qd)\"\n  @have \"(ra /\\<^sub>R rb) +\\<^sub>R (rc /\\<^sub>R rd) = (ra *\\<^sub>R rd +\\<^sub>R rb *\\<^sub>R rc) /\\<^sub>R (rb *\\<^sub>R rd)\"\n@qed\n      \nlemma ord_field_le_divide_switch [backward1]:\n  \"is_ord_field(R) \\<Longrightarrow> a \\<in>. R \\<Longrightarrow> c \\<in>. R \\<Longrightarrow> b >\\<^sub>R 0\\<^sub>R \\<Longrightarrow> d >\\<^sub>R 0\\<^sub>R \\<Longrightarrow>\n   a /\\<^sub>R b \\<le>\\<^sub>R c /\\<^sub>R d \\<Longrightarrow> a *\\<^sub>R d \\<le>\\<^sub>R b *\\<^sub>R c\"\n@proof\n  @have \"a /\\<^sub>R b *\\<^sub>R (b *\\<^sub>R d) \\<le>\\<^sub>R c /\\<^sub>R d *\\<^sub>R (b *\\<^sub>R d)\" @have \"b *\\<^sub>R d >\\<^sub>R 0\\<^sub>R\"\n@qed\n\nlemma ord_field_le_divide_switch2 [backward1]:\n  \"is_ord_field(R) \\<Longrightarrow> a \\<in>. R \\<Longrightarrow> c \\<in>. R \\<Longrightarrow> b >\\<^sub>R 0\\<^sub>R \\<Longrightarrow> d >\\<^sub>R 0\\<^sub>R \\<Longrightarrow>\n   a *\\<^sub>R d \\<le>\\<^sub>R b *\\<^sub>R c \\<Longrightarrow> a /\\<^sub>R b \\<le>\\<^sub>R c /\\<^sub>R d\"\n@proof\n  @have \"a *\\<^sub>R d /\\<^sub>R (b *\\<^sub>R d) \\<le>\\<^sub>R b *\\<^sub>R c /\\<^sub>R (b *\\<^sub>R d)\" @have \"b *\\<^sub>R d >\\<^sub>R 0\\<^sub>R\"\n@qed\n      \nlemma ord_field_le_divide_switch3 [backward1]:\n  \"is_ord_field(R) \\<Longrightarrow> a \\<in>. R \\<Longrightarrow> c \\<in>. R \\<Longrightarrow> b >\\<^sub>R 0\\<^sub>R \\<Longrightarrow> d >\\<^sub>R 0\\<^sub>R \\<Longrightarrow>\n   a /\\<^sub>R b <\\<^sub>R c /\\<^sub>R d \\<Longrightarrow> a *\\<^sub>R d <\\<^sub>R b *\\<^sub>R c\"\n@proof\n  @have \"a /\\<^sub>R b *\\<^sub>R (b *\\<^sub>R d) <\\<^sub>R c /\\<^sub>R d *\\<^sub>R (b *\\<^sub>R d)\" @have \"b *\\<^sub>R d >\\<^sub>R 0\\<^sub>R\"\n@qed\n\nlemma ord_field_le_divide_switch4 [backward1]:\n  \"is_ord_field(R) \\<Longrightarrow> a \\<in>. R \\<Longrightarrow> c \\<in>. R \\<Longrightarrow> b >\\<^sub>R 0\\<^sub>R \\<Longrightarrow> d >\\<^sub>R 0\\<^sub>R \\<Longrightarrow>\n   a *\\<^sub>R d <\\<^sub>R b *\\<^sub>R c \\<Longrightarrow> a /\\<^sub>R b <\\<^sub>R c /\\<^sub>R d\"\n@proof\n  @have \"a *\\<^sub>R d /\\<^sub>R (b *\\<^sub>R d) <\\<^sub>R b *\\<^sub>R c /\\<^sub>R (b *\\<^sub>R d)\" @have \"b *\\<^sub>R d >\\<^sub>R 0\\<^sub>R\"\n@qed\n\nlemma ord_field_of_rat_le [backward]:\n  \"is_ord_field(R) \\<Longrightarrow> r \\<le>\\<^sub>\\<rat> s \\<Longrightarrow> of_rat(R,r) \\<le>\\<^sub>R of_rat(R,s)\"\n@proof\n  @obtain \"a\\<in>.\\<int>\" b where \"b>\\<^sub>\\<int>0\\<^sub>\\<int>\" \"r = of_int(\\<rat>,a) /\\<^sub>\\<rat> of_int(\\<rat>,b)\"\n  @obtain \"c\\<in>.\\<int>\" d where \"d>\\<^sub>\\<int>0\\<^sub>\\<int>\" \"s = of_int(\\<rat>,c) /\\<^sub>\\<rat> of_int(\\<rat>,d)\"\n  @have \"of_int(\\<rat>,a) *\\<^sub>\\<rat> of_int(\\<rat>,d) \\<le>\\<^sub>\\<rat> of_int(\\<rat>,b) *\\<^sub>\\<rat> of_int(\\<rat>,c)\"\n  @have \"of_int(R,a) *\\<^sub>R of_int(R,d) \\<le>\\<^sub>R of_int(R,b) *\\<^sub>R of_int(R,c)\"\n@qed\n\nlemma ord_field_of_rat_less [backward]:\n  \"is_ord_field(R) \\<Longrightarrow> r <\\<^sub>\\<rat> s \\<Longrightarrow> of_rat(R,r) <\\<^sub>R of_rat(R,s)\"\n@proof\n  @obtain \"a\\<in>.\\<int>\" b where \"b>\\<^sub>\\<int>0\\<^sub>\\<int>\" \"r = of_int(\\<rat>,a) /\\<^sub>\\<rat> of_int(\\<rat>,b)\"\n  @obtain \"c\\<in>.\\<int>\" d where \"d>\\<^sub>\\<int>0\\<^sub>\\<int>\" \"s = of_int(\\<rat>,c) /\\<^sub>\\<rat> of_int(\\<rat>,d)\"\n  @have \"of_int(\\<rat>,a) *\\<^sub>\\<rat> of_int(\\<rat>,d) <\\<^sub>\\<rat> of_int(\\<rat>,b) *\\<^sub>\\<rat> of_int(\\<rat>,c)\"\n  @have \"of_int(R,a) *\\<^sub>R of_int(R,d) <\\<^sub>R of_int(R,b) *\\<^sub>R of_int(R,c)\"\n@qed\n\nlemma ord_field_of_rat_positive:\n  \"is_ord_field(R) \\<Longrightarrow> r >\\<^sub>\\<rat> \\<zero>\\<^sub>\\<rat> \\<Longrightarrow> of_rat(R,r) >\\<^sub>R \\<zero>\\<^sub>R\"\n@proof @have \"of_rat(R,r) >\\<^sub>R of_rat(R,0\\<^sub>\\<rat>)\" @qed\nsetup {* add_forward_prfstep_cond @{thm ord_field_of_rat_positive} [with_term \"of_rat(?R,?r)\"] *}\n\nsection \\<open>Rationals is an archimedean field\\<close>\n\nlemma int_has_of_nat_ge [forward]: \"is_archimedean(\\<int>)\"\n@proof\n  @have \"\\<forall>z\\<in>.\\<int>. \\<exists>n\\<in>nat. of_nat(\\<int>,n) \\<ge>\\<^sub>\\<int> z\" @with\n    @obtain \"a\\<in>.\\<nat>\" \"b\\<in>.\\<nat>\" where \"z = of_nat(\\<int>,a) -\\<^sub>\\<int> of_nat(\\<int>,b)\"\n    @have \"of_nat(\\<int>,a) \\<ge>\\<^sub>\\<int> z\"\n  @end\n@qed\n\nlemma is_archimedeanI_pos_of_int [forward]:\n  \"is_ord_ring(R) \\<Longrightarrow> \\<forall>x >\\<^sub>R 0\\<^sub>R. \\<exists>z\\<in>.\\<int>. of_int(R,z) \\<ge>\\<^sub>R x \\<Longrightarrow> is_archimedean(R)\"\n@proof\n  @have \"\\<forall>x >\\<^sub>R 0\\<^sub>R. \\<exists>n\\<in>nat. of_nat(R,n) \\<ge>\\<^sub>R x\" @with\n    @obtain \"z\\<in>.\\<int>\" where \"of_int(R,z) \\<ge>\\<^sub>R x\"\n    @obtain \"n\\<in>nat\" where \"of_nat(\\<int>,n) \\<ge>\\<^sub>\\<int> z\"\n    @have \"of_nat(R,n) = of_int(R,of_nat(\\<int>,n))\"\n  @end\n@qed\n\nlemma rat_is_archimedean [forward]: \"is_archimedean(\\<rat>)\"\n@proof\n  @have \"\\<forall>r >\\<^sub>\\<rat> 0\\<^sub>\\<rat>. \\<exists>z\\<in>.\\<int>. of_int(\\<rat>,z) \\<ge>\\<^sub>\\<rat> r\" @with\n    @obtain \"a\\<in>.\\<int>\" b where \"b>\\<^sub>\\<int>0\\<^sub>\\<int>\" \"r = of_int(\\<rat>,a) /\\<^sub>\\<rat> of_int(\\<rat>,b)\"\n    @have \"of_int(\\<rat>,b) \\<ge>\\<^sub>\\<rat> of_int(\\<rat>,1\\<^sub>\\<int>)\" @end\n@qed\n\nlemma is_archimedeanI_pos_of_rat [forward]:\n  \"is_ord_field(R) \\<Longrightarrow> \\<forall>x >\\<^sub>R 0\\<^sub>R. \\<exists>z\\<in>.\\<rat>. of_rat(R,z) \\<ge>\\<^sub>R x \\<Longrightarrow> is_archimedean(R)\"\n@proof\n  @have \"\\<forall>x >\\<^sub>R 0\\<^sub>R. \\<exists>n\\<in>nat. of_nat(R,n) \\<ge>\\<^sub>R x\" @with\n    @obtain \"r\\<in>.\\<rat>\" where \"of_rat(R,r) \\<ge>\\<^sub>R x\"\n    @obtain \"n\\<in>nat\" where \"of_nat(\\<rat>,n) \\<ge>\\<^sub>\\<rat> r\"\n    @have \"of_nat(R,n) = of_rat(R,of_nat(\\<rat>,n))\"\n    @have \"of_rat(R,of_nat(\\<rat>,n)) \\<ge>\\<^sub>R of_rat(R,r)\"\n  @end\n@qed\n\nsection \\<open>More properties of archimedean fields\\<close>\n  \nlemma is_archimedeanD_rat [backward]:\n  \"is_archimedean(R) \\<Longrightarrow> is_field(R) \\<Longrightarrow> x \\<in>. R \\<Longrightarrow> \\<exists>r\\<in>.\\<rat>. of_rat(R,r) >\\<^sub>R x\"\n@proof\n  @obtain \"n\\<in>nat\" where \"of_nat(R,n) >\\<^sub>R x\"\n  @have \"of_rat(R,of_nat(\\<rat>,n)) = of_nat(R,n)\"\n@qed\n\nlemma is_archimedeanD_rat_pos [backward]:\n  \"is_archimedean(R) \\<Longrightarrow> is_field(R) \\<Longrightarrow> x \\<in>. R \\<Longrightarrow> \\<exists>r>\\<^sub>\\<rat>\\<zero>\\<^sub>\\<rat>. of_rat(R,r) >\\<^sub>R x\"\n@proof\n  @obtain \"r\\<in>.\\<rat>\" where \"of_rat(R,r) >\\<^sub>R x\"\n  @obtain \"r'\\<in>.\\<rat>\" where \"r' >\\<^sub>\\<rat> \\<zero>\\<^sub>\\<rat>\" \"r' \\<ge>\\<^sub>\\<rat> r\"\n@qed\n\nlemma is_archimedeanD_rat_less [backward]:\n  \"is_archimedean(R) \\<Longrightarrow> is_field(R) \\<Longrightarrow> x >\\<^sub>R \\<zero>\\<^sub>R \\<Longrightarrow> \\<exists>r>\\<^sub>\\<rat>\\<zero>\\<^sub>\\<rat>. of_rat(R,r) <\\<^sub>R x\"\n@proof\n  @obtain r where \"r>\\<^sub>\\<rat>\\<zero>\\<^sub>\\<rat>\" \"of_rat(R,r) >\\<^sub>R inv(R,x)\"\n  @have \"of_rat(R,inv(\\<rat>,r)) <\\<^sub>R x\"\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/Rat.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8519528019683105, "lm_q2_score": 0.8221891370573388, "lm_q1q2_score": 0.700466339063907}}
{"text": "\\<^marker>\\<open>creator \"Kevin Kappelmann\"\\<close>\nsubsubsection \\<open>Transport Between Lists and Sets\\<close>\ntheory Transport_List_Sets\n  imports\n    Transport_PER\n    Transport_Syntax\n    \"HOL-Library.FSet\"\nbegin\n\nparagraph \\<open>Summary\\<close>\ntext \\<open>Introductory examples from the Transport paper. Transports between lists\nand (finite) sets.  Refer to the paper for more details.\\<close>\n\nparagraph \\<open>Introductory examples from paper\\<close>\n\ncontext\n  includes transport_syntax\nbegin\n\ntext \\<open>Left and right relations.\\<close>\n\ndefinition \"L1 xs xs' \\<equiv> fset_of_list xs = fset_of_list xs'\"\nabbreviation (input) \"(Rfin :: 'a fset \\<Rightarrow> _) \\<equiv> (=)\"\ndefinition \"L2 xs xs' \\<equiv> set xs = set xs'\"\nabbreviation (input) \"(R :: 'a set \\<Rightarrow> _) \\<equiv> (=\\<^bsub>finite :: 'a set \\<Rightarrow> bool\\<^esub>)\"\n\ncontext\n  includes galois_rel_syntax\nbegin\n\ninterpretation t : transport L2 R l r for L2 R l r .\n\ntext \\<open>Proofs of equivalences.\\<close>\n\nlemma list_fset_PER [per_intro]:\n  \"(L1 \\<equiv>\\<^bsub>PER\\<^esub> Rfin) fset_of_list sorted_list_of_fset\"\n  unfolding L1_def by fastforce\n\nlemma list_set_PER [per_intro]: \"(L2 \\<equiv>\\<^bsub>PER\\<^esub> R) set sorted_list_of_set\"\n  unfolding L2_def by fastforce\n\ntext \\<open>We can rewrite the Galois relators in the following theorems to\nthe relator of the paper.\\<close>\n\ndefinition \"LFS xs s \\<equiv> fset_of_list xs = s\"\ndefinition \"LS xs s \\<equiv> set xs = s\"\n\nlemma list_fset_Galois_eq: \"(\\<^bsub>L1\\<^esub>\\<lessapprox>\\<^bsub>Rfin sorted_list_of_fset\\<^esub>) \\<equiv> LFS\"\n  unfolding LFS_def L1_def by (intro eq_reflection ext) (auto)\nlemma list_fset_Galois_eq_symm: \"(\\<^bsub>Rfin\\<^esub>\\<lessapprox>\\<^bsub>L1 fset_of_list\\<^esub>) \\<equiv> LFS\\<inverse>\"\n  unfolding LFS_def L1_def by (intro eq_reflection ext) (auto)\nlemma list_set_Galois_eq: \"(\\<^bsub>L2\\<^esub>\\<lessapprox>\\<^bsub>R sorted_list_of_set\\<^esub>) \\<equiv> LS\"\n  unfolding LS_def L2_def by (intro eq_reflection ext) (auto)\n\ndeclare list_fset_Galois_eq[transport_relator_rewrite, unif_hint]\n  list_fset_Galois_eq_symm[transport_relator_rewrite, unif_hint]\n  list_set_Galois_eq[transport_relator_rewrite, unif_hint]\n\nend\n\n(*unification hint*)\nlemma L1_eq_L2 [unif_hint]: \"L1 \\<equiv> L2\"\n  unfolding L1_def L2_def\n  by (intro eq_reflection ext) (auto simp: fset_of_list_elem)\n\ndefinition \"max_list xs \\<equiv> foldr max xs (0 :: nat)\"\n\ntext \\<open>Proof of parametricity for @{term max_list}.\\<close>\n\nlemma max_max_list_removeAll_eq_maxlist:\n  assumes \"x \\<in> set xs\"\n  shows \"max x (max_list (removeAll x xs)) = max_list xs\"\n  unfolding max_list_def using assms by (induction xs)\n  (simp_all, (metis max.left_idem removeAll_id max.left_commute)+)\n\nlemma max_list_parametric [transport_parametric]:\n  \"(L2 \\<Rrightarrow> (=)) max_list max_list\"\nproof (intro Dep_Fun_Rel_relI)\n  fix xs xs' :: \"nat list\" assume \"L2 xs xs'\"\n  then have \"finite (set xs)\" \"set xs = set xs'\" unfolding L2_def by auto\n  then show \"max_list xs = max_list xs'\"\n  proof (induction \"set xs\"  arbitrary: xs xs' rule: finite_induct)\n    case (insert x F)\n    then have \"F = set (removeAll x xs)\" by auto\n    moreover from insert have \"... = set (removeAll x xs')\" by auto\n    ultimately have \"max_list (removeAll x xs) = max_list (removeAll x xs')\"\n      (is \"?lhs = ?rhs\") using insert by blast\n    then have \"max x ?lhs = max x ?rhs\" by simp\n    then show ?case\n      using insert max_max_list_removeAll_eq_maxlist insertI1 by metis\n  qed auto\nqed\n\nlemma max_list_parametricfin [transport_parametric]:\n  \"(L1 \\<Rrightarrow> (=)) max_list max_list\"\n  using max_list_parametric by (simp only: L1_eq_L2)\n\ntext \\<open>Transport from lists to finite sets.\\<close>\n\ntransport_term max_fset :: \"nat fset \\<Rightarrow> nat\" where x = max_list\n  by transport_term_prover\n\ntext \\<open>Use @{command print_theorems} to show all theorems.\\<close>\n(*print_theorems*)\n\nlemma \"(LFS \\<Rrightarrow> (=)) max_list max_fset\" by (fact max_fset_related')\n\nlemma [transport_parametric]: \"(Rfin \\<Rrightarrow> (=)) max_fset max_fset\"\n  by simp\n\ntext \\<open>Transport from lists to sets.\\<close>\n\ntransport_term max_set :: \"nat set \\<Rightarrow> nat\" where x = max_list\n  by transport_term_prover\n\nlemma \"(LS \\<Rrightarrow> (=)) max_list max_set\" by (fact max_set_related')\n\ntext \\<open>The registration of symmetric equivalence rules is not done by default as\nof now, but that would not be a problem in principle.\\<close>\n\nlemma list_fset_PER_sym [per_intro]:\n  \"(Rfin \\<equiv>\\<^bsub>PER\\<^esub> L1) sorted_list_of_fset fset_of_list\"\n  by (subst transport.partial_equivalence_rel_equivalence_right_left_iff_partial_equivalence_rel_equivalence_left_right)\n  (fact list_fset_PER)\n\ntext \\<open>Transport from finite sets to lists.\\<close>\n\ntransport_term max_list' :: \"nat list \\<Rightarrow> nat\" where x = max_fset\n  by transport_term_prover\n\nlemma \"(LFS\\<inverse> \\<Rrightarrow> (=)) max_fset max_list'\" by (fact max_list'_related')\n\n\ntext \\<open>Transporting higher-order functions.\\<close>\n\nlemma map_parametric [transport_parametric]:\n  \"(((=) \\<Rrightarrow> (=)) \\<Rrightarrow> L2 \\<Rrightarrow> L2) map map\"\n  unfolding L2_def\n  by (intro Dep_Fun_Rel_relI) simp\n\n(*sorted_list_of_fset requires a linorder*)\n(*in theory, we could use a different transport function to avoid that constraint*)\ntransport_term map_set :: \"('a :: linorder \\<Rightarrow> 'b) \\<Rightarrow> 'a set \\<Rightarrow> ('b :: linorder) set\"\n  where x = \"map :: ('a :: linorder \\<Rightarrow> 'b) \\<Rightarrow> 'a list \\<Rightarrow> ('b :: linorder) list\"\n  by transport_term_prover\n\nlemma \"(((=) \\<Rrightarrow> (=)) \\<Rrightarrow> LS \\<Rrightarrow> LS) map map_set\" by (fact map_set_related')\n\n\nlemma filter_parametric [transport_parametric]:\n  \"(((=) \\<Rrightarrow> (\\<longleftrightarrow>)) \\<Rrightarrow> L2 \\<Rrightarrow> L2) filter filter\"\n  unfolding L2_def by (intro Dep_Fun_Rel_relI) simp\n\ntransport_term filter_set :: \"('a :: linorder \\<Rightarrow> bool) \\<Rightarrow> 'a set \\<Rightarrow> 'a set\"\n  where x = \"filter :: ('a :: linorder \\<Rightarrow> bool) \\<Rightarrow> 'a list \\<Rightarrow> 'a list\"\n  by transport_term_prover\n\nlemma \"(((=) \\<Rrightarrow> (=)) \\<Rrightarrow> LS \\<Rrightarrow> LS) filter filter_set\"\n  by (rule filter_set_related')\n\nlemma append_parametric [transport_parametric]:\n  \"(L2 \\<Rrightarrow> L2 \\<Rrightarrow> L2) append append\"\n  unfolding L2_def by (intro Dep_Fun_Rel_relI) simp\n\ntransport_term append_set :: \"('a :: linorder) set \\<Rightarrow> 'a set \\<Rightarrow> 'a set\"\n  where x = \"append :: ('a :: linorder) list \\<Rightarrow> 'a list \\<Rightarrow> 'a list\"\n  by transport_term_prover\n\nlemma \"(LS \\<Rrightarrow> LS \\<Rrightarrow> LS) append append_set\"\n  by (rule append_set_related')\n\ntext \\<open>The prototype also provides a simplified definition.\\<close>\nlemma \"append_set s s' \\<equiv> set (sorted_list_of_set s) \\<union> set (sorted_list_of_set s')\"\n  by (fact append_set_app_eq)\n\nlemma \"finite s \\<Longrightarrow> finite s' \\<Longrightarrow> append_set s s' = s \\<union> s'\"\n  by (auto simp: append_set_app_eq)\n\nend\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/Transport/Examples/Transport_List_Sets.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8221891305219505, "lm_q2_score": 0.8519528076067261, "lm_q1q2_score": 0.7004663381319087}}
{"text": "theory NatsBug\nimports Main\n        \"$HIPSTER_HOME/IsaHipster\"\nbegin\n\ndatatype Nat = Z | S Nat\n\nfun leq :: \"Nat \\<Rightarrow> Nat \\<Rightarrow> bool\" where\n  \"leq Z _ = True\"\n| \"leq _ Z = False\"\n| \"leq (S x) (S y) = leq x y\"\n\nfun eqN :: \"Nat \\<Rightarrow> Nat \\<Rightarrow> bool\" where (* own definition for equality *)\n  \"eqN Z Z = True\"\n| \"eqN (S n) (S m) = eqN n m\"\n| \"eqN _     _     = False\"\n\n(* less or equal to Z *)\nfun lez :: \"Nat \\<Rightarrow> bool\" where          (* - as a function definition relying on Isabelle's equality *)\n  \"lez x = (x = Z)\"\n\nfun lezP :: \"Nat \\<Rightarrow> bool\" where         (* - as a function definition via pattern matching *)\n  \"lezP Z = True\"\n| \"lezP _ = False\"\n\nfun lezzP :: \"Nat \\<Rightarrow> bool\" where        (* - as a function definition via our own equality *)\n  \"lezzP x = eqN x Z\"\n\ndefinition leZ :: \"Nat \\<Rightarrow> bool\" where   (* - as a constant definition relying on Isabelle's equality *)\n  \"leZ x \\<equiv> (x = Z)\"\n\ndefinition leZZ :: \"Nat \\<Rightarrow> bool\" where  (* - as a constant definition relying on own equality *)\n  \"leZZ x \\<equiv> eqN x Z\"\n\n\n(* hipster_cond lezzP leq *) (* skipping of conditions in output solved *)\n(* hipster_cond lezP leq *)  (* skipping of conditions in output solved *)\n\n(* hipster lezzP *) (* nothing weird, ok *)\n(* hipster lezP *)  (* everything trivial, ok*)\n\n\n(* FIXME: 1. Isabelle's equality = (gets translated as a separate predicate Haskell\n             function equal_<Type> which will be missing in the original theory) *)\n(* hipster lez *)  (* equations only with lez are trivial, aren't returned *)\nlemma unknown [thy_expl]: \"equal_Nat x y = equal_Nat y x\" (* free variable equal_Nat instead of equality = *)\noops\n\n\n(** QUICK REFERENCE: Haskell transaltions **)\n(*  equal_Nat :: Nat -> Nat -> Bool\n    equal_Nat Z (S nat) = False\n    equal_Nat (S nat) Z = False\n    equal_Nat (S nata) (S nat) = equal_Nat nata nat\n    equal_Nat Z Z = True\n    \n    leZ :: Nat -> Bool\n    leZ x = equal_Nat x Z\n    \n    lez :: Nat -> Bool\n    lez x = equal_Nat x Z *)\n\n(*  eqN :: Nat -> Nat -> Bool\n    eqN Z Z = True\n    eqN (S n) (S m) = eqN n m\n    eqN (S v) Z = False\n    eqN Z (S v) = False\n    \n    leZZ :: Nat -> Bool\n    leZZ x = eqN x Z\n    \n    lezzP :: Nat -> Bool\n    lezzP x = eqN x Z\n    \n    lezP :: Nat -> Bool\n    lezP Z = True\n    lezP (S v) = False *)\n\n(*  leq :: Nat -> Nat -> Bool\n    leq Z uu = True\n    leq (S v) Z = False\n    leq (S x) (S y) = leq x y *)\n\n\n(*  Notes to self  *)\n(* cond with: lezP leq*)\nlemma dub00 [thy_expl]: \"lezP y \\<and> lezP x \\<Longrightarrow> x = y\" (* Hipster fails for some reason: no double induction? *)\napply(induction y, induction x)\nby (simp_all)\n\n(* Constant definition issues *)\n(* leZ *)\nlemma dub01 [thy_expl]: \"leZ (S Z) = False\" (* Hipster fails *)\n(* Hipster does not get leZ_def, but it also fails when provided manually with it:\n    by (hipster_induct_simp_metis NatsBug.leZ_def) *)\nby (simp add: leZ_def)\n\n(* leZZ *)\nlemma dub02 [thy_expl]: \"eqN Z x = leZZ x\" (* Hipster fails *)\napply (induction x)\nby (simp_all add: leZZ_def)\n\n\nend\n\n", "meta": {"author": "moajohansson", "repo": "IsaHipster", "sha": "91f6ea3f1166a9de547722ece6445fe843ad89b4", "save_path": "github-repos/isabelle/moajohansson-IsaHipster", "path": "github-repos/isabelle/moajohansson-IsaHipster/IsaHipster-91f6ea3f1166a9de547722ece6445fe843ad89b4/Examples/NatsBug.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527982093666, "lm_q2_score": 0.8221891370573388, "lm_q1q2_score": 0.7004663359733442}}
{"text": "(*\nAuthor:  Christian Sternagel <c.sternagel@gmail.com>\nAuthor:  Ren\u00e9 Thiemann <rene.thiemann@uibk.ac.at>\nLicense: LGPL\n*)\nsubsection \\<open>Results on Bijections\\<close>\n\ntheory Fun_More imports Main begin\n\nlemma finite_card_eq_imp_bij_betw:\n  assumes \"finite A\"\n    and \"card (f ` A) = card A\"\n  shows \"bij_betw f A (f ` A)\"\n  using \\<open>card (f ` A) = card A\\<close>\n  unfolding inj_on_iff_eq_card [OF \\<open>finite A\\<close>, symmetric]\n  by (rule inj_on_imp_bij_betw)\n\ntext \\<open>Every bijective function between two subsets of a set can be turned\ninto a compatible renaming (with finite domain) on the full set.\\<close>\nlemma bij_betw_extend:\n  assumes *: \"bij_betw f A B\"\n    and \"A \\<subseteq> V\"\n    and \"B \\<subseteq> V\"\n    and \"finite A\"\n  shows \"\\<exists>g. finite {x. g x \\<noteq> x} \\<and>\n    (\\<forall>x\\<in>UNIV - (A \\<union> B). g x = x) \\<and>\n    (\\<forall>x\\<in>A. g x = f x) \\<and>\n    bij_betw g V V\"\nproof -\n  have \"finite B\" using assms by (metis bij_betw_finite)\n  have [simp]: \"card A = card B\" by (metis * bij_betw_same_card)\n  have \"card (A - B) = card (B - A)\"\n  proof -\n    have \"card (A - B) = card A - card (A \\<inter> B)\"\n      by (metis \\<open>finite A\\<close> card_Diff_subset_Int finite_Int)\n    moreover have \"card (B - A) = card B - card (A \\<inter> B)\"\n      by (metis \\<open>finite A\\<close> card_Diff_subset_Int finite_Int inf_commute)\n    ultimately show ?thesis by simp\n  qed\n  then obtain g where **: \"bij_betw g (B - A) (A - B)\"\n    by (metis \\<open>finite A\\<close> \\<open>finite B\\<close> bij_betw_iff_card finite_Diff)\n  define h where \"h = (\\<lambda>x. if x \\<in> A then f x else if x \\<in> B - A then g x else x)\"\n  have \"bij_betw h A B\"\n    by (metis (full_types) * bij_betw_cong h_def)\n  moreover have \"bij_betw h (V - (A \\<union> B)) (V - (A \\<union> B))\"\n    by (auto simp: bij_betw_def h_def inj_on_def)\n  moreover have \"B \\<inter> (V - (A \\<union> B)) = {}\" by blast\n  ultimately have \"bij_betw h (A \\<union> (V - (A \\<union> B))) (B \\<union> (V - (A \\<union> B)))\"\n    by (rule bij_betw_combine)\n  moreover have \"A \\<union> (V - (A \\<union> B)) = V - (B - A)\"\n    and \"B \\<union> (V - (A \\<union> B)) = V - (A - B)\"\n    using \\<open>A \\<subseteq> V\\<close> and \\<open>B \\<subseteq> V\\<close> by blast+\n  ultimately have \"bij_betw h (V - (B - A)) (V - (A - B))\" by simp\n  moreover have \"bij_betw h (B - A) (A - B)\"\n    using ** by (auto simp: bij_betw_def h_def inj_on_def)\n  moreover have \"(V - (A - B)) \\<inter> (A - B) = {}\" by blast\n  ultimately have \"bij_betw h ((V - (B - A)) \\<union> (B - A)) ((V - (A - B)) \\<union> (A - B))\"\n    by (rule bij_betw_combine)\n  moreover have \"(V - (B - A)) \\<union> (B - A) = V\"\n    and \"(V - (A - B)) \\<union> (A - B) = V\"\n    using \\<open>A \\<subseteq> V\\<close> and \\<open>B \\<subseteq> V\\<close> by auto\n  ultimately have \"bij_betw h V V\" by simp\n  moreover have \"\\<forall>x\\<in>A. h x = f x\" by (auto simp: h_def)\n  moreover have \"finite {x. h x \\<noteq> x}\"\n  proof -\n    have \"finite (A \\<union> (B - A))\" using \\<open>finite A\\<close> and \\<open>finite B\\<close> by auto\n    moreover have \"{x. h x \\<noteq> x} \\<subseteq> (A \\<union> (B - A))\" by (auto simp: h_def)\n    ultimately show ?thesis by (metis finite_subset)\n  qed\n  moreover have \"\\<forall>x\\<in>UNIV - (A \\<union> B). h x = x\" by (simp add: h_def)\n  ultimately show ?thesis by blast\nqed\n\n\nsubsection \\<open>Merging Functions\\<close>\n(* Copied and canonized from IsaFoR's Term theory and Polynomial Factorization in the AFP. *)\ndefinition fun_merge :: \"('a \\<Rightarrow> 'b)list \\<Rightarrow> 'a set list \\<Rightarrow> 'a \\<Rightarrow> 'b\"\n  where\n    \"fun_merge fs as a = (fs ! (LEAST i. i < length as \\<and> a \\<in> as ! i)) a\"\n\nlemma fun_merge_eq_nth:\n  assumes i: \"i < length as\"\n    and a: \"a \\<in> as ! i\"\n    and ident: \"\\<And> i j a. i < length as \\<Longrightarrow> j < length as \\<Longrightarrow> a \\<in> as ! i \\<Longrightarrow> a \\<in> as ! j \\<Longrightarrow> (fs ! i) a = (fs ! j) a\"\n  shows \"fun_merge fs as a = (fs ! i) a\"\nproof -\n  let ?p = \"\\<lambda> i. i < length as \\<and> a \\<in> as ! i\"\n  let ?l = \"LEAST i. ?p i\"\n  have p: \"?p ?l\"\n    by (rule LeastI, insert i a, auto)\n  show ?thesis unfolding fun_merge_def\n    by (rule ident[OF _ i _ a], insert p, auto)\nqed\n\nlemma fun_merge_part:\n  assumes \"\\<forall>i<length as.\\<forall>j<length as. i \\<noteq> j \\<longrightarrow> as ! i \\<inter> as ! j = {}\"\n    and \"i < length as\"\n    and \"a \\<in> as ! i\"\n  shows \"fun_merge fs as a = (fs ! i) a\"\nproof(rule fun_merge_eq_nth [OF assms(2, 3)])\n  fix i j a\n  assume \"i < length as\" and \"j < length as\" and \"a \\<in> as ! i\" and \"a \\<in> as ! j\"\n  then have \"i = j\" using assms by (cases \"i = j\") auto\n  then show \"(fs ! i) a = (fs ! j) a\" by simp\nqed\n\nlemma fun_merge:\n  assumes part: \"\\<forall>i<length Xs.\\<forall>j<length Xs. i \\<noteq> j \\<longrightarrow> Xs ! i \\<inter> Xs ! j = {}\"\n  shows \"\\<exists>\\<sigma>. \\<forall>i<length Xs. \\<forall>x\\<in> Xs ! i. \\<sigma> x = \\<tau> i x\"\nproof -\n  let ?\\<tau> = \"map \\<tau> [0 ..< length Xs]\"\n  let ?\\<sigma> = \"fun_merge ?\\<tau> Xs\"\n  show ?thesis\n    by (rule exI[of _ ?\\<sigma>], intro allI impI ballI,\n      insert fun_merge_part[OF part, of _ _ ?\\<tau>], 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/First_Order_Terms/Fun_More.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8519528019683105, "lm_q2_score": 0.8221891327004132, "lm_q1q2_score": 0.7004663353520121}}
{"text": "(*  Title:      HOL/Library/Function_Algebras.thy\n    Author:     Jeremy Avigad and Kevin Donnelly; Florian Haftmann, TUM\n*)\n\nsection \\<open>Pointwise instantiation of functions to algebra type classes\\<close>\n\ntheory Function_Algebras\nimports MainRLT\nbegin\n\ntext \\<open>Pointwise operations\\<close>\n\ninstantiation \"fun\" :: (type, plus) plus\nbegin\n\ndefinition \"f + g = (\\<lambda>x. f x + g x)\"\ninstance ..\n\nend\n\nlemma plus_fun_apply [simp]:\n  \"(f + g) x = f x + g x\"\n  by (simp add: plus_fun_def)\n\ninstantiation \"fun\" :: (type, zero) zero\nbegin\n\ndefinition \"0 = (\\<lambda>x. 0)\"\ninstance ..\n\nend\n\nlemma zero_fun_apply [simp]:\n  \"0 x = 0\"\n  by (simp add: zero_fun_def)\n\ninstantiation \"fun\" :: (type, times) times\nbegin\n\ndefinition \"f * g = (\\<lambda>x. f x * g x)\"\ninstance ..\n\nend\n\nlemma times_fun_apply [simp]:\n  \"(f * g) x = f x * g x\"\n  by (simp add: times_fun_def)\n\ninstantiation \"fun\" :: (type, one) one\nbegin\n\ndefinition \"1 = (\\<lambda>x. 1)\"\ninstance ..\n\nend\n\nlemma one_fun_apply [simp]:\n  \"1 x = 1\"\n  by (simp add: one_fun_def)\n\n\ntext \\<open>Additive structures\\<close>\n\ninstance \"fun\" :: (type, semigroup_add) semigroup_add\n  by standard (simp add: fun_eq_iff add.assoc)\n\ninstance \"fun\" :: (type, cancel_semigroup_add) cancel_semigroup_add\n  by standard (simp_all add: fun_eq_iff)\n\ninstance \"fun\" :: (type, ab_semigroup_add) ab_semigroup_add\n  by standard (simp add: fun_eq_iff add.commute)\n\ninstance \"fun\" :: (type, cancel_ab_semigroup_add) cancel_ab_semigroup_add\n  by standard (simp_all add: fun_eq_iff diff_diff_eq)\n\ninstance \"fun\" :: (type, monoid_add) monoid_add\n  by standard (simp_all add: fun_eq_iff)\n\ninstance \"fun\" :: (type, comm_monoid_add) comm_monoid_add\n  by standard simp\n\ninstance \"fun\" :: (type, cancel_comm_monoid_add) cancel_comm_monoid_add ..\n\ninstance \"fun\" :: (type, group_add) group_add\n  by standard (simp_all add: fun_eq_iff)\n\ninstance \"fun\" :: (type, ab_group_add) ab_group_add\n  by standard simp_all\n\n\ntext \\<open>Multiplicative structures\\<close>\n\ninstance \"fun\" :: (type, semigroup_mult) semigroup_mult\n  by standard (simp add: fun_eq_iff mult.assoc)\n\ninstance \"fun\" :: (type, ab_semigroup_mult) ab_semigroup_mult\n  by standard (simp add: fun_eq_iff mult.commute)\n\ninstance \"fun\" :: (type, monoid_mult) monoid_mult\n  by standard (simp_all add: fun_eq_iff)\n\ninstance \"fun\" :: (type, comm_monoid_mult) comm_monoid_mult\n  by standard simp\n\n\ntext \\<open>Misc\\<close>\n\ninstance \"fun\" :: (type, \"Rings.dvd\") \"Rings.dvd\" ..\n\ninstance \"fun\" :: (type, mult_zero) mult_zero\n  by standard (simp_all add: fun_eq_iff)\n\ninstance \"fun\" :: (type, zero_neq_one) zero_neq_one\n  by standard (simp add: fun_eq_iff)\n\n\ntext \\<open>Ring structures\\<close>\n\ninstance \"fun\" :: (type, semiring) semiring\n  by standard (simp_all add: fun_eq_iff algebra_simps)\n\ninstance \"fun\" :: (type, comm_semiring) comm_semiring\n  by standard (simp add: fun_eq_iff  algebra_simps)\n\ninstance \"fun\" :: (type, semiring_0) semiring_0 ..\n\ninstance \"fun\" :: (type, comm_semiring_0) comm_semiring_0 ..\n\ninstance \"fun\" :: (type, semiring_0_cancel) semiring_0_cancel ..\n\ninstance \"fun\" :: (type, comm_semiring_0_cancel) comm_semiring_0_cancel ..\n\ninstance \"fun\" :: (type, semiring_1) semiring_1 ..\n\nlemma numeral_fun: \\<^marker>\\<open>contributor \\<open>Akihisa Yamada\\<close>\\<close>\n  \\<open>numeral n = (\\<lambda>x::'a. numeral n)\\<close>\n  by (induction n) (simp_all only: numeral.simps plus_fun_def, simp_all)\n\nlemma numeral_fun_apply [simp]: \\<^marker>\\<open>contributor \\<open>Akihisa Yamada\\<close>\\<close>\n  \\<open>numeral n x = numeral n\\<close>\n  by (simp add: numeral_fun)\n\nlemma of_nat_fun: \"of_nat n = (\\<lambda>x::'a. of_nat n)\"\nproof -\n  have comp: \"comp = (\\<lambda>f g x. f (g x))\"\n    by (rule ext)+ simp\n  have plus_fun: \"plus = (\\<lambda>f g x. f x + g x)\"\n    by (rule ext, rule ext) (fact plus_fun_def)\n  have \"of_nat n = (comp (plus (1::'b)) ^^ n) (\\<lambda>x::'a. 0)\"\n    by (simp add: of_nat_def plus_fun zero_fun_def one_fun_def comp)\n  also have \"... = comp ((plus 1) ^^ n) (\\<lambda>x::'a. 0)\"\n    by (simp only: comp_funpow)\n  finally show ?thesis by (simp add: of_nat_def comp)\nqed\n\nlemma of_nat_fun_apply [simp]:\n  \"of_nat n x = of_nat n\"\n  by (simp add: of_nat_fun)\n\ninstance \"fun\" :: (type, comm_semiring_1) comm_semiring_1 ..\n\ninstance \"fun\" :: (type, semiring_1_cancel) semiring_1_cancel ..\n\ninstance \"fun\" :: (type, comm_semiring_1_cancel) comm_semiring_1_cancel\n  by standard (auto simp add: times_fun_def algebra_simps)\n\ninstance \"fun\" :: (type, semiring_char_0) semiring_char_0\nproof\n  from inj_of_nat have \"inj (\\<lambda>n (x::'a). of_nat n :: 'b)\"\n    by (rule inj_fun)\n  then have \"inj (\\<lambda>n. of_nat n :: 'a \\<Rightarrow> 'b)\"\n    by (simp add: of_nat_fun)\n  then show \"inj (of_nat :: nat \\<Rightarrow> 'a \\<Rightarrow> 'b)\" .\nqed\n\ninstance \"fun\" :: (type, ring) ring ..\n\ninstance \"fun\" :: (type, comm_ring) comm_ring ..\n\ninstance \"fun\" :: (type, ring_1) ring_1 ..\n\ninstance \"fun\" :: (type, comm_ring_1) comm_ring_1 ..\n\ninstance \"fun\" :: (type, ring_char_0) ring_char_0 ..\n\n\ntext \\<open>Ordered structures\\<close>\n\ninstance \"fun\" :: (type, ordered_ab_semigroup_add) ordered_ab_semigroup_add\n  by standard (auto simp add: le_fun_def intro: add_left_mono)\n\ninstance \"fun\" :: (type, ordered_cancel_ab_semigroup_add) ordered_cancel_ab_semigroup_add ..\n\ninstance \"fun\" :: (type, ordered_ab_semigroup_add_imp_le) ordered_ab_semigroup_add_imp_le\n  by standard (simp add: le_fun_def)\n\ninstance \"fun\" :: (type, ordered_comm_monoid_add) ordered_comm_monoid_add ..\n\ninstance \"fun\" :: (type, ordered_cancel_comm_monoid_add) ordered_cancel_comm_monoid_add ..\n\ninstance \"fun\" :: (type, ordered_ab_group_add) ordered_ab_group_add ..\n\ninstance \"fun\" :: (type, ordered_semiring) ordered_semiring\n  by standard (auto simp add: le_fun_def intro: mult_left_mono mult_right_mono)\n\ninstance \"fun\" :: (type, dioid) dioid\nproof standard\n  fix a b :: \"'a \\<Rightarrow> 'b\"\n  show \"a \\<le> b \\<longleftrightarrow> (\\<exists>c. b = a + c)\"\n    unfolding le_fun_def plus_fun_def fun_eq_iff choice_iff[symmetric, of \"\\<lambda>x c. b x = a x + c\"]\n    by (intro arg_cong[where f=All] ext canonically_ordered_monoid_add_class.le_iff_add)\nqed\n\ninstance \"fun\" :: (type, ordered_comm_semiring) ordered_comm_semiring\n  by standard (fact mult_left_mono)\n\ninstance \"fun\" :: (type, ordered_cancel_semiring) ordered_cancel_semiring ..\n\ninstance \"fun\" :: (type, ordered_cancel_comm_semiring) ordered_cancel_comm_semiring ..\n\ninstance \"fun\" :: (type, ordered_ring) ordered_ring ..\n\ninstance \"fun\" :: (type, ordered_comm_ring) ordered_comm_ring ..\n\n\nlemmas func_plus = plus_fun_def\nlemmas func_zero = zero_fun_def\nlemmas func_times = times_fun_def\nlemmas func_one = one_fun_def\n\nend\n\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/Function_Algebras.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.851952809486198, "lm_q2_score": 0.822189123986562, "lm_q1q2_score": 0.7004663341093474}}
{"text": "theory Fibonacci\n  imports Syntax\nbegin\n\nno_notation Set.image (infixr \"`\" 90)\n  and comp_op (\"n_\" [90] 91)\n\n(* Some numbers written in Suc form *)\nlemma numeral_4 [simp]: \"4 = Suc (Suc (Suc (Suc 0)))\"\n  by arith\n\nlemma numeral_6 [simp]: \"6 = Suc (Suc (Suc (Suc (Suc (Suc 0)))))\"\n  by arith\n\nlemma numeral_8 [simp]: \"8 = Suc (Suc (Suc (Suc (Suc (Suc (Suc (Suc 0)))))))\"\n  by arith\n\n(* Definition of Fibonacci starting by 1 and 2: [1 2 3 5 8 13 ...] *)\nfun fib :: \"nat => nat\" where\n  \"fib 0 = 1\"\n| \"fib (Suc 0) = 2\"\n| \"fib (Suc (Suc x)) = fib x + fib (Suc x)\"\n\n\n\n(* Calculate the sum of even fibonnaci number smaller than m and maximum index n *)\nfun sum_efib :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\" where\n  \"sum_efib m 0 = 0\"\n| \"sum_efib m (Suc n) = sum_efib m n + (if (fib n) mod 2 \\<noteq> 0 \\<or> fib n > m then 0 else fib n)\"\n\n(* Predicate that indicates whether the sum is the sum of even fibonnaci numbers smaller than m *)\ndefinition is_sum_efib :: \"nat \\<Rightarrow> nat \\<Rightarrow> bool\" where\n  \"is_sum_efib sum m \\<equiv> \\<exists>n. sum = sum_efib m n \\<and> fib n > m\"\n\n(* List of even fibonacci number: [2, 8, 34, ...] *)\nfun efib :: \"nat \\<Rightarrow> nat\" where\n  \"efib 0 = 2\"\n| \"efib (Suc 0) = 8\"\n| \"efib (Suc (Suc n)) = 4*efib (Suc n) + efib n\"\n\n(* Some lemmas about Fibonacci numbers *)\nlemma fib_parity1: \"(fib k) mod 2 = 0 \\<Longrightarrow> (fib (Suc k)) mod 2 = Suc 0\"\n  apply (induct k, auto)\n  by (metis One_nat_def mod_2_not_eq_zero_eq_one_nat)\n\nlemma fib_parity2: \"(fib k) mod 2 = 0 \\<Longrightarrow> (fib (Suc (Suc k))) mod 2 = Suc 0\"\n  apply (induct k, auto)\n  by presburger\n\nlemma fib_parity3: \"(fib n) mod 2 = 0 \\<longleftrightarrow> n mod 3 = 1\"\n  apply (induct n rule: fib.induct, simp_all, default)\n  apply (subgoal_tac \"fib x mod 2 = 0 \\<or> fib x mod 2 = Suc 0\")\n  apply (erule disjE)\n  apply (subgoal_tac \"fib (Suc (Suc x)) mod 2 = Suc 0\")\n  apply simp\n  apply (metis fib_parity2)\n  apply (subgoal_tac \"x mod 3 = 0 \\<or> x mod 3 = Suc (Suc 0)\")\n  apply (erule disjE)\n  apply (metis fib.simps(3) fib_parity1 mod_Suc numeral_plus_numeral one_is_add semiring_norm(3) zero_neq_numeral)\n  apply (metis (hide_lams, no_types) Suc_numeral add_One_commute mod_2_not_eq_zero_eq_one_nat mod_Suc numeral_One numeral_plus_numeral one_is_add semiring_norm(3) zero_neq_numeral)\n  apply force\n  apply force\n  apply (subgoal_tac \"x mod 3 = 0 \\<or> x mod 3 = 1 \\<or> x mod 3 = 2\")\n  apply (erule disjE)\n  apply (subgoal_tac \"fib x mod 2 = Suc 0 \\<and> fib (Suc x) mod 2 = 0\")\n  apply (metis mod_Suc n_not_Suc_n)\n  apply (metis mod_Suc n_not_Suc_n)\n  apply (erule disjE)\n  apply (subgoal_tac \"fib x mod 2 = 0 \\<and> fib (Suc x) mod 2 = Suc 0\")\n  apply (metis Suc_eq_plus1_left Suc_numeral add_2_eq_Suc' mod_add_left_eq mod_self n_not_Suc_n semiring_norm(5))\n  apply (metis One_nat_def fib_parity1)\n  apply (subgoal_tac \"fib x mod 2 = Suc 0 \\<and> fib (Suc x) mod 2 = Suc 0\")\n  apply (simp add: mod_add_eq)\n  apply (metis One_nat_def Suc_1 mod_Suc_eq_Suc_mod mod_mod_trivial n_not_Suc_n not_mod_2_eq_1_eq_0)\n  by force\n\nlemma efib_correct: \"efib n = fib (3*n + 1)\"\n  apply (induct n rule: fib.induct)\n  by simp_all\n\nlemma efib_mod_2_eq_0: \"(efib n) mod 2 = 0\"\n  apply (induct n rule: fib.induct)\n  apply force\n  apply force\nusing efib.simps(3) by presburger\n\nlemma fib_6_n: \"fib (6 + n) = 4*fib (n + 3) + fib n\"\n  by (unfold Num.numeral_3_eq_3 numeral_6) simp\n\nlemma sum_efib_fib: \"\\<lbrakk>(fib k) mod 2 = 0; fib k \\<le> m\\<rbrakk> \\<Longrightarrow> sum_efib m (k + 3) = sum_efib m k + fib k\"\nproof -\n  assume assms: \"fib k mod 2 = 0\" \"fib k \\<le> m\"\n  hence \"fib (Suc k) mod 2 = Suc 0\"\n    by (metis fib_parity1)\n  hence \"fib (Suc (Suc k)) mod 2 = Suc 0\"\n    by (simp, metis assms(1) mod_add_left_eq plus_nat.add_0)    \n  hence \"sum_efib m (k + 3) = sum_efib m (k + 1)\" using assms\n    apply (simp add: Num.numeral_2_eq_2 Num.numeral_3_eq_3)\n    by (metis Zero_not_Suc mod_add_left_eq plus_nat.add_0)\n  thus ?thesis using assms\n    by simp\nqed  \n\nrecord sum_efib_state =\n  x :: nat\n  y :: nat\n  n :: nat\n  k :: nat\n  tmp :: nat\n  sum :: nat\n\nlemma sum_efib: \"\\<turnstile> \\<lbrace> True \\<rbrace>\n    `sum := 0\n  \\<lbrace> is_sum_efib `sum m \\<rbrace>\"\n  apply hoare\n  apply (auto simp: is_sum_efib_def)\n  apply (rule_tac x=0 in exI)\n  apply auto\noops\n\nlemma sum_efib: \"\\<turnstile> \\<lbrace> True \\<rbrace>\n    `x := 2;\n    `y := 8;\n    `sum := 0;\n    `n := 0;\n    `k := 1;\n    while `x \\<le> m \n    inv\n      (`k \\<ge> 1) \\<and> (`x = efib `n) \\<and> (`x = fib `k) \\<and>\n      (`y = efib (`n + 1)) \\<and> (`y = fib (`k + 3)) \\<and>\n      (`sum = sum_efib m `k)\n    do\n      `tmp := `x;\n      `x := `y;\n      `y := 4 * `y + `tmp;\n      `sum := `sum + `tmp;\n      `n := `n + 1;\n      `k := `k + 3\n    od\n  \\<lbrace> is_sum_efib `sum m \\<rbrace>\"\n  apply (hoare, auto)\n  apply (force simp: is_sum_efib_def)\n  apply (simp add: numeral_3_eq_3)\n  by (simp add: efib_mod_2_eq_0 sum_efib_fib)\n\nlemma sum_efib_refinement: \"\\<lbrakk> True, is_sum_efib `sum m\\<rbrakk>\n    \\<sqsubseteq>\n  `x := 2;\n  `y := 8;\n  `sum := 0;\n  `n := 0;\n  `k := 1;\n  while `x \\<le> m do\n    `tmp := `x;\n    `x := `y;\n    `y := 4 * `y + `tmp;\n    `sum := `sum + `tmp;\n    `n := `n + 1;\n    `k := `k + 3\n  od\"\nproof -\n  have \"\\<lbrakk> True, is_sum_efib `sum m\\<rbrakk> \\<sqsubseteq>\n      `x := 2; \n      \\<lbrakk> `x = efib 0 \\<and> `x = fib 1, is_sum_efib `sum m\\<rbrakk>\"\n    by morgan simp\n  also have \"... \\<sqsubseteq>\n      `x := 2; \n      `y := 8;\n      \\<lbrakk> `x = efib 0  \\<and> `x = fib 1 \\<and> `y = efib 1 \\<and> `y = fib 4, \n        is_sum_efib `sum m\\<rbrakk>\"\napply morgan_step\n    by morgan simp\n  also have \"... \\<sqsubseteq>\n      `x := 2; \n      `y := 8;\n      `sum := 0;\n      \\<lbrakk> `x = efib 0  \\<and> `x = fib 1 \\<and> `y = efib 1 \\<and> `y = fib 4 \\<and> `sum = sum_efib m 1, \n        is_sum_efib `sum m\\<rbrakk>\"\n    by morgan simp\n  also have \"... \\<sqsubseteq>\n      `x := 2; \n      `y := 8;\n      `sum := 0;\n      `n := 0;\n      \\<lbrakk> `x = efib `n  \\<and> `x = fib 1 \\<and> `y = efib (`n + 1) \\<and> `y = fib 4 \\<and> `n \\<ge> 0\n        \\<and> `sum = sum_efib m 1, \n        is_sum_efib `sum m\\<rbrakk>\"\n    by morgan simp\n  also have \"... \\<sqsubseteq>\n      `x := 2; \n      `y := 8;\n      `sum := 0;\n      `n := 0;\n      `k := 1;\n      \\<lbrakk> `x = efib `n  \\<and> `x = fib `k \\<and> `y = efib (`n + 1) \\<and> `y = fib (`k + 3) \\<and> `n \\<ge> 0\n        \\<and> `k \\<ge> 1 \\<and> `sum = sum_efib m `k, \n        is_sum_efib `sum m\\<rbrakk>\"\n    by morgan simp\n  also have \"... \\<sqsubseteq>\n      `x := 2; \n      `y := 8;\n      `sum := 0;\n      `n := 0;\n      `k := 1;\n      while `x \\<le> m do\n        \\<lbrakk> `x = efib `n  \\<and> `x = fib `k \\<and> `y = efib (`n + 1) \\<and> `y = fib (`k + 3) \\<and> `n \\<ge> 0\n          \\<and> `k \\<ge> 1 \\<and> `sum = sum_efib m `k \\<and> `x \\<le> m, \n          `x = efib `n  \\<and> `x = fib `k \\<and> `y = efib (`n + 1) \\<and> `y = fib (`k + 3) \\<and> `n \\<ge> 0\n          \\<and> `k \\<ge> 1 \\<and> `sum = sum_efib m `k \\<rbrakk>\n      od\"\n    by morgan (auto simp: is_sum_efib_def)\n  also have \"... \\<sqsubseteq>\n      `x := 2; \n      `y := 8;\n      `sum := 0;\n      `n := 0;\n      `k := 1;\n      while `x \\<le> m do\n        \\<lbrakk> `x = efib `n  \\<and> `x = fib `k \\<and> `y = efib (`n + 1) \\<and> `y = fib (`k + 3) \\<and> `n \\<ge> 0\n          \\<and> `k \\<ge> 1 \\<and> `sum = sum_efib m `k \\<and> `x \\<le> m, \n          `x = efib `n  \\<and> `x = fib (`k + 3) \\<and> `y = efib (`n + 1) \\<and> `y = fib (6 + `k) \\<and> `n \\<ge> 0\n          \\<and> `k + 3 \\<ge> 1 \\<and> `sum = sum_efib m (`k + 3) \\<rbrakk>;\n        `k := `k + 3\n      od\"\n    by morgan simp\n  also have \"... \\<sqsubseteq>\n      `x := 2; \n      `y := 8;\n      `sum := 0;\n      `n := 0;\n      `k := 1;\n      while `x \\<le> m do\n        \\<lbrakk> `x = efib `n  \\<and> `x = fib `k \\<and> `y = efib (`n + 1) \\<and> `y = fib (`k + 3) \\<and> `n \\<ge> 0\n          \\<and> `k \\<ge> 1 \\<and> `sum = sum_efib m `k \\<and> `x \\<le> m, \n          `x = efib (`n + 1)  \\<and> `x = fib (`k + 3) \\<and> `y = efib (`n + 2) \\<and> `y = fib (6 + `k) \n          \\<and> (`n + 1) \\<ge> 0 \\<and> `k + 3 \\<ge> 1 \\<and> `sum = sum_efib m (`k + 3) \\<rbrakk>;\n        `n := `n + 1;\n        `k := `k + 3\n      od\"\n    by morgan simp\n  also have \"... \\<sqsubseteq>\n      `x := 2; \n      `y := 8;\n      `sum := 0;\n      `n := 0;\n      `k := 1;\n      while `x \\<le> m do\n        \\<lbrakk> `x = efib `n  \\<and> `x = fib `k \\<and> `y = efib (`n + 1) \\<and> `y = fib (`k + 3) \\<and> `n \\<ge> 0\n          \\<and> `k \\<ge> 1 \\<and> `sum = sum_efib m `k \\<and> `x \\<le> m, \n          `x = efib (`n + 1)  \\<and> `x = fib (`k + 3) \\<and> `y = efib (`n + 2) \\<and> `y = fib (6 + `k) \n          \\<and> (`n + 1) \\<ge> 0 \\<and> `k + 3 \\<ge> 1 \\<and> (`sum + `tmp) = sum_efib m (`k + 3) \\<rbrakk>;\n        `sum := `sum + `tmp;\n        `n := `n + 1;\n        `k := `k + 3\n      od\"\n    by morgan simp\n  also have \"... \\<sqsubseteq>\n      `x := 2; \n      `y := 8;\n      `sum := 0;\n      `n := 0;\n      `k := 1;\n      while `x \\<le> m do\n        \\<lbrakk> `x = efib `n  \\<and> `x = fib `k \\<and> `y = efib (`n + 1) \\<and> `y = fib (`k + 3) \\<and> `n \\<ge> 0\n          \\<and> `k \\<ge> 1 \\<and> `sum = sum_efib m `k \\<and> `x \\<le> m, \n          `x = efib (`n + 1)  \\<and> `x = fib (`k + 3) \\<and> (4*`y + `tmp) = efib (`n + 2)\n          \\<and> (4*`y + `tmp) = fib (6 + `k) \\<and> (`n + 1) \\<ge> 0 \\<and> `k + 3 \\<ge> 1 \n          \\<and> (`sum + `tmp) = sum_efib m (`k + 3) \\<rbrakk>;\n        `y := 4*`y + `tmp;\n        `sum := `sum + `tmp;\n        `n := `n + 1;\n        `k := `k + 3\n      od\"\n    by morgan simp\n  also have \"... \\<sqsubseteq>\n      `x := 2; \n      `y := 8;\n      `sum := 0;\n      `n := 0;\n      `k := 1;\n      while `x \\<le> m do\n        \\<lbrakk> `x = efib `n  \\<and> `x = fib `k \\<and> `y = efib (`n + 1) \\<and> `y = fib (`k + 3) \\<and> `n \\<ge> 0\n          \\<and> `k \\<ge> 1 \\<and> `sum = sum_efib m `k \\<and> `x \\<le> m, \n          `y = efib (`n + 1)  \\<and> `y = fib (`k + 3) \\<and> (4*`y + `tmp) = efib (`n + 2)\n          \\<and> (4*`y + `tmp) = fib (6 + `k) \\<and> (`n + 1) \\<ge> 0 \\<and> `k + 3 \\<ge> 1 \n          \\<and> (`sum + `tmp) = sum_efib m (`k + 3) \\<rbrakk>;\n        `x := `y;\n        `y := 4*`y + `tmp;\n        `sum := `sum + `tmp;\n        `n := `n + 1;\n        `k := `k + 3\n      od\"\n    by morgan simp\n  also have \"... \\<sqsubseteq>\n      `x := 2; \n      `y := 8;\n      `sum := 0;\n      `n := 0;\n      `k := 1;\n      while `x \\<le> m do\n        \\<lbrakk> `x = efib `n  \\<and> `x = fib `k \\<and> `y = efib (`n + 1) \\<and> `y = fib (`k + 3) \\<and> `n \\<ge> 0\n          \\<and> `k \\<ge> 1 \\<and> `sum = sum_efib m `k \\<and> `x \\<le> m, \n          `y = efib (`n + 1)  \\<and> `y = fib (`k + 3) \\<and> (4*`y + `x) = efib (`n + 2)\n          \\<and> (4*`y + `x) = fib (6 + `k)\n          \\<and> (`sum + `x) = sum_efib m (`k + 3) \\<rbrakk>;\n        `tmp := `x;\n        `x := `y;\n        `y := 4*`y + `tmp;\n        `sum := `sum + `tmp;\n        `n := `n + 1;\n        `k := `k + 3\n      od\"\n    by morgan simp\n  also have \"... \\<sqsubseteq>\n      `x := 2; \n      `y := 8;\n      `sum := 0;\n      `n := 0;\n      `k := 1;\n      while `x \\<le> m do\n        `tmp := `x;\n        `x := `y;\n        `y := 4*`y + `tmp;\n        `sum := `sum + `tmp;\n        `n := `n + 1;\n        `k := `k + 3\n      od\"\n    apply (morgan, auto)\n    apply (simp add: numeral_3_eq_3)\n    by (simp add: efib_mod_2_eq_0 sum_efib_fib)\n  finally show ?thesis\n    by auto\nqed\n\nhide_const x y n k tmp sum\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/HL/Fibonacci.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528057272544, "lm_q2_score": 0.8221891261650248, "lm_q1q2_score": 0.7004663328747325}}
{"text": "(* Author: Lukas Koller *)\ntheory MinWeightMatching\n  imports Main tsp.Misc tsp.WeightedGraph tsp.CompleteGraph\nbegin\n\ndefinition \"is_perf_match E M \\<equiv> M \\<subseteq> E \\<and> matching M \\<and> Vs M = Vs E\"\n\nlemma is_perf_matchI:\n  assumes \"M \\<subseteq> E\" \"matching M\" \"Vs M = Vs E\"\n  shows \"is_perf_match E M\"\n  using assms by (auto simp: is_perf_match_def)\n\nlemma is_perf_matchI2:\n  assumes \"M \\<subseteq> E\" \"\\<And>u. u \\<in> Vs E \\<Longrightarrow> \\<exists>!e \\<in> M. u \\<in> e\"\n  shows \"is_perf_match E M\"\nproof -\n  have \"Vs M = Vs E\"\n    using assms\n  proof (intro equalityI)\n    show \"Vs E \\<subseteq> Vs M\"\n    proof\n      fix v\n      assume \"v \\<in> Vs E\"\n      then obtain e where \"e \\<in> M\" \"v \\<in> e\"\n        using assms by meson\n      thus \"v \\<in> Vs M\"\n        by (auto intro: vs_member_intro)\n    qed\n  qed (auto simp: Vs_subset)\n  moreover hence \"matching M\"\n    unfolding matching_def2 using assms by auto\n  ultimately show ?thesis\n    using assms by (intro is_perf_matchI)\nqed\n\nlemma is_perf_matchE:\n  assumes \"is_perf_match E M\"\n  shows \"M \\<subseteq> E\" \"matching M\" \"Vs M = Vs E\"\n  using assms[unfolded is_perf_match_def] by auto\n\nlemma extend_perf_match:\n  assumes \"is_perf_match E M\" \"u \\<notin> Vs E\" \"v \\<notin> Vs E\" \"{{u,v}} \\<union> E \\<subseteq> E'\" \"Vs E' = Vs E \\<union> {u,v}\"\n  shows \"is_perf_match E' ({{u,v}} \\<union> M)\"\nproof (rule is_perf_matchI2)\n  have \"M \\<subseteq> E\"\n    using assms by (auto simp: is_perf_matchE)\n  thus \"{{u,v}} \\<union> M \\<subseteq> E'\"\n    using assms by auto\n\n  show \"\\<And>w. w \\<in> Vs E' \\<Longrightarrow> \\<exists>!e \\<in> {{u,v}} \\<union> M. w \\<in> e\"\n  proof -\n    fix w\n    assume \"w \\<in> Vs E'\"\n    then consider \"w \\<in> {u,v}\" | \"w \\<in> Vs E - {u,v}\"\n      using assms by auto\n    thus \"\\<exists>!e \\<in> {{u,v}} \\<union> M. w \\<in> e\"\n    proof cases\n      assume \"w \\<in> {u,v}\"\n      moreover hence \"\\<exists>!e \\<in> {{u,v}}. w \\<in> e\"\n        by auto\n      moreover have \"w \\<notin> Vs M\"\n        using assms calculation by (auto simp: is_perf_matchE)\n      moreover hence \"\\<forall>e \\<in> M. w \\<notin> e\"\n        using vs_member[of w M] by auto\n      ultimately show \"\\<exists>!e \\<in> {{u,v}} \\<union> M. w \\<in> e\"\n        by auto\n    next\n      assume \"w \\<in> Vs E - {u,v}\"\n      moreover hence \"w \\<in> Vs M\" \"matching M\"\n        using assms by (auto simp: is_perf_matchE)\n      moreover hence \"\\<exists>!e \\<in> M. w \\<in> e\"\n        by (auto simp: matching_def2)\n      ultimately show \"\\<exists>!e \\<in> {{u,v}} \\<union> M. w \\<in> e\"\n        by auto \n    qed\n  qed\nqed\n\nlemma restr_graph_compl': \n  \"graph_invar E \\<Longrightarrow> is_complete E \\<Longrightarrow> V \\<subseteq> Vs E \\<Longrightarrow> is_complete {e \\<in> E. e \\<subseteq> V}\" \n  by (intro restr_compl_graph_abs.E\\<^sub>V_complete) unfold_locales (* TODO: clean up lemma!? *)\n\nlemma restr_graph_Vs':\n  \"graph_invar E \\<Longrightarrow> is_complete E \\<Longrightarrow> V \\<subseteq> Vs E \\<Longrightarrow> card V \\<noteq> 1 \\<Longrightarrow> Vs {e \\<in> E. e \\<subseteq> V} = V\"\n  by (intro restr_compl_graph_abs.Vs_E\\<^sub>V_eq_V) unfold_locales (* TODO: clean up lemma!? *)\n\ncontext compl_graph_abs\nbegin\n\nlemma perf_match_exists: \n  assumes \"even (card (Vs E))\"\n  obtains M where \"is_perf_match E M\"\nproof -\n  have \"finite (Vs E)\" \"even (card (Vs E))\"\n    using graph assms finite_subset[OF Vs_subset] by auto\n  thus ?thesis\n    using assms graph complete (* restr_graph_compl restr_graph_Vs *) that\n  proof (induction \"Vs E\" arbitrary: E thesis rule: finite_even_induct)\n    case empty\n    moreover hence \"E = {}\"\n      by (intro Vs_emptyE) auto\n    moreover hence \"is_perf_match E {}\"\n      by (auto intro: is_perf_matchI simp: matching_def)\n    ultimately show ?case by auto\n  next\n    case (insert2 u v V)\n    have \"even (card V)\"\n      apply (rule finite_even_cardI)\n      using insert2 by auto\n    moreover have \"V \\<subseteq> Vs E\"\n      using insert2 by auto\n    moreover hence \"V = Vs {e \\<in> E. e \\<subseteq> V}\" (is \"V = Vs ?E'\")\n      using insert2 calculation by (intro restr_graph_Vs'[symmetric]) auto\n    moreover have \"even (card (Vs ?E'))\" \n      using calculation by auto\n    moreover have \"graph_invar ?E'\" \n      apply (rule graph_subset)\n      using insert2 by auto\n    moreover have \"is_complete ?E'\"\n      using insert2 calculation by (intro restr_graph_compl') \n    ultimately obtain M where \"is_perf_match ?E' M\"\n      using is_completeE[of ?E'] by (elim insert2.hyps(5))\n    moreover have \"u \\<notin> Vs ?E'\" \"v \\<notin> Vs ?E'\" \"Vs E = Vs ?E' \\<union> {u,v}\"\n      using insert2 by (auto simp: \\<open>V = Vs {e \\<in> E. e \\<subseteq> V}\\<close>[symmetric])\n    moreover have \"u \\<in> Vs E\" \"v \\<in> Vs E\"\n      using insert2 by auto\n    moreover hence \"{u,v} \\<in> E\"\n      using insert2 by (intro is_completeE)\n    moreover hence \"{{u,v}} \\<union> ?E' \\<subseteq> E\"\n      by auto\n    ultimately have \"is_perf_match E ({{u,v}} \\<union> M)\"\n      by (intro extend_perf_match)\n    thus ?case\n      using insert2 by auto\n  qed\nqed\n\nend\n\ncontext restr_compl_graph_abs\nbegin\n\nlemma perf_match_exists: \n  assumes \"even (card (Vs E\\<^sub>V))\"\n  obtains M where \"is_perf_match E\\<^sub>V M\"\n  apply (rule compl_graph_abs.perf_match_exists[of E\\<^sub>V])\n  apply unfold_locales\n  using graph_E\\<^sub>V E\\<^sub>V_complete assms that by auto (* TODO: clean up lemma!? *)\n\nend\n\ncontext compl_graph_abs\nbegin\n\nlemma restr_perf_match_exists: \n  assumes \"V \\<subseteq> Vs E\" \"even (card (Vs {e \\<in> E. e \\<subseteq> V}))\"\n  obtains M where \"is_perf_match {e \\<in> E. e \\<subseteq> V} M\"\n  apply (rule restr_compl_graph_abs.perf_match_exists)\n  apply unfold_locales\n  using assms that by auto (* TODO: clean up lemma!? *)\n\nend\n\nabbreviation \"cost_of_match c M \\<equiv> sum c M\"\n\ncontext w_graph_abs\nbegin\n\nabbreviation \"cost_of_match\\<^sub>c M \\<equiv> sum c M\"\n\nend\n\ncontext pos_w_graph_abs\nbegin\n\nlemma cost_of_match_sum: \"cost_of_match\\<^sub>c (set M) \\<le> \\<Sum>\\<^sub># (image_mset c (mset M))\"\nproof (induction M)\n  case (Cons e M)\n  thus ?case \n    by (cases \"e \\<in> set M\") (auto simp: add_left_mono insert_absorb add_increasing costs_ge_0)\nqed auto\n\nend\n\ndefinition \"is_min_match E c M \\<equiv> \n  is_perf_match E M \\<and> (\\<forall>M'. is_perf_match E M' \\<longrightarrow> cost_of_match c M \\<le> cost_of_match c M')\"\n\nlemma is_min_matchE:\n  assumes \"is_min_match E c M\"\n  shows \"is_perf_match E M\" \"\\<And>M'. is_perf_match E M' \\<Longrightarrow> cost_of_match c M \\<le> cost_of_match c M'\"\n  using assms[unfolded is_min_match_def] by auto\n\nlemma is_min_matchE2:\n  assumes \"is_min_match E c M\"\n  shows \"M \\<subseteq> E\" \"matching M\" \"Vs M = Vs E\" \n    \"\\<And>M'. is_perf_match E M' \\<Longrightarrow> cost_of_match c M \\<le> cost_of_match c M'\"\n  using is_min_matchE[OF assms] is_perf_matchE[of E M] by auto \n\nlocale min_weight_matching =\n  w_graph_abs E c for E :: \"'a set set\" and c +\n  fixes comp_match\n  assumes match: \"\\<And>E. (\\<exists>M. is_perf_match E M) \\<Longrightarrow> is_min_match E c (comp_match E c)\"\n\nend", "meta": {"author": "kollerlukas", "repo": "tsp", "sha": "1da45a02ba155387a267adacadae9a0dc374167c", "save_path": "github-repos/isabelle/kollerlukas-tsp", "path": "github-repos/isabelle/kollerlukas-tsp/tsp-1da45a02ba155387a267adacadae9a0dc374167c/problems/MinWeightMatching.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8519528019683105, "lm_q2_score": 0.8221891283434877, "lm_q1q2_score": 0.7004663316401172}}
{"text": "\\<^marker>\\<open>creator \"Kevin Kappelmann\"\\<close>\nparagraph \\<open>Reflexive\\<close>\ntheory Binary_Relations_Reflexive\n  imports\n    Functions_Monotone\nbegin\n\nconsts reflexive_on :: \"'a \\<Rightarrow> ('b \\<Rightarrow> 'b \\<Rightarrow> bool) \\<Rightarrow> bool\"\n\noverloading\n  reflexive_on_pred \\<equiv> \"reflexive_on :: ('a \\<Rightarrow> bool) \\<Rightarrow> ('a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> bool\"\nbegin\n  definition \"reflexive_on_pred P R \\<equiv> \\<forall>x. P x \\<longrightarrow> R x x\"\nend\n\nlemma reflexive_onI [intro]:\n  assumes \"\\<And>x. P x \\<Longrightarrow> R x x\"\n  shows \"reflexive_on P R\"\n  using assms unfolding reflexive_on_pred_def by blast\n\nlemma reflexive_onD [dest]:\n  assumes \"reflexive_on P R\"\n  and \"P x\"\n  shows \"R x x\"\n  using assms unfolding reflexive_on_pred_def by blast\n\nlemma le_in_dom_if_reflexive_on:\n  assumes \"reflexive_on P R\"\n  shows \"P \\<le> in_dom R\"\n  using assms by blast\n\nlemma le_in_codom_if_reflexive_on:\n  assumes \"reflexive_on P R\"\n  shows \"P \\<le> in_codom R\"\n  using assms by blast\n\nlemma in_codom_eq_in_dom_if_reflexive_on_in_field:\n  assumes \"reflexive_on (in_field R) R\"\n  shows \"in_codom R = in_dom R\"\n  using assms by blast\n\nlemma reflexive_on_rel_inv_iff_reflexive_on [iff]:\n  \"reflexive_on P R\\<inverse> \\<longleftrightarrow> reflexive_on (P :: 'a \\<Rightarrow> bool) (R :: 'a \\<Rightarrow> _)\"\n  by blast\n\nlemma antimono_reflexive_on [iff]:\n  \"antimono (\\<lambda>(P :: 'a \\<Rightarrow> bool). reflexive_on P (R :: 'a \\<Rightarrow> _))\"\n  by (intro antimonoI) auto\n\nlemma reflexive_on_if_le_pred_if_reflexive_on:\n  fixes P P' :: \"'a \\<Rightarrow> bool\" and R :: \"'a \\<Rightarrow> _\"\n  assumes \"reflexive_on P R\"\n  and \"P' \\<le> P\"\n  shows \"reflexive_on P' R\"\n  using assms by blast\n\nlemma reflexive_on_sup_eq [simp]:\n  \"(reflexive_on :: ('a \\<Rightarrow> bool) \\<Rightarrow> ('a \\<Rightarrow> _) \\<Rightarrow> _) ((P :: 'a \\<Rightarrow> bool) \\<squnion> Q)\n  = reflexive_on P \\<sqinter> reflexive_on Q\"\n  by (intro ext iffI reflexive_onI)\n    (auto intro: reflexive_on_if_le_pred_if_reflexive_on)\n\nlemma reflexive_on_iff_eq_restrict_left_le:\n  \"reflexive_on (P :: 'a \\<Rightarrow> bool) (R :: 'a \\<Rightarrow> _) \\<longleftrightarrow> ((=)\\<restriction>\\<^bsub>P\\<^esub> \\<le> R)\"\n  by blast\n\ndefinition \"reflexive (R :: 'a \\<Rightarrow> _) \\<equiv> reflexive_on (\\<top> :: 'a \\<Rightarrow> bool) R\"\n\nlemma reflexive_eq_reflexive_on:\n  \"reflexive (R :: 'a \\<Rightarrow> _) = reflexive_on (\\<top> :: 'a \\<Rightarrow> bool) R\"\n  unfolding reflexive_def ..\n\nlemma reflexiveI [intro]:\n  assumes \"\\<And>x. R x x\"\n  shows \"reflexive R\"\n  unfolding reflexive_eq_reflexive_on using assms by (intro reflexive_onI)\n\nlemma reflexiveD:\n  assumes \"reflexive R\"\n  shows \"R x x\"\n  using assms unfolding reflexive_eq_reflexive_on by (blast intro: top1I)\n\nlemma reflexive_on_if_reflexive:\n  fixes P :: \"'a \\<Rightarrow> bool\" and R :: \"'a \\<Rightarrow> _\"\n  assumes \"reflexive R\"\n  shows \"reflexive_on P R\"\n  using assms by (intro reflexive_onI) (blast dest: reflexiveD)\n\nlemma reflexive_rel_inv_iff_reflexive [iff]:\n  \"reflexive R\\<inverse> \\<longleftrightarrow> reflexive R\"\n  by (blast dest: reflexiveD)\n\nlemma reflexive_iff_eq_le: \"reflexive R \\<longleftrightarrow> ((=) \\<le> R)\"\n  unfolding reflexive_eq_reflexive_on reflexive_on_iff_eq_restrict_left_le\n  by simp\n\nparagraph \\<open>Instantiations\\<close>\n\nlemma reflexive_eq: \"reflexive (=)\"\n  by (rule reflexiveI) (rule refl)\n\nlemma reflexive_top: \"reflexive \\<top>\"\n  by (rule reflexiveI) auto\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_Reflexive.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8519528019683106, "lm_q2_score": 0.8221891261650248, "lm_q1q2_score": 0.7004663297841697}}
{"text": "theory Exercise6\n  imports Main\nbegin\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 n) s = n\" |\n\"aval (V x) s = s x\" |\n\"aval (Plus a1 a2) s = (aval a1 s) + (aval a2 s)\"\n\n(* NOTE: aval_rel name is taken by an auto-generated property\n   during the definition of aval, so switching to double\n   underscore here. *)\ninductive aval__rel :: \"aexp \\<Rightarrow> state \\<Rightarrow> val \\<Rightarrow> bool\" where\nnum: \"aval__rel (N n) s n\" |\nvar: \"(s v = n) \\<Longrightarrow> aval__rel (V v) s n\" |\nplus: \"\n  aval__rel a s na\n  \\<Longrightarrow> aval__rel b s nb\n  \\<Longrightarrow> aval__rel (Plus a b) s (na + nb)\"\n\ntheorem rel_thus_aval: \"aval__rel a s v \\<Longrightarrow> aval a s = v\"\n  apply (induction rule: aval__rel.induct)\n  apply auto\n  done\n\ntheorem aval_thus_rel: \"(aval a s = n) \\<Longrightarrow> aval__rel a s n\"\n  apply (induction a arbitrary: s n)\n    apply (simp add: aval__rel.num)\n  using aval__rel.var apply (simp add: aval__rel.intros)\n  apply (metis aval.simps(3) aval__rel.simps)\n  done\n\ntheorem rel_is_aval: \"aval__rel a s v \\<longleftrightarrow> aval a s = v\"\n  using rel_thus_aval aval_thus_rel apply blast\n  done\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/ch4/Exercise6.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8918110339361276, "lm_q2_score": 0.7853085808877581, "lm_q1q2_score": 0.7003468574804247}}
{"text": "theory VDMSet\nimports VDMToolKit\nbegin\n\nsection {* VDM set operators *}\n\ntext{*\nVDM set operators have a direct correspondence in Isabelle. TODO? \n*}\n\ntext {* set comprehension *}\n\n(* { expr | var . filter }, { var \\<in> type . filter }, { var . filter } *)\n\n(*declare [[show_types]]*)\nvalue \"{ x+x | x . x \\<in> {(1::nat),2,3} }\"\n\nvalue \"{ x+x | x . x \\<in> {(1::nat),2,3} }\"\n\n(*value \"{ x+x | x . x \\<in> {(1::nat)..3} }\" --\"not always work\"*)\n\nlemma \"{ x . x \\<in> {1,(2::nat), 3} | x \\<le> 2} = { x \\<in> {1,2,3} . x \\<le> 2 }\"\nfind_theorems \"_ = (_::'a set)\" intro\napply (rule equalityI)\napply (rule subsetI, simp)\ndefer\napply (rule subsetI, simp, elim disjE, simp_all) oops\n\n\nvalue \"{ [A,B,C,D,E,F] ! i | i . i \\<in> {0,2,4} }\"\n\n(* { s(i) | i in set inds s & i mod 2 = 0 } *)\n\ntext{* Sequences may have invariants within their inner type. *}\n\ntype_synonym 'a VDMSet = \"'a set\"\n\ndefinition \n  inv_SetElems :: \"('a \\<Rightarrow> \\<bool>) \\<Rightarrow> 'a VDMSet \\<Rightarrow> \\<bool>\"\nwhere\n  \"inv_SetElems einv s \\<equiv> \\<forall> e \\<in> s . einv e\"\n\nlemma l_inv_SetElems_Cons: \"(inv_SetElems f (insert a s)) = (f a \\<and> (inv_SetElems f s))\"\nunfolding inv_SetElems_def\nby auto\n\n(*\ntext {* Useful example for XO if you use set comprehension *}\n\ntype_synonym Pos = \"(\\<nat> \\<times> \\<nat>)\"\ntype_synonym Line = \"Pos set\"\n\nabbreviation SIZE :: \\<nat> where \"SIZE \\<equiv> 3\"\n\nabbreviation\n  BOARD :: \"\\<nat> set\"\nwhere\n  \"BOARD \\<equiv> {1 .. 3}\"\n\ndefinition\n  inv_Pos :: \"Pos \\<Rightarrow> bool\"\nwhere\n  \"inv_Pos z \\<equiv> let (x,y) = z in  \n                  nat1 x \\<and> x \\<le> SIZE \\<and> \n                  nat1 y \\<and> y \\<le> SIZE\"\n\ndefinition\n  row :: \"nat \\<Rightarrow> Line\"\nwhere\n  \"row rr \\<equiv> { (rr, c) | c . c \\<in> BOARD \\<and> inv_Pos (rr, c) }\"\n\nlemma \"row 1 = A\"\nunfolding row_def inv_Pos_def nat1G0\napply simp\noops\n\ndefinition\n  col :: \"nat \\<Rightarrow> Line\"\nwhere\n  \"col cc \\<equiv> { (r,cc) | r . r \\<in> BOARD \\<and> inv_Pos (r, cc) }\"\n\nlemma \"row 1 = A\" unfolding row_def inv_Pos_def apply simp oops\n\nabbreviation\n  allRows0 :: \"Line set\"\nwhere\n  \"allRows0 \\<equiv> { row 1, row 2, row 3 }\"\n\nabbreviation\n  allRows :: \"Line set\"\nwhere\n  \"allRows \\<equiv> \\<Union> r \\<in> BOARD . { row r }\"\n \nabbreviation\n  allCols :: \"Line set\"\nwhere\n  \"allCols \\<equiv> \\<Union> c \\<in> BOARD . { col c }\"\n\nabbreviation\n  downwardDiag :: \"Line\"\nwhere\n  \"downwardDiag \\<equiv> { (x,x)| x . x \\<in> BOARD }\"\n\nabbreviation\n  upwardDiag :: \"Line\"\nwhere\n  \"upwardDiag \\<equiv> { (x,y) . x \\<in> BOARD \\<and> y = SIZE-x+(1::nat) }\"\n\n(* Use definition to tame unfolding *)\ndefinition\n  winningLines :: \"Line set\"\nwhere\n   \"winningLines \\<equiv> allRows \\<union> allCols \\<union> {downwardDiag, upwardDiag}\"\n\nabbreviation\n  explicitWinningLines :: \"Line set\"\nwhere\n  \"explicitWinningLines \\<equiv> \n          { {(1, 1), (1, 2), (1, 3)}, \n\t\t\t\t\t \t{(2, 1), (2, 2), (2, 3)}, \n\t\t\t\t\t  {(3, 1), (3, 2), (3, 3)},  \n\n\t\t\t\t\t  {(1, 1), (2, 1), (3, 1)}, \n\t\t\t\t\t  {(1, 2), (2, 2), (3, 2)}, \n\t\t\t\t\t  {(1, 3), (2, 3), (3, 3)}, \n\n\t\t\t\t\t  {(1, 1), (2, 2), (3, 3)},\n \n\t\t\t\t\t  {(1, 3), (2, 2), (3, 1)}\n\t\t\t\t  }\"\t\n*)\n\nend\n", "meta": {"author": "habbmehdi", "repo": "DotsAndBoxes", "sha": "860ceeed5b96492720a56037d5770bea255b5c45", "save_path": "github-repos/isabelle/habbmehdi-DotsAndBoxes", "path": "github-repos/isabelle/habbmehdi-DotsAndBoxes/DotsAndBoxes-860ceeed5b96492720a56037d5770bea255b5c45/DotsAndBoxes-Isabelle/VDMSet.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026550642019, "lm_q2_score": 0.7634837635542925, "lm_q1q2_score": 0.7003456834067618}}
{"text": "(*\n  File:   Prime_Harmonic_Misc.thy\n  Author: Manuel Eberl <eberlm@in.tum.de>\n\n*)\n\nsection \\<open>Auxiliary lemmas\\<close>\ntheory Prime_Harmonic_Misc\nimports\n  Complex_Main\n  \"HOL-Number_Theory.Number_Theory\" \nbegin\n\nlemma sum_list_nonneg: \"\\<forall>x\\<in>set xs. x \\<ge> 0 \\<Longrightarrow> sum_list xs \\<ge> (0 :: 'a :: ordered_ab_group_add)\"\n  by (induction xs) auto\n\nlemma sum_telescope':\n  assumes \"m \\<le> n\"\n  shows   \"(\\<Sum>k = Suc m..n. f k - f (Suc k)) = f (Suc m) - (f (Suc n) :: 'a :: ab_group_add)\"\n  by (rule dec_induct[OF assms]) (simp_all add: algebra_simps)\n\nlemma dvd_prodI:\n  assumes \"finite A\" \"x \\<in> A\"\n  shows   \"f x dvd prod f A\"\nproof -\n  from assms have \"prod f A = f x * prod f (A - {x})\" \n    by (intro prod.remove) simp_all\n  thus ?thesis by simp\nqed\n\nlemma dvd_prodD: \"finite A \\<Longrightarrow> prod f A dvd x \\<Longrightarrow> a \\<in> A \\<Longrightarrow> f a dvd x\"\n  by (erule dvd_trans[OF dvd_prodI])\n\nlemma multiplicity_power_nat: \n  \"prime p \\<Longrightarrow> n > 0 \\<Longrightarrow> multiplicity p (n ^ k :: nat) = k * multiplicity p n\"\n  by (induction k) (simp_all add: prime_elem_multiplicity_mult_distrib)\n\nlemma multiplicity_prod_prime_powers_nat':\n  \"finite S \\<Longrightarrow> \\<forall>p\\<in>S. prime p \\<Longrightarrow> prime p \\<Longrightarrow> \n     multiplicity p (\\<Prod>S :: nat) = (if p \\<in> S then 1 else 0)\"\n  using multiplicity_prod_prime_powers[of S p \"\\<lambda>_. 1\"] by simp\n\nlemma prod_prime_subset:\n  assumes \"finite A\" \"finite B\"\n  assumes \"\\<And>x. x \\<in> A \\<Longrightarrow> prime (x::nat)\"\n  assumes \"\\<And>x. x \\<in> B \\<Longrightarrow> prime x\"\n  assumes \"\\<Prod>A dvd \\<Prod>B\"\n  shows   \"A \\<subseteq> B\"\nproof\n  fix x assume x: \"x \\<in> A\"\n  from assms(4)[of 0] have \"0 \\<notin> B\" by auto\n  with assms have nonzero: \"\\<forall>z\\<in>B. z \\<noteq> 0\" by (intro ballI notI) auto\n\n  from x assms have \"1 = multiplicity x (\\<Prod>A)\"\n    by (subst multiplicity_prod_prime_powers_nat') simp_all\n  also from assms nonzero have \"\\<dots> \\<le> multiplicity x (\\<Prod>B)\" by (intro dvd_imp_multiplicity_le) auto\n  finally have \"multiplicity x (\\<Prod>B) > 0\" by simp\n  moreover from assms x have \"prime x\" by simp\n  ultimately show \"x \\<in> B\" using assms(2,4)\n    by (subst (asm) multiplicity_prod_prime_powers_nat') (simp_all split: if_split_asm)\nqed\n\nlemma prod_prime_eq:\n  assumes \"finite A\" \"finite B\" \"\\<And>x. x \\<in> A \\<Longrightarrow> prime (x::nat)\" \"\\<And>x. x \\<in> B \\<Longrightarrow> prime x\" \"\\<Prod>A = \\<Prod>B\"\n  shows   \"A = B\"\n  using assms by (intro equalityI prod_prime_subset) simp_all\n\nlemma ln_ln_nonneg:\n  assumes x: \"x \\<ge> (3 :: real)\"\n  shows   \"ln (ln x) \\<ge> 0\"\nproof -\n  have \"exp 1 \\<le> (3::real)\" by (rule  exp_le)\n  hence \"ln (exp 1) \\<le> ln (3 :: real)\" by (subst ln_le_cancel_iff) simp_all\n  also from x have \"\\<dots> \\<le> ln x\" by (subst ln_le_cancel_iff) simp_all\n  finally have \"ln 1 \\<le> ln (ln x)\" using x by (subst ln_le_cancel_iff) simp_all\n  thus ?thesis 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/Prime_Harmonic_Series/Prime_Harmonic_Misc.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382236515259, "lm_q2_score": 0.8128673133042217, "lm_q1q2_score": 0.7003162611685075}}
{"text": "(*  Title:      HOL/HOLCF/Fix.thy\n    Author:     Franz Regensburger\n    Author:     Brian Huffman\n*)\n\nsection \\<open>Fixed point operator and admissibility\\<close>\n\ntheory Fix\nimports Cfun\nbegin\n\ndefault_sort pcpo\n\nsubsection \\<open>Iteration\\<close>\n\nprimrec iterate :: \"nat \\<Rightarrow> ('a::cpo \\<rightarrow> 'a) \\<rightarrow> ('a \\<rightarrow> 'a)\" where\n    \"iterate 0 = (\\<Lambda> F x. x)\"\n  | \"iterate (Suc n) = (\\<Lambda> F x. F\\<cdot>(iterate n\\<cdot>F\\<cdot>x))\"\n\ntext \\<open>Derive inductive properties of iterate from primitive recursion\\<close>\n\nlemma iterate_0 [simp]: \"iterate 0\\<cdot>F\\<cdot>x = x\"\nby simp\n\nlemma iterate_Suc [simp]: \"iterate (Suc n)\\<cdot>F\\<cdot>x = F\\<cdot>(iterate n\\<cdot>F\\<cdot>x)\"\nby simp\n\ndeclare iterate.simps [simp del]\n\nlemma iterate_Suc2: \"iterate (Suc n)\\<cdot>F\\<cdot>x = iterate n\\<cdot>F\\<cdot>(F\\<cdot>x)\"\nby (induct n) simp_all\n\nlemma iterate_iterate:\n  \"iterate m\\<cdot>F\\<cdot>(iterate n\\<cdot>F\\<cdot>x) = iterate (m + n)\\<cdot>F\\<cdot>x\"\nby (induct m) simp_all\n\ntext \\<open>The sequence of function iterations is a chain.\\<close>\n\nlemma chain_iterate [simp]: \"chain (\\<lambda>i. iterate i\\<cdot>F\\<cdot>\\<bottom>)\"\nby (rule chainI, unfold iterate_Suc2, rule monofun_cfun_arg, rule minimal)\n\n\nsubsection \\<open>Least fixed point operator\\<close>\n\ndefinition\n  \"fix\" :: \"('a \\<rightarrow> 'a) \\<rightarrow> 'a\" where\n  \"fix = (\\<Lambda> F. \\<Squnion>i. iterate i\\<cdot>F\\<cdot>\\<bottom>)\"\n\ntext \\<open>Binder syntax for @{term fix}\\<close>\n\nabbreviation\n  fix_syn :: \"('a \\<Rightarrow> 'a) \\<Rightarrow> 'a\"  (binder \"\\<mu> \" 10) where\n  \"fix_syn (\\<lambda>x. f x) \\<equiv> fix\\<cdot>(\\<Lambda> x. f x)\"\n\nnotation (ASCII)\n  fix_syn  (binder \"FIX \" 10)\n\ntext \\<open>Properties of @{term fix}\\<close>\n\ntext \\<open>direct connection between @{term fix} and iteration\\<close>\n\nlemma fix_def2: \"fix\\<cdot>F = (\\<Squnion>i. iterate i\\<cdot>F\\<cdot>\\<bottom>)\"\nunfolding fix_def by simp\n\nlemma iterate_below_fix: \"iterate n\\<cdot>f\\<cdot>\\<bottom> \\<sqsubseteq> fix\\<cdot>f\"\n  unfolding fix_def2\n  using chain_iterate by (rule is_ub_thelub)\n\ntext \\<open>\n  Kleene's fixed point theorems for continuous functions in pointed\n  omega cpo's\n\\<close>\n\nlemma fix_eq: \"fix\\<cdot>F = F\\<cdot>(fix\\<cdot>F)\"\napply (simp add: fix_def2)\napply (subst lub_range_shift [of _ 1, symmetric])\napply (rule chain_iterate)\napply (subst contlub_cfun_arg)\napply (rule chain_iterate)\napply simp\ndone\n\nlemma fix_least_below: \"F\\<cdot>x \\<sqsubseteq> x \\<Longrightarrow> fix\\<cdot>F \\<sqsubseteq> x\"\napply (simp add: fix_def2)\napply (rule lub_below)\napply (rule chain_iterate)\napply (induct_tac i)\napply simp\napply simp\napply (erule rev_below_trans)\napply (erule monofun_cfun_arg)\ndone\n\nlemma fix_least: \"F\\<cdot>x = x \\<Longrightarrow> fix\\<cdot>F \\<sqsubseteq> x\"\nby (rule fix_least_below, simp)\n\nlemma fix_eqI:\n  assumes fixed: \"F\\<cdot>x = x\" and least: \"\\<And>z. F\\<cdot>z = z \\<Longrightarrow> x \\<sqsubseteq> z\"\n  shows \"fix\\<cdot>F = x\"\napply (rule below_antisym)\napply (rule fix_least [OF fixed])\napply (rule least [OF fix_eq [symmetric]])\ndone\n\nlemma fix_eq2: \"f \\<equiv> fix\\<cdot>F \\<Longrightarrow> f = F\\<cdot>f\"\nby (simp add: fix_eq [symmetric])\n\nlemma fix_eq3: \"f \\<equiv> fix\\<cdot>F \\<Longrightarrow> f\\<cdot>x = F\\<cdot>f\\<cdot>x\"\nby (erule fix_eq2 [THEN cfun_fun_cong])\n\nlemma fix_eq4: \"f = fix\\<cdot>F \\<Longrightarrow> f = F\\<cdot>f\"\napply (erule ssubst)\napply (rule fix_eq)\ndone\n\nlemma fix_eq5: \"f = fix\\<cdot>F \\<Longrightarrow> f\\<cdot>x = F\\<cdot>f\\<cdot>x\"\nby (erule fix_eq4 [THEN cfun_fun_cong])\n\ntext \\<open>strictness of @{term fix}\\<close>\n\nlemma fix_bottom_iff: \"(fix\\<cdot>F = \\<bottom>) = (F\\<cdot>\\<bottom> = \\<bottom>)\"\napply (rule iffI)\napply (erule subst)\napply (rule fix_eq [symmetric])\napply (erule fix_least [THEN bottomI])\ndone\n\nlemma fix_strict: \"F\\<cdot>\\<bottom> = \\<bottom> \\<Longrightarrow> fix\\<cdot>F = \\<bottom>\"\nby (simp add: fix_bottom_iff)\n\nlemma fix_defined: \"F\\<cdot>\\<bottom> \\<noteq> \\<bottom> \\<Longrightarrow> fix\\<cdot>F \\<noteq> \\<bottom>\"\nby (simp add: fix_bottom_iff)\n\ntext \\<open>@{term fix} applied to identity and constant functions\\<close>\n\nlemma fix_id: \"(\\<mu> x. x) = \\<bottom>\"\nby (simp add: fix_strict)\n\nlemma fix_const: \"(\\<mu> x. c) = c\"\nby (subst fix_eq, simp)\n\nsubsection \\<open>Fixed point induction\\<close>\n\nlemma fix_ind: \"\\<lbrakk>adm P; P \\<bottom>; \\<And>x. P x \\<Longrightarrow> P (F\\<cdot>x)\\<rbrakk> \\<Longrightarrow> P (fix\\<cdot>F)\"\nunfolding fix_def2\napply (erule admD)\napply (rule chain_iterate)\napply (rule nat_induct, simp_all)\ndone\n\nlemma cont_fix_ind:\n  \"\\<lbrakk>cont F; adm P; P \\<bottom>; \\<And>x. P x \\<Longrightarrow> P (F x)\\<rbrakk> \\<Longrightarrow> P (fix\\<cdot>(Abs_cfun F))\"\nby (simp add: fix_ind)\n\nlemma def_fix_ind:\n  \"\\<lbrakk>f \\<equiv> fix\\<cdot>F; adm P; P \\<bottom>; \\<And>x. P x \\<Longrightarrow> P (F\\<cdot>x)\\<rbrakk> \\<Longrightarrow> P f\"\nby (simp add: fix_ind)\n\nlemma fix_ind2:\n  assumes adm: \"adm P\"\n  assumes 0: \"P \\<bottom>\" and 1: \"P (F\\<cdot>\\<bottom>)\"\n  assumes step: \"\\<And>x. \\<lbrakk>P x; P (F\\<cdot>x)\\<rbrakk> \\<Longrightarrow> P (F\\<cdot>(F\\<cdot>x))\"\n  shows \"P (fix\\<cdot>F)\"\nunfolding fix_def2\napply (rule admD [OF adm chain_iterate])\napply (rule nat_less_induct)\napply (case_tac n)\napply (simp add: 0)\napply (case_tac nat)\napply (simp add: 1)\napply (frule_tac x=nat in spec)\napply (simp add: step)\ndone\n\nlemma parallel_fix_ind:\n  assumes adm: \"adm (\\<lambda>x. P (fst x) (snd x))\"\n  assumes base: \"P \\<bottom> \\<bottom>\"\n  assumes step: \"\\<And>x y. P x y \\<Longrightarrow> P (F\\<cdot>x) (G\\<cdot>y)\"\n  shows \"P (fix\\<cdot>F) (fix\\<cdot>G)\"\nproof -\n  from adm have adm': \"adm (case_prod P)\"\n    unfolding split_def .\n  have \"\\<And>i. P (iterate i\\<cdot>F\\<cdot>\\<bottom>) (iterate i\\<cdot>G\\<cdot>\\<bottom>)\"\n    by (induct_tac i, simp add: base, simp add: step)\n  hence \"\\<And>i. case_prod P (iterate i\\<cdot>F\\<cdot>\\<bottom>, iterate i\\<cdot>G\\<cdot>\\<bottom>)\"\n    by simp\n  hence \"case_prod P (\\<Squnion>i. (iterate i\\<cdot>F\\<cdot>\\<bottom>, iterate i\\<cdot>G\\<cdot>\\<bottom>))\"\n    by - (rule admD [OF adm'], simp, assumption)\n  hence \"case_prod P (\\<Squnion>i. iterate i\\<cdot>F\\<cdot>\\<bottom>, \\<Squnion>i. iterate i\\<cdot>G\\<cdot>\\<bottom>)\"\n    by (simp add: lub_Pair)\n  hence \"P (\\<Squnion>i. iterate i\\<cdot>F\\<cdot>\\<bottom>) (\\<Squnion>i. iterate i\\<cdot>G\\<cdot>\\<bottom>)\"\n    by simp\n  thus \"P (fix\\<cdot>F) (fix\\<cdot>G)\"\n    by (simp add: fix_def2)\nqed\n\nlemma cont_parallel_fix_ind:\n  assumes \"cont F\" and \"cont G\"\n  assumes \"adm (\\<lambda>x. P (fst x) (snd x))\"\n  assumes \"P \\<bottom> \\<bottom>\"\n  assumes \"\\<And>x y. P x y \\<Longrightarrow> P (F x) (G y)\"\n  shows \"P (fix\\<cdot>(Abs_cfun F)) (fix\\<cdot>(Abs_cfun G))\"\nby (rule parallel_fix_ind, simp_all add: assms)\n\nsubsection \\<open>Fixed-points on product types\\<close>\n\ntext \\<open>\n  Bekic's Theorem: Simultaneous fixed points over pairs\n  can be written in terms of separate fixed points.\n\\<close>\n\nlemma fix_cprod:\n  \"fix\\<cdot>(F::'a \\<times> 'b \\<rightarrow> 'a \\<times> 'b) =\n   (\\<mu> x. fst (F\\<cdot>(x, \\<mu> y. snd (F\\<cdot>(x, y)))),\n    \\<mu> y. snd (F\\<cdot>(\\<mu> x. fst (F\\<cdot>(x, \\<mu> y. snd (F\\<cdot>(x, y)))), y)))\"\n  (is \"fix\\<cdot>F = (?x, ?y)\")\nproof (rule fix_eqI)\n  have 1: \"fst (F\\<cdot>(?x, ?y)) = ?x\"\n    by (rule trans [symmetric, OF fix_eq], simp)\n  have 2: \"snd (F\\<cdot>(?x, ?y)) = ?y\"\n    by (rule trans [symmetric, OF fix_eq], simp)\n  from 1 2 show \"F\\<cdot>(?x, ?y) = (?x, ?y)\" by (simp add: prod_eq_iff)\nnext\n  fix z assume F_z: \"F\\<cdot>z = z\"\n  obtain x y where z: \"z = (x,y)\" by (rule prod.exhaust)\n  from F_z z have F_x: \"fst (F\\<cdot>(x, y)) = x\" by simp\n  from F_z z have F_y: \"snd (F\\<cdot>(x, y)) = y\" by simp\n  let ?y1 = \"\\<mu> y. snd (F\\<cdot>(x, y))\"\n  have \"?y1 \\<sqsubseteq> y\" by (rule fix_least, simp add: F_y)\n  hence \"fst (F\\<cdot>(x, ?y1)) \\<sqsubseteq> fst (F\\<cdot>(x, y))\"\n    by (simp add: fst_monofun monofun_cfun)\n  hence \"fst (F\\<cdot>(x, ?y1)) \\<sqsubseteq> x\" using F_x by simp\n  hence 1: \"?x \\<sqsubseteq> x\" by (simp add: fix_least_below)\n  hence \"snd (F\\<cdot>(?x, y)) \\<sqsubseteq> snd (F\\<cdot>(x, y))\"\n    by (simp add: snd_monofun monofun_cfun)\n  hence \"snd (F\\<cdot>(?x, y)) \\<sqsubseteq> y\" using F_y by simp\n  hence 2: \"?y \\<sqsubseteq> y\" by (simp add: fix_least_below)\n  show \"(?x, ?y) \\<sqsubseteq> z\" using z 1 2 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/HOLCF/Fix.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8128673178375735, "lm_q2_score": 0.8615382147637195, "lm_q1q2_score": 0.700316257849556}}
{"text": "(*  Title:      HOL/Library/FSet.thy\n    Author:     Ondrej Kuncar, TU Muenchen\n    Author:     Cezary Kaliszyk and Christian Urban\n    Author:     Andrei Popescu, TU Muenchen\n*)\n\nsection \\<open>Type of finite sets defined as a subtype of sets\\<close>\n\ntheory FSet\nimports Main Countable\nbegin\n\nsubsection \\<open>Definition of the type\\<close>\n\ntypedef 'a fset = \"{A :: 'a set. finite A}\"  morphisms fset Abs_fset\nby auto\n\nsetup_lifting type_definition_fset\n\n\nsubsection \\<open>Basic operations and type class instantiations\\<close>\n\n(* FIXME transfer and right_total vs. bi_total *)\ninstantiation fset :: (finite) finite\nbegin\ninstance by (standard; transfer; simp)\nend\n\ninstantiation fset :: (type) \"{bounded_lattice_bot, distrib_lattice, minus}\"\nbegin\n\nlift_definition bot_fset :: \"'a fset\" is \"{}\" parametric empty_transfer by simp\n\nlift_definition less_eq_fset :: \"'a fset \\<Rightarrow> 'a fset \\<Rightarrow> bool\" is subset_eq parametric subset_transfer\n  .\n\ndefinition less_fset :: \"'a fset \\<Rightarrow> 'a fset \\<Rightarrow> bool\" where \"xs < ys \\<equiv> xs \\<le> ys \\<and> xs \\<noteq> (ys::'a fset)\"\n\nlemma less_fset_transfer[transfer_rule]:\n  includes lifting_syntax\n  assumes [transfer_rule]: \"bi_unique A\"\n  shows \"((pcr_fset A) ===> (pcr_fset A) ===> (=)) (\\<subset>) (<)\"\n  unfolding less_fset_def[abs_def] psubset_eq[abs_def] by transfer_prover\n\n\nlift_definition sup_fset :: \"'a fset \\<Rightarrow> 'a fset \\<Rightarrow> 'a fset\" is union parametric union_transfer\n  by simp\n\nlift_definition inf_fset :: \"'a fset \\<Rightarrow> 'a fset \\<Rightarrow> 'a fset\" is inter parametric inter_transfer\n  by simp\n\nlift_definition minus_fset :: \"'a fset \\<Rightarrow> 'a fset \\<Rightarrow> 'a fset\" is minus parametric Diff_transfer\n  by simp\n\ninstance\n  by (standard; transfer; auto)+\n\nend\n\nabbreviation fempty :: \"'a fset\" (\"{||}\") where \"{||} \\<equiv> bot\"\nabbreviation fsubset_eq :: \"'a fset \\<Rightarrow> 'a fset \\<Rightarrow> bool\" (infix \"|\\<subseteq>|\" 50) where \"xs |\\<subseteq>| ys \\<equiv> xs \\<le> ys\"\nabbreviation fsubset :: \"'a fset \\<Rightarrow> 'a fset \\<Rightarrow> bool\" (infix \"|\\<subset>|\" 50) where \"xs |\\<subset>| ys \\<equiv> xs < ys\"\nabbreviation funion :: \"'a fset \\<Rightarrow> 'a fset \\<Rightarrow> 'a fset\" (infixl \"|\\<union>|\" 65) where \"xs |\\<union>| ys \\<equiv> sup xs ys\"\nabbreviation finter :: \"'a fset \\<Rightarrow> 'a fset \\<Rightarrow> 'a fset\" (infixl \"|\\<inter>|\" 65) where \"xs |\\<inter>| ys \\<equiv> inf xs ys\"\nabbreviation fminus :: \"'a fset \\<Rightarrow> 'a fset \\<Rightarrow> 'a fset\" (infixl \"|-|\" 65) where \"xs |-| ys \\<equiv> minus xs ys\"\n\ninstantiation fset :: (equal) equal\nbegin\ndefinition \"HOL.equal A B \\<longleftrightarrow> A |\\<subseteq>| B \\<and> B |\\<subseteq>| A\"\ninstance by intro_classes (auto simp add: equal_fset_def)\nend\n\ninstantiation fset :: (type) conditionally_complete_lattice\nbegin\n\ncontext includes lifting_syntax\nbegin\n\nlemma right_total_Inf_fset_transfer:\n  assumes [transfer_rule]: \"bi_unique A\" and [transfer_rule]: \"right_total A\"\n  shows \"(rel_set (rel_set A) ===> rel_set A)\n    (\\<lambda>S. if finite (\\<Inter>S \\<inter> Collect (Domainp A)) then \\<Inter>S \\<inter> Collect (Domainp A) else {})\n      (\\<lambda>S. if finite (Inf S) then Inf S else {})\"\n    by transfer_prover\n\nlemma Inf_fset_transfer:\n  assumes [transfer_rule]: \"bi_unique A\" and [transfer_rule]: \"bi_total A\"\n  shows \"(rel_set (rel_set A) ===> rel_set A) (\\<lambda>A. if finite (Inf A) then Inf A else {})\n    (\\<lambda>A. if finite (Inf A) then Inf A else {})\"\n  by transfer_prover\n\nlift_definition Inf_fset :: \"'a fset set \\<Rightarrow> 'a fset\" is \"\\<lambda>A. if finite (Inf A) then Inf A else {}\"\nparametric right_total_Inf_fset_transfer Inf_fset_transfer by simp\n\nlemma Sup_fset_transfer:\n  assumes [transfer_rule]: \"bi_unique A\"\n  shows \"(rel_set (rel_set A) ===> rel_set A) (\\<lambda>A. if finite (Sup A) then Sup A else {})\n  (\\<lambda>A. if finite (Sup A) then Sup A else {})\" by transfer_prover\n\nlift_definition Sup_fset :: \"'a fset set \\<Rightarrow> 'a fset\" is \"\\<lambda>A. if finite (Sup A) then Sup A else {}\"\nparametric Sup_fset_transfer by simp\n\nlemma finite_Sup: \"\\<exists>z. finite z \\<and> (\\<forall>a. a \\<in> X \\<longrightarrow> a \\<le> z) \\<Longrightarrow> finite (Sup X)\"\nby (auto intro: finite_subset)\n\nlemma transfer_bdd_below[transfer_rule]: \"(rel_set (pcr_fset (=)) ===> (=)) bdd_below bdd_below\"\n  by auto\n\nend\n\ninstance\nproof\n  fix x z :: \"'a fset\"\n  fix X :: \"'a fset set\"\n  {\n    assume \"x \\<in> X\" \"bdd_below X\"\n    then show \"Inf X |\\<subseteq>| x\" by transfer auto\n  next\n    assume \"X \\<noteq> {}\" \"(\\<And>x. x \\<in> X \\<Longrightarrow> z |\\<subseteq>| x)\"\n    then show \"z |\\<subseteq>| Inf X\" by transfer (clarsimp, blast)\n  next\n    assume \"x \\<in> X\" \"bdd_above X\"\n    then obtain z where \"x \\<in> X\" \"(\\<And>x. x \\<in> X \\<Longrightarrow> x |\\<subseteq>| z)\"\n      by (auto simp: bdd_above_def)\n    then show \"x |\\<subseteq>| Sup X\"\n      by transfer (auto intro!: finite_Sup)\n  next\n    assume \"X \\<noteq> {}\" \"(\\<And>x. x \\<in> X \\<Longrightarrow> x |\\<subseteq>| z)\"\n    then show \"Sup X |\\<subseteq>| z\" by transfer (clarsimp, blast)\n  }\nqed\nend\n\ninstantiation fset :: (finite) complete_lattice\nbegin\n\nlift_definition top_fset :: \"'a fset\" is UNIV parametric right_total_UNIV_transfer UNIV_transfer\n  by simp\n\ninstance\n  by (standard; transfer; auto)\n\nend\n\ninstantiation fset :: (finite) complete_boolean_algebra\nbegin\n\nlift_definition uminus_fset :: \"'a fset \\<Rightarrow> 'a fset\" is uminus\n  parametric right_total_Compl_transfer Compl_transfer by simp\n\ninstance\n  by (standard; transfer) (simp_all add: Inf_Sup Diff_eq)\nend\n\nabbreviation fUNIV :: \"'a::finite fset\" where \"fUNIV \\<equiv> top\"\nabbreviation fuminus :: \"'a::finite fset \\<Rightarrow> 'a fset\" (\"|-| _\" [81] 80) where \"|-| x \\<equiv> uminus x\"\n\ndeclare top_fset.rep_eq[simp]\n\n\nsubsection \\<open>Other operations\\<close>\n\nlift_definition finsert :: \"'a \\<Rightarrow> 'a fset \\<Rightarrow> 'a fset\" is insert parametric Lifting_Set.insert_transfer\n  by simp\n\nsyntax\n  \"_insert_fset\"     :: \"args => 'a fset\"  (\"{|(_)|}\")\n\ntranslations\n  \"{|x, xs|}\" == \"CONST finsert x {|xs|}\"\n  \"{|x|}\"     == \"CONST finsert x {||}\"\n\nlift_definition fmember :: \"'a \\<Rightarrow> 'a fset \\<Rightarrow> bool\" (infix \"|\\<in>|\" 50) is Set.member\n  parametric member_transfer .\n\nlemma fmember_iff_member_fset: \"x |\\<in>| A \\<longleftrightarrow> x \\<in> fset A\"\n  by (rule fmember.rep_eq)\n\nabbreviation notin_fset :: \"'a \\<Rightarrow> 'a fset \\<Rightarrow> bool\" (infix \"|\\<notin>|\" 50) where \"x |\\<notin>| S \\<equiv> \\<not> (x |\\<in>| S)\"\n\ncontext includes lifting_syntax\nbegin\n\nlift_definition ffilter :: \"('a \\<Rightarrow> bool) \\<Rightarrow> 'a fset \\<Rightarrow> 'a fset\" is Set.filter\n  parametric Lifting_Set.filter_transfer unfolding Set.filter_def by simp\n\nlift_definition fPow :: \"'a fset \\<Rightarrow> 'a fset fset\" is Pow parametric Pow_transfer\nby (simp add: finite_subset)\n\nlift_definition fcard :: \"'a fset \\<Rightarrow> nat\" is card parametric card_transfer .\n\nlift_definition fimage :: \"('a \\<Rightarrow> 'b) \\<Rightarrow> 'a fset \\<Rightarrow> 'b fset\" (infixr \"|`|\" 90) is image\n  parametric image_transfer by simp\n\nlift_definition fthe_elem :: \"'a fset \\<Rightarrow> 'a\" is the_elem .\n\nlift_definition fbind :: \"'a fset \\<Rightarrow> ('a \\<Rightarrow> 'b fset) \\<Rightarrow> 'b fset\" is Set.bind parametric bind_transfer\nby (simp add: Set.bind_def)\n\nlift_definition ffUnion :: \"'a fset fset \\<Rightarrow> 'a fset\" is Union parametric Union_transfer by simp\n\nlift_definition fBall :: \"'a fset \\<Rightarrow> ('a \\<Rightarrow> bool) \\<Rightarrow> bool\" is Ball parametric Ball_transfer .\nlift_definition fBex :: \"'a fset \\<Rightarrow> ('a \\<Rightarrow> bool) \\<Rightarrow> bool\" is Bex parametric Bex_transfer .\n\nlift_definition ffold :: \"('a \\<Rightarrow> 'b \\<Rightarrow> 'b) \\<Rightarrow> 'b \\<Rightarrow> 'a fset \\<Rightarrow> 'b\" is Finite_Set.fold .\n\nlift_definition fset_of_list :: \"'a list \\<Rightarrow> 'a fset\" is set by (rule finite_set)\n\nlift_definition sorted_list_of_fset :: \"'a::linorder fset \\<Rightarrow> 'a list\" is sorted_list_of_set .\n\nsubsection \\<open>Transferred lemmas from Set.thy\\<close>\n\nlemmas fset_eqI = set_eqI[Transfer.transferred]\nlemmas fset_eq_iff[no_atp] = set_eq_iff[Transfer.transferred]\nlemmas fBallI[intro!] = ballI[Transfer.transferred]\nlemmas fbspec[dest?] = bspec[Transfer.transferred]\nlemmas fBallE[elim] = ballE[Transfer.transferred]\nlemmas fBexI[intro] = bexI[Transfer.transferred]\nlemmas rev_fBexI[intro?] = rev_bexI[Transfer.transferred]\nlemmas fBexCI = bexCI[Transfer.transferred]\nlemmas fBexE[elim!] = bexE[Transfer.transferred]\nlemmas fBall_triv[simp] = ball_triv[Transfer.transferred]\nlemmas fBex_triv[simp] = bex_triv[Transfer.transferred]\nlemmas fBex_triv_one_point1[simp] = bex_triv_one_point1[Transfer.transferred]\nlemmas fBex_triv_one_point2[simp] = bex_triv_one_point2[Transfer.transferred]\nlemmas fBex_one_point1[simp] = bex_one_point1[Transfer.transferred]\nlemmas fBex_one_point2[simp] = bex_one_point2[Transfer.transferred]\nlemmas fBall_one_point1[simp] = ball_one_point1[Transfer.transferred]\nlemmas fBall_one_point2[simp] = ball_one_point2[Transfer.transferred]\nlemmas fBall_conj_distrib = ball_conj_distrib[Transfer.transferred]\nlemmas fBex_disj_distrib = bex_disj_distrib[Transfer.transferred]\nlemmas fBall_cong[fundef_cong] = ball_cong[Transfer.transferred]\nlemmas fBex_cong[fundef_cong] = bex_cong[Transfer.transferred]\nlemmas fsubsetI[intro!] = subsetI[Transfer.transferred]\nlemmas fsubsetD[elim, intro?] = subsetD[Transfer.transferred]\nlemmas rev_fsubsetD[no_atp,intro?] = rev_subsetD[Transfer.transferred]\nlemmas fsubsetCE[no_atp,elim] = subsetCE[Transfer.transferred]\nlemmas fsubset_eq[no_atp] = subset_eq[Transfer.transferred]\nlemmas contra_fsubsetD[no_atp] = contra_subsetD[Transfer.transferred]\nlemmas fsubset_refl = subset_refl[Transfer.transferred]\nlemmas fsubset_trans = subset_trans[Transfer.transferred]\nlemmas fset_rev_mp = rev_subsetD[Transfer.transferred]\nlemmas fset_mp = subsetD[Transfer.transferred]\nlemmas fsubset_not_fsubset_eq[code] = subset_not_subset_eq[Transfer.transferred]\nlemmas eq_fmem_trans = eq_mem_trans[Transfer.transferred]\nlemmas fsubset_antisym[intro!] = subset_antisym[Transfer.transferred]\nlemmas fequalityD1 = equalityD1[Transfer.transferred]\nlemmas fequalityD2 = equalityD2[Transfer.transferred]\nlemmas fequalityE = equalityE[Transfer.transferred]\nlemmas fequalityCE[elim] = equalityCE[Transfer.transferred]\nlemmas eqfset_imp_iff = eqset_imp_iff[Transfer.transferred]\nlemmas eqfelem_imp_iff = eqelem_imp_iff[Transfer.transferred]\nlemmas fempty_iff[simp] = empty_iff[Transfer.transferred]\nlemmas fempty_fsubsetI[iff] = empty_subsetI[Transfer.transferred]\nlemmas equalsffemptyI = equals0I[Transfer.transferred]\nlemmas equalsffemptyD = equals0D[Transfer.transferred]\nlemmas fBall_fempty[simp] = ball_empty[Transfer.transferred]\nlemmas fBex_fempty[simp] = bex_empty[Transfer.transferred]\nlemmas fPow_iff[iff] = Pow_iff[Transfer.transferred]\nlemmas fPowI = PowI[Transfer.transferred]\nlemmas fPowD = PowD[Transfer.transferred]\nlemmas fPow_bottom = Pow_bottom[Transfer.transferred]\nlemmas fPow_top = Pow_top[Transfer.transferred]\nlemmas fPow_not_fempty = Pow_not_empty[Transfer.transferred]\nlemmas finter_iff[simp] = Int_iff[Transfer.transferred]\nlemmas finterI[intro!] = IntI[Transfer.transferred]\nlemmas finterD1 = IntD1[Transfer.transferred]\nlemmas finterD2 = IntD2[Transfer.transferred]\nlemmas finterE[elim!] = IntE[Transfer.transferred]\nlemmas funion_iff[simp] = Un_iff[Transfer.transferred]\nlemmas funionI1[elim?] = UnI1[Transfer.transferred]\nlemmas funionI2[elim?] = UnI2[Transfer.transferred]\nlemmas funionCI[intro!] = UnCI[Transfer.transferred]\nlemmas funionE[elim!] = UnE[Transfer.transferred]\nlemmas fminus_iff[simp] = Diff_iff[Transfer.transferred]\nlemmas fminusI[intro!] = DiffI[Transfer.transferred]\nlemmas fminusD1 = DiffD1[Transfer.transferred]\nlemmas fminusD2 = DiffD2[Transfer.transferred]\nlemmas fminusE[elim!] = DiffE[Transfer.transferred]\nlemmas finsert_iff[simp] = insert_iff[Transfer.transferred]\nlemmas finsertI1 = insertI1[Transfer.transferred]\nlemmas finsertI2 = insertI2[Transfer.transferred]\nlemmas finsertE[elim!] = insertE[Transfer.transferred]\nlemmas finsertCI[intro!] = insertCI[Transfer.transferred]\nlemmas fsubset_finsert_iff = subset_insert_iff[Transfer.transferred]\nlemmas finsert_ident = insert_ident[Transfer.transferred]\nlemmas fsingletonI[intro!,no_atp] = singletonI[Transfer.transferred]\nlemmas fsingletonD[dest!,no_atp] = singletonD[Transfer.transferred]\nlemmas fsingleton_iff = singleton_iff[Transfer.transferred]\nlemmas fsingleton_inject[dest!] = singleton_inject[Transfer.transferred]\nlemmas fsingleton_finsert_inj_eq[iff,no_atp] = singleton_insert_inj_eq[Transfer.transferred]\nlemmas fsingleton_finsert_inj_eq'[iff,no_atp] = singleton_insert_inj_eq'[Transfer.transferred]\nlemmas fsubset_fsingletonD = subset_singletonD[Transfer.transferred]\nlemmas fminus_single_finsert = Diff_single_insert[Transfer.transferred]\nlemmas fdoubleton_eq_iff = doubleton_eq_iff[Transfer.transferred]\nlemmas funion_fsingleton_iff = Un_singleton_iff[Transfer.transferred]\nlemmas fsingleton_funion_iff = singleton_Un_iff[Transfer.transferred]\nlemmas fimage_eqI[simp, intro] = image_eqI[Transfer.transferred]\nlemmas fimageI = imageI[Transfer.transferred]\nlemmas rev_fimage_eqI = rev_image_eqI[Transfer.transferred]\nlemmas fimageE[elim!] = imageE[Transfer.transferred]\nlemmas Compr_fimage_eq = Compr_image_eq[Transfer.transferred]\nlemmas fimage_funion = image_Un[Transfer.transferred]\nlemmas fimage_iff = image_iff[Transfer.transferred]\nlemmas fimage_fsubset_iff[no_atp] = image_subset_iff[Transfer.transferred]\nlemmas fimage_fsubsetI = image_subsetI[Transfer.transferred]\nlemmas fimage_ident[simp] = image_ident[Transfer.transferred]\nlemmas if_split_fmem1 = if_split_mem1[Transfer.transferred]\nlemmas if_split_fmem2 = if_split_mem2[Transfer.transferred]\nlemmas pfsubsetI[intro!,no_atp] = psubsetI[Transfer.transferred]\nlemmas pfsubsetE[elim!,no_atp] = psubsetE[Transfer.transferred]\nlemmas pfsubset_finsert_iff = psubset_insert_iff[Transfer.transferred]\nlemmas pfsubset_eq = psubset_eq[Transfer.transferred]\nlemmas pfsubset_imp_fsubset = psubset_imp_subset[Transfer.transferred]\nlemmas pfsubset_trans = psubset_trans[Transfer.transferred]\nlemmas pfsubsetD = psubsetD[Transfer.transferred]\nlemmas pfsubset_fsubset_trans = psubset_subset_trans[Transfer.transferred]\nlemmas fsubset_pfsubset_trans = subset_psubset_trans[Transfer.transferred]\nlemmas pfsubset_imp_ex_fmem = psubset_imp_ex_mem[Transfer.transferred]\nlemmas fimage_fPow_mono = image_Pow_mono[Transfer.transferred]\nlemmas fimage_fPow_surj = image_Pow_surj[Transfer.transferred]\nlemmas fsubset_finsertI = subset_insertI[Transfer.transferred]\nlemmas fsubset_finsertI2 = subset_insertI2[Transfer.transferred]\nlemmas fsubset_finsert = subset_insert[Transfer.transferred]\nlemmas funion_upper1 = Un_upper1[Transfer.transferred]\nlemmas funion_upper2 = Un_upper2[Transfer.transferred]\nlemmas funion_least = Un_least[Transfer.transferred]\nlemmas finter_lower1 = Int_lower1[Transfer.transferred]\nlemmas finter_lower2 = Int_lower2[Transfer.transferred]\nlemmas finter_greatest = Int_greatest[Transfer.transferred]\nlemmas fminus_fsubset = Diff_subset[Transfer.transferred]\nlemmas fminus_fsubset_conv = Diff_subset_conv[Transfer.transferred]\nlemmas fsubset_fempty[simp] = subset_empty[Transfer.transferred]\nlemmas not_pfsubset_fempty[iff] = not_psubset_empty[Transfer.transferred]\nlemmas finsert_is_funion = insert_is_Un[Transfer.transferred]\nlemmas finsert_not_fempty[simp] = insert_not_empty[Transfer.transferred]\nlemmas fempty_not_finsert = empty_not_insert[Transfer.transferred]\nlemmas finsert_absorb = insert_absorb[Transfer.transferred]\nlemmas finsert_absorb2[simp] = insert_absorb2[Transfer.transferred]\nlemmas finsert_commute = insert_commute[Transfer.transferred]\nlemmas finsert_fsubset[simp] = insert_subset[Transfer.transferred]\nlemmas finsert_inter_finsert[simp] = insert_inter_insert[Transfer.transferred]\nlemmas finsert_disjoint[simp,no_atp] = insert_disjoint[Transfer.transferred]\nlemmas disjoint_finsert[simp,no_atp] = disjoint_insert[Transfer.transferred]\nlemmas fimage_fempty[simp] = image_empty[Transfer.transferred]\nlemmas fimage_finsert[simp] = image_insert[Transfer.transferred]\nlemmas fimage_constant = image_constant[Transfer.transferred]\nlemmas fimage_constant_conv = image_constant_conv[Transfer.transferred]\nlemmas fimage_fimage = image_image[Transfer.transferred]\nlemmas finsert_fimage[simp] = insert_image[Transfer.transferred]\nlemmas fimage_is_fempty[iff] = image_is_empty[Transfer.transferred]\nlemmas fempty_is_fimage[iff] = empty_is_image[Transfer.transferred]\nlemmas fimage_cong = image_cong[Transfer.transferred]\nlemmas fimage_finter_fsubset = image_Int_subset[Transfer.transferred]\nlemmas fimage_fminus_fsubset = image_diff_subset[Transfer.transferred]\nlemmas finter_absorb = Int_absorb[Transfer.transferred]\nlemmas finter_left_absorb = Int_left_absorb[Transfer.transferred]\nlemmas finter_commute = Int_commute[Transfer.transferred]\nlemmas finter_left_commute = Int_left_commute[Transfer.transferred]\nlemmas finter_assoc = Int_assoc[Transfer.transferred]\nlemmas finter_ac = Int_ac[Transfer.transferred]\nlemmas finter_absorb1 = Int_absorb1[Transfer.transferred]\nlemmas finter_absorb2 = Int_absorb2[Transfer.transferred]\nlemmas finter_fempty_left = Int_empty_left[Transfer.transferred]\nlemmas finter_fempty_right = Int_empty_right[Transfer.transferred]\nlemmas disjoint_iff_fnot_equal = disjoint_iff_not_equal[Transfer.transferred]\nlemmas finter_funion_distrib = Int_Un_distrib[Transfer.transferred]\nlemmas finter_funion_distrib2 = Int_Un_distrib2[Transfer.transferred]\nlemmas finter_fsubset_iff[no_atp, simp] = Int_subset_iff[Transfer.transferred]\nlemmas funion_absorb = Un_absorb[Transfer.transferred]\nlemmas funion_left_absorb = Un_left_absorb[Transfer.transferred]\nlemmas funion_commute = Un_commute[Transfer.transferred]\nlemmas funion_left_commute = Un_left_commute[Transfer.transferred]\nlemmas funion_assoc = Un_assoc[Transfer.transferred]\nlemmas funion_ac = Un_ac[Transfer.transferred]\nlemmas funion_absorb1 = Un_absorb1[Transfer.transferred]\nlemmas funion_absorb2 = Un_absorb2[Transfer.transferred]\nlemmas funion_fempty_left = Un_empty_left[Transfer.transferred]\nlemmas funion_fempty_right = Un_empty_right[Transfer.transferred]\nlemmas funion_finsert_left[simp] = Un_insert_left[Transfer.transferred]\nlemmas funion_finsert_right[simp] = Un_insert_right[Transfer.transferred]\nlemmas finter_finsert_left = Int_insert_left[Transfer.transferred]\nlemmas finter_finsert_left_ifffempty[simp] = Int_insert_left_if0[Transfer.transferred]\nlemmas finter_finsert_left_if1[simp] = Int_insert_left_if1[Transfer.transferred]\nlemmas finter_finsert_right = Int_insert_right[Transfer.transferred]\nlemmas finter_finsert_right_ifffempty[simp] = Int_insert_right_if0[Transfer.transferred]\nlemmas finter_finsert_right_if1[simp] = Int_insert_right_if1[Transfer.transferred]\nlemmas funion_finter_distrib = Un_Int_distrib[Transfer.transferred]\nlemmas funion_finter_distrib2 = Un_Int_distrib2[Transfer.transferred]\nlemmas funion_finter_crazy = Un_Int_crazy[Transfer.transferred]\nlemmas fsubset_funion_eq = subset_Un_eq[Transfer.transferred]\nlemmas funion_fempty[iff] = Un_empty[Transfer.transferred]\nlemmas funion_fsubset_iff[no_atp, simp] = Un_subset_iff[Transfer.transferred]\nlemmas funion_fminus_finter = Un_Diff_Int[Transfer.transferred]\nlemmas ffunion_empty[simp] = Union_empty[Transfer.transferred]\nlemmas ffunion_mono = Union_mono[Transfer.transferred]\nlemmas ffunion_insert[simp] = Union_insert[Transfer.transferred]\nlemmas fminus_finter2 = Diff_Int2[Transfer.transferred]\nlemmas funion_finter_assoc_eq = Un_Int_assoc_eq[Transfer.transferred]\nlemmas fBall_funion = ball_Un[Transfer.transferred]\nlemmas fBex_funion = bex_Un[Transfer.transferred]\nlemmas fminus_eq_fempty_iff[simp,no_atp] = Diff_eq_empty_iff[Transfer.transferred]\nlemmas fminus_cancel[simp] = Diff_cancel[Transfer.transferred]\nlemmas fminus_idemp[simp] = Diff_idemp[Transfer.transferred]\nlemmas fminus_triv = Diff_triv[Transfer.transferred]\nlemmas fempty_fminus[simp] = empty_Diff[Transfer.transferred]\nlemmas fminus_fempty[simp] = Diff_empty[Transfer.transferred]\nlemmas fminus_finsertffempty[simp,no_atp] = Diff_insert0[Transfer.transferred]\nlemmas fminus_finsert = Diff_insert[Transfer.transferred]\nlemmas fminus_finsert2 = Diff_insert2[Transfer.transferred]\nlemmas finsert_fminus_if = insert_Diff_if[Transfer.transferred]\nlemmas finsert_fminus1[simp] = insert_Diff1[Transfer.transferred]\nlemmas finsert_fminus_single[simp] = insert_Diff_single[Transfer.transferred]\nlemmas finsert_fminus = insert_Diff[Transfer.transferred]\nlemmas fminus_finsert_absorb = Diff_insert_absorb[Transfer.transferred]\nlemmas fminus_disjoint[simp] = Diff_disjoint[Transfer.transferred]\nlemmas fminus_partition = Diff_partition[Transfer.transferred]\nlemmas double_fminus = double_diff[Transfer.transferred]\nlemmas funion_fminus_cancel[simp] = Un_Diff_cancel[Transfer.transferred]\nlemmas funion_fminus_cancel2[simp] = Un_Diff_cancel2[Transfer.transferred]\nlemmas fminus_funion = Diff_Un[Transfer.transferred]\nlemmas fminus_finter = Diff_Int[Transfer.transferred]\nlemmas funion_fminus = Un_Diff[Transfer.transferred]\nlemmas finter_fminus = Int_Diff[Transfer.transferred]\nlemmas fminus_finter_distrib = Diff_Int_distrib[Transfer.transferred]\nlemmas fminus_finter_distrib2 = Diff_Int_distrib2[Transfer.transferred]\nlemmas fUNIV_bool[no_atp] = UNIV_bool[Transfer.transferred]\nlemmas fPow_fempty[simp] = Pow_empty[Transfer.transferred]\nlemmas fPow_finsert = Pow_insert[Transfer.transferred]\nlemmas funion_fPow_fsubset = Un_Pow_subset[Transfer.transferred]\nlemmas fPow_finter_eq[simp] = Pow_Int_eq[Transfer.transferred]\nlemmas fset_eq_fsubset = set_eq_subset[Transfer.transferred]\nlemmas fsubset_iff[no_atp] = subset_iff[Transfer.transferred]\nlemmas fsubset_iff_pfsubset_eq = subset_iff_psubset_eq[Transfer.transferred]\nlemmas all_not_fin_conv[simp] = all_not_in_conv[Transfer.transferred]\nlemmas ex_fin_conv = ex_in_conv[Transfer.transferred]\nlemmas fimage_mono = image_mono[Transfer.transferred]\nlemmas fPow_mono = Pow_mono[Transfer.transferred]\nlemmas finsert_mono = insert_mono[Transfer.transferred]\nlemmas funion_mono = Un_mono[Transfer.transferred]\nlemmas finter_mono = Int_mono[Transfer.transferred]\nlemmas fminus_mono = Diff_mono[Transfer.transferred]\nlemmas fin_mono = in_mono[Transfer.transferred]\nlemmas fthe_felem_eq[simp] = the_elem_eq[Transfer.transferred]\nlemmas fLeast_mono = Least_mono[Transfer.transferred]\nlemmas fbind_fbind = bind_bind[Transfer.transferred]\nlemmas fempty_fbind[simp] = empty_bind[Transfer.transferred]\nlemmas nonfempty_fbind_const = nonempty_bind_const[Transfer.transferred]\nlemmas fbind_const = bind_const[Transfer.transferred]\nlemmas ffmember_filter[simp] = member_filter[Transfer.transferred]\nlemmas fequalityI = equalityI[Transfer.transferred]\nlemmas fset_of_list_simps[simp] = set_simps[Transfer.transferred]\nlemmas fset_of_list_append[simp] = set_append[Transfer.transferred]\nlemmas fset_of_list_rev[simp] = set_rev[Transfer.transferred]\nlemmas fset_of_list_map[simp] = set_map[Transfer.transferred]\n\n\nsubsection \\<open>Additional lemmas\\<close>\n\nsubsubsection \\<open>\\<open>ffUnion\\<close>\\<close>\n\nlemmas ffUnion_funion_distrib[simp] = Union_Un_distrib[Transfer.transferred]\n\n\nsubsubsection \\<open>\\<open>fbind\\<close>\\<close>\n\nlemma fbind_cong[fundef_cong]: \"A = B \\<Longrightarrow> (\\<And>x. x |\\<in>| B \\<Longrightarrow> f x = g x) \\<Longrightarrow> fbind A f = fbind B g\"\nby transfer force\n\n\nsubsubsection \\<open>\\<open>fsingleton\\<close>\\<close>\n\nlemmas fsingletonE = fsingletonD [elim_format]\n\n\nsubsubsection \\<open>\\<open>femepty\\<close>\\<close>\n\nlemma fempty_ffilter[simp]: \"ffilter (\\<lambda>_. False) A = {||}\"\nby transfer auto\n\n(* FIXME, transferred doesn't work here *)\nlemma femptyE [elim!]: \"a |\\<in>| {||} \\<Longrightarrow> P\"\n  by simp\n\n\nsubsubsection \\<open>\\<open>fset\\<close>\\<close>\n\nlemmas fset_simps[simp] = bot_fset.rep_eq finsert.rep_eq\n\nlemma finite_fset [simp]:\n  shows \"finite (fset S)\"\n  by transfer simp\n\nlemmas fset_cong = fset_inject\n\nlemma filter_fset [simp]:\n  shows \"fset (ffilter P xs) = Collect P \\<inter> fset xs\"\n  by transfer auto\n\nlemma notin_fset: \"x |\\<notin>| S \\<longleftrightarrow> x \\<notin> fset S\"\n  by (simp add: fmember_iff_member_fset)\n\nlemmas inter_fset[simp] = inf_fset.rep_eq\n\nlemmas union_fset[simp] = sup_fset.rep_eq\n\nlemmas minus_fset[simp] = minus_fset.rep_eq\n\n\nsubsubsection \\<open>\\<open>ffilter\\<close>\\<close>\n\nlemma subset_ffilter:\n  \"ffilter P A |\\<subseteq>| ffilter Q A = (\\<forall> x. x |\\<in>| A \\<longrightarrow> P x \\<longrightarrow> Q x)\"\n  by transfer auto\n\nlemma eq_ffilter:\n  \"(ffilter P A = ffilter Q A) = (\\<forall>x. x |\\<in>| A \\<longrightarrow> P x = Q x)\"\n  by transfer auto\n\nlemma pfsubset_ffilter:\n  \"(\\<And>x. x |\\<in>| A \\<Longrightarrow> P x \\<Longrightarrow> Q x) \\<Longrightarrow> (x |\\<in>| A \\<and> \\<not> P x \\<and> Q x) \\<Longrightarrow>\n    ffilter P A |\\<subset>| ffilter Q A\"\n  unfolding less_fset_def by (auto simp add: subset_ffilter eq_ffilter)\n\n\nsubsubsection \\<open>\\<open>fset_of_list\\<close>\\<close>\n\nlemma fset_of_list_filter[simp]:\n  \"fset_of_list (filter P xs) = ffilter P (fset_of_list xs)\"\n  by transfer (auto simp: Set.filter_def)\n\nlemma fset_of_list_subset[intro]:\n  \"set xs \\<subseteq> set ys \\<Longrightarrow> fset_of_list xs |\\<subseteq>| fset_of_list ys\"\n  by transfer simp\n\nlemma fset_of_list_elem: \"(x |\\<in>| fset_of_list xs) \\<longleftrightarrow> (x \\<in> set xs)\"\n  by transfer simp\n\n\nsubsubsection \\<open>\\<open>finsert\\<close>\\<close>\n\n(* FIXME, transferred doesn't work here *)\nlemma set_finsert:\n  assumes \"x |\\<in>| A\"\n  obtains B where \"A = finsert x B\" and \"x |\\<notin>| B\"\nusing assms by transfer (metis Set.set_insert finite_insert)\n\nlemma mk_disjoint_finsert: \"a |\\<in>| A \\<Longrightarrow> \\<exists>B. A = finsert a B \\<and> a |\\<notin>| B\"\n  by (rule exI [where x = \"A |-| {|a|}\"]) blast\n\nlemma finsert_eq_iff:\n  assumes \"a |\\<notin>| A\" and \"b |\\<notin>| B\"\n  shows \"(finsert a A = finsert b B) =\n    (if a = b then A = B else \\<exists>C. A = finsert b C \\<and> b |\\<notin>| C \\<and> B = finsert a C \\<and> a |\\<notin>| C)\"\n  using assms by transfer (force simp: insert_eq_iff)\n\n\nsubsubsection \\<open>\\<open>fimage\\<close>\\<close>\n\nlemma subset_fimage_iff: \"(B |\\<subseteq>| f|`|A) = (\\<exists> AA. AA |\\<subseteq>| A \\<and> B = f|`|AA)\"\nby transfer (metis mem_Collect_eq rev_finite_subset subset_image_iff)\n\nlemma fimage_strict_mono:\n  assumes \"inj_on f (fset B)\" and \"A |\\<subset>| B\"\n  shows \"f |`| A |\\<subset>| f |`| B\"\n  \\<comment> \\<open>TODO: Configure transfer framework to lift @{thm Fun.image_strict_mono}.\\<close>\nproof (rule pfsubsetI)\n  from \\<open>A |\\<subset>| B\\<close> have \"A |\\<subseteq>| B\"\n    by (rule pfsubset_imp_fsubset)\n  thus \"f |`| A |\\<subseteq>| f |`| B\"\n    by (rule fimage_mono)\nnext\n  from \\<open>A |\\<subset>| B\\<close> have \"A |\\<subseteq>| B\" and \"A \\<noteq> B\"\n    by (simp_all add: pfsubset_eq)\n\n  have \"fset A \\<noteq> fset B\"\n    using \\<open>A \\<noteq> B\\<close>\n    by (simp add: fset_cong)\n  hence \"f ` fset A \\<noteq> f ` fset B\"\n    using \\<open>A |\\<subseteq>| B\\<close>\n    by (simp add: inj_on_image_eq_iff[OF \\<open>inj_on f (fset B)\\<close>] less_eq_fset.rep_eq)\n  hence \"fset (f |`| A) \\<noteq> fset (f |`| B)\"\n    by (simp add: fimage.rep_eq)\n  thus \"f |`| A \\<noteq> f |`| B\"\n    by (simp add: fset_cong)\nqed\n\n\nsubsubsection \\<open>bounded quantification\\<close>\n\nlemma bex_simps [simp, no_atp]:\n  \"\\<And>A P Q. fBex A (\\<lambda>x. P x \\<and> Q) = (fBex A P \\<and> Q)\"\n  \"\\<And>A P Q. fBex A (\\<lambda>x. P \\<and> Q x) = (P \\<and> fBex A Q)\"\n  \"\\<And>P. fBex {||} P = False\"\n  \"\\<And>a B P. fBex (finsert a B) P = (P a \\<or> fBex B P)\"\n  \"\\<And>A P f. fBex (f |`| A) P = fBex A (\\<lambda>x. P (f x))\"\n  \"\\<And>A P. (\\<not> fBex A P) = fBall A (\\<lambda>x. \\<not> P x)\"\nby auto\n\nlemma ball_simps [simp, no_atp]:\n  \"\\<And>A P Q. fBall A (\\<lambda>x. P x \\<or> Q) = (fBall A P \\<or> Q)\"\n  \"\\<And>A P Q. fBall A (\\<lambda>x. P \\<or> Q x) = (P \\<or> fBall A Q)\"\n  \"\\<And>A P Q. fBall A (\\<lambda>x. P \\<longrightarrow> Q x) = (P \\<longrightarrow> fBall A Q)\"\n  \"\\<And>A P Q. fBall A (\\<lambda>x. P x \\<longrightarrow> Q) = (fBex A P \\<longrightarrow> Q)\"\n  \"\\<And>P. fBall {||} P = True\"\n  \"\\<And>a B P. fBall (finsert a B) P = (P a \\<and> fBall B P)\"\n  \"\\<And>A P f. fBall (f |`| A) P = fBall A (\\<lambda>x. P (f x))\"\n  \"\\<And>A P. (\\<not> fBall A P) = fBex A (\\<lambda>x. \\<not> P x)\"\nby auto\n\nlemma atomize_fBall:\n    \"(\\<And>x. x |\\<in>| A ==> P x) == Trueprop (fBall A (\\<lambda>x. P x))\"\napply (simp only: atomize_all atomize_imp)\napply (rule equal_intr_rule)\n  by (transfer, simp)+\n\nlemma fBall_mono[mono]: \"P \\<le> Q \\<Longrightarrow> fBall S P \\<le> fBall S Q\"\nby auto\n\nlemma fBex_mono[mono]: \"P \\<le> Q \\<Longrightarrow> fBex S P \\<le> fBex S Q\"\nby auto\n\nend\n\n\nsubsubsection \\<open>\\<open>fcard\\<close>\\<close>\n\n(* FIXME: improve transferred to handle bounded meta quantification *)\n\nlemma fcard_fempty:\n  \"fcard {||} = 0\"\n  by transfer (rule card.empty)\n\nlemma fcard_finsert_disjoint:\n  \"x |\\<notin>| A \\<Longrightarrow> fcard (finsert x A) = Suc (fcard A)\"\n  by transfer (rule card_insert_disjoint)\n\nlemma fcard_finsert_if:\n  \"fcard (finsert x A) = (if x |\\<in>| A then fcard A else Suc (fcard A))\"\n  by transfer (rule card_insert_if)\n\nlemma fcard_0_eq [simp, no_atp]:\n  \"fcard A = 0 \\<longleftrightarrow> A = {||}\"\n  by transfer (rule card_0_eq)\n\nlemma fcard_Suc_fminus1:\n  \"x |\\<in>| A \\<Longrightarrow> Suc (fcard (A |-| {|x|})) = fcard A\"\n  by transfer (rule card_Suc_Diff1)\n\nlemma fcard_fminus_fsingleton:\n  \"x |\\<in>| A \\<Longrightarrow> fcard (A |-| {|x|}) = fcard A - 1\"\n  by transfer (rule card_Diff_singleton)\n\nlemma fcard_fminus_fsingleton_if:\n  \"fcard (A |-| {|x|}) = (if x |\\<in>| A then fcard A - 1 else fcard A)\"\n  by transfer (rule card_Diff_singleton_if)\n\nlemma fcard_fminus_finsert[simp]:\n  assumes \"a |\\<in>| A\" and \"a |\\<notin>| B\"\n  shows \"fcard (A |-| finsert a B) = fcard (A |-| B) - 1\"\nusing assms by transfer (rule card_Diff_insert)\n\nlemma fcard_finsert: \"fcard (finsert x A) = Suc (fcard (A |-| {|x|}))\"\nby transfer (rule card.insert_remove)\n\nlemma fcard_finsert_le: \"fcard A \\<le> fcard (finsert x A)\"\nby transfer (rule card_insert_le)\n\nlemma fcard_mono:\n  \"A |\\<subseteq>| B \\<Longrightarrow> fcard A \\<le> fcard B\"\nby transfer (rule card_mono)\n\nlemma fcard_seteq: \"A |\\<subseteq>| B \\<Longrightarrow> fcard B \\<le> fcard A \\<Longrightarrow> A = B\"\nby transfer (rule card_seteq)\n\nlemma pfsubset_fcard_mono: \"A |\\<subset>| B \\<Longrightarrow> fcard A < fcard B\"\nby transfer (rule psubset_card_mono)\n\nlemma fcard_funion_finter:\n  \"fcard A + fcard B = fcard (A |\\<union>| B) + fcard (A |\\<inter>| B)\"\nby transfer (rule card_Un_Int)\n\nlemma fcard_funion_disjoint:\n  \"A |\\<inter>| B = {||} \\<Longrightarrow> fcard (A |\\<union>| B) = fcard A + fcard B\"\nby transfer (rule card_Un_disjoint)\n\nlemma fcard_funion_fsubset:\n  \"B |\\<subseteq>| A \\<Longrightarrow> fcard (A |-| B) = fcard A - fcard B\"\nby transfer (rule card_Diff_subset)\n\nlemma diff_fcard_le_fcard_fminus:\n  \"fcard A - fcard B \\<le> fcard(A |-| B)\"\nby transfer (rule diff_card_le_card_Diff)\n\nlemma fcard_fminus1_less: \"x |\\<in>| A \\<Longrightarrow> fcard (A |-| {|x|}) < fcard A\"\nby transfer (rule card_Diff1_less)\n\nlemma fcard_fminus2_less:\n  \"x |\\<in>| A \\<Longrightarrow> y |\\<in>| A \\<Longrightarrow> fcard (A |-| {|x|} |-| {|y|}) < fcard A\"\nby transfer (rule card_Diff2_less)\n\nlemma fcard_fminus1_le: \"fcard (A |-| {|x|}) \\<le> fcard A\"\nby transfer (rule card_Diff1_le)\n\nlemma fcard_pfsubset: \"A |\\<subseteq>| B \\<Longrightarrow> fcard A < fcard B \\<Longrightarrow> A < B\"\nby transfer (rule card_psubset)\n\n\nsubsubsection \\<open>\\<open>sorted_list_of_fset\\<close>\\<close>\n\nlemma sorted_list_of_fset_simps[simp]:\n  \"set (sorted_list_of_fset S) = fset S\"\n  \"fset_of_list (sorted_list_of_fset S) = S\"\nby (transfer, simp)+\n\n\nsubsubsection \\<open>\\<open>ffold\\<close>\\<close>\n\n(* FIXME: improve transferred to handle bounded meta quantification *)\n\ncontext comp_fun_commute\nbegin\n  lemmas ffold_empty[simp] = fold_empty[Transfer.transferred]\n\n  lemma ffold_finsert [simp]:\n    assumes \"x |\\<notin>| A\"\n    shows \"ffold f z (finsert x A) = f x (ffold f z A)\"\n    using assms by (transfer fixing: f) (rule fold_insert)\n\n  lemma ffold_fun_left_comm:\n    \"f x (ffold f z A) = ffold f (f x z) A\"\n    by (transfer fixing: f) (rule fold_fun_left_comm)\n\n  lemma ffold_finsert2:\n    \"x |\\<notin>| A \\<Longrightarrow> ffold f z (finsert x A) = ffold f (f x z) A\"\n    by (transfer fixing: f) (rule fold_insert2)\n\n  lemma ffold_rec:\n    assumes \"x |\\<in>| A\"\n    shows \"ffold f z A = f x (ffold f z (A |-| {|x|}))\"\n    using assms by (transfer fixing: f) (rule fold_rec)\n\n  lemma ffold_finsert_fremove:\n    \"ffold f z (finsert x A) = f x (ffold f z (A |-| {|x|}))\"\n     by (transfer fixing: f) (rule fold_insert_remove)\nend\n\nlemma ffold_fimage:\n  assumes \"inj_on g (fset A)\"\n  shows \"ffold f z (g |`| A) = ffold (f \\<circ> g) z A\"\nusing assms by transfer' (rule fold_image)\n\nlemma ffold_cong:\n  assumes \"comp_fun_commute f\" \"comp_fun_commute g\"\n  \"\\<And>x. x |\\<in>| A \\<Longrightarrow> f x = g x\"\n    and \"s = t\" and \"A = B\"\n  shows \"ffold f s A = ffold g t B\"\n  using assms[unfolded comp_fun_commute_def']\n  by transfer (meson Finite_Set.fold_cong subset_UNIV)\n\ncontext comp_fun_idem\nbegin\n\n  lemma ffold_finsert_idem:\n    \"ffold f z (finsert x A) = f x (ffold f z A)\"\n    by (transfer fixing: f) (rule fold_insert_idem)\n\n  declare ffold_finsert [simp del] ffold_finsert_idem [simp]\n\n  lemma ffold_finsert_idem2:\n    \"ffold f z (finsert x A) = ffold f (f x z) A\"\n    by (transfer fixing: f) (rule fold_insert_idem2)\n\nend\n\n\nsubsubsection \\<open>@{term fsubset}\\<close>\n\nlemma wfP_pfsubset: \"wfP (|\\<subset>|)\"\nproof (rule wfP_if_convertible_to_nat)\n  show \"\\<And>x y. x |\\<subset>| y \\<Longrightarrow> fcard x < fcard y\"\n    by (rule pfsubset_fcard_mono)\nqed\n\n\nsubsubsection \\<open>Group operations\\<close>\n\nlocale comm_monoid_fset = comm_monoid\nbegin\n\nsublocale set: comm_monoid_set ..\n\nlift_definition F :: \"('b \\<Rightarrow> 'a) \\<Rightarrow> 'b fset \\<Rightarrow> 'a\" is set.F .\n\nlemmas cong[fundef_cong] = set.cong[Transfer.transferred]\n\nlemma cong_simp[cong]:\n  \"\\<lbrakk> A = B;  \\<And>x. x |\\<in>| B =simp=> g x = h x \\<rbrakk> \\<Longrightarrow> F g A = F h B\"\nunfolding simp_implies_def by (auto cong: cong)\n\nend\n\ncontext comm_monoid_add begin\n\nsublocale fsum: comm_monoid_fset plus 0\n  rewrites \"comm_monoid_set.F plus 0 = sum\"\n  defines fsum = fsum.F\nproof -\n  show \"comm_monoid_fset (+) 0\" by standard\n\n  show \"comm_monoid_set.F (+) 0 = sum\" unfolding sum_def ..\nqed\n\nend\n\n\nsubsubsection \\<open>Semilattice operations\\<close>\n\nlocale semilattice_fset = semilattice\nbegin\n\nsublocale set: semilattice_set ..\n\nlift_definition F :: \"'a fset \\<Rightarrow> 'a\" is set.F .\n\nlemma eq_fold: \"F (finsert x A) = ffold f x A\"\n  by transfer (rule set.eq_fold)\n\nlemma singleton [simp]: \"F {|x|} = x\"\n  by transfer (rule set.singleton)\n\nlemma insert_not_elem: \"x |\\<notin>| A \\<Longrightarrow> A \\<noteq> {||} \\<Longrightarrow> F (finsert x A) = x \\<^bold>* F A\"\n  by transfer (rule set.insert_not_elem)\n\nlemma in_idem: \"x |\\<in>| A \\<Longrightarrow> x \\<^bold>* F A = F A\"\n  by transfer (rule set.in_idem)\n\nlemma insert [simp]: \"A \\<noteq> {||} \\<Longrightarrow> F (finsert x A) = x \\<^bold>* F A\"\n  by transfer (rule set.insert)\n\nend\n\nlocale semilattice_order_fset = binary?: semilattice_order + semilattice_fset\nbegin\n\nend\n\n\ncontext linorder begin\n\nsublocale fMin: semilattice_order_fset min less_eq less\n  rewrites \"semilattice_set.F min = Min\"\n  defines fMin = fMin.F\nproof -\n  show \"semilattice_order_fset min (\\<le>) (<)\" by standard\n\n  show \"semilattice_set.F min = Min\" unfolding Min_def ..\nqed\n\nsublocale fMax: semilattice_order_fset max greater_eq greater\n  rewrites \"semilattice_set.F max = Max\"\n  defines fMax = fMax.F\nproof -\n  show \"semilattice_order_fset max (\\<ge>) (>)\"\n    by standard\n\n  show \"semilattice_set.F max = Max\"\n    unfolding Max_def ..\nqed\n\nend\n\nlemma mono_fMax_commute: \"mono f \\<Longrightarrow> A \\<noteq> {||} \\<Longrightarrow> f (fMax A) = fMax (f |`| A)\"\n  by transfer (rule mono_Max_commute)\n\nlemma mono_fMin_commute: \"mono f \\<Longrightarrow> A \\<noteq> {||} \\<Longrightarrow> f (fMin A) = fMin (f |`| A)\"\n  by transfer (rule mono_Min_commute)\n\nlemma fMax_in[simp]: \"A \\<noteq> {||} \\<Longrightarrow> fMax A |\\<in>| A\"\n  by transfer (rule Max_in)\n\nlemma fMin_in[simp]: \"A \\<noteq> {||} \\<Longrightarrow> fMin A |\\<in>| A\"\n  by transfer (rule Min_in)\n\nlemma fMax_ge[simp]: \"x |\\<in>| A \\<Longrightarrow> x \\<le> fMax A\"\n  by transfer (rule Max_ge)\n\nlemma fMin_le[simp]: \"x |\\<in>| A \\<Longrightarrow> fMin A \\<le> x\"\n  by transfer (rule Min_le)\n\nlemma fMax_eqI: \"(\\<And>y. y |\\<in>| A \\<Longrightarrow> y \\<le> x) \\<Longrightarrow> x |\\<in>| A \\<Longrightarrow> fMax A = x\"\n  by transfer (rule Max_eqI)\n\nlemma fMin_eqI: \"(\\<And>y. y |\\<in>| A \\<Longrightarrow> x \\<le> y) \\<Longrightarrow> x |\\<in>| A \\<Longrightarrow> fMin A = x\"\n  by transfer (rule Min_eqI)\n\nlemma fMax_finsert[simp]: \"fMax (finsert x A) = (if A = {||} then x else max x (fMax A))\"\n  by transfer simp\n\nlemma fMin_finsert[simp]: \"fMin (finsert x A) = (if A = {||} then x else min x (fMin A))\"\n  by transfer simp\n\ncontext linorder begin\n\nlemma fset_linorder_max_induct[case_names fempty finsert]:\n  assumes \"P {||}\"\n  and     \"\\<And>x S. \\<lbrakk>\\<forall>y. y |\\<in>| S \\<longrightarrow> y < x; P S\\<rbrakk> \\<Longrightarrow> P (finsert x S)\"\n  shows \"P S\"\nproof -\n  (* FIXME transfer and right_total vs. bi_total *)\n  note Domainp_forall_transfer[transfer_rule]\n  show ?thesis\n  using assms by (transfer fixing: less) (auto intro: finite_linorder_max_induct)\nqed\n\nlemma fset_linorder_min_induct[case_names fempty finsert]:\n  assumes \"P {||}\"\n  and     \"\\<And>x S. \\<lbrakk>\\<forall>y. y |\\<in>| S \\<longrightarrow> y > x; P S\\<rbrakk> \\<Longrightarrow> P (finsert x S)\"\n  shows \"P S\"\nproof -\n  (* FIXME transfer and right_total vs. bi_total *)\n  note Domainp_forall_transfer[transfer_rule]\n  show ?thesis\n  using assms by (transfer fixing: less) (auto intro: finite_linorder_min_induct)\nqed\n\nend\n\n\nsubsection \\<open>Choice in fsets\\<close>\n\nlemma fset_choice:\n  assumes \"\\<forall>x. x |\\<in>| A \\<longrightarrow> (\\<exists>y. P x y)\"\n  shows \"\\<exists>f. \\<forall>x. x |\\<in>| A \\<longrightarrow> P x (f x)\"\n  using assms by transfer metis\n\n\nsubsection \\<open>Induction and Cases rules for fsets\\<close>\n\nlemma fset_exhaust [case_names empty insert, cases type: fset]:\n  assumes fempty_case: \"S = {||} \\<Longrightarrow> P\"\n  and     finsert_case: \"\\<And>x S'. S = finsert x S' \\<Longrightarrow> P\"\n  shows \"P\"\n  using assms by transfer blast\n\nlemma fset_induct [case_names empty insert]:\n  assumes fempty_case: \"P {||}\"\n  and     finsert_case: \"\\<And>x S. P S \\<Longrightarrow> P (finsert x S)\"\n  shows \"P S\"\nproof -\n  (* FIXME transfer and right_total vs. bi_total *)\n  note Domainp_forall_transfer[transfer_rule]\n  show ?thesis\n  using assms by transfer (auto intro: finite_induct)\nqed\n\nlemma fset_induct_stronger [case_names empty insert, induct type: fset]:\n  assumes empty_fset_case: \"P {||}\"\n  and     insert_fset_case: \"\\<And>x S. \\<lbrakk>x |\\<notin>| S; P S\\<rbrakk> \\<Longrightarrow> P (finsert x S)\"\n  shows \"P S\"\nproof -\n  (* FIXME transfer and right_total vs. bi_total *)\n  note Domainp_forall_transfer[transfer_rule]\n  show ?thesis\n  using assms by transfer (auto intro: finite_induct)\nqed\n\nlemma fset_card_induct:\n  assumes empty_fset_case: \"P {||}\"\n  and     card_fset_Suc_case: \"\\<And>S T. Suc (fcard S) = (fcard T) \\<Longrightarrow> P S \\<Longrightarrow> P T\"\n  shows \"P S\"\nproof (induct S)\n  case empty\n  show \"P {||}\" by (rule empty_fset_case)\nnext\n  case (insert x S)\n  have h: \"P S\" by fact\n  have \"x |\\<notin>| S\" by fact\n  then have \"Suc (fcard S) = fcard (finsert x S)\"\n    by transfer auto\n  then show \"P (finsert x S)\"\n    using h card_fset_Suc_case by simp\nqed\n\nlemma fset_strong_cases:\n  obtains \"xs = {||}\"\n    | ys x where \"x |\\<notin>| ys\" and \"xs = finsert x ys\"\nby transfer blast\n\nlemma fset_induct2:\n  \"P {||} {||} \\<Longrightarrow>\n  (\\<And>x xs. x |\\<notin>| xs \\<Longrightarrow> P (finsert x xs) {||}) \\<Longrightarrow>\n  (\\<And>y ys. y |\\<notin>| ys \\<Longrightarrow> P {||} (finsert y ys)) \\<Longrightarrow>\n  (\\<And>x xs y ys. \\<lbrakk>P xs ys; x |\\<notin>| xs; y |\\<notin>| ys\\<rbrakk> \\<Longrightarrow> P (finsert x xs) (finsert y ys)) \\<Longrightarrow>\n  P xsa ysa\"\n  apply (induct xsa arbitrary: ysa)\n  apply (induct_tac x rule: fset_induct_stronger)\n  apply simp_all\n  apply (induct_tac xa rule: fset_induct_stronger)\n  apply simp_all\n  done\n\n\nsubsection \\<open>Setup for Lifting/Transfer\\<close>\n\nsubsubsection \\<open>Relator and predicator properties\\<close>\n\nlift_definition rel_fset :: \"('a \\<Rightarrow> 'b \\<Rightarrow> bool) \\<Rightarrow> 'a fset \\<Rightarrow> 'b fset \\<Rightarrow> bool\" is rel_set\nparametric rel_set_transfer .\n\nlemma rel_fset_alt_def: \"rel_fset R = (\\<lambda>A B. (\\<forall>x.\\<exists>y. x|\\<in>|A \\<longrightarrow> y|\\<in>|B \\<and> R x y)\n  \\<and> (\\<forall>y. \\<exists>x. y|\\<in>|B \\<longrightarrow> x|\\<in>|A \\<and> R x y))\"\napply (rule ext)+\napply transfer'\napply (subst rel_set_def[unfolded fun_eq_iff])\nby blast\n\nlemma finite_rel_set:\n  assumes fin: \"finite X\" \"finite Z\"\n  assumes R_S: \"rel_set (R OO S) X Z\"\n  shows \"\\<exists>Y. finite Y \\<and> rel_set R X Y \\<and> rel_set S Y Z\"\nproof -\n  obtain f where f: \"\\<forall>x\\<in>X. R x (f x) \\<and> (\\<exists>z\\<in>Z. S (f x) z)\"\n  apply atomize_elim\n  apply (subst bchoice_iff[symmetric])\n  using R_S[unfolded rel_set_def OO_def] by blast\n\n  obtain g where g: \"\\<forall>z\\<in>Z. S (g z) z \\<and> (\\<exists>x\\<in>X. R x (g z))\"\n  apply atomize_elim\n  apply (subst bchoice_iff[symmetric])\n  using R_S[unfolded rel_set_def OO_def] by blast\n\n  let ?Y = \"f ` X \\<union> g ` Z\"\n  have \"finite ?Y\" by (simp add: fin)\n  moreover have \"rel_set R X ?Y\"\n    unfolding rel_set_def\n    using f g by clarsimp blast\n  moreover have \"rel_set S ?Y Z\"\n    unfolding rel_set_def\n    using f g by clarsimp blast\n  ultimately show ?thesis by metis\nqed\n\nsubsubsection \\<open>Transfer rules for the Transfer package\\<close>\n\ntext \\<open>Unconditional transfer rules\\<close>\n\ncontext includes lifting_syntax\nbegin\n\nlemmas fempty_transfer [transfer_rule] = empty_transfer[Transfer.transferred]\n\nlemma finsert_transfer [transfer_rule]:\n  \"(A ===> rel_fset A ===> rel_fset A) finsert finsert\"\n  unfolding rel_fun_def rel_fset_alt_def by blast\n\nlemma funion_transfer [transfer_rule]:\n  \"(rel_fset A ===> rel_fset A ===> rel_fset A) funion funion\"\n  unfolding rel_fun_def rel_fset_alt_def by blast\n\nlemma ffUnion_transfer [transfer_rule]:\n  \"(rel_fset (rel_fset A) ===> rel_fset A) ffUnion ffUnion\"\n  unfolding rel_fun_def rel_fset_alt_def by transfer (simp, fast)\n\nlemma fimage_transfer [transfer_rule]:\n  \"((A ===> B) ===> rel_fset A ===> rel_fset B) fimage fimage\"\n  unfolding rel_fun_def rel_fset_alt_def by simp blast\n\nlemma fBall_transfer [transfer_rule]:\n  \"(rel_fset A ===> (A ===> (=)) ===> (=)) fBall fBall\"\n  unfolding rel_fset_alt_def rel_fun_def by blast\n\nlemma fBex_transfer [transfer_rule]:\n  \"(rel_fset A ===> (A ===> (=)) ===> (=)) fBex fBex\"\n  unfolding rel_fset_alt_def rel_fun_def by blast\n\n(* FIXME transfer doesn't work here *)\nlemma fPow_transfer [transfer_rule]:\n  \"(rel_fset A ===> rel_fset (rel_fset A)) fPow fPow\"\n  unfolding rel_fun_def\n  using Pow_transfer[unfolded rel_fun_def, rule_format, Transfer.transferred]\n  by blast\n\nlemma rel_fset_transfer [transfer_rule]:\n  \"((A ===> B ===> (=)) ===> rel_fset A ===> rel_fset B ===> (=))\n    rel_fset rel_fset\"\n  unfolding rel_fun_def\n  using rel_set_transfer[unfolded rel_fun_def,rule_format, Transfer.transferred, where A = A and B = B]\n  by simp\n\nlemma bind_transfer [transfer_rule]:\n  \"(rel_fset A ===> (A ===> rel_fset B) ===> rel_fset B) fbind fbind\"\n  unfolding rel_fun_def\n  using bind_transfer[unfolded rel_fun_def, rule_format, Transfer.transferred] by blast\n\ntext \\<open>Rules requiring bi-unique, bi-total or right-total relations\\<close>\n\nlemma fmember_transfer [transfer_rule]:\n  assumes \"bi_unique A\"\n  shows \"(A ===> rel_fset A ===> (=)) (|\\<in>|) (|\\<in>|)\"\n  using assms unfolding rel_fun_def rel_fset_alt_def bi_unique_def by metis\n\nlemma finter_transfer [transfer_rule]:\n  assumes \"bi_unique A\"\n  shows \"(rel_fset A ===> rel_fset A ===> rel_fset A) finter finter\"\n  using assms unfolding rel_fun_def\n  using inter_transfer[unfolded rel_fun_def, rule_format, Transfer.transferred] by blast\n\nlemma fminus_transfer [transfer_rule]:\n  assumes \"bi_unique A\"\n  shows \"(rel_fset A ===> rel_fset A ===> rel_fset A) (|-|) (|-|)\"\n  using assms unfolding rel_fun_def\n  using Diff_transfer[unfolded rel_fun_def, rule_format, Transfer.transferred] by blast\n\nlemma fsubset_transfer [transfer_rule]:\n  assumes \"bi_unique A\"\n  shows \"(rel_fset A ===> rel_fset A ===> (=)) (|\\<subseteq>|) (|\\<subseteq>|)\"\n  using assms unfolding rel_fun_def\n  using subset_transfer[unfolded rel_fun_def, rule_format, Transfer.transferred] by blast\n\nlemma fSup_transfer [transfer_rule]:\n  \"bi_unique A \\<Longrightarrow> (rel_set (rel_fset A) ===> rel_fset A) Sup Sup\"\n  unfolding rel_fun_def\n  apply clarify\n  apply transfer'\n  using Sup_fset_transfer[unfolded rel_fun_def] by blast\n\n(* FIXME: add right_total_fInf_transfer *)\n\nlemma fInf_transfer [transfer_rule]:\n  assumes \"bi_unique A\" and \"bi_total A\"\n  shows \"(rel_set (rel_fset A) ===> rel_fset A) Inf Inf\"\n  using assms unfolding rel_fun_def\n  apply clarify\n  apply transfer'\n  using Inf_fset_transfer[unfolded rel_fun_def] by blast\n\nlemma ffilter_transfer [transfer_rule]:\n  assumes \"bi_unique A\"\n  shows \"((A ===> (=)) ===> rel_fset A ===> rel_fset A) ffilter ffilter\"\n  using assms unfolding rel_fun_def\n  using Lifting_Set.filter_transfer[unfolded rel_fun_def, rule_format, Transfer.transferred] by blast\n\nlemma card_transfer [transfer_rule]:\n  \"bi_unique A \\<Longrightarrow> (rel_fset A ===> (=)) fcard fcard\"\n  unfolding rel_fun_def\n  using card_transfer[unfolded rel_fun_def, rule_format, Transfer.transferred] by blast\n\nend\n\nlifting_update fset.lifting\nlifting_forget fset.lifting\n\n\nsubsection \\<open>BNF setup\\<close>\n\ncontext\nincludes fset.lifting\nbegin\n\nlemma rel_fset_alt:\n  \"rel_fset R a b \\<longleftrightarrow> (\\<forall>t \\<in> fset a. \\<exists>u \\<in> fset b. R t u) \\<and> (\\<forall>t \\<in> fset b. \\<exists>u \\<in> fset a. R u t)\"\nby transfer (simp add: rel_set_def)\n\nlemma fset_to_fset: \"finite A \\<Longrightarrow> fset (the_inv fset A) = A\"\napply (rule f_the_inv_into_f[unfolded inj_on_def])\napply (simp add: fset_inject)\napply (rule range_eqI Abs_fset_inverse[symmetric] CollectI)+\n.\n\nlemma rel_fset_aux:\n\"(\\<forall>t \\<in> fset a. \\<exists>u \\<in> fset b. R t u) \\<and> (\\<forall>u \\<in> fset b. \\<exists>t \\<in> fset a. R t u) \\<longleftrightarrow>\n ((BNF_Def.Grp {a. fset a \\<subseteq> {(a, b). R a b}} (fimage fst))\\<inverse>\\<inverse> OO\n  BNF_Def.Grp {a. fset a \\<subseteq> {(a, b). R a b}} (fimage snd)) a b\" (is \"?L = ?R\")\nproof\n  assume ?L\n  define R' where \"R' =\n    the_inv fset (Collect (case_prod R) \\<inter> (fset a \\<times> fset b))\" (is \"_ = the_inv fset ?L'\")\n  have \"finite ?L'\" by (intro finite_Int[OF disjI2] finite_cartesian_product) (transfer, simp)+\n  hence *: \"fset R' = ?L'\" unfolding R'_def by (intro fset_to_fset)\n  show ?R unfolding Grp_def relcompp.simps conversep.simps\n  proof (intro CollectI case_prodI exI[of _ a] exI[of _ b] exI[of _ R'] conjI refl)\n    from * show \"a = fimage fst R'\" using conjunct1[OF \\<open>?L\\<close>]\n      by (transfer, auto simp add: image_def Int_def split: prod.splits)\n    from * show \"b = fimage snd R'\" using conjunct2[OF \\<open>?L\\<close>]\n      by (transfer, auto simp add: image_def Int_def split: prod.splits)\n  qed (auto simp add: *)\nnext\n  assume ?R thus ?L unfolding Grp_def relcompp.simps conversep.simps\n  apply (simp add: subset_eq Ball_def)\n  apply (rule conjI)\n  apply (transfer, clarsimp, metis snd_conv)\n  by (transfer, clarsimp, metis fst_conv)\nqed\n\nbnf \"'a fset\"\n  map: fimage\n  sets: fset\n  bd: natLeq\n  wits: \"{||}\"\n  rel: rel_fset\napply -\n          apply transfer' apply simp\n         apply transfer' apply force\n        apply transfer apply force\n       apply transfer' apply force\n      apply (rule natLeq_card_order)\n       apply (rule natLeq_cinfinite)\n  apply (rule regularCard_natLeq)\n    apply transfer apply (metis finite_iff_ordLess_natLeq)\n   apply (fastforce simp: rel_fset_alt)\n apply (simp add: Grp_def relcompp.simps conversep.simps fun_eq_iff rel_fset_alt\n   rel_fset_aux[unfolded OO_Grp_alt])\napply transfer apply simp\ndone\n\nlemma rel_fset_fset: \"rel_set \\<chi> (fset A1) (fset A2) = rel_fset \\<chi> A1 A2\"\n  by transfer (rule refl)\n\nend\n\nlemmas [simp] = fset.map_comp fset.map_id fset.set_map\n\n\nsubsection \\<open>Size setup\\<close>\n\ncontext includes fset.lifting begin\nlift_definition size_fset :: \"('a \\<Rightarrow> nat) \\<Rightarrow> 'a fset \\<Rightarrow> nat\" is \"\\<lambda>f. sum (Suc \\<circ> f)\" .\nend\n\ninstantiation fset :: (type) size begin\ndefinition size_fset where\n  size_fset_overloaded_def: \"size_fset = FSet.size_fset (\\<lambda>_. 0)\"\ninstance ..\nend\n\nlemmas size_fset_simps[simp] =\n  size_fset_def[THEN meta_eq_to_obj_eq, THEN fun_cong, THEN fun_cong,\n    unfolded map_fun_def comp_def id_apply]\n\nlemmas size_fset_overloaded_simps[simp] =\n  size_fset_simps[of \"\\<lambda>_. 0\", unfolded add_0_left add_0_right,\n    folded size_fset_overloaded_def]\n\nlemma fset_size_o_map: \"inj f \\<Longrightarrow> size_fset g \\<circ> fimage f = size_fset (g \\<circ> f)\"\n  apply (subst fun_eq_iff)\n  including fset.lifting by transfer (auto intro: sum.reindex_cong subset_inj_on)\n\nsetup \\<open>\nBNF_LFP_Size.register_size_global \\<^type_name>\\<open>fset\\<close> \\<^const_name>\\<open>size_fset\\<close>\n  @{thm size_fset_overloaded_def} @{thms size_fset_simps size_fset_overloaded_simps}\n  @{thms fset_size_o_map}\n\\<close>\n\nlifting_update fset.lifting\nlifting_forget fset.lifting\n\nsubsection \\<open>Advanced relator customization\\<close>\n\ntext \\<open>Set vs. sum relators:\\<close>\n\nlemma rel_set_rel_sum[simp]:\n\"rel_set (rel_sum \\<chi> \\<phi>) A1 A2 \\<longleftrightarrow>\n rel_set \\<chi> (Inl -` A1) (Inl -` A2) \\<and> rel_set \\<phi> (Inr -` A1) (Inr -` A2)\"\n(is \"?L \\<longleftrightarrow> ?Rl \\<and> ?Rr\")\nproof safe\n  assume L: \"?L\"\n  show ?Rl unfolding rel_set_def Bex_def vimage_eq proof safe\n    fix l1 assume \"Inl l1 \\<in> A1\"\n    then obtain a2 where a2: \"a2 \\<in> A2\" and \"rel_sum \\<chi> \\<phi> (Inl l1) a2\"\n    using L unfolding rel_set_def by auto\n    then obtain l2 where \"a2 = Inl l2 \\<and> \\<chi> l1 l2\" by (cases a2, auto)\n    thus \"\\<exists> l2. Inl l2 \\<in> A2 \\<and> \\<chi> l1 l2\" using a2 by auto\n  next\n    fix l2 assume \"Inl l2 \\<in> A2\"\n    then obtain a1 where a1: \"a1 \\<in> A1\" and \"rel_sum \\<chi> \\<phi> a1 (Inl l2)\"\n    using L unfolding rel_set_def by auto\n    then obtain l1 where \"a1 = Inl l1 \\<and> \\<chi> l1 l2\" by (cases a1, auto)\n    thus \"\\<exists> l1. Inl l1 \\<in> A1 \\<and> \\<chi> l1 l2\" using a1 by auto\n  qed\n  show ?Rr unfolding rel_set_def Bex_def vimage_eq proof safe\n    fix r1 assume \"Inr r1 \\<in> A1\"\n    then obtain a2 where a2: \"a2 \\<in> A2\" and \"rel_sum \\<chi> \\<phi> (Inr r1) a2\"\n    using L unfolding rel_set_def by auto\n    then obtain r2 where \"a2 = Inr r2 \\<and> \\<phi> r1 r2\" by (cases a2, auto)\n    thus \"\\<exists> r2. Inr r2 \\<in> A2 \\<and> \\<phi> r1 r2\" using a2 by auto\n  next\n    fix r2 assume \"Inr r2 \\<in> A2\"\n    then obtain a1 where a1: \"a1 \\<in> A1\" and \"rel_sum \\<chi> \\<phi> a1 (Inr r2)\"\n    using L unfolding rel_set_def by auto\n    then obtain r1 where \"a1 = Inr r1 \\<and> \\<phi> r1 r2\" by (cases a1, auto)\n    thus \"\\<exists> r1. Inr r1 \\<in> A1 \\<and> \\<phi> r1 r2\" using a1 by auto\n  qed\nnext\n  assume Rl: \"?Rl\" and Rr: \"?Rr\"\n  show ?L unfolding rel_set_def Bex_def vimage_eq proof safe\n    fix a1 assume a1: \"a1 \\<in> A1\"\n    show \"\\<exists> a2. a2 \\<in> A2 \\<and> rel_sum \\<chi> \\<phi> a1 a2\"\n    proof(cases a1)\n      case (Inl l1) then obtain l2 where \"Inl l2 \\<in> A2 \\<and> \\<chi> l1 l2\"\n      using Rl a1 unfolding rel_set_def by blast\n      thus ?thesis unfolding Inl by auto\n    next\n      case (Inr r1) then obtain r2 where \"Inr r2 \\<in> A2 \\<and> \\<phi> r1 r2\"\n      using Rr a1 unfolding rel_set_def by blast\n      thus ?thesis unfolding Inr by auto\n    qed\n  next\n    fix a2 assume a2: \"a2 \\<in> A2\"\n    show \"\\<exists> a1. a1 \\<in> A1 \\<and> rel_sum \\<chi> \\<phi> a1 a2\"\n    proof(cases a2)\n      case (Inl l2) then obtain l1 where \"Inl l1 \\<in> A1 \\<and> \\<chi> l1 l2\"\n      using Rl a2 unfolding rel_set_def by blast\n      thus ?thesis unfolding Inl by auto\n    next\n      case (Inr r2) then obtain r1 where \"Inr r1 \\<in> A1 \\<and> \\<phi> r1 r2\"\n      using Rr a2 unfolding rel_set_def by blast\n      thus ?thesis unfolding Inr by auto\n    qed\n  qed\nqed\n\n\nsubsubsection \\<open>Countability\\<close>\n\n\n\nlemma fset_of_list_surj[simp, intro]: \"surj fset_of_list\"\nproof -\n  have \"x \\<in> range fset_of_list\" for x :: \"'a fset\"\n    unfolding image_iff\n    using exists_fset_of_list by fastforce\n  thus ?thesis by auto\nqed\n\ninstance fset :: (countable) countable\nproof\n  obtain to_nat :: \"'a list \\<Rightarrow> nat\" where \"inj to_nat\"\n    by (metis ex_inj)\n  moreover have \"inj (inv fset_of_list)\"\n    using fset_of_list_surj by (rule surj_imp_inj_inv)\n  ultimately have \"inj (to_nat \\<circ> inv fset_of_list)\"\n    by (rule inj_compose)\n  thus \"\\<exists>to_nat::'a fset \\<Rightarrow> nat. inj to_nat\"\n    by auto\nqed\n\n\nsubsection \\<open>Quickcheck setup\\<close>\n\ntext \\<open>Setup adapted from sets.\\<close>\n\nnotation Quickcheck_Exhaustive.orelse (infixr \"orelse\" 55)\n\ncontext\n  includes term_syntax\nbegin\n\ndefinition [code_unfold]:\n\"valterm_femptyset = Code_Evaluation.valtermify ({||} :: ('a :: typerep) fset)\"\n\ndefinition [code_unfold]:\n\"valtermify_finsert x s = Code_Evaluation.valtermify finsert {\\<cdot>} (x :: ('a :: typerep * _)) {\\<cdot>} s\"\n\nend\n\ninstantiation fset :: (exhaustive) exhaustive\nbegin\n\nfun exhaustive_fset where\n\"exhaustive_fset f i = (if i = 0 then None else (f {||} orelse exhaustive_fset (\\<lambda>A. f A orelse Quickcheck_Exhaustive.exhaustive (\\<lambda>x. if x |\\<in>| A then None else f (finsert x A)) (i - 1)) (i - 1)))\"\n\ninstance ..\n\nend\n\ninstantiation fset :: (full_exhaustive) full_exhaustive\nbegin\n\nfun full_exhaustive_fset where\n\"full_exhaustive_fset f i = (if i = 0 then None else (f valterm_femptyset orelse full_exhaustive_fset (\\<lambda>A. f A orelse Quickcheck_Exhaustive.full_exhaustive (\\<lambda>x. if fst x |\\<in>| fst A then None else f (valtermify_finsert x A)) (i - 1)) (i - 1)))\"\n\ninstance ..\n\nend\n\nno_notation Quickcheck_Exhaustive.orelse (infixr \"orelse\" 55)\n\ninstantiation fset :: (random) random\nbegin\n\ncontext\n  includes state_combinator_syntax\nbegin\n\nfun random_aux_fset :: \"natural \\<Rightarrow> natural \\<Rightarrow> natural \\<times> natural \\<Rightarrow> ('a fset \\<times> (unit \\<Rightarrow> term)) \\<times> natural \\<times> natural\" where\n\"random_aux_fset 0 j = Quickcheck_Random.collapse (Random.select_weight [(1, Pair valterm_femptyset)])\" |\n\"random_aux_fset (Code_Numeral.Suc i) j =\n  Quickcheck_Random.collapse (Random.select_weight\n    [(1, Pair valterm_femptyset),\n     (Code_Numeral.Suc i,\n      Quickcheck_Random.random j \\<circ>\\<rightarrow> (\\<lambda>x. random_aux_fset i j \\<circ>\\<rightarrow> (\\<lambda>s. Pair (valtermify_finsert x s))))])\"\n\n\n\ndefinition \"random_fset i = random_aux_fset i i\"\n\ninstance ..\n\nend\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/FSet.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382200964034, "lm_q2_score": 0.8128673110375458, "lm_q1q2_score": 0.7003162563258367}}
{"text": "theory Refinement\nimports Setup\nbegin\n\nsection {* Program and datatype refinement \\label{sec:refinement} *}\n\ntext {*\n  Code generation by shallow embedding (cf.~\\secref{sec:principle})\n  allows to choose code equations and datatype constructors freely,\n  given that some very basic syntactic properties are met; this\n  flexibility opens up mechanisms for refinement which allow to extend\n  the scope and quality of generated code dramatically.\n*}\n\n\nsubsection {* Program refinement *}\n\ntext {*\n  Program refinement works by choosing appropriate code equations\n  explicitly (cf.~\\secref{sec:equations}); as example, we use Fibonacci\n  numbers:\n*}\n\nfun %quote fib :: \"nat \\<Rightarrow> nat\" where\n    \"fib 0 = 0\"\n  | \"fib (Suc 0) = Suc 0\"\n  | \"fib (Suc (Suc n)) = fib n + fib (Suc n)\"\n\ntext {*\n  \\noindent The runtime of the corresponding code grows exponential due\n  to two recursive calls:\n*}\n\ntext %quotetypewriter {*\n  @{code_stmts fib (consts) fib (Haskell)}\n*}\n\ntext {*\n  \\noindent A more efficient implementation would use dynamic\n  programming, e.g.~sharing of common intermediate results between\n  recursive calls.  This idea is expressed by an auxiliary operation\n  which computes a Fibonacci number and its successor simultaneously:\n*}\n\ndefinition %quote fib_step :: \"nat \\<Rightarrow> nat \\<times> nat\" where\n  \"fib_step n = (fib (Suc n), fib n)\"\n\ntext {*\n  \\noindent This operation can be implemented by recursion using\n  dynamic programming:\n*}\n\nlemma %quote [code]:\n  \"fib_step 0 = (Suc 0, 0)\"\n  \"fib_step (Suc n) = (let (m, q) = fib_step n in (m + q, m))\"\n  by (simp_all add: fib_step_def)\n\ntext {*\n  \\noindent What remains is to implement @{const fib} by @{const\n  fib_step} as follows:\n*}\n\nlemma %quote [code]:\n  \"fib 0 = 0\"\n  \"fib (Suc n) = fst (fib_step n)\"\n  by (simp_all add: fib_step_def)\n\ntext {*\n  \\noindent The resulting code shows only linear growth of runtime:\n*}\n\ntext %quotetypewriter {*\n  @{code_stmts fib (consts) fib fib_step (Haskell)}\n*}\n\n\nsubsection {* Datatype refinement *}\n\ntext {*\n  Selecting specific code equations \\emph{and} datatype constructors\n  leads to datatype refinement.  As an example, we will develop an\n  alternative representation of the queue example given in\n  \\secref{sec:queue_example}.  The amortised representation is\n  convenient for generating code but exposes its \\qt{implementation}\n  details, which may be cumbersome when proving theorems about it.\n  Therefore, here is a simple, straightforward representation of\n  queues:\n*}\n\ndatatype %quote 'a queue = Queue \"'a list\"\n\ndefinition %quote empty :: \"'a queue\" where\n  \"empty = Queue []\"\n\nprimrec %quote enqueue :: \"'a \\<Rightarrow> 'a queue \\<Rightarrow> 'a queue\" where\n  \"enqueue x (Queue xs) = Queue (xs @ [x])\"\n\nfun %quote dequeue :: \"'a queue \\<Rightarrow> 'a option \\<times> 'a queue\" where\n    \"dequeue (Queue []) = (None, Queue [])\"\n  | \"dequeue (Queue (x # xs)) = (Some x, Queue xs)\"\n\ntext {*\n  \\noindent This we can use directly for proving;  for executing,\n  we provide an alternative characterisation:\n*}\n\ndefinition %quote AQueue :: \"'a list \\<Rightarrow> 'a list \\<Rightarrow> 'a queue\" where\n  \"AQueue xs ys = Queue (ys @ rev xs)\"\n\ncode_datatype %quote AQueue\n\ntext {*\n  \\noindent Here we define a \\qt{constructor} @{const \"AQueue\"} which\n  is defined in terms of @{text \"Queue\"} and interprets its arguments\n  according to what the \\emph{content} of an amortised queue is supposed\n  to be.\n\n  The prerequisite for datatype constructors is only syntactical: a\n  constructor must be of type @{text \"\\<tau> = \\<dots> \\<Rightarrow> \\<kappa> \\<alpha>\\<^sub>1 \\<dots> \\<alpha>\\<^sub>n\"} where @{text\n  \"{\\<alpha>\\<^sub>1, \\<dots>, \\<alpha>\\<^sub>n}\"} is exactly the set of \\emph{all} type variables in\n  @{text \"\\<tau>\"}; then @{text \"\\<kappa>\"} is its corresponding datatype.  The\n  HOL datatype package by default registers any new datatype with its\n  constructors, but this may be changed using @{command_def\n  code_datatype}; the currently chosen constructors can be inspected\n  using the @{command print_codesetup} command.\n\n  Equipped with this, we are able to prove the following equations\n  for our primitive queue operations which \\qt{implement} the simple\n  queues in an amortised fashion:\n*}\n\nlemma %quote empty_AQueue [code]:\n  \"empty = AQueue [] []\"\n  by (simp add: AQueue_def empty_def)\n\nlemma %quote enqueue_AQueue [code]:\n  \"enqueue x (AQueue xs ys) = AQueue (x # xs) ys\"\n  by (simp add: AQueue_def)\n\nlemma %quote dequeue_AQueue [code]:\n  \"dequeue (AQueue xs []) =\n    (if xs = [] then (None, AQueue [] [])\n    else dequeue (AQueue [] (rev xs)))\"\n  \"dequeue (AQueue xs (y # ys)) = (Some y, AQueue xs ys)\"\n  by (simp_all add: AQueue_def)\n\ntext {*\n  \\noindent It is good style, although no absolute requirement, to\n  provide code equations for the original artefacts of the implemented\n  type, if possible; in our case, these are the datatype constructor\n  @{const Queue} and the case combinator @{const case_queue}:\n*}\n\nlemma %quote Queue_AQueue [code]:\n  \"Queue = AQueue []\"\n  by (simp add: AQueue_def fun_eq_iff)\n\nlemma %quote case_queue_AQueue [code]:\n  \"case_queue f (AQueue xs ys) = f (ys @ rev xs)\"\n  by (simp add: AQueue_def)\n\ntext {*\n  \\noindent The resulting code looks as expected:\n*}\n\ntext %quotetypewriter {*\n  @{code_stmts empty enqueue dequeue Queue case_queue (SML)}\n*}\n\ntext {*\n  The same techniques can also be applied to types which are not\n  specified as datatypes, e.g.~type @{typ int} is originally specified\n  as quotient type by means of @{command_def typedef}, but for code\n  generation constants allowing construction of binary numeral values\n  are used as constructors for @{typ int}.\n\n  This approach however fails if the representation of a type demands\n  invariants; this issue is discussed in the next section.\n*}\n\n\nsubsection {* Datatype refinement involving invariants \\label{sec:invariant} *}\n\ntext {*\n  Datatype representation involving invariants require a dedicated\n  setup for the type and its primitive operations.  As a running\n  example, we implement a type @{text \"'a dlist\"} of list consisting\n  of distinct elements.\n\n  The first step is to decide on which representation the abstract\n  type (in our example @{text \"'a dlist\"}) should be implemented.\n  Here we choose @{text \"'a list\"}.  Then a conversion from the concrete\n  type to the abstract type must be specified, here:\n*}\n\ntext %quote {*\n  @{term_type Dlist}\n*}\n\ntext {*\n  \\noindent Next follows the specification of a suitable \\emph{projection},\n  i.e.~a conversion from abstract to concrete type:\n*}\n\ntext %quote {*\n  @{term_type list_of_dlist}\n*}\n\ntext {*\n  \\noindent This projection must be specified such that the following\n  \\emph{abstract datatype certificate} can be proven:\n*}\n\nlemma %quote [code abstype]:\n  \"Dlist (list_of_dlist dxs) = dxs\"\n  by (fact Dlist_list_of_dlist)\n\ntext {*\n  \\noindent Note that so far the invariant on representations\n  (@{term_type distinct}) has never been mentioned explicitly:\n  the invariant is only referred to implicitly: all values in\n  set @{term \"{xs. list_of_dlist (Dlist xs) = xs}\"} are invariant,\n  and in our example this is exactly @{term \"{xs. distinct xs}\"}.\n  \n  The primitive operations on @{typ \"'a dlist\"} are specified\n  indirectly using the projection @{const list_of_dlist}.  For\n  the empty @{text \"dlist\"}, @{const Dlist.empty}, we finally want\n  the code equation\n*}\n\ntext %quote {*\n  @{term \"Dlist.empty = Dlist []\"}\n*}\n\ntext {*\n  \\noindent This we have to prove indirectly as follows:\n*}\n\nlemma %quote [code]:\n  \"list_of_dlist Dlist.empty = []\"\n  by (fact list_of_dlist_empty)\n\ntext {*\n  \\noindent This equation logically encodes both the desired code\n  equation and that the expression @{const Dlist} is applied to obeys\n  the implicit invariant.  Equations for insertion and removal are\n  similar:\n*}\n\nlemma %quote [code]:\n  \"list_of_dlist (Dlist.insert x dxs) = List.insert x (list_of_dlist dxs)\"\n  by (fact list_of_dlist_insert)\n\nlemma %quote [code]:\n  \"list_of_dlist (Dlist.remove x dxs) = remove1 x (list_of_dlist dxs)\"\n  by (fact list_of_dlist_remove)\n\ntext {*\n  \\noindent Then the corresponding code is as follows:\n*}\n\ntext %quotetypewriter {*\n  @{code_stmts Dlist.empty Dlist.insert Dlist.remove list_of_dlist (Haskell)}\n*}\n\ntext {*\n  See further @{cite \"Haftmann-Kraus-Kuncar-Nipkow:2013:data_refinement\"}\n  for the meta theory of datatype refinement involving invariants.\n\n  Typical data structures implemented by representations involving\n  invariants are available in the library, theory @{theory Mapping}\n  specifies key-value-mappings (type @{typ \"('a, 'b) mapping\"});\n  these can be implemented by red-black-trees (theory @{theory RBT}).\n*}\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/Doc/Codegen/Refinement.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8128673178375734, "lm_q2_score": 0.8615382094310357, "lm_q1q2_score": 0.7003162535147915}}
{"text": "theory Chapter21_1_Language\nimports DeBruijnEnvironment\nbegin\n\ndatatype kind =\n  Star\n\ndatatype type = \n  Tyvar var\n| Nat\n| Arrow type type\n| All type\n| Unit\n| Prod type type\n| Void\n| Sum type type\n\nprimrec type_insert :: \"var => type => type\"\nwhere \"type_insert n (Tyvar v) = Tyvar (incr n v)\"\n    | \"type_insert n Nat = Nat\"\n    | \"type_insert n (Arrow e1 e2) = Arrow (type_insert n e1) (type_insert n e2)\"\n    | \"type_insert n (All e) = All (type_insert (next n) e)\"\n    | \"type_insert n Unit = Unit\"\n    | \"type_insert n (Prod e1 e2) = Prod (type_insert n e1) (type_insert n e2)\"\n    | \"type_insert n Void = Void\"\n    | \"type_insert n (Sum e1 e2) = Sum (type_insert n e1) (type_insert n e2)\"\n\nprimrec type_subst :: \"type => var => type => type\"\nwhere \"type_subst e' n (Tyvar v) = (if v = n then e' else Tyvar (subr n v))\"\n    | \"type_subst e' n Nat = Nat\"\n    | \"type_subst e' n (Arrow e1 e2) = Arrow (type_subst e' n e1) (type_subst e' n e2)\"\n    | \"type_subst e' n (All e) = All (type_subst (type_insert first e') (next n) e)\"\n    | \"type_subst e' n Unit = Unit\"\n    | \"type_subst e' n (Prod e1 e2) = Prod (type_subst e' n e1) (type_subst e' n e2)\"\n    | \"type_subst e' n Void = Void\"\n    | \"type_subst e' n (Sum e1 e2) = Sum (type_subst e' n e1) (type_subst e' n e2)\"\n\n\n\nlemma [simp]: \"canswap m n ==> \n        type_insert m o type_insert n = type_insert (next n) o type_insert m\"\nby auto\n\nlemma [simp]: \"canswap m n ==> type_insert m (type_subst t' n t) =\n                  type_subst (type_insert m t') (next n) (type_insert m t)\"\nby (induction t arbitrary: m n t', simp_all)\n\ndatatype expr = \n  Var var\n| Zero\n| Suc expr\n| Iter expr expr expr\n| Lam type expr\n| Appl expr expr\n| TyLam expr\n| TyAppl type expr\n| Triv\n| Pair expr expr\n| ProjL expr\n| ProjR expr\n| Abort type expr\n| Case expr expr expr\n| InL type type expr\n| InR type type expr\n\nprimrec insert :: \"var => expr => expr\"\nwhere \"insert n (Var v) = Var (incr n v)\"\n    | \"insert n Zero = Zero\"\n    | \"insert n (Suc e) = Suc (insert n e)\"\n    | \"insert n (Iter et e0 es) = Iter (insert n et) (insert n e0) (insert (next n) es)\"\n    | \"insert n (Lam t e) = Lam t (insert (next n) e)\"\n    | \"insert n (Appl e1 e2) = Appl (insert n e1) (insert n e2)\"\n    | \"insert n (TyLam e) = TyLam (insert n e)\"\n    | \"insert n (TyAppl t e) = TyAppl t (insert n e)\"\n    | \"insert n Triv = Triv\"\n    | \"insert n (Pair e1 e2) = Pair (insert n e1) (insert n e2)\"\n    | \"insert n (ProjL e) = ProjL (insert n e)\"\n    | \"insert n (ProjR e) = ProjR (insert n e)\"\n    | \"insert n (Abort t e) = Abort t (insert n e)\"\n    | \"insert n (Case et el er) = Case (insert n et) (insert (next n) el) (insert (next n) er)\"\n    | \"insert n (InL t1 t2 e) = InL t1 t2 (insert n e)\"\n    | \"insert n (InR t1 t2 e) = InR t1 t2 (insert n e)\"\n\nprimrec expr_insert_type :: \"var => expr => expr\"\nwhere \"expr_insert_type n (Var v) = Var v\"\n    | \"expr_insert_type n Zero = Zero\"\n    | \"expr_insert_type n (Suc e) = Suc (expr_insert_type n e)\"\n    | \"expr_insert_type n (Iter et e0 es) = \n                      Iter (expr_insert_type n et) \n                           (expr_insert_type n e0) \n                           (expr_insert_type n es)\"\n    | \"expr_insert_type n (Lam t e) = Lam (type_insert n t) (expr_insert_type n e)\"\n    | \"expr_insert_type n (Appl e1 e2) = Appl (expr_insert_type n e1) (expr_insert_type n e2)\"\n    | \"expr_insert_type n (TyLam e) = TyLam (expr_insert_type (next n) e)\"\n    | \"expr_insert_type n (TyAppl t e) = TyAppl (type_insert n t) (expr_insert_type n e)\"\n    | \"expr_insert_type n Triv = Triv\"\n    | \"expr_insert_type n (Pair e1 e2) = Pair (expr_insert_type n e1) (expr_insert_type n e2)\"\n    | \"expr_insert_type n (ProjL e) = ProjL (expr_insert_type n e)\"\n    | \"expr_insert_type n (ProjR e) = ProjR (expr_insert_type n e)\"\n    | \"expr_insert_type n (Abort t e) = Abort (type_insert n t) (expr_insert_type n e)\"\n    | \"expr_insert_type n (Case et el er) = \n                      Case (expr_insert_type n et) (expr_insert_type n el) (expr_insert_type n er)\"\n    | \"expr_insert_type n (InL t1 t2 e) = \n                      InL (type_insert n t1) (type_insert n t2) (expr_insert_type n e)\"\n    | \"expr_insert_type n (InR t1 t2 e) = \n                      InR (type_insert n t1) (type_insert n t2) (expr_insert_type n e)\"\n\nprimrec subst :: \"expr => var => expr => expr\"\nwhere \"subst e' n (Var v) = (if v = n then e' else Var (subr n v))\"\n    | \"subst e' n Zero = Zero\"\n    | \"subst e' n (Suc e) = Suc (subst e' n e)\"\n    | \"subst e' n (Iter et e0 es) = \n                      Iter (subst e' n et) \n                           (subst e' n e0) \n                           (subst (insert first e') (next n) es)\"\n    | \"subst e' n (Lam t e) = Lam t (subst (insert first e') (next n) e)\"\n    | \"subst e' n (Appl e1 e2) = Appl (subst e' n e1) (subst e' n e2)\"\n    | \"subst e' n (TyLam e) = TyLam (subst (expr_insert_type first e') n e)\"\n    | \"subst e' n (TyAppl t e) = TyAppl t (subst e' n e)\"\n    | \"subst e' n Triv = Triv\"\n    | \"subst e' n (Pair e1 e2) = Pair (subst e' n e1) (subst e' n e2)\"\n    | \"subst e' n (ProjL e) = ProjL (subst e' n e)\"\n    | \"subst e' n (ProjR e) = ProjR (subst e' n e)\"\n    | \"subst e' n (Abort t e) = Abort t (subst e' n e)\"\n    | \"subst e' n (Case et el er) = \n                      Case (subst e' n et) \n                           (subst (insert first e') (next n)el) \n                           (subst (insert first e') (next n) er)\"\n    | \"subst e' n (InL t1 t2 e) = InL t1 t2 (subst e' n e)\"\n    | \"subst e' n (InR t1 t2 e) = InR t1 t2 (subst e' n e)\"\n\nprimrec expr_subst_type :: \"type => var => expr => expr\"\nwhere \"expr_subst_type t' n (Var v) = Var v\"\n    | \"expr_subst_type t' n Zero = Zero\"\n    | \"expr_subst_type t' n (Suc e) = Suc (expr_subst_type t' n e)\"\n    | \"expr_subst_type t' n (Iter et e0 es) = \n                      Iter (expr_subst_type t' n et) \n                           (expr_subst_type t' n e0) \n                           (expr_subst_type t' n es)\"\n    | \"expr_subst_type t' n (Lam t e) = Lam (type_subst t' n t) (expr_subst_type t' n e)\"\n    | \"expr_subst_type t' n (Appl e1 e2) = \n                Appl (expr_subst_type t' n e1) (expr_subst_type t' n e2)\"\n    | \"expr_subst_type t' n (TyLam e) = TyLam (expr_subst_type (type_insert first t') (next n) e)\"\n    | \"expr_subst_type t' n (TyAppl t e) = TyAppl (type_subst t' n t) (expr_subst_type t' n e)\"\n    | \"expr_subst_type t' n Triv = Triv\"\n    | \"expr_subst_type t' n (Pair e1 e2) = \n            Pair (expr_subst_type t' n e1) (expr_subst_type t' n e2)\"\n    | \"expr_subst_type t' n (ProjL e) = ProjL (expr_subst_type t' n e)\"\n    | \"expr_subst_type t' n (ProjR e) = ProjR (expr_subst_type t' n e)\"\n    | \"expr_subst_type t' n (Abort t e) = Abort (type_subst t' n t) (expr_subst_type t' n e)\"\n    | \"expr_subst_type t' n (Case et el er) = \n            Case (expr_subst_type t' n et) (expr_subst_type t' n el) (expr_subst_type t' n er)\"\n    | \"expr_subst_type t' n (InL t1 t2 e) = \n                      InL (type_subst t' n t1) (type_subst t' n t2) (expr_subst_type t' n e)\"\n    | \"expr_subst_type t' n (InR t1 t2 e) = \n                      InR (type_subst t' n t1) (type_subst t' n t2) (expr_subst_type t' n e)\"\n\nlemma [simp]: \"canswap m n ==> insert m (insert n e) = insert (next n) (insert m e)\"\nby (induction e arbitrary: n m, simp_all)\n\nlemma [simp]: \"insert n (expr_insert_type m e) = expr_insert_type m (insert n e)\"\nby (induction e arbitrary: n m, simp_all)\n\nlemma [simp]: \"canswap n m ==> expr_insert_type n (expr_insert_type m e) = \n                    expr_insert_type (next m) (expr_insert_type n e)\"\nby (induction e arbitrary: n m, simp_all)\n\nlemma [simp]: \"canswap m n ==> \n        type_insert m (type_insert n e) = type_insert (next n) (type_insert m e)\"\nby (induction e arbitrary: n m, simp_all)\n\nlemma [simp]: \"canswap m n ==> type_insert m o type_insert n = type_insert (next n) o type_insert m\"\nby auto\n\nlemma [simp]: \"canswap m n ==> type_insert m (type_subst t' n t) =\n                  type_subst (type_insert m t') (next n) (type_insert m t)\"\nby (induction t arbitrary: m n t', simp_all)\n\nlemma [simp]: \"canswap m n ==> type_insert m o type_subst t' n = \n                                   type_subst (type_insert m t') (next n) o type_insert m\"\nby auto\n\nlemma [simp]: \"type_subst t' n (type_insert n t) = t\"\nby (induction t arbitrary: n t', simp_all)\n\nlemma [simp]: \"canswap m n ==> type_subst (type_insert n t') m (type_insert (next n) t) = \n                                    type_insert n (type_subst t' m t)\"\nby (induction t arbitrary: n m t', simp_all)\n\nlemma [simp]: \"canswap m n ==> \n                  type_subst (type_subst t' n t'') m (type_subst (type_insert m t') (next n) t) = \n                      type_subst t' n (type_subst t'' m t)\"\nproof (induction t arbitrary: n m t' t'')\ncase (Tyvar v)\n  thus ?case by (cases n, cases m, cases v, auto)\nnext case Arrow\n  thus ?case by simp\nnext case All\n  thus ?case by simp\nnext case Nat\n  thus ?case by simp\nnext case Unit\n  thus ?case by simp\nnext case Prod\n  thus ?case by simp\nnext case Void\n  thus ?case by simp\nnext case Sum\n  thus ?case by simp\nqed\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/Chapter21_1_Language.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122163480666, "lm_q2_score": 0.7718434978390747, "lm_q1q2_score": 0.700303034698215}}
{"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_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 lt :: \"Nat => Nat => bool\" where\n\"lt y (Z) = False\"\n| \"lt (Z) (S z2) = True\"\n| \"lt (S n) (S z2) = lt n z2\"\n\n(*fun did not finish the proof*)\nfunction mod2 :: \"Nat => Nat => Nat\" where\n\"mod2 y (Z) = Z\"\n| \"mod2 y (S z2) =\n     (if lt y (S z2) then y else mod2 (minus y (S z2)) (S z2))\"\nby pat_completeness auto\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 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 (mod2 n (length xs)) xs) (take (mod2 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_mod.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587993853654, "lm_q2_score": 0.7879311956428947, "lm_q1q2_score": 0.7002807834378546}}
{"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_MSortBUPermutes\n  imports \"../../Test_Base\"\nbegin\n\ndatatype 'a list = nil2 | cons2 \"'a\" \"'a list\"\n\ndatatype Nat = Z | S \"Nat\"\n\nfun map :: \"('a => 'b) => 'a list => 'b list\" where\n  \"map f (nil2) = nil2\"\n| \"map f (cons2 y xs) = cons2 (f y) (map f xs)\"\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 mergingbu :: \"(Nat list) list => Nat list\" where\n  \"mergingbu (nil2) = nil2\"\n| \"mergingbu (cons2 xs (nil2)) = xs\"\n| \"mergingbu (cons2 xs (cons2 z x2)) =\n     mergingbu (pairwise (cons2 xs (cons2 z x2)))\"\n  by pat_completeness auto\n\nfun msortbu :: \"Nat list => Nat list\" where\n  \"msortbu x = mergingbu (map (% (y :: Nat) => cons2 y (nil2)) x)\"\n\nfun elem :: \"'a => 'a list => bool\" where\n  \"elem x (nil2) = False\"\n| \"elem x (cons2 z xs) = ((z = x) | (elem x xs))\"\n\nfun deleteBy :: \"('a => ('a => bool)) => 'a => 'a list =>\n                 'a list\" where\n  \"deleteBy x y (nil2) = nil2\"\n| \"deleteBy x y (cons2 y2 ys) =\n     (if (x y) y2 then ys else cons2 y2 (deleteBy x y ys))\"\n\nfun isPermutation :: \"'a list => 'a list => bool\" where\n  \"isPermutation (nil2) (nil2) = True\"\n| \"isPermutation (nil2) (cons2 z x2) = False\"\n| \"isPermutation (cons2 x3 xs) y =\n     ((elem x3 y) &\n        (isPermutation\n           xs (deleteBy (% (x4 :: 'a) => % (x5 :: 'a) => (x4 = x5)) x3 y)))\"\n\ntheorem property0 :\n  \"isPermutation (msortbu 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_sort_nat_MSortBUPermutes.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587875995482, "lm_q2_score": 0.7879311956428946, "lm_q1q2_score": 0.7002807741514414}}
{"text": "theory Submission\n  imports Defs\nbegin\n\ntheorem good_node_def:\n  \"good_node i \\<longleftrightarrow> E\\<^sup>*\\<^sup>* i 0\"\n  apply safe\n  subgoal premises prems\n    using prems by induction auto\n  subgoal premises prems\n    using prems by (induction rule: converse_rtranclp_induct) (auto intro: good_node.intros)\n  done\n\nlemma E_determ:\n  assumes \"E a b\" \"E a c\"\n  shows \"b = c\"\n  using assms unfolding E_def by auto\n\nlemma reaches_bound:\n  assumes \"E\\<^sup>*\\<^sup>* i j\" \"i < n\"\n  shows \"j < n\"\n  using assms by cases (auto simp: E_def)\n\nlemma reaches1_0:\n  \"E\\<^sup>+\\<^sup>+ 0 j \\<longleftrightarrow> False\"\n  by (meson E_def tranclpD zero_less_iff_neq_zero)\n\nlemma cycle_never_reaches_0:\n  assumes \"E\\<^sup>+\\<^sup>+ j 0\" \"E\\<^sup>+\\<^sup>+ j j\"\n  shows False\n  using assms\n  apply (induction j rule: converse_tranclp_induct)\n   apply (metis E_def converse_tranclpE less_numeral_extra(3))\n  by (metis E_determ rtranclpD tranclp.trancl_into_trancl tranclpD)\n\nlemma reaches_determ:\n  assumes \"E\\<^sup>*\\<^sup>* a b\" \"E\\<^sup>*\\<^sup>* a c\"\n  obtains \"E\\<^sup>*\\<^sup>* c b\" | \"E\\<^sup>*\\<^sup>* b c\"\n  apply atomize_elim\n  using assms\n  apply induction\n   apply auto\n  by (metis E_determ converse_rtranclpE r_into_rtranclp)\n\n\\<comment> \\<open>This definition and the theorem are copied from the timed automata graph library\n(cf.\\ \\<^url>\\<open>https://github.com/wimmers/munta/blob/13a3a83270f9613b164af58a8ece6373c92fb7c8/library/Graphs.thy#L436\\<close>)\\<close>\ndefinition sink where\n  \"sink a \\<equiv> \\<nexists>b. E a b\"\n\nlemma sink_or_cycle:\n  assumes \"finite {b. E\\<^sup>*\\<^sup>* a b}\"\n  obtains b where \"E\\<^sup>*\\<^sup>* a b\" \"sink b\" | b where \"E\\<^sup>*\\<^sup>* a b\" \"E\\<^sup>+\\<^sup>+ b b\"\nproof -\n  let ?S = \"{b. E\\<^sup>+\\<^sup>+ a b}\"\n  have \"?S \\<subseteq> {b. E\\<^sup>*\\<^sup>* a b}\"\n    by auto\n  then have \"finite ?S\"\n    using assms by (rule finite_subset)\n  then show ?thesis\n    using that\n  proof (induction ?S arbitrary: a rule: finite_psubset_induct)\n    case psubset\n    consider (empty) \"Collect (E\\<^sup>+\\<^sup>+ a) = {}\" | b where \"E\\<^sup>+\\<^sup>+ a b\"\n      by auto\n    then show ?case\n    proof cases\n      case empty\n      then have \"sink a\"\n        unfolding sink_def by auto\n      with psubset.prems show ?thesis\n        by auto\n    next\n      case 2\n      show ?thesis\n      proof (cases \"E\\<^sup>*\\<^sup>* b a\")\n        case True\n        with \\<open>E\\<^sup>+\\<^sup>+ a b\\<close> have \"E\\<^sup>+\\<^sup>+ a a\"\n          by auto\n        with psubset.prems show ?thesis\n          by auto\n      next\n        case False\n        show ?thesis\n        proof (cases \"E\\<^sup>+\\<^sup>+ b b\")\n          case True\n          with \\<open>E\\<^sup>+\\<^sup>+ a b\\<close> psubset.prems show ?thesis\n            by (auto intro: tranclp_into_rtranclp)\n        next\n          case False\n          with \\<open>\\<not> E\\<^sup>*\\<^sup>* b a\\<close> \\<open>E\\<^sup>+\\<^sup>+ a b\\<close> have \"Collect (E\\<^sup>+\\<^sup>+ b) \\<subset> Collect (E\\<^sup>+\\<^sup>+ a)\"\n            by (intro psubsetI) auto\n          then show ?thesis\n            using \\<open>E\\<^sup>+\\<^sup>+ a b\\<close> psubset.prems\n            by - (erule psubset.hyps; meson tranclp_into_rtranclp tranclp_rtranclp_tranclp)\n        qed\n      qed\n    qed\n  qed\nqed\n\n\ntheorem good_node_characterization_1:\n  assumes \"i < n\" \"i > 0\" \"good_node i\"\n  shows \"\\<not> (\\<exists>j. E\\<^sup>*\\<^sup>* i j \\<and> E\\<^sup>+\\<^sup>+ j j)\" (* this is right *)\n  using assms(3) unfolding good_node_def\nproof safe\n  \\<comment> \\<open>paths are determinstic & nothing can leave from \\<open>0\\<close>\\<close>\n  fix j :: nat\n  assume prems: \"E\\<^sup>*\\<^sup>* i 0\" and \"E\\<^sup>*\\<^sup>* i j\" and \"E\\<^sup>+\\<^sup>+ j j\"\n  from \\<open>E\\<^sup>*\\<^sup>* i 0\\<close> \\<open>E\\<^sup>*\\<^sup>* i j\\<close> consider \"j = 0\" | \"E\\<^sup>+\\<^sup>+ 0 j\" | \"E\\<^sup>+\\<^sup>+ j 0\"\n    by (metis reaches_determ rtranclpD)\n  then show False\n  proof cases\n    case 1\n    with \\<open>E\\<^sup>+\\<^sup>+ j j\\<close> show ?thesis\n      by (simp add: reaches1_0)\n  next\n    case 2\n    then show ?thesis\n      by (simp add: reaches1_0)\n  next\n    case 3\n    with \\<open>E\\<^sup>+\\<^sup>+ j j\\<close> show ?thesis\n      using cycle_never_reaches_0 by auto\n  qed\nqed\n\n\ntheorem good_node_characterization_2:\n  assumes \"i < n\" \"i > 0\" \"\\<not> (\\<exists>j. E\\<^sup>*\\<^sup>* i j \\<and> E\\<^sup>+\\<^sup>+ j j)\"\n  shows \"good_node i\" (* this is right *)\n  unfolding good_node_def\nproof -\n  \\<comment> \\<open>if a node cannot reach a cycle, then it has to reach a sink\\<close>\n  let ?S = \"{j. E\\<^sup>*\\<^sup>* i j}\"\n  have \"sink 0\"\n    unfolding sink_def E_def by auto\n  have \"?S \\<subseteq> {0..<n}\"\n    using \\<open>i < n\\<close> by (auto intro: reaches_bound)\n  then have \"finite ?S\"\n    by (rule finite_subset) rule\n  with assms(3) obtain j where j: \"E\\<^sup>*\\<^sup>* i j\" \"sink j\"\n    by (auto elim: sink_or_cycle)\n  with \\<open>i < n\\<close> have \"j < n\"\n    by (auto intro: reaches_bound)\n  with \\<open>sink j\\<close> have \"j = 0\"\n    unfolding sink_def E_def n_def using wellformed by auto\n  with \\<open>E\\<^sup>*\\<^sup>* i j\\<close> show \"E\\<^sup>*\\<^sup>* i 0\"\n    by simp\nqed\n\ncorollary good_node_characterization:\n  assumes \"i < n\" \"i > 0\"\n  shows \"good_node i \\<longleftrightarrow> \\<not> (\\<exists>j. E\\<^sup>*\\<^sup>* i j \\<and> E\\<^sup>+\\<^sup>+ j j)\" (* this is right *)\n  using good_node_characterization_1 good_node_characterization_2 assms by blast\n\nend", "meta": {"author": "maxhaslbeck", "repo": "proofground2020-solutions", "sha": "023ec2643f6aa06e60bec391e20f178c258ea1a3", "save_path": "github-repos/isabelle/maxhaslbeck-proofground2020-solutions", "path": "github-repos/isabelle/maxhaslbeck-proofground2020-solutions/proofground2020-solutions-023ec2643f6aa06e60bec391e20f178c258ea1a3/good_nodes/Isabelle/wimmers/Submission.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8887587905460026, "lm_q2_score": 0.787931190663057, "lm_q1q2_score": 0.7002807720471703}}
{"text": "(*  Title:      HOL/BNF_Cardinal_Arithmetic.thy\n    Author:     Dmitriy Traytel, TU Muenchen\n    Copyright   2012\n\nCardinal arithmetic as needed by bounded natural functors.\n*)\n\nsection {* Cardinal Arithmetic as Needed by Bounded Natural Functors *}\n\ntheory BNF_Cardinal_Arithmetic\nimports BNF_Cardinal_Order_Relation\nbegin\n\nlemma dir_image: \"\\<lbrakk>\\<And>x y. (f x = f y) = (x = y); Card_order r\\<rbrakk> \\<Longrightarrow> r =o dir_image r f\"\nby (rule dir_image_ordIso) (auto simp add: inj_on_def card_order_on_def)\n\nlemma card_order_dir_image:\n  assumes bij: \"bij f\" and co: \"card_order r\"\n  shows \"card_order (dir_image r f)\"\nproof -\n  from assms have \"Field (dir_image r f) = UNIV\"\n    using card_order_on_Card_order[of UNIV r] unfolding bij_def dir_image_Field by auto\n  moreover from bij have \"\\<And>x y. (f x = f y) = (x = y)\" unfolding bij_def inj_on_def by auto\n  with co have \"Card_order (dir_image r f)\"\n    using card_order_on_Card_order[of UNIV r] Card_order_ordIso2[OF _ dir_image] by blast\n  ultimately show ?thesis by auto\nqed\n\nlemma ordIso_refl: \"Card_order r \\<Longrightarrow> r =o r\"\nby (rule card_order_on_ordIso)\n\nlemma ordLeq_refl: \"Card_order r \\<Longrightarrow> r \\<le>o r\"\nby (rule ordIso_imp_ordLeq, rule card_order_on_ordIso)\n\nlemma card_of_ordIso_subst: \"A = B \\<Longrightarrow> |A| =o |B|\"\nby (simp only: ordIso_refl card_of_Card_order)\n\nlemma Field_card_order: \"card_order r \\<Longrightarrow> Field r = UNIV\"\nusing card_order_on_Card_order[of UNIV r] by simp\n\n\nsubsection {* Zero *}\n\ndefinition czero where\n  \"czero = card_of {}\"\n\nlemma czero_ordIso:\n  \"czero =o czero\"\nusing card_of_empty_ordIso by (simp add: czero_def)\n\nlemma card_of_ordIso_czero_iff_empty:\n  \"|A| =o (czero :: 'b rel) \\<longleftrightarrow> A = ({} :: 'a set)\"\nunfolding czero_def by (rule iffI[OF card_of_empty2]) (auto simp: card_of_refl card_of_empty_ordIso)\n\n(* A \"not czero\" Cardinal predicate *)\nabbreviation Cnotzero where\n  \"Cnotzero (r :: 'a rel) \\<equiv> \\<not>(r =o (czero :: 'a rel)) \\<and> Card_order r\"\n\n(*helper*)\nlemma Cnotzero_imp_not_empty: \"Cnotzero r \\<Longrightarrow> Field r \\<noteq> {}\"\n  unfolding Card_order_iff_ordIso_card_of czero_def by force\n\nlemma czeroI:\n  \"\\<lbrakk>Card_order r; Field r = {}\\<rbrakk> \\<Longrightarrow> r =o czero\"\nusing Cnotzero_imp_not_empty ordIso_transitive[OF _ czero_ordIso] by blast\n\nlemma czeroE:\n  \"r =o czero \\<Longrightarrow> Field r = {}\"\nunfolding czero_def\nby (drule card_of_cong) (simp only: Field_card_of card_of_empty2)\n\nlemma Cnotzero_mono:\n  \"\\<lbrakk>Cnotzero r; Card_order q; r \\<le>o q\\<rbrakk> \\<Longrightarrow> Cnotzero q\"\napply (rule ccontr)\napply auto\napply (drule czeroE)\napply (erule notE)\napply (erule czeroI)\napply (drule card_of_mono2)\napply (simp only: card_of_empty3)\ndone\n\nsubsection {* (In)finite cardinals *}\n\ndefinition cinfinite where\n  \"cinfinite r = (\\<not> finite (Field r))\"\n\nabbreviation Cinfinite where\n  \"Cinfinite r \\<equiv> cinfinite r \\<and> Card_order r\"\n\ndefinition cfinite where\n  \"cfinite r = finite (Field r)\"\n\nabbreviation Cfinite where\n  \"Cfinite r \\<equiv> cfinite r \\<and> Card_order r\"\n\nlemma Cfinite_ordLess_Cinfinite: \"\\<lbrakk>Cfinite r; Cinfinite s\\<rbrakk> \\<Longrightarrow> r <o s\"\n  unfolding cfinite_def cinfinite_def\n  by (blast intro: finite_ordLess_infinite card_order_on_well_order_on)\n\nlemmas natLeq_card_order = natLeq_Card_order[unfolded Field_natLeq]\n\nlemma natLeq_cinfinite: \"cinfinite natLeq\"\nunfolding cinfinite_def Field_natLeq by (rule infinite_UNIV_nat)\n\nlemma natLeq_ordLeq_cinfinite:\n  assumes inf: \"Cinfinite r\"\n  shows \"natLeq \\<le>o r\"\nproof -\n  from inf have \"natLeq \\<le>o |Field r|\" unfolding cinfinite_def\n    using infinite_iff_natLeq_ordLeq by blast\n  also from inf have \"|Field r| =o r\" by (simp add: card_of_unique ordIso_symmetric)\n  finally show ?thesis .\nqed\n\nlemma cinfinite_not_czero: \"cinfinite r \\<Longrightarrow> \\<not> (r =o (czero :: 'a rel))\"\nunfolding cinfinite_def by (cases \"Field r = {}\") (auto dest: czeroE)\n\nlemma Cinfinite_Cnotzero: \"Cinfinite r \\<Longrightarrow> Cnotzero r\"\nby (rule conjI[OF cinfinite_not_czero]) simp_all\n\nlemma Cinfinite_cong: \"\\<lbrakk>r1 =o r2; Cinfinite r1\\<rbrakk> \\<Longrightarrow> Cinfinite r2\"\nusing Card_order_ordIso2[of r1 r2] unfolding cinfinite_def ordIso_iff_ordLeq\nby (auto dest: card_of_ordLeq_infinite[OF card_of_mono2])\n\nlemma cinfinite_mono: \"\\<lbrakk>r1 \\<le>o r2; cinfinite r1\\<rbrakk> \\<Longrightarrow> cinfinite r2\"\nunfolding cinfinite_def by (auto dest: card_of_ordLeq_infinite[OF card_of_mono2])\n\n\nsubsection {* Binary sum *}\n\ndefinition csum (infixr \"+c\" 65) where\n  \"r1 +c r2 \\<equiv> |Field r1 <+> Field r2|\"\n\nlemma Field_csum: \"Field (r +c s) = Inl ` Field r \\<union> Inr ` Field s\"\n  unfolding csum_def Field_card_of by auto\n\nlemma Card_order_csum:\n  \"Card_order (r1 +c r2)\"\nunfolding csum_def by (simp add: card_of_Card_order)\n\nlemma csum_Cnotzero1:\n  \"Cnotzero r1 \\<Longrightarrow> Cnotzero (r1 +c r2)\"\nunfolding csum_def using Cnotzero_imp_not_empty[of r1] Plus_eq_empty_conv[of \"Field r1\" \"Field r2\"]\n   card_of_ordIso_czero_iff_empty[of \"Field r1 <+> Field r2\"] by (auto intro: card_of_Card_order)\n\nlemma card_order_csum:\n  assumes \"card_order r1\" \"card_order r2\"\n  shows \"card_order (r1 +c r2)\"\nproof -\n  have \"Field r1 = UNIV\" \"Field r2 = UNIV\" using assms card_order_on_Card_order by auto\n  thus ?thesis unfolding csum_def by (auto simp: card_of_card_order_on)\nqed\n\nlemma cinfinite_csum:\n  \"cinfinite r1 \\<or> cinfinite r2 \\<Longrightarrow> cinfinite (r1 +c r2)\"\nunfolding cinfinite_def csum_def by (auto simp: Field_card_of)\n\nlemma Cinfinite_csum1:\n  \"Cinfinite r1 \\<Longrightarrow> Cinfinite (r1 +c r2)\"\nunfolding cinfinite_def csum_def by (rule conjI[OF _ card_of_Card_order]) (auto simp: Field_card_of)\n\nlemma Cinfinite_csum:\n  \"Cinfinite r1 \\<or> Cinfinite r2 \\<Longrightarrow> Cinfinite (r1 +c r2)\"\nunfolding cinfinite_def csum_def by (rule conjI[OF _ card_of_Card_order]) (auto simp: Field_card_of)\n\nlemma Cinfinite_csum_weak:\n  \"\\<lbrakk>Cinfinite r1; Cinfinite r2\\<rbrakk> \\<Longrightarrow> Cinfinite (r1 +c r2)\"\nby (erule Cinfinite_csum1)\n\nlemma csum_cong: \"\\<lbrakk>p1 =o r1; p2 =o r2\\<rbrakk> \\<Longrightarrow> p1 +c p2 =o r1 +c r2\"\nby (simp only: csum_def ordIso_Plus_cong)\n\nlemma csum_cong1: \"p1 =o r1 \\<Longrightarrow> p1 +c q =o r1 +c q\"\nby (simp only: csum_def ordIso_Plus_cong1)\n\nlemma csum_cong2: \"p2 =o r2 \\<Longrightarrow> q +c p2 =o q +c r2\"\nby (simp only: csum_def ordIso_Plus_cong2)\n\nlemma csum_mono: \"\\<lbrakk>p1 \\<le>o r1; p2 \\<le>o r2\\<rbrakk> \\<Longrightarrow> p1 +c p2 \\<le>o r1 +c r2\"\nby (simp only: csum_def ordLeq_Plus_mono)\n\nlemma csum_mono1: \"p1 \\<le>o r1 \\<Longrightarrow> p1 +c q \\<le>o r1 +c q\"\nby (simp only: csum_def ordLeq_Plus_mono1)\n\nlemma csum_mono2: \"p2 \\<le>o r2 \\<Longrightarrow> q +c p2 \\<le>o q +c r2\"\nby (simp only: csum_def ordLeq_Plus_mono2)\n\nlemma ordLeq_csum1: \"Card_order p1 \\<Longrightarrow> p1 \\<le>o p1 +c p2\"\nby (simp only: csum_def Card_order_Plus1)\n\nlemma ordLeq_csum2: \"Card_order p2 \\<Longrightarrow> p2 \\<le>o p1 +c p2\"\nby (simp only: csum_def Card_order_Plus2)\n\nlemma csum_com: \"p1 +c p2 =o p2 +c p1\"\nby (simp only: csum_def card_of_Plus_commute)\n\nlemma csum_assoc: \"(p1 +c p2) +c p3 =o p1 +c p2 +c p3\"\nby (simp only: csum_def Field_card_of card_of_Plus_assoc)\n\nlemma Cfinite_csum: \"\\<lbrakk>Cfinite r; Cfinite s\\<rbrakk> \\<Longrightarrow> Cfinite (r +c s)\"\n  unfolding cfinite_def csum_def Field_card_of using card_of_card_order_on by simp\n\nlemma csum_csum: \"(r1 +c r2) +c (r3 +c r4) =o (r1 +c r3) +c (r2 +c r4)\"\nproof -\n  have \"(r1 +c r2) +c (r3 +c r4) =o r1 +c r2 +c (r3 +c r4)\"\n    by (rule csum_assoc)\n  also have \"r1 +c r2 +c (r3 +c r4) =o r1 +c (r2 +c r3) +c r4\"\n    by (intro csum_assoc csum_cong2 ordIso_symmetric)\n  also have \"r1 +c (r2 +c r3) +c r4 =o r1 +c (r3 +c r2) +c r4\"\n    by (intro csum_com csum_cong1 csum_cong2)\n  also have \"r1 +c (r3 +c r2) +c r4 =o r1 +c r3 +c r2 +c r4\"\n    by (intro csum_assoc csum_cong2 ordIso_symmetric)\n  also have \"r1 +c r3 +c r2 +c r4 =o (r1 +c r3) +c (r2 +c r4)\"\n    by (intro csum_assoc ordIso_symmetric)\n  finally show ?thesis .\nqed\n\nlemma Plus_csum: \"|A <+> B| =o |A| +c |B|\"\nby (simp only: csum_def Field_card_of card_of_refl)\n\nlemma Un_csum: \"|A \\<union> B| \\<le>o |A| +c |B|\"\nusing ordLeq_ordIso_trans[OF card_of_Un_Plus_ordLeq Plus_csum] by blast\n\n\nsubsection {* One *}\n\ndefinition cone where\n  \"cone = card_of {()}\"\n\nlemma Card_order_cone: \"Card_order cone\"\nunfolding cone_def by (rule card_of_Card_order)\n\nlemma Cfinite_cone: \"Cfinite cone\"\n  unfolding cfinite_def by (simp add: Card_order_cone)\n\nlemma cone_not_czero: \"\\<not> (cone =o czero)\"\nunfolding czero_def cone_def ordIso_iff_ordLeq using card_of_empty3 empty_not_insert by blast\n\nlemma cone_ordLeq_Cnotzero: \"Cnotzero r \\<Longrightarrow> cone \\<le>o r\"\nunfolding cone_def by (rule Card_order_singl_ordLeq) (auto intro: czeroI)\n\n\nsubsection {* Two *}\n\ndefinition ctwo where\n  \"ctwo = |UNIV :: bool set|\"\n\nlemma Card_order_ctwo: \"Card_order ctwo\"\nunfolding ctwo_def by (rule card_of_Card_order)\n\nlemma ctwo_not_czero: \"\\<not> (ctwo =o czero)\"\nusing card_of_empty3[of \"UNIV :: bool set\"] ordIso_iff_ordLeq\nunfolding czero_def ctwo_def using UNIV_not_empty by auto\n\nlemma ctwo_Cnotzero: \"Cnotzero ctwo\"\nby (simp add: ctwo_not_czero Card_order_ctwo)\n\n\nsubsection {* Family sum *}\n\ndefinition Csum where\n  \"Csum r rs \\<equiv> |SIGMA i : Field r. Field (rs i)|\"\n\n(* Similar setup to the one for SIGMA from theory Big_Operators: *)\nsyntax \"_Csum\" ::\n  \"pttrn => ('a * 'a) set => 'b * 'b set => (('a * 'b) * ('a * 'b)) set\"\n  (\"(3CSUM _:_. _)\" [0, 51, 10] 10)\n\ntranslations\n  \"CSUM i:r. rs\" == \"CONST Csum r (%i. rs)\"\n\nlemma SIGMA_CSUM: \"|SIGMA i : I. As i| = (CSUM i : |I|. |As i| )\"\nby (auto simp: Csum_def Field_card_of)\n\n(* NB: Always, under the cardinal operator,\noperations on sets are reduced automatically to operations on cardinals.\nThis should make cardinal reasoning more direct and natural.  *)\n\n\nsubsection {* Product *}\n\ndefinition cprod (infixr \"*c\" 80) where\n  \"r1 *c r2 = |Field r1 <*> Field r2|\"\n\nlemma card_order_cprod:\n  assumes \"card_order r1\" \"card_order r2\"\n  shows \"card_order (r1 *c r2)\"\nproof -\n  have \"Field r1 = UNIV\" \"Field r2 = UNIV\" using assms card_order_on_Card_order by auto\n  thus ?thesis by (auto simp: cprod_def card_of_card_order_on)\nqed\n\nlemma Card_order_cprod: \"Card_order (r1 *c r2)\"\nby (simp only: cprod_def Field_card_of card_of_card_order_on)\n\nlemma cprod_mono1: \"p1 \\<le>o r1 \\<Longrightarrow> p1 *c q \\<le>o r1 *c q\"\nby (simp only: cprod_def ordLeq_Times_mono1)\n\nlemma cprod_mono2: \"p2 \\<le>o r2 \\<Longrightarrow> q *c p2 \\<le>o q *c r2\"\nby (simp only: cprod_def ordLeq_Times_mono2)\n\nlemma cprod_mono: \"\\<lbrakk>p1 \\<le>o r1; p2 \\<le>o r2\\<rbrakk> \\<Longrightarrow> p1 *c p2 \\<le>o r1 *c r2\"\nby (rule ordLeq_transitive[OF cprod_mono1 cprod_mono2])\n\nlemma ordLeq_cprod2: \"\\<lbrakk>Cnotzero p1; Card_order p2\\<rbrakk> \\<Longrightarrow> p2 \\<le>o p1 *c p2\"\nunfolding cprod_def by (rule Card_order_Times2) (auto intro: czeroI)\n\nlemma cinfinite_cprod: \"\\<lbrakk>cinfinite r1; cinfinite r2\\<rbrakk> \\<Longrightarrow> cinfinite (r1 *c r2)\"\nby (simp add: cinfinite_def cprod_def Field_card_of infinite_cartesian_product)\n\nlemma cinfinite_cprod2: \"\\<lbrakk>Cnotzero r1; Cinfinite r2\\<rbrakk> \\<Longrightarrow> cinfinite (r1 *c r2)\"\nby (rule cinfinite_mono) (auto intro: ordLeq_cprod2)\n\nlemma Cinfinite_cprod2: \"\\<lbrakk>Cnotzero r1; Cinfinite r2\\<rbrakk> \\<Longrightarrow> Cinfinite (r1 *c r2)\"\nby (blast intro: cinfinite_cprod2 Card_order_cprod)\n\nlemma cprod_cong: \"\\<lbrakk>p1 =o r1; p2 =o r2\\<rbrakk> \\<Longrightarrow> p1 *c p2 =o r1 *c r2\"\nunfolding ordIso_iff_ordLeq by (blast intro: cprod_mono)\n\nlemma cprod_cong1: \"\\<lbrakk>p1 =o r1\\<rbrakk> \\<Longrightarrow> p1 *c p2 =o r1 *c p2\"\nunfolding ordIso_iff_ordLeq by (blast intro: cprod_mono1)\n\nlemma cprod_cong2: \"p2 =o r2 \\<Longrightarrow> q *c p2 =o q *c r2\"\nunfolding ordIso_iff_ordLeq by (blast intro: cprod_mono2)\n\nlemma cprod_com: \"p1 *c p2 =o p2 *c p1\"\nby (simp only: cprod_def card_of_Times_commute)\n\nlemma card_of_Csum_Times:\n  \"\\<forall>i \\<in> I. |A i| \\<le>o |B| \\<Longrightarrow> (CSUM i : |I|. |A i| ) \\<le>o |I| *c |B|\"\nby (simp only: Csum_def cprod_def Field_card_of card_of_Sigma_mono1)\n\nlemma card_of_Csum_Times':\n  assumes \"Card_order r\" \"\\<forall>i \\<in> I. |A i| \\<le>o r\"\n  shows \"(CSUM i : |I|. |A i| ) \\<le>o |I| *c r\"\nproof -\n  from assms(1) have *: \"r =o |Field r|\" by (simp add: card_of_unique)\n  with assms(2) have \"\\<forall>i \\<in> I. |A i| \\<le>o |Field r|\" by (blast intro: ordLeq_ordIso_trans)\n  hence \"(CSUM i : |I|. |A i| ) \\<le>o |I| *c |Field r|\" by (simp only: card_of_Csum_Times)\n  also from * have \"|I| *c |Field r| \\<le>o |I| *c r\"\n    by (simp only: Field_card_of card_of_refl cprod_def ordIso_imp_ordLeq)\n  finally show ?thesis .\nqed\n\nlemma cprod_csum_distrib1: \"r1 *c r2 +c r1 *c r3 =o r1 *c (r2 +c r3)\"\nunfolding csum_def cprod_def by (simp add: Field_card_of card_of_Times_Plus_distrib ordIso_symmetric)\n\nlemma csum_absorb2': \"\\<lbrakk>Card_order r2; r1 \\<le>o r2; cinfinite r1 \\<or> cinfinite r2\\<rbrakk> \\<Longrightarrow> r1 +c r2 =o r2\"\nunfolding csum_def by (rule conjunct2[OF Card_order_Plus_infinite])\n  (auto simp: cinfinite_def dest: cinfinite_mono)\n\nlemma csum_absorb1':\n  assumes card: \"Card_order r2\"\n  and r12: \"r1 \\<le>o r2\" and cr12: \"cinfinite r1 \\<or> cinfinite r2\"\n  shows \"r2 +c r1 =o r2\"\nby (rule ordIso_transitive, rule csum_com, rule csum_absorb2', (simp only: assms)+)\n\nlemma csum_absorb1: \"\\<lbrakk>Cinfinite r2; r1 \\<le>o r2\\<rbrakk> \\<Longrightarrow> r2 +c r1 =o r2\"\nby (rule csum_absorb1') auto\n\n\nsubsection {* Exponentiation *}\n\ndefinition cexp (infixr \"^c\" 90) where\n  \"r1 ^c r2 \\<equiv> |Func (Field r2) (Field r1)|\"\n\nlemma Card_order_cexp: \"Card_order (r1 ^c r2)\"\nunfolding cexp_def by (rule card_of_Card_order)\n\nlemma cexp_mono':\n  assumes 1: \"p1 \\<le>o r1\" and 2: \"p2 \\<le>o r2\"\n  and n: \"Field p2 = {} \\<Longrightarrow> Field r2 = {}\"\n  shows \"p1 ^c p2 \\<le>o r1 ^c r2\"\nproof(cases \"Field p1 = {}\")\n  case True\n  hence \"Field p2 \\<noteq> {} \\<Longrightarrow> Func (Field p2) {} = {}\" unfolding Func_is_emp by simp\n  with True have \"|Field |Func (Field p2) (Field p1)|| \\<le>o cone\"\n    unfolding cone_def Field_card_of\n    by (cases \"Field p2 = {}\", auto intro: surj_imp_ordLeq simp: Func_empty)\n  hence \"|Func (Field p2) (Field p1)| \\<le>o cone\" by (simp add: Field_card_of cexp_def)\n  hence \"p1 ^c p2 \\<le>o cone\" unfolding cexp_def .\n  thus ?thesis\n  proof (cases \"Field p2 = {}\")\n    case True\n    with n have \"Field r2 = {}\" .\n    hence \"cone \\<le>o r1 ^c r2\" unfolding cone_def cexp_def Func_def\n      by (auto intro: card_of_ordLeqI[where f=\"\\<lambda>_ _. undefined\"])\n    thus ?thesis using `p1 ^c p2 \\<le>o cone` ordLeq_transitive by auto\n  next\n    case False with True have \"|Field (p1 ^c p2)| =o czero\"\n      unfolding card_of_ordIso_czero_iff_empty cexp_def Field_card_of Func_def by auto\n    thus ?thesis unfolding cexp_def card_of_ordIso_czero_iff_empty Field_card_of\n      by (simp add: card_of_empty)\n  qed\nnext\n  case False\n  have 1: \"|Field p1| \\<le>o |Field r1|\" and 2: \"|Field p2| \\<le>o |Field r2|\"\n    using 1 2 by (auto simp: card_of_mono2)\n  obtain f1 where f1: \"f1 ` Field r1 = Field p1\"\n    using 1 unfolding card_of_ordLeq2[OF False, symmetric] by auto\n  obtain f2 where f2: \"inj_on f2 (Field p2)\" \"f2 ` Field p2 \\<subseteq> Field r2\"\n    using 2 unfolding card_of_ordLeq[symmetric] by blast\n  have 0: \"Func_map (Field p2) f1 f2 ` (Field (r1 ^c r2)) = Field (p1 ^c p2)\"\n    unfolding cexp_def Field_card_of using Func_map_surj[OF f1 f2 n, symmetric] .\n  have 00: \"Field (p1 ^c p2) \\<noteq> {}\" unfolding cexp_def Field_card_of Func_is_emp\n    using False by simp\n  show ?thesis\n    using 0 card_of_ordLeq2[OF 00] unfolding cexp_def Field_card_of by blast\nqed\n\nlemma cexp_mono:\n  assumes 1: \"p1 \\<le>o r1\" and 2: \"p2 \\<le>o r2\"\n  and n: \"p2 =o czero \\<Longrightarrow> r2 =o czero\" and card: \"Card_order p2\"\n  shows \"p1 ^c p2 \\<le>o r1 ^c r2\"\n  by (rule cexp_mono'[OF 1 2 czeroE[OF n[OF czeroI[OF card]]]])\n\nlemma cexp_mono1:\n  assumes 1: \"p1 \\<le>o r1\" and q: \"Card_order q\"\n  shows \"p1 ^c q \\<le>o r1 ^c q\"\nusing ordLeq_refl[OF q] by (rule cexp_mono[OF 1]) (auto simp: q)\n\nlemma cexp_mono2':\n  assumes 2: \"p2 \\<le>o r2\" and q: \"Card_order q\"\n  and n: \"Field p2 = {} \\<Longrightarrow> Field r2 = {}\"\n  shows \"q ^c p2 \\<le>o q ^c r2\"\nusing ordLeq_refl[OF q] by (rule cexp_mono'[OF _ 2 n]) auto\n\nlemma cexp_mono2:\n  assumes 2: \"p2 \\<le>o r2\" and q: \"Card_order q\"\n  and n: \"p2 =o czero \\<Longrightarrow> r2 =o czero\" and card: \"Card_order p2\"\n  shows \"q ^c p2 \\<le>o q ^c r2\"\nusing ordLeq_refl[OF q] by (rule cexp_mono[OF _ 2 n card]) auto\n\nlemma cexp_mono2_Cnotzero:\n  assumes \"p2 \\<le>o r2\" \"Card_order q\" \"Cnotzero p2\"\n  shows \"q ^c p2 \\<le>o q ^c r2\"\nusing assms(3) czeroI by (blast intro: cexp_mono2'[OF assms(1,2)])\n\nlemma cexp_cong:\n  assumes 1: \"p1 =o r1\" and 2: \"p2 =o r2\"\n  and Cr: \"Card_order r2\"\n  and Cp: \"Card_order p2\"\n  shows \"p1 ^c p2 =o r1 ^c r2\"\nproof -\n  obtain f where \"bij_betw f (Field p2) (Field r2)\"\n    using 2 card_of_ordIso[of \"Field p2\" \"Field r2\"] card_of_cong by auto\n  hence 0: \"Field p2 = {} \\<longleftrightarrow> Field r2 = {}\" unfolding bij_betw_def by auto\n  have r: \"p2 =o czero \\<Longrightarrow> r2 =o czero\"\n    and p: \"r2 =o czero \\<Longrightarrow> p2 =o czero\"\n     using 0 Cr Cp czeroE czeroI by auto\n  show ?thesis using 0 1 2 unfolding ordIso_iff_ordLeq\n    using r p cexp_mono[OF _ _ _ Cp] cexp_mono[OF _ _ _ Cr] by blast\nqed\n\nlemma cexp_cong1:\n  assumes 1: \"p1 =o r1\" and q: \"Card_order q\"\n  shows \"p1 ^c q =o r1 ^c q\"\nby (rule cexp_cong[OF 1 _ q q]) (rule ordIso_refl[OF q])\n\nlemma cexp_cong2:\n  assumes 2: \"p2 =o r2\" and q: \"Card_order q\" and p: \"Card_order p2\"\n  shows \"q ^c p2 =o q ^c r2\"\nby (rule cexp_cong[OF _ 2]) (auto simp only: ordIso_refl Card_order_ordIso2[OF p 2] q p)\n\nlemma cexp_cone:\n  assumes \"Card_order r\"\n  shows \"r ^c cone =o r\"\nproof -\n  have \"r ^c cone =o |Field r|\"\n    unfolding cexp_def cone_def Field_card_of Func_empty\n      card_of_ordIso[symmetric] bij_betw_def Func_def inj_on_def image_def\n    by (rule exI[of _ \"\\<lambda>f. f ()\"]) auto\n  also have \"|Field r| =o r\" by (rule card_of_Field_ordIso[OF assms])\n  finally show ?thesis .\nqed\n\nlemma cexp_cprod:\n  assumes r1: \"Card_order r1\"\n  shows \"(r1 ^c r2) ^c r3 =o r1 ^c (r2 *c r3)\" (is \"?L =o ?R\")\nproof -\n  have \"?L =o r1 ^c (r3 *c r2)\"\n    unfolding cprod_def cexp_def Field_card_of\n    using card_of_Func_Times by(rule ordIso_symmetric)\n  also have \"r1 ^c (r3 *c r2) =o ?R\"\n    apply(rule cexp_cong2) using cprod_com r1 by (auto simp: Card_order_cprod)\n  finally show ?thesis .\nqed\n\nlemma cprod_infinite1': \"\\<lbrakk>Cinfinite r; Cnotzero p; p \\<le>o r\\<rbrakk> \\<Longrightarrow> r *c p =o r\"\nunfolding cinfinite_def cprod_def\nby (rule Card_order_Times_infinite[THEN conjunct1]) (blast intro: czeroI)+\n\nlemma cprod_infinite: \"Cinfinite r \\<Longrightarrow> r *c r =o r\"\nusing cprod_infinite1' Cinfinite_Cnotzero ordLeq_refl by blast\n\nlemma cexp_cprod_ordLeq:\n  assumes r1: \"Card_order r1\" and r2: \"Cinfinite r2\"\n  and r3: \"Cnotzero r3\" \"r3 \\<le>o r2\"\n  shows \"(r1 ^c r2) ^c r3 =o r1 ^c r2\" (is \"?L =o ?R\")\nproof-\n  have \"?L =o r1 ^c (r2 *c r3)\" using cexp_cprod[OF r1] .\n  also have \"r1 ^c (r2 *c r3) =o ?R\"\n  apply(rule cexp_cong2)\n  apply(rule cprod_infinite1'[OF r2 r3]) using r1 r2 by (fastforce simp: Card_order_cprod)+\n  finally show ?thesis .\nqed\n\nlemma Cnotzero_UNIV: \"Cnotzero |UNIV|\"\nby (auto simp: card_of_Card_order card_of_ordIso_czero_iff_empty)\n\nlemma ordLess_ctwo_cexp:\n  assumes \"Card_order r\"\n  shows \"r <o ctwo ^c r\"\nproof -\n  have \"r <o |Pow (Field r)|\" using assms by (rule Card_order_Pow)\n  also have \"|Pow (Field r)| =o ctwo ^c r\"\n    unfolding ctwo_def cexp_def Field_card_of by (rule card_of_Pow_Func)\n  finally show ?thesis .\nqed\n\nlemma ordLeq_cexp1:\n  assumes \"Cnotzero r\" \"Card_order q\"\n  shows \"q \\<le>o q ^c r\"\nproof (cases \"q =o (czero :: 'a rel)\")\n  case True thus ?thesis by (simp only: card_of_empty cexp_def czero_def ordIso_ordLeq_trans)\nnext\n  case False\n  thus ?thesis\n    apply -\n    apply (rule ordIso_ordLeq_trans)\n    apply (rule ordIso_symmetric)\n    apply (rule cexp_cone)\n    apply (rule assms(2))\n    apply (rule cexp_mono2)\n    apply (rule cone_ordLeq_Cnotzero)\n    apply (rule assms(1))\n    apply (rule assms(2))\n    apply (rule notE)\n    apply (rule cone_not_czero)\n    apply assumption\n    apply (rule Card_order_cone)\n  done\nqed\n\nlemma ordLeq_cexp2:\n  assumes \"ctwo \\<le>o q\" \"Card_order r\"\n  shows \"r \\<le>o q ^c r\"\nproof (cases \"r =o (czero :: 'a rel)\")\n  case True thus ?thesis by (simp only: card_of_empty cexp_def czero_def ordIso_ordLeq_trans)\nnext\n  case False thus ?thesis\n    apply -\n    apply (rule ordLess_imp_ordLeq)\n    apply (rule ordLess_ordLeq_trans)\n    apply (rule ordLess_ctwo_cexp)\n    apply (rule assms(2))\n    apply (rule cexp_mono1)\n    apply (rule assms(1))\n    apply (rule assms(2))\n  done\nqed\n\nlemma cinfinite_cexp: \"\\<lbrakk>ctwo \\<le>o q; Cinfinite r\\<rbrakk> \\<Longrightarrow> cinfinite (q ^c r)\"\nby (rule cinfinite_mono[OF ordLeq_cexp2]) simp_all\n\nlemma Cinfinite_cexp:\n  \"\\<lbrakk>ctwo \\<le>o q; Cinfinite r\\<rbrakk> \\<Longrightarrow> Cinfinite (q ^c r)\"\nby (simp add: cinfinite_cexp Card_order_cexp)\n\nlemma ctwo_ordLess_natLeq: \"ctwo <o natLeq\"\nunfolding ctwo_def using finite_UNIV natLeq_cinfinite natLeq_Card_order\nby (intro Cfinite_ordLess_Cinfinite) (auto simp: cfinite_def card_of_Card_order)\n\nlemma ctwo_ordLess_Cinfinite: \"Cinfinite r \\<Longrightarrow> ctwo <o r\"\nby (rule ordLess_ordLeq_trans[OF ctwo_ordLess_natLeq natLeq_ordLeq_cinfinite])\n\nlemma ctwo_ordLeq_Cinfinite:\n  assumes \"Cinfinite r\"\n  shows \"ctwo \\<le>o r\"\nby (rule ordLess_imp_ordLeq[OF ctwo_ordLess_Cinfinite[OF assms]])\n\nlemma Un_Cinfinite_bound: \"\\<lbrakk>|A| \\<le>o r; |B| \\<le>o r; Cinfinite r\\<rbrakk> \\<Longrightarrow> |A \\<union> B| \\<le>o r\"\nby (auto simp add: cinfinite_def card_of_Un_ordLeq_infinite_Field)\n\nlemma UNION_Cinfinite_bound: \"\\<lbrakk>|I| \\<le>o r; \\<forall>i \\<in> I. |A i| \\<le>o r; Cinfinite r\\<rbrakk> \\<Longrightarrow> |\\<Union>i \\<in> I. A i| \\<le>o r\"\nby (auto simp add: card_of_UNION_ordLeq_infinite_Field cinfinite_def)\n\nlemma csum_cinfinite_bound:\n  assumes \"p \\<le>o r\" \"q \\<le>o r\" \"Card_order p\" \"Card_order q\" \"Cinfinite r\"\n  shows \"p +c q \\<le>o r\"\nproof -\n  from assms(1-4) have \"|Field p| \\<le>o r\" \"|Field q| \\<le>o r\"\n    unfolding card_order_on_def using card_of_least ordLeq_transitive by blast+\n  with assms show ?thesis unfolding cinfinite_def csum_def\n    by (blast intro: card_of_Plus_ordLeq_infinite_Field)\nqed\n\nlemma cprod_cinfinite_bound:\n  assumes \"p \\<le>o r\" \"q \\<le>o r\" \"Card_order p\" \"Card_order q\" \"Cinfinite r\"\n  shows \"p *c q \\<le>o r\"\nproof -\n  from assms(1-4) have \"|Field p| \\<le>o r\" \"|Field q| \\<le>o r\"\n    unfolding card_order_on_def using card_of_least ordLeq_transitive by blast+\n  with assms show ?thesis unfolding cinfinite_def cprod_def\n    by (blast intro: card_of_Times_ordLeq_infinite_Field)\nqed\n\nlemma cprod_csum_cexp:\n  \"r1 *c r2 \\<le>o (r1 +c r2) ^c ctwo\"\nunfolding cprod_def csum_def cexp_def ctwo_def Field_card_of\nproof -\n  let ?f = \"\\<lambda>(a, b). %x. if x then Inl a else Inr b\"\n  have \"inj_on ?f (Field r1 \\<times> Field r2)\" (is \"inj_on _ ?LHS\")\n    by (auto simp: inj_on_def fun_eq_iff split: bool.split)\n  moreover\n  have \"?f ` ?LHS \\<subseteq> Func (UNIV :: bool set) (Field r1 <+> Field r2)\" (is \"_ \\<subseteq> ?RHS\")\n    by (auto simp: Func_def)\n  ultimately show \"|?LHS| \\<le>o |?RHS|\" using card_of_ordLeq by blast\nqed\n\nlemma Cfinite_cprod_Cinfinite: \"\\<lbrakk>Cfinite r; Cinfinite s\\<rbrakk> \\<Longrightarrow> r *c s \\<le>o s\"\nby (intro cprod_cinfinite_bound)\n  (auto intro: ordLeq_refl ordLess_imp_ordLeq[OF Cfinite_ordLess_Cinfinite])\n\nlemma cprod_cexp: \"(r *c s) ^c t =o r ^c t *c s ^c t\"\n  unfolding cprod_def cexp_def Field_card_of by (rule Func_Times_Range)\n\nlemma cprod_cexp_csum_cexp_Cinfinite:\n  assumes t: \"Cinfinite t\"\n  shows \"(r *c s) ^c t \\<le>o (r +c s) ^c t\"\nproof -\n  have \"(r *c s) ^c t \\<le>o ((r +c s) ^c ctwo) ^c t\"\n    by (rule cexp_mono1[OF cprod_csum_cexp conjunct2[OF t]])\n  also have \"((r +c s) ^c ctwo) ^c t =o (r +c s) ^c (ctwo *c t)\"\n    by (rule cexp_cprod[OF Card_order_csum])\n  also have \"(r +c s) ^c (ctwo *c t) =o (r +c s) ^c (t *c ctwo)\"\n    by (rule cexp_cong2[OF cprod_com Card_order_csum Card_order_cprod])\n  also have \"(r +c s) ^c (t *c ctwo) =o ((r +c s) ^c t) ^c ctwo\"\n    by (rule ordIso_symmetric[OF cexp_cprod[OF Card_order_csum]])\n  also have \"((r +c s) ^c t) ^c ctwo =o (r +c s) ^c t\"\n    by (rule cexp_cprod_ordLeq[OF Card_order_csum t ctwo_Cnotzero ctwo_ordLeq_Cinfinite[OF t]])\n  finally show ?thesis .\nqed\n\nlemma Cfinite_cexp_Cinfinite:\n  assumes s: \"Cfinite s\" and t: \"Cinfinite t\"\n  shows \"s ^c t \\<le>o ctwo ^c t\"\nproof (cases \"s \\<le>o ctwo\")\n  case True thus ?thesis using t by (blast intro: cexp_mono1)\nnext\n  case False\n  hence \"ctwo \\<le>o s\" using ordLeq_total[of s ctwo] Card_order_ctwo s\n    by (auto intro: card_order_on_well_order_on)\n  hence \"Cnotzero s\" using Cnotzero_mono[OF ctwo_Cnotzero] s by blast\n  hence st: \"Cnotzero (s *c t)\" by (intro Cinfinite_Cnotzero[OF Cinfinite_cprod2]) (auto simp: t)\n  have \"s ^c t \\<le>o (ctwo ^c s) ^c t\"\n    using assms by (blast intro: cexp_mono1 ordLess_imp_ordLeq[OF ordLess_ctwo_cexp])\n  also have \"(ctwo ^c s) ^c t =o ctwo ^c (s *c t)\"\n    by (blast intro: Card_order_ctwo cexp_cprod)\n  also have \"ctwo ^c (s *c t) \\<le>o ctwo ^c t\"\n    using assms st by (intro cexp_mono2_Cnotzero Cfinite_cprod_Cinfinite Card_order_ctwo)\n  finally show ?thesis .\nqed\n\nlemma csum_Cfinite_cexp_Cinfinite:\n  assumes r: \"Card_order r\" and s: \"Cfinite s\" and t: \"Cinfinite t\"\n  shows \"(r +c s) ^c t \\<le>o (r +c ctwo) ^c t\"\nproof (cases \"Cinfinite r\")\n  case True\n  hence \"r +c s =o r\" by (intro csum_absorb1 ordLess_imp_ordLeq[OF Cfinite_ordLess_Cinfinite] s)\n  hence \"(r +c s) ^c t =o r ^c t\" using t by (blast intro: cexp_cong1)\n  also have \"r ^c t \\<le>o (r +c ctwo) ^c t\" using t by (blast intro: cexp_mono1 ordLeq_csum1 r)\n  finally show ?thesis .\nnext\n  case False\n  with r have \"Cfinite r\" unfolding cinfinite_def cfinite_def by auto\n  hence \"Cfinite (r +c s)\" by (intro Cfinite_csum s)\n  hence \"(r +c s) ^c t \\<le>o ctwo ^c t\" by (intro Cfinite_cexp_Cinfinite t)\n  also have \"ctwo ^c t \\<le>o (r +c ctwo) ^c t\" using t\n    by (blast intro: cexp_mono1 ordLeq_csum2 Card_order_ctwo)\n  finally show ?thesis .\nqed\n\n(* cardSuc *)\n\nlemma Cinfinite_cardSuc: \"Cinfinite r \\<Longrightarrow> Cinfinite (cardSuc r)\"\nby (simp add: cinfinite_def cardSuc_Card_order cardSuc_finite)\n\nlemma cardSuc_UNION_Cinfinite:\n  assumes \"Cinfinite r\" \"relChain (cardSuc r) As\" \"B \\<le> (UN i : Field (cardSuc r). As i)\" \"|B| <=o r\"\n  shows \"EX i : Field (cardSuc r). B \\<le> As i\"\nusing cardSuc_UNION assms unfolding cinfinite_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/BNF_Cardinal_Arithmetic.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8887587846530938, "lm_q2_score": 0.787931190663057, "lm_q1q2_score": 0.7002807674039636}}
{"text": "(* Title:      Algebras for Aggregation and Minimisation with a Linear Order\n   Author:     Walter Guttmann\n   Maintainer: Walter Guttmann <walter.guttmann at canterbury.ac.nz>\n*)\n\nsection \\<open>Algebras for Aggregation and Minimisation with a Linear Order\\<close>\n\ntext \\<open>\nThis theory gives several classes of instances of linear aggregation lattices as described in \\cite{Guttmann2018a}.\nEach of these instances can be used as edge weights and the resulting graphs will form s-algebras and m-algebras as shown in a separate theory.\n\\<close>\n\ntheory Linear_Aggregation_Algebras\n\nimports Matrix_Aggregation_Algebras HOL.Real\n\nbegin\n\nno_notation\n  inf (infixl \"\\<sqinter>\" 70)\n  and uminus (\"- _\" [81] 80)\n\nsubsection \\<open>Linearly Ordered Commutative Semigroups\\<close>\n\ntext \\<open>\nAny linearly ordered commutative semigroup extended by new least and greatest elements forms a linear aggregation lattice.\nThe extension is done so that the new least element is a unit of aggregation and the new greatest element is a zero of aggregation.\n\\<close>\n\ndatatype 'a ext =\n    Bot\n  | Val 'a\n  | Top\n\ninstantiation ext :: (linordered_ab_semigroup_add) linear_aggregation_kleene_algebra\nbegin\n\nfun plus_ext :: \"'a ext \\<Rightarrow> 'a ext \\<Rightarrow> 'a ext\" where\n  \"plus_ext Bot x = x\"\n| \"plus_ext (Val x) Bot = Val x\"\n| \"plus_ext (Val x) (Val y) = Val (x + y)\"\n| \"plus_ext (Val _) Top = Top\"\n| \"plus_ext Top _ = Top\"\n\nfun sup_ext :: \"'a ext \\<Rightarrow> 'a ext \\<Rightarrow> 'a ext\" where\n  \"sup_ext Bot x = x\"\n| \"sup_ext (Val x) Bot = Val x\"\n| \"sup_ext (Val x) (Val y) = Val (max x y)\"\n| \"sup_ext (Val _) Top = Top\"\n| \"sup_ext Top _ = Top\"\n\nfun inf_ext :: \"'a ext \\<Rightarrow> 'a ext \\<Rightarrow> 'a ext\" where\n  \"inf_ext Bot _ = Bot\"\n| \"inf_ext (Val _) Bot = Bot\"\n| \"inf_ext (Val x) (Val y) = Val (min x y)\"\n| \"inf_ext (Val x) Top = Val x\"\n| \"inf_ext Top x = x\"\n\nfun times_ext :: \"'a ext \\<Rightarrow> 'a ext \\<Rightarrow> 'a ext\" where \"times_ext x y = x \\<sqinter> y\"\n\nfun uminus_ext :: \"'a ext \\<Rightarrow> 'a ext\" where\n  \"uminus_ext Bot = Top\"\n| \"uminus_ext (Val _) = Bot\"\n| \"uminus_ext Top = Bot\"\n\nfun star_ext :: \"'a ext \\<Rightarrow> 'a ext\" where \"star_ext _ = Top\"\n\nfun conv_ext :: \"'a ext \\<Rightarrow> 'a ext\" where \"conv_ext x = x\"\n\ndefinition bot_ext :: \"'a ext\" where \"bot_ext \\<equiv> Bot\"\ndefinition one_ext :: \"'a ext\" where \"one_ext \\<equiv> Top\"\ndefinition top_ext :: \"'a ext\" where \"top_ext \\<equiv> Top\"\n\nfun less_eq_ext :: \"'a ext \\<Rightarrow> 'a ext \\<Rightarrow> bool\" where\n  \"less_eq_ext Bot _ = True\"\n| \"less_eq_ext (Val _) Bot = False\"\n| \"less_eq_ext (Val x) (Val y) = (x \\<le> y)\"\n| \"less_eq_ext (Val _) Top = True\"\n| \"less_eq_ext Top Bot = False\"\n| \"less_eq_ext Top (Val _) = False\"\n| \"less_eq_ext Top Top = True\"\n\nfun less_ext :: \"'a ext \\<Rightarrow> 'a ext \\<Rightarrow> bool\" where \"less_ext x y = (x \\<le> y \\<and> \\<not> y \\<le> x)\"\n\ninstance\nproof\n  fix x y z :: \"'a ext\"\n  show \"(x + y) + z = x + (y + z)\"\n    by (cases x; cases y; cases z) (simp_all add: add.assoc)\n  show \"x + y = y + x\"\n    by (cases x; cases y) (simp_all add: add.commute)\n  show \"(x < y) = (x \\<le> y \\<and> \\<not> y \\<le> x)\"\n    by simp\n  show \"x \\<le> x\"\n    using less_eq_ext.elims(3) by fastforce\n  show \"x \\<le> y \\<Longrightarrow> y \\<le> z \\<Longrightarrow> x \\<le> z\"\n    by (cases x; cases y; cases z) simp_all\n  show \"x \\<le> y \\<Longrightarrow> y \\<le> x \\<Longrightarrow> x = y\"\n    by (cases x; cases y) simp_all\n  show \"x \\<sqinter> y \\<le> x\"\n    by (cases x; cases y) simp_all\n  show \"x \\<sqinter> y \\<le> y\"\n    by (cases x; cases y) simp_all\n  show \"x \\<le> y \\<Longrightarrow> x \\<le> z \\<Longrightarrow> x \\<le> y \\<sqinter> z\"\n    by (cases x; cases y; cases z) simp_all\n  show \"x \\<le> x \\<squnion> y\"\n    by (cases x; cases y) simp_all\n  show \"y \\<le> x \\<squnion> y\"\n    by (cases x; cases y) simp_all\n  show \"y \\<le> x \\<Longrightarrow> z \\<le> x \\<Longrightarrow> y \\<squnion> z \\<le> x\"\n    by (cases x; cases y; cases z) simp_all\n  show \"bot \\<le> x\"\n    by (simp add: bot_ext_def)\n  show \"x \\<le> top\"\n    by (cases x) (simp_all add: top_ext_def)\n  show \"x \\<noteq> bot \\<and> x + bot \\<le> y + bot \\<longrightarrow> x + z \\<le> y + z\"\n    by (cases x; cases y; cases z) (simp_all add: bot_ext_def add_right_mono)\n  show \"x + y + bot = x + y\"\n    by (cases x; cases y) (simp_all add: bot_ext_def)\n  show \"x + y = bot \\<longrightarrow> x = bot\"\n    by (cases x; cases y) (simp_all add: bot_ext_def)\n  show \"x \\<le> y \\<or> y \\<le> x\"\n    by (cases x; cases y) (simp_all add: linear)\n  show \"-x = (if x = bot then top else bot)\"\n    by (cases x) (simp_all add: bot_ext_def top_ext_def)\n  show \"(1::'a ext) = top\"\n    by (simp add: one_ext_def top_ext_def)\n  show \"x * y = x \\<sqinter> y\"\n    by simp\n  show \"x\\<^sup>T = x\"\n    by simp\n  show \"x\\<^sup>\\<star> = top\"\n    by (simp add: top_ext_def)\nqed\n\nend\n\ntext \\<open>\nAn example of a linearly ordered commutative semigroup is the set of real numbers with standard addition as aggregation.\n\\<close>\n\nlemma example_real_ext_matrix:\n  fixes x :: \"('a::enum,real ext) square\"\n  shows \"minarc\\<^sub>M x \\<preceq> \\<ominus>\\<ominus>x\"\n  by (rule agg_square_m_algebra.minarc_below)\n\ntext \\<open>\nAnother example of a linearly ordered commutative semigroup is the set of real numbers with maximum as aggregation.\n\\<close>\n\ndatatype real_max = Rmax real\n\ninstantiation real_max :: linordered_ab_semigroup_add\nbegin\n\nfun less_eq_real_max where \"less_eq_real_max (Rmax x) (Rmax y) = (x \\<le> y)\"\nfun less_real_max where \"less_real_max (Rmax x) (Rmax y) = (x < y)\"\nfun plus_real_max where \"plus_real_max (Rmax x) (Rmax y) = Rmax (max x y)\"\n\ninstance\nproof\n  fix x y z :: real_max\n  show \"(x + y) + z = x + (y + z)\"\n    by (cases x; cases y; cases z) simp\n  show \"x + y = y + x\"\n    by (cases x; cases y) simp\n  show \"(x < y) = (x \\<le> y \\<and> \\<not> y \\<le> x)\"\n    by (cases x; cases y) auto\n  show \"x \\<le> x\"\n    by (cases x) simp\n  show \"x \\<le> y \\<Longrightarrow> y \\<le> z \\<Longrightarrow> x \\<le> z\"\n    by (cases x; cases y; cases z) simp\n  show \"x \\<le> y \\<Longrightarrow> y \\<le> x \\<Longrightarrow> x = y\"\n    by (cases x; cases y) simp\n  show \"x \\<le> y \\<Longrightarrow> z + x \\<le> z + y\"\n    by (cases x; cases y; cases z) simp\n  show \"x \\<le> y \\<or> y \\<le> x\"\n    by (cases x; cases y) auto\nqed\n\nend\n\nlemma example_real_max_ext_matrix:\n  fixes x :: \"('a::enum,real_max ext) square\"\n  shows \"minarc\\<^sub>M x \\<preceq> \\<ominus>\\<ominus>x\"\n  by (rule agg_square_m_algebra.minarc_below)\n\ntext \\<open>\nA third example of a linearly ordered commutative semigroup is the set of real numbers with minimum as aggregation.\n\\<close>\n\ndatatype real_min = Rmin real\n\ninstantiation real_min :: linordered_ab_semigroup_add\nbegin\n\nfun less_eq_real_min where \"less_eq_real_min (Rmin x) (Rmin y) = (x \\<le> y)\"\nfun less_real_min where \"less_real_min (Rmin x) (Rmin y) = (x < y)\"\nfun plus_real_min where \"plus_real_min (Rmin x) (Rmin y) = Rmin (min x y)\"\n\ninstance\nproof\n  fix x y z :: real_min\n  show \"(x + y) + z = x + (y + z)\"\n    by (cases x; cases y; cases z) simp\n  show \"x + y = y + x\"\n    by (cases x; cases y) simp\n  show \"(x < y) = (x \\<le> y \\<and> \\<not> y \\<le> x)\"\n    by (cases x; cases y) auto\n  show \"x \\<le> x\"\n    by (cases x) simp\n  show \"x \\<le> y \\<Longrightarrow> y \\<le> z \\<Longrightarrow> x \\<le> z\"\n    by (cases x; cases y; cases z) simp\n  show \"x \\<le> y \\<Longrightarrow> y \\<le> x \\<Longrightarrow> x = y\"\n    by (cases x; cases y) simp\n  show \"x \\<le> y \\<Longrightarrow> z + x \\<le> z + y\"\n    by (cases x; cases y; cases z) simp\n  show \"x \\<le> y \\<or> y \\<le> x\"\n    by (cases x; cases y) auto\nqed\n\nend\n\nlemma example_real_min_ext_matrix:\n  fixes x :: \"('a::enum,real_min ext) square\"\n  shows \"minarc\\<^sub>M x \\<preceq> \\<ominus>\\<ominus>x\"\n  by (rule agg_square_m_algebra.minarc_below)\n\nsubsection \\<open>Linearly Ordered Commutative Monoids\\<close>\n\ntext \\<open>\nAny linearly ordered commutative monoid extended by new least and greatest elements forms a linear aggregation lattice.\nThis is similar to linearly ordered commutative semigroups except that the aggregation $\\bot + \\bot$ produces the unit of the monoid instead of the least element.\nApplied to weighted graphs, this means that the aggregation of the empty graph will be the unit of the monoid (for example, $0$ for real numbers under standard addition, instead of $\\bot$).\n\\<close>\n\nclass linordered_comm_monoid_add = linordered_ab_semigroup_add + comm_monoid_add\n\ndatatype 'a ext0 =\n    Bot\n  | Val 'a\n  | Top\n\ninstantiation ext0 :: (linordered_comm_monoid_add) linear_aggregation_kleene_algebra\nbegin\n\nfun plus_ext0 :: \"'a ext0 \\<Rightarrow> 'a ext0 \\<Rightarrow> 'a ext0\" where\n  \"plus_ext0 Bot Bot = Val 0\"\n| \"plus_ext0 Bot x = x\"\n| \"plus_ext0 (Val x) Bot = Val x\"\n| \"plus_ext0 (Val x) (Val y) = Val (x + y)\"\n| \"plus_ext0 (Val _) Top = Top\"\n| \"plus_ext0 Top _ = Top\"\n\nfun sup_ext0 :: \"'a ext0 \\<Rightarrow> 'a ext0 \\<Rightarrow> 'a ext0\" where\n  \"sup_ext0 Bot x = x\"\n| \"sup_ext0 (Val x) Bot = Val x\"\n| \"sup_ext0 (Val x) (Val y) = Val (max x y)\"\n| \"sup_ext0 (Val _) Top = Top\"\n| \"sup_ext0 Top _ = Top\"\n\nfun inf_ext0 :: \"'a ext0 \\<Rightarrow> 'a ext0 \\<Rightarrow> 'a ext0\" where\n  \"inf_ext0 Bot _ = Bot\"\n| \"inf_ext0 (Val _) Bot = Bot\"\n| \"inf_ext0 (Val x) (Val y) = Val (min x y)\"\n| \"inf_ext0 (Val x) Top = Val x\"\n| \"inf_ext0 Top x = x\"\n\nfun times_ext0 :: \"'a ext0 \\<Rightarrow> 'a ext0 \\<Rightarrow> 'a ext0\" where \"times_ext0 x y = x \\<sqinter> y\"\n\nfun uminus_ext0 :: \"'a ext0 \\<Rightarrow> 'a ext0\" where\n  \"uminus_ext0 Bot = Top\"\n| \"uminus_ext0 (Val _) = Bot\"\n| \"uminus_ext0 Top = Bot\"\n\nfun star_ext0 :: \"'a ext0 \\<Rightarrow> 'a ext0\" where \"star_ext0 _ = Top\"\n\nfun conv_ext0 :: \"'a ext0 \\<Rightarrow> 'a ext0\" where \"conv_ext0 x = x\"\n\ndefinition bot_ext0 :: \"'a ext0\" where \"bot_ext0 \\<equiv> Bot\"\ndefinition one_ext0 :: \"'a ext0\" where \"one_ext0 \\<equiv> Top\"\ndefinition top_ext0 :: \"'a ext0\" where \"top_ext0 \\<equiv> Top\"\n\nfun less_eq_ext0 :: \"'a ext0 \\<Rightarrow> 'a ext0 \\<Rightarrow> bool\" where\n  \"less_eq_ext0 Bot _ = True\"\n| \"less_eq_ext0 (Val _) Bot = False\"\n| \"less_eq_ext0 (Val x) (Val y) = (x \\<le> y)\"\n| \"less_eq_ext0 (Val _) Top = True\"\n| \"less_eq_ext0 Top Bot = False\"\n| \"less_eq_ext0 Top (Val _) = False\"\n| \"less_eq_ext0 Top Top = True\"\n\nfun less_ext0 :: \"'a ext0 \\<Rightarrow> 'a ext0 \\<Rightarrow> bool\" where \"less_ext0 x y = (x \\<le> y \\<and> \\<not> y \\<le> x)\"\n\ninstance\nproof\n  fix x y z :: \"'a ext0\"\n  show \"(x + y) + z = x + (y + z)\"\n    by (cases x; cases y; cases z) (simp_all add: add.assoc)\n  show \"x + y = y + x\"\n    by (cases x; cases y) (simp_all add: add.commute)\n  show \"(x < y) = (x \\<le> y \\<and> \\<not> y \\<le> x)\"\n    by simp\n  show \"x \\<le> x\"\n    using less_eq_ext0.elims(3) by fastforce\n  show \"x \\<le> y \\<Longrightarrow> y \\<le> z \\<Longrightarrow> x \\<le> z\"\n    by (cases x; cases y; cases z) simp_all\n  show \"x \\<le> y \\<Longrightarrow> y \\<le> x \\<Longrightarrow> x = y\"\n    by (cases x; cases y) simp_all\n  show \"x \\<sqinter> y \\<le> x\"\n    by (cases x; cases y) simp_all\n  show \"x \\<sqinter> y \\<le> y\"\n    by (cases x; cases y) simp_all\n  show \"x \\<le> y \\<Longrightarrow> x \\<le> z \\<Longrightarrow> x \\<le> y \\<sqinter> z\"\n    by (cases x; cases y; cases z) simp_all\n  show \"x \\<le> x \\<squnion> y\"\n    by (cases x; cases y) simp_all\n  show \"y \\<le> x \\<squnion> y\"\n    by (cases x; cases y) simp_all\n  show \"y \\<le> x \\<Longrightarrow> z \\<le> x \\<Longrightarrow> y \\<squnion> z \\<le> x\"\n    by (cases x; cases y; cases z) simp_all\n  show \"bot \\<le> x\"\n    by (simp add: bot_ext0_def)\n  show \"x \\<le> top\"\n    by (cases x) (simp_all add: top_ext0_def)\n  show \"x \\<noteq> bot \\<and> x + bot \\<le> y + bot \\<longrightarrow> x + z \\<le> y + z\"\n    apply (cases x; cases y; cases z)\n    prefer 11 using add_right_mono bot_ext0_def apply fastforce\n    by (simp_all add: bot_ext0_def add_right_mono)\n  show \"x + y + bot = x + y\"\n    by (cases x; cases y) (simp_all add: bot_ext0_def)\n  show \"x + y = bot \\<longrightarrow> x = bot\"\n    by (cases x; cases y) (simp_all add: bot_ext0_def)\n  show \"x \\<le> y \\<or> y \\<le> x\"\n    by (cases x; cases y) (simp_all add: linear)\n  show \"-x = (if x = bot then top else bot)\"\n    by (cases x) (simp_all add: bot_ext0_def top_ext0_def)\n  show \"(1::'a ext0) = top\"\n    by (simp add: one_ext0_def top_ext0_def)\n  show \"x * y = x \\<sqinter> y\"\n    by simp\n  show \"x\\<^sup>T = x\"\n    by simp\n  show \"x\\<^sup>\\<star> = top\"\n    by (simp add: top_ext0_def)\nqed\n\nend\n\ntext \\<open>\nAn example of a linearly ordered commutative monoid is the set of real numbers with standard addition and unit $0$.\n\\<close>\n\ninstantiation real :: linordered_comm_monoid_add\nbegin\n\ninstance ..\n\nend\n\nsubsection \\<open>Linearly Ordered Commutative Monoids with a Least Element\\<close>\n\ntext \\<open>\nIf a linearly ordered commutative monoid already contains a least element which is a unit of aggregation, only a new greatest element has to be added to obtain a linear aggregation lattice.\n\\<close>\n\nclass linordered_comm_monoid_add_bot = linordered_ab_semigroup_add + order_bot +\n  assumes bot_zero [simp]: \"bot + x = x\"\nbegin\n\nsublocale linordered_comm_monoid_add where zero = bot\n  apply unfold_locales\n  by simp\n\nend\n\ndatatype 'a extT =\n    Val 'a\n  | Top\n\ninstantiation extT :: (linordered_comm_monoid_add_bot) linear_aggregation_kleene_algebra\nbegin\n\nfun plus_extT :: \"'a extT \\<Rightarrow> 'a extT \\<Rightarrow> 'a extT\" where\n  \"plus_extT (Val x) (Val y) = Val (x + y)\"\n| \"plus_extT (Val _) Top = Top\"\n| \"plus_extT Top _ = Top\"\n\nfun sup_extT :: \"'a extT \\<Rightarrow> 'a extT \\<Rightarrow> 'a extT\" where\n  \"sup_extT (Val x) (Val y) = Val (max x y)\"\n| \"sup_extT (Val _) Top = Top\"\n| \"sup_extT Top _ = Top\"\n\nfun inf_extT :: \"'a extT \\<Rightarrow> 'a extT \\<Rightarrow> 'a extT\" where\n  \"inf_extT (Val x) (Val y) = Val (min x y)\"\n| \"inf_extT (Val x) Top = Val x\"\n| \"inf_extT Top x = x\"\n\nfun times_extT :: \"'a extT \\<Rightarrow> 'a extT \\<Rightarrow> 'a extT\" where \"times_extT x y = x \\<sqinter> y\"\n\nfun uminus_extT :: \"'a extT \\<Rightarrow> 'a extT\" where \"uminus_extT x = (if x = Val bot then Top else Val bot)\"\n\nfun star_extT :: \"'a extT \\<Rightarrow> 'a extT\" where \"star_extT _ = Top\"\n\nfun conv_extT :: \"'a extT \\<Rightarrow> 'a extT\" where \"conv_extT x = x\"\n\ndefinition bot_extT :: \"'a extT\" where \"bot_extT \\<equiv> Val bot\"\ndefinition one_extT :: \"'a extT\" where \"one_extT \\<equiv> Top\"\ndefinition top_extT :: \"'a extT\" where \"top_extT \\<equiv> Top\"\n\nfun less_eq_extT :: \"'a extT \\<Rightarrow> 'a extT \\<Rightarrow> bool\" where\n  \"less_eq_extT (Val x) (Val y) = (x \\<le> y)\"\n| \"less_eq_extT Top (Val _) = False\"\n| \"less_eq_extT _ Top = True\"\n\nfun less_extT :: \"'a extT \\<Rightarrow> 'a extT \\<Rightarrow> bool\" where \"less_extT x y = (x \\<le> y \\<and> \\<not> y \\<le> x)\"\n\ninstance\nproof\n  fix x y z :: \"'a extT\"\n  show \"(x + y) + z = x + (y + z)\"\n    by (cases x; cases y; cases z) (simp_all add: add.assoc)\n  show \"x + y = y + x\"\n    by (cases x; cases y) (simp_all add: add.commute)\n  show \"(x < y) = (x \\<le> y \\<and> \\<not> y \\<le> x)\"\n    by simp\n  show \"x \\<le> x\"\n    by (cases x) simp_all\n  show \"x \\<le> y \\<Longrightarrow> y \\<le> z \\<Longrightarrow> x \\<le> z\"\n    by (cases x; cases y; cases z) simp_all\n  show \"x \\<le> y \\<Longrightarrow> y \\<le> x \\<Longrightarrow> x = y\"\n    by (cases x; cases y) simp_all\n  show \"x \\<sqinter> y \\<le> x\"\n    by (cases x; cases y) simp_all\n  show \"x \\<sqinter> y \\<le> y\"\n    by (cases x; cases y) simp_all\n  show \"x \\<le> y \\<Longrightarrow> x \\<le> z \\<Longrightarrow> x \\<le> y \\<sqinter> z\"\n    by (cases x; cases y; cases z) simp_all\n  show \"x \\<le> x \\<squnion> y\"\n    by (cases x; cases y) simp_all\n  show \"y \\<le> x \\<squnion> y\"\n    by (cases x; cases y) simp_all\n  show \"y \\<le> x \\<Longrightarrow> z \\<le> x \\<Longrightarrow> y \\<squnion> z \\<le> x\"\n    by (cases x; cases y; cases z) simp_all\n  show \"bot \\<le> x\"\n    by (cases x) (simp_all add: bot_extT_def)\n  show \"x \\<le> top\"\n    by (cases x) (simp_all add: top_extT_def)\n  show \"x \\<noteq> bot \\<and> x + bot \\<le> y + bot \\<longrightarrow> x + z \\<le> y + z\"\n    by (cases x; cases y; cases z) (simp_all add: bot_extT_def add_right_mono)\n  show \"x + y + bot = x + y\"\n    by (cases x; cases y) (simp_all add: bot_extT_def)\n  show \"x + y = bot \\<longrightarrow> x = bot\"\n    apply (cases x; cases y)\n    apply (metis (mono_tags) add.commute add_right_mono bot.extremum bot.extremum_uniqueI bot_zero extT.inject plus_extT.simps(1) bot_extT_def)\n    by (simp_all add: bot_extT_def)\n  show \"x \\<le> y \\<or> y \\<le> x\"\n    by (cases x; cases y) (simp_all add: linear)\n  show \"-x = (if x = bot then top else bot)\"\n    by (cases x) (simp_all add: bot_extT_def top_extT_def)\n  show \"(1::'a extT) = top\"\n    by (simp add: one_extT_def top_extT_def)\n  show \"x * y = x \\<sqinter> y\"\n    by simp\n  show \"x\\<^sup>T = x\"\n    by simp\n  show \"x\\<^sup>\\<star> = top\"\n    by (simp add: top_extT_def)\nqed\n\nend\n\ntext \\<open>\nAn example of a linearly ordered commutative monoid with a least element is the set of real numbers extended by minus infinity with maximum as aggregation.\n\\<close>\n\ndatatype real_max_bot =\n    MInfty\n  | R real\n\ninstantiation real_max_bot :: linordered_comm_monoid_add_bot\nbegin\n\ndefinition \"bot_real_max_bot \\<equiv> MInfty\"\n\nfun less_eq_real_max_bot where\n  \"less_eq_real_max_bot MInfty _ = True\"\n| \"less_eq_real_max_bot (R _) MInfty = False\"\n| \"less_eq_real_max_bot (R x) (R y) = (x \\<le> y)\"\n\nfun less_real_max_bot where\n  \"less_real_max_bot _ MInfty = False\"\n| \"less_real_max_bot MInfty (R _) = True\"\n| \"less_real_max_bot (R x) (R y) = (x < y)\"\n\nfun plus_real_max_bot where\n  \"plus_real_max_bot MInfty y = y\"\n| \"plus_real_max_bot x MInfty = x\"\n| \"plus_real_max_bot (R x) (R y) = R (max x y)\"\n\ninstance\nproof\n  fix x y z :: real_max_bot\n  show \"(x + y) + z = x + (y + z)\"\n    by (cases x; cases y; cases z) simp_all\n  show \"x + y = y + x\"\n    by (cases x; cases y) simp_all\n  show \"(x < y) = (x \\<le> y \\<and> \\<not> y \\<le> x)\"\n    by (cases x; cases y) auto\n  show \"x \\<le> x\"\n    by (cases x) simp_all\n  show \"x \\<le> y \\<Longrightarrow> y \\<le> z \\<Longrightarrow> x \\<le> z\"\n    by (cases x; cases y; cases z) simp_all\n  show \"x \\<le> y \\<Longrightarrow> y \\<le> x \\<Longrightarrow> x = y\"\n    by (cases x; cases y) simp_all\n  show \"x \\<le> y \\<Longrightarrow> z + x \\<le> z + y\"\n    by (cases x; cases y; cases z) simp_all\n  show \"x \\<le> y \\<or> y \\<le> x\"\n    by (cases x; cases y) auto\n  show \"bot \\<le> x\"\n    by (cases x) (simp_all add: bot_real_max_bot_def)\n  show \"bot + x = x\"\n    by (cases x) (simp_all add: bot_real_max_bot_def)\nqed\n\nend\n\nsubsection \\<open>Linearly Ordered Commutative Monoids with a Greatest Element\\<close>\n\ntext \\<open>\nIf a linearly ordered commutative monoid already contains a greatest element which is a unit of aggregation, only a new least element has to be added to obtain a linear aggregation lattice.\n\\<close>\n\nclass linordered_comm_monoid_add_top = linordered_ab_semigroup_add + order_top +\n  assumes top_zero [simp]: \"top + x = x\"\nbegin\n\nsublocale linordered_comm_monoid_add where zero = top\n  apply unfold_locales\n  by simp\n\nlemma add_decreasing: \"x + y \\<le> x\"\n  using add_left_mono top.extremum by fastforce\n\n\n\nend\n\ndatatype 'a extB =\n    Bot\n  | Val 'a\n\ninstantiation extB :: (linordered_comm_monoid_add_top) linear_aggregation_kleene_algebra\nbegin\n\nfun plus_extB :: \"'a extB \\<Rightarrow> 'a extB \\<Rightarrow> 'a extB\" where\n  \"plus_extB Bot Bot = Val top\"\n| \"plus_extB Bot (Val x) = Val x\"\n| \"plus_extB (Val x) Bot = Val x\"\n| \"plus_extB (Val x) (Val y) = Val (x + y)\"\n\nfun sup_extB :: \"'a extB \\<Rightarrow> 'a extB \\<Rightarrow> 'a extB\" where\n  \"sup_extB Bot x = x\"\n| \"sup_extB (Val x) Bot = Val x\"\n| \"sup_extB (Val x) (Val y) = Val (max x y)\"\n\nfun inf_extB :: \"'a extB \\<Rightarrow> 'a extB \\<Rightarrow> 'a extB\" where\n  \"inf_extB Bot _ = Bot\"\n| \"inf_extB (Val _) Bot = Bot\"\n| \"inf_extB (Val x) (Val y) = Val (min x y)\"\n\nfun times_extB :: \"'a extB \\<Rightarrow> 'a extB \\<Rightarrow> 'a extB\" where \"times_extB x y = x \\<sqinter> y\"\n\nfun uminus_extB :: \"'a extB \\<Rightarrow> 'a extB\" where\n  \"uminus_extB Bot = Val top\"\n| \"uminus_extB (Val _) = Bot\"\n\nfun star_extB :: \"'a extB \\<Rightarrow> 'a extB\" where \"star_extB _ = Val top\"\n\nfun conv_extB :: \"'a extB \\<Rightarrow> 'a extB\" where \"conv_extB x = x\"\n\ndefinition bot_extB :: \"'a extB\" where \"bot_extB \\<equiv> Bot\"\ndefinition one_extB :: \"'a extB\" where \"one_extB \\<equiv> Val top\"\ndefinition top_extB :: \"'a extB\" where \"top_extB \\<equiv> Val top\"\n\nfun less_eq_extB :: \"'a extB \\<Rightarrow> 'a extB \\<Rightarrow> bool\" where\n  \"less_eq_extB Bot _ = True\"\n| \"less_eq_extB (Val _) Bot = False\"\n| \"less_eq_extB (Val x) (Val y) = (x \\<le> y)\"\n\nfun less_extB :: \"'a extB \\<Rightarrow> 'a extB \\<Rightarrow> bool\" where \"less_extB x y = (x \\<le> y \\<and> \\<not> y \\<le> x)\"\n\ninstance\nproof\n  fix x y z :: \"'a extB\"\n  show \"(x + y) + z = x + (y + z)\"\n    by (cases x; cases y; cases z) (simp_all add: add.assoc)\n  show \"x + y = y + x\"\n    by (cases x; cases y) (simp_all add: add.commute)\n  show \"(x < y) = (x \\<le> y \\<and> \\<not> y \\<le> x)\"\n    by simp\n  show \"x \\<le> x\"\n    by (cases x) simp_all\n  show \"x \\<le> y \\<Longrightarrow> y \\<le> z \\<Longrightarrow> x \\<le> z\"\n    by (cases x; cases y; cases z) simp_all\n  show \"x \\<le> y \\<Longrightarrow> y \\<le> x \\<Longrightarrow> x = y\"\n    by (cases x; cases y) simp_all\n  show \"x \\<sqinter> y \\<le> x\"\n    by (cases x; cases y) simp_all\n  show \"x \\<sqinter> y \\<le> y\"\n    by (cases x; cases y) simp_all\n  show \"x \\<le> y \\<Longrightarrow> x \\<le> z \\<Longrightarrow> x \\<le> y \\<sqinter> z\"\n    by (cases x; cases y; cases z) simp_all\n  show \"x \\<le> x \\<squnion> y\"\n    by (cases x; cases y) simp_all\n  show \"y \\<le> x \\<squnion> y\"\n    by (cases x; cases y) simp_all\n  show \"y \\<le> x \\<Longrightarrow> z \\<le> x \\<Longrightarrow> y \\<squnion> z \\<le> x\"\n    by (cases x; cases y; cases z) simp_all\n  show \"bot \\<le> x\"\n    by (simp add: bot_extB_def)\n  show 1: \"x \\<le> top\"\n    by (cases x) (simp_all add: top_extB_def)\n  show \"x \\<noteq> bot \\<and> x + bot \\<le> y + bot \\<longrightarrow> x + z \\<le> y + z\"\n    apply (cases x; cases y; cases z)\n    prefer 6 using 1 apply (metis (mono_tags, lifting) plus_extB.simps(2,4) top_extB_def add_right_mono less_eq_extB.simps(3) top_zero)\n    by (simp_all add: bot_extB_def add_right_mono)\n  show \"x + y + bot = x + y\"\n    by (cases x; cases y) (simp_all add: bot_extB_def)\n  show \"x + y = bot \\<longrightarrow> x = bot\"\n    by (cases x; cases y) (simp_all add: bot_extB_def)\n  show \"x \\<le> y \\<or> y \\<le> x\"\n    by (cases x; cases y) (simp_all add: linear)\n  show \"-x = (if x = bot then top else bot)\"\n    by (cases x) (simp_all add: bot_extB_def top_extB_def)\n  show \"(1::'a extB) = top\"\n    by (simp add: one_extB_def top_extB_def)\n  show \"x * y = x \\<sqinter> y\"\n    by simp\n  show \"x\\<^sup>T = x\"\n    by simp\n  show \"x\\<^sup>\\<star> = top\"\n    by (simp add: top_extB_def)\nqed\n\nend\n\ntext \\<open>\nAn example of a linearly ordered commutative monoid with a greatest element is the set of real numbers extended by infinity with minimum as aggregation.\n\\<close>\n\ndatatype real_min_top =\n    R real\n  | PInfty\n\ninstantiation real_min_top :: linordered_comm_monoid_add_top\nbegin\n\ndefinition \"top_real_min_top \\<equiv> PInfty\"\n\nfun less_eq_real_min_top where\n  \"less_eq_real_min_top _ PInfty = True\"\n| \"less_eq_real_min_top PInfty (R _) = False\"\n| \"less_eq_real_min_top (R x) (R y) = (x \\<le> y)\"\n\nfun less_real_min_top where\n  \"less_real_min_top PInfty _ = False\"\n| \"less_real_min_top (R _) PInfty = True\"\n| \"less_real_min_top (R x) (R y) = (x < y)\"\n\nfun plus_real_min_top where\n  \"plus_real_min_top PInfty y = y\"\n| \"plus_real_min_top x PInfty = x\"\n| \"plus_real_min_top (R x) (R y) = R (min x y)\"\n\ninstance\nproof\n  fix x y z :: real_min_top\n  show \"(x + y) + z = x + (y + z)\"\n    by (cases x; cases y; cases z) simp_all\n  show \"x + y = y + x\"\n    by (cases x; cases y) simp_all\n  show \"(x < y) = (x \\<le> y \\<and> \\<not> y \\<le> x)\"\n    by (cases x; cases y) auto\n  show \"x \\<le> x\"\n    by (cases x) simp_all\n  show \"x \\<le> y \\<Longrightarrow> y \\<le> z \\<Longrightarrow> x \\<le> z\"\n    by (cases x; cases y; cases z) simp_all\n  show \"x \\<le> y \\<Longrightarrow> y \\<le> x \\<Longrightarrow> x = y\"\n    by (cases x; cases y) simp_all\n  show \"x \\<le> y \\<Longrightarrow> z + x \\<le> z + y\"\n    by (cases x; cases y; cases z) simp_all\n  show \"x \\<le> y \\<or> y \\<le> x\"\n    by (cases x; cases y) auto\n  show \"x \\<le> top\"\n    by (cases x) (simp_all add: top_real_min_top_def)\n  show \"top + x = x\"\n    by (cases x) (simp_all add: top_real_min_top_def)\nqed\n\nend\n\ntext \\<open>\nAnother example of a linearly ordered commutative monoid with a greatest element is the unit interval of real numbers with any triangular norm (t-norm) as aggregation.\nIdeally, we would like to show that the unit interval is an instance of \\<open>linordered_comm_monoid_add_top\\<close>.\nHowever, this class has an addition operation, so the instantiation would require dependent types.\nWe therefore show only the order property in general and a particular instance of the class.\n\\<close>\n\ntypedef (overloaded) unit = \"{0..1} :: real set\"\n  by auto\n\nsetup_lifting type_definition_unit\n\ninstantiation unit :: bounded_linorder\nbegin\n\nlift_definition bot_unit :: unit is 0\n  by simp\n\nlift_definition top_unit :: unit is 1\n  by simp\n\nlift_definition less_eq_unit :: \"unit \\<Rightarrow> unit \\<Rightarrow> bool\" is less_eq .\n\nlift_definition less_unit :: \"unit \\<Rightarrow> unit \\<Rightarrow> bool\" is less .\n\ninstance\n  apply intro_classes\n  using bot_unit.rep_eq top_unit.rep_eq less_eq_unit.rep_eq less_unit.rep_eq unit.Rep_unit_inject unit.Rep_unit by auto\n\nend\n\ntext \\<open>\nWe give the \\L{}ukasiewicz t-norm as a particular instance.\n\\<close>\n\ninstantiation unit :: linordered_comm_monoid_add_top\nbegin\n\nabbreviation tl :: \"real \\<Rightarrow> real \\<Rightarrow> real\" where\n  \"tl x y \\<equiv> max (x + y - 1) 0\"\n\nlemma tl_assoc:\n  \"x \\<in> {0..1} \\<Longrightarrow> z \\<in> {0..1} \\<Longrightarrow> tl (tl x y) z = tl x (tl y z)\"\n  by auto\n\nlemma tl_top_zero:\n  \"x \\<in> {0..1} \\<Longrightarrow> tl 1 x = x\"\n  by auto\n\nlift_definition plus_unit :: \"unit \\<Rightarrow> unit \\<Rightarrow> unit\" is tl\n  by simp\n\ninstance\n  apply intro_classes\n  apply (metis (mono_tags, lifting) plus_unit.rep_eq unit.Rep_unit_inject unit.Rep_unit tl_assoc)\n  using unit.Rep_unit_inject plus_unit.rep_eq apply fastforce\n  apply (simp add: less_eq_unit.rep_eq plus_unit.rep_eq)\n  by (metis (mono_tags, lifting) top_unit.rep_eq unit.Rep_unit_inject unit.Rep_unit plus_unit.rep_eq tl_top_zero)\n\nend\n\nsubsection \\<open>Linearly Ordered Commutative Monoids with a Least Element and a Greatest Element\\<close>\n\ntext \\<open>\nIf a linearly ordered commutative monoid already contains a least element which is a unit of aggregation and a greatest element, it forms a linear aggregation lattice.\n\\<close>\n\nclass linordered_bounded_comm_monoid_add_bot = linordered_comm_monoid_add_bot + order_top\nbegin\n\nsubclass bounded_linorder ..\n\nsubclass aggregation_order\n  apply unfold_locales\n  apply (simp add: add_right_mono)\n  apply simp\n  by (metis add_0_right add_left_mono bot.extremum bot.extremum_unique)\n\nsublocale linear_aggregation_kleene_algebra where sup = max and inf = min and times = min and conv = id and one = top and star = \"\\<lambda>x . top\" and uminus = \"\\<lambda>x . if x = bot then top else bot\"\n  apply unfold_locales\n  by simp_all\n\nlemma t_top: \"x + top = top\"\n  by (metis add_right_mono bot.extremum bot_zero top_unique)\n\nlemma add_increasing: \"x \\<le> x + y\"\n  using add_left_mono bot.extremum by fastforce\n\nlemma t_max: \"max x y \\<le> x + y\"\n  using add_commute add_increasing by force\n\nend\n\ntext \\<open>\nAn example of a linearly ordered commutative monoid with a least and a greatest element is the unit interval of real numbers with any triangular conorm (t-conorm) as aggregation.\nFor the reason outlined above, we show just a particular instance of \\<open>linordered_bounded_comm_monoid_add_bot\\<close>.\nBecause the \\<open>plus\\<close> functions in the two instances given for the unit type are different, we work on a copy of the unit type.\n\\<close>\n\ntypedef (overloaded) unit2 = \"{0..1} :: real set\"\n  by auto\n\nsetup_lifting type_definition_unit2\n\ninstantiation unit2 :: bounded_linorder\nbegin\n\nlift_definition bot_unit2 :: unit2 is 0\n  by simp\n\nlift_definition top_unit2 :: unit2 is 1\n  by simp\n\nlift_definition less_eq_unit2 :: \"unit2 \\<Rightarrow> unit2 \\<Rightarrow> bool\" is less_eq .\n\nlift_definition less_unit2 :: \"unit2 \\<Rightarrow> unit2 \\<Rightarrow> bool\" is less .\n\ninstance\n  apply intro_classes\n  using bot_unit2.rep_eq top_unit2.rep_eq less_eq_unit2.rep_eq less_unit2.rep_eq unit2.Rep_unit2_inject unit2.Rep_unit2 by auto\n\nend\n\ntext \\<open>\nWe give the product t-conorm as a particular instance.\n\\<close>\n\ninstantiation unit2 :: linordered_bounded_comm_monoid_add_bot\nbegin\n\nabbreviation sp :: \"real \\<Rightarrow> real \\<Rightarrow> real\" where\n  \"sp x y \\<equiv> x + y - x * y\"\n\nlemma sp_assoc:\n  \"sp (sp x y) z = sp x (sp y z)\"\n  by (unfold left_diff_distrib right_diff_distrib distrib_left distrib_right) simp\n\nlemma sp_mono:\n  assumes \"z \\<in> {0..1}\"\n      and \"x \\<le> y\"\n    shows \"sp z x \\<le> sp z y\"\nproof -\n  have \"z + (1 - z) * x \\<le> z + (1 - z) * y\"\n    using assms mult_left_mono by fastforce\n  thus ?thesis\n    by (unfold left_diff_distrib right_diff_distrib distrib_left distrib_right) simp\nqed\n\nlift_definition plus_unit2 :: \"unit2 \\<Rightarrow> unit2 \\<Rightarrow> unit2\" is sp\nproof -\n  fix x y :: real\n  assume 1: \"x \\<in> {0..1}\"\n  assume 2: \"y \\<in> {0..1}\"\n  have \"x - x * y \\<le> 1 - y\"\n    using 1 2 by (metis (full_types) atLeastAtMost_iff diff_ge_0_iff_ge left_diff_distrib' mult.commute mult.left_neutral mult_left_le)\n  hence 3: \"x + y - x * y \\<le> 1\"\n    by simp\n  have \"y * (x - 1) \\<le> 0\"\n    using 1 2 by (meson atLeastAtMost_iff le_iff_diff_le_0 mult_nonneg_nonpos)\n  hence \"x + y - x * y \\<ge> 0\"\n    using 1 by (metis (no_types) atLeastAtMost_iff diff_diff_eq2 diff_ge_0_iff_ge left_diff_distrib mult.commute mult.left_neutral order_trans)\n  thus \"x + y - x * y \\<in> {0..1}\"\n    using 3 by simp\nqed\n\ninstance\n  apply intro_classes\n  apply (metis (mono_tags, lifting) plus_unit2.rep_eq unit2.Rep_unit2_inject sp_assoc)\n  using unit2.Rep_unit2_inject plus_unit2.rep_eq apply fastforce\n  using sp_mono unit2.Rep_unit2 less_eq_unit2.rep_eq plus_unit2.rep_eq apply simp\n  using bot_unit2.rep_eq unit2.Rep_unit2_inject plus_unit2.rep_eq by fastforce\n\nend\n\nsubsection \\<open>Constant Aggregation\\<close>\n\ntext \\<open>\nAny linear order with a constant element extended by new least and greatest elements forms a linear aggregation lattice where the aggregation returns the given constant.\n\\<close>\n\nclass pointed_linorder = linorder +\n  fixes const :: 'a\n\ndatatype 'a extC =\n    Bot\n  | Val 'a\n  | Top\n\ninstantiation extC :: (pointed_linorder) linear_aggregation_kleene_algebra\nbegin\n\nfun plus_extC :: \"'a extC \\<Rightarrow> 'a extC \\<Rightarrow> 'a extC\" where \"plus_extC x y = Val const\"\n\nfun sup_extC :: \"'a extC \\<Rightarrow> 'a extC \\<Rightarrow> 'a extC\" where\n  \"sup_extC Bot x = x\"\n| \"sup_extC (Val x) Bot = Val x\"\n| \"sup_extC (Val x) (Val y) = Val (max x y)\"\n| \"sup_extC (Val _) Top = Top\"\n| \"sup_extC Top _ = Top\"\n\nfun inf_extC :: \"'a extC \\<Rightarrow> 'a extC \\<Rightarrow> 'a extC\" where\n  \"inf_extC Bot _ = Bot\"\n| \"inf_extC (Val _) Bot = Bot\"\n| \"inf_extC (Val x) (Val y) = Val (min x y)\"\n| \"inf_extC (Val x) Top = Val x\"\n| \"inf_extC Top x = x\"\n\nfun times_extC :: \"'a extC \\<Rightarrow> 'a extC \\<Rightarrow> 'a extC\" where \"times_extC x y = x \\<sqinter> y\"\n\nfun uminus_extC :: \"'a extC \\<Rightarrow> 'a extC\" where\n  \"uminus_extC Bot = Top\"\n| \"uminus_extC (Val _) = Bot\"\n| \"uminus_extC Top = Bot\"\n\nfun star_extC :: \"'a extC \\<Rightarrow> 'a extC\" where \"star_extC _ = Top\"\n\nfun conv_extC :: \"'a extC \\<Rightarrow> 'a extC\" where \"conv_extC x = x\"\n\ndefinition bot_extC :: \"'a extC\" where \"bot_extC \\<equiv> Bot\"\ndefinition one_extC :: \"'a extC\" where \"one_extC \\<equiv> Top\"\ndefinition top_extC :: \"'a extC\" where \"top_extC \\<equiv> Top\"\n\nfun less_eq_extC :: \"'a extC \\<Rightarrow> 'a extC \\<Rightarrow> bool\" where\n  \"less_eq_extC Bot _ = True\"\n| \"less_eq_extC (Val _) Bot = False\"\n| \"less_eq_extC (Val x) (Val y) = (x \\<le> y)\"\n| \"less_eq_extC (Val _) Top = True\"\n| \"less_eq_extC Top Bot = False\"\n| \"less_eq_extC Top (Val _) = False\"\n| \"less_eq_extC Top Top = True\"\n\nfun less_extC :: \"'a extC \\<Rightarrow> 'a extC \\<Rightarrow> bool\" where \"less_extC x y = (x \\<le> y \\<and> \\<not> y \\<le> x)\"\n\ninstance\nproof\n  fix x y z :: \"'a extC\"\n  show \"(x + y) + z = x + (y + z)\"\n    by simp\n  show \"x + y = y + x\"\n    by simp\n  show \"(x < y) = (x \\<le> y \\<and> \\<not> y \\<le> x)\"\n    by simp\n  show \"x \\<le> x\"\n    by (cases x) simp_all\n  show \"x \\<le> y \\<Longrightarrow> y \\<le> z \\<Longrightarrow> x \\<le> z\"\n    by (cases x; cases y; cases z) simp_all\n  show \"x \\<le> y \\<Longrightarrow> y \\<le> x \\<Longrightarrow> x = y\"\n    by (cases x; cases y) simp_all\n  show \"x \\<sqinter> y \\<le> x\"\n    by (cases x; cases y) simp_all\n  show \"x \\<sqinter> y \\<le> y\"\n    by (cases x; cases y) simp_all\n  show \"x \\<le> y \\<Longrightarrow> x \\<le> z \\<Longrightarrow> x \\<le> y \\<sqinter> z\"\n    by (cases x; cases y; cases z) simp_all\n  show \"x \\<le> x \\<squnion> y\"\n    by (cases x; cases y) simp_all\n  show \"y \\<le> x \\<squnion> y\"\n    by (cases x; cases y) simp_all\n  show \"y \\<le> x \\<Longrightarrow> z \\<le> x \\<Longrightarrow> y \\<squnion> z \\<le> x\"\n    by (cases x; cases y; cases z) simp_all\n  show \"bot \\<le> x\"\n    by (simp add: bot_extC_def)\n  show \"x \\<le> top\"\n    by (cases x) (simp_all add: top_extC_def)\n  show \"x \\<noteq> bot \\<and> x + bot \\<le> y + bot \\<longrightarrow> x + z \\<le> y + z\"\n    by simp\n  show \"x + y + bot = x + y\"\n    by simp\n  show \"x + y = bot \\<longrightarrow> x = bot\"\n    by (simp add: bot_extC_def)\n  show \"x \\<le> y \\<or> y \\<le> x\"\n    by (cases x; cases y) (simp_all add: linear)\n  show \"-x = (if x = bot then top else bot)\"\n    by (cases x) (simp_all add: bot_extC_def top_extC_def)\n  show \"(1::'a extC) = top\"\n    by (simp add: one_extC_def top_extC_def)\n  show \"x * y = x \\<sqinter> y\"\n    by simp\n  show \"x\\<^sup>T = x\"\n    by simp\n  show \"x\\<^sup>\\<star> = top\"\n    by (simp add: top_extC_def)\nqed\n\nend\n\ntext \\<open>\nAn example of a linear order is the set of real numbers.\nAny real number can be chosen as the constant.\n\\<close>\n\ninstantiation real :: pointed_linorder\nbegin\n\ninstance ..\n\nend\n\ntext \\<open>\nThe following instance shows that any linear order with a constant forms a linearly ordered commutative semigroup with the alpha-median operation as aggregation.\nThe alpha-median of two elements is the median of these elements and the given constant.\n\\<close>\n\nfun median3 :: \"'a::ord \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> 'a\" where\n  \"median3 x y z =\n    (if x \\<le> y \\<and> y \\<le> z then y else\n     if x \\<le> z \\<and> z \\<le> y then z else\n     if y \\<le> x \\<and> x \\<le> z then x else\n     if y \\<le> z \\<and> z \\<le> x then z else\n     if z \\<le> x \\<and> x \\<le> y then x else y)\"\n\ninterpretation alpha_median: linordered_ab_semigroup_add where plus = \"median3 const\" and less_eq = less_eq and less = less\nproof\n  fix a b c :: 'a\n  show \"median3 const (median3 const a b) c = median3 const a (median3 const b c)\"\n    by (cases \"const \\<le> a\"; cases \"const \\<le> b\"; cases \"const \\<le> c\"; cases \"a \\<le> b\"; cases \"a \\<le> c\"; cases \"b \\<le> c\") auto\n  show \"median3 const a b = median3 const b a\"\n    by (cases \"const \\<le> a\"; cases \"const \\<le> b\"; cases \"a \\<le> b\") auto\n  assume \"a \\<le> b\"\n  thus \"median3 const c a \\<le> median3 const c b\"\n    by (cases \"const \\<le> a\"; cases \"const \\<le> b\"; cases \"const \\<le> c\"; cases \"a \\<le> c\"; cases \"b \\<le> c\") auto\nqed\n\nsubsection \\<open>Counting Aggregation\\<close>\n\ntext \\<open>\nAny linear order extended by new least and greatest elements and a copy of the natural numbers forms a linear aggregation lattice where the aggregation counts non-$\\bot$ elements using the copy of the natural numbers.\n\\<close>\n\ndatatype 'a extN =\n    Bot\n  | Val 'a\n  | N nat\n  | Top\n\ninstantiation extN :: (linorder) linear_aggregation_kleene_algebra\nbegin\n\nfun plus_extN :: \"'a extN \\<Rightarrow> 'a extN \\<Rightarrow> 'a extN\" where\n  \"plus_extN Bot Bot = N 0\"\n| \"plus_extN Bot (Val _) = N 1\"\n| \"plus_extN Bot (N y) = N y\"\n| \"plus_extN Bot Top = N 1\"\n| \"plus_extN (Val _) Bot = N 1\"\n| \"plus_extN (Val _) (Val _) = N 2\"\n| \"plus_extN (Val _) (N y) = N (y + 1)\"\n| \"plus_extN (Val _) Top = N 2\"\n| \"plus_extN (N x) Bot = N x\"\n| \"plus_extN (N x) (Val _) = N (x + 1)\"\n| \"plus_extN (N x) (N y) = N (x + y)\"\n| \"plus_extN (N x) Top = N (x + 1)\"\n| \"plus_extN Top Bot = N 1\"\n| \"plus_extN Top (Val _) = N 2\"\n| \"plus_extN Top (N y) = N (y + 1)\"\n| \"plus_extN Top Top = N 2\"\n\nfun sup_extN :: \"'a extN \\<Rightarrow> 'a extN \\<Rightarrow> 'a extN\" where\n  \"sup_extN Bot x = x\"\n| \"sup_extN (Val x) Bot = Val x\"\n| \"sup_extN (Val x) (Val y) = Val (max x y)\"\n| \"sup_extN (Val _) (N y) = N y\"\n| \"sup_extN (Val _) Top = Top\"\n| \"sup_extN (N x) Bot = N x\"\n| \"sup_extN (N x) (Val _) = N x\"\n| \"sup_extN (N x) (N y) = N (max x y)\"\n| \"sup_extN (N _) Top = Top\"\n| \"sup_extN Top _ = Top\"\n\nfun inf_extN :: \"'a extN \\<Rightarrow> 'a extN \\<Rightarrow> 'a extN\" where\n  \"inf_extN Bot _ = Bot\"\n| \"inf_extN (Val _) Bot = Bot\"\n| \"inf_extN (Val x) (Val y) = Val (min x y)\"\n| \"inf_extN (Val x) (N _) = Val x\"\n| \"inf_extN (Val x) Top = Val x\"\n| \"inf_extN (N _) Bot = Bot\"\n| \"inf_extN (N _) (Val y) = Val y\"\n| \"inf_extN (N x) (N y) = N (min x y)\"\n| \"inf_extN (N x) Top = N x\"\n| \"inf_extN Top y = y\"\n\nfun times_extN :: \"'a extN \\<Rightarrow> 'a extN \\<Rightarrow> 'a extN\" where \"times_extN x y = x \\<sqinter> y\"\n\nfun uminus_extN :: \"'a extN \\<Rightarrow> 'a extN\" where\n  \"uminus_extN Bot = Top\"\n| \"uminus_extN (Val _) = Bot\"\n| \"uminus_extN (N _) = Bot\"\n| \"uminus_extN Top = Bot\"\n\nfun star_extN :: \"'a extN \\<Rightarrow> 'a extN\" where \"star_extN _ = Top\"\n\nfun conv_extN :: \"'a extN \\<Rightarrow> 'a extN\" where \"conv_extN x = x\"\n\ndefinition bot_extN :: \"'a extN\" where \"bot_extN \\<equiv> Bot\"\ndefinition one_extN :: \"'a extN\" where \"one_extN \\<equiv> Top\"\ndefinition top_extN :: \"'a extN\" where \"top_extN \\<equiv> Top\"\n\nfun less_eq_extN :: \"'a extN \\<Rightarrow> 'a extN \\<Rightarrow> bool\" where\n  \"less_eq_extN Bot _ = True\"\n| \"less_eq_extN (Val _) Bot = False\"\n| \"less_eq_extN (Val x) (Val y) = (x \\<le> y)\"\n| \"less_eq_extN (Val _) (N _) = True\"\n| \"less_eq_extN (Val _) Top = True\"\n| \"less_eq_extN (N _) Bot = False\"\n| \"less_eq_extN (N _) (Val _) = False\"\n| \"less_eq_extN (N x) (N y) = (x \\<le> y)\"\n| \"less_eq_extN (N _) Top = True\"\n| \"less_eq_extN Top Bot = False\"\n| \"less_eq_extN Top (Val _) = False\"\n| \"less_eq_extN Top (N _) = False\"\n| \"less_eq_extN Top Top = True\"\n\nfun less_extN :: \"'a extN \\<Rightarrow> 'a extN \\<Rightarrow> bool\" where \"less_extN x y = (x \\<le> y \\<and> \\<not> y \\<le> x)\"\n\ninstance\nproof\n  fix x y z :: \"'a extN\"\n  show \"(x + y) + z = x + (y + z)\"\n    by (cases x; cases y; cases z) simp_all\n  show \"x + y = y + x\"\n    by (cases x; cases y) simp_all\n  show \"(x < y) = (x \\<le> y \\<and> \\<not> y \\<le> x)\"\n    by simp\n  show \"x \\<le> x\"\n    by (cases x) simp_all\n  show \"x \\<le> y \\<Longrightarrow> y \\<le> z \\<Longrightarrow> x \\<le> z\"\n    by (cases x; cases y; cases z) simp_all\n  show \"x \\<le> y \\<Longrightarrow> y \\<le> x \\<Longrightarrow> x = y\"\n    by (cases x; cases y) simp_all\n  show \"x \\<sqinter> y \\<le> x\"\n    by (cases x; cases y) simp_all\n  show \"x \\<sqinter> y \\<le> y\"\n    by (cases x; cases y) simp_all\n  show \"x \\<le> y \\<Longrightarrow> x \\<le> z \\<Longrightarrow> x \\<le> y \\<sqinter> z\"\n    by (cases x; cases y; cases z) simp_all\n  show \"x \\<le> x \\<squnion> y\"\n    by (cases x; cases y) simp_all\n  show \"y \\<le> x \\<squnion> y\"\n    by (cases x; cases y) simp_all\n  show \"y \\<le> x \\<Longrightarrow> z \\<le> x \\<Longrightarrow> y \\<squnion> z \\<le> x\"\n    by (cases x; cases y; cases z) simp_all\n  show \"bot \\<le> x\"\n    by (simp add: bot_extN_def)\n  show \"x \\<le> top\"\n    by (cases x) (simp_all add: top_extN_def)\n  show \"x \\<noteq> bot \\<and> x + bot \\<le> y + bot \\<longrightarrow> x + z \\<le> y + z\"\n    by (cases x; cases y; cases z) (simp_all add: bot_extN_def)\n  show \"x + y + bot = x + y\"\n    by (cases x; cases y) (simp_all add: bot_extN_def)\n  show \"x + y = bot \\<longrightarrow> x = bot\"\n    by (cases x; cases y) (simp_all add: bot_extN_def)\n  show \"x \\<le> y \\<or> y \\<le> x\"\n    by (cases x; cases y) (simp_all add: linear)\n  show \"-x = (if x = bot then top else bot)\"\n    by (cases x) (simp_all add: bot_extN_def top_extN_def)\n  show \"(1::'a extN) = top\"\n    by (simp add: one_extN_def top_extN_def)\n  show \"x * y = x \\<sqinter> y\"\n    by simp\n  show \"x\\<^sup>T = x\"\n    by simp\n  show \"x\\<^sup>\\<star> = top\"\n    by (simp add: top_extN_def)\nqed\n\nend\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/Aggregation_Algebras/Linear_Aggregation_Algebras.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8856314677809304, "lm_q2_score": 0.7905303285397349, "lm_q1q2_score": 0.7001185351899866}}
{"text": "(* Title:       Proving the impossibility of trisecting an angle and doubling the cube\n   Authors:     Ralph Romanos <ralph.romanos at student.ecp.fr> (2012), \n                Lawrence Paulson <lp15 at cam.ac.uk> (2012)\n   Maintainer:  Ralph Romanos <ralph.romanos at student.ecp.fr>\n*)\n\nheader {* Proving the impossibility of trisecting an angle and doubling the cube *}\n\ntheory Impossible_Geometry \nimports Complex_Main\nbegin\n\nsection {* Formal Proof *}\n\nsubsection {* Definition of the set of Points *}\n\ndatatype point = Point real real\n\ndefinition points_def:\n  \"points = {M. \\<exists> x \\<in> \\<real>. \\<exists> y \\<in> \\<real>. (M = Point x y)}\"\n\nprimrec abscissa :: \"point => real\"\n  where abscissa: \"abscissa (Point x y) = x\"\n\nprimrec ordinate :: \"point => real\"\n  where ordinate: \"ordinate (Point x y) = y\"\n\nlemma point_surj [simp]: \n  \"Point (abscissa M) (ordinate M) = M\"\n  by (induct M) simp\n\nlemma point_eqI [intro?]: \n  \"\\<lbrakk>abscissa M = abscissa N; ordinate M = ordinate N\\<rbrakk> \\<Longrightarrow> M = N\"\n  by (induct M, induct N) simp\n\nlemma point_eq_iff: \n  \"M = N <-> abscissa M = abscissa N \\<and> ordinate M = ordinate N\"\n  by (induct M, induct N) simp\n\nsubsection {* Subtraction *}\n\ntext {* Datatype point has a structure of abelian group *}\n\ninstantiation point :: ab_group_add\nbegin\n\ndefinition point_zero_def:\n  \"0 = Point 0 0\"\n\ndefinition point_one_def:\n  \"point_one = Point 1 0\"\n\ndefinition point_add_def:\n  \"A + B = Point (abscissa A + abscissa B) (ordinate A + ordinate B)\"\n\ndefinition point_minus_def:\n  \"- A = Point (- abscissa A) (- ordinate A)\"\n\ndefinition point_diff_def:\n  \"A - (B::point) = A + - B\"\n\nlemma Point_eq_0 [simp]: \n  \"Point xA yA = 0 <-> (xA = 0 \\<and> yA = 0)\"\n  by (simp add: point_zero_def)\n\nlemma point_abscissa_zero [simp]: \n  \"abscissa 0 = 0\"\n  by (simp add: point_zero_def)\n\nlemma point_ordinate_zero [simp]: \n  \"ordinate 0 = 0\"\n  by (simp add: point_zero_def)\n\nlemma point_add [simp]:\n  \"Point xA yA + Point xB yB = Point (xA + xB) (yA + yB)\"\n  by (simp add: point_add_def)\n\nlemma point_abscissa_add [simp]:\n  \"abscissa (A + B) = abscissa A + abscissa B\"\n  by (simp add: point_add_def)\n\nlemma point_ordinate_add [simp]:\n  \"ordinate (A + B) = ordinate A + ordinate B\"\n  by (simp add: point_add_def)\n\nlemma point_minus [simp]:\n  \"- (Point xA yA) = Point (- xA) (- yA)\"\n  by (simp add: point_minus_def)\n\nlemma point_abscissa_minus [simp]:\n  \"abscissa (- A) = - abscissa (A)\"\n  by (simp add: point_minus_def)\n\nlemma point_ordinate_minus [simp]:\n  \"ordinate (- A) = - ordinate (A)\"\n  by (simp add: point_minus_def)\n\nlemma point_diff [simp]:\n  \"Point xA yA - Point xB yB = Point (xA - xB) (yA - yB)\"\n  by (simp add: point_diff_def)\n\nlemma point_abscissa_diff [simp]:\n  \"abscissa (A - B) = abscissa (A) - abscissa (B)\"\n  by (simp add: point_diff_def)\n\nlemma point_ordinate_diff [simp]:\n  \"ordinate (A - B) = ordinate (A) - ordinate (B)\"\n  by (simp add: point_diff_def)\n\ninstance\n  by intro_classes (simp_all add: point_add_def point_diff_def)\n\nend\n\nsubsection {* Metric Space *}\n\ntext {* We can also define a distance, hence point is also a metric space *}\n\ninstantiation point :: metric_space\nbegin\n\ndefinition point_dist_def:\n  \"dist A B =  sqrt ((abscissa (A - B))^2 + (ordinate (A - B))^2)\"\n\ndefinition open_point_def:\n  \"open (S :: point set) <-> (\\<forall> A \\<in> S. \\<exists> epsilon > 0. \\<forall> B. dist B A < epsilon --> B \\<in> S)\"\n\n\n\nlemma real_sqrt_diff_squares_triangle_ineq:\n  fixes a b c d :: real\n  shows \"sqrt ((a - c)^2 + (b - d)^2) \\<le> sqrt (a^2 + b^2) + sqrt (c^2 + d^2)\"\nproof -\n  have \"sqrt ((a - c)^2 + (b - d)^2) \\<le> sqrt (a^2 + b^2) + sqrt ((-c)^2 + (-d)^2)\"\n    by (metis diff_conv_add_uminus real_sqrt_sum_squares_triangle_ineq)\n  also have \"... = sqrt (a^2 + b^2) + sqrt (c^2 + d^2)\"\n    by simp\n  finally show ?thesis .\nqed\n\ninstance\nproof\n  fix A B C :: point and S :: \"point set\"\n  show \"(dist A B = 0) = (A = B)\"\n    by (induct A, induct B) (simp add: point_dist_def)\n  show \"(dist A B) \\<le> (dist A C) + (dist B C)\"\n  proof -\n    have \"sqrt ((abscissa (A - B))^2 + (ordinate (A - B))^2) \\<le> \n          sqrt ((abscissa (A - C))^2 + (ordinate (A - C))^2) + \n          sqrt ((abscissa (B - C))^2 + (ordinate (B - C))^2)\"\n      using real_sqrt_diff_squares_triangle_ineq \n             [of \"abscissa (A) - abscissa (C)\" \"abscissa (B) - abscissa (C)\" \n                 \"ordinate (A) - ordinate (C)\" \"ordinate (B) - ordinate (C)\"] \n      by (simp only: point_diff_def) (simp add: algebra_simps)\n    thus ?thesis\n      by (simp add: point_dist_def)\n  qed\n  show \"open S <-> (\\<forall> A \\<in> S. \\<exists> epsilon > 0. \\<forall> B. dist B A < epsilon --> B \\<in> S)\"\n    by (rule open_point_def)\nqed\nend\n\nsubsection {* Geometric Definitions *}\n\ntext {* These geometric definitions will later be used to define\nconstructible points *}\n\ntext {* The distance between two points is defined with the distance\nof the metric space point *}\ndefinition distance_def:\n  \"distance A B = dist A B\"\n\ntext {* @{term \"parallel A B C D\"} is true if the lines @{term \"(AB)\"}\nand @{term \"(CD)\"} are parallel. If not it is false. *}\n\ndefinition parallel_def:\n  \"parallel A B C D = ((abscissa A - abscissa B) * (ordinate C - ordinate D) = (ordinate A - ordinate B) * (abscissa C - abscissa D))\"\n\ntext {* Three points @{term \"A B C\"} are collinear if and only if the\nlines @{term \"(AB)\"} and @{term \"(AC)\"} are parallel *}\n\ndefinition collinear_def:\n  \"collinear A B C = parallel A B A C\"\n\ntext {* The point @{term M} is the intersection of two lines @{term\n\"(AB)\"} and @{term \"(CD)\"} if and only if the points @{term A}, @{term\nM} and @{term B} are collinear and the points @{term C}, @{term M} and\n@{term D} are also collinear *}\n\ndefinition is_intersection_def:\n  \"is_intersection M A B C D = (collinear A M B \\<and> collinear C M D)\"\n\n\nsubsection {*Reals definable with square roots*}\n\ntext {* The inductive set @{term \"radical_sqrt\"} defines the reals\nthat can be defined with square roots. If @{term x} is in the\nfollowing set, then it depends only upon rational expressions and\nsquare roots. For example, suppose @{term x} is of the form : $x =\n(\\sqrt{a + \\sqrt{b}} + \\sqrt{c + \\sqrt{d*e +f}}) / (\\sqrt{a} +\n\\sqrt{b}) + (a + \\sqrt{b}) / \\sqrt{g}$, where @{term a}, @{term b},\n@{term c}, @{term d}, @{term e}, @{term f} and @{term g} are\nrationals. Then @{term x} is in @{term \"radical_sqrt\"} because it is\nonly defined with rationals and square roots of radicals. *}\n\ninductive_set radical_sqrt :: \"real set\"\n  where\n  \"x \\<in> \\<rat> \\<Longrightarrow> x \\<in> radical_sqrt\"|\n  \"x \\<in> radical_sqrt \\<Longrightarrow> -x \\<in> radical_sqrt\"|\n  \"x \\<in> radical_sqrt \\<Longrightarrow> x \\<noteq> 0 \\<Longrightarrow> 1/x \\<in> radical_sqrt\"|\n  \"x \\<in> radical_sqrt \\<Longrightarrow> y \\<in> radical_sqrt \\<Longrightarrow> x+y \\<in> radical_sqrt\"|\n  \"x \\<in> radical_sqrt \\<Longrightarrow> y \\<in> radical_sqrt \\<Longrightarrow> x*y \\<in> radical_sqrt\"|\n  \"x \\<in> radical_sqrt \\<Longrightarrow> x \\<ge> 0 \\<Longrightarrow> sqrt x \\<in> radical_sqrt\"\n\ntext {* Here, we list some rules that will be used to prove that a\ngiven real is in @{term \"radical_sqrt\"}. *}\n\ntext {* Given two reals in @{term \"radical_sqrt\"} @{term x} and @{term\ny}, the subtraction $x - y$ is also in @{term \"radical_sqrt\"}. *}\n\nlemma radical_sqrt_rule_subtraction:\n  \"x \\<in> radical_sqrt \\<Longrightarrow> y \\<in> radical_sqrt \\<Longrightarrow> x-y \\<in> radical_sqrt\"\nby (metis diff_conv_add_uminus radical_sqrt.intros(2) radical_sqrt.intros(4))\n\n\ntext {* Given two reals in @{term \"radical_sqrt\"} @{term x} and @{term\ny}, and $y \\neq 0$, the division $x / y$ is also in @{term\n\"radical_sqrt\"}. *}\n\nlemma radical_sqrt_rule_division:\n  \"x \\<in> radical_sqrt \\<Longrightarrow> y \\<in> radical_sqrt \\<Longrightarrow> y \\<noteq> 0 \\<Longrightarrow> x/y \\<in> radical_sqrt\"\n  by (metis divide_real_def radical_sqrt.intros(3) radical_sqrt.intros(5) real_scaleR_def real_vector.scale_one)\n\n\ntext {* Given a positive real @{term x} in @{term \"radical_sqrt\"}, its\nsquare $x^2$ is also in @{term \"radical_sqrt\"}. *}\n\nlemma radical_sqrt_rule_power2:\n  \"x \\<in> radical_sqrt \\<Longrightarrow> x \\<ge> 0 \\<Longrightarrow> x^2 \\<in> radical_sqrt\"\nby (metis power2_eq_square radical_sqrt.intros(5))\n\n\ntext {* Given a positive real @{term x} in @{term \"radical_sqrt\"}, its\ncube $x^3$ is also in @{term \"radical_sqrt\"}. *}\n\nlemma radical_sqrt_rule_power3:\n  \"x \\<in> radical_sqrt \\<Longrightarrow> x \\<ge> 0 \\<Longrightarrow> x^3 \\<in> radical_sqrt\"\n  by (metis power3_eq_cube radical_sqrt.intros(5))\n\nsubsection {* Introduction of the datatype expr which represents radical expressions *}\n\ntext {* An expression expr is either a rational constant: Const or the\nnegation of an expression or the inverse of an expression or the\naddition of two expressions or the multiplication of two expressions\nor the square root of an expression. *}\n\ndatatype expr = Const rat | Negation expr | Inverse expr | Addition expr expr | Multiplication expr expr | Sqrt expr\n\ntext {* The function @{term \"translation\"} translates a given\nexpression into its equivalent real. *}\n\nfun translation :: \"expr => real\" (\"(2\\<lbrace>_\\<rbrace>)\")\n  where\n  \"translation (Const x) = of_rat x\"|\n  \"translation (Negation e) = - translation e\"|\n  \"translation (Inverse e) = (1::real) / translation e\"|\n  \"translation (Addition e1 e2) = translation e1 + translation e2\"|\n  \"translation (Multiplication e1 e2) = translation e1 * translation e2\"|\n  \"translation (Sqrt e) = (if translation e < 0 then 0 else sqrt (translation e))\"\n\ntext {* Define the set of all the radicals of a given expression. For\nexample, suppose @{term \"expr\"} is of the form : expr = Addition (Sqrt\n(Addition (Const @{term a}) Sqrt (Const @{term b}))) (Sqrt (Addition\n(Const @{term c}) (Sqrt (Sqrt (Const @{term d}))))), where @{term a},\n@{term b}, @{term c} and @{term d} are rationals. This can be\ntranslated as follows: @{text \"\\<lbrace>expr\\<rbrace> =\"}~$\\sqrt{a + \\sqrt{b}} +\n\\sqrt{c + \\sqrt{\\sqrt{d}}}$. Moreover, the set @{term \"radicals\"} of\nthis expression is : @{text \"\\<lbrace>\"}Addition (Const @{term a}) (Sqrt\n(Const @{term b})), Const @{term b}, Addition (Const @{term c}) (Sqrt\n(Sqrt (Const @{term d}))), Sqrt (Const @{term d}), Const @{term\nd}@{text \"\\<rbrace>\"}. *}\n\nfun radicals :: \"expr => expr set\" \n  where\n  \"radicals (Const x) = {}\"|\n  \"radicals (Negation e) = (radicals e)\"|\n  \"radicals (Inverse e) = (radicals e)\"|\n  \"radicals (Addition e1 e2) = ((radicals e1) \\<union> (radicals e2))\"|\n  \"radicals (Multiplication e1 e2) = ((radicals e1) \\<union> (radicals e2))\"|\n  \"radicals (Sqrt e) = (if \\<lbrace>e\\<rbrace> < 0 then radicals e else {e} \\<union> (radicals e))\"\n\n\ntext {* If @{term r} is in @{term \"radicals\"} of @{term e} then the\nset @{term \"radical_sqrt\"} of @{term r} is a subset (strictly\nspeaking) of the set @{term \"radicals\"} of @{term e}. *}\n\nlemma radicals_expr_subset: \"r \\<in> radicals e \\<Longrightarrow> radicals r \\<subset> radicals e\"\n  by (induct e, auto simp add: split_if_asm)\n\ntext {* If @{term x} is in @{term \"radical_sqrt\"} then there exists a\nradical expression @{term e} which translation is @{term x} (it is\nimportant to notice that this expression is not necessarily\nunique). *}\n\nlemma radical_sqrt_correct_expr:\n  \"x \\<in> radical_sqrt \\<Longrightarrow> (\\<exists> e. \\<lbrace>e\\<rbrace> = x)\"\n  apply (rule radical_sqrt.induct)\n  apply auto \n  apply (erule Rats_induct)\n  apply (metis translation.simps(1))\n  apply (metis translation.simps(2))\n  apply (metis translation.simps(3))\n  apply (metis translation.simps(4))\n  apply (metis translation.simps(5))\n  apply (metis linorder_not_less translation.simps(6))\n  done\n\ntext {* The order of an expression is the maximum number of radicals\none over another occuring in a given expression. Using the example\nabove, suppose @{term \"expr\"} is of the form : expr = Addition (Sqrt\n(Addition (Const @{term a}) Sqrt (Const @{term b}))) (Sqrt (Addition\n(Const @{term c}) (Sqrt (Sqrt (Const @{term d}))))), where @{term a},\n@{term b}, @{term c} and @{term d} are rationals and which can be\ntranslated as follows: @{text \"\\<lbrace>expr\\<rbrace> =\"}~$\\sqrt{a + \\sqrt{b} +\n\\sqrt{c + \\sqrt{\\sqrt{d}}}}$. The order of @{term expr} is $max (2,3)\n= 3$. *}\n\nfun order :: \"expr => nat\"\n  where\n  \"order (Const x) = 0\"|\n  \"order (Negation e) = order e\"|\n  \"order (Inverse e) = order e\"|\n  \"order (Addition e1 e2) = max (order e1) (order e2)\"|\n  \"order (Multiplication e1 e2) = max (order e1) (order e2)\"|\n  \"order (Sqrt e) = 1 + order e\"\n\ntext {* If an expression @{term s} is one of the radicals (or in\n@{term \"radicals\"}) of the expression @{term r}, then its order is\nsmaller (strictly speaking) then the order of @{term r}. *}\n\nlemma in_radicals_smaller_order:\n  \"s \\<in> radicals r \\<Longrightarrow> (order s) < (order r)\"\n  apply (induct r, auto)\n  apply (metis insert_iff insert_is_Un less_Suc_eq) \n  done\n\ntext {* The following theorem is the converse of the previous lemma. *}\n\nlemma in_radicals_smaller_order_contrap:\n  \"(order s) \\<ge> (order r) \\<Longrightarrow> \\<not> (s \\<in> radicals r)\"\n  by (metis in_radicals_smaller_order leD)\n\ntext {* An expression @{term r} cannot be one of its own radicals. *}\n\nlemma not_in_own_radicals:\n  \"\\<not> (r \\<in> radicals r)\"\n  by (metis in_radicals_smaller_order order_less_irrefl)\n \n\ntext {* If an expression @{term e} is a radical expression and it has\nno radicals then its translation is a rational. *}\n\nlemma radicals_empty_rational: \"radicals e = {} \\<Longrightarrow> \\<lbrace>e\\<rbrace> \\<in> \\<rat>\"\n  by (induct e, auto)\n\ntext {* A finite non-empty set of natural numbers has necessarily a\nmaximum. *}\n\nlemma finite_set_has_max:\n  \"finite (s:: nat set) \\<Longrightarrow> s \\<noteq> {} \\<Longrightarrow> \\<exists>k \\<in> s. \\<forall> p \\<in> s. p \\<le> k\"\n  by (metis Max_ge Max_in)\n\ntext {* There is a finite number of radicals in an expression. *}\n\nlemma finite_radicals: \"finite (radicals e)\"\n  by (induct e, auto)\n\ntext {* We define here a new set corresponding to the orders of each\nelement in the set @{term \"radicals\"} of an expression @{term\nexpr}. Using the example above, suppose @{term expr} is of the form :\nexpr = Addition (Sqrt (Addition (Const @{term a}) Sqrt (Const @{term\nb}))) (Sqrt (Addition (Const @{term c}) (Sqrt (Sqrt (Const @{term\nd}))))), where @{term a}, @{term b}, @{term c} and @{term d} are\nrationals and which can be translated as follows: @{text \"\\<lbrace>expr\\<rbrace>\n=\"}~$\\sqrt{a + \\sqrt{b}} + \\sqrt{c + \\sqrt{\\sqrt{d}}}$. The set @{term\n\"radicals\"} of @{term expr} is $\\{$Addition (Const @{term a}) Sqrt\n(Const @{term b}), Const @{term b}, Addition (Const @{term c}) (Sqrt\n(Sqrt (Const @{term d}))), Sqrt (Const @{term d}), Const @{term\nd}$\\}$; therefore, the set @{term \"order_radicals\"} of this set is\n$\\{1,0,2,1,0\\}$.  *}\n\nfun order_radicals:: \"expr set => nat set\"\n  where \"order_radicals s = {y. \\<exists> x \\<in> s. y = order x}\"\n\ntext {* If the set of radicals of an expression @{term e} is not empty\nand is finite then the set @{term \"order_radicals\"} of the set of\nradicals of @{term e} is not empty and is also finite. *}\n\n\n\ntext {* The following lemma states that given an expression @{term e},\nif the set @{term \"order_radicals\"} of the set @{term \"radicals e\"} is\nnot empty and is finite, then there exists a radical @{term r} of\n@{term e} which is of highest order among the radicals of @{term e}.\n*}\n\nlemma finite_order_radicals_has_max:\n  \"order_radicals (radicals e) \\<noteq> {} \\<Longrightarrow> \n   finite (order_radicals (radicals e)) \\<Longrightarrow> \n   \\<exists> r. (r \\<in> radicals e) \\<and> (\\<forall> s \\<in> (radicals e). (order r \\<ge> order s))\"\n  using finite_set_has_max [of \"order_radicals (radicals e)\"]\n    by auto\n\n\ntext {* This important lemma states that in an expression that has at\nleast one radical, we can find an upmost radical @{term r} which is\nnot radical of any other term of the expression @{term e}. It is also\nimportant to notice that this upmost radical is not necessarily unique\nand is not the term of highest order of the expression @{term\ne}. Using the example above, suppose @{term e} is of the form : @{term\ne} = Addition (Sqrt (Addition (Const @{term a}) Sqrt (Const @{term\nb}))) (Sqrt (Addition (Const @{term c}) (Sqrt (Sqrt (Const @{term\nd}))))), where @{term a}, @{term b}, @{term c} and @{term d} are\nrationals and which can be translated as follows: @{text \"\\<lbrace>e\\<rbrace>\n=\"}~$\\sqrt{a + \\sqrt{b}} + \\sqrt{c + \\sqrt{\\sqrt{d}}}$. The possible\nupmost radicals in this expression are Addition (Const @{term a})\n(Sqrt (Const @{term b})) or Addition (Const @{term c}) (Sqrt (Sqrt\n(Const @{term d}))). *}\n\n\n\n\n\ntext {* The following 7 lemmas are used to prove the main lemma @{term\n\"radical_sqrt_normal_form\"} which states that if an expression @{term\ne} has at least one radical then it can be written in a normal\nform. This means that there exist three radical expressions @{term a},\n@{term b} and @{term r} such that @{text \"\\<lbrace>e\\<rbrace> = \\<lbrace>a\\<rbrace> + \\<lbrace>b\\<rbrace> *\n\\<sqrt>\\<lbrace>r\\<rbrace>\"} and the radicals of @{term a} are radicals of @{term e}\nbut are not @{term r}, and the same goes for the radicals of @{term b}\nand @{term r}. It is important to notice that @{term a}, @{term b} and\n@{term r} are not unique and @{term \"Sqrt r\"} is not necessarily the\nterm of highest order. *}\n\nlemma radical_sqrt_normal_form_sublemma:\n  \"((a::real) - b) * (a + b) = a * a - b * b\"\n  by (metis comm_semiring_1_class.normalizing_semiring_rules(7) square_diff_square_factored)\n\nlemma eq_sqrt_squared:\n  \"(x::real) \\<ge> 0 \\<Longrightarrow> (sqrt x) * (sqrt x) = x\"\n  by (metis abs_of_nonneg real_sqrt_abs2 real_sqrt_mult)\n\nlemma radical_sqrt_normal_form_lemma4: \n  assumes \"z \\<ge> 0\" \"x \\<noteq> y * sqrt z\"\n  shows\n   \"1 / (x + y * sqrt z) = \n    x / (x * x - y * y * z) - (y * sqrt z) / (x * x - y * y * z)\"\nproof -\n  have \"1 / (x + y * sqrt z) = ((x - y * sqrt z) / (x + y * sqrt z)) / (x - y * sqrt z)\"\n    by (auto simp add: eq_divide_imp assms) \n  also have \"... = x / (x * x - y * y * z) - (y * sqrt z) / (x * x - y * y * z)\"\n    by (auto simp add: algebra_simps eq_sqrt_squared diff_divide_distrib assms)\n  finally show ?thesis .\nqed\n\nlemma radical_sqrt_normal_form_lemma:\n  fixes e::expr\n  assumes \"radicals e \\<noteq> {}\" \n  and \"\\<forall>s \\<in> radicals e. r \\<notin> radicals s\" \n  and \"r : radicals e\"\n  shows \"\\<exists>a b. 0 \\<le> \\<lbrace>r\\<rbrace> & \\<lbrace>e\\<rbrace> = \\<lbrace>a\\<rbrace> + \\<lbrace>b\\<rbrace> * sqrt \\<lbrace>r\\<rbrace> & \n          radicals a \\<union> radicals b \\<union> radicals r \\<subseteq> radicals e & \n          r \\<notin> radicals a \\<union> radicals b\"\n       (is \"\\<exists>a b. ?concl e a b\")\n  using assms\nproof (induct e)\n  case (Const rat) thus ?case \n    by auto\nnext\n  case (Negation e)\n  obtain a b\n    where a2: \"?concl e a b\"\n    by (metis Negation radicals.simps(2))\n  hence \"\\<lbrace>Negation e\\<rbrace> = \\<lbrace>Negation a\\<rbrace> + \\<lbrace>Negation b\\<rbrace> * sqrt \\<lbrace>r\\<rbrace>\"\n    by simp\n  thus ?case using a2 \n    by (metis radicals.simps(2))\nnext\n  case (Inverse e) \n  obtain a b\n    where \"?concl e a b\"\n    by (metis Inverse radicals.simps(3))\n  thus ?case \n    apply (case_tac \"\\<lbrace>b\\<rbrace> * sqrt \\<lbrace>r\\<rbrace> = \\<lbrace>a\\<rbrace>\")\n    apply simp\n    apply (case_tac \"\\<lbrace>a\\<rbrace> = 0\")\n    apply (metis add_0_right divide_zero mult_zero_right)\n    apply (rule_tac x = \"Multiplication (Const 1) (Inverse (Multiplication (Const 2) a))\"in exI)\n    apply (rule_tac x = \"Const 0\" in exI, simp)\n    apply (rule_tac x = \"Multiplication a (Inverse (Addition (Multiplication a a) (Negation (Multiplication (Multiplication b b) r))))\" in exI)\n    apply (rule_tac x = \"Negation (Multiplication b (Inverse (Addition (Multiplication a a) (Negation (Multiplication (Multiplication b b) r)))))\" in exI)\n    apply (simp add: algebra_simps not_in_own_radicals eq_diff_eq' radical_sqrt_normal_form_lemma4)\n    done\nnext\n  case (Addition e1 e2)\n  hence d1: \"\\<forall>s \\<in> radicals e1 \\<union> radicals e2. r \\<notin> radicals s\"\n    by (metis radicals.simps(4))\n  show ?case\n  proof (cases \"r: radicals e1 & r : radicals e2\")\n    case True\n    obtain a1 b1 a2 b2\n      where ab: \"?concl e1 a1 b1\"\n        and bb: \"?concl e2 a2 b2\"\n      using Addition.hyps\n      by (simp add: d1) (metis True empty_iff)\n    thus ?thesis \n      apply simp\n      apply (rule_tac x = \"Addition a1 a2\" in exI)\n      apply (rule_tac x = \"Addition b1 b2\" in exI)\n      apply (auto simp add: comm_semiring_class.distrib)\n      done\n  next\n    case False \n    thus ?thesis\n    proof (cases \"r: radicals e1\")\n      case True\n      obtain a1 b1\n      where \"0 \\<le> \\<lbrace>r\\<rbrace>\" \"?concl e1 a1 b1\"\n        using Addition.hyps\n        by (auto simp: d1) (metis True empty_iff)\n      thus ?thesis \n        apply (rule_tac x = \"Addition a1 e2\" in exI)\n        apply (rule_tac x = \"b1\" in exI)    using False True\n        apply auto\n        done\n    next\n      case False\n      obtain a2 b2\n        where \"0 \\<le> \\<lbrace>r\\<rbrace>\" \"?concl e2 a2 b2\"\n        using Addition d1\n        by (metis False Un_iff empty_iff radicals.simps(4))\n      thus ?thesis\n        apply (rule_tac x = \"Addition a2 e1\" in exI)\n        apply (rule_tac x = \"b2\" in exI)    using False \n        apply auto\n        done\n    qed\n  qed\nnext\n  case (Multiplication e1 e2)\n  show ?case\n  proof (cases \"r: radicals e1 & r : radicals e2\")\n    case True\n    then obtain a1 b1 a2 b2\n      where \"?concl e1 a1 b1\" \"?concl e2 a2 b2\"\n      using Multiplication\n      by simp (metis True empty_iff) \n    thus ?thesis \n      apply (rule_tac x = \"Addition (Multiplication a1 a2) (Multiplication r (Multiplication b1 b2))\" in exI)\n      apply (rule_tac x = \"Addition (Multiplication a1 b2) (Multiplication a2 b1)\" in exI)\n      apply (auto simp add: not_in_own_radicals algebra_simps eq_sqrt_squared)\n      done\n  next\n    case False \n    thus ?thesis\n    proof (cases \"r: radicals e1\")\n      case True\n      then obtain a1 b1\n      where \"?concl e1 a1 b1\"\n        using Multiplication.hyps Multiplication(4)\n        by auto (metis True empty_iff)\n      thus ?thesis \n        apply (rule_tac x = \"Multiplication a1 e2\" in exI)\n        apply (rule_tac x = \"Multiplication b1 e2\" in exI)\n        apply (simp add: algebra_simps)\n        by (metis False True le_supI1 radicals.simps(5))\n    next\n      case False\n      then obtain a2 b2\n        where \"?concl e2 a2 b2\"\n        using Multiplication.hyps Multiplication(4) Multiplication(5)\n        by auto blast\n      thus ?thesis \n        apply (rule_tac x = \"Multiplication a2 e1\" in exI)\n        apply (rule_tac x = \"Multiplication b2 e1\" in exI)\n        apply (simp add: algebra_simps)\n        by (metis False le_supI2)\n    qed\n  qed\nnext\n  case (Sqrt e)\n  show ?case\n  proof (cases \"\\<lbrace>e\\<rbrace> < 0\")\n    case True thus ?thesis\n      using Sqrt\n      apply (rule_tac x = \"Const 0\" in exI)\n      apply (rule_tac x = \"Const 0\" in exI)\n      apply auto\n      done\n  next\n    case False thus ?thesis\n      apply (rule_tac x = \"Const 0\" in exI)\n      apply (rule_tac x = \"Const 1\" in exI)   using Sqrt\n      apply (auto simp add: linorder_not_less)\n      done\n  qed\nqed\n\ntext {* This main lemma is essential for the remaining part of the proof. *}\n\ntheorem radical_sqrt_normal_form:\n  \"radicals e \\<noteq> {} \\<Longrightarrow> \n   \\<exists> r \\<in> radicals e.\n        \\<exists> a b. \\<lbrace>e\\<rbrace> = \\<lbrace>Addition a (Multiplication b (Sqrt r))\\<rbrace> \\<and> \\<lbrace>r\\<rbrace> \\<ge> 0 \\<and>\n               radicals a \\<union> radicals b \\<union> radicals r \\<subseteq> radicals e & \n               r \\<notin> radicals a \\<union> radicals b \\<union> radicals r\"\n  using upmost_radical_sqrt2 [of e] radical_sqrt_normal_form_lemma\n  by auto (metis all_not_in_conv leD)\n\n\nsubsection {* Important properties of the roots of a cubic equation *}\n\ntext {* The following 7 lemmas are used to prove a main result about\nthe properties of the roots of a cubic equation (@{term\n\"cubic_root_radical_sqrt_rational\"}) which states that assuming that\n@{term a} @{term b} and @{term c} are rationals and that @{term x} is\na radical satisfying $x^3 + a x^2 + b x + c = 0$ then there exists a\nrational root. This lemma will be used in the proof of the\nimpossibility of trisection an angle and of duplicating a cube. *}\n\n\nlemma cubic_root_radical_sqrt_steplemma:\n  fixes P :: \"real set\"\n  assumes Nats [THEN set_mp, intro]: \"Nats \\<subseteq> P\" \n  and Neg:  \"\\<forall>x \\<in> P. -x \\<in> P\" \n  and Inv:  \"\\<forall>x \\<in> P. x \\<noteq> 0 \\<longrightarrow> 1/x \\<in> P\"\n  and Add:  \"\\<forall>x \\<in> P. \\<forall>y \\<in> P. x+y \\<in> P\" \n  and Mult: \"\\<forall>x \\<in> P. \\<forall>y \\<in> P. x*y \\<in> P\" \n  and a: \"(a \\<in> P)\" and b: \"(b \\<in> P)\" and c: \"(c \\<in> P)\" \n  and eq0: \"z^3 + a * z^2 + b * z + c = 0\"\n  and u: \"(u \\<in> P)\" \n  and v: \"(v \\<in> P)\" \n  and s: \"((s * s) \\<in> P)\" \n  and z: \"(z = u + v * s)\"\n  shows \"\\<exists>w \\<in> P. w^3 + a * w^2 + b * w + c = 0\"\nproof (cases \"v * s = 0\")\n  case True\n  thus ?thesis\n    by (metis eq0 u z add_0_iff)\nnext\n  case False\n  hence sl0: \"v \\<noteq> 0\"\n    by (metis mult_eq_0_iff)\n  from Add Neg have Minus: \"\\<forall>x \\<in> P. \\<forall>y \\<in> P. x - y \\<in> P\" by (simp only: diff_conv_add_uminus) blast\n  have l2: \"(u^3 + 3 * u * v^2 * s^2 + a * u^2 + a * v^2 * s^2 + b * u + c) + (3 * u^2 * v + v^3 * s^2 + 2 * a * u * v + b * v) * s = 0\" \n    using eq0 z\n    by algebra\n  show ?thesis\n  proof (cases \"3 * u^2 * v + v^3 * s^2 + 2 * a * u * v + b * v \\<noteq> 0\")\n    case True\n    hence  \"s * ((3 * u^2 * v + v^3 * s^2 + 2 * a * u * v + b * v) * (1/ (3 * u^2 * v + v^3 * s^2 + 2 * a * u * v + b * v)))= - (u^3 + 3 * u * v^2 * s^2 + a * u^2 + a * v^2 * s^2 + b * u + c)* (1/ (3 * u^2 * v + v^3 * s^2 + 2 * a * u * v + b * v))\"\n      using l2\n      by algebra\n    hence \"s * ((3 * u^2 * v + v^3 * s^2 + 2 * a * u * v + b * v) /\n                (3 * u^2 * v + v^3 * s^2 + 2 * a * u * v + b * v))\n           = - (u^3 + 3 * u * v^2 * s^2 + a * u^2 + a * v^2 * s^2 + b * u + c) *\n               (1 / (3 * u^2 * v + v^3 * s^2 + 2 * a * u * v + b * v))\"\n      by auto\n    hence \"s = - (u^3 + 3 * u * v^2 * s^2 + a * u^2 + a * v^2 * s^2 + b * u + c) * \n               (1 /(3 * u^2 * v + v^3 * s^2 + 2 * a * u * v + b * v))\"\n      by (metis mult_1_right True divide_self_if)\n    hence l10: \"s = - (u *u *u  + 3 * u * v *v * (s*s) + a * u *u + a * v*v * (s *s) + b * u + c) *\n                (1 / (3 * u *u * v + v *v*v * (s *s) + 2 * a * u * v + b * v))\"\n      by (simp add: algebra_simps power2_eq_square power3_eq_cube)        \n    have \"(3*u*u * v + v*v*v * (s *s) + 2 * a * u * v + b * v) \\<in> P\" \n      using a b u v s Nats Mult Add\n      by auto \n    hence l103: \"1 / (3 * u *u * v + v *v*v * (s *s) + 2 * a * u * v + b * v) \\<in> P\" \n      using Inv True\n      by auto\n    have \"-(u*u*u + 3 * u * v *v * (s*s) + a * u *u + a * v*v * (s *s) + b * u + c) \\<in> P\" \n      using a b c u v s Mult Add Neg Minus Nats\n      by simp\n    hence \"- (u *u *u  + 3 * u * v *v * (s*s) + a * u *u + a * v*v * (s *s) + b * u + c) * (1 /(3 * u *u * v + v *v*v * (s *s) + 2 * a * u * v + b * v)) \\<in> P\" \n      using l103 Mult\n      by metis\n    hence \"s \\<in> P\" \n      using l10\n      by auto\n    hence \"z \\<in> P\" \n      using z u v Mult Add\n      by auto\n    thus ?thesis \n      using eq0\n      by auto\n  next\n    case False\n    have \"(- a - 2 * u)^3 + a * (- a - 2 * u)^2 + b * ( - a - 2 * u) + c =\n          (- a - 2 * u)^3 + a * (- a - 2 * u)^2 + (- (3 * u^2 + v^2 * s^2 + 2 * a * u)) * \n          ( - a - 2 * u) + (- (u^3) - 3 * u * v^2 * s^2 - a * u^2 - a * v^2 * s^2 + 3 * u^3 + v^2 * s^2 * u + 2 * a * u^2)\"\n      using l2 False sl0\n      by algebra\n    also have \"... = 0\"\n      by (simp add: algebra_simps power_def)\n    finally show ?thesis \n      by (metis a u Add Neg diff_conv_add_uminus mult_2)\n  qed\nqed\n\nlemma cubic_root_radical_sqrt_steplemma_sqrt:\n  assumes Nats [THEN set_mp, intro]: \"Nats \\<subseteq> P\" \n  and Neg:  \"\\<forall>x \\<in> P. -x \\<in> P\" \n  and Inv:  \"\\<forall>x \\<in> P. x \\<noteq> 0 \\<longrightarrow> 1/x \\<in> P\"\n  and Add:  \"\\<forall>x \\<in> P. \\<forall>y \\<in> P. x+y \\<in> P\" \n  and Mult: \"\\<forall>x \\<in> P. \\<forall>y \\<in> P. x*y \\<in> P\" \n  and a: \"(a \\<in> P)\" and b: \"(b \\<in> P)\" and c: \"(c \\<in> P)\" \n  and eq0: \"z^3 + a * z^2 + b * z + c = 0\"\n  and u: \"(u \\<in> P)\" \n  and v: \"(v \\<in> P)\" \n  and s: \"(s \\<in> P)\"\n  and sPositive: \"s \\<ge> 0\"\n  and z: \"z = u + v * sqrt s\"\n  shows \"\\<exists>w \\<in> P. w^3 + a * w^2 + b * w + c = 0\"\nproof-\n  have \"(sqrt s) * (sqrt s) \\<in> P\"\n    by (metis eq_sqrt_squared s sPositive) \n  thus ?thesis \n    using cubic_root_radical_sqrt_steplemma [of P a b c z u v \"sqrt s\"] \n          Neg Add Mult Inv a b c u v s eq0 z\n    by auto\nqed\n\nlemma cubic_root_radical_sqrt_lemma:\n  fixes e::expr\n  assumes a: \"a \\<in> \\<rat>\" and b: \"b \\<in> \\<rat>\" and c: \"c \\<in> \\<rat>\" \n  and notEmpty: \"radicals e \\<noteq> {}\" \n  and eq0: \"\\<lbrace>e\\<rbrace>^ 3 + a * \\<lbrace>e\\<rbrace>^2 + b * \\<lbrace>e\\<rbrace> + c = 0\"\n  shows \"\\<exists> e1. radicals e1 \\<subset> radicals e & (\\<lbrace>e1\\<rbrace>^3 + a * \\<lbrace>e1\\<rbrace>^2 + b * \\<lbrace>e1\\<rbrace> + c = 0)\"\nproof -\n  obtain r u v\n    where hypsruv: \"\\<lbrace>r\\<rbrace> \\<ge> 0\" \"r \\<in> radicals e\" \n                   \"\\<lbrace>e\\<rbrace> = \\<lbrace>Addition u (Multiplication v (Sqrt r))\\<rbrace>\" \n                    \"radicals u \\<union> radicals v \\<union> radicals r \\<subseteq> radicals e\" \n                    \"r \\<notin> radicals u \\<union> radicals v\" \"r \\<notin> radicals r\" \n    using notEmpty radical_sqrt_normal_form [of e]\n    by blast\n  let ?E = \"{x. \\<exists> ex. (\\<lbrace>ex\\<rbrace> = x) & ((radicals ex) \\<subseteq> (radicals e)) & (r \\<notin> (radicals ex))}\"\n  have NatsE: \"Nats \\<subseteq> ?E\" \n    by (force elim: Nats_cases intro: exI[of _ \"Const (rat_of_nat n)\" for n])\n  have negE: \"\\<forall>x \\<in> ?E. -x \\<in> ?E\" \n    using hypsruv by (force intro: exI[of _ \"Negation ex\" for ex])\n  have invE: \"\\<forall>x \\<in> ?E. x \\<noteq> 0 --> 1/x \\<in> ?E\" \n    using hypsruv by (force intro: exI[of _ \"Inverse ex\" for ex])\n  have addE: \"\\<forall>x \\<in> ?E. \\<forall>y \\<in> ?E. x+y \\<in> ?E\"\n    using hypsruv by (force intro: exI[of _ \"Addition ex1 ex2\" for ex1 ex2])\n  have multE: \"\\<forall>x \\<in> ?E. \\<forall>y \\<in> ?E. x*y \\<in> ?E\"\n    using hypsruv by (force intro: exI[of _ \"Multiplication ex1 ex2\" for ex1 ex2])\n  obtain ra rb rc\n    where hypsra: \"a = of_rat ra\"\n      and hypsrb: \"b = of_rat rb\"\n      and hypsrc: \"c = of_rat rc\"\n    unfolding Rats_def\n    by (metis Rats_cases a b c)\n  have \"a \\<in> ?E & b \\<in> ?E & c \\<in> ?E & \\<lbrace>u\\<rbrace> \\<in> ?E & \\<lbrace>v\\<rbrace> \\<in> ?E & \\<lbrace>r\\<rbrace> \\<in> ?E & \\<lbrace>r\\<rbrace> \\<ge> 0 & \\<lbrace>e\\<rbrace> = \\<lbrace>u\\<rbrace> + \\<lbrace>v\\<rbrace> * sqrt \\<lbrace>r\\<rbrace>\"\n    using a b c notEmpty hypsruv hypsra hypsrb hypsrc\n    by (auto intro: exI[of _ \"Const x\" for x])\n  with eq0 hypsruv NatsE negE invE addE multE \n      cubic_root_radical_sqrt_steplemma_sqrt [of \"?E\" a b c\"\\<lbrace>e\\<rbrace>\" \"\\<lbrace>u\\<rbrace>\" \"\\<lbrace>v\\<rbrace>\" \"\\<lbrace>r\\<rbrace>\"]\n   obtain w where \"w \\<in> ?E & (w^3 + a * w^2 + b * w + c = 0)\"\n     by auto \n   then obtain e2\n     where \"\\<lbrace>e2\\<rbrace> = w\" \"radicals e2 \\<subseteq> radicals e\" \"r \\<notin> radicals e2\" \n           \"\\<lbrace>e2\\<rbrace>^3 + a * \\<lbrace>e2\\<rbrace>^2 + b * \\<lbrace>e2\\<rbrace> + c = 0\" \n     by auto\n   with hypsruv show ?thesis  \n     by (metis subset_iff_psubset_eq)\nqed\n\nlemma cubic_root_radical_sqrt:\n  assumes abc: \"a \\<in> \\<rat>\" \"b \\<in> \\<rat>\" \"c \\<in> \\<rat>\"\n  shows \"card (radicals e) = n \\<Longrightarrow> \\<lbrace>e\\<rbrace>^3 + a * \\<lbrace>e\\<rbrace>^2 + b * \\<lbrace>e\\<rbrace> + c = 0 \\<Longrightarrow>\n         \\<exists>x \\<in> \\<rat>. x^3 + a * x^2 + b * x + c = 0\"\nproof (induct n arbitrary: e rule: less_induct) \n  case (less n)\n  thus ?case\n  proof cases\n    assume n: \"n = 0\"\n    thus ?thesis \n      using less.prems radicals_empty_rational [of e] finite_radicals [of e]\n      by (auto simp add: card_eq_0_iff n)\n  next\n    assume \"n \\<noteq> 0\"\n    hence \"card (radicals e) \\<noteq> 0\" \n      using less.prems by auto\n    hence \"radicals e \\<noteq> {}\"\n      by (metis card.empty)\n    hence \"\\<exists> e1. radicals e1 \\<subset> radicals e & (\\<lbrace>e1\\<rbrace>^3 + a * \\<lbrace>e1\\<rbrace>^2 + b * \\<lbrace>e1\\<rbrace> + c = 0)\" \n      using abc less.prems cubic_root_radical_sqrt_lemma [of \"a\" \"b\" \"c\" \"e\"]\n      by auto\n    then obtain e1\n      where hypse1: \"radicals e1 \\<subset> radicals e & (\\<lbrace>e1\\<rbrace>^3 + a * \\<lbrace>e1\\<rbrace>^2 + b * \\<lbrace>e1\\<rbrace> + c = 0)\" \n      by auto\n    hence \"card (radicals e1) < card (radicals e)\" \n      by (metis finite_radicals psubset_card_mono)\n    hence \"card (radicals e1) < n & a : Rats & b : Rats & c : Rats & \\<lbrace>e1\\<rbrace>^3 + a * \\<lbrace>e1\\<rbrace>^2 + b * \\<lbrace>e1\\<rbrace> + c = 0\" \n      using hypse1 less.prems abc\n      by auto\n    thus ?thesis using less.hyps [of _ e1]\n      by auto\n  qed\nqed\n\ntext {* Now we can prove the final result about the properties of the\nroots of a cubic equation. *}\n\ntheorem cubic_root_radical_sqrt_rational:\n  assumes a: \"a \\<in> \\<rat>\" and b: \"b \\<in> \\<rat>\" and c: \"c \\<in> \\<rat>\" \n  and x: \"x \\<in> radical_sqrt\"\n  and x_eqn: \"x^3 + a * x^2 + b * x + c = 0\"\n  shows c: \"\\<exists>x \\<in> \\<rat>. x^3 + a * x^2 + b * x + c = 0\"\nproof-\n   obtain e n\n    where \"\\<lbrace>e\\<rbrace> = x & (\\<lbrace>e\\<rbrace>^ 3 + a * \\<lbrace>e\\<rbrace>^2 + b * \\<lbrace>e\\<rbrace> + c = 0)\" \"n = card (radicals e)\" \n    using x x_eqn radical_sqrt_correct_expr [of x]\n    by auto\n  thus ?thesis\n    using cubic_root_radical_sqrt [OF a b c]\n    by auto\nqed\n\nsubsection {* Important properties of radicals *}\n\nlemma sqrt_roots:\n  \"y^2=x \\<Longrightarrow> x\\<ge>0 & (sqrt (x) = y | sqrt (x) = -y)\"\n  apply (simp add: power_def)\n  by (metis abs_of_nonneg abs_of_nonpos real_sqrt_abs2 zero_le_mult_iff zero_le_square)\n\nlemma radical_sqrt_linear_equation:\n  assumes a: \"a \\<in> radical_sqrt\" \n  and b: \"b \\<in> radical_sqrt\" \n  and abNotNull: \"\\<not> (a = 0 & b = 0)\" \n  and eq0: \"a * x + b = 0\"\n  shows \"x \\<in> radical_sqrt\"\nproof (cases \"a=0\")\n  case True\n  thus ?thesis \n    using abNotNull eq0\n    by auto\nnext\n  case False\n  hence l0: \"a \\<noteq> 0\" \n    by simp\n  hence \"x = - b /a\" \n    using eq0\n    by (metis add_0_iff add_minus_cancel nonzero_divide_eq_eq\n              comm_semiring_1_class.normalizing_semiring_rules(7))\n  also have \"... \\<in> radical_sqrt\" \n    using a b radical_sqrt.simps l0\n    by (metis radical_sqrt.intros(2) radical_sqrt_rule_division)\n  finally show ?thesis .\nqed\n\n\nlemma radical_sqrt_simultaneous_linear_equation:\n  assumes a: \"a \\<in> radical_sqrt\" \n  and b: \"b \\<in> radical_sqrt\" \n  and c: \"c \\<in> radical_sqrt\" \n  and d: \"d \\<in> radical_sqrt\" \n  and e: \"e \\<in> radical_sqrt\"\n  and f: \"f \\<in> radical_sqrt\"\n  and NotNull: \"\\<not> (a*e - b*d =0 & a*f - c*d = 0 & e*c = b*f)\" \n  and eq0: \"a*x + b*y = c\" \n  and eq1: \"d*x + e*y = f\"\n  shows \"x \\<in> radical_sqrt & y \\<in> radical_sqrt\"\nproof (cases \"a*e - b*d =0\")\n  case False\n  hence \"(a*e-b*d) * x = (e*c-b*f)\" using eq0 eq1\n    by algebra\n  hence x: \"x = (e*c-b*f) / (a*e-b*d)\" \n    by (metis False comm_semiring_1_class.normalizing_semiring_rules(7) nonzero_divide_eq_eq) \n  hence \"(a*e-b*d) * y = (a*f - d*c)\" using eq0 eq1 \n    by algebra\n  hence y: \"y = (a*f-d*c)/(a*e-b*d)\"\n    by (metis False comm_semiring_1_class.normalizing_semiring_rules(7) nonzero_divide_eq_eq) \n  have ae_rad: \"(a*e -b*d) \\<in> radical_sqrt\"\n    using a e b d radical_sqrt.simps\n    by (metis radical_sqrt.intros(5) radical_sqrt_rule_subtraction)\n  hence \"((e*c-b*f) / (a*e-b*d)) \\<in> radical_sqrt\"  \"((a*f-d*c) / (a*e-b*d)) \\<in> radical_sqrt\"\n    by (metis False a b c d e f radical_sqrt.intros(5) radical_sqrt_rule_division radical_sqrt_rule_subtraction)+\n  thus ?thesis\n    by (simp add: x y)\nnext\n  case True\n  hence \"(a*e-b*d) * x = (e*c-b*f)\" \"(a*e-b*d) * y = (a*f - d*c)\" using eq0 eq1\n    by algebra+\n  thus ?thesis using NotNull True\n    by simp\nqed\n\n\nlemma radical_sqrt_quadratic_equation:\n  assumes a: \"a \\<in> radical_sqrt\" \n      and b: \"b \\<in> radical_sqrt\"\n      and c: \"c \\<in> radical_sqrt\" \n      and eq0: \"a*x^2+b*x+c =0\" \n      and NotNull: \"\\<not> (a = 0 & b = 0 & c = 0)\"\n  shows \"x \\<in> radical_sqrt\"\nproof (cases \"a=0\")\n  case True\n  have \"\\<not> (b = 0 & c = 0)\" \n    by (metis True NotNull) \n  thus ?thesis \n    using b c radical_sqrt_linear_equation [of \"b\" \"c\" \"x\"]\n    by (metis True add_0 eq0 mult_zero_left)\nnext\n  case False\n  hence \"(2*a*x+b)^2 = 4*a*(- c)+b^2\" using eq0\n    by algebra\n  hence \"(b^2 - 4*a*c)\\<ge>0 & (sqrt ((b^2 - 4*a*c)) = (2*a*x+b) | sqrt ((b^2 - 4*a*c)) = -(2*a*x+b))\" \n    using sqrt_roots [of \"2*a*x+b\" \"b^2 - 4*a*c\"]\n    by auto\n  hence l12: \"b^2 - 4*a*c \\<ge> 0 & ((-b + sqrt (b^2 - 4*a*c)) / (2*a) = x |\n                                 (-b - sqrt (b^2 - 4*a*c)) / (2*a) = x)\" \n    using False\n    by auto\n  have \"4*a*c \\<in> radical_sqrt\"\n    using a c radical_sqrt.simps\n    by (metis Rats_number_of radical_sqrt.intros(1) radical_sqrt.intros(5))\n  hence \"b^2 - 4*a*c \\<in> radical_sqrt\" using a b c\n    by (metis power2_eq_square radical_sqrt.intros(5) radical_sqrt_rule_subtraction) \n  hence l22: \"sqrt (b^2 - 4*a*c) \\<in> radical_sqrt\"\n    using l12\n    by (metis radical_sqrt.intros(6))\n  hence l23: \"(-b + sqrt (b^2 - 4*a*c)) / (2*a) \\<in> radical_sqrt\"\n    using b a False\n    apply (simp add: algebra_simps) \n    apply (metis radical_sqrt_rule_division radical_sqrt_rule_subtraction double_zero_sym mult_2_right mult_2_right radical_sqrt.intros(4))\n    done\n  have \"(-b - sqrt (b^2 - 4*a*c)) / (2*a) \\<in> radical_sqrt\" \n    using a b False l22\n    by (metis divide_zero mult_2 radical_sqrt.intros(2) radical_sqrt.intros(4) radical_sqrt_rule_division radical_sqrt_rule_subtraction)\n  thus ?thesis \n    by (metis l12 l23)\nqed\n\n\nlemma radical_sqrt_simultaneous_linear_quadratic:\n  assumes a: \"a \\<in> radical_sqrt\" \n      and b: \"b \\<in> radical_sqrt\" \n      and c: \"c \\<in> radical_sqrt\" \n      and d: \"d \\<in> radical_sqrt\"\n      and e: \"e \\<in> radical_sqrt\" \n      and f: \"f \\<in> radical_sqrt\" \n      and NotNull: \"\\<not>(d=0 & e=0 & f=0)\" \n      and eq0: \"(x-a)^2 + (y-b)^2 = c\" \n      and eq1: \"d*x+e*y = f\"\n  shows \"x \\<in> radical_sqrt & y \\<in> radical_sqrt\"\nproof (cases \"d=0 & e=0\")\n  case True\n  thus ?thesis\n    by (metis add_0 eq1 mult_zero_left NotNull)\nnext\n  case False\n  hence l10: \"(e^2 + d^2) * x^2 + (2*e*b*d - 2*a*e^2 - 2*d*f)*x + (a^2 * e^2 + f^2 - 2* e *b* f + b^2 * e^2 - e^2 *c) = 0\"\n     using eq0 eq1\n    by algebra\n  have l12: \"\\<not> (e^2 +d^2 = 0 & 2*e*b*d - 2*a*e^2 - 2*d*f = 0 & a^2 * e^2 + f^2 - 2* e *b* f + b^2 * e^2 - e^2 *c = 0)\"\n    using False power_def\n    by auto\n  have l13: \"(e^2 +d^2) \\<in> radical_sqrt\" \n    using e d\n    by (metis power2_eq_square radical_sqrt.intros(4) radical_sqrt.intros(5))\n  have sl1: \"(2*e*b*d) \\<in> radical_sqrt\"\n    using e b d\n    by (metis (lifting) mult_2 radical_sqrt.intros(4) radical_sqrt.intros(5))\n  hence sl2: \"(- 2*a*e^2) \\<in> radical_sqrt\" using radical_sqrt.intros\n    by (metis a comm_semiring_1_class.normalizing_semiring_rules(29) e minus_mult_left mult_2)\n  have \"(- 2*d*f) \\<in> radical_sqrt\" using radical_sqrt.intros\n    by (metis d f minus_mult_left mult_2)\n  hence sl4: \"((2*e*b*d) + (- 2*a*e^2) + (- 2*d*f)) \\<in> radical_sqrt\"\n    using sl1 sl2\n    by (metis radical_sqrt.intros(4))\n  have sl5: \"2*e*b*d - 2*a*e^2 - 2*d*f = (2*e*b*d) + (- 2*a*e^2) + (- 2*d*f)\"\n    by auto\n  hence l14: \"(2*e*b*d - 2*a*e^2 - 2*d*f) \\<in> radical_sqrt\"\n    using sl4\n    by metis\n  have sl6: \"(a^2 * e^2) \\<in> radical_sqrt\"\n    using a e\n    by (metis comm_semiring_1_class.normalizing_semiring_rules(29) radical_sqrt.intros(5))\n  have sl7: \"(f^2) \\<in> radical_sqrt\" \n    using f\n    by (metis comm_semiring_1_class.normalizing_semiring_rules(29) radical_sqrt.intros(5))\n  have sl8: \"(- 2 * e *b* f) \\<in> radical_sqrt\"\n    using e b f\n    by (metis (full_types) comm_semiring_1_class.normalizing_semiring_rules(7) minus_mult_commute mult_2 radical_sqrt.intros(2) radical_sqrt.intros(4) radical_sqrt.intros(5))\n  have sl9: \"(b^2 * e^2) \\<in> radical_sqrt\" \n    using b e\n    by (metis comm_semiring_1_class.normalizing_semiring_rules(29) comm_semiring_1_class.normalizing_semiring_rules(30) radical_sqrt.intros(5))\n  have sl10: \"(- c* e^2) \\<in> radical_sqrt\"\n    using c e\n    by (metis comm_semiring_1_class.normalizing_semiring_rules(29) radical_sqrt.intros(2) radical_sqrt.intros(5))\n  have sl6: \"(a^2 * e^2 + f^2 + (- 2 * e *b* f) + b^2 * e^2 + (- c* e^2)) \\<in> radical_sqrt\" \n    using a e f b c sl6 sl7 sl8 sl9 sl10\n    by (metis (hide_lams, no_types) power2_eq_square radical_sqrt.intros(4))\n  have \"a^2 * e^2 + f^2 - 2* e *b* f + b^2 * e^2 - e^2 *c = a^2 * e^2 + f^2 + (- 2 * e *b* f) + b^2 * e^2 + (- c* e^2)\" \n    by auto\n  hence \"(a^2 * e^2 + f^2 - 2* e *b* f + b^2 * e^2 - e^2 *c) \\<in> radical_sqrt\"\n    using sl6\n    by metis\n  hence x: \"x \\<in> radical_sqrt\"\n    using radical_sqrt_quadratic_equation [of \"e^2 +d^2\" \"2*e*b*d - 2*a*e^2 - 2*d*f\" \"a^2 * e^2 + f^2 - 2* e *b* f + b^2 * e^2 - e^2 *c\" \"x\"] l13 l14 l12 l10\n    by auto\n  have l18: \"e*y + (d*x - f) = 0\" \n    using eq1\n    by auto\n  hence y: \"y \\<in> radical_sqrt\" \n    using e d f x False\n  proof (cases \"e = 0\")\n    case True\n    hence l22: \"1 * y^2 + (- 2* b) * y + (b^2 + (x - a)^2 - c) =0\"\n      using eq0\n      by algebra\n    have l24: \"1 \\<in> radical_sqrt\"\n      by (metis Rats_1 radical_sqrt.intros(1))\n    have l25: \"(- 2* b) \\<in> radical_sqrt\" \n      using b\n      by (metis minus_mult_commute mult_2 radical_sqrt.intros(2) radical_sqrt.intros(4))\n    have l26: \"(b^2 + (x - a)^2 - c) \\<in> radical_sqrt\" \n      using a b c x\n      by (metis comm_semiring_1_class.normalizing_semiring_rules(29) radical_sqrt.intros(4) radical_sqrt.intros(5) radical_sqrt_rule_subtraction)\n    thus ?thesis\n      using radical_sqrt_quadratic_equation [of \"1::real\" \"- 2* b\" \"b^2 + (x - a)^2 - c\" \"y\"] l22 l24 l25 l26\n      by auto\n  next\n    case False\n    hence l29: \"\\<not> (e=0 & d*x-f = 0)\"\n      by simp\n    have \"(d*x - f) \\<in> radical_sqrt\"\n      using d f x\n      by (metis radical_sqrt.intros(5) radical_sqrt_rule_subtraction)\n    thus ?thesis \n      using radical_sqrt_linear_equation [of \"e\" \"d*x - f\" y] e d f l18 l29\n      by auto\n  qed\n  show ?thesis\n    by (metis x y)\nqed\n\n\n\n\nsubsection {* Important properties of geometrical points which coordinates are radicals *}\n\nlemma radical_sqrt_line_line_intersection:\n  assumes absA: \"(abscissa (A)) \\<in> radical_sqrt\"\n      and ordA: \"(ordinate A) \\<in> radical_sqrt\" \n      and absB: \"(abscissa B) \\<in> radical_sqrt\" \n      and ordB: \"(ordinate B) \\<in> radical_sqrt\"\n      and absC: \"(abscissa C) \\<in> radical_sqrt\" \n      and ordC: \"(ordinate C) \\<in> radical_sqrt\" \n      and absD: \"(abscissa D) \\<in> radical_sqrt\" \n      and ordD: \"(ordinate D) \\<in> radical_sqrt\" \n      and notParallel: \"\\<not> (parallel A B C D)\"\n      and isIntersec: \"is_intersection X A B C D\"\n  shows \"(abscissa X) \\<in> radical_sqrt & (ordinate X) \\<in> radical_sqrt\"\nproof-\n  have l2: \"(abscissa A - abscissa X) * (ordinate A - ordinate B) = (ordinate A - ordinate X) * (abscissa A - abscissa B) & (abscissa C - abscissa X) * (ordinate C - ordinate D) = (ordinate C - ordinate X) * (abscissa C - abscissa D)\"\n    using isIntersec is_intersection_def collinear_def parallel_def\n    by auto\n  hence l4: \"(- (ordinate A - ordinate B)) * abscissa X + (abscissa A - abscissa B) * ordinate X = (- abscissa A * (ordinate A - ordinate B) + ordinate A * (abscissa A - abscissa B))\"\n    by (simp add: algebra_simps)\n  have l6: \"(- (ordinate C - ordinate D)) * abscissa X + (abscissa C - abscissa D) * ordinate X = (- abscissa C * (ordinate C - ordinate D) + ordinate C * (abscissa C - abscissa D))\"\n    using l2\n    by (simp add: algebra_simps)\n  have sl1: \"(- (ordinate A - ordinate B)) \\<in> radical_sqrt\" \n    by (metis ordA ordB minus_diff_eq radical_sqrt_rule_subtraction)\n  have sl2: \"(abscissa A - abscissa B) \\<in> radical_sqrt\"\n    by (metis absA absB radical_sqrt_rule_subtraction)\n  have sl3: \"(- abscissa A * (ordinate A - ordinate B) + ordinate A * (abscissa A - abscissa B)) \\<in> radical_sqrt\"\n    using absA ordA ordB absB\n    by (metis diff_conv_add_uminus radical_sqrt.intros(2) radical_sqrt.intros(4) radical_sqrt.intros(5))\n  have sl4: \"(- (ordinate C - ordinate D)) \\<in> radical_sqrt\"\n    by (metis ordC ordD minus_diff_eq radical_sqrt_rule_subtraction)\n  have sl5: \"(abscissa C - abscissa D) \\<in> radical_sqrt\"\n    by (metis absC absD radical_sqrt_rule_subtraction)\n  have sl6: \"(- abscissa C * (ordinate C - ordinate D) + ordinate C * (abscissa C - abscissa D)) \\<in> radical_sqrt\"\n    using absC ordC absD ordD\n    by (metis diff_conv_add_uminus radical_sqrt.intros(2) radical_sqrt.intros(4) radical_sqrt.intros(5))\n  have \"(- (ordinate A - ordinate B)) * (abscissa C - abscissa D) \\<noteq> (abscissa A - abscissa B) * (- (ordinate C - ordinate D))\"\n    using notParallel parallel_def\n    by (simp add: algebra_simps)\n  thus ?thesis\n    using radical_sqrt_simultaneous_linear_equation [of \"- (ordinate A - ordinate B)\" \"(abscissa A - abscissa B)\" \"- abscissa A * (ordinate A - ordinate B) + ordinate A * (abscissa A - abscissa B)\" \"- (ordinate C - ordinate D)\" \"abscissa C - abscissa D\" \"- abscissa C * (ordinate C - ordinate D) + ordinate C * (abscissa C - abscissa D)\" \"abscissa X\" \"ordinate X\"] absA ordA absB ordB absC ordC absD ordD l4 sl1 sl2 sl3 sl4 sl5 sl6 l6\n    by simp\nqed\n\n\nlemma radical_sqrt_line_circle_intersection:\n  assumes absA: \"(abscissa A) \\<in> radical_sqrt\" and ordA: \"(ordinate A) \\<in> radical_sqrt\"\n      and absB: \"(abscissa B) \\<in> radical_sqrt\" and ordB: \"(ordinate B) \\<in> radical_sqrt\"\n      and absC: \"(abscissa C) \\<in> radical_sqrt\" and ordC: \"(ordinate C) \\<in> radical_sqrt\"\n      and absD: \"(abscissa D) \\<in> radical_sqrt\" and ordD: \"(ordinate D) \\<in> radical_sqrt\"\n      and absE: \"(abscissa E) \\<in> radical_sqrt\" and ordE: \"(ordinate E) \\<in> radical_sqrt\"\n      and notEqual: \"A \\<noteq> B\"\n      and colin: \"collinear A X B\" \n      and eqDist: \"(distance C X = distance D E)\"\nshows \"(abscissa X) \\<in> radical_sqrt & (ordinate X) \\<in> radical_sqrt\"\nproof-\n  have l3: \"(- (ordinate A - ordinate B)) * abscissa X + (abscissa A - abscissa B) * ordinate X = (- abscissa A * (ordinate A - ordinate B) + ordinate A * (abscissa A - abscissa B))\"\n    using colin  unfolding collinear_def parallel_def\n    by algebra\n  have \"sqrt ((abscissa X - abscissa C)^2 + (ordinate X - ordinate C) ^2) = sqrt ((abscissa D - abscissa E)^2 + (ordinate D - ordinate E) ^2)\" \n    using eqDist distance_def\n    by (metis (no_types) minus_diff_eq point_abscissa_diff point_dist_def point_ordinate_diff power2_minus)\n  hence l6: \"(abscissa X - abscissa C)^2 + (ordinate X - ordinate C) ^2 = (abscissa D - abscissa E)^2 + (ordinate D - ordinate E)^2\"\n    by auto\n  have l8: \"\\<not> (- (ordinate A - ordinate B) = 0 & (abscissa A - abscissa B) = 0 & (- abscissa A * (ordinate A - ordinate B) + ordinate A * (abscissa A - abscissa B)) = 0)\" \n    using notEqual  unfolding point_eq_iff\n    by auto\n  have sl1: \"(- (ordinate A - ordinate B)) \\<in> radical_sqrt\"\n    by (metis ordA ordB minus_diff_eq radical_sqrt_rule_subtraction)\n  have sl2: \"(abscissa A - abscissa B) \\<in> radical_sqrt\"\n    by (metis absA absB radical_sqrt_rule_subtraction)\n  have sl3: \"(- abscissa A * (ordinate A - ordinate B) + ordinate A * (abscissa A - abscissa B)) \\<in> radical_sqrt\" \n    by (metis absA ordA absB ordB diff_conv_add_uminus radical_sqrt.intros(2) radical_sqrt.intros(4) radical_sqrt.intros(5))\n  have \"(abscissa D - abscissa E)^2 + (ordinate D - ordinate E)^2 \\<in> radical_sqrt\"\n    by (metis power2_eq_square \n             absD absE ordD ordE radical_sqrt_rule_subtraction radical_sqrt.intros(5) radical_sqrt.intros(4) ) \n  thus ?thesis\n    using radical_sqrt_simultaneous_linear_quadratic \n            [of \"abscissa C\" \"ordinate C\" \n                \"(abscissa D - abscissa E)^2 + (ordinate D - ordinate E)^2\" \n                \"- (ordinate A - ordinate B)\" \"abscissa A - abscissa B\" \n                \"- abscissa A * (ordinate A - ordinate B) + ordinate A * (abscissa A - abscissa B)\" \n                \"abscissa X\" \"ordinate X\"] \n       l3 absC ordC sl1 sl2 sl3 l6 l8\n    by simp\nqed\n\n\nlemma radical_sqrt_circle_circle_intersection:\n  assumes absA: \"(abscissa A) \\<in> radical_sqrt\" and ordA: \"(ordinate A)  \\<in> radical_sqrt\"\n      and absB: \"(abscissa B) \\<in> radical_sqrt\" and ordB: \"(ordinate B) \\<in> radical_sqrt\"\n      and absC: \"(abscissa C) \\<in> radical_sqrt\" and ordC: \"(ordinate C) \\<in> radical_sqrt\"\n      and absD: \"(abscissa D) \\<in> radical_sqrt\" and ordD: \"(ordinate D) \\<in> radical_sqrt\"\n      and absE: \"(abscissa E) \\<in> radical_sqrt\" and ordE: \"(ordinate E) \\<in> radical_sqrt\"\n      and absF: \"(abscissa F) \\<in> radical_sqrt\" and ordF: \"(ordinate F) \\<in> radical_sqrt\"\n      and eqDist0: \"distance A X = distance B C\" \n      and eqDist1: \"distance D X = distance E F\"\n      and notEqual: \"\\<not> (A = D & distance B C = distance E F)\"\n  shows \"(abscissa X) \\<in> radical_sqrt & (ordinate X) \\<in> radical_sqrt\"\nproof- \n  have \"sqrt ((abscissa X - abscissa A)^2 + (ordinate X - ordinate A) ^2) = sqrt ((abscissa B - abscissa C)^2 + (ordinate B - ordinate C) ^2)\"\n    by (metis (no_types) eqDist0 distance_def minus_diff_eq point_abscissa_diff point_dist_def point_ordinate_diff power2_minus)\n  hence \"(sqrt ((abscissa X - abscissa A)^2 + (ordinate X - ordinate A) ^2))^2 = (sqrt ((abscissa B - abscissa C)^2 + (ordinate B - ordinate C)^2)) ^2\" \n    by (auto simp add: power_def)\n  hence l3: \"(abscissa X - abscissa A)^2 + (ordinate X - ordinate A) ^2 = (abscissa B - abscissa C)^2 + (ordinate B - ordinate C)^2\"\n    by auto\n  have \"sqrt ((abscissa X - abscissa D)^2 + (ordinate X - ordinate D) ^2) = sqrt ((abscissa E - abscissa F)^2 + (ordinate E - ordinate F) ^2)\"\n    by (metis (no_types) eqDist1 distance_def minus_diff_eq point_abscissa_diff point_dist_def point_ordinate_diff power2_minus)\n  hence l3bis: \"(abscissa X - abscissa D)^2 + (ordinate X - ordinate D) ^2 = (abscissa E - abscissa F)^2 + (ordinate E - ordinate F)^2\"\n    by auto\n  have l4: \"\\<not> (abscissa A = abscissa D & ordinate A = ordinate D)\"\n    by (metis point_eq_iff notEqual eqDist0 eqDist1)\n  have \"(abscissa B - abscissa C) \\<in> radical_sqrt\" \n    by (metis absB absC radical_sqrt_rule_subtraction)\n  hence sl1: \"((abscissa B - abscissa C)^2) \\<in> radical_sqrt\" \n    by (metis (no_types) comm_semiring_1_class.normalizing_semiring_rules(33) comm_semiring_1_class.normalizing_semiring_rules(36) power_even_eq radical_sqrt.intros(5))\n  have \"(ordinate B - ordinate C) \\<in> radical_sqrt\" \n    by (metis ordB ordC radical_sqrt_rule_subtraction)\n  hence \"(ordinate B - ordinate C)^2 \\<in> radical_sqrt\" \n    by (metis (no_types) comm_semiring_1_class.normalizing_semiring_rules(33) comm_semiring_1_class.normalizing_semiring_rules(36) power_even_eq radical_sqrt.intros(5))\n  hence sl3: \"((abscissa B - abscissa C)^2 + (ordinate B - ordinate C)^2) \\<in> radical_sqrt\"\n    by (metis radical_sqrt.intros(4) sl1) \n  have \"(abscissa E - abscissa F) \\<in> radical_sqrt\"\n    by (metis absE absF radical_sqrt_rule_subtraction)\n  hence sl4: \"((abscissa E - abscissa F)^2) \\<in> radical_sqrt\" \n    by (metis (no_types) comm_semiring_1_class.normalizing_semiring_rules(33) comm_semiring_1_class.normalizing_semiring_rules(36) power_even_eq radical_sqrt.intros(5))\n  have \"(ordinate E - ordinate F) \\<in> radical_sqrt\" \n    by (metis ordE ordF radical_sqrt_rule_subtraction)\n  hence \"(ordinate E - ordinate F)^2 \\<in> radical_sqrt\" \n    by (metis (no_types) comm_semiring_1_class.normalizing_semiring_rules(33) comm_semiring_1_class.normalizing_semiring_rules(36) power_even_eq radical_sqrt.intros(5))\n  hence \"((abscissa E - abscissa F)^2 + (ordinate E - ordinate F)^2) \\<in> radical_sqrt\"\n    by (metis radical_sqrt.intros(4) sl4) \n  thus ?thesis \n    using radical_sqrt_simultaneous_quadratic_quadratic\n            [of \"abscissa A\" \"ordinate A\" \"(abscissa B - abscissa C)^2 + (ordinate B - ordinate C)^2\" \n                \"abscissa D\" \"ordinate D\" \"(abscissa E - abscissa F)^2 + (ordinate E - ordinate F)^2\" \n                \"abscissa X\" \"ordinate X\"] \n          absA ordA absD ordD l3 l3bis l4 sl3\n    by auto\nqed\n\nsubsection {* Definition of the set of contructible points *}\n\ninductive_set constructible :: \"point set\"\n  where\n  \"(M \\<in> points \\<and> (abscissa M) \\<in> \\<rat> \\<and> (ordinate M) \\<in> \\<rat>) \\<Longrightarrow> M \\<in> constructible\"|\n  \"(A \\<in> constructible \\<and> B \\<in> constructible \\<and> C \\<in> constructible \\<and> D \\<in> constructible \\<and> \\<not> parallel A B C D \\<and> is_intersection M A B C D) \\<Longrightarrow> M \\<in> constructible\"|\n  \"(A \\<in> constructible \\<and> B \\<in> constructible \\<and> C \\<in> constructible \\<and> D \\<in> constructible \\<and> E \\<in> constructible \\<and> \\<not> A = B \\<and> collinear A M B \\<and> distance C M = distance D E) \\<Longrightarrow> M \\<in> constructible\"|\n  \"(A \\<in> constructible \\<and> B \\<in> constructible \\<and> C \\<in> constructible \\<and> D \\<in> constructible \\<and> E \\<in> constructible \\<and> F \\<in> constructible \\<and> \\<not> (A = D \\<and> distance B C = distance E F) \\<and> distance A M = distance B C \\<and> distance D M = distance E F) \\<Longrightarrow> M \\<in> constructible\"\n\nsubsection {* An important property about constructible points: their\ncoordinates are radicals *}\n\nlemma constructible_radical_sqrt:\n  assumes h: \"M \\<in> constructible\"\n  shows \"(abscissa M) \\<in> radical_sqrt & (ordinate M) \\<in> radical_sqrt\"\n  apply (rule constructible.induct)\n  apply (metis assms)\n  apply (metis radical_sqrt.intros(1))\n  apply (metis radical_sqrt_line_line_intersection)\n  apply (metis radical_sqrt_line_circle_intersection)\n  apply (metis radical_sqrt_circle_circle_intersection)\n  done\n\nsubsection {* Proving the impossibility of duplicating the cube *}\n\nlemma impossibility_of_doubling_the_cube_lemma:\n  assumes x: \"x \\<in> radical_sqrt\"\n  and x_eqn: \"x^3 = 2\"\n  shows False\nproof-\n  have  \"\\<exists>x \\<in> Rats. x^3 + 0 * x^2 + 0 * x + (- 2) = (0::real)\" \n    using x x_eqn cubic_root_radical_sqrt_rational [of \"0\" \"0\" \"- 2\"]\n    by auto\n  then obtain y::real where hypsy: \"y: Rats & y^3 = 2\"\n    by (simp only: left_minus mult_zero_left add_0_right real_add_minus_iff) auto\n  then obtain r where hypsr: \"y = of_rat r\" \n    unfolding Rats_def\n    by (metis Rats_cases hypsy)\n  hence \"\\<exists>! p. r = Fract (fst p) (snd p) & snd p > 0 & coprime (fst p) (snd p)\" \n    by (metis quotient_of_unique)\n  then obtain p where hypsp: \"r = Fract (fst p) (snd p) & snd p > 0 & coprime (fst p) (snd p)\" \n    by auto\n  have l6: \"r^3 = 2\" \n    by (metis (lifting) hypsy hypsr of_rat_eq_iff of_rat_numeral_eq of_rat_power)\n  have l7: \"r^3  = Fract ((fst p)^3) ((snd p)^3)\" \n    by (metis (no_types) hypsp mult_rat power3_eq_cube)\n  have l8: \"(snd p) ^3 > 0 & coprime ((fst p)^3) ((snd p)^3)\" \n    by (metis hypsp gcd_exp_int power_one zero_less_power)\n  have \"Fract ((fst p)^3) ((snd p)^3) = 2\"\n    using l6 l7\n    by auto\n  hence \"Fract ((fst p)^3) ((snd p)^3) = Fract 2 1\"\n    by (metis rat_number_expand(3))\n  hence l12: \"(fst p) ^3 = ((snd p)^3) * 2\" using hypsp\n    by (simp add: eq_rat)\n  hence \"2 dvd (fst p)^3\"\n    using l8\n    by (auto simp add: dvd_def)\n  hence two_dvd_fst: \"2 dvd fst p\"\n    by (auto dest: two_is_prime simp add: numeral_3_eq_3 ac_simps)\n  hence \"8 dvd (fst p)^3\"\n    by (auto simp add: dvd_def power_def)\n  hence \"8 dvd ((snd p)^3) * 2\" \n    using l12\n    by auto\n  hence \"2 dvd (snd p)^3\"\n    by (auto simp add: dvd_def)\n  then have two_dvd_snd: \"2 dvd snd p\"\n    by (auto dest: two_is_prime simp add: numeral_3_eq_3 ac_simps)\n  thus ?thesis \n    using hypsp\n    apply (auto simp add: dvd_def)\n    by (metis gcd_greatest_int one_less_numeral_iff rel_simps(9) \n              two_dvd_fst two_dvd_snd zdvd_not_zless zero_less_one)\nqed\n\n\ntheorem impossibility_of_doubling_the_cube:\n  \"x^3 = 2 \\<Longrightarrow> (Point x 0) \\<notin> constructible\"\n  by (metis abscissa.simps constructible_radical_sqrt impossibility_of_doubling_the_cube_lemma)\n\n\nsubsection {* Proving the impossibility of trisecting an angle *}\n\nlemma cos_3:\n  shows \"cos(3 * x) = 4 * (cos x)^3 - 3 * (cos x)\"\nproof-\n  have \"cos (3 * x) = cos (x + 2*x)\"\n    by simp\n  also have \"... = cos x * cos (2 * x) - sin x * sin (2 * x)\" \n    using sin_cos_add_lemma [of \"x\" \"2*x\"]\n    by (metis cos_add)\n  also have \"... = cos x * (cos x * cos x - sin x * sin x) - sin x * (sin x * cos x + cos x * sin x)\"\n    by (metis cos_add mult_2 sin_add)\n  also have \"... = cos x * (cos x * cos x - (1 - cos x * cos x)) - sin x * (sin x * cos x + cos x * sin x)\"\n    by (metis comm_semiring_1_class.normalizing_semiring_rules(29) sin_squared_eq)\n  also have \"... = cos x * (2 * cos x * cos x) + cos x * ( - 1) - sin x * sin x * cos x - sin x * sin x * cos x\"\n    by (auto simp add: algebra_simps) \n  also have \"... = 2* cos x * cos x * cos x - cos x - (1 - cos x * cos x) * cos x - (1 - cos x * cos x) * cos x\"\n    apply auto\n    by (metis add_0_left add_diff_cancel comm_semiring_1_class.normalizing_semiring_rules(24) cos_diff2 cos_zero)\n  also have \"... = 2 * cos x *cos x * cos x - cos x + - 2 * ((1 - cos x * cos x) * cos x)\"\n    by auto\n  also have \"... = 4 * cos x * cos x * cos x - 3 * cos x\"\n    by (simp add: algebra_simps)\n  also have \"... = 4 * cos x ^3 - 3 * cos x\"\n    by (simp add: power_def)\n  finally show ?thesis .\nqed\n\nlemma impossibility_of_trisecting_pi_over_3_lemma:\n  assumes x: \"x \\<in> radical_sqrt\"\n  and x_eqn: \"x^3 - 3 * x - 1 = 0\"\n  shows False\nproof-\n  have \"\\<exists>x \\<in> Rats. x^3 + (- 3) * x = (1::real)\"\n    using x_eqn cubic_root_radical_sqrt_rational [of 0 \"- 3\" \"- 1\"] x\n    by force\n  then obtain y :: real where hypsy: \"y \\<in> Rats \\<and> y ^ 3 - 3 * y = 1\" by auto\n  then obtain r where hypsr: \"y = of_rat r\" \n    by (metis Rats_cases)\n  then obtain p where hypsp: \"r = Fract (fst p) (snd p) & snd p > 0 & coprime (fst p) (snd p)\" \n      using quotient_of_unique hypsy\n      by blast\n  have r3eq: \"r^3 - 3 * r = 1\" \n    using hypsy hypsr [[hypsubst_thin = true]]\n    by auto (metis (hide_lams, no_types) of_rat_1 of_rat_diff of_rat_eq_iff of_rat_mult of_rat_numeral_eq of_rat_power)\n  have l7: \"(snd p) ^3 > 0 & coprime ((fst p)^3) ((snd p)^3)\"\n    by (metis hypsp gcd_exp_int power_one zero_less_power)\n  have \"r^3  = Fract ((fst p)^3) ((snd p)^3)\" \n    by (metis (no_types) mult_rat power3_eq_cube hypsp)\n  then have \"Fract ((fst p)^3) ((snd p)^3) - (Fract (3 * (fst p)) (snd p)) = 1\"\n    using r3eq hypsp\n    by (simp add: Fract_of_int_quotient)\n  then have l10: \"Fract ((fst p)^3) ((snd p)^3) - Fract (3 * (fst p) * (snd p)^2 ) ((snd p)^3) = 1\" \n    using hypsp\n    by (simp add: power_def algebra_simps Fract_of_int_quotient)\n  have \"Fract ((fst p)^3 - (3 * (fst p) * (snd p)^2)) ((snd p)^3) =\n        Fract (((fst p)^3 - (3 * (fst p) * (snd p)^2))*(snd p)^3) (((snd p)^3) * (snd p)^3)\"\n    using l7\n        mult_rat_cancel [of \"(snd p)^3\" \"((fst p)^3 - (3 * (fst p) * (snd p)^2))\" \"(snd p)^3\"]\n    by (auto simp add: algebra_simps)\n  also have \"... = Fract 1 1\"\n    by (metis l7 l10 one_rat diff_rat mult_neg_pos not_square_less_zero int_distrib(3))\n  finally have \"(fst p)^3 - 3 * (fst p) * (snd p)^2 = (snd p)^3\" using hypsp\n    by (simp add: eq_rat) \n  hence \"(fst p) * ((fst p)^2 - 3 * (snd p) ^2) = (snd p)^3\"\n        \"(snd p) * ((snd p)^2 + 3 * (fst p) * (snd p)) = (fst p) ^3\" \n    by (auto simp add: power_def algebra_simps)\n  hence \"(fst p) dvd ((snd p)^3)\"  \"(snd p) dvd ((fst p)^3)\"\n    apply (auto simp add: dvd_def)\n    apply (rule_tac x = \"(fst p)^2 - 3 * (snd p) ^2\" in exI)\n    apply (rule_tac [2] x = \"(snd p)^2 + 3 * (fst p) * (snd p)\" in exI)\n    apply auto\n    done\n  moreover have \"coprime (fst p) ((snd p)^3)\"  \"coprime ((fst p)^3) (snd p)\"\n    using hypsp\n    by (auto simp add: coprime_exp_int gcd_commute_int)\n  ultimately have \"(fst p) = 1 | (fst p) = - 1\"  \"(snd p) = 1\" \n    using hypsp \n    by auto\n  hence \"r = 1 | r = - 1\"\n    by (metis hypsp minus_rat one_rat)\n  with r3eq show False\n    by (auto simp add: power_def algebra_simps)\nqed\n\n\ntheorem impossibility_of_trisecting_angle_pi_over_3: \n  \"Point (cos (pi / 9)) 0 \\<notin> constructible\"\nproof-\n  have \"cos (3 *(pi/9)) = 4 * (cos (pi/9))^3 - 3 * cos (pi/9)\" \n    using cos_3 [of \"pi / 9\"]\n    by auto\n  hence \"1/2 = 4 * (cos (pi/9))^3 - 3 * cos (pi/9)\" \n    by (simp add: cos_60)\n  hence \"8 * (cos (pi/9))^3 - 6 * cos (pi/9) - 1 = 0\"\n    by (simp add: algebra_simps)\n  hence \"(2 * cos (pi / 9)) ^3 - 3 * (2 * cos (pi / 9)) - 1 = 0\"\n    by (simp add: algebra_simps power_def)\n  hence \"\\<not> (2 * cos (pi / 9)) \\<in> radical_sqrt\"\n    by (metis impossibility_of_trisecting_pi_over_3_lemma)\n  hence \"\\<not> (cos (pi / 9)) \\<in> radical_sqrt\"\n    by (metis divide_self_if mult_zero_right one_add_one radical_sqrt.intros(4) radical_sqrt.intros(5) radical_sqrt_rule_division)\n  thus ?thesis\n    by (metis abscissa.simps constructible_radical_sqrt)\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/Impossible_Geometry/Impossible_Geometry.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314738181875, "lm_q2_score": 0.7905303186696747, "lm_q1q2_score": 0.7001185312213855}}
{"text": "theory hw01\n  imports Main\nbegin\n\nfun listsum:: \"int list \\<Rightarrow> int\" where\n  \"listsum [] = 0\"\n| \"listsum (x # xs) =  listsum xs + x\"\n\nvalue \"listsum [1,2,3] = 6\"\nvalue \"listsum [] = 0\"\nvalue \"listsum [1,-2,3] = 2\"\n\nlemma listsum_filter_x: \"listsum (filter (\\<lambda>x. x\\<noteq>0) l) = listsum l\"\n  apply(induction l)\n  apply(auto)\n  done\n\nlemma listsum_append: \"listsum (xs @ ys) = listsum xs + listsum ys\"\n  apply(induction xs)\n   apply(auto)\n  done\n\nlemma listsum_rev: \"listsum (rev xs) = listsum xs\"\n  apply(induction xs)\n   apply(auto simp:listsum_append)\n  done\n\nlemma listsum_noneg: \"listsum (filter (\\<lambda>x. x>0) l) \\<ge> listsum l\"\n  apply(induction l)\n   apply(auto)\n  done\n\nfun flatten :: \"'a list list \\<Rightarrow> 'a list\" where\n  \"flatten [] = []\"\n| \"flatten (l#ls) = l @ flatten ls\"\n\nvalue \"flatten [[1,2,3],[2]] = [1,2,3,2::int]\"\nvalue \"flatten [[1,2,3],[],[2]] = [1,2,3,2::int]\"\n\nlemma \"listsum (flatten xs) = listsum(map listsum xs)\"\n  apply(induction xs)\n  apply(auto simp:listsum_append)\n  done\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/01/hw01.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314738181875, "lm_q2_score": 0.7905303087996143, "lm_q1q2_score": 0.7001185224801493}}
{"text": "theory sse_boolean_algebra_quantification\n  imports sse_boolean_algebra\nbegin\nhide_const(open) List.list.Nil no_notation List.list.Nil (\"[]\")  (*We have no use for lists... *)\nhide_const(open) Relation.converse no_notation Relation.converse (\"(_\\<inverse>)\" [1000] 999) (*..nor for relations in this work*)\nnitpick_params[assms=true, user_axioms=true, show_all, expect=genuine, format=3] (*default Nitpick settings*)\n\n\nsubsection \\<open>Obtaining a complete Boolean Algebra\\<close>\n\ntext\\<open>\\noindent{Our aim is to obtain a complete Boolean algebra which we can use to interpret\nquantified formulas (in the spirit of Boolean-valued models for set theory).}\\<close>\n\ntext\\<open>\\noindent{We start by defining infinite meet (infimum) and infinite join (supremum) operations,}\\<close>\ndefinition infimum:: \"(\\<sigma>\\<Rightarrow>bool)\\<Rightarrow>\\<sigma>\" (\"\\<^bold>\\<And>_\") where \"\\<^bold>\\<And>S \\<equiv> \\<lambda>w. \\<forall>X. S X \\<longrightarrow> X w\"\ndefinition supremum::\"(\\<sigma>\\<Rightarrow>bool)\\<Rightarrow>\\<sigma>\" (\"\\<^bold>\\<Or>_\") where \"\\<^bold>\\<Or>S \\<equiv> \\<lambda>w. \\<exists>X. S X  \\<and>  X w\"\n\ntext\\<open>\\noindent{and show that the corresponding lattice is complete.}\\<close>\nabbreviation \"upper_bound U S \\<equiv> \\<forall>X. (S X) \\<longrightarrow> X \\<^bold>\\<preceq> U\"\nabbreviation \"lower_bound L S \\<equiv> \\<forall>X. (S X) \\<longrightarrow> L \\<^bold>\\<preceq> X\"\nabbreviation \"is_supremum U S \\<equiv> upper_bound U S \\<and> (\\<forall>X. upper_bound X S \\<longrightarrow> U \\<^bold>\\<preceq> X)\"\nabbreviation \"is_infimum  L S \\<equiv> lower_bound L S \\<and> (\\<forall>X. lower_bound X S \\<longrightarrow> X \\<^bold>\\<preceq> L)\"\n\nlemma sup_char: \"is_supremum \\<^bold>\\<Or>S S\" unfolding supremum_def by auto\nlemma sup_ext: \"\\<forall>S. \\<exists>X. is_supremum X S\" by (metis supremum_def)\nlemma inf_char: \"is_infimum \\<^bold>\\<And>S S\" unfolding infimum_def by auto\nlemma inf_ext: \"\\<forall>S. \\<exists>X. is_infimum X S\" by (metis infimum_def)\n\ntext\\<open>\\noindent{We can check that being closed under supremum/infimum entails being closed under join/meet.}\\<close>\nabbreviation \"meet_closed S \\<equiv>  \\<forall>X Y. (S X \\<and> S Y) \\<longrightarrow> S(X \\<^bold>\\<and> Y)\"\nabbreviation \"join_closed S \\<equiv>  \\<forall>X Y. (S X \\<and> S Y) \\<longrightarrow> S(X \\<^bold>\\<or> Y)\"\n\nabbreviation \"nonEmpty S \\<equiv> \\<exists>x. S x\"\nabbreviation \"contains S D \\<equiv>  \\<forall>X. D X \\<longrightarrow> S X\"\nabbreviation \"infimum_closed S  \\<equiv> \\<forall>D. nonEmpty D \\<and> contains S D \\<longrightarrow> S(\\<^bold>\\<And>D)\"\nabbreviation \"supremum_closed S \\<equiv> \\<forall>D. nonEmpty D \\<and> contains S D \\<longrightarrow> S(\\<^bold>\\<Or>D)\"\n\nlemma inf_meet_closed: \"\\<forall>S. infimum_closed S \\<longrightarrow> meet_closed S\" proof -\n  { fix S\n    { assume inf_closed: \"infimum_closed S\"\n      hence \"meet_closed S\" proof -\n        { fix X::\"\\<sigma>\" and Y::\"\\<sigma>\"\n          let ?D=\"\\<lambda>Z. Z=X \\<or> Z=Y\"\n          { assume \"S X \\<and> S Y\"\n            hence \"contains S ?D\" by simp\n            moreover have \"nonEmpty ?D\" by auto\n            ultimately have \"S(\\<^bold>\\<And>?D)\" using inf_closed by simp\n            hence \"S(\\<lambda>w. \\<forall>Z. (Z=X \\<or> Z=Y) \\<longrightarrow> Z w)\" unfolding infimum_def by simp\n            moreover have \"(\\<lambda>w. \\<forall>Z. (Z=X \\<or> Z=Y) \\<longrightarrow> Z w) = (\\<lambda>w. X w \\<and> Y w)\" by auto\n            ultimately have \"S(\\<lambda>w. X w \\<and> Y w)\" by simp\n          } hence \"(S X \\<and> S Y) \\<longrightarrow> S(X \\<^bold>\\<and> Y)\" unfolding conn by (rule impI)\n        } thus ?thesis by simp  qed\n    } hence \"infimum_closed S \\<longrightarrow> meet_closed S\" by simp\n  } thus ?thesis by (rule allI)\nqed\nlemma sup_join_closed: \"\\<forall>P. supremum_closed P \\<longrightarrow> join_closed P\" proof -\n  { fix S\n    { assume sup_closed: \"supremum_closed S\"\n      hence \"join_closed S\" proof -\n        { fix X::\"\\<sigma>\" and Y::\"\\<sigma>\"\n          let ?D=\"\\<lambda>Z. Z=X \\<or> Z=Y\"\n          { assume \"S X \\<and> S Y\"\n            hence \"contains S ?D\" by simp\n            moreover have \"nonEmpty ?D\" by auto\n            ultimately have \"S(\\<^bold>\\<Or>?D)\" using sup_closed by simp\n            hence \"S(\\<lambda>w. \\<exists>Z. (Z=X \\<or> Z=Y) \\<and> Z w)\" unfolding supremum_def by simp\n            moreover have \"(\\<lambda>w. \\<exists>Z. (Z=X \\<or> Z=Y) \\<and> Z w) = (\\<lambda>w. X w \\<or> Y w)\" by auto\n            ultimately have \"S(\\<lambda>w. X w \\<or> Y w)\" by simp\n          } hence \"(S X \\<and> S Y) \\<longrightarrow> S(X \\<^bold>\\<or> Y)\" unfolding conn by (rule impI)\n        } thus ?thesis by simp qed\n    } hence \"supremum_closed S \\<longrightarrow> join_closed S\" by simp\n  } thus ?thesis by (rule allI)\nqed\n\n\nsubsection \\<open>Adding quantifiers (restricted and unrestricted)\\<close>\n\ntext\\<open>\\noindent{We can harness HOL to define quantification over individuals of arbitrary type (using polymorphism).\nThese (unrestricted) quantifiers take a propositional function and give a proposition.}\\<close>  \nabbreviation mforall::\"('t\\<Rightarrow>\\<sigma>)\\<Rightarrow>\\<sigma>\" (\"\\<^bold>\\<forall>_\" [55]56) where \"\\<^bold>\\<forall>\\<pi> \\<equiv> \\<lambda>w. \\<forall>X. (\\<pi> X) w\"\nabbreviation mexists::\"('t\\<Rightarrow>\\<sigma>)\\<Rightarrow>\\<sigma>\" (\"\\<^bold>\\<exists>_\" [55]56) where \"\\<^bold>\\<exists>\\<pi> \\<equiv> \\<lambda>w. \\<exists>X. (\\<pi> X) w\"\ntext\\<open>\\noindent{To improve readability, we introduce for them an useful binder notation.}\\<close>\nabbreviation mforallB (binder\"\\<^bold>\\<forall>\"[55]56) where \"\\<^bold>\\<forall>X. \\<pi> X \\<equiv> \\<^bold>\\<forall>\\<pi>\"\nabbreviation mexistsB (binder\"\\<^bold>\\<exists>\"[55]56) where \"\\<^bold>\\<exists>X. \\<pi> X \\<equiv> \\<^bold>\\<exists>\\<pi>\"\n\n(*TODO: is it possible to also add binder notation to the ones below?*)\ntext\\<open>\\noindent{Moreover, we define restricted quantifiers which take a 'functional domain' as additional parameter.\nThe latter is a propositional function that maps each element 'e' to the proposition 'e exists'.}\\<close>\nabbreviation mforall_restr::\"('t\\<Rightarrow>\\<sigma>)\\<Rightarrow>('t\\<Rightarrow>\\<sigma>)\\<Rightarrow>\\<sigma>\" (\"\\<^bold>\\<forall>\\<^sup>R(_)_\") where \"\\<^bold>\\<forall>\\<^sup>R(\\<delta>)\\<pi> \\<equiv> \\<lambda>w.\\<forall>X. (\\<delta> X) w \\<longrightarrow> (\\<pi> X) w\" \nabbreviation mexists_restr::\"('t\\<Rightarrow>\\<sigma>)\\<Rightarrow>('t\\<Rightarrow>\\<sigma>)\\<Rightarrow>\\<sigma>\" (\"\\<^bold>\\<exists>\\<^sup>R(_)_\") where \"\\<^bold>\\<exists>\\<^sup>R(\\<delta>)\\<pi> \\<equiv> \\<lambda>w.\\<exists>X. (\\<delta> X) w  \\<and>  (\\<pi> X) w\"\n\n\nsubsection \\<open>Relating quantifiers with further operators\\<close>\n\ntext\\<open>\\noindent{The following 'type-lifting' function is useful for converting sets into 'rigid' propositional functions.}\\<close>\nabbreviation lift_conv::\"('t\\<Rightarrow>bool)\\<Rightarrow>('t\\<Rightarrow>\\<sigma>)\" (\"\\<lparr>_\\<rparr>\") where \"\\<lparr>S\\<rparr> \\<equiv> \\<lambda>X. \\<lambda>w. S X\"\n\ntext\\<open>\\noindent{We introduce an useful operator: the range of a propositional function (resp. restricted over a domain),}\\<close>\ndefinition pfunRange::\"('t\\<Rightarrow>\\<sigma>)\\<Rightarrow>(\\<sigma>\\<Rightarrow>bool)\" (\"Ra(_)\") where \"Ra(\\<pi>) \\<equiv> \\<lambda>Y. \\<exists>x. (\\<pi> x) = Y\"\ndefinition pfunRange_restr::\"('t\\<Rightarrow>\\<sigma>)\\<Rightarrow>('t\\<Rightarrow>bool)\\<Rightarrow>(\\<sigma>\\<Rightarrow>bool)\" (\"Ra[_|_]\") where \"Ra[\\<pi>|D] \\<equiv> \\<lambda>Y. \\<exists>x. (D x) \\<and> (\\<pi> x) = Y\"\n\ntext\\<open>\\noindent{and check that taking infinite joins/meets (suprema/infima) over the range of a propositional function\ncan be equivalently codified by using quantifiers. This is a quite useful simplifying relationship.}\\<close>\nlemma Ra_all: \"\\<^bold>\\<And>Ra(\\<pi>) = \\<^bold>\\<forall>\\<pi>\" by (metis (full_types) infimum_def pfunRange_def)\nlemma Ra_ex:  \"\\<^bold>\\<Or>Ra(\\<pi>) = \\<^bold>\\<exists>\\<pi>\" by (metis (full_types) pfunRange_def supremum_def)\nlemma Ra_restr_all: \"\\<^bold>\\<And>Ra[\\<pi>|D] = \\<^bold>\\<forall>\\<^sup>R\\<lparr>D\\<rparr>\\<pi>\" by (metis (full_types) pfunRange_restr_def infimum_def)\nlemma Ra_restr_ex:  \"\\<^bold>\\<Or>Ra[\\<pi>|D] = \\<^bold>\\<exists>\\<^sup>R\\<lparr>D\\<rparr>\\<pi>\" by (metis pfunRange_restr_def supremum_def)\n\ntext\\<open>\\noindent{We further introduce the positive (negative) restriction of a propositional function wrt. a domain,}\\<close>\nabbreviation pfunRestr_pos::\"('t\\<Rightarrow>\\<sigma>)\\<Rightarrow>('t\\<Rightarrow>\\<sigma>)\\<Rightarrow>('t\\<Rightarrow>\\<sigma>)\" (\"[_|_]\\<^sup>P\") where \"[\\<pi>|\\<delta>]\\<^sup>P \\<equiv> \\<lambda>X. \\<lambda>w. (\\<delta> X) w \\<longrightarrow> (\\<pi> X) w\"\nabbreviation pfunRestr_neg::\"('t\\<Rightarrow>\\<sigma>)\\<Rightarrow>('t\\<Rightarrow>\\<sigma>)\\<Rightarrow>('t\\<Rightarrow>\\<sigma>)\" (\"[_|_]\\<^sup>N\") where \"[\\<pi>|\\<delta>]\\<^sup>N \\<equiv> \\<lambda>X. \\<lambda>w. (\\<delta> X) w  \\<and>  (\\<pi> X) w\"\n\ntext\\<open>\\noindent{and check that some additional simplifying relationships obtain.}\\<close>\nlemma all_restr: \"\\<^bold>\\<forall>\\<^sup>R(\\<delta>)\\<pi> = \\<^bold>\\<forall>[\\<pi>|\\<delta>]\\<^sup>P\" by simp\nlemma ex_restr:  \"\\<^bold>\\<exists>\\<^sup>R(\\<delta>)\\<pi> = \\<^bold>\\<exists>[\\<pi>|\\<delta>]\\<^sup>N\" by simp\nlemma Ra_all_restr: \"\\<^bold>\\<And>Ra[\\<pi>|D] = \\<^bold>\\<forall>[\\<pi>|\\<lparr>D\\<rparr>]\\<^sup>P\" using Ra_restr_all by blast\nlemma Ra_ex_restr:  \"\\<^bold>\\<Or>Ra[\\<pi>|D] = \\<^bold>\\<exists>[\\<pi>|\\<lparr>D\\<rparr>]\\<^sup>N\" by (simp add: Ra_restr_ex)\n\ntext\\<open>\\noindent{Observe that using these operators has the advantage of allowing for binder notation,}\\<close>\nlemma \"\\<^bold>\\<forall>X. [\\<pi>|\\<delta>]\\<^sup>P X = \\<^bold>\\<forall>[\\<pi>|\\<delta>]\\<^sup>P\" by simp\nlemma \"\\<^bold>\\<exists>X. [\\<pi>|\\<delta>]\\<^sup>N X = \\<^bold>\\<exists>[\\<pi>|\\<delta>]\\<^sup>N\" by simp\n\ntext\\<open>\\noindent{noting that extra care should be taken when working with complements or negations;\nalways remember to switch P/N (positive/negative restriction) accordingly.}\\<close>\nlemma \"\\<^bold>\\<forall>\\<^sup>R(\\<delta>)\\<pi>  = \\<^bold>\\<forall>X.  [\\<pi>|\\<delta>]\\<^sup>P X\" by simp\nlemma \"\\<^bold>\\<forall>\\<^sup>R(\\<delta>)\\<pi>\\<^sup>c = \\<^bold>\\<forall>X. \\<^bold>\\<midarrow>[\\<pi>|\\<delta>]\\<^sup>N X\" by (simp add: compl_def)\nlemma \"\\<^bold>\\<exists>\\<^sup>R(\\<delta>)\\<pi>  = \\<^bold>\\<exists>X.  [\\<pi>|\\<delta>]\\<^sup>N X\" by simp\nlemma \"\\<^bold>\\<exists>\\<^sup>R(\\<delta>)\\<pi>\\<^sup>c = \\<^bold>\\<exists>X. \\<^bold>\\<midarrow>[\\<pi>|\\<delta>]\\<^sup>P X\" by (simp add: compl_def)\n\ntext\\<open>\\noindent{The previous definitions allow us to nicely characterize the interaction\nbetween function composition and (restricted) quantification:}\\<close>\nlemma Ra_all_comp1: \"\\<^bold>\\<forall>(\\<pi>\\<circ>\\<gamma>) = \\<^bold>\\<forall>[\\<pi>|\\<lparr>Ra \\<gamma>\\<rparr>]\\<^sup>P\" by (metis comp_apply pfunRange_def)\nlemma Ra_all_comp2: \"\\<^bold>\\<forall>(\\<pi>\\<circ>\\<gamma>) = \\<^bold>\\<forall>\\<^sup>R\\<lparr>Ra \\<gamma>\\<rparr> \\<pi>\" by (metis comp_apply pfunRange_def)\nlemma Ra_ex_comp1:  \"\\<^bold>\\<exists>(\\<pi>\\<circ>\\<gamma>) = \\<^bold>\\<exists>[\\<pi>|\\<lparr>Ra \\<gamma>\\<rparr>]\\<^sup>N\" by (metis comp_apply pfunRange_def)\nlemma Ra_ex_comp2:  \"\\<^bold>\\<exists>(\\<pi>\\<circ>\\<gamma>) = \\<^bold>\\<exists>\\<^sup>R\\<lparr>Ra \\<gamma>\\<rparr> \\<pi>\" by (metis comp_apply pfunRange_def)\n\ntext\\<open>\\noindent{This useful operator returns for a given domain of propositions the domain of their complements:}\\<close>\ndefinition dom_compl::\"(\\<sigma>\\<Rightarrow>bool)\\<Rightarrow>(\\<sigma>\\<Rightarrow>bool)\" (\"(_\\<inverse>)\") where \"D\\<inverse> \\<equiv> \\<lambda>X. \\<exists>Y. (D Y) \\<and> (X = \\<^bold>\\<midarrow>Y)\"\nlemma dom_compl_def2: \"D\\<inverse> = (\\<lambda>X. D(\\<^bold>\\<midarrow>X))\" unfolding dom_compl_def by (metis comp_symm fun_upd_same)\nlemma dom_compl_invol: \"D = (D\\<inverse>)\\<inverse>\" unfolding dom_compl_def by (metis comp_symm fun_upd_same)\n\ntext\\<open>\\noindent{We can now check an infinite variant of the De Morgan laws,}\\<close>\nlemma iDM_a: \"\\<^bold>\\<midarrow>(\\<^bold>\\<And>S) = \\<^bold>\\<Or>S\\<inverse>\" unfolding dom_compl_def2 infimum_def supremum_def using compl_def by force\nlemma iDM_b:\" \\<^bold>\\<midarrow>(\\<^bold>\\<Or>S) = \\<^bold>\\<And>S\\<inverse>\" unfolding dom_compl_def2 infimum_def supremum_def using compl_def by force\n\ntext\\<open>\\noindent{and some useful dualities regarding the range of propositional functions (restricted wrt. a domain).}\\<close>\nlemma Ra_compl: \"Ra[\\<pi>\\<^sup>c|D]  = Ra[\\<pi>|D]\\<inverse>\" unfolding pfunRange_restr_def dom_compl_def by auto\nlemma Ra_dual1: \"Ra[\\<pi>\\<^sup>d|D]  = Ra[\\<pi>|D\\<inverse>]\\<inverse>\" unfolding pfunRange_restr_def dom_compl_def using dual_def by auto\nlemma Ra_dual2: \"Ra[\\<pi>\\<^sup>d|D]  = Ra[\\<pi>\\<^sup>c|D\\<inverse>]\" unfolding pfunRange_restr_def dom_compl_def using dual_def by auto\nlemma Ra_dual3: \"Ra[\\<pi>\\<^sup>d|D]\\<inverse> = Ra[\\<pi>|D\\<inverse>]\" unfolding pfunRange_restr_def dom_compl_def using dual_def comp_symm by metis\nlemma Ra_dual4: \"Ra[\\<pi>\\<^sup>d|D\\<inverse>] = Ra[\\<pi>|D]\\<inverse>\" using Ra_dual3 dual_symm by metis\n\ntext\\<open>\\noindent{Finally, we check some facts concerning duality for quantifiers.}\\<close>\nlemma \"\\<^bold>\\<exists>\\<pi>\\<^sup>c = \\<^bold>\\<midarrow>(\\<^bold>\\<forall>\\<pi>)\" using compl_def by auto\nlemma \"\\<^bold>\\<forall>\\<pi>\\<^sup>c = \\<^bold>\\<midarrow>(\\<^bold>\\<exists>\\<pi>)\" using compl_def by auto\nlemma \"\\<^bold>\\<exists>X. \\<^bold>\\<midarrow>\\<pi> X = \\<^bold>\\<midarrow>(\\<^bold>\\<forall>X. \\<pi> X)\" using compl_def by auto\nlemma \"\\<^bold>\\<forall>X. \\<^bold>\\<midarrow>\\<pi> X = \\<^bold>\\<midarrow>(\\<^bold>\\<exists>X. \\<pi> X)\" using compl_def by auto\n\nlemma \"\\<^bold>\\<exists>\\<^sup>R(\\<delta>)\\<pi>\\<^sup>c = \\<^bold>\\<midarrow>(\\<^bold>\\<forall>\\<^sup>R(\\<delta>)\\<pi>)\" using compl_def by auto\nlemma \"\\<^bold>\\<forall>\\<^sup>R(\\<delta>)\\<pi>\\<^sup>c = \\<^bold>\\<midarrow>(\\<^bold>\\<exists>\\<^sup>R(\\<delta>)\\<pi>)\" using compl_def by auto\nlemma \"\\<^bold>\\<exists>X. \\<^bold>\\<midarrow>[\\<pi>|\\<delta>]\\<^sup>P X = \\<^bold>\\<midarrow>(\\<^bold>\\<forall>X. [\\<pi>|\\<delta>]\\<^sup>P X)\" using compl_def by auto\nlemma \"\\<^bold>\\<forall>X. \\<^bold>\\<midarrow>[\\<pi>|\\<delta>]\\<^sup>P X = \\<^bold>\\<midarrow>(\\<^bold>\\<exists>X. [\\<pi>|\\<delta>]\\<^sup>P X)\" using compl_def by auto\nlemma \"\\<^bold>\\<exists>X. \\<^bold>\\<midarrow>[\\<pi>|\\<delta>]\\<^sup>N X = \\<^bold>\\<midarrow>(\\<^bold>\\<forall>X. [\\<pi>|\\<delta>]\\<^sup>N X)\" using compl_def by auto\nlemma \"\\<^bold>\\<forall>X. \\<^bold>\\<midarrow>[\\<pi>|\\<delta>]\\<^sup>N X = \\<^bold>\\<midarrow>(\\<^bold>\\<exists>X. [\\<pi>|\\<delta>]\\<^sup>N X)\" using compl_def by auto\n\ntext\\<open>\\noindent{Warning: Do not switch P and N when passing to the dual form.}\\<close>\nlemma \"\\<^bold>\\<forall>X. [\\<pi>|\\<delta>]\\<^sup>P X = \\<^bold>\\<midarrow>(\\<^bold>\\<exists>X. \\<^bold>\\<midarrow>[\\<pi>|\\<delta>]\\<^sup>N X)\" nitpick oops \\<comment>\\<open> wrong: counterexample \\<close>\nlemma \"\\<^bold>\\<forall>X. [\\<pi>|\\<delta>]\\<^sup>P X = \\<^bold>\\<midarrow>(\\<^bold>\\<exists>X. \\<^bold>\\<midarrow>[\\<pi>|\\<delta>]\\<^sup>P X)\" using compl_def by auto \\<comment>\\<open> correct \\<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/Topological_Semantics/sse_boolean_algebra_quantification.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127566694177, "lm_q2_score": 0.8198933425148213, "lm_q1q2_score": 0.7001173842817341}}
{"text": "(*  Title:      Util_NatInf.thy\n    Date:       Oct 2006\n    Author:     David Trachtenherz\n*)\n\nheader {* Results for natural arithmetics with infinity *}\n\ntheory Util_NatInf\nimports \"~~/src/HOL/Library/Extended_Nat\"\nbegin\n\n\n\nsubsection {* Arithmetic operations with @{typ enat} *} \n\nsubsubsection {* Additional definitions *}\n\ninstantiation enat :: \"{Divides.div}\"\nbegin\n\ndefinition\n  div_enat_def [code del]: \"\n  a div b \\<equiv> (case a of \n    (enat x) \\<Rightarrow> (case b of (enat y) \\<Rightarrow> enat (x div y) | \\<infinity> \\<Rightarrow> 0) | \n    \\<infinity> \\<Rightarrow> (case b of (enat y) \\<Rightarrow> ((case y of 0 \\<Rightarrow> 0 | Suc n \\<Rightarrow> \\<infinity>)) | \\<infinity> \\<Rightarrow> \\<infinity> ))\"\ndefinition\n  mod_enat_def [code del]: \"\n  a mod b \\<equiv> (case a of \n    (enat x) \\<Rightarrow> (case b of (enat y) \\<Rightarrow> enat (x mod y) | \\<infinity> \\<Rightarrow> a) | \n    \\<infinity> \\<Rightarrow> \\<infinity>)\"\n\ninstance ..\n\nend\n\n\nlemmas enat_arith_defs = \n  zero_enat_def one_enat_def\n  plus_enat_def diff_enat_def times_enat_def div_enat_def mod_enat_def\ndeclare zero_enat_def[simp]\n\n\nlemmas ineq0_conv_enat[simp] = i0_less[symmetric, unfolded zero_enat_def]\n\nlemmas iless_eSuc0_enat[simp] = iless_eSuc0[unfolded zero_enat_def]\n\n\nsubsubsection {* Addition, difference, order *}\n\nlemma diff_eq_conv_nat: \"(x - y = (z::nat)) = (if y < x then x = y + z else z = 0)\"\nby auto\nlemma idiff_eq_conv: \"\n  (x - y = (z::enat)) = \n  (if y < x then x = y + z else if x \\<noteq> \\<infinity> then z = 0 else z = \\<infinity>)\"\nby (case_tac x, case_tac y, case_tac z, auto, case_tac z, auto)\nlemmas idiff_eq_conv_enat = idiff_eq_conv[unfolded zero_enat_def]\n\nlemma less_eq_idiff_eq_sum: \"y \\<le> (x::enat) \\<Longrightarrow> (z \\<le> x - y) = (z + y \\<le> x)\"\nby (case_tac x, case_tac y, case_tac z, fastforce+)\n\n\nlemma eSuc_pred: \"0 < n \\<Longrightarrow> eSuc (n - eSuc 0) = n\"\napply (case_tac n)\napply (simp add: eSuc_enat)+\ndone\nlemmas eSuc_pred_enat = eSuc_pred[unfolded zero_enat_def]\nlemmas iadd_0_enat[simp] = add_0_left[where 'a = enat, unfolded zero_enat_def]\nlemmas iadd_0_right_enat[simp] = add_0_right[where 'a=enat, unfolded zero_enat_def]\n\nlemma ile_add1: \"(n::enat) \\<le> n + m\"\nby (case_tac m, case_tac n, simp_all)\nlemma ile_add2: \"(n::enat) \\<le> m + n\"\nby (simp only: add.commute[of m] ile_add1)\n\nlemma iadd_iless_mono: \"\\<lbrakk> (i::enat) < j; k < l \\<rbrakk> \\<Longrightarrow> i + k < j + l\"\nby (case_tac i, case_tac k, case_tac j, case_tac l, simp_all)\n\nlemma trans_ile_iadd1: \"i \\<le> (j::enat) \\<Longrightarrow> i \\<le> j + m\" \nby (rule order_trans[OF _ ile_add1])\nlemma trans_ile_iadd2: \"i \\<le> (j::enat) \\<Longrightarrow> i \\<le> m + j\"\nby (rule order_trans[OF _ ile_add2])\n\nlemma trans_iless_iadd1: \"i < (j::enat) \\<Longrightarrow> i < j + m\"\nby (rule order_less_le_trans[OF _ ile_add1])\nlemma trans_iless_iadd2: \"i < (j::enat) \\<Longrightarrow> i < m + j\"\nby (rule order_less_le_trans[OF _ ile_add2])\n\nthm add_leD1[no_vars]\n\n\n\nthm diff_le_mono\n\n\nthm diff_less_mono\nlemma idiff_iless_mono: \"\\<lbrakk> m < (n::enat); l \\<le> m \\<rbrakk> \\<Longrightarrow> m - l < n - l\"\nby (case_tac m, case_tac n, case_tac l, simp_all, case_tac l, simp_all)\nthm diff_less_mono2\nlemma idiff_iless_mono2: \"\\<lbrakk> m < (n::enat); m < l \\<rbrakk> \\<Longrightarrow> l - n \\<le> l - m\"\nby (case_tac m, case_tac n, case_tac l, simp_all, case_tac l, simp_all)\n\n\nsubsubsection {* Multiplication and division *}\n\nlemmas imult_infinity_enat[simp] = imult_infinity[unfolded zero_enat_def]\nlemmas imult_infinity_right_enat[simp] = imult_infinity_right[unfolded zero_enat_def]\n\nlemma idiv_enat_enat[simp, code]: \"enat a div enat b = enat (a div b)\"\nunfolding div_enat_def by simp\nlemma idiv_infinity: \"0 < n \\<Longrightarrow> (\\<infinity>::enat) div n = \\<infinity>\"\nunfolding div_enat_def\napply (case_tac n, simp_all)\napply (rename_tac n1, case_tac n1, simp_all)\ndone\nlemmas idiv_infinity_enat[simp] = idiv_infinity[unfolded zero_enat_def]\n\nlemma idiv_infinity_right[simp]: \"n \\<noteq> \\<infinity> \\<Longrightarrow> n div (\\<infinity>::enat) = 0\"\nunfolding div_enat_def by (case_tac n, simp_all)\n\nlemma idiv_infinity_if: \"n div \\<infinity> = (if n = \\<infinity> then \\<infinity> else 0::enat)\"\nunfolding div_enat_def\nby (case_tac n, simp_all)\n\nlemmas idiv_infinity_if_enat = idiv_infinity_if[unfolded zero_enat_def]\n\nlemmas imult_0_enat[simp] = mult_zero_left[where 'a=enat,unfolded zero_enat_def]\nlemmas imult_0_right_enat[simp] = mult_zero_right[where 'a=enat,unfolded zero_enat_def]\n\nlemmas imult_is_0_enat = imult_is_0[unfolded zero_enat_def]\nlemmas enat_0_less_mult_iff_enat = enat_0_less_mult_iff[unfolded zero_enat_def]\n\nlemma imult_infinity_if: \"\\<infinity> * n = (if n = 0 then 0 else \\<infinity>::enat)\"\nby (case_tac n, simp_all)\nlemma imult_infinity_right_if: \"n * \\<infinity> = (if n = 0 then 0 else \\<infinity>::enat)\"\nby (case_tac n, simp_all)\nlemmas imult_infinity_if_enat = imult_infinity_if[unfolded zero_enat_def]\nlemmas imult_infinity_right_if_enat = imult_infinity_right_if[unfolded zero_enat_def]\n\nlemmas imult_is_infinity_enat = imult_is_infinity[unfolded zero_enat_def]\n\nlemma idiv_by_0: \"(a::enat) div 0 = 0\"\nunfolding div_enat_def by (case_tac a, simp_all)\nlemmas idiv_by_0_enat[simp, code] = idiv_by_0[unfolded zero_enat_def]\n\nlemma idiv_0: \"0 div (a::enat) = 0\"\nunfolding div_enat_def by (case_tac a, simp_all)\nlemmas idiv_0_enat[simp, code] = idiv_0[unfolded zero_enat_def]\n\nthm mod_by_0\nlemma imod_by_0: \"(a::enat) mod 0 = a\"\nunfolding mod_enat_def by (case_tac a, simp_all)\nlemmas imod_by_0_enat[simp, code] = imod_by_0[unfolded zero_enat_def]\n\nlemma imod_0: \"0 mod (a::enat) = 0\"\nunfolding mod_enat_def by (case_tac a, simp_all)\nlemmas imod_0_enat[simp, code] = imod_0[unfolded zero_enat_def]\n\nlemma imod_enat_enat[simp, code]: \"enat a mod enat b = enat (a mod b)\"\nunfolding mod_enat_def by simp\nlemma imod_infinity[simp, code]: \"\\<infinity> mod n = (\\<infinity>::enat)\"\nunfolding mod_enat_def by simp\nlemma imod_infinity_right[simp, code]: \"n mod (\\<infinity>::enat) = n\"\nunfolding mod_enat_def by (case_tac n) simp_all\n\n(*<*)\nthm mult_Suc\n(*lemma imult_Suc: \"eSuc m * n = n + m * n\"*)\n(*lemmas imult_Suc = mult_eSuc*)\n\nthm mult_Suc_right\n(*lemma imult_Suc_right: \"m * eSuc n = m + m * n\"*)\n(*lemmas imult_Suc_right mult_eSuc_right*)\n(*>*)\n\nlemma idiv_self: \"\\<lbrakk> 0 < (n::enat); n \\<noteq> \\<infinity> \\<rbrakk> \\<Longrightarrow> n div n = 1\"\nby (case_tac n, simp_all add: one_enat_def)\nlemma imod_self: \"n \\<noteq> \\<infinity> \\<Longrightarrow> (n::enat) mod n = 0\"\nby (case_tac n, simp_all)\n\nlemma idiv_iless: \"m < (n::enat) \\<Longrightarrow> m div n = 0\"\nby (case_tac m, simp_all) (case_tac n, simp_all)\nlemma imod_iless: \"m < (n::enat) \\<Longrightarrow> m mod n = m\"\nby (case_tac m, simp_all) (case_tac n, simp_all)\n\nlemma imod_iless_divisor: \"\\<lbrakk> 0 < (n::enat); m \\<noteq> \\<infinity> \\<rbrakk>  \\<Longrightarrow> m mod n < n\"\nby (case_tac m, simp_all) (case_tac n, simp_all)\nlemma imod_ile_dividend: \"(m::enat) mod n \\<le> m\"\nby (case_tac m, simp_all) (case_tac n, simp_all)\nlemma idiv_ile_dividend: \"(m::enat) div n \\<le> m\"\nby (case_tac m, simp_all) (case_tac n, simp_all)\n\nthm div_mult2_eq\nlemma idiv_imult2_eq: \"(a::enat) div (b * c) = a div b div c\"\napply (case_tac a, case_tac b, case_tac c, simp add: div_mult2_eq)\napply (simp add: imult_infinity_right_if idiv_infinity_right)\napply (simp add: imult_infinity_if idiv_infinity_right idiv_0[unfolded zero_enat_def])\napply (case_tac \"b = 0\", simp)\napply (case_tac \"c = 0\", simp)\nthm idiv_infinity\nthm idiv_infinity[OF enat_0_less_mult_iff[THEN iffD2]]\napply (simp add: idiv_infinity[OF enat_0_less_mult_iff[THEN iffD2]])\ndone\n\n\nthm mult_le_mono\nlemma imult_ile_mono: \"\\<lbrakk> (i::enat) \\<le> j; k \\<le> l \\<rbrakk> \\<Longrightarrow> i * k \\<le> j * l\"\napply (case_tac i, case_tac j, case_tac k, case_tac l, simp_all add: mult_le_mono)\napply (case_tac k, case_tac l, simp_all)\napply (case_tac k, case_tac l, simp_all)\ndone\n\nlemma imult_ile_mono1: \"(i::enat) \\<le> j \\<Longrightarrow> i * k \\<le> j * k\"\nby (rule imult_ile_mono[OF _ order_refl])\nthm mult_le_mono2\nlemma imult_ile_mono2: \"(i::enat) \\<le> j \\<Longrightarrow> k * i \\<le> k * j\"\nby (rule imult_ile_mono[OF order_refl])\n\nlemma imult_iless_mono1: \"\\<lbrakk> (i::enat) < j; 0 < k; k \\<noteq> \\<infinity> \\<rbrakk> \\<Longrightarrow> i * k \\<le> j * k\"\nby (case_tac i, case_tac j, case_tac k, simp_all)\nlemma imult_iless_mono2: \"\\<lbrakk> (i::enat) < j; 0 < k; k \\<noteq> \\<infinity> \\<rbrakk> \\<Longrightarrow> k * i \\<le> k * j\"\nby (simp only: mult.commute[of k], rule imult_iless_mono1)\n\nlemma imod_1: \"(enat m) mod eSuc 0 = 0\"\nby (simp add: eSuc_enat)\nlemmas imod_1_enat[simp, code] = imod_1[unfolded zero_enat_def]\n\nlemma imod_iadd_self2: \"(m + enat n) mod (enat n) = m mod (enat n)\"\nby (case_tac m, simp_all)\n\nlemma imod_iadd_self1: \"(enat n + m) mod (enat n) = m mod (enat n)\"\nby (simp only: add.commute[of _ m] imod_iadd_self2)\n\nlemma idiv_imod_equality: \"(m::enat) div n * n + m mod n + k = m + k\"\nby (case_tac m, simp_all) (case_tac n, simp_all)\nlemma imod_idiv_equality: \"(m::enat) div n * n + m mod n = m\"\nby (insert idiv_imod_equality[of m n 0], simp)\n\nlemma idiv_ile_mono: \"m \\<le> (n::enat) \\<Longrightarrow> m div k \\<le> n div k\"\napply (case_tac \"k = 0\", simp)\napply (case_tac m, case_tac k, simp_all)\napply (case_tac n)\n apply (simp add: div_le_mono)\napply (simp add: idiv_infinity)\napply (simp add: i0_lb[unfolded zero_enat_def])\ndone\nlemma idiv_ile_mono2: \"\\<lbrakk> 0 < m; m \\<le> (n::enat) \\<rbrakk> \\<Longrightarrow> k div n \\<le> k div m\"\napply (case_tac \"n = 0\", simp)\napply (case_tac m, case_tac k, simp_all)\napply (case_tac n)\n apply (simp add: div_le_mono2)\napply simp\ndone\n\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/List-Infinite/CommonArith/Util_NatInf.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127529517044, "lm_q2_score": 0.819893340314393, "lm_q1q2_score": 0.700117379354632}}
{"text": "(*<*)\ntheory natsum imports Main begin\n(*>*)\ntext\\<open>\\noindent\nIn particular, there are \\<open>case\\<close>-expressions, for example\n@{term[display]\"case n of 0 => 0 | Suc m => m\"}\nprimitive recursion, for example\n\\<close>\n\nprimrec sum :: \"nat \\<Rightarrow> nat\" where\n\"sum 0 = 0\" |\n\"sum (Suc n) = Suc n + sum n\"\n\ntext\\<open>\\noindent\nand induction, for example\n\\<close>\n\nlemma \"sum n + sum n = n*(Suc n)\"\napply(induct_tac n)\napply(auto)\ndone\n\ntext\\<open>\\newcommand{\\mystar}{*%\n}\n\\index{arithmetic operations!for \\protect\\isa{nat}}%\nThe arithmetic operations \\isadxboldpos{+}{$HOL2arithfun},\n\\isadxboldpos{-}{$HOL2arithfun}, \\isadxboldpos{\\mystar}{$HOL2arithfun},\n\\sdx{div}, \\sdx{mod}, \\cdx{min} and\n\\cdx{max} are predefined, as are the relations\n\\isadxboldpos{\\isasymle}{$HOL2arithrel} and\n\\isadxboldpos{<}{$HOL2arithrel}. As usual, \\<^prop>\\<open>m-n = (0::nat)\\<close> if\n\\<^prop>\\<open>m<n\\<close>. There is even a least number operation\n\\sdx{LEAST}\\@.  For example, \\<^prop>\\<open>(LEAST n. 0 < n) = Suc 0\\<close>.\n\\begin{warn}\\index{overloading}\n  The constants \\cdx{0} and \\cdx{1} and the operations\n  \\isadxboldpos{+}{$HOL2arithfun}, \\isadxboldpos{-}{$HOL2arithfun},\n  \\isadxboldpos{\\mystar}{$HOL2arithfun}, \\cdx{min},\n  \\cdx{max}, \\isadxboldpos{\\isasymle}{$HOL2arithrel} and\n  \\isadxboldpos{<}{$HOL2arithrel} are overloaded: they are available\n  not just for natural numbers but for other types as well.\n  For example, given the goal \\<open>x + 0 = x\\<close>, there is nothing to indicate\n  that you are talking about natural numbers. Hence Isabelle can only infer\n  that \\<^term>\\<open>x\\<close> is of some arbitrary type where \\<open>0\\<close> and \\<open>+\\<close> are\n  declared. As a consequence, you will be unable to prove the\n  goal. To alert you to such pitfalls, Isabelle flags numerals without a\n  fixed type in its output: \\<^prop>\\<open>x+0 = x\\<close>. (In the absence of a numeral,\n  it may take you some time to realize what has happened if \\pgmenu{Show\n  Types} is not set).  In this particular example, you need to include\n  an explicit type constraint, for example \\<open>x+0 = (x::nat)\\<close>. If there\n  is enough contextual information this may not be necessary: \\<^prop>\\<open>Suc x =\n  x\\<close> automatically implies \\<open>x::nat\\<close> because \\<^term>\\<open>Suc\\<close> is not\n  overloaded.\n\n  For details on overloading see \\S\\ref{sec:overloading}.\n  Table~\\ref{tab:overloading} in the appendix shows the most important\n  overloaded operations.\n\\end{warn}\n\\begin{warn}\n  The symbols \\isadxboldpos{>}{$HOL2arithrel} and\n  \\isadxboldpos{\\isasymge}{$HOL2arithrel} are merely syntax: \\<open>x > y\\<close>\n  stands for \\<^prop>\\<open>y < x\\<close> and similary for \\<open>\\<ge>\\<close> and\n  \\<open>\\<le>\\<close>.\n\\end{warn}\n\\begin{warn}\n  Constant \\<open>1::nat\\<close> is defined to equal \\<^term>\\<open>Suc 0\\<close>. This definition\n  (see \\S\\ref{sec:ConstDefinitions}) is unfolded automatically by some\n  tactics (like \\<open>auto\\<close>, \\<open>simp\\<close> and \\<open>arith\\<close>) but not by\n  others (especially the single step tactics in Chapter~\\ref{chap:rules}).\n  If you need the full set of numerals, see~\\S\\ref{sec:numerals}.\n  \\emph{Novices are advised to stick to \\<^term>\\<open>0::nat\\<close> and \\<^term>\\<open>Suc\\<close>.}\n\\end{warn}\n\nBoth \\<open>auto\\<close> and \\<open>simp\\<close>\n(a method introduced below, \\S\\ref{sec:Simplification}) prove \nsimple arithmetic goals automatically:\n\\<close>\n\nlemma \"\\<lbrakk> \\<not> m < n; m < n + (1::nat) \\<rbrakk> \\<Longrightarrow> m = n\"\n(*<*)by(auto)(*>*)\n\ntext\\<open>\\noindent\nFor efficiency's sake, this built-in prover ignores quantified formulae,\nmany logical connectives, and all arithmetic operations apart from addition.\nIn consequence, \\<open>auto\\<close> and \\<open>simp\\<close> cannot prove this slightly more complex goal:\n\\<close>\n\nlemma \"m \\<noteq> (n::nat) \\<Longrightarrow> m < n \\<or> n < m\"\n(*<*)by(arith)(*>*)\n\ntext\\<open>\\noindent The method \\methdx{arith} is more general.  It attempts to\nprove the first subgoal provided it is a \\textbf{linear arithmetic} formula.\nSuch formulas may involve the usual logical connectives (\\<open>\\<not>\\<close>,\n\\<open>\\<and>\\<close>, \\<open>\\<or>\\<close>, \\<open>\\<longrightarrow>\\<close>, \\<open>=\\<close>,\n\\<open>\\<forall>\\<close>, \\<open>\\<exists>\\<close>), the relations \\<open>=\\<close>,\n\\<open>\\<le>\\<close> and \\<open><\\<close>, and the operations \\<open>+\\<close>, \\<open>-\\<close>,\n\\<^term>\\<open>min\\<close> and \\<^term>\\<open>max\\<close>.  For example,\\<close>\n\nlemma \"min i (max j (k*k)) = max (min (k*k) i) (min i (j::nat))\"\napply(arith)\n(*<*)done(*>*)\n\ntext\\<open>\\noindent\nsucceeds because \\<^term>\\<open>k*k\\<close> can be treated as atomic. In contrast,\n\\<close>\n\nlemma \"n*n = n+1 \\<Longrightarrow> n=0\"\n(*<*)oops(*>*)\n\ntext\\<open>\\noindent\nis not proved by \\<open>arith\\<close> because the proof relies \non properties of multiplication. Only multiplication by numerals (which is\nthe same as iterated addition) is taken into account.\n\n\\begin{warn} The running time of \\<open>arith\\<close> is exponential in the number\n  of occurrences of \\ttindexboldpos{-}{$HOL2arithfun}, \\cdx{min} and\n  \\cdx{max} because they are first eliminated by case distinctions.\n\nIf \\<open>k\\<close> is a numeral, \\sdx{div}~\\<open>k\\<close>, \\sdx{mod}~\\<open>k\\<close> and\n\\<open>k\\<close>~\\sdx{dvd} are also supported, where the former two are eliminated\nby case distinctions, again blowing up the running time.\n\nIf the formula involves quantifiers, \\<open>arith\\<close> may take\nsuper-exponential time and space.\n\\end{warn}\n\\<close>\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/Misc/natsum.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933315126792, "lm_q2_score": 0.8539127473751341, "lm_q1q2_score": 0.7001173672665435}}
